diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..f049cc8529 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +root = true + +# properties +[*.{h,c,hpp,cpp,m,java}] +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true diff --git a/build.mak.in b/build.mak.in index 1eb6741d46..0d871a2d54 100644 --- a/build.mak.in +++ b/build.mak.in @@ -223,7 +223,7 @@ OBOE_CFLAGS = @ac_oboe_cflags@ # PJMEDIA features exclusion PJ_VIDEO_CFLAGS += $(SDL_CFLAGS) $(FFMPEG_CFLAGS) $(V4L2_CFLAGS) $(DSHOW_CFLAGS) $(QT_CFLAGS) \ - $(OPENH264_CFLAGS) $(VPX_CFLAGS) $(DARWIN_CFLAGS) + $(OPENH264_CFLAGS) $(VPX_CFLAGS) $(DARWIN_CFLAGS) PJ_VIDEO_LDFLAGS += $(SDL_LDFLAGS) $(FFMPEG_LDFLAGS) $(V4L2_LDFLAGS) $(DSHOW_LDFLAGS) \ $(OPENH264_LDFLAGS) $(VPX_LDFLAGS) @@ -231,40 +231,40 @@ PJ_VIDEO_LDFLAGS += $(SDL_LDFLAGS) $(FFMPEG_LDFLAGS) $(V4L2_LDFLAGS) $(DSHOW_LDF export APP_CC := @CC@ export APP_CXX := @CXX@ export APP_CFLAGS := -DPJ_AUTOCONF=1\ - @CFLAGS@\ - $(PJ_VIDEO_CFLAGS) \ - -I$(PJDIR)/pjlib/include\ - -I$(PJDIR)/pjlib-util/include\ - -I$(PJDIR)/pjnath/include\ - -I$(PJDIR)/pjmedia/include\ - -I$(PJDIR)/pjsip/include + @CFLAGS@\ + $(PJ_VIDEO_CFLAGS) \ + -I$(PJDIR)/pjlib/include\ + -I$(PJDIR)/pjlib-util/include\ + -I$(PJDIR)/pjnath/include\ + -I$(PJDIR)/pjmedia/include\ + -I$(PJDIR)/pjsip/include export APP_CXXFLAGS := @CXXFLAGS@ $(APP_CFLAGS) export APP_LDFLAGS := -L$(PJDIR)/pjlib/lib\ - -L$(PJDIR)/pjlib-util/lib\ - -L$(PJDIR)/pjnath/lib\ - -L$(PJDIR)/pjmedia/lib\ - -L$(PJDIR)/pjsip/lib\ - -L$(PJDIR)/third_party/lib\ - $(PJ_VIDEO_LDFLAGS) \ - @LDFLAGS@ + -L$(PJDIR)/pjlib-util/lib\ + -L$(PJDIR)/pjnath/lib\ + -L$(PJDIR)/pjmedia/lib\ + -L$(PJDIR)/pjsip/lib\ + -L$(PJDIR)/third_party/lib\ + $(PJ_VIDEO_LDFLAGS) \ + @LDFLAGS@ export APP_LDXXFLAGS := $(APP_LDFLAGS) export APP_LIB_FILES := \ - $(PJ_DIR)/pjsip/lib/libpjsua-$(LIB_SUFFIX) \ - $(PJ_DIR)/pjsip/lib/libpjsip-ua-$(LIB_SUFFIX) \ - $(PJ_DIR)/pjsip/lib/libpjsip-simple-$(LIB_SUFFIX) \ - $(PJ_DIR)/pjsip/lib/libpjsip-$(LIB_SUFFIX) \ - $(PJ_DIR)/pjmedia/lib/libpjmedia-codec-$(LIB_SUFFIX) \ - $(PJ_DIR)/pjmedia/lib/libpjmedia-videodev-$(LIB_SUFFIX) \ - $(PJ_DIR)/pjmedia/lib/libpjmedia-$(LIB_SUFFIX) \ - $(PJ_DIR)/pjmedia/lib/libpjmedia-audiodev-$(LIB_SUFFIX) \ - $(PJ_DIR)/pjnath/lib/libpjnath-$(LIB_SUFFIX) \ - $(PJ_DIR)/pjlib-util/lib/libpjlib-util-$(LIB_SUFFIX) \ - $(APP_THIRD_PARTY_LIB_FILES) \ - $(PJ_DIR)/pjlib/lib/libpj-$(LIB_SUFFIX) + $(PJ_DIR)/pjsip/lib/libpjsua-$(LIB_SUFFIX) \ + $(PJ_DIR)/pjsip/lib/libpjsip-ua-$(LIB_SUFFIX) \ + $(PJ_DIR)/pjsip/lib/libpjsip-simple-$(LIB_SUFFIX) \ + $(PJ_DIR)/pjsip/lib/libpjsip-$(LIB_SUFFIX) \ + $(PJ_DIR)/pjmedia/lib/libpjmedia-codec-$(LIB_SUFFIX) \ + $(PJ_DIR)/pjmedia/lib/libpjmedia-videodev-$(LIB_SUFFIX) \ + $(PJ_DIR)/pjmedia/lib/libpjmedia-$(LIB_SUFFIX) \ + $(PJ_DIR)/pjmedia/lib/libpjmedia-audiodev-$(LIB_SUFFIX) \ + $(PJ_DIR)/pjnath/lib/libpjnath-$(LIB_SUFFIX) \ + $(PJ_DIR)/pjlib-util/lib/libpjlib-util-$(LIB_SUFFIX) \ + $(APP_THIRD_PARTY_LIB_FILES) \ + $(PJ_DIR)/pjlib/lib/libpj-$(LIB_SUFFIX) export APP_LIBXX_FILES := \ - $(PJ_DIR)/pjsip/lib/libpjsua2-$(LIB_SUFFIX) \ - $(APP_LIB_FILES) + $(PJ_DIR)/pjsip/lib/libpjsua2-$(LIB_SUFFIX) \ + $(APP_LIB_FILES) ifeq ($(PJ_SHARED_LIBRARIES),) export PJLIB_LDLIB := -lpj-$(TARGET_NAME) @@ -294,21 +294,21 @@ export PJSUA_LIB_LDLIB := -lpjsua export PJSUA2_LIB_LDLIB := -lpjsua2 export ADD_LIB_FILES := $(PJ_DIR)/pjsip/lib/libpjsua.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjsip/lib/libpjsua.$(SHLIB_SUFFIX) \ - $(PJ_DIR)/pjsip/lib/libpjsip-ua.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjsip/lib/libpjsip-ua.$(SHLIB_SUFFIX) \ - $(PJ_DIR)/pjsip/lib/libpjsip-simple.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjsip/lib/libpjsip-simple.$(SHLIB_SUFFIX) \ - $(PJ_DIR)/pjsip/lib/libpjsip.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjsip/lib/libpjsip.$(SHLIB_SUFFIX) \ - $(PJ_DIR)/pjmedia/lib/libpjmedia-codec.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjmedia/lib/libpjmedia-codec.$(SHLIB_SUFFIX) \ - $(PJ_DIR)/pjmedia/lib/libpjmedia-videodev.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjmedia/lib/libpjmedia-videodev.$(SHLIB_SUFFIX) \ - $(PJ_DIR)/pjmedia/lib/libpjmedia.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjmedia/lib/libpjmedia.$(SHLIB_SUFFIX) \ - $(PJ_DIR)/pjmedia/lib/libpjmedia-audiodev.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjmedia/lib/libpjmedia-audiodev.$(SHLIB_SUFFIX) \ - $(PJ_DIR)/pjnath/lib/libpjnath.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjnath/lib/libpjnath.$(SHLIB_SUFFIX) \ - $(PJ_DIR)/pjlib-util/lib/libpjlib-util.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjlib-util/lib/libpjlib-util.$(SHLIB_SUFFIX) \ - $(PJ_DIR)/pjlib/lib/libpj.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjlib/lib/libpj.$(SHLIB_SUFFIX) + $(PJ_DIR)/pjsip/lib/libpjsip-ua.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjsip/lib/libpjsip-ua.$(SHLIB_SUFFIX) \ + $(PJ_DIR)/pjsip/lib/libpjsip-simple.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjsip/lib/libpjsip-simple.$(SHLIB_SUFFIX) \ + $(PJ_DIR)/pjsip/lib/libpjsip.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjsip/lib/libpjsip.$(SHLIB_SUFFIX) \ + $(PJ_DIR)/pjmedia/lib/libpjmedia-codec.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjmedia/lib/libpjmedia-codec.$(SHLIB_SUFFIX) \ + $(PJ_DIR)/pjmedia/lib/libpjmedia-videodev.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjmedia/lib/libpjmedia-videodev.$(SHLIB_SUFFIX) \ + $(PJ_DIR)/pjmedia/lib/libpjmedia.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjmedia/lib/libpjmedia.$(SHLIB_SUFFIX) \ + $(PJ_DIR)/pjmedia/lib/libpjmedia-audiodev.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjmedia/lib/libpjmedia-audiodev.$(SHLIB_SUFFIX) \ + $(PJ_DIR)/pjnath/lib/libpjnath.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjnath/lib/libpjnath.$(SHLIB_SUFFIX) \ + $(PJ_DIR)/pjlib-util/lib/libpjlib-util.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjlib-util/lib/libpjlib-util.$(SHLIB_SUFFIX) \ + $(PJ_DIR)/pjlib/lib/libpj.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjlib/lib/libpj.$(SHLIB_SUFFIX) APP_LIB_FILES += $(ADD_LIB_FILES) APP_LIBXX_FILES += $(PJ_DIR)/pjsip/lib/libpjsua2.$(SHLIB_SUFFIX).$(PJ_VERSION_MAJOR) $(PJ_DIR)/pjsip/lib/libpjsua2.$(SHLIB_SUFFIX) \ - $(ADD_LIB_FILES) + $(ADD_LIB_FILES) endif ifeq ($(PJ_EXCLUDE_PJSUA2),1) @@ -316,23 +316,23 @@ export PJSUA2_LIB_LDLIB := endif export APP_LDLIBS := $(PJSUA_LIB_LDLIB) \ - $(PJSIP_UA_LDLIB) \ - $(PJSIP_SIMPLE_LDLIB) \ - $(PJSIP_LDLIB) \ - $(PJMEDIA_CODEC_LDLIB) \ - $(PJMEDIA_LDLIB) \ - $(PJMEDIA_VIDEODEV_LDLIB) \ - $(PJMEDIA_AUDIODEV_LDLIB) \ - $(PJMEDIA_LDLIB) \ - $(PJNATH_LDLIB) \ - $(PJLIB_UTIL_LDLIB) \ - $(APP_THIRD_PARTY_LIBS)\ - $(APP_THIRD_PARTY_EXT)\ - $(PJLIB_LDLIB) \ - @LIBS@ + $(PJSIP_UA_LDLIB) \ + $(PJSIP_SIMPLE_LDLIB) \ + $(PJSIP_LDLIB) \ + $(PJMEDIA_CODEC_LDLIB) \ + $(PJMEDIA_LDLIB) \ + $(PJMEDIA_VIDEODEV_LDLIB) \ + $(PJMEDIA_AUDIODEV_LDLIB) \ + $(PJMEDIA_LDLIB) \ + $(PJNATH_LDLIB) \ + $(PJLIB_UTIL_LDLIB) \ + $(APP_THIRD_PARTY_LIBS)\ + $(APP_THIRD_PARTY_EXT)\ + $(PJLIB_LDLIB) \ + @LIBS@ export APP_LDXXLIBS := $(PJSUA2_LIB_LDLIB) \ - -lstdc++ \ - $(APP_LDLIBS) + -lstdc++ \ + $(APP_LDLIBS) # Here are the variables to use if application is using the library # from within the source distribution diff --git a/pjlib-util/include/pjlib-util.h b/pjlib-util/include/pjlib-util.h index 334e73c96b..9b82f81ffb 100644 --- a/pjlib-util/include/pjlib-util.h +++ b/pjlib-util/include/pjlib-util.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -72,5 +71,5 @@ #include #include -#endif /* __PJLIB_UTIL_H__ */ +#endif /* __PJLIB_UTIL_H__ */ diff --git a/pjlib-util/include/pjlib-util/base64.h b/pjlib-util/include/pjlib-util/base64.h index bb84498474..14accfbbeb 100644 --- a/pjlib-util/include/pjlib-util/base64.h +++ b/pjlib-util/include/pjlib-util/base64.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -40,44 +39,44 @@ PJ_BEGIN_DECL * Helper macro to calculate the approximate length required for base256 to * base64 conversion. */ -#define PJ_BASE256_TO_BASE64_LEN(len) (len * 4 / 3 + 3) +#define PJ_BASE256_TO_BASE64_LEN(len) (len * 4 / 3 + 3) /** * Helper macro to calculate the approximage length required for base64 to * base256 conversion. */ -#define PJ_BASE64_TO_BASE256_LEN(len) (len * 3 / 4) +#define PJ_BASE64_TO_BASE256_LEN(len) (len * 3 / 4) /** * Encode a buffer into base64 encoding. * - * @param input The input buffer. + * @param input The input buffer. * @param in_len Size of the input buffer. * @param output Output buffer. Caller must allocate this buffer with - * the appropriate size. + * the appropriate size. * @param out_len On entry, it specifies the length of the output buffer. - * Upon return, this will be filled with the actual - * length of the output buffer. + * Upon return, this will be filled with the actual + * length of the output buffer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pj_base64_encode(const pj_uint8_t *input, int in_len, - char *output, int *out_len); + char *output, int *out_len); /** * Decode base64 string. * - * @param input Input string. - * @param out Buffer to store the output. Caller must allocate - * this buffer with the appropriate size. + * @param input Input string. + * @param out Buffer to store the output. Caller must allocate + * this buffer with the appropriate size. * @param out_len On entry, it specifies the length of the output buffer. - * Upon return, this will be filled with the actual - * length of the output. + * Upon return, this will be filled with the actual + * length of the output. */ PJ_DECL(pj_status_t) pj_base64_decode(const pj_str_t *input, - pj_uint8_t *out, int *out_len); + pj_uint8_t *out, int *out_len); @@ -88,5 +87,5 @@ PJ_DECL(pj_status_t) pj_base64_decode(const pj_str_t *input, PJ_END_DECL -#endif /* __PJLIB_UTIL_BASE64_H__ */ +#endif /* __PJLIB_UTIL_BASE64_H__ */ diff --git a/pjlib-util/include/pjlib-util/cli.h b/pjlib-util/include/pjlib-util/cli.h index 34fa3161dc..1b6daf7f8d 100644 --- a/pjlib-util/include/pjlib-util/cli.h +++ b/pjlib-util/include/pjlib-util/cli.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) * @@ -60,10 +59,10 @@ PJ_BEGIN_DECL - - - - + + + + \endverbatim */ @@ -299,10 +298,10 @@ typedef pj_status_t (*pj_cli_cmd_handler)(pj_cli_cmd_val *cval); * Write a log message to the CLI application. The CLI application * will send the log message to all the registered front-ends. * - * @param cli The CLI application instance. - * @param level Verbosity level of this message message. + * @param cli The CLI application instance. + * @param level Verbosity level of this message message. * @param buffer The message itself. - * @param len Length of this message. + * @param len Length of this message. */ PJ_DECL(void) pj_cli_write_log(pj_cli_t *cli, int level, @@ -312,10 +311,10 @@ PJ_DECL(void) pj_cli_write_log(pj_cli_t *cli, /** * Create a new CLI application instance. * - * @param cfg CLI application creation parameters. - * @param p_cli Pointer to receive the returned instance. + * @param cfg CLI application creation parameters. + * @param p_cli Pointer to receive the returned instance. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_cli_create(pj_cli_cfg *cfg, pj_cli_t **p_cli); @@ -323,18 +322,18 @@ PJ_DECL(pj_status_t) pj_cli_create(pj_cli_cfg *cfg, /** * This specifies the function to get the id of the specified command * - * @param cmd The specified command. + * @param cmd The specified command. * - * @return The command id + * @return The command id */ PJ_DECL(pj_cli_cmd_id) pj_cli_get_cmd_id(const pj_cli_cmd_spec *cmd); /** * Get the internal parameter of the CLI instance. * - * @param cli The CLI application instance. + * @param cli The CLI application instance. * - * @return CLI parameter instance. + * @return CLI parameter instance. */ PJ_DECL(pj_cli_cfg*) pj_cli_get_param(pj_cli_t *cli); @@ -346,29 +345,29 @@ PJ_DECL(pj_cli_cfg*) pj_cli_get_param(pj_cli_t *cli); * See also pj_cli_sess_end_session() to end a session instead of quitting the * whole application. * - * @param cli The CLI application instance. - * @param req The session on which the shutdown request is - * received. - * @param restart Indicate whether application restart is wanted. + * @param cli The CLI application instance. + * @param req The session on which the shutdown request is + * received. + * @param restart Indicate whether application restart is wanted. */ PJ_DECL(void) pj_cli_quit(pj_cli_t *cli, pj_cli_sess *req, - pj_bool_t restart); + pj_bool_t restart); /** * Check if application shutdown or restart has been requested. * - * @param cli The CLI application instance. + * @param cli The CLI application instance. * - * @return PJ_TRUE if pj_cli_quit() has been called. + * @return PJ_TRUE if pj_cli_quit() has been called. */ PJ_DECL(pj_bool_t) pj_cli_is_quitting(pj_cli_t *cli); /** * Check if application restart has been requested. * - * @param cli The CLI application instance. + * @param cli The CLI application instance. * - * @return PJ_TRUE if pj_cli_quit() has been called with - * restart parameter set. + * @return PJ_TRUE if pj_cli_quit() has been called with + * restart parameter set. */ PJ_DECL(pj_bool_t) pj_cli_is_restarting(pj_cli_t *cli); @@ -376,7 +375,7 @@ PJ_DECL(pj_bool_t) pj_cli_is_restarting(pj_cli_t *cli); * Destroy a CLI application instance. This would also close all sessions * currently running for this CLI application. * - * @param cli The CLI application. + * @param cli The CLI application. */ PJ_DECL(void) pj_cli_destroy(pj_cli_t *cli); @@ -390,8 +389,8 @@ PJ_DECL(void) pj_cli_cfg_default(pj_cli_cfg *param); /** * Register a front end to the CLI application. * - * @param cli The CLI application. - * @param fe The CLI front end to be registered. + * @param cli The CLI application. + * @param fe The CLI front end to be registered. */ PJ_DECL(void) pj_cli_register_front_end(pj_cli_t *cli, pj_cli_front_end *fe); @@ -402,44 +401,44 @@ PJ_DECL(void) pj_cli_register_front_end(pj_cli_t *cli, * * Note that the input string MUST be NULL terminated. * - * @param cli The CLI application. - * @param group Optional group to which this command will be added - * to, or specify NULL if this command is a root - * command. - * @param xml Input string containing XML node text for the - * command, MUST be NULL terminated. - * @param handler Function handler for the command. This must be NULL - * if the command specifies a command group. - * @param p_cmd Optional pointer to store the newly created - * specification. - * @param get_choice Function handler for the argument. Specify this for - * dynamic choice type arguments. - * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @param cli The CLI application. + * @param group Optional group to which this command will be added + * to, or specify NULL if this command is a root + * command. + * @param xml Input string containing XML node text for the + * command, MUST be NULL terminated. + * @param handler Function handler for the command. This must be NULL + * if the command specifies a command group. + * @param p_cmd Optional pointer to store the newly created + * specification. + * @param get_choice Function handler for the argument. Specify this for + * dynamic choice type arguments. + * + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_cli_add_cmd_from_xml(pj_cli_t *cli, - pj_cli_cmd_spec *group, + pj_cli_cmd_spec *group, const pj_str_t *xml, pj_cli_cmd_handler handler, pj_cli_cmd_spec **p_cmd, - pj_cli_get_dyn_choice get_choice); + pj_cli_get_dyn_choice get_choice); /** * Initialize pj_cli_exec_info with its default values. * - * @param param The param to be initialized. + * @param param The param to be initialized. */ PJ_DECL(void) pj_cli_exec_info_default(pj_cli_exec_info *param); /** * Write a log message to the specific CLI session. * - * @param sess The CLI active session. + * @param sess The CLI active session. * @param buffer The message itself. - * @param len Length of this message. + * @param len Length of this message. */ PJ_DECL(void) pj_cli_sess_write_msg(pj_cli_sess *sess, - const char *buffer, - pj_size_t len); + const char *buffer, + pj_size_t len); /** * Parse an input cmdline string. The first word of the command line is the @@ -459,29 +458,29 @@ PJ_DECL(void) pj_cli_sess_write_msg(pj_cli_sess *sess, * which will be removed by the function. However any more characters * following this newline will cause an error to be returned. * - * @param sess The CLI session. - * @param cmdline The command line string to be parsed. - * @param val Structure to store the parsing result. - * @param pool The pool to allocate memory from. - * @param info Additional info to be returned regarding the parsing. - * - * @return This function returns the status of the parsing, - * which can be one of the following : - * - PJ_SUCCESS: a command was executed successfully. - * - PJ_EINVAL: invalid parameter to this function. - * - PJ_ENOTFOUND: command is not found. - * - PJ_CLI_EAMBIGUOUS: command/argument is ambiguous. - * - PJ_CLI_EMISSINGARG: missing argument. - * - PJ_CLI_EINVARG: invalid command argument. - * - PJ_CLI_EEXIT: "exit" has been called to end - * the current session. This is a signal for the - * application to end it's main loop. + * @param sess The CLI session. + * @param cmdline The command line string to be parsed. + * @param val Structure to store the parsing result. + * @param pool The pool to allocate memory from. + * @param info Additional info to be returned regarding the parsing. + * + * @return This function returns the status of the parsing, + * which can be one of the following : + * - PJ_SUCCESS: a command was executed successfully. + * - PJ_EINVAL: invalid parameter to this function. + * - PJ_ENOTFOUND: command is not found. + * - PJ_CLI_EAMBIGUOUS: command/argument is ambiguous. + * - PJ_CLI_EMISSINGARG: missing argument. + * - PJ_CLI_EINVARG: invalid command argument. + * - PJ_CLI_EEXIT: "exit" has been called to end + * the current session. This is a signal for the + * application to end it's main loop. */ PJ_DECL(pj_status_t) pj_cli_sess_parse(pj_cli_sess *sess, - char *cmdline, - pj_cli_cmd_val *val, - pj_pool_t *pool, - pj_cli_exec_info *info); + char *cmdline, + pj_cli_cmd_val *val, + pj_pool_t *pool, + pj_cli_exec_info *info); /** * End the specified session, and destroy it to release all resources used @@ -491,7 +490,7 @@ PJ_DECL(pj_status_t) pj_cli_sess_parse(pj_cli_sess *sess, * creation process. * See also pj_cli_quit() to quit the whole application instead. * - * @param sess The CLI session to be destroyed. + * @param sess The CLI session to be destroyed. */ PJ_DECL(void) pj_cli_sess_end_session(pj_cli_sess *sess); @@ -504,23 +503,23 @@ PJ_DECL(void) pj_cli_sess_end_session(pj_cli_sess *sess); * * See also pj_cli_sess_parse() for more info regarding the cmdline format. * - * @param sess The CLI session. - * @param cmdline The command line string to be executed. - * @param pool The pool to allocate memory from. - * @param info Optional pointer to receive additional information - * related to the execution of the command (such as - * the command return value). + * @param sess The CLI session. + * @param cmdline The command line string to be executed. + * @param pool The pool to allocate memory from. + * @param info Optional pointer to receive additional information + * related to the execution of the command (such as + * the command return value). * - * @return This function returns the status of the command - * parsing and execution (note that the return value - * of the handler itself will be returned in \a info - * argument, if specified). Please see the return value - * of pj_cli_sess_parse() for possible return values. + * @return This function returns the status of the command + * parsing and execution (note that the return value + * of the handler itself will be returned in \a info + * argument, if specified). Please see the return value + * of pj_cli_sess_parse() for possible return values. */ PJ_DECL(pj_status_t) pj_cli_sess_exec(pj_cli_sess *sess, - char *cmdline, - pj_pool_t *pool, - pj_cli_exec_info *info); + char *cmdline, + pj_pool_t *pool, + pj_cli_exec_info *info); /** * @} diff --git a/pjlib-util/include/pjlib-util/cli_console.h b/pjlib-util/include/pjlib-util/cli_console.h index 5b68ead83e..2e589b4df4 100644 --- a/pjlib-util/include/pjlib-util/cli_console.h +++ b/pjlib-util/include/pjlib-util/cli_console.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) * @@ -70,7 +69,7 @@ typedef struct pj_cli_console_cfg /** * Initialize pj_cli_console_cfg with its default values. * - * @param param The structure to be initialized. + * @param param The structure to be initialized. */ PJ_DECL(void) pj_cli_console_cfg_default(pj_cli_console_cfg *param); @@ -80,33 +79,33 @@ PJ_DECL(void) pj_cli_console_cfg_default(pj_cli_console_cfg *param); * the only session instance for the console front end. On Windows operating * system, this may open a new console window. * - * @param cli The CLI application instance. - * @param param Optional console CLI parameters. If this value is - * NULL, default parameters will be used. - * @param p_sess Pointer to receive the session instance for the - * console front end. - * @param p_fe Optional pointer to receive the front-end instance - * of the console front-end just created. + * @param cli The CLI application instance. + * @param param Optional console CLI parameters. If this value is + * NULL, default parameters will be used. + * @param p_sess Pointer to receive the session instance for the + * console front end. + * @param p_fe Optional pointer to receive the front-end instance + * of the console front-end just created. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_cli_console_create(pj_cli_t *cli, - const pj_cli_console_cfg *param, - pj_cli_sess **p_sess, - pj_cli_front_end **p_fe); + const pj_cli_console_cfg *param, + pj_cli_sess **p_sess, + pj_cli_front_end **p_fe); /** * Retrieve a cmdline from console stdin and process the input accordingly. * - * @param sess The CLI session. - * @param buf Pointer to receive the buffer. - * @param maxlen Maximum length to read. + * @param sess The CLI session. + * @param buf Pointer to receive the buffer. + * @param maxlen Maximum length to read. * - * @return PJ_SUCCESS if an input was read + * @return PJ_SUCCESS if an input was read */ PJ_DECL(pj_status_t) pj_cli_console_process(pj_cli_sess *sess, - char *buf, - unsigned maxlen); + char *buf, + unsigned maxlen); /** * @} diff --git a/pjlib-util/include/pjlib-util/cli_imp.h b/pjlib-util/include/pjlib-util/cli_imp.h index bb1324e8f8..8d4aeb738d 100644 --- a/pjlib-util/include/pjlib-util/cli_imp.h +++ b/pjlib-util/include/pjlib-util/cli_imp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) * @@ -40,21 +39,21 @@ PJ_BEGIN_DECL * Default log level for console sessions. */ #ifndef PJ_CLI_CONSOLE_LOG_LEVEL -# define PJ_CLI_CONSOLE_LOG_LEVEL PJ_LOG_MAX_LEVEL +# define PJ_CLI_CONSOLE_LOG_LEVEL PJ_LOG_MAX_LEVEL #endif /** * Default log level for telnet sessions. */ #ifndef PJ_CLI_TELNET_LOG_LEVEL -# define PJ_CLI_TELNET_LOG_LEVEL 4 +# define PJ_CLI_TELNET_LOG_LEVEL 4 #endif /** * Default port number for telnet daemon. */ #ifndef PJ_CLI_TELNET_PORT -# define PJ_CLI_TELNET_PORT 0 +# define PJ_CLI_TELNET_PORT 0 #endif /** @@ -62,10 +61,10 @@ PJ_BEGIN_DECL */ typedef enum pj_cli_front_end_type { - PJ_CLI_CONSOLE_FRONT_END, /**< Console front end. */ - PJ_CLI_TELNET_FRONT_END, /**< Telnet front end. */ - PJ_CLI_HTTP_FRONT_END, /**< HTTP front end. */ - PJ_CLI_GUI_FRONT_END /**< GUI front end. */ + PJ_CLI_CONSOLE_FRONT_END, /**< Console front end. */ + PJ_CLI_TELNET_FRONT_END, /**< Telnet front end. */ + PJ_CLI_HTTP_FRONT_END, /**< HTTP front end. */ + PJ_CLI_GUI_FRONT_END /**< GUI front end. */ } pj_cli_front_end_type; @@ -81,21 +80,21 @@ typedef struct pj_cli_front_end_op * the session if the session's log verbosity level is greater than the * level of this log message. * - * @param fe The front end. - * @param level Verbosity level of this message message. - * @param data The message itself. - * @param len Length of this message. + * @param fe The front end. + * @param level Verbosity level of this message message. + * @param data The message itself. + * @param len Length of this message. */ void (*on_write_log)(pj_cli_front_end *fe, int level, - const char *data, pj_size_t len); + const char *data, pj_size_t len); /** * Callback to be called when the application is quitting, to signal the * front-end to end its main loop or any currently blocking functions, * if any. * - * @param fe The front end. - * @param req The session which requested the application quit. + * @param fe The front end. + * @param req The session which requested the application quit. */ void (*on_quit)(pj_cli_front_end *fe, pj_cli_sess *req); @@ -103,7 +102,7 @@ typedef struct pj_cli_front_end_op * Callback to be called to close and self destroy the front-end. This * must also close any active sessions created by this front-ends. * - * @param fe The front end. + * @param fe The front end. */ void (*on_destroy)(pj_cli_front_end *fe); @@ -152,7 +151,7 @@ typedef struct pj_cli_sess_op /** * Callback to be called to close and self destroy the session. * - * @param sess The session to destroy. + * @param sess The session to destroy. */ void (*destroy)(pj_cli_sess *sess); @@ -205,4 +204,4 @@ struct pj_cli_sess PJ_END_DECL -#endif /* __PJLIB_UTIL_CLI_IMP_H__ */ +#endif /* __PJLIB_UTIL_CLI_IMP_H__ */ diff --git a/pjlib-util/include/pjlib-util/cli_telnet.h b/pjlib-util/include/pjlib-util/cli_telnet.h index 929c4b465e..b03aea003a 100644 --- a/pjlib-util/include/pjlib-util/cli_telnet.h +++ b/pjlib-util/include/pjlib-util/cli_telnet.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) * @@ -44,7 +43,7 @@ typedef struct pj_cli_telnet_info /** * The telnet's ip address. */ - pj_str_t ip_address; + pj_str_t ip_address; /** * The telnet's port number. @@ -59,7 +58,7 @@ typedef struct pj_cli_telnet_info /** * This specifies the callback called when telnet is started * - * @param status The status of telnet startup process. + * @param status The status of telnet startup process. * */ typedef void (*pj_cli_telnet_on_started)(pj_status_t status); @@ -127,7 +126,7 @@ typedef struct pj_cli_telnet_cfg /** * Initialize pj_cli_telnet_cfg with its default values. * - * @param param The structure to be initialized. + * @param param The structure to be initialized. */ PJ_DECL(void) pj_cli_telnet_cfg_default(pj_cli_telnet_cfg *param); @@ -135,17 +134,17 @@ PJ_DECL(void) pj_cli_telnet_cfg_default(pj_cli_telnet_cfg *param); /** * Create, initialize, and start a telnet daemon for the application. * - * @param cli The CLI application instance. - * @param param Optional parameters for creating the telnet daemon. - * If this value is NULL, default parameters will be used. - * @param p_fe Optional pointer to receive the front-end instance - * of the telnet front-end just created. + * @param cli The CLI application instance. + * @param param Optional parameters for creating the telnet daemon. + * If this value is NULL, default parameters will be used. + * @param p_fe Optional pointer to receive the front-end instance + * of the telnet front-end just created. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_cli_telnet_create(pj_cli_t *cli, - pj_cli_telnet_cfg *param, - pj_cli_front_end **p_fe); + pj_cli_telnet_cfg *param, + pj_cli_front_end **p_fe); /** @@ -154,10 +153,10 @@ PJ_DECL(pj_status_t) pj_cli_telnet_create(pj_cli_t *cli, * @param fe The front end. * @param info The telnet runtime information. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pj_cli_telnet_get_info(pj_cli_front_end *fe, - pj_cli_telnet_info *info); + pj_cli_telnet_info *info); /** * @} diff --git a/pjlib-util/include/pjlib-util/config.h b/pjlib-util/include/pjlib-util/config.h index 13aa6a3aa8..46b4d5de44 100644 --- a/pjlib-util/include/pjlib-util/config.h +++ b/pjlib-util/include/pjlib-util/config.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -49,7 +48,7 @@ * Maximum server address entries per one SRV record */ #ifndef PJ_DNS_SRV_MAX_ADDR -# define PJ_DNS_SRV_MAX_ADDR 8 +# define PJ_DNS_SRV_MAX_ADDR 8 #endif @@ -66,7 +65,7 @@ * Default: 16 */ #ifndef PJ_DNS_MAX_NAMES_IN_NAMETABLE -# define PJ_DNS_MAX_NAMES_IN_NAMETABLE 16 +# define PJ_DNS_MAX_NAMES_IN_NAMETABLE 16 #endif @@ -79,7 +78,7 @@ * Maximum numbers of DNS nameservers that can be configured in resolver. */ #ifndef PJ_DNS_RESOLVER_MAX_NS -# define PJ_DNS_RESOLVER_MAX_NS 16 +# define PJ_DNS_RESOLVER_MAX_NS 16 #endif @@ -115,7 +114,7 @@ * @see PJ_DNS_RESOLVER_INVALID_TTL */ #ifndef PJ_DNS_RESOLVER_MAX_TTL -# define PJ_DNS_RESOLVER_MAX_TTL (5*60) +# define PJ_DNS_RESOLVER_MAX_TTL (5*60) #endif /** @@ -129,7 +128,7 @@ * @see PJ_DNS_RESOLVER_MAX_TTL */ #ifndef PJ_DNS_RESOLVER_INVALID_TTL -# define PJ_DNS_RESOLVER_INVALID_TTL 60 +# define PJ_DNS_RESOLVER_INVALID_TTL 60 #endif /** @@ -146,7 +145,7 @@ * @see PJ_DNS_RESOLVER_BAD_NS_TTL */ #ifndef PJ_DNS_RESOLVER_GOOD_NS_TTL -# define PJ_DNS_RESOLVER_GOOD_NS_TTL (10*60) +# define PJ_DNS_RESOLVER_GOOD_NS_TTL (10*60) #endif /** @@ -158,7 +157,7 @@ * @see PJ_DNS_RESOLVER_GOOD_NS_TTL */ #ifndef PJ_DNS_RESOLVER_BAD_NS_TTL -# define PJ_DNS_RESOLVER_BAD_NS_TTL (1*60) +# define PJ_DNS_RESOLVER_BAD_NS_TTL (1*60) #endif @@ -169,7 +168,7 @@ * Default: 512 byes */ #ifndef PJ_DNS_RESOLVER_MAX_UDP_SIZE -# define PJ_DNS_RESOLVER_MAX_UDP_SIZE 512 +# define PJ_DNS_RESOLVER_MAX_UDP_SIZE 512 #endif @@ -182,7 +181,7 @@ * Default: 512 */ #ifndef PJ_DNS_RESOLVER_RES_BUF_SIZE -# define PJ_DNS_RESOLVER_RES_BUF_SIZE 512 +# define PJ_DNS_RESOLVER_RES_BUF_SIZE 512 #endif @@ -192,7 +191,7 @@ * default: 4000 */ #ifndef PJ_DNS_RESOLVER_TMP_BUF_SIZE -# define PJ_DNS_RESOLVER_TMP_BUF_SIZE 4000 +# define PJ_DNS_RESOLVER_TMP_BUF_SIZE 4000 #endif @@ -207,7 +206,7 @@ * This would save several kilobytes of .bss memory in the SIP parser. */ #ifndef PJ_SCANNER_USE_BITWISE -# define PJ_SCANNER_USE_BITWISE 1 +# define PJ_SCANNER_USE_BITWISE 1 #endif @@ -223,7 +222,7 @@ * Default: 16 */ #ifndef PJSTUN_MAX_ATTR -# define PJSTUN_MAX_ATTR 16 +# define PJSTUN_MAX_ATTR 16 #endif @@ -234,7 +233,7 @@ * Default: 16 */ #ifndef PJ_STUN_MAX_ATTR -# define PJ_STUN_MAX_ATTR 16 +# define PJ_STUN_MAX_ATTR 16 #endif @@ -251,7 +250,7 @@ * Default: 1 */ #ifndef PJ_CRC32_HAS_TABLES -# define PJ_CRC32_HAS_TABLES 1 +# define PJ_CRC32_HAS_TABLES 1 #endif @@ -291,7 +290,7 @@ * Default: 512 */ #ifndef PJ_CLI_MAX_CMDBUF -# define PJ_CLI_MAX_CMDBUF 512 +# define PJ_CLI_MAX_CMDBUF 512 #endif /** @@ -299,7 +298,7 @@ * Default: 8 */ #ifndef PJ_CLI_MAX_ARGS -# define PJ_CLI_MAX_ARGS 8 +# define PJ_CLI_MAX_ARGS 8 #endif /** @@ -307,7 +306,7 @@ * Default: 32 */ #ifndef PJ_CLI_MAX_HINTS -# define PJ_CLI_MAX_HINTS 32 +# define PJ_CLI_MAX_HINTS 32 #endif /** @@ -315,7 +314,7 @@ * Default: 4 */ #ifndef PJ_CLI_MAX_SHORTCUTS -# define PJ_CLI_MAX_SHORTCUTS 4 +# define PJ_CLI_MAX_SHORTCUTS 4 #endif /** @@ -370,5 +369,5 @@ * @} */ -#endif /* __PJLIB_UTIL_CONFIG_H__ */ +#endif /* __PJLIB_UTIL_CONFIG_H__ */ diff --git a/pjlib-util/include/pjlib-util/crc32.h b/pjlib-util/include/pjlib-util/crc32.h index 66596cbc5a..b843a40c20 100644 --- a/pjlib-util/include/pjlib-util/crc32.h +++ b/pjlib-util/include/pjlib-util/crc32.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -40,49 +39,49 @@ PJ_BEGIN_DECL /** CRC32 context. */ typedef struct pj_crc32_context { - pj_uint32_t crc_state; /**< Current state. */ + pj_uint32_t crc_state; /**< Current state. */ } pj_crc32_context; /** * Initialize CRC32 context. * - * @param ctx CRC32 context. + * @param ctx CRC32 context. */ PJ_DECL(void) pj_crc32_init(pj_crc32_context *ctx); /** * Feed data incrementally to the CRC32 algorithm. * - * @param ctx CRC32 context. - * @param data Input data. + * @param ctx CRC32 context. + * @param data Input data. * @param nbytes Length of the input data. * - * @return The current CRC32 value. + * @return The current CRC32 value. */ PJ_DECL(pj_uint32_t) pj_crc32_update(pj_crc32_context *ctx, - const pj_uint8_t *data, - pj_size_t nbytes); + const pj_uint8_t *data, + pj_size_t nbytes); /** * Finalize CRC32 calculation and retrieve the CRC32 value. * - * @param ctx CRC32 context. + * @param ctx CRC32 context. * - * @return The current CRC value. + * @return The current CRC value. */ PJ_DECL(pj_uint32_t) pj_crc32_final(pj_crc32_context *ctx); /** * Perform one-off CRC32 calculation to the specified data. * - * @param data Input data. + * @param data Input data. * @param nbytes Length of input data. * - * @return CRC value of the data. + * @return CRC value of the data. */ PJ_DECL(pj_uint32_t) pj_crc32_calc(const pj_uint8_t *data, - pj_size_t nbytes); + pj_size_t nbytes); /** @@ -92,5 +91,5 @@ PJ_DECL(pj_uint32_t) pj_crc32_calc(const pj_uint8_t *data, PJ_END_DECL -#endif /* __PJLIB_UTIL_CRC32_H__ */ +#endif /* __PJLIB_UTIL_CRC32_H__ */ diff --git a/pjlib-util/include/pjlib-util/dns.h b/pjlib-util/include/pjlib-util/dns.h index 8de09b0b24..e58a1db646 100644 --- a/pjlib-util/include/pjlib-util/dns.h +++ b/pjlib-util/include/pjlib-util/dns.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -62,7 +61,7 @@ PJ_BEGIN_DECL enum { - PJ_DNS_CLASS_IN = 1 /**< DNS class IN. */ + PJ_DNS_CLASS_IN = 1 /**< DNS class IN. */ }; /** @@ -71,54 +70,54 @@ enum */ typedef enum pj_dns_type { - PJ_DNS_TYPE_A = 1, /**< Host address (A) record. */ - PJ_DNS_TYPE_NS = 2, /**< Authoritative name server (NS) */ - PJ_DNS_TYPE_MD = 3, /**< Mail destination (MD) record. */ - PJ_DNS_TYPE_MF = 4, /**< Mail forwarder (MF) record. */ - PJ_DNS_TYPE_CNAME = 5, /**< Canonical name (CNAME) record. */ - PJ_DNS_TYPE_SOA = 6, /**< Marks start of zone authority. */ - PJ_DNS_TYPE_MB = 7, /**< Mailbox domain name (MB). */ - PJ_DNS_TYPE_MG = 8, /**< Mail group member (MG). */ - PJ_DNS_TYPE_MR = 9, /**< Mail rename domain name. */ - PJ_DNS_TYPE_NULL = 10, /**< NULL RR. */ - PJ_DNS_TYPE_WKS = 11, /**< Well known service description */ - PJ_DNS_TYPE_PTR = 12, /**< Domain name pointer. */ - PJ_DNS_TYPE_HINFO = 13, /**< Host information. */ - PJ_DNS_TYPE_MINFO = 14, /**< Mailbox or mail list information. */ - PJ_DNS_TYPE_MX = 15, /**< Mail exchange record. */ - PJ_DNS_TYPE_TXT = 16, /**< Text string. */ - PJ_DNS_TYPE_RP = 17, /**< Responsible person. */ - PJ_DNS_TYPE_AFSB = 18, /**< AFS cell database. */ - PJ_DNS_TYPE_X25 = 19, /**< X.25 calling address. */ - PJ_DNS_TYPE_ISDN = 20, /**< ISDN calling address. */ - PJ_DNS_TYPE_RT = 21, /**< Router. */ - PJ_DNS_TYPE_NSAP = 22, /**< NSAP address. */ - PJ_DNS_TYPE_NSAP_PTR= 23, /**< NSAP reverse address. */ - PJ_DNS_TYPE_SIG = 24, /**< Signature. */ - PJ_DNS_TYPE_KEY = 25, /**< Key. */ - PJ_DNS_TYPE_PX = 26, /**< X.400 mail mapping. */ - PJ_DNS_TYPE_GPOS = 27, /**< Geographical position (withdrawn) */ - PJ_DNS_TYPE_AAAA = 28, /**< IPv6 address. */ - PJ_DNS_TYPE_LOC = 29, /**< Location. */ - PJ_DNS_TYPE_NXT = 30, /**< Next valid name in the zone. */ - PJ_DNS_TYPE_EID = 31, /**< Endpoint idenfitier. */ - PJ_DNS_TYPE_NIMLOC = 32, /**< Nimrod locator. */ - PJ_DNS_TYPE_SRV = 33, /**< Server selection (SRV) record. */ - PJ_DNS_TYPE_ATMA = 34, /**< DNS ATM address record. */ - PJ_DNS_TYPE_NAPTR = 35, /**< DNS Naming authority pointer record. */ - PJ_DNS_TYPE_KX = 36, /**< DNS key exchange record. */ - PJ_DNS_TYPE_CERT = 37, /**< DNS certificate record. */ - PJ_DNS_TYPE_A6 = 38, /**< DNS IPv6 address (experimental) */ - PJ_DNS_TYPE_DNAME = 39, /**< DNS non-terminal name redirection rec. */ - - PJ_DNS_TYPE_OPT = 41, /**< DNS options - contains EDNS metadata. */ - PJ_DNS_TYPE_APL = 42, /**< DNS Address Prefix List (APL) record. */ - PJ_DNS_TYPE_DS = 43, /**< DNS Delegation Signer (DS) */ - PJ_DNS_TYPE_SSHFP = 44, /**< DNS SSH Key Fingerprint */ - PJ_DNS_TYPE_IPSECKEY= 45, /**< DNS IPSEC Key. */ - PJ_DNS_TYPE_RRSIG = 46, /**< DNS Resource Record signature. */ - PJ_DNS_TYPE_NSEC = 47, /**< DNS Next Secure Name. */ - PJ_DNS_TYPE_DNSKEY = 48 /**< DNSSEC Key. */ + PJ_DNS_TYPE_A = 1, /**< Host address (A) record. */ + PJ_DNS_TYPE_NS = 2, /**< Authoritative name server (NS) */ + PJ_DNS_TYPE_MD = 3, /**< Mail destination (MD) record. */ + PJ_DNS_TYPE_MF = 4, /**< Mail forwarder (MF) record. */ + PJ_DNS_TYPE_CNAME = 5, /**< Canonical name (CNAME) record. */ + PJ_DNS_TYPE_SOA = 6, /**< Marks start of zone authority. */ + PJ_DNS_TYPE_MB = 7, /**< Mailbox domain name (MB). */ + PJ_DNS_TYPE_MG = 8, /**< Mail group member (MG). */ + PJ_DNS_TYPE_MR = 9, /**< Mail rename domain name. */ + PJ_DNS_TYPE_NULL = 10, /**< NULL RR. */ + PJ_DNS_TYPE_WKS = 11, /**< Well known service description */ + PJ_DNS_TYPE_PTR = 12, /**< Domain name pointer. */ + PJ_DNS_TYPE_HINFO = 13, /**< Host information. */ + PJ_DNS_TYPE_MINFO = 14, /**< Mailbox or mail list information. */ + PJ_DNS_TYPE_MX = 15, /**< Mail exchange record. */ + PJ_DNS_TYPE_TXT = 16, /**< Text string. */ + PJ_DNS_TYPE_RP = 17, /**< Responsible person. */ + PJ_DNS_TYPE_AFSB = 18, /**< AFS cell database. */ + PJ_DNS_TYPE_X25 = 19, /**< X.25 calling address. */ + PJ_DNS_TYPE_ISDN = 20, /**< ISDN calling address. */ + PJ_DNS_TYPE_RT = 21, /**< Router. */ + PJ_DNS_TYPE_NSAP = 22, /**< NSAP address. */ + PJ_DNS_TYPE_NSAP_PTR= 23, /**< NSAP reverse address. */ + PJ_DNS_TYPE_SIG = 24, /**< Signature. */ + PJ_DNS_TYPE_KEY = 25, /**< Key. */ + PJ_DNS_TYPE_PX = 26, /**< X.400 mail mapping. */ + PJ_DNS_TYPE_GPOS = 27, /**< Geographical position (withdrawn) */ + PJ_DNS_TYPE_AAAA = 28, /**< IPv6 address. */ + PJ_DNS_TYPE_LOC = 29, /**< Location. */ + PJ_DNS_TYPE_NXT = 30, /**< Next valid name in the zone. */ + PJ_DNS_TYPE_EID = 31, /**< Endpoint idenfitier. */ + PJ_DNS_TYPE_NIMLOC = 32, /**< Nimrod locator. */ + PJ_DNS_TYPE_SRV = 33, /**< Server selection (SRV) record. */ + PJ_DNS_TYPE_ATMA = 34, /**< DNS ATM address record. */ + PJ_DNS_TYPE_NAPTR = 35, /**< DNS Naming authority pointer record. */ + PJ_DNS_TYPE_KX = 36, /**< DNS key exchange record. */ + PJ_DNS_TYPE_CERT = 37, /**< DNS certificate record. */ + PJ_DNS_TYPE_A6 = 38, /**< DNS IPv6 address (experimental) */ + PJ_DNS_TYPE_DNAME = 39, /**< DNS non-terminal name redirection rec. */ + + PJ_DNS_TYPE_OPT = 41, /**< DNS options - contains EDNS metadata. */ + PJ_DNS_TYPE_APL = 42, /**< DNS Address Prefix List (APL) record. */ + PJ_DNS_TYPE_DS = 43, /**< DNS Delegation Signer (DS) */ + PJ_DNS_TYPE_SSHFP = 44, /**< DNS SSH Key Fingerprint */ + PJ_DNS_TYPE_IPSECKEY= 45, /**< DNS IPSEC Key. */ + PJ_DNS_TYPE_RRSIG = 46, /**< DNS Resource Record signature. */ + PJ_DNS_TYPE_NSEC = 47, /**< DNS Next Secure Name. */ + PJ_DNS_TYPE_DNSKEY = 48 /**< DNSSEC Key. */ } pj_dns_type; @@ -133,56 +132,56 @@ typedef enum pj_dns_type */ typedef struct pj_dns_hdr { - pj_uint16_t id; /**< Transaction ID. */ - pj_uint16_t flags; /**< Flags. */ - pj_uint16_t qdcount; /**< Nb. of queries. */ - pj_uint16_t anscount; /**< Nb. of res records */ - pj_uint16_t nscount; /**< Nb. of NS records. */ + pj_uint16_t id; /**< Transaction ID. */ + pj_uint16_t flags; /**< Flags. */ + pj_uint16_t qdcount; /**< Nb. of queries. */ + pj_uint16_t anscount; /**< Nb. of res records */ + pj_uint16_t nscount; /**< Nb. of NS records. */ pj_uint16_t arcount; /**< Nb. of additional records */ } pj_dns_hdr; /** Create RCODE flag */ -#define PJ_DNS_SET_RCODE(c) ((pj_uint16_t)((c) & 0x0F)) +#define PJ_DNS_SET_RCODE(c) ((pj_uint16_t)((c) & 0x0F)) /** Create RA (Recursion Available) bit */ -#define PJ_DNS_SET_RA(on) ((pj_uint16_t)((on) << 7)) +#define PJ_DNS_SET_RA(on) ((pj_uint16_t)((on) << 7)) /** Create RD (Recursion Desired) bit */ -#define PJ_DNS_SET_RD(on) ((pj_uint16_t)((on) << 8)) +#define PJ_DNS_SET_RD(on) ((pj_uint16_t)((on) << 8)) /** Create TC (Truncated) bit */ -#define PJ_DNS_SET_TC(on) ((pj_uint16_t)((on) << 9)) +#define PJ_DNS_SET_TC(on) ((pj_uint16_t)((on) << 9)) /** Create AA (Authoritative Answer) bit */ -#define PJ_DNS_SET_AA(on) ((pj_uint16_t)((on) << 10)) +#define PJ_DNS_SET_AA(on) ((pj_uint16_t)((on) << 10)) /** Create four bits opcode */ -#define PJ_DNS_SET_OPCODE(o) ((pj_uint16_t)((o) << 11)) +#define PJ_DNS_SET_OPCODE(o) ((pj_uint16_t)((o) << 11)) /** Create query/response bit */ -#define PJ_DNS_SET_QR(on) ((pj_uint16_t)((on) << 15)) +#define PJ_DNS_SET_QR(on) ((pj_uint16_t)((on) << 15)) /** Get RCODE value */ -#define PJ_DNS_GET_RCODE(val) (((val) & PJ_DNS_SET_RCODE(0x0F)) >> 0) +#define PJ_DNS_GET_RCODE(val) (((val) & PJ_DNS_SET_RCODE(0x0F)) >> 0) /** Get RA bit */ -#define PJ_DNS_GET_RA(val) (((val) & PJ_DNS_SET_RA(1)) >> 7) +#define PJ_DNS_GET_RA(val) (((val) & PJ_DNS_SET_RA(1)) >> 7) /** Get RD bit */ -#define PJ_DNS_GET_RD(val) (((val) & PJ_DNS_SET_RD(1)) >> 8) +#define PJ_DNS_GET_RD(val) (((val) & PJ_DNS_SET_RD(1)) >> 8) /** Get TC bit */ -#define PJ_DNS_GET_TC(val) (((val) & PJ_DNS_SET_TC(1)) >> 9) +#define PJ_DNS_GET_TC(val) (((val) & PJ_DNS_SET_TC(1)) >> 9) /** Get AA bit */ -#define PJ_DNS_GET_AA(val) (((val) & PJ_DNS_SET_AA(1)) >> 10) +#define PJ_DNS_GET_AA(val) (((val) & PJ_DNS_SET_AA(1)) >> 10) /** Get OPCODE value */ -#define PJ_DNS_GET_OPCODE(val) (((val) & PJ_DNS_SET_OPCODE(0x0F)) >> 11) +#define PJ_DNS_GET_OPCODE(val) (((val) & PJ_DNS_SET_OPCODE(0x0F)) >> 11) /** Get QR bit */ -#define PJ_DNS_GET_QR(val) (((val) & PJ_DNS_SET_QR(1)) >> 15) +#define PJ_DNS_GET_QR(val) (((val) & PJ_DNS_SET_QR(1)) >> 15) /** @@ -192,15 +191,15 @@ typedef struct pj_dns_hdr */ typedef enum pj_dns_rcode { - PJ_DNS_RCODE_FORMERR = 1, /**< Format error. */ - PJ_DNS_RCODE_SERVFAIL = 2, /**< Server failure. */ - PJ_DNS_RCODE_NXDOMAIN = 3, /**< Name Error. */ - PJ_DNS_RCODE_NOTIMPL = 4, /**< Not Implemented. */ - PJ_DNS_RCODE_REFUSED = 5, /**< Refused. */ - PJ_DNS_RCODE_YXDOMAIN = 6, /**< The name exists. */ - PJ_DNS_RCODE_YXRRSET = 7, /**< The RRset (name, type) exists. */ + PJ_DNS_RCODE_FORMERR = 1, /**< Format error. */ + PJ_DNS_RCODE_SERVFAIL = 2, /**< Server failure. */ + PJ_DNS_RCODE_NXDOMAIN = 3, /**< Name Error. */ + PJ_DNS_RCODE_NOTIMPL = 4, /**< Not Implemented. */ + PJ_DNS_RCODE_REFUSED = 5, /**< Refused. */ + PJ_DNS_RCODE_YXDOMAIN = 6, /**< The name exists. */ + PJ_DNS_RCODE_YXRRSET = 7, /**< The RRset (name, type) exists. */ PJ_DNS_RCODE_NXRRSET = 8, /**< The RRset (name, type) doesn't exist*/ - PJ_DNS_RCODE_NOTAUTH = 9, /**< Not authorized. */ + PJ_DNS_RCODE_NOTAUTH = 9, /**< Not authorized. */ PJ_DNS_RCODE_NOTZONE = 10 /**< The zone specified is not a zone. */ } pj_dns_rcode; @@ -211,9 +210,9 @@ typedef enum pj_dns_rcode */ typedef struct pj_dns_parsed_query { - pj_str_t name; /**< The domain in the query. */ - pj_uint16_t type; /**< Type of the query (pj_dns_type) */ - pj_uint16_t dnsclass; /**< Network class (PJ_DNS_CLASS_IN=1) */ + pj_str_t name; /**< The domain in the query. */ + pj_uint16_t type; /**< Type of the query (pj_dns_type) */ + pj_uint16_t dnsclass; /**< Network class (PJ_DNS_CLASS_IN=1) */ } pj_dns_parsed_query; @@ -223,52 +222,52 @@ typedef struct pj_dns_parsed_query */ typedef struct pj_dns_parsed_rr { - pj_str_t name; /**< The domain name which this rec pertains. */ - pj_uint16_t type; /**< RR type code. */ - pj_uint16_t dnsclass; /**< Class of data (PJ_DNS_CLASS_IN=1). */ - pj_uint32_t ttl; /**< Time to live. */ - pj_uint16_t rdlength; /**< Resource data length. */ - void *data; /**< Pointer to the raw resource data, only - when the type is not known. If it is known, - the data will be put in rdata below. */ + pj_str_t name; /**< The domain name which this rec pertains. */ + pj_uint16_t type; /**< RR type code. */ + pj_uint16_t dnsclass; /**< Class of data (PJ_DNS_CLASS_IN=1). */ + pj_uint32_t ttl; /**< Time to live. */ + pj_uint16_t rdlength; /**< Resource data length. */ + void *data; /**< Pointer to the raw resource data, only + when the type is not known. If it is known, + the data will be put in rdata below. */ /** For resource types that are recognized/supported by this library, * the parsed resource data will be placed in this rdata union. */ union rdata { - /** SRV Resource Data (PJ_DNS_TYPE_SRV, 33) */ - struct srv { - pj_uint16_t prio; /**< Target priority (lower is higher). */ - pj_uint16_t weight; /**< Weight/proportion */ - pj_uint16_t port; /**< Port number of the service */ - pj_str_t target; /**< Target name. */ - } srv; /**< SRV Resource Data (PJ_DNS_TYPE_SRV, 33) */ - - /** CNAME Resource Data (PJ_DNS_TYPE_CNAME, 5) */ - struct cname { - pj_str_t name; /**< Primary canonical name for an alias. */ - } cname; /**< CNAME Resource Data (PJ_DNS_TYPE_CNAME, 5) */ - - /** NS Resource Data (PJ_DNS_TYPE_NS, 2) */ - struct ns { - pj_str_t name; /**< Primary name server. */ - } ns; /**< NS Resource Data (PJ_DNS_TYPE_NS, 2) */ - - /** PTR Resource Data (PJ_DNS_TYPE_PTR, 12) */ - struct ptr { - pj_str_t name; /**< PTR name. */ - } ptr; /**< PTR Resource Data (PJ_DNS_TYPE_PTR, 12) */ - - /** A Resource Data (PJ_DNS_TYPE_A, 1) */ - struct a { - pj_in_addr ip_addr;/**< IPv4 address in network byte order. */ - } a; /**< A Resource Data (PJ_DNS_TYPE_A, 1) */ - - /** AAAA Resource Data (PJ_DNS_TYPE_AAAA, 28) */ - struct aaaa { - pj_in6_addr ip_addr;/**< IPv6 address in network byte order. */ - } aaaa; /**< AAAA Resource Data (PJ_DNS_TYPE_AAAA, 28) */ + /** SRV Resource Data (PJ_DNS_TYPE_SRV, 33) */ + struct srv { + pj_uint16_t prio; /**< Target priority (lower is higher). */ + pj_uint16_t weight; /**< Weight/proportion */ + pj_uint16_t port; /**< Port number of the service */ + pj_str_t target; /**< Target name. */ + } srv; /**< SRV Resource Data (PJ_DNS_TYPE_SRV, 33) */ + + /** CNAME Resource Data (PJ_DNS_TYPE_CNAME, 5) */ + struct cname { + pj_str_t name; /**< Primary canonical name for an alias. */ + } cname; /**< CNAME Resource Data (PJ_DNS_TYPE_CNAME, 5) */ + + /** NS Resource Data (PJ_DNS_TYPE_NS, 2) */ + struct ns { + pj_str_t name; /**< Primary name server. */ + } ns; /**< NS Resource Data (PJ_DNS_TYPE_NS, 2) */ + + /** PTR Resource Data (PJ_DNS_TYPE_PTR, 12) */ + struct ptr { + pj_str_t name; /**< PTR name. */ + } ptr; /**< PTR Resource Data (PJ_DNS_TYPE_PTR, 12) */ + + /** A Resource Data (PJ_DNS_TYPE_A, 1) */ + struct a { + pj_in_addr ip_addr;/**< IPv4 address in network byte order. */ + } a; /**< A Resource Data (PJ_DNS_TYPE_A, 1) */ + + /** AAAA Resource Data (PJ_DNS_TYPE_AAAA, 28) */ + struct aaaa { + pj_in6_addr ip_addr;/**< IPv6 address in network byte order. */ + } aaaa; /**< AAAA Resource Data (PJ_DNS_TYPE_AAAA, 28) */ } rdata; @@ -282,11 +281,11 @@ typedef struct pj_dns_parsed_rr */ typedef struct pj_dns_parsed_packet { - pj_dns_hdr hdr; /**< Pointer to DNS hdr, in host byte order */ - pj_dns_parsed_query *q; /**< Array of DNS queries. */ - pj_dns_parsed_rr *ans; /**< Array of DNS RR answer. */ - pj_dns_parsed_rr *ns; /**< Array of NS record in the answer. */ - pj_dns_parsed_rr *arr; /**< Array of additional RR answer. */ + pj_dns_hdr hdr; /**< Pointer to DNS hdr, in host byte order */ + pj_dns_parsed_query *q; /**< Array of DNS queries. */ + pj_dns_parsed_rr *ans; /**< Array of DNS RR answer. */ + pj_dns_parsed_rr *ns; /**< Array of NS record in the answer. */ + pj_dns_parsed_rr *arr; /**< Array of additional RR answer. */ } pj_dns_parsed_packet; @@ -296,9 +295,9 @@ typedef struct pj_dns_parsed_packet */ enum pj_dns_dup_options { - PJ_DNS_NO_QD = 1, /**< Do not duplicate the query section. */ - PJ_DNS_NO_ANS = 2, /**< Do not duplicate the answer section. */ - PJ_DNS_NO_NS = 4, /**< Do not duplicate the NS section. */ + PJ_DNS_NO_QD = 1, /**< Do not duplicate the query section. */ + PJ_DNS_NO_ANS = 2, /**< Do not duplicate the answer section. */ + PJ_DNS_NO_NS = 4, /**< Do not duplicate the NS section. */ PJ_DNS_NO_AR = 8 /**< Do not duplicate the additional rec section */ }; @@ -313,61 +312,61 @@ enum pj_dns_dup_options * specified. Once the packet is successfully built, application can send * the packet via TCP or UDP connection. * - * @param packet The buffer to put the DNS query packet. - * @param size On input, it specifies the size of the buffer. - * On output, it will be filled with the actual size of - * the DNS query packet. - * @param id DNS query ID to associate DNS response with the - * query. - * @param qtype DNS type of record to be queried (see #pj_dns_type). - * @param name Name to be queried from the DNS server. + * @param packet The buffer to put the DNS query packet. + * @param size On input, it specifies the size of the buffer. + * On output, it will be filled with the actual size of + * the DNS query packet. + * @param id DNS query ID to associate DNS response with the + * query. + * @param qtype DNS type of record to be queried (see #pj_dns_type). + * @param name Name to be queried from the DNS server. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_dns_make_query(void *packet, - unsigned *size, - pj_uint16_t id, - int qtype, - const pj_str_t *name); + unsigned *size, + pj_uint16_t id, + int qtype, + const pj_str_t *name); /** * Parse raw DNS packet into parsed DNS packet structure. This function is * able to parse few DNS resource records such as A record, PTR record, * CNAME record, NS record, and SRV record. * - * @param pool Pool to allocate memory for the parsed packet. - * @param packet Pointer to the DNS packet (the TCP/UDP payload of - * the raw packet). - * @param size The size of the DNS packet. - * @param p_res Pointer to store the resulting parsed packet. + * @param pool Pool to allocate memory for the parsed packet. + * @param packet Pointer to the DNS packet (the TCP/UDP payload of + * the raw packet). + * @param size The size of the DNS packet. + * @param p_res Pointer to store the resulting parsed packet. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_dns_parse_packet(pj_pool_t *pool, - const void *packet, - unsigned size, - pj_dns_parsed_packet **p_res); + const void *packet, + unsigned size, + pj_dns_parsed_packet **p_res); /** * Duplicate DNS packet. * - * @param pool The pool to allocate memory for the duplicated packet. - * @param p The DNS packet to be cloned. - * @param options Option flags, from pj_dns_dup_options. - * @param p_dst Pointer to store the cloned DNS packet. + * @param pool The pool to allocate memory for the duplicated packet. + * @param p The DNS packet to be cloned. + * @param options Option flags, from pj_dns_dup_options. + * @param p_dst Pointer to store the cloned DNS packet. */ PJ_DECL(void) pj_dns_packet_dup(pj_pool_t *pool, - const pj_dns_parsed_packet*p, - unsigned options, - pj_dns_parsed_packet **p_dst); + const pj_dns_parsed_packet*p, + unsigned options, + pj_dns_parsed_packet **p_dst); /** * Utility function to get the type name string of the specified DNS type. * - * @param type DNS type (see #pj_dns_type). + * @param type DNS type (see #pj_dns_type). * - * @return String name of the type (e.g. "A", "SRV", etc.). + * @return String name of the type (e.g. "A", "SRV", etc.). */ PJ_DECL(const char *) pj_dns_get_type_name(int type); @@ -375,77 +374,77 @@ PJ_DECL(const char *) pj_dns_get_type_name(int type); /** * Initialize DNS record as DNS SRV record. * - * @param rec The DNS resource record to be initialized as DNS - * SRV record. - * @param res_name Resource name. - * @param dnsclass DNS class. - * @param ttl Resource TTL value. - * @param prio DNS SRV priority. - * @param weight DNS SRV weight. - * @param port Target port. - * @param target Target name. + * @param rec The DNS resource record to be initialized as DNS + * SRV record. + * @param res_name Resource name. + * @param dnsclass DNS class. + * @param ttl Resource TTL value. + * @param prio DNS SRV priority. + * @param weight DNS SRV weight. + * @param port Target port. + * @param target Target name. */ PJ_DECL(void) pj_dns_init_srv_rr(pj_dns_parsed_rr *rec, - const pj_str_t *res_name, - unsigned dnsclass, - unsigned ttl, - unsigned prio, - unsigned weight, - unsigned port, - const pj_str_t *target); + const pj_str_t *res_name, + unsigned dnsclass, + unsigned ttl, + unsigned prio, + unsigned weight, + unsigned port, + const pj_str_t *target); /** * Initialize DNS record as DNS CNAME record. * - * @param rec The DNS resource record to be initialized as DNS - * CNAME record. - * @param res_name Resource name. - * @param dnsclass DNS class. - * @param ttl Resource TTL value. - * @param name Host name. + * @param rec The DNS resource record to be initialized as DNS + * CNAME record. + * @param res_name Resource name. + * @param dnsclass DNS class. + * @param ttl Resource TTL value. + * @param name Host name. */ PJ_DECL(void) pj_dns_init_cname_rr(pj_dns_parsed_rr *rec, - const pj_str_t *res_name, - unsigned dnsclass, - unsigned ttl, - const pj_str_t *name); + const pj_str_t *res_name, + unsigned dnsclass, + unsigned ttl, + const pj_str_t *name); /** * Initialize DNS record as DNS A record. * - * @param rec The DNS resource record to be initialized as DNS - * A record. - * @param res_name Resource name. - * @param dnsclass DNS class. - * @param ttl Resource TTL value. - * @param ip_addr Host address. + * @param rec The DNS resource record to be initialized as DNS + * A record. + * @param res_name Resource name. + * @param dnsclass DNS class. + * @param ttl Resource TTL value. + * @param ip_addr Host address. */ PJ_DECL(void) pj_dns_init_a_rr(pj_dns_parsed_rr *rec, - const pj_str_t *res_name, - unsigned dnsclass, - unsigned ttl, - const pj_in_addr *ip_addr); + const pj_str_t *res_name, + unsigned dnsclass, + unsigned ttl, + const pj_in_addr *ip_addr); /** * Initialize DNS record as DNS AAAA record. * - * @param rec The DNS resource record to be initialized as DNS - * AAAA record. - * @param res_name Resource name. - * @param dnsclass DNS class. - * @param ttl Resource TTL value. - * @param ip_addr Host address. + * @param rec The DNS resource record to be initialized as DNS + * AAAA record. + * @param res_name Resource name. + * @param dnsclass DNS class. + * @param ttl Resource TTL value. + * @param ip_addr Host address. */ PJ_DECL(void) pj_dns_init_aaaa_rr(pj_dns_parsed_rr *rec, - const pj_str_t *res_name, - unsigned dnsclass, - unsigned ttl, - const pj_in6_addr *ip_addr); + const pj_str_t *res_name, + unsigned dnsclass, + unsigned ttl, + const pj_in6_addr *ip_addr); /** * Dump DNS packet to standard log. * - * @param res The DNS packet. + * @param res The DNS packet. */ PJ_DECL(void) pj_dns_dump_packet(const pj_dns_parsed_packet *res); @@ -457,5 +456,5 @@ PJ_DECL(void) pj_dns_dump_packet(const pj_dns_parsed_packet *res); PJ_END_DECL -#endif /* __PJLIB_UTIL_DNS_H__ */ +#endif /* __PJLIB_UTIL_DNS_H__ */ diff --git a/pjlib-util/include/pjlib-util/dns_server.h b/pjlib-util/include/pjlib-util/dns_server.h index d73ff3da4e..25d2b30e79 100644 --- a/pjlib-util/include/pjlib-util/dns_server.h +++ b/pjlib-util/include/pjlib-util/dns_server.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,32 +45,32 @@ typedef struct pj_dns_server pj_dns_server; /** * Create the DNS server instance. The instance will run immediately. * - * @param pf The pool factory to create memory pools. + * @param pf The pool factory to create memory pools. * @param ioqueue Ioqueue instance where the server socket will be - * registered to. - * @param af Address family of the server socket (valid values - * are pj_AF_INET() for IPv4 and pj_AF_INET6() for IPv6). - * @param port The UDP port to listen. - * @param flags Flags, currently must be zero. - * @param p_srv Pointer to receive the DNS server instance. + * registered to. + * @param af Address family of the server socket (valid values + * are pj_AF_INET() for IPv4 and pj_AF_INET6() for IPv6). + * @param port The UDP port to listen. + * @param flags Flags, currently must be zero. + * @param p_srv Pointer to receive the DNS server instance. * - * @return PJ_SUCCESS if server has been created successfully, - * otherwise the function will return the appropriate - * error code. + * @return PJ_SUCCESS if server has been created successfully, + * otherwise the function will return the appropriate + * error code. */ PJ_DECL(pj_status_t) pj_dns_server_create(pj_pool_factory *pf, - pj_ioqueue_t *ioqueue, - int af, - unsigned port, - unsigned flags, - pj_dns_server **p_srv); + pj_ioqueue_t *ioqueue, + int af, + unsigned port, + unsigned flags, + pj_dns_server **p_srv); /** * Destroy DNS server instance. * - * @param srv The DNS server instance. + * @param srv The DNS server instance. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_dns_server_destroy(pj_dns_server *srv); @@ -79,30 +78,30 @@ PJ_DECL(pj_status_t) pj_dns_server_destroy(pj_dns_server *srv); /** * Add generic resource record entries to the server. * - * @param srv The DNS server instance. - * @param count Number of records to be added. - * @param rr Array of records to be added. + * @param srv The DNS server instance. + * @param count Number of records to be added. + * @param rr Array of records to be added. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_dns_server_add_rec(pj_dns_server *srv, - unsigned count, - const pj_dns_parsed_rr rr[]); + unsigned count, + const pj_dns_parsed_rr rr[]); /** * Remove the specified record from the server. * - * @param srv The DNS server instance. + * @param srv The DNS server instance. * @param dns_class The resource's DNS class. Valid value is PJ_DNS_CLASS_IN. - * @param type The resource type. - * @param name The resource name to be removed. + * @param type The resource type. + * @param name The resource name to be removed. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_dns_server_del_rec(pj_dns_server *srv, - int dns_class, - pj_dns_type type, - const pj_str_t *name); + int dns_class, + pj_dns_type type, + const pj_str_t *name); @@ -113,5 +112,5 @@ PJ_DECL(pj_status_t) pj_dns_server_del_rec(pj_dns_server *srv, PJ_END_DECL -#endif /* __PJLIB_UTIL_DNS_SERVER_H__ */ +#endif /* __PJLIB_UTIL_DNS_SERVER_H__ */ diff --git a/pjlib-util/include/pjlib-util/errno.h b/pjlib-util/include/pjlib-util/errno.h index 8fa99b1bb6..b6f1fe9478 100644 --- a/pjlib-util/include/pjlib-util/errno.h +++ b/pjlib-util/include/pjlib-util/errno.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -43,67 +42,67 @@ * @hideinitializer * Unable to resolve STUN server */ -#define PJLIB_UTIL_ESTUNRESOLVE (PJLIB_UTIL_ERRNO_START+1) /* 320001 */ +#define PJLIB_UTIL_ESTUNRESOLVE (PJLIB_UTIL_ERRNO_START+1) /* 320001 */ /** * @hideinitializer * Unknown STUN message type. */ -#define PJLIB_UTIL_ESTUNINMSGTYPE (PJLIB_UTIL_ERRNO_START+2) /* 320002 */ +#define PJLIB_UTIL_ESTUNINMSGTYPE (PJLIB_UTIL_ERRNO_START+2) /* 320002 */ /** * @hideinitializer * Invalid STUN message length */ -#define PJLIB_UTIL_ESTUNINMSGLEN (PJLIB_UTIL_ERRNO_START+3) /* 320003 */ +#define PJLIB_UTIL_ESTUNINMSGLEN (PJLIB_UTIL_ERRNO_START+3) /* 320003 */ /** * @hideinitializer * Invalid STUN attribute length */ -#define PJLIB_UTIL_ESTUNINATTRLEN (PJLIB_UTIL_ERRNO_START+4) /* 320004 */ +#define PJLIB_UTIL_ESTUNINATTRLEN (PJLIB_UTIL_ERRNO_START+4) /* 320004 */ /** * @hideinitializer * Invalid STUN attribute type */ -#define PJLIB_UTIL_ESTUNINATTRTYPE (PJLIB_UTIL_ERRNO_START+5) /* 320005 */ +#define PJLIB_UTIL_ESTUNINATTRTYPE (PJLIB_UTIL_ERRNO_START+5) /* 320005 */ /** * @hideinitializer * Invalid STUN server/socket index */ -#define PJLIB_UTIL_ESTUNININDEX (PJLIB_UTIL_ERRNO_START+6) /* 320006 */ +#define PJLIB_UTIL_ESTUNININDEX (PJLIB_UTIL_ERRNO_START+6) /* 320006 */ /** * @hideinitializer * No STUN binding response in the message */ -#define PJLIB_UTIL_ESTUNNOBINDRES (PJLIB_UTIL_ERRNO_START+7) /* 320007 */ +#define PJLIB_UTIL_ESTUNNOBINDRES (PJLIB_UTIL_ERRNO_START+7) /* 320007 */ /** * @hideinitializer * Received STUN error attribute */ -#define PJLIB_UTIL_ESTUNRECVERRATTR (PJLIB_UTIL_ERRNO_START+8) /* 320008 */ +#define PJLIB_UTIL_ESTUNRECVERRATTR (PJLIB_UTIL_ERRNO_START+8) /* 320008 */ /** * @hideinitializer * No STUN mapped address attribute */ -#define PJLIB_UTIL_ESTUNNOMAP (PJLIB_UTIL_ERRNO_START+9) /* 320009 */ +#define PJLIB_UTIL_ESTUNNOMAP (PJLIB_UTIL_ERRNO_START+9) /* 320009 */ /** * @hideinitializer * Received no response from STUN server */ -#define PJLIB_UTIL_ESTUNNOTRESPOND (PJLIB_UTIL_ERRNO_START+10) /* 320010 */ +#define PJLIB_UTIL_ESTUNNOTRESPOND (PJLIB_UTIL_ERRNO_START+10) /* 320010 */ /** * @hideinitializer * Symetric NAT detected by STUN */ -#define PJLIB_UTIL_ESTUNSYMMETRIC (PJLIB_UTIL_ERRNO_START+11) /* 320011 */ +#define PJLIB_UTIL_ESTUNSYMMETRIC (PJLIB_UTIL_ERRNO_START+11) /* 320011 */ /** * @hideinitializer * Invalid STUN magic value */ -#define PJLIB_UTIL_ESTUNNOTMAGIC (PJLIB_UTIL_ERRNO_START+12) /* 320012 */ +#define PJLIB_UTIL_ESTUNNOTMAGIC (PJLIB_UTIL_ERRNO_START+12) /* 320012 */ /** * @hideinitializer * Invalid STUN fingerprint value */ -#define PJLIB_UTIL_ESTUNFINGERPRINT (PJLIB_UTIL_ERRNO_START+13) /* 320013 */ +#define PJLIB_UTIL_ESTUNFINGERPRINT (PJLIB_UTIL_ERRNO_START+13) /* 320013 */ @@ -114,7 +113,7 @@ * @hideinitializer * General invalid XML message. */ -#define PJLIB_UTIL_EINXML (PJLIB_UTIL_ERRNO_START+20) /* 320020 */ +#define PJLIB_UTIL_EINXML (PJLIB_UTIL_ERRNO_START+20) /* 320020 */ /************************************************************ @@ -124,7 +123,7 @@ * @hideinitializer * General invalid JSON message. */ -#define PJLIB_UTIL_EINJSON (PJLIB_UTIL_ERRNO_START+30) /* 320030 */ +#define PJLIB_UTIL_EINJSON (PJLIB_UTIL_ERRNO_START+30) /* 320030 */ /************************************************************ @@ -136,21 +135,21 @@ * This error occurs when the user supplied buffer for creating DNS * query (#pj_dns_make_query() function) is too small. */ -#define PJLIB_UTIL_EDNSQRYTOOSMALL (PJLIB_UTIL_ERRNO_START+40) /* 320040 */ +#define PJLIB_UTIL_EDNSQRYTOOSMALL (PJLIB_UTIL_ERRNO_START+40) /* 320040 */ /** * @hideinitializer * Invalid DNS packet length. * This error occurs when the received DNS response packet does not * match all the fields length. */ -#define PJLIB_UTIL_EDNSINSIZE (PJLIB_UTIL_ERRNO_START+41) /* 320041 */ +#define PJLIB_UTIL_EDNSINSIZE (PJLIB_UTIL_ERRNO_START+41) /* 320041 */ /** * @hideinitializer * Invalid DNS class. * This error occurs when the received DNS response contains network * class other than IN (Internet). */ -#define PJLIB_UTIL_EDNSINCLASS (PJLIB_UTIL_ERRNO_START+42) /* 320042 */ +#define PJLIB_UTIL_EDNSINCLASS (PJLIB_UTIL_ERRNO_START+42) /* 320042 */ /** * @hideinitializer * Invalid DNS name pointer. @@ -158,39 +157,39 @@ * response packet, when the name pointer points to an invalid address * or the parsing has triggerred too much recursion. */ -#define PJLIB_UTIL_EDNSINNAMEPTR (PJLIB_UTIL_ERRNO_START+43) /* 320043 */ +#define PJLIB_UTIL_EDNSINNAMEPTR (PJLIB_UTIL_ERRNO_START+43) /* 320043 */ /** * @hideinitializer * Invalid DNS nameserver address. If hostname was specified for nameserver * address, this error means that the function was unable to resolve * the nameserver hostname. */ -#define PJLIB_UTIL_EDNSINNSADDR (PJLIB_UTIL_ERRNO_START+44) /* 320044 */ +#define PJLIB_UTIL_EDNSINNSADDR (PJLIB_UTIL_ERRNO_START+44) /* 320044 */ /** * @hideinitializer * No nameserver is in DNS resolver. No nameserver is configured in the * resolver. */ -#define PJLIB_UTIL_EDNSNONS (PJLIB_UTIL_ERRNO_START+45) /* 320045 */ +#define PJLIB_UTIL_EDNSNONS (PJLIB_UTIL_ERRNO_START+45) /* 320045 */ /** * @hideinitializer * No working DNS nameserver. All nameservers have been queried, * but none was able to serve any DNS requests. These "bad" nameservers * will be re-tested again for "goodness" after some period. */ -#define PJLIB_UTIL_EDNSNOWORKINGNS (PJLIB_UTIL_ERRNO_START+46) /* 320046 */ +#define PJLIB_UTIL_EDNSNOWORKINGNS (PJLIB_UTIL_ERRNO_START+46) /* 320046 */ /** * @hideinitializer * No answer record in the DNS response. */ -#define PJLIB_UTIL_EDNSNOANSWERREC (PJLIB_UTIL_ERRNO_START+47) /* 320047 */ +#define PJLIB_UTIL_EDNSNOANSWERREC (PJLIB_UTIL_ERRNO_START+47) /* 320047 */ /** * @hideinitializer * Invalid DNS answer. This error is raised for example when the DNS * answer does not have a query section, or the type of RR in the answer * doesn't match the query. */ -#define PJLIB_UTIL_EDNSINANSWER (PJLIB_UTIL_ERRNO_START+48) /* 320048 */ +#define PJLIB_UTIL_EDNSINANSWER (PJLIB_UTIL_ERRNO_START+48) /* 320048 */ /* DNS ERRORS MAPPED FROM RCODE: */ @@ -198,26 +197,26 @@ /** * Start of error code mapped from DNS RCODE */ -#define PJLIB_UTIL_DNS_RCODE_START (PJLIB_UTIL_ERRNO_START+50) /* 320050 */ +#define PJLIB_UTIL_DNS_RCODE_START (PJLIB_UTIL_ERRNO_START+50) /* 320050 */ /** * Map DNS RCODE status into pj_status_t. */ -#define PJ_STATUS_FROM_DNS_RCODE(rcode) (rcode==0 ? PJ_SUCCESS : \ - PJLIB_UTIL_DNS_RCODE_START+rcode) +#define PJ_STATUS_FROM_DNS_RCODE(rcode) (rcode==0 ? PJ_SUCCESS : \ + PJLIB_UTIL_DNS_RCODE_START+rcode) /** * @hideinitializer * Format error - The name server was unable to interpret the query. * This corresponds to DNS RCODE 1. */ -#define PJLIB_UTIL_EDNS_FORMERR PJ_STATUS_FROM_DNS_RCODE(1) /* 320051 */ +#define PJLIB_UTIL_EDNS_FORMERR PJ_STATUS_FROM_DNS_RCODE(1) /* 320051 */ /** * @hideinitializer * Server failure - The name server was unable to process this query due to a * problem with the name server. * This corresponds to DNS RCODE 2. */ -#define PJLIB_UTIL_EDNS_SERVFAIL PJ_STATUS_FROM_DNS_RCODE(2) /* 320052 */ +#define PJLIB_UTIL_EDNS_SERVFAIL PJ_STATUS_FROM_DNS_RCODE(2) /* 320052 */ /** * @hideinitializer * Name Error - Meaningful only for responses from an authoritative name @@ -225,51 +224,51 @@ * does not exist. * This corresponds to DNS RCODE 3. */ -#define PJLIB_UTIL_EDNS_NXDOMAIN PJ_STATUS_FROM_DNS_RCODE(3) /* 320053 */ +#define PJLIB_UTIL_EDNS_NXDOMAIN PJ_STATUS_FROM_DNS_RCODE(3) /* 320053 */ /** * @hideinitializer * Not Implemented - The name server does not support the requested kind of * query. * This corresponds to DNS RCODE 4. */ -#define PJLIB_UTIL_EDNS_NOTIMPL PJ_STATUS_FROM_DNS_RCODE(4) /* 320054 */ +#define PJLIB_UTIL_EDNS_NOTIMPL PJ_STATUS_FROM_DNS_RCODE(4) /* 320054 */ /** * @hideinitializer * Refused - The name server refuses to perform the specified operation for * policy reasons. * This corresponds to DNS RCODE 5. */ -#define PJLIB_UTIL_EDNS_REFUSED PJ_STATUS_FROM_DNS_RCODE(5) /* 320055 */ +#define PJLIB_UTIL_EDNS_REFUSED PJ_STATUS_FROM_DNS_RCODE(5) /* 320055 */ /** * @hideinitializer * The name exists. * This corresponds to DNS RCODE 6. */ -#define PJLIB_UTIL_EDNS_YXDOMAIN PJ_STATUS_FROM_DNS_RCODE(6) /* 320056 */ +#define PJLIB_UTIL_EDNS_YXDOMAIN PJ_STATUS_FROM_DNS_RCODE(6) /* 320056 */ /** * @hideinitializer * The RRset (name, type) exists. * This corresponds to DNS RCODE 7. */ -#define PJLIB_UTIL_EDNS_YXRRSET PJ_STATUS_FROM_DNS_RCODE(7) /* 320057 */ +#define PJLIB_UTIL_EDNS_YXRRSET PJ_STATUS_FROM_DNS_RCODE(7) /* 320057 */ /** * @hideinitializer * The RRset (name, type) does not exist. * This corresponds to DNS RCODE 8. */ -#define PJLIB_UTIL_EDNS_NXRRSET PJ_STATUS_FROM_DNS_RCODE(8) /* 320058 */ +#define PJLIB_UTIL_EDNS_NXRRSET PJ_STATUS_FROM_DNS_RCODE(8) /* 320058 */ /** * @hideinitializer * The requestor is not authorized to perform this operation. * This corresponds to DNS RCODE 9. */ -#define PJLIB_UTIL_EDNS_NOTAUTH PJ_STATUS_FROM_DNS_RCODE(9) /* 320059 */ +#define PJLIB_UTIL_EDNS_NOTAUTH PJ_STATUS_FROM_DNS_RCODE(9) /* 320059 */ /** * @hideinitializer * The zone specified is not a zone. * This corresponds to DNS RCODE 10. */ -#define PJLIB_UTIL_EDNS_NOTZONE PJ_STATUS_FROM_DNS_RCODE(10)/* 320060 */ +#define PJLIB_UTIL_EDNS_NOTZONE PJ_STATUS_FROM_DNS_RCODE(10)/* 320060 */ /************************************************************ @@ -341,22 +340,22 @@ * @hideinitializer * Missing/invalidSTUN MESSAGE-INTEGRITY attribute. */ -#define PJLIB_UTIL_ESTUNMSGINT (PJLIB_UTIL_ERRNO_START+122)/* 320122 */ +#define PJLIB_UTIL_ESTUNMSGINT (PJLIB_UTIL_ERRNO_START+122)/* 320122 */ /** * @hideinitializer * Found duplicate STUN attribute. */ -#define PJLIB_UTIL_ESTUNDUPATTR (PJLIB_UTIL_ERRNO_START+123)/* 320123 */ +#define PJLIB_UTIL_ESTUNDUPATTR (PJLIB_UTIL_ERRNO_START+123)/* 320123 */ /** * @hideinitializer * Missing STUN REALM attribute. */ -#define PJLIB_UTIL_ESTUNNOREALM (PJLIB_UTIL_ERRNO_START+124)/* 320124 */ +#define PJLIB_UTIL_ESTUNNOREALM (PJLIB_UTIL_ERRNO_START+124)/* 320124 */ /** * @hideinitializer * Missing/stale STUN NONCE attribute value. */ -#define PJLIB_UTIL_ESTUNNONCE (PJLIB_UTIL_ERRNO_START+125)/* 320125 */ +#define PJLIB_UTIL_ESTUNNONCE (PJLIB_UTIL_ERRNO_START+125)/* 320125 */ /** * @hideinitializer * STUN transaction terminates with failure. @@ -364,7 +363,7 @@ #define PJLIB_UTIL_ESTUNTSXFAILED (PJLIB_UTIL_ERRNO_START+126)/* 320126 */ -//#define PJ_STATUS_FROM_STUN_CODE(code) (PJLIB_UTIL_ERRNO_START+code) +//#define PJ_STATUS_FROM_STUN_CODE(code) (PJLIB_UTIL_ERRNO_START+code) /************************************************************ * HTTP Client ERROR @@ -373,27 +372,27 @@ * @hideinitializer * Invalid URL format */ -#define PJLIB_UTIL_EHTTPINURL (PJLIB_UTIL_ERRNO_START+151)/* 320151 */ +#define PJLIB_UTIL_EHTTPINURL (PJLIB_UTIL_ERRNO_START+151)/* 320151 */ /** * @hideinitializer * Invalid port number */ -#define PJLIB_UTIL_EHTTPINPORT (PJLIB_UTIL_ERRNO_START+152)/* 320152 */ +#define PJLIB_UTIL_EHTTPINPORT (PJLIB_UTIL_ERRNO_START+152)/* 320152 */ /** * @hideinitializer * Incomplete headers received */ -#define PJLIB_UTIL_EHTTPINCHDR (PJLIB_UTIL_ERRNO_START+153)/* 320153 */ +#define PJLIB_UTIL_EHTTPINCHDR (PJLIB_UTIL_ERRNO_START+153)/* 320153 */ /** * @hideinitializer * Insufficient buffer */ -#define PJLIB_UTIL_EHTTPINSBUF (PJLIB_UTIL_ERRNO_START+154)/* 320154 */ +#define PJLIB_UTIL_EHTTPINSBUF (PJLIB_UTIL_ERRNO_START+154)/* 320154 */ /** * @hideinitializer * Connection lost */ -#define PJLIB_UTIL_EHTTPLOST (PJLIB_UTIL_ERRNO_START+155)/* 320155 */ +#define PJLIB_UTIL_EHTTPLOST (PJLIB_UTIL_ERRNO_START+155)/* 320155 */ /************************************************************ * CLI ERROR @@ -405,44 +404,44 @@ * pj_cli_sess_exec() to indicate that "exit" or equivalent command has been * called to end the current session. */ -#define PJ_CLI_EEXIT (PJLIB_UTIL_ERRNO_START+201)/* 320201 */ +#define PJ_CLI_EEXIT (PJLIB_UTIL_ERRNO_START+201)/* 320201 */ /** * @hideinitializer * A required CLI argument is not specified. */ -#define PJ_CLI_EMISSINGARG (PJLIB_UTIL_ERRNO_START+202)/* 320202 */ +#define PJ_CLI_EMISSINGARG (PJLIB_UTIL_ERRNO_START+202)/* 320202 */ /** * @hideinitializer * Too many CLI arguments. */ -#define PJ_CLI_ETOOMANYARGS (PJLIB_UTIL_ERRNO_START+203)/* 320203 */ +#define PJ_CLI_ETOOMANYARGS (PJLIB_UTIL_ERRNO_START+203)/* 320203 */ /** * @hideinitializer * Invalid CLI argument. Typically this is caused by extra characters * specified in the command line which does not match any arguments. */ -#define PJ_CLI_EINVARG (PJLIB_UTIL_ERRNO_START+204)/* 320204 */ +#define PJ_CLI_EINVARG (PJLIB_UTIL_ERRNO_START+204)/* 320204 */ /** * @hideinitializer * CLI command with the specified name already exist. */ -#define PJ_CLI_EBADNAME (PJLIB_UTIL_ERRNO_START+205)/* 320205 */ +#define PJ_CLI_EBADNAME (PJLIB_UTIL_ERRNO_START+205)/* 320205 */ /** * @hideinitializer * CLI command with the specified id already exist. */ -#define PJ_CLI_EBADID (PJLIB_UTIL_ERRNO_START+206)/* 320206 */ +#define PJ_CLI_EBADID (PJLIB_UTIL_ERRNO_START+206)/* 320206 */ /** * @hideinitializer * Invalid XML format for CLI command specification. */ -#define PJ_CLI_EBADXML (PJLIB_UTIL_ERRNO_START+207)/* 320207 */ +#define PJ_CLI_EBADXML (PJLIB_UTIL_ERRNO_START+207)/* 320207 */ /** * @hideinitializer * CLI command entered by user match with more than one command/argument * specification. */ -#define PJ_CLI_EAMBIGUOUS (PJLIB_UTIL_ERRNO_START+208)/* 320208 */ +#define PJ_CLI_EAMBIGUOUS (PJLIB_UTIL_ERRNO_START+208)/* 320208 */ /** * @hideinitializer * Telnet connection lost. @@ -453,4 +452,4 @@ * @} */ -#endif /* __PJLIB_UTIL_ERRNO_H__ */ +#endif /* __PJLIB_UTIL_ERRNO_H__ */ diff --git a/pjlib-util/include/pjlib-util/getopt.h b/pjlib-util/include/pjlib-util/getopt.h index 2eb746ca0f..4ad705419c 100644 --- a/pjlib-util/include/pjlib-util/getopt.h +++ b/pjlib-util/include/pjlib-util/getopt.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* Declarations for pj_getopt. Copyright (C) 1989,90,91,92,93,94,96,97,98 Free Software Foundation, Inc. This file is part of the GNU C Library. @@ -32,7 +31,7 @@ * @{ */ -#ifdef __cplusplus +#ifdef __cplusplus extern "C" { #endif @@ -68,9 +67,9 @@ extern int pj_optopt; zero. The field `has_arg' is: - no_argument (or 0) if the option does not take an argument, - required_argument (or 1) if the option requires an argument, - optional_argument (or 2) if the option takes an optional argument. + no_argument (or 0) if the option does not take an argument, + required_argument (or 1) if the option requires an argument, + optional_argument (or 2) if the option takes an optional argument. If the field `flag' is not NULL, it points to a variable that is set to the value given in the field `val' when the option is found, but @@ -95,9 +94,9 @@ struct pj_getopt_option /* Names for the values of the `has_arg' field of `struct pj_getopt_option'. */ -# define no_argument 0 -# define required_argument 1 -# define optional_argument 2 +# define no_argument 0 +# define required_argument 1 +# define optional_argument 2 /* Get definitions and prototypes for functions to process the @@ -127,13 +126,13 @@ struct pj_getopt_option int pj_getopt (int argc, char *const *argv, const char *shortopts); int pj_getopt_long (int argc, char *const *argv, const char *options, - const struct pj_getopt_option *longopts, int *longind); + const struct pj_getopt_option *longopts, int *longind); int pj_getopt_long_only (int argc, char *const *argv, - const char *shortopts, - const struct pj_getopt_option *longopts, int *longind); + const char *shortopts, + const struct pj_getopt_option *longopts, int *longind); -#ifdef __cplusplus +#ifdef __cplusplus } #endif diff --git a/pjlib-util/include/pjlib-util/hmac_md5.h b/pjlib-util/include/pjlib-util/hmac_md5.h index 2b59024ee8..cb278db818 100644 --- a/pjlib-util/include/pjlib-util/hmac_md5.h +++ b/pjlib-util/include/pjlib-util/hmac_md5.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -48,54 +47,54 @@ PJ_BEGIN_DECL */ typedef struct pj_hmac_md5_context { - pj_md5_context context; /**< MD5 context */ - pj_uint8_t k_opad[64]; /**< opad xor-ed with key */ + pj_md5_context context; /**< MD5 context */ + pj_uint8_t k_opad[64]; /**< opad xor-ed with key */ } pj_hmac_md5_context; /** * Calculate HMAC MD5 digest for the specified input and key. * - * @param input Pointer to the input stream. - * @param input_len Length of input stream in bytes. - * @param key Pointer to the authentication key. - * @param key_len Length of the authentication key. - * @param digest Buffer to be filled with HMAC MD5 digest. + * @param input Pointer to the input stream. + * @param input_len Length of input stream in bytes. + * @param key Pointer to the authentication key. + * @param key_len Length of the authentication key. + * @param digest Buffer to be filled with HMAC MD5 digest. */ PJ_DECL(void) pj_hmac_md5(const pj_uint8_t *input, unsigned input_len, - const pj_uint8_t *key, unsigned key_len, - pj_uint8_t digest[16]); + const pj_uint8_t *key, unsigned key_len, + pj_uint8_t digest[16]); /** * Initiate HMAC-MD5 context for incremental hashing. * - * @param hctx HMAC-MD5 context. - * @param key Pointer to the authentication key. - * @param key_len Length of the authentication key. + * @param hctx HMAC-MD5 context. + * @param key Pointer to the authentication key. + * @param key_len Length of the authentication key. */ PJ_DECL(void) pj_hmac_md5_init(pj_hmac_md5_context *hctx, - const pj_uint8_t *key, unsigned key_len); + const pj_uint8_t *key, unsigned key_len); /** * Append string to the message. * - * @param hctx HMAC-MD5 context. - * @param input Pointer to the input stream. - * @param input_len Length of input stream in bytes. + * @param hctx HMAC-MD5 context. + * @param input Pointer to the input stream. + * @param input_len Length of input stream in bytes. */ PJ_DECL(void) pj_hmac_md5_update(pj_hmac_md5_context *hctx, - const pj_uint8_t *input, - unsigned input_len); + const pj_uint8_t *input, + unsigned input_len); /** * Finish the message and return the digest. * - * @param hctx HMAC-MD5 context. - * @param digest Buffer to be filled with HMAC MD5 digest. + * @param hctx HMAC-MD5 context. + * @param digest Buffer to be filled with HMAC MD5 digest. */ PJ_DECL(void) pj_hmac_md5_final(pj_hmac_md5_context *hctx, - pj_uint8_t digest[16]); + pj_uint8_t digest[16]); /** * @} @@ -104,6 +103,6 @@ PJ_DECL(void) pj_hmac_md5_final(pj_hmac_md5_context *hctx, PJ_END_DECL -#endif /* __PJLIB_UTIL_HMAC_MD5_H__ */ +#endif /* __PJLIB_UTIL_HMAC_MD5_H__ */ diff --git a/pjlib-util/include/pjlib-util/hmac_sha1.h b/pjlib-util/include/pjlib-util/hmac_sha1.h index dc1ff201d6..d975f89307 100644 --- a/pjlib-util/include/pjlib-util/hmac_sha1.h +++ b/pjlib-util/include/pjlib-util/hmac_sha1.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,8 +43,8 @@ PJ_BEGIN_DECL */ typedef struct pj_hmac_sha1_context { - pj_sha1_context context; /**< SHA1 context */ - pj_uint8_t k_opad[64]; /**< opad xor-ed with key */ + pj_sha1_context context; /**< SHA1 context */ + pj_uint8_t k_opad[64]; /**< opad xor-ed with key */ } pj_hmac_sha1_context; @@ -53,46 +52,46 @@ typedef struct pj_hmac_sha1_context * Calculate HMAC-SHA1 digest for the specified input and key with this * single function call. * - * @param input Pointer to the input stream. - * @param input_len Length of input stream in bytes. - * @param key Pointer to the authentication key. - * @param key_len Length of the authentication key. - * @param digest Buffer to be filled with HMAC SHA1 digest. + * @param input Pointer to the input stream. + * @param input_len Length of input stream in bytes. + * @param key Pointer to the authentication key. + * @param key_len Length of the authentication key. + * @param digest Buffer to be filled with HMAC SHA1 digest. */ PJ_DECL(void) pj_hmac_sha1(const pj_uint8_t *input, unsigned input_len, - const pj_uint8_t *key, unsigned key_len, - pj_uint8_t digest[20]); + const pj_uint8_t *key, unsigned key_len, + pj_uint8_t digest[20]); /** * Initiate HMAC-SHA1 context for incremental hashing. * - * @param hctx HMAC-SHA1 context. - * @param key Pointer to the authentication key. - * @param key_len Length of the authentication key. + * @param hctx HMAC-SHA1 context. + * @param key Pointer to the authentication key. + * @param key_len Length of the authentication key. */ PJ_DECL(void) pj_hmac_sha1_init(pj_hmac_sha1_context *hctx, - const pj_uint8_t *key, unsigned key_len); + const pj_uint8_t *key, unsigned key_len); /** * Append string to the message. * - * @param hctx HMAC-SHA1 context. - * @param input Pointer to the input stream. - * @param input_len Length of input stream in bytes. + * @param hctx HMAC-SHA1 context. + * @param input Pointer to the input stream. + * @param input_len Length of input stream in bytes. */ PJ_DECL(void) pj_hmac_sha1_update(pj_hmac_sha1_context *hctx, - const pj_uint8_t *input, - unsigned input_len); + const pj_uint8_t *input, + unsigned input_len); /** * Finish the message and return the digest. * - * @param hctx HMAC-SHA1 context. - * @param digest Buffer to be filled with HMAC SHA1 digest. + * @param hctx HMAC-SHA1 context. + * @param digest Buffer to be filled with HMAC SHA1 digest. */ PJ_DECL(void) pj_hmac_sha1_final(pj_hmac_sha1_context *hctx, - pj_uint8_t digest[20]); + pj_uint8_t digest[20]); /** @@ -102,6 +101,6 @@ PJ_DECL(void) pj_hmac_sha1_final(pj_hmac_sha1_context *hctx, PJ_END_DECL -#endif /* __PJLIB_UTIL_HMAC_SHA1_H__ */ +#endif /* __PJLIB_UTIL_HMAC_SHA1_H__ */ diff --git a/pjlib-util/include/pjlib-util/http_client.h b/pjlib-util/include/pjlib-util/http_client.h index 8ca37e8da6..955e7c0736 100644 --- a/pjlib-util/include/pjlib-util/http_client.h +++ b/pjlib-util/include/pjlib-util/http_client.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -53,8 +52,8 @@ typedef struct pj_http_req pj_http_req; */ typedef struct pj_http_header_elmt { - pj_str_t name; /**< Header name */ - pj_str_t value; /**< Header value */ + pj_str_t name; /**< Header name */ + pj_str_t value; /**< Header value */ } pj_http_header_elmt; /** @@ -83,7 +82,7 @@ typedef struct pj_http_auth_cred * * Default is empty. */ - pj_str_t scheme; + pj_str_t scheme; /** * Specify specific authentication realm to be responded. If this field @@ -92,14 +91,14 @@ typedef struct pj_http_auth_cred * * Default is empty. */ - pj_str_t realm; + pj_str_t realm; /** * Specify authentication username. * * Default is empty. */ - pj_str_t username; + pj_str_t username; /** * The type of password in \a data field. Currently only 0 is @@ -107,7 +106,7 @@ typedef struct pj_http_auth_cred * * Default is 0. */ - unsigned data_type; + unsigned data_type; /** * Specify authentication password. The encoding of the password depends @@ -115,7 +114,7 @@ typedef struct pj_http_auth_cred * * Default is empty. */ - pj_str_t data; + pj_str_t data; } pj_http_auth_cred; @@ -186,7 +185,7 @@ typedef struct pj_http_req_param /** * Authentication credential needed to respond to 401/407 response. */ - pj_http_auth_cred auth_cred; + pj_http_auth_cred auth_cred; /** * Optional source port range to use when binding the socket. @@ -199,7 +198,7 @@ typedef struct pj_http_req_param * * Default is 0 (The OS will select the source port automatically) */ - pj_uint16_t source_port_range_start; + pj_uint16_t source_port_range_start; /** * Optional source port range to use when binding. @@ -207,7 +206,7 @@ typedef struct pj_http_req_param * * Default is 0 (The OS will select the source port automatically)) */ - pj_uint16_t source_port_range_size; + pj_uint16_t source_port_range_size; /** * Max number of retries if binding to a port fails. @@ -216,7 +215,7 @@ typedef struct pj_http_req_param * * Default is 3 */ - pj_uint16_t max_retries; + pj_uint16_t max_retries; } pj_http_req_param; @@ -225,14 +224,14 @@ typedef struct pj_http_req_param */ typedef struct pj_http_auth_chal { - pj_str_t scheme; /**< Auth scheme. */ - pj_str_t realm; /**< Realm for the challenge. */ - pj_str_t domain; /**< Domain. */ - pj_str_t nonce; /**< Nonce challenge. */ - pj_str_t opaque; /**< Opaque value. */ - int stale; /**< Stale parameter. */ - pj_str_t algorithm; /**< Algorithm parameter. */ - pj_str_t qop; /**< Quality of protection. */ + pj_str_t scheme; /**< Auth scheme. */ + pj_str_t realm; /**< Realm for the challenge. */ + pj_str_t domain; /**< Domain. */ + pj_str_t nonce; /**< Nonce challenge. */ + pj_str_t opaque; /**< Opaque value. */ + int stale; /**< Stale parameter. */ + pj_str_t algorithm; /**< Algorithm parameter. */ + pj_str_t qop; /**< Quality of protection. */ } pj_http_auth_chal; /** @@ -245,9 +244,9 @@ typedef struct pj_http_resp pj_str_t reason; /**< Reason phrase */ pj_http_headers headers; /**< Response headers */ pj_http_auth_chal auth_chal; /**< Parsed WWW-Authenticate header, if - any. */ + any. */ pj_int32_t content_length; /**< The value of content-length header - field. -1 if not specified. */ + field. -1 if not specified. */ void *data; /**< Data received */ pj_size_t size; /**< Data size */ } pj_http_resp; @@ -257,8 +256,8 @@ typedef struct pj_http_resp */ typedef struct pj_http_url { - pj_str_t username; /**< Username part */ - pj_str_t passwd; /**< Password part */ + pj_str_t username; /**< Username part */ + pj_str_t passwd; /**< Password part */ pj_str_t protocol; /**< Protocol used */ pj_str_t host; /**< Host name */ pj_uint16_t port; /**< Port number */ @@ -274,8 +273,8 @@ typedef struct pj_http_req_callback * This callback is called when a complete HTTP response header * is received. * - * @param http_req The http request. - * @param resp The response of the request. + * @param http_req The http request. + * @param resp The response of the request. */ void (*on_response)(pj_http_req *http_req, const pj_http_resp *resp); @@ -287,13 +286,13 @@ typedef struct pj_http_req_callback * callback to be called, application MUST set http_req_param.total_size * to a value greater than 0. * - * @param http_req The http request. - * @param data Pointer to the data that will be sent. Application + * @param http_req The http request. + * @param data Pointer to the data that will be sent. Application * must set the pointer to the current data chunk/segment * to be sent. Data must remain valid until the next * on_send_data() callback or for the last segment, * until it is sent. - * @param size Pointer to the data size that will be sent. + * @param size Pointer to the data size that will be sent. */ void (*on_send_data)(pj_http_req *http_req, void **data, pj_size_t *size); @@ -307,9 +306,9 @@ typedef struct pj_http_req_callback * on_complete() callback will be called with the response * parameter containing the complete data. * - * @param http_req The http request. - * @param data The buffer containing the data. - * @param size The length of data in the buffer. + * @param http_req The http request. + * @param data The buffer containing the data. + * @param size The length of data in the buffer. */ void (*on_data_read)(pj_http_req *http_req, void *data, pj_size_t size); @@ -327,15 +326,15 @@ typedef struct pj_http_req_callback * pj_http_req immediately by calling #pj_http_req_destroy() inside * the callback. * - * @param http_req The http request. - * @param status The status of the request operation. PJ_SUCCESS + * @param http_req The http request. + * @param status The status of the request operation. PJ_SUCCESS * if the operation completed successfully * (connection-wise). To check the server's * status-code response to the HTTP request, * application should check resp->status_code instead. - * @param resp The response of the corresponding request. If - * the status argument is non-PJ_SUCCESS, this - * argument will be set to NULL. + * @param resp The response of the corresponding request. If + * the status argument is non-PJ_SUCCESS, this + * argument will be set to NULL. */ void (*on_complete)(pj_http_req *http_req, pj_status_t status, @@ -347,7 +346,7 @@ typedef struct pj_http_req_callback /** * Initialize the http request parameters with the default values. * - * @param param The parameter to be initialized. + * @param param The parameter to be initialized. */ PJ_DECL(void) pj_http_req_param_default(pj_http_req_param *param); @@ -355,12 +354,12 @@ PJ_DECL(void) pj_http_req_param_default(pj_http_req_param *param); * Add a header element/field. Application MUST make sure that * name and val pointer remains valid until the HTTP request is sent. * - * @param headers The headers. - * @param name The header field name. - * @param val The header field value. + * @param headers The headers. + * @param name The header field name. + * @param val The header field value. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_http_headers_add_elmt(pj_http_headers *headers, pj_str_t *name, @@ -371,12 +370,12 @@ PJ_DECL(pj_status_t) pj_http_headers_add_elmt(pj_http_headers *headers, * its parameters. Application MUST make sure that name and val pointer * remains valid until the HTTP request is sent. * - * @param headers The headers. - * @param name The header field name. - * @param val The header field value. + * @param headers The headers. + * @param name The header field name. + * @param val The header field value. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_http_headers_add_elmt2(pj_http_headers *headers, char *name, char *val); @@ -384,11 +383,11 @@ PJ_DECL(pj_status_t) pj_http_headers_add_elmt2(pj_http_headers *headers, /** * Parse a http URL into its components. * - * @param url The URL to be parsed. - * @param hurl Pointer to receive the parsed result. + * @param url The URL to be parsed. + * @param hurl Pointer to receive the parsed result. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_http_req_parse_url(const pj_str_t *url, pj_http_url *hurl); @@ -396,24 +395,24 @@ PJ_DECL(pj_status_t) pj_http_req_parse_url(const pj_str_t *url, /** * Create the HTTP request. * - * @param pool Pool to use. HTTP request will use the pool's factory + * @param pool Pool to use. HTTP request will use the pool's factory * to allocate its own memory pool. - * @param url HTTP URL request. - * @param timer The timer to use. - * @param ioqueue The ioqueue to use. - * @param param Optional parameters. When this parameter is not + * @param url HTTP URL request. + * @param timer The timer to use. + * @param ioqueue The ioqueue to use. + * @param param Optional parameters. When this parameter is not * specifed (NULL), the default values will be used. - * @param hcb Pointer to structure containing application - * callbacks. - * @param http_req Pointer to receive the http request instance. + * @param hcb Pointer to structure containing application + * callbacks. + * @param http_req Pointer to receive the http request instance. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_http_req_create(pj_pool_t *pool, const pj_str_t *url, - pj_timer_heap_t *timer, - pj_ioqueue_t *ioqueue, + pj_timer_heap_t *timer, + pj_ioqueue_t *ioqueue, const pj_http_req_param *param, const pj_http_req_callback *hcb, pj_http_req **http_req); @@ -458,7 +457,7 @@ PJ_DECL(pj_status_t) pj_http_req_cancel(pj_http_req *http_req, /** * Destroy the http request. * - * @param http_req The http request to be destroyed. + * @param http_req The http request to be destroyed. * * @return PJ_SUCCESS if success. */ @@ -469,8 +468,8 @@ PJ_DECL(pj_status_t) pj_http_req_destroy(pj_http_req *http_req); * * @param http_req The http request. * - * @return PJ_TRUE if a request is pending, or - * PJ_FALSE if idle + * @return PJ_TRUE if a request is pending, or + * PJ_FALSE if idle */ PJ_DECL(pj_bool_t) pj_http_req_is_running(const pj_http_req *http_req); @@ -480,7 +479,7 @@ PJ_DECL(pj_bool_t) pj_http_req_is_running(const pj_http_req *http_req); * * @param http_req The http request. * - * @return The user data. + * @return The user data. */ PJ_DECL(void *) pj_http_req_get_user_data(pj_http_req *http_req); @@ -491,4 +490,4 @@ PJ_DECL(void *) pj_http_req_get_user_data(pj_http_req *http_req); PJ_END_DECL -#endif /* __PJLIB_UTIL_HTTP_CLIENT_H__ */ +#endif /* __PJLIB_UTIL_HTTP_CLIENT_H__ */ diff --git a/pjlib-util/include/pjlib-util/json.h b/pjlib-util/include/pjlib-util/json.h index 56d55b467e..b6702b04a3 100644 --- a/pjlib-util/include/pjlib-util/json.h +++ b/pjlib-util/include/pjlib-util/json.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -44,12 +43,12 @@ PJ_BEGIN_DECL */ typedef enum pj_json_val_type { - PJ_JSON_VAL_NULL, /**< Null value (null) */ - PJ_JSON_VAL_BOOL, /**< Boolean value (true, false) */ - PJ_JSON_VAL_NUMBER, /**< Numeric (float or fixed point) */ - PJ_JSON_VAL_STRING, /**< Literal string value. */ - PJ_JSON_VAL_ARRAY, /**< Array */ - PJ_JSON_VAL_OBJ /**< Object. */ + PJ_JSON_VAL_NULL, /**< Null value (null) */ + PJ_JSON_VAL_BOOL, /**< Boolean value (true, false) */ + PJ_JSON_VAL_NUMBER, /**< Numeric (float or fixed point) */ + PJ_JSON_VAL_STRING, /**< Literal string value. */ + PJ_JSON_VAL_ARRAY, /**< Array */ + PJ_JSON_VAL_OBJ /**< Object. */ } pj_json_val_type; /* Forward declaration for JSON element */ @@ -73,15 +72,15 @@ typedef struct pj_json_list struct pj_json_elem { PJ_DECL_LIST_MEMBER(pj_json_elem); - pj_str_t name; /**< ELement name. */ - pj_json_val_type type; /**< Element type. */ + pj_str_t name; /**< ELement name. */ + pj_json_val_type type; /**< Element type. */ union { - pj_bool_t is_true; /**< Boolean value. */ - float num; /**< Number value. */ - pj_str_t str; /**< String value. */ - pj_json_list children; /**< Object and array children */ - } value; /**< Element value. */ + pj_bool_t is_true; /**< Boolean value. */ + float num; /**< Number value. */ + pj_str_t str; /**< String value. */ + pj_json_list children; /**< Object and array children */ + } value; /**< Element value. */ }; /** @@ -90,40 +89,40 @@ struct pj_json_elem */ typedef struct pj_json_err_info { - unsigned line; /**< Line location of the error */ - unsigned col; /**< Column location of the error */ - int err_char; /**< The offending character. */ + unsigned line; /**< Line location of the error */ + unsigned col; /**< Column location of the error */ + int err_char; /**< The offending character. */ } pj_json_err_info; /** * Type of function callback to write JSON document in pj_json_writef(). * - * @param s The string to be written to the document. - * @param size The length of the string - * @param user_data User data that was specified to pj_json_writef() + * @param s The string to be written to the document. + * @param size The length of the string + * @param user_data User data that was specified to pj_json_writef() * - * @return If the callback returns non-PJ_SUCCESS, it will - * stop the pj_json_writef() function and this error - * will be returned to caller. + * @return If the callback returns non-PJ_SUCCESS, it will + * stop the pj_json_writef() function and this error + * will be returned to caller. */ typedef pj_status_t (*pj_json_writer)(const char *s, - unsigned size, - void *user_data); + unsigned size, + void *user_data); /** * Initialize null element. * - * @param el The element. - * @param name Name to be given to the element, or NULL. + * @param el The element. + * @param name Name to be given to the element, or NULL. */ PJ_DECL(void) pj_json_elem_null(pj_json_elem *el, pj_str_t *name); /** * Initialize boolean element with the specified value. * - * @param el The element. - * @param name Name to be given to the element, or NULL. - * @param val The value. + * @param el The element. + * @param name Name to be given to the element, or NULL. + * @param val The value. */ PJ_DECL(void) pj_json_elem_bool(pj_json_elem *el, pj_str_t *name, pj_bool_t val); @@ -131,9 +130,9 @@ PJ_DECL(void) pj_json_elem_bool(pj_json_elem *el, pj_str_t *name, /** * Initialize number element with the specified value. * - * @param el The element. - * @param name Name to be given to the element, or NULL. - * @param val The value. + * @param el The element. + * @param name Name to be given to the element, or NULL. + * @param val The value. */ PJ_DECL(void) pj_json_elem_number(pj_json_elem *el, pj_str_t *name, float val); @@ -141,9 +140,9 @@ PJ_DECL(void) pj_json_elem_number(pj_json_elem *el, pj_str_t *name, /** * Initialize string element with the specified value. * - * @param el The element. - * @param name Name to be given to the element, or NULL. - * @param val The value. + * @param el The element. + * @param name Name to be given to the element, or NULL. + * @param val The value. */ PJ_DECL(void) pj_json_elem_string(pj_json_elem *el, pj_str_t *name, pj_str_t *val); @@ -151,24 +150,24 @@ PJ_DECL(void) pj_json_elem_string(pj_json_elem *el, pj_str_t *name, /** * Initialize element as an empty array * - * @param el The element. - * @param name Name to be given to the element, or NULL. + * @param el The element. + * @param name Name to be given to the element, or NULL. */ PJ_DECL(void) pj_json_elem_array(pj_json_elem *el, pj_str_t *name); /** * Initialize element as an empty object * - * @param el The element. - * @param name Name to be given to the element, or NULL. + * @param el The element. + * @param name Name to be given to the element, or NULL. */ PJ_DECL(void) pj_json_elem_obj(pj_json_elem *el, pj_str_t *name); /** * Add an element to an object or array. * - * @param el The object or array element. - * @param child Element to be added to the object or array. + * @param el The object or array element. + * @param child Element to be added to the object or array. */ PJ_DECL(void) pj_json_elem_add(pj_json_elem *el, pj_json_elem *child); @@ -176,13 +175,13 @@ PJ_DECL(void) pj_json_elem_add(pj_json_elem *el, pj_json_elem *child); * Parse a JSON document in the buffer. The buffer MUST be NULL terminated, * or if not then it must have enough size to put the NULL character. * - * @param pool The pool to allocate memory for creating elements. - * @param buffer String buffer containing JSON document. - * @param size Size of the document. - * @param err_info Optional structure to be filled with info when - * parsing failed. + * @param pool The pool to allocate memory for creating elements. + * @param buffer String buffer containing JSON document. + * @param size Size of the document. + * @param err_info Optional structure to be filled with info when + * parsing failed. * - * @return The root element from the document. + * @return The root element from the document. */ PJ_DECL(pj_json_elem*) pj_json_parse(pj_pool_t *pool, char *buffer, @@ -192,13 +191,13 @@ PJ_DECL(pj_json_elem*) pj_json_parse(pj_pool_t *pool, /** * Write the specified element to the string buffer. * - * @param elem The element to be written. - * @param buffer Output buffer. - * @param size On input, it must be set to the size of the buffer. - * Upon successful return, this will be set to - * the length of the written string. + * @param elem The element to be written. + * @param buffer Output buffer. + * @param size On input, it must be set to the size of the buffer. + * Upon successful return, this will be set to + * the length of the written string. * - * @return PJ_SUCCESS on success or the appropriate error. + * @return PJ_SUCCESS on success or the appropriate error. */ PJ_DECL(pj_status_t) pj_json_write(const pj_json_elem *elem, char *buffer, unsigned *size); @@ -207,13 +206,13 @@ PJ_DECL(pj_status_t) pj_json_write(const pj_json_elem *elem, * Incrementally write the element to arbitrary medium using the specified * callback to write the document chunks. * - * @param elem The element to be written. - * @param writer Callback function which will be called to write - * text chunks. - * @param user_data Arbitrary user data which will be given back when - * calling the callback. + * @param elem The element to be written. + * @param writer Callback function which will be called to write + * text chunks. + * @param user_data Arbitrary user data which will be given back when + * calling the callback. * - * @return PJ_SUCCESS on success or the appropriate error. + * @return PJ_SUCCESS on success or the appropriate error. */ PJ_DECL(pj_status_t) pj_json_writef(const pj_json_elem *elem, pj_json_writer writer, @@ -225,4 +224,4 @@ PJ_DECL(pj_status_t) pj_json_writef(const pj_json_elem *elem, PJ_END_DECL -#endif /* __PJLIB_UTIL_JSON_H__ */ +#endif /* __PJLIB_UTIL_JSON_H__ */ diff --git a/pjlib-util/include/pjlib-util/md5.h b/pjlib-util/include/pjlib-util/md5.h index f8c68be8b8..219f52bfe3 100644 --- a/pjlib-util/include/pjlib-util/md5.h +++ b/pjlib-util/include/pjlib-util/md5.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,27 +38,27 @@ PJ_BEGIN_DECL /** MD5 context. */ typedef struct pj_md5_context { - pj_uint32_t buf[4]; /**< buf */ - pj_uint32_t bits[2]; /**< bits */ - pj_uint8_t in[64]; /**< in */ + pj_uint32_t buf[4]; /**< buf */ + pj_uint32_t bits[2]; /**< bits */ + pj_uint8_t in[64]; /**< in */ } pj_md5_context; /** Initialize the algorithm. - * @param pms MD5 context. + * @param pms MD5 context. */ PJ_DECL(void) pj_md5_init(pj_md5_context *pms); /** Append a string to the message. - * @param pms MD5 context. - * @param data Data. - * @param nbytes Length of data. + * @param pms MD5 context. + * @param data Data. + * @param nbytes Length of data. */ PJ_DECL(void) pj_md5_update( pj_md5_context *pms, - const pj_uint8_t *data, unsigned nbytes); + const pj_uint8_t *data, unsigned nbytes); /** Finish the message and return the digest. - * @param pms MD5 context. - * @param digest 16 byte digest. + * @param pms MD5 context. + * @param digest 16 byte digest. */ PJ_DECL(void) pj_md5_final(pj_md5_context *pms, pj_uint8_t digest[16]); @@ -71,4 +70,4 @@ PJ_DECL(void) pj_md5_final(pj_md5_context *pms, pj_uint8_t digest[16]); PJ_END_DECL -#endif /* __PJLIB_UTIL_MD5_H__ */ +#endif /* __PJLIB_UTIL_MD5_H__ */ diff --git a/pjlib-util/include/pjlib-util/pcap.h b/pjlib-util/include/pjlib-util/pcap.h index d6283dc248..4e127b0494 100644 --- a/pjlib-util/include/pjlib-util/pcap.h +++ b/pjlib-util/include/pjlib-util/pcap.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -66,10 +65,10 @@ typedef enum pj_pcap_proto_type */ typedef struct pj_pcap_udp_hdr { - pj_uint16_t src_port; /**< Source port. */ - pj_uint16_t dst_port; /**< Destination port */ - pj_uint16_t len; /**< Length. */ - pj_uint16_t csum; /**< Checksum. */ + pj_uint16_t src_port; /**< Source port. */ + pj_uint16_t dst_port; /**< Destination port */ + pj_uint16_t len; /**< Length. */ + pj_uint16_t csum; /**< Checksum. */ } pj_pcap_udp_hdr; @@ -83,40 +82,40 @@ typedef struct pj_pcap_filter /** * Select data link type, or zero to include any supported data links. */ - pj_pcap_link_type link; + pj_pcap_link_type link; /** * Select protocol, or zero to include all supported protocols. */ - pj_pcap_proto_type proto; + pj_pcap_proto_type proto; /** * Specify source IP address of the packets, or zero to include packets * from any IP addresses. Note that IP address here must be in * network byte order. */ - pj_uint32_t ip_src; + pj_uint32_t ip_src; /** * Specify destination IP address of the packets, or zero to include packets * destined to any IP addresses. Note that IP address here must be in * network byte order. */ - pj_uint32_t ip_dst; + pj_uint32_t ip_dst; /** * Specify source port of the packets, or zero to include packets with * any source port number. Note that the port number must be in network * byte order. */ - pj_uint16_t src_port; + pj_uint16_t src_port; /** * Specify destination port of the packets, or zero to include packets with * any destination port number. Note that the port number must be in network * byte order. */ - pj_uint16_t dst_port; + pj_uint16_t dst_port; } pj_pcap_filter; @@ -136,22 +135,22 @@ PJ_DECL(void) pj_pcap_filter_default(pj_pcap_filter *filter); /** * Open PCAP file. * - * @param pool Pool to allocate memory. - * @param path File/path name. + * @param pool Pool to allocate memory. + * @param path File/path name. * @param p_file Pointer to receive PCAP file handle. * - * @return PJ_SUCCESS if file can be opened successfully. + * @return PJ_SUCCESS if file can be opened successfully. */ PJ_DECL(pj_status_t) pj_pcap_open(pj_pool_t *pool, - const char *path, - pj_pcap_file **p_file); + const char *path, + pj_pcap_file **p_file); /** * Close PCAP file. * - * @param file PCAP file handle. + * @param file PCAP file handle. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_pcap_close(pj_pcap_file *file); @@ -159,31 +158,31 @@ PJ_DECL(pj_status_t) pj_pcap_close(pj_pcap_file *file); * Configure filter for reading the file. When filter is configured, * only packets matching all the filter settings will be returned. * - * @param file PCAP file handle. + * @param file PCAP file handle. * @param filter The filter. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_pcap_set_filter(pj_pcap_file *file, - const pj_pcap_filter *filter); + const pj_pcap_filter *filter); /** * Read UDP payload from the next packet in the PCAP file. Optionally it * can return the UDP header, if caller supplies it. * - * @param file PCAP file handle. - * @param udp_hdr Optional buffer to receive UDP header. - * @param udp_payload Buffer to receive the UDP payload. + * @param file PCAP file handle. + * @param udp_hdr Optional buffer to receive UDP header. + * @param udp_payload Buffer to receive the UDP payload. * @param udp_payload_size On input, specify the size of the buffer. - * On output, it will be filled with the actual size - * of the payload as read from the packet. + * On output, it will be filled with the actual size + * of the payload as read from the packet. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_pcap_read_udp(pj_pcap_file *file, - pj_pcap_udp_hdr *udp_hdr, - pj_uint8_t *udp_payload, - pj_size_t *udp_payload_size); + pj_pcap_udp_hdr *udp_hdr, + pj_uint8_t *udp_payload, + pj_size_t *udp_payload_size); /** @@ -192,5 +191,5 @@ PJ_DECL(pj_status_t) pj_pcap_read_udp(pj_pcap_file *file, PJ_END_DECL -#endif /* __PJLIB_UTIL_PCAP_H__ */ +#endif /* __PJLIB_UTIL_PCAP_H__ */ diff --git a/pjlib-util/include/pjlib-util/resolver.h b/pjlib-util/include/pjlib-util/resolver.h index fa22d0463b..5ea01aca73 100644 --- a/pjlib-util/include/pjlib-util/resolver.h +++ b/pjlib-util/include/pjlib-util/resolver.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -173,15 +172,15 @@ typedef struct pj_dns_async_query pj_dns_async_query; * Type of asynchronous callback which will be called when the asynchronous * query completes. * - * @param user_data The user data set by application when creating the - * asynchronous query. - * @param status Status of the DNS resolution. - * @param response The response packet received from the server. This - * argument may be NULL when status is not PJ_SUCCESS. + * @param user_data The user data set by application when creating the + * asynchronous query. + * @param status Status of the DNS resolution. + * @param response The response packet received from the server. This + * argument may be NULL when status is not PJ_SUCCESS. */ typedef void pj_dns_callback(void *user_data, - pj_status_t status, - pj_dns_parsed_packet *response); + pj_status_t status, + pj_dns_parsed_packet *response); /** @@ -189,13 +188,13 @@ typedef void pj_dns_callback(void *user_data, */ typedef struct pj_dns_settings { - unsigned options; /**< Options flags. */ - unsigned qretr_delay; /**< Query retransmit delay in msec. */ - unsigned qretr_count; /**< Query maximum retransmission count. */ - unsigned cache_max_ttl; /**< Maximum TTL for cached responses. If the - value is zero, caching is disabled. */ - unsigned good_ns_ttl; /**< See #PJ_DNS_RESOLVER_GOOD_NS_TTL */ - unsigned bad_ns_ttl; /**< See #PJ_DNS_RESOLVER_BAD_NS_TTL */ + unsigned options; /**< Options flags. */ + unsigned qretr_delay; /**< Query retransmit delay in msec. */ + unsigned qretr_count; /**< Query maximum retransmission count. */ + unsigned cache_max_ttl; /**< Maximum TTL for cached responses. If the + value is zero, caching is disabled. */ + unsigned good_ns_ttl; /**< See #PJ_DNS_RESOLVER_GOOD_NS_TTL */ + unsigned bad_ns_ttl; /**< See #PJ_DNS_RESOLVER_BAD_NS_TTL */ } pj_dns_settings; @@ -206,21 +205,21 @@ typedef struct pj_dns_settings typedef struct pj_dns_a_record { /** The target name being queried. */ - pj_str_t name; + pj_str_t name; /** If target name corresponds to a CNAME entry, the alias contains * the value of the CNAME entry, otherwise it will be empty. */ - pj_str_t alias; + pj_str_t alias; /** Number of IP addresses. */ - unsigned addr_count; + unsigned addr_count; /** IP addresses of the host found in the response */ - pj_in_addr addr[PJ_DNS_MAX_IP_IN_A_REC]; + pj_in_addr addr[PJ_DNS_MAX_IP_IN_A_REC]; /** Internal buffer for hostname and alias. */ - char buf_[128]; + char buf_[128]; } pj_dns_a_record; @@ -233,35 +232,35 @@ typedef struct pj_dns_a_record typedef struct pj_dns_addr_record { /** The target name being queried. */ - pj_str_t name; + pj_str_t name; /** If target name corresponds to a CNAME entry, the alias contains * the value of the CNAME entry, otherwise it will be empty. */ - pj_str_t alias; + pj_str_t alias; /** Number of IP addresses. */ - unsigned addr_count; + unsigned addr_count; /** IP addresses of the host found in the response */ struct { - /** IP address family */ - int af; - - /** IP address */ - union { - /** IPv4 address */ - pj_in_addr v4; + /** IP address family */ + int af; + + /** IP address */ + union { + /** IPv4 address */ + pj_in_addr v4; - /** IPv6 address */ - pj_in6_addr v6; - } ip; + /** IPv6 address */ + pj_in6_addr v6; + } ip; } addr[PJ_DNS_MAX_IP_IN_A_REC]; /** Internal buffer for hostname and alias. */ - char buf_[128]; + char buf_[128]; } pj_dns_addr_record; @@ -269,7 +268,7 @@ typedef struct pj_dns_addr_record /** * Set default values to the DNS settings. * - * @param s The DNS settings to be initialized. + * @param s The DNS settings to be initialized. */ PJ_DECL(void) pj_dns_settings_default(pj_dns_settings *s); @@ -282,28 +281,28 @@ PJ_DECL(void) pj_dns_settings_default(pj_dns_settings *s); * and ioqueue instance, so that it doesn't need to poll the resolver * periodically. * - * @param pf Pool factory where the memory pool will be created from. - * @param name Optional resolver name to identify the instance in - * the log. + * @param pf Pool factory where the memory pool will be created from. + * @param name Optional resolver name to identify the instance in + * the log. * @param options Optional options, must be zero for now. - * @param timer Optional timer heap instance to be used by the resolver. - * If timer heap is not specified, an internal timer will be - * created, and application would need to poll the resolver - * periodically. + * @param timer Optional timer heap instance to be used by the resolver. + * If timer heap is not specified, an internal timer will be + * created, and application would need to poll the resolver + * periodically. * @param ioqueue Optional I/O Queue instance to be used by the resolver. - * If ioqueue is not specified, an internal one will be - * created, and application would need to poll the resolver - * periodically. + * If ioqueue is not specified, an internal one will be + * created, and application would need to poll the resolver + * periodically. * @param p_resolver Pointer to receive the resolver instance. * - * @return PJ_SUCCESS on success, or the appropriate error code, + * @return PJ_SUCCESS on success, or the appropriate error code, */ PJ_DECL(pj_status_t) pj_dns_resolver_create(pj_pool_factory *pf, - const char *name, - unsigned options, - pj_timer_heap_t *timer, - pj_ioqueue_t *ioqueue, - pj_dns_resolver **p_resolver); + const char *name, + unsigned options, + pj_timer_heap_t *timer, + pj_ioqueue_t *ioqueue, + pj_dns_resolver **p_resolver); /** @@ -315,29 +314,29 @@ PJ_DECL(pj_status_t) pj_dns_resolver_create(pj_pool_factory *pf, * @param resolver The resolver instance. * @param count Number of name servers in the array. * @param servers Array of name server IP addresses or hostnames. If - * hostname is specified, the hostname must be resolvable - * with pj_gethostbyname(). - * @param ports Optional array of ports. If this argument is NULL, - * the nameserver will use default port. + * hostname is specified, the hostname must be resolvable + * with pj_gethostbyname(). + * @param ports Optional array of ports. If this argument is NULL, + * the nameserver will use default port. * - * @return PJ_SUCCESS on success, or the appropriate error code, + * @return PJ_SUCCESS on success, or the appropriate error code, */ PJ_DECL(pj_status_t) pj_dns_resolver_set_ns(pj_dns_resolver *resolver, - unsigned count, - const pj_str_t servers[], - const pj_uint16_t ports[]); + unsigned count, + const pj_str_t servers[], + const pj_uint16_t ports[]); /** * Get the resolver current settings. * * @param resolver The resolver instance. - * @param st Buffer to be filled up with resolver settings. + * @param st Buffer to be filled up with resolver settings. * - * @return The query timeout setting, in seconds. + * @return The query timeout setting, in seconds. */ PJ_DECL(pj_status_t) pj_dns_resolver_get_settings(pj_dns_resolver *resolver, - pj_dns_settings *st); + pj_dns_settings *st); /** @@ -346,12 +345,12 @@ PJ_DECL(pj_status_t) pj_dns_resolver_get_settings(pj_dns_resolver *resolver, * ensure that all fields are initialized properly. * * @param resolver The resolver instance. - * @param st The resolver settings. + * @param st The resolver settings. * - * @return PJ_SUCCESS on success, or the appropriate error code, + * @return PJ_SUCCESS on success, or the appropriate error code, */ PJ_DECL(pj_status_t) pj_dns_resolver_set_settings(pj_dns_resolver *resolver, - const pj_dns_settings *st); + const pj_dns_settings *st); /** @@ -362,11 +361,11 @@ PJ_DECL(pj_status_t) pj_dns_resolver_set_settings(pj_dns_resolver *resolver, * * @param resolver The resolver instance. * @param timeout Maximum time to wait for event occurence. If this - * argument is NULL, this function will wait forever - * until events occur. + * argument is NULL, this function will wait forever + * until events occur. */ PJ_DECL(void) pj_dns_resolver_handle_events(pj_dns_resolver *resolver, - const pj_time_val *timeout); + const pj_time_val *timeout); /** @@ -374,13 +373,13 @@ PJ_DECL(void) pj_dns_resolver_handle_events(pj_dns_resolver *resolver, * * @param resolver The resolver object to be destryed * @param notify If non-zero, all pending asynchronous queries will be - * cancelled and its callback will be called. If FALSE, - * then no callback will be called. + * cancelled and its callback will be called. If FALSE, + * then no callback will be called. * - * @return PJ_SUCCESS on success, or the appropriate error code, + * @return PJ_SUCCESS on success, or the appropriate error code, */ PJ_DECL(pj_status_t) pj_dns_resolver_destroy(pj_dns_resolver *resolver, - pj_bool_t notify); + pj_bool_t notify); /** @@ -399,68 +398,68 @@ PJ_DECL(pj_status_t) pj_dns_resolver_destroy(pj_dns_resolver *resolver, * is started. * * @param resolver The resolver object. - * @param name The name to be resolved. - * @param type The type of resource (see #pj_dns_type constants). + * @param name The name to be resolved. + * @param type The type of resource (see #pj_dns_type constants). * @param options Optional options, must be zero for now. - * @param cb Callback to be called when the query completes, - * either successfully or with failure. + * @param cb Callback to be called when the query completes, + * either successfully or with failure. * @param user_data Arbitrary user data to be associated with the query, - * and which will be given back in the callback. + * and which will be given back in the callback. * @param p_query Optional pointer to receive the query object, if one - * was started. If this pointer is specified, a NULL may - * be returned if response cache is available immediately. + * was started. If this pointer is specified, a NULL may + * be returned if response cache is available immediately. * - * @return PJ_SUCCESS if either an asynchronous query has been - * started successfully or response cache is available and - * the user callback has been called. + * @return PJ_SUCCESS if either an asynchronous query has been + * started successfully or response cache is available and + * the user callback has been called. */ PJ_DECL(pj_status_t) pj_dns_resolver_start_query(pj_dns_resolver *resolver, - const pj_str_t *name, - int type, - unsigned options, - pj_dns_callback *cb, - void *user_data, - pj_dns_async_query **p_query); + const pj_str_t *name, + int type, + unsigned options, + pj_dns_callback *cb, + void *user_data, + pj_dns_async_query **p_query); /** * Cancel a pending query. * - * @param query The pending asynchronous query to be cancelled. + * @param query The pending asynchronous query to be cancelled. * @param notify If non-zero, the callback will be called with failure - * status to notify that the query has been cancelled. + * status to notify that the query has been cancelled. * - * @return PJ_SUCCESS on success, or the appropriate error code, + * @return PJ_SUCCESS on success, or the appropriate error code, */ PJ_DECL(pj_status_t) pj_dns_resolver_cancel_query(pj_dns_async_query *query, - pj_bool_t notify); + pj_bool_t notify); /** * A utility function to parse a DNS response containing A records into * DNS A record. * - * @param pkt The DNS response packet. - * @param rec The structure to be initialized with the parsed - * DNS A record from the packet. + * @param pkt The DNS response packet. + * @param rec The structure to be initialized with the parsed + * DNS A record from the packet. * - * @return PJ_SUCCESS if response can be parsed successfully. + * @return PJ_SUCCESS if response can be parsed successfully. */ PJ_DECL(pj_status_t) pj_dns_parse_a_response(const pj_dns_parsed_packet *pkt, - pj_dns_a_record *rec); + pj_dns_a_record *rec); /** * A utility function to parse a DNS response containing AAAA records into * DNS AAAA record. * - * @param pkt The DNS response packet. - * @param rec The structure to be initialized with the parsed - * DNS AAAA record from the packet. + * @param pkt The DNS response packet. + * @param rec The structure to be initialized with the parsed + * DNS AAAA record from the packet. * - * @return PJ_SUCCESS if response can be parsed successfully. + * @return PJ_SUCCESS if response can be parsed successfully. */ PJ_DECL(pj_status_t) pj_dns_parse_addr_response( - const pj_dns_parsed_packet *pkt, - pj_dns_addr_record *rec); + const pj_dns_parsed_packet *pkt, + pj_dns_addr_record *rec); /** @@ -472,25 +471,25 @@ PJ_DECL(pj_status_t) pj_dns_parse_addr_response( * it can be indexed. * * @param resolver The resolver instance. - * @param pkt DNS packet to be added to the DNS cache. If the packet - * matches existing entry, it will update the entry. + * @param pkt DNS packet to be added to the DNS cache. If the packet + * matches existing entry, it will update the entry. * @param set_ttl If the value is PJ_FALSE, the entry will not expire - * (so use with care). Otherwise cache expiration will be - * calculated based on the TTL of the answeres. + * (so use with care). Otherwise cache expiration will be + * calculated based on the TTL of the answeres. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_dns_resolver_add_entry(pj_dns_resolver *resolver, - const pj_dns_parsed_packet *pkt, - pj_bool_t set_ttl); + const pj_dns_parsed_packet *pkt, + pj_bool_t set_ttl); /** * Get the total number of response in the response cache. * * @param resolver The resolver instance. * - * @return Current number of entries being stored in the response - * cache. + * @return Current number of entries being stored in the response + * cache. */ PJ_DECL(unsigned) pj_dns_resolver_get_cached_count(pj_dns_resolver *resolver); @@ -502,7 +501,7 @@ PJ_DECL(unsigned) pj_dns_resolver_get_cached_count(pj_dns_resolver *resolver); * @param detail Will print detailed entries. */ PJ_DECL(void) pj_dns_resolver_dump(pj_dns_resolver *resolver, - pj_bool_t detail); + pj_bool_t detail); /** @@ -512,5 +511,5 @@ PJ_DECL(void) pj_dns_resolver_dump(pj_dns_resolver *resolver, PJ_END_DECL -#endif /* __PJLIB_UTIL_RESOLVER_H__ */ +#endif /* __PJLIB_UTIL_RESOLVER_H__ */ diff --git a/pjlib-util/include/pjlib-util/scanner.h b/pjlib-util/include/pjlib-util/scanner.h index 1588d5417a..72e515e28e 100644 --- a/pjlib-util/include/pjlib-util/scanner.h +++ b/pjlib-util/include/pjlib-util/scanner.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -111,8 +110,8 @@ PJ_DECL(void) pj_cis_add_str( pj_cis_t *cis, const char *str); /** * Add specification from another specification. * - * @param cis The specification is to be set. - * @param rhs The specification to be copied. + * @param cis The specification is to be set. + * @param rhs The specification to be copied. */ PJ_DECL(void) pj_cis_add_cis( pj_cis_t *cis, const pj_cis_t *rhs); @@ -146,7 +145,7 @@ PJ_DECL(void) pj_cis_invert( pj_cis_t *cis ); * @param cis The scanner character specification. * @param c The character to check for matching. * - * @return Non-zero if match (not necessarily one). + * @return Non-zero if match (not necessarily one). */ PJ_INLINE(int) pj_cis_match( const pj_cis_t *cis, pj_uint8_t c ) { @@ -160,7 +159,7 @@ PJ_INLINE(int) pj_cis_match( const pj_cis_t *cis, pj_uint8_t c ) enum { /** This flags specifies that the scanner should automatically skip - whitespaces + whitespaces */ PJ_SCAN_AUTOSKIP_WS = 1, @@ -193,12 +192,12 @@ typedef void (*pj_syn_err_func_ptr)(struct pj_scanner *scanner); */ typedef struct pj_scanner { - char *begin; /**< Start of input buffer. */ - char *end; /**< End of input buffer. */ - char *curptr; /**< Current pointer. */ - int line; /**< Current line. */ - char *start_line; /**< Where current line starts. */ - int skip_ws; /**< Skip whitespace flag. */ + char *begin; /**< Start of input buffer. */ + char *end; /**< End of input buffer. */ + char *curptr; /**< Current pointer. */ + int line; /**< Current line. */ + char *start_line; /**< Where current line starts. */ + int skip_ws; /**< Skip whitespace flag. */ pj_syn_err_func_ptr callback; /**< Syntax error callback. */ } pj_scanner; @@ -210,8 +209,8 @@ typedef struct pj_scanner typedef struct pj_scan_state { char *curptr; /**< Current scanner's pointer. */ - int line; /**< Current line. */ - char *start_line; /**< Start of current line. */ + int line; /**< Current line. */ + char *start_line; /**< Start of current line. */ } pj_scan_state; @@ -223,16 +222,16 @@ typedef struct pj_scan_state * @param scanner The scanner to be initialized. * @param bufstart The input buffer to scan, which must be NULL terminated. * @param buflen The length of the input buffer, which normally is - * strlen(bufstart), hence not counting the NULL terminator. + * strlen(bufstart), hence not counting the NULL terminator. * @param options Zero, or combination of PJ_SCAN_AUTOSKIP_WS or - * PJ_SCAN_AUTOSKIP_WS_HEADER + * PJ_SCAN_AUTOSKIP_WS_HEADER * @param callback Callback to be called when the scanner encounters syntax - * error condition. + * error condition. */ PJ_DECL(void) pj_scan_init( pj_scanner *scanner, char *bufstart, - pj_size_t buflen, - unsigned options, - pj_syn_err_func_ptr callback ); + pj_size_t buflen, + unsigned options, + pj_syn_err_func_ptr callback ); /** @@ -263,14 +262,14 @@ PJ_INLINE(int) pj_scan_is_eof( const pj_scanner *scanner) * be called thrown. * * @param scanner The scanner. - * @param spec The spec to match input string. - * @param out String to store the result. + * @param spec The spec to match input string. + * @param out String to store the result. * * @return the character right after the peek-ed position or zero if there's - * no more characters. + * no more characters. */ PJ_DECL(int) pj_scan_peek( pj_scanner *scanner, - const pj_cis_t *spec, pj_str_t *out); + const pj_cis_t *spec, pj_str_t *out); /** @@ -280,14 +279,14 @@ PJ_DECL(int) pj_scan_peek( pj_scanner *scanner, * syntax error callback will be called. * * @param scanner The scanner. - * @param len Length to peek. - * @param out String to store the result. + * @param len Length to peek. + * @param out String to store the result. * * @return the character right after the peek-ed position or zero if there's - * no more characters. + * no more characters. */ PJ_DECL(int) pj_scan_peek_n( pj_scanner *scanner, - pj_size_t len, pj_str_t *out); + pj_size_t len, pj_str_t *out); /** @@ -297,14 +296,14 @@ PJ_DECL(int) pj_scan_peek_n( pj_scanner *scanner, * be called. * * @param scanner The scanner. - * @param spec The peeking will stop when the input match this spec. - * @param out String to store the result. + * @param spec The peeking will stop when the input match this spec. + * @param out String to store the result. * * @return the character right after the peek-ed position. */ PJ_DECL(int) pj_scan_peek_until( pj_scanner *scanner, - const pj_cis_t *spec, - pj_str_t *out); + const pj_cis_t *spec, + pj_str_t *out); /** @@ -315,11 +314,11 @@ PJ_DECL(int) pj_scan_peek_until( pj_scanner *scanner, * an exception will be thrown. * * @param scanner The scanner. - * @param spec The spec to match input string. - * @param out String to store the result. + * @param spec The spec to match input string. + * @param out String to store the result. */ PJ_DECL(void) pj_scan_get( pj_scanner *scanner, - const pj_cis_t *spec, pj_str_t *out); + const pj_cis_t *spec, pj_str_t *out); /** @@ -328,11 +327,11 @@ PJ_DECL(void) pj_scan_get( pj_scanner *scanner, * specification for '%' characted. * * @param scanner The scanner. - * @param spec The spec to match input string. - * @param out String to store the result. + * @param spec The spec to match input string. + * @param out String to store the result. */ PJ_DECL(void) pj_scan_get_unescape( pj_scanner *scanner, - const pj_cis_t *spec, pj_str_t *out); + const pj_cis_t *spec, pj_str_t *out); /** @@ -340,21 +339,21 @@ PJ_DECL(void) pj_scan_get_unescape( pj_scanner *scanner, * syntax error will be thrown. Note that the resulting string will contain * the enclosing quote. * - * @param scanner The scanner. - * @param begin_quote The character to begin the quote. - * @param end_quote The character to end the quote. - * @param out String to store the result. + * @param scanner The scanner. + * @param begin_quote The character to begin the quote. + * @param end_quote The character to end the quote. + * @param out String to store the result. */ PJ_DECL(void) pj_scan_get_quote( pj_scanner *scanner, - int begin_quote, int end_quote, - pj_str_t *out); + int begin_quote, int end_quote, + pj_str_t *out); /** * Get characters between quotes. If current input doesn't match begin_quote, * syntax error will be thrown. Note that the resulting string will contain * the enclosing quote. * - * @param scanner The scanner. + * @param scanner The scanner. * @param begin_quotes The character array to begin the quotes. For example, * the two characters " and '. * @param end_quotes The character array to end the quotes. The position @@ -376,11 +375,11 @@ PJ_DECL(void) pj_scan_get_quotes(pj_scanner *scanner, * Get N characters from the scanner. * * @param scanner The scanner. - * @param N Number of characters to get. - * @param out String to store the result. + * @param N Number of characters to get. + * @param out String to store the result. */ PJ_DECL(void) pj_scan_get_n( pj_scanner *scanner, - unsigned N, pj_str_t *out); + unsigned N, pj_str_t *out); /** @@ -398,55 +397,55 @@ PJ_DECL(int) pj_scan_get_char( pj_scanner *scanner ); * current character matches the spec. * * @param scanner The scanner. - * @param spec Get until the input match this spec. - * @param out String to store the result. + * @param spec Get until the input match this spec. + * @param out String to store the result. */ PJ_DECL(void) pj_scan_get_until( pj_scanner *scanner, - const pj_cis_t *spec, pj_str_t *out); + const pj_cis_t *spec, pj_str_t *out); /** * Get characters from the scanner and move the scanner position until the * current character matches until_char. * - * @param scanner The scanner. + * @param scanner The scanner. * @param until_char Get until the input match this character. - * @param out String to store the result. + * @param out String to store the result. */ PJ_DECL(void) pj_scan_get_until_ch( pj_scanner *scanner, - int until_char, pj_str_t *out); + int until_char, pj_str_t *out); /** * Get characters from the scanner and move the scanner position until the * current character matches until_char. * - * @param scanner The scanner. - * @param until_spec Get until the input match any of these characters. - * @param out String to store the result. + * @param scanner The scanner. + * @param until_spec Get until the input match any of these characters. + * @param out String to store the result. */ PJ_DECL(void) pj_scan_get_until_chr( pj_scanner *scanner, - const char *until_spec, pj_str_t *out); + const char *until_spec, pj_str_t *out); /** * Advance the scanner N characters, and skip whitespace * if necessary. * * @param scanner The scanner. - * @param N Number of characters to skip. - * @param skip Flag to specify whether whitespace should be skipped - * after skipping the characters. + * @param N Number of characters to skip. + * @param skip Flag to specify whether whitespace should be skipped + * after skipping the characters. */ PJ_DECL(void) pj_scan_advance_n( pj_scanner *scanner, - unsigned N, pj_bool_t skip); + unsigned N, pj_bool_t skip); /** * Compare string in current position with the specified string. * * @param scanner The scanner. - * @param s The string to compare with. - * @param len Length of the string to compare. + * @param s The string to compare with. + * @param len Length of the string to compare. * * @return zero, <0, or >0 (just like strcmp()). */ @@ -458,8 +457,8 @@ PJ_DECL(int) pj_scan_strcmp( pj_scanner *scanner, const char *s, int len); * string. * * @param scanner The scanner. - * @param s The string to compare with. - * @param len Length of the string to compare with. + * @param s The string to compare with. + * @param len Length of the string to compare with. * * @return zero, <0, or >0 (just like strcmp()). */ @@ -474,15 +473,15 @@ PJ_DECL(int) pj_scan_stricmp( pj_scanner *scanner, const char *s, int len); * -1. * * @param scanner The scanner. - * @param s The string to compare with. - * @param len Length of the string to compare with. + * @param s The string to compare with. + * @param len Length of the string to compare with. * - * @return zero if equal or -1. + * @return zero if equal or -1. * * @see strnicmp_alnum, pj_stricmp_alnum */ PJ_DECL(int) pj_scan_stricmp_alnum( pj_scanner *scanner, const char *s, - int len); + int len); /** @@ -514,10 +513,10 @@ PJ_DECL(void) pj_scan_skip_line( pj_scanner *scanner ); * Save the full scanner state. * * @param scanner The scanner. - * @param state Variable to store scanner's state. + * @param state Variable to store scanner's state. */ PJ_DECL(void) pj_scan_save_state( const pj_scanner *scanner, - pj_scan_state *state); + pj_scan_state *state); /** @@ -526,17 +525,17 @@ PJ_DECL(void) pj_scan_save_state( const pj_scanner *scanner, * it. This will only restore the scanner scanning position. * * @param scanner The scanner. - * @param state State of the scanner. + * @param state State of the scanner. */ PJ_DECL(void) pj_scan_restore_state( pj_scanner *scanner, - pj_scan_state *state); + pj_scan_state *state); /** * Get current column position. * * @param scanner The scanner. * - * @return The column position. + * @return The column position. */ PJ_INLINE(int) pj_scan_get_col( const pj_scanner *scanner ) { diff --git a/pjlib-util/include/pjlib-util/scanner_cis_bitwise.h b/pjlib-util/include/pjlib-util/scanner_cis_bitwise.h index a0d3a2c7c3..c706cc489e 100644 --- a/pjlib-util/include/pjlib-util/scanner_cis_bitwise.h +++ b/pjlib-util/include/pjlib-util/scanner_cis_bitwise.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -94,4 +93,4 @@ typedef struct pj_cis_t PJ_END_DECL -#endif /* __PJLIB_UTIL_SCANNER_CIS_BIT_H__ */ +#endif /* __PJLIB_UTIL_SCANNER_CIS_BIT_H__ */ diff --git a/pjlib-util/include/pjlib-util/scanner_cis_uint.h b/pjlib-util/include/pjlib-util/scanner_cis_uint.h index 0bd8759f55..277df3bd94 100644 --- a/pjlib-util/include/pjlib-util/scanner_cis_uint.h +++ b/pjlib-util/include/pjlib-util/scanner_cis_uint.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,7 +45,7 @@ typedef int pj_cis_buf_t; */ typedef struct pj_cis_t { - PJ_CIS_ELEM_TYPE cis_buf[256]; /**< Internal buffer. */ + PJ_CIS_ELEM_TYPE cis_buf[256]; /**< Internal buffer. */ } pj_cis_t; @@ -81,4 +80,4 @@ typedef struct pj_cis_t PJ_END_DECL -#endif /* __PJLIB_UTIL_SCANNER_CIS_BIT_H__ */ +#endif /* __PJLIB_UTIL_SCANNER_CIS_BIT_H__ */ diff --git a/pjlib-util/include/pjlib-util/sha1.h b/pjlib-util/include/pjlib-util/sha1.h index 7529a7b30a..8ebceb5843 100644 --- a/pjlib-util/include/pjlib-util/sha1.h +++ b/pjlib-util/include/pjlib-util/sha1.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,35 +37,35 @@ PJ_BEGIN_DECL /** SHA1 context */ typedef struct pj_sha1_context { - pj_uint32_t state[5]; /**< State */ - pj_uint32_t count[2]; /**< Count */ - pj_uint8_t buffer[64]; /**< Buffer */ + pj_uint32_t state[5]; /**< State */ + pj_uint32_t count[2]; /**< Count */ + pj_uint8_t buffer[64]; /**< Buffer */ } pj_sha1_context; /** SHA1 digest size is 20 bytes */ -#define PJ_SHA1_DIGEST_SIZE 20 +#define PJ_SHA1_DIGEST_SIZE 20 /** Initialize the algorithm. - * @param ctx SHA1 context. + * @param ctx SHA1 context. */ PJ_DECL(void) pj_sha1_init(pj_sha1_context *ctx); /** Append a stream to the message. - * @param ctx SHA1 context. - * @param data Data. - * @param nbytes Length of data. + * @param ctx SHA1 context. + * @param data Data. + * @param nbytes Length of data. */ PJ_DECL(void) pj_sha1_update(pj_sha1_context *ctx, - const pj_uint8_t *data, - const pj_size_t nbytes); + const pj_uint8_t *data, + const pj_size_t nbytes); /** Finish the message and return the digest. - * @param ctx SHA1 context. - * @param digest 16 byte digest. + * @param ctx SHA1 context. + * @param digest 16 byte digest. */ PJ_DECL(void) pj_sha1_final(pj_sha1_context *ctx, - pj_uint8_t digest[PJ_SHA1_DIGEST_SIZE]); + pj_uint8_t digest[PJ_SHA1_DIGEST_SIZE]); /** @@ -76,5 +75,5 @@ PJ_DECL(void) pj_sha1_final(pj_sha1_context *ctx, PJ_END_DECL -#endif /* __PJLIB_UTIL_SHA1_H__ */ +#endif /* __PJLIB_UTIL_SHA1_H__ */ diff --git a/pjlib-util/include/pjlib-util/srv_resolver.h b/pjlib-util/include/pjlib-util/srv_resolver.h index bcaf98438e..1f92cb588d 100644 --- a/pjlib-util/include/pjlib-util/srv_resolver.h +++ b/pjlib-util/include/pjlib-util/srv_resolver.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -72,7 +71,7 @@ PJ_BEGIN_DECL * * Reference: * - RFC 2782: - * A DNS RR for specifying the location of services (DNS SRV) + * A DNS RR for specifying the location of services (DNS SRV) */ /** @@ -87,7 +86,7 @@ typedef enum pj_dns_srv_option * make the resolver fallback to both DNS A and DNS AAAA * resolutions if SRV resolution fails. */ - PJ_DNS_SRV_FALLBACK_A = 1, + PJ_DNS_SRV_FALLBACK_A = 1, /** * Specify if the resolver should fallback with DNS AAAA @@ -96,7 +95,7 @@ typedef enum pj_dns_srv_option * make the resolver fallback to both DNS A and DNS AAAA * resolutions if SRV resolution fails. */ - PJ_DNS_SRV_FALLBACK_AAAA = 2, + PJ_DNS_SRV_FALLBACK_AAAA = 2, /** * Specify if the resolver should try to resolve with DNS AAAA @@ -104,7 +103,7 @@ typedef enum pj_dns_srv_option * option is not specified, the SRV resolver will query the * DNS A record for the target instead. */ - PJ_DNS_SRV_RESOLVE_AAAA = 4, + PJ_DNS_SRV_RESOLVE_AAAA = 4, /** * Specify if the resolver should try to resolve with DNS AAAA @@ -123,22 +122,22 @@ typedef enum pj_dns_srv_option typedef struct pj_dns_srv_record { /** Number of address records. */ - unsigned count; + unsigned count; /** Address records. */ struct { - /** Server priority (the lower the higher the priority). */ - unsigned priority; + /** Server priority (the lower the higher the priority). */ + unsigned priority; - /** Server weight (the higher the more load it can handle). */ - unsigned weight; + /** Server weight (the higher the more load it can handle). */ + unsigned weight; - /** Port number. */ - pj_uint16_t port; + /** Port number. */ + pj_uint16_t port; - /** The host address. */ - pj_dns_addr_record server; + /** The host address. */ + pj_dns_addr_record server; } entry[PJ_DNS_SRV_MAX_ADDR]; @@ -153,62 +152,62 @@ typedef struct pj_dns_srv_async_query pj_dns_srv_async_query; * when the resolution process completes. */ typedef void pj_dns_srv_resolver_cb(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec); + pj_status_t status, + const pj_dns_srv_record *rec); /** * Start DNS SRV resolution for the specified name. The full name of the * entry will be concatenated from \a res_name and \a domain_name fragments. * - * @param domain_name The domain name part of the name. - * @param res_name The full service name, including the transport name - * and with all the leading underscore characters and - * ending dot (e.g. "_sip._udp.", "_stun._udp."). - * @param def_port The port number to be assigned to the resolved address - * when the DNS SRV resolution fails and the name is - * resolved with DNS A resolution. - * @param pool Memory pool used to allocate memory for the query. - * @param resolver The resolver instance. - * @param option Option flags, which can be constructed from - * #pj_dns_srv_option bitmask. Note that this argument - * was called "fallback_a" in pjsip version 0.8.0 and - * older, but the new option should be backward - * compatible with existing applications. If application - * specifies PJ_TRUE as "fallback_a" value, it will - * correspond to PJ_DNS_SRV_FALLBACK_A option. - * @param token Arbitrary data to be associated with this query when - * the calback is called. - * @param cb Pointer to callback function to receive the - * notification when the resolution process completes. - * @param p_query Optional pointer to receive the query object, if one - * was started. If this pointer is specified, a NULL may - * be returned if response cache is available immediately. - * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @param domain_name The domain name part of the name. + * @param res_name The full service name, including the transport name + * and with all the leading underscore characters and + * ending dot (e.g. "_sip._udp.", "_stun._udp."). + * @param def_port The port number to be assigned to the resolved address + * when the DNS SRV resolution fails and the name is + * resolved with DNS A resolution. + * @param pool Memory pool used to allocate memory for the query. + * @param resolver The resolver instance. + * @param option Option flags, which can be constructed from + * #pj_dns_srv_option bitmask. Note that this argument + * was called "fallback_a" in pjsip version 0.8.0 and + * older, but the new option should be backward + * compatible with existing applications. If application + * specifies PJ_TRUE as "fallback_a" value, it will + * correspond to PJ_DNS_SRV_FALLBACK_A option. + * @param token Arbitrary data to be associated with this query when + * the calback is called. + * @param cb Pointer to callback function to receive the + * notification when the resolution process completes. + * @param p_query Optional pointer to receive the query object, if one + * was started. If this pointer is specified, a NULL may + * be returned if response cache is available immediately. + * + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_dns_srv_resolve(const pj_str_t *domain_name, - const pj_str_t *res_name, - unsigned def_port, - pj_pool_t *pool, - pj_dns_resolver *resolver, - unsigned option, - void *token, - pj_dns_srv_resolver_cb *cb, - pj_dns_srv_async_query **p_query); + const pj_str_t *res_name, + unsigned def_port, + pj_pool_t *pool, + pj_dns_resolver *resolver, + unsigned option, + void *token, + pj_dns_srv_resolver_cb *cb, + pj_dns_srv_async_query **p_query); /** * Cancel an outstanding DNS SRV query. * - * @param query The pending asynchronous query to be cancelled. + * @param query The pending asynchronous query to be cancelled. * @param notify If non-zero, the callback will be called with failure - * status to notify that the query has been cancelled. + * status to notify that the query has been cancelled. * - * @return PJ_SUCCESS on success, or the appropriate error code, + * @return PJ_SUCCESS on success, or the appropriate error code, */ PJ_DECL(pj_status_t) pj_dns_srv_cancel_query(pj_dns_srv_async_query *query, - pj_bool_t notify); + pj_bool_t notify); /** @@ -218,5 +217,5 @@ PJ_DECL(pj_status_t) pj_dns_srv_cancel_query(pj_dns_srv_async_query *query, PJ_END_DECL -#endif /* __PJLIB_UTIL_SRV_RESOLVER_H__ */ +#endif /* __PJLIB_UTIL_SRV_RESOLVER_H__ */ diff --git a/pjlib-util/include/pjlib-util/string.h b/pjlib-util/include/pjlib-util/string.h index 48e432b3d7..5537c99161 100644 --- a/pjlib-util/include/pjlib-util/string.h +++ b/pjlib-util/include/pjlib-util/string.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -41,20 +40,20 @@ PJ_BEGIN_DECL * characters, the function would simply return the original string. * Otherwise a new string will be allocated. * - * @param pool Pool to allocate the string. - * @param src Source string to unescape. + * @param pool Pool to allocate the string. + * @param src Source string to unescape. * - * @return String with no escaped characters. + * @return String with no escaped characters. */ PJ_DECL(pj_str_t) pj_str_unescape( pj_pool_t *pool, const pj_str_t *src); /** * Unescape string to destination. * - * @param dst Target string. - * @param src Source string. + * @param dst Target string. + * @param src Source string. * - * @return Target string. + * @return Target string. */ PJ_DECL(pj_str_t*) pj_strcpy_unescape(pj_str_t *dst, const pj_str_t *src); @@ -62,35 +61,35 @@ PJ_DECL(pj_str_t*) pj_strcpy_unescape(pj_str_t *dst, const pj_str_t *src); * Copy string to destination while escaping reserved characters, up to * the specified maximum length. * - * @param dst Target string. - * @param src Source string. - * @param max Maximum length to copy to target string. - * @param unres Unreserved characters, which are allowed to appear - * unescaped. + * @param dst Target string. + * @param src Source string. + * @param max Maximum length to copy to target string. + * @param unres Unreserved characters, which are allowed to appear + * unescaped. * - * @return The target string if all characters have been copied - * successfully, or NULL if there's not enough buffer to - * escape the strings. + * @return The target string if all characters have been copied + * successfully, or NULL if there's not enough buffer to + * escape the strings. */ PJ_DECL(pj_str_t*) pj_strncpy_escape(pj_str_t *dst, const pj_str_t *src, - pj_ssize_t max, const pj_cis_t *unres); + pj_ssize_t max, const pj_cis_t *unres); /** * Copy string to destination while escaping reserved characters, up to * the specified maximum length. * - * @param dst Target string. - * @param src Source string. - * @param max Maximum length to copy to target string. - * @param unres Unreserved characters, which are allowed to appear - * unescaped. + * @param dst Target string. + * @param src Source string. + * @param max Maximum length to copy to target string. + * @param unres Unreserved characters, which are allowed to appear + * unescaped. * - * @return The length of the destination, or -1 if there's not - * enough buffer. + * @return The length of the destination, or -1 if there's not + * enough buffer. */ PJ_DECL(pj_ssize_t) pj_strncpy2_escape(char *dst, const pj_str_t *src, - pj_ssize_t max, const pj_cis_t *unres); + pj_ssize_t max, const pj_cis_t *unres); PJ_END_DECL @@ -99,4 +98,4 @@ PJ_END_DECL * @} */ -#endif /* __PJLIB_UTIL_STRING_H__ */ +#endif /* __PJLIB_UTIL_STRING_H__ */ diff --git a/pjlib-util/include/pjlib-util/stun_simple.h b/pjlib-util/include/pjlib-util/stun_simple.h index 1320f7f33e..68d69a3062 100644 --- a/pjlib-util/include/pjlib-util/stun_simple.h +++ b/pjlib-util/include/pjlib-util/stun_simple.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,11 +35,11 @@ PJ_BEGIN_DECL */ typedef enum pjstun_msg_type { - PJSTUN_BINDING_REQUEST = 0x0001, /**< Binding request */ - PJSTUN_BINDING_RESPONSE = 0x0101, /**< Binding response */ - PJSTUN_BINDING_ERROR_RESPONSE = 0x0111, /**< Binding error */ - PJSTUN_SHARED_SECRET_REQUEST = 0x0002, /**< Secret request */ - PJSTUN_SHARED_SECRET_RESPONSE = 0x0102, /**< Secret response */ + PJSTUN_BINDING_REQUEST = 0x0001, /**< Binding request */ + PJSTUN_BINDING_RESPONSE = 0x0101, /**< Binding response */ + PJSTUN_BINDING_ERROR_RESPONSE = 0x0111, /**< Binding error */ + PJSTUN_SHARED_SECRET_REQUEST = 0x0002, /**< Secret request */ + PJSTUN_SHARED_SECRET_RESPONSE = 0x0102, /**< Secret response */ PJSTUN_SHARED_SECRET_ERROR_RESPONSE = 0x0112 /**< Secret error */ } pjstun_msg_type; @@ -70,9 +69,9 @@ typedef enum pjstun_attr_type */ typedef struct pjstun_msg_hdr { - pj_uint16_t type; - pj_uint16_t length; - pj_uint32_t tsx[4]; + pj_uint16_t type; + pj_uint16_t length; + pj_uint32_t tsx[4]; } pjstun_msg_hdr; @@ -81,8 +80,8 @@ typedef struct pjstun_msg_hdr */ typedef struct pjstun_attr_hdr { - pj_uint16_t type; - pj_uint16_t length; + pj_uint16_t type; + pj_uint16_t length; } pjstun_attr_hdr; @@ -91,11 +90,11 @@ typedef struct pjstun_attr_hdr */ typedef struct pjstun_mapped_addr_attr { - pjstun_attr_hdr hdr; - pj_uint8_t ignored; - pj_uint8_t family; - pj_uint16_t port; - pj_uint32_t addr; + pjstun_attr_hdr hdr; + pj_uint8_t ignored; + pj_uint8_t family; + pj_uint16_t port; + pj_uint32_t addr; } pjstun_mapped_addr_attr; typedef pjstun_mapped_addr_attr pjstun_response_addr_attr; @@ -105,42 +104,42 @@ typedef pjstun_mapped_addr_attr pjstun_reflected_form_attr; typedef struct pjstun_change_request_attr { - pjstun_attr_hdr hdr; - pj_uint32_t value; + pjstun_attr_hdr hdr; + pj_uint32_t value; } pjstun_change_request_attr; typedef struct pjstun_username_attr { - pjstun_attr_hdr hdr; - pj_uint32_t value[1]; + pjstun_attr_hdr hdr; + pj_uint32_t value[1]; } pjstun_username_attr; typedef pjstun_username_attr pjstun_password_attr; typedef struct pjstun_error_code_attr { - pjstun_attr_hdr hdr; - pj_uint16_t ignored; - pj_uint8_t err_class; - pj_uint8_t number; - char reason[4]; + pjstun_attr_hdr hdr; + pj_uint16_t ignored; + pj_uint8_t err_class; + pj_uint8_t number; + char reason[4]; } pjstun_error_code_attr; typedef struct pjstun_msg { pjstun_msg_hdr *hdr; - int attr_count; + int attr_count; pjstun_attr_hdr *attr[PJSTUN_MAX_ATTR]; } pjstun_msg; /* STUN message API (stun.c). */ PJ_DECL(pj_status_t) pjstun_create_bind_req( pj_pool_t *pool, - void **msg, pj_size_t *len, - pj_uint32_t id_hi, - pj_uint32_t id_lo); + void **msg, pj_size_t *len, + pj_uint32_t id_hi, + pj_uint32_t id_lo); PJ_DECL(pj_status_t) pjstun_parse_msg( void *buf, pj_size_t len, - pjstun_msg *msg); + pjstun_msg *msg); PJ_DECL(void*) pjstun_msg_find_attr( pjstun_msg *msg, pjstun_attr_type t); @@ -170,34 +169,34 @@ PJ_DECL(void*) pjstun_msg_find_attr( pjstun_msg *msg, pjstun_attr_type t); * by the servers, and when both are equal, the address will be returned in * \a mapped_addr argument. * - * @param pf The pool factory where memory will be allocated from. - * @param sock_cnt Number of sockets in the socket array. - * @param sock Array of local UDP sockets which public addresses are - * to be queried from the STUN servers. - * @param srv1 Host name or IP address string of the first STUN - * server. - * @param port1 The port number of the first STUN server. - * @param srv2 Host name or IP address string of the second STUN - * server. - * @param port2 The port number of the second STUN server. - * @param mapped_addr Array to receive the mapped public address of the local - * UDP sockets, when the function returns PJ_SUCCESS. + * @param pf The pool factory where memory will be allocated from. + * @param sock_cnt Number of sockets in the socket array. + * @param sock Array of local UDP sockets which public addresses are + * to be queried from the STUN servers. + * @param srv1 Host name or IP address string of the first STUN + * server. + * @param port1 The port number of the first STUN server. + * @param srv2 Host name or IP address string of the second STUN + * server. + * @param port2 The port number of the second STUN server. + * @param mapped_addr Array to receive the mapped public address of the local + * UDP sockets, when the function returns PJ_SUCCESS. * - * @return This functions returns PJ_SUCCESS if responses are - * received from all servers AND all servers returned the - * same mapped public address. Otherwise this function may - * return one of the following error codes: - * - PJLIB_UTIL_ESTUNNOTRESPOND: no respons from servers. - * - PJLIB_UTIL_ESTUNSYMMETRIC: different mapped addresses - * are returned by servers. - * - etc. + * @return This functions returns PJ_SUCCESS if responses are + * received from all servers AND all servers returned the + * same mapped public address. Otherwise this function may + * return one of the following error codes: + * - PJLIB_UTIL_ESTUNNOTRESPOND: no respons from servers. + * - PJLIB_UTIL_ESTUNSYMMETRIC: different mapped addresses + * are returned by servers. + * - etc. * */ PJ_DECL(pj_status_t) pjstun_get_mapped_addr( pj_pool_factory *pf, - int sock_cnt, pj_sock_t sock[], - const pj_str_t *srv1, int port1, - const pj_str_t *srv2, int port2, - pj_sockaddr_in mapped_addr[]); + int sock_cnt, pj_sock_t sock[], + const pj_str_t *srv1, int port1, + const pj_str_t *srv2, int port2, + pj_sockaddr_in mapped_addr[]); /* @@ -209,7 +208,7 @@ typedef struct pjstun_setting * Specifies whether STUN request generated by old STUN library should * insert magic cookie (specified in RFC 5389) in the transaction ID. */ - pj_bool_t use_stun2; + pj_bool_t use_stun2; /** * Address family of the STUN servers. @@ -254,29 +253,29 @@ typedef struct pjstun_setting * by the servers, and when both are equal, the address will be returned in * \a mapped_addr argument. * - * @param pf The pool factory where memory will be allocated from. - * @param opt The STUN settings. - * @param sock_cnt Number of sockets in the socket array. - * @param sock Array of local UDP sockets which public addresses are - * to be queried from the STUN servers. - * @param mapped_addr Array to receive the mapped public address of the local - * UDP sockets, when the function returns PJ_SUCCESS. + * @param pf The pool factory where memory will be allocated from. + * @param opt The STUN settings. + * @param sock_cnt Number of sockets in the socket array. + * @param sock Array of local UDP sockets which public addresses are + * to be queried from the STUN servers. + * @param mapped_addr Array to receive the mapped public address of the local + * UDP sockets, when the function returns PJ_SUCCESS. * - * @return This functions returns PJ_SUCCESS if responses are - * received from all servers AND all servers returned the - * same mapped public address. Otherwise this function may - * return one of the following error codes: - * - PJLIB_UTIL_ESTUNNOTRESPOND: no respons from servers. - * - PJLIB_UTIL_ESTUNSYMMETRIC: different mapped addresses - * are returned by servers. - * - etc. + * @return This functions returns PJ_SUCCESS if responses are + * received from all servers AND all servers returned the + * same mapped public address. Otherwise this function may + * return one of the following error codes: + * - PJLIB_UTIL_ESTUNNOTRESPOND: no respons from servers. + * - PJLIB_UTIL_ESTUNSYMMETRIC: different mapped addresses + * are returned by servers. + * - etc. * */ PJ_DECL(pj_status_t) pjstun_get_mapped_addr2( pj_pool_factory *pf, - const pjstun_setting *opt, - int sock_cnt, - pj_sock_t sock[], - pj_sockaddr_in mapped_addr[]); + const pjstun_setting *opt, + int sock_cnt, + pj_sock_t sock[], + pj_sockaddr_in mapped_addr[]); PJ_END_DECL @@ -285,5 +284,5 @@ PJ_END_DECL * @} */ -#endif /* __PJSTUN_H__ */ +#endif /* __PJSTUN_H__ */ diff --git a/pjlib-util/include/pjlib-util/types.h b/pjlib-util/include/pjlib-util/types.h index e1dcbc49bf..6f4db4980f 100644 --- a/pjlib-util/include/pjlib-util/types.h +++ b/pjlib-util/include/pjlib-util/types.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -91,5 +90,5 @@ PJ_END_DECL * \n */ -#endif /* __PJLIB_UTIL_TYPES_H__ */ +#endif /* __PJLIB_UTIL_TYPES_H__ */ diff --git a/pjlib-util/include/pjlib-util/xml.h b/pjlib-util/include/pjlib-util/xml.h index 359ab9d32b..1a24a21283 100644 --- a/pjlib-util/include/pjlib-util/xml.h +++ b/pjlib-util/include/pjlib-util/xml.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,8 +45,8 @@ typedef struct pj_xml_node pj_xml_node; struct pj_xml_attr { PJ_DECL_LIST_MEMBER(pj_xml_attr); /**< Standard list elements. */ - pj_str_t name; /**< Attribute name. */ - pj_str_t value; /**< Attribute value. */ + pj_str_t name; /**< Attribute name. */ + pj_str_t value; /**< Attribute value. */ }; /** This structure describes XML node head inside XML node structure. @@ -61,10 +60,10 @@ typedef struct pj_xml_node_head struct pj_xml_node { PJ_DECL_LIST_MEMBER(pj_xml_node); /**< List @a prev and @a next member */ - pj_str_t name; /**< Node name. */ - pj_xml_attr attr_head; /**< Attribute list. */ - pj_xml_node_head node_head; /**< Node list. */ - pj_str_t content; /**< Node content. */ + pj_str_t name; /**< Node name. */ + pj_xml_attr attr_head; /**< Attribute list. */ + pj_xml_node_head node_head; /**< Node list. */ + pj_str_t content; /**< Node content. */ }; /** @@ -76,11 +75,11 @@ struct pj_xml_node * Note that the XML message input buffer MUST be NULL terminated and have * length at least len+1 (len MUST NOT include the NULL terminator). * - * @param pool Pool to allocate memory from. - * @param msg The XML message to parse, MUST be NULL terminated. - * @param len The length of the message, not including NULL terminator. + * @param pool Pool to allocate memory from. + * @param msg The XML message to parse, MUST be NULL terminated. + * @param len The length of the message, not including NULL terminator. * - * @return XML root node, or NULL if the XML document can not be parsed. + * @return XML root node, or NULL if the XML document can not be parsed. */ PJ_DECL(pj_xml_node*) pj_xml_parse( pj_pool_t *pool, char *msg, pj_size_t len); @@ -89,24 +88,24 @@ PJ_DECL(pj_xml_node*) pj_xml_parse( pj_pool_t *pool, char *msg, pj_size_t len); * Print XML into XML message. Note that the function WILL NOT NULL terminate * the output. * - * @param node The XML node to print. - * @param buf Buffer to hold the output message. - * @param len The length of the buffer. + * @param node The XML node to print. + * @param buf Buffer to hold the output message. + * @param len The length of the buffer. * @param prolog If set to nonzero, will print XML prolog ("next is the starting point. - * @param name Node name to find. + * @param node node->next is the starting point. + * @param name Node name to find. * - * @return XML node found or NULL. + * @return XML node found or NULL. */ PJ_DECL(pj_xml_node*) pj_xml_find_next_node(const pj_xml_node *parent, - const pj_xml_node *node, - const pj_str_t *name); + const pj_xml_node *node, + const pj_str_t *name); /** * Recursively find the first node with the specified name in the child nodes * and their children. * * @param parent Parent node. - * @param name Node name to find. + * @param name Node name to find. * - * @return XML node found or NULL. + * @return XML node found or NULL. */ PJ_DECL(pj_xml_node*) pj_xml_find_node_rec(const pj_xml_node *parent, - const pj_str_t *name); + const pj_str_t *name); /** * Find first attribute within a node with the specified name and optional * value. * - * @param node XML Node. - * @param name Attribute name to find. - * @param value Optional value to match. + * @param node XML Node. + * @param name Attribute name to find. + * @param value Optional value to match. * - * @return XML attribute found, or NULL. + * @return XML attribute found, or NULL. */ PJ_DECL(pj_xml_attr*) pj_xml_find_attr(const pj_xml_node *node, - const pj_str_t *name, - const pj_str_t *value); + const pj_str_t *name, + const pj_str_t *value); /** * Find a direct child node with the specified name and match the function. * * @param parent Parent node. - * @param name Optional name. If this is NULL, the name will not be - * matched. - * @param data Data to be passed to matching function. - * @param match Optional matching function. + * @param name Optional name. If this is NULL, the name will not be + * matched. + * @param data Data to be passed to matching function. + * @param match Optional matching function. * - * @return The first matched node, or NULL. + * @return The first matched node, or NULL. */ PJ_DECL(pj_xml_node*) pj_xml_find( const pj_xml_node *parent, - const pj_str_t *name, - const void *data, - pj_bool_t (*match)(const pj_xml_node *, - const void*)); + const pj_str_t *name, + const void *data, + pj_bool_t (*match)(const pj_xml_node *, + const void*)); /** @@ -226,18 +225,18 @@ PJ_DECL(pj_xml_node*) pj_xml_find( const pj_xml_node *parent, * function. * * @param parent Parent node. - * @param name Optional name. If this is NULL, the name will not be - * matched. - * @param data Data to be passed to matching function. - * @param match Optional matching function. + * @param name Optional name. If this is NULL, the name will not be + * matched. + * @param data Data to be passed to matching function. + * @param match Optional matching function. * - * @return The first matched node, or NULL. + * @return The first matched node, or NULL. */ PJ_DECL(pj_xml_node*) pj_xml_find_rec(const pj_xml_node *parent, - const pj_str_t *name, - const void *data, - pj_bool_t (*match)(const pj_xml_node*, - const void*)); + const pj_str_t *name, + const void *data, + pj_bool_t (*match)(const pj_xml_node*, + const void*)); /** @@ -246,4 +245,4 @@ PJ_DECL(pj_xml_node*) pj_xml_find_rec(const pj_xml_node *parent, PJ_END_DECL -#endif /* __PJ_XML_H__ */ +#endif /* __PJ_XML_H__ */ diff --git a/pjlib-util/src/pjlib-util-test/encryption.c b/pjlib-util/src/pjlib-util-test/encryption.c index b2b0acd3f0..40e7cd9a00 100644 --- a/pjlib-util/src/pjlib-util-test/encryption.c +++ b/pjlib-util/src/pjlib-util-test/encryption.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,7 +45,7 @@ static char *sha1_test_results[] = { static void digest_to_hex(const pj_uint8_t digest[PJ_SHA1_DIGEST_SIZE], - char *output) + char *output) { int i,j; char *c = output; @@ -77,12 +76,12 @@ static int sha1_test1(void) for (k = 0; k < 2; k++){ pj_sha1_init(&context); pj_sha1_update(&context, (pj_uint8_t*)sha1_test_data[k], - pj_ansi_strlen(sha1_test_data[k])); + pj_ansi_strlen(sha1_test_data[k])); pj_sha1_final(&context, digest); - digest_to_hex(digest, output); + digest_to_hex(digest, output); if (pj_ansi_strcmp(output, sha1_test_results[k])) { - PJ_LOG(3, (THIS_FILE, " incorrect hash result on k=%d", k)); + PJ_LOG(3, (THIS_FILE, " incorrect hash result on k=%d", k)); return -10; } } @@ -94,7 +93,7 @@ static int sha1_test1(void) pj_sha1_final(&context, digest); digest_to_hex(digest, output); if (strcmp(output, sha1_test_results[2])) { - PJ_LOG(3, (THIS_FILE, " incorrect hash result!")); + PJ_LOG(3, (THIS_FILE, " incorrect hash result!")); return -20; } @@ -108,18 +107,18 @@ static int sha1_test1(void) pj_sha1_final(&context, digest); digest_to_hex(digest, output); if (strcmp(output, sha1_test_results[2])) { - pj_pool_release(pool); - PJ_LOG(3, (THIS_FILE, " incorrect hash result for block update!")); + pj_pool_release(pool); + PJ_LOG(3, (THIS_FILE, " incorrect hash result for block update!")); return -21; } /* verify that original buffer was not modified */ for (k=0; k 0) { - pj_crc32_update(&ctx, (pj_uint8_t*)crc32_test_data[i].input + len/2, - len - len/2); - } + if (len/2 > 0) { + pj_crc32_update(&ctx, (pj_uint8_t*)crc32_test_data[i].input + len/2, + len - len/2); + } - crc1 = pj_crc32_final(&ctx); + crc1 = pj_crc32_final(&ctx); - if (crc0 != crc1) { - PJ_LOG(3,(THIS_FILE, - " error: crc algorithm error on test %d", i)); - return -85; - } + if (crc0 != crc1) { + PJ_LOG(3,(THIS_FILE, + " error: crc algorithm error on test %d", i)); + return -85; + } } return 0; @@ -512,65 +511,65 @@ static struct base64_test_vec } base64_test_vec[] = { { - "", - "", - ENCODE_DECODE + "", + "", + ENCODE_DECODE }, { - "f", - "Zg==", - ENCODE_DECODE + "f", + "Zg==", + ENCODE_DECODE }, { - "fo", - "Zm8=", - ENCODE_DECODE + "fo", + "Zm8=", + ENCODE_DECODE }, { - "foo", - "Zm9v", - ENCODE_DECODE + "foo", + "Zm9v", + ENCODE_DECODE }, { - "foob", - "Zm9vYg==", - ENCODE_DECODE + "foob", + "Zm9vYg==", + ENCODE_DECODE }, { - "fooba", - "Zm9vYmE=", - ENCODE_DECODE + "fooba", + "Zm9vYmE=", + ENCODE_DECODE }, { - "foobar", - "Zm9vYmFy", - ENCODE_DECODE + "foobar", + "Zm9vYmFy", + ENCODE_DECODE }, { - "\x14\xfb\x9c\x03\xd9\x7e", - "FPucA9l+", - ENCODE_DECODE + "\x14\xfb\x9c\x03\xd9\x7e", + "FPucA9l+", + ENCODE_DECODE }, { - "\x14\xfb\x9c\x03\xd9", - "FPucA9k=", - ENCODE_DECODE + "\x14\xfb\x9c\x03\xd9", + "FPucA9k=", + ENCODE_DECODE }, { - "\x14\xfb\x9c\x03", - "FPucAw==", - ENCODE_DECODE + "\x14\xfb\x9c\x03", + "FPucAw==", + ENCODE_DECODE }, /* with whitespaces */ { - "foobar", - "Zm9v\r\nYmFy", - DECODE + "foobar", + "Zm9v\r\nYmFy", + DECODE }, { - "foobar", - "\nZ\r\nm 9\tv\nYm\nF\ny\n", - DECODE + "foobar", + "\nZ\r\nm 9\tv\nYm\nF\ny\n", + DECODE }, }; @@ -584,43 +583,43 @@ static int base64_test(void) PJ_LOG(3, (THIS_FILE, " base64 test..")); for (i=0; i #include -#define ACTION_REPLY 0 -#define ACTION_IGNORE -1 +#define ACTION_REPLY 0 +#define ACTION_IGNORE -1 static struct server_t { - pj_sock_t sock; - pj_uint16_t port; - pj_thread_t *thread; + pj_sock_t sock; + pj_uint16_t port; + pj_thread_t *thread; /* Action: - * 0: reply with the response in resp. + * 0: reply with the response in resp. * -1: ignore query (to simulate timeout). * other: reply with that error */ - int action; + int action; pj_bool_t send_content_length; - unsigned data_size; + unsigned data_size; unsigned buf_size; } g_server; @@ -68,34 +67,34 @@ static int server_thread(void *p) pj_sock_t newsock = PJ_INVALID_SOCKET; while (!thread_quit) { - pj_ssize_t pkt_len; - int rc; + pj_ssize_t pkt_len; + int rc; pj_fd_set_t rset; - pj_time_val timeout = {0, 500}; - - while (!thread_quit) { - PJ_FD_ZERO(&rset); - PJ_FD_SET(srv->sock, &rset); - rc = pj_sock_select((int)srv->sock+1, &rset, NULL, NULL, &timeout); - if (rc != 1) { - continue; - } - - rc = pj_sock_accept(srv->sock, &newsock, NULL, NULL); - if (rc == PJ_SUCCESS) { - break; - } - } - - if (thread_quit) - break; - - while (!thread_quit) { + pj_time_val timeout = {0, 500}; + + while (!thread_quit) { + PJ_FD_ZERO(&rset); + PJ_FD_SET(srv->sock, &rset); + rc = pj_sock_select((int)srv->sock+1, &rset, NULL, NULL, &timeout); + if (rc != 1) { + continue; + } + + rc = pj_sock_accept(srv->sock, &newsock, NULL, NULL); + if (rc == PJ_SUCCESS) { + break; + } + } + + if (thread_quit) + break; + + while (!thread_quit) { PJ_FD_ZERO(&rset); PJ_FD_SET(newsock, &rset); rc = pj_sock_select((int)newsock+1, &rset, NULL, NULL, &timeout); if (rc != 1) { - PJ_LOG(3,("http test", "client timeout")); + PJ_LOG(3,("http test", "client timeout")); continue; } @@ -106,17 +105,17 @@ static int server_thread(void *p) } } - if (thread_quit) - break; + if (thread_quit) + break; - /* Simulate network RTT */ - pj_thread_sleep(50); + /* Simulate network RTT */ + pj_thread_sleep(50); - if (srv->action == ACTION_IGNORE) { - continue; - } else if (srv->action == ACTION_REPLY) { + if (srv->action == ACTION_IGNORE) { + continue; + } else if (srv->action == ACTION_REPLY) { pj_size_t send_len = 0; - unsigned ctr = 0; + unsigned ctr = 0; pj_ansi_sprintf(pkt, "HTTP/1.0 200 OK\r\n"); if (srv->send_content_length) { pj_ansi_sprintf(pkt + pj_ansi_strlen(pkt), @@ -127,23 +126,23 @@ static int server_thread(void *p) pkt_len = pj_ansi_strlen(pkt); rc = pj_sock_send(newsock, pkt, &pkt_len, 0); if (rc != PJ_SUCCESS) { - pj_sock_close(newsock); - continue; + pj_sock_close(newsock); + continue; } while (send_len < srv->data_size) { pkt_len = srv->data_size - send_len; if (pkt_len > (signed)srv->buf_size) pkt_len = srv->buf_size; - send_len += pkt_len; + send_len += pkt_len; pj_create_random_string(pkt, pkt_len); pj_ansi_sprintf(pkt, "\nPacket: %d", ++ctr); pkt[pj_ansi_strlen(pkt)] = '\n'; - rc = pj_sock_send(newsock, pkt, &pkt_len, 0); - if (rc != PJ_SUCCESS) - break; + rc = pj_sock_send(newsock, pkt, &pkt_len, 0); + if (rc != PJ_SUCCESS) + break; } pj_sock_close(newsock); - } + } } return 0; @@ -228,10 +227,10 @@ static void on_response(pj_http_req *hreq, const pj_http_resp *resp) #endif if (test_cancel) { - /* Need to delay closing the client socket here, otherwise the - * server will get SIGPIPE when sending response. - */ - pj_thread_sleep(100); + /* Need to delay closing the client socket here, otherwise the + * server will get SIGPIPE when sending response. + */ + pj_thread_sleep(100); pj_http_req_cancel(hreq, PJ_TRUE); test_cancel = PJ_FALSE; } @@ -260,16 +259,16 @@ static int parse_url_test() { struct test_data { - char *url; - pj_status_t result; - const char *username; - const char *passwd; - const char *host; - int port; - const char *path; + char *url; + pj_status_t result; + const char *username; + const char *passwd; + const char *host; + int port; + const char *path; } test_data[] = { - /* Simple URL without '/' in the end */ + /* Simple URL without '/' in the end */ {"http://www.pjsip.org", PJ_SUCCESS, "", "", "www.pjsip.org", 80, "/"}, /* Simple URL with port number but without '/' in the end */ @@ -277,97 +276,97 @@ static int parse_url_test() /* URL with path */ {"http://127.0.0.1:280/Joomla/index.php?option=com_content&task=view&id=5&Itemid=6", - PJ_SUCCESS, "", "", "127.0.0.1", 280, - "/Joomla/index.php?option=com_content&task=view&id=5&Itemid=6"}, + PJ_SUCCESS, "", "", "127.0.0.1", 280, + "/Joomla/index.php?option=com_content&task=view&id=5&Itemid=6"}, - /* URL with port and path */ - {"http://pjsip.org:81/about-us/", PJ_SUCCESS, "", "", "pjsip.org", 81, "/about-us/"}, + /* URL with port and path */ + {"http://pjsip.org:81/about-us/", PJ_SUCCESS, "", "", "pjsip.org", 81, "/about-us/"}, - /* unsupported protocol */ - {"ftp://www.pjsip.org", PJ_ENOTSUP, "", "", "", 80, ""}, + /* unsupported protocol */ + {"ftp://www.pjsip.org", PJ_ENOTSUP, "", "", "", 80, ""}, - /* invalid format */ - {"http:/pjsip.org/about-us/", PJLIB_UTIL_EHTTPINURL, "", "", "", 80, ""}, + /* invalid format */ + {"http:/pjsip.org/about-us/", PJLIB_UTIL_EHTTPINURL, "", "", "", 80, ""}, - /* invalid port number */ - {"http://pjsip.org:xyz/", PJLIB_UTIL_EHTTPINPORT, "", "", "", 80, ""}, + /* invalid port number */ + {"http://pjsip.org:xyz/", PJLIB_UTIL_EHTTPINPORT, "", "", "", 80, ""}, - /* with username and password */ - {"http://user:pass@pjsip.org", PJ_SUCCESS, "user", "pass", "pjsip.org", 80, "/"}, + /* with username and password */ + {"http://user:pass@pjsip.org", PJ_SUCCESS, "user", "pass", "pjsip.org", 80, "/"}, - /* password only*/ - {"http://:pass@pjsip.org", PJ_SUCCESS, "", "pass", "pjsip.org", 80, "/"}, + /* password only*/ + {"http://:pass@pjsip.org", PJ_SUCCESS, "", "pass", "pjsip.org", 80, "/"}, - /* user only*/ - {"http://user:@pjsip.org", PJ_SUCCESS, "user", "", "pjsip.org", 80, "/"}, + /* user only*/ + {"http://user:@pjsip.org", PJ_SUCCESS, "user", "", "pjsip.org", 80, "/"}, - /* empty username and passwd*/ - {"http://:@pjsip.org", PJ_SUCCESS, "", "", "pjsip.org", 80, "/"}, + /* empty username and passwd*/ + {"http://:@pjsip.org", PJ_SUCCESS, "", "", "pjsip.org", 80, "/"}, - /* '@' character in username and path */ - {"http://user@pjsip.org/@", PJ_SUCCESS, "user", "", "pjsip.org", 80, "/@"}, + /* '@' character in username and path */ + {"http://user@pjsip.org/@", PJ_SUCCESS, "user", "", "pjsip.org", 80, "/@"}, - /* '@' character in path */ - {"http://pjsip.org/@", PJ_SUCCESS, "", "", "pjsip.org", 80, "/@"}, + /* '@' character in path */ + {"http://pjsip.org/@", PJ_SUCCESS, "", "", "pjsip.org", 80, "/@"}, - /* '@' character in path */ - {"http://pjsip.org/one@", PJ_SUCCESS, "", "", "pjsip.org", 80, "/one@"}, + /* '@' character in path */ + {"http://pjsip.org/one@", PJ_SUCCESS, "", "", "pjsip.org", 80, "/one@"}, - /* Invalid URL */ - {"http://:", PJ_EINVAL, "", "", "", 0, ""}, + /* Invalid URL */ + {"http://:", PJ_EINVAL, "", "", "", 0, ""}, - /* Invalid URL */ - {"http://@", PJ_EINVAL, "", "", "", 0, ""}, + /* Invalid URL */ + {"http://@", PJ_EINVAL, "", "", "", 0, ""}, - /* Invalid URL */ - {"http", PJ_EINVAL, "", "", "", 0, ""}, + /* Invalid URL */ + {"http", PJ_EINVAL, "", "", "", 0, ""}, - /* Invalid URL */ - {"http:/", PJ_EINVAL, "", "", "", 0, ""}, + /* Invalid URL */ + {"http:/", PJ_EINVAL, "", "", "", 0, ""}, - /* Invalid URL */ - {"http://", PJ_EINVAL, "", "", "", 0, ""}, + /* Invalid URL */ + {"http://", PJ_EINVAL, "", "", "", 0, ""}, - /* Invalid URL */ - {"http:///", PJ_EINVAL, "", "", "", 0, ""}, + /* Invalid URL */ + {"http:///", PJ_EINVAL, "", "", "", 0, ""}, - /* Invalid URL */ - {"http://@/", PJ_EINVAL, "", "", "", 0, ""}, + /* Invalid URL */ + {"http://@/", PJ_EINVAL, "", "", "", 0, ""}, - /* Invalid URL */ - {"http:///@", PJ_EINVAL, "", "", "", 0, ""}, + /* Invalid URL */ + {"http:///@", PJ_EINVAL, "", "", "", 0, ""}, - /* Invalid URL */ - {"http://:::", PJ_EINVAL, "", "", "", 0, ""}, + /* Invalid URL */ + {"http://:::", PJ_EINVAL, "", "", "", 0, ""}, }; unsigned i; for (i=0; iurl)); - status = parse_url(ptd->url, &hurl); - - if (status != ptd->result) { - PJ_LOG(3,(THIS_FILE, "%d", status)); - return -11; - } - if (status != PJ_SUCCESS) - continue; - if (pj_strcmp2(&hurl.username, ptd->username)) - return -12; - if (pj_strcmp2(&hurl.passwd, ptd->passwd)) - return -13; - if (pj_strcmp2(&hurl.host, ptd->host)) - return -14; - if (hurl.port != ptd->port) - return -15; - if (pj_strcmp2(&hurl.path, ptd->path)) - return -16; + struct test_data *ptd; + pj_http_url hurl; + pj_status_t status; + + ptd = &test_data[i]; + + PJ_LOG(3, (THIS_FILE, ".. %s", ptd->url)); + status = parse_url(ptd->url, &hurl); + + if (status != ptd->result) { + PJ_LOG(3,(THIS_FILE, "%d", status)); + return -11; + } + if (status != PJ_SUCCESS) + continue; + if (pj_strcmp2(&hurl.username, ptd->username)) + return -12; + if (pj_strcmp2(&hurl.passwd, ptd->passwd)) + return -13; + if (pj_strcmp2(&hurl.host, ptd->host)) + return -14; + if (hurl.port != ptd->port) + return -15; + if (pj_strcmp2(&hurl.path, ptd->path)) + return -16; } return 0; @@ -418,16 +417,16 @@ int http_client_test1() return -43; { - pj_sockaddr_in addr2; - int addr_len = sizeof(addr2); - sstatus = pj_sock_getsockname(g_server.sock, &addr2, &addr_len); - if (sstatus != PJ_SUCCESS) - return -44; - g_server.port = pj_sockaddr_in_get_port(&addr2); - pj_ansi_snprintf(urlbuf, sizeof(urlbuf), - "http://127.0.0.1:%d/about-us/", - g_server.port); - url = pj_str(urlbuf); + pj_sockaddr_in addr2; + int addr_len = sizeof(addr2); + sstatus = pj_sock_getsockname(g_server.sock, &addr2, &addr_len); + if (sstatus != PJ_SUCCESS) + return -44; + g_server.port = pj_sockaddr_in_get_port(&addr2); + pj_ansi_snprintf(urlbuf, sizeof(urlbuf), + "http://127.0.0.1:%d/about-us/", + g_server.port); + url = pj_str(urlbuf); } sstatus = pj_sock_listen(g_server.sock, 8); @@ -453,8 +452,8 @@ int http_client_test1() while (pj_http_req_is_running(http_req)) { pj_time_val delay = {0, 50}; - pj_ioqueue_poll(ioqueue, &delay); - pj_timer_heap_poll(timer_heap, NULL); + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer_heap, NULL); } if (pj_http_req_start(http_req)) @@ -462,8 +461,8 @@ int http_client_test1() while (pj_http_req_is_running(http_req)) { pj_time_val delay = {0, 50}; - pj_ioqueue_poll(ioqueue, &delay); - pj_timer_heap_poll(timer_heap, NULL); + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer_heap, NULL); } #ifdef USE_LOCAL_SERVER @@ -530,16 +529,16 @@ int http_client_test2() return -43; { - pj_sockaddr_in addr2; - int addr_len = sizeof(addr2); - sstatus = pj_sock_getsockname(g_server.sock, &addr2, &addr_len); - if (sstatus != PJ_SUCCESS) - return -44; - g_server.port = pj_sockaddr_in_get_port(&addr2); - pj_ansi_snprintf(urlbuf, sizeof(urlbuf), - "http://127.0.0.1:%d", - g_server.port); - url = pj_str(urlbuf); + pj_sockaddr_in addr2; + int addr_len = sizeof(addr2); + sstatus = pj_sock_getsockname(g_server.sock, &addr2, &addr_len); + if (sstatus != PJ_SUCCESS) + return -44; + g_server.port = pj_sockaddr_in_get_port(&addr2); + pj_ansi_snprintf(urlbuf, sizeof(urlbuf), + "http://127.0.0.1:%d", + g_server.port); + url = pj_str(urlbuf); } sstatus = pj_sock_listen(g_server.sock, 8); @@ -558,17 +557,17 @@ int http_client_test2() #endif pj_http_headers_add_elmt2(¶m.headers, (char*)"Accept", - (char*)"image/gif, image/x-xbitmap, image/jpeg, " - "image/pjpeg, application/x-ms-application," - " application/vnd.ms-xpsdocument, " - "application/xaml+xml, " - "application/x-ms-xbap, " - "application/x-shockwave-flash, " - "application/vnd.ms-excel, " - "application/vnd.ms-powerpoint, " - "application/msword, */*"); + (char*)"image/gif, image/x-xbitmap, image/jpeg, " + "image/pjpeg, application/x-ms-application," + " application/vnd.ms-xpsdocument, " + "application/xaml+xml, " + "application/x-ms-xbap, " + "application/x-shockwave-flash, " + "application/vnd.ms-excel, " + "application/vnd.ms-powerpoint, " + "application/msword, */*"); pj_http_headers_add_elmt2(¶m.headers, (char*)"Accept-Language", - (char*)"en-sg"); + (char*)"en-sg"); pj_http_headers_add_elmt2(¶m.headers, (char*)"User-Agent", (char*)"Mozilla/4.0 (compatible; MSIE 7.0; " "Windows NT 6.0; SLCC1; " @@ -583,8 +582,8 @@ int http_client_test2() while (pj_http_req_is_running(http_req)) { pj_time_val delay = {0, 50}; - pj_ioqueue_poll(ioqueue, &delay); - pj_timer_heap_poll(timer_heap, NULL); + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer_heap, NULL); } #ifdef USE_LOCAL_SERVER @@ -598,8 +597,8 @@ int http_client_test2() while (pj_http_req_is_running(http_req)) { pj_time_val delay = {0, 50}; - pj_ioqueue_poll(ioqueue, &delay); - pj_timer_heap_poll(timer_heap, NULL); + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer_heap, NULL); } #ifdef USE_LOCAL_SERVER @@ -659,16 +658,16 @@ int http_client_test_put1() return -43; { - pj_sockaddr_in addr2; - int addr_len = sizeof(addr2); - sstatus = pj_sock_getsockname(g_server.sock, &addr2, &addr_len); - if (sstatus != PJ_SUCCESS) - return -44; - g_server.port = pj_sockaddr_in_get_port(&addr2); - pj_ansi_snprintf(urlbuf, sizeof(urlbuf), - "http://127.0.0.1:%d/test/test.txt", - g_server.port); - url = pj_str(urlbuf); + pj_sockaddr_in addr2; + int addr_len = sizeof(addr2); + sstatus = pj_sock_getsockname(g_server.sock, &addr2, &addr_len); + if (sstatus != PJ_SUCCESS) + return -44; + g_server.port = pj_sockaddr_in_get_port(&addr2); + pj_ansi_snprintf(urlbuf, sizeof(urlbuf), + "http://127.0.0.1:%d/test/test.txt", + g_server.port); + url = pj_str(urlbuf); } sstatus = pj_sock_listen(g_server.sock, 8); @@ -701,8 +700,8 @@ int http_client_test_put1() while (pj_http_req_is_running(http_req)) { pj_time_val delay = {0, 50}; - pj_ioqueue_poll(ioqueue, &delay); - pj_timer_heap_poll(timer_heap, NULL); + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer_heap, NULL); } #ifdef USE_LOCAL_SERVER @@ -762,16 +761,16 @@ int http_client_test_put2() return -43; { - pj_sockaddr_in addr2; - int addr_len = sizeof(addr2); - sstatus = pj_sock_getsockname(g_server.sock, &addr2, &addr_len); - if (sstatus != PJ_SUCCESS) - return -44; - g_server.port = pj_sockaddr_in_get_port(&addr2); - pj_ansi_snprintf(urlbuf, sizeof(urlbuf), - "http://127.0.0.1:%d/test/test2.txt", - g_server.port); - url = pj_str(urlbuf); + pj_sockaddr_in addr2; + int addr_len = sizeof(addr2); + sstatus = pj_sock_getsockname(g_server.sock, &addr2, &addr_len); + if (sstatus != PJ_SUCCESS) + return -44; + g_server.port = pj_sockaddr_in_get_port(&addr2); + pj_ansi_snprintf(urlbuf, sizeof(urlbuf), + "http://127.0.0.1:%d/test/test2.txt", + g_server.port); + url = pj_str(urlbuf); } sstatus = pj_sock_listen(g_server.sock, 8); @@ -802,8 +801,8 @@ int http_client_test_put2() while (pj_http_req_is_running(http_req)) { pj_time_val delay = {0, 50}; - pj_ioqueue_poll(ioqueue, &delay); - pj_timer_heap_poll(timer_heap, NULL); + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer_heap, NULL); } #ifdef USE_LOCAL_SERVER @@ -857,16 +856,16 @@ int http_client_test_delete() return -43; { - pj_sockaddr_in addr2; - int addr_len = sizeof(addr2); - sstatus = pj_sock_getsockname(g_server.sock, &addr2, &addr_len); - if (sstatus != PJ_SUCCESS) - return -44; - g_server.port = pj_sockaddr_in_get_port(&addr2); - pj_ansi_snprintf(urlbuf, sizeof(urlbuf), - "http://127.0.0.1:%d/test/test2.txt", - g_server.port); - url = pj_str(urlbuf); + pj_sockaddr_in addr2; + int addr_len = sizeof(addr2); + sstatus = pj_sock_getsockname(g_server.sock, &addr2, &addr_len); + if (sstatus != PJ_SUCCESS) + return -44; + g_server.port = pj_sockaddr_in_get_port(&addr2); + pj_ansi_snprintf(urlbuf, sizeof(urlbuf), + "http://127.0.0.1:%d/test/test2.txt", + g_server.port); + url = pj_str(urlbuf); } sstatus = pj_sock_listen(g_server.sock, 8); @@ -893,8 +892,8 @@ int http_client_test_delete() while (pj_http_req_is_running(http_req)) { pj_time_val delay = {0, 50}; - pj_ioqueue_poll(ioqueue, &delay); - pj_timer_heap_poll(timer_heap, NULL); + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer_heap, NULL); } #ifdef USE_LOCAL_SERVER @@ -953,4 +952,4 @@ int http_client_test() * when this test is disabled. */ int dummy_http_client_test; -#endif /* INCLUDE_HTTP_CLIENT_TEST */ +#endif /* INCLUDE_HTTP_CLIENT_TEST */ diff --git a/pjlib-util/src/pjlib-util-test/json_test.c b/pjlib-util/src/pjlib-util-test/json_test.c index ddcba75015..c0b6706e2a 100644 --- a/pjlib-util/src/pjlib-util-test/json_test.c +++ b/pjlib-util/src/pjlib-util-test/json_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -18,7 +17,7 @@ */ #include "test.h" -#define THIS_FILE "json_test.c" +#define THIS_FILE "json_test.c" #if INCLUDE_JSON_TEST @@ -40,12 +39,12 @@ static char json_doc1[] = },\ \"Array1\": [116, false, \"string\", {}],\ \"Array2\": [\ - {\ - \"Float\": 123.,\ - },\ - {\ - \"Float\": 123.,\ - }\ + {\ + \"Float\": 123.,\ + },\ + {\ + \"Float\": 123.,\ + }\ ]\ },\ \"Integer\": 800,\ @@ -66,16 +65,16 @@ static int json_verify_1() size = (unsigned)strlen(json_doc1); elem = pj_json_parse(pool, json_doc1, &size, &err); if (!elem) { - PJ_LOG(1, (THIS_FILE, " Error: json_verify_1() parse error")); - goto on_error; + PJ_LOG(1, (THIS_FILE, " Error: json_verify_1() parse error")); + goto on_error; } size = (unsigned)strlen(json_doc1) * 2; out_buf = pj_pool_alloc(pool, size); if (pj_json_write(elem, out_buf, &size)) { - PJ_LOG(1, (THIS_FILE, " Error: json_verify_1() write error")); - goto on_error; + PJ_LOG(1, (THIS_FILE, " Error: json_verify_1() write error")); + goto on_error; } PJ_LOG(3,(THIS_FILE, "Json document:\n%s", out_buf)); @@ -94,7 +93,7 @@ int json_test(void) rc = json_verify_1(); if (rc) - return rc; + return rc; return 0; } diff --git a/pjlib-util/src/pjlib-util-test/main.c b/pjlib-util/src/pjlib-util-test/main.c index e6df3d76b9..a5413f162c 100644 --- a/pjlib-util/src/pjlib-util-test/main.c +++ b/pjlib-util/src/pjlib-util-test/main.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -76,26 +75,26 @@ int main(int argc, char *argv[]) while (argc > 1) { char *arg = argv[--argc]; - if (*arg=='-' && *(arg+1)=='i') { - interractive = 1; + if (*arg=='-' && *(arg+1)=='i') { + interractive = 1; - } else if (*arg=='-' && *(arg+1)=='n') { - no_trap = 1; - } + } else if (*arg=='-' && *(arg+1)=='n') { + no_trap = 1; + } } if (!no_trap) { - init_signals(); + init_signals(); } rc = test_main(); if (interractive) { - char s[10]; - puts(""); - puts("Press to exit"); - if (!fgets(s, sizeof(s), stdin)) - return rc; + char s[10]; + puts(""); + puts("Press to exit"); + if (!fgets(s, sizeof(s), stdin)) + return rc; } return rc; diff --git a/pjlib-util/src/pjlib-util-test/resolver_test.c b/pjlib-util/src/pjlib-util-test/resolver_test.c index 061194b8d5..cc2a17b234 100644 --- a/pjlib-util/src/pjlib-util-test/resolver_test.c +++ b/pjlib-util/src/pjlib-util-test/resolver_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -33,31 +32,31 @@ //////////////////////////////////////////////////////////////////////////// -#define ACTION_REPLY 0 -#define ACTION_IGNORE -1 -#define ACTION_CB -2 +#define ACTION_REPLY 0 +#define ACTION_IGNORE -1 +#define ACTION_CB -2 #undef s6_addr32 #define s6_addr32(addr, idx) *((pj_uint32_t *)(addr.s6_addr + idx*4)) static struct server_t { - pj_sock_t sock; - pj_uint16_t port; - pj_thread_t *thread; + pj_sock_t sock; + pj_uint16_t port; + pj_thread_t *thread; /* Action: - * 0: reply with the response in resp. + * 0: reply with the response in resp. * -1: ignore query (to simulate timeout). * other: reply with that error */ - int action; + int action; pj_dns_parsed_packet resp; - void (*action_cb)(const pj_dns_parsed_packet *pkt, - pj_dns_parsed_packet **p_res); + void (*action_cb)(const pj_dns_parsed_packet *pkt, + pj_dns_parsed_packet **p_res); - unsigned pkt_count; + unsigned pkt_count; } g_server[2]; @@ -77,8 +76,8 @@ struct label_tab unsigned count; struct { - unsigned pos; - pj_str_t label; + unsigned pos; + pj_str_t label; } a[MAX_LABEL]; }; @@ -95,8 +94,8 @@ static void write32(pj_uint8_t *p, pj_uint32_t val) } static int print_name(pj_uint8_t *pkt, int size, - pj_uint8_t *pos, const pj_str_t *name, - struct label_tab *tab) + pj_uint8_t *pos, const pj_str_t *name, + struct label_tab *tab) { pj_uint8_t *p = pos; const char *endlabel, *endname; @@ -105,20 +104,20 @@ static int print_name(pj_uint8_t *pkt, int size, /* Check if name is in the table */ for (i=0; icount; ++i) { - if (pj_strcmp(&tab->a[i].label, name)==0) - break; + if (pj_strcmp(&tab->a[i].label, name)==0) + break; } if (i != tab->count) { - write16(p, (pj_uint16_t)(tab->a[i].pos | (0xc0 << 8))); - return 2; + write16(p, (pj_uint16_t)(tab->a[i].pos | (0xc0 << 8))); + return 2; } else { - if (tab->count < MAX_LABEL) { - tab->a[tab->count].pos = (unsigned)(p-pkt); - tab->a[tab->count].label.ptr = (char*)(p+1); - tab->a[tab->count].label.slen = name->slen; - ++tab->count; - } + if (tab->count < MAX_LABEL) { + tab->a[tab->count].pos = (unsigned)(p-pkt); + tab->a[tab->count].label.ptr = (char*)(p+1); + tab->a[tab->count].label.slen = name->slen; + ++tab->count; + } } endlabel = name->ptr; @@ -128,27 +127,27 @@ static int print_name(pj_uint8_t *pkt, int size, while (endlabel != endname) { - while (endlabel != endname && *endlabel != '.') - ++endlabel; + while (endlabel != endname && *endlabel != '.') + ++endlabel; - label.slen = (endlabel - label.ptr); + label.slen = (endlabel - label.ptr); - if (size < label.slen+1) - return -1; + if (size < label.slen+1) + return -1; - *p = (pj_uint8_t)label.slen; - pj_memcpy(p+1, label.ptr, label.slen); + *p = (pj_uint8_t)label.slen; + pj_memcpy(p+1, label.ptr, label.slen); - size -= (int)(label.slen+1); - p += (label.slen+1); + size -= (int)(label.slen+1); + p += (label.slen+1); - if (endlabel != endname && *endlabel == '.') - ++endlabel; - label.ptr = (char*)endlabel; + if (endlabel != endname && *endlabel == '.') + ++endlabel; + label.ptr = (char*)endlabel; } if (size == 0) - return -1; + return -1; *p++ = '\0'; @@ -156,104 +155,104 @@ static int print_name(pj_uint8_t *pkt, int size, } static int print_rr(pj_uint8_t *pkt, int size, pj_uint8_t *pos, - const pj_dns_parsed_rr *rr, struct label_tab *tab) + const pj_dns_parsed_rr *rr, struct label_tab *tab) { pj_uint8_t *p = pos; int len; len = print_name(pkt, size, pos, &rr->name, tab); if (len < 0) - return -1; + return -1; p += len; size -= len; if (size < 8) - return -1; + return -1; pj_assert(rr->dnsclass == 1); - write16(p+0, (pj_uint16_t)rr->type); /* type */ - write16(p+2, (pj_uint16_t)rr->dnsclass); /* class */ - write32(p+4, rr->ttl); /* TTL */ + write16(p+0, (pj_uint16_t)rr->type); /* type */ + write16(p+2, (pj_uint16_t)rr->dnsclass); /* class */ + write32(p+4, rr->ttl); /* TTL */ p += 8; size -= 8; if (rr->type == PJ_DNS_TYPE_A) { - if (size < 6) - return -1; + if (size < 6) + return -1; - /* RDLEN is 4 */ - write16(p, 4); + /* RDLEN is 4 */ + write16(p, 4); - /* Address */ - pj_memcpy(p+2, &rr->rdata.a.ip_addr, 4); + /* Address */ + pj_memcpy(p+2, &rr->rdata.a.ip_addr, 4); - p += 6; - size -= 6; + p += 6; + size -= 6; } else if (rr->type == PJ_DNS_TYPE_AAAA) { - if (size < 18) - return -1; + if (size < 18) + return -1; - /* RDLEN is 16 */ - write16(p, 16); + /* RDLEN is 16 */ + write16(p, 16); - /* Address */ - pj_memcpy(p+2, &rr->rdata.aaaa.ip_addr, 16); + /* Address */ + pj_memcpy(p+2, &rr->rdata.aaaa.ip_addr, 16); - p += 18; - size -= 18; + p += 18; + size -= 18; } else if (rr->type == PJ_DNS_TYPE_CNAME || - rr->type == PJ_DNS_TYPE_NS || - rr->type == PJ_DNS_TYPE_PTR) { + rr->type == PJ_DNS_TYPE_NS || + rr->type == PJ_DNS_TYPE_PTR) { - if (size < 4) - return -1; + if (size < 4) + return -1; - len = print_name(pkt, size-2, p+2, &rr->rdata.cname.name, tab); - if (len < 0) - return -1; + len = print_name(pkt, size-2, p+2, &rr->rdata.cname.name, tab); + if (len < 0) + return -1; - write16(p, (pj_uint16_t)len); + write16(p, (pj_uint16_t)len); - p += (len + 2); - size -= (len + 2); + p += (len + 2); + size -= (len + 2); } else if (rr->type == PJ_DNS_TYPE_SRV) { - if (size < 10) - return -1; + if (size < 10) + return -1; - write16(p+2, rr->rdata.srv.prio); /* Priority */ - write16(p+4, rr->rdata.srv.weight); /* Weight */ - write16(p+6, rr->rdata.srv.port); /* Port */ + write16(p+2, rr->rdata.srv.prio); /* Priority */ + write16(p+4, rr->rdata.srv.weight); /* Weight */ + write16(p+6, rr->rdata.srv.port); /* Port */ - /* Target */ - len = print_name(pkt, size-8, p+8, &rr->rdata.srv.target, tab); - if (len < 0) - return -1; + /* Target */ + len = print_name(pkt, size-8, p+8, &rr->rdata.srv.target, tab); + if (len < 0) + return -1; - /* RDLEN */ - write16(p, (pj_uint16_t)(len + 6)); + /* RDLEN */ + write16(p, (pj_uint16_t)(len + 6)); - p += (len + 8); - size -= (len + 8); + p += (len + 8); + size -= (len + 8); } else { - pj_assert(!"Not supported"); - return -1; + pj_assert(!"Not supported"); + return -1; } return (int)(p-pos); } static int print_packet(const pj_dns_parsed_packet *rec, pj_uint8_t *pkt, - int size) + int size) { pj_uint8_t *p = pkt; struct label_tab tab; @@ -270,7 +269,7 @@ static int print_packet(const pj_dns_parsed_packet *rec, pj_uint8_t *pkt, pj_assert(sizeof(pj_dns_hdr)==12); if (size < (int)sizeof(pj_dns_hdr)) - return -1; + return -1; /* Initialize header */ write16(p+0, rec->hdr.id); @@ -286,54 +285,54 @@ static int print_packet(const pj_dns_parsed_packet *rec, pj_uint8_t *pkt, /* Print queries */ for (i=0; ihdr.qdcount; ++i) { - len = print_name(pkt, size, p, &rec->q[i].name, &tab); - if (len < 0) - return -1; + len = print_name(pkt, size, p, &rec->q[i].name, &tab); + if (len < 0) + return -1; - p += len; - size -= len; + p += len; + size -= len; - if (size < 4) - return -1; + if (size < 4) + return -1; - /* Set type */ - write16(p+0, (pj_uint16_t)rec->q[i].type); + /* Set type */ + write16(p+0, (pj_uint16_t)rec->q[i].type); - /* Set class (IN=1) */ - pj_assert(rec->q[i].dnsclass == 1); - write16(p+2, rec->q[i].dnsclass); + /* Set class (IN=1) */ + pj_assert(rec->q[i].dnsclass == 1); + write16(p+2, rec->q[i].dnsclass); - p += 4; + p += 4; } /* Print answers */ for (i=0; ihdr.anscount; ++i) { - len = print_rr(pkt, size, p, &rec->ans[i], &tab); - if (len < 0) - return -1; + len = print_rr(pkt, size, p, &rec->ans[i], &tab); + if (len < 0) + return -1; - p += len; - size -= len; + p += len; + size -= len; } /* Print NS records */ for (i=0; ihdr.nscount; ++i) { - len = print_rr(pkt, size, p, &rec->ns[i], &tab); - if (len < 0) - return -1; + len = print_rr(pkt, size, p, &rec->ns[i], &tab); + if (len < 0) + return -1; - p += len; - size -= len; + p += len; + size -= len; } /* Print additional records */ for (i=0; ihdr.arcount; ++i) { - len = print_rr(pkt, size, p, &rec->arr[i], &tab); - if (len < 0) - return -1; + len = print_rr(pkt, size, p, &rec->arr[i], &tab); + if (len < 0) + return -1; - p += len; - size -= len; + p += len; + size -= len; } return (int)(p - pkt); @@ -345,70 +344,70 @@ static int server_thread(void *p) struct server_t *srv = (struct server_t*)p; while (!thread_quit) { - pj_fd_set_t rset; - pj_time_val timeout = {0, 500}; - pj_sockaddr src_addr; - pj_dns_parsed_packet *req; - char pkt[1024]; - pj_ssize_t pkt_len; - int rc, src_len; - - PJ_FD_ZERO(&rset); - PJ_FD_SET(srv->sock, &rset); - - rc = pj_sock_select((int)(srv->sock+1), &rset, NULL, NULL, &timeout); - if (rc != 1) - continue; - - src_len = sizeof(src_addr); - pkt_len = sizeof(pkt); - rc = pj_sock_recvfrom(srv->sock, pkt, &pkt_len, 0, - &src_addr, &src_len); - if (rc != 0) { - app_perror("Server error receiving packet", rc); - continue; - } - - PJ_LOG(5,(THIS_FILE, "Server %d processing packet", srv - &g_server[0])); - srv->pkt_count++; - - rc = pj_dns_parse_packet(pool, pkt, (unsigned)pkt_len, &req); - if (rc != PJ_SUCCESS) { - app_perror("server error parsing packet", rc); - continue; - } - - /* Verify packet */ - if (req->hdr.qdcount != 1) { - PJ_LOG(5,(THIS_FILE, "server receive multiple queries in a packet")); - continue; - } - - if (req->q[0].dnsclass != 1) { - PJ_LOG(5,(THIS_FILE, "server receive query with invalid DNS class")); - continue; - } - - /* Simulate network RTT */ - pj_thread_sleep(50); - - if (srv->action == ACTION_IGNORE) { - continue; - } else if (srv->action == ACTION_REPLY) { - srv->resp.hdr.id = req->hdr.id; - pkt_len = print_packet(&srv->resp, (pj_uint8_t*)pkt, sizeof(pkt)); - pj_sock_sendto(srv->sock, pkt, &pkt_len, 0, &src_addr, src_len); - } else if (srv->action == ACTION_CB) { - pj_dns_parsed_packet *resp; - (*srv->action_cb)(req, &resp); - resp->hdr.id = req->hdr.id; - pkt_len = print_packet(resp, (pj_uint8_t*)pkt, sizeof(pkt)); - pj_sock_sendto(srv->sock, pkt, &pkt_len, 0, &src_addr, src_len); - } else if (srv->action > 0) { - req->hdr.flags |= PJ_DNS_SET_RCODE(srv->action); - pkt_len = print_packet(req, (pj_uint8_t*)pkt, sizeof(pkt)); - pj_sock_sendto(srv->sock, pkt, &pkt_len, 0, &src_addr, src_len); - } + pj_fd_set_t rset; + pj_time_val timeout = {0, 500}; + pj_sockaddr src_addr; + pj_dns_parsed_packet *req; + char pkt[1024]; + pj_ssize_t pkt_len; + int rc, src_len; + + PJ_FD_ZERO(&rset); + PJ_FD_SET(srv->sock, &rset); + + rc = pj_sock_select((int)(srv->sock+1), &rset, NULL, NULL, &timeout); + if (rc != 1) + continue; + + src_len = sizeof(src_addr); + pkt_len = sizeof(pkt); + rc = pj_sock_recvfrom(srv->sock, pkt, &pkt_len, 0, + &src_addr, &src_len); + if (rc != 0) { + app_perror("Server error receiving packet", rc); + continue; + } + + PJ_LOG(5,(THIS_FILE, "Server %d processing packet", srv - &g_server[0])); + srv->pkt_count++; + + rc = pj_dns_parse_packet(pool, pkt, (unsigned)pkt_len, &req); + if (rc != PJ_SUCCESS) { + app_perror("server error parsing packet", rc); + continue; + } + + /* Verify packet */ + if (req->hdr.qdcount != 1) { + PJ_LOG(5,(THIS_FILE, "server receive multiple queries in a packet")); + continue; + } + + if (req->q[0].dnsclass != 1) { + PJ_LOG(5,(THIS_FILE, "server receive query with invalid DNS class")); + continue; + } + + /* Simulate network RTT */ + pj_thread_sleep(50); + + if (srv->action == ACTION_IGNORE) { + continue; + } else if (srv->action == ACTION_REPLY) { + srv->resp.hdr.id = req->hdr.id; + pkt_len = print_packet(&srv->resp, (pj_uint8_t*)pkt, sizeof(pkt)); + pj_sock_sendto(srv->sock, pkt, &pkt_len, 0, &src_addr, src_len); + } else if (srv->action == ACTION_CB) { + pj_dns_parsed_packet *resp; + (*srv->action_cb)(req, &resp); + resp->hdr.id = req->hdr.id; + pkt_len = print_packet(resp, (pj_uint8_t*)pkt, sizeof(pkt)); + pj_sock_sendto(srv->sock, pkt, &pkt_len, 0, &src_addr, src_len); + } else if (srv->action > 0) { + req->hdr.flags |= PJ_DNS_SET_RCODE(srv->action); + pkt_len = print_packet(req, (pj_uint8_t*)pkt, sizeof(pkt)); + pj_sock_sendto(srv->sock, pkt, &pkt_len, 0, &src_addr, src_len); + } } return 0; @@ -419,9 +418,9 @@ static int poll_worker_thread(void *p) PJ_UNUSED_ARG(p); while (!thread_quit) { - pj_time_val delay = {0, 100}; - pj_timer_heap_poll(timer_heap, NULL); - pj_ioqueue_poll(ioqueue, &delay); + pj_time_val delay = {0, 100}; + pj_timer_heap_poll(timer_heap, NULL); + pj_ioqueue_poll(ioqueue, &delay); } return 0; @@ -437,11 +436,11 @@ static int init(pj_bool_t use_ipv6) int i; if (use_ipv6) { - nameservers[0] = pj_str("::1"); - nameservers[1] = pj_str("::1"); + nameservers[0] = pj_str("::1"); + nameservers[1] = pj_str("::1"); } else { - nameservers[0] = pj_str("127.0.0.1"); - nameservers[1] = pj_str("127.0.0.1"); + nameservers[0] = pj_str("127.0.0.1"); + nameservers[1] = pj_str("127.0.0.1"); } ports[0] = 5553; ports[1] = 5554; @@ -457,24 +456,24 @@ static int init(pj_bool_t use_ipv6) thread_quit = PJ_FALSE; for (i=0; i<2; ++i) { - pj_sockaddr addr; + pj_sockaddr addr; - status = pj_sock_socket((use_ipv6? pj_AF_INET6() : pj_AF_INET()), - pj_SOCK_DGRAM(), 0, &g_server[i].sock); - if (status != PJ_SUCCESS) - return -10; + status = pj_sock_socket((use_ipv6? pj_AF_INET6() : pj_AF_INET()), + pj_SOCK_DGRAM(), 0, &g_server[i].sock); + if (status != PJ_SUCCESS) + return -10; - pj_sockaddr_init((use_ipv6? pj_AF_INET6() : pj_AF_INET()), - &addr, NULL, (pj_uint16_t)g_server[i].port); + pj_sockaddr_init((use_ipv6? pj_AF_INET6() : pj_AF_INET()), + &addr, NULL, (pj_uint16_t)g_server[i].port); - status = pj_sock_bind(g_server[i].sock, &addr, pj_sockaddr_get_len(&addr)); - if (status != PJ_SUCCESS) - return -20; + status = pj_sock_bind(g_server[i].sock, &addr, pj_sockaddr_get_len(&addr)); + if (status != PJ_SUCCESS) + return -20; - status = pj_thread_create(pool, NULL, &server_thread, &g_server[i], - 0, 0, &g_server[i].thread); - if (status != PJ_SUCCESS) - return -30; + status = pj_thread_create(pool, NULL, &server_thread, &g_server[i], + 0, 0, &g_server[i].thread); + if (status != PJ_SUCCESS) + return -30; } status = pj_timer_heap_create(pool, 16, &timer_heap); @@ -485,7 +484,7 @@ static int init(pj_bool_t use_ipv6) status = pj_dns_resolver_create(mem, NULL, 0, timer_heap, ioqueue, &resolver); if (status != PJ_SUCCESS) - return -40; + return -40; pj_dns_resolver_get_settings(resolver, &set); set.good_ns_ttl = 20; @@ -509,8 +508,8 @@ static void destroy(void) thread_quit = PJ_TRUE; for (i=0; i<2; ++i) { - pj_thread_join(g_server[i].thread); - pj_sock_close(g_server[i].sock); + pj_thread_join(g_server[i].thread); + pj_sock_close(g_server[i].sock); } pj_thread_join(poll_thread); @@ -536,7 +535,7 @@ static int a_parser_test(void) pkt.q = PJ_POOL_ZALLOC_T(pool, pj_dns_parsed_query); pkt.ans = (pj_dns_parsed_rr*) - pj_pool_calloc(pool, 32, sizeof(pj_dns_parsed_rr)); + pj_pool_calloc(pool, 32, sizeof(pj_dns_parsed_rr)); /* Simple answer with direct A record, but with addition of * a CNAME and another A to confuse the parser. @@ -738,7 +737,7 @@ static int addr_parser_test(void) pkt.q = PJ_POOL_ZALLOC_T(pool, pj_dns_parsed_query); pkt.ans = (pj_dns_parsed_rr*) - pj_pool_calloc(pool, 32, sizeof(pj_dns_parsed_rr)); + pj_pool_calloc(pool, 32, sizeof(pj_dns_parsed_rr)); /* Simple answer with direct A record, but with addition of * a CNAME and another A to confuse the parser. @@ -941,8 +940,8 @@ static int addr_parser_test(void) #define IP_ADDR0 0x00010203 static void dns_callback(void *user_data, - pj_status_t status, - pj_dns_parsed_packet *resp) + pj_status_t status, + pj_dns_parsed_packet *resp) { PJ_UNUSED_ARG(user_data); @@ -997,9 +996,9 @@ static int simple_test(void) r->ans[0].rdata.a.ip_addr.s_addr = IP_ADDR0; status = pj_dns_resolver_start_query(resolver, &name, PJ_DNS_TYPE_A, 0, - &dns_callback, NULL, NULL); + &dns_callback, NULL, NULL); if (status != PJ_SUCCESS) - return -1000; + return -1000; pj_sem_wait(sem); pj_thread_sleep(1000); @@ -1017,8 +1016,8 @@ static int simple_test(void) /* DNS nameserver fail-over test */ static void dns_callback_1b(void *user_data, - pj_status_t status, - pj_dns_parsed_packet *resp) + pj_status_t status, + pj_dns_parsed_packet *resp) { PJ_UNUSED_ARG(user_data); PJ_UNUSED_ARG(resp); @@ -1026,7 +1025,7 @@ static void dns_callback_1b(void *user_data, pj_sem_post(sem); PJ_ASSERT_ON_FAIL(status==PJ_STATUS_FROM_DNS_RCODE(PJ_DNS_RCODE_NXDOMAIN), - return); + return); } @@ -1047,9 +1046,9 @@ static int dns_test(void) g_server[1].action = PJ_DNS_RCODE_NXDOMAIN; status = pj_dns_resolver_start_query(resolver, &name, PJ_DNS_TYPE_A, 0, - &dns_callback_1b, NULL, NULL); + &dns_callback_1b, NULL, NULL); if (status != PJ_SUCCESS) - return -1000; + return -1000; pj_sem_wait(sem); pj_thread_sleep(1000); @@ -1061,7 +1060,7 @@ static int dns_test(void) /* Wait to allow active period to complete and get into probing state */ PJ_LOG(3,(THIS_FILE, " waiting for active NS to expire (%d sec)", - set.good_ns_ttl)); + set.good_ns_ttl)); pj_thread_sleep(set.good_ns_ttl * 1000); /* @@ -1076,9 +1075,9 @@ static int dns_test(void) name = pj_str("name01"); status = pj_dns_resolver_start_query(resolver, &name, PJ_DNS_TYPE_A, 0, - &dns_callback_1b, NULL, NULL); + &dns_callback_1b, NULL, NULL); if (status != PJ_SUCCESS) - return -1000; + return -1000; pj_sem_wait(sem); @@ -1098,9 +1097,9 @@ static int dns_test(void) name = pj_str("name02"); status = pj_dns_resolver_start_query(resolver, &name, PJ_DNS_TYPE_A, 0, - &dns_callback_1b, NULL, NULL); + &dns_callback_1b, NULL, NULL); if (status != PJ_SUCCESS) - return -1000; + return -1000; pj_sem_wait(sem); pj_thread_sleep(1000); @@ -1110,8 +1109,8 @@ static int dns_test(void) /* Wait to allow probing period to complete, server 0 will be in bad state */ PJ_LOG(3,(THIS_FILE, " waiting for probing state to end (%d sec)", - set.qretr_delay * - (set.qretr_count+2) / 1000)); + set.qretr_delay * + (set.qretr_count+2) / 1000)); pj_thread_sleep(set.qretr_delay * (set.qretr_count + 2)); @@ -1127,9 +1126,9 @@ static int dns_test(void) name = pj_str("name03"); status = pj_dns_resolver_start_query(resolver, &name, PJ_DNS_TYPE_A, 0, - &dns_callback_1b, NULL, NULL); + &dns_callback_1b, NULL, NULL); if (status != PJ_SUCCESS) - return -1000; + return -1000; pj_sem_wait(sem); pj_thread_sleep(1000); @@ -1140,7 +1139,7 @@ static int dns_test(void) /* Wait to allow active & bad period to complete, both will be in probing state */ PJ_LOG(3,(THIS_FILE, " waiting for active NS to expire (%d sec)", - set.good_ns_ttl)); + set.good_ns_ttl)); pj_thread_sleep(set.good_ns_ttl * 1000); /* @@ -1154,15 +1153,15 @@ static int dns_test(void) name = pj_str("name04"); status = pj_dns_resolver_start_query(resolver, &name, PJ_DNS_TYPE_A, 0, - &dns_callback_1b, NULL, NULL); + &dns_callback_1b, NULL, NULL); if (status != PJ_SUCCESS) - return -1000; + return -1000; pj_sem_wait(sem); /* Wait to allow probing period to complete, server 0 remains active, server 1 will be bad */ PJ_LOG(3,(THIS_FILE, " waiting for probing state (%d sec)", - set.qretr_delay * (set.qretr_count+2) / 1000)); + set.qretr_delay * (set.qretr_count+2) / 1000)); pj_thread_sleep(1000 + set.qretr_delay * (set.qretr_count + 2)); /* @@ -1177,9 +1176,9 @@ static int dns_test(void) name = pj_str("name05"); status = pj_dns_resolver_start_query(resolver, &name, PJ_DNS_TYPE_A, 0, - &dns_callback_1b, NULL, NULL); + &dns_callback_1b, NULL, NULL); if (status != PJ_SUCCESS) - return -1000; + return -1000; pj_sem_wait(sem); pj_thread_sleep(1000); @@ -1196,10 +1195,10 @@ static int dns_test(void) //////////////////////////////////////////////////////////////////////////// /* Resolver test, normal, with CNAME */ #define IP_ADDR1 0x02030405 -#define PORT1 50061 +#define PORT1 50061 static void action1_1(const pj_dns_parsed_packet *pkt, - pj_dns_parsed_packet **p_res) + pj_dns_parsed_packet **p_res) { pj_dns_parsed_packet *res; char *target = "sip.somedomain.com"; @@ -1207,11 +1206,11 @@ static void action1_1(const pj_dns_parsed_packet *pkt, res = PJ_POOL_ZALLOC_T(pool, pj_dns_parsed_packet); if (res->q == NULL) { - res->q = PJ_POOL_ZALLOC_T(pool, pj_dns_parsed_query); + res->q = PJ_POOL_ZALLOC_T(pool, pj_dns_parsed_query); } if (res->ans == NULL) { - res->ans = (pj_dns_parsed_rr*) - pj_pool_calloc(pool, 4, sizeof(pj_dns_parsed_rr)); + res->ans = (pj_dns_parsed_rr*) + pj_pool_calloc(pool, 4, sizeof(pj_dns_parsed_rr)); } res->hdr.qdcount = 1; @@ -1221,64 +1220,64 @@ static void action1_1(const pj_dns_parsed_packet *pkt, if (pkt->q[0].type == PJ_DNS_TYPE_SRV) { - pj_assert(pj_strcmp2(&pkt->q[0].name, "_sip._udp.somedomain.com")==0); + pj_assert(pj_strcmp2(&pkt->q[0].name, "_sip._udp.somedomain.com")==0); - res->hdr.anscount = 1; - res->ans[0].type = PJ_DNS_TYPE_SRV; - res->ans[0].dnsclass = 1; - res->ans[0].name = res->q[0].name; - res->ans[0].ttl = 1; - res->ans[0].rdata.srv.prio = 1; - res->ans[0].rdata.srv.weight = 2; - res->ans[0].rdata.srv.port = PORT1; - res->ans[0].rdata.srv.target = pj_str(target); + res->hdr.anscount = 1; + res->ans[0].type = PJ_DNS_TYPE_SRV; + res->ans[0].dnsclass = 1; + res->ans[0].name = res->q[0].name; + res->ans[0].ttl = 1; + res->ans[0].rdata.srv.prio = 1; + res->ans[0].rdata.srv.weight = 2; + res->ans[0].rdata.srv.port = PORT1; + res->ans[0].rdata.srv.target = pj_str(target); } else if (pkt->q[0].type == PJ_DNS_TYPE_A) { - char *alias = "sipalias.somedomain.com"; + char *alias = "sipalias.somedomain.com"; - pj_assert(pj_strcmp2(&res->q[0].name, target)==0); + pj_assert(pj_strcmp2(&res->q[0].name, target)==0); - res->hdr.anscount = 2; - res->ans[0].type = PJ_DNS_TYPE_CNAME; - res->ans[0].dnsclass = 1; - res->ans[0].ttl = 1000; /* resolver should select minimum TTL */ - res->ans[0].name = res->q[0].name; - res->ans[0].rdata.cname.name = pj_str(alias); + res->hdr.anscount = 2; + res->ans[0].type = PJ_DNS_TYPE_CNAME; + res->ans[0].dnsclass = 1; + res->ans[0].ttl = 1000; /* resolver should select minimum TTL */ + res->ans[0].name = res->q[0].name; + res->ans[0].rdata.cname.name = pj_str(alias); - res->ans[1].type = PJ_DNS_TYPE_A; - res->ans[1].dnsclass = 1; - res->ans[1].ttl = 1; - res->ans[1].name = pj_str(alias); - res->ans[1].rdata.a.ip_addr.s_addr = IP_ADDR1; + res->ans[1].type = PJ_DNS_TYPE_A; + res->ans[1].dnsclass = 1; + res->ans[1].ttl = 1; + res->ans[1].name = pj_str(alias); + res->ans[1].rdata.a.ip_addr.s_addr = IP_ADDR1; } else if (pkt->q[0].type == PJ_DNS_TYPE_AAAA) { - char *alias = "sipalias.somedomain.com"; - - pj_assert(pj_strcmp2(&res->q[0].name, target)==0); - - res->hdr.anscount = 2; - res->ans[0].type = PJ_DNS_TYPE_CNAME; - res->ans[0].dnsclass = 1; - res->ans[0].ttl = 1000; /* resolver should select minimum TTL */ - res->ans[0].name = res->q[0].name; - res->ans[0].rdata.cname.name = pj_str(alias); - - res->ans[1].type = PJ_DNS_TYPE_AAAA; - res->ans[1].dnsclass = 1; - res->ans[1].ttl = 1; - res->ans[1].name = pj_str(alias); - s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 0) = IP_ADDR1; - s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 1) = IP_ADDR1; - s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 2) = IP_ADDR1; - s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 3) = IP_ADDR1; + char *alias = "sipalias.somedomain.com"; + + pj_assert(pj_strcmp2(&res->q[0].name, target)==0); + + res->hdr.anscount = 2; + res->ans[0].type = PJ_DNS_TYPE_CNAME; + res->ans[0].dnsclass = 1; + res->ans[0].ttl = 1000; /* resolver should select minimum TTL */ + res->ans[0].name = res->q[0].name; + res->ans[0].rdata.cname.name = pj_str(alias); + + res->ans[1].type = PJ_DNS_TYPE_AAAA; + res->ans[1].dnsclass = 1; + res->ans[1].ttl = 1; + res->ans[1].name = pj_str(alias); + s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 0) = IP_ADDR1; + s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 1) = IP_ADDR1; + s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 2) = IP_ADDR1; + s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 3) = IP_ADDR1; } *p_res = res; } static void srv_cb_1(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec) + pj_status_t status, + const pj_dns_srv_record *rec) { PJ_UNUSED_ARG(user_data); @@ -1289,9 +1288,9 @@ static void srv_cb_1(void *user_data, PJ_ASSERT_ON_FAIL(rec->entry[0].priority == 1, return); PJ_ASSERT_ON_FAIL(rec->entry[0].weight == 2, return); PJ_ASSERT_ON_FAIL(pj_strcmp2(&rec->entry[0].server.name, "sip.somedomain.com")==0, - return); + return); PJ_ASSERT_ON_FAIL(pj_strcmp2(&rec->entry[0].server.alias, "sipalias.somedomain.com")==0, - return); + return); /* IPv4 only */ PJ_ASSERT_ON_FAIL(rec->entry[0].server.addr_count == 1, return); @@ -1303,22 +1302,22 @@ static void srv_cb_1(void *user_data, static void srv_cb_1b(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec) + pj_status_t status, + const pj_dns_srv_record *rec) { PJ_UNUSED_ARG(user_data); pj_sem_post(sem); PJ_ASSERT_ON_FAIL(status==PJ_STATUS_FROM_DNS_RCODE(PJ_DNS_RCODE_NXDOMAIN), - return); + return); PJ_ASSERT_ON_FAIL(rec->count == 0, return); } static void srv_cb_1c(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec) + pj_status_t status, + const pj_dns_srv_record *rec) { PJ_UNUSED_ARG(user_data); @@ -1330,23 +1329,23 @@ static void srv_cb_1c(void *user_data, PJ_ASSERT_ON_FAIL(rec->entry[0].weight == 2, return); PJ_ASSERT_ON_FAIL(pj_strcmp2(&rec->entry[0].server.name, "sip.somedomain.com")==0, - return); + return); PJ_ASSERT_ON_FAIL(pj_strcmp2(&rec->entry[0].server.alias, "sipalias.somedomain.com")==0, - return); + return); PJ_ASSERT_ON_FAIL(rec->entry[0].port == PORT1, return); /* IPv4 and IPv6 */ PJ_ASSERT_ON_FAIL(rec->entry[0].server.addr_count == 2, return); PJ_ASSERT_ON_FAIL(rec->entry[0].server.addr[0].af == pj_AF_INET() && - rec->entry[0].server.addr[0].ip.v4.s_addr == IP_ADDR1, return); + rec->entry[0].server.addr[0].ip.v4.s_addr == IP_ADDR1, return); PJ_ASSERT_ON_FAIL(rec->entry[0].server.addr[1].af == pj_AF_INET6() && - s6_addr32(rec->entry[0].server.addr[1].ip.v6, 0) == IP_ADDR1, return); + s6_addr32(rec->entry[0].server.addr[1].ip.v6, 0) == IP_ADDR1, return); } static void srv_cb_1d(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec) + pj_status_t status, + const pj_dns_srv_record *rec) { PJ_UNUSED_ARG(user_data); @@ -1358,15 +1357,15 @@ static void srv_cb_1d(void *user_data, PJ_ASSERT_ON_FAIL(rec->entry[0].weight == 2, return); PJ_ASSERT_ON_FAIL(pj_strcmp2(&rec->entry[0].server.name, "sip.somedomain.com")==0, - return); + return); PJ_ASSERT_ON_FAIL(pj_strcmp2(&rec->entry[0].server.alias, "sipalias.somedomain.com")==0, - return); + return); PJ_ASSERT_ON_FAIL(rec->entry[0].port == PORT1, return); /* IPv6 only */ PJ_ASSERT_ON_FAIL(rec->entry[0].server.addr_count == 1, return); PJ_ASSERT_ON_FAIL(rec->entry[0].server.addr[0].af == pj_AF_INET6() && - s6_addr32(rec->entry[0].server.addr[0].ip.v6, 0) == IP_ADDR1, return); + s6_addr32(rec->entry[0].server.addr[0].ip.v6, 0) == IP_ADDR1, return); } @@ -1390,7 +1389,7 @@ static int srv_resolver_test(void) g_server[1].pkt_count = 0; status = pj_dns_srv_resolve(&domain, &res_name, 5061, pool, resolver, PJ_TRUE, - NULL, &srv_cb_1, NULL); + NULL, &srv_cb_1, NULL); pj_assert(status == PJ_SUCCESS); pj_sem_wait(sem); @@ -1417,8 +1416,8 @@ static int srv_resolver_test(void) g_server[1].pkt_count = 0; status = pj_dns_srv_resolve(&domain, &res_name, 5061, pool, resolver, - PJ_DNS_SRV_RESOLVE_AAAA, - NULL, &srv_cb_1c, NULL); + PJ_DNS_SRV_RESOLVE_AAAA, + NULL, &srv_cb_1c, NULL); pj_assert(status == PJ_SUCCESS); pj_sem_wait(sem); @@ -1436,8 +1435,8 @@ static int srv_resolver_test(void) g_server[1].pkt_count = 0; status = pj_dns_srv_resolve(&domain, &res_name, 5061, pool, resolver, - PJ_DNS_SRV_RESOLVE_AAAA_ONLY, - NULL, &srv_cb_1d, NULL); + PJ_DNS_SRV_RESOLVE_AAAA_ONLY, + NULL, &srv_cb_1d, NULL); pj_assert(status == PJ_SUCCESS); pj_sem_wait(sem); @@ -1450,12 +1449,12 @@ static int srv_resolver_test(void) g_server[1].pkt_count = 0; status = pj_dns_srv_resolve(&domain, &res_name, 5061, pool, resolver, PJ_TRUE, - NULL, &srv_cb_1, NULL); + NULL, &srv_cb_1, NULL); pj_assert(status == PJ_SUCCESS); status = pj_dns_srv_resolve(&domain, &res_name, 5061, pool, resolver, PJ_TRUE, - NULL, &srv_cb_1, NULL); + NULL, &srv_cb_1, NULL); pj_assert(status == PJ_SUCCESS); pj_sem_wait(sem); @@ -1474,7 +1473,7 @@ static int srv_resolver_test(void) g_server[1].action = PJ_DNS_RCODE_NXDOMAIN; status = pj_dns_srv_resolve(&domain, &res_name, 5061, pool, resolver, PJ_TRUE, - NULL, &srv_cb_1b, NULL); + NULL, &srv_cb_1b, NULL); pj_assert(status == PJ_SUCCESS); pj_sem_wait(sem); @@ -1486,12 +1485,12 @@ static int srv_resolver_test(void) //////////////////////////////////////////////////////////////////////////// /* Fallback because there's no SRV in answer */ -#define TARGET "domain2.com" +#define TARGET "domain2.com" #define IP_ADDR2 0x02030405 -#define PORT2 50062 +#define PORT2 50062 static void action2_1(const pj_dns_parsed_packet *pkt, - pj_dns_parsed_packet **p_res) + pj_dns_parsed_packet **p_res) { pj_dns_parsed_packet *res; @@ -1499,7 +1498,7 @@ static void action2_1(const pj_dns_parsed_packet *pkt, res->q = PJ_POOL_ZALLOC_T(pool, pj_dns_parsed_query); res->ans = (pj_dns_parsed_rr*) - pj_pool_calloc(pool, 4, sizeof(pj_dns_parsed_rr)); + pj_pool_calloc(pool, 4, sizeof(pj_dns_parsed_rr)); res->hdr.qdcount = 1; res->q[0].type = pkt->q[0].type; @@ -1508,56 +1507,56 @@ static void action2_1(const pj_dns_parsed_packet *pkt, if (pkt->q[0].type == PJ_DNS_TYPE_SRV) { - pj_assert(pj_strcmp2(&pkt->q[0].name, "_sip._udp." TARGET)==0); + pj_assert(pj_strcmp2(&pkt->q[0].name, "_sip._udp." TARGET)==0); - res->hdr.anscount = 1; - res->ans[0].type = PJ_DNS_TYPE_A; // <-- this will cause the fallback - res->ans[0].dnsclass = 1; - res->ans[0].name = res->q[0].name; - res->ans[0].ttl = 1; - res->ans[0].rdata.srv.prio = 1; - res->ans[0].rdata.srv.weight = 2; - res->ans[0].rdata.srv.port = PORT2; - res->ans[0].rdata.srv.target = pj_str("sip01." TARGET); + res->hdr.anscount = 1; + res->ans[0].type = PJ_DNS_TYPE_A; // <-- this will cause the fallback + res->ans[0].dnsclass = 1; + res->ans[0].name = res->q[0].name; + res->ans[0].ttl = 1; + res->ans[0].rdata.srv.prio = 1; + res->ans[0].rdata.srv.weight = 2; + res->ans[0].rdata.srv.port = PORT2; + res->ans[0].rdata.srv.target = pj_str("sip01." TARGET); } else if (pkt->q[0].type == PJ_DNS_TYPE_A) { - char *alias = "sipalias01." TARGET; + char *alias = "sipalias01." TARGET; - pj_assert(pj_strcmp2(&res->q[0].name, TARGET)==0); + pj_assert(pj_strcmp2(&res->q[0].name, TARGET)==0); - res->hdr.anscount = 2; - res->ans[0].type = PJ_DNS_TYPE_CNAME; - res->ans[0].dnsclass = 1; - res->ans[0].name = res->q[0].name; - res->ans[0].ttl = 1; - res->ans[0].rdata.cname.name = pj_str(alias); + res->hdr.anscount = 2; + res->ans[0].type = PJ_DNS_TYPE_CNAME; + res->ans[0].dnsclass = 1; + res->ans[0].name = res->q[0].name; + res->ans[0].ttl = 1; + res->ans[0].rdata.cname.name = pj_str(alias); - res->ans[1].type = PJ_DNS_TYPE_A; - res->ans[1].dnsclass = 1; - res->ans[1].name = pj_str(alias); - res->ans[1].ttl = 1; - res->ans[1].rdata.a.ip_addr.s_addr = IP_ADDR2; + res->ans[1].type = PJ_DNS_TYPE_A; + res->ans[1].dnsclass = 1; + res->ans[1].name = pj_str(alias); + res->ans[1].ttl = 1; + res->ans[1].rdata.a.ip_addr.s_addr = IP_ADDR2; } else if (pkt->q[0].type == PJ_DNS_TYPE_AAAA) { - char *alias = "sipalias01." TARGET; - - pj_assert(pj_strcmp2(&res->q[0].name, TARGET)==0); - - res->hdr.anscount = 2; - res->ans[0].type = PJ_DNS_TYPE_CNAME; - res->ans[0].dnsclass = 1; - res->ans[0].name = res->q[0].name; - res->ans[0].ttl = 1; - res->ans[0].rdata.cname.name = pj_str(alias); - - res->ans[1].type = PJ_DNS_TYPE_AAAA; - res->ans[1].dnsclass = 1; - res->ans[1].ttl = 1; - res->ans[1].name = pj_str(alias); - s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 0) = IP_ADDR2; - s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 1) = IP_ADDR2; - s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 2) = IP_ADDR2; - s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 3) = IP_ADDR2; + char *alias = "sipalias01." TARGET; + + pj_assert(pj_strcmp2(&res->q[0].name, TARGET)==0); + + res->hdr.anscount = 2; + res->ans[0].type = PJ_DNS_TYPE_CNAME; + res->ans[0].dnsclass = 1; + res->ans[0].name = res->q[0].name; + res->ans[0].ttl = 1; + res->ans[0].rdata.cname.name = pj_str(alias); + + res->ans[1].type = PJ_DNS_TYPE_AAAA; + res->ans[1].dnsclass = 1; + res->ans[1].ttl = 1; + res->ans[1].name = pj_str(alias); + s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 0) = IP_ADDR2; + s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 1) = IP_ADDR2; + s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 2) = IP_ADDR2; + s6_addr32(res->ans[1].rdata.aaaa.ip_addr, 3) = IP_ADDR2; } *p_res = res; @@ -1566,8 +1565,8 @@ static void action2_1(const pj_dns_parsed_packet *pkt, #define SRV_CB_CHECK(cond, err) if(!(cond)) { *cb_err=err; goto on_return; } static void srv_cb_2(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec) + pj_status_t status, + const pj_dns_srv_record *rec) { int *cb_err = (int*)user_data; @@ -1577,21 +1576,21 @@ static void srv_cb_2(void *user_data, SRV_CB_CHECK(rec->entry[0].weight == 0, -40); SRV_CB_CHECK(pj_strcmp2(&rec->entry[0].server.name, TARGET)==0, -50); SRV_CB_CHECK(pj_strcmp2(&rec->entry[0].server.alias, - "sipalias01." TARGET)==0, -60); + "sipalias01." TARGET)==0, -60); SRV_CB_CHECK(rec->entry[0].port == PORT2, -70); /* IPv4 only */ SRV_CB_CHECK(rec->entry[0].server.addr_count == 1, -80); SRV_CB_CHECK(rec->entry[0].server.addr[0].af == pj_AF_INET() && - rec->entry[0].server.addr[0].ip.v4.s_addr == IP_ADDR2, -90); + rec->entry[0].server.addr[0].ip.v4.s_addr == IP_ADDR2, -90); on_return: pj_sem_post(sem); } static void srv_cb_2a(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec) + pj_status_t status, + const pj_dns_srv_record *rec) { int *cb_err = (int*)user_data; @@ -1601,24 +1600,24 @@ static void srv_cb_2a(void *user_data, SRV_CB_CHECK(rec->entry[0].weight == 0, -40); SRV_CB_CHECK(pj_strcmp2(&rec->entry[0].server.name, TARGET)==0, -50); SRV_CB_CHECK(pj_strcmp2(&rec->entry[0].server.alias, - "sipalias01." TARGET)==0, -60); + "sipalias01." TARGET)==0, -60); SRV_CB_CHECK(rec->entry[0].port == PORT2, -70); /* IPv4 and IPv6 */ SRV_CB_CHECK(rec->entry[0].server.addr_count == 2, -80); SRV_CB_CHECK(rec->entry[0].server.addr[0].af == pj_AF_INET() && - rec->entry[0].server.addr[0].ip.v4.s_addr == IP_ADDR2, -90); + rec->entry[0].server.addr[0].ip.v4.s_addr == IP_ADDR2, -90); SRV_CB_CHECK(rec->entry[0].server.addr[1].af == pj_AF_INET6() && - s6_addr32(rec->entry[0].server.addr[1].ip.v6, 0) == IP_ADDR2, - -100); + s6_addr32(rec->entry[0].server.addr[1].ip.v6, 0) == IP_ADDR2, + -100); on_return: pj_sem_post(sem); } static void srv_cb_2b(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec) + pj_status_t status, + const pj_dns_srv_record *rec) { int *cb_err = (int*)user_data; @@ -1628,14 +1627,14 @@ static void srv_cb_2b(void *user_data, SRV_CB_CHECK(rec->entry[0].weight == 0, -40); SRV_CB_CHECK(pj_strcmp2(&rec->entry[0].server.name, TARGET)==0, -50); SRV_CB_CHECK(pj_strcmp2(&rec->entry[0].server.alias, - "sipalias01." TARGET)==0, -60); + "sipalias01." TARGET)==0, -60); SRV_CB_CHECK(rec->entry[0].port == PORT2, -70); /* IPv6 only */ SRV_CB_CHECK(rec->entry[0].server.addr_count == 1, -80); SRV_CB_CHECK(rec->entry[0].server.addr[0].af == pj_AF_INET6() && - s6_addr32(rec->entry[0].server.addr[0].ip.v6, 0) == IP_ADDR2, - -90); + s6_addr32(rec->entry[0].server.addr[0].ip.v6, 0) == IP_ADDR2, + -90); on_return: pj_sem_post(sem); @@ -1657,17 +1656,17 @@ static int srv_resolver_fallback_test(void) g_server[1].action_cb = &action2_1; status = pj_dns_srv_resolve(&domain, &res_name, PORT2, pool, resolver, PJ_TRUE, - &cb_err, &srv_cb_2, NULL); + &cb_err, &srv_cb_2, NULL); if (status != PJ_SUCCESS) { - app_perror(" srv_resolve error", status); - return -10; + app_perror(" srv_resolve error", status); + return -10; } pj_sem_wait(sem); if (cb_err != 0) { - PJ_LOG(3,("test", " srv_resolve cb error, code=%d", cb_err)); - return -20; + PJ_LOG(3,("test", " srv_resolve cb error, code=%d", cb_err)); + return -20; } /* Subsequent query should just get the response from the cache */ @@ -1676,22 +1675,22 @@ static int srv_resolver_fallback_test(void) g_server[1].pkt_count = 0; status = pj_dns_srv_resolve(&domain, &res_name, PORT2, pool, resolver, PJ_TRUE, - &cb_err, &srv_cb_2, NULL); + &cb_err, &srv_cb_2, NULL); if (status != PJ_SUCCESS) { - app_perror(" srv_resolve error", status); - return -30; + app_perror(" srv_resolve error", status); + return -30; } pj_sem_wait(sem); if (cb_err != 0) { - PJ_LOG(3,("test", " srv_resolve cb error, code=%d", cb_err)); - return -40; + PJ_LOG(3,("test", " srv_resolve cb error, code=%d", cb_err)); + return -40; } if (g_server[0].pkt_count != 0 || g_server[1].pkt_count != 0) { - PJ_LOG(3,("test", " srv_resolve() not from cache")); - return -50; + PJ_LOG(3,("test", " srv_resolve() not from cache")); + return -50; } /* Clear cache */ @@ -1706,18 +1705,18 @@ static int srv_resolver_fallback_test(void) g_server[1].action_cb = &action2_1; status = pj_dns_srv_resolve(&domain, &res_name, PORT2, pool, resolver, - PJ_DNS_SRV_FALLBACK_A | PJ_DNS_SRV_FALLBACK_AAAA, - &cb_err, &srv_cb_2a, NULL); + PJ_DNS_SRV_FALLBACK_A | PJ_DNS_SRV_FALLBACK_AAAA, + &cb_err, &srv_cb_2a, NULL); if (status != PJ_SUCCESS) { - app_perror(" srv_resolve error", status); - return -60; + app_perror(" srv_resolve error", status); + return -60; } pj_sem_wait(sem); if (cb_err != 0) { - PJ_LOG(3,("test", " srv_resolve cb error, code=%d", cb_err)); - return -70; + PJ_LOG(3,("test", " srv_resolve cb error, code=%d", cb_err)); + return -70; } /* Clear cache */ @@ -1732,18 +1731,18 @@ static int srv_resolver_fallback_test(void) g_server[1].action_cb = &action2_1; status = pj_dns_srv_resolve(&domain, &res_name, PORT2, pool, resolver, - PJ_DNS_SRV_FALLBACK_AAAA, - &cb_err, &srv_cb_2b, NULL); + PJ_DNS_SRV_FALLBACK_AAAA, + &cb_err, &srv_cb_2b, NULL); if (status != PJ_SUCCESS) { - app_perror(" srv_resolve error", status); - return -80; + app_perror(" srv_resolve error", status); + return -80; } pj_sem_wait(sem); if (cb_err != 0) { - PJ_LOG(3,("test", " srv_resolve cb error, code=%d", cb_err)); - return -90; + PJ_LOG(3,("test", " srv_resolve cb error, code=%d", cb_err)); + return -90; } /* Clear cache */ @@ -1755,14 +1754,14 @@ static int srv_resolver_fallback_test(void) //////////////////////////////////////////////////////////////////////////// /* Too many SRV or A entries */ -#define DOMAIN3 "d3" +#define DOMAIN3 "d3" #define SRV_COUNT3 (PJ_DNS_SRV_MAX_ADDR+1) #define A_COUNT3 (PJ_DNS_MAX_IP_IN_A_REC+1) -#define PORT3 50063 +#define PORT3 50063 #define IP_ADDR3 0x03030303 static void action3_1(const pj_dns_parsed_packet *pkt, - pj_dns_parsed_packet **p_res) + pj_dns_parsed_packet **p_res) { pj_dns_parsed_packet *res; unsigned i; @@ -1770,7 +1769,7 @@ static void action3_1(const pj_dns_parsed_packet *pkt, res = PJ_POOL_ZALLOC_T(pool, pj_dns_parsed_packet); if (res->q == NULL) { - res->q = PJ_POOL_ZALLOC_T(pool, pj_dns_parsed_query); + res->q = PJ_POOL_ZALLOC_T(pool, pj_dns_parsed_query); } res->hdr.qdcount = 1; @@ -1780,51 +1779,51 @@ static void action3_1(const pj_dns_parsed_packet *pkt, if (pkt->q[0].type == PJ_DNS_TYPE_SRV) { - pj_assert(pj_strcmp2(&pkt->q[0].name, "_sip._udp." DOMAIN3)==0); + pj_assert(pj_strcmp2(&pkt->q[0].name, "_sip._udp." DOMAIN3)==0); - res->hdr.anscount = SRV_COUNT3; - res->ans = (pj_dns_parsed_rr*) - pj_pool_calloc(pool, SRV_COUNT3, sizeof(pj_dns_parsed_rr)); + res->hdr.anscount = SRV_COUNT3; + res->ans = (pj_dns_parsed_rr*) + pj_pool_calloc(pool, SRV_COUNT3, sizeof(pj_dns_parsed_rr)); - for (i=0; ians[i].type = PJ_DNS_TYPE_SRV; - res->ans[i].dnsclass = 1; - res->ans[i].name = res->q[0].name; - res->ans[i].ttl = 1; - res->ans[i].rdata.srv.prio = (pj_uint16_t)i; - res->ans[i].rdata.srv.weight = 2; - res->ans[i].rdata.srv.port = (pj_uint16_t)(PORT3+i); + res->ans[i].type = PJ_DNS_TYPE_SRV; + res->ans[i].dnsclass = 1; + res->ans[i].name = res->q[0].name; + res->ans[i].ttl = 1; + res->ans[i].rdata.srv.prio = (pj_uint16_t)i; + res->ans[i].rdata.srv.weight = 2; + res->ans[i].rdata.srv.port = (pj_uint16_t)(PORT3+i); - target = (char*)pj_pool_alloc(pool, 16); - sprintf(target, "sip%02d." DOMAIN3, i); - res->ans[i].rdata.srv.target = pj_str(target); - } + target = (char*)pj_pool_alloc(pool, 16); + sprintf(target, "sip%02d." DOMAIN3, i); + res->ans[i].rdata.srv.target = pj_str(target); + } } else if (pkt->q[0].type == PJ_DNS_TYPE_A) { - //pj_assert(pj_strcmp2(&res->q[0].name, "sip." DOMAIN3)==0); + //pj_assert(pj_strcmp2(&res->q[0].name, "sip." DOMAIN3)==0); - res->hdr.anscount = A_COUNT3; - res->ans = (pj_dns_parsed_rr*) - pj_pool_calloc(pool, A_COUNT3, sizeof(pj_dns_parsed_rr)); + res->hdr.anscount = A_COUNT3; + res->ans = (pj_dns_parsed_rr*) + pj_pool_calloc(pool, A_COUNT3, sizeof(pj_dns_parsed_rr)); - for (i=0; ians[i].type = PJ_DNS_TYPE_A; - res->ans[i].dnsclass = 1; - res->ans[i].ttl = 1; - res->ans[i].name = res->q[0].name; - res->ans[i].rdata.a.ip_addr.s_addr = IP_ADDR3+i; - } + for (i=0; ians[i].type = PJ_DNS_TYPE_A; + res->ans[i].dnsclass = 1; + res->ans[i].ttl = 1; + res->ans[i].name = res->q[0].name; + res->ans[i].rdata.a.ip_addr.s_addr = IP_ADDR3+i; + } } *p_res = res; } static void srv_cb_3(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec) + pj_status_t status, + const pj_dns_srv_record *rec) { unsigned i; int *cb_err = (int*)user_data; @@ -1836,19 +1835,19 @@ static void srv_cb_3(void *user_data, SRV_CB_CHECK(rec->count == PJ_DNS_SRV_MAX_ADDR, -20); for (i=0; ientry[i].priority == i, -30); - SRV_CB_CHECK(rec->entry[i].weight == 2, -40); - //pj_assert(pj_strcmp2(&rec->entry[i].server.name, "sip." DOMAIN3)==0); - SRV_CB_CHECK(rec->entry[i].server.alias.slen == 0, -50); - SRV_CB_CHECK(rec->entry[i].port == PORT3+i, -60); + SRV_CB_CHECK(rec->entry[i].priority == i, -30); + SRV_CB_CHECK(rec->entry[i].weight == 2, -40); + //pj_assert(pj_strcmp2(&rec->entry[i].server.name, "sip." DOMAIN3)==0); + SRV_CB_CHECK(rec->entry[i].server.alias.slen == 0, -50); + SRV_CB_CHECK(rec->entry[i].port == PORT3+i, -60); - SRV_CB_CHECK(rec->entry[i].server.addr_count == PJ_DNS_MAX_IP_IN_A_REC, -70); + SRV_CB_CHECK(rec->entry[i].server.addr_count == PJ_DNS_MAX_IP_IN_A_REC, -70); - for (j=0; jentry[i].server.addr[j].ip.v4.s_addr == IP_ADDR3+j, -80); - } + for (j=0; jentry[i].server.addr[j].ip.v4.s_addr == IP_ADDR3+j, -80); + } } on_return: @@ -1874,17 +1873,17 @@ static int srv_resolver_many_test(void) g_server[1].pkt_count = 0; status = pj_dns_srv_resolve(&domain, &res_name, 1, pool, resolver, PJ_TRUE, - &cb_err, &srv_cb_3, NULL); + &cb_err, &srv_cb_3, NULL); if (status != PJ_SUCCESS) { - app_perror(" srv_resolve error", status); - return -10; + app_perror(" srv_resolve error", status); + return -10; } pj_sem_wait(sem); if (cb_err != 0) { - PJ_LOG(3,("test", " srv_resolve cb error, code=%d", cb_err)); - return -20; + PJ_LOG(3,("test", " srv_resolve cb error, code=%d", cb_err)); + return -20; } return 0; @@ -1900,35 +1899,35 @@ int resolver_test(void) rc = init(PJ_FALSE); if (rc != 0) - goto on_error; + goto on_error; rc = a_parser_test(); if (rc != 0) - goto on_error; + goto on_error; rc = addr_parser_test(); if (rc != 0) - goto on_error; + goto on_error; rc = simple_test(); if (rc != 0) - goto on_error; + goto on_error; rc = dns_test(); if (rc != 0) - goto on_error; + goto on_error; rc = srv_resolver_test(); if (rc != 0) - goto on_error; + goto on_error; rc = srv_resolver_fallback_test(); if (rc != 0) - goto on_error; + goto on_error; rc = srv_resolver_many_test(); if (rc != 0) - goto on_error; + goto on_error; destroy(); @@ -1939,27 +1938,27 @@ int resolver_test(void) rc = init(PJ_TRUE); if (rc != 0) - goto on_error; + goto on_error; rc = simple_test(); if (rc != 0) - goto on_error; + goto on_error; rc = dns_test(); if (rc != 0) - goto on_error; + goto on_error; rc = srv_resolver_test(); if (rc != 0) - goto on_error; + goto on_error; rc = srv_resolver_fallback_test(); if (rc != 0) - goto on_error; + goto on_error; rc = srv_resolver_many_test(); if (rc != 0) - goto on_error; + goto on_error; destroy(); #endif diff --git a/pjlib-util/src/pjlib-util-test/stun.c b/pjlib-util/src/pjlib-util-test/stun.c index ea1411947c..863571e916 100644 --- a/pjlib-util/src/pjlib-util-test/stun.c +++ b/pjlib-util/src/pjlib-util-test/stun.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib-util/src/pjlib-util-test/test.c b/pjlib-util/src/pjlib-util-test/test.c index 704a73e5ee..f83e4f6946 100644 --- a/pjlib-util/src/pjlib-util-test/test.c +++ b/pjlib-util/src/pjlib-util-test/test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,20 +30,20 @@ void app_perror(const char *msg, pj_status_t rc) PJ_LOG(1,("test", "%s: [pj_status_t=%d] %s", msg, rc, errbuf)); } -#define DO_TEST(test) do { \ - PJ_LOG(3, ("test", "Running %s...", #test)); \ - rc = test; \ - PJ_LOG(3, ("test", \ - "%s(%d)", \ - (char*)(rc ? "..ERROR" : "..success"), rc)); \ - if (rc!=0) goto on_return; \ - } while (0) +#define DO_TEST(test) do { \ + PJ_LOG(3, ("test", "Running %s...", #test)); \ + rc = test; \ + PJ_LOG(3, ("test", \ + "%s(%d)", \ + (char*)(rc ? "..ERROR" : "..success"), rc)); \ + if (rc!=0) goto on_return; \ + } while (0) pj_pool_factory *mem; int param_log_decor = PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_TIME | - PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_INDENT; + PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_INDENT; static int test_inner(void) { @@ -58,8 +57,8 @@ static int test_inner(void) rc = pj_init(); if (rc != 0) { - app_perror("pj_init() error!!", rc); - return rc; + app_perror("pj_init() error!!", rc); + return rc; } rc = pjlib_util_init(); diff --git a/pjlib-util/src/pjlib-util-test/test.h b/pjlib-util/src/pjlib-util-test/test.h index 94516dbe1a..9469e1f74f 100644 --- a/pjlib-util/src/pjlib-util-test/test.h +++ b/pjlib-util/src/pjlib-util-test/test.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -20,16 +19,16 @@ #include #if defined(PJ_EXCLUDE_BENCHMARK_TESTS) && (PJ_EXCLUDE_BENCHMARK_TESTS==1) -# define WITH_BENCHMARK 0 +# define WITH_BENCHMARK 0 #else -# define WITH_BENCHMARK 1 +# define WITH_BENCHMARK 1 #endif -#define INCLUDE_XML_TEST 1 -#define INCLUDE_JSON_TEST 1 -#define INCLUDE_ENCRYPTION_TEST 1 -#define INCLUDE_STUN_TEST 1 -#define INCLUDE_RESOLVER_TEST 1 +#define INCLUDE_XML_TEST 1 +#define INCLUDE_JSON_TEST 1 +#define INCLUDE_ENCRYPTION_TEST 1 +#define INCLUDE_STUN_TEST 1 +#define INCLUDE_RESOLVER_TEST 1 #define INCLUDE_HTTP_CLIENT_TEST 1 extern int xml_test(void); diff --git a/pjlib-util/src/pjlib-util-test/xml.c b/pjlib-util/src/pjlib-util-test/xml.c index f14167b164..aac987ff55 100644 --- a/pjlib-util/src/pjlib-util-test/xml.c +++ b/pjlib-util/src/pjlib-util-test/xml.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -107,15 +106,15 @@ static int xml_parse_print_test(const char *doc) pj_strdup2(pool, &msg, doc); root = pj_xml_parse(pool, msg.ptr, msg.slen); if (!root) { - PJ_LOG(1, (THIS_FILE, " Error: unable to parse XML")); - return -10; + PJ_LOG(1, (THIS_FILE, " Error: unable to parse XML")); + return -10; } output = (char*)pj_pool_zalloc(pool, msg.slen + 512); output_len = pj_xml_print(root, output, msg.slen+512, PJ_TRUE); if (output_len < 1) { - PJ_LOG(1, (THIS_FILE, " Error: buffer too small to print XML file")); - return -20; + PJ_LOG(1, (THIS_FILE, " Error: buffer too small to print XML file")); + return -20; } output[output_len] = '\0'; @@ -128,9 +127,9 @@ int xml_test() { unsigned i; for (i=0; i @@ -21,8 +20,8 @@ #include #include -#define INV -1 -#define PADDING '=' +#define INV -1 +#define PADDING '=' static const char base64_char[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', @@ -37,49 +36,49 @@ static const char base64_char[] = { static int base256_char(char c) { if (c >= 'A' && c <= 'Z') - return (c - 'A'); + return (c - 'A'); else if (c >= 'a' && c <= 'z') - return (c - 'a' + 26); + return (c - 'a' + 26); else if (c >= '0' && c <= '9') - return (c - '0' + 52); + return (c - '0' + 52); else if (c == '+') - return (62); + return (62); else if (c == '/') - return (63); + return (63); else { - /* It *may* happen on bad input, so this is not a good idea. - * pj_assert(!"Should not happen as '=' should have been filtered"); - */ - return INV; + /* It *may* happen on bad input, so this is not a good idea. + * pj_assert(!"Should not happen as '=' should have been filtered"); + */ + return INV; } } static void base256to64(pj_uint8_t c1, pj_uint8_t c2, pj_uint8_t c3, - int padding, char *output) + int padding, char *output) { *output++ = base64_char[c1>>2]; *output++ = base64_char[((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4)]; switch (padding) { case 0: - *output++ = base64_char[((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6)]; - *output = base64_char[c3 & 0x3F]; - break; + *output++ = base64_char[((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6)]; + *output = base64_char[c3 & 0x3F]; + break; case 1: - *output++ = base64_char[((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6)]; - *output = PADDING; - break; + *output++ = base64_char[((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6)]; + *output = PADDING; + break; case 2: default: - *output++ = PADDING; - *output = PADDING; - break; + *output++ = PADDING; + *output = PADDING; + break; } } PJ_DEF(pj_status_t) pj_base64_encode(const pj_uint8_t *input, int in_len, - char *output, int *out_len) + char *output, int *out_len) { const pj_uint8_t *pi = input; pj_uint8_t c1, c2, c3; @@ -88,32 +87,32 @@ PJ_DEF(pj_status_t) pj_base64_encode(const pj_uint8_t *input, int in_len, PJ_ASSERT_RETURN(input && output && out_len, PJ_EINVAL); PJ_ASSERT_RETURN(*out_len >= PJ_BASE256_TO_BASE64_LEN(in_len), - PJ_ETOOSMALL); + PJ_ETOOSMALL); while (i < in_len) { - c1 = *pi++; - ++i; - - if (i == in_len) { - base256to64(c1, 0, 0, 2, po); - po += 4; - break; - } else { - c2 = *pi++; - ++i; - - if (i == in_len) { - base256to64(c1, c2, 0, 1, po); - po += 4; - break; - } else { - c3 = *pi++; - ++i; - base256to64(c1, c2, c3, 0, po); - } - } - - po += 4; + c1 = *pi++; + ++i; + + if (i == in_len) { + base256to64(c1, 0, 0, 2, po); + po += 4; + break; + } else { + c2 = *pi++; + ++i; + + if (i == in_len) { + base256to64(c1, c2, 0, 1, po); + po += 4; + break; + } else { + c3 = *pi++; + ++i; + base256to64(c1, c2, c3, 0, po); + } + } + + po += 4; } *out_len = (int)(po - output); @@ -122,7 +121,7 @@ PJ_DEF(pj_status_t) pj_base64_encode(const pj_uint8_t *input, int in_len, PJ_DEF(pj_status_t) pj_base64_decode(const pj_str_t *input, - pj_uint8_t *out, int *out_len) + pj_uint8_t *out, int *out_len) { const char *buf; int len; @@ -134,33 +133,33 @@ PJ_DEF(pj_status_t) pj_base64_decode(const pj_str_t *input, buf = input->ptr; len = (int)input->slen; while (len && buf[len-1] == '=') - --len; + --len; PJ_ASSERT_RETURN(*out_len >= PJ_BASE64_TO_BASE256_LEN(len), - PJ_ETOOSMALL); + PJ_ETOOSMALL); for (i=0, j=0; i 1) { - out[j++] = (pj_uint8_t)((c[0]<<2) | ((c[1] & 0x30)>>4)); - if (k > 2) { - out[j++] = (pj_uint8_t) - (((c[1] & 0x0F)<<4) | ((c[2] & 0x3C)>>2)); - } - } - break; - } - - out[j++] = (pj_uint8_t)((c[0]<<2) | ((c[1] & 0x30)>>4)); - out[j++] = (pj_uint8_t)(((c[1] & 0x0F)<<4) | ((c[2] & 0x3C)>>2)); - out[j++] = (pj_uint8_t)(((c[2] & 0x03)<<6) | (c[3] & 0x3F)); + /* Fill up c, silently ignoring invalid characters */ + for (k=0; k<4 && i 1) { + out[j++] = (pj_uint8_t)((c[0]<<2) | ((c[1] & 0x30)>>4)); + if (k > 2) { + out[j++] = (pj_uint8_t) + (((c[1] & 0x0F)<<4) | ((c[2] & 0x3C)>>2)); + } + } + break; + } + + out[j++] = (pj_uint8_t)((c[0]<<2) | ((c[1] & 0x30)>>4)); + out[j++] = (pj_uint8_t)(((c[1] & 0x0F)<<4) | ((c[2] & 0x3C)>>2)); + out[j++] = (pj_uint8_t)(((c[2] & 0x03)<<6) | (c[3] & 0x3F)); } pj_assert(j <= *out_len); diff --git a/pjlib-util/src/pjlib-util/cli.c b/pjlib-util/src/pjlib-util/cli.c index 94e1439c7f..e3a9c1822e 100644 --- a/pjlib-util/src/pjlib-util/cli.c +++ b/pjlib-util/src/pjlib-util/cli.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) * @@ -29,7 +28,7 @@ #include #include -#define CMD_HASH_TABLE_SIZE 63 /* Hash table size */ +#define CMD_HASH_TABLE_SIZE 63 /* Hash table size */ #define CLI_CMD_CHANGE_LOG 30000 #define CLI_CMD_EXIT 30001 @@ -40,7 +39,7 @@ #if 1 /* Enable some tracing */ #define THIS_FILE "cli.c" - #define TRACE_(arg) PJ_LOG(3,arg) + #define TRACE_(arg) PJ_LOG(3,arg) #else #define TRACE_(arg) #endif @@ -57,7 +56,7 @@ \verbatim - + \endverbatim @@ -125,13 +124,13 @@ struct pj_cli_cmd_spec struct pj_cli_t { - pj_pool_t *pool; /* Pool to allocate memory from */ + pj_pool_t *pool; /* Pool to allocate memory from */ pj_cli_cfg cfg; /* CLI configuration */ pj_cli_cmd_spec root; /* Root of command tree structure */ pj_cli_front_end fe_head; /* List of front-ends */ pj_hash_table_t *cmd_name_hash; /* Command name hash table, this will - include the command name and shortcut - as hash key */ + include the command name and shortcut + as hash key */ pj_hash_table_t *cmd_id_hash; /* Command id hash table */ pj_bool_t is_quitting; @@ -247,39 +246,39 @@ struct pj_cli_arg_spec */ typedef enum pj_cli_parse_mode { PARSE_NONE, - PARSE_COMPLETION, /* Complete the command line */ + PARSE_COMPLETION, /* Complete the command line */ PARSE_NEXT_AVAIL, /* Find the next available command line */ - PARSE_EXEC /* Exec the command line */ + PARSE_EXEC /* Exec the command line */ } pj_cli_parse_mode; /** * This is used to get the matched command/argument from the * command/argument structure. * - * @param sess The session on which the command is execute on. - * @param cmd The active command. - * @param cmd_val The command value to match. - * @param argc The number of argument that the - * current active command have. - * @param pool The memory pool to allocate memory. - * @param get_cmd Set true to search matching command from sub command. - * @param parse_mode The parse mode. - * @param p_cmd The command that mathes the command value. - * @param info The output information containing any hints for - * matching command/arg. - * @return This function return the status of the - * matching process.Please see the return value - * of pj_cli_sess_parse() for possible return values. + * @param sess The session on which the command is execute on. + * @param cmd The active command. + * @param cmd_val The command value to match. + * @param argc The number of argument that the + * current active command have. + * @param pool The memory pool to allocate memory. + * @param get_cmd Set true to search matching command from sub command. + * @param parse_mode The parse mode. + * @param p_cmd The command that mathes the command value. + * @param info The output information containing any hints for + * matching command/arg. + * @return This function return the status of the + * matching process.Please see the return value + * of pj_cli_sess_parse() for possible return values. */ static pj_status_t get_available_cmds(pj_cli_sess *sess, - pj_cli_cmd_spec *cmd, - pj_str_t *cmd_val, - unsigned argc, - pj_pool_t *pool, - pj_bool_t get_cmd, - pj_cli_parse_mode parse_mode, - pj_cli_cmd_spec **p_cmd, - pj_cli_exec_info *info); + pj_cli_cmd_spec *cmd, + pj_str_t *cmd_val, + unsigned argc, + pj_pool_t *pool, + pj_bool_t get_cmd, + pj_cli_parse_mode parse_mode, + pj_cli_cmd_spec **p_cmd, + pj_cli_exec_info *info); PJ_DEF(pj_cli_cmd_id) pj_cli_get_cmd_id(const pj_cli_cmd_spec *cmd) { @@ -320,8 +319,8 @@ PJ_DEF(void) pj_cli_write_log(pj_cli_t *cli, } PJ_DEF(void) pj_cli_sess_write_msg(pj_cli_sess *sess, - const char *buffer, - pj_size_t len) + const char *buffer, + pj_size_t len) { struct pj_cli_front_end *fe; @@ -342,9 +341,9 @@ static pj_status_t cmd_handler(pj_cli_cmd_val *cval) level = pj_strtoul(&cval->argv[1]); if (!level && cval->argv[1].slen > 0 && (cval->argv[1].ptr[0] < '0' || cval->argv[1].ptr[0] > '9')) - { + { return PJ_CLI_EINVARG; - } + } cval->sess->log_level = level; return PJ_SUCCESS; case CLI_CMD_EXIT: @@ -394,10 +393,10 @@ PJ_DEF(pj_status_t) pj_cli_create(pj_cli_cfg *cfg, pj_str_t xml = pj_str(cmd_xmls[i]); if (pj_cli_add_cmd_from_xml(cli, NULL, &xml, - &cmd_handler, NULL, NULL) != PJ_SUCCESS) - { + &cmd_handler, NULL, NULL) != PJ_SUCCESS) + { TRACE_((THIS_FILE, "Failed to add command #%d", i)); - } + } } *p_cli = cli; @@ -419,13 +418,13 @@ PJ_DEF(void) pj_cli_register_front_end(pj_cli_t *cli, } PJ_DEF(void) pj_cli_quit(pj_cli_t *cli, pj_cli_sess *req, - pj_bool_t restart) + pj_bool_t restart) { pj_cli_front_end *fe; pj_assert(cli); if (cli->is_quitting) - return; + return; cli->is_quitting = PJ_TRUE; cli->is_restarting = restart; @@ -457,7 +456,7 @@ PJ_DEF(void) pj_cli_destroy(pj_cli_t *cli) pj_cli_front_end *fe; if (!cli) - return; + return; if (!pj_cli_is_quitting(cli)) pj_cli_quit(cli, NULL, PJ_FALSE); @@ -465,8 +464,8 @@ PJ_DEF(void) pj_cli_destroy(pj_cli_t *cli) fe = cli->fe_head.next; while (fe != &cli->fe_head) { pj_list_erase(fe); - if (fe->op && fe->op->on_destroy) - (*fe->op->on_destroy)(fe); + if (fe->op && fe->op->on_destroy) + (*fe->op->on_destroy)(fe); fe = cli->fe_head.next; } @@ -491,8 +490,8 @@ static void on_syntax_error(pj_scanner *scanner) /* Get the command from the command hash */ static pj_cli_cmd_spec *get_cmd_name(const pj_cli_t *cli, - const pj_cli_cmd_spec *group, - const pj_str_t *cmd) + const pj_cli_cmd_spec *group, + const pj_str_t *cmd) { pj_str_t cmd_val; char cmd_ptr[MAX_CMD_HASH_NAME_LENGTH]; @@ -501,18 +500,18 @@ static pj_cli_cmd_spec *get_cmd_name(const pj_cli_t *cli, cmd_val.slen = 0; if (group) { - char cmd_str[MAX_CMD_ID_LENGTH]; - pj_ansi_sprintf(cmd_str, "%d", group->id); - pj_strcat2(&cmd_val, cmd_str); + char cmd_str[MAX_CMD_ID_LENGTH]; + pj_ansi_sprintf(cmd_str, "%d", group->id); + pj_strcat2(&cmd_val, cmd_str); } pj_strcat(&cmd_val, cmd); return (pj_cli_cmd_spec *)pj_hash_get(cli->cmd_name_hash, cmd_val.ptr, - (unsigned)cmd_val.slen, NULL); + (unsigned)cmd_val.slen, NULL); } /* Add command to the command hash */ static void add_cmd_name(pj_cli_t *cli, pj_cli_cmd_spec *group, - pj_cli_cmd_spec *cmd, pj_str_t *cmd_name) + pj_cli_cmd_spec *cmd, pj_str_t *cmd_name) { pj_str_t cmd_val; pj_str_t add_cmd; @@ -522,15 +521,15 @@ static void add_cmd_name(pj_cli_t *cli, pj_cli_cmd_spec *group, cmd_val.slen = 0; if (group) { - char cmd_str[MAX_CMD_ID_LENGTH]; - pj_ansi_sprintf(cmd_str, "%d", group->id); - pj_strcat2(&cmd_val, cmd_str); + char cmd_str[MAX_CMD_ID_LENGTH]; + pj_ansi_sprintf(cmd_str, "%d", group->id); + pj_strcat2(&cmd_val, cmd_str); } pj_strcat(&cmd_val, cmd_name); pj_strdup(cli->pool, &add_cmd, &cmd_val); pj_hash_set(cli->pool, cli->cmd_name_hash, cmd_val.ptr, - (unsigned)cmd_val.slen, 0, cmd); + (unsigned)cmd_val.slen, 0, cmd); } /** @@ -538,9 +537,9 @@ static void add_cmd_name(pj_cli_t *cli, pj_cli_cmd_spec *group, * argument values to command structure. **/ static pj_status_t add_choice_node(pj_cli_t *cli, - pj_xml_node *xml_node, - pj_cli_arg_spec *arg, - pj_cli_get_dyn_choice get_choice) + pj_xml_node *xml_node, + pj_cli_arg_spec *arg, + pj_cli_get_dyn_choice get_choice) { pj_xml_node *choice_node; pj_xml_node *sub_node; @@ -549,41 +548,41 @@ static pj_status_t add_choice_node(pj_cli_t *cli, sub_node = xml_node; arg->type = PJ_CLI_ARG_CHOICE; - arg->get_dyn_choice = get_choice; + arg->get_dyn_choice = get_choice; choice_node = sub_node->node_head.next; while (choice_node != (pj_xml_node*)&sub_node->node_head) { - pj_xml_attr *choice_attr; - unsigned *stat_cnt = &arg->stat_choice_cnt; - pj_cli_arg_choice_val *choice_val = &choice_values[*stat_cnt]; - pj_bzero(choice_val, sizeof(*choice_val)); - - choice_attr = choice_node->attr_head.next; - while (choice_attr != &choice_node->attr_head) { - if (!pj_stricmp2(&choice_attr->name, "value")) { - pj_strassign(&choice_val->value, &choice_attr->value); - } else if (!pj_stricmp2(&choice_attr->name, "desc")) { - pj_strassign(&choice_val->desc, &choice_attr->value); - } - choice_attr = choice_attr->next; - } - if (++(*stat_cnt) >= PJ_CLI_MAX_CHOICE_VAL) - break; - choice_node = choice_node->next; + pj_xml_attr *choice_attr; + unsigned *stat_cnt = &arg->stat_choice_cnt; + pj_cli_arg_choice_val *choice_val = &choice_values[*stat_cnt]; + pj_bzero(choice_val, sizeof(*choice_val)); + + choice_attr = choice_node->attr_head.next; + while (choice_attr != &choice_node->attr_head) { + if (!pj_stricmp2(&choice_attr->name, "value")) { + pj_strassign(&choice_val->value, &choice_attr->value); + } else if (!pj_stricmp2(&choice_attr->name, "desc")) { + pj_strassign(&choice_val->desc, &choice_attr->value); + } + choice_attr = choice_attr->next; + } + if (++(*stat_cnt) >= PJ_CLI_MAX_CHOICE_VAL) + break; + choice_node = choice_node->next; } if (arg->stat_choice_cnt > 0) { unsigned i; - arg->stat_choice_val = (pj_cli_arg_choice_val *) - pj_pool_zalloc(cli->pool, - arg->stat_choice_cnt * - sizeof(pj_cli_arg_choice_val)); + arg->stat_choice_val = (pj_cli_arg_choice_val *) + pj_pool_zalloc(cli->pool, + arg->stat_choice_cnt * + sizeof(pj_cli_arg_choice_val)); for (i = 0; i < arg->stat_choice_cnt; i++) { - pj_strdup(cli->pool, &arg->stat_choice_val[i].value, - &choice_values[i].value); + pj_strdup(cli->pool, &arg->stat_choice_val[i].value, + &choice_values[i].value); pj_strdup(cli->pool, &arg->stat_choice_val[i].desc, - &choice_values[i].desc); + &choice_values[i].desc); } } return status; @@ -593,50 +592,50 @@ static pj_status_t add_choice_node(pj_cli_t *cli, * This method is to parse and add the argument attribute to command structure. **/ static pj_status_t add_arg_node(pj_cli_t *cli, - pj_xml_node *xml_node, - pj_cli_cmd_spec *cmd, - pj_cli_arg_spec *arg, - pj_cli_get_dyn_choice get_choice) + pj_xml_node *xml_node, + pj_cli_cmd_spec *cmd, + pj_cli_arg_spec *arg, + pj_cli_get_dyn_choice get_choice) { pj_xml_attr *attr; pj_status_t status = PJ_SUCCESS; pj_xml_node *sub_node = xml_node; if (cmd->arg_cnt >= PJ_CLI_MAX_ARGS) - return PJ_CLI_ETOOMANYARGS; + return PJ_CLI_ETOOMANYARGS; pj_bzero(arg, sizeof(*arg)); attr = sub_node->attr_head.next; arg->optional = PJ_FALSE; arg->validate = PJ_TRUE; - while (attr != &sub_node->attr_head) { - if (!pj_stricmp2(&attr->name, "name")) { - pj_strassign(&arg->name, &attr->value); - } else if (!pj_stricmp2(&attr->name, "id")) { - arg->id = pj_strtol(&attr->value); - } else if (!pj_stricmp2(&attr->name, "type")) { - if (!pj_stricmp2(&attr->value, "text")) { - arg->type = PJ_CLI_ARG_TEXT; - } else if (!pj_stricmp2(&attr->value, "int")) { - arg->type = PJ_CLI_ARG_INT; - } else if (!pj_stricmp2(&attr->value, "choice")) { - /* Get choice value */ - add_choice_node(cli, xml_node, arg, get_choice); - } - } else if (!pj_stricmp2(&attr->name, "desc")) { - pj_strassign(&arg->desc, &attr->value); - } else if (!pj_stricmp2(&attr->name, "optional")) { - if (!pj_strcmp2(&attr->value, "1")) { - arg->optional = PJ_TRUE; - } - } else if (!pj_stricmp2(&attr->name, "validate")) { - if (!pj_strcmp2(&attr->value, "1")) { - arg->validate = PJ_TRUE; - } else { - arg->validate = PJ_FALSE; - } - } - attr = attr->next; + while (attr != &sub_node->attr_head) { + if (!pj_stricmp2(&attr->name, "name")) { + pj_strassign(&arg->name, &attr->value); + } else if (!pj_stricmp2(&attr->name, "id")) { + arg->id = pj_strtol(&attr->value); + } else if (!pj_stricmp2(&attr->name, "type")) { + if (!pj_stricmp2(&attr->value, "text")) { + arg->type = PJ_CLI_ARG_TEXT; + } else if (!pj_stricmp2(&attr->value, "int")) { + arg->type = PJ_CLI_ARG_INT; + } else if (!pj_stricmp2(&attr->value, "choice")) { + /* Get choice value */ + add_choice_node(cli, xml_node, arg, get_choice); + } + } else if (!pj_stricmp2(&attr->name, "desc")) { + pj_strassign(&arg->desc, &attr->value); + } else if (!pj_stricmp2(&attr->name, "optional")) { + if (!pj_strcmp2(&attr->value, "1")) { + arg->optional = PJ_TRUE; + } + } else if (!pj_stricmp2(&attr->name, "validate")) { + if (!pj_strcmp2(&attr->value, "1")) { + arg->validate = PJ_TRUE; + } else { + arg->validate = PJ_FALSE; + } + } + attr = attr->next; } cmd->arg_cnt++; return status; @@ -645,12 +644,12 @@ static pj_status_t add_arg_node(pj_cli_t *cli, /** * This method is to parse and add the command attribute to command structure. **/ -static pj_status_t add_cmd_node(pj_cli_t *cli, - pj_cli_cmd_spec *group, - pj_xml_node *xml_node, - pj_cli_cmd_handler handler, - pj_cli_cmd_spec **p_cmd, - pj_cli_get_dyn_choice get_choice) +static pj_status_t add_cmd_node(pj_cli_t *cli, + pj_cli_cmd_spec *group, + pj_xml_node *xml_node, + pj_cli_cmd_handler handler, + pj_cli_cmd_spec **p_cmd, + pj_cli_get_dyn_choice get_choice) { pj_xml_node *root = xml_node; pj_xml_attr *attr; @@ -672,21 +671,21 @@ static pj_status_t add_cmd_node(pj_cli_t *cli, if (!pj_stricmp2(&attr->name, "name")) { pj_strltrim(&attr->value); if (!attr->value.slen || - (get_cmd_name(cli, group, &attr->value))) + (get_cmd_name(cli, group, &attr->value))) { return PJ_CLI_EBADNAME; } pj_strdup(cli->pool, &cmd->name, &attr->value); - } else if (!pj_stricmp2(&attr->name, "id")) { - pj_bool_t is_valid = PJ_FALSE; - if (attr->value.slen) { - pj_cli_cmd_id cmd_id = pj_strtol(&attr->value); - if (!pj_hash_get(cli->cmd_id_hash, &cmd_id, - sizeof(pj_cli_cmd_id), NULL)) - is_valid = PJ_TRUE; - } - if (!is_valid) - return PJ_CLI_EBADID; + } else if (!pj_stricmp2(&attr->name, "id")) { + pj_bool_t is_valid = PJ_FALSE; + if (attr->value.slen) { + pj_cli_cmd_id cmd_id = pj_strtol(&attr->value); + if (!pj_hash_get(cli->cmd_id_hash, &cmd_id, + sizeof(pj_cli_cmd_id), NULL)) + is_valid = PJ_TRUE; + } + if (!is_valid) + return PJ_CLI_EBADID; cmd->id = (pj_cli_cmd_id)pj_strtol(&attr->value); } else if (!pj_stricmp2(&attr->name, "sc")) { pj_scanner scanner; @@ -694,9 +693,9 @@ static pj_status_t add_cmd_node(pj_cli_t *cli, PJ_USE_EXCEPTION; - /* The buffer passed to the scanner is not NULL terminated, - * but should be safe. See ticket #2063. - */ + /* The buffer passed to the scanner is not NULL terminated, + * but should be safe. See ticket #2063. + */ pj_scan_init(&scanner, attr->value.ptr, attr->value.slen, PJ_SCAN_AUTOSKIP_WS, &on_syntax_error); @@ -737,19 +736,19 @@ static pj_status_t add_cmd_node(pj_cli_t *cli, /* Get the command childs/arguments */ sub_node = root->node_head.next; while (sub_node != (pj_xml_node*)&root->node_head) { - if (!pj_stricmp2(&sub_node->name, "CMD")) { - status = add_cmd_node(cli, cmd, sub_node, handler, NULL, - get_choice); - if (status != PJ_SUCCESS) - return status; - } else if (!pj_stricmp2(&sub_node->name, "ARG")) { - /* Get argument attribute */ - status = add_arg_node(cli, sub_node, - cmd, &args[cmd->arg_cnt], - get_choice); - - if (status != PJ_SUCCESS) - return status; + if (!pj_stricmp2(&sub_node->name, "CMD")) { + status = add_cmd_node(cli, cmd, sub_node, handler, NULL, + get_choice); + if (status != PJ_SUCCESS) + return status; + } else if (!pj_stricmp2(&sub_node->name, "ARG")) { + /* Get argument attribute */ + status = add_arg_node(cli, sub_node, + cmd, &args[cmd->arg_cnt], + get_choice); + + if (status != PJ_SUCCESS) + return status; } sub_node = sub_node->next; } @@ -765,17 +764,17 @@ static pj_status_t add_cmd_node(pj_cli_t *cli, cmd->arg = (pj_cli_arg_spec *)pj_pool_zalloc(cli->pool, cmd->arg_cnt * sizeof(pj_cli_arg_spec)); - + for (i = 0; i < cmd->arg_cnt; i++) { pj_strdup(cli->pool, &cmd->arg[i].name, &args[i].name); pj_strdup(cli->pool, &cmd->arg[i].desc, &args[i].desc); - cmd->arg[i].id = args[i].id; + cmd->arg[i].id = args[i].id; cmd->arg[i].type = args[i].type; - cmd->arg[i].optional = args[i].optional; - cmd->arg[i].validate = args[i].validate; - cmd->arg[i].get_dyn_choice = args[i].get_dyn_choice; - cmd->arg[i].stat_choice_cnt = args[i].stat_choice_cnt; - cmd->arg[i].stat_choice_val = args[i].stat_choice_val; + cmd->arg[i].optional = args[i].optional; + cmd->arg[i].validate = args[i].validate; + cmd->arg[i].get_dyn_choice = args[i].get_dyn_choice; + cmd->arg[i].stat_choice_cnt = args[i].stat_choice_cnt; + cmd->arg[i].stat_choice_val = args[i].stat_choice_val; } } @@ -785,23 +784,23 @@ static pj_status_t add_cmd_node(pj_cli_t *cli, cmd->sc = (pj_str_t *)pj_pool_zalloc(cli->pool, cmd->sc_cnt * sizeof(pj_str_t)); for (i = 0; i < cmd->sc_cnt; i++) { - pj_strdup(cli->pool, &cmd->sc[i], &sc[i]); - /** Add shortcut to root command **/ - add_cmd_name(cli, &cli->root, cmd, &sc[i]); + pj_strdup(cli->pool, &cmd->sc[i], &sc[i]); + /** Add shortcut to root command **/ + add_cmd_name(cli, &cli->root, cmd, &sc[i]); } } add_cmd_name(cli, group, cmd, &cmd->name); pj_hash_set(cli->pool, cli->cmd_id_hash, - &cmd->id, sizeof(pj_cli_cmd_id), 0, cmd); + &cmd->id, sizeof(pj_cli_cmd_id), 0, cmd); cmd->handler = handler; if (group) { - if (!group->sub_cmd) { - group->sub_cmd = PJ_POOL_ALLOC_T(cli->pool, struct pj_cli_cmd_spec); - pj_list_init(group->sub_cmd); - } + if (!group->sub_cmd) { + group->sub_cmd = PJ_POOL_ALLOC_T(cli->pool, struct pj_cli_cmd_spec); + pj_list_init(group->sub_cmd); + } pj_list_push_back(group->sub_cmd, cmd); } else { pj_list_push_back(cli->root.sub_cmd, cmd); @@ -814,11 +813,11 @@ static pj_status_t add_cmd_node(pj_cli_t *cli, } PJ_DEF(pj_status_t) pj_cli_add_cmd_from_xml(pj_cli_t *cli, - pj_cli_cmd_spec *group, + pj_cli_cmd_spec *group, const pj_str_t *xml, pj_cli_cmd_handler handler, pj_cli_cmd_spec **p_cmd, - pj_cli_get_dyn_choice get_choice) + pj_cli_get_dyn_choice get_choice) { pj_pool_t *pool; pj_xml_node *root; @@ -833,9 +832,9 @@ PJ_DEF(pj_status_t) pj_cli_add_cmd_from_xml(pj_cli_t *cli, root = pj_xml_parse(pool, xml->ptr, xml->slen); if (!root) { - TRACE_((THIS_FILE, "Error: unable to parse XML")); - pj_pool_release(pool); - return PJ_CLI_EBADXML; + TRACE_((THIS_FILE, "Error: unable to parse XML")); + pj_pool_release(pool); + return PJ_CLI_EBADXML; } status = add_cmd_node(cli, group, root, handler, p_cmd, get_choice); pj_pool_release(pool); @@ -843,10 +842,10 @@ PJ_DEF(pj_status_t) pj_cli_add_cmd_from_xml(pj_cli_t *cli, } PJ_DEF(pj_status_t) pj_cli_sess_parse(pj_cli_sess *sess, - char *cmdline, - pj_cli_cmd_val *val, - pj_pool_t *pool, - pj_cli_exec_info *info) + char *cmdline, + pj_cli_cmd_val *val, + pj_pool_t *pool, + pj_cli_exec_info *info) { pj_scanner scanner; pj_str_t str; @@ -871,90 +870,90 @@ PJ_DEF(pj_status_t) pj_cli_sess_parse(pj_cli_sess *sess, len = pj_ansi_strlen(cmdline); if (len > 0 && ((cmdline[len - 1] == '\r')||(cmdline[len - 1] == '\n'))) { cmdline[--len] = 0; - parse_mode = PARSE_EXEC; + parse_mode = PARSE_EXEC; } else if (len > 0 && - (cmdline[len - 1] == '\t' || cmdline[len - 1] == '?')) + (cmdline[len - 1] == '\t' || cmdline[len - 1] == '?')) { - cmdline[--len] = 0; - if (len == 0) { - parse_mode = PARSE_NEXT_AVAIL; - } else { - if (cmdline[len - 1] == ' ') - parse_mode = PARSE_NEXT_AVAIL; - else - parse_mode = PARSE_COMPLETION; - } + cmdline[--len] = 0; + if (len == 0) { + parse_mode = PARSE_NEXT_AVAIL; + } else { + if (cmdline[len - 1] == ' ') + parse_mode = PARSE_NEXT_AVAIL; + else + parse_mode = PARSE_COMPLETION; + } } val->argc = 0; info->err_pos = 0; cmd = &sess->fe->cli->root; if (len > 0) { - pj_scan_init(&scanner, cmdline, len, PJ_SCAN_AUTOSKIP_WS, - &on_syntax_error); - PJ_TRY { - val->argc = 0; - while (!pj_scan_is_eof(&scanner)) { - info->err_pos = (int)(scanner.curptr - scanner.begin); - if (*scanner.curptr == '\'' || *scanner.curptr == '"' || - *scanner.curptr == '{') - { - pj_scan_get_quotes(&scanner, "'\"{", "'\"}", 3, &str); - /* Remove the quotes */ - str.ptr++; - str.slen -= 2; - } else { - pj_scan_get_until_chr(&scanner, " \t\r\n", &str); - } - ++val->argc; - if (val->argc == PJ_CLI_MAX_ARGS) - PJ_THROW(PJ_CLI_ETOOMANYARGS); - - status = get_available_cmds(sess, cmd, &str, val->argc-1, - pool, PJ_TRUE, parse_mode, - &next_cmd, info); - - if (status != PJ_SUCCESS) - PJ_THROW(status); - - if (cmd != next_cmd) { - /* Found new command, set it as the active command */ - cmd = next_cmd; - val->argc = 1; - val->cmd = cmd; - } - if (parse_mode == PARSE_EXEC) - pj_strassign(&val->argv[val->argc-1], &info->hint->name); - else - pj_strassign(&val->argv[val->argc-1], &str); - - } - if (!pj_scan_is_eof(&scanner)) - PJ_THROW(PJ_CLI_EINVARG); - - } - PJ_CATCH_ANY { - pj_scan_fini(&scanner); - return PJ_GET_EXCEPTION(); - } - PJ_END; - - pj_scan_fini(&scanner); + pj_scan_init(&scanner, cmdline, len, PJ_SCAN_AUTOSKIP_WS, + &on_syntax_error); + PJ_TRY { + val->argc = 0; + while (!pj_scan_is_eof(&scanner)) { + info->err_pos = (int)(scanner.curptr - scanner.begin); + if (*scanner.curptr == '\'' || *scanner.curptr == '"' || + *scanner.curptr == '{') + { + pj_scan_get_quotes(&scanner, "'\"{", "'\"}", 3, &str); + /* Remove the quotes */ + str.ptr++; + str.slen -= 2; + } else { + pj_scan_get_until_chr(&scanner, " \t\r\n", &str); + } + ++val->argc; + if (val->argc == PJ_CLI_MAX_ARGS) + PJ_THROW(PJ_CLI_ETOOMANYARGS); + + status = get_available_cmds(sess, cmd, &str, val->argc-1, + pool, PJ_TRUE, parse_mode, + &next_cmd, info); + + if (status != PJ_SUCCESS) + PJ_THROW(status); + + if (cmd != next_cmd) { + /* Found new command, set it as the active command */ + cmd = next_cmd; + val->argc = 1; + val->cmd = cmd; + } + if (parse_mode == PARSE_EXEC) + pj_strassign(&val->argv[val->argc-1], &info->hint->name); + else + pj_strassign(&val->argv[val->argc-1], &str); + + } + if (!pj_scan_is_eof(&scanner)) + PJ_THROW(PJ_CLI_EINVARG); + + } + PJ_CATCH_ANY { + pj_scan_fini(&scanner); + return PJ_GET_EXCEPTION(); + } + PJ_END; + + pj_scan_fini(&scanner); } if ((parse_mode == PARSE_NEXT_AVAIL) || (parse_mode == PARSE_EXEC)) { - /* If exec mode, just get the matching argument */ - status = get_available_cmds(sess, cmd, NULL, val->argc, pool, - (parse_mode==PARSE_NEXT_AVAIL), - parse_mode, - NULL, info); - if ((status != PJ_SUCCESS) && (status != PJ_CLI_EINVARG)) { - pj_str_t data = pj_str(cmdline); - pj_strrtrim(&data); - data.ptr[data.slen] = ' '; - data.ptr[data.slen+1] = 0; - - info->err_pos = (int)pj_ansi_strlen(cmdline); - } + /* If exec mode, just get the matching argument */ + status = get_available_cmds(sess, cmd, NULL, val->argc, pool, + (parse_mode==PARSE_NEXT_AVAIL), + parse_mode, + NULL, info); + if ((status != PJ_SUCCESS) && (status != PJ_CLI_EINVARG)) { + pj_str_t data = pj_str(cmdline); + pj_strrtrim(&data); + data.ptr[data.slen] = ' '; + data.ptr[data.slen+1] = 0; + + info->err_pos = (int)pj_ansi_strlen(cmdline); + } } val->sess = sess; @@ -962,9 +961,9 @@ PJ_DEF(pj_status_t) pj_cli_sess_parse(pj_cli_sess *sess, } PJ_DECL(pj_status_t) pj_cli_sess_exec(pj_cli_sess *sess, - char *cmdline, - pj_pool_t *pool, - pj_cli_exec_info *info) + char *cmdline, + pj_pool_t *pool, + pj_cli_exec_info *info) { pj_cli_cmd_val val; pj_status_t status; @@ -979,11 +978,11 @@ PJ_DECL(pj_status_t) pj_cli_sess_exec(pj_cli_sess *sess, cmd.slen = pj_ansi_strlen(cmdline); if (pj_strtrim(&cmd)->slen == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; if (!info) info = &einfo; - + status = pj_cli_sess_parse(sess, cmdline, &val, pool, info); if (status != PJ_SUCCESS) return status; @@ -992,28 +991,28 @@ PJ_DECL(pj_status_t) pj_cli_sess_exec(pj_cli_sess *sess, info->cmd_ret = (*val.cmd->handler)(&val); if (info->cmd_ret == PJ_CLI_EINVARG || info->cmd_ret == PJ_CLI_EEXIT) - { + { return info->cmd_ret; - } + } } return PJ_SUCCESS; } static pj_bool_t hint_inserted(const pj_str_t *name, - const pj_str_t *desc, - const pj_str_t *type, - pj_cli_exec_info *info) + const pj_str_t *desc, + const pj_str_t *type, + pj_cli_exec_info *info) { unsigned i; for(i=0; ihint_cnt; ++i) { - pj_cli_hint_info *hint = &info->hint[i]; - if ((!pj_strncmp(&hint->name, name, hint->name.slen)) && - (!pj_strncmp(&hint->desc, desc, hint->desc.slen)) && - (!pj_strncmp(&hint->type, type, hint->type.slen))) - { - return PJ_TRUE; - } + pj_cli_hint_info *hint = &info->hint[i]; + if ((!pj_strncmp(&hint->name, name, hint->name.slen)) && + (!pj_strncmp(&hint->desc, desc, hint->desc.slen)) && + (!pj_strncmp(&hint->type, type, hint->type.slen))) + { + return PJ_TRUE; + } } return PJ_FALSE; } @@ -1021,33 +1020,33 @@ static pj_bool_t hint_inserted(const pj_str_t *name, /** This will insert new hint with the option to check for the same previous entry **/ static pj_status_t insert_new_hint2(pj_pool_t *pool, - pj_bool_t unique_insert, - const pj_str_t *name, - const pj_str_t *desc, - const pj_str_t *type, - pj_cli_exec_info *info) + pj_bool_t unique_insert, + const pj_str_t *name, + const pj_str_t *desc, + const pj_str_t *type, + pj_cli_exec_info *info) { pj_cli_hint_info *hint; PJ_ASSERT_RETURN(pool && info, PJ_EINVAL); PJ_ASSERT_RETURN((info->hint_cnt < PJ_CLI_MAX_HINTS), PJ_EINVAL); if ((unique_insert) && (hint_inserted(name, desc, type, info))) - return PJ_SUCCESS; + return PJ_SUCCESS; hint = &info->hint[info->hint_cnt]; pj_strdup(pool, &hint->name, name); if (desc && (desc->slen > 0)) { - pj_strdup(pool, &hint->desc, desc); + pj_strdup(pool, &hint->desc, desc); } else { - hint->desc.slen = 0; + hint->desc.slen = 0; } if (type && (type->slen > 0)) { - pj_strdup(pool, &hint->type, type); + pj_strdup(pool, &hint->type, type); } else { - hint->type.slen = 0; + hint->type.slen = 0; } ++info->hint_cnt; @@ -1056,21 +1055,21 @@ static pj_status_t insert_new_hint2(pj_pool_t *pool, /** This will insert new hint without checking for the same previous entry **/ static pj_status_t insert_new_hint(pj_pool_t *pool, - const pj_str_t *name, - const pj_str_t *desc, - const pj_str_t *type, - pj_cli_exec_info *info) + const pj_str_t *name, + const pj_str_t *desc, + const pj_str_t *type, + pj_cli_exec_info *info) { return insert_new_hint2(pool, PJ_FALSE, name, desc, type, info); } /** This will get a complete/exact match of a command from the cmd hash **/ static pj_status_t get_comp_match_cmds(const pj_cli_t *cli, - const pj_cli_cmd_spec *group, - const pj_str_t *cmd_val, - pj_pool_t *pool, - pj_cli_cmd_spec **p_cmd, - pj_cli_exec_info *info) + const pj_cli_cmd_spec *group, + const pj_str_t *cmd_val, + pj_pool_t *pool, + pj_cli_cmd_spec **p_cmd, + pj_cli_exec_info *info) { pj_cli_cmd_spec *cmd; PJ_ASSERT_RETURN(cli && group && cmd_val && pool && info, PJ_EINVAL); @@ -1078,13 +1077,13 @@ static pj_status_t get_comp_match_cmds(const pj_cli_t *cli, cmd = get_cmd_name(cli, group, cmd_val); if (cmd) { - pj_status_t status; - status = insert_new_hint(pool, cmd_val, &cmd->desc, NULL, info); + pj_status_t status; + status = insert_new_hint(pool, cmd_val, &cmd->desc, NULL, info); - if (status != PJ_SUCCESS) - return status; + if (status != PJ_SUCCESS) + return status; - *p_cmd = cmd; + *p_cmd = cmd; } return PJ_SUCCESS; @@ -1094,10 +1093,10 @@ static pj_status_t get_comp_match_cmds(const pj_cli_t *cli, command. This method should be called from root command, as shortcut could only be executed from root **/ static pj_status_t get_pattern_match_shortcut(const pj_cli_t *cli, - const pj_str_t *cmd_val, - pj_pool_t *pool, - pj_cli_cmd_spec **p_cmd, - pj_cli_exec_info *info) + const pj_str_t *cmd_val, + pj_pool_t *pool, + pj_cli_cmd_spec **p_cmd, + pj_cli_exec_info *info) { pj_hash_iterator_t it_buf, *it; pj_status_t status; @@ -1105,31 +1104,31 @@ static pj_status_t get_pattern_match_shortcut(const pj_cli_t *cli, it = pj_hash_first(cli->cmd_name_hash, &it_buf); while (it) { - unsigned i; - pj_cli_cmd_spec *cmd = (pj_cli_cmd_spec *) - pj_hash_this(cli->cmd_name_hash, it); - - PJ_ASSERT_RETURN(cmd, PJ_EINVAL); - - for (i=0; i < cmd->sc_cnt; ++i) { - static const pj_str_t SHORTCUT = {"SC", 2}; - pj_str_t *sc = &cmd->sc[i]; - PJ_ASSERT_RETURN(sc, PJ_EINVAL); - - if (!pj_strncmp(sc, cmd_val, cmd_val->slen)) { - /** Unique hints needed because cmd hash contain command name - and shortcut referencing to the same command **/ - status = insert_new_hint2(pool, PJ_TRUE, sc, &cmd->desc, - &SHORTCUT, info); - if (status != PJ_SUCCESS) - return status; - - if (p_cmd) - *p_cmd = cmd; - } - } - - it = pj_hash_next(cli->cmd_name_hash, it); + unsigned i; + pj_cli_cmd_spec *cmd = (pj_cli_cmd_spec *) + pj_hash_this(cli->cmd_name_hash, it); + + PJ_ASSERT_RETURN(cmd, PJ_EINVAL); + + for (i=0; i < cmd->sc_cnt; ++i) { + static const pj_str_t SHORTCUT = {"SC", 2}; + pj_str_t *sc = &cmd->sc[i]; + PJ_ASSERT_RETURN(sc, PJ_EINVAL); + + if (!pj_strncmp(sc, cmd_val, cmd_val->slen)) { + /** Unique hints needed because cmd hash contain command name + and shortcut referencing to the same command **/ + status = insert_new_hint2(pool, PJ_TRUE, sc, &cmd->desc, + &SHORTCUT, info); + if (status != PJ_SUCCESS) + return status; + + if (p_cmd) + *p_cmd = cmd; + } + } + + it = pj_hash_next(cli->cmd_name_hash, it); } return PJ_SUCCESS; @@ -1138,50 +1137,50 @@ static pj_status_t get_pattern_match_shortcut(const pj_cli_t *cli, /** This method will search a pattern match to the input command from the child command list of the current/active command. **/ static pj_status_t get_pattern_match_cmds(pj_cli_cmd_spec *cmd, - const pj_str_t *cmd_val, - pj_pool_t *pool, - pj_cli_cmd_spec **p_cmd, - pj_cli_parse_mode parse_mode, - pj_cli_exec_info *info) + const pj_str_t *cmd_val, + pj_pool_t *pool, + pj_cli_cmd_spec **p_cmd, + pj_cli_parse_mode parse_mode, + pj_cli_exec_info *info) { pj_status_t status; PJ_ASSERT_RETURN(cmd && pool && info && cmd_val, PJ_EINVAL); /* Get matching command */ if (cmd->sub_cmd) { - pj_cli_cmd_spec *child_cmd = cmd->sub_cmd->next; - while (child_cmd != cmd->sub_cmd) { - pj_bool_t found = PJ_FALSE; - if (!pj_strncmp(&child_cmd->name, cmd_val, cmd_val->slen)) { - status = insert_new_hint(pool, &child_cmd->name, - &child_cmd->desc, NULL, info); - if (status != PJ_SUCCESS) - return status; - - found = PJ_TRUE; - } - if (found) { - if (parse_mode == PARSE_NEXT_AVAIL) { - /** Only insert shortcut on next available commands mode **/ - unsigned i; - for (i=0; i < child_cmd->sc_cnt; ++i) { - static const pj_str_t SHORTCUT = {"SC", 2}; - pj_str_t *sc = &child_cmd->sc[i]; - PJ_ASSERT_RETURN(sc, PJ_EINVAL); - - status = insert_new_hint(pool, sc, - &child_cmd->desc, &SHORTCUT, - info); - if (status != PJ_SUCCESS) - return status; - } - } - - if (p_cmd) - *p_cmd = child_cmd; - } - child_cmd = child_cmd->next; - } + pj_cli_cmd_spec *child_cmd = cmd->sub_cmd->next; + while (child_cmd != cmd->sub_cmd) { + pj_bool_t found = PJ_FALSE; + if (!pj_strncmp(&child_cmd->name, cmd_val, cmd_val->slen)) { + status = insert_new_hint(pool, &child_cmd->name, + &child_cmd->desc, NULL, info); + if (status != PJ_SUCCESS) + return status; + + found = PJ_TRUE; + } + if (found) { + if (parse_mode == PARSE_NEXT_AVAIL) { + /** Only insert shortcut on next available commands mode **/ + unsigned i; + for (i=0; i < child_cmd->sc_cnt; ++i) { + static const pj_str_t SHORTCUT = {"SC", 2}; + pj_str_t *sc = &child_cmd->sc[i]; + PJ_ASSERT_RETURN(sc, PJ_EINVAL); + + status = insert_new_hint(pool, sc, + &child_cmd->desc, &SHORTCUT, + info); + if (status != PJ_SUCCESS) + return status; + } + } + + if (p_cmd) + *p_cmd = child_cmd; + } + child_cmd = child_cmd->next; + } } return PJ_SUCCESS; } @@ -1189,12 +1188,12 @@ static pj_status_t get_pattern_match_cmds(pj_cli_cmd_spec *cmd, /** This will match the arguments passed to the command with the argument list of the specified command list. **/ static pj_status_t get_match_args(pj_cli_sess *sess, - pj_cli_cmd_spec *cmd, - const pj_str_t *cmd_val, - unsigned argc, - pj_pool_t *pool, - pj_cli_parse_mode parse_mode, - pj_cli_exec_info *info) + pj_cli_cmd_spec *cmd, + const pj_str_t *cmd_val, + unsigned argc, + pj_pool_t *pool, + pj_cli_parse_mode parse_mode, + pj_cli_exec_info *info) { pj_cli_arg_spec *arg; pj_status_t status = PJ_SUCCESS; @@ -1202,88 +1201,88 @@ static pj_status_t get_match_args(pj_cli_sess *sess, PJ_ASSERT_RETURN(cmd && pool && cmd_val && info, PJ_EINVAL); if ((argc > cmd->arg_cnt) && (!cmd->sub_cmd)) { - if (cmd_val->slen > 0) - return PJ_CLI_ETOOMANYARGS; - else - return PJ_SUCCESS; + if (cmd_val->slen > 0) + return PJ_CLI_ETOOMANYARGS; + else + return PJ_SUCCESS; } if (cmd->arg_cnt > 0) { - arg = &cmd->arg[argc-1]; - PJ_ASSERT_RETURN(arg, PJ_EINVAL); - if (arg->type == PJ_CLI_ARG_CHOICE) { - unsigned j; - - if ((parse_mode == PARSE_EXEC) && (!arg->validate)) { - /* If no validation needed, then insert the values */ - status = insert_new_hint(pool, cmd_val, NULL, NULL, info); - return status; - } - - for (j=0; j < arg->stat_choice_cnt; ++j) { - pj_cli_arg_choice_val *choice_val = &arg->stat_choice_val[j]; - - PJ_ASSERT_RETURN(choice_val, PJ_EINVAL); - - if (!pj_strncmp(&choice_val->value, cmd_val, cmd_val->slen)) { - status = insert_new_hint(pool, - &choice_val->value, - &choice_val->desc, - &arg_type[PJ_CLI_ARG_CHOICE].msg, - info); - if (status != PJ_SUCCESS) - return status; - } - } - if (arg->get_dyn_choice) { - pj_cli_dyn_choice_param dyn_choice_param; - static pj_str_t choice_str = {"choice", 6}; - - /* Get the dynamic choice values */ - dyn_choice_param.sess = sess; - dyn_choice_param.cmd = cmd; - dyn_choice_param.arg_id = arg->id; - dyn_choice_param.max_cnt = PJ_CLI_MAX_CHOICE_VAL; - dyn_choice_param.pool = pool; - dyn_choice_param.cnt = 0; - - (*arg->get_dyn_choice)(&dyn_choice_param); - for (j=0; j < dyn_choice_param.cnt; ++j) { - pj_cli_arg_choice_val *choice = &dyn_choice_param.choice[j]; - if (!pj_strncmp(&choice->value, cmd_val, cmd_val->slen)) { - pj_strassign(&info->hint[info->hint_cnt].name, - &choice->value); - pj_strassign(&info->hint[info->hint_cnt].type, - &choice_str); - pj_strassign(&info->hint[info->hint_cnt].desc, - &choice->desc); - if ((++info->hint_cnt) >= PJ_CLI_MAX_HINTS) - break; - } - } - if ((info->hint_cnt == 0) && (!arg->optional)) - return PJ_CLI_EMISSINGARG; - } - } else { - if (cmd_val->slen == 0) { - if (info->hint_cnt == 0) { - if (!((parse_mode == PARSE_EXEC) && (arg->optional))) { - /* For exec mode,no need to insert hint if optional */ - status = insert_new_hint(pool, - &arg->name, - &arg->desc, - &arg_type[arg->type].msg, - info); - if (status != PJ_SUCCESS) - return status; - } - if (!arg->optional) - return PJ_CLI_EMISSINGARG; - } - } else { - return insert_new_hint(pool, cmd_val, NULL, NULL, info); - } - } + arg = &cmd->arg[argc-1]; + PJ_ASSERT_RETURN(arg, PJ_EINVAL); + if (arg->type == PJ_CLI_ARG_CHOICE) { + unsigned j; + + if ((parse_mode == PARSE_EXEC) && (!arg->validate)) { + /* If no validation needed, then insert the values */ + status = insert_new_hint(pool, cmd_val, NULL, NULL, info); + return status; + } + + for (j=0; j < arg->stat_choice_cnt; ++j) { + pj_cli_arg_choice_val *choice_val = &arg->stat_choice_val[j]; + + PJ_ASSERT_RETURN(choice_val, PJ_EINVAL); + + if (!pj_strncmp(&choice_val->value, cmd_val, cmd_val->slen)) { + status = insert_new_hint(pool, + &choice_val->value, + &choice_val->desc, + &arg_type[PJ_CLI_ARG_CHOICE].msg, + info); + if (status != PJ_SUCCESS) + return status; + } + } + if (arg->get_dyn_choice) { + pj_cli_dyn_choice_param dyn_choice_param; + static pj_str_t choice_str = {"choice", 6}; + + /* Get the dynamic choice values */ + dyn_choice_param.sess = sess; + dyn_choice_param.cmd = cmd; + dyn_choice_param.arg_id = arg->id; + dyn_choice_param.max_cnt = PJ_CLI_MAX_CHOICE_VAL; + dyn_choice_param.pool = pool; + dyn_choice_param.cnt = 0; + + (*arg->get_dyn_choice)(&dyn_choice_param); + for (j=0; j < dyn_choice_param.cnt; ++j) { + pj_cli_arg_choice_val *choice = &dyn_choice_param.choice[j]; + if (!pj_strncmp(&choice->value, cmd_val, cmd_val->slen)) { + pj_strassign(&info->hint[info->hint_cnt].name, + &choice->value); + pj_strassign(&info->hint[info->hint_cnt].type, + &choice_str); + pj_strassign(&info->hint[info->hint_cnt].desc, + &choice->desc); + if ((++info->hint_cnt) >= PJ_CLI_MAX_HINTS) + break; + } + } + if ((info->hint_cnt == 0) && (!arg->optional)) + return PJ_CLI_EMISSINGARG; + } + } else { + if (cmd_val->slen == 0) { + if (info->hint_cnt == 0) { + if (!((parse_mode == PARSE_EXEC) && (arg->optional))) { + /* For exec mode,no need to insert hint if optional */ + status = insert_new_hint(pool, + &arg->name, + &arg->desc, + &arg_type[arg->type].msg, + info); + if (status != PJ_SUCCESS) + return status; + } + if (!arg->optional) + return PJ_CLI_EMISSINGARG; + } + } else { + return insert_new_hint(pool, cmd_val, NULL, NULL, info); + } + } } return status; } @@ -1291,14 +1290,14 @@ static pj_status_t get_match_args(pj_cli_sess *sess, /** This will check for a match of the commands/arguments input. Any match will be inserted to the hint data. **/ static pj_status_t get_available_cmds(pj_cli_sess *sess, - pj_cli_cmd_spec *cmd, - pj_str_t *cmd_val, - unsigned argc, - pj_pool_t *pool, - pj_bool_t get_cmd, - pj_cli_parse_mode parse_mode, - pj_cli_cmd_spec **p_cmd, - pj_cli_exec_info *info) + pj_cli_cmd_spec *cmd, + pj_str_t *cmd_val, + unsigned argc, + pj_pool_t *pool, + pj_bool_t get_cmd, + pj_cli_parse_mode parse_mode, + pj_cli_cmd_spec **p_cmd, + pj_cli_exec_info *info) { pj_status_t status = PJ_SUCCESS; pj_str_t *prefix; @@ -1309,49 +1308,49 @@ static pj_status_t get_available_cmds(pj_cli_sess *sess, info->hint_cnt = 0; if (get_cmd) { - status = get_comp_match_cmds(sess->fe->cli, cmd, prefix, pool, p_cmd, - info); - if (status != PJ_SUCCESS) - return status; - - /** If exact match found, then no need to search for pattern match **/ - if (info->hint_cnt == 0) { - if ((parse_mode != PARSE_NEXT_AVAIL) && - (cmd == &sess->fe->cli->root)) - { - /** Pattern match for shortcut needed on root command only **/ - status = get_pattern_match_shortcut(sess->fe->cli, prefix, pool, - p_cmd, info); - - if (status != PJ_SUCCESS) - return status; - } - - status = get_pattern_match_cmds(cmd, prefix, pool, p_cmd, - parse_mode, info); - } - - if (status != PJ_SUCCESS) - return status; + status = get_comp_match_cmds(sess->fe->cli, cmd, prefix, pool, p_cmd, + info); + if (status != PJ_SUCCESS) + return status; + + /** If exact match found, then no need to search for pattern match **/ + if (info->hint_cnt == 0) { + if ((parse_mode != PARSE_NEXT_AVAIL) && + (cmd == &sess->fe->cli->root)) + { + /** Pattern match for shortcut needed on root command only **/ + status = get_pattern_match_shortcut(sess->fe->cli, prefix, pool, + p_cmd, info); + + if (status != PJ_SUCCESS) + return status; + } + + status = get_pattern_match_cmds(cmd, prefix, pool, p_cmd, + parse_mode, info); + } + + if (status != PJ_SUCCESS) + return status; } if (argc > 0) - status = get_match_args(sess, cmd, prefix, argc, - pool, parse_mode, info); - - if (status == PJ_SUCCESS) { - if (prefix->slen > 0) { - /** If a command entered is not a an empty command, and have a - single match in the command list then it is a valid command **/ - if (info->hint_cnt == 0) { - status = PJ_CLI_EINVARG; - } else if (info->hint_cnt > 1) { - status = PJ_CLI_EAMBIGUOUS; - } - } else { - if (info->hint_cnt > 0) - status = PJ_CLI_EAMBIGUOUS; - } + status = get_match_args(sess, cmd, prefix, argc, + pool, parse_mode, info); + + if (status == PJ_SUCCESS) { + if (prefix->slen > 0) { + /** If a command entered is not a an empty command, and have a + single match in the command list then it is a valid command **/ + if (info->hint_cnt == 0) { + status = PJ_CLI_EINVARG; + } else if (info->hint_cnt > 1) { + status = PJ_CLI_EAMBIGUOUS; + } + } else { + if (info->hint_cnt > 0) + status = PJ_CLI_EAMBIGUOUS; + } } return status; diff --git a/pjlib-util/src/pjlib-util/cli_console.c b/pjlib-util/src/pjlib-util/cli_console.c index 5f5528f7cb..36af9477d7 100644 --- a/pjlib-util/src/pjlib-util/cli_console.c +++ b/pjlib-util/src/pjlib-util/cli_console.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) * @@ -57,7 +56,7 @@ struct cli_console_fe }; static void console_write_log(pj_cli_front_end *fe, int level, - const char *data, pj_size_t len) + const char *data, pj_size_t len) { struct cli_console_fe * cfe = (struct cli_console_fe *)fe; @@ -91,7 +90,7 @@ static void console_destroy(pj_cli_front_end *fe) if (cfe->input_thread) { pj_thread_destroy(cfe->input_thread); - cfe->input_thread = NULL; + cfe->input_thread = NULL; } pj_sem_destroy(cfe->thread_sem); @@ -109,9 +108,9 @@ PJ_DEF(void) pj_cli_console_cfg_default(pj_cli_console_cfg *param) } PJ_DEF(pj_status_t) pj_cli_console_create(pj_cli_t *cli, - const pj_cli_console_cfg *param, - pj_cli_sess **p_sess, - pj_cli_front_end **p_fe) + const pj_cli_console_cfg *param, + pj_cli_sess **p_sess, + pj_cli_front_end **p_fe) { pj_cli_sess *sess; struct cli_console_fe *fe; @@ -147,26 +146,26 @@ PJ_DEF(pj_status_t) pj_cli_console_create(pj_cli_t *cli, fe->sess = sess; status = pj_sem_create(pool, "console_fe", 0, 1, &fe->thread_sem); if (status != PJ_SUCCESS) - return status; + return status; status = pj_sem_create(pool, "console_fe", 0, 1, &fe->input.sem); if (status != PJ_SUCCESS) - return status; + return status; pj_cli_register_front_end(cli, &fe->base); if (param->prompt_str.slen == 0) { - pj_str_t prompt_sign = pj_str(">>> "); - fe->cfg.prompt_str.ptr = pj_pool_alloc(fe->pool, prompt_sign.slen+1); - pj_strcpy(&fe->cfg.prompt_str, &prompt_sign); + pj_str_t prompt_sign = pj_str(">>> "); + fe->cfg.prompt_str.ptr = pj_pool_alloc(fe->pool, prompt_sign.slen+1); + pj_strcpy(&fe->cfg.prompt_str, &prompt_sign); } else { - fe->cfg.prompt_str.ptr = pj_pool_alloc(fe->pool, - param->prompt_str.slen+1); - pj_strcpy(&fe->cfg.prompt_str, ¶m->prompt_str); + fe->cfg.prompt_str.ptr = pj_pool_alloc(fe->pool, + param->prompt_str.slen+1); + pj_strcpy(&fe->cfg.prompt_str, ¶m->prompt_str); } fe->cfg.prompt_str.ptr[fe->cfg.prompt_str.slen] = 0; if (param->quit_command.slen) - pj_strdup(fe->pool, &fe->cfg.quit_command, ¶m->quit_command); + pj_strdup(fe->pool, &fe->cfg.quit_command, ¶m->quit_command); *p_sess = sess; if (p_fe) @@ -191,9 +190,9 @@ static void send_prompt_str(pj_cli_sess *sess) } static void send_err_arg(pj_cli_sess *sess, - const pj_cli_exec_info *info, - const pj_str_t *msg, - pj_bool_t with_return) + const pj_cli_exec_info *info, + const pj_str_t *msg, + pj_bool_t with_return) { pj_str_t send_data; char data_str[256]; @@ -205,12 +204,12 @@ static void send_err_arg(pj_cli_sess *sess, send_data.slen = 0; if (with_return) - pj_strcat2(&send_data, "\r\n"); + pj_strcat2(&send_data, "\r\n"); len = fe->cfg.prompt_str.slen + info->err_pos; for (i=0;islen > 0)) { - int j; - - for (j=0;j<(max_len-cmd_len);++j) { - pj_strcat2(send_data, " "); - } - pj_strcat2(send_data, " "); - pj_strcat(send_data, desc); - send_data->ptr[send_data->slen] = 0; - printf("%s", send_data->ptr); - send_data->slen = 0; + int j; + + for (j=0;j<(max_len-cmd_len);++j) { + pj_strcat2(send_data, " "); + } + pj_strcat2(send_data, " "); + pj_strcat(send_data, desc); + send_data->ptr[send_data->slen] = 0; + printf("%s", send_data->ptr); + send_data->slen = 0; } } static void send_ambi_arg(pj_cli_sess *sess, - const pj_cli_exec_info *info, - pj_bool_t with_return) + const pj_cli_exec_info *info, + pj_bool_t with_return) { unsigned i; pj_size_t len; @@ -275,92 +274,92 @@ static void send_ambi_arg(pj_cli_sess *sess, send_data.slen = 0; if (with_return) - pj_strcat2(&send_data, "\r\n"); + pj_strcat2(&send_data, "\r\n"); len = fe->cfg.prompt_str.slen + info->err_pos; for (i=0;ihint_cnt;++i) { - if (hint[i].type.slen > 0) { - if (pj_stricmp(&hint[i].type, &sc_type) == 0) { - if ((i > 0) && (!pj_stricmp(&hint[i-1].desc, &hint[i].desc))) { - cmd_length += (hint[i].name.slen + 3); - } else { - cmd_length = hint[i].name.slen; - } - } else { - cmd_length = hint[i].name.slen; - } - } else { - cmd_length = hint[i].name.slen; - } - - if (cmd_length > max_length) { - max_length = cmd_length; - } + if (hint[i].type.slen > 0) { + if (pj_stricmp(&hint[i].type, &sc_type) == 0) { + if ((i > 0) && (!pj_stricmp(&hint[i-1].desc, &hint[i].desc))) { + cmd_length += (hint[i].name.slen + 3); + } else { + cmd_length = hint[i].name.slen; + } + } else { + cmd_length = hint[i].name.slen; + } + } else { + cmd_length = hint[i].name.slen; + } + + if (cmd_length > max_length) { + max_length = cmd_length; + } } cmd_length = 0; for (i=0;ihint_cnt;++i) { - if (hint[i].type.slen > 0) { - if (pj_stricmp(&hint[i].type, &sc_type) == 0) { - parse_state = OP_SHORTCUT; - } else if (pj_stricmp(&hint[i].type, &choice_type) == 0) { - parse_state = OP_CHOICE; - } else { - parse_state = OP_TYPE; - } - } else { - parse_state = OP_NORMAL; - } - - if (parse_state != OP_SHORTCUT) { - pj_strcat2(&send_data, "\r\n "); - cmd_length = hint[i].name.slen; - } - - switch (parse_state) { - case OP_CHOICE: - pj_strcat2(&send_data, "["); - pj_strcat(&send_data, &hint[i].name); - pj_strcat2(&send_data, "]"); - break; - case OP_TYPE: - pj_strcat2(&send_data, "<"); - pj_strcat(&send_data, &hint[i].type); - pj_strcat2(&send_data, ">"); - break; - case OP_SHORTCUT: - /* Format : "Command | sc | description" */ - { - cmd_length += hint[i].name.slen; - if ((i > 0) && (!pj_stricmp(&hint[i-1].desc, &hint[i].desc))) { - pj_strcat2(&send_data, " | "); - cmd_length += 3; - } else { - pj_strcat2(&send_data, "\r\n "); - } - pj_strcat(&send_data, &hint[i].name); - } - break; - default: - pj_strcat(&send_data, &hint[i].name); - break; - } - - if ((parse_state == OP_TYPE) || (parse_state == OP_CHOICE) || - ((i+1) >= info->hint_cnt) || - (pj_strncmp(&hint[i].desc, &hint[i+1].desc, hint[i].desc.slen))) - { - /* Add description info */ - send_hint_arg(&send_data, &hint[i].desc, cmd_length, max_length); - - cmd_length = 0; - } + if (hint[i].type.slen > 0) { + if (pj_stricmp(&hint[i].type, &sc_type) == 0) { + parse_state = OP_SHORTCUT; + } else if (pj_stricmp(&hint[i].type, &choice_type) == 0) { + parse_state = OP_CHOICE; + } else { + parse_state = OP_TYPE; + } + } else { + parse_state = OP_NORMAL; + } + + if (parse_state != OP_SHORTCUT) { + pj_strcat2(&send_data, "\r\n "); + cmd_length = hint[i].name.slen; + } + + switch (parse_state) { + case OP_CHOICE: + pj_strcat2(&send_data, "["); + pj_strcat(&send_data, &hint[i].name); + pj_strcat2(&send_data, "]"); + break; + case OP_TYPE: + pj_strcat2(&send_data, "<"); + pj_strcat(&send_data, &hint[i].type); + pj_strcat2(&send_data, ">"); + break; + case OP_SHORTCUT: + /* Format : "Command | sc | description" */ + { + cmd_length += hint[i].name.slen; + if ((i > 0) && (!pj_stricmp(&hint[i-1].desc, &hint[i].desc))) { + pj_strcat2(&send_data, " | "); + cmd_length += 3; + } else { + pj_strcat2(&send_data, "\r\n "); + } + pj_strcat(&send_data, &hint[i].name); + } + break; + default: + pj_strcat(&send_data, &hint[i].name); + break; + } + + if ((parse_state == OP_TYPE) || (parse_state == OP_CHOICE) || + ((i+1) >= info->hint_cnt) || + (pj_strncmp(&hint[i].desc, &hint[i+1].desc, hint[i].desc.slen))) + { + /* Add description info */ + send_hint_arg(&send_data, &hint[i].desc, cmd_length, max_length); + + cmd_length = 0; + } } pj_strcat2(&send_data, "\r\n"); pj_strcat(&send_data, &fe->cfg.prompt_str); @@ -387,27 +386,27 @@ static pj_bool_t handle_hint(pj_cli_sess *sess) cmd_val = PJ_POOL_ZALLOC_T(pool, pj_cli_cmd_val); status = pj_cli_sess_parse(sess, recv_buf, cmd_val, - pool, &info); + pool, &info); switch (status) { case PJ_CLI_EINVARG: - send_inv_arg(sess, &info, PJ_TRUE); - break; + send_inv_arg(sess, &info, PJ_TRUE); + break; case PJ_CLI_ETOOMANYARGS: - send_too_many_arg(sess, &info, PJ_TRUE); - break; + send_too_many_arg(sess, &info, PJ_TRUE); + break; case PJ_CLI_EMISSINGARG: case PJ_CLI_EAMBIGUOUS: - send_ambi_arg(sess, &info, PJ_TRUE); - break; + send_ambi_arg(sess, &info, PJ_TRUE); + break; case PJ_SUCCESS: - if (info.hint_cnt > 0) { - /* Compelete command */ - send_ambi_arg(sess, &info, PJ_TRUE); - } else { - retval = PJ_FALSE; - } - break; + if (info.hint_cnt > 0) { + /* Compelete command */ + send_ambi_arg(sess, &info, PJ_TRUE); + } else { + retval = PJ_FALSE; + } + break; } pj_pool_release(pool); @@ -428,29 +427,29 @@ static pj_bool_t handle_exec(pj_cli_sess *sess) printf("\r\n"); pool = pj_pool_create(pj_cli_get_param(cli)->pf, "handle_exec", - PJ_CLI_CONSOLE_POOL_SIZE, PJ_CLI_CONSOLE_POOL_INC, - NULL); + PJ_CLI_CONSOLE_POOL_SIZE, PJ_CLI_CONSOLE_POOL_INC, + NULL); status = pj_cli_sess_exec(sess, recv_buf, - pool, &info); + pool, &info); switch (status) { case PJ_CLI_EINVARG: - send_inv_arg(sess, &info, PJ_FALSE); - break; + send_inv_arg(sess, &info, PJ_FALSE); + break; case PJ_CLI_ETOOMANYARGS: - send_too_many_arg(sess, &info, PJ_FALSE); - break; + send_too_many_arg(sess, &info, PJ_FALSE); + break; case PJ_CLI_EAMBIGUOUS: case PJ_CLI_EMISSINGARG: - send_ambi_arg(sess, &info, PJ_FALSE); - break; + send_ambi_arg(sess, &info, PJ_FALSE); + break; case PJ_CLI_EEXIT: - retval = PJ_FALSE; - break; + retval = PJ_FALSE; + break; case PJ_SUCCESS: - send_prompt_str(sess); - break; + send_prompt_str(sess); + break; } pj_pool_release(pool); @@ -464,54 +463,54 @@ static int readline_thread(void * p) printf("%s", fe->cfg.prompt_str.ptr); while (!fe->thread_quit) { - pj_size_t input_len = 0; - pj_str_t input_str; - char *recv_buf = fe->input.buf; - pj_bool_t is_valid = PJ_TRUE; - - if (fgets(recv_buf, fe->input.maxlen, stdin) == NULL) { - /* - * Be friendly to users who redirect commands into - * program, when file ends, resume with kbd. - * If exit is desired end script with q for quit - */ - /* Reopen stdin/stdout/stderr to /dev/console */ + pj_size_t input_len = 0; + pj_str_t input_str; + char *recv_buf = fe->input.buf; + pj_bool_t is_valid = PJ_TRUE; + + if (fgets(recv_buf, fe->input.maxlen, stdin) == NULL) { + /* + * Be friendly to users who redirect commands into + * program, when file ends, resume with kbd. + * If exit is desired end script with q for quit + */ + /* Reopen stdin/stdout/stderr to /dev/console */ #if ((defined(PJ_WIN32) && PJ_WIN32!=0) || \ (defined(PJ_WIN64) && PJ_WIN64!=0)) && \ (!defined(PJ_WIN32_WINCE) || PJ_WIN32_WINCE==0) - if (freopen ("CONIN$", "r", stdin) == NULL) { + if (freopen ("CONIN$", "r", stdin) == NULL) { #else - if (1) { + if (1) { #endif - puts("Cannot switch back to console from file redirection"); - if (fe->cfg.quit_command.slen) { - pj_memcpy(recv_buf, fe->cfg.quit_command.ptr, - fe->input.maxlen); - } - recv_buf[fe->cfg.quit_command.slen] = '\0'; - } else { - puts("Switched back to console from file redirection"); - continue; - } - } - - input_str.ptr = recv_buf; - input_str.slen = pj_ansi_strlen(recv_buf); - pj_strrtrim(&input_str); - recv_buf[input_str.slen] = '\n'; - recv_buf[input_str.slen+1] = 0; - if (fe->thread_quit) { - break; - } - input_len = pj_ansi_strlen(fe->input.buf); - if ((input_len > 1) && (fe->input.buf[input_len-2] == '?')) { - fe->input.buf[input_len-1] = 0; - is_valid = handle_hint(fe->sess); - if (!is_valid) - printf("%s", fe->cfg.prompt_str.ptr); - } else { - is_valid = handle_exec(fe->sess); - } + puts("Cannot switch back to console from file redirection"); + if (fe->cfg.quit_command.slen) { + pj_memcpy(recv_buf, fe->cfg.quit_command.ptr, + fe->input.maxlen); + } + recv_buf[fe->cfg.quit_command.slen] = '\0'; + } else { + puts("Switched back to console from file redirection"); + continue; + } + } + + input_str.ptr = recv_buf; + input_str.slen = pj_ansi_strlen(recv_buf); + pj_strrtrim(&input_str); + recv_buf[input_str.slen] = '\n'; + recv_buf[input_str.slen+1] = 0; + if (fe->thread_quit) { + break; + } + input_len = pj_ansi_strlen(fe->input.buf); + if ((input_len > 1) && (fe->input.buf[input_len-2] == '?')) { + fe->input.buf[input_len-1] = 0; + is_valid = handle_hint(fe->sess); + if (!is_valid) + printf("%s", fe->cfg.prompt_str.ptr); + } else { + is_valid = handle_exec(fe->sess); + } pj_sem_post(fe->input.sem); pj_sem_wait(fe->thread_sem); @@ -521,8 +520,8 @@ static int readline_thread(void * p) } PJ_DEF(pj_status_t) pj_cli_console_process(pj_cli_sess *sess, - char *buf, - unsigned maxlen) + char *buf, + unsigned maxlen) { struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe; diff --git a/pjlib-util/src/pjlib-util/cli_telnet.c b/pjlib-util/src/pjlib-util/cli_telnet.c index 857edb36f2..28286ede1c 100644 --- a/pjlib-util/src/pjlib-util/cli_telnet.c +++ b/pjlib-util/src/pjlib-util/cli_telnet.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) * @@ -52,7 +51,7 @@ #if 1 /* Enable some tracing */ #define THIS_FILE "cli_telnet.c" - #define TRACE_(arg) PJ_LOG(3,arg) + #define TRACE_(arg) PJ_LOG(3,arg) #else #define TRACE_(arg) #endif @@ -72,14 +71,14 @@ */ enum cli_telnet_option_states { - OPT_DISABLE, /* Option disable */ - OPT_ENABLE, /* Option enable */ - OPT_EXPECT_DISABLE, /* Already send disable req, expecting resp */ - OPT_EXPECT_ENABLE, /* Already send enable req, expecting resp */ - OPT_EXPECT_DISABLE_REV, /* Already send disable req, expecting resp, - * need to send enable req */ - OPT_EXPECT_ENABLE_REV /* Already send enable req, expecting resp, - * need to send disable req */ + OPT_DISABLE, /* Option disable */ + OPT_ENABLE, /* Option enable */ + OPT_EXPECT_DISABLE, /* Already send disable req, expecting resp */ + OPT_EXPECT_ENABLE, /* Already send enable req, expecting resp */ + OPT_EXPECT_DISABLE_REV, /* Already send disable req, expecting resp, + * need to send enable req */ + OPT_EXPECT_ENABLE_REV /* Already send enable req, expecting resp, + * need to send disable req */ }; /** @@ -129,95 +128,95 @@ typedef enum cmd_parse_state typedef enum cli_telnet_command { - SUBNEGO_END = 240, /* End of subnegotiation parameters. */ - NOP = 241, /* No operation. */ - DATA_MARK = 242, /* Marker for NVT cleaning. */ - BREAK = 243, /* Indicates that the "break" key was hit. */ - INT_PROCESS = 244, /* Suspend, interrupt or abort the process. */ - ABORT_OUTPUT = 245, /* Abort output, abort output stream. */ - ARE_YOU_THERE = 246, /* Are you there. */ - ERASE_CHAR = 247, /* Erase character, erase the current char. */ - ERASE_LINE = 248, /* Erase line, erase the current line. */ - GO_AHEAD = 249, /* Go ahead, other end can transmit. */ - SUBNEGO_BEGIN = 250, /* Subnegotiation begin. */ - WILL = 251, /* Accept the use of option. */ - WONT = 252, /* Refuse the use of option. */ - DO = 253, /* Request to use option. */ - DONT = 254, /* Request to not use option. */ - IAC = 255 /* Interpret as command */ + SUBNEGO_END = 240, /* End of subnegotiation parameters. */ + NOP = 241, /* No operation. */ + DATA_MARK = 242, /* Marker for NVT cleaning. */ + BREAK = 243, /* Indicates that the "break" key was hit. */ + INT_PROCESS = 244, /* Suspend, interrupt or abort the process. */ + ABORT_OUTPUT = 245, /* Abort output, abort output stream. */ + ARE_YOU_THERE = 246, /* Are you there. */ + ERASE_CHAR = 247, /* Erase character, erase the current char. */ + ERASE_LINE = 248, /* Erase line, erase the current line. */ + GO_AHEAD = 249, /* Go ahead, other end can transmit. */ + SUBNEGO_BEGIN = 250, /* Subnegotiation begin. */ + WILL = 251, /* Accept the use of option. */ + WONT = 252, /* Refuse the use of option. */ + DO = 253, /* Request to use option. */ + DONT = 254, /* Request to not use option. */ + IAC = 255 /* Interpret as command */ } cli_telnet_command; enum cli_telnet_options { - TRANSMIT_BINARY = 0, /* Transmit Binary. */ - TERM_ECHO = 1, /* Echo. */ - RECONNECT = 2, /* Reconnection. */ - SUPPRESS_GA = 3, /* Suppress Go Aheah. */ - MESSAGE_SIZE_NEGO = 4, /* Approx Message Size Negotiation. */ - STATUS = 5, /* Status. */ - TIMING_MARK = 6, /* Timing Mark. */ - RTCE_OPTION = 7, /* Remote Controlled Trans and Echo. */ - OUTPUT_LINE_WIDTH = 8, /* Output Line Width. */ - OUTPUT_PAGE_SIZE = 9, /* Output Page Size. */ - CR_DISPOSITION = 10, /* Carriage-Return Disposition. */ - HORI_TABSTOPS = 11, /* Horizontal Tabstops. */ - HORI_TAB_DISPO = 12, /* Horizontal Tab Disposition. */ - FF_DISP0 = 13, /* Formfeed Disposition. */ - VERT_TABSTOPS = 14, /* Vertical Tabstops. */ - VERT_TAB_DISPO = 15, /* Vertical Tab Disposition. */ - LF_DISP0 = 16, /* Linefeed Disposition. */ - EXT_ASCII = 17, /* Extended ASCII. */ - LOGOUT = 18, /* Logout. */ - BYTE_MACRO = 19, /* Byte Macro. */ - DE_TERMINAL = 20, /* Data Entry Terminal. */ - SUPDUP_PROTO = 21, /* SUPDUP Protocol. */ - SUPDUP_OUTPUT = 22, /* SUPDUP Output. */ - SEND_LOC = 23, /* Send Location. */ - TERM_TYPE = 24, /* Terminal Type. */ - EOR = 25, /* End of Record. */ - TACACS_UID = 26, /* TACACS User Identification. */ - OUTPUT_MARKING = 27, /* Output Marking. */ - TTYLOC = 28, /* Terminal Location Number. */ - USE_3270_REGIME = 29, /* Telnet 3270 Regime. */ - USE_X3_PAD = 30, /* X.3 PAD. */ - WINDOW_SIZE = 31, /* Window Size. */ - TERM_SPEED = 32, /* Terminal Speed. */ - REM_FLOW_CONTROL = 33, /* Remote Flow Control. */ - LINE_MODE = 34, /* Linemode. */ - X_DISP_LOC = 35, /* X Display Location. */ - ENVIRONMENT = 36, /* Environment. */ - AUTH = 37, /* Authentication. */ - ENCRYPTION = 38, /* Encryption Option. */ - NEW_ENVIRONMENT = 39, /* New Environment. */ - TN_3270E = 40, /* TN3270E. */ - XAUTH = 41, /* XAUTH. */ - CHARSET = 42, /* CHARSET. */ - REM_SERIAL_PORT = 43, /* Telnet Remote Serial Port. */ - COM_PORT_CONTROL = 44, /* Com Port Control. */ - SUPP_LOCAL_ECHO = 45, /* Telnet Suppress Local Echo. */ - START_TLS = 46, /* Telnet Start TLS. */ - KERMIT = 47, /* KERMIT. */ - SEND_URL = 48, /* SEND-URL. */ - FWD_X = 49, /* FORWARD_X. */ - EXT_OPTIONS = 255 /* Extended-Options-List */ + TRANSMIT_BINARY = 0, /* Transmit Binary. */ + TERM_ECHO = 1, /* Echo. */ + RECONNECT = 2, /* Reconnection. */ + SUPPRESS_GA = 3, /* Suppress Go Aheah. */ + MESSAGE_SIZE_NEGO = 4, /* Approx Message Size Negotiation. */ + STATUS = 5, /* Status. */ + TIMING_MARK = 6, /* Timing Mark. */ + RTCE_OPTION = 7, /* Remote Controlled Trans and Echo. */ + OUTPUT_LINE_WIDTH = 8, /* Output Line Width. */ + OUTPUT_PAGE_SIZE = 9, /* Output Page Size. */ + CR_DISPOSITION = 10, /* Carriage-Return Disposition. */ + HORI_TABSTOPS = 11, /* Horizontal Tabstops. */ + HORI_TAB_DISPO = 12, /* Horizontal Tab Disposition. */ + FF_DISP0 = 13, /* Formfeed Disposition. */ + VERT_TABSTOPS = 14, /* Vertical Tabstops. */ + VERT_TAB_DISPO = 15, /* Vertical Tab Disposition. */ + LF_DISP0 = 16, /* Linefeed Disposition. */ + EXT_ASCII = 17, /* Extended ASCII. */ + LOGOUT = 18, /* Logout. */ + BYTE_MACRO = 19, /* Byte Macro. */ + DE_TERMINAL = 20, /* Data Entry Terminal. */ + SUPDUP_PROTO = 21, /* SUPDUP Protocol. */ + SUPDUP_OUTPUT = 22, /* SUPDUP Output. */ + SEND_LOC = 23, /* Send Location. */ + TERM_TYPE = 24, /* Terminal Type. */ + EOR = 25, /* End of Record. */ + TACACS_UID = 26, /* TACACS User Identification. */ + OUTPUT_MARKING = 27, /* Output Marking. */ + TTYLOC = 28, /* Terminal Location Number. */ + USE_3270_REGIME = 29, /* Telnet 3270 Regime. */ + USE_X3_PAD = 30, /* X.3 PAD. */ + WINDOW_SIZE = 31, /* Window Size. */ + TERM_SPEED = 32, /* Terminal Speed. */ + REM_FLOW_CONTROL = 33, /* Remote Flow Control. */ + LINE_MODE = 34, /* Linemode. */ + X_DISP_LOC = 35, /* X Display Location. */ + ENVIRONMENT = 36, /* Environment. */ + AUTH = 37, /* Authentication. */ + ENCRYPTION = 38, /* Encryption Option. */ + NEW_ENVIRONMENT = 39, /* New Environment. */ + TN_3270E = 40, /* TN3270E. */ + XAUTH = 41, /* XAUTH. */ + CHARSET = 42, /* CHARSET. */ + REM_SERIAL_PORT = 43, /* Telnet Remote Serial Port. */ + COM_PORT_CONTROL = 44, /* Com Port Control. */ + SUPP_LOCAL_ECHO = 45, /* Telnet Suppress Local Echo. */ + START_TLS = 46, /* Telnet Start TLS. */ + KERMIT = 47, /* KERMIT. */ + SEND_URL = 48, /* SEND-URL. */ + FWD_X = 49, /* FORWARD_X. */ + EXT_OPTIONS = 255 /* Extended-Options-List */ }; enum terminal_cmd { - TC_ESC = 27, - TC_UP = 65, - TC_DOWN = 66, - TC_RIGHT = 67, - TC_LEFT = 68, - TC_END = 70, - TC_HOME = 72, - TC_CTRL_C = 3, - TC_CR = 13, - TC_BS = 8, - TC_TAB = 9, - TC_QM = 63, - TC_BELL = 7, - TC_DEL = 127 + TC_ESC = 27, + TC_UP = 65, + TC_DOWN = 66, + TC_RIGHT = 67, + TC_LEFT = 68, + TC_END = 70, + TC_HOME = 72, + TC_CTRL_C = 3, + TC_CR = 13, + TC_BS = 8, + TC_TAB = 9, + TC_QM = 63, + TC_BELL = 7, + TC_DEL = 127 }; /** @@ -241,17 +240,17 @@ typedef struct telnet_recv_buf { /** * Buffer containing the characters, NULL terminated. */ - unsigned char rbuf[PJ_CLI_MAX_CMDBUF]; + unsigned char rbuf[PJ_CLI_MAX_CMDBUF]; /** * Current length of the command line. */ - unsigned len; + unsigned len; /** * Current cursor position. */ - unsigned cur_pos; + unsigned cur_pos; } telnet_recv_buf; /** @@ -267,20 +266,20 @@ typedef struct cmd_history typedef struct cli_telnet_sess { - pj_cli_sess base; - pj_pool_t *pool; - pj_activesock_t *asock; - pj_bool_t authorized; - pj_ioqueue_op_key_t op_key; - pj_mutex_t *smutex; - cmd_parse_state parse_state; + pj_cli_sess base; + pj_pool_t *pool; + pj_activesock_t *asock; + pj_bool_t authorized; + pj_ioqueue_op_key_t op_key; + pj_mutex_t *smutex; + cmd_parse_state parse_state; cli_telnet_sess_option telnet_option[MAX_CLI_TELNET_OPTIONS]; - cmd_history *history; - cmd_history *active_history; + cmd_history *history; + cmd_history *active_history; - telnet_recv_buf *rcmd; - unsigned char buf[CLI_TELNET_BUF_SIZE + MAX_CUT_MSG_LEN]; - unsigned buf_len; + telnet_recv_buf *rcmd; + unsigned char buf[CLI_TELNET_BUF_SIZE + MAX_CUT_MSG_LEN]; + unsigned buf_len; } cli_telnet_sess; typedef struct cli_telnet_fe @@ -291,7 +290,7 @@ typedef struct cli_telnet_fe pj_bool_t own_ioqueue; pj_cli_sess sess_head; - pj_activesock_t *asock; + pj_activesock_t *asock; pj_thread_t *worker_thread; pj_bool_t is_quitting; pj_mutex_t *mutex; @@ -320,29 +319,29 @@ static unsigned recv_buf_right_len(telnet_recv_buf *recv_buf) * Insert character to the receive buffer. */ static pj_bool_t recv_buf_insert(telnet_recv_buf *recv_buf, - unsigned char *data) + unsigned char *data) { if (recv_buf->len+1 >= PJ_CLI_MAX_CMDBUF) { - return PJ_FALSE; + return PJ_FALSE; } else { - if (*data == '\t' || *data == '?' || *data == '\r') { - /* Always insert to the end of line */ - recv_buf->rbuf[recv_buf->len] = *data; - } else { - /* Insert based on the current cursor pos */ - unsigned cur_pos = recv_buf->cur_pos; - unsigned rlen = recv_buf_right_len(recv_buf); - if (rlen > 0) { - /* Shift right characters */ - pj_memmove(&recv_buf->rbuf[cur_pos+1], - &recv_buf->rbuf[cur_pos], - rlen+1); - } - recv_buf->rbuf[cur_pos] = *data; - } - ++recv_buf->cur_pos; - ++recv_buf->len; - recv_buf->rbuf[recv_buf->len] = 0; + if (*data == '\t' || *data == '?' || *data == '\r') { + /* Always insert to the end of line */ + recv_buf->rbuf[recv_buf->len] = *data; + } else { + /* Insert based on the current cursor pos */ + unsigned cur_pos = recv_buf->cur_pos; + unsigned rlen = recv_buf_right_len(recv_buf); + if (rlen > 0) { + /* Shift right characters */ + pj_memmove(&recv_buf->rbuf[cur_pos+1], + &recv_buf->rbuf[cur_pos], + rlen+1); + } + recv_buf->rbuf[cur_pos] = *data; + } + ++recv_buf->cur_pos; + ++recv_buf->len; + recv_buf->rbuf[recv_buf->len] = 0; } return PJ_TRUE; } @@ -353,18 +352,18 @@ static pj_bool_t recv_buf_insert(telnet_recv_buf *recv_buf, static pj_bool_t recv_buf_backspace(telnet_recv_buf *recv_buf) { if ((recv_buf->cur_pos == 0) || (recv_buf->len == 0)) { - return PJ_FALSE; + return PJ_FALSE; } else { - unsigned rlen = recv_buf_right_len(recv_buf); - if (rlen) { - unsigned cur_pos = recv_buf->cur_pos; - /* Shift left characters */ - pj_memmove(&recv_buf->rbuf[cur_pos-1], &recv_buf->rbuf[cur_pos], - rlen); - } - --recv_buf->cur_pos; - --recv_buf->len; - recv_buf->rbuf[recv_buf->len] = 0; + unsigned rlen = recv_buf_right_len(recv_buf); + if (rlen) { + unsigned cur_pos = recv_buf->cur_pos; + /* Shift left characters */ + pj_memmove(&recv_buf->rbuf[cur_pos-1], &recv_buf->rbuf[cur_pos], + rlen); + } + --recv_buf->cur_pos; + --recv_buf->len; + recv_buf->rbuf[recv_buf->len] = 0; } return PJ_TRUE; } @@ -381,7 +380,7 @@ static int compare_str(void *value, const pj_list_type *nd) * the first entry of the history. */ static pj_status_t insert_history(cli_telnet_sess *sess, - char *cmd_val) + char *cmd_val) { cmd_history *in_history; pj_str_t cmd; @@ -391,27 +390,27 @@ static pj_status_t insert_history(cli_telnet_sess *sess, cmd = pj_str(cmd_val); pj_strtrim(&cmd); if (cmd.slen == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Find matching history */ in_history = pj_list_search(sess->history, (void*)&cmd, compare_str); if (!in_history) { - if (pj_list_size(sess->history) < PJ_CLI_MAX_CMD_HISTORY) { - char *data_history; - in_history = PJ_POOL_ZALLOC_T(sess->pool, cmd_history); - pj_list_init(in_history); - data_history = (char *)pj_pool_calloc(sess->pool, - sizeof(char), PJ_CLI_MAX_CMDBUF); - in_history->command.ptr = data_history; - in_history->command.slen = 0; - } else { - /* Get the oldest history */ - in_history = sess->history->prev; - pj_list_erase(in_history); - } - pj_strncpy(&in_history->command, &cmd, PJ_CLI_MAX_CMDBUF); + if (pj_list_size(sess->history) < PJ_CLI_MAX_CMD_HISTORY) { + char *data_history; + in_history = PJ_POOL_ZALLOC_T(sess->pool, cmd_history); + pj_list_init(in_history); + data_history = (char *)pj_pool_calloc(sess->pool, + sizeof(char), PJ_CLI_MAX_CMDBUF); + in_history->command.ptr = data_history; + in_history->command.slen = 0; + } else { + /* Get the oldest history */ + in_history = sess->history->prev; + pj_list_erase(in_history); + } + pj_strncpy(&in_history->command, &cmd, PJ_CLI_MAX_CMDBUF); } else { - pj_list_erase(in_history); + pj_list_erase(in_history); } pj_list_push_front(sess->history, in_history); sess->active_history = sess->history; @@ -436,15 +435,15 @@ static pj_str_t* get_prev_history(cli_telnet_sess *sess, pj_bool_t is_forward) history_size = pj_list_size(sess->history); if (history_size == 0) { - return NULL; + return NULL; } else { - if (is_forward) { - node = (node->next==root)?node->next->next:node->next; - } else { - node = (node->prev==root)?node->prev->prev:node->prev; - } - retval = &node->command; - sess->active_history = node; + if (is_forward) { + node = (node->next==root)?node->next->next:node->next; + } else { + node = (node->prev==root)?node->prev->prev:node->prev; + } + retval = &node->command; + sess->active_history = node; } return retval; } @@ -456,8 +455,8 @@ static pj_str_t* get_prev_history(cli_telnet_sess *sess, pj_bool_t is_forward) * referenced - (RFC-854). */ static pj_bool_t send_telnet_cmd(cli_telnet_sess *sess, - cli_telnet_command cmd, - unsigned char option) + cli_telnet_command cmd, + unsigned char option) { unsigned char buf[3]; PJ_ASSERT_RETURN(sess, PJ_FALSE); @@ -478,8 +477,8 @@ static pj_bool_t send_telnet_cmd(cli_telnet_sess *sess, * negotiation process. */ static pj_bool_t send_enable_option(cli_telnet_sess *sess, - pj_bool_t is_local, - unsigned char option) + pj_bool_t is_local, + unsigned char option) { cli_telnet_sess_option *sess_option; enum cli_telnet_option_states *state; @@ -488,39 +487,39 @@ static pj_bool_t send_enable_option(cli_telnet_sess *sess, sess_option = &sess->telnet_option[option]; state = is_local?(&sess_option->local_state):(&sess_option->peer_state); switch (*state) { - case OPT_ENABLE: - /* Ignore if already enabled */ - break; - case OPT_DISABLE: - *state = OPT_EXPECT_ENABLE; - send_telnet_cmd(sess, (is_local?WILL:DO), option); - break; - case OPT_EXPECT_ENABLE: - *state = OPT_DISABLE; - break; - case OPT_EXPECT_DISABLE: - *state = OPT_EXPECT_DISABLE_REV; - break; - case OPT_EXPECT_ENABLE_REV: - *state = OPT_EXPECT_ENABLE; - break; - case OPT_EXPECT_DISABLE_REV: - *state = OPT_DISABLE; - break; - default: - return PJ_FALSE; + case OPT_ENABLE: + /* Ignore if already enabled */ + break; + case OPT_DISABLE: + *state = OPT_EXPECT_ENABLE; + send_telnet_cmd(sess, (is_local?WILL:DO), option); + break; + case OPT_EXPECT_ENABLE: + *state = OPT_DISABLE; + break; + case OPT_EXPECT_DISABLE: + *state = OPT_EXPECT_DISABLE_REV; + break; + case OPT_EXPECT_ENABLE_REV: + *state = OPT_EXPECT_ENABLE; + break; + case OPT_EXPECT_DISABLE_REV: + *state = OPT_DISABLE; + break; + default: + return PJ_FALSE; } return PJ_TRUE; } static pj_bool_t send_cmd_do(cli_telnet_sess *sess, - unsigned char option) + unsigned char option) { return send_enable_option(sess, PJ_FALSE, option); } static pj_bool_t send_cmd_will(cli_telnet_sess *sess, - unsigned char option) + unsigned char option) { return send_enable_option(sess, PJ_TRUE, option); } @@ -531,8 +530,8 @@ static pj_bool_t send_cmd_will(cli_telnet_sess *sess, * negotiation process. */ static pj_bool_t receive_enable_option(cli_telnet_sess *sess, - pj_bool_t is_local, - unsigned char option) + pj_bool_t is_local, + unsigned char option) { cli_telnet_sess_option *sess_opt; enum cli_telnet_option_states *state; @@ -543,32 +542,32 @@ static pj_bool_t receive_enable_option(cli_telnet_sess *sess, state = is_local?(&sess_opt->local_state):(&sess_opt->peer_state); opt_ena = is_local?sess_opt->local_is_enable:sess_opt->peer_is_enable; switch (*state) { - case OPT_ENABLE: - /* Ignore if already enabled */ - break; - case OPT_DISABLE: - if (opt_ena) { - *state = OPT_ENABLE; - send_telnet_cmd(sess, is_local?WILL:DO, option); - } else { - send_telnet_cmd(sess, is_local?WONT:DONT, option); - } - break; - case OPT_EXPECT_ENABLE: - *state = OPT_ENABLE; - break; - case OPT_EXPECT_DISABLE: - *state = OPT_DISABLE; - break; - case OPT_EXPECT_ENABLE_REV: - *state = OPT_EXPECT_DISABLE; - send_telnet_cmd(sess, is_local?WONT:DONT, option); - break; - case OPT_EXPECT_DISABLE_REV: - *state = OPT_EXPECT_DISABLE; - break; - default: - return PJ_FALSE; + case OPT_ENABLE: + /* Ignore if already enabled */ + break; + case OPT_DISABLE: + if (opt_ena) { + *state = OPT_ENABLE; + send_telnet_cmd(sess, is_local?WILL:DO, option); + } else { + send_telnet_cmd(sess, is_local?WONT:DONT, option); + } + break; + case OPT_EXPECT_ENABLE: + *state = OPT_ENABLE; + break; + case OPT_EXPECT_DISABLE: + *state = OPT_DISABLE; + break; + case OPT_EXPECT_ENABLE_REV: + *state = OPT_EXPECT_DISABLE; + send_telnet_cmd(sess, is_local?WONT:DONT, option); + break; + case OPT_EXPECT_DISABLE_REV: + *state = OPT_EXPECT_DISABLE; + break; + default: + return PJ_FALSE; } return PJ_TRUE; } @@ -579,8 +578,8 @@ static pj_bool_t receive_enable_option(cli_telnet_sess *sess, * negotiation process. */ static pj_bool_t receive_disable_option(cli_telnet_sess *sess, - pj_bool_t is_local, - unsigned char option) + pj_bool_t is_local, + unsigned char option) { cli_telnet_sess_option *sess_opt; enum cli_telnet_option_states *state; @@ -591,28 +590,28 @@ static pj_bool_t receive_disable_option(cli_telnet_sess *sess, state = is_local?(&sess_opt->local_state):(&sess_opt->peer_state); switch (*state) { - case OPT_ENABLE: - /* Disabling option always need to be accepted */ - *state = OPT_DISABLE; - send_telnet_cmd(sess, is_local?WONT:DONT, option); - break; - case OPT_DISABLE: - /* Ignore if already enabled */ - break; - case OPT_EXPECT_ENABLE: - case OPT_EXPECT_DISABLE: - *state = OPT_DISABLE; - break; - case OPT_EXPECT_ENABLE_REV: - *state = OPT_DISABLE; - send_telnet_cmd(sess, is_local?WONT:DONT, option); - break; - case OPT_EXPECT_DISABLE_REV: - *state = OPT_EXPECT_ENABLE; - send_telnet_cmd(sess, is_local?WILL:DO, option); - break; - default: - return PJ_FALSE; + case OPT_ENABLE: + /* Disabling option always need to be accepted */ + *state = OPT_DISABLE; + send_telnet_cmd(sess, is_local?WONT:DONT, option); + break; + case OPT_DISABLE: + /* Ignore if already enabled */ + break; + case OPT_EXPECT_ENABLE: + case OPT_EXPECT_DISABLE: + *state = OPT_DISABLE; + break; + case OPT_EXPECT_ENABLE_REV: + *state = OPT_DISABLE; + send_telnet_cmd(sess, is_local?WONT:DONT, option); + break; + case OPT_EXPECT_DISABLE_REV: + *state = OPT_EXPECT_ENABLE; + send_telnet_cmd(sess, is_local?WILL:DO, option); + break; + default: + return PJ_FALSE; } return PJ_TRUE; } @@ -638,21 +637,21 @@ static pj_bool_t receive_wont(cli_telnet_sess *sess, unsigned char option) } static void set_local_option(cli_telnet_sess *sess, - unsigned char option, - pj_bool_t enable) + unsigned char option, + pj_bool_t enable) { sess->telnet_option[option].local_is_enable = enable; } static void set_peer_option(cli_telnet_sess *sess, - unsigned char option, - pj_bool_t enable) + unsigned char option, + pj_bool_t enable) { sess->telnet_option[option].peer_is_enable = enable; } static pj_bool_t is_local_option_state_ena(cli_telnet_sess *sess, - unsigned char option) + unsigned char option) { return (sess->telnet_option[option].local_state == OPT_ENABLE); } @@ -686,10 +685,10 @@ static void send_prompt_str(cli_telnet_sess *sess) * the error position of the source command. */ static void send_err_arg(cli_telnet_sess *sess, - const pj_cli_exec_info *info, - const pj_str_t *msg, - pj_bool_t with_return, - pj_bool_t with_last_cmd) + const pj_cli_exec_info *info, + const pj_str_t *msg, + pj_bool_t with_return, + pj_bool_t with_last_cmd) { pj_str_t send_data; char data_str[256]; @@ -701,58 +700,58 @@ static void send_err_arg(cli_telnet_sess *sess, send_data.slen = 0; if (with_return) - pj_strcat2(&send_data, "\r\n"); + pj_strcat2(&send_data, "\r\n"); len = fe->cfg.prompt_str.slen + info->err_pos; /* Set the error pointer mark */ for (i=0;icfg.prompt_str); if (with_last_cmd) - pj_strcat2(&send_data, (char *)sess->rcmd->rbuf); + pj_strcat2(&send_data, (char *)sess->rcmd->rbuf); telnet_sess_send(sess, &send_data); } static void send_inv_arg(cli_telnet_sess *sess, - const pj_cli_exec_info *info, - pj_bool_t with_return, - pj_bool_t with_last_cmd) + const pj_cli_exec_info *info, + pj_bool_t with_return, + pj_bool_t with_last_cmd) { static const pj_str_t ERR_MSG = {"%Error : Invalid Arguments\r\n", 28}; send_err_arg(sess, info, &ERR_MSG, with_return, with_last_cmd); } static void send_too_many_arg(cli_telnet_sess *sess, - const pj_cli_exec_info *info, - pj_bool_t with_return, - pj_bool_t with_last_cmd) + const pj_cli_exec_info *info, + pj_bool_t with_return, + pj_bool_t with_last_cmd) { static const pj_str_t ERR_MSG = {"%Error : Too Many Arguments\r\n", 29}; send_err_arg(sess, info, &ERR_MSG, with_return, with_last_cmd); } static void send_hint_arg(cli_telnet_sess *sess, - pj_str_t *send_data, - const pj_str_t *desc, - pj_ssize_t cmd_len, - pj_ssize_t max_len) + pj_str_t *send_data, + const pj_str_t *desc, + pj_ssize_t cmd_len, + pj_ssize_t max_len) { if ((desc) && (desc->slen > 0)) { - int j; - - for (j=0;j<(max_len-cmd_len);++j) { - pj_strcat2(send_data, " "); - } - pj_strcat2(send_data, " "); - pj_strcat(send_data, desc); - telnet_sess_send(sess, send_data); - send_data->slen = 0; + int j; + + for (j=0;j<(max_len-cmd_len);++j) { + pj_strcat2(send_data, " "); + } + pj_strcat2(send_data, " "); + pj_strcat(send_data, desc); + telnet_sess_send(sess, send_data); + send_data->slen = 0; } } @@ -761,9 +760,9 @@ static void send_hint_arg(cli_telnet_sess *sess, * is ambiguous. It will show the matching command as the hint information. */ static void send_ambi_arg(cli_telnet_sess *sess, - const pj_cli_exec_info *info, - pj_bool_t with_return, - pj_bool_t with_last_cmd) + const pj_cli_exec_info *info, + pj_bool_t with_return, + pj_bool_t with_last_cmd) { unsigned i; pj_size_t len; @@ -780,103 +779,103 @@ static void send_ambi_arg(cli_telnet_sess *sess, send_data.slen = 0; if (with_return) - pj_strcat2(&send_data, "\r\n"); + pj_strcat2(&send_data, "\r\n"); len = fe->cfg.prompt_str.slen + info->err_pos; for (i=0;ihint_cnt;++i) { - if (hint[i].type.slen > 0) { - if (pj_stricmp(&hint[i].type, &sc_type) == 0) { - if ((i > 0) && (!pj_stricmp(&hint[i-1].desc, &hint[i].desc))) { - cmd_length += (hint[i].name.slen + 3); - } else { - cmd_length = hint[i].name.slen; - } - } else { - cmd_length = hint[i].name.slen; - } - } else { - cmd_length = hint[i].name.slen; - } - - if (cmd_length > max_length) { - max_length = cmd_length; - } + if (hint[i].type.slen > 0) { + if (pj_stricmp(&hint[i].type, &sc_type) == 0) { + if ((i > 0) && (!pj_stricmp(&hint[i-1].desc, &hint[i].desc))) { + cmd_length += (hint[i].name.slen + 3); + } else { + cmd_length = hint[i].name.slen; + } + } else { + cmd_length = hint[i].name.slen; + } + } else { + cmd_length = hint[i].name.slen; + } + + if (cmd_length > max_length) { + max_length = cmd_length; + } } cmd_length = 0; /* Build hint information */ for (i=0;ihint_cnt;++i) { - if (hint[i].type.slen > 0) { - if (pj_stricmp(&hint[i].type, &sc_type) == 0) { - parse_state = OP_SHORTCUT; - } else if (pj_stricmp(&hint[i].type, &choice_type) == 0) { - parse_state = OP_CHOICE; - } else { - parse_state = OP_TYPE; - } - } else { - parse_state = OP_NORMAL; - } - - if (parse_state != OP_SHORTCUT) { - pj_strcat2(&send_data, "\r\n "); - cmd_length = hint[i].name.slen; - } - - switch (parse_state) { - case OP_CHOICE: - /* Format : "[Choice Value] description" */ - pj_strcat2(&send_data, "["); - pj_strcat(&send_data, &hint[i].name); - pj_strcat2(&send_data, "]"); - break; - case OP_TYPE: - /* Format : " description" */ - pj_strcat2(&send_data, "<"); - pj_strcat(&send_data, &hint[i].name); - pj_strcat2(&send_data, ">"); - break; - case OP_SHORTCUT: - /* Format : "Command | sc | description" */ - { - cmd_length += hint[i].name.slen; - if ((i > 0) && (!pj_stricmp(&hint[i-1].desc, &hint[i].desc))) { - pj_strcat2(&send_data, " | "); - cmd_length += 3; - } else { - pj_strcat2(&send_data, "\r\n "); - } - pj_strcat(&send_data, &hint[i].name); - } - break; - default: - /* Command */ - pj_strcat(&send_data, &hint[i].name); - break; - } - - if ((parse_state == OP_TYPE) || (parse_state == OP_CHOICE) || - ((i+1) >= info->hint_cnt) || - (pj_strncmp(&hint[i].desc, &hint[i+1].desc, hint[i].desc.slen))) - { - /* Add description info */ - send_hint_arg(sess, &send_data, - &hint[i].desc, cmd_length, - max_length); - - cmd_length = 0; - } + if (hint[i].type.slen > 0) { + if (pj_stricmp(&hint[i].type, &sc_type) == 0) { + parse_state = OP_SHORTCUT; + } else if (pj_stricmp(&hint[i].type, &choice_type) == 0) { + parse_state = OP_CHOICE; + } else { + parse_state = OP_TYPE; + } + } else { + parse_state = OP_NORMAL; + } + + if (parse_state != OP_SHORTCUT) { + pj_strcat2(&send_data, "\r\n "); + cmd_length = hint[i].name.slen; + } + + switch (parse_state) { + case OP_CHOICE: + /* Format : "[Choice Value] description" */ + pj_strcat2(&send_data, "["); + pj_strcat(&send_data, &hint[i].name); + pj_strcat2(&send_data, "]"); + break; + case OP_TYPE: + /* Format : " description" */ + pj_strcat2(&send_data, "<"); + pj_strcat(&send_data, &hint[i].name); + pj_strcat2(&send_data, ">"); + break; + case OP_SHORTCUT: + /* Format : "Command | sc | description" */ + { + cmd_length += hint[i].name.slen; + if ((i > 0) && (!pj_stricmp(&hint[i-1].desc, &hint[i].desc))) { + pj_strcat2(&send_data, " | "); + cmd_length += 3; + } else { + pj_strcat2(&send_data, "\r\n "); + } + pj_strcat(&send_data, &hint[i].name); + } + break; + default: + /* Command */ + pj_strcat(&send_data, &hint[i].name); + break; + } + + if ((parse_state == OP_TYPE) || (parse_state == OP_CHOICE) || + ((i+1) >= info->hint_cnt) || + (pj_strncmp(&hint[i].desc, &hint[i+1].desc, hint[i].desc.slen))) + { + /* Add description info */ + send_hint_arg(sess, &send_data, + &hint[i].desc, cmd_length, + max_length); + + cmd_length = 0; + } } pj_strcat2(&send_data, "\r\n"); pj_strcat(&send_data, &fe->cfg.prompt_str); if (with_last_cmd) - pj_strcat2(&send_data, (char *)sess->rcmd->rbuf); + pj_strcat2(&send_data, (char *)sess->rcmd->rbuf); telnet_sess_send(sess, &send_data); } @@ -885,7 +884,7 @@ static void send_ambi_arg(cli_telnet_sess *sess, * This method is to send command completion of the entered command. */ static void send_comp_arg(cli_telnet_sess *sess, - pj_cli_exec_info *info) + pj_cli_exec_info *info) { pj_str_t send_data; char data[128]; @@ -906,16 +905,16 @@ static void send_comp_arg(cli_telnet_sess *sess, static pj_bool_t handle_alfa_num(cli_telnet_sess *sess, unsigned char *data) { if (is_local_option_state_ena(sess, TERM_ECHO)) { - if (recv_buf_right_len(sess->rcmd) > 0) { - /* Cursor is not at EOL, insert character */ - unsigned char echo[5] = {0x1b, 0x5b, 0x31, 0x40, 0x00}; - echo[4] = *data; - telnet_sess_send2(sess, echo, 5); - } else { - /* Append character */ - telnet_sess_send2(sess, data, 1); - } - return PJ_TRUE; + if (recv_buf_right_len(sess->rcmd) > 0) { + /* Cursor is not at EOL, insert character */ + unsigned char echo[5] = {0x1b, 0x5b, 0x31, 0x40, 0x00}; + echo[4] = *data; + telnet_sess_send2(sess, echo, 5); + } else { + /* Append character */ + telnet_sess_send2(sess, data, 1); + } + return PJ_TRUE; } return PJ_FALSE; } @@ -927,19 +926,19 @@ static pj_bool_t handle_backspace(cli_telnet_sess *sess, unsigned char *data) { unsigned rlen = recv_buf_right_len(sess->rcmd); if (recv_buf_backspace(sess->rcmd)) { - if (rlen) { - /* - * Cursor is not at the end of line, move the characters - * after the cursor to left - */ - unsigned char echo[5] = {0x00, 0x1b, 0x5b, 0x31, 0x50}; - echo[0] = *data; - telnet_sess_send2(sess, echo, 5); - } else { - const static unsigned char echo[3] = {0x08, 0x20, 0x08}; - telnet_sess_send2(sess, echo, 3); - } - return PJ_TRUE; + if (rlen) { + /* + * Cursor is not at the end of line, move the characters + * after the cursor to left + */ + unsigned char echo[5] = {0x00, 0x1b, 0x5b, 0x31, 0x50}; + echo[0] = *data; + telnet_sess_send2(sess, echo, 5); + } else { + const static unsigned char echo[3] = {0x08, 0x20, 0x08}; + telnet_sess_send2(sess, echo, 3); + } + return PJ_TRUE; } return PJ_FALSE; } @@ -961,15 +960,15 @@ static pj_status_t get_last_token(pj_str_t *cmd, pj_str_t *str) pj_scanner scanner; PJ_USE_EXCEPTION; pj_scan_init(&scanner, cmd->ptr, cmd->slen, PJ_SCAN_AUTOSKIP_WS, - &on_syntax_error); + &on_syntax_error); PJ_TRY { - while (!pj_scan_is_eof(&scanner)) { - pj_scan_get_until_chr(&scanner, " \t\r\n", str); - } + while (!pj_scan_is_eof(&scanner)) { + pj_scan_get_until_chr(&scanner, " \t\r\n", str); + } } PJ_CATCH_ANY { - pj_scan_fini(&scanner); - return PJ_GET_EXCEPTION(); + pj_scan_fini(&scanner); + return PJ_GET_EXCEPTION(); } PJ_END; @@ -990,62 +989,62 @@ static pj_bool_t handle_tab(cli_telnet_sess *sess) pj_cli_cmd_val *cmd_val; pj_cli_exec_info info; pool = pj_pool_create(sess->pool->factory, "handle_tab", - PJ_CLI_TELNET_POOL_SIZE, PJ_CLI_TELNET_POOL_INC, - NULL); + PJ_CLI_TELNET_POOL_SIZE, PJ_CLI_TELNET_POOL_INC, + NULL); cmd_val = PJ_POOL_ZALLOC_T(pool, pj_cli_cmd_val); status = pj_cli_sess_parse(&sess->base, (char *)&sess->rcmd->rbuf, cmd_val, - pool, &info); + pool, &info); len = (unsigned)pj_ansi_strlen((char *)sess->rcmd->rbuf); switch (status) { case PJ_CLI_EINVARG: - send_inv_arg(sess, &info, PJ_TRUE, PJ_TRUE); - break; + send_inv_arg(sess, &info, PJ_TRUE, PJ_TRUE); + break; case PJ_CLI_ETOOMANYARGS: - send_too_many_arg(sess, &info, PJ_TRUE, PJ_TRUE); - break; + send_too_many_arg(sess, &info, PJ_TRUE, PJ_TRUE); + break; case PJ_CLI_EMISSINGARG: case PJ_CLI_EAMBIGUOUS: - send_ambi_arg(sess, &info, PJ_TRUE, PJ_TRUE); - break; + send_ambi_arg(sess, &info, PJ_TRUE, PJ_TRUE); + break; case PJ_SUCCESS: - if (len > sess->rcmd->cur_pos) - { - /* Send the cursor to EOL */ - unsigned rlen = len - sess->rcmd->cur_pos+1; - unsigned char *data_sent = &sess->rcmd->rbuf[sess->rcmd->cur_pos-1]; - telnet_sess_send2(sess, data_sent, rlen); - } - if (info.hint_cnt > 0) { - /* Complete command */ - pj_str_t cmd = pj_str((char *)sess->rcmd->rbuf); - pj_str_t last_token; - - if (get_last_token(&cmd, &last_token) == PJ_SUCCESS) { - /* Hint contains the match to the last command entered */ - pj_str_t *hint_info = &info.hint[0].name; - pj_strtrim(&last_token); - if (hint_info->slen >= last_token.slen) { - hint_info->slen -= last_token.slen; - pj_memmove(hint_info->ptr, - &hint_info->ptr[last_token.slen], - hint_info->slen); - } - send_comp_arg(sess, &info); - - pj_memcpy(&sess->rcmd->rbuf[len], info.hint[0].name.ptr, - info.hint[0].name.slen); - - len += (unsigned)info.hint[0].name.slen; - sess->rcmd->rbuf[len] = 0; - } - } else { - retval = PJ_FALSE; - } - break; + if (len > sess->rcmd->cur_pos) + { + /* Send the cursor to EOL */ + unsigned rlen = len - sess->rcmd->cur_pos+1; + unsigned char *data_sent = &sess->rcmd->rbuf[sess->rcmd->cur_pos-1]; + telnet_sess_send2(sess, data_sent, rlen); + } + if (info.hint_cnt > 0) { + /* Complete command */ + pj_str_t cmd = pj_str((char *)sess->rcmd->rbuf); + pj_str_t last_token; + + if (get_last_token(&cmd, &last_token) == PJ_SUCCESS) { + /* Hint contains the match to the last command entered */ + pj_str_t *hint_info = &info.hint[0].name; + pj_strtrim(&last_token); + if (hint_info->slen >= last_token.slen) { + hint_info->slen -= last_token.slen; + pj_memmove(hint_info->ptr, + &hint_info->ptr[last_token.slen], + hint_info->slen); + } + send_comp_arg(sess, &info); + + pj_memcpy(&sess->rcmd->rbuf[len], info.hint[0].name.ptr, + info.hint[0].name.slen); + + len += (unsigned)info.hint[0].name.slen; + sess->rcmd->rbuf[len] = 0; + } + } else { + retval = PJ_FALSE; + } + break; } sess->rcmd->len = len; sess->rcmd->cur_pos = sess->rcmd->len; @@ -1069,34 +1068,34 @@ static pj_bool_t handle_return(cli_telnet_sess *sess) insert_history(sess, (char *)&sess->rcmd->rbuf); pool = pj_pool_create(sess->pool->factory, "handle_return", - PJ_CLI_TELNET_POOL_SIZE, PJ_CLI_TELNET_POOL_INC, - NULL); + PJ_CLI_TELNET_POOL_SIZE, PJ_CLI_TELNET_POOL_INC, + NULL); status = pj_cli_sess_exec(&sess->base, (char *)&sess->rcmd->rbuf, - pool, &info); + pool, &info); switch (status) { case PJ_CLI_EINVARG: - send_inv_arg(sess, &info, PJ_FALSE, PJ_FALSE); - break; + send_inv_arg(sess, &info, PJ_FALSE, PJ_FALSE); + break; case PJ_CLI_ETOOMANYARGS: - send_too_many_arg(sess, &info, PJ_FALSE, PJ_FALSE); - break; + send_too_many_arg(sess, &info, PJ_FALSE, PJ_FALSE); + break; case PJ_CLI_EAMBIGUOUS: case PJ_CLI_EMISSINGARG: - send_ambi_arg(sess, &info, PJ_FALSE, PJ_FALSE); - break; + send_ambi_arg(sess, &info, PJ_FALSE, PJ_FALSE); + break; case PJ_CLI_EEXIT: - retval = PJ_FALSE; - break; + retval = PJ_FALSE; + break; case PJ_SUCCESS: - send_prompt_str(sess); - break; + send_prompt_str(sess); + break; } if (retval) { - sess->rcmd->rbuf[0] = 0; - sess->rcmd->len = 0; - sess->rcmd->cur_pos = sess->rcmd->len; + sess->rcmd->rbuf[0] = 0; + sess->rcmd->len = 0; + sess->rcmd->cur_pos = sess->rcmd->len; } pj_pool_release(pool); @@ -1109,9 +1108,9 @@ static pj_bool_t handle_return(cli_telnet_sess *sess) static pj_bool_t handle_right_key(cli_telnet_sess *sess) { if (recv_buf_right_len(sess->rcmd)) { - unsigned char *data = &sess->rcmd->rbuf[sess->rcmd->cur_pos++]; - telnet_sess_send2(sess, data, 1); - return PJ_TRUE; + unsigned char *data = &sess->rcmd->rbuf[sess->rcmd->cur_pos++]; + telnet_sess_send2(sess, data, 1); + return PJ_TRUE; } return PJ_FALSE; } @@ -1123,9 +1122,9 @@ static pj_bool_t handle_left_key(cli_telnet_sess *sess) { static const unsigned char move_cursor_left = 0x08; if (sess->rcmd->cur_pos) { - telnet_sess_send2(sess, &move_cursor_left, 1); - --sess->rcmd->cur_pos; - return PJ_TRUE; + telnet_sess_send2(sess, &move_cursor_left, 1); + --sess->rcmd->cur_pos; + return PJ_TRUE; } return PJ_FALSE; } @@ -1141,81 +1140,81 @@ static pj_bool_t handle_up_down(cli_telnet_sess *sess, pj_bool_t is_up) history = get_prev_history(sess, is_up); if (history) { - pj_str_t send_data; - char str[PJ_CLI_MAX_CMDBUF]; - enum { - MOVE_CURSOR_LEFT = 0x08, - CLEAR_CHAR = 0x20 - }; - send_data.ptr = str; - send_data.slen = 0; - - /* Move cursor position to the beginning of line */ - if (sess->rcmd->cur_pos > 0) { - pj_memset(send_data.ptr, MOVE_CURSOR_LEFT, sess->rcmd->cur_pos); - send_data.slen = sess->rcmd->cur_pos; - } - - if (sess->rcmd->len > (unsigned)history->slen) { - /* Clear the command currently shown*/ - unsigned buf_len = sess->rcmd->len; - pj_memset(&send_data.ptr[send_data.slen], CLEAR_CHAR, buf_len); - send_data.slen += buf_len; - - /* Move cursor position to the beginning of line */ - pj_memset(&send_data.ptr[send_data.slen], MOVE_CURSOR_LEFT, - buf_len); - send_data.slen += buf_len; - } - /* Send data */ - pj_strcat(&send_data, history); - telnet_sess_send(sess, &send_data); - pj_ansi_strncpy((char*)&sess->rcmd->rbuf, history->ptr, history->slen); - sess->rcmd->rbuf[history->slen] = 0; - sess->rcmd->len = (unsigned)history->slen; - sess->rcmd->cur_pos = sess->rcmd->len; - return PJ_TRUE; + pj_str_t send_data; + char str[PJ_CLI_MAX_CMDBUF]; + enum { + MOVE_CURSOR_LEFT = 0x08, + CLEAR_CHAR = 0x20 + }; + send_data.ptr = str; + send_data.slen = 0; + + /* Move cursor position to the beginning of line */ + if (sess->rcmd->cur_pos > 0) { + pj_memset(send_data.ptr, MOVE_CURSOR_LEFT, sess->rcmd->cur_pos); + send_data.slen = sess->rcmd->cur_pos; + } + + if (sess->rcmd->len > (unsigned)history->slen) { + /* Clear the command currently shown*/ + unsigned buf_len = sess->rcmd->len; + pj_memset(&send_data.ptr[send_data.slen], CLEAR_CHAR, buf_len); + send_data.slen += buf_len; + + /* Move cursor position to the beginning of line */ + pj_memset(&send_data.ptr[send_data.slen], MOVE_CURSOR_LEFT, + buf_len); + send_data.slen += buf_len; + } + /* Send data */ + pj_strcat(&send_data, history); + telnet_sess_send(sess, &send_data); + pj_ansi_strncpy((char*)&sess->rcmd->rbuf, history->ptr, history->slen); + sess->rcmd->rbuf[history->slen] = 0; + sess->rcmd->len = (unsigned)history->slen; + sess->rcmd->cur_pos = sess->rcmd->len; + return PJ_TRUE; } return PJ_FALSE; } static pj_status_t process_vt100_cmd(cli_telnet_sess *sess, - unsigned char *cmd) + unsigned char *cmd) { pj_status_t status = PJ_TRUE; switch (*cmd) { - case TC_ESC: - break; - case TC_UP: - status = handle_up_down(sess, PJ_TRUE); - break; - case TC_DOWN: - status = handle_up_down(sess, PJ_FALSE); - break; - case TC_RIGHT: - status = handle_right_key(sess); - break; - case TC_LEFT: - status = handle_left_key(sess); - break; - case TC_END: - break; - case TC_HOME: - break; - case TC_CTRL_C: - break; - case TC_CR: - break; - case TC_BS: - break; - case TC_TAB: - break; - case TC_QM: - break; - case TC_BELL: - break; - case TC_DEL: - break; + case TC_ESC: + break; + case TC_UP: + status = handle_up_down(sess, PJ_TRUE); + break; + case TC_DOWN: + status = handle_up_down(sess, PJ_FALSE); + break; + case TC_RIGHT: + status = handle_right_key(sess); + break; + case TC_LEFT: + status = handle_left_key(sess); + break; + case TC_END: + break; + case TC_HOME: + break; + case TC_CTRL_C: + break; + case TC_CR: + break; + case TC_BS: + break; + case TC_TAB: + break; + case TC_QM: + break; + case TC_BELL: + break; + case TC_DEL: + break; }; return status; } @@ -1233,7 +1232,7 @@ PJ_DEF(void) pj_cli_telnet_cfg_default(pj_cli_telnet_cfg *param) * Send a message to a telnet session */ static pj_status_t telnet_sess_send(cli_telnet_sess *sess, - const pj_str_t *str) + const pj_str_t *str) { pj_ssize_t sz; pj_status_t status = PJ_SUCCESS; @@ -1264,7 +1263,7 @@ static pj_status_t telnet_sess_send(cli_telnet_sess *sess, MAX_CUT_MSG_LEN, CUT_MSG); sess->buf_len = (unsigned)(CLI_TELNET_BUF_SIZE + pj_ansi_strlen((char *)sess->buf+ - CLI_TELNET_BUF_SIZE)); + CLI_TELNET_BUF_SIZE)); } else sess->buf_len += clen; } else if (status == PJ_SUCCESS && sz < str->slen) { @@ -1282,7 +1281,7 @@ static pj_status_t telnet_sess_send(cli_telnet_sess *sess, * (add single linefeed character with carriage return) */ static pj_status_t telnet_sess_send_with_format(cli_telnet_sess *sess, - const pj_str_t *str) + const pj_str_t *str) { pj_scanner scanner; pj_str_t out_str; @@ -1293,45 +1292,45 @@ static pj_status_t telnet_sess_send_with_format(cli_telnet_sess *sess, PJ_USE_EXCEPTION; pj_scan_init(&scanner, str->ptr, str->slen, - PJ_SCAN_AUTOSKIP_WS, &on_syntax_error); + PJ_SCAN_AUTOSKIP_WS, &on_syntax_error); str_begin = scanner.begin; PJ_TRY { - while (!pj_scan_is_eof(&scanner)) { - pj_scan_get_until_ch(&scanner, '\n', &out_str); - str_len = (int)(scanner.curptr - str_begin); - if (*scanner.curptr == '\n') { - if ((str_len > 1) && (out_str.ptr[str_len-2] == '\r')) - { - continue; - } else { - int str_pos = (int)(str_begin - scanner.begin); - - if (str_len > 0) { - pj_str_t s; - pj_strset(&s, &str->ptr[str_pos], str_len); - telnet_sess_send(sess, &s); - } - telnet_sess_send(sess, &CR_LF); - - if (!pj_scan_is_eof(&scanner)) { - pj_scan_advance_n(&scanner, 1, PJ_TRUE); - str_begin = scanner.curptr; - } - } - } else { - pj_str_t s; - int str_pos = (int)(str_begin - scanner.begin); - - pj_strset(&s, &str->ptr[str_pos], str_len); - telnet_sess_send(sess, &s); - } - } + while (!pj_scan_is_eof(&scanner)) { + pj_scan_get_until_ch(&scanner, '\n', &out_str); + str_len = (int)(scanner.curptr - str_begin); + if (*scanner.curptr == '\n') { + if ((str_len > 1) && (out_str.ptr[str_len-2] == '\r')) + { + continue; + } else { + int str_pos = (int)(str_begin - scanner.begin); + + if (str_len > 0) { + pj_str_t s; + pj_strset(&s, &str->ptr[str_pos], str_len); + telnet_sess_send(sess, &s); + } + telnet_sess_send(sess, &CR_LF); + + if (!pj_scan_is_eof(&scanner)) { + pj_scan_advance_n(&scanner, 1, PJ_TRUE); + str_begin = scanner.curptr; + } + } + } else { + pj_str_t s; + int str_pos = (int)(str_begin - scanner.begin); + + pj_strset(&s, &str->ptr[str_pos], str_len); + telnet_sess_send(sess, &s); + } + } } PJ_CATCH_ANY { - pj_scan_fini(&scanner); - return (PJ_GET_EXCEPTION()); + pj_scan_fini(&scanner); + return (PJ_GET_EXCEPTION()); } PJ_END; @@ -1365,7 +1364,7 @@ static void telnet_sess_destroy(pj_cli_sess *sess) } static void telnet_fe_write_log(pj_cli_front_end *fe, int level, - const char *data, pj_size_t len) + const char *data, pj_size_t len) { cli_telnet_fe *tfe = (cli_telnet_fe *)fe; pj_cli_sess *sess; @@ -1377,12 +1376,12 @@ static void telnet_fe_write_log(pj_cli_front_end *fe, int level, cli_telnet_sess *tsess = (cli_telnet_sess *)sess; sess = sess->next; - if (tsess->base.log_level >= level) { - pj_str_t s; + if (tsess->base.log_level >= level) { + pj_str_t s; - pj_strset(&s, (char *)data, len); - telnet_sess_send_with_format(tsess, &s); - } + pj_strset(&s, (char *)data, len); + telnet_sess_send_with_format(tsess, &s); + } } pj_mutex_unlock(tfe->mutex); @@ -1410,18 +1409,18 @@ static void telnet_fe_destroy(pj_cli_front_end *fe) pj_mutex_unlock(tfe->mutex); if (tfe->asock) { - pj_activesock_close(tfe->asock); - tfe->asock = NULL; + pj_activesock_close(tfe->asock); + tfe->asock = NULL; } if (tfe->own_ioqueue && tfe->cfg.ioqueue) { pj_ioqueue_destroy(tfe->cfg.ioqueue); - tfe->cfg.ioqueue = NULL; + tfe->cfg.ioqueue = NULL; } if (tfe->worker_thread) { - pj_thread_destroy(tfe->worker_thread); - tfe->worker_thread = NULL; + pj_thread_destroy(tfe->worker_thread); + tfe->worker_thread = NULL; } pj_mutex_destroy(tfe->mutex); @@ -1434,7 +1433,7 @@ static int poll_worker_thread(void *p) cli_telnet_fe *fe = (cli_telnet_fe *)p; while (!fe->is_quitting) { - pj_time_val delay = {0, 50}; + pj_time_val delay = {0, 50}; pj_ioqueue_poll(fe->cfg.ioqueue, &delay); } @@ -1442,16 +1441,16 @@ static int poll_worker_thread(void *p) } static pj_bool_t telnet_sess_on_data_sent(pj_activesock_t *asock, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t sent) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t sent) { cli_telnet_sess *sess = (cli_telnet_sess *) - pj_activesock_get_user_data(asock); + pj_activesock_get_user_data(asock); PJ_UNUSED_ARG(op_key); if (sent <= 0) { - TRACE_((THIS_FILE, "Error On data send")); + TRACE_((THIS_FILE, "Error On data send")); pj_cli_sess_end_session(&sess->base); return PJ_FALSE; } @@ -1475,10 +1474,10 @@ static pj_bool_t telnet_sess_on_data_sent(pj_activesock_t *asock, } static pj_bool_t telnet_sess_on_data_read(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { cli_telnet_sess *sess = (cli_telnet_sess *) pj_activesock_get_user_data(asock); @@ -1493,104 +1492,104 @@ static pj_bool_t telnet_sess_on_data_read(pj_activesock_t *asock, return PJ_FALSE; if (status != PJ_SUCCESS && status != PJ_EPENDING) { - TRACE_((THIS_FILE, "Error on data read %d", status)); - pj_cli_sess_end_session(&sess->base); + TRACE_((THIS_FILE, "Error on data read %d", status)); + pj_cli_sess_end_session(&sess->base); return PJ_FALSE; } pj_mutex_lock(sess->smutex); switch (sess->parse_state) { - case ST_CR: - sess->parse_state = ST_NORMAL; - if (*cdata == 0 || *cdata == '\n') { - pj_mutex_unlock(sess->smutex); - is_valid = handle_return(sess); - if (!is_valid) { - // handle_return() can only return PJ_FALSE if - // pj_cli_sess_exec() returns PJ_CLI_EEXIT, - // in which case CLI session has been ended by - // cmd_handler() of CLI_CMD_EXIT. - // - // pj_cli_sess_end_session(&sess->base); - return PJ_FALSE; - } - pj_mutex_lock(sess->smutex); - } - break; - case ST_NORMAL: - if (*cdata == IAC) { - sess->parse_state = ST_IAC; - } else if (*cdata == 127) { - is_valid = handle_backspace(sess, cdata); - } else if (*cdata == 27) { - sess->parse_state = ST_ESC; - } else { - if (recv_buf_insert(sess->rcmd, cdata)) { - if (*cdata == '\r') { - sess->parse_state = ST_CR; - } else if ((*cdata == '\t') || (*cdata == '?')) { - is_valid = handle_tab(sess); - } else if (*cdata > 31 && *cdata < 127) { - is_valid = handle_alfa_num(sess, cdata); - } - } else { - is_valid = PJ_FALSE; - } - } - break; - case ST_ESC: - if (*cdata == 91) { - sess->parse_state = ST_VT100; - } else { - sess->parse_state = ST_NORMAL; - } - break; - case ST_VT100: - sess->parse_state = ST_NORMAL; - is_valid = process_vt100_cmd(sess, cdata); - break; - case ST_IAC: - switch ((unsigned) *cdata) { - case DO: - sess->parse_state = ST_DO; - break; - case DONT: - sess->parse_state = ST_DONT; - break; - case WILL: - sess->parse_state = ST_WILL; - break; - case WONT: - sess->parse_state = ST_WONT; - break; - default: - sess->parse_state = ST_NORMAL; - break; - } - break; - case ST_DO: - receive_do(sess, *cdata); - sess->parse_state = ST_NORMAL; - break; - case ST_DONT: - receive_dont(sess, *cdata); - sess->parse_state = ST_NORMAL; - break; - case ST_WILL: - receive_will(sess, *cdata); - sess->parse_state = ST_NORMAL; - break; - case ST_WONT: - receive_wont(sess, *cdata); - sess->parse_state = ST_NORMAL; - break; - default: - sess->parse_state = ST_NORMAL; - break; + case ST_CR: + sess->parse_state = ST_NORMAL; + if (*cdata == 0 || *cdata == '\n') { + pj_mutex_unlock(sess->smutex); + is_valid = handle_return(sess); + if (!is_valid) { + // handle_return() can only return PJ_FALSE if + // pj_cli_sess_exec() returns PJ_CLI_EEXIT, + // in which case CLI session has been ended by + // cmd_handler() of CLI_CMD_EXIT. + // + // pj_cli_sess_end_session(&sess->base); + return PJ_FALSE; + } + pj_mutex_lock(sess->smutex); + } + break; + case ST_NORMAL: + if (*cdata == IAC) { + sess->parse_state = ST_IAC; + } else if (*cdata == 127) { + is_valid = handle_backspace(sess, cdata); + } else if (*cdata == 27) { + sess->parse_state = ST_ESC; + } else { + if (recv_buf_insert(sess->rcmd, cdata)) { + if (*cdata == '\r') { + sess->parse_state = ST_CR; + } else if ((*cdata == '\t') || (*cdata == '?')) { + is_valid = handle_tab(sess); + } else if (*cdata > 31 && *cdata < 127) { + is_valid = handle_alfa_num(sess, cdata); + } + } else { + is_valid = PJ_FALSE; + } + } + break; + case ST_ESC: + if (*cdata == 91) { + sess->parse_state = ST_VT100; + } else { + sess->parse_state = ST_NORMAL; + } + break; + case ST_VT100: + sess->parse_state = ST_NORMAL; + is_valid = process_vt100_cmd(sess, cdata); + break; + case ST_IAC: + switch ((unsigned) *cdata) { + case DO: + sess->parse_state = ST_DO; + break; + case DONT: + sess->parse_state = ST_DONT; + break; + case WILL: + sess->parse_state = ST_WILL; + break; + case WONT: + sess->parse_state = ST_WONT; + break; + default: + sess->parse_state = ST_NORMAL; + break; + } + break; + case ST_DO: + receive_do(sess, *cdata); + sess->parse_state = ST_NORMAL; + break; + case ST_DONT: + receive_dont(sess, *cdata); + sess->parse_state = ST_NORMAL; + break; + case ST_WILL: + receive_will(sess, *cdata); + sess->parse_state = ST_NORMAL; + break; + case ST_WONT: + receive_wont(sess, *cdata); + sess->parse_state = ST_NORMAL; + break; + default: + sess->parse_state = ST_NORMAL; + break; } if (!is_valid) { - send_bell(sess); + send_bell(sess); } pj_mutex_unlock(sess->smutex); @@ -1599,10 +1598,10 @@ static pj_bool_t telnet_sess_on_data_read(pj_activesock_t *asock, } static pj_bool_t telnet_fe_on_accept(pj_activesock_t *asock, - pj_sock_t newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len, - pj_status_t status) + pj_sock_t newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len, + pj_status_t status) { cli_telnet_fe *fe = (cli_telnet_fe *) pj_activesock_get_user_data(asock); @@ -1618,18 +1617,18 @@ static pj_bool_t telnet_fe_on_accept(pj_activesock_t *asock, return PJ_FALSE; if (status != PJ_SUCCESS && status != PJ_EPENDING) { - TRACE_((THIS_FILE, "Error on data accept (status=%d)", status)); - if (status == PJ_ESOCKETSTOP) { - sstatus = telnet_restart(fe); - if (sstatus != PJ_SUCCESS) { - if (fe->own_ioqueue && fe->cfg.ioqueue) { - pj_ioqueue_destroy(fe->cfg.ioqueue); - fe->cfg.ioqueue = NULL; - } - TRACE_((THIS_FILE, "Error restarting telnet (status=%d)", - status)); - } - } + TRACE_((THIS_FILE, "Error on data accept (status=%d)", status)); + if (status == PJ_ESOCKETSTOP) { + sstatus = telnet_restart(fe); + if (sstatus != PJ_SUCCESS) { + if (fe->own_ioqueue && fe->cfg.ioqueue) { + pj_ioqueue_destroy(fe->cfg.ioqueue); + fe->cfg.ioqueue = NULL; + } + TRACE_((THIS_FILE, "Error restarting telnet (status=%d)", + status)); + } + } return PJ_FALSE; } @@ -1665,7 +1664,7 @@ static pj_bool_t telnet_fe_on_accept(pj_activesock_t *asock, sstatus = pj_activesock_create(pool, newsock, pj_SOCK_STREAM(), NULL, fe->cfg.ioqueue, - &asock_cb, sess, &sess->asock); + &asock_cb, sess, &sess->asock); if (sstatus != PJ_SUCCESS) { TRACE_((THIS_FILE, "Failure creating active socket")); goto on_exit; @@ -1722,8 +1721,8 @@ static pj_bool_t telnet_fe_on_accept(pj_activesock_t *asock, } PJ_DEF(pj_status_t) pj_cli_telnet_create(pj_cli_t *cli, - pj_cli_telnet_cfg *param, - pj_cli_front_end **p_fe) + pj_cli_telnet_cfg *param, + pj_cli_front_end **p_fe) { cli_telnet_fe *fe; pj_pool_t *pool; @@ -1767,7 +1766,7 @@ PJ_DEF(pj_status_t) pj_cli_telnet_create(pj_cli_t *cli, /* Start telnet daemon */ status = telnet_start(fe); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; pj_cli_register_front_end(cli, &fe->base); @@ -1781,12 +1780,12 @@ PJ_DEF(pj_status_t) pj_cli_telnet_create(pj_cli_t *cli, on_exit: if (fe->own_ioqueue && fe->cfg.ioqueue) { pj_ioqueue_destroy(fe->cfg.ioqueue); - fe->cfg.ioqueue = NULL; + fe->cfg.ioqueue = NULL; } if (fe->mutex) { pj_mutex_destroy(fe->mutex); - fe->mutex = NULL; + fe->mutex = NULL; } pj_pool_release(pool); @@ -1813,43 +1812,43 @@ static pj_status_t telnet_start(cli_telnet_fe *fe) val = 1; status = pj_sock_setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, - &val, sizeof(val)); + &val, sizeof(val)); if (status != PJ_SUCCESS) { - PJ_PERROR(3, (THIS_FILE, status, "Failed setting socket options")); + PJ_PERROR(3, (THIS_FILE, status, "Failed setting socket options")); } /* The loop is silly, but what else can we do? */ for (msec=MIN_WAIT_ON_TELNET_RESTART, restart_retry=0; - restart_retry < MAX_RETRY_ON_TELNET_RESTART; - ++restart_retry, msec=(mseccfg.port = pj_sockaddr_in_get_port(&addr); - if (fe->cfg.prompt_str.slen == 0) { - pj_str_t prompt_sign = {"> ", 2}; - char *prompt_data = pj_pool_alloc(fe->pool, - pj_gethostname()->slen+2); - fe->cfg.prompt_str.ptr = prompt_data; + if (fe->cfg.prompt_str.slen == 0) { + pj_str_t prompt_sign = {"> ", 2}; + char *prompt_data = pj_pool_alloc(fe->pool, + pj_gethostname()->slen+2); + fe->cfg.prompt_str.ptr = prompt_data; - pj_strcpy(&fe->cfg.prompt_str, pj_gethostname()); - pj_strcat(&fe->cfg.prompt_str, &prompt_sign); - } + pj_strcpy(&fe->cfg.prompt_str, pj_gethostname()); + pj_strcat(&fe->cfg.prompt_str, &prompt_sign); + } } else { PJ_PERROR(3, (THIS_FILE, status, "Failed binding the socket")); goto on_exit; @@ -1863,7 +1862,7 @@ static pj_status_t telnet_start(cli_telnet_fe *fe) asock_cb.on_accept_complete2 = &telnet_fe_on_accept; status = pj_activesock_create(fe->pool, sock, pj_SOCK_STREAM(), NULL, fe->cfg.ioqueue, - &asock_cb, fe, &fe->asock); + &asock_cb, fe, &fe->asock); if (status != PJ_SUCCESS) goto on_exit; @@ -1884,15 +1883,15 @@ static pj_status_t telnet_start(cli_telnet_fe *fe) on_exit: if (fe->cfg.on_started) { - (*fe->cfg.on_started)(status); + (*fe->cfg.on_started)(status); } if (fe->asock) { pj_activesock_close(fe->asock); - fe->asock = NULL; + fe->asock = NULL; } else if (sock != PJ_INVALID_SOCKET) { pj_sock_close(sock); - sock = PJ_INVALID_SOCKET; + sock = PJ_INVALID_SOCKET; } return status; @@ -1905,9 +1904,9 @@ static pj_status_t telnet_restart(cli_telnet_fe *fe) fe->is_quitting = PJ_TRUE; if (fe->worker_thread) { - pj_thread_join(fe->worker_thread); - pj_thread_destroy(fe->worker_thread); - fe->worker_thread = NULL; + pj_thread_join(fe->worker_thread); + pj_thread_destroy(fe->worker_thread); + fe->worker_thread = NULL; } pj_mutex_lock(fe->mutex); @@ -1915,8 +1914,8 @@ static pj_status_t telnet_restart(cli_telnet_fe *fe) /* Destroy all the sessions */ sess = fe->sess_head.next; while (sess != &fe->sess_head) { - (*sess->op->destroy)(sess); - sess = fe->sess_head.next; + (*sess->op->destroy)(sess); + sess = fe->sess_head.next; } pj_mutex_unlock(fe->mutex); @@ -1924,7 +1923,7 @@ static pj_status_t telnet_restart(cli_telnet_fe *fe) /** Close existing activesock **/ status = pj_activesock_close(fe->asock); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; fe->asock = NULL; fe->is_quitting = PJ_FALSE; @@ -1932,10 +1931,10 @@ static pj_status_t telnet_restart(cli_telnet_fe *fe) /** Start Telnet **/ status = telnet_start(fe); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; if (fe->cfg.on_started) { - (*fe->cfg.on_started)(PJ_SUCCESS); + (*fe->cfg.on_started)(PJ_SUCCESS); } TRACE_((THIS_FILE, "Telnet restarted")); @@ -1945,20 +1944,20 @@ static pj_status_t telnet_restart(cli_telnet_fe *fe) } PJ_DEF(pj_status_t) pj_cli_telnet_get_info(pj_cli_front_end *fe, - pj_cli_telnet_info *info) + pj_cli_telnet_info *info) { pj_sockaddr hostip; pj_status_t status; cli_telnet_fe *tfe = (cli_telnet_fe*) fe; PJ_ASSERT_RETURN(fe && (fe->type == PJ_CLI_TELNET_FRONT_END) && info, - PJ_EINVAL); + PJ_EINVAL); pj_strset(&info->ip_address, info->buf_, 0); status = pj_gethostip(pj_AF_INET(), &hostip); if (status != PJ_SUCCESS) - return status; + return status; pj_sockaddr_print(&hostip, info->buf_, sizeof(info->buf_), 0); pj_strset2(&info->ip_address, info->buf_); diff --git a/pjlib-util/src/pjlib-util/crc32.c b/pjlib-util/src/pjlib-util/crc32.c index 947eec1994..a73f836d9b 100644 --- a/pjlib-util/src/pjlib-util/crc32.c +++ b/pjlib-util/src/pjlib-util/crc32.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * This is an implementation of CRC32. See ISO 3309 and ITU-T V.42 * for a formal specification @@ -20,7 +19,7 @@ /* Table of CRC-32's of all single byte values (made by makecrc.c) */ #if defined(PJ_IS_LITTLE_ENDIAN) && PJ_IS_LITTLE_ENDIAN != 0 -#define CRC32_INDEX(c) (c & 0xff) +#define CRC32_INDEX(c) (c & 0xff) #define CRC32_SHIFTED(c) (c >> 8) #define CRC32_SWAP(c) (c) @@ -81,7 +80,7 @@ static const pj_uint32_t crc_tab[] = { #elif defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN != 0 -#define CRC32_INDEX(c) (c >> 24) +#define CRC32_INDEX(c) (c >> 24) #define CRC32_SHIFTED(c) (c << 8) #define CRC32_SWAP(c) ((((c) & 0xff000000) >> 24) | \ (((c) & 0x00ff0000) >> 8) | \ @@ -154,27 +153,27 @@ PJ_DEF(void) pj_crc32_init(pj_crc32_context *ctx) } PJ_DEF(pj_uint32_t) pj_crc32_update(pj_crc32_context *ctx, - const pj_uint8_t *data, - pj_size_t nbytes) + const pj_uint8_t *data, + pj_size_t nbytes) { pj_uint32_t crc = ctx->crc_state ^ CRC32_NEGL; for( ; (((unsigned long)(pj_ssize_t)data) & 0x03) && nbytes > 0; --nbytes) { - crc = crc_tab[CRC32_INDEX(crc) ^ *data++] ^ CRC32_SHIFTED(crc); + crc = crc_tab[CRC32_INDEX(crc) ^ *data++] ^ CRC32_SHIFTED(crc); } while (nbytes >= 4) { - crc ^= *(const pj_uint32_t *)data; - crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); - crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); - crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); - crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); - nbytes -= 4; - data += 4; + crc ^= *(const pj_uint32_t *)data; + crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); + crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); + crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); + crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); + nbytes -= 4; + data += 4; } while (nbytes--) { - crc = crc_tab[CRC32_INDEX(crc) ^ *data++] ^ CRC32_SHIFTED(crc); + crc = crc_tab[CRC32_INDEX(crc) ^ *data++] ^ CRC32_SHIFTED(crc); } ctx->crc_state = crc ^ CRC32_NEGL; @@ -197,25 +196,25 @@ PJ_DEF(void) pj_crc32_init(pj_crc32_context *ctx) PJ_DEF(pj_uint32_t) pj_crc32_update(pj_crc32_context *ctx, - const pj_uint8_t *octets, - pj_size_t len) + const pj_uint8_t *octets, + pj_size_t len) { pj_uint32_t crc = ctx->crc_state; while (len--) { - pj_uint32_t temp; - int j; - - temp = (pj_uint32_t)((crc & 0xFF) ^ *octets++); - for (j = 0; j < 8; j++) - { - if (temp & 0x1) - temp = (temp >> 1) ^ 0xEDB88320; - else - temp >>= 1; - } - crc = (crc >> 8) ^ temp; + pj_uint32_t temp; + int j; + + temp = (pj_uint32_t)((crc & 0xFF) ^ *octets++); + for (j = 0; j < 8; j++) + { + if (temp & 0x1) + temp = (temp >> 1) ^ 0xEDB88320; + else + temp >>= 1; + } + crc = (crc >> 8) ^ temp; } ctx->crc_state = crc; @@ -232,7 +231,7 @@ PJ_DEF(pj_uint32_t) pj_crc32_final(pj_crc32_context *ctx) PJ_DEF(pj_uint32_t) pj_crc32_calc( const pj_uint8_t *data, - pj_size_t nbytes) + pj_size_t nbytes) { pj_crc32_context ctx; diff --git a/pjlib-util/src/pjlib-util/dns.c b/pjlib-util/src/pjlib-util/dns.c index 1f712eeced..fc96632587 100644 --- a/pjlib-util/src/pjlib-util/dns.c +++ b/pjlib-util/src/pjlib-util/dns.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,7 +28,7 @@ PJ_DEF(const char *) pj_dns_get_type_name(int type) { switch (type) { - case PJ_DNS_TYPE_A: return "A"; + case PJ_DNS_TYPE_A: return "A"; case PJ_DNS_TYPE_AAAA: return "AAAA"; case PJ_DNS_TYPE_SRV: return "SRV"; case PJ_DNS_TYPE_NS: return "NS"; @@ -54,10 +53,10 @@ static void write16(pj_uint8_t *p, pj_uint16_t val) * Initialize a DNS query transaction. */ PJ_DEF(pj_status_t) pj_dns_make_query( void *packet, - unsigned *size, - pj_uint16_t id, - int qtype, - const pj_str_t *name) + unsigned *size, + pj_uint16_t id, + int qtype, + const pj_str_t *name) { pj_uint8_t *p = (pj_uint8_t*)packet; const char *startlabel, *endlabel, *endname; @@ -86,14 +85,14 @@ PJ_DEF(pj_status_t) pj_dns_make_query( void *packet, startlabel = endlabel = name->ptr; endname = name->ptr + name->slen; while (endlabel != endname) { - while (endlabel != endname && *endlabel != '.') - ++endlabel; - *p++ = (pj_uint8_t)(endlabel - startlabel); - pj_memcpy(p, startlabel, endlabel-startlabel); - p += (endlabel-startlabel); - if (endlabel != endname && *endlabel == '.') - ++endlabel; - startlabel = endlabel; + while (endlabel != endname && *endlabel != '.') + ++endlabel; + *p++ = (pj_uint8_t)(endlabel - startlabel); + pj_memcpy(p, startlabel, endlabel-startlabel); + p += (endlabel-startlabel); + if (endlabel != endname && *endlabel == '.') + ++endlabel; + startlabel = endlabel; } *p++ = '\0'; @@ -116,66 +115,66 @@ PJ_DEF(pj_status_t) pj_dns_make_query( void *packet, * it may contain pointers when name compression is applied) */ static pj_status_t get_name_len(int rec_counter, const pj_uint8_t *pkt, - const pj_uint8_t *start, const pj_uint8_t *max, - int *parsed_len, int *name_len) + const pj_uint8_t *start, const pj_uint8_t *max, + int *parsed_len, int *name_len) { const pj_uint8_t *p; pj_status_t status; /* Limit the number of recursion */ if (rec_counter > 10) { - /* Too many name recursion */ - return PJLIB_UTIL_EDNSINNAMEPTR; + /* Too many name recursion */ + return PJLIB_UTIL_EDNSINNAMEPTR; } *name_len = *parsed_len = 0; p = start; while (*p) { - if ((*p & 0xc0) == 0xc0) { - /* Compression is found! */ - int ptr_len = 0; - int dummy; - pj_uint16_t offset; - - /* Get the 14bit offset */ - pj_memcpy(&offset, p, 2); - offset ^= pj_htons((pj_uint16_t)(0xc0 << 8)); - offset = pj_ntohs(offset); - - /* Check that offset is valid */ - if (offset >= max - pkt) - return PJLIB_UTIL_EDNSINNAMEPTR; - - /* Get the name length from that offset. */ - status = get_name_len(rec_counter+1, pkt, pkt + offset, max, - &dummy, &ptr_len); - if (status != PJ_SUCCESS) - return status; - - *parsed_len += 2; - *name_len += ptr_len; - - return PJ_SUCCESS; - } else { - unsigned label_len = *p; - - /* Check that label length is valid. - * Each label consists of an octet length (of size 1) followed - * by the octet of the specified length (label_len). Then it - * must be followed by either another label's octet length or - * a zero length octet (that terminates the sequence). - */ - if (p+1+label_len+1 > max) - return PJLIB_UTIL_EDNSINNAMEPTR; - - p += (label_len + 1); - *parsed_len += (label_len + 1); - - if (*p != 0) - ++label_len; - - *name_len += label_len; - } + if ((*p & 0xc0) == 0xc0) { + /* Compression is found! */ + int ptr_len = 0; + int dummy; + pj_uint16_t offset; + + /* Get the 14bit offset */ + pj_memcpy(&offset, p, 2); + offset ^= pj_htons((pj_uint16_t)(0xc0 << 8)); + offset = pj_ntohs(offset); + + /* Check that offset is valid */ + if (offset >= max - pkt) + return PJLIB_UTIL_EDNSINNAMEPTR; + + /* Get the name length from that offset. */ + status = get_name_len(rec_counter+1, pkt, pkt + offset, max, + &dummy, &ptr_len); + if (status != PJ_SUCCESS) + return status; + + *parsed_len += 2; + *name_len += ptr_len; + + return PJ_SUCCESS; + } else { + unsigned label_len = *p; + + /* Check that label length is valid. + * Each label consists of an octet length (of size 1) followed + * by the octet of the specified length (label_len). Then it + * must be followed by either another label's octet length or + * a zero length octet (that terminates the sequence). + */ + if (p+1+label_len+1 > max) + return PJLIB_UTIL_EDNSINNAMEPTR; + + p += (label_len + 1); + *parsed_len += (label_len + 1); + + if (*p != 0) + ++label_len; + + *name_len += label_len; + } } ++p; (*parsed_len)++; @@ -188,60 +187,60 @@ static pj_status_t get_name_len(int rec_counter, const pj_uint8_t *pkt, * it may contain pointers when compression is applied). */ static pj_status_t get_name(int rec_counter, const pj_uint8_t *pkt, - const pj_uint8_t *start, const pj_uint8_t *max, - pj_str_t *name) + const pj_uint8_t *start, const pj_uint8_t *max, + pj_str_t *name) { const pj_uint8_t *p; pj_status_t status; /* Limit the number of recursion */ if (rec_counter > 10) { - /* Too many name recursion */ - return PJLIB_UTIL_EDNSINNAMEPTR; + /* Too many name recursion */ + return PJLIB_UTIL_EDNSINNAMEPTR; } p = start; while (*p) { - if ((*p & 0xc0) == 0xc0) { - /* Compression is found! */ - pj_uint16_t offset; - - /* Get the 14bit offset */ - pj_memcpy(&offset, p, 2); - offset ^= pj_htons((pj_uint16_t)(0xc0 << 8)); - offset = pj_ntohs(offset); - - /* Check that offset is valid */ - if (offset >= max - pkt) - return PJLIB_UTIL_EDNSINNAMEPTR; - - /* Retrieve the name from that offset. */ - status = get_name(rec_counter+1, pkt, pkt + offset, max, name); - if (status != PJ_SUCCESS) - return status; - - return PJ_SUCCESS; - } else { - unsigned label_len = *p; - - /* Check that label length is valid. - * Each label consists of an octet length (of size 1) followed - * by the octet of the specified length (label_len). Then it - * must be followed by either another label's octet length or - * a zero length octet (that terminates the sequence). - */ - if (p+1+label_len+1 > max) - return PJLIB_UTIL_EDNSINNAMEPTR; - - pj_memcpy(name->ptr + name->slen, p+1, label_len); - name->slen += label_len; - - p += label_len + 1; - if (*p != 0) { - *(name->ptr + name->slen) = '.'; - ++name->slen; - } - } + if ((*p & 0xc0) == 0xc0) { + /* Compression is found! */ + pj_uint16_t offset; + + /* Get the 14bit offset */ + pj_memcpy(&offset, p, 2); + offset ^= pj_htons((pj_uint16_t)(0xc0 << 8)); + offset = pj_ntohs(offset); + + /* Check that offset is valid */ + if (offset >= max - pkt) + return PJLIB_UTIL_EDNSINNAMEPTR; + + /* Retrieve the name from that offset. */ + status = get_name(rec_counter+1, pkt, pkt + offset, max, name); + if (status != PJ_SUCCESS) + return status; + + return PJ_SUCCESS; + } else { + unsigned label_len = *p; + + /* Check that label length is valid. + * Each label consists of an octet length (of size 1) followed + * by the octet of the specified length (label_len). Then it + * must be followed by either another label's octet length or + * a zero length octet (that terminates the sequence). + */ + if (p+1+label_len+1 > max) + return PJLIB_UTIL_EDNSINNAMEPTR; + + pj_memcpy(name->ptr + name->slen, p+1, label_len); + name->slen += label_len; + + p += label_len + 1; + if (*p != 0) { + *(name->ptr + name->slen) = '.'; + ++name->slen; + } + } } return PJ_SUCCESS; @@ -250,8 +249,8 @@ static pj_status_t get_name(int rec_counter, const pj_uint8_t *pkt, /* Parse query records. */ static pj_status_t parse_query(pj_dns_parsed_query *q, pj_pool_t *pool, - const pj_uint8_t *pkt, const pj_uint8_t *start, - const pj_uint8_t *max, int *parsed_len) + const pj_uint8_t *pkt, const pj_uint8_t *start, + const pj_uint8_t *max, int *parsed_len) { const pj_uint8_t *p = start; int name_len, name_part_len; @@ -260,7 +259,7 @@ static pj_status_t parse_query(pj_dns_parsed_query *q, pj_pool_t *pool, /* Get the length of the name */ status = get_name_len(0, pkt, start, max, &name_part_len, &name_len); if (status != PJ_SUCCESS) - return status; + return status; /* Allocate memory for the name */ q->name.ptr = (char*) pj_pool_alloc(pool, name_len+4); @@ -269,13 +268,13 @@ static pj_status_t parse_query(pj_dns_parsed_query *q, pj_pool_t *pool, /* Get the name */ status = get_name(0, pkt, start, max, &q->name); if (status != PJ_SUCCESS) - return status; + return status; p = (start + name_part_len); /* Check the size can accomodate next few fields. */ if (p + 4 > max) - return PJLIB_UTIL_EDNSINSIZE; + return PJLIB_UTIL_EDNSINSIZE; /* Get the type */ pj_memcpy(&q->type, p, 2); @@ -295,9 +294,9 @@ static pj_status_t parse_query(pj_dns_parsed_query *q, pj_pool_t *pool, /* Parse RR records */ static pj_status_t parse_rr(pj_dns_parsed_rr *rr, pj_pool_t *pool, - const pj_uint8_t *pkt, - const pj_uint8_t *start, const pj_uint8_t *max, - int *parsed_len) + const pj_uint8_t *pkt, + const pj_uint8_t *start, const pj_uint8_t *max, + int *parsed_len) { const pj_uint8_t *p = start; int name_len, name_part_len; @@ -306,7 +305,7 @@ static pj_status_t parse_rr(pj_dns_parsed_rr *rr, pj_pool_t *pool, /* Get the length of the name */ status = get_name_len(0, pkt, start, max, &name_part_len, &name_len); if (status != PJ_SUCCESS) - return status; + return status; /* Allocate memory for the name */ rr->name.ptr = (char*) pj_pool_alloc(pool, name_len+4); @@ -315,13 +314,13 @@ static pj_status_t parse_rr(pj_dns_parsed_rr *rr, pj_pool_t *pool, /* Get the name */ status = get_name(0, pkt, start, max, &rr->name); if (status != PJ_SUCCESS) - return status; + return status; p = (start + name_part_len); /* Check the size can accomodate next few fields. */ if (p+10 > max) - return PJLIB_UTIL_EDNSINSIZE; + return PJLIB_UTIL_EDNSINSIZE; /* Get the type */ pj_memcpy(&rr->type, p, 2); @@ -335,13 +334,13 @@ static pj_status_t parse_rr(pj_dns_parsed_rr *rr, pj_pool_t *pool, /* Class MUST be IN */ if (rr->dnsclass != 1) { - /* Class is not IN, return error only if type is known (see #1889) */ - if (rr->type == PJ_DNS_TYPE_A || rr->type == PJ_DNS_TYPE_AAAA || - rr->type == PJ_DNS_TYPE_CNAME || rr->type == PJ_DNS_TYPE_NS || - rr->type == PJ_DNS_TYPE_PTR || rr->type == PJ_DNS_TYPE_SRV) - { - return PJLIB_UTIL_EDNSINCLASS; - } + /* Class is not IN, return error only if type is known (see #1889) */ + if (rr->type == PJ_DNS_TYPE_A || rr->type == PJ_DNS_TYPE_AAAA || + rr->type == PJ_DNS_TYPE_CNAME || rr->type == PJ_DNS_TYPE_NS || + rr->type == PJ_DNS_TYPE_PTR || rr->type == PJ_DNS_TYPE_SRV) + { + return PJLIB_UTIL_EDNSINCLASS; + } } /* Get TTL */ @@ -356,76 +355,76 @@ static pj_status_t parse_rr(pj_dns_parsed_rr *rr, pj_pool_t *pool, /* Check that length is valid */ if (p + rr->rdlength > max) - return PJLIB_UTIL_EDNSINSIZE; + return PJLIB_UTIL_EDNSINSIZE; /* Parse some well known records */ if (rr->type == PJ_DNS_TYPE_A) { - pj_memcpy(&rr->rdata.a.ip_addr, p, 4); - p += 4; + pj_memcpy(&rr->rdata.a.ip_addr, p, 4); + p += 4; } else if (rr->type == PJ_DNS_TYPE_AAAA) { - pj_memcpy(&rr->rdata.aaaa.ip_addr, p, 16); - p += 16; + pj_memcpy(&rr->rdata.aaaa.ip_addr, p, 16); + p += 16; } else if (rr->type == PJ_DNS_TYPE_CNAME || - rr->type == PJ_DNS_TYPE_NS || - rr->type == PJ_DNS_TYPE_PTR) + rr->type == PJ_DNS_TYPE_NS || + rr->type == PJ_DNS_TYPE_PTR) { - /* Get the length of the target name */ - status = get_name_len(0, pkt, p, max, &name_part_len, &name_len); - if (status != PJ_SUCCESS) - return status; + /* Get the length of the target name */ + status = get_name_len(0, pkt, p, max, &name_part_len, &name_len); + if (status != PJ_SUCCESS) + return status; - /* Allocate memory for the name */ - rr->rdata.cname.name.ptr = (char*) pj_pool_alloc(pool, name_len); - rr->rdata.cname.name.slen = 0; + /* Allocate memory for the name */ + rr->rdata.cname.name.ptr = (char*) pj_pool_alloc(pool, name_len); + rr->rdata.cname.name.slen = 0; - /* Get the name */ - status = get_name(0, pkt, p, max, &rr->rdata.cname.name); - if (status != PJ_SUCCESS) - return status; + /* Get the name */ + status = get_name(0, pkt, p, max, &rr->rdata.cname.name); + if (status != PJ_SUCCESS) + return status; - p += name_part_len; + p += name_part_len; } else if (rr->type == PJ_DNS_TYPE_SRV) { - /* Priority */ - pj_memcpy(&rr->rdata.srv.prio, p, 2); - rr->rdata.srv.prio = pj_ntohs(rr->rdata.srv.prio); - p += 2; - - /* Weight */ - pj_memcpy(&rr->rdata.srv.weight, p, 2); - rr->rdata.srv.weight = pj_ntohs(rr->rdata.srv.weight); - p += 2; - - /* Port */ - pj_memcpy(&rr->rdata.srv.port, p, 2); - rr->rdata.srv.port = pj_ntohs(rr->rdata.srv.port); - p += 2; - - /* Get the length of the target name */ - status = get_name_len(0, pkt, p, max, &name_part_len, &name_len); - if (status != PJ_SUCCESS) - return status; - - /* Allocate memory for the name */ - rr->rdata.srv.target.ptr = (char*) pj_pool_alloc(pool, name_len); - rr->rdata.srv.target.slen = 0; - - /* Get the name */ - status = get_name(0, pkt, p, max, &rr->rdata.srv.target); - if (status != PJ_SUCCESS) - return status; - p += name_part_len; + /* Priority */ + pj_memcpy(&rr->rdata.srv.prio, p, 2); + rr->rdata.srv.prio = pj_ntohs(rr->rdata.srv.prio); + p += 2; + + /* Weight */ + pj_memcpy(&rr->rdata.srv.weight, p, 2); + rr->rdata.srv.weight = pj_ntohs(rr->rdata.srv.weight); + p += 2; + + /* Port */ + pj_memcpy(&rr->rdata.srv.port, p, 2); + rr->rdata.srv.port = pj_ntohs(rr->rdata.srv.port); + p += 2; + + /* Get the length of the target name */ + status = get_name_len(0, pkt, p, max, &name_part_len, &name_len); + if (status != PJ_SUCCESS) + return status; + + /* Allocate memory for the name */ + rr->rdata.srv.target.ptr = (char*) pj_pool_alloc(pool, name_len); + rr->rdata.srv.target.slen = 0; + + /* Get the name */ + status = get_name(0, pkt, p, max, &rr->rdata.srv.target); + if (status != PJ_SUCCESS) + return status; + p += name_part_len; } else { - /* Copy the raw data */ - rr->data = pj_pool_alloc(pool, rr->rdlength); - pj_memcpy(rr->data, p, rr->rdlength); + /* Copy the raw data */ + rr->data = pj_pool_alloc(pool, rr->rdlength); + pj_memcpy(rr->data, p, rr->rdlength); - p += rr->rdlength; + p += rr->rdlength; } *parsed_len = (int)(p - start); @@ -437,9 +436,9 @@ static pj_status_t parse_rr(pj_dns_parsed_rr *rr, pj_pool_t *pool, * Parse raw DNS packet into DNS packet structure. */ PJ_DEF(pj_status_t) pj_dns_parse_packet( pj_pool_t *pool, - const void *packet, - unsigned size, - pj_dns_parsed_packet **p_res) + const void *packet, + unsigned size, + pj_dns_parsed_packet **p_res) { pj_dns_parsed_packet *res; const pj_uint8_t *start, *end; @@ -451,14 +450,14 @@ PJ_DEF(pj_status_t) pj_dns_parse_packet( pj_pool_t *pool, /* Packet size must be at least as big as the header */ if (size < sizeof(pj_dns_hdr)) - return PJLIB_UTIL_EDNSINSIZE; + return PJLIB_UTIL_EDNSINSIZE; /* Create the structure */ res = PJ_POOL_ZALLOC_T(pool, pj_dns_parsed_packet); /* Copy the DNS header, and convert endianness to host byte order */ pj_memcpy(&res->hdr, packet, sizeof(pj_dns_hdr)); - res->hdr.id = pj_ntohs(res->hdr.id); + res->hdr.id = pj_ntohs(res->hdr.id); res->hdr.flags = pj_ntohs(res->hdr.flags); res->hdr.qdcount = pj_ntohs(res->hdr.qdcount); res->hdr.anscount = pj_ntohs(res->hdr.anscount); @@ -472,73 +471,73 @@ PJ_DEF(pj_status_t) pj_dns_parse_packet( pj_pool_t *pool, /* Parse query records (if any). */ if (res->hdr.qdcount) { - res->q = (pj_dns_parsed_query*) - pj_pool_zalloc(pool, res->hdr.qdcount * - sizeof(pj_dns_parsed_query)); - for (i=0; ihdr.qdcount; ++i) { - int parsed_len = 0; - - status = parse_query(&res->q[i], pool, (const pj_uint8_t*)packet, - start, end, &parsed_len); - if (status != PJ_SUCCESS) - return status; - - start += parsed_len; - } + res->q = (pj_dns_parsed_query*) + pj_pool_zalloc(pool, res->hdr.qdcount * + sizeof(pj_dns_parsed_query)); + for (i=0; ihdr.qdcount; ++i) { + int parsed_len = 0; + + status = parse_query(&res->q[i], pool, (const pj_uint8_t*)packet, + start, end, &parsed_len); + if (status != PJ_SUCCESS) + return status; + + start += parsed_len; + } } /* Parse answer, if any */ if (res->hdr.anscount) { - res->ans = (pj_dns_parsed_rr*) - pj_pool_zalloc(pool, res->hdr.anscount * - sizeof(pj_dns_parsed_rr)); + res->ans = (pj_dns_parsed_rr*) + pj_pool_zalloc(pool, res->hdr.anscount * + sizeof(pj_dns_parsed_rr)); - for (i=0; ihdr.anscount; ++i) { - int parsed_len; + for (i=0; ihdr.anscount; ++i) { + int parsed_len; - status = parse_rr(&res->ans[i], pool, (const pj_uint8_t*)packet, - start, end, &parsed_len); - if (status != PJ_SUCCESS) - return status; + status = parse_rr(&res->ans[i], pool, (const pj_uint8_t*)packet, + start, end, &parsed_len); + if (status != PJ_SUCCESS) + return status; - start += parsed_len; - } + start += parsed_len; + } } /* Parse authoritative NS records, if any */ if (res->hdr.nscount) { - res->ns = (pj_dns_parsed_rr*) - pj_pool_zalloc(pool, res->hdr.nscount * - sizeof(pj_dns_parsed_rr)); + res->ns = (pj_dns_parsed_rr*) + pj_pool_zalloc(pool, res->hdr.nscount * + sizeof(pj_dns_parsed_rr)); - for (i=0; ihdr.nscount; ++i) { - int parsed_len; + for (i=0; ihdr.nscount; ++i) { + int parsed_len; - status = parse_rr(&res->ns[i], pool, (const pj_uint8_t*)packet, - start, end, &parsed_len); - if (status != PJ_SUCCESS) - return status; + status = parse_rr(&res->ns[i], pool, (const pj_uint8_t*)packet, + start, end, &parsed_len); + if (status != PJ_SUCCESS) + return status; - start += parsed_len; - } + start += parsed_len; + } } /* Parse additional RR answer, if any */ if (res->hdr.arcount) { - res->arr = (pj_dns_parsed_rr*) - pj_pool_zalloc(pool, res->hdr.arcount * - sizeof(pj_dns_parsed_rr)); + res->arr = (pj_dns_parsed_rr*) + pj_pool_zalloc(pool, res->hdr.arcount * + sizeof(pj_dns_parsed_rr)); - for (i=0; ihdr.arcount; ++i) { - int parsed_len; + for (i=0; ihdr.arcount; ++i) { + int parsed_len; - status = parse_rr(&res->arr[i], pool, (const pj_uint8_t*)packet, - start, end, &parsed_len); - if (status != PJ_SUCCESS) - return status; + status = parse_rr(&res->arr[i], pool, (const pj_uint8_t*)packet, + start, end, &parsed_len); + if (status != PJ_SUCCESS) + return status; - start += parsed_len; - } + start += parsed_len; + } } /* Looks like everything is okay */ @@ -553,41 +552,41 @@ PJ_DEF(pj_status_t) pj_dns_parse_packet( pj_pool_t *pool, * the string with the pool, but rather just use the pointer there. */ static void apply_name_table( unsigned *count, - pj_str_t nametable[], - const pj_str_t *src, - pj_pool_t *pool, - pj_str_t *dst) + pj_str_t nametable[], + const pj_str_t *src, + pj_pool_t *pool, + pj_str_t *dst) { unsigned i; /* Scan strings in nametable */ for (i=0; i<*count; ++i) { - if (pj_stricmp(&nametable[i], src) == 0) - break; + if (pj_stricmp(&nametable[i], src) == 0) + break; } /* If name is found in nametable, use the pointer in the nametable */ if (i != *count) { - dst->ptr = nametable[i].ptr; - dst->slen = nametable[i].slen; - return; + dst->ptr = nametable[i].ptr; + dst->slen = nametable[i].slen; + return; } /* Otherwise duplicate the string, and insert new name in nametable */ pj_strdup(pool, dst, src); if (*count < PJ_DNS_MAX_NAMES_IN_NAMETABLE) { - nametable[*count].ptr = dst->ptr; - nametable[*count].slen = dst->slen; + nametable[*count].ptr = dst->ptr; + nametable[*count].slen = dst->slen; - ++(*count); + ++(*count); } } static void copy_query(pj_pool_t *pool, pj_dns_parsed_query *dst, - const pj_dns_parsed_query *src, - unsigned *nametable_count, - pj_str_t nametable[]) + const pj_dns_parsed_query *src, + unsigned *nametable_count, + pj_str_t nametable[]) { pj_memcpy(dst, src, sizeof(*src)); apply_name_table(nametable_count, nametable, &src->name, pool, &dst->name); @@ -595,32 +594,32 @@ static void copy_query(pj_pool_t *pool, pj_dns_parsed_query *dst, static void copy_rr(pj_pool_t *pool, pj_dns_parsed_rr *dst, - const pj_dns_parsed_rr *src, - unsigned *nametable_count, - pj_str_t nametable[]) + const pj_dns_parsed_rr *src, + unsigned *nametable_count, + pj_str_t nametable[]) { pj_memcpy(dst, src, sizeof(*src)); apply_name_table(nametable_count, nametable, &src->name, pool, &dst->name); if (src->data) { - dst->data = pj_pool_alloc(pool, src->rdlength); - pj_memcpy(dst->data, src->data, src->rdlength); + dst->data = pj_pool_alloc(pool, src->rdlength); + pj_memcpy(dst->data, src->data, src->rdlength); } if (src->type == PJ_DNS_TYPE_SRV) { - apply_name_table(nametable_count, nametable, &src->rdata.srv.target, - pool, &dst->rdata.srv.target); + apply_name_table(nametable_count, nametable, &src->rdata.srv.target, + pool, &dst->rdata.srv.target); } else if (src->type == PJ_DNS_TYPE_A) { - dst->rdata.a.ip_addr.s_addr = src->rdata.a.ip_addr.s_addr; + dst->rdata.a.ip_addr.s_addr = src->rdata.a.ip_addr.s_addr; } else if (src->type == PJ_DNS_TYPE_AAAA) { - pj_memcpy(&dst->rdata.aaaa.ip_addr, &src->rdata.aaaa.ip_addr, - sizeof(pj_in6_addr)); + pj_memcpy(&dst->rdata.aaaa.ip_addr, &src->rdata.aaaa.ip_addr, + sizeof(pj_in6_addr)); } else if (src->type == PJ_DNS_TYPE_CNAME) { - pj_strdup(pool, &dst->rdata.cname.name, &src->rdata.cname.name); + pj_strdup(pool, &dst->rdata.cname.name, &src->rdata.cname.name); } else if (src->type == PJ_DNS_TYPE_NS) { - pj_strdup(pool, &dst->rdata.ns.name, &src->rdata.ns.name); + pj_strdup(pool, &dst->rdata.ns.name, &src->rdata.ns.name); } else if (src->type == PJ_DNS_TYPE_PTR) { - pj_strdup(pool, &dst->rdata.ptr.name, &src->rdata.ptr.name); + pj_strdup(pool, &dst->rdata.ptr.name, &src->rdata.ptr.name); } } @@ -628,9 +627,9 @@ static void copy_rr(pj_pool_t *pool, pj_dns_parsed_rr *dst, * Duplicate DNS packet. */ PJ_DEF(void) pj_dns_packet_dup(pj_pool_t *pool, - const pj_dns_parsed_packet*p, - unsigned options, - pj_dns_parsed_packet **p_dst) + const pj_dns_parsed_packet*p, + unsigned options, + pj_dns_parsed_packet **p_dst) { pj_dns_parsed_packet *dst; unsigned nametable_count = 0; @@ -655,66 +654,66 @@ PJ_DEF(void) pj_dns_packet_dup(pj_pool_t *pool, dst->hdr.anscount = 0; dst->hdr.nscount = 0; dst->hdr.arcount = 0; - + /* Copy query section */ if (p->hdr.qdcount && (options & PJ_DNS_NO_QD)==0) { - dst->q = (pj_dns_parsed_query*) - pj_pool_alloc(pool, p->hdr.qdcount * - sizeof(pj_dns_parsed_query)); - for (i=0; ihdr.qdcount; ++i) { - copy_query(pool, &dst->q[i], &p->q[i], - &nametable_count, nametable); - ++dst->hdr.qdcount; - } + dst->q = (pj_dns_parsed_query*) + pj_pool_alloc(pool, p->hdr.qdcount * + sizeof(pj_dns_parsed_query)); + for (i=0; ihdr.qdcount; ++i) { + copy_query(pool, &dst->q[i], &p->q[i], + &nametable_count, nametable); + ++dst->hdr.qdcount; + } } /* Copy answer section */ if (p->hdr.anscount && (options & PJ_DNS_NO_ANS)==0) { - dst->ans = (pj_dns_parsed_rr*) - pj_pool_alloc(pool, p->hdr.anscount * - sizeof(pj_dns_parsed_rr)); - for (i=0; ihdr.anscount; ++i) { - copy_rr(pool, &dst->ans[i], &p->ans[i], - &nametable_count, nametable); - ++dst->hdr.anscount; - } + dst->ans = (pj_dns_parsed_rr*) + pj_pool_alloc(pool, p->hdr.anscount * + sizeof(pj_dns_parsed_rr)); + for (i=0; ihdr.anscount; ++i) { + copy_rr(pool, &dst->ans[i], &p->ans[i], + &nametable_count, nametable); + ++dst->hdr.anscount; + } } /* Copy NS section */ if (p->hdr.nscount && (options & PJ_DNS_NO_NS)==0) { - dst->ns = (pj_dns_parsed_rr*) - pj_pool_alloc(pool, p->hdr.nscount * - sizeof(pj_dns_parsed_rr)); - for (i=0; ihdr.nscount; ++i) { - copy_rr(pool, &dst->ns[i], &p->ns[i], - &nametable_count, nametable); - ++dst->hdr.nscount; - } + dst->ns = (pj_dns_parsed_rr*) + pj_pool_alloc(pool, p->hdr.nscount * + sizeof(pj_dns_parsed_rr)); + for (i=0; ihdr.nscount; ++i) { + copy_rr(pool, &dst->ns[i], &p->ns[i], + &nametable_count, nametable); + ++dst->hdr.nscount; + } } /* Copy additional info section */ if (p->hdr.arcount && (options & PJ_DNS_NO_AR)==0) { - dst->arr = (pj_dns_parsed_rr*) - pj_pool_alloc(pool, p->hdr.arcount * - sizeof(pj_dns_parsed_rr)); - for (i=0; ihdr.arcount; ++i) { - copy_rr(pool, &dst->arr[i], &p->arr[i], - &nametable_count, nametable); - ++dst->hdr.arcount; - } + dst->arr = (pj_dns_parsed_rr*) + pj_pool_alloc(pool, p->hdr.arcount * + sizeof(pj_dns_parsed_rr)); + for (i=0; ihdr.arcount; ++i) { + copy_rr(pool, &dst->arr[i], &p->arr[i], + &nametable_count, nametable); + ++dst->hdr.arcount; + } } } PJ_DEF(void) pj_dns_init_srv_rr( pj_dns_parsed_rr *rec, - const pj_str_t *res_name, - unsigned dnsclass, - unsigned ttl, - unsigned prio, - unsigned weight, - unsigned port, - const pj_str_t *target) + const pj_str_t *res_name, + unsigned dnsclass, + unsigned ttl, + unsigned prio, + unsigned weight, + unsigned port, + const pj_str_t *target) { pj_bzero(rec, sizeof(*rec)); rec->name = *res_name; @@ -729,10 +728,10 @@ PJ_DEF(void) pj_dns_init_srv_rr( pj_dns_parsed_rr *rec, PJ_DEF(void) pj_dns_init_cname_rr( pj_dns_parsed_rr *rec, - const pj_str_t *res_name, - unsigned dnsclass, - unsigned ttl, - const pj_str_t *name) + const pj_str_t *res_name, + unsigned dnsclass, + unsigned ttl, + const pj_str_t *name) { pj_bzero(rec, sizeof(*rec)); rec->name = *res_name; @@ -744,10 +743,10 @@ PJ_DEF(void) pj_dns_init_cname_rr( pj_dns_parsed_rr *rec, PJ_DEF(void) pj_dns_init_a_rr( pj_dns_parsed_rr *rec, - const pj_str_t *res_name, - unsigned dnsclass, - unsigned ttl, - const pj_in_addr *ip_addr) + const pj_str_t *res_name, + unsigned dnsclass, + unsigned ttl, + const pj_in_addr *ip_addr) { pj_bzero(rec, sizeof(*rec)); rec->name = *res_name; @@ -759,10 +758,10 @@ PJ_DEF(void) pj_dns_init_a_rr( pj_dns_parsed_rr *rec, PJ_DEF(void) pj_dns_init_aaaa_rr(pj_dns_parsed_rr *rec, - const pj_str_t *res_name, - unsigned dnsclass, - unsigned ttl, - const pj_in6_addr *ip_addr) + const pj_str_t *res_name, + unsigned dnsclass, + unsigned ttl, + const pj_in6_addr *ip_addr) { pj_bzero(rec, sizeof(*rec)); rec->name = *res_name; diff --git a/pjlib-util/src/pjlib-util/dns_dump.c b/pjlib-util/src/pjlib-util/dns_dump.c index ab9ca684cf..9578371a4b 100644 --- a/pjlib-util/src/pjlib-util/dns_dump.c +++ b/pjlib-util/src/pjlib-util/dns_dump.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -23,51 +22,51 @@ #include #define THIS_FILE "dns_dump.c" -#define LEVEL 3 +#define LEVEL 3 static const char *spell_ttl(char *buf, int size, unsigned ttl) { -#define DAY (3600*24) -#define HOUR (3600) -#define MINUTE (60) +#define DAY (3600*24) +#define HOUR (3600) +#define MINUTE (60) char *p = buf; int len; if (ttl > DAY) { - len = pj_ansi_snprintf(p, size, "%dd ", ttl/DAY); - if (len < 1 || len >= size) - return "-err-"; - size -= len; - p += len; - ttl %= DAY; + len = pj_ansi_snprintf(p, size, "%dd ", ttl/DAY); + if (len < 1 || len >= size) + return "-err-"; + size -= len; + p += len; + ttl %= DAY; } if (ttl > HOUR) { - len = pj_ansi_snprintf(p, size, "%dh ", ttl/HOUR); - if (len < 1 || len >= size) - return "-err-"; - size -= len; - p += len; - ttl %= HOUR; + len = pj_ansi_snprintf(p, size, "%dh ", ttl/HOUR); + if (len < 1 || len >= size) + return "-err-"; + size -= len; + p += len; + ttl %= HOUR; } if (ttl > MINUTE) { - len = pj_ansi_snprintf(p, size, "%dm ", ttl/MINUTE); - if (len < 1 || len >= size) - return "-err-"; - size -= len; - p += len; - ttl %= MINUTE; + len = pj_ansi_snprintf(p, size, "%dm ", ttl/MINUTE); + if (len < 1 || len >= size) + return "-err-"; + size -= len; + p += len; + ttl %= MINUTE; } if (ttl > 0) { - len = pj_ansi_snprintf(p, size, "%ds ", ttl); - if (len < 1 || len >= size) - return "-err-"; - size -= len; - p += len; - ttl = 0; + len = pj_ansi_snprintf(p, size, "%ds ", ttl); + if (len < 1 || len >= size) + return "-err-"; + size -= len; + p += len; + ttl = 0; } *p = '\0'; @@ -78,11 +77,11 @@ static const char *spell_ttl(char *buf, int size, unsigned ttl) static void dump_query(unsigned index, const pj_dns_parsed_query *q) { PJ_LOG(3,(THIS_FILE, " %d. Name: %.*s", - index, (int)q->name.slen, q->name.ptr)); + index, (int)q->name.slen, q->name.ptr)); PJ_LOG(3,(THIS_FILE, " Type: %s (%d)", - pj_dns_get_type_name(q->type), q->type)); + pj_dns_get_type_name(q->type), q->type)); PJ_LOG(3,(THIS_FILE, " Class: %s (%d)", - (q->dnsclass==1 ? "IN" : ""), q->dnsclass)); + (q->dnsclass==1 ? "IN" : ""), q->dnsclass)); } static void dump_answer(unsigned index, const pj_dns_parsed_rr *rr) @@ -93,37 +92,37 @@ static void dump_answer(unsigned index, const pj_dns_parsed_rr *rr) char addr[PJ_INET6_ADDRSTRLEN]; if (name->slen == 0) - name = &root_name; + name = &root_name; PJ_LOG(3,(THIS_FILE, " %d. %s record (type=%d)", - index, pj_dns_get_type_name(rr->type), - rr->type)); + index, pj_dns_get_type_name(rr->type), + rr->type)); PJ_LOG(3,(THIS_FILE, " Name: %.*s", (int)name->slen, name->ptr)); PJ_LOG(3,(THIS_FILE, " TTL: %u (%s)", rr->ttl, - spell_ttl(ttl_words, sizeof(ttl_words), rr->ttl))); + spell_ttl(ttl_words, sizeof(ttl_words), rr->ttl))); PJ_LOG(3,(THIS_FILE, " Data length: %u", rr->rdlength)); if (rr->type == PJ_DNS_TYPE_SRV) { - PJ_LOG(3,(THIS_FILE, " SRV: prio=%d, weight=%d %.*s:%d", - rr->rdata.srv.prio, rr->rdata.srv.weight, - (int)rr->rdata.srv.target.slen, - rr->rdata.srv.target.ptr, - rr->rdata.srv.port)); + PJ_LOG(3,(THIS_FILE, " SRV: prio=%d, weight=%d %.*s:%d", + rr->rdata.srv.prio, rr->rdata.srv.weight, + (int)rr->rdata.srv.target.slen, + rr->rdata.srv.target.ptr, + rr->rdata.srv.port)); } else if (rr->type == PJ_DNS_TYPE_CNAME || - rr->type == PJ_DNS_TYPE_NS || - rr->type == PJ_DNS_TYPE_PTR) + rr->type == PJ_DNS_TYPE_NS || + rr->type == PJ_DNS_TYPE_PTR) { - PJ_LOG(3,(THIS_FILE, " Name: %.*s", - (int)rr->rdata.cname.name.slen, - rr->rdata.cname.name.ptr)); + PJ_LOG(3,(THIS_FILE, " Name: %.*s", + (int)rr->rdata.cname.name.slen, + rr->rdata.cname.name.ptr)); } else if (rr->type == PJ_DNS_TYPE_A) { - PJ_LOG(3,(THIS_FILE, " IP address: %s", - pj_inet_ntop2(pj_AF_INET(), &rr->rdata.a.ip_addr, - addr, sizeof(addr)))); + PJ_LOG(3,(THIS_FILE, " IP address: %s", + pj_inet_ntop2(pj_AF_INET(), &rr->rdata.a.ip_addr, + addr, sizeof(addr)))); } else if (rr->type == PJ_DNS_TYPE_AAAA) { - PJ_LOG(3,(THIS_FILE, " IPv6 address: %s", - pj_inet_ntop2(pj_AF_INET6(), &rr->rdata.aaaa.ip_addr, - addr, sizeof(addr)))); + PJ_LOG(3,(THIS_FILE, " IPv6 address: %s", + pj_inet_ntop2(pj_AF_INET6(), &rr->rdata.aaaa.ip_addr, + addr, sizeof(addr)))); } } @@ -136,14 +135,14 @@ PJ_DEF(void) pj_dns_dump_packet(const pj_dns_parsed_packet *res) /* Header part */ PJ_LOG(3,(THIS_FILE, "Domain Name System packet (%s):", - (PJ_DNS_GET_QR(res->hdr.flags) ? "response" : "query"))); + (PJ_DNS_GET_QR(res->hdr.flags) ? "response" : "query"))); PJ_LOG(3,(THIS_FILE, " Transaction ID: %d", res->hdr.id)); PJ_LOG(3,(THIS_FILE, - " Flags: opcode=%d, authoritative=%d, truncated=%d, rcode=%d", - PJ_DNS_GET_OPCODE(res->hdr.flags), - PJ_DNS_GET_AA(res->hdr.flags), - PJ_DNS_GET_TC(res->hdr.flags), - PJ_DNS_GET_RCODE(res->hdr.flags))); + " Flags: opcode=%d, authoritative=%d, truncated=%d, rcode=%d", + PJ_DNS_GET_OPCODE(res->hdr.flags), + PJ_DNS_GET_AA(res->hdr.flags), + PJ_DNS_GET_TC(res->hdr.flags), + PJ_DNS_GET_RCODE(res->hdr.flags))); PJ_LOG(3,(THIS_FILE, " Nb of queries: %d", res->hdr.qdcount)); PJ_LOG(3,(THIS_FILE, " Nb of answer RR: %d", res->hdr.anscount)); PJ_LOG(3,(THIS_FILE, " Nb of authority RR: %d", res->hdr.nscount)); @@ -152,42 +151,42 @@ PJ_DEF(void) pj_dns_dump_packet(const pj_dns_parsed_packet *res) /* Dump queries */ if (res->hdr.qdcount) { - PJ_LOG(3,(THIS_FILE, " Queries:")); + PJ_LOG(3,(THIS_FILE, " Queries:")); - for (i=0; ihdr.qdcount; ++i) { - dump_query(i, &res->q[i]); - } - PJ_LOG(3,(THIS_FILE, "")); + for (i=0; ihdr.qdcount; ++i) { + dump_query(i, &res->q[i]); + } + PJ_LOG(3,(THIS_FILE, "")); } /* Dump answers */ if (res->hdr.anscount) { - PJ_LOG(3,(THIS_FILE, " Answers RR:")); + PJ_LOG(3,(THIS_FILE, " Answers RR:")); - for (i=0; ihdr.anscount; ++i) { - dump_answer(i, &res->ans[i]); - } - PJ_LOG(3,(THIS_FILE, "")); + for (i=0; ihdr.anscount; ++i) { + dump_answer(i, &res->ans[i]); + } + PJ_LOG(3,(THIS_FILE, "")); } /* Dump NS sections */ if (res->hdr.nscount) { - PJ_LOG(3,(THIS_FILE, " NS Authority RR:")); + PJ_LOG(3,(THIS_FILE, " NS Authority RR:")); - for (i=0; ihdr.nscount; ++i) { - dump_answer(i, &res->ns[i]); - } - PJ_LOG(3,(THIS_FILE, "")); + for (i=0; ihdr.nscount; ++i) { + dump_answer(i, &res->ns[i]); + } + PJ_LOG(3,(THIS_FILE, "")); } /* Dump Additional info sections */ if (res->hdr.arcount) { - PJ_LOG(3,(THIS_FILE, " Additional Info RR:")); + PJ_LOG(3,(THIS_FILE, " Additional Info RR:")); - for (i=0; ihdr.arcount; ++i) { - dump_answer(i, &res->arr[i]); - } - PJ_LOG(3,(THIS_FILE, "")); + for (i=0; ihdr.arcount; ++i) { + dump_answer(i, &res->arr[i]); + } + PJ_LOG(3,(THIS_FILE, "")); } } diff --git a/pjlib-util/src/pjlib-util/dns_server.c b/pjlib-util/src/pjlib-util/dns_server.c index 5f6e8a2d98..9e8feeac97 100644 --- a/pjlib-util/src/pjlib-util/dns_server.c +++ b/pjlib-util/src/pjlib-util/dns_server.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,8 +26,8 @@ #include #define THIS_FILE "dns_server.c" -#define MAX_ANS 16 -#define MAX_PKT 1500 +#define MAX_ANS 16 +#define MAX_PKT 1500 #define MAX_LABEL 32 struct label_tab @@ -36,42 +35,42 @@ struct label_tab unsigned count; struct { - unsigned pos; - pj_str_t label; + unsigned pos; + pj_str_t label; } a[MAX_LABEL]; }; struct rr { PJ_DECL_LIST_MEMBER(struct rr); - pj_dns_parsed_rr rec; + pj_dns_parsed_rr rec; }; struct pj_dns_server { - pj_pool_t *pool; - pj_pool_factory *pf; - pj_activesock_t *asock; - pj_ioqueue_op_key_t send_key; - struct rr rr_list; + pj_pool_t *pool; + pj_pool_factory *pf; + pj_activesock_t *asock; + pj_ioqueue_op_key_t send_key; + struct rr rr_list; }; static pj_bool_t on_data_recvfrom(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status); + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status); PJ_DEF(pj_status_t) pj_dns_server_create( pj_pool_factory *pf, - pj_ioqueue_t *ioqueue, - int af, - unsigned port, - unsigned flags, - pj_dns_server **p_srv) + pj_ioqueue_t *ioqueue, + int af, + unsigned port, + unsigned flags, + pj_dns_server **p_srv) { pj_pool_t *pool; pj_dns_server *srv; @@ -96,15 +95,15 @@ PJ_DEF(pj_status_t) pj_dns_server_create( pj_pool_factory *pf, sock_cb.on_data_recvfrom = &on_data_recvfrom; status = pj_activesock_create_udp(pool, &sock_addr, NULL, ioqueue, - &sock_cb, srv, &srv->asock, NULL); + &sock_cb, srv, &srv->asock, NULL); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; pj_ioqueue_op_key_init(&srv->send_key, sizeof(srv->send_key)); status = pj_activesock_start_recvfrom(srv->asock, pool, MAX_PKT, 0); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; *p_srv = srv; return PJ_SUCCESS; @@ -120,8 +119,8 @@ PJ_DEF(pj_status_t) pj_dns_server_destroy(pj_dns_server *srv) PJ_ASSERT_RETURN(srv, PJ_EINVAL); if (srv->asock) { - pj_activesock_close(srv->asock); - srv->asock = NULL; + pj_activesock_close(srv->asock); + srv->asock = NULL; } pj_pool_safe_release(&srv->pool); @@ -131,20 +130,20 @@ PJ_DEF(pj_status_t) pj_dns_server_destroy(pj_dns_server *srv) static struct rr* find_rr( pj_dns_server *srv, - unsigned dns_class, - unsigned type /* pj_dns_type */, - const pj_str_t *name) + unsigned dns_class, + unsigned type /* pj_dns_type */, + const pj_str_t *name) { struct rr *r; r = srv->rr_list.next; while (r != &srv->rr_list) { - if (r->rec.dnsclass == dns_class && r->rec.type == type && - pj_stricmp(&r->rec.name, name)==0) - { - return r; - } - r = r->next; + if (r->rec.dnsclass == dns_class && r->rec.type == type && + pj_stricmp(&r->rec.name, name)==0) + { + return r; + } + r = r->next; } return NULL; @@ -152,24 +151,24 @@ static struct rr* find_rr( pj_dns_server *srv, PJ_DEF(pj_status_t) pj_dns_server_add_rec( pj_dns_server *srv, - unsigned count, - const pj_dns_parsed_rr rr_param[]) + unsigned count, + const pj_dns_parsed_rr rr_param[]) { unsigned i; PJ_ASSERT_RETURN(srv && count && rr_param, PJ_EINVAL); for (i=0; ipool, struct rr); - pj_memcpy(&rr->rec, &rr_param[i], sizeof(pj_dns_parsed_rr)); + rr = (struct rr*) PJ_POOL_ZALLOC_T(srv->pool, struct rr); + pj_memcpy(&rr->rec, &rr_param[i], sizeof(pj_dns_parsed_rr)); - pj_list_push_back(&srv->rr_list, rr); + pj_list_push_back(&srv->rr_list, rr); } return PJ_SUCCESS; @@ -177,9 +176,9 @@ PJ_DEF(pj_status_t) pj_dns_server_add_rec( pj_dns_server *srv, PJ_DEF(pj_status_t) pj_dns_server_del_rec( pj_dns_server *srv, - int dns_class, - pj_dns_type type, - const pj_str_t *name) + int dns_class, + pj_dns_type type, + const pj_str_t *name) { struct rr *rr; @@ -187,7 +186,7 @@ PJ_DEF(pj_status_t) pj_dns_server_del_rec( pj_dns_server *srv, rr = find_rr(srv, dns_class, type, name); if (!rr) - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; pj_list_erase(rr); @@ -208,8 +207,8 @@ static void write32(pj_uint8_t *p, pj_uint32_t val) } static int print_name(pj_uint8_t *pkt, int size, - pj_uint8_t *pos, const pj_str_t *name, - struct label_tab *tab) + pj_uint8_t *pos, const pj_str_t *name, + struct label_tab *tab) { pj_uint8_t *p = pos; const char *endlabel, *endname; @@ -218,20 +217,20 @@ static int print_name(pj_uint8_t *pkt, int size, /* Check if name is in the table */ for (i=0; icount; ++i) { - if (pj_strcmp(&tab->a[i].label, name)==0) - break; + if (pj_strcmp(&tab->a[i].label, name)==0) + break; } if (i != tab->count) { - write16(p, (pj_uint16_t)(tab->a[i].pos | (0xc0 << 8))); - return 2; + write16(p, (pj_uint16_t)(tab->a[i].pos | (0xc0 << 8))); + return 2; } else { - if (tab->count < MAX_LABEL) { - tab->a[tab->count].pos = (unsigned)(p-pkt); - tab->a[tab->count].label.ptr = (char*)(p+1); - tab->a[tab->count].label.slen = name->slen; - ++tab->count; - } + if (tab->count < MAX_LABEL) { + tab->a[tab->count].pos = (unsigned)(p-pkt); + tab->a[tab->count].label.ptr = (char*)(p+1); + tab->a[tab->count].label.slen = name->slen; + ++tab->count; + } } endlabel = name->ptr; @@ -241,27 +240,27 @@ static int print_name(pj_uint8_t *pkt, int size, while (endlabel != endname) { - while (endlabel != endname && *endlabel != '.') - ++endlabel; + while (endlabel != endname && *endlabel != '.') + ++endlabel; - label.slen = (endlabel - label.ptr); + label.slen = (endlabel - label.ptr); - if (size < label.slen+1) - return -1; + if (size < label.slen+1) + return -1; - *p = (pj_uint8_t)label.slen; - pj_memcpy(p+1, label.ptr, label.slen); + *p = (pj_uint8_t)label.slen; + pj_memcpy(p+1, label.ptr, label.slen); - size -= (int)(label.slen+1); - p += (label.slen+1); + size -= (int)(label.slen+1); + p += (label.slen+1); - if (endlabel != endname && *endlabel == '.') - ++endlabel; - label.ptr = (char*)endlabel; + if (endlabel != endname && *endlabel == '.') + ++endlabel; + label.ptr = (char*)endlabel; } if (size == 0) - return -1; + return -1; *p++ = '\0'; @@ -269,104 +268,104 @@ static int print_name(pj_uint8_t *pkt, int size, } static int print_rr(pj_uint8_t *pkt, int size, pj_uint8_t *pos, - const pj_dns_parsed_rr *rr, struct label_tab *tab) + const pj_dns_parsed_rr *rr, struct label_tab *tab) { pj_uint8_t *p = pos; int len; len = print_name(pkt, size, pos, &rr->name, tab); if (len < 0) - return -1; + return -1; p += len; size -= len; if (size < 8) - return -1; + return -1; pj_assert(rr->dnsclass == 1); - write16(p+0, (pj_uint16_t)rr->type); /* type */ - write16(p+2, (pj_uint16_t)rr->dnsclass); /* class */ - write32(p+4, rr->ttl); /* TTL */ + write16(p+0, (pj_uint16_t)rr->type); /* type */ + write16(p+2, (pj_uint16_t)rr->dnsclass); /* class */ + write32(p+4, rr->ttl); /* TTL */ p += 8; size -= 8; if (rr->type == PJ_DNS_TYPE_A) { - if (size < 6) - return -1; + if (size < 6) + return -1; - /* RDLEN is 4 */ - write16(p, 4); + /* RDLEN is 4 */ + write16(p, 4); - /* Address */ - pj_memcpy(p+2, &rr->rdata.a.ip_addr, 4); + /* Address */ + pj_memcpy(p+2, &rr->rdata.a.ip_addr, 4); - p += 6; - size -= 6; + p += 6; + size -= 6; } else if (rr->type == PJ_DNS_TYPE_AAAA) { - if (size < 18) - return -1; + if (size < 18) + return -1; - /* RDLEN is 16 */ - write16(p, 16); + /* RDLEN is 16 */ + write16(p, 16); - /* Address */ - pj_memcpy(p+2, &rr->rdata.aaaa.ip_addr, 16); + /* Address */ + pj_memcpy(p+2, &rr->rdata.aaaa.ip_addr, 16); - p += 18; - size -= 18; + p += 18; + size -= 18; } else if (rr->type == PJ_DNS_TYPE_CNAME || - rr->type == PJ_DNS_TYPE_NS || - rr->type == PJ_DNS_TYPE_PTR) { + rr->type == PJ_DNS_TYPE_NS || + rr->type == PJ_DNS_TYPE_PTR) { - if (size < 4) - return -1; + if (size < 4) + return -1; - len = print_name(pkt, size-2, p+2, &rr->rdata.cname.name, tab); - if (len < 0) - return -1; + len = print_name(pkt, size-2, p+2, &rr->rdata.cname.name, tab); + if (len < 0) + return -1; - write16(p, (pj_uint16_t)len); + write16(p, (pj_uint16_t)len); - p += (len + 2); - size -= (len + 2); + p += (len + 2); + size -= (len + 2); } else if (rr->type == PJ_DNS_TYPE_SRV) { - if (size < 10) - return -1; + if (size < 10) + return -1; - write16(p+2, rr->rdata.srv.prio); /* Priority */ - write16(p+4, rr->rdata.srv.weight); /* Weight */ - write16(p+6, rr->rdata.srv.port); /* Port */ + write16(p+2, rr->rdata.srv.prio); /* Priority */ + write16(p+4, rr->rdata.srv.weight); /* Weight */ + write16(p+6, rr->rdata.srv.port); /* Port */ - /* Target */ - len = print_name(pkt, size-8, p+8, &rr->rdata.srv.target, tab); - if (len < 0) - return -1; + /* Target */ + len = print_name(pkt, size-8, p+8, &rr->rdata.srv.target, tab); + if (len < 0) + return -1; - /* RDLEN */ - write16(p, (pj_uint16_t)(len + 6)); + /* RDLEN */ + write16(p, (pj_uint16_t)(len + 6)); - p += (len + 8); - size -= (len + 8); + p += (len + 8); + size -= (len + 8); } else { - pj_assert(!"Not supported"); - return -1; + pj_assert(!"Not supported"); + return -1; } return (int)(p-pos); } static int print_packet(const pj_dns_parsed_packet *rec, pj_uint8_t *pkt, - int size) + int size) { pj_uint8_t *p = pkt; struct label_tab tab; @@ -376,7 +375,7 @@ static int print_packet(const pj_dns_parsed_packet *rec, pj_uint8_t *pkt, pj_assert(sizeof(pj_dns_hdr)==12); if (size < (int)sizeof(pj_dns_hdr)) - return -1; + return -1; /* Initialize header */ write16(p+0, rec->hdr.id); @@ -392,54 +391,54 @@ static int print_packet(const pj_dns_parsed_packet *rec, pj_uint8_t *pkt, /* Print queries */ for (i=0; ihdr.qdcount; ++i) { - len = print_name(pkt, size, p, &rec->q[i].name, &tab); - if (len < 0) - return -1; + len = print_name(pkt, size, p, &rec->q[i].name, &tab); + if (len < 0) + return -1; - p += len; - size -= len; + p += len; + size -= len; - if (size < 4) - return -1; + if (size < 4) + return -1; - /* Set type */ - write16(p+0, (pj_uint16_t)rec->q[i].type); + /* Set type */ + write16(p+0, (pj_uint16_t)rec->q[i].type); - /* Set class (IN=1) */ - pj_assert(rec->q[i].dnsclass == 1); - write16(p+2, rec->q[i].dnsclass); + /* Set class (IN=1) */ + pj_assert(rec->q[i].dnsclass == 1); + write16(p+2, rec->q[i].dnsclass); - p += 4; + p += 4; } /* Print answers */ for (i=0; ihdr.anscount; ++i) { - len = print_rr(pkt, size, p, &rec->ans[i], &tab); - if (len < 0) - return -1; + len = print_rr(pkt, size, p, &rec->ans[i], &tab); + if (len < 0) + return -1; - p += len; - size -= len; + p += len; + size -= len; } /* Print NS records */ for (i=0; ihdr.nscount; ++i) { - len = print_rr(pkt, size, p, &rec->ns[i], &tab); - if (len < 0) - return -1; + len = print_rr(pkt, size, p, &rec->ns[i], &tab); + if (len < 0) + return -1; - p += len; - size -= len; + p += len; + size -= len; } /* Print additional records */ for (i=0; ihdr.arcount; ++i) { - len = print_rr(pkt, size, p, &rec->arr[i], &tab); - if (len < 0) - return -1; + len = print_rr(pkt, size, p, &rec->arr[i], &tab); + if (len < 0) + return -1; - p += len; - size -= len; + p += len; + size -= len; } return (int)(p - pkt); @@ -447,11 +446,11 @@ static int print_packet(const pj_dns_parsed_packet *rec, pj_uint8_t *pkt, static pj_bool_t on_data_recvfrom(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status) + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status) { pj_dns_server *srv; pj_pool_t *pool; @@ -462,18 +461,18 @@ static pj_bool_t on_data_recvfrom(pj_activesock_t *asock, unsigned i; if (status != PJ_SUCCESS) - return PJ_TRUE; + return PJ_TRUE; srv = (pj_dns_server*) pj_activesock_get_user_data(asock); pool = pj_pool_create(srv->pf, "dnssrvrx", 512, 256, NULL); status = pj_dns_parse_packet(pool, data, (unsigned)size, &req); if (status != PJ_SUCCESS) { - char addrinfo[PJ_INET6_ADDRSTRLEN+10]; - pj_sockaddr_print(src_addr, addrinfo, sizeof(addrinfo), 3); - PJ_PERROR(4,(THIS_FILE, status, "Error parsing query from %s", - addrinfo)); - goto on_return; + char addrinfo[PJ_INET6_ADDRSTRLEN+10]; + pj_sockaddr_print(src_addr, addrinfo, sizeof(addrinfo), 3); + PJ_PERROR(4,(THIS_FILE, status, "Error parsing query from %s", + addrinfo)); + goto on_return; } /* Init answer */ @@ -484,78 +483,78 @@ static pj_bool_t on_data_recvfrom(pj_activesock_t *asock, pj_memcpy(ans.q, req->q, sizeof(pj_dns_parsed_query)); if (req->hdr.qdcount != 1) { - ans.hdr.flags = PJ_DNS_SET_RCODE(PJ_DNS_RCODE_FORMERR); - goto send_pkt; + ans.hdr.flags = PJ_DNS_SET_RCODE(PJ_DNS_RCODE_FORMERR); + goto send_pkt; } if (req->q[0].dnsclass != PJ_DNS_CLASS_IN) { - ans.hdr.flags = PJ_DNS_SET_RCODE(PJ_DNS_RCODE_NOTIMPL); - goto send_pkt; + ans.hdr.flags = PJ_DNS_SET_RCODE(PJ_DNS_RCODE_NOTIMPL); + goto send_pkt; } /* Find the record */ rr = find_rr(srv, req->q->dnsclass, req->q->type, &req->q->name); if (rr == NULL) { - ans.hdr.flags = PJ_DNS_SET_RCODE(PJ_DNS_RCODE_NXDOMAIN); - goto send_pkt; + ans.hdr.flags = PJ_DNS_SET_RCODE(PJ_DNS_RCODE_NXDOMAIN); + goto send_pkt; } /* Init answer record */ ans.hdr.anscount = 0; ans.ans = (pj_dns_parsed_rr*) - pj_pool_calloc(pool, MAX_ANS, sizeof(pj_dns_parsed_rr)); + pj_pool_calloc(pool, MAX_ANS, sizeof(pj_dns_parsed_rr)); /* DNS SRV query needs special treatment since it returns multiple * records */ if (req->q->type == PJ_DNS_TYPE_SRV) { - struct rr *r; - - r = srv->rr_list.next; - while (r != &srv->rr_list) { - if (r->rec.dnsclass == req->q->dnsclass && - r->rec.type == PJ_DNS_TYPE_SRV && - pj_stricmp(&r->rec.name, &req->q->name)==0 && - ans.hdr.anscount < MAX_ANS) - { - pj_memcpy(&ans.ans[ans.hdr.anscount], &r->rec, - sizeof(pj_dns_parsed_rr)); - ++ans.hdr.anscount; - } - r = r->next; - } + struct rr *r; + + r = srv->rr_list.next; + while (r != &srv->rr_list) { + if (r->rec.dnsclass == req->q->dnsclass && + r->rec.type == PJ_DNS_TYPE_SRV && + pj_stricmp(&r->rec.name, &req->q->name)==0 && + ans.hdr.anscount < MAX_ANS) + { + pj_memcpy(&ans.ans[ans.hdr.anscount], &r->rec, + sizeof(pj_dns_parsed_rr)); + ++ans.hdr.anscount; + } + r = r->next; + } } else { - /* Otherwise just copy directly from the server record */ - pj_memcpy(&ans.ans[ans.hdr.anscount], &rr->rec, - sizeof(pj_dns_parsed_rr)); - ++ans.hdr.anscount; + /* Otherwise just copy directly from the server record */ + pj_memcpy(&ans.ans[ans.hdr.anscount], &rr->rec, + sizeof(pj_dns_parsed_rr)); + ++ans.hdr.anscount; } /* For each CNAME entry, add A entry */ for (i=0; irec, - sizeof(pj_dns_parsed_rr)); - ++ans.hdr.anscount; - } + if (ans.ans[i].type == PJ_DNS_TYPE_CNAME) { + struct rr *r; + + r = find_rr(srv, ans.ans[i].dnsclass, PJ_DNS_TYPE_A, + &ans.ans[i].name); + pj_memcpy(&ans.ans[ans.hdr.anscount], &r->rec, + sizeof(pj_dns_parsed_rr)); + ++ans.hdr.anscount; + } } send_pkt: pkt_len = print_packet(&ans, (pj_uint8_t*)data, MAX_PKT); if (pkt_len < 1) { - PJ_LOG(4,(THIS_FILE, "Error: answer too large")); - goto on_return; + PJ_LOG(4,(THIS_FILE, "Error: answer too large")); + goto on_return; } status = pj_activesock_sendto(srv->asock, &srv->send_key, data, &pkt_len, - 0, src_addr, addr_len); + 0, src_addr, addr_len); if (status != PJ_SUCCESS && status != PJ_EPENDING) { - PJ_PERROR(4,(THIS_FILE, status, "Error sending answer")); - goto on_return; + PJ_PERROR(4,(THIS_FILE, status, "Error sending answer")); + goto on_return; } on_return: diff --git a/pjlib-util/src/pjlib-util/errno.c b/pjlib-util/src/pjlib-util/errno.c index d5bccd3372..b5590c5a7c 100644 --- a/pjlib-util/src/pjlib-util/errno.c +++ b/pjlib-util/src/pjlib-util/errno.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,141 +35,141 @@ static const struct } err_str[] = { /* STUN errors */ - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNRESOLVE, "Unable to resolve STUN server" ), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINMSGTYPE, "Unknown STUN message type" ), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINMSGLEN, "Invalid STUN message length" ), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINATTRLEN, "STUN attribute length error" ), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINATTRTYPE, "Invalid STUN attribute type" ), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNININDEX, "Invalid STUN server/socket index" ), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOBINDRES, "No STUN binding response in the message" ), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNRECVERRATTR, "Received STUN error attribute" ), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOMAP, "No STUN mapped address attribute" ), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOTRESPOND, "Received no response from STUN server" ), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNSYMMETRIC, "Symetric NAT detected by STUN" ), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNRESOLVE, "Unable to resolve STUN server" ), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINMSGTYPE, "Unknown STUN message type" ), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINMSGLEN, "Invalid STUN message length" ), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINATTRLEN, "STUN attribute length error" ), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINATTRTYPE, "Invalid STUN attribute type" ), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNININDEX, "Invalid STUN server/socket index" ), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOBINDRES, "No STUN binding response in the message" ), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNRECVERRATTR, "Received STUN error attribute" ), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOMAP, "No STUN mapped address attribute" ), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOTRESPOND, "Received no response from STUN server" ), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNSYMMETRIC, "Symetric NAT detected by STUN" ), /* XML errors */ - PJ_BUILD_ERR( PJLIB_UTIL_EINXML, "Invalid XML message" ), + PJ_BUILD_ERR( PJLIB_UTIL_EINXML, "Invalid XML message" ), /* JSON errors */ - PJ_BUILD_ERR( PJLIB_UTIL_EINJSON, "Invalid JSON document" ), + PJ_BUILD_ERR( PJLIB_UTIL_EINJSON, "Invalid JSON document" ), /* DNS errors */ - PJ_BUILD_ERR( PJLIB_UTIL_EDNSQRYTOOSMALL, "DNS query packet buffer is too small"), - PJ_BUILD_ERR( PJLIB_UTIL_EDNSINSIZE, "Invalid DNS packet length"), - PJ_BUILD_ERR( PJLIB_UTIL_EDNSINCLASS, "Invalid DNS class"), - PJ_BUILD_ERR( PJLIB_UTIL_EDNSINNAMEPTR, "Invalid DNS name pointer"), - PJ_BUILD_ERR( PJLIB_UTIL_EDNSINNSADDR, "Invalid DNS nameserver address"), - PJ_BUILD_ERR( PJLIB_UTIL_EDNSNONS, "No nameserver is in DNS resolver"), - PJ_BUILD_ERR( PJLIB_UTIL_EDNSNOWORKINGNS, "No working DNS nameserver"), - PJ_BUILD_ERR( PJLIB_UTIL_EDNSNOANSWERREC, "No answer record in the DNS response"), - PJ_BUILD_ERR( PJLIB_UTIL_EDNSINANSWER, "Invalid DNS answer"), - - PJ_BUILD_ERR( PJLIB_UTIL_EDNS_FORMERR, "DNS \"Format error\""), - PJ_BUILD_ERR( PJLIB_UTIL_EDNS_SERVFAIL, "DNS \"Server failure\""), - PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NXDOMAIN, "DNS \"Name Error\""), - PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NOTIMPL, "DNS \"Not Implemented\""), - PJ_BUILD_ERR( PJLIB_UTIL_EDNS_REFUSED, "DNS \"Refused\""), - PJ_BUILD_ERR( PJLIB_UTIL_EDNS_YXDOMAIN, "DNS \"The name exists\""), - PJ_BUILD_ERR( PJLIB_UTIL_EDNS_YXRRSET, "DNS \"The RRset (name, type) exists\""), - PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NXRRSET, "DNS \"The RRset (name, type) does not exist\""), - PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NOTAUTH, "DNS \"Not authorized\""), - PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NOTZONE, "DNS \"The zone specified is not a zone\""), + PJ_BUILD_ERR( PJLIB_UTIL_EDNSQRYTOOSMALL, "DNS query packet buffer is too small"), + PJ_BUILD_ERR( PJLIB_UTIL_EDNSINSIZE, "Invalid DNS packet length"), + PJ_BUILD_ERR( PJLIB_UTIL_EDNSINCLASS, "Invalid DNS class"), + PJ_BUILD_ERR( PJLIB_UTIL_EDNSINNAMEPTR, "Invalid DNS name pointer"), + PJ_BUILD_ERR( PJLIB_UTIL_EDNSINNSADDR, "Invalid DNS nameserver address"), + PJ_BUILD_ERR( PJLIB_UTIL_EDNSNONS, "No nameserver is in DNS resolver"), + PJ_BUILD_ERR( PJLIB_UTIL_EDNSNOWORKINGNS, "No working DNS nameserver"), + PJ_BUILD_ERR( PJLIB_UTIL_EDNSNOANSWERREC, "No answer record in the DNS response"), + PJ_BUILD_ERR( PJLIB_UTIL_EDNSINANSWER, "Invalid DNS answer"), + + PJ_BUILD_ERR( PJLIB_UTIL_EDNS_FORMERR, "DNS \"Format error\""), + PJ_BUILD_ERR( PJLIB_UTIL_EDNS_SERVFAIL, "DNS \"Server failure\""), + PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NXDOMAIN, "DNS \"Name Error\""), + PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NOTIMPL, "DNS \"Not Implemented\""), + PJ_BUILD_ERR( PJLIB_UTIL_EDNS_REFUSED, "DNS \"Refused\""), + PJ_BUILD_ERR( PJLIB_UTIL_EDNS_YXDOMAIN, "DNS \"The name exists\""), + PJ_BUILD_ERR( PJLIB_UTIL_EDNS_YXRRSET, "DNS \"The RRset (name, type) exists\""), + PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NXRRSET, "DNS \"The RRset (name, type) does not exist\""), + PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NOTAUTH, "DNS \"Not authorized\""), + PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NOTZONE, "DNS \"The zone specified is not a zone\""), /* STUN */ - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNTOOMANYATTR, "Too many STUN attributes"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNUNKNOWNATTR, "Unknown STUN attribute"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINADDRLEN, "Invalid STUN socket address length"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNIPV6NOTSUPP, "STUN IPv6 attribute not supported"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOTRESPONSE, "Expecting STUN response message"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINVALIDID, "STUN transaction ID mismatch"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOHANDLER, "Unable to find STUN handler for the request"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNMSGINTPOS, "Found non-FINGERPRINT attr. after MESSAGE-INTEGRITY"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNFINGERPOS, "Found STUN attribute after FINGERPRINT"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOUSERNAME, "Missing STUN USERNAME attribute"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNMSGINT, "Missing/invalid STUN MESSAGE-INTEGRITY attribute"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNDUPATTR, "Found duplicate STUN attribute"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOREALM, "Missing STUN REALM attribute"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNONCE, "Missing/stale STUN NONCE attribute value"), - PJ_BUILD_ERR( PJLIB_UTIL_ESTUNTSXFAILED, "STUN transaction terminates with failure"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNTOOMANYATTR, "Too many STUN attributes"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNUNKNOWNATTR, "Unknown STUN attribute"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINADDRLEN, "Invalid STUN socket address length"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNIPV6NOTSUPP, "STUN IPv6 attribute not supported"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOTRESPONSE, "Expecting STUN response message"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINVALIDID, "STUN transaction ID mismatch"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOHANDLER, "Unable to find STUN handler for the request"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNMSGINTPOS, "Found non-FINGERPRINT attr. after MESSAGE-INTEGRITY"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNFINGERPOS, "Found STUN attribute after FINGERPRINT"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOUSERNAME, "Missing STUN USERNAME attribute"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNMSGINT, "Missing/invalid STUN MESSAGE-INTEGRITY attribute"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNDUPATTR, "Found duplicate STUN attribute"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOREALM, "Missing STUN REALM attribute"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNONCE, "Missing/stale STUN NONCE attribute value"), + PJ_BUILD_ERR( PJLIB_UTIL_ESTUNTSXFAILED, "STUN transaction terminates with failure"), /* HTTP Client */ - PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINURL, "Invalid URL format"), - PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINPORT, "Invalid URL port number"), - PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINCHDR, "Incomplete response header received"), - PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINSBUF, "Insufficient buffer"), - PJ_BUILD_ERR( PJLIB_UTIL_EHTTPLOST, "Connection lost"), + PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINURL, "Invalid URL format"), + PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINPORT, "Invalid URL port number"), + PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINCHDR, "Incomplete response header received"), + PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINSBUF, "Insufficient buffer"), + PJ_BUILD_ERR( PJLIB_UTIL_EHTTPLOST, "Connection lost"), /* CLI */ - PJ_BUILD_ERR( PJ_CLI_EEXIT, "Exit current session"), - PJ_BUILD_ERR( PJ_CLI_EMISSINGARG, "Missing argument"), - PJ_BUILD_ERR( PJ_CLI_ETOOMANYARGS, "Too many arguments"), - PJ_BUILD_ERR( PJ_CLI_EINVARG, "Invalid argument"), - PJ_BUILD_ERR( PJ_CLI_EBADNAME, "Command name already exists"), - PJ_BUILD_ERR( PJ_CLI_EBADID, "Command id already exists"), - PJ_BUILD_ERR( PJ_CLI_EBADXML, "Invalid XML format"), - PJ_BUILD_ERR( PJ_CLI_ETELNETLOST, "Connection lost"), + PJ_BUILD_ERR( PJ_CLI_EEXIT, "Exit current session"), + PJ_BUILD_ERR( PJ_CLI_EMISSINGARG, "Missing argument"), + PJ_BUILD_ERR( PJ_CLI_ETOOMANYARGS, "Too many arguments"), + PJ_BUILD_ERR( PJ_CLI_EINVARG, "Invalid argument"), + PJ_BUILD_ERR( PJ_CLI_EBADNAME, "Command name already exists"), + PJ_BUILD_ERR( PJ_CLI_EBADID, "Command id already exists"), + PJ_BUILD_ERR( PJ_CLI_EBADXML, "Invalid XML format"), + PJ_BUILD_ERR( PJ_CLI_ETELNETLOST, "Connection lost"), }; -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ /* * pjlib_util_strerror() */ pj_str_t pjlib_util_strerror(pj_status_t statcode, - char *buf, pj_size_t bufsize ) + char *buf, pj_size_t bufsize ) { pj_str_t errstr; #if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0) if (statcode >= PJLIB_UTIL_ERRNO_START && - statcode < PJLIB_UTIL_ERRNO_START + PJ_ERRNO_SPACE_SIZE) + statcode < PJLIB_UTIL_ERRNO_START + PJ_ERRNO_SPACE_SIZE) { - /* Find the error in the table. - * Use binary search! - */ - int first = 0; - int n = PJ_ARRAY_SIZE(err_str); - - while (n > 0) { - int half = n/2; - int mid = first + half; - - if (err_str[mid].code < statcode) { - first = mid+1; - n -= (half+1); - } else if (err_str[mid].code > statcode) { - n = half; - } else { - first = mid; - break; - } - } - - - if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { - pj_str_t msg; - - msg.ptr = (char*)err_str[first].msg; - msg.slen = pj_ansi_strlen(err_str[first].msg); - - errstr.ptr = buf; - pj_strncpy_with_null(&errstr, &msg, bufsize); - return errstr; - - } + /* Find the error in the table. + * Use binary search! + */ + int first = 0; + int n = PJ_ARRAY_SIZE(err_str); + + while (n > 0) { + int half = n/2; + int mid = first + half; + + if (err_str[mid].code < statcode) { + first = mid+1; + n -= (half+1); + } else if (err_str[mid].code > statcode) { + n = half; + } else { + first = mid; + break; + } + } + + + if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { + pj_str_t msg; + + msg.ptr = (char*)err_str[first].msg; + msg.slen = pj_ansi_strlen(err_str[first].msg); + + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, &msg, bufsize); + return errstr; + + } } -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ /* Error not found. */ errstr.ptr = buf; errstr.slen = pj_ansi_snprintf(buf, bufsize, - "Unknown pjlib-util error %d", - statcode); + "Unknown pjlib-util error %d", + statcode); if (errstr.slen < 1 || errstr.slen >= (pj_ssize_t)bufsize) - errstr.slen = bufsize - 1; + errstr.slen = bufsize - 1; return errstr; } @@ -180,8 +179,8 @@ PJ_DEF(pj_status_t) pjlib_util_init(void) pj_status_t status; status = pj_register_strerror(PJLIB_UTIL_ERRNO_START, - PJ_ERRNO_SPACE_SIZE, - &pjlib_util_strerror); + PJ_ERRNO_SPACE_SIZE, + &pjlib_util_strerror); pj_assert(status == PJ_SUCCESS); return status; diff --git a/pjlib-util/src/pjlib-util/getopt.c b/pjlib-util/src/pjlib-util/getopt.c index 0a560f02d5..75cef24635 100644 --- a/pjlib-util/src/pjlib-util/getopt.c +++ b/pjlib-util/src/pjlib-util/getopt.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * pj_getopt entry points * @@ -11,9 +10,9 @@ /* Internal only. Users should not call this directly. */ static int _getopt_internal (int argc, char *const *argv, - const char *shortopts, - const struct pj_getopt_option *longopts, int *longind, - int long_only); + const char *shortopts, + const struct pj_getopt_option *longopts, int *longind, + int long_only); /* pj_getopt_long and pj_getopt_long_only entry points for GNU pj_getopt. Copyright (C) 1987,88,89,90,91,92,93,94,96,97 Free Software Foundation, Inc. @@ -48,7 +47,7 @@ int _getopt_internal (int argc, char *const *argv, int pj_getopt_long (int argc, char *const *argv, const char *options, - const struct pj_getopt_option *long_options, int *opt_index) + const struct pj_getopt_option *long_options, int *opt_index) { return _getopt_internal (argc, argv, options, long_options, opt_index, 0); } @@ -62,13 +61,13 @@ int pj_getopt (int argc, char * const * argv, const char * optstring) { return _getopt_internal (argc, argv, optstring, - (const struct pj_getopt_option *) 0, - (int *) 0, - 0); + (const struct pj_getopt_option *) 0, + (int *) 0, + 0); } -#define _(msgid) (msgid) +#define _(msgid) (msgid) /* This version of `pj_getopt' appears to the caller like standard Unix `pj_getopt' but it behaves differently for the user, since it allows the user @@ -171,7 +170,7 @@ my_index (const char *str, int chr) while (*str) { if (*str == chr) - return (char *) str; + return (char *) str; str++; } return 0; @@ -214,39 +213,39 @@ exchange (char **argv) while (top > middle && middle > bottom) { if (top - middle > middle - bottom) - { - /* Bottom segment is the short one. */ - int len = middle - bottom; - register int i; - - /* Swap it with the top part of the top segment. */ - for (i = 0; i < len; i++) - { - tem = argv[bottom + i]; - argv[bottom + i] = argv[top - (middle - bottom) + i]; - argv[top - (middle - bottom) + i] = tem; - SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); - } - /* Exclude the moved bottom segment from further swapping. */ - top -= len; - } + { + /* Bottom segment is the short one. */ + int len = middle - bottom; + register int i; + + /* Swap it with the top part of the top segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[top - (middle - bottom) + i]; + argv[top - (middle - bottom) + i] = tem; + SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); + } + /* Exclude the moved bottom segment from further swapping. */ + top -= len; + } else - { - /* Top segment is the short one. */ - int len = top - middle; - register int i; - - /* Swap it with the bottom part of the bottom segment. */ - for (i = 0; i < len; i++) - { - tem = argv[bottom + i]; - argv[bottom + i] = argv[middle + i]; - argv[middle + i] = tem; - SWAP_FLAGS (bottom + i, middle + i); - } - /* Exclude the moved top segment from further swapping. */ - bottom += len; - } + { + /* Top segment is the short one. */ + int len = top - middle; + register int i; + + /* Swap it with the bottom part of the bottom segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[middle + i]; + argv[middle + i] = tem; + SWAP_FLAGS (bottom + i, middle + i); + } + /* Exclude the moved top segment from further swapping. */ + bottom += len; + } } /* Update records for the slots the non-options now occupy. */ @@ -258,7 +257,7 @@ exchange (char **argv) /* Initialize the internal data when the first call is made. */ static const char *_getopt_initialize (int argc, char *const *argv, - const char *optstring) + const char *optstring) { PJ_UNUSED_ARG(argc); PJ_UNUSED_ARG(argv); @@ -352,15 +351,15 @@ static const char *_getopt_initialize (int argc, char *const *argv, static int _getopt_internal (int argc, char *const *argv, const char *optstring, - const struct pj_getopt_option *longopts, int *longind, - int long_only) + const struct pj_getopt_option *longopts, int *longind, + int long_only) { pj_optarg = NULL; if (pj_optind == 0 || !__getopt_initialized) { if (pj_optind == 0) - pj_optind = 1; /* Don't scan ARGV[0], the program name. */ + pj_optind = 1; /* Don't scan ARGV[0], the program name. */ optstring = _getopt_initialize (argc, argv, optstring); __getopt_initialized = 1; } @@ -376,76 +375,76 @@ _getopt_internal (int argc, char *const *argv, const char *optstring, /* Advance to the next ARGV-element. */ /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been - moved back by the user (who may also have changed the arguments). */ + moved back by the user (who may also have changed the arguments). */ if (last_nonopt > pj_optind) - last_nonopt = pj_optind; + last_nonopt = pj_optind; if (first_nonopt > pj_optind) - first_nonopt = pj_optind; + first_nonopt = pj_optind; if (ordering == PERMUTE) - { - /* If we have just processed some options following some non-options, - exchange them so that the options come first. */ + { + /* If we have just processed some options following some non-options, + exchange them so that the options come first. */ - if (first_nonopt != last_nonopt && last_nonopt != pj_optind) - exchange ((char **) argv); - else if (last_nonopt != pj_optind) - first_nonopt = pj_optind; + if (first_nonopt != last_nonopt && last_nonopt != pj_optind) + exchange ((char **) argv); + else if (last_nonopt != pj_optind) + first_nonopt = pj_optind; - /* Skip any additional non-options - and extend the range of non-options previously skipped. */ + /* Skip any additional non-options + and extend the range of non-options previously skipped. */ - while (pj_optind < argc && NONOPTION_P) - pj_optind++; - last_nonopt = pj_optind; - } + while (pj_optind < argc && NONOPTION_P) + pj_optind++; + last_nonopt = pj_optind; + } /* The special ARGV-element `--' means premature end of options. - Skip it like a null option, - then exchange with previous non-options as if it were an option, - then skip everything else like a non-option. */ + Skip it like a null option, + then exchange with previous non-options as if it were an option, + then skip everything else like a non-option. */ if (pj_optind != argc && !pj_ansi_strcmp(argv[pj_optind], "--")) - { - pj_optind++; + { + pj_optind++; - if (first_nonopt != last_nonopt && last_nonopt != pj_optind) - exchange ((char **) argv); - else if (first_nonopt == last_nonopt) - first_nonopt = pj_optind; - last_nonopt = argc; + if (first_nonopt != last_nonopt && last_nonopt != pj_optind) + exchange ((char **) argv); + else if (first_nonopt == last_nonopt) + first_nonopt = pj_optind; + last_nonopt = argc; - pj_optind = argc; - } + pj_optind = argc; + } /* If we have done all the ARGV-elements, stop the scan - and back over any non-options that we skipped and permuted. */ + and back over any non-options that we skipped and permuted. */ if (pj_optind == argc) - { - /* Set the next-arg-index to point at the non-options - that we previously skipped, so the caller will digest them. */ - if (first_nonopt != last_nonopt) - pj_optind = first_nonopt; - return -1; - } + { + /* Set the next-arg-index to point at the non-options + that we previously skipped, so the caller will digest them. */ + if (first_nonopt != last_nonopt) + pj_optind = first_nonopt; + return -1; + } /* If we have come to a non-option and did not permute it, - either stop the scan or describe it to the caller and pass it by. */ + either stop the scan or describe it to the caller and pass it by. */ if (NONOPTION_P) - { - if (ordering == REQUIRE_ORDER) - return -1; - pj_optarg = argv[pj_optind++]; - return 1; - } + { + if (ordering == REQUIRE_ORDER) + return -1; + pj_optarg = argv[pj_optind++]; + return 1; + } /* We have found another option-ARGV-element. - Skip the initial punctuation. */ + Skip the initial punctuation. */ nextchar = (argv[pj_optind] + 1 - + (longopts != NULL && argv[pj_optind][1] == '-')); + + (longopts != NULL && argv[pj_optind][1] == '-')); } /* Decode the current option-ARGV-element. */ @@ -465,7 +464,7 @@ _getopt_internal (int argc, char *const *argv, const char *optstring, if (longopts != NULL && (argv[pj_optind][1] == '-' - || (long_only && (argv[pj_optind][2] || !my_index (optstring, argv[pj_optind][1]))))) + || (long_only && (argv[pj_optind][2] || !my_index (optstring, argv[pj_optind][1]))))) { char *nameend; const struct pj_getopt_option *p; @@ -476,93 +475,93 @@ _getopt_internal (int argc, char *const *argv, const char *optstring, int option_index; for (nameend = nextchar; *nameend && *nameend != '='; nameend++) - /* Do nothing. */ ; + /* Do nothing. */ ; /* Test all long options for either exact match - or abbreviated matches. */ + or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) - if (!strncmp (p->name, nextchar, nameend - nextchar)) - { - if ((unsigned int) (nameend - nextchar) - == (unsigned int) strlen (p->name)) - { - /* Exact match found. */ - pfound = p; - indfound = option_index; - exact = 1; - break; - } - else if (pfound == NULL) - { - /* First nonexact match found. */ - pfound = p; - indfound = option_index; - } - else - /* Second or later nonexact match found. */ - ambig = 1; - } + if (!strncmp (p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int) (nameend - nextchar) + == (unsigned int) strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else + /* Second or later nonexact match found. */ + ambig = 1; + } if (ambig && !exact) - { - nextchar += strlen (nextchar); - pj_optind++; - pj_optopt = 0; - return '?'; - } + { + nextchar += strlen (nextchar); + pj_optind++; + pj_optopt = 0; + return '?'; + } if (pfound != NULL) - { - option_index = indfound; - pj_optind++; - if (*nameend) - { - /* Don't test has_arg with >, because some C compilers don't - allow it to be used on enums. */ - if (pfound->has_arg) - pj_optarg = nameend + 1; - else - { - nextchar += strlen (nextchar); - - pj_optopt = pfound->val; - return '?'; - } - } - else if (pfound->has_arg == 1) - { - if (pj_optind < argc) - pj_optarg = argv[pj_optind++]; - else - { - nextchar += strlen (nextchar); - pj_optopt = pfound->val; - return optstring[0] == ':' ? ':' : '?'; - } - } - nextchar += strlen (nextchar); - if (longind != NULL) - *longind = option_index; - if (pfound->flag) - { - *(pfound->flag) = pfound->val; - return 0; - } - return pfound->val; - } + { + option_index = indfound; + pj_optind++; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + pj_optarg = nameend + 1; + else + { + nextchar += strlen (nextchar); + + pj_optopt = pfound->val; + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (pj_optind < argc) + pj_optarg = argv[pj_optind++]; + else + { + nextchar += strlen (nextchar); + pj_optopt = pfound->val; + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen (nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } /* Can't find it as a long option. If this is not pj_getopt_long_only, - or the option starts with '--' or is not a valid short - option, then it's an error. - Otherwise interpret it as a short option. */ + or the option starts with '--' or is not a valid short + option, then it's an error. + Otherwise interpret it as a short option. */ if (!long_only || argv[pj_optind][1] == '-' - || my_index (optstring, *nextchar) == NULL) - { - nextchar = (char *) ""; - pj_optind++; - pj_optopt = 0; - return '?'; - } + || my_index (optstring, *nextchar) == NULL) + { + nextchar = (char *) ""; + pj_optind++; + pj_optopt = 0; + return '?'; + } } /* Look at and handle the next short option-character. */ @@ -577,153 +576,153 @@ _getopt_internal (int argc, char *const *argv, const char *optstring, if (temp == NULL || c == ':') { - pj_optopt = c; - return '?'; + pj_optopt = c; + return '?'; } /* Convenience. Treat POSIX -W foo same as long option --foo */ if (temp[0] == 'W' && temp[1] == ';') { - char *nameend; - const struct pj_getopt_option *p; - const struct pj_getopt_option *pfound = NULL; - int exact = 0; - int ambig = 0; - int indfound = 0; - int option_index; - - /* This is an option that requires an argument. */ - if (*nextchar != '\0') - { - pj_optarg = nextchar; - /* If we end this ARGV-element by taking the rest as an arg, - we must advance to the next element now. */ - pj_optind++; - } - else if (pj_optind == argc) - { - pj_optopt = c; - if (optstring[0] == ':') - c = ':'; - else - c = '?'; - return c; - } - else - /* We already incremented `pj_optind' once; - increment it again when taking next ARGV-elt as argument. */ - pj_optarg = argv[pj_optind++]; - - /* pj_optarg is now the argument, see if it's in the - table of longopts. */ - - for (nextchar = nameend = pj_optarg; *nameend && *nameend != '='; nameend++) - /* Do nothing. */ ; - - /* Test all long options for either exact match - or abbreviated matches. */ - for (p = longopts, option_index = 0; p->name; p++, option_index++) - if (!strncmp (p->name, nextchar, nameend - nextchar)) - { - if ((unsigned int) (nameend - nextchar) == strlen (p->name)) - { - /* Exact match found. */ - pfound = p; - indfound = option_index; - exact = 1; - break; - } - else if (pfound == NULL) - { - /* First nonexact match found. */ - pfound = p; - indfound = option_index; - } - else - /* Second or later nonexact match found. */ - ambig = 1; - } - if (ambig && !exact) - { - nextchar += strlen (nextchar); - pj_optind++; - return '?'; - } - if (pfound != NULL) - { - option_index = indfound; - if (*nameend) - { - /* Don't test has_arg with >, because some C compilers don't - allow it to be used on enums. */ - if (pfound->has_arg) - pj_optarg = nameend + 1; - else - { - nextchar += strlen (nextchar); - return '?'; - } - } - else if (pfound->has_arg == 1) - { - if (pj_optind < argc) - pj_optarg = argv[pj_optind++]; - else - { - nextchar += strlen (nextchar); - return optstring[0] == ':' ? ':' : '?'; - } - } - nextchar += strlen (nextchar); - if (longind != NULL) - *longind = option_index; - if (pfound->flag) - { - *(pfound->flag) = pfound->val; - return 0; - } - return pfound->val; - } - nextchar = NULL; - return 'W'; /* Let the application handle it. */ + char *nameend; + const struct pj_getopt_option *p; + const struct pj_getopt_option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = 0; + int option_index; + + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + pj_optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + pj_optind++; + } + else if (pj_optind == argc) + { + pj_optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + return c; + } + else + /* We already incremented `pj_optind' once; + increment it again when taking next ARGV-elt as argument. */ + pj_optarg = argv[pj_optind++]; + + /* pj_optarg is now the argument, see if it's in the + table of longopts. */ + + for (nextchar = nameend = pj_optarg; *nameend && *nameend != '='; nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int) (nameend - nextchar) == strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else + /* Second or later nonexact match found. */ + ambig = 1; + } + if (ambig && !exact) + { + nextchar += strlen (nextchar); + pj_optind++; + return '?'; + } + if (pfound != NULL) + { + option_index = indfound; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + pj_optarg = nameend + 1; + else + { + nextchar += strlen (nextchar); + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (pj_optind < argc) + pj_optarg = argv[pj_optind++]; + else + { + nextchar += strlen (nextchar); + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen (nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + nextchar = NULL; + return 'W'; /* Let the application handle it. */ } if (temp[1] == ':') { - if (temp[2] == ':') - { - /* This is an option that accepts an argument optionally. */ - if (*nextchar != '\0') - { - pj_optarg = nextchar; - pj_optind++; - } - else - pj_optarg = NULL; - nextchar = NULL; - } - else - { - /* This is an option that requires an argument. */ - if (*nextchar != '\0') - { - pj_optarg = nextchar; - /* If we end this ARGV-element by taking the rest as an arg, - we must advance to the next element now. */ - pj_optind++; - } - else if (pj_optind == argc) - { - pj_optopt = c; - if (optstring[0] == ':') - c = ':'; - else - c = '?'; - } - else - /* We already incremented `pj_optind' once; - increment it again when taking next ARGV-elt as argument. */ - pj_optarg = argv[pj_optind++]; - nextchar = NULL; - } + if (temp[2] == ':') + { + /* This is an option that accepts an argument optionally. */ + if (*nextchar != '\0') + { + pj_optarg = nextchar; + pj_optind++; + } + else + pj_optarg = NULL; + nextchar = NULL; + } + else + { + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + pj_optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + pj_optind++; + } + else if (pj_optind == argc) + { + pj_optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + } + else + /* We already incremented `pj_optind' once; + increment it again when taking next ARGV-elt as argument. */ + pj_optarg = argv[pj_optind++]; + nextchar = NULL; + } } return c; } diff --git a/pjlib-util/src/pjlib-util/hmac_md5.c b/pjlib-util/src/pjlib-util/hmac_md5.c index de0aa0e053..ae38f531b7 100644 --- a/pjlib-util/src/pjlib-util/hmac_md5.c +++ b/pjlib-util/src/pjlib-util/hmac_md5.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -22,7 +21,7 @@ PJ_DEF(void) pj_hmac_md5_init(pj_hmac_md5_context *hctx, - const pj_uint8_t *key, unsigned key_len) + const pj_uint8_t *key, unsigned key_len) { pj_uint8_t k_ipad[64]; pj_uint8_t tk[16]; @@ -64,14 +63,14 @@ PJ_DEF(void) pj_hmac_md5_init(pj_hmac_md5_context *hctx, } PJ_DEF(void) pj_hmac_md5_update(pj_hmac_md5_context *hctx, - const pj_uint8_t *input, - unsigned input_len) + const pj_uint8_t *input, + unsigned input_len) { pj_md5_update(&hctx->context, input, input_len); } PJ_DEF(void) pj_hmac_md5_final(pj_hmac_md5_context *hctx, - pj_uint8_t digest[16]) + pj_uint8_t digest[16]) { pj_md5_final(&hctx->context, digest); @@ -85,8 +84,8 @@ PJ_DEF(void) pj_hmac_md5_final(pj_hmac_md5_context *hctx, } PJ_DEF(void) pj_hmac_md5( const pj_uint8_t *input, unsigned input_len, - const pj_uint8_t *key, unsigned key_len, - pj_uint8_t digest[16] ) + const pj_uint8_t *key, unsigned key_len, + pj_uint8_t digest[16] ) { pj_hmac_md5_context ctx; diff --git a/pjlib-util/src/pjlib-util/hmac_sha1.c b/pjlib-util/src/pjlib-util/hmac_sha1.c index 4d91186b43..d3a007c2bf 100644 --- a/pjlib-util/src/pjlib-util/hmac_sha1.c +++ b/pjlib-util/src/pjlib-util/hmac_sha1.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -22,7 +21,7 @@ PJ_DEF(void) pj_hmac_sha1_init(pj_hmac_sha1_context *hctx, - const pj_uint8_t *key, unsigned key_len) + const pj_uint8_t *key, unsigned key_len) { pj_uint8_t k_ipad[64]; pj_uint8_t tk[20]; @@ -63,13 +62,13 @@ PJ_DEF(void) pj_hmac_sha1_init(pj_hmac_sha1_context *hctx, } PJ_DEF(void) pj_hmac_sha1_update(pj_hmac_sha1_context *hctx, - const pj_uint8_t *input, unsigned input_len) + const pj_uint8_t *input, unsigned input_len) { pj_sha1_update(&hctx->context, input, input_len); } PJ_DEF(void) pj_hmac_sha1_final(pj_hmac_sha1_context *hctx, - pj_uint8_t digest[20]) + pj_uint8_t digest[20]) { pj_sha1_final(&hctx->context, digest); @@ -83,8 +82,8 @@ PJ_DEF(void) pj_hmac_sha1_final(pj_hmac_sha1_context *hctx, } PJ_DEF(void) pj_hmac_sha1(const pj_uint8_t *input, unsigned input_len, - const pj_uint8_t *key, unsigned key_len, - pj_uint8_t digest[20] ) + const pj_uint8_t *key, unsigned key_len, + pj_uint8_t digest[20] ) { pj_hmac_sha1_context ctx; diff --git a/pjlib-util/src/pjlib-util/http_client.c b/pjlib-util/src/pjlib-util/http_client.c index b14ca50f0b..70e1221ee3 100644 --- a/pjlib-util/src/pjlib-util/http_client.c +++ b/pjlib-util/src/pjlib-util/http_client.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -37,7 +36,7 @@ #if 0 /* Enable some tracing */ - #define TRACE_(arg) PJ_LOG(3,arg) + #define TRACE_(arg) PJ_LOG(3,arg) #else #define TRACE_(arg) #endif @@ -102,9 +101,9 @@ enum http_state enum auth_state { - AUTH_NONE, /* Not authenticating */ - AUTH_RETRYING, /* New request with auth has been submitted */ - AUTH_DONE /* Done retrying the request with auth. */ + AUTH_NONE, /* Not authenticating */ + AUTH_RETRYING, /* New request with auth has been submitted */ + AUTH_DONE /* Done retrying the request with auth. */ }; struct pj_http_req @@ -121,11 +120,11 @@ struct pj_http_req pj_status_t error; /* Error status */ pj_str_t buffer; /* Buffer to send/receive msgs */ enum http_state state; /* State of the HTTP request */ - enum auth_state auth_state; /* Authentication state */ + enum auth_state auth_state; /* Authentication state */ pj_timer_entry timer_entry;/* Timer entry */ pj_bool_t resolved; /* Whether URL's host is resolved */ pj_http_resp response; /* HTTP response */ - pj_ioqueue_op_key_t op_key; + pj_ioqueue_op_key_t op_key; struct tcp_state { /* Total data sent so far if the data is sent in segments (i.e. @@ -159,7 +158,7 @@ static pj_status_t http_response_parse(pj_pool_t *pool, static void restart_req_with_auth(pj_http_req *hreq); /* Parse authentication challenge */ static pj_status_t parse_auth_chal(pj_pool_t *pool, pj_str_t *input, - pj_http_auth_chal *chal); + pj_http_auth_chal *chal); static pj_uint16_t get_http_default_port(const pj_str_t *protocol) { @@ -198,7 +197,7 @@ static void on_syntax_error(pj_scanner *scanner) /* Callback when connection is established to the server */ static pj_bool_t http_on_connect(pj_activesock_t *asock, - pj_status_t status) + pj_status_t status) { pj_http_req *hreq = (pj_http_req*) pj_activesock_get_user_data(asock); @@ -218,8 +217,8 @@ static pj_bool_t http_on_connect(pj_activesock_t *asock, } static pj_bool_t http_on_data_sent(pj_activesock_t *asock, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t sent) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t sent) { pj_http_req *hreq = (pj_http_req*) pj_activesock_get_user_data(asock); @@ -290,10 +289,10 @@ static pj_bool_t http_on_data_sent(pj_activesock_t *asock, } static pj_bool_t http_on_data_read(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { pj_http_req *hreq = (pj_http_req*) pj_activesock_get_user_data(asock); @@ -341,49 +340,49 @@ static pj_bool_t http_on_data_read(pj_activesock_t *asock, * Proxy-Authenticate header */ if (hreq->response.status_code == 401 || - hreq->response.status_code == 407) + hreq->response.status_code == 407) { - const pj_str_t STR_WWW_AUTH = { "WWW-Authenticate", 16 }; - const pj_str_t STR_PROXY_AUTH = { "Proxy-Authenticate", 18 }; - pj_http_resp *response = &hreq->response; - pj_http_headers *hdrs = &response->headers; - unsigned i; - - status = PJ_ENOTFOUND; - for (i = 0; i < hdrs->count; i++) { - if (!pj_stricmp(&hdrs->header[i].name, &STR_WWW_AUTH) || - !pj_stricmp(&hdrs->header[i].name, &STR_PROXY_AUTH)) - { - status = parse_auth_chal(hreq->pool, - &hdrs->header[i].value, - &response->auth_chal); - break; - } - } + const pj_str_t STR_WWW_AUTH = { "WWW-Authenticate", 16 }; + const pj_str_t STR_PROXY_AUTH = { "Proxy-Authenticate", 18 }; + pj_http_resp *response = &hreq->response; + pj_http_headers *hdrs = &response->headers; + unsigned i; + + status = PJ_ENOTFOUND; + for (i = 0; i < hdrs->count; i++) { + if (!pj_stricmp(&hdrs->header[i].name, &STR_WWW_AUTH) || + !pj_stricmp(&hdrs->header[i].name, &STR_PROXY_AUTH)) + { + status = parse_auth_chal(hreq->pool, + &hdrs->header[i].value, + &response->auth_chal); + break; + } + } /* Check if we should perform authentication */ if (status == PJ_SUCCESS && - hreq->auth_state == AUTH_NONE && - hreq->response.auth_chal.scheme.slen && - hreq->param.auth_cred.username.slen && - (hreq->param.auth_cred.scheme.slen == 0 || - !pj_stricmp(&hreq->response.auth_chal.scheme, - &hreq->param.auth_cred.scheme)) && - (hreq->param.auth_cred.realm.slen == 0 || - !pj_stricmp(&hreq->response.auth_chal.realm, - &hreq->param.auth_cred.realm)) - ) - { - /* Yes, authentication is required and we have been - * configured with credential. - */ - restart_req_with_auth(hreq); - if (hreq->auth_state == AUTH_RETRYING) { - /* We'll be resending the request with auth. This - * connection has been closed. - */ - return PJ_FALSE; - } + hreq->auth_state == AUTH_NONE && + hreq->response.auth_chal.scheme.slen && + hreq->param.auth_cred.username.slen && + (hreq->param.auth_cred.scheme.slen == 0 || + !pj_stricmp(&hreq->response.auth_chal.scheme, + &hreq->param.auth_cred.scheme)) && + (hreq->param.auth_cred.realm.slen == 0 || + !pj_stricmp(&hreq->response.auth_chal.realm, + &hreq->param.auth_cred.realm)) + ) + { + /* Yes, authentication is required and we have been + * configured with credential. + */ + restart_req_with_auth(hreq); + if (hreq->auth_state == AUTH_RETRYING) { + /* We'll be resending the request with auth. This + * connection has been closed. + */ + return PJ_FALSE; + } } } @@ -395,17 +394,17 @@ static pj_bool_t http_on_data_read(pj_activesock_t *asock, hreq->response.data = NULL; hreq->response.size = 0; - if (rem > 0 || hreq->response.content_length == 0) - return http_on_data_read(asock, (rem == 0 ? NULL: - (char *)data + size - rem), - rem, PJ_SUCCESS, NULL); + if (rem > 0 || hreq->response.content_length == 0) + return http_on_data_read(asock, (rem == 0 ? NULL: + (char *)data + size - rem), + rem, PJ_SUCCESS, NULL); } return PJ_TRUE; } if (hreq->state != READING_DATA) - return PJ_FALSE; + return PJ_FALSE; if (hreq->cb.on_data_read) { /* If application wishes to receive the data once available, call * its callback. @@ -449,11 +448,11 @@ static pj_bool_t http_on_data_read(pj_activesock_t *asock, * or if it's already EOF. */ if ((hreq->response.content_length >=0 && - (pj_ssize_t)hreq->tcp_state.current_read_size >= + (pj_ssize_t)hreq->tcp_state.current_read_size >= hreq->response.content_length) || (status == PJ_EEOF && hreq->response.content_length == -1)) { - /* Finish reading */ + /* Finish reading */ http_req_end_request(hreq); hreq->response.size = hreq->tcp_state.current_read_size; @@ -479,7 +478,7 @@ static pj_bool_t http_on_data_read(pj_activesock_t *asock, /* Callback to be called when query has timed out */ static void on_timeout( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { pj_http_req *hreq = (pj_http_req *) entry->user_data; @@ -490,8 +489,8 @@ static void on_timeout( pj_timer_heap_t *timer_heap, * same time response arrives). */ if (hreq->state == READING_COMPLETE) { - /* Yeah, we finish on time */ - return; + /* Yeah, we finish on time */ + return; } /* Invalidate id. */ @@ -504,90 +503,90 @@ static void on_timeout( pj_timer_heap_t *timer_heap, /* Parse authentication challenge */ static pj_status_t parse_auth_chal(pj_pool_t *pool, pj_str_t *input, - pj_http_auth_chal *chal) + pj_http_auth_chal *chal) { pj_scanner scanner; - const pj_str_t REALM_STR = { "realm", 5}, - NONCE_STR = { "nonce", 5}, - ALGORITHM_STR = { "algorithm", 9 }, - STALE_STR = { "stale", 5}, - QOP_STR = { "qop", 3}, - OPAQUE_STR = { "opaque", 6}; + const pj_str_t REALM_STR = { "realm", 5}, + NONCE_STR = { "nonce", 5}, + ALGORITHM_STR = { "algorithm", 9 }, + STALE_STR = { "stale", 5}, + QOP_STR = { "qop", 3}, + OPAQUE_STR = { "opaque", 6}; pj_status_t status = PJ_SUCCESS; PJ_USE_EXCEPTION ; pj_scan_init(&scanner, input->ptr, input->slen, PJ_SCAN_AUTOSKIP_WS, - &on_syntax_error); + &on_syntax_error); PJ_TRY { - /* Get auth scheme */ - if (*scanner.curptr == '"') { - pj_scan_get_quote(&scanner, '"', '"', &chal->scheme); - chal->scheme.ptr++; - chal->scheme.slen -= 2; - } else { - pj_scan_get_until_chr(&scanner, " \t\r\n", &chal->scheme); - } - - /* Loop parsing all parameters */ - for (;;) { - const char *end_param = ", \t\r\n;"; - pj_str_t name, value; - - /* Get pair of parameter name and value */ - value.ptr = NULL; - value.slen = 0; - pj_scan_get_until_chr(&scanner, "=, \t\r\n", &name); - if (*scanner.curptr == '=') { - pj_scan_get_char(&scanner); - if (!pj_scan_is_eof(&scanner)) { - if (*scanner.curptr == '"' || *scanner.curptr == '\'') { - int quote_char = *scanner.curptr; - pj_scan_get_quote(&scanner, quote_char, quote_char, - &value); - value.ptr++; - value.slen -= 2; - } else if (!strchr(end_param, *scanner.curptr)) { - pj_scan_get_until_chr(&scanner, end_param, &value); - } - } - value = pj_str_unescape(pool, &value); - } - - if (!pj_stricmp(&name, &REALM_STR)) { - chal->realm = value; - - } else if (!pj_stricmp(&name, &NONCE_STR)) { - chal->nonce = value; - - } else if (!pj_stricmp(&name, &ALGORITHM_STR)) { - chal->algorithm = value; - - } else if (!pj_stricmp(&name, &OPAQUE_STR)) { - chal->opaque = value; - - } else if (!pj_stricmp(&name, &QOP_STR)) { - chal->qop = value; - - } else if (!pj_stricmp(&name, &STALE_STR)) { - chal->stale = value.slen && - (*value.ptr != '0') && - (*value.ptr != 'f') && - (*value.ptr != 'F'); - - } - - /* Eat comma */ - if (!pj_scan_is_eof(&scanner) && *scanner.curptr == ',') - pj_scan_get_char(&scanner); - else - break; - } + /* Get auth scheme */ + if (*scanner.curptr == '"') { + pj_scan_get_quote(&scanner, '"', '"', &chal->scheme); + chal->scheme.ptr++; + chal->scheme.slen -= 2; + } else { + pj_scan_get_until_chr(&scanner, " \t\r\n", &chal->scheme); + } + + /* Loop parsing all parameters */ + for (;;) { + const char *end_param = ", \t\r\n;"; + pj_str_t name, value; + + /* Get pair of parameter name and value */ + value.ptr = NULL; + value.slen = 0; + pj_scan_get_until_chr(&scanner, "=, \t\r\n", &name); + if (*scanner.curptr == '=') { + pj_scan_get_char(&scanner); + if (!pj_scan_is_eof(&scanner)) { + if (*scanner.curptr == '"' || *scanner.curptr == '\'') { + int quote_char = *scanner.curptr; + pj_scan_get_quote(&scanner, quote_char, quote_char, + &value); + value.ptr++; + value.slen -= 2; + } else if (!strchr(end_param, *scanner.curptr)) { + pj_scan_get_until_chr(&scanner, end_param, &value); + } + } + value = pj_str_unescape(pool, &value); + } + + if (!pj_stricmp(&name, &REALM_STR)) { + chal->realm = value; + + } else if (!pj_stricmp(&name, &NONCE_STR)) { + chal->nonce = value; + + } else if (!pj_stricmp(&name, &ALGORITHM_STR)) { + chal->algorithm = value; + + } else if (!pj_stricmp(&name, &OPAQUE_STR)) { + chal->opaque = value; + + } else if (!pj_stricmp(&name, &QOP_STR)) { + chal->qop = value; + + } else if (!pj_stricmp(&name, &STALE_STR)) { + chal->stale = value.slen && + (*value.ptr != '0') && + (*value.ptr != 'f') && + (*value.ptr != 'F'); + + } + + /* Eat comma */ + if (!pj_scan_is_eof(&scanner) && *scanner.curptr == ',') + pj_scan_get_char(&scanner); + else + break; + } } PJ_CATCH_ANY { - status = PJ_GET_EXCEPTION(); - pj_bzero(chal, sizeof(*chal)); - TRACE_((THIS_FILE, "Error: parsing of auth header failed")); + status = PJ_GET_EXCEPTION(); + pj_bzero(chal, sizeof(*chal)); + TRACE_((THIS_FILE, "Error: parsing of auth header failed")); } PJ_END; pj_scan_fini(&scanner); @@ -785,12 +784,12 @@ static char *get_url_at_pos(const char *str, pj_size_t len) if (p==end) return NULL; for (; p!=end; ++p) { - switch (*p) { - case '/': - return NULL; - case '@': - return (char*)p; - } + switch (*p) { + case '/': + return NULL; + case '@': + return (char*)p; + } } return NULL; @@ -810,7 +809,7 @@ PJ_DEF(pj_status_t) pj_http_req_parse_url(const pj_str_t *url, pj_scan_init(&scanner, url->ptr, url->slen, 0, &on_syntax_error); PJ_TRY { - pj_str_t s; + pj_str_t s; /* Exhaust any whitespaces. */ pj_scan_skip_whitespace(&scanner); @@ -819,10 +818,10 @@ PJ_DEF(pj_status_t) pj_http_req_parse_url(const pj_str_t *url, pj_scan_get_until_ch(&scanner, ':', &s); if (!pj_stricmp2(&s, http_protocol_names[PROTOCOL_HTTP])) { pj_strset2(&hurl->protocol, - (char*)http_protocol_names[PROTOCOL_HTTP]); + (char*)http_protocol_names[PROTOCOL_HTTP]); } else if (!pj_stricmp2(&s, http_protocol_names[PROTOCOL_HTTPS])) { pj_strset2(&hurl->protocol, - (char*)http_protocol_names[PROTOCOL_HTTPS]); + (char*)http_protocol_names[PROTOCOL_HTTPS]); } else { PJ_THROW(PJ_ENOTSUP); // unsupported protocol } @@ -836,10 +835,10 @@ PJ_DEF(pj_status_t) pj_http_req_parse_url(const pj_str_t *url, /* Parse username and password */ pj_scan_get_until_chr(&scanner, ":@", &hurl->username); if (*scanner.curptr == ':') { - pj_scan_get_char(&scanner); - pj_scan_get_until_chr(&scanner, "@", &hurl->passwd); + pj_scan_get_char(&scanner); + pj_scan_get_until_chr(&scanner, "@", &hurl->passwd); } else { - hurl->passwd.slen = 0; + hurl->passwd.slen = 0; } pj_scan_get_char(&scanner); } @@ -873,7 +872,7 @@ PJ_DEF(pj_status_t) pj_http_req_parse_url(const pj_str_t *url, } PJ_CATCH_ANY { pj_scan_fini(&scanner); - return PJ_GET_EXCEPTION(); + return PJ_GET_EXCEPTION(); } PJ_END; @@ -943,12 +942,12 @@ PJ_DEF(pj_status_t) pj_http_req_create(pj_pool_t *pool, /* Parse the URL */ if (!pj_strdup_with_null(hreq->pool, &hreq->url, url)) { - pj_pool_release(hreq->pool); + pj_pool_release(hreq->pool); return PJ_ENOMEM; } status = pj_http_req_parse_url(&hreq->url, &hreq->hurl); if (status != PJ_SUCCESS) { - pj_pool_release(hreq->pool); + pj_pool_release(hreq->pool); return status; // Invalid URL supplied } @@ -956,39 +955,39 @@ PJ_DEF(pj_status_t) pj_http_req_create(pj_pool_t *pool, * remove them from the URL. */ if ((at_pos=get_url_at_pos(hreq->url.ptr, hreq->url.slen)) != NULL) { - pj_str_t tmp; - char *user_pos = pj_strchr(&hreq->url, '/'); - int removed_len; - - /* Save credential first, unescape the string */ - tmp = pj_str_unescape(hreq->pool, &hreq->hurl.username);; - pj_strdup(hreq->pool, &hreq->param.auth_cred.username, &tmp); - - tmp = pj_str_unescape(hreq->pool, &hreq->hurl.passwd); - pj_strdup(hreq->pool, &hreq->param.auth_cred.data, &tmp); - - hreq->hurl.username.ptr = hreq->hurl.passwd.ptr = NULL; - hreq->hurl.username.slen = hreq->hurl.passwd.slen = 0; - - /* Remove "username:password@" from the URL */ - pj_assert(user_pos != 0 && user_pos < at_pos); - user_pos += 2; - removed_len = (int)(at_pos + 1 - user_pos); - pj_memmove(user_pos, at_pos+1, hreq->url.ptr+hreq->url.slen-at_pos-1); - hreq->url.slen -= removed_len; - - /* Need to adjust hostname and path pointers due to memmove*/ - if (hreq->hurl.host.ptr > user_pos && - hreq->hurl.host.ptr < user_pos + hreq->url.slen) - { - hreq->hurl.host.ptr -= removed_len; - } - /* path may come from a string constant, don't shift it if so */ - if (hreq->hurl.path.ptr > user_pos && - hreq->hurl.path.ptr < user_pos + hreq->url.slen) - { - hreq->hurl.path.ptr -= removed_len; - } + pj_str_t tmp; + char *user_pos = pj_strchr(&hreq->url, '/'); + int removed_len; + + /* Save credential first, unescape the string */ + tmp = pj_str_unescape(hreq->pool, &hreq->hurl.username);; + pj_strdup(hreq->pool, &hreq->param.auth_cred.username, &tmp); + + tmp = pj_str_unescape(hreq->pool, &hreq->hurl.passwd); + pj_strdup(hreq->pool, &hreq->param.auth_cred.data, &tmp); + + hreq->hurl.username.ptr = hreq->hurl.passwd.ptr = NULL; + hreq->hurl.username.slen = hreq->hurl.passwd.slen = 0; + + /* Remove "username:password@" from the URL */ + pj_assert(user_pos != 0 && user_pos < at_pos); + user_pos += 2; + removed_len = (int)(at_pos + 1 - user_pos); + pj_memmove(user_pos, at_pos+1, hreq->url.ptr+hreq->url.slen-at_pos-1); + hreq->url.slen -= removed_len; + + /* Need to adjust hostname and path pointers due to memmove*/ + if (hreq->hurl.host.ptr > user_pos && + hreq->hurl.host.ptr < user_pos + hreq->url.slen) + { + hreq->hurl.host.ptr -= removed_len; + } + /* path may come from a string constant, don't shift it if so */ + if (hreq->hurl.path.ptr > user_pos && + hreq->hurl.path.ptr < user_pos + hreq->url.slen) + { + hreq->hurl.path.ptr -= removed_len; + } } *http_req = hreq; @@ -1030,13 +1029,13 @@ static pj_status_t start_http_req(pj_http_req *http_req, /* Resolve the Internet address of the host */ status = pj_sockaddr_init(http_req->param.addr_family, &http_req->addr, &http_req->hurl.host, - http_req->hurl.port); - if (status != PJ_SUCCESS || - !pj_sockaddr_has_addr(&http_req->addr) || - (http_req->param.addr_family==pj_AF_INET() && - http_req->addr.ipv4.sin_addr.s_addr==PJ_INADDR_NONE)) - { - goto on_return; + http_req->hurl.port); + if (status != PJ_SUCCESS || + !pj_sockaddr_has_addr(&http_req->addr) || + (http_req->param.addr_family==pj_AF_INET() && + http_req->addr.ipv4.sin_addr.s_addr==PJ_INADDR_NONE)) + { + goto on_return; } http_req->resolved = PJ_TRUE; } @@ -1050,41 +1049,41 @@ static pj_status_t start_http_req(pj_http_req *http_req, asock_cb.on_data_read = &http_on_data_read; asock_cb.on_data_sent = &http_on_data_sent; asock_cb.on_connect_complete = &http_on_connect; - + do { - pj_sockaddr_in bound_addr; - pj_uint16_t port = 0; + pj_sockaddr_in bound_addr; + pj_uint16_t port = 0; - /* If we are using port restriction. - * Get a random port within the range - */ - if (http_req->param.source_port_range_start != 0) { - port = (pj_uint16_t) - (http_req->param.source_port_range_start + - (pj_rand() % http_req->param.source_port_range_size)); - } + /* If we are using port restriction. + * Get a random port within the range + */ + if (http_req->param.source_port_range_start != 0) { + port = (pj_uint16_t) + (http_req->param.source_port_range_start + + (pj_rand() % http_req->param.source_port_range_size)); + } - pj_sockaddr_in_init(&bound_addr, NULL, port); - status = pj_sock_bind(sock, &bound_addr, sizeof(bound_addr)); + pj_sockaddr_in_init(&bound_addr, NULL, port); + status = pj_sock_bind(sock, &bound_addr, sizeof(bound_addr)); } while (status != PJ_SUCCESS && (retry++ < http_req->param.max_retries)); if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "Unable to bind to the requested port")); - pj_sock_close(sock); - goto on_return; + PJ_PERROR(1,(THIS_FILE, status, + "Unable to bind to the requested port")); + pj_sock_close(sock); + goto on_return; } // TODO: should we set whole data to 0 by default? // or add it in the param? status = pj_activesock_create(http_req->pool, sock, pj_SOCK_STREAM(), NULL, http_req->ioqueue, - &asock_cb, http_req, &http_req->asock); + &asock_cb, http_req, &http_req->asock); if (status != PJ_SUCCESS) { pj_sock_close(sock); - goto on_return; // error creating activesock + goto on_return; // error creating activesock } /* Schedule timeout timer for the request */ @@ -1094,7 +1093,7 @@ static pj_status_t start_http_req(pj_http_req *http_req, &http_req->param.timeout); if (status != PJ_SUCCESS) { http_req->timer_entry.id = 0; - goto on_return; // error scheduling timer + goto on_return; // error scheduling timer } /* Connect to host */ @@ -1116,9 +1115,9 @@ static pj_status_t start_http_req(pj_http_req *http_req, on_return: http_req->error = status; if (notify_on_fail) - pj_http_req_cancel(http_req, PJ_TRUE); + pj_http_req_cancel(http_req, PJ_TRUE); else - http_req_end_request(http_req); + http_req_end_request(http_req); return status; } @@ -1155,9 +1154,9 @@ static pj_status_t auth_respond_basic(pj_http_req *hreq) phdr = &hreq->param.headers.header[hreq->param.headers.count++]; pj_bzero(phdr, sizeof(*phdr)); if (hreq->response.status_code == 401) - phdr->name = pj_str("Authorization"); + phdr->name = pj_str("Authorization"); else - phdr->name = pj_str("Proxy-Authorization"); + phdr->name = pj_str("Proxy-Authorization"); len = (int)(PJ_BASE256_TO_BASE64_LEN(user_pass.slen) + 10); phdr->value.ptr = (char*)pj_pool_alloc(hreq->pool, len); @@ -1166,7 +1165,7 @@ static pj_status_t auth_respond_basic(pj_http_req *hreq) pj_strcpy2(&phdr->value, "Basic "); len -= (int)phdr->value.slen; pj_base64_encode((pj_uint8_t*)user_pass.ptr, (int)user_pass.slen, - phdr->value.ptr + phdr->value.slen, &len); + phdr->value.ptr + phdr->value.slen, &len); phdr->value.slen += len; return PJ_SUCCESS; @@ -1175,8 +1174,8 @@ static pj_status_t auth_respond_basic(pj_http_req *hreq) /** Length of digest string. */ #define MD5_STRLEN 32 /* A macro just to get rid of type mismatch between char and unsigned char */ -#define MD5_APPEND(pms,buf,len) pj_md5_update(pms, (const pj_uint8_t*)buf, \ - (unsigned)len) +#define MD5_APPEND(pms,buf,len) pj_md5_update(pms, (const pj_uint8_t*)buf, \ + (unsigned)len) /* Transform digest to string. * output must be at least PJSIP_MD5STRLEN+1 bytes. @@ -1187,20 +1186,20 @@ static void digest2str(const unsigned char digest[], char *output) { int i; for (i = 0; i<16; ++i) { - pj_val_to_hex_digit(digest[i], output); - output += 2; + pj_val_to_hex_digit(digest[i], output); + output += 2; } } static void auth_create_digest_response(pj_str_t *result, - const pj_http_auth_cred *cred, - const pj_str_t *nonce, - const pj_str_t *nc, - const pj_str_t *cnonce, - const pj_str_t *qop, - const pj_str_t *uri, - const pj_str_t *realm, - const pj_str_t *method) + const pj_http_auth_cred *cred, + const pj_str_t *nonce, + const pj_str_t *nc, + const pj_str_t *cnonce, + const pj_str_t *qop, + const pj_str_t *uri, + const pj_str_t *realm, + const pj_str_t *method) { char ha1[MD5_STRLEN]; char ha2[MD5_STRLEN]; @@ -1212,24 +1211,24 @@ static void auth_create_digest_response(pj_str_t *result, TRACE_((THIS_FILE, "Begin creating digest")); if (cred->data_type == 0) { - /*** - *** ha1 = MD5(username ":" realm ":" password) - ***/ - pj_md5_init(&pms); - MD5_APPEND( &pms, cred->username.ptr, cred->username.slen); - MD5_APPEND( &pms, ":", 1); - MD5_APPEND( &pms, realm->ptr, realm->slen); - MD5_APPEND( &pms, ":", 1); - MD5_APPEND( &pms, cred->data.ptr, cred->data.slen); - pj_md5_final(&pms, digest); - - digest2str(digest, ha1); + /*** + *** ha1 = MD5(username ":" realm ":" password) + ***/ + pj_md5_init(&pms); + MD5_APPEND( &pms, cred->username.ptr, cred->username.slen); + MD5_APPEND( &pms, ":", 1); + MD5_APPEND( &pms, realm->ptr, realm->slen); + MD5_APPEND( &pms, ":", 1); + MD5_APPEND( &pms, cred->data.ptr, cred->data.slen); + pj_md5_final(&pms, digest); + + digest2str(digest, ha1); } else if (cred->data_type == 1) { - pj_assert(cred->data.slen == 32); - pj_memcpy( ha1, cred->data.ptr, cred->data.slen ); + pj_assert(cred->data.slen == 32); + pj_memcpy( ha1, cred->data.ptr, cred->data.slen ); } else { - pj_assert(!"Invalid data_type"); + pj_assert(!"Invalid data_type"); } TRACE_((THIS_FILE, " ha1=%.32s", ha1)); @@ -1258,12 +1257,12 @@ static void auth_create_digest_response(pj_str_t *result, MD5_APPEND( &pms, ":", 1); MD5_APPEND( &pms, nonce->ptr, nonce->slen); if (qop && qop->slen != 0) { - MD5_APPEND( &pms, ":", 1); - MD5_APPEND( &pms, nc->ptr, nc->slen); - MD5_APPEND( &pms, ":", 1); - MD5_APPEND( &pms, cnonce->ptr, cnonce->slen); - MD5_APPEND( &pms, ":", 1); - MD5_APPEND( &pms, qop->ptr, qop->slen); + MD5_APPEND( &pms, ":", 1); + MD5_APPEND( &pms, nc->ptr, nc->slen); + MD5_APPEND( &pms, ":", 1); + MD5_APPEND( &pms, cnonce->ptr, cnonce->slen); + MD5_APPEND( &pms, ":", 1); + MD5_APPEND( &pms, qop->ptr, qop->slen); } MD5_APPEND( &pms, ":", 1); MD5_APPEND( &pms, ha2, MD5_STRLEN); @@ -1288,21 +1287,21 @@ static pj_bool_t auth_has_qop( pj_pool_t *pool, const pj_str_t *qop_offer) pj_strdup_with_null( pool, &qop, qop_offer); p = qop.ptr; while (*p) { - *p = (char)pj_tolower(*p); - ++p; + *p = (char)pj_tolower(*p); + ++p; } p = qop.ptr; while (*p) { - if (*p=='a' && *(p+1)=='u' && *(p+2)=='t' && *(p+3)=='h') { - int e = *(p+4); - if (e=='"' || e==',' || e==0) - return PJ_TRUE; - else - p += 4; - } else { - ++p; - } + if (*p=='a' && *(p+1)=='u' && *(p+2)=='t' && *(p+3)=='h') { + int e = *(p+4); + if (e=='"' || e==',' || e==0) + return PJ_TRUE; + else + p += 4; + } else { + ++p; + } } return PJ_FALSE; @@ -1322,34 +1321,34 @@ static pj_status_t auth_respond_digest(pj_http_req *hreq) /* Check algorithm is supported. We only support MD5 */ if (chal->algorithm.slen!=0 && - pj_stricmp2(&chal->algorithm, "MD5")) + pj_stricmp2(&chal->algorithm, "MD5")) { - TRACE_((THIS_FILE, "Error: Unsupported digest algorithm \"%.*s\"", - chal->algorithm.slen, chal->algorithm.ptr)); - return PJ_ENOTSUP; + TRACE_((THIS_FILE, "Error: Unsupported digest algorithm \"%.*s\"", + chal->algorithm.slen, chal->algorithm.ptr)); + return PJ_ENOTSUP; } /* Add Authorization header */ phdr = &hreq->param.headers.header[hreq->param.headers.count++]; pj_bzero(phdr, sizeof(*phdr)); if (hreq->response.status_code == 401) - phdr->name = pj_str("Authorization"); + phdr->name = pj_str("Authorization"); else - phdr->name = pj_str("Proxy-Authorization"); + phdr->name = pj_str("Proxy-Authorization"); /* Allocate space for the header */ len = (int)(8 + /* Digest */ - 16 + hreq->param.auth_cred.username.slen + /* username= */ - 12 + chal->realm.slen + /* realm= */ - 12 + chal->nonce.slen + /* nonce= */ - 8 + hreq->hurl.path.slen + /* uri= */ - 16 + /* algorithm=MD5 */ - 16 + MD5_STRLEN + /* response= */ - 12 + /* qop=auth */ - 8 + /* nc=.. */ - 30 + /* cnonce= */ - 12 + chal->opaque.slen + /* opaque=".." */ - 0); + 16 + hreq->param.auth_cred.username.slen + /* username= */ + 12 + chal->realm.slen + /* realm= */ + 12 + chal->nonce.slen + /* nonce= */ + 8 + hreq->hurl.path.slen + /* uri= */ + 16 + /* algorithm=MD5 */ + 16 + MD5_STRLEN + /* response= */ + 12 + /* qop=auth */ + 8 + /* nc=.. */ + 30 + /* cnonce= */ + 12 + chal->opaque.slen + /* opaque=".." */ + 0); phdr->value.ptr = (char*)pj_pool_alloc(hreq->pool, len); /* Configure buffer to temporarily store the digest */ @@ -1357,84 +1356,84 @@ static pj_status_t auth_respond_digest(pj_http_req *hreq) digest_response.slen = MD5_STRLEN; if (chal->qop.slen == 0) { - const pj_str_t STR_MD5 = { "MD5", 3 }; - int max_len; - - /* Server doesn't require quality of protection. */ - auth_create_digest_response(&digest_response, cred, - &chal->nonce, NULL, NULL, NULL, - &hreq->hurl.path, &chal->realm, - &hreq->param.method); - - max_len = len; - len = pj_ansi_snprintf( - phdr->value.ptr, max_len, - "Digest username=\"%.*s\", " - "realm=\"%.*s\", " - "nonce=\"%.*s\", " - "uri=\"%.*s\", " - "algorithm=%.*s, " - "response=\"%.*s\"", - STR_PREC(cred->username), - STR_PREC(chal->realm), - STR_PREC(chal->nonce), - STR_PREC(hreq->hurl.path), - STR_PREC(STR_MD5), - STR_PREC(digest_response)); - if (len < 0 || len >= max_len) - return PJ_ETOOSMALL; - phdr->value.slen = len; + const pj_str_t STR_MD5 = { "MD5", 3 }; + int max_len; + + /* Server doesn't require quality of protection. */ + auth_create_digest_response(&digest_response, cred, + &chal->nonce, NULL, NULL, NULL, + &hreq->hurl.path, &chal->realm, + &hreq->param.method); + + max_len = len; + len = pj_ansi_snprintf( + phdr->value.ptr, max_len, + "Digest username=\"%.*s\", " + "realm=\"%.*s\", " + "nonce=\"%.*s\", " + "uri=\"%.*s\", " + "algorithm=%.*s, " + "response=\"%.*s\"", + STR_PREC(cred->username), + STR_PREC(chal->realm), + STR_PREC(chal->nonce), + STR_PREC(hreq->hurl.path), + STR_PREC(STR_MD5), + STR_PREC(digest_response)); + if (len < 0 || len >= max_len) + return PJ_ETOOSMALL; + phdr->value.slen = len; } else if (auth_has_qop(hreq->pool, &chal->qop)) { - /* Server requires quality of protection. - * We respond with selecting "qop=auth" protection. - */ - const pj_str_t STR_MD5 = { "MD5", 3 }; - const pj_str_t qop = pj_str("auth"); - const pj_str_t nc = pj_str("00000001"); - const pj_str_t cnonce = pj_str("b39971"); - int max_len; - - auth_create_digest_response(&digest_response, cred, - &chal->nonce, &nc, &cnonce, &qop, - &hreq->hurl.path, &chal->realm, - &hreq->param.method); - max_len = len; - len = pj_ansi_snprintf( - phdr->value.ptr, max_len, - "Digest username=\"%.*s\", " - "realm=\"%.*s\", " - "nonce=\"%.*s\", " - "uri=\"%.*s\", " - "algorithm=%.*s, " - "response=\"%.*s\", " - "qop=%.*s, " - "nc=%.*s, " - "cnonce=\"%.*s\"", - STR_PREC(cred->username), - STR_PREC(chal->realm), - STR_PREC(chal->nonce), - STR_PREC(hreq->hurl.path), - STR_PREC(STR_MD5), - STR_PREC(digest_response), - STR_PREC(qop), - STR_PREC(nc), - STR_PREC(cnonce)); - if (len < 0 || len >= max_len) - return PJ_ETOOSMALL; - phdr->value.slen = len; - - if (chal->opaque.slen) { - pj_strcat2(&phdr->value, ", opaque=\""); - pj_strcat(&phdr->value, &chal->opaque); - pj_strcat2(&phdr->value, "\""); - } + /* Server requires quality of protection. + * We respond with selecting "qop=auth" protection. + */ + const pj_str_t STR_MD5 = { "MD5", 3 }; + const pj_str_t qop = pj_str("auth"); + const pj_str_t nc = pj_str("00000001"); + const pj_str_t cnonce = pj_str("b39971"); + int max_len; + + auth_create_digest_response(&digest_response, cred, + &chal->nonce, &nc, &cnonce, &qop, + &hreq->hurl.path, &chal->realm, + &hreq->param.method); + max_len = len; + len = pj_ansi_snprintf( + phdr->value.ptr, max_len, + "Digest username=\"%.*s\", " + "realm=\"%.*s\", " + "nonce=\"%.*s\", " + "uri=\"%.*s\", " + "algorithm=%.*s, " + "response=\"%.*s\", " + "qop=%.*s, " + "nc=%.*s, " + "cnonce=\"%.*s\"", + STR_PREC(cred->username), + STR_PREC(chal->realm), + STR_PREC(chal->nonce), + STR_PREC(hreq->hurl.path), + STR_PREC(STR_MD5), + STR_PREC(digest_response), + STR_PREC(qop), + STR_PREC(nc), + STR_PREC(cnonce)); + if (len < 0 || len >= max_len) + return PJ_ETOOSMALL; + phdr->value.slen = len; + + if (chal->opaque.slen) { + pj_strcat2(&phdr->value, ", opaque=\""); + pj_strcat(&phdr->value, &chal->opaque); + pj_strcat2(&phdr->value, "\""); + } } else { - /* Server requires quality protection that we don't support. */ - TRACE_((THIS_FILE, "Error: Unsupported qop offer %.*s", - chal->qop.slen, chal->qop.ptr)); - return PJ_ENOTSUP; + /* Server requires quality protection that we don't support. */ + TRACE_((THIS_FILE, "Error: Unsupported qop offer %.*s", + chal->qop.slen, chal->qop.ptr)); + return PJ_ENOTSUP; } return PJ_SUCCESS; @@ -1448,42 +1447,42 @@ static void restart_req_with_auth(pj_http_req *hreq) pj_status_t status; if (hreq->param.headers.count >= PJ_HTTP_HEADER_SIZE) { - TRACE_((THIS_FILE, "Error: no place to put Authorization header")); - hreq->auth_state = AUTH_DONE; - return; + TRACE_((THIS_FILE, "Error: no place to put Authorization header")); + hreq->auth_state = AUTH_DONE; + return; } /* If credential specifies specific scheme, make sure they match */ if (cred->scheme.slen && pj_stricmp(&chal->scheme, &cred->scheme)) { - status = PJ_ENOTSUP; - TRACE_((THIS_FILE, "Error: auth schemes mismatch")); - goto on_error; + status = PJ_ENOTSUP; + TRACE_((THIS_FILE, "Error: auth schemes mismatch")); + goto on_error; } /* If credential specifies specific realm, make sure they match */ if (cred->realm.slen && pj_stricmp(&chal->realm, &cred->realm)) { - status = PJ_ENOTSUP; - TRACE_((THIS_FILE, "Error: auth realms mismatch")); - goto on_error; + status = PJ_ENOTSUP; + TRACE_((THIS_FILE, "Error: auth realms mismatch")); + goto on_error; } if (!pj_stricmp2(&chal->scheme, "basic")) { - status = auth_respond_basic(hreq); + status = auth_respond_basic(hreq); } else if (!pj_stricmp2(&chal->scheme, "digest")) { - status = auth_respond_digest(hreq); + status = auth_respond_digest(hreq); } else { - TRACE_((THIS_FILE, "Error: unsupported HTTP auth scheme")); - status = PJ_ENOTSUP; + TRACE_((THIS_FILE, "Error: unsupported HTTP auth scheme")); + status = PJ_ENOTSUP; } if (status != PJ_SUCCESS) - goto on_error; + goto on_error; http_req_end_request(hreq); status = start_http_req(hreq, PJ_TRUE); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; hreq->auth_state = AUTH_RETRYING; return; @@ -1497,7 +1496,7 @@ static void restart_req_with_auth(pj_http_req *hreq) * result at the back of the string. */ static void str_snprintf(pj_str_t *s, size_t size, - pj_bool_t append, const char *format, ...) + pj_bool_t append, const char *format, ...) { va_list arg; int retval; @@ -1612,7 +1611,7 @@ static pj_status_t http_req_start_reading(pj_http_req *hreq) static pj_status_t http_req_end_request(pj_http_req *hreq) { if (hreq->asock) { - pj_activesock_close(hreq->asock); + pj_activesock_close(hreq->asock); hreq->asock = NULL; } diff --git a/pjlib-util/src/pjlib-util/json.c b/pjlib-util/src/pjlib-util/json.c index c3f231e3a1..ff8f554391 100644 --- a/pjlib-util/src/pjlib-util/json.c +++ b/pjlib-util/src/pjlib-util/json.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -24,20 +23,20 @@ #include #include -#define EL_INIT(p_el, nm, typ) do { \ - if (nm) { \ - p_el->name = *nm; \ - } else { \ - p_el->name.ptr = (char*)""; \ - p_el->name.slen = 0; \ - } \ - p_el->type = typ; \ - } while (0) +#define EL_INIT(p_el, nm, typ) do { \ + if (nm) { \ + p_el->name = *nm; \ + } else { \ + p_el->name.ptr = (char*)""; \ + p_el->name.slen = 0; \ + } \ + p_el->type = typ; \ + } while (0) struct write_state; struct parse_state; -#define NO_NAME 1 +#define NO_NAME 1 static pj_status_t elem_write(const pj_json_elem *elem, struct write_state *st, @@ -92,10 +91,10 @@ PJ_DEF(void) pj_json_elem_add(pj_json_elem *el, pj_json_elem *child) struct parse_state { - pj_pool_t *pool; - pj_scanner scanner; - pj_json_err_info *err_info; - pj_cis_t float_spec; /* numbers with dot! */ + pj_pool_t *pool; + pj_scanner scanner; + pj_json_err_info *err_info; + pj_cis_t float_spec; /* numbers with dot! */ }; static pj_status_t parse_children(struct parse_state *st, @@ -106,19 +105,19 @@ static pj_status_t parse_children(struct parse_state *st, pj_scan_get_char(&st->scanner); while (*st->scanner.curptr != end_quote) { - pj_json_elem *child; + pj_json_elem *child; - while (*st->scanner.curptr == ',') - pj_scan_get_char(&st->scanner); + while (*st->scanner.curptr == ',') + pj_scan_get_char(&st->scanner); - if (*st->scanner.curptr == end_quote) - break; + if (*st->scanner.curptr == end_quote) + break; - child = parse_elem_throw(st, NULL); - if (!child) - return PJLIB_UTIL_EINJSON; + child = parse_elem_throw(st, NULL); + if (!child) + return PJLIB_UTIL_EINJSON; - pj_json_elem_add(parent, child); + pj_json_elem_add(parent, child); } pj_scan_get_char(&st->scanner); @@ -139,8 +138,8 @@ static unsigned parse_quoted_string(struct parse_state *st, token.slen-=2; if (pj_strchr(&token, '\\') == NULL) { - *output = token; - return 0; + *output = token; + return 0; } output->ptr = op = pj_pool_alloc(st->pool, token.slen); @@ -149,45 +148,45 @@ static unsigned parse_quoted_string(struct parse_state *st, iend = token.ptr + token.slen; while (ip != iend) { - if (*ip == '\\') { - ++ip; - if (ip==iend) { - goto on_error; - } - if (*ip == 'u') { - ip++; - if (iend - ip < 4) { - ip = iend -1; - goto on_error; - } - /* Only use the last two hext digits because we're on - * ASCII */ - *op++ = (char)(pj_hex_digit_to_val(ip[2]) * 16 + - pj_hex_digit_to_val(ip[3])); - ip += 4; - } else if (*ip=='"' || *ip=='\\' || *ip=='/') { - *op++ = *ip++; - } else if (*ip=='b') { - *op++ = '\b'; - ip++; - } else if (*ip=='f') { - *op++ = '\f'; - ip++; - } else if (*ip=='n') { - *op++ = '\n'; - ip++; - } else if (*ip=='r') { - *op++ = '\r'; - ip++; - } else if (*ip=='t') { - *op++ = '\t'; - ip++; - } else { - goto on_error; - } - } else { - *op++ = *ip++; - } + if (*ip == '\\') { + ++ip; + if (ip==iend) { + goto on_error; + } + if (*ip == 'u') { + ip++; + if (iend - ip < 4) { + ip = iend -1; + goto on_error; + } + /* Only use the last two hext digits because we're on + * ASCII */ + *op++ = (char)(pj_hex_digit_to_val(ip[2]) * 16 + + pj_hex_digit_to_val(ip[3])); + ip += 4; + } else if (*ip=='"' || *ip=='\\' || *ip=='/') { + *op++ = *ip++; + } else if (*ip=='b') { + *op++ = '\b'; + ip++; + } else if (*ip=='f') { + *op++ = '\f'; + ip++; + } else if (*ip=='n') { + *op++ = '\n'; + ip++; + } else if (*ip=='r') { + *op++ = '\r'; + ip++; + } else if (*ip=='t') { + *op++ = '\t'; + ip++; + } else { + goto on_error; + } + } else { + *op++ = *ip++; + } } output->slen = op - output->ptr; @@ -205,85 +204,85 @@ static pj_json_elem* parse_elem_throw(struct parse_state *st, pj_str_t token; if (!elem) - elem = pj_pool_alloc(st->pool, sizeof(*elem)); + elem = pj_pool_alloc(st->pool, sizeof(*elem)); /* Parse name */ if (*st->scanner.curptr == '"') { - pj_scan_get_char(&st->scanner); - pj_scan_get_until_ch(&st->scanner, '"', &token); - pj_scan_get_char(&st->scanner); - - if (*st->scanner.curptr == ':') { - pj_scan_get_char(&st->scanner); - name = token; - } else { - value = token; - } + pj_scan_get_char(&st->scanner); + pj_scan_get_until_ch(&st->scanner, '"', &token); + pj_scan_get_char(&st->scanner); + + if (*st->scanner.curptr == ':') { + pj_scan_get_char(&st->scanner); + name = token; + } else { + value = token; + } } if (value.slen) { - /* Element with string value and no name */ - pj_json_elem_string(elem, &name, &value); - return elem; + /* Element with string value and no name */ + pj_json_elem_string(elem, &name, &value); + return elem; } /* Parse value */ if (pj_cis_match(&st->float_spec, *st->scanner.curptr) || - *st->scanner.curptr == '-') + *st->scanner.curptr == '-') { - float val; - pj_bool_t neg = PJ_FALSE; + float val; + pj_bool_t neg = PJ_FALSE; - if (*st->scanner.curptr == '-') { - pj_scan_get_char(&st->scanner); - neg = PJ_TRUE; - } + if (*st->scanner.curptr == '-') { + pj_scan_get_char(&st->scanner); + neg = PJ_TRUE; + } - pj_scan_get(&st->scanner, &st->float_spec, &token); - val = pj_strtof(&token); - if (neg) val = -val; + pj_scan_get(&st->scanner, &st->float_spec, &token); + val = pj_strtof(&token); + if (neg) val = -val; - pj_json_elem_number(elem, &name, val); + pj_json_elem_number(elem, &name, val); } else if (*st->scanner.curptr == '"') { - unsigned err; - char *start = st->scanner.curptr; + unsigned err; + char *start = st->scanner.curptr; - err = parse_quoted_string(st, &token); - if (err) { - st->scanner.curptr = start + err; - return NULL; - } + err = parse_quoted_string(st, &token); + if (err) { + st->scanner.curptr = start + err; + return NULL; + } - pj_json_elem_string(elem, &name, &token); + pj_json_elem_string(elem, &name, &token); } else if (pj_isalpha(*st->scanner.curptr)) { - if (pj_scan_strcmp(&st->scanner, "false", 5)==0) { - pj_json_elem_bool(elem, &name, PJ_FALSE); - pj_scan_advance_n(&st->scanner, 5, PJ_TRUE); - } else if (pj_scan_strcmp(&st->scanner, "true", 4)==0) { - pj_json_elem_bool(elem, &name, PJ_TRUE); - pj_scan_advance_n(&st->scanner, 4, PJ_TRUE); - } else if (pj_scan_strcmp(&st->scanner, "null", 4)==0) { - pj_json_elem_null(elem, &name); - pj_scan_advance_n(&st->scanner, 4, PJ_TRUE); - } else { - return NULL; - } + if (pj_scan_strcmp(&st->scanner, "false", 5)==0) { + pj_json_elem_bool(elem, &name, PJ_FALSE); + pj_scan_advance_n(&st->scanner, 5, PJ_TRUE); + } else if (pj_scan_strcmp(&st->scanner, "true", 4)==0) { + pj_json_elem_bool(elem, &name, PJ_TRUE); + pj_scan_advance_n(&st->scanner, 4, PJ_TRUE); + } else if (pj_scan_strcmp(&st->scanner, "null", 4)==0) { + pj_json_elem_null(elem, &name); + pj_scan_advance_n(&st->scanner, 4, PJ_TRUE); + } else { + return NULL; + } } else if (*st->scanner.curptr == '[') { - pj_json_elem_array(elem, &name); - if (parse_children(st, elem) != PJ_SUCCESS) - return NULL; + pj_json_elem_array(elem, &name); + if (parse_children(st, elem) != PJ_SUCCESS) + return NULL; } else if (*st->scanner.curptr == '{') { - pj_json_elem_obj(elem, &name); - if (parse_children(st, elem) != PJ_SUCCESS) - return NULL; + pj_json_elem_obj(elem, &name); + if (parse_children(st, elem) != PJ_SUCCESS) + return NULL; } else { - return NULL; + return NULL; } return elem; @@ -308,7 +307,7 @@ PJ_DEF(pj_json_elem*) pj_json_parse(pj_pool_t *pool, PJ_ASSERT_RETURN(pool && buffer && size, NULL); if (!*size) - return NULL; + return NULL; pj_bzero(&st, sizeof(st)); st.pool = pool; @@ -321,17 +320,17 @@ PJ_DEF(pj_json_elem*) pj_json_parse(pj_pool_t *pool, pj_cis_add_str(&st.float_spec, ".0123456789"); PJ_TRY { - root = parse_elem_throw(&st, NULL); + root = parse_elem_throw(&st, NULL); } PJ_CATCH_ANY { - root = NULL; + root = NULL; } PJ_END if (!root && err_info) { - err_info->line = st.scanner.line; - err_info->col = pj_scan_get_col(&st.scanner) + 1; - err_info->err_char = *st.scanner.curptr; + err_info->line = st.scanner.line; + err_info->col = pj_scan_get_col(&st.scanner) + 1; + err_info->err_char = *st.scanner.curptr; } *size = (unsigned)((buffer + *size) - st.scanner.curptr); @@ -343,17 +342,17 @@ PJ_DEF(pj_json_elem*) pj_json_parse(pj_pool_t *pool, struct buf_writer_data { - char *pos; - unsigned size; + char *pos; + unsigned size; }; static pj_status_t buf_writer(const char *s, - unsigned size, - void *user_data) + unsigned size, + void *user_data) { struct buf_writer_data *buf_data = (struct buf_writer_data*)user_data; if (size+1 >= buf_data->size) - return PJ_ETOOBIG; + return PJ_ETOOBIG; pj_memcpy(buf_data->pos, s, size); buf_data->pos += size; @@ -375,34 +374,34 @@ PJ_DEF(pj_status_t) pj_json_write(const pj_json_elem *elem, status = pj_json_writef(elem, &buf_writer, &buf_data); if (status != PJ_SUCCESS) - return status; + return status; *buf_data.pos = '\0'; *size = (unsigned)(buf_data.pos - buffer); return PJ_SUCCESS; } -#define MAX_INDENT 100 +#define MAX_INDENT 100 #ifndef PJ_JSON_NAME_MIN_LEN -# define PJ_JSON_NAME_MIN_LEN 20 +# define PJ_JSON_NAME_MIN_LEN 20 #endif -#define ESC_BUF_LEN 64 +#define ESC_BUF_LEN 64 #ifndef PJ_JSON_INDENT_SIZE -# define PJ_JSON_INDENT_SIZE 3 +# define PJ_JSON_INDENT_SIZE 3 #endif struct write_state { - pj_json_writer writer; - void *user_data; - char indent_buf[MAX_INDENT]; - int indent; - char space[PJ_JSON_NAME_MIN_LEN]; + pj_json_writer writer; + void *user_data; + char indent_buf[MAX_INDENT]; + int indent; + char space[PJ_JSON_NAME_MIN_LEN]; }; #define CHECK(expr) do { \ - status=expr; if (status!=PJ_SUCCESS) return status; } \ - while (0) + status=expr; if (status!=PJ_SUCCESS) return status; } \ + while (0) static pj_status_t write_string_escaped(const pj_str_t *value, struct write_state *st) @@ -415,64 +414,64 @@ static pj_status_t write_string_escaped(const pj_str_t *value, pj_status_t status; while (ip != iend) { - /* Write to buffer to speedup writing instead of calling - * the callback one by one for each character. - */ - while (ip != iend && op != oend) { - if (oend - op < 2) - break; - - if (*ip == '"') { - *op++ = '\\'; - *op++ = '"'; - ip++; - } else if (*ip == '\\') { - *op++ = '\\'; - *op++ = '\\'; - ip++; - } else if (*ip == '/') { - *op++ = '\\'; - *op++ = '/'; - ip++; - } else if (*ip == '\b') { - *op++ = '\\'; - *op++ = 'b'; - ip++; - } else if (*ip == '\f') { - *op++ = '\\'; - *op++ = 'f'; - ip++; - } else if (*ip == '\n') { - *op++ = '\\'; - *op++ = 'n'; - ip++; - } else if (*ip == '\r') { - *op++ = '\\'; - *op++ = 'r'; - ip++; - } else if (*ip == '\t') { - *op++ = '\\'; - *op++ = 't'; - ip++; - } else if ((*ip >= 32 && *ip < 127)) { - /* unescaped */ - *op++ = *ip++; - } else { - /* escaped */ - if (oend - op < 6) - break; - *op++ = '\\'; - *op++ = 'u'; - *op++ = '0'; - *op++ = '0'; - pj_val_to_hex_digit(*ip, op); - op+=2; - ip++; - } - } - - CHECK( st->writer( buf, (unsigned)(op-buf), st->user_data) ); - op = buf; + /* Write to buffer to speedup writing instead of calling + * the callback one by one for each character. + */ + while (ip != iend && op != oend) { + if (oend - op < 2) + break; + + if (*ip == '"') { + *op++ = '\\'; + *op++ = '"'; + ip++; + } else if (*ip == '\\') { + *op++ = '\\'; + *op++ = '\\'; + ip++; + } else if (*ip == '/') { + *op++ = '\\'; + *op++ = '/'; + ip++; + } else if (*ip == '\b') { + *op++ = '\\'; + *op++ = 'b'; + ip++; + } else if (*ip == '\f') { + *op++ = '\\'; + *op++ = 'f'; + ip++; + } else if (*ip == '\n') { + *op++ = '\\'; + *op++ = 'n'; + ip++; + } else if (*ip == '\r') { + *op++ = '\\'; + *op++ = 'r'; + ip++; + } else if (*ip == '\t') { + *op++ = '\\'; + *op++ = 't'; + ip++; + } else if ((*ip >= 32 && *ip < 127)) { + /* unescaped */ + *op++ = *ip++; + } else { + /* escaped */ + if (oend - op < 6) + break; + *op++ = '\\'; + *op++ = 'u'; + *op++ = '0'; + *op++ = '0'; + pj_val_to_hex_digit(*ip, op); + op+=2; + ip++; + } + } + + CHECK( st->writer( buf, (unsigned)(op-buf), st->user_data) ); + op = buf; } return PJ_SUCCESS; @@ -490,42 +489,42 @@ static pj_status_t write_children(const pj_json_list *list, CHECK( st->writer( " ", 1, st->user_data) ); if (!pj_list_empty(list)) { - pj_bool_t indent_added = PJ_FALSE; - pj_json_elem *child = list->next; - - if (child->name.slen == 0) { - /* Simple list */ - while (child != (pj_json_elem*)list) { - status = elem_write(child, st, flags); - if (status != PJ_SUCCESS) - return status; - - if (child->next != (pj_json_elem*)list) - CHECK( st->writer( ", ", 2, st->user_data) ); - child = child->next; - } - } else { - if (st->indent < sizeof(st->indent_buf)) { - st->indent += PJ_JSON_INDENT_SIZE; - indent_added = PJ_TRUE; - } - CHECK( st->writer( "\n", 1, st->user_data) ); - while (child != (pj_json_elem*)list) { - status = elem_write(child, st, flags); - if (status != PJ_SUCCESS) - return status; - - if (child->next != (pj_json_elem*)list) - CHECK( st->writer( ",\n", 2, st->user_data) ); - else - CHECK( st->writer( "\n", 1, st->user_data) ); - child = child->next; - } - if (indent_added) { - st->indent -= PJ_JSON_INDENT_SIZE; - } - CHECK( st->writer( st->indent_buf, st->indent, st->user_data) ); - } + pj_bool_t indent_added = PJ_FALSE; + pj_json_elem *child = list->next; + + if (child->name.slen == 0) { + /* Simple list */ + while (child != (pj_json_elem*)list) { + status = elem_write(child, st, flags); + if (status != PJ_SUCCESS) + return status; + + if (child->next != (pj_json_elem*)list) + CHECK( st->writer( ", ", 2, st->user_data) ); + child = child->next; + } + } else { + if (st->indent < sizeof(st->indent_buf)) { + st->indent += PJ_JSON_INDENT_SIZE; + indent_added = PJ_TRUE; + } + CHECK( st->writer( "\n", 1, st->user_data) ); + while (child != (pj_json_elem*)list) { + status = elem_write(child, st, flags); + if (status != PJ_SUCCESS) + return status; + + if (child->next != (pj_json_elem*)list) + CHECK( st->writer( ",\n", 2, st->user_data) ); + else + CHECK( st->writer( "\n", 1, st->user_data) ); + child = child->next; + } + if (indent_added) { + st->indent -= PJ_JSON_INDENT_SIZE; + } + CHECK( st->writer( st->indent_buf, st->indent, st->user_data) ); + } } CHECK( st->writer( "es[1], 1, st->user_data) ); @@ -539,63 +538,63 @@ static pj_status_t elem_write(const pj_json_elem *elem, pj_status_t status; if (elem->name.slen) { - CHECK( st->writer( st->indent_buf, st->indent, st->user_data) ); - if ((flags & NO_NAME)==0) { - CHECK( st->writer( "\"", 1, st->user_data) ); - CHECK( write_string_escaped(&elem->name, st) ); - CHECK( st->writer( "\": ", 3, st->user_data) ); - if (elem->name.slen < PJ_JSON_NAME_MIN_LEN /*&& - elem->type != PJ_JSON_VAL_OBJ && - elem->type != PJ_JSON_VAL_ARRAY*/) - { - CHECK( st->writer( st->space, - (unsigned)(PJ_JSON_NAME_MIN_LEN - - elem->name.slen), - st->user_data) ); - } - } + CHECK( st->writer( st->indent_buf, st->indent, st->user_data) ); + if ((flags & NO_NAME)==0) { + CHECK( st->writer( "\"", 1, st->user_data) ); + CHECK( write_string_escaped(&elem->name, st) ); + CHECK( st->writer( "\": ", 3, st->user_data) ); + if (elem->name.slen < PJ_JSON_NAME_MIN_LEN /*&& + elem->type != PJ_JSON_VAL_OBJ && + elem->type != PJ_JSON_VAL_ARRAY*/) + { + CHECK( st->writer( st->space, + (unsigned)(PJ_JSON_NAME_MIN_LEN - + elem->name.slen), + st->user_data) ); + } + } } switch (elem->type) { case PJ_JSON_VAL_NULL: - CHECK( st->writer( "null", 4, st->user_data) ); - break; + CHECK( st->writer( "null", 4, st->user_data) ); + break; case PJ_JSON_VAL_BOOL: - if (elem->value.is_true) - CHECK( st->writer( "true", 4, st->user_data) ); - else - CHECK( st->writer( "false", 5, st->user_data) ); - break; + if (elem->value.is_true) + CHECK( st->writer( "true", 4, st->user_data) ); + else + CHECK( st->writer( "false", 5, st->user_data) ); + break; case PJ_JSON_VAL_NUMBER: - { - char num_buf[65]; - int len; - - if (elem->value.num == (int)elem->value.num) - len = pj_ansi_snprintf(num_buf, sizeof(num_buf), "%d", - (int)elem->value.num); - else - len = pj_ansi_snprintf(num_buf, sizeof(num_buf), "%f", - elem->value.num); - - if (len < 0 || len >= sizeof(num_buf)) - return PJ_ETOOBIG; - CHECK( st->writer( num_buf, len, st->user_data) ); - } - break; + { + char num_buf[65]; + int len; + + if (elem->value.num == (int)elem->value.num) + len = pj_ansi_snprintf(num_buf, sizeof(num_buf), "%d", + (int)elem->value.num); + else + len = pj_ansi_snprintf(num_buf, sizeof(num_buf), "%f", + elem->value.num); + + if (len < 0 || len >= sizeof(num_buf)) + return PJ_ETOOBIG; + CHECK( st->writer( num_buf, len, st->user_data) ); + } + break; case PJ_JSON_VAL_STRING: - CHECK( st->writer( "\"", 1, st->user_data) ); - CHECK( write_string_escaped( &elem->value.str, st) ); - CHECK( st->writer( "\"", 1, st->user_data) ); - break; + CHECK( st->writer( "\"", 1, st->user_data) ); + CHECK( write_string_escaped( &elem->value.str, st) ); + CHECK( st->writer( "\"", 1, st->user_data) ); + break; case PJ_JSON_VAL_ARRAY: - CHECK( write_children(&elem->value.children, "[]", st) ); - break; + CHECK( write_children(&elem->value.children, "[]", st) ); + break; case PJ_JSON_VAL_OBJ: - CHECK( write_children(&elem->value.children, "{}", st) ); - break; + CHECK( write_children(&elem->value.children, "{}", st) ); + break; default: - pj_assert(!"Unhandled value type"); + pj_assert(!"Unhandled value type"); } return PJ_SUCCESS; @@ -611,9 +610,9 @@ PJ_DEF(pj_status_t) pj_json_writef( const pj_json_elem *elem, PJ_ASSERT_RETURN(elem && writer, PJ_EINVAL); - st.writer = writer; - st.user_data = user_data; - st.indent = 0; + st.writer = writer; + st.user_data = user_data; + st.indent = 0; pj_memset(st.indent_buf, ' ', MAX_INDENT); pj_memset(st.space, ' ', PJ_JSON_NAME_MIN_LEN); diff --git a/pjlib-util/src/pjlib-util/md5.c b/pjlib-util/src/pjlib-util/md5.c index 495758df04..1c538f34d9 100644 --- a/pjlib-util/src/pjlib-util/md5.c +++ b/pjlib-util/src/pjlib-util/md5.c @@ -1,10 +1,9 @@ -/* $Id$ */ /* * This is the implementation of MD5 algorithm, based on the code * written by Colin Plumb. This file is put in public domain. */ #include -#include /* pj_memcpy */ +#include /* pj_memcpy */ /* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was @@ -27,7 +26,7 @@ #endif #ifndef HIGHFIRST -#define byteReverse(buf, len) /* Nothing */ +#define byteReverse(buf, len) /* Nothing */ #else static void byteReverse(unsigned char *buf, unsigned longs); @@ -39,10 +38,10 @@ static void byteReverse(unsigned char *buf, unsigned longs) { pj_uint32_t t; do { - t = (pj_uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 | - ((unsigned) buf[1] << 8 | buf[0]); - *(pj_uint32_t *) buf = t; - buf += 4; + t = (pj_uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 | + ((unsigned) buf[1] << 8 | buf[0]); + *(pj_uint32_t *) buf = t; + buf += 4; } while (--longs); } #endif @@ -71,7 +70,7 @@ PJ_DEF(void) pj_md5_init(pj_md5_context *ctx) * of bytes. */ PJ_DEF(void) pj_md5_update( pj_md5_context *ctx, - unsigned char const *buf, unsigned len) + unsigned char const *buf, unsigned len) { pj_uint32_t t; @@ -79,35 +78,35 @@ PJ_DEF(void) pj_md5_update( pj_md5_context *ctx, t = ctx->bits[0]; if ((ctx->bits[0] = t + ((pj_uint32_t) len << 3)) < t) - ctx->bits[1]++; /* Carry from low to high */ + ctx->bits[1]++; /* Carry from low to high */ ctx->bits[1] += len >> 29; - t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ + t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ /* Handle any leading odd-sized chunks */ if (t) { - unsigned char *p = (unsigned char *) ctx->in + t; - - t = 64 - t; - if (len < t) { - pj_memcpy(p, buf, len); - return; - } - pj_memcpy(p, buf, t); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (pj_uint32_t *) ctx->in); - buf += t; - len -= t; + unsigned char *p = (unsigned char *) ctx->in + t; + + t = 64 - t; + if (len < t) { + pj_memcpy(p, buf, len); + return; + } + pj_memcpy(p, buf, t); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (pj_uint32_t *) ctx->in); + buf += t; + len -= t; } /* Process data in 64-byte chunks */ while (len >= 64) { - pj_memcpy(ctx->in, buf, 64); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (pj_uint32_t *) ctx->in); - buf += 64; - len -= 64; + pj_memcpy(ctx->in, buf, 64); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (pj_uint32_t *) ctx->in); + buf += 64; + len -= 64; } /* Handle any remaining bytes of data. */ @@ -137,16 +136,16 @@ PJ_DEF(void) pj_md5_final(pj_md5_context *ctx, unsigned char digest[16]) /* Pad out to 56 mod 64 */ if (count < 8) { - /* Two lots of padding: Pad the first block to 64 bytes */ - pj_bzero(p, count); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (pj_uint32_t *) ctx->in); + /* Two lots of padding: Pad the first block to 64 bytes */ + pj_bzero(p, count); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (pj_uint32_t *) ctx->in); - /* Now fill the next block with 56 bytes */ - pj_bzero(ctx->in, 56); + /* Now fill the next block with 56 bytes */ + pj_bzero(ctx->in, 56); } else { - /* Pad block to 56 bytes */ - pj_bzero(p, count - 8); + /* Pad block to 56 bytes */ + pj_bzero(p, count - 8); } byteReverse(ctx->in, 14); @@ -159,7 +158,7 @@ PJ_DEF(void) pj_md5_final(pj_md5_context *ctx, unsigned char digest[16]) MD5Transform(ctx->buf, (pj_uint32_t *) ctx->in); byteReverse((unsigned char *) ctx->buf, 4); pj_memcpy(digest, ctx->buf, 16); - pj_bzero(ctx, sizeof(*ctx)); /* In case it's sensitive */ + pj_bzero(ctx, sizeof(*ctx)); /* In case it's sensitive */ } #ifndef ASM_MD5 @@ -174,7 +173,7 @@ PJ_DEF(void) pj_md5_final(pj_md5_context *ctx, unsigned char digest[16]) /* This is the central step in the MD5 algorithm. */ #define MD5STEP(f, w, x, y, z, data, s) \ - ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) + ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to diff --git a/pjlib-util/src/pjlib-util/pcap.c b/pjlib-util/src/pjlib-util/pcap.c index 03a1c7c2e6..56857df296 100644 --- a/pjlib-util/src/pjlib-util/pcap.c +++ b/pjlib-util/src/pjlib-util/pcap.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,7 +26,7 @@ #include #if 0 -# define TRACE_(x) PJ_LOG(5,x) +# define TRACE_(x) PJ_LOG(5,x) #else # define TRACE_(x) #endif @@ -68,25 +67,25 @@ typedef pj_uint8_t pj_pcap_eth_hdr[14]; typedef struct pj_pcap_ip_hdr { - pj_uint8_t v_ihl; - pj_uint8_t tos; - pj_uint16_t len; - pj_uint16_t id; - pj_uint16_t flags_fragment; - pj_uint8_t ttl; - pj_uint8_t proto; - pj_uint16_t csum; - pj_uint32_t ip_src; - pj_uint32_t ip_dst; + pj_uint8_t v_ihl; + pj_uint8_t tos; + pj_uint16_t len; + pj_uint16_t id; + pj_uint16_t flags_fragment; + pj_uint8_t ttl; + pj_uint8_t proto; + pj_uint16_t csum; + pj_uint32_t ip_src; + pj_uint32_t ip_dst; } pj_pcap_ip_hdr; /* Implementation of pcap file */ struct pj_pcap_file { - char obj_name[PJ_MAX_OBJ_NAME]; + char obj_name[PJ_MAX_OBJ_NAME]; pj_oshandle_t fd; - pj_bool_t swap; - pj_pcap_hdr hdr; + pj_bool_t swap; + pj_pcap_hdr hdr; pj_pcap_filter filter; }; @@ -100,8 +99,8 @@ PJ_DEF(void) pj_pcap_filter_default(pj_pcap_filter *filter) /* Open pcap file */ PJ_DEF(pj_status_t) pj_pcap_open(pj_pool_t *pool, - const char *path, - pj_pcap_file **p_file) + const char *path, + pj_pcap_file **p_file) { pj_pcap_file *file; pj_ssize_t sz; @@ -111,13 +110,13 @@ PJ_DEF(pj_status_t) pj_pcap_open(pj_pool_t *pool, /* More sanity checks */ TRACE_(("pcap", "sizeof(pj_pcap_eth_hdr)=%d", - sizeof(pj_pcap_eth_hdr))); + sizeof(pj_pcap_eth_hdr))); PJ_ASSERT_RETURN(sizeof(pj_pcap_eth_hdr)==14, PJ_EBUG); TRACE_(("pcap", "sizeof(pj_pcap_ip_hdr)=%d", - sizeof(pj_pcap_ip_hdr))); + sizeof(pj_pcap_ip_hdr))); PJ_ASSERT_RETURN(sizeof(pj_pcap_ip_hdr)==20, PJ_EBUG); TRACE_(("pcap", "sizeof(pj_pcap_udp_hdr)=%d", - sizeof(pj_pcap_udp_hdr))); + sizeof(pj_pcap_udp_hdr))); PJ_ASSERT_RETURN(sizeof(pj_pcap_udp_hdr)==8, PJ_EBUG); file = PJ_POOL_ZALLOC_T(pool, pj_pcap_file); @@ -126,26 +125,26 @@ PJ_DEF(pj_status_t) pj_pcap_open(pj_pool_t *pool, status = pj_file_open(pool, path, PJ_O_RDONLY, &file->fd); if (status != PJ_SUCCESS) - return status; + return status; /* Read file pcap header */ sz = sizeof(file->hdr); status = pj_file_read(file->fd, &file->hdr, &sz); if (status != PJ_SUCCESS) { - pj_file_close(file->fd); - return status; + pj_file_close(file->fd); + return status; } /* Check magic number */ if (file->hdr.magic_number == 0xa1b2c3d4) { - file->swap = PJ_FALSE; + file->swap = PJ_FALSE; } else if (file->hdr.magic_number == 0xd4c3b2a1) { - file->swap = PJ_TRUE; - file->hdr.network = pj_ntohl(file->hdr.network); + file->swap = PJ_TRUE; + file->hdr.network = pj_ntohl(file->hdr.network); } else { - /* Not PCAP file */ - pj_file_close(file->fd); - return PJ_EINVALIDOP; + /* Not PCAP file */ + pj_file_close(file->fd); + return PJ_EINVALIDOP; } TRACE_((file->obj_name, "PCAP file %s opened", path)); @@ -164,7 +163,7 @@ PJ_DEF(pj_status_t) pj_pcap_close(pj_pcap_file *file) /* Setup filter */ PJ_DEF(pj_status_t) pj_pcap_set_filter(pj_pcap_file *file, - const pj_pcap_filter *fil) + const pj_pcap_filter *fil) { PJ_ASSERT_RETURN(file && fil, PJ_EINVAL); pj_memcpy(&file->filter, fil, sizeof(pj_pcap_filter)); @@ -173,15 +172,15 @@ PJ_DEF(pj_status_t) pj_pcap_set_filter(pj_pcap_file *file, /* Read file */ static pj_status_t read_file(pj_pcap_file *file, - void *buf, - pj_ssize_t *sz) + void *buf, + pj_ssize_t *sz) { pj_status_t status; status = pj_file_read(file->fd, buf, sz); if (status != PJ_SUCCESS) - return status; + return status; if (*sz == 0) - return PJ_EEOF; + return PJ_EEOF; return PJ_SUCCESS; } @@ -190,206 +189,206 @@ static pj_status_t skip(pj_oshandle_t fd, pj_off_t bytes) pj_status_t status; status = pj_file_setpos(fd, bytes, PJ_SEEK_CUR); if (status != PJ_SUCCESS) - return status; + return status; return PJ_SUCCESS; } #define SKIP_PKT() \ - if (rec_incl > sz_read) { \ - status = skip(file->fd, rec_incl-sz_read);\ - if (status != PJ_SUCCESS) \ - return status; \ - } + if (rec_incl > sz_read) { \ + status = skip(file->fd, rec_incl-sz_read);\ + if (status != PJ_SUCCESS) \ + return status; \ + } /* Read UDP packet */ PJ_DEF(pj_status_t) pj_pcap_read_udp(pj_pcap_file *file, - pj_pcap_udp_hdr *udp_hdr, - pj_uint8_t *udp_payload, - pj_size_t *udp_payload_size) + pj_pcap_udp_hdr *udp_hdr, + pj_uint8_t *udp_payload, + pj_size_t *udp_payload_size) { PJ_ASSERT_RETURN(file && udp_payload && udp_payload_size, PJ_EINVAL); PJ_ASSERT_RETURN(*udp_payload_size, PJ_EINVAL); /* Check data link type in PCAP file header */ if ((file->filter.link && - file->hdr.network != (pj_uint32_t)file->filter.link) || - file->hdr.network != PJ_PCAP_LINK_TYPE_ETH) + file->hdr.network != (pj_uint32_t)file->filter.link) || + file->hdr.network != PJ_PCAP_LINK_TYPE_ETH) { - /* Link header other than Ethernet is not supported for now */ - return PJ_ENOTSUP; + /* Link header other than Ethernet is not supported for now */ + return PJ_ENOTSUP; } /* Loop until we have the packet */ for (;;) { - union { - pj_pcap_rec_hdr rec; - pj_pcap_eth_hdr eth; - pj_pcap_ip_hdr ip; - pj_pcap_udp_hdr udp; - } tmp; - unsigned rec_incl; - pj_ssize_t sz; - pj_size_t sz_read = 0; - char addr[PJ_INET_ADDRSTRLEN]; - pj_status_t status; - - TRACE_((file->obj_name, "Reading packet..")); - pj_bzero(&addr, sizeof(addr)); - - /* Read PCAP packet header */ - sz = sizeof(tmp.rec); - status = read_file(file, &tmp.rec, &sz); - if (status != PJ_SUCCESS) { - TRACE_((file->obj_name, "read_file() error: %d", status)); - return status; - } - - rec_incl = tmp.rec.incl_len; - - /* Swap byte ordering */ - if (file->swap) { - tmp.rec.incl_len = pj_ntohl(tmp.rec.incl_len); - tmp.rec.orig_len = pj_ntohl(tmp.rec.orig_len); - tmp.rec.ts_sec = pj_ntohl(tmp.rec.ts_sec); - tmp.rec.ts_usec = pj_ntohl(tmp.rec.ts_usec); - } - - /* Read link layer header */ - switch (file->hdr.network) { - case PJ_PCAP_LINK_TYPE_ETH: - sz = sizeof(tmp.eth); - status = read_file(file, &tmp.eth, &sz); - break; - default: - TRACE_((file->obj_name, "Error: link layer not Ethernet")); - return PJ_ENOTSUP; - } - - if (status != PJ_SUCCESS) { - TRACE_((file->obj_name, "Error reading Eth header: %d", status)); - return status; - } - - sz_read += sz; - - /* Read IP header */ - sz = sizeof(tmp.ip); - status = read_file(file, &tmp.ip, &sz); - if (status != PJ_SUCCESS) { - TRACE_((file->obj_name, "Error reading IP header: %d", status)); - return status; - } - - sz_read += sz; - - /* Skip if IP source mismatch */ - if (file->filter.ip_src && tmp.ip.ip_src != file->filter.ip_src) { - TRACE_((file->obj_name, "IP source %s mismatch, skipping", - pj_inet_ntop2(pj_AF_INET(), (pj_in_addr*)&tmp.ip.ip_src, - addr, sizeof(addr)))); - SKIP_PKT(); - continue; - } - - /* Skip if IP destination mismatch */ - if (file->filter.ip_dst && tmp.ip.ip_dst != file->filter.ip_dst) { - TRACE_((file->obj_name, "IP detination %s mismatch, skipping", - pj_inet_ntop2(pj_AF_INET(), (pj_in_addr*)&tmp.ip.ip_dst, - addr, sizeof(addr)))); - SKIP_PKT(); - continue; - } - - /* Skip if proto mismatch */ - if (file->filter.proto && tmp.ip.proto != file->filter.proto) { - TRACE_((file->obj_name, "IP proto %d mismatch, skipping", - tmp.ip.proto)); - SKIP_PKT(); - continue; - } - - /* Read transport layer header */ - switch (tmp.ip.proto) { - case PJ_PCAP_PROTO_TYPE_UDP: - sz = sizeof(tmp.udp); - status = read_file(file, &tmp.udp, &sz); - if (status != PJ_SUCCESS) { - TRACE_((file->obj_name, "Error reading UDP header: %d",status)); - return status; - } - - sz_read += sz; - - /* Skip if source port mismatch */ - if (file->filter.src_port && - tmp.udp.src_port != file->filter.src_port) - { - TRACE_((file->obj_name, "UDP src port %d mismatch, skipping", - pj_ntohs(tmp.udp.src_port))); - SKIP_PKT(); - continue; - } - - /* Skip if destination port mismatch */ - if (file->filter.dst_port && - tmp.udp.dst_port != file->filter.dst_port) - { - TRACE_((file->obj_name, "UDP dst port %d mismatch, skipping", - pj_ntohs(tmp.udp.dst_port))); - SKIP_PKT(); - continue; - } - - /* Copy UDP header if caller wants it */ - if (udp_hdr) { - pj_memcpy(udp_hdr, &tmp.udp, sizeof(*udp_hdr)); - } - - /* Calculate payload size */ - sz = pj_ntohs(tmp.udp.len) - sizeof(tmp.udp); - break; - default: - TRACE_((file->obj_name, "Not UDP, skipping")); - SKIP_PKT(); - continue; - } - - /* Check if payload fits the buffer */ - if (sz > (pj_ssize_t)*udp_payload_size) { - TRACE_((file->obj_name, - "Error: packet too large (%d bytes required)", sz)); - SKIP_PKT(); - return PJ_ETOOSMALL; - } - - /* Read the payload */ - status = read_file(file, udp_payload, &sz); - if (status != PJ_SUCCESS) { - TRACE_((file->obj_name, "Error reading payload: %d", status)); - return status; - } - - sz_read += sz; - - *udp_payload_size = sz; - - // Some layers may have trailer, e.g: link eth2. - /* Check that we've read all the packets */ - //PJ_ASSERT_RETURN(sz_read == rec_incl, PJ_EBUG); - - /* Skip trailer */ - while (sz_read < rec_incl) { - sz = rec_incl - sz_read; - status = read_file(file, &tmp.eth, &sz); - if (status != PJ_SUCCESS) { - TRACE_((file->obj_name, "Error reading trailer: %d", status)); - return status; - } - sz_read += sz; - } - - return PJ_SUCCESS; + union { + pj_pcap_rec_hdr rec; + pj_pcap_eth_hdr eth; + pj_pcap_ip_hdr ip; + pj_pcap_udp_hdr udp; + } tmp; + unsigned rec_incl; + pj_ssize_t sz; + pj_size_t sz_read = 0; + char addr[PJ_INET_ADDRSTRLEN]; + pj_status_t status; + + TRACE_((file->obj_name, "Reading packet..")); + pj_bzero(&addr, sizeof(addr)); + + /* Read PCAP packet header */ + sz = sizeof(tmp.rec); + status = read_file(file, &tmp.rec, &sz); + if (status != PJ_SUCCESS) { + TRACE_((file->obj_name, "read_file() error: %d", status)); + return status; + } + + rec_incl = tmp.rec.incl_len; + + /* Swap byte ordering */ + if (file->swap) { + tmp.rec.incl_len = pj_ntohl(tmp.rec.incl_len); + tmp.rec.orig_len = pj_ntohl(tmp.rec.orig_len); + tmp.rec.ts_sec = pj_ntohl(tmp.rec.ts_sec); + tmp.rec.ts_usec = pj_ntohl(tmp.rec.ts_usec); + } + + /* Read link layer header */ + switch (file->hdr.network) { + case PJ_PCAP_LINK_TYPE_ETH: + sz = sizeof(tmp.eth); + status = read_file(file, &tmp.eth, &sz); + break; + default: + TRACE_((file->obj_name, "Error: link layer not Ethernet")); + return PJ_ENOTSUP; + } + + if (status != PJ_SUCCESS) { + TRACE_((file->obj_name, "Error reading Eth header: %d", status)); + return status; + } + + sz_read += sz; + + /* Read IP header */ + sz = sizeof(tmp.ip); + status = read_file(file, &tmp.ip, &sz); + if (status != PJ_SUCCESS) { + TRACE_((file->obj_name, "Error reading IP header: %d", status)); + return status; + } + + sz_read += sz; + + /* Skip if IP source mismatch */ + if (file->filter.ip_src && tmp.ip.ip_src != file->filter.ip_src) { + TRACE_((file->obj_name, "IP source %s mismatch, skipping", + pj_inet_ntop2(pj_AF_INET(), (pj_in_addr*)&tmp.ip.ip_src, + addr, sizeof(addr)))); + SKIP_PKT(); + continue; + } + + /* Skip if IP destination mismatch */ + if (file->filter.ip_dst && tmp.ip.ip_dst != file->filter.ip_dst) { + TRACE_((file->obj_name, "IP detination %s mismatch, skipping", + pj_inet_ntop2(pj_AF_INET(), (pj_in_addr*)&tmp.ip.ip_dst, + addr, sizeof(addr)))); + SKIP_PKT(); + continue; + } + + /* Skip if proto mismatch */ + if (file->filter.proto && tmp.ip.proto != file->filter.proto) { + TRACE_((file->obj_name, "IP proto %d mismatch, skipping", + tmp.ip.proto)); + SKIP_PKT(); + continue; + } + + /* Read transport layer header */ + switch (tmp.ip.proto) { + case PJ_PCAP_PROTO_TYPE_UDP: + sz = sizeof(tmp.udp); + status = read_file(file, &tmp.udp, &sz); + if (status != PJ_SUCCESS) { + TRACE_((file->obj_name, "Error reading UDP header: %d",status)); + return status; + } + + sz_read += sz; + + /* Skip if source port mismatch */ + if (file->filter.src_port && + tmp.udp.src_port != file->filter.src_port) + { + TRACE_((file->obj_name, "UDP src port %d mismatch, skipping", + pj_ntohs(tmp.udp.src_port))); + SKIP_PKT(); + continue; + } + + /* Skip if destination port mismatch */ + if (file->filter.dst_port && + tmp.udp.dst_port != file->filter.dst_port) + { + TRACE_((file->obj_name, "UDP dst port %d mismatch, skipping", + pj_ntohs(tmp.udp.dst_port))); + SKIP_PKT(); + continue; + } + + /* Copy UDP header if caller wants it */ + if (udp_hdr) { + pj_memcpy(udp_hdr, &tmp.udp, sizeof(*udp_hdr)); + } + + /* Calculate payload size */ + sz = pj_ntohs(tmp.udp.len) - sizeof(tmp.udp); + break; + default: + TRACE_((file->obj_name, "Not UDP, skipping")); + SKIP_PKT(); + continue; + } + + /* Check if payload fits the buffer */ + if (sz > (pj_ssize_t)*udp_payload_size) { + TRACE_((file->obj_name, + "Error: packet too large (%d bytes required)", sz)); + SKIP_PKT(); + return PJ_ETOOSMALL; + } + + /* Read the payload */ + status = read_file(file, udp_payload, &sz); + if (status != PJ_SUCCESS) { + TRACE_((file->obj_name, "Error reading payload: %d", status)); + return status; + } + + sz_read += sz; + + *udp_payload_size = sz; + + // Some layers may have trailer, e.g: link eth2. + /* Check that we've read all the packets */ + //PJ_ASSERT_RETURN(sz_read == rec_incl, PJ_EBUG); + + /* Skip trailer */ + while (sz_read < rec_incl) { + sz = rec_incl - sz_read; + status = read_file(file, &tmp.eth, &sz); + if (status != PJ_SUCCESS) { + TRACE_((file->obj_name, "Error reading trailer: %d", status)); + return status; + } + sz_read += sz; + } + + return PJ_SUCCESS; } /* Does not reach here */ diff --git a/pjlib-util/src/pjlib-util/resolver.c b/pjlib-util/src/pjlib-util/resolver.c index ad1aee5ef8..409f82ba2a 100644 --- a/pjlib-util/src/pjlib-util/resolver.c +++ b/pjlib-util/src/pjlib-util/resolver.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,7 +34,7 @@ #include -#define THIS_FILE "resolver.c" +#define THIS_FILE "resolver.c" /* Check that maximum DNS nameservers is not too large. @@ -46,15 +45,15 @@ #endif -#define RES_HASH_TABLE_SIZE 127 /**< Hash table size (must be 2^n-1 */ -#define PORT 53 /**< Default NS port. */ -#define Q_HASH_TABLE_SIZE 127 /**< Query hash table size */ -#define TIMER_SIZE 127 /**< Initial number of timers. */ -#define MAX_FD 3 /**< Maximum internal sockets. */ +#define RES_HASH_TABLE_SIZE 127 /**< Hash table size (must be 2^n-1 */ +#define PORT 53 /**< Default NS port. */ +#define Q_HASH_TABLE_SIZE 127 /**< Query hash table size */ +#define TIMER_SIZE 127 /**< Initial number of timers. */ +#define MAX_FD 3 /**< Maximum internal sockets. */ -#define RES_BUF_SZ PJ_DNS_RESOLVER_RES_BUF_SIZE -#define UDPSZ PJ_DNS_RESOLVER_MAX_UDP_SIZE -#define TMP_SZ PJ_DNS_RESOLVER_TMP_BUF_SIZE +#define RES_BUF_SZ PJ_DNS_RESOLVER_RES_BUF_SIZE +#define UDPSZ PJ_DNS_RESOLVER_MAX_UDP_SIZE +#define TMP_SZ PJ_DNS_RESOLVER_TMP_BUF_SIZE /* Nameserver state */ @@ -80,16 +79,16 @@ static const char *state_names[3] = */ struct nameserver { - pj_sockaddr addr; /**< Server address. */ + pj_sockaddr addr; /**< Server address. */ - enum ns_state state; /**< Nameserver state. */ - pj_time_val state_expiry; /**< Time set next state. */ - pj_time_val rt_delay; /**< Response time. */ + enum ns_state state; /**< Nameserver state. */ + pj_time_val state_expiry; /**< Time set next state. */ + pj_time_val rt_delay; /**< Response time. */ /* For calculating rt_delay: */ - pj_uint16_t q_id; /**< Query ID. */ - pj_time_val sent_time; /**< Time this query is sent. */ + pj_uint16_t q_id; /**< Query ID. */ + pj_time_val sent_time; /**< Time this query is sent. */ }; @@ -105,8 +104,8 @@ struct query_head /* Key to look for outstanding query and/or cached response */ struct res_key { - pj_uint16_t qtype; /**< Query type. */ - char name[PJ_MAX_HOSTNAME]; /**< Name being queried */ + pj_uint16_t qtype; /**< Query type. */ + char name[PJ_MAX_HOSTNAME]; /**< Name being queried */ }; @@ -128,21 +127,21 @@ struct res_key */ struct pj_dns_async_query { - PJ_DECL_LIST_MEMBER(pj_dns_async_query); /**< List member. */ + PJ_DECL_LIST_MEMBER(pj_dns_async_query); /**< List member. */ - pj_dns_resolver *resolver; /**< The resolver instance. */ - pj_uint16_t id; /**< Transaction ID. */ + pj_dns_resolver *resolver; /**< The resolver instance. */ + pj_uint16_t id; /**< Transaction ID. */ - unsigned transmit_cnt; /**< Number of transmissions. */ + unsigned transmit_cnt; /**< Number of transmissions. */ - struct res_key key; /**< Key to index this query. */ - pj_hash_entry_buf hbufid; /**< Hash buffer 1 */ - pj_hash_entry_buf hbufkey; /**< Hash buffer 2 */ - pj_timer_entry timer_entry; /**< Timer to manage timeouts */ - unsigned options; /**< Query options. */ - void *user_data; /**< Application data. */ - pj_dns_callback *cb; /**< Callback to be called. */ - struct query_head child_head; /**< Child queries list head. */ + struct res_key key; /**< Key to index this query. */ + pj_hash_entry_buf hbufid; /**< Hash buffer 1 */ + pj_hash_entry_buf hbufkey; /**< Hash buffer 2 */ + pj_timer_entry timer_entry; /**< Timer to manage timeouts */ + unsigned options; /**< Query options. */ + void *user_data; /**< Application data. */ + pj_dns_callback *cb; /**< Callback to be called. */ + struct query_head child_head; /**< Child queries list head. */ }; @@ -153,72 +152,72 @@ struct cached_res { PJ_DECL_LIST_MEMBER(struct cached_res); - pj_pool_t *pool; /**< Cache's pool. */ - struct res_key key; /**< Resource key. */ - pj_hash_entry_buf hbuf; /**< Hash buffer */ - pj_time_val expiry_time; /**< Expiration time. */ - pj_dns_parsed_packet *pkt; /**< The response packet. */ - unsigned ref_cnt; /**< Reference counter. */ + pj_pool_t *pool; /**< Cache's pool. */ + struct res_key key; /**< Resource key. */ + pj_hash_entry_buf hbuf; /**< Hash buffer */ + pj_time_val expiry_time; /**< Expiration time. */ + pj_dns_parsed_packet *pkt; /**< The response packet. */ + unsigned ref_cnt; /**< Reference counter. */ }; /* Resolver entry */ struct pj_dns_resolver { - pj_str_t name; /**< Resolver instance name for id. */ + pj_str_t name; /**< Resolver instance name for id. */ /* Internals */ - pj_pool_t *pool; /**< Internal pool. */ - pj_grp_lock_t *grp_lock; /**< Group lock protection. */ - pj_bool_t own_timer; /**< Do we own timer? */ - pj_timer_heap_t *timer; /**< Timer instance. */ - pj_bool_t own_ioqueue; /**< Do we own ioqueue? */ - pj_ioqueue_t *ioqueue; /**< Ioqueue instance. */ - char tmp_pool[TMP_SZ];/**< Temporary pool buffer. */ + pj_pool_t *pool; /**< Internal pool. */ + pj_grp_lock_t *grp_lock; /**< Group lock protection. */ + pj_bool_t own_timer; /**< Do we own timer? */ + pj_timer_heap_t *timer; /**< Timer instance. */ + pj_bool_t own_ioqueue; /**< Do we own ioqueue? */ + pj_ioqueue_t *ioqueue; /**< Ioqueue instance. */ + char tmp_pool[TMP_SZ];/**< Temporary pool buffer. */ /* Socket */ - pj_sock_t udp_sock; /**< UDP socket. */ - pj_ioqueue_key_t *udp_key; /**< UDP socket ioqueue key. */ - unsigned char udp_rx_pkt[UDPSZ];/**< UDP receive buffer. */ - unsigned char udp_tx_pkt[UDPSZ];/**< UDP transmit buffer. */ - pj_ioqueue_op_key_t udp_op_rx_key; /**< UDP read operation key. */ - pj_ioqueue_op_key_t udp_op_tx_key; /**< UDP write operation key. */ - pj_sockaddr udp_src_addr; /**< Source address of packet */ - int udp_addr_len; /**< Source address length. */ + pj_sock_t udp_sock; /**< UDP socket. */ + pj_ioqueue_key_t *udp_key; /**< UDP socket ioqueue key. */ + unsigned char udp_rx_pkt[UDPSZ];/**< UDP receive buffer. */ + unsigned char udp_tx_pkt[UDPSZ];/**< UDP transmit buffer. */ + pj_ioqueue_op_key_t udp_op_rx_key; /**< UDP read operation key. */ + pj_ioqueue_op_key_t udp_op_tx_key; /**< UDP write operation key. */ + pj_sockaddr udp_src_addr; /**< Source address of packet */ + int udp_addr_len; /**< Source address length. */ #if PJ_HAS_IPV6 /* IPv6 socket */ - pj_sock_t udp6_sock; /**< UDP socket. */ - pj_ioqueue_key_t *udp6_key; /**< UDP socket ioqueue key. */ - unsigned char udp6_rx_pkt[UDPSZ];/**< UDP receive buffer. */ - //unsigned char udp6_tx_pkt[UDPSZ];/**< UDP transmit buffer. */ - pj_ioqueue_op_key_t udp6_op_rx_key;/**< UDP read operation key. */ - pj_ioqueue_op_key_t udp6_op_tx_key;/**< UDP write operation key. */ - pj_sockaddr udp6_src_addr; /**< Source address of packet */ - int udp6_addr_len; /**< Source address length. */ + pj_sock_t udp6_sock; /**< UDP socket. */ + pj_ioqueue_key_t *udp6_key; /**< UDP socket ioqueue key. */ + unsigned char udp6_rx_pkt[UDPSZ];/**< UDP receive buffer. */ + //unsigned char udp6_tx_pkt[UDPSZ];/**< UDP transmit buffer. */ + pj_ioqueue_op_key_t udp6_op_rx_key;/**< UDP read operation key. */ + pj_ioqueue_op_key_t udp6_op_tx_key;/**< UDP write operation key. */ + pj_sockaddr udp6_src_addr; /**< Source address of packet */ + int udp6_addr_len; /**< Source address length. */ #endif /* Settings */ - pj_dns_settings settings; /**< Resolver settings. */ + pj_dns_settings settings; /**< Resolver settings. */ /* Nameservers */ - unsigned ns_count; /**< Number of name servers. */ - struct nameserver ns[PJ_DNS_RESOLVER_MAX_NS]; /**< Array of NS. */ + unsigned ns_count; /**< Number of name servers. */ + struct nameserver ns[PJ_DNS_RESOLVER_MAX_NS]; /**< Array of NS. */ /* Last DNS transaction ID used. */ - pj_uint16_t last_id; + pj_uint16_t last_id; /* Hash table for cached response */ - pj_hash_table_t *hrescache; /**< Cached response in hash table */ + pj_hash_table_t *hrescache; /**< Cached response in hash table */ /* Pending asynchronous query, hashed by transaction ID. */ - pj_hash_table_t *hquerybyid; + pj_hash_table_t *hquerybyid; /* Pending asynchronous query, hashed by "res_key" */ - pj_hash_table_t *hquerybyres; + pj_hash_table_t *hquerybyres; /* Query entries free list */ - struct query_head query_free_nodes; + struct query_head query_free_nodes; }; @@ -229,12 +228,12 @@ static void on_read_complete(pj_ioqueue_key_t *key, /* Callback to be called when query has timed out */ static void on_timeout( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry); + struct pj_timer_entry *entry); /* Select which nameserver to use */ static pj_status_t select_nameservers(pj_dns_resolver *resolver, - unsigned *count, - unsigned servers[]); + unsigned *count, + unsigned servers[]); /* Destructor */ static void dns_resolver_on_destroy(void *member); @@ -244,22 +243,22 @@ static void close_sock(pj_dns_resolver *resv) { /* Close existing socket */ if (resv->udp_key != NULL) { - pj_ioqueue_unregister(resv->udp_key); - resv->udp_key = NULL; - resv->udp_sock = PJ_INVALID_SOCKET; + pj_ioqueue_unregister(resv->udp_key); + resv->udp_key = NULL; + resv->udp_sock = PJ_INVALID_SOCKET; } else if (resv->udp_sock != PJ_INVALID_SOCKET) { - pj_sock_close(resv->udp_sock); - resv->udp_sock = PJ_INVALID_SOCKET; + pj_sock_close(resv->udp_sock); + resv->udp_sock = PJ_INVALID_SOCKET; } #if PJ_HAS_IPV6 if (resv->udp6_key != NULL) { - pj_ioqueue_unregister(resv->udp6_key); - resv->udp6_key = NULL; - resv->udp6_sock = PJ_INVALID_SOCKET; + pj_ioqueue_unregister(resv->udp6_key); + resv->udp6_key = NULL; + resv->udp6_sock = PJ_INVALID_SOCKET; } else if (resv->udp6_sock != PJ_INVALID_SOCKET) { - pj_sock_close(resv->udp6_sock); - resv->udp6_sock = PJ_INVALID_SOCKET; + pj_sock_close(resv->udp6_sock); + resv->udp6_sock = PJ_INVALID_SOCKET; } #endif } @@ -276,21 +275,21 @@ static pj_status_t init_sock(pj_dns_resolver *resv) /* Create the UDP socket */ status = pj_sock_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, &resv->udp_sock); if (status != PJ_SUCCESS) - return status; + return status; /* Bind to any address/port */ status = pj_sock_bind_in(resv->udp_sock, 0, 0); if (status != PJ_SUCCESS) - return status; + return status; /* Register to ioqueue */ pj_bzero(&socket_cb, sizeof(socket_cb)); socket_cb.on_read_complete = &on_read_complete; status = pj_ioqueue_register_sock2(resv->pool, resv->ioqueue, - resv->udp_sock, resv->grp_lock, - resv, &socket_cb, &resv->udp_key); + resv->udp_sock, resv->grp_lock, + resv, &socket_cb, &resv->udp_key); if (status != PJ_SUCCESS) - return status; + return status; pj_ioqueue_op_key_init(&resv->udp_op_rx_key, sizeof(resv->udp_op_rx_key)); pj_ioqueue_op_key_init(&resv->udp_op_tx_key, sizeof(resv->udp_op_tx_key)); @@ -299,11 +298,11 @@ static pj_status_t init_sock(pj_dns_resolver *resv) rx_pkt_size = sizeof(resv->udp_rx_pkt); resv->udp_addr_len = sizeof(resv->udp_src_addr); status = pj_ioqueue_recvfrom(resv->udp_key, &resv->udp_op_rx_key, - resv->udp_rx_pkt, &rx_pkt_size, - PJ_IOQUEUE_ALWAYS_ASYNC, - &resv->udp_src_addr, &resv->udp_addr_len); + resv->udp_rx_pkt, &rx_pkt_size, + PJ_IOQUEUE_ALWAYS_ASYNC, + &resv->udp_src_addr, &resv->udp_addr_len); if (status != PJ_EPENDING) - return status; + return status; #if PJ_HAS_IPV6 @@ -311,48 +310,48 @@ static pj_status_t init_sock(pj_dns_resolver *resv) /* Create the UDP socket */ status = pj_sock_socket(pj_AF_INET6(), pj_SOCK_DGRAM(), 0, - &resv->udp6_sock); + &resv->udp6_sock); if (status != PJ_SUCCESS) { - /* Skip IPv6 socket on system without IPv6 (see ticket #1953) */ - if (status == PJ_STATUS_FROM_OS(OSERR_EAFNOSUPPORT)) { - PJ_LOG(3,(resv->name.ptr, - "System does not support IPv6, resolver will " - "ignore any IPv6 nameservers")); - return PJ_SUCCESS; - } - return status; + /* Skip IPv6 socket on system without IPv6 (see ticket #1953) */ + if (status == PJ_STATUS_FROM_OS(OSERR_EAFNOSUPPORT)) { + PJ_LOG(3,(resv->name.ptr, + "System does not support IPv6, resolver will " + "ignore any IPv6 nameservers")); + return PJ_SUCCESS; + } + return status; } /* Bind to any address/port */ pj_sockaddr_init(pj_AF_INET6(), &bound_addr, NULL, 0); status = pj_sock_bind(resv->udp6_sock, &bound_addr, - pj_sockaddr_get_len(&bound_addr)); + pj_sockaddr_get_len(&bound_addr)); if (status != PJ_SUCCESS) - return status; + return status; /* Register to ioqueue */ pj_bzero(&socket_cb, sizeof(socket_cb)); socket_cb.on_read_complete = &on_read_complete; status = pj_ioqueue_register_sock2(resv->pool, resv->ioqueue, - resv->udp6_sock, resv->grp_lock, - resv, &socket_cb, &resv->udp6_key); + resv->udp6_sock, resv->grp_lock, + resv, &socket_cb, &resv->udp6_key); if (status != PJ_SUCCESS) - return status; + return status; pj_ioqueue_op_key_init(&resv->udp6_op_rx_key, - sizeof(resv->udp6_op_rx_key)); + sizeof(resv->udp6_op_rx_key)); pj_ioqueue_op_key_init(&resv->udp6_op_tx_key, - sizeof(resv->udp6_op_tx_key)); + sizeof(resv->udp6_op_tx_key)); /* Start asynchronous read to the UDP socket */ rx_pkt_size = sizeof(resv->udp6_rx_pkt); resv->udp6_addr_len = sizeof(resv->udp6_src_addr); status = pj_ioqueue_recvfrom(resv->udp6_key, &resv->udp6_op_rx_key, - resv->udp6_rx_pkt, &rx_pkt_size, - PJ_IOQUEUE_ALWAYS_ASYNC, - &resv->udp6_src_addr, &resv->udp6_addr_len); + resv->udp6_rx_pkt, &rx_pkt_size, + PJ_IOQUEUE_ALWAYS_ASYNC, + &resv->udp6_src_addr, &resv->udp6_addr_len); if (status != PJ_EPENDING) - return status; + return status; #else PJ_UNUSED_ARG(bound_addr); #endif @@ -377,11 +376,11 @@ PJ_DEF(void) pj_dns_settings_default(pj_dns_settings *s) * Create the resolver. */ PJ_DEF(pj_status_t) pj_dns_resolver_create( pj_pool_factory *pf, - const char *name, - unsigned options, - pj_timer_heap_t *timer, - pj_ioqueue_t *ioqueue, - pj_dns_resolver **p_resolver) + const char *name, + unsigned options, + pj_timer_heap_t *timer, + pj_ioqueue_t *ioqueue, + pj_dns_resolver **p_resolver) { pj_pool_t *pool; pj_dns_resolver *resv; @@ -391,12 +390,12 @@ PJ_DEF(pj_status_t) pj_dns_resolver_create( pj_pool_factory *pf, PJ_ASSERT_RETURN(pf && p_resolver, PJ_EINVAL); if (name == NULL) - name = THIS_FILE; + name = THIS_FILE; /* Create and initialize resolver instance */ pool = pj_pool_create(pf, name, 4000, 4000, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create pool and name */ resv = PJ_POOL_ZALLOC_T(pool, struct pj_dns_resolver); @@ -406,10 +405,10 @@ PJ_DEF(pj_status_t) pj_dns_resolver_create( pj_pool_factory *pf, /* Create group lock */ status = pj_grp_lock_create_w_handler(pool, NULL, resv, - &dns_resolver_on_destroy, - &resv->grp_lock); + &dns_resolver_on_destroy, + &resv->grp_lock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; pj_grp_lock_add_ref(resv->grp_lock); @@ -423,18 +422,18 @@ PJ_DEF(pj_status_t) pj_dns_resolver_create( pj_pool_factory *pf, /* Create the timer heap if one is not specified */ if (resv->timer == NULL) { - resv->own_timer = PJ_TRUE; - status = pj_timer_heap_create(pool, TIMER_SIZE, &resv->timer); - if (status != PJ_SUCCESS) - goto on_error; + resv->own_timer = PJ_TRUE; + status = pj_timer_heap_create(pool, TIMER_SIZE, &resv->timer); + if (status != PJ_SUCCESS) + goto on_error; } /* Create the ioqueue if one is not specified */ if (resv->ioqueue == NULL) { - resv->own_ioqueue = PJ_TRUE; - status = pj_ioqueue_create(pool, MAX_FD, &resv->ioqueue); - if (status != PJ_SUCCESS) - goto on_error; + resv->own_ioqueue = PJ_TRUE; + status = pj_ioqueue_create(pool, MAX_FD, &resv->ioqueue); + if (status != PJ_SUCCESS) + goto on_error; } /* Response cache hash table */ @@ -448,7 +447,7 @@ PJ_DEF(pj_status_t) pj_dns_resolver_create( pj_pool_factory *pf, /* Initialize the UDP socket */ status = init_sock(resv); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Looks like everything is okay */ *p_resolver = resv; @@ -471,56 +470,56 @@ void dns_resolver_on_destroy(void *member) * Destroy DNS resolver instance. */ PJ_DEF(pj_status_t) pj_dns_resolver_destroy( pj_dns_resolver *resolver, - pj_bool_t notify) + pj_bool_t notify) { pj_hash_iterator_t it_buf, *it; PJ_ASSERT_RETURN(resolver, PJ_EINVAL); if (notify) { - /* - * Notify pending queries if requested. - */ - it = pj_hash_first(resolver->hquerybyid, &it_buf); - while (it) { - pj_dns_async_query *q = (pj_dns_async_query *) - pj_hash_this(resolver->hquerybyid, it); - pj_dns_async_query *cq; - if (q->cb) - (*q->cb)(q->user_data, PJ_ECANCELLED, NULL); - - cq = q->child_head.next; - while (cq != (pj_dns_async_query*)&q->child_head) { - if (cq->cb) - (*cq->cb)(cq->user_data, PJ_ECANCELLED, NULL); - cq = cq->next; - } - it = pj_hash_next(resolver->hquerybyid, it); - } + /* + * Notify pending queries if requested. + */ + it = pj_hash_first(resolver->hquerybyid, &it_buf); + while (it) { + pj_dns_async_query *q = (pj_dns_async_query *) + pj_hash_this(resolver->hquerybyid, it); + pj_dns_async_query *cq; + if (q->cb) + (*q->cb)(q->user_data, PJ_ECANCELLED, NULL); + + cq = q->child_head.next; + while (cq != (pj_dns_async_query*)&q->child_head) { + if (cq->cb) + (*cq->cb)(cq->user_data, PJ_ECANCELLED, NULL); + cq = cq->next; + } + it = pj_hash_next(resolver->hquerybyid, it); + } } /* Destroy cached entries */ it = pj_hash_first(resolver->hrescache, &it_buf); while (it) { - struct cached_res *cache; + struct cached_res *cache; - cache = (struct cached_res*) pj_hash_this(resolver->hrescache, it); - pj_hash_set(NULL, resolver->hrescache, &cache->key, - sizeof(cache->key), 0, NULL); - pj_pool_release(cache->pool); + cache = (struct cached_res*) pj_hash_this(resolver->hrescache, it); + pj_hash_set(NULL, resolver->hrescache, &cache->key, + sizeof(cache->key), 0, NULL); + pj_pool_release(cache->pool); - it = pj_hash_first(resolver->hrescache, &it_buf); + it = pj_hash_first(resolver->hrescache, &it_buf); } if (resolver->own_timer && resolver->timer) { - pj_timer_heap_destroy(resolver->timer); - resolver->timer = NULL; + pj_timer_heap_destroy(resolver->timer); + resolver->timer = NULL; } close_sock(resolver); if (resolver->own_ioqueue && resolver->ioqueue) { - pj_ioqueue_destroy(resolver->ioqueue); - resolver->ioqueue = NULL; + pj_ioqueue_destroy(resolver->ioqueue); + resolver->ioqueue = NULL; } pj_grp_lock_dec_ref(resolver->grp_lock); @@ -534,9 +533,9 @@ PJ_DEF(pj_status_t) pj_dns_resolver_destroy( pj_dns_resolver *resolver, * Configure name servers for the DNS resolver. */ PJ_DEF(pj_status_t) pj_dns_resolver_set_ns( pj_dns_resolver *resolver, - unsigned count, - const pj_str_t servers[], - const pj_uint16_t ports[]) + unsigned count, + const pj_str_t servers[], + const pj_uint16_t ports[]) { unsigned i; pj_time_val now; @@ -548,7 +547,7 @@ PJ_DEF(pj_status_t) pj_dns_resolver_set_ns( pj_dns_resolver *resolver, pj_grp_lock_acquire(resolver->grp_lock); if (count > PJ_DNS_RESOLVER_MAX_NS) - count = PJ_DNS_RESOLVER_MAX_NS; + count = PJ_DNS_RESOLVER_MAX_NS; resolver->ns_count = 0; pj_bzero(resolver->ns, sizeof(resolver->ns)); @@ -556,21 +555,21 @@ PJ_DEF(pj_status_t) pj_dns_resolver_set_ns( pj_dns_resolver *resolver, pj_gettimeofday(&now); for (i=0; ins[i]; - - status = pj_sockaddr_init(pj_AF_INET(), &ns->addr, &servers[i], - (pj_uint16_t)(ports ? ports[i] : PORT)); - if (status != PJ_SUCCESS) - status = pj_sockaddr_init(pj_AF_INET6(), &ns->addr, &servers[i], - (pj_uint16_t)(ports ? ports[i] : PORT)); - if (status != PJ_SUCCESS) { - pj_grp_lock_release(resolver->grp_lock); - return PJLIB_UTIL_EDNSINNSADDR; - } - - ns->state = STATE_ACTIVE; - ns->state_expiry = now; - ns->rt_delay.sec = 10; + struct nameserver *ns = &resolver->ns[i]; + + status = pj_sockaddr_init(pj_AF_INET(), &ns->addr, &servers[i], + (pj_uint16_t)(ports ? ports[i] : PORT)); + if (status != PJ_SUCCESS) + status = pj_sockaddr_init(pj_AF_INET6(), &ns->addr, &servers[i], + (pj_uint16_t)(ports ? ports[i] : PORT)); + if (status != PJ_SUCCESS) { + pj_grp_lock_release(resolver->grp_lock); + return PJLIB_UTIL_EDNSINNSADDR; + } + + ns->state = STATE_ACTIVE; + ns->state_expiry = now; + ns->rt_delay.sec = 10; } resolver->ns_count = count; @@ -585,7 +584,7 @@ PJ_DEF(pj_status_t) pj_dns_resolver_set_ns( pj_dns_resolver *resolver, * Modify the resolver settings. */ PJ_DEF(pj_status_t) pj_dns_resolver_set_settings(pj_dns_resolver *resolver, - const pj_dns_settings *st) + const pj_dns_settings *st) { PJ_ASSERT_RETURN(resolver && st, PJ_EINVAL); @@ -600,7 +599,7 @@ PJ_DEF(pj_status_t) pj_dns_resolver_set_settings(pj_dns_resolver *resolver, * Get the resolver current settings. */ PJ_DEF(pj_status_t) pj_dns_resolver_get_settings( pj_dns_resolver *resolver, - pj_dns_settings *st) + pj_dns_settings *st) { PJ_ASSERT_RETURN(resolver && st, PJ_EINVAL); @@ -615,7 +614,7 @@ PJ_DEF(pj_status_t) pj_dns_resolver_get_settings( pj_dns_resolver *resolver, * Poll for events from the resolver. */ PJ_DEF(void) pj_dns_resolver_handle_events(pj_dns_resolver *resolver, - const pj_time_val *timeout) + const pj_time_val *timeout) { PJ_ASSERT_ON_FAIL(resolver, return); @@ -631,9 +630,9 @@ PJ_DEF(void) pj_dns_resolver_handle_events(pj_dns_resolver *resolver, * a new one. */ static pj_dns_async_query *alloc_qnode(pj_dns_resolver *resolver, - unsigned options, - void *user_data, - pj_dns_callback *cb) + unsigned options, + void *user_data, + pj_dns_callback *cb) { pj_dns_async_query *q; @@ -641,11 +640,11 @@ static pj_dns_async_query *alloc_qnode(pj_dns_resolver *resolver, options |= resolver->settings.options; if (!pj_list_empty(&resolver->query_free_nodes)) { - q = resolver->query_free_nodes.next; - pj_list_erase(q); - pj_bzero(q, sizeof(*q)); + q = resolver->query_free_nodes.next; + pj_list_erase(q); + pj_bzero(q, sizeof(*q)); } else { - q = PJ_POOL_ZALLOC_T(resolver->pool, pj_dns_async_query); + q = PJ_POOL_ZALLOC_T(resolver->pool, pj_dns_async_query); } /* Init query */ @@ -663,7 +662,7 @@ static pj_dns_async_query *alloc_qnode(pj_dns_resolver *resolver, * Transmit query. */ static pj_status_t transmit_query(pj_dns_resolver *resolver, - pj_dns_async_query *q) + pj_dns_async_query *q) { unsigned pkt_size; unsigned i, server_cnt, send_cnt; @@ -677,11 +676,11 @@ static pj_status_t transmit_query(pj_dns_resolver *resolver, server_cnt = PJ_ARRAY_SIZE(servers); status = select_nameservers(resolver, &server_cnt, servers); if (status != PJ_SUCCESS) { - return status; + return status; } if (server_cnt == 0) { - return PJLIB_UTIL_EDNSNOWORKINGNS; + return PJLIB_UTIL_EDNSNOWORKINGNS; } /* Start retransmit/timeout timer for the query */ @@ -694,40 +693,40 @@ static pj_status_t transmit_query(pj_dns_resolver *resolver, delay.msec = resolver->settings.qretr_delay; pj_time_val_normalize(&delay); status = pj_timer_heap_schedule_w_grp_lock(resolver->timer, - &q->timer_entry, - &delay, 1, - resolver->grp_lock); + &q->timer_entry, + &delay, 1, + resolver->grp_lock); if (status != PJ_SUCCESS) { - return status; + return status; } /* Check if the socket is available for sending */ if (pj_ioqueue_is_pending(resolver->udp_key, &resolver->udp_op_tx_key) #if PJ_HAS_IPV6 - || (resolver->udp6_key && - pj_ioqueue_is_pending(resolver->udp6_key, - &resolver->udp6_op_tx_key)) + || (resolver->udp6_key && + pj_ioqueue_is_pending(resolver->udp6_key, + &resolver->udp6_op_tx_key)) #endif - ) + ) { - ++q->transmit_cnt; - PJ_LOG(4,(resolver->name.ptr, - "Socket busy in transmitting DNS %s query for %s%s", - pj_dns_get_type_name(q->key.qtype), - q->key.name, - (q->transmit_cnt < resolver->settings.qretr_count? - ", will try again later":""))); - return PJ_SUCCESS; + ++q->transmit_cnt; + PJ_LOG(4,(resolver->name.ptr, + "Socket busy in transmitting DNS %s query for %s%s", + pj_dns_get_type_name(q->key.qtype), + q->key.name, + (q->transmit_cnt < resolver->settings.qretr_count? + ", will try again later":""))); + return PJ_SUCCESS; } /* Create DNS query packet */ pkt_size = sizeof(resolver->udp_tx_pkt); name = pj_str(q->key.name); status = pj_dns_make_query(resolver->udp_tx_pkt, &pkt_size, - q->id, q->key.qtype, &name); + q->id, q->key.qtype, &name); if (status != PJ_SUCCESS) { - pj_timer_heap_cancel(resolver->timer, &q->timer_entry); - return status; + pj_timer_heap_cancel(resolver->timer, &q->timer_entry); + return status; } /* Get current time. */ @@ -737,51 +736,51 @@ static pj_status_t transmit_query(pj_dns_resolver *resolver, send_cnt = 0; for (i=0; ins[servers[i]]; - - if (ns->addr.addr.sa_family == pj_AF_INET()) { - status = pj_ioqueue_sendto(resolver->udp_key, - &resolver->udp_op_tx_key, - resolver->udp_tx_pkt, &sent, 0, - &ns->addr, - pj_sockaddr_get_len(&ns->addr)); - if (status == PJ_SUCCESS || status == PJ_EPENDING) - send_cnt++; - } + pj_ssize_t sent = (pj_ssize_t) pkt_size; + struct nameserver *ns = &resolver->ns[servers[i]]; + + if (ns->addr.addr.sa_family == pj_AF_INET()) { + status = pj_ioqueue_sendto(resolver->udp_key, + &resolver->udp_op_tx_key, + resolver->udp_tx_pkt, &sent, 0, + &ns->addr, + pj_sockaddr_get_len(&ns->addr)); + if (status == PJ_SUCCESS || status == PJ_EPENDING) + send_cnt++; + } #if PJ_HAS_IPV6 - else if (resolver->udp6_key) { - status = pj_ioqueue_sendto(resolver->udp6_key, - &resolver->udp6_op_tx_key, - resolver->udp_tx_pkt, &sent, 0, - &ns->addr, - pj_sockaddr_get_len(&ns->addr)); - if (status == PJ_SUCCESS || status == PJ_EPENDING) - send_cnt++; - } + else if (resolver->udp6_key) { + status = pj_ioqueue_sendto(resolver->udp6_key, + &resolver->udp6_op_tx_key, + resolver->udp_tx_pkt, &sent, 0, + &ns->addr, + pj_sockaddr_get_len(&ns->addr)); + if (status == PJ_SUCCESS || status == PJ_EPENDING) + send_cnt++; + } #endif - else { - continue; - } - - PJ_PERROR(4,(resolver->name.ptr, status, - "%s %d bytes to NS %d (%s:%d): DNS %s query for %s", - (q->transmit_cnt==0? "Transmitting":"Re-transmitting"), - (int)pkt_size, servers[i], - pj_sockaddr_print(&ns->addr, addr, sizeof(addr), 2), - pj_sockaddr_get_port(&ns->addr), - pj_dns_get_type_name(q->key.qtype), - q->key.name)); - - if (ns->q_id == 0) { - ns->q_id = q->id; - ns->sent_time = now; - } + else { + continue; + } + + PJ_PERROR(4,(resolver->name.ptr, status, + "%s %d bytes to NS %d (%s:%d): DNS %s query for %s", + (q->transmit_cnt==0? "Transmitting":"Re-transmitting"), + (int)pkt_size, servers[i], + pj_sockaddr_print(&ns->addr, addr, sizeof(addr), 2), + pj_sockaddr_get_port(&ns->addr), + pj_dns_get_type_name(q->key.qtype), + q->key.name)); + + if (ns->q_id == 0) { + ns->q_id = q->id; + ns->sent_time = now; + } } if (send_cnt == 0) { pj_timer_heap_cancel(resolver->timer, &q->timer_entry); - return PJLIB_UTIL_EDNSNOWORKINGNS; + return PJLIB_UTIL_EDNSNOWORKINGNS; } ++q->transmit_cnt; @@ -808,7 +807,7 @@ static void init_res_key(struct res_key *key, int type, const pj_str_t *name) /* Copy key, in lowercase */ for (i=0; ipool->factory, "dnscache", - RES_BUF_SZ, 256, NULL); + RES_BUF_SZ, 256, NULL); cache = PJ_POOL_ZALLOC_T(pool, struct cached_res); cache->pool = pool; cache->ref_cnt = 1; @@ -858,12 +857,12 @@ static void free_entry(pj_dns_resolver *resolver, struct cached_res *cache) * Create and start asynchronous DNS query for a single resource. */ PJ_DEF(pj_status_t) pj_dns_resolver_start_query( pj_dns_resolver *resolver, - const pj_str_t *name, - int type, - unsigned options, - pj_dns_callback *cb, - void *user_data, - pj_dns_async_query **p_query) + const pj_str_t *name, + int type, + unsigned options, + pj_dns_callback *cb, + void *user_data, + pj_dns_async_query **p_query) { pj_time_val now; struct res_key key; @@ -877,7 +876,7 @@ PJ_DEF(pj_status_t) pj_dns_resolver_start_query( pj_dns_resolver *resolver, /* Check name is not too long. */ PJ_ASSERT_RETURN(name->slen>0 && name->slen < PJ_MAX_HOSTNAME, - PJ_ENAMETOOLONG); + PJ_ENAMETOOLONG); /* Check type */ PJ_ASSERT_RETURN(type > 0 && type < 0xFFFF, PJ_EINVAL); @@ -896,92 +895,92 @@ PJ_DEF(pj_status_t) pj_dns_resolver_start_query( pj_dns_resolver *resolver, */ hval = 0; cache = (struct cached_res *) pj_hash_get(resolver->hrescache, &key, - sizeof(key), &hval); + sizeof(key), &hval); if (cache) { - /* We've found a cached entry. */ - - /* Check for expiration */ - if (PJ_TIME_VAL_GT(cache->expiry_time, now)) { - - /* Log */ - PJ_LOG(5,(resolver->name.ptr, - "Picked up DNS %s record for %.*s from cache, ttl=%d", - pj_dns_get_type_name(type), - (int)name->slen, name->ptr, - (int)(cache->expiry_time.sec - now.sec))); - - /* Map DNS Rcode in the response into PJLIB status name space */ - status = PJ_DNS_GET_RCODE(cache->pkt->hdr.flags); - status = PJ_STATUS_FROM_DNS_RCODE(status); - - /* Workaround for deadlock problem. Need to increment the cache's - * ref counter first before releasing mutex, so the cache won't be - * destroyed by other thread while in callback. - */ - cache->ref_cnt++; - pj_grp_lock_release(resolver->grp_lock); - - /* This cached response is still valid. Just return this - * response to caller. - */ - if (cb) { - (*cb)(user_data, status, cache->pkt); - } - - /* Done. No host resolution is necessary */ - pj_grp_lock_acquire(resolver->grp_lock); - - /* Decrement the ref counter. Also check if it is time to free - * the cache (as it has been expired). - */ - cache->ref_cnt--; - if (cache->ref_cnt <= 0) - free_entry(resolver, cache); - - /* Must return PJ_SUCCESS */ - status = PJ_SUCCESS; - - /* - * We cannot write to *p_query after calling cb because what - * p_query points to may have been freed by cb. + /* We've found a cached entry. */ + + /* Check for expiration */ + if (PJ_TIME_VAL_GT(cache->expiry_time, now)) { + + /* Log */ + PJ_LOG(5,(resolver->name.ptr, + "Picked up DNS %s record for %.*s from cache, ttl=%d", + pj_dns_get_type_name(type), + (int)name->slen, name->ptr, + (int)(cache->expiry_time.sec - now.sec))); + + /* Map DNS Rcode in the response into PJLIB status name space */ + status = PJ_DNS_GET_RCODE(cache->pkt->hdr.flags); + status = PJ_STATUS_FROM_DNS_RCODE(status); + + /* Workaround for deadlock problem. Need to increment the cache's + * ref counter first before releasing mutex, so the cache won't be + * destroyed by other thread while in callback. + */ + cache->ref_cnt++; + pj_grp_lock_release(resolver->grp_lock); + + /* This cached response is still valid. Just return this + * response to caller. + */ + if (cb) { + (*cb)(user_data, status, cache->pkt); + } + + /* Done. No host resolution is necessary */ + pj_grp_lock_acquire(resolver->grp_lock); + + /* Decrement the ref counter. Also check if it is time to free + * the cache (as it has been expired). + */ + cache->ref_cnt--; + if (cache->ref_cnt <= 0) + free_entry(resolver, cache); + + /* Must return PJ_SUCCESS */ + status = PJ_SUCCESS; + + /* + * We cannot write to *p_query after calling cb because what + * p_query points to may have been freed by cb. * Refer to ticket #1974. - */ - pj_grp_lock_release(resolver->grp_lock); - return status; - } - - /* At this point, we have a cached entry, but this entry has expired. - * Remove this entry from the cached list. - */ - pj_hash_set(NULL, resolver->hrescache, &key, sizeof(key), 0, NULL); - - /* Also free the cache, if it is not being used (by callback). */ - cache->ref_cnt--; - if (cache->ref_cnt <= 0) - free_entry(resolver, cache); - - /* Must continue with creating a query now */ + */ + pj_grp_lock_release(resolver->grp_lock); + return status; + } + + /* At this point, we have a cached entry, but this entry has expired. + * Remove this entry from the cached list. + */ + pj_hash_set(NULL, resolver->hrescache, &key, sizeof(key), 0, NULL); + + /* Also free the cache, if it is not being used (by callback). */ + cache->ref_cnt--; + if (cache->ref_cnt <= 0) + free_entry(resolver, cache); + + /* Must continue with creating a query now */ } /* Next, check if we have pending query on the same resource */ q = (pj_dns_async_query *) pj_hash_get(resolver->hquerybyres, &key, - sizeof(key), NULL); + sizeof(key), NULL); if (q) { - /* Yes, there's another pending query to the same key. - * Just create a new child query and add this query to - * pending query's child queries. - */ - pj_dns_async_query *nq; - - nq = alloc_qnode(resolver, options, user_data, cb); - pj_list_push_back(&q->child_head, nq); - - /* Done. This child query will be notified once the "parent" - * query completes. - */ - p_q = nq; - status = PJ_SUCCESS; - goto on_return; + /* Yes, there's another pending query to the same key. + * Just create a new child query and add this query to + * pending query's child queries. + */ + pj_dns_async_query *nq; + + nq = alloc_qnode(resolver, options, user_data, cb); + pj_list_push_back(&q->child_head, nq); + + /* Done. This child query will be notified once the "parent" + * query completes. + */ + p_q = nq; + status = PJ_SUCCESS; + goto on_return; } /* There's no pending query to the same key, initiate a new one. */ @@ -991,27 +990,27 @@ PJ_DEF(pj_status_t) pj_dns_resolver_start_query( pj_dns_resolver *resolver, /* TODO: dnsext-forgery-resilient: randomize id for security */ q->id = resolver->last_id++; if (resolver->last_id == 0) - resolver->last_id = 1; + resolver->last_id = 1; pj_memcpy(&q->key, &key, sizeof(struct res_key)); /* Send the query */ status = transmit_query(resolver, q); if (status != PJ_SUCCESS) { - pj_list_push_back(&resolver->query_free_nodes, q); - goto on_return; + pj_list_push_back(&resolver->query_free_nodes, q); + goto on_return; } /* Add query entry to the hash tables */ pj_hash_set_np(resolver->hquerybyid, &q->id, sizeof(q->id), - 0, q->hbufid, q); + 0, q->hbufid, q); pj_hash_set_np(resolver->hquerybyres, &q->key, sizeof(q->key), - 0, q->hbufkey, q); + 0, q->hbufkey, q); p_q = q; on_return: if (p_query) - *p_query = p_q; + *p_query = p_q; pj_grp_lock_release(resolver->grp_lock); return status; @@ -1022,7 +1021,7 @@ PJ_DEF(pj_status_t) pj_dns_resolver_start_query( pj_dns_resolver *resolver, * Cancel a pending query. */ PJ_DEF(pj_status_t) pj_dns_resolver_cancel_query(pj_dns_async_query *query, - pj_bool_t notify) + pj_bool_t notify) { pj_dns_callback *cb; @@ -1031,15 +1030,15 @@ PJ_DEF(pj_status_t) pj_dns_resolver_cancel_query(pj_dns_async_query *query, pj_grp_lock_acquire(query->resolver->grp_lock); if (query->timer_entry.id == 1) { - pj_timer_heap_cancel_if_active(query->resolver->timer, - &query->timer_entry, 0); + pj_timer_heap_cancel_if_active(query->resolver->timer, + &query->timer_entry, 0); } cb = query->cb; query->cb = NULL; if (notify) - (*cb)(query->user_data, PJ_ECANCELLED, NULL); + (*cb)(query->user_data, PJ_ECANCELLED, NULL); pj_grp_lock_release(query->resolver->grp_lock); return PJ_SUCCESS; @@ -1050,7 +1049,7 @@ PJ_DEF(pj_status_t) pj_dns_resolver_cancel_query(pj_dns_async_query *query, * DNS response containing A packet. */ PJ_DEF(pj_status_t) pj_dns_parse_a_response(const pj_dns_parsed_packet *pkt, - pj_dns_a_record *rec) + pj_dns_a_record *rec) { enum { MAX_SEARCH = 20 }; pj_str_t hostname, alias = {NULL, 0}, *resname; @@ -1065,22 +1064,22 @@ PJ_DEF(pj_status_t) pj_dns_parse_a_response(const pj_dns_parsed_packet *pkt, /* Return error if there's error in the packet. */ if (PJ_DNS_GET_RCODE(pkt->hdr.flags)) - return PJ_STATUS_FROM_DNS_RCODE(PJ_DNS_GET_RCODE(pkt->hdr.flags)); + return PJ_STATUS_FROM_DNS_RCODE(PJ_DNS_GET_RCODE(pkt->hdr.flags)); /* Return error if there's no query section */ if (pkt->hdr.qdcount == 0) - return PJLIB_UTIL_EDNSINANSWER; + return PJLIB_UTIL_EDNSINANSWER; /* Return error if there's no answer */ if (pkt->hdr.anscount == 0) - return PJLIB_UTIL_EDNSNOANSWERREC; + return PJLIB_UTIL_EDNSNOANSWERREC; /* Get the hostname from the query. */ hostname = pkt->q[0].name; /* Copy hostname to the record */ if (hostname.slen > (int)bufleft) { - return PJ_ENAMETOOLONG; + return PJ_ENAMETOOLONG; } pj_memcpy(&rec->buf_[bufstart], hostname.ptr, hostname.slen); @@ -1092,68 +1091,68 @@ PJ_DEF(pj_status_t) pj_dns_parse_a_response(const pj_dns_parsed_packet *pkt, /* Find the first RR which name matches the hostname */ for (ansidx=0; ansidx < pkt->hdr.anscount; ++ansidx) { - if (pj_stricmp(&pkt->ans[ansidx].name, &hostname)==0) - break; + if (pj_stricmp(&pkt->ans[ansidx].name, &hostname)==0) + break; } if (ansidx == pkt->hdr.anscount) - return PJLIB_UTIL_EDNSNOANSWERREC; + return PJLIB_UTIL_EDNSNOANSWERREC; resname = &hostname; /* Keep following CNAME records. */ while (pkt->ans[ansidx].type == PJ_DNS_TYPE_CNAME && - search_cnt++ < MAX_SEARCH) + search_cnt++ < MAX_SEARCH) { - resname = &pkt->ans[ansidx].rdata.cname.name; + resname = &pkt->ans[ansidx].rdata.cname.name; - if (!alias.slen) - alias = *resname; + if (!alias.slen) + alias = *resname; - for (i=0; i < pkt->hdr.anscount; ++i) { - if (pj_stricmp(resname, &pkt->ans[i].name)==0) { - break; - } - } + for (i=0; i < pkt->hdr.anscount; ++i) { + if (pj_stricmp(resname, &pkt->ans[i].name)==0) { + break; + } + } - if (i==pkt->hdr.anscount) - return PJLIB_UTIL_EDNSNOANSWERREC; + if (i==pkt->hdr.anscount) + return PJLIB_UTIL_EDNSNOANSWERREC; - ansidx = i; + ansidx = i; } if (search_cnt >= MAX_SEARCH) - return PJLIB_UTIL_EDNSINANSWER; + return PJLIB_UTIL_EDNSINANSWER; if (pkt->ans[ansidx].type != PJ_DNS_TYPE_A) - return PJLIB_UTIL_EDNSINANSWER; + return PJLIB_UTIL_EDNSINANSWER; /* Copy alias to the record, if present. */ if (alias.slen) { - if (alias.slen > (int)bufleft) - return PJ_ENAMETOOLONG; + if (alias.slen > (int)bufleft) + return PJ_ENAMETOOLONG; - pj_memcpy(&rec->buf_[bufstart], alias.ptr, alias.slen); - rec->alias.ptr = &rec->buf_[bufstart]; - rec->alias.slen = alias.slen; + pj_memcpy(&rec->buf_[bufstart], alias.ptr, alias.slen); + rec->alias.ptr = &rec->buf_[bufstart]; + rec->alias.slen = alias.slen; - bufstart += alias.slen; - bufleft -= alias.slen; + bufstart += alias.slen; + bufleft -= alias.slen; } /* Get the IP addresses. */ for (i=0; i < pkt->hdr.anscount; ++i) { - if (pkt->ans[i].type == PJ_DNS_TYPE_A && - pj_stricmp(&pkt->ans[i].name, resname)==0 && - rec->addr_count < PJ_DNS_MAX_IP_IN_A_REC) - { - rec->addr[rec->addr_count++].s_addr = - pkt->ans[i].rdata.a.ip_addr.s_addr; - } + if (pkt->ans[i].type == PJ_DNS_TYPE_A && + pj_stricmp(&pkt->ans[i].name, resname)==0 && + rec->addr_count < PJ_DNS_MAX_IP_IN_A_REC) + { + rec->addr[rec->addr_count++].s_addr = + pkt->ans[i].rdata.a.ip_addr.s_addr; + } } if (rec->addr_count == 0) - return PJLIB_UTIL_EDNSNOANSWERREC; + return PJLIB_UTIL_EDNSNOANSWERREC; return PJ_SUCCESS; } @@ -1163,8 +1162,8 @@ PJ_DEF(pj_status_t) pj_dns_parse_a_response(const pj_dns_parsed_packet *pkt, * DNS response containing A and/or AAAA packet. */ PJ_DEF(pj_status_t) pj_dns_parse_addr_response( - const pj_dns_parsed_packet *pkt, - pj_dns_addr_record *rec) + const pj_dns_parsed_packet *pkt, + pj_dns_addr_record *rec) { enum { MAX_SEARCH = 20 }; pj_str_t hostname, alias = {NULL, 0}, *resname; @@ -1181,22 +1180,22 @@ PJ_DEF(pj_status_t) pj_dns_parse_addr_response( /* Return error if there's error in the packet. */ if (PJ_DNS_GET_RCODE(pkt->hdr.flags)) - return PJ_STATUS_FROM_DNS_RCODE(PJ_DNS_GET_RCODE(pkt->hdr.flags)); + return PJ_STATUS_FROM_DNS_RCODE(PJ_DNS_GET_RCODE(pkt->hdr.flags)); /* Return error if there's no query section */ if (pkt->hdr.qdcount == 0) - return PJLIB_UTIL_EDNSINANSWER; + return PJLIB_UTIL_EDNSINANSWER; /* Return error if there's no answer */ if (pkt->hdr.anscount == 0) - return PJLIB_UTIL_EDNSNOANSWERREC; + return PJLIB_UTIL_EDNSNOANSWERREC; /* Get the hostname from the query. */ hostname = pkt->q[0].name; /* Copy hostname to the record */ if (hostname.slen > (int)bufleft) { - return PJ_ENAMETOOLONG; + return PJ_ENAMETOOLONG; } pj_memcpy(&rec->buf_[bufstart], hostname.ptr, hostname.slen); @@ -1208,78 +1207,78 @@ PJ_DEF(pj_status_t) pj_dns_parse_addr_response( /* Find the first RR which name matches the hostname. */ for (ansidx=0; ansidx < pkt->hdr.anscount; ++ansidx) { - if (pj_stricmp(&pkt->ans[ansidx].name, &hostname)==0) - break; + if (pj_stricmp(&pkt->ans[ansidx].name, &hostname)==0) + break; } if (ansidx == pkt->hdr.anscount) - return PJLIB_UTIL_EDNSNOANSWERREC; + return PJLIB_UTIL_EDNSNOANSWERREC; resname = &hostname; /* Keep following CNAME records. */ while (pkt->ans[ansidx].type == PJ_DNS_TYPE_CNAME && - cnt++ < MAX_SEARCH) + cnt++ < MAX_SEARCH) { - resname = &pkt->ans[ansidx].rdata.cname.name; + resname = &pkt->ans[ansidx].rdata.cname.name; - if (!alias.slen) - alias = *resname; + if (!alias.slen) + alias = *resname; - for (i=0; i < pkt->hdr.anscount; ++i) { - if (pj_stricmp(resname, &pkt->ans[i].name)==0) - break; - } + for (i=0; i < pkt->hdr.anscount; ++i) { + if (pj_stricmp(resname, &pkt->ans[i].name)==0) + break; + } - if (i==pkt->hdr.anscount) - return PJLIB_UTIL_EDNSNOANSWERREC; + if (i==pkt->hdr.anscount) + return PJLIB_UTIL_EDNSNOANSWERREC; - ansidx = i; + ansidx = i; } if (cnt >= MAX_SEARCH) - return PJLIB_UTIL_EDNSINANSWER; + return PJLIB_UTIL_EDNSINANSWER; if (pkt->ans[ansidx].type != PJ_DNS_TYPE_A && - pkt->ans[ansidx].type != PJ_DNS_TYPE_AAAA) + pkt->ans[ansidx].type != PJ_DNS_TYPE_AAAA) { - return PJLIB_UTIL_EDNSINANSWER; + return PJLIB_UTIL_EDNSINANSWER; } /* Copy alias to the record, if present. */ if (alias.slen) { - if (alias.slen > (int)bufleft) - return PJ_ENAMETOOLONG; + if (alias.slen > (int)bufleft) + return PJ_ENAMETOOLONG; - pj_memcpy(&rec->buf_[bufstart], alias.ptr, alias.slen); - rec->alias.ptr = &rec->buf_[bufstart]; - rec->alias.slen = alias.slen; + pj_memcpy(&rec->buf_[bufstart], alias.ptr, alias.slen); + rec->alias.ptr = &rec->buf_[bufstart]; + rec->alias.slen = alias.slen; - bufstart += alias.slen; - bufleft -= alias.slen; + bufstart += alias.slen; + bufleft -= alias.slen; } /* Get the IP addresses. */ cnt = 0; for (i=0; i < pkt->hdr.anscount && cnt < PJ_DNS_MAX_IP_IN_A_REC ; ++i) { - if ((pkt->ans[i].type == PJ_DNS_TYPE_A || - pkt->ans[i].type == PJ_DNS_TYPE_AAAA) && - pj_stricmp(&pkt->ans[i].name, resname)==0) - { - if (pkt->ans[i].type == PJ_DNS_TYPE_A) { - rec->addr[cnt].af = pj_AF_INET(); - rec->addr[cnt].ip.v4 = pkt->ans[i].rdata.a.ip_addr; - } else { - rec->addr[cnt].af = pj_AF_INET6(); - rec->addr[cnt].ip.v6 = pkt->ans[i].rdata.aaaa.ip_addr; - } - ++cnt; - } + if ((pkt->ans[i].type == PJ_DNS_TYPE_A || + pkt->ans[i].type == PJ_DNS_TYPE_AAAA) && + pj_stricmp(&pkt->ans[i].name, resname)==0) + { + if (pkt->ans[i].type == PJ_DNS_TYPE_A) { + rec->addr[cnt].af = pj_AF_INET(); + rec->addr[cnt].ip.v4 = pkt->ans[i].rdata.a.ip_addr; + } else { + rec->addr[cnt].af = pj_AF_INET6(); + rec->addr[cnt].ip.v6 = pkt->ans[i].rdata.aaaa.ip_addr; + } + ++cnt; + } } rec->addr_count = cnt; if (cnt == 0) - return PJLIB_UTIL_EDNSNOANSWERREC; + return PJLIB_UTIL_EDNSNOANSWERREC; return PJ_SUCCESS; } @@ -1287,9 +1286,9 @@ PJ_DEF(pj_status_t) pj_dns_parse_addr_response( /* Set nameserver state */ static void set_nameserver_state(pj_dns_resolver *resolver, - unsigned index, - enum ns_state state, - const pj_time_val *now) + unsigned index, + enum ns_state state, + const pj_time_val *now) { struct nameserver *ns = &resolver->ns[index]; enum ns_state old_state = ns->state; @@ -1299,17 +1298,17 @@ static void set_nameserver_state(pj_dns_resolver *resolver, ns->state_expiry = *now; if (state == STATE_PROBING) - ns->state_expiry.sec += ((resolver->settings.qretr_count + 2) * - resolver->settings.qretr_delay) / 1000; + ns->state_expiry.sec += ((resolver->settings.qretr_count + 2) * + resolver->settings.qretr_delay) / 1000; else if (state == STATE_ACTIVE) - ns->state_expiry.sec += resolver->settings.good_ns_ttl; + ns->state_expiry.sec += resolver->settings.good_ns_ttl; else - ns->state_expiry.sec += resolver->settings.bad_ns_ttl; + ns->state_expiry.sec += resolver->settings.bad_ns_ttl; PJ_LOG(5, (resolver->name.ptr, "Nameserver %s:%d state changed %s --> %s", - pj_sockaddr_print(&ns->addr, addr, sizeof(addr), 2), - pj_sockaddr_get_port(&ns->addr), - state_names[old_state], state_names[state])); + pj_sockaddr_print(&ns->addr, addr, sizeof(addr), 2), + pj_sockaddr_get_port(&ns->addr), + state_names[old_state], state_names[state])); } @@ -1326,8 +1325,8 @@ static void set_nameserver_state(pj_dns_resolver *resolver, * also include the NS to re-check again that the server is still bad. */ static pj_status_t select_nameservers(pj_dns_resolver *resolver, - unsigned *count, - unsigned servers[]) + unsigned *count, + unsigned servers[]) { unsigned i, max_count=*count; int min; @@ -1340,45 +1339,45 @@ static pj_status_t select_nameservers(pj_dns_resolver *resolver, /* Check that nameservers are configured. */ if (resolver->ns_count == 0) - return PJLIB_UTIL_EDNSNONS; + return PJLIB_UTIL_EDNSNONS; pj_gettimeofday(&now); /* Select one Active nameserver with best response time. */ for (min=-1, i=0; ins_count; ++i) { - struct nameserver *ns = &resolver->ns[i]; + struct nameserver *ns = &resolver->ns[i]; - if (ns->state != STATE_ACTIVE) - continue; + if (ns->state != STATE_ACTIVE) + continue; - if (min == -1) - min = i; - else if (PJ_TIME_VAL_LT(ns->rt_delay, resolver->ns[min].rt_delay)) - min = i; + if (min == -1) + min = i; + else if (PJ_TIME_VAL_LT(ns->rt_delay, resolver->ns[min].rt_delay)) + min = i; } if (min != -1) { - servers[0] = min; - ++(*count); + servers[0] = min; + ++(*count); } /* Scan nameservers. */ for (i=0; ins_count && *count < max_count; ++i) { - struct nameserver *ns = &resolver->ns[i]; - - if (PJ_TIME_VAL_LTE(ns->state_expiry, now)) { - if (ns->state == STATE_PROBING) { - set_nameserver_state(resolver, i, STATE_BAD, &now); - } else { - set_nameserver_state(resolver, i, STATE_PROBING, &now); - if ((int)i != min) { - servers[*count] = i; - ++(*count); - } - } - } else if (ns->state == STATE_PROBING && (int)i != min) { - servers[*count] = i; - ++(*count); - } + struct nameserver *ns = &resolver->ns[i]; + + if (PJ_TIME_VAL_LTE(ns->state_expiry, now)) { + if (ns->state == STATE_PROBING) { + set_nameserver_state(resolver, i, STATE_BAD, &now); + } else { + set_nameserver_state(resolver, i, STATE_PROBING, &now); + if ((int)i != min) { + servers[*count] = i; + ++(*count); + } + } + } else if (ns->state == STATE_PROBING && (int)i != min) { + servers[*count] = i; + ++(*count); + } } return PJ_SUCCESS; @@ -1387,8 +1386,8 @@ static pj_status_t select_nameservers(pj_dns_resolver *resolver, /* Update name server status */ static void report_nameserver_status(pj_dns_resolver *resolver, - const pj_sockaddr *ns_addr, - const pj_dns_parsed_packet *pkt) + const pj_sockaddr *ns_addr, + const pj_dns_parsed_packet *pkt) { unsigned i; int rcode; @@ -1400,11 +1399,11 @@ static void report_nameserver_status(pj_dns_resolver *resolver, * it returned the following status codes */ if (pkt) { - rcode = PJ_DNS_GET_RCODE(pkt->hdr.flags); - q_id = pkt->hdr.id; + rcode = PJ_DNS_GET_RCODE(pkt->hdr.flags); + q_id = pkt->hdr.id; } else { - rcode = 0; - q_id = (pj_uint32_t)-1; + rcode = 0; + q_id = (pj_uint32_t)-1; } /* Some nameserver is reported to respond with PJ_DNS_RCODE_SERVFAIL for @@ -1413,12 +1412,12 @@ static void report_nameserver_status(pj_dns_resolver *resolver, * queries. So let's not mark nameserver as bad for SERVFAIL response. */ if (!pkt || /* rcode == PJ_DNS_RCODE_SERVFAIL || */ - rcode == PJ_DNS_RCODE_REFUSED || - rcode == PJ_DNS_RCODE_NOTAUTH) + rcode == PJ_DNS_RCODE_REFUSED || + rcode == PJ_DNS_RCODE_NOTAUTH) { - is_good = PJ_FALSE; + is_good = PJ_FALSE; } else { - is_good = PJ_TRUE; + is_good = PJ_TRUE; } @@ -1427,105 +1426,105 @@ static void report_nameserver_status(pj_dns_resolver *resolver, /* Recheck all nameservers. */ for (i=0; ins_count; ++i) { - struct nameserver *ns = &resolver->ns[i]; - - if (pj_sockaddr_cmp(&ns->addr, ns_addr) == 0) { - if (q_id == ns->q_id) { - /* Calculate response time */ - pj_time_val rt = now; - PJ_TIME_VAL_SUB(rt, ns->sent_time); - ns->rt_delay = rt; - ns->q_id = 0; - } - set_nameserver_state(resolver, i, - (is_good ? STATE_ACTIVE : STATE_BAD), &now); - break; - } + struct nameserver *ns = &resolver->ns[i]; + + if (pj_sockaddr_cmp(&ns->addr, ns_addr) == 0) { + if (q_id == ns->q_id) { + /* Calculate response time */ + pj_time_val rt = now; + PJ_TIME_VAL_SUB(rt, ns->sent_time); + ns->rt_delay = rt; + ns->q_id = 0; + } + set_nameserver_state(resolver, i, + (is_good ? STATE_ACTIVE : STATE_BAD), &now); + break; + } } } /* Update response cache */ static void update_res_cache(pj_dns_resolver *resolver, - const struct res_key *key, - pj_status_t status, - pj_bool_t set_expiry, - const pj_dns_parsed_packet *pkt) + const struct res_key *key, + pj_status_t status, + pj_bool_t set_expiry, + const pj_dns_parsed_packet *pkt) { struct cached_res *cache; pj_uint32_t hval=0, ttl; /* If status is unsuccessful, clear the same entry from the cache */ if (status != PJ_SUCCESS) { - cache = (struct cached_res *) pj_hash_get(resolver->hrescache, key, - sizeof(*key), &hval); - /* Remove the entry before releasing its pool (see ticket #1710) */ - pj_hash_set(NULL, resolver->hrescache, key, sizeof(*key), hval, NULL); - - /* Free the entry */ - if (cache && --cache->ref_cnt <= 0) - free_entry(resolver, cache); + cache = (struct cached_res *) pj_hash_get(resolver->hrescache, key, + sizeof(*key), &hval); + /* Remove the entry before releasing its pool (see ticket #1710) */ + pj_hash_set(NULL, resolver->hrescache, key, sizeof(*key), hval, NULL); + + /* Free the entry */ + if (cache && --cache->ref_cnt <= 0) + free_entry(resolver, cache); } /* Calculate expiration time. */ if (set_expiry) { - if (pkt->hdr.anscount == 0 || status != PJ_SUCCESS) { - /* If we don't have answers for the name, then give a different - * ttl value (note: PJ_DNS_RESOLVER_INVALID_TTL may be zero, - * which means that invalid names won't be kept in the cache) - */ - ttl = PJ_DNS_RESOLVER_INVALID_TTL; - - } else { - /* Otherwise get the minimum TTL from the answers */ - unsigned i; - ttl = 0xFFFFFFFF; - for (i=0; ihdr.anscount; ++i) { - if (pkt->ans[i].ttl < ttl) - ttl = pkt->ans[i].ttl; - } - } + if (pkt->hdr.anscount == 0 || status != PJ_SUCCESS) { + /* If we don't have answers for the name, then give a different + * ttl value (note: PJ_DNS_RESOLVER_INVALID_TTL may be zero, + * which means that invalid names won't be kept in the cache) + */ + ttl = PJ_DNS_RESOLVER_INVALID_TTL; + + } else { + /* Otherwise get the minimum TTL from the answers */ + unsigned i; + ttl = 0xFFFFFFFF; + for (i=0; ihdr.anscount; ++i) { + if (pkt->ans[i].ttl < ttl) + ttl = pkt->ans[i].ttl; + } + } } else { - ttl = 0xFFFFFFFF; + ttl = 0xFFFFFFFF; } /* Apply maximum TTL */ if (ttl > resolver->settings.cache_max_ttl) - ttl = resolver->settings.cache_max_ttl; + ttl = resolver->settings.cache_max_ttl; /* Get a cache response entry */ cache = (struct cached_res *) pj_hash_get(resolver->hrescache, key, - sizeof(*key), &hval); + sizeof(*key), &hval); /* If TTL is zero, clear the same entry in the hash table */ if (ttl == 0) { - /* Remove the entry before releasing its pool (see ticket #1710) */ - pj_hash_set(NULL, resolver->hrescache, key, sizeof(*key), hval, NULL); + /* Remove the entry before releasing its pool (see ticket #1710) */ + pj_hash_set(NULL, resolver->hrescache, key, sizeof(*key), hval, NULL); - /* Free the entry */ - if (cache && --cache->ref_cnt <= 0) - free_entry(resolver, cache); - return; + /* Free the entry */ + if (cache && --cache->ref_cnt <= 0) + free_entry(resolver, cache); + return; } if (cache == NULL) { - cache = alloc_entry(resolver); + cache = alloc_entry(resolver); } else { - /* Remove the entry before resetting its pool (see ticket #1710) */ - pj_hash_set(NULL, resolver->hrescache, key, sizeof(*key), hval, NULL); - - if (cache->ref_cnt > 1) { - /* When cache entry is being used by callback (to app), - * just decrement ref_cnt so it will be freed after - * the callback returns and allocate new entry. - */ - cache->ref_cnt--; - cache = alloc_entry(resolver); - } else { - /* Reset cache to avoid bloated cache pool */ - reset_entry(&cache); - } + /* Remove the entry before resetting its pool (see ticket #1710) */ + pj_hash_set(NULL, resolver->hrescache, key, sizeof(*key), hval, NULL); + + if (cache->ref_cnt > 1) { + /* When cache entry is being used by callback (to app), + * just decrement ref_cnt so it will be freed after + * the callback returns and allocate new entry. + */ + cache->ref_cnt--; + cache = alloc_entry(resolver); + } else { + /* Reset cache to avoid bloated cache pool */ + reset_entry(&cache); + } } /* Duplicate the packet. @@ -1535,16 +1534,16 @@ static void update_res_cache(pj_dns_resolver *resolver, * the name being requested. */ pj_dns_packet_dup(cache->pool, pkt, - PJ_DNS_NO_NS | PJ_DNS_NO_AR, - &cache->pkt); + PJ_DNS_NO_NS | PJ_DNS_NO_AR, + &cache->pkt); /* Calculate expiration time */ if (set_expiry) { - pj_gettimeofday(&cache->expiry_time); - cache->expiry_time.sec += ttl; + pj_gettimeofday(&cache->expiry_time); + cache->expiry_time.sec += ttl; } else { - cache->expiry_time.sec = 0x7FFFFFFFL; - cache->expiry_time.msec = 0; + cache->expiry_time.sec = 0x7FFFFFFFL; + cache->expiry_time.msec = 0; } /* Copy key to the cached response */ @@ -1552,14 +1551,14 @@ static void update_res_cache(pj_dns_resolver *resolver, /* Update the hash table */ pj_hash_set_np(resolver->hrescache, &cache->key, sizeof(*key), hval, - cache->hbuf, cache); + cache->hbuf, cache); } /* Callback to be called when query has timed out */ static void on_timeout( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { pj_dns_resolver *resolver; pj_dns_async_query *q, *cq; @@ -1577,9 +1576,9 @@ static void on_timeout( pj_timer_heap_t *timer_heap, * response arrives) */ if (pj_hash_get(resolver->hquerybyid, &q->id, sizeof(q->id), NULL)==NULL) { - /* Yeah, this query is done. */ - pj_grp_lock_release(resolver->grp_lock); - return; + /* Yeah, this query is done. */ + pj_grp_lock_release(resolver->grp_lock); + return; } /* Invalidate id. */ @@ -1587,17 +1586,17 @@ static void on_timeout( pj_timer_heap_t *timer_heap, /* Check to see if we should retransmit instead of time out */ if (q->transmit_cnt < resolver->settings.qretr_count) { - status = transmit_query(resolver, q); - if (status == PJ_SUCCESS) { - pj_grp_lock_release(resolver->grp_lock); - return; - } else { - /* Error occurs */ - PJ_PERROR(4,(resolver->name.ptr, status, - "Error transmitting request")); - - /* Let it fallback to timeout section below */ - } + status = transmit_query(resolver, q); + if (status == PJ_SUCCESS) { + pj_grp_lock_release(resolver->grp_lock); + return; + } else { + /* Error occurs */ + PJ_PERROR(4,(resolver->name.ptr, status, + "Error transmitting request")); + + /* Let it fallback to timeout section below */ + } } /* Clear hash table entries */ @@ -1609,14 +1608,14 @@ static void on_timeout( pj_timer_heap_t *timer_heap, /* Call application callback, if any. */ if (q->cb) - (*q->cb)(q->user_data, PJ_ETIMEDOUT, NULL); + (*q->cb)(q->user_data, PJ_ETIMEDOUT, NULL); /* Call application callback for child queries. */ cq = q->child_head.next; while (cq != (void*)&q->child_head) { - if (cq->cb) - (*cq->cb)(cq->user_data, PJ_ETIMEDOUT, NULL); - cq = cq->next; + if (cq->cb) + (*cq->cb)(cq->user_data, PJ_ETIMEDOUT, NULL); + cq = cq->next; } /* Workaround for deadlock problem in #1565 (similar to #1108) */ @@ -1629,9 +1628,9 @@ static void on_timeout( pj_timer_heap_t *timer_heap, /* Put child entries into recycle list */ cq = q->child_head.next; while (cq != (void*)&q->child_head) { - pj_dns_async_query *next = cq->next; - pj_list_push_back(&resolver->query_free_nodes, cq); - cq = next; + pj_dns_async_query *next = cq->next; + pj_list_push_back(&resolver->query_free_nodes, cq); + cq = next; } /* Put query entry into recycle list */ @@ -1664,17 +1663,17 @@ static void on_read_complete(pj_ioqueue_key_t *key, #if PJ_HAS_IPV6 if (key == resolver->udp6_key) { - src_addr = &resolver->udp6_src_addr; - src_addr_len = &resolver->udp6_addr_len; - rx_pkt = resolver->udp6_rx_pkt; - rx_pkt_size = sizeof(resolver->udp6_rx_pkt); + src_addr = &resolver->udp6_src_addr; + src_addr_len = &resolver->udp6_addr_len; + rx_pkt = resolver->udp6_rx_pkt; + rx_pkt_size = sizeof(resolver->udp6_rx_pkt); } else #endif { - src_addr = &resolver->udp_src_addr; - src_addr_len = &resolver->udp_addr_len; - rx_pkt = resolver->udp_rx_pkt; - rx_pkt_size = sizeof(resolver->udp_rx_pkt); + src_addr = &resolver->udp_src_addr; + src_addr_len = &resolver->udp_addr_len; + rx_pkt = resolver->udp_rx_pkt; + rx_pkt_size = sizeof(resolver->udp_rx_pkt); } pj_grp_lock_acquire(resolver->grp_lock); @@ -1682,36 +1681,36 @@ static void on_read_complete(pj_ioqueue_key_t *key, /* Check for errors */ if (bytes_read < 0) { - status = (pj_status_t)-bytes_read; - PJ_PERROR(4,(resolver->name.ptr, status, "DNS resolver read error")); + status = (pj_status_t)-bytes_read; + PJ_PERROR(4,(resolver->name.ptr, status, "DNS resolver read error")); - goto read_next_packet; + goto read_next_packet; } PJ_LOG(5,(resolver->name.ptr, - "Received %d bytes DNS response from %s:%d", - (int)bytes_read, - pj_sockaddr_print(src_addr, addr, sizeof(addr), 2), - pj_sockaddr_get_port(src_addr))); + "Received %d bytes DNS response from %s:%d", + (int)bytes_read, + pj_sockaddr_print(src_addr, addr, sizeof(addr), 2), + pj_sockaddr_get_port(src_addr))); /* Check for zero packet */ if (bytes_read == 0) - goto read_next_packet; + goto read_next_packet; /* Create temporary pool from a fixed buffer */ pool = pj_pool_create_on_buf("restmp", resolver->tmp_pool, - sizeof(resolver->tmp_pool)); + sizeof(resolver->tmp_pool)); /* Parse DNS response */ status = -1; dns_pkt = NULL; PJ_TRY { - status = pj_dns_parse_packet(pool, rx_pkt, - (unsigned)bytes_read, &dns_pkt); + status = pj_dns_parse_packet(pool, rx_pkt, + (unsigned)bytes_read, &dns_pkt); } PJ_CATCH_ANY { - status = PJ_ENOMEM; + status = PJ_ENOMEM; } PJ_END; @@ -1720,24 +1719,24 @@ static void on_read_complete(pj_ioqueue_key_t *key, /* Handle parse error */ if (status != PJ_SUCCESS) { - PJ_PERROR(3,(resolver->name.ptr, status, - "Error parsing DNS response from %s:%d", - pj_sockaddr_print(src_addr, addr, sizeof(addr), 2), - pj_sockaddr_get_port(src_addr))); - goto read_next_packet; + PJ_PERROR(3,(resolver->name.ptr, status, + "Error parsing DNS response from %s:%d", + pj_sockaddr_print(src_addr, addr, sizeof(addr), 2), + pj_sockaddr_get_port(src_addr))); + goto read_next_packet; } /* Find the query based on the transaction ID */ q = (pj_dns_async_query*) pj_hash_get(resolver->hquerybyid, &dns_pkt->hdr.id, - sizeof(dns_pkt->hdr.id), NULL); + sizeof(dns_pkt->hdr.id), NULL); if (!q) { - PJ_LOG(5,(resolver->name.ptr, - "DNS response from %s:%d id=%d discarded", - pj_sockaddr_print(src_addr, addr, sizeof(addr), 2), - pj_sockaddr_get_port(src_addr), - (unsigned)dns_pkt->hdr.id)); - goto read_next_packet; + PJ_LOG(5,(resolver->name.ptr, + "DNS response from %s:%d id=%d discarded", + pj_sockaddr_print(src_addr, addr, sizeof(addr), 2), + pj_sockaddr_get_port(src_addr), + (unsigned)dns_pkt->hdr.id)); + goto read_next_packet; } /* Map DNS Rcode in the response into PJLIB status name space */ @@ -1759,18 +1758,18 @@ static void on_read_complete(pj_ioqueue_key_t *key, * record before it is saved to the hash table. */ if (q->cb) - (*q->cb)(q->user_data, status, dns_pkt); + (*q->cb)(q->user_data, status, dns_pkt); /* If query has subqueries, notify subqueries's application callback */ if (!pj_list_empty(&q->child_head)) { - pj_dns_async_query *child_q; - - child_q = q->child_head.next; - while (child_q != (pj_dns_async_query*)&q->child_head) { - if (child_q->cb) - (*child_q->cb)(child_q->user_data, status, dns_pkt); - child_q = child_q->next; - } + pj_dns_async_query *child_q; + + child_q = q->child_head.next; + while (child_q != (pj_dns_async_query*)&q->child_head) { + if (child_q->cb) + (*child_q->cb)(child_q->user_data, status, dns_pkt); + child_q = child_q->next; + } } /* Workaround for deadlock problem in #1108 */ @@ -1778,39 +1777,39 @@ static void on_read_complete(pj_ioqueue_key_t *key, /* Truncated responses MUST NOT be saved (cached). */ if (PJ_DNS_GET_TC(dns_pkt->hdr.flags) == 0) { - /* Save/update response cache. */ - update_res_cache(resolver, &q->key, status, PJ_TRUE, dns_pkt); + /* Save/update response cache. */ + update_res_cache(resolver, &q->key, status, PJ_TRUE, dns_pkt); } /* Recycle query objects, starting with the child queries */ if (!pj_list_empty(&q->child_head)) { - pj_dns_async_query *child_q; - - child_q = q->child_head.next; - while (child_q != (pj_dns_async_query*)&q->child_head) { - pj_dns_async_query *next = child_q->next; - pj_list_erase(child_q); - pj_list_push_back(&resolver->query_free_nodes, child_q); - child_q = next; - } + pj_dns_async_query *child_q; + + child_q = q->child_head.next; + while (child_q != (pj_dns_async_query*)&q->child_head) { + pj_dns_async_query *next = child_q->next; + pj_list_erase(child_q); + pj_list_push_back(&resolver->query_free_nodes, child_q); + child_q = next; + } } pj_list_push_back(&resolver->query_free_nodes, q); read_next_packet: if (pool) { - /* needed just in case PJ_HAS_POOL_ALT_API is set */ - pj_pool_release(pool); + /* needed just in case PJ_HAS_POOL_ALT_API is set */ + pj_pool_release(pool); } status = pj_ioqueue_recvfrom(key, op_key, rx_pkt, &rx_pkt_size, - PJ_IOQUEUE_ALWAYS_ASYNC, - src_addr, src_addr_len); + PJ_IOQUEUE_ALWAYS_ASYNC, + src_addr, src_addr_len); if (status != PJ_EPENDING && status != PJ_ECANCELLED) { - PJ_PERROR(4,(resolver->name.ptr, status, - "DNS resolver ioqueue read error")); + PJ_PERROR(4,(resolver->name.ptr, status, + "DNS resolver ioqueue read error")); - pj_assert(!"Unhandled error"); + pj_assert(!"Unhandled error"); } pj_grp_lock_release(resolver->grp_lock); @@ -1823,8 +1822,8 @@ static void on_read_complete(pj_ioqueue_key_t *key, * into the resolver. */ PJ_DEF(pj_status_t) pj_dns_resolver_add_entry( pj_dns_resolver *resolver, - const pj_dns_parsed_packet *pkt, - pj_bool_t set_ttl) + const pj_dns_parsed_packet *pkt, + pj_bool_t set_ttl) { struct res_key key; @@ -1836,26 +1835,26 @@ PJ_DEF(pj_status_t) pj_dns_resolver_add_entry( pj_dns_resolver *resolver, /* Make sure there are answers in the packet */ PJ_ASSERT_RETURN((pkt->hdr.anscount && pkt->ans) || - (pkt->hdr.qdcount && pkt->q), - PJLIB_UTIL_EDNSNOANSWERREC); + (pkt->hdr.qdcount && pkt->q), + PJLIB_UTIL_EDNSNOANSWERREC); pj_grp_lock_acquire(resolver->grp_lock); /* Build resource key for looking up hash tables */ pj_bzero(&key, sizeof(struct res_key)); if (pkt->hdr.anscount) { - /* Make sure name is not too long. */ - PJ_ASSERT_RETURN(pkt->ans[0].name.slen < PJ_MAX_HOSTNAME, - PJ_ENAMETOOLONG); + /* Make sure name is not too long. */ + PJ_ASSERT_RETURN(pkt->ans[0].name.slen < PJ_MAX_HOSTNAME, + PJ_ENAMETOOLONG); - init_res_key(&key, pkt->ans[0].type, &pkt->ans[0].name); + init_res_key(&key, pkt->ans[0].type, &pkt->ans[0].name); } else { - /* Make sure name is not too long. */ - PJ_ASSERT_RETURN(pkt->q[0].name.slen < PJ_MAX_HOSTNAME, - PJ_ENAMETOOLONG); + /* Make sure name is not too long. */ + PJ_ASSERT_RETURN(pkt->q[0].name.slen < PJ_MAX_HOSTNAME, + PJ_ENAMETOOLONG); - init_res_key(&key, pkt->q[0].type, &pkt->q[0].name); + init_res_key(&key, pkt->q[0].type, &pkt->q[0].name); } /* Insert entry. */ @@ -1888,7 +1887,7 @@ PJ_DEF(unsigned) pj_dns_resolver_get_cached_count(pj_dns_resolver *resolver) * Dump resolver state to the log. */ PJ_DEF(void) pj_dns_resolver_dump(pj_dns_resolver *resolver, - pj_bool_t detail) + pj_bool_t detail) { #if PJ_LOG_MAX_LEVEL >= 3 unsigned i; @@ -1902,57 +1901,57 @@ PJ_DEF(void) pj_dns_resolver_dump(pj_dns_resolver *resolver, PJ_LOG(3,(resolver->name.ptr, " Name servers:")); for (i=0; ins_count; ++i) { - char addr[PJ_INET6_ADDRSTRLEN]; - struct nameserver *ns = &resolver->ns[i]; - - PJ_LOG(3,(resolver->name.ptr, - " NS %d: %s:%d (state=%s until %ds, rtt=%d ms)", - i, - pj_sockaddr_print(&ns->addr, addr, sizeof(addr), 2), - pj_sockaddr_get_port(&ns->addr), - state_names[ns->state], - ns->state_expiry.sec - now.sec, - PJ_TIME_VAL_MSEC(ns->rt_delay))); + char addr[PJ_INET6_ADDRSTRLEN]; + struct nameserver *ns = &resolver->ns[i]; + + PJ_LOG(3,(resolver->name.ptr, + " NS %d: %s:%d (state=%s until %ds, rtt=%d ms)", + i, + pj_sockaddr_print(&ns->addr, addr, sizeof(addr), 2), + pj_sockaddr_get_port(&ns->addr), + state_names[ns->state], + ns->state_expiry.sec - now.sec, + PJ_TIME_VAL_MSEC(ns->rt_delay))); } PJ_LOG(3,(resolver->name.ptr, " Nb. of cached responses: %u", - pj_hash_count(resolver->hrescache))); + pj_hash_count(resolver->hrescache))); if (detail) { - pj_hash_iterator_t itbuf, *it; - it = pj_hash_first(resolver->hrescache, &itbuf); - while (it) { - struct cached_res *cache; - cache = (struct cached_res*)pj_hash_this(resolver->hrescache, it); - PJ_LOG(3,(resolver->name.ptr, - " Type %s: %s", - pj_dns_get_type_name(cache->key.qtype), - cache->key.name)); - it = pj_hash_next(resolver->hrescache, it); - } + pj_hash_iterator_t itbuf, *it; + it = pj_hash_first(resolver->hrescache, &itbuf); + while (it) { + struct cached_res *cache; + cache = (struct cached_res*)pj_hash_this(resolver->hrescache, it); + PJ_LOG(3,(resolver->name.ptr, + " Type %s: %s", + pj_dns_get_type_name(cache->key.qtype), + cache->key.name)); + it = pj_hash_next(resolver->hrescache, it); + } } PJ_LOG(3,(resolver->name.ptr, " Nb. of pending queries: %u (%u)", - pj_hash_count(resolver->hquerybyid), - pj_hash_count(resolver->hquerybyres))); + pj_hash_count(resolver->hquerybyid), + pj_hash_count(resolver->hquerybyres))); if (detail) { - pj_hash_iterator_t itbuf, *it; - it = pj_hash_first(resolver->hquerybyid, &itbuf); - while (it) { - struct pj_dns_async_query *q; - q = (pj_dns_async_query*) pj_hash_this(resolver->hquerybyid, it); - PJ_LOG(3,(resolver->name.ptr, - " Type %s: %s", - pj_dns_get_type_name(q->key.qtype), - q->key.name)); - it = pj_hash_next(resolver->hquerybyid, it); - } + pj_hash_iterator_t itbuf, *it; + it = pj_hash_first(resolver->hquerybyid, &itbuf); + while (it) { + struct pj_dns_async_query *q; + q = (pj_dns_async_query*) pj_hash_this(resolver->hquerybyid, it); + PJ_LOG(3,(resolver->name.ptr, + " Type %s: %s", + pj_dns_get_type_name(q->key.qtype), + q->key.name)); + it = pj_hash_next(resolver->hquerybyid, it); + } } PJ_LOG(3,(resolver->name.ptr, " Nb. of pending query free nodes: %u", - pj_list_size(&resolver->query_free_nodes))); + pj_list_size(&resolver->query_free_nodes))); PJ_LOG(3,(resolver->name.ptr, " Nb. of timer entries: %u", - pj_timer_heap_count(resolver->timer))); + pj_timer_heap_count(resolver->timer))); PJ_LOG(3,(resolver->name.ptr, " Pool capacity: %d, used size: %d", - pj_pool_get_capacity(resolver->pool), - pj_pool_get_used_size(resolver->pool))); + pj_pool_get_capacity(resolver->pool), + pj_pool_get_used_size(resolver->pool))); pj_grp_lock_release(resolver->grp_lock); #endif diff --git a/pjlib-util/src/pjlib-util/resolver_wrap.cpp b/pjlib-util/src/pjlib-util/resolver_wrap.cpp index f70bb0a0b4..26f842d44a 100644 --- a/pjlib-util/src/pjlib-util/resolver_wrap.cpp +++ b/pjlib-util/src/pjlib-util/resolver_wrap.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjlib-util/src/pjlib-util/scanner.c b/pjlib-util/src/pjlib-util/scanner.c index daf96c7e7b..f83fefac20 100644 --- a/pjlib-util/src/pjlib-util/scanner.c +++ b/pjlib-util/src/pjlib-util/scanner.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,10 +27,10 @@ #define THIS_FILE "scanner.c" -#define PJ_SCAN_IS_SPACE(c) ((c)==' ' || (c)=='\t') -#define PJ_SCAN_IS_NEWLINE(c) ((c)=='\r' || (c)=='\n') -#define PJ_SCAN_IS_PROBABLY_SPACE(c) ((c) <= 32) -#define PJ_SCAN_CHECK_EOF(s) (s != scanner->end) +#define PJ_SCAN_IS_SPACE(c) ((c)==' ' || (c)=='\t') +#define PJ_SCAN_IS_NEWLINE(c) ((c)=='\r' || (c)=='\n') +#define PJ_SCAN_IS_PROBABLY_SPACE(c) ((c) <= 32) +#define PJ_SCAN_CHECK_EOF(s) (s != scanner->end) #if defined(PJ_SCANNER_USE_BITWISE) && PJ_SCANNER_USE_BITWISE != 0 @@ -54,7 +53,7 @@ PJ_DEF(void) pj_cis_add_range(pj_cis_t *cis, int cstart, int cend) while (cstart != cend) { PJ_CIS_SET(cis, cstart); - ++cstart; + ++cstart; } } @@ -73,7 +72,7 @@ PJ_DEF(void) pj_cis_add_str( pj_cis_t *cis, const char *str) { while (*str) { PJ_CIS_SET(cis, *str); - ++str; + ++str; } } @@ -81,8 +80,8 @@ PJ_DEF(void) pj_cis_add_cis( pj_cis_t *cis, const pj_cis_t *rhs) { int i; for (i=0; i<256; ++i) { - if (PJ_CIS_ISSET(rhs, i)) - PJ_CIS_SET(cis, i); + if (PJ_CIS_ISSET(rhs, i)) + PJ_CIS_SET(cis, i); } } @@ -98,7 +97,7 @@ PJ_DEF(void) pj_cis_del_str( pj_cis_t *cis, const char *str) { while (*str) { PJ_CIS_CLR(cis, *str); - ++str; + ++str; } } @@ -107,7 +106,7 @@ PJ_DEF(void) pj_cis_invert( pj_cis_t *cis ) unsigned i; /* Can not set zero. This is the requirement of the parser. */ for (i=1; i<256; ++i) { - if (PJ_CIS_ISSET(cis,i)) + if (PJ_CIS_ISSET(cis,i)) PJ_CIS_CLR(cis,i); else PJ_CIS_SET(cis,i); @@ -115,8 +114,8 @@ PJ_DEF(void) pj_cis_invert( pj_cis_t *cis ) } PJ_DEF(void) pj_scan_init( pj_scanner *scanner, char *bufstart, - pj_size_t buflen, unsigned options, - pj_syn_err_func_ptr callback ) + pj_size_t buflen, unsigned options, + pj_syn_err_func_ptr callback ) { PJ_CHECK_STACK(); @@ -128,7 +127,7 @@ PJ_DEF(void) pj_scan_init( pj_scanner *scanner, char *bufstart, scanner->skip_ws = options; if (scanner->skip_ws) - pj_scan_skip_whitespace(scanner); + pj_scan_skip_whitespace(scanner); } @@ -143,53 +142,53 @@ PJ_DEF(void) pj_scan_skip_whitespace( pj_scanner *scanner ) register char *s = scanner->curptr; while (PJ_SCAN_IS_SPACE(*s)) { - ++s; + ++s; } if (PJ_SCAN_IS_NEWLINE(*s) && (scanner->skip_ws & PJ_SCAN_AUTOSKIP_NEWLINE)) { - for (;;) { - if (*s == '\r') { - ++s; - if (*s == '\n') ++s; - ++scanner->line; - scanner->curptr = scanner->start_line = s; - } else if (*s == '\n') { - ++s; - ++scanner->line; - scanner->curptr = scanner->start_line = s; - } else if (PJ_SCAN_IS_SPACE(*s)) { - do { - ++s; - } while (PJ_SCAN_IS_SPACE(*s)); - } else { - break; - } - } + for (;;) { + if (*s == '\r') { + ++s; + if (*s == '\n') ++s; + ++scanner->line; + scanner->curptr = scanner->start_line = s; + } else if (*s == '\n') { + ++s; + ++scanner->line; + scanner->curptr = scanner->start_line = s; + } else if (PJ_SCAN_IS_SPACE(*s)) { + do { + ++s; + } while (PJ_SCAN_IS_SPACE(*s)); + } else { + break; + } + } } if (PJ_SCAN_IS_NEWLINE(*s) && (scanner->skip_ws & PJ_SCAN_AUTOSKIP_WS_HEADER)==PJ_SCAN_AUTOSKIP_WS_HEADER) { - /* Check for header continuation. */ - scanner->curptr = s; - - if (*s == '\r') { - ++s; - } - if (*s == '\n') { - ++s; - } - scanner->start_line = s; - - if (PJ_SCAN_IS_SPACE(*s)) { - register char *t = s; - do { - ++t; - } while (PJ_SCAN_IS_SPACE(*t)); - - ++scanner->line; - scanner->curptr = t; - } + /* Check for header continuation. */ + scanner->curptr = s; + + if (*s == '\r') { + ++s; + } + if (*s == '\n') { + ++s; + } + scanner->start_line = s; + + if (PJ_SCAN_IS_SPACE(*s)) { + register char *t = s; + do { + ++t; + } while (PJ_SCAN_IS_SPACE(*t)); + + ++scanner->line; + scanner->curptr = t; + } } else { - scanner->curptr = s; + scanner->curptr = s; } } @@ -203,26 +202,26 @@ PJ_DEF(void) pj_scan_skip_line( pj_scanner *scanner ) s = pj_memchr(scanner->curptr, '\n', scanner->end - scanner->curptr); if (!s) { - scanner->curptr = scanner->end; + scanner->curptr = scanner->end; } else { - scanner->curptr = scanner->start_line = s+1; - scanner->line++; + scanner->curptr = scanner->start_line = s+1; + scanner->line++; } } PJ_DEF(int) pj_scan_peek( pj_scanner *scanner, - const pj_cis_t *spec, pj_str_t *out) + const pj_cis_t *spec, pj_str_t *out) { register char *s = scanner->curptr; if (s >= scanner->end) { - pj_scan_syntax_err(scanner); - return -1; + pj_scan_syntax_err(scanner); + return -1; } /* Don't need to check EOF with PJ_SCAN_CHECK_EOF(s) */ while (pj_cis_match(spec, *s)) - ++s; + ++s; pj_strset3(out, scanner->curptr, s); return *s; @@ -230,13 +229,13 @@ PJ_DEF(int) pj_scan_peek( pj_scanner *scanner, PJ_DEF(int) pj_scan_peek_n( pj_scanner *scanner, - pj_size_t len, pj_str_t *out) + pj_size_t len, pj_str_t *out) { char *endpos = scanner->curptr + len; if (endpos > scanner->end) { - pj_scan_syntax_err(scanner); - return -1; + pj_scan_syntax_err(scanner); + return -1; } pj_strset(out, scanner->curptr, len); @@ -245,18 +244,18 @@ PJ_DEF(int) pj_scan_peek_n( pj_scanner *scanner, PJ_DEF(int) pj_scan_peek_until( pj_scanner *scanner, - const pj_cis_t *spec, - pj_str_t *out) + const pj_cis_t *spec, + pj_str_t *out) { register char *s = scanner->curptr; if (s >= scanner->end) { - pj_scan_syntax_err(scanner); - return -1; + pj_scan_syntax_err(scanner); + return -1; } while (PJ_SCAN_CHECK_EOF(s) && !pj_cis_match( spec, *s)) - ++s; + ++s; pj_strset3(out, scanner->curptr, s); return *s; @@ -264,19 +263,19 @@ PJ_DEF(int) pj_scan_peek_until( pj_scanner *scanner, PJ_DEF(void) pj_scan_get( pj_scanner *scanner, - const pj_cis_t *spec, pj_str_t *out) + const pj_cis_t *spec, pj_str_t *out) { register char *s = scanner->curptr; pj_assert(pj_cis_match(spec,0)==0); if (pj_scan_is_eof(scanner) || !pj_cis_match(spec, *s)) { - pj_scan_syntax_err(scanner); - return; + pj_scan_syntax_err(scanner); + return; } do { - ++s; + ++s; } while (pj_cis_match(spec, *s)); /* No need to check EOF here (PJ_SCAN_CHECK_EOF(s)) because * buffer is NULL terminated and pj_cis_match(spec,0) should be @@ -288,13 +287,13 @@ PJ_DEF(void) pj_scan_get( pj_scanner *scanner, scanner->curptr = s; if (PJ_SCAN_IS_PROBABLY_SPACE(*s) && scanner->skip_ws) { - pj_scan_skip_whitespace(scanner); + pj_scan_skip_whitespace(scanner); } } PJ_DEF(void) pj_scan_get_unescape( pj_scanner *scanner, - const pj_cis_t *spec, pj_str_t *out) + const pj_cis_t *spec, pj_str_t *out) { register char *s = scanner->curptr; char *dst = s; @@ -305,51 +304,51 @@ PJ_DEF(void) pj_scan_get_unescape( pj_scanner *scanner, pj_assert(pj_cis_match(spec,'%')==0); if (pj_scan_is_eof(scanner) || (!pj_cis_match(spec, *s) && *s != '%')) { - pj_scan_syntax_err(scanner); - return; + pj_scan_syntax_err(scanner); + return; } out->ptr = s; do { - if (*s == '%') { - if (s+3 <= scanner->end && pj_isxdigit(*(s+1)) && - pj_isxdigit(*(s+2))) - { - *dst = (pj_uint8_t) ((pj_hex_digit_to_val(*(s+1)) << 4) + - pj_hex_digit_to_val(*(s+2))); - ++dst; - s += 3; - } else { - *dst++ = *s++; - *dst++ = *s++; - break; - } - } - - if (pj_cis_match(spec, *s)) { - char *start = s; - do { - ++s; - } while (pj_cis_match(spec, *s)); - - if (dst != start) pj_memmove(dst, start, s-start); - dst += (s-start); - } - + if (*s == '%') { + if (s+3 <= scanner->end && pj_isxdigit(*(s+1)) && + pj_isxdigit(*(s+2))) + { + *dst = (pj_uint8_t) ((pj_hex_digit_to_val(*(s+1)) << 4) + + pj_hex_digit_to_val(*(s+2))); + ++dst; + s += 3; + } else { + *dst++ = *s++; + *dst++ = *s++; + break; + } + } + + if (pj_cis_match(spec, *s)) { + char *start = s; + do { + ++s; + } while (pj_cis_match(spec, *s)); + + if (dst != start) pj_memmove(dst, start, s-start); + dst += (s-start); + } + } while (*s == '%'); scanner->curptr = s; out->slen = (dst - out->ptr); if (PJ_SCAN_IS_PROBABLY_SPACE(*s) && scanner->skip_ws) { - pj_scan_skip_whitespace(scanner); + pj_scan_skip_whitespace(scanner); } } PJ_DEF(void) pj_scan_get_quote( pj_scanner *scanner, - int begin_quote, int end_quote, - pj_str_t *out) + int begin_quote, int end_quote, + pj_str_t *out) { char beg = (char)begin_quote; char end = (char)end_quote; @@ -368,53 +367,53 @@ PJ_DEF(void) pj_scan_get_quotes(pj_scanner *scanner, /* Check and eat the begin_quote. */ for (i = 0; i < qsize; ++i) { - if (*s == begin_quote[i]) { - qpair = i; - break; - } + if (*s == begin_quote[i]) { + qpair = i; + break; + } } if (qpair == -1) { - pj_scan_syntax_err(scanner); - return; + pj_scan_syntax_err(scanner); + return; } ++s; /* Loop until end_quote is found. */ do { - /* loop until end_quote is found. */ - while (PJ_SCAN_CHECK_EOF(s) && *s != '\n' && *s != end_quote[qpair]) { - ++s; - } - - /* check that no backslash character precedes the end_quote. */ - if (*s == end_quote[qpair]) { - if (*(s-1) == '\\') { - char *q = s-2; - char *r = s-2; - - while (r != scanner->begin && *r == '\\') { - --r; - } - /* break from main loop if we have odd number of backslashes */ - if (((unsigned)(q-r) & 0x01) == 1) { - break; - } - ++s; - } else { - /* end_quote is not preceeded by backslash. break now. */ - break; - } - } else { - /* loop ended by non-end_quote character. break now. */ - break; - } + /* loop until end_quote is found. */ + while (PJ_SCAN_CHECK_EOF(s) && *s != '\n' && *s != end_quote[qpair]) { + ++s; + } + + /* check that no backslash character precedes the end_quote. */ + if (*s == end_quote[qpair]) { + if (*(s-1) == '\\') { + char *q = s-2; + char *r = s-2; + + while (r != scanner->begin && *r == '\\') { + --r; + } + /* break from main loop if we have odd number of backslashes */ + if (((unsigned)(q-r) & 0x01) == 1) { + break; + } + ++s; + } else { + /* end_quote is not preceeded by backslash. break now. */ + break; + } + } else { + /* loop ended by non-end_quote character. break now. */ + break; + } } while (1); /* Check and eat the end quote. */ if (*s != end_quote[qpair]) { - pj_scan_syntax_err(scanner); - return; + pj_scan_syntax_err(scanner); + return; } ++s; @@ -423,17 +422,17 @@ PJ_DEF(void) pj_scan_get_quotes(pj_scanner *scanner, scanner->curptr = s; if (PJ_SCAN_IS_PROBABLY_SPACE(*s) && scanner->skip_ws) { - pj_scan_skip_whitespace(scanner); + pj_scan_skip_whitespace(scanner); } } PJ_DEF(void) pj_scan_get_n( pj_scanner *scanner, - unsigned N, pj_str_t *out) + unsigned N, pj_str_t *out) { if (scanner->curptr + N > scanner->end) { - pj_scan_syntax_err(scanner); - return; + pj_scan_syntax_err(scanner); + return; } pj_strset(out, scanner->curptr, N); @@ -441,9 +440,9 @@ PJ_DEF(void) pj_scan_get_n( pj_scanner *scanner, scanner->curptr += N; if (!pj_scan_is_eof(scanner) && - PJ_SCAN_IS_PROBABLY_SPACE(*scanner->curptr) && scanner->skip_ws) + PJ_SCAN_IS_PROBABLY_SPACE(*scanner->curptr) && scanner->skip_ws) { - pj_scan_skip_whitespace(scanner); + pj_scan_skip_whitespace(scanner); } } @@ -454,8 +453,8 @@ PJ_DEF(int) pj_scan_get_char( pj_scanner *scanner ) int chr; if (s >= scanner->end || !*s) { - pj_scan_syntax_err(scanner); - return 0; + pj_scan_syntax_err(scanner); + return 0; } chr = *s; @@ -463,9 +462,9 @@ PJ_DEF(int) pj_scan_get_char( pj_scanner *scanner ) ++s; scanner->curptr = s; if (PJ_SCAN_CHECK_EOF(s) && PJ_SCAN_IS_PROBABLY_SPACE(*s) && - scanner->skip_ws) + scanner->skip_ws) { - pj_scan_skip_whitespace(scanner); + pj_scan_skip_whitespace(scanner); } return chr; } @@ -474,16 +473,16 @@ PJ_DEF(int) pj_scan_get_char( pj_scanner *scanner ) PJ_DEF(void) pj_scan_get_newline( pj_scanner *scanner ) { if (pj_scan_is_eof(scanner) || !PJ_SCAN_IS_NEWLINE(*scanner->curptr)) { - pj_scan_syntax_err(scanner); - return; + pj_scan_syntax_err(scanner); + return; } /* We have checked scanner->curptr validity above */ if (*scanner->curptr == '\r') { - ++scanner->curptr; + ++scanner->curptr; } if (!pj_scan_is_eof(scanner) && *scanner->curptr == '\n') { - ++scanner->curptr; + ++scanner->curptr; } ++scanner->line; @@ -494,9 +493,9 @@ PJ_DEF(void) pj_scan_get_newline( pj_scanner *scanner ) * This would cause scanner to incorrectly eat two new lines, e.g. * when parsing: * - * Content-Length: 120\r\n - * \r\n - * ... + * Content-Length: 120\r\n + * \r\n + * ... * * When pj_scan_get_newline() is called to parse the first newline * in the Content-Length header, it will eat the second newline @@ -510,17 +509,17 @@ PJ_DEF(void) pj_scan_get_newline( pj_scanner *scanner ) PJ_DEF(void) pj_scan_get_until( pj_scanner *scanner, - const pj_cis_t *spec, pj_str_t *out) + const pj_cis_t *spec, pj_str_t *out) { register char *s = scanner->curptr; if (s >= scanner->end) { - pj_scan_syntax_err(scanner); - return; + pj_scan_syntax_err(scanner); + return; } while (PJ_SCAN_CHECK_EOF(s) && !pj_cis_match(spec, *s)) { - ++s; + ++s; } pj_strset3(out, scanner->curptr, s); @@ -528,25 +527,25 @@ PJ_DEF(void) pj_scan_get_until( pj_scanner *scanner, scanner->curptr = s; if (!pj_scan_is_eof(scanner) && PJ_SCAN_IS_PROBABLY_SPACE(*s) && - scanner->skip_ws) + scanner->skip_ws) { - pj_scan_skip_whitespace(scanner); + pj_scan_skip_whitespace(scanner); } } PJ_DEF(void) pj_scan_get_until_ch( pj_scanner *scanner, - int until_char, pj_str_t *out) + int until_char, pj_str_t *out) { register char *s = scanner->curptr; if (s >= scanner->end) { - pj_scan_syntax_err(scanner); - return; + pj_scan_syntax_err(scanner); + return; } while (PJ_SCAN_CHECK_EOF(s) && *s != until_char) { - ++s; + ++s; } pj_strset3(out, scanner->curptr, s); @@ -554,27 +553,27 @@ PJ_DEF(void) pj_scan_get_until_ch( pj_scanner *scanner, scanner->curptr = s; if (!pj_scan_is_eof(scanner) && PJ_SCAN_IS_PROBABLY_SPACE(*s) && - scanner->skip_ws) + scanner->skip_ws) { - pj_scan_skip_whitespace(scanner); + pj_scan_skip_whitespace(scanner); } } PJ_DEF(void) pj_scan_get_until_chr( pj_scanner *scanner, - const char *until_spec, pj_str_t *out) + const char *until_spec, pj_str_t *out) { register char *s = scanner->curptr; pj_size_t speclen; if (s >= scanner->end) { - pj_scan_syntax_err(scanner); - return; + pj_scan_syntax_err(scanner); + return; } speclen = strlen(until_spec); while (PJ_SCAN_CHECK_EOF(s) && !memchr(until_spec, *s, speclen)) { - ++s; + ++s; } pj_strset3(out, scanner->curptr, s); @@ -582,26 +581,26 @@ PJ_DEF(void) pj_scan_get_until_chr( pj_scanner *scanner, scanner->curptr = s; if (!pj_scan_is_eof(scanner) && PJ_SCAN_IS_PROBABLY_SPACE(*s) && - scanner->skip_ws) + scanner->skip_ws) { - pj_scan_skip_whitespace(scanner); + pj_scan_skip_whitespace(scanner); } } PJ_DEF(void) pj_scan_advance_n( pj_scanner *scanner, - unsigned N, pj_bool_t skip_ws) + unsigned N, pj_bool_t skip_ws) { if (scanner->curptr + N > scanner->end) { - pj_scan_syntax_err(scanner); - return; + pj_scan_syntax_err(scanner); + return; } scanner->curptr += N; if (!pj_scan_is_eof(scanner) && - PJ_SCAN_IS_PROBABLY_SPACE(*scanner->curptr) && skip_ws) + PJ_SCAN_IS_PROBABLY_SPACE(*scanner->curptr) && skip_ws) { - pj_scan_skip_whitespace(scanner); + pj_scan_skip_whitespace(scanner); } } @@ -609,8 +608,8 @@ PJ_DEF(void) pj_scan_advance_n( pj_scanner *scanner, PJ_DEF(int) pj_scan_strcmp( pj_scanner *scanner, const char *s, int len) { if (scanner->curptr + len > scanner->end) { - pj_scan_syntax_err(scanner); - return -1; + pj_scan_syntax_err(scanner); + return -1; } return strncmp(scanner->curptr, s, len); } @@ -619,24 +618,24 @@ PJ_DEF(int) pj_scan_strcmp( pj_scanner *scanner, const char *s, int len) PJ_DEF(int) pj_scan_stricmp( pj_scanner *scanner, const char *s, int len) { if (scanner->curptr + len > scanner->end) { - pj_scan_syntax_err(scanner); - return -1; + pj_scan_syntax_err(scanner); + return -1; } return pj_ansi_strnicmp(scanner->curptr, s, len); } PJ_DEF(int) pj_scan_stricmp_alnum( pj_scanner *scanner, const char *s, - int len) + int len) { if (scanner->curptr + len > scanner->end) { - pj_scan_syntax_err(scanner); - return -1; + pj_scan_syntax_err(scanner); + return -1; } return strnicmp_alnum(scanner->curptr, s, len); } PJ_DEF(void) pj_scan_save_state( const pj_scanner *scanner, - pj_scan_state *state) + pj_scan_state *state) { state->curptr = scanner->curptr; state->line = scanner->line; @@ -645,7 +644,7 @@ PJ_DEF(void) pj_scan_save_state( const pj_scanner *scanner, PJ_DEF(void) pj_scan_restore_state( pj_scanner *scanner, - pj_scan_state *state) + pj_scan_state *state) { scanner->curptr = state->curptr; scanner->line = state->line; diff --git a/pjlib-util/src/pjlib-util/scanner_cis_bitwise.c b/pjlib-util/src/pjlib-util/scanner_cis_bitwise.c index 7eea1c2a26..8142dd794d 100644 --- a/pjlib-util/src/pjlib-util/scanner_cis_bitwise.c +++ b/pjlib-util/src/pjlib-util/scanner_cis_bitwise.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,7 +37,7 @@ PJ_DEF(pj_status_t) pj_cis_init(pj_cis_buf_t *cis_buf, pj_cis_t *cis) for (i=0; iuse_mask & (1 << i)) == 0) { cis->cis_id = i; - cis_buf->use_mask |= (1 << i); + cis_buf->use_mask |= (1 << i); return PJ_SUCCESS; } } diff --git a/pjlib-util/src/pjlib-util/scanner_cis_uint.c b/pjlib-util/src/pjlib-util/scanner_cis_uint.c index 4e126a783c..b61ee147b5 100644 --- a/pjlib-util/src/pjlib-util/scanner_cis_uint.c +++ b/pjlib-util/src/pjlib-util/scanner_cis_uint.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib-util/src/pjlib-util/sha1.c b/pjlib-util/src/pjlib-util/sha1.c index a707a9689c..e72a82da81 100644 --- a/pjlib-util/src/pjlib-util/sha1.c +++ b/pjlib-util/src/pjlib-util/sha1.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Modified 2/07 * By Benny Prijono @@ -20,10 +19,10 @@ Still 100% Public Domain Corrected a problem which generated improper hash values on 16 bit machines Routine SHA1Update changed from - void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned int + void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned int len) to - void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned + void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned long len) The 'len' parameter was declared an int which works fine on 32 bit machines. @@ -204,20 +203,20 @@ PJ_DEF(void) pj_sha1_init(pj_sha1_context* context) /* Run your data through this. */ PJ_DEF(void) pj_sha1_update(pj_sha1_context* context, - const pj_uint8_t* data, const pj_size_t len) + const pj_uint8_t* data, const pj_size_t len) { pj_size_t i, j; j = (context->count[0] >> 3) & 63; if ((context->count[0] += (pj_uint32_t)len << 3) < (len << 3)) - context->count[1]++; + context->count[1]++; context->count[1] += ((pj_uint32_t)len >> 29); if ((j + len) > 63) { pj_memcpy(&context->buffer[j], data, (i = 64-j)); SHA1_Transform(context->state, context->buffer); for ( ; i + 63 < len; i += 64) { - pj_uint8_t tmp[64]; - pj_memcpy(tmp, data + i, 64); + pj_uint8_t tmp[64]; + pj_memcpy(tmp, data + i, 64); SHA1_Transform(context->state, tmp); } j = 0; @@ -230,7 +229,7 @@ PJ_DEF(void) pj_sha1_update(pj_sha1_context* context, /* Add padding and return the message digest. */ PJ_DEF(void) pj_sha1_final(pj_sha1_context* context, - pj_uint8_t digest[PJ_SHA1_DIGEST_SIZE]) + pj_uint8_t digest[PJ_SHA1_DIGEST_SIZE]) { pj_uint32_t i; pj_uint8_t finalcount[8]; @@ -254,7 +253,7 @@ PJ_DEF(void) pj_sha1_final(pj_sha1_context* context, pj_memset(context->buffer, 0, 64); pj_memset(context->state, 0, 20); pj_memset(context->count, 0, 8); - pj_memset(finalcount, 0, 8); /* SWR */ + pj_memset(finalcount, 0, 8); /* SWR */ #ifdef SHA1HANDSOFF /* make SHA1Transform overwrite its own static vars */ SHA1_Transform(context->state, context->buffer); diff --git a/pjlib-util/src/pjlib-util/srv_resolver.c b/pjlib-util/src/pjlib-util/srv_resolver.c index 23234bdb46..7bd7b6c3eb 100644 --- a/pjlib-util/src/pjlib-util/srv_resolver.c +++ b/pjlib-util/src/pjlib-util/srv_resolver.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,66 +29,66 @@ #define THIS_FILE "srv_resolver.c" -#define ADDR_MAX_COUNT PJ_DNS_MAX_IP_IN_A_REC +#define ADDR_MAX_COUNT PJ_DNS_MAX_IP_IN_A_REC struct common { - pj_dns_type type; /**< Type of this structure.*/ + pj_dns_type type; /**< Type of this structure.*/ }; #pragma pack(1) struct srv_target { - struct common common; - struct common common_aaaa; + struct common common; + struct common common_aaaa; pj_dns_srv_async_query *parent; - pj_str_t target_name; - pj_dns_async_query *q_a; - pj_dns_async_query *q_aaaa; - char target_buf[PJ_MAX_HOSTNAME]; - pj_str_t cname; - char cname_buf[PJ_MAX_HOSTNAME]; - pj_uint16_t port; - unsigned priority; - unsigned weight; - unsigned sum; - unsigned addr_cnt; - pj_sockaddr addr[ADDR_MAX_COUNT];/**< Address family and IP.*/ + pj_str_t target_name; + pj_dns_async_query *q_a; + pj_dns_async_query *q_aaaa; + char target_buf[PJ_MAX_HOSTNAME]; + pj_str_t cname; + char cname_buf[PJ_MAX_HOSTNAME]; + pj_uint16_t port; + unsigned priority; + unsigned weight; + unsigned sum; + unsigned addr_cnt; + pj_sockaddr addr[ADDR_MAX_COUNT];/**< Address family and IP.*/ }; #pragma pack() struct pj_dns_srv_async_query { - struct common common; - char *objname; + struct common common; + char *objname; - pj_dns_type dns_state; /**< DNS type being resolved. */ - pj_dns_resolver *resolver; /**< Resolver SIP instance. */ - void *token; - pj_dns_async_query *q_srv; + pj_dns_type dns_state; /**< DNS type being resolved. */ + pj_dns_resolver *resolver; /**< Resolver SIP instance. */ + void *token; + pj_dns_async_query *q_srv; pj_dns_srv_resolver_cb *cb; - pj_status_t last_error; + pj_status_t last_error; /* Original request: */ - unsigned option; - pj_str_t full_name; - pj_str_t domain_part; - pj_uint16_t def_port; + unsigned option; + pj_str_t full_name; + pj_str_t domain_part; + pj_uint16_t def_port; /* SRV records and their resolved IP addresses: */ - unsigned srv_cnt; - struct srv_target srv[PJ_DNS_SRV_MAX_ADDR]; + unsigned srv_cnt; + struct srv_target srv[PJ_DNS_SRV_MAX_ADDR]; /* Number of hosts in SRV records that the IP address has been resolved */ - unsigned host_resolved; + unsigned host_resolved; }; /* Async resolver callback, forward decl. */ static void dns_callback(void *user_data, - pj_status_t status, - pj_dns_parsed_packet *pkt); + pj_status_t status, + pj_dns_parsed_packet *pkt); @@ -97,14 +96,14 @@ static void dns_callback(void *user_data, * The public API to invoke DNS SRV resolution. */ PJ_DEF(pj_status_t) pj_dns_srv_resolve( const pj_str_t *domain_name, - const pj_str_t *res_name, - unsigned def_port, - pj_pool_t *pool, - pj_dns_resolver *resolver, - unsigned option, - void *token, - pj_dns_srv_resolver_cb *cb, - pj_dns_srv_async_query **p_query) + const pj_str_t *res_name, + unsigned def_port, + pj_pool_t *pool, + pj_dns_resolver *resolver, + unsigned option, + void *token, + pj_dns_srv_resolver_cb *cb, + pj_dns_srv_async_query **p_query) { pj_size_t len; pj_str_t target_name; @@ -112,15 +111,15 @@ PJ_DEF(pj_status_t) pj_dns_srv_resolve( const pj_str_t *domain_name, pj_status_t status; PJ_ASSERT_RETURN(domain_name && domain_name->slen && - res_name && res_name->slen && - pool && resolver && cb, PJ_EINVAL); + res_name && res_name->slen && + pool && resolver && cb, PJ_EINVAL); /* Build full name */ len = domain_name->slen + res_name->slen + 2; target_name.ptr = (char*) pj_pool_alloc(pool, len); pj_strcpy(&target_name, res_name); if (res_name->ptr[res_name->slen-1] != '.') - pj_strcat2(&target_name, "."); + pj_strcat2(&target_name, "."); len = target_name.slen; pj_strcat(&target_name, domain_name); target_name.ptr[target_name.slen] = '\0'; @@ -141,24 +140,24 @@ PJ_DEF(pj_status_t) pj_dns_srv_resolve( const pj_str_t *domain_name, /* Normalize query job option PJ_DNS_SRV_RESOLVE_AAAA_ONLY */ if (query_job->option & PJ_DNS_SRV_RESOLVE_AAAA_ONLY) - query_job->option |= PJ_DNS_SRV_RESOLVE_AAAA; + query_job->option |= PJ_DNS_SRV_RESOLVE_AAAA; /* Start the asynchronous query_job */ query_job->dns_state = PJ_DNS_TYPE_SRV; PJ_LOG(5, (query_job->objname, - "Starting async DNS %s query_job: target=%.*s:%d", - pj_dns_get_type_name(query_job->dns_state), - (int)target_name.slen, target_name.ptr, - def_port)); + "Starting async DNS %s query_job: target=%.*s:%d", + pj_dns_get_type_name(query_job->dns_state), + (int)target_name.slen, target_name.ptr, + def_port)); status = pj_dns_resolver_start_query(resolver, &target_name, - query_job->dns_state, 0, - &dns_callback, - query_job, &query_job->q_srv); + query_job->dns_state, 0, + &dns_callback, + query_job, &query_job->q_srv); if (status==PJ_SUCCESS && p_query) - *p_query = query_job; + *p_query = query_job; return status; } @@ -168,36 +167,36 @@ PJ_DEF(pj_status_t) pj_dns_srv_resolve( const pj_str_t *domain_name, * Cancel pending query. */ PJ_DEF(pj_status_t) pj_dns_srv_cancel_query(pj_dns_srv_async_query *query, - pj_bool_t notify) + pj_bool_t notify) { pj_bool_t has_pending = PJ_FALSE; unsigned i; if (query->q_srv) { - pj_dns_resolver_cancel_query(query->q_srv, PJ_FALSE); - query->q_srv = NULL; - has_pending = PJ_TRUE; + pj_dns_resolver_cancel_query(query->q_srv, PJ_FALSE); + query->q_srv = NULL; + has_pending = PJ_TRUE; } for (i=0; isrv_cnt; ++i) { - struct srv_target *srv = &query->srv[i]; - if (srv->q_a) { - pj_dns_resolver_cancel_query(srv->q_a, PJ_FALSE); - srv->q_a = NULL; - has_pending = PJ_TRUE; - } - if (srv->q_aaaa) { - /* Check if it is a dummy query. */ - if (srv->q_aaaa != (pj_dns_async_query*)0x1) { - pj_dns_resolver_cancel_query(srv->q_aaaa, PJ_FALSE); - has_pending = PJ_TRUE; - } - srv->q_aaaa = NULL; - } + struct srv_target *srv = &query->srv[i]; + if (srv->q_a) { + pj_dns_resolver_cancel_query(srv->q_a, PJ_FALSE); + srv->q_a = NULL; + has_pending = PJ_TRUE; + } + if (srv->q_aaaa) { + /* Check if it is a dummy query. */ + if (srv->q_aaaa != (pj_dns_async_query*)0x1) { + pj_dns_resolver_cancel_query(srv->q_aaaa, PJ_FALSE); + has_pending = PJ_TRUE; + } + srv->q_aaaa = NULL; + } } if (has_pending && notify && query->cb) { - (*query->cb)(query->token, PJ_ECANCELLED, NULL); + (*query->cb)(query->token, PJ_ECANCELLED, NULL); } return has_pending? PJ_SUCCESS : PJ_EINVALIDOP; @@ -205,134 +204,134 @@ PJ_DEF(pj_status_t) pj_dns_srv_cancel_query(pj_dns_srv_async_query *query, #define SWAP(type,ptr1,ptr2) if (ptr1 != ptr2) { \ - type tmp; \ - pj_memcpy(&tmp, ptr1, sizeof(type)); \ - pj_memcpy(ptr1, ptr2, sizeof(type)); \ - (ptr1)->target_name.ptr = (ptr1)->target_buf;\ - pj_memcpy(ptr2, &tmp, sizeof(type)); \ - (ptr2)->target_name.ptr = (ptr2)->target_buf;\ - } else {} + type tmp; \ + pj_memcpy(&tmp, ptr1, sizeof(type)); \ + pj_memcpy(ptr1, ptr2, sizeof(type)); \ + (ptr1)->target_name.ptr = (ptr1)->target_buf;\ + pj_memcpy(ptr2, &tmp, sizeof(type)); \ + (ptr2)->target_name.ptr = (ptr2)->target_buf;\ + } else {} /* Build server entries in the query_job based on received SRV response */ static void build_server_entries(pj_dns_srv_async_query *query_job, - pj_dns_parsed_packet *response) + pj_dns_parsed_packet *response) { unsigned i; /* Save the Resource Records in DNS answer into SRV targets. */ query_job->srv_cnt = 0; for (i=0; ihdr.anscount && - query_job->srv_cnt < PJ_DNS_SRV_MAX_ADDR; ++i) + query_job->srv_cnt < PJ_DNS_SRV_MAX_ADDR; ++i) { - pj_dns_parsed_rr *rr = &response->ans[i]; - struct srv_target *srv = &query_job->srv[query_job->srv_cnt]; - - if (rr->type != PJ_DNS_TYPE_SRV) { - PJ_LOG(4,(query_job->objname, - "Received non SRV answer for SRV query_job!")); - continue; - } - - if (rr->rdata.srv.target.slen > PJ_MAX_HOSTNAME) { - PJ_LOG(4,(query_job->objname, "Hostname is too long!")); - continue; - } - - if (rr->rdata.srv.target.slen == 0) { - PJ_LOG(4,(query_job->objname, "Hostname is empty!")); - continue; - } - - /* Build the SRV entry for RR */ - pj_bzero(srv, sizeof(*srv)); - srv->target_name.ptr = srv->target_buf; - pj_strncpy(&srv->target_name, &rr->rdata.srv.target, - sizeof(srv->target_buf)); - srv->port = rr->rdata.srv.port; - srv->priority = rr->rdata.srv.prio; - srv->weight = rr->rdata.srv.weight; - - ++query_job->srv_cnt; + pj_dns_parsed_rr *rr = &response->ans[i]; + struct srv_target *srv = &query_job->srv[query_job->srv_cnt]; + + if (rr->type != PJ_DNS_TYPE_SRV) { + PJ_LOG(4,(query_job->objname, + "Received non SRV answer for SRV query_job!")); + continue; + } + + if (rr->rdata.srv.target.slen > PJ_MAX_HOSTNAME) { + PJ_LOG(4,(query_job->objname, "Hostname is too long!")); + continue; + } + + if (rr->rdata.srv.target.slen == 0) { + PJ_LOG(4,(query_job->objname, "Hostname is empty!")); + continue; + } + + /* Build the SRV entry for RR */ + pj_bzero(srv, sizeof(*srv)); + srv->target_name.ptr = srv->target_buf; + pj_strncpy(&srv->target_name, &rr->rdata.srv.target, + sizeof(srv->target_buf)); + srv->port = rr->rdata.srv.port; + srv->priority = rr->rdata.srv.prio; + srv->weight = rr->rdata.srv.weight; + + ++query_job->srv_cnt; } if (query_job->srv_cnt == 0) { - PJ_LOG(4,(query_job->objname, - "Could not find SRV record in DNS answer!")); - return; + PJ_LOG(4,(query_job->objname, + "Could not find SRV record in DNS answer!")); + return; } /* First pass: - * order the entries based on priority. + * order the entries based on priority. */ for (i=0; isrv_cnt-1; ++i) { - unsigned min = i, j; - for (j=i+1; jsrv_cnt; ++j) { - if (query_job->srv[j].priority < query_job->srv[min].priority) - min = j; - } - SWAP(struct srv_target, &query_job->srv[i], &query_job->srv[min]); + unsigned min = i, j; + for (j=i+1; jsrv_cnt; ++j) { + if (query_job->srv[j].priority < query_job->srv[min].priority) + min = j; + } + SWAP(struct srv_target, &query_job->srv[i], &query_job->srv[min]); } /* Second pass: - * Order the entry in a list. + * Order the entry in a list. * * The algorithm for selecting server among servers with the same * priority is described in RFC 2782. */ for (i=0; isrv_cnt; ++i) { - unsigned j, count=1, sum; - - /* Calculate running sum for servers with the same priority */ - sum = query_job->srv[i].sum = query_job->srv[i].weight; - for (j=i+1; jsrv_cnt && - query_job->srv[j].priority == query_job->srv[i].priority; ++j) - { - sum += query_job->srv[j].weight; - query_job->srv[j].sum = sum; - ++count; - } - - if (count > 1) { - unsigned r; - - /* Elect one random number between zero and the total sum of - * weight (inclusive). - */ - r = pj_rand() % (sum + 1); - - /* Select the first server which running sum is greater than or - * equal to the random number. - */ - for (j=i; jsrv[j].sum >= r) - break; - } - - /* Must have selected one! */ - pj_assert(j != i+count); - - /* Put this entry in front (of entries with same priority) */ - SWAP(struct srv_target, &query_job->srv[i], &query_job->srv[j]); - - /* Remove all other entries (of the same priority) */ - /* Don't need to do this. - * See https://github.com/pjsip/pjproject/issues/1719 - while (count > 1) { - pj_array_erase(query_job->srv, sizeof(struct srv_target), - query_job->srv_cnt, i+1); - --count; - --query_job->srv_cnt; - } - */ - } + unsigned j, count=1, sum; + + /* Calculate running sum for servers with the same priority */ + sum = query_job->srv[i].sum = query_job->srv[i].weight; + for (j=i+1; jsrv_cnt && + query_job->srv[j].priority == query_job->srv[i].priority; ++j) + { + sum += query_job->srv[j].weight; + query_job->srv[j].sum = sum; + ++count; + } + + if (count > 1) { + unsigned r; + + /* Elect one random number between zero and the total sum of + * weight (inclusive). + */ + r = pj_rand() % (sum + 1); + + /* Select the first server which running sum is greater than or + * equal to the random number. + */ + for (j=i; jsrv[j].sum >= r) + break; + } + + /* Must have selected one! */ + pj_assert(j != i+count); + + /* Put this entry in front (of entries with same priority) */ + SWAP(struct srv_target, &query_job->srv[i], &query_job->srv[j]); + + /* Remove all other entries (of the same priority) */ + /* Don't need to do this. + * See https://github.com/pjsip/pjproject/issues/1719 + while (count > 1) { + pj_array_erase(query_job->srv, sizeof(struct srv_target), + query_job->srv_cnt, i+1); + --count; + --query_job->srv_cnt; + } + */ + } } /* Since we've been moving around SRV entries, update the pointers * in target_name. */ for (i=0; isrv_cnt; ++i) { - query_job->srv[i].target_name.ptr = query_job->srv[i].target_buf; + query_job->srv[i].target_name.ptr = query_job->srv[i].target_buf; } /* Check for Additional Info section if A/AAAA records are available, and @@ -340,69 +339,69 @@ static void build_server_entries(pj_dns_srv_async_query *query_job, * record with another DNS query_job). */ for (i=0; ihdr.arcount; ++i) { - pj_dns_parsed_rr *rr = &response->arr[i]; - unsigned j; - - /* Skip non-A/AAAA record */ - if (rr->type != PJ_DNS_TYPE_A && rr->type != PJ_DNS_TYPE_AAAA) - continue; - - /* Also skip if: - * - it is A record and app only want AAAA record, or - * - it is AAAA record and app does not want AAAA record - */ - if ((rr->type == PJ_DNS_TYPE_A && - (query_job->option & PJ_DNS_SRV_RESOLVE_AAAA_ONLY)!=0) || - (rr->type == PJ_DNS_TYPE_AAAA && - (query_job->option & PJ_DNS_SRV_RESOLVE_AAAA)==0)) - { - continue; - } - - /* Yippeaiyee!! There is an "A/AAAA" record! - * Update the IP address of the corresponding SRV record. - */ - for (j=0; jsrv_cnt; ++j) { - if (pj_stricmp(&rr->name, &query_job->srv[j].target_name)==0 - && query_job->srv[j].addr_cnt < ADDR_MAX_COUNT) - { - unsigned cnt = query_job->srv[j].addr_cnt; - if (rr->type == PJ_DNS_TYPE_A) { - pj_sockaddr_init(pj_AF_INET(), - &query_job->srv[j].addr[cnt], NULL, - query_job->srv[j].port); - query_job->srv[j].addr[cnt].ipv4.sin_addr = - rr->rdata.a.ip_addr; - } else { - pj_sockaddr_init(pj_AF_INET6(), - &query_job->srv[j].addr[cnt], NULL, - query_job->srv[j].port); - query_job->srv[j].addr[cnt].ipv6.sin6_addr = - rr->rdata.aaaa.ip_addr; - } - - /* Only increment host_resolved once per SRV record */ - if (query_job->srv[j].addr_cnt == 0) - ++query_job->host_resolved; - - ++query_job->srv[j].addr_cnt; - break; - } - } - - /* Not valid message; SRV entry might have been deleted in - * server selection process. - */ - /* - if (j == query_job->srv_cnt) { - PJ_LOG(4,(query_job->objname, - "Received DNS SRV answer with A record, but " - "couldn't find matching name (name=%.*s)", - (int)rr->name.slen, - rr->name.ptr)); - } - */ - + pj_dns_parsed_rr *rr = &response->arr[i]; + unsigned j; + + /* Skip non-A/AAAA record */ + if (rr->type != PJ_DNS_TYPE_A && rr->type != PJ_DNS_TYPE_AAAA) + continue; + + /* Also skip if: + * - it is A record and app only want AAAA record, or + * - it is AAAA record and app does not want AAAA record + */ + if ((rr->type == PJ_DNS_TYPE_A && + (query_job->option & PJ_DNS_SRV_RESOLVE_AAAA_ONLY)!=0) || + (rr->type == PJ_DNS_TYPE_AAAA && + (query_job->option & PJ_DNS_SRV_RESOLVE_AAAA)==0)) + { + continue; + } + + /* Yippeaiyee!! There is an "A/AAAA" record! + * Update the IP address of the corresponding SRV record. + */ + for (j=0; jsrv_cnt; ++j) { + if (pj_stricmp(&rr->name, &query_job->srv[j].target_name)==0 + && query_job->srv[j].addr_cnt < ADDR_MAX_COUNT) + { + unsigned cnt = query_job->srv[j].addr_cnt; + if (rr->type == PJ_DNS_TYPE_A) { + pj_sockaddr_init(pj_AF_INET(), + &query_job->srv[j].addr[cnt], NULL, + query_job->srv[j].port); + query_job->srv[j].addr[cnt].ipv4.sin_addr = + rr->rdata.a.ip_addr; + } else { + pj_sockaddr_init(pj_AF_INET6(), + &query_job->srv[j].addr[cnt], NULL, + query_job->srv[j].port); + query_job->srv[j].addr[cnt].ipv6.sin6_addr = + rr->rdata.aaaa.ip_addr; + } + + /* Only increment host_resolved once per SRV record */ + if (query_job->srv[j].addr_cnt == 0) + ++query_job->host_resolved; + + ++query_job->srv[j].addr_cnt; + break; + } + } + + /* Not valid message; SRV entry might have been deleted in + * server selection process. + */ + /* + if (j == query_job->srv_cnt) { + PJ_LOG(4,(query_job->objname, + "Received DNS SRV answer with A record, but " + "couldn't find matching name (name=%.*s)", + (int)rr->name.slen, + rr->name.ptr)); + } + */ + } /* Rescan again the name specified in the SRV record to see if IP @@ -410,63 +409,63 @@ static void build_server_entries(pj_dns_srv_async_query *query_job, * knows..). */ for (i=0; isrv_cnt; ++i) { - pj_in_addr addr; - pj_in6_addr addr6; - unsigned cnt = query_job->srv[i].addr_cnt; - - if (cnt != 0) { - /* IP address already resolved */ - continue; - } - - if ((query_job->option & PJ_DNS_SRV_RESOLVE_AAAA_ONLY)==0 && - pj_inet_pton(pj_AF_INET(), &query_job->srv[i].target_name, - &addr) == PJ_SUCCESS) - { - pj_sockaddr_init(pj_AF_INET(), &query_job->srv[i].addr[cnt], - NULL, query_job->srv[i].port); - query_job->srv[i].addr[cnt].ipv4.sin_addr = addr; - ++query_job->srv[i].addr_cnt; - ++query_job->host_resolved; - } else if ((query_job->option & PJ_DNS_SRV_RESOLVE_AAAA)!=0 && - pj_inet_pton(pj_AF_INET6(), &query_job->srv[i].target_name, - &addr6) == PJ_SUCCESS) - { - pj_sockaddr_init(pj_AF_INET6(), &query_job->srv[i].addr[cnt], - NULL, query_job->srv[i].port); - query_job->srv[i].addr[cnt].ipv6.sin6_addr = addr6; - ++query_job->srv[i].addr_cnt; - ++query_job->host_resolved; - } + pj_in_addr addr; + pj_in6_addr addr6; + unsigned cnt = query_job->srv[i].addr_cnt; + + if (cnt != 0) { + /* IP address already resolved */ + continue; + } + + if ((query_job->option & PJ_DNS_SRV_RESOLVE_AAAA_ONLY)==0 && + pj_inet_pton(pj_AF_INET(), &query_job->srv[i].target_name, + &addr) == PJ_SUCCESS) + { + pj_sockaddr_init(pj_AF_INET(), &query_job->srv[i].addr[cnt], + NULL, query_job->srv[i].port); + query_job->srv[i].addr[cnt].ipv4.sin_addr = addr; + ++query_job->srv[i].addr_cnt; + ++query_job->host_resolved; + } else if ((query_job->option & PJ_DNS_SRV_RESOLVE_AAAA)!=0 && + pj_inet_pton(pj_AF_INET6(), &query_job->srv[i].target_name, + &addr6) == PJ_SUCCESS) + { + pj_sockaddr_init(pj_AF_INET6(), &query_job->srv[i].addr[cnt], + NULL, query_job->srv[i].port); + query_job->srv[i].addr[cnt].ipv6.sin6_addr = addr6; + ++query_job->srv[i].addr_cnt; + ++query_job->host_resolved; + } } /* Print resolved entries to the log */ PJ_LOG(5,(query_job->objname, - "SRV query_job for %.*s completed, " - "%d of %d total entries selected%c", - (int)query_job->full_name.slen, - query_job->full_name.ptr, - query_job->srv_cnt, - response->hdr.anscount, - (query_job->srv_cnt ? ':' : ' '))); + "SRV query_job for %.*s completed, " + "%d of %d total entries selected%c", + (int)query_job->full_name.slen, + query_job->full_name.ptr, + query_job->srv_cnt, + response->hdr.anscount, + (query_job->srv_cnt ? ':' : ' '))); for (i=0; isrv_cnt; ++i) { - char addr[PJ_INET6_ADDRSTRLEN]; - - if (query_job->srv[i].addr_cnt != 0) { - pj_sockaddr_print(&query_job->srv[i].addr[0], - addr, sizeof(addr), 2); - } else - pj_ansi_strcpy(addr, "-"); - - PJ_LOG(5,(query_job->objname, - " %d: SRV %d %d %d %.*s (%s)", - i, query_job->srv[i].priority, - query_job->srv[i].weight, - query_job->srv[i].port, - (int)query_job->srv[i].target_name.slen, - query_job->srv[i].target_name.ptr, - addr)); + char addr[PJ_INET6_ADDRSTRLEN]; + + if (query_job->srv[i].addr_cnt != 0) { + pj_sockaddr_print(&query_job->srv[i].addr[0], + addr, sizeof(addr), 2); + } else + pj_ansi_strcpy(addr, "-"); + + PJ_LOG(5,(query_job->objname, + " %d: SRV %d %d %d %.*s (%s)", + i, query_job->srv[i].priority, + query_job->srv[i].weight, + query_job->srv[i].port, + (int)query_job->srv[i].target_name.slen, + query_job->srv[i].target_name.ptr, + addr)); } } @@ -482,69 +481,69 @@ static pj_status_t resolve_hostnames(pj_dns_srv_async_query *query_job) query_job->dns_state = PJ_DNS_TYPE_A; for (i=0; isrv_cnt; ++i) { - struct srv_target *srv = &query_job->srv[i]; - - if (srv->addr_cnt != 0) { - /* - * This query is already counted as resolved because of the - * additional records in the SRV response or the target name - * is an IP address exception in build_server_entries(). - */ - continue; - } - - PJ_LOG(5, (query_job->objname, - "Starting async DNS A query_job for %.*s", - (int)srv->target_name.slen, - srv->target_name.ptr)); - - srv->common.type = PJ_DNS_TYPE_A; - srv->common_aaaa.type = PJ_DNS_TYPE_AAAA; - srv->parent = query_job; - srv->q_a = NULL; - srv->q_aaaa = NULL; - - status = PJ_SUCCESS; - - /* Start DNS A record query */ - if ((query_job->option & PJ_DNS_SRV_RESOLVE_AAAA_ONLY) == 0) - { - if ((query_job->option & PJ_DNS_SRV_RESOLVE_AAAA) != 0) { - /* If there will be DNS AAAA query too, let's setup - * a dummy one here, otherwise app callback may be called - * immediately (before DNS AAAA query is sent) when - * DNS A record is available in the cache. - */ - srv->q_aaaa = (pj_dns_async_query*)0x1; - } - status = pj_dns_resolver_start_query(query_job->resolver, - &srv->target_name, - PJ_DNS_TYPE_A, 0, - &dns_callback, - &srv->common, &srv->q_a); - } - - /* Start DNS AAAA record query */ - if (status == PJ_SUCCESS && - (query_job->option & PJ_DNS_SRV_RESOLVE_AAAA) != 0) - { - status = pj_dns_resolver_start_query(query_job->resolver, - &srv->target_name, - PJ_DNS_TYPE_AAAA, 0, - &dns_callback, - &srv->common_aaaa, &srv->q_aaaa); - } - - /* See also #1809: dns_callback() will be invoked synchronously when response - * is available in the cache, and var 'query_job->host_resolved' will get - * incremented within the dns_callback(), which will cause this function - * returning false error, so don't use that variable for counting errors. - */ - if (status != PJ_SUCCESS) { - query_job->host_resolved++; - err_cnt++; - err = status; - } + struct srv_target *srv = &query_job->srv[i]; + + if (srv->addr_cnt != 0) { + /* + * This query is already counted as resolved because of the + * additional records in the SRV response or the target name + * is an IP address exception in build_server_entries(). + */ + continue; + } + + PJ_LOG(5, (query_job->objname, + "Starting async DNS A query_job for %.*s", + (int)srv->target_name.slen, + srv->target_name.ptr)); + + srv->common.type = PJ_DNS_TYPE_A; + srv->common_aaaa.type = PJ_DNS_TYPE_AAAA; + srv->parent = query_job; + srv->q_a = NULL; + srv->q_aaaa = NULL; + + status = PJ_SUCCESS; + + /* Start DNS A record query */ + if ((query_job->option & PJ_DNS_SRV_RESOLVE_AAAA_ONLY) == 0) + { + if ((query_job->option & PJ_DNS_SRV_RESOLVE_AAAA) != 0) { + /* If there will be DNS AAAA query too, let's setup + * a dummy one here, otherwise app callback may be called + * immediately (before DNS AAAA query is sent) when + * DNS A record is available in the cache. + */ + srv->q_aaaa = (pj_dns_async_query*)0x1; + } + status = pj_dns_resolver_start_query(query_job->resolver, + &srv->target_name, + PJ_DNS_TYPE_A, 0, + &dns_callback, + &srv->common, &srv->q_a); + } + + /* Start DNS AAAA record query */ + if (status == PJ_SUCCESS && + (query_job->option & PJ_DNS_SRV_RESOLVE_AAAA) != 0) + { + status = pj_dns_resolver_start_query(query_job->resolver, + &srv->target_name, + PJ_DNS_TYPE_AAAA, 0, + &dns_callback, + &srv->common_aaaa, &srv->q_aaaa); + } + + /* See also #1809: dns_callback() will be invoked synchronously when response + * is available in the cache, and var 'query_job->host_resolved' will get + * incremented within the dns_callback(), which will cause this function + * returning false error, so don't use that variable for counting errors. + */ + if (status != PJ_SUCCESS) { + query_job->host_resolved++; + err_cnt++; + err = status; + } } return (err_cnt == query_job->srv_cnt) ? err : PJ_SUCCESS; @@ -555,8 +554,8 @@ static pj_status_t resolve_hostnames(pj_dns_srv_async_query *query_job) * query_job has completed (successfully or with error). */ static void dns_callback(void *user_data, - pj_status_t status, - pj_dns_parsed_packet *pkt) + pj_status_t status, + pj_dns_parsed_packet *pkt) { struct common *common = (struct common*) user_data; pj_dns_srv_async_query *query_job; @@ -564,286 +563,286 @@ static void dns_callback(void *user_data, unsigned i; if (common->type == PJ_DNS_TYPE_SRV) { - query_job = (pj_dns_srv_async_query*) common; - srv = NULL; + query_job = (pj_dns_srv_async_query*) common; + srv = NULL; } else if (common->type == PJ_DNS_TYPE_A) { - srv = (struct srv_target*) common; - query_job = srv->parent; + srv = (struct srv_target*) common; + query_job = srv->parent; } else if (common->type == PJ_DNS_TYPE_AAAA) { - srv = (struct srv_target*)((pj_int8_t*)common-sizeof(struct common)); - query_job = srv->parent; + srv = (struct srv_target*)((pj_int8_t*)common-sizeof(struct common)); + query_job = srv->parent; } else { - pj_assert(!"Unexpected user data!"); - return; + pj_assert(!"Unexpected user data!"); + return; } /* Proceed to next stage */ if (query_job->dns_state == PJ_DNS_TYPE_SRV) { - /* We are getting SRV response */ - - /* Clear the outstanding job */ - query_job->q_srv = NULL; - - if (status == PJ_SUCCESS) { - if (PJ_DNS_GET_TC(pkt->hdr.flags)) { - /* Got truncated answer, the standard recommends to follow up - * the query using TCP. Since we currently don't support it, - * just return error. - */ - PJ_LOG(4,(query_job->objname, - "Discard truncated DNS SRV response for %.*s", - (int)query_job->full_name.slen, - query_job->full_name.ptr)); - - status = PJ_EIGNORED; - query_job->last_error = status; - goto on_error; - } else if (pkt->hdr.anscount != 0) { - /* Got SRV response, build server entry. If A records are - * available in additional records section of the DNS response, - * save them too. - */ - build_server_entries(query_job, pkt); - } - - } else { - char errmsg[PJ_ERR_MSG_SIZE]; - - /* Update query_job last error */ - query_job->last_error = status; - - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(4,(query_job->objname, - "DNS SRV resolution failed for %.*s: %s", - (int)query_job->full_name.slen, - query_job->full_name.ptr, - errmsg)); - - /* Trigger error when fallback is disabled */ - if ((query_job->option & - (PJ_DNS_SRV_FALLBACK_A | PJ_DNS_SRV_FALLBACK_AAAA)) == 0) - { - goto on_error; - } - } - - /* If we can't build SRV record, assume the original target is - * an A record and resolve with DNS A resolution. - */ - if (query_job->srv_cnt == 0 && query_job->domain_part.slen > 0) { - unsigned new_option = 0; - - /* Looks like we aren't getting any SRV responses. - * Resolve the original target as A record by creating a - * single "dummy" srv record and start the hostname resolution. - */ - PJ_LOG(4, (query_job->objname, - "DNS SRV resolution failed for %.*s, trying " - "resolving A/AAAA record for %.*s", - (int)query_job->full_name.slen, - query_job->full_name.ptr, - (int)query_job->domain_part.slen, - query_job->domain_part.ptr)); - - /* Create a "dummy" srv record using the original target */ - i = query_job->srv_cnt++; - pj_bzero(&query_job->srv[i], sizeof(query_job->srv[i])); - query_job->srv[i].target_name = query_job->domain_part; - query_job->srv[i].priority = 0; - query_job->srv[i].weight = 0; - query_job->srv[i].port = query_job->def_port; - - /* Update query_job resolution option based on fallback option */ - if (query_job->option & PJ_DNS_SRV_FALLBACK_AAAA) - new_option |= (PJ_DNS_SRV_RESOLVE_AAAA | - PJ_DNS_SRV_RESOLVE_AAAA_ONLY); - if (query_job->option & PJ_DNS_SRV_FALLBACK_A) - new_option &= (~PJ_DNS_SRV_RESOLVE_AAAA_ONLY); - - query_job->option = new_option; - } - - - /* Resolve server hostnames (DNS A/AAAA record) for hosts which - * don't have A/AAAA record yet. - */ - if (query_job->host_resolved != query_job->srv_cnt) { - status = resolve_hostnames(query_job); - if (status != PJ_SUCCESS) - goto on_error; - - /* Must return now. Callback may have been called and query_job - * may have been destroyed. - */ - return; - } + /* We are getting SRV response */ + + /* Clear the outstanding job */ + query_job->q_srv = NULL; + + if (status == PJ_SUCCESS) { + if (PJ_DNS_GET_TC(pkt->hdr.flags)) { + /* Got truncated answer, the standard recommends to follow up + * the query using TCP. Since we currently don't support it, + * just return error. + */ + PJ_LOG(4,(query_job->objname, + "Discard truncated DNS SRV response for %.*s", + (int)query_job->full_name.slen, + query_job->full_name.ptr)); + + status = PJ_EIGNORED; + query_job->last_error = status; + goto on_error; + } else if (pkt->hdr.anscount != 0) { + /* Got SRV response, build server entry. If A records are + * available in additional records section of the DNS response, + * save them too. + */ + build_server_entries(query_job, pkt); + } + + } else { + char errmsg[PJ_ERR_MSG_SIZE]; + + /* Update query_job last error */ + query_job->last_error = status; + + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(4,(query_job->objname, + "DNS SRV resolution failed for %.*s: %s", + (int)query_job->full_name.slen, + query_job->full_name.ptr, + errmsg)); + + /* Trigger error when fallback is disabled */ + if ((query_job->option & + (PJ_DNS_SRV_FALLBACK_A | PJ_DNS_SRV_FALLBACK_AAAA)) == 0) + { + goto on_error; + } + } + + /* If we can't build SRV record, assume the original target is + * an A record and resolve with DNS A resolution. + */ + if (query_job->srv_cnt == 0 && query_job->domain_part.slen > 0) { + unsigned new_option = 0; + + /* Looks like we aren't getting any SRV responses. + * Resolve the original target as A record by creating a + * single "dummy" srv record and start the hostname resolution. + */ + PJ_LOG(4, (query_job->objname, + "DNS SRV resolution failed for %.*s, trying " + "resolving A/AAAA record for %.*s", + (int)query_job->full_name.slen, + query_job->full_name.ptr, + (int)query_job->domain_part.slen, + query_job->domain_part.ptr)); + + /* Create a "dummy" srv record using the original target */ + i = query_job->srv_cnt++; + pj_bzero(&query_job->srv[i], sizeof(query_job->srv[i])); + query_job->srv[i].target_name = query_job->domain_part; + query_job->srv[i].priority = 0; + query_job->srv[i].weight = 0; + query_job->srv[i].port = query_job->def_port; + + /* Update query_job resolution option based on fallback option */ + if (query_job->option & PJ_DNS_SRV_FALLBACK_AAAA) + new_option |= (PJ_DNS_SRV_RESOLVE_AAAA | + PJ_DNS_SRV_RESOLVE_AAAA_ONLY); + if (query_job->option & PJ_DNS_SRV_FALLBACK_A) + new_option &= (~PJ_DNS_SRV_RESOLVE_AAAA_ONLY); + + query_job->option = new_option; + } + + + /* Resolve server hostnames (DNS A/AAAA record) for hosts which + * don't have A/AAAA record yet. + */ + if (query_job->host_resolved != query_job->srv_cnt) { + status = resolve_hostnames(query_job); + if (status != PJ_SUCCESS) + goto on_error; + + /* Must return now. Callback may have been called and query_job + * may have been destroyed. + */ + return; + } } else if (query_job->dns_state == PJ_DNS_TYPE_A) { - pj_bool_t is_type_a, srv_completed; + pj_bool_t is_type_a, srv_completed; pj_dns_addr_record rec; - /* Avoid warning: potentially uninitialized local variable 'rec' */ - rec.alias.slen = 0; - rec.addr_count = 0; - - /* Clear outstanding job */ - if (common->type == PJ_DNS_TYPE_A) { - srv_completed = (srv->q_aaaa == NULL); - srv->q_a = NULL; - } else if (common->type == PJ_DNS_TYPE_AAAA) { - srv_completed = (srv->q_a == NULL); - srv->q_aaaa = NULL; - } else { - pj_assert(!"Unexpected job type"); - query_job->last_error = status = PJ_EINVALIDOP; - goto on_error; - } - - is_type_a = (common->type == PJ_DNS_TYPE_A); + /* Avoid warning: potentially uninitialized local variable 'rec' */ + rec.alias.slen = 0; + rec.addr_count = 0; + + /* Clear outstanding job */ + if (common->type == PJ_DNS_TYPE_A) { + srv_completed = (srv->q_aaaa == NULL); + srv->q_a = NULL; + } else if (common->type == PJ_DNS_TYPE_AAAA) { + srv_completed = (srv->q_a == NULL); + srv->q_aaaa = NULL; + } else { + pj_assert(!"Unexpected job type"); + query_job->last_error = status = PJ_EINVALIDOP; + goto on_error; + } + + is_type_a = (common->type == PJ_DNS_TYPE_A); /* Parse response */ if (status==PJ_SUCCESS && pkt->hdr.anscount != 0) { status = pj_dns_parse_addr_response(pkt, &rec); if (status!=PJ_SUCCESS) { PJ_PERROR(4,(query_job->objname, status, - "DNS %s record parse error for '%.*s'.", - (is_type_a ? "A" : "AAAA"), - (int)query_job->domain_part.slen, - query_job->domain_part.ptr)); - } - } - - /* Check that we really have answer */ - if (status==PJ_SUCCESS && pkt->hdr.anscount != 0) { - char addr[PJ_INET6_ADDRSTRLEN]; - - pj_assert(rec.addr_count != 0); - - /* Update CNAME alias, if present. */ - if (srv->cname.slen==0 && rec.alias.slen) { - pj_assert(rec.alias.slen <= (int)sizeof(srv->cname_buf)); - srv->cname.ptr = srv->cname_buf; - pj_strcpy(&srv->cname, &rec.alias); - //} else { - //srv->cname.slen = 0; - } - - /* Update IP address of the corresponding hostname or CNAME */ - for (i=0; iaddr_cntaddr[srv->addr_cnt], - NULL, srv->port); - srv->addr[srv->addr_cnt].ipv4.sin_addr = - rec.addr[i].ip.v4; - added = PJ_TRUE; - } else if (!is_type_a && rec.addr[i].af == pj_AF_INET6()) { - pj_sockaddr_init(pj_AF_INET6(), &srv->addr[srv->addr_cnt], - NULL, srv->port); - srv->addr[srv->addr_cnt].ipv6.sin6_addr = - rec.addr[i].ip.v6; - added = PJ_TRUE; - } else { - /* Mismatched address family, e.g: getting IPv6 address in - * DNS A query resolution. - */ - PJ_LOG(4,(query_job->objname, - "Bad address family in DNS %s query for %.*s", - (is_type_a? "A" : "AAAA"), - (int)srv->target_name.slen, - srv->target_name.ptr)); - } - - if (added) { - PJ_LOG(5,(query_job->objname, - "DNS %s for %.*s: %s", - (is_type_a? "A" : "AAAA"), - (int)srv->target_name.slen, - srv->target_name.ptr, - pj_sockaddr_print(&srv->addr[srv->addr_cnt], - addr, sizeof(addr), 2))); - - ++srv->addr_cnt; - } - } - - } else if (status != PJ_SUCCESS) { - /* Update last error */ - query_job->last_error = status; - - /* Log error */ - PJ_PERROR(4,(query_job->objname, status, - "DNS %s record resolution failed", - (is_type_a? "A" : "AAAA"))); - } - - /* Increment host resolved count when both DNS A and AAAA record - * queries for this server are completed. - */ - if (srv_completed) - ++query_job->host_resolved; + "DNS %s record parse error for '%.*s'.", + (is_type_a ? "A" : "AAAA"), + (int)query_job->domain_part.slen, + query_job->domain_part.ptr)); + } + } + + /* Check that we really have answer */ + if (status==PJ_SUCCESS && pkt->hdr.anscount != 0) { + char addr[PJ_INET6_ADDRSTRLEN]; + + pj_assert(rec.addr_count != 0); + + /* Update CNAME alias, if present. */ + if (srv->cname.slen==0 && rec.alias.slen) { + pj_assert(rec.alias.slen <= (int)sizeof(srv->cname_buf)); + srv->cname.ptr = srv->cname_buf; + pj_strcpy(&srv->cname, &rec.alias); + //} else { + //srv->cname.slen = 0; + } + + /* Update IP address of the corresponding hostname or CNAME */ + for (i=0; iaddr_cntaddr[srv->addr_cnt], + NULL, srv->port); + srv->addr[srv->addr_cnt].ipv4.sin_addr = + rec.addr[i].ip.v4; + added = PJ_TRUE; + } else if (!is_type_a && rec.addr[i].af == pj_AF_INET6()) { + pj_sockaddr_init(pj_AF_INET6(), &srv->addr[srv->addr_cnt], + NULL, srv->port); + srv->addr[srv->addr_cnt].ipv6.sin6_addr = + rec.addr[i].ip.v6; + added = PJ_TRUE; + } else { + /* Mismatched address family, e.g: getting IPv6 address in + * DNS A query resolution. + */ + PJ_LOG(4,(query_job->objname, + "Bad address family in DNS %s query for %.*s", + (is_type_a? "A" : "AAAA"), + (int)srv->target_name.slen, + srv->target_name.ptr)); + } + + if (added) { + PJ_LOG(5,(query_job->objname, + "DNS %s for %.*s: %s", + (is_type_a? "A" : "AAAA"), + (int)srv->target_name.slen, + srv->target_name.ptr, + pj_sockaddr_print(&srv->addr[srv->addr_cnt], + addr, sizeof(addr), 2))); + + ++srv->addr_cnt; + } + } + + } else if (status != PJ_SUCCESS) { + /* Update last error */ + query_job->last_error = status; + + /* Log error */ + PJ_PERROR(4,(query_job->objname, status, + "DNS %s record resolution failed", + (is_type_a? "A" : "AAAA"))); + } + + /* Increment host resolved count when both DNS A and AAAA record + * queries for this server are completed. + */ + if (srv_completed) + ++query_job->host_resolved; } else { - pj_assert(!"Unexpected state!"); - query_job->last_error = status = PJ_EINVALIDOP; - goto on_error; + pj_assert(!"Unexpected state!"); + query_job->last_error = status = PJ_EINVALIDOP; + goto on_error; } /* Check if all hosts have been resolved */ if (query_job->host_resolved == query_job->srv_cnt) { - /* Got all answers, build server addresses */ - pj_dns_srv_record srv_rec; - - srv_rec.count = 0; - for (i=0; isrv_cnt; ++i) { - unsigned j; - struct srv_target *srv2 = &query_job->srv[i]; - pj_dns_addr_record *s = &srv_rec.entry[srv_rec.count].server; - - srv_rec.entry[srv_rec.count].priority = srv2->priority; - srv_rec.entry[srv_rec.count].weight = srv2->weight; - srv_rec.entry[srv_rec.count].port = (pj_uint16_t)srv2->port ; - - srv_rec.entry[srv_rec.count].server.name = srv2->target_name; - srv_rec.entry[srv_rec.count].server.alias = srv2->cname; - srv_rec.entry[srv_rec.count].server.addr_count = 0; - - pj_assert(srv2->addr_cnt <= PJ_DNS_MAX_IP_IN_A_REC); - - for (j=0; jaddr_cnt; ++j) { - s->addr[j].af = srv2->addr[j].addr.sa_family; - if (s->addr[j].af == pj_AF_INET()) - s->addr[j].ip.v4 = srv2->addr[j].ipv4.sin_addr; - else - s->addr[j].ip.v6 = srv2->addr[j].ipv6.sin6_addr; - ++s->addr_count; - } - - if (srv2->addr_cnt > 0) { - ++srv_rec.count; - if (srv_rec.count == PJ_DNS_SRV_MAX_ADDR) - break; - } - } - - PJ_LOG(5,(query_job->objname, - "Server resolution complete, %d server entry(s) found", - srv_rec.count)); - - - if (srv_rec.count > 0) - status = PJ_SUCCESS; - else { - status = query_job->last_error; - if (status == PJ_SUCCESS) - status = PJLIB_UTIL_EDNSNOANSWERREC; - } - - /* Call the callback */ - (*query_job->cb)(query_job->token, status, &srv_rec); + /* Got all answers, build server addresses */ + pj_dns_srv_record srv_rec; + + srv_rec.count = 0; + for (i=0; isrv_cnt; ++i) { + unsigned j; + struct srv_target *srv2 = &query_job->srv[i]; + pj_dns_addr_record *s = &srv_rec.entry[srv_rec.count].server; + + srv_rec.entry[srv_rec.count].priority = srv2->priority; + srv_rec.entry[srv_rec.count].weight = srv2->weight; + srv_rec.entry[srv_rec.count].port = (pj_uint16_t)srv2->port ; + + srv_rec.entry[srv_rec.count].server.name = srv2->target_name; + srv_rec.entry[srv_rec.count].server.alias = srv2->cname; + srv_rec.entry[srv_rec.count].server.addr_count = 0; + + pj_assert(srv2->addr_cnt <= PJ_DNS_MAX_IP_IN_A_REC); + + for (j=0; jaddr_cnt; ++j) { + s->addr[j].af = srv2->addr[j].addr.sa_family; + if (s->addr[j].af == pj_AF_INET()) + s->addr[j].ip.v4 = srv2->addr[j].ipv4.sin_addr; + else + s->addr[j].ip.v6 = srv2->addr[j].ipv6.sin6_addr; + ++s->addr_count; + } + + if (srv2->addr_cnt > 0) { + ++srv_rec.count; + if (srv_rec.count == PJ_DNS_SRV_MAX_ADDR) + break; + } + } + + PJ_LOG(5,(query_job->objname, + "Server resolution complete, %d server entry(s) found", + srv_rec.count)); + + + if (srv_rec.count > 0) + status = PJ_SUCCESS; + else { + status = query_job->last_error; + if (status == PJ_SUCCESS) + status = PJLIB_UTIL_EDNSNOANSWERREC; + } + + /* Call the callback */ + (*query_job->cb)(query_job->token, status, &srv_rec); } @@ -852,17 +851,17 @@ static void dns_callback(void *user_data, on_error: /* Check for failure */ if (status != PJ_SUCCESS) { - PJ_PERROR(4,(query_job->objname, status, - "DNS %s record resolution error for '%.*s'.", - pj_dns_get_type_name(query_job->dns_state), - (int)query_job->domain_part.slen, - query_job->domain_part.ptr)); + PJ_PERROR(4,(query_job->objname, status, + "DNS %s record resolution error for '%.*s'.", + pj_dns_get_type_name(query_job->dns_state), + (int)query_job->domain_part.slen, + query_job->domain_part.ptr)); - /* Cancel any pending query */ - pj_dns_srv_cancel_query(query_job, PJ_FALSE); + /* Cancel any pending query */ + pj_dns_srv_cancel_query(query_job, PJ_FALSE); - (*query_job->cb)(query_job->token, status, NULL); - return; + (*query_job->cb)(query_job->token, status, NULL); + return; } } diff --git a/pjlib-util/src/pjlib-util/string.c b/pjlib-util/src/pjlib-util/string.c index 4958278ff0..6b33b3c43f 100644 --- a/pjlib-util/src/pjlib-util/string.c +++ b/pjlib-util/src/pjlib-util/string.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,49 +29,49 @@ PJ_DEF(pj_str_t) pj_str_unescape( pj_pool_t *pool, const pj_str_t *src_str) char *dst; if (pj_strchr(src_str, '%')==NULL) - return *src_str; + return *src_str; dst = dst_str.ptr = (char*) pj_pool_alloc(pool, src_str->slen); while (src != end) { - if (*src == '%' && src < end-2 && pj_isxdigit(*(src+1)) && - pj_isxdigit(*(src+2))) - { - *dst = (pj_uint8_t) ((pj_hex_digit_to_val(*(src+1)) << 4) + - pj_hex_digit_to_val(*(src+2))); - ++dst; - src += 3; - } else { - *dst++ = *src++; - } + if (*src == '%' && src < end-2 && pj_isxdigit(*(src+1)) && + pj_isxdigit(*(src+2))) + { + *dst = (pj_uint8_t) ((pj_hex_digit_to_val(*(src+1)) << 4) + + pj_hex_digit_to_val(*(src+2))); + ++dst; + src += 3; + } else { + *dst++ = *src++; + } } dst_str.slen = dst - dst_str.ptr; return dst_str; } PJ_DEF(pj_str_t*) pj_strcpy_unescape(pj_str_t *dst_str, - const pj_str_t *src_str) + const pj_str_t *src_str) { const char *src = src_str->ptr; const char *end = src + src_str->slen; char *dst = dst_str->ptr; while (src != end) { - if (*src == '%' && src < end-2) { - *dst = (pj_uint8_t) ((pj_hex_digit_to_val(*(src+1)) << 4) + - pj_hex_digit_to_val(*(src+2))); - ++dst; - src += 3; - } else { - *dst++ = *src++; - } + if (*src == '%' && src < end-2) { + *dst = (pj_uint8_t) ((pj_hex_digit_to_val(*(src+1)) << 4) + + pj_hex_digit_to_val(*(src+2))); + ++dst; + src += 3; + } else { + *dst++ = *src++; + } } dst_str->slen = dst - dst_str->ptr; return dst_str; } PJ_DEF(pj_ssize_t) pj_strncpy2_escape( char *dst_str, const pj_str_t *src_str, - pj_ssize_t max, const pj_cis_t *unres) + pj_ssize_t max, const pj_cis_t *unres) { const char *src = src_str->ptr; const char *src_end = src + src_str->slen; @@ -80,29 +79,29 @@ PJ_DEF(pj_ssize_t) pj_strncpy2_escape( char *dst_str, const pj_str_t *src_str, char *dst_end = dst + max; if (max < src_str->slen) - return -1; + return -1; while (src != src_end && dst != dst_end) { - if (pj_cis_match(unres, *src)) { - *dst++ = *src++; - } else { - if (dst < dst_end-2) { - *dst++ = '%'; - pj_val_to_hex_digit(*src, dst); - dst+=2; - ++src; - } else { - break; - } - } + if (pj_cis_match(unres, *src)) { + *dst++ = *src++; + } else { + if (dst < dst_end-2) { + *dst++ = '%'; + pj_val_to_hex_digit(*src, dst); + dst+=2; + ++src; + } else { + break; + } + } } return src==src_end ? dst-dst_str : -1; } PJ_DEF(pj_str_t*) pj_strncpy_escape(pj_str_t *dst_str, - const pj_str_t *src_str, - pj_ssize_t max, const pj_cis_t *unres) + const pj_str_t *src_str, + pj_ssize_t max, const pj_cis_t *unres) { dst_str->slen = pj_strncpy2_escape(dst_str->ptr, src_str, max, unres); return dst_str->slen < 0 ? NULL : dst_str; diff --git a/pjlib-util/src/pjlib-util/stun_simple.c b/pjlib-util/src/pjlib-util/stun_simple.c index d0549176dd..aff052026b 100644 --- a/pjlib-util/src/pjlib-util/stun_simple.c +++ b/pjlib-util/src/pjlib-util/stun_simple.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,9 +26,9 @@ #define THIS_FILE "stun_simple.c" PJ_DEF(pj_status_t) pjstun_create_bind_req( pj_pool_t *pool, - void **msg, pj_size_t *len, - pj_uint32_t id_hi, - pj_uint32_t id_lo) + void **msg, pj_size_t *len, + pj_uint32_t id_hi, + pj_uint32_t id_lo) { pjstun_msg_hdr *hdr; @@ -38,7 +37,7 @@ PJ_DEF(pj_status_t) pjstun_create_bind_req( pj_pool_t *pool, hdr = PJ_POOL_ZALLOC_T(pool, pjstun_msg_hdr); if (!hdr) - return PJ_ENOMEM; + return PJ_ENOMEM; hdr->type = pj_htons(PJSTUN_BINDING_REQUEST); hdr->tsx[2] = pj_htonl(id_hi); @@ -50,7 +49,7 @@ PJ_DEF(pj_status_t) pjstun_create_bind_req( pj_pool_t *pool, } PJ_DEF(pj_status_t) pjstun_parse_msg( void *buf, pj_size_t buf_len, - pjstun_msg *msg) + pjstun_msg *msg) { pj_uint16_t msg_type, msg_len; char *p_attr; @@ -68,53 +67,53 @@ PJ_DEF(pj_status_t) pjstun_parse_msg( void *buf, pj_size_t buf_len, case PJSTUN_SHARED_SECRET_REQUEST: case PJSTUN_SHARED_SECRET_RESPONSE: case PJSTUN_SHARED_SECRET_ERROR_RESPONSE: - break; + break; default: - PJ_LOG(4,(THIS_FILE, "Error: unknown msg type %d", msg_type)); - return PJLIB_UTIL_ESTUNINMSGTYPE; + PJ_LOG(4,(THIS_FILE, "Error: unknown msg type %d", msg_type)); + return PJLIB_UTIL_ESTUNINMSGTYPE; } msg_len = pj_ntohs(msg->hdr->length); if (msg_len != buf_len - sizeof(pjstun_msg_hdr)) { - PJ_LOG(4,(THIS_FILE, "Error: invalid msg_len %d (expecting %d)", - msg_len, buf_len - sizeof(pjstun_msg_hdr))); - return PJLIB_UTIL_ESTUNINMSGLEN; + PJ_LOG(4,(THIS_FILE, "Error: invalid msg_len %d (expecting %d)", + msg_len, buf_len - sizeof(pjstun_msg_hdr))); + return PJLIB_UTIL_ESTUNINMSGLEN; } msg->attr_count = 0; p_attr = (char*)buf + sizeof(pjstun_msg_hdr); while (msg_len > 0 && msg->attr_count < attr_max_cnt) { - pjstun_attr_hdr **attr = &msg->attr[msg->attr_count]; - pj_uint32_t len; - pj_uint16_t attr_type; - - *attr = (pjstun_attr_hdr*)p_attr; - len = pj_ntohs((pj_uint16_t) ((*attr)->length)) + sizeof(pjstun_attr_hdr); - len = (len + 3) & ~3; - - if (msg_len < len) { - PJ_LOG(4,(THIS_FILE, "Error: length mismatch in attr %d", - msg->attr_count)); - return PJLIB_UTIL_ESTUNINATTRLEN; - } - - attr_type = pj_ntohs((*attr)->type); - if (attr_type > PJSTUN_ATTR_REFLECTED_FROM && - attr_type != PJSTUN_ATTR_XOR_MAPPED_ADDR) - { - PJ_LOG(5,(THIS_FILE, "Warning: unknown attr type %x in attr %d. " - "Attribute was ignored.", - attr_type, msg->attr_count)); - } - - msg_len = (pj_uint16_t)(msg_len - len); - p_attr += len; - ++msg->attr_count; + pjstun_attr_hdr **attr = &msg->attr[msg->attr_count]; + pj_uint32_t len; + pj_uint16_t attr_type; + + *attr = (pjstun_attr_hdr*)p_attr; + len = pj_ntohs((pj_uint16_t) ((*attr)->length)) + sizeof(pjstun_attr_hdr); + len = (len + 3) & ~3; + + if (msg_len < len) { + PJ_LOG(4,(THIS_FILE, "Error: length mismatch in attr %d", + msg->attr_count)); + return PJLIB_UTIL_ESTUNINATTRLEN; + } + + attr_type = pj_ntohs((*attr)->type); + if (attr_type > PJSTUN_ATTR_REFLECTED_FROM && + attr_type != PJSTUN_ATTR_XOR_MAPPED_ADDR) + { + PJ_LOG(5,(THIS_FILE, "Warning: unknown attr type %x in attr %d. " + "Attribute was ignored.", + attr_type, msg->attr_count)); + } + + msg_len = (pj_uint16_t)(msg_len - len); + p_attr += len; + ++msg->attr_count; } if (msg->attr_count == attr_max_cnt) { - PJ_LOG(4, (THIS_FILE, "Warning: max number attribute %d reached.", - attr_max_cnt)); + PJ_LOG(4, (THIS_FILE, "Warning: max number attribute %d reached.", + attr_max_cnt)); } return PJ_SUCCESS; @@ -127,9 +126,9 @@ PJ_DEF(void*) pjstun_msg_find_attr( pjstun_msg *msg, pjstun_attr_type t) PJ_CHECK_STACK(); for (i=0; iattr_count; ++i) { - pjstun_attr_hdr *attr = msg->attr[i]; - if (pj_ntohs(attr->type) == t) - return attr; + pjstun_attr_hdr *attr = msg->attr[i]; + if (pj_ntohs(attr->type) == t) + return attr; } return 0; diff --git a/pjlib-util/src/pjlib-util/stun_simple_client.c b/pjlib-util/src/pjlib-util/stun_simple_client.c index 04dec72182..3d3f2eda36 100644 --- a/pjlib-util/src/pjlib-util/stun_simple_client.c +++ b/pjlib-util/src/pjlib-util/stun_simple_client.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,15 +31,15 @@ enum { MAX_REQUEST = 4 }; static int stun_timer[] = {500, 500, 500, 500 }; #define STUN_MAGIC 0x2112A442 -#define THIS_FILE "stun_client.c" +#define THIS_FILE "stun_client.c" -#define TRACE_(x) PJ_LOG(6,x) +#define TRACE_(x) PJ_LOG(6,x) PJ_DEF(pj_status_t) pjstun_get_mapped_addr( pj_pool_factory *pf, - int sock_cnt, pj_sock_t sock[], - const pj_str_t *srv1, int port1, - const pj_str_t *srv2, int port2, - pj_sockaddr_in mapped_addr[]) + int sock_cnt, pj_sock_t sock[], + const pj_str_t *srv1, int port1, + const pj_str_t *srv2, int port2, + pj_sockaddr_in mapped_addr[]) { pjstun_setting opt; @@ -55,10 +54,10 @@ PJ_DEF(pj_status_t) pjstun_get_mapped_addr( pj_pool_factory *pf, } PJ_DEF(pj_status_t) pjstun_get_mapped_addr2(pj_pool_factory *pf, - const pjstun_setting *opt, - int sock_cnt, - pj_sock_t sock[], - pj_sockaddr_in mapped_addr[]) + const pjstun_setting *opt, + int sock_cnt, + pj_sock_t sock[], + pj_sockaddr_in mapped_addr[]) { unsigned srv_cnt; const pj_str_t *srv1, *srv2; @@ -67,13 +66,13 @@ PJ_DEF(pj_status_t) pjstun_get_mapped_addr2(pj_pool_factory *pf, int i, send_cnt = 0, nfds; pj_pool_t *pool; struct query_rec { - struct { - pj_uint32_t mapped_addr; - pj_uint32_t mapped_port; - } srv[2]; + struct { + pj_uint32_t mapped_addr; + pj_uint32_t mapped_port; + } srv[2]; } *rec; void *out_msg; - pj_size_t out_msg_len; + pj_size_t out_msg_len; int wait_resp = 0; pj_status_t status; @@ -89,28 +88,28 @@ PJ_DEF(pj_status_t) pjstun_get_mapped_addr2(pj_pool_factory *pf, /* Create pool. */ pool = pj_pool_create(pf, "stun%p", 400, 400, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Allocate client records */ rec = (struct query_rec*) pj_pool_calloc(pool, sock_cnt, sizeof(*rec)); if (!rec) { - status = PJ_ENOMEM; - goto on_error; + status = PJ_ENOMEM; + goto on_error; } TRACE_((THIS_FILE, " Memory allocated.")); /* Create the outgoing BIND REQUEST message template */ status = pjstun_create_bind_req( pool, &out_msg, &out_msg_len, - pj_rand(), pj_rand()); + pj_rand(), pj_rand()); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Insert magic cookie (specified in RFC 5389) when requested to. */ if (opt->use_stun2) { - pjstun_msg_hdr *hdr = (pjstun_msg_hdr*)out_msg; - hdr->tsx[0] = pj_htonl(STUN_MAGIC); + pjstun_msg_hdr *hdr = (pjstun_msg_hdr*)out_msg; + hdr->tsx[0] = pj_htonl(STUN_MAGIC); } TRACE_((THIS_FILE, " Binding request created.")); @@ -118,19 +117,19 @@ PJ_DEF(pj_status_t) pjstun_get_mapped_addr2(pj_pool_factory *pf, /* Resolve servers. */ status = pj_sockaddr_init(opt->af, &srv_addr[0], srv1, (pj_uint16_t)port1); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; srv_cnt = 1; if (srv2 && port2) { - status = pj_sockaddr_init(opt->af, &srv_addr[1], srv2, - (pj_uint16_t)port2); - if (status != PJ_SUCCESS) - goto on_error; - - if (pj_sockaddr_cmp(&srv_addr[1], &srv_addr[0]) != 0) { - srv_cnt++; - } + status = pj_sockaddr_init(opt->af, &srv_addr[1], srv2, + (pj_uint16_t)port2); + if (status != PJ_SUCCESS) + goto on_error; + + if (pj_sockaddr_cmp(&srv_addr[1], &srv_addr[0]) != 0) { + srv_cnt++; + } } TRACE_((THIS_FILE, " Server initialized, using %d server(s)", srv_cnt)); @@ -146,9 +145,9 @@ PJ_DEF(pj_status_t) pjstun_get_mapped_addr2(pj_pool_factory *pf, #if defined(PJ_SELECT_NEEDS_NFDS) && PJ_SELECT_NEEDS_NFDS!=0 nfds = -1; for (i=0; i nfds) { - nfds = sock[i]; - } + if (sock[i] > nfds) { + nfds = sock[i]; + } } #else nfds = FD_SETSIZE-1; @@ -156,198 +155,198 @@ PJ_DEF(pj_status_t) pjstun_get_mapped_addr2(pj_pool_factory *pf, /* Main retransmission loop. */ for (send_cnt=0; send_cnttsx[2] = pj_htonl(i); - msg_hdr->tsx[3] = pj_htonl(j); + /* Modify message so that we can distinguish response. */ + msg_hdr->tsx[2] = pj_htonl(i); + msg_hdr->tsx[3] = pj_htonl(j); - /* Send! */ + /* Send! */ sent_len = out_msg_len; - status = pj_sock_sendto(sock[i], out_msg, &sent_len, 0, - (pj_sockaddr_t*)&srv_addr[j], - pj_sockaddr_get_len(&srv_addr[j])); - } - } - - /* All requests sent. - * The loop below will wait for responses until all responses have - * been received (i.e. wait_resp==0) or timeout occurs, which then - * we'll go to the next retransmission iteration. - */ - TRACE_((THIS_FILE, " Request(s) sent, counter=%d", send_cnt)); - - /* Calculate time of next retransmission. */ - pj_gettickcount(&next_tx); - next_tx.sec += (stun_timer[send_cnt]/1000); - next_tx.msec += (stun_timer[send_cnt]%1000); - pj_time_val_normalize(&next_tx); - - for (pj_gettickcount(&now), select_rc=1; - status==PJ_SUCCESS && select_rc>=1 && wait_resp>0 - && PJ_TIME_VAL_LT(now, next_tx); - pj_gettickcount(&now)) - { - pj_time_val timeout; - - timeout = next_tx; - PJ_TIME_VAL_SUB(timeout, now); - - for (i=0; i=1 && wait_resp>0 + && PJ_TIME_VAL_LT(now, next_tx); + pj_gettickcount(&now)) + { + pj_time_val timeout; + + timeout = next_tx; + PJ_TIME_VAL_SUB(timeout, now); + + for (i=0; itsx[2]); - srv_idx = pj_ntohl(msg.hdr->tsx[3]); - - if (sock_idx<0 || sock_idx>=sock_cnt || sock_idx!=i || - srv_idx<0 || srv_idx>=2) - { - status = PJLIB_UTIL_ESTUNININDEX; - continue; - } - - if (pj_ntohs(msg.hdr->type) != PJSTUN_BINDING_RESPONSE) { - status = PJLIB_UTIL_ESTUNNOBINDRES; - continue; - } - - if (rec[sock_idx].srv[srv_idx].mapped_port != 0) { - /* Already got response */ - continue; - } - - /* From this part, we consider the packet as a valid STUN - * response for our request. - */ - --wait_resp; - - if (pjstun_msg_find_attr(&msg, PJSTUN_ATTR_ERROR_CODE) != NULL) { - status = PJLIB_UTIL_ESTUNRECVERRATTR; - continue; - } - - attr = (pjstun_mapped_addr_attr*) - pjstun_msg_find_attr(&msg, PJSTUN_ATTR_MAPPED_ADDR); - if (!attr) { - attr = (pjstun_mapped_addr_attr*) - pjstun_msg_find_attr(&msg, PJSTUN_ATTR_XOR_MAPPED_ADDR); - if (!attr || attr->family != 1) { - status = PJLIB_UTIL_ESTUNNOMAP; - continue; - } - } - - rec[sock_idx].srv[srv_idx].mapped_addr = attr->addr; - rec[sock_idx].srv[srv_idx].mapped_port = attr->port; - if (pj_ntohs(attr->hdr.type) == PJSTUN_ATTR_XOR_MAPPED_ADDR) { - rec[sock_idx].srv[srv_idx].mapped_addr ^= pj_htonl(STUN_MAGIC); - rec[sock_idx].srv[srv_idx].mapped_port ^= pj_htons(STUN_MAGIC >> 16); - } - } - } - - /* The best scenario is if all requests have been replied. - * Then we don't need to go to the next retransmission iteration. - */ - if (wait_resp <= 0) - break; + status = pj_sock_recvfrom( sock[i], recv_buf, + &len, 0, + (pj_sockaddr_t*)&addr, + &addrlen); + + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, + "recvfrom() error ignored")); + + /* Ignore non-PJ_SUCCESS status. + * It possible that other SIP entity is currently + * sending SIP request to us, and because SIP message + * is larger than STUN, we could get EMSGSIZE when + * we call recvfrom(). + */ + status = PJ_SUCCESS; + continue; + } + + status = pjstun_parse_msg(recv_buf, len, &msg); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, + "STUN parsing error ignored")); + + /* Also ignore non-successful parsing. This may not + * be STUN response at all. See the comment above. + */ + status = PJ_SUCCESS; + continue; + } + + sock_idx = pj_ntohl(msg.hdr->tsx[2]); + srv_idx = pj_ntohl(msg.hdr->tsx[3]); + + if (sock_idx<0 || sock_idx>=sock_cnt || sock_idx!=i || + srv_idx<0 || srv_idx>=2) + { + status = PJLIB_UTIL_ESTUNININDEX; + continue; + } + + if (pj_ntohs(msg.hdr->type) != PJSTUN_BINDING_RESPONSE) { + status = PJLIB_UTIL_ESTUNNOBINDRES; + continue; + } + + if (rec[sock_idx].srv[srv_idx].mapped_port != 0) { + /* Already got response */ + continue; + } + + /* From this part, we consider the packet as a valid STUN + * response for our request. + */ + --wait_resp; + + if (pjstun_msg_find_attr(&msg, PJSTUN_ATTR_ERROR_CODE) != NULL) { + status = PJLIB_UTIL_ESTUNRECVERRATTR; + continue; + } + + attr = (pjstun_mapped_addr_attr*) + pjstun_msg_find_attr(&msg, PJSTUN_ATTR_MAPPED_ADDR); + if (!attr) { + attr = (pjstun_mapped_addr_attr*) + pjstun_msg_find_attr(&msg, PJSTUN_ATTR_XOR_MAPPED_ADDR); + if (!attr || attr->family != 1) { + status = PJLIB_UTIL_ESTUNNOMAP; + continue; + } + } + + rec[sock_idx].srv[srv_idx].mapped_addr = attr->addr; + rec[sock_idx].srv[srv_idx].mapped_port = attr->port; + if (pj_ntohs(attr->hdr.type) == PJSTUN_ATTR_XOR_MAPPED_ADDR) { + rec[sock_idx].srv[srv_idx].mapped_addr ^= pj_htonl(STUN_MAGIC); + rec[sock_idx].srv[srv_idx].mapped_port ^= pj_htons(STUN_MAGIC >> 16); + } + } + } + + /* The best scenario is if all requests have been replied. + * Then we don't need to go to the next retransmission iteration. + */ + if (wait_resp <= 0) + break; } TRACE_((THIS_FILE, " All responses received, calculating result..")); for (i=0; i diff --git a/pjlib-util/src/pjlib-util/xml.c b/pjlib-util/src/pjlib-util/xml.c index 5c2d8eb174..16b0a62c11 100644 --- a/pjlib-util/src/pjlib-util/xml.c +++ b/pjlib-util/src/pjlib-util/xml.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,8 +24,8 @@ #include #include -#define EX_SYNTAX_ERROR 12 -#define THIS_FILE "xml.c" +#define EX_SYNTAX_ERROR 12 +#define THIS_FILE "xml.c" static void on_syntax_error(struct pj_scanner *scanner) { @@ -59,38 +58,38 @@ static pj_xml_node *xml_parse_node( pj_pool_t *pool, pj_scanner *scanner) PJ_CHECK_STACK(); if (*scanner->curptr != '<') - on_syntax_error(scanner); + on_syntax_error(scanner); /* Handle Processing Instructino (PI) construct (i.e. "curptr == '<' && *(scanner->curptr+1) == '?') { - pj_scan_advance_n(scanner, 2, PJ_FALSE); - for (;;) { - pj_str_t dummy; - pj_scan_get_until_ch(scanner, '?', &dummy); - if (*scanner->curptr=='?' && *(scanner->curptr+1)=='>') { - pj_scan_advance_n(scanner, 2, PJ_TRUE); - break; - } else { - pj_scan_advance_n(scanner, 1, PJ_FALSE); - } - } - return xml_parse_node(pool, scanner); + pj_scan_advance_n(scanner, 2, PJ_FALSE); + for (;;) { + pj_str_t dummy; + pj_scan_get_until_ch(scanner, '?', &dummy); + if (*scanner->curptr=='?' && *(scanner->curptr+1)=='>') { + pj_scan_advance_n(scanner, 2, PJ_TRUE); + break; + } else { + pj_scan_advance_n(scanner, 1, PJ_FALSE); + } + } + return xml_parse_node(pool, scanner); } /* Handle comments construct (i.e. "', &dummy); - if (pj_scan_strcmp(scanner, ">", 1) == 0) { - pj_scan_advance_n(scanner, 1, PJ_TRUE); - break; - } else { - pj_scan_advance_n(scanner, 1, PJ_FALSE); - } - } - return xml_parse_node(pool, scanner); + pj_scan_advance_n(scanner, 2, PJ_FALSE); + for (;;) { + pj_str_t dummy; + pj_scan_get_until_ch(scanner, '>', &dummy); + if (pj_scan_strcmp(scanner, ">", 1) == 0) { + pj_scan_advance_n(scanner, 1, PJ_TRUE); + break; + } else { + pj_scan_advance_n(scanner, 1, PJ_FALSE); + } + } + return xml_parse_node(pool, scanner); } /* Alloc node. */ @@ -104,73 +103,73 @@ static pj_xml_node *xml_parse_node( pj_pool_t *pool, pj_scanner *scanner) /* Get attributes. */ while (*scanner->curptr != '>' && *scanner->curptr != '/') { - pj_xml_attr *attr = alloc_attr(pool); - - pj_scan_get_until_chr( scanner, "=> \t\r\n", &attr->name); - if (*scanner->curptr == '=') { - pj_scan_get_char( scanner ); + pj_xml_attr *attr = alloc_attr(pool); + + pj_scan_get_until_chr( scanner, "=> \t\r\n", &attr->name); + if (*scanner->curptr == '=') { + pj_scan_get_char( scanner ); pj_scan_get_quotes(scanner, "\"'", "\"'", 2, &attr->value); - /* remove quote characters */ - ++attr->value.ptr; - attr->value.slen -= 2; - } - - pj_list_push_back( &node->attr_head, attr ); + /* remove quote characters */ + ++attr->value.ptr; + attr->value.slen -= 2; + } + + pj_list_push_back( &node->attr_head, attr ); } if (*scanner->curptr == '/') { - pj_scan_get_char(scanner); - if (pj_scan_get_char(scanner) != '>') - on_syntax_error(scanner); - return node; + pj_scan_get_char(scanner); + if (pj_scan_get_char(scanner) != '>') + on_syntax_error(scanner); + return node; } /* Enclosing bracket. */ if (pj_scan_get_char(scanner) != '>') - on_syntax_error(scanner); + on_syntax_error(scanner); /* Sub nodes. */ while (*scanner->curptr == '<' && *(scanner->curptr+1) != '/' - && *(scanner->curptr+1) != '!') + && *(scanner->curptr+1) != '!') { - pj_xml_node *sub_node = xml_parse_node(pool, scanner); - pj_list_push_back( &node->node_head, sub_node ); + pj_xml_node *sub_node = xml_parse_node(pool, scanner); + pj_list_push_back( &node->node_head, sub_node ); } /* Content. */ if (!pj_scan_is_eof(scanner) && *scanner->curptr != '<') { - pj_scan_get_until_ch(scanner, '<', &node->content); + pj_scan_get_until_ch(scanner, '<', &node->content); } /* CDATA content. */ if (*scanner->curptr == '<' && *(scanner->curptr+1) == '!' && - pj_scan_strcmp(scanner, "content); - while (pj_scan_strcmp(scanner, "]]>", 3)) { - pj_str_t dummy; - - pj_scan_advance_n(scanner, 1, PJ_FALSE); - pj_scan_get_until_ch(scanner, ']', &dummy); - } - node->content.slen = scanner->curptr - node->content.ptr; - pj_scan_advance_n(scanner, 3, PJ_TRUE); + pj_scan_advance_n(scanner, 9, PJ_FALSE); + pj_scan_get_until_ch(scanner, ']', &node->content); + while (pj_scan_strcmp(scanner, "]]>", 3)) { + pj_str_t dummy; + + pj_scan_advance_n(scanner, 1, PJ_FALSE); + pj_scan_get_until_ch(scanner, ']', &dummy); + } + node->content.slen = scanner->curptr - node->content.ptr; + pj_scan_advance_n(scanner, 3, PJ_TRUE); } /* Enclosing node. */ if (pj_scan_get_char(scanner) != '<' || pj_scan_get_char(scanner) != '/') - on_syntax_error(scanner); + on_syntax_error(scanner); pj_scan_get_until_chr(scanner, " \t>", &end_name); /* Compare name. */ if (pj_stricmp(&node->name, &end_name) != 0) - on_syntax_error(scanner); + on_syntax_error(scanner); /* Enclosing '>' */ if (pj_scan_get_char(scanner) != '>') - on_syntax_error(scanner); + on_syntax_error(scanner); return node; } @@ -182,17 +181,17 @@ PJ_DEF(pj_xml_node*) pj_xml_parse( pj_pool_t *pool, char *msg, pj_size_t len) PJ_USE_EXCEPTION; if (!msg || !len || !pool) - return NULL; + return NULL; pj_scan_init( &scanner, msg, len, - PJ_SCAN_AUTOSKIP_WS|PJ_SCAN_AUTOSKIP_NEWLINE, - &on_syntax_error); + PJ_SCAN_AUTOSKIP_WS|PJ_SCAN_AUTOSKIP_NEWLINE, + &on_syntax_error); PJ_TRY { - node = xml_parse_node(pool, &scanner); + node = xml_parse_node(pool, &scanner); } PJ_CATCH_ANY { - PJ_LOG(4,(THIS_FILE, "Syntax error parsing XML in line %d column %d", - scanner.line, pj_scan_get_col(&scanner))); + PJ_LOG(4,(THIS_FILE, "Syntax error parsing XML in line %d column %d", + scanner.line, pj_scan_get_col(&scanner))); } PJ_END; pj_scan_fini( &scanner ); @@ -201,22 +200,22 @@ PJ_DEF(pj_xml_node*) pj_xml_parse( pj_pool_t *pool, char *msg, pj_size_t len) /* This is a recursive function. */ static int xml_print_node( const pj_xml_node *node, int indent, - char *buf, pj_size_t len ) + char *buf, pj_size_t len ) { int i; char *p = buf; pj_xml_attr *attr; pj_xml_node *sub_node; -#define SIZE_LEFT() ((int)(len - (p-buf))) +#define SIZE_LEFT() ((int)(len - (p-buf))) PJ_CHECK_STACK(); /* Print name. */ if (SIZE_LEFT() < node->name.slen + indent + 5) - return -1; + return -1; for (i=0; iname.ptr, node->name.slen); p += node->name.slen; @@ -225,36 +224,36 @@ static int xml_print_node( const pj_xml_node *node, int indent, attr = node->attr_head.next; while (attr != &node->attr_head) { - if (SIZE_LEFT() < attr->name.slen + attr->value.slen + 4) - return -1; + if (SIZE_LEFT() < attr->name.slen + attr->value.slen + 4) + return -1; - *p++ = ' '; + *p++ = ' '; - /* Attribute name. */ - pj_memcpy(p, attr->name.ptr, attr->name.slen); - p += attr->name.slen; + /* Attribute name. */ + pj_memcpy(p, attr->name.ptr, attr->name.slen); + p += attr->name.slen; - /* Attribute value. */ - if (attr->value.slen) { - *p++ = '='; - *p++ = '"'; - pj_memcpy(p, attr->value.ptr, attr->value.slen); - p += attr->value.slen; - *p++ = '"'; - } + /* Attribute value. */ + if (attr->value.slen) { + *p++ = '='; + *p++ = '"'; + pj_memcpy(p, attr->value.ptr, attr->value.slen); + p += attr->value.slen; + *p++ = '"'; + } - attr = attr->next; + attr = attr->next; } /* Check for empty node. */ if (node->content.slen==0 && - node->node_head.next==(pj_xml_node*)&node->node_head) + node->node_head.next==(pj_xml_node*)&node->node_head) { if (SIZE_LEFT() < 3) return -1; - *p++ = ' '; - *p++ = '/'; - *p++ = '>'; - return (int)(p-buf); + *p++ = ' '; + *p++ = '/'; + *p++ = '>'; + return (int)(p-buf); } /* Enclosing '>' */ @@ -264,39 +263,39 @@ static int xml_print_node( const pj_xml_node *node, int indent, /* Print sub nodes. */ sub_node = node->node_head.next; while (sub_node != (pj_xml_node*)&node->node_head) { - int printed; + int printed; - if (SIZE_LEFT() < indent + 3) - return -1; - //*p++ = '\r'; - *p++ = '\n'; + if (SIZE_LEFT() < indent + 3) + return -1; + //*p++ = '\r'; + *p++ = '\n'; - printed = xml_print_node(sub_node, indent + 1, p, SIZE_LEFT()); - if (printed < 0) - return -1; + printed = xml_print_node(sub_node, indent + 1, p, SIZE_LEFT()); + if (printed < 0) + return -1; - p += printed; - sub_node = sub_node->next; + p += printed; + sub_node = sub_node->next; } /* Content. */ if (node->content.slen) { - if (SIZE_LEFT() < node->content.slen) return -1; - pj_memcpy(p, node->content.ptr, node->content.slen); - p += node->content.slen; + if (SIZE_LEFT() < node->content.slen) return -1; + pj_memcpy(p, node->content.ptr, node->content.slen); + p += node->content.slen; } /* Enclosing node. */ if (node->node_head.next != (pj_xml_node*)&node->node_head) { - if (SIZE_LEFT() < node->name.slen + 5 + indent) - return -1; - //*p++ = '\r'; - *p++ = '\n'; - for (i=0; iname.slen + 5 + indent) + return -1; + //*p++ = '\r'; + *p++ = '\n'; + for (i=0; iname.slen + 3) - return -1; + if (SIZE_LEFT() < node->name.slen + 3) + return -1; } *p++ = '<'; *p++ = '/'; @@ -310,25 +309,25 @@ static int xml_print_node( const pj_xml_node *node, int indent, } PJ_DEF(int) pj_xml_print(const pj_xml_node *node, char *buf, pj_size_t len, - pj_bool_t include_prolog) + pj_bool_t include_prolog) { int prolog_len = 0; int printed; if (!node || !buf || !len) - return 0; + return 0; if (include_prolog) { - pj_str_t prolog = {"\n", 39}; - if ((int)len < prolog.slen) - return -1; - pj_memcpy(buf, prolog.ptr, prolog.slen); - prolog_len = (int)prolog.slen; + pj_str_t prolog = {"\n", 39}; + if ((int)len < prolog.slen) + return -1; + pj_memcpy(buf, prolog.ptr, prolog.slen); + prolog_len = (int)prolog.slen; } printed = xml_print_node(node, 0, buf+prolog_len, len-prolog_len) + prolog_len; if (printed > 0 && len-printed >= 1) { - buf[printed++] = '\n'; + buf[printed++] = '\n'; } return printed; } @@ -341,7 +340,7 @@ PJ_DEF(pj_xml_node*) pj_xml_node_new(pj_pool_t *pool, const pj_str_t *name) } PJ_DEF(pj_xml_attr*) pj_xml_attr_new( pj_pool_t *pool, const pj_str_t *name, - const pj_str_t *value) + const pj_str_t *value) { pj_xml_attr *attr = alloc_attr(pool); pj_strdup( pool, &attr->name, name); @@ -360,70 +359,70 @@ PJ_DEF(void) pj_xml_add_attr( pj_xml_node *node, pj_xml_attr *attr ) } PJ_DEF(pj_xml_node*) pj_xml_find_node(const pj_xml_node *parent, - const pj_str_t *name) + const pj_str_t *name) { const pj_xml_node *node = parent->node_head.next; PJ_CHECK_STACK(); while (node != (void*)&parent->node_head) { - if (pj_stricmp(&node->name, name) == 0) - return (pj_xml_node*)node; - node = node->next; + if (pj_stricmp(&node->name, name) == 0) + return (pj_xml_node*)node; + node = node->next; } return NULL; } PJ_DEF(pj_xml_node*) pj_xml_find_node_rec(const pj_xml_node *parent, - const pj_str_t *name) + const pj_str_t *name) { const pj_xml_node *node = parent->node_head.next; PJ_CHECK_STACK(); while (node != (void*)&parent->node_head) { - pj_xml_node *found; - if (pj_stricmp(&node->name, name) == 0) - return (pj_xml_node*)node; - found = pj_xml_find_node_rec(node, name); - if (found) - return (pj_xml_node*)found; - node = node->next; + pj_xml_node *found; + if (pj_stricmp(&node->name, name) == 0) + return (pj_xml_node*)node; + found = pj_xml_find_node_rec(node, name); + if (found) + return (pj_xml_node*)found; + node = node->next; } return NULL; } PJ_DEF(pj_xml_node*) pj_xml_find_next_node( const pj_xml_node *parent, - const pj_xml_node *node, - const pj_str_t *name) + const pj_xml_node *node, + const pj_str_t *name) { PJ_CHECK_STACK(); node = node->next; while (node != (void*)&parent->node_head) { - if (pj_stricmp(&node->name, name) == 0) - return (pj_xml_node*)node; - node = node->next; + if (pj_stricmp(&node->name, name) == 0) + return (pj_xml_node*)node; + node = node->next; } return NULL; } PJ_DEF(pj_xml_attr*) pj_xml_find_attr( const pj_xml_node *node, - const pj_str_t *name, - const pj_str_t *value) + const pj_str_t *name, + const pj_str_t *value) { const pj_xml_attr *attr = node->attr_head.next; while (attr != (void*)&node->attr_head) { - if (pj_stricmp(&attr->name, name)==0) { - if (value) { - if (pj_stricmp(&attr->value, value)==0) - return (pj_xml_attr*)attr; - } else { - return (pj_xml_attr*)attr; - } - } - attr = attr->next; + if (pj_stricmp(&attr->name, name)==0) { + if (value) { + if (pj_stricmp(&attr->value, value)==0) + return (pj_xml_attr*)attr; + } else { + return (pj_xml_attr*)attr; + } + } + attr = attr->next; } return NULL; } @@ -431,69 +430,69 @@ PJ_DEF(pj_xml_attr*) pj_xml_find_attr( const pj_xml_node *node, PJ_DEF(pj_xml_node*) pj_xml_find( const pj_xml_node *parent, - const pj_str_t *name, - const void *data, - pj_bool_t (*match)(const pj_xml_node *, - const void*)) + const pj_str_t *name, + const void *data, + pj_bool_t (*match)(const pj_xml_node *, + const void*)) { const pj_xml_node *node = (const pj_xml_node *)parent->node_head.next; if (!name && !match) - return NULL; + return NULL; while (node != (const pj_xml_node*) &parent->node_head) { - if (name) { - if (pj_stricmp(&node->name, name)!=0) { - node = node->next; - continue; - } - } - if (match) { - if (match(node, data)) - return (pj_xml_node*)node; - } else { - return (pj_xml_node*)node; - } - - node = node->next; + if (name) { + if (pj_stricmp(&node->name, name)!=0) { + node = node->next; + continue; + } + } + if (match) { + if (match(node, data)) + return (pj_xml_node*)node; + } else { + return (pj_xml_node*)node; + } + + node = node->next; } return NULL; } PJ_DEF(pj_xml_node*) pj_xml_find_rec( const pj_xml_node *parent, - const pj_str_t *name, - const void *data, - pj_bool_t (*match)(const pj_xml_node*, - const void*)) + const pj_str_t *name, + const void *data, + pj_bool_t (*match)(const pj_xml_node*, + const void*)) { const pj_xml_node *node = (const pj_xml_node *)parent->node_head.next; if (!name && !match) - return NULL; + return NULL; while (node != (const pj_xml_node*) &parent->node_head) { - pj_xml_node *found; - - if (name) { - if (pj_stricmp(&node->name, name)==0) { - if (match) { - if (match(node, data)) - return (pj_xml_node*)node; - } else { - return (pj_xml_node*)node; - } - } - - } else if (match) { - if (match(node, data)) - return (pj_xml_node*)node; - } - - found = pj_xml_find_rec(node, name, data, match); - if (found) - return found; - - node = node->next; + pj_xml_node *found; + + if (name) { + if (pj_stricmp(&node->name, name)==0) { + if (match) { + if (match(node, data)) + return (pj_xml_node*)node; + } else { + return (pj_xml_node*)node; + } + } + + } else if (match) { + if (match(node, data)) + return (pj_xml_node*)node; + } + + found = pj_xml_find_rec(node, name, data, match); + if (found) + return found; + + node = node->next; } return NULL; } @@ -513,26 +512,26 @@ PJ_DEF(pj_xml_node*) pj_xml_clone( pj_pool_t *pool, const pj_xml_node *rhs) r_attr = rhs->attr_head.next; while (r_attr != &rhs->attr_head) { - pj_xml_attr *attr; + pj_xml_attr *attr; - attr = alloc_attr(pool); - pj_strdup(pool, &attr->name, &r_attr->name); - pj_strdup(pool, &attr->value, &r_attr->value); + attr = alloc_attr(pool); + pj_strdup(pool, &attr->name, &r_attr->name); + pj_strdup(pool, &attr->value, &r_attr->value); - pj_list_push_back(&node->attr_head, attr); + pj_list_push_back(&node->attr_head, attr); - r_attr = r_attr->next; + r_attr = r_attr->next; } /* Clone all child nodes. */ child = rhs->node_head.next; while (child != (pj_xml_node*) &rhs->node_head) { - pj_xml_node *new_child; + pj_xml_node *new_child; - new_child = pj_xml_clone(pool, child); - pj_list_push_back(&node->node_head, new_child); + new_child = pj_xml_clone(pool, child); + pj_list_push_back(&node->node_head, new_child); - child = child->next; + child = child->next; } return node; diff --git a/pjlib-util/src/pjlib-util/xml_wrap.cpp b/pjlib-util/src/pjlib-util/xml_wrap.cpp index e1d729ffde..7435cc44f5 100644 --- a/pjlib-util/src/pjlib-util/xml_wrap.cpp +++ b/pjlib-util/src/pjlib-util/xml_wrap.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjlib/build/os-auto.mak.in b/pjlib/build/os-auto.mak.in index 1e44d12f3a..4d3724c3e7 100644 --- a/pjlib/build/os-auto.mak.in +++ b/pjlib/build/os-auto.mak.in @@ -8,17 +8,17 @@ AC_OS_OBJS=@ac_os_objs@ # (the library) for this specific operating system. Object files common # to all operating systems should go in Makefile instead. # -export PJLIB_OBJS += $(AC_OS_OBJS) \ - addr_resolv_sock.o \ - log_writer_stdout.o \ - os_timestamp_common.o \ - pool_policy_malloc.o sock_bsd.o sock_select.o +export PJLIB_OBJS += $(AC_OS_OBJS) \ + addr_resolv_sock.o \ + log_writer_stdout.o \ + os_timestamp_common.o \ + pool_policy_malloc.o sock_bsd.o sock_select.o # # TEST_OBJS are operating system specific object files to be included in # the test application. # -export TEST_OBJS += @ac_main_obj@ +export TEST_OBJS += @ac_main_obj@ # # Additional LDFLAGS for pjlib-test @@ -30,5 +30,5 @@ export TEST_OBJS += @ac_main_obj@ # TARGETS are make targets in the Makefile, to be executed for this given # operating system. # -export TARGETS = $(PJLIB_LIB) $(PJLIB_SONAME) +export TARGETS = $(PJLIB_LIB) $(PJLIB_SONAME) export TARGETS_EXE = $(TEST_EXE) diff --git a/pjlib/include/pj++/file.hpp b/pjlib/include/pj++/file.hpp index ee6998c50f..c75cd34f7a 100644 --- a/pjlib/include/pj++/file.hpp +++ b/pjlib/include/pj++/file.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/include/pj++/hash.hpp b/pjlib/include/pj++/hash.hpp index de89e5a603..445883e75f 100644 --- a/pjlib/include/pj++/hash.hpp +++ b/pjlib/include/pj++/hash.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,36 +35,36 @@ class Pj_Hash_Table : public Pj_Object class iterator { public: - iterator() + iterator() { } - explicit iterator(pj_hash_table_t *h, pj_hash_iterator_t *i) + explicit iterator(pj_hash_table_t *h, pj_hash_iterator_t *i) : ht_(h), it_(i) { } - iterator(const iterator &rhs) + iterator(const iterator &rhs) : ht_(rhs.ht_), it_(rhs.it_) { } - void operator++() + void operator++() { it_ = pj_hash_next(ht_, it_); } - bool operator==(const iterator &rhs) + bool operator==(const iterator &rhs) { return ht_ == rhs.ht_ && it_ == rhs.it_; } - iterator & operator=(const iterator &rhs) + iterator & operator=(const iterator &rhs) { ht_=rhs.ht_; it_=rhs.it_; return *this; } private: - pj_hash_table_t *ht_; - pj_hash_iterator_t it_val_; - pj_hash_iterator_t *it_; + pj_hash_table_t *ht_; + pj_hash_iterator_t it_val_; + pj_hash_iterator_t *it_; - friend class Pj_Hash_Table; + friend class Pj_Hash_Table; }; // @@ -73,7 +72,7 @@ class Pj_Hash_Table : public Pj_Object // Pj_Hash_Table(Pj_Pool *pool, unsigned size) { - table_ = pj_hash_create(pool->pool_(), size); + table_ = pj_hash_create(pool->pool_(), size); } // @@ -90,7 +89,7 @@ class Pj_Hash_Table : public Pj_Object const void *key, unsigned keylen = PJ_HASH_KEY_STRING) { - return pj_hash_calc(initial_hval, key, keylen); + return pj_hash_calc(initial_hval, key, keylen); } // @@ -98,7 +97,7 @@ class Pj_Hash_Table : public Pj_Object // pj_hash_table_t *pj_hash_table_t_() { - return table_; + return table_; } // @@ -106,7 +105,7 @@ class Pj_Hash_Table : public Pj_Object // void *get(const void *key, unsigned keylen = PJ_HASH_KEY_STRING) { - return pj_hash_get(table_, key, keylen); + return pj_hash_get(table_, key, keylen); } // @@ -118,7 +117,7 @@ class Pj_Hash_Table : public Pj_Object void *value, unsigned keylen = PJ_HASH_KEY_STRING) { - pj_hash_set(pool->pool_(), table_, key, keylen, value); + pj_hash_set(pool->pool_(), table_, key, keylen, value); } // @@ -126,7 +125,7 @@ class Pj_Hash_Table : public Pj_Object // unsigned count() { - return pj_hash_count(table_); + return pj_hash_count(table_); } // @@ -134,9 +133,9 @@ class Pj_Hash_Table : public Pj_Object // iterator begin() { - iterator it(table_, NULL); - it.it_ = pj_hash_first(table_, &it.it_val_); - return it; + iterator it(table_, NULL); + it.it_ = pj_hash_first(table_, &it.it_val_); + return it; } // @@ -144,7 +143,7 @@ class Pj_Hash_Table : public Pj_Object // iterator end() { - return iterator(table_, NULL); + return iterator(table_, NULL); } private: @@ -152,5 +151,5 @@ class Pj_Hash_Table : public Pj_Object }; -#endif /* __PJPP_HASH_HPP__ */ +#endif /* __PJPP_HASH_HPP__ */ diff --git a/pjlib/include/pj++/list.hpp b/pjlib/include/pj++/list.hpp index 3dfdf6aedd..0cde6871bc 100644 --- a/pjlib/include/pj++/list.hpp +++ b/pjlib/include/pj++/list.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -48,35 +47,35 @@ class Pj_List : public Pj_Object class const_iterator { public: - const_iterator() + const_iterator() : node_(NULL) {} - const_iterator(const List_Node *nd) + const_iterator(const List_Node *nd) : node_((List_Node*)nd) {} - const List_Node * operator *() + const List_Node * operator *() { return node_; } - const List_Node * operator -> () + const List_Node * operator -> () { return node_; } - const_iterator operator++() + const_iterator operator++() { return const_iterator((const List_Node *)node_->next); } - bool operator==(const const_iterator &rhs) + bool operator==(const const_iterator &rhs) { return node_ == rhs.node_; } - bool operator!=(const const_iterator &rhs) + bool operator!=(const const_iterator &rhs) { return node_ != rhs.node_; } protected: - List_Node *node_; + List_Node *node_; }; // @@ -85,28 +84,28 @@ class Pj_List : public Pj_Object class iterator : public const_iterator { public: - iterator() + iterator() {} - iterator(List_Node *nd) + iterator(List_Node *nd) : const_iterator(nd) {} - List_Node * operator *() + List_Node * operator *() { return node_; } - List_Node * operator -> () + List_Node * operator -> () { return node_; } - iterator operator++() + iterator operator++() { return iterator((List_Node*)node_->next); } - bool operator==(const iterator &rhs) + bool operator==(const iterator &rhs) { return node_ == rhs.node_; } - bool operator!=(const iterator &rhs) + bool operator!=(const iterator &rhs) { return node_ != rhs.node_; } @@ -126,11 +125,11 @@ class Pj_List : public Pj_Object // operator pj_list&() { - return (pj_list&)root_; + return (pj_list&)root_; } operator const pj_list&() { - return (const pj_list&)root_; + return (const pj_list&)root_; } // @@ -138,11 +137,11 @@ class Pj_List : public Pj_Object // operator pj_list*() { - return (pj_list*)&root_; + return (pj_list*)&root_; } operator const pj_list*() { - return (const pj_list*)&root_; + return (const pj_list*)&root_; } // @@ -150,7 +149,7 @@ class Pj_List : public Pj_Object // bool empty() const { - return pj_list_empty(&root_); + return pj_list_empty(&root_); } // @@ -158,7 +157,7 @@ class Pj_List : public Pj_Object // iterator begin() { - return iterator(root_.next); + return iterator(root_.next); } // @@ -166,7 +165,7 @@ class Pj_List : public Pj_Object // const_iterator begin() const { - return const_iterator(root_.next); + return const_iterator(root_.next); } // @@ -174,7 +173,7 @@ class Pj_List : public Pj_Object // const_iterator end() const { - return const_iterator((List_Node*)&root_); + return const_iterator((List_Node*)&root_); } // @@ -182,7 +181,7 @@ class Pj_List : public Pj_Object // iterator end() { - return iterator((List_Node*)&root_); + return iterator((List_Node*)&root_); } // @@ -190,7 +189,7 @@ class Pj_List : public Pj_Object // void insert_before (iterator &pos, List_Node *node) { - pj_list_insert_before( *pos, node ); + pj_list_insert_before( *pos, node ); } // @@ -198,7 +197,7 @@ class Pj_List : public Pj_Object // void insert_after(iterator &pos, List_Node *node) { - pj_list_insert_after(*pos, node); + pj_list_insert_after(*pos, node); } // @@ -206,7 +205,7 @@ class Pj_List : public Pj_Object // void merge_first(List_Node *list2) { - pj_list_merge_first(&root_, list2); + pj_list_merge_first(&root_, list2); } // @@ -214,7 +213,7 @@ class Pj_List : public Pj_Object // void merge_last(Pj_List *list) { - pj_list_merge_last(&root_, &list->root_); + pj_list_merge_last(&root_, &list->root_); } // @@ -222,7 +221,7 @@ class Pj_List : public Pj_Object // void insert_nodes_before(iterator &pos, Pj_List *list2) { - pj_list_insert_nodes_before(*pos, &list2->root_); + pj_list_insert_nodes_before(*pos, &list2->root_); } // @@ -230,7 +229,7 @@ class Pj_List : public Pj_Object // void insert_nodes_after(iterator &pos, Pj_List *list2) { - pj_list_insert_nodes_after(*pos, &list2->root_); + pj_list_insert_nodes_after(*pos, &list2->root_); } // @@ -238,7 +237,7 @@ class Pj_List : public Pj_Object // void erase(iterator &it) { - pj_list_erase(*it); + pj_list_erase(*it); } // @@ -246,7 +245,7 @@ class Pj_List : public Pj_Object // List_Node *front() { - return root_.next; + return root_.next; } // @@ -254,7 +253,7 @@ class Pj_List : public Pj_Object // const List_Node *front() const { - return root_.next; + return root_.next; } // @@ -262,7 +261,7 @@ class Pj_List : public Pj_Object // void pop_front() { - pj_list_erase(root_.next); + pj_list_erase(root_.next); } // @@ -270,7 +269,7 @@ class Pj_List : public Pj_Object // List_Node *back() { - return root_.prev; + return root_.prev; } // @@ -278,7 +277,7 @@ class Pj_List : public Pj_Object // const List_Node *back() const { - return root_.prev; + return root_.prev; } // @@ -286,7 +285,7 @@ class Pj_List : public Pj_Object // void pop_back() { - pj_list_erase(root_.prev); + pj_list_erase(root_.prev); } // @@ -294,8 +293,8 @@ class Pj_List : public Pj_Object // iterator find(List_Node *node) { - List_Node *n = pj_list_find_node(&root_, node); - return n ? iterator(n) : end(); + List_Node *n = pj_list_find_node(&root_, node); + return n ? iterator(n) : end(); } // @@ -303,8 +302,8 @@ class Pj_List : public Pj_Object // const_iterator find(List_Node *node) const { - List_Node *n = pj_list_find_node(&root_, node); - return n ? const_iterator(n) : end(); + List_Node *n = pj_list_find_node(&root_, node); + return n ? const_iterator(n) : end(); } // @@ -312,7 +311,7 @@ class Pj_List : public Pj_Object // void push_back(List_Node *node) { - pj_list_insert_after(root_.prev, node); + pj_list_insert_after(root_.prev, node); } // @@ -320,7 +319,7 @@ class Pj_List : public Pj_Object // void push_front(List_Node *node) { - pj_list_insert_before(root_.next, node); + pj_list_insert_before(root_.next, node); } // @@ -328,25 +327,25 @@ class Pj_List : public Pj_Object // void clear() { - root_.next = &root_; - root_.prev = &root_; + root_.next = &root_; + root_.prev = &root_; } private: struct RootNode { - PJ_DECL_LIST_MEMBER(List_Node); + PJ_DECL_LIST_MEMBER(List_Node); } root_; void compiletest() { - // If you see error in this line, - // it's because List_Node is not derived from Pj_List_Node. - List_Node *n = (List_Node*)0; - n = (List_Node *)n->next; n = (List_Node *)n->prev; + // If you see error in this line, + // it's because List_Node is not derived from Pj_List_Node. + List_Node *n = (List_Node*)0; + n = (List_Node *)n->next; n = (List_Node *)n->prev; } }; -#endif /* __PJPP_LIST_HPP__ */ +#endif /* __PJPP_LIST_HPP__ */ diff --git a/pjlib/include/pj++/lock.hpp b/pjlib/include/pj++/lock.hpp index 7bf0c36b51..76a1ef2b40 100644 --- a/pjlib/include/pj++/lock.hpp +++ b/pjlib/include/pj++/lock.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -145,5 +144,5 @@ class Pj_Semaphore_Lock : public Pj_Lock -#endif /* __PJPP_LOCK_HPP__ */ +#endif /* __PJPP_LOCK_HPP__ */ diff --git a/pjlib/include/pj++/os.hpp b/pjlib/include/pj++/os.hpp index 31cb7313a4..190285f09e 100644 --- a/pjlib/include/pj++/os.hpp +++ b/pjlib/include/pj++/os.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -86,7 +85,7 @@ class Pj_Thread_API // static pj_status_t sleep(unsigned msec) { - return pj_thread_sleep(msec); + return pj_thread_sleep(msec); } // @@ -119,7 +118,7 @@ class Pj_Thread : public Pj_Object public: enum Flags { - FLAG_SUSPENDED = PJ_THREAD_SUSPENDED + FLAG_SUSPENDED = PJ_THREAD_SUSPENDED }; // @@ -149,7 +148,7 @@ class Pj_Thread : public Pj_Object pj_status_t create( Pj_Pool *pool, unsigned flags = 0, const char *thread_name = NULL, - pj_size_t stack_size = PJ_THREAD_DEFAULT_STACK_SIZE) + pj_size_t stack_size = PJ_THREAD_DEFAULT_STACK_SIZE) { destroy(); return Pj_Thread_API::create( pool, &thread_, &thread_proc, this, @@ -161,7 +160,7 @@ class Pj_Thread : public Pj_Object // pj_thread_t *pj_thread_t_() { - return thread_; + return thread_; } // @@ -321,7 +320,7 @@ class Pj_Atomic_Var : public Pj_Object pj_status_t create( Pj_Pool *pool, pj_atomic_value_t value) { destroy(); - return pj_atomic_create(pool->pool_(), value, &var_); + return pj_atomic_create(pool->pool_(), value, &var_); } // @@ -340,7 +339,7 @@ class Pj_Atomic_Var : public Pj_Object // pj_atomic_t *pj_atomic_t_() { - return var_; + return var_; } // @@ -348,7 +347,7 @@ class Pj_Atomic_Var : public Pj_Object // void set(pj_atomic_value_t val) { - pj_atomic_set(var_, val); + pj_atomic_set(var_, val); } // @@ -356,7 +355,7 @@ class Pj_Atomic_Var : public Pj_Object // pj_atomic_value_t get() { - return pj_atomic_get(var_); + return pj_atomic_get(var_); } // @@ -364,7 +363,7 @@ class Pj_Atomic_Var : public Pj_Object // void inc() { - pj_atomic_inc(var_); + pj_atomic_inc(var_); } // @@ -380,7 +379,7 @@ class Pj_Atomic_Var : public Pj_Object // void dec() { - pj_atomic_dec(var_); + pj_atomic_dec(var_); } // @@ -423,9 +422,9 @@ class Pj_Mutex : public Pj_Object // enum Type { - DEFAULT = PJ_MUTEX_DEFAULT, - SIMPLE = PJ_MUTEX_SIMPLE, - RECURSE = PJ_MUTEX_RECURSE, + DEFAULT = PJ_MUTEX_DEFAULT, + SIMPLE = PJ_MUTEX_SIMPLE, + RECURSE = PJ_MUTEX_RECURSE, }; // @@ -452,7 +451,7 @@ class Pj_Mutex : public Pj_Object pj_status_t create( Pj_Pool *pool, Type type, const char *name = NULL) { destroy(); - return pj_mutex_create( pool->pool_(), name, type, + return pj_mutex_create( pool->pool_(), name, type, &mutex_ ); } @@ -477,7 +476,7 @@ class Pj_Mutex : public Pj_Object // pj_mutex_t *pj_mutex_t_() { - return mutex_; + return mutex_; } // @@ -486,7 +485,7 @@ class Pj_Mutex : public Pj_Object void destroy() { if (mutex_) { - pj_mutex_destroy(mutex_); + pj_mutex_destroy(mutex_); mutex_ = NULL; } } @@ -496,7 +495,7 @@ class Pj_Mutex : public Pj_Object // pj_status_t acquire() { - return pj_mutex_lock(mutex_); + return pj_mutex_lock(mutex_); } // @@ -504,7 +503,7 @@ class Pj_Mutex : public Pj_Object // pj_status_t release() { - return pj_mutex_unlock(mutex_); + return pj_mutex_unlock(mutex_); } // @@ -512,7 +511,7 @@ class Pj_Mutex : public Pj_Object // pj_status_t tryacquire() { - return pj_mutex_trylock(mutex_); + return pj_mutex_trylock(mutex_); } private: @@ -533,7 +532,7 @@ class Pj_Semaphore : public Pj_Object unsigned initial = 0, const char *name = NULL) : sem_(NULL) { - create(pool, max, initial, name); + create(pool, max, initial, name); } // @@ -551,7 +550,7 @@ class Pj_Semaphore : public Pj_Object unsigned initial = 0, const char *name = NULL ) { destroy(); - return pj_sem_create( pool->pool_(), name, initial, max, &sem_); + return pj_sem_create( pool->pool_(), name, initial, max, &sem_); } // @@ -570,7 +569,7 @@ class Pj_Semaphore : public Pj_Object // pj_sem_t *pj_sem_t_() { - return (pj_sem_t*)this; + return (pj_sem_t*)this; } // @@ -578,7 +577,7 @@ class Pj_Semaphore : public Pj_Object // pj_status_t wait() { - return pj_sem_wait(this->pj_sem_t_()); + return pj_sem_wait(this->pj_sem_t_()); } // @@ -586,7 +585,7 @@ class Pj_Semaphore : public Pj_Object // pj_status_t acquire() { - return wait(); + return wait(); } // @@ -594,7 +593,7 @@ class Pj_Semaphore : public Pj_Object // pj_status_t trywait() { - return pj_sem_trywait(this->pj_sem_t_()); + return pj_sem_trywait(this->pj_sem_t_()); } // @@ -602,7 +601,7 @@ class Pj_Semaphore : public Pj_Object // pj_status_t tryacquire() { - return trywait(); + return trywait(); } // @@ -610,7 +609,7 @@ class Pj_Semaphore : public Pj_Object // pj_status_t post() { - return pj_sem_post(this->pj_sem_t_()); + return pj_sem_post(this->pj_sem_t_()); } // @@ -618,7 +617,7 @@ class Pj_Semaphore : public Pj_Object // pj_status_t release() { - return post(); + return post(); } private: @@ -657,7 +656,7 @@ class Pj_Event bool initial = false, const char *name = NULL) { destroy(); - return pj_event_create(pool->pool_(), name, manual_reset, initial, + return pj_event_create(pool->pool_(), name, manual_reset, initial, &event_); } @@ -666,7 +665,7 @@ class Pj_Event // pj_event_t *pj_event_t_() { - return event_; + return event_; } // @@ -675,7 +674,7 @@ class Pj_Event void destroy() { if (event_) { - pj_event_destroy(event_); + pj_event_destroy(event_); event_ = NULL; } } @@ -685,7 +684,7 @@ class Pj_Event // pj_status_t wait() { - return pj_event_wait(event_); + return pj_event_wait(event_); } // @@ -693,7 +692,7 @@ class Pj_Event // pj_status_t trywait() { - return pj_event_trywait(event_); + return pj_event_trywait(event_); } // @@ -701,7 +700,7 @@ class Pj_Event // pj_status_t set() { - return pj_event_set(this->pj_event_t_()); + return pj_event_set(this->pj_event_t_()); } // @@ -709,7 +708,7 @@ class Pj_Event // pj_status_t pulse() { - return pj_event_pulse(this->pj_event_t_()); + return pj_event_pulse(this->pj_event_t_()); } // @@ -717,7 +716,7 @@ class Pj_Event // pj_status_t reset() { - return pj_event_reset(this->pj_event_t_()); + return pj_event_reset(this->pj_event_t_()); } private: @@ -732,54 +731,54 @@ class Pj_Timestamp public: pj_status_t get_timestamp() { - return pj_get_timestamp(&ts_); + return pj_get_timestamp(&ts_); } Pj_Timestamp& operator += (const Pj_Timestamp &rhs) { - pj_add_timestamp(&ts_, &rhs.ts_); - return *this; + pj_add_timestamp(&ts_, &rhs.ts_); + return *this; } Pj_Timestamp& operator -= (const Pj_Timestamp &rhs) { - pj_sub_timestamp(&ts_, &rhs.ts_); - return *this; + pj_sub_timestamp(&ts_, &rhs.ts_); + return *this; } Pj_Time_Val to_time() const { - Pj_Timestamp zero; - pj_memset(&zero, 0, sizeof(zero)); - return Pj_Time_Val(pj_elapsed_time(&zero.ts_, &ts_)); + Pj_Timestamp zero; + pj_memset(&zero, 0, sizeof(zero)); + return Pj_Time_Val(pj_elapsed_time(&zero.ts_, &ts_)); } pj_uint32_t to_msec() const { - Pj_Timestamp zero; - pj_memset(&zero, 0, sizeof(zero)); - return pj_elapsed_msec(&zero.ts_, &ts_); + Pj_Timestamp zero; + pj_memset(&zero, 0, sizeof(zero)); + return pj_elapsed_msec(&zero.ts_, &ts_); } pj_uint32_t to_usec() const { - Pj_Timestamp zero; - pj_memset(&zero, 0, sizeof(zero)); - return pj_elapsed_usec(&zero.ts_, &ts_); + Pj_Timestamp zero; + pj_memset(&zero, 0, sizeof(zero)); + return pj_elapsed_usec(&zero.ts_, &ts_); } pj_uint32_t to_nanosec() const { - Pj_Timestamp zero; - pj_memset(&zero, 0, sizeof(zero)); - return pj_elapsed_nanosec(&zero.ts_, &ts_); + Pj_Timestamp zero; + pj_memset(&zero, 0, sizeof(zero)); + return pj_elapsed_nanosec(&zero.ts_, &ts_); } pj_uint32_t to_cycle() const { - Pj_Timestamp zero; - pj_memset(&zero, 0, sizeof(zero)); - return pj_elapsed_cycle(&zero.ts_, &ts_); + Pj_Timestamp zero; + pj_memset(&zero, 0, sizeof(zero)); + return pj_elapsed_cycle(&zero.ts_, &ts_); } private: @@ -798,7 +797,7 @@ class Pj_OS_API // static pj_status_t gettimeofday( Pj_Time_Val *tv ) { - return pj_gettimeofday(tv); + return pj_gettimeofday(tv); } // @@ -807,7 +806,7 @@ class Pj_OS_API static pj_status_t time_decode( const Pj_Time_Val *tv, pj_parsed_time *pt ) { - return pj_time_decode(tv, pt); + return pj_time_decode(tv, pt); } // @@ -816,7 +815,7 @@ class Pj_OS_API static pj_status_t time_encode( const pj_parsed_time *pt, Pj_Time_Val *tv) { - return pj_time_encode(pt, tv); + return pj_time_encode(pt, tv); } // @@ -824,7 +823,7 @@ class Pj_OS_API // static pj_status_t time_local_to_gmt( Pj_Time_Val *tv ) { - return pj_time_local_to_gmt( tv ); + return pj_time_local_to_gmt( tv ); } // @@ -832,7 +831,7 @@ class Pj_OS_API // static pj_status_t time_gmt_to_local( Pj_Time_Val *tv) { - return pj_time_gmt_to_local( tv ); + return pj_time_gmt_to_local( tv ); } }; @@ -866,5 +865,5 @@ inline pj_status_t Pj_Time_Val::to_local() return Pj_OS_API::time_gmt_to_local(this); } -#endif /* __PJPP_OS_HPP__ */ +#endif /* __PJPP_OS_HPP__ */ diff --git a/pjlib/include/pj++/pool.hpp b/pjlib/include/pj++/pool.hpp index 607ca7fc95..5965de0124 100644 --- a/pjlib/include/pj++/pool.hpp +++ b/pjlib/include/pj++/pool.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -112,7 +111,7 @@ class Pj_Pool : public Pj_Object ~Pj_Pool() { if (p_) - pj_pool_release(p_); + pj_pool_release(p_); } // @@ -120,7 +119,7 @@ class Pj_Pool : public Pj_Object // const char *getobjname() const { - return pj_pool_getobjname(p_); + return pj_pool_getobjname(p_); } // @@ -128,7 +127,7 @@ class Pj_Pool : public Pj_Object // operator pj_pool_t*() { - return p_; + return p_; } // @@ -136,7 +135,7 @@ class Pj_Pool : public Pj_Object // pj_pool_t *pool_() { - return p_; + return p_; } // @@ -144,7 +143,7 @@ class Pj_Pool : public Pj_Object // const pj_pool_t *pool_() const { - return p_; + return p_; } // @@ -152,7 +151,7 @@ class Pj_Pool : public Pj_Object // pj_pool_t *pj_pool_t_() { - return p_; + return p_; } // @@ -160,7 +159,7 @@ class Pj_Pool : public Pj_Object // void reset() { - pj_pool_reset(p_); + pj_pool_reset(p_); } // @@ -168,7 +167,7 @@ class Pj_Pool : public Pj_Object // pj_size_t get_capacity() { - pj_pool_get_capacity(p_); + pj_pool_get_capacity(p_); } // @@ -176,7 +175,7 @@ class Pj_Pool : public Pj_Object // pj_size_t get_used_size() { - pj_pool_get_used_size(p_); + pj_pool_get_used_size(p_); } // @@ -184,7 +183,7 @@ class Pj_Pool : public Pj_Object // void *alloc(pj_size_t size) { - return pj_pool_alloc(p_, size); + return pj_pool_alloc(p_, size); } // @@ -192,7 +191,7 @@ class Pj_Pool : public Pj_Object // void *calloc(pj_size_t count, pj_size_t elem) { - return pj_pool_calloc(p_, count, elem); + return pj_pool_calloc(p_, count, elem); } // @@ -218,9 +217,9 @@ class Pj_Caching_Pool // Construct caching pool. // Pj_Caching_Pool( pj_size_t cache_capacity = 0, - const pj_pool_factory_policy *pol=&pj_pool_factory_default_policy) + const pj_pool_factory_policy *pol=&pj_pool_factory_default_policy) { - pj_caching_pool_init(&cp_, pol, cache_capacity); + pj_caching_pool_init(&cp_, pol, cache_capacity); } // @@ -228,7 +227,7 @@ class Pj_Caching_Pool // ~Pj_Caching_Pool() { - pj_caching_pool_destroy(&cp_); + pj_caching_pool_destroy(&cp_); } // @@ -239,7 +238,7 @@ class Pj_Caching_Pool const char *name = NULL, pj_pool_callback *callback = NULL) { - return (pj_pool_t*)(*cp_.factory.create_pool)(&cp_.factory, name, + return (pj_pool_t*)(*cp_.factory.create_pool)(&cp_.factory, name, initial_size, increment_size, callback); @@ -275,5 +274,5 @@ inline Pj_Pool::Pj_Pool( Pj_Caching_Pool &caching_pool, } -#endif /* __PJPP_POOL_HPP__ */ +#endif /* __PJPP_POOL_HPP__ */ diff --git a/pjlib/include/pj++/proactor.hpp b/pjlib/include/pj++/proactor.hpp index 14ec287805..49fa5441db 100644 --- a/pjlib/include/pj++/proactor.hpp +++ b/pjlib/include/pj++/proactor.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,7 +45,7 @@ class Pj_Async_Op : public pj_ioqueue_op_key_t Pj_Async_Op() : handler_(NULL) { - pj_ioqueue_op_key_init(this, sizeof(*this)); + pj_ioqueue_op_key_init(this, sizeof(*this)); } // @@ -55,7 +54,7 @@ class Pj_Async_Op : public pj_ioqueue_op_key_t explicit Pj_Async_Op(Pj_Event_Handler *handler) : handler_(handler) { - pj_ioqueue_op_key_init(this, sizeof(*this)); + pj_ioqueue_op_key_init(this, sizeof(*this)); } // @@ -319,7 +318,7 @@ class Pj_Proactor : public Pj_Object // Create proactor. // pj_status_t create( Pj_Pool *pool, pj_size_t max_fd, - pj_size_t timer_entry_count) + pj_size_t timer_entry_count) { pj_status_t status; @@ -413,7 +412,7 @@ class Pj_Proactor : public Pj_Object * with the timeout to wait from timer, and use the minimum value. */ if (max_timeout && timeout >= *max_timeout) { - timeout = *max_timeout; + timeout = *max_timeout; } /* Poll events in ioqueue. */ @@ -421,7 +420,7 @@ class Pj_Proactor : public Pj_Object ioqueue_count = pj_ioqueue_poll(ioq_, &timeout); if (ioqueue_count < 0) - return ioqueue_count; + return ioqueue_count; return ioqueue_count + timer_count; } @@ -449,7 +448,7 @@ class Pj_Proactor : public Pj_Object static bool schedule_timer( pj_timer_heap_t *timer, Pj_Event_Handler *handler, - const Pj_Time_Val &delay, + const Pj_Time_Val &delay, int id=-1) { handler->timer_.id = id; @@ -465,7 +464,7 @@ class Pj_Proactor : public Pj_Object pj_ssize_t bytes_read) { Pj_Event_Handler *handler = - (Pj_Event_Handler*) pj_ioqueue_get_user_data(key); + (Pj_Event_Handler*) pj_ioqueue_get_user_data(key); handler->on_read_complete((Pj_Async_Op*)op_key, bytes_read); } @@ -478,7 +477,7 @@ class Pj_Proactor : public Pj_Object pj_ssize_t bytes_sent) { Pj_Event_Handler *handler = - (Pj_Event_Handler*) pj_ioqueue_get_user_data(key); + (Pj_Event_Handler*) pj_ioqueue_get_user_data(key); handler->on_write_complete((Pj_Async_Op*)op_key, bytes_sent); } @@ -492,7 +491,7 @@ class Pj_Proactor : public Pj_Object pj_status_t status) { Pj_Event_Handler *handler = - (Pj_Event_Handler*) pj_ioqueue_get_user_data(key); + (Pj_Event_Handler*) pj_ioqueue_get_user_data(key); handler->on_accept_complete((Pj_Async_Op*)op_key, new_sock, status); } @@ -504,12 +503,12 @@ class Pj_Proactor : public Pj_Object pj_status_t status) { Pj_Event_Handler *handler = - (Pj_Event_Handler*) pj_ioqueue_get_user_data(key); + (Pj_Event_Handler*) pj_ioqueue_get_user_data(key); handler->on_connect_complete(status); } }; -#endif /* __PJPP_PROACTOR_HPP__ */ +#endif /* __PJPP_PROACTOR_HPP__ */ diff --git a/pjlib/include/pj++/scanner.hpp b/pjlib/include/pj++/scanner.hpp index 1be9ba5f72..deef01c8c5 100644 --- a/pjlib/include/pj++/scanner.hpp +++ b/pjlib/include/pj++/scanner.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,7 +33,7 @@ class Pj_Cis_Buffer public: Pj_Cis_Buffer() { - pj_cis_buf_init(&buf_); + pj_cis_buf_init(&buf_); } private: @@ -49,57 +48,57 @@ class Pj_Cis public: Pj_Cis(Pj_Cis_Buffer *buf) { - pj_cis_init(&buf->buf_, &cis_); + pj_cis_init(&buf->buf_, &cis_); } Pj_Cis(const Pj_Cis &rhs) { - pj_cis_dup(&cis_, (pj_cis_t*)&rhs.cis_); + pj_cis_dup(&cis_, (pj_cis_t*)&rhs.cis_); } void add_range(int start, int end) { - pj_cis_add_range(&cis_, start, end); + pj_cis_add_range(&cis_, start, end); } void add_alpha() { - pj_cis_add_alpha(&cis_); + pj_cis_add_alpha(&cis_); } void add_num() { - pj_cis_add_num(&cis_); + pj_cis_add_num(&cis_); } void add_str(const char *str) { - pj_cis_add_str(&cis_, str); + pj_cis_add_str(&cis_, str); } void add_cis(const Pj_Cis &rhs) { - pj_cis_add_cis(&cis_, &rhs.cis_); + pj_cis_add_cis(&cis_, &rhs.cis_); } void del_range(int start, int end) { - pj_cis_del_range(&cis_, start, end); + pj_cis_del_range(&cis_, start, end); } void del_str(const char *str) { - pj_cis_del_str(&cis_, str); + pj_cis_del_str(&cis_, str); } void invert() { - pj_cis_invert(&cis_); + pj_cis_invert(&cis_); } bool match(int c) const { - return pj_cis_match(&cis_, c) != 0; + return pj_cis_match(&cis_, c) != 0; } private: @@ -115,126 +114,126 @@ class Pj_Scanner enum { - SYNTAX_ERROR = 101 + SYNTAX_ERROR = 101 }; static void syntax_error_handler_throw_pj(pj_scanner *); typedef pj_scan_state State; void init(char *buf, int len, unsigned options=PJ_SCAN_AUTOSKIP_WS, - pj_syn_err_func_ptr callback = &syntax_error_handler_throw_pj) + pj_syn_err_func_ptr callback = &syntax_error_handler_throw_pj) { - pj_scan_init(&scanner_, buf, len, options, callback); + pj_scan_init(&scanner_, buf, len, options, callback); } void fini() { - pj_scan_fini(&scanner_); + pj_scan_fini(&scanner_); } int eof() const { - return pj_scan_is_eof(&scanner_); + return pj_scan_is_eof(&scanner_); } int peek_char() const { - return *scanner_.curptr; + return *scanner_.curptr; } int peek(const Pj_Cis *cis, Pj_String *out) { - return pj_scan_peek(&scanner_, &cis->cis_, out); + return pj_scan_peek(&scanner_, &cis->cis_, out); } int peek_n(pj_size_t len, Pj_String *out) { - return pj_scan_peek_n(&scanner_, len, out); + return pj_scan_peek_n(&scanner_, len, out); } int peek_until(const Pj_Cis *cis, Pj_String *out) { - return pj_scan_peek_until(&scanner_, &cis->cis_, out); + return pj_scan_peek_until(&scanner_, &cis->cis_, out); } void get(const Pj_Cis *cis, Pj_String *out) { - pj_scan_get(&scanner_, &cis->cis_, out); + pj_scan_get(&scanner_, &cis->cis_, out); } void get_n(unsigned N, Pj_String *out) { - pj_scan_get_n(&scanner_, N, out); + pj_scan_get_n(&scanner_, N, out); } int get_char() { - return pj_scan_get_char(&scanner_); + return pj_scan_get_char(&scanner_); } void get_quote(int begin_quote, int end_quote, Pj_String *out) { - pj_scan_get_quote(&scanner_, begin_quote, end_quote, out); + pj_scan_get_quote(&scanner_, begin_quote, end_quote, out); } void get_newline() { - pj_scan_get_newline(&scanner_); + pj_scan_get_newline(&scanner_); } void get_until(const Pj_Cis *cis, Pj_String *out) { - pj_scan_get_until(&scanner_, &cis->cis_, out); + pj_scan_get_until(&scanner_, &cis->cis_, out); } void get_until_ch(int until_ch, Pj_String *out) { - pj_scan_get_until_ch(&scanner_, until_ch, out); + pj_scan_get_until_ch(&scanner_, until_ch, out); } void get_until_chr(const char *spec, Pj_String *out) { - pj_scan_get_until_chr(&scanner_, spec, out); + pj_scan_get_until_chr(&scanner_, spec, out); } void advance_n(unsigned N, bool skip_ws=true) { - pj_scan_advance_n(&scanner_, N, skip_ws); + pj_scan_advance_n(&scanner_, N, skip_ws); } int strcmp(const char *s, int len) { - return pj_scan_strcmp(&scanner_, s, len); + return pj_scan_strcmp(&scanner_, s, len); } int stricmp(const char *s, int len) { - return pj_scan_stricmp(&scanner_, s, len); + return pj_scan_stricmp(&scanner_, s, len); } void skip_ws() { - pj_scan_skip_whitespace(&scanner_); + pj_scan_skip_whitespace(&scanner_); } void save_state(State *state) const { - pj_scan_save_state(&scanner_, state); + pj_scan_save_state(&scanner_, state); } void restore_state(State *state) { - pj_scan_restore_state(&scanner_, state); + pj_scan_restore_state(&scanner_, state); } int get_pos_line() const { - return scanner_.line; + return scanner_.line; } int get_pos_col() const { - return pj_scan_get_col(&scanner_); + return pj_scan_get_col(&scanner_); } @@ -242,5 +241,5 @@ class Pj_Scanner pj_scanner scanner_; }; -#endif /* __PJPP_SCANNER_HPP__ */ +#endif /* __PJPP_SCANNER_HPP__ */ diff --git a/pjlib/include/pj++/sock.hpp b/pjlib/include/pj++/sock.hpp index 66a03f359a..f972b6e739 100644 --- a/pjlib/include/pj++/sock.hpp +++ b/pjlib/include/pj++/sock.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -43,7 +42,7 @@ class Pj_Inet_Addr : public pj_sockaddr_in, public Pj_Addr // pj_uint16_t get_port_number() const { - return pj_sockaddr_in_get_port(this); + return pj_sockaddr_in_get_port(this); } // @@ -51,8 +50,8 @@ class Pj_Inet_Addr : public pj_sockaddr_in, public Pj_Addr // void set_port_number(pj_uint16_t port) { - sin_family = PJ_AF_INET; - pj_sockaddr_in_set_port(this, port); + sin_family = PJ_AF_INET; + pj_sockaddr_in_set_port(this, port); } // @@ -60,7 +59,7 @@ class Pj_Inet_Addr : public pj_sockaddr_in, public Pj_Addr // pj_uint32_t get_ip_address() const { - return pj_sockaddr_in_get_addr(this).s_addr; + return pj_sockaddr_in_get_addr(this).s_addr; } // @@ -68,7 +67,7 @@ class Pj_Inet_Addr : public pj_sockaddr_in, public Pj_Addr // const char *get_address() const { - return pj_inet_ntoa(sin_addr); + return pj_inet_ntoa(sin_addr); } // @@ -76,8 +75,8 @@ class Pj_Inet_Addr : public pj_sockaddr_in, public Pj_Addr // void set_ip_address(pj_uint32_t addr) { - sin_family = PJ_AF_INET; - pj_sockaddr_in_set_addr(this, addr); + sin_family = PJ_AF_INET; + pj_sockaddr_in_set_addr(this, addr); } // @@ -85,7 +84,7 @@ class Pj_Inet_Addr : public pj_sockaddr_in, public Pj_Addr // pj_status_t set_address(const pj_str_t *addr) { - return pj_sockaddr_in_set_str_addr(this, addr); + return pj_sockaddr_in_set_str_addr(this, addr); } // @@ -94,7 +93,7 @@ class Pj_Inet_Addr : public pj_sockaddr_in, public Pj_Addr pj_status_t set_address(const char *addr) { pj_str_t s; - return pj_sockaddr_in_set_str_addr(this, pj_cstr(&s, addr)); + return pj_sockaddr_in_set_str_addr(this, pj_cstr(&s, addr)); } // @@ -102,7 +101,7 @@ class Pj_Inet_Addr : public pj_sockaddr_in, public Pj_Addr // bool operator==(const Pj_Inet_Addr &rhs) const { - return sin_family == rhs.sin_family && + return sin_family == rhs.sin_family && sin_addr.s_addr == rhs.sin_addr.s_addr && sin_port == rhs.sin_port; } @@ -166,7 +165,7 @@ class Pj_Socket // void set_handle(pj_sock_t sock) { - sock_ = sock; + sock_ = sock; } // @@ -174,7 +173,7 @@ class Pj_Socket // pj_sock_t get_handle() const { - return sock_; + return sock_; } // @@ -182,7 +181,7 @@ class Pj_Socket // pj_sock_t& get_handle() { - return sock_; + return sock_; } // @@ -198,7 +197,7 @@ class Pj_Socket // pj_status_t create(int af, int type, int proto) { - return pj_sock_socket(af, type, proto, &sock_); + return pj_sock_socket(af, type, proto, &sock_); } // @@ -206,7 +205,7 @@ class Pj_Socket // pj_status_t bind(const Pj_Inet_Addr &addr) { - return pj_sock_bind(sock_, &addr, sizeof(Pj_Inet_Addr)); + return pj_sock_bind(sock_, &addr, sizeof(Pj_Inet_Addr)); } // @@ -214,7 +213,7 @@ class Pj_Socket // pj_status_t close() { - pj_sock_close(sock_); + pj_sock_close(sock_); } // @@ -222,7 +221,7 @@ class Pj_Socket // pj_status_t getpeername(Pj_Inet_Addr *addr) { - return pj_sock_getpeername(sock_, addr, &addr->addrlen_); + return pj_sock_getpeername(sock_, addr, &addr->addrlen_); } // @@ -230,7 +229,7 @@ class Pj_Socket // pj_status_t getsockname(Pj_Inet_Addr *addr) { - return pj_sock_getsockname(sock_, addr, &addr->addrlen_); + return pj_sock_getsockname(sock_, addr, &addr->addrlen_); } // @@ -239,7 +238,7 @@ class Pj_Socket pj_status_t getsockopt(pj_uint16_t level, pj_uint16_t optname, void *optval, int *optlen) { - return pj_sock_getsockopt(sock_, level, optname, optval, optlen); + return pj_sock_getsockopt(sock_, level, optname, optval, optlen); } // @@ -248,7 +247,7 @@ class Pj_Socket pj_status_t setsockopt(pj_uint16_t level, pj_uint16_t optname, const void *optval, int optlen) { - return pj_sock_setsockopt(sock_, level, optname, optval, optlen); + return pj_sock_setsockopt(sock_, level, optname, optval, optlen); } // @@ -257,7 +256,7 @@ class Pj_Socket pj_ssize_t recv(void *buf, pj_size_t len, int flag = 0) { pj_ssize_t bytes = len; - if (pj_sock_recv(sock_, buf, &bytes, flag) != PJ_SUCCESS) + if (pj_sock_recv(sock_, buf, &bytes, flag) != PJ_SUCCESS) return -1; return bytes; } @@ -268,7 +267,7 @@ class Pj_Socket pj_ssize_t send(const void *buf, pj_ssize_t len, int flag = 0) { pj_ssize_t bytes = len; - if (pj_sock_send(sock_, buf, &bytes, flag) != PJ_SUCCESS) + if (pj_sock_send(sock_, buf, &bytes, flag) != PJ_SUCCESS) return -1; return bytes; } @@ -278,7 +277,7 @@ class Pj_Socket // pj_status_t connect(const Pj_Inet_Addr &addr) { - return pj_sock_connect(sock_, &addr, sizeof(Pj_Inet_Addr)); + return pj_sock_connect(sock_, &addr, sizeof(Pj_Inet_Addr)); } // @@ -339,7 +338,7 @@ class Pj_Sock_Stream : public Pj_Socket // pj_status_t listen(int backlog = 5) { - return pj_sock_listen(sock_, backlog); + return pj_sock_listen(sock_, backlog); } // @@ -363,7 +362,7 @@ class Pj_Sock_Stream : public Pj_Socket // pj_status_t shutdown(int how = PJ_SHUT_RDWR) { - return pj_sock_shutdown(sock_, how); + return pj_sock_shutdown(sock_, how); } }; @@ -415,7 +414,7 @@ class Pj_Sock_Dgram : public Pj_Socket { pj_ssize_t bytes = len; int *addrlen = fromaddr ? &fromaddr->addrlen_ : NULL; - if (pj_sock_recvfrom( sock_, buf, &bytes, flag, + if (pj_sock_recvfrom( sock_, buf, &bytes, flag, fromaddr, addrlen) != PJ_SUCCESS) { return -1; @@ -430,7 +429,7 @@ class Pj_Sock_Dgram : public Pj_Socket const Pj_Inet_Addr &addr) { pj_ssize_t bytes = len; - if (pj_sock_sendto( sock_, buf, &bytes, flag, + if (pj_sock_sendto( sock_, buf, &bytes, flag, &addr, sizeof(pj_sockaddr_in)) != PJ_SUCCESS) { return -1; @@ -440,5 +439,5 @@ class Pj_Sock_Dgram : public Pj_Socket }; -#endif /* __PJPP_SOCK_HPP__ */ +#endif /* __PJPP_SOCK_HPP__ */ diff --git a/pjlib/include/pj++/string.hpp b/pjlib/include/pj++/string.hpp index 56d242e090..2c6b218cd8 100644 --- a/pjlib/include/pj++/string.hpp +++ b/pjlib/include/pj++/string.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,8 +34,8 @@ class Pj_String : public pj_str_t // Pj_String() { - pj_assert(sizeof(Pj_String) == sizeof(pj_str_t)); - ptr=NULL; + pj_assert(sizeof(Pj_String) == sizeof(pj_str_t)); + ptr=NULL; slen=0; } @@ -45,7 +44,7 @@ class Pj_String : public pj_str_t // Pj_String(char *str) { - set(str); + set(str); } // @@ -53,7 +52,7 @@ class Pj_String : public pj_str_t // Pj_String(Pj_Pool &pool, const char *src) { - set(pool, src); + set(pool, src); } // @@ -61,8 +60,8 @@ class Pj_String : public pj_str_t // explicit Pj_String(pj_str_t &s) { - ptr = s.ptr; - slen = s.slen; + ptr = s.ptr; + slen = s.slen; } // @@ -70,8 +69,8 @@ class Pj_String : public pj_str_t // explicit Pj_String(const pj_str_t &s) { - ptr = (char*)s.ptr; - slen = s.slen; + ptr = (char*)s.ptr; + slen = s.slen; } // @@ -79,7 +78,7 @@ class Pj_String : public pj_str_t // Pj_String(Pj_Pool &pool, const pj_str_t *s) { - set(pool, s); + set(pool, s); } // @@ -87,7 +86,7 @@ class Pj_String : public pj_str_t // Pj_String(Pj_Pool &pool, const Pj_String &rhs) { - set(pool, rhs); + set(pool, rhs); } // @@ -95,8 +94,8 @@ class Pj_String : public pj_str_t // explicit Pj_String(const Pj_String &rhs) { - ptr = rhs.ptr; - slen = rhs.slen; + ptr = rhs.ptr; + slen = rhs.slen; } // @@ -104,7 +103,7 @@ class Pj_String : public pj_str_t // Pj_String(char *str, pj_size_t len) { - set(str, len); + set(str, len); } // @@ -112,7 +111,7 @@ class Pj_String : public pj_str_t // Pj_String(char *begin, char *end) { - pj_strset3(this, begin, end); + pj_strset3(this, begin, end); } // @@ -120,7 +119,7 @@ class Pj_String : public pj_str_t // operator pj_str_t*() { - return this; + return this; } // @@ -128,7 +127,7 @@ class Pj_String : public pj_str_t // operator const pj_str_t*() const { - return this; + return this; } // @@ -136,7 +135,7 @@ class Pj_String : public pj_str_t // pj_size_t length() const { - return pj_strlen(this); + return pj_strlen(this); } // @@ -144,7 +143,7 @@ class Pj_String : public pj_str_t // pj_size_t size() const { - return length(); + return length(); } // @@ -152,7 +151,7 @@ class Pj_String : public pj_str_t // const char *buf() const { - return ptr; + return ptr; } // @@ -160,7 +159,7 @@ class Pj_String : public pj_str_t // void set(char *str) { - pj_strset2(this, str); + pj_strset2(this, str); } // @@ -168,7 +167,7 @@ class Pj_String : public pj_str_t // void set(Pj_Pool &pool, const char *s) { - pj_strdup2(pool, this, s); + pj_strdup2(pool, this, s); } // @@ -176,7 +175,7 @@ class Pj_String : public pj_str_t // void set(pj_str_t *s) { - pj_strassign(this, s); + pj_strassign(this, s); } // @@ -184,7 +183,7 @@ class Pj_String : public pj_str_t // void set(Pj_Pool &pool, const pj_str_t *s) { - pj_strdup(pool, this, s); + pj_strdup(pool, this, s); } // @@ -192,7 +191,7 @@ class Pj_String : public pj_str_t // void set(char *str, pj_size_t len) { - pj_strset(this, str, len); + pj_strset(this, str, len); } // @@ -200,7 +199,7 @@ class Pj_String : public pj_str_t // void set(char *begin, char *end) { - pj_strset3(this, begin, end); + pj_strset3(this, begin, end); } // @@ -208,7 +207,7 @@ class Pj_String : public pj_str_t // void set(Pj_String &rhs) { - pj_strassign(this, &rhs); + pj_strassign(this, &rhs); } // @@ -216,7 +215,7 @@ class Pj_String : public pj_str_t // void set(Pj_Pool &pool, const Pj_String *s) { - pj_strdup(pool, this, s); + pj_strdup(pool, this, s); } // @@ -224,7 +223,7 @@ class Pj_String : public pj_str_t // void set(Pj_Pool &pool, const Pj_String &s) { - pj_strdup(pool, this, &s); + pj_strdup(pool, this, &s); } // @@ -232,7 +231,7 @@ class Pj_String : public pj_str_t // void strcpy(const pj_str_t *s) { - pj_strcpy(this, s); + pj_strcpy(this, s); } // @@ -240,7 +239,7 @@ class Pj_String : public pj_str_t // void strcpy(const Pj_String &rhs) { - pj_strcpy(this, &rhs); + pj_strcpy(this, &rhs); } // @@ -248,7 +247,7 @@ class Pj_String : public pj_str_t // void strcpy(const char *s) { - pj_strcpy2(this, s); + pj_strcpy2(this, s); } // @@ -256,7 +255,7 @@ class Pj_String : public pj_str_t // int strcmp(const char *s) const { - return pj_strcmp2(this, s); + return pj_strcmp2(this, s); } // @@ -264,7 +263,7 @@ class Pj_String : public pj_str_t // int strcmp(const pj_str_t *s) const { - return pj_strcmp(this, s); + return pj_strcmp(this, s); } // @@ -272,7 +271,7 @@ class Pj_String : public pj_str_t // int strcmp(const Pj_String &rhs) const { - return pj_strcmp(this, &rhs); + return pj_strcmp(this, &rhs); } // @@ -280,7 +279,7 @@ class Pj_String : public pj_str_t // int strncmp(const char *s, pj_size_t len) const { - return pj_strncmp2(this, s, len); + return pj_strncmp2(this, s, len); } // @@ -288,7 +287,7 @@ class Pj_String : public pj_str_t // int strncmp(const pj_str_t *s, pj_size_t len) const { - return pj_strncmp(this, s, len); + return pj_strncmp(this, s, len); } // @@ -296,7 +295,7 @@ class Pj_String : public pj_str_t // int strncmp(const Pj_String &rhs, pj_size_t len) const { - return pj_strncmp(this, &rhs, len); + return pj_strncmp(this, &rhs, len); } // @@ -304,7 +303,7 @@ class Pj_String : public pj_str_t // int stricmp(const char *s) const { - return pj_stricmp2(this, s); + return pj_stricmp2(this, s); } // @@ -312,7 +311,7 @@ class Pj_String : public pj_str_t // int stricmp(const pj_str_t *s) const { - return pj_stricmp(this, s); + return pj_stricmp(this, s); } // @@ -320,7 +319,7 @@ class Pj_String : public pj_str_t // int stricmp(const Pj_String &rhs) const { - return stricmp(&rhs); + return stricmp(&rhs); } // @@ -328,7 +327,7 @@ class Pj_String : public pj_str_t // int strnicmp(const char *s, pj_size_t len) const { - return pj_strnicmp2(this, s, len); + return pj_strnicmp2(this, s, len); } // @@ -336,7 +335,7 @@ class Pj_String : public pj_str_t // int strnicmp(const pj_str_t *s, pj_size_t len) const { - return pj_strnicmp(this, s, len); + return pj_strnicmp(this, s, len); } // @@ -344,7 +343,7 @@ class Pj_String : public pj_str_t // int strnicmp(const Pj_String &rhs, pj_size_t len) const { - return strnicmp(&rhs, len); + return strnicmp(&rhs, len); } // @@ -352,7 +351,7 @@ class Pj_String : public pj_str_t // bool operator==(const char *s) const { - return strcmp(s) == 0; + return strcmp(s) == 0; } // @@ -360,7 +359,7 @@ class Pj_String : public pj_str_t // bool operator==(const pj_str_t *s) const { - return strcmp(s) == 0; + return strcmp(s) == 0; } // @@ -368,7 +367,7 @@ class Pj_String : public pj_str_t // bool operator==(const Pj_String &rhs) const { - return pj_strcmp(this, &rhs) == 0; + return pj_strcmp(this, &rhs) == 0; } // @@ -376,8 +375,8 @@ class Pj_String : public pj_str_t // Pj_String& operator=(char *s) { - set(s); - return *this; + set(s); + return *this; } /// @@ -385,9 +384,9 @@ class Pj_String : public pj_str_t // Pj_String& operator=(const Pj_String &rhs) { - ptr = rhs.ptr; - slen = rhs.slen; - return *this; + ptr = rhs.ptr; + slen = rhs.slen; + return *this; } // @@ -395,7 +394,7 @@ class Pj_String : public pj_str_t // char *strchr(int chr) { - return pj_strchr(this, chr); + return pj_strchr(this, chr); } // @@ -403,7 +402,7 @@ class Pj_String : public pj_str_t // char *find(int chr) { - return strchr(chr); + return strchr(chr); } // @@ -411,7 +410,7 @@ class Pj_String : public pj_str_t // void strcat(const Pj_String &rhs) { - pj_strcat(this, &rhs); + pj_strcat(this, &rhs); } // @@ -419,7 +418,7 @@ class Pj_String : public pj_str_t // void ltrim() { - pj_strltrim(this); + pj_strltrim(this); } // @@ -427,7 +426,7 @@ class Pj_String : public pj_str_t // void rtrim() { - pj_strrtrim(this); + pj_strrtrim(this); } // @@ -435,7 +434,7 @@ class Pj_String : public pj_str_t // void trim() { - pj_strtrim(this); + pj_strtrim(this); } // @@ -443,7 +442,7 @@ class Pj_String : public pj_str_t // unsigned long to_ulong() const { - return pj_strtoul(this); + return pj_strtoul(this); } // @@ -464,5 +463,5 @@ class Pj_String : public pj_str_t }; -#endif /* __PJPP_STRING_HPP__ */ +#endif /* __PJPP_STRING_HPP__ */ diff --git a/pjlib/include/pj++/timer.hpp b/pjlib/include/pj++/timer.hpp index 6bab73e211..18116856f2 100644 --- a/pjlib/include/pj++/timer.hpp +++ b/pjlib/include/pj++/timer.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -108,7 +107,7 @@ class Pj_Timer_Heap : public Pj_Object pj_status_t create(Pj_Pool *pool, pj_size_t initial_count) { destroy(); - return pj_timer_heap_create(pool->pool_(), initial_count, &ht_); + return pj_timer_heap_create(pool->pool_(), initial_count, &ht_); } // @@ -127,7 +126,7 @@ class Pj_Timer_Heap : public Pj_Object // pj_timer_heap_t *get_timer_heap() { - return ht_; + return ht_; } // @@ -153,7 +152,7 @@ class Pj_Timer_Heap : public Pj_Object int id) { ent->entry_.id = id; - return pj_timer_heap_schedule(ht_, &ent->entry_, &delay) == 0; + return pj_timer_heap_schedule(ht_, &ent->entry_, &delay) == 0; } // @@ -161,7 +160,7 @@ class Pj_Timer_Heap : public Pj_Object // bool cancel(Pj_Timer_Entry *ent) { - return pj_timer_heap_cancel(ht_, &ent->entry_) == 1; + return pj_timer_heap_cancel(ht_, &ent->entry_) == 1; } // @@ -169,7 +168,7 @@ class Pj_Timer_Heap : public Pj_Object // pj_size_t count() { - return pj_timer_heap_count(ht_); + return pj_timer_heap_count(ht_); } // @@ -178,7 +177,7 @@ class Pj_Timer_Heap : public Pj_Object // bool earliest_time(Pj_Time_Val *t) { - return pj_timer_heap_earliest_time(ht_, t) == PJ_SUCCESS; + return pj_timer_heap_earliest_time(ht_, t) == PJ_SUCCESS; } // @@ -187,12 +186,12 @@ class Pj_Timer_Heap : public Pj_Object // unsigned poll(Pj_Time_Val *next_delay = NULL) { - return pj_timer_heap_poll(ht_, next_delay); + return pj_timer_heap_poll(ht_, next_delay); } private: pj_timer_heap_t *ht_; }; -#endif /* __PJPP_TIMER_HPP__ */ +#endif /* __PJPP_TIMER_HPP__ */ diff --git a/pjlib/include/pj++/tree.hpp b/pjlib/include/pj++/tree.hpp index b28e2990df..745b650d0c 100644 --- a/pjlib/include/pj++/tree.hpp +++ b/pjlib/include/pj++/tree.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,96 +33,96 @@ class PJ_Tree class Node : private pj_rbtree_node { - friend class PJ_Tree; - friend class iterator; - friend class reverse_iterator; + friend class PJ_Tree; + friend class iterator; + friend class reverse_iterator; public: - Node() {} - explicit Node(void *data) { user_data = data; } - void set_user_data(void *data) { user_data = data; } - void *get_user_data() const { return user_data; } + Node() {} + explicit Node(void *data) { user_data = data; } + void set_user_data(void *data) { user_data = data; } + void *get_user_data() const { return user_data; } }; class iterator { public: - iterator() {} - iterator(const iterator &rhs) : tr_(rhs.tr_), nd_(rhs.nd_) {} - iterator(pj_rbtree *tr, pj_rbtree_node *nd) : tr_(tr), nd_(nd) {} - Node *operator*() { return (Node*)nd_; } - bool operator==(const iterator &rhs) const { return tr_==rhs.tr_ && nd_==rhs.nd_; } - iterator &operator=(const iterator &rhs) { tr_=rhs.tr_; nd_=rhs.nd_; return *this; } - void operator++() { nd_=pj_rbtree_next(tr_, nd_); } - void operator--() { nd_=pj_rbtree_prev(tr_, nd_); } + iterator() {} + iterator(const iterator &rhs) : tr_(rhs.tr_), nd_(rhs.nd_) {} + iterator(pj_rbtree *tr, pj_rbtree_node *nd) : tr_(tr), nd_(nd) {} + Node *operator*() { return (Node*)nd_; } + bool operator==(const iterator &rhs) const { return tr_==rhs.tr_ && nd_==rhs.nd_; } + iterator &operator=(const iterator &rhs) { tr_=rhs.tr_; nd_=rhs.nd_; return *this; } + void operator++() { nd_=pj_rbtree_next(tr_, nd_); } + void operator--() { nd_=pj_rbtree_prev(tr_, nd_); } protected: - pj_rbtree *tr_; - pj_rbtree_node *nd_; + pj_rbtree *tr_; + pj_rbtree_node *nd_; }; class reverse_iterator : public iterator { public: - reverse_iterator() {} - reverse_iterator(const reverse_iterator &it) : iterator(it) {} - reverse_iterator(pj_rbtree *t, pj_rbtree_node *n) : iterator(t, n) {} - reverse_iterator &operator=(const reverse_iterator &rhs) { iterator::operator=(rhs); return *this; } - Node *operator*() { return (Node*)nd_; } - bool operator==(const reverse_iterator &rhs) const { return iterator::operator==(rhs); } - void operator++() { nd_=pj_rbtree_prev(tr_, nd_); } - void operator--() { nd_=pj_rbtree_next(tr_, nd_); } + reverse_iterator() {} + reverse_iterator(const reverse_iterator &it) : iterator(it) {} + reverse_iterator(pj_rbtree *t, pj_rbtree_node *n) : iterator(t, n) {} + reverse_iterator &operator=(const reverse_iterator &rhs) { iterator::operator=(rhs); return *this; } + Node *operator*() { return (Node*)nd_; } + bool operator==(const reverse_iterator &rhs) const { return iterator::operator==(rhs); } + void operator++() { nd_=pj_rbtree_prev(tr_, nd_); } + void operator--() { nd_=pj_rbtree_next(tr_, nd_); } }; explicit PJ_Tree(Comp *comp) { pj_rbtree_init(&t_, comp); } iterator begin() { - return iterator(&t_, pj_rbtree_first(&t_)); + return iterator(&t_, pj_rbtree_first(&t_)); } iterator end() { - return iterator(&t_, NULL); + return iterator(&t_, NULL); } reverse_iterator rbegin() { - return reverse_iterator(&t_, pj_rbtree_last(&t_)); + return reverse_iterator(&t_, pj_rbtree_last(&t_)); } reverse_iterator rend() { - return reverse_iterator(&t_, NULL); + return reverse_iterator(&t_, NULL); } bool insert(Node *node) { - return pj_rbtree_insert(&t_, node)==0 ? true : false; + return pj_rbtree_insert(&t_, node)==0 ? true : false; } Node *find(const void *key) { - return (Node*)pj_rbtree_find(&t_, key); + return (Node*)pj_rbtree_find(&t_, key); } Node *erase(Node *node) { - return (Node*)pj_rbtree_erase(&t_, node); + return (Node*)pj_rbtree_erase(&t_, node); } unsigned max_height(Node *node=NULL) { - return pj_rbtree_max_height(&t_, node); + return pj_rbtree_max_height(&t_, node); } unsigned min_height(Node *node=NULL) { - return pj_rbtree_min_height(&t_, node); + return pj_rbtree_min_height(&t_, node); } private: pj_rbtree t_; }; -#endif /* __PJPP_TREE_HPP__ */ +#endif /* __PJPP_TREE_HPP__ */ diff --git a/pjlib/include/pj++/types.hpp b/pjlib/include/pj++/types.hpp index 48dc40b6ec..e34c4edb25 100644 --- a/pjlib/include/pj++/types.hpp +++ b/pjlib/include/pj++/types.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -124,25 +123,25 @@ class Pj_Time_Val : public pj_time_val Pj_Time_Val & operator = (const Pj_Time_Val &rhs) { - sec = rhs.sec; - msec = rhs.msec; - return *this; + sec = rhs.sec; + msec = rhs.msec; + return *this; } Pj_Time_Val & operator += (const Pj_Time_Val &rhs) { - PJ_TIME_VAL_ADD((*this), rhs); - return *this; + PJ_TIME_VAL_ADD((*this), rhs); + return *this; } Pj_Time_Val & operator -= (const Pj_Time_Val &rhs) { - PJ_TIME_VAL_SUB((*this), rhs); - return *this; + PJ_TIME_VAL_SUB((*this), rhs); + return *this; } /* Must include os.hpp to use these, otherwise unresolved in linking */ - inline pj_status_t gettimeofday(); + inline pj_status_t gettimeofday(); inline pj_parsed_time decode(); inline pj_status_t encode(const pj_parsed_time *pt); inline pj_status_t to_gmt(); @@ -160,16 +159,16 @@ class Pj_Time_Val : public pj_time_val // // Macro to declare common object comparison operators. // -#define PJ_DECLARE_OPERATORS(rhs_type) \ - bool operator!=(rhs_type rhs) const { \ - return !operator==(rhs); } \ - bool operator<=(rhs_type rhs) const { \ - return operator<(rhs) || operator==(rhs); } \ - bool operator>(rhs_type rhs) const { \ - return !operator<=(rhs); } \ - bool operator>=(rhs_type rhs) const { \ - return !operator<(rhs); } - - -#endif /* __PJPP_TYPES_HPP__ */ +#define PJ_DECLARE_OPERATORS(rhs_type) \ + bool operator!=(rhs_type rhs) const { \ + return !operator==(rhs); } \ + bool operator<=(rhs_type rhs) const { \ + return operator<(rhs) || operator==(rhs); } \ + bool operator>(rhs_type rhs) const { \ + return !operator<=(rhs); } \ + bool operator>=(rhs_type rhs) const { \ + return !operator<(rhs); } + + +#endif /* __PJPP_TYPES_HPP__ */ diff --git a/pjlib/include/pj/activesock.h b/pjlib/include/pj/activesock.h index 1e72d70f78..5fb2039d35 100644 --- a/pjlib/include/pj/activesock.h +++ b/pjlib/include/pj/activesock.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -59,135 +58,135 @@ typedef struct pj_activesock_cb * This callback is called when a data arrives as the result of * pj_activesock_start_read(). * - * @param asock The active socket. - * @param data The buffer containing the new data, if any. If - * the status argument is non-PJ_SUCCESS, this - * argument may be NULL. - * @param size The length of data in the buffer. - * @param status The status of the read operation. This may contain - * non-PJ_SUCCESS for example when the TCP connection - * has been closed. In this case, the buffer may - * contain left over data from previous callback which - * the application may want to process. - * @param remainder If application wishes to leave some data in the - * buffer (common for TCP applications), it should - * move the remainder data to the front part of the - * buffer and set the remainder length here. The value - * of this parameter will be ignored for datagram - * sockets. + * @param asock The active socket. + * @param data The buffer containing the new data, if any. If + * the status argument is non-PJ_SUCCESS, this + * argument may be NULL. + * @param size The length of data in the buffer. + * @param status The status of the read operation. This may contain + * non-PJ_SUCCESS for example when the TCP connection + * has been closed. In this case, the buffer may + * contain left over data from previous callback which + * the application may want to process. + * @param remainder If application wishes to leave some data in the + * buffer (common for TCP applications), it should + * move the remainder data to the front part of the + * buffer and set the remainder length here. The value + * of this parameter will be ignored for datagram + * sockets. * - * @return PJ_TRUE if further read is desired, and PJ_FALSE - * when application no longer wants to receive data. - * Application may destroy the active socket in the - * callback and return PJ_FALSE here. + * @return PJ_TRUE if further read is desired, and PJ_FALSE + * when application no longer wants to receive data. + * Application may destroy the active socket in the + * callback and return PJ_FALSE here. */ pj_bool_t (*on_data_read)(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder); + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder); /** * This callback is called when a packet arrives as the result of * pj_activesock_start_recvfrom(). * - * @param asock The active socket. - * @param data The buffer containing the packet, if any. If - * the status argument is non-PJ_SUCCESS, this - * argument will be set to NULL. - * @param size The length of packet in the buffer. If - * the status argument is non-PJ_SUCCESS, this - * argument will be set to zero. - * @param src_addr Source address of the packet. - * @param addr_len Length of the source address. - * @param status This contains + * @param asock The active socket. + * @param data The buffer containing the packet, if any. If + * the status argument is non-PJ_SUCCESS, this + * argument will be set to NULL. + * @param size The length of packet in the buffer. If + * the status argument is non-PJ_SUCCESS, this + * argument will be set to zero. + * @param src_addr Source address of the packet. + * @param addr_len Length of the source address. + * @param status This contains * - * @return PJ_TRUE if further read is desired, and PJ_FALSE - * when application no longer wants to receive data. - * Application may destroy the active socket in the - * callback and return PJ_FALSE here. + * @return PJ_TRUE if further read is desired, and PJ_FALSE + * when application no longer wants to receive data. + * Application may destroy the active socket in the + * callback and return PJ_FALSE here. */ pj_bool_t (*on_data_recvfrom)(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status); + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status); /** * This callback is called when data has been sent. * - * @param asock The active socket. - * @param send_key Key associated with the send operation. - * @param sent If value is positive non-zero it indicates the - * number of data sent. When the value is negative, - * it contains the error code which can be retrieved - * by negating the value (i.e. status=-sent). + * @param asock The active socket. + * @param send_key Key associated with the send operation. + * @param sent If value is positive non-zero it indicates the + * number of data sent. When the value is negative, + * it contains the error code which can be retrieved + * by negating the value (i.e. status=-sent). * - * @return Application may destroy the active socket in the - * callback and return PJ_FALSE here. + * @return Application may destroy the active socket in the + * callback and return PJ_FALSE here. */ pj_bool_t (*on_data_sent)(pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent); + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent); /** * This callback is called when new connection arrives as the result * of pj_activesock_start_accept(). If the status of accept operation is * needed use on_accept_complete2 instead of this callback. * - * @param asock The active socket. - * @param newsock The new incoming socket. - * @param src_addr The source address of the connection. - * @param addr_len Length of the source address. + * @param asock The active socket. + * @param newsock The new incoming socket. + * @param src_addr The source address of the connection. + * @param addr_len Length of the source address. * - * @return PJ_TRUE if further accept() is desired, and PJ_FALSE - * when application no longer wants to accept incoming - * connection. Application may destroy the active socket - * in the callback and return PJ_FALSE here. + * @return PJ_TRUE if further accept() is desired, and PJ_FALSE + * when application no longer wants to accept incoming + * connection. Application may destroy the active socket + * in the callback and return PJ_FALSE here. */ pj_bool_t (*on_accept_complete)(pj_activesock_t *asock, - pj_sock_t newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len); + pj_sock_t newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len); /** * This callback is called when new connection arrives as the result * of pj_activesock_start_accept(). * - * @param asock The active socket. - * @param newsock The new incoming socket. - * @param src_addr The source address of the connection. - * @param addr_len Length of the source address. - * @param status The status of the accept operation. This may contain - * non-PJ_SUCCESS for example when the TCP listener is in - * bad state for example on iOS platform after the - * application waking up from background. + * @param asock The active socket. + * @param newsock The new incoming socket. + * @param src_addr The source address of the connection. + * @param addr_len Length of the source address. + * @param status The status of the accept operation. This may contain + * non-PJ_SUCCESS for example when the TCP listener is in + * bad state for example on iOS platform after the + * application waking up from background. * - * @return PJ_TRUE if further accept() is desired, and PJ_FALSE - * when application no longer wants to accept incoming - * connection. Application may destroy the active socket - * in the callback and return PJ_FALSE here. + * @return PJ_TRUE if further accept() is desired, and PJ_FALSE + * when application no longer wants to accept incoming + * connection. Application may destroy the active socket + * in the callback and return PJ_FALSE here. */ pj_bool_t (*on_accept_complete2)(pj_activesock_t *asock, - pj_sock_t newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len, - pj_status_t status); + pj_sock_t newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len, + pj_status_t status); /** * This callback is called when pending connect operation has been * completed. * - * @param asock The active socket. - * @param status The connection result. If connection has been - * successfully established, the status will contain - * PJ_SUCCESS. + * @param asock The active socket. + * @param status The connection result. If connection has been + * successfully established, the status will contain + * PJ_SUCCESS. * - * @return Application may destroy the active socket in the - * callback and return PJ_FALSE here. + * @return Application may destroy the active socket in the + * callback and return PJ_FALSE here. */ pj_bool_t (*on_connect_complete)(pj_activesock_t *asock, - pj_status_t status); + pj_status_t status); } pj_activesock_cb; @@ -253,7 +252,7 @@ typedef struct pj_activesock_cfg /** * Initialize the active socket configuration with the default values. * - * @param cfg The configuration to be initialized. + * @param cfg The configuration to be initialized. */ PJ_DECL(void) pj_activesock_cfg_default(pj_activesock_cfg *cfg); @@ -262,73 +261,73 @@ PJ_DECL(void) pj_activesock_cfg_default(pj_activesock_cfg *cfg); * Create the active socket for the specified socket. This will register * the socket to the specified ioqueue. * - * @param pool Pool to allocate memory from. - * @param sock The socket handle. - * @param sock_type Specify socket type, either pj_SOCK_DGRAM() or - * pj_SOCK_STREAM(). The active socket needs this - * information to handle connection closure for - * connection oriented sockets. - * @param ioqueue The ioqueue to use. - * @param opt Optional settings. When this setting is not specifed, - * the default values will be used. - * @param cb Pointer to structure containing application - * callbacks. - * @param user_data Arbitrary user data to be associated with this - * active socket. - * @param p_asock Pointer to receive the active socket instance. - * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @param pool Pool to allocate memory from. + * @param sock The socket handle. + * @param sock_type Specify socket type, either pj_SOCK_DGRAM() or + * pj_SOCK_STREAM(). The active socket needs this + * information to handle connection closure for + * connection oriented sockets. + * @param ioqueue The ioqueue to use. + * @param opt Optional settings. When this setting is not specifed, + * the default values will be used. + * @param cb Pointer to structure containing application + * callbacks. + * @param user_data Arbitrary user data to be associated with this + * active socket. + * @param p_asock Pointer to receive the active socket instance. + * + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_activesock_create(pj_pool_t *pool, - pj_sock_t sock, - int sock_type, - const pj_activesock_cfg *opt, - pj_ioqueue_t *ioqueue, - const pj_activesock_cb *cb, - void *user_data, - pj_activesock_t **p_asock); + pj_sock_t sock, + int sock_type, + const pj_activesock_cfg *opt, + pj_ioqueue_t *ioqueue, + const pj_activesock_cb *cb, + void *user_data, + pj_activesock_t **p_asock); /** * Create UDP socket descriptor, bind it to the specified address, and * create the active socket for the socket descriptor. * - * @param pool Pool to allocate memory from. - * @param addr Specifies the address family of the socket and the - * address where the socket should be bound to. If - * this argument is NULL, then AF_INET is assumed and - * the socket will be bound to any addresses and port. - * @param ioqueue The ioqueue. - * @param opt Optional settings. When this setting is not specifed, - * the default values will be used. - * @param cb Pointer to structure containing application - * callbacks. - * @param user_data Arbitrary user data to be associated with this - * active socket. - * @param p_asock Pointer to receive the active socket instance. - * @param bound_addr If this argument is specified, it will be filled with - * the bound address on return. - * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @param pool Pool to allocate memory from. + * @param addr Specifies the address family of the socket and the + * address where the socket should be bound to. If + * this argument is NULL, then AF_INET is assumed and + * the socket will be bound to any addresses and port. + * @param ioqueue The ioqueue. + * @param opt Optional settings. When this setting is not specifed, + * the default values will be used. + * @param cb Pointer to structure containing application + * callbacks. + * @param user_data Arbitrary user data to be associated with this + * active socket. + * @param p_asock Pointer to receive the active socket instance. + * @param bound_addr If this argument is specified, it will be filled with + * the bound address on return. + * + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_activesock_create_udp(pj_pool_t *pool, - const pj_sockaddr *addr, - const pj_activesock_cfg *opt, - pj_ioqueue_t *ioqueue, - const pj_activesock_cb *cb, - void *user_data, - pj_activesock_t **p_asock, - pj_sockaddr *bound_addr); + const pj_sockaddr *addr, + const pj_activesock_cfg *opt, + pj_ioqueue_t *ioqueue, + const pj_activesock_cb *cb, + void *user_data, + pj_activesock_t **p_asock, + pj_sockaddr *bound_addr); /** * Close the active socket. This will unregister the socket from the * ioqueue and ultimately close the socket. * - * @param asock The active socket. + * @param asock The active socket. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_activesock_close(pj_activesock_t *asock); @@ -344,12 +343,12 @@ PJ_DECL(pj_status_t) pj_activesock_close(pj_activesock_t *asock); * This API is only available if PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT * is set to non-zero. * - * @param asock The active socket. - * @param val The value of background mode setting. + * @param asock The active socket. + * @param val The value of background mode setting. * */ PJ_DECL(void) pj_activesock_set_iphone_os_bg(pj_activesock_t *asock, - int val); + int val); /** * Enable/disable support for iPhone OS background mode. This setting @@ -361,7 +360,7 @@ PJ_DECL(void) pj_activesock_set_iphone_os_bg(pj_activesock_t *asock, * This API is only available if PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT * is set to non-zero. * - * @param val The value of global background mode setting. + * @param val The value of global background mode setting. * */ PJ_DECL(void) pj_activesock_enable_iphone_os_bg(pj_bool_t val); @@ -372,23 +371,23 @@ PJ_DECL(void) pj_activesock_enable_iphone_os_bg(pj_bool_t val); * inspect this data in the callbacks and associate it with higher * level processing. * - * @param asock The active socket. + * @param asock The active socket. * @param user_data The user data to be associated with the active - * socket. + * socket. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_activesock_set_user_data(pj_activesock_t *asock, - void *user_data); + void *user_data); /** * Retrieve the user data previously associated with this active * socket. * - * @param asock The active socket. + * @param asock The active socket. * - * @return The user data. + * @return The user data. */ PJ_DECL(void*) pj_activesock_get_user_data(pj_activesock_t *asock); @@ -407,131 +406,131 @@ PJ_DECL(void*) pj_activesock_get_user_data(pj_activesock_t *asock); * operations. Further read operations will be done automatically by the * active socket when \a on_data_read() callback returns non-zero. * - * @param asock The active socket. - * @param pool Pool used to allocate buffers for incoming data. + * @param asock The active socket. + * @param pool Pool used to allocate buffers for incoming data. * @param buff_size The size of each buffer, in bytes. - * @param flags Flags to be given to pj_ioqueue_recv(). + * @param flags Flags to be given to pj_ioqueue_recv(). * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_activesock_start_read(pj_activesock_t *asock, - pj_pool_t *pool, - unsigned buff_size, - pj_uint32_t flags); + pj_pool_t *pool, + unsigned buff_size, + pj_uint32_t flags); /** * Same as #pj_activesock_start_read(), except that the application * supplies the buffers for the read operation so that the acive socket * does not have to allocate the buffers. * - * @param asock The active socket. - * @param pool Pool used to allocate buffers for incoming data. + * @param asock The active socket. + * @param pool Pool used to allocate buffers for incoming data. * @param buff_size The size of each buffer, in bytes. * @param readbuf Array of packet buffers, each has buff_size size. - * @param flags Flags to be given to pj_ioqueue_recv(). + * @param flags Flags to be given to pj_ioqueue_recv(). * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_activesock_start_read2(pj_activesock_t *asock, - pj_pool_t *pool, - unsigned buff_size, - void *readbuf[], - pj_uint32_t flags); + pj_pool_t *pool, + unsigned buff_size, + void *readbuf[], + pj_uint32_t flags); /** * Same as pj_activesock_start_read(), except that this function is used * only for datagram sockets, and it will trigger \a on_data_recvfrom() * callback instead. * - * @param asock The active socket. - * @param pool Pool used to allocate buffers for incoming data. + * @param asock The active socket. + * @param pool Pool used to allocate buffers for incoming data. * @param buff_size The size of each buffer, in bytes. - * @param flags Flags to be given to pj_ioqueue_recvfrom(). + * @param flags Flags to be given to pj_ioqueue_recvfrom(). * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_activesock_start_recvfrom(pj_activesock_t *asock, - pj_pool_t *pool, - unsigned buff_size, - pj_uint32_t flags); + pj_pool_t *pool, + unsigned buff_size, + pj_uint32_t flags); /** * Same as #pj_activesock_start_recvfrom() except that the recvfrom() * operation takes the buffer from the argument rather than creating * new ones. * - * @param asock The active socket. - * @param pool Pool used to allocate buffers for incoming data. + * @param asock The active socket. + * @param pool Pool used to allocate buffers for incoming data. * @param buff_size The size of each buffer, in bytes. * @param readbuf Array of packet buffers, each has buff_size size. - * @param flags Flags to be given to pj_ioqueue_recvfrom(). + * @param flags Flags to be given to pj_ioqueue_recvfrom(). * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_activesock_start_recvfrom2(pj_activesock_t *asock, - pj_pool_t *pool, - unsigned buff_size, - void *readbuf[], - pj_uint32_t flags); + pj_pool_t *pool, + unsigned buff_size, + void *readbuf[], + pj_uint32_t flags); /** * Send data using the socket. * - * @param asock The active socket. + * @param asock The active socket. * @param send_key The operation key to send the data, which is useful - * if application wants to submit multiple pending - * send operations and want to track which exact data - * has been sent in the \a on_data_sent() callback. - * @param data The data to be sent. This data must remain valid - * until the data has been sent. - * @param size The size of the data. - * @param flags Flags to be given to pj_ioqueue_send(). - * - * - * @return PJ_SUCCESS if data has been sent immediately, or - * PJ_EPENDING if data cannot be sent immediately. In - * this case the \a on_data_sent() callback will be - * called when data is actually sent. Any other return - * value indicates error condition. + * if application wants to submit multiple pending + * send operations and want to track which exact data + * has been sent in the \a on_data_sent() callback. + * @param data The data to be sent. This data must remain valid + * until the data has been sent. + * @param size The size of the data. + * @param flags Flags to be given to pj_ioqueue_send(). + * + * + * @return PJ_SUCCESS if data has been sent immediately, or + * PJ_EPENDING if data cannot be sent immediately. In + * this case the \a on_data_sent() callback will be + * called when data is actually sent. Any other return + * value indicates error condition. */ PJ_DECL(pj_status_t) pj_activesock_send(pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t *size, - unsigned flags); + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t *size, + unsigned flags); /** * Send datagram using the socket. * - * @param asock The active socket. + * @param asock The active socket. * @param send_key The operation key to send the data, which is useful - * if application wants to submit multiple pending - * send operations and want to track which exact data - * has been sent in the \a on_data_sent() callback. - * @param data The data to be sent. This data must remain valid - * until the data has been sent. - * @param size The size of the data. - * @param flags Flags to be given to pj_ioqueue_send(). - * @param addr The destination address. + * if application wants to submit multiple pending + * send operations and want to track which exact data + * has been sent in the \a on_data_sent() callback. + * @param data The data to be sent. This data must remain valid + * until the data has been sent. + * @param size The size of the data. + * @param flags Flags to be given to pj_ioqueue_send(). + * @param addr The destination address. * @param addr_len The length of the address. * - * @return PJ_SUCCESS if data has been sent immediately, or - * PJ_EPENDING if data cannot be sent immediately. In - * this case the \a on_data_sent() callback will be - * called when data is actually sent. Any other return - * value indicates error condition. + * @return PJ_SUCCESS if data has been sent immediately, or + * PJ_EPENDING if data cannot be sent immediately. In + * this case the \a on_data_sent() callback will be + * called when data is actually sent. Any other return + * value indicates error condition. */ PJ_DECL(pj_status_t) pj_activesock_sendto(pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t *size, - unsigned flags, - const pj_sockaddr_t *addr, - int addr_len); + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t *size, + unsigned flags, + const pj_sockaddr_t *addr, + int addr_len); #if PJ_HAS_TCP /** @@ -546,40 +545,40 @@ PJ_DECL(pj_status_t) pj_activesock_sendto(pj_activesock_t *asock, * operations. Further accept() operations will be done automatically by * the active socket when \a on_accept_complete() callback returns non-zero. * - * @param asock The active socket. - * @param pool Pool used to allocate some internal data for the - * operation. + * @param asock The active socket. + * @param pool Pool used to allocate some internal data for the + * operation. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_activesock_start_accept(pj_activesock_t *asock, - pj_pool_t *pool); + pj_pool_t *pool); /** * Starts asynchronous socket connect() operation for this socket. Once * the connection is done (either successfully or not), the * \a on_connect_complete() callback will be called. * - * @param asock The active socket. - * @param pool The pool to allocate some internal data for the - * operation. + * @param asock The active socket. + * @param pool The pool to allocate some internal data for the + * operation. * @param remaddr Remote address. * @param addr_len Length of the remote address. * - * @return PJ_SUCCESS if connection can be established immediately, - * or PJ_EPENDING if connection cannot be established - * immediately. In this case the \a on_connect_complete() - * callback will be called when connection is complete. - * Any other return value indicates error condition. + * @return PJ_SUCCESS if connection can be established immediately, + * or PJ_EPENDING if connection cannot be established + * immediately. In this case the \a on_connect_complete() + * callback will be called when connection is complete. + * Any other return value indicates error condition. */ PJ_DECL(pj_status_t) pj_activesock_start_connect(pj_activesock_t *asock, - pj_pool_t *pool, - const pj_sockaddr_t *remaddr, - int addr_len); + pj_pool_t *pool, + const pj_sockaddr_t *remaddr, + int addr_len); -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ /** * @} @@ -587,5 +586,5 @@ PJ_DECL(pj_status_t) pj_activesock_start_connect(pj_activesock_t *asock, PJ_END_DECL -#endif /* __PJ_ASYNCSOCK_H__ */ +#endif /* __PJ_ASYNCSOCK_H__ */ diff --git a/pjlib/include/pj/addr_resolv.h b/pjlib/include/pj/addr_resolv.h index 7e89936cca..90f2a57f07 100644 --- a/pjlib/include/pj/addr_resolv.h +++ b/pjlib/include/pj/addr_resolv.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -64,11 +63,11 @@ PJ_BEGIN_DECL /** This structure describes an Internet host address. */ typedef struct pj_hostent { - char *h_name; /**< The official name of the host. */ - char **h_aliases; /**< Aliases list. */ - int h_addrtype; /**< Host address type. */ - int h_length; /**< Length of address. */ - char **h_addr_list; /**< List of addresses. */ + char *h_name; /**< The official name of the host. */ + char **h_aliases; /**< Aliases list. */ + int h_addrtype; /**< Host address type. */ + int h_length; /**< Length of address. */ + char **h_addr_list; /**< List of addresses. */ } pj_hostent; /** Shortcut to h_addr_list[0] */ @@ -79,8 +78,8 @@ typedef struct pj_hostent */ typedef struct pj_addrinfo { - char ai_canonname[PJ_MAX_HOSTNAME]; /**< Canonical name for host*/ - pj_sockaddr ai_addr; /**< Binary address. */ + char ai_canonname[PJ_MAX_HOSTNAME]; /**< Canonical name for host*/ + pj_sockaddr ai_addr; /**< Binary address. */ } pj_addrinfo; @@ -89,14 +88,14 @@ typedef struct pj_addrinfo * For host resolution function that also works with IPv6, please see * #pj_getaddrinfo(). * - * @param name Host name to resolve. Specifying IPv4 address here - * may fail on some platforms (e.g. Windows) - * @param he The pj_hostent structure to be filled. Note that - * the pointers in this structure points to temporary - * variables which value will be reset upon subsequent - * invocation. + * @param name Host name to resolve. Specifying IPv4 address here + * may fail on some platforms (e.g. Windows) + * @param he The pj_hostent structure to be filled. Note that + * the pointers in this structure points to temporary + * variables which value will be reset upon subsequent + * invocation. * - * @return PJ_SUCCESS, or the appropriate error codes. + * @return PJ_SUCCESS, or the appropriate error codes. */ PJ_DECL(pj_status_t) pj_gethostbyname(const pj_str_t *name, pj_hostent *he); @@ -104,14 +103,14 @@ PJ_DECL(pj_status_t) pj_gethostbyname(const pj_str_t *name, pj_hostent *he); /** * Resolve the primary IP address of local host. * - * @param af The desired address family to query. Valid values - * are pj_AF_INET() or pj_AF_INET6(). + * @param af The desired address family to query. Valid values + * are pj_AF_INET() or pj_AF_INET6(). * @param addr On successful resolution, the address family and address - * part of this socket address will be filled up with the host - * IP address, in network byte order. Other parts of the socket - * address are untouched. + * part of this socket address will be filled up with the host + * IP address, in network byte order. Other parts of the socket + * address are untouched. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_gethostip(int af, pj_sockaddr *addr); @@ -119,21 +118,21 @@ PJ_DECL(pj_status_t) pj_gethostip(int af, pj_sockaddr *addr); /** * Get the interface IP address to send data to the specified destination. * - * @param af The desired address family to query. Valid values - * are pj_AF_INET() or pj_AF_INET6(). - * @param dst The destination host. + * @param af The desired address family to query. Valid values + * are pj_AF_INET() or pj_AF_INET6(). + * @param dst The destination host. * @param itf_addr On successful resolution, the address family and address - * part of this socket address will be filled up with the host - * IP address, in network byte order. Other parts of the socket - * address should be ignored. + * part of this socket address will be filled up with the host + * IP address, in network byte order. Other parts of the socket + * address should be ignored. * @param allow_resolve If \a dst may contain hostname (instead of IP - * address), specify whether hostname resolution should - * be performed. If not, default interface address will - * be returned. + * address), specify whether hostname resolution should + * be performed. If not, default interface address will + * be returned. * @param p_dst_addr If not NULL, it will be filled with the IP address of - * the destination host. + * the destination host. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_getipinterface(int af, const pj_str_t *dst, @@ -145,17 +144,17 @@ PJ_DECL(pj_status_t) pj_getipinterface(int af, * Get the IP address of the default interface. Default interface is the * interface of the default route. * - * @param af The desired address family to query. Valid values - * are pj_AF_INET() or pj_AF_INET6(). + * @param af The desired address family to query. Valid values + * are pj_AF_INET() or pj_AF_INET6(). * @param addr On successful resolution, the address family and address - * part of this socket address will be filled up with the host - * IP address, in network byte order. Other parts of the socket - * address are untouched. + * part of this socket address will be filled up with the host + * IP address, in network byte order. Other parts of the socket + * address are untouched. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_getdefaultipinterface(int af, - pj_sockaddr *addr); + pj_sockaddr *addr); /** @@ -164,21 +163,21 @@ PJ_DECL(pj_status_t) pj_getdefaultipinterface(int af, * to be used in creating a socket with which to address the specified * service. * - * @param af The desired address family to query. Valid values - * are pj_AF_INET(), pj_AF_INET6(), or pj_AF_UNSPEC(). - * @param name Descriptive name or an address string, such as host - * name. - * @param count On input, it specifies the number of elements in - * \a ai array. On output, this will be set with the - * number of address informations found for the - * specified name. - * @param ai Array of address info to be filled with the information - * about the host. - * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @param af The desired address family to query. Valid values + * are pj_AF_INET(), pj_AF_INET6(), or pj_AF_UNSPEC(). + * @param name Descriptive name or an address string, such as host + * name. + * @param count On input, it specifies the number of elements in + * \a ai array. On output, this will be set with the + * number of address informations found for the + * specified name. + * @param ai Array of address info to be filled with the information + * about the host. + * + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *name, - unsigned *count, pj_addrinfo ai[]); + unsigned *count, pj_addrinfo ai[]); @@ -186,5 +185,5 @@ PJ_DECL(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *name, PJ_END_DECL -#endif /* __PJ_ADDR_RESOLV_H__ */ +#endif /* __PJ_ADDR_RESOLV_H__ */ diff --git a/pjlib/include/pj/array.h b/pjlib/include/pj/array.h index ca737823e1..71521537ae 100644 --- a/pjlib/include/pj/array.h +++ b/pjlib/include/pj/array.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -41,49 +40,49 @@ PJ_BEGIN_DECL * Insert value to the array at the given position, and rearrange the * remaining nodes after the position. * - * @param array the array. + * @param array the array. * @param elem_size the size of the individual element. - * @param count the CURRENT number of elements in the array. - * @param pos the position where the new element is put. - * @param value the value to copy to the new element. + * @param count the CURRENT number of elements in the array. + * @param pos the position where the new element is put. + * @param value the value to copy to the new element. */ PJ_DECL(void) pj_array_insert( void *array, - unsigned elem_size, - unsigned count, - unsigned pos, - const void *value); + unsigned elem_size, + unsigned count, + unsigned pos, + const void *value); /** * Erase a value from the array at given position, and rearrange the remaining * elements post the erased element. * - * @param array the array. + * @param array the array. * @param elem_size the size of the individual element. - * @param count the current number of elements in the array. - * @param pos the index/position to delete. + * @param count the current number of elements in the array. + * @param pos the index/position to delete. */ PJ_DECL(void) pj_array_erase( void *array, - unsigned elem_size, - unsigned count, - unsigned pos); + unsigned elem_size, + unsigned count, + unsigned pos); /** * Search the first value in the array according to matching function. * - * @param array the array. + * @param array the array. * @param elem_size the individual size of the element. - * @param count the number of elements. + * @param count the number of elements. * @param matching the matching function, which MUST return PJ_SUCCESS if - * the specified element match. + * the specified element match. * @param result the pointer to the value found. * - * @return PJ_SUCCESS if value is found, otherwise the error code. + * @return PJ_SUCCESS if value is found, otherwise the error code. */ PJ_DECL(pj_status_t) pj_array_find( const void *array, - unsigned elem_size, - unsigned count, - pj_status_t (*matching)(const void *value), - void **result); + unsigned elem_size, + unsigned count, + pj_status_t (*matching)(const void *value), + void **result); /** * @} @@ -92,5 +91,5 @@ PJ_DECL(pj_status_t) pj_array_find( const void *array, PJ_END_DECL -#endif /* __PJ_ARRAY_H__ */ +#endif /* __PJ_ARRAY_H__ */ diff --git a/pjlib/include/pj/assert.h b/pjlib/include/pj/assert.h index 01e70022c8..7df702c229 100644 --- a/pjlib/include/pj/assert.h +++ b/pjlib/include/pj/assert.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -43,7 +42,7 @@ * offending statements. * For release build, this macro will not do anything. * - * @param expr The expression to be evaluated. + * @param expr The expression to be evaluated. */ #ifndef pj_assert # define pj_assert(expr) assert(expr) @@ -57,9 +56,9 @@ */ // #if defined(PJ_ENABLE_EXTRA_CHECK) && PJ_ENABLE_EXTRA_CHECK != 0 #define PJ_ASSERT_RETURN(expr,retval) \ - do { \ - if (!(expr)) { pj_assert(expr); return retval; } \ - } while (0) + do { \ + if (!(expr)) { pj_assert(expr); return retval; } \ + } while (0) //#else //# define PJ_ASSERT_RETURN(expr,retval) pj_assert(expr) //#endif @@ -71,15 +70,15 @@ */ //#if defined(PJ_ENABLE_EXTRA_CHECK) && PJ_ENABLE_EXTRA_CHECK != 0 #define PJ_ASSERT_ON_FAIL(expr,exec_on_fail) \ - do { \ - pj_assert(expr); \ - if (!(expr)) exec_on_fail; \ - } while (0) + do { \ + pj_assert(expr); \ + if (!(expr)) exec_on_fail; \ + } while (0) //#else //# define PJ_ASSERT_ON_FAIL(expr,exec_on_fail) pj_assert(expr) //#endif /** @} */ -#endif /* __PJ_ASSERT_H__ */ +#endif /* __PJ_ASSERT_H__ */ diff --git a/pjlib/include/pj/compat/assert.h b/pjlib/include/pj/compat/assert.h index b7c76f3edf..98ef938de5 100644 --- a/pjlib/include/pj/compat/assert.h +++ b/pjlib/include/pj/compat/assert.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -33,5 +32,5 @@ # define assert(expr) #endif -#endif /* __PJ_COMPAT_ASSERT_H__ */ +#endif /* __PJ_COMPAT_ASSERT_H__ */ diff --git a/pjlib/include/pj/compat/cc_armcc.h b/pjlib/include/pj/compat/cc_armcc.h index 16f9654d0a..9acd762b31 100644 --- a/pjlib/include/pj/compat/cc_armcc.h +++ b/pjlib/include/pj/compat/cc_armcc.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,30 +28,30 @@ # error "This file is only for armcc!" #endif -#define PJ_CC_NAME "armcc" +#define PJ_CC_NAME "armcc" #define PJ_CC_VER_1 (__ARMCC_VERSION/100000) #define PJ_CC_VER_2 ((__ARMCC_VERSION%100000)/10000) #define PJ_CC_VER_3 (__ARMCC_VERSION%10000) #ifdef __cplusplus -# define PJ_INLINE_SPECIFIER inline +# define PJ_INLINE_SPECIFIER inline #else -# define PJ_INLINE_SPECIFIER static __inline +# define PJ_INLINE_SPECIFIER static __inline #endif -#define PJ_THREAD_FUNC -#define PJ_NORETURN -#define PJ_ATTR_NORETURN __attribute__ ((noreturn)) -#define PJ_ATTR_MAY_ALIAS __attribute__ ((__may_alias__)) +#define PJ_THREAD_FUNC +#define PJ_NORETURN +#define PJ_ATTR_NORETURN __attribute__ ((noreturn)) +#define PJ_ATTR_MAY_ALIAS __attribute__ ((__may_alias__)) -#define PJ_HAS_INT64 1 +#define PJ_HAS_INT64 1 typedef long long pj_int64_t; typedef unsigned long long pj_uint64_t; -#define PJ_INT64_FMT "L" +#define PJ_INT64_FMT "L" -#define PJ_UNREACHED(x) +#define PJ_UNREACHED(x) -#endif /* __PJ_COMPAT_CC_ARMCC_H__ */ +#endif /* __PJ_COMPAT_CC_ARMCC_H__ */ diff --git a/pjlib/include/pj/compat/cc_codew.h b/pjlib/include/pj/compat/cc_codew.h index 4674a121ba..11c15c8be0 100644 --- a/pjlib/include/pj/compat/cc_codew.h +++ b/pjlib/include/pj/compat/cc_codew.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,28 +28,28 @@ # error "This file is only for Code Warrior!" #endif -#define PJ_CC_NAME "codewarrior" -#define PJ_CC_VER_1 ((__MWERKS__ & 0xF000) >> 12) -#define PJ_CC_VER_2 ((__MWERKS__ & 0x0F00) >> 8) -#define PJ_CC_VER_3 ((__MWERKS__ & 0xFF)) +#define PJ_CC_NAME "codewarrior" +#define PJ_CC_VER_1 ((__MWERKS__ & 0xF000) >> 12) +#define PJ_CC_VER_2 ((__MWERKS__ & 0x0F00) >> 8) +#define PJ_CC_VER_3 ((__MWERKS__ & 0xFF)) -#define PJ_INLINE_SPECIFIER static inline -#define PJ_THREAD_FUNC -#define PJ_NORETURN -#define PJ_ATTR_NORETURN -#define PJ_ATTR_MAY_ALIAS +#define PJ_INLINE_SPECIFIER static inline +#define PJ_THREAD_FUNC +#define PJ_NORETURN +#define PJ_ATTR_NORETURN +#define PJ_ATTR_MAY_ALIAS -#define PJ_HAS_INT64 1 +#define PJ_HAS_INT64 1 typedef long long pj_int64_t; typedef unsigned long long pj_uint64_t; -#define PJ_INT64(val) val##LL -#define PJ_UINT64(val) val##LLU -#define PJ_INT64_FMT "L" +#define PJ_INT64(val) val##LL +#define PJ_UINT64(val) val##LLU +#define PJ_INT64_FMT "L" -#define PJ_UNREACHED(x) +#define PJ_UNREACHED(x) -#endif /* __PJ_COMPAT_CC_CODEW_H__ */ +#endif /* __PJ_COMPAT_CC_CODEW_H__ */ diff --git a/pjlib/include/pj/compat/cc_gcc.h b/pjlib/include/pj/compat/cc_gcc.h index 37f361b0e1..1acf692ccd 100644 --- a/pjlib/include/pj/compat/cc_gcc.h +++ b/pjlib/include/pj/compat/cc_gcc.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,52 +28,52 @@ # error "This file is only for gcc!" #endif -#define PJ_CC_NAME "gcc" -#define PJ_CC_VER_1 __GNUC__ -#define PJ_CC_VER_2 __GNUC_MINOR__ +#define PJ_CC_NAME "gcc" +#define PJ_CC_VER_1 __GNUC__ +#define PJ_CC_VER_2 __GNUC_MINOR__ /* __GNUC_PATCHLEVEL__ doesn't exist in gcc-2.9x.x */ #ifdef __GNUC_PATCHLEVEL__ -# define PJ_CC_VER_3 __GNUC_PATCHLEVEL__ +# define PJ_CC_VER_3 __GNUC_PATCHLEVEL__ #else -# define PJ_CC_VER_3 0 +# define PJ_CC_VER_3 0 #endif -#define PJ_THREAD_FUNC -#define PJ_NORETURN +#define PJ_THREAD_FUNC +#define PJ_NORETURN -#define PJ_HAS_INT64 1 +#define PJ_HAS_INT64 1 #ifdef __STRICT_ANSI__ #include - typedef int64_t pj_int64_t; - typedef uint64_t pj_uint64_t; - #define PJ_INLINE_SPECIFIER static __inline - #define PJ_ATTR_NORETURN - #define PJ_ATTR_MAY_ALIAS + typedef int64_t pj_int64_t; + typedef uint64_t pj_uint64_t; + #define PJ_INLINE_SPECIFIER static __inline + #define PJ_ATTR_NORETURN + #define PJ_ATTR_MAY_ALIAS #else - typedef long long pj_int64_t; - typedef unsigned long long pj_uint64_t; - #define PJ_INLINE_SPECIFIER static inline - #define PJ_ATTR_NORETURN __attribute__ ((noreturn)) - #define PJ_ATTR_MAY_ALIAS __attribute__((__may_alias__)) + typedef long long pj_int64_t; + typedef unsigned long long pj_uint64_t; + #define PJ_INLINE_SPECIFIER static inline + #define PJ_ATTR_NORETURN __attribute__ ((noreturn)) + #define PJ_ATTR_MAY_ALIAS __attribute__((__may_alias__)) #endif -#define PJ_INT64(val) val##LL -#define PJ_UINT64(val) val##ULL -#define PJ_INT64_FMT "L" +#define PJ_INT64(val) val##LL +#define PJ_UINT64(val) val##ULL +#define PJ_INT64_FMT "L" #ifdef __GLIBC__ -# define PJ_HAS_BZERO 1 +# define PJ_HAS_BZERO 1 #endif -#define PJ_UNREACHED(x) +#define PJ_UNREACHED(x) #define PJ_ALIGN_DATA(declaration, alignment) declaration __attribute__((aligned (alignment))) -#endif /* __PJ_COMPAT_CC_GCC_H__ */ +#endif /* __PJ_COMPAT_CC_GCC_H__ */ diff --git a/pjlib/include/pj/compat/cc_gcce.h b/pjlib/include/pj/compat/cc_gcce.h index 06de5be6b4..ea2a214111 100644 --- a/pjlib/include/pj/compat/cc_gcce.h +++ b/pjlib/include/pj/compat/cc_gcce.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,27 +28,27 @@ # error "This file is only for gcce!" #endif -#define PJ_CC_NAME "gcce" -#define PJ_CC_VER_1 __GCCE__ -#define PJ_CC_VER_2 __GCCE_MINOR__ -#define PJ_CC_VER_3 __GCCE_PATCHLEVEL__ +#define PJ_CC_NAME "gcce" +#define PJ_CC_VER_1 __GCCE__ +#define PJ_CC_VER_2 __GCCE_MINOR__ +#define PJ_CC_VER_3 __GCCE_PATCHLEVEL__ -#define PJ_INLINE_SPECIFIER static inline -#define PJ_THREAD_FUNC -#define PJ_NORETURN -#define PJ_ATTR_NORETURN __attribute__ ((noreturn)) -#define PJ_ATTR_MAY_ALIAS __attribute__ ((__may_alias__)) +#define PJ_INLINE_SPECIFIER static inline +#define PJ_THREAD_FUNC +#define PJ_NORETURN +#define PJ_ATTR_NORETURN __attribute__ ((noreturn)) +#define PJ_ATTR_MAY_ALIAS __attribute__ ((__may_alias__)) -#define PJ_HAS_INT64 1 +#define PJ_HAS_INT64 1 typedef long long pj_int64_t; typedef unsigned long long pj_uint64_t; -#define PJ_INT64(val) val##LL -#define PJ_UINT64(val) val##LLU -#define PJ_INT64_FMT "L" +#define PJ_INT64(val) val##LL +#define PJ_UINT64(val) val##LLU +#define PJ_INT64_FMT "L" -#endif /* __PJ_COMPAT_CC_GCCE_H__ */ +#endif /* __PJ_COMPAT_CC_GCCE_H__ */ diff --git a/pjlib/include/pj/compat/cc_msvc.h b/pjlib/include/pj/compat/cc_msvc.h index 659d3a428f..f35e002972 100644 --- a/pjlib/include/pj/compat/cc_msvc.h +++ b/pjlib/include/pj/compat/cc_msvc.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,10 +28,10 @@ # error "This header file is only for Visual C compiler!" #endif -#define PJ_CC_NAME "msvc" -#define PJ_CC_VER_1 (_MSC_VER/100) -#define PJ_CC_VER_2 (_MSC_VER%100) -#define PJ_CC_VER_3 0 +#define PJ_CC_NAME "msvc" +#define PJ_CC_VER_1 (_MSC_VER/100) +#define PJ_CC_VER_2 (_MSC_VER%100) +#define PJ_CC_VER_3 0 /* Disable CRT deprecation warnings. */ #if PJ_CC_VER_1 >= 8 && !defined(_CRT_SECURE_NO_DEPRECATE) @@ -56,33 +55,33 @@ #endif #ifdef __cplusplus -# define PJ_INLINE_SPECIFIER inline +# define PJ_INLINE_SPECIFIER inline #else -# define PJ_INLINE_SPECIFIER static __inline +# define PJ_INLINE_SPECIFIER static __inline #endif #define PJ_EXPORT_DECL_SPECIFIER __declspec(dllexport) -#define PJ_EXPORT_DEF_SPECIFIER __declspec(dllexport) +#define PJ_EXPORT_DEF_SPECIFIER __declspec(dllexport) #define PJ_IMPORT_DECL_SPECIFIER __declspec(dllimport) -#define PJ_THREAD_FUNC -#define PJ_NORETURN __declspec(noreturn) -#define PJ_ATTR_NORETURN -#define PJ_ATTR_MAY_ALIAS +#define PJ_THREAD_FUNC +#define PJ_NORETURN __declspec(noreturn) +#define PJ_ATTR_NORETURN +#define PJ_ATTR_MAY_ALIAS -#define PJ_HAS_INT64 1 +#define PJ_HAS_INT64 1 typedef __int64 pj_int64_t; typedef unsigned __int64 pj_uint64_t; -#define PJ_INT64(val) val##i64 -#define PJ_UINT64(val) val##ui64 -#define PJ_INT64_FMT "I64" +#define PJ_INT64(val) val##i64 +#define PJ_UINT64(val) val##ui64 +#define PJ_INT64_FMT "I64" -#define PJ_UNREACHED(x) +#define PJ_UNREACHED(x) #define PJ_ALIGN_DATA(declaration, alignment) __declspec(align(alignment)) declaration -#endif /* __PJ_COMPAT_CC_MSVC_H__ */ +#endif /* __PJ_COMPAT_CC_MSVC_H__ */ diff --git a/pjlib/include/pj/compat/cc_mwcc.h b/pjlib/include/pj/compat/cc_mwcc.h index 6c9e617ec9..a34461b8be 100644 --- a/pjlib/include/pj/compat/cc_mwcc.h +++ b/pjlib/include/pj/compat/cc_mwcc.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,28 +28,28 @@ # error "This file is only for mwcc!" #endif -#define PJ_CC_NAME "mwcc32sym" -#define PJ_CC_VER_1 1 -#define PJ_CC_VER_2 0 -#define PJ_CC_VER_3 0 +#define PJ_CC_NAME "mwcc32sym" +#define PJ_CC_VER_1 1 +#define PJ_CC_VER_2 0 +#define PJ_CC_VER_3 0 -#define PJ_INLINE_SPECIFIER static inline -#define PJ_THREAD_FUNC -#define PJ_NORETURN -#define PJ_ATTR_NORETURN __attribute__ ((noreturn)) -#define PJ_ATTR_MAY_ALIAS +#define PJ_INLINE_SPECIFIER static inline +#define PJ_THREAD_FUNC +#define PJ_NORETURN +#define PJ_ATTR_NORETURN __attribute__ ((noreturn)) +#define PJ_ATTR_MAY_ALIAS -#define PJ_HAS_INT64 1 +#define PJ_HAS_INT64 1 typedef long long pj_int64_t; typedef unsigned long long pj_uint64_t; -#define PJ_INT64(val) val##LL -#define PJ_UINT64(val) val##LLU -#define PJ_INT64_FMT "L" +#define PJ_INT64(val) val##LL +#define PJ_UINT64(val) val##LLU +#define PJ_INT64_FMT "L" -#define PJ_UNREACHED(x) +#define PJ_UNREACHED(x) -#endif /* __PJ_COMPAT_CC_MWCC_H__ */ +#endif /* __PJ_COMPAT_CC_MWCC_H__ */ diff --git a/pjlib/include/pj/compat/ctype.h b/pjlib/include/pj/compat/ctype.h index ad1bf6721e..a5c222a2bb 100644 --- a/pjlib/include/pj/compat/ctype.h +++ b/pjlib/include/pj/compat/ctype.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,18 +27,18 @@ #if defined(PJ_HAS_CTYPE_H) && PJ_HAS_CTYPE_H != 0 # include #else -# define isalnum(c) (isalpha(c) || isdigit(c)) -# define isalpha(c) (islower(c) || isupper(c)) -# define isascii(c) (((unsigned char)(c))<=0x7f) -# define isdigit(c) ((c)>='0' && (c)<='9') -# define isspace(c) ((c)==' ' || (c)=='\t' ||\ - (c)=='\n' || (c)=='\r' || (c)=='\v') -# define islower(c) ((c)>='a' && (c)<='z') -# define isupper(c) ((c)>='A' && (c)<='Z') -# define isxdigit(c) (isdigit(c) || (tolower(c)>='a'&&tolower(c)<='f')) -# define tolower(c) (((c) >= 'A' && (c) <= 'Z') ? (c)+('a'-'A') : (c)) -# define toupper(c) (((c) >= 'a' && (c) <= 'z') ? (c)-('a'-'A') : (c)) +# define isalnum(c) (isalpha(c) || isdigit(c)) +# define isalpha(c) (islower(c) || isupper(c)) +# define isascii(c) (((unsigned char)(c))<=0x7f) +# define isdigit(c) ((c)>='0' && (c)<='9') +# define isspace(c) ((c)==' ' || (c)=='\t' ||\ + (c)=='\n' || (c)=='\r' || (c)=='\v') +# define islower(c) ((c)>='a' && (c)<='z') +# define isupper(c) ((c)>='A' && (c)<='Z') +# define isxdigit(c) (isdigit(c) || (tolower(c)>='a'&&tolower(c)<='f')) +# define tolower(c) (((c) >= 'A' && (c) <= 'Z') ? (c)+('a'-'A') : (c)) +# define toupper(c) (((c) >= 'a' && (c) <= 'z') ? (c)-('a'-'A') : (c)) #endif -#endif /* __PJ_COMPAT_CTYPE_H__ */ +#endif /* __PJ_COMPAT_CTYPE_H__ */ diff --git a/pjlib/include/pj/compat/errno.h b/pjlib/include/pj/compat/errno.h index 7bbd488900..8ad3cdc3bb 100644 --- a/pjlib/include/pj/compat/errno.h +++ b/pjlib/include/pj/compat/errno.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,14 +24,14 @@ defined(PJ_WIN64) && PJ_WIN64 != 0 typedef unsigned long pj_os_err_type; -# define pj_get_native_os_error() GetLastError() -# define pj_get_native_netos_error() WSAGetLastError() +# define pj_get_native_os_error() GetLastError() +# define pj_get_native_netos_error() WSAGetLastError() #elif defined(PJ_HAS_ERRNO_VAR) && PJ_HAS_ERRNO_VAR!= 0 typedef int pj_os_err_type; -# define pj_get_native_os_error() (errno) -# define pj_get_native_netos_error() (errno) +# define pj_get_native_os_error() (errno) +# define pj_get_native_netos_error() (errno) #else @@ -41,5 +40,5 @@ #endif -#endif /* __PJ_COMPAT_ERRNO_H__ */ +#endif /* __PJ_COMPAT_ERRNO_H__ */ diff --git a/pjlib/include/pj/compat/high_precision.h b/pjlib/include/pj/compat/high_precision.h index e25f35d3ff..e352184357 100644 --- a/pjlib/include/pj/compat/high_precision.h +++ b/pjlib/include/pj/compat/high_precision.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -84,5 +83,5 @@ #endif -#endif /* __PJ_COMPAT_HIGH_PRECISION_H__ */ +#endif /* __PJ_COMPAT_HIGH_PRECISION_H__ */ diff --git a/pjlib/include/pj/compat/limits.h b/pjlib/include/pj/compat/limits.h index 83d78e4839..fe3a14c789 100644 --- a/pjlib/include/pj/compat/limits.h +++ b/pjlib/include/pj/compat/limits.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2017 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2017 George Joseph @@ -33,8 +32,8 @@ # ifdef _MSC_VER # pragma message("limits.h is not found or not supported. LONG_MIN and "\ - "LONG_MAX will be defined by the library in "\ - "pj/compats/limits.h and overridable in config_site.h") + "LONG_MAX will be defined by the library in "\ + "pj/compats/limits.h and overridable in config_site.h") # else # warning "limits.h is not found or not supported. LONG_MIN and LONG_MAX " \ "will be defined by the library in pj/compats/limits.h and "\ diff --git a/pjlib/include/pj/compat/m_alpha.h b/pjlib/include/pj/compat/m_alpha.h index e35a4b9bd6..64fc78aeff 100644 --- a/pjlib/include/pj/compat/m_alpha.h +++ b/pjlib/include/pj/compat/m_alpha.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,12 +24,12 @@ * @brief Describes Alpha processor family specifics. */ -#define PJ_M_NAME "alpha" +#define PJ_M_NAME "alpha" -#define PJ_HAS_PENTIUM 0 -#define PJ_IS_LITTLE_ENDIAN 1 -#define PJ_IS_BIG_ENDIAN 0 +#define PJ_HAS_PENTIUM 0 +#define PJ_IS_LITTLE_ENDIAN 1 +#define PJ_IS_BIG_ENDIAN 0 -#endif /* __PJ_COMPAT_M_ALPHA_H__ */ +#endif /* __PJ_COMPAT_M_ALPHA_H__ */ diff --git a/pjlib/include/pj/compat/m_armv4.h b/pjlib/include/pj/compat/m_armv4.h index 701e45ae41..4ba43e8b67 100644 --- a/pjlib/include/pj/compat/m_armv4.h +++ b/pjlib/include/pj/compat/m_armv4.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,11 +28,11 @@ * This file covers PJ_M_ARMV4 etc. */ -#define PJ_M_NAME "armv4" +#define PJ_M_NAME "armv4" -#define PJ_HAS_PENTIUM 0 -#define PJ_IS_LITTLE_ENDIAN 1 -#define PJ_IS_BIG_ENDIAN 0 +#define PJ_HAS_PENTIUM 0 +#define PJ_IS_LITTLE_ENDIAN 1 +#define PJ_IS_BIG_ENDIAN 0 -#endif /* __PJ_COMPAT_M_ARMV4_H__ */ +#endif /* __PJ_COMPAT_M_ARMV4_H__ */ diff --git a/pjlib/include/pj/compat/m_auto.h.in b/pjlib/include/pj/compat/m_auto.h.in index 79330b9bdd..d5a9ce9038 100644 --- a/pjlib/include/pj/compat/m_auto.h.in +++ b/pjlib/include/pj/compat/m_auto.h.in @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,7 +33,7 @@ */ #ifdef PJ_DARWINOS # ifdef __BIG_ENDIAN__ -# define WORDS_BIGENDIAN 1 +# define WORDS_BIGENDIAN 1 # endif #else /* Endianness, as detected by autoconf */ @@ -42,11 +41,11 @@ #endif #ifdef WORDS_BIGENDIAN -# define PJ_IS_LITTLE_ENDIAN 0 -# define PJ_IS_BIG_ENDIAN 1 +# define PJ_IS_LITTLE_ENDIAN 0 +# define PJ_IS_BIG_ENDIAN 1 #else -# define PJ_IS_LITTLE_ENDIAN 1 -# define PJ_IS_BIG_ENDIAN 0 +# define PJ_IS_LITTLE_ENDIAN 1 +# define PJ_IS_BIG_ENDIAN 0 #endif @@ -54,7 +53,7 @@ #undef PJ_HAS_FLOATING_POINT /* Deprecated */ -#define PJ_HAS_PENTIUM 0 +#define PJ_HAS_PENTIUM 0 -#endif /* __PJ_COMPAT_M_AUTO_H__ */ +#endif /* __PJ_COMPAT_M_AUTO_H__ */ diff --git a/pjlib/include/pj/compat/m_i386.h b/pjlib/include/pj/compat/m_i386.h index f56d100402..ba2795732a 100644 --- a/pjlib/include/pj/compat/m_i386.h +++ b/pjlib/include/pj/compat/m_i386.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,11 +24,11 @@ * @brief Describes Intel i386 family processor specifics. */ -#define PJ_M_NAME "i386" +#define PJ_M_NAME "i386" -#define PJ_HAS_PENTIUM 1 -#define PJ_IS_LITTLE_ENDIAN 1 -#define PJ_IS_BIG_ENDIAN 0 +#define PJ_HAS_PENTIUM 1 +#define PJ_IS_LITTLE_ENDIAN 1 +#define PJ_IS_BIG_ENDIAN 0 -#endif /* __PJ_COMPAT_M_i386_H__ */ +#endif /* __PJ_COMPAT_M_i386_H__ */ diff --git a/pjlib/include/pj/compat/m_m68k.h b/pjlib/include/pj/compat/m_m68k.h index 45a03d32cc..a8fbaf2251 100644 --- a/pjlib/include/pj/compat/m_m68k.h +++ b/pjlib/include/pj/compat/m_m68k.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,11 +24,11 @@ * @brief Describes Motorola m68k family processor specifics. */ -#define PJ_M_NAME "m68k" +#define PJ_M_NAME "m68k" -#define PJ_HAS_PENTIUM 0 -#define PJ_IS_LITTLE_ENDIAN 1 -#define PJ_IS_BIG_ENDIAN 0 +#define PJ_HAS_PENTIUM 0 +#define PJ_IS_LITTLE_ENDIAN 1 +#define PJ_IS_BIG_ENDIAN 0 -#endif /* __PJ_COMPAT_M_M68K_H__ */ +#endif /* __PJ_COMPAT_M_M68K_H__ */ diff --git a/pjlib/include/pj/compat/m_powerpc.h b/pjlib/include/pj/compat/m_powerpc.h index 13a6992f57..b22538c849 100644 --- a/pjlib/include/pj/compat/m_powerpc.h +++ b/pjlib/include/pj/compat/m_powerpc.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,12 +24,12 @@ * @brief Describes PowerPC family processor specifics. */ -#define PJ_M_NAME "powerpc" +#define PJ_M_NAME "powerpc" -#define PJ_HAS_PENTIUM 0 -#define PJ_IS_LITTLE_ENDIAN 0 -#define PJ_IS_BIG_ENDIAN 1 +#define PJ_HAS_PENTIUM 0 +#define PJ_IS_LITTLE_ENDIAN 0 +#define PJ_IS_BIG_ENDIAN 1 -#endif /* __PJ_COMPAT_M_POWERPC_H__ */ +#endif /* __PJ_COMPAT_M_POWERPC_H__ */ diff --git a/pjlib/include/pj/compat/m_sparc.h b/pjlib/include/pj/compat/m_sparc.h index a1508a56fe..9b37caed8e 100644 --- a/pjlib/include/pj/compat/m_sparc.h +++ b/pjlib/include/pj/compat/m_sparc.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,11 +24,11 @@ * @brief Describes SPARC family processor specifics. */ -#define PJ_M_NAME "sparc" +#define PJ_M_NAME "sparc" -#define PJ_HAS_PENTIUM 0 -#define PJ_IS_LITTLE_ENDIAN 0 -#define PJ_IS_BIG_ENDIAN 1 +#define PJ_HAS_PENTIUM 0 +#define PJ_IS_LITTLE_ENDIAN 0 +#define PJ_IS_BIG_ENDIAN 1 -#endif /* __PJ_COMPAT_M_SPARC_H__ */ +#endif /* __PJ_COMPAT_M_SPARC_H__ */ diff --git a/pjlib/include/pj/compat/m_x86_64.h b/pjlib/include/pj/compat/m_x86_64.h index f0edfafa8c..f8c26119ee 100644 --- a/pjlib/include/pj/compat/m_x86_64.h +++ b/pjlib/include/pj/compat/m_x86_64.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,12 +24,12 @@ * @brief Describes 64bit x86 Intel/AMD family processor specifics. */ -#define PJ_M_NAME "x86_64" +#define PJ_M_NAME "x86_64" -#define PJ_HAS_PENTIUM 1 -#define PJ_IS_LITTLE_ENDIAN 1 -#define PJ_IS_BIG_ENDIAN 0 +#define PJ_HAS_PENTIUM 1 +#define PJ_IS_LITTLE_ENDIAN 1 +#define PJ_IS_BIG_ENDIAN 0 -#endif /* __PJ_COMPAT_M_x86_64_H__ */ +#endif /* __PJ_COMPAT_M_x86_64_H__ */ diff --git a/pjlib/include/pj/compat/malloc.h b/pjlib/include/pj/compat/malloc.h index a60b57e2e4..a95e9c228b 100644 --- a/pjlib/include/pj/compat/malloc.h +++ b/pjlib/include/pj/compat/malloc.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,4 +30,4 @@ # include #endif -#endif /* __PJ_COMPAT_MALLOC_H__ */ +#endif /* __PJ_COMPAT_MALLOC_H__ */ diff --git a/pjlib/include/pj/compat/os_auto.h.in b/pjlib/include/pj/compat/os_auto.h.in index d9f28132e3..b37b1aef0c 100644 --- a/pjlib/include/pj/compat/os_auto.h.in +++ b/pjlib/include/pj/compat/os_auto.h.in @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -42,7 +41,7 @@ #undef PJ_ANDROID #if defined(PJ_WIN32_WINNT) && !defined(_WIN32_WINNT) -# define _WIN32_WINNT PJ_WIN32_WINNT +# define _WIN32_WINNT PJ_WIN32_WINNT #endif /* Headers availability */ @@ -96,11 +95,11 @@ /* On these OSes, semaphore feature depends on semaphore.h */ #if defined(PJ_HAS_SEMAPHORE_H) && PJ_HAS_SEMAPHORE_H!=0 -# define PJ_HAS_SEMAPHORE 1 +# define PJ_HAS_SEMAPHORE 1 #elif defined(PJ_WIN32) && PJ_WIN32!=0 -# define PJ_HAS_SEMAPHORE 1 +# define PJ_HAS_SEMAPHORE 1 #else -# define PJ_HAS_SEMAPHORE 0 +# define PJ_HAS_SEMAPHORE 0 #endif /* Do we have pthread_mutexattr_settype()? */ @@ -158,7 +157,7 @@ /* Default threading is enabled, unless it's overridden. */ #ifndef PJ_HAS_THREADS -# define PJ_HAS_THREADS (1) +# define PJ_HAS_THREADS (1) #endif /* Do we need high resolution timer? */ @@ -193,20 +192,20 @@ # include "TargetConditionals.h" # if TARGET_OS_IPHONE -# include "Availability.h" - /* Use CFHost API for pj_getaddrinfo() (see ticket #1246) */ -# ifndef PJ_GETADDRINFO_USE_CFHOST -# define PJ_GETADDRINFO_USE_CFHOST 0 -# endif -# ifdef __IPHONE_4_0 - /* Is multitasking support available? (see ticket #1107) */ -# define PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT 1 - /* Activesock TCP background mode support (VoIP socket). - * Disabled by default, VoIP socket deprecated since iOS 9 and - * on iOS16 using VoIP socket causes app getting killed. - */ -# define PJ_ACTIVESOCK_TCP_IPHONE_OS_BG 0 -# endif +# include "Availability.h" + /* Use CFHost API for pj_getaddrinfo() (see ticket #1246) */ +# ifndef PJ_GETADDRINFO_USE_CFHOST +# define PJ_GETADDRINFO_USE_CFHOST 0 +# endif +# ifdef __IPHONE_4_0 + /* Is multitasking support available? (see ticket #1107) */ +# define PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT 1 + /* Activesock TCP background mode support (VoIP socket). + * Disabled by default, VoIP socket deprecated since iOS 9 and + * on iOS16 using VoIP socket causes app getting killed. + */ +# define PJ_ACTIVESOCK_TCP_IPHONE_OS_BG 0 +# endif # endif #endif @@ -240,5 +239,5 @@ #undef PJ_HAS_PTHREAD_SET_NAME_NP -#endif /* __PJ_COMPAT_OS_AUTO_H__ */ +#endif /* __PJ_COMPAT_OS_AUTO_H__ */ diff --git a/pjlib/include/pj/compat/os_darwinos.h b/pjlib/include/pj/compat/os_darwinos.h index 98435a8b1c..e6687f1fbe 100644 --- a/pjlib/include/pj/compat/os_darwinos.h +++ b/pjlib/include/pj/compat/os_darwinos.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,45 +24,45 @@ * @brief Describes Darwin/MacOSX operating system specifics. */ -#define PJ_OS_NAME "darwin" - -#define PJ_HAS_ARPA_INET_H 1 -#define PJ_HAS_ASSERT_H 1 -#define PJ_HAS_CTYPE_H 1 -#define PJ_HAS_ERRNO_H 1 -#define PJ_HAS_LINUX_SOCKET_H 0 -#define PJ_HAS_MALLOC_H 0 -#define PJ_HAS_NETDB_H 1 -#define PJ_HAS_NETINET_IN_H 1 -#define PJ_HAS_NETINET_TCP_H 1 -#define PJ_HAS_SETJMP_H 1 -#define PJ_HAS_STDARG_H 1 -#define PJ_HAS_STDDEF_H 1 -#define PJ_HAS_STDIO_H 1 -#define PJ_HAS_STDLIB_H 1 -#define PJ_HAS_STRING_H 1 -#define PJ_HAS_SYS_IOCTL_H 1 -#define PJ_HAS_SYS_SELECT_H 1 -#define PJ_HAS_SYS_SOCKET_H 1 -#define PJ_HAS_SYS_TIME_H 1 -#define PJ_HAS_SYS_TIMEB_H 1 -#define PJ_HAS_SYS_TYPES_H 1 -#define PJ_HAS_TIME_H 1 -#define PJ_HAS_UNISTD_H 1 - -#define PJ_HAS_MSWSOCK_H 0 -#define PJ_HAS_WINSOCK_H 0 -#define PJ_HAS_WINSOCK2_H 0 - -#define PJ_HAS_LOCALTIME_R 1 +#define PJ_OS_NAME "darwin" + +#define PJ_HAS_ARPA_INET_H 1 +#define PJ_HAS_ASSERT_H 1 +#define PJ_HAS_CTYPE_H 1 +#define PJ_HAS_ERRNO_H 1 +#define PJ_HAS_LINUX_SOCKET_H 0 +#define PJ_HAS_MALLOC_H 0 +#define PJ_HAS_NETDB_H 1 +#define PJ_HAS_NETINET_IN_H 1 +#define PJ_HAS_NETINET_TCP_H 1 +#define PJ_HAS_SETJMP_H 1 +#define PJ_HAS_STDARG_H 1 +#define PJ_HAS_STDDEF_H 1 +#define PJ_HAS_STDIO_H 1 +#define PJ_HAS_STDLIB_H 1 +#define PJ_HAS_STRING_H 1 +#define PJ_HAS_SYS_IOCTL_H 1 +#define PJ_HAS_SYS_SELECT_H 1 +#define PJ_HAS_SYS_SOCKET_H 1 +#define PJ_HAS_SYS_TIME_H 1 +#define PJ_HAS_SYS_TIMEB_H 1 +#define PJ_HAS_SYS_TYPES_H 1 +#define PJ_HAS_TIME_H 1 +#define PJ_HAS_UNISTD_H 1 + +#define PJ_HAS_MSWSOCK_H 0 +#define PJ_HAS_WINSOCK_H 0 +#define PJ_HAS_WINSOCK2_H 0 + +#define PJ_HAS_LOCALTIME_R 1 /* Is errno a good way to retrieve OS errors? */ -#define PJ_HAS_ERRNO_VAR 1 +#define PJ_HAS_ERRNO_VAR 1 /* Has inet_aton() ? */ -#define PJ_SOCK_HAS_INET_ATON 1 +#define PJ_SOCK_HAS_INET_ATON 1 /* When this macro is set, getsockopt(SOL_SOCKET, SO_ERROR) will return * the status of non-blocking connect() operation. @@ -82,22 +81,22 @@ /* Default threading is enabled, unless it's overridden. */ #ifndef PJ_HAS_THREADS -# define PJ_HAS_THREADS (1) +# define PJ_HAS_THREADS (1) #endif -#define PJ_HAS_HIGH_RES_TIMER 1 -#define PJ_HAS_MALLOC 1 +#define PJ_HAS_HIGH_RES_TIMER 1 +#define PJ_HAS_MALLOC 1 #ifndef PJ_OS_HAS_CHECK_STACK # define PJ_OS_HAS_CHECK_STACK 0 #endif -#define PJ_NATIVE_STRING_IS_UNICODE 0 +#define PJ_NATIVE_STRING_IS_UNICODE 0 -#define PJ_ATOMIC_VALUE_TYPE long +#define PJ_ATOMIC_VALUE_TYPE long /* Set 1 if native sockaddr_in has sin_len member. * Default: 0 */ -#define PJ_SOCKADDR_HAS_LEN 1 +#define PJ_SOCKADDR_HAS_LEN 1 /* * gcc complains that it can not use precompiled header because @@ -106,7 +105,7 @@ * * This changes the default value for Darwin. */ -#define PJ_IOQUEUE_MAX_HANDLES 1024 +#define PJ_IOQUEUE_MAX_HANDLES 1024 /** * If this macro is set, it tells select I/O Queue that select() needs to @@ -118,25 +117,25 @@ * * Default: 0 */ -#define PJ_SELECT_NEEDS_NFDS 0 +#define PJ_SELECT_NEEDS_NFDS 0 /* If 1, use Read/Write mutex emulation for platforms that don't support it */ -#define PJ_EMULATE_RWMUTEX 0 +#define PJ_EMULATE_RWMUTEX 0 /* If 1, pj_thread_create() should enforce the stack size when creating * threads. * Default: 0 (let OS decide the thread's stack size). */ -#define PJ_THREAD_SET_STACK_SIZE 0 +#define PJ_THREAD_SET_STACK_SIZE 0 /* If 1, pj_thread_create() should allocate stack from the pool supplied. * Default: 0 (let OS allocate memory for thread's stack). */ -#define PJ_THREAD_ALLOCATE_STACK 0 +#define PJ_THREAD_ALLOCATE_STACK 0 /* MacOS has had socklen since 10.4 */ -#define PJ_HAS_SOCKLEN_T 1 +#define PJ_HAS_SOCKLEN_T 1 -#endif /* __PJ_COMPAT_OS_DARWINOS_H__ */ +#endif /* __PJ_COMPAT_OS_DARWINOS_H__ */ diff --git a/pjlib/include/pj/compat/os_linux.h b/pjlib/include/pj/compat/os_linux.h index c33f2c19ca..3c1d26ef00 100644 --- a/pjlib/include/pj/compat/os_linux.h +++ b/pjlib/include/pj/compat/os_linux.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,44 +24,44 @@ * @brief Describes Linux operating system specifics. */ -#define PJ_OS_NAME "linux" - -#define PJ_HAS_ARPA_INET_H 1 -#define PJ_HAS_ASSERT_H 1 -#define PJ_HAS_CTYPE_H 1 -#define PJ_HAS_ERRNO_H 1 -#define PJ_HAS_LINUX_SOCKET_H 0 -#define PJ_HAS_MALLOC_H 1 -#define PJ_HAS_NETDB_H 1 -#define PJ_HAS_NETINET_IN_H 1 -#define PJ_HAS_SETJMP_H 1 -#define PJ_HAS_STDARG_H 1 -#define PJ_HAS_STDDEF_H 1 -#define PJ_HAS_STDIO_H 1 -#define PJ_HAS_STDLIB_H 1 -#define PJ_HAS_STRING_H 1 -#define PJ_HAS_SYS_IOCTL_H 1 -#define PJ_HAS_SYS_SELECT_H 1 -#define PJ_HAS_SYS_SOCKET_H 1 -#define PJ_HAS_SYS_TIME_H 1 -#define PJ_HAS_SYS_TIMEB_H 1 -#define PJ_HAS_SYS_TYPES_H 1 -#define PJ_HAS_TIME_H 1 -#define PJ_HAS_UNISTD_H 1 -#define PJ_HAS_SEMAPHORE_H 1 - -#define PJ_HAS_MSWSOCK_H 0 -#define PJ_HAS_WINSOCK_H 0 -#define PJ_HAS_WINSOCK2_H 0 - -#define PJ_HAS_LOCALTIME_R 1 - -#define PJ_SOCK_HAS_INET_ATON 1 +#define PJ_OS_NAME "linux" + +#define PJ_HAS_ARPA_INET_H 1 +#define PJ_HAS_ASSERT_H 1 +#define PJ_HAS_CTYPE_H 1 +#define PJ_HAS_ERRNO_H 1 +#define PJ_HAS_LINUX_SOCKET_H 0 +#define PJ_HAS_MALLOC_H 1 +#define PJ_HAS_NETDB_H 1 +#define PJ_HAS_NETINET_IN_H 1 +#define PJ_HAS_SETJMP_H 1 +#define PJ_HAS_STDARG_H 1 +#define PJ_HAS_STDDEF_H 1 +#define PJ_HAS_STDIO_H 1 +#define PJ_HAS_STDLIB_H 1 +#define PJ_HAS_STRING_H 1 +#define PJ_HAS_SYS_IOCTL_H 1 +#define PJ_HAS_SYS_SELECT_H 1 +#define PJ_HAS_SYS_SOCKET_H 1 +#define PJ_HAS_SYS_TIME_H 1 +#define PJ_HAS_SYS_TIMEB_H 1 +#define PJ_HAS_SYS_TYPES_H 1 +#define PJ_HAS_TIME_H 1 +#define PJ_HAS_UNISTD_H 1 +#define PJ_HAS_SEMAPHORE_H 1 + +#define PJ_HAS_MSWSOCK_H 0 +#define PJ_HAS_WINSOCK_H 0 +#define PJ_HAS_WINSOCK2_H 0 + +#define PJ_HAS_LOCALTIME_R 1 + +#define PJ_SOCK_HAS_INET_ATON 1 /* Set 1 if native sockaddr_in has sin_len member. * Default: 0 */ -#define PJ_SOCKADDR_HAS_LEN 0 +#define PJ_SOCKADDR_HAS_LEN 0 /** * If this macro is set, it tells select I/O Queue that select() needs to @@ -74,11 +73,11 @@ * * Default: 0 */ -#define PJ_SELECT_NEEDS_NFDS 0 +#define PJ_SELECT_NEEDS_NFDS 0 /* Is errno a good way to retrieve OS errors? */ -#define PJ_HAS_ERRNO_VAR 1 +#define PJ_HAS_ERRNO_VAR 1 /* When this macro is set, getsockopt(SOL_SOCKET, SO_ERROR) will return * the status of non-blocking connect() operation. @@ -97,35 +96,35 @@ /* Default threading is enabled, unless it's overridden. */ #ifndef PJ_HAS_THREADS -# define PJ_HAS_THREADS (1) +# define PJ_HAS_THREADS (1) #endif -#define PJ_HAS_HIGH_RES_TIMER 1 +#define PJ_HAS_HIGH_RES_TIMER 1 #define PJ_HAS_MALLOC 1 #ifndef PJ_OS_HAS_CHECK_STACK # define PJ_OS_HAS_CHECK_STACK 0 #endif #define PJ_NATIVE_STRING_IS_UNICODE 0 -#define PJ_ATOMIC_VALUE_TYPE long +#define PJ_ATOMIC_VALUE_TYPE long /* If 1, use Read/Write mutex emulation for platforms that don't support it */ -#define PJ_EMULATE_RWMUTEX 0 +#define PJ_EMULATE_RWMUTEX 0 /* If 1, pj_thread_create() should enforce the stack size when creating * threads. * Default: 0 (let OS decide the thread's stack size). */ -#define PJ_THREAD_SET_STACK_SIZE 0 +#define PJ_THREAD_SET_STACK_SIZE 0 /* If 1, pj_thread_create() should allocate stack from the pool supplied. * Default: 0 (let OS allocate memory for thread's stack). */ -#define PJ_THREAD_ALLOCATE_STACK 0 +#define PJ_THREAD_ALLOCATE_STACK 0 /* Linux has socklen_t */ -#define PJ_HAS_SOCKLEN_T 1 +#define PJ_HAS_SOCKLEN_T 1 -#endif /* __PJ_COMPAT_OS_LINUX_H__ */ +#endif /* __PJ_COMPAT_OS_LINUX_H__ */ diff --git a/pjlib/include/pj/compat/os_palmos.h b/pjlib/include/pj/compat/os_palmos.h index 7d403cd526..083631e477 100644 --- a/pjlib/include/pj/compat/os_palmos.h +++ b/pjlib/include/pj/compat/os_palmos.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,39 +24,39 @@ * @brief Describes PalmOS operating system specifics. */ -#define PJ_OS_NAME "palmos" - -#define PJ_HAS_ARPA_INET_H 0 -#define PJ_HAS_ASSERT_H 1 -#define PJ_HAS_CTYPE_H 1 -#define PJ_HAS_ERRNO_H 0 -#define PJ_HAS_MALLOC_H 1 -#define PJ_HAS_NETDB_H 0 -#define PJ_HAS_NETINET_IN_H 0 -#define PJ_HAS_SETJMP_H 1 -#define PJ_HAS_STDARG_H 1 -#define PJ_HAS_STDDEF_H 1 -#define PJ_HAS_STDIO_H 1 -#define PJ_HAS_STDLIB_H 1 -#define PJ_HAS_STRING_H 1 -#define PJ_HAS_SYS_IOCTL_H 0 -#define PJ_HAS_SYS_SELECT_H 0 -#define PJ_HAS_SYS_SOCKET_H 0 -#define PJ_HAS_SYS_TIMEB_H 0 -#define PJ_HAS_SYS_TYPES_H 1 -#define PJ_HAS_TIME_H 1 -#define PJ_HAS_UNISTD_H 0 - -#define PJ_HAS_MSWSOCK_H 0 -#define PJ_HAS_WINSOCK_H 0 -#define PJ_HAS_WINSOCK2_H 0 - -#define PJ_SOCK_HAS_INET_ATON 0 +#define PJ_OS_NAME "palmos" + +#define PJ_HAS_ARPA_INET_H 0 +#define PJ_HAS_ASSERT_H 1 +#define PJ_HAS_CTYPE_H 1 +#define PJ_HAS_ERRNO_H 0 +#define PJ_HAS_MALLOC_H 1 +#define PJ_HAS_NETDB_H 0 +#define PJ_HAS_NETINET_IN_H 0 +#define PJ_HAS_SETJMP_H 1 +#define PJ_HAS_STDARG_H 1 +#define PJ_HAS_STDDEF_H 1 +#define PJ_HAS_STDIO_H 1 +#define PJ_HAS_STDLIB_H 1 +#define PJ_HAS_STRING_H 1 +#define PJ_HAS_SYS_IOCTL_H 0 +#define PJ_HAS_SYS_SELECT_H 0 +#define PJ_HAS_SYS_SOCKET_H 0 +#define PJ_HAS_SYS_TIMEB_H 0 +#define PJ_HAS_SYS_TYPES_H 1 +#define PJ_HAS_TIME_H 1 +#define PJ_HAS_UNISTD_H 0 + +#define PJ_HAS_MSWSOCK_H 0 +#define PJ_HAS_WINSOCK_H 0 +#define PJ_HAS_WINSOCK2_H 0 + +#define PJ_SOCK_HAS_INET_ATON 0 /* Set 1 if native sockaddr_in has sin_len member. * Default: 0 */ -#define PJ_SOCKADDR_HAS_LEN 0 +#define PJ_SOCKADDR_HAS_LEN 0 /** * If this macro is set, it tells select I/O Queue that select() needs to @@ -69,11 +68,11 @@ * * Default: 0 */ -#define PJ_SELECT_NEEDS_NFDS 0 +#define PJ_SELECT_NEEDS_NFDS 0 /* Is errno a good way to retrieve OS errors? */ -#define PJ_HAS_ERRNO_VAR 0 +#define PJ_HAS_ERRNO_VAR 0 /* When this macro is set, getsockopt(SOL_SOCKET, SO_ERROR) will return * the status of non-blocking connect() operation. @@ -92,28 +91,28 @@ /* Default threading is enabled, unless it's overridden. */ #ifndef PJ_HAS_THREADS -# define PJ_HAS_THREADS (1) +# define PJ_HAS_THREADS (1) #endif -#define PJ_HAS_HIGH_RES_TIMER 1 +#define PJ_HAS_HIGH_RES_TIMER 1 #ifndef PJ_OS_HAS_CHECK_STACK -# define PJ_OS_HAS_CHECK_STACK 0 -#define PJ_NATIVE_STRING_IS_UNICODE 0 +# define PJ_OS_HAS_CHECK_STACK 0 +#define PJ_NATIVE_STRING_IS_UNICODE 0 /* If 1, use Read/Write mutex emulation for platforms that don't support it */ -#define PJ_EMULATE_RWMUTEX 1 +#define PJ_EMULATE_RWMUTEX 1 /* If 1, pj_thread_create() should enforce the stack size when creating * threads. * Default: 0 (let OS decide the thread's stack size). */ -#define PJ_THREAD_SET_STACK_SIZE 0 +#define PJ_THREAD_SET_STACK_SIZE 0 /* If 1, pj_thread_create() should allocate stack from the pool supplied. * Default: 0 (let OS allocate memory for thread's stack). */ -#define PJ_THREAD_ALLOCATE_STACK 0 +#define PJ_THREAD_ALLOCATE_STACK 0 -#endif /* __PJ_COMPAT_OS_PALMOS_H__ */ +#endif /* __PJ_COMPAT_OS_PALMOS_H__ */ diff --git a/pjlib/include/pj/compat/os_rtems.h b/pjlib/include/pj/compat/os_rtems.h index b9a50478ca..7e67816a74 100644 --- a/pjlib/include/pj/compat/os_rtems.h +++ b/pjlib/include/pj/compat/os_rtems.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,45 +30,45 @@ * @brief Describes Linux operating system specifics. */ -#define PJ_OS_NAME "rtems" - -#define PJ_HAS_ARPA_INET_H 1 -#define PJ_HAS_ASSERT_H 1 -#define PJ_HAS_CTYPE_H 1 -#define PJ_HAS_ERRNO_H 1 -#define PJ_HAS_LINUX_SOCKET_H 0 -#define PJ_HAS_MALLOC_H 1 -#define PJ_HAS_NETDB_H 1 -#define PJ_HAS_NETINET_IN_H 1 -#define PJ_HAS_SETJMP_H 1 -#define PJ_HAS_STDARG_H 0 -#define PJ_HAS_STDDEF_H 1 -#define PJ_HAS_STDIO_H 1 -#define PJ_HAS_STDLIB_H 1 -#define PJ_HAS_STRING_H 1 -#define PJ_HAS_SYS_IOCTL_H 1 -#define PJ_HAS_SYS_SELECT_H 1 -#define PJ_HAS_SYS_SOCKET_H 1 -#define PJ_HAS_SYS_TIME_H 1 -#define PJ_HAS_SYS_TIMEB_H 1 -#define PJ_HAS_SYS_TYPES_H 1 -#define PJ_HAS_TIME_H 1 -#define PJ_HAS_UNISTD_H 1 - -#define PJ_HAS_MSWSOCK_H 0 -#define PJ_HAS_WINSOCK_H 0 -#define PJ_HAS_WINSOCK2_H 0 - -#define PJ_SOCK_HAS_INET_ATON 1 +#define PJ_OS_NAME "rtems" + +#define PJ_HAS_ARPA_INET_H 1 +#define PJ_HAS_ASSERT_H 1 +#define PJ_HAS_CTYPE_H 1 +#define PJ_HAS_ERRNO_H 1 +#define PJ_HAS_LINUX_SOCKET_H 0 +#define PJ_HAS_MALLOC_H 1 +#define PJ_HAS_NETDB_H 1 +#define PJ_HAS_NETINET_IN_H 1 +#define PJ_HAS_SETJMP_H 1 +#define PJ_HAS_STDARG_H 0 +#define PJ_HAS_STDDEF_H 1 +#define PJ_HAS_STDIO_H 1 +#define PJ_HAS_STDLIB_H 1 +#define PJ_HAS_STRING_H 1 +#define PJ_HAS_SYS_IOCTL_H 1 +#define PJ_HAS_SYS_SELECT_H 1 +#define PJ_HAS_SYS_SOCKET_H 1 +#define PJ_HAS_SYS_TIME_H 1 +#define PJ_HAS_SYS_TIMEB_H 1 +#define PJ_HAS_SYS_TYPES_H 1 +#define PJ_HAS_TIME_H 1 +#define PJ_HAS_UNISTD_H 1 + +#define PJ_HAS_MSWSOCK_H 0 +#define PJ_HAS_WINSOCK_H 0 +#define PJ_HAS_WINSOCK2_H 0 + +#define PJ_SOCK_HAS_INET_ATON 1 /* Set 1 if native sockaddr_in has sin_len member. * Default: 0 */ -#define PJ_SOCKADDR_HAS_LEN 1 +#define PJ_SOCKADDR_HAS_LEN 1 /* Is errno a good way to retrieve OS errors? */ -#define PJ_HAS_ERRNO_VAR 1 +#define PJ_HAS_ERRNO_VAR 1 /* When this macro is set, getsockopt(SOL_SOCKET, SO_ERROR) will return * the status of non-blocking connect() operation. @@ -86,7 +85,7 @@ * * Default: 0 */ -#define PJ_SELECT_NEEDS_NFDS 1 +#define PJ_SELECT_NEEDS_NFDS 1 /* This value specifies the value set in errno by the OS when a non-blocking * socket recv() can not return immediate daata. @@ -100,20 +99,20 @@ /* Default threading is enabled, unless it's overridden. */ #ifndef PJ_HAS_THREADS -# define PJ_HAS_THREADS (1) +# define PJ_HAS_THREADS (1) #endif -#define PJ_HAS_HIGH_RES_TIMER 1 +#define PJ_HAS_HIGH_RES_TIMER 1 #define PJ_HAS_MALLOC 1 #ifndef PJ_OS_HAS_CHECK_STACK # define PJ_OS_HAS_CHECK_STACK 0 #endif #define PJ_NATIVE_STRING_IS_UNICODE 0 -#define PJ_ATOMIC_VALUE_TYPE int +#define PJ_ATOMIC_VALUE_TYPE int /* If 1, use Read/Write mutex emulation for platforms that don't support it */ -#define PJ_EMULATE_RWMUTEX 1 +#define PJ_EMULATE_RWMUTEX 1 /* Missing socklen_t */ typedef int socklen_t; @@ -130,10 +129,10 @@ typedef int socklen_t; #define PJ_THREAD_ALLOCATE_STACK 1 /* RTEMS has socklen_t (does it? )*/ -#define PJ_HAS_SOCKLEN_T 1 +#define PJ_HAS_SOCKLEN_T 1 -#endif /* __PJ_COMPAT_OS_RTEMS_H__ */ +#endif /* __PJ_COMPAT_OS_RTEMS_H__ */ diff --git a/pjlib/include/pj/compat/os_sunos.h b/pjlib/include/pj/compat/os_sunos.h index 73c132f911..c6bb7fd4cf 100644 --- a/pjlib/include/pj/compat/os_sunos.h +++ b/pjlib/include/pj/compat/os_sunos.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,45 +24,45 @@ * @brief Describes SunOS/Solaris operating system specifics. */ -#define PJ_OS_NAME "sunos" - -#define PJ_HAS_ARPA_INET_H 1 -#define PJ_HAS_ASSERT_H 1 -#define PJ_HAS_CTYPE_H 1 -#define PJ_HAS_ERRNO_H 1 -#define PJ_HAS_LINUX_SOCKET_H 0 -#define PJ_HAS_MALLOC_H 1 -#define PJ_HAS_NETDB_H 1 -#define PJ_HAS_NETINET_IN_H 1 -#define PJ_HAS_SETJMP_H 1 -#define PJ_HAS_STDARG_H 1 -#define PJ_HAS_STDDEF_H 1 -#define PJ_HAS_STDIO_H 1 -#define PJ_HAS_STDLIB_H 1 -#define PJ_HAS_STRING_H 1 -#define PJ_HAS_SYS_IOCTL_H 1 -#define PJ_HAS_SYS_SELECT_H 1 -#define PJ_HAS_SYS_SOCKET_H 1 -#define PJ_HAS_SYS_TIME_H 0 -#define PJ_HAS_SYS_TIMEB_H 1 -#define PJ_HAS_SYS_TYPES_H 1 -#define PJ_HAS_TIME_H 1 -#define PJ_HAS_UNISTD_H 1 - -#define PJ_HAS_MSWSOCK_H 0 -#define PJ_HAS_WINSOCK_H 0 -#define PJ_HAS_WINSOCK2_H 0 - -#define PJ_SOCK_HAS_INET_ATON 0 +#define PJ_OS_NAME "sunos" + +#define PJ_HAS_ARPA_INET_H 1 +#define PJ_HAS_ASSERT_H 1 +#define PJ_HAS_CTYPE_H 1 +#define PJ_HAS_ERRNO_H 1 +#define PJ_HAS_LINUX_SOCKET_H 0 +#define PJ_HAS_MALLOC_H 1 +#define PJ_HAS_NETDB_H 1 +#define PJ_HAS_NETINET_IN_H 1 +#define PJ_HAS_SETJMP_H 1 +#define PJ_HAS_STDARG_H 1 +#define PJ_HAS_STDDEF_H 1 +#define PJ_HAS_STDIO_H 1 +#define PJ_HAS_STDLIB_H 1 +#define PJ_HAS_STRING_H 1 +#define PJ_HAS_SYS_IOCTL_H 1 +#define PJ_HAS_SYS_SELECT_H 1 +#define PJ_HAS_SYS_SOCKET_H 1 +#define PJ_HAS_SYS_TIME_H 0 +#define PJ_HAS_SYS_TIMEB_H 1 +#define PJ_HAS_SYS_TYPES_H 1 +#define PJ_HAS_TIME_H 1 +#define PJ_HAS_UNISTD_H 1 + +#define PJ_HAS_MSWSOCK_H 0 +#define PJ_HAS_WINSOCK_H 0 +#define PJ_HAS_WINSOCK2_H 0 + +#define PJ_SOCK_HAS_INET_ATON 0 /* Set 1 if native sockaddr_in has sin_len member. * Default: 0 */ -#define PJ_SOCKADDR_HAS_LEN 0 +#define PJ_SOCKADDR_HAS_LEN 0 /* Is errno a good way to retrieve OS errors? */ -#define PJ_HAS_ERRNO_VAR 1 +#define PJ_HAS_ERRNO_VAR 1 /* When this macro is set, getsockopt(SOL_SOCKET, SO_ERROR) will return * the status of non-blocking connect() operation. @@ -90,43 +89,43 @@ * * Default: 0 */ -#define PJ_SELECT_NEEDS_NFDS 0 +#define PJ_SELECT_NEEDS_NFDS 0 /* Default threading is enabled, unless it's overridden. */ #ifndef PJ_HAS_THREADS -# define PJ_HAS_THREADS (1) +# define PJ_HAS_THREADS (1) #endif -#define PJ_HAS_HIGH_RES_TIMER 1 -#define PJ_HAS_MALLOC 1 +#define PJ_HAS_HIGH_RES_TIMER 1 +#define PJ_HAS_MALLOC 1 #ifndef PJ_OS_HAS_CHECK_STACK # define PJ_OS_HAS_CHECK_STACK 0 #endif -#define PJ_NATIVE_STRING_IS_UNICODE 0 +#define PJ_NATIVE_STRING_IS_UNICODE 0 -#define PJ_ATOMIC_VALUE_TYPE long +#define PJ_ATOMIC_VALUE_TYPE long /* Get BSD related identifers in Sun's include files */ #define BSD_COMP /* If 1, use Read/Write mutex emulation for platforms that don't support it */ -#define PJ_EMULATE_RWMUTEX 0 +#define PJ_EMULATE_RWMUTEX 0 /* If 1, pj_thread_create() should enforce the stack size when creating * threads. * Default: 0 (let OS decide the thread's stack size). */ -#define PJ_THREAD_SET_STACK_SIZE 0 +#define PJ_THREAD_SET_STACK_SIZE 0 /* If 1, pj_thread_create() should allocate stack from the pool supplied. * Default: 0 (let OS allocate memory for thread's stack). */ -#define PJ_THREAD_ALLOCATE_STACK 0 +#define PJ_THREAD_ALLOCATE_STACK 0 /* SunOS has socklen_t (does it? )*/ -#define PJ_HAS_SOCKLEN_T 1 +#define PJ_HAS_SOCKLEN_T 1 -#endif /* __PJ_COMPAT_OS_SUNOS_H__ */ +#endif /* __PJ_COMPAT_OS_SUNOS_H__ */ diff --git a/pjlib/include/pj/compat/os_symbian.h b/pjlib/include/pj/compat/os_symbian.h index 9f953648d0..7fd5df5e00 100644 --- a/pjlib/include/pj/compat/os_symbian.h +++ b/pjlib/include/pj/compat/os_symbian.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,46 +24,46 @@ * @brief Describes Symbian operating system specifics. */ -#define PJ_OS_NAME "symbian" - -#define PJ_HAS_ARPA_INET_H 1 -#define PJ_HAS_ASSERT_H 1 -#define PJ_HAS_CTYPE_H 1 -#define PJ_HAS_ERRNO_H 1 -#define PJ_HAS_LINUX_SOCKET_H 0 -#define PJ_HAS_MALLOC_H 0 -#define PJ_HAS_NETDB_H 1 -#define PJ_HAS_NETINET_IN_H 1 -#define PJ_HAS_NETINET_TCP_H 0 -#define PJ_HAS_SETJMP_H 1 -#define PJ_HAS_STDARG_H 1 -#define PJ_HAS_STDDEF_H 1 -#define PJ_HAS_STDIO_H 1 -#define PJ_HAS_STDLIB_H 1 -#define PJ_HAS_STRING_H 1 -#define PJ_HAS_NO_SNPRINTF 1 -#define PJ_HAS_SYS_IOCTL_H 1 -#define PJ_HAS_SYS_SELECT_H 0 -#define PJ_HAS_SYS_SOCKET_H 1 -#define PJ_HAS_SYS_TIME_H 1 -#define PJ_HAS_SYS_TIMEB_H 0 -#define PJ_HAS_SYS_TYPES_H 1 -#define PJ_HAS_TIME_H 1 -#define PJ_HAS_UNISTD_H 1 - -#define PJ_HAS_MSWSOCK_H 0 -#define PJ_HAS_WINSOCK_H 0 -#define PJ_HAS_WINSOCK2_H 0 - -#define PJ_SOCK_HAS_INET_ATON 0 +#define PJ_OS_NAME "symbian" + +#define PJ_HAS_ARPA_INET_H 1 +#define PJ_HAS_ASSERT_H 1 +#define PJ_HAS_CTYPE_H 1 +#define PJ_HAS_ERRNO_H 1 +#define PJ_HAS_LINUX_SOCKET_H 0 +#define PJ_HAS_MALLOC_H 0 +#define PJ_HAS_NETDB_H 1 +#define PJ_HAS_NETINET_IN_H 1 +#define PJ_HAS_NETINET_TCP_H 0 +#define PJ_HAS_SETJMP_H 1 +#define PJ_HAS_STDARG_H 1 +#define PJ_HAS_STDDEF_H 1 +#define PJ_HAS_STDIO_H 1 +#define PJ_HAS_STDLIB_H 1 +#define PJ_HAS_STRING_H 1 +#define PJ_HAS_NO_SNPRINTF 1 +#define PJ_HAS_SYS_IOCTL_H 1 +#define PJ_HAS_SYS_SELECT_H 0 +#define PJ_HAS_SYS_SOCKET_H 1 +#define PJ_HAS_SYS_TIME_H 1 +#define PJ_HAS_SYS_TIMEB_H 0 +#define PJ_HAS_SYS_TYPES_H 1 +#define PJ_HAS_TIME_H 1 +#define PJ_HAS_UNISTD_H 1 + +#define PJ_HAS_MSWSOCK_H 0 +#define PJ_HAS_WINSOCK_H 0 +#define PJ_HAS_WINSOCK2_H 0 + +#define PJ_SOCK_HAS_INET_ATON 0 /* Set 1 if native sockaddr_in has sin_len member. * Default: 0 */ -#define PJ_SOCKADDR_HAS_LEN 0 +#define PJ_SOCKADDR_HAS_LEN 0 /* Is errno a good way to retrieve OS errors? */ -#define PJ_HAS_ERRNO_VAR 1 +#define PJ_HAS_ERRNO_VAR 1 /* When this macro is set, getsockopt(SOL_SOCKET, SO_ERROR) will return * the status of non-blocking connect() operation. @@ -81,7 +80,7 @@ * * Default: 0 */ -#define PJ_SELECT_NEEDS_NFDS 0 +#define PJ_SELECT_NEEDS_NFDS 0 /* This value specifies the value set in errno by the OS when a non-blocking * socket recv() can not return immediate daata. @@ -96,12 +95,12 @@ /* * We don't want to use threads in Symbian */ -#define PJ_HAS_THREADS 0 +#define PJ_HAS_THREADS 0 /* * Declare __FD_SETSIZE now before including . -#define __FD_SETSIZE PJ_IOQUEUE_MAX_HANDLES +#define __FD_SETSIZE PJ_IOQUEUE_MAX_HANDLES */ #ifndef NULL @@ -110,58 +109,58 @@ /* Endianness */ #ifndef PJ_IS_LITTLE_ENDIAN -# define PJ_IS_LITTLE_ENDIAN 1 -# define PJ_IS_BIG_ENDIAN 0 +# define PJ_IS_LITTLE_ENDIAN 1 +# define PJ_IS_BIG_ENDIAN 0 #endif /* Doesn't seem to allow more than this */ -#define PJ_IOQUEUE_MAX_HANDLES 8 +#define PJ_IOQUEUE_MAX_HANDLES 8 /* * Override features. */ -#define PJ_HAS_FLOATING_POINT 0 +#define PJ_HAS_FLOATING_POINT 0 #define PJ_HAS_MALLOC 0 -#define PJ_HAS_SEMAPHORE 1 -#define PJ_HAS_EVENT_OBJ 0 -#define PJ_HAS_HIGH_RES_TIMER 1 +#define PJ_HAS_SEMAPHORE 1 +#define PJ_HAS_EVENT_OBJ 0 +#define PJ_HAS_HIGH_RES_TIMER 1 #define PJ_OS_HAS_CHECK_STACK 0 -#define PJ_TERM_HAS_COLOR 0 +#define PJ_TERM_HAS_COLOR 0 #define PJ_NATIVE_STRING_IS_UNICODE 0 -#define PJ_NATIVE_ERR_POSITIVE 0 +#define PJ_NATIVE_ERR_POSITIVE 0 -#define PJ_ATOMIC_VALUE_TYPE int -#define PJ_THREAD_DESC_SIZE 128 +#define PJ_ATOMIC_VALUE_TYPE int +#define PJ_THREAD_DESC_SIZE 128 /* If 1, use Read/Write mutex emulation for platforms that don't support it */ -#define PJ_EMULATE_RWMUTEX 1 +#define PJ_EMULATE_RWMUTEX 1 /* If 1, pj_thread_create() should enforce the stack size when creating * threads. * Default: 0 (let OS decide the thread's stack size). */ -#define PJ_THREAD_SET_STACK_SIZE 0 +#define PJ_THREAD_SET_STACK_SIZE 0 /* If 1, pj_thread_create() should allocate stack from the pool supplied. * Default: 0 (let OS allocate memory for thread's stack). */ -#define PJ_THREAD_ALLOCATE_STACK 0 +#define PJ_THREAD_ALLOCATE_STACK 0 /* Missing socklen_t */ -#define PJ_HAS_SOCKLEN_T 1 +#define PJ_HAS_SOCKLEN_T 1 typedef unsigned int socklen_t; #ifndef __GCCE__ #include #endif -#define PJ_EXPORT_DECL_SPECIFIER IMPORT_C +#define PJ_EXPORT_DECL_SPECIFIER IMPORT_C //#define PJ_EXPORT_DECL_SPECIFIER -#define PJ_EXPORT_DEF_SPECIFIER EXPORT_C -#define PJ_IMPORT_DECL_SPECIFIER IMPORT_C +#define PJ_EXPORT_DEF_SPECIFIER EXPORT_C +#define PJ_IMPORT_DECL_SPECIFIER IMPORT_C -#endif /* __PJ_COMPAT_OS_SYMBIAN_H__ */ +#endif /* __PJ_COMPAT_OS_SYMBIAN_H__ */ diff --git a/pjlib/include/pj/compat/os_win32.h b/pjlib/include/pj/compat/os_win32.h index 5284ecc10e..a16378c212 100644 --- a/pjlib/include/pj/compat/os_win32.h +++ b/pjlib/include/pj/compat/os_win32.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,55 +24,55 @@ * @brief Describes Win32 operating system family specifics. */ -#define PJ_OS_NAME "win32" +#define PJ_OS_NAME "win32" #define WIN32_LEAN_AND_MEAN -#define PJ_WIN32_WINNT 0x0400 +#define PJ_WIN32_WINNT 0x0400 #ifndef _WIN32_WINNT -# define _WIN32_WINNT PJ_WIN32_WINNT +# define _WIN32_WINNT PJ_WIN32_WINNT #endif -#define PJ_HAS_ARPA_INET_H 0 -#define PJ_HAS_ASSERT_H 1 -#define PJ_HAS_CTYPE_H 1 -#define PJ_HAS_ERRNO_H 0 /* Must be zero, otherwise errno_test() fails. */ -#define PJ_HAS_LINUX_SOCKET_H 0 -#define PJ_HAS_MALLOC_H 1 -#define PJ_HAS_NETDB_H 0 -#define PJ_HAS_NETINET_IN_H 0 -#define PJ_HAS_NETINET_TCP_H 0 -#define PJ_HAS_SETJMP_H 1 -#define PJ_HAS_STDARG_H 1 -#define PJ_HAS_STDDEF_H 1 +#define PJ_HAS_ARPA_INET_H 0 +#define PJ_HAS_ASSERT_H 1 +#define PJ_HAS_CTYPE_H 1 +#define PJ_HAS_ERRNO_H 0 /* Must be zero, otherwise errno_test() fails. */ +#define PJ_HAS_LINUX_SOCKET_H 0 +#define PJ_HAS_MALLOC_H 1 +#define PJ_HAS_NETDB_H 0 +#define PJ_HAS_NETINET_IN_H 0 +#define PJ_HAS_NETINET_TCP_H 0 +#define PJ_HAS_SETJMP_H 1 +#define PJ_HAS_STDARG_H 1 +#define PJ_HAS_STDDEF_H 1 #undef PJ_HAS_STDINT_H -#define PJ_HAS_STDIO_H 1 -#define PJ_HAS_STDLIB_H 1 -#define PJ_HAS_STRING_H 1 -#define PJ_HAS_SYS_IOCTL_H 0 -#define PJ_HAS_SYS_SELECT_H 0 -#define PJ_HAS_SYS_SOCKET_H 0 -#define PJ_HAS_SYS_TIME_H 0 -#define PJ_HAS_SYS_TIMEB_H 1 -#define PJ_HAS_SYS_TYPES_H 1 -#define PJ_HAS_TIME_H 1 -#define PJ_HAS_UNISTD_H 0 -#define PJ_HAS_LIMITS_H 1 - -#define PJ_HAS_MSWSOCK_H 1 -#define PJ_HAS_WINSOCK_H 0 -#define PJ_HAS_WINSOCK2_H 1 -#define PJ_HAS_WS2TCPIP_H 1 - -#define PJ_SOCK_HAS_INET_ATON 0 +#define PJ_HAS_STDIO_H 1 +#define PJ_HAS_STDLIB_H 1 +#define PJ_HAS_STRING_H 1 +#define PJ_HAS_SYS_IOCTL_H 0 +#define PJ_HAS_SYS_SELECT_H 0 +#define PJ_HAS_SYS_SOCKET_H 0 +#define PJ_HAS_SYS_TIME_H 0 +#define PJ_HAS_SYS_TIMEB_H 1 +#define PJ_HAS_SYS_TYPES_H 1 +#define PJ_HAS_TIME_H 1 +#define PJ_HAS_UNISTD_H 0 +#define PJ_HAS_LIMITS_H 1 + +#define PJ_HAS_MSWSOCK_H 1 +#define PJ_HAS_WINSOCK_H 0 +#define PJ_HAS_WINSOCK2_H 1 +#define PJ_HAS_WS2TCPIP_H 1 + +#define PJ_SOCK_HAS_INET_ATON 0 /* Set 1 if native sockaddr_in has sin_len member. * Default: 0 */ -#define PJ_SOCKADDR_HAS_LEN 0 +#define PJ_SOCKADDR_HAS_LEN 0 /* Is errno a good way to retrieve OS errors? (No) */ -#define PJ_HAS_ERRNO_VAR 0 +#define PJ_HAS_ERRNO_VAR 0 /* When this macro is set, getsockopt(SOL_SOCKET, SO_ERROR) will return * the status of non-blocking connect() operation. @@ -100,17 +99,17 @@ * * Default: 0 */ -#define PJ_SELECT_NEEDS_NFDS 0 +#define PJ_SELECT_NEEDS_NFDS 0 /* Default threading is enabled, unless it's overridden. */ #ifndef PJ_HAS_THREADS -# define PJ_HAS_THREADS (1) +# define PJ_HAS_THREADS (1) #endif -#define PJ_HAS_HIGH_RES_TIMER 1 -#define PJ_HAS_MALLOC 1 +#define PJ_HAS_HIGH_RES_TIMER 1 +#define PJ_HAS_MALLOC 1 #ifndef PJ_OS_HAS_CHECK_STACK -# define PJ_OS_HAS_CHECK_STACK 1 +# define PJ_OS_HAS_CHECK_STACK 1 #endif #ifdef UNICODE @@ -119,30 +118,30 @@ # define PJ_NATIVE_STRING_IS_UNICODE 0 #endif -#define PJ_ATOMIC_VALUE_TYPE long +#define PJ_ATOMIC_VALUE_TYPE long /* If 1, use Read/Write mutex emulation for platforms that don't support it */ -#define PJ_EMULATE_RWMUTEX 1 +#define PJ_EMULATE_RWMUTEX 1 /* If 1, pj_thread_create() should enforce the stack size when creating * threads. * Default: 0 (let OS decide the thread's stack size). */ -#define PJ_THREAD_SET_STACK_SIZE 0 +#define PJ_THREAD_SET_STACK_SIZE 0 /* If 1, pj_thread_create() should allocate stack from the pool supplied. * Default: 0 (let OS allocate memory for thread's stack). */ -#define PJ_THREAD_ALLOCATE_STACK 0 +#define PJ_THREAD_ALLOCATE_STACK 0 /* Endianness */ #if defined(_M_ARM64) # ifndef PJ_IS_LITTLE_ENDIAN -# define PJ_IS_LITTLE_ENDIAN 1 -# define PJ_IS_BIG_ENDIAN 0 +# define PJ_IS_LITTLE_ENDIAN 1 +# define PJ_IS_BIG_ENDIAN 0 # endif #endif -#endif /* __PJ_COMPAT_OS_WIN32_H__ */ +#endif /* __PJ_COMPAT_OS_WIN32_H__ */ diff --git a/pjlib/include/pj/compat/os_win32_wince.h b/pjlib/include/pj/compat/os_win32_wince.h index 9ae05313e2..6c39d0c904 100644 --- a/pjlib/include/pj/compat/os_win32_wince.h +++ b/pjlib/include/pj/compat/os_win32_wince.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,51 +24,51 @@ * @brief Describes Win32 operating system family specifics. */ -#define PJ_OS_NAME "win32-wince" +#define PJ_OS_NAME "win32-wince" #define WIN32_LEAN_AND_MEAN #define RPC_NO_WINDOWS_H -//#define PJ_WIN32_WINNT 0x0400 -//#define _WIN32_WINNT PJ_WIN32_WINNT - -#define PJ_HAS_ARPA_INET_H 0 -#define PJ_HAS_ASSERT_H 1 -#define PJ_HAS_CTYPE_H 1 -#define PJ_HAS_ERRNO_H 0 /* Must be zero, otherwise errno_test() fails. */ -#define PJ_HAS_LINUX_SOCKET_H 0 -#define PJ_HAS_MALLOC_H 1 -#define PJ_HAS_NETDB_H 0 -#define PJ_HAS_NETINET_IN_H 0 -#define PJ_HAS_NETINET_TCP_H 0 -#define PJ_HAS_SETJMP_H 1 -#define PJ_HAS_STDARG_H 1 -#define PJ_HAS_STDDEF_H 1 -#define PJ_HAS_STDIO_H 1 -#define PJ_HAS_STDLIB_H 1 -#define PJ_HAS_STRING_H 1 -#define PJ_HAS_SYS_IOCTL_H 0 -#define PJ_HAS_SYS_SELECT_H 0 -#define PJ_HAS_SYS_SOCKET_H 0 -#define PJ_HAS_SYS_TIME_H 0 -#define PJ_HAS_SYS_TIMEB_H 0 /* Doesn't have sys/timeb.h */ -#define PJ_HAS_SYS_TYPES_H 0 /* Doesn't have sys/types.h */ -#define PJ_HAS_TIME_H 1 -#define PJ_HAS_UNISTD_H 0 - -#define PJ_HAS_MSWSOCK_H 1 -#define PJ_HAS_WINSOCK_H 0 -#define PJ_HAS_WINSOCK2_H 1 - -#define PJ_SOCK_HAS_INET_ATON 0 +//#define PJ_WIN32_WINNT 0x0400 +//#define _WIN32_WINNT PJ_WIN32_WINNT + +#define PJ_HAS_ARPA_INET_H 0 +#define PJ_HAS_ASSERT_H 1 +#define PJ_HAS_CTYPE_H 1 +#define PJ_HAS_ERRNO_H 0 /* Must be zero, otherwise errno_test() fails. */ +#define PJ_HAS_LINUX_SOCKET_H 0 +#define PJ_HAS_MALLOC_H 1 +#define PJ_HAS_NETDB_H 0 +#define PJ_HAS_NETINET_IN_H 0 +#define PJ_HAS_NETINET_TCP_H 0 +#define PJ_HAS_SETJMP_H 1 +#define PJ_HAS_STDARG_H 1 +#define PJ_HAS_STDDEF_H 1 +#define PJ_HAS_STDIO_H 1 +#define PJ_HAS_STDLIB_H 1 +#define PJ_HAS_STRING_H 1 +#define PJ_HAS_SYS_IOCTL_H 0 +#define PJ_HAS_SYS_SELECT_H 0 +#define PJ_HAS_SYS_SOCKET_H 0 +#define PJ_HAS_SYS_TIME_H 0 +#define PJ_HAS_SYS_TIMEB_H 0 /* Doesn't have sys/timeb.h */ +#define PJ_HAS_SYS_TYPES_H 0 /* Doesn't have sys/types.h */ +#define PJ_HAS_TIME_H 1 +#define PJ_HAS_UNISTD_H 0 + +#define PJ_HAS_MSWSOCK_H 1 +#define PJ_HAS_WINSOCK_H 0 +#define PJ_HAS_WINSOCK2_H 1 + +#define PJ_SOCK_HAS_INET_ATON 0 /* Set 1 if native sockaddr_in has sin_len member. * Default: 0 */ -#define PJ_SOCKADDR_HAS_LEN 0 +#define PJ_SOCKADDR_HAS_LEN 0 /* Is errno a good way to retrieve OS errors? (no) */ -#define PJ_HAS_ERRNO_VAR 0 +#define PJ_HAS_ERRNO_VAR 0 /* When this macro is set, getsockopt(SOL_SOCKET, SO_ERROR) will return * the status of non-blocking connect() operation. @@ -96,51 +95,51 @@ * * Default: 0 */ -#define PJ_SELECT_NEEDS_NFDS 0 +#define PJ_SELECT_NEEDS_NFDS 0 /* Endianness */ #ifndef PJ_IS_LITTLE_ENDIAN -# define PJ_IS_LITTLE_ENDIAN 1 -# define PJ_IS_BIG_ENDIAN 0 +# define PJ_IS_LITTLE_ENDIAN 1 +# define PJ_IS_BIG_ENDIAN 0 #endif /* Default threading is enabled, unless it's overridden. */ #ifndef PJ_HAS_THREADS -# define PJ_HAS_THREADS (1) +# define PJ_HAS_THREADS (1) #endif -#define PJ_HAS_HIGH_RES_TIMER 1 +#define PJ_HAS_HIGH_RES_TIMER 1 #define PJ_HAS_MALLOC 1 -#define PJ_OS_HAS_CHECK_STACK 1 +#define PJ_OS_HAS_CHECK_STACK 1 -#define PJ_ATOMIC_VALUE_TYPE long +#define PJ_ATOMIC_VALUE_TYPE long /* TlsAlloc() error value. */ -#define TLS_OUT_OF_INDEXES 0xFFFFFFFF +#define TLS_OUT_OF_INDEXES 0xFFFFFFFF /* No console. */ -#define PJ_TERM_HAS_COLOR 0 +#define PJ_TERM_HAS_COLOR 0 /* No rdtsc */ -#define PJ_TIMESTAMP_USE_RDTSC 0 +#define PJ_TIMESTAMP_USE_RDTSC 0 /* Native string is Unicode. */ #define PJ_NATIVE_STRING_IS_UNICODE 1 /* If 1, use Read/Write mutex emulation for platforms that don't support it */ -#define PJ_EMULATE_RWMUTEX 1 +#define PJ_EMULATE_RWMUTEX 1 /* If 1, pj_thread_create() should enforce the stack size when creating * threads. * Default: 0 (let OS decide the thread's stack size). */ -#define PJ_THREAD_SET_STACK_SIZE 0 +#define PJ_THREAD_SET_STACK_SIZE 0 /* If 1, pj_thread_create() should allocate stack from the pool supplied. * Default: 0 (let OS allocate memory for thread's stack). */ -#define PJ_THREAD_ALLOCATE_STACK 0 +#define PJ_THREAD_ALLOCATE_STACK 0 -#endif /* __PJ_COMPAT_OS_WIN32_WINCE_H__ */ +#endif /* __PJ_COMPAT_OS_WIN32_WINCE_H__ */ diff --git a/pjlib/include/pj/compat/os_winphone8.h b/pjlib/include/pj/compat/os_winphone8.h index a7c26e9cbe..5ec3176d01 100644 --- a/pjlib/include/pj/compat/os_winphone8.h +++ b/pjlib/include/pj/compat/os_winphone8.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,54 +24,54 @@ * @brief Describes Windows Phone 8 operating system family specifics. */ -#define PJ_OS_NAME "winphone8" +#define PJ_OS_NAME "winphone8" #define WIN32_LEAN_AND_MEAN #define RPC_NO_WINDOWS_H -#define PJ_WIN32_WINNT 0x0602 /*_WIN32_WINNT_WIN8*/ +#define PJ_WIN32_WINNT 0x0602 /*_WIN32_WINNT_WIN8*/ #ifdef _WIN32_WINNT #undef _WIN32_WINNT -#define _WIN32_WINNT PJ_WIN32_WINNT +#define _WIN32_WINNT PJ_WIN32_WINNT #endif -#define PJ_HAS_ARPA_INET_H 0 -#define PJ_HAS_ASSERT_H 1 -#define PJ_HAS_CTYPE_H 1 -#define PJ_HAS_ERRNO_H 0 /* Must be zero, otherwise errno_test() fails. */ -#define PJ_HAS_LINUX_SOCKET_H 0 -#define PJ_HAS_MALLOC_H 1 -#define PJ_HAS_NETDB_H 0 -#define PJ_HAS_NETINET_IN_H 0 -#define PJ_HAS_NETINET_TCP_H 0 -#define PJ_HAS_SETJMP_H 1 -#define PJ_HAS_STDARG_H 1 -#define PJ_HAS_STDDEF_H 1 -#define PJ_HAS_STDIO_H 1 -#define PJ_HAS_STDLIB_H 1 -#define PJ_HAS_STRING_H 1 -#define PJ_HAS_SYS_IOCTL_H 0 -#define PJ_HAS_SYS_SELECT_H 0 -#define PJ_HAS_SYS_SOCKET_H 0 -#define PJ_HAS_SYS_TIME_H 0 -#define PJ_HAS_SYS_TIMEB_H 0 /* Doesn't have sys/timeb.h */ -#define PJ_HAS_SYS_TYPES_H 0 /* Doesn't have sys/types.h */ -#define PJ_HAS_TIME_H 1 -#define PJ_HAS_UNISTD_H 0 - -#define PJ_HAS_MSWSOCK_H 1 -#define PJ_HAS_WINSOCK_H 0 -#define PJ_HAS_WINSOCK2_H 1 - -#define PJ_SOCK_HAS_INET_ATON 0 +#define PJ_HAS_ARPA_INET_H 0 +#define PJ_HAS_ASSERT_H 1 +#define PJ_HAS_CTYPE_H 1 +#define PJ_HAS_ERRNO_H 0 /* Must be zero, otherwise errno_test() fails. */ +#define PJ_HAS_LINUX_SOCKET_H 0 +#define PJ_HAS_MALLOC_H 1 +#define PJ_HAS_NETDB_H 0 +#define PJ_HAS_NETINET_IN_H 0 +#define PJ_HAS_NETINET_TCP_H 0 +#define PJ_HAS_SETJMP_H 1 +#define PJ_HAS_STDARG_H 1 +#define PJ_HAS_STDDEF_H 1 +#define PJ_HAS_STDIO_H 1 +#define PJ_HAS_STDLIB_H 1 +#define PJ_HAS_STRING_H 1 +#define PJ_HAS_SYS_IOCTL_H 0 +#define PJ_HAS_SYS_SELECT_H 0 +#define PJ_HAS_SYS_SOCKET_H 0 +#define PJ_HAS_SYS_TIME_H 0 +#define PJ_HAS_SYS_TIMEB_H 0 /* Doesn't have sys/timeb.h */ +#define PJ_HAS_SYS_TYPES_H 0 /* Doesn't have sys/types.h */ +#define PJ_HAS_TIME_H 1 +#define PJ_HAS_UNISTD_H 0 + +#define PJ_HAS_MSWSOCK_H 1 +#define PJ_HAS_WINSOCK_H 0 +#define PJ_HAS_WINSOCK2_H 1 + +#define PJ_SOCK_HAS_INET_ATON 0 /* Set 1 if native sockaddr_in has sin_len member. * Default: 0 */ -#define PJ_SOCKADDR_HAS_LEN 0 +#define PJ_SOCKADDR_HAS_LEN 0 /* Is errno a good way to retrieve OS errors? (no) */ -#define PJ_HAS_ERRNO_VAR 0 +#define PJ_HAS_ERRNO_VAR 0 /* When this macro is set, getsockopt(SOL_SOCKET, SO_ERROR) will return * the status of non-blocking connect() operation. @@ -99,52 +98,52 @@ * * Default: 0 */ -#define PJ_SELECT_NEEDS_NFDS 0 +#define PJ_SELECT_NEEDS_NFDS 0 /* Endianness */ #ifndef PJ_IS_LITTLE_ENDIAN -# define PJ_IS_LITTLE_ENDIAN 1 -# define PJ_IS_BIG_ENDIAN 0 +# define PJ_IS_LITTLE_ENDIAN 1 +# define PJ_IS_BIG_ENDIAN 0 #endif /* Default threading is enabled, unless it's overridden. */ #ifndef PJ_HAS_THREADS -# define PJ_HAS_THREADS (1) +# define PJ_HAS_THREADS (1) #endif -#define PJ_HAS_HIGH_RES_TIMER 1 +#define PJ_HAS_HIGH_RES_TIMER 1 #define PJ_HAS_MALLOC 1 -#define PJ_OS_HAS_CHECK_STACK 1 +#define PJ_OS_HAS_CHECK_STACK 1 -#define PJ_ATOMIC_VALUE_TYPE long +#define PJ_ATOMIC_VALUE_TYPE long /* No console. */ -#define PJ_TERM_HAS_COLOR 0 +#define PJ_TERM_HAS_COLOR 0 /* TlsAlloc() error value. */ #ifndef TLS_OUT_OF_INDEXES - #define TLS_OUT_OF_INDEXES 0xFFFFFFFF + #define TLS_OUT_OF_INDEXES 0xFFFFFFFF #endif /* No rdtsc */ -#define PJ_TIMESTAMP_USE_RDTSC 0 +#define PJ_TIMESTAMP_USE_RDTSC 0 /* Native string is Unicode. */ #define PJ_NATIVE_STRING_IS_UNICODE 1 /* If 1, use Read/Write mutex emulation for platforms that don't support it */ -#define PJ_EMULATE_RWMUTEX 1 +#define PJ_EMULATE_RWMUTEX 1 /* If 1, pj_thread_create() should enforce the stack size when creating * threads. * Default: 0 (let OS decide the thread's stack size). */ -#define PJ_THREAD_SET_STACK_SIZE 0 +#define PJ_THREAD_SET_STACK_SIZE 0 /* If 1, pj_thread_create() should allocate stack from the pool supplied. * Default: 0 (let OS allocate memory for thread's stack). */ -#define PJ_THREAD_ALLOCATE_STACK 0 +#define PJ_THREAD_ALLOCATE_STACK 0 -#endif /* __PJ_COMPAT_OS_WINPHONE8_H__ */ +#endif /* __PJ_COMPAT_OS_WINPHONE8_H__ */ diff --git a/pjlib/include/pj/compat/os_winuwp.h b/pjlib/include/pj/compat/os_winuwp.h index b14b6b6847..6565613e85 100644 --- a/pjlib/include/pj/compat/os_winuwp.h +++ b/pjlib/include/pj/compat/os_winuwp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,55 +24,55 @@ * @brief Describes Windows UWP operating system family specifics. */ -#define PJ_OS_NAME "winuwp" +#define PJ_OS_NAME "winuwp" #define WIN32_LEAN_AND_MEAN #define RPC_NO_WINDOWS_H -#define PJ_WIN32_WINNT 0x0602 /*_WIN32_WINNT_WIN8*/ +#define PJ_WIN32_WINNT 0x0602 /*_WIN32_WINNT_WIN8*/ #ifdef _WIN32_WINNT #undef _WIN32_WINNT -#define _WIN32_WINNT PJ_WIN32_WINNT +#define _WIN32_WINNT PJ_WIN32_WINNT #endif -#define PJ_HAS_ARPA_INET_H 0 -#define PJ_HAS_ASSERT_H 1 -#define PJ_HAS_CTYPE_H 1 -#define PJ_HAS_ERRNO_H 0 /* Must be zero, otherwise errno_test() fails. */ -#define PJ_HAS_LINUX_SOCKET_H 0 -#define PJ_HAS_MALLOC_H 1 -#define PJ_HAS_NETDB_H 0 -#define PJ_HAS_NETINET_IN_H 0 -#define PJ_HAS_NETINET_TCP_H 0 -#define PJ_HAS_SETJMP_H 1 -#define PJ_HAS_STDARG_H 1 -#define PJ_HAS_STDDEF_H 1 -#define PJ_HAS_STDIO_H 1 -#define PJ_HAS_STDLIB_H 1 -#define PJ_HAS_STRING_H 1 -#define PJ_HAS_SYS_IOCTL_H 0 -#define PJ_HAS_SYS_SELECT_H 0 -#define PJ_HAS_SYS_SOCKET_H 0 -#define PJ_HAS_SYS_TIME_H 0 -#define PJ_HAS_SYS_TIMEB_H 0 /* Doesn't have sys/timeb.h */ -#define PJ_HAS_SYS_TYPES_H 0 /* Doesn't have sys/types.h */ -#define PJ_HAS_TIME_H 1 -#define PJ_HAS_UNISTD_H 0 +#define PJ_HAS_ARPA_INET_H 0 +#define PJ_HAS_ASSERT_H 1 +#define PJ_HAS_CTYPE_H 1 +#define PJ_HAS_ERRNO_H 0 /* Must be zero, otherwise errno_test() fails. */ +#define PJ_HAS_LINUX_SOCKET_H 0 +#define PJ_HAS_MALLOC_H 1 +#define PJ_HAS_NETDB_H 0 +#define PJ_HAS_NETINET_IN_H 0 +#define PJ_HAS_NETINET_TCP_H 0 +#define PJ_HAS_SETJMP_H 1 +#define PJ_HAS_STDARG_H 1 +#define PJ_HAS_STDDEF_H 1 +#define PJ_HAS_STDIO_H 1 +#define PJ_HAS_STDLIB_H 1 +#define PJ_HAS_STRING_H 1 +#define PJ_HAS_SYS_IOCTL_H 0 +#define PJ_HAS_SYS_SELECT_H 0 +#define PJ_HAS_SYS_SOCKET_H 0 +#define PJ_HAS_SYS_TIME_H 0 +#define PJ_HAS_SYS_TIMEB_H 0 /* Doesn't have sys/timeb.h */ +#define PJ_HAS_SYS_TYPES_H 0 /* Doesn't have sys/types.h */ +#define PJ_HAS_TIME_H 1 +#define PJ_HAS_UNISTD_H 0 #define PJ_HAS_LIMITS_H 1 -#define PJ_HAS_MSWSOCK_H 1 -#define PJ_HAS_WINSOCK_H 0 -#define PJ_HAS_WINSOCK2_H 1 +#define PJ_HAS_MSWSOCK_H 1 +#define PJ_HAS_WINSOCK_H 0 +#define PJ_HAS_WINSOCK2_H 1 -#define PJ_SOCK_HAS_INET_ATON 0 +#define PJ_SOCK_HAS_INET_ATON 0 /* Set 1 if native sockaddr_in has sin_len member. * Default: 0 */ -#define PJ_SOCKADDR_HAS_LEN 0 +#define PJ_SOCKADDR_HAS_LEN 0 /* Is errno a good way to retrieve OS errors? (no) */ -#define PJ_HAS_ERRNO_VAR 0 +#define PJ_HAS_ERRNO_VAR 0 /* When this macro is set, getsockopt(SOL_SOCKET, SO_ERROR) will return * the status of non-blocking connect() operation. @@ -100,50 +99,50 @@ * * Default: 0 */ -#define PJ_SELECT_NEEDS_NFDS 0 +#define PJ_SELECT_NEEDS_NFDS 0 /* Endianness */ #ifndef PJ_IS_LITTLE_ENDIAN -# define PJ_IS_LITTLE_ENDIAN 1 -# define PJ_IS_BIG_ENDIAN 0 +# define PJ_IS_LITTLE_ENDIAN 1 +# define PJ_IS_BIG_ENDIAN 0 #endif /* Default threading is enabled, unless it's overridden. */ #ifndef PJ_HAS_THREADS -# define PJ_HAS_THREADS (1) +# define PJ_HAS_THREADS (1) #endif -#define PJ_HAS_HIGH_RES_TIMER 1 +#define PJ_HAS_HIGH_RES_TIMER 1 #define PJ_HAS_MALLOC 1 #ifndef PJ_OS_HAS_CHECK_STACK # define PJ_OS_HAS_CHECK_STACK 0 #endif -#define PJ_ATOMIC_VALUE_TYPE long +#define PJ_ATOMIC_VALUE_TYPE long /* No console. */ -#define PJ_TERM_HAS_COLOR 0 +#define PJ_TERM_HAS_COLOR 0 /* No rdtsc */ -#define PJ_TIMESTAMP_USE_RDTSC 0 +#define PJ_TIMESTAMP_USE_RDTSC 0 /* Native string is Unicode. */ #define PJ_NATIVE_STRING_IS_UNICODE 1 /* If 1, use Read/Write mutex emulation for platforms that don't support it */ -#define PJ_EMULATE_RWMUTEX 1 +#define PJ_EMULATE_RWMUTEX 1 /* If 1, pj_thread_create() should enforce the stack size when creating * threads. * Default: 0 (let OS decide the thread's stack size). */ -#define PJ_THREAD_SET_STACK_SIZE 0 +#define PJ_THREAD_SET_STACK_SIZE 0 /* If 1, pj_thread_create() should allocate stack from the pool supplied. * Default: 0 (let OS allocate memory for thread's stack). */ -#define PJ_THREAD_ALLOCATE_STACK 0 +#define PJ_THREAD_ALLOCATE_STACK 0 -#endif /* __PJ_COMPAT_OS_UWP_H__ */ +#endif /* __PJ_COMPAT_OS_UWP_H__ */ diff --git a/pjlib/include/pj/compat/rand.h b/pjlib/include/pj/compat/rand.h index 7e7782bd2b..aac7bbf87b 100644 --- a/pjlib/include/pj/compat/rand.h +++ b/pjlib/include/pj/compat/rand.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,11 +33,11 @@ # if defined(RAND_MAX) && RAND_MAX <= 0xFFFF /* * When rand() is only 16 bit strong, double the strength - * by calling it twice! - */ + * by calling it twice! + */ PJ_INLINE(int) platform_rand(void) { - return ((rand() & 0xFFFF) << 16) | (rand() & 0xFFFF); + return ((rand() & 0xFFFF) << 16) | (rand() & 0xFFFF); } # else # define platform_rand rand @@ -46,11 +45,11 @@ #else # warning "platform_rand() is not implemented" -# define platform_rand() 1 +# define platform_rand() 1 # define platform_srand(seed) #endif -#endif /* __PJ_COMPAT_RAND_H__ */ +#endif /* __PJ_COMPAT_RAND_H__ */ diff --git a/pjlib/include/pj/compat/setjmp.h b/pjlib/include/pj/compat/setjmp.h index 9dab44b5c9..1eff8b9e33 100644 --- a/pjlib/include/pj/compat/setjmp.h +++ b/pjlib/include/pj/compat/setjmp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,10 +28,10 @@ # include typedef jmp_buf pj_jmp_buf; # ifndef pj_setjmp -# define pj_setjmp(buf) setjmp(buf) +# define pj_setjmp(buf) setjmp(buf) # endif # ifndef pj_longjmp -# define pj_longjmp(buf,d) longjmp(buf,d) +# define pj_longjmp(buf,d) longjmp(buf,d) # endif #elif defined(PJ_SYMBIAN) && PJ_SYMBIAN!=0 @@ -41,10 +40,10 @@ #else # warning "setjmp()/longjmp() is not implemented" typedef int pj_jmp_buf[1]; -# define pj_setjmp(buf) 0 -# define pj_longjmp(buf,d) 0 +# define pj_setjmp(buf) 0 +# define pj_longjmp(buf,d) 0 #endif -#endif /* __PJ_COMPAT_SETJMP_H__ */ +#endif /* __PJ_COMPAT_SETJMP_H__ */ diff --git a/pjlib/include/pj/compat/size_t.h b/pjlib/include/pj/compat/size_t.h index 3f4e47b5fb..97ee066659 100644 --- a/pjlib/include/pj/compat/size_t.h +++ b/pjlib/include/pj/compat/size_t.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,5 +27,5 @@ # include #endif -#endif /* __PJ_COMPAT_SIZE_T_H__ */ +#endif /* __PJ_COMPAT_SIZE_T_H__ */ diff --git a/pjlib/include/pj/compat/socket.h b/pjlib/include/pj/compat/socket.h index 66c03fa5aa..51f4b0cc5f 100644 --- a/pjlib/include/pj/compat/socket.h +++ b/pjlib/include/pj/compat/socket.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -64,18 +63,18 @@ */ #if defined(_MSC_VER) && defined(PJ_HAS_IPV6) && PJ_HAS_IPV6!=0 # ifndef s_addr -# define s_addr S_un.S_addr +# define s_addr S_un.S_addr # endif # if !defined(IPPROTO_IPV6) && (_WIN32_WINNT == 0x0500) - /* Need to download and install IPv6Kit for this platform. - * Please see the comments above about Visual Studio 6. - */ -# include + /* Need to download and install IPv6Kit for this platform. + * Please see the comments above about Visual Studio 6. + */ +# include # endif # define PJ_SOCK_HAS_GETADDRINFO 1 -#endif /* _MSC_VER */ +#endif /* _MSC_VER */ #if defined(PJ_HAS_SYS_TYPES_H) && PJ_HAS_SYS_TYPES_H != 0 # include @@ -127,7 +126,7 @@ #endif #if defined(PJ_HAS_SYS_IOCTL_H) && PJ_HAS_SYS_IOCTL_H != 0 -# include /* FBIONBIO */ +# include /* FBIONBIO */ #endif #if defined(PJ_HAS_ERRNO_H) && PJ_HAS_ERRNO_H != 0 @@ -220,5 +219,5 @@ # define PJ_SOCKADDR_RESET_LEN(addr) #endif -#endif /* __PJ_COMPAT_SOCKET_H__ */ +#endif /* __PJ_COMPAT_SOCKET_H__ */ diff --git a/pjlib/include/pj/compat/stdarg.h b/pjlib/include/pj/compat/stdarg.h index 13e307525f..97f12d2d57 100644 --- a/pjlib/include/pj/compat/stdarg.h +++ b/pjlib/include/pj/compat/stdarg.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,4 +28,4 @@ # include #endif -#endif /* __PJ_COMPAT_STDARG_H__ */ +#endif /* __PJ_COMPAT_STDARG_H__ */ diff --git a/pjlib/include/pj/compat/stdfileio.h b/pjlib/include/pj/compat/stdfileio.h index 06047f626c..01c7a6fec8 100644 --- a/pjlib/include/pj/compat/stdfileio.h +++ b/pjlib/include/pj/compat/stdfileio.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,4 +28,4 @@ # include #endif -#endif /* __PJ_COMPAT_STDFILEIO_H__ */ +#endif /* __PJ_COMPAT_STDFILEIO_H__ */ diff --git a/pjlib/include/pj/compat/string.h b/pjlib/include/pj/compat/string.h index 28aab254d5..70a61f6731 100644 --- a/pjlib/include/pj/compat/string.h +++ b/pjlib/include/pj/compat/string.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,40 +43,40 @@ #endif #if defined(_MSC_VER) -# define strcasecmp _stricmp -# define strncasecmp _strnicmp +# define strcasecmp _stricmp +# define strncasecmp _strnicmp /* snprintf() and vsnprintf() are available since Visual Studio 2015 */ #if _MSC_VER < 1900 -# define snprintf _snprintf -# define vsnprintf _vsnprintf +# define snprintf _snprintf +# define vsnprintf _vsnprintf #endif -# define snwprintf _snwprintf -# define wcsicmp _wcsicmp -# define wcsnicmp _wcsnicmp +# define snwprintf _snwprintf +# define wcsicmp _wcsicmp +# define wcsnicmp _wcsnicmp #else -# define stricmp strcasecmp -# define strnicmp strncasecmp +# define stricmp strcasecmp +# define strnicmp strncasecmp # if defined(PJ_NATIVE_STRING_IS_UNICODE) && PJ_NATIVE_STRING_IS_UNICODE!=0 -# error "Implement Unicode string functions" +# error "Implement Unicode string functions" # endif #endif -#define pj_ansi_strcmp strcmp -#define pj_ansi_strncmp strncmp -#define pj_ansi_strlen strlen -#define pj_ansi_strcpy strcpy -#define pj_ansi_strncpy strncpy -#define pj_ansi_strcat strcat -#define pj_ansi_strstr strstr -#define pj_ansi_strchr strchr -#define pj_ansi_strcasecmp strcasecmp -#define pj_ansi_stricmp strcasecmp -#define pj_ansi_strncasecmp strncasecmp -#define pj_ansi_strnicmp strncasecmp -#define pj_ansi_sprintf sprintf +#define pj_ansi_strcmp strcmp +#define pj_ansi_strncmp strncmp +#define pj_ansi_strlen strlen +#define pj_ansi_strcpy strcpy +#define pj_ansi_strncpy strncpy +#define pj_ansi_strcat strcat +#define pj_ansi_strstr strstr +#define pj_ansi_strchr strchr +#define pj_ansi_strcasecmp strcasecmp +#define pj_ansi_stricmp strcasecmp +#define pj_ansi_strncasecmp strncasecmp +#define pj_ansi_strnicmp strncasecmp +#define pj_ansi_sprintf sprintf #if defined(PJ_HAS_NO_SNPRINTF) && PJ_HAS_NO_SNPRINTF != 0 # include @@ -88,62 +87,62 @@ PJ_END_DECL #endif -#define pj_ansi_snprintf snprintf -#define pj_ansi_vsprintf vsprintf -#define pj_ansi_vsnprintf vsnprintf - -#define pj_unicode_strcmp wcscmp -#define pj_unicode_strncmp wcsncmp -#define pj_unicode_strlen wcslen -#define pj_unicode_strcpy wcscpy -#define pj_unicode_strncpy wcsncpy -#define pj_unicode_strcat wcscat -#define pj_unicode_strstr wcsstr -#define pj_unicode_strchr wcschr -#define pj_unicode_strcasecmp wcsicmp -#define pj_unicode_stricmp wcsicmp -#define pj_unicode_strncasecmp wcsnicmp -#define pj_unicode_strnicmp wcsnicmp -#define pj_unicode_sprintf swprintf -#define pj_unicode_snprintf snwprintf -#define pj_unicode_vsprintf vswprintf -#define pj_unicode_vsnprintf vsnwprintf +#define pj_ansi_snprintf snprintf +#define pj_ansi_vsprintf vsprintf +#define pj_ansi_vsnprintf vsnprintf + +#define pj_unicode_strcmp wcscmp +#define pj_unicode_strncmp wcsncmp +#define pj_unicode_strlen wcslen +#define pj_unicode_strcpy wcscpy +#define pj_unicode_strncpy wcsncpy +#define pj_unicode_strcat wcscat +#define pj_unicode_strstr wcsstr +#define pj_unicode_strchr wcschr +#define pj_unicode_strcasecmp wcsicmp +#define pj_unicode_stricmp wcsicmp +#define pj_unicode_strncasecmp wcsnicmp +#define pj_unicode_strnicmp wcsnicmp +#define pj_unicode_sprintf swprintf +#define pj_unicode_snprintf snwprintf +#define pj_unicode_vsprintf vswprintf +#define pj_unicode_vsnprintf vsnwprintf #if defined(PJ_NATIVE_STRING_IS_UNICODE) && PJ_NATIVE_STRING_IS_UNICODE!=0 -# define pj_native_strcmp pj_unicode_strcmp -# define pj_native_strncmp pj_unicode_strncmp -# define pj_native_strlen pj_unicode_strlen -# define pj_native_strcpy pj_unicode_strcpy -# define pj_native_strncpy pj_unicode_strncpy -# define pj_native_strcat pj_unicode_strcat -# define pj_native_strstr pj_unicode_strstr -# define pj_native_strchr pj_unicode_strchr -# define pj_native_strcasecmp pj_unicode_strcasecmp -# define pj_native_stricmp pj_unicode_stricmp +# define pj_native_strcmp pj_unicode_strcmp +# define pj_native_strncmp pj_unicode_strncmp +# define pj_native_strlen pj_unicode_strlen +# define pj_native_strcpy pj_unicode_strcpy +# define pj_native_strncpy pj_unicode_strncpy +# define pj_native_strcat pj_unicode_strcat +# define pj_native_strstr pj_unicode_strstr +# define pj_native_strchr pj_unicode_strchr +# define pj_native_strcasecmp pj_unicode_strcasecmp +# define pj_native_stricmp pj_unicode_stricmp # define pj_native_strncasecmp pj_unicode_strncasecmp -# define pj_native_strnicmp pj_unicode_strnicmp -# define pj_native_sprintf pj_unicode_sprintf -# define pj_native_snprintf pj_unicode_snprintf -# define pj_native_vsprintf pj_unicode_vsprintf -# define pj_native_vsnprintf pj_unicode_vsnprintf +# define pj_native_strnicmp pj_unicode_strnicmp +# define pj_native_sprintf pj_unicode_sprintf +# define pj_native_snprintf pj_unicode_snprintf +# define pj_native_vsprintf pj_unicode_vsprintf +# define pj_native_vsnprintf pj_unicode_vsnprintf #else -# define pj_native_strcmp pj_ansi_strcmp -# define pj_native_strncmp pj_ansi_strncmp -# define pj_native_strlen pj_ansi_strlen -# define pj_native_strcpy pj_ansi_strcpy -# define pj_native_strncpy pj_ansi_strncpy -# define pj_native_strcat pj_ansi_strcat -# define pj_native_strstr pj_ansi_strstr -# define pj_native_strchr pj_ansi_strchr -# define pj_native_strcasecmp pj_ansi_strcasecmp -# define pj_native_stricmp pj_ansi_stricmp +# define pj_native_strcmp pj_ansi_strcmp +# define pj_native_strncmp pj_ansi_strncmp +# define pj_native_strlen pj_ansi_strlen +# define pj_native_strcpy pj_ansi_strcpy +# define pj_native_strncpy pj_ansi_strncpy +# define pj_native_strcat pj_ansi_strcat +# define pj_native_strstr pj_ansi_strstr +# define pj_native_strchr pj_ansi_strchr +# define pj_native_strcasecmp pj_ansi_strcasecmp +# define pj_native_stricmp pj_ansi_stricmp # define pj_native_strncasecmp pj_ansi_strncasecmp -# define pj_native_strnicmp pj_ansi_strnicmp -# define pj_native_sprintf pj_ansi_sprintf -# define pj_native_snprintf pj_ansi_snprintf -# define pj_native_vsprintf pj_ansi_vsprintf -# define pj_native_vsnprintf pj_ansi_vsnprintf +# define pj_native_strnicmp pj_ansi_strnicmp +# define pj_native_sprintf pj_ansi_sprintf +# define pj_native_snprintf pj_ansi_snprintf +# define pj_native_vsprintf pj_ansi_vsprintf +# define pj_native_vsnprintf pj_ansi_vsnprintf #endif -#endif /* __PJ_COMPAT_STRING_H__ */ +#endif /* __PJ_COMPAT_STRING_H__ */ diff --git a/pjlib/include/pj/compat/time.h b/pjlib/include/pj/compat/time.h index 6ac2432819..b6999d38b4 100644 --- a/pjlib/include/pj/compat/time.h +++ b/pjlib/include/pj/compat/time.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,5 +37,5 @@ #endif -#endif /* __PJ_COMPAT_TIME_H__ */ +#endif /* __PJ_COMPAT_TIME_H__ */ diff --git a/pjlib/include/pj/config.h b/pjlib/include/pj/config.h index c59780a3c0..ba7c27211a 100644 --- a/pjlib/include/pj/config.h +++ b/pjlib/include/pj/config.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -102,14 +101,14 @@ # define PJ_WIN32 1 #elif defined(PJ_WIN32) || defined(_WIN32) || defined(__WIN32__) || \ - defined(WIN32) || defined(PJ_WIN64) || defined(_WIN64) || \ - defined(WIN64) || defined(__TOS_WIN__) + defined(WIN32) || defined(PJ_WIN64) || defined(_WIN64) || \ + defined(WIN64) || defined(__TOS_WIN__) # if defined(PJ_WIN64) || defined(_WIN64) || defined(WIN64) - /* - * Win64 - */ -# undef PJ_WIN64 -# define PJ_WIN64 1 + /* + * Win64 + */ +# undef PJ_WIN64 +# define PJ_WIN64 1 # endif # undef PJ_WIN32 # define PJ_WIN32 1 @@ -120,7 +119,7 @@ * Linux */ # undef PJ_LINUX -# define PJ_LINUX 1 +# define PJ_LINUX 1 # include #elif defined(PJ_PALMOS) && PJ_PALMOS!=0 @@ -134,7 +133,7 @@ * SunOS */ # undef PJ_SUNOS -# define PJ_SUNOS 1 +# define PJ_SUNOS 1 # include #elif defined(PJ_DARWINOS) || defined(__MACOSX__) || \ @@ -143,7 +142,7 @@ * MacOS X */ # undef PJ_DARWINOS -# define PJ_DARWINOS 1 +# define PJ_DARWINOS 1 # include #elif defined(PJ_RTEMS) && PJ_RTEMS!=0 @@ -166,42 +165,42 @@ #include #elif defined (PJ_M_I386) || defined(_i386_) || defined(i_386_) || \ - defined(_X86_) || defined(x86) || defined(__i386__) || \ - defined(__i386) || defined(_M_IX86) || defined(__I86__) + defined(_X86_) || defined(x86) || defined(__i386__) || \ + defined(__i386) || defined(_M_IX86) || defined(__I86__) /* * Generic i386 processor family, little-endian */ # undef PJ_M_I386 -# define PJ_M_I386 1 -# define PJ_M_NAME "i386" -# define PJ_HAS_PENTIUM 1 -# define PJ_IS_LITTLE_ENDIAN 1 -# define PJ_IS_BIG_ENDIAN 0 +# define PJ_M_I386 1 +# define PJ_M_NAME "i386" +# define PJ_HAS_PENTIUM 1 +# define PJ_IS_LITTLE_ENDIAN 1 +# define PJ_IS_BIG_ENDIAN 0 #elif defined (PJ_M_X86_64) || defined(__amd64__) || defined(__amd64) || \ - defined(__x86_64__) || defined(__x86_64) || \ - defined(_M_X64) || defined(_M_AMD64) + defined(__x86_64__) || defined(__x86_64) || \ + defined(_M_X64) || defined(_M_AMD64) /* * AMD 64bit processor, little endian */ # undef PJ_M_X86_64 -# define PJ_M_X86_64 1 -# define PJ_M_NAME "x86_64" -# define PJ_HAS_PENTIUM 1 -# define PJ_IS_LITTLE_ENDIAN 1 -# define PJ_IS_BIG_ENDIAN 0 +# define PJ_M_X86_64 1 +# define PJ_M_NAME "x86_64" +# define PJ_HAS_PENTIUM 1 +# define PJ_IS_LITTLE_ENDIAN 1 +# define PJ_IS_BIG_ENDIAN 0 #elif defined(PJ_M_IA64) || defined(__ia64__) || defined(_IA64) || \ - defined(__IA64__) || defined( _M_IA64) + defined(__IA64__) || defined( _M_IA64) /* * Intel IA64 processor, default to little endian */ # undef PJ_M_IA64 -# define PJ_M_IA64 1 -# define PJ_M_NAME "ia64" -# define PJ_HAS_PENTIUM 1 -# define PJ_IS_LITTLE_ENDIAN 1 -# define PJ_IS_BIG_ENDIAN 0 +# define PJ_M_IA64 1 +# define PJ_M_NAME "ia64" +# define PJ_HAS_PENTIUM 1 +# define PJ_IS_LITTLE_ENDIAN 1 +# define PJ_IS_BIG_ENDIAN 0 #elif defined (PJ_M_M68K) && PJ_M_M68K != 0 @@ -209,86 +208,86 @@ * Motorola m68k processor, big endian */ # undef PJ_M_M68K -# define PJ_M_M68K 1 -# define PJ_M_NAME "m68k" -# define PJ_HAS_PENTIUM 0 -# define PJ_IS_LITTLE_ENDIAN 0 -# define PJ_IS_BIG_ENDIAN 1 +# define PJ_M_M68K 1 +# define PJ_M_NAME "m68k" +# define PJ_HAS_PENTIUM 0 +# define PJ_IS_LITTLE_ENDIAN 0 +# define PJ_IS_BIG_ENDIAN 1 #elif defined (PJ_M_ALPHA) || defined (__alpha__) || defined (__alpha) || \ - defined (_M_ALPHA) + defined (_M_ALPHA) /* * DEC Alpha processor, little endian */ # undef PJ_M_ALPHA -# define PJ_M_ALPHA 1 -# define PJ_M_NAME "alpha" -# define PJ_HAS_PENTIUM 0 -# define PJ_IS_LITTLE_ENDIAN 1 -# define PJ_IS_BIG_ENDIAN 0 +# define PJ_M_ALPHA 1 +# define PJ_M_NAME "alpha" +# define PJ_HAS_PENTIUM 0 +# define PJ_IS_LITTLE_ENDIAN 1 +# define PJ_IS_BIG_ENDIAN 0 #elif defined(PJ_M_MIPS) || defined(__mips__) || defined(__mips) || \ - defined(__MIPS__) || defined(MIPS) || defined(_MIPS_) + defined(__MIPS__) || defined(MIPS) || defined(_MIPS_) /* * MIPS, bi-endian, so raise error if endianness is not configured */ # undef PJ_M_MIPS -# define PJ_M_MIPS 1 -# define PJ_M_NAME "mips" -# define PJ_HAS_PENTIUM 0 +# define PJ_M_MIPS 1 +# define PJ_M_NAME "mips" +# define PJ_HAS_PENTIUM 0 # if !PJ_IS_LITTLE_ENDIAN && !PJ_IS_BIG_ENDIAN -# error Endianness must be declared for this processor +# error Endianness must be declared for this processor # endif -#elif defined (PJ_M_SPARC) || defined( __sparc__) || defined(__sparc) +#elif defined (PJ_M_SPARC) || defined( __sparc__) || defined(__sparc) /* * Sun Sparc, big endian */ # undef PJ_M_SPARC -# define PJ_M_SPARC 1 -# define PJ_M_NAME "sparc" -# define PJ_HAS_PENTIUM 0 -# define PJ_IS_LITTLE_ENDIAN 0 -# define PJ_IS_BIG_ENDIAN 1 +# define PJ_M_SPARC 1 +# define PJ_M_NAME "sparc" +# define PJ_HAS_PENTIUM 0 +# define PJ_IS_LITTLE_ENDIAN 0 +# define PJ_IS_BIG_ENDIAN 1 #elif defined(ARM) || defined(_ARM_) || defined(__arm__) || \ defined(_M_ARM) || defined(_M_ARM64) || defined(__aarch64__) -# define PJ_HAS_PENTIUM 0 +# define PJ_HAS_PENTIUM 0 /* * ARM, bi-endian, so raise error if endianness is not configured */ # if !PJ_IS_LITTLE_ENDIAN && !PJ_IS_BIG_ENDIAN -# error Endianness must be declared for this processor +# error Endianness must be declared for this processor # endif # if defined (PJ_M_ARMV7) || defined(ARMV7) -# undef PJ_M_ARMV7 -# define PJ_M_ARM7 1 -# define PJ_M_NAME "armv7" +# undef PJ_M_ARMV7 +# define PJ_M_ARM7 1 +# define PJ_M_NAME "armv7" # elif defined (PJ_M_ARMV4) || defined(ARMV4) -# undef PJ_M_ARMV4 -# define PJ_M_ARMV4 1 -# define PJ_M_NAME "armv4" +# undef PJ_M_ARMV4 +# define PJ_M_ARMV4 1 +# define PJ_M_NAME "armv4" # elif defined (PJ_M_ARM64) || defined(ARM64) || defined(__aarch64__) -# undef PJ_M_ARM64 -# define PJ_M_ARM64 1 -# define PJ_M_NAME "arm64" +# undef PJ_M_ARM64 +# define PJ_M_ARM64 1 +# define PJ_M_NAME "arm64" # endif #elif defined (PJ_M_POWERPC) || defined(__powerpc) || defined(__powerpc__) || \ - defined(__POWERPC__) || defined(__ppc__) || defined(_M_PPC) || \ - defined(_ARCH_PPC) + defined(__POWERPC__) || defined(__ppc__) || defined(_M_PPC) || \ + defined(_ARCH_PPC) /* * PowerPC, bi-endian, so raise error if endianness is not configured */ # undef PJ_M_POWERPC -# define PJ_M_POWERPC 1 -# define PJ_M_NAME "powerpc" -# define PJ_HAS_PENTIUM 0 +# define PJ_M_POWERPC 1 +# define PJ_M_NAME "powerpc" +# define PJ_HAS_PENTIUM 0 # if !PJ_IS_LITTLE_ENDIAN && !PJ_IS_BIG_ENDIAN -# error Endianness must be declared for this processor +# error Endianness must be declared for this processor # endif #elif defined (PJ_M_NIOS2) || defined(__nios2) || defined(__nios2__) || \ @@ -297,12 +296,12 @@ * Nios2, little endian */ # undef PJ_M_NIOS2 -# define PJ_M_NIOS2 1 -# define PJ_M_NAME "nios2" -# define PJ_HAS_PENTIUM 0 -# define PJ_IS_LITTLE_ENDIAN 1 -# define PJ_IS_BIG_ENDIAN 0 - +# define PJ_M_NIOS2 1 +# define PJ_M_NAME "nios2" +# define PJ_HAS_PENTIUM 0 +# define PJ_IS_LITTLE_ENDIAN 1 +# define PJ_IS_BIG_ENDIAN 0 + #else # error "Please specify target machine." #endif @@ -337,7 +336,7 @@ # undef PJ_EXCEPTION_USE_WIN32_SEH # undef PJ_HAS_ERROR_STRING -# define PJ_HAS_IPV6 1 +# define PJ_HAS_IPV6 1 #endif /** @@ -359,9 +358,9 @@ */ #ifndef PJ_DEBUG # ifndef NDEBUG -# define PJ_DEBUG 1 +# define PJ_DEBUG 1 # else -# define PJ_DEBUG 0 +# define PJ_DEBUG 0 # endif #endif @@ -374,7 +373,7 @@ * Default: 0 */ #ifndef PJ_DEBUG_MUTEX -# define PJ_DEBUG_MUTEX 0 +# define PJ_DEBUG_MUTEX 0 #endif /** @@ -392,7 +391,7 @@ * Default: 1. */ #ifndef PJ_HAS_FLOATING_POINT -# define PJ_HAS_FLOATING_POINT 1 +# define PJ_HAS_FLOATING_POINT 1 #endif /** @@ -425,7 +424,7 @@ * Default: 4000 */ #ifndef PJ_LOG_MAX_SIZE -# define PJ_LOG_MAX_SIZE 4000 +# define PJ_LOG_MAX_SIZE 4000 #endif /** @@ -465,7 +464,7 @@ * Default: space */ #ifndef PJ_LOG_INDENT_CHAR -# define PJ_LOG_INDENT_CHAR '.' +# define PJ_LOG_INDENT_CHAR '.' #endif /** @@ -492,7 +491,7 @@ * Default: 12 */ #ifndef PJ_LOG_THREAD_WIDTH -# define PJ_LOG_THREAD_WIDTH 12 +# define PJ_LOG_THREAD_WIDTH 12 #endif /** @@ -501,7 +500,7 @@ * Default: 1 */ #ifndef PJ_TERM_HAS_COLOR -# define PJ_TERM_HAS_COLOR 1 +# define PJ_TERM_HAS_COLOR 1 #endif @@ -517,7 +516,7 @@ * Default: 0 */ #ifndef PJ_SAFE_POOL -# define PJ_SAFE_POOL 0 +# define PJ_SAFE_POOL 0 #endif @@ -530,7 +529,7 @@ * Default: 0 */ #ifndef PJ_POOL_DEBUG -# define PJ_POOL_DEBUG 0 +# define PJ_POOL_DEBUG 0 #endif @@ -541,7 +540,7 @@ * Default: 0 */ #ifndef PJ_POOL_RELEASE_WIPE_DATA -# define PJ_POOL_RELEASE_WIPE_DATA 0 +# define PJ_POOL_RELEASE_WIPE_DATA 0 #endif @@ -554,7 +553,7 @@ * Default: 1 */ #ifndef PJ_TIMER_DEBUG -# define PJ_TIMER_DEBUG 1 +# define PJ_TIMER_DEBUG 1 #endif @@ -594,7 +593,7 @@ * Set this to 1 to enable debugging on the group lock. Default: 0 */ #ifndef PJ_GRP_LOCK_DEBUG -# define PJ_GRP_LOCK_DEBUG 0 +# define PJ_GRP_LOCK_DEBUG 0 #endif @@ -617,7 +616,7 @@ * tracks the filename and line number of each functions. */ #ifndef PJ_OS_HAS_CHECK_STACK -# define PJ_OS_HAS_CHECK_STACK 0 +# define PJ_OS_HAS_CHECK_STACK 0 #endif /** @@ -626,7 +625,7 @@ * Default: 0 */ #ifndef PJ_HAS_POOL_ALT_API -# define PJ_HAS_POOL_ALT_API PJ_POOL_DEBUG +# define PJ_HAS_POOL_ALT_API PJ_POOL_DEBUG #endif @@ -637,7 +636,7 @@ * Default: 1 */ #ifndef PJ_HAS_TCP -# define PJ_HAS_TCP 1 +# define PJ_HAS_TCP 1 #endif /** @@ -647,7 +646,7 @@ * Default: 0 (disabled, for now) */ #ifndef PJ_HAS_IPV6 -# define PJ_HAS_IPV6 0 +# define PJ_HAS_IPV6 0 #endif /** @@ -658,7 +657,7 @@ * Default: 128 */ #ifndef PJ_MAX_HOSTNAME -# define PJ_MAX_HOSTNAME (128) +# define PJ_MAX_HOSTNAME (128) #endif /** @@ -679,7 +678,7 @@ * the underlying implementation changes. */ #ifndef PJ_IOQUEUE_MAX_HANDLES -# define PJ_IOQUEUE_MAX_HANDLES (64) +# define PJ_IOQUEUE_MAX_HANDLES (64) #endif @@ -700,7 +699,7 @@ * Default: 1 */ #ifndef PJ_IOQUEUE_HAS_SAFE_UNREG -# define PJ_IOQUEUE_HAS_SAFE_UNREG 1 +# define PJ_IOQUEUE_HAS_SAFE_UNREG 1 #endif @@ -726,7 +725,7 @@ */ #if (PJ_IOQUEUE_DEFAULT_ALLOW_CONCURRENCY==0) && (PJ_IOQUEUE_HAS_SAFE_UNREG==0) # error PJ_IOQUEUE_HAS_SAFE_UNREG must be enabled if ioqueue concurrency \ - is disabled + is disabled #endif @@ -740,7 +739,7 @@ * Default: 500 msec. */ #ifndef PJ_IOQUEUE_KEY_FREE_DELAY -# define PJ_IOQUEUE_KEY_FREE_DELAY 500 +# define PJ_IOQUEUE_KEY_FREE_DELAY 500 #endif @@ -763,9 +762,9 @@ #ifndef PJ_FD_SETSIZE_SETABLE # if (defined(PJ_HAS_WINSOCK_H) && PJ_HAS_WINSOCK_H!=0) || \ (defined(PJ_HAS_WINSOCK2_H) && PJ_HAS_WINSOCK2_H!=0) -# define PJ_FD_SETSIZE_SETABLE 1 +# define PJ_FD_SETSIZE_SETABLE 1 # else -# define PJ_FD_SETSIZE_SETABLE 0 +# define PJ_FD_SETSIZE_SETABLE 0 # endif #endif @@ -778,7 +777,7 @@ #if PJ_FD_SETSIZE_SETABLE /* Only override FD_SETSIZE if the value has not been set */ # ifndef FD_SETSIZE -# define FD_SETSIZE PJ_IOQUEUE_MAX_HANDLES +# define FD_SETSIZE PJ_IOQUEUE_MAX_HANDLES # endif #else /* When FD_SETSIZE is not changeable, check if PJ_IOQUEUE_MAX_HANDLES @@ -790,9 +789,9 @@ */ /* # ifdef FD_SETSIZE -# if PJ_IOQUEUE_MAX_HANDLES > FD_SETSIZE -# error "PJ_IOQUEUE_MAX_HANDLES is greater than FD_SETSIZE" -# endif +# if PJ_IOQUEUE_MAX_HANDLES > FD_SETSIZE +# error "PJ_IOQUEUE_MAX_HANDLES is greater than FD_SETSIZE" +# endif # endif */ #endif @@ -805,7 +804,7 @@ * Default: 1 */ #ifndef PJ_IP_HELPER_IGNORE_LOOPBACK_IF -# define PJ_IP_HELPER_IGNORE_LOOPBACK_IF 1 +# define PJ_IP_HELPER_IGNORE_LOOPBACK_IF 1 #endif @@ -815,7 +814,7 @@ * Default: 1 */ #ifndef PJ_HAS_SEMAPHORE -# define PJ_HAS_SEMAPHORE 1 +# define PJ_HAS_SEMAPHORE 1 #endif /** @@ -825,9 +824,9 @@ */ #ifndef PJ_SEMAPHORE_USE_DISPATCH_SEM # if defined(PJ_DARWINOS) && PJ_DARWINOS != 0 -# define PJ_SEMAPHORE_USE_DISPATCH_SEM 1 +# define PJ_SEMAPHORE_USE_DISPATCH_SEM 1 # else -# define PJ_SEMAPHORE_USE_DISPATCH_SEM 0 +# define PJ_SEMAPHORE_USE_DISPATCH_SEM 0 # endif #endif @@ -838,7 +837,7 @@ * Default: 1 */ #ifndef PJ_HAS_EVENT_OBJ -# define PJ_HAS_EVENT_OBJ 1 +# define PJ_HAS_EVENT_OBJ 1 #endif @@ -846,7 +845,7 @@ * Maximum file name length. */ #ifndef PJ_MAXPATH -# define PJ_MAXPATH 260 +# define PJ_MAXPATH 260 #endif @@ -911,7 +910,7 @@ * Default: 1 */ #ifndef PJ_HAS_ERROR_STRING -# define PJ_HAS_ERROR_STRING 1 +# define PJ_HAS_ERROR_STRING 1 #endif @@ -924,7 +923,7 @@ * Default: 0 */ #ifndef PJ_HAS_STRICMP_ALNUM -# define PJ_HAS_STRICMP_ALNUM 0 +# define PJ_HAS_STRICMP_ALNUM 0 #endif /* @@ -934,10 +933,10 @@ */ #if defined(PJ_ENABLE_EXTRA_CHECK) && PJ_ENABLE_EXTRA_CHECK==0 # ifdef _MSC_VER -# pragma message("Warning: PJ_ENABLE_EXTRA_CHECK macro is deprecated"\ - " and has no effect") +# pragma message("Warning: PJ_ENABLE_EXTRA_CHECK macro is deprecated"\ + " and has no effect") # else -# warning "PJ_ENABLE_EXTRA_CHECK macro is deprecated and has no effect" +# warning "PJ_ENABLE_EXTRA_CHECK macro is deprecated and has no effect" # endif #endif @@ -950,30 +949,30 @@ * Dummy QoS backend implementation, will always return error on all * the APIs. */ -#define PJ_QOS_DUMMY 1 +#define PJ_QOS_DUMMY 1 /** QoS backend based on setsockopt(IP_TOS) */ -#define PJ_QOS_BSD 2 +#define PJ_QOS_BSD 2 /** QoS backend for Windows Mobile 6 */ -#define PJ_QOS_WM 3 +#define PJ_QOS_WM 3 /** QoS backend for Symbian */ -#define PJ_QOS_SYMBIAN 4 +#define PJ_QOS_SYMBIAN 4 /** QoS backend for Darwin */ -#define PJ_QOS_DARWIN 5 +#define PJ_QOS_DARWIN 5 /** * Force the use of some QoS backend API for some platforms. */ #ifndef PJ_QOS_IMPLEMENTATION # if defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE && _WIN32_WCE >= 0x502 - /* Windows Mobile 6 or later */ -# define PJ_QOS_IMPLEMENTATION PJ_QOS_WM + /* Windows Mobile 6 or later */ +# define PJ_QOS_IMPLEMENTATION PJ_QOS_WM # elif defined(PJ_DARWINOS) - /* Darwin OS (e.g: iOS, MacOS, tvOS) */ -# define PJ_QOS_IMPLEMENTATION PJ_QOS_DARWIN + /* Darwin OS (e.g: iOS, MacOS, tvOS) */ +# define PJ_QOS_IMPLEMENTATION PJ_QOS_DARWIN # endif #endif @@ -987,7 +986,7 @@ * Default: 0 (for now) */ #ifndef PJ_HAS_SSL_SOCK -# define PJ_HAS_SSL_SOCK 0 +# define PJ_HAS_SSL_SOCK 0 #endif @@ -995,14 +994,14 @@ * Secure socket implementation. * Select one of these implementations in PJ_SSL_SOCK_IMP. */ -#define PJ_SSL_SOCK_IMP_NONE 0 /**< Disable SSL socket. */ -#define PJ_SSL_SOCK_IMP_OPENSSL 1 /**< Using OpenSSL. */ -#define PJ_SSL_SOCK_IMP_GNUTLS 2 /**< Using GnuTLS. */ -#define PJ_SSL_SOCK_IMP_DARWIN 3 /**< Using Apple's Secure - Transport (deprecated in - MacOS 10.15 & iOS 13.0)*/ -#define PJ_SSL_SOCK_IMP_APPLE 4 /**< Using Apple's Network - framework. */ +#define PJ_SSL_SOCK_IMP_NONE 0 /**< Disable SSL socket. */ +#define PJ_SSL_SOCK_IMP_OPENSSL 1 /**< Using OpenSSL. */ +#define PJ_SSL_SOCK_IMP_GNUTLS 2 /**< Using GnuTLS. */ +#define PJ_SSL_SOCK_IMP_DARWIN 3 /**< Using Apple's Secure + Transport (deprecated in + MacOS 10.15 & iOS 13.0)*/ +#define PJ_SSL_SOCK_IMP_APPLE 4 /**< Using Apple's Network + framework. */ /** * Select which SSL socket implementation to use. Currently pjlib supports @@ -1015,9 +1014,9 @@ */ #ifndef PJ_SSL_SOCK_IMP # if PJ_HAS_SSL_SOCK==0 -# define PJ_SSL_SOCK_IMP PJ_SSL_SOCK_IMP_NONE +# define PJ_SSL_SOCK_IMP PJ_SSL_SOCK_IMP_NONE # else -# define PJ_SSL_SOCK_IMP PJ_SSL_SOCK_IMP_OPENSSL +# define PJ_SSL_SOCK_IMP PJ_SSL_SOCK_IMP_OPENSSL # endif #endif @@ -1083,7 +1082,7 @@ * Default: 4 */ #ifndef PJ_MAX_SOCKOPT_PARAMS -# define PJ_MAX_SOCKOPT_PARAMS 4 +# define PJ_MAX_SOCKOPT_PARAMS 4 #endif @@ -1157,8 +1156,8 @@ * macros. * - Declare these macros in your config_site.h: \verbatim - #define PJ_EXPORT_SPECIFIER __declspec(dllexport) - #define PJ_IMPORT_SPECIFIER __declspec(dllimport) + #define PJ_EXPORT_SPECIFIER __declspec(dllexport) + #define PJ_IMPORT_SPECIFIER __declspec(dllimport) \endverbatim * - And in the application (that links with the DLL) project, add * PJ_DLL in the macro declarations. @@ -1176,7 +1175,7 @@ * @param type The return type of the function. * Expand the function as inline. */ -#define PJ_INLINE(type) PJ_INLINE_SPECIFIER type +#define PJ_INLINE(type) PJ_INLINE_SPECIFIER type /** * This macro declares platform/compiler specific specifier prefix @@ -1231,15 +1230,15 @@ */ #if defined(PJ_DLL) # if defined(PJ_EXPORTING) -# define PJ_DECL(type) PJ_EXPORT_DECL_SPECIFIER type +# define PJ_DECL(type) PJ_EXPORT_DECL_SPECIFIER type # else -# define PJ_DECL(type) PJ_IMPORT_DECL_SPECIFIER type +# define PJ_DECL(type) PJ_IMPORT_DECL_SPECIFIER type # endif #elif !defined(PJ_DECL) # if defined(__cplusplus) -# define PJ_DECL(type) type +# define PJ_DECL(type) type # else -# define PJ_DECL(type) extern type +# define PJ_DECL(type) extern type # endif #endif @@ -1250,9 +1249,9 @@ * Define a function. */ #if defined(PJ_DLL) && defined(PJ_EXPORTING) -# define PJ_DEF(type) PJ_EXPORT_DEF_SPECIFIER type +# define PJ_DEF(type) PJ_EXPORT_DEF_SPECIFIER type #elif !defined(PJ_DEF) -# define PJ_DEF(type) type +# define PJ_DEF(type) type #endif @@ -1277,8 +1276,8 @@ #ifdef __cplusplus # define PJ_DECL_NO_RETURN(type) PJ_DECL(type) PJ_NORETURN # define PJ_IDECL_NO_RETURN(type) PJ_INLINE(type) PJ_NORETURN -# define PJ_BEGIN_DECL extern "C" { -# define PJ_END_DECL } +# define PJ_BEGIN_DECL extern "C" { +# define PJ_END_DECL } #else # define PJ_DECL_NO_RETURN(type) PJ_NORETURN PJ_DECL(type) # define PJ_IDECL_NO_RETURN(type) PJ_NORETURN PJ_INLINE(type) @@ -1295,12 +1294,12 @@ */ #if defined(PJ_DLL) # if defined(PJ_EXPORTING) -# define PJ_DECL_DATA(type) PJ_EXPORT_DECL_SPECIFIER extern type +# define PJ_DECL_DATA(type) PJ_EXPORT_DECL_SPECIFIER extern type # else -# define PJ_DECL_DATA(type) PJ_IMPORT_DECL_SPECIFIER extern type +# define PJ_DECL_DATA(type) PJ_IMPORT_DECL_SPECIFIER extern type # endif #elif !defined(PJ_DECL_DATA) -# define PJ_DECL_DATA(type) extern type +# define PJ_DECL_DATA(type) extern type #endif @@ -1310,9 +1309,9 @@ * Define a global data. */ #if defined(PJ_DLL) && defined(PJ_EXPORTING) -# define PJ_DEF_DATA(type) PJ_EXPORT_DEF_SPECIFIER type +# define PJ_DEF_DATA(type) PJ_EXPORT_DEF_SPECIFIER type #elif !defined(PJ_DEF_DATA) -# define PJ_DEF_DATA(type) type +# define PJ_DEF_DATA(type) type #endif @@ -1350,7 +1349,7 @@ * Example: PJ_TODO(CLEAN_UP_ERROR); */ #ifndef PJ_TODO -# define PJ_TODO(id) TODO___##id: +# define PJ_TODO(id) TODO___##id: #endif /** @@ -1404,10 +1403,10 @@ PJ_BEGIN_DECL /** PJLIB version major number. */ -#define PJ_VERSION_NUM_MAJOR 2 +#define PJ_VERSION_NUM_MAJOR 2 /** PJLIB version minor number. */ -#define PJ_VERSION_NUM_MINOR 12 +#define PJ_VERSION_NUM_MINOR 12 /** PJLIB version revision number. */ #define PJ_VERSION_NUM_REV 0 @@ -1416,16 +1415,16 @@ PJ_BEGIN_DECL * Extra suffix for the version (e.g. "-trunk"), or empty for * web release version. */ -#define PJ_VERSION_NUM_EXTRA "-dev" +#define PJ_VERSION_NUM_EXTRA "-dev" /** * PJLIB version number consists of three bytes with the following format: * 0xMMIIRR00, where MM: major number, II: minor number, RR: revision * number, 00: always zero for now. */ -#define PJ_VERSION_NUM ((PJ_VERSION_NUM_MAJOR << 24) | \ - (PJ_VERSION_NUM_MINOR << 16) | \ - (PJ_VERSION_NUM_REV << 8)) +#define PJ_VERSION_NUM ((PJ_VERSION_NUM_MAJOR << 24) | \ + (PJ_VERSION_NUM_MINOR << 16) | \ + (PJ_VERSION_NUM_REV << 8)) /** * PJLIB version string constant. @see pj_get_version() @@ -1447,5 +1446,5 @@ PJ_DECL(void) pj_dump_config(void); PJ_END_DECL -#endif /* __PJ_CONFIG_H__ */ +#endif /* __PJ_CONFIG_H__ */ diff --git a/pjlib/include/pj/config_site_sample.h b/pjlib/include/pj/config_site_sample.h index 6e8f355333..fb68d4d5d1 100644 --- a/pjlib/include/pj/config_site_sample.h +++ b/pjlib/include/pj/config_site_sample.h @@ -30,24 +30,24 @@ */ /* Disable floating point support */ - #define PJ_HAS_FLOATING_POINT 0 + #define PJ_HAS_FLOATING_POINT 0 /* * PJMEDIA settings */ /* Select codecs to disable */ - #define PJMEDIA_HAS_L16_CODEC 0 - #define PJMEDIA_HAS_ILBC_CODEC 0 + #define PJMEDIA_HAS_L16_CODEC 0 + #define PJMEDIA_HAS_ILBC_CODEC 0 /* We probably need more buffers on WM, so increase the limit */ - #define PJMEDIA_SOUND_BUFFER_COUNT 32 + #define PJMEDIA_SOUND_BUFFER_COUNT 32 /* Fine tune Speex's default settings for best performance/quality */ - #define PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY 5 + #define PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY 5 /* For CPU reason, disable speex AEC and use the echo suppressor. */ - #define PJMEDIA_HAS_SPEEX_AEC 0 + #define PJMEDIA_HAS_SPEEX_AEC 0 /* Previously, resampling is disabled due to performance reason and * this condition prevented some 'light' wideband codecs (e.g: G722.1) @@ -58,11 +58,11 @@ * using small filter. For example PJSUA_DEFAULT_CODEC_QUALITY must * be set to 3 or 4 so pjsua-lib will apply small filter resampling. */ - //#define PJMEDIA_RESAMPLE_IMP PJMEDIA_RESAMPLE_NONE - #define PJMEDIA_RESAMPLE_IMP PJMEDIA_RESAMPLE_LIBRESAMPLE + //#define PJMEDIA_RESAMPLE_IMP PJMEDIA_RESAMPLE_NONE + #define PJMEDIA_RESAMPLE_IMP PJMEDIA_RESAMPLE_LIBRESAMPLE /* Use the lighter WSOLA implementation */ - #define PJMEDIA_WSOLA_IMP PJMEDIA_WSOLA_IMP_WSOLA_LITE + #define PJMEDIA_WSOLA_IMP PJMEDIA_WSOLA_IMP_WSOLA_LITE /* * PJSIP settings. @@ -71,9 +71,9 @@ /* Set maximum number of dialog/transaction/calls to minimum to reduce * memory usage */ - #define PJSIP_MAX_TSX_COUNT 31 - #define PJSIP_MAX_DIALOG_COUNT 31 - #define PJSUA_MAX_CALLS 4 + #define PJSIP_MAX_TSX_COUNT 31 + #define PJSIP_MAX_DIALOG_COUNT 31 + #define PJSUA_MAX_CALLS 4 /* * PJSUA settings @@ -82,16 +82,16 @@ /* Default codec quality, previously was set to 5, however it is now * set to 4 to make sure pjsua instantiates resampler with small filter. */ - #define PJSUA_DEFAULT_CODEC_QUALITY 4 + #define PJSUA_DEFAULT_CODEC_QUALITY 4 /* Set maximum number of objects to minimum to reduce memory usage */ - #define PJSUA_MAX_ACC 4 - #define PJSUA_MAX_PLAYERS 4 - #define PJSUA_MAX_RECORDERS 4 - #define PJSUA_MAX_CONF_PORTS (PJSUA_MAX_CALLS+2*PJSUA_MAX_PLAYERS) - #define PJSUA_MAX_BUDDIES 32 + #define PJSUA_MAX_ACC 4 + #define PJSUA_MAX_PLAYERS 4 + #define PJSUA_MAX_RECORDERS 4 + #define PJSUA_MAX_CONF_PORTS (PJSUA_MAX_CALLS+2*PJSUA_MAX_PLAYERS) + #define PJSUA_MAX_BUDDIES 32 -#endif /* PJ_WIN32_WINCE */ +#endif /* PJ_WIN32_WINCE */ /* @@ -104,25 +104,25 @@ */ /* Disable floating point support */ - #define PJ_HAS_FLOATING_POINT 0 + #define PJ_HAS_FLOATING_POINT 0 /* Misc PJLIB setting */ - #define PJ_MAXPATH 80 + #define PJ_MAXPATH 80 /* This is important for Symbian. Symbian lacks vsnprintf(), so * if the log buffer is not long enough it's possible that * large incoming packet will corrupt memory when the log tries * to log the packet. */ - #define PJ_LOG_MAX_SIZE (PJSIP_MAX_PKT_LEN+500) + #define PJ_LOG_MAX_SIZE (PJSIP_MAX_PKT_LEN+500) /* Since we don't have threads, log buffer can use static buffer * rather than stack */ - #define PJ_LOG_USE_STACK_BUFFER 0 + #define PJ_LOG_USE_STACK_BUFFER 0 /* Disable check stack since it increases footprint */ - #define PJ_OS_HAS_CHECK_STACK 0 + #define PJ_OS_HAS_CHECK_STACK 0 /* @@ -130,19 +130,19 @@ */ /* Disable non-Symbian audio devices */ - #define PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO 0 - #define PJMEDIA_AUDIO_DEV_HAS_WMME 0 + #define PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO 0 + #define PJMEDIA_AUDIO_DEV_HAS_WMME 0 /* Select codecs to disable */ - #define PJMEDIA_HAS_L16_CODEC 0 - #define PJMEDIA_HAS_ILBC_CODEC 0 - #define PJMEDIA_HAS_G722_CODEC 0 + #define PJMEDIA_HAS_L16_CODEC 0 + #define PJMEDIA_HAS_ILBC_CODEC 0 + #define PJMEDIA_HAS_G722_CODEC 0 /* Fine tune Speex's default settings for best performance/quality */ - #define PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY 5 + #define PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY 5 /* For CPU reason, disable speex AEC and use the echo suppressor. */ - #define PJMEDIA_HAS_SPEEX_AEC 0 + #define PJMEDIA_HAS_SPEEX_AEC 0 /* Previously, resampling is disabled due to performance reason and * this condition prevented some 'light' wideband codecs (e.g: G722.1) @@ -153,40 +153,40 @@ * using small filter. For example PJSUA_DEFAULT_CODEC_QUALITY must * be set to 3 or 4 so pjsua-lib will apply small filter resampling. */ - //#define PJMEDIA_RESAMPLE_IMP PJMEDIA_RESAMPLE_NONE - #define PJMEDIA_RESAMPLE_IMP PJMEDIA_RESAMPLE_LIBRESAMPLE + //#define PJMEDIA_RESAMPLE_IMP PJMEDIA_RESAMPLE_NONE + #define PJMEDIA_RESAMPLE_IMP PJMEDIA_RESAMPLE_LIBRESAMPLE /* Use the lighter WSOLA implementation */ - #define PJMEDIA_WSOLA_IMP PJMEDIA_WSOLA_IMP_WSOLA_LITE + #define PJMEDIA_WSOLA_IMP PJMEDIA_WSOLA_IMP_WSOLA_LITE /* We probably need more buffers especially if MDA audio backend * is used, so increase the limit */ - #define PJMEDIA_SOUND_BUFFER_COUNT 32 + #define PJMEDIA_SOUND_BUFFER_COUNT 32 /* * PJSIP settings. */ /* Disable safe module access, since we don't use multithreading */ - #define PJSIP_SAFE_MODULE 0 + #define PJSIP_SAFE_MODULE 0 /* Use large enough packet size */ - #define PJSIP_MAX_PKT_LEN 2000 + #define PJSIP_MAX_PKT_LEN 2000 /* Symbian has problem with too many large blocks */ - #define PJSIP_POOL_LEN_ENDPT 1000 - #define PJSIP_POOL_INC_ENDPT 1000 - #define PJSIP_POOL_RDATA_LEN 2000 - #define PJSIP_POOL_RDATA_INC 2000 - #define PJSIP_POOL_LEN_TDATA 2000 - #define PJSIP_POOL_INC_TDATA 512 - #define PJSIP_POOL_LEN_UA 2000 - #define PJSIP_POOL_INC_UA 1000 - #define PJSIP_POOL_TSX_LAYER_LEN 256 - #define PJSIP_POOL_TSX_LAYER_INC 256 - #define PJSIP_POOL_TSX_LEN 512 - #define PJSIP_POOL_TSX_INC 128 + #define PJSIP_POOL_LEN_ENDPT 1000 + #define PJSIP_POOL_INC_ENDPT 1000 + #define PJSIP_POOL_RDATA_LEN 2000 + #define PJSIP_POOL_RDATA_INC 2000 + #define PJSIP_POOL_LEN_TDATA 2000 + #define PJSIP_POOL_INC_TDATA 512 + #define PJSIP_POOL_LEN_UA 2000 + #define PJSIP_POOL_INC_UA 1000 + #define PJSIP_POOL_TSX_LAYER_LEN 256 + #define PJSIP_POOL_TSX_LAYER_INC 256 + #define PJSIP_POOL_TSX_LEN 512 + #define PJSIP_POOL_TSX_INC 128 /* * PJSUA settings. @@ -195,19 +195,19 @@ /* Default codec quality, previously was set to 5, however it is now * set to 4 to make sure pjsua instantiates resampler with small filter. */ - #define PJSUA_DEFAULT_CODEC_QUALITY 4 + #define PJSUA_DEFAULT_CODEC_QUALITY 4 /* Set maximum number of dialog/transaction/calls to minimum */ - #define PJSIP_MAX_TSX_COUNT 31 - #define PJSIP_MAX_DIALOG_COUNT 31 - #define PJSUA_MAX_CALLS 4 + #define PJSIP_MAX_TSX_COUNT 31 + #define PJSIP_MAX_DIALOG_COUNT 31 + #define PJSUA_MAX_CALLS 4 /* Other pjsua settings */ - #define PJSUA_MAX_ACC 4 - #define PJSUA_MAX_PLAYERS 4 - #define PJSUA_MAX_RECORDERS 4 - #define PJSUA_MAX_CONF_PORTS (PJSUA_MAX_CALLS+2*PJSUA_MAX_PLAYERS) - #define PJSUA_MAX_BUDDIES 32 + #define PJSUA_MAX_ACC 4 + #define PJSUA_MAX_PLAYERS 4 + #define PJSUA_MAX_RECORDERS 4 + #define PJSUA_MAX_CONF_PORTS (PJSUA_MAX_CALLS+2*PJSUA_MAX_PLAYERS) + #define PJSUA_MAX_BUDDIES 32 #endif @@ -220,22 +220,22 @@ #ifdef PJ_CONFIG_NOKIA_APS_DIRECT /* MUST use switchboard rather than the conference bridge */ - #define PJMEDIA_CONF_USE_SWITCH_BOARD 1 + #define PJMEDIA_CONF_USE_SWITCH_BOARD 1 /* Enable APS sound device backend and disable MDA & VAS */ - #define PJMEDIA_AUDIO_DEV_HAS_SYMB_MDA 0 - #define PJMEDIA_AUDIO_DEV_HAS_SYMB_APS 1 - #define PJMEDIA_AUDIO_DEV_HAS_SYMB_VAS 0 + #define PJMEDIA_AUDIO_DEV_HAS_SYMB_MDA 0 + #define PJMEDIA_AUDIO_DEV_HAS_SYMB_APS 1 + #define PJMEDIA_AUDIO_DEV_HAS_SYMB_VAS 0 /* Enable passthrough codec framework */ - #define PJMEDIA_HAS_PASSTHROUGH_CODECS 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODECS 1 /* And selectively enable which codecs are supported by the handset */ - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMU 1 - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMA 1 - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR 1 - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_G729 1 - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_ILBC 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMU 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMA 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_G729 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_ILBC 1 #endif @@ -249,22 +249,22 @@ #ifdef PJ_CONFIG_NOKIA_VAS_DIRECT /* MUST use switchboard rather than the conference bridge */ - #define PJMEDIA_CONF_USE_SWITCH_BOARD 1 + #define PJMEDIA_CONF_USE_SWITCH_BOARD 1 /* Enable VAS sound device backend and disable MDA & APS */ - #define PJMEDIA_AUDIO_DEV_HAS_SYMB_MDA 0 - #define PJMEDIA_AUDIO_DEV_HAS_SYMB_APS 0 - #define PJMEDIA_AUDIO_DEV_HAS_SYMB_VAS 1 + #define PJMEDIA_AUDIO_DEV_HAS_SYMB_MDA 0 + #define PJMEDIA_AUDIO_DEV_HAS_SYMB_APS 0 + #define PJMEDIA_AUDIO_DEV_HAS_SYMB_VAS 1 /* Enable passthrough codec framework */ - #define PJMEDIA_HAS_PASSTHROUGH_CODECS 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODECS 1 /* And selectively enable which codecs are supported by the handset */ - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMU 1 - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMA 1 - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR 1 - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_G729 1 - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_ILBC 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMU 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMA 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_G729 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_ILBC 1 #endif @@ -276,21 +276,21 @@ #ifdef PJ_CONFIG_WIN32_WMME_DIRECT /* MUST use switchboard rather than the conference bridge */ - #define PJMEDIA_CONF_USE_SWITCH_BOARD 1 + #define PJMEDIA_CONF_USE_SWITCH_BOARD 1 /* Only WMME supports the "direct" feature */ - #define PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO 0 - #define PJMEDIA_AUDIO_DEV_HAS_WMME 1 + #define PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO 0 + #define PJMEDIA_AUDIO_DEV_HAS_WMME 1 /* Enable passthrough codec framework */ - #define PJMEDIA_HAS_PASSTHROUGH_CODECS 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODECS 1 /* Only PCMA and PCMU are supported by WMME-direct */ - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMU 1 - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMA 1 - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR 0 - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_G729 0 - #define PJMEDIA_HAS_PASSTHROUGH_CODEC_ILBC 0 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMU 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMA 1 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR 0 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_G729 0 + #define PJMEDIA_HAS_PASSTHROUGH_CODEC_ILBC 0 #endif @@ -305,37 +305,37 @@ /* Both armv6 and armv7 has FP hardware support. * See https://github.com/pjsip/pjproject/issues/1589 for more info */ - #define PJ_HAS_FLOATING_POINT 1 + #define PJ_HAS_FLOATING_POINT 1 /* * PJMEDIA settings */ /* We have our own native CoreAudio backend */ - #define PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO 0 - #define PJMEDIA_AUDIO_DEV_HAS_WMME 0 - #define PJMEDIA_AUDIO_DEV_HAS_COREAUDIO 1 + #define PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO 0 + #define PJMEDIA_AUDIO_DEV_HAS_WMME 0 + #define PJMEDIA_AUDIO_DEV_HAS_COREAUDIO 1 /* The CoreAudio backend has built-in echo canceller! */ #define PJMEDIA_HAS_SPEEX_AEC 0 /* Disable some codecs */ - #define PJMEDIA_HAS_L16_CODEC 0 - //#define PJMEDIA_HAS_G722_CODEC 0 + #define PJMEDIA_HAS_L16_CODEC 0 + //#define PJMEDIA_HAS_G722_CODEC 0 /* Use the built-in CoreAudio's iLBC codec (yay!) */ - #define PJMEDIA_HAS_ILBC_CODEC 1 - #define PJMEDIA_ILBC_CODEC_USE_COREAUDIO 1 + #define PJMEDIA_HAS_ILBC_CODEC 1 + #define PJMEDIA_ILBC_CODEC_USE_COREAUDIO 1 /* Fine tune Speex's default settings for best performance/quality */ - #define PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY 5 + #define PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY 5 /* * PJSIP settings. */ /* Increase allowable packet size, just in case */ - //#define PJSIP_MAX_PKT_LEN 2000 + //#define PJSIP_MAX_PKT_LEN 2000 /* * PJSUA settings. @@ -344,19 +344,19 @@ /* Default codec quality, previously was set to 5, however it is now * set to 4 to make sure pjsua instantiates resampler with small filter. */ - #define PJSUA_DEFAULT_CODEC_QUALITY 4 + #define PJSUA_DEFAULT_CODEC_QUALITY 4 /* Set maximum number of dialog/transaction/calls to minimum */ - #define PJSIP_MAX_TSX_COUNT 31 - #define PJSIP_MAX_DIALOG_COUNT 31 - #define PJSUA_MAX_CALLS 4 + #define PJSIP_MAX_TSX_COUNT 31 + #define PJSIP_MAX_DIALOG_COUNT 31 + #define PJSUA_MAX_CALLS 4 /* Other pjsua settings */ - #define PJSUA_MAX_ACC 4 - #define PJSUA_MAX_PLAYERS 4 - #define PJSUA_MAX_RECORDERS 4 - #define PJSUA_MAX_CONF_PORTS (PJSUA_MAX_CALLS+2*PJSUA_MAX_PLAYERS) - #define PJSUA_MAX_BUDDIES 32 + #define PJSUA_MAX_ACC 4 + #define PJSUA_MAX_PLAYERS 4 + #define PJSUA_MAX_RECORDERS 4 + #define PJSUA_MAX_CONF_PORTS (PJSUA_MAX_CALLS+2*PJSUA_MAX_PLAYERS) + #define PJSUA_MAX_BUDDIES 32 #endif @@ -371,31 +371,31 @@ /* Disable floating point support */ #undef PJ_HAS_FLOATING_POINT - #define PJ_HAS_FLOATING_POINT 0 + #define PJ_HAS_FLOATING_POINT 0 /* * PJMEDIA settings */ /* We have our own OpenSL ES backend */ - #define PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO 0 - #define PJMEDIA_AUDIO_DEV_HAS_WMME 0 + #define PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO 0 + #define PJMEDIA_AUDIO_DEV_HAS_WMME 0 #define PJMEDIA_AUDIO_DEV_HAS_OPENSL 0 - #define PJMEDIA_AUDIO_DEV_HAS_ANDROID_JNI 1 + #define PJMEDIA_AUDIO_DEV_HAS_ANDROID_JNI 1 /* Disable some codecs */ - #define PJMEDIA_HAS_L16_CODEC 0 - //#define PJMEDIA_HAS_G722_CODEC 0 + #define PJMEDIA_HAS_L16_CODEC 0 + //#define PJMEDIA_HAS_G722_CODEC 0 /* Fine tune Speex's default settings for best performance/quality */ - #define PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY 5 + #define PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY 5 /* * PJSIP settings. */ /* Increase allowable packet size, just in case */ - //#define PJSIP_MAX_PKT_LEN 2000 + //#define PJSIP_MAX_PKT_LEN 2000 /* * PJSUA settings. @@ -404,22 +404,22 @@ /* Default codec quality, previously was set to 5, however it is now * set to 4 to make sure pjsua instantiates resampler with small filter. */ - #define PJSUA_DEFAULT_CODEC_QUALITY 4 + #define PJSUA_DEFAULT_CODEC_QUALITY 4 /* Set maximum number of dialog/transaction/calls to minimum */ - #define PJSIP_MAX_TSX_COUNT 31 - #define PJSIP_MAX_DIALOG_COUNT 31 - #define PJSUA_MAX_CALLS 4 + #define PJSIP_MAX_TSX_COUNT 31 + #define PJSIP_MAX_DIALOG_COUNT 31 + #define PJSUA_MAX_CALLS 4 /* Separate worker thread for timer and ioqueue */ - // #define PJSUA_SEPARATE_WORKER_FOR_TIMER 1 + // #define PJSUA_SEPARATE_WORKER_FOR_TIMER 1 /* Other pjsua settings */ - #define PJSUA_MAX_ACC 4 - #define PJSUA_MAX_PLAYERS 4 - #define PJSUA_MAX_RECORDERS 4 - #define PJSUA_MAX_CONF_PORTS (PJSUA_MAX_CALLS+2*PJSUA_MAX_PLAYERS) - #define PJSUA_MAX_BUDDIES 32 + #define PJSUA_MAX_ACC 4 + #define PJSUA_MAX_PLAYERS 4 + #define PJSUA_MAX_RECORDERS 4 + #define PJSUA_MAX_CONF_PORTS (PJSUA_MAX_CALLS+2*PJSUA_MAX_PLAYERS) + #define PJSUA_MAX_BUDDIES 32 #endif @@ -428,14 +428,14 @@ */ #if defined(PJ_CONFIG_BB10) && PJ_CONFIG_BB10 /* Quality 3 - 4 to use resampling small filter */ - #define PJSUA_DEFAULT_CODEC_QUALITY 4 - #define PJMEDIA_HAS_LEGACY_SOUND_API 0 + #define PJSUA_DEFAULT_CODEC_QUALITY 4 + #define PJMEDIA_HAS_LEGACY_SOUND_API 0 #undef PJMEDIA_HAS_SPEEX_AEC - #define PJMEDIA_HAS_SPEEX_AEC 0 + #define PJMEDIA_HAS_SPEEX_AEC 0 #undef PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO - #define PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO 0 + #define PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO 0 #undef PJMEDIA_AUDIO_DEV_HAS_ALSA - #define PJMEDIA_AUDIO_DEV_HAS_ALSA 0 + #define PJMEDIA_AUDIO_DEV_HAS_ALSA 0 #endif @@ -445,41 +445,41 @@ #ifdef PJ_CONFIG_MINIMAL_SIZE # undef PJ_OS_HAS_CHECK_STACK -# define PJ_OS_HAS_CHECK_STACK 0 -# define PJ_LOG_MAX_LEVEL 0 -# define PJ_HAS_ERROR_STRING 0 +# define PJ_OS_HAS_CHECK_STACK 0 +# define PJ_LOG_MAX_LEVEL 0 +# define PJ_HAS_ERROR_STRING 0 # undef PJ_IOQUEUE_MAX_HANDLES /* Putting max handles to lower than 32 will make pj_fd_set_t size smaller * than native fdset_t and will trigger assertion on sock_select.c. */ -# define PJ_IOQUEUE_MAX_HANDLES 32 -# define PJ_CRC32_HAS_TABLES 0 -# define PJSIP_MAX_TSX_COUNT 15 -# define PJSIP_MAX_DIALOG_COUNT 15 -# define PJSIP_UDP_SO_SNDBUF_SIZE 4000 -# define PJSIP_UDP_SO_RCVBUF_SIZE 4000 -# define PJMEDIA_HAS_ALAW_ULAW_TABLE 0 +# define PJ_IOQUEUE_MAX_HANDLES 32 +# define PJ_CRC32_HAS_TABLES 0 +# define PJSIP_MAX_TSX_COUNT 15 +# define PJSIP_MAX_DIALOG_COUNT 15 +# define PJSIP_UDP_SO_SNDBUF_SIZE 4000 +# define PJSIP_UDP_SO_RCVBUF_SIZE 4000 +# define PJMEDIA_HAS_ALAW_ULAW_TABLE 0 #elif defined(PJ_CONFIG_MAXIMUM_SPEED) -# define PJ_SCANNER_USE_BITWISE 0 +# define PJ_SCANNER_USE_BITWISE 0 # undef PJ_OS_HAS_CHECK_STACK -# define PJ_OS_HAS_CHECK_STACK 0 -# define PJ_LOG_MAX_LEVEL 3 -# define PJ_IOQUEUE_MAX_HANDLES 5000 -# define PJSIP_MAX_TSX_COUNT ((640*1024)-1) -# define PJSIP_MAX_DIALOG_COUNT ((640*1024)-1) -# define PJSIP_UDP_SO_SNDBUF_SIZE (24*1024*1024) -# define PJSIP_UDP_SO_RCVBUF_SIZE (24*1024*1024) -# define PJ_DEBUG 0 -# define PJSIP_SAFE_MODULE 0 -# define PJ_HAS_STRICMP_ALNUM 0 -# define PJSIP_UNESCAPE_IN_PLACE 1 +# define PJ_OS_HAS_CHECK_STACK 0 +# define PJ_LOG_MAX_LEVEL 3 +# define PJ_IOQUEUE_MAX_HANDLES 5000 +# define PJSIP_MAX_TSX_COUNT ((640*1024)-1) +# define PJSIP_MAX_DIALOG_COUNT ((640*1024)-1) +# define PJSIP_UDP_SO_SNDBUF_SIZE (24*1024*1024) +# define PJSIP_UDP_SO_RCVBUF_SIZE (24*1024*1024) +# define PJ_DEBUG 0 +# define PJSIP_SAFE_MODULE 0 +# define PJ_HAS_STRICMP_ALNUM 0 +# define PJSIP_UNESCAPE_IN_PLACE 1 # if defined(PJ_WIN32) || defined(PJ_WIN64) -# define PJSIP_MAX_NET_EVENTS 10 +# define PJSIP_MAX_NET_EVENTS 10 # endif -# define PJSUA_MAX_CALLS 512 +# define PJSUA_MAX_CALLS 512 #endif diff --git a/pjlib/include/pj/ctype.h b/pjlib/include/pj/ctype.h index acf4ad7d87..915abb5ffd 100644 --- a/pjlib/include/pj/ctype.h +++ b/pjlib/include/pj/ctype.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -138,13 +137,13 @@ PJ_INLINE(int) pj_isxdigit(unsigned char c){ return isxdigit(c); } * Array of hex digits, in lowerspace. */ /*extern char pj_hex_digits[];*/ -#define pj_hex_digits "0123456789abcdef" +#define pj_hex_digits "0123456789abcdef" /** * Convert a value to hex representation. - * @param value Integral value to convert. - * @param p Buffer to hold the hex representation, which must be - * at least two bytes length. + * @param value Integral value to convert. + * @param p Buffer to hold the hex representation, which must be + * at least two bytes length. */ PJ_INLINE(void) pj_val_to_hex_digit(unsigned value, char *p) { @@ -154,22 +153,22 @@ PJ_INLINE(void) pj_val_to_hex_digit(unsigned value, char *p) /** * Convert hex digit c to integral value. - * @param c The hex digit character. - * @return The integral value between 0 and 15. + * @param c The hex digit character. + * @return The integral value between 0 and 15. */ PJ_INLINE(unsigned) pj_hex_digit_to_val(unsigned char c) { if (c <= '9') - return (c-'0') & 0x0F; + return (c-'0') & 0x0F; else if (c <= 'F') - return (c-'A'+10) & 0x0F; + return (c-'A'+10) & 0x0F; else - return (c-'a'+10) & 0x0F; + return (c-'a'+10) & 0x0F; } /** @} */ PJ_END_DECL -#endif /* __PJ_CTYPE_H__ */ +#endif /* __PJ_CTYPE_H__ */ diff --git a/pjlib/include/pj/doxygen.h b/pjlib/include/pj/doxygen.h index 2f0ea832eb..da85afae88 100644 --- a/pjlib/include/pj/doxygen.h +++ b/pjlib/include/pj/doxygen.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,7 +26,7 @@ /*////////////////////////////////////////////////////////////////////////// */ /* - INTRODUCTION PAGE + INTRODUCTION PAGE */ /** @@ -444,7 +443,7 @@ /*////////////////////////////////////////////////////////////////////////// */ /* - BUILDING AND INSTALLING PJLIB + BUILDING AND INSTALLING PJLIB */ @@ -580,10 +579,10 @@ * * For Linux kernel target, you are also required to declare the following * variables in this file: - * - \c KERNEL_DIR: full path of kernel source tree. - * - \c KERNEL_ARCH: kernel ARCH options (e.g. "ARCH=um"), or leave blank - * for default. - * - \c PJPROJECT_DIR: full path of PJPROJECT source tree. + * - \c KERNEL_DIR: full path of kernel source tree. + * - \c KERNEL_ARCH: kernel ARCH options (e.g. "ARCH=um"), or leave blank + * for default. + * - \c PJPROJECT_DIR: full path of PJPROJECT source tree. * * Apart from these, there are also additional steps required to build * Linux kernel target, which will be explained in \ref linux_kern_target_subsec. @@ -666,7 +665,7 @@ * * For building PJLIB for Linux kernel target, there are additional steps required. * In general, the additional tasks are: - * - Declare some more variables in build.mak file (this + * - Declare some more variables in build.mak file (this * has been explained in \ref build_mak_sec above). * - Perform these two small modifications in kernel source tree. * @@ -692,9 +691,9 @@ * the additional symbols to be exported in extra-exports.c file, and add * a this file to be compiled into the kernel: * - * - Copy the file extra-exports.c from pjlib/src/pj - * directory to $KERNEL_SRC/kernel/ directory. - * - Edit Makefile in that directory, and add this line + * - Copy the file extra-exports.c from pjlib/src/pj + * directory to $KERNEL_SRC/kernel/ directory. + * - Edit Makefile in that directory, and add this line * somewhere after the declaration of that variable: \verbatim obj-y += extra-exports.o @@ -924,11 +923,11 @@ export OS_SOURCES := # pjlib/build/os-xos.mak: # XOS specific configuration for PJLIB. # -export PJLIB_OBJS += os_core_xos.o \ +export PJLIB_OBJS += os_core_xos.o \ os_error_unix.o \ os_time_ansi.o -export TEST_OBJS += main.o -export TARGETS = pjlib pjlib-test +export TEST_OBJS += main.o +export TARGETS = pjlib pjlib-test \endverbatim * * @subsection new_target_src_sec Create and Edit Source Files @@ -992,5 +991,5 @@ export TARGETS = pjlib pjlib-test * to edit the file or create new file etc. */ -#endif /* __PJ_DOXYGEN_H__ */ +#endif /* __PJ_DOXYGEN_H__ */ diff --git a/pjlib/include/pj/errno.h b/pjlib/include/pj/errno.h index 4652bd1e62..e106121030 100644 --- a/pjlib/include/pj/errno.h +++ b/pjlib/include/pj/errno.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -88,35 +87,35 @@ PJ_BEGIN_DECL * Buffer for title string of #PJ_PERROR(). */ #ifndef PJ_PERROR_TITLE_BUF_SIZE -# define PJ_PERROR_TITLE_BUF_SIZE 120 +# define PJ_PERROR_TITLE_BUF_SIZE 120 #endif /** * Get the last platform error/status, folded into pj_status_t. - * @return OS dependent error code, folded into pj_status_t. - * @remark This function gets errno, or calls GetLastError() function and - * convert the code into pj_status_t with PJ_STATUS_FROM_OS. Do - * not call this for socket functions! - * @see pj_get_netos_error() + * @return OS dependent error code, folded into pj_status_t. + * @remark This function gets errno, or calls GetLastError() function and + * convert the code into pj_status_t with PJ_STATUS_FROM_OS. Do + * not call this for socket functions! + * @see pj_get_netos_error() */ PJ_DECL(pj_status_t) pj_get_os_error(void); /** * Set last error. - * @param code pj_status_t + * @param code pj_status_t */ PJ_DECL(void) pj_set_os_error(pj_status_t code); /** * Get the last error from socket operations. - * @return Last socket error, folded into pj_status_t. + * @return Last socket error, folded into pj_status_t. */ PJ_DECL(pj_status_t) pj_get_netos_error(void); /** * Set error code. - * @param code pj_status_t. + * @param code pj_status_t. */ PJ_DECL(void) pj_set_netos_error(pj_status_t code); @@ -126,14 +125,14 @@ PJ_DECL(void) pj_set_netos_error(pj_status_t code); * string will be NULL terminated. * * @param statcode The error code. - * @param buf Buffer to hold the error message string. + * @param buf Buffer to hold the error message string. * @param bufsize Size of the buffer. * - * @return The error message as NULL terminated string, + * @return The error message as NULL terminated string, * wrapped with pj_str_t. */ PJ_DECL(pj_str_t) pj_strerror( pj_status_t statcode, - char *buf, pj_size_t bufsize); + char *buf, pj_size_t bufsize); /** * A utility macro to print error message pertaining to the specified error @@ -155,17 +154,17 @@ PJ_DECL(pj_str_t) pj_strerror( pj_status_t statcode, * * @see pj_perror() * - * @param level The logging verbosity level, valid values are 0-6. Lower - * number indicates higher importance, with level zero - * indicates fatal error. Only numeral argument is - * permitted (e.g. not variable). - * @param arg Enclosed 'printf' like arguments, with the following - * arguments: - * - the sender (NULL terminated string), - * - the error code (pj_status_t) - * - the format string (title_fmt), and - * - optional variable number of arguments suitable for the - * format string. + * @param level The logging verbosity level, valid values are 0-6. Lower + * number indicates higher importance, with level zero + * indicates fatal error. Only numeral argument is + * permitted (e.g. not variable). + * @param arg Enclosed 'printf' like arguments, with the following + * arguments: + * - the sender (NULL terminated string), + * - the error code (pj_status_t) + * - the format string (title_fmt), and + * - optional variable number of arguments suitable for the + * format string. * * Sample: * \verbatim @@ -173,9 +172,9 @@ PJ_DECL(pj_str_t) pj_strerror( pj_status_t statcode, \endverbatim * @hideinitializer */ -#define PJ_PERROR(level,arg) do { \ - pj_perror_wrapper_##level(arg); \ - } while (0) +#define PJ_PERROR(level,arg) do { \ + pj_perror_wrapper_##level(arg); \ + } while (0) /** * A utility function to print error message pertaining to the specified error @@ -200,17 +199,17 @@ PJ_DECL(pj_str_t) pj_strerror( pj_status_t statcode, * @see PJ_PERROR() */ PJ_DECL(void) pj_perror(int log_level, const char *sender, pj_status_t status, - const char *title_fmt, ...); + const char *title_fmt, ...); /** * Type of callback to be specified in #pj_register_strerror() * - * @param e The error code to lookup. - * @param msg Buffer to store the error message. - * @param max Length of the buffer. + * @param e The error code to lookup. + * @param msg Buffer to store the error message. + * @param max Length of the buffer. * - * @return The error string. + * @return The error string. */ typedef pj_str_t (*pj_error_callback)(pj_status_t e, char *msg, pj_size_t max); @@ -221,22 +220,22 @@ typedef pj_str_t (*pj_error_callback)(pj_status_t e, char *msg, pj_size_t max); * for the specified error code range. This handler will be called * by #pj_strerror(). * - * @param start_code The starting error code where the handler should - * be called to retrieve the error message. - * @param err_space The size of error space. The error code range then - * will fall in start_code to start_code+err_space-1 - * range. - * @param f The handler to be called when #pj_strerror() is - * supplied with error code that falls into this range. + * @param start_code The starting error code where the handler should + * be called to retrieve the error message. + * @param err_space The size of error space. The error code range then + * will fall in start_code to start_code+err_space-1 + * range. + * @param f The handler to be called when #pj_strerror() is + * supplied with error code that falls into this range. * - * @return PJ_SUCCESS or the specified error code. The - * registration may fail when the error space has been - * occupied by other handler, or when there are too many - * handlers registered to PJLIB. + * @return PJ_SUCCESS or the specified error code. The + * registration may fail when the error space has been + * occupied by other handler, or when there are too many + * handlers registered to PJLIB. */ PJ_DECL(pj_status_t) pj_register_strerror(pj_status_t start_code, - pj_status_t err_space, - pj_error_callback f); + pj_status_t err_space, + pj_error_callback f); /** * @hideinitializer @@ -252,12 +251,12 @@ PJ_DECL(pj_status_t) pj_register_strerror(pj_status_t start_code, * the operating system doesn't report error codes properly. * * @param os_code Platform OS error code. This value may be evaluated - * more than once. - * @return The platform os error code folded into pj_status_t. + * more than once. + * @return The platform os error code folded into pj_status_t. */ #ifndef PJ_RETURN_OS_ERROR # define PJ_RETURN_OS_ERROR(os_code) (os_code ? \ - PJ_STATUS_FROM_OS(os_code) : -1) + PJ_STATUS_FROM_OS(os_code) : -1) #endif @@ -265,10 +264,10 @@ PJ_DECL(pj_status_t) pj_register_strerror(pj_status_t start_code, * @hideinitializer * Fold a platform specific error into an pj_status_t code. * - * @param e The platform os error code. - * @return pj_status_t - * @warning Macro implementation; the syserr argument may be evaluated - * multiple times. + * @param e The platform os error code. + * @return pj_status_t + * @warning Macro implementation; the syserr argument may be evaluated + * multiple times. */ #if PJ_NATIVE_ERR_POSITIVE # define PJ_STATUS_FROM_OS(e) (e == 0 ? PJ_SUCCESS : e + PJ_ERRNO_START_SYS) @@ -280,11 +279,11 @@ PJ_DECL(pj_status_t) pj_register_strerror(pj_status_t start_code, * @hideinitializer * Fold an pj_status_t code back to the native platform defined error. * - * @param e The pj_status_t folded platform os error code. - * @return pj_os_err_type - * @warning macro implementation; the statcode argument may be evaluated - * multiple times. If the statcode was not created by - * pj_get_os_error or PJ_STATUS_FROM_OS, the results are undefined. + * @param e The pj_status_t folded platform os error code. + * @return pj_os_err_type + * @warning macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by + * pj_get_os_error or PJ_STATUS_FROM_OS, the results are undefined. */ #if PJ_NATIVE_ERR_POSITIVE # define PJ_STATUS_TO_OS(e) (e == 0 ? PJ_SUCCESS : e - PJ_ERRNO_START_SYS) @@ -303,8 +302,8 @@ PJ_DECL(pj_status_t) pj_register_strerror(pj_status_t start_code, * Use this macro to generate error message text for your error code, * so that they look uniformly as the rest of the libraries. * - * @param code The error code - * @param msg The error test. + * @param code The error code + * @param msg The error test. */ #ifndef PJ_BUILD_ERR # define PJ_BUILD_ERR(code,msg) { code, msg " (" #code ")" } @@ -315,47 +314,47 @@ PJ_DECL(pj_status_t) pj_register_strerror(pj_status_t start_code, * @hideinitializer * Unknown error has been reported. */ -#define PJ_EUNKNOWN (PJ_ERRNO_START_STATUS + 1) /* 70001 */ +#define PJ_EUNKNOWN (PJ_ERRNO_START_STATUS + 1) /* 70001 */ /** * @hideinitializer * The operation is pending and will be completed later. */ -#define PJ_EPENDING (PJ_ERRNO_START_STATUS + 2) /* 70002 */ +#define PJ_EPENDING (PJ_ERRNO_START_STATUS + 2) /* 70002 */ /** * @hideinitializer * Too many connecting sockets. */ -#define PJ_ETOOMANYCONN (PJ_ERRNO_START_STATUS + 3) /* 70003 */ +#define PJ_ETOOMANYCONN (PJ_ERRNO_START_STATUS + 3) /* 70003 */ /** * @hideinitializer * Invalid argument. */ -#define PJ_EINVAL (PJ_ERRNO_START_STATUS + 4) /* 70004 */ +#define PJ_EINVAL (PJ_ERRNO_START_STATUS + 4) /* 70004 */ /** * @hideinitializer * Name too long (eg. hostname too long). */ -#define PJ_ENAMETOOLONG (PJ_ERRNO_START_STATUS + 5) /* 70005 */ +#define PJ_ENAMETOOLONG (PJ_ERRNO_START_STATUS + 5) /* 70005 */ /** * @hideinitializer * Not found. */ -#define PJ_ENOTFOUND (PJ_ERRNO_START_STATUS + 6) /* 70006 */ +#define PJ_ENOTFOUND (PJ_ERRNO_START_STATUS + 6) /* 70006 */ /** * @hideinitializer * Not enough memory. */ -#define PJ_ENOMEM (PJ_ERRNO_START_STATUS + 7) /* 70007 */ +#define PJ_ENOMEM (PJ_ERRNO_START_STATUS + 7) /* 70007 */ /** * @hideinitializer * Bug detected! */ -#define PJ_EBUG (PJ_ERRNO_START_STATUS + 8) /* 70008 */ +#define PJ_EBUG (PJ_ERRNO_START_STATUS + 8) /* 70008 */ /** * @hideinitializer * Operation timed out. */ -#define PJ_ETIMEDOUT (PJ_ERRNO_START_STATUS + 9) /* 70009 */ +#define PJ_ETIMEDOUT (PJ_ERRNO_START_STATUS + 9) /* 70009 */ /** * @hideinitializer * Too many objects. @@ -370,17 +369,17 @@ PJ_DECL(pj_status_t) pj_register_strerror(pj_status_t start_code, * @hideinitializer * The specified option is not supported. */ -#define PJ_ENOTSUP (PJ_ERRNO_START_STATUS + 12)/* 70012 */ +#define PJ_ENOTSUP (PJ_ERRNO_START_STATUS + 12)/* 70012 */ /** * @hideinitializer * Invalid operation. */ -#define PJ_EINVALIDOP (PJ_ERRNO_START_STATUS + 13)/* 70013 */ +#define PJ_EINVALIDOP (PJ_ERRNO_START_STATUS + 13)/* 70013 */ /** * @hideinitializer * Operation is cancelled. */ -#define PJ_ECANCELLED (PJ_ERRNO_START_STATUS + 14)/* 70014 */ +#define PJ_ECANCELLED (PJ_ERRNO_START_STATUS + 14)/* 70014 */ /** * @hideinitializer * Object already exists. @@ -390,48 +389,48 @@ PJ_DECL(pj_status_t) pj_register_strerror(pj_status_t start_code, * @hideinitializer * End of file. */ -#define PJ_EEOF (PJ_ERRNO_START_STATUS + 16)/* 70016 */ +#define PJ_EEOF (PJ_ERRNO_START_STATUS + 16)/* 70016 */ /** * @hideinitializer * Size is too big. */ -#define PJ_ETOOBIG (PJ_ERRNO_START_STATUS + 17)/* 70017 */ +#define PJ_ETOOBIG (PJ_ERRNO_START_STATUS + 17)/* 70017 */ /** * @hideinitializer * Error in gethostbyname(). This is a generic error returned when * gethostbyname() has returned an error. */ -#define PJ_ERESOLVE (PJ_ERRNO_START_STATUS + 18)/* 70018 */ +#define PJ_ERESOLVE (PJ_ERRNO_START_STATUS + 18)/* 70018 */ /** * @hideinitializer * Size is too small. */ -#define PJ_ETOOSMALL (PJ_ERRNO_START_STATUS + 19)/* 70019 */ +#define PJ_ETOOSMALL (PJ_ERRNO_START_STATUS + 19)/* 70019 */ /** * @hideinitializer * Ignored */ -#define PJ_EIGNORED (PJ_ERRNO_START_STATUS + 20)/* 70020 */ +#define PJ_EIGNORED (PJ_ERRNO_START_STATUS + 20)/* 70020 */ /** * @hideinitializer * IPv6 is not supported */ -#define PJ_EIPV6NOTSUP (PJ_ERRNO_START_STATUS + 21)/* 70021 */ +#define PJ_EIPV6NOTSUP (PJ_ERRNO_START_STATUS + 21)/* 70021 */ /** * @hideinitializer * Unsupported address family */ -#define PJ_EAFNOTSUP (PJ_ERRNO_START_STATUS + 22)/* 70022 */ +#define PJ_EAFNOTSUP (PJ_ERRNO_START_STATUS + 22)/* 70022 */ /** * @hideinitializer * Object no longer exists */ -#define PJ_EGONE (PJ_ERRNO_START_STATUS + 23)/* 70023 */ +#define PJ_EGONE (PJ_ERRNO_START_STATUS + 23)/* 70023 */ /** * @hideinitializer * Socket is stopped */ -#define PJ_ESOCKETSTOP (PJ_ERRNO_START_STATUS + 24)/* 70024 */ +#define PJ_ESOCKETSTOP (PJ_ERRNO_START_STATUS + 24)/* 70024 */ /** @} */ /* pj_errnum */ @@ -441,44 +440,44 @@ PJ_DECL(pj_status_t) pj_register_strerror(pj_status_t start_code, /** * PJ_ERRNO_START is where PJLIB specific error values start. */ -#define PJ_ERRNO_START 20000 +#define PJ_ERRNO_START 20000 /** * PJ_ERRNO_SPACE_SIZE is the maximum number of errors in one of * the error/status range below. */ -#define PJ_ERRNO_SPACE_SIZE 50000 +#define PJ_ERRNO_SPACE_SIZE 50000 /** * PJ_ERRNO_START_STATUS is where PJLIB specific status codes start. * Effectively the error in this class would be 70000 - 119000. */ -#define PJ_ERRNO_START_STATUS (PJ_ERRNO_START + PJ_ERRNO_SPACE_SIZE) +#define PJ_ERRNO_START_STATUS (PJ_ERRNO_START + PJ_ERRNO_SPACE_SIZE) /** * PJ_ERRNO_START_SYS converts platform specific error codes into * pj_status_t values. * Effectively the error in this class would be 120000 - 169000. */ -#define PJ_ERRNO_START_SYS (PJ_ERRNO_START_STATUS + PJ_ERRNO_SPACE_SIZE) +#define PJ_ERRNO_START_SYS (PJ_ERRNO_START_STATUS + PJ_ERRNO_SPACE_SIZE) /** * PJ_ERRNO_START_USER are reserved for applications that use error * codes along with PJLIB codes. * Effectively the error in this class would be 170000 - 219000. */ -#define PJ_ERRNO_START_USER (PJ_ERRNO_START_SYS + PJ_ERRNO_SPACE_SIZE) +#define PJ_ERRNO_START_USER (PJ_ERRNO_START_SYS + PJ_ERRNO_SPACE_SIZE) /* * Below are list of error spaces that have been taken so far: - * - PJSIP_ERRNO_START (PJ_ERRNO_START_USER) - * - PJMEDIA_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE) - * - PJSIP_SIMPLE_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*2) - * - PJLIB_UTIL_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*3) - * - PJNATH_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*4) + * - PJSIP_ERRNO_START (PJ_ERRNO_START_USER) + * - PJMEDIA_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE) + * - PJSIP_SIMPLE_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*2) + * - PJLIB_UTIL_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*3) + * - PJNATH_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*4) * - PJMEDIA_AUDIODEV_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*5) - * - PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*6) + * - PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*6) * - PJMEDIA_VIDEODEV_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*7) */ @@ -495,10 +494,10 @@ void pj_errno_clear_handlers(void); * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 1 - #define pj_perror_wrapper_1(arg) pj_perror_1 arg + #define pj_perror_wrapper_1(arg) pj_perror_1 arg /** Internal function. */ PJ_DECL(void) pj_perror_1(const char *sender, pj_status_t status, - const char *title_fmt, ...); + const char *title_fmt, ...); #else #define pj_perror_wrapper_1(arg) #endif @@ -510,10 +509,10 @@ void pj_errno_clear_handlers(void); * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 2 - #define pj_perror_wrapper_2(arg) pj_perror_2 arg + #define pj_perror_wrapper_2(arg) pj_perror_2 arg /** Internal function. */ PJ_DECL(void) pj_perror_2(const char *sender, pj_status_t status, - const char *title_fmt, ...); + const char *title_fmt, ...); #else #define pj_perror_wrapper_2(arg) #endif @@ -525,10 +524,10 @@ void pj_errno_clear_handlers(void); * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 3 - #define pj_perror_wrapper_3(arg) pj_perror_3 arg + #define pj_perror_wrapper_3(arg) pj_perror_3 arg /** Internal function. */ PJ_DECL(void) pj_perror_3(const char *sender, pj_status_t status, - const char *title_fmt, ...); + const char *title_fmt, ...); #else #define pj_perror_wrapper_3(arg) #endif @@ -540,10 +539,10 @@ void pj_errno_clear_handlers(void); * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 4 - #define pj_perror_wrapper_4(arg) pj_perror_4 arg + #define pj_perror_wrapper_4(arg) pj_perror_4 arg /** Internal function. */ PJ_DECL(void) pj_perror_4(const char *sender, pj_status_t status, - const char *title_fmt, ...); + const char *title_fmt, ...); #else #define pj_perror_wrapper_4(arg) #endif @@ -555,10 +554,10 @@ void pj_errno_clear_handlers(void); * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 5 - #define pj_perror_wrapper_5(arg) pj_perror_5 arg + #define pj_perror_wrapper_5(arg) pj_perror_5 arg /** Internal function. */ PJ_DECL(void) pj_perror_5(const char *sender, pj_status_t status, - const char *title_fmt, ...); + const char *title_fmt, ...); #else #define pj_perror_wrapper_5(arg) #endif @@ -570,10 +569,10 @@ void pj_errno_clear_handlers(void); * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 6 - #define pj_perror_wrapper_6(arg) pj_perror_6 arg + #define pj_perror_wrapper_6(arg) pj_perror_6 arg /** Internal function. */ PJ_DECL(void) pj_perror_6(const char *sender, pj_status_t status, - const char *title_fmt, ...); + const char *title_fmt, ...); #else #define pj_perror_wrapper_6(arg) #endif @@ -583,5 +582,5 @@ void pj_errno_clear_handlers(void); PJ_END_DECL -#endif /* __PJ_ERRNO_H__ */ +#endif /* __PJ_ERRNO_H__ */ diff --git a/pjlib/include/pj/except.h b/pjlib/include/pj/except.h index 9369825c6f..33dedc9874 100644 --- a/pjlib/include/pj/except.h +++ b/pjlib/include/pj/except.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -86,9 +85,9 @@ PJ_BEGIN_DECL } PJ_CATCH_ANY { if (PJ_GET_EXCEPTION() == NO_MEMORY) - ...; // handle no memory situation - else if (PJ_GET_EXCEPTION() == SYNTAX_ERROR) - ...; // handle syntax error + ...; // handle no memory situation + else if (PJ_GET_EXCEPTION() == SYNTAX_ERROR) + ...; // handle syntax error } PJ_END; } @@ -123,31 +122,31 @@ PJ_BEGIN_DECL * - You CAN NOT make nested exception in one single function without using * a nested PJ_USE_EXCEPTION. Samples: \verbatim - void wrong_sample() - { - PJ_USE_EXCEPTION; - - PJ_TRY { - // Do stuffs - ... - } - PJ_CATCH_ANY { - // Do other stuffs - .... - .. - - // The following block is WRONG! You MUST declare - // PJ_USE_EXCEPTION once again in this block. - PJ_TRY { - .. - } - PJ_CATCH_ANY { - .. - } - PJ_END; - } - PJ_END; - } + void wrong_sample() + { + PJ_USE_EXCEPTION; + + PJ_TRY { + // Do stuffs + ... + } + PJ_CATCH_ANY { + // Do other stuffs + .... + .. + + // The following block is WRONG! You MUST declare + // PJ_USE_EXCEPTION once again in this block. + PJ_TRY { + .. + } + PJ_CATCH_ANY { + .. + } + PJ_END; + } + PJ_END; + } \endverbatim @@ -157,18 +156,18 @@ PJ_BEGIN_DECL * but rather in the subsequent execution of PJ_TRY block: \verbatim void wrong_sample() - { - PJ_USE_EXCEPTION; - - PJ_TRY { - // do some stuffs - ... - return; <======= DO NOT DO THIS! - } - PJ_CATCH_ANY { - } - PJ_END; - } + { + PJ_USE_EXCEPTION; + + PJ_TRY { + // do some stuffs + ... + return; <======= DO NOT DO THIS! + } + PJ_CATCH_ANY { + } + PJ_END; + } \endverbatim * - You can not provide more than PJ_CATCH or PJ_CATCH_ANY nor use PJ_CATCH @@ -279,13 +278,13 @@ pj_throw_exception_(pj_exception_id_t id) PJ_ATTR_NORETURN } #define PJ_USE_EXCEPTION -#define PJ_TRY __try -#define PJ_CATCH(id) __except(GetExceptionCode()==id ? \ - EXCEPTION_EXECUTE_HANDLER : \ - EXCEPTION_CONTINUE_SEARCH) -#define PJ_CATCH_ANY __except(EXCEPTION_EXECUTE_HANDLER) -#define PJ_END -#define PJ_THROW(id) pj_throw_exception_(id) +#define PJ_TRY __try +#define PJ_CATCH(id) __except(GetExceptionCode()==id ? \ + EXCEPTION_EXECUTE_HANDLER : \ + EXCEPTION_CONTINUE_SEARCH) +#define PJ_CATCH_ANY __except(EXCEPTION_EXECUTE_HANDLER) +#define PJ_END +#define PJ_THROW(id) pj_throw_exception_(id) #define PJ_GET_EXCEPTION() GetExceptionCode() @@ -308,24 +307,24 @@ class TPjException }; #define PJ_USE_EXCEPTION -#define PJ_TRY try -//#define PJ_CATCH(id) -#define PJ_CATCH_ANY catch (const TPjException & pj_excp_) +#define PJ_TRY try +//#define PJ_CATCH(id) +#define PJ_CATCH_ANY catch (const TPjException & pj_excp_) #define PJ_END -#define PJ_THROW(x_id) do { TPjException e; e.code_=x_id; throw e;} \ - while (0) -#define PJ_GET_EXCEPTION() pj_excp_.code_ +#define PJ_THROW(x_id) do { TPjException e; e.code_=x_id; throw e;} \ + while (0) +#define PJ_GET_EXCEPTION() pj_excp_.code_ #else #define PJ_USE_EXCEPTION -#define PJ_TRY -#define PJ_CATCH_ANY if (0) +#define PJ_TRY +#define PJ_CATCH_ANY if (0) #define PJ_END -#define PJ_THROW(x_id) do { PJ_LOG(1,("PJ_THROW"," error code = %d",x_id)); } while (0) -#define PJ_GET_EXCEPTION() 0 +#define PJ_THROW(x_id) do { PJ_LOG(1,("PJ_THROW"," error code = %d",x_id)); } while (0) +#define PJ_GET_EXCEPTION() 0 -#endif /* __cplusplus */ +#endif /* __cplusplus */ #else /***************************************************************************** @@ -371,51 +370,51 @@ PJ_DECL(void) pj_pop_exception_handler_(struct pj_exception_state_t *rec); * Start exception specification block. * @hideinitializer */ -#define PJ_TRY if (1) { \ - pj_push_exception_handler_(&pj_x_except__); \ - pj_x_code__ = pj_setjmp(pj_x_except__.state); \ - if (pj_x_code__ == 0) +#define PJ_TRY if (1) { \ + pj_push_exception_handler_(&pj_x_except__); \ + pj_x_code__ = pj_setjmp(pj_x_except__.state); \ + if (pj_x_code__ == 0) /** * Catch the specified exception Id. * @param id The exception number to catch. * @hideinitializer */ -#define PJ_CATCH(id) else if (pj_x_code__ == (id)) +#define PJ_CATCH(id) else if (pj_x_code__ == (id)) /** * Catch any exception number. * @hideinitializer */ -#define PJ_CATCH_ANY else +#define PJ_CATCH_ANY else /** * End of exception specification block. * @hideinitializer */ -#define PJ_END pj_pop_exception_handler_(&pj_x_except__); \ - } else {} +#define PJ_END pj_pop_exception_handler_(&pj_x_except__); \ + } else {} /** * Throw exception. * @param exception_id The exception number. * @hideinitializer */ -#define PJ_THROW(exception_id) pj_throw_exception_(exception_id) +#define PJ_THROW(exception_id) pj_throw_exception_(exception_id) /** * Get current exception. * @return Current exception code. * @hideinitializer */ -#define PJ_GET_EXCEPTION() (pj_x_code__) +#define PJ_GET_EXCEPTION() (pj_x_code__) -#endif /* PJ_EXCEPTION_USE_WIN32_SEH */ +#endif /* PJ_EXCEPTION_USE_WIN32_SEH */ PJ_END_DECL -#endif /* __PJ_EXCEPTION_H__ */ +#endif /* __PJ_EXCEPTION_H__ */ diff --git a/pjlib/include/pj/fifobuf.h b/pjlib/include/pj/fifobuf.h index 8a4b2d618c..26b8fb776e 100644 --- a/pjlib/include/pj/fifobuf.h +++ b/pjlib/include/pj/fifobuf.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,13 +31,13 @@ struct pj_fifobuf_t int full; }; -PJ_DECL(void) pj_fifobuf_init (pj_fifobuf_t *fb, void *buffer, unsigned size); +PJ_DECL(void) pj_fifobuf_init (pj_fifobuf_t *fb, void *buffer, unsigned size); PJ_DECL(unsigned) pj_fifobuf_max_size (pj_fifobuf_t *fb); -PJ_DECL(void*) pj_fifobuf_alloc (pj_fifobuf_t *fb, unsigned size); +PJ_DECL(void*) pj_fifobuf_alloc (pj_fifobuf_t *fb, unsigned size); PJ_DECL(pj_status_t) pj_fifobuf_unalloc (pj_fifobuf_t *fb, void *buf); PJ_DECL(pj_status_t) pj_fifobuf_free (pj_fifobuf_t *fb, void *buf); PJ_END_DECL -#endif /* __PJ_FIFOBUF_H__ */ +#endif /* __PJ_FIFOBUF_H__ */ diff --git a/pjlib/include/pj/file_access.h b/pjlib/include/pj/file_access.h index 30b633a0f2..d805e6d306 100644 --- a/pjlib/include/pj/file_access.h +++ b/pjlib/include/pj/file_access.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -106,4 +105,4 @@ PJ_DECL(pj_status_t) pj_file_getstat(const char *filename, pj_file_stat *stat); PJ_END_DECL -#endif /* __PJ_FILE_ACCESS_H__ */ +#endif /* __PJ_FILE_ACCESS_H__ */ diff --git a/pjlib/include/pj/file_io.h b/pjlib/include/pj/file_io.h index d036543059..343615b435 100644 --- a/pjlib/include/pj/file_io.h +++ b/pjlib/include/pj/file_io.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -167,9 +166,9 @@ PJ_DECL(pj_status_t) pj_file_getpos(pj_oshandle_t fd, /** * Flush file buffers. * - * @param fd The file descriptor. + * @param fd The file descriptor. * - * @return PJ_SUCCESS or the appropriate error code on error. + * @return PJ_SUCCESS or the appropriate error code on error. */ PJ_DECL(pj_status_t) pj_file_flush(pj_oshandle_t fd); diff --git a/pjlib/include/pj/guid.h b/pjlib/include/pj/guid.h index 7b24dd516e..95eff02158 100644 --- a/pjlib/include/pj/guid.h +++ b/pjlib/include/pj/guid.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -96,16 +95,16 @@ PJ_DECL(pj_str_t*) pj_generate_unique_string_lower(pj_str_t *str); /** * Generate a unique string. * - * @param pool Pool to allocate memory from. - * @param str The string. + * @param pool Pool to allocate memory from. + * @param str The string. */ PJ_DECL(void) pj_create_unique_string(pj_pool_t *pool, pj_str_t *str); /** * Generate a unique string in lowercase. * - * @param pool Pool to allocate memory from. - * @param str The string. + * @param pool Pool to allocate memory from. + * @param str The string. */ PJ_DECL(void) pj_create_unique_string_lower(pj_pool_t *pool, pj_str_t *str); diff --git a/pjlib/include/pj/hash.h b/pjlib/include/pj/hash.h index 35c3413728..030e98176b 100644 --- a/pjlib/include/pj/hash.h +++ b/pjlib/include/pj/hash.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -43,12 +42,12 @@ PJ_BEGIN_DECL * If this constant is used as keylen, then the key is interpreted as * NULL terminated string. */ -#define PJ_HASH_KEY_STRING ((unsigned)-1) +#define PJ_HASH_KEY_STRING ((unsigned)-1) /** * This indicates the size of of each hash entry. */ -#define PJ_HASH_ENTRY_BUF_SIZE (3*sizeof(void*) + 2*sizeof(pj_uint32_t)) +#define PJ_HASH_ENTRY_BUF_SIZE (3*sizeof(void*) + 2*sizeof(pj_uint32_t)) /** * Type declaration for entry buffer, used by #pj_hash_set_np() @@ -59,15 +58,15 @@ typedef void *pj_hash_entry_buf[(PJ_HASH_ENTRY_BUF_SIZE+sizeof(void*)-1)/(sizeof * This is the function that is used by the hash table to calculate hash value * of the specified key. * - * @param hval the initial hash value, or zero. - * @param key the key to calculate. + * @param hval the initial hash value, or zero. + * @param key the key to calculate. * @param keylen the length of the key, or PJ_HASH_KEY_STRING to treat - * the key as null terminated string. + * the key as null terminated string. * * @return the hash value. */ PJ_DECL(pj_uint32_t) pj_hash_calc(pj_uint32_t hval, - const void *key, unsigned keylen); + const void *key, unsigned keylen); /** @@ -88,8 +87,8 @@ PJ_DECL(pj_uint32_t) pj_hash_calc_tolower(pj_uint32_t hval, /** * Create a hash table with the specified 'bucket' size. * - * @param pool the pool from which the hash table will be allocated from. - * @param size the bucket size, which will be round-up to the nearest 2^n-1 + * @param pool the pool from which the hash table will be allocated from. + * @param size the bucket size, which will be round-up to the nearest 2^n-1 * * @return the hash table. */ @@ -99,20 +98,20 @@ PJ_DECL(pj_hash_table_t*) pj_hash_create(pj_pool_t *pool, unsigned size); /** * Get the value associated with the specified key. * - * @param ht the hash table. - * @param key the key to look for. + * @param ht the hash table. + * @param key the key to look for. * @param keylen the length of the key, or PJ_HASH_KEY_STRING to use the - * string length of the key. - * @param hval if this argument is not NULL and the value is not zero, - * the value will be used as the computed hash value. If - * the argument is not NULL and the value is zero, it will - * be filled with the computed hash upon return. + * string length of the key. + * @param hval if this argument is not NULL and the value is not zero, + * the value will be used as the computed hash value. If + * the argument is not NULL and the value is zero, it will + * be filled with the computed hash upon return. * * @return the value associated with the key, or NULL if the key is not found. */ PJ_DECL(void *) pj_hash_get( pj_hash_table_t *ht, - const void *key, unsigned keylen, - pj_uint32_t *hval ); + const void *key, unsigned keylen, + pj_uint32_t *hval ); /** @@ -122,8 +121,8 @@ PJ_DECL(void *) pj_hash_get( pj_hash_table_t *ht, * @see pj_hash_get() */ PJ_DECL(void *) pj_hash_get_lower( pj_hash_table_t *ht, - const void *key, unsigned keylen, - pj_uint32_t *hval ); + const void *key, unsigned keylen, + pj_uint32_t *hval ); /** @@ -133,23 +132,23 @@ PJ_DECL(void *) pj_hash_get_lower( pj_hash_table_t *ht, * with the specified pool. Otherwise if value is NULL, entry will be * deleted if it exists. * - * @param pool the pool to allocate the new entry if a new entry has to be - * created. - * @param ht the hash table. - * @param key the key. If pool is not specified, the key MUST point to - * buffer that remains valid for the duration of the entry. + * @param pool the pool to allocate the new entry if a new entry has to be + * created. + * @param ht the hash table. + * @param key the key. If pool is not specified, the key MUST point to + * buffer that remains valid for the duration of the entry. * @param keylen the length of the key, or PJ_HASH_KEY_STRING to use the - * string length of the key. - * @param hval if the value is not zero, then the hash table will use - * this value to search the entry's index, otherwise it will - * compute the key. This value can be obtained when calling - * #pj_hash_get(). - * @param value value to be associated, or NULL to delete the entry with - * the specified key. + * string length of the key. + * @param hval if the value is not zero, then the hash table will use + * this value to search the entry's index, otherwise it will + * compute the key. This value can be obtained when calling + * #pj_hash_get(). + * @param value value to be associated, or NULL to delete the entry with + * the specified key. */ PJ_DECL(void) pj_hash_set( pj_pool_t *pool, pj_hash_table_t *ht, - const void *key, unsigned keylen, pj_uint32_t hval, - void *value ); + const void *key, unsigned keylen, pj_uint32_t hval, + void *value ); /** @@ -159,7 +158,7 @@ PJ_DECL(void) pj_hash_set( pj_pool_t *pool, pj_hash_table_t *ht, * @see pj_hash_set() */ PJ_DECL(void) pj_hash_set_lower( pj_pool_t *pool, pj_hash_table_t *ht, - const void *key, unsigned keylen, + const void *key, unsigned keylen, pj_uint32_t hval, void *value ); @@ -168,23 +167,23 @@ PJ_DECL(void) pj_hash_set_lower( pj_pool_t *pool, pj_hash_table_t *ht, * like #pj_hash_set(), except that it doesn't use pool (hence the np -- no * pool suffix). If new entry needs to be allocated, it will use the entry_buf. * - * @param ht the hash table. - * @param key the key. + * @param ht the hash table. + * @param key the key. * @param keylen the length of the key, or PJ_HASH_KEY_STRING to use the - * string length of the key. - * @param hval if the value is not zero, then the hash table will use - * this value to search the entry's index, otherwise it will - * compute the key. This value can be obtained when calling - * #pj_hash_get(). + * string length of the key. + * @param hval if the value is not zero, then the hash table will use + * this value to search the entry's index, otherwise it will + * compute the key. This value can be obtained when calling + * #pj_hash_get(). * @param entry_buf Buffer which will be used for the new entry, when one needs - * to be created. - * @param value value to be associated, or NULL to delete the entry with - * the specified key. + * to be created. + * @param value value to be associated, or NULL to delete the entry with + * the specified key. */ PJ_DECL(void) pj_hash_set_np(pj_hash_table_t *ht, - const void *key, unsigned keylen, - pj_uint32_t hval, pj_hash_entry_buf entry_buf, - void *value); + const void *key, unsigned keylen, + pj_uint32_t hval, pj_hash_entry_buf entry_buf, + void *value); /** * Variant of #pj_hash_set_np() with the key being converted to lowercase @@ -193,15 +192,15 @@ PJ_DECL(void) pj_hash_set_np(pj_hash_table_t *ht, * @see pj_hash_set_np() */ PJ_DECL(void) pj_hash_set_np_lower(pj_hash_table_t *ht, - const void *key, unsigned keylen, - pj_uint32_t hval, + const void *key, unsigned keylen, + pj_uint32_t hval, pj_hash_entry_buf entry_buf, - void *value); + void *value); /** * Get the total number of entries in the hash table. * - * @param ht the hash table. + * @param ht the hash table. * * @return the number of entries in the hash table. */ @@ -211,36 +210,36 @@ PJ_DECL(unsigned) pj_hash_count( pj_hash_table_t *ht ); /** * Get the iterator to the first element in the hash table. * - * @param ht the hash table. - * @param it the iterator for iterating hash elements. + * @param ht the hash table. + * @param it the iterator for iterating hash elements. * * @return the iterator to the hash element, or NULL if no element presents. */ PJ_DECL(pj_hash_iterator_t*) pj_hash_first( pj_hash_table_t *ht, - pj_hash_iterator_t *it ); + pj_hash_iterator_t *it ); /** * Get the next element from the iterator. * - * @param ht the hash table. - * @param it the hash iterator. + * @param ht the hash table. + * @param it the hash iterator. * * @return the next iterator, or NULL if there's no more element. */ PJ_DECL(pj_hash_iterator_t*) pj_hash_next( pj_hash_table_t *ht, - pj_hash_iterator_t *it ); + pj_hash_iterator_t *it ); /** * Get the value associated with a hash iterator. * - * @param ht the hash table. - * @param it the hash iterator. + * @param ht the hash table. + * @param it the hash iterator. * * @return the value associated with the current element in iterator. */ PJ_DECL(void*) pj_hash_this( pj_hash_table_t *ht, - pj_hash_iterator_t *it ); + pj_hash_iterator_t *it ); /** diff --git a/pjlib/include/pj/ioqueue.h b/pjlib/include/pj/ioqueue.h index c02b12d257..d8276a9be2 100644 --- a/pjlib/include/pj/ioqueue.h +++ b/pjlib/include/pj/ioqueue.h @@ -1,6 +1,4 @@ -/* $Id$ - */ -/* +/* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono * @@ -16,7 +14,7 @@ * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __PJ_IOQUEUE_H__ #define __PJ_IOQUEUE_H__ @@ -35,7 +33,7 @@ PJ_BEGIN_DECL * @brief Input/Output * @ingroup PJ_OS * - * This section contains API building blocks to perform network I/O and + * This section contains API building blocks to perform network I/O and * communications. If provides: * - @ref PJ_SOCK *\n @@ -69,13 +67,13 @@ PJ_BEGIN_DECL * asynchronous operation and to be notified later when the operation has * completed. * - * The I/O Queue can work on both socket and file descriptors. For + * The I/O Queue can work on both socket and file descriptors. For * asynchronous file operations however, one must make sure that the correct * file I/O back-end is used, because not all file I/O back-end can be * used with the ioqueue. Please see \ref PJ_FILE_IO for more details. * * The framework works natively in platforms where asynchronous operation API - * exists, such as in Windows NT with IoCompletionPort/IOCP. In other + * exists, such as in Windows NT with IoCompletionPort/IOCP. In other * platforms, the I/O queue abstracts the operating system's event poll API * to provide semantics similar to IoCompletionPort with minimal penalties * (i.e. per ioqueue and per handle mutex protection). @@ -88,14 +86,14 @@ PJ_BEGIN_DECL * platform. * * Currently, the I/O Queue is implemented using: - * - select(), as the common denominator, but the least - * efficient. Also the number of descriptor is limited to + * - select(), as the common denominator, but the least + * efficient. Also the number of descriptor is limited to * \c PJ_IOQUEUE_MAX_HANDLES (which by default is 64). - * - /dev/epoll on Linux (user mode and kernel mode), + * - /dev/epoll on Linux (user mode and kernel mode), * a much faster replacement for select() on Linux (and more importantly * doesn't have limitation on number of descriptors). - * - I/O Completion ports on Windows NT/2000/XP, which is the most - * efficient way to dispatch events in Windows NT based OSes, and most + * - I/O Completion ports on Windows NT/2000/XP, which is the most + * efficient way to dispatch events in Windows NT based OSes, and most * importantly, it doesn't have the limit on how many handles to monitor. * And it works with files (not only sockets) as well. * @@ -110,9 +108,9 @@ PJ_BEGIN_DECL * These parallel executions are completely safe when the events happen for * two different handles. * - * However, with multithreading, care must be taken when multiple events - * happen on the same handle, or when event is happening on a handle (and - * the callback is being executed) and application is performing + * However, with multithreading, care must be taken when multiple events + * happen on the same handle, or when event is happening on a handle (and + * the callback is being executed) and application is performing * unregistration to the handle at the same time. * * The treatments of above scenario differ according to the concurrency @@ -121,17 +119,17 @@ PJ_BEGIN_DECL * \subsection pj_ioq_concur_set Concurrency Settings for Handles * * Concurrency can be set on per handle (key) basis, by using - * #pj_ioqueue_set_concurrency() function. The default key concurrency value - * for the handle is inherited from the key concurrency setting of the ioqueue, + * #pj_ioqueue_set_concurrency() function. The default key concurrency value + * for the handle is inherited from the key concurrency setting of the ioqueue, * and the key concurrency setting for the ioqueue can be changed by using - * #pj_ioqueue_set_default_concurrency(). The default key concurrency setting + * #pj_ioqueue_set_default_concurrency(). The default key concurrency setting * for ioqueue itself is controlled by compile time setting * PJ_IOQUEUE_DEFAULT_ALLOW_CONCURRENCY. * * Note that this key concurrency setting only controls whether multiple - * threads are allowed to operate on the same key at the same time. - * The ioqueue itself always allows multiple threads to enter the ioqeuue at - * the same time, and also simultaneous callback calls to differrent + * threads are allowed to operate on the same key at the same time. + * The ioqueue itself always allows multiple threads to enter the ioqeuue at + * the same time, and also simultaneous callback calls to differrent * keys is always allowed regardless to the key concurrency setting. * * \subsection pj_ioq_parallel Parallel Callback Executions for the Same Handle @@ -158,7 +156,7 @@ PJ_BEGIN_DECL * promote good performance and scalability for application. * * However this setting has a major drawback with regard to synchronization, - * and application MUST carefully follow the following guidelines to ensure + * and application MUST carefully follow the following guidelines to ensure * that parallel access to the key does not cause problems: * * - Always note that callback may be called simultaneously for the same @@ -175,7 +173,7 @@ PJ_BEGIN_DECL * * \subsection pj_ioq_disallow_concur Concurrency is Disabled * - * Alternatively, application may disable key concurrency to make + * Alternatively, application may disable key concurrency to make * synchronization easier. As noted above, there are three ways to control * key concurrency setting: * - by controlling on per handle/key basis, with #pj_ioqueue_set_concurrency(). @@ -207,9 +205,9 @@ PJ_BEGIN_DECL * the pointer supplied when the asynchronous function is called. */ typedef struct pj_ioqueue_op_key_t -{ +{ void *internal__[32]; /**< Internal I/O Queue data. */ - void *activesock_data; /**< Active socket data. */ + void *activesock_data; /**< Active socket data. */ void *user_data; /**< Application data. */ } pj_ioqueue_op_key_t; @@ -223,52 +221,52 @@ typedef struct pj_ioqueue_callback * This callback is called when #pj_ioqueue_recv or #pj_ioqueue_recvfrom * completes. * - * @param key The key. + * @param key The key. * @param op_key Operation key. - * @param bytes_read >= 0 to indicate the amount of data read, + * @param bytes_read >= 0 to indicate the amount of data read, * otherwise negative value containing the error * code. To obtain the pj_status_t error code, use * (pj_status_t code = -bytes_read). */ - void (*on_read_complete)(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, + void (*on_read_complete)(pj_ioqueue_key_t *key, + pj_ioqueue_op_key_t *op_key, pj_ssize_t bytes_read); /** * This callback is called when #pj_ioqueue_send or #pj_ioqueue_sendto * completes. * - * @param key The key. + * @param key The key. * @param op_key Operation key. - * @param bytes_sent >= 0 to indicate the amount of data written, + * @param bytes_sent >= 0 to indicate the amount of data written, * otherwise negative value containing the error * code. To obtain the pj_status_t error code, use * (pj_status_t code = -bytes_sent). */ - void (*on_write_complete)(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, + void (*on_write_complete)(pj_ioqueue_key_t *key, + pj_ioqueue_op_key_t *op_key, pj_ssize_t bytes_sent); /** * This callback is called when #pj_ioqueue_accept completes. * - * @param key The key. + * @param key The key. * @param op_key Operation key. * @param sock Newly connected socket. - * @param status Zero if the operation completes successfully. + * @param status Zero if the operation completes successfully. */ - void (*on_accept_complete)(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_sock_t sock, + void (*on_accept_complete)(pj_ioqueue_key_t *key, + pj_ioqueue_op_key_t *op_key, + pj_sock_t sock, pj_status_t status); /** * This callback is called when #pj_ioqueue_connect completes. * - * @param key The key. - * @param status PJ_SUCCESS if the operation completes successfully. + * @param key The key. + * @param status PJ_SUCCESS if the operation completes successfully. */ - void (*on_connect_complete)(pj_ioqueue_key_t *key, + void (*on_connect_complete)(pj_ioqueue_key_t *key, pj_status_t status); } pj_ioqueue_callback; @@ -279,17 +277,17 @@ typedef struct pj_ioqueue_callback */ typedef enum pj_ioqueue_operation_e { - PJ_IOQUEUE_OP_NONE = 0, /**< No operation. */ - PJ_IOQUEUE_OP_READ = 1, /**< read() operation. */ + PJ_IOQUEUE_OP_NONE = 0, /**< No operation. */ + PJ_IOQUEUE_OP_READ = 1, /**< read() operation. */ PJ_IOQUEUE_OP_RECV = 2, /**< recv() operation. */ - PJ_IOQUEUE_OP_RECV_FROM = 4, /**< recvfrom() operation. */ - PJ_IOQUEUE_OP_WRITE = 8, /**< write() operation. */ + PJ_IOQUEUE_OP_RECV_FROM = 4, /**< recvfrom() operation. */ + PJ_IOQUEUE_OP_WRITE = 8, /**< write() operation. */ PJ_IOQUEUE_OP_SEND = 16, /**< send() operation. */ - PJ_IOQUEUE_OP_SEND_TO = 32, /**< sendto() operation. */ + PJ_IOQUEUE_OP_SEND_TO = 32, /**< sendto() operation. */ #if defined(PJ_HAS_TCP) && PJ_HAS_TCP != 0 - PJ_IOQUEUE_OP_ACCEPT = 64, /**< accept() operation. */ - PJ_IOQUEUE_OP_CONNECT = 128 /**< connect() operation. */ -#endif /* PJ_HAS_TCP */ + PJ_IOQUEUE_OP_ACCEPT = 64, /**< accept() operation. */ + PJ_IOQUEUE_OP_CONNECT = 128 /**< connect() operation. */ +#endif /* PJ_HAS_TCP */ } pj_ioqueue_operation_e; @@ -321,7 +319,7 @@ typedef enum pj_ioqueue_operation_e #if !defined(PJ_IOQUEUE_MAX_CAND_EVENTS) || \ PJ_IOQUEUE_MAX_CAND_EVENTS < PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL # undef PJ_IOQUEUE_MAX_CAND_EVENTS -# define PJ_IOQUEUE_MAX_CAND_EVENTS PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL +# define PJ_IOQUEUE_MAX_CAND_EVENTS PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL #endif @@ -329,7 +327,7 @@ typedef enum pj_ioqueue_operation_e * When this flag is specified in ioqueue's recv() or send() operations, * the ioqueue will always mark the operation as asynchronous. */ -#define PJ_IOQUEUE_ALWAYS_ASYNC ((pj_uint32_t)1 << (pj_uint32_t)31) +#define PJ_IOQUEUE_ALWAYS_ASYNC ((pj_uint32_t)1 << (pj_uint32_t)31) /** @@ -351,7 +349,7 @@ typedef enum pj_ioqueue_epoll_flag * epoll when neither are available. */ PJ_IOQUEUE_EPOLL_AUTO = PJ_IOQUEUE_EPOLL_EXCLUSIVE | - PJ_IOQUEUE_EPOLL_ONESHOT, + PJ_IOQUEUE_EPOLL_ONESHOT, } pj_ioqueue_epoll_flag; @@ -386,7 +384,7 @@ typedef struct pj_ioqueue_cfg /** * Initialize the ioqueue configuration with the default values. * - * @param cfg The configuration to be initialized. + * @param cfg The configuration to be initialized. */ PJ_DECL(void) pj_ioqueue_cfg_default(pj_ioqueue_cfg *cfg); @@ -394,7 +392,7 @@ PJ_DECL(void) pj_ioqueue_cfg_default(pj_ioqueue_cfg *cfg); /** * Return the name of the ioqueue implementation. * - * @return Implementation name. + * @return Implementation name. */ PJ_DECL(const char*) pj_ioqueue_name(void); @@ -402,40 +400,40 @@ PJ_DECL(const char*) pj_ioqueue_name(void); /** * Create a new I/O Queue framework. * - * @param pool The pool to allocate the I/O queue structure. - * @param max_fd The maximum number of handles to be supported, which - * should not exceed PJ_IOQUEUE_MAX_HANDLES. - * @param ioqueue Pointer to hold the newly created I/O Queue. + * @param pool The pool to allocate the I/O queue structure. + * @param max_fd The maximum number of handles to be supported, which + * should not exceed PJ_IOQUEUE_MAX_HANDLES. + * @param ioqueue Pointer to hold the newly created I/O Queue. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ -PJ_DECL(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, - pj_size_t max_fd, - pj_ioqueue_t **ioqueue); +PJ_DECL(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, + pj_size_t max_fd, + pj_ioqueue_t **ioqueue); /** * Create a new I/O Queue framework. * - * @param pool The pool to allocate the I/O queue structure. - * @param max_fd The maximum number of handles to be supported, which - * should not exceed PJ_IOQUEUE_MAX_HANDLES. + * @param pool The pool to allocate the I/O queue structure. + * @param max_fd The maximum number of handles to be supported, which + * should not exceed PJ_IOQUEUE_MAX_HANDLES. * @param cfg Optional ioqueue configuration. Application must * initialize this structure with pj_ioqueue_cfg_default() * first. If this is not specified, default config values * as set pj_ioqueue_cfg_default() by will be used. - * @param ioqueue Pointer to hold the newly created I/O Queue. + * @param ioqueue Pointer to hold the newly created I/O Queue. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pj_ioqueue_create2( pj_pool_t *pool, - pj_size_t max_fd, - const pj_ioqueue_cfg *cfg, - pj_ioqueue_t **ioqueue); + pj_size_t max_fd, + const pj_ioqueue_cfg *cfg, + pj_ioqueue_t **ioqueue); /** * Destroy the I/O queue. * - * @param ioque The I/O Queue to be destroyed. + * @param ioque The I/O Queue to be destroyed. * * @return PJ_SUCCESS if success. */ @@ -446,8 +444,8 @@ PJ_DECL(pj_status_t) pj_ioqueue_destroy( pj_ioqueue_t *ioque ); * be called right after the I/O queue is created, before any handle is * registered to the I/O queue. * - * Initially the I/O queue is created with non-recursive mutex protection. - * Applications can supply alternative lock to be used by calling this + * Initially the I/O queue is created with non-recursive mutex protection. + * Applications can supply alternative lock to be used by calling this * function. * * @param ioque The ioqueue instance. @@ -456,53 +454,53 @@ PJ_DECL(pj_status_t) pj_ioqueue_destroy( pj_ioqueue_t *ioque ); * * @return PJ_SUCCESS or the appropriate error code. */ -PJ_DECL(pj_status_t) pj_ioqueue_set_lock( pj_ioqueue_t *ioque, - pj_lock_t *lock, - pj_bool_t auto_delete ); +PJ_DECL(pj_status_t) pj_ioqueue_set_lock( pj_ioqueue_t *ioque, + pj_lock_t *lock, + pj_bool_t auto_delete ); /** * Set default concurrency policy for this ioqueue. If this function is not - * called, the default concurrency policy for the ioqueue is controlled by + * called, the default concurrency policy for the ioqueue is controlled by * compile time setting PJ_IOQUEUE_DEFAULT_ALLOW_CONCURRENCY. * * Note that changing the concurrency setting to the ioqueue will only affect * subsequent key registrations. To modify the concurrency setting for * individual key, use #pj_ioqueue_set_concurrency(). * - * @param ioqueue The ioqueue instance. - * @param allow Non-zero to allow concurrent callback calls, or - * PJ_FALSE to disallow it. + * @param ioqueue The ioqueue instance. + * @param allow Non-zero to allow concurrent callback calls, or + * PJ_FALSE to disallow it. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ioqueue_set_default_concurrency(pj_ioqueue_t *ioqueue, - pj_bool_t allow); + pj_bool_t allow); /** - * Register a socket to the I/O queue framework. + * Register a socket to the I/O queue framework. * When a socket is registered to the IOQueue, it may be modified to use - * non-blocking IO. If it is modified, there is no guarantee that this + * non-blocking IO. If it is modified, there is no guarantee that this * modification will be restored after the socket is unregistered. * - * @param pool To allocate the resource for the specified handle, - * which must be valid until the handle/key is unregistered - * from I/O Queue. - * @param ioque The I/O Queue. - * @param sock The socket. + * @param pool To allocate the resource for the specified handle, + * which must be valid until the handle/key is unregistered + * from I/O Queue. + * @param ioque The I/O Queue. + * @param sock The socket. * @param user_data User data to be associated with the key, which can be - * retrieved later. - * @param cb Callback to be called when I/O operation completes. + * retrieved later. + * @param cb Callback to be called when I/O operation completes. * @param key Pointer to receive the key to be associated with this * socket. Subsequent I/O queue operation will need this * key. * - * @return PJ_SUCCESS on success, or the error code. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, - pj_ioqueue_t *ioque, - pj_sock_t sock, - void *user_data, - const pj_ioqueue_callback *cb, + pj_ioqueue_t *ioque, + pj_sock_t sock, + void *user_data, + const pj_ioqueue_callback *cb, pj_ioqueue_key_t **key ); /** @@ -511,11 +509,11 @@ PJ_DECL(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, * when the socket is registered and decrease it when it is destroyed. */ PJ_DECL(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, - pj_ioqueue_t *ioque, - pj_sock_t sock, - pj_grp_lock_t *grp_lock, - void *user_data, - const pj_ioqueue_callback *cb, + pj_ioqueue_t *ioque, + pj_sock_t sock, + pj_grp_lock_t *grp_lock, + void *user_data, + const pj_ioqueue_callback *cb, pj_ioqueue_key_t **key ); /** @@ -525,7 +523,7 @@ PJ_DECL(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, * operations except asynchronous connect, and if necessary call * #pj_ioqueue_post_completion() to cancel the pending operations. * - * Note that asynchronous connect operation will automatically be + * Note that asynchronous connect operation will automatically be * cancelled during the unregistration. * * Also note that when I/O Completion Port backend is used, application @@ -533,7 +531,7 @@ PJ_DECL(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, * because there is no unregistering API for IOCP. The only way to * unregister the handle from IOCP is to close the handle. * - * @param key The key that was previously obtained from registration. + * @param key The key that was previously obtained from registration. * * @return PJ_SUCCESS on success or the error code. * @@ -545,9 +543,9 @@ PJ_DECL(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key ); /** * Get user data associated with an ioqueue key. * - * @param key The key that was previously obtained from registration. + * @param key The key that was previously obtained from registration. * - * @return The user data associated with the descriptor, or NULL + * @return The user data associated with the descriptor, or NULL * on error or if no data is associated with the key during * registration. */ @@ -557,7 +555,7 @@ PJ_DECL(void*) pj_ioqueue_get_user_data( pj_ioqueue_key_t *key ); * Set or change the user data to be associated with the file descriptor or * handle or socket descriptor. * - * @param key The key that was previously obtained from registration. + * @param key The key that was previously obtained from registration. * @param user_data User data to be associated with the descriptor. * @param old_data Optional parameter to retrieve the old user data. * @@ -583,44 +581,44 @@ PJ_DECL(pj_status_t) pj_ioqueue_set_user_data( pj_ioqueue_key_t *key, * setting the \a allow flag to false. With concurrency disabled, only * one thread can call the key's callback at one time. * - * @param key The key that was previously obtained from registration. - * @param allow Set this to non-zero to allow concurrent callback calls - * and zero (PJ_FALSE) to disallow it. + * @param key The key that was previously obtained from registration. + * @param allow Set this to non-zero to allow concurrent callback calls + * and zero (PJ_FALSE) to disallow it. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ioqueue_set_concurrency(pj_ioqueue_key_t *key, - pj_bool_t allow); + pj_bool_t allow); /** - * Acquire the key's mutex. When the key's concurrency is disabled, + * Acquire the key's mutex. When the key's concurrency is disabled, * application may call this function to synchronize its operation * with the key's callback (i.e. this function will block until the * key's callback returns). * - * @param key The key that was previously obtained from registration. + * @param key The key that was previously obtained from registration. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ioqueue_lock_key(pj_ioqueue_key_t *key); /** - * Try to acquire the key's mutex. When the key's concurrency is disabled, + * Try to acquire the key's mutex. When the key's concurrency is disabled, * application may call this function to synchronize its operation * with the key's callback. * - * @param key The key that was previously obtained from registration. + * @param key The key that was previously obtained from registration. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ioqueue_trylock_key(pj_ioqueue_key_t *key); /** * Release the lock previously acquired with pj_ioqueue_lock_key(). * - * @param key The key that was previously obtained from registration. + * @param key The key that was previously obtained from registration. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ioqueue_unlock_key(pj_ioqueue_key_t *key); @@ -628,15 +626,15 @@ PJ_DECL(pj_status_t) pj_ioqueue_unlock_key(pj_ioqueue_key_t *key); * Initialize operation key. * * @param op_key The operation key to be initialied. - * @param size The size of the operation key. + * @param size The size of the operation key. */ PJ_DECL(void) pj_ioqueue_op_key_init( pj_ioqueue_op_key_t *op_key, - pj_size_t size ); + pj_size_t size ); /** * Check if operation is pending on the specified operation key. - * The \c op_key must have been initialized with #pj_ioqueue_op_key_init() - * or submitted as pending operation before, or otherwise the result + * The \c op_key must have been initialized with #pj_ioqueue_op_key_init() + * or submitted as pending operation before, or otherwise the result * is undefined. * * @param key The key. @@ -651,7 +649,7 @@ PJ_DECL(pj_bool_t) pj_ioqueue_is_pending( pj_ioqueue_key_t *key, /** * Post completion status to the specified operation key and call the - * appropriate callback. When the callback is called, the number of bytes + * appropriate callback. When the callback is called, the number of bytes * received in read/write callback or the status in accept/connect callback * will be set from the \c bytes_status parameter. * @@ -676,7 +674,7 @@ PJ_DECL(pj_status_t) pj_ioqueue_post_completion( pj_ioqueue_key_t *key, * * @param key The key. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ioqueue_clear_key( pj_ioqueue_key_t *key ); @@ -684,7 +682,7 @@ PJ_DECL(pj_status_t) pj_ioqueue_clear_key( pj_ioqueue_key_t *key ); #if defined(PJ_HAS_TCP) && PJ_HAS_TCP != 0 /** - * Instruct I/O Queue to accept incoming connection on the specified + * Instruct I/O Queue to accept incoming connection on the specified * listening socket. This function will return immediately (i.e. non-blocking) * regardless whether a connection is immediately available. If the function * can't complete immediately, the caller will be notified about the incoming @@ -692,23 +690,23 @@ PJ_DECL(pj_status_t) pj_ioqueue_clear_key( pj_ioqueue_key_t *key ); * immediately available, the function returns PJ_SUCCESS with the new * connection; in this case, the callback WILL NOT be called. * - * @param key The key which registered to the server socket. + * @param key The key which registered to the server socket. * @param op_key An operation specific key to be associated with the * pending operation, so that application can keep track of * which operation has been completed when the callback is * called. * @param new_sock Argument which contain pointer to receive the new socket * for the incoming connection. - * @param local Optional argument which contain pointer to variable to + * @param local Optional argument which contain pointer to variable to * receive local address. - * @param remote Optional argument which contain pointer to variable to + * @param remote Optional argument which contain pointer to variable to * receive the remote address. * @param addrlen On input, contains the length of the buffer for the - * address, and on output, contains the actual length of the - * address. This argument is optional. + * address, and on output, contains the actual length of the + * address. This argument is optional. * @return - * - PJ_SUCCESS When connection is available immediately, and the - * parameters will be updated to contain information about + * - PJ_SUCCESS When connection is available immediately, and the + * parameters will be updated to contain information about * the new connection. In this case, a completion callback * WILL NOT be called. * - PJ_EPENDING If no connection is available immediately. When a new @@ -717,10 +715,10 @@ PJ_DECL(pj_status_t) pj_ioqueue_clear_key( pj_ioqueue_key_t *key ); */ PJ_DECL(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - pj_sock_t *new_sock, - pj_sockaddr_t *local, - pj_sockaddr_t *remote, - int *addrlen ); + pj_sock_t *new_sock, + pj_sockaddr_t *local, + pj_sockaddr_t *remote, + int *addrlen ); /** * Initiate non-blocking socket connect. If the socket can NOT be connected @@ -729,21 +727,21 @@ PJ_DECL(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, * socket is connected immediately, the function returns PJ_SUCCESS and * completion callback WILL NOT be called. * - * @param key The key associated with TCP socket - * @param addr The remote address. + * @param key The key associated with TCP socket + * @param addr The remote address. * @param addrlen The remote address length. * * @return * - PJ_SUCCESS If socket is connected immediately. In this case, the * completion callback WILL NOT be called. - * - PJ_EPENDING If operation is queued, or + * - PJ_EPENDING If operation is queued, or * - non-zero Indicates the error code. */ PJ_DECL(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, - const pj_sockaddr_t *addr, - int addrlen ); + const pj_sockaddr_t *addr, + int addrlen ); -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ /** * Poll the I/O Queue for completed events. @@ -751,36 +749,36 @@ PJ_DECL(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, * Note: polling the ioqueue is not necessary in Symbian. Please see * @ref PJ_SYMBIAN_OS for more info. * - * @param ioque the I/O Queue. - * @param timeout polling timeout, or NULL if the thread wishes to wait - * indefinetely for the event. + * @param ioque the I/O Queue. + * @param timeout polling timeout, or NULL if the thread wishes to wait + * indefinetely for the event. * - * @return + * @return * - zero if timed out (no event). * - (<0) if error occured during polling. Callback will NOT be called. * - (>1) to indicate numbers of events. Callbacks have been called. */ PJ_DECL(int) pj_ioqueue_poll( pj_ioqueue_t *ioque, - const pj_time_val *timeout); + const pj_time_val *timeout); /** * Instruct the I/O Queue to read from the specified handle. This function - * returns immediately (i.e. non-blocking) regardless whether some data has - * been transferred. If the operation can't complete immediately, caller will + * returns immediately (i.e. non-blocking) regardless whether some data has + * been transferred. If the operation can't complete immediately, caller will * be notified about the completion when it calls pj_ioqueue_poll(). If data * is immediately available, the function will return PJ_SUCCESS and the * callback WILL NOT be called. * - * @param key The key that uniquely identifies the handle. + * @param key The key that uniquely identifies the handle. * @param op_key An operation specific key to be associated with the * pending operation, so that application can keep track of * which operation has been completed when the callback is - * called. Caller must make sure that this key remains + * called. Caller must make sure that this key remains * valid until the function completes. * @param buffer The buffer to hold the read data. The caller MUST make sure - * that this buffer remain valid until the framework completes - * reading the handle. + * that this buffer remain valid until the framework completes + * reading the handle. * @param length On input, it specifies the size of the buffer. If data is * available to be read immediately, the function returns * PJ_SUCCESS and this argument will be filled with the @@ -790,7 +788,7 @@ PJ_DECL(int) pj_ioqueue_poll( pj_ioqueue_t *ioque, * caller's stack and doesn't have to remain valid for the * duration of pending operation. * @param flags Recv flag. If flags has PJ_IOQUEUE_ALWAYS_ASYNC then - * the function will never return PJ_SUCCESS. + * the function will never return PJ_SUCCESS. * * @return * - PJ_SUCCESS If immediate data has been received in the buffer. In this @@ -801,9 +799,9 @@ PJ_DECL(int) pj_ioqueue_poll( pj_ioqueue_t *ioque, */ PJ_DECL(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - void *buffer, - pj_ssize_t *length, - pj_uint32_t flags ); + void *buffer, + pj_ssize_t *length, + pj_uint32_t flags ); /** * This function behaves similarly as #pj_ioqueue_recv(), except that it is @@ -811,14 +809,14 @@ PJ_DECL(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, * along with the data. Caller MUST make sure that both buffer and addr * remain valid until the framework completes reading the data. * - * @param key The key that uniquely identifies the handle. + * @param key The key that uniquely identifies the handle. * @param op_key An operation specific key to be associated with the * pending operation, so that application can keep track of * which operation has been completed when the callback is * called. * @param buffer The buffer to hold the read data. The caller MUST make sure - * that this buffer remain valid until the framework completes - * reading the handle. + * that this buffer remain valid until the framework completes + * reading the handle. * @param length On input, it specifies the size of the buffer. If data is * available to be read immediately, the function returns * PJ_SUCCESS and this argument will be filled with the @@ -828,7 +826,7 @@ PJ_DECL(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, * caller's stack and doesn't have to remain valid for the * duration of pending operation. * @param flags Recv flag. If flags has PJ_IOQUEUE_ALWAYS_ASYNC then - * the function will never return PJ_SUCCESS. + * the function will never return PJ_SUCCESS. * @param addr Optional Pointer to buffer to receive the address. * @param addrlen On input, specifies the length of the address buffer. * On output, it will be filled with the actual length of @@ -836,45 +834,45 @@ PJ_DECL(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, * specified. * * @return - * - PJ_SUCCESS If immediate data has been received. In this case, the - * callback must have been called before this function - * returns, and no pending operation is scheduled. + * - PJ_SUCCESS If immediate data has been received. In this case, the + * callback must have been called before this function + * returns, and no pending operation is scheduled. * - PJ_EPENDING If the operation has been queued. * - non-zero The return value indicates the error code. */ PJ_DECL(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - void *buffer, - pj_ssize_t *length, + void *buffer, + pj_ssize_t *length, pj_uint32_t flags, - pj_sockaddr_t *addr, - int *addrlen); + pj_sockaddr_t *addr, + int *addrlen); /** * Instruct the I/O Queue to write to the handle. This function will return - * immediately (i.e. non-blocking) regardless whether some data has been + * immediately (i.e. non-blocking) regardless whether some data has been * transferred. If the function can't complete immediately, the caller will - * be notified about the completion when it calls pj_ioqueue_poll(). If + * be notified about the completion when it calls pj_ioqueue_poll(). If * operation completes immediately and data has been transferred, the function * returns PJ_SUCCESS and the callback will NOT be called. * - * @param key The key that identifies the handle. + * @param key The key that identifies the handle. * @param op_key An operation specific key to be associated with the * pending operation, so that application can keep track of * which operation has been completed when the callback is * called. - * @param data The data to send. Caller MUST make sure that this buffer - * remains valid until the write operation completes. + * @param data The data to send. Caller MUST make sure that this buffer + * remains valid until the write operation completes. * @param length On input, it specifies the length of data to send. When * data was sent immediately, this function returns PJ_SUCCESS * and this parameter contains the length of data sent. If * data can not be sent immediately, an asynchronous operation * is scheduled and caller will be notified via callback the - * number of bytes sent. This parameter can point to local - * variable on caller's stack and doesn't have to remain + * number of bytes sent. This parameter can point to local + * variable on caller's stack and doesn't have to remain * valid until the operation has completed. * @param flags Send flags. If flags has PJ_IOQUEUE_ALWAYS_ASYNC then - * the function will never return PJ_SUCCESS. + * the function will never return PJ_SUCCESS. * * @return * - PJ_SUCCESS If data was immediately transferred. In this case, no @@ -886,36 +884,36 @@ PJ_DECL(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, */ PJ_DECL(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - const void *data, - pj_ssize_t *length, - pj_uint32_t flags ); + const void *data, + pj_ssize_t *length, + pj_uint32_t flags ); /** * Instruct the I/O Queue to write to the handle. This function will return - * immediately (i.e. non-blocking) regardless whether some data has been + * immediately (i.e. non-blocking) regardless whether some data has been * transferred. If the function can't complete immediately, the caller will - * be notified about the completion when it calls pj_ioqueue_poll(). If + * be notified about the completion when it calls pj_ioqueue_poll(). If * operation completes immediately and data has been transferred, the function * returns PJ_SUCCESS and the callback will NOT be called. * - * @param key the key that identifies the handle. + * @param key the key that identifies the handle. * @param op_key An operation specific key to be associated with the * pending operation, so that application can keep track of * which operation has been completed when the callback is * called. - * @param data the data to send. Caller MUST make sure that this buffer - * remains valid until the write operation completes. + * @param data the data to send. Caller MUST make sure that this buffer + * remains valid until the write operation completes. * @param length On input, it specifies the length of data to send. When * data was sent immediately, this function returns PJ_SUCCESS * and this parameter contains the length of data sent. If * data can not be sent immediately, an asynchronous operation * is scheduled and caller will be notified via callback the - * number of bytes sent. This parameter can point to local - * variable on caller's stack and doesn't have to remain + * number of bytes sent. This parameter can point to local + * variable on caller's stack and doesn't have to remain * valid until the operation has completed. * @param flags send flags. If flags has PJ_IOQUEUE_ALWAYS_ASYNC then - * the function will never return PJ_SUCCESS. + * the function will never return PJ_SUCCESS. * @param addr Optional remote address. * @param addrlen Remote address length, \c addr is specified. * @@ -926,11 +924,11 @@ PJ_DECL(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, */ PJ_DECL(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - const void *data, - pj_ssize_t *length, + const void *data, + pj_ssize_t *length, pj_uint32_t flags, - const pj_sockaddr_t *addr, - int addrlen); + const pj_sockaddr_t *addr, + int addrlen); /** @@ -939,5 +937,5 @@ PJ_DECL(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, PJ_END_DECL -#endif /* __PJ_IOQUEUE_H__ */ +#endif /* __PJ_IOQUEUE_H__ */ diff --git a/pjlib/include/pj/ip_helper.h b/pjlib/include/pj/ip_helper.h index 96c72edcfe..c31387f9ce 100644 --- a/pjlib/include/pj/ip_helper.h +++ b/pjlib/include/pj/ip_helper.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -47,9 +46,9 @@ typedef union pj_ip_route_entry /** IP routing entry for IP version 4 routing */ struct { - pj_in_addr if_addr; /**< Local interface IP address. */ - pj_in_addr dst_addr; /**< Destination IP address. */ - pj_in_addr mask; /**< Destination mask. */ + pj_in_addr if_addr; /**< Local interface IP address. */ + pj_in_addr dst_addr; /**< Destination IP address. */ + pj_in_addr mask; /**< Destination mask. */ } ipv4; } pj_ip_route_entry; @@ -65,7 +64,7 @@ typedef struct pj_enum_ip_option * * Default: pj_AF_UNSPEC(). */ - int af; + int af; /** * IPv6 addresses can have a DEPRECATED flag, if this flag is set, any @@ -75,7 +74,7 @@ typedef struct pj_enum_ip_option * * Default: PJ_FALSE. */ - pj_bool_t omit_deprecated_ipv6; + pj_bool_t omit_deprecated_ipv6; } pj_enum_ip_option; @@ -83,7 +82,7 @@ typedef struct pj_enum_ip_option /** * Get default values of IP enumeration option. * - * @param opt The IP enumeration option. + * @param opt The IP enumeration option. */ PJ_INLINE(void) pj_enum_ip_option_default(pj_enum_ip_option *opt) { @@ -94,53 +93,53 @@ PJ_INLINE(void) pj_enum_ip_option_default(pj_enum_ip_option *opt) /** * Enumerate the local IP interfaces currently active in the host. * - * @param af Family of the address to be retrieved. Application - * may specify pj_AF_UNSPEC() to retrieve all addresses, - * or pj_AF_INET() or pj_AF_INET6() to retrieve interfaces - * with specific address family. - * @param count On input, specify the number of entries. On output, - * it will be filled with the actual number of entries. - * @param ifs Array of socket addresses, which address part will - * be filled with the interface address. The address - * family part will be initialized with the address - * family of the IP address. + * @param af Family of the address to be retrieved. Application + * may specify pj_AF_UNSPEC() to retrieve all addresses, + * or pj_AF_INET() or pj_AF_INET6() to retrieve interfaces + * with specific address family. + * @param count On input, specify the number of entries. On output, + * it will be filled with the actual number of entries. + * @param ifs Array of socket addresses, which address part will + * be filled with the interface address. The address + * family part will be initialized with the address + * family of the IP address. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_enum_ip_interface(int af, - unsigned *count, - pj_sockaddr ifs[]); + unsigned *count, + pj_sockaddr ifs[]); /** * Enumerate the local IP interfaces currently active in the host with * capability to filter DEPRECATED IPv6 addresses (currently only for Linux). * - * @param opt The option, default option will be used if NULL. - * @param count On input, specify the number of entries. On output, - * it will be filled with the actual number of entries. - * @param ifs Array of socket (with flags) addresses, which address part - * will be filled with the interface address. The address - * family part will be initialized with the address - * family of the IP address. + * @param opt The option, default option will be used if NULL. + * @param count On input, specify the number of entries. On output, + * it will be filled with the actual number of entries. + * @param ifs Array of socket (with flags) addresses, which address part + * will be filled with the interface address. The address + * family part will be initialized with the address + * family of the IP address. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_enum_ip_interface2(const pj_enum_ip_option *opt, - unsigned *count, - pj_sockaddr ifs[]); + unsigned *count, + pj_sockaddr ifs[]); /** * Enumerate the IP routing table for this host. * - * @param count On input, specify the number of routes entries. On output, - * it will be filled with the actual number of route entries. + * @param count On input, specify the number of routes entries. On output, + * it will be filled with the actual number of route entries. * @param routes Array of IP routing entries. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_enum_ip_route(unsigned *count, - pj_ip_route_entry routes[]); + pj_ip_route_entry routes[]); @@ -149,5 +148,5 @@ PJ_DECL(pj_status_t) pj_enum_ip_route(unsigned *count, PJ_END_DECL -#endif /* __PJ_IP_ROUTE_H__ */ +#endif /* __PJ_IP_ROUTE_H__ */ diff --git a/pjlib/include/pj/limits.h b/pjlib/include/pj/limits.h index 8b00ae52a8..7273671983 100644 --- a/pjlib/include/pj/limits.h +++ b/pjlib/include/pj/limits.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2017 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2017 George Joseph @@ -28,24 +27,24 @@ #include /** Maximum value for signed 32-bit integer. */ -#define PJ_MAXINT32 0x7fffffff +#define PJ_MAXINT32 0x7fffffff /** Minimum value for signed 32-bit integer. */ -#define PJ_MININT32 0x80000000 +#define PJ_MININT32 0x80000000 /** Maximum value for unsigned 16-bit integer. */ -#define PJ_MAXUINT16 0xffff +#define PJ_MAXUINT16 0xffff /** Maximum value for unsigned char. */ -#define PJ_MAXUINT8 0xff +#define PJ_MAXUINT8 0xff /** Maximum value for long. */ -#define PJ_MAXLONG LONG_MAX +#define PJ_MAXLONG LONG_MAX /** Minimum value for long. */ -#define PJ_MINLONG LONG_MIN +#define PJ_MINLONG LONG_MIN /** Minimum value for unsigned long. */ -#define PJ_MAXULONG ULONG_MAX +#define PJ_MAXULONG ULONG_MAX #endif /* __PJ_LIMITS_H__ */ diff --git a/pjlib/include/pj/list.h b/pjlib/include/pj/list.h index b258ba9075..f1b5d4cdd4 100644 --- a/pjlib/include/pj/list.h +++ b/pjlib/include/pj/list.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -94,7 +93,7 @@ PJ_INLINE(void) pj_list_init(pj_list_type * node) /** * Check that the list is empty. * - * @param node The list head. + * @param node The list head. * * @return Non-zero if the list is empty, or zero if it is not empty. * @@ -108,19 +107,19 @@ PJ_INLINE(int) pj_list_empty(const pj_list_type * node) /** * Insert the node to the list before the specified element position. * - * @param pos The element to which the node will be inserted before. - * @param node The element to be inserted. + * @param pos The element to which the node will be inserted before. + * @param node The element to be inserted. * */ -PJ_IDECL(void) pj_list_insert_before(pj_list_type *pos, pj_list_type *node); +PJ_IDECL(void) pj_list_insert_before(pj_list_type *pos, pj_list_type *node); /** * Insert the node to the back of the list. This is just an alias for * #pj_list_insert_before(). * - * @param list The list. - * @param node The element to be inserted. + * @param list The list. + * @param node The element to be inserted. */ PJ_INLINE(void) pj_list_push_back(pj_list_type *list, pj_list_type *node) { @@ -131,18 +130,18 @@ PJ_INLINE(void) pj_list_push_back(pj_list_type *list, pj_list_type *node) /** * Inserts all nodes in \a nodes to the target list. * - * @param lst The target list. - * @param nodes Nodes list. + * @param lst The target list. + * @param nodes Nodes list. */ PJ_IDECL(void) pj_list_insert_nodes_before(pj_list_type *lst, - pj_list_type *nodes); + pj_list_type *nodes); /** * Insert a node to the list after the specified element position. * - * @param pos The element in the list which will precede the inserted - * element. - * @param node The element to be inserted after the position element. + * @param pos The element in the list which will precede the inserted + * element. + * @param node The element to be inserted after the position element. * */ PJ_IDECL(void) pj_list_insert_after(pj_list_type *pos, pj_list_type *node); @@ -152,8 +151,8 @@ PJ_IDECL(void) pj_list_insert_after(pj_list_type *pos, pj_list_type *node); * Insert the node to the front of the list. This is just an alias for * #pj_list_insert_after(). * - * @param list The list. - * @param node The element to be inserted. + * @param list The list. + * @param node The element to be inserted. */ PJ_INLINE(void) pj_list_push_front(pj_list_type *list, pj_list_type *node) { @@ -164,11 +163,11 @@ PJ_INLINE(void) pj_list_push_front(pj_list_type *list, pj_list_type *node) /** * Insert all nodes in \a nodes to the target list. * - * @param lst The target list. - * @param nodes Nodes list. + * @param lst The target list. + * @param nodes Nodes list. */ PJ_IDECL(void) pj_list_insert_nodes_after(pj_list_type *lst, - pj_list_type *nodes); + pj_list_type *nodes); /** @@ -180,8 +179,8 @@ PJ_IDECL(void) pj_list_insert_nodes_after(pj_list_type *lst, * at \a list2->next. If \a list2 is to be included in the operation, use * \a pj_list_insert_nodes_before. * - * @param list1 The destination list. - * @param list2 The source list. + * @param list1 The destination list. + * @param list2 The source list. * */ PJ_IDECL(void) pj_list_merge_first(pj_list_type *list1, pj_list_type *list2); @@ -196,9 +195,9 @@ PJ_IDECL(void) pj_list_merge_first(pj_list_type *list1, pj_list_type *list2); * at \a list2->next. If \a list2 is to be included in the operation, use * \a pj_list_insert_nodes_before. * - * @param list1 The element in the list which will precede the inserted - * element. - * @param list2 The element in the list to be inserted. + * @param list1 The element in the list which will precede the inserted + * element. + * @param list2 The element in the list to be inserted. * */ PJ_IDECL(void) pj_list_merge_last( pj_list_type *list1, pj_list_type *list2); @@ -207,7 +206,7 @@ PJ_IDECL(void) pj_list_merge_last( pj_list_type *list1, pj_list_type *list2); /** * Erase the node from the list it currently belongs. * - * @param node The element to be erased. + * @param node The element to be erased. */ PJ_IDECL(void) pj_list_erase(pj_list_type *node); @@ -215,14 +214,14 @@ PJ_IDECL(void) pj_list_erase(pj_list_type *node); /** * Find node in the list. * - * @param list The list head. - * @param node The node element to be searched. + * @param list The list head. + * @param node The node element to be searched. * * @return The node itself if it is found in the list, or NULL if it is not * found in the list. */ PJ_IDECL(pj_list_type*) pj_list_find_node(pj_list_type *list, - pj_list_type *node); + pj_list_type *node); /** @@ -231,26 +230,26 @@ PJ_IDECL(pj_list_type*) pj_list_find_node(pj_list_type *list, * first node, and call the user supplied comparison function until the * comparison function returns ZERO. * - * @param list The list head. - * @param value The user defined value to be passed in the comparison - * function - * @param comp The comparison function, which should return ZERO to - * indicate that the searched value is found. + * @param list The list head. + * @param value The user defined value to be passed in the comparison + * function + * @param comp The comparison function, which should return ZERO to + * indicate that the searched value is found. * * @return The first node that matched, or NULL if it is not found. */ PJ_IDECL(pj_list_type*) pj_list_search(pj_list_type *list, void *value, - int (*comp)(void *value, - const pj_list_type *node) - ); + int (*comp)(void *value, + const pj_list_type *node) + ); /** * Traverse the list to get the number of elements in the list. * - * @param list The list head. + * @param list The list head. * - * @return Number of elements. + * @return Number of elements. */ PJ_IDECL(pj_size_t) pj_list_size(const pj_list_type *list); @@ -265,5 +264,5 @@ PJ_IDECL(pj_size_t) pj_list_size(const pj_list_type *list); PJ_END_DECL -#endif /* __PJ_LIST_H__ */ +#endif /* __PJ_LIST_H__ */ diff --git a/pjlib/include/pj/list_i.h b/pjlib/include/pj/list_i.h index 91ee183f08..90718d74dd 100644 --- a/pjlib/include/pj/list_i.h +++ b/pjlib/include/pj/list_i.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -58,18 +57,18 @@ PJ_IDEF(void) pj_list_insert_nodes_before(pj_list_type *pos, pj_list_type *lst) PJ_IDEF(void) pj_list_merge_last(pj_list_type *lst1, pj_list_type *lst2) { if (!pj_list_empty(lst2)) { - pj_link_node(((pj_list*)lst1)->prev, ((pj_list*)lst2)->next); - pj_link_node(((pj_list*)lst2)->prev, lst1); - pj_list_init(lst2); + pj_link_node(((pj_list*)lst1)->prev, ((pj_list*)lst2)->next); + pj_link_node(((pj_list*)lst2)->prev, lst1); + pj_list_init(lst2); } } PJ_IDEF(void) pj_list_merge_first(pj_list_type *lst1, pj_list_type *lst2) { if (!pj_list_empty(lst2)) { - pj_link_node(((pj_list*)lst2)->prev, ((pj_list*)lst1)->next); - pj_link_node(((pj_list*)lst1), ((pj_list*)lst2)->next); - pj_list_init(lst2); + pj_link_node(((pj_list*)lst2)->prev, ((pj_list*)lst1)->next); + pj_link_node(((pj_list*)lst1), ((pj_list*)lst2)->next); + pj_list_init(lst2); } } @@ -89,18 +88,18 @@ PJ_IDEF(pj_list_type*) pj_list_find_node(pj_list_type *list, pj_list_type *node) { pj_list *p = (pj_list *) ((pj_list*)list)->next; while (p != list && p != node) - p = (pj_list *) p->next; + p = (pj_list *) p->next; return p==node ? p : NULL; } PJ_IDEF(pj_list_type*) pj_list_search(pj_list_type *list, void *value, - int (*comp)(void *value, const pj_list_type *node)) + int (*comp)(void *value, const pj_list_type *node)) { pj_list *p = (pj_list *) ((pj_list*)list)->next; while (p != list && (*comp)(value, p) != 0) - p = (pj_list *) p->next; + p = (pj_list *) p->next; return p==list ? NULL : p; } @@ -112,8 +111,8 @@ PJ_IDEF(pj_size_t) pj_list_size(const pj_list_type *list) pj_size_t count = 0; while (node != list) { - ++count; - node = (pj_list*)node->next; + ++count; + node = (pj_list*)node->next; } return count; diff --git a/pjlib/include/pj/lock.h b/pjlib/include/pj/lock.h index 86b2fa8b7d..ccf953fa8f 100644 --- a/pjlib/include/pj/lock.h +++ b/pjlib/include/pj/lock.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,71 +45,71 @@ PJ_BEGIN_DECL /** * Create simple, non recursive mutex lock object. * - * @param pool Memory pool. - * @param name Lock object's name. - * @param lock Pointer to store the returned handle. + * @param pool Memory pool. + * @param name Lock object's name. + * @param lock Pointer to store the returned handle. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_lock_create_simple_mutex( pj_pool_t *pool, - const char *name, - pj_lock_t **lock ); + const char *name, + pj_lock_t **lock ); /** * Create recursive mutex lock object. * - * @param pool Memory pool. - * @param name Lock object's name. - * @param lock Pointer to store the returned handle. + * @param pool Memory pool. + * @param name Lock object's name. + * @param lock Pointer to store the returned handle. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_lock_create_recursive_mutex( pj_pool_t *pool, - const char *name, - pj_lock_t **lock ); + const char *name, + pj_lock_t **lock ); /** * Create NULL mutex. A NULL mutex doesn't actually have any synchronization * object attached to it. * - * @param pool Memory pool. - * @param name Lock object's name. - * @param lock Pointer to store the returned handle. + * @param pool Memory pool. + * @param name Lock object's name. + * @param lock Pointer to store the returned handle. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_lock_create_null_mutex( pj_pool_t *pool, - const char *name, - pj_lock_t **lock ); + const char *name, + pj_lock_t **lock ); #if defined(PJ_HAS_SEMAPHORE) && PJ_HAS_SEMAPHORE != 0 /** * Create semaphore lock object. * - * @param pool Memory pool. - * @param name Lock object's name. + * @param pool Memory pool. + * @param name Lock object's name. * @param initial Initial value of the semaphore. - * @param max Maximum value of the semaphore. - * @param lock Pointer to store the returned handle. + * @param max Maximum value of the semaphore. + * @param lock Pointer to store the returned handle. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_lock_create_semaphore( pj_pool_t *pool, - const char *name, - unsigned initial, - unsigned max, - pj_lock_t **lock ); + const char *name, + unsigned initial, + unsigned max, + pj_lock_t **lock ); -#endif /* PJ_HAS_SEMAPHORE */ +#endif /* PJ_HAS_SEMAPHORE */ /** * Acquire lock on the specified lock object. * - * @param lock The lock object. + * @param lock The lock object. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_lock_acquire( pj_lock_t *lock ); @@ -118,9 +117,9 @@ PJ_DECL(pj_status_t) pj_lock_acquire( pj_lock_t *lock ); /** * Try to acquire lock on the specified lock object. * - * @param lock The lock object. + * @param lock The lock object. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_lock_tryacquire( pj_lock_t *lock ); @@ -128,9 +127,9 @@ PJ_DECL(pj_status_t) pj_lock_tryacquire( pj_lock_t *lock ); /** * Release lock on the specified lock object. * - * @param lock The lock object. + * @param lock The lock object. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_lock_release( pj_lock_t *lock ); @@ -138,9 +137,9 @@ PJ_DECL(pj_status_t) pj_lock_release( pj_lock_t *lock ); /** * Destroy the lock object. * - * @param lock The lock object. + * @param lock The lock object. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_lock_destroy( pj_lock_t *lock ); @@ -189,7 +188,7 @@ typedef struct pj_grp_lock_config /** * Creation flags, currently must be zero. */ - unsigned flags; + unsigned flags; } pj_grp_lock_config; @@ -198,7 +197,7 @@ typedef struct pj_grp_lock_config * The group lock destroy handler, a destructor function called when * a group lock is about to be destroyed. * - * @param member A pointer to be passed to the handler. + * @param member A pointer to be passed to the handler. */ typedef void (*pj_grp_lock_handler)(void *member); @@ -206,7 +205,7 @@ typedef void (*pj_grp_lock_handler)(void *member); /** * Initialize the config with the default values. * - * @param cfg The config to be initialized. + * @param cfg The config to be initialized. */ PJ_DECL(void) pj_grp_lock_config_default(pj_grp_lock_config *cfg); @@ -214,13 +213,13 @@ PJ_DECL(void) pj_grp_lock_config_default(pj_grp_lock_config *cfg); * Create a group lock object. Initially the group lock will have reference * counter of zero. * - * @param pool The group lock only uses the pool parameter to get - * the pool factory, from which it will create its own - * pool. - * @param cfg Optional configuration. - * @param p_grp_lock Pointer to receive the newly created group lock. + * @param pool The group lock only uses the pool parameter to get + * the pool factory, from which it will create its own + * pool. + * @param cfg Optional configuration. + * @param p_grp_lock Pointer to receive the newly created group lock. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_grp_lock_create(pj_pool_t *pool, const pj_grp_lock_config *cfg, @@ -231,28 +230,28 @@ PJ_DECL(pj_status_t) pj_grp_lock_create(pj_pool_t *pool, * called by the group lock when it is about to be destroyed. Initially the * group lock will have reference counter of zero. * - * @param pool The group lock only uses the pool parameter to get - * the pool factory, from which it will create its own - * pool. - * @param cfg Optional configuration. - * @param member A pointer to be passed to the handler. - * @param handler The destroy handler. - * @param p_grp_lock Pointer to receive the newly created group lock. + * @param pool The group lock only uses the pool parameter to get + * the pool factory, from which it will create its own + * pool. + * @param cfg Optional configuration. + * @param member A pointer to be passed to the handler. + * @param handler The destroy handler. + * @param p_grp_lock Pointer to receive the newly created group lock. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_grp_lock_create_w_handler(pj_pool_t *pool, - const pj_grp_lock_config *cfg, - void *member, + const pj_grp_lock_config *cfg, + void *member, pj_grp_lock_handler handler, - pj_grp_lock_t **p_grp_lock); + pj_grp_lock_t **p_grp_lock); /** * Forcibly destroy the group lock, ignoring the reference counter value. * - * @param grp_lock The group lock. + * @param grp_lock The group lock. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_grp_lock_destroy( pj_grp_lock_t *grp_lock); @@ -260,10 +259,10 @@ PJ_DECL(pj_status_t) pj_grp_lock_destroy( pj_grp_lock_t *grp_lock); * Move the contents of the old lock to the new lock and destroy the * old lock. * - * @param old_lock The old group lock to be destroyed. - * @param new_lock The new group lock. + * @param old_lock The old group lock to be destroyed. + * @param new_lock The new group lock. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_grp_lock_replace(pj_grp_lock_t *old_lock, pj_grp_lock_t *new_lock); @@ -271,9 +270,9 @@ PJ_DECL(pj_status_t) pj_grp_lock_replace(pj_grp_lock_t *old_lock, /** * Acquire lock on the specified group lock. * - * @param grp_lock The group lock. + * @param grp_lock The group lock. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_grp_lock_acquire( pj_grp_lock_t *grp_lock); @@ -281,9 +280,9 @@ PJ_DECL(pj_status_t) pj_grp_lock_acquire( pj_grp_lock_t *grp_lock); * Acquire lock on the specified group lock if it is available, otherwise * return immediately wihout waiting. * - * @param grp_lock The group lock. + * @param grp_lock The group lock. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_grp_lock_tryacquire( pj_grp_lock_t *grp_lock); @@ -292,9 +291,9 @@ PJ_DECL(pj_status_t) pj_grp_lock_tryacquire( pj_grp_lock_t *grp_lock); * to be destroyed if it is the last one to hold the reference counter. * In that case, the function will return PJ_EGONE. * - * @param grp_lock The group lock. + * @param grp_lock The group lock. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_grp_lock_release( pj_grp_lock_t *grp_lock); @@ -302,12 +301,12 @@ PJ_DECL(pj_status_t) pj_grp_lock_release( pj_grp_lock_t *grp_lock); * Add a destructor handler, to be called by the group lock when it is * about to be destroyed. * - * @param grp_lock The group lock. - * @param pool Pool to allocate memory for the handler. - * @param member A pointer to be passed to the handler. - * @param handler The destroy handler. + * @param grp_lock The group lock. + * @param pool Pool to allocate memory for the handler. + * @param member A pointer to be passed to the handler. + * @param handler The destroy handler. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_grp_lock_add_handler(pj_grp_lock_t *grp_lock, pj_pool_t *pool, @@ -318,11 +317,11 @@ PJ_DECL(pj_status_t) pj_grp_lock_add_handler(pj_grp_lock_t *grp_lock, * Remove previously registered handler. All parameters must be the same * as when the handler was added. * - * @param grp_lock The group lock. - * @param member A pointer to be passed to the handler. - * @param handler The destroy handler. + * @param grp_lock The group lock. + * @param member A pointer to be passed to the handler. + * @param handler The destroy handler. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_grp_lock_del_handler(pj_grp_lock_t *grp_lock, void *member, @@ -331,9 +330,9 @@ PJ_DECL(pj_status_t) pj_grp_lock_del_handler(pj_grp_lock_t *grp_lock, /** * Increment reference counter to prevent the group lock grom being destroyed. * - * @param grp_lock The group lock. + * @param grp_lock The group lock. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ #if !PJ_GRP_LOCK_DEBUG PJ_DECL(pj_status_t) pj_grp_lock_add_ref(pj_grp_lock_t *grp_lock); @@ -341,17 +340,17 @@ PJ_DECL(pj_status_t) pj_grp_lock_add_ref(pj_grp_lock_t *grp_lock); /** * Debug version of pj_grp_lock_add_ref(), allowing to specify file and lineno. * - * @param grp_lock The group lock. - * @param x Filename - * @param y Line number + * @param grp_lock The group lock. + * @param x Filename + * @param y Line number * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ #define pj_grp_lock_add_ref_dbg(grp_lock, x, y) pj_grp_lock_add_ref(grp_lock) #else -#define pj_grp_lock_add_ref(g) pj_grp_lock_add_ref_dbg(g, __FILE__, __LINE__) +#define pj_grp_lock_add_ref(g) pj_grp_lock_add_ref_dbg(g, __FILE__, __LINE__) PJ_DECL(pj_status_t) pj_grp_lock_add_ref_dbg(pj_grp_lock_t *grp_lock, const char *file, @@ -362,9 +361,9 @@ PJ_DECL(pj_status_t) pj_grp_lock_add_ref_dbg(pj_grp_lock_t *grp_lock, * Decrement the reference counter. When the counter value reaches zero, the * group lock will be destroyed and all destructor handlers will be called. * - * @param grp_lock The group lock. + * @param grp_lock The group lock. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ #if !PJ_GRP_LOCK_DEBUG PJ_DECL(pj_status_t) pj_grp_lock_dec_ref(pj_grp_lock_t *grp_lock); @@ -372,16 +371,16 @@ PJ_DECL(pj_status_t) pj_grp_lock_dec_ref(pj_grp_lock_t *grp_lock); /** * Debug version of pj_grp_lock_dec_ref(), allowing to specify file and lineno. * - * @param grp_lock The group lock. - * @param x Filename - * @param y Line number + * @param grp_lock The group lock. + * @param x Filename + * @param y Line number * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ #define pj_grp_lock_dec_ref_dbg(grp_lock, x, y) pj_grp_lock_dec_ref(grp_lock) #else -#define pj_grp_lock_dec_ref(g) pj_grp_lock_dec_ref_dbg(g, __FILE__, __LINE__) +#define pj_grp_lock_dec_ref(g) pj_grp_lock_dec_ref_dbg(g, __FILE__, __LINE__) PJ_DECL(pj_status_t) pj_grp_lock_dec_ref_dbg(pj_grp_lock_t *grp_lock, const char *file, @@ -393,9 +392,9 @@ PJ_DECL(pj_status_t) pj_grp_lock_dec_ref_dbg(pj_grp_lock_t *grp_lock, * Get current reference count value. This normally is only used for * debugging purpose. * - * @param grp_lock The group lock. + * @param grp_lock The group lock. * - * @return The reference count value. + * @return The reference count value. */ PJ_DECL(int) pj_grp_lock_get_ref(pj_grp_lock_t *grp_lock); @@ -406,7 +405,7 @@ PJ_DECL(int) pj_grp_lock_get_ref(pj_grp_lock_t *grp_lock); * reference counter value along with the source file and line. If * debugging is disabled, this will only print the reference counter. * - * @param grp_lock The group lock. + * @param grp_lock The group lock. */ PJ_DECL(void) pj_grp_lock_dump(pj_grp_lock_t *grp_lock); @@ -422,11 +421,11 @@ PJ_DECL(void) pj_grp_lock_dump(pj_grp_lock_t *grp_lock); * will be locked before the group lock (the group lock's ''pos'' value is * zero). * - * @param grp_lock The group lock. - * @param ext_lock The external lock - * @param pos The position. + * @param grp_lock The group lock. + * @param ext_lock The external lock + * @param pos The position. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_grp_lock_chain_lock(pj_grp_lock_t *grp_lock, pj_lock_t *ext_lock, @@ -435,10 +434,10 @@ PJ_DECL(pj_status_t) pj_grp_lock_chain_lock(pj_grp_lock_t *grp_lock, /** * Remove an external lock from group lock's list of synchronized locks. * - * @param grp_lock The group lock. - * @param ext_lock The external lock + * @param grp_lock The group lock. + * @param ext_lock The external lock * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_grp_lock_unchain_lock(pj_grp_lock_t *grp_lock, pj_lock_t *ext_lock); @@ -450,5 +449,5 @@ PJ_DECL(pj_status_t) pj_grp_lock_unchain_lock(pj_grp_lock_t *grp_lock, PJ_END_DECL -#endif /* __PJ_LOCK_H__ */ +#endif /* __PJ_LOCK_H__ */ diff --git a/pjlib/include/pj/log.h b/pjlib/include/pj/log.h index 2cb27c1921..c89f2b5668 100644 --- a/pjlib/include/pj/log.h +++ b/pjlib/include/pj/log.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -69,18 +68,18 @@ PJ_BEGIN_DECL */ enum pj_log_decoration { - PJ_LOG_HAS_DAY_NAME = 1, /**< Include day name [default: no] */ - PJ_LOG_HAS_YEAR = 2, /**< Include year digit [no] */ - PJ_LOG_HAS_MONTH = 4, /**< Include month [no] */ - PJ_LOG_HAS_DAY_OF_MON = 8, /**< Include day of month [no] */ - PJ_LOG_HAS_TIME = 16, /**< Include time [yes] */ + PJ_LOG_HAS_DAY_NAME = 1, /**< Include day name [default: no] */ + PJ_LOG_HAS_YEAR = 2, /**< Include year digit [no] */ + PJ_LOG_HAS_MONTH = 4, /**< Include month [no] */ + PJ_LOG_HAS_DAY_OF_MON = 8, /**< Include day of month [no] */ + PJ_LOG_HAS_TIME = 16, /**< Include time [yes] */ PJ_LOG_HAS_MICRO_SEC = 32, /**< Include microseconds [yes] */ - PJ_LOG_HAS_SENDER = 64, /**< Include sender in the log [yes] */ - PJ_LOG_HAS_NEWLINE = 128, /**< Terminate each call with newline [yes] */ - PJ_LOG_HAS_CR = 256, /**< Include carriage return [no] */ - PJ_LOG_HAS_SPACE = 512, /**< Include two spaces before log [yes] */ - PJ_LOG_HAS_COLOR = 1024, /**< Colorize logs [yes on win32] */ - PJ_LOG_HAS_LEVEL_TEXT = 2048, /**< Include level text string [no] */ + PJ_LOG_HAS_SENDER = 64, /**< Include sender in the log [yes] */ + PJ_LOG_HAS_NEWLINE = 128, /**< Terminate each call with newline [yes] */ + PJ_LOG_HAS_CR = 256, /**< Include carriage return [no] */ + PJ_LOG_HAS_SPACE = 512, /**< Include two spaces before log [yes] */ + PJ_LOG_HAS_COLOR = 1024, /**< Colorize logs [yes on win32] */ + PJ_LOG_HAS_LEVEL_TEXT = 2048, /**< Include level text string [no] */ PJ_LOG_HAS_THREAD_ID = 4096, /**< Include thread identification [no] */ PJ_LOG_HAS_THREAD_SWC = 8192, /**< Add mark when thread has switched [yes]*/ PJ_LOG_HAS_INDENT =16384 /**< Indentation. Say yes! [yes] */ @@ -90,13 +89,13 @@ enum pj_log_decoration * Write log message. * This is the main macro used to write text to the logging backend. * - * @param level The logging verbosity level. Lower number indicates higher - * importance, with level zero indicates fatal error. Only - * numeral argument is permitted (e.g. not variable). - * @param arg Enclosed 'printf' like arguments, with the first - * argument is the sender, the second argument is format - * string and the following arguments are variable number of - * arguments suitable for the format string. + * @param level The logging verbosity level. Lower number indicates higher + * importance, with level zero indicates fatal error. Only + * numeral argument is permitted (e.g. not variable). + * @param arg Enclosed 'printf' like arguments, with the first + * argument is the sender, the second argument is format + * string and the following arguments are variable number of + * arguments suitable for the format string. * * Sample: * \verbatim @@ -104,19 +103,19 @@ enum pj_log_decoration \endverbatim * @hideinitializer */ -#define PJ_LOG(level,arg) do { \ - if (level <= pj_log_get_level()) { \ - pj_log_wrapper_##level(arg); \ - } \ - } while (0) +#define PJ_LOG(level,arg) do { \ + if (level <= pj_log_get_level()) { \ + pj_log_wrapper_##level(arg); \ + } \ + } while (0) /** * Signature for function to be registered to the logging subsystem to * write the actual log message to some output device. * - * @param level Log level. - * @param data Log message, which will be NULL terminated. - * @param len Message length. + * @param level Log level. + * @param data Log message, which will be NULL terminated. + * @param len Message length. */ typedef void pj_log_func(int level, const char *data, int len); @@ -126,9 +125,9 @@ typedef void pj_log_func(int level, const char *data, int len); * Application normally should NOT need to call this function, but * rather use the PJ_LOG macro. * - * @param level Log level. + * @param level Log level. * @param buffer Log message. - * @param len Message length. + * @param len Message length. */ PJ_DECL(void) pj_log_write(int level, const char *buffer, int len); @@ -139,12 +138,12 @@ PJ_DECL(void) pj_log_write(int level, const char *buffer, int len); * Write to log. * * @param sender Source of the message. - * @param level Verbosity level. + * @param level Verbosity level. * @param format Format. * @param marker Marker. */ PJ_DECL(void) pj_log(const char *sender, int level, - const char *format, va_list marker); + const char *format, va_list marker); /** * Change log output function. The front-end logging functions will call @@ -152,15 +151,15 @@ PJ_DECL(void) pj_log(const char *sender, int level, * By default, the front-end functions use pj_log_write() to write * the messages, unless it's changed by calling this function. * - * @param func The function that will be called to write the log - * messages to the desired device. + * @param func The function that will be called to write the log + * messages to the desired device. */ PJ_DECL(void) pj_log_set_log_func( pj_log_func *func ); /** * Get the current log output function that is used to write log messages. * - * @return Current log output function. + * @return Current log output function. */ PJ_DECL(pj_log_func*) pj_log_get_log_func(void); @@ -171,15 +170,15 @@ PJ_DECL(pj_log_func*) pj_log_get_log_func(void); * the maximum level of verbosity can not exceed compile time value of * PJ_LOG_MAX_LEVEL. * - * @param level The maximum level of verbosity of the logging - * messages (6=very detailed..1=error only, 0=disabled) + * @param level The maximum level of verbosity of the logging + * messages (6=very detailed..1=error only, 0=disabled) */ PJ_DECL(void) pj_log_set_level(int level); /** * Get current maximum log verbositylevel. * - * @return Current log maximum level. + * @return Current log maximum level. */ #if 1 PJ_DECL(int) pj_log_get_level(void); @@ -194,15 +193,15 @@ PJ_DECL_DATA(int) pj_log_max_level; * can specify that date/time information should be displayed with each * log message. * - * @param decor Bitmask combination of #pj_log_decoration to control - * the layout of the log message. + * @param decor Bitmask combination of #pj_log_decoration to control + * the layout of the log message. */ PJ_DECL(void) pj_log_set_decor(unsigned decor); /** * Get current log decoration flag. * - * @return Log decoration flag. + * @return Log decoration flag. */ PJ_DECL(unsigned) pj_log_get_decor(void); @@ -211,8 +210,8 @@ PJ_DECL(unsigned) pj_log_get_decor(void); * before the message, and is useful to show the depth of function calls. * * @param indent The indentation to add or substract. Positive value - * adds current indent, negative value subtracts current - * indent. + * adds current indent, negative value subtracts current + * indent. */ PJ_DECL(void) pj_log_add_indent(int indent); @@ -226,7 +225,7 @@ PJ_DECL(void) pj_log_set_indent(int indent); /** * Get current indentation value. * - * @return Current indentation value. + * @return Current indentation value. */ PJ_DECL(int) pj_log_get_indent(void); @@ -243,16 +242,16 @@ PJ_DECL(void) pj_log_pop_indent(void); /** * Set color of log messages. * - * @param level Log level which color will be changed. - * @param color Desired color. + * @param level Log level which color will be changed. + * @param color Desired color. */ PJ_DECL(void) pj_log_set_color(int level, pj_color_t color); /** * Get color of log messages. * - * @param level Log level which color will be returned. - * @return Log color. + * @param level Log level which color will be returned. + * @return Log color. */ PJ_DECL(pj_color_t) pj_log_get_color(int level); @@ -261,7 +260,7 @@ PJ_DECL(pj_color_t) pj_log_get_color(int level); */ pj_status_t pj_log_init(void); -#else /* #if PJ_LOG_MAX_LEVEL >= 1 */ +#else /* #if PJ_LOG_MAX_LEVEL >= 1 */ /** * Change log output function. The front-end logging functions will call @@ -269,8 +268,8 @@ pj_status_t pj_log_init(void); * By default, the front-end functions use pj_log_write() to write * the messages, unless it's changed by calling this function. * - * @param func The function that will be called to write the log - * messages to the desired device. + * @param func The function that will be called to write the log + * messages to the desired device. */ # define pj_log_set_log_func(func) @@ -278,7 +277,7 @@ pj_status_t pj_log_init(void); * Write to log. * * @param sender Source of the message. - * @param level Verbosity level. + * @param level Verbosity level. * @param format Format. * @param marker Marker. */ @@ -291,8 +290,8 @@ pj_status_t pj_log_init(void); * the maximum level of verbosity can not exceed compile time value of * PJ_LOG_MAX_LEVEL. * - * @param level The maximum level of verbosity of the logging - * messages (6=very detailed..1=error only, 0=disabled) + * @param level The maximum level of verbosity of the logging + * messages (6=very detailed..1=error only, 0=disabled) */ # define pj_log_set_level(level) @@ -302,8 +301,8 @@ pj_status_t pj_log_init(void); * can specify that date/time information should be displayed with each * log message. * - * @param decor Bitmask combination of #pj_log_decoration to control - * the layout of the log message. + * @param decor Bitmask combination of #pj_log_decoration to control + * the layout of the log message. */ # define pj_log_set_decor(decor) @@ -312,8 +311,8 @@ pj_status_t pj_log_init(void); * before the message, and is useful to show the depth of function calls. * * @param indent The indentation to add or substract. Positive value - * adds current indent, negative value subtracts current - * indent. + * adds current indent, negative value subtracts current + * indent. */ # define pj_log_add_indent(indent) @@ -327,9 +326,9 @@ pj_status_t pj_log_init(void); /** * Get current indentation value. * - * @return Current indentation value. + * @return Current indentation value. */ -# define pj_log_get_indent() 0 +# define pj_log_get_indent() 0 /** * Push indentation to the right by default value (PJ_LOG_INDENT_SIZE). @@ -344,30 +343,30 @@ pj_status_t pj_log_init(void); /** * Set color of log messages. * - * @param level Log level which color will be changed. - * @param color Desired color. + * @param level Log level which color will be changed. + * @param color Desired color. */ # define pj_log_set_color(level, color) /** * Get current maximum log verbositylevel. * - * @return Current log maximum level. + * @return Current log maximum level. */ -# define pj_log_get_level() 0 +# define pj_log_get_level() 0 /** * Get current log decoration flag. * - * @return Log decoration flag. + * @return Log decoration flag. */ -# define pj_log_get_decor() 0 +# define pj_log_get_decor() 0 /** * Get color of log messages. * - * @param level Log level which color will be returned. - * @return Log color. + * @param level Log level which color will be returned. + * @return Log color. */ # define pj_log_get_color(level) 0 @@ -375,9 +374,9 @@ pj_status_t pj_log_init(void); /** * Internal. */ -# define pj_log_init() PJ_SUCCESS +# define pj_log_init() PJ_SUCCESS -#endif /* #if PJ_LOG_MAX_LEVEL >= 1 */ +#endif /* #if PJ_LOG_MAX_LEVEL >= 1 */ /** * @} @@ -398,7 +397,7 @@ pj_status_t pj_log_init(void); * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 1 - #define pj_log_wrapper_1(arg) pj_log_1 arg + #define pj_log_wrapper_1(arg) pj_log_1 arg /** Internal function. */ PJ_DECL(void) pj_log_1(const char *src, const char *format, ...); #else @@ -412,7 +411,7 @@ pj_status_t pj_log_init(void); * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 2 - #define pj_log_wrapper_2(arg) pj_log_2 arg + #define pj_log_wrapper_2(arg) pj_log_2 arg /** Internal function. */ PJ_DECL(void) pj_log_2(const char *src, const char *format, ...); #else @@ -426,7 +425,7 @@ pj_status_t pj_log_init(void); * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 3 - #define pj_log_wrapper_3(arg) pj_log_3 arg + #define pj_log_wrapper_3(arg) pj_log_3 arg /** Internal function. */ PJ_DECL(void) pj_log_3(const char *src, const char *format, ...); #else @@ -440,7 +439,7 @@ pj_status_t pj_log_init(void); * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 4 - #define pj_log_wrapper_4(arg) pj_log_4 arg + #define pj_log_wrapper_4(arg) pj_log_4 arg /** Internal function. */ PJ_DECL(void) pj_log_4(const char *src, const char *format, ...); #else @@ -454,7 +453,7 @@ pj_status_t pj_log_init(void); * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 5 - #define pj_log_wrapper_5(arg) pj_log_5 arg + #define pj_log_wrapper_5(arg) pj_log_5 arg /** Internal function. */ PJ_DECL(void) pj_log_5(const char *src, const char *format, ...); #else @@ -468,7 +467,7 @@ pj_status_t pj_log_init(void); * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 6 - #define pj_log_wrapper_6(arg) pj_log_6 arg + #define pj_log_wrapper_6(arg) pj_log_6 arg /** Internal function. */ PJ_DECL(void) pj_log_6(const char *src, const char *format, ...); #else diff --git a/pjlib/include/pj/math.h b/pjlib/include/pj/math.h index 4485aeaa60..53d9f0e261 100644 --- a/pjlib/include/pj/math.h +++ b/pjlib/include/pj/math.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,40 +45,40 @@ PJ_BEGIN_DECL * Mathematical constants */ /** pi */ -#define PJ_PI 3.14159265358979323846 /* pi */ +#define PJ_PI 3.14159265358979323846 /* pi */ /** 1/pi */ -#define PJ_1_PI 0.318309886183790671538 /* 1/pi */ +#define PJ_1_PI 0.318309886183790671538 /* 1/pi */ /** * Mathematical macros */ /** Get the absolute value */ -#define PJ_ABS(x) ((x) > 0 ? (x) : -(x)) +#define PJ_ABS(x) ((x) > 0 ? (x) : -(x)) /** Get the maximum of two values */ -#define PJ_MAX(x, y) ((x) > (y)? (x) : (y)) +#define PJ_MAX(x, y) ((x) > (y)? (x) : (y)) /** Get the minimum of two values */ -#define PJ_MIN(x, y) ((x) < (y)? (x) : (y)) +#define PJ_MIN(x, y) ((x) < (y)? (x) : (y)) /** * This structure describes statistics state. */ typedef struct pj_math_stat { - int n; /**< number of samples */ - int max; /**< maximum value */ - int min; /**< minimum value */ - int last; /**< last value */ - int mean; /**< mean */ + int n; /**< number of samples */ + int max; /**< maximum value */ + int min; /**< minimum value */ + int last; /**< last value */ + int mean; /**< mean */ /* Private members */ #if PJ_HAS_FLOATING_POINT - float fmean_; /**< mean(floating point) */ + float fmean_; /**< mean(floating point) */ #else - int mean_res_; /**< mean residue */ + int mean_res_; /**< mean residue */ #endif - pj_highprec_t m2_; /**< variance * n */ + pj_highprec_t m2_; /**< variance * n */ } pj_math_stat; /** @@ -96,14 +95,14 @@ PJ_INLINE(unsigned) pj_isqrt(unsigned i) /* Rough guess, calculate half bit of input */ prev = i >> 2; while (prev) { - prev >>= 2; - res <<= 1; + prev >>= 2; + res <<= 1; } /* Babilonian method */ do { - prev = res; - res = (prev + i/prev) >> 1; + prev = res; + res = (prev + i/prev) >> 1; } while ((prev+res)>>1 != res); return res; @@ -112,7 +111,7 @@ PJ_INLINE(unsigned) pj_isqrt(unsigned i) /** * Initialize statistics state. * - * @param stat Statistic state. + * @param stat Statistic state. */ PJ_INLINE(void) pj_math_stat_init(pj_math_stat *stat) { @@ -122,26 +121,26 @@ PJ_INLINE(void) pj_math_stat_init(pj_math_stat *stat) /** * Update statistics state as a new sample comes. * - * @param stat Statistic state. - * @param val The new sample data. + * @param stat Statistic state. + * @param val The new sample data. */ PJ_INLINE(void) pj_math_stat_update(pj_math_stat *stat, int val) { #if PJ_HAS_FLOATING_POINT - float delta; + float delta; #else - int delta; + int delta; #endif stat->last = val; if (stat->n++) { - if (stat->min > val) - stat->min = val; - if (stat->max < val) - stat->max = val; + if (stat->min > val) + stat->min = val; + if (stat->max < val) + stat->max = val; } else { - stat->min = stat->max = val; + stat->min = stat->max = val; } #if PJ_HAS_FLOATING_POINT @@ -157,11 +156,11 @@ PJ_INLINE(void) pj_math_stat_update(pj_math_stat *stat, int val) stat->mean += delta/stat->n; stat->mean_res_ += delta % stat->n; if (stat->mean_res_ >= stat->n) { - ++stat->mean; - stat->mean_res_ -= stat->n; + ++stat->mean; + stat->mean_res_ -= stat->n; } else if (stat->mean_res_ <= -stat->n) { - --stat->mean; - stat->mean_res_ += stat->n; + --stat->mean; + stat->mean_res_ += stat->n; } stat->m2_ += delta * (val-stat->mean); @@ -171,9 +170,9 @@ PJ_INLINE(void) pj_math_stat_update(pj_math_stat *stat, int val) /** * Get the standard deviation of specified statistics state. * - * @param stat Statistic state. + * @param stat Statistic state. * - * @return The standard deviation. + * @return The standard deviation. */ PJ_INLINE(unsigned) pj_math_stat_get_stddev(const pj_math_stat *stat) { @@ -186,14 +185,14 @@ PJ_INLINE(unsigned) pj_math_stat_get_stddev(const pj_math_stat *stat) * the statistic state is operated in 'read-only' mode as a storage of * statistical data. * - * @param stat Statistic state. + * @param stat Statistic state. * - * @param dev The standard deviation. + * @param dev The standard deviation. */ PJ_INLINE(void) pj_math_stat_set_stddev(pj_math_stat *stat, unsigned dev) { if (stat->n == 0) - stat->n = 1; + stat->n = 1; stat->m2_ = dev*dev*stat->n; } diff --git a/pjlib/include/pj/os.h b/pjlib/include/pj/os.h index 738ddec3b1..64597180dc 100644 --- a/pjlib/include/pj/os.h +++ b/pjlib/include/pj/os.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -64,14 +63,14 @@ typedef struct pj_sys_info * Null terminated string containing processor information (e.g. "i386", * "x86_64"). It may contain empty string if the value cannot be obtained. */ - pj_str_t machine; + pj_str_t machine; /** * Null terminated string identifying the system operation (e.g. "Linux", * "win32", "wince"). It may contain empty string if the value cannot be * obtained. */ - pj_str_t os_name; + pj_str_t os_name; /** * A number containing the operating system version number. By convention, @@ -85,33 +84,33 @@ typedef struct pj_sys_info * * This field may contain zero if the OS version cannot be obtained. */ - pj_uint32_t os_ver; + pj_uint32_t os_ver; /** * Null terminated string identifying the SDK name that is used to build * the library (e.g. "glibc", "uclibc", "msvc", "wince"). It may contain * empty string if the value cannot eb obtained. */ - pj_str_t sdk_name; + pj_str_t sdk_name; /** * A number containing the SDK version, using the numbering convention as * the "os_ver" field. The value will be zero if the version cannot be * obtained. */ - pj_uint32_t sdk_ver; + pj_uint32_t sdk_ver; /** * A longer null terminated string identifying the underlying system with * as much information as possible. */ - pj_str_t info; + pj_str_t info; /** * Other flags containing system specific information. The value is * bitmask of #pj_sys_info_flag constants. */ - pj_uint32_t flags; + pj_uint32_t flags; } pj_sys_info; @@ -119,7 +118,7 @@ typedef struct pj_sys_info /** * Obtain the system information. * - * @return System information structure. + * @return System information structure. */ PJ_DECL(const pj_sys_info*) pj_get_sys_info(void); @@ -161,7 +160,7 @@ typedef int (PJ_THREAD_FUNC pj_thread_proc)(void*); * Size of thread struct. */ #if !defined(PJ_THREAD_DESC_SIZE) -# define PJ_THREAD_DESC_SIZE (64) +# define PJ_THREAD_DESC_SIZE (64) #endif /** @@ -186,22 +185,22 @@ PJ_DECL(pj_uint32_t) pj_getpid(void); * @param arg Argument to be passed to the thread entry function. * @param stack_size The size of the stack for the new thread, or ZERO or * PJ_THREAD_DEFAULT_STACK_SIZE to let the - * library choose the reasonable size for the stack. + * library choose the reasonable size for the stack. * For some systems, the stack will be allocated from * the pool, so the pool must have suitable capacity. * @param flags Flags for thread creation, which is bitmask combination * from enum pj_thread_create_flags. * @param thread Pointer to hold the newly created thread. * - * @return PJ_SUCCESS on success, or the error code. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_thread_create( pj_pool_t *pool, const char *thread_name, - pj_thread_proc *proc, + pj_thread_proc *proc, void *arg, - pj_size_t stack_size, + pj_size_t stack_size, unsigned flags, - pj_thread_t **thread ); + pj_thread_t **thread ); /** * Register a thread that was created by external or native API to PJLIB. @@ -220,13 +219,13 @@ PJ_DECL(pj_status_t) pj_thread_create( pj_pool_t *pool, * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_thread_register ( const char *thread_name, - pj_thread_desc desc, - pj_thread_t **thread); + pj_thread_desc desc, + pj_thread_t **thread); /** * Check if this thread has been registered to PJLIB. * - * @return Non-zero if it is registered. + * @return Non-zero if it is registered. */ PJ_DECL(pj_bool_t) pj_thread_is_registered(void); @@ -234,9 +233,9 @@ PJ_DECL(pj_bool_t) pj_thread_is_registered(void); /** * Get thread priority value for the thread. * - * @param thread Thread handle. + * @param thread Thread handle. * - * @return Thread priority value, or -1 on error. + * @return Thread priority value, or -1 on error. */ PJ_DECL(int) pj_thread_get_prio(pj_thread_t *thread); @@ -249,18 +248,18 @@ PJ_DECL(int) pj_thread_get_prio(pj_thread_t *thread); * For Android, this function will only set the priority of the calling thread * (the thread param must be set to NULL or the calling thread handle). * - * @param thread Thread handle. - * @param prio New priority to be set to the thread. + * @param thread Thread handle. + * @param prio New priority to be set to the thread. * - * @return PJ_SUCCESS on success or the error code. + * @return PJ_SUCCESS on success or the error code. */ PJ_DECL(pj_status_t) pj_thread_set_prio(pj_thread_t *thread, int prio); /** * Get the lowest priority value available for this thread. * - * @param thread Thread handle. - * @return Minimum thread priority value, or -1 on error. + * @param thread Thread handle. + * @return Minimum thread priority value, or -1 on error. */ PJ_DECL(int) pj_thread_get_prio_min(pj_thread_t *thread); @@ -268,8 +267,8 @@ PJ_DECL(int) pj_thread_get_prio_min(pj_thread_t *thread); /** * Get the highest priority value available for this thread. * - * @param thread Thread handle. - * @return Minimum thread priority value, or -1 on error. + * @param thread Thread handle. + * @return Minimum thread priority value, or -1 on error. */ PJ_DECL(int) pj_thread_get_prio_max(pj_thread_t *thread); @@ -278,12 +277,12 @@ PJ_DECL(int) pj_thread_get_prio_max(pj_thread_t *thread); * Return native handle from pj_thread_t for manipulation using native * OS APIs. * - * @param thread PJLIB thread descriptor. + * @param thread PJLIB thread descriptor. * - * @return Native thread handle. For example, when the - * backend thread uses pthread, this function will - * return pointer to pthread_t, and on Windows, - * this function will return HANDLE. + * @return Native thread handle. For example, when the + * backend thread uses pthread, this function will + * return pointer to pthread_t, and on Windows, + * this function will return HANDLE. */ PJ_DECL(void*) pj_thread_get_os_handle(pj_thread_t *thread); @@ -371,16 +370,16 @@ PJ_DECL(pj_uint32_t) pj_thread_get_stack_max_usage(pj_thread_t *thread); * Dump thread stack status. */ PJ_DECL(pj_status_t) pj_thread_get_stack_info(pj_thread_t *thread, - const char **file, - int *line); + const char **file, + int *line); #else # define PJ_CHECK_STACK() /** pj_thread_get_stack_max_usage() for the thread */ -# define pj_thread_get_stack_max_usage(thread) 0 +# define pj_thread_get_stack_max_usage(thread) 0 /** pj_thread_get_stack_info() for the thread */ -# define pj_thread_get_stack_info(thread,f,l) (*(f)="",*(l)=0) -#endif /* PJ_OS_HAS_CHECK_STACK */ +# define pj_thread_get_stack_info(thread,f,l) (*(f)="",*(l)=0) +#endif /* PJ_OS_HAS_CHECK_STACK */ /** * @} @@ -398,17 +397,17 @@ PJ_DECL(pj_status_t) pj_thread_get_stack_info(pj_thread_t *thread, * pattern to allow application (in this case, PJLIB) to register asynchronous * tasks. PJLIB port for Symbian complies to this recommended behavior. * As the result, few things have been changed in PJLIB for Symbian: - * - the timer heap (see @ref PJ_TIMER) is implemented with active - * object framework, and each timer entry registered to the timer - * heap will register an Active Object to the Active Scheduler. - * Because of this, polling the timer heap with pj_timer_heap_poll() - * is no longer necessary, and this function will just evaluate - * to nothing. - * - the ioqueue (see @ref PJ_IOQUEUE) is also implemented with - * active object framework, with each asynchronous operation will - * register an Active Object to the Active Scheduler. Because of - * this, polling the ioqueue with pj_ioqueue_poll() is no longer - * necessary, and this function will just evaluate to nothing. + * - the timer heap (see @ref PJ_TIMER) is implemented with active + * object framework, and each timer entry registered to the timer + * heap will register an Active Object to the Active Scheduler. + * Because of this, polling the timer heap with pj_timer_heap_poll() + * is no longer necessary, and this function will just evaluate + * to nothing. + * - the ioqueue (see @ref PJ_IOQUEUE) is also implemented with + * active object framework, with each asynchronous operation will + * register an Active Object to the Active Scheduler. Because of + * this, polling the ioqueue with pj_ioqueue_poll() is no longer + * necessary, and this function will just evaluate to nothing. * * Since timer heap and ioqueue polling are no longer necessary, Symbian * application can now poll for all events by calling @@ -429,19 +428,19 @@ PJ_DECL(pj_status_t) pj_thread_get_stack_info(pj_thread_t *thread, * really necessary (for example, when it's not sure there are other * Active Objects currently running in the application). * - * @param priority The minimum priority of the Active Objects to - * poll, which values are from CActive::TPriority - * constants. If -1 is given, CActive::EPriorityStandard. - * priority will be used. - * @param ms_timeout Optional timeout to wait. Application should - * specify -1 to let the function wait indefinitely - * for any events. + * @param priority The minimum priority of the Active Objects to + * poll, which values are from CActive::TPriority + * constants. If -1 is given, CActive::EPriorityStandard. + * priority will be used. + * @param ms_timeout Optional timeout to wait. Application should + * specify -1 to let the function wait indefinitely + * for any events. * - * @return PJ_TRUE if there have been any events executed - * during the polling. This function will only return - * PJ_FALSE if \a ms_timeout argument is specified - * (i.e. the value is not -1) and there was no event - * executed when the timeout timer elapsed. + * @return PJ_TRUE if there have been any events executed + * during the polling. This function will only return + * PJ_FALSE if \a ms_timeout argument is specified + * (i.e. the value is not -1) and there was no event + * executed when the timeout timer elapsed. */ PJ_DECL(pj_bool_t) pj_symbianos_poll(int priority, int ms_timeout); @@ -457,28 +456,28 @@ typedef struct pj_symbianos_params * value is NULL, PJLIB will create a new RSocketServ instance * when pj_init() is called. */ - void *rsocketserv; + void *rsocketserv; /** * Optional RConnection instance to be used by PJLIB when creating * sockets. If this value is NULL, no RConnection will be * specified when creating sockets. */ - void *rconnection; + void *rconnection; /** * Optional RHostResolver instance to be used by PJLIB. If this value * is NULL, a new RHostResolver instance will be created when * pj_init() is called. */ - void *rhostresolver; + void *rhostresolver; /** * Optional RHostResolver for IPv6 instance to be used by PJLIB. * If this value is NULL, a new RHostResolver instance will be created * when pj_init() is called. */ - void *rhostresolver6; + void *rhostresolver6; } pj_symbianos_params; @@ -486,10 +485,10 @@ typedef struct pj_symbianos_params * Specify Symbian OS parameters to be used by PJLIB. This function MUST * be called before #pj_init() is called. * - * @param prm Symbian specific parameters. + * @param prm Symbian specific parameters. * - * @return PJ_SUCCESS if the parameters can be applied - * successfully. + * @return PJ_SUCCESS if the parameters can be applied + * successfully. */ PJ_DECL(pj_status_t) pj_symbianos_set_params(pj_symbianos_params *prm); @@ -500,9 +499,9 @@ PJ_DECL(pj_status_t) pj_symbianos_set_params(pj_symbianos_params *prm); * different access point may cause the WaitForRequest() for the function to * block indefinitely. * - * @param up If set to PJ_FALSE it will cause PJLIB to not try - * to access socket API, and error will be returned - * immediately instead. + * @param up If set to PJ_FALSE it will cause PJLIB to not try + * to access socket API, and error will be returned + * immediately instead. */ PJ_DECL(void) pj_symbianos_set_connection_status(pj_bool_t up); @@ -521,31 +520,31 @@ PJ_DECL(void) pj_symbianos_set_connection_status(pj_bool_t up); * Allocate thread local storage index. The initial value of the variable at * the index is zero. * - * @param index Pointer to hold the return value. - * @return PJ_SUCCESS on success, or the error code. + * @param index Pointer to hold the return value. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_thread_local_alloc(long *index); /** * Deallocate thread local variable. * - * @param index The variable index. + * @param index The variable index. */ PJ_DECL(void) pj_thread_local_free(long index); /** * Set the value of thread local variable. * - * @param index The index of the variable. - * @param value The value. + * @param index The index of the variable. + * @param value The value. */ PJ_DECL(pj_status_t) pj_thread_local_set(long index, void *value); /** * Get the value of thread local variable. * - * @param index The index of the variable. - * @return The value. + * @param index The index of the variable. + * @return The value. */ PJ_DECL(void*) pj_thread_local_get(long index); @@ -573,20 +572,20 @@ PJ_DECL(void*) pj_thread_local_get(long index); /** * Create atomic variable. * - * @param pool The pool. + * @param pool The pool. * @param initial The initial value of the atomic variable. * @param atomic Pointer to hold the atomic variable upon return. * - * @return PJ_SUCCESS on success, or the error code. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_atomic_create( pj_pool_t *pool, - pj_atomic_value_t initial, - pj_atomic_t **atomic ); + pj_atomic_value_t initial, + pj_atomic_t **atomic ); /** * Destroy atomic variable. * - * @param atomic_var the atomic variable. + * @param atomic_var the atomic variable. * * @return PJ_SUCCESS if success. */ @@ -595,16 +594,16 @@ PJ_DECL(pj_status_t) pj_atomic_destroy( pj_atomic_t *atomic_var ); /** * Set the value of an atomic type, and return the previous value. * - * @param atomic_var the atomic variable. - * @param value value to be set to the variable. + * @param atomic_var the atomic variable. + * @param value value to be set to the variable. */ PJ_DECL(void) pj_atomic_set( pj_atomic_t *atomic_var, - pj_atomic_value_t value); + pj_atomic_value_t value); /** * Get the value of an atomic type. * - * @param atomic_var the atomic variable. + * @param atomic_var the atomic variable. * * @return the value of the atomic variable. */ @@ -613,14 +612,14 @@ PJ_DECL(pj_atomic_value_t) pj_atomic_get(pj_atomic_t *atomic_var); /** * Increment the value of an atomic type. * - * @param atomic_var the atomic variable. + * @param atomic_var the atomic variable. */ PJ_DECL(void) pj_atomic_inc(pj_atomic_t *atomic_var); /** * Increment the value of an atomic type and get the result. * - * @param atomic_var the atomic variable. + * @param atomic_var the atomic variable. * * @return The incremented value. */ @@ -629,14 +628,14 @@ PJ_DECL(pj_atomic_value_t) pj_atomic_inc_and_get(pj_atomic_t *atomic_var); /** * Decrement the value of an atomic type. * - * @param atomic_var the atomic variable. + * @param atomic_var the atomic variable. */ PJ_DECL(void) pj_atomic_dec(pj_atomic_t *atomic_var); /** * Decrement the value of an atomic type and get the result. * - * @param atomic_var the atomic variable. + * @param atomic_var the atomic variable. * * @return The decremented value. */ @@ -645,22 +644,22 @@ PJ_DECL(pj_atomic_value_t) pj_atomic_dec_and_get(pj_atomic_t *atomic_var); /** * Add a value to an atomic type. * - * @param atomic_var The atomic variable. - * @param value Value to be added. + * @param atomic_var The atomic variable. + * @param value Value to be added. */ PJ_DECL(void) pj_atomic_add( pj_atomic_t *atomic_var, - pj_atomic_value_t value); + pj_atomic_value_t value); /** * Add a value to an atomic type and get the result. * - * @param atomic_var The atomic variable. - * @param value Value to be added. + * @param atomic_var The atomic variable. + * @param value Value to be added. * * @return The result after the addition. */ PJ_DECL(pj_atomic_value_t) pj_atomic_add_and_get( pj_atomic_t *atomic_var, - pj_atomic_value_t value); + pj_atomic_value_t value); /** * @} @@ -694,16 +693,16 @@ typedef enum pj_mutex_type_e /** * Create mutex of the specified type. * - * @param pool The pool. - * @param name Name to be associated with the mutex (for debugging). - * @param type The type of the mutex, of type #pj_mutex_type_e. - * @param mutex Pointer to hold the returned mutex instance. + * @param pool The pool. + * @param name Name to be associated with the mutex (for debugging). + * @param type The type of the mutex, of type #pj_mutex_type_e. + * @param mutex Pointer to hold the returned mutex instance. * - * @return PJ_SUCCESS on success, or the error code. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_mutex_create(pj_pool_t *pool, const char *name, - int type, + int type, pj_mutex_t **mutex); /** @@ -711,68 +710,68 @@ PJ_DECL(pj_status_t) pj_mutex_create(pj_pool_t *pool, * This function is a simple wrapper for #pj_mutex_create to create * non-recursive mutex. * - * @param pool The pool. - * @param name Mutex name. - * @param mutex Pointer to hold the returned mutex instance. + * @param pool The pool. + * @param name Mutex name. + * @param mutex Pointer to hold the returned mutex instance. * - * @return PJ_SUCCESS on success, or the error code. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_mutex_create_simple( pj_pool_t *pool, const char *name, - pj_mutex_t **mutex ); + pj_mutex_t **mutex ); /** * Create recursive mutex. * This function is a simple wrapper for #pj_mutex_create to create * recursive mutex. * - * @param pool The pool. - * @param name Mutex name. - * @param mutex Pointer to hold the returned mutex instance. + * @param pool The pool. + * @param name Mutex name. + * @param mutex Pointer to hold the returned mutex instance. * - * @return PJ_SUCCESS on success, or the error code. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_mutex_create_recursive( pj_pool_t *pool, - const char *name, - pj_mutex_t **mutex ); + const char *name, + pj_mutex_t **mutex ); /** * Acquire mutex lock. * - * @param mutex The mutex. - * @return PJ_SUCCESS on success, or the error code. + * @param mutex The mutex. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_mutex_lock(pj_mutex_t *mutex); /** * Release mutex lock. * - * @param mutex The mutex. - * @return PJ_SUCCESS on success, or the error code. + * @param mutex The mutex. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_mutex_unlock(pj_mutex_t *mutex); /** * Try to acquire mutex lock. * - * @param mutex The mutex. - * @return PJ_SUCCESS on success, or the error code if the - * lock couldn't be acquired. + * @param mutex The mutex. + * @return PJ_SUCCESS on success, or the error code if the + * lock couldn't be acquired. */ PJ_DECL(pj_status_t) pj_mutex_trylock(pj_mutex_t *mutex); /** * Destroy mutex. * - * @param mutex Te mutex. - * @return PJ_SUCCESS on success, or the error code. + * @param mutex Te mutex. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_mutex_destroy(pj_mutex_t *mutex); /** * Determine whether calling thread is owning the mutex (only available when * PJ_DEBUG is set). - * @param mutex The mutex. - * @return Non-zero if yes. + * @param mutex The mutex. + * @return Non-zero if yes. */ PJ_DECL(pj_bool_t) pj_mutex_is_locked(pj_mutex_t *mutex); @@ -801,52 +800,52 @@ typedef struct pj_rwmutex_t pj_rwmutex_t; /** * Create reader/writer mutex. * - * @param pool Pool to allocate memory for the mutex. - * @param name Name to be assigned to the mutex. - * @param mutex Pointer to receive the newly created mutex. + * @param pool Pool to allocate memory for the mutex. + * @param name Name to be assigned to the mutex. + * @param mutex Pointer to receive the newly created mutex. * - * @return PJ_SUCCESS on success, or the error code. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_rwmutex_create(pj_pool_t *pool, const char *name, - pj_rwmutex_t **mutex); + pj_rwmutex_t **mutex); /** * Lock the mutex for reading. * - * @param mutex The mutex. - * @return PJ_SUCCESS on success, or the error code. + * @param mutex The mutex. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_rwmutex_lock_read(pj_rwmutex_t *mutex); /** * Lock the mutex for writing. * - * @param mutex The mutex. - * @return PJ_SUCCESS on success, or the error code. + * @param mutex The mutex. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_rwmutex_lock_write(pj_rwmutex_t *mutex); /** * Release read lock. * - * @param mutex The mutex. - * @return PJ_SUCCESS on success, or the error code. + * @param mutex The mutex. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_rwmutex_unlock_read(pj_rwmutex_t *mutex); /** * Release write lock. * - * @param mutex The mutex. - * @return PJ_SUCCESS on success, or the error code. + * @param mutex The mutex. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_rwmutex_unlock_write(pj_rwmutex_t *mutex); /** * Destroy reader/writer mutex. * - * @param mutex The mutex. - * @return PJ_SUCCESS on success, or the error code. + * @param mutex The mutex. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_rwmutex_destroy(pj_rwmutex_t *mutex); @@ -903,60 +902,60 @@ PJ_DECL(void) pj_leave_critical_section(void); /** * Create semaphore. * - * @param pool The pool. - * @param name Name to be assigned to the semaphore (for logging purpose) + * @param pool The pool. + * @param name Name to be assigned to the semaphore (for logging purpose) * @param initial The initial count of the semaphore. - * @param max The maximum count of the semaphore. - * @param sem Pointer to hold the semaphore created. + * @param max The maximum count of the semaphore. + * @param sem Pointer to hold the semaphore created. * - * @return PJ_SUCCESS on success, or the error code. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_sem_create( pj_pool_t *pool, const char *name, - unsigned initial, + unsigned initial, unsigned max, - pj_sem_t **sem); + pj_sem_t **sem); /** * Wait for semaphore. * - * @param sem The semaphore. + * @param sem The semaphore. * - * @return PJ_SUCCESS on success, or the error code. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_sem_wait(pj_sem_t *sem); /** * Try wait for semaphore. * - * @param sem The semaphore. + * @param sem The semaphore. * - * @return PJ_SUCCESS on success, or the error code. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_sem_trywait(pj_sem_t *sem); /** * Release semaphore. * - * @param sem The semaphore. + * @param sem The semaphore. * - * @return PJ_SUCCESS on success, or the error code. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_sem_post(pj_sem_t *sem); /** * Destroy semaphore. * - * @param sem The semaphore. + * @param sem The semaphore. * - * @return PJ_SUCCESS on success, or the error code. + * @return PJ_SUCCESS on success, or the error code. */ PJ_DECL(pj_status_t) pj_sem_destroy(pj_sem_t *sem); /** * @} */ -#endif /* PJ_HAS_SEMAPHORE */ +#endif /* PJ_HAS_SEMAPHORE */ /* **************************************************************************/ @@ -973,22 +972,22 @@ PJ_DECL(pj_status_t) pj_sem_destroy(pj_sem_t *sem); /** * Create event object. * - * @param pool The pool. - * @param name The name of the event object (for logging purpose). - * @param manual_reset Specify whether the event is manual-reset - * @param initial Specify the initial state of the event object. - * @param event Pointer to hold the returned event object. + * @param pool The pool. + * @param name The name of the event object (for logging purpose). + * @param manual_reset Specify whether the event is manual-reset + * @param initial Specify the initial state of the event object. + * @param event Pointer to hold the returned event object. * * @return event handle, or NULL if failed. */ PJ_DECL(pj_status_t) pj_event_create(pj_pool_t *pool, const char *name, - pj_bool_t manual_reset, pj_bool_t initial, - pj_event_t **event); + pj_bool_t manual_reset, pj_bool_t initial, + pj_event_t **event); /** * Wait for event to be signaled. * - * @param event The event object. + * @param event The event object. * * @return zero if successfull. */ @@ -1010,7 +1009,7 @@ PJ_DECL(pj_status_t) pj_event_trywait(pj_event_t *event); * If there is no thread waiting on the event, the event object state * remains signaled. * - * @param event The event object. + * @param event The event object. * * @return zero if successfull. */ @@ -1022,7 +1021,7 @@ PJ_DECL(pj_status_t) pj_event_set(pj_event_t *event); * manual-reset event, this function will release all waiting threads. For * auto-reset event, this function will only release one waiting thread. * - * @param event The event object. + * @param event The event object. * * @return zero if successfull. */ @@ -1031,7 +1030,7 @@ PJ_DECL(pj_status_t) pj_event_pulse(pj_event_t *event); /** * Set the event object state to non-signaled. * - * @param event The event object. + * @param event The event object. * * @return zero if successfull. */ @@ -1040,7 +1039,7 @@ PJ_DECL(pj_status_t) pj_event_reset(pj_event_t *event); /** * Destroy the event object. * - * @param event The event object. + * @param event The event object. * * @return zero if successfull. */ @@ -1049,7 +1048,7 @@ PJ_DECL(pj_status_t) pj_event_destroy(pj_event_t *event); /** * @} */ -#endif /* PJ_HAS_EVENT_OBJ */ +#endif /* PJ_HAS_EVENT_OBJ */ /* **************************************************************************/ /** @@ -1067,7 +1066,7 @@ PJ_DECL(pj_status_t) pj_event_destroy(pj_event_t *event); /** * Get current time of day in local representation. * - * @param tv Variable to store the result. + * @param tv Variable to store the result. * * @return zero if successfull. */ @@ -1077,8 +1076,8 @@ PJ_DECL(pj_status_t) pj_gettimeofday(pj_time_val *tv); /** * Parse time value into date/time representation. * - * @param tv The time. - * @param pt Variable to store the date time result. + * @param tv The time. + * @param pt Variable to store the date time result. * * @return zero if successfull. */ @@ -1087,8 +1086,8 @@ PJ_DECL(pj_status_t) pj_time_decode(const pj_time_val *tv, pj_parsed_time *pt); /** * Encode date/time to time value. * - * @param pt The date/time. - * @param tv Variable to store time value result. + * @param pt The date/time. + * @param tv Variable to store time value result. * * @return zero if successfull. */ @@ -1097,7 +1096,7 @@ PJ_DECL(pj_status_t) pj_time_encode(const pj_parsed_time *pt, pj_time_val *tv); /** * Convert local time to GMT. * - * @param tv Time to convert. + * @param tv Time to convert. * * @return zero if successfull. */ @@ -1106,7 +1105,7 @@ PJ_DECL(pj_status_t) pj_time_local_to_gmt(pj_time_val *tv); /** * Convert GMT to local time. * - * @param tv Time to convert. + * @param tv Time to convert. * * @return zero if successfull. */ @@ -1128,7 +1127,7 @@ PJ_DECL(pj_status_t) pj_time_gmt_to_local(pj_time_val *tv); /** * Set current terminal color. * - * @param color The RGB color. + * @param color The RGB color. * * @return zero on success. */ @@ -1145,7 +1144,7 @@ PJ_DECL(pj_color_t) pj_term_get_color(void); * @} */ -#endif /* PJ_TERM_HAS_COLOR */ +#endif /* PJ_TERM_HAS_COLOR */ /* **************************************************************************/ /** @@ -1176,7 +1175,7 @@ PJ_DECL(pj_color_t) pj_term_get_color(void); /** * Get monotonic time since some unspecified starting point. * - * @param tv Variable to store the result. + * @param tv Variable to store the result. * * @return PJ_SUCCESS if successful. */ @@ -1186,8 +1185,8 @@ PJ_DECL(pj_status_t) pj_gettickcount(pj_time_val *tv); * Acquire high resolution timer value. The time value are stored * in cycles. * - * @param ts High resolution timer value. - * @return PJ_SUCCESS or the appropriate error code. + * @param ts High resolution timer value. + * @return PJ_SUCCESS or the appropriate error code. * * @see pj_get_timestamp_freq(). */ @@ -1196,19 +1195,19 @@ PJ_DECL(pj_status_t) pj_get_timestamp(pj_timestamp *ts); /** * Get high resolution timer frequency, in cycles per second. * - * @param freq Timer frequency, in cycles per second. - * @return PJ_SUCCESS or the appropriate error code. + * @param freq Timer frequency, in cycles per second. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_get_timestamp_freq(pj_timestamp *freq); /** * Set timestamp from 32bit values. - * @param t The timestamp to be set. - * @param hi The high 32bit part. - * @param lo The low 32bit part. + * @param t The timestamp to be set. + * @param hi The high 32bit part. + * @param lo The low 32bit part. */ PJ_INLINE(void) pj_set_timestamp32(pj_timestamp *t, pj_uint32_t hi, - pj_uint32_t lo) + pj_uint32_t lo) { t->u32.hi = hi; t->u32.lo = lo; @@ -1217,36 +1216,36 @@ PJ_INLINE(void) pj_set_timestamp32(pj_timestamp *t, pj_uint32_t hi, /** * Compare timestamp t1 and t2. - * @param t1 t1. - * @param t2 t2. - * @return -1 if (t1 < t2), 1 if (t1 > t2), or 0 if (t1 == t2) + * @param t1 t1. + * @param t2 t2. + * @return -1 if (t1 < t2), 1 if (t1 > t2), or 0 if (t1 == t2) */ PJ_INLINE(int) pj_cmp_timestamp(const pj_timestamp *t1, const pj_timestamp *t2) { #if PJ_HAS_INT64 if (t1->u64 < t2->u64) - return -1; + return -1; else if (t1->u64 > t2->u64) - return 1; + return 1; else - return 0; + return 0; #else if (t1->u32.hi < t2->u32.hi || - (t1->u32.hi == t2->u32.hi && t1->u32.lo < t2->u32.lo)) - return -1; + (t1->u32.hi == t2->u32.hi && t1->u32.lo < t2->u32.lo)) + return -1; else if (t1->u32.hi > t2->u32.hi || - (t1->u32.hi == t2->u32.hi && t1->u32.lo > t2->u32.lo)) - return 1; + (t1->u32.hi == t2->u32.hi && t1->u32.lo > t2->u32.lo)) + return 1; else - return 0; + return 0; #endif } /** * Add timestamp t2 to t1. - * @param t1 t1. - * @param t2 t2. + * @param t1 t1. + * @param t2 t2. */ PJ_INLINE(void) pj_add_timestamp(pj_timestamp *t1, const pj_timestamp *t2) { @@ -1257,14 +1256,14 @@ PJ_INLINE(void) pj_add_timestamp(pj_timestamp *t1, const pj_timestamp *t2) t1->u32.hi += t2->u32.hi; t1->u32.lo += t2->u32.lo; if (t1->u32.lo < old) - ++t1->u32.hi; + ++t1->u32.hi; #endif } /** * Add timestamp t2 to t1. - * @param t1 t1. - * @param t2 t2. + * @param t1 t1. + * @param t2 t2. */ PJ_INLINE(void) pj_add_timestamp32(pj_timestamp *t1, pj_uint32_t t2) { @@ -1274,14 +1273,14 @@ PJ_INLINE(void) pj_add_timestamp32(pj_timestamp *t1, pj_uint32_t t2) pj_uint32_t old = t1->u32.lo; t1->u32.lo += t2; if (t1->u32.lo < old) - ++t1->u32.hi; + ++t1->u32.hi; #endif } /** * Substract timestamp t2 from t1. - * @param t1 t1. - * @param t2 t2. + * @param t1 t1. + * @param t2 t2. */ PJ_INLINE(void) pj_sub_timestamp(pj_timestamp *t1, const pj_timestamp *t2) { @@ -1290,18 +1289,18 @@ PJ_INLINE(void) pj_sub_timestamp(pj_timestamp *t1, const pj_timestamp *t2) #else t1->u32.hi -= t2->u32.hi; if (t1->u32.lo >= t2->u32.lo) - t1->u32.lo -= t2->u32.lo; + t1->u32.lo -= t2->u32.lo; else { - t1->u32.lo -= t2->u32.lo; - --t1->u32.hi; + t1->u32.lo -= t2->u32.lo; + --t1->u32.hi; } #endif } /** * Substract timestamp t2 from t1. - * @param t1 t1. - * @param t2 t2. + * @param t1 t1. + * @param t2 t2. */ PJ_INLINE(void) pj_sub_timestamp32(pj_timestamp *t1, pj_uint32_t t2) { @@ -1309,10 +1308,10 @@ PJ_INLINE(void) pj_sub_timestamp32(pj_timestamp *t1, pj_uint32_t t2) t1->u64 -= t2; #else if (t1->u32.lo >= t2) - t1->u32.lo -= t2; + t1->u32.lo -= t2; else { - t1->u32.lo -= t2; - --t1->u32.hi; + t1->u32.lo -= t2; + --t1->u32.hi; } #endif } @@ -1322,7 +1321,7 @@ PJ_INLINE(void) pj_sub_timestamp32(pj_timestamp *t1, pj_uint32_t t2) * and return a 32bit signed integer difference. */ PJ_INLINE(pj_int32_t) pj_timestamp_diff32(const pj_timestamp *t1, - const pj_timestamp *t2) + const pj_timestamp *t2) { /* Be careful with the signess (I think!) */ #if PJ_HAS_INT64 @@ -1346,7 +1345,7 @@ PJ_INLINE(pj_int32_t) pj_timestamp_diff32(const pj_timestamp *t1, * @param start The starting timestamp. * @param stop The end timestamp. * - * @return Elapsed time as #pj_time_val. + * @return Elapsed time as #pj_time_val. * * @see pj_elapsed_usec(), pj_elapsed_cycle(), pj_elapsed_nanosec() */ @@ -1364,7 +1363,7 @@ PJ_DECL(pj_time_val) pj_elapsed_time( const pj_timestamp *start, * @param start The starting timestamp. * @param stop The end timestamp. * - * @return Elapsed time in milisecond. + * @return Elapsed time in milisecond. * * @see pj_elapsed_time(), pj_elapsed_cycle(), pj_elapsed_nanosec() */ @@ -1388,7 +1387,7 @@ PJ_DECL(pj_uint64_t) pj_elapsed_msec64(const pj_timestamp *start, * @param start The starting timestamp. * @param stop The end timestamp. * - * @return Elapsed time in microsecond. + * @return Elapsed time in microsecond. * * @see pj_elapsed_time(), pj_elapsed_cycle(), pj_elapsed_nanosec() */ @@ -1406,7 +1405,7 @@ PJ_DECL(pj_uint32_t) pj_elapsed_usec( const pj_timestamp *start, * @param start The starting timestamp. * @param stop The end timestamp. * - * @return Elapsed time in nanoseconds. + * @return Elapsed time in nanoseconds. * * @see pj_elapsed_time(), pj_elapsed_cycle(), pj_elapsed_usec() */ @@ -1424,7 +1423,7 @@ PJ_DECL(pj_uint32_t) pj_elapsed_nanosec( const pj_timestamp *start, * @param start The starting timestamp. * @param stop The end timestamp. * - * @return Elapsed time in cycles. + * @return Elapsed time in cycles. * * @see pj_elapsed_usec(), pj_elapsed_time(), pj_elapsed_nanosec() */ @@ -1432,7 +1431,7 @@ PJ_DECL(pj_uint32_t) pj_elapsed_cycle( const pj_timestamp *start, const pj_timestamp *stop ); -#endif /* PJ_HAS_HIGH_RES_TIMER */ +#endif /* PJ_HAS_HIGH_RES_TIMER */ /** @} */ @@ -1455,16 +1454,16 @@ typedef int (*pj_main_func_ptr)(int argc, char *argv[]); * provided, it will call main_func() function. * * @param main_func Application's main function. - * @param argc Number of arguments from the main() function, which - * will be passed to main_func() function. - * @param argv The arguments from the main() function, which will - * be passed to main_func() function. + * @param argc Number of arguments from the main() function, which + * will be passed to main_func() function. + * @param argv The arguments from the main() function, which will + * be passed to main_func() function. * @param flags Flags for application execution, currently must be 0. * * @return main_func()'s return value. */ PJ_DECL(int) pj_run_app(pj_main_func_ptr main_func, int argc, char *argv[], - unsigned flags); + unsigned flags); /** @} */ diff --git a/pjlib/include/pj/pool.h b/pjlib/include/pj/pool.h index 81b1104831..22cb71aaeb 100644 --- a/pjlib/include/pj/pool.h +++ b/pjlib/include/pj/pool.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -177,64 +176,64 @@ PJ_BEGIN_DECL static void my_perror(const char *title, pj_status_t status) { - PJ_PERROR(1,(THIS_FILE, status, title)); + PJ_PERROR(1,(THIS_FILE, status, title)); } static void pool_demo_1(pj_pool_factory *pfactory) { - unsigned i; - pj_pool_t *pool; - - // Must create pool before we can allocate anything - pool = pj_pool_create(pfactory, // the factory - "pool1", // pool's name - 4000, // initial size - 4000, // increment size - NULL); // use default callback. - if (pool == NULL) { - my_perror("Error creating pool", PJ_ENOMEM); - return; - } - - // Demo: allocate some memory chunks - for (i=0; i<1000; ++i) { - void *p; - - p = pj_pool_alloc(pool, (pj_rand()+1) % 512); - - // Do something with p - ... - - // Look! No need to free p!! - } - - // Done with silly demo, must free pool to release all memory. - pj_pool_release(pool); + unsigned i; + pj_pool_t *pool; + + // Must create pool before we can allocate anything + pool = pj_pool_create(pfactory, // the factory + "pool1", // pool's name + 4000, // initial size + 4000, // increment size + NULL); // use default callback. + if (pool == NULL) { + my_perror("Error creating pool", PJ_ENOMEM); + return; + } + + // Demo: allocate some memory chunks + for (i=0; i<1000; ++i) { + void *p; + + p = pj_pool_alloc(pool, (pj_rand()+1) % 512); + + // Do something with p + ... + + // Look! No need to free p!! + } + + // Done with silly demo, must free pool to release all memory. + pj_pool_release(pool); } int main() { - pj_caching_pool cp; - pj_status_t status; + pj_caching_pool cp; + pj_status_t status; // Must init PJLIB before anything else - status = pj_init(); - if (status != PJ_SUCCESS) { - my_perror("Error initializing PJLIB", status); - return 1; - } + status = pj_init(); + if (status != PJ_SUCCESS) { + my_perror("Error initializing PJLIB", status); + return 1; + } - // Create the pool factory, in this case, a caching pool, - // using default pool policy. - pj_caching_pool_init(&cp, NULL, 1024*1024 ); + // Create the pool factory, in this case, a caching pool, + // using default pool policy. + pj_caching_pool_init(&cp, NULL, 1024*1024 ); - // Do a demo - pool_demo_1(&cp.factory); + // Do a demo + pool_demo_1(&cp.factory); - // Done with demos, destroy caching pool before exiting app. - pj_caching_pool_destroy(&cp); + // Done with demos, destroy caching pool before exiting app. + pj_caching_pool_destroy(&cp); - return 0; + return 0; } \endcode @@ -268,9 +267,9 @@ PJ_BEGIN_DECL * - By design, memory allocation from a pool is not thread safe. We assumed * that a pool will be owned by an object, and thread safety should be * handled by that object. Thus these functions are not thread safe: - * - #pj_pool_alloc, - * - #pj_pool_calloc, - * - and other pool statistic functions. + * - #pj_pool_alloc, + * - #pj_pool_calloc, + * - and other pool statistic functions. * - Threading in the pool factory is decided by the policy set for the * factory when it was created. * @@ -312,19 +311,19 @@ struct pj_pool_t PJ_DECL_LIST_MEMBER(struct pj_pool_t); /**< Standard list elements. */ /** Pool name */ - char obj_name[PJ_MAX_OBJ_NAME]; + char obj_name[PJ_MAX_OBJ_NAME]; /** Pool factory. */ pj_pool_factory *factory; /** Data put by factory */ - void *factory_data; + void *factory_data; /** Current capacity allocated by the pool. */ - pj_size_t capacity; + pj_size_t capacity; /** Size of memory block to be allocated when the pool runs out of memory */ - pj_size_t increment_size; + pj_size_t increment_size; /** List of memory blocks allcoated by the pool. */ pj_pool_block block_list; @@ -338,7 +337,7 @@ struct pj_pool_t /** * Guidance on how much memory required for initial pool administrative data. */ -#define PJ_POOL_SIZE (sizeof(struct pj_pool_t)) +#define PJ_POOL_SIZE (sizeof(struct pj_pool_t)) /** * Pool memory alignment (must be power of 2). @@ -351,39 +350,39 @@ struct pj_pool_t * Create a new pool from the pool factory. This wrapper will call create_pool * member of the pool factory. * - * @param factory The pool factory. - * @param name The name to be assigned to the pool. The name should - * not be longer than PJ_MAX_OBJ_NAME (32 chars), or - * otherwise it will be truncated. - * @param initial_size The size of initial memory blocks taken by the pool. - * Note that the pool will take 68+20 bytes for - * administrative area from this block. + * @param factory The pool factory. + * @param name The name to be assigned to the pool. The name should + * not be longer than PJ_MAX_OBJ_NAME (32 chars), or + * otherwise it will be truncated. + * @param initial_size The size of initial memory blocks taken by the pool. + * Note that the pool will take 68+20 bytes for + * administrative area from this block. * @param increment_size the size of each additional blocks to be allocated - * when the pool is running out of memory. If user - * requests memory which is larger than this size, then - * an error occurs. - * Note that each time a pool allocates additional block, - * it needs PJ_POOL_SIZE more to store some - * administrative info. - * @param callback Callback to be called when error occurs in the pool. - * If this value is NULL, then the callback from pool - * factory policy will be used. - * Note that when an error occurs during pool creation, - * the callback itself is not called. Instead, NULL - * will be returned. + * when the pool is running out of memory. If user + * requests memory which is larger than this size, then + * an error occurs. + * Note that each time a pool allocates additional block, + * it needs PJ_POOL_SIZE more to store some + * administrative info. + * @param callback Callback to be called when error occurs in the pool. + * If this value is NULL, then the callback from pool + * factory policy will be used. + * Note that when an error occurs during pool creation, + * the callback itself is not called. Instead, NULL + * will be returned. * * @return The memory pool, or NULL. */ PJ_IDECL(pj_pool_t*) pj_pool_create(pj_pool_factory *factory, - const char *name, - pj_size_t initial_size, - pj_size_t increment_size, - pj_pool_callback *callback); + const char *name, + pj_size_t initial_size, + pj_size_t increment_size, + pj_pool_callback *callback); /** * Release the pool back to pool factory. * - * @param pool Memory pool. + * @param pool Memory pool. */ PJ_IDECL(void) pj_pool_release( pj_pool_t *pool ); @@ -391,7 +390,7 @@ PJ_IDECL(void) pj_pool_release( pj_pool_t *pool ); /** * Release the pool back to pool factory and set the pool pointer to zero. * - * @param ppool Pointer to memory pool. + * @param ppool Pointer to memory pool. */ PJ_IDECL(void) pj_pool_safe_release( pj_pool_t **ppool ); @@ -400,7 +399,7 @@ PJ_IDECL(void) pj_pool_safe_release( pj_pool_t **ppool ); * Release the pool back to pool factory and set the pool pointer to zero. * The memory pool content will be wiped out first before released. * - * @param ppool Pointer to memory pool. + * @param ppool Pointer to memory pool. */ PJ_IDECL(void) pj_pool_secure_release( pj_pool_t **ppool ); @@ -432,7 +431,7 @@ PJ_DECL(void) pj_pool_reset( pj_pool_t *pool ); * There's no guarantee that the returned value represent a single * contiguous block, because the capacity may be spread in several blocks. * - * @param pool the pool. + * @param pool the pool. * * @return the capacity. */ @@ -441,7 +440,7 @@ PJ_IDECL(pj_size_t) pj_pool_get_capacity( pj_pool_t *pool ); /** * Get the total size of user allocation request. * - * @param pool the pool. + * @param pool the pool. * * @return the total size. */ @@ -452,8 +451,8 @@ PJ_IDECL(pj_size_t) pj_pool_get_used_size( pj_pool_t *pool ); * If there's no storage available in the pool, then the pool can allocate more * blocks if the increment size is larger than the requested size. * - * @param pool the pool. - * @param size the requested size. + * @param pool the pool. + * @param size the requested size. * * @return pointer to the allocated memory. * @@ -466,23 +465,23 @@ PJ_IDECL(void*) pj_pool_alloc( pj_pool_t *pool, pj_size_t size); * This function behaves like pj_pool_alloc(), except that the storage will * be initialized to zero. * - * @param pool the pool. - * @param count the number of elements in the array. - * @param elem the size of individual element. + * @param pool the pool. + * @param count the number of elements in the array. + * @param elem the size of individual element. * * @return pointer to the allocated memory. */ PJ_IDECL(void*) pj_pool_calloc( pj_pool_t *pool, pj_size_t count, - pj_size_t elem); + pj_size_t elem); /** * Allocate storage from the pool and initialize it to zero. * - * @param pool The pool. - * @param size The size to be allocated. + * @param pool The pool. + * @param size The size to be allocated. * - * @return Pointer to the allocated memory. + * @return Pointer to the allocated memory. * * @see PJ_POOL_ZALLOC_T */ @@ -498,13 +497,13 @@ PJ_INLINE(void*) pj_pool_zalloc(pj_pool_t *pool, pj_size_t size) * since the return value of this macro will be type-casted to the specified * type. * - * @param pool The pool - * @param type The type of object to be allocated + * @param pool The pool + * @param type The type of object to be allocated * - * @return Memory buffer of the specified type. + * @return Memory buffer of the specified type. */ #define PJ_POOL_ALLOC_T(pool,type) \ - ((type*)pj_pool_alloc(pool, sizeof(type))) + ((type*)pj_pool_alloc(pool, sizeof(type))) /** * This macro allocates memory from the pool, zeroes the buffer, and @@ -512,13 +511,13 @@ PJ_INLINE(void*) pj_pool_zalloc(pj_pool_t *pool, pj_size_t size) * safety than pj_pool_zalloc() since the return value of this macro will be * type-casted to the specified type. * - * @param pool The pool - * @param type The type of object to be allocated + * @param pool The pool + * @param type The type of object to be allocated * - * @return Memory buffer of the specified type. + * @return Memory buffer of the specified type. */ #define PJ_POOL_ZALLOC_T(pool,type) \ - ((type*)pj_pool_zalloc(pool, sizeof(type))) + ((type*)pj_pool_zalloc(pool, sizeof(type))) /* * Internal functions @@ -529,9 +528,9 @@ PJ_IDECL(void*) pj_pool_alloc_from_block(pj_pool_block *block, pj_size_t size); PJ_DECL(void*) pj_pool_allocate_find(pj_pool_t *pool, pj_size_t size); - + /** - * @} // PJ_POOL + * @} // PJ_POOL */ /* **************************************************************************/ @@ -600,19 +599,19 @@ typedef struct pj_pool_factory_policy * Allocate memory block (for use by pool). This function is called * by memory pool to allocate memory block. * - * @param factory Pool factory. - * @param size The size of memory block to allocate. + * @param factory Pool factory. + * @param size The size of memory block to allocate. * - * @return Memory block. + * @return Memory block. */ void* (*block_alloc)(pj_pool_factory *factory, pj_size_t size); /** * Free memory block. * - * @param factory Pool factory. - * @param mem Memory block previously allocated by block_alloc(). - * @param size The size of memory block. + * @param factory Pool factory. + * @param mem Memory block previously allocated by block_alloc(). + * @param size The size of memory block. */ void (*block_free)(pj_pool_factory *factory, void *mem, pj_size_t size); @@ -674,45 +673,45 @@ struct pj_pool_factory /** * Create a new pool from the pool factory. * - * @param factory The pool factory. - * @param name the name to be assigned to the pool. The name should - * not be longer than PJ_MAX_OBJ_NAME (32 chars), or - * otherwise it will be truncated. + * @param factory The pool factory. + * @param name the name to be assigned to the pool. The name should + * not be longer than PJ_MAX_OBJ_NAME (32 chars), or + * otherwise it will be truncated. * @param initial_size the size of initial memory blocks taken by the pool. - * Note that the pool will take 68+20 bytes for - * administrative area from this block. + * Note that the pool will take 68+20 bytes for + * administrative area from this block. * @param increment_size the size of each additional blocks to be allocated - * when the pool is running out of memory. If user - * requests memory which is larger than this size, then - * an error occurs. - * Note that each time a pool allocates additional block, - * it needs 20 bytes (equal to sizeof(pj_pool_block)) to - * store some administrative info. - * @param callback Cllback to be called when error occurs in the pool. - * Note that when an error occurs during pool creation, - * the callback itself is not called. Instead, NULL - * will be returned. + * when the pool is running out of memory. If user + * requests memory which is larger than this size, then + * an error occurs. + * Note that each time a pool allocates additional block, + * it needs 20 bytes (equal to sizeof(pj_pool_block)) to + * store some administrative info. + * @param callback Cllback to be called when error occurs in the pool. + * Note that when an error occurs during pool creation, + * the callback itself is not called. Instead, NULL + * will be returned. * * @return the memory pool, or NULL. */ - pj_pool_t* (*create_pool)( pj_pool_factory *factory, - const char *name, - pj_size_t initial_size, - pj_size_t increment_size, - pj_pool_callback *callback); + pj_pool_t* (*create_pool)( pj_pool_factory *factory, + const char *name, + pj_size_t initial_size, + pj_size_t increment_size, + pj_pool_callback *callback); /** * Release the pool to the pool factory. * - * @param factory The pool factory. - * @param pool The pool to be released. + * @param factory The pool factory. + * @param pool The pool to be released. */ void (*release_pool)( pj_pool_factory *factory, pj_pool_t *pool ); /** * Dump pool status to log. * - * @param factory The pool factory. + * @param factory The pool factory. */ void (*dump_status)( pj_pool_factory *factory, pj_bool_t detail ); @@ -722,10 +721,10 @@ struct pj_pool_factory * for example to keep track of the total number of memory blocks * currently allocated by applications. * - * @param factory The pool factory. - * @param size Size requested by application. + * @param factory The pool factory. + * @param size Size requested by application. * - * @return MUST return PJ_TRUE, otherwise the block + * @return MUST return PJ_TRUE, otherwise the block * allocation is cancelled. */ pj_bool_t (*on_block_alloc)(pj_pool_factory *factory, pj_size_t size); @@ -736,8 +735,8 @@ struct pj_pool_factory * for example to keep track of the total number of memory blocks * currently allocated by applications. * - * @param factory The pool factory. - * @param size Size freed. + * @param factory The pool factory. + * @param size Size freed. */ void (*on_block_free)(pj_pool_factory *factory, pj_size_t size); @@ -752,11 +751,11 @@ struct pj_pool_factory * @param callback Callback. * @return The pool object, or NULL. */ -PJ_DECL(pj_pool_t*) pj_pool_create_int( pj_pool_factory *factory, - const char *name, - pj_size_t initial_size, - pj_size_t increment_size, - pj_pool_callback *callback); +PJ_DECL(pj_pool_t*) pj_pool_create_int( pj_pool_factory *factory, + const char *name, + pj_size_t initial_size, + pj_size_t increment_size, + pj_pool_callback *callback); /** * This function is intended to be used by pool factory implementors. @@ -766,9 +765,9 @@ PJ_DECL(pj_pool_t*) pj_pool_create_int( pj_pool_factory *factory, * @param callback Callback function. */ PJ_DECL(void) pj_pool_init_int( pj_pool_t *pool, - const char *name, - pj_size_t increment_size, - pj_pool_callback *callback); + const char *name, + pj_size_t increment_size, + pj_pool_callback *callback); /** * This function is intended to be used by pool factory implementors. @@ -779,17 +778,17 @@ PJ_DECL(void) pj_pool_destroy_int( pj_pool_t *pool ); /** * Dump pool factory state. - * @param pf The pool factory. + * @param pf The pool factory. * @param detail Detail state required. */ PJ_INLINE(void) pj_pool_factory_dump( pj_pool_factory *pf, - pj_bool_t detail ) + pj_bool_t detail ) { (*pf->dump_status)(pf, detail); } /** - * @} // PJ_POOL_FACTORY + * @} // PJ_POOL_FACTORY */ /* **************************************************************************/ @@ -813,7 +812,7 @@ PJ_INLINE(void) pj_pool_factory_dump( pj_pool_factory *pf, * Number of unique sizes, to be used as index to the free list. * Each pool in the free list is organized by it's size. */ -#define PJ_CACHING_POOL_ARRAY_SIZE 16 +#define PJ_CACHING_POOL_ARRAY_SIZE 16 /** * Declaration for caching pool. Application doesn't normally need to @@ -832,7 +831,7 @@ struct pj_caching_pool * in it's free list, which will be returned to application when it * requests to create a new pool. */ - pj_size_t capacity; + pj_size_t capacity; /** Maximum size that can be held by this factory. Once the capacity * has exceeded @a max_capacity, further #pj_pool_release() will @@ -851,33 +850,33 @@ struct pj_caching_pool /** * Total size of memory currently used by application. */ - pj_size_t used_size; + pj_size_t used_size; /** * The maximum size of memory used by application throughout the life * of the caching pool. */ - pj_size_t peak_used_size; + pj_size_t peak_used_size; /** * Lists of pools in the cache, indexed by pool size. */ - pj_list free_list[PJ_CACHING_POOL_ARRAY_SIZE]; + pj_list free_list[PJ_CACHING_POOL_ARRAY_SIZE]; /** * List of pools currently allocated by applications. */ - pj_list used_list; + pj_list used_list; /** * Internal pool. */ - char pool_buf[256 * (sizeof(size_t) / 4)]; + char pool_buf[256 * (sizeof(size_t) / 4)]; /** * Mutex. */ - pj_lock_t *lock; + pj_lock_t *lock; }; @@ -885,28 +884,28 @@ struct pj_caching_pool /** * Initialize caching pool. * - * @param ch_pool The caching pool factory to be initialized. - * @param policy Pool factory policy. - * @param max_capacity The total capacity to be retained in the cache. When - * the pool is returned to the cache, it will be kept in - * recycling list if the total capacity of pools in this - * list plus the capacity of the pool is still below this - * value. + * @param ch_pool The caching pool factory to be initialized. + * @param policy Pool factory policy. + * @param max_capacity The total capacity to be retained in the cache. When + * the pool is returned to the cache, it will be kept in + * recycling list if the total capacity of pools in this + * list plus the capacity of the pool is still below this + * value. */ PJ_DECL(void) pj_caching_pool_init( pj_caching_pool *ch_pool, - const pj_pool_factory_policy *policy, - pj_size_t max_capacity); + const pj_pool_factory_policy *policy, + pj_size_t max_capacity); /** * Destroy caching pool, and release all the pools in the recycling list. * - * @param ch_pool The caching pool. + * @param ch_pool The caching pool. */ PJ_DECL(void) pj_caching_pool_destroy( pj_caching_pool *ch_pool ); /** - * @} // PJ_CACHING_POOL + * @} // PJ_CACHING_POOL */ # if PJ_FUNCTIONS_ARE_INLINED @@ -915,5 +914,5 @@ PJ_DECL(void) pj_caching_pool_destroy( pj_caching_pool *ch_pool ); PJ_END_DECL -#endif /* __PJ_POOL_H__ */ +#endif /* __PJ_POOL_H__ */ diff --git a/pjlib/include/pj/pool_alt.h b/pjlib/include/pj/pool_alt.h index 547ea840fd..037e392d12 100644 --- a/pjlib/include/pj/pool_alt.h +++ b/pjlib/include/pj/pool_alt.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,13 +43,13 @@ struct pj_pool_t { struct pj_pool_mem *first_mem; pj_pool_factory *factory; - char obj_name[32]; - pj_size_t used_size; + char obj_name[32]; + pj_size_t used_size; pj_pool_callback *cb; }; -#define PJ_POOL_SIZE (sizeof(struct pj_pool_t)) +#define PJ_POOL_SIZE (sizeof(struct pj_pool_t)) /** * This constant denotes the exception number that will be thrown by default @@ -69,23 +68,23 @@ PJ_DECL(int) pj_NO_MEMORY_EXCEPTION(void); * function. */ #define pj_pool_create(fc,nm,init,inc,cb) \ - pj_pool_create_imp(__FILE__, __LINE__, fc, nm, init, inc, cb) + pj_pool_create_imp(__FILE__, __LINE__, fc, nm, init, inc, cb) -#define pj_pool_release(pool) pj_pool_release_imp(pool) -#define pj_pool_safe_release(pool) pj_pool_safe_release_imp(pool) -#define pj_pool_secure_release(pool) pj_pool_secure_release_imp(pool) -#define pj_pool_getobjname(pool) pj_pool_getobjname_imp(pool) -#define pj_pool_reset(pool) pj_pool_reset_imp(pool) -#define pj_pool_get_capacity(pool) pj_pool_get_capacity_imp(pool) -#define pj_pool_get_used_size(pool) pj_pool_get_used_size_imp(pool) -#define pj_pool_alloc(pool,sz) \ - pj_pool_alloc_imp(__FILE__, __LINE__, pool, sz) +#define pj_pool_release(pool) pj_pool_release_imp(pool) +#define pj_pool_safe_release(pool) pj_pool_safe_release_imp(pool) +#define pj_pool_secure_release(pool) pj_pool_secure_release_imp(pool) +#define pj_pool_getobjname(pool) pj_pool_getobjname_imp(pool) +#define pj_pool_reset(pool) pj_pool_reset_imp(pool) +#define pj_pool_get_capacity(pool) pj_pool_get_capacity_imp(pool) +#define pj_pool_get_used_size(pool) pj_pool_get_used_size_imp(pool) +#define pj_pool_alloc(pool,sz) \ + pj_pool_alloc_imp(__FILE__, __LINE__, pool, sz) -#define pj_pool_calloc(pool,cnt,elem) \ - pj_pool_calloc_imp(__FILE__, __LINE__, pool, cnt, elem) +#define pj_pool_calloc(pool,cnt,elem) \ + pj_pool_calloc_imp(__FILE__, __LINE__, pool, cnt, elem) -#define pj_pool_zalloc(pool,sz) \ - pj_pool_zalloc_imp(__FILE__, __LINE__, pool, sz) +#define pj_pool_zalloc(pool,sz) \ + pj_pool_zalloc_imp(__FILE__, __LINE__, pool, sz) @@ -95,11 +94,11 @@ PJ_DECL(int) pj_NO_MEMORY_EXCEPTION(void); /* Create pool */ PJ_DECL(pj_pool_t*) pj_pool_create_imp(const char *file, int line, - void *factory, - const char *name, - pj_size_t initial_size, - pj_size_t increment_size, - pj_pool_callback *callback); + void *factory, + const char *name, + pj_size_t initial_size, + pj_size_t increment_size, + pj_pool_callback *callback); /* Release pool */ PJ_DECL(void) pj_pool_release_imp(pj_pool_t *pool); @@ -124,22 +123,22 @@ PJ_DECL(pj_size_t) pj_pool_get_used_size_imp(pj_pool_t *pool); /* Allocate memory from the pool */ PJ_DECL(void*) pj_pool_alloc_imp(const char *file, int line, - pj_pool_t *pool, pj_size_t sz); + pj_pool_t *pool, pj_size_t sz); /* Allocate memory from the pool and zero the memory */ PJ_DECL(void*) pj_pool_calloc_imp(const char *file, int line, - pj_pool_t *pool, unsigned cnt, - unsigned elemsz); + pj_pool_t *pool, unsigned cnt, + unsigned elemsz); /* Allocate memory from the pool and zero the memory */ PJ_DECL(void*) pj_pool_zalloc_imp(const char *file, int line, - pj_pool_t *pool, pj_size_t sz); + pj_pool_t *pool, pj_size_t sz); #define PJ_POOL_ZALLOC_T(pool,type) \ - ((type*)pj_pool_zalloc(pool, sizeof(type))) + ((type*)pj_pool_zalloc(pool, sizeof(type))) #define PJ_POOL_ALLOC_T(pool,type) \ - ((type*)pj_pool_alloc(pool, sizeof(type))) + ((type*)pj_pool_alloc(pool, sizeof(type))) #ifndef PJ_POOL_ALIGNMENT # define PJ_POOL_ALIGNMENT 4 #endif @@ -153,19 +152,19 @@ typedef struct pj_pool_factory_policy * Allocate memory block (for use by pool). This function is called * by memory pool to allocate memory block. * - * @param factory Pool factory. - * @param size The size of memory block to allocate. + * @param factory Pool factory. + * @param size The size of memory block to allocate. * - * @return Memory block. + * @return Memory block. */ void* (*block_alloc)(pj_pool_factory *factory, pj_size_t size); /** * Free memory block. * - * @param factory Pool factory. - * @param mem Memory block previously allocated by block_alloc(). - * @param size The size of memory block. + * @param factory Pool factory. + * @param mem Memory block previously allocated by block_alloc(). + * @param size The size of memory block. */ void (*block_free)(pj_pool_factory *factory, void *mem, pj_size_t size); @@ -209,5 +208,5 @@ typedef struct pj_pool_block PJ_END_DECL -#endif /* __PJ_POOL_ALT_H__ */ +#endif /* __PJ_POOL_ALT_H__ */ diff --git a/pjlib/include/pj/pool_buf.h b/pjlib/include/pj/pool_buf.h index b7cf180eb7..734790dbb9 100644 --- a/pjlib/include/pj/pool_buf.h +++ b/pjlib/include/pj/pool_buf.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -85,15 +84,15 @@ PJ_BEGIN_DECL * pool (such as mutexes) have been destroyed before the pool gets * invalidated. * - * @param name Optional pool name. - * @param buf Buffer to be used by the pool. - * @param size The size of the buffer. + * @param name Optional pool name. + * @param buf Buffer to be used by the pool. + * @param size The size of the buffer. * - * @return The memory pool instance. + * @return The memory pool instance. */ PJ_DECL(pj_pool_t*) pj_pool_create_on_buf(const char *name, - void *buf, - pj_size_t size); + void *buf, + pj_size_t size); PJ_END_DECL @@ -101,5 +100,5 @@ PJ_END_DECL * @} */ -#endif /* __POOL_STACK_H__ */ +#endif /* __POOL_STACK_H__ */ diff --git a/pjlib/include/pj/pool_i.h b/pjlib/include/pj/pool_i.h index 60edb7dd37..d19835f717 100644 --- a/pjlib/include/pj/pool_i.h +++ b/pjlib/include/pj/pool_i.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,8 +31,8 @@ PJ_IDEF(pj_size_t) pj_pool_get_used_size( pj_pool_t *pool ) pj_pool_block *b = pool->block_list.next; pj_size_t used_size = sizeof(pj_pool_t); while (b != &pool->block_list) { - used_size += (b->cur - b->buf) + sizeof(pj_pool_block); - b = b->next; + used_size += (b->cur - b->buf) + sizeof(pj_pool_block); + b = b->next; } return used_size; } @@ -45,12 +44,12 @@ PJ_IDEF(void*) pj_pool_alloc_from_block( pj_pool_block *block, pj_size_t size ) * memory address, but no memory will be allocated. */ if (size & (PJ_POOL_ALIGNMENT-1)) { - size = (size + PJ_POOL_ALIGNMENT) & ~(PJ_POOL_ALIGNMENT-1); + size = (size + PJ_POOL_ALIGNMENT) & ~(PJ_POOL_ALIGNMENT-1); } if ((pj_size_t)(block->end - block->cur) >= size) { - void *ptr = block->cur; - block->cur += size; - return ptr; + void *ptr = block->cur; + block->cur += size; + return ptr; } return NULL; } @@ -59,7 +58,7 @@ PJ_IDEF(void*) pj_pool_alloc( pj_pool_t *pool, pj_size_t size) { void *ptr = pj_pool_alloc_from_block(pool->block_list.next, size); if (!ptr) - ptr = pj_pool_allocate_find(pool, size); + ptr = pj_pool_allocate_find(pool, size); return ptr; } @@ -68,7 +67,7 @@ PJ_IDEF(void*) pj_pool_calloc( pj_pool_t *pool, pj_size_t count, pj_size_t size) { void *buf = pj_pool_alloc( pool, size*count); if (buf) - pj_bzero(buf, size * count); + pj_bzero(buf, size * count); return buf; } @@ -78,10 +77,10 @@ PJ_IDEF(const char *) pj_pool_getobjname( const pj_pool_t *pool ) } PJ_IDEF(pj_pool_t*) pj_pool_create( pj_pool_factory *f, - const char *name, - pj_size_t initial_size, - pj_size_t increment_size, - pj_pool_callback *callback) + const char *name, + pj_size_t initial_size, + pj_size_t increment_size, + pj_pool_callback *callback) { return (*f->create_pool)(f, name, initial_size, increment_size, callback); } @@ -93,14 +92,14 @@ PJ_IDEF(void) pj_pool_release( pj_pool_t *pool ) b = pool->block_list.next; while (b != &pool->block_list) { - volatile unsigned char *p = b->buf; - while (p < b->end) *p++ = 0; - b = b->next; + volatile unsigned char *p = b->buf; + while (p < b->end) *p++ = 0; + b = b->next; } #endif if (pool->factory->release_pool) - (*pool->factory->release_pool)(pool->factory, pool); + (*pool->factory->release_pool)(pool->factory, pool); } @@ -109,7 +108,7 @@ PJ_IDEF(void) pj_pool_safe_release( pj_pool_t **ppool ) pj_pool_t *pool = *ppool; *ppool = NULL; if (pool) - pj_pool_release(pool); + pj_pool_release(pool); } PJ_IDEF(void) pj_pool_secure_release( pj_pool_t **ppool ) @@ -119,13 +118,13 @@ PJ_IDEF(void) pj_pool_secure_release( pj_pool_t **ppool ) *ppool = NULL; if (!pool) - return; + return; b = pool->block_list.next; while (b != &pool->block_list) { - volatile unsigned char *p = b->buf; - while (p < b->end) *p++ = 0; - b = b->next; + volatile unsigned char *p = b->buf; + while (p < b->end) *p++ = 0; + b = b->next; } pj_pool_release(pool); diff --git a/pjlib/include/pj/rand.h b/pjlib/include/pj/rand.h index 1a69183f10..5016ac7dca 100644 --- a/pjlib/include/pj/rand.h +++ b/pjlib/include/pj/rand.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -43,7 +42,7 @@ PJ_BEGIN_DECL /** * Put in seed to random number generator. * - * @param seed Seed value. + * @param seed Seed value. */ PJ_DECL(void) pj_srand(unsigned int seed); @@ -62,5 +61,5 @@ PJ_DECL(int) pj_rand(void); PJ_END_DECL -#endif /* __PJ_RAND_H__ */ +#endif /* __PJ_RAND_H__ */ diff --git a/pjlib/include/pj/rbtree.h b/pjlib/include/pj/rbtree.h index fee00bf4dd..5da0a43e49 100644 --- a/pjlib/include/pj/rbtree.h +++ b/pjlib/include/pj/rbtree.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -103,13 +102,13 @@ typedef struct pj_rbtree /** * Guidance on how much memory required for each of the node. */ -#define PJ_RBTREE_NODE_SIZE (sizeof(pj_rbtree_node)) +#define PJ_RBTREE_NODE_SIZE (sizeof(pj_rbtree_node)) /** * Guidance on memory required for the tree. */ -#define PJ_RBTREE_SIZE (sizeof(pj_rbtree)) +#define PJ_RBTREE_SIZE (sizeof(pj_rbtree)) /** @@ -145,7 +144,7 @@ PJ_DECL(pj_rbtree_node*) pj_rbtree_last( pj_rbtree *tree ); * @return the successive node, or NULL if the node has no successor. */ PJ_DECL(pj_rbtree_node*) pj_rbtree_next( pj_rbtree *tree, - pj_rbtree_node *node ); + pj_rbtree_node *node ); /** * The the previous node for the specified node. @@ -155,7 +154,7 @@ PJ_DECL(pj_rbtree_node*) pj_rbtree_next( pj_rbtree *tree, * @return the previous node, or NULL if the node has no previous node. */ PJ_DECL(pj_rbtree_node*) pj_rbtree_prev( pj_rbtree *tree, - pj_rbtree_node *node ); + pj_rbtree_node *node ); /** * Insert a new node. @@ -166,7 +165,7 @@ PJ_DECL(pj_rbtree_node*) pj_rbtree_prev( pj_rbtree *tree, * @return zero on success, or -1 if the key already exist. */ PJ_DECL(int) pj_rbtree_insert( pj_rbtree *tree, - pj_rbtree_node *node ); + pj_rbtree_node *node ); /** * Find a node which has the specified key. @@ -176,7 +175,7 @@ PJ_DECL(int) pj_rbtree_insert( pj_rbtree *tree, * be found. */ PJ_DECL(pj_rbtree_node*) pj_rbtree_find( pj_rbtree *tree, - const void *key ); + const void *key ); /** * Erase a node from the tree. @@ -185,7 +184,7 @@ PJ_DECL(pj_rbtree_node*) pj_rbtree_find( pj_rbtree *tree, * @return the tree node itself. */ PJ_DECL(pj_rbtree_node*) pj_rbtree_erase( pj_rbtree *tree, - pj_rbtree_node *node ); + pj_rbtree_node *node ); /** * Get the maximum tree height from the specified node. @@ -194,7 +193,7 @@ PJ_DECL(pj_rbtree_node*) pj_rbtree_erase( pj_rbtree *tree, * @return the maximum height, which should be at most lg(N) */ PJ_DECL(unsigned) pj_rbtree_max_height( pj_rbtree *tree, - pj_rbtree_node *node ); + pj_rbtree_node *node ); /** * Get the minumum tree height from the specified node. @@ -203,7 +202,7 @@ PJ_DECL(unsigned) pj_rbtree_max_height( pj_rbtree *tree, * @return the height */ PJ_DECL(unsigned) pj_rbtree_min_height( pj_rbtree *tree, - pj_rbtree_node *node ); + pj_rbtree_node *node ); /** @@ -212,5 +211,5 @@ PJ_DECL(unsigned) pj_rbtree_min_height( pj_rbtree *tree, PJ_END_DECL -#endif /* __PJ_RBTREE_H__ */ +#endif /* __PJ_RBTREE_H__ */ diff --git a/pjlib/include/pj/sock.h b/pjlib/include/pj/sock.h index e4bb207fe5..bb9774f5dd 100644 --- a/pjlib/include/pj/sock.h +++ b/pjlib/include/pj/sock.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -65,11 +64,11 @@ PJ_BEGIN_DECL /** Address family is unspecified. @see pj_AF_UNSPEC() */ extern const pj_uint16_t PJ_AF_UNSPEC; -/** Unix domain socket. @see pj_AF_UNIX() */ +/** Unix domain socket. @see pj_AF_UNIX() */ extern const pj_uint16_t PJ_AF_UNIX; -/** POSIX name for AF_UNIX */ -#define PJ_AF_LOCAL PJ_AF_UNIX; +/** POSIX name for AF_UNIX */ +#define PJ_AF_LOCAL PJ_AF_UNIX; /** Internet IP protocol. @see pj_AF_INET() */ extern const pj_uint16_t PJ_AF_INET; @@ -109,15 +108,15 @@ extern const pj_uint16_t PJ_AF_IRDA; /** Get #PJ_AF_UNSPEC value */ # define pj_AF_UNSPEC() PJ_AF_UNSPEC /** Get #PJ_AF_UNIX value. */ -# define pj_AF_UNIX() PJ_AF_UNIX +# define pj_AF_UNIX() PJ_AF_UNIX /** Get #PJ_AF_INET value. */ -# define pj_AF_INET() PJ_AF_INET +# define pj_AF_INET() PJ_AF_INET /** Get #PJ_AF_INET6 value. */ # define pj_AF_INET6() PJ_AF_INET6 /** Get #PJ_AF_PACKET value. */ # define pj_AF_PACKET() PJ_AF_PACKET /** Get #PJ_AF_IRDA value. */ -# define pj_AF_IRDA() PJ_AF_IRDA +# define pj_AF_IRDA() PJ_AF_IRDA #endif @@ -204,11 +203,11 @@ extern const pj_uint16_t PJ_SOL_IPV6; /** Get #PJ_SOL_SOCKET constant */ # define pj_SOL_SOCKET() PJ_SOL_SOCKET /** Get #PJ_SOL_IP constant */ -# define pj_SOL_IP() PJ_SOL_IP +# define pj_SOL_IP() PJ_SOL_IP /** Get #PJ_SOL_TCP constant */ -# define pj_SOL_TCP() PJ_SOL_TCP +# define pj_SOL_TCP() PJ_SOL_TCP /** Get #PJ_SOL_UDP constant */ -# define pj_SOL_UDP() PJ_SOL_UDP +# define pj_SOL_UDP() PJ_SOL_UDP /** Get #PJ_SOL_IPV6 constant */ # define pj_SOL_IPV6() PJ_SOL_IPV6 #endif @@ -261,10 +260,10 @@ extern const pj_uint16_t PJ_IPTOS_MINCOST; PJ_DECL(int) pj_IPTOS_MINCOST(void); #else /** Get #PJ_IP_TOS constant */ -# define pj_IP_TOS() PJ_IP_TOS +# define pj_IP_TOS() PJ_IP_TOS /** Get #PJ_IPTOS_LOWDELAY constant */ -# define pj_IPTOS_LOWDELAY() PJ_IP_TOS_LOWDELAY +# define pj_IPTOS_LOWDELAY() PJ_IP_TOS_LOWDELAY /** Get #PJ_IPTOS_THROUGHPUT constant */ # define pj_IPTOS_THROUGHPUT() PJ_IP_TOS_THROUGHPUT @@ -273,7 +272,7 @@ extern const pj_uint16_t PJ_IPTOS_MINCOST; # define pj_IPTOS_RELIABILITY() PJ_IP_TOS_RELIABILITY /** Get #PJ_IPTOS_MINCOST constant */ -# define pj_IPTOS_MINCOST() PJ_IP_TOS_MINCOST +# define pj_IPTOS_MINCOST() PJ_IP_TOS_MINCOST #endif @@ -286,7 +285,7 @@ extern const pj_uint16_t PJ_IPV6_TCLASS; PJ_DECL(int) pj_IPV6_TCLASS(void); #else /** Get #PJ_IPV6_TCLASS constant */ -# define pj_IPV6_TCLASS() PJ_IPV6_TCLASS +# define pj_IPV6_TCLASS() PJ_IPV6_TCLASS #endif @@ -372,7 +371,7 @@ extern const pj_uint16_t PJ_IP_DROP_MEMBERSHIP; PJ_DECL(pj_uint16_t) pj_IP_DROP_MEMBERSHIP(void); #else /** Get #PJ_SO_TYPE constant */ -# define pj_SO_TYPE() PJ_SO_TYPE +# define pj_SO_TYPE() PJ_SO_TYPE /** Get #PJ_SO_RCVBUF constant */ # define pj_SO_RCVBUF() PJ_SO_RCVBUF @@ -434,13 +433,13 @@ extern const int PJ_MSG_DONTROUTE; PJ_DECL(int) pj_MSG_DONTROUTE(void); #else /** Get #PJ_MSG_OOB constant */ -# define pj_MSG_OOB() PJ_MSG_OOB +# define pj_MSG_OOB() PJ_MSG_OOB /** Get #PJ_MSG_PEEK constant */ -# define pj_MSG_PEEK() PJ_MSG_PEEK +# define pj_MSG_PEEK() PJ_MSG_PEEK /** Get #PJ_MSG_DONTROUTE constant */ -# define pj_MSG_DONTROUTE() PJ_MSG_DONTROUTE +# define pj_MSG_DONTROUTE() PJ_MSG_DONTROUTE #endif @@ -449,21 +448,21 @@ extern const int PJ_MSG_DONTROUTE; */ typedef enum pj_socket_sd_type { - PJ_SD_RECEIVE = 0, /**< No more receive. */ - PJ_SHUT_RD = 0, /**< Alias for SD_RECEIVE. */ - PJ_SD_SEND = 1, /**< No more sending. */ - PJ_SHUT_WR = 1, /**< Alias for SD_SEND. */ - PJ_SD_BOTH = 2, /**< No more send and receive. */ - PJ_SHUT_RDWR = 2 /**< Alias for SD_BOTH. */ + PJ_SD_RECEIVE = 0, /**< No more receive. */ + PJ_SHUT_RD = 0, /**< Alias for SD_RECEIVE. */ + PJ_SD_SEND = 1, /**< No more sending. */ + PJ_SHUT_WR = 1, /**< Alias for SD_SEND. */ + PJ_SD_BOTH = 2, /**< No more send and receive. */ + PJ_SHUT_RDWR = 2 /**< Alias for SD_BOTH. */ } pj_socket_sd_type; /** Address to accept any incoming messages. */ -#define PJ_INADDR_ANY ((pj_uint32_t)0) +#define PJ_INADDR_ANY ((pj_uint32_t)0) /** Address indicating an error return */ -#define PJ_INADDR_NONE ((pj_uint32_t)0xffffffff) +#define PJ_INADDR_NONE ((pj_uint32_t)0xffffffff) /** Address to send to all hosts. */ #define PJ_INADDR_BROADCAST ((pj_uint32_t)0xffffffff) @@ -475,7 +474,7 @@ typedef enum pj_socket_sd_type * denominator (five, in Win32 systems) will be used. */ #if !defined(PJ_SOMAXCONN) -# define PJ_SOMAXCONN 5 +# define PJ_SOMAXCONN 5 #endif @@ -495,7 +494,7 @@ typedef enum pj_socket_sd_type typedef struct pj_in_addr { - pj_uint32_t s_addr; /**< The 32bit IP address. */ + pj_uint32_t s_addr; /**< The 32bit IP address. */ } pj_in_addr; #else @@ -508,19 +507,19 @@ typedef struct in_addr pj_in_addr; /** * Maximum length of text representation of an IPv4 address. */ -#define PJ_INET_ADDRSTRLEN 16 +#define PJ_INET_ADDRSTRLEN 16 /** * Maximum length of text representation of an IPv6 address. */ -#define PJ_INET6_ADDRSTRLEN 46 +#define PJ_INET6_ADDRSTRLEN 46 /** * The size of sin_zero field in pj_sockaddr_in structure. Most OSes * use 8, but others such as the BSD TCP/IP stack in eCos uses 24. */ #ifndef PJ_SOCKADDR_IN_SIN_ZERO_LEN -# define PJ_SOCKADDR_IN_SIN_ZERO_LEN 8 +# define PJ_SOCKADDR_IN_SIN_ZERO_LEN 8 #endif /** @@ -534,14 +533,14 @@ typedef struct in_addr pj_in_addr; struct pj_sockaddr_in { #if defined(PJ_SOCKADDR_HAS_LEN) && PJ_SOCKADDR_HAS_LEN!=0 - pj_uint8_t sin_zero_len; /**< Just ignore this. */ - pj_uint8_t sin_family; /**< Address family. */ + pj_uint8_t sin_zero_len; /**< Just ignore this. */ + pj_uint8_t sin_family; /**< Address family. */ #else - pj_uint16_t sin_family; /**< Address family. */ + pj_uint16_t sin_family; /**< Address family. */ #endif - pj_uint16_t sin_port; /**< Transport layer port number. */ - pj_in_addr sin_addr; /**< IP address. */ - char sin_zero_pad[PJ_SOCKADDR_IN_SIN_ZERO_LEN]; /**< Padding.*/ + pj_uint16_t sin_port; /**< Transport layer port number. */ + pj_in_addr sin_addr; /**< IP address. */ + char sin_zero_pad[PJ_SOCKADDR_IN_SIN_ZERO_LEN]; /**< Padding.*/ }; @@ -558,7 +557,7 @@ typedef union pj_in6_addr pj_uint8_t s6_addr[16]; /**< 8-bit array */ /* While these are used for proper alignment */ - pj_uint32_t u6_addr32[4]; + pj_uint32_t u6_addr32[4]; /* Do not use this with Winsock2, as this will align pj_sockaddr_in6 * to 64-bit boundary and Winsock2 doesn't like it! @@ -567,7 +566,7 @@ typedef union pj_in6_addr */ #if 0 && defined(PJ_HAS_INT64) && PJ_HAS_INT64!=0 && \ (!defined(PJ_WIN32) || PJ_WIN32==0) - pj_int64_t u6_addr64[2]; + pj_int64_t u6_addr64[2]; #endif } pj_in6_addr; @@ -596,15 +595,15 @@ typedef struct in6_addr pj_in6_addr; typedef struct pj_sockaddr_in6 { #if defined(PJ_SOCKADDR_HAS_LEN) && PJ_SOCKADDR_HAS_LEN!=0 - pj_uint8_t sin6_zero_len; /**< Just ignore this. */ - pj_uint8_t sin6_family; /**< Address family. */ + pj_uint8_t sin6_zero_len; /**< Just ignore this. */ + pj_uint8_t sin6_family; /**< Address family. */ #else - pj_uint16_t sin6_family; /**< Address family */ + pj_uint16_t sin6_family; /**< Address family */ #endif - pj_uint16_t sin6_port; /**< Transport layer port number. */ - pj_uint32_t sin6_flowinfo; /**< IPv6 flow information */ - pj_in6_addr sin6_addr; /**< IPv6 address. */ - pj_uint32_t sin6_scope_id; /**< Set of interfaces for a scope */ + pj_uint16_t sin6_port; /**< Transport layer port number. */ + pj_uint32_t sin6_flowinfo; /**< IPv6 flow information */ + pj_in6_addr sin6_addr; /**< IPv6 address. */ + pj_uint32_t sin6_scope_id; /**< Set of interfaces for a scope */ } pj_sockaddr_in6; @@ -622,7 +621,7 @@ typedef struct pj_addr_hdr pj_uint8_t sa_zero_len; pj_uint8_t sa_family; #else - pj_uint16_t sa_family; /**< Common data: address family. */ + pj_uint16_t sa_family; /**< Common data: address family. */ #endif } pj_addr_hdr; @@ -632,9 +631,9 @@ typedef struct pj_addr_hdr */ typedef union pj_sockaddr { - pj_addr_hdr addr; /**< Generic transport address. */ - pj_sockaddr_in ipv4; /**< IPv4 transport address. */ - pj_sockaddr_in6 ipv6; /**< IPv6 transport address. */ + pj_addr_hdr addr; /**< Generic transport address. */ + pj_sockaddr_in ipv4; /**< IPv4 transport address. */ + pj_sockaddr_in6 ipv6; /**< IPv6 transport address. */ } pj_sockaddr; @@ -642,8 +641,8 @@ typedef union pj_sockaddr * This structure provides multicast group information for IPv4 addresses. */ typedef struct pj_ip_mreq { - pj_in_addr imr_multiaddr; /**< IP multicast address of group. */ - pj_in_addr imr_interface; /**< local IP address of interface. */ + pj_in_addr imr_multiaddr; /**< IP multicast address of group. */ + pj_in_addr imr_interface; /**< local IP address of interface. */ } pj_ip_mreq; @@ -657,17 +656,17 @@ typedef struct pj_sockopt_params /** Array of options to be applied. */ struct { - /** The level at which the option is defined. */ - int level; + /** The level at which the option is defined. */ + int level; - /** Option name. */ - int optname; + /** Option name. */ + int optname; - /** Pointer to the buffer in which the option is specified. */ - void *optval; + /** Pointer to the buffer in which the option is specified. */ + void *optval; - /** Buffer size of the buffer pointed by optval. */ - int optlen; + /** Buffer size of the buffer pointed by optval. */ + int optlen; } options[PJ_MAX_SOCKOPT_PARAMS]; } pj_sockopt_params; @@ -682,7 +681,7 @@ typedef struct pj_sockopt_params * Convert 16-bit value from network byte order to host byte order. * * @param netshort 16-bit network value. - * @return 16-bit host value. + * @return 16-bit host value. */ PJ_DECL(pj_uint16_t) pj_ntohs(pj_uint16_t netshort); @@ -690,7 +689,7 @@ PJ_DECL(pj_uint16_t) pj_ntohs(pj_uint16_t netshort); * Convert 16-bit value from host byte order to network byte order. * * @param hostshort 16-bit host value. - * @return 16-bit network value. + * @return 16-bit network value. */ PJ_DECL(pj_uint16_t) pj_htons(pj_uint16_t hostshort); @@ -698,7 +697,7 @@ PJ_DECL(pj_uint16_t) pj_htons(pj_uint16_t hostshort); * Convert 32-bit value from network byte order to host byte order. * * @param netlong 32-bit network value. - * @return 32-bit host value. + * @return 32-bit host value. */ PJ_DECL(pj_uint32_t) pj_ntohl(pj_uint32_t netlong); @@ -706,7 +705,7 @@ PJ_DECL(pj_uint32_t) pj_ntohl(pj_uint32_t netlong); * Convert 32-bit value from host byte order to network byte order. * * @param hostlong 32-bit host value. - * @return 32-bit network value. + * @return 32-bit network value. */ PJ_DECL(pj_uint32_t) pj_htonl(pj_uint32_t hostlong); @@ -715,7 +714,7 @@ PJ_DECL(pj_uint32_t) pj_htonl(pj_uint32_t hostlong); * to string in standard numbers and dots notation. * * @param inaddr The host address. - * @return The string address. + * @return The string address. */ PJ_DECL(char*) pj_inet_ntoa(pj_in_addr inaddr); @@ -724,10 +723,10 @@ PJ_DECL(char*) pj_inet_ntoa(pj_in_addr inaddr); * numbers-and-dots notation into binary data and stores it in the structure * that inp points to. * - * @param cp IP address in standard numbers-and-dots notation. - * @param inp Structure that holds the output of the conversion. + * @param cp IP address in standard numbers-and-dots notation. + * @param inp Structure that holds the output of the conversion. * - * @return nonzero if the address is valid, zero if not. + * @return nonzero if the address is valid, zero if not. */ PJ_DECL(int) pj_inet_aton(const pj_str_t *cp, pj_in_addr *inp); @@ -736,15 +735,15 @@ PJ_DECL(int) pj_inet_aton(const pj_str_t *cp, pj_in_addr *inp); * into its numeric binary form. It supports both IPv4 and IPv6 address * conversion. * - * @param af Specify the family of the address. The PJ_AF_INET and - * PJ_AF_INET6 address families shall be supported. - * @param src Points to the string being passed in. - * @param dst Points to a buffer into which the function stores the - * numeric address; this shall be large enough to hold the - * numeric address (32 bits for PJ_AF_INET, 128 bits for - * PJ_AF_INET6). + * @param af Specify the family of the address. The PJ_AF_INET and + * PJ_AF_INET6 address families shall be supported. + * @param src Points to the string being passed in. + * @param dst Points to a buffer into which the function stores the + * numeric address; this shall be large enough to hold the + * numeric address (32 bits for PJ_AF_INET, 128 bits for + * PJ_AF_INET6). * - * @return PJ_SUCCESS if conversion was successful. + * @return PJ_SUCCESS if conversion was successful. */ PJ_DECL(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst); @@ -754,65 +753,65 @@ PJ_DECL(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst); * conversion. * @see pj_sockaddr_print() * - * @param af Specify the family of the address. This can be PJ_AF_INET - * or PJ_AF_INET6. - * @param src Points to a buffer holding an IPv4 address if the af argument - * is PJ_AF_INET, or an IPv6 address if the af argument is - * PJ_AF_INET6; the address must be in network byte order. - * @param dst Points to a buffer where the function stores the resulting - * text string; it shall not be NULL. - * @param size Specifies the size of this buffer, which shall be large - * enough to hold the text string (PJ_INET_ADDRSTRLEN characters - * for IPv4, PJ_INET6_ADDRSTRLEN characters for IPv6). + * @param af Specify the family of the address. This can be PJ_AF_INET + * or PJ_AF_INET6. + * @param src Points to a buffer holding an IPv4 address if the af argument + * is PJ_AF_INET, or an IPv6 address if the af argument is + * PJ_AF_INET6; the address must be in network byte order. + * @param dst Points to a buffer where the function stores the resulting + * text string; it shall not be NULL. + * @param size Specifies the size of this buffer, which shall be large + * enough to hold the text string (PJ_INET_ADDRSTRLEN characters + * for IPv4, PJ_INET6_ADDRSTRLEN characters for IPv6). * - * @return PJ_SUCCESS if conversion was successful. + * @return PJ_SUCCESS if conversion was successful. */ PJ_DECL(pj_status_t) pj_inet_ntop(int af, const void *src, - char *dst, int size); + char *dst, int size); /** * Converts numeric address into its text string representation. * @see pj_sockaddr_print() * - * @param af Specify the family of the address. This can be PJ_AF_INET - * or PJ_AF_INET6. - * @param src Points to a buffer holding an IPv4 address if the af argument - * is PJ_AF_INET, or an IPv6 address if the af argument is - * PJ_AF_INET6; the address must be in network byte order. - * @param dst Points to a buffer where the function stores the resulting - * text string; it shall not be NULL. - * @param size Specifies the size of this buffer, which shall be large - * enough to hold the text string (PJ_INET_ADDRSTRLEN characters - * for IPv4, PJ_INET6_ADDRSTRLEN characters for IPv6). + * @param af Specify the family of the address. This can be PJ_AF_INET + * or PJ_AF_INET6. + * @param src Points to a buffer holding an IPv4 address if the af argument + * is PJ_AF_INET, or an IPv6 address if the af argument is + * PJ_AF_INET6; the address must be in network byte order. + * @param dst Points to a buffer where the function stores the resulting + * text string; it shall not be NULL. + * @param size Specifies the size of this buffer, which shall be large + * enough to hold the text string (PJ_INET_ADDRSTRLEN characters + * for IPv4, PJ_INET6_ADDRSTRLEN characters for IPv6). * - * @return The address string or NULL if failed. + * @return The address string or NULL if failed. */ PJ_DECL(char*) pj_inet_ntop2(int af, const void *src, - char *dst, int size); + char *dst, int size); /** * Print socket address. * - * @param addr The socket address. - * @param buf Text buffer. - * @param size Size of buffer. - * @param flags Bitmask combination of these value: - * - 1: port number is included. - * - 2: square bracket is included for IPv6 address. + * @param addr The socket address. + * @param buf Text buffer. + * @param size Size of buffer. + * @param flags Bitmask combination of these value: + * - 1: port number is included. + * - 2: square bracket is included for IPv6 address. * - * @return The address string. + * @return The address string. */ PJ_DECL(char*) pj_sockaddr_print(const pj_sockaddr_t *addr, - char *buf, int size, - unsigned flags); + char *buf, int size, + unsigned flags); /** * Convert address string with numbers and dots to binary IP address. * - * @param cp The IP address in numbers and dots notation. - * @return If success, the IP address is returned in network - * byte order. If failed, PJ_INADDR_NONE will be - * returned. + * @param cp The IP address in numbers and dots notation. + * @return If success, the IP address is returned in network + * byte order. If failed, PJ_INADDR_NONE will be + * returned. * @remark * This is an obsolete interface to #pj_inet_aton(); it is obsolete * because -1 is a valid address (255.255.255.255), and #pj_inet_aton() @@ -823,10 +822,10 @@ PJ_DECL(pj_in_addr) pj_inet_addr(const pj_str_t *cp); /** * Convert address string with numbers and dots to binary IP address. * - * @param cp The IP address in numbers and dots notation. - * @return If success, the IP address is returned in network - * byte order. If failed, PJ_INADDR_NONE will be - * returned. + * @param cp The IP address in numbers and dots notation. + * @return If success, the IP address is returned in network + * byte order. If failed, PJ_INADDR_NONE will be + * returned. * @remark * This is an obsolete interface to #pj_inet_aton(); it is obsolete * because -1 is a valid address (255.255.255.255), and #pj_inet_aton() @@ -842,16 +841,16 @@ PJ_DECL(pj_in_addr) pj_inet_addr2(const char *cp); * * @see pj_sockaddr_init() * - * @param addr The IP socket address to be set. - * @param cp The address string, which can be in a standard - * dotted numbers or a hostname to be resolved. - * @param port The port number, in host byte order. + * @param addr The IP socket address to be set. + * @param cp The address string, which can be in a standard + * dotted numbers or a hostname to be resolved. + * @param port The port number, in host byte order. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sockaddr_in_init( pj_sockaddr_in *addr, - const pj_str_t *cp, - pj_uint16_t port); + const pj_str_t *cp, + pj_uint16_t port); /** * Initialize IP socket address based on the address and port info. @@ -861,47 +860,47 @@ PJ_DECL(pj_status_t) pj_sockaddr_in_init( pj_sockaddr_in *addr, * * @see pj_sockaddr_in_init() * - * @param af Internet address family. - * @param addr The IP socket address to be set. - * @param cp The address string, which can be in a standard - * dotted numbers or a hostname to be resolved. - * @param port The port number, in host byte order. + * @param af Internet address family. + * @param addr The IP socket address to be set. + * @param cp The address string, which can be in a standard + * dotted numbers or a hostname to be resolved. + * @param port The port number, in host byte order. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sockaddr_init(int af, - pj_sockaddr *addr, - const pj_str_t *cp, - pj_uint16_t port); + pj_sockaddr *addr, + const pj_str_t *cp, + pj_uint16_t port); /** * Compare two socket addresses. * - * @param addr1 First address. - * @param addr2 Second address. + * @param addr1 First address. + * @param addr2 Second address. * - * @return Zero on equal, -1 if addr1 is less than addr2, - * and +1 if addr1 is more than addr2. + * @return Zero on equal, -1 if addr1 is less than addr2, + * and +1 if addr1 is more than addr2. */ PJ_DECL(int) pj_sockaddr_cmp(const pj_sockaddr_t *addr1, - const pj_sockaddr_t *addr2); + const pj_sockaddr_t *addr2); /** * Get pointer to the address part of a socket address. * - * @param addr Socket address. + * @param addr Socket address. * - * @return Pointer to address part (sin_addr or sin6_addr, - * depending on address family) + * @return Pointer to address part (sin_addr or sin6_addr, + * depending on address family) */ PJ_DECL(void*) pj_sockaddr_get_addr(const pj_sockaddr_t *addr); /** * Check that a socket address contains a non-zero address part. * - * @param addr Socket address. + * @param addr Socket address. * - * @return Non-zero if address is set to non-zero. + * @return Non-zero if address is set to non-zero. */ PJ_DECL(pj_bool_t) pj_sockaddr_has_addr(const pj_sockaddr_t *addr); @@ -910,9 +909,9 @@ PJ_DECL(pj_bool_t) pj_sockaddr_has_addr(const pj_sockaddr_t *addr); * family. For PJ_AF_INET, the length will be sizeof(pj_in_addr), and * for PJ_AF_INET6, the length will be sizeof(pj_in6_addr). * - * @param addr Socket address. + * @param addr Socket address. * - * @return Length in bytes. + * @return Length in bytes. */ PJ_DECL(unsigned) pj_sockaddr_get_addr_len(const pj_sockaddr_t *addr); @@ -921,28 +920,28 @@ PJ_DECL(unsigned) pj_sockaddr_get_addr_len(const pj_sockaddr_t *addr); * family. For PJ_AF_INET, the length will be sizeof(pj_sockaddr_in), and * for PJ_AF_INET6, the length will be sizeof(pj_sockaddr_in6). * - * @param addr Socket address. + * @param addr Socket address. * - * @return Length in bytes. + * @return Length in bytes. */ PJ_DECL(unsigned) pj_sockaddr_get_len(const pj_sockaddr_t *addr); /** * Copy only the address part (sin_addr/sin6_addr) of a socket address. * - * @param dst Destination socket address. - * @param src Source socket address. + * @param dst Destination socket address. + * @param src Source socket address. * * @see pj_sockaddr_cp() */ PJ_DECL(void) pj_sockaddr_copy_addr(pj_sockaddr *dst, - const pj_sockaddr *src); + const pj_sockaddr *src); /** * Copy socket address. This will copy the whole structure depending * on the address family of the source socket address. * - * @param dst Destination socket address. - * @param src Source socket address. + * @param dst Destination socket address. + * @param src Source socket address. * * @see pj_sockaddr_copy_addr() */ @@ -955,34 +954,34 @@ PJ_DECL(void) pj_sockaddr_cp(pj_sockaddr_t *dst, const pj_sockaddr_t *src); * IPv6 address. * * @param dst_af Desired address family. - * @param dst Destination socket address, invalid if synthesis is - * required and failed. - * @param src Source socket address. + * @param dst Destination socket address, invalid if synthesis is + * required and failed. + * @param src Source socket address. * - * @return PJ_SUCCESS on success, or the error status - * if synthesis is required and failed. + * @return PJ_SUCCESS on success, or the error status + * if synthesis is required and failed. */ PJ_DECL(pj_status_t) pj_sockaddr_synthesize(int dst_af, - pj_sockaddr_t *dst, - const pj_sockaddr_t *src); + pj_sockaddr_t *dst, + const pj_sockaddr_t *src); /** * Get the IP address of an IPv4 socket address. * The address is returned as 32bit value in host byte order. * - * @param addr The IP socket address. - * @return 32bit address, in host byte order. + * @param addr The IP socket address. + * @return 32bit address, in host byte order. */ PJ_DECL(pj_in_addr) pj_sockaddr_in_get_addr(const pj_sockaddr_in *addr); /** * Set the IP address of an IPv4 socket address. * - * @param addr The IP socket address. + * @param addr The IP socket address. * @param hostaddr The host address, in host byte order. */ PJ_DECL(void) pj_sockaddr_in_set_addr(pj_sockaddr_in *addr, - pj_uint32_t hostaddr); + pj_uint32_t hostaddr); /** * Set the IP address of an IP socket address from string address, @@ -993,14 +992,14 @@ PJ_DECL(void) pj_sockaddr_in_set_addr(pj_sockaddr_in *addr, * * @see pj_sockaddr_set_str_addr() * - * @param addr The IP socket address to be set. - * @param cp The address string, which can be in a standard - * dotted numbers or a hostname to be resolved. + * @param addr The IP socket address to be set. + * @param cp The address string, which can be in a standard + * dotted numbers or a hostname to be resolved. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pj_sockaddr_in_set_str_addr( pj_sockaddr_in *addr, - const pj_str_t *cp); + const pj_str_t *cp); /** * Set the IP address of an IPv4 or IPv6 socket address from string address, @@ -1009,24 +1008,24 @@ PJ_DECL(pj_status_t) pj_sockaddr_in_set_str_addr( pj_sockaddr_in *addr, * is specified, then the function will resolve the host into the IP * address according to the address family. * - * @param af Address family. - * @param addr The IP socket address to be set. - * @param cp The address string, which can be in a standard - * IP numbers (IPv4 or IPv6) or a hostname to be resolved. + * @param af Address family. + * @param addr The IP socket address to be set. + * @param cp The address string, which can be in a standard + * IP numbers (IPv4 or IPv6) or a hostname to be resolved. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pj_sockaddr_set_str_addr(int af, - pj_sockaddr *addr, - const pj_str_t *cp); + pj_sockaddr *addr, + const pj_str_t *cp); /** * Get the port number of a socket address, in host byte order. * This function can be used for both IPv4 and IPv6 socket address. * - * @param addr Socket address. + * @param addr Socket address. * - * @return Port number, in host byte order. + * @return Port number, in host byte order. */ PJ_DECL(pj_uint16_t) pj_sockaddr_get_port(const pj_sockaddr_t *addr); @@ -1034,30 +1033,30 @@ PJ_DECL(pj_uint16_t) pj_sockaddr_get_port(const pj_sockaddr_t *addr); * Get the transport layer port number of an Internet socket address. * The port is returned in host byte order. * - * @param addr The IP socket address. - * @return Port number, in host byte order. + * @param addr The IP socket address. + * @return Port number, in host byte order. */ PJ_DECL(pj_uint16_t) pj_sockaddr_in_get_port(const pj_sockaddr_in *addr); /** * Set the port number of an Internet socket address. * - * @param addr The socket address. + * @param addr The socket address. * @param hostport The port number, in host byte order. */ PJ_DECL(pj_status_t) pj_sockaddr_set_port(pj_sockaddr *addr, - pj_uint16_t hostport); + pj_uint16_t hostport); /** * Set the port number of an IPv4 socket address. * * @see pj_sockaddr_set_port() * - * @param addr The IP socket address. + * @param addr The IP socket address. * @param hostport The port number, in host byte order. */ PJ_DECL(void) pj_sockaddr_in_set_port(pj_sockaddr_in *addr, - pj_uint16_t hostport); + pj_uint16_t hostport); /** * Parse string containing IP address and optional port into socket address, @@ -1096,22 +1095,22 @@ PJ_DECL(void) pj_sockaddr_in_set_port(pj_sockaddr_in *addr, * otherwise the port number will be included as part of the IP address * (see "fec0::01:80" example above). * - * @param af Optionally specify the address family to be used. If the - * address family is to be deducted from the input, specify - * pj_AF_UNSPEC() here. Other supported values are - * #pj_AF_INET() and #pj_AF_INET6() + * @param af Optionally specify the address family to be used. If the + * address family is to be deducted from the input, specify + * pj_AF_UNSPEC() here. Other supported values are + * #pj_AF_INET() and #pj_AF_INET6() * @param options Additional options to assist the parsing, must be zero - * for now. - * @param str The input string to be parsed. - * @param addr Pointer to store the result. + * for now. + * @param str The input string to be parsed. + * @param addr Pointer to store the result. * - * @return PJ_SUCCESS if the parsing is successful. + * @return PJ_SUCCESS if the parsing is successful. * * @see pj_sockaddr_parse2() */ PJ_DECL(pj_status_t) pj_sockaddr_parse(int af, unsigned options, - const pj_str_t *str, - pj_sockaddr *addr); + const pj_str_t *str, + pj_sockaddr *addr); /** * This function is similar to #pj_sockaddr_parse(), except that it will not @@ -1123,29 +1122,29 @@ PJ_DECL(pj_status_t) pj_sockaddr_parse(int af, unsigned options, * address MUST be enclosed in square brackets, otherwise the port number will * be considered as part of the IPv6 IP address. * - * @param af Optionally specify the address family to be used. If the - * address family is to be deducted from the input, specify - * #pj_AF_UNSPEC() here. Other supported values are - * #pj_AF_INET() and #pj_AF_INET6() + * @param af Optionally specify the address family to be used. If the + * address family is to be deducted from the input, specify + * #pj_AF_UNSPEC() here. Other supported values are + * #pj_AF_INET() and #pj_AF_INET6() * @param options Additional options to assist the parsing, must be zero - * for now. - * @param str The input string to be parsed. + * for now. + * @param str The input string to be parsed. * @param hostpart Optional pointer to store the host part of the socket - * address, with any brackets removed. - * @param port Optional pointer to store the port number. If port number - * is not found, this will be set to zero upon return. - * @param raf Optional pointer to store the detected address family of - * the input address. + * address, with any brackets removed. + * @param port Optional pointer to store the port number. If port number + * is not found, this will be set to zero upon return. + * @param raf Optional pointer to store the detected address family of + * the input address. * - * @return PJ_SUCCESS if the parsing is successful. + * @return PJ_SUCCESS if the parsing is successful. * * @see pj_sockaddr_parse() */ PJ_DECL(pj_status_t) pj_sockaddr_parse2(int af, unsigned options, - const pj_str_t *str, - pj_str_t *hostpart, - pj_uint16_t *port, - int *raf); + const pj_str_t *str, + pj_str_t *hostpart, + pj_uint16_t *port, + int *raf); /***************************************************************************** * @@ -1157,8 +1156,8 @@ PJ_DECL(pj_status_t) pj_sockaddr_parse2(int af, unsigned options, /** * Get system's host name. * - * @return The hostname, or empty string if the hostname can not - * be identified. + * @return The hostname, or empty string if the hostname can not + * be identified. */ PJ_DECL(const pj_str_t*) pj_gethostname(void); @@ -1166,8 +1165,8 @@ PJ_DECL(const pj_str_t*) pj_gethostname(void); * Get host's IP address, which the the first IP address that is resolved * from the hostname. * - * @return The host's IP address, PJ_INADDR_NONE if the host - * IP address can not be identified. + * @return The host's IP address, PJ_INADDR_NONE if the host + * IP address can not be identified. */ PJ_DECL(pj_in_addr) pj_gethostaddr(void); @@ -1183,28 +1182,28 @@ PJ_DECL(pj_in_addr) pj_gethostaddr(void); * Create new socket/endpoint for communication. * * @param family Specifies a communication domain; this selects the - * protocol family which will be used for communication. - * @param type The socket has the indicated type, which specifies the - * communication semantics. + * protocol family which will be used for communication. + * @param type The socket has the indicated type, which specifies the + * communication semantics. * @param protocol Specifies a particular protocol to be used with the - * socket. Normally only a single protocol exists to support - * a particular socket type within a given protocol family, - * in which a case protocol can be specified as 0. - * @param sock New socket descriptor, or PJ_INVALID_SOCKET on error. + * socket. Normally only a single protocol exists to support + * a particular socket type within a given protocol family, + * in which a case protocol can be specified as 0. + * @param sock New socket descriptor, or PJ_INVALID_SOCKET on error. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sock_socket(int family, - int type, - int protocol, - pj_sock_t *sock); + int type, + int protocol, + pj_sock_t *sock); /** * Close the socket descriptor. * * @param sockfd The socket descriptor. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sock_close(pj_sock_t sockfd); @@ -1219,42 +1218,42 @@ PJ_DECL(pj_status_t) pj_sock_close(pj_sock_t sockfd); * @param my_addr The local address to bind the socket to. * @param addrlen The length of the address. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sock_bind( pj_sock_t sockfd, - const pj_sockaddr_t *my_addr, - int addrlen); + const pj_sockaddr_t *my_addr, + int addrlen); /** * Bind the IP socket sockfd to the given address and port. * * @param sockfd The socket descriptor. - * @param addr Local address to bind the socket to, in host byte order. - * @param port The local port to bind the socket to, in host byte order. + * @param addr Local address to bind the socket to, in host byte order. + * @param port The local port to bind the socket to, in host byte order. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sock_bind_in( pj_sock_t sockfd, - pj_uint32_t addr, - pj_uint16_t port); + pj_uint32_t addr, + pj_uint16_t port); /** * Bind the IP socket sockfd to the given address and a random port in the * specified range. * - * @param sockfd The socket desriptor. - * @param addr The local address and port to bind the socket to. - * @param port_range The port range, relative the to start port number - * specified in port field in addr. Note that if the - * port is zero, this param will be ignored. - * @param max_try Maximum retries. + * @param sockfd The socket desriptor. + * @param addr The local address and port to bind the socket to. + * @param port_range The port range, relative the to start port number + * specified in port field in addr. Note that if the + * port is zero, this param will be ignored. + * @param max_try Maximum retries. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sock_bind_random( pj_sock_t sockfd, - const pj_sockaddr_t *addr, - pj_uint16_t port_range, - pj_uint16_t max_try); + const pj_sockaddr_t *addr, + pj_uint16_t port_range, + pj_uint16_t max_try); #if PJ_HAS_TCP /** @@ -1262,31 +1261,31 @@ PJ_DECL(pj_status_t) pj_sock_bind_random( pj_sock_t sockfd, * oriented sockets (such as PJ_SOCK_STREAM or PJ_SOCK_SEQPACKET), and it * indicates the willingness to accept incoming connections. * - * @param sockfd The socket descriptor. - * @param backlog Defines the maximum length the queue of pending - * connections may grow to. + * @param sockfd The socket descriptor. + * @param backlog Defines the maximum length the queue of pending + * connections may grow to. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sock_listen( pj_sock_t sockfd, - int backlog ); + int backlog ); /** * Accept new connection on the specified connection oriented server socket. * * @param serverfd The server socket. * @param newsock New socket on success, of PJ_INVALID_SOCKET if failed. - * @param addr A pointer to sockaddr type. If the argument is not NULL, - * it will be filled by the address of connecting entity. + * @param addr A pointer to sockaddr type. If the argument is not NULL, + * it will be filled by the address of connecting entity. * @param addrlen Initially specifies the length of the address, and upon - * return will be filled with the exact address length. + * return will be filled with the exact address length. * - * @return Zero on success, or the error number. + * @return Zero on success, or the error number. */ PJ_DECL(pj_status_t) pj_sock_accept( pj_sock_t serverfd, - pj_sock_t *newsock, - pj_sockaddr_t *addr, - int *addrlen); + pj_sock_t *newsock, + pj_sockaddr_t *addr, + int *addrlen); #endif /** @@ -1299,209 +1298,209 @@ PJ_DECL(pj_status_t) pj_sock_accept( pj_sock_t serverfd, * addrlen) in the communications space of the socket. Each communications * space interprets the serv_addr parameter in its own way. * - * @param sockfd The socket descriptor. - * @param serv_addr Server address to connect to. - * @param addrlen The length of server address. + * @param sockfd The socket descriptor. + * @param serv_addr Server address to connect to. + * @param addrlen The length of server address. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sock_connect( pj_sock_t sockfd, - const pj_sockaddr_t *serv_addr, - int addrlen); + const pj_sockaddr_t *serv_addr, + int addrlen); /** * Return the address of peer which is connected to socket sockfd. * - * @param sockfd The socket descriptor. - * @param addr Pointer to sockaddr structure to which the address - * will be returned. - * @param namelen Initially the length of the addr. Upon return the value - * will be set to the actual length of the address. + * @param sockfd The socket descriptor. + * @param addr Pointer to sockaddr structure to which the address + * will be returned. + * @param namelen Initially the length of the addr. Upon return the value + * will be set to the actual length of the address. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sock_getpeername(pj_sock_t sockfd, - pj_sockaddr_t *addr, - int *namelen); + pj_sockaddr_t *addr, + int *namelen); /** * Return the current name of the specified socket. * - * @param sockfd The socket descriptor. - * @param addr Pointer to sockaddr structure to which the address - * will be returned. - * @param namelen Initially the length of the addr. Upon return the value - * will be set to the actual length of the address. + * @param sockfd The socket descriptor. + * @param addr Pointer to sockaddr structure to which the address + * will be returned. + * @param namelen Initially the length of the addr. Upon return the value + * will be set to the actual length of the address. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sock_getsockname( pj_sock_t sockfd, - pj_sockaddr_t *addr, - int *namelen); + pj_sockaddr_t *addr, + int *namelen); /** * Get socket option associated with a socket. Options may exist at multiple * protocol levels; they are always present at the uppermost socket level. * - * @param sockfd The socket descriptor. - * @param level The level which to get the option from. - * @param optname The option name. - * @param optval Identifies the buffer which the value will be - * returned. - * @param optlen Initially contains the length of the buffer, upon - * return will be set to the actual size of the value. + * @param sockfd The socket descriptor. + * @param level The level which to get the option from. + * @param optname The option name. + * @param optval Identifies the buffer which the value will be + * returned. + * @param optlen Initially contains the length of the buffer, upon + * return will be set to the actual size of the value. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sock_getsockopt( pj_sock_t sockfd, - pj_uint16_t level, - pj_uint16_t optname, - void *optval, - int *optlen); + pj_uint16_t level, + pj_uint16_t optname, + void *optval, + int *optlen); /** * Manipulate the options associated with a socket. Options may exist at * multiple protocol levels; they are always present at the uppermost socket * level. * - * @param sockfd The socket descriptor. - * @param level The level which to get the option from. - * @param optname The option name. - * @param optval Identifies the buffer which contain the value. - * @param optlen The length of the value. + * @param sockfd The socket descriptor. + * @param level The level which to get the option from. + * @param optname The option name. + * @param optval Identifies the buffer which contain the value. + * @param optlen The length of the value. * - * @return PJ_SUCCESS or the status code. + * @return PJ_SUCCESS or the status code. */ PJ_DECL(pj_status_t) pj_sock_setsockopt( pj_sock_t sockfd, - pj_uint16_t level, - pj_uint16_t optname, - const void *optval, - int optlen); + pj_uint16_t level, + pj_uint16_t optname, + const void *optval, + int optlen); /** * Set socket options associated with a socket. This method will apply all the * options specified, and ignore any errors that might be raised. * - * @param sockfd The socket descriptor. - * @param params The socket options. + * @param sockfd The socket descriptor. + * @param params The socket options. * - * @return PJ_SUCCESS or the last error code. + * @return PJ_SUCCESS or the last error code. */ PJ_DECL(pj_status_t) pj_sock_setsockopt_params( pj_sock_t sockfd, - const pj_sockopt_params *params); + const pj_sockopt_params *params); /** * Helper function to set socket buffer size using #pj_sock_setsockopt() * with capability to auto retry with lower buffer setting value until * the highest possible value is successfully set. * - * @param sockfd The socket descriptor. - * @param optname The option name, valid values are pj_SO_RCVBUF() - * and pj_SO_SNDBUF(). - * @param auto_retry Option whether auto retry with lower value is - * enabled. - * @param buf_size On input, specify the prefered buffer size setting, - * on output, the buffer size setting applied. + * @param sockfd The socket descriptor. + * @param optname The option name, valid values are pj_SO_RCVBUF() + * and pj_SO_SNDBUF(). + * @param auto_retry Option whether auto retry with lower value is + * enabled. + * @param buf_size On input, specify the prefered buffer size setting, + * on output, the buffer size setting applied. * - * @return PJ_SUCCESS or the status code. + * @return PJ_SUCCESS or the status code. */ PJ_DECL(pj_status_t) pj_sock_setsockopt_sobuf( pj_sock_t sockfd, - pj_uint16_t optname, - pj_bool_t auto_retry, - unsigned *buf_size); + pj_uint16_t optname, + pj_bool_t auto_retry, + unsigned *buf_size); /** * Receives data stream or message coming to the specified socket. * - * @param sockfd The socket descriptor. - * @param buf The buffer to receive the data or message. - * @param len On input, the length of the buffer. On return, - * contains the length of data received. - * @param flags Flags (such as pj_MSG_PEEK()). + * @param sockfd The socket descriptor. + * @param buf The buffer to receive the data or message. + * @param len On input, the length of the buffer. On return, + * contains the length of data received. + * @param flags Flags (such as pj_MSG_PEEK()). * - * @return PJ_SUCCESS or the error code. + * @return PJ_SUCCESS or the error code. */ PJ_DECL(pj_status_t) pj_sock_recv(pj_sock_t sockfd, - void *buf, - pj_ssize_t *len, - unsigned flags); + void *buf, + pj_ssize_t *len, + unsigned flags); /** * Receives data stream or message coming to the specified socket. * - * @param sockfd The socket descriptor. - * @param buf The buffer to receive the data or message. - * @param len On input, the length of the buffer. On return, - * contains the length of data received. - * @param flags Flags (such as pj_MSG_PEEK()). - * @param from If not NULL, it will be filled with the source - * address of the connection. - * @param fromlen Initially contains the length of from address, - * and upon return will be filled with the actual - * length of the address. + * @param sockfd The socket descriptor. + * @param buf The buffer to receive the data or message. + * @param len On input, the length of the buffer. On return, + * contains the length of data received. + * @param flags Flags (such as pj_MSG_PEEK()). + * @param from If not NULL, it will be filled with the source + * address of the connection. + * @param fromlen Initially contains the length of from address, + * and upon return will be filled with the actual + * length of the address. * - * @return PJ_SUCCESS or the error code. + * @return PJ_SUCCESS or the error code. */ PJ_DECL(pj_status_t) pj_sock_recvfrom( pj_sock_t sockfd, - void *buf, - pj_ssize_t *len, - unsigned flags, - pj_sockaddr_t *from, - int *fromlen); + void *buf, + pj_ssize_t *len, + unsigned flags, + pj_sockaddr_t *from, + int *fromlen); /** * Transmit data to the socket. * - * @param sockfd Socket descriptor. - * @param buf Buffer containing data to be sent. - * @param len On input, the length of the data in the buffer. - * Upon return, it will be filled with the length - * of data sent. - * @param flags Flags (such as pj_MSG_DONTROUTE()). + * @param sockfd Socket descriptor. + * @param buf Buffer containing data to be sent. + * @param len On input, the length of the data in the buffer. + * Upon return, it will be filled with the length + * of data sent. + * @param flags Flags (such as pj_MSG_DONTROUTE()). * - * @return PJ_SUCCESS or the status code. + * @return PJ_SUCCESS or the status code. */ PJ_DECL(pj_status_t) pj_sock_send(pj_sock_t sockfd, - const void *buf, - pj_ssize_t *len, - unsigned flags); + const void *buf, + pj_ssize_t *len, + unsigned flags); /** * Transmit data to the socket to the specified address. * - * @param sockfd Socket descriptor. - * @param buf Buffer containing data to be sent. - * @param len On input, the length of the data in the buffer. - * Upon return, it will be filled with the length - * of data sent. - * @param flags Flags (such as pj_MSG_DONTROUTE()). - * @param to The address to send. - * @param tolen The length of the address in bytes. + * @param sockfd Socket descriptor. + * @param buf Buffer containing data to be sent. + * @param len On input, the length of the data in the buffer. + * Upon return, it will be filled with the length + * of data sent. + * @param flags Flags (such as pj_MSG_DONTROUTE()). + * @param to The address to send. + * @param tolen The length of the address in bytes. * - * @return PJ_SUCCESS or the status code. + * @return PJ_SUCCESS or the status code. */ PJ_DECL(pj_status_t) pj_sock_sendto(pj_sock_t sockfd, - const void *buf, - pj_ssize_t *len, - unsigned flags, - const pj_sockaddr_t *to, - int tolen); + const void *buf, + pj_ssize_t *len, + unsigned flags, + const pj_sockaddr_t *to, + int tolen); #if PJ_HAS_TCP /** * The shutdown call causes all or part of a full-duplex connection on the * socket associated with sockfd to be shut down. * - * @param sockfd The socket descriptor. - * @param how If how is PJ_SHUT_RD, further receptions will be - * disallowed. If how is PJ_SHUT_WR, further transmissions - * will be disallowed. If how is PJ_SHUT_RDWR, further - * receptions andtransmissions will be disallowed. + * @param sockfd The socket descriptor. + * @param how If how is PJ_SHUT_RD, further receptions will be + * disallowed. If how is PJ_SHUT_WR, further transmissions + * will be disallowed. If how is PJ_SHUT_RDWR, further + * receptions andtransmissions will be disallowed. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pj_sock_shutdown( pj_sock_t sockfd, - int how); + int how); #endif /***************************************************************************** @@ -1516,38 +1515,38 @@ PJ_DECL(pj_status_t) pj_sock_shutdown( pj_sock_t sockfd, * with square bracket if it's IPv6 address. * * @param host_str The host address string. - * @param port The port address. - * @param buf Text buffer. - * @param size Size of buffer. - * @param flag Bitmask combination of these value: - * - 1: port number is included. + * @param port The port address. + * @param buf Text buffer. + * @param size Size of buffer. + * @param flag Bitmask combination of these value: + * - 1: port number is included. * - * @return The address string. + * @return The address string. */ PJ_DECL(char *) pj_addr_str_print( const pj_str_t *host_str, int port, - char *buf, int size, unsigned flag); + char *buf, int size, unsigned flag); /** * Create socket pair * @param family Specifies a communication domain; this selects the - * protocol family which will be used for communication. - * On Unix, support AF_UNIX, AF_INET and AF_INET6, - * On Win32, not support AF_UNIX. - * @param type The socket has the indicated type, which specifies the - * communication semantics. + * protocol family which will be used for communication. + * On Unix, support AF_UNIX, AF_INET and AF_INET6, + * On Win32, not support AF_UNIX. + * @param type The socket has the indicated type, which specifies the + * communication semantics. * @param protocol Specifies a particular protocol to be used with the - * socket. Normally only a single protocol exists to support - * a particular socket type within a given protocol family, - * in which a case protocol can be specified as 0. - * @param sv The new sockets vector + * socket. Normally only a single protocol exists to support + * a particular socket type within a given protocol family, + * in which a case protocol can be specified as 0. + * @param sv The new sockets vector * - * @return Zero on success. + * @return Zero on success. * */ PJ_DECL(pj_status_t) pj_sock_socketpair(int family, - int type, - int protocol, - pj_sock_t sv[2]); + int type, + int protocol, + pj_sock_t sv[2]); /** * @} @@ -1556,5 +1555,5 @@ PJ_DECL(pj_status_t) pj_sock_socketpair(int family, PJ_END_DECL -#endif /* __PJ_SOCK_H__ */ +#endif /* __PJ_SOCK_H__ */ diff --git a/pjlib/include/pj/sock_qos.h b/pjlib/include/pj/sock_qos.h index 7e8d439a10..93e0450663 100644 --- a/pjlib/include/pj/sock_qos.h +++ b/pjlib/include/pj/sock_qos.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -120,12 +119,12 @@ PJ_BEGIN_DECL \code typedef enum pj_qos_type { - PJ_QOS_TYPE_BEST_EFFORT, - PJ_QOS_TYPE_BACKGROUND, - PJ_QOS_TYPE_VIDEO, - PJ_QOS_TYPE_VOICE, - PJ_QOS_TYPE_CONTROL, - PJ_QOS_TYPE_SIGNALLING + PJ_QOS_TYPE_BEST_EFFORT, + PJ_QOS_TYPE_BACKGROUND, + PJ_QOS_TYPE_VIDEO, + PJ_QOS_TYPE_VOICE, + PJ_QOS_TYPE_CONTROL, + PJ_QOS_TYPE_SIGNALLING } pj_qos_type; \endcode @@ -135,14 +134,14 @@ PJ_BEGIN_DECL \code ================================================================= - PJLIB Traffic Type IP DSCP WMM 802.1p + PJLIB Traffic Type IP DSCP WMM 802.1p ----------------------------------------------------------------- - BEST_EFFORT 0x00 BE (Bulk Effort) 0 - BACKGROUND 0x08 BK (Bulk) 2 - VIDEO 0x28 VI (Video) 5 - VOICE 0x30 VO (Voice) 6 - CONTROL 0x38 VO (Voice) 7 - SIGNALLING 0x28 VI (Video) 5 + BEST_EFFORT 0x00 BE (Bulk Effort) 0 + BACKGROUND 0x08 BK (Bulk) 2 + VIDEO 0x28 VI (Video) 5 + VOICE 0x30 VO (Voice) 6 + CONTROL 0x38 VO (Voice) 7 + SIGNALLING 0x28 VI (Video) 5 ================================================================= \endcode @@ -155,11 +154,11 @@ PJ_BEGIN_DECL \code // Set QoS parameters PJ_DECL(pj_status_t) pj_sock_set_qos_type(pj_sock_t sock, - pj_qos_type val); + pj_qos_type val); // Get QoS parameters PJ_DECL(pj_status_t) pj_sock_get_qos_type(pj_sock_t sock, - pj_qos_type *p_val); + pj_qos_type *p_val); \endcode The API will set the traffic type according to the DSCP class, for both @@ -180,26 +179,26 @@ PJ_BEGIN_DECL \code typedef enum pj_qos_flag { - PJ_QOS_PARAM_HAS_DSCP = 1, - PJ_QOS_PARAM_HAS_SO_PRIO = 2, - PJ_QOS_PARAM_HAS_WMM = 4 + PJ_QOS_PARAM_HAS_DSCP = 1, + PJ_QOS_PARAM_HAS_SO_PRIO = 2, + PJ_QOS_PARAM_HAS_WMM = 4 } pj_qos_flag; typedef enum pj_qos_wmm_prio { - PJ_QOS_WMM_PRIO_BULK_EFFORT, - PJ_QOS_WMM_PRIO_BULK, - PJ_QOS_WMM_PRIO_VIDEO, - PJ_QOS_WMM_PRIO_VOICE + PJ_QOS_WMM_PRIO_BULK_EFFORT, + PJ_QOS_WMM_PRIO_BULK, + PJ_QOS_WMM_PRIO_VIDEO, + PJ_QOS_WMM_PRIO_VOICE } pj_qos_wmm_prio; typedef struct pj_qos_params { - pj_uint8_t flags; // Determines which values to - // set, bitmask of pj_qos_flag - pj_uint8_t dscp_val; // The 6 bits DSCP value to set - pj_uint8_t so_prio; // SO_PRIORITY value - pj_qos_wmm_prio wmm_prio; // WMM priority value + pj_uint8_t flags; // Determines which values to + // set, bitmask of pj_qos_flag + pj_uint8_t dscp_val; // The 6 bits DSCP value to set + pj_uint8_t so_prio; // SO_PRIORITY value + pj_qos_wmm_prio wmm_prio; // WMM priority value } pj_qos_params; \endcode @@ -209,15 +208,15 @@ PJ_BEGIN_DECL \code // Retrieve QoS params for the specified traffic type PJ_DECL(pj_status_t) pj_qos_get_params(pj_qos_type type, - pj_qos_params *p); + pj_qos_params *p); // Set QoS parameters to the socket PJ_DECL(pj_status_t) pj_sock_set_qos_params(pj_sock_t sock, - const pj_qos_params *p); + const pj_qos_params *p); // Get QoS parameters from the socket PJ_DECL(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, - pj_qos_params *p); + pj_qos_params *p); \endcode @@ -234,14 +233,14 @@ PJ_BEGIN_DECL */ typedef enum pj_qos_type { - PJ_QOS_TYPE_BEST_EFFORT, /**< Best effort traffic (default value). - Any QoS function calls with specifying - this value are effectively no-op */ - PJ_QOS_TYPE_BACKGROUND, /**< Background traffic. */ - PJ_QOS_TYPE_VIDEO, /**< Video traffic. */ - PJ_QOS_TYPE_VOICE, /**< Voice traffic. */ - PJ_QOS_TYPE_CONTROL, /**< Control traffic. */ - PJ_QOS_TYPE_SIGNALLING /**< Signalling traffic. */ + PJ_QOS_TYPE_BEST_EFFORT, /**< Best effort traffic (default value). + Any QoS function calls with specifying + this value are effectively no-op */ + PJ_QOS_TYPE_BACKGROUND, /**< Background traffic. */ + PJ_QOS_TYPE_VIDEO, /**< Video traffic. */ + PJ_QOS_TYPE_VOICE, /**< Voice traffic. */ + PJ_QOS_TYPE_CONTROL, /**< Control traffic. */ + PJ_QOS_TYPE_SIGNALLING /**< Signalling traffic. */ } pj_qos_type; /** @@ -250,9 +249,9 @@ typedef enum pj_qos_type */ typedef enum pj_qos_flag { - PJ_QOS_PARAM_HAS_DSCP = 1, /**< DSCP field is set. */ - PJ_QOS_PARAM_HAS_SO_PRIO = 2, /**< Socket SO_PRIORITY */ - PJ_QOS_PARAM_HAS_WMM = 4 /**< WMM field is set. */ + PJ_QOS_PARAM_HAS_DSCP = 1, /**< DSCP field is set. */ + PJ_QOS_PARAM_HAS_SO_PRIO = 2, /**< Socket SO_PRIORITY */ + PJ_QOS_PARAM_HAS_WMM = 4 /**< WMM field is set. */ } pj_qos_flag; @@ -261,10 +260,10 @@ typedef enum pj_qos_flag */ typedef enum pj_qos_wmm_prio { - PJ_QOS_WMM_PRIO_BULK_EFFORT, /**< Bulk effort priority */ - PJ_QOS_WMM_PRIO_BULK, /**< Bulk priority. */ - PJ_QOS_WMM_PRIO_VIDEO, /**< Video priority */ - PJ_QOS_WMM_PRIO_VOICE /**< Voice priority */ + PJ_QOS_WMM_PRIO_BULK_EFFORT, /**< Bulk effort priority */ + PJ_QOS_WMM_PRIO_BULK, /**< Bulk priority. */ + PJ_QOS_WMM_PRIO_VIDEO, /**< Video priority */ + PJ_QOS_WMM_PRIO_VOICE /**< Voice priority */ } pj_qos_wmm_prio; @@ -274,10 +273,10 @@ typedef enum pj_qos_wmm_prio typedef struct pj_qos_params { pj_uint8_t flags; /**< Determines which values to - set, bitmask of pj_qos_flag */ - pj_uint8_t dscp_val; /**< The 6 bits DSCP value to set */ - pj_uint8_t so_prio; /**< SO_PRIORITY value */ - pj_qos_wmm_prio wmm_prio; /**< WMM priority value */ + set, bitmask of pj_qos_flag */ + pj_uint8_t dscp_val; /**< The 6 bits DSCP value to set */ + pj_uint8_t so_prio; /**< SO_PRIORITY value */ + pj_qos_wmm_prio wmm_prio; /**< WMM priority value */ } pj_qos_params; @@ -286,15 +285,15 @@ typedef struct pj_qos_params * This is the high level and portable API to enable QoS on the specified * socket, by setting the traffic type to the specified parameter. * - * @param sock The socket. - * @param type Traffic type to be set. + * @param sock The socket. + * @param type Traffic type to be set. * - * @return PJ_SUCCESS if at least Layer 2 or Layer 3 setting is - * successfully set. If both Layer 2 and Layer 3 settings - * can't be set, this function will return error. + * @return PJ_SUCCESS if at least Layer 2 or Layer 3 setting is + * successfully set. If both Layer 2 and Layer 3 settings + * can't be set, this function will return error. */ PJ_DECL(pj_status_t) pj_sock_set_qos_type(pj_sock_t sock, - pj_qos_type type); + pj_qos_type type); /** * This is the high level and portable API to get the traffic type that has @@ -302,14 +301,14 @@ PJ_DECL(pj_status_t) pj_sock_set_qos_type(pj_sock_t sock, * were modified by using low level API, this function may return approximation * of the closest QoS type that matches the settings. * - * @param sock The socket. + * @param sock The socket. * @param p_type Pointer to receive the traffic type of the socket. * - * @return PJ_SUCCESS if traffic type for the socket can be obtained - * or approximated.. + * @return PJ_SUCCESS if traffic type for the socket can be obtained + * or approximated.. */ PJ_DECL(pj_status_t) pj_sock_get_qos_type(pj_sock_t sock, - pj_qos_type *p_type); + pj_qos_type *p_type); /** @@ -317,31 +316,31 @@ PJ_DECL(pj_status_t) pj_sock_get_qos_type(pj_sock_t sock, * logging if the operations failed. Both QoS traffic type and the low level * QoS parameters can be applied with this function. * - * @param sock The socket handle. - * @param qos_type QoS traffic type. The QoS traffic type will be applied - * only if the value is not PJ_QOS_TYPE_BEST_EFFORT, - * @param qos_params Optional low-level QoS parameters. This will be - * applied only if this argument is not NULL and the - * flags inside the structure is non-zero. Upon return, - * the flags will indicate which parameters have been - * applied successfully. - * @param log_level This function will print to log at this level upon - * encountering errors. - * @param log_sender Optional sender name in the log. - * @param sock_name Optional name to help identify the socket in the log. + * @param sock The socket handle. + * @param qos_type QoS traffic type. The QoS traffic type will be applied + * only if the value is not PJ_QOS_TYPE_BEST_EFFORT, + * @param qos_params Optional low-level QoS parameters. This will be + * applied only if this argument is not NULL and the + * flags inside the structure is non-zero. Upon return, + * the flags will indicate which parameters have been + * applied successfully. + * @param log_level This function will print to log at this level upon + * encountering errors. + * @param log_sender Optional sender name in the log. + * @param sock_name Optional name to help identify the socket in the log. * - * @return PJ_SUCCESS if at least Layer 2 or Layer 3 setting is - * successfully set. If both Layer 2 and Layer 3 settings - * can't be set, this function will return error. + * @return PJ_SUCCESS if at least Layer 2 or Layer 3 setting is + * successfully set. If both Layer 2 and Layer 3 settings + * can't be set, this function will return error. * * @see pj_sock_apply_qos2() */ PJ_DECL(pj_status_t) pj_sock_apply_qos(pj_sock_t sock, - pj_qos_type qos_type, - pj_qos_params *qos_params, - unsigned log_level, - const char *log_sender, - const char *sock_name); + pj_qos_type qos_type, + pj_qos_params *qos_params, + unsigned log_level, + const char *log_sender, + const char *sock_name); /** * Variant of #pj_sock_apply_qos() where the \a qos_params parameter is @@ -350,24 +349,24 @@ PJ_DECL(pj_status_t) pj_sock_apply_qos(pj_sock_t sock, * @see pj_sock_apply_qos() */ PJ_DECL(pj_status_t) pj_sock_apply_qos2(pj_sock_t sock, - pj_qos_type qos_type, - const pj_qos_params *qos_params, - unsigned log_level, - const char *log_sender, - const char *sock_name); + pj_qos_type qos_type, + const pj_qos_params *qos_params, + unsigned log_level, + const char *log_sender, + const char *sock_name); /** * Retrieve the standard mapping of QoS params for the specified traffic * type. * - * @param type The traffic type from which the QoS parameters - * are to be retrieved. + * @param type The traffic type from which the QoS parameters + * are to be retrieved. * @param p_param Pointer to receive the QoS parameters. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_qos_get_params(pj_qos_type type, - pj_qos_params *p_param); + pj_qos_params *p_param); /** @@ -376,47 +375,47 @@ PJ_DECL(pj_status_t) pj_qos_get_params(pj_qos_type type, * approximation of the closest matching traffic type for the specified * QoS parameters. * - * @param param Structure containing QoS parameters to map into - * "standard" traffic types. + * @param param Structure containing QoS parameters to map into + * "standard" traffic types. * @param p_type Pointer to receive the traffic type. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_qos_get_type(const pj_qos_params *param, - pj_qos_type *p_type); + pj_qos_type *p_type); /** * This is a low level API to set QoS parameters to the socket. * - * @param sock The socket. - * @param param Structure containing QoS parameters to be applied - * to the socket. Upon return, the \a flags field - * of this structure will be set with bitmask value - * indicating which QoS settings have successfully - * been applied to the socket. + * @param sock The socket. + * @param param Structure containing QoS parameters to be applied + * to the socket. Upon return, the \a flags field + * of this structure will be set with bitmask value + * indicating which QoS settings have successfully + * been applied to the socket. * - * @return PJ_SUCCESS if at least one field setting has been - * successfully set. If no setting can't be set, - * this function will return error. + * @return PJ_SUCCESS if at least one field setting has been + * successfully set. If no setting can't be set, + * this function will return error. */ PJ_DECL(pj_status_t) pj_sock_set_qos_params(pj_sock_t sock, - pj_qos_params *param); + pj_qos_params *param); /** * This is a low level API to get QoS parameters from the socket. * - * @param sock The socket. + * @param sock The socket. * @param p_param Pointer to receive the parameters. Upon returning - * successfully, the \a flags field of this structure - * will be initialized with the appropriate bitmask - * to indicate which fields have been successfully - * retrieved. + * successfully, the \a flags field of this structure + * will be initialized with the appropriate bitmask + * to indicate which fields have been successfully + * retrieved. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, - pj_qos_params *p_param); + pj_qos_params *p_param); /** @@ -426,5 +425,5 @@ PJ_DECL(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, PJ_END_DECL -#endif /* __PJ_SOCK_QOS_H__ */ +#endif /* __PJ_SOCK_QOS_H__ */ diff --git a/pjlib/include/pj/sock_select.h b/pjlib/include/pj/sock_select.h index 1b5b335b6c..d35cd6bc7d 100644 --- a/pjlib/include/pj/sock_select.h +++ b/pjlib/include/pj/sock_select.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -87,7 +86,7 @@ PJ_DECL(pj_size_t) PJ_FD_COUNT(const pj_fd_set_t *fdsetp); * If the file descriptor fd is already in this set, there shall be no effect * on the set, nor will an error be returned. * - * @param fd The socket descriptor. + * @param fd The socket descriptor. * @param fdsetp The descriptor set. */ PJ_DECL(void) PJ_FD_SET(pj_sock_t fd, pj_fd_set_t *fdsetp); @@ -97,7 +96,7 @@ PJ_DECL(void) PJ_FD_SET(pj_sock_t fd, pj_fd_set_t *fdsetp); * If fd is not a member of this set, there shall be no effect on the set, * nor will an error be returned. * - * @param fd The socket descriptor. + * @param fd The socket descriptor. * @param fdsetp The descriptor set. */ PJ_DECL(void) PJ_FD_CLR(pj_sock_t fd, pj_fd_set_t *fdsetp); @@ -107,10 +106,10 @@ PJ_DECL(void) PJ_FD_CLR(pj_sock_t fd, pj_fd_set_t *fdsetp); * Evaluate to non-zero if the file descriptor fd is a member of the set * pointed to by fdsetp, and shall evaluate to zero otherwise. * - * @param fd The socket descriptor. + * @param fd The socket descriptor. * @param fdsetp The descriptor set. * - * @return Nonzero if fd is member of the descriptor set. + * @return Nonzero if fd is member of the descriptor set. */ PJ_DECL(pj_bool_t) PJ_FD_ISSET(pj_sock_t fd, const pj_fd_set_t *fdsetp); @@ -120,26 +119,26 @@ PJ_DECL(pj_bool_t) PJ_FD_ISSET(pj_sock_t fd, const pj_fd_set_t *fdsetp); * The behaviour is the same as select() function call which appear in * standard BSD socket libraries. * - * @param n On Unices, this specifies the highest-numbered - * descriptor in any of the three set, plus 1. On Windows, - * the value is ignored. + * @param n On Unices, this specifies the highest-numbered + * descriptor in any of the three set, plus 1. On Windows, + * the value is ignored. * @param readfds Optional pointer to a set of sockets to be checked for - * readability. + * readability. * @param writefds Optional pointer to a set of sockets to be checked for - * writability. + * writability. * @param exceptfds Optional pointer to a set of sockets to be checked for - * errors. + * errors. * @param timeout Maximum time for select to wait, or null for blocking - * operations. + * operations. * - * @return The total number of socket handles that are ready, or - * zero if the time limit expired, or -1 if an error occurred. + * @return The total number of socket handles that are ready, or + * zero if the time limit expired, or -1 if an error occurred. */ PJ_DECL(int) pj_sock_select( int n, - pj_fd_set_t *readfds, - pj_fd_set_t *writefds, - pj_fd_set_t *exceptfds, - const pj_time_val *timeout); + pj_fd_set_t *readfds, + pj_fd_set_t *writefds, + pj_fd_set_t *exceptfds, + const pj_time_val *timeout); /** @@ -149,4 +148,4 @@ PJ_DECL(int) pj_sock_select( int n, PJ_END_DECL -#endif /* __PJ_SELECT_H__ */ +#endif /* __PJ_SELECT_H__ */ diff --git a/pjlib/include/pj/ssl_sock.h b/pjlib/include/pj/ssl_sock.h index a08132d473..484a1235a0 100644 --- a/pjlib/include/pj/ssl_sock.h +++ b/pjlib/include/pj/ssl_sock.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * @@ -68,55 +67,55 @@ typedef enum pj_ssl_cert_verify_flag_t /** * No error in verification. */ - PJ_SSL_CERT_ESUCCESS = 0, + PJ_SSL_CERT_ESUCCESS = 0, /** * The issuer certificate cannot be found. */ - PJ_SSL_CERT_EISSUER_NOT_FOUND = (1 << 0), + PJ_SSL_CERT_EISSUER_NOT_FOUND = (1 << 0), /** * The certificate is untrusted. */ - PJ_SSL_CERT_EUNTRUSTED = (1 << 1), + PJ_SSL_CERT_EUNTRUSTED = (1 << 1), /** * The certificate has expired or not yet valid. */ - PJ_SSL_CERT_EVALIDITY_PERIOD = (1 << 2), + PJ_SSL_CERT_EVALIDITY_PERIOD = (1 << 2), /** * One or more fields of the certificate cannot be decoded due to * invalid format. */ - PJ_SSL_CERT_EINVALID_FORMAT = (1 << 3), + PJ_SSL_CERT_EINVALID_FORMAT = (1 << 3), /** * The certificate cannot be used for the specified purpose. */ - PJ_SSL_CERT_EINVALID_PURPOSE = (1 << 4), + PJ_SSL_CERT_EINVALID_PURPOSE = (1 << 4), /** * The issuer info in the certificate does not match to the (candidate) * issuer certificate, e.g: issuer name not match to subject name * of (candidate) issuer certificate. */ - PJ_SSL_CERT_EISSUER_MISMATCH = (1 << 5), + PJ_SSL_CERT_EISSUER_MISMATCH = (1 << 5), /** * The CRL certificate cannot be found or cannot be read properly. */ - PJ_SSL_CERT_ECRL_FAILURE = (1 << 6), + PJ_SSL_CERT_ECRL_FAILURE = (1 << 6), /** * The certificate has been revoked. */ - PJ_SSL_CERT_EREVOKED = (1 << 7), + PJ_SSL_CERT_EREVOKED = (1 << 7), /** * The certificate chain length is too long. */ - PJ_SSL_CERT_ECHAIN_TOO_LONG = (1 << 8), + PJ_SSL_CERT_ECHAIN_TOO_LONG = (1 << 8), /** * The server identity does not match to any identities specified in @@ -124,12 +123,12 @@ typedef enum pj_ssl_cert_verify_flag_t * This flag will only be set by application as SSL socket does not * perform server identity verification. */ - PJ_SSL_CERT_EIDENTITY_NOT_MATCH = (1 << 30), + PJ_SSL_CERT_EIDENTITY_NOT_MATCH = (1 << 30), /** * Unknown verification error. */ - PJ_SSL_CERT_EUNKNOWN = (1 << 31) + PJ_SSL_CERT_EUNKNOWN = (1 << 31) } pj_ssl_cert_verify_flag_t; @@ -151,47 +150,47 @@ typedef enum pj_ssl_cert_name_type */ typedef struct pj_ssl_cert_info { - unsigned version; /**< Certificate version */ + unsigned version; /**< Certificate version */ - pj_uint8_t serial_no[20]; /**< Serial number, array of - octets, first index is - MSB */ + pj_uint8_t serial_no[20]; /**< Serial number, array of + octets, first index is + MSB */ struct { - pj_str_t cn; /**< Common name */ - pj_str_t info; /**< One line subject, fields - are separated by slash, e.g: - "CN=sample.org/OU=HRD" */ - } subject; /**< Subject */ + pj_str_t cn; /**< Common name */ + pj_str_t info; /**< One line subject, fields + are separated by slash, e.g: + "CN=sample.org/OU=HRD" */ + } subject; /**< Subject */ struct { - pj_str_t cn; /**< Common name */ - pj_str_t info; /**< One line subject, fields - are separated by slash.*/ - } issuer; /**< Issuer */ + pj_str_t cn; /**< Common name */ + pj_str_t info; /**< One line subject, fields + are separated by slash.*/ + } issuer; /**< Issuer */ struct { - pj_time_val start; /**< Validity start */ - pj_time_val end; /**< Validity end */ - pj_bool_t gmt; /**< Flag if validity date/time - use GMT */ - } validity; /**< Validity */ + pj_time_val start; /**< Validity start */ + pj_time_val end; /**< Validity end */ + pj_bool_t gmt; /**< Flag if validity date/time + use GMT */ + } validity; /**< Validity */ struct { - unsigned cnt; /**< # of entry */ - struct { - pj_ssl_cert_name_type type; - /**< Name type */ - pj_str_t name; /**< The name */ - } *entry; /**< Subject alt name entry */ - } subj_alt_name; /**< Subject alternative - name extension */ - - pj_str_t raw; /**< Raw certificate in PEM format, only - available for remote certificate. */ + unsigned cnt; /**< # of entry */ + struct { + pj_ssl_cert_name_type type; + /**< Name type */ + pj_str_t name; /**< The name */ + } *entry; /**< Subject alt name entry */ + } subj_alt_name; /**< Subject alternative + name extension */ + + pj_str_t raw; /**< Raw certificate in PEM format, only + available for remote certificate. */ struct { - unsigned cnt; /**< # of entry */ + unsigned cnt; /**< # of entry */ pj_str_t *cert_raw; } raw_chain; @@ -208,21 +207,21 @@ typedef pj_str_t pj_ssl_cert_buffer; * suffix, e.g: "pjsip_rsa.pem", the library will automatically check for * other certificates with "_ecc" and "_dsa" suffix. * - * @param pool The pool. - * @param CA_file The file of trusted CA list. - * @param cert_file The file of certificate. - * @param privkey_file The file of private key. - * @param privkey_pass The password of private key, if any. - * @param p_cert Pointer to credential instance to be created. + * @param pool The pool. + * @param CA_file The file of trusted CA list. + * @param cert_file The file of certificate. + * @param privkey_file The file of private key. + * @param privkey_pass The password of private key, if any. + * @param p_cert Pointer to credential instance to be created. * - * @return PJ_SUCCESS when successful. + * @return PJ_SUCCESS when successful. */ PJ_DECL(pj_status_t) pj_ssl_cert_load_from_files(pj_pool_t *pool, - const pj_str_t *CA_file, - const pj_str_t *cert_file, - const pj_str_t *privkey_file, - const pj_str_t *privkey_pass, - pj_ssl_cert_t **p_cert); + const pj_str_t *CA_file, + const pj_str_t *cert_file, + const pj_str_t *privkey_file, + const pj_str_t *privkey_pass, + pj_ssl_cert_t **p_cert); /** * Create credential from files. TLS server application can provide multiple @@ -234,84 +233,84 @@ PJ_DECL(pj_status_t) pj_ssl_cert_load_from_files(pj_pool_t *pool, * accepts an additional param CA_path to load CA certificates from * a directory. * - * @param pool The pool. - * @param CA_file The file of trusted CA list. - * @param CA_path The path to a directory of trusted CA list. - * @param cert_file The file of certificate. - * @param privkey_file The file of private key. - * @param privkey_pass The password of private key, if any. - * @param p_cert Pointer to credential instance to be created. + * @param pool The pool. + * @param CA_file The file of trusted CA list. + * @param CA_path The path to a directory of trusted CA list. + * @param cert_file The file of certificate. + * @param privkey_file The file of private key. + * @param privkey_pass The password of private key, if any. + * @param p_cert Pointer to credential instance to be created. * - * @return PJ_SUCCESS when successful. + * @return PJ_SUCCESS when successful. */ PJ_DECL(pj_status_t) pj_ssl_cert_load_from_files2( - pj_pool_t *pool, - const pj_str_t *CA_file, - const pj_str_t *CA_path, - const pj_str_t *cert_file, - const pj_str_t *privkey_file, - const pj_str_t *privkey_pass, - pj_ssl_cert_t **p_cert); + pj_pool_t *pool, + const pj_str_t *CA_file, + const pj_str_t *CA_path, + const pj_str_t *cert_file, + const pj_str_t *privkey_file, + const pj_str_t *privkey_pass, + pj_ssl_cert_t **p_cert); /** * Create credential from data buffer. The certificate expected is in * PEM format. * - * @param pool The pool. - * @param CA_buf The buffer of trusted CA list. - * @param cert_buf The buffer of certificate. - * @param privkey_buf The buffer of private key. - * @param privkey_pass The password of private key, if any. - * @param p_cert Pointer to credential instance to be created. + * @param pool The pool. + * @param CA_buf The buffer of trusted CA list. + * @param cert_buf The buffer of certificate. + * @param privkey_buf The buffer of private key. + * @param privkey_pass The password of private key, if any. + * @param p_cert Pointer to credential instance to be created. * - * @return PJ_SUCCESS when successful. + * @return PJ_SUCCESS when successful. */ PJ_DECL(pj_status_t) pj_ssl_cert_load_from_buffer(pj_pool_t *pool, - const pj_ssl_cert_buffer *CA_buf, - const pj_ssl_cert_buffer *cert_buf, - const pj_ssl_cert_buffer *privkey_buf, - const pj_str_t *privkey_pass, - pj_ssl_cert_t **p_cert); + const pj_ssl_cert_buffer *CA_buf, + const pj_ssl_cert_buffer *cert_buf, + const pj_ssl_cert_buffer *privkey_buf, + const pj_str_t *privkey_pass, + pj_ssl_cert_t **p_cert); /** * Dump SSL certificate info. * - * @param ci The certificate info. - * @param indent String for left indentation. - * @param buf The buffer where certificate info will be printed on. - * @param buf_size The buffer size. + * @param ci The certificate info. + * @param indent String for left indentation. + * @param buf The buffer where certificate info will be printed on. + * @param buf_size The buffer size. * - * @return The length of the dump result, or -1 when buffer size - * is not sufficient. + * @return The length of the dump result, or -1 when buffer size + * is not sufficient. */ PJ_DECL(pj_ssize_t) pj_ssl_cert_info_dump(const pj_ssl_cert_info *ci, - const char *indent, - char *buf, - pj_size_t buf_size); + const char *indent, + char *buf, + pj_size_t buf_size); /** * Get SSL certificate verification error messages from verification status. * - * @param verify_status The SSL certificate verification status. - * @param error_strings Array of strings to receive the verification error - * messages. - * @param count On input it specifies maximum error messages should be - * retrieved. On output it specifies the number of error - * messages retrieved. + * @param verify_status The SSL certificate verification status. + * @param error_strings Array of strings to receive the verification error + * messages. + * @param count On input it specifies maximum error messages should be + * retrieved. On output it specifies the number of error + * messages retrieved. * - * @return PJ_SUCCESS when successful. + * @return PJ_SUCCESS when successful. */ PJ_DECL(pj_status_t) pj_ssl_cert_get_verify_status_strings( - pj_uint32_t verify_status, - const char *error_strings[], - unsigned *count); + pj_uint32_t verify_status, + const char *error_strings[], + unsigned *count); /** * Wipe out the keys in the SSL certificate. * - * @param cert The SSL certificate. + * @param cert The SSL certificate. * */ PJ_DECL(void) pj_ssl_cert_wipe_keys(pj_ssl_cert_t *cert); @@ -326,77 +325,77 @@ typedef enum pj_ssl_cipher { PJ_TLS_UNKNOWN_CIPHER = -1, /* NULL */ - PJ_TLS_NULL_WITH_NULL_NULL = 0x00000000, + PJ_TLS_NULL_WITH_NULL_NULL = 0x00000000, /* TLS/SSLv3 */ - PJ_TLS_RSA_WITH_NULL_MD5 = 0x00000001, - PJ_TLS_RSA_WITH_NULL_SHA = 0x00000002, - PJ_TLS_RSA_WITH_NULL_SHA256 = 0x0000003B, - PJ_TLS_RSA_WITH_RC4_128_MD5 = 0x00000004, - PJ_TLS_RSA_WITH_RC4_128_SHA = 0x00000005, - PJ_TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0x0000000A, - PJ_TLS_RSA_WITH_AES_128_CBC_SHA = 0x0000002F, - PJ_TLS_RSA_WITH_AES_256_CBC_SHA = 0x00000035, - PJ_TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x0000003C, - PJ_TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x0000003D, - PJ_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = 0x0000000D, - PJ_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = 0x00000010, - PJ_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = 0x00000013, - PJ_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x00000016, - PJ_TLS_DH_DSS_WITH_AES_128_CBC_SHA = 0x00000030, - PJ_TLS_DH_RSA_WITH_AES_128_CBC_SHA = 0x00000031, - PJ_TLS_DHE_DSS_WITH_AES_128_CBC_SHA = 0x00000032, - PJ_TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x00000033, - PJ_TLS_DH_DSS_WITH_AES_256_CBC_SHA = 0x00000036, - PJ_TLS_DH_RSA_WITH_AES_256_CBC_SHA = 0x00000037, - PJ_TLS_DHE_DSS_WITH_AES_256_CBC_SHA = 0x00000038, - PJ_TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x00000039, - PJ_TLS_DH_DSS_WITH_AES_128_CBC_SHA256 = 0x0000003E, - PJ_TLS_DH_RSA_WITH_AES_128_CBC_SHA256 = 0x0000003F, - PJ_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = 0x00000040, - PJ_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x00000067, - PJ_TLS_DH_DSS_WITH_AES_256_CBC_SHA256 = 0x00000068, - PJ_TLS_DH_RSA_WITH_AES_256_CBC_SHA256 = 0x00000069, - PJ_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = 0x0000006A, - PJ_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x0000006B, - PJ_TLS_DH_anon_WITH_RC4_128_MD5 = 0x00000018, - PJ_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = 0x0000001B, - PJ_TLS_DH_anon_WITH_AES_128_CBC_SHA = 0x00000034, - PJ_TLS_DH_anon_WITH_AES_256_CBC_SHA = 0x0000003A, - PJ_TLS_DH_anon_WITH_AES_128_CBC_SHA256 = 0x0000006C, - PJ_TLS_DH_anon_WITH_AES_256_CBC_SHA256 = 0x0000006D, + PJ_TLS_RSA_WITH_NULL_MD5 = 0x00000001, + PJ_TLS_RSA_WITH_NULL_SHA = 0x00000002, + PJ_TLS_RSA_WITH_NULL_SHA256 = 0x0000003B, + PJ_TLS_RSA_WITH_RC4_128_MD5 = 0x00000004, + PJ_TLS_RSA_WITH_RC4_128_SHA = 0x00000005, + PJ_TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0x0000000A, + PJ_TLS_RSA_WITH_AES_128_CBC_SHA = 0x0000002F, + PJ_TLS_RSA_WITH_AES_256_CBC_SHA = 0x00000035, + PJ_TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x0000003C, + PJ_TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x0000003D, + PJ_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = 0x0000000D, + PJ_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = 0x00000010, + PJ_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = 0x00000013, + PJ_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x00000016, + PJ_TLS_DH_DSS_WITH_AES_128_CBC_SHA = 0x00000030, + PJ_TLS_DH_RSA_WITH_AES_128_CBC_SHA = 0x00000031, + PJ_TLS_DHE_DSS_WITH_AES_128_CBC_SHA = 0x00000032, + PJ_TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x00000033, + PJ_TLS_DH_DSS_WITH_AES_256_CBC_SHA = 0x00000036, + PJ_TLS_DH_RSA_WITH_AES_256_CBC_SHA = 0x00000037, + PJ_TLS_DHE_DSS_WITH_AES_256_CBC_SHA = 0x00000038, + PJ_TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x00000039, + PJ_TLS_DH_DSS_WITH_AES_128_CBC_SHA256 = 0x0000003E, + PJ_TLS_DH_RSA_WITH_AES_128_CBC_SHA256 = 0x0000003F, + PJ_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = 0x00000040, + PJ_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x00000067, + PJ_TLS_DH_DSS_WITH_AES_256_CBC_SHA256 = 0x00000068, + PJ_TLS_DH_RSA_WITH_AES_256_CBC_SHA256 = 0x00000069, + PJ_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = 0x0000006A, + PJ_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x0000006B, + PJ_TLS_DH_anon_WITH_RC4_128_MD5 = 0x00000018, + PJ_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = 0x0000001B, + PJ_TLS_DH_anon_WITH_AES_128_CBC_SHA = 0x00000034, + PJ_TLS_DH_anon_WITH_AES_256_CBC_SHA = 0x0000003A, + PJ_TLS_DH_anon_WITH_AES_128_CBC_SHA256 = 0x0000006C, + PJ_TLS_DH_anon_WITH_AES_256_CBC_SHA256 = 0x0000006D, /* TLS (deprecated) */ - PJ_TLS_RSA_EXPORT_WITH_RC4_40_MD5 = 0x00000003, - PJ_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = 0x00000006, - PJ_TLS_RSA_WITH_IDEA_CBC_SHA = 0x00000007, - PJ_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x00000008, - PJ_TLS_RSA_WITH_DES_CBC_SHA = 0x00000009, - PJ_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = 0x0000000B, - PJ_TLS_DH_DSS_WITH_DES_CBC_SHA = 0x0000000C, - PJ_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x0000000E, - PJ_TLS_DH_RSA_WITH_DES_CBC_SHA = 0x0000000F, - PJ_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = 0x00000011, - PJ_TLS_DHE_DSS_WITH_DES_CBC_SHA = 0x00000012, - PJ_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x00000014, - PJ_TLS_DHE_RSA_WITH_DES_CBC_SHA = 0x00000015, - PJ_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 = 0x00000017, - PJ_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA = 0x00000019, - PJ_TLS_DH_anon_WITH_DES_CBC_SHA = 0x0000001A, + PJ_TLS_RSA_EXPORT_WITH_RC4_40_MD5 = 0x00000003, + PJ_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = 0x00000006, + PJ_TLS_RSA_WITH_IDEA_CBC_SHA = 0x00000007, + PJ_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x00000008, + PJ_TLS_RSA_WITH_DES_CBC_SHA = 0x00000009, + PJ_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = 0x0000000B, + PJ_TLS_DH_DSS_WITH_DES_CBC_SHA = 0x0000000C, + PJ_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x0000000E, + PJ_TLS_DH_RSA_WITH_DES_CBC_SHA = 0x0000000F, + PJ_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = 0x00000011, + PJ_TLS_DHE_DSS_WITH_DES_CBC_SHA = 0x00000012, + PJ_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x00000014, + PJ_TLS_DHE_RSA_WITH_DES_CBC_SHA = 0x00000015, + PJ_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 = 0x00000017, + PJ_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA = 0x00000019, + PJ_TLS_DH_anon_WITH_DES_CBC_SHA = 0x0000001A, /* SSLv3 */ - PJ_SSL_FORTEZZA_KEA_WITH_NULL_SHA = 0x0000001C, - PJ_SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA = 0x0000001D, - PJ_SSL_FORTEZZA_KEA_WITH_RC4_128_SHA = 0x0000001E, + PJ_SSL_FORTEZZA_KEA_WITH_NULL_SHA = 0x0000001C, + PJ_SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA = 0x0000001D, + PJ_SSL_FORTEZZA_KEA_WITH_RC4_128_SHA = 0x0000001E, /* SSLv2 */ - PJ_SSL_CK_RC4_128_WITH_MD5 = 0x00010080, - PJ_SSL_CK_RC4_128_EXPORT40_WITH_MD5 = 0x00020080, - PJ_SSL_CK_RC2_128_CBC_WITH_MD5 = 0x00030080, - PJ_SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5 = 0x00040080, - PJ_SSL_CK_IDEA_128_CBC_WITH_MD5 = 0x00050080, - PJ_SSL_CK_DES_64_CBC_WITH_MD5 = 0x00060040, - PJ_SSL_CK_DES_192_EDE3_CBC_WITH_MD5 = 0x000700C0 + PJ_SSL_CK_RC4_128_WITH_MD5 = 0x00010080, + PJ_SSL_CK_RC4_128_EXPORT40_WITH_MD5 = 0x00020080, + PJ_SSL_CK_RC2_128_CBC_WITH_MD5 = 0x00030080, + PJ_SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5 = 0x00040080, + PJ_SSL_CK_IDEA_128_CBC_WITH_MD5 = 0x00050080, + PJ_SSL_CK_DES_64_CBC_WITH_MD5 = 0x00060040, + PJ_SSL_CK_DES_192_EDE3_CBC_WITH_MD5 = 0x000700C0 } pj_ssl_cipher; @@ -404,21 +403,21 @@ typedef enum pj_ssl_cipher { /** * Get cipher list supported by SSL/TLS backend. * - * @param ciphers The ciphers buffer to receive cipher list. - * @param cipher_num Maximum number of ciphers to be received. + * @param ciphers The ciphers buffer to receive cipher list. + * @param cipher_num Maximum number of ciphers to be received. * - * @return PJ_SUCCESS when successful. + * @return PJ_SUCCESS when successful. */ PJ_DECL(pj_status_t) pj_ssl_cipher_get_availables(pj_ssl_cipher ciphers[], - unsigned *cipher_num); + unsigned *cipher_num); /** * Check if the specified cipher is supported by SSL/TLS backend. * - * @param cipher The cipher. + * @param cipher The cipher. * - * @return PJ_TRUE when supported. + * @return PJ_TRUE when supported. */ PJ_DECL(pj_bool_t) pj_ssl_cipher_is_supported(pj_ssl_cipher cipher); @@ -426,10 +425,10 @@ PJ_DECL(pj_bool_t) pj_ssl_cipher_is_supported(pj_ssl_cipher cipher); /** * Get cipher name string. * - * @param cipher The cipher. + * @param cipher The cipher. * - * @return The cipher name or NULL if cipher is not recognized/ - * supported. + * @return The cipher name or NULL if cipher is not recognized/ + * supported. */ PJ_DECL(const char*) pj_ssl_cipher_name(pj_ssl_cipher cipher); @@ -439,10 +438,10 @@ PJ_DECL(const char*) pj_ssl_cipher_name(pj_ssl_cipher cipher); * (e.g. OpenSSL or Symbian implementation), cipher names may not be * equivalent for the same cipher ID. * - * @param cipher_name The cipher name string. + * @param cipher_name The cipher name string. * - * @return The cipher ID or PJ_TLS_UNKNOWN_CIPHER if the cipher - * name string is not recognized/supported. + * @return The cipher ID or PJ_TLS_UNKNOWN_CIPHER if the cipher + * name string is not recognized/supported. */ PJ_DECL(pj_ssl_cipher) pj_ssl_cipher_id(const char *cipher_name); @@ -451,56 +450,56 @@ PJ_DECL(pj_ssl_cipher) pj_ssl_cipher_id(const char *cipher_name); */ typedef enum pj_ssl_curve { - PJ_TLS_UNKNOWN_CURVE = 0, - PJ_TLS_CURVE_SECT163K1 = 1, - PJ_TLS_CURVE_SECT163R1 = 2, - PJ_TLS_CURVE_SECT163R2 = 3, - PJ_TLS_CURVE_SECT193R1 = 4, - PJ_TLS_CURVE_SECT193R2 = 5, - PJ_TLS_CURVE_SECT233K1 = 6, - PJ_TLS_CURVE_SECT233R1 = 7, - PJ_TLS_CURVE_SECT239K1 = 8, - PJ_TLS_CURVE_SECT283K1 = 9, - PJ_TLS_CURVE_SECT283R1 = 10, - PJ_TLS_CURVE_SECT409K1 = 11, - PJ_TLS_CURVE_SECT409R1 = 12, - PJ_TLS_CURVE_SECT571K1 = 13, - PJ_TLS_CURVE_SECT571R1 = 14, - PJ_TLS_CURVE_SECP160K1 = 15, - PJ_TLS_CURVE_SECP160R1 = 16, - PJ_TLS_CURVE_SECP160R2 = 17, - PJ_TLS_CURVE_SECP192K1 = 18, - PJ_TLS_CURVE_SECP192R1 = 19, - PJ_TLS_CURVE_SECP224K1 = 20, - PJ_TLS_CURVE_SECP224R1 = 21, - PJ_TLS_CURVE_SECP256K1 = 22, - PJ_TLS_CURVE_SECP256R1 = 23, - PJ_TLS_CURVE_SECP384R1 = 24, - PJ_TLS_CURVE_SECP521R1 = 25, - PJ_TLS_CURVE_BRAINPOOLP256R1 = 26, - PJ_TLS_CURVE_BRAINPOOLP384R1 = 27, - PJ_TLS_CURVE_BRAINPOOLP512R1 = 28, - PJ_TLS_CURVE_ARBITRARY_EXPLICIT_PRIME_CURVES = 0XFF01, - PJ_TLS_CURVE_ARBITRARY_EXPLICIT_CHAR2_CURVES = 0XFF02 + PJ_TLS_UNKNOWN_CURVE = 0, + PJ_TLS_CURVE_SECT163K1 = 1, + PJ_TLS_CURVE_SECT163R1 = 2, + PJ_TLS_CURVE_SECT163R2 = 3, + PJ_TLS_CURVE_SECT193R1 = 4, + PJ_TLS_CURVE_SECT193R2 = 5, + PJ_TLS_CURVE_SECT233K1 = 6, + PJ_TLS_CURVE_SECT233R1 = 7, + PJ_TLS_CURVE_SECT239K1 = 8, + PJ_TLS_CURVE_SECT283K1 = 9, + PJ_TLS_CURVE_SECT283R1 = 10, + PJ_TLS_CURVE_SECT409K1 = 11, + PJ_TLS_CURVE_SECT409R1 = 12, + PJ_TLS_CURVE_SECT571K1 = 13, + PJ_TLS_CURVE_SECT571R1 = 14, + PJ_TLS_CURVE_SECP160K1 = 15, + PJ_TLS_CURVE_SECP160R1 = 16, + PJ_TLS_CURVE_SECP160R2 = 17, + PJ_TLS_CURVE_SECP192K1 = 18, + PJ_TLS_CURVE_SECP192R1 = 19, + PJ_TLS_CURVE_SECP224K1 = 20, + PJ_TLS_CURVE_SECP224R1 = 21, + PJ_TLS_CURVE_SECP256K1 = 22, + PJ_TLS_CURVE_SECP256R1 = 23, + PJ_TLS_CURVE_SECP384R1 = 24, + PJ_TLS_CURVE_SECP521R1 = 25, + PJ_TLS_CURVE_BRAINPOOLP256R1 = 26, + PJ_TLS_CURVE_BRAINPOOLP384R1 = 27, + PJ_TLS_CURVE_BRAINPOOLP512R1 = 28, + PJ_TLS_CURVE_ARBITRARY_EXPLICIT_PRIME_CURVES = 0XFF01, + PJ_TLS_CURVE_ARBITRARY_EXPLICIT_CHAR2_CURVES = 0XFF02 } pj_ssl_curve; /** * Get curve list supported by SSL/TLS backend. * - * @param curves The curves buffer to receive curve list. - * @param curve_num Maximum number of curves to be received. + * @param curves The curves buffer to receive curve list. + * @param curve_num Maximum number of curves to be received. * - * @return PJ_SUCCESS when successful. + * @return PJ_SUCCESS when successful. */ PJ_DECL(pj_status_t) pj_ssl_curve_get_availables(pj_ssl_curve curves[], - unsigned *curve_num); + unsigned *curve_num); /** * Check if the specified curve is supported by SSL/TLS backend. * - * @param curve The curve. + * @param curve The curve. * - * @return PJ_TRUE when supported. + * @return PJ_TRUE when supported. */ PJ_DECL(pj_bool_t) pj_ssl_curve_is_supported(pj_ssl_curve curve); @@ -508,10 +507,10 @@ PJ_DECL(pj_bool_t) pj_ssl_curve_is_supported(pj_ssl_curve curve); /** * Get curve name string. * - * @param curve The curve. + * @param curve The curve. * - * @return The curve name or NULL if curve is not recognized/ - * supported. + * @return The curve name or NULL if curve is not recognized/ + * supported. */ PJ_DECL(const char*) pj_ssl_curve_name(pj_ssl_curve curve); @@ -520,10 +519,10 @@ PJ_DECL(const char*) pj_ssl_curve_name(pj_ssl_curve curve); * (e.g. OpenSSL or Symbian implementation), curve names may not be * equivalent for the same curve ID. * - * @param curve_name The curve name string. + * @param curve_name The curve name string. * - * @return The curve ID or PJ_TLS_UNKNOWN_CURVE if the curve - * name string is not recognized/supported. + * @return The curve ID or PJ_TLS_UNKNOWN_CURVE if the curve + * name string is not recognized/supported. */ PJ_DECL(pj_ssl_curve) pj_ssl_curve_id(const char *curve_name); @@ -532,12 +531,12 @@ PJ_DECL(pj_ssl_curve) pj_ssl_curve_id(const char *curve_name); */ typedef enum pj_ssl_entropy { - PJ_SSL_ENTROPY_NONE = 0, /**< None */ - PJ_SSL_ENTROPY_EGD = 1, /**< EGD */ - PJ_SSL_ENTROPY_RANDOM = 2, /**< Random */ - PJ_SSL_ENTROPY_URANDOM = 3, /**< Urandom */ - PJ_SSL_ENTROPY_FILE = 4, /**< File */ - PJ_SSL_ENTROPY_UNKNOWN = 0x0F /**< Unknown */ + PJ_SSL_ENTROPY_NONE = 0, /**< None */ + PJ_SSL_ENTROPY_EGD = 1, /**< EGD */ + PJ_SSL_ENTROPY_RANDOM = 2, /**< Random */ + PJ_SSL_ENTROPY_URANDOM = 3, /**< Urandom */ + PJ_SSL_ENTROPY_FILE = 4, /**< File */ + PJ_SSL_ENTROPY_UNKNOWN = 0x0F /**< Unknown */ } pj_ssl_entropy_t; /** @@ -549,146 +548,146 @@ typedef struct pj_ssl_sock_cb * This callback is called when a data arrives as the result of * pj_ssl_sock_start_read(). * - * @param ssock The secure socket. - * @param data The buffer containing the new data, if any. If - * the status argument is non-PJ_SUCCESS, this - * argument may be NULL. - * @param size The length of data in the buffer. - * @param status The status of the read operation. This may contain - * non-PJ_SUCCESS for example when the TCP connection - * has been closed. In this case, the buffer may - * contain left over data from previous callback which - * the application may want to process. - * @param remainder If application wishes to leave some data in the - * buffer (common for TCP applications), it should - * move the remainder data to the front part of the - * buffer and set the remainder length here. The value - * of this parameter will be ignored for datagram - * sockets. + * @param ssock The secure socket. + * @param data The buffer containing the new data, if any. If + * the status argument is non-PJ_SUCCESS, this + * argument may be NULL. + * @param size The length of data in the buffer. + * @param status The status of the read operation. This may contain + * non-PJ_SUCCESS for example when the TCP connection + * has been closed. In this case, the buffer may + * contain left over data from previous callback which + * the application may want to process. + * @param remainder If application wishes to leave some data in the + * buffer (common for TCP applications), it should + * move the remainder data to the front part of the + * buffer and set the remainder length here. The value + * of this parameter will be ignored for datagram + * sockets. * - * @return PJ_TRUE if further read is desired, and PJ_FALSE - * when application no longer wants to receive data. - * Application may destroy the secure socket in the - * callback and return PJ_FALSE here. + * @return PJ_TRUE if further read is desired, and PJ_FALSE + * when application no longer wants to receive data. + * Application may destroy the secure socket in the + * callback and return PJ_FALSE here. */ pj_bool_t (*on_data_read)(pj_ssl_sock_t *ssock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder); + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder); /** * This callback is called when a packet arrives as the result of * pj_ssl_sock_start_recvfrom(). * - * @param ssock The secure socket. - * @param data The buffer containing the packet, if any. If - * the status argument is non-PJ_SUCCESS, this - * argument will be set to NULL. - * @param size The length of packet in the buffer. If - * the status argument is non-PJ_SUCCESS, this - * argument will be set to zero. - * @param src_addr Source address of the packet. - * @param addr_len Length of the source address. - * @param status This contains + * @param ssock The secure socket. + * @param data The buffer containing the packet, if any. If + * the status argument is non-PJ_SUCCESS, this + * argument will be set to NULL. + * @param size The length of packet in the buffer. If + * the status argument is non-PJ_SUCCESS, this + * argument will be set to zero. + * @param src_addr Source address of the packet. + * @param addr_len Length of the source address. + * @param status This contains * - * @return PJ_TRUE if further read is desired, and PJ_FALSE - * when application no longer wants to receive data. - * Application may destroy the secure socket in the - * callback and return PJ_FALSE here. + * @return PJ_TRUE if further read is desired, and PJ_FALSE + * when application no longer wants to receive data. + * Application may destroy the secure socket in the + * callback and return PJ_FALSE here. */ pj_bool_t (*on_data_recvfrom)(pj_ssl_sock_t *ssock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status); + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status); /** * This callback is called when data has been sent. * - * @param ssock The secure socket. - * @param send_key Key associated with the send operation. - * @param sent If value is positive non-zero it indicates the - * number of data sent. When the value is negative, - * it contains the error code which can be retrieved - * by negating the value (i.e. status=-sent). + * @param ssock The secure socket. + * @param send_key Key associated with the send operation. + * @param sent If value is positive non-zero it indicates the + * number of data sent. When the value is negative, + * it contains the error code which can be retrieved + * by negating the value (i.e. status=-sent). * - * @return Application may destroy the secure socket in the - * callback and return PJ_FALSE here. + * @return Application may destroy the secure socket in the + * callback and return PJ_FALSE here. */ pj_bool_t (*on_data_sent)(pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent); + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent); /** * This callback is called when new connection arrives as the result * of pj_ssl_sock_start_accept(). If the status of accept operation is * needed use on_accept_complete2 instead of this callback. * - * @param ssock The secure socket. - * @param newsock The new incoming secure socket. - * @param src_addr The source address of the connection. - * @param addr_len Length of the source address. + * @param ssock The secure socket. + * @param newsock The new incoming secure socket. + * @param src_addr The source address of the connection. + * @param addr_len Length of the source address. * - * @return PJ_TRUE if further accept() is desired, and PJ_FALSE - * when application no longer wants to accept incoming - * connection. Application may destroy the secure socket - * in the callback and return PJ_FALSE here. + * @return PJ_TRUE if further accept() is desired, and PJ_FALSE + * when application no longer wants to accept incoming + * connection. Application may destroy the secure socket + * in the callback and return PJ_FALSE here. */ pj_bool_t (*on_accept_complete)(pj_ssl_sock_t *ssock, - pj_ssl_sock_t *newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len); + pj_ssl_sock_t *newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len); /** * This callback is called when new connection arrives as the result * of pj_ssl_sock_start_accept(). * - * @param asock The active socket. - * @param newsock The new incoming socket. - * @param src_addr The source address of the connection. - * @param addr_len Length of the source address. - * @param status The status of the accept operation. This may contain - * non-PJ_SUCCESS for example when the TCP listener is in - * bad state for example on iOS platform after the - * application waking up from background. + * @param asock The active socket. + * @param newsock The new incoming socket. + * @param src_addr The source address of the connection. + * @param addr_len Length of the source address. + * @param status The status of the accept operation. This may contain + * non-PJ_SUCCESS for example when the TCP listener is in + * bad state for example on iOS platform after the + * application waking up from background. * - * @return PJ_TRUE if further accept() is desired, and PJ_FALSE - * when application no longer wants to accept incoming - * connection. Application may destroy the active socket - * in the callback and return PJ_FALSE here. + * @return PJ_TRUE if further accept() is desired, and PJ_FALSE + * when application no longer wants to accept incoming + * connection. Application may destroy the active socket + * in the callback and return PJ_FALSE here. */ pj_bool_t (*on_accept_complete2)(pj_ssl_sock_t *ssock, - pj_ssl_sock_t *newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len, - pj_status_t status); + pj_ssl_sock_t *newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len, + pj_status_t status); /** * This callback is called when pending connect operation has been * completed. * - * @param ssock The secure socket. - * @param status The connection result. If connection has been - * successfully established, the status will contain - * PJ_SUCCESS. + * @param ssock The secure socket. + * @param status The connection result. If connection has been + * successfully established, the status will contain + * PJ_SUCCESS. * - * @return Application may destroy the secure socket in the - * callback and return PJ_FALSE here. + * @return Application may destroy the secure socket in the + * callback and return PJ_FALSE here. */ pj_bool_t (*on_connect_complete)(pj_ssl_sock_t *ssock, - pj_status_t status); + pj_status_t status); /** * This callback is called when certificate verification is being done. * Certification info can be obtained from #pj_ssl_sock_info. Currently * it's only implemented for OpenSSL backend. * - * @param ssock The secure socket. - * @param is_server PJ_TRUE to indicate an incoming connection. + * @param ssock The secure socket. + * @param is_server PJ_TRUE to indicate an incoming connection. * - * @return Return PJ_TRUE if verification is successful. + * @return Return PJ_TRUE if verification is successful. * If verification failed, then the connection will be - * dropped immediately. + * dropped immediately. * */ pj_bool_t (*on_verify_cb)(pj_ssl_sock_t *ssock, pj_bool_t is_server); @@ -708,17 +707,17 @@ typedef enum pj_ssl_sock_proto PJ_SSL_SOCK_PROTO_DEFAULT = 0, /** - * SSLv2.0 protocol. + * SSLv2.0 protocol. */ PJ_SSL_SOCK_PROTO_SSL2 = (1 << 0), /** - * SSLv3.0 protocol. + * SSLv3.0 protocol. */ PJ_SSL_SOCK_PROTO_SSL3 = (1 << 1), /** - * TLSv1.0 protocol. + * TLSv1.0 protocol. */ PJ_SSL_SOCK_PROTO_TLS1 = (1 << 2), @@ -745,7 +744,7 @@ typedef enum pj_ssl_sock_proto PJ_SSL_SOCK_PROTO_ALL = PJ_SSL_SOCK_PROTO_SSL23, /** - * DTLSv1.0 protocol. + * DTLSv1.0 protocol. */ PJ_SSL_SOCK_PROTO_DTLS1 = (1 << 16), @@ -798,12 +797,12 @@ typedef struct pj_ssl_sock_info /** * Status of peer certificate verification. */ - pj_uint32_t verify_status; + pj_uint32_t verify_status; /** * Last native error returned by the backend. */ - unsigned long last_native_err; + unsigned long last_native_err; /** * Group lock assigned to the ioqueue key. @@ -975,7 +974,7 @@ typedef struct pj_ssl_sock_param * Algorithms are: "MD5", "SHA1", "SHA224", "SHA256", "SHA384", "SHA512" * Example: "ECDSA+SHA256:RSA+SHA256" */ - pj_str_t sigalgs; + pj_str_t sigalgs; /** * Reseed random number generator. @@ -986,7 +985,7 @@ typedef struct pj_ssl_sock_param * * Default value is PJ_SSL_ENTROPY_NONE. */ - pj_ssl_entropy_t entropy_type; + pj_ssl_entropy_t entropy_type; /** * When using a file/socket for entropy #PJ_SSL_ENTROPY_EGD or @@ -995,7 +994,7 @@ typedef struct pj_ssl_sock_param * * Default value is an empty string. */ - pj_str_t entropy_path; + pj_str_t entropy_path; /** * Security negotiation timeout. If this is set to zero (both sec and @@ -1003,7 +1002,7 @@ typedef struct pj_ssl_sock_param * * Default value is zero. */ - pj_time_val timeout; + pj_time_val timeout; /** * Specify whether endpoint should verify peer certificate. @@ -1124,7 +1123,7 @@ typedef struct pj_ssl_start_connect_param { * Initialize the secure socket parameters for its creation with * the default values. * - * @param param The parameter to be initialized. + * @param param The parameter to be initialized. */ PJ_DECL(void) pj_ssl_sock_param_default(pj_ssl_sock_param *param); @@ -1132,27 +1131,27 @@ PJ_DECL(void) pj_ssl_sock_param_default(pj_ssl_sock_param *param); /** * Duplicate pj_ssl_sock_param. * - * @param pool Pool to allocate memory. - * @param dst Destination parameter. - * @param src Source parameter. + * @param pool Pool to allocate memory. + * @param dst Destination parameter. + * @param src Source parameter. */ PJ_DECL(void) pj_ssl_sock_param_copy(pj_pool_t *pool, - pj_ssl_sock_param *dst, - const pj_ssl_sock_param *src); + pj_ssl_sock_param *dst, + const pj_ssl_sock_param *src); /** * Create secure socket instance. * - * @param pool The pool for allocating secure socket instance. - * @param param The secure socket parameter, see #pj_ssl_sock_param. - * @param p_ssock Pointer to secure socket instance to be created. + * @param pool The pool for allocating secure socket instance. + * @param param The secure socket parameter, see #pj_ssl_sock_param. + * @param p_ssock Pointer to secure socket instance to be created. * - * @return PJ_SUCCESS when successful. + * @return PJ_SUCCESS when successful. */ PJ_DECL(pj_status_t) pj_ssl_sock_create(pj_pool_t *pool, - const pj_ssl_sock_param *param, - pj_ssl_sock_t **p_ssock); + const pj_ssl_sock_param *param, + pj_ssl_sock_t **p_ssock); /** @@ -1162,27 +1161,27 @@ PJ_DECL(pj_status_t) pj_ssl_sock_create(pj_pool_t *pool, * Socket client may also need to provide certificate in case requested * by the server. * - * @param ssock The secure socket instance. - * @param pool The pool. - * @param cert The endpoint certificate/credentials, see - * #pj_ssl_cert_t. + * @param ssock The secure socket instance. + * @param pool The pool. + * @param cert The endpoint certificate/credentials, see + * #pj_ssl_cert_t. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_ssl_sock_set_certificate( - pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_ssl_cert_t *cert); + pj_ssl_sock_t *ssock, + pj_pool_t *pool, + const pj_ssl_cert_t *cert); /** * Close and destroy the secure socket. * - * @param ssock The secure socket. + * @param ssock The secure socket. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_ssl_sock_close(pj_ssl_sock_t *ssock); @@ -1192,23 +1191,23 @@ PJ_DECL(pj_status_t) pj_ssl_sock_close(pj_ssl_sock_t *ssock); * inspect this data in the callbacks and associate it with higher * level processing. * - * @param ssock The secure socket. - * @param user_data The user data to be associated with the secure - * socket. + * @param ssock The secure socket. + * @param user_data The user data to be associated with the secure + * socket. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_ssl_sock_set_user_data(pj_ssl_sock_t *ssock, - void *user_data); + void *user_data); /** * Retrieve the user data previously associated with this secure * socket. * - * @param ssock The secure socket. + * @param ssock The secure socket. * - * @return The user data. + * @return The user data. */ PJ_DECL(void*) pj_ssl_sock_get_user_data(pj_ssl_sock_t *ssock); @@ -1216,13 +1215,13 @@ PJ_DECL(void*) pj_ssl_sock_get_user_data(pj_ssl_sock_t *ssock); /** * Retrieve the local address and port used by specified secure socket. * - * @param ssock The secure socket. - * @param info The info buffer to be set, see #pj_ssl_sock_info. + * @param ssock The secure socket. + * @param info The info buffer to be set, see #pj_ssl_sock_info. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pj_ssl_sock_get_info(pj_ssl_sock_t *ssock, - pj_ssl_sock_info *info); + pj_ssl_sock_info *info); /** @@ -1239,131 +1238,131 @@ PJ_DECL(pj_status_t) pj_ssl_sock_get_info(pj_ssl_sock_t *ssock, * operations. Further read operations will be done automatically by the * secure socket when \a on_data_read() callback returns non-zero. * - * @param ssock The secure socket. - * @param pool Pool used to allocate buffers for incoming data. - * @param buff_size The size of each buffer, in bytes. - * @param flags Flags to be given to pj_ioqueue_recv(). + * @param ssock The secure socket. + * @param pool Pool used to allocate buffers for incoming data. + * @param buff_size The size of each buffer, in bytes. + * @param flags Flags to be given to pj_ioqueue_recv(). * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_ssl_sock_start_read(pj_ssl_sock_t *ssock, - pj_pool_t *pool, - unsigned buff_size, - pj_uint32_t flags); + pj_pool_t *pool, + unsigned buff_size, + pj_uint32_t flags); /** * Same as #pj_ssl_sock_start_read(), except that the application * supplies the buffers for the read operation so that the acive socket * does not have to allocate the buffers. * - * @param ssock The secure socket. - * @param pool Pool used to allocate buffers for incoming data. - * @param buff_size The size of each buffer, in bytes. - * @param readbuf Array of packet buffers, each has buff_size size. - * @param flags Flags to be given to pj_ioqueue_recv(). + * @param ssock The secure socket. + * @param pool Pool used to allocate buffers for incoming data. + * @param buff_size The size of each buffer, in bytes. + * @param readbuf Array of packet buffers, each has buff_size size. + * @param flags Flags to be given to pj_ioqueue_recv(). * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_ssl_sock_start_read2(pj_ssl_sock_t *ssock, - pj_pool_t *pool, - unsigned buff_size, - void *readbuf[], - pj_uint32_t flags); + pj_pool_t *pool, + unsigned buff_size, + void *readbuf[], + pj_uint32_t flags); /** * Same as pj_ssl_sock_start_read(), except that this function is used * only for datagram sockets, and it will trigger \a on_data_recvfrom() * callback instead. * - * @param ssock The secure socket. - * @param pool Pool used to allocate buffers for incoming data. - * @param buff_size The size of each buffer, in bytes. - * @param flags Flags to be given to pj_ioqueue_recvfrom(). + * @param ssock The secure socket. + * @param pool Pool used to allocate buffers for incoming data. + * @param buff_size The size of each buffer, in bytes. + * @param flags Flags to be given to pj_ioqueue_recvfrom(). * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_ssl_sock_start_recvfrom(pj_ssl_sock_t *ssock, - pj_pool_t *pool, - unsigned buff_size, - pj_uint32_t flags); + pj_pool_t *pool, + unsigned buff_size, + pj_uint32_t flags); /** * Same as #pj_ssl_sock_start_recvfrom() except that the recvfrom() * operation takes the buffer from the argument rather than creating * new ones. * - * @param ssock The secure socket. - * @param pool Pool used to allocate buffers for incoming data. - * @param buff_size The size of each buffer, in bytes. - * @param readbuf Array of packet buffers, each has buff_size size. - * @param flags Flags to be given to pj_ioqueue_recvfrom(). + * @param ssock The secure socket. + * @param pool Pool used to allocate buffers for incoming data. + * @param buff_size The size of each buffer, in bytes. + * @param readbuf Array of packet buffers, each has buff_size size. + * @param flags Flags to be given to pj_ioqueue_recvfrom(). * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_ssl_sock_start_recvfrom2(pj_ssl_sock_t *ssock, - pj_pool_t *pool, - unsigned buff_size, - void *readbuf[], - pj_uint32_t flags); + pj_pool_t *pool, + unsigned buff_size, + void *readbuf[], + pj_uint32_t flags); /** * Send data using the socket. * - * @param ssock The secure socket. - * @param send_key The operation key to send the data, which is useful - * if application wants to submit multiple pending - * send operations and want to track which exact data - * has been sent in the \a on_data_sent() callback. - * @param data The data to be sent. This data must remain valid - * until the data has been sent. - * @param size The size of the data. - * @param flags Flags to be given to pj_ioqueue_send(). - * - * @return PJ_SUCCESS if data has been sent immediately, or - * PJ_EPENDING if data cannot be sent immediately or - * PJ_ENOMEM when sending buffer could not handle all - * queued data, see \a send_buffer_size. The callback - * \a on_data_sent() will be called when data is actually - * sent. Any other return value indicates error condition. + * @param ssock The secure socket. + * @param send_key The operation key to send the data, which is useful + * if application wants to submit multiple pending + * send operations and want to track which exact data + * has been sent in the \a on_data_sent() callback. + * @param data The data to be sent. This data must remain valid + * until the data has been sent. + * @param size The size of the data. + * @param flags Flags to be given to pj_ioqueue_send(). + * + * @return PJ_SUCCESS if data has been sent immediately, or + * PJ_EPENDING if data cannot be sent immediately or + * PJ_ENOMEM when sending buffer could not handle all + * queued data, see \a send_buffer_size. The callback + * \a on_data_sent() will be called when data is actually + * sent. Any other return value indicates error condition. */ PJ_DECL(pj_status_t) pj_ssl_sock_send(pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t *size, - unsigned flags); + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t *size, + unsigned flags); /** * Send datagram using the socket. * - * @param ssock The secure socket. - * @param send_key The operation key to send the data, which is useful - * if application wants to submit multiple pending - * send operations and want to track which exact data - * has been sent in the \a on_data_sent() callback. - * @param data The data to be sent. This data must remain valid - * until the data has been sent. - * @param size The size of the data. - * @param flags Flags to be given to pj_ioqueue_send(). - * @param addr The destination address. - * @param addr_len Length of buffer containing destination address. - * - * @return PJ_SUCCESS if data has been sent immediately, or - * PJ_EPENDING if data cannot be sent immediately. In - * this case the \a on_data_sent() callback will be - * called when data is actually sent. Any other return - * value indicates error condition. + * @param ssock The secure socket. + * @param send_key The operation key to send the data, which is useful + * if application wants to submit multiple pending + * send operations and want to track which exact data + * has been sent in the \a on_data_sent() callback. + * @param data The data to be sent. This data must remain valid + * until the data has been sent. + * @param size The size of the data. + * @param flags Flags to be given to pj_ioqueue_send(). + * @param addr The destination address. + * @param addr_len Length of buffer containing destination address. + * + * @return PJ_SUCCESS if data has been sent immediately, or + * PJ_EPENDING if data cannot be sent immediately. In + * this case the \a on_data_sent() callback will be + * called when data is actually sent. Any other return + * value indicates error condition. */ PJ_DECL(pj_status_t) pj_ssl_sock_sendto(pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t *size, - unsigned flags, - const pj_sockaddr_t *addr, - int addr_len); + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t *size, + unsigned flags, + const pj_sockaddr_t *addr, + int addr_len); /** @@ -1377,19 +1376,19 @@ PJ_DECL(pj_status_t) pj_ssl_sock_sendto(pj_ssl_sock_t *ssock, * operations. Further accept() operations will be done automatically by * the secure socket when \a on_accept_complete() callback returns non-zero. * - * @param ssock The secure socket. - * @param pool Pool used to allocate some internal data for the - * operation. - * @param local_addr Local address to bind on. - * @param addr_len Length of buffer containing local address. + * @param ssock The secure socket. + * @param pool Pool used to allocate some internal data for the + * operation. + * @param local_addr Local address to bind on. + * @param addr_len Length of buffer containing local address. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_ssl_sock_start_accept(pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_sockaddr_t *local_addr, - int addr_len); + pj_pool_t *pool, + const pj_sockaddr_t *local_addr, + int addr_len); /** @@ -1398,22 +1397,22 @@ PJ_DECL(pj_status_t) pj_ssl_sock_start_accept(pj_ssl_sock_t *ssock, * socket reported in \a on_accept_complete() callback when there is * an incoming connection. * - * @param ssock The secure socket. - * @param pool Pool used to allocate some internal data for the - * operation. - * @param local_addr Local address to bind on. - * @param addr_len Length of buffer containing local address. - * @param newsock_param Secure socket parameter for new accepted sockets. + * @param ssock The secure socket. + * @param pool Pool used to allocate some internal data for the + * operation. + * @param local_addr Local address to bind on. + * @param addr_len Length of buffer containing local address. + * @param newsock_param Secure socket parameter for new accepted sockets. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_ssl_sock_start_accept2(pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_sockaddr_t *local_addr, - int addr_len, - const pj_ssl_sock_param *newsock_param); + pj_pool_t *pool, + const pj_sockaddr_t *local_addr, + int addr_len, + const pj_ssl_sock_param *newsock_param); /** @@ -1421,43 +1420,43 @@ pj_ssl_sock_start_accept2(pj_ssl_sock_t *ssock, * for this socket. Once the connection is done (either successfully or not), * the \a on_connect_complete() callback will be called. * - * @param ssock The secure socket. - * @param pool The pool to allocate some internal data for the - * operation. - * @param localaddr Local address. - * @param remaddr Remote address. - * @param addr_len Length of buffer containing above addresses. - * - * @return PJ_SUCCESS if connection can be established immediately - * or PJ_EPENDING if connection cannot be established - * immediately. In this case the \a on_connect_complete() - * callback will be called when connection is complete. - * Any other return value indicates error condition. + * @param ssock The secure socket. + * @param pool The pool to allocate some internal data for the + * operation. + * @param localaddr Local address. + * @param remaddr Remote address. + * @param addr_len Length of buffer containing above addresses. + * + * @return PJ_SUCCESS if connection can be established immediately + * or PJ_EPENDING if connection cannot be established + * immediately. In this case the \a on_connect_complete() + * callback will be called when connection is complete. + * Any other return value indicates error condition. */ PJ_DECL(pj_status_t) pj_ssl_sock_start_connect(pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_sockaddr_t *localaddr, - const pj_sockaddr_t *remaddr, - int addr_len); + pj_pool_t *pool, + const pj_sockaddr_t *localaddr, + const pj_sockaddr_t *remaddr, + int addr_len); /** * Same as #pj_ssl_sock_start_connect(), but application can provide a * \a port_range parameter, which will be used to bind the socket to * random port. * - * @param ssock The secure socket. + * @param ssock The secure socket. * * @param connect_param The parameter, refer to \a pj_ssl_start_connect_param. * - * @return PJ_SUCCESS if connection can be established immediately - * or PJ_EPENDING if connection cannot be established - * immediately. In this case the \a on_connect_complete() - * callback will be called when connection is complete. - * Any other return value indicates error condition. + * @return PJ_SUCCESS if connection can be established immediately + * or PJ_EPENDING if connection cannot be established + * immediately. In this case the \a on_connect_complete() + * callback will be called when connection is complete. + * Any other return value indicates error condition. */ PJ_DECL(pj_status_t) pj_ssl_sock_start_connect2( - pj_ssl_sock_t *ssock, - pj_ssl_start_connect_param *connect_param); + pj_ssl_sock_t *ssock, + pj_ssl_start_connect_param *connect_param); /** * Starts SSL/TLS renegotiation over an already established SSL connection @@ -1466,12 +1465,12 @@ PJ_DECL(pj_status_t) pj_ssl_sock_start_connect2( * when the renegotiation fails, the connection will be closed and callback * \a on_data_read() will be invoked with non-PJ_SUCCESS status code. * - * @param ssock The secure socket. + * @param ssock The secure socket. * - * @return PJ_SUCCESS if renegotiation is completed immediately, - * or PJ_EPENDING if renegotiation has been started and - * waiting for completion, or the appropriate error code - * on failure. + * @return PJ_SUCCESS if renegotiation is completed immediately, + * or PJ_EPENDING if renegotiation has been started and + * waiting for completion, or the appropriate error code + * on failure. */ PJ_DECL(pj_status_t) pj_ssl_sock_renegotiate(pj_ssl_sock_t *ssock); @@ -1481,4 +1480,4 @@ PJ_DECL(pj_status_t) pj_ssl_sock_renegotiate(pj_ssl_sock_t *ssock); PJ_END_DECL -#endif /* __PJ_SSL_SOCK_H__ */ +#endif /* __PJ_SSL_SOCK_H__ */ diff --git a/pjlib/include/pj/string.h b/pjlib/include/pj/string.h index e34a3337ad..eed1632a41 100644 --- a/pjlib/include/pj/string.h +++ b/pjlib/include/pj/string.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -74,9 +73,9 @@ PJ_BEGIN_DECL * to indicate the truncation. * This macro is used to check the result of pj_ansi_snprintf(). * - * @param ret The return value of pj_ansi_snprintf(). - * @param str The string. - * @param len The length of the string buffer. + * @param ret The return value of pj_ansi_snprintf(). + * @param str The string. + * @param len The length of the string buffer. */ #define PJ_CHECK_TRUNC_STR(ret, str, len) \ if ((ret) >= (len) || (ret) < 0) pj_ansi_strcpy((str) + (len) - 3, "..") @@ -84,19 +83,19 @@ PJ_BEGIN_DECL /** * Create string initializer from a normal C string. * - * @param str Null terminated string to be stored. + * @param str Null terminated string to be stored. * - * @return pj_str_t. + * @return pj_str_t. */ PJ_IDECL(pj_str_t) pj_str(char *str); /** * Create constant string from normal C string. * - * @param str The string to be initialized. - * @param s Null terminated string. + * @param str The string to be initialized. + * @param s Null terminated string. * - * @return pj_str_t. + * @return pj_str_t. */ PJ_INLINE(const pj_str_t*) pj_cstr(pj_str_t *str, const char *s) { @@ -108,8 +107,8 @@ PJ_INLINE(const pj_str_t*) pj_cstr(pj_str_t *str, const char *s) /** * Set the pointer and length to the specified value. * - * @param str the string. - * @param ptr pointer to set. + * @param str the string. + * @param ptr pointer to set. * @param length length to set. * * @return the string. @@ -125,8 +124,8 @@ PJ_INLINE(pj_str_t*) pj_strset( pj_str_t *str, char *ptr, pj_size_t length) * Set the pointer and length of the string to the source string, which * must be NULL terminated. * - * @param str the string. - * @param src pointer to set. + * @param str the string. + * @param src pointer to set. * * @return the string. */ @@ -140,9 +139,9 @@ PJ_INLINE(pj_str_t*) pj_strset2( pj_str_t *str, char *src) /** * Set the pointer and the length of the string. * - * @param str The target string. - * @param begin The start of the string. - * @param end The end of the string. + * @param str The target string. + * @param begin The start of the string. + * @param end The end of the string. * * @return the target string. */ @@ -156,8 +155,8 @@ PJ_INLINE(pj_str_t*) pj_strset3( pj_str_t *str, char *begin, char *end ) /** * Assign string. * - * @param dst The target string. - * @param src The source string. + * @param dst The target string. + * @param src The source string. * * @return the target string. */ @@ -166,8 +165,8 @@ PJ_IDECL(pj_str_t*) pj_strassign( pj_str_t *dst, pj_str_t *src ); /** * Copy string contents. * - * @param dst The target string. - * @param src The source string. + * @param dst The target string. + * @param src The source string. * * @return the target string. */ @@ -176,8 +175,8 @@ PJ_IDECL(pj_str_t*) pj_strcpy(pj_str_t *dst, const pj_str_t *src); /** * Copy string contents. * - * @param dst The target string. - * @param src The source string. + * @param dst The target string. + * @param src The source string. * * @return the target string. */ @@ -186,87 +185,87 @@ PJ_IDECL(pj_str_t*) pj_strcpy2(pj_str_t *dst, const char *src); /** * Copy source string to destination up to the specified max length. * - * @param dst The target string. - * @param src The source string. - * @param max Maximum characters to copy. + * @param dst The target string. + * @param src The source string. + * @param max Maximum characters to copy. * * @return the target string. */ PJ_IDECL(pj_str_t*) pj_strncpy(pj_str_t *dst, const pj_str_t *src, - pj_ssize_t max); + pj_ssize_t max); /** * Copy source string to destination up to the specified max length, * and NULL terminate the destination. If source string length is * greater than or equal to max, then max-1 will be copied. * - * @param dst The target string. - * @param src The source string. - * @param max Maximum characters to copy. + * @param dst The target string. + * @param src The source string. + * @param max Maximum characters to copy. * * @return the target string. */ PJ_IDECL(pj_str_t*) pj_strncpy_with_null(pj_str_t *dst, const pj_str_t *src, - pj_ssize_t max); + pj_ssize_t max); /** * Duplicate string. * - * @param pool The pool. - * @param dst The string result. - * @param src The string to duplicate. + * @param pool The pool. + * @param dst The string result. + * @param src The string to duplicate. * * @return the string result. */ PJ_IDECL(pj_str_t*) pj_strdup(pj_pool_t *pool, - pj_str_t *dst, - const pj_str_t *src); + pj_str_t *dst, + const pj_str_t *src); /** * Duplicate string and NULL terminate the destination string. * - * @param pool The pool. - * @param dst The string result. - * @param src The string to duplicate. + * @param pool The pool. + * @param dst The string result. + * @param src The string to duplicate. * - * @return The string result. + * @return The string result. */ PJ_IDECL(pj_str_t*) pj_strdup_with_null(pj_pool_t *pool, - pj_str_t *dst, - const pj_str_t *src); + pj_str_t *dst, + const pj_str_t *src); /** * Duplicate string. * - * @param pool The pool. - * @param dst The string result. - * @param src The string to duplicate. + * @param pool The pool. + * @param dst The string result. + * @param src The string to duplicate. * * @return the string result. */ PJ_IDECL(pj_str_t*) pj_strdup2(pj_pool_t *pool, - pj_str_t *dst, - const char *src); + pj_str_t *dst, + const char *src); /** * Duplicate string and NULL terminate the destination string. * - * @param pool The pool. - * @param dst The string result. - * @param src The string to duplicate. + * @param pool The pool. + * @param dst The string result. + * @param src The string to duplicate. * - * @return The string result. + * @return The string result. */ PJ_IDECL(pj_str_t*) pj_strdup2_with_null(pj_pool_t *pool, - pj_str_t *dst, - const char *src); + pj_str_t *dst, + const char *src); /** * Duplicate string. * - * @param pool The pool. - * @param src The string to duplicate. + * @param pool The pool. + * @param src The string to duplicate. * * @return the string result. */ @@ -275,7 +274,7 @@ PJ_IDECL(pj_str_t) pj_strdup3(pj_pool_t *pool, const char *src); /** * Return the length of the string. * - * @param str The string. + * @param str The string. * * @return the length of the string. */ @@ -287,7 +286,7 @@ PJ_INLINE(pj_size_t) pj_strlen( const pj_str_t *str ) /** * Return the pointer to the string data. * - * @param str The string. + * @param str The string. * * @return the pointer to the string buffer. */ @@ -299,11 +298,11 @@ PJ_INLINE(const char*) pj_strbuf( const pj_str_t *str ) /** * Compare strings. * - * @param str1 The string to compare. - * @param str2 The string to compare. + * @param str1 The string to compare. + * @param str2 The string to compare. * * @return - * - < 0 if str1 is less than str2 + * - < 0 if str1 is less than str2 * - 0 if str1 is identical to str2 * - > 0 if str1 is greater than str2 */ @@ -312,11 +311,11 @@ PJ_IDECL(int) pj_strcmp( const pj_str_t *str1, const pj_str_t *str2); /** * Compare strings. * - * @param str1 The string to compare. - * @param str2 The string to compare. + * @param str1 The string to compare. + * @param str2 The string to compare. * * @return - * - < 0 if str1 is less than str2 + * - < 0 if str1 is less than str2 * - 0 if str1 is identical to str2 * - > 0 if str1 is greater than str2 */ @@ -325,41 +324,41 @@ PJ_IDECL(int) pj_strcmp2( const pj_str_t *str1, const char *str2 ); /** * Compare strings. * - * @param str1 The string to compare. - * @param str2 The string to compare. - * @param len The maximum number of characters to compare. + * @param str1 The string to compare. + * @param str2 The string to compare. + * @param len The maximum number of characters to compare. * * @return - * - < 0 if str1 is less than str2 + * - < 0 if str1 is less than str2 * - 0 if str1 is identical to str2 * - > 0 if str1 is greater than str2 */ PJ_IDECL(int) pj_strncmp( const pj_str_t *str1, const pj_str_t *str2, - pj_size_t len); + pj_size_t len); /** * Compare strings. * - * @param str1 The string to compare. - * @param str2 The string to compare. - * @param len The maximum number of characters to compare. + * @param str1 The string to compare. + * @param str2 The string to compare. + * @param len The maximum number of characters to compare. * * @return - * - < 0 if str1 is less than str2 + * - < 0 if str1 is less than str2 * - 0 if str1 is identical to str2 * - > 0 if str1 is greater than str2 */ PJ_IDECL(int) pj_strncmp2( const pj_str_t *str1, const char *str2, - pj_size_t len); + pj_size_t len); /** * Perform case-insensitive comparison to the strings. * - * @param str1 The string to compare. - * @param str2 The string to compare. + * @param str1 The string to compare. + * @param str2 The string to compare. * * @return - * - < 0 if str1 is less than str2 + * - < 0 if str1 is less than str2 * - 0 if str1 is equal to str2 * - > 0 if str1 is greater than str2 */ @@ -373,19 +372,19 @@ PJ_IDECL(int) pj_stricmp(const pj_str_t *str1, const pj_str_t *str2); * If non-alnum inputs are given, then the function may mistakenly * treat two strings as equal. * - * @param str1 The string to compare. - * @param str2 The string to compare. - * @param len The length to compare. + * @param str1 The string to compare. + * @param str2 The string to compare. + * @param len The length to compare. * * @return - * - 0 if str1 is equal to str2 - * - (-1) if not equal. + * - 0 if str1 is equal to str2 + * - (-1) if not equal. */ #if defined(PJ_HAS_STRICMP_ALNUM) && PJ_HAS_STRICMP_ALNUM!=0 PJ_IDECL(int) strnicmp_alnum(const char *str1, const char *str2, - int len); + int len); #else -#define strnicmp_alnum pj_ansi_strnicmp +#define strnicmp_alnum pj_ansi_strnicmp #endif /** @@ -396,12 +395,12 @@ PJ_IDECL(int) strnicmp_alnum(const char *str1, const char *str2, * If non-alnum inputs are given, then the function may mistakenly * treat two strings as equal. * - * @param str1 The string to compare. - * @param str2 The string to compare. + * @param str1 The string to compare. + * @param str2 The string to compare. * * @return - * - 0 if str1 is equal to str2 - * - (-1) if not equal. + * - 0 if str1 is equal to str2 + * - (-1) if not equal. */ #if defined(PJ_HAS_STRICMP_ALNUM) && PJ_HAS_STRICMP_ALNUM!=0 PJ_IDECL(int) pj_stricmp_alnum(const pj_str_t *str1, const pj_str_t *str2); @@ -412,11 +411,11 @@ PJ_IDECL(int) pj_stricmp_alnum(const pj_str_t *str1, const pj_str_t *str2); /** * Perform case-insensitive comparison to the strings. * - * @param str1 The string to compare. - * @param str2 The string to compare. + * @param str1 The string to compare. + * @param str2 The string to compare. * * @return - * - < 0 if str1 is less than str2 + * - < 0 if str1 is less than str2 * - 0 if str1 is identical to str2 * - > 0 if str1 is greater than str2 */ @@ -425,38 +424,38 @@ PJ_IDECL(int) pj_stricmp2( const pj_str_t *str1, const char *str2); /** * Perform case-insensitive comparison to the strings. * - * @param str1 The string to compare. - * @param str2 The string to compare. - * @param len The maximum number of characters to compare. + * @param str1 The string to compare. + * @param str2 The string to compare. + * @param len The maximum number of characters to compare. * * @return - * - < 0 if str1 is less than str2 + * - < 0 if str1 is less than str2 * - 0 if str1 is identical to str2 * - > 0 if str1 is greater than str2 */ PJ_IDECL(int) pj_strnicmp( const pj_str_t *str1, const pj_str_t *str2, - pj_size_t len); + pj_size_t len); /** * Perform case-insensitive comparison to the strings. * - * @param str1 The string to compare. - * @param str2 The string to compare. - * @param len The maximum number of characters to compare. + * @param str1 The string to compare. + * @param str2 The string to compare. + * @param len The maximum number of characters to compare. * * @return - * - < 0 if str1 is less than str2 + * - < 0 if str1 is less than str2 * - 0 if str1 is identical to str2 * - > 0 if str1 is greater than str2 */ PJ_IDECL(int) pj_strnicmp2( const pj_str_t *str1, const char *str2, - pj_size_t len); + pj_size_t len); /** * Concatenate strings. * - * @param dst The destination string. - * @param src The source string. + * @param dst The destination string. + * @param src The source string. */ PJ_IDECL(void) pj_strcat(pj_str_t *dst, const pj_str_t *src); @@ -464,8 +463,8 @@ PJ_IDECL(void) pj_strcat(pj_str_t *dst, const pj_str_t *src); /** * Concatenate strings. * - * @param dst The destination string. - * @param src The source string. + * @param dst The destination string. + * @param src The source string. */ PJ_IDECL(void) pj_strcat2(pj_str_t *dst, const char *src); @@ -473,15 +472,15 @@ PJ_IDECL(void) pj_strcat2(pj_str_t *dst, const char *src); /** * Finds a character in a string. * - * @param str The string. - * @param chr The character to find. + * @param str The string. + * @param chr The character to find. * * @return the pointer to first character found, or NULL. */ PJ_INLINE(char*) pj_strchr( const pj_str_t *str, int chr) { if (str->slen == 0) - return NULL; + return NULL; return (char*) memchr((char*)str->ptr, chr, str->slen); } @@ -490,7 +489,7 @@ PJ_INLINE(char*) pj_strchr( const pj_str_t *str, int chr) * Find the first index of character, in a string, that does not belong to a * set of characters. * - * @param str The string. + * @param str The string. * @param set_char The string containing the set of characters. * * @return the index of the first character in the str that doesn't belong to @@ -503,7 +502,7 @@ PJ_DECL(pj_ssize_t) pj_strspn(const pj_str_t *str, const pj_str_t *set_char); * Find the first index of character, in a string, that does not belong to a * set of characters. * - * @param str The string. + * @param str The string. * @param set_char The string containing the set of characters. * * @return the index of the first character in the str that doesn't belong to @@ -516,7 +515,7 @@ PJ_DECL(pj_ssize_t) pj_strspn2(const pj_str_t *str, const char *set_char); * Find the first index of character, in a string, that belong to a set of * characters. * - * @param str The string. + * @param str The string. * @param set_char The string containing the set of characters. * * @return the index of the first character in the str that belong to @@ -529,7 +528,7 @@ PJ_DECL(pj_ssize_t) pj_strcspn(const pj_str_t *str, const pj_str_t *set_char); * Find the first index of character, in a string, that belong to a set of * characters. * - * @param str The string. + * @param str The string. * @param set_char The string containing the set of characters. * * @return the index of the first character in the str that belong to @@ -541,41 +540,41 @@ PJ_DECL(pj_ssize_t) pj_strcspn2(const pj_str_t *str, const char *set_char); /** * Find tokens from a string using the delimiter. * - * @param str The string. - * @param delim The string containing the delimiter. It might contain - * multiple character treated as unique set. If same character - * was found on the set, it will be skipped. - * @param tok The string containing the token. + * @param str The string. + * @param delim The string containing the delimiter. It might contain + * multiple character treated as unique set. If same character + * was found on the set, it will be skipped. + * @param tok The string containing the token. * @param start_idx The search will start from this index. * * @return the index of token from the str, or the length of the str * if the token is not found. */ PJ_DECL(pj_ssize_t) pj_strtok(const pj_str_t *str, const pj_str_t *delim, - pj_str_t *tok, pj_size_t start_idx); + pj_str_t *tok, pj_size_t start_idx); /** * Find tokens from a string using the delimiter. * - * @param str The string. - * @param delim The string containing the delimiter. It might contain - * multiple character treated as unique set. If same character - * was found on the set, it will be skipped. - * @param tok The string containing the token. + * @param str The string. + * @param delim The string containing the delimiter. It might contain + * multiple character treated as unique set. If same character + * was found on the set, it will be skipped. + * @param tok The string containing the token. * @param start_idx The search will start from this index. * * @return the index of token from the str, or the length of the str * if the token is not found. */ PJ_DECL(pj_ssize_t) pj_strtok2(const pj_str_t *str, const char *delim, - pj_str_t *tok, pj_size_t start_idx); + pj_str_t *tok, pj_size_t start_idx); /** * Find the occurence of a substring substr in string str. * - * @param str The string to search. + * @param str The string to search. * @param substr The string to search fo. * * @return the pointer to the position of substr in str, or NULL. Note @@ -588,7 +587,7 @@ PJ_DECL(char*) pj_strstr(const pj_str_t *str, const pj_str_t *substr); * Performs substring lookup like pj_strstr() but ignores the case of * both strings. * - * @param str The string to search. + * @param str The string to search. * @param substr The string to search fo. * * @return the pointer to the position of substr in str, or NULL. Note @@ -600,7 +599,7 @@ PJ_DECL(char*) pj_stristr(const pj_str_t *str, const pj_str_t *substr); /** * Remove (trim) leading whitespaces from the string. * - * @param str The string. + * @param str The string. * * @return the string. */ @@ -609,7 +608,7 @@ PJ_DECL(pj_str_t*) pj_strltrim( pj_str_t *str ); /** * Remove (trim) the trailing whitespaces from the string. * - * @param str The string. + * @param str The string. * * @return the string. */ @@ -618,7 +617,7 @@ PJ_DECL(pj_str_t*) pj_strrtrim( pj_str_t *str ); /** * Remove (trim) leading and trailing whitespaces from the string. * - * @param str The string. + * @param str The string. * * @return the string. */ @@ -628,7 +627,7 @@ PJ_IDECL(pj_str_t*) pj_strtrim( pj_str_t *str ); * Initialize the buffer with some random string. Note that the * generated string is not NULL terminated. * - * @param str the string to store the result. + * @param str the string to store the result. * @param length the length of the random string to generate. * * @return the string. @@ -640,7 +639,7 @@ PJ_DECL(char*) pj_create_random_string(char *str, pj_size_t length); * soon as non-digit character is found or all the characters have * been processed. * - * @param str the string. + * @param str the string. * * @return the integer. */ @@ -674,7 +673,7 @@ PJ_DECL(pj_status_t) pj_strtol2(const pj_str_t *str, long *value); * soon as non-digit character is found or all the characters have * been processed. * - * @param str the string. + * @param str the string. * * @return the unsigned integer. */ @@ -687,15 +686,15 @@ PJ_DECL(unsigned long) pj_strtoul(const pj_str_t *str); * the first character it cannot recognize as part of a number, that is * a character greater than or equal to base. * - * @param str The input string. + * @param str The input string. * @param endptr Optional pointer to receive the remainder/unparsed - * portion of the input. - * @param base Number base to use. + * portion of the input. + * @param base Number base to use. * * @return the unsigned integer number. */ PJ_DECL(unsigned long) pj_strtoul2(const pj_str_t *str, pj_str_t *endptr, - unsigned base); + unsigned base); /** * Convert string to unsigned long integer. The conversion will stop as @@ -704,7 +703,7 @@ PJ_DECL(unsigned long) pj_strtoul2(const pj_str_t *str, pj_str_t *endptr, * * @param str The input string. * @param value Pointer to an unsigned long to receive the value. - * @param base Number base to use. + * @param base Number base to use. * * @return PJ_SUCCESS if successful. Otherwise: * PJ_ETOOBIG if the value was an impossibly long positive number. @@ -716,12 +715,12 @@ PJ_DECL(unsigned long) pj_strtoul2(const pj_str_t *str, pj_str_t *endptr, * *value will be left untouched. */ PJ_DECL(pj_status_t) pj_strtoul3(const pj_str_t *str, unsigned long *value, - unsigned base); + unsigned base); /** * Convert string to float. * - * @param str the string. + * @param str the string. * * @return the value. */ @@ -731,8 +730,8 @@ PJ_DECL(float) pj_strtof(const pj_str_t *str); * Utility to convert unsigned integer to string. Note that the * string will be NULL terminated. * - * @param val the unsigned integer value. - * @param buf the buffer + * @param val the unsigned integer value. + * @param buf the buffer * * @return the number of characters written */ @@ -742,12 +741,12 @@ PJ_DECL(int) pj_utoa(unsigned long val, char *buf); * Convert unsigned integer to string with minimum digits. Note that the * string will be NULL terminated. * - * @param val The unsigned integer value. - * @param buf The buffer. + * @param val The unsigned integer value. + * @param buf The buffer. * @param min_dig Minimum digits to be printed, or zero to specify no - * minimum digit. - * @param pad The padding character to be put in front of the string - * when the digits is less than minimum. + * minimum digit. + * @param pad The padding character to be put in front of the string + * when the digits is less than minimum. * * @return the number of characters written. */ @@ -757,8 +756,8 @@ PJ_DECL(int) pj_utoa_pad( unsigned long val, char *buf, int min_dig, int pad); /** * Fill the memory location with zero. * - * @param dst The destination buffer. - * @param size The number of bytes. + * @param dst The destination buffer. + * @param size The number of bytes. */ PJ_INLINE(void) pj_bzero(void *dst, pj_size_t size) { @@ -773,9 +772,9 @@ PJ_INLINE(void) pj_bzero(void *dst, pj_size_t size) /** * Fill the memory location with value. * - * @param dst The destination buffer. - * @param c Character to set. - * @param size The number of characters. + * @param dst The destination buffer. + * @param c Character to set. + * @param size The number of characters. * * @return the value of dst. */ @@ -787,9 +786,9 @@ PJ_INLINE(void*) pj_memset(void *dst, int c, pj_size_t size) /** * Copy buffer. * - * @param dst The destination buffer. - * @param src The source buffer. - * @param size The size to copy. + * @param dst The destination buffer. + * @param src The source buffer. + * @param size The size to copy. * * @return the destination buffer. */ @@ -801,9 +800,9 @@ PJ_INLINE(void*) pj_memcpy(void *dst, const void *src, pj_size_t size) /** * Move memory. * - * @param dst The destination buffer. - * @param src The source buffer. - * @param size The size to copy. + * @param dst The destination buffer. + * @param src The source buffer. + * @param size The size to copy. * * @return the destination buffer. */ @@ -815,9 +814,9 @@ PJ_INLINE(void*) pj_memmove(void *dst, const void *src, pj_size_t size) /** * Compare buffers. * - * @param buf1 The first buffer. - * @param buf2 The second buffer. - * @param size The size to compare. + * @param buf1 The first buffer. + * @param buf2 The second buffer. + * @param size The size to compare. * * @return negative, zero, or positive value. */ @@ -829,9 +828,9 @@ PJ_INLINE(int) pj_memcmp(const void *buf1, const void *buf2, pj_size_t size) /** * Find character in the buffer. * - * @param buf The buffer. - * @param c The character to find. - * @param size The size to check. + * @param buf The buffer. + * @param c The character to find. + * @param size The size to check. * * @return the pointer to location where the character is found, or NULL if * not found. @@ -851,5 +850,5 @@ PJ_INLINE(void*) pj_memchr(const void *buf, int c, pj_size_t size) PJ_END_DECL -#endif /* __PJ_STRING_H__ */ +#endif /* __PJ_STRING_H__ */ diff --git a/pjlib/include/pj/string_i.h b/pjlib/include/pj/string_i.h index 61cebfb7e0..bb2f769391 100644 --- a/pjlib/include/pj/string_i.h +++ b/pjlib/include/pj/string_i.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,26 +29,26 @@ PJ_IDEF(pj_str_t) pj_str(char *str) } PJ_IDEF(pj_str_t*) pj_strdup(pj_pool_t *pool, - pj_str_t *dst, - const pj_str_t *src) + pj_str_t *dst, + const pj_str_t *src) { pj_assert(src->slen >= 0); /* Without this, destination will be corrupted */ if (dst == src) - return dst; + return dst; if (src->slen > 0) { - dst->ptr = (char*)pj_pool_alloc(pool, src->slen); - pj_memcpy(dst->ptr, src->ptr, src->slen); + dst->ptr = (char*)pj_pool_alloc(pool, src->slen); + pj_memcpy(dst->ptr, src->ptr, src->slen); } dst->slen = (src->slen < 0)? 0: src->slen; return dst; } PJ_IDEF(pj_str_t*) pj_strdup_with_null( pj_pool_t *pool, - pj_str_t *dst, - const pj_str_t *src) + pj_str_t *dst, + const pj_str_t *src) { pj_size_t src_slen = src->slen; @@ -57,11 +56,11 @@ PJ_IDEF(pj_str_t*) pj_strdup_with_null( pj_pool_t *pool, /* Check if the source's length is invalid */ if (src_slen < 0) - src_slen = 0; + src_slen = 0; dst->ptr = (char*)pj_pool_alloc(pool, src_slen+1); if (src_slen) { - pj_memcpy(dst->ptr, src->ptr, src_slen); + pj_memcpy(dst->ptr, src->ptr, src_slen); } dst->slen = src_slen; dst->ptr[dst->slen] = '\0'; @@ -69,27 +68,27 @@ PJ_IDEF(pj_str_t*) pj_strdup_with_null( pj_pool_t *pool, } PJ_IDEF(pj_str_t*) pj_strdup2(pj_pool_t *pool, - pj_str_t *dst, - const char *src) + pj_str_t *dst, + const char *src) { dst->slen = src ? pj_ansi_strlen(src) : 0; if (dst->slen) { - dst->ptr = (char*)pj_pool_alloc(pool, dst->slen); - pj_memcpy(dst->ptr, src, dst->slen); + dst->ptr = (char*)pj_pool_alloc(pool, dst->slen); + pj_memcpy(dst->ptr, src, dst->slen); } else { - dst->ptr = NULL; + dst->ptr = NULL; } return dst; } PJ_IDEF(pj_str_t*) pj_strdup2_with_null( pj_pool_t *pool, - pj_str_t *dst, - const char *src) + pj_str_t *dst, + const char *src) { dst->slen = src ? pj_ansi_strlen(src) : 0; dst->ptr = (char*)pj_pool_alloc(pool, dst->slen+1); if (dst->slen) { - pj_memcpy(dst->ptr, src, dst->slen); + pj_memcpy(dst->ptr, src, dst->slen); } dst->ptr[dst->slen] = '\0'; return dst; @@ -115,7 +114,7 @@ PJ_IDEF(pj_str_t*) pj_strcpy(pj_str_t *dst, const pj_str_t *src) dst->slen = (src->slen < 0)? 0: src->slen; if (src->slen > 0) - pj_memcpy(dst->ptr, src->ptr, src->slen); + pj_memcpy(dst->ptr, src->ptr, src->slen); return dst; } @@ -123,36 +122,36 @@ PJ_IDEF(pj_str_t*) pj_strcpy2(pj_str_t *dst, const char *src) { dst->slen = src ? pj_ansi_strlen(src) : 0; if (dst->slen > 0) - pj_memcpy(dst->ptr, src, dst->slen); + pj_memcpy(dst->ptr, src, dst->slen); return dst; } PJ_IDEF(pj_str_t*) pj_strncpy( pj_str_t *dst, const pj_str_t *src, - pj_ssize_t max) + pj_ssize_t max) { pj_assert(src->slen >= 0); pj_assert(max >= 0); if (max > src->slen) max = src->slen; if (max > 0) - pj_memcpy(dst->ptr, src->ptr, max); + pj_memcpy(dst->ptr, src->ptr, max); dst->slen = (max < 0)? 0: max; return dst; } PJ_IDEF(pj_str_t*) pj_strncpy_with_null( pj_str_t *dst, const pj_str_t *src, - pj_ssize_t max) + pj_ssize_t max) { pj_assert(src->slen >= 0); pj_assert(max > 0); if (max <= src->slen) - max = (max > 0)? max-1: 0; + max = (max > 0)? max-1: 0; else - max = (src->slen < 0)? 0: src->slen; + max = (src->slen < 0)? 0: src->slen; if (max > 0) - pj_memcpy(dst->ptr, src->ptr, max); + pj_memcpy(dst->ptr, src->ptr, max); dst->ptr[max] = '\0'; dst->slen = max; return dst; @@ -165,23 +164,23 @@ PJ_IDEF(int) pj_strcmp( const pj_str_t *str1, const pj_str_t *str2) pj_assert(str2->slen >= 0); if (str1->slen <= 0) { - return str2->slen<=0 ? 0 : -1; + return str2->slen<=0 ? 0 : -1; } else if (str2->slen <= 0) { - return 1; + return 1; } else { - pj_size_t min = (str1->slen < str2->slen)? str1->slen : str2->slen; - int res = pj_memcmp(str1->ptr, str2->ptr, min); - if (res == 0) { - return (str1->slen < str2->slen) ? -1 : - (str1->slen == str2->slen ? 0 : 1); - } else { - return res; - } + pj_size_t min = (str1->slen < str2->slen)? str1->slen : str2->slen; + int res = pj_memcmp(str1->ptr, str2->ptr, min); + if (res == 0) { + return (str1->slen < str2->slen) ? -1 : + (str1->slen == str2->slen ? 0 : 1); + } else { + return res; + } } } PJ_IDEF(int) pj_strncmp( const pj_str_t *str1, const pj_str_t *str2, - pj_size_t len) + pj_size_t len) { pj_str_t copy1, copy2; @@ -189,30 +188,30 @@ PJ_IDEF(int) pj_strncmp( const pj_str_t *str1, const pj_str_t *str2, pj_assert(str2->slen >= 0); if (len < (unsigned)str1->slen && str1->slen > 0) { - copy1.ptr = str1->ptr; - copy1.slen = len; - str1 = ©1; + copy1.ptr = str1->ptr; + copy1.slen = len; + str1 = ©1; } if (len < (unsigned)str2->slen && str2->slen > 0) { - copy2.ptr = str2->ptr; - copy2.slen = len; - str2 = ©2; + copy2.ptr = str2->ptr; + copy2.slen = len; + str2 = ©2; } return pj_strcmp(str1, str2); } PJ_IDEF(int) pj_strncmp2( const pj_str_t *str1, const char *str2, - pj_size_t len) + pj_size_t len) { pj_str_t copy2; if (str2) { - copy2.ptr = (char*)str2; - copy2.slen = pj_ansi_strlen(str2); + copy2.ptr = (char*)str2; + copy2.slen = pj_ansi_strlen(str2); } else { - copy2.slen = 0; + copy2.slen = 0; } return pj_strncmp(str1, ©2, len); @@ -223,11 +222,11 @@ PJ_IDEF(int) pj_strcmp2( const pj_str_t *str1, const char *str2 ) pj_str_t copy2; if (str2) { - copy2.ptr = (char*)str2; - copy2.slen = pj_ansi_strlen(str2); + copy2.ptr = (char*)str2; + copy2.slen = pj_ansi_strlen(str2); } else { - copy2.ptr = NULL; - copy2.slen = 0; + copy2.ptr = NULL; + copy2.slen = 0; } return pj_strcmp(str1, ©2); @@ -239,52 +238,52 @@ PJ_IDEF(int) pj_stricmp( const pj_str_t *str1, const pj_str_t *str2) pj_assert(str2->slen >= 0); if (str1->slen <= 0) { - return str2->slen<=0 ? 0 : -1; + return str2->slen<=0 ? 0 : -1; } else if (str2->slen <= 0) { - return 1; + return 1; } else { - pj_size_t min = (str1->slen < str2->slen)? str1->slen : str2->slen; - int res = pj_ansi_strnicmp(str1->ptr, str2->ptr, min); - if (res == 0) { - return (str1->slen < str2->slen) ? -1 : - (str1->slen == str2->slen ? 0 : 1); - } else { - return res; - } + pj_size_t min = (str1->slen < str2->slen)? str1->slen : str2->slen; + int res = pj_ansi_strnicmp(str1->ptr, str2->ptr, min); + if (res == 0) { + return (str1->slen < str2->slen) ? -1 : + (str1->slen == str2->slen ? 0 : 1); + } else { + return res; + } } } #if defined(PJ_HAS_STRICMP_ALNUM) && PJ_HAS_STRICMP_ALNUM!=0 PJ_IDEF(int) strnicmp_alnum( const char *str1, const char *str2, - int len) + int len) { if (len==0) - return 0; + return 0; else { - register const pj_uint32_t *p1 = (pj_uint32_t*)str1, - *p2 = (pj_uint32_t*)str2; - while (len > 3 && (*p1 & 0x5F5F5F5F)==(*p2 & 0x5F5F5F5F)) - ++p1, ++p2, len-=4; + register const pj_uint32_t *p1 = (pj_uint32_t*)str1, + *p2 = (pj_uint32_t*)str2; + while (len > 3 && (*p1 & 0x5F5F5F5F)==(*p2 & 0x5F5F5F5F)) + ++p1, ++p2, len-=4; - if (len > 3) - return -1; + if (len > 3) + return -1; #if defined(PJ_IS_LITTLE_ENDIAN) && PJ_IS_LITTLE_ENDIAN!=0 - else if (len==3) - return ((*p1 & 0x005F5F5F)==(*p2 & 0x005F5F5F)) ? 0 : -1; - else if (len==2) - return ((*p1 & 0x00005F5F)==(*p2 & 0x00005F5F)) ? 0 : -1; - else if (len==1) - return ((*p1 & 0x0000005F)==(*p2 & 0x0000005F)) ? 0 : -1; + else if (len==3) + return ((*p1 & 0x005F5F5F)==(*p2 & 0x005F5F5F)) ? 0 : -1; + else if (len==2) + return ((*p1 & 0x00005F5F)==(*p2 & 0x00005F5F)) ? 0 : -1; + else if (len==1) + return ((*p1 & 0x0000005F)==(*p2 & 0x0000005F)) ? 0 : -1; #else - else if (len==3) - return ((*p1 & 0x5F5F5F00)==(*p2 & 0x5F5F5F00)) ? 0 : -1; - else if (len==2) - return ((*p1 & 0x5F5F0000)==(*p2 & 0x5F5F0000)) ? 0 : -1; - else if (len==1) - return ((*p1 & 0x5F000000)==(*p2 & 0x5F000000)) ? 0 : -1; + else if (len==3) + return ((*p1 & 0x5F5F5F00)==(*p2 & 0x5F5F5F00)) ? 0 : -1; + else if (len==2) + return ((*p1 & 0x5F5F0000)==(*p2 & 0x5F5F0000)) ? 0 : -1; + else if (len==1) + return ((*p1 & 0x5F000000)==(*p2 & 0x5F000000)) ? 0 : -1; #endif - else - return 0; + else + return 0; } } @@ -293,83 +292,83 @@ PJ_IDEF(int) pj_stricmp_alnum(const pj_str_t *str1, const pj_str_t *str2) register int len = str1->slen; if (len != str2->slen) { - return (len < str2->slen) ? -1 : 1; + return (len < str2->slen) ? -1 : 1; } else if (len == 0) { - return 0; + return 0; } else { - register const pj_uint32_t *p1 = (pj_uint32_t*)str1->ptr, - *p2 = (pj_uint32_t*)str2->ptr; - while (len > 3 && (*p1 & 0x5F5F5F5F)==(*p2 & 0x5F5F5F5F)) - ++p1, ++p2, len-=4; + register const pj_uint32_t *p1 = (pj_uint32_t*)str1->ptr, + *p2 = (pj_uint32_t*)str2->ptr; + while (len > 3 && (*p1 & 0x5F5F5F5F)==(*p2 & 0x5F5F5F5F)) + ++p1, ++p2, len-=4; - if (len > 3) - return -1; + if (len > 3) + return -1; #if defined(PJ_IS_LITTLE_ENDIAN) && PJ_IS_LITTLE_ENDIAN!=0 - else if (len==3) - return ((*p1 & 0x005F5F5F)==(*p2 & 0x005F5F5F)) ? 0 : -1; - else if (len==2) - return ((*p1 & 0x00005F5F)==(*p2 & 0x00005F5F)) ? 0 : -1; - else if (len==1) - return ((*p1 & 0x0000005F)==(*p2 & 0x0000005F)) ? 0 : -1; + else if (len==3) + return ((*p1 & 0x005F5F5F)==(*p2 & 0x005F5F5F)) ? 0 : -1; + else if (len==2) + return ((*p1 & 0x00005F5F)==(*p2 & 0x00005F5F)) ? 0 : -1; + else if (len==1) + return ((*p1 & 0x0000005F)==(*p2 & 0x0000005F)) ? 0 : -1; #else - else if (len==3) - return ((*p1 & 0x5F5F5F00)==(*p2 & 0x5F5F5F00)) ? 0 : -1; - else if (len==2) - return ((*p1 & 0x5F5F0000)==(*p2 & 0x5F5F0000)) ? 0 : -1; - else if (len==1) - return ((*p1 & 0x5F000000)==(*p2 & 0x5F000000)) ? 0 : -1; + else if (len==3) + return ((*p1 & 0x5F5F5F00)==(*p2 & 0x5F5F5F00)) ? 0 : -1; + else if (len==2) + return ((*p1 & 0x5F5F0000)==(*p2 & 0x5F5F0000)) ? 0 : -1; + else if (len==1) + return ((*p1 & 0x5F000000)==(*p2 & 0x5F000000)) ? 0 : -1; #endif - else - return 0; + else + return 0; } } -#endif /* PJ_HAS_STRICMP_ALNUM */ +#endif /* PJ_HAS_STRICMP_ALNUM */ PJ_IDEF(int) pj_stricmp2( const pj_str_t *str1, const char *str2) { pj_str_t copy2; if (str2) { - copy2.ptr = (char*)str2; - copy2.slen = pj_ansi_strlen(str2); + copy2.ptr = (char*)str2; + copy2.slen = pj_ansi_strlen(str2); } else { - copy2.ptr = NULL; - copy2.slen = 0; + copy2.ptr = NULL; + copy2.slen = 0; } return pj_stricmp(str1, ©2); } PJ_IDEF(int) pj_strnicmp( const pj_str_t *str1, const pj_str_t *str2, - pj_size_t len) + pj_size_t len) { pj_str_t copy1, copy2; if (len < (unsigned)str1->slen && str1->slen > 0) { - copy1.ptr = str1->ptr; - copy1.slen = len; - str1 = ©1; + copy1.ptr = str1->ptr; + copy1.slen = len; + str1 = ©1; } if (len < (unsigned)str2->slen && str2->slen > 0) { - copy2.ptr = str2->ptr; - copy2.slen = len; - str2 = ©2; + copy2.ptr = str2->ptr; + copy2.slen = len; + str2 = ©2; } return pj_stricmp(str1, str2); } PJ_IDEF(int) pj_strnicmp2( const pj_str_t *str1, const char *str2, - pj_size_t len) + pj_size_t len) { pj_str_t copy2; if (str2) { - copy2.ptr = (char*)str2; - copy2.slen = pj_ansi_strlen(str2); + copy2.ptr = (char*)str2; + copy2.slen = pj_ansi_strlen(str2); } else { - copy2.slen = 0; + copy2.slen = 0; } return pj_strnicmp(str1, ©2, len); @@ -381,8 +380,8 @@ PJ_IDEF(void) pj_strcat(pj_str_t *dst, const pj_str_t *src) pj_assert(dst->slen >= 0); if (src->slen > 0 && dst->slen >= 0) { - pj_memcpy(dst->ptr + dst->slen, src->ptr, src->slen); - dst->slen += src->slen; + pj_memcpy(dst->ptr + dst->slen, src->ptr, src->slen); + dst->slen += src->slen; } } @@ -393,8 +392,8 @@ PJ_IDEF(void) pj_strcat2(pj_str_t *dst, const char *str) pj_assert(dst->slen >= 0); if (len && dst->slen >= 0) { - pj_memcpy(dst->ptr + dst->slen, str, len); - dst->slen += len; + pj_memcpy(dst->ptr + dst->slen, str, len); + dst->slen += len; } } diff --git a/pjlib/include/pj/timer.h b/pjlib/include/pj/timer.h index 4b76ab65d2..263ae01510 100644 --- a/pjlib/include/pj/timer.h +++ b/pjlib/include/pj/timer.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -84,7 +83,7 @@ struct pj_timer_entry; * @param entry Timer entry which timer's has expired. */ typedef void pj_timer_heap_callback(pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry); + struct pj_timer_entry *entry); /** @@ -141,8 +140,8 @@ typedef struct pj_timer_entry pj_grp_lock_t *_grp_lock; #if PJ_TIMER_DEBUG - const char *src_file; - int src_line; + const char *src_file; + int src_line; #endif #endif @@ -173,7 +172,7 @@ PJ_DECL(pj_size_t) pj_timer_heap_mem_size(pj_size_t count); * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_timer_heap_create( pj_pool_t *pool, - pj_size_t count, + pj_size_t count, pj_timer_heap_t **ht); /** @@ -248,18 +247,18 @@ PJ_DECL(pj_bool_t) pj_timer_entry_running( pj_timer_entry *entry ); */ #if PJ_TIMER_DEBUG # define pj_timer_heap_schedule(ht,e,d) \ - pj_timer_heap_schedule_dbg(ht,e,d,__FILE__,__LINE__) + pj_timer_heap_schedule_dbg(ht,e,d,__FILE__,__LINE__) PJ_DECL(pj_status_t) pj_timer_heap_schedule_dbg( pj_timer_heap_t *ht, - pj_timer_entry *entry, - const pj_time_val *delay, - const char *src_file, - int src_line); + pj_timer_entry *entry, + const pj_time_val *delay, + const char *src_file, + int src_line); #else PJ_DECL(pj_status_t) pj_timer_heap_schedule( pj_timer_heap_t *ht, - pj_timer_entry *entry, - const pj_time_val *delay); -#endif /* PJ_TIMER_DEBUG */ + pj_timer_entry *entry, + const pj_time_val *delay); +#endif /* PJ_TIMER_DEBUG */ /** * Schedule a timer entry which will expire AFTER the specified delay, and @@ -271,31 +270,31 @@ PJ_DECL(pj_status_t) pj_timer_heap_schedule( pj_timer_heap_t *ht, * @param entry The entry to be registered. * @param delay The interval to expire. * @param id_val The value to be set to the "id" field of the timer entry - * once the timer is scheduled. + * once the timer is scheduled. * @param grp_lock The group lock. * * @return PJ_SUCCESS, or the appropriate error code. */ #if PJ_TIMER_DEBUG # define pj_timer_heap_schedule_w_grp_lock(ht,e,d,id,g) \ - pj_timer_heap_schedule_w_grp_lock_dbg(ht,e,d,id,g,__FILE__,__LINE__) + pj_timer_heap_schedule_w_grp_lock_dbg(ht,e,d,id,g,__FILE__,__LINE__) PJ_DECL(pj_status_t) pj_timer_heap_schedule_w_grp_lock_dbg( - pj_timer_heap_t *ht, - pj_timer_entry *entry, - const pj_time_val *delay, - int id_val, - pj_grp_lock_t *grp_lock, - const char *src_file, - int src_line); + pj_timer_heap_t *ht, + pj_timer_entry *entry, + const pj_time_val *delay, + int id_val, + pj_grp_lock_t *grp_lock, + const char *src_file, + int src_line); #else PJ_DECL(pj_status_t) pj_timer_heap_schedule_w_grp_lock( - pj_timer_heap_t *ht, - pj_timer_entry *entry, - const pj_time_val *delay, - int id_val, - pj_grp_lock_t *grp_lock); -#endif /* PJ_TIMER_DEBUG */ + pj_timer_heap_t *ht, + pj_timer_entry *entry, + const pj_time_val *delay, + int id_val, + pj_grp_lock_t *grp_lock); +#endif /* PJ_TIMER_DEBUG */ /** @@ -310,7 +309,7 @@ PJ_DECL(pj_status_t) pj_timer_heap_schedule_w_grp_lock( * cancelled. */ PJ_DECL(int) pj_timer_heap_cancel( pj_timer_heap_t *ht, - pj_timer_entry *entry); + pj_timer_entry *entry); /** * Cancel only if the previously registered timer is active. This will @@ -349,7 +348,7 @@ PJ_DECL(pj_size_t) pj_timer_heap_count( pj_timer_heap_t *ht ); * @return PJ_SUCCESS, or PJ_ENOTFOUND if no entry is scheduled. */ PJ_DECL(pj_status_t) pj_timer_heap_earliest_time( pj_timer_heap_t *ht, - pj_time_val *timeval); + pj_time_val *timeval); /** * Poll the timer heap, check for expired timers and call the callback for @@ -360,8 +359,8 @@ PJ_DECL(pj_status_t) pj_timer_heap_earliest_time( pj_timer_heap_t *ht, * * @param ht The timer heap. * @param next_delay If this parameter is not NULL, it will be filled up with - * the time delay until the next timer elapsed, or - * PJ_MAXINT32 in the sec part if no entry exist. + * the time delay until the next timer elapsed, or + * PJ_MAXINT32 in the sec part if no entry exist. * * @return The number of timers expired. */ @@ -372,7 +371,7 @@ PJ_DECL(unsigned) pj_timer_heap_poll( pj_timer_heap_t *ht, /** * Dump timer heap entries. * - * @param ht The timer heap. + * @param ht The timer heap. */ PJ_DECL(void) pj_timer_heap_dump(pj_timer_heap_t *ht); #endif @@ -383,5 +382,5 @@ PJ_DECL(void) pj_timer_heap_dump(pj_timer_heap_t *ht); PJ_END_DECL -#endif /* __PJ_TIMER_H__ */ +#endif /* __PJ_TIMER_H__ */ diff --git a/pjlib/include/pj/types.h b/pjlib/include/pj/types.h index d861803d78..236917dda7 100644 --- a/pjlib/include/pj/types.h +++ b/pjlib/include/pj/types.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,25 +37,25 @@ PJ_BEGIN_DECL /* ************************************************************************* */ /** Signed 32bit integer. */ -typedef int pj_int32_t; +typedef int pj_int32_t; /** Unsigned 32bit integer. */ -typedef unsigned int pj_uint32_t; +typedef unsigned int pj_uint32_t; /** Signed 16bit integer. */ -typedef short pj_int16_t; +typedef short pj_int16_t; /** Unsigned 16bit integer. */ -typedef unsigned short pj_uint16_t; +typedef unsigned short pj_uint16_t; /** Signed 8bit integer. */ -typedef signed char pj_int8_t; +typedef signed char pj_int8_t; /** Unsigned 8bit integer. */ -typedef unsigned char pj_uint8_t; +typedef unsigned char pj_uint8_t; /** Large unsigned integer. */ -typedef size_t pj_size_t; +typedef size_t pj_size_t; /** Large signed integer. */ #if defined(PJ_WIN64) && PJ_WIN64!=0 @@ -66,10 +65,10 @@ typedef size_t pj_size_t; #endif /** Status code. */ -typedef int pj_status_t; +typedef int pj_status_t; /** Boolean. */ -typedef int pj_bool_t; +typedef int pj_bool_t; /** Native char type, which will be equal to wchar_t for Unicode * and char for ANSI. */ @@ -82,9 +81,9 @@ typedef int pj_bool_t; /** This macro creates Unicode or ANSI literal string depending whether * native platform string is Unicode or ANSI. */ #if defined(PJ_NATIVE_STRING_IS_UNICODE) && PJ_NATIVE_STRING_IS_UNICODE!=0 -# define PJ_T(literal_str) L##literal_str +# define PJ_T(literal_str) L##literal_str #else -# define PJ_T(literal_str) literal_str +# define PJ_T(literal_str) literal_str #endif /** Some constants */ @@ -136,11 +135,11 @@ typedef union pj_timestamp struct { #if defined(PJ_IS_LITTLE_ENDIAN) && PJ_IS_LITTLE_ENDIAN!=0 - pj_uint32_t lo; /**< Low 32-bit value of the 64-bit value. */ - pj_uint32_t hi; /**< high 32-bit value of the 64-bit value. */ + pj_uint32_t lo; /**< Low 32-bit value of the 64-bit value. */ + pj_uint32_t hi; /**< high 32-bit value of the 64-bit value. */ #else - pj_uint32_t hi; /**< high 32-bit value of the 64-bit value. */ - pj_uint32_t lo; /**< Low 32-bit value of the 64-bit value. */ + pj_uint32_t hi; /**< high 32-bit value of the 64-bit value. */ + pj_uint32_t lo; /**< Low 32-bit value of the 64-bit value. */ #endif } u32; /**< The 64-bit value as two 32-bit values. */ @@ -179,7 +178,7 @@ typedef struct pj_hash_entry pj_hash_entry; */ typedef struct pj_hash_iterator_t { - pj_uint32_t index; /**< Internal index. */ + pj_uint32_t index; /**< Internal index. */ pj_hash_entry *entry; /**< Internal entry. */ } pj_hash_iterator_t; @@ -284,7 +283,7 @@ typedef int pj_exception_id_t; /** * Length of object names. */ -#define PJ_MAX_OBJ_NAME 32 +#define PJ_MAX_OBJ_NAME 32 /* ************************************************************************* */ /* @@ -319,7 +318,7 @@ typedef void (*pj_exit_callback)(void); * Register cleanup function to be called by PJLIB when pj_shutdown() is * called. * - * @param func The function to be registered. + * @param func The function to be registered. * * @return PJ_SUCCESS on success. */ @@ -330,9 +329,9 @@ PJ_DECL(pj_status_t) pj_atexit(pj_exit_callback func); /** * Swap the byte order of an 16bit data. * - * @param val16 The 16bit data. + * @param val16 The 16bit data. * - * @return An 16bit data with swapped byte order. + * @return An 16bit data with swapped byte order. */ PJ_INLINE(pj_int16_t) pj_swap16(pj_int16_t val16) { @@ -346,9 +345,9 @@ PJ_INLINE(pj_int16_t) pj_swap16(pj_int16_t val16) /** * Swap the byte order of an 32bit data. * - * @param val32 The 32bit data. + * @param val32 The 32bit data. * - * @return An 32bit data with swapped byte order. + * @return An 32bit data with swapped byte order. */ PJ_INLINE(pj_int32_t) pj_swap32(pj_int32_t val32) { @@ -419,7 +418,7 @@ PJ_DECL(void) pj_time_val_normalize(pj_time_val *t); * @return Total time in miliseconds. * @hideinitializer */ -#define PJ_TIME_VAL_MSEC(t) ((t).sec * 1000 + (t).msec) +#define PJ_TIME_VAL_MSEC(t) ((t).sec * 1000 + (t).msec) /** * This macro will check if \a t1 is equal to \a t2. @@ -429,7 +428,7 @@ PJ_DECL(void) pj_time_val_normalize(pj_time_val *t); * @return Non-zero if both time values are equal. * @hideinitializer */ -#define PJ_TIME_VAL_EQ(t1, t2) ((t1).sec==(t2).sec && (t1).msec==(t2).msec) +#define PJ_TIME_VAL_EQ(t1, t2) ((t1).sec==(t2).sec && (t1).msec==(t2).msec) /** * This macro will check if \a t1 is greater than \a t2 @@ -439,7 +438,7 @@ PJ_DECL(void) pj_time_val_normalize(pj_time_val *t); * @return Non-zero if t1 is greater than t2. * @hideinitializer */ -#define PJ_TIME_VAL_GT(t1, t2) ((t1).sec>(t2).sec || \ +#define PJ_TIME_VAL_GT(t1, t2) ((t1).sec>(t2).sec || \ ((t1).sec==(t2).sec && (t1).msec>(t2).msec)) /** @@ -450,7 +449,7 @@ PJ_DECL(void) pj_time_val_normalize(pj_time_val *t); * @return Non-zero if t1 is greater than or equal to t2. * @hideinitializer */ -#define PJ_TIME_VAL_GTE(t1, t2) (PJ_TIME_VAL_GT(t1,t2) || \ +#define PJ_TIME_VAL_GTE(t1, t2) (PJ_TIME_VAL_GT(t1,t2) || \ PJ_TIME_VAL_EQ(t1,t2)) /** @@ -461,7 +460,7 @@ PJ_DECL(void) pj_time_val_normalize(pj_time_val *t); * @return Non-zero if t1 is less than t2. * @hideinitializer */ -#define PJ_TIME_VAL_LT(t1, t2) (!(PJ_TIME_VAL_GTE(t1,t2))) +#define PJ_TIME_VAL_LT(t1, t2) (!(PJ_TIME_VAL_GTE(t1,t2))) /** * This macro will check if \a t1 is less than or equal to \a t2. @@ -471,7 +470,7 @@ PJ_DECL(void) pj_time_val_normalize(pj_time_val *t); * @return Non-zero if t1 is less than or equal to t2. * @hideinitializer */ -#define PJ_TIME_VAL_LTE(t1, t2) (!PJ_TIME_VAL_GT(t1, t2)) +#define PJ_TIME_VAL_LTE(t1, t2) (!PJ_TIME_VAL_GT(t1, t2)) /** * Add \a t2 to \a t1 and store the result in \a t1. Effectively @@ -481,11 +480,11 @@ PJ_DECL(void) pj_time_val_normalize(pj_time_val *t); * @param t2 The time value to be added to \a t1. * @hideinitializer */ -#define PJ_TIME_VAL_ADD(t1, t2) do { \ - (t1).sec += (t2).sec; \ - (t1).msec += (t2).msec; \ - pj_time_val_normalize(&(t1)); \ - } while (0) +#define PJ_TIME_VAL_ADD(t1, t2) do { \ + (t1).sec += (t2).sec; \ + (t1).msec += (t2).msec; \ + pj_time_val_normalize(&(t1)); \ + } while (0) /** @@ -496,11 +495,11 @@ PJ_DECL(void) pj_time_val_normalize(pj_time_val *t); * @param t2 The time value to be substracted from \a t1. * @hideinitializer */ -#define PJ_TIME_VAL_SUB(t1, t2) do { \ - (t1).sec -= (t2).sec; \ - (t1).msec -= (t2).msec; \ - pj_time_val_normalize(&(t1)); \ - } while (0) +#define PJ_TIME_VAL_SUB(t1, t2) do { \ + (t1).sec -= (t2).sec; \ + (t1).msec -= (t2).msec; \ + pj_time_val_normalize(&(t1)); \ + } while (0) /** @@ -544,7 +543,7 @@ typedef struct pj_parsed_time /** - * @} // Time Management + * @} // Time Management */ /* ************************************************************************* */ @@ -555,9 +554,9 @@ typedef struct pj_parsed_time * Color code combination. */ enum { - PJ_TERM_COLOR_R = 2, /**< Red */ - PJ_TERM_COLOR_G = 4, /**< Green */ - PJ_TERM_COLOR_B = 1, /**< Blue. */ + PJ_TERM_COLOR_R = 2, /**< Red */ + PJ_TERM_COLOR_G = 4, /**< Green */ + PJ_TERM_COLOR_B = 1, /**< Blue. */ PJ_TERM_COLOR_BRIGHT = 8 /**< Bright mask. */ }; diff --git a/pjlib/include/pj/unicode.h b/pjlib/include/pj/unicode.h index 2e62855b3b..5f037b0d4e 100644 --- a/pjlib/include/pj/unicode.h +++ b/pjlib/include/pj/unicode.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -40,29 +39,29 @@ PJ_BEGIN_DECL /** * Convert ANSI strings to Unicode strings. * - * @param str The ANSI string to be converted. - * @param len The length of the input string. - * @param wbuf Buffer to hold the Unicode string output. - * @param wbuf_count Buffer size, in number of elements (not bytes). + * @param str The ANSI string to be converted. + * @param len The length of the input string. + * @param wbuf Buffer to hold the Unicode string output. + * @param wbuf_count Buffer size, in number of elements (not bytes). * - * @return The Unicode string, NULL terminated. + * @return The Unicode string, NULL terminated. */ PJ_DECL(wchar_t*) pj_ansi_to_unicode(const char *str, int len, - wchar_t *wbuf, int wbuf_count); + wchar_t *wbuf, int wbuf_count); /** * Convert Unicode string to ANSI string. * - * @param wstr The Unicode string to be converted. - * @param len The length of the input string. - * @param buf Buffer to hold the ANSI string output. - * @param buf_size Size of the output buffer. + * @param wstr The Unicode string to be converted. + * @param len The length of the input string. + * @param buf Buffer to hold the ANSI string output. + * @param buf_size Size of the output buffer. * - * @return The ANSI string, NULL terminated. + * @return The ANSI string, NULL terminated. */ PJ_DECL(char*) pj_unicode_to_ansi(const wchar_t *wstr, pj_ssize_t len, - char *buf, int buf_size); + char *buf, int buf_size); #if defined(PJ_NATIVE_STRING_IS_UNICODE) && PJ_NATIVE_STRING_IS_UNICODE!=0 @@ -79,9 +78,9 @@ PJ_DECL(char*) pj_unicode_to_ansi(const wchar_t *wstr, pj_ssize_t len, * This macro will convert ANSI string to native, when the platform's * native string is Unicode (PJ_NATIVE_STRING_IS_UNICODE is non-zero). */ -# define PJ_STRING_TO_NATIVE(s,buf,max) pj_ansi_to_unicode( \ - s, strlen(s), \ - buf, max) +# define PJ_STRING_TO_NATIVE(s,buf,max) pj_ansi_to_unicode( \ + s, strlen(s), \ + buf, max) /** * This macro is used to declare temporary ANSI buffer for Unicode to @@ -89,16 +88,16 @@ PJ_DECL(char*) pj_unicode_to_ansi(const wchar_t *wstr, pj_ssize_t len, * When PJ_NATIVE_STRING_IS_UNICODE macro is not defined, this * macro will expand to nothing. */ -# define PJ_DECL_ANSI_TEMP_BUF(buf,size) char buf[size]; +# define PJ_DECL_ANSI_TEMP_BUF(buf,size) char buf[size]; /** * This macro will convert Unicode string to ANSI, when the platform's * native string is Unicode (PJ_NATIVE_STRING_IS_UNICODE is non-zero). */ -# define PJ_NATIVE_TO_STRING(cs,buf,max) pj_unicode_to_ansi( \ - cs, wcslen(cs), \ - buf, max) +# define PJ_NATIVE_TO_STRING(cs,buf,max) pj_unicode_to_ansi( \ + cs, wcslen(cs), \ + buf, max) #else @@ -113,7 +112,7 @@ PJ_DECL(char*) pj_unicode_to_ansi(const wchar_t *wstr, pj_ssize_t len, * This macro will convert ANSI string to native, when the platform's * native string is Unicode (PJ_NATIVE_STRING_IS_UNICODE is non-zero). */ -# define PJ_STRING_TO_NATIVE(s,buf,max) ((char*)s) +# define PJ_STRING_TO_NATIVE(s,buf,max) ((char*)s) /** * This macro is used to declare temporary ANSI buffer for Unicode to * ANSI conversion, and should be put in declaration section of a block. @@ -125,7 +124,7 @@ PJ_DECL(char*) pj_unicode_to_ansi(const wchar_t *wstr, pj_ssize_t len, * This macro will convert Unicode string to ANSI, when the platform's * native string is Unicode (PJ_NATIVE_STRING_IS_UNICODE is non-zero). */ -# define PJ_NATIVE_TO_STRING(cs,buf,max) ((char*)(const char*)cs) +# define PJ_NATIVE_TO_STRING(cs,buf,max) ((char*)(const char*)cs) #endif @@ -138,4 +137,4 @@ PJ_END_DECL */ -#endif /* __PJ_UNICODE_H__ */ +#endif /* __PJ_UNICODE_H__ */ diff --git a/pjlib/include/pjlib++.hpp b/pjlib/include/pjlib++.hpp index f91a1ce1bf..8ef6a269d4 100644 --- a/pjlib/include/pjlib++.hpp +++ b/pjlib/include/pjlib++.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,4 +31,4 @@ #include #include -#endif /* __PJLIBPP_H__ */ +#endif /* __PJLIBPP_H__ */ diff --git a/pjlib/include/pjlib.h b/pjlib/include/pjlib.h index 8cce8806c7..dfb9e53f24 100644 --- a/pjlib/include/pjlib.h +++ b/pjlib/include/pjlib.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pj/activesock.c b/pjlib/src/pj/activesock.c index 61aed1c884..f901545b7f 100644 --- a/pjlib/src/pj/activesock.c +++ b/pjlib/src/pj/activesock.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -33,7 +32,7 @@ static pj_bool_t ios_bg_support = PJ_TRUE; #endif -#define PJ_ACTIVESOCK_MAX_LOOP 50 +#define PJ_ACTIVESOCK_MAX_LOOP 50 enum read_type @@ -52,74 +51,74 @@ enum shutdown_dir struct read_op { - pj_ioqueue_op_key_t op_key; - pj_uint8_t *pkt; - unsigned max_size; - pj_size_t size; - pj_sockaddr src_addr; - int src_addr_len; + pj_ioqueue_op_key_t op_key; + pj_uint8_t *pkt; + unsigned max_size; + pj_size_t size; + pj_sockaddr src_addr; + int src_addr_len; }; struct accept_op { - pj_ioqueue_op_key_t op_key; - pj_sock_t new_sock; - pj_sockaddr rem_addr; - int rem_addr_len; + pj_ioqueue_op_key_t op_key; + pj_sock_t new_sock; + pj_sockaddr rem_addr; + int rem_addr_len; }; struct send_data { - pj_uint8_t *data; - pj_ssize_t len; - pj_ssize_t sent; - unsigned flags; + pj_uint8_t *data; + pj_ssize_t len; + pj_ssize_t sent; + unsigned flags; }; struct pj_activesock_t { - pj_ioqueue_key_t *key; - pj_bool_t stream_oriented; - pj_bool_t whole_data; - pj_ioqueue_t *ioqueue; - void *user_data; - unsigned async_count; - unsigned shutdown; - unsigned max_loop; - pj_activesock_cb cb; + pj_ioqueue_key_t *key; + pj_bool_t stream_oriented; + pj_bool_t whole_data; + pj_ioqueue_t *ioqueue; + void *user_data; + unsigned async_count; + unsigned shutdown; + unsigned max_loop; + pj_activesock_cb cb; #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 - int bg_setting; - pj_sock_t sock; - CFReadStreamRef readStream; + int bg_setting; + pj_sock_t sock; + CFReadStreamRef readStream; #endif - unsigned err_counter; - pj_status_t last_err; + unsigned err_counter; + pj_status_t last_err; - struct send_data send_data; + struct send_data send_data; - struct read_op *read_op; - pj_uint32_t read_flags; - enum read_type read_type; + struct read_op *read_op; + pj_uint32_t read_flags; + enum read_type read_type; - struct accept_op *accept_op; + struct accept_op *accept_op; }; static void ioqueue_on_read_complete(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_read); + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_read); static void ioqueue_on_write_complete(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_sent); + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_sent); #if PJ_HAS_TCP static void ioqueue_on_accept_complete(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_sock_t sock, - pj_status_t status); + pj_ioqueue_op_key_t *op_key, + pj_sock_t sock, + pj_status_t status); static void ioqueue_on_connect_complete(pj_ioqueue_key_t *key, - pj_status_t status); + pj_status_t status); #endif PJ_DEF(void) pj_activesock_cfg_default(pj_activesock_cfg *cfg) @@ -135,46 +134,46 @@ PJ_DEF(void) pj_activesock_cfg_default(pj_activesock_cfg *cfg) static void activesock_destroy_iphone_os_stream(pj_activesock_t *asock) { if (asock->readStream) { - CFReadStreamClose(asock->readStream); - CFRelease(asock->readStream); - asock->readStream = NULL; + CFReadStreamClose(asock->readStream); + CFRelease(asock->readStream); + asock->readStream = NULL; } } static void activesock_create_iphone_os_stream(pj_activesock_t *asock) { if (ios_bg_support && asock->bg_setting && asock->stream_oriented) { - activesock_destroy_iphone_os_stream(asock); - - CFStreamCreatePairWithSocket(kCFAllocatorDefault, asock->sock, - &asock->readStream, NULL); - - if (!asock->readStream || - CFReadStreamSetProperty(asock->readStream, - kCFStreamNetworkServiceType, - kCFStreamNetworkServiceTypeVoIP) - != TRUE || - CFReadStreamOpen(asock->readStream) != TRUE) - { - PJ_LOG(2,("", "Failed to configure TCP transport for VoIP " - "usage. Usage of THIS particular TCP transport in " - "background mode will not be supported.")); - - - activesock_destroy_iphone_os_stream(asock); - } + activesock_destroy_iphone_os_stream(asock); + + CFStreamCreatePairWithSocket(kCFAllocatorDefault, asock->sock, + &asock->readStream, NULL); + + if (!asock->readStream || + CFReadStreamSetProperty(asock->readStream, + kCFStreamNetworkServiceType, + kCFStreamNetworkServiceTypeVoIP) + != TRUE || + CFReadStreamOpen(asock->readStream) != TRUE) + { + PJ_LOG(2,("", "Failed to configure TCP transport for VoIP " + "usage. Usage of THIS particular TCP transport in " + "background mode will not be supported.")); + + + activesock_destroy_iphone_os_stream(asock); + } } } PJ_DEF(void) pj_activesock_set_iphone_os_bg(pj_activesock_t *asock, - int val) + int val) { asock->bg_setting = val; if (asock->bg_setting) - activesock_create_iphone_os_stream(asock); + activesock_create_iphone_os_stream(asock); else - activesock_destroy_iphone_os_stream(asock); + activesock_destroy_iphone_os_stream(asock); } PJ_DEF(void) pj_activesock_enable_iphone_os_bg(pj_bool_t val) @@ -184,13 +183,13 @@ PJ_DEF(void) pj_activesock_enable_iphone_os_bg(pj_bool_t val) #endif PJ_DEF(pj_status_t) pj_activesock_create( pj_pool_t *pool, - pj_sock_t sock, - int sock_type, - const pj_activesock_cfg *opt, - pj_ioqueue_t *ioqueue, - const pj_activesock_cb *cb, - void *user_data, - pj_activesock_t **p_asock) + pj_sock_t sock, + int sock_type, + const pj_activesock_cfg *opt, + pj_ioqueue_t *ioqueue, + const pj_activesock_cb *cb, + void *user_data, + pj_activesock_t **p_asock) { pj_activesock_t *asock; pj_ioqueue_callback ioq_cb; @@ -199,7 +198,7 @@ PJ_DEF(pj_status_t) pj_activesock_create( pj_pool_t *pool, PJ_ASSERT_RETURN(pool && ioqueue && cb && p_asock, PJ_EINVAL); PJ_ASSERT_RETURN(sock!=0 && sock!=PJ_INVALID_SOCKET, PJ_EINVAL); PJ_ASSERT_RETURN(sock_type==pj_SOCK_STREAM() || - sock_type==pj_SOCK_DGRAM(), PJ_EINVAL); + sock_type==pj_SOCK_DGRAM(), PJ_EINVAL); PJ_ASSERT_RETURN(!opt || opt->async_cnt >= 1, PJ_EINVAL); asock = PJ_POOL_ZALLOC_T(pool, pj_activesock_t); @@ -223,15 +222,15 @@ PJ_DEF(pj_status_t) pj_activesock_create( pj_pool_t *pool, (opt? opt->grp_lock : NULL), asock, &ioq_cb, &asock->key); if (status != PJ_SUCCESS) { - pj_activesock_close(asock); - return status; + pj_activesock_close(asock); + return status; } if (asock->whole_data) { - /* Must disable concurrency otherwise there is a race condition */ - pj_ioqueue_set_concurrency(asock->key, 0); + /* Must disable concurrency otherwise there is a race condition */ + pj_ioqueue_set_concurrency(asock->key, 0); } else if (opt && opt->concurrency >= 0) { - pj_ioqueue_set_concurrency(asock->key, opt->concurrency); + pj_ioqueue_set_concurrency(asock->key, opt->concurrency); } #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ @@ -246,49 +245,49 @@ PJ_DEF(pj_status_t) pj_activesock_create( pj_pool_t *pool, PJ_DEF(pj_status_t) pj_activesock_create_udp( pj_pool_t *pool, - const pj_sockaddr *addr, - const pj_activesock_cfg *opt, - pj_ioqueue_t *ioqueue, - const pj_activesock_cb *cb, - void *user_data, - pj_activesock_t **p_asock, - pj_sockaddr *bound_addr) + const pj_sockaddr *addr, + const pj_activesock_cfg *opt, + pj_ioqueue_t *ioqueue, + const pj_activesock_cb *cb, + void *user_data, + pj_activesock_t **p_asock, + pj_sockaddr *bound_addr) { pj_sock_t sock_fd; pj_sockaddr default_addr; pj_status_t status; if (addr == NULL) { - pj_sockaddr_init(pj_AF_INET(), &default_addr, NULL, 0); - addr = &default_addr; + pj_sockaddr_init(pj_AF_INET(), &default_addr, NULL, 0); + addr = &default_addr; } status = pj_sock_socket(addr->addr.sa_family, pj_SOCK_DGRAM(), 0, - &sock_fd); + &sock_fd); if (status != PJ_SUCCESS) { - return status; + return status; } status = pj_sock_bind(sock_fd, addr, pj_sockaddr_get_len(addr)); if (status != PJ_SUCCESS) { - pj_sock_close(sock_fd); - return status; + pj_sock_close(sock_fd); + return status; } status = pj_activesock_create(pool, sock_fd, pj_SOCK_DGRAM(), opt, - ioqueue, cb, user_data, p_asock); + ioqueue, cb, user_data, p_asock); if (status != PJ_SUCCESS) { - pj_sock_close(sock_fd); - return status; + pj_sock_close(sock_fd); + return status; } if (bound_addr) { - int addr_len = sizeof(*bound_addr); - status = pj_sock_getsockname(sock_fd, bound_addr, &addr_len); - if (status != PJ_SUCCESS) { - pj_activesock_close(*p_asock); - return status; - } + int addr_len = sizeof(*bound_addr); + status = pj_sock_getsockname(sock_fd, bound_addr, &addr_len); + if (status != PJ_SUCCESS) { + pj_activesock_close(*p_asock); + return status; + } } return PJ_SUCCESS; @@ -305,26 +304,26 @@ PJ_DEF(pj_status_t) pj_activesock_close(pj_activesock_t *asock) /* Avoid double unregistration on the key */ key = asock->key; if (key) { - pj_ioqueue_lock_key(key); - unregister = (asock->key != NULL); - asock->key = NULL; - pj_ioqueue_unlock_key(key); + pj_ioqueue_lock_key(key); + unregister = (asock->key != NULL); + asock->key = NULL; + pj_ioqueue_unlock_key(key); } if (unregister) { - pj_ioqueue_unregister(key); + pj_ioqueue_unregister(key); #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 - activesock_destroy_iphone_os_stream(asock); -#endif + activesock_destroy_iphone_os_stream(asock); +#endif } return PJ_SUCCESS; } PJ_DEF(pj_status_t) pj_activesock_set_user_data( pj_activesock_t *asock, - void *user_data) + void *user_data) { PJ_ASSERT_RETURN(asock, PJ_EINVAL); asock->user_data = user_data; @@ -340,9 +339,9 @@ PJ_DEF(void*) pj_activesock_get_user_data(pj_activesock_t *asock) PJ_DEF(pj_status_t) pj_activesock_start_read(pj_activesock_t *asock, - pj_pool_t *pool, - unsigned buff_size, - pj_uint32_t flags) + pj_pool_t *pool, + unsigned buff_size, + pj_uint32_t flags) { void **readbuf; unsigned i; @@ -350,10 +349,10 @@ PJ_DEF(pj_status_t) pj_activesock_start_read(pj_activesock_t *asock, PJ_ASSERT_RETURN(asock && pool && buff_size, PJ_EINVAL); readbuf = (void**) pj_pool_calloc(pool, asock->async_count, - sizeof(void*)); + sizeof(void*)); for (i=0; iasync_count; ++i) { - readbuf[i] = pj_pool_alloc(pool, buff_size); + readbuf[i] = pj_pool_alloc(pool, buff_size); } return pj_activesock_start_read2(asock, pool, buff_size, readbuf, flags); @@ -361,10 +360,10 @@ PJ_DEF(pj_status_t) pj_activesock_start_read(pj_activesock_t *asock, PJ_DEF(pj_status_t) pj_activesock_start_read2( pj_activesock_t *asock, - pj_pool_t *pool, - unsigned buff_size, - void *readbuf[], - pj_uint32_t flags) + pj_pool_t *pool, + unsigned buff_size, + void *readbuf[], + pj_uint32_t flags) { unsigned i; pj_status_t status; @@ -374,24 +373,24 @@ PJ_DEF(pj_status_t) pj_activesock_start_read2( pj_activesock_t *asock, PJ_ASSERT_RETURN(asock->read_op == NULL, PJ_EINVALIDOP); asock->read_op = (struct read_op*) - pj_pool_calloc(pool, asock->async_count, - sizeof(struct read_op)); + pj_pool_calloc(pool, asock->async_count, + sizeof(struct read_op)); asock->read_type = TYPE_RECV; asock->read_flags = flags; for (i=0; iasync_count; ++i) { - struct read_op *r = &asock->read_op[i]; - pj_ssize_t size_to_read; + struct read_op *r = &asock->read_op[i]; + pj_ssize_t size_to_read; - r->pkt = (pj_uint8_t*)readbuf[i]; - size_to_read = r->max_size = buff_size; + r->pkt = (pj_uint8_t*)readbuf[i]; + size_to_read = r->max_size = buff_size; - status = pj_ioqueue_recv(asock->key, &r->op_key, r->pkt, &size_to_read, - PJ_IOQUEUE_ALWAYS_ASYNC | flags); - PJ_ASSERT_RETURN(status != PJ_SUCCESS, PJ_EBUG); + status = pj_ioqueue_recv(asock->key, &r->op_key, r->pkt, &size_to_read, + PJ_IOQUEUE_ALWAYS_ASYNC | flags); + PJ_ASSERT_RETURN(status != PJ_SUCCESS, PJ_EBUG); - if (status != PJ_EPENDING) - return status; + if (status != PJ_EPENDING) + return status; } return PJ_SUCCESS; @@ -399,9 +398,9 @@ PJ_DEF(pj_status_t) pj_activesock_start_read2( pj_activesock_t *asock, PJ_DEF(pj_status_t) pj_activesock_start_recvfrom(pj_activesock_t *asock, - pj_pool_t *pool, - unsigned buff_size, - pj_uint32_t flags) + pj_pool_t *pool, + unsigned buff_size, + pj_uint32_t flags) { void **readbuf; unsigned i; @@ -409,22 +408,22 @@ PJ_DEF(pj_status_t) pj_activesock_start_recvfrom(pj_activesock_t *asock, PJ_ASSERT_RETURN(asock && pool && buff_size, PJ_EINVAL); readbuf = (void**) pj_pool_calloc(pool, asock->async_count, - sizeof(void*)); + sizeof(void*)); for (i=0; iasync_count; ++i) { - readbuf[i] = pj_pool_alloc(pool, buff_size); + readbuf[i] = pj_pool_alloc(pool, buff_size); } return pj_activesock_start_recvfrom2(asock, pool, buff_size, - readbuf, flags); + readbuf, flags); } PJ_DEF(pj_status_t) pj_activesock_start_recvfrom2( pj_activesock_t *asock, - pj_pool_t *pool, - unsigned buff_size, - void *readbuf[], - pj_uint32_t flags) + pj_pool_t *pool, + unsigned buff_size, + void *readbuf[], + pj_uint32_t flags) { unsigned i; pj_status_t status; @@ -433,27 +432,27 @@ PJ_DEF(pj_status_t) pj_activesock_start_recvfrom2( pj_activesock_t *asock, PJ_ASSERT_RETURN(asock->read_type == TYPE_NONE, PJ_EINVALIDOP); asock->read_op = (struct read_op*) - pj_pool_calloc(pool, asock->async_count, - sizeof(struct read_op)); + pj_pool_calloc(pool, asock->async_count, + sizeof(struct read_op)); asock->read_type = TYPE_RECV_FROM; asock->read_flags = flags; for (i=0; iasync_count; ++i) { - struct read_op *r = &asock->read_op[i]; - pj_ssize_t size_to_read; + struct read_op *r = &asock->read_op[i]; + pj_ssize_t size_to_read; - r->pkt = (pj_uint8_t*) readbuf[i]; - size_to_read = r->max_size = buff_size; - r->src_addr_len = sizeof(r->src_addr); + r->pkt = (pj_uint8_t*) readbuf[i]; + size_to_read = r->max_size = buff_size; + r->src_addr_len = sizeof(r->src_addr); - status = pj_ioqueue_recvfrom(asock->key, &r->op_key, r->pkt, - &size_to_read, - PJ_IOQUEUE_ALWAYS_ASYNC | flags, - &r->src_addr, &r->src_addr_len); - PJ_ASSERT_RETURN(status != PJ_SUCCESS, PJ_EBUG); + status = pj_ioqueue_recvfrom(asock->key, &r->op_key, r->pkt, + &size_to_read, + PJ_IOQUEUE_ALWAYS_ASYNC | flags, + &r->src_addr, &r->src_addr_len); + PJ_ASSERT_RETURN(status != PJ_SUCCESS, PJ_EBUG); - if (status != PJ_EPENDING) - return status; + if (status != PJ_EPENDING) + return status; } return PJ_SUCCESS; @@ -461,8 +460,8 @@ PJ_DEF(pj_status_t) pj_activesock_start_recvfrom2( pj_activesock_t *asock, static void ioqueue_on_read_complete(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_read) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_read) { pj_activesock_t *asock; struct read_op *r = (struct read_op*)op_key; @@ -473,197 +472,197 @@ static void ioqueue_on_read_complete(pj_ioqueue_key_t *key, /* Ignore if we've been shutdown */ if (asock->shutdown & SHUT_RX) - return; + return; do { - unsigned flags; - - if (bytes_read > 0) { - /* - * We've got new data. - */ - pj_size_t remainder; - pj_bool_t ret; - - /* Append this new data to existing data. If socket is stream - * oriented, user might have left some data in the buffer. - * Otherwise if socket is datagram there will be nothing in - * existing packet hence the packet will contain only the new - * packet. - */ - r->size += bytes_read; - - /* Set default remainder to zero */ - remainder = 0; - - /* And return value to TRUE */ - ret = PJ_TRUE; - - /* Notify callback */ - if (asock->read_type == TYPE_RECV && asock->cb.on_data_read) { - ret = (*asock->cb.on_data_read)(asock, r->pkt, r->size, - PJ_SUCCESS, &remainder); - } else if (asock->read_type == TYPE_RECV_FROM && - asock->cb.on_data_recvfrom) - { - ret = (*asock->cb.on_data_recvfrom)(asock, r->pkt, r->size, - &r->src_addr, - r->src_addr_len, - PJ_SUCCESS); - } - - /* If callback returns false, we have been destroyed! */ - if (!ret) - return; - - /* Only stream oriented socket may leave data in the packet */ - if (asock->stream_oriented) { - r->size = remainder; - } else { - r->size = 0; - } - - } else if (bytes_read <= 0 && - -bytes_read != PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK) && - -bytes_read != PJ_STATUS_FROM_OS(OSERR_EINPROGRESS) && - (asock->stream_oriented || - -bytes_read != PJ_STATUS_FROM_OS(OSERR_ECONNRESET))) - { - pj_size_t remainder; - pj_bool_t ret; - - if (bytes_read == 0) { - /* For stream/connection oriented socket, this means the - * connection has been closed. For datagram sockets, it means - * we've received datagram with zero length. - */ - if (asock->stream_oriented) - status = PJ_EEOF; - else - status = PJ_SUCCESS; - } else { - /* This means we've got an error. If this is stream/connection - * oriented, it means connection has been closed. For datagram - * sockets, it means we've got some error (e.g. EWOULDBLOCK). - */ - status = (pj_status_t)-bytes_read; - } - - /* Set default remainder to zero */ - remainder = 0; - - /* And return value to TRUE */ - ret = PJ_TRUE; - - /* Notify callback */ - if (asock->read_type == TYPE_RECV && asock->cb.on_data_read) { - /* For connection oriented socket, we still need to report - * the remainder data (if any) to the user to let user do - * processing with the remainder data before it closes the - * connection. - * If there is no remainder data, set the packet to NULL. - */ - - /* Shouldn't set the packet to NULL, as there may be active - * socket user, such as SSL socket, that needs to have access - * to the read buffer packet. - */ - //ret = (*asock->cb.on_data_read)(asock, (r->size? r->pkt:NULL), - // r->size, status, &remainder); - ret = (*asock->cb.on_data_read)(asock, r->pkt, r->size, - status, &remainder); - - } else if (asock->read_type == TYPE_RECV_FROM && - asock->cb.on_data_recvfrom) - { - /* This would always be datagram oriented hence there's - * nothing in the packet. We can't be sure if there will be - * anything useful in the source_addr, so just put NULL - * there too. - */ - /* In some scenarios, status may be PJ_SUCCESS. The upper - * layer application may not expect the callback to be called - * with successful status and NULL data, so lets not call the - * callback if the status is PJ_SUCCESS. - */ - if (status != PJ_SUCCESS ) { - ret = (*asock->cb.on_data_recvfrom)(asock, NULL, 0, - NULL, 0, status); - } - } - - /* If callback returns false, we have been destroyed! */ - if (!ret) - return; - - /* Also stop further read if we've been shutdown */ - if (asock->shutdown & SHUT_RX) - return; - - /* Only stream oriented socket may leave data in the packet */ - if (asock->stream_oriented) { - r->size = remainder; - } else { - r->size = 0; - } - } - - /* Read next data. We limit ourselves to processing max_loop immediate - * data, so when the loop counter has exceeded this value, force the - * read()/recvfrom() to return pending operation to allow the program - * to do other jobs. - */ - bytes_read = r->max_size - r->size; - flags = asock->read_flags; - if (++loop >= asock->max_loop) - flags |= PJ_IOQUEUE_ALWAYS_ASYNC; - - if (asock->read_type == TYPE_RECV) { - status = pj_ioqueue_recv(key, op_key, r->pkt + r->size, - &bytes_read, flags); - } else { - r->src_addr_len = sizeof(r->src_addr); - status = pj_ioqueue_recvfrom(key, op_key, r->pkt + r->size, - &bytes_read, flags, - &r->src_addr, &r->src_addr_len); - } - - if (status == PJ_SUCCESS) { - /* Immediate data */ - ; - } else if (status != PJ_EPENDING && status != PJ_ECANCELLED) { - /* Error */ - bytes_read = -status; - } else { - break; - } + unsigned flags; + + if (bytes_read > 0) { + /* + * We've got new data. + */ + pj_size_t remainder; + pj_bool_t ret; + + /* Append this new data to existing data. If socket is stream + * oriented, user might have left some data in the buffer. + * Otherwise if socket is datagram there will be nothing in + * existing packet hence the packet will contain only the new + * packet. + */ + r->size += bytes_read; + + /* Set default remainder to zero */ + remainder = 0; + + /* And return value to TRUE */ + ret = PJ_TRUE; + + /* Notify callback */ + if (asock->read_type == TYPE_RECV && asock->cb.on_data_read) { + ret = (*asock->cb.on_data_read)(asock, r->pkt, r->size, + PJ_SUCCESS, &remainder); + } else if (asock->read_type == TYPE_RECV_FROM && + asock->cb.on_data_recvfrom) + { + ret = (*asock->cb.on_data_recvfrom)(asock, r->pkt, r->size, + &r->src_addr, + r->src_addr_len, + PJ_SUCCESS); + } + + /* If callback returns false, we have been destroyed! */ + if (!ret) + return; + + /* Only stream oriented socket may leave data in the packet */ + if (asock->stream_oriented) { + r->size = remainder; + } else { + r->size = 0; + } + + } else if (bytes_read <= 0 && + -bytes_read != PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK) && + -bytes_read != PJ_STATUS_FROM_OS(OSERR_EINPROGRESS) && + (asock->stream_oriented || + -bytes_read != PJ_STATUS_FROM_OS(OSERR_ECONNRESET))) + { + pj_size_t remainder; + pj_bool_t ret; + + if (bytes_read == 0) { + /* For stream/connection oriented socket, this means the + * connection has been closed. For datagram sockets, it means + * we've received datagram with zero length. + */ + if (asock->stream_oriented) + status = PJ_EEOF; + else + status = PJ_SUCCESS; + } else { + /* This means we've got an error. If this is stream/connection + * oriented, it means connection has been closed. For datagram + * sockets, it means we've got some error (e.g. EWOULDBLOCK). + */ + status = (pj_status_t)-bytes_read; + } + + /* Set default remainder to zero */ + remainder = 0; + + /* And return value to TRUE */ + ret = PJ_TRUE; + + /* Notify callback */ + if (asock->read_type == TYPE_RECV && asock->cb.on_data_read) { + /* For connection oriented socket, we still need to report + * the remainder data (if any) to the user to let user do + * processing with the remainder data before it closes the + * connection. + * If there is no remainder data, set the packet to NULL. + */ + + /* Shouldn't set the packet to NULL, as there may be active + * socket user, such as SSL socket, that needs to have access + * to the read buffer packet. + */ + //ret = (*asock->cb.on_data_read)(asock, (r->size? r->pkt:NULL), + // r->size, status, &remainder); + ret = (*asock->cb.on_data_read)(asock, r->pkt, r->size, + status, &remainder); + + } else if (asock->read_type == TYPE_RECV_FROM && + asock->cb.on_data_recvfrom) + { + /* This would always be datagram oriented hence there's + * nothing in the packet. We can't be sure if there will be + * anything useful in the source_addr, so just put NULL + * there too. + */ + /* In some scenarios, status may be PJ_SUCCESS. The upper + * layer application may not expect the callback to be called + * with successful status and NULL data, so lets not call the + * callback if the status is PJ_SUCCESS. + */ + if (status != PJ_SUCCESS ) { + ret = (*asock->cb.on_data_recvfrom)(asock, NULL, 0, + NULL, 0, status); + } + } + + /* If callback returns false, we have been destroyed! */ + if (!ret) + return; + + /* Also stop further read if we've been shutdown */ + if (asock->shutdown & SHUT_RX) + return; + + /* Only stream oriented socket may leave data in the packet */ + if (asock->stream_oriented) { + r->size = remainder; + } else { + r->size = 0; + } + } + + /* Read next data. We limit ourselves to processing max_loop immediate + * data, so when the loop counter has exceeded this value, force the + * read()/recvfrom() to return pending operation to allow the program + * to do other jobs. + */ + bytes_read = r->max_size - r->size; + flags = asock->read_flags; + if (++loop >= asock->max_loop) + flags |= PJ_IOQUEUE_ALWAYS_ASYNC; + + if (asock->read_type == TYPE_RECV) { + status = pj_ioqueue_recv(key, op_key, r->pkt + r->size, + &bytes_read, flags); + } else { + r->src_addr_len = sizeof(r->src_addr); + status = pj_ioqueue_recvfrom(key, op_key, r->pkt + r->size, + &bytes_read, flags, + &r->src_addr, &r->src_addr_len); + } + + if (status == PJ_SUCCESS) { + /* Immediate data */ + ; + } else if (status != PJ_EPENDING && status != PJ_ECANCELLED) { + /* Error */ + bytes_read = -status; + } else { + break; + } } while (1); } static pj_status_t send_remaining(pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key) + pj_ioqueue_op_key_t *send_key) { struct send_data *sd = (struct send_data*)send_key->activesock_data; pj_status_t status; do { - pj_ssize_t size; - - size = sd->len - sd->sent; - status = pj_ioqueue_send(asock->key, send_key, - sd->data+sd->sent, &size, sd->flags); - if (status != PJ_SUCCESS) { - /* Pending or error */ - break; - } - - sd->sent += size; - if (sd->sent == sd->len) { - /* The whole data has been sent. */ - return PJ_SUCCESS; - } + pj_ssize_t size; + + size = sd->len - sd->sent; + status = pj_ioqueue_send(asock->key, send_key, + sd->data+sd->sent, &size, sd->flags); + if (status != PJ_SUCCESS) { + /* Pending or error */ + break; + } + + sd->sent += size; + if (sd->sent == sd->len) { + /* The whole data has been sent. */ + return PJ_SUCCESS; + } } while (sd->sent < sd->len); @@ -672,77 +671,77 @@ static pj_status_t send_remaining(pj_activesock_t *asock, PJ_DEF(pj_status_t) pj_activesock_send( pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t *size, - unsigned flags) + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t *size, + unsigned flags) { PJ_ASSERT_RETURN(asock && send_key && data && size, PJ_EINVAL); if (asock->shutdown & SHUT_TX) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; send_key->activesock_data = NULL; if (asock->whole_data) { - pj_ssize_t whole; - pj_status_t status; - - whole = *size; - - status = pj_ioqueue_send(asock->key, send_key, data, size, flags); - if (status != PJ_SUCCESS) { - /* Pending or error */ - return status; - } - - if (*size == whole) { - /* The whole data has been sent. */ - return PJ_SUCCESS; - } - - /* Data was partially sent */ - asock->send_data.data = (pj_uint8_t*)data; - asock->send_data.len = whole; - asock->send_data.sent = *size; - asock->send_data.flags = flags; - send_key->activesock_data = &asock->send_data; - - /* Try again */ - status = send_remaining(asock, send_key); - if (status == PJ_SUCCESS) { - *size = whole; - } - return status; + pj_ssize_t whole; + pj_status_t status; + + whole = *size; + + status = pj_ioqueue_send(asock->key, send_key, data, size, flags); + if (status != PJ_SUCCESS) { + /* Pending or error */ + return status; + } + + if (*size == whole) { + /* The whole data has been sent. */ + return PJ_SUCCESS; + } + + /* Data was partially sent */ + asock->send_data.data = (pj_uint8_t*)data; + asock->send_data.len = whole; + asock->send_data.sent = *size; + asock->send_data.flags = flags; + send_key->activesock_data = &asock->send_data; + + /* Try again */ + status = send_remaining(asock, send_key); + if (status == PJ_SUCCESS) { + *size = whole; + } + return status; } else { - return pj_ioqueue_send(asock->key, send_key, data, size, flags); + return pj_ioqueue_send(asock->key, send_key, data, size, flags); } } PJ_DEF(pj_status_t) pj_activesock_sendto( pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t *size, - unsigned flags, - const pj_sockaddr_t *addr, - int addr_len) + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t *size, + unsigned flags, + const pj_sockaddr_t *addr, + int addr_len) { PJ_ASSERT_RETURN(asock && send_key && data && size && addr && addr_len, - PJ_EINVAL); + PJ_EINVAL); if (asock->shutdown & SHUT_TX) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; return pj_ioqueue_sendto(asock->key, send_key, data, size, flags, - addr, addr_len); + addr, addr_len); } static void ioqueue_on_write_complete(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_sent) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_sent) { pj_activesock_t *asock; @@ -753,47 +752,47 @@ static void ioqueue_on_write_complete(pj_ioqueue_key_t *key, * buffer. */ if (asock->shutdown & SHUT_TX) - return; + return; if (bytes_sent > 0 && op_key->activesock_data) { - /* whole_data is requested. Make sure we send all the data */ - struct send_data *sd = (struct send_data*)op_key->activesock_data; - - sd->sent += bytes_sent; - if (sd->sent == sd->len) { - /* all has been sent */ - bytes_sent = sd->sent; - op_key->activesock_data = NULL; - } else { - /* send remaining data */ - pj_status_t status; - - status = send_remaining(asock, op_key); - if (status == PJ_EPENDING) - return; - else if (status == PJ_SUCCESS) - bytes_sent = sd->sent; - else - bytes_sent = -status; - - op_key->activesock_data = NULL; - } + /* whole_data is requested. Make sure we send all the data */ + struct send_data *sd = (struct send_data*)op_key->activesock_data; + + sd->sent += bytes_sent; + if (sd->sent == sd->len) { + /* all has been sent */ + bytes_sent = sd->sent; + op_key->activesock_data = NULL; + } else { + /* send remaining data */ + pj_status_t status; + + status = send_remaining(asock, op_key); + if (status == PJ_EPENDING) + return; + else if (status == PJ_SUCCESS) + bytes_sent = sd->sent; + else + bytes_sent = -status; + + op_key->activesock_data = NULL; + } } if (asock->cb.on_data_sent) { - pj_bool_t ret; + pj_bool_t ret; - ret = (*asock->cb.on_data_sent)(asock, op_key, bytes_sent); + ret = (*asock->cb.on_data_sent)(asock, op_key, bytes_sent); - /* If callback returns false, we have been destroyed! */ - if (!ret) - return; + /* If callback returns false, we have been destroyed! */ + if (!ret) + return; } } #if PJ_HAS_TCP PJ_DEF(pj_status_t) pj_activesock_start_accept(pj_activesock_t *asock, - pj_pool_t *pool) + pj_pool_t *pool) { unsigned i; @@ -802,34 +801,34 @@ PJ_DEF(pj_status_t) pj_activesock_start_accept(pj_activesock_t *asock, /* Ignore if we've been shutdown */ if (asock->shutdown) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; asock->accept_op = (struct accept_op*) - pj_pool_calloc(pool, asock->async_count, - sizeof(struct accept_op)); + pj_pool_calloc(pool, asock->async_count, + sizeof(struct accept_op)); for (i=0; iasync_count; ++i) { - struct accept_op *a = &asock->accept_op[i]; - pj_status_t status; - - do { - a->new_sock = PJ_INVALID_SOCKET; - a->rem_addr_len = sizeof(a->rem_addr); - - status = pj_ioqueue_accept(asock->key, &a->op_key, &a->new_sock, - NULL, &a->rem_addr, &a->rem_addr_len); - if (status == PJ_SUCCESS) { - /* We've got immediate connection. Not sure if it's a good - * idea to call the callback now (probably application will - * not be prepared to process it), so lets just silently - * close the socket. - */ - pj_sock_close(a->new_sock); - } - } while (status == PJ_SUCCESS); - - if (status != PJ_EPENDING) { - return status; - } + struct accept_op *a = &asock->accept_op[i]; + pj_status_t status; + + do { + a->new_sock = PJ_INVALID_SOCKET; + a->rem_addr_len = sizeof(a->rem_addr); + + status = pj_ioqueue_accept(asock->key, &a->op_key, &a->new_sock, + NULL, &a->rem_addr, &a->rem_addr_len); + if (status == PJ_SUCCESS) { + /* We've got immediate connection. Not sure if it's a good + * idea to call the callback now (probably application will + * not be prepared to process it), so lets just silently + * close the socket. + */ + pj_sock_close(a->new_sock); + } + } while (status == PJ_SUCCESS); + + if (status != PJ_EPENDING) { + return status; + } } return PJ_SUCCESS; @@ -837,9 +836,9 @@ PJ_DEF(pj_status_t) pj_activesock_start_accept(pj_activesock_t *asock, static void ioqueue_on_accept_complete(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_sock_t new_sock, - pj_status_t status) + pj_ioqueue_op_key_t *op_key, + pj_sock_t new_sock, + pj_status_t status) { pj_activesock_t *asock = (pj_activesock_t*) pj_ioqueue_get_user_data(key); struct accept_op *accept_op = (struct accept_op*) op_key; @@ -848,119 +847,119 @@ static void ioqueue_on_accept_complete(pj_ioqueue_key_t *key, /* Ignore if we've been shutdown */ if (asock->shutdown) - return; + return; do { - if (status == asock->last_err && status != PJ_SUCCESS) { - asock->err_counter++; - if (asock->err_counter >= PJ_ACTIVESOCK_MAX_CONSECUTIVE_ACCEPT_ERROR) { - PJ_LOG(3, ("", "Received %d consecutive errors: %d for the accept()" - " operation, stopping further ioqueue accepts.", - asock->err_counter, asock->last_err)); - - if ((status == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK)) && - (asock->cb.on_accept_complete2)) - { - (*asock->cb.on_accept_complete2)(asock, - accept_op->new_sock, - &accept_op->rem_addr, - accept_op->rem_addr_len, - PJ_ESOCKETSTOP); - } - return; - } - } else { - asock->err_counter = 0; - asock->last_err = status; - } - - if (status==PJ_SUCCESS && (asock->cb.on_accept_complete2 || - asock->cb.on_accept_complete)) { - pj_bool_t ret; - - /* Notify callback */ - if (asock->cb.on_accept_complete2) { - ret = (*asock->cb.on_accept_complete2)(asock, - accept_op->new_sock, - &accept_op->rem_addr, - accept_op->rem_addr_len, - status); - } else { - ret = (*asock->cb.on_accept_complete)(asock, - accept_op->new_sock, - &accept_op->rem_addr, - accept_op->rem_addr_len); - } - - /* If callback returns false, we have been destroyed! */ - if (!ret) - return; + if (status == asock->last_err && status != PJ_SUCCESS) { + asock->err_counter++; + if (asock->err_counter >= PJ_ACTIVESOCK_MAX_CONSECUTIVE_ACCEPT_ERROR) { + PJ_LOG(3, ("", "Received %d consecutive errors: %d for the accept()" + " operation, stopping further ioqueue accepts.", + asock->err_counter, asock->last_err)); + + if ((status == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK)) && + (asock->cb.on_accept_complete2)) + { + (*asock->cb.on_accept_complete2)(asock, + accept_op->new_sock, + &accept_op->rem_addr, + accept_op->rem_addr_len, + PJ_ESOCKETSTOP); + } + return; + } + } else { + asock->err_counter = 0; + asock->last_err = status; + } + + if (status==PJ_SUCCESS && (asock->cb.on_accept_complete2 || + asock->cb.on_accept_complete)) { + pj_bool_t ret; + + /* Notify callback */ + if (asock->cb.on_accept_complete2) { + ret = (*asock->cb.on_accept_complete2)(asock, + accept_op->new_sock, + &accept_op->rem_addr, + accept_op->rem_addr_len, + status); + } else { + ret = (*asock->cb.on_accept_complete)(asock, + accept_op->new_sock, + &accept_op->rem_addr, + accept_op->rem_addr_len); + } + + /* If callback returns false, we have been destroyed! */ + if (!ret) + return; #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 - activesock_create_iphone_os_stream(asock); + activesock_create_iphone_os_stream(asock); #endif - } else if (status==PJ_SUCCESS) { - /* Application doesn't handle the new socket, we need to - * close it to avoid resource leak. - */ - pj_sock_close(accept_op->new_sock); - } + } else if (status==PJ_SUCCESS) { + /* Application doesn't handle the new socket, we need to + * close it to avoid resource leak. + */ + pj_sock_close(accept_op->new_sock); + } - /* Don't start another accept() if we've been shutdown */ - if (asock->shutdown) - return; + /* Don't start another accept() if we've been shutdown */ + if (asock->shutdown) + return; - /* Prepare next accept() */ - accept_op->new_sock = PJ_INVALID_SOCKET; - accept_op->rem_addr_len = sizeof(accept_op->rem_addr); + /* Prepare next accept() */ + accept_op->new_sock = PJ_INVALID_SOCKET; + accept_op->rem_addr_len = sizeof(accept_op->rem_addr); - status = pj_ioqueue_accept(asock->key, op_key, &accept_op->new_sock, - NULL, &accept_op->rem_addr, - &accept_op->rem_addr_len); + status = pj_ioqueue_accept(asock->key, op_key, &accept_op->new_sock, + NULL, &accept_op->rem_addr, + &accept_op->rem_addr_len); } while (status != PJ_EPENDING && status != PJ_ECANCELLED); } PJ_DEF(pj_status_t) pj_activesock_start_connect( pj_activesock_t *asock, - pj_pool_t *pool, - const pj_sockaddr_t *remaddr, - int addr_len) + pj_pool_t *pool, + const pj_sockaddr_t *remaddr, + int addr_len) { PJ_UNUSED_ARG(pool); if (asock->shutdown) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; return pj_ioqueue_connect(asock->key, remaddr, addr_len); } static void ioqueue_on_connect_complete(pj_ioqueue_key_t *key, - pj_status_t status) + pj_status_t status) { pj_activesock_t *asock = (pj_activesock_t*) pj_ioqueue_get_user_data(key); /* Ignore if we've been shutdown */ if (asock->shutdown) - return; + return; if (asock->cb.on_connect_complete) { - pj_bool_t ret; + pj_bool_t ret; - ret = (*asock->cb.on_connect_complete)(asock, status); + ret = (*asock->cb.on_connect_complete)(asock, status); - if (!ret) { - /* We've been destroyed */ - return; - } - + if (!ret) { + /* We've been destroyed */ + return; + } + #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 - activesock_create_iphone_os_stream(asock); + activesock_create_iphone_os_stream(asock); #endif - + } } -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ diff --git a/pjlib/src/pj/addr_resolv_sock.c b/pjlib/src/pj/addr_resolv_sock.c index 0954f2ee0a..8142212891 100644 --- a/pjlib/src/pj/addr_resolv_sock.c +++ b/pjlib/src/pj/addr_resolv_sock.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -37,18 +36,18 @@ PJ_DEF(pj_status_t) pj_gethostbyname(const pj_str_t *hostname, pj_hostent *phe) pj_assert(hostname && hostname ->slen < PJ_MAX_HOSTNAME); if (hostname->slen >= PJ_MAX_HOSTNAME) - return PJ_ENAMETOOLONG; + return PJ_ENAMETOOLONG; pj_memcpy(copy, hostname->ptr, hostname->slen); copy[ hostname->slen ] = '\0'; he = gethostbyname(copy); if (!he) { - return PJ_ERESOLVE; - /* DO NOT use pj_get_netos_error() since host resolution error - * is reported in h_errno instead of errno! - return pj_get_netos_error(); - */ + return PJ_ERESOLVE; + /* DO NOT use pj_get_netos_error() since host resolution error + * is reported in h_errno instead of errno! + return pj_get_netos_error(); + */ } phe->h_name = he->h_name; @@ -62,7 +61,7 @@ PJ_DEF(pj_status_t) pj_gethostbyname(const pj_str_t *hostname, pj_hostent *phe) /* Resolve IPv4/IPv6 address */ PJ_DEF(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *nodename, - unsigned *count, pj_addrinfo ai[]) + unsigned *count, pj_addrinfo ai[]) { #if defined(PJ_SOCK_HAS_GETADDRINFO) && PJ_SOCK_HAS_GETADDRINFO!=0 char nodecopy[PJ_MAX_HOSTNAME]; @@ -80,35 +79,35 @@ PJ_DEF(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *nodename, PJ_ASSERT_RETURN(nodename && count && *count && ai, PJ_EINVAL); PJ_ASSERT_RETURN(nodename->ptr && nodename->slen, PJ_EINVAL); PJ_ASSERT_RETURN(af==PJ_AF_INET || af==PJ_AF_INET6 || - af==PJ_AF_UNSPEC, PJ_EINVAL); + af==PJ_AF_UNSPEC, PJ_EINVAL); #if PJ_WIN32_WINCE /* Check if nodename is IP address */ pj_bzero(&ai[0], sizeof(ai[0])); if ((af==PJ_AF_INET || af==PJ_AF_UNSPEC) && - pj_inet_pton(PJ_AF_INET, nodename, - &ai[0].ai_addr.ipv4.sin_addr) == PJ_SUCCESS) + pj_inet_pton(PJ_AF_INET, nodename, + &ai[0].ai_addr.ipv4.sin_addr) == PJ_SUCCESS) { - af = PJ_AF_INET; - has_addr = PJ_TRUE; + af = PJ_AF_INET; + has_addr = PJ_TRUE; } else if ((af==PJ_AF_INET6 || af==PJ_AF_UNSPEC) && - pj_inet_pton(PJ_AF_INET6, nodename, - &ai[0].ai_addr.ipv6.sin6_addr) == PJ_SUCCESS) + pj_inet_pton(PJ_AF_INET6, nodename, + &ai[0].ai_addr.ipv6.sin6_addr) == PJ_SUCCESS) { - af = PJ_AF_INET6; - has_addr = PJ_TRUE; + af = PJ_AF_INET6; + has_addr = PJ_TRUE; } if (has_addr) { - pj_str_t tmp; + pj_str_t tmp; - tmp.ptr = ai[0].ai_canonname; - pj_strncpy_with_null(&tmp, nodename, PJ_MAX_HOSTNAME); - ai[0].ai_addr.addr.sa_family = (pj_uint16_t)af; - *count = 1; + tmp.ptr = ai[0].ai_canonname; + pj_strncpy_with_null(&tmp, nodename, PJ_MAX_HOSTNAME); + ai[0].ai_addr.addr.sa_family = (pj_uint16_t)af; + *count = 1; - return PJ_SUCCESS; + return PJ_SUCCESS; } #else /* PJ_WIN32_WINCE */ @@ -117,57 +116,57 @@ PJ_DEF(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *nodename, /* Copy node name to null terminated string. */ if (nodename->slen >= PJ_MAX_HOSTNAME) - return PJ_ENAMETOOLONG; + return PJ_ENAMETOOLONG; pj_memcpy(nodecopy, nodename->ptr, nodename->slen); nodecopy[nodename->slen] = '\0'; #if defined(PJ_GETADDRINFO_USE_CFHOST) && PJ_GETADDRINFO_USE_CFHOST!=0 hostname = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, nodecopy, - kCFStringEncodingASCII, - kCFAllocatorNull); + kCFStringEncodingASCII, + kCFAllocatorNull); hostRef = CFHostCreateWithName(kCFAllocatorDefault, hostname); if (CFHostStartInfoResolution(hostRef, kCFHostAddresses, nil)) { - CFArrayRef addrRef = CFHostGetAddressing(hostRef, nil); - i = 0; - if (addrRef != nil) { - CFIndex idx, naddr; - - naddr = CFArrayGetCount(addrRef); - for (idx = 0; idx < naddr && i < *count; idx++) { - struct sockaddr *addr; - size_t addr_size; - - addr = (struct sockaddr *) - CFDataGetBytePtr(CFArrayGetValueAtIndex(addrRef, idx)); - /* This should not happen. */ - pj_assert(addr); - - /* Ignore unwanted address families */ - if (af!=PJ_AF_UNSPEC && addr->sa_family != af) - continue; - - /* Store canonical name */ - pj_ansi_strcpy(ai[i].ai_canonname, nodecopy); - - /* Store address */ - addr_size = sizeof(*addr); - if (addr->sa_family == PJ_AF_INET6) { - addr_size = addr->sa_len; - } - PJ_ASSERT_ON_FAIL(addr_size <= sizeof(pj_sockaddr), continue); - pj_memcpy(&ai[i].ai_addr, addr, addr_size); - PJ_SOCKADDR_RESET_LEN(&ai[i].ai_addr); - - i++; - } - } - - *count = i; - if (*count == 0) - status = PJ_ERESOLVE; + CFArrayRef addrRef = CFHostGetAddressing(hostRef, nil); + i = 0; + if (addrRef != nil) { + CFIndex idx, naddr; + + naddr = CFArrayGetCount(addrRef); + for (idx = 0; idx < naddr && i < *count; idx++) { + struct sockaddr *addr; + size_t addr_size; + + addr = (struct sockaddr *) + CFDataGetBytePtr(CFArrayGetValueAtIndex(addrRef, idx)); + /* This should not happen. */ + pj_assert(addr); + + /* Ignore unwanted address families */ + if (af!=PJ_AF_UNSPEC && addr->sa_family != af) + continue; + + /* Store canonical name */ + pj_ansi_strcpy(ai[i].ai_canonname, nodecopy); + + /* Store address */ + addr_size = sizeof(*addr); + if (addr->sa_family == PJ_AF_INET6) { + addr_size = addr->sa_len; + } + PJ_ASSERT_ON_FAIL(addr_size <= sizeof(pj_sockaddr), continue); + pj_memcpy(&ai[i].ai_addr, addr, addr_size); + PJ_SOCKADDR_RESET_LEN(&ai[i].ai_addr); + + i++; + } + } + + *count = i; + if (*count == 0) + status = PJ_ERESOLVE; } else { - status = PJ_ERESOLVE; + status = PJ_ERESOLVE; } CFRelease(hostRef); @@ -184,57 +183,57 @@ PJ_DEF(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *nodename, rc = getaddrinfo(nodecopy, NULL, &hint, &res); if (rc != 0) - return PJ_ERESOLVE; + return PJ_ERESOLVE; orig_res = res; /* Enumerate each item in the result */ for (i=0; i<*count && res; res=res->ai_next) { - unsigned j; - pj_bool_t duplicate_found = PJ_FALSE; + unsigned j; + pj_bool_t duplicate_found = PJ_FALSE; - /* Ignore unwanted address families */ - if (af!=PJ_AF_UNSPEC && res->ai_family != af) - continue; + /* Ignore unwanted address families */ + if (af!=PJ_AF_UNSPEC && res->ai_family != af) + continue; - if (res->ai_socktype != pj_SOCK_DGRAM() && + if (res->ai_socktype != pj_SOCK_DGRAM() && res->ai_socktype != pj_SOCK_STREAM() && /* It is possible that the result's sock type * is unspecified. */ res->ai_socktype != 0) { - continue; - } - - /* Add current address in the resulting list if there - * is no duplicates only. */ - for (j = 0; j < i; j++) { - if (!pj_sockaddr_cmp(&ai[j].ai_addr, res->ai_addr)) { - duplicate_found = PJ_TRUE; - break; - } - } - if (duplicate_found) { - continue; - } - - /* Store canonical name (possibly truncating the name) */ - if (res->ai_canonname) { - pj_ansi_strncpy(ai[i].ai_canonname, res->ai_canonname, - sizeof(ai[i].ai_canonname)); - ai[i].ai_canonname[sizeof(ai[i].ai_canonname)-1] = '\0'; - } else { - pj_ansi_strcpy(ai[i].ai_canonname, nodecopy); - } - - /* Store address */ - PJ_ASSERT_ON_FAIL(res->ai_addrlen <= sizeof(pj_sockaddr), continue); - pj_memcpy(&ai[i].ai_addr, res->ai_addr, res->ai_addrlen); - PJ_SOCKADDR_RESET_LEN(&ai[i].ai_addr); - - /* Next slot */ - ++i; + continue; + } + + /* Add current address in the resulting list if there + * is no duplicates only. */ + for (j = 0; j < i; j++) { + if (!pj_sockaddr_cmp(&ai[j].ai_addr, res->ai_addr)) { + duplicate_found = PJ_TRUE; + break; + } + } + if (duplicate_found) { + continue; + } + + /* Store canonical name (possibly truncating the name) */ + if (res->ai_canonname) { + pj_ansi_strncpy(ai[i].ai_canonname, res->ai_canonname, + sizeof(ai[i].ai_canonname)); + ai[i].ai_canonname[sizeof(ai[i].ai_canonname)-1] = '\0'; + } else { + pj_ansi_strcpy(ai[i].ai_canonname, nodecopy); + } + + /* Store address */ + PJ_ASSERT_ON_FAIL(res->ai_addrlen <= sizeof(pj_sockaddr), continue); + pj_memcpy(&ai[i].ai_addr, res->ai_addr, res->ai_addrlen); + PJ_SOCKADDR_RESET_LEN(&ai[i].ai_addr); + + /* Next slot */ + ++i; } *count = i; @@ -245,7 +244,7 @@ PJ_DEF(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *nodename, return (*count > 0? PJ_SUCCESS : PJ_ERESOLVE); #endif -#else /* PJ_SOCK_HAS_GETADDRINFO */ +#else /* PJ_SOCK_HAS_GETADDRINFO */ pj_bool_t has_addr = PJ_FALSE; PJ_ASSERT_RETURN(count && *count, PJ_EINVAL); @@ -255,29 +254,29 @@ PJ_DEF(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *nodename, /* Check if nodename is IP address */ pj_bzero(&ai[0], sizeof(ai[0])); if ((af==PJ_AF_INET || af==PJ_AF_UNSPEC) && - pj_inet_pton(PJ_AF_INET, nodename, - &ai[0].ai_addr.ipv4.sin_addr) == PJ_SUCCESS) + pj_inet_pton(PJ_AF_INET, nodename, + &ai[0].ai_addr.ipv4.sin_addr) == PJ_SUCCESS) { - af = PJ_AF_INET; - has_addr = PJ_TRUE; + af = PJ_AF_INET; + has_addr = PJ_TRUE; } else if ((af==PJ_AF_INET6 || af==PJ_AF_UNSPEC) && - pj_inet_pton(PJ_AF_INET6, nodename, - &ai[0].ai_addr.ipv6.sin6_addr) == PJ_SUCCESS) + pj_inet_pton(PJ_AF_INET6, nodename, + &ai[0].ai_addr.ipv6.sin6_addr) == PJ_SUCCESS) { - af = PJ_AF_INET6; - has_addr = PJ_TRUE; + af = PJ_AF_INET6; + has_addr = PJ_TRUE; } if (has_addr) { - pj_str_t tmp; + pj_str_t tmp; - tmp.ptr = ai[0].ai_canonname; - pj_strncpy_with_null(&tmp, nodename, PJ_MAX_HOSTNAME); - ai[0].ai_addr.addr.sa_family = (pj_uint16_t)af; - *count = 1; + tmp.ptr = ai[0].ai_canonname; + pj_strncpy_with_null(&tmp, nodename, PJ_MAX_HOSTNAME); + ai[0].ai_addr.addr.sa_family = (pj_uint16_t)af; + *count = 1; - return PJ_SUCCESS; + return PJ_SUCCESS; } #else /* PJ_WIN32_WINCE */ @@ -285,45 +284,45 @@ PJ_DEF(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *nodename, #endif if (af == PJ_AF_INET || af == PJ_AF_UNSPEC) { - pj_hostent he; - unsigned i, max_count; - pj_status_t status; - - /* VC6 complains that "he" is uninitialized */ - #ifdef _MSC_VER - pj_bzero(&he, sizeof(he)); - #endif + pj_hostent he; + unsigned i, max_count; + pj_status_t status; + + /* VC6 complains that "he" is uninitialized */ + #ifdef _MSC_VER + pj_bzero(&he, sizeof(he)); + #endif - status = pj_gethostbyname(nodename, &he); - if (status != PJ_SUCCESS) - return status; + status = pj_gethostbyname(nodename, &he); + if (status != PJ_SUCCESS) + return status; - max_count = *count; - *count = 0; + max_count = *count; + *count = 0; - pj_bzero(ai, max_count * sizeof(pj_addrinfo)); + pj_bzero(ai, max_count * sizeof(pj_addrinfo)); - for (i=0; he.h_addr_list[i] && *count 0? PJ_SUCCESS : PJ_ERESOLVE); + return (*count > 0? PJ_SUCCESS : PJ_ERESOLVE); } else { - /* IPv6 is not supported */ - *count = 0; + /* IPv6 is not supported */ + *count = 0; - return PJ_EIPV6NOTSUP; + return PJ_EIPV6NOTSUP; } -#endif /* PJ_SOCK_HAS_GETADDRINFO */ +#endif /* PJ_SOCK_HAS_GETADDRINFO */ } diff --git a/pjlib/src/pj/addr_resolv_symbian.cpp b/pjlib/src/pj/addr_resolv_symbian.cpp index 924155f101..32981a9d4e 100644 --- a/pjlib/src/pj/addr_resolv_symbian.cpp +++ b/pjlib/src/pj/addr_resolv_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,8 +27,8 @@ #include "os_symbian.h" -#define THIS_FILE "addr_resolv_symbian.cpp" -#define TRACE_ME 0 +#define THIS_FILE "addr_resolv_symbian.cpp" +#define TRACE_ME 0 // PJLIB API: resolve hostname @@ -43,7 +42,7 @@ PJ_DEF(pj_status_t) pj_gethostbyname(const pj_str_t *name, pj_hostent *he) status = pj_getaddrinfo(PJ_AF_INET, name, &count, &ai); if (status != PJ_SUCCESS) - return status; + return status; aliases[0] = ai.ai_canonname; aliases[1] = NULL; @@ -64,7 +63,7 @@ PJ_DEF(pj_status_t) pj_gethostbyname(const pj_str_t *name, pj_hostent *he) // Resolve for specific address family static pj_status_t getaddrinfo_by_af(int af, const pj_str_t *name, - unsigned *count, pj_addrinfo ai[]) + unsigned *count, pj_addrinfo ai[]) { unsigned i; pj_status_t status; @@ -73,9 +72,9 @@ static pj_status_t getaddrinfo_by_af(int af, const pj_str_t *name, #if !defined(PJ_HAS_IPV6) || !PJ_HAS_IPV6 if (af == PJ_AF_INET6) - return PJ_EIPV6NOTSUP; + return PJ_EIPV6NOTSUP; #endif - + // Return failure if access point is marked as down by app. PJ_SYMBIAN_CHECK_CONNECTION(); @@ -97,60 +96,60 @@ static pj_status_t getaddrinfo_by_af(int af, const pj_str_t *name, // Iterate each result i = 0; while (reqStatus == KErrNone && i < *count) { - - // Get the resolved TInetAddr - TInetAddr inetAddr(nameEntry().iAddr); - int addrlen; + + // Get the resolved TInetAddr + TInetAddr inetAddr(nameEntry().iAddr); + int addrlen; #if TRACE_ME - if (1) { - pj_sockaddr a; - char ipaddr[PJ_INET6_ADDRSTRLEN+2]; - int namelen; - - namelen = sizeof(pj_sockaddr); - if (PjSymbianOS::Addr2pj(inetAddr, a, &namelen, - PJ_FALSE) == PJ_SUCCESS) - { - PJ_LOG(5,(THIS_FILE, "resolve %.*s: %s", - (int)name->slen, name->ptr, - pj_sockaddr_print(&a, ipaddr, sizeof(ipaddr), 2))); - } - } + if (1) { + pj_sockaddr a; + char ipaddr[PJ_INET6_ADDRSTRLEN+2]; + int namelen; + + namelen = sizeof(pj_sockaddr); + if (PjSymbianOS::Addr2pj(inetAddr, a, &namelen, + PJ_FALSE) == PJ_SUCCESS) + { + PJ_LOG(5,(THIS_FILE, "resolve %.*s: %s", + (int)name->slen, name->ptr, + pj_sockaddr_print(&a, ipaddr, sizeof(ipaddr), 2))); + } + } #endif - - // Ignore if this is not the same address family - // Not a good idea, as Symbian mapps IPv4 to IPv6. - //fam = inetAddr.Family(); - //if (fam != af) { - // resv.Next(nameEntry, reqStatus); - // User::WaitForRequest(reqStatus); - // continue; - //} - - // Convert IP address first to get IPv4 mapped address - addrlen = sizeof(ai[i].ai_addr); - status = PjSymbianOS::Addr2pj(inetAddr, ai[i].ai_addr, - &addrlen, PJ_TRUE); - if (status != PJ_SUCCESS) - return status; - - // Ignore if address family doesn't match - if (ai[i].ai_addr.addr.sa_family != af) { - resv.Next(nameEntry, reqStatus); - User::WaitForRequest(reqStatus); - continue; - } + + // Ignore if this is not the same address family + // Not a good idea, as Symbian mapps IPv4 to IPv6. + //fam = inetAddr.Family(); + //if (fam != af) { + // resv.Next(nameEntry, reqStatus); + // User::WaitForRequest(reqStatus); + // continue; + //} + + // Convert IP address first to get IPv4 mapped address + addrlen = sizeof(ai[i].ai_addr); + status = PjSymbianOS::Addr2pj(inetAddr, ai[i].ai_addr, + &addrlen, PJ_TRUE); + if (status != PJ_SUCCESS) + return status; + + // Ignore if address family doesn't match + if (ai[i].ai_addr.addr.sa_family != af) { + resv.Next(nameEntry, reqStatus); + User::WaitForRequest(reqStatus); + continue; + } - // Convert the official address to ANSI. - pj_unicode_to_ansi((const wchar_t*)nameEntry().iName.Ptr(), - nameEntry().iName.Length(), - ai[i].ai_canonname, sizeof(ai[i].ai_canonname)); - - // Next - ++i; - resv.Next(nameEntry, reqStatus); - User::WaitForRequest(reqStatus); + // Convert the official address to ANSI. + pj_unicode_to_ansi((const wchar_t*)nameEntry().iName.Ptr(), + nameEntry().iName.Length(), + ai[i].ai_canonname, sizeof(ai[i].ai_canonname)); + + // Next + ++i; + resv.Next(nameEntry, reqStatus); + User::WaitForRequest(reqStatus); } *count = i; @@ -159,43 +158,43 @@ static pj_status_t getaddrinfo_by_af(int af, const pj_str_t *name, /* Resolve IPv4/IPv6 address */ PJ_DEF(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *nodename, - unsigned *count, pj_addrinfo ai[]) + unsigned *count, pj_addrinfo ai[]) { unsigned start; pj_status_t status = PJ_EAFNOTSUP; PJ_ASSERT_RETURN(af==PJ_AF_INET || af==PJ_AF_INET6 || af==PJ_AF_UNSPEC, - PJ_EAFNOTSUP); + PJ_EAFNOTSUP); PJ_ASSERT_RETURN(nodename && count && *count && ai, PJ_EINVAL); start = 0; if (af==PJ_AF_INET6 || af==PJ_AF_UNSPEC) { unsigned max = *count; - status = getaddrinfo_by_af(PJ_AF_INET6, nodename, - &max, &ai[start]); - if (status == PJ_SUCCESS) { - (*count) -= max; - start += max; - } + status = getaddrinfo_by_af(PJ_AF_INET6, nodename, + &max, &ai[start]); + if (status == PJ_SUCCESS) { + (*count) -= max; + start += max; + } } if (af==PJ_AF_INET || af==PJ_AF_UNSPEC) { unsigned max = *count; - status = getaddrinfo_by_af(PJ_AF_INET, nodename, - &max, &ai[start]); - if (status == PJ_SUCCESS) { - (*count) -= max; - start += max; - } + status = getaddrinfo_by_af(PJ_AF_INET, nodename, + &max, &ai[start]); + if (status == PJ_SUCCESS) { + (*count) -= max; + start += max; + } } *count = start; if (*count) { - return PJ_SUCCESS; + return PJ_SUCCESS; } else { - return status!=PJ_SUCCESS ? status : PJ_ENOTFOUND; + return status!=PJ_SUCCESS ? status : PJ_ENOTFOUND; } } diff --git a/pjlib/src/pj/array.c b/pjlib/src/pj/array.c index 2072a3d328..094ea1f01c 100644 --- a/pjlib/src/pj/array.c +++ b/pjlib/src/pj/array.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -23,48 +22,48 @@ #include PJ_DEF(void) pj_array_insert( void *array, - unsigned elem_size, - unsigned count, - unsigned pos, - const void *value) + unsigned elem_size, + unsigned count, + unsigned pos, + const void *value) { if (count && pos < count) { - pj_memmove( (char*)array + (pos+1)*elem_size, - (char*)array + pos*elem_size, - (count-pos)*(pj_size_t)elem_size); + pj_memmove( (char*)array + (pos+1)*elem_size, + (char*)array + pos*elem_size, + (count-pos)*(pj_size_t)elem_size); } pj_memmove((char*)array + pos*elem_size, value, elem_size); } PJ_DEF(void) pj_array_erase( void *array, - unsigned elem_size, - unsigned count, - unsigned pos) + unsigned elem_size, + unsigned count, + unsigned pos) { pj_assert(count != 0); if (pos < count-1) { - pj_memmove( (char*)array + pos*elem_size, - (char*)array + (pos+1)*elem_size, - (count-pos-1)*(pj_size_t)elem_size); + pj_memmove( (char*)array + pos*elem_size, + (char*)array + (pos+1)*elem_size, + (count-pos-1)*(pj_size_t)elem_size); } } PJ_DEF(pj_status_t) pj_array_find( const void *array, - unsigned elem_size, - unsigned count, - pj_status_t (*matching)(const void *value), - void **result) + unsigned elem_size, + unsigned count, + pj_status_t (*matching)(const void *value), + void **result) { unsigned i; const char *char_array = (const char*)array; for (i=0; i diff --git a/pjlib/src/pj/compat/string.c b/pjlib/src/pj/compat/string.c index 137691ebfe..61b9a1218c 100644 --- a/pjlib/src/pj/compat/string.c +++ b/pjlib/src/pj/compat/string.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,9 +23,9 @@ PJ_DEF(int) strcasecmp(const char *s1, const char *s2) { while ((*s1==*s2) || (pj_tolower(*s1)==pj_tolower(*s2))) { - if (!*s1++) - return 0; - ++s2; + if (!*s1++) + return 0; + ++s2; } return (pj_tolower(*s1) < pj_tolower(*s2)) ? -1 : 1; } @@ -36,9 +35,9 @@ PJ_DEF(int) strncasecmp(const char *s1, const char *s2, int len) if (!len) return 0; while ((*s1==*s2) || (pj_tolower(*s1)==pj_tolower(*s2))) { - if (!*s1++ || --len <= 0) - return 0; - ++s2; + if (!*s1++ || --len <= 0) + return 0; + ++s2; } return (pj_tolower(*s1) < pj_tolower(*s2)) ? -1 : 1; } diff --git a/pjlib/src/pj/compat/string_compat.c b/pjlib/src/pj/compat/string_compat.c index 64e917ad0f..58a07c978c 100644 --- a/pjlib/src/pj/compat/string_compat.c +++ b/pjlib/src/pj/compat/string_compat.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,9 +28,9 @@ PJ_DEF(int) strcasecmp(const char *s1, const char *s2) { while ((*s1==*s2) || (pj_tolower(*s1)==pj_tolower(*s2))) { - if (!*s1++) - return 0; - ++s2; + if (!*s1++) + return 0; + ++s2; } return (pj_tolower(*s1) < pj_tolower(*s2)) ? -1 : 1; } @@ -41,9 +40,9 @@ PJ_DEF(int) strncasecmp(const char *s1, const char *s2, int len) if (!len) return 0; while ((*s1==*s2) || (pj_tolower(*s1)==pj_tolower(*s2))) { - if (!*s1++ || --len <= 0) - return 0; - ++s2; + if (!*s1++ || --len <= 0) + return 0; + ++s2; } return (pj_tolower(*s1) < pj_tolower(*s2)) ? -1 : 1; } diff --git a/pjlib/src/pj/config.c b/pjlib/src/pj/config.c index 0c25d62ab6..081b4100e0 100644 --- a/pjlib/src/pj/config.c +++ b/pjlib/src/pj/config.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -23,21 +22,21 @@ static const char *id = "config.c"; -#define PJ_MAKE_VERSION3_1(a,b,d) #a "." #b d -#define PJ_MAKE_VERSION3_2(a,b,d) PJ_MAKE_VERSION3_1(a,b,d) +#define PJ_MAKE_VERSION3_1(a,b,d) #a "." #b d +#define PJ_MAKE_VERSION3_2(a,b,d) PJ_MAKE_VERSION3_1(a,b,d) -#define PJ_MAKE_VERSION4_1(a,b,c,d) #a "." #b "." #c d -#define PJ_MAKE_VERSION4_2(a,b,c,d) PJ_MAKE_VERSION4_1(a,b,c,d) +#define PJ_MAKE_VERSION4_1(a,b,c,d) #a "." #b "." #c d +#define PJ_MAKE_VERSION4_2(a,b,c,d) PJ_MAKE_VERSION4_1(a,b,c,d) #if PJ_VERSION_NUM_REV PJ_DEF_DATA(const char*) PJ_VERSION = PJ_MAKE_VERSION4_2(PJ_VERSION_NUM_MAJOR, - PJ_VERSION_NUM_MINOR, - PJ_VERSION_NUM_REV, - PJ_VERSION_NUM_EXTRA); + PJ_VERSION_NUM_MINOR, + PJ_VERSION_NUM_REV, + PJ_VERSION_NUM_EXTRA); #else PJ_DEF_DATA(const char*) PJ_VERSION = PJ_MAKE_VERSION3_2(PJ_VERSION_NUM_MAJOR, - PJ_VERSION_NUM_MINOR, - PJ_VERSION_NUM_EXTRA); + PJ_VERSION_NUM_MINOR, + PJ_VERSION_NUM_EXTRA); #endif /* @@ -57,9 +56,9 @@ PJ_DEF(void) pj_dump_config(void) PJ_LOG(3, (id, " PJ_HAS_PENTIUM : %d", PJ_HAS_PENTIUM)); PJ_LOG(3, (id, " PJ_OS_NAME : %s", PJ_OS_NAME)); PJ_LOG(3, (id, " PJ_CC_NAME/VER_(1,2,3) : %s-%d.%d.%d", PJ_CC_NAME, - PJ_CC_VER_1, PJ_CC_VER_2, PJ_CC_VER_3)); + PJ_CC_VER_1, PJ_CC_VER_2, PJ_CC_VER_3)); PJ_LOG(3, (id, " PJ_IS_(BIG/LITTLE)_ENDIAN : %s", - (PJ_IS_BIG_ENDIAN?"big-endian":"little-endian"))); + (PJ_IS_BIG_ENDIAN?"big-endian":"little-endian"))); PJ_LOG(3, (id, " PJ_HAS_INT64 : %d", PJ_HAS_INT64)); PJ_LOG(3, (id, " PJ_HAS_FLOATING_POINT : %d", PJ_HAS_FLOATING_POINT)); PJ_LOG(3, (id, " PJ_DEBUG : %d", PJ_DEBUG)); diff --git a/pjlib/src/pj/ctype.c b/pjlib/src/pj/ctype.c index d000659648..4f4117777e 100644 --- a/pjlib/src/pj/ctype.c +++ b/pjlib/src/pj/ctype.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,7 +20,7 @@ /* char pj_hex_digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; */ int pjlib_ctype_c_dummy_symbol; diff --git a/pjlib/src/pj/errno.c b/pjlib/src/pj/errno.c index 8cf90f3cbb..aabfa6cbed 100644 --- a/pjlib/src/pj/errno.c +++ b/pjlib/src/pj/errno.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,20 +29,20 @@ PJ_BEGIN_DECL PJ_DECL(int) platform_strerror(pj_os_err_type code, - char *buf, pj_size_t bufsize ); + char *buf, pj_size_t bufsize ); PJ_END_DECL #ifndef PJLIB_MAX_ERR_MSG_HANDLER -# define PJLIB_MAX_ERR_MSG_HANDLER 10 +# define PJLIB_MAX_ERR_MSG_HANDLER 10 #endif /* Error message handler. */ static unsigned err_msg_hnd_cnt; static struct err_msg_hnd { - pj_status_t begin; - pj_status_t end; - pj_str_t (*strerror)(pj_status_t, char*, pj_size_t); + pj_status_t begin; + pj_status_t end; + pj_str_t (*strerror)(pj_status_t, char*, pj_size_t); } err_msg_hnd[PJLIB_MAX_ERR_MSG_HANDLER]; @@ -67,21 +66,21 @@ static const struct PJ_BUILD_ERR(PJ_ETIMEDOUT, "Operation timed out" ), PJ_BUILD_ERR(PJ_ETOOMANY, "Too many objects of the specified type"), PJ_BUILD_ERR(PJ_EBUSY, "Object is busy"), - PJ_BUILD_ERR(PJ_ENOTSUP, "Option/operation is not supported"), - PJ_BUILD_ERR(PJ_EINVALIDOP, "Invalid operation"), + PJ_BUILD_ERR(PJ_ENOTSUP, "Option/operation is not supported"), + PJ_BUILD_ERR(PJ_EINVALIDOP, "Invalid operation"), PJ_BUILD_ERR(PJ_ECANCELLED, "Operation cancelled"), PJ_BUILD_ERR(PJ_EEXISTS, "Object already exists" ), - PJ_BUILD_ERR(PJ_EEOF, "End of file" ), - PJ_BUILD_ERR(PJ_ETOOBIG, "Size is too big"), - PJ_BUILD_ERR(PJ_ERESOLVE, "gethostbyname() has returned error"), - PJ_BUILD_ERR(PJ_ETOOSMALL, "Size is too short"), - PJ_BUILD_ERR(PJ_EIGNORED, "Ignored"), + PJ_BUILD_ERR(PJ_EEOF, "End of file" ), + PJ_BUILD_ERR(PJ_ETOOBIG, "Size is too big"), + PJ_BUILD_ERR(PJ_ERESOLVE, "gethostbyname() has returned error"), + PJ_BUILD_ERR(PJ_ETOOSMALL, "Size is too short"), + PJ_BUILD_ERR(PJ_EIGNORED, "Ignored"), PJ_BUILD_ERR(PJ_EIPV6NOTSUP, "IPv6 is not supported"), - PJ_BUILD_ERR(PJ_EAFNOTSUP, "Unsupported address family"), - PJ_BUILD_ERR(PJ_EGONE, "Object no longer exists"), + PJ_BUILD_ERR(PJ_EAFNOTSUP, "Unsupported address family"), + PJ_BUILD_ERR(PJ_EGONE, "Object no longer exists"), PJ_BUILD_ERR(PJ_ESOCKETSTOP, "Socket is in bad state") }; -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ /* @@ -109,16 +108,16 @@ static int pjlib_error(pj_status_t code, char *buf, pj_size_t size) len = pj_ansi_snprintf( buf, size, "Unknown pjlib error %d", code); if (len < 1 || len >= (int)size) - len = (int)(size - 1); + len = (int)(size - 1); return len; } -#define IN_RANGE(val,start,end) ((val)>=(start) && (val)<(end)) +#define IN_RANGE(val,start,end) ((val)>=(start) && (val)<(end)) /* Register strerror handle. */ PJ_DEF(pj_status_t) pj_register_strerror( pj_status_t start, - pj_status_t space, - pj_error_callback f) + pj_status_t space, + pj_error_callback f) { unsigned i; @@ -127,26 +126,26 @@ PJ_DEF(pj_status_t) pj_register_strerror( pj_status_t start, /* Check if there aren't too many handlers registered. */ PJ_ASSERT_RETURN(err_msg_hnd_cnt < PJ_ARRAY_SIZE(err_msg_hnd), - PJ_ETOOMANY); + PJ_ETOOMANY); /* Start error must be greater than PJ_ERRNO_START_USER */ PJ_ASSERT_RETURN(start >= PJ_ERRNO_START_USER, PJ_EEXISTS); /* Check that no existing handler has covered the specified range. */ for (i=0; i= (int)bufsize) { - len = (int)(bufsize - 1); - buf[len] = '\0'; + len = (int)(bufsize - 1); + buf[len] = '\0'; } errstr.ptr = buf; @@ -225,8 +224,8 @@ static void invoke_log(const char *sender, int level, const char *format, ...) } static void pj_perror_imp(int log_level, const char *sender, - pj_status_t status, - const char *title_fmt, va_list marker) + pj_status_t status, + const char *title_fmt, va_list marker) { char titlebuf[PJ_PERROR_TITLE_BUF_SIZE]; char errmsg[PJ_ERR_MSG_SIZE]; @@ -235,7 +234,7 @@ static void pj_perror_imp(int log_level, const char *sender, /* Build the title */ len = pj_ansi_vsnprintf(titlebuf, sizeof(titlebuf), title_fmt, marker); if (len < 0 || len >= (int)sizeof(titlebuf)) - pj_ansi_strcpy(titlebuf, "Error"); + pj_ansi_strcpy(titlebuf, "Error"); /* Get the error */ pj_strerror(status, errmsg, sizeof(errmsg)); @@ -245,7 +244,7 @@ static void pj_perror_imp(int log_level, const char *sender, } PJ_DEF(void) pj_perror(int log_level, const char *sender, pj_status_t status, - const char *title_fmt, ...) + const char *title_fmt, ...) { va_list marker; va_start(marker, title_fmt); @@ -254,7 +253,7 @@ PJ_DEF(void) pj_perror(int log_level, const char *sender, pj_status_t status, } PJ_DEF(void) pj_perror_1(const char *sender, pj_status_t status, - const char *title_fmt, ...) + const char *title_fmt, ...) { va_list marker; va_start(marker, title_fmt); @@ -264,15 +263,15 @@ PJ_DEF(void) pj_perror_1(const char *sender, pj_status_t status, #else /* #if PJ_LOG_MAX_LEVEL >= 1 */ PJ_DEF(void) pj_perror(int log_level, const char *sender, pj_status_t status, - const char *title_fmt, ...) + const char *title_fmt, ...) { } -#endif /* #if PJ_LOG_MAX_LEVEL >= 1 */ +#endif /* #if PJ_LOG_MAX_LEVEL >= 1 */ #if PJ_LOG_MAX_LEVEL >= 2 PJ_DEF(void) pj_perror_2(const char *sender, pj_status_t status, - const char *title_fmt, ...) + const char *title_fmt, ...) { va_list marker; va_start(marker, title_fmt); @@ -283,7 +282,7 @@ PJ_DEF(void) pj_perror_2(const char *sender, pj_status_t status, #if PJ_LOG_MAX_LEVEL >= 3 PJ_DEF(void) pj_perror_3(const char *sender, pj_status_t status, - const char *title_fmt, ...) + const char *title_fmt, ...) { va_list marker; va_start(marker, title_fmt); @@ -294,7 +293,7 @@ PJ_DEF(void) pj_perror_3(const char *sender, pj_status_t status, #if PJ_LOG_MAX_LEVEL >= 4 PJ_DEF(void) pj_perror_4(const char *sender, pj_status_t status, - const char *title_fmt, ...) + const char *title_fmt, ...) { va_list marker; va_start(marker, title_fmt); @@ -305,7 +304,7 @@ PJ_DEF(void) pj_perror_4(const char *sender, pj_status_t status, #if PJ_LOG_MAX_LEVEL >= 5 PJ_DEF(void) pj_perror_5(const char *sender, pj_status_t status, - const char *title_fmt, ...) + const char *title_fmt, ...) { va_list marker; va_start(marker, title_fmt); @@ -316,7 +315,7 @@ PJ_DEF(void) pj_perror_5(const char *sender, pj_status_t status, #if PJ_LOG_MAX_LEVEL >= 6 PJ_DEF(void) pj_perror_6(const char *sender, pj_status_t status, - const char *title_fmt, ...) + const char *title_fmt, ...) { va_list marker; va_start(marker, title_fmt); diff --git a/pjlib/src/pj/except.c b/pjlib/src/pj/except.c index abe1ce61e3..96da69f062 100644 --- a/pjlib/src/pj/except.c +++ b/pjlib/src/pj/except.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -43,10 +42,10 @@ PJ_DEF(void) pj_throw_exception_(int exception_id) struct pj_exception_state_t *handler; handler = (struct pj_exception_state_t*) - pj_thread_local_get(thread_local_id); + pj_thread_local_get(thread_local_id); if (handler == NULL) { PJ_LOG(1,("except.c", "!!!FATAL: unhandled exception %s!\n", - pj_exception_id_name(exception_id))); + pj_exception_id_name(exception_id))); pj_assert(handler != NULL); /* This will crash the system! */ } @@ -57,15 +56,15 @@ PJ_DEF(void) pj_throw_exception_(int exception_id) static void exception_cleanup(void) { if (thread_local_id != -1) { - pj_thread_local_free(thread_local_id); - thread_local_id = -1; + pj_thread_local_free(thread_local_id); + thread_local_id = -1; } #if defined(PJ_HAS_EXCEPTION_NAMES) && PJ_HAS_EXCEPTION_NAMES != 0 { - unsigned i; - for (i=0; iprev = parent_handler; pj_thread_local_set(thread_local_id, rec); } @@ -92,9 +91,9 @@ PJ_DEF(void) pj_pop_exception_handler_(struct pj_exception_state_t *rec) struct pj_exception_state_t *handler; handler = (struct pj_exception_state_t *) - pj_thread_local_get(thread_local_id); + pj_thread_local_get(thread_local_id); if (handler && handler==rec) { - pj_thread_local_set(thread_local_id, handler->prev); + pj_thread_local_set(thread_local_id, handler->prev); } } #endif @@ -152,8 +151,8 @@ PJ_DEF(const char*) pj_exception_id_name(pj_exception_id_t id) if (exception_id_names[id] == NULL) { pj_ansi_snprintf(unknown_name, sizeof(unknown_name), - "exception %d", id); - return unknown_name; + "exception %d", id); + return unknown_name; } return exception_id_names[id]; diff --git a/pjlib/src/pj/exception_symbian.cpp b/pjlib/src/pj/exception_symbian.cpp index 4b5da40697..99dade874f 100644 --- a/pjlib/src/pj/exception_symbian.cpp +++ b/pjlib/src/pj/exception_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pj/extra-exports.c b/pjlib/src/pj/extra-exports.c index 23a37bd9fc..26d215e66b 100644 --- a/pjlib/src/pj/extra-exports.c +++ b/pjlib/src/pj/extra-exports.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pj/fifobuf.c b/pjlib/src/pj/fifobuf.c index 565a99359c..464f3114cc 100644 --- a/pjlib/src/pj/fifobuf.c +++ b/pjlib/src/pj/fifobuf.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,8 +30,8 @@ PJ_DEF(void) pj_fifobuf_init (pj_fifobuf_t *fifobuf, void *buffer, unsigned size PJ_CHECK_STACK(); PJ_LOG(6, (THIS_FILE, - "fifobuf_init fifobuf=%p buffer=%p, size=%d", - fifobuf, buffer, size)); + "fifobuf_init fifobuf=%p buffer=%p, size=%d", + fifobuf, buffer, size)); fifobuf->first = (char*)buffer; fifobuf->last = fifobuf->first + size; @@ -47,10 +46,10 @@ PJ_DEF(unsigned) pj_fifobuf_max_size (pj_fifobuf_t *fifobuf) PJ_CHECK_STACK(); if (fifobuf->uend >= fifobuf->ubegin) { - s1 = (unsigned)(fifobuf->last - fifobuf->uend); - s2 = (unsigned)(fifobuf->ubegin - fifobuf->first); + s1 = (unsigned)(fifobuf->last - fifobuf->uend); + s2 = (unsigned)(fifobuf->ubegin - fifobuf->first); } else { - s1 = s2 = (unsigned)(fifobuf->ubegin - fifobuf->uend); + s1 = s2 = (unsigned)(fifobuf->ubegin - fifobuf->uend); } return s1full) { - PJ_LOG(6, (THIS_FILE, - "fifobuf_alloc fifobuf=%p, size=%d: full!", - fifobuf, size)); - return NULL; + PJ_LOG(6, (THIS_FILE, + "fifobuf_alloc fifobuf=%p, size=%d: full!", + fifobuf, size)); + return NULL; } /* try to allocate from the end part of the fifo */ if (fifobuf->uend >= fifobuf->ubegin) { - available = (unsigned)(fifobuf->last - fifobuf->uend); - if (available >= size+SZ) { - char *ptr = fifobuf->uend; - fifobuf->uend += (size+SZ); - if (fifobuf->uend == fifobuf->last) - fifobuf->uend = fifobuf->first; - if (fifobuf->uend == fifobuf->ubegin) - fifobuf->full = 1; - *(unsigned*)ptr = size+SZ; - ptr += SZ; - - PJ_LOG(6, (THIS_FILE, - "fifobuf_alloc fifobuf=%p, size=%d: returning %p, p1=%p, p2=%p", - fifobuf, size, ptr, fifobuf->ubegin, fifobuf->uend)); - return ptr; - } + available = (unsigned)(fifobuf->last - fifobuf->uend); + if (available >= size+SZ) { + char *ptr = fifobuf->uend; + fifobuf->uend += (size+SZ); + if (fifobuf->uend == fifobuf->last) + fifobuf->uend = fifobuf->first; + if (fifobuf->uend == fifobuf->ubegin) + fifobuf->full = 1; + *(unsigned*)ptr = size+SZ; + ptr += SZ; + + PJ_LOG(6, (THIS_FILE, + "fifobuf_alloc fifobuf=%p, size=%d: returning %p, p1=%p, p2=%p", + fifobuf, size, ptr, fifobuf->ubegin, fifobuf->uend)); + return ptr; + } } /* try to allocate from the start part of the fifo */ start = (fifobuf->uend <= fifobuf->ubegin) ? fifobuf->uend : fifobuf->first; available = (unsigned)(fifobuf->ubegin - start); if (available >= size+SZ) { - char *ptr = start; - fifobuf->uend = start + size + SZ; - if (fifobuf->uend == fifobuf->ubegin) - fifobuf->full = 1; - *(unsigned*)ptr = size+SZ; - ptr += SZ; - - PJ_LOG(6, (THIS_FILE, - "fifobuf_alloc fifobuf=%p, size=%d: returning %p, p1=%p, p2=%p", - fifobuf, size, ptr, fifobuf->ubegin, fifobuf->uend)); - return ptr; + char *ptr = start; + fifobuf->uend = start + size + SZ; + if (fifobuf->uend == fifobuf->ubegin) + fifobuf->full = 1; + *(unsigned*)ptr = size+SZ; + ptr += SZ; + + PJ_LOG(6, (THIS_FILE, + "fifobuf_alloc fifobuf=%p, size=%d: returning %p, p1=%p, p2=%p", + fifobuf, size, ptr, fifobuf->ubegin, fifobuf->uend)); + return ptr; } PJ_LOG(6, (THIS_FILE, - "fifobuf_alloc fifobuf=%p, size=%d: no space left! p1=%p, p2=%p", - fifobuf, size, fifobuf->ubegin, fifobuf->uend)); + "fifobuf_alloc fifobuf=%p, size=%d: no space left! p1=%p, p2=%p", + fifobuf, size, fifobuf->ubegin, fifobuf->uend)); return NULL; } @@ -126,19 +125,19 @@ PJ_DEF(pj_status_t) pj_fifobuf_unalloc (pj_fifobuf_t *fifobuf, void *buf) endptr = fifobuf->uend; if (endptr == fifobuf->first) - endptr = fifobuf->last; + endptr = fifobuf->last; if (ptr+sz != endptr) { - pj_assert(!"Invalid pointer to undo alloc"); - return -1; + pj_assert(!"Invalid pointer to undo alloc"); + return -1; } fifobuf->uend = ptr; fifobuf->full = 0; PJ_LOG(6, (THIS_FILE, - "fifobuf_unalloc fifobuf=%p, ptr=%p, size=%d, p1=%p, p2=%p", - fifobuf, buf, sz, fifobuf->ubegin, fifobuf->uend)); + "fifobuf_unalloc fifobuf=%p, ptr=%p, size=%d, p1=%p, p2=%p", + fifobuf, buf, sz, fifobuf->ubegin, fifobuf->uend)); return 0; } @@ -153,37 +152,37 @@ PJ_DEF(pj_status_t) pj_fifobuf_free (pj_fifobuf_t *fifobuf, void *buf) ptr -= SZ; if (ptr < fifobuf->first || ptr >= fifobuf->last) { - pj_assert(!"Invalid pointer to free"); - return -1; + pj_assert(!"Invalid pointer to free"); + return -1; } if (ptr != fifobuf->ubegin && ptr != fifobuf->first) { - pj_assert(!"Invalid free() sequence!"); - return -1; + pj_assert(!"Invalid free() sequence!"); + return -1; } end = (fifobuf->uend > fifobuf->ubegin) ? fifobuf->uend : fifobuf->last; sz = *(unsigned*)ptr; if (ptr+sz > end) { - pj_assert(!"Invalid size!"); - return -1; + pj_assert(!"Invalid size!"); + return -1; } fifobuf->ubegin = ptr + sz; /* Rollover */ if (fifobuf->ubegin == fifobuf->last) - fifobuf->ubegin = fifobuf->first; + fifobuf->ubegin = fifobuf->first; /* Reset if fifobuf is empty */ if (fifobuf->ubegin == fifobuf->uend) - fifobuf->ubegin = fifobuf->uend = fifobuf->first; + fifobuf->ubegin = fifobuf->uend = fifobuf->first; fifobuf->full = 0; PJ_LOG(6, (THIS_FILE, - "fifobuf_free fifobuf=%p, ptr=%p, size=%d, p1=%p, p2=%p", - fifobuf, buf, sz, fifobuf->ubegin, fifobuf->uend)); + "fifobuf_free fifobuf=%p, ptr=%p, size=%d, p1=%p, p2=%p", + fifobuf, buf, sz, fifobuf->ubegin, fifobuf->uend)); return 0; } diff --git a/pjlib/src/pj/file_access_unistd.c b/pjlib/src/pj/file_access_unistd.c index b257ff4b02..6102cd09e7 100644 --- a/pjlib/src/pj/file_access_unistd.c +++ b/pjlib/src/pj/file_access_unistd.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,7 +23,7 @@ #include #include #include -#include /* rename() */ +#include /* rename() */ #include /* @@ -37,7 +36,7 @@ PJ_DEF(pj_bool_t) pj_file_exists(const char *filename) PJ_ASSERT_RETURN(filename, 0); if (stat(filename, &buf) != 0) - return 0; + return 0; return PJ_TRUE; } @@ -53,7 +52,7 @@ PJ_DEF(pj_off_t) pj_file_size(const char *filename) PJ_ASSERT_RETURN(filename, -1); if (stat(filename, &buf) != 0) - return -1; + return -1; return buf.st_size; } @@ -67,7 +66,7 @@ PJ_DEF(pj_status_t) pj_file_delete(const char *filename) PJ_ASSERT_RETURN(filename, PJ_EINVAL); if (unlink(filename)!=0) { - return PJ_RETURN_OS_ERROR(errno); + return PJ_RETURN_OS_ERROR(errno); } return PJ_SUCCESS; } @@ -81,7 +80,7 @@ PJ_DEF(pj_status_t) pj_file_move( const char *oldname, const char *newname) PJ_ASSERT_RETURN(oldname && newname, PJ_EINVAL); if (rename(oldname, newname) != 0) { - return PJ_RETURN_OS_ERROR(errno); + return PJ_RETURN_OS_ERROR(errno); } return PJ_SUCCESS; } @@ -91,14 +90,14 @@ PJ_DEF(pj_status_t) pj_file_move( const char *oldname, const char *newname) * pj_file_getstat() */ PJ_DEF(pj_status_t) pj_file_getstat(const char *filename, - pj_file_stat *statbuf) + pj_file_stat *statbuf) { struct stat buf; PJ_ASSERT_RETURN(filename && statbuf, PJ_EINVAL); if (stat(filename, &buf) != 0) { - return PJ_RETURN_OS_ERROR(errno); + return PJ_RETURN_OS_ERROR(errno); } statbuf->size = buf.st_size; diff --git a/pjlib/src/pj/file_access_win32.c b/pjlib/src/pj/file_access_win32.c index e93605f4dc..99f473e1a6 100644 --- a/pjlib/src/pj/file_access_win32.c +++ b/pjlib/src/pj/file_access_win32.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,24 +38,24 @@ static pj_status_t get_file_size(HANDLE hFile, pj_off_t *size) FILE_COMPRESSION_INFO fileInfo; if (GetFileInformationByHandleEx(hFile, FileCompressionInfo, &fileInfo, - sizeof(FILE_COMPRESSION_INFO))) + sizeof(FILE_COMPRESSION_INFO))) { - *size = fileInfo.CompressedFileSize.QuadPart; + *size = fileInfo.CompressedFileSize.QuadPart; } else { - *size = -1; - return PJ_RETURN_OS_ERROR(GetLastError()); + *size = -1; + return PJ_RETURN_OS_ERROR(GetLastError()); } #else DWORD sizeLo, sizeHi; sizeLo = GetFileSize(hFile, &sizeHi); if (sizeLo == INVALID_FILE_SIZE) { - DWORD dwStatus = GetLastError(); - if (dwStatus != NO_ERROR) { - *size = -1; - return PJ_RETURN_OS_ERROR(dwStatus); - } + DWORD dwStatus = GetLastError(); + if (dwStatus != NO_ERROR) { + *size = -1; + return PJ_RETURN_OS_ERROR(dwStatus); + } } *size = sizeHi; *size = ((*size) << 32) + sizeLo; @@ -77,11 +76,11 @@ static HANDLE WINAPI create_file(LPCTSTR filename, DWORD desired_access, PJ_UNUSED_ARG(template_file); return CreateFile2(filename, desired_access, share_mode, - creation_disposition, NULL); + creation_disposition, NULL); #else return CreateFile(filename, desired_access, share_mode, - security_attributes, creation_disposition, - flags_and_attributes, template_file); + security_attributes, creation_disposition, + flags_and_attributes, template_file); #endif } @@ -96,9 +95,9 @@ PJ_DEF(pj_bool_t) pj_file_exists(const char *filename) PJ_ASSERT_RETURN(filename != NULL, 0); hFile = create_file(PJ_STRING_TO_NATIVE(filename, - wfilename, sizeof(wfilename)), - CONTROL_ACCESS, - FILE_SHARE_READ, NULL, + wfilename, sizeof(wfilename)), + CONTROL_ACCESS, + FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) return 0; @@ -120,8 +119,8 @@ PJ_DEF(pj_off_t) pj_file_size(const char *filename) PJ_ASSERT_RETURN(filename != NULL, -1); hFile = create_file(PJ_STRING_TO_NATIVE(filename, - wfilename, sizeof(wfilename)), - CONTROL_ACCESS, + wfilename, sizeof(wfilename)), + CONTROL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) @@ -163,11 +162,11 @@ PJ_DEF(pj_status_t) pj_file_move( const char *oldname, const char *newname) #if PJ_WIN32_WINNT >= 0x0400 rc = MoveFileEx(PJ_STRING_TO_NATIVE(oldname,woldname,sizeof(woldname)), - PJ_STRING_TO_NATIVE(newname,wnewname,sizeof(wnewname)), + PJ_STRING_TO_NATIVE(newname,wnewname,sizeof(wnewname)), MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING); #else rc = MoveFile(PJ_STRING_TO_NATIVE(oldname,woldname,sizeof(woldname)), - PJ_STRING_TO_NATIVE(newname,wnewname,sizeof(wnewname))); + PJ_STRING_TO_NATIVE(newname,wnewname,sizeof(wnewname))); #endif if (!rc) @@ -189,7 +188,7 @@ static pj_status_t file_time_to_time_val(const FILETIME *file_time, #if !defined(PJ_WIN32_WINPHONE8) || !PJ_WIN32_WINPHONE8 if (!FileTimeToLocalFileTime(file_time, &local_file_time)) - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); #endif if (!FileTimeToSystemTime(file_time, &localTime)) @@ -227,38 +226,38 @@ PJ_DEF(pj_status_t) pj_file_getstat(const char *filename, pj_file_stat *stat) PJ_ASSERT_RETURN(filename!=NULL && stat!=NULL, PJ_EINVAL); hFile = create_file(PJ_STRING_TO_NATIVE(filename, - wfilename, sizeof(wfilename)), - CONTROL_ACCESS, - FILE_SHARE_READ, NULL, + wfilename, sizeof(wfilename)), + CONTROL_ACCESS, + FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) return PJ_RETURN_OS_ERROR(GetLastError()); if (get_file_size(hFile, &stat->size) != PJ_SUCCESS) { - CloseHandle(hFile); - return PJ_RETURN_OS_ERROR(GetLastError()); + CloseHandle(hFile); + return PJ_RETURN_OS_ERROR(GetLastError()); } #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 if (GetFileInformationByHandleEx(hFile, FileBasicInfo, &fileInfo, - sizeof(FILE_BASIC_INFO))) + sizeof(FILE_BASIC_INFO))) { - creationTime.dwLowDateTime = fileInfo.CreationTime.LowPart; - creationTime.dwHighDateTime = fileInfo.CreationTime.HighPart; - accessTime.dwLowDateTime = fileInfo.LastAccessTime.LowPart; - accessTime.dwHighDateTime = fileInfo.LastAccessTime.HighPart; - writeTime.dwLowDateTime = fileInfo.LastWriteTime.LowPart; - writeTime.dwHighDateTime = fileInfo.LastWriteTime.HighPart; + creationTime.dwLowDateTime = fileInfo.CreationTime.LowPart; + creationTime.dwHighDateTime = fileInfo.CreationTime.HighPart; + accessTime.dwLowDateTime = fileInfo.LastAccessTime.LowPart; + accessTime.dwHighDateTime = fileInfo.LastAccessTime.HighPart; + writeTime.dwLowDateTime = fileInfo.LastWriteTime.LowPart; + writeTime.dwHighDateTime = fileInfo.LastWriteTime.HighPart; } else { - CloseHandle(hFile); - return PJ_RETURN_OS_ERROR(GetLastError()); + CloseHandle(hFile); + return PJ_RETURN_OS_ERROR(GetLastError()); } #else if (GetFileTime(hFile, &creationTime, &accessTime, &writeTime) == FALSE) { - DWORD dwStatus = GetLastError(); - CloseHandle(hFile); - return PJ_RETURN_OS_ERROR(dwStatus); + DWORD dwStatus = GetLastError(); + CloseHandle(hFile); + return PJ_RETURN_OS_ERROR(dwStatus); } #endif diff --git a/pjlib/src/pj/file_io_ansi.c b/pjlib/src/pj/file_io_ansi.c index 0570b81c7a..adb59c71d1 100644 --- a/pjlib/src/pj/file_io_ansi.c +++ b/pjlib/src/pj/file_io_ansi.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -170,7 +169,7 @@ PJ_DEF(pj_status_t) pj_file_flush(pj_oshandle_t fd) rc = fflush((FILE*)fd); if (rc == EOF) { - return PJ_RETURN_OS_ERROR(errno); + return PJ_RETURN_OS_ERROR(errno); } return PJ_SUCCESS; diff --git a/pjlib/src/pj/file_io_win32.c b/pjlib/src/pj/file_io_win32.c index 81f849e87e..7c84c36f56 100644 --- a/pjlib/src/pj/file_io_win32.c +++ b/pjlib/src/pj/file_io_win32.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,7 +38,7 @@ static pj_status_t set_file_pointer(pj_oshandle_t fd, liDistance.QuadPart = offset; if (!SetFilePointerEx(fd, liDistance, &liNewPos, dwMoveMethod)) { - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); } *newPos = liNewPos.QuadPart; #else @@ -50,10 +49,10 @@ static pj_status_t set_file_pointer(pj_oshandle_t fd, dwNewPos = SetFilePointer(fd, (long)offset, &hi32, dwMoveMethod); if (dwNewPos == (DWORD)INVALID_SET_FILE_POINTER) { - DWORD dwStatus = GetLastError(); - if (dwStatus != 0) - return PJ_RETURN_OS_ERROR(dwStatus); - /* dwNewPos actually is not an error. */ + DWORD dwStatus = GetLastError(); + if (dwStatus != 0) + return PJ_RETURN_OS_ERROR(dwStatus); + /* dwNewPos actually is not an error. */ } *newPos = hi32; *newPos = (*newPos << 32) + dwNewPos; @@ -94,15 +93,15 @@ PJ_DEF(pj_status_t) pj_file_open( pj_pool_t *pool, dwDesiredAccess |= GENERIC_WRITE; if ((flags & PJ_O_APPEND) == PJ_O_APPEND) { #if !defined(PJ_WIN32_WINCE) || !PJ_WIN32_WINCE - /* FILE_APPEND_DATA is invalid on WM2003 and WM5, but it seems - * to be working on WM6. All are tested on emulator though. - * Removing this also seem to work (i.e. data is appended), so - * I guess this flag is "optional". - * See https://github.com/pjsip/pjproject/issues/825 - */ + /* FILE_APPEND_DATA is invalid on WM2003 and WM5, but it seems + * to be working on WM6. All are tested on emulator though. + * Removing this also seem to work (i.e. data is appended), so + * I guess this flag is "optional". + * See https://github.com/pjsip/pjproject/issues/825 + */ dwDesiredAccess |= FILE_APPEND_DATA; #endif - dwCreationDisposition |= OPEN_ALWAYS; + dwCreationDisposition |= OPEN_ALWAYS; } else { dwDesiredAccess &= ~(FILE_APPEND_DATA); dwCreationDisposition |= CREATE_ALWAYS; @@ -125,30 +124,30 @@ PJ_DEF(pj_status_t) pj_file_open( pj_pool_t *pool, #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 hFile = CreateFile2(PJ_STRING_TO_NATIVE(pathname, - wpathname, sizeof(wpathname)), - dwDesiredAccess, dwShareMode, dwCreationDisposition, - NULL); + wpathname, sizeof(wpathname)), + dwDesiredAccess, dwShareMode, dwCreationDisposition, + NULL); #else hFile = CreateFile(PJ_STRING_TO_NATIVE(pathname, - wpathname, sizeof(wpathname)), - dwDesiredAccess, dwShareMode, NULL, - dwCreationDisposition, dwFlagsAndAttributes, NULL); + wpathname, sizeof(wpathname)), + dwDesiredAccess, dwShareMode, NULL, + dwCreationDisposition, dwFlagsAndAttributes, NULL); #endif if (hFile == INVALID_HANDLE_VALUE) { - DWORD lastErr = GetLastError(); + DWORD lastErr = GetLastError(); *fd = 0; return PJ_RETURN_OS_ERROR(lastErr); } if ((flags & PJ_O_APPEND) == PJ_O_APPEND) { - pj_status_t status; + pj_status_t status; - status = pj_file_setpos(hFile, 0, PJ_SEEK_END); - if (status != PJ_SUCCESS) { - pj_file_close(hFile); - return status; - } + status = pj_file_setpos(hFile, 0, PJ_SEEK_END); + if (status != PJ_SUCCESS) { + pj_file_close(hFile); + return status; + } } *fd = hFile; @@ -239,7 +238,7 @@ PJ_DEF(pj_status_t) pj_file_setpos( pj_oshandle_t fd, } if (set_file_pointer(fd, offset, &newPos, dwMoveMethod) != PJ_SUCCESS) { - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); } return PJ_SUCCESS; @@ -249,7 +248,7 @@ PJ_DEF(pj_status_t) pj_file_getpos( pj_oshandle_t fd, pj_off_t *pos) { if (set_file_pointer(fd, 0, pos, FILE_CURRENT) != PJ_SUCCESS) { - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); } return PJ_SUCCESS; @@ -262,7 +261,7 @@ PJ_DEF(pj_status_t) pj_file_flush(pj_oshandle_t fd) rc = FlushFileBuffers(fd); if (!rc) { - DWORD dwStatus = GetLastError(); + DWORD dwStatus = GetLastError(); if (dwStatus != 0) return PJ_RETURN_OS_ERROR(dwStatus); } diff --git a/pjlib/src/pj/guid.c b/pjlib/src/pj/guid.c index c16a7ce0e6..2b8eb840ff 100644 --- a/pjlib/src/pj/guid.c +++ b/pjlib/src/pj/guid.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,7 +26,7 @@ PJ_DEF(pj_str_t*) pj_generate_unique_string_lower(pj_str_t *str) pj_generate_unique_string(str); for (i = 0; i < str->slen; i++) - str->ptr[i] = (char)pj_tolower(str->ptr[i]); + str->ptr[i] = (char)pj_tolower(str->ptr[i]); return str; } @@ -44,5 +43,5 @@ PJ_DEF(void) pj_create_unique_string_lower(pj_pool_t *pool, pj_str_t *str) pj_create_unique_string(pool, str); for (i = 0; i < str->slen; i++) - str->ptr[i] = (char)pj_tolower(str->ptr[i]); + str->ptr[i] = (char)pj_tolower(str->ptr[i]); } diff --git a/pjlib/src/pj/guid_android.c b/pjlib/src/pj/guid_android.c index 14ee026575..2e633823ab 100644 --- a/pjlib/src/pj/guid_android.c +++ b/pjlib/src/pj/guid_android.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2015-2016 Teluu Inc. (http://www.teluu.com) * @@ -81,23 +80,23 @@ PJ_DEF(pj_str_t*) pj_generate_unique_string(pj_str_t *str) goto on_error; javaUuid = (*jni_env)->CallStaticObjectMethod(jni_env, uuid_class, - get_uuid_method); + get_uuid_method); if (javaUuid == 0) goto on_error; to_string_method = (*jni_env)->GetMethodID(jni_env, uuid_class, - "toString", - "()Ljava/lang/String;"); + "toString", + "()Ljava/lang/String;"); if (to_string_method == 0) goto on_error; uuid_string = (*jni_env)->CallObjectMethod(jni_env, javaUuid, - to_string_method); + to_string_method); if (uuid_string == 0) goto on_error; native_string = (*jni_env)->GetStringUTFChars(jni_env, uuid_string, - JNI_FALSE); + JNI_FALSE); if (native_string == 0) goto on_error; diff --git a/pjlib/src/pj/guid_simple.c b/pjlib/src/pj/guid_simple.c index 029ee8ddbe..9bf42ebb25 100644 --- a/pjlib/src/pj/guid_simple.c +++ b/pjlib/src/pj/guid_simple.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,11 +37,11 @@ static void init_guid_chars(void) unsigned i; for (i=0; i<10; ++i) - *p++ = '0'+i; + *p++ = '0'+i; for (i=0; i<26; ++i) { - *p++ = 'a'+i; - *p++ = 'A'+i; + *p++ = 'a'+i; + *p++ = 'A'+i; } *p++ = '-'; @@ -56,23 +55,23 @@ PJ_DEF(pj_str_t*) pj_generate_unique_string(pj_str_t *str) PJ_CHECK_STACK(); if (guid_chars[0] == '\0') { - pj_enter_critical_section(); - if (guid_chars[0] == '\0') { - init_guid_chars(); - } - pj_leave_critical_section(); + pj_enter_critical_section(); + if (guid_chars[0] == '\0') { + init_guid_chars(); + } + pj_leave_critical_section(); } /* This would only work if PJ_GUID_STRING_LENGTH is multiple of 2 bytes */ pj_assert(PJ_GUID_STRING_LENGTH % 2 == 0); for (p=str->ptr, end=p+PJ_GUID_STRING_LENGTH; p0 && p>=8, rand_val>>=8, p++) { - *p = guid_chars[(rand_val & 0xFF) & 63]; - } + for ( ; rand_idx>0 && p>=8, rand_val>>=8, p++) { + *p = guid_chars[(rand_val & 0xFF) & 63]; + } } str->slen = PJ_GUID_STRING_LENGTH; diff --git a/pjlib/src/pj/guid_uuid.c b/pjlib/src/pj/guid_uuid.c index 98c52fa0e9..8f366f372e 100644 --- a/pjlib/src/pj/guid_uuid.c +++ b/pjlib/src/pj/guid_uuid.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pj/guid_win32.c b/pjlib/src/pj/guid_win32.c index de944f1049..a0b607734c 100644 --- a/pjlib/src/pj/guid_win32.c +++ b/pjlib/src/pj/guid_win32.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,7 +34,7 @@ PJ_DEF(unsigned) pj_GUID_STRING_LENGTH() PJ_INLINE(void) hex2digit(unsigned value, char *p) { static char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; *p++ = hex[ (value & 0xF0) >> 4 ]; *p++ = hex[ (value & 0x0F) ]; } @@ -51,9 +50,9 @@ static void guid_to_str( GUID *guid, pj_str_t *str ) guid->Data3 = pj_ntohs(guid->Data3); for (i=0; i<16; ++i) { - hex2digit( *src, dst ); - dst += 2; - ++src; + hex2digit( *src, dst ); + dst += 2; + ++src; } str->slen = 32; } diff --git a/pjlib/src/pj/hash.c b/pjlib/src/pj/hash.c index f45cde3f53..f87bddf2bc 100644 --- a/pjlib/src/pj/hash.c +++ b/pjlib/src/pj/hash.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,7 +27,7 @@ /** * The hash multiplier used to calculate hash value. */ -#define PJ_HASH_MULTIPLIER 33 +#define PJ_HASH_MULTIPLIER 33 struct pj_hash_entry @@ -44,28 +43,28 @@ struct pj_hash_entry struct pj_hash_table_t { pj_hash_entry **table; - unsigned count, rows; - pj_hash_iterator_t iterator; + unsigned count, rows; + pj_hash_iterator_t iterator; }; PJ_DEF(pj_uint32_t) pj_hash_calc(pj_uint32_t hash, const void *key, - unsigned keylen) + unsigned keylen) { PJ_CHECK_STACK(); if (keylen==PJ_HASH_KEY_STRING) { - const pj_uint8_t *p = (const pj_uint8_t*)key; - for ( ; *p; ++p ) { - hash = (hash * PJ_HASH_MULTIPLIER) + *p; - } + const pj_uint8_t *p = (const pj_uint8_t*)key; + for ( ; *p; ++p ) { + hash = (hash * PJ_HASH_MULTIPLIER) + *p; + } } else { - const pj_uint8_t *p = (const pj_uint8_t*)key, - *end = p + keylen; - for ( ; p!=end; ++p) { - hash = (hash * PJ_HASH_MULTIPLIER) + *p; - } + const pj_uint8_t *p = (const pj_uint8_t*)key, + *end = p + keylen; + for ( ; p!=end; ++p) { + hash = (hash * PJ_HASH_MULTIPLIER) + *p; + } } return hash; } @@ -78,10 +77,10 @@ PJ_DEF(pj_uint32_t) pj_hash_calc_tolower( pj_uint32_t hval, for (i=0; islen; ++i) { int lower = pj_tolower(key->ptr[i]); - if (result) - result[i] = (char)lower; + if (result) + result[i] = (char)lower; - hval = hval * PJ_HASH_MULTIPLIER + lower; + hval = hval * PJ_HASH_MULTIPLIER + lower; } return hval; @@ -107,98 +106,98 @@ PJ_DEF(pj_hash_table_t*) pj_hash_create(pj_pool_t *pool, unsigned size) */ table_size = 8; do { - table_size <<= 1; + table_size <<= 1; } while (table_size < size); table_size -= 1; h->rows = table_size; h->table = (pj_hash_entry**) - pj_pool_calloc(pool, table_size+1, sizeof(pj_hash_entry*)); + pj_pool_calloc(pool, table_size+1, sizeof(pj_hash_entry*)); return h; } static pj_hash_entry **find_entry( pj_pool_t *pool, pj_hash_table_t *ht, - const void *key, unsigned keylen, - void *val, pj_uint32_t *hval, - void *entry_buf, pj_bool_t lower) + const void *key, unsigned keylen, + void *val, pj_uint32_t *hval, + void *entry_buf, pj_bool_t lower) { pj_uint32_t hash; pj_hash_entry **p_entry, *entry; if (hval && *hval != 0) { - hash = *hval; - if (keylen==PJ_HASH_KEY_STRING) { - keylen = (unsigned)pj_ansi_strlen((const char*)key); - } + hash = *hval; + if (keylen==PJ_HASH_KEY_STRING) { + keylen = (unsigned)pj_ansi_strlen((const char*)key); + } } else { - /* This slightly differs with pj_hash_calc() because we need - * to get the keylen when keylen is PJ_HASH_KEY_STRING. - */ - hash=0; - if (keylen==PJ_HASH_KEY_STRING) { - const pj_uint8_t *p = (const pj_uint8_t*)key; - for ( ; *p; ++p ) { + /* This slightly differs with pj_hash_calc() because we need + * to get the keylen when keylen is PJ_HASH_KEY_STRING. + */ + hash=0; + if (keylen==PJ_HASH_KEY_STRING) { + const pj_uint8_t *p = (const pj_uint8_t*)key; + for ( ; *p; ++p ) { if (lower) hash = hash * PJ_HASH_MULTIPLIER + pj_tolower(*p); else - hash = hash * PJ_HASH_MULTIPLIER + *p; - } - keylen = (unsigned)(p - (const unsigned char*)key); - } else { - const pj_uint8_t *p = (const pj_uint8_t*)key, - *end = p + keylen; - for ( ; p!=end; ++p) { - if (lower) + hash = hash * PJ_HASH_MULTIPLIER + *p; + } + keylen = (unsigned)(p - (const unsigned char*)key); + } else { + const pj_uint8_t *p = (const pj_uint8_t*)key, + *end = p + keylen; + for ( ; p!=end; ++p) { + if (lower) hash = hash * PJ_HASH_MULTIPLIER + pj_tolower(*p); else hash = hash * PJ_HASH_MULTIPLIER + *p; - } - } + } + } - /* Report back the computed hash. */ - if (hval) - *hval = hash; + /* Report back the computed hash. */ + if (hval) + *hval = hash; } /* scan the linked list */ for (p_entry = &ht->table[hash & ht->rows], entry=*p_entry; - entry; - p_entry = &entry->next, entry = *p_entry) + entry; + p_entry = &entry->next, entry = *p_entry) { - if (entry->hash==hash && entry->keylen==keylen && + if (entry->hash==hash && entry->keylen==keylen && ((lower && pj_ansi_strnicmp((const char*)entry->key, - (const char*)key, keylen)==0) || - (!lower && pj_memcmp(entry->key, key, keylen)==0))) - { - break; - } + (const char*)key, keylen)==0) || + (!lower && pj_memcmp(entry->key, key, keylen)==0))) + { + break; + } } if (entry || val==NULL) - return p_entry; + return p_entry; /* Entry not found, create a new one. * If entry_buf is specified, use it. Otherwise allocate from pool. */ if (entry_buf) { - entry = (pj_hash_entry*)entry_buf; + entry = (pj_hash_entry*)entry_buf; } else { - /* Pool must be specified! */ - PJ_ASSERT_RETURN(pool != NULL, NULL); - - entry = PJ_POOL_ALLOC_T(pool, pj_hash_entry); - PJ_LOG(6, ("hashtbl", - "%p: New p_entry %p created, pool used=%u, cap=%u", - ht, entry, pj_pool_get_used_size(pool), - pj_pool_get_capacity(pool))); + /* Pool must be specified! */ + PJ_ASSERT_RETURN(pool != NULL, NULL); + + entry = PJ_POOL_ALLOC_T(pool, pj_hash_entry); + PJ_LOG(6, ("hashtbl", + "%p: New p_entry %p created, pool used=%u, cap=%u", + ht, entry, pj_pool_get_used_size(pool), + pj_pool_get_capacity(pool))); } entry->next = NULL; entry->hash = hash; if (pool) { - entry->key = pj_pool_alloc(pool, keylen); - pj_memcpy(entry->key, key, keylen); + entry->key = pj_pool_alloc(pool, keylen); + pj_memcpy(entry->key, key, keylen); } else { - entry->key = (void*)key; + entry->key = (void*)key; } entry->keylen = keylen; entry->value = val; @@ -210,8 +209,8 @@ static pj_hash_entry **find_entry( pj_pool_t *pool, pj_hash_table_t *ht, } PJ_DEF(void *) pj_hash_get( pj_hash_table_t *ht, - const void *key, unsigned keylen, - pj_uint32_t *hval) + const void *key, unsigned keylen, + pj_uint32_t *hval) { pj_hash_entry *entry; entry = *find_entry( NULL, ht, key, keylen, NULL, hval, NULL, PJ_FALSE); @@ -219,8 +218,8 @@ PJ_DEF(void *) pj_hash_get( pj_hash_table_t *ht, } PJ_DEF(void *) pj_hash_get_lower( pj_hash_table_t *ht, - const void *key, unsigned keylen, - pj_uint32_t *hval) + const void *key, unsigned keylen, + pj_uint32_t *hval) { pj_hash_entry *entry; entry = *find_entry( NULL, ht, key, keylen, NULL, hval, NULL, PJ_TRUE); @@ -228,56 +227,56 @@ PJ_DEF(void *) pj_hash_get_lower( pj_hash_table_t *ht, } static void hash_set( pj_pool_t *pool, pj_hash_table_t *ht, - const void *key, unsigned keylen, pj_uint32_t hval, - void *value, void *entry_buf, pj_bool_t lower ) + const void *key, unsigned keylen, pj_uint32_t hval, + void *value, void *entry_buf, pj_bool_t lower ) { pj_hash_entry **p_entry; p_entry = find_entry( pool, ht, key, keylen, value, &hval, entry_buf, lower); if (*p_entry) { - if (value == NULL) { - /* delete entry */ - PJ_LOG(6, ("hashtbl", "%p: p_entry %p deleted", ht, *p_entry)); - *p_entry = (*p_entry)->next; - --ht->count; - - } else { - /* overwrite */ - (*p_entry)->value = value; - PJ_LOG(6, ("hashtbl", "%p: p_entry %p value set to %p", ht, - *p_entry, value)); - } + if (value == NULL) { + /* delete entry */ + PJ_LOG(6, ("hashtbl", "%p: p_entry %p deleted", ht, *p_entry)); + *p_entry = (*p_entry)->next; + --ht->count; + + } else { + /* overwrite */ + (*p_entry)->value = value; + PJ_LOG(6, ("hashtbl", "%p: p_entry %p value set to %p", ht, + *p_entry, value)); + } } } PJ_DEF(void) pj_hash_set( pj_pool_t *pool, pj_hash_table_t *ht, - const void *key, unsigned keylen, pj_uint32_t hval, - void *value ) + const void *key, unsigned keylen, pj_uint32_t hval, + void *value ) { hash_set(pool, ht, key, keylen, hval, value, NULL, PJ_FALSE); } PJ_DEF(void) pj_hash_set_lower( pj_pool_t *pool, pj_hash_table_t *ht, - const void *key, unsigned keylen, + const void *key, unsigned keylen, pj_uint32_t hval, void *value ) { hash_set(pool, ht, key, keylen, hval, value, NULL, PJ_TRUE); } PJ_DEF(void) pj_hash_set_np( pj_hash_table_t *ht, - const void *key, unsigned keylen, - pj_uint32_t hval, pj_hash_entry_buf entry_buf, - void *value) + const void *key, unsigned keylen, + pj_uint32_t hval, pj_hash_entry_buf entry_buf, + void *value) { hash_set(NULL, ht, key, keylen, hval, value, (void *)entry_buf, PJ_FALSE); } PJ_DEF(void) pj_hash_set_np_lower( pj_hash_table_t *ht, - const void *key, unsigned keylen, - pj_uint32_t hval, + const void *key, unsigned keylen, + pj_uint32_t hval, pj_hash_entry_buf entry_buf, - void *value) + void *value) { hash_set(NULL, ht, key, keylen, hval, value, (void *)entry_buf, PJ_TRUE); } @@ -288,34 +287,34 @@ PJ_DEF(unsigned) pj_hash_count( pj_hash_table_t *ht ) } PJ_DEF(pj_hash_iterator_t*) pj_hash_first( pj_hash_table_t *ht, - pj_hash_iterator_t *it ) + pj_hash_iterator_t *it ) { it->index = 0; it->entry = NULL; for (; it->index <= ht->rows; ++it->index) { - it->entry = ht->table[it->index]; - if (it->entry) { - break; - } + it->entry = ht->table[it->index]; + if (it->entry) { + break; + } } return it->entry ? it : NULL; } PJ_DEF(pj_hash_iterator_t*) pj_hash_next( pj_hash_table_t *ht, - pj_hash_iterator_t *it ) + pj_hash_iterator_t *it ) { it->entry = it->entry->next; if (it->entry) { - return it; + return it; } for (++it->index; it->index <= ht->rows; ++it->index) { - it->entry = ht->table[it->index]; - if (it->entry) { - break; - } + it->entry = ht->table[it->index]; + if (it->entry) { + break; + } } return it->entry ? it : NULL; @@ -337,25 +336,25 @@ void pj_hash_dump_collision( pj_hash_table_t *ht ) int len, totlen = 0; for (i=0; i<=ht->rows; ++i) { - unsigned count = 0; - pj_hash_entry *entry = ht->table[i]; - while (entry) { - ++count; - entry = entry->next; - } - if (count < min) - min = count; - if (count > max) - max = count; - len = pj_snprintf( line+totlen, sizeof(line)-totlen, "%3d:%3d ", i, count); - if (len < 1) - break; - totlen += len; - - if ((i+1) % 10 == 0) { - line[totlen] = '\0'; - PJ_LOG(4,(__FILE__, line)); - } + unsigned count = 0; + pj_hash_entry *entry = ht->table[i]; + while (entry) { + ++count; + entry = entry->next; + } + if (count < min) + min = count; + if (count > max) + max = count; + len = pj_snprintf( line+totlen, sizeof(line)-totlen, "%3d:%3d ", i, count); + if (len < 1) + break; + totlen += len; + + if ((i+1) % 10 == 0) { + line[totlen] = '\0'; + PJ_LOG(4,(__FILE__, line)); + } } PJ_LOG(4,(__FILE__,"Count: %d, min: %d, max: %d\n", ht->count, min, max)); diff --git a/pjlib/src/pj/ioqueue_common_abs.c b/pjlib/src/pj/ioqueue_common_abs.c index 99e4b5cc63..c257dd235e 100644 --- a/pjlib/src/pj/ioqueue_common_abs.c +++ b/pjlib/src/pj/ioqueue_common_abs.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,7 +27,7 @@ * This file is NOT supposed to be compiled as stand-alone source. */ -#define PENDING_RETRY 2 +#define PENDING_RETRY 2 PJ_DEF(void) pj_ioqueue_cfg_default(pj_ioqueue_cfg *cfg) { @@ -46,7 +45,7 @@ static void ioqueue_init( pj_ioqueue_t *ioqueue ) static pj_status_t ioqueue_destroy(pj_ioqueue_t *ioqueue) { if (ioqueue->auto_delete_lock && ioqueue->lock ) { - pj_lock_release(ioqueue->lock); + pj_lock_release(ioqueue->lock); return pj_lock_destroy(ioqueue->lock); } @@ -57,8 +56,8 @@ static pj_status_t ioqueue_destroy(pj_ioqueue_t *ioqueue) * pj_ioqueue_set_lock() */ PJ_DEF(pj_status_t) pj_ioqueue_set_lock( pj_ioqueue_t *ioqueue, - pj_lock_t *lock, - pj_bool_t auto_delete ) + pj_lock_t *lock, + pj_bool_t auto_delete ) { PJ_ASSERT_RETURN(ioqueue && lock, PJ_EINVAL); @@ -108,7 +107,7 @@ static pj_status_t ioqueue_init_key( pj_pool_t *pool, rc = pj_ioqueue_set_concurrency(key, ioqueue->cfg.default_concurrency); if (rc != PJ_SUCCESS) - return rc; + return rc; /* Get socket type. When socket type is datagram, some optimization * will be performed during send to allow parallel send operations. @@ -123,13 +122,13 @@ static pj_status_t ioqueue_init_key( pj_pool_t *pool, #if !PJ_IOQUEUE_HAS_SAFE_UNREG rc = pj_lock_create_simple_mutex(pool, NULL, &key->lock); if (rc != PJ_SUCCESS) - return rc; + return rc; #endif /* Group lock */ key->grp_lock = grp_lock; if (key->grp_lock) { - pj_grp_lock_add_ref_dbg(key->grp_lock, "ioqueue", 0); + pj_grp_lock_add_ref_dbg(key->grp_lock, "ioqueue", 0); } return PJ_SUCCESS; @@ -202,105 +201,105 @@ PJ_INLINE(int) key_has_pending_connect(pj_ioqueue_key_t *key) * framework. */ pj_bool_t ioqueue_dispatch_write_event( pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *h) + pj_ioqueue_key_t *h) { pj_status_t rc; /* Try lock the key. */ rc = pj_ioqueue_trylock_key(h); if (rc != PJ_SUCCESS) { - return PJ_FALSE; + return PJ_FALSE; } if (IS_CLOSING(h)) { - pj_ioqueue_unlock_key(h); - return PJ_TRUE; + pj_ioqueue_unlock_key(h); + return PJ_TRUE; } #if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0 if (h->connecting) { - /* Completion of connect() operation */ - pj_status_t status; - pj_bool_t has_lock; + /* Completion of connect() operation */ + pj_status_t status; + pj_bool_t has_lock; - /* Clear operation. */ - h->connecting = 0; + /* Clear operation. */ + h->connecting = 0; ioqueue_remove_from_set2(ioqueue, h, WRITEABLE_EVENT|EXCEPTION_EVENT); #if (defined(PJ_HAS_SO_ERROR) && PJ_HAS_SO_ERROR!=0) - /* from connect(2): - * On Linux, use getsockopt to read the SO_ERROR option at - * level SOL_SOCKET to determine whether connect() completed - * successfully (if SO_ERROR is zero). - */ - { - int value; - int vallen = sizeof(value); - int gs_rc = pj_sock_getsockopt(h->fd, SOL_SOCKET, SO_ERROR, - &value, &vallen); - if (gs_rc != 0) { - /* Argh!! What to do now??? - * Just indicate that the socket is connected. The - * application will get error as soon as it tries to use - * the socket to send/receive. - */ - status = PJ_SUCCESS; - } else { - status = PJ_STATUS_FROM_OS(value); - } - } + /* from connect(2): + * On Linux, use getsockopt to read the SO_ERROR option at + * level SOL_SOCKET to determine whether connect() completed + * successfully (if SO_ERROR is zero). + */ + { + int value; + int vallen = sizeof(value); + int gs_rc = pj_sock_getsockopt(h->fd, SOL_SOCKET, SO_ERROR, + &value, &vallen); + if (gs_rc != 0) { + /* Argh!! What to do now??? + * Just indicate that the socket is connected. The + * application will get error as soon as it tries to use + * the socket to send/receive. + */ + status = PJ_SUCCESS; + } else { + status = PJ_STATUS_FROM_OS(value); + } + } #elif (defined(PJ_WIN32) && PJ_WIN32!=0) || (defined(PJ_WIN64) && PJ_WIN64!=0) - status = PJ_SUCCESS; /* success */ + status = PJ_SUCCESS; /* success */ #else - /* Excellent information in D.J. Bernstein page: - * http://cr.yp.to/docs/connect.html - * - * Seems like the most portable way of detecting connect() - * failure is to call getpeername(). If socket is connected, - * getpeername() will return 0. If the socket is not connected, - * it will return ENOTCONN, and read(fd, &ch, 1) will produce - * the right errno through error slippage. This is a combination - * of suggestions from Douglas C. Schmidt and Ken Keys. - */ - { - struct sockaddr_in addr; - int addrlen = sizeof(addr); - - status = pj_sock_getpeername(h->fd, (struct sockaddr*)&addr, - &addrlen); - } + /* Excellent information in D.J. Bernstein page: + * http://cr.yp.to/docs/connect.html + * + * Seems like the most portable way of detecting connect() + * failure is to call getpeername(). If socket is connected, + * getpeername() will return 0. If the socket is not connected, + * it will return ENOTCONN, and read(fd, &ch, 1) will produce + * the right errno through error slippage. This is a combination + * of suggestions from Douglas C. Schmidt and Ken Keys. + */ + { + struct sockaddr_in addr; + int addrlen = sizeof(addr); + + status = pj_sock_getpeername(h->fd, (struct sockaddr*)&addr, + &addrlen); + } #endif /* Unlock; from this point we don't need to hold key's mutex - * (unless concurrency is disabled, which in this case we should - * hold the mutex while calling the callback) */ - if (h->allow_concurrent) { - /* concurrency may be changed while we're in the callback, so - * save it to a flag. - */ - has_lock = PJ_FALSE; - pj_ioqueue_unlock_key(h); - } else { - has_lock = PJ_TRUE; - } - - /* Call callback. */ + * (unless concurrency is disabled, which in this case we should + * hold the mutex while calling the callback) */ + if (h->allow_concurrent) { + /* concurrency may be changed while we're in the callback, so + * save it to a flag. + */ + has_lock = PJ_FALSE; + pj_ioqueue_unlock_key(h); + } else { + has_lock = PJ_TRUE; + } + + /* Call callback. */ if (h->cb.on_connect_complete && !IS_CLOSING(h)) - (*h->cb.on_connect_complete)(h, status); + (*h->cb.on_connect_complete)(h, status); - /* Unlock if we still hold the lock */ - if (has_lock) { - pj_ioqueue_unlock_key(h); - } + /* Unlock if we still hold the lock */ + if (has_lock) { + pj_ioqueue_unlock_key(h); + } /* Done. */ } else #endif /* PJ_HAS_TCP */ if (key_has_pending_write(h)) { - /* Socket is writable. */ + /* Socket is writable. */ struct write_operation *write_op; pj_ssize_t sent; pj_status_t send_rc = PJ_SUCCESS; @@ -327,41 +326,41 @@ pj_bool_t ioqueue_dispatch_write_event( pj_ioqueue_t *ioqueue, if (write_op->op == PJ_IOQUEUE_OP_SEND) { send_rc = pj_sock_send(h->fd, write_op->buf+write_op->written, &sent, write_op->flags); - /* Can't do this. We only clear "op" after we're finished sending - * the whole buffer. - */ - //write_op->op = 0; + /* Can't do this. We only clear "op" after we're finished sending + * the whole buffer. + */ + //write_op->op = 0; } else if (write_op->op == PJ_IOQUEUE_OP_SEND_TO) { - int retry = 2; - while (--retry >= 0) { - send_rc = pj_sock_sendto(h->fd, - write_op->buf+write_op->written, - &sent, write_op->flags, - &write_op->rmt_addr, - write_op->rmt_addrlen); + int retry = 2; + while (--retry >= 0) { + send_rc = pj_sock_sendto(h->fd, + write_op->buf+write_op->written, + &sent, write_op->flags, + &write_op->rmt_addr, + write_op->rmt_addrlen); #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ - PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 - /* Special treatment for dead UDP sockets here, see ticket #1107 */ - if (send_rc==PJ_STATUS_FROM_OS(EPIPE) && !IS_CLOSING(h) && - h->fd_type==pj_SOCK_DGRAM()) - { - PJ_PERROR(4,(THIS_FILE, send_rc, - "Send error for socket %d, retrying", - h->fd)); - send_rc = replace_udp_sock(h); - continue; - } + PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 + /* Special treatment for dead UDP sockets here, see ticket #1107 */ + if (send_rc==PJ_STATUS_FROM_OS(EPIPE) && !IS_CLOSING(h) && + h->fd_type==pj_SOCK_DGRAM()) + { + PJ_PERROR(4,(THIS_FILE, send_rc, + "Send error for socket %d, retrying", + h->fd)); + send_rc = replace_udp_sock(h); + continue; + } #endif - break; - } + break; + } - /* Can't do this. We only clear "op" after we're finished sending - * the whole buffer. - */ - //write_op->op = 0; + /* Can't do this. We only clear "op" after we're finished sending + * the whole buffer. + */ + //write_op->op = 0; } else { pj_assert(!"Invalid operation type!"); - write_op->op = PJ_IOQUEUE_OP_NONE; + write_op->op = PJ_IOQUEUE_OP_NONE; send_rc = PJ_EBUG; } @@ -377,9 +376,9 @@ pj_bool_t ioqueue_dispatch_write_event( pj_ioqueue_t *ioqueue, write_op->written == (pj_ssize_t)write_op->size || h->fd_type == pj_SOCK_DGRAM()) { - pj_bool_t has_lock; + pj_bool_t has_lock; - write_op->op = PJ_IOQUEUE_OP_NONE; + write_op->op = PJ_IOQUEUE_OP_NONE; if (h->fd_type != pj_SOCK_DGRAM()) { /* Write completion of the whole stream. */ @@ -391,30 +390,30 @@ pj_bool_t ioqueue_dispatch_write_event( pj_ioqueue_t *ioqueue, } - /* Unlock; from this point we don't need to hold key's mutex - * (unless concurrency is disabled, which in this case we should - * hold the mutex while calling the callback) */ - if (h->allow_concurrent) { - /* concurrency may be changed while we're in the callback, so - * save it to a flag. - */ - has_lock = PJ_FALSE; - pj_ioqueue_unlock_key(h); - PJ_RACE_ME(5); - } else { - has_lock = PJ_TRUE; - } - - /* Call callback. */ + /* Unlock; from this point we don't need to hold key's mutex + * (unless concurrency is disabled, which in this case we should + * hold the mutex while calling the callback) */ + if (h->allow_concurrent) { + /* concurrency may be changed while we're in the callback, so + * save it to a flag. + */ + has_lock = PJ_FALSE; + pj_ioqueue_unlock_key(h); + PJ_RACE_ME(5); + } else { + has_lock = PJ_TRUE; + } + + /* Call callback. */ if (h->cb.on_write_complete && !IS_CLOSING(h)) { - (*h->cb.on_write_complete)(h, + (*h->cb.on_write_complete)(h, (pj_ioqueue_op_key_t*)write_op, write_op->written); } - if (has_lock) { - pj_ioqueue_unlock_key(h); - } + if (has_lock) { + pj_ioqueue_unlock_key(h); + } } else { pj_ioqueue_unlock_key(h); @@ -427,84 +426,84 @@ pj_bool_t ioqueue_dispatch_write_event( pj_ioqueue_t *ioqueue, * are signalled for the same event, but only one thread eventually * able to process the event. */ - pj_ioqueue_unlock_key(h); + pj_ioqueue_unlock_key(h); - return PJ_FALSE; + return PJ_FALSE; } return PJ_TRUE; } pj_bool_t ioqueue_dispatch_read_event( pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *h ) + pj_ioqueue_key_t *h ) { pj_status_t rc; /* Try lock the key. */ rc = pj_ioqueue_trylock_key(h); if (rc != PJ_SUCCESS) { - return PJ_FALSE; + return PJ_FALSE; } if (IS_CLOSING(h)) { - pj_ioqueue_unlock_key(h); - return PJ_TRUE; + pj_ioqueue_unlock_key(h); + return PJ_TRUE; } # if PJ_HAS_TCP if (!pj_list_empty(&h->accept_list)) { struct accept_operation *accept_op; - pj_bool_t has_lock; - + pj_bool_t has_lock; + /* Get one accept operation from the list. */ - accept_op = h->accept_list.next; + accept_op = h->accept_list.next; pj_list_erase(accept_op); accept_op->op = PJ_IOQUEUE_OP_NONE; - /* Clear bit in fdset if there is no more pending accept */ + /* Clear bit in fdset if there is no more pending accept */ if (pj_list_empty(&h->accept_list)) ioqueue_remove_from_set(ioqueue, h, READABLE_EVENT); - rc=pj_sock_accept(h->fd, accept_op->accept_fd, + rc=pj_sock_accept(h->fd, accept_op->accept_fd, accept_op->rmt_addr, accept_op->addrlen); - if (rc==PJ_SUCCESS && accept_op->local_addr) { - rc = pj_sock_getsockname(*accept_op->accept_fd, + if (rc==PJ_SUCCESS && accept_op->local_addr) { + rc = pj_sock_getsockname(*accept_op->accept_fd, accept_op->local_addr, - accept_op->addrlen); - } - - /* Unlock; from this point we don't need to hold key's mutex - * (unless concurrency is disabled, which in this case we should - * hold the mutex while calling the callback) */ - if (h->allow_concurrent) { - /* concurrency may be changed while we're in the callback, so - * save it to a flag. - */ - has_lock = PJ_FALSE; - pj_ioqueue_unlock_key(h); - PJ_RACE_ME(5); - } else { - has_lock = PJ_TRUE; - } - - /* Call callback. */ + accept_op->addrlen); + } + + /* Unlock; from this point we don't need to hold key's mutex + * (unless concurrency is disabled, which in this case we should + * hold the mutex while calling the callback) */ + if (h->allow_concurrent) { + /* concurrency may be changed while we're in the callback, so + * save it to a flag. + */ + has_lock = PJ_FALSE; + pj_ioqueue_unlock_key(h); + PJ_RACE_ME(5); + } else { + has_lock = PJ_TRUE; + } + + /* Call callback. */ if (h->cb.on_accept_complete && !IS_CLOSING(h)) { - (*h->cb.on_accept_complete)(h, + (*h->cb.on_accept_complete)(h, (pj_ioqueue_op_key_t*)accept_op, *accept_op->accept_fd, rc); - } + } - if (has_lock) { - pj_ioqueue_unlock_key(h); - } + if (has_lock) { + pj_ioqueue_unlock_key(h); + } } else # endif if (key_has_pending_read(h)) { struct read_operation *read_op; pj_ssize_t bytes_read; - pj_bool_t has_lock; + pj_bool_t has_lock; /* Get one pending read operation from the list. */ read_op = h->read_list.next; @@ -516,19 +515,19 @@ pj_bool_t ioqueue_dispatch_read_event( pj_ioqueue_t *ioqueue, bytes_read = read_op->size; - if (read_op->op == PJ_IOQUEUE_OP_RECV_FROM) { - read_op->op = PJ_IOQUEUE_OP_NONE; - rc = pj_sock_recvfrom(h->fd, read_op->buf, &bytes_read, - read_op->flags, - read_op->rmt_addr, + if (read_op->op == PJ_IOQUEUE_OP_RECV_FROM) { + read_op->op = PJ_IOQUEUE_OP_NONE; + rc = pj_sock_recvfrom(h->fd, read_op->buf, &bytes_read, + read_op->flags, + read_op->rmt_addr, read_op->rmt_addrlen); - } else if (read_op->op == PJ_IOQUEUE_OP_RECV) { - read_op->op = PJ_IOQUEUE_OP_NONE; - rc = pj_sock_recv(h->fd, read_op->buf, &bytes_read, - read_op->flags); + } else if (read_op->op == PJ_IOQUEUE_OP_RECV) { + read_op->op = PJ_IOQUEUE_OP_NONE; + rc = pj_sock_recv(h->fd, read_op->buf, &bytes_read, + read_op->flags); } else { pj_assert(read_op->op == PJ_IOQUEUE_OP_READ); - read_op->op = PJ_IOQUEUE_OP_NONE; + read_op->op = PJ_IOQUEUE_OP_NONE; /* * User has specified pj_ioqueue_read(). * On Win32, we should do ReadFile(). But because we got @@ -541,11 +540,11 @@ pj_bool_t ioqueue_dispatch_read_event( pj_ioqueue_t *ioqueue, * read(). That's why we only specify PJ_LINUX here so * that error is easier to catch. */ -# if defined(PJ_WIN32) && PJ_WIN32 != 0 || \ - defined(PJ_WIN64) && PJ_WIN64 != 0 || \ - defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE != 0 +# if defined(PJ_WIN32) && PJ_WIN32 != 0 || \ + defined(PJ_WIN64) && PJ_WIN64 != 0 || \ + defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE != 0 rc = pj_sock_recv(h->fd, read_op->buf, &bytes_read, - read_op->flags); + read_op->flags); //rc = ReadFile((HANDLE)h->fd, read_op->buf, read_op->size, // &bytes_read, NULL); # elif (defined(PJ_HAS_UNISTD_H) && PJ_HAS_UNISTD_H != 0) @@ -555,66 +554,66 @@ pj_bool_t ioqueue_dispatch_read_event( pj_ioqueue_t *ioqueue, # error "Implement read() for this platform!" # endif } - - if (rc != PJ_SUCCESS) { -# if (defined(PJ_WIN32) && PJ_WIN32 != 0) || \ - (defined(PJ_WIN64) && PJ_WIN64 != 0) - /* On Win32, for UDP, WSAECONNRESET on the receive side - * indicates that previous sending has triggered ICMP Port - * Unreachable message. - * But we wouldn't know at this point which one of previous - * key that has triggered the error, since UDP socket can - * be shared! - * So we'll just ignore it! - */ - - if (rc == PJ_STATUS_FROM_OS(WSAECONNRESET)) { - //PJ_LOG(4,(THIS_FILE, + + if (rc != PJ_SUCCESS) { +# if (defined(PJ_WIN32) && PJ_WIN32 != 0) || \ + (defined(PJ_WIN64) && PJ_WIN64 != 0) + /* On Win32, for UDP, WSAECONNRESET on the receive side + * indicates that previous sending has triggered ICMP Port + * Unreachable message. + * But we wouldn't know at this point which one of previous + * key that has triggered the error, since UDP socket can + * be shared! + * So we'll just ignore it! + */ + + if (rc == PJ_STATUS_FROM_OS(WSAECONNRESET)) { + //PJ_LOG(4,(THIS_FILE, // "Ignored ICMP port unreach. on key=%p", h)); - } -# endif + } +# endif /* In any case we would report this to caller. */ bytes_read = -rc; #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 - /* Special treatment for dead UDP sockets here, see ticket #1107 */ - if (rc == PJ_STATUS_FROM_OS(ENOTCONN) && !IS_CLOSING(h) && - h->fd_type==pj_SOCK_DGRAM()) - { - rc = replace_udp_sock(h); - if (rc != PJ_SUCCESS) { - bytes_read = -rc; - } - } + /* Special treatment for dead UDP sockets here, see ticket #1107 */ + if (rc == PJ_STATUS_FROM_OS(ENOTCONN) && !IS_CLOSING(h) && + h->fd_type==pj_SOCK_DGRAM()) + { + rc = replace_udp_sock(h); + if (rc != PJ_SUCCESS) { + bytes_read = -rc; + } + } #endif - } - - /* Unlock; from this point we don't need to hold key's mutex - * (unless concurrency is disabled, which in this case we should - * hold the mutex while calling the callback) */ - if (h->allow_concurrent) { - /* concurrency may be changed while we're in the callback, so - * save it to a flag. - */ - has_lock = PJ_FALSE; - pj_ioqueue_unlock_key(h); - PJ_RACE_ME(5); - } else { - has_lock = PJ_TRUE; - } - - /* Call callback. */ + } + + /* Unlock; from this point we don't need to hold key's mutex + * (unless concurrency is disabled, which in this case we should + * hold the mutex while calling the callback) */ + if (h->allow_concurrent) { + /* concurrency may be changed while we're in the callback, so + * save it to a flag. + */ + has_lock = PJ_FALSE; + pj_ioqueue_unlock_key(h); + PJ_RACE_ME(5); + } else { + has_lock = PJ_TRUE; + } + + /* Call callback. */ if (h->cb.on_read_complete && !IS_CLOSING(h)) { - (*h->cb.on_read_complete)(h, + (*h->cb.on_read_complete)(h, (pj_ioqueue_op_key_t*)read_op, bytes_read); } - if (has_lock) { - pj_ioqueue_unlock_key(h); - } + if (has_lock) { + pj_ioqueue_unlock_key(h); + } } else { /* @@ -622,9 +621,9 @@ pj_bool_t ioqueue_dispatch_read_event( pj_ioqueue_t *ioqueue, * are signalled for the same event, but only one thread eventually * able to process the event. */ - pj_ioqueue_unlock_key(h); + pj_ioqueue_unlock_key(h); - return PJ_FALSE; + return PJ_FALSE; } return PJ_TRUE; @@ -632,7 +631,7 @@ pj_bool_t ioqueue_dispatch_read_event( pj_ioqueue_t *ioqueue, pj_bool_t ioqueue_dispatch_exception_event( pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *h ) + pj_ioqueue_key_t *h ) { pj_bool_t has_lock; pj_status_t rc; @@ -640,7 +639,7 @@ pj_bool_t ioqueue_dispatch_exception_event( pj_ioqueue_t *ioqueue, /* Try lock the key. */ rc = pj_ioqueue_trylock_key(h); if (rc != PJ_SUCCESS) { - return PJ_FALSE; + return PJ_FALSE; } if (!h->connecting) { @@ -648,13 +647,13 @@ pj_bool_t ioqueue_dispatch_exception_event( pj_ioqueue_t *ioqueue, * the remaining thread will see h->connecting as zero because * it has been processed by other thread. */ - pj_ioqueue_unlock_key(h); - return PJ_TRUE; + pj_ioqueue_unlock_key(h); + return PJ_TRUE; } if (IS_CLOSING(h)) { - pj_ioqueue_unlock_key(h); - return PJ_TRUE; + pj_ioqueue_unlock_key(h); + return PJ_TRUE; } /* Clear operation. */ @@ -666,34 +665,34 @@ pj_bool_t ioqueue_dispatch_exception_event( pj_ioqueue_t *ioqueue, * (unless concurrency is disabled, which in this case we should * hold the mutex while calling the callback) */ if (h->allow_concurrent) { - /* concurrency may be changed while we're in the callback, so - * save it to a flag. - */ - has_lock = PJ_FALSE; - pj_ioqueue_unlock_key(h); - PJ_RACE_ME(5); + /* concurrency may be changed while we're in the callback, so + * save it to a flag. + */ + has_lock = PJ_FALSE; + pj_ioqueue_unlock_key(h); + PJ_RACE_ME(5); } else { - has_lock = PJ_TRUE; + has_lock = PJ_TRUE; } /* Call callback. */ if (h->cb.on_connect_complete && !IS_CLOSING(h)) { - pj_status_t status = -1; + pj_status_t status = -1; #if (defined(PJ_HAS_SO_ERROR) && PJ_HAS_SO_ERROR!=0) - int value; - int vallen = sizeof(value); - int gs_rc = pj_sock_getsockopt(h->fd, SOL_SOCKET, SO_ERROR, - &value, &vallen); - if (gs_rc == 0) { - status = PJ_RETURN_OS_ERROR(value); - } + int value; + int vallen = sizeof(value); + int gs_rc = pj_sock_getsockopt(h->fd, SOL_SOCKET, SO_ERROR, + &value, &vallen); + if (gs_rc == 0) { + status = PJ_RETURN_OS_ERROR(value); + } #endif - (*h->cb.on_connect_complete)(h, status); + (*h->cb.on_connect_complete)(h, status); } if (has_lock) { - pj_ioqueue_unlock_key(h); + pj_ioqueue_unlock_key(h); } return PJ_TRUE; @@ -706,9 +705,9 @@ pj_bool_t ioqueue_dispatch_exception_event( pj_ioqueue_t *ioqueue, */ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - void *buffer, - pj_ssize_t *length, - unsigned flags ) + void *buffer, + pj_ssize_t *length, + unsigned flags ) { struct read_operation *read_op; @@ -720,7 +719,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, * #469). */ if (IS_CLOSING(key)) - return PJ_ECANCELLED; + return PJ_ECANCELLED; read_op = (struct read_operation*)op_key; PJ_ASSERT_RETURN(read_op->op == PJ_IOQUEUE_OP_NONE, PJ_EPENDING); @@ -729,22 +728,22 @@ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, /* Try to see if there's data immediately available. */ if ((flags & PJ_IOQUEUE_ALWAYS_ASYNC) == 0) { - pj_status_t status; - pj_ssize_t size; - - size = *length; - status = pj_sock_recv(key->fd, buffer, &size, flags); - if (status == PJ_SUCCESS) { - /* Yes! Data is available! */ - *length = size; - return PJ_SUCCESS; - } else { - /* If error is not EWOULDBLOCK (or EAGAIN on Linux), report - * the error to caller. - */ - if (status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) - return status; - } + pj_status_t status; + pj_ssize_t size; + + size = *length; + status = pj_sock_recv(key->fd, buffer, &size, flags); + if (status == PJ_SUCCESS) { + /* Yes! Data is available! */ + *length = size; + return PJ_SUCCESS; + } else { + /* If error is not EWOULDBLOCK (or EAGAIN on Linux), report + * the error to caller. + */ + if (status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) + return status; + } } flags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC); @@ -764,8 +763,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, * corrupt the ioqueue set. See #913 */ if (IS_CLOSING(key)) { - pj_ioqueue_unlock_key(key); - return PJ_ECANCELLED; + pj_ioqueue_unlock_key(key); + return PJ_ECANCELLED; } pj_list_insert_before(&key->read_list, read_op); ioqueue_add_to_set(key->ioqueue, key, READABLE_EVENT); @@ -781,11 +780,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, */ PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - void *buffer, - pj_ssize_t *length, + void *buffer, + pj_ssize_t *length, unsigned flags, - pj_sockaddr_t *addr, - int *addrlen) + pj_sockaddr_t *addr, + int *addrlen) { struct read_operation *read_op; @@ -794,7 +793,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, /* Check if key is closing. */ if (IS_CLOSING(key)) - return PJ_ECANCELLED; + return PJ_ECANCELLED; read_op = (struct read_operation*)op_key; PJ_ASSERT_RETURN(read_op->op == PJ_IOQUEUE_OP_NONE, PJ_EPENDING); @@ -803,23 +802,23 @@ PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, /* Try to see if there's data immediately available. */ if ((flags & PJ_IOQUEUE_ALWAYS_ASYNC) == 0) { - pj_status_t status; - pj_ssize_t size; - - size = *length; - status = pj_sock_recvfrom(key->fd, buffer, &size, flags, - addr, addrlen); - if (status == PJ_SUCCESS) { - /* Yes! Data is available! */ - *length = size; - return PJ_SUCCESS; - } else { - /* If error is not EWOULDBLOCK (or EAGAIN on Linux), report - * the error to caller. - */ - if (status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) - return status; - } + pj_status_t status; + pj_ssize_t size; + + size = *length; + status = pj_sock_recvfrom(key->fd, buffer, &size, flags, + addr, addrlen); + if (status == PJ_SUCCESS) { + /* Yes! Data is available! */ + *length = size; + return PJ_SUCCESS; + } else { + /* If error is not EWOULDBLOCK (or EAGAIN on Linux), report + * the error to caller. + */ + if (status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) + return status; + } } flags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC); @@ -841,8 +840,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, * corrupt the ioqueue set. See #913 */ if (IS_CLOSING(key)) { - pj_ioqueue_unlock_key(key); - return PJ_ECANCELLED; + pj_ioqueue_unlock_key(key); + return PJ_ECANCELLED; } pj_list_insert_before(&key->read_list, read_op); ioqueue_add_to_set(key->ioqueue, key, READABLE_EVENT); @@ -858,8 +857,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, */ PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - const void *data, - pj_ssize_t *length, + const void *data, + pj_ssize_t *length, unsigned flags) { struct write_operation *write_op; @@ -872,7 +871,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, /* Check if key is closing. */ if (IS_CLOSING(key)) - return PJ_ECANCELLED; + return PJ_ECANCELLED; /* We can not use PJ_IOQUEUE_ALWAYS_ASYNC for socket write. */ flags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC); @@ -918,29 +917,29 @@ PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, /* Spin if write_op has pending operation */ for (retry=0; write_op->op != 0 && retryop) { - /* Unable to send packet because there is already pending write in the - * write_op. We could not put the operation into the write_op - * because write_op already contains a pending operation! And - * we could not send the packet directly with send() either, - * because that will break the order of the packet. So we can - * only return error here. - * - * This could happen for example in multithreads program, - * where polling is done by one thread, while other threads are doing - * the sending only. If the polling thread runs on lower priority - * than the sending thread, then it's possible that the pending - * write flag is not cleared in-time because clearing is only done - * during polling. - * - * Aplication should specify multiple write operation keys on - * situation like this. - */ - //pj_assert(!"ioqueue: there is pending operation on this key!"); - return PJ_EBUSY; + /* Unable to send packet because there is already pending write in the + * write_op. We could not put the operation into the write_op + * because write_op already contains a pending operation! And + * we could not send the packet directly with send() either, + * because that will break the order of the packet. So we can + * only return error here. + * + * This could happen for example in multithreads program, + * where polling is done by one thread, while other threads are doing + * the sending only. If the polling thread runs on lower priority + * than the sending thread, then it's possible that the pending + * write flag is not cleared in-time because clearing is only done + * during polling. + * + * Aplication should specify multiple write operation keys on + * situation like this. + */ + //pj_assert(!"ioqueue: there is pending operation on this key!"); + return PJ_EBUSY; } write_op->op = PJ_IOQUEUE_OP_SEND; @@ -955,8 +954,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, * corrupt the ioqueue set. See #913 */ if (IS_CLOSING(key)) { - pj_ioqueue_unlock_key(key); - return PJ_ECANCELLED; + pj_ioqueue_unlock_key(key); + return PJ_ECANCELLED; } pj_list_insert_before(&key->write_list, write_op); ioqueue_add_to_set(key->ioqueue, key, WRITEABLE_EVENT); @@ -973,11 +972,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, */ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - const void *data, - pj_ssize_t *length, + const void *data, + pj_ssize_t *length, pj_uint32_t flags, - const pj_sockaddr_t *addr, - int addrlen) + const pj_sockaddr_t *addr, + int addrlen) { struct write_operation *write_op; unsigned retry; @@ -989,14 +988,14 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, PJ_CHECK_STACK(); #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ - PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 + PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 retry_on_restart: #else PJ_UNUSED_ARG(restart_retry); #endif /* Check if key is closing. */ if (IS_CLOSING(key)) - return PJ_ECANCELLED; + return PJ_ECANCELLED; /* We can not use PJ_IOQUEUE_ALWAYS_ASYNC for socket write */ flags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC); @@ -1031,23 +1030,23 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, */ if (status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) { #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ - PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 - /* Special treatment for dead UDP sockets here, see ticket #1107 */ - if (status == PJ_STATUS_FROM_OS(EPIPE) && !IS_CLOSING(key) && - key->fd_type == pj_SOCK_DGRAM()) - { - if (!restart_retry) { - PJ_PERROR(4, (THIS_FILE, status, - "Send error for socket %d, retrying", - key->fd)); - status = replace_udp_sock(key); - if (status == PJ_SUCCESS) { - restart_retry = PJ_TRUE; - goto retry_on_restart; - } - } - status = PJ_ESOCKETSTOP; - } + PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 + /* Special treatment for dead UDP sockets here, see ticket #1107 */ + if (status == PJ_STATUS_FROM_OS(EPIPE) && !IS_CLOSING(key) && + key->fd_type == pj_SOCK_DGRAM()) + { + if (!restart_retry) { + PJ_PERROR(4, (THIS_FILE, status, + "Send error for socket %d, retrying", + key->fd)); + status = replace_udp_sock(key); + if (status == PJ_SUCCESS) { + restart_retry = PJ_TRUE; + goto retry_on_restart; + } + } + status = PJ_ESOCKETSTOP; + } #endif return status; } @@ -1066,29 +1065,29 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, /* Spin if write_op has pending operation */ for (retry=0; write_op->op != 0 && retryop) { - /* Unable to send packet because there is already pending write on the - * write_op. We could not put the operation into the write_op - * because write_op already contains a pending operation! And - * we could not send the packet directly with sendto() either, - * because that will break the order of the packet. So we can - * only return error here. - * - * This could happen for example in multithreads program, - * where polling is done by one thread, while other threads are doing - * the sending only. If the polling thread runs on lower priority - * than the sending thread, then it's possible that the pending - * write flag is not cleared in-time because clearing is only done - * during polling. - * - * Aplication should specify multiple write operation keys on - * situation like this. - */ - //pj_assert(!"ioqueue: there is pending operation on this key!"); - return PJ_EBUSY; + /* Unable to send packet because there is already pending write on the + * write_op. We could not put the operation into the write_op + * because write_op already contains a pending operation! And + * we could not send the packet directly with sendto() either, + * because that will break the order of the packet. So we can + * only return error here. + * + * This could happen for example in multithreads program, + * where polling is done by one thread, while other threads are doing + * the sending only. If the polling thread runs on lower priority + * than the sending thread, then it's possible that the pending + * write flag is not cleared in-time because clearing is only done + * during polling. + * + * Aplication should specify multiple write operation keys on + * situation like this. + */ + //pj_assert(!"ioqueue: there is pending operation on this key!"); + return PJ_EBUSY; } write_op->op = PJ_IOQUEUE_OP_SEND_TO; @@ -1105,8 +1104,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, * corrupt the ioqueue set. See #913 */ if (IS_CLOSING(key)) { - pj_ioqueue_unlock_key(key); - return PJ_ECANCELLED; + pj_ioqueue_unlock_key(key); + return PJ_ECANCELLED; } pj_list_insert_before(&key->write_list, write_op); ioqueue_add_to_set(key->ioqueue, key, WRITEABLE_EVENT); @@ -1121,10 +1120,10 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, */ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - pj_sock_t *new_sock, - pj_sockaddr_t *local, - pj_sockaddr_t *remote, - int *addrlen) + pj_sock_t *new_sock, + pj_sockaddr_t *local, + pj_sockaddr_t *remote, + int *addrlen) { struct accept_operation *accept_op; pj_status_t status; @@ -1134,7 +1133,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, /* Check if key is closing. */ if (IS_CLOSING(key)) - return PJ_ECANCELLED; + return PJ_ECANCELLED; accept_op = (struct accept_operation*)op_key; PJ_ASSERT_RETURN(accept_op->op == PJ_IOQUEUE_OP_NONE, PJ_EPENDING); @@ -1183,8 +1182,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, * corrupt the ioqueue set. See #913 */ if (IS_CLOSING(key)) { - pj_ioqueue_unlock_key(key); - return PJ_ECANCELLED; + pj_ioqueue_unlock_key(key); + return PJ_ECANCELLED; } pj_list_insert_before(&key->accept_list, accept_op); ioqueue_add_to_set(key->ioqueue, key, READABLE_EVENT); @@ -1198,8 +1197,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, * since there's no overlapped version of connect()). */ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, - const pj_sockaddr_t *addr, - int addrlen ) + const pj_sockaddr_t *addr, + int addrlen ) { pj_status_t status; @@ -1208,7 +1207,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, /* Check if key is closing. */ if (IS_CLOSING(key)) - return PJ_ECANCELLED; + return PJ_ECANCELLED; /* Check if socket has not been marked for connecting */ if (key->connecting != 0) @@ -1216,35 +1215,35 @@ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, status = pj_sock_connect(key->fd, addr, addrlen); if (status == PJ_SUCCESS) { - /* Connected! */ - return PJ_SUCCESS; + /* Connected! */ + return PJ_SUCCESS; } else { - if (status == PJ_STATUS_FROM_OS(PJ_BLOCKING_CONNECT_ERROR_VAL)) { - /* Pending! */ - pj_ioqueue_lock_key(key); - /* Check again. Handle may have been closed after the previous - * check in multithreaded app. See #913 - */ - if (IS_CLOSING(key)) { - pj_ioqueue_unlock_key(key); - return PJ_ECANCELLED; - } - key->connecting = PJ_TRUE; + if (status == PJ_STATUS_FROM_OS(PJ_BLOCKING_CONNECT_ERROR_VAL)) { + /* Pending! */ + pj_ioqueue_lock_key(key); + /* Check again. Handle may have been closed after the previous + * check in multithreaded app. See #913 + */ + if (IS_CLOSING(key)) { + pj_ioqueue_unlock_key(key); + return PJ_ECANCELLED; + } + key->connecting = PJ_TRUE; ioqueue_add_to_set2(key->ioqueue, key, - WRITEABLE_EVENT|EXCEPTION_EVENT); + WRITEABLE_EVENT|EXCEPTION_EVENT); pj_ioqueue_unlock_key(key); - return PJ_EPENDING; - } else { - /* Error! */ - return status; - } + return PJ_EPENDING; + } else { + /* Error! */ + return status; + } } } -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ PJ_DEF(void) pj_ioqueue_op_key_init( pj_ioqueue_op_key_t *op_key, - pj_size_t size ) + pj_size_t size ) { pj_bzero(op_key, size); } @@ -1290,7 +1289,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_post_completion( pj_ioqueue_key_t *key, pj_ioqueue_unlock_key(key); if (key->cb.on_read_complete) - (*key->cb.on_read_complete)(key, op_key, bytes_status); + (*key->cb.on_read_complete)(key, op_key, bytes_status); return PJ_SUCCESS; } op_rec = op_rec->next; @@ -1306,7 +1305,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_post_completion( pj_ioqueue_key_t *key, pj_ioqueue_unlock_key(key); if (key->cb.on_write_complete) - (*key->cb.on_write_complete)(key, op_key, bytes_status); + (*key->cb.on_write_complete)(key, op_key, bytes_status); return PJ_SUCCESS; } op_rec = op_rec->next; @@ -1321,7 +1320,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_post_completion( pj_ioqueue_key_t *key, pj_ioqueue_unlock_key(key); if (key->cb.on_accept_complete) { - (*key->cb.on_accept_complete)(key, op_key, + (*key->cb.on_accept_complete)(key, op_key, PJ_INVALID_SOCKET, (pj_status_t)bytes_status); } @@ -1334,7 +1333,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_post_completion( pj_ioqueue_key_t *key, if (key->connecting) { key->connecting = 0; ioqueue_remove_from_set2(key->ioqueue, key, - WRITEABLE_EVENT|EXCEPTION_EVENT); + WRITEABLE_EVENT|EXCEPTION_EVENT); } pj_ioqueue_unlock_key(key); @@ -1357,7 +1356,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_clear_key( pj_ioqueue_key_t *key ) /* Remove key from sets */ ioqueue_remove_from_set2(key->ioqueue, key, - READABLE_EVENT|WRITEABLE_EVENT|EXCEPTION_EVENT); + READABLE_EVENT|WRITEABLE_EVENT|EXCEPTION_EVENT); pj_ioqueue_unlock_key(key); @@ -1367,7 +1366,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_clear_key( pj_ioqueue_key_t *key ) PJ_DEF(pj_status_t) pj_ioqueue_set_default_concurrency( pj_ioqueue_t *ioqueue, - pj_bool_t allow) + pj_bool_t allow) { PJ_ASSERT_RETURN(ioqueue != NULL, PJ_EINVAL); ioqueue->cfg.default_concurrency = allow; @@ -1376,7 +1375,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_set_default_concurrency( pj_ioqueue_t *ioqueue, PJ_DEF(pj_status_t) pj_ioqueue_set_concurrency(pj_ioqueue_key_t *key, - pj_bool_t allow) + pj_bool_t allow) { PJ_ASSERT_RETURN(key, PJ_EINVAL); @@ -1392,25 +1391,25 @@ PJ_DEF(pj_status_t) pj_ioqueue_set_concurrency(pj_ioqueue_key_t *key, PJ_DEF(pj_status_t) pj_ioqueue_lock_key(pj_ioqueue_key_t *key) { if (key->grp_lock) - return pj_grp_lock_acquire(key->grp_lock); + return pj_grp_lock_acquire(key->grp_lock); else - return pj_lock_acquire(key->lock); + return pj_lock_acquire(key->lock); } PJ_DEF(pj_status_t) pj_ioqueue_trylock_key(pj_ioqueue_key_t *key) { if (key->grp_lock) - return pj_grp_lock_tryacquire(key->grp_lock); + return pj_grp_lock_tryacquire(key->grp_lock); else - return pj_lock_tryacquire(key->lock); + return pj_lock_tryacquire(key->lock); } PJ_DEF(pj_status_t) pj_ioqueue_unlock_key(pj_ioqueue_key_t *key) { if (key->grp_lock) - return pj_grp_lock_release(key->grp_lock); + return pj_grp_lock_release(key->grp_lock); else - return pj_lock_release(key->lock); + return pj_lock_release(key->lock); } diff --git a/pjlib/src/pj/ioqueue_common_abs.h b/pjlib/src/pj/ioqueue_common_abs.h index 936a7951cc..77787b15c6 100644 --- a/pjlib/src/pj/ioqueue_common_abs.h +++ b/pjlib/src/pj/ioqueue_common_abs.h @@ -47,11 +47,11 @@ struct read_operation PJ_DECL_LIST_MEMBER(struct read_operation); pj_ioqueue_operation_e op; - void *buf; - pj_size_t size; + void *buf; + pj_size_t size; unsigned flags; - pj_sockaddr_t *rmt_addr; - int *rmt_addrlen; + pj_sockaddr_t *rmt_addr; + int *rmt_addrlen; }; struct write_operation @@ -59,12 +59,12 @@ struct write_operation PJ_DECL_LIST_MEMBER(struct write_operation); pj_ioqueue_operation_e op; - char *buf; - pj_size_t size; + char *buf; + pj_size_t size; pj_ssize_t written; unsigned flags; - pj_sockaddr_in rmt_addr; - int rmt_addrlen; + pj_sockaddr_in rmt_addr; + int rmt_addrlen; }; struct accept_operation @@ -73,9 +73,9 @@ struct accept_operation pj_ioqueue_operation_e op; pj_sock_t *accept_fd; - pj_sockaddr_t *local_addr; - pj_sockaddr_t *rmt_addr; - int *addrlen; + pj_sockaddr_t *local_addr; + pj_sockaddr_t *rmt_addr; + int *addrlen; }; union operation_key @@ -89,11 +89,11 @@ union operation_key }; #if PJ_IOQUEUE_HAS_SAFE_UNREG -# define UNREG_FIELDS \ - unsigned ref_count; \ - pj_bool_t closing; \ - pj_time_val free_time; \ - +# define UNREG_FIELDS \ + unsigned ref_count; \ + pj_bool_t closing; \ + pj_time_val free_time; \ + #else # define UNREG_FIELDS #endif @@ -101,25 +101,25 @@ union operation_key #define DECLARE_COMMON_KEY \ PJ_DECL_LIST_MEMBER(struct pj_ioqueue_key_t); \ pj_ioqueue_t *ioqueue; \ - pj_grp_lock_t *grp_lock; \ + pj_grp_lock_t *grp_lock; \ pj_lock_t *lock; \ - pj_bool_t inside_callback; \ - pj_bool_t destroy_requested; \ - pj_bool_t allow_concurrent; \ - pj_sock_t fd; \ + pj_bool_t inside_callback; \ + pj_bool_t destroy_requested; \ + pj_bool_t allow_concurrent; \ + pj_sock_t fd; \ int fd_type; \ - void *user_data; \ - pj_ioqueue_callback cb; \ + void *user_data; \ + pj_ioqueue_callback cb; \ int connecting; \ struct read_operation read_list; \ struct write_operation write_list; \ - struct accept_operation accept_list; \ + struct accept_operation accept_list; \ UNREG_FIELDS #define DECLARE_COMMON_IOQUEUE \ pj_lock_t *lock; \ - pj_bool_t auto_delete_lock; \ + pj_bool_t auto_delete_lock; \ pj_ioqueue_cfg cfg; diff --git a/pjlib/src/pj/ioqueue_dummy.c b/pjlib/src/pj/ioqueue_dummy.c index 43dd162515..fb373b417f 100644 --- a/pjlib/src/pj/ioqueue_dummy.c +++ b/pjlib/src/pj/ioqueue_dummy.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,32 +29,32 @@ #define THIS_FILE "ioqueue" #define PJ_IOQUEUE_IS_READ_OP(op) \ - ((op & PJ_IOQUEUE_OP_READ) || (op & PJ_IOQUEUE_OP_RECV_FROM)) + ((op & PJ_IOQUEUE_OP_READ) || (op & PJ_IOQUEUE_OP_RECV_FROM)) #define PJ_IOQUEUE_IS_WRITE_OP(op) \ - ((op & PJ_IOQUEUE_OP_WRITE) || (op & PJ_IOQUEUE_OP_SEND_TO)) + ((op & PJ_IOQUEUE_OP_WRITE) || (op & PJ_IOQUEUE_OP_SEND_TO)) #if PJ_HAS_TCP -# define PJ_IOQUEUE_IS_ACCEPT_OP(op) (op & PJ_IOQUEUE_OP_ACCEPT) -# define PJ_IOQUEUE_IS_CONNECT_OP(op) (op & PJ_IOQUEUE_OP_CONNECT) +# define PJ_IOQUEUE_IS_ACCEPT_OP(op) (op & PJ_IOQUEUE_OP_ACCEPT) +# define PJ_IOQUEUE_IS_CONNECT_OP(op) (op & PJ_IOQUEUE_OP_CONNECT) #else -# define PJ_IOQUEUE_IS_ACCEPT_OP(op) 0 -# define PJ_IOQUEUE_IS_CONNECT_OP(op) 0 +# define PJ_IOQUEUE_IS_ACCEPT_OP(op) 0 +# define PJ_IOQUEUE_IS_CONNECT_OP(op) 0 #endif #if defined(PJ_DEBUG) && PJ_DEBUG != 0 -# define VALIDATE_FD_SET 1 +# define VALIDATE_FD_SET 1 #else -# define VALIDATE_FD_SET 0 +# define VALIDATE_FD_SET 0 #endif struct pj_ioqueue_key_t { PJ_DECL_LIST_MEMBER(struct pj_ioqueue_key_t) - pj_sock_t fd; + pj_sock_t fd; pj_ioqueue_operation_e op; - void *user_data; - pj_ioqueue_callback cb; + void *user_data; + pj_ioqueue_callback cb; }; struct pj_ioqueue_t @@ -63,9 +62,9 @@ struct pj_ioqueue_t }; PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, - pj_size_t max_fd, - int max_threads, - pj_ioqueue_t **ptr_ioqueue) + pj_size_t max_fd, + int max_threads, + pj_ioqueue_t **ptr_ioqueue) { return PJ_ENOTSUP; } @@ -76,24 +75,24 @@ PJ_DEF(pj_status_t) pj_ioqueue_destroy(pj_ioqueue_t *ioque) } PJ_DEF(pj_status_t) pj_ioqueue_set_lock( pj_ioqueue_t *ioque, - pj_lock_t *lock, - pj_bool_t auto_delete ) + pj_lock_t *lock, + pj_bool_t auto_delete ) { return PJ_ENOTSUP; } PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, - pj_ioqueue_t *ioque, - pj_sock_t sock, - void *user_data, - const pj_ioqueue_callback *cb, - pj_ioqueue_key_t **ptr_key) + pj_ioqueue_t *ioque, + pj_sock_t sock, + void *user_data, + const pj_ioqueue_callback *cb, + pj_ioqueue_key_t **ptr_key) { return PJ_ENOTSUP; } PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_t *ioque, - pj_ioqueue_key_t *key) + pj_ioqueue_key_t *key) { return PJ_ENOTSUP; } @@ -110,57 +109,57 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioque, const pj_time_val *timeout) } PJ_DEF(pj_status_t) pj_ioqueue_read( pj_ioqueue_t *ioque, - pj_ioqueue_key_t *key, - void *buffer, - pj_size_t buflen) + pj_ioqueue_key_t *key, + void *buffer, + pj_size_t buflen) { return -1; } PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_t *ioque, - pj_ioqueue_key_t *key, - void *buffer, - pj_size_t buflen, - unsigned flags) + pj_ioqueue_key_t *key, + void *buffer, + pj_size_t buflen, + unsigned flags) { return -1; } PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_t *ioque, - pj_ioqueue_key_t *key, - void *buffer, - pj_size_t buflen, - unsigned flags, - pj_sockaddr_t *addr, - int *addrlen) + pj_ioqueue_key_t *key, + void *buffer, + pj_size_t buflen, + unsigned flags, + pj_sockaddr_t *addr, + int *addrlen) { return -1; } PJ_DEF(pj_status_t) pj_ioqueue_write( pj_ioqueue_t *ioque, - pj_ioqueue_key_t *key, - const void *data, - pj_size_t datalen) + pj_ioqueue_key_t *key, + const void *data, + pj_size_t datalen) { return -1; } PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_t *ioque, - pj_ioqueue_key_t *key, - const void *data, - pj_size_t datalen, - unsigned flags) + pj_ioqueue_key_t *key, + const void *data, + pj_size_t datalen, + unsigned flags) { return -1; } PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_t *ioque, - pj_ioqueue_key_t *key, - const void *data, - pj_size_t datalen, - unsigned flags, - const pj_sockaddr_t *addr, - int addrlen) + pj_ioqueue_key_t *key, + const void *data, + pj_size_t datalen, + unsigned flags, + const pj_sockaddr_t *addr, + int addrlen) { return -1; } @@ -170,11 +169,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_t *ioque, * Initiate overlapped accept() operation. */ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - pj_sock_t *new_sock, - pj_sockaddr_t *local, - pj_sockaddr_t *remote, - int *addrlen) + pj_ioqueue_key_t *key, + pj_sock_t *new_sock, + pj_sockaddr_t *local, + pj_sockaddr_t *remote, + int *addrlen) { return -1; } @@ -184,11 +183,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_t *ioqueue, * since there's no overlapped version of connect()). */ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - const pj_sockaddr_t *addr, - int addrlen ) + pj_ioqueue_key_t *key, + const pj_sockaddr_t *addr, + int addrlen ) { return -1; } -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ diff --git a/pjlib/src/pj/ioqueue_epoll.c b/pjlib/src/pj/ioqueue_epoll.c index 21cb41fc4d..6a6bc72026 100644 --- a/pjlib/src/pj/ioqueue_epoll.c +++ b/pjlib/src/pj/ioqueue_epoll.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -42,17 +41,17 @@ #include #include -#define epoll_data data.ptr -#define epoll_data_type void* -#define ioctl_val_type unsigned long -#define getsockopt_val_ptr int* -#define os_getsockopt getsockopt -#define os_ioctl ioctl -#define os_read read -#define os_close close -#define os_epoll_create epoll_create -#define os_epoll_ctl epoll_ctl -#define os_epoll_wait epoll_wait +#define epoll_data data.ptr +#define epoll_data_type void* +#define ioctl_val_type unsigned long +#define getsockopt_val_ptr int* +#define os_getsockopt getsockopt +#define os_ioctl ioctl +#define os_read read +#define os_close close +#define os_epoll_create epoll_create +#define os_epoll_ctl epoll_ctl +#define os_epoll_wait epoll_wait #define THIS_FILE "ioq_epoll" @@ -63,12 +62,12 @@ /* Enable this during development to warn against stray events. * But don't enable this during production, for performance reason. */ -//#define TRACE_WARN(expr) PJ_LOG(2,expr) +//#define TRACE_WARN(expr) PJ_LOG(2,expr) #define TRACE_WARN(expr) #ifndef EPOLLEXCLUSIVE -# define EPOLLEXCLUSIVE (1U << 28) +# define EPOLLEXCLUSIVE (1U << 28) #endif enum { IO_MASK = EPOLLIN | EPOLLOUT | EPOLLERR }; @@ -91,7 +90,7 @@ struct pj_ioqueue_key_t struct queue { - pj_ioqueue_key_t *key; + pj_ioqueue_key_t *key; enum ioqueue_event_type event_type; }; @@ -102,17 +101,17 @@ struct pj_ioqueue_t { DECLARE_COMMON_IOQUEUE - unsigned max, count; - //pj_ioqueue_key_t hlist; - pj_ioqueue_key_t active_list; - int epfd; + unsigned max, count; + //pj_ioqueue_key_t hlist; + pj_ioqueue_key_t active_list; + int epfd; //struct epoll_event *events; //struct queue *queue; #if PJ_IOQUEUE_HAS_SAFE_UNREG - pj_mutex_t *ref_cnt_mutex; - pj_ioqueue_key_t closing_list; - pj_ioqueue_key_t free_list; + pj_mutex_t *ref_cnt_mutex; + pj_ioqueue_key_t closing_list; + pj_ioqueue_key_t free_list; #endif }; @@ -155,22 +154,22 @@ static unsigned detect_epoll_support() /* Note: this function should be thread-safe */ if (epoll_support != -1) - return epoll_support; + return epoll_support; #ifdef DISABLE_EXCLUSIVE_ONESHOT PJ_LOG(3,(THIS_FILE, "epoll EXCLUSIVE/ONESHOT support disabled, reason: %s", - DISABLE_EXCLUSIVE_ONESHOT)); + DISABLE_EXCLUSIVE_ONESHOT)); epoll_support = 0; return epoll_support; #endif epfd = os_epoll_create(5); if (epfd < 0) - goto on_error; + goto on_error; evfd = eventfd(0, 0); if (evfd < 0) - goto on_error; + goto on_error; /* * Choose events that should cause an error on EPOLLEXCLUSIVE enabled @@ -181,57 +180,57 @@ static unsigned detect_epoll_support() ev.events = EPOLLIN | EPOLLEXCLUSIVE | EPOLLONESHOT; rc = epoll_ctl(epfd, EPOLL_CTL_ADD, evfd, &ev); if (rc == 0) { - /* The kernel has accepted our invalid request. Assume it probably - * doesn't know about/support EPOLLEXCLUSIVE. But we assume that - * it may still be able to support EPOLLONESHOT, since this was - * added very long time ago. - */ - disable_exclusive = 1; - rc = epoll_ctl(epfd, EPOLL_CTL_DEL, evfd, &ev); - if (rc != 0) - goto on_error; + /* The kernel has accepted our invalid request. Assume it probably + * doesn't know about/support EPOLLEXCLUSIVE. But we assume that + * it may still be able to support EPOLLONESHOT, since this was + * added very long time ago. + */ + disable_exclusive = 1; + rc = epoll_ctl(epfd, EPOLL_CTL_DEL, evfd, &ev); + if (rc != 0) + goto on_error; } else if (errno != EINVAL) { - /* Unexpected error */ - goto on_error; + /* Unexpected error */ + goto on_error; } /* Check EPOLLEXCLUSIVE support */ if (!disable_exclusive) { - ev.events = EPOLLIN | EPOLLEXCLUSIVE; - rc = epoll_ctl(epfd, EPOLL_CTL_ADD, evfd, &ev); - if (rc == 0) { - support_exclusive = 1; - rc = epoll_ctl(epfd, EPOLL_CTL_DEL, evfd, &ev); - if (rc != 0) - goto on_error; - } + ev.events = EPOLLIN | EPOLLEXCLUSIVE; + rc = epoll_ctl(epfd, EPOLL_CTL_ADD, evfd, &ev); + if (rc == 0) { + support_exclusive = 1; + rc = epoll_ctl(epfd, EPOLL_CTL_DEL, evfd, &ev); + if (rc != 0) + goto on_error; + } } /* Check EPOLLONESHOT support */ ev.events = EPOLLIN | EPOLLONESHOT; rc = epoll_ctl(epfd, EPOLL_CTL_ADD, evfd, &ev); if (rc == 0) { - support_oneshot = 1; - rc = epoll_ctl(epfd, EPOLL_CTL_DEL, evfd, &ev); - if (rc != 0) - goto on_error; + support_oneshot = 1; + rc = epoll_ctl(epfd, EPOLL_CTL_DEL, evfd, &ev); + if (rc != 0) + goto on_error; } tmp_epoll_support = 0; if (support_exclusive && !disable_exclusive) - tmp_epoll_support |= PJ_IOQUEUE_EPOLL_EXCLUSIVE; + tmp_epoll_support |= PJ_IOQUEUE_EPOLL_EXCLUSIVE; if (support_oneshot) - tmp_epoll_support |= PJ_IOQUEUE_EPOLL_ONESHOT; + tmp_epoll_support |= PJ_IOQUEUE_EPOLL_ONESHOT; pj_ansi_snprintf(ioq_name, sizeof(ioq_name), "epoll[0x%x]", - tmp_epoll_support); + tmp_epoll_support); epoll_support = tmp_epoll_support; if (epfd > 0) - os_close(epfd); + os_close(epfd); if (evfd > 0) - os_close(evfd); + os_close(evfd); return epoll_support; @@ -239,9 +238,9 @@ static unsigned detect_epoll_support() rc = PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); PJ_PERROR(2,(THIS_FILE, rc, "detect_epoll_support() error")); if (epfd >= 0) - os_close(epfd); + os_close(epfd); if (evfd >= 0) - os_close(evfd); + os_close(evfd); return 0; } @@ -274,14 +273,14 @@ PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, */ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, pj_size_t max_fd, - const pj_ioqueue_cfg *cfg, + const pj_ioqueue_cfg *cfg, pj_ioqueue_t **p_ioqueue) { pj_ioqueue_t *ioqueue; pj_status_t rc; pj_lock_t *lock; const unsigned type_mask = PJ_IOQUEUE_EPOLL_EXCLUSIVE | - PJ_IOQUEUE_EPOLL_ONESHOT; + PJ_IOQUEUE_EPOLL_ONESHOT; unsigned epoll_support, valid_types; int i; @@ -298,10 +297,10 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, ioqueue_init(ioqueue); if (cfg) - pj_memcpy(&ioqueue->cfg, cfg, sizeof(*cfg)); + pj_memcpy(&ioqueue->cfg, cfg, sizeof(*cfg)); else { - pj_ioqueue_cfg_default(&ioqueue->cfg); - cfg = &ioqueue->cfg; + pj_ioqueue_cfg_default(&ioqueue->cfg); + cfg = &ioqueue->cfg; } ioqueue->max = max_fd; ioqueue->count = 0; @@ -317,14 +316,14 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, */ ioqueue->cfg.epoll_flags &= ~type_mask; if (valid_types & PJ_IOQUEUE_EPOLL_EXCLUSIVE) { - ioqueue->cfg.epoll_flags |= PJ_IOQUEUE_EPOLL_EXCLUSIVE; + ioqueue->cfg.epoll_flags |= PJ_IOQUEUE_EPOLL_EXCLUSIVE; } else if (valid_types & PJ_IOQUEUE_EPOLL_ONESHOT) { - ioqueue->cfg.epoll_flags |= PJ_IOQUEUE_EPOLL_ONESHOT; + ioqueue->cfg.epoll_flags |= PJ_IOQUEUE_EPOLL_ONESHOT; } else if ((cfg->epoll_flags & type_mask) == 0) { - /* user has disabled both EXCLUSIVE and ONESHOT */ + /* user has disabled both EXCLUSIVE and ONESHOT */ } else { - /* the requested epoll type is not available */ - return PJ_EINVAL; + /* the requested epoll type is not available */ + return PJ_EINVAL; } #if PJ_IOQUEUE_HAS_SAFE_UNREG @@ -338,7 +337,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, */ rc = pj_mutex_create_simple(pool, NULL, &ioqueue->ref_cnt_mutex); if (rc != PJ_SUCCESS) - return rc; + return rc; /* Init key list */ @@ -348,28 +347,28 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, /* Pre-create all keys according to max_fd */ for ( i=0; iref_count = 0; - rc = pj_lock_create_recursive_mutex(pool, NULL, &key->lock); - if (rc != PJ_SUCCESS) { - key = ioqueue->free_list.next; - while (key != &ioqueue->free_list) { - pj_lock_destroy(key->lock); - key = key->next; - } - pj_mutex_destroy(ioqueue->ref_cnt_mutex); - return rc; - } - - pj_list_push_back(&ioqueue->free_list, key); + pj_ioqueue_key_t *key; + + key = PJ_POOL_ALLOC_T(pool, pj_ioqueue_key_t); + key->ref_count = 0; + rc = pj_lock_create_recursive_mutex(pool, NULL, &key->lock); + if (rc != PJ_SUCCESS) { + key = ioqueue->free_list.next; + while (key != &ioqueue->free_list) { + pj_lock_destroy(key->lock); + key = key->next; + } + pj_mutex_destroy(ioqueue->ref_cnt_mutex); + return rc; + } + + pj_list_push_back(&ioqueue->free_list, key); } #endif rc = pj_lock_create_simple_mutex(pool, "ioq%p", &lock); if (rc != PJ_SUCCESS) - return rc; + return rc; rc = pj_ioqueue_set_lock(ioqueue, lock, PJ_TRUE); if (rc != PJ_SUCCESS) @@ -377,9 +376,9 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, ioqueue->epfd = os_epoll_create(max_fd); if (ioqueue->epfd < 0) { - pj_lock_acquire(ioqueue->lock); - ioqueue_destroy(ioqueue); - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + pj_lock_acquire(ioqueue->lock); + ioqueue_destroy(ioqueue); + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); } /*ioqueue->events = pj_pool_calloc(pool, max_fd, sizeof(struct epoll_event)); @@ -390,7 +389,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, */ PJ_LOG(4, ("pjlib", "epoll I/O Queue created (flags:0x%x, ptr=%p)", - ioqueue->cfg.epoll_flags, ioqueue)); + ioqueue->cfg.epoll_flags, ioqueue)); *p_ioqueue = ioqueue; return PJ_SUCCESS; @@ -416,20 +415,20 @@ PJ_DEF(pj_status_t) pj_ioqueue_destroy(pj_ioqueue_t *ioqueue) /* Destroy reference counters */ key = ioqueue->active_list.next; while (key != &ioqueue->active_list) { - pj_lock_destroy(key->lock); - key = key->next; + pj_lock_destroy(key->lock); + key = key->next; } key = ioqueue->closing_list.next; while (key != &ioqueue->closing_list) { - pj_lock_destroy(key->lock); - key = key->next; + pj_lock_destroy(key->lock); + key = key->next; } key = ioqueue->free_list.next; while (key != &ioqueue->free_list) { - pj_lock_destroy(key->lock); - key = key->next; + pj_lock_destroy(key->lock); + key = key->next; } pj_mutex_destroy(ioqueue->ref_cnt_mutex); @@ -443,11 +442,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_destroy(pj_ioqueue_t *ioqueue) * Register a socket to ioqueue. */ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, - pj_ioqueue_t *ioqueue, - pj_sock_t sock, - pj_grp_lock_t *grp_lock, - void *user_data, - const pj_ioqueue_callback *cb, + pj_ioqueue_t *ioqueue, + pj_sock_t sock, + pj_grp_lock_t *grp_lock, + void *user_data, + const pj_ioqueue_callback *cb, pj_ioqueue_key_t **p_key) { pj_ioqueue_key_t *key = NULL; @@ -462,17 +461,17 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, if (ioqueue->count >= ioqueue->max) { status = PJ_ETOOMANY; - TRACE_((THIS_FILE, "pj_ioqueue_register_sock error: too many files")); - goto on_return; + TRACE_((THIS_FILE, "pj_ioqueue_register_sock error: too many files")); + goto on_return; } /* Set socket to nonblocking. */ value = 1; if ((rc=os_ioctl(sock, FIONBIO, (ioctl_val_type)&value))) { - TRACE_((THIS_FILE, "pj_ioqueue_register_sock error: ioctl rc=%d", + TRACE_((THIS_FILE, "pj_ioqueue_register_sock error: ioctl rc=%d", rc)); status = pj_get_netos_error(); - goto on_return; + goto on_return; } /* If safe unregistration (PJ_IOQUEUE_HAS_SAFE_UNREG) is used, get @@ -485,8 +484,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, pj_assert(!pj_list_empty(&ioqueue->free_list)); if (pj_list_empty(&ioqueue->free_list)) { - status = PJ_ETOOMANY; - goto on_return; + status = PJ_ETOOMANY; + goto on_return; } key = ioqueue->free_list.next; @@ -498,32 +497,32 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, status = ioqueue_init_key(pool, ioqueue, key, sock, grp_lock, user_data, cb); if (status != PJ_SUCCESS) { - key = NULL; - goto on_return; + key = NULL; + goto on_return; } pj_bzero(&key->ev, sizeof(key->ev)); key->ev.epoll_data = (epoll_data_type)key; key->ev.events = 0; if (ioqueue->cfg.epoll_flags & PJ_IOQUEUE_EPOLL_EXCLUSIVE) - key->ev.events |= EPOLLEXCLUSIVE; + key->ev.events |= EPOLLEXCLUSIVE; else if (ioqueue->cfg.epoll_flags & PJ_IOQUEUE_EPOLL_ONESHOT) - key->ev.events |= EPOLLONESHOT; + key->ev.events |= EPOLLONESHOT; /* Create key's mutex */ /* rc = pj_mutex_create_recursive(pool, NULL, &key->mutex); if (rc != PJ_SUCCESS) { - key = NULL; - goto on_return; + key = NULL; + goto on_return; } */ /* os_epoll_ctl. */ rc = os_epoll_ctl(ioqueue->epfd, EPOLL_CTL_ADD, sock, &key->ev); if (rc < 0) { - status = pj_get_os_error(); - pj_lock_destroy(key->lock); - key = NULL; - PJ_PERROR(1,(THIS_FILE, status, "epol_ctl(ADD) error")); - goto on_return; + status = pj_get_os_error(); + pj_lock_destroy(key->lock); + key = NULL; + PJ_PERROR(1,(THIS_FILE, status, "epol_ctl(ADD) error")); + goto on_return; } /* Register */ @@ -534,8 +533,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, on_return: if (status != PJ_SUCCESS) { - if (key && key->grp_lock) - pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0); + if (key && key->grp_lock) + pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0); } *p_key = key; pj_lock_release(ioqueue->lock); @@ -544,11 +543,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, } PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, - pj_ioqueue_t *ioqueue, - pj_sock_t sock, - void *user_data, - const pj_ioqueue_callback *cb, - pj_ioqueue_key_t **p_key) + pj_ioqueue_t *ioqueue, + pj_sock_t sock, + void *user_data, + const pj_ioqueue_callback *cb, + pj_ioqueue_key_t **p_key) { return pj_ioqueue_register_sock2(pool, ioqueue, sock, NULL, user_data, cb, p_key); @@ -575,13 +574,13 @@ static void decrement_counter(pj_ioqueue_key_t *key) --key->ref_count; if (key->ref_count == 0) { - pj_assert(key->closing == 1); - pj_gettickcount(&key->free_time); - key->free_time.msec += PJ_IOQUEUE_KEY_FREE_DELAY; - pj_time_val_normalize(&key->free_time); + pj_assert(key->closing == 1); + pj_gettickcount(&key->free_time); + key->free_time.msec += PJ_IOQUEUE_KEY_FREE_DELAY; + pj_time_val_normalize(&key->free_time); - pj_list_erase(key); - pj_list_push_back(&key->ioqueue->closing_list, key); + pj_list_erase(key); + pj_list_push_back(&key->ioqueue->closing_list, key); } pj_mutex_unlock(key->ioqueue->ref_cnt_mutex); @@ -611,8 +610,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key) /* Best effort to avoid double key-unregistration */ if (IS_CLOSING(key)) { - pj_ioqueue_unlock_key(key); - return PJ_SUCCESS; + pj_ioqueue_unlock_key(key); + return PJ_SUCCESS; } /* Also lock ioqueue */ @@ -620,13 +619,13 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key) /* Avoid "negative" ioqueue count */ if (ioqueue->count > 0) { - --ioqueue->count; + --ioqueue->count; } else { - /* If this happens, very likely there is double unregistration - * of a key. - */ - pj_assert(!"Bad ioqueue count in key unregistration!"); - PJ_LOG(1,(THIS_FILE, "Bad ioqueue count in key unregistration!")); + /* If this happens, very likely there is double unregistration + * of a key. + */ + pj_assert(!"Bad ioqueue count in key unregistration!"); + PJ_LOG(1,(THIS_FILE, "Bad ioqueue count in key unregistration!")); } #if !PJ_IOQUEUE_HAS_SAFE_UNREG @@ -640,10 +639,10 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key) key->ev.events &= ~IO_MASK; status = os_epoll_ctl( ioqueue->epfd, EPOLL_CTL_DEL, key->fd, &key->ev); if (status != 0) { - status = pj_get_os_error(); - PJ_PERROR(2, (THIS_FILE, status, - "Ignoring pj_ioqueue_unregister error: os_epoll_ctl")); - /* From epoll doc: "Closing a file descriptor cause it to be + status = pj_get_os_error(); + PJ_PERROR(2, (THIS_FILE, status, + "Ignoring pj_ioqueue_unregister error: os_epoll_ctl")); + /* From epoll doc: "Closing a file descriptor cause it to be * removed from all epoll interest lists". So we should just * proceed instead of returning failure here. */ @@ -667,30 +666,30 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key) /* Done. */ if (key->grp_lock) { - /* just dec_ref and unlock. we will set grp_lock to NULL - * elsewhere */ - pj_grp_lock_t *grp_lock = key->grp_lock; - // Don't set grp_lock to NULL otherwise the other thread - // will crash. Just leave it as dangling pointer, but this - // should be safe - //key->grp_lock = NULL; - pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); - pj_grp_lock_release(grp_lock); + /* just dec_ref and unlock. we will set grp_lock to NULL + * elsewhere */ + pj_grp_lock_t *grp_lock = key->grp_lock; + // Don't set grp_lock to NULL otherwise the other thread + // will crash. Just leave it as dangling pointer, but this + // should be safe + //key->grp_lock = NULL; + pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); + pj_grp_lock_release(grp_lock); } else { - pj_ioqueue_unlock_key(key); + pj_ioqueue_unlock_key(key); } #else if (key->grp_lock) { - /* set grp_lock to NULL and unlock */ - pj_grp_lock_t *grp_lock = key->grp_lock; - // Don't set grp_lock to NULL otherwise the other thread - // will crash. Just leave it as dangling pointer, but this - // should be safe - //key->grp_lock = NULL; - pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); - pj_grp_lock_release(grp_lock); + /* set grp_lock to NULL and unlock */ + pj_grp_lock_t *grp_lock = key->grp_lock; + // Don't set grp_lock to NULL otherwise the other thread + // will crash. Just leave it as dangling pointer, but this + // should be safe + //key->grp_lock = NULL; + pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); + pj_grp_lock_release(grp_lock); } else { - pj_ioqueue_unlock_key(key); + pj_ioqueue_unlock_key(key); } pj_lock_destroy(key->lock); @@ -702,7 +701,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key) static void update_epoll_event_set(pj_ioqueue_t *ioqueue, pj_ioqueue_key_t *key, - pj_uint32_t events) + pj_uint32_t events) { int rc; /* From epoll_ctl(2): @@ -710,18 +709,18 @@ static void update_epoll_event_set(pj_ioqueue_t *ioqueue, * attempts to employ it with EPOLL_CTL_MOD yield an error. */ if (key->ev.events & EPOLLEXCLUSIVE) { - rc = os_epoll_ctl(ioqueue->epfd, EPOLL_CTL_DEL, key->fd, &key->ev); - key->ev.events = events; - rc = os_epoll_ctl(ioqueue->epfd, EPOLL_CTL_ADD, key->fd, &key->ev); + rc = os_epoll_ctl(ioqueue->epfd, EPOLL_CTL_DEL, key->fd, &key->ev); + key->ev.events = events; + rc = os_epoll_ctl(ioqueue->epfd, EPOLL_CTL_ADD, key->fd, &key->ev); } else { - key->ev.events = events; - rc = os_epoll_ctl(ioqueue->epfd, EPOLL_CTL_MOD, key->fd, &key->ev); + key->ev.events = events; + rc = os_epoll_ctl(ioqueue->epfd, EPOLL_CTL_MOD, key->fd, &key->ev); } if (rc != 0) { - pj_status_t status = pj_get_os_error(); - PJ_PERROR(1,(THIS_FILE, status, - "epol_ctl(MOD) error (events=0x%x)", events)); + pj_status_t status = pj_get_os_error(); + PJ_PERROR(1,(THIS_FILE, status, + "epol_ctl(MOD) error (events=0x%x)", events)); } } @@ -732,8 +731,8 @@ static void update_epoll_event_set(pj_ioqueue_t *ioqueue, * set for the specified event. */ static void ioqueue_remove_from_set( pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - enum ioqueue_event_type event_type ) + pj_ioqueue_key_t *key, + enum ioqueue_event_type event_type ) { ioqueue_remove_from_set2(ioqueue, key, event_type); } @@ -745,9 +744,9 @@ static void ioqueue_remove_from_set2(pj_ioqueue_t *ioqueue, pj_uint32_t events = key->ev.events; if (event_types & READABLE_EVENT) - events &= ~EPOLLIN; + events &= ~EPOLLIN; if (event_types & WRITEABLE_EVENT) - events &= ~EPOLLOUT; + events &= ~EPOLLOUT; /* Note that although EPOLLERR is removed, epoll will still report * EPOLLERR events to us and there is no way to disable it. But we @@ -755,10 +754,10 @@ static void ioqueue_remove_from_set2(pj_ioqueue_t *ioqueue, * in our own record. */ if (event_types & EXCEPTION_EVENT) - events &= ~EPOLLERR; + events &= ~EPOLLERR; if (events != key->ev.events) - update_epoll_event_set(ioqueue, key, events); + update_epoll_event_set(ioqueue, key, events); } /* @@ -769,26 +768,26 @@ static void ioqueue_remove_from_set2(pj_ioqueue_t *ioqueue, */ static void ioqueue_add_to_set( pj_ioqueue_t *ioqueue, pj_ioqueue_key_t *key, - enum ioqueue_event_type event_type ) + enum ioqueue_event_type event_type ) { ioqueue_add_to_set2(ioqueue, key, event_type); } static void ioqueue_add_to_set2(pj_ioqueue_t *ioqueue, pj_ioqueue_key_t *key, - unsigned event_types ) + unsigned event_types ) { pj_uint32_t events = key->ev.events; if (event_types & READABLE_EVENT) - events |= EPOLLIN; + events |= EPOLLIN; if (event_types & WRITEABLE_EVENT) - events |= EPOLLOUT; + events |= EPOLLOUT; if (event_types & EXCEPTION_EVENT) - events |= EPOLLERR; + events |= EPOLLERR; if (events != key->ev.events) - update_epoll_event_set(ioqueue, key, events); + update_epoll_event_set(ioqueue, key, events); } @@ -802,19 +801,19 @@ static void scan_closing_keys(pj_ioqueue_t *ioqueue) pj_gettickcount(&now); h = ioqueue->closing_list.next; while (h != &ioqueue->closing_list) { - pj_ioqueue_key_t *next = h->next; - - pj_assert(h->closing != 0); - - if (PJ_TIME_VAL_GTE(now, h->free_time)) { - pj_list_erase(h); - // Don't set grp_lock to NULL otherwise the other thread - // will crash. Just leave it as dangling pointer, but this - // should be safe - //h->grp_lock = NULL; - pj_list_push_back(&ioqueue->free_list, h); - } - h = next; + pj_ioqueue_key_t *next = h->next; + + pj_assert(h->closing != 0); + + if (PJ_TIME_VAL_GTE(now, h->free_time)) { + pj_list_erase(h); + // Don't set grp_lock to NULL otherwise the other thread + // will crash. Just leave it as dangling pointer, but this + // should be safe + //h->grp_lock = NULL; + pj_list_push_back(&ioqueue->free_list, h); + } + h = next; } } #endif @@ -849,139 +848,139 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) * pending closing keys. */ if (count == 0 && !pj_list_empty(&ioqueue->closing_list)) { - pj_lock_acquire(ioqueue->lock); - scan_closing_keys(ioqueue); - pj_lock_release(ioqueue->lock); + pj_lock_acquire(ioqueue->lock); + scan_closing_keys(ioqueue); + pj_lock_release(ioqueue->lock); } #endif - TRACE_((THIS_FILE, " os_epoll_wait timed out")); - return count; + TRACE_((THIS_FILE, " os_epoll_wait timed out")); + return count; } else if (count < 0) { - TRACE_((THIS_FILE, " os_epoll_wait error")); - return -pj_get_netos_error(); + TRACE_((THIS_FILE, " os_epoll_wait error")); + return -pj_get_netos_error(); } pj_get_timestamp(&t2); TRACE_((THIS_FILE, " os_epoll_wait returns %d, time=%d usec", - count, pj_elapsed_usec(&t1, &t2))); + count, pj_elapsed_usec(&t1, &t2))); /* Lock ioqueue. */ pj_lock_acquire(ioqueue->lock); for (event_cnt=0, i=0; iconnecting) && !IS_CLOSING(h)) { + /* + * Check for completion of connect() operation. + */ + if ((events[i].events & EPOLLOUT) && (h->connecting) && !IS_CLOSING(h)) { #if PJ_IOQUEUE_HAS_SAFE_UNREG - increment_counter(h); + increment_counter(h); #endif - queue[event_cnt].key = h; - queue[event_cnt].event_type = WRITEABLE_EVENT; - ++event_cnt; - continue; - } + queue[event_cnt].key = h; + queue[event_cnt].event_type = WRITEABLE_EVENT; + ++event_cnt; + continue; + } #endif /* PJ_HAS_TCP */ - /* - * Check for error condition. - */ - if ((events[i].events & EPOLLERR) && !IS_CLOSING(h)) { - /* - * We need to handle this exception event. If it's related to us - * connecting, report it as such. If not, just report it as a - * read event and the higher layers will handle it. - */ - if (h->connecting) { + /* + * Check for error condition. + */ + if ((events[i].events & EPOLLERR) && !IS_CLOSING(h)) { + /* + * We need to handle this exception event. If it's related to us + * connecting, report it as such. If not, just report it as a + * read event and the higher layers will handle it. + */ + if (h->connecting) { #if PJ_IOQUEUE_HAS_SAFE_UNREG - increment_counter(h); + increment_counter(h); #endif - queue[event_cnt].key = h; - queue[event_cnt].event_type = EXCEPTION_EVENT; - ++event_cnt; - } else if (key_has_pending_read(h) || key_has_pending_accept(h)) { + queue[event_cnt].key = h; + queue[event_cnt].event_type = EXCEPTION_EVENT; + ++event_cnt; + } else if (key_has_pending_read(h) || key_has_pending_accept(h)) { #if PJ_IOQUEUE_HAS_SAFE_UNREG - increment_counter(h); + increment_counter(h); #endif - queue[event_cnt].key = h; - queue[event_cnt].event_type = READABLE_EVENT; - ++event_cnt; - } - continue; - } - - if (ioqueue->cfg.epoll_flags & PJ_IOQUEUE_EPOLL_ONESHOT) { - /* We are not processing this event, but we still need to rearm - * to receive future events. - */ - if (!IS_CLOSING(h)) - update_epoll_event_set(ioqueue, h, h->ev.events); - } - - /* There are some innocent cases where this might happen: - * 1. TCP outgoing connection failure. Although app has handled the - * failure event, epoll will keep reporting EPOLLHUP until the - * socket is unregistered. - * 2. Thread A and B are woken up for a single EPOLLIN, (or when - * EPOLLEXCLUSIVE is used, two packets arrives almost simultaneously, - * only single pending recv() was submitted. This also causes both - * threads to be woken up. This scenario can be observed in ioq_reg.c - * test) - * - Thread A is processing the event - * - Thread B waits for ioqueue lock - * - Thread A releases the ioqueue lock, acquires key lock, remove - * pending recv() from list, release key lock (because concurrency - * is enabled). - * - Thread B resumes, it finds no pending recv() op. - * 3. Other scenarios involving TCP in normal operation using plain or - * EPOLLEXCLUSIVE (didn't happen with ONESHOT), for both EPOLLIN - * and EPOLLOUT events. Not sure what, but it happens only - * sporadically, so probably it's fine. This is reproducible with - * "tcp (multithreads)" test in ioq_stress_test.c. - */ - TRACE_WARN((THIS_FILE, " UNHANDLED event %d: events=0x%x, h=%p", - i, events[i].events, h)); + queue[event_cnt].key = h; + queue[event_cnt].event_type = READABLE_EVENT; + ++event_cnt; + } + continue; + } + + if (ioqueue->cfg.epoll_flags & PJ_IOQUEUE_EPOLL_ONESHOT) { + /* We are not processing this event, but we still need to rearm + * to receive future events. + */ + if (!IS_CLOSING(h)) + update_epoll_event_set(ioqueue, h, h->ev.events); + } + + /* There are some innocent cases where this might happen: + * 1. TCP outgoing connection failure. Although app has handled the + * failure event, epoll will keep reporting EPOLLHUP until the + * socket is unregistered. + * 2. Thread A and B are woken up for a single EPOLLIN, (or when + * EPOLLEXCLUSIVE is used, two packets arrives almost simultaneously, + * only single pending recv() was submitted. This also causes both + * threads to be woken up. This scenario can be observed in ioq_reg.c + * test) + * - Thread A is processing the event + * - Thread B waits for ioqueue lock + * - Thread A releases the ioqueue lock, acquires key lock, remove + * pending recv() from list, release key lock (because concurrency + * is enabled). + * - Thread B resumes, it finds no pending recv() op. + * 3. Other scenarios involving TCP in normal operation using plain or + * EPOLLEXCLUSIVE (didn't happen with ONESHOT), for both EPOLLIN + * and EPOLLOUT events. Not sure what, but it happens only + * sporadically, so probably it's fine. This is reproducible with + * "tcp (multithreads)" test in ioq_stress_test.c. + */ + TRACE_WARN((THIS_FILE, " UNHANDLED event %d: events=0x%x, h=%p", + i, events[i].events, h)); } for (i=0; igrp_lock) - pj_grp_lock_add_ref_dbg(queue[i].key->grp_lock, "ioqueue", 0); + if (queue[i].key->grp_lock) + pj_grp_lock_add_ref_dbg(queue[i].key->grp_lock, "ioqueue", 0); } PJ_RACE_ME(5); @@ -994,59 +993,59 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) /* Now process the events. */ for (i=0; icfg.epoll_flags & PJ_IOQUEUE_EPOLL_ONESHOT) && - (queue[i].key->ev.events & IO_MASK)) - { - pj_ioqueue_lock_key(queue[i].key); - update_epoll_event_set(ioqueue, queue[i].key, - queue[i].key->ev.events); - pj_ioqueue_unlock_key(queue[i].key); - } + if ((ioqueue->cfg.epoll_flags & PJ_IOQUEUE_EPOLL_ONESHOT) && + (queue[i].key->ev.events & IO_MASK)) + { + pj_ioqueue_lock_key(queue[i].key); + update_epoll_event_set(ioqueue, queue[i].key, + queue[i].key->ev.events); + pj_ioqueue_unlock_key(queue[i].key); + } #if PJ_IOQUEUE_HAS_SAFE_UNREG - decrement_counter(queue[i].key); + decrement_counter(queue[i].key); #endif - if (queue[i].key->grp_lock) - pj_grp_lock_dec_ref_dbg(queue[i].key->grp_lock, - "ioqueue", 0); + if (queue[i].key->grp_lock) + pj_grp_lock_dec_ref_dbg(queue[i].key->grp_lock, + "ioqueue", 0); } /* Special case: @@ -1056,25 +1055,25 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) * log message above. */ if (count > 0 && !event_cnt && msec > 0) { - /* We need to sleep in order to avoid busy polling, such + /* We need to sleep in order to avoid busy polling, such * as in the case of the thread that doesn't process * the event as explained above. * Limit the duration of the sleep, as doing pj_thread_sleep() for * a long time is very inefficient. The main objective here is just * to avoid busy loop. */ - int delay = msec - pj_elapsed_usec(&t1, &t2)/1000; + int delay = msec - pj_elapsed_usec(&t1, &t2)/1000; if (delay > 10) delay = 10; - if (delay > 0) - pj_thread_sleep(delay); + if (delay > 0) + pj_thread_sleep(delay); } TRACE_((THIS_FILE, " poll: count=%d events=%d processed=%d", - count, event_cnt, processed_cnt)); + count, event_cnt, processed_cnt)); pj_get_timestamp(&t1); TRACE_((THIS_FILE, "ioqueue_poll() returns %d, time=%d usec", - processed_cnt, pj_elapsed_usec(&t2, &t1))); + processed_cnt, pj_elapsed_usec(&t2, &t1))); return processed_cnt; } diff --git a/pjlib/src/pj/ioqueue_kqueue.c b/pjlib/src/pj/ioqueue_kqueue.c index a41db0f821..681fcb0402 100644 --- a/pjlib/src/pj/ioqueue_kqueue.c +++ b/pjlib/src/pj/ioqueue_kqueue.c @@ -113,7 +113,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, */ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, pj_size_t max_fd, - const pj_ioqueue_cfg *cfg, + const pj_ioqueue_cfg *cfg, pj_ioqueue_t **p_ioqueue) { pj_ioqueue_t *ioqueue; @@ -123,21 +123,21 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, /* Check that arguments are valid. */ PJ_ASSERT_RETURN(pool != NULL && p_ioqueue != NULL && max_fd > 0, - PJ_EINVAL); + PJ_EINVAL); /* Check that size of pj_ioqueue_op_key_t is sufficient */ PJ_ASSERT_RETURN(sizeof(pj_ioqueue_op_key_t) - sizeof(void *) >= - sizeof(union operation_key), - PJ_EBUG); + sizeof(union operation_key), + PJ_EBUG); ioqueue = pj_pool_alloc(pool, sizeof(pj_ioqueue_t)); ioqueue_init(ioqueue); if (cfg) - pj_memcpy(&ioqueue->cfg, cfg, sizeof(*cfg)); + pj_memcpy(&ioqueue->cfg, cfg, sizeof(*cfg)); else - pj_ioqueue_cfg_default(&ioqueue->cfg); + pj_ioqueue_cfg_default(&ioqueue->cfg); ioqueue->max = max_fd; ioqueue->count = 0; pj_list_init(&ioqueue->active_list); @@ -153,7 +153,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, */ rc = pj_mutex_create_simple(pool, NULL, &ioqueue->ref_cnt_mutex); if (rc != PJ_SUCCESS) - return rc; + return rc; /* Init key list */ pj_list_init(&ioqueue->free_list); @@ -161,43 +161,43 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, /* Pre-create all keys according to max_fd */ for (i = 0; i < max_fd; ++i) { - pj_ioqueue_key_t *key; - - key = PJ_POOL_ALLOC_T(pool, pj_ioqueue_key_t); - key->ref_count = 0; - rc = pj_lock_create_recursive_mutex(pool, NULL, &key->lock); - if (rc != PJ_SUCCESS) { - key = ioqueue->free_list.next; - while (key != &ioqueue->free_list) { - pj_lock_destroy(key->lock); - key = key->next; - } - pj_mutex_destroy(ioqueue->ref_cnt_mutex); - return rc; - } - - pj_list_push_back(&ioqueue->free_list, key); + pj_ioqueue_key_t *key; + + key = PJ_POOL_ALLOC_T(pool, pj_ioqueue_key_t); + key->ref_count = 0; + rc = pj_lock_create_recursive_mutex(pool, NULL, &key->lock); + if (rc != PJ_SUCCESS) { + key = ioqueue->free_list.next; + while (key != &ioqueue->free_list) { + pj_lock_destroy(key->lock); + key = key->next; + } + pj_mutex_destroy(ioqueue->ref_cnt_mutex); + return rc; + } + + pj_list_push_back(&ioqueue->free_list, key); } #endif rc = pj_lock_create_simple_mutex(pool, "ioq%p", &lock); if (rc != PJ_SUCCESS) - return rc; + return rc; rc = pj_ioqueue_set_lock(ioqueue, lock, PJ_TRUE); if (rc != PJ_SUCCESS) - return rc; + return rc; /* create kqueue */ ioqueue->kfd = os_kqueue_open(); if (ioqueue->kfd == -1) { - pj_lock_acquire(ioqueue->lock); - ioqueue_destroy(ioqueue); - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + pj_lock_acquire(ioqueue->lock); + ioqueue_destroy(ioqueue); + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); } PJ_LOG(4, - ("pjlib", "%s I/O Queue created (%p)", pj_ioqueue_name(), ioqueue)); + ("pjlib", "%s I/O Queue created (%p)", pj_ioqueue_name(), ioqueue)); *p_ioqueue = ioqueue; return PJ_SUCCESS; @@ -223,20 +223,20 @@ PJ_DEF(pj_status_t) pj_ioqueue_destroy(pj_ioqueue_t *ioqueue) /* Destroy reference counters */ key = ioqueue->active_list.next; while (key != &ioqueue->active_list) { - pj_lock_destroy(key->lock); - key = key->next; + pj_lock_destroy(key->lock); + key = key->next; } key = ioqueue->closing_list.next; while (key != &ioqueue->closing_list) { - pj_lock_destroy(key->lock); - key = key->next; + pj_lock_destroy(key->lock); + key = key->next; } key = ioqueue->free_list.next; while (key != &ioqueue->free_list) { - pj_lock_destroy(key->lock); - key = key->next; + pj_lock_destroy(key->lock); + key = key->next; } pj_mutex_destroy(ioqueue->ref_cnt_mutex); @@ -251,9 +251,9 @@ PJ_DEF(pj_status_t) pj_ioqueue_destroy(pj_ioqueue_t *ioqueue) */ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, pj_ioqueue_t *ioqueue, - pj_sock_t sock, pj_grp_lock_t *grp_lock, - void *user_data, const pj_ioqueue_callback *cb, - pj_ioqueue_key_t **p_key) + pj_sock_t sock, pj_grp_lock_t *grp_lock, + void *user_data, const pj_ioqueue_callback *cb, + pj_ioqueue_key_t **p_key) { pj_ioqueue_key_t *key = NULL; pj_uint32_t value; @@ -262,14 +262,14 @@ pj_ioqueue_register_sock2(pj_pool_t *pool, pj_ioqueue_t *ioqueue, struct kevent events[2]; PJ_ASSERT_RETURN( - pool && ioqueue && sock != PJ_INVALID_SOCKET && cb && p_key, PJ_EINVAL); + pool && ioqueue && sock != PJ_INVALID_SOCKET && cb && p_key, PJ_EINVAL); pj_lock_acquire(ioqueue->lock); if (ioqueue->count >= ioqueue->max) { - rc = PJ_ETOOMANY; - TRACE_((THIS_FILE, "pj_ioqueue_register_sock error: too many files")); - goto on_return; + rc = PJ_ETOOMANY; + TRACE_((THIS_FILE, "pj_ioqueue_register_sock error: too many files")); + goto on_return; } /* If safe unregistration (PJ_IOQUEUE_HAS_SAFE_UNREG) is used, get @@ -282,8 +282,8 @@ pj_ioqueue_register_sock2(pj_pool_t *pool, pj_ioqueue_t *ioqueue, pj_assert(!pj_list_empty(&ioqueue->free_list)); if (pj_list_empty(&ioqueue->free_list)) { - rc = PJ_ETOOMANY; - goto on_return; + rc = PJ_ETOOMANY; + goto on_return; } key = ioqueue->free_list.next; @@ -295,8 +295,8 @@ pj_ioqueue_register_sock2(pj_pool_t *pool, pj_ioqueue_t *ioqueue, rc = ioqueue_init_key(pool, ioqueue, key, sock, grp_lock, user_data, cb); if (rc != PJ_SUCCESS) { - key = NULL; - goto on_return; + key = NULL; + goto on_return; } /* Initialize kevent structure, ADD read/write, default disable write */ @@ -306,19 +306,19 @@ pj_ioqueue_register_sock2(pj_pool_t *pool, pj_ioqueue_t *ioqueue, /* add event to kqueue */ status = os_kqueue_ctl(ioqueue->kfd, events, 2, NULL, 0, NULL); if (status == -1) { - rc = pj_get_os_error(); - pj_lock_destroy(key->lock); - key = NULL; - TRACE_((THIS_FILE, "pj_ioqueue_register_sock error: kevent rc=%d", - status)); - goto on_return; + rc = pj_get_os_error(); + pj_lock_destroy(key->lock); + key = NULL; + TRACE_((THIS_FILE, "pj_ioqueue_register_sock error: kevent rc=%d", + status)); + goto on_return; } /* Set socket to nonblocking. */ value = 1; if (ioctl(sock, FIONBIO, &value)) { - rc = pj_get_netos_error(); - goto on_return; + rc = pj_get_netos_error(); + goto on_return; } /* Put in active list. */ @@ -327,8 +327,8 @@ pj_ioqueue_register_sock2(pj_pool_t *pool, pj_ioqueue_t *ioqueue, on_return: if (rc != PJ_SUCCESS) { - if (key && key->grp_lock) - pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0); + if (key && key->grp_lock) + pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0); } *p_key = key; pj_lock_release(ioqueue->lock); @@ -338,11 +338,11 @@ pj_ioqueue_register_sock2(pj_pool_t *pool, pj_ioqueue_t *ioqueue, PJ_DEF(pj_status_t) pj_ioqueue_register_sock(pj_pool_t *pool, pj_ioqueue_t *ioqueue, pj_sock_t sock, - void *user_data, const pj_ioqueue_callback *cb, - pj_ioqueue_key_t **p_key) + void *user_data, const pj_ioqueue_callback *cb, + pj_ioqueue_key_t **p_key) { return pj_ioqueue_register_sock2(pool, ioqueue, sock, NULL, user_data, cb, - p_key); + p_key); } #if PJ_IOQUEUE_HAS_SAFE_UNREG @@ -366,13 +366,13 @@ static void decrement_counter(pj_ioqueue_key_t *key) --key->ref_count; if (key->ref_count == 0) { - pj_assert(key->closing == 1); - pj_gettickcount(&key->free_time); - key->free_time.msec += PJ_IOQUEUE_KEY_FREE_DELAY; - pj_time_val_normalize(&key->free_time); + pj_assert(key->closing == 1); + pj_gettickcount(&key->free_time); + key->free_time.msec += PJ_IOQUEUE_KEY_FREE_DELAY; + pj_time_val_normalize(&key->free_time); - pj_list_erase(key); - pj_list_push_back(&key->ioqueue->closing_list, key); + pj_list_erase(key); + pj_list_push_back(&key->ioqueue->closing_list, key); } pj_mutex_unlock(key->ioqueue->ref_cnt_mutex); pj_lock_release(key->ioqueue->lock); @@ -402,8 +402,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister(pj_ioqueue_key_t *key) /* Best effort to avoid double key-unregistration */ if (IS_CLOSING(key)) { - pj_ioqueue_unlock_key(key); - return PJ_SUCCESS; + pj_ioqueue_unlock_key(key); + return PJ_SUCCESS; } /* Also lock ioqueue */ @@ -411,13 +411,13 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister(pj_ioqueue_key_t *key) /* Avoid "negative" ioqueue count */ if (ioqueue->count > 0) { - --ioqueue->count; + --ioqueue->count; } else { - /* If this happens, very likely there is double unregistration - * of a key. - */ - pj_assert(!"Bad ioqueue count in key unregistration!"); - PJ_LOG(1, (THIS_FILE, "Bad ioqueue count in key unregistration!")); + /* If this happens, very likely there is double unregistration + * of a key. + */ + pj_assert(!"Bad ioqueue count in key unregistration!"); + PJ_LOG(1, (THIS_FILE, "Bad ioqueue count in key unregistration!")); } #if !PJ_IOQUEUE_HAS_SAFE_UNREG @@ -431,10 +431,10 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister(pj_ioqueue_key_t *key) /* delete event from kqueue */ status = os_kqueue_ctl(ioqueue->kfd, events, 2, NULL, 0, NULL); if (status == -1) { - pj_status_t rc = pj_get_os_error(); - pj_lock_release(ioqueue->lock); - pj_ioqueue_unlock_key(key); - return rc; + pj_status_t rc = pj_get_os_error(); + pj_lock_release(ioqueue->lock); + pj_ioqueue_unlock_key(key); + return rc; } /* Destroy the key. */ @@ -451,30 +451,30 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister(pj_ioqueue_key_t *key) /* Done. */ if (key->grp_lock) { - /* just dec_ref and unlock. we will set grp_lock to NULL - * elsewhere */ - pj_grp_lock_t *grp_lock = key->grp_lock; - // Don't set grp_lock to NULL otherwise the other thread - // will crash. Just leave it as dangling pointer, but this - // should be safe - // key->grp_lock = NULL; - pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); - pj_grp_lock_release(grp_lock); + /* just dec_ref and unlock. we will set grp_lock to NULL + * elsewhere */ + pj_grp_lock_t *grp_lock = key->grp_lock; + // Don't set grp_lock to NULL otherwise the other thread + // will crash. Just leave it as dangling pointer, but this + // should be safe + // key->grp_lock = NULL; + pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); + pj_grp_lock_release(grp_lock); } else { - pj_ioqueue_unlock_key(key); + pj_ioqueue_unlock_key(key); } #else if (key->grp_lock) { - /* set grp_lock to NULL and unlock */ - pj_grp_lock_t *grp_lock = key->grp_lock; - // Don't set grp_lock to NULL otherwise the other thread - // will crash. Just leave it as dangling pointer, but this - // should be safe - // key->grp_lock = NULL; - pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); - pj_grp_lock_release(grp_lock); + /* set grp_lock to NULL and unlock */ + pj_grp_lock_t *grp_lock = key->grp_lock; + // Don't set grp_lock to NULL otherwise the other thread + // will crash. Just leave it as dangling pointer, but this + // should be safe + // key->grp_lock = NULL; + pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); + pj_grp_lock_release(grp_lock); } else { - pj_ioqueue_unlock_key(key); + pj_ioqueue_unlock_key(key); } pj_lock_destroy(key->lock); @@ -489,29 +489,29 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister(pj_ioqueue_key_t *key) * set for the specified event. */ static void ioqueue_remove_from_set2(pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - unsigned event_types) + pj_ioqueue_key_t *key, + unsigned event_types) { struct kevent event; if (event_types & READABLE_EVENT) { - /* - if (!key_has_pending_read(key) && !key_has_pending_accept(key)) { - EV_SET(&event, key->fd, EVFILT_READ, EV_DISABLE, 0, 0, key); - os_kqueue_ctl(ioqueue->kfd, &event, 1, NULL, 0, NULL); - } - */ + /* + if (!key_has_pending_read(key) && !key_has_pending_accept(key)) { + EV_SET(&event, key->fd, EVFILT_READ, EV_DISABLE, 0, 0, key); + os_kqueue_ctl(ioqueue->kfd, &event, 1, NULL, 0, NULL); + } + */ } if (event_types & WRITEABLE_EVENT) { - if (!key_has_pending_write(key) && !key_has_pending_connect(key)) { - EV_SET(&event, key->fd, EVFILT_WRITE, EV_DISABLE, 0, 0, key); - os_kqueue_ctl(ioqueue->kfd, &event, 1, NULL, 0, NULL); - } + if (!key_has_pending_write(key) && !key_has_pending_connect(key)) { + EV_SET(&event, key->fd, EVFILT_WRITE, EV_DISABLE, 0, 0, key); + os_kqueue_ctl(ioqueue->kfd, &event, 1, NULL, 0, NULL); + } } } static void ioqueue_remove_from_set( pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - enum ioqueue_event_type event_type ) + pj_ioqueue_key_t *key, + enum ioqueue_event_type event_type ) { ioqueue_remove_from_set2(ioqueue, key, event_type); } @@ -523,26 +523,26 @@ static void ioqueue_remove_from_set( pj_ioqueue_t *ioqueue, * set for the specified event. */ static void ioqueue_add_to_set2(pj_ioqueue_t *ioqueue, pj_ioqueue_key_t *key, - unsigned event_types) + unsigned event_types) { struct kevent event; if (event_types & READABLE_EVENT) { - /* - EV_SET(&event, key->fd, EVFILT_READ, EV_ENABLE, 0, 0, key); - os_kqueue_ctl(ioqueue->kfd, &event, 1, NULL, 0, NULL); - */ + /* + EV_SET(&event, key->fd, EVFILT_READ, EV_ENABLE, 0, 0, key); + os_kqueue_ctl(ioqueue->kfd, &event, 1, NULL, 0, NULL); + */ } if (event_types & WRITEABLE_EVENT) { - EV_SET(&event, key->fd, EVFILT_WRITE, EV_ENABLE, 0, 0, key); - os_kqueue_ctl(ioqueue->kfd, &event, 1, NULL, 0, NULL); + EV_SET(&event, key->fd, EVFILT_WRITE, EV_ENABLE, 0, 0, key); + os_kqueue_ctl(ioqueue->kfd, &event, 1, NULL, 0, NULL); } } static void ioqueue_add_to_set( pj_ioqueue_t *ioqueue, pj_ioqueue_key_t *key, - enum ioqueue_event_type event_type ) + enum ioqueue_event_type event_type ) { ioqueue_add_to_set2(ioqueue, key, event_type); } @@ -557,19 +557,19 @@ static void scan_closing_keys(pj_ioqueue_t *ioqueue) pj_gettickcount(&now); h = ioqueue->closing_list.next; while (h != &ioqueue->closing_list) { - pj_ioqueue_key_t *next = h->next; - - pj_assert(h->closing != 0); - - if (PJ_TIME_VAL_GTE(now, h->free_time)) { - pj_list_erase(h); - // Don't set grp_lock to NULL otherwise the other thread - // will crash. Just leave it as dangling pointer, but this - // should be safe - // h->grp_lock = NULL; - pj_list_push_back(&ioqueue->free_list, h); - } - h = next; + pj_ioqueue_key_t *next = h->next; + + pj_assert(h->closing != 0); + + if (PJ_TIME_VAL_GTE(now, h->free_time)) { + pj_list_erase(h); + // Don't set grp_lock to NULL otherwise the other thread + // will crash. Just leave it as dangling pointer, but this + // should be safe + // h->grp_lock = NULL; + pj_list_push_back(&ioqueue->free_list, h); + } + h = next; } } #endif @@ -584,7 +584,7 @@ PJ_DEF(int) pj_ioqueue_poll(pj_ioqueue_t *ioqueue, const pj_time_val *timeout) struct timespec xtimeout = {1, 0}; enum { - MAX_EVENTS = PJ_IOQUEUE_MAX_CAND_EVENTS + MAX_EVENTS = PJ_IOQUEUE_MAX_CAND_EVENTS }; struct kevent events[MAX_EVENTS]; struct queue queue[MAX_EVENTS]; @@ -592,76 +592,76 @@ PJ_DEF(int) pj_ioqueue_poll(pj_ioqueue_t *ioqueue, const pj_time_val *timeout) PJ_CHECK_STACK(); if (timeout) { - xtimeout.tv_sec = timeout->sec; - xtimeout.tv_nsec = timeout->msec * 1000000; + xtimeout.tv_sec = timeout->sec; + xtimeout.tv_nsec = timeout->msec * 1000000; } TRACE_((THIS_FILE, "start kqueue wait, msec=%d", - xtimeout.tv_sec * 1000 + xtimeout.tv_nsec / 1000000)); + xtimeout.tv_sec * 1000 + xtimeout.tv_nsec / 1000000)); count = - os_kqueue_wait(ioqueue->kfd, NULL, 0, events, MAX_EVENTS, &xtimeout); + os_kqueue_wait(ioqueue->kfd, NULL, 0, events, MAX_EVENTS, &xtimeout); if (count == 0) { #if PJ_IOQUEUE_HAS_SAFE_UNREG - /* Check the closing keys only when there's no activity and when there - * are pending closing keys. - */ - if (count == 0 && !pj_list_empty(&ioqueue->closing_list)) { - pj_lock_acquire(ioqueue->lock); - scan_closing_keys(ioqueue); - pj_lock_release(ioqueue->lock); - } + /* Check the closing keys only when there's no activity and when there + * are pending closing keys. + */ + if (count == 0 && !pj_list_empty(&ioqueue->closing_list)) { + pj_lock_acquire(ioqueue->lock); + scan_closing_keys(ioqueue); + pj_lock_release(ioqueue->lock); + } #endif - TRACE_((THIS_FILE, "kqueue wait timed out")); - return count; + TRACE_((THIS_FILE, "kqueue wait timed out")); + return count; } else if (count < 0) { - TRACE_((THIS_FILE, "kqueue wait error")); - return -pj_get_netos_error(); + TRACE_((THIS_FILE, "kqueue wait error")); + return -pj_get_netos_error(); } /* Lock ioqueue. */ pj_lock_acquire(ioqueue->lock); for (event_cnt = 0, i = 0; i < count; ++i) { - pj_ioqueue_key_t *h = (pj_ioqueue_key_t *)events[i].udata; + pj_ioqueue_key_t *h = (pj_ioqueue_key_t *)events[i].udata; - TRACE_((THIS_FILE, "event %d: events=%d", i, events[i].filter)); + TRACE_((THIS_FILE, "event %d: events=%d", i, events[i].filter)); - /* - * Check readability. - */ - if ((events[i].filter & EVFILT_READ) && - (key_has_pending_read(h) || key_has_pending_accept(h)) && - !IS_CLOSING(h)) { + /* + * Check readability. + */ + if ((events[i].filter & EVFILT_READ) && + (key_has_pending_read(h) || key_has_pending_accept(h)) && + !IS_CLOSING(h)) { #if PJ_IOQUEUE_HAS_SAFE_UNREG - increment_counter(h); + increment_counter(h); #endif - queue[event_cnt].key = h; - queue[event_cnt].event_type = READABLE_EVENT; - ++event_cnt; - continue; - } - - /* - * Check for writeability. - */ - if ((events[i].filter & EVFILT_WRITE) && - (key_has_pending_write(h) || key_has_pending_connect(h)) && - !IS_CLOSING(h)) { + queue[event_cnt].key = h; + queue[event_cnt].event_type = READABLE_EVENT; + ++event_cnt; + continue; + } + + /* + * Check for writeability. + */ + if ((events[i].filter & EVFILT_WRITE) && + (key_has_pending_write(h) || key_has_pending_connect(h)) && + !IS_CLOSING(h)) { #if PJ_IOQUEUE_HAS_SAFE_UNREG - increment_counter(h); + increment_counter(h); #endif - queue[event_cnt].key = h; - queue[event_cnt].event_type = WRITEABLE_EVENT; - ++event_cnt; - continue; - } + queue[event_cnt].key = h; + queue[event_cnt].event_type = WRITEABLE_EVENT; + ++event_cnt; + continue; + } } for (i = 0; i < event_cnt; ++i) { - if (queue[i].key->grp_lock) - pj_grp_lock_add_ref_dbg(queue[i].key->grp_lock, "ioqueue", 0); + if (queue[i].key->grp_lock) + pj_grp_lock_add_ref_dbg(queue[i].key->grp_lock, "ioqueue", 0); } pj_lock_release(ioqueue->lock); @@ -671,36 +671,36 @@ PJ_DEF(int) pj_ioqueue_poll(pj_ioqueue_t *ioqueue, const pj_time_val *timeout) /* Now process the events. */ for (i = 0; i < event_cnt; ++i) { - /* Just do not exceed PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL */ - if (processed_cnt < PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL) { - switch (queue[i].event_type) { - case READABLE_EVENT: - if (ioqueue_dispatch_read_event(ioqueue, queue[i].key)) - ++processed_cnt; - break; - case WRITEABLE_EVENT: - if (ioqueue_dispatch_write_event(ioqueue, queue[i].key)) - ++processed_cnt; - break; - case EXCEPTION_EVENT: - if (ioqueue_dispatch_exception_event(ioqueue, queue[i].key)) - ++processed_cnt; - break; - case NO_EVENT: - pj_assert(!"Invalid event!"); - break; - } - } + /* Just do not exceed PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL */ + if (processed_cnt < PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL) { + switch (queue[i].event_type) { + case READABLE_EVENT: + if (ioqueue_dispatch_read_event(ioqueue, queue[i].key)) + ++processed_cnt; + break; + case WRITEABLE_EVENT: + if (ioqueue_dispatch_write_event(ioqueue, queue[i].key)) + ++processed_cnt; + break; + case EXCEPTION_EVENT: + if (ioqueue_dispatch_exception_event(ioqueue, queue[i].key)) + ++processed_cnt; + break; + case NO_EVENT: + pj_assert(!"Invalid event!"); + break; + } + } #if PJ_IOQUEUE_HAS_SAFE_UNREG - decrement_counter(queue[i].key); + decrement_counter(queue[i].key); #endif - if (queue[i].key->grp_lock) - pj_grp_lock_dec_ref_dbg(queue[i].key->grp_lock, "ioqueue", 0); + if (queue[i].key->grp_lock) + pj_grp_lock_dec_ref_dbg(queue[i].key->grp_lock, "ioqueue", 0); } TRACE_((THIS_FILE, " poll: count=%d events=%d processed=%d", count, - event_cnt, processed_cnt)); + event_cnt, processed_cnt)); return processed_cnt; } diff --git a/pjlib/src/pj/ioqueue_select.c b/pjlib/src/pj/ioqueue_select.c index 4674f88bee..bd6d2286eb 100644 --- a/pjlib/src/pj/ioqueue_select.c +++ b/pjlib/src/pj/ioqueue_select.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -81,15 +80,15 @@ */ /* #if defined(PJ_DEBUG) && PJ_DEBUG != 0 -# define VALIDATE_FD_SET 1 +# define VALIDATE_FD_SET 1 #else -# define VALIDATE_FD_SET 0 +# define VALIDATE_FD_SET 0 #endif */ #define VALIDATE_FD_SET 0 #if 0 -# define TRACE__(args) PJ_LOG(3,args) +# define TRACE__(args) PJ_LOG(3,args) #else # define TRACE__(args) #endif @@ -109,25 +108,25 @@ struct pj_ioqueue_t { DECLARE_COMMON_IOQUEUE - unsigned max, count; /* Max and current key count */ - int nfds; /* The largest fd value (for select)*/ - pj_ioqueue_key_t active_list; /* List of active keys. */ - pj_fd_set_t rfdset; - pj_fd_set_t wfdset; + unsigned max, count; /* Max and current key count */ + int nfds; /* The largest fd value (for select)*/ + pj_ioqueue_key_t active_list; /* List of active keys. */ + pj_fd_set_t rfdset; + pj_fd_set_t wfdset; #if PJ_HAS_TCP - pj_fd_set_t xfdset; + pj_fd_set_t xfdset; #endif #if PJ_IOQUEUE_HAS_SAFE_UNREG - pj_mutex_t *ref_cnt_mutex; - pj_ioqueue_key_t closing_list; - pj_ioqueue_key_t free_list; + pj_mutex_t *ref_cnt_mutex; + pj_ioqueue_key_t closing_list; + pj_ioqueue_key_t free_list; #endif }; /* Proto */ #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ - PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 + PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 static pj_status_t replace_udp_sock(pj_ioqueue_key_t *h); #endif @@ -166,9 +165,9 @@ static void rescan_fdset(pj_ioqueue_t *ioqueue) int max = 0; while (key != &ioqueue->active_list) { - if (key->fd > max) - max = key->fd; - key = key->next; + if (key->fd > max) + max = key->fd; + key = key->next; } ioqueue->nfds = max; @@ -201,7 +200,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, */ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, pj_size_t max_fd, - const pj_ioqueue_cfg *cfg, + const pj_ioqueue_cfg *cfg, pj_ioqueue_t **p_ioqueue) { pj_ioqueue_t *ioqueue; @@ -223,9 +222,9 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, ioqueue_init(ioqueue); if (cfg) - pj_memcpy(&ioqueue->cfg, cfg, sizeof(*cfg)); + pj_memcpy(&ioqueue->cfg, cfg, sizeof(*cfg)); else - pj_ioqueue_cfg_default(&ioqueue->cfg); + pj_ioqueue_cfg_default(&ioqueue->cfg); ioqueue->max = (unsigned)max_fd; ioqueue->count = 0; PJ_FD_ZERO(&ioqueue->rfdset); @@ -248,7 +247,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, */ rc = pj_mutex_create_simple(pool, NULL, &ioqueue->ref_cnt_mutex); if (rc != PJ_SUCCESS) - return rc; + return rc; /* Init key list */ @@ -258,29 +257,29 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, /* Pre-create all keys according to max_fd */ for (i=0; iref_count = 0; - rc = pj_lock_create_recursive_mutex(pool, NULL, &key->lock); - if (rc != PJ_SUCCESS) { - key = ioqueue->free_list.next; - while (key != &ioqueue->free_list) { - pj_lock_destroy(key->lock); - key = key->next; - } - pj_mutex_destroy(ioqueue->ref_cnt_mutex); - return rc; - } - - pj_list_push_back(&ioqueue->free_list, key); + pj_ioqueue_key_t *key; + + key = PJ_POOL_ALLOC_T(pool, pj_ioqueue_key_t); + key->ref_count = 0; + rc = pj_lock_create_recursive_mutex(pool, NULL, &key->lock); + if (rc != PJ_SUCCESS) { + key = ioqueue->free_list.next; + while (key != &ioqueue->free_list) { + pj_lock_destroy(key->lock); + key = key->next; + } + pj_mutex_destroy(ioqueue->ref_cnt_mutex); + return rc; + } + + pj_list_push_back(&ioqueue->free_list, key); } #endif /* Create and init ioqueue mutex */ rc = pj_lock_create_simple_mutex(pool, "ioq%p", &lock); if (rc != PJ_SUCCESS) - return rc; + return rc; rc = pj_ioqueue_set_lock(ioqueue, lock, PJ_TRUE); if (rc != PJ_SUCCESS) @@ -309,20 +308,20 @@ PJ_DEF(pj_status_t) pj_ioqueue_destroy(pj_ioqueue_t *ioqueue) /* Destroy reference counters */ key = ioqueue->active_list.next; while (key != &ioqueue->active_list) { - pj_lock_destroy(key->lock); - key = key->next; + pj_lock_destroy(key->lock); + key = key->next; } key = ioqueue->closing_list.next; while (key != &ioqueue->closing_list) { - pj_lock_destroy(key->lock); - key = key->next; + pj_lock_destroy(key->lock); + key = key->next; } key = ioqueue->free_list.next; while (key != &ioqueue->free_list) { - pj_lock_destroy(key->lock); - key = key->next; + pj_lock_destroy(key->lock); + key = key->next; } pj_mutex_destroy(ioqueue->ref_cnt_mutex); @@ -338,11 +337,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_destroy(pj_ioqueue_t *ioqueue) * Register socket handle to ioqueue. */ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, - pj_ioqueue_t *ioqueue, - pj_sock_t sock, - pj_grp_lock_t *grp_lock, - void *user_data, - const pj_ioqueue_callback *cb, + pj_ioqueue_t *ioqueue, + pj_sock_t sock, + pj_grp_lock_t *grp_lock, + void *user_data, + const pj_ioqueue_callback *cb, pj_ioqueue_key_t **p_key) { pj_ioqueue_key_t *key = NULL; @@ -363,17 +362,17 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, * an fd that is higher than FD_SETSIZE. */ if (sizeof(fd_set) < FD_SETSIZE && sock >= FD_SETSIZE) { - PJ_LOG(4, ("pjlib", "Failed to register socket to ioqueue because " - "socket fd is too big (fd=%d/FD_SETSIZE=%d)", - sock, FD_SETSIZE)); - return PJ_ETOOBIG; + PJ_LOG(4, ("pjlib", "Failed to register socket to ioqueue because " + "socket fd is too big (fd=%d/FD_SETSIZE=%d)", + sock, FD_SETSIZE)); + return PJ_ETOOBIG; } pj_lock_acquire(ioqueue->lock); if (ioqueue->count >= ioqueue->max) { rc = PJ_ETOOMANY; - goto on_return; + goto on_return; } /* If safe unregistration (PJ_IOQUEUE_HAS_SAFE_UNREG) is used, get @@ -386,8 +385,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, pj_assert(!pj_list_empty(&ioqueue->free_list)); if (pj_list_empty(&ioqueue->free_list)) { - rc = PJ_ETOOMANY; - goto on_return; + rc = PJ_ETOOMANY; + goto on_return; } key = ioqueue->free_list.next; @@ -398,8 +397,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, rc = ioqueue_init_key(pool, ioqueue, key, sock, grp_lock, user_data, cb); if (rc != PJ_SUCCESS) { - key = NULL; - goto on_return; + key = NULL; + goto on_return; } /* Set socket to nonblocking. */ @@ -412,7 +411,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, if (ioctl(sock, FIONBIO, &value)) { #endif rc = pj_get_netos_error(); - goto on_return; + goto on_return; } @@ -426,8 +425,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, on_return: /* On error, socket may be left in non-blocking mode. */ if (rc != PJ_SUCCESS) { - if (key && key->grp_lock) - pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0); + if (key && key->grp_lock) + pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0); } *p_key = key; pj_lock_release(ioqueue->lock); @@ -436,11 +435,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, } PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, - pj_ioqueue_t *ioqueue, - pj_sock_t sock, - void *user_data, - const pj_ioqueue_callback *cb, - pj_ioqueue_key_t **p_key) + pj_ioqueue_t *ioqueue, + pj_sock_t sock, + void *user_data, + const pj_ioqueue_callback *cb, + pj_ioqueue_key_t **p_key) { return pj_ioqueue_register_sock2(pool, ioqueue, sock, NULL, user_data, cb, p_key); @@ -467,15 +466,15 @@ static void decrement_counter(pj_ioqueue_key_t *key) --key->ref_count; if (key->ref_count == 0) { - pj_assert(key->closing == 1); - pj_gettickcount(&key->free_time); - key->free_time.msec += PJ_IOQUEUE_KEY_FREE_DELAY; - pj_time_val_normalize(&key->free_time); + pj_assert(key->closing == 1); + pj_gettickcount(&key->free_time); + key->free_time.msec += PJ_IOQUEUE_KEY_FREE_DELAY; + pj_time_val_normalize(&key->free_time); - pj_list_erase(key); - pj_list_push_back(&key->ioqueue->closing_list, key); - /* Rescan fdset to get max descriptor */ - rescan_fdset(key->ioqueue); + pj_list_erase(key); + pj_list_push_back(&key->ioqueue->closing_list, key); + /* Rescan fdset to get max descriptor */ + rescan_fdset(key->ioqueue); } pj_mutex_unlock(key->ioqueue->ref_cnt_mutex); pj_lock_release(key->ioqueue->lock); @@ -504,8 +503,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key) /* Best effort to avoid double key-unregistration */ if (IS_CLOSING(key)) { - pj_ioqueue_unlock_key(key); - return PJ_SUCCESS; + pj_ioqueue_unlock_key(key); + return PJ_SUCCESS; } /* Also lock ioqueue */ @@ -513,13 +512,13 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key) /* Avoid "negative" ioqueue count */ if (ioqueue->count > 0) { - --ioqueue->count; + --ioqueue->count; } else { - /* If this happens, very likely there is double unregistration - * of a key. - */ - pj_assert(!"Bad ioqueue count in key unregistration!"); - PJ_LOG(1,(THIS_FILE, "Bad ioqueue count in key unregistration!")); + /* If this happens, very likely there is double unregistration + * of a key. + */ + pj_assert(!"Bad ioqueue count in key unregistration!"); + PJ_LOG(1,(THIS_FILE, "Bad ioqueue count in key unregistration!")); } #if !PJ_IOQUEUE_HAS_SAFE_UNREG @@ -529,10 +528,10 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key) /* Remove socket from sets and close socket. */ if (key->fd != PJ_INVALID_SOCKET) { - PJ_FD_CLR(key->fd, &ioqueue->rfdset); - PJ_FD_CLR(key->fd, &ioqueue->wfdset); + PJ_FD_CLR(key->fd, &ioqueue->rfdset); + PJ_FD_CLR(key->fd, &ioqueue->wfdset); #if PJ_HAS_TCP - PJ_FD_CLR(key->fd, &ioqueue->xfdset); + PJ_FD_CLR(key->fd, &ioqueue->xfdset); #endif pj_sock_close(key->fd); @@ -559,30 +558,30 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key) /* Done. */ if (key->grp_lock) { - /* just dec_ref and unlock. we will set grp_lock to NULL - * elsewhere */ - pj_grp_lock_t *grp_lock = key->grp_lock; - // Don't set grp_lock to NULL otherwise the other thread - // will crash. Just leave it as dangling pointer, but this - // should be safe - //key->grp_lock = NULL; - pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); - pj_grp_lock_release(grp_lock); + /* just dec_ref and unlock. we will set grp_lock to NULL + * elsewhere */ + pj_grp_lock_t *grp_lock = key->grp_lock; + // Don't set grp_lock to NULL otherwise the other thread + // will crash. Just leave it as dangling pointer, but this + // should be safe + //key->grp_lock = NULL; + pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); + pj_grp_lock_release(grp_lock); } else { - pj_ioqueue_unlock_key(key); + pj_ioqueue_unlock_key(key); } #else if (key->grp_lock) { - /* set grp_lock to NULL and unlock */ - pj_grp_lock_t *grp_lock = key->grp_lock; - // Don't set grp_lock to NULL otherwise the other thread - // will crash. Just leave it as dangling pointer, but this - // should be safe - //key->grp_lock = NULL; - pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); - pj_grp_lock_release(grp_lock); + /* set grp_lock to NULL and unlock */ + pj_grp_lock_t *grp_lock = key->grp_lock; + // Don't set grp_lock to NULL otherwise the other thread + // will crash. Just leave it as dangling pointer, but this + // should be safe + //key->grp_lock = NULL; + pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); + pj_grp_lock_release(grp_lock); } else { - pj_ioqueue_unlock_key(key); + pj_ioqueue_unlock_key(key); } pj_lock_destroy(key->lock); @@ -597,9 +596,9 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key) */ #if VALIDATE_FD_SET static void validate_sets(const pj_ioqueue_t *ioqueue, - const pj_fd_set_t *rfdset, - const pj_fd_set_t *wfdset, - const pj_fd_set_t *xfdset) + const pj_fd_set_t *rfdset, + const pj_fd_set_t *wfdset, + const pj_fd_set_t *xfdset) { pj_ioqueue_key_t *key; @@ -613,42 +612,42 @@ static void validate_sets(const pj_ioqueue_t *ioqueue, key = ioqueue->active_list.next; while (key != &ioqueue->active_list) { - if (!pj_list_empty(&key->read_list) + if (!pj_list_empty(&key->read_list) #if defined(PJ_HAS_TCP) && PJ_HAS_TCP != 0 - || !pj_list_empty(&key->accept_list) + || !pj_list_empty(&key->accept_list) #endif - ) - { - pj_assert(PJ_FD_ISSET(key->fd, rfdset)); - } - else { - pj_assert(PJ_FD_ISSET(key->fd, rfdset) == 0); - } - if (!pj_list_empty(&key->write_list) + ) + { + pj_assert(PJ_FD_ISSET(key->fd, rfdset)); + } + else { + pj_assert(PJ_FD_ISSET(key->fd, rfdset) == 0); + } + if (!pj_list_empty(&key->write_list) #if defined(PJ_HAS_TCP) && PJ_HAS_TCP != 0 - || key->connecting + || key->connecting #endif - ) - { - pj_assert(PJ_FD_ISSET(key->fd, wfdset)); - } - else { - pj_assert(PJ_FD_ISSET(key->fd, wfdset) == 0); - } + ) + { + pj_assert(PJ_FD_ISSET(key->fd, wfdset)); + } + else { + pj_assert(PJ_FD_ISSET(key->fd, wfdset) == 0); + } #if defined(PJ_HAS_TCP) && PJ_HAS_TCP != 0 - if (key->connecting) - { - pj_assert(PJ_FD_ISSET(key->fd, xfdset)); - } - else { - pj_assert(PJ_FD_ISSET(key->fd, xfdset) == 0); - } + if (key->connecting) + { + pj_assert(PJ_FD_ISSET(key->fd, xfdset)); + } + else { + pj_assert(PJ_FD_ISSET(key->fd, xfdset) == 0); + } #endif /* PJ_HAS_TCP */ - key = key->next; + key = key->next; } } -#endif /* VALIDATE_FD_SET */ +#endif /* VALIDATE_FD_SET */ /* ioqueue_remove_from_set() @@ -657,8 +656,8 @@ static void validate_sets(const pj_ioqueue_t *ioqueue, * set for the specified event. */ static void ioqueue_remove_from_set( pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - enum ioqueue_event_type event_type ) + pj_ioqueue_key_t *key, + enum ioqueue_event_type event_type ) { ioqueue_remove_from_set2(ioqueue, key, event_type); } @@ -689,7 +688,7 @@ static void ioqueue_remove_from_set2(pj_ioqueue_t *ioqueue, */ static void ioqueue_add_to_set( pj_ioqueue_t *ioqueue, pj_ioqueue_key_t *key, - enum ioqueue_event_type event_type ) + enum ioqueue_event_type event_type ) { ioqueue_add_to_set2(ioqueue, key, event_type); } @@ -722,19 +721,19 @@ static void scan_closing_keys(pj_ioqueue_t *ioqueue) pj_gettickcount(&now); h = ioqueue->closing_list.next; while (h != &ioqueue->closing_list) { - pj_ioqueue_key_t *next = h->next; - - pj_assert(h->closing != 0); - - if (PJ_TIME_VAL_GTE(now, h->free_time)) { - pj_list_erase(h); - // Don't set grp_lock to NULL otherwise the other thread - // will crash. Just leave it as dangling pointer, but this - // should be safe - //h->grp_lock = NULL; - pj_list_push_back(&ioqueue->free_list, h); - } - h = next; + pj_ioqueue_key_t *next = h->next; + + pj_assert(h->closing != 0); + + if (PJ_TIME_VAL_GTE(now, h->free_time)) { + pj_list_erase(h); + // Don't set grp_lock to NULL otherwise the other thread + // will crash. Just leave it as dangling pointer, but this + // should be safe + //h->grp_lock = NULL; + pj_list_push_back(&ioqueue->free_list, h); + } + h = next; } } #endif @@ -744,8 +743,8 @@ static void scan_closing_keys(pj_ioqueue_t *ioqueue) static pj_status_t replace_udp_sock(pj_ioqueue_key_t *h) { enum flags { - HAS_PEER_ADDR = 1, - HAS_QOS = 2 + HAS_PEER_ADDR = 1, + HAS_QOS = 2 }; pj_sock_t old_sock, new_sock = PJ_INVALID_SOCKET; pj_sockaddr local_addr, rem_addr; @@ -786,7 +785,7 @@ static pj_status_t replace_udp_sock(pj_ioqueue_key_t *h) status = pj_sock_getsockname(old_sock, &local_addr, &addr_len); if (status != PJ_SUCCESS) { PJ_PERROR(5,(THIS_FILE, status, "Error get socket name")); - continue; + continue; } addr_len = sizeof(rem_addr); @@ -794,28 +793,28 @@ static pj_status_t replace_udp_sock(pj_ioqueue_key_t *h) if (status != PJ_SUCCESS) { PJ_PERROR(5,(THIS_FILE, status, "Error get peer name")); } else { - flags |= HAS_PEER_ADDR; + flags |= HAS_PEER_ADDR; } status = pj_sock_get_qos_params(old_sock, &qos_params); if (status == PJ_STATUS_FROM_OS(EBADF) || status == PJ_STATUS_FROM_OS(EINVAL)) { - PJ_PERROR(5,(THIS_FILE, status, "Error get qos param")); - continue; + PJ_PERROR(5,(THIS_FILE, status, "Error get qos param")); + continue; } if (status != PJ_SUCCESS) { - PJ_PERROR(5,(THIS_FILE, status, "Error get qos param")); + PJ_PERROR(5,(THIS_FILE, status, "Error get qos param")); } else { - flags |= HAS_QOS; + flags |= HAS_QOS; } /* We're done with the old socket, close it otherwise we'll get * error in bind() */ status = pj_sock_close(old_sock); - if (status != PJ_SUCCESS) { + if (status != PJ_SUCCESS) { PJ_PERROR(5,(THIS_FILE, status, "Error closing socket")); } @@ -886,17 +885,17 @@ static pj_status_t replace_udp_sock(pj_ioqueue_key_t *h) if (ioctl(new_sock, FIONBIO, &val)) { #endif status = pj_get_netos_error(); - goto on_error; + goto on_error; } /* Replace the occurrence of old socket with new socket in the * fd sets. */ for (i=0; ifd, fds[i])) { - PJ_FD_CLR(h->fd, fds[i]); - PJ_FD_SET(new_sock, fds[i]); - } + if (PJ_FD_ISSET(h->fd, fds[i])) { + PJ_FD_CLR(h->fd, fds[i]); + PJ_FD_SET(new_sock, fds[i]); + } } /* And finally replace the fd in the key */ @@ -910,15 +909,15 @@ static pj_status_t replace_udp_sock(pj_ioqueue_key_t *h) on_error: if (new_sock != PJ_INVALID_SOCKET) - pj_sock_close(new_sock); + pj_sock_close(new_sock); if (old_sock != PJ_INVALID_SOCKET) - pj_sock_close(old_sock); + pj_sock_close(old_sock); /* Clear the occurrence of old socket in the fd sets. */ for (i=0; ifd, fds[i])) { - PJ_FD_CLR(h->fd, fds[i]); - } + if (PJ_FD_ISSET(h->fd, fds[i])) { + PJ_FD_CLR(h->fd, fds[i]); + } } h->fd = PJ_INVALID_SOCKET; @@ -955,7 +954,7 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) enum { MAX_EVENTS = PJ_IOQUEUE_MAX_CAND_EVENTS }; struct event { - pj_ioqueue_key_t *key; + pj_ioqueue_key_t *key; enum ioqueue_event_type event_type; } event[MAX_EVENTS]; @@ -978,13 +977,13 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) #if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0 && PJ_FD_COUNT(&ioqueue->xfdset)==0 #endif - ) + ) { #if PJ_IOQUEUE_HAS_SAFE_UNREG - scan_closing_keys(ioqueue); + scan_closing_keys(ioqueue); #endif - pj_lock_release(ioqueue->lock); - TRACE__((THIS_FILE, " poll: no fd is set")); + pj_lock_release(ioqueue->lock); + TRACE__((THIS_FILE, " poll: no fd is set")); if (timeout) pj_thread_sleep(PJ_TIME_VAL_MSEC(*timeout)); return 0; @@ -1014,20 +1013,20 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) #endif count = pj_sock_select(nfds+1, &rfdset, &wfdset, &xfdset, - timeout); + timeout); #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 /* Ignore Invalid Handle Exception raised by select().*/ } __except (GetExceptionCode() == STATUS_INVALID_HANDLE ? - EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH) { + EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH) { } #endif if (count == 0) - return 0; + return 0; else if (count < 0) - return -pj_get_netos_error(); + return -pj_get_netos_error(); /* Scan descriptor sets for event and add the events in the event * array to be processed later in this function. We do this so that @@ -1041,17 +1040,17 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) * coming with accept(). */ for (h = ioqueue->active_list.next; - h != &ioqueue->active_list && event_cnt < MAX_EVENTS; - h = h->next) + h != &ioqueue->active_list && event_cnt < MAX_EVENTS; + h = h->next) { - if (h->fd == PJ_INVALID_SOCKET) - continue; + if (h->fd == PJ_INVALID_SOCKET) + continue; - if ( (key_has_pending_write(h) || key_has_pending_connect(h)) - && PJ_FD_ISSET(h->fd, &wfdset) && !IS_CLOSING(h)) + if ( (key_has_pending_write(h) || key_has_pending_connect(h)) + && PJ_FD_ISSET(h->fd, &wfdset) && !IS_CLOSING(h)) { #if PJ_IOQUEUE_HAS_SAFE_UNREG - increment_counter(h); + increment_counter(h); #endif event[event_cnt].key = h; event[event_cnt].event_type = WRITEABLE_EVENT; @@ -1059,24 +1058,24 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) } /* Scan for readable socket. */ - if ((key_has_pending_read(h) || key_has_pending_accept(h)) + if ((key_has_pending_read(h) || key_has_pending_accept(h)) && PJ_FD_ISSET(h->fd, &rfdset) && !IS_CLOSING(h) && - event_cnt < MAX_EVENTS) + event_cnt < MAX_EVENTS) { #if PJ_IOQUEUE_HAS_SAFE_UNREG - increment_counter(h); + increment_counter(h); #endif event[event_cnt].key = h; event[event_cnt].event_type = READABLE_EVENT; ++event_cnt; - } + } #if PJ_HAS_TCP if (key_has_pending_connect(h) && PJ_FD_ISSET(h->fd, &xfdset) && - !IS_CLOSING(h) && event_cnt < MAX_EVENTS) - { + !IS_CLOSING(h) && event_cnt < MAX_EVENTS) + { #if PJ_IOQUEUE_HAS_SAFE_UNREG - increment_counter(h); + increment_counter(h); #endif event[event_cnt].key = h; event[event_cnt].event_type = EXCEPTION_EVENT; @@ -1086,8 +1085,8 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) } for (i=0; igrp_lock) - pj_grp_lock_add_ref_dbg(event[i].key->grp_lock, "ioqueue", 0); + if (event[i].key->grp_lock) + pj_grp_lock_add_ref_dbg(event[i].key->grp_lock, "ioqueue", 0); } PJ_RACE_ME(5); @@ -1103,38 +1102,38 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) */ for (i=0; igrp_lock) - pj_grp_lock_dec_ref_dbg(event[i].key->grp_lock, - "ioqueue", 0); + if (event[i].key->grp_lock) + pj_grp_lock_dec_ref_dbg(event[i].key->grp_lock, + "ioqueue", 0); } TRACE__((THIS_FILE, " poll: count=%d events=%d processed=%d", - count, event_cnt, processed_cnt)); + count, event_cnt, processed_cnt)); return processed_cnt; } diff --git a/pjlib/src/pj/ioqueue_symbian.cpp b/pjlib/src/pj/ioqueue_symbian.cpp index 12646214cd..d21f60e94f 100644 --- a/pjlib/src/pj/ioqueue_symbian.cpp +++ b/pjlib/src/pj/ioqueue_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,7 +33,7 @@ class CIoqueueCallback; */ struct pj_ioqueue_t { - int eventCount; + int eventCount; }; @@ -45,26 +44,26 @@ class CIoqueueCallback : public CActive { public: static CIoqueueCallback* NewL(pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - pj_sock_t sock, - const pj_ioqueue_callback *cb, - void *user_data); + pj_ioqueue_key_t *key, + pj_sock_t sock, + const pj_ioqueue_callback *cb, + void *user_data); // // Start asynchronous recv() operation // pj_status_t StartRead(pj_ioqueue_op_key_t *op_key, - void *buf, pj_ssize_t *size, unsigned flags, - pj_sockaddr_t *addr, int *addrlen); + void *buf, pj_ssize_t *size, unsigned flags, + pj_sockaddr_t *addr, int *addrlen); // // Start asynchronous accept() operation. // pj_status_t StartAccept(pj_ioqueue_op_key_t *op_key, - pj_sock_t *new_sock, - pj_sockaddr_t *local, - pj_sockaddr_t *remote, - int *addrlen ); + pj_sock_t *new_sock, + pj_sockaddr_t *local, + pj_sockaddr_t *remote, + int *addrlen ); // // Completion callback. @@ -80,91 +79,91 @@ class CIoqueueCallback : public CActive // Cancel operation and call callback. // void CancelOperation(pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_status); + pj_ssize_t bytes_status); // // Accessors // void* get_user_data() const { - return user_data_; + return user_data_; } void set_user_data(void *user_data) { - user_data_ = user_data; + user_data_ = user_data; } pj_ioqueue_op_key_t *get_op_key() const { - return pending_data_.common_.op_key_; + return pending_data_.common_.op_key_; } CPjSocket* get_pj_socket() { - return sock_; + return sock_; } private: // Type of pending operation. enum Type { - TYPE_NONE, - TYPE_READ, - TYPE_ACCEPT, + TYPE_NONE, + TYPE_READ, + TYPE_ACCEPT, }; // Static data. - pj_ioqueue_t *ioqueue_; - pj_ioqueue_key_t *key_; - CPjSocket *sock_; - pj_ioqueue_callback cb_; - void *user_data_; + pj_ioqueue_t *ioqueue_; + pj_ioqueue_key_t *key_; + CPjSocket *sock_; + pj_ioqueue_callback cb_; + void *user_data_; // Symbian data. - TPtr8 aBufferPtr_; - TInetAddr aAddress_; + TPtr8 aBufferPtr_; + TInetAddr aAddress_; // Application data. - Type type_; + Type type_; union Pending_Data { - struct Common - { - pj_ioqueue_op_key_t *op_key_; - } common_; - - struct Pending_Read - { - pj_ioqueue_op_key_t *op_key_; - pj_sockaddr_t *addr_; - int *addrlen_; - } read_; - - struct Pending_Accept - { - pj_ioqueue_op_key_t *op_key_; - pj_sock_t *new_sock_; - pj_sockaddr_t *local_; - pj_sockaddr_t *remote_; - int *addrlen_; - } accept_; + struct Common + { + pj_ioqueue_op_key_t *op_key_; + } common_; + + struct Pending_Read + { + pj_ioqueue_op_key_t *op_key_; + pj_sockaddr_t *addr_; + int *addrlen_; + } read_; + + struct Pending_Accept + { + pj_ioqueue_op_key_t *op_key_; + pj_sock_t *new_sock_; + pj_sockaddr_t *local_; + pj_sockaddr_t *remote_; + int *addrlen_; + } accept_; }; - union Pending_Data pending_data_; - RSocket blank_sock_; + union Pending_Data pending_data_; + RSocket blank_sock_; CIoqueueCallback(pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, pj_sock_t sock, - const pj_ioqueue_callback *cb, void *user_data) + pj_ioqueue_key_t *key, pj_sock_t sock, + const pj_ioqueue_callback *cb, void *user_data) : CActive(CActive::EPriorityStandard), - ioqueue_(ioqueue), key_(key), sock_((CPjSocket*)sock), - user_data_(user_data), aBufferPtr_(NULL, 0), type_(TYPE_NONE) + ioqueue_(ioqueue), key_(key), sock_((CPjSocket*)sock), + user_data_(user_data), aBufferPtr_(NULL, 0), type_(TYPE_NONE) { - pj_memcpy(&cb_, cb, sizeof(*cb)); + pj_memcpy(&cb_, cb, sizeof(*cb)); } void ConstructL() { - CActiveScheduler::Add(this); + CActiveScheduler::Add(this); } void HandleReadCompletion(); @@ -173,13 +172,13 @@ class CIoqueueCallback : public CActive CIoqueueCallback* CIoqueueCallback::NewL(pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - pj_sock_t sock, - const pj_ioqueue_callback *cb, - void *user_data) + pj_ioqueue_key_t *key, + pj_sock_t sock, + const pj_ioqueue_callback *cb, + void *user_data) { CIoqueueCallback *self = new CIoqueueCallback(ioqueue, key, sock, - cb, user_data); + cb, user_data); CleanupStack::PushL(self); self->ConstructL(); CleanupStack::Pop(self); @@ -192,9 +191,9 @@ CIoqueueCallback* CIoqueueCallback::NewL(pj_ioqueue_t *ioqueue, // Start asynchronous recv() operation // pj_status_t CIoqueueCallback::StartRead(pj_ioqueue_op_key_t *op_key, - void *buf, pj_ssize_t *size, - unsigned flags, - pj_sockaddr_t *addr, int *addrlen) + void *buf, pj_ssize_t *size, + unsigned flags, + pj_sockaddr_t *addr, int *addrlen) { PJ_ASSERT_RETURN(IsActive()==false, PJ_EBUSY); PJ_ASSERT_RETURN(pending_data_.common_.op_key_==NULL, PJ_EBUSY); @@ -209,20 +208,20 @@ pj_status_t CIoqueueCallback::StartRead(pj_ioqueue_op_key_t *op_key, type_ = TYPE_READ; if (addr && addrlen) { - sock_->Socket().RecvFrom(aBufferPtr_, aAddress_, flags, iStatus); + sock_->Socket().RecvFrom(aBufferPtr_, aAddress_, flags, iStatus); } else { - aAddress_.SetAddress(0); - aAddress_.SetPort(0); - - if (sock_->IsDatagram()) { - sock_->Socket().Recv(aBufferPtr_, flags, iStatus); - } else { - // Using static like this is not pretty, but we don't need to use - // the value anyway, hence doing it like this is probably most - // optimal. - static TSockXfrLength len; - sock_->Socket().RecvOneOrMore(aBufferPtr_, flags, iStatus, len); - } + aAddress_.SetAddress(0); + aAddress_.SetPort(0); + + if (sock_->IsDatagram()) { + sock_->Socket().Recv(aBufferPtr_, flags, iStatus); + } else { + // Using static like this is not pretty, but we don't need to use + // the value anyway, hence doing it like this is probably most + // optimal. + static TSockXfrLength len; + sock_->Socket().RecvOneOrMore(aBufferPtr_, flags, iStatus, len); + } } SetActive(); @@ -234,17 +233,17 @@ pj_status_t CIoqueueCallback::StartRead(pj_ioqueue_op_key_t *op_key, // Start asynchronous accept() operation. // pj_status_t CIoqueueCallback::StartAccept(pj_ioqueue_op_key_t *op_key, - pj_sock_t *new_sock, - pj_sockaddr_t *local, - pj_sockaddr_t *remote, - int *addrlen ) + pj_sock_t *new_sock, + pj_sockaddr_t *local, + pj_sockaddr_t *remote, + int *addrlen ) { PJ_ASSERT_RETURN(IsActive()==false, PJ_EBUSY); PJ_ASSERT_RETURN(pending_data_.common_.op_key_==NULL, PJ_EBUSY); // addrlen must be specified if local or remote is specified PJ_ASSERT_RETURN((!local && !remote) || - (addrlen && *addrlen), PJ_EINVAL); + (addrlen && *addrlen), PJ_EINVAL); pending_data_.accept_.op_key_ = op_key; pending_data_.accept_.new_sock_ = new_sock; @@ -269,13 +268,13 @@ pj_status_t CIoqueueCallback::StartAccept(pj_ioqueue_op_key_t *op_key, void CIoqueueCallback::HandleReadCompletion() { if (pending_data_.read_.addr_ && pending_data_.read_.addrlen_) { - PjSymbianOS::Addr2pj(aAddress_, - *(pj_sockaddr*)pending_data_.read_.addr_, - pending_data_.read_.addrlen_); - pending_data_.read_.addr_ = NULL; - pending_data_.read_.addrlen_ = NULL; + PjSymbianOS::Addr2pj(aAddress_, + *(pj_sockaddr*)pending_data_.read_.addr_, + pending_data_.read_.addrlen_); + pending_data_.read_.addr_ = NULL; + pending_data_.read_.addrlen_ = NULL; } - + pending_data_.read_.op_key_ = NULL; } @@ -285,53 +284,53 @@ void CIoqueueCallback::HandleReadCompletion() // CPjSocket *CIoqueueCallback::HandleAcceptCompletion() { - CPjSocket *pjNewSock = new CPjSocket(get_pj_socket()->GetAf(), - get_pj_socket()->GetSockType(), - blank_sock_); - int addrlen = 0; - - if (pending_data_.accept_.new_sock_) { - *pending_data_.accept_.new_sock_ = (pj_sock_t)pjNewSock; - pending_data_.accept_.new_sock_ = NULL; - } - - if (pending_data_.accept_.local_) { - TInetAddr aAddr; - pj_sockaddr *ptr_sockaddr; - - blank_sock_.LocalName(aAddr); - ptr_sockaddr = (pj_sockaddr*)pending_data_.accept_.local_; - addrlen = *pending_data_.accept_.addrlen_; - PjSymbianOS::Addr2pj(aAddr, *ptr_sockaddr, &addrlen); - pending_data_.accept_.local_ = NULL; - } - - if (pending_data_.accept_.remote_) { - TInetAddr aAddr; - pj_sockaddr *ptr_sockaddr; - - blank_sock_.RemoteName(aAddr); - ptr_sockaddr = (pj_sockaddr*)pending_data_.accept_.remote_; - addrlen = *pending_data_.accept_.addrlen_; - PjSymbianOS::Addr2pj(aAddr, *ptr_sockaddr, &addrlen); - pending_data_.accept_.remote_ = NULL; - } - - if (pending_data_.accept_.addrlen_) { - if (addrlen == 0) { - if (pjNewSock->GetAf() == PJ_AF_INET) - addrlen = sizeof(pj_sockaddr_in); - else if (pjNewSock->GetAf() == PJ_AF_INET6) - addrlen = sizeof(pj_sockaddr_in6); - else { - pj_assert(!"Unsupported address family"); - } - } - *pending_data_.accept_.addrlen_ = addrlen; - pending_data_.accept_.addrlen_ = NULL; - } - - return pjNewSock; + CPjSocket *pjNewSock = new CPjSocket(get_pj_socket()->GetAf(), + get_pj_socket()->GetSockType(), + blank_sock_); + int addrlen = 0; + + if (pending_data_.accept_.new_sock_) { + *pending_data_.accept_.new_sock_ = (pj_sock_t)pjNewSock; + pending_data_.accept_.new_sock_ = NULL; + } + + if (pending_data_.accept_.local_) { + TInetAddr aAddr; + pj_sockaddr *ptr_sockaddr; + + blank_sock_.LocalName(aAddr); + ptr_sockaddr = (pj_sockaddr*)pending_data_.accept_.local_; + addrlen = *pending_data_.accept_.addrlen_; + PjSymbianOS::Addr2pj(aAddr, *ptr_sockaddr, &addrlen); + pending_data_.accept_.local_ = NULL; + } + + if (pending_data_.accept_.remote_) { + TInetAddr aAddr; + pj_sockaddr *ptr_sockaddr; + + blank_sock_.RemoteName(aAddr); + ptr_sockaddr = (pj_sockaddr*)pending_data_.accept_.remote_; + addrlen = *pending_data_.accept_.addrlen_; + PjSymbianOS::Addr2pj(aAddr, *ptr_sockaddr, &addrlen); + pending_data_.accept_.remote_ = NULL; + } + + if (pending_data_.accept_.addrlen_) { + if (addrlen == 0) { + if (pjNewSock->GetAf() == PJ_AF_INET) + addrlen = sizeof(pj_sockaddr_in); + else if (pjNewSock->GetAf() == PJ_AF_INET6) + addrlen = sizeof(pj_sockaddr_in6); + else { + pj_assert(!"Unsupported address family"); + } + } + *pending_data_.accept_.addrlen_ = addrlen; + pending_data_.accept_.addrlen_ = NULL; + } + + return pjNewSock; } @@ -346,58 +345,58 @@ void CIoqueueCallback::RunL() type_ = TYPE_NONE; if (cur_type == TYPE_READ) { - // - // Completion of asynchronous RecvFrom() - // - - /* Clear op_key (save it to temp variable first!) */ - pj_ioqueue_op_key_t *op_key = pending_data_.read_.op_key_; - pending_data_.read_.op_key_ = NULL; - - // Handle failure condition - if (iStatus != KErrNone) { - if (cb_.on_read_complete) { - cb_.on_read_complete( key_, op_key, - -PJ_RETURN_OS_ERROR(iStatus.Int())); - } - return; - } - - HandleReadCompletion(); - - /* Call callback */ - if (cb_.on_read_complete) { - cb_.on_read_complete(key_, op_key, aBufferPtr_.Length()); - } + // + // Completion of asynchronous RecvFrom() + // + + /* Clear op_key (save it to temp variable first!) */ + pj_ioqueue_op_key_t *op_key = pending_data_.read_.op_key_; + pending_data_.read_.op_key_ = NULL; + + // Handle failure condition + if (iStatus != KErrNone) { + if (cb_.on_read_complete) { + cb_.on_read_complete( key_, op_key, + -PJ_RETURN_OS_ERROR(iStatus.Int())); + } + return; + } + + HandleReadCompletion(); + + /* Call callback */ + if (cb_.on_read_complete) { + cb_.on_read_complete(key_, op_key, aBufferPtr_.Length()); + } } else if (cur_type == TYPE_ACCEPT) { - // - // Completion of asynchronous Accept() - // - - /* Clear op_key (save it to temp variable first!) */ - pj_ioqueue_op_key_t *op_key = pending_data_.read_.op_key_; - pending_data_.read_.op_key_ = NULL; - - // Handle failure condition - if (iStatus != KErrNone) { - if (pending_data_.accept_.new_sock_) - *pending_data_.accept_.new_sock_ = PJ_INVALID_SOCKET; - - if (cb_.on_accept_complete) { - cb_.on_accept_complete( key_, op_key, PJ_INVALID_SOCKET, - -PJ_RETURN_OS_ERROR(iStatus.Int())); - } - return; - } - - CPjSocket *pjNewSock = HandleAcceptCompletion(); - - // Call callback. - if (cb_.on_accept_complete) { - cb_.on_accept_complete( key_, op_key, (pj_sock_t)pjNewSock, - PJ_SUCCESS); - } + // + // Completion of asynchronous Accept() + // + + /* Clear op_key (save it to temp variable first!) */ + pj_ioqueue_op_key_t *op_key = pending_data_.read_.op_key_; + pending_data_.read_.op_key_ = NULL; + + // Handle failure condition + if (iStatus != KErrNone) { + if (pending_data_.accept_.new_sock_) + *pending_data_.accept_.new_sock_ = PJ_INVALID_SOCKET; + + if (cb_.on_accept_complete) { + cb_.on_accept_complete( key_, op_key, PJ_INVALID_SOCKET, + -PJ_RETURN_OS_ERROR(iStatus.Int())); + } + return; + } + + CPjSocket *pjNewSock = HandleAcceptCompletion(); + + // Call callback. + if (cb_.on_accept_complete) { + cb_.on_accept_complete( key_, op_key, (pj_sock_t)pjNewSock, + PJ_SUCCESS); + } } ioq->eventCount++; @@ -409,9 +408,9 @@ void CIoqueueCallback::RunL() void CIoqueueCallback::DoCancel() { if (type_ == TYPE_READ) - sock_->Socket().CancelRecv(); + sock_->Socket().CancelRecv(); else if (type_ == TYPE_ACCEPT) - sock_->Socket().CancelAccept(); + sock_->Socket().CancelAccept(); type_ = TYPE_NONE; pending_data_.common_.op_key_ = NULL; @@ -421,7 +420,7 @@ void CIoqueueCallback::DoCancel() // Cancel operation and call callback. // void CIoqueueCallback::CancelOperation(pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_status) + pj_ssize_t bytes_status) { Type cur_type = type_; @@ -430,10 +429,10 @@ void CIoqueueCallback::CancelOperation(pj_ioqueue_op_key_t *op_key, Cancel(); if (cur_type == TYPE_READ) { - if (cb_.on_read_complete) - cb_.on_read_complete(key_, op_key, bytes_status); + if (cb_.on_read_complete) + cb_.on_read_complete(key_, op_key, bytes_status); } else if (cur_type == TYPE_ACCEPT) - ; + ; } @@ -443,7 +442,7 @@ void CIoqueueCallback::CancelOperation(pj_ioqueue_op_key_t *op_key, */ struct pj_ioqueue_key_t { - CIoqueueCallback *cbObj; + CIoqueueCallback *cbObj; }; @@ -459,9 +458,9 @@ PJ_DEF(const char*) pj_ioqueue_name(void) /* * Create a new I/O Queue framework. */ -PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, - pj_size_t max_fd, - pj_ioqueue_t **p_ioqueue) +PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, + pj_size_t max_fd, + pj_ioqueue_t **p_ioqueue) { pj_ioqueue_t *ioq; @@ -487,36 +486,36 @@ PJ_DEF(pj_status_t) pj_ioqueue_destroy( pj_ioqueue_t *ioq ) * Set the lock object to be used by the I/O Queue. */ PJ_DEF(pj_status_t) pj_ioqueue_set_lock( pj_ioqueue_t *ioq, - pj_lock_t *lock, - pj_bool_t auto_delete ) + pj_lock_t *lock, + pj_bool_t auto_delete ) { /* Don't really need lock for now */ PJ_UNUSED_ARG(ioq); if (auto_delete) { - pj_lock_destroy(lock); + pj_lock_destroy(lock); } return PJ_SUCCESS; } PJ_DEF(pj_status_t) pj_ioqueue_set_default_concurrency(pj_ioqueue_t *ioqueue, - pj_bool_t allow) + pj_bool_t allow) { - /* Not supported, just return PJ_SUCCESS silently */ - PJ_UNUSED_ARG(ioqueue); - PJ_UNUSED_ARG(allow); - return PJ_SUCCESS; + /* Not supported, just return PJ_SUCCESS silently */ + PJ_UNUSED_ARG(ioqueue); + PJ_UNUSED_ARG(allow); + return PJ_SUCCESS; } /* * Register a socket to the I/O queue framework. */ PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, - pj_ioqueue_t *ioq, - pj_sock_t sock, - void *user_data, - const pj_ioqueue_callback *cb, + pj_ioqueue_t *ioq, + pj_sock_t sock, + void *user_data, + const pj_ioqueue_callback *cb, pj_ioqueue_key_t **p_key ) { pj_ioqueue_key_t *key; @@ -529,11 +528,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, } PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, - pj_ioqueue_t *ioqueue, - pj_sock_t sock, - pj_grp_lock_t *grp_lock, - void *user_data, - const pj_ioqueue_callback *cb, + pj_ioqueue_t *ioqueue, + pj_sock_t sock, + pj_grp_lock_t *grp_lock, + void *user_data, + const pj_ioqueue_callback *cb, pj_ioqueue_key_t **p_key) { PJ_UNUSED_ARG(grp_lock); @@ -547,11 +546,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key ) { if (key == NULL || key->cbObj == NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; // Cancel pending async object if (key->cbObj) { - key->cbObj->Cancel(); + key->cbObj->Cancel(); } // Close socket. @@ -560,8 +559,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key ) // Delete async object. if (key->cbObj) { - delete key->cbObj; - key->cbObj = NULL; + delete key->cbObj; + key->cbObj = NULL; } return PJ_SUCCESS; @@ -586,7 +585,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_set_user_data( pj_ioqueue_key_t *key, void **old_data) { if (old_data) - *old_data = key->cbObj->get_user_data(); + *old_data = key->cbObj->get_user_data(); key->cbObj->set_user_data(user_data); return PJ_SUCCESS; @@ -597,7 +596,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_set_user_data( pj_ioqueue_key_t *key, * Initialize operation key. */ PJ_DEF(void) pj_ioqueue_op_key_init( pj_ioqueue_op_key_t *op_key, - pj_size_t size ) + pj_size_t size ) { pj_bzero(op_key, size); } @@ -610,7 +609,7 @@ PJ_DEF(pj_bool_t) pj_ioqueue_is_pending( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key ) { return key->cbObj->get_op_key()==op_key && - key->cbObj->IsActive(); + key->cbObj->IsActive(); } @@ -623,7 +622,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_post_completion( pj_ioqueue_key_t *key, pj_ssize_t bytes_status ) { if (pj_ioqueue_is_pending(key, op_key)) { - key->cbObj->CancelOperation(op_key, bytes_status); + key->cbObj->CancelOperation(op_key, bytes_status); } return PJ_SUCCESS; } @@ -636,10 +635,10 @@ PJ_DEF(pj_status_t) pj_ioqueue_post_completion( pj_ioqueue_key_t *key, */ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - pj_sock_t *new_sock, - pj_sockaddr_t *local, - pj_sockaddr_t *remote, - int *addrlen ) + pj_sock_t *new_sock, + pj_sockaddr_t *local, + pj_sockaddr_t *remote, + int *addrlen ) { return key->cbObj->StartAccept(op_key, new_sock, local, remote, addrlen); @@ -650,8 +649,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, * Initiate non-blocking socket connect. */ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, - const pj_sockaddr_t *addr, - int addrlen ) + const pj_sockaddr_t *addr, + int addrlen ) { pj_status_t status; @@ -664,9 +663,9 @@ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, // Convert address status = PjSymbianOS::pj2Addr(*(const pj_sockaddr*)addr, addrlen, - inetAddr); + inetAddr); if (status != PJ_SUCCESS) - return status; + return status; // We don't support async connect for now. PJ_TODO(IOQUEUE_SUPPORT_ASYNC_CONNECT); @@ -675,19 +674,19 @@ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, User::WaitForRequest(reqStatus); if (reqStatus == KErrNone) - return PJ_SUCCESS; + return PJ_SUCCESS; return PJ_RETURN_OS_ERROR(reqStatus.Int()); } -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ /* * Poll the I/O Queue for completed events. */ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioq, - const pj_time_val *timeout) + const pj_time_val *timeout) { /* Polling is not necessary on Symbian, since all async activities * are registered to active scheduler. @@ -703,13 +702,13 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioq, */ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - void *buffer, - pj_ssize_t *length, - pj_uint32_t flags ) + void *buffer, + pj_ssize_t *length, + pj_uint32_t flags ) { // If socket has reader, delete it. if (key->cbObj->get_pj_socket()->Reader()) - key->cbObj->get_pj_socket()->DestroyReader(); + key->cbObj->get_pj_socket()->DestroyReader(); // Clear flag flags &= ~PJ_IOQUEUE_ALWAYS_ASYNC; @@ -724,31 +723,31 @@ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, */ PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - void *buffer, - pj_ssize_t *length, + void *buffer, + pj_ssize_t *length, pj_uint32_t flags, - pj_sockaddr_t *addr, - int *addrlen) + pj_sockaddr_t *addr, + int *addrlen) { CPjSocket *sock = key->cbObj->get_pj_socket(); // If address is specified, check that the length match the // address family if (addr || addrlen) { - PJ_ASSERT_RETURN(addr && addrlen && *addrlen, PJ_EINVAL); - if (sock->GetAf() == PJ_AF_INET) { - PJ_ASSERT_RETURN(*addrlen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); - } else if (sock->GetAf() == PJ_AF_INET6) { - PJ_ASSERT_RETURN(*addrlen>=(int)sizeof(pj_sockaddr_in6), PJ_EINVAL); - } + PJ_ASSERT_RETURN(addr && addrlen && *addrlen, PJ_EINVAL); + if (sock->GetAf() == PJ_AF_INET) { + PJ_ASSERT_RETURN(*addrlen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); + } else if (sock->GetAf() == PJ_AF_INET6) { + PJ_ASSERT_RETURN(*addrlen>=(int)sizeof(pj_sockaddr_in6), PJ_EINVAL); + } } // If socket has reader, delete it. if (sock->Reader()) - sock->DestroyReader(); + sock->DestroyReader(); if (key->cbObj->IsActive()) - return PJ_EBUSY; + return PJ_EBUSY; // Clear flag flags &= ~PJ_IOQUEUE_ALWAYS_ASYNC; @@ -761,9 +760,9 @@ PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, */ PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - const void *data, - pj_ssize_t *length, - pj_uint32_t flags ) + const void *data, + pj_ssize_t *length, + pj_uint32_t flags ) { TRequestStatus reqStatus; TPtrC8 aBuffer((const TUint8*)data, (TInt)*length); @@ -784,7 +783,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, User::WaitForRequest(reqStatus); if (reqStatus.Int() != KErrNone) - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR(reqStatus.Int()); //At least in UIQ Emulator, aLen.Length() reports incorrect length //for UDP (some newlc.com users seem to have reported this too). @@ -798,11 +797,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, */ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - const void *data, - pj_ssize_t *length, + const void *data, + pj_ssize_t *length, pj_uint32_t flags, - const pj_sockaddr_t *addr, - int addrlen) + const pj_sockaddr_t *addr, + int addrlen) { TRequestStatus reqStatus; TPtrC8 aBuffer; @@ -820,9 +819,9 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, // Convert address status = PjSymbianOS::pj2Addr(*(const pj_sockaddr*)addr, addrlen, - inetAddr); + inetAddr); if (status != PJ_SUCCESS) - return status; + return status; // Clear flag flags &= ~PJ_IOQUEUE_ALWAYS_ASYNC; @@ -834,7 +833,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, User::WaitForRequest(reqStatus); if (reqStatus.Int() != KErrNone) - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR(reqStatus.Int()); //At least in UIQ Emulator, aLen.Length() reports incorrect length //for UDP (some newlc.com users seem to have reported this too). @@ -843,24 +842,24 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, } PJ_DEF(pj_status_t) pj_ioqueue_set_concurrency(pj_ioqueue_key_t *key, - pj_bool_t allow) + pj_bool_t allow) { - /* Not supported, just return PJ_SUCCESS silently */ - PJ_UNUSED_ARG(key); - PJ_UNUSED_ARG(allow); - return PJ_SUCCESS; + /* Not supported, just return PJ_SUCCESS silently */ + PJ_UNUSED_ARG(key); + PJ_UNUSED_ARG(allow); + return PJ_SUCCESS; } PJ_DEF(pj_status_t) pj_ioqueue_lock_key(pj_ioqueue_key_t *key) { - /* Not supported, just return PJ_SUCCESS silently */ - PJ_UNUSED_ARG(key); - return PJ_SUCCESS; + /* Not supported, just return PJ_SUCCESS silently */ + PJ_UNUSED_ARG(key); + return PJ_SUCCESS; } PJ_DEF(pj_status_t) pj_ioqueue_unlock_key(pj_ioqueue_key_t *key) { - /* Not supported, just return PJ_SUCCESS silently */ - PJ_UNUSED_ARG(key); - return PJ_SUCCESS; + /* Not supported, just return PJ_SUCCESS silently */ + PJ_UNUSED_ARG(key); + return PJ_SUCCESS; } diff --git a/pjlib/src/pj/ioqueue_uwp.cpp b/pjlib/src/pj/ioqueue_uwp.cpp index a02832e9d2..81e9ec4e92 100644 --- a/pjlib/src/pj/ioqueue_uwp.cpp +++ b/pjlib/src/pj/ioqueue_uwp.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2016 Teluu Inc. (http://www.teluu.com) * @@ -46,15 +45,15 @@ struct pj_ioqueue_t { DECLARE_COMMON_IOQUEUE pj_thread_desc thread_desc[16]; - unsigned thread_cnt; + unsigned thread_cnt; }; #include "ioqueue_common_abs.c" static void ioqueue_remove_from_set2(pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - unsigned event_types) + pj_ioqueue_key_t *key, + unsigned event_types) { PJ_UNUSED_ARG(ioqueue); PJ_UNUSED_ARG(key); @@ -62,8 +61,8 @@ static void ioqueue_remove_from_set2(pj_ioqueue_t *ioqueue, } static void ioqueue_remove_from_set( pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - enum ioqueue_event_type event_type ) + pj_ioqueue_key_t *key, + enum ioqueue_event_type event_type ) { ioqueue_remove_from_set2(ioqueue, key, event_type); } @@ -71,14 +70,14 @@ static void ioqueue_remove_from_set( pj_ioqueue_t *ioqueue, static void start_next_read(pj_ioqueue_key_t *key) { if (key_has_pending_read(key)) { - PjUwpSocket *s = (PjUwpSocket*)key->fd; - struct read_operation *op; - op = (struct read_operation*)key->read_list.next; - - if (op->op == PJ_IOQUEUE_OP_RECV) - s->Recv(NULL, (pj_ssize_t*)&op->size); - else - s->RecvFrom(NULL, (pj_ssize_t*)&op->size, NULL); + PjUwpSocket *s = (PjUwpSocket*)key->fd; + struct read_operation *op; + op = (struct read_operation*)key->read_list.next; + + if (op->op == PJ_IOQUEUE_OP_RECV) + s->Recv(NULL, (pj_ssize_t*)&op->size); + else + s->RecvFrom(NULL, (pj_ssize_t*)&op->size, NULL); } } @@ -86,44 +85,44 @@ static void start_next_read(pj_ioqueue_key_t *key) static void start_next_write(pj_ioqueue_key_t *key) { if (key_has_pending_write(key)) { - PjUwpSocket *s = (PjUwpSocket*)key->fd; - struct write_operation *op; - op = (struct write_operation*)key->write_list.next; - - if (op->op == PJ_IOQUEUE_OP_SEND) - s->Send(op->buf, (pj_ssize_t*)&op->size); - else - s->SendTo(op->buf, (pj_ssize_t*)&op->size, &op->rmt_addr); + PjUwpSocket *s = (PjUwpSocket*)key->fd; + struct write_operation *op; + op = (struct write_operation*)key->write_list.next; + + if (op->op == PJ_IOQUEUE_OP_SEND) + s->Send(op->buf, (pj_ssize_t*)&op->size); + else + s->SendTo(op->buf, (pj_ssize_t*)&op->size, &op->rmt_addr); } } static void ioqueue_add_to_set2(pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - unsigned event_types ) + pj_ioqueue_key_t *key, + unsigned event_types ) { PJ_UNUSED_ARG(ioqueue); if (event_types & READABLE_EVENT) { - /* This is either recv, recvfrom, or accept, do nothing on accept */ - start_next_read(key); + /* This is either recv, recvfrom, or accept, do nothing on accept */ + start_next_read(key); } if (event_types & WRITEABLE_EVENT) { - /* This is either send, sendto, or connect, do nothing on connect */ - //start_next_write(key); + /* This is either send, sendto, or connect, do nothing on connect */ + //start_next_write(key); } } static void ioqueue_add_to_set( pj_ioqueue_t *ioqueue, pj_ioqueue_key_t *key, - enum ioqueue_event_type event_type ) + enum ioqueue_event_type event_type ) { ioqueue_add_to_set2(ioqueue, key, event_type); } static void check_thread(pj_ioqueue_t *ioq) { if (pj_thread_is_registered()) - return; + return; pj_thread_t *t; char tmp[16]; @@ -142,7 +141,7 @@ static void on_read(PjUwpSocket *s, int bytes_read) ioqueue_dispatch_read_event(key->ioqueue, key); if (bytes_read > 0) - start_next_read(key); + start_next_read(key); } static void on_write(PjUwpSocket *s, int bytes_sent) @@ -201,7 +200,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, */ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, pj_size_t max_fd, - const pj_ioqueue_cfg *cfg, + const pj_ioqueue_cfg *cfg, pj_ioqueue_t **p_ioqueue) { pj_ioqueue_t *ioq; @@ -213,18 +212,18 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, ioq = PJ_POOL_ZALLOC_T(pool, pj_ioqueue_t); if (cfg) - pj_memcpy(&ioq->cfg, cfg, sizeof(*cfg)); + pj_memcpy(&ioq->cfg, cfg, sizeof(*cfg)); else - pj_ioqueue_cfg_default(&ioq->cfg); + pj_ioqueue_cfg_default(&ioq->cfg); /* Create and init ioqueue mutex */ rc = pj_lock_create_null_mutex(pool, "ioq%p", &lock); if (rc != PJ_SUCCESS) - return rc; + return rc; rc = pj_ioqueue_set_lock(ioq, lock, PJ_TRUE); if (rc != PJ_SUCCESS) - return rc; + return rc; PJ_LOG(4, ("pjlib", "uwp I/O Queue created (%p)", ioq)); @@ -246,26 +245,26 @@ PJ_DEF(pj_status_t) pj_ioqueue_destroy( pj_ioqueue_t *ioq ) * Register a socket to the I/O queue framework. */ PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, - pj_ioqueue_t *ioqueue, - pj_sock_t sock, - void *user_data, - const pj_ioqueue_callback *cb, + pj_ioqueue_t *ioqueue, + pj_sock_t sock, + void *user_data, + const pj_ioqueue_callback *cb, pj_ioqueue_key_t **p_key ) { return pj_ioqueue_register_sock2(pool, ioqueue, sock, NULL, user_data, - cb, p_key); + cb, p_key); } PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, - pj_ioqueue_t *ioqueue, - pj_sock_t sock, - pj_grp_lock_t *grp_lock, - void *user_data, - const pj_ioqueue_callback *cb, + pj_ioqueue_t *ioqueue, + pj_sock_t sock, + pj_grp_lock_t *grp_lock, + void *user_data, + const pj_ioqueue_callback *cb, pj_ioqueue_key_t **p_key) { PjUwpSocketCallback uwp_cb = - { &on_read, &on_write, &on_accept, &on_connect }; + { &on_read, &on_write, &on_accept, &on_connect }; pj_ioqueue_key_t *key; pj_status_t rc; @@ -274,17 +273,17 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, key = PJ_POOL_ZALLOC_T(pool, pj_ioqueue_key_t); rc = ioqueue_init_key(pool, ioqueue, key, sock, grp_lock, user_data, cb); if (rc != PJ_SUCCESS) { - key = NULL; - goto on_return; + key = NULL; + goto on_return; } /* Create ioqueue key lock, if not yet */ if (!key->lock) { - rc = pj_lock_create_simple_mutex(pool, NULL, &key->lock); - if (rc != PJ_SUCCESS) { - key = NULL; - goto on_return; - } + rc = pj_lock_create_simple_mutex(pool, NULL, &key->lock); + if (rc != PJ_SUCCESS) { + key = NULL; + goto on_return; + } } PjUwpSocket *s = (PjUwpSocket*)sock; @@ -292,8 +291,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, on_return: if (rc != PJ_SUCCESS) { - if (key && key->grp_lock) - pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0); + if (key && key->grp_lock) + pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0); } *p_key = key; pj_lock_release(ioqueue->lock); @@ -334,11 +333,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key ) pj_lock_release(ioqueue->lock); if (key->grp_lock) { - pj_grp_lock_t *grp_lock = key->grp_lock; - pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); - pj_grp_lock_release(grp_lock); + pj_grp_lock_t *grp_lock = key->grp_lock; + pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); + pj_grp_lock_release(grp_lock); } else { - pj_ioqueue_unlock_key(key); + pj_ioqueue_unlock_key(key); } pj_lock_destroy(key->lock); @@ -351,7 +350,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key ) * Poll the I/O Queue for completed events. */ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioq, - const pj_time_val *timeout) + const pj_time_val *timeout) { /* Polling is not necessary on UWP, since each socket handles * its events already. diff --git a/pjlib/src/pj/ioqueue_winnt.c b/pjlib/src/pj/ioqueue_winnt.c index e0a4441d9c..17662b3519 100644 --- a/pjlib/src/pj/ioqueue_winnt.c +++ b/pjlib/src/pj/ioqueue_winnt.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,11 +43,11 @@ /* The address specified in AcceptEx() must be 16 more than the size of * SOCKADDR (source: MSDN). */ -#define ACCEPT_ADDR_LEN (sizeof(pj_sockaddr_in)+16) +#define ACCEPT_ADDR_LEN (sizeof(pj_sockaddr_in)+16) typedef struct generic_overlapped { - WSAOVERLAPPED overlapped; + WSAOVERLAPPED overlapped; pj_ioqueue_operation_e operation; } generic_overlapped; @@ -57,9 +56,9 @@ typedef struct generic_overlapped */ typedef struct ioqueue_overlapped { - WSAOVERLAPPED overlapped; + WSAOVERLAPPED overlapped; pj_ioqueue_operation_e operation; - WSABUF wsabuf; + WSABUF wsabuf; pj_sockaddr_in dummy_addr; int dummy_addrlen; } ioqueue_overlapped; @@ -70,14 +69,14 @@ typedef struct ioqueue_overlapped */ typedef struct ioqueue_accept_rec { - WSAOVERLAPPED overlapped; + WSAOVERLAPPED overlapped; pj_ioqueue_operation_e operation; - pj_sock_t newsock; - pj_sock_t *newsock_ptr; - int *addrlen; - void *remote; - void *local; - char accept_buf[2 * ACCEPT_ADDR_LEN]; + pj_sock_t newsock; + pj_sock_t *newsock_ptr; + int *addrlen; + void *remote; + void *local; + char accept_buf[2 * ACCEPT_ADDR_LEN]; } ioqueue_accept_rec; #endif @@ -111,21 +110,21 @@ struct pj_ioqueue_key_t PJ_DECL_LIST_MEMBER(struct pj_ioqueue_key_t); pj_ioqueue_t *ioqueue; - HANDLE hnd; - void *user_data; + HANDLE hnd; + void *user_data; enum handle_type hnd_type; - pj_ioqueue_callback cb; - pj_bool_t allow_concurrent; + pj_ioqueue_callback cb; + pj_bool_t allow_concurrent; #if PJ_HAS_TCP - int connecting; + int connecting; #endif #if PJ_IOQUEUE_HAS_SAFE_UNREG - pj_atomic_t *ref_count; - pj_bool_t closing; - pj_time_val free_time; - pj_mutex_t *mutex; + pj_atomic_t *ref_count; + pj_bool_t closing; + pj_time_val free_time; + pj_mutex_t *mutex; #endif }; @@ -136,10 +135,10 @@ struct pj_ioqueue_key_t struct pj_ioqueue_t { pj_ioqueue_cfg cfg; - HANDLE iocp; + HANDLE iocp; pj_lock_t *lock; pj_bool_t auto_delete_lock; - pj_bool_t default_concurrency; + pj_bool_t default_concurrency; #if PJ_IOQUEUE_HAS_SAFE_UNREG pj_ioqueue_key_t active_list; @@ -149,10 +148,10 @@ struct pj_ioqueue_t /* These are to keep track of connecting sockets */ #if PJ_HAS_TCP - unsigned event_count; - HANDLE event_pool[MAXIMUM_WAIT_OBJECTS+1]; - unsigned connecting_count; - HANDLE connecting_handles[MAXIMUM_WAIT_OBJECTS+1]; + unsigned event_count; + HANDLE event_pool[MAXIMUM_WAIT_OBJECTS+1]; + unsigned connecting_count; + HANDLE connecting_handles[MAXIMUM_WAIT_OBJECTS+1]; pj_ioqueue_key_t *connecting_keys[MAXIMUM_WAIT_OBJECTS+1]; #endif }; @@ -191,29 +190,29 @@ static void ioqueue_on_accept_complete(pj_ioqueue_key_t *key, /* Operation complete immediately. */ if (accept_overlapped->addrlen) { - GetAcceptExSockaddrs( accept_overlapped->accept_buf, - 0, - ACCEPT_ADDR_LEN, - ACCEPT_ADDR_LEN, - &local, - &locallen, - &remote, - &remotelen); - if (*accept_overlapped->addrlen >= locallen) { - if (accept_overlapped->local) - pj_memcpy(accept_overlapped->local, local, locallen); - if (accept_overlapped->remote) - pj_memcpy(accept_overlapped->remote, remote, locallen); - } else { - if (accept_overlapped->local) - pj_bzero(accept_overlapped->local, - *accept_overlapped->addrlen); - if (accept_overlapped->remote) - pj_bzero(accept_overlapped->remote, - *accept_overlapped->addrlen); - } - - *accept_overlapped->addrlen = locallen; + GetAcceptExSockaddrs( accept_overlapped->accept_buf, + 0, + ACCEPT_ADDR_LEN, + ACCEPT_ADDR_LEN, + &local, + &locallen, + &remote, + &remotelen); + if (*accept_overlapped->addrlen >= locallen) { + if (accept_overlapped->local) + pj_memcpy(accept_overlapped->local, local, locallen); + if (accept_overlapped->remote) + pj_memcpy(accept_overlapped->remote, remote, locallen); + } else { + if (accept_overlapped->local) + pj_bzero(accept_overlapped->local, + *accept_overlapped->addrlen); + if (accept_overlapped->remote) + pj_bzero(accept_overlapped->remote, + *accept_overlapped->addrlen); + } + + *accept_overlapped->addrlen = locallen; } if (accept_overlapped->newsock_ptr) *accept_overlapped->newsock_ptr = accept_overlapped->newsock; @@ -227,9 +226,9 @@ static void erase_connecting_socket( pj_ioqueue_t *ioqueue, unsigned pos) /* Remove key from array of connecting handles. */ pj_array_erase(ioqueue->connecting_keys, sizeof(key), - ioqueue->connecting_count, pos); + ioqueue->connecting_count, pos); pj_array_erase(ioqueue->connecting_handles, sizeof(HANDLE), - ioqueue->connecting_count, pos); + ioqueue->connecting_count, pos); --ioqueue->connecting_count; /* Disassociate the socket from the event. */ @@ -237,13 +236,13 @@ static void erase_connecting_socket( pj_ioqueue_t *ioqueue, unsigned pos) /* Put event object to pool. */ if (ioqueue->event_count < MAXIMUM_WAIT_OBJECTS) { - ioqueue->event_pool[ioqueue->event_count++] = hEvent; + ioqueue->event_pool[ioqueue->event_count++] = hEvent; } else { - /* Shouldn't happen. There should be no more pending connections - * than max. - */ - pj_assert(0); - CloseHandle(hEvent); + /* Shouldn't happen. There should be no more pending connections + * than max. + */ + pj_assert(0); + CloseHandle(hEvent); } } @@ -258,54 +257,54 @@ static void erase_connecting_socket( pj_ioqueue_t *ioqueue, unsigned pos) static int check_connecting( pj_ioqueue_t *ioqueue ) { if (ioqueue->connecting_count) { - int i, count; - struct - { - pj_ioqueue_key_t *key; - pj_status_t status; - } events[PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL-1]; - - pj_lock_acquire(ioqueue->lock); - for (count=0; countconnecting_count, - ioqueue->connecting_handles, - FALSE, 0); - if (result >= WAIT_OBJECT_0 && - result < WAIT_OBJECT_0+ioqueue->connecting_count) - { - WSANETWORKEVENTS net_events; - - /* Got completed connect(). */ - unsigned pos = result - WAIT_OBJECT_0; - events[count].key = ioqueue->connecting_keys[pos]; - - /* See whether connect has succeeded. */ - WSAEnumNetworkEvents((pj_sock_t)events[count].key->hnd, - ioqueue->connecting_handles[pos], - &net_events); - events[count].status = - PJ_STATUS_FROM_OS(net_events.iErrorCode[FD_CONNECT_BIT]); - - /* Erase socket from pending connect. */ - erase_connecting_socket(ioqueue, pos); - } else { - /* No more events */ - break; - } - } - pj_lock_release(ioqueue->lock); - - /* Call callbacks. */ - for (i=0; icb.on_connect_complete) { - events[i].key->cb.on_connect_complete(events[i].key, - events[i].status); - } - } - - return count; + int i, count; + struct + { + pj_ioqueue_key_t *key; + pj_status_t status; + } events[PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL-1]; + + pj_lock_acquire(ioqueue->lock); + for (count=0; countconnecting_count, + ioqueue->connecting_handles, + FALSE, 0); + if (result >= WAIT_OBJECT_0 && + result < WAIT_OBJECT_0+ioqueue->connecting_count) + { + WSANETWORKEVENTS net_events; + + /* Got completed connect(). */ + unsigned pos = result - WAIT_OBJECT_0; + events[count].key = ioqueue->connecting_keys[pos]; + + /* See whether connect has succeeded. */ + WSAEnumNetworkEvents((pj_sock_t)events[count].key->hnd, + ioqueue->connecting_handles[pos], + &net_events); + events[count].status = + PJ_STATUS_FROM_OS(net_events.iErrorCode[FD_CONNECT_BIT]); + + /* Erase socket from pending connect. */ + erase_connecting_socket(ioqueue, pos); + } else { + /* No more events */ + break; + } + } + pj_lock_release(ioqueue->lock); + + /* Call callbacks. */ + for (i=0; icb.on_connect_complete) { + events[i].key->cb.on_connect_complete(events[i].key, + events[i].status); + } + } + + return count; } return 0; @@ -336,7 +335,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, */ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, pj_size_t max_fd, - const pj_ioqueue_cfg *cfg, + const pj_ioqueue_cfg *cfg, pj_ioqueue_t **p_ioqueue) { pj_ioqueue_t *ioqueue; @@ -355,19 +354,19 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, /* Create IOCP */ ioqueue = pj_pool_zalloc(pool, sizeof(*ioqueue)); if (cfg) - pj_memcpy(&ioqueue->cfg, cfg, sizeof(*cfg)); + pj_memcpy(&ioqueue->cfg, cfg, sizeof(*cfg)); else - pj_ioqueue_cfg_default(&ioqueue->cfg); + pj_ioqueue_cfg_default(&ioqueue->cfg); ioqueue->iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); if (ioqueue->iocp == NULL) - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); /* Create IOCP mutex */ rc = pj_lock_create_recursive_mutex(pool, NULL, &ioqueue->lock); if (rc != PJ_SUCCESS) { - CloseHandle(ioqueue->iocp); - return rc; + CloseHandle(ioqueue->iocp); + return rc; } ioqueue->auto_delete_lock = PJ_TRUE; @@ -385,36 +384,36 @@ PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool, * in free_list. */ for (i=0; iref_count); - if (rc != PJ_SUCCESS) { - key = ioqueue->free_list.next; - while (key != &ioqueue->free_list) { - pj_atomic_destroy(key->ref_count); - pj_mutex_destroy(key->mutex); - key = key->next; - } - CloseHandle(ioqueue->iocp); - return rc; - } - - rc = pj_mutex_create_recursive(pool, "ioqkey", &key->mutex); - if (rc != PJ_SUCCESS) { - pj_atomic_destroy(key->ref_count); - key = ioqueue->free_list.next; - while (key != &ioqueue->free_list) { - pj_atomic_destroy(key->ref_count); - pj_mutex_destroy(key->mutex); - key = key->next; - } - CloseHandle(ioqueue->iocp); - return rc; - } - - pj_list_push_back(&ioqueue->free_list, key); + pj_ioqueue_key_t *key; + + key = pj_pool_alloc(pool, sizeof(pj_ioqueue_key_t)); + + rc = pj_atomic_create(pool, 0, &key->ref_count); + if (rc != PJ_SUCCESS) { + key = ioqueue->free_list.next; + while (key != &ioqueue->free_list) { + pj_atomic_destroy(key->ref_count); + pj_mutex_destroy(key->mutex); + key = key->next; + } + CloseHandle(ioqueue->iocp); + return rc; + } + + rc = pj_mutex_create_recursive(pool, "ioqkey", &key->mutex); + if (rc != PJ_SUCCESS) { + pj_atomic_destroy(key->ref_count); + key = ioqueue->free_list.next; + while (key != &ioqueue->free_list) { + pj_atomic_destroy(key->ref_count); + pj_mutex_destroy(key->mutex); + key = key->next; + } + CloseHandle(ioqueue->iocp); + return rc; + } + + pj_list_push_back(&ioqueue->free_list, key); } #endif @@ -442,35 +441,35 @@ PJ_DEF(pj_status_t) pj_ioqueue_destroy( pj_ioqueue_t *ioqueue ) #if PJ_HAS_TCP /* Destroy events in the pool */ for (i=0; ievent_count; ++i) { - CloseHandle(ioqueue->event_pool[i]); + CloseHandle(ioqueue->event_pool[i]); } ioqueue->event_count = 0; #endif if (CloseHandle(ioqueue->iocp) != TRUE) - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); #if PJ_IOQUEUE_HAS_SAFE_UNREG /* Destroy reference counters */ key = ioqueue->active_list.next; while (key != &ioqueue->active_list) { - pj_atomic_destroy(key->ref_count); - pj_mutex_destroy(key->mutex); - key = key->next; + pj_atomic_destroy(key->ref_count); + pj_mutex_destroy(key->mutex); + key = key->next; } key = ioqueue->closing_list.next; while (key != &ioqueue->closing_list) { - pj_atomic_destroy(key->ref_count); - pj_mutex_destroy(key->mutex); - key = key->next; + pj_atomic_destroy(key->ref_count); + pj_mutex_destroy(key->mutex); + key = key->next; } key = ioqueue->free_list.next; while (key != &ioqueue->free_list) { - pj_atomic_destroy(key->ref_count); - pj_mutex_destroy(key->mutex); - key = key->next; + pj_atomic_destroy(key->ref_count); + pj_mutex_destroy(key->mutex); + key = key->next; } #endif @@ -482,7 +481,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_destroy( pj_ioqueue_t *ioqueue ) PJ_DEF(pj_status_t) pj_ioqueue_set_default_concurrency(pj_ioqueue_t *ioqueue, - pj_bool_t allow) + pj_bool_t allow) { PJ_ASSERT_RETURN(ioqueue != NULL, PJ_EINVAL); ioqueue->default_concurrency = allow; @@ -493,8 +492,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_set_default_concurrency(pj_ioqueue_t *ioqueue, * pj_ioqueue_set_lock() */ PJ_DEF(pj_status_t) pj_ioqueue_set_lock( pj_ioqueue_t *ioqueue, - pj_lock_t *lock, - pj_bool_t auto_delete ) + pj_lock_t *lock, + pj_bool_t auto_delete ) { PJ_ASSERT_RETURN(ioqueue && lock, PJ_EINVAL); @@ -512,11 +511,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_set_lock( pj_ioqueue_t *ioqueue, * pj_ioqueue_register_sock() */ PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, - pj_ioqueue_t *ioqueue, - pj_sock_t sock, - void *user_data, - const pj_ioqueue_callback *cb, - pj_ioqueue_key_t **key ) + pj_ioqueue_t *ioqueue, + pj_sock_t sock, + void *user_data, + const pj_ioqueue_callback *cb, + pj_ioqueue_key_t **key ) { HANDLE hioq; pj_ioqueue_key_t *rec; @@ -537,8 +536,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, * the free list. */ if (pj_list_empty(&ioqueue->free_list)) { - pj_lock_release(ioqueue->lock); - return PJ_ETOOMANY; + pj_lock_release(ioqueue->lock); + return PJ_ETOOMANY; } rec = ioqueue->free_list.next; @@ -564,8 +563,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, /* Set concurrency for this handle */ rc = pj_ioqueue_set_concurrency(rec, ioqueue->default_concurrency); if (rc != PJ_SUCCESS) { - pj_lock_release(ioqueue->lock); - return rc; + pj_lock_release(ioqueue->lock); + return rc; } #if PJ_HAS_TCP @@ -576,15 +575,15 @@ PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, value = 1; rc = ioctlsocket(sock, FIONBIO, &value); if (rc != 0) { - pj_lock_release(ioqueue->lock); + pj_lock_release(ioqueue->lock); return PJ_RETURN_OS_ERROR(WSAGetLastError()); } /* Associate with IOCP */ hioq = CreateIoCompletionPort((HANDLE)sock, ioqueue->iocp, (DWORD)rec, 0); if (!hioq) { - pj_lock_release(ioqueue->lock); - return PJ_RETURN_OS_ERROR(GetLastError()); + pj_lock_release(ioqueue->lock); + return PJ_RETURN_OS_ERROR(GetLastError()); } *key = rec; @@ -633,17 +632,17 @@ static void decrement_counter(pj_ioqueue_key_t *key) { if (pj_atomic_dec_and_get(key->ref_count) == 0) { - pj_lock_acquire(key->ioqueue->lock); + pj_lock_acquire(key->ioqueue->lock); - pj_assert(key->closing == 1); - pj_gettickcount(&key->free_time); - key->free_time.msec += PJ_IOQUEUE_KEY_FREE_DELAY; - pj_time_val_normalize(&key->free_time); + pj_assert(key->closing == 1); + pj_gettickcount(&key->free_time); + key->free_time.msec += PJ_IOQUEUE_KEY_FREE_DELAY; + pj_time_val_normalize(&key->free_time); - pj_list_erase(key); - pj_list_push_back(&key->ioqueue->closing_list, key); + pj_list_erase(key); + pj_list_push_back(&key->ioqueue->closing_list, key); - pj_lock_release(key->ioqueue->lock); + pj_lock_release(key->ioqueue->lock); } } #endif @@ -653,7 +652,7 @@ static void decrement_counter(pj_ioqueue_key_t *key) * and return the key and bytes transferred of the last operation. */ static pj_bool_t poll_iocp( HANDLE hIocp, DWORD dwTimeout, - pj_ssize_t *p_bytes, pj_ioqueue_key_t **p_key ) + pj_ssize_t *p_bytes, pj_ioqueue_key_t **p_key ) { DWORD dwBytesTransferred, dwKey; generic_overlapped *pOv; @@ -663,8 +662,8 @@ static pj_bool_t poll_iocp( HANDLE hIocp, DWORD dwTimeout, /* Poll for completion status. */ rcGetQueued = GetQueuedCompletionStatus(hIocp, &dwBytesTransferred, - &dwKey, (OVERLAPPED**)&pOv, - dwTimeout); + &dwKey, (OVERLAPPED**)&pOv, + dwTimeout); /* The return value is: * - nonzero if event was dequeued. @@ -672,104 +671,104 @@ static pj_bool_t poll_iocp( HANDLE hIocp, DWORD dwTimeout, * - zero and pOv!=NULL if event for failed I/O was dequeued. */ if (pOv) { - pj_bool_t has_lock; + pj_bool_t has_lock; - /* Event was dequeued for either successfull or failed I/O */ - key = (pj_ioqueue_key_t*)dwKey; - size_status = dwBytesTransferred; + /* Event was dequeued for either successfull or failed I/O */ + key = (pj_ioqueue_key_t*)dwKey; + size_status = dwBytesTransferred; - /* Report to caller regardless */ - if (p_bytes) - *p_bytes = size_status; - if (p_key) - *p_key = key; + /* Report to caller regardless */ + if (p_bytes) + *p_bytes = size_status; + if (p_key) + *p_key = key; #if PJ_IOQUEUE_HAS_SAFE_UNREG - /* We shouldn't call callbacks if key is quitting. */ - if (key->closing) - return PJ_TRUE; - - /* If concurrency is disabled, lock the key - * (and save the lock status to local var since app may change - * concurrency setting while in the callback) */ - if (key->allow_concurrent == PJ_FALSE) { - pj_mutex_lock(key->mutex); - has_lock = PJ_TRUE; - } else { - has_lock = PJ_FALSE; - } - - /* Now that we get the lock, check again that key is not closing */ - if (key->closing) { - if (has_lock) { - pj_mutex_unlock(key->mutex); - } - return PJ_TRUE; - } - - /* Increment reference counter to prevent this key from being - * deleted - */ - pj_atomic_inc(key->ref_count); + /* We shouldn't call callbacks if key is quitting. */ + if (key->closing) + return PJ_TRUE; + + /* If concurrency is disabled, lock the key + * (and save the lock status to local var since app may change + * concurrency setting while in the callback) */ + if (key->allow_concurrent == PJ_FALSE) { + pj_mutex_lock(key->mutex); + has_lock = PJ_TRUE; + } else { + has_lock = PJ_FALSE; + } + + /* Now that we get the lock, check again that key is not closing */ + if (key->closing) { + if (has_lock) { + pj_mutex_unlock(key->mutex); + } + return PJ_TRUE; + } + + /* Increment reference counter to prevent this key from being + * deleted + */ + pj_atomic_inc(key->ref_count); #else - PJ_UNUSED_ARG(has_lock); + PJ_UNUSED_ARG(has_lock); #endif - /* Carry out the callback */ - switch (pOv->operation) { - case PJ_IOQUEUE_OP_READ: - case PJ_IOQUEUE_OP_RECV: - case PJ_IOQUEUE_OP_RECV_FROM: + /* Carry out the callback */ + switch (pOv->operation) { + case PJ_IOQUEUE_OP_READ: + case PJ_IOQUEUE_OP_RECV: + case PJ_IOQUEUE_OP_RECV_FROM: pOv->operation = 0; if (key->cb.on_read_complete) - key->cb.on_read_complete(key, (pj_ioqueue_op_key_t*)pOv, + key->cb.on_read_complete(key, (pj_ioqueue_op_key_t*)pOv, size_status); - break; - case PJ_IOQUEUE_OP_WRITE: - case PJ_IOQUEUE_OP_SEND: - case PJ_IOQUEUE_OP_SEND_TO: + break; + case PJ_IOQUEUE_OP_WRITE: + case PJ_IOQUEUE_OP_SEND: + case PJ_IOQUEUE_OP_SEND_TO: pOv->operation = 0; if (key->cb.on_write_complete) - key->cb.on_write_complete(key, (pj_ioqueue_op_key_t*)pOv, + key->cb.on_write_complete(key, (pj_ioqueue_op_key_t*)pOv, size_status); - break; + break; #if PJ_HAS_TCP - case PJ_IOQUEUE_OP_ACCEPT: - /* special case for accept. */ - ioqueue_on_accept_complete(key, (ioqueue_accept_rec*)pOv); + case PJ_IOQUEUE_OP_ACCEPT: + /* special case for accept. */ + ioqueue_on_accept_complete(key, (ioqueue_accept_rec*)pOv); if (key->cb.on_accept_complete) { ioqueue_accept_rec *accept_rec = (ioqueue_accept_rec*)pOv; - pj_status_t status = PJ_SUCCESS; - pj_sock_t newsock; + pj_status_t status = PJ_SUCCESS; + pj_sock_t newsock; - newsock = accept_rec->newsock; - accept_rec->newsock = PJ_INVALID_SOCKET; + newsock = accept_rec->newsock; + accept_rec->newsock = PJ_INVALID_SOCKET; - if (newsock == PJ_INVALID_SOCKET) { - int dwError = WSAGetLastError(); - if (dwError == 0) dwError = OSERR_ENOTCONN; - status = PJ_RETURN_OS_ERROR(dwError); - } + if (newsock == PJ_INVALID_SOCKET) { + int dwError = WSAGetLastError(); + if (dwError == 0) dwError = OSERR_ENOTCONN; + status = PJ_RETURN_OS_ERROR(dwError); + } - key->cb.on_accept_complete(key, (pj_ioqueue_op_key_t*)pOv, + key->cb.on_accept_complete(key, (pj_ioqueue_op_key_t*)pOv, newsock, status); - + } - break; - case PJ_IOQUEUE_OP_CONNECT: + break; + case PJ_IOQUEUE_OP_CONNECT: #endif - case PJ_IOQUEUE_OP_NONE: - pj_assert(0); - break; - } + case PJ_IOQUEUE_OP_NONE: + pj_assert(0); + break; + } #if PJ_IOQUEUE_HAS_SAFE_UNREG - decrement_counter(key); - if (has_lock) - pj_mutex_unlock(key->mutex); + decrement_counter(key); + if (has_lock) + pj_mutex_unlock(key->mutex); #endif - return PJ_TRUE; + return PJ_TRUE; } /* No event was queued. */ @@ -789,21 +788,21 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key ) #if PJ_HAS_TCP if (key->connecting) { - unsigned pos; + unsigned pos; pj_ioqueue_t *ioqueue; ioqueue = key->ioqueue; - /* Erase from connecting_handles */ - pj_lock_acquire(ioqueue->lock); - for (pos=0; pos < ioqueue->connecting_count; ++pos) { - if (ioqueue->connecting_keys[pos] == key) { - erase_connecting_socket(ioqueue, pos); - break; - } - } - key->connecting = 0; - pj_lock_release(ioqueue->lock); + /* Erase from connecting_handles */ + pj_lock_acquire(ioqueue->lock); + for (pos=0; pos < ioqueue->connecting_count; ++pos) { + if (ioqueue->connecting_keys[pos] == key) { + erase_connecting_socket(ioqueue, pos); + break; + } + } + key->connecting = 0; + pj_lock_release(ioqueue->lock); } #endif @@ -815,10 +814,10 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key ) * processing the callback */ if (key->allow_concurrent == PJ_FALSE) { - pj_mutex_lock(key->mutex); - has_lock = PJ_TRUE; + pj_mutex_lock(key->mutex); + has_lock = PJ_TRUE; } else { - has_lock = PJ_FALSE; + has_lock = PJ_FALSE; } #else PJ_UNUSED_ARG(has_lock); @@ -859,7 +858,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key ) * an ugly solution.. * * Update 2008/02/13: - * This should not happen if concurrency is disallowed for the key. + * This should not happen if concurrency is disallowed for the key. * So at least application has a solution for this (i.e. by disallowing * concurrency in the key). */ @@ -867,15 +866,15 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key ) //Doing this with RETRY I think should solve the IOCP setting the //socket signalled, without causing the deadlock. //while (pj_atomic_get(key->ref_count) != 1) - // pj_thread_sleep(0); + // pj_thread_sleep(0); for (i=0; pj_atomic_get(key->ref_count) != 1 && imutex); + pj_mutex_unlock(key->mutex); #endif return PJ_SUCCESS; @@ -888,26 +887,26 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key ) static void scan_closing_keys(pj_ioqueue_t *ioqueue) { if (!pj_list_empty(&ioqueue->closing_list)) { - pj_time_val now; - pj_ioqueue_key_t *key; - - pj_gettickcount(&now); - - /* Move closing keys to free list when they've finished the closing - * idle time. - */ - key = ioqueue->closing_list.next; - while (key != &ioqueue->closing_list) { - pj_ioqueue_key_t *next = key->next; - - pj_assert(key->closing != 0); - - if (PJ_TIME_VAL_GTE(now, key->free_time)) { - pj_list_erase(key); - pj_list_push_back(&ioqueue->free_list, key); - } - key = next; - } + pj_time_val now; + pj_ioqueue_key_t *key; + + pj_gettickcount(&now); + + /* Move closing keys to free list when they've finished the closing + * idle time. + */ + key = ioqueue->closing_list.next; + while (key != &ioqueue->closing_list) { + pj_ioqueue_key_t *next = key->next; + + pj_assert(key->closing != 0); + + if (PJ_TIME_VAL_GTE(now, key->free_time)) { + pj_list_erase(key); + pj_list_push_back(&ioqueue->free_list, key); + } + key = next; + } } } #endif @@ -936,9 +935,9 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) #if PJ_HAS_TCP /* Check the connecting array, only when there's no activity. */ if (event_count == 0) { - connect_count = check_connecting(ioqueue); - if (connect_count > 0) - event_count += connect_count; + connect_count = check_connecting(ioqueue); + if (connect_count > 0) + event_count += connect_count; } #endif @@ -947,9 +946,9 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) * pending closing keys. */ if (event_count == 0 && !pj_list_empty(&ioqueue->closing_list)) { - pj_lock_acquire(ioqueue->lock); - scan_closing_keys(ioqueue); - pj_lock_release(ioqueue->lock); + pj_lock_acquire(ioqueue->lock); + scan_closing_keys(ioqueue); + pj_lock_release(ioqueue->lock); } #endif @@ -964,9 +963,9 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) */ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - void *buffer, - pj_ssize_t *length, - pj_uint32_t flags ) + void *buffer, + pj_ssize_t *length, + pj_uint32_t flags ) { /* * Ideally we should just call pj_ioqueue_recvfrom() with NULL addr and @@ -984,7 +983,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, #if PJ_IOQUEUE_HAS_SAFE_UNREG /* Check key is not closing */ if (key->closing) - return PJ_ECANCELLED; + return PJ_ECANCELLED; #endif op_key_rec = (union operation_key*)op_key->internal__; @@ -997,18 +996,18 @@ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, * immediately available. */ if ((flags & PJ_IOQUEUE_ALWAYS_ASYNC) == 0) { - rc = WSARecv((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1, - &bytesRead, &dwFlags, NULL, NULL); - if (rc == 0) { - *length = bytesRead; - return PJ_SUCCESS; - } else { - DWORD dwError = WSAGetLastError(); - if (dwError != WSAEWOULDBLOCK) { - *length = -1; - return PJ_RETURN_OS_ERROR(dwError); - } - } + rc = WSARecv((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1, + &bytesRead, &dwFlags, NULL, NULL); + if (rc == 0) { + *length = bytesRead; + return PJ_SUCCESS; + } else { + DWORD dwError = WSAGetLastError(); + if (dwError != WSAEWOULDBLOCK) { + *length = -1; + return PJ_RETURN_OS_ERROR(dwError); + } + } } dwFlags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC); @@ -1023,9 +1022,9 @@ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, rc = WSARecv((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1, &bytesRead, &dwFlags, - &op_key_rec->overlapped.overlapped, NULL); + &op_key_rec->overlapped.overlapped, NULL); if (rc == SOCKET_ERROR) { - DWORD dwStatus = WSAGetLastError(); + DWORD dwStatus = WSAGetLastError(); if (dwStatus!=WSA_IO_PENDING) { *length = -1; return PJ_STATUS_FROM_OS(dwStatus); @@ -1043,11 +1042,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, */ PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - void *buffer, - pj_ssize_t *length, + void *buffer, + pj_ssize_t *length, pj_uint32_t flags, - pj_sockaddr_t *addr, - int *addrlen) + pj_sockaddr_t *addr, + int *addrlen) { int rc; DWORD bytesRead; @@ -1060,7 +1059,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, #if PJ_IOQUEUE_HAS_SAFE_UNREG /* Check key is not closing */ if (key->closing) - return PJ_ECANCELLED; + return PJ_ECANCELLED; #endif op_key_rec = (union operation_key*)op_key->internal__; @@ -1073,18 +1072,18 @@ PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, * immediately available. */ if ((flags & PJ_IOQUEUE_ALWAYS_ASYNC) == 0) { - rc = WSARecvFrom((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1, - &bytesRead, &dwFlags, addr, addrlen, NULL, NULL); - if (rc == 0) { - *length = bytesRead; - return PJ_SUCCESS; - } else { - DWORD dwError = WSAGetLastError(); - if (dwError != WSAEWOULDBLOCK) { - *length = -1; - return PJ_RETURN_OS_ERROR(dwError); - } - } + rc = WSARecvFrom((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1, + &bytesRead, &dwFlags, addr, addrlen, NULL, NULL); + if (rc == 0) { + *length = bytesRead; + return PJ_SUCCESS; + } else { + DWORD dwError = WSAGetLastError(); + if (dwError != WSAEWOULDBLOCK) { + *length = -1; + return PJ_RETURN_OS_ERROR(dwError); + } + } } dwFlags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC); @@ -1099,9 +1098,9 @@ PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, rc = WSARecvFrom((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1, &bytesRead, &dwFlags, addr, addrlen, - &op_key_rec->overlapped.overlapped, NULL); + &op_key_rec->overlapped.overlapped, NULL); if (rc == SOCKET_ERROR) { - DWORD dwStatus = WSAGetLastError(); + DWORD dwStatus = WSAGetLastError(); if (dwStatus!=WSA_IO_PENDING) { *length = -1; return PJ_STATUS_FROM_OS(dwStatus); @@ -1119,9 +1118,9 @@ PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, */ PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - const void *data, - pj_ssize_t *length, - pj_uint32_t flags ) + const void *data, + pj_ssize_t *length, + pj_uint32_t flags ) { return pj_ioqueue_sendto(key, op_key, data, length, flags, NULL, 0); } @@ -1134,11 +1133,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, */ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - const void *data, - pj_ssize_t *length, + const void *data, + pj_ssize_t *length, pj_uint32_t flags, - const pj_sockaddr_t *addr, - int addrlen) + const pj_sockaddr_t *addr, + int addrlen) { int rc; DWORD bytesWritten; @@ -1151,7 +1150,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, #if PJ_IOQUEUE_HAS_SAFE_UNREG /* Check key is not closing */ if (key->closing) - return PJ_ECANCELLED; + return PJ_ECANCELLED; #endif op_key_rec = (union operation_key*)op_key->internal__; @@ -1165,19 +1164,19 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, dwFlags = flags; if ((flags & PJ_IOQUEUE_ALWAYS_ASYNC) == 0) { - rc = WSASendTo((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1, - &bytesWritten, dwFlags, addr, addrlen, - NULL, NULL); - if (rc == 0) { - *length = bytesWritten; - return PJ_SUCCESS; - } else { - DWORD dwStatus = WSAGetLastError(); - if (dwStatus != WSAEWOULDBLOCK) { - *length = -1; - return PJ_RETURN_OS_ERROR(dwStatus); - } - } + rc = WSASendTo((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1, + &bytesWritten, dwFlags, addr, addrlen, + NULL, NULL); + if (rc == 0) { + *length = bytesWritten; + return PJ_SUCCESS; + } else { + DWORD dwStatus = WSAGetLastError(); + if (dwStatus != WSAEWOULDBLOCK) { + *length = -1; + return PJ_RETURN_OS_ERROR(dwStatus); + } + } } dwFlags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC); @@ -1192,9 +1191,9 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, rc = WSASendTo((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1, &bytesWritten, dwFlags, addr, addrlen, - &op_key_rec->overlapped.overlapped, NULL); + &op_key_rec->overlapped.overlapped, NULL); if (rc == SOCKET_ERROR) { - DWORD dwStatus = WSAGetLastError(); + DWORD dwStatus = WSAGetLastError(); if (dwStatus!=WSA_IO_PENDING) return PJ_STATUS_FROM_OS(dwStatus); } @@ -1212,10 +1211,10 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, */ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, - pj_sock_t *new_sock, - pj_sockaddr_t *local, - pj_sockaddr_t *remote, - int *addrlen) + pj_sock_t *new_sock, + pj_sockaddr_t *local, + pj_sockaddr_t *remote, + int *addrlen) { BOOL rc; DWORD bytesReceived; @@ -1229,7 +1228,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, #if PJ_IOQUEUE_HAS_SAFE_UNREG /* Check key is not closing */ if (key->closing) - return PJ_ECANCELLED; + return PJ_ECANCELLED; #endif /* @@ -1238,25 +1237,25 @@ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, sock = WSAAccept((SOCKET)key->hnd, remote, addrlen, NULL, 0); if (sock != INVALID_SOCKET) { /* Yes! New socket is available! */ - if (local && addrlen) { - int status; - - /* On WinXP or later, use SO_UPDATE_ACCEPT_CONTEXT so that socket - * addresses can be obtained with getsockname() and getpeername(). - */ - status = setsockopt(sock, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, - (char*)&key->hnd, sizeof(SOCKET)); - /* SO_UPDATE_ACCEPT_CONTEXT is for WinXP or later. - * So ignore the error status. - */ - - status = getsockname(sock, local, addrlen); - if (status != 0) { - DWORD dwError = WSAGetLastError(); - closesocket(sock); - return PJ_RETURN_OS_ERROR(dwError); - } - } + if (local && addrlen) { + int status; + + /* On WinXP or later, use SO_UPDATE_ACCEPT_CONTEXT so that socket + * addresses can be obtained with getsockname() and getpeername(). + */ + status = setsockopt(sock, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, + (char*)&key->hnd, sizeof(SOCKET)); + /* SO_UPDATE_ACCEPT_CONTEXT is for WinXP or later. + * So ignore the error status. + */ + + status = getsockname(sock, local, addrlen); + if (status != 0) { + DWORD dwError = WSAGetLastError(); + closesocket(sock); + return PJ_RETURN_OS_ERROR(dwError); + } + } *new_sock = sock; return PJ_SUCCESS; @@ -1277,7 +1276,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, status = pj_sock_socket(pj_AF_INET(), pj_SOCK_STREAM(), 0, &op_key_rec->accept.newsock); if (status != PJ_SUCCESS) - return status; + return status; op_key_rec->accept.operation = PJ_IOQUEUE_OP_ACCEPT; op_key_rec->accept.addrlen = addrlen; @@ -1285,20 +1284,20 @@ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, op_key_rec->accept.remote = remote; op_key_rec->accept.newsock_ptr = new_sock; pj_bzero( &op_key_rec->accept.overlapped, - sizeof(op_key_rec->accept.overlapped)); + sizeof(op_key_rec->accept.overlapped)); rc = AcceptEx( (SOCKET)key->hnd, (SOCKET)op_key_rec->accept.newsock, - op_key_rec->accept.accept_buf, - 0, ACCEPT_ADDR_LEN, ACCEPT_ADDR_LEN, - &bytesReceived, - &op_key_rec->accept.overlapped ); + op_key_rec->accept.accept_buf, + 0, ACCEPT_ADDR_LEN, ACCEPT_ADDR_LEN, + &bytesReceived, + &op_key_rec->accept.overlapped ); if (rc == TRUE) { - ioqueue_on_accept_complete(key, &op_key_rec->accept); - return PJ_SUCCESS; + ioqueue_on_accept_complete(key, &op_key_rec->accept); + return PJ_SUCCESS; } else { - DWORD dwStatus = WSAGetLastError(); - if (dwStatus!=WSA_IO_PENDING) + DWORD dwStatus = WSAGetLastError(); + if (dwStatus!=WSA_IO_PENDING) return PJ_STATUS_FROM_OS(dwStatus); } @@ -1314,8 +1313,8 @@ PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, * since there's no overlapped version of connect()). */ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, - const pj_sockaddr_t *addr, - int addrlen ) + const pj_sockaddr_t *addr, + int addrlen ) { HANDLE hEvent; pj_ioqueue_t *ioqueue; @@ -1326,19 +1325,19 @@ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, #if PJ_IOQUEUE_HAS_SAFE_UNREG /* Check key is not closing */ if (key->closing) - return PJ_ECANCELLED; + return PJ_ECANCELLED; #endif /* Initiate connect() */ if (connect((pj_sock_t)key->hnd, addr, addrlen) != 0) { - DWORD dwStatus; - dwStatus = WSAGetLastError(); + DWORD dwStatus; + dwStatus = WSAGetLastError(); if (dwStatus != WSAEWOULDBLOCK) { - return PJ_RETURN_OS_ERROR(dwStatus); - } + return PJ_RETURN_OS_ERROR(dwStatus); + } } else { - /* Connect has completed immediately! */ - return PJ_SUCCESS; + /* Connect has completed immediately! */ + return PJ_SUCCESS; } ioqueue = key->ioqueue; @@ -1347,21 +1346,21 @@ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, pj_lock_acquire(ioqueue->lock); if (ioqueue->connecting_count >= MAXIMUM_WAIT_OBJECTS) { - pj_lock_release(ioqueue->lock); - return PJ_ETOOMANYCONN; + pj_lock_release(ioqueue->lock); + return PJ_ETOOMANYCONN; } /* Get or create event object. */ if (ioqueue->event_count) { - hEvent = ioqueue->event_pool[ioqueue->event_count - 1]; - --ioqueue->event_count; + hEvent = ioqueue->event_pool[ioqueue->event_count - 1]; + --ioqueue->event_count; } else { - hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - if (hEvent == NULL) { - DWORD dwStatus = GetLastError(); - pj_lock_release(ioqueue->lock); - return PJ_STATUS_FROM_OS(dwStatus); - } + hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + if (hEvent == NULL) { + DWORD dwStatus = GetLastError(); + pj_lock_release(ioqueue->lock); + return PJ_STATUS_FROM_OS(dwStatus); + } } /* Mark key as connecting. @@ -1371,9 +1370,9 @@ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, /* Associate socket events to the event object. */ if (WSAEventSelect((pj_sock_t)key->hnd, hEvent, FD_CONNECT) != 0) { - CloseHandle(hEvent); - pj_lock_release(ioqueue->lock); - return PJ_RETURN_OS_ERROR(WSAGetLastError()); + CloseHandle(hEvent); + pj_lock_release(ioqueue->lock); + return PJ_RETURN_OS_ERROR(WSAGetLastError()); } /* Add to array. */ @@ -1385,11 +1384,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, return PJ_EPENDING; } -#endif /* #if PJ_HAS_TCP */ +#endif /* #if PJ_HAS_TCP */ PJ_DEF(void) pj_ioqueue_op_key_init( pj_ioqueue_op_key_t *op_key, - pj_size_t size ) + pj_size_t size ) { pj_bzero(op_key, size); } @@ -1427,7 +1426,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_post_completion( pj_ioqueue_key_t *key, } PJ_DEF(pj_status_t) pj_ioqueue_set_concurrency(pj_ioqueue_key_t *key, - pj_bool_t allow) + pj_bool_t allow) { PJ_ASSERT_RETURN(key, PJ_EINVAL); diff --git a/pjlib/src/pj/ip_helper_generic.c b/pjlib/src/pj/ip_helper_generic.c index 28f3c6bdcf..478c6b12f6 100644 --- a/pjlib/src/pj/ip_helper_generic.c +++ b/pjlib/src/pj/ip_helper_generic.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,22 +38,22 @@ /* Set to 1 to enable tracing */ #if 0 # include -# define THIS_FILE "ip_helper_generic.c" -# define TRACE_(exp) PJ_LOG(5,exp) +# define THIS_FILE "ip_helper_generic.c" +# define TRACE_(exp) PJ_LOG(5,exp) static const char *get_os_errmsg(void) { - static char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(pj_get_os_error(), errmsg, sizeof(errmsg)); - return errmsg; + static char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(pj_get_os_error(), errmsg, sizeof(errmsg)); + return errmsg; } static const char *get_addr(void *addr) { - static char txt[PJ_INET6_ADDRSTRLEN]; - struct sockaddr *ad = (struct sockaddr*)addr; - if (ad->sa_family != PJ_AF_INET && ad->sa_family != PJ_AF_INET6) - return "?"; - return pj_inet_ntop2(ad->sa_family, pj_sockaddr_get_addr(ad), - txt, sizeof(txt)); + static char txt[PJ_INET6_ADDRSTRLEN]; + struct sockaddr *ad = (struct sockaddr*)addr; + if (ad->sa_family != PJ_AF_INET && ad->sa_family != PJ_AF_INET6) + return "?"; + return pj_inet_ntop2(ad->sa_family, pj_sockaddr_get_addr(ad), + txt, sizeof(txt)); } #else # define TRACE_(exp) @@ -68,8 +67,8 @@ defined(PJ_HAS_NET_IF_H) && PJ_HAS_NET_IF_H != 0 /* Using getifaddrs() is preferred since it can work with both IPv4 and IPv6 */ static pj_status_t if_enum_by_af(int af, - unsigned *p_cnt, - pj_sockaddr ifs[]) + unsigned *p_cnt, + pj_sockaddr ifs[]) { struct ifaddrs *ifap = NULL, *it; unsigned max; @@ -77,81 +76,81 @@ static pj_status_t if_enum_by_af(int af, PJ_ASSERT_RETURN(af==PJ_AF_INET || af==PJ_AF_INET6, PJ_EINVAL); TRACE_((THIS_FILE, "Starting interface enum with getifaddrs() for af=%d", - af)); + af)); if (getifaddrs(&ifap) != 0) { - TRACE_((THIS_FILE, " getifarrds() failed: %s", get_os_errmsg())); - return PJ_RETURN_OS_ERROR(pj_get_netos_error()); + TRACE_((THIS_FILE, " getifarrds() failed: %s", get_os_errmsg())); + return PJ_RETURN_OS_ERROR(pj_get_netos_error()); } it = ifap; max = *p_cnt; *p_cnt = 0; for (; it!=NULL && *p_cnt < max; it = it->ifa_next) { - struct sockaddr *ad = it->ifa_addr; + struct sockaddr *ad = it->ifa_addr; - TRACE_((THIS_FILE, " checking %s", it->ifa_name)); + TRACE_((THIS_FILE, " checking %s", it->ifa_name)); - if ((it->ifa_flags & IFF_UP)==0) { - TRACE_((THIS_FILE, " interface is down")); - continue; /* Skip when interface is down */ - } + if ((it->ifa_flags & IFF_UP)==0) { + TRACE_((THIS_FILE, " interface is down")); + continue; /* Skip when interface is down */ + } - if ((it->ifa_flags & IFF_RUNNING)==0) { - TRACE_((THIS_FILE, " interface is not running")); - continue; /* Skip when interface is not running */ - } + if ((it->ifa_flags & IFF_RUNNING)==0) { + TRACE_((THIS_FILE, " interface is not running")); + continue; /* Skip when interface is not running */ + } #if PJ_IP_HELPER_IGNORE_LOOPBACK_IF - if (it->ifa_flags & IFF_LOOPBACK) { - TRACE_((THIS_FILE, " loopback interface")); - continue; /* Skip loopback interface */ - } + if (it->ifa_flags & IFF_LOOPBACK) { + TRACE_((THIS_FILE, " loopback interface")); + continue; /* Skip loopback interface */ + } #endif - if (ad==NULL) { - TRACE_((THIS_FILE, " NULL address ignored")); - continue; /* reported to happen on Linux 2.6.25.9 - with ppp interface */ - } - - if (ad->sa_family != af) { - TRACE_((THIS_FILE, " address %s ignored (af=%d)", - get_addr(ad), ad->sa_family)); - continue; /* Skip when interface is down */ - } - - /* Ignore 192.0.0.0/29 address. - * Ref: https://datatracker.ietf.org/doc/html/rfc7335#section-4 - */ - if (af==pj_AF_INET() && - (pj_ntohl(((pj_sockaddr_in*)ad)->sin_addr.s_addr) >> 4) == - 201326592) /* 0b1100000000000000000000000000 which is - 192.0.0.0 >> 4 */ - { - TRACE_((THIS_FILE, " address %s ignored (192.0.0.0/29 class)", - get_addr(ad), ad->sa_family)); - continue; - } - - /* Ignore 0.0.0.0/8 address. This is a special address - * which doesn't seem to have practical use. - */ - if (af==pj_AF_INET() && - (pj_ntohl(((pj_sockaddr_in*)ad)->sin_addr.s_addr) >> 24) == 0) - { - TRACE_((THIS_FILE, " address %s ignored (0.0.0.0/8 class)", - get_addr(ad), ad->sa_family)); - continue; - } - - TRACE_((THIS_FILE, " address %s (af=%d) added at index %d", - get_addr(ad), ad->sa_family, *p_cnt)); - - pj_bzero(&ifs[*p_cnt], sizeof(ifs[0])); - pj_memcpy(&ifs[*p_cnt], ad, pj_sockaddr_get_len(ad)); - PJ_SOCKADDR_RESET_LEN(&ifs[*p_cnt]); - (*p_cnt)++; + if (ad==NULL) { + TRACE_((THIS_FILE, " NULL address ignored")); + continue; /* reported to happen on Linux 2.6.25.9 + with ppp interface */ + } + + if (ad->sa_family != af) { + TRACE_((THIS_FILE, " address %s ignored (af=%d)", + get_addr(ad), ad->sa_family)); + continue; /* Skip when interface is down */ + } + + /* Ignore 192.0.0.0/29 address. + * Ref: https://datatracker.ietf.org/doc/html/rfc7335#section-4 + */ + if (af==pj_AF_INET() && + (pj_ntohl(((pj_sockaddr_in*)ad)->sin_addr.s_addr) >> 4) == + 201326592) /* 0b1100000000000000000000000000 which is + 192.0.0.0 >> 4 */ + { + TRACE_((THIS_FILE, " address %s ignored (192.0.0.0/29 class)", + get_addr(ad), ad->sa_family)); + continue; + } + + /* Ignore 0.0.0.0/8 address. This is a special address + * which doesn't seem to have practical use. + */ + if (af==pj_AF_INET() && + (pj_ntohl(((pj_sockaddr_in*)ad)->sin_addr.s_addr) >> 24) == 0) + { + TRACE_((THIS_FILE, " address %s ignored (0.0.0.0/8 class)", + get_addr(ad), ad->sa_family)); + continue; + } + + TRACE_((THIS_FILE, " address %s (af=%d) added at index %d", + get_addr(ad), ad->sa_family, *p_cnt)); + + pj_bzero(&ifs[*p_cnt], sizeof(ifs[0])); + pj_memcpy(&ifs[*p_cnt], ad, pj_sockaddr_get_len(ad)); + PJ_SOCKADDR_RESET_LEN(&ifs[*p_cnt]); + (*p_cnt)++; } freeifaddrs(ifap); @@ -164,8 +163,8 @@ static pj_status_t if_enum_by_af(int af, /* Note: this does not work with IPv6 */ static pj_status_t if_enum_by_af(int af, - unsigned *p_cnt, - pj_sockaddr ifs[]) + unsigned *p_cnt, + pj_sockaddr ifs[]) { pj_sock_t sock; char buf[512]; @@ -177,98 +176,98 @@ static pj_status_t if_enum_by_af(int af, PJ_ASSERT_RETURN(af==PJ_AF_INET || af==PJ_AF_INET6, PJ_EINVAL); TRACE_((THIS_FILE, "Starting interface enum with SIOCGIFCONF for af=%d", - af)); + af)); status = pj_sock_socket(af, PJ_SOCK_DGRAM, 0, &sock); if (status != PJ_SUCCESS) - return status; + return status; /* Query available interfaces */ ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if (ioctl(sock, SIOCGIFCONF, &ifc) < 0) { - int oserr = pj_get_netos_error(); - TRACE_((THIS_FILE, " ioctl(SIOCGIFCONF) failed: %s", get_os_errmsg())); - pj_sock_close(sock); - return PJ_RETURN_OS_ERROR(oserr); + int oserr = pj_get_netos_error(); + TRACE_((THIS_FILE, " ioctl(SIOCGIFCONF) failed: %s", get_os_errmsg())); + pj_sock_close(sock); + return PJ_RETURN_OS_ERROR(oserr); } /* Interface interfaces */ ifr = (struct ifreq*) ifc.ifc_req; count = ifc.ifc_len / sizeof(struct ifreq); if (count > *p_cnt) - count = *p_cnt; + count = *p_cnt; *p_cnt = 0; for (i=0; iifr_addr; - - TRACE_((THIS_FILE, " checking interface %s", itf->ifr_name)); + struct sockaddr *ad = &itf->ifr_addr; + + TRACE_((THIS_FILE, " checking interface %s", itf->ifr_name)); - /* Skip address with different family */ - if (ad->sa_family != af) { - TRACE_((THIS_FILE, " address %s (af=%d) ignored", - get_addr(ad), (int)ad->sa_family)); - continue; - } + /* Skip address with different family */ + if (ad->sa_family != af) { + TRACE_((THIS_FILE, " address %s (af=%d) ignored", + get_addr(ad), (int)ad->sa_family)); + continue; + } if (ioctl(sock, SIOCGIFFLAGS, &iff) != 0) { - TRACE_((THIS_FILE, " ioctl(SIOCGIFFLAGS) failed: %s", - get_os_errmsg())); - continue; /* Failed to get flags, continue */ - } + TRACE_((THIS_FILE, " ioctl(SIOCGIFFLAGS) failed: %s", + get_os_errmsg())); + continue; /* Failed to get flags, continue */ + } - if ((iff.ifr_flags & IFF_UP)==0) { - TRACE_((THIS_FILE, " interface is down")); - continue; /* Skip when interface is down */ - } + if ((iff.ifr_flags & IFF_UP)==0) { + TRACE_((THIS_FILE, " interface is down")); + continue; /* Skip when interface is down */ + } - if ((iff.ifr_flags & IFF_RUNNING)==0) { - TRACE_((THIS_FILE, " interface is not running")); - continue; /* Skip when interface is not running */ - } + if ((iff.ifr_flags & IFF_RUNNING)==0) { + TRACE_((THIS_FILE, " interface is not running")); + continue; /* Skip when interface is not running */ + } #if PJ_IP_HELPER_IGNORE_LOOPBACK_IF - if (iff.ifr_flags & IFF_LOOPBACK) { - TRACE_((THIS_FILE, " loopback interface")); - continue; /* Skip loopback interface */ - } + if (iff.ifr_flags & IFF_LOOPBACK) { + TRACE_((THIS_FILE, " loopback interface")); + continue; /* Skip loopback interface */ + } #endif - /* Ignore 192.0.0.0/29 address. - * Ref: https://datatracker.ietf.org/doc/html/rfc7335#section-4 - */ - if (af==pj_AF_INET() && - (pj_ntohl(((pj_sockaddr_in*)ad)->sin_addr.s_addr) >> 4) == - 201326592) /* 0b1100000000000000000000000000 which is - 192.0.0.0 >> 4 */ - { - TRACE_((THIS_FILE, " address %s ignored (192.0.0.0/29 class)", - get_addr(ad), ad->sa_family)); - continue; - } - - /* Ignore 0.0.0.0/8 address. This is a special address - * which doesn't seem to have practical use. - */ - if (af==pj_AF_INET() && - (pj_ntohl(((pj_sockaddr_in*)ad)->sin_addr.s_addr) >> 24) == 0) - { - TRACE_((THIS_FILE, " address %s ignored (0.0.0.0/8 class)", - get_addr(ad), ad->sa_family)); - continue; - } - - TRACE_((THIS_FILE, " address %s (af=%d) added at index %d", - get_addr(ad), ad->sa_family, *p_cnt)); - - pj_bzero(&ifs[*p_cnt], sizeof(ifs[0])); - pj_memcpy(&ifs[*p_cnt], ad, pj_sockaddr_get_len(ad)); - PJ_SOCKADDR_RESET_LEN(&ifs[*p_cnt]); - (*p_cnt)++; + /* Ignore 192.0.0.0/29 address. + * Ref: https://datatracker.ietf.org/doc/html/rfc7335#section-4 + */ + if (af==pj_AF_INET() && + (pj_ntohl(((pj_sockaddr_in*)ad)->sin_addr.s_addr) >> 4) == + 201326592) /* 0b1100000000000000000000000000 which is + 192.0.0.0 >> 4 */ + { + TRACE_((THIS_FILE, " address %s ignored (192.0.0.0/29 class)", + get_addr(ad), ad->sa_family)); + continue; + } + + /* Ignore 0.0.0.0/8 address. This is a special address + * which doesn't seem to have practical use. + */ + if (af==pj_AF_INET() && + (pj_ntohl(((pj_sockaddr_in*)ad)->sin_addr.s_addr) >> 24) == 0) + { + TRACE_((THIS_FILE, " address %s ignored (0.0.0.0/8 class)", + get_addr(ad), ad->sa_family)); + continue; + } + + TRACE_((THIS_FILE, " address %s (af=%d) added at index %d", + get_addr(ad), ad->sa_family, *p_cnt)); + + pj_bzero(&ifs[*p_cnt], sizeof(ifs[0])); + pj_memcpy(&ifs[*p_cnt], ad, pj_sockaddr_get_len(ad)); + PJ_SOCKADDR_RESET_LEN(&ifs[*p_cnt]); + (*p_cnt)++; } /* Done with socket */ @@ -295,93 +294,93 @@ static pj_status_t if_enum_by_af(int af, unsigned *p_cnt, pj_sockaddr ifs[]) status = pj_sock_socket(af, PJ_SOCK_DGRAM, 0, &sock); if (status != PJ_SUCCESS) - return status; + return status; if_list = if_nameindex(); if (if_list == NULL) - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; max_count = *p_cnt; *p_cnt = 0; for (i=0; if_list[i].if_index && *p_cntsa_family != af) { - TRACE_((THIS_FILE, " address %s family %d ignored", - get_addr(&ifreq.ifr_addr), - ifreq.ifr_addr.sa_family)); - continue; /* Not address family that we want, continue */ - } - - /* Ignore 192.0.0.0/29 address. - * Ref: https://datatracker.ietf.org/doc/html/rfc7335#section-4 - */ - if (af==pj_AF_INET() && - (pj_ntohl(((pj_sockaddr_in*)ad)->sin_addr.s_addr) >> 4) == - 201326592) /* 0b1100000000000000000000000000 which is - 192.0.0.0 >> 4 */ - { - TRACE_((THIS_FILE, " address %s ignored (192.0.0.0/29 class)", - get_addr(ad), ad->sa_family)); - continue; - } - - /* Ignore 0.0.0.0/8 address. This is a special address - * which doesn't seem to have practical use. - */ - if (af==pj_AF_INET() && - (pj_ntohl(((pj_sockaddr_in*)ad)->sin_addr.s_addr) >> 24) == 0) - { - TRACE_((THIS_FILE, " address %s ignored (0.0.0.0/8 class)", - get_addr(ad), ad->sa_family)); - continue; - } - - /* Got an address ! */ - TRACE_((THIS_FILE, " address %s (af=%d) added at index %d", - get_addr(ad), ad->sa_family, *p_cnt)); - - pj_bzero(&ifs[*p_cnt], sizeof(ifs[0])); - pj_memcpy(&ifs[*p_cnt], ad, pj_sockaddr_get_len(ad)); - PJ_SOCKADDR_RESET_LEN(&ifs[*p_cnt]); - (*p_cnt)++; + /* Note: SIOCGIFADDR does not work for IPv6! */ + if ((rc=ioctl(sock, SIOCGIFADDR, &ifreq)) != 0) { + TRACE_((THIS_FILE, " ioctl(SIOCGIFADDR) failed: %s", + get_os_errmsg())); + continue; /* Failed to get address, continue */ + } + + ad = (struct sockaddr*) &ifreq.ifr_addr; + + if (ad->sa_family != af) { + TRACE_((THIS_FILE, " address %s family %d ignored", + get_addr(&ifreq.ifr_addr), + ifreq.ifr_addr.sa_family)); + continue; /* Not address family that we want, continue */ + } + + /* Ignore 192.0.0.0/29 address. + * Ref: https://datatracker.ietf.org/doc/html/rfc7335#section-4 + */ + if (af==pj_AF_INET() && + (pj_ntohl(((pj_sockaddr_in*)ad)->sin_addr.s_addr) >> 4) == + 201326592) /* 0b1100000000000000000000000000 which is + 192.0.0.0 >> 4 */ + { + TRACE_((THIS_FILE, " address %s ignored (192.0.0.0/29 class)", + get_addr(ad), ad->sa_family)); + continue; + } + + /* Ignore 0.0.0.0/8 address. This is a special address + * which doesn't seem to have practical use. + */ + if (af==pj_AF_INET() && + (pj_ntohl(((pj_sockaddr_in*)ad)->sin_addr.s_addr) >> 24) == 0) + { + TRACE_((THIS_FILE, " address %s ignored (0.0.0.0/8 class)", + get_addr(ad), ad->sa_family)); + continue; + } + + /* Got an address ! */ + TRACE_((THIS_FILE, " address %s (af=%d) added at index %d", + get_addr(ad), ad->sa_family, *p_cnt)); + + pj_bzero(&ifs[*p_cnt], sizeof(ifs[0])); + pj_memcpy(&ifs[*p_cnt], ad, pj_sockaddr_get_len(ad)); + PJ_SOCKADDR_RESET_LEN(&ifs[*p_cnt]); + (*p_cnt)++; } if_freenameindex(if_list); @@ -393,8 +392,8 @@ static pj_status_t if_enum_by_af(int af, unsigned *p_cnt, pj_sockaddr ifs[]) #else static pj_status_t if_enum_by_af(int af, - unsigned *p_cnt, - pj_sockaddr ifs[]) + unsigned *p_cnt, + pj_sockaddr ifs[]) { pj_status_t status; @@ -405,7 +404,7 @@ static pj_status_t if_enum_by_af(int af, /* Just get one default route */ status = pj_getdefaultipinterface(af, &ifs[0]); if (status != PJ_SUCCESS) - return status; + return status; *p_cnt = 1; return PJ_SUCCESS; @@ -416,29 +415,29 @@ static pj_status_t if_enum_by_af(int af, * Enumerate the local IP interface currently active in the host. */ PJ_DEF(pj_status_t) pj_enum_ip_interface(int af, - unsigned *p_cnt, - pj_sockaddr ifs[]) + unsigned *p_cnt, + pj_sockaddr ifs[]) { unsigned start; pj_status_t status; start = 0; if (af==PJ_AF_INET6 || af==PJ_AF_UNSPEC) { - unsigned max = *p_cnt; - status = if_enum_by_af(PJ_AF_INET6, &max, &ifs[start]); - if (status == PJ_SUCCESS) { - start += max; - (*p_cnt) -= max; - } + unsigned max = *p_cnt; + status = if_enum_by_af(PJ_AF_INET6, &max, &ifs[start]); + if (status == PJ_SUCCESS) { + start += max; + (*p_cnt) -= max; + } } if (af==PJ_AF_INET || af==PJ_AF_UNSPEC) { - unsigned max = *p_cnt; - status = if_enum_by_af(PJ_AF_INET, &max, &ifs[start]); - if (status == PJ_SUCCESS) { - start += max; - (*p_cnt) -= max; - } + unsigned max = *p_cnt; + status = if_enum_by_af(PJ_AF_INET, &max, &ifs[start]); + if (status == PJ_SUCCESS) { + start += max; + (*p_cnt) -= max; + } } *p_cnt = start; @@ -450,7 +449,7 @@ PJ_DEF(pj_status_t) pj_enum_ip_interface(int af, * Enumerate the IP routing table for this host. */ PJ_DEF(pj_status_t) pj_enum_ip_route(unsigned *p_cnt, - pj_ip_route_entry routes[]) + pj_ip_route_entry routes[]) { pj_sockaddr itf; pj_status_t status; @@ -462,7 +461,7 @@ PJ_DEF(pj_status_t) pj_enum_ip_route(unsigned *p_cnt, /* Just get one default route */ status = pj_getdefaultipinterface(PJ_AF_INET, &itf); if (status != PJ_SUCCESS) - return status; + return status; routes[0].ipv4.if_addr.s_addr = itf.ipv4.sin_addr.s_addr; routes[0].ipv4.dst_addr.s_addr = 0; @@ -486,7 +485,7 @@ static pj_status_t get_ipv6_deprecated(unsigned *count, pj_sockaddr addr[]) int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (fd < 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); bzero(&netlink_req, sizeof(netlink_req)); @@ -498,66 +497,66 @@ static pj_status_t get_ipv6_deprecated(unsigned *count, pj_sockaddr addr[]) int rtn = send(fd, &netlink_req, netlink_req.nlmsg_info.nlmsg_len, 0); if (rtn < 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); char read_buffer[pagesize]; size_t idx = 0; while(1) { - bzero(read_buffer, pagesize); - int read_size = recv(fd, read_buffer, pagesize, 0); - if (read_size < 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); - - struct nlmsghdr *nlmsg_ptr = (struct nlmsghdr *) read_buffer; - int nlmsg_len = read_size; - - if (nlmsg_len < sizeof (struct nlmsghdr)) - return PJ_ETOOSMALL; - - if (nlmsg_ptr->nlmsg_type == NLMSG_DONE) - break; - - for(; NLMSG_OK(nlmsg_ptr, nlmsg_len); - nlmsg_ptr = NLMSG_NEXT(nlmsg_ptr, nlmsg_len)) - { - struct ifaddrmsg *ifaddrmsg_ptr; - struct rtattr *rtattr_ptr; - int ifaddrmsg_len; - - ifaddrmsg_ptr = (struct ifaddrmsg*)NLMSG_DATA(nlmsg_ptr); - - if (ifaddrmsg_ptr->ifa_flags & IFA_F_DEPRECATED || - ifaddrmsg_ptr->ifa_flags & IFA_F_TENTATIVE) - { - rtattr_ptr = (struct rtattr*)IFA_RTA(ifaddrmsg_ptr); - ifaddrmsg_len = IFA_PAYLOAD(nlmsg_ptr); - - for(;RTA_OK(rtattr_ptr, ifaddrmsg_len); - rtattr_ptr = RTA_NEXT(rtattr_ptr, ifaddrmsg_len)) - { - switch(rtattr_ptr->rta_type) { - case IFA_ADDRESS: - // Check if addr can contains more data - if (idx >= *count) - break; - // Store deprecated IP - char deprecatedAddr[PJ_INET6_ADDRSTRLEN]; - inet_ntop(ifaddrmsg_ptr->ifa_family, - RTA_DATA(rtattr_ptr), - deprecatedAddr, - sizeof(deprecatedAddr)); - pj_str_t pj_addr_str; - pj_cstr(&pj_addr_str, deprecatedAddr); - pj_sockaddr_init(pj_AF_INET6(), &addr[idx], - &pj_addr_str, 0); - ++idx; - default: - break; - } - } - } - } + bzero(read_buffer, pagesize); + int read_size = recv(fd, read_buffer, pagesize, 0); + if (read_size < 0) + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + + struct nlmsghdr *nlmsg_ptr = (struct nlmsghdr *) read_buffer; + int nlmsg_len = read_size; + + if (nlmsg_len < sizeof (struct nlmsghdr)) + return PJ_ETOOSMALL; + + if (nlmsg_ptr->nlmsg_type == NLMSG_DONE) + break; + + for(; NLMSG_OK(nlmsg_ptr, nlmsg_len); + nlmsg_ptr = NLMSG_NEXT(nlmsg_ptr, nlmsg_len)) + { + struct ifaddrmsg *ifaddrmsg_ptr; + struct rtattr *rtattr_ptr; + int ifaddrmsg_len; + + ifaddrmsg_ptr = (struct ifaddrmsg*)NLMSG_DATA(nlmsg_ptr); + + if (ifaddrmsg_ptr->ifa_flags & IFA_F_DEPRECATED || + ifaddrmsg_ptr->ifa_flags & IFA_F_TENTATIVE) + { + rtattr_ptr = (struct rtattr*)IFA_RTA(ifaddrmsg_ptr); + ifaddrmsg_len = IFA_PAYLOAD(nlmsg_ptr); + + for(;RTA_OK(rtattr_ptr, ifaddrmsg_len); + rtattr_ptr = RTA_NEXT(rtattr_ptr, ifaddrmsg_len)) + { + switch(rtattr_ptr->rta_type) { + case IFA_ADDRESS: + // Check if addr can contains more data + if (idx >= *count) + break; + // Store deprecated IP + char deprecatedAddr[PJ_INET6_ADDRSTRLEN]; + inet_ntop(ifaddrmsg_ptr->ifa_family, + RTA_DATA(rtattr_ptr), + deprecatedAddr, + sizeof(deprecatedAddr)); + pj_str_t pj_addr_str; + pj_cstr(&pj_addr_str, deprecatedAddr); + pj_sockaddr_init(pj_AF_INET6(), &addr[idx], + &pj_addr_str, 0); + ++idx; + default: + break; + } + } + } + } } close(fd); @@ -571,52 +570,52 @@ static pj_status_t get_ipv6_deprecated(unsigned *count, pj_sockaddr addr[]) * Enumerate the local IP interface currently active in the host. */ PJ_DEF(pj_status_t) pj_enum_ip_interface2( const pj_enum_ip_option *opt, - unsigned *p_cnt, - pj_sockaddr ifs[]) + unsigned *p_cnt, + pj_sockaddr ifs[]) { pj_enum_ip_option opt_; if (opt) - opt_ = *opt; + opt_ = *opt; else - pj_enum_ip_option_default(&opt_); + pj_enum_ip_option_default(&opt_); if (opt_.af != pj_AF_INET() && opt_.omit_deprecated_ipv6) { #if defined(PJ_LINUX) && PJ_LINUX!=0 - pj_sockaddr addrs[*p_cnt]; - pj_sockaddr deprecatedAddrs[*p_cnt]; - unsigned deprecatedCount = *p_cnt; - unsigned cnt = 0; - int i; - pj_status_t status; - - status = get_ipv6_deprecated(&deprecatedCount, deprecatedAddrs); - if (status != PJ_SUCCESS) - return status; - - status = pj_enum_ip_interface(opt_.af, p_cnt, addrs); - if (status != PJ_SUCCESS) - return status; - - for (i = 0; i < *p_cnt; ++i) { - int j; - - ifs[cnt++] = addrs[i]; - - if (addrs[i].addr.sa_family != pj_AF_INET6()) - continue; - - for (j = 0; j < deprecatedCount; ++j) { - if (pj_sockaddr_cmp(&addrs[i], &deprecatedAddrs[j]) == 0) { - cnt--; - break; - } - } - } - - *p_cnt = cnt; - return *p_cnt ? PJ_SUCCESS : PJ_ENOTFOUND; + pj_sockaddr addrs[*p_cnt]; + pj_sockaddr deprecatedAddrs[*p_cnt]; + unsigned deprecatedCount = *p_cnt; + unsigned cnt = 0; + int i; + pj_status_t status; + + status = get_ipv6_deprecated(&deprecatedCount, deprecatedAddrs); + if (status != PJ_SUCCESS) + return status; + + status = pj_enum_ip_interface(opt_.af, p_cnt, addrs); + if (status != PJ_SUCCESS) + return status; + + for (i = 0; i < *p_cnt; ++i) { + int j; + + ifs[cnt++] = addrs[i]; + + if (addrs[i].addr.sa_family != pj_AF_INET6()) + continue; + + for (j = 0; j < deprecatedCount; ++j) { + if (pj_sockaddr_cmp(&addrs[i], &deprecatedAddrs[j]) == 0) { + cnt--; + break; + } + } + } + + *p_cnt = cnt; + return *p_cnt ? PJ_SUCCESS : PJ_ENOTFOUND; #else return PJ_ENOTSUP; #endif diff --git a/pjlib/src/pj/ip_helper_symbian.cpp b/pjlib/src/pj/ip_helper_symbian.cpp index c9b3ddcbaf..59fe1fe7d0 100644 --- a/pjlib/src/pj/ip_helper_symbian.cpp +++ b/pjlib/src/pj/ip_helper_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,12 +27,12 @@ #include "os_symbian.h" -#define THIS_FILE "ip_helper_symbian.cpp" -#define TRACE_ME 0 +#define THIS_FILE "ip_helper_symbian.cpp" +#define TRACE_ME 0 static pj_status_t rsock_enum_interface(int af, - unsigned *p_cnt, - pj_sockaddr ifs[]) + unsigned *p_cnt, + pj_sockaddr ifs[]) { TInt rc; RSocket rSock; @@ -41,55 +40,55 @@ static pj_status_t rsock_enum_interface(int af, unsigned i; if (PjSymbianOS::Instance()->Connection()) { - - rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), - af, PJ_SOCK_DGRAM, KProtocolInetUdp, - *PjSymbianOS::Instance()->Connection()); + + rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), + af, PJ_SOCK_DGRAM, KProtocolInetUdp, + *PjSymbianOS::Instance()->Connection()); } else { - - rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), - af, PJ_SOCK_DGRAM, KProtocolInetUdp); - + + rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), + af, PJ_SOCK_DGRAM, KProtocolInetUdp); + } if (rc != KErrNone) - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR(rc); rSock.SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl); for (i=0; i<*p_cnt && - rSock.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, - info) == KErrNone; ) + rSock.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, + info) == KErrNone; ) { - TInetAddr &iAddress = info().iAddress; - int namelen; + TInetAddr &iAddress = info().iAddress; + int namelen; #if TRACE_ME - if (1) { - pj_sockaddr a; - char ipaddr[PJ_INET6_ADDRSTRLEN+2]; - - namelen = sizeof(pj_sockaddr); - if (PjSymbianOS::Addr2pj(iAddress, a, &namelen, - PJ_FALSE) == PJ_SUCCESS) - { - PJ_LOG(5,(THIS_FILE, "Enum: found address %s", - pj_sockaddr_print(&a, ipaddr, sizeof(ipaddr), 2))); - } - } + if (1) { + pj_sockaddr a; + char ipaddr[PJ_INET6_ADDRSTRLEN+2]; + + namelen = sizeof(pj_sockaddr); + if (PjSymbianOS::Addr2pj(iAddress, a, &namelen, + PJ_FALSE) == PJ_SUCCESS) + { + PJ_LOG(5,(THIS_FILE, "Enum: found address %s", + pj_sockaddr_print(&a, ipaddr, sizeof(ipaddr), 2))); + } + } #endif - - namelen = sizeof(ifs[i]); - if (PjSymbianOS::Addr2pj(iAddress, ifs[i], &namelen, - PJ_TRUE) != PJ_SUCCESS) - { - continue; - } + + namelen = sizeof(ifs[i]); + if (PjSymbianOS::Addr2pj(iAddress, ifs[i], &namelen, + PJ_TRUE) != PJ_SUCCESS) + { + continue; + } - if (ifs[i].addr.sa_family != af) - continue; - - ++i; + if (ifs[i].addr.sa_family != af) + continue; + + ++i; } rSock.Close(); @@ -99,37 +98,37 @@ static pj_status_t rsock_enum_interface(int af, return PJ_SUCCESS; } - + /* * Enumerate the local IP interface currently active in the host. */ PJ_DEF(pj_status_t) pj_enum_ip_interface(int af, - unsigned *p_cnt, - pj_sockaddr ifs[]) + unsigned *p_cnt, + pj_sockaddr ifs[]) { unsigned start; pj_status_t status = PJ_SUCCESS; start = 0; - + /* Get IPv6 interface first. */ if (af==PJ_AF_INET6 || af==PJ_AF_UNSPEC) { - unsigned max = *p_cnt; - status = rsock_enum_interface(PJ_AF_INET6, &max, &ifs[start]); - if (status == PJ_SUCCESS) { - (*p_cnt) -= max; - start += max; - } + unsigned max = *p_cnt; + status = rsock_enum_interface(PJ_AF_INET6, &max, &ifs[start]); + if (status == PJ_SUCCESS) { + (*p_cnt) -= max; + start += max; + } } /* Get IPv4 interface. */ if (af==PJ_AF_INET || af==PJ_AF_UNSPEC) { - unsigned max = *p_cnt; - status = rsock_enum_interface(PJ_AF_INET, &max, &ifs[start]); - if (status == PJ_SUCCESS) { - (*p_cnt) -= max; - start += max; - } + unsigned max = *p_cnt; + status = rsock_enum_interface(PJ_AF_INET, &max, &ifs[start]); + if (status == PJ_SUCCESS) { + (*p_cnt) -= max; + start += max; + } } *p_cnt = start; @@ -141,18 +140,18 @@ PJ_DEF(pj_status_t) pj_enum_ip_interface(int af, * Enumerate the local IP interface currently active in the host. */ PJ_DEF(pj_status_t) pj_enum_ip_interface2( const pj_enum_ip_option *opt, - unsigned *count, - pj_sockaddr ifs[]) + unsigned *count, + pj_sockaddr ifs[]) { pj_enum_ip_option opt_; if (opt && opt->omit_deprecated_ipv6) - return PJ_ENOTSUP; + return PJ_ENOTSUP; if (opt) - opt_ = *opt; + opt_ = *opt; else - pj_enum_ip_option_default(&opt_); + pj_enum_ip_option_default(&opt_); return pj_enum_ip_interface(opt_.af, count, ifs); } @@ -161,7 +160,7 @@ PJ_DEF(pj_status_t) pj_enum_ip_interface2( const pj_enum_ip_option *opt, * Enumerate the IP routing table for this host. */ PJ_DEF(pj_status_t) pj_enum_ip_route(unsigned *p_cnt, - pj_ip_route_entry routes[]) + pj_ip_route_entry routes[]) { PJ_ASSERT_RETURN(p_cnt && *p_cnt > 0 && routes, PJ_EINVAL); *p_cnt = 0; diff --git a/pjlib/src/pj/ip_helper_win32.c b/pjlib/src/pj/ip_helper_win32.c index cdc1c19e56..e2d72a07f0 100644 --- a/pjlib/src/pj/ip_helper_win32.c +++ b/pjlib/src/pj/ip_helper_win32.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -71,26 +70,26 @@ */ #if defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE!=0 /* on CE, follow the PJLIB Unicode setting */ -# define GPA_TEXT(x) PJ_T(x) -# define gpa_char pj_char_t +# define GPA_TEXT(x) PJ_T(x) +# define gpa_char pj_char_t #else /* on non-CE, always use ANSI format */ -# define GPA_TEXT(x) x -# define gpa_char char +# define GPA_TEXT(x) x +# define gpa_char char #endif typedef DWORD (WINAPI *PFN_GetIpAddrTable)(PMIB_IPADDRTABLE pIpAddrTable, - PULONG pdwSize, - BOOL bOrder); + PULONG pdwSize, + BOOL bOrder); typedef DWORD (WINAPI *PFN_GetAdapterAddresses)(ULONG Family, - ULONG Flags, - PVOID Reserved, - PIP_ADAPTER_ADDRESSES AdapterAddresses, - PULONG SizePointer); + ULONG Flags, + PVOID Reserved, + PIP_ADAPTER_ADDRESSES AdapterAddresses, + PULONG SizePointer); typedef DWORD (WINAPI *PFN_GetIpForwardTable)(PMIB_IPFORWARDTABLE pIpForwardTable, - PULONG pdwSize, - BOOL bOrder); + PULONG pdwSize, + BOOL bOrder); typedef DWORD (WINAPI *PFN_GetIfEntry)(PMIB_IFROW pIfRow); static HANDLE s_hDLL; @@ -113,48 +112,48 @@ static void unload_iphlp_module(void) static FARPROC GetIpHlpApiProc(gpa_char *lpProcName) { if(NULL == s_hDLL) { - s_hDLL = LoadLibrary(PJ_T("IpHlpApi")); - if(NULL != s_hDLL) { - pj_atexit(&unload_iphlp_module); - } + s_hDLL = LoadLibrary(PJ_T("IpHlpApi")); + if(NULL != s_hDLL) { + pj_atexit(&unload_iphlp_module); + } } - + if(NULL != s_hDLL) - return GetProcAddress(s_hDLL, lpProcName); + return GetProcAddress(s_hDLL, lpProcName); return NULL; } static DWORD MyGetIpAddrTable(PMIB_IPADDRTABLE pIpAddrTable, - PULONG pdwSize, - BOOL bOrder) + PULONG pdwSize, + BOOL bOrder) { if(NULL == s_pfnGetIpAddrTable) { - s_pfnGetIpAddrTable = (PFN_GetIpAddrTable) - GetIpHlpApiProc(GPA_TEXT("GetIpAddrTable")); + s_pfnGetIpAddrTable = (PFN_GetIpAddrTable) + GetIpHlpApiProc(GPA_TEXT("GetIpAddrTable")); } if(NULL != s_pfnGetIpAddrTable) { - return s_pfnGetIpAddrTable(pIpAddrTable, pdwSize, bOrder); + return s_pfnGetIpAddrTable(pIpAddrTable, pdwSize, bOrder); } return ERROR_NOT_SUPPORTED; } static DWORD MyGetAdapterAddresses(ULONG Family, - ULONG Flags, - PVOID Reserved, - PIP_ADAPTER_ADDRESSES AdapterAddresses, - PULONG SizePointer) + ULONG Flags, + PVOID Reserved, + PIP_ADAPTER_ADDRESSES AdapterAddresses, + PULONG SizePointer) { if(NULL == s_pfnGetAdapterAddresses) { - s_pfnGetAdapterAddresses = (PFN_GetAdapterAddresses) - GetIpHlpApiProc(GPA_TEXT("GetAdaptersAddresses")); + s_pfnGetAdapterAddresses = (PFN_GetAdapterAddresses) + GetIpHlpApiProc(GPA_TEXT("GetAdaptersAddresses")); } if(NULL != s_pfnGetAdapterAddresses) { - return s_pfnGetAdapterAddresses(Family, Flags, Reserved, - AdapterAddresses, SizePointer); + return s_pfnGetAdapterAddresses(Family, Flags, Reserved, + AdapterAddresses, SizePointer); } return ERROR_NOT_SUPPORTED; @@ -164,12 +163,12 @@ static DWORD MyGetAdapterAddresses(ULONG Family, static DWORD MyGetIfEntry(MIB_IFROW *pIfRow) { if(NULL == s_pfnGetIfEntry) { - s_pfnGetIfEntry = (PFN_GetIfEntry) - GetIpHlpApiProc(GPA_TEXT("GetIfEntry")); + s_pfnGetIfEntry = (PFN_GetIfEntry) + GetIpHlpApiProc(GPA_TEXT("GetIfEntry")); } if(NULL != s_pfnGetIfEntry) { - return s_pfnGetIfEntry(pIfRow); + return s_pfnGetIfEntry(pIfRow); } return ERROR_NOT_SUPPORTED; @@ -178,16 +177,16 @@ static DWORD MyGetIfEntry(MIB_IFROW *pIfRow) static DWORD MyGetIpForwardTable(PMIB_IPFORWARDTABLE pIpForwardTable, - PULONG pdwSize, - BOOL bOrder) + PULONG pdwSize, + BOOL bOrder) { if(NULL == s_pfnGetIpForwardTable) { - s_pfnGetIpForwardTable = (PFN_GetIpForwardTable) - GetIpHlpApiProc(GPA_TEXT("GetIpForwardTable")); + s_pfnGetIpForwardTable = (PFN_GetIpForwardTable) + GetIpHlpApiProc(GPA_TEXT("GetIpForwardTable")); } if(NULL != s_pfnGetIpForwardTable) { - return s_pfnGetIpForwardTable(pIpForwardTable, pdwSize, bOrder); + return s_pfnGetIpForwardTable(pIpForwardTable, pdwSize, bOrder); } return ERROR_NOT_SUPPORTED; @@ -197,7 +196,7 @@ static DWORD MyGetIpForwardTable(PMIB_IPFORWARDTABLE pIpForwardTable, * for IPv4 addresses only. */ static pj_status_t enum_ipv4_interface(unsigned *p_cnt, - pj_sockaddr ifs[]) + pj_sockaddr ifs[]) { char ipTabBuff[512]; MIB_IPADDRTABLE *pTab = (MIB_IPADDRTABLE*)ipTabBuff; @@ -210,18 +209,18 @@ static pj_status_t enum_ipv4_interface(unsigned *p_cnt, /* Get IP address table */ rc = MyGetIpAddrTable(pTab, &tabSize, FALSE); if (rc != NO_ERROR) { - if (rc == ERROR_INSUFFICIENT_BUFFER) { - /* Retry with larger buffer */ - pTab = (MIB_IPADDRTABLE*)malloc(tabSize); - if (pTab) - rc = MyGetIpAddrTable(pTab, &tabSize, FALSE); - } - - if (rc != NO_ERROR) { - if (pTab != (MIB_IPADDRTABLE*)ipTabBuff) - free(pTab); - return PJ_RETURN_OS_ERROR(rc); - } + if (rc == ERROR_INSUFFICIENT_BUFFER) { + /* Retry with larger buffer */ + pTab = (MIB_IPADDRTABLE*)malloc(tabSize); + if (pTab) + rc = MyGetIpAddrTable(pTab, &tabSize, FALSE); + } + + if (rc != NO_ERROR) { + if (pTab != (MIB_IPADDRTABLE*)ipTabBuff) + free(pTab); + return PJ_RETURN_OS_ERROR(rc); + } } /* Reset result */ @@ -231,36 +230,36 @@ static pj_status_t enum_ipv4_interface(unsigned *p_cnt, count = (pTab->dwNumEntries < *p_cnt) ? pTab->dwNumEntries : *p_cnt; *p_cnt = 0; for (i=0; itable[i].dwAddr == 0) - continue; + /* Ignore 0.0.0.0 address (interface is down?) */ + if (pTab->table[i].dwAddr == 0) + continue; - /* Ignore 0.0.0.0/8 address. This is a special address - * which doesn't seem to have practical use. - */ - if ((pj_ntohl(pTab->table[i].dwAddr) >> 24) == 0) - continue; + /* Ignore 0.0.0.0/8 address. This is a special address + * which doesn't seem to have practical use. + */ + if ((pj_ntohl(pTab->table[i].dwAddr) >> 24) == 0) + continue; #if PJ_IP_HELPER_IGNORE_LOOPBACK_IF - /* Investigate the type of this interface */ - pj_bzero(&ifRow, sizeof(ifRow)); - ifRow.dwIndex = pTab->table[i].dwIndex; - if (MyGetIfEntry(&ifRow) != 0) - continue; - - if (ifRow.dwType == MIB_IF_TYPE_LOOPBACK) - continue; + /* Investigate the type of this interface */ + pj_bzero(&ifRow, sizeof(ifRow)); + ifRow.dwIndex = pTab->table[i].dwIndex; + if (MyGetIfEntry(&ifRow) != 0) + continue; + + if (ifRow.dwType == MIB_IF_TYPE_LOOPBACK) + continue; #endif - ifs[*p_cnt].ipv4.sin_family = PJ_AF_INET; - ifs[*p_cnt].ipv4.sin_addr.s_addr = pTab->table[i].dwAddr; - (*p_cnt)++; + ifs[*p_cnt].ipv4.sin_family = PJ_AF_INET; + ifs[*p_cnt].ipv4.sin_addr.s_addr = pTab->table[i].dwAddr; + (*p_cnt)++; } if (pTab != (MIB_IPADDRTABLE*)ipTabBuff) - free(pTab); + free(pTab); return (*p_cnt) ? PJ_SUCCESS : PJ_ENOTFOUND; } @@ -269,8 +268,8 @@ static pj_status_t enum_ipv4_interface(unsigned *p_cnt, * which works for both IPv4 and IPv6. */ static pj_status_t enum_ipv4_ipv6_interface(int af, - unsigned *p_cnt, - pj_sockaddr ifs[]) + unsigned *p_cnt, + pj_sockaddr ifs[]) { pj_uint8_t buffer[600]; IP_ADAPTER_ADDRESSES *adapter = (IP_ADAPTER_ADDRESSES*)buffer; @@ -281,24 +280,24 @@ static pj_status_t enum_ipv4_ipv6_interface(int af, DWORD rc; flags = GAA_FLAG_SKIP_FRIENDLY_NAME | - GAA_FLAG_SKIP_DNS_SERVER | - GAA_FLAG_SKIP_MULTICAST; + GAA_FLAG_SKIP_DNS_SERVER | + GAA_FLAG_SKIP_MULTICAST; rc = MyGetAdapterAddresses(af, flags, NULL, adapter, &size); if (rc != ERROR_SUCCESS) { - if (rc == ERROR_BUFFER_OVERFLOW) { - /* Retry with larger memory size */ - adapterBuf = malloc(size); - adapter = (IP_ADAPTER_ADDRESSES*) adapterBuf; - if (adapter != NULL) - rc = MyGetAdapterAddresses(af, flags, NULL, adapter, &size); - } - - if (rc != ERROR_SUCCESS) { - if (adapterBuf) - free(adapterBuf); - return PJ_RETURN_OS_ERROR(rc); - } + if (rc == ERROR_BUFFER_OVERFLOW) { + /* Retry with larger memory size */ + adapterBuf = malloc(size); + adapter = (IP_ADAPTER_ADDRESSES*) adapterBuf; + if (adapter != NULL) + rc = MyGetAdapterAddresses(af, flags, NULL, adapter, &size); + } + + if (rc != ERROR_SUCCESS) { + if (adapterBuf) + free(adapterBuf); + return PJ_RETURN_OS_ERROR(rc); + } } /* Reset result */ @@ -306,54 +305,54 @@ static pj_status_t enum_ipv4_ipv6_interface(int af, /* Enumerate interface */ for (i=0; i<*p_cnt && adapter; adapter = adapter->Next) { - if (adapter->FirstUnicastAddress) { - SOCKET_ADDRESS *pAddr = &adapter->FirstUnicastAddress->Address; - - /* Ignore address family which we didn't request, just in case */ - if (pAddr->lpSockaddr->sa_family != PJ_AF_INET && - pAddr->lpSockaddr->sa_family != PJ_AF_INET6) - { - continue; - } - - /* Apply some filtering to known IPv4 unusable addresses */ - if (pAddr->lpSockaddr->sa_family == PJ_AF_INET) { - const pj_sockaddr_in *addr_in = - (const pj_sockaddr_in*)pAddr->lpSockaddr; - - /* Ignore 0.0.0.0 address (interface is down?) */ - if (addr_in->sin_addr.s_addr == 0) - continue; - - /* Ignore 0.0.0.0/8 address. This is a special address - * which doesn't seem to have practical use. - */ - if ((pj_ntohl(addr_in->sin_addr.s_addr) >> 24) == 0) - continue; - } + if (adapter->FirstUnicastAddress) { + SOCKET_ADDRESS *pAddr = &adapter->FirstUnicastAddress->Address; + + /* Ignore address family which we didn't request, just in case */ + if (pAddr->lpSockaddr->sa_family != PJ_AF_INET && + pAddr->lpSockaddr->sa_family != PJ_AF_INET6) + { + continue; + } + + /* Apply some filtering to known IPv4 unusable addresses */ + if (pAddr->lpSockaddr->sa_family == PJ_AF_INET) { + const pj_sockaddr_in *addr_in = + (const pj_sockaddr_in*)pAddr->lpSockaddr; + + /* Ignore 0.0.0.0 address (interface is down?) */ + if (addr_in->sin_addr.s_addr == 0) + continue; + + /* Ignore 0.0.0.0/8 address. This is a special address + * which doesn't seem to have practical use. + */ + if ((pj_ntohl(addr_in->sin_addr.s_addr) >> 24) == 0) + continue; + } #if PJ_IP_HELPER_IGNORE_LOOPBACK_IF - /* Ignore loopback interfaces */ - /* This should have been IF_TYPE_SOFTWARE_LOOPBACK according to - * MSDN, and this macro should have been declared in Ipifcons.h, - * but some SDK versions don't have it. - */ - if (adapter->IfType == MIB_IF_TYPE_LOOPBACK) - continue; + /* Ignore loopback interfaces */ + /* This should have been IF_TYPE_SOFTWARE_LOOPBACK according to + * MSDN, and this macro should have been declared in Ipifcons.h, + * but some SDK versions don't have it. + */ + if (adapter->IfType == MIB_IF_TYPE_LOOPBACK) + continue; #endif - /* Ignore down interface */ - if (adapter->OperStatus != IfOperStatusUp) - continue; + /* Ignore down interface */ + if (adapter->OperStatus != IfOperStatusUp) + continue; - ifs[i].addr.sa_family = pAddr->lpSockaddr->sa_family; - pj_memcpy(&ifs[i], pAddr->lpSockaddr, pAddr->iSockaddrLength); - ++i; - } + ifs[i].addr.sa_family = pAddr->lpSockaddr->sa_family; + pj_memcpy(&ifs[i], pAddr->lpSockaddr, pAddr->iSockaddrLength); + ++i; + } } if (adapterBuf) - free(adapterBuf); + free(adapterBuf); *p_cnt = i; return (*p_cnt) ? PJ_SUCCESS : PJ_ENOTFOUND; @@ -364,18 +363,18 @@ static pj_status_t enum_ipv4_ipv6_interface(int af, * Enumerate the local IP interface currently active in the host. */ PJ_DEF(pj_status_t) pj_enum_ip_interface(int af, - unsigned *p_cnt, - pj_sockaddr ifs[]) + unsigned *p_cnt, + pj_sockaddr ifs[]) { pj_status_t status = -1; PJ_ASSERT_RETURN(p_cnt && ifs, PJ_EINVAL); PJ_ASSERT_RETURN(af==PJ_AF_UNSPEC || af==PJ_AF_INET || af==PJ_AF_INET6, - PJ_EAFNOTSUP); + PJ_EAFNOTSUP); status = enum_ipv4_ipv6_interface(af, p_cnt, ifs); if (status != PJ_SUCCESS && (af==PJ_AF_INET || af==PJ_AF_UNSPEC)) - status = enum_ipv4_interface(p_cnt, ifs); + status = enum_ipv4_interface(p_cnt, ifs); return status; } @@ -384,18 +383,18 @@ PJ_DEF(pj_status_t) pj_enum_ip_interface(int af, * Enumerate the local IP interface currently active in the host. */ PJ_DEF(pj_status_t) pj_enum_ip_interface2( const pj_enum_ip_option *opt, - unsigned *p_cnt, - pj_sockaddr ifs[]) + unsigned *p_cnt, + pj_sockaddr ifs[]) { pj_enum_ip_option opt_; if (opt && opt->omit_deprecated_ipv6) - return PJ_ENOTSUP; + return PJ_ENOTSUP; if (opt) - opt_ = *opt; + opt_ = *opt; else - pj_enum_ip_option_default(&opt_); + pj_enum_ip_option_default(&opt_); return pj_enum_ip_interface(opt_.af, p_cnt, ifs); } @@ -405,7 +404,7 @@ PJ_DEF(pj_status_t) pj_enum_ip_interface2( const pj_enum_ip_option *opt, * Enumerate the IP routing table for this host. */ PJ_DEF(pj_status_t) pj_enum_ip_route(unsigned *p_cnt, - pj_ip_route_entry routes[]) + pj_ip_route_entry routes[]) { char ipTabBuff[1024]; MIB_IPADDRTABLE *pIpTab; @@ -424,14 +423,14 @@ PJ_DEF(pj_status_t) pj_enum_ip_route(unsigned *p_cnt, tabSize = sizeof(ipTabBuff); rc = MyGetIpAddrTable(pIpTab, &tabSize, FALSE); if (rc != NO_ERROR) - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR(rc); /* Next get IP route table */ tabSize = sizeof(rtabBuff); rc = MyGetIpForwardTable(prTab, &tabSize, 1); if (rc != NO_ERROR) - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR(rc); /* Reset routes */ pj_bzero(routes, sizeof(routes[0]) * (*p_cnt)); @@ -440,22 +439,22 @@ PJ_DEF(pj_status_t) pj_enum_ip_route(unsigned *p_cnt, count = (prTab->dwNumEntries < *p_cnt) ? prTab->dwNumEntries : *p_cnt; *p_cnt = 0; for (i=0; idwNumEntries; ++j) { - if (pIpTab->table[j].dwIndex == prTab->table[i].dwForwardIfIndex) - break; - } + /* Find interface entry */ + for (j=0; jdwNumEntries; ++j) { + if (pIpTab->table[j].dwIndex == prTab->table[i].dwForwardIfIndex) + break; + } - if (j==pIpTab->dwNumEntries) - continue; /* Interface not found */ + if (j==pIpTab->dwNumEntries) + continue; /* Interface not found */ - routes[*p_cnt].ipv4.if_addr.s_addr = pIpTab->table[j].dwAddr; - routes[*p_cnt].ipv4.dst_addr.s_addr = prTab->table[i].dwForwardDest; - routes[*p_cnt].ipv4.mask.s_addr = prTab->table[i].dwForwardMask; + routes[*p_cnt].ipv4.if_addr.s_addr = pIpTab->table[j].dwAddr; + routes[*p_cnt].ipv4.dst_addr.s_addr = prTab->table[i].dwForwardDest; + routes[*p_cnt].ipv4.mask.s_addr = prTab->table[i].dwForwardMask; - (*p_cnt)++; + (*p_cnt)++; } return PJ_SUCCESS; diff --git a/pjlib/src/pj/ip_helper_winphone8.c b/pjlib/src/pj/ip_helper_winphone8.c index c581ded609..65a4094eb5 100644 --- a/pjlib/src/pj/ip_helper_winphone8.c +++ b/pjlib/src/pj/ip_helper_winphone8.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -27,8 +26,8 @@ * Enumerate the local IP interface currently active in the host. */ PJ_DEF(pj_status_t) pj_enum_ip_interface(int af, - unsigned *p_cnt, - pj_sockaddr ifs[]) + unsigned *p_cnt, + pj_sockaddr ifs[]) { PJ_UNUSED_ARG(af); PJ_UNUSED_ARG(ifs); @@ -44,8 +43,8 @@ PJ_DEF(pj_status_t) pj_enum_ip_interface(int af, * Enumerate the local IP interface currently active in the host. */ PJ_DEF(pj_status_t) pj_enum_ip_interface2( const pj_enum_ip_option *opt, - unsigned *p_cnt, - pj_sockaddr ifs[]) + unsigned *p_cnt, + pj_sockaddr ifs[]) { PJ_UNUSED_ARG(opt); PJ_UNUSED_ARG(ifs); @@ -64,7 +63,7 @@ PJ_DEF(pj_status_t) pj_enum_ip_interface2( const pj_enum_ip_option *opt, * Enumerate the IP routing table for this host. */ PJ_DEF(pj_status_t) pj_enum_ip_route(unsigned *p_cnt, - pj_ip_route_entry routes[]) + pj_ip_route_entry routes[]) { PJ_UNUSED_ARG(routes); PJ_ASSERT_RETURN(p_cnt, PJ_EINVAL); diff --git a/pjlib/src/pj/list.c b/pjlib/src/pj/list.c index 2d7a3b06a4..1d79a175ca 100644 --- a/pjlib/src/pj/list.c +++ b/pjlib/src/pj/list.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pj/lock.c b/pjlib/src/pj/lock.c index e6967d1348..af5e303da0 100644 --- a/pjlib/src/pj/lock.c +++ b/pjlib/src/pj/lock.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,7 +24,7 @@ #include #include -#define THIS_FILE "lock.c" +#define THIS_FILE "lock.c" typedef void LOCK_OBJ; @@ -36,10 +35,10 @@ struct pj_lock_t { LOCK_OBJ *lock_object; - pj_status_t (*acquire) (LOCK_OBJ*); - pj_status_t (*tryacquire) (LOCK_OBJ*); - pj_status_t (*release) (LOCK_OBJ*); - pj_status_t (*destroy) (LOCK_OBJ*); + pj_status_t (*acquire) (LOCK_OBJ*); + pj_status_t (*tryacquire) (LOCK_OBJ*); + pj_status_t (*release) (LOCK_OBJ*); + pj_status_t (*destroy) (LOCK_OBJ*); }; typedef pj_status_t (*FPTR)(LOCK_OBJ*); @@ -57,9 +56,9 @@ static pj_lock_t mutex_lock_template = }; static pj_status_t create_mutex_lock( pj_pool_t *pool, - const char *name, - int type, - pj_lock_t **lock ) + const char *name, + int type, + pj_lock_t **lock ) { pj_lock_t *p_lock; pj_mutex_t *mutex; @@ -69,12 +68,12 @@ static pj_status_t create_mutex_lock( pj_pool_t *pool, p_lock = PJ_POOL_ALLOC_T(pool, pj_lock_t); if (!p_lock) - return PJ_ENOMEM; + return PJ_ENOMEM; pj_memcpy(p_lock, &mutex_lock_template, sizeof(pj_lock_t)); rc = pj_mutex_create(pool, name, type, &mutex); if (rc != PJ_SUCCESS) - return rc; + return rc; p_lock->lock_object = mutex; *lock = p_lock; @@ -83,15 +82,15 @@ static pj_status_t create_mutex_lock( pj_pool_t *pool, PJ_DEF(pj_status_t) pj_lock_create_simple_mutex( pj_pool_t *pool, - const char *name, - pj_lock_t **lock ) + const char *name, + pj_lock_t **lock ) { return create_mutex_lock(pool, name, PJ_MUTEX_SIMPLE, lock); } PJ_DEF(pj_status_t) pj_lock_create_recursive_mutex( pj_pool_t *pool, - const char *name, - pj_lock_t **lock ) + const char *name, + pj_lock_t **lock ) { return create_mutex_lock(pool, name, PJ_MUTEX_RECURSE, lock); } @@ -116,8 +115,8 @@ static pj_lock_t null_lock_template = }; PJ_DEF(pj_status_t) pj_lock_create_null_mutex( pj_pool_t *pool, - const char *name, - pj_lock_t **lock ) + const char *name, + pj_lock_t **lock ) { PJ_UNUSED_ARG(name); PJ_UNUSED_ARG(pool); @@ -144,10 +143,10 @@ static pj_lock_t sem_lock_template = }; PJ_DEF(pj_status_t) pj_lock_create_semaphore( pj_pool_t *pool, - const char *name, - unsigned initial, - unsigned max, - pj_lock_t **lock ) + const char *name, + unsigned initial, + unsigned max, + pj_lock_t **lock ) { pj_lock_t *p_lock; pj_sem_t *sem; @@ -157,7 +156,7 @@ PJ_DEF(pj_status_t) pj_lock_create_semaphore( pj_pool_t *pool, p_lock = PJ_POOL_ALLOC_T(pool, pj_lock_t); if (!p_lock) - return PJ_ENOMEM; + return PJ_ENOMEM; pj_memcpy(p_lock, &sem_lock_template, sizeof(pj_lock_t)); rc = pj_sem_create( pool, name, initial, max, &sem); @@ -171,7 +170,7 @@ PJ_DEF(pj_status_t) pj_lock_create_semaphore( pj_pool_t *pool, } -#endif /* PJ_HAS_SEMAPHORE */ +#endif /* PJ_HAS_SEMAPHORE */ PJ_DEF(pj_status_t) pj_lock_acquire( pj_lock_t *lock ) @@ -207,8 +206,8 @@ PJ_DEF(pj_status_t) pj_lock_destroy( pj_lock_t *lock ) typedef struct grp_lock_item { PJ_DECL_LIST_MEMBER(struct grp_lock_item); - int prio; - pj_lock_t *lock; + int prio; + pj_lock_t *lock; } grp_lock_item; @@ -216,8 +215,8 @@ typedef struct grp_lock_item typedef struct grp_destroy_callback { PJ_DECL_LIST_MEMBER(struct grp_destroy_callback); - void *comp; - void (*handler)(void*); + void *comp; + void (*handler)(void*); } grp_destroy_callback; #if PJ_GRP_LOCK_DEBUG @@ -225,29 +224,29 @@ typedef struct grp_destroy_callback typedef struct grp_lock_ref { PJ_DECL_LIST_MEMBER(struct grp_lock_ref); - const char *file; - int line; + const char *file; + int line; } grp_lock_ref; #endif /* The group lock */ struct pj_grp_lock_t { - pj_lock_t base; + pj_lock_t base; - pj_pool_t *pool; - pj_atomic_t *ref_cnt; - pj_lock_t *own_lock; + pj_pool_t *pool; + pj_atomic_t *ref_cnt; + pj_lock_t *own_lock; - pj_thread_t *owner; - int owner_cnt; + pj_thread_t *owner; + int owner_cnt; - grp_lock_item lock_list; + grp_lock_item lock_list; grp_destroy_callback destroy_list; #if PJ_GRP_LOCK_DEBUG - grp_lock_ref ref_list; - grp_lock_ref ref_free_list; + grp_lock_ref ref_list; + grp_lock_ref ref_free_list; #endif }; @@ -261,16 +260,16 @@ static void grp_lock_set_owner_thread(pj_grp_lock_t *glock) { if (!glock->owner) { #if PJ_HAS_THREADS - glock->owner = pj_thread_this(); + glock->owner = pj_thread_this(); #else glock->owner = (pj_thread_t *) -1; #endif - glock->owner_cnt = 1; + glock->owner_cnt = 1; } else { #if PJ_HAS_THREADS - pj_assert(glock->owner == pj_thread_this()); + pj_assert(glock->owner == pj_thread_this()); #endif - glock->owner_cnt++; + glock->owner_cnt++; } } @@ -281,8 +280,8 @@ static void grp_lock_unset_owner_thread(pj_grp_lock_t *glock) #endif pj_assert(glock->owner_cnt > 0); if (--glock->owner_cnt <= 0) { - glock->owner = NULL; - glock->owner_cnt = 0; + glock->owner = NULL; + glock->owner_cnt = 0; } } @@ -295,8 +294,8 @@ static pj_status_t grp_lock_acquire(LOCK_OBJ *p) lck = glock->lock_list.next; while (lck != &glock->lock_list) { - pj_lock_acquire(lck->lock); - lck = lck->next; + pj_lock_acquire(lck->lock); + lck = lck->next; } grp_lock_set_owner_thread(glock); pj_grp_lock_add_ref(glock); @@ -312,16 +311,16 @@ static pj_status_t grp_lock_tryacquire(LOCK_OBJ *p) lck = glock->lock_list.next; while (lck != &glock->lock_list) { - pj_status_t status = pj_lock_tryacquire(lck->lock); - if (status != PJ_SUCCESS) { - lck = lck->prev; - while (lck != &glock->lock_list) { - pj_lock_release(lck->lock); - lck = lck->prev; - } - return status; - } - lck = lck->next; + pj_status_t status = pj_lock_tryacquire(lck->lock); + if (status != PJ_SUCCESS) { + lck = lck->prev; + while (lck != &glock->lock_list) { + pj_lock_release(lck->lock); + lck = lck->prev; + } + return status; + } + lck = lck->next; } grp_lock_set_owner_thread(glock); pj_grp_lock_add_ref(glock); @@ -337,17 +336,17 @@ static pj_status_t grp_lock_release(LOCK_OBJ *p) lck = glock->lock_list.prev; while (lck != &glock->lock_list) { - pj_lock_release(lck->lock); - lck = lck->prev; + pj_lock_release(lck->lock); + lck = lck->prev; } return pj_grp_lock_dec_ref(glock); } static pj_status_t grp_lock_add_handler( pj_grp_lock_t *glock, - pj_pool_t *pool, - void *comp, - void (*destroy)(void *comp), - pj_bool_t acquire_lock) + pj_pool_t *pool, + void *comp, + void (*destroy)(void *comp), + pj_bool_t acquire_lock) { grp_destroy_callback *cb; @@ -355,7 +354,7 @@ static pj_status_t grp_lock_add_handler( pj_grp_lock_t *glock, grp_lock_acquire(glock); if (pool == NULL) - pool = glock->pool; + pool = glock->pool; cb = PJ_POOL_ZALLOC_T(pool, grp_destroy_callback); cb->comp = comp; @@ -376,27 +375,27 @@ static pj_status_t grp_lock_destroy(LOCK_OBJ *p) grp_destroy_callback *cb; if (!glock->pool) { - /* already destroyed?! */ - return PJ_EINVAL; + /* already destroyed?! */ + return PJ_EINVAL; } /* Release all chained locks */ lck = glock->lock_list.next; while (lck != &glock->lock_list) { - if (lck->lock != glock->own_lock) { - int i; - for (i=0; iowner_cnt; ++i) - pj_lock_release(lck->lock); - } - lck = lck->next; + if (lck->lock != glock->own_lock) { + int i; + for (i=0; iowner_cnt; ++i) + pj_lock_release(lck->lock); + } + lck = lck->next; } /* Call callbacks */ cb = glock->destroy_list.next; while (cb != &glock->destroy_list) { - grp_destroy_callback *next = cb->next; - cb->handler(cb->comp); - cb = next; + grp_destroy_callback *next = cb->next; + cb->handler(cb->comp); + cb = next; } pj_lock_destroy(glock->own_lock); @@ -422,7 +421,7 @@ PJ_DEF(pj_status_t) pj_grp_lock_create( pj_pool_t *pool, pool = pj_pool_create(pool->factory, "glck%p", 512, 512, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; glock = PJ_POOL_ZALLOC_T(pool, pj_grp_lock_t); glock->base.lock_object = glock; @@ -441,12 +440,12 @@ PJ_DEF(pj_status_t) pj_grp_lock_create( pj_pool_t *pool, status = pj_atomic_create(pool, 0, &glock->ref_cnt); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_lock_create_recursive_mutex(pool, pool->obj_name, &glock->own_lock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; own_lock = PJ_POOL_ZALLOC_T(pool, grp_lock_item); own_lock->lock = glock->own_lock; @@ -461,16 +460,16 @@ PJ_DEF(pj_status_t) pj_grp_lock_create( pj_pool_t *pool, } PJ_DEF(pj_status_t) pj_grp_lock_create_w_handler( pj_pool_t *pool, - const pj_grp_lock_config *cfg, - void *member, + const pj_grp_lock_config *cfg, + void *member, void (*handler)(void *member), - pj_grp_lock_t **p_grp_lock) + pj_grp_lock_t **p_grp_lock) { pj_status_t status; status = pj_grp_lock_create(pool, cfg, p_grp_lock); if (status == PJ_SUCCESS) { - pj_pool_t *pool = (*p_grp_lock)->pool; + pj_pool_t *pool = (*p_grp_lock)->pool; grp_lock_add_handler(*p_grp_lock, pool, member, handler, PJ_FALSE); } @@ -505,14 +504,14 @@ PJ_DEF(pj_status_t) pj_grp_lock_replace( pj_grp_lock_t *old_lock, /* Move handlers from old to new */ ocb = old_lock->destroy_list.next; while (ocb != &old_lock->destroy_list) { - grp_destroy_callback *ncb; + grp_destroy_callback *ncb; - ncb = PJ_POOL_ALLOC_T(new_lock->pool, grp_destroy_callback); - ncb->comp = ocb->comp; - ncb->handler = ocb->handler; - pj_list_push_back(&new_lock->destroy_list, ncb); + ncb = PJ_POOL_ALLOC_T(new_lock->pool, grp_destroy_callback); + ncb->comp = ocb->comp; + ncb->handler = ocb->handler; + pj_list_push_back(&new_lock->destroy_list, ncb); - ocb = ocb->next; + ocb = ocb->next; } pj_list_init(&old_lock->destroy_list); @@ -539,13 +538,13 @@ PJ_DEF(pj_status_t) pj_grp_lock_del_handler( pj_grp_lock_t *glock, cb = glock->destroy_list.next; while (cb != &glock->destroy_list) { - if (cb->comp == comp && cb->handler == destroy) - break; - cb = cb->next; + if (cb->comp == comp && cb->handler == destroy) + break; + cb = cb->next; } if (cb != &glock->destroy_list) - pj_list_erase(cb); + pj_list_erase(cb); grp_lock_release(glock); return PJ_SUCCESS; @@ -561,8 +560,8 @@ static pj_status_t grp_lock_dec_ref(pj_grp_lock_t *glock) { int cnt; /* for debugging */ if ((cnt=pj_atomic_dec_and_get(glock->ref_cnt)) == 0) { - grp_lock_destroy(glock); - return PJ_EGONE; + grp_lock_destroy(glock); + return PJ_EGONE; } pj_assert(cnt > 0); return PJ_SUCCESS; @@ -575,9 +574,9 @@ static pj_status_t grp_lock_dec_ref_dump(pj_grp_lock_t *glock) status = grp_lock_dec_ref(glock); if (status == PJ_SUCCESS) { - pj_grp_lock_dump(glock); + pj_grp_lock_dump(glock); } else if (status == PJ_EGONE) { - PJ_LOG(4,(THIS_FILE, "Group lock %p destroyed.", glock)); + PJ_LOG(4,(THIS_FILE, "Group lock %p destroyed.", glock)); } return status; @@ -592,10 +591,10 @@ PJ_DEF(pj_status_t) pj_grp_lock_add_ref_dbg(pj_grp_lock_t *glock, pj_enter_critical_section(); if (!pj_list_empty(&glock->ref_free_list)) { - ref = glock->ref_free_list.next; - pj_list_erase(ref); + ref = glock->ref_free_list.next; + pj_list_erase(ref); } else { - ref = PJ_POOL_ALLOC_T(glock->pool, grp_lock_ref); + ref = PJ_POOL_ALLOC_T(glock->pool, grp_lock_ref); } ref->file = file; @@ -607,10 +606,10 @@ PJ_DEF(pj_status_t) pj_grp_lock_add_ref_dbg(pj_grp_lock_t *glock, status = grp_lock_add_ref(glock); if (status != PJ_SUCCESS) { - pj_enter_critical_section(); - pj_list_erase(ref); - pj_list_push_back(&glock->ref_free_list, ref); - pj_leave_critical_section(); + pj_enter_critical_section(); + pj_list_erase(ref); + pj_list_push_back(&glock->ref_free_list, ref); + pj_leave_critical_section(); } return status; @@ -628,18 +627,18 @@ PJ_DEF(pj_status_t) pj_grp_lock_dec_ref_dbg(pj_grp_lock_t *glock, /* Find the same source file */ ref = glock->ref_list.next; while (ref != &glock->ref_list) { - if (strcmp(ref->file, file) == 0) { - pj_list_erase(ref); - pj_list_push_back(&glock->ref_free_list, ref); - break; - } - ref = ref->next; + if (strcmp(ref->file, file) == 0) { + pj_list_erase(ref); + pj_list_push_back(&glock->ref_free_list, ref); + break; + } + ref = ref->next; } pj_leave_critical_section(); if (ref == &glock->ref_list) { - PJ_LOG(2,(THIS_FILE, "pj_grp_lock_dec_ref_dbg() could not find " - "matching ref for %s", file)); + PJ_LOG(2,(THIS_FILE, "pj_grp_lock_dec_ref_dbg() could not find " + "matching ref for %s", file)); } return grp_lock_dec_ref_dump(glock); @@ -671,13 +670,13 @@ PJ_DEF(pj_status_t) pj_grp_lock_chain_lock( pj_grp_lock_t *glock, grp_lock_acquire(glock); for (i=0; iowner_cnt; ++i) - pj_lock_acquire(lock); + pj_lock_acquire(lock); lck = glock->lock_list.next; while (lck != &glock->lock_list) { - if (lck->prio >= pos) - break; - lck = lck->next; + if (lck->prio >= pos) + break; + lck = lck->next; } new_lck = PJ_POOL_ZALLOC_T(glock->pool, grp_lock_item); @@ -699,17 +698,17 @@ PJ_DEF(pj_status_t) pj_grp_lock_unchain_lock( pj_grp_lock_t *glock, lck = glock->lock_list.next; while (lck != &glock->lock_list) { - if (lck->lock == lock) - break; - lck = lck->next; + if (lck->lock == lock) + break; + lck = lck->next; } if (lck != &glock->lock_list) { - int i; + int i; - pj_list_erase(lck); - for (i=0; iowner_cnt; ++i) - pj_lock_release(lck->lock); + pj_list_erase(lck); + for (i=0; iowner_cnt; ++i) + pj_lock_release(lck->lock); } grp_lock_release(glock); @@ -731,40 +730,40 @@ PJ_DEF(void) pj_grp_lock_dump(pj_grp_lock_t *grp_lock) ref = grp_lock->ref_list.next; while (ref != &grp_lock->ref_list && info.slen < sizeof(info_buf)) { - char *start = info.ptr + info.slen; - int max_len = sizeof(info_buf) - info.slen; - int len; + char *start = info.ptr + info.slen; + int max_len = sizeof(info_buf) - info.slen; + int len; - len = pj_ansi_snprintf(start, max_len, "\t%s:%d\n", ref->file, ref->line); - if (len < 1 || len >= max_len) { - len = strlen(ref->file); - if (len > max_len - 1) - len = max_len - 1; + len = pj_ansi_snprintf(start, max_len, "\t%s:%d\n", ref->file, ref->line); + if (len < 1 || len >= max_len) { + len = strlen(ref->file); + if (len > max_len - 1) + len = max_len - 1; - memcpy(start, ref->file, len); - start[len++] = '\n'; - } + memcpy(start, ref->file, len); + start[len++] = '\n'; + } - info.slen += len; + info.slen += len; - ref = ref->next; + ref = ref->next; } if (ref != &grp_lock->ref_list) { - int i; - for (i=0; i<4; ++i) - info_buf[sizeof(info_buf)-i-1] = '.'; + int i; + for (i=0; i<4; ++i) + info_buf[sizeof(info_buf)-i-1] = '.'; } info.ptr[info.slen-1] = '\0'; pj_leave_critical_section(); PJ_LOG(4,(THIS_FILE, "Group lock %p, ref_cnt=%d. Reference holders:\n%s", - grp_lock, pj_grp_lock_get_ref(grp_lock)-1, info.ptr)); + grp_lock, pj_grp_lock_get_ref(grp_lock)-1, info.ptr)); grp_lock_dec_ref(grp_lock); #else PJ_LOG(4,(THIS_FILE, "Group lock %p, ref_cnt=%d.", - grp_lock, pj_grp_lock_get_ref(grp_lock))); + grp_lock, pj_grp_lock_get_ref(grp_lock))); #endif } diff --git a/pjlib/src/pj/log.c b/pjlib/src/pj/log.c index 7bf21a8466..907a41fd86 100644 --- a/pjlib/src/pj/log.c +++ b/pjlib/src/pj/log.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,59 +45,59 @@ static int log_indent; static pj_log_func *log_writer = &pj_log_write; static unsigned log_decor = PJ_LOG_HAS_TIME | PJ_LOG_HAS_MICRO_SEC | - PJ_LOG_HAS_SENDER | PJ_LOG_HAS_NEWLINE | - PJ_LOG_HAS_SPACE | PJ_LOG_HAS_THREAD_SWC | - PJ_LOG_HAS_INDENT + PJ_LOG_HAS_SENDER | PJ_LOG_HAS_NEWLINE | + PJ_LOG_HAS_SPACE | PJ_LOG_HAS_THREAD_SWC | + PJ_LOG_HAS_INDENT #if (defined(PJ_WIN32) && PJ_WIN32!=0) || \ (defined(PJ_WIN64) && PJ_WIN64!=0) - | PJ_LOG_HAS_COLOR + | PJ_LOG_HAS_COLOR #endif - ; + ; static pj_color_t PJ_LOG_COLOR_0 = PJ_TERM_COLOR_BRIGHT | PJ_TERM_COLOR_R; static pj_color_t PJ_LOG_COLOR_1 = PJ_TERM_COLOR_BRIGHT | PJ_TERM_COLOR_R; static pj_color_t PJ_LOG_COLOR_2 = PJ_TERM_COLOR_BRIGHT | - PJ_TERM_COLOR_R | - PJ_TERM_COLOR_G; + PJ_TERM_COLOR_R | + PJ_TERM_COLOR_G; static pj_color_t PJ_LOG_COLOR_3 = PJ_TERM_COLOR_BRIGHT | - PJ_TERM_COLOR_R | - PJ_TERM_COLOR_G | - PJ_TERM_COLOR_B; + PJ_TERM_COLOR_R | + PJ_TERM_COLOR_G | + PJ_TERM_COLOR_B; static pj_color_t PJ_LOG_COLOR_4 = PJ_TERM_COLOR_R | - PJ_TERM_COLOR_G | - PJ_TERM_COLOR_B; + PJ_TERM_COLOR_G | + PJ_TERM_COLOR_B; static pj_color_t PJ_LOG_COLOR_5 = PJ_TERM_COLOR_R | - PJ_TERM_COLOR_G | - PJ_TERM_COLOR_B; + PJ_TERM_COLOR_G | + PJ_TERM_COLOR_B; static pj_color_t PJ_LOG_COLOR_6 = PJ_TERM_COLOR_R | - PJ_TERM_COLOR_G | - PJ_TERM_COLOR_B; + PJ_TERM_COLOR_G | + PJ_TERM_COLOR_B; /* Default terminal color */ static pj_color_t PJ_LOG_COLOR_77 = PJ_TERM_COLOR_R | - PJ_TERM_COLOR_G | - PJ_TERM_COLOR_B; + PJ_TERM_COLOR_G | + PJ_TERM_COLOR_B; #if PJ_LOG_USE_STACK_BUFFER==0 static char log_buffer[PJ_LOG_MAX_SIZE]; #endif -#define LOG_MAX_INDENT 80 +#define LOG_MAX_INDENT 80 #if PJ_HAS_THREADS static void logging_shutdown(void) { if (thread_suspended_tls_id != -1) { - pj_thread_local_free(thread_suspended_tls_id); - thread_suspended_tls_id = -1; + pj_thread_local_free(thread_suspended_tls_id); + thread_suspended_tls_id = -1; } # if PJ_LOG_ENABLE_INDENT if (thread_indent_tls_id != -1) { - pj_thread_local_free(thread_indent_tls_id); - thread_indent_tls_id = -1; + pj_thread_local_free(thread_indent_tls_id); + thread_indent_tls_id = -1; } # endif } -#endif /* PJ_HAS_THREADS */ +#endif /* PJ_HAS_THREADS */ #if PJ_LOG_ENABLE_INDENT && PJ_HAS_THREADS PJ_DEF(void) pj_log_set_indent(int indent) @@ -123,7 +122,7 @@ static int log_get_raw_indent(void) { return log_indent; } -#endif /* PJ_LOG_ENABLE_INDENT && PJ_HAS_THREADS */ +#endif /* PJ_LOG_ENABLE_INDENT && PJ_HAS_THREADS */ PJ_DEF(int) pj_log_get_indent(void) { @@ -150,20 +149,20 @@ pj_status_t pj_log_init(void) { #if PJ_HAS_THREADS if (thread_suspended_tls_id == -1) { - pj_status_t status; - status = pj_thread_local_alloc(&thread_suspended_tls_id); - if (status != PJ_SUCCESS) - return status; + pj_status_t status; + status = pj_thread_local_alloc(&thread_suspended_tls_id); + if (status != PJ_SUCCESS) + return status; # if PJ_LOG_ENABLE_INDENT - status = pj_thread_local_alloc(&thread_indent_tls_id); - if (status != PJ_SUCCESS) { - pj_thread_local_free(thread_suspended_tls_id); - thread_suspended_tls_id = -1; - return status; - } + status = pj_thread_local_alloc(&thread_indent_tls_id); + if (status != PJ_SUCCESS) { + pj_thread_local_free(thread_suspended_tls_id); + thread_suspended_tls_id = -1; + return status; + } # endif - pj_atexit(&logging_shutdown); + pj_atexit(&logging_shutdown); } #endif g_last_thread = NULL; @@ -200,49 +199,49 @@ PJ_DEF(void) pj_log_set_color(int level, pj_color_t color) { switch (level) { - case 0: PJ_LOG_COLOR_0 = color; - break; - case 1: PJ_LOG_COLOR_1 = color; - break; - case 2: PJ_LOG_COLOR_2 = color; - break; - case 3: PJ_LOG_COLOR_3 = color; - break; - case 4: PJ_LOG_COLOR_4 = color; - break; - case 5: PJ_LOG_COLOR_5 = color; - break; - case 6: PJ_LOG_COLOR_6 = color; - break; - /* Default terminal color */ - case 77: PJ_LOG_COLOR_77 = color; - break; - default: - /* Do nothing */ - break; + case 0: PJ_LOG_COLOR_0 = color; + break; + case 1: PJ_LOG_COLOR_1 = color; + break; + case 2: PJ_LOG_COLOR_2 = color; + break; + case 3: PJ_LOG_COLOR_3 = color; + break; + case 4: PJ_LOG_COLOR_4 = color; + break; + case 5: PJ_LOG_COLOR_5 = color; + break; + case 6: PJ_LOG_COLOR_6 = color; + break; + /* Default terminal color */ + case 77: PJ_LOG_COLOR_77 = color; + break; + default: + /* Do nothing */ + break; } } PJ_DEF(pj_color_t) pj_log_get_color(int level) { switch (level) { - case 0: - return PJ_LOG_COLOR_0; - case 1: - return PJ_LOG_COLOR_1; - case 2: - return PJ_LOG_COLOR_2; - case 3: - return PJ_LOG_COLOR_3; - case 4: - return PJ_LOG_COLOR_4; - case 5: - return PJ_LOG_COLOR_5; - case 6: - return PJ_LOG_COLOR_6; - default: - /* Return default terminal color */ - return PJ_LOG_COLOR_77; + case 0: + return PJ_LOG_COLOR_0; + case 1: + return PJ_LOG_COLOR_1; + case 2: + return PJ_LOG_COLOR_2; + case 3: + return PJ_LOG_COLOR_3; + case 4: + return PJ_LOG_COLOR_4; + case 5: + return PJ_LOG_COLOR_5; + case 6: + return PJ_LOG_COLOR_6; + default: + /* Return default terminal color */ + return PJ_LOG_COLOR_77; } } @@ -276,21 +275,21 @@ PJ_DEF(pj_log_func*) pj_log_get_log_func(void) */ static void suspend_logging(int *saved_level) { - /* Save the level regardless, just in case PJLIB is shutdown - * between suspend and resume. - */ - *saved_level = pj_log_max_level; + /* Save the level regardless, just in case PJLIB is shutdown + * between suspend and resume. + */ + *saved_level = pj_log_max_level; #if PJ_HAS_THREADS if (thread_suspended_tls_id != -1) { - pj_thread_local_set(thread_suspended_tls_id, - (void*)(pj_ssize_t)PJ_TRUE); + pj_thread_local_set(thread_suspended_tls_id, + (void*)(pj_ssize_t)PJ_TRUE); } else #endif { - pj_log_max_level = 0; + pj_log_max_level = 0; } } @@ -300,17 +299,17 @@ static void resume_logging(int *saved_level) #if PJ_HAS_THREADS if (thread_suspended_tls_id != -1) { - pj_thread_local_set(thread_suspended_tls_id, - (void*)(pj_size_t)PJ_FALSE); + pj_thread_local_set(thread_suspended_tls_id, + (void*)(pj_size_t)PJ_FALSE); } else #endif { - /* Only revert the level if application doesn't change the - * logging level between suspend and resume. - */ - if (pj_log_max_level==0 && *saved_level) - pj_log_max_level = *saved_level; + /* Only revert the level if application doesn't change the + * logging level between suspend and resume. + */ + if (pj_log_max_level==0 && *saved_level) + pj_log_max_level = *saved_level; } } @@ -320,17 +319,17 @@ static pj_bool_t is_logging_suspended(void) #if PJ_HAS_THREADS if (thread_suspended_tls_id != -1) { - return pj_thread_local_get(thread_suspended_tls_id) != NULL; + return pj_thread_local_get(thread_suspended_tls_id) != NULL; } else #endif { - return pj_log_max_level == 0; + return pj_log_max_level == 0; } } PJ_DEF(void) pj_log( const char *sender, int level, - const char *format, va_list marker) + const char *format, va_list marker) { pj_time_val now; pj_parsed_time ptime; @@ -343,10 +342,10 @@ PJ_DEF(void) pj_log( const char *sender, int level, PJ_CHECK_STACK(); if (level > pj_log_max_level) - return; + return; if (is_logging_suspended()) - return; + return; /* Temporarily disable logging for this thread. Some of PJLIB APIs that * this function calls below will recursively call the logging function @@ -360,95 +359,95 @@ PJ_DEF(void) pj_log( const char *sender, int level, pre = log_buffer; if (log_decor & PJ_LOG_HAS_LEVEL_TEXT) { - static const char *ltexts[] = { "FATAL:", "ERROR:", " WARN:", - " INFO:", "DEBUG:", "TRACE:", "DETRC:"}; - pj_ansi_strcpy(pre, ltexts[level]); - pre += 6; + static const char *ltexts[] = { "FATAL:", "ERROR:", " WARN:", + " INFO:", "DEBUG:", "TRACE:", "DETRC:"}; + pj_ansi_strcpy(pre, ltexts[level]); + pre += 6; } if (log_decor & PJ_LOG_HAS_DAY_NAME) { - static const char *wdays[] = { "Sun", "Mon", "Tue", "Wed", - "Thu", "Fri", "Sat"}; - pj_ansi_strcpy(pre, wdays[ptime.wday]); - pre += 3; + static const char *wdays[] = { "Sun", "Mon", "Tue", "Wed", + "Thu", "Fri", "Sat"}; + pj_ansi_strcpy(pre, wdays[ptime.wday]); + pre += 3; } if (log_decor & PJ_LOG_HAS_YEAR) { - if (pre!=log_buffer) *pre++ = ' '; - pre += pj_utoa(ptime.year, pre); + if (pre!=log_buffer) *pre++ = ' '; + pre += pj_utoa(ptime.year, pre); } if (log_decor & PJ_LOG_HAS_MONTH) { - *pre++ = '-'; - pre += pj_utoa_pad(ptime.mon+1, pre, 2, '0'); + *pre++ = '-'; + pre += pj_utoa_pad(ptime.mon+1, pre, 2, '0'); } if (log_decor & PJ_LOG_HAS_DAY_OF_MON) { - *pre++ = '-'; - pre += pj_utoa_pad(ptime.day, pre, 2, '0'); + *pre++ = '-'; + pre += pj_utoa_pad(ptime.day, pre, 2, '0'); } if (log_decor & PJ_LOG_HAS_TIME) { - if (pre!=log_buffer) *pre++ = ' '; - pre += pj_utoa_pad(ptime.hour, pre, 2, '0'); - *pre++ = ':'; - pre += pj_utoa_pad(ptime.min, pre, 2, '0'); - *pre++ = ':'; - pre += pj_utoa_pad(ptime.sec, pre, 2, '0'); + if (pre!=log_buffer) *pre++ = ' '; + pre += pj_utoa_pad(ptime.hour, pre, 2, '0'); + *pre++ = ':'; + pre += pj_utoa_pad(ptime.min, pre, 2, '0'); + *pre++ = ':'; + pre += pj_utoa_pad(ptime.sec, pre, 2, '0'); } if (log_decor & PJ_LOG_HAS_MICRO_SEC) { - *pre++ = '.'; - pre += pj_utoa_pad(ptime.msec, pre, 3, '0'); + *pre++ = '.'; + pre += pj_utoa_pad(ptime.msec, pre, 3, '0'); } if (log_decor & PJ_LOG_HAS_SENDER) { - enum { SENDER_WIDTH = PJ_LOG_SENDER_WIDTH }; - pj_size_t sender_len = strlen(sender); - if (pre!=log_buffer) *pre++ = ' '; - if (sender_len <= SENDER_WIDTH) { - while (sender_len < SENDER_WIDTH) - *pre++ = ' ', ++sender_len; - while (*sender) - *pre++ = *sender++; - } else { - int i; - for (i=0; i 0) { - pj_memset(pre, PJ_LOG_INDENT_CHAR, indent); - pre += indent; - } + int indent = pj_log_get_indent(); + if (indent > 0) { + pj_memset(pre, PJ_LOG_INDENT_CHAR, indent); + pre += indent; + } } #endif @@ -456,33 +455,33 @@ PJ_DEF(void) pj_log( const char *sender, int level, /* Print the whole message to the string log_buffer. */ print_len = pj_ansi_vsnprintf(pre, sizeof(log_buffer)-len, format, - marker); + marker); if (print_len < 0) { - level = 1; - print_len = pj_ansi_snprintf(pre, sizeof(log_buffer)-len, - ""); + level = 1; + print_len = pj_ansi_snprintf(pre, sizeof(log_buffer)-len, + ""); } if (print_len < 1 || print_len >= (int)(sizeof(log_buffer)-len)) { - print_len = sizeof(log_buffer) - len - 1; + print_len = sizeof(log_buffer) - len - 1; } len = len + print_len; if (len > 0 && len < (int)sizeof(log_buffer)-2) { - if (log_decor & PJ_LOG_HAS_CR) { - log_buffer[len++] = '\r'; - } - if (log_decor & PJ_LOG_HAS_NEWLINE) { - log_buffer[len++] = '\n'; - } - log_buffer[len] = '\0'; + if (log_decor & PJ_LOG_HAS_CR) { + log_buffer[len++] = '\r'; + } + if (log_decor & PJ_LOG_HAS_NEWLINE) { + log_buffer[len++] = '\n'; + } + log_buffer[len] = '\0'; } else { - len = sizeof(log_buffer)-1; - if (log_decor & PJ_LOG_HAS_CR) { - log_buffer[sizeof(log_buffer)-3] = '\r'; - } - if (log_decor & PJ_LOG_HAS_NEWLINE) { - log_buffer[sizeof(log_buffer)-2] = '\n'; - } - log_buffer[sizeof(log_buffer)-1] = '\0'; + len = sizeof(log_buffer)-1; + if (log_decor & PJ_LOG_HAS_CR) { + log_buffer[sizeof(log_buffer)-3] = '\r'; + } + if (log_decor & PJ_LOG_HAS_NEWLINE) { + log_buffer[sizeof(log_buffer)-2] = '\n'; + } + log_buffer[sizeof(log_buffer)-1] = '\0'; } /* It should be safe to resume logging at this point. Application can @@ -491,7 +490,7 @@ PJ_DEF(void) pj_log( const char *sender, int level, resume_logging(&saved_level); if (log_writer) - (*log_writer)(level, log_buffer, len); + (*log_writer)(level, log_buffer, len); } /* @@ -511,7 +510,7 @@ PJ_DEF(void) pj_log_1(const char *obj, const char *format, ...) pj_log(obj, 1, format, arg); va_end(arg); } -#endif /* PJ_LOG_MAX_LEVEL >= 1 */ +#endif /* PJ_LOG_MAX_LEVEL >= 1 */ #if PJ_LOG_MAX_LEVEL >= 2 PJ_DEF(void) pj_log_2(const char *obj, const char *format, ...) diff --git a/pjlib/src/pj/log_writer_printk.c b/pjlib/src/pj/log_writer_printk.c index 51ab669949..e99f5f9d5f 100644 --- a/pjlib/src/pj/log_writer_printk.c +++ b/pjlib/src/pj/log_writer_printk.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pj/log_writer_stdout.c b/pjlib/src/pj/log_writer_stdout.c index ede1505970..7a09393b09 100644 --- a/pjlib/src/pj/log_writer_stdout.c +++ b/pjlib/src/pj/log_writer_stdout.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -47,11 +46,11 @@ PJ_DEF(void) pj_log_write(int level, const char *buffer, int len) /* Copy to terminal/file. */ if (pj_log_get_decor() & PJ_LOG_HAS_COLOR) { - term_set_color(level); - printf("%s", buffer); - term_restore_color(); + term_set_color(level); + printf("%s", buffer); + term_restore_color(); } else { - printf("%s", buffer); + printf("%s", buffer); } } diff --git a/pjlib/src/pj/log_writer_symbian_console.cpp b/pjlib/src/pj/log_writer_symbian_console.cpp index 0ecb82659b..aa13c5e3c1 100644 --- a/pjlib/src/pj/log_writer_symbian_console.cpp +++ b/pjlib/src/pj/log_writer_symbian_console.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pj/os_core_darwin.m b/pjlib/src/pj/os_core_darwin.m index 7b21f8720c..a3896cec3d 100644 --- a/pjlib/src/pj/os_core_darwin.m +++ b/pjlib/src/pj/os_core_darwin.m @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjlib/src/pj/os_core_symbian.cpp b/pjlib/src/pj/os_core_symbian.cpp index d6a1df22f3..8dba29dd9e 100644 --- a/pjlib/src/pj/os_core_symbian.cpp +++ b/pjlib/src/pj/os_core_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,10 +30,10 @@ #include "os_symbian.h" -#define PJ_MAX_TLS 32 -#define DUMMY_MUTEX ((pj_mutex_t*)101) -#define DUMMY_SEMAPHORE ((pj_sem_t*)102) -#define THIS_FILE "os_core_symbian.c" +#define PJ_MAX_TLS 32 +#define DUMMY_MUTEX ((pj_mutex_t*)101) +#define DUMMY_SEMAPHORE ((pj_sem_t*)102) +#define THIS_FILE "os_core_symbian.c" /* Default message slot number for RSocketServ::Connect(). * Increase it to 32 from the default 8 (KESockDefaultMessageSlots) @@ -51,22 +50,22 @@ struct pj_thread_t { - char obj_name[PJ_MAX_OBJ_NAME]; - void *tls_values[PJ_MAX_TLS]; + char obj_name[PJ_MAX_OBJ_NAME]; + void *tls_values[PJ_MAX_TLS]; #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0 - pj_uint32_t stk_size; - pj_uint32_t stk_max_usage; - char *stk_start; - const char *caller_file; - int caller_line; + pj_uint32_t stk_size; + pj_uint32_t stk_max_usage; + char *stk_start; + const char *caller_file; + int caller_line; #endif } main_thread; struct pj_atomic_t { - pj_atomic_value_t value; + pj_atomic_value_t value; }; struct pj_sem_t @@ -194,7 +193,7 @@ TInt PjSymbianOS::Initialize() #if 0 pj_assert(console_ == NULL); TRAPD(err, console_ = Console::NewL(_L("PJLIB"), - TSize(KConsFullScreen,KConsFullScreen))); + TSize(KConsFullScreen,KConsFullScreen))); return err; #endif @@ -202,40 +201,40 @@ TInt PjSymbianOS::Initialize() * in the parameters */ if (!isSocketServInitialized_ && appSocketServ_ == NULL) { - err = socketServ_.Connect(PJ_SYMBIAN_SOCK_MSG_SLOTS); - if (err != KErrNone) - goto on_error; + err = socketServ_.Connect(PJ_SYMBIAN_SOCK_MSG_SLOTS); + if (err != KErrNone) + goto on_error; - isSocketServInitialized_ = true; + isSocketServInitialized_ = true; } if (!isResolverInitialized_) { - if (appHostResolver_ == NULL) { - if (Connection()) - err = hostResolver_.Open(SocketServ(), KAfInet, KSockStream, - *Connection()); - else - err = hostResolver_.Open(SocketServ(), KAfInet, KSockStream); - - if (err != KErrNone) - goto on_error; - } - + if (appHostResolver_ == NULL) { + if (Connection()) + err = hostResolver_.Open(SocketServ(), KAfInet, KSockStream, + *Connection()); + else + err = hostResolver_.Open(SocketServ(), KAfInet, KSockStream); + + if (err != KErrNone) + goto on_error; + } + #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6!=0 - if (appHostResolver6_ == NULL) { - if (Connection()) - err = hostResolver6_.Open(SocketServ(), KAfInet6, KSockStream, - *Connection()); - else - err = hostResolver6_.Open(SocketServ(), KAfInet6, KSockStream); - - if (err != KErrNone) - goto on_error; - } + if (appHostResolver6_ == NULL) { + if (Connection()) + err = hostResolver6_.Open(SocketServ(), KAfInet6, KSockStream, + *Connection()); + else + err = hostResolver6_.Open(SocketServ(), KAfInet6, KSockStream); + + if (err != KErrNone) + goto on_error; + } #endif - - - isResolverInitialized_ = true; + + + isResolverInitialized_ = true; } isConnectionUp_ = true; @@ -253,16 +252,16 @@ void PjSymbianOS::Shutdown() isConnectionUp_ = false; if (isResolverInitialized_) { - hostResolver_.Close(); + hostResolver_.Close(); #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6!=0 - hostResolver6_.Close(); + hostResolver6_.Close(); #endif - isResolverInitialized_ = false; + isResolverInitialized_ = false; } if (isSocketServInitialized_) { - socketServ_.Close(); - isSocketServInitialized_ = false; + socketServ_.Close(); + isSocketServInitialized_ = false; } delete console_; @@ -333,13 +332,13 @@ PJ_DEF(void) pj_symbianos_set_connection_status(pj_bool_t up) */ PJ_DEF(pj_status_t) pj_init(void) { - char stack_ptr; + char stack_ptr; pj_status_t status; /* Check if PJLIB have been initialized */ if (initialized) { - ++initialized; - return PJ_SUCCESS; + ++initialized; + return PJ_SUCCESS; } pj_ansi_strcpy(main_thread.obj_name, "pjthread"); @@ -355,7 +354,7 @@ PJ_DEF(pj_status_t) pj_init(void) TInt err; err = os->Initialize(); if (err != KErrNone) - return PJ_RETURN_OS_ERROR(err); + return PJ_RETURN_OS_ERROR(err); /* Init logging */ pj_log_init(); @@ -391,7 +390,7 @@ PJ_DEF(pj_status_t) pj_init(void) PJ_DEF(pj_status_t) pj_atexit(pj_exit_callback func) { if (atexit_count >= PJ_ARRAY_SIZE(atexit_func)) - return PJ_ETOOMANY; + return PJ_ETOOMANY; atexit_func[atexit_count++] = func; return PJ_SUCCESS; @@ -404,18 +403,18 @@ PJ_DEF(void) pj_shutdown(void) /* Only perform shutdown operation when 'initialized' reaches zero */ pj_assert(initialized > 0); if (--initialized != 0) - return; + return; /* Call atexit() functions */ while (atexit_count > 0) { - (*atexit_func[atexit_count-1])(); - --atexit_count; + (*atexit_func[atexit_count-1])(); + --atexit_count; } /* Free exception ID */ if (PJ_NO_MEMORY_EXCEPTION != -1) { - pj_exception_id_free(PJ_NO_MEMORY_EXCEPTION); - PJ_NO_MEMORY_EXCEPTION = -1; + pj_exception_id_free(PJ_NO_MEMORY_EXCEPTION); + PJ_NO_MEMORY_EXCEPTION = -1; } /* Clear static variables */ @@ -436,8 +435,8 @@ class CPollTimeoutTimer : public CActive virtual void RunL(); virtual void DoCancel(); -private: - RTimer rtimer_; +private: + RTimer rtimer_; explicit CPollTimeoutTimer(TInt prio); void ConstructL(int msec); @@ -490,10 +489,10 @@ PJ_DEF(pj_bool_t) pj_symbianos_poll(int priority, int ms_timeout) CPollTimeoutTimer *timer = NULL; if (priority==-1) - priority = EPriorityNull; + priority = EPriorityNull; if (ms_timeout >= 0) { - timer = CPollTimeoutTimer::NewL(ms_timeout, priority); + timer = CPollTimeoutTimer::NewL(ms_timeout, priority); } PjSymbianOS::Instance()->WaitForActiveObjects(priority); @@ -501,14 +500,14 @@ PJ_DEF(pj_bool_t) pj_symbianos_poll(int priority, int ms_timeout) if (timer) { bool timer_is_active = timer->IsActive(); - timer->Cancel(); + timer->Cancel(); delete timer; - return timer_is_active ? PJ_TRUE : PJ_FALSE; - + return timer_is_active ? PJ_TRUE : PJ_FALSE; + } else { - return PJ_TRUE; + return PJ_TRUE; } } @@ -576,7 +575,7 @@ PJ_DEF(void*) pj_thread_get_os_handle(pj_thread_t *thread) * pj_thread_register(..) */ PJ_DEF(pj_status_t) pj_thread_register ( const char *cstr_thread_name, - pj_thread_desc desc, + pj_thread_desc desc, pj_thread_t **thread_ptr) { PJ_UNUSED_ARG(cstr_thread_name); @@ -590,12 +589,12 @@ PJ_DEF(pj_status_t) pj_thread_register ( const char *cstr_thread_name, * pj_thread_create(...) */ PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool, - const char *thread_name, - pj_thread_proc *proc, - void *arg, - pj_size_t stack_size, - unsigned flags, - pj_thread_t **ptr_thread) + const char *thread_name, + pj_thread_proc *proc, + void *arg, + pj_size_t stack_size, + unsigned flags, + pj_thread_t **ptr_thread) { PJ_UNUSED_ARG(pool); PJ_UNUSED_ARG(thread_name); @@ -675,12 +674,12 @@ PJ_DEF(pj_status_t) pj_thread_local_alloc(long *index) /* Find unused TLS variable */ for (i=0; i= 0 && index < (int)PJ_ARRAY_SIZE(tls_vars) && - tls_vars[index] != 0, return); + tls_vars[index] != 0, return); tls_vars[index] = 0; } @@ -708,7 +707,7 @@ PJ_DEF(pj_status_t) pj_thread_local_set(long index, void *value) pj_thread_t *rec = pj_thread_this(); PJ_ASSERT_RETURN(index >= 0 && index < (int)PJ_ARRAY_SIZE(tls_vars) && - tls_vars[index] != 0, PJ_EINVAL); + tls_vars[index] != 0, PJ_EINVAL); rec->tls_values[index] = value; return PJ_SUCCESS; @@ -722,7 +721,7 @@ PJ_DEF(void*) pj_thread_local_get(long index) pj_thread_t *rec = pj_thread_this(); PJ_ASSERT_RETURN(index >= 0 && index < (int)PJ_ARRAY_SIZE(tls_vars) && - tls_vars[index] != 0, NULL); + tls_vars[index] != 0, NULL); return rec->tls_values[index]; } @@ -733,8 +732,8 @@ PJ_DEF(void*) pj_thread_local_get(long index) * Create atomic variable. */ PJ_DEF(pj_status_t) pj_atomic_create( pj_pool_t *pool, - pj_atomic_value_t initial, - pj_atomic_t **atomic ) + pj_atomic_value_t initial, + pj_atomic_t **atomic ) { *atomic = (pj_atomic_t*)pj_pool_alloc(pool, sizeof(struct pj_atomic_t)); (*atomic)->value = initial; @@ -756,7 +755,7 @@ PJ_DEF(pj_status_t) pj_atomic_destroy( pj_atomic_t *atomic_var ) * Set the value of an atomic type, and return the previous value. */ PJ_DEF(void) pj_atomic_set( pj_atomic_t *atomic_var, - pj_atomic_value_t value) + pj_atomic_value_t value) { atomic_var->value = value; } @@ -795,7 +794,7 @@ PJ_DEF(pj_atomic_value_t) pj_atomic_inc_and_get(pj_atomic_t *atomic_var) PJ_DEF(void) pj_atomic_dec(pj_atomic_t *atomic_var) { --atomic_var->value; -} +} /* @@ -811,7 +810,7 @@ PJ_DEF(pj_atomic_value_t) pj_atomic_dec_and_get(pj_atomic_t *atomic_var) * Add a value to an atomic type. */ PJ_DEF(void) pj_atomic_add( pj_atomic_t *atomic_var, - pj_atomic_value_t value) + pj_atomic_value_t value) { atomic_var->value += value; } @@ -821,7 +820,7 @@ PJ_DEF(void) pj_atomic_add( pj_atomic_t *atomic_var, * Add a value to an atomic type and get the result. */ PJ_DEF(pj_atomic_value_t) pj_atomic_add_and_get( pj_atomic_t *atomic_var, - pj_atomic_value_t value) + pj_atomic_value_t value) { atomic_var->value += value; return atomic_var->value; @@ -833,7 +832,7 @@ PJ_DEF(pj_atomic_value_t) pj_atomic_add_and_get( pj_atomic_t *atomic_var, PJ_DEF(pj_status_t) pj_mutex_create( pj_pool_t *pool, const char *name, - int type, + int type, pj_mutex_t **mutex) { PJ_UNUSED_ARG(pool); @@ -849,15 +848,15 @@ PJ_DEF(pj_status_t) pj_mutex_create( pj_pool_t *pool, */ PJ_DEF(pj_status_t) pj_mutex_create_simple( pj_pool_t *pool, const char *name, - pj_mutex_t **mutex ) + pj_mutex_t **mutex ) { return pj_mutex_create(pool, name, PJ_MUTEX_SIMPLE, mutex); } PJ_DEF(pj_status_t) pj_mutex_create_recursive( pj_pool_t *pool, - const char *name, - pj_mutex_t **mutex ) + const char *name, + pj_mutex_t **mutex ) { return pj_mutex_create(pool, name, PJ_MUTEX_RECURSE, mutex); } @@ -934,9 +933,9 @@ PJ_DEF(void) pj_leave_critical_section(void) */ PJ_DEF(pj_status_t) pj_sem_create( pj_pool_t *pool, const char *name, - unsigned initial, + unsigned initial, unsigned max, - pj_sem_t **p_sem) + pj_sem_t **p_sem) { pj_sem_t *sem; @@ -958,11 +957,11 @@ PJ_DEF(pj_status_t) pj_sem_create( pj_pool_t *pool, PJ_DEF(pj_status_t) pj_sem_wait(pj_sem_t *sem) { if (sem->value > 0) { - sem->value--; - return PJ_SUCCESS; + sem->value--; + return PJ_SUCCESS; } else { - pj_assert(!"Unexpected!"); - return PJ_EINVALIDOP; + pj_assert(!"Unexpected!"); + return PJ_EINVALIDOP; } } @@ -973,11 +972,11 @@ PJ_DEF(pj_status_t) pj_sem_wait(pj_sem_t *sem) PJ_DEF(pj_status_t) pj_sem_trywait(pj_sem_t *sem) { if (sem->value > 0) { - sem->value--; - return PJ_SUCCESS; + sem->value--; + return PJ_SUCCESS; } else { - pj_assert(!"Unexpected!"); - return PJ_EINVALIDOP; + pj_assert(!"Unexpected!"); + return PJ_EINVALIDOP; } } @@ -1016,16 +1015,16 @@ PJ_DEF(void) pj_thread_check_stack(const char *file, int line) /* Calculate current usage. */ usage = (&stk_ptr > thread->stk_start) ? &stk_ptr - thread->stk_start : - thread->stk_start - &stk_ptr; + thread->stk_start - &stk_ptr; /* Assert if stack usage is dangerously high. */ pj_assert("STACK OVERFLOW!! " && (usage <= thread->stk_size - 128)); /* Keep statistic. */ if (usage > thread->stk_max_usage) { - thread->stk_max_usage = usage; - thread->caller_file = file; - thread->caller_line = line; + thread->stk_max_usage = usage; + thread->caller_file = file; + thread->caller_line = line; } } @@ -1041,8 +1040,8 @@ PJ_DEF(pj_uint32_t) pj_thread_get_stack_max_usage(pj_thread_t *thread) * Dump thread stack status. */ PJ_DEF(pj_status_t) pj_thread_get_stack_info(pj_thread_t *thread, - const char **file, - int *line) + const char **file, + int *line) { pj_assert(thread); @@ -1051,7 +1050,7 @@ PJ_DEF(pj_status_t) pj_thread_get_stack_info(pj_thread_t *thread, return 0; } -#endif /* PJ_OS_HAS_CHECK_STACK */ +#endif /* PJ_OS_HAS_CHECK_STACK */ /* * pj_run_app() diff --git a/pjlib/src/pj/os_core_unix.c b/pjlib/src/pj/os_core_unix.c index e9772ceca9..79ee53b926 100644 --- a/pjlib/src/pj/os_core_unix.c +++ b/pjlib/src/pj/os_core_unix.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -43,8 +42,8 @@ # include #endif -#include // getpid() -#include // errno +#include // getpid() +#include // errno #include #if defined(PJ_HAS_PTHREAD_NP_H) && PJ_HAS_PTHREAD_NP_H != 0 @@ -79,38 +78,38 @@ JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) struct pj_thread_t { - char obj_name[PJ_MAX_OBJ_NAME]; - pthread_t thread; + char obj_name[PJ_MAX_OBJ_NAME]; + pthread_t thread; pj_thread_proc *proc; - void *arg; - pj_uint32_t signature1; - pj_uint32_t signature2; + void *arg; + pj_uint32_t signature1; + pj_uint32_t signature2; - pj_mutex_t *suspended_mutex; + pj_mutex_t *suspended_mutex; #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0 - pj_uint32_t stk_size; - pj_uint32_t stk_max_usage; - char *stk_start; - const char *caller_file; - int caller_line; + pj_uint32_t stk_size; + pj_uint32_t stk_max_usage; + char *stk_start; + const char *caller_file; + int caller_line; #endif }; struct pj_atomic_t { - pj_mutex_t *mutex; - pj_atomic_value_t value; + pj_mutex_t *mutex; + pj_atomic_value_t value; }; struct pj_mutex_t { pthread_mutex_t mutex; - char obj_name[PJ_MAX_OBJ_NAME]; + char obj_name[PJ_MAX_OBJ_NAME]; #if PJ_DEBUG - int nesting_level; - pj_thread_t *owner; - char owner_name[PJ_MAX_OBJ_NAME]; + int nesting_level; + pj_thread_t *owner; + char owner_name[PJ_MAX_OBJ_NAME]; #endif }; @@ -120,9 +119,9 @@ struct pj_sem_t #if defined(PJ_SEMAPHORE_USE_DISPATCH_SEM) && PJ_SEMAPHORE_USE_DISPATCH_SEM != 0 dispatch_semaphore_t sem; #else - sem_t *sem; + sem_t *sem; #endif - char obj_name[PJ_MAX_OBJ_NAME]; + char obj_name[PJ_MAX_OBJ_NAME]; }; #endif /* PJ_HAS_SEMAPHORE */ @@ -130,19 +129,19 @@ struct pj_sem_t struct pj_event_t { enum event_state { - EV_STATE_OFF, - EV_STATE_SET, - EV_STATE_PULSED + EV_STATE_OFF, + EV_STATE_SET, + EV_STATE_PULSED } state; - pj_mutex_t mutex; - pthread_cond_t cond; + pj_mutex_t mutex; + pthread_cond_t cond; - pj_bool_t auto_reset; - unsigned threads_waiting; - unsigned threads_to_release; + pj_bool_t auto_reset; + unsigned threads_waiting; + unsigned threads_to_release; }; -#endif /* PJ_HAS_EVENT_OBJ */ +#endif /* PJ_HAS_EVENT_OBJ */ /* @@ -177,8 +176,8 @@ PJ_DEF(pj_status_t) pj_init(void) /* Check if PJLIB have been initialized */ if (initialized) { - ++initialized; - return PJ_SUCCESS; + ++initialized; + return PJ_SUCCESS; } /* Init logging */ @@ -187,12 +186,12 @@ PJ_DEF(pj_status_t) pj_init(void) #if PJ_HAS_THREADS /* Init this thread's TLS. */ if ((rc=pj_thread_init()) != 0) { - return rc; + return rc; } /* Critical section. */ if ((rc=init_mutex(&critical_section, "critsec", PJ_MUTEX_RECURSE)) != 0) - return rc; + return rc; #endif @@ -214,10 +213,10 @@ PJ_DEF(pj_status_t) pj_init(void) /* Startup timestamp */ #if defined(PJ_HAS_HIGH_RES_TIMER) && PJ_HAS_HIGH_RES_TIMER != 0 { - pj_timestamp dummy_ts; - if ((rc=pj_get_timestamp(&dummy_ts)) != 0) { - return rc; - } + pj_timestamp dummy_ts; + if ((rc=pj_get_timestamp(&dummy_ts)) != 0) { + return rc; + } } #endif @@ -226,7 +225,7 @@ PJ_DEF(pj_status_t) pj_init(void) pj_assert(initialized == 1); PJ_LOG(4,(THIS_FILE, "pjlib %s for POSIX initialized", - PJ_VERSION)); + PJ_VERSION)); return PJ_SUCCESS; } @@ -237,7 +236,7 @@ PJ_DEF(pj_status_t) pj_init(void) PJ_DEF(pj_status_t) pj_atexit(void (*func)(void)) { if (atexit_count >= PJ_ARRAY_SIZE(atexit_func)) - return PJ_ETOOMANY; + return PJ_ETOOMANY; atexit_func[atexit_count++] = func; return PJ_SUCCESS; @@ -253,18 +252,18 @@ PJ_DEF(void) pj_shutdown() /* Only perform shutdown operation when 'initialized' reaches zero */ pj_assert(initialized > 0); if (--initialized != 0) - return; + return; /* Call atexit() functions */ for (i=atexit_count-1; i>=0; --i) { - (*atexit_func[i])(); + (*atexit_func[i])(); } atexit_count = 0; /* Free exception ID */ if (PJ_NO_MEMORY_EXCEPTION != -1) { - pj_exception_id_free(PJ_NO_MEMORY_EXCEPTION); - PJ_NO_MEMORY_EXCEPTION = -1; + pj_exception_id_free(PJ_NO_MEMORY_EXCEPTION); + PJ_NO_MEMORY_EXCEPTION = -1; } #if PJ_HAS_THREADS @@ -273,8 +272,8 @@ PJ_DEF(void) pj_shutdown() /* Free PJLIB TLS */ if (thread_tls_id != -1) { - pj_thread_local_free(thread_tls_id); - thread_tls_id = -1; + pj_thread_local_free(thread_tls_id); + thread_tls_id = -1; } /* Ticket #1132: Assertion when (re)starting PJLIB on different thread */ @@ -387,7 +386,7 @@ static pj_status_t set_android_thread_priority(int priority) setpriority(PRIO_PROCESS, 0, priority); } else { PJ_LOG(5, (THIS_FILE, "Setting thread priority to %d successful", - priority)); + priority)); } on_return: @@ -410,7 +409,7 @@ PJ_DEF(int) pj_thread_get_prio(pj_thread_t *thread) rc = pthread_getschedparam (thread->thread, &policy, ¶m); if (rc != 0) - return -1; + return -1; return param.sched_priority; #else @@ -438,13 +437,13 @@ PJ_DEF(pj_status_t) pj_thread_set_prio(pj_thread_t *thread, int prio) rc = pthread_getschedparam (thread->thread, &policy, ¶m); if (rc != 0) - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR(rc); param.sched_priority = prio; rc = pthread_setschedparam(thread->thread, policy, ¶m); if (rc != 0) - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR(rc); return PJ_SUCCESS; @@ -470,7 +469,7 @@ PJ_DEF(int) pj_thread_get_prio_min(pj_thread_t *thread) rc = pthread_getschedparam(thread->thread, &policy, ¶m); if (rc != 0) - return -1; + return -1; #if defined(_POSIX_PRIORITY_SCHEDULING) return sched_get_priority_min(policy); @@ -495,7 +494,7 @@ PJ_DEF(int) pj_thread_get_prio_max(pj_thread_t *thread) rc = pthread_getschedparam(thread->thread, &policy, ¶m); if (rc != 0) - return -1; + return -1; #if defined(_POSIX_PRIORITY_SCHEDULING) return sched_get_priority_max(policy); @@ -528,8 +527,8 @@ PJ_DEF(void*) pj_thread_get_os_handle(pj_thread_t *thread) * pj_thread_register(..) */ PJ_DEF(pj_status_t) pj_thread_register ( const char *cstr_thread_name, - pj_thread_desc desc, - pj_thread_t **ptr_thread) + pj_thread_desc desc, + pj_thread_t **ptr_thread) { #if PJ_HAS_THREADS char stack_ptr; @@ -539,29 +538,29 @@ PJ_DEF(pj_status_t) pj_thread_register ( const char *cstr_thread_name, /* Size sanity check. */ if (sizeof(pj_thread_desc) < sizeof(pj_thread_t)) { - pj_assert(!"Not enough pj_thread_desc size!"); - return PJ_EBUG; + pj_assert(!"Not enough pj_thread_desc size!"); + return PJ_EBUG; } /* Warn if this thread has been registered before */ if (pj_thread_local_get (thread_tls_id) != 0) { - // 2006-02-26 bennylp: - // This wouldn't work in all cases!. - // If thread is created by external module (e.g. sound thread), - // thread may be reused while the pool used for the thread descriptor - // has been deleted by application. - //*thread_ptr = (pj_thread_t*)pj_thread_local_get (thread_tls_id); + // 2006-02-26 bennylp: + // This wouldn't work in all cases!. + // If thread is created by external module (e.g. sound thread), + // thread may be reused while the pool used for the thread descriptor + // has been deleted by application. + //*thread_ptr = (pj_thread_t*)pj_thread_local_get (thread_tls_id); //return PJ_SUCCESS; - PJ_LOG(4,(THIS_FILE, "Info: possibly re-registering existing " - "thread")); + PJ_LOG(4,(THIS_FILE, "Info: possibly re-registering existing " + "thread")); } /* On the other hand, also warn if the thread descriptor buffer seem to * have been used to register other threads. */ pj_assert(thread->signature1 != SIGNATURE1 || - thread->signature2 != SIGNATURE2 || - (thread->thread == pthread_self())); + thread->signature2 != SIGNATURE2 || + (thread->thread == pthread_self())); /* Initialize and set the thread entry. */ pj_bzero(desc, sizeof(struct pj_thread_t)); @@ -570,16 +569,16 @@ PJ_DEF(pj_status_t) pj_thread_register ( const char *cstr_thread_name, thread->signature2 = SIGNATURE2; if(cstr_thread_name && pj_strlen(&thread_name) < sizeof(thread->obj_name)-1) - pj_ansi_snprintf(thread->obj_name, sizeof(thread->obj_name), - cstr_thread_name, thread->thread); + pj_ansi_snprintf(thread->obj_name, sizeof(thread->obj_name), + cstr_thread_name, thread->thread); else - pj_ansi_snprintf(thread->obj_name, sizeof(thread->obj_name), - "thr%p", (void*)thread->thread); + pj_ansi_snprintf(thread->obj_name, sizeof(thread->obj_name), + "thr%p", (void*)thread->thread); rc = pj_thread_local_set(thread_tls_id, thread); if (rc != PJ_SUCCESS) { - pj_bzero(desc, sizeof(struct pj_thread_t)); - return rc; + pj_bzero(desc, sizeof(struct pj_thread_t)); + return rc; } #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0 @@ -610,7 +609,7 @@ pj_status_t pj_thread_init(void) rc = pj_thread_local_alloc(&thread_tls_id ); if (rc != PJ_SUCCESS) { - return rc; + return rc; } return pj_thread_register("thr%p", (long*)&main_thread, &dummy); #else @@ -632,8 +631,8 @@ static void set_thread_display_name(const char *name) char xname[16]; // On linux, thread display name length is restricted to 16 (include '\0') if (pj_ansi_strlen(name) >= 16) { - pj_ansi_snprintf(xname, 16, "%s", name); - name = xname; + pj_ansi_snprintf(xname, 16, "%s", name); + name = xname; } #endif @@ -669,13 +668,13 @@ static void *thread_main(void *param) /* Set current thread id. */ rc = pj_thread_local_set(thread_tls_id, rec); if (rc != PJ_SUCCESS) { - pj_assert(!"Thread TLS ID is not set (pj_init() error?)"); + pj_assert(!"Thread TLS ID is not set (pj_init() error?)"); } /* Check if suspension is required. */ if (rec->suspended_mutex) { - pj_mutex_lock(rec->suspended_mutex); - pj_mutex_unlock(rec->suspended_mutex); + pj_mutex_lock(rec->suspended_mutex); + pj_mutex_unlock(rec->suspended_mutex); } PJ_LOG(6,(rec->obj_name, "Thread started")); @@ -696,12 +695,12 @@ static void *thread_main(void *param) * pj_thread_create(...) */ PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool, - const char *thread_name, - pj_thread_proc *proc, - void *arg, - pj_size_t stack_size, - unsigned flags, - pj_thread_t **ptr_thread) + const char *thread_name, + pj_thread_proc *proc, + void *arg, + pj_size_t stack_size, + unsigned flags, + pj_thread_t **ptr_thread) { #if PJ_HAS_THREADS pj_thread_t *rec; @@ -720,18 +719,18 @@ PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool, /* Set name. */ if (!thread_name) - thread_name = "thr%p"; + thread_name = "thr%p"; if (strchr(thread_name, '%')) { - pj_ansi_snprintf(rec->obj_name, PJ_MAX_OBJ_NAME, thread_name, rec); + pj_ansi_snprintf(rec->obj_name, PJ_MAX_OBJ_NAME, thread_name, rec); } else { - strncpy(rec->obj_name, thread_name, PJ_MAX_OBJ_NAME); - rec->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; + strncpy(rec->obj_name, thread_name, PJ_MAX_OBJ_NAME); + rec->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; } /* Set default stack size */ if (stack_size == 0) - stack_size = PJ_THREAD_DEFAULT_STACK_SIZE; + stack_size = PJ_THREAD_DEFAULT_STACK_SIZE; #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0 rec->stk_size = stack_size; @@ -740,14 +739,14 @@ PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool, /* Emulate suspended thread with mutex. */ if (flags & PJ_THREAD_SUSPENDED) { - rc = pj_mutex_create_simple(pool, NULL, &rec->suspended_mutex); - if (rc != PJ_SUCCESS) { - return rc; - } + rc = pj_mutex_create_simple(pool, NULL, &rec->suspended_mutex); + if (rc != PJ_SUCCESS) { + return rc; + } - pj_mutex_lock(rec->suspended_mutex); + pj_mutex_lock(rec->suspended_mutex); } else { - pj_assert(rec->suspended_mutex == NULL); + pj_assert(rec->suspended_mutex == NULL); } @@ -758,10 +757,10 @@ PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool, /* Set thread's stack size */ rc = pthread_attr_setstacksize(&thread_attr, stack_size); if (rc != 0) { - pthread_attr_destroy(&thread_attr); - return PJ_RETURN_OS_ERROR(rc); + pthread_attr_destroy(&thread_attr); + return PJ_RETURN_OS_ERROR(rc); } -#endif /* PJ_THREAD_SET_STACK_SIZE */ +#endif /* PJ_THREAD_SET_STACK_SIZE */ #if defined(PJ_THREAD_ALLOCATE_STACK) && PJ_THREAD_ALLOCATE_STACK!=0 @@ -771,10 +770,10 @@ PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool, rc = pthread_attr_setstackaddr(&thread_attr, stack_addr); if (rc != 0) { - pthread_attr_destroy(&thread_attr); - return PJ_RETURN_OS_ERROR(rc); + pthread_attr_destroy(&thread_attr); + return PJ_RETURN_OS_ERROR(rc); } -#endif /* PJ_THREAD_ALLOCATE_STACK */ +#endif /* PJ_THREAD_ALLOCATE_STACK */ /* Create the thread. */ @@ -782,8 +781,8 @@ PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool, rec->arg = arg; rc = pthread_create( &rec->thread, &thread_attr, &thread_main, rec); if (rc != 0) { - pthread_attr_destroy(&thread_attr); - return PJ_RETURN_OS_ERROR(rc); + pthread_attr_destroy(&thread_attr); + return PJ_RETURN_OS_ERROR(rc); } /* Destroy thread attributes */ @@ -840,9 +839,9 @@ PJ_DEF(pj_thread_t*) pj_thread_this(void) pj_thread_t *rec = (pj_thread_t*)pj_thread_local_get(thread_tls_id); if (rec == NULL) { - pj_assert(!"Calling pjlib from unknown/external thread. You must " - "register external threads with pj_thread_register() " - "before calling any pjlib functions."); + pj_assert(!"Calling pjlib from unknown/external thread. You must " + "register external threads with pj_thread_register() " + "before calling any pjlib functions."); } /* @@ -871,19 +870,19 @@ PJ_DEF(pj_status_t) pj_thread_join(pj_thread_t *p) PJ_CHECK_STACK(); if (p == pj_thread_this()) - return PJ_ECANCELLED; + return PJ_ECANCELLED; PJ_LOG(6, (pj_thread_this()->obj_name, "Joining thread %s", p->obj_name)); result = pthread_join( rec->thread, &ret); if (result == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; else { - /* Calling pthread_join() on a thread that no longer exists and - * getting back ESRCH isn't an error (in this context). - * Thanks Phil Torre . - */ - return result==ESRCH ? PJ_SUCCESS : PJ_RETURN_OS_ERROR(result); + /* Calling pthread_join() on a thread that no longer exists and + * getting back ESRCH isn't an error (in this context). + * Thanks Phil Torre . + */ + return result==ESRCH ? PJ_SUCCESS : PJ_RETURN_OS_ERROR(result); } #else PJ_CHECK_STACK(); @@ -901,8 +900,8 @@ PJ_DEF(pj_status_t) pj_thread_destroy(pj_thread_t *p) /* Destroy mutex used to suspend thread */ if (p->suspended_mutex) { - pj_mutex_destroy(p->suspended_mutex); - p->suspended_mutex = NULL; + pj_mutex_destroy(p->suspended_mutex); + p->suspended_mutex = NULL; } return PJ_SUCCESS; @@ -923,7 +922,7 @@ PJ_DEF(pj_status_t) pj_thread_sleep(unsigned msec) req.tv_nsec = (msec % 1000) * NANOSEC_PER_MSEC; if (nanosleep(&req, NULL) == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); #else @@ -944,11 +943,11 @@ PJ_DEF(pj_status_t) pj_thread_sleep(unsigned msec) * return successfully if it is. */ if (pj_get_native_os_error() == ETIMEDOUT) - return PJ_SUCCESS; + return PJ_SUCCESS; return pj_get_os_error(); -#endif /* PJ_RTEMS */ +#endif /* PJ_RTEMS */ } #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0 @@ -964,16 +963,16 @@ PJ_DEF(void) pj_thread_check_stack(const char *file, int line) /* Calculate current usage. */ usage = (&stk_ptr > thread->stk_start) ? &stk_ptr - thread->stk_start : - thread->stk_start - &stk_ptr; + thread->stk_start - &stk_ptr; /* Assert if stack usage is dangerously high. */ pj_assert("STACK OVERFLOW!! " && (usage <= thread->stk_size - 128)); /* Keep statistic. */ if (usage > thread->stk_max_usage) { - thread->stk_max_usage = usage; - thread->caller_file = file; - thread->caller_line = line; + thread->stk_max_usage = usage; + thread->caller_file = file; + thread->caller_line = line; } } @@ -989,8 +988,8 @@ PJ_DEF(pj_uint32_t) pj_thread_get_stack_max_usage(pj_thread_t *thread) * pj_thread_get_stack_info() */ PJ_DEF(pj_status_t) pj_thread_get_stack_info( pj_thread_t *thread, - const char **file, - int *line ) + const char **file, + int *line ) { pj_assert(thread); @@ -999,15 +998,15 @@ PJ_DEF(pj_status_t) pj_thread_get_stack_info( pj_thread_t *thread, return 0; } -#endif /* PJ_OS_HAS_CHECK_STACK */ +#endif /* PJ_OS_HAS_CHECK_STACK */ /////////////////////////////////////////////////////////////////////////////// /* * pj_atomic_create() */ PJ_DEF(pj_status_t) pj_atomic_create( pj_pool_t *pool, - pj_atomic_value_t initial, - pj_atomic_t **ptr_atomic) + pj_atomic_value_t initial, + pj_atomic_t **ptr_atomic) { pj_status_t rc; pj_atomic_t *atomic_var; @@ -1019,7 +1018,7 @@ PJ_DEF(pj_status_t) pj_atomic_create( pj_pool_t *pool, #if PJ_HAS_THREADS rc = pj_mutex_create(pool, "atm%p", PJ_MUTEX_SIMPLE, &atomic_var->mutex); if (rc != PJ_SUCCESS) - return rc; + return rc; #endif atomic_var->value = initial; @@ -1191,18 +1190,18 @@ PJ_DEF(pj_status_t) pj_thread_local_alloc(long *p_index) pj_assert( sizeof(pthread_key_t) <= sizeof(long)); if ((rc=pthread_key_create(&key, NULL)) != 0) - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR(rc); *p_index = key; return PJ_SUCCESS; #else int i; for (i=0; i: - // The RTEMS implementation of POSIX mutexes doesn't include - // pthread_mutexattr_settype(), so what follows is a hack - // until I get RTEMS patched to support the set/get functions. - // - // More info: - // newlib's pthread also lacks pthread_mutexattr_settype(), - // but it seems to have mutexattr.recursive. - PJ_TODO(FIX_RTEMS_RECURSIVE_MUTEX_TYPE) - attr.recursive = 1; + // Phil Torre : + // The RTEMS implementation of POSIX mutexes doesn't include + // pthread_mutexattr_settype(), so what follows is a hack + // until I get RTEMS patched to support the set/get functions. + // + // More info: + // newlib's pthread also lacks pthread_mutexattr_settype(), + // but it seems to have mutexattr.recursive. + PJ_TODO(FIX_RTEMS_RECURSIVE_MUTEX_TYPE) + attr.recursive = 1; #else - rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); #endif } if (rc != 0) { - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR(rc); } rc = pthread_mutex_init(&mutex->mutex, &attr); if (rc != 0) { - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR(rc); } rc = pthread_mutexattr_destroy(&attr); if (rc != 0) { - pj_status_t status = PJ_RETURN_OS_ERROR(rc); - pthread_mutex_destroy(&mutex->mutex); - return status; + pj_status_t status = PJ_RETURN_OS_ERROR(rc); + pthread_mutex_destroy(&mutex->mutex); + return status; } #if PJ_DEBUG @@ -1347,13 +1346,13 @@ static pj_status_t init_mutex(pj_mutex_t *mutex, const char *name, int type) /* Set name. */ if (!name) { - name = "mtx%p"; + name = "mtx%p"; } if (strchr(name, '%')) { - pj_ansi_snprintf(mutex->obj_name, PJ_MAX_OBJ_NAME, name, mutex); + pj_ansi_snprintf(mutex->obj_name, PJ_MAX_OBJ_NAME, name, mutex); } else { - strncpy(mutex->obj_name, name, PJ_MAX_OBJ_NAME); - mutex->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; + strncpy(mutex->obj_name, name, PJ_MAX_OBJ_NAME); + mutex->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; } PJ_LOG(6, (mutex->obj_name, "Mutex created")); @@ -1367,9 +1366,9 @@ static pj_status_t init_mutex(pj_mutex_t *mutex, const char *name, int type) * pj_mutex_create() */ PJ_DEF(pj_status_t) pj_mutex_create(pj_pool_t *pool, - const char *name, - int type, - pj_mutex_t **ptr_mutex) + const char *name, + int type, + pj_mutex_t **ptr_mutex) { #if PJ_HAS_THREADS pj_status_t rc; @@ -1381,7 +1380,7 @@ PJ_DEF(pj_status_t) pj_mutex_create(pj_pool_t *pool, PJ_ASSERT_RETURN(mutex, PJ_ENOMEM); if ((rc=init_mutex(mutex, name, type)) != PJ_SUCCESS) - return rc; + return rc; *ptr_mutex = mutex; return PJ_SUCCESS; @@ -1396,7 +1395,7 @@ PJ_DEF(pj_status_t) pj_mutex_create(pj_pool_t *pool, */ PJ_DEF(pj_status_t) pj_mutex_create_simple( pj_pool_t *pool, const char *name, - pj_mutex_t **mutex ) + pj_mutex_t **mutex ) { return pj_mutex_create(pool, name, PJ_MUTEX_SIMPLE, mutex); } @@ -1405,8 +1404,8 @@ PJ_DEF(pj_status_t) pj_mutex_create_simple( pj_pool_t *pool, * pj_mutex_create_recursive() */ PJ_DEF(pj_status_t) pj_mutex_create_recursive( pj_pool_t *pool, - const char *name, - pj_mutex_t **mutex ) + const char *name, + pj_mutex_t **mutex ) { return pj_mutex_create(pool, name, PJ_MUTEX_RECURSE, mutex); } @@ -1424,11 +1423,11 @@ PJ_DEF(pj_status_t) pj_mutex_lock(pj_mutex_t *mutex) #if PJ_DEBUG PJ_LOG(6,(mutex->obj_name, "Mutex: thread %s is waiting (mutex owner=%s)", - pj_thread_this()->obj_name, - mutex->owner_name)); + pj_thread_this()->obj_name, + mutex->owner_name)); #else PJ_LOG(6,(mutex->obj_name, "Mutex: thread %s is waiting", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); #endif status = pthread_mutex_lock( &mutex->mutex ); @@ -1436,28 +1435,28 @@ PJ_DEF(pj_status_t) pj_mutex_lock(pj_mutex_t *mutex) #if PJ_DEBUG if (status == PJ_SUCCESS) { - mutex->owner = pj_thread_this(); - pj_ansi_strcpy(mutex->owner_name, mutex->owner->obj_name); - ++mutex->nesting_level; + mutex->owner = pj_thread_this(); + pj_ansi_strcpy(mutex->owner_name, mutex->owner->obj_name); + ++mutex->nesting_level; } PJ_LOG(6,(mutex->obj_name, - (status==0 ? - "Mutex acquired by thread %s (level=%d)" : - "Mutex acquisition FAILED by %s (level=%d)"), - pj_thread_this()->obj_name, - mutex->nesting_level)); + (status==0 ? + "Mutex acquired by thread %s (level=%d)" : + "Mutex acquisition FAILED by %s (level=%d)"), + pj_thread_this()->obj_name, + mutex->nesting_level)); #else PJ_LOG(6,(mutex->obj_name, - (status==0 ? "Mutex acquired by thread %s" : "FAILED by %s"), - pj_thread_this()->obj_name)); + (status==0 ? "Mutex acquired by thread %s" : "FAILED by %s"), + pj_thread_this()->obj_name)); #endif if (status == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; else - return PJ_RETURN_OS_ERROR(status); -#else /* PJ_HAS_THREADS */ + return PJ_RETURN_OS_ERROR(status); +#else /* PJ_HAS_THREADS */ pj_assert( mutex == (pj_mutex_t*)1 ); return PJ_SUCCESS; #endif @@ -1477,23 +1476,23 @@ PJ_DEF(pj_status_t) pj_mutex_unlock(pj_mutex_t *mutex) #if PJ_DEBUG pj_assert(mutex->owner == pj_thread_this()); if (--mutex->nesting_level == 0) { - mutex->owner = NULL; - mutex->owner_name[0] = '\0'; + mutex->owner = NULL; + mutex->owner_name[0] = '\0'; } PJ_LOG(6,(mutex->obj_name, "Mutex released by thread %s (level=%d)", - pj_thread_this()->obj_name, - mutex->nesting_level)); + pj_thread_this()->obj_name, + mutex->nesting_level)); #else PJ_LOG(6,(mutex->obj_name, "Mutex released by thread %s", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); #endif status = pthread_mutex_unlock( &mutex->mutex ); if (status == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; else - return PJ_RETURN_OS_ERROR(status); + return PJ_RETURN_OS_ERROR(status); #else /* PJ_HAS_THREADS */ pj_assert( mutex == (pj_mutex_t*)1 ); @@ -1513,33 +1512,33 @@ PJ_DEF(pj_status_t) pj_mutex_trylock(pj_mutex_t *mutex) PJ_ASSERT_RETURN(mutex, PJ_EINVAL); PJ_LOG(6,(mutex->obj_name, "Mutex: thread %s is trying", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); status = pthread_mutex_trylock( &mutex->mutex ); if (status==0) { #if PJ_DEBUG - mutex->owner = pj_thread_this(); - pj_ansi_strcpy(mutex->owner_name, mutex->owner->obj_name); - ++mutex->nesting_level; + mutex->owner = pj_thread_this(); + pj_ansi_strcpy(mutex->owner_name, mutex->owner->obj_name); + ++mutex->nesting_level; - PJ_LOG(6,(mutex->obj_name, "Mutex acquired by thread %s (level=%d)", - pj_thread_this()->obj_name, - mutex->nesting_level)); + PJ_LOG(6,(mutex->obj_name, "Mutex acquired by thread %s (level=%d)", + pj_thread_this()->obj_name, + mutex->nesting_level)); #else - PJ_LOG(6,(mutex->obj_name, "Mutex acquired by thread %s", - pj_thread_this()->obj_name)); + PJ_LOG(6,(mutex->obj_name, "Mutex acquired by thread %s", + pj_thread_this()->obj_name)); #endif } else { - PJ_LOG(6,(mutex->obj_name, "Mutex: thread %s's trylock() failed", - pj_thread_this()->obj_name)); + PJ_LOG(6,(mutex->obj_name, "Mutex: thread %s's trylock() failed", + pj_thread_this()->obj_name)); } if (status==0) - return PJ_SUCCESS; + return PJ_SUCCESS; else - return PJ_RETURN_OS_ERROR(status); -#else /* PJ_HAS_THREADS */ + return PJ_RETURN_OS_ERROR(status); +#else /* PJ_HAS_THREADS */ pj_assert( mutex == (pj_mutex_t*)1); return PJ_SUCCESS; #endif @@ -1559,20 +1558,20 @@ PJ_DEF(pj_status_t) pj_mutex_destroy(pj_mutex_t *mutex) #if PJ_HAS_THREADS PJ_LOG(6,(mutex->obj_name, "Mutex destroyed by thread %s", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); for (retry=0; retrymutex ); - if (status == PJ_SUCCESS) - break; - else if (retrymutex); + status = pthread_mutex_destroy( &mutex->mutex ); + if (status == PJ_SUCCESS) + break; + else if (retrymutex); } if (status == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; else { - return PJ_RETURN_OS_ERROR(status); + return PJ_RETURN_OS_ERROR(status); } #else pj_assert( mutex == (pj_mutex_t*)1 ); @@ -1600,7 +1599,7 @@ PJ_DEF(pj_bool_t) pj_mutex_is_locked(pj_mutex_t *mutex) #if defined(PJ_EMULATE_RWMUTEX) && PJ_EMULATE_RWMUTEX!=0 /* We need semaphore functionality to emulate rwmutex */ # if !defined(PJ_HAS_SEMAPHORE) || PJ_HAS_SEMAPHORE==0 -# error "Semaphore support needs to be enabled to emulate rwmutex" +# error "Semaphore support needs to be enabled to emulate rwmutex" # endif # include "os_rwmutex.c" #else @@ -1610,7 +1609,7 @@ struct pj_rwmutex_t }; PJ_DEF(pj_status_t) pj_rwmutex_create(pj_pool_t *pool, const char *name, - pj_rwmutex_t **p_mutex) + pj_rwmutex_t **p_mutex) { pj_rwmutex_t *rwm; pj_status_t status; @@ -1622,7 +1621,7 @@ PJ_DEF(pj_status_t) pj_rwmutex_create(pj_pool_t *pool, const char *name, status = pthread_rwlock_init(&rwm->rwlock, NULL); if (status != 0) - return PJ_RETURN_OS_ERROR(status); + return PJ_RETURN_OS_ERROR(status); *p_mutex = rwm; return PJ_SUCCESS; @@ -1638,7 +1637,7 @@ PJ_DEF(pj_status_t) pj_rwmutex_lock_read(pj_rwmutex_t *mutex) status = pthread_rwlock_rdlock(&mutex->rwlock); if (status != 0) - return PJ_RETURN_OS_ERROR(status); + return PJ_RETURN_OS_ERROR(status); return PJ_SUCCESS; } @@ -1653,7 +1652,7 @@ PJ_DEF(pj_status_t) pj_rwmutex_lock_write(pj_rwmutex_t *mutex) status = pthread_rwlock_wrlock(&mutex->rwlock); if (status != 0) - return PJ_RETURN_OS_ERROR(status); + return PJ_RETURN_OS_ERROR(status); return PJ_SUCCESS; } @@ -1677,7 +1676,7 @@ PJ_DEF(pj_status_t) pj_rwmutex_unlock_write(pj_rwmutex_t *mutex) status = pthread_rwlock_unlock(&mutex->rwlock); if (status != 0) - return PJ_RETURN_OS_ERROR(status); + return PJ_RETURN_OS_ERROR(status); return PJ_SUCCESS; } @@ -1692,12 +1691,12 @@ PJ_DEF(pj_status_t) pj_rwmutex_destroy(pj_rwmutex_t *mutex) status = pthread_rwlock_destroy(&mutex->rwlock); if (status != 0) - return PJ_RETURN_OS_ERROR(status); + return PJ_RETURN_OS_ERROR(status); return PJ_SUCCESS; } -#endif /* PJ_EMULATE_RWMUTEX */ +#endif /* PJ_EMULATE_RWMUTEX */ /////////////////////////////////////////////////////////////////////////////// @@ -1707,10 +1706,10 @@ PJ_DEF(pj_status_t) pj_rwmutex_destroy(pj_rwmutex_t *mutex) * pj_sem_create() */ PJ_DEF(pj_status_t) pj_sem_create( pj_pool_t *pool, - const char *name, - unsigned initial, - unsigned max, - pj_sem_t **ptr_sem) + const char *name, + unsigned initial, + unsigned max, + pj_sem_t **ptr_sem) { #if PJ_HAS_THREADS pj_sem_t *sem; @@ -1729,50 +1728,50 @@ PJ_DEF(pj_status_t) pj_sem_create( pj_pool_t *pool, # else /* MacOS X doesn't support anonymous semaphore */ { - char sem_name[PJ_GUID_MAX_LENGTH+1]; - pj_str_t nam; - - /* We should use SEM_NAME_LEN, but this doesn't seem to be - * declared anywhere? The value here is just from trial and error - * to get the longest name supported. - */ -# define MAX_SEM_NAME_LEN 23 - - /* Create a unique name for the semaphore. */ - if (PJ_GUID_STRING_LENGTH <= MAX_SEM_NAME_LEN) { - nam.ptr = sem_name; - pj_generate_unique_string(&nam); - sem_name[nam.slen] = '\0'; - } else { - pj_create_random_string(sem_name, MAX_SEM_NAME_LEN); - sem_name[MAX_SEM_NAME_LEN] = '\0'; - } - - /* Create semaphore */ - sem->sem = sem_open(sem_name, O_CREAT|O_EXCL, S_IRUSR|S_IWUSR, - initial); - if (sem->sem == SEM_FAILED) - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); - - /* And immediately release the name as we don't need it */ - sem_unlink(sem_name); + char sem_name[PJ_GUID_MAX_LENGTH+1]; + pj_str_t nam; + + /* We should use SEM_NAME_LEN, but this doesn't seem to be + * declared anywhere? The value here is just from trial and error + * to get the longest name supported. + */ +# define MAX_SEM_NAME_LEN 23 + + /* Create a unique name for the semaphore. */ + if (PJ_GUID_STRING_LENGTH <= MAX_SEM_NAME_LEN) { + nam.ptr = sem_name; + pj_generate_unique_string(&nam); + sem_name[nam.slen] = '\0'; + } else { + pj_create_random_string(sem_name, MAX_SEM_NAME_LEN); + sem_name[MAX_SEM_NAME_LEN] = '\0'; + } + + /* Create semaphore */ + sem->sem = sem_open(sem_name, O_CREAT|O_EXCL, S_IRUSR|S_IWUSR, + initial); + if (sem->sem == SEM_FAILED) + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + + /* And immediately release the name as we don't need it */ + sem_unlink(sem_name); } # endif #else sem->sem = PJ_POOL_ALLOC_T(pool, sem_t); if (sem_init( sem->sem, 0, initial) != 0) - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); #endif /* Set name. */ if (!name) { - name = "sem%p"; + name = "sem%p"; } if (strchr(name, '%')) { - pj_ansi_snprintf(sem->obj_name, PJ_MAX_OBJ_NAME, name, sem); + pj_ansi_snprintf(sem->obj_name, PJ_MAX_OBJ_NAME, name, sem); } else { - strncpy(sem->obj_name, name, PJ_MAX_OBJ_NAME); - sem->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; + strncpy(sem->obj_name, name, PJ_MAX_OBJ_NAME); + sem->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; } PJ_LOG(6, (sem->obj_name, "Semaphore created")); @@ -1797,7 +1796,7 @@ PJ_DEF(pj_status_t) pj_sem_wait(pj_sem_t *sem) PJ_ASSERT_RETURN(sem, PJ_EINVAL); PJ_LOG(6, (sem->obj_name, "Semaphore: thread %s is waiting", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); #if defined(PJ_SEMAPHORE_USE_DISPATCH_SEM) && PJ_SEMAPHORE_USE_DISPATCH_SEM != 0 result = dispatch_semaphore_wait(sem->sem, DISPATCH_TIME_FOREVER); @@ -1806,17 +1805,17 @@ PJ_DEF(pj_status_t) pj_sem_wait(pj_sem_t *sem) #endif if (result == 0) { - PJ_LOG(6, (sem->obj_name, "Semaphore acquired by thread %s", - pj_thread_this()->obj_name)); + PJ_LOG(6, (sem->obj_name, "Semaphore acquired by thread %s", + pj_thread_this()->obj_name)); } else { - PJ_LOG(6, (sem->obj_name, "Semaphore: thread %s FAILED to acquire", - pj_thread_this()->obj_name)); + PJ_LOG(6, (sem->obj_name, "Semaphore: thread %s FAILED to acquire", + pj_thread_this()->obj_name)); } if (result == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; else - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); #else pj_assert( sem == (pj_sem_t*) 1 ); return PJ_SUCCESS; @@ -1841,13 +1840,13 @@ PJ_DEF(pj_status_t) pj_sem_trywait(pj_sem_t *sem) #endif if (result == 0) { - PJ_LOG(6, (sem->obj_name, "Semaphore acquired by thread %s", - pj_thread_this()->obj_name)); + PJ_LOG(6, (sem->obj_name, "Semaphore acquired by thread %s", + pj_thread_this()->obj_name)); } if (result == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; else - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); #else pj_assert( sem == (pj_sem_t*)1 ); return PJ_SUCCESS; @@ -1862,7 +1861,7 @@ PJ_DEF(pj_status_t) pj_sem_post(pj_sem_t *sem) #if PJ_HAS_THREADS int result; PJ_LOG(6, (sem->obj_name, "Semaphore released by thread %s", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); #if defined(PJ_SEMAPHORE_USE_DISPATCH_SEM) && PJ_SEMAPHORE_USE_DISPATCH_SEM != 0 dispatch_semaphore_signal(sem->sem); result = 0; @@ -1871,9 +1870,9 @@ PJ_DEF(pj_status_t) pj_sem_post(pj_sem_t *sem) #endif if (result == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; else - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); #else pj_assert( sem == (pj_sem_t*) 1); return PJ_SUCCESS; @@ -1892,7 +1891,7 @@ PJ_DEF(pj_status_t) pj_sem_destroy(pj_sem_t *sem) PJ_ASSERT_RETURN(sem, PJ_EINVAL); PJ_LOG(6, (sem->obj_name, "Semaphore destroyed by thread %s", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); #if defined(PJ_DARWINOS) && PJ_DARWINOS!=0 # if defined(PJ_SEMAPHORE_USE_DISPATCH_SEM) && PJ_SEMAPHORE_USE_DISPATCH_SEM != 0 dispatch_release(sem->sem); @@ -1905,16 +1904,16 @@ PJ_DEF(pj_status_t) pj_sem_destroy(pj_sem_t *sem) #endif if (result == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; else - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); #else pj_assert( sem == (pj_sem_t*) 1 ); return PJ_SUCCESS; #endif } -#endif /* PJ_HAS_SEMAPHORE */ +#endif /* PJ_HAS_SEMAPHORE */ /////////////////////////////////////////////////////////////////////////////// #if defined(PJ_HAS_EVENT_OBJ) && PJ_HAS_EVENT_OBJ != 0 @@ -1923,8 +1922,8 @@ PJ_DEF(pj_status_t) pj_sem_destroy(pj_sem_t *sem) * pj_event_create() */ PJ_DEF(pj_status_t) pj_event_create(pj_pool_t *pool, const char *name, - pj_bool_t manual_reset, pj_bool_t initial, - pj_event_t **ptr_event) + pj_bool_t manual_reset, pj_bool_t initial, + pj_event_t **ptr_event) { pj_event_t *event; @@ -1936,11 +1935,11 @@ PJ_DEF(pj_status_t) pj_event_create(pj_pool_t *pool, const char *name, event->threads_waiting = 0; if (initial) { - event->state = EV_STATE_SET; - event->threads_to_release = 1; + event->state = EV_STATE_SET; + event->threads_to_release = 1; } else { - event->state = EV_STATE_OFF; - event->threads_to_release = 0; + event->state = EV_STATE_OFF; + event->threads_to_release = 0; } *ptr_event = event; @@ -1950,23 +1949,23 @@ PJ_DEF(pj_status_t) pj_event_create(pj_pool_t *pool, const char *name, static void event_on_one_release(pj_event_t *event) { if (event->state == EV_STATE_SET) { - if (event->auto_reset) { - event->threads_to_release = 0; - event->state = EV_STATE_OFF; - } else { - /* Manual reset remains on */ - } + if (event->auto_reset) { + event->threads_to_release = 0; + event->state = EV_STATE_OFF; + } else { + /* Manual reset remains on */ + } } else { - if (event->auto_reset) { - /* Only release one */ - event->threads_to_release = 0; - event->state = EV_STATE_OFF; - } else { - event->threads_to_release--; - pj_assert(event->threads_to_release >= 0); - if (event->threads_to_release==0) - event->state = EV_STATE_OFF; - } + if (event->auto_reset) { + /* Only release one */ + event->threads_to_release = 0; + event->state = EV_STATE_OFF; + } else { + event->threads_to_release--; + pj_assert(event->threads_to_release >= 0); + if (event->threads_to_release==0) + event->state = EV_STATE_OFF; + } } } @@ -1978,7 +1977,7 @@ PJ_DEF(pj_status_t) pj_event_wait(pj_event_t *event) pthread_mutex_lock(&event->mutex.mutex); event->threads_waiting++; while (event->state == EV_STATE_OFF) - pthread_cond_wait(&event->cond, &event->mutex.mutex); + pthread_cond_wait(&event->cond, &event->mutex.mutex); event->threads_waiting--; event_on_one_release(event); pthread_mutex_unlock(&event->mutex.mutex); @@ -1995,7 +1994,7 @@ PJ_DEF(pj_status_t) pj_event_trywait(pj_event_t *event) pthread_mutex_lock(&event->mutex.mutex); status = event->state != EV_STATE_OFF ? PJ_SUCCESS : -1; if (status==PJ_SUCCESS) { - event_on_one_release(event); + event_on_one_release(event); } pthread_mutex_unlock(&event->mutex.mutex); @@ -2011,9 +2010,9 @@ PJ_DEF(pj_status_t) pj_event_set(pj_event_t *event) event->threads_to_release = 1; event->state = EV_STATE_SET; if (event->auto_reset) - pthread_cond_signal(&event->cond); + pthread_cond_signal(&event->cond); else - pthread_cond_broadcast(&event->cond); + pthread_cond_broadcast(&event->cond); pthread_mutex_unlock(&event->mutex.mutex); return PJ_SUCCESS; } @@ -2025,13 +2024,13 @@ PJ_DEF(pj_status_t) pj_event_pulse(pj_event_t *event) { pthread_mutex_lock(&event->mutex.mutex); if (event->threads_waiting) { - event->threads_to_release = event->auto_reset ? 1 : - event->threads_waiting; - event->state = EV_STATE_PULSED; - if (event->threads_to_release==1) - pthread_cond_signal(&event->cond); - else - pthread_cond_broadcast(&event->cond); + event->threads_to_release = event->auto_reset ? 1 : + event->threads_waiting; + event->state = EV_STATE_PULSED; + if (event->threads_to_release==1) + pthread_cond_signal(&event->cond); + else + pthread_cond_broadcast(&event->cond); } pthread_mutex_unlock(&event->mutex.mutex); return PJ_SUCCESS; @@ -2059,7 +2058,7 @@ PJ_DEF(pj_status_t) pj_event_destroy(pj_event_t *event) return PJ_SUCCESS; } -#endif /* PJ_HAS_EVENT_OBJ */ +#endif /* PJ_HAS_EVENT_OBJ */ /////////////////////////////////////////////////////////////////////////////// #if defined(PJ_TERM_HAS_COLOR) && PJ_TERM_HAS_COLOR != 0 @@ -2076,48 +2075,48 @@ PJ_DEF(pj_status_t) pj_term_set_color(pj_color_t color) char ansi_color[12] = "\033[01;3"; if (color & PJ_TERM_COLOR_BRIGHT) { - color ^= PJ_TERM_COLOR_BRIGHT; + color ^= PJ_TERM_COLOR_BRIGHT; } else { - strcpy(ansi_color, "\033[00;3"); + strcpy(ansi_color, "\033[00;3"); } switch (color) { case 0: - /* black color */ - strcat(ansi_color, "0m"); - break; + /* black color */ + strcat(ansi_color, "0m"); + break; case PJ_TERM_COLOR_R: - /* red color */ - strcat(ansi_color, "1m"); - break; + /* red color */ + strcat(ansi_color, "1m"); + break; case PJ_TERM_COLOR_G: - /* green color */ - strcat(ansi_color, "2m"); - break; + /* green color */ + strcat(ansi_color, "2m"); + break; case PJ_TERM_COLOR_B: - /* blue color */ - strcat(ansi_color, "4m"); - break; + /* blue color */ + strcat(ansi_color, "4m"); + break; case PJ_TERM_COLOR_R | PJ_TERM_COLOR_G: - /* yellow color */ - strcat(ansi_color, "3m"); - break; + /* yellow color */ + strcat(ansi_color, "3m"); + break; case PJ_TERM_COLOR_R | PJ_TERM_COLOR_B: - /* magenta color */ - strcat(ansi_color, "5m"); - break; + /* magenta color */ + strcat(ansi_color, "5m"); + break; case PJ_TERM_COLOR_G | PJ_TERM_COLOR_B: - /* cyan color */ - strcat(ansi_color, "6m"); - break; + /* cyan color */ + strcat(ansi_color, "6m"); + break; case PJ_TERM_COLOR_R | PJ_TERM_COLOR_G | PJ_TERM_COLOR_B: - /* white color */ - strcat(ansi_color, "7m"); - break; + /* white color */ + strcat(ansi_color, "7m"); + break; default: - /* default console color */ - strcpy(ansi_color, "\033[00m"); - break; + /* default console color */ + strcpy(ansi_color, "\033[00m"); + break; } fputs(ansi_color, stdout); @@ -2133,7 +2132,7 @@ PJ_DEF(pj_color_t) pj_term_get_color(void) return 0; } -#endif /* PJ_TERM_HAS_COLOR */ +#endif /* PJ_TERM_HAS_COLOR */ #if !defined(PJ_DARWINOS) || PJ_DARWINOS == 0 /* diff --git a/pjlib/src/pj/os_core_win32.c b/pjlib/src/pj/os_core_win32.c index a4e3d66eab..566c364cb8 100644 --- a/pjlib/src/pj/os_core_win32.c +++ b/pjlib/src/pj/os_core_win32.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -50,31 +49,31 @@ */ #if defined(PJ_DEBUG_MUTEX) && PJ_DEBUG_MUTEX # undef PJ_DEBUG -# define PJ_DEBUG 1 +# define PJ_DEBUG 1 # define LOG_MUTEX(expr) PJ_LOG(5,expr) #else # define LOG_MUTEX(expr) PJ_LOG(6,expr) #endif -#define THIS_FILE "os_core_win32.c" +#define THIS_FILE "os_core_win32.c" /* * Implementation of pj_thread_t. */ struct pj_thread_t { - char obj_name[PJ_MAX_OBJ_NAME]; - HANDLE hthread; - DWORD idthread; + char obj_name[PJ_MAX_OBJ_NAME]; + HANDLE hthread; + DWORD idthread; pj_thread_proc *proc; - void *arg; + void *arg; #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0 - pj_uint32_t stk_size; - pj_uint32_t stk_max_usage; - char *stk_start; - const char *caller_file; - int caller_line; + pj_uint32_t stk_size; + pj_uint32_t stk_max_usage; + char *stk_start; + const char *caller_file; + int caller_line; #endif }; @@ -85,14 +84,14 @@ struct pj_thread_t struct pj_mutex_t { #if PJ_WIN32_WINNT >= 0x0400 - CRITICAL_SECTION crit; + CRITICAL_SECTION crit; #else - HANDLE hMutex; + HANDLE hMutex; #endif - char obj_name[PJ_MAX_OBJ_NAME]; + char obj_name[PJ_MAX_OBJ_NAME]; #if PJ_DEBUG - int nesting_level; - pj_thread_t *owner; + int nesting_level; + pj_thread_t *owner; #endif }; @@ -101,8 +100,8 @@ struct pj_mutex_t */ typedef struct pj_sem_t { - HANDLE hSemaphore; - char obj_name[PJ_MAX_OBJ_NAME]; + HANDLE hSemaphore; + char obj_name[PJ_MAX_OBJ_NAME]; } pj_mem_t; @@ -111,8 +110,8 @@ typedef struct pj_sem_t */ struct pj_event_t { - HANDLE hEvent; - char obj_name[PJ_MAX_OBJ_NAME]; + HANDLE hEvent; + char obj_name[PJ_MAX_OBJ_NAME]; }; /* @@ -156,18 +155,18 @@ PJ_DEF(pj_status_t) pj_init(void) /* Check if PJLIB have been initialized */ if (initialized) { - ++initialized; - return PJ_SUCCESS; + ++initialized; + return PJ_SUCCESS; } /* Init Winsock.. */ if (WSAStartup(MAKEWORD(2,0), &wsa) != 0) { - return PJ_RETURN_OS_ERROR(WSAGetLastError()); + return PJ_RETURN_OS_ERROR(WSAGetLastError()); } /* Init this thread's TLS. */ if ((rc=pj_thread_init()) != PJ_SUCCESS) { - return rc; + return rc; } /* Init logging */ @@ -179,7 +178,7 @@ PJ_DEF(pj_status_t) pj_init(void) /* Initialize critical section. */ if ((rc=init_mutex(&critical_section_mutex, "pj%p")) != PJ_SUCCESS) - return rc; + return rc; /* Startup GUID. */ guid.ptr = dummy_guid; @@ -195,13 +194,13 @@ PJ_DEF(pj_status_t) pj_init(void) /* Startup timestamp */ #if defined(PJ_HAS_HIGH_RES_TIMER) && PJ_HAS_HIGH_RES_TIMER != 0 { - pj_timestamp dummy_ts; - if ((rc=pj_get_timestamp_freq(&dummy_ts)) != PJ_SUCCESS) { - return rc; - } - if ((rc=pj_get_timestamp(&dummy_ts)) != PJ_SUCCESS) { - return rc; - } + pj_timestamp dummy_ts; + if ((rc=pj_get_timestamp_freq(&dummy_ts)) != PJ_SUCCESS) { + return rc; + } + if ((rc=pj_get_timestamp(&dummy_ts)) != PJ_SUCCESS) { + return rc; + } } #endif @@ -210,7 +209,7 @@ PJ_DEF(pj_status_t) pj_init(void) pj_assert(initialized == 1); PJ_LOG(4,(THIS_FILE, "pjlib %s for win32 initialized", - PJ_VERSION)); + PJ_VERSION)); return PJ_SUCCESS; } @@ -221,7 +220,7 @@ PJ_DEF(pj_status_t) pj_init(void) PJ_DEF(pj_status_t) pj_atexit(void (*func)(void)) { if (atexit_count >= PJ_ARRAY_SIZE(atexit_func)) - return PJ_ETOOMANY; + return PJ_ETOOMANY; atexit_func[atexit_count++] = func; return PJ_SUCCESS; @@ -238,27 +237,27 @@ PJ_DEF(void) pj_shutdown() /* Only perform shutdown operation when 'initialized' reaches zero */ pj_assert(initialized > 0); if (--initialized != 0) - return; + return; /* Display stack usage */ #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0 { - pj_thread_t *rec = (pj_thread_t*)main_thread; - PJ_LOG(5,(rec->obj_name, "Main thread stack max usage=%u by %s:%d", - rec->stk_max_usage, rec->caller_file, rec->caller_line)); + pj_thread_t *rec = (pj_thread_t*)main_thread; + PJ_LOG(5,(rec->obj_name, "Main thread stack max usage=%u by %s:%d", + rec->stk_max_usage, rec->caller_file, rec->caller_line)); } #endif /* Call atexit() functions */ for (i=atexit_count-1; i>=0; --i) { - (*atexit_func[i])(); + (*atexit_func[i])(); } atexit_count = 0; /* Free exception ID */ if (PJ_NO_MEMORY_EXCEPTION != -1) { - pj_exception_id_free(PJ_NO_MEMORY_EXCEPTION); - PJ_NO_MEMORY_EXCEPTION = -1; + pj_exception_id_free(PJ_NO_MEMORY_EXCEPTION); + PJ_NO_MEMORY_EXCEPTION = -1; } /* Destroy PJLIB critical section */ @@ -266,8 +265,8 @@ PJ_DEF(void) pj_shutdown() /* Free PJLIB TLS */ if (thread_tls_id != -1) { - pj_thread_local_free(thread_tls_id); - thread_tls_id = -1; + pj_thread_local_free(thread_tls_id); + thread_tls_id = -1; } /* Clear static variables */ @@ -321,15 +320,15 @@ PJ_DEF(pj_status_t) pj_thread_set_prio(pj_thread_t *thread, int prio) #if PJ_HAS_THREADS PJ_ASSERT_RETURN(thread, PJ_EINVAL); PJ_ASSERT_RETURN(prio>=THREAD_PRIORITY_IDLE && - prio<=THREAD_PRIORITY_TIME_CRITICAL, - PJ_EINVAL); + prio<=THREAD_PRIORITY_TIME_CRITICAL, + PJ_EINVAL); #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 if (SetThreadPriorityRT(thread->hthread, prio) == FALSE) #else if (SetThreadPriority(thread->hthread, prio) == FALSE) #endif - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); return PJ_SUCCESS; @@ -381,7 +380,7 @@ PJ_DEF(void*) pj_thread_get_os_handle(pj_thread_t *thread) * pj_thread_register(..) */ PJ_DEF(pj_status_t) pj_thread_register ( const char *cstr_thread_name, - pj_thread_desc desc, + pj_thread_desc desc, pj_thread_t **thread_ptr) { char stack_ptr; @@ -391,18 +390,18 @@ PJ_DEF(pj_status_t) pj_thread_register ( const char *cstr_thread_name, /* Size sanity check. */ if (sizeof(pj_thread_desc) < sizeof(pj_thread_t)) { - pj_assert(!"Not enough pj_thread_desc size!"); - return PJ_EBUG; + pj_assert(!"Not enough pj_thread_desc size!"); + return PJ_EBUG; } /* If a thread descriptor has been registered before, just return it. */ if (pj_thread_local_get (thread_tls_id) != 0) { - // 2006-02-26 bennylp: - // This wouldn't work in all cases!. - // If thread is created by external module (e.g. sound thread), - // thread may be reused while the pool used for the thread descriptor - // has been deleted by application. - //*thread_ptr = (pj_thread_t*)pj_thread_local_get (thread_tls_id); + // 2006-02-26 bennylp: + // This wouldn't work in all cases!. + // If thread is created by external module (e.g. sound thread), + // thread may be reused while the pool used for the thread descriptor + // has been deleted by application. + //*thread_ptr = (pj_thread_t*)pj_thread_local_get (thread_tls_id); //return PJ_SUCCESS; } @@ -420,15 +419,15 @@ PJ_DEF(pj_status_t) pj_thread_register ( const char *cstr_thread_name, #endif if (cstr_thread_name && pj_strlen(&thread_name) < sizeof(thread->obj_name)-1) - pj_ansi_snprintf(thread->obj_name, sizeof(thread->obj_name), - cstr_thread_name, thread->idthread); + pj_ansi_snprintf(thread->obj_name, sizeof(thread->obj_name), + cstr_thread_name, thread->idthread); else - pj_ansi_snprintf(thread->obj_name, sizeof(thread->obj_name), - "thr%p", (void*)(pj_ssize_t)thread->idthread); + pj_ansi_snprintf(thread->obj_name, sizeof(thread->obj_name), + "thr%p", (void*)(pj_ssize_t)thread->idthread); rc = pj_thread_local_set(thread_tls_id, thread); if (rc != PJ_SUCCESS) - return rc; + return rc; *thread_ptr = thread; return PJ_SUCCESS; @@ -444,7 +443,7 @@ pj_status_t pj_thread_init(void) rc = pj_thread_local_alloc(&thread_tls_id); if (rc != PJ_SUCCESS) - return rc; + return rc; return pj_thread_register("thr%p", main_thread, &thread); } @@ -465,7 +464,7 @@ typedef struct tagTHREADNAME_INFO { // The SetThreadDescription API was brought in version 1607 of Windows 10. typedef HRESULT(WINAPI *FnSetThreadDescription)(HANDLE hThread, - PCWSTR lpThreadDescription); + PCWSTR lpThreadDescription); static void set_thread_display_name(const char *name) { @@ -477,13 +476,13 @@ static void set_thread_display_name(const char *name) #else /* Set thread name by SetThreadDescription (if support) */ FnSetThreadDescription fn = (FnSetThreadDescription)GetProcAddress( - GetModuleHandle(PJ_T("Kernel32.dll")), "SetThreadDescription"); + GetModuleHandle(PJ_T("Kernel32.dll")), "SetThreadDescription"); PJ_LOG(5, (THIS_FILE, "SetThreadDescription:%p, name:%s", fn, name)); if (fn) { - wchar_t wname[PJ_MAX_OBJ_NAME]; - pj_ansi_to_unicode(name, pj_ansi_strlen(name), wname, PJ_MAX_OBJ_NAME); - fn(GetCurrentThread(), wname); - return; + wchar_t wname[PJ_MAX_OBJ_NAME]; + pj_ansi_to_unicode(name, pj_ansi_strlen(name), wname, PJ_MAX_OBJ_NAME); + fn(GetCurrentThread(), wname); + return; } /* Set thread name by throwing an exception */ @@ -493,23 +492,23 @@ static void set_thread_display_name(const char *name) // The debugger needs to be around to catch the name in the exception. // If there isn't a debugger, we are needlessly throwing an exception. if (!IsDebuggerPresent()) { - return; + return; } { - const DWORD MS_VC_EXCEPTION = 0x406D1388; - THREADNAME_INFO info; - info.dwType = 0x1000; - info.szName = name; - info.dwThreadID = (DWORD)-1; - info.dwFlags = 0; + const DWORD MS_VC_EXCEPTION = 0x406D1388; + THREADNAME_INFO info; + info.dwType = 0x1000; + info.szName = name; + info.dwThreadID = (DWORD)-1; + info.dwFlags = 0; #pragma warning(push) #pragma warning(disable : 6320 6322) - __try { - RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), - (ULONG_PTR *)&info); - } __except (EXCEPTION_EXECUTE_HANDLER) { - } + __try { + RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), + (ULONG_PTR *)&info); + } __except (EXCEPTION_EXECUTE_HANDLER) { + } #pragma warning(pop) } # endif @@ -527,7 +526,7 @@ static DWORD WINAPI thread_main(void *param) #endif if (pj_thread_local_set(thread_tls_id, rec) != PJ_SUCCESS) { - pj_assert(!"TLS is not set (pj_init() error?)"); + pj_assert(!"TLS is not set (pj_init() error?)"); } PJ_LOG(6,(rec->obj_name, "Thread started")); @@ -539,7 +538,7 @@ static DWORD WINAPI thread_main(void *param) PJ_LOG(6,(rec->obj_name, "Thread quitting")); #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0 PJ_LOG(5,(rec->obj_name, "Thread stack max usage=%u by %s:%d", - rec->stk_max_usage, rec->caller_file, rec->caller_line)); + rec->stk_max_usage, rec->caller_file, rec->caller_line)); #endif return (DWORD)result; @@ -550,10 +549,10 @@ static DWORD WINAPI thread_main(void *param) */ PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool, const char *thread_name, - pj_thread_proc *proc, + pj_thread_proc *proc, void *arg, - pj_size_t stack_size, - unsigned flags, + pj_size_t stack_size, + unsigned flags, pj_thread_t **thread_ptr) { DWORD dwflags = 0; @@ -568,22 +567,22 @@ PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool, /* Set flags */ if (flags & PJ_THREAD_SUSPENDED) - dwflags |= CREATE_SUSPENDED; + dwflags |= CREATE_SUSPENDED; /* Create thread record and assign name for the thread */ rec = (struct pj_thread_t*) pj_pool_calloc(pool, 1, sizeof(pj_thread_t)); if (!rec) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Set name. */ if (!thread_name) - thread_name = "thr%p"; + thread_name = "thr%p"; if (strchr(thread_name, '%')) { - pj_ansi_snprintf(rec->obj_name, PJ_MAX_OBJ_NAME, thread_name, rec); + pj_ansi_snprintf(rec->obj_name, PJ_MAX_OBJ_NAME, thread_name, rec); } else { - pj_ansi_strncpy(rec->obj_name, thread_name, PJ_MAX_OBJ_NAME); - rec->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; + pj_ansi_strncpy(rec->obj_name, thread_name, PJ_MAX_OBJ_NAME); + rec->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; } PJ_LOG(6, (rec->obj_name, "Thread created")); @@ -599,16 +598,16 @@ PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool, #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 rec->hthread = CreateThreadRT(NULL, 0, - thread_main, rec, - dwflags, NULL); + thread_main, rec, + dwflags, NULL); #else rec->hthread = CreateThread(NULL, stack_size, - thread_main, rec, - dwflags, &rec->idthread); + thread_main, rec, + dwflags, &rec->idthread); #endif if (rec->hthread == NULL) - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); /* Success! */ *thread_ptr = rec; @@ -656,9 +655,9 @@ PJ_DEF(pj_thread_t*) pj_thread_this(void) pj_thread_t *rec = pj_thread_local_get(thread_tls_id); if (rec == NULL) { - pj_assert(!"Calling pjlib from unknown/external thread. You must " - "register external threads with pj_thread_register() " - "before calling any pjlib functions."); + pj_assert(!"Calling pjlib from unknown/external thread. You must " + "register external threads with pj_thread_register() " + "before calling any pjlib functions."); } /* @@ -682,7 +681,7 @@ PJ_DEF(pj_status_t) pj_thread_join(pj_thread_t *p) PJ_ASSERT_RETURN(p, PJ_EINVAL); if (p == pj_thread_this()) - return PJ_ECANCELLED; + return PJ_ECANCELLED; PJ_LOG(6, (pj_thread_this()->obj_name, "Joining thread %s", p->obj_name)); @@ -747,17 +746,17 @@ PJ_DEF(void) pj_thread_check_stack(const char *file, int line) /* Calculate current usage. */ usage = (&stk_ptr > thread->stk_start) ? - (pj_uint32_t)(&stk_ptr - thread->stk_start) : - (pj_uint32_t)(thread->stk_start - &stk_ptr); + (pj_uint32_t)(&stk_ptr - thread->stk_start) : + (pj_uint32_t)(thread->stk_start - &stk_ptr); /* Assert if stack usage is dangerously high. */ pj_assert("STACK OVERFLOW!! " && (usage <= thread->stk_size - 128)); /* Keep statistic. */ if (usage > thread->stk_max_usage) { - thread->stk_max_usage = usage; - thread->caller_file = file; - thread->caller_line = line; + thread->stk_max_usage = usage; + thread->caller_file = file; + thread->caller_line = line; } } @@ -774,8 +773,8 @@ PJ_DEF(pj_uint32_t) pj_thread_get_stack_max_usage(pj_thread_t *thread) * pj_thread_get_stack_info() */ PJ_DEF(pj_status_t) pj_thread_get_stack_info( pj_thread_t *thread, - const char **file, - int *line ) + const char **file, + int *line ) { pj_assert(thread); @@ -784,7 +783,7 @@ PJ_DEF(pj_status_t) pj_thread_get_stack_info( pj_thread_t *thread, return 0; } -#endif /* PJ_OS_HAS_CHECK_STACK */ +#endif /* PJ_OS_HAS_CHECK_STACK */ /////////////////////////////////////////////////////////////////////////////// @@ -798,7 +797,7 @@ PJ_DEF(pj_status_t) pj_atomic_create( pj_pool_t *pool, { pj_atomic_t *atomic_var = pj_pool_alloc(pool, sizeof(pj_atomic_t)); if (!atomic_var) - return PJ_ENOMEM; + return PJ_ENOMEM; atomic_var->value = initial; *atomic_ptr = atomic_var; @@ -889,7 +888,7 @@ PJ_DEF(void) pj_atomic_dec(pj_atomic_t *atomic_var) * pj_atomic_add() */ PJ_DEF(void) pj_atomic_add( pj_atomic_t *atomic_var, - pj_atomic_value_t value ) + pj_atomic_value_t value ) { PJ_ASSERT_ON_FAIL(atomic_var, return); #if defined(PJ_WIN32_WINNT) && PJ_WIN32_WINNT >= 0x0400 @@ -903,7 +902,7 @@ PJ_DEF(void) pj_atomic_add( pj_atomic_t *atomic_var, * pj_atomic_add_and_get() */ PJ_DEF(pj_atomic_value_t) pj_atomic_add_and_get( pj_atomic_t *atomic_var, - pj_atomic_value_t value) + pj_atomic_value_t value) { #if defined(PJ_WIN32_WINNT) && PJ_WIN32_WINNT >= 0x0400 long oldValue = InterlockedExchangeAdd( &atomic_var->value, value); @@ -999,7 +998,7 @@ static pj_status_t init_mutex(pj_mutex_t *mutex, const char *name) #else mutex->hMutex = CreateMutex(NULL, FALSE, NULL); if (!mutex->hMutex) { - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); } #endif @@ -1011,13 +1010,13 @@ static pj_status_t init_mutex(pj_mutex_t *mutex, const char *name) /* Set name. */ if (!name) { - name = "mtx%p"; + name = "mtx%p"; } if (strchr(name, '%')) { - pj_ansi_snprintf(mutex->obj_name, PJ_MAX_OBJ_NAME, name, mutex); + pj_ansi_snprintf(mutex->obj_name, PJ_MAX_OBJ_NAME, name, mutex); } else { - pj_ansi_strncpy(mutex->obj_name, name, PJ_MAX_OBJ_NAME); - mutex->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; + pj_ansi_strncpy(mutex->obj_name, name, PJ_MAX_OBJ_NAME); + mutex->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; } PJ_LOG(6, (mutex->obj_name, "Mutex created")); @@ -1056,7 +1055,7 @@ PJ_DEF(pj_status_t) pj_mutex_create(pj_pool_t *pool, */ PJ_DEF(pj_status_t) pj_mutex_create_simple( pj_pool_t *pool, const char *name, - pj_mutex_t **mutex ) + pj_mutex_t **mutex ) { return pj_mutex_create(pool, name, PJ_MUTEX_SIMPLE, mutex); } @@ -1065,8 +1064,8 @@ PJ_DEF(pj_status_t) pj_mutex_create_simple( pj_pool_t *pool, * pj_mutex_create_recursive() */ PJ_DEF(pj_status_t) pj_mutex_create_recursive( pj_pool_t *pool, - const char *name, - pj_mutex_t **mutex ) + const char *name, + pj_mutex_t **mutex ) { return pj_mutex_create(pool, name, PJ_MUTEX_RECURSE, mutex); } @@ -1082,7 +1081,7 @@ PJ_DEF(pj_status_t) pj_mutex_lock(pj_mutex_t *mutex) PJ_ASSERT_RETURN(mutex, PJ_EINVAL); LOG_MUTEX((mutex->obj_name, "Mutex: thread %s is waiting", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); #if PJ_WIN32_WINNT >= 0x0400 EnterCriticalSection(&mutex->crit); @@ -1095,13 +1094,13 @@ PJ_DEF(pj_status_t) pj_mutex_lock(pj_mutex_t *mutex) #endif LOG_MUTEX((mutex->obj_name, - (status==PJ_SUCCESS ? "Mutex acquired by thread %s" : "FAILED by %s"), - pj_thread_this()->obj_name)); + (status==PJ_SUCCESS ? "Mutex acquired by thread %s" : "FAILED by %s"), + pj_thread_this()->obj_name)); #if PJ_DEBUG if (status == PJ_SUCCESS) { - mutex->owner = pj_thread_this(); - ++mutex->nesting_level; + mutex->owner = pj_thread_this(); + ++mutex->nesting_level; } #endif @@ -1121,12 +1120,12 @@ PJ_DEF(pj_status_t) pj_mutex_unlock(pj_mutex_t *mutex) #if PJ_DEBUG pj_assert(mutex->owner == pj_thread_this()); if (--mutex->nesting_level == 0) { - mutex->owner = NULL; + mutex->owner = NULL; } #endif LOG_MUTEX((mutex->obj_name, "Mutex released by thread %s", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); #if PJ_WIN32_WINNT >= 0x0400 LeaveCriticalSection(&mutex->crit); @@ -1149,7 +1148,7 @@ PJ_DEF(pj_status_t) pj_mutex_trylock(pj_mutex_t *mutex) PJ_ASSERT_RETURN(mutex, PJ_EINVAL); LOG_MUTEX((mutex->obj_name, "Mutex: thread %s is trying", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); #if PJ_WIN32_WINNT >= 0x0400 status=TryEnterCriticalSection(&mutex->crit) ? PJ_SUCCESS : PJ_EUNKNOWN; @@ -1158,16 +1157,16 @@ PJ_DEF(pj_status_t) pj_mutex_trylock(pj_mutex_t *mutex) PJ_SUCCESS : PJ_ETIMEDOUT; #endif if (status==PJ_SUCCESS) { - LOG_MUTEX((mutex->obj_name, "Mutex acquired by thread %s", - pj_thread_this()->obj_name)); + LOG_MUTEX((mutex->obj_name, "Mutex acquired by thread %s", + pj_thread_this()->obj_name)); #if PJ_DEBUG - mutex->owner = pj_thread_this(); - ++mutex->nesting_level; + mutex->owner = pj_thread_this(); + ++mutex->nesting_level; #endif } else { - LOG_MUTEX((mutex->obj_name, "Mutex: thread %s's trylock() failed", - pj_thread_this()->obj_name)); + LOG_MUTEX((mutex->obj_name, "Mutex: thread %s's trylock() failed", + pj_thread_this()->obj_name)); } return status; @@ -1238,7 +1237,7 @@ PJ_DEF(void) pj_leave_critical_section(void) */ PJ_DEF(pj_status_t) pj_sem_create( pj_pool_t *pool, const char *name, - unsigned initial, + unsigned initial, unsigned max, pj_sem_t **sem_ptr) { @@ -1252,23 +1251,23 @@ PJ_DEF(pj_status_t) pj_sem_create( pj_pool_t *pool, #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 /** SEMAPHORE_ALL_ACCESS **/ sem->hSemaphore = CreateSemaphoreEx(NULL, initial, max, NULL, 0, - SEMAPHORE_ALL_ACCESS); + SEMAPHORE_ALL_ACCESS); #else sem->hSemaphore = CreateSemaphore(NULL, initial, max, NULL); #endif if (!sem->hSemaphore) - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); /* Set name. */ if (!name) { - name = "sem%p"; + name = "sem%p"; } if (strchr(name, '%')) { - pj_ansi_snprintf(sem->obj_name, PJ_MAX_OBJ_NAME, name, sem); + pj_ansi_snprintf(sem->obj_name, PJ_MAX_OBJ_NAME, name, sem); } else { - pj_ansi_strncpy(sem->obj_name, name, PJ_MAX_OBJ_NAME); - sem->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; + pj_ansi_strncpy(sem->obj_name, name, PJ_MAX_OBJ_NAME); + sem->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; } LOG_MUTEX((sem->obj_name, "Semaphore created")); @@ -1285,7 +1284,7 @@ static pj_status_t pj_sem_wait_for(pj_sem_t *sem, unsigned timeout) PJ_ASSERT_RETURN(sem, PJ_EINVAL); LOG_MUTEX((sem->obj_name, "Semaphore: thread %s is waiting", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 result = WaitForSingleObjectEx(sem->hSemaphore, timeout, FALSE); @@ -1294,11 +1293,11 @@ static pj_status_t pj_sem_wait_for(pj_sem_t *sem, unsigned timeout) #endif if (result == WAIT_OBJECT_0) { - LOG_MUTEX((sem->obj_name, "Semaphore acquired by thread %s", - pj_thread_this()->obj_name)); + LOG_MUTEX((sem->obj_name, "Semaphore acquired by thread %s", + pj_thread_this()->obj_name)); } else { - LOG_MUTEX((sem->obj_name, "Semaphore: thread %s FAILED to acquire", - pj_thread_this()->obj_name)); + LOG_MUTEX((sem->obj_name, "Semaphore: thread %s FAILED to acquire", + pj_thread_this()->obj_name)); } if (result==WAIT_OBJECT_0) @@ -1340,7 +1339,7 @@ PJ_DEF(pj_status_t) pj_sem_post(pj_sem_t *sem) PJ_ASSERT_RETURN(sem, PJ_EINVAL); LOG_MUTEX((sem->obj_name, "Semaphore released by thread %s", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); if (ReleaseSemaphore(sem->hSemaphore, 1, NULL)) return PJ_SUCCESS; @@ -1357,7 +1356,7 @@ PJ_DEF(pj_status_t) pj_sem_destroy(pj_sem_t *sem) PJ_ASSERT_RETURN(sem, PJ_EINVAL); LOG_MUTEX((sem->obj_name, "Semaphore destroyed by thread %s", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); if (CloseHandle(sem->hSemaphore)) return PJ_SUCCESS; @@ -1365,7 +1364,7 @@ PJ_DEF(pj_status_t) pj_sem_destroy(pj_sem_t *sem) return PJ_RETURN_OS_ERROR(GetLastError()); } -#endif /* PJ_HAS_SEMAPHORE */ +#endif /* PJ_HAS_SEMAPHORE */ /////////////////////////////////////////////////////////////////////////////// @@ -1376,7 +1375,7 @@ PJ_DEF(pj_status_t) pj_sem_destroy(pj_sem_t *sem) */ PJ_DEF(pj_status_t) pj_event_create( pj_pool_t *pool, const char *name, - pj_bool_t manual_reset, + pj_bool_t manual_reset, pj_bool_t initial, pj_event_t **event_ptr) { @@ -1391,25 +1390,25 @@ PJ_DEF(pj_status_t) pj_event_create( pj_pool_t *pool, #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 event->hEvent = CreateEventEx(NULL, NULL, - (manual_reset? 0x1:0x0) | (initial? 0x2:0x0), - EVENT_ALL_ACCESS); + (manual_reset? 0x1:0x0) | (initial? 0x2:0x0), + EVENT_ALL_ACCESS); #else event->hEvent = CreateEvent(NULL, manual_reset ? TRUE : FALSE, - initial ? TRUE : FALSE, NULL); + initial ? TRUE : FALSE, NULL); #endif if (!event->hEvent) - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); /* Set name. */ if (!name) { - name = "evt%p"; + name = "evt%p"; } if (strchr(name, '%')) { - pj_ansi_snprintf(event->obj_name, PJ_MAX_OBJ_NAME, name, event); + pj_ansi_snprintf(event->obj_name, PJ_MAX_OBJ_NAME, name, event); } else { - pj_ansi_strncpy(event->obj_name, name, PJ_MAX_OBJ_NAME); - event->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; + pj_ansi_strncpy(event->obj_name, name, PJ_MAX_OBJ_NAME); + event->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; } PJ_LOG(6, (event->obj_name, "Event created")); @@ -1426,7 +1425,7 @@ static pj_status_t pj_event_wait_for(pj_event_t *event, unsigned timeout) PJ_ASSERT_RETURN(event, PJ_EINVAL); PJ_LOG(6, (event->obj_name, "Event: thread %s is waiting", - pj_thread_this()->obj_name)); + pj_thread_this()->obj_name)); #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 result = WaitForSingleObjectEx(event->hEvent, timeout, FALSE); @@ -1435,11 +1434,11 @@ static pj_status_t pj_event_wait_for(pj_event_t *event, unsigned timeout) #endif if (result == WAIT_OBJECT_0) { - PJ_LOG(6, (event->obj_name, "Event: thread %s is released", - pj_thread_this()->obj_name)); + PJ_LOG(6, (event->obj_name, "Event: thread %s is released", + pj_thread_this()->obj_name)); } else { - PJ_LOG(6, (event->obj_name, "Event: thread %s FAILED to acquire", - pj_thread_this()->obj_name)); + PJ_LOG(6, (event->obj_name, "Event: thread %s FAILED to acquire", + pj_thread_this()->obj_name)); } if (result==WAIT_OBJECT_0) @@ -1502,9 +1501,9 @@ PJ_DEF(pj_status_t) pj_event_pulse(pj_event_t *event) PJ_LOG(6, (event->obj_name, "Pulsing event")); if (PulseEvent(event->hEvent)) - return PJ_SUCCESS; + return PJ_SUCCESS; else - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); #endif } @@ -1540,7 +1539,7 @@ PJ_DEF(pj_status_t) pj_event_destroy(pj_event_t *event) return PJ_RETURN_OS_ERROR(GetLastError()); } -#endif /* PJ_HAS_EVENT_OBJ */ +#endif /* PJ_HAS_EVENT_OBJ */ /////////////////////////////////////////////////////////////////////////////// #if defined(PJ_TERM_HAS_COLOR) && PJ_TERM_HAS_COLOR != 0 @@ -1553,13 +1552,13 @@ static WORD pj_color_to_os_attr(pj_color_t color) WORD attr = 0; if (color & PJ_TERM_COLOR_R) - attr |= FOREGROUND_RED; + attr |= FOREGROUND_RED; if (color & PJ_TERM_COLOR_G) - attr |= FOREGROUND_GREEN; + attr |= FOREGROUND_GREEN; if (color & PJ_TERM_COLOR_B) - attr |= FOREGROUND_BLUE; + attr |= FOREGROUND_BLUE; if (color & PJ_TERM_COLOR_BRIGHT) - attr |= FOREGROUND_INTENSITY; + attr |= FOREGROUND_INTENSITY; return attr; } @@ -1569,13 +1568,13 @@ static pj_color_t os_attr_to_pj_color(WORD attr) int color = 0; if (attr & FOREGROUND_RED) - color |= PJ_TERM_COLOR_R; + color |= PJ_TERM_COLOR_R; if (attr & FOREGROUND_GREEN) - color |= PJ_TERM_COLOR_G; + color |= PJ_TERM_COLOR_G; if (attr & FOREGROUND_BLUE) - color |= PJ_TERM_COLOR_B; + color |= PJ_TERM_COLOR_B; if (attr & FOREGROUND_INTENSITY) - color |= PJ_TERM_COLOR_BRIGHT; + color |= PJ_TERM_COLOR_BRIGHT; return color; } @@ -1610,7 +1609,7 @@ PJ_DEF(pj_color_t) pj_term_get_color(void) return os_attr_to_pj_color(info.wAttributes); } -#endif /* PJ_TERM_HAS_COLOR */ +#endif /* PJ_TERM_HAS_COLOR */ /* * pj_run_app() diff --git a/pjlib/src/pj/os_error_symbian.cpp b/pjlib/src/pj/os_error_symbian.cpp index d04907fe54..ee0dbd3f3e 100644 --- a/pjlib/src/pj/os_error_symbian.cpp +++ b/pjlib/src/pj/os_error_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,51 +34,51 @@ static const struct { /* * Generic error -1 to -46 */ - PJ_BUILD_ERR( KErrNotFound, "Unable to find the specified object"), - PJ_BUILD_ERR( KErrGeneral, "General (unspecified) error"), - PJ_BUILD_ERR( KErrCancel, "The operation was cancelled"), - PJ_BUILD_ERR( KErrNoMemory, "Not enough memory"), + PJ_BUILD_ERR( KErrNotFound, "Unable to find the specified object"), + PJ_BUILD_ERR( KErrGeneral, "General (unspecified) error"), + PJ_BUILD_ERR( KErrCancel, "The operation was cancelled"), + PJ_BUILD_ERR( KErrNoMemory, "Not enough memory"), PJ_BUILD_ERR( KErrNotSupported, "The operation requested is not supported"), - PJ_BUILD_ERR( KErrArgument, "Bad request"), + PJ_BUILD_ERR( KErrArgument, "Bad request"), PJ_BUILD_ERR( KErrTotalLossOfPrecision, "Total loss of precision"), PJ_BUILD_ERR( KErrBadHandle, "Bad object"), - PJ_BUILD_ERR( KErrOverflow, "Overflow"), + PJ_BUILD_ERR( KErrOverflow, "Overflow"), PJ_BUILD_ERR( KErrUnderflow, "Underflow"), PJ_BUILD_ERR( KErrAlreadyExists,"Already exists"), PJ_BUILD_ERR( KErrPathNotFound, "Unable to find the specified folder"), - PJ_BUILD_ERR( KErrDied, "Closed"), - PJ_BUILD_ERR( KErrInUse, "The specified object is currently in use by another program"), - PJ_BUILD_ERR( KErrServerTerminated, "Server has closed"), + PJ_BUILD_ERR( KErrDied, "Closed"), + PJ_BUILD_ERR( KErrInUse, "The specified object is currently in use by another program"), + PJ_BUILD_ERR( KErrServerTerminated, "Server has closed"), PJ_BUILD_ERR( KErrServerBusy, "Server busy"), PJ_BUILD_ERR( KErrCompletion, "Completion error"), - PJ_BUILD_ERR( KErrNotReady, "Not ready"), - PJ_BUILD_ERR( KErrUnknown, "Unknown error"), - PJ_BUILD_ERR( KErrCorrupt, "Corrupt"), + PJ_BUILD_ERR( KErrNotReady, "Not ready"), + PJ_BUILD_ERR( KErrUnknown, "Unknown error"), + PJ_BUILD_ERR( KErrCorrupt, "Corrupt"), PJ_BUILD_ERR( KErrAccessDenied, "Access denied"), - PJ_BUILD_ERR( KErrLocked, "Locked"), - PJ_BUILD_ERR( KErrWrite, "Failed to write"), + PJ_BUILD_ERR( KErrLocked, "Locked"), + PJ_BUILD_ERR( KErrWrite, "Failed to write"), PJ_BUILD_ERR( KErrDisMounted, "Wrong disk present"), - PJ_BUILD_ERR( KErrEof, "Unexpected end of file"), - PJ_BUILD_ERR( KErrDiskFull, "Disk full"), + PJ_BUILD_ERR( KErrEof, "Unexpected end of file"), + PJ_BUILD_ERR( KErrDiskFull, "Disk full"), PJ_BUILD_ERR( KErrBadDriver, "Bad device driver"), - PJ_BUILD_ERR( KErrBadName, "Bad name"), + PJ_BUILD_ERR( KErrBadName, "Bad name"), PJ_BUILD_ERR( KErrCommsLineFail,"Comms line failed"), PJ_BUILD_ERR( KErrCommsFrame, "Comms frame error"), PJ_BUILD_ERR( KErrCommsOverrun, "Comms overrun error"), PJ_BUILD_ERR( KErrCommsParity, "Comms parity error"), - PJ_BUILD_ERR( KErrTimedOut, "Timed out"), + PJ_BUILD_ERR( KErrTimedOut, "Timed out"), PJ_BUILD_ERR( KErrCouldNotConnect, "Failed to connect"), PJ_BUILD_ERR( KErrCouldNotDisconnect, "Failed to disconnect"), PJ_BUILD_ERR( KErrDisconnected, "Disconnected"), PJ_BUILD_ERR( KErrBadLibraryEntryPoint, "Bad library entry point"), PJ_BUILD_ERR( KErrBadDescriptor,"Bad descriptor"), - PJ_BUILD_ERR( KErrAbort, "Interrupted"), - PJ_BUILD_ERR( KErrTooBig, "Too big"), + PJ_BUILD_ERR( KErrAbort, "Interrupted"), + PJ_BUILD_ERR( KErrTooBig, "Too big"), PJ_BUILD_ERR( KErrDivideByZero, "Divide by zero"), - PJ_BUILD_ERR( KErrBadPower, "Batteries too low"), - PJ_BUILD_ERR( KErrDirFull, "Folder full"), + PJ_BUILD_ERR( KErrBadPower, "Batteries too low"), + PJ_BUILD_ERR( KErrDirFull, "Folder full"), PJ_BUILD_ERR( KErrHardwareNotAvailable, ""), - PJ_BUILD_ERR( KErrSessionClosed, ""), + PJ_BUILD_ERR( KErrSessionClosed, ""), PJ_BUILD_ERR( KErrPermissionDenied, ""), /* @@ -94,7 +93,7 @@ static const struct { {0, NULL} }; -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ PJ_DEF(pj_status_t) pj_get_os_error(void) @@ -120,7 +119,7 @@ PJ_DEF(void) pj_set_netos_error(pj_status_t code) PJ_BEGIN_DECL PJ_DECL(int) platform_strerror( pj_os_err_type os_errcode, - char *buf, pj_size_t bufsize); + char *buf, pj_size_t bufsize); PJ_END_DECL /* @@ -130,7 +129,7 @@ PJ_END_DECL * in errno.c */ PJ_DEF(int) platform_strerror( pj_os_err_type os_errcode, - char *buf, pj_size_t bufsize) + char *buf, pj_size_t bufsize) { int len = 0; @@ -145,26 +144,26 @@ PJ_DEF(int) platform_strerror( pj_os_err_type os_errcode, if (!len) { #if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING!=0) - int i; + int i; for (i = 0; gaErrorList[i].msg; ++i) { if (gaErrorList[i].code == os_errcode) { len = strlen(gaErrorList[i].msg); - if ((pj_size_t)len >= bufsize) { - len = bufsize-1; - } - pj_memcpy(buf, gaErrorList[i].msg, len); - buf[len] = '\0'; + if ((pj_size_t)len >= bufsize) { + len = bufsize-1; + } + pj_memcpy(buf, gaErrorList[i].msg, len); + buf[len] = '\0'; break; } } -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ } if (!len) { - len = pj_ansi_snprintf( buf, bufsize-1, "Symbian native error %d", - os_errcode); - buf[len] = '\0'; + len = pj_ansi_snprintf( buf, bufsize-1, "Symbian native error %d", + os_errcode); + buf[len] = '\0'; } return len; diff --git a/pjlib/src/pj/os_error_unix.c b/pjlib/src/pj/os_error_unix.c index 523f585a25..45dffdbf92 100644 --- a/pjlib/src/pj/os_error_unix.c +++ b/pjlib/src/pj/os_error_unix.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,7 +43,7 @@ PJ_DEF(void) pj_set_netos_error(pj_status_t code) PJ_BEGIN_DECL PJ_DECL(int) platform_strerror(pj_os_err_type code, - char *buf, pj_size_t bufsize ); + char *buf, pj_size_t bufsize ); PJ_END_DECL /* @@ -61,7 +60,7 @@ int platform_strerror( pj_os_err_type os_errcode, if (len >= bufsize) len = bufsize - 1; if (len > 0) - pj_memcpy(buf, syserr, len); + pj_memcpy(buf, syserr, len); buf[len] = '\0'; return len; } diff --git a/pjlib/src/pj/os_error_win32.c b/pjlib/src/pj/os_error_win32.c index 3cdc25f617..25719aad42 100644 --- a/pjlib/src/pj/os_error_win32.c +++ b/pjlib/src/pj/os_error_win32.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -109,7 +108,7 @@ static const struct { {0, NULL} }; -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ @@ -156,63 +155,63 @@ int platform_strerror( pj_os_err_type os_errcode, if (!len) { #if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING!=0) - int i; + int i; for (i = 0; gaErrorList[i].msg; ++i) { if (gaErrorList[i].code == os_errcode) { len = strlen(gaErrorList[i].msg); - if ((pj_size_t)len >= bufsize) { - len = bufsize-1; - } - pj_memcpy(buf, gaErrorList[i].msg, len); - buf[len] = '\0'; + if ((pj_size_t)len >= bufsize) { + len = bufsize-1; + } + pj_memcpy(buf, gaErrorList[i].msg, len); + buf[len] = '\0'; break; } } -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ } if (!len) { #if PJ_NATIVE_STRING_IS_UNICODE - len = FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - os_errcode, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - wbuf, - PJ_ARRAY_SIZE(wbuf), - NULL); - if (len) { - pj_unicode_to_ansi(wbuf, len, buf, bufsize); - } + len = FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + os_errcode, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + wbuf, + PJ_ARRAY_SIZE(wbuf), + NULL); + if (len) { + pj_unicode_to_ansi(wbuf, len, buf, bufsize); + } #else - len = FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - os_errcode, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - buf, - (int)bufsize, - NULL); - buf[bufsize-1] = '\0'; + len = FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + os_errcode, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + buf, + (int)bufsize, + NULL); + buf[bufsize-1] = '\0'; #endif - if (len) { - /* Remove trailing newlines. */ - while (len && (buf[len-1] == '\n' || buf[len-1] == '\r')) { - buf[len-1] = '\0'; - --len; - } - } + if (len) { + /* Remove trailing newlines. */ + while (len && (buf[len-1] == '\n' || buf[len-1] == '\r')) { + buf[len-1] = '\0'; + --len; + } + } } if (!len) { - len = pj_ansi_snprintf( buf, bufsize, "Win32 error code %u", - (unsigned)os_errcode); - if (len < 0 || len >= (int)bufsize) - len = bufsize-1; - buf[len] = '\0'; + len = pj_ansi_snprintf( buf, bufsize, "Win32 error code %u", + (unsigned)os_errcode); + if (len < 0 || len >= (int)bufsize) + len = bufsize-1; + buf[len] = '\0'; } return (int)len; diff --git a/pjlib/src/pj/os_info.c b/pjlib/src/pj/os_info.c index 0c268e93db..b3304ae543 100644 --- a/pjlib/src/pj/os_info.c +++ b/pjlib/src/pj/os_info.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,7 +31,7 @@ /* For uname() */ # include # include -# define PJ_HAS_UNAME 1 +# define PJ_HAS_UNAME 1 #endif #if defined(PJ_HAS_LIMITS_H) && PJ_HAS_LIMITS_H != 0 @@ -52,7 +51,7 @@ #endif #ifndef PJ_SYS_INFO_BUFFER_SIZE -# define PJ_SYS_INFO_BUFFER_SIZE 64 +# define PJ_SYS_INFO_BUFFER_SIZE 64 #endif @@ -76,22 +75,22 @@ static char *ver_info(pj_uint32_t ver, char *buf) pj_size_t len; if (ver == 0) { - *buf = '\0'; - return buf; + *buf = '\0'; + return buf; } sprintf(buf, "-%u.%u", - (ver & 0xFF000000) >> 24, - (ver & 0x00FF0000) >> 16); + (ver & 0xFF000000) >> 24, + (ver & 0x00FF0000) >> 16); len = strlen(buf); if (ver & 0xFFFF) { - sprintf(buf+len, ".%u", (ver & 0xFF00) >> 8); - len = strlen(buf); + sprintf(buf+len, ".%u", (ver & 0xFF00) >> 8); + len = strlen(buf); - if (ver & 0x00FF) { - sprintf(buf+len, ".%u", (ver & 0xFF)); - } + if (ver & 0x00FF) { + sprintf(buf+len, ".%u", (ver & 0xFF)); + } } return buf; @@ -106,22 +105,22 @@ static pj_uint32_t parse_version(char *str) pj_str_t token, delim; while (*str && !pj_isdigit(*str)) - str++; + str++; maxtok = 4; delim = pj_str(".-"); for (found_idx = pj_strtok(&in_str, &delim, &token, 0), i=0; - found_idx != in_str.slen && i < maxtok; - ++i, found_idx = pj_strtok(&in_str, &delim, &token, - found_idx + token.slen)) + found_idx != in_str.slen && i < maxtok; + ++i, found_idx = pj_strtok(&in_str, &delim, &token, + found_idx + token.slen)) { - int n; + int n; - if (!pj_isdigit(*token.ptr)) - break; - - n = atoi(token.ptr); - version |= (n << ((3-i)*8)); + if (!pj_isdigit(*token.ptr)) + break; + + n = atoi(token.ptr); + version |= (n << ((3-i)*8)); } return version; @@ -135,141 +134,141 @@ PJ_DEF(const pj_sys_info*) pj_get_sys_info(void) pj_size_t left = PJ_SYS_INFO_BUFFER_SIZE, len; if (si_initialized) - return &si; + return &si; si.machine.ptr = si.os_name.ptr = si.sdk_name.ptr = si.info.ptr = ""; -#define ALLOC_CP_STR(str,field) \ - do { \ - len = pj_ansi_strlen(str); \ - if (len && left >= len+1) { \ - si.field.ptr = si_buffer + PJ_SYS_INFO_BUFFER_SIZE - left; \ - si.field.slen = len; \ - pj_memcpy(si.field.ptr, str, len+1); \ - left -= (len+1); \ - } \ - } while (0) +#define ALLOC_CP_STR(str,field) \ + do { \ + len = pj_ansi_strlen(str); \ + if (len && left >= len+1) { \ + si.field.ptr = si_buffer + PJ_SYS_INFO_BUFFER_SIZE - left; \ + si.field.slen = len; \ + pj_memcpy(si.field.ptr, str, len+1); \ + left -= (len+1); \ + } \ + } while (0) /* * Machine and OS info. */ #if defined(PJ_HAS_UNAME) && PJ_HAS_UNAME #if defined(PJ_DARWINOS) && PJ_DARWINOS != 0 && TARGET_OS_IPHONE && \ - (!defined TARGET_IPHONE_SIMULATOR || TARGET_IPHONE_SIMULATOR == 0) + (!defined TARGET_IPHONE_SIMULATOR || TARGET_IPHONE_SIMULATOR == 0) { - pj_str_t buf = {si_buffer + PJ_SYS_INFO_BUFFER_SIZE - left, left}; - pj_str_t machine = {"arm-", 4}; - pj_str_t sdk_name = {"iOS-SDK", 7}; + pj_str_t buf = {si_buffer + PJ_SYS_INFO_BUFFER_SIZE - left, left}; + pj_str_t machine = {"arm-", 4}; + pj_str_t sdk_name = {"iOS-SDK", 7}; size_t size = PJ_SYS_INFO_BUFFER_SIZE - machine.slen; - char tmp[PJ_SYS_INFO_BUFFER_SIZE]; + char tmp[PJ_SYS_INFO_BUFFER_SIZE]; int name[] = {CTL_HW,HW_MACHINE}; - pj_iphone_os_get_sys_info(&si, &buf); - left -= si.os_name.slen + 1; + pj_iphone_os_get_sys_info(&si, &buf); + left -= si.os_name.slen + 1; - si.os_ver = parse_version(si.machine.ptr); + si.os_ver = parse_version(si.machine.ptr); - pj_memcpy(tmp, machine.ptr, machine.slen); + pj_memcpy(tmp, machine.ptr, machine.slen); sysctl(name, 2, tmp+machine.slen, &size, NULL, 0); ALLOC_CP_STR(tmp, machine); - si.sdk_name = sdk_name; + si.sdk_name = sdk_name; - #ifdef PJ_SDK_NAME - pj_memcpy(tmp, PJ_SDK_NAME, pj_ansi_strlen(PJ_SDK_NAME) + 1); - si.sdk_ver = parse_version(tmp); - #endif + #ifdef PJ_SDK_NAME + pj_memcpy(tmp, PJ_SDK_NAME, pj_ansi_strlen(PJ_SDK_NAME) + 1); + si.sdk_ver = parse_version(tmp); + #endif } #else { - struct utsname u; - - /* Successful uname() returns zero on Linux and positive value - * on OpenSolaris. - */ - if (uname(&u) == -1) - goto get_sdk_info; - - ALLOC_CP_STR(u.machine, machine); - ALLOC_CP_STR(u.sysname, os_name); - - si.os_ver = parse_version(u.release); + struct utsname u; + + /* Successful uname() returns zero on Linux and positive value + * on OpenSolaris. + */ + if (uname(&u) == -1) + goto get_sdk_info; + + ALLOC_CP_STR(u.machine, machine); + ALLOC_CP_STR(u.sysname, os_name); + + si.os_ver = parse_version(u.release); } #endif #elif defined(_MSC_VER) { #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 - si.os_name = pj_str("winphone"); + si.os_name = pj_str("winphone"); #else - OSVERSIONINFO ovi; + OSVERSIONINFO ovi; - ovi.dwOSVersionInfoSize = sizeof(ovi); + ovi.dwOSVersionInfoSize = sizeof(ovi); - if (GetVersionEx(&ovi) == FALSE) - goto get_sdk_info; + if (GetVersionEx(&ovi) == FALSE) + goto get_sdk_info; - si.os_ver = (ovi.dwMajorVersion << 24) | - (ovi.dwMinorVersion << 16); - #if defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE - si.os_name = pj_str("wince"); - #else - si.os_name = pj_str("win32"); - #endif + si.os_ver = (ovi.dwMajorVersion << 24) | + (ovi.dwMinorVersion << 16); + #if defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE + si.os_name = pj_str("wince"); + #else + si.os_name = pj_str("win32"); + #endif #endif } { - SYSTEM_INFO wsi; + SYSTEM_INFO wsi; #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 - GetNativeSystemInfo(&wsi); + GetNativeSystemInfo(&wsi); #else - GetSystemInfo(&wsi); + GetSystemInfo(&wsi); #endif - - switch (wsi.wProcessorArchitecture) { - #if (defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE) || \ - (defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8) - case PROCESSOR_ARCHITECTURE_ARM: - si.machine = pj_str("arm"); - break; - case PROCESSOR_ARCHITECTURE_SHX: - si.machine = pj_str("shx"); - break; - #else - case PROCESSOR_ARCHITECTURE_AMD64: - si.machine = pj_str("x86_64"); - break; - case PROCESSOR_ARCHITECTURE_IA64: - si.machine = pj_str("ia64"); - break; - case PROCESSOR_ARCHITECTURE_INTEL: - si.machine = pj_str("i386"); - break; - #endif /* PJ_WIN32_WINCE */ - } + + switch (wsi.wProcessorArchitecture) { + #if (defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE) || \ + (defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8) + case PROCESSOR_ARCHITECTURE_ARM: + si.machine = pj_str("arm"); + break; + case PROCESSOR_ARCHITECTURE_SHX: + si.machine = pj_str("shx"); + break; + #else + case PROCESSOR_ARCHITECTURE_AMD64: + si.machine = pj_str("x86_64"); + break; + case PROCESSOR_ARCHITECTURE_IA64: + si.machine = pj_str("ia64"); + break; + case PROCESSOR_ARCHITECTURE_INTEL: + si.machine = pj_str("i386"); + break; + #endif /* PJ_WIN32_WINCE */ + } #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 - /* Avoid compile warning. */ - goto get_sdk_info; + /* Avoid compile warning. */ + goto get_sdk_info; #endif } #elif defined(PJ_SYMBIAN) && PJ_SYMBIAN != 0 { - pj_symbianos_get_model_info(si_buffer, sizeof(si_buffer)); - ALLOC_CP_STR(si_buffer, machine); - - char *p = si_buffer + sizeof(si_buffer) - left; - unsigned plen; - plen = pj_symbianos_get_platform_info(p, left); - if (plen) { - /* Output format will be "Series60vX.X" */ - si.os_name = pj_str("S60"); - si.os_ver = parse_version(p+9); - } else { - si.os_name = pj_str("Unknown"); - } - - /* Avoid compile warning on Symbian. */ - goto get_sdk_info; + pj_symbianos_get_model_info(si_buffer, sizeof(si_buffer)); + ALLOC_CP_STR(si_buffer, machine); + + char *p = si_buffer + sizeof(si_buffer) - left; + unsigned plen; + plen = pj_symbianos_get_platform_info(p, left); + if (plen) { + /* Output format will be "Series60vX.X" */ + si.os_name = pj_str("S60"); + si.os_ver = parse_version(p+9); + } else { + si.os_name = pj_str("Unknown"); + } + + /* Avoid compile warning on Symbian. */ + goto get_sdk_info; } #endif @@ -280,15 +279,15 @@ PJ_DEF(const pj_sys_info*) pj_get_sys_info(void) #if defined(__GLIBC__) si.sdk_ver = (__GLIBC__ << 24) | - (__GLIBC_MINOR__ << 16); + (__GLIBC_MINOR__ << 16); si.sdk_name = pj_str("glibc"); #elif defined(__GNU_LIBRARY__) si.sdk_ver = (__GNU_LIBRARY__ << 24) | - (__GNU_LIBRARY_MINOR__ << 16); + (__GNU_LIBRARY_MINOR__ << 16); si.sdk_name = pj_str("libc"); #elif defined(__UCLIBC__) si.sdk_ver = (__UCLIBC_MAJOR__ << 24) | - (__UCLIBC_MINOR__ << 16); + (__UCLIBC_MINOR__ << 16); si.sdk_name = pj_str("uclibc"); #elif defined(_WIN32_WCE) && _WIN32_WCE /* Old window mobile declares _WIN32_WCE as decimal (e.g. 300, 420, etc.), @@ -296,13 +295,13 @@ PJ_DEF(const pj_sys_info*) pj_get_sys_info(void) * http://social.msdn.microsoft.com/forums/en-US/vssmartdevicesnative/thread/8a97c59f-5a1c-4bc6-99e6-427f065ff439/ */ #if _WIN32_WCE <= 500 - si.sdk_ver = ( (_WIN32_WCE / 100) << 24) | - ( ((_WIN32_WCE % 100) / 10) << 16) | - ( (_WIN32_WCE % 10) << 8); + si.sdk_ver = ( (_WIN32_WCE / 100) << 24) | + ( ((_WIN32_WCE % 100) / 10) << 16) | + ( (_WIN32_WCE % 10) << 8); #else - si.sdk_ver = ( ((_WIN32_WCE & 0xFF00) >> 8) << 24) | - ( ((_WIN32_WCE & 0x00F0) >> 4) << 16) | - ( ((_WIN32_WCE & 0x000F) >> 0) << 8); + si.sdk_ver = ( ((_WIN32_WCE & 0xFF00) >> 8) << 24) | + ( ((_WIN32_WCE & 0x00F0) >> 4) << 16) | + ( ((_WIN32_WCE & 0x000F) >> 0) << 8); #endif si.sdk_name = pj_str("cesdk"); #elif defined(_MSC_VER) @@ -313,8 +312,8 @@ PJ_DEF(const pj_sys_info*) pj_get_sys_info(void) * The Visual C++ 2005 compiler version is 1400. */ si.sdk_ver = ((_MSC_VER / 100) << 24) | - (((_MSC_VER % 100) / 10) << 16) | - ((_MSC_VER % 10) << 8); + (((_MSC_VER % 100) / 10) << 16) | + ((_MSC_VER % 10) << 8); si.sdk_name = pj_str("msvc"); #elif defined(PJ_SYMBIAN) && PJ_SYMBIAN != 0 pj_symbianos_get_sdk_info(&si.sdk_name, &si.sdk_ver); @@ -324,22 +323,22 @@ PJ_DEF(const pj_sys_info*) pj_get_sys_info(void) * Build the info string. */ { - char tmp[PJ_SYS_INFO_BUFFER_SIZE]; - char os_ver[20], sdk_ver[20]; - int cnt; - - cnt = pj_ansi_snprintf(tmp, sizeof(tmp), - "%s%s%s%s%s%s%s", - si.os_name.ptr, - ver_info(si.os_ver, os_ver), - (si.machine.slen ? "/" : ""), - si.machine.ptr, - (si.sdk_name.slen ? "/" : ""), - si.sdk_name.ptr, - ver_info(si.sdk_ver, sdk_ver)); - if (cnt > 0 && cnt < (int)sizeof(tmp)) { - ALLOC_CP_STR(tmp, info); - } + char tmp[PJ_SYS_INFO_BUFFER_SIZE]; + char os_ver[20], sdk_ver[20]; + int cnt; + + cnt = pj_ansi_snprintf(tmp, sizeof(tmp), + "%s%s%s%s%s%s%s", + si.os_name.ptr, + ver_info(si.os_ver, os_ver), + (si.machine.slen ? "/" : ""), + si.machine.ptr, + (si.sdk_name.slen ? "/" : ""), + si.sdk_name.ptr, + ver_info(si.sdk_ver, sdk_ver)); + if (cnt > 0 && cnt < (int)sizeof(tmp)) { + ALLOC_CP_STR(tmp, info); + } } si_initialized = PJ_TRUE; diff --git a/pjlib/src/pj/os_info_iphone.m b/pjlib/src/pj/os_info_iphone.m index ef20f927fa..d273310240 100644 --- a/pjlib/src/pj/os_info_iphone.m +++ b/pjlib/src/pj/os_info_iphone.m @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,18 +31,18 @@ void pj_iphone_os_get_sys_info(pj_sys_info *si, pj_str_t *si_buffer) UIDevice *device = [UIDevice currentDevice]; if ([device respondsToSelector:@selector(isMultitaskingSupported)]) - si->flags |= PJ_SYS_HAS_IOS_BG; + si->flags |= PJ_SYS_HAS_IOS_BG; -#define ALLOC_CP_STR(str,field) \ +#define ALLOC_CP_STR(str,field) \ do { \ - len = [str length]; \ - if (len && left >= len+1) { \ - si->field.ptr = si_buffer->ptr + buf_len - left; \ - si->field.slen = len; \ - [str getCString:si->field.ptr maxLength:len+1 \ - encoding:NSASCIIStringEncoding]; \ - left -= (len+1); \ - } \ + len = [str length]; \ + if (len && left >= len+1) { \ + si->field.ptr = si_buffer->ptr + buf_len - left; \ + si->field.slen = len; \ + [str getCString:si->field.ptr maxLength:len+1 \ + encoding:NSASCIIStringEncoding]; \ + left -= (len+1); \ + } \ } while (0) ALLOC_CP_STR([device systemName], os_name); diff --git a/pjlib/src/pj/os_info_symbian.cpp b/pjlib/src/pj/os_info_symbian.cpp index 4c2e86b5e8..2138fa388f 100644 --- a/pjlib/src/pj/os_info_symbian.cpp +++ b/pjlib/src/pj/os_info_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011 Teluu Inc. (http://www.teluu.com) * @@ -23,9 +22,9 @@ #include #include -#include /* link against efsrv.lib */ -#include /* link against hal.lib */ -#include /* link against charconv.lib */ +#include /* link against efsrv.lib */ +#include /* link against hal.lib */ +#include /* link against charconv.lib */ PJ_BEGIN_DECL @@ -60,21 +59,21 @@ unsigned pj_symbianos_get_model_info(char *buf, unsigned buf_size) fs.Connect(1); err = file.Open(fs, KModelFilename, EFileRead); if (err == KErrNone) { - TFileText text; - text.Set(file); - TBuf16<64> ModelName16; - err = text.Read(ModelName16); - if (err == KErrNone) { - TPtr8 ptr8((TUint8*)tmp_buf, sizeof(tmp_buf)); - ptr8.Copy(ModelName16); - pj_strset(&tmp_str, tmp_buf, ptr8.Length()); - pj_strtrim(&tmp_str); - } - file.Close(); + TFileText text; + text.Set(file); + TBuf16<64> ModelName16; + err = text.Read(ModelName16); + if (err == KErrNone) { + TPtr8 ptr8((TUint8*)tmp_buf, sizeof(tmp_buf)); + ptr8.Copy(ModelName16); + pj_strset(&tmp_str, tmp_buf, ptr8.Length()); + pj_strtrim(&tmp_str); + } + file.Close(); } fs.Close(); if (err != KErrNone) - goto on_return; + goto on_return; /* The retrieved model name is usually in long format, e.g: * "� Nokia N95 (01.01)", "(C) Nokia E52". As we need only @@ -89,30 +88,30 @@ unsigned pj_symbianos_get_model_info(char *buf, unsigned buf_size) /* Remove "(C)" */ p = pj_stristr(&tmp_str, &st_copyright); if (p) { - p += st_copyright.slen; - pj_strset(&tmp_str, p, tmp_str.slen - (p - tmp_str.ptr)); + p += st_copyright.slen; + pj_strset(&tmp_str, p, tmp_str.slen - (p - tmp_str.ptr)); } /* Remove "Nokia" */ p = pj_stristr(&tmp_str, &st_nokia); if (p) { - p += st_nokia.slen; - pj_strset(&tmp_str, p, tmp_str.slen - (p - tmp_str.ptr)); + p += st_nokia.slen; + pj_strset(&tmp_str, p, tmp_str.slen - (p - tmp_str.ptr)); } /* Remove language version, e.g: "(01.01)" */ p = pj_strchr(&tmp_str, '('); if (p) { - tmp_str.slen = p - tmp_str.ptr; + tmp_str.slen = p - tmp_str.ptr; } pj_strtrim(&tmp_str); if (tmp_str.slen == 0) - goto on_return; + goto on_return; if ((unsigned)tmp_str.slen > buf_size - model_name.slen - 3) - tmp_str.slen = buf_size - model_name.slen - 3; + tmp_str.slen = buf_size - model_name.slen - 3; pj_strcat2(&model_name, "("); pj_strcat(&model_name, &tmp_str); @@ -142,19 +141,19 @@ unsigned pj_symbianos_get_platform_info(char *buf, unsigned buf_size) fs.Connect(1); err = ff.FindWildByDir(KS60ProductIDFile, KROMInstallDir, result); if (err == KErrNone) { - err = result->Sort(ESortByName|EDescending); - if (err == KErrNone) { - TPtr8 tmp_ptr8((TUint8*)buf, buf_size); - const pj_str_t tmp_ext = {".sis", 4}; - char *p; - - tmp_ptr8.Copy((*result)[0].iName); - pj_strset(&plat_info, buf, (pj_size_t)tmp_ptr8.Length()); - p = pj_stristr(&plat_info, &tmp_ext); - if (p) - plat_info.slen -= (p - plat_info.ptr); - } - delete result; + err = result->Sort(ESortByName|EDescending); + if (err == KErrNone) { + TPtr8 tmp_ptr8((TUint8*)buf, buf_size); + const pj_str_t tmp_ext = {".sis", 4}; + char *p; + + tmp_ptr8.Copy((*result)[0].iName); + pj_strset(&plat_info, buf, (pj_size_t)tmp_ptr8.Length()); + p = pj_stristr(&plat_info, &tmp_ext); + if (p) + plat_info.slen -= (p - plat_info.ptr); + } + delete result; } fs.Close(); buf[plat_info.slen] = '\0'; @@ -168,23 +167,23 @@ void pj_symbianos_get_sdk_info(pj_str_t *name, pj_uint32_t *ver) { const pj_str_t S60 = {"S60", 3}; #if defined(__SERIES60_30__) - *name = S60; - *ver = (3 << 24); + *name = S60; + *ver = (3 << 24); #elif defined(__SERIES60_31__) - *name = S60; - *ver = (3 << 24) | (1 << 16); + *name = S60; + *ver = (3 << 24) | (1 << 16); #elif defined(__S60_32__) - *name = S60; - *ver = (3 << 24) | (2 << 16); + *name = S60; + *ver = (3 << 24) | (2 << 16); #elif defined(__S60_50__) - *name = S60; - *ver = (5 << 24); + *name = S60; + *ver = (5 << 24); #elif defined(__NOKIA_N97__) - *name = pj_str("N97"); - *ver = (1 << 24); + *name = pj_str("N97"); + *ver = (1 << 24); #else - *name = pj_str("Unknown"); - *ver = 0; + *name = pj_str("Unknown"); + *ver = 0; #endif } diff --git a/pjlib/src/pj/os_rwmutex.c b/pjlib/src/pj/os_rwmutex.c index 4a87afe297..b529321815 100644 --- a/pjlib/src/pj/os_rwmutex.c +++ b/pjlib/src/pj/os_rwmutex.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -49,7 +48,7 @@ struct pj_rwmutex_t * */ PJ_DEF(pj_status_t) pj_rwmutex_create(pj_pool_t *pool, const char *name, - pj_rwmutex_t **p_mutex) + pj_rwmutex_t **p_mutex) { pj_status_t status; pj_rwmutex_t *rwmutex; @@ -61,12 +60,12 @@ PJ_DEF(pj_status_t) pj_rwmutex_create(pj_pool_t *pool, const char *name, status = pj_mutex_create_simple(pool, name, &rwmutex ->read_lock); if (status != PJ_SUCCESS) - return status; + return status; status = pj_sem_create(pool, name, 1, 1, &rwmutex->write_lock); if (status != PJ_SUCCESS) { - pj_mutex_destroy(rwmutex->read_lock); - return status; + pj_mutex_destroy(rwmutex->read_lock); + return status; } rwmutex->reader_count = 0; @@ -86,8 +85,8 @@ PJ_DEF(pj_status_t) pj_rwmutex_lock_read(pj_rwmutex_t *mutex) status = pj_mutex_lock(mutex->read_lock); if (status != PJ_SUCCESS) { - pj_assert(!"This pretty much is unexpected"); - return status; + pj_assert(!"This pretty much is unexpected"); + return status; } mutex->reader_count++; @@ -95,7 +94,7 @@ PJ_DEF(pj_status_t) pj_rwmutex_lock_read(pj_rwmutex_t *mutex) pj_assert(mutex->reader_count < 0x7FFFFFF0L); if (mutex->reader_count == 1) - pj_sem_wait(mutex->write_lock); + pj_sem_wait(mutex->write_lock); status = pj_mutex_unlock(mutex->read_lock); return status; @@ -123,15 +122,15 @@ PJ_DEF(pj_status_t) pj_rwmutex_unlock_read(pj_rwmutex_t *mutex) status = pj_mutex_lock(mutex->read_lock); if (status != PJ_SUCCESS) { - pj_assert(!"This pretty much is unexpected"); - return status; + pj_assert(!"This pretty much is unexpected"); + return status; } pj_assert(mutex->reader_count >= 1); --mutex->reader_count; if (mutex->reader_count == 0) - pj_sem_post(mutex->write_lock); + pj_sem_post(mutex->write_lock); status = pj_mutex_unlock(mutex->read_lock); return status; diff --git a/pjlib/src/pj/os_symbian.h b/pjlib/src/pj/os_symbian.h index c40c2236fa..fc5af96ba1 100644 --- a/pjlib/src/pj/os_symbian.h +++ b/pjlib/src/pj/os_symbian.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,7 +38,7 @@ class CPjSocketReader; #ifndef PJ_SYMBIAN_TIMER_PRIORITY -# define PJ_SYMBIAN_TIMER_PRIORITY EPriorityNormal +# define PJ_SYMBIAN_TIMER_PRIORITY EPriorityNormal #endif // @@ -50,13 +49,13 @@ class CPjSocket public: enum { - MAX_LEN = 1500, + MAX_LEN = 1500, }; // Construct CPjSocket CPjSocket(int af, int sock_type, RSocket &sock) - : af_(af), sock_(sock), sock_type_(sock_type), connected_(false), - sockReader_(NULL) + : af_(af), sock_(sock), sock_type_(sock_type), connected_(false), + sockReader_(NULL) { } @@ -66,44 +65,44 @@ class CPjSocket // Get address family int GetAf() const { - return af_; + return af_; } // Get the internal RSocket RSocket& Socket() { - return sock_; + return sock_; } // Get socket connected flag. bool IsConnected() const { - return connected_; + return connected_; } // Set socket connected flag. void SetConnected(bool connected) { - connected_ = connected; + connected_ = connected; } // Get socket type int GetSockType() const { - return sock_type_; + return sock_type_; } // Returns true if socket is a datagram bool IsDatagram() const { - return sock_type_ == KSockDatagram; + return sock_type_ == KSockDatagram; } // Get socket reader, if any. // May return NULL. CPjSocketReader *Reader() { - return sockReader_; + return sockReader_; } // Create socket reader. @@ -113,12 +112,12 @@ class CPjSocket void DestroyReader(); private: - int af_; - RSocket sock_; // Must not be reference, or otherwise - // it may point to local variable! - unsigned sock_type_; + int af_; + RSocket sock_; // Must not be reference, or otherwise + // it may point to local variable! + unsigned sock_type_; - bool connected_; + bool connected_; CPjSocketReader *sockReader_; }; @@ -137,16 +136,16 @@ class CPjSocketReader : public CActive // Start asynchronous read from the socket. void StartRecv(void (*cb)(void *key)=NULL, - void *key=NULL, - TDes8 *aDesc = NULL, - TUint flags = 0); + void *key=NULL, + TDes8 *aDesc = NULL, + TUint flags = 0); // Start asynchronous read from the socket. void StartRecvFrom(void (*cb)(void *key)=NULL, - void *key=NULL, - TDes8 *aDesc = NULL, - TUint flags = 0, - TSockAddr *fromAddr = NULL); + void *key=NULL, + TDes8 *aDesc = NULL, + TUint flags = 0, + TSockAddr *fromAddr = NULL); // Cancel asynchronous read. void DoCancel(); @@ -157,7 +156,7 @@ class CPjSocketReader : public CActive // Check if there's pending data. bool HasData() const { - return buffer_.Length() != 0; + return buffer_.Length() != 0; } // Append data to aDesc, up to aDesc's maximum size. @@ -165,13 +164,13 @@ class CPjSocketReader : public CActive void ReadData(TDes8 &aDesc, TInetAddr *addr=NULL); private: - CPjSocket &sock_; - bool isDatagram_; - TPtr8 buffer_; - TInetAddr recvAddr_; + CPjSocket &sock_; + bool isDatagram_; + TPtr8 buffer_; + TInetAddr recvAddr_; - void (*readCb_)(void *key); - void *key_; + void (*readCb_)(void *key); + void *key_; // // Constructor @@ -200,8 +199,8 @@ class CPjTimeoutTimer : public CActive virtual TInt RunError(TInt aError); private: - RTimer timer_; - pj_bool_t hasTimedOut_; + RTimer timer_; + pj_bool_t hasTimedOut_; CPjTimeoutTimer(); void ConstructL(); @@ -243,74 +242,74 @@ class PjSymbianOS // Get RSocketServ instance to be used by all sockets. RSocketServ &SocketServ() { - return appSocketServ_ ? *appSocketServ_ : socketServ_; + return appSocketServ_ ? *appSocketServ_ : socketServ_; } // Get RConnection instance, if any. RConnection *Connection() { - return appConnection_; + return appConnection_; } // Convert TInetAddr to pj_sockaddr_in static inline pj_status_t Addr2pj(const TInetAddr & sym_addr, - pj_sockaddr &pj_addr, - int *addr_len, - pj_bool_t convert_ipv4_mapped_addr = PJ_FALSE) + pj_sockaddr &pj_addr, + int *addr_len, + pj_bool_t convert_ipv4_mapped_addr = PJ_FALSE) { TUint fam = sym_addr.Family(); - pj_bzero(&pj_addr, *addr_len); - if (fam == PJ_AF_INET || - (convert_ipv4_mapped_addr && - fam == PJ_AF_INET6 && - sym_addr.IsV4Mapped())) - { - pj_addr.addr.sa_family = PJ_AF_INET; - PJ_ASSERT_RETURN(*addr_len>=(int)sizeof(pj_sockaddr_in), PJ_ETOOSMALL); - pj_addr.ipv4.sin_addr.s_addr = pj_htonl(sym_addr.Address()); - pj_addr.ipv4.sin_port = pj_htons((pj_uint16_t) sym_addr.Port()); - *addr_len = sizeof(pj_sockaddr_in); - } else if (fam == PJ_AF_INET6) { - PJ_ASSERT_RETURN(*addr_len>=(int)sizeof(pj_sockaddr_in6), PJ_ETOOSMALL); - const TIp6Addr & ip6 = sym_addr.Ip6Address(); - pj_addr.addr.sa_family = PJ_AF_INET6; - pj_memcpy(&pj_addr.ipv6.sin6_addr, ip6.u.iAddr8, 16); - pj_addr.ipv6.sin6_port = pj_htons((pj_uint16_t) sym_addr.Port()); - pj_addr.ipv6.sin6_scope_id = pj_htonl(sym_addr.Scope()); - pj_addr.ipv6.sin6_flowinfo = pj_htonl(sym_addr.FlowLabel()); - *addr_len = sizeof(pj_sockaddr_in6); - } else { - pj_assert(!"Unsupported address family"); - return PJ_EAFNOTSUP; - } - - return PJ_SUCCESS; + pj_bzero(&pj_addr, *addr_len); + if (fam == PJ_AF_INET || + (convert_ipv4_mapped_addr && + fam == PJ_AF_INET6 && + sym_addr.IsV4Mapped())) + { + pj_addr.addr.sa_family = PJ_AF_INET; + PJ_ASSERT_RETURN(*addr_len>=(int)sizeof(pj_sockaddr_in), PJ_ETOOSMALL); + pj_addr.ipv4.sin_addr.s_addr = pj_htonl(sym_addr.Address()); + pj_addr.ipv4.sin_port = pj_htons((pj_uint16_t) sym_addr.Port()); + *addr_len = sizeof(pj_sockaddr_in); + } else if (fam == PJ_AF_INET6) { + PJ_ASSERT_RETURN(*addr_len>=(int)sizeof(pj_sockaddr_in6), PJ_ETOOSMALL); + const TIp6Addr & ip6 = sym_addr.Ip6Address(); + pj_addr.addr.sa_family = PJ_AF_INET6; + pj_memcpy(&pj_addr.ipv6.sin6_addr, ip6.u.iAddr8, 16); + pj_addr.ipv6.sin6_port = pj_htons((pj_uint16_t) sym_addr.Port()); + pj_addr.ipv6.sin6_scope_id = pj_htonl(sym_addr.Scope()); + pj_addr.ipv6.sin6_flowinfo = pj_htonl(sym_addr.FlowLabel()); + *addr_len = sizeof(pj_sockaddr_in6); + } else { + pj_assert(!"Unsupported address family"); + return PJ_EAFNOTSUP; + } + + return PJ_SUCCESS; } // Convert pj_sockaddr_in to TInetAddr static inline pj_status_t pj2Addr(const pj_sockaddr &pj_addr, - int addrlen, - TInetAddr & sym_addr) + int addrlen, + TInetAddr & sym_addr) { - if (pj_addr.addr.sa_family == PJ_AF_INET) { - PJ_ASSERT_RETURN(addrlen >= (int)sizeof(pj_sockaddr_in), PJ_EINVAL); - sym_addr.Init(KAfInet); - sym_addr.SetAddress((TUint32)pj_ntohl(pj_addr.ipv4.sin_addr.s_addr)); - sym_addr.SetPort(pj_ntohs(pj_addr.ipv4.sin_port)); - } else if (pj_addr.addr.sa_family == PJ_AF_INET6) { - TIp6Addr ip6; - - PJ_ASSERT_RETURN(addrlen>=(int)sizeof(pj_sockaddr_in6), PJ_EINVAL); - pj_memcpy(ip6.u.iAddr8, &pj_addr.ipv6.sin6_addr, 16); - sym_addr.Init(KAfInet6); - sym_addr.SetAddress(ip6); - sym_addr.SetScope(pj_ntohl(pj_addr.ipv6.sin6_scope_id)); - sym_addr.SetFlowLabel(pj_ntohl(pj_addr.ipv6.sin6_flowinfo)); - } else { - pj_assert(!"Unsupported address family"); - } - return PJ_SUCCESS; + if (pj_addr.addr.sa_family == PJ_AF_INET) { + PJ_ASSERT_RETURN(addrlen >= (int)sizeof(pj_sockaddr_in), PJ_EINVAL); + sym_addr.Init(KAfInet); + sym_addr.SetAddress((TUint32)pj_ntohl(pj_addr.ipv4.sin_addr.s_addr)); + sym_addr.SetPort(pj_ntohs(pj_addr.ipv4.sin_port)); + } else if (pj_addr.addr.sa_family == PJ_AF_INET6) { + TIp6Addr ip6; + + PJ_ASSERT_RETURN(addrlen>=(int)sizeof(pj_sockaddr_in6), PJ_EINVAL); + pj_memcpy(ip6.u.iAddr8, &pj_addr.ipv6.sin6_addr, 16); + sym_addr.Init(KAfInet6); + sym_addr.SetAddress(ip6); + sym_addr.SetScope(pj_ntohl(pj_addr.ipv6.sin6_scope_id)); + sym_addr.SetFlowLabel(pj_ntohl(pj_addr.ipv6.sin6_flowinfo)); + } else { + pj_assert(!"Unsupported address family"); + } + return PJ_SUCCESS; } @@ -321,11 +320,11 @@ class PjSymbianOS // Get RHostResolver instance RHostResolver & GetResolver(int af) { - if (af==PJ_AF_INET6) { - return appHostResolver6_ ? *appHostResolver6_ : hostResolver6_; - } else { - return appHostResolver_ ? *appHostResolver_ : hostResolver_; - } + if (af==PJ_AF_INET6) { + return appHostResolver6_ ? *appHostResolver6_ : hostResolver6_; + } else { + return appHostResolver_ ? *appHostResolver_ : hostResolver_; + } } // @@ -333,7 +332,7 @@ class PjSymbianOS // bool IsConnectionUp() const { - return isConnectionUp_; + return isConnectionUp_; } // @@ -341,7 +340,7 @@ class PjSymbianOS // void SetConnectionStatus(bool up) { - isConnectionUp_ = up; + isConnectionUp_ = up; } // @@ -361,7 +360,7 @@ class PjSymbianOS // Get console CConsoleBase *Console() { - return console_; + return console_; } // @@ -369,7 +368,7 @@ class PjSymbianOS // CPjTimeoutTimer *SelectTimeoutTimer() { - return selectTimeoutTimer_; + return selectTimeoutTimer_; } // @@ -377,9 +376,9 @@ class PjSymbianOS // void WaitForActiveObjects(TInt aPriority = CActive::EPriorityStandard) { - TInt aError; - CActiveScheduler::Current()->WaitForAnyRequest(); - CActiveScheduler::RunIfReady(aError, aPriority); + TInt aError; + CActiveScheduler::Current()->WaitForAnyRequest(); + CActiveScheduler::RunIfReady(aError, aPriority); } private: @@ -414,9 +413,9 @@ class PjSymbianOS #define PJ_SYMBIAN_CHECK_CONNECTION2(retval) \ do { \ - if (!PjSymbianOS::Instance()->IsConnectionUp()) \ - return retval; \ + if (!PjSymbianOS::Instance()->IsConnectionUp()) \ + return retval; \ } while (0); -#endif /* __OS_SYMBIAN_H__ */ +#endif /* __OS_SYMBIAN_H__ */ diff --git a/pjlib/src/pj/os_time_bsd.c b/pjlib/src/pj/os_time_bsd.c index 3adba23ff3..49d957a276 100644 --- a/pjlib/src/pj/os_time_bsd.c +++ b/pjlib/src/pj/os_time_bsd.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pj/os_time_common.c b/pjlib/src/pj/os_time_common.c index b828cfbe98..3c833079ef 100644 --- a/pjlib/src/pj/os_time_common.c +++ b/pjlib/src/pj/os_time_common.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pj/os_time_unix.c b/pjlib/src/pj/os_time_unix.c index 70c8c1fe62..fedcd48425 100644 --- a/pjlib/src/pj/os_time_unix.c +++ b/pjlib/src/pj/os_time_unix.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,7 +37,7 @@ PJ_DEF(pj_status_t) pj_gettimeofday(pj_time_val *p_tv) rc = gettimeofday(&the_time, NULL); if (rc != 0) - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); p_tv->sec = the_time.tv_sec; p_tv->msec = the_time.tv_usec / 1000; diff --git a/pjlib/src/pj/os_time_win32.c b/pjlib/src/pj/os_time_win32.c index eb359c7d7f..4e224a1020 100644 --- a/pjlib/src/pj/os_time_win32.c +++ b/pjlib/src/pj/os_time_win32.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -57,13 +56,13 @@ static LARGE_INTEGER base_time; static LARGE_INTEGER g_start_time; /* Time gettimeofday() is first called */ static pj_timestamp g_start_tick; /* TS gettimeofday() is first called */ static pj_timestamp g_last_update; /* Last time check_system_time() is - called, to periodically synchronize - with up-to-date system time (in case - user changes system time). */ + called, to periodically synchronize + with up-to-date system time (in case + user changes system time). */ static pj_uint64_t g_update_period; /* Period (in TS) check_system_time() - should be called. */ + should be called. */ -/* Period on which check_system_time() is called, in seconds */ +/* Period on which check_system_time() is called, in seconds */ #ifndef PJ_WINCE_TIME_CHECK_INTERVAL # define PJ_WINCE_TIME_CHECK_INTERVAL (10) #endif @@ -88,13 +87,13 @@ static pj_status_t init_start_time(void) status = pj_get_timestamp(&g_start_tick); if (status != PJ_SUCCESS) - return status; + return status; g_last_update.u64 = g_start_tick.u64; status = pj_get_timestamp_freq(&freq); if (status != PJ_SUCCESS) - return status; + return status; g_update_period = PJ_WINCE_TIME_CHECK_INTERVAL * freq.u64; @@ -125,24 +124,24 @@ static pj_status_t check_system_time(pj_uint64_t ts_elapsed) /* Get our calculated system time */ status = pj_get_timestamp_freq(&freq); if (status != PJ_SUCCESS) - return status; + return status; calc.QuadPart = g_start_time.QuadPart + ts_elapsed / freq.u64; /* See the difference between calculated and actual system time */ if (calc.QuadPart >= cur.QuadPart) { - diff = (DWORD)(calc.QuadPart - cur.QuadPart); + diff = (DWORD)(calc.QuadPart - cur.QuadPart); } else { - diff = (DWORD)(cur.QuadPart - calc.QuadPart); + diff = (DWORD)(cur.QuadPart - calc.QuadPart); } if (diff > MIS) { - /* System time has changed */ - PJ_LOG(3,("os_time_win32.c", "WinCE system time changed detected " - "(diff=%u)", diff)); - status = init_start_time(); + /* System time has changed */ + PJ_LOG(3,("os_time_win32.c", "WinCE system time changed detected " + "(diff=%u)", diff)); + status = init_start_time(); } else { - status = PJ_SUCCESS; + status = PJ_SUCCESS; } return status; @@ -189,27 +188,27 @@ PJ_DEF(pj_status_t) pj_gettimeofday(pj_time_val *tv) pj_status_t status; if (base_time.QuadPart == 0) { - status = get_base_time(); - if (status != PJ_SUCCESS) - return status; + status = get_base_time(); + if (status != PJ_SUCCESS) + return status; } #ifdef WINCE_TIME do { - status = pj_get_timestamp(&tick); - if (status != PJ_SUCCESS) - return status; - - if (tick.u64 - g_last_update.u64 >= g_update_period) { - pj_enter_critical_section(); - if (tick.u64 - g_last_update.u64 >= g_update_period) { - g_last_update.u64 = tick.u64; - check_system_time(tick.u64 - g_start_tick.u64); - } - pj_leave_critical_section(); - } else { - break; - } + status = pj_get_timestamp(&tick); + if (status != PJ_SUCCESS) + return status; + + if (tick.u64 - g_last_update.u64 >= g_update_period) { + pj_enter_critical_section(); + if (tick.u64 - g_last_update.u64 >= g_update_period) { + g_last_update.u64 = tick.u64; + check_system_time(tick.u64 - g_start_tick.u64); + } + pj_leave_critical_section(); + } else { + break; + } } while (1); msec_elapsed = pj_elapsed_msec64(&g_start_tick, &tick); @@ -228,7 +227,7 @@ PJ_DEF(pj_status_t) pj_gettimeofday(pj_time_val *tv) tv->sec = li.LowPart; tv->msec = st.wMilliseconds; -#endif /* WINCE_TIME */ +#endif /* WINCE_TIME */ return PJ_SUCCESS; } @@ -311,7 +310,7 @@ PJ_DEF(pj_status_t) pj_time_local_to_gmt(pj_time_val *tv) ft_local.dwHighDateTime = li.HighPart; if (LocalFileTimeToFileTime(&ft_local, &ft_gmt) == 0) - return PJ_EINVAL; + return PJ_EINVAL; li.LowPart = ft_gmt.dwLowDateTime; li.HighPart = ft_gmt.dwHighDateTime; @@ -344,7 +343,7 @@ PJ_DEF(pj_status_t) pj_time_gmt_to_local(pj_time_val *tv) ft_gmt.dwHighDateTime = li.HighPart; if (FileTimeToLocalFileTime(&ft_gmt, &ft_local) == 0) - return PJ_EINVAL; + return PJ_EINVAL; li.LowPart = ft_local.dwLowDateTime; li.HighPart = ft_local.dwHighDateTime; diff --git a/pjlib/src/pj/os_timestamp_common.c b/pjlib/src/pj/os_timestamp_common.c index f4f7b33104..be733da6ab 100644 --- a/pjlib/src/pj/os_timestamp_common.c +++ b/pjlib/src/pj/os_timestamp_common.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,7 +26,7 @@ #define USEC (1000000UL) #define MSEC (1000) -#define u64tohighprec(u64) ((pj_highprec_t)((pj_int64_t)(u64))) +#define u64tohighprec(u64) ((pj_highprec_t)((pj_int64_t)(u64))) static pj_highprec_t get_elapsed( const pj_timestamp *start, const pj_timestamp *stop ) diff --git a/pjlib/src/pj/os_timestamp_posix.c b/pjlib/src/pj/os_timestamp_posix.c index 0aed8c4704..07ef682a94 100644 --- a/pjlib/src/pj/os_timestamp_posix.c +++ b/pjlib/src/pj/os_timestamp_posix.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -56,9 +55,9 @@ static int get_machine_speed_mhz() char buf[512]; int len; char *pos, *end; - + PJ_CHECK_STACK(); - + /* Open /proc/cpuinfo and read the file */ strm = fopen("/proc/cpuinfo", "r"); if (!strm) @@ -88,15 +87,15 @@ static int get_machine_speed_mhz() PJ_DEF(pj_status_t) pj_get_timestamp(pj_timestamp *ts) { if (machine_speed_mhz == 0) { - machine_speed_mhz = get_machine_speed_mhz(); - if (machine_speed_mhz > 0) { - machine_speed.u64 = machine_speed_mhz * 1000000.0; - } + machine_speed_mhz = get_machine_speed_mhz(); + if (machine_speed_mhz > 0) { + machine_speed.u64 = machine_speed_mhz * 1000000.0; + } } if (machine_speed_mhz == -1) { - ts->u64 = 0; - return -1; + ts->u64 = 0; + return -1; } ts->u64 = rdtsc(); return 0; @@ -105,15 +104,15 @@ PJ_DEF(pj_status_t) pj_get_timestamp(pj_timestamp *ts) PJ_DEF(pj_status_t) pj_get_timestamp_freq(pj_timestamp *freq) { if (machine_speed_mhz == 0) { - machine_speed_mhz = get_machine_speed_mhz(); - if (machine_speed_mhz > 0) { - machine_speed.u64 = machine_speed_mhz * 1000000.0; - } + machine_speed_mhz = get_machine_speed_mhz(); + if (machine_speed_mhz > 0) { + machine_speed.u64 = machine_speed_mhz * 1000000.0; + } } if (machine_speed_mhz == -1) { - freq->u64 = 1; /* return 1 to prevent division by zero in apps. */ - return -1; + freq->u64 = 1; /* return 1 to prevent division by zero in apps. */ + return -1; } freq->u64 = machine_speed.u64; @@ -137,7 +136,7 @@ PJ_DEF(pj_status_t) pj_get_timestamp_freq(pj_timestamp *freq) #endif #ifndef NSEC_PER_SEC -# define NSEC_PER_SEC 1000000000 +# define NSEC_PER_SEC 1000000000 #endif #if USE_KERN_BOOTTIME @@ -179,12 +178,12 @@ PJ_DEF(pj_status_t) pj_get_timestamp(pj_timestamp *ts) ret = host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &serv); if (ret != KERN_SUCCESS) { - return PJ_RETURN_OS_ERROR(EINVAL); + return PJ_RETURN_OS_ERROR(EINVAL); } ret = clock_get_time(serv, &tp); if (ret != KERN_SUCCESS) { - return PJ_RETURN_OS_ERROR(EINVAL); + return PJ_RETURN_OS_ERROR(EINVAL); } ts->u64 = tp.tv_sec; @@ -213,7 +212,7 @@ PJ_DEF(pj_status_t) pj_get_timestamp_freq(pj_timestamp *freq) # include #endif -#define NSEC_PER_SEC 1000000000 +#define NSEC_PER_SEC 1000000000 #if defined(ANDROID_ALARM_GET_TIME) static int s_alarm_fd = -1; @@ -221,7 +220,7 @@ static int s_alarm_fd = -1; void close_alarm_fd() { if (s_alarm_fd != -1) - close(s_alarm_fd); + close(s_alarm_fd); s_alarm_fd = -1; } #endif @@ -235,8 +234,8 @@ PJ_DEF(pj_status_t) pj_get_timestamp(pj_timestamp *ts) if (s_alarm_fd == -1) { int fd = open("/dev/alarm", O_RDONLY); if (fd >= 0) { - s_alarm_fd = fd; - pj_atexit(&close_alarm_fd); + s_alarm_fd = fd; + pj_atexit(&close_alarm_fd); } } @@ -249,15 +248,15 @@ PJ_DEF(pj_status_t) pj_get_timestamp(pj_timestamp *ts) #endif if (err != 0) { - /* Fallback to CLOCK_MONOTONIC if /dev/alarm is not found, or - * getting ANDROID_ALARM_ELAPSED_REALTIME fails, or + /* Fallback to CLOCK_MONOTONIC if /dev/alarm is not found, or + * getting ANDROID_ALARM_ELAPSED_REALTIME fails, or * CLOCK_BOOTTIME fails. - */ + */ err = clock_gettime(CLOCK_MONOTONIC, &tp); } if (err != 0) { - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); } ts->u64 = tp.tv_sec; @@ -280,14 +279,14 @@ PJ_DEF(pj_status_t) pj_get_timestamp_freq(pj_timestamp *freq) #include #include -#define NSEC_PER_SEC 1000000000 +#define NSEC_PER_SEC 1000000000 PJ_DEF(pj_status_t) pj_get_timestamp(pj_timestamp *ts) { struct timespec tp; if (clock_gettime(CLOCK_MONOTONIC, &tp) != 0) { - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); } ts->u64 = tp.tv_sec; @@ -309,14 +308,14 @@ PJ_DEF(pj_status_t) pj_get_timestamp_freq(pj_timestamp *freq) #include #include -#define USEC_PER_SEC 1000000 +#define USEC_PER_SEC 1000000 PJ_DEF(pj_status_t) pj_get_timestamp(pj_timestamp *ts) { struct timeval tv; if (gettimeofday(&tv, NULL) != 0) { - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); } ts->u64 = tv.tv_sec; diff --git a/pjlib/src/pj/os_timestamp_win32.c b/pjlib/src/pj/os_timestamp_win32.c index e77b14a330..1803d91d80 100644 --- a/pjlib/src/pj/os_timestamp_win32.c +++ b/pjlib/src/pj/os_timestamp_win32.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,9 +26,9 @@ #if 1 -# define TRACE_(x) PJ_LOG(3,x) +# define TRACE_(x) PJ_LOG(3,x) #else -# define TRACE_(x) ; +# define TRACE_(x) ; #endif @@ -54,23 +53,23 @@ static pj_status_t GetCpuHz(void) #if defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE!=0 rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, - L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", - 0, 0, &key); + L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", + 0, 0, &key); #else rc = RegOpenKey( HKEY_LOCAL_MACHINE, - "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", - &key); + "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", + &key); #endif if (rc != ERROR_SUCCESS) - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR(rc); size = sizeof(CpuMhz); rc = RegQueryValueEx(key, "~MHz", NULL, NULL, (BYTE*)&CpuMhz, &size); RegCloseKey(key); if (rc != ERROR_SUCCESS) { - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR(rc); } CpuHz = CpuMhz; @@ -84,8 +83,8 @@ __declspec(naked) __int64 rdtsc() { __asm { - RDTSC - RET + RDTSC + RET } } @@ -100,9 +99,9 @@ PJ_DEF(pj_status_t) pj_get_timestamp_freq(pj_timestamp *freq) pj_status_t status; if (CpuHz == 0) { - status = GetCpuHz(); - if (status != PJ_SUCCESS) - return status; + status = GetCpuHz(); + if (status != PJ_SUCCESS) + return status; } freq->u64 = CpuHz; @@ -143,47 +142,47 @@ PJ_DEF(pj_status_t) pj_get_timestamp(pj_timestamp *ts) */ i = 0; do { - LARGE_INTEGER val; - pj_int64_t counter64, time64, diff; - pj_time_val time_now; - - /* Retrieve the counter */ - if (!QueryPerformanceCounter(&val)) - return PJ_RETURN_OS_ERROR(GetLastError()); - - /* Regardless of the goodness of the value, we should put - * the counter here, because normally application wouldn't - * check the error result of this function. - */ - ts->u64 = val.QuadPart; - - /* Retrieve time */ - pj_gettimeofday(&time_now); - - /* Get the counter elapsed time in miliseconds */ - counter64 = (val.QuadPart - g_ts_base.u64) * 1000 / g_ts_freq.u64; - - /* Get the time elapsed in miliseconds. - * We don't want to use PJ_TIME_VAL_MSEC() since it's using - * 32bit calculation, which limits the maximum elapsed time - * to around 49 days only. - */ - time64 = time_now.sec; - time64 = time64 * 1000 + time_now.msec; - //time64 = GetTickCount(); - - /* It's good if the difference between two clocks are within - * some compile time constant (default: 20ms, which to allow - * context switch happen between QueryPerformanceCounter and - * pj_gettimeofday()). - */ - diff = (time64 - g_time_base) - counter64; - if (diff >= -20 && diff <= 20) { - /* It's good */ - return PJ_SUCCESS; - } - - ++i; + LARGE_INTEGER val; + pj_int64_t counter64, time64, diff; + pj_time_val time_now; + + /* Retrieve the counter */ + if (!QueryPerformanceCounter(&val)) + return PJ_RETURN_OS_ERROR(GetLastError()); + + /* Regardless of the goodness of the value, we should put + * the counter here, because normally application wouldn't + * check the error result of this function. + */ + ts->u64 = val.QuadPart; + + /* Retrieve time */ + pj_gettimeofday(&time_now); + + /* Get the counter elapsed time in miliseconds */ + counter64 = (val.QuadPart - g_ts_base.u64) * 1000 / g_ts_freq.u64; + + /* Get the time elapsed in miliseconds. + * We don't want to use PJ_TIME_VAL_MSEC() since it's using + * 32bit calculation, which limits the maximum elapsed time + * to around 49 days only. + */ + time64 = time_now.sec; + time64 = time64 * 1000 + time_now.msec; + //time64 = GetTickCount(); + + /* It's good if the difference between two clocks are within + * some compile time constant (default: 20ms, which to allow + * context switch happen between QueryPerformanceCounter and + * pj_gettimeofday()). + */ + diff = (time64 - g_time_base) - counter64; + if (diff >= -20 && diff <= 20) { + /* It's good */ + return PJ_SUCCESS; + } + + ++i; } while (i < MAX_RETRY); @@ -199,13 +198,13 @@ static pj_status_t init_performance_counter(void) /* Get the frequency */ if (!QueryPerformanceFrequency(&val)) - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); g_ts_freq.u64 = val.QuadPart; /* Get the base timestamp */ if (!QueryPerformanceCounter(&val)) - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); g_ts_base.u64 = val.QuadPart; @@ -213,7 +212,7 @@ static pj_status_t init_performance_counter(void) /* Get the base time */ status = pj_gettimeofday(&time_base); if (status != PJ_SUCCESS) - return status; + return status; /* Convert time base to 64bit value in msec */ g_time_base = time_base.sec; @@ -226,34 +225,34 @@ static pj_status_t init_performance_counter(void) PJ_DEF(pj_status_t) pj_get_timestamp_freq(pj_timestamp *freq) { if (g_ts_freq.u64 == 0) { - enum { MAX_REPEAT = 10 }; - unsigned i; - pj_status_t status; - - /* Make unellegant compiler happy */ - status = 0; - - /* Repeat initializing performance counter until we're sure - * the base timing is correct. It is possible that the system - * returns bad counter during this initialization! - */ - for (i=0; iu64 = g_ts_freq.u64; @@ -273,7 +272,7 @@ PJ_DEF(pj_status_t) pj_get_timestamp(pj_timestamp *ts) LARGE_INTEGER val; if (!QueryPerformanceCounter(&val)) - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); ts->u64 = val.QuadPart; return PJ_SUCCESS; @@ -284,12 +283,12 @@ PJ_DEF(pj_status_t) pj_get_timestamp_freq(pj_timestamp *freq) LARGE_INTEGER val; if (!QueryPerformanceFrequency(&val)) - return PJ_RETURN_OS_ERROR(GetLastError()); + return PJ_RETURN_OS_ERROR(GetLastError()); freq->u64 = val.QuadPart; return PJ_SUCCESS; } -#endif /* PJ_TIMESTAMP_USE_RDTSC */ +#endif /* PJ_TIMESTAMP_USE_RDTSC */ diff --git a/pjlib/src/pj/pool.c b/pjlib/src/pj/pool.c index 7c4d34a5a0..b3288d3cbb 100644 --- a/pjlib/src/pj/pool.c +++ b/pjlib/src/pj/pool.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,7 +30,7 @@ # include #endif -#define LOG(expr) PJ_LOG(6,expr) +#define LOG(expr) PJ_LOG(6,expr) #define ALIGN_PTR(PTR,ALIGNMENT) (PTR + (-(pj_ssize_t)(PTR) & (ALIGNMENT-1))) PJ_DEF_DATA(int) PJ_NO_MEMORY_EXCEPTION; @@ -54,14 +53,14 @@ static pj_pool_block *pj_pool_create_block( pj_pool_t *pool, pj_size_t size) pj_assert(size >= sizeof(pj_pool_block)); LOG((pool->obj_name, "create_block(sz=%u), cur.cap=%u, cur.used=%u", - size, pool->capacity, pj_pool_get_used_size(pool))); + size, pool->capacity, pj_pool_get_used_size(pool))); /* Request memory from allocator. */ block = (pj_pool_block*) - (*pool->factory->policy.block_alloc)(pool->factory, size); + (*pool->factory->policy.block_alloc)(pool->factory, size); if (block == NULL) { - (*pool->callback)(pool, size); - return NULL; + (*pool->callback)(pool, size); + return NULL; } /* Add capacity. */ @@ -97,20 +96,20 @@ PJ_DEF(void*) pj_pool_allocate_find(pj_pool_t *pool, pj_size_t size) PJ_CHECK_STACK(); while (block != &pool->block_list) { - p = pj_pool_alloc_from_block(block, size); - if (p != NULL) - return p; - block = block->next; + p = pj_pool_alloc_from_block(block, size); + if (p != NULL) + return p; + block = block->next; } /* No available space in all blocks. */ /* If pool is configured NOT to expand, return error. */ if (pool->increment_size == 0) { - LOG((pool->obj_name, "Can't expand pool to allocate %u bytes " - "(used=%u, cap=%u)", - size, pj_pool_get_used_size(pool), pool->capacity)); - (*pool->callback)(pool, size); - return NULL; + LOG((pool->obj_name, "Can't expand pool to allocate %u bytes " + "(used=%u, cap=%u)", + size, pj_pool_get_used_size(pool), pool->capacity)); + (*pool->callback)(pool, size); + return NULL; } /* If pool is configured to expand, but the increment size @@ -119,7 +118,7 @@ PJ_DEF(void*) pj_pool_allocate_find(pj_pool_t *pool, pj_size_t size) * the block. */ if (pool->increment_size < - size + sizeof(pj_pool_block) + PJ_POOL_ALIGNMENT) + size + sizeof(pj_pool_block) + PJ_POOL_ALIGNMENT) { pj_size_t count; count = (size + pool->increment_size + sizeof(pj_pool_block) + @@ -132,18 +131,18 @@ PJ_DEF(void*) pj_pool_allocate_find(pj_pool_t *pool, pj_size_t size) } LOG((pool->obj_name, - "%u bytes requested, resizing pool by %u bytes (used=%u, cap=%u)", - size, block_size, pj_pool_get_used_size(pool), pool->capacity)); + "%u bytes requested, resizing pool by %u bytes (used=%u, cap=%u)", + size, block_size, pj_pool_get_used_size(pool), pool->capacity)); block = pj_pool_create_block(pool, block_size); if (!block) - return NULL; + return NULL; p = pj_pool_alloc_from_block(block, size); pj_assert(p != NULL); #if PJ_DEBUG if (p == NULL) { - PJ_UNUSED_ARG(p); + PJ_UNUSED_ARG(p); } #endif return p; @@ -153,9 +152,9 @@ PJ_DEF(void*) pj_pool_allocate_find(pj_pool_t *pool, pj_size_t size) * Internal function to initialize pool. */ PJ_DEF(void) pj_pool_init_int( pj_pool_t *pool, - const char *name, - pj_size_t increment_size, - pj_pool_callback *callback) + const char *name, + pj_size_t increment_size, + pj_pool_callback *callback) { PJ_CHECK_STACK(); @@ -163,15 +162,15 @@ PJ_DEF(void) pj_pool_init_int( pj_pool_t *pool, pool->callback = callback; if (name) { - if (strchr(name, '%') != NULL) { - pj_ansi_snprintf(pool->obj_name, sizeof(pool->obj_name), - name, pool); - } else { - pj_ansi_strncpy(pool->obj_name, name, PJ_MAX_OBJ_NAME); - pool->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; - } + if (strchr(name, '%') != NULL) { + pj_ansi_snprintf(pool->obj_name, sizeof(pool->obj_name), + name, pool); + } else { + pj_ansi_strncpy(pool->obj_name, name, PJ_MAX_OBJ_NAME); + pool->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; + } } else { - pool->obj_name[0] = '\0'; + pool->obj_name[0] = '\0'; } } @@ -179,9 +178,9 @@ PJ_DEF(void) pj_pool_init_int( pj_pool_t *pool, * Create new memory pool. */ PJ_DEF(pj_pool_t*) pj_pool_create_int( pj_pool_factory *f, const char *name, - pj_size_t initial_size, - pj_size_t increment_size, - pj_pool_callback *callback) + pj_size_t initial_size, + pj_size_t increment_size, + pj_pool_callback *callback) { pj_pool_t *pool; pj_pool_block *block; @@ -191,16 +190,16 @@ PJ_DEF(pj_pool_t*) pj_pool_create_int( pj_pool_factory *f, const char *name, /* Size must be at least sizeof(pj_pool)+sizeof(pj_pool_block) */ PJ_ASSERT_RETURN(initial_size >= sizeof(pj_pool_t)+sizeof(pj_pool_block), - NULL); + NULL); /* If callback is NULL, set calback from the policy */ if (callback == NULL) - callback = f->policy.callback; + callback = f->policy.callback; /* Allocate initial block */ buffer = (pj_uint8_t*) (*f->policy.block_alloc)(f, initial_size); if (!buffer) - return NULL; + return NULL; /* Set pool administrative data. */ pool = (pj_pool_t*)buffer; @@ -241,7 +240,7 @@ static void reset_pool(pj_pool_t *pool) block = pool->block_list.prev; if (block == &pool->block_list) - return; + return; /* Skip the first block because it is occupying the same memory as the pool itself. @@ -249,11 +248,11 @@ static void reset_pool(pj_pool_t *pool) block = block->prev; while (block != &pool->block_list) { - pj_pool_block *prev = block->prev; - pj_list_erase(block); - (*pool->factory->policy.block_free)(pool->factory, block, - block->end - (unsigned char*)block); - block = prev; + pj_pool_block *prev = block->prev; + pj_list_erase(block); + (*pool->factory->policy.block_free)(pool->factory, block, + block->end - (unsigned char*)block); + block = prev; } block = pool->block_list.next; @@ -270,8 +269,8 @@ static void reset_pool(pj_pool_t *pool) PJ_DEF(void) pj_pool_reset(pj_pool_t *pool) { LOG((pool->obj_name, "reset(): cap=%d, used=%d(%d%%)", - pool->capacity, pj_pool_get_used_size(pool), - pj_pool_get_used_size(pool)*100/pool->capacity)); + pool->capacity, pj_pool_get_used_size(pool), + pj_pool_get_used_size(pool)*100/pool->capacity)); reset_pool(pool); } @@ -284,18 +283,18 @@ PJ_DEF(void) pj_pool_destroy_int(pj_pool_t *pool) pj_size_t initial_size; LOG((pool->obj_name, "destroy(): cap=%d, used=%d(%d%%), block0=%p-%p", - pool->capacity, pj_pool_get_used_size(pool), - pj_pool_get_used_size(pool)*100/pool->capacity, - ((pj_pool_block*)pool->block_list.next)->buf, - ((pj_pool_block*)pool->block_list.next)->end)); + pool->capacity, pj_pool_get_used_size(pool), + pj_pool_get_used_size(pool)*100/pool->capacity, + ((pj_pool_block*)pool->block_list.next)->buf, + ((pj_pool_block*)pool->block_list.next)->end)); reset_pool(pool); initial_size = ((pj_pool_block*)pool->block_list.next)->end - - (unsigned char*)pool; + (unsigned char*)pool; if (pool->factory->policy.block_free) - (*pool->factory->policy.block_free)(pool->factory, pool, initial_size); + (*pool->factory->policy.block_free)(pool->factory, pool, initial_size); } -#endif /* PJ_HAS_POOL_ALT_API */ +#endif /* PJ_HAS_POOL_ALT_API */ diff --git a/pjlib/src/pj/pool_buf.c b/pjlib/src/pj/pool_buf.c index f1cb3d2427..50a0fa57de 100644 --- a/pjlib/src/pj/pool_buf.c +++ b/pjlib/src/pj/pool_buf.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,8 +24,8 @@ static struct pj_pool_factory stack_based_factory; struct creation_param { - void *stack_buf; - pj_size_t size; + void *stack_buf; + pj_size_t size; }; static int is_initialized; @@ -36,11 +35,11 @@ static void* stack_alloc(pj_pool_factory *factory, pj_size_t size); static void pool_buf_cleanup(void) { if (tls != -1) { - pj_thread_local_free(tls); - tls = -1; + pj_thread_local_free(tls); + tls = -1; } if (is_initialized) - is_initialized = 0; + is_initialized = 0; } static pj_status_t pool_buf_initialize(void) @@ -60,8 +59,8 @@ static void* stack_alloc(pj_pool_factory *factory, pj_size_t size) param = (struct creation_param*) pj_thread_local_get(tls); if (param == NULL) { - /* Don't assert(), this is normal no-memory situation */ - return NULL; + /* Don't assert(), this is normal no-memory situation */ + return NULL; } pj_thread_local_set(tls, NULL); @@ -78,8 +77,8 @@ static void* stack_alloc(pj_pool_factory *factory, pj_size_t size) PJ_DEF(pj_pool_t*) pj_pool_create_on_buf(const char *name, - void *buf, - pj_size_t size) + void *buf, + pj_size_t size) { #if PJ_HAS_POOL_ALT_API == 0 struct creation_param param; @@ -88,17 +87,17 @@ PJ_DEF(pj_pool_t*) pj_pool_create_on_buf(const char *name, PJ_ASSERT_RETURN(buf && size, NULL); if (!is_initialized) { - if (pool_buf_initialize() != PJ_SUCCESS) - return NULL; - is_initialized = 1; + if (pool_buf_initialize() != PJ_SUCCESS) + return NULL; + is_initialized = 1; } /* Check and align buffer */ align_diff = (pj_size_t)buf; if (align_diff & (PJ_POOL_ALIGNMENT-1)) { - align_diff &= (PJ_POOL_ALIGNMENT-1); - buf = (void*) (((char*)buf) + align_diff); - size -= align_diff; + align_diff &= (PJ_POOL_ALIGNMENT-1); + buf = (void*) (((char*)buf) + align_diff); + size -= align_diff; } param.stack_buf = buf; @@ -106,7 +105,7 @@ PJ_DEF(pj_pool_t*) pj_pool_create_on_buf(const char *name, pj_thread_local_set(tls, ¶m); return pj_pool_create_int(&stack_based_factory, name, size, 0, - pj_pool_factory_default_policy.callback); + pj_pool_factory_default_policy.callback); #else PJ_UNUSED_ARG(buf); return pj_pool_create(NULL, name, size, size, NULL); diff --git a/pjlib/src/pj/pool_caching.c b/pjlib/src/pj/pool_caching.c index 8e2c992001..6da91bf0ce 100644 --- a/pjlib/src/pj/pool_caching.c +++ b/pjlib/src/pj/pool_caching.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,10 +27,10 @@ #if !PJ_HAS_POOL_ALT_API static pj_pool_t* cpool_create_pool(pj_pool_factory *pf, - const char *name, - pj_size_t initial_size, - pj_size_t increment_sz, - pj_pool_callback *callback); + const char *name, + pj_size_t initial_size, + pj_size_t increment_sz, + pj_pool_callback *callback); static void cpool_release_pool(pj_pool_factory *pf, pj_pool_t *pool); static void cpool_dump_status(pj_pool_factory *factory, pj_bool_t detail ); static pj_bool_t cpool_on_block_alloc(pj_pool_factory *f, pj_size_t sz); @@ -51,8 +50,8 @@ static pj_size_t pool_sizes[PJ_CACHING_POOL_ARRAY_SIZE] = PJ_DEF(void) pj_caching_pool_init( pj_caching_pool *cp, - const pj_pool_factory_policy *policy, - pj_size_t max_capacity) + const pj_pool_factory_policy *policy, + pj_size_t max_capacity) { int i; pj_pool_t *pool; @@ -64,10 +63,10 @@ PJ_DEF(void) pj_caching_pool_init( pj_caching_pool *cp, cp->max_capacity = max_capacity; pj_list_init(&cp->used_list); for (i=0; ifree_list[i]); + pj_list_init(&cp->free_list[i]); if (policy == NULL) { - policy = &pj_pool_factory_default_policy; + policy = &pj_pool_factory_default_policy; } pj_memcpy(&cp->factory.policy, policy, sizeof(pj_pool_factory_policy)); @@ -90,37 +89,37 @@ PJ_DEF(void) pj_caching_pool_destroy( pj_caching_pool *cp ) /* Delete all pool in free list */ for (i=0; i < PJ_CACHING_POOL_ARRAY_SIZE; ++i) { - pj_pool_t *next; - pool = (pj_pool_t*) cp->free_list[i].next; - for (; pool != (void*)&cp->free_list[i]; pool = next) { - next = pool->next; - pj_list_erase(pool); - pj_pool_destroy_int(pool); - } + pj_pool_t *next; + pool = (pj_pool_t*) cp->free_list[i].next; + for (; pool != (void*)&cp->free_list[i]; pool = next) { + next = pool->next; + pj_list_erase(pool); + pj_pool_destroy_int(pool); + } } /* Delete all pools in used list */ pool = (pj_pool_t*) cp->used_list.next; while (pool != (pj_pool_t*) &cp->used_list) { - pj_pool_t *next = pool->next; - pj_list_erase(pool); - PJ_LOG(4,(pool->obj_name, - "Pool is not released by application, releasing now")); - pj_pool_destroy_int(pool); - pool = next; + pj_pool_t *next = pool->next; + pj_list_erase(pool); + PJ_LOG(4,(pool->obj_name, + "Pool is not released by application, releasing now")); + pj_pool_destroy_int(pool); + pool = next; } if (cp->lock) { - pj_lock_destroy(cp->lock); - pj_lock_create_null_mutex(NULL, "cachingpool", &cp->lock); + pj_lock_destroy(cp->lock); + pj_lock_create_null_mutex(NULL, "cachingpool", &cp->lock); } } static pj_pool_t* cpool_create_pool(pj_pool_factory *pf, - const char *name, - pj_size_t initial_size, - pj_size_t increment_sz, - pj_pool_callback *callback) + const char *name, + pj_size_t initial_size, + pj_size_t increment_sz, + pj_pool_callback *callback) { pj_caching_pool *cp = (pj_caching_pool*)pf; pj_pool_t *pool; @@ -132,7 +131,7 @@ static pj_pool_t* cpool_create_pool(pj_pool_factory *pf, /* Use pool factory's policy when callback is NULL */ if (callback == NULL) { - callback = pf->policy.callback; + callback = pf->policy.callback; } /* Search the suitable size for the pool. @@ -141,50 +140,50 @@ static pj_pool_t* cpool_create_pool(pj_pool_factory *pf, * for this purpose. */ if (initial_size <= pool_sizes[START_SIZE]) { - for (idx=START_SIZE-1; - idx >= 0 && pool_sizes[idx] >= initial_size; - --idx) - ; - ++idx; + for (idx=START_SIZE-1; + idx >= 0 && pool_sizes[idx] >= initial_size; + --idx) + ; + ++idx; } else { - for (idx=START_SIZE+1; - idx < PJ_CACHING_POOL_ARRAY_SIZE && - pool_sizes[idx] < initial_size; - ++idx) - ; + for (idx=START_SIZE+1; + idx < PJ_CACHING_POOL_ARRAY_SIZE && + pool_sizes[idx] < initial_size; + ++idx) + ; } /* Check whether there's a pool in the list. */ if (idx==PJ_CACHING_POOL_ARRAY_SIZE || pj_list_empty(&cp->free_list[idx])) { - /* No pool is available. */ - /* Set minimum size. */ - if (idx < PJ_CACHING_POOL_ARRAY_SIZE) - initial_size = pool_sizes[idx]; - - /* Create new pool */ - pool = pj_pool_create_int(&cp->factory, name, initial_size, - increment_sz, callback); - if (!pool) { - pj_lock_release(cp->lock); - return NULL; - } + /* No pool is available. */ + /* Set minimum size. */ + if (idx < PJ_CACHING_POOL_ARRAY_SIZE) + initial_size = pool_sizes[idx]; + + /* Create new pool */ + pool = pj_pool_create_int(&cp->factory, name, initial_size, + increment_sz, callback); + if (!pool) { + pj_lock_release(cp->lock); + return NULL; + } } else { - /* Get one pool from the list. */ - pool = (pj_pool_t*) cp->free_list[idx].next; - pj_list_erase(pool); + /* Get one pool from the list. */ + pool = (pj_pool_t*) cp->free_list[idx].next; + pj_list_erase(pool); - /* Initialize the pool. */ - pj_pool_init_int(pool, name, increment_sz, callback); + /* Initialize the pool. */ + pj_pool_init_int(pool, name, increment_sz, callback); - /* Update pool manager's free capacity. */ - if (cp->capacity > pj_pool_get_capacity(pool)) { - cp->capacity -= pj_pool_get_capacity(pool); - } else { - cp->capacity = 0; - } + /* Update pool manager's free capacity. */ + if (cp->capacity > pj_pool_get_capacity(pool)) { + cp->capacity -= pj_pool_get_capacity(pool); + } else { + cp->capacity = 0; + } - PJ_LOG(6, (pool->obj_name, "pool reused, size=%u", pool->capacity)); + PJ_LOG(6, (pool->obj_name, "pool reused, size=%u", pool->capacity)); } /* Put in used list. */ @@ -215,8 +214,8 @@ static void cpool_release_pool( pj_pool_factory *pf, pj_pool_t *pool) #if PJ_SAFE_POOL /* Make sure pool is still in our used list */ if (pj_list_find_node(&cp->used_list, pool) != pool) { - pj_assert(!"Attempt to destroy pool that has been destroyed before"); - return; + pj_assert(!"Attempt to destroy pool that has been destroyed before"); + return; } #endif @@ -233,17 +232,17 @@ static void cpool_release_pool( pj_pool_factory *pf, pj_pool_t *pool) * maximum capacity. . */ if (pool_capacity > pool_sizes[PJ_CACHING_POOL_ARRAY_SIZE-1] || - cp->capacity + pool_capacity > cp->max_capacity) + cp->capacity + pool_capacity > cp->max_capacity) { - pj_pool_destroy_int(pool); - pj_lock_release(cp->lock); - return; + pj_pool_destroy_int(pool); + pj_lock_release(cp->lock); + return; } /* Reset pool. */ PJ_LOG(6, (pool->obj_name, "recycle(): cap=%d, used=%d(%d%%)", - pool_capacity, pj_pool_get_used_size(pool), - pj_pool_get_used_size(pool)*100/pool_capacity)); + pool_capacity, pj_pool_get_used_size(pool), + pj_pool_get_used_size(pool)*100/pool_capacity)); pj_pool_reset(pool); pool_capacity = pj_pool_get_capacity(pool); @@ -255,10 +254,10 @@ static void cpool_release_pool( pj_pool_factory *pf, pj_pool_t *pool) pj_assert(i= PJ_CACHING_POOL_ARRAY_SIZE ) { - /* Something has gone wrong with the pool. */ - pj_pool_destroy_int(pool); - pj_lock_release(cp->lock); - return; + /* Something has gone wrong with the pool. */ + pj_pool_destroy_int(pool); + pj_lock_release(cp->lock); + return; } pj_list_insert_after(&cp->free_list[i], pool); @@ -276,27 +275,27 @@ static void cpool_dump_status(pj_pool_factory *factory, pj_bool_t detail ) PJ_LOG(3,("cachpool", " Dumping caching pool:")); PJ_LOG(3,("cachpool", " Capacity=%u, max_capacity=%u, used_cnt=%u", \ - cp->capacity, cp->max_capacity, cp->used_count)); + cp->capacity, cp->max_capacity, cp->used_count)); if (detail) { - pj_pool_t *pool = (pj_pool_t*) cp->used_list.next; - pj_size_t total_used = 0, total_capacity = 0; + pj_pool_t *pool = (pj_pool_t*) cp->used_list.next; + pj_size_t total_used = 0, total_capacity = 0; PJ_LOG(3,("cachpool", " Dumping all active pools:")); - while (pool != (void*)&cp->used_list) { - pj_size_t pool_capacity = pj_pool_get_capacity(pool); - PJ_LOG(3,("cachpool", " %16s: %8d of %8d (%d%%) used", - pj_pool_getobjname(pool), - pj_pool_get_used_size(pool), - pool_capacity, - pj_pool_get_used_size(pool)*100/pool_capacity)); - total_used += pj_pool_get_used_size(pool); - total_capacity += pool_capacity; - pool = pool->next; - } - if (total_capacity) { - PJ_LOG(3,("cachpool", " Total %9d of %9d (%d %%) used!", - total_used, total_capacity, - total_used * 100 / total_capacity)); - } + while (pool != (void*)&cp->used_list) { + pj_size_t pool_capacity = pj_pool_get_capacity(pool); + PJ_LOG(3,("cachpool", " %16s: %8d of %8d (%d%%) used", + pj_pool_getobjname(pool), + pj_pool_get_used_size(pool), + pool_capacity, + pj_pool_get_used_size(pool)*100/pool_capacity)); + total_used += pj_pool_get_used_size(pool); + total_capacity += pool_capacity; + pool = pool->next; + } + if (total_capacity) { + PJ_LOG(3,("cachpool", " Total %9d of %9d (%d %%) used!", + total_used, total_capacity, + total_used * 100 / total_capacity)); + } } pj_lock_release(cp->lock); @@ -316,7 +315,7 @@ static pj_bool_t cpool_on_block_alloc(pj_pool_factory *f, pj_size_t sz) cp->used_size += sz; if (cp->used_size > cp->peak_used_size) - cp->peak_used_size = cp->used_size; + cp->peak_used_size = cp->used_size; //if (cp->mutex) pj_mutex_unlock(cp->mutex); @@ -334,5 +333,5 @@ static void cpool_on_block_free(pj_pool_factory *f, pj_size_t sz) } -#endif /* PJ_HAS_POOL_ALT_API */ +#endif /* PJ_HAS_POOL_ALT_API */ diff --git a/pjlib/src/pj/pool_dbg.c b/pjlib/src/pj/pool_dbg.c index 7089d4d140..df6c860222 100644 --- a/pjlib/src/pj/pool_dbg.c +++ b/pjlib/src/pj/pool_dbg.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,7 +35,7 @@ (defined(PJ_WIN64) && PJ_WIN64 != 0)) && \ defined(PJ_DEBUG) && PJ_DEBUG!=0 && !PJ_NATIVE_STRING_IS_UNICODE # include -# define TRACE_(msg) OutputDebugString(msg) +# define TRACE_(msg) OutputDebugString(msg) #endif /* Uncomment this to enable TRACE_ */ @@ -54,11 +53,11 @@ PJ_DEF(int) pj_NO_MEMORY_EXCEPTION() /* Create pool */ PJ_DEF(pj_pool_t*) pj_pool_create_imp( const char *file, int line, - void *factory, - const char *name, - pj_size_t initial_size, - pj_size_t increment_size, - pj_pool_callback *callback) + void *factory, + const char *name, + pj_size_t initial_size, + pj_size_t increment_size, + pj_pool_callback *callback) { pj_pool_t *pool; @@ -70,13 +69,13 @@ PJ_DEF(pj_pool_t*) pj_pool_create_imp( const char *file, int line, pool = malloc(sizeof(struct pj_pool_t)); if (!pool) - return NULL; + return NULL; if (name) { - pj_ansi_strncpy(pool->obj_name, name, sizeof(pool->obj_name)); - pool->obj_name[sizeof(pool->obj_name)-1] = '\0'; + pj_ansi_strncpy(pool->obj_name, name, sizeof(pool->obj_name)); + pool->obj_name[sizeof(pool->obj_name)-1] = '\0'; } else { - strcpy(pool->obj_name, "altpool"); + strcpy(pool->obj_name, "altpool"); } pool->factory = NULL; @@ -101,7 +100,7 @@ PJ_DEF(void) pj_pool_safe_release_imp( pj_pool_t **ppool ) pj_pool_t *pool = *ppool; *ppool = NULL; if (pool) - pj_pool_release(pool); + pj_pool_release(pool); } /* Secure release pool */ @@ -127,9 +126,9 @@ PJ_DEF(void) pj_pool_reset_imp(pj_pool_t *pool) mem = pool->first_mem; while (mem) { - struct pj_pool_mem *next = mem->next; - free(mem); - mem = next; + struct pj_pool_mem *next = mem->next; + free(mem); + mem = next; } pool->first_mem = NULL; @@ -152,7 +151,7 @@ PJ_DEF(pj_size_t) pj_pool_get_used_size_imp(pj_pool_t *pool) /* Allocate memory from the pool */ PJ_DEF(void*) pj_pool_alloc_imp( const char *file, int line, - pj_pool_t *pool, pj_size_t sz) + pj_pool_t *pool, pj_size_t sz) { struct pj_pool_mem *mem; @@ -161,9 +160,9 @@ PJ_DEF(void*) pj_pool_alloc_imp( const char *file, int line, mem = malloc(sz + sizeof(struct pj_pool_mem)); if (!mem) { - if (pool->cb) - (*pool->cb)(pool, sz); - return NULL; + if (pool->cb) + (*pool->cb)(pool, sz); + return NULL; } mem->next = pool->first_mem; @@ -171,11 +170,11 @@ PJ_DEF(void*) pj_pool_alloc_imp( const char *file, int line, #ifdef TRACE_ { - char msg[120]; - pj_ansi_sprintf(msg, "Mem %X (%d+%d bytes) allocated by %s:%d\r\n", - mem, sz, sizeof(struct pj_pool_mem), - file, line); - TRACE_(msg); + char msg[120]; + pj_ansi_sprintf(msg, "Mem %X (%d+%d bytes) allocated by %s:%d\r\n", + mem, sz, sizeof(struct pj_pool_mem), + file, line); + TRACE_(msg); } #endif @@ -184,14 +183,14 @@ PJ_DEF(void*) pj_pool_alloc_imp( const char *file, int line, /* Allocate memory from the pool and zero the memory */ PJ_DEF(void*) pj_pool_calloc_imp( const char *file, int line, - pj_pool_t *pool, unsigned cnt, - unsigned elemsz) + pj_pool_t *pool, unsigned cnt, + unsigned elemsz) { void *mem; mem = pj_pool_alloc_imp(file, line, pool, cnt*elemsz); if (!mem) - return NULL; + return NULL; pj_bzero(mem, cnt*elemsz); return mem; @@ -199,11 +198,11 @@ PJ_DEF(void*) pj_pool_calloc_imp( const char *file, int line, /* Allocate memory from the pool and zero the memory */ PJ_DEF(void*) pj_pool_zalloc_imp( const char *file, int line, - pj_pool_t *pool, pj_size_t sz) + pj_pool_t *pool, pj_size_t sz) { return pj_pool_calloc_imp(file, line, pool, 1, sz); } -#endif /* PJ_HAS_POOL_ALT_API */ +#endif /* PJ_HAS_POOL_ALT_API */ diff --git a/pjlib/src/pj/pool_policy_kmalloc.c b/pjlib/src/pj/pool_policy_kmalloc.c index 3f7ca4ffaa..3464aafa36 100644 --- a/pjlib/src/pj/pool_policy_kmalloc.c +++ b/pjlib/src/pj/pool_policy_kmalloc.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,7 +30,7 @@ static void *default_block_alloc(pj_pool_factory *factory, pj_size_t size) } static void default_block_free(pj_pool_factory *factory, - void *mem, pj_size_t size) + void *mem, pj_size_t size) { PJ_CHECK_STACK(); PJ_UNUSED_ARG(factory); diff --git a/pjlib/src/pj/pool_policy_malloc.c b/pjlib/src/pj/pool_policy_malloc.c index b2a9157da5..16b7f640b2 100644 --- a/pjlib/src/pj/pool_policy_malloc.c +++ b/pjlib/src/pj/pool_policy_malloc.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -37,29 +36,29 @@ static void *default_block_alloc(pj_pool_factory *factory, pj_size_t size) PJ_CHECK_STACK(); if (factory->on_block_alloc) { - int rc; - rc = factory->on_block_alloc(factory, size); - if (!rc) - return NULL; + int rc; + rc = factory->on_block_alloc(factory, size); + if (!rc) + return NULL; } p = malloc(size+(SIG_SIZE << 1)); if (p == NULL) { - if (factory->on_block_free) - factory->on_block_free(factory, size); + if (factory->on_block_free) + factory->on_block_free(factory, size); } else { - /* Apply signature when PJ_SAFE_POOL is set. It will move - * "p" pointer forward. - */ - APPLY_SIG(p, size); + /* Apply signature when PJ_SAFE_POOL is set. It will move + * "p" pointer forward. + */ + APPLY_SIG(p, size); } return p; } static void default_block_free(pj_pool_factory *factory, void *mem, - pj_size_t size) + pj_size_t size) { PJ_CHECK_STACK(); @@ -101,4 +100,4 @@ PJ_DEF(const pj_pool_factory_policy*) pj_pool_factory_get_default_policy(void) } -#endif /* PJ_HAS_POOL_ALT_API */ +#endif /* PJ_HAS_POOL_ALT_API */ diff --git a/pjlib/src/pj/pool_policy_new.cpp b/pjlib/src/pj/pool_policy_new.cpp index 66375cd4fb..02cfabcabe 100644 --- a/pjlib/src/pj/pool_policy_new.cpp +++ b/pjlib/src/pj/pool_policy_new.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,20 +35,20 @@ static void *operator_new(pj_pool_factory *factory, pj_size_t size) PJ_CHECK_STACK(); if (factory->on_block_alloc) { - int rc; - rc = factory->on_block_alloc(factory, size); - if (!rc) - return NULL; + int rc; + rc = factory->on_block_alloc(factory, size); + if (!rc) + return NULL; } mem = (void*) new char[size+(SIG_SIZE << 1)]; /* Exception for new operator may be disabled, so.. */ if (mem) { - /* Apply signature when PJ_SAFE_POOL is set. It will move - * "mem" pointer forward. - */ - APPLY_SIG(mem, size); + /* Apply signature when PJ_SAFE_POOL is set. It will move + * "mem" pointer forward. + */ + APPLY_SIG(mem, size); } return mem; @@ -98,5 +97,5 @@ PJ_DEF(const pj_pool_factory_policy*) pj_pool_factory_get_default_policy(void) } -#endif /* PJ_HAS_POOL_ALT_API */ +#endif /* PJ_HAS_POOL_ALT_API */ diff --git a/pjlib/src/pj/pool_signature.h b/pjlib/src/pj/pool_signature.h index e51f292122..a77fe428d8 100644 --- a/pjlib/src/pj/pool_signature.h +++ b/pjlib/src/pj/pool_signature.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,18 +20,18 @@ #include #if PJ_SAFE_POOL -# define SIG_SIZE sizeof(pj_uint32_t) +# define SIG_SIZE sizeof(pj_uint32_t) static void apply_signature(void *p, pj_size_t size); static void check_pool_signature(void *p, pj_size_t size); -# define APPLY_SIG(p,sz) apply_signature(p,sz), \ - p=(void*)(((char*)p)+SIG_SIZE) -# define REMOVE_SIG(p,sz) check_pool_signature(p,sz), \ - p=(void*)(((char*)p)-SIG_SIZE) +# define APPLY_SIG(p,sz) apply_signature(p,sz), \ + p=(void*)(((char*)p)+SIG_SIZE) +# define REMOVE_SIG(p,sz) check_pool_signature(p,sz), \ + p=(void*)(((char*)p)-SIG_SIZE) -# define SIG_BEGIN 0x600DC0DE -# define SIG_END 0x0BADC0DE +# define SIG_BEGIN 0x600DC0DE +# define SIG_END 0x0BADC0DE static void apply_signature(void *p, pj_size_t size) { @@ -62,7 +61,7 @@ static void check_pool_signature(void *p, pj_size_t size) } #else -# define SIG_SIZE 0 +# define SIG_SIZE 0 # define APPLY_SIG(p,sz) # define REMOVE_SIG(p,sz) #endif diff --git a/pjlib/src/pj/rand.c b/pjlib/src/pj/rand.c index 4f788bb490..99f6541654 100644 --- a/pjlib/src/pj/rand.c +++ b/pjlib/src/pj/rand.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pj/rbtree.c b/pjlib/src/pj/rbtree.c index b640087bb6..3b1246b0ba 100644 --- a/pjlib/src/pj/rbtree.c +++ b/pjlib/src/pj/rbtree.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -37,9 +36,9 @@ static void left_rotate( pj_rbtree *tree, pj_rbtree_node *node ) rnode->parent = parent; if (parent != tree->null) { if (parent->left == node) - parent->left = rnode; + parent->left = rnode; else - parent->right = rnode; + parent->right = rnode; } else { tree->root = rnode; } @@ -59,15 +58,15 @@ static void right_rotate( pj_rbtree *tree, pj_rbtree_node *node ) node->left = lnode->right; if (lnode->right != tree->null) - lnode->right->parent = node; + lnode->right->parent = node; parent = node->parent; lnode->parent = parent; if (parent != tree->null) { if (parent->left == node) - parent->left = lnode; - else - parent->right = lnode; + parent->left = lnode; + else + parent->right = lnode; } else { tree->root = lnode; } @@ -84,46 +83,46 @@ static void insert_fixup( pj_rbtree *tree, pj_rbtree_node *node ) while (node != tree->root && node->parent->color == PJ_RBCOLOR_RED) { parent = node->parent; if (parent == parent->parent->left) { - temp = parent->parent->right; - if (temp->color == PJ_RBCOLOR_RED) { - temp->color = PJ_RBCOLOR_BLACK; - node = parent; - node->color = PJ_RBCOLOR_BLACK; - node = node->parent; - node->color = PJ_RBCOLOR_RED; - } else { - if (node == parent->right) { - node = parent; - left_rotate(tree, node); - } - temp = node->parent; - temp->color = PJ_RBCOLOR_BLACK; - temp = temp->parent; - temp->color = PJ_RBCOLOR_RED; - right_rotate( tree, temp); - } + temp = parent->parent->right; + if (temp->color == PJ_RBCOLOR_RED) { + temp->color = PJ_RBCOLOR_BLACK; + node = parent; + node->color = PJ_RBCOLOR_BLACK; + node = node->parent; + node->color = PJ_RBCOLOR_RED; + } else { + if (node == parent->right) { + node = parent; + left_rotate(tree, node); + } + temp = node->parent; + temp->color = PJ_RBCOLOR_BLACK; + temp = temp->parent; + temp->color = PJ_RBCOLOR_RED; + right_rotate( tree, temp); + } } else { - temp = parent->parent->left; - if (temp->color == PJ_RBCOLOR_RED) { - temp->color = PJ_RBCOLOR_BLACK; - node = parent; - node->color = PJ_RBCOLOR_BLACK; - node = node->parent; - node->color = PJ_RBCOLOR_RED; - } else { - if (node == parent->left) { - node = parent; - right_rotate(tree, node); - } - temp = node->parent; - temp->color = PJ_RBCOLOR_BLACK; - temp = temp->parent; - temp->color = PJ_RBCOLOR_RED; - left_rotate(tree, temp); - } + temp = parent->parent->left; + if (temp->color == PJ_RBCOLOR_RED) { + temp->color = PJ_RBCOLOR_BLACK; + node = parent; + node->color = PJ_RBCOLOR_BLACK; + node = node->parent; + node->color = PJ_RBCOLOR_RED; + } else { + if (node == parent->left) { + node = parent; + right_rotate(tree, node); + } + temp = node->parent; + temp->color = PJ_RBCOLOR_BLACK; + temp = temp->parent; + temp->color = PJ_RBCOLOR_RED; + left_rotate(tree, temp); + } } } - + tree->root->color = PJ_RBCOLOR_BLACK; } @@ -136,60 +135,60 @@ static void delete_fixup( pj_rbtree *tree, pj_rbtree_node *node ) while (node != tree->root && node->color == PJ_RBCOLOR_BLACK) { if (node->parent->left == node) { - temp = node->parent->right; - if (temp->color == PJ_RBCOLOR_RED) { - temp->color = PJ_RBCOLOR_BLACK; - node->parent->color = PJ_RBCOLOR_RED; - left_rotate(tree, node->parent); - temp = node->parent->right; - } - if (temp->left->color == PJ_RBCOLOR_BLACK && - temp->right->color == PJ_RBCOLOR_BLACK) - { - temp->color = PJ_RBCOLOR_RED; - node = node->parent; - } else { - if (temp->right->color == PJ_RBCOLOR_BLACK) { - temp->left->color = PJ_RBCOLOR_BLACK; - temp->color = PJ_RBCOLOR_RED; - right_rotate( tree, temp); - temp = node->parent->right; - } - temp->color = node->parent->color; - temp->right->color = PJ_RBCOLOR_BLACK; - node->parent->color = PJ_RBCOLOR_BLACK; - left_rotate(tree, node->parent); - node = tree->root; - } + temp = node->parent->right; + if (temp->color == PJ_RBCOLOR_RED) { + temp->color = PJ_RBCOLOR_BLACK; + node->parent->color = PJ_RBCOLOR_RED; + left_rotate(tree, node->parent); + temp = node->parent->right; + } + if (temp->left->color == PJ_RBCOLOR_BLACK && + temp->right->color == PJ_RBCOLOR_BLACK) + { + temp->color = PJ_RBCOLOR_RED; + node = node->parent; + } else { + if (temp->right->color == PJ_RBCOLOR_BLACK) { + temp->left->color = PJ_RBCOLOR_BLACK; + temp->color = PJ_RBCOLOR_RED; + right_rotate( tree, temp); + temp = node->parent->right; + } + temp->color = node->parent->color; + temp->right->color = PJ_RBCOLOR_BLACK; + node->parent->color = PJ_RBCOLOR_BLACK; + left_rotate(tree, node->parent); + node = tree->root; + } } else { - temp = node->parent->left; - if (temp->color == PJ_RBCOLOR_RED) { - temp->color = PJ_RBCOLOR_BLACK; - node->parent->color = PJ_RBCOLOR_RED; - right_rotate( tree, node->parent); - temp = node->parent->left; - } - if (temp->right->color == PJ_RBCOLOR_BLACK && - temp->left->color == PJ_RBCOLOR_BLACK) - { - temp->color = PJ_RBCOLOR_RED; - node = node->parent; - } else { - if (temp->left->color == PJ_RBCOLOR_BLACK) { - temp->right->color = PJ_RBCOLOR_BLACK; - temp->color = PJ_RBCOLOR_RED; - left_rotate( tree, temp); - temp = node->parent->left; - } - temp->color = node->parent->color; - node->parent->color = PJ_RBCOLOR_BLACK; - temp->left->color = PJ_RBCOLOR_BLACK; - right_rotate(tree, node->parent); - node = tree->root; - } + temp = node->parent->left; + if (temp->color == PJ_RBCOLOR_RED) { + temp->color = PJ_RBCOLOR_BLACK; + node->parent->color = PJ_RBCOLOR_RED; + right_rotate( tree, node->parent); + temp = node->parent->left; + } + if (temp->right->color == PJ_RBCOLOR_BLACK && + temp->left->color == PJ_RBCOLOR_BLACK) + { + temp->color = PJ_RBCOLOR_RED; + node = node->parent; + } else { + if (temp->left->color == PJ_RBCOLOR_BLACK) { + temp->right->color = PJ_RBCOLOR_BLACK; + temp->color = PJ_RBCOLOR_RED; + left_rotate( tree, temp); + temp = node->parent->left; + } + temp->color = node->parent->color; + node->parent->color = PJ_RBCOLOR_BLACK; + temp->left->color = PJ_RBCOLOR_BLACK; + right_rotate(tree, node->parent); + node = tree->root; + } } } - + node->color = PJ_RBCOLOR_BLACK; } @@ -215,7 +214,7 @@ PJ_DEF(pj_rbtree_node*) pj_rbtree_first( pj_rbtree *tree ) PJ_CHECK_STACK(); while (node->left != null) - node = node->left; + node = node->left; return node != null ? node : NULL; } @@ -227,33 +226,33 @@ PJ_DEF(pj_rbtree_node*) pj_rbtree_last( pj_rbtree *tree ) PJ_CHECK_STACK(); while (node->right != null) - node = node->right; + node = node->right; return node != null ? node : NULL; } PJ_DEF(pj_rbtree_node*) pj_rbtree_next( pj_rbtree *tree, - register pj_rbtree_node *node ) + register pj_rbtree_node *node ) { register pj_rbtree_node *null = tree->null; PJ_CHECK_STACK(); if (node->right != null) { - for (node=node->right; node->left!=null; node = node->left) - /* void */; + for (node=node->right; node->left!=null; node = node->left) + /* void */; } else { register pj_rbtree_node *temp = node->parent; while (temp!=null && temp->right==node) { - node = temp; - temp = temp->parent; - } - node = temp; + node = temp; + temp = temp->parent; + } + node = temp; } return node != null ? node : NULL; } PJ_DEF(pj_rbtree_node*) pj_rbtree_prev( pj_rbtree *tree, - register pj_rbtree_node *node ) + register pj_rbtree_node *node ) { register pj_rbtree_node *null = tree->null; @@ -261,12 +260,12 @@ PJ_DEF(pj_rbtree_node*) pj_rbtree_prev( pj_rbtree *tree, if (node->left != null) { for (node=node->left; node->right!=null; node=node->right) - /* void */; + /* void */; } else { register pj_rbtree_node *temp = node->parent; while (temp!=null && temp->left==node) { - node = temp; - temp = temp->parent; + node = temp; + temp = temp->parent; } node = temp; } @@ -274,23 +273,23 @@ PJ_DEF(pj_rbtree_node*) pj_rbtree_prev( pj_rbtree *tree, } PJ_DEF(int) pj_rbtree_insert( pj_rbtree *tree, - pj_rbtree_node *element ) + pj_rbtree_node *element ) { int rv = 0; pj_rbtree_node *node, *parent = tree->null, - *null = tree->null; + *null = tree->null; pj_rbtree_comp *comp = tree->comp; - + PJ_CHECK_STACK(); - node = tree->root; + node = tree->root; while (node != null) { rv = (*comp)(element->key, node->key); if (rv == 0) { - /* found match, i.e. entry with equal key already exist */ - return -1; - } - parent = node; + /* found match, i.e. entry with equal key already exist */ + return -1; + } + parent = node; node = rv < 0 ? node->left : node->right; } @@ -301,23 +300,23 @@ PJ_DEF(int) pj_rbtree_insert( pj_rbtree *tree, if (parent != null) { node->parent = parent; if (rv < 0) - parent->left = node; + parent->left = node; else - parent->right = node; + parent->right = node; insert_fixup( tree, node); } else { tree->root = node; node->parent = null; node->color = PJ_RBCOLOR_BLACK; } - + ++tree->size; return 0; } PJ_DEF(pj_rbtree_node*) pj_rbtree_find( pj_rbtree *tree, - const void *key ) + const void *key ) { int rv; pj_rbtree_node *node = tree->root; @@ -327,14 +326,14 @@ PJ_DEF(pj_rbtree_node*) pj_rbtree_find( pj_rbtree *tree, while (node != null) { rv = (*comp)(key, node->key); if (rv == 0) - return node; + return node; node = rv < 0 ? node->left : node->right; } return node != null ? node : NULL; } PJ_DEF(pj_rbtree_node*) pj_rbtree_erase( pj_rbtree *tree, - pj_rbtree_node *node ) + pj_rbtree_node *node ) { pj_rbtree_node *succ; pj_rbtree_node *null = tree->null; @@ -347,7 +346,7 @@ PJ_DEF(pj_rbtree_node*) pj_rbtree_erase( pj_rbtree *tree, succ = node; } else { for (succ=node->right; succ->left!=null; succ=succ->left) - /* void */; + /* void */; } child = succ->left != null ? succ->left : succ->right; @@ -355,10 +354,10 @@ PJ_DEF(pj_rbtree_node*) pj_rbtree_erase( pj_rbtree *tree, child->parent = parent; if (parent != null) { - if (parent->left == succ) - parent->left = child; + if (parent->left == succ) + parent->left = child; else - parent->right = child; + parent->right = child; } else tree->root = child; @@ -370,23 +369,23 @@ PJ_DEF(pj_rbtree_node*) pj_rbtree_erase( pj_rbtree *tree, parent = node->parent; if (parent != null) { - if (parent->left==node) - parent->left=succ; - else - parent->right=succ; + if (parent->left==node) + parent->left=succ; + else + parent->right=succ; } if (node->left != null) - node->left->parent = succ;; + node->left->parent = succ;; if (node->right != null) - node->right->parent = succ; + node->right->parent = succ; if (tree->root == node) - tree->root = succ; + tree->root = succ; } if (succ->color == PJ_RBCOLOR_BLACK) { - if (child != null) - delete_fixup(tree, child); + if (child != null) + delete_fixup(tree, child); tree->null->color = PJ_RBCOLOR_BLACK; } @@ -396,14 +395,14 @@ PJ_DEF(pj_rbtree_node*) pj_rbtree_erase( pj_rbtree *tree, PJ_DEF(unsigned) pj_rbtree_max_height( pj_rbtree *tree, - pj_rbtree_node *node ) + pj_rbtree_node *node ) { unsigned l, r; PJ_CHECK_STACK(); if (node==NULL) - node = tree->root; + node = tree->root; l = node->left != tree->null ? pj_rbtree_max_height(tree,node->left)+1 : 0; r = node->right != tree->null ? pj_rbtree_max_height(tree,node->right)+1 : 0; @@ -411,14 +410,14 @@ PJ_DEF(unsigned) pj_rbtree_max_height( pj_rbtree *tree, } PJ_DEF(unsigned) pj_rbtree_min_height( pj_rbtree *tree, - pj_rbtree_node *node ) + pj_rbtree_node *node ) { unsigned l, r; PJ_CHECK_STACK(); if (node==NULL) - node=tree->root; + node=tree->root; l = (node->left != tree->null) ? pj_rbtree_max_height(tree,node->left)+1 : 0; r = (node->right != tree->null) ? pj_rbtree_max_height(tree,node->right)+1 : 0; diff --git a/pjlib/src/pj/sock_bsd.c b/pjlib/src/pj/sock_bsd.c index bd9e0a4c8a..6d4c7f6bc5 100644 --- a/pjlib/src/pj/sock_bsd.c +++ b/pjlib/src/pj/sock_bsd.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -26,25 +25,25 @@ #include #include -#define THIS_FILE "sock_bsd.c" +#define THIS_FILE "sock_bsd.c" /* * Address families conversion. * The values here are indexed based on pj_addr_family. */ -const pj_uint16_t PJ_AF_UNSPEC = AF_UNSPEC; -const pj_uint16_t PJ_AF_UNIX = AF_UNIX; -const pj_uint16_t PJ_AF_INET = AF_INET; -const pj_uint16_t PJ_AF_INET6 = AF_INET6; +const pj_uint16_t PJ_AF_UNSPEC = AF_UNSPEC; +const pj_uint16_t PJ_AF_UNIX = AF_UNIX; +const pj_uint16_t PJ_AF_INET = AF_INET; +const pj_uint16_t PJ_AF_INET6 = AF_INET6; #ifdef AF_PACKET -const pj_uint16_t PJ_AF_PACKET = AF_PACKET; +const pj_uint16_t PJ_AF_PACKET = AF_PACKET; #else -const pj_uint16_t PJ_AF_PACKET = 0xFFFF; +const pj_uint16_t PJ_AF_PACKET = 0xFFFF; #endif #ifdef AF_IRDA -const pj_uint16_t PJ_AF_IRDA = AF_IRDA; +const pj_uint16_t PJ_AF_IRDA = AF_IRDA; #else -const pj_uint16_t PJ_AF_IRDA = 0xFFFF; +const pj_uint16_t PJ_AF_IRDA = 0xFFFF; #endif /* @@ -52,83 +51,83 @@ const pj_uint16_t PJ_AF_IRDA = 0xFFFF; * The values here are indexed based on pj_sock_type */ const pj_uint16_t PJ_SOCK_STREAM= SOCK_STREAM; -const pj_uint16_t PJ_SOCK_DGRAM = SOCK_DGRAM; -const pj_uint16_t PJ_SOCK_RAW = SOCK_RAW; -const pj_uint16_t PJ_SOCK_RDM = SOCK_RDM; +const pj_uint16_t PJ_SOCK_DGRAM = SOCK_DGRAM; +const pj_uint16_t PJ_SOCK_RAW = SOCK_RAW; +const pj_uint16_t PJ_SOCK_RDM = SOCK_RDM; /* * Socket level values. */ -const pj_uint16_t PJ_SOL_SOCKET = SOL_SOCKET; +const pj_uint16_t PJ_SOL_SOCKET = SOL_SOCKET; #if (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64) || \ (defined (IPPROTO_IP)) -const pj_uint16_t PJ_SOL_IP = IPPROTO_IP; +const pj_uint16_t PJ_SOL_IP = IPPROTO_IP; #elif defined(SOL_IP) -const pj_uint16_t PJ_SOL_IP = SOL_IP; +const pj_uint16_t PJ_SOL_IP = SOL_IP; #else -const pj_uint16_t PJ_SOL_IP = 0; +const pj_uint16_t PJ_SOL_IP = 0; #endif /* SOL_IP */ #if defined(SOL_TCP) -const pj_uint16_t PJ_SOL_TCP = SOL_TCP; +const pj_uint16_t PJ_SOL_TCP = SOL_TCP; #elif defined(IPPROTO_TCP) -const pj_uint16_t PJ_SOL_TCP = IPPROTO_TCP; +const pj_uint16_t PJ_SOL_TCP = IPPROTO_TCP; #elif (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64) -const pj_uint16_t PJ_SOL_TCP = IPPROTO_TCP; +const pj_uint16_t PJ_SOL_TCP = IPPROTO_TCP; #else -const pj_uint16_t PJ_SOL_TCP = 6; +const pj_uint16_t PJ_SOL_TCP = 6; #endif /* SOL_TCP */ #ifdef SOL_UDP -const pj_uint16_t PJ_SOL_UDP = SOL_UDP; +const pj_uint16_t PJ_SOL_UDP = SOL_UDP; #elif defined(IPPROTO_UDP) -const pj_uint16_t PJ_SOL_UDP = IPPROTO_UDP; +const pj_uint16_t PJ_SOL_UDP = IPPROTO_UDP; #elif (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64) -const pj_uint16_t PJ_SOL_UDP = IPPROTO_UDP; +const pj_uint16_t PJ_SOL_UDP = IPPROTO_UDP; #else -const pj_uint16_t PJ_SOL_UDP = 17; +const pj_uint16_t PJ_SOL_UDP = 17; #endif /* SOL_UDP */ #ifdef SOL_IPV6 -const pj_uint16_t PJ_SOL_IPV6 = SOL_IPV6; +const pj_uint16_t PJ_SOL_IPV6 = SOL_IPV6; #elif (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64) # if defined(IPPROTO_IPV6) || (_WIN32_WINNT >= 0x0501) - const pj_uint16_t PJ_SOL_IPV6 = IPPROTO_IPV6; + const pj_uint16_t PJ_SOL_IPV6 = IPPROTO_IPV6; # else - const pj_uint16_t PJ_SOL_IPV6 = 41; + const pj_uint16_t PJ_SOL_IPV6 = 41; # endif #else -const pj_uint16_t PJ_SOL_IPV6 = 41; +const pj_uint16_t PJ_SOL_IPV6 = 41; #endif /* SOL_IPV6 */ /* IP_TOS */ #ifdef IP_TOS -const pj_uint16_t PJ_IP_TOS = IP_TOS; +const pj_uint16_t PJ_IP_TOS = IP_TOS; #else -const pj_uint16_t PJ_IP_TOS = 1; +const pj_uint16_t PJ_IP_TOS = 1; #endif /* TOS settings (declared in netinet/ip.h) */ #ifdef IPTOS_LOWDELAY -const pj_uint16_t PJ_IPTOS_LOWDELAY = IPTOS_LOWDELAY; +const pj_uint16_t PJ_IPTOS_LOWDELAY = IPTOS_LOWDELAY; #else -const pj_uint16_t PJ_IPTOS_LOWDELAY = 0x10; +const pj_uint16_t PJ_IPTOS_LOWDELAY = 0x10; #endif #ifdef IPTOS_THROUGHPUT -const pj_uint16_t PJ_IPTOS_THROUGHPUT = IPTOS_THROUGHPUT; +const pj_uint16_t PJ_IPTOS_THROUGHPUT = IPTOS_THROUGHPUT; #else -const pj_uint16_t PJ_IPTOS_THROUGHPUT = 0x08; +const pj_uint16_t PJ_IPTOS_THROUGHPUT = 0x08; #endif #ifdef IPTOS_RELIABILITY -const pj_uint16_t PJ_IPTOS_RELIABILITY = IPTOS_RELIABILITY; +const pj_uint16_t PJ_IPTOS_RELIABILITY = IPTOS_RELIABILITY; #else -const pj_uint16_t PJ_IPTOS_RELIABILITY = 0x04; +const pj_uint16_t PJ_IPTOS_RELIABILITY = 0x04; #endif #ifdef IPTOS_MINCOST -const pj_uint16_t PJ_IPTOS_MINCOST = IPTOS_MINCOST; +const pj_uint16_t PJ_IPTOS_MINCOST = IPTOS_MINCOST; #else -const pj_uint16_t PJ_IPTOS_MINCOST = 0x02; +const pj_uint16_t PJ_IPTOS_MINCOST = 0x02; #endif @@ -174,9 +173,9 @@ const pj_uint16_t PJ_IP_DROP_MEMBERSHIP = 0xFFFF; #endif /* recv() and send() flags */ -const int PJ_MSG_OOB = MSG_OOB; -const int PJ_MSG_PEEK = MSG_PEEK; -const int PJ_MSG_DONTROUTE = MSG_DONTROUTE; +const int PJ_MSG_OOB = MSG_OOB; +const int PJ_MSG_PEEK = MSG_PEEK; +const int PJ_MSG_DONTROUTE = MSG_DONTROUTE; #if 0 @@ -184,7 +183,7 @@ static void CHECK_ADDR_LEN(const pj_sockaddr *addr, int len) { pj_sockaddr *a = (pj_sockaddr*)addr; pj_assert((a->addr.sa_family==PJ_AF_INET && len==sizeof(pj_sockaddr_in)) || - (a->addr.sa_family==PJ_AF_INET6 && len==sizeof(pj_sockaddr_in6))); + (a->addr.sa_family==PJ_AF_INET6 && len==sizeof(pj_sockaddr_in6))); } #else @@ -255,12 +254,12 @@ PJ_DEF(int) pj_inet_aton(const pj_str_t *cp, pj_in_addr *inp) inp->s_addr = PJ_INADDR_NONE; /* Caution: - * this function might be called with cp->slen >= 16 + * this function might be called with cp->slen >= 16 * (i.e. when called with hostname to check if it's an IP addr). */ PJ_ASSERT_RETURN(cp && cp->slen && inp, 0); if (cp->slen >= PJ_INET_ADDRSTRLEN) { - return 0; + return 0; } pj_memcpy(tempaddr, cp->ptr, cp->slen); @@ -288,15 +287,15 @@ PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) * compatible with pj_inet_aton() */ if (af==PJ_AF_INET) { - ((pj_in_addr*)dst)->s_addr = PJ_INADDR_NONE; + ((pj_in_addr*)dst)->s_addr = PJ_INADDR_NONE; } /* Caution: - * this function might be called with cp->slen >= 46 + * this function might be called with cp->slen >= 46 * (i.e. when called with hostname to check if it's an IP addr). */ if (src->slen >= PJ_INET6_ADDRSTRLEN) { - return PJ_ENAMETOOLONG; + return PJ_ENAMETOOLONG; } pj_memcpy(tempaddr, src->ptr, src->slen); @@ -307,11 +306,11 @@ PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) * Implementation using inet_pton() */ if (inet_pton(af, tempaddr, dst) != 1) { - pj_status_t status = pj_get_netos_error(); - if (status == PJ_SUCCESS) - status = PJ_EUNKNOWN; + pj_status_t status = pj_get_netos_error(); + if (status == PJ_SUCCESS) + status = PJ_EUNKNOWN; - return status; + return status; } return PJ_SUCCESS; @@ -322,37 +321,37 @@ PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) * Should also work on Unicode systems. */ { - PJ_DECL_UNICODE_TEMP_BUF(wtempaddr,PJ_INET6_ADDRSTRLEN) - pj_sockaddr sock_addr; - int addr_len = sizeof(sock_addr); - int rc; - - sock_addr.addr.sa_family = (pj_uint16_t)af; - rc = WSAStringToAddress( - PJ_STRING_TO_NATIVE(tempaddr,wtempaddr,sizeof(wtempaddr)), - af, NULL, (LPSOCKADDR)&sock_addr, &addr_len); - if (rc != 0) { - /* If you get rc 130022 Invalid argument (WSAEINVAL) with IPv6, - * check that you have IPv6 enabled (install it in the network - * adapter). - */ - pj_status_t status = pj_get_netos_error(); - if (status == PJ_SUCCESS) - status = PJ_EUNKNOWN; - - return status; - } - - if (sock_addr.addr.sa_family == PJ_AF_INET) { - pj_memcpy(dst, &sock_addr.ipv4.sin_addr, 4); - return PJ_SUCCESS; - } else if (sock_addr.addr.sa_family == PJ_AF_INET6) { - pj_memcpy(dst, &sock_addr.ipv6.sin6_addr, 16); - return PJ_SUCCESS; - } else { - pj_assert(!"Shouldn't happen"); - return PJ_EBUG; - } + PJ_DECL_UNICODE_TEMP_BUF(wtempaddr,PJ_INET6_ADDRSTRLEN) + pj_sockaddr sock_addr; + int addr_len = sizeof(sock_addr); + int rc; + + sock_addr.addr.sa_family = (pj_uint16_t)af; + rc = WSAStringToAddress( + PJ_STRING_TO_NATIVE(tempaddr,wtempaddr,sizeof(wtempaddr)), + af, NULL, (LPSOCKADDR)&sock_addr, &addr_len); + if (rc != 0) { + /* If you get rc 130022 Invalid argument (WSAEINVAL) with IPv6, + * check that you have IPv6 enabled (install it in the network + * adapter). + */ + pj_status_t status = pj_get_netos_error(); + if (status == PJ_SUCCESS) + status = PJ_EUNKNOWN; + + return status; + } + + if (sock_addr.addr.sa_family == PJ_AF_INET) { + pj_memcpy(dst, &sock_addr.ipv4.sin_addr, 4); + return PJ_SUCCESS; + } else if (sock_addr.addr.sa_family == PJ_AF_INET6) { + pj_memcpy(dst, &sock_addr.ipv6.sin6_addr, 16); + return PJ_SUCCESS; + } else { + pj_assert(!"Shouldn't happen"); + return PJ_EBUG; + } } #elif !defined(PJ_HAS_IPV6) || PJ_HAS_IPV6==0 /* IPv6 support is disabled, just return error without raising assertion */ @@ -367,7 +366,7 @@ PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) * Convert IPv4/IPv6 address to text. */ PJ_DEF(pj_status_t) pj_inet_ntop(int af, const void *src, - char *dst, int size) + char *dst, int size) { PJ_ASSERT_RETURN(src && dst && size, PJ_EINVAL); @@ -381,11 +380,11 @@ PJ_DEF(pj_status_t) pj_inet_ntop(int af, const void *src, * Implementation using inet_ntop() */ if (inet_ntop(af, src, dst, size) == NULL) { - pj_status_t status = pj_get_netos_error(); - if (status == PJ_SUCCESS) - status = PJ_EUNKNOWN; + pj_status_t status = pj_get_netos_error(); + if (status == PJ_SUCCESS) + status = PJ_EUNKNOWN; - return status; + return status; } return PJ_SUCCESS; @@ -396,50 +395,50 @@ PJ_DEF(pj_status_t) pj_inet_ntop(int af, const void *src, * Should also work on Unicode systems. */ { - PJ_DECL_UNICODE_TEMP_BUF(wtempaddr,PJ_INET6_ADDRSTRLEN) - pj_sockaddr sock_addr; - DWORD addr_len, addr_str_len; - int rc; - - pj_bzero(&sock_addr, sizeof(sock_addr)); - sock_addr.addr.sa_family = (pj_uint16_t)af; - if (af == PJ_AF_INET) { - if (size < PJ_INET_ADDRSTRLEN) - return PJ_ETOOSMALL; - pj_memcpy(&sock_addr.ipv4.sin_addr, src, 4); - addr_len = sizeof(pj_sockaddr_in); - addr_str_len = PJ_INET_ADDRSTRLEN; - } else if (af == PJ_AF_INET6) { - if (size < PJ_INET6_ADDRSTRLEN) - return PJ_ETOOSMALL; - pj_memcpy(&sock_addr.ipv6.sin6_addr, src, 16); - addr_len = sizeof(pj_sockaddr_in6); - addr_str_len = PJ_INET6_ADDRSTRLEN; - } else { - pj_assert(!"Unsupported address family"); - return PJ_EAFNOTSUP; - } + PJ_DECL_UNICODE_TEMP_BUF(wtempaddr,PJ_INET6_ADDRSTRLEN) + pj_sockaddr sock_addr; + DWORD addr_len, addr_str_len; + int rc; + + pj_bzero(&sock_addr, sizeof(sock_addr)); + sock_addr.addr.sa_family = (pj_uint16_t)af; + if (af == PJ_AF_INET) { + if (size < PJ_INET_ADDRSTRLEN) + return PJ_ETOOSMALL; + pj_memcpy(&sock_addr.ipv4.sin_addr, src, 4); + addr_len = sizeof(pj_sockaddr_in); + addr_str_len = PJ_INET_ADDRSTRLEN; + } else if (af == PJ_AF_INET6) { + if (size < PJ_INET6_ADDRSTRLEN) + return PJ_ETOOSMALL; + pj_memcpy(&sock_addr.ipv6.sin6_addr, src, 16); + addr_len = sizeof(pj_sockaddr_in6); + addr_str_len = PJ_INET6_ADDRSTRLEN; + } else { + pj_assert(!"Unsupported address family"); + return PJ_EAFNOTSUP; + } #if PJ_NATIVE_STRING_IS_UNICODE - rc = WSAAddressToString((LPSOCKADDR)&sock_addr, addr_len, - NULL, wtempaddr, &addr_str_len); - if (rc == 0) { - pj_unicode_to_ansi(wtempaddr, wcslen(wtempaddr), dst, size); - } + rc = WSAAddressToString((LPSOCKADDR)&sock_addr, addr_len, + NULL, wtempaddr, &addr_str_len); + if (rc == 0) { + pj_unicode_to_ansi(wtempaddr, wcslen(wtempaddr), dst, size); + } #else - rc = WSAAddressToString((LPSOCKADDR)&sock_addr, addr_len, - NULL, dst, &addr_str_len); + rc = WSAAddressToString((LPSOCKADDR)&sock_addr, addr_len, + NULL, dst, &addr_str_len); #endif - if (rc != 0) { - pj_status_t status = pj_get_netos_error(); - if (status == PJ_SUCCESS) - status = PJ_EUNKNOWN; + if (rc != 0) { + pj_status_t status = pj_get_netos_error(); + if (status == PJ_SUCCESS) + status = PJ_EUNKNOWN; - return status; - } + return status; + } - return PJ_SUCCESS; + return PJ_SUCCESS; } #elif !defined(PJ_HAS_IPV6) || PJ_HAS_IPV6==0 @@ -462,13 +461,13 @@ PJ_DEF(const pj_str_t*) pj_gethostname(void) PJ_CHECK_STACK(); if (hostname.ptr == NULL) { - hostname.ptr = buf; - if (gethostname(buf, sizeof(buf)) != 0) { - hostname.ptr[0] = '\0'; - hostname.slen = 0; - } else { + hostname.ptr = buf; + if (gethostname(buf, sizeof(buf)) != 0) { + hostname.ptr[0] = '\0'; + hostname.slen = 0; + } else { hostname.slen = strlen(buf); - } + } } return &hostname; } @@ -478,9 +477,9 @@ PJ_DEF(const pj_str_t*) pj_gethostname(void) * Create new socket/endpoint for communication and returns a descriptor. */ PJ_DEF(pj_status_t) pj_sock_socket(int af, - int type, - int proto, - pj_sock_t *sock) + int type, + int proto, + pj_sock_t *sock) { PJ_CHECK_STACK(); @@ -492,7 +491,7 @@ PJ_DEF(pj_status_t) pj_sock_socket(int af, *sock = WSASocket(af, type, proto, NULL, 0, WSA_FLAG_OVERLAPPED); if (*sock == PJ_INVALID_SOCKET) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); #if PJ_SOCK_DISABLE_WSAECONNRESET && \ (!defined(PJ_WIN32_WINCE) || PJ_WIN32_WINCE==0) @@ -505,18 +504,18 @@ PJ_DEF(pj_status_t) pj_sock_socket(int af, * See https://github.com/pjsip/pjproject/issues/1197 */ if (type==PJ_SOCK_DGRAM) { - DWORD dwBytesReturned = 0; - BOOL bNewBehavior = FALSE; - DWORD rc; - - rc = WSAIoctl(*sock, SIO_UDP_CONNRESET, - &bNewBehavior, sizeof(bNewBehavior), - NULL, 0, &dwBytesReturned, - NULL, NULL); - - if (rc==SOCKET_ERROR) { - // Ignored.. - } + DWORD dwBytesReturned = 0; + BOOL bNewBehavior = FALSE; + DWORD rc; + + rc = WSAIoctl(*sock, SIO_UDP_CONNRESET, + &bNewBehavior, sizeof(bNewBehavior), + NULL, 0, &dwBytesReturned, + NULL, NULL); + + if (rc==SOCKET_ERROR) { + // Ignored.. + } } #endif @@ -528,9 +527,9 @@ PJ_DEF(pj_status_t) pj_sock_socket(int af, * Create new socket/endpoint for communication and returns a descriptor. */ PJ_DEF(pj_status_t) pj_sock_socket(int af, - int type, - int proto, - pj_sock_t *sock) + int type, + int proto, + pj_sock_t *sock) { PJ_CHECK_STACK(); @@ -542,27 +541,27 @@ PJ_DEF(pj_status_t) pj_sock_socket(int af, *sock = socket(af, type, proto); if (*sock == PJ_INVALID_SOCKET) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else { - pj_int32_t val = 1; - if (type == pj_SOCK_STREAM()) { - pj_sock_setsockopt(*sock, pj_SOL_SOCKET(), pj_SO_NOSIGPIPE(), - &val, sizeof(val)); - } + pj_int32_t val = 1; + if (type == pj_SOCK_STREAM()) { + pj_sock_setsockopt(*sock, pj_SOL_SOCKET(), pj_SO_NOSIGPIPE(), + &val, sizeof(val)); + } #if defined(PJ_SOCK_HAS_IPV6_V6ONLY) && PJ_SOCK_HAS_IPV6_V6ONLY != 0 - if (af == PJ_AF_INET6) { - pj_sock_setsockopt(*sock, PJ_SOL_IPV6, IPV6_V6ONLY, - &val, sizeof(val)); - } + if (af == PJ_AF_INET6) { + pj_sock_setsockopt(*sock, PJ_SOL_IPV6, IPV6_V6ONLY, + &val, sizeof(val)); + } #endif #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 - if (type == pj_SOCK_DGRAM()) { - pj_sock_setsockopt(*sock, pj_SOL_SOCKET(), SO_NOSIGPIPE, - &val, sizeof(val)); - } + if (type == pj_SOCK_DGRAM()) { + pj_sock_setsockopt(*sock, pj_SOL_SOCKET(), SO_NOSIGPIPE, + &val, sizeof(val)); + } #endif - return PJ_SUCCESS; + return PJ_SUCCESS; } } #endif @@ -571,8 +570,8 @@ PJ_DEF(pj_status_t) pj_sock_socket(int af, * Bind socket. */ PJ_DEF(pj_status_t) pj_sock_bind( pj_sock_t sock, - const pj_sockaddr_t *addr, - int len) + const pj_sockaddr_t *addr, + int len) { PJ_CHECK_STACK(); @@ -581,9 +580,9 @@ PJ_DEF(pj_status_t) pj_sock_bind( pj_sock_t sock, CHECK_ADDR_LEN(addr, len); if (bind(sock, (struct sockaddr*)addr, len) != 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else - return PJ_SUCCESS; + return PJ_SUCCESS; } @@ -591,8 +590,8 @@ PJ_DEF(pj_status_t) pj_sock_bind( pj_sock_t sock, * Bind socket. */ PJ_DEF(pj_status_t) pj_sock_bind_in( pj_sock_t sock, - pj_uint32_t addr32, - pj_uint16_t port) + pj_uint32_t addr32, + pj_uint16_t port) { pj_sockaddr_in addr; @@ -625,24 +624,24 @@ PJ_DEF(pj_status_t) pj_sock_close(pj_sock_t sock) #endif if (rc != 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else - return PJ_SUCCESS; + return PJ_SUCCESS; } /* * Get remote's name. */ PJ_DEF(pj_status_t) pj_sock_getpeername( pj_sock_t sock, - pj_sockaddr_t *addr, - int *namelen) + pj_sockaddr_t *addr, + int *namelen) { PJ_CHECK_STACK(); if (getpeername(sock, (struct sockaddr*)addr, (socklen_t*)namelen) != 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else { - PJ_SOCKADDR_RESET_LEN(addr); - return PJ_SUCCESS; + PJ_SOCKADDR_RESET_LEN(addr); + return PJ_SUCCESS; } } @@ -650,15 +649,15 @@ PJ_DEF(pj_status_t) pj_sock_getpeername( pj_sock_t sock, * Get socket name. */ PJ_DEF(pj_status_t) pj_sock_getsockname( pj_sock_t sock, - pj_sockaddr_t *addr, - int *namelen) + pj_sockaddr_t *addr, + int *namelen) { PJ_CHECK_STACK(); if (getsockname(sock, (struct sockaddr*)addr, (socklen_t*)namelen) != 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else { - PJ_SOCKADDR_RESET_LEN(addr); - return PJ_SUCCESS; + PJ_SOCKADDR_RESET_LEN(addr); + return PJ_SUCCESS; } } @@ -666,9 +665,9 @@ PJ_DEF(pj_status_t) pj_sock_getsockname( pj_sock_t sock, * Send data */ PJ_DEF(pj_status_t) pj_sock_send(pj_sock_t sock, - const void *buf, - pj_ssize_t *len, - unsigned flags) + const void *buf, + pj_ssize_t *len, + unsigned flags) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(len, PJ_EINVAL); @@ -681,9 +680,9 @@ PJ_DEF(pj_status_t) pj_sock_send(pj_sock_t sock, *len = send(sock, (const char*)buf, (int)(*len), flags); if (*len < 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else - return PJ_SUCCESS; + return PJ_SUCCESS; } @@ -691,11 +690,11 @@ PJ_DEF(pj_status_t) pj_sock_send(pj_sock_t sock, * Send data. */ PJ_DEF(pj_status_t) pj_sock_sendto(pj_sock_t sock, - const void *buf, - pj_ssize_t *len, - unsigned flags, - const pj_sockaddr_t *to, - int tolen) + const void *buf, + pj_ssize_t *len, + unsigned flags, + const pj_sockaddr_t *to, + int tolen) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(len, PJ_EINVAL); @@ -703,21 +702,21 @@ PJ_DEF(pj_status_t) pj_sock_sendto(pj_sock_t sock, CHECK_ADDR_LEN(to, tolen); *len = sendto(sock, (const char*)buf, (int)(*len), flags, - (const struct sockaddr*)to, tolen); + (const struct sockaddr*)to, tolen); if (*len < 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else - return PJ_SUCCESS; + return PJ_SUCCESS; } /* * Receive data. */ PJ_DEF(pj_status_t) pj_sock_recv(pj_sock_t sock, - void *buf, - pj_ssize_t *len, - unsigned flags) + void *buf, + pj_ssize_t *len, + unsigned flags) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(buf && len, PJ_EINVAL); @@ -725,34 +724,34 @@ PJ_DEF(pj_status_t) pj_sock_recv(pj_sock_t sock, *len = recv(sock, (char*)buf, (int)(*len), flags); if (*len < 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else - return PJ_SUCCESS; + return PJ_SUCCESS; } /* * Receive data. */ PJ_DEF(pj_status_t) pj_sock_recvfrom(pj_sock_t sock, - void *buf, - pj_ssize_t *len, - unsigned flags, - pj_sockaddr_t *from, - int *fromlen) + void *buf, + pj_ssize_t *len, + unsigned flags, + pj_sockaddr_t *from, + int *fromlen) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(buf && len, PJ_EINVAL); *len = recvfrom(sock, (char*)buf, (int)(*len), flags, - (struct sockaddr*)from, (socklen_t*)fromlen); + (struct sockaddr*)from, (socklen_t*)fromlen); if (*len < 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else { if (from) { PJ_SOCKADDR_RESET_LEN(from); } - return PJ_SUCCESS; + return PJ_SUCCESS; } } @@ -760,28 +759,28 @@ PJ_DEF(pj_status_t) pj_sock_recvfrom(pj_sock_t sock, * Get socket option. */ PJ_DEF(pj_status_t) pj_sock_getsockopt( pj_sock_t sock, - pj_uint16_t level, - pj_uint16_t optname, - void *optval, - int *optlen) + pj_uint16_t level, + pj_uint16_t optname, + void *optval, + int *optlen) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(optval && optlen, PJ_EINVAL); if (getsockopt(sock, level, optname, (char*)optval, (socklen_t*)optlen)!=0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else - return PJ_SUCCESS; + return PJ_SUCCESS; } /* * Set socket option. */ PJ_DEF(pj_status_t) pj_sock_setsockopt( pj_sock_t sock, - pj_uint16_t level, - pj_uint16_t optname, - const void *optval, - int optlen) + pj_uint16_t level, + pj_uint16_t optname, + const void *optval, + int optlen) { int status; PJ_CHECK_STACK(); @@ -789,24 +788,24 @@ PJ_DEF(pj_status_t) pj_sock_setsockopt( pj_sock_t sock, #if (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_SUNOS) && PJ_SUNOS) /* Some opt may still need int value (e.g:SO_EXCLUSIVEADDRUSE in win32). */ status = setsockopt(sock, - level, - ((optname&0xff00)==0xff00)?(int)optname|0xffff0000:optname, - (const char*)optval, optlen); + level, + ((optname&0xff00)==0xff00)?(int)optname|0xffff0000:optname, + (const char*)optval, optlen); #else status = setsockopt(sock, level, optname, (const char*)optval, optlen); #endif if (status != 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else - return PJ_SUCCESS; + return PJ_SUCCESS; } /* * Set socket option. */ PJ_DEF(pj_status_t) pj_sock_setsockopt_params( pj_sock_t sockfd, - const pj_sockopt_params *params) + const pj_sockopt_params *params) { unsigned int i = 0; pj_status_t retval = PJ_SUCCESS; @@ -814,17 +813,17 @@ PJ_DEF(pj_status_t) pj_sock_setsockopt_params( pj_sock_t sockfd, PJ_ASSERT_RETURN(params, PJ_EINVAL); for (;icnt && ioptions[i].level, - (pj_uint16_t)params->options[i].optname, - params->options[i].optval, - params->options[i].optlen); - if (status != PJ_SUCCESS) { - retval = status; - PJ_PERROR(4,(THIS_FILE, status, - "Warning: error applying sock opt %d", - params->options[i].optname)); - } + pj_status_t status = pj_sock_setsockopt(sockfd, + (pj_uint16_t)params->options[i].level, + (pj_uint16_t)params->options[i].optname, + params->options[i].optval, + params->options[i].optlen); + if (status != PJ_SUCCESS) { + retval = status; + PJ_PERROR(4,(THIS_FILE, status, + "Warning: error applying sock opt %d", + params->options[i].optname)); + } } return retval; @@ -834,14 +833,14 @@ PJ_DEF(pj_status_t) pj_sock_setsockopt_params( pj_sock_t sockfd, * Connect socket. */ PJ_DEF(pj_status_t) pj_sock_connect( pj_sock_t sock, - const pj_sockaddr_t *addr, - int namelen) + const pj_sockaddr_t *addr, + int namelen) { PJ_CHECK_STACK(); if (connect(sock, (struct sockaddr*)addr, namelen) != 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else - return PJ_SUCCESS; + return PJ_SUCCESS; } @@ -850,59 +849,59 @@ PJ_DEF(pj_status_t) pj_sock_connect( pj_sock_t sock, */ #if PJ_HAS_TCP PJ_DEF(pj_status_t) pj_sock_shutdown( pj_sock_t sock, - int how) + int how) { PJ_CHECK_STACK(); if (shutdown(sock, how) != 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else - return PJ_SUCCESS; + return PJ_SUCCESS; } /* * Start listening to incoming connections. */ PJ_DEF(pj_status_t) pj_sock_listen( pj_sock_t sock, - int backlog) + int backlog) { PJ_CHECK_STACK(); if (listen(sock, backlog) != 0) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else - return PJ_SUCCESS; + return PJ_SUCCESS; } /* * Accept incoming connections */ PJ_DEF(pj_status_t) pj_sock_accept( pj_sock_t serverfd, - pj_sock_t *newsock, - pj_sockaddr_t *addr, - int *addrlen) + pj_sock_t *newsock, + pj_sockaddr_t *addr, + int *addrlen) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(newsock != NULL, PJ_EINVAL); #if defined(PJ_SOCKADDR_HAS_LEN) && PJ_SOCKADDR_HAS_LEN!=0 if (addr) { - PJ_SOCKADDR_SET_LEN(addr, *addrlen); + PJ_SOCKADDR_SET_LEN(addr, *addrlen); } #endif *newsock = accept(serverfd, (struct sockaddr*)addr, (socklen_t*)addrlen); if (*newsock==PJ_INVALID_SOCKET) - return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); else { - + #if defined(PJ_SOCKADDR_HAS_LEN) && PJ_SOCKADDR_HAS_LEN!=0 - if (addr) { - PJ_SOCKADDR_RESET_LEN(addr); - } + if (addr) { + PJ_SOCKADDR_RESET_LEN(addr); + } #endif - - return PJ_SUCCESS; + + return PJ_SUCCESS; } } -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ diff --git a/pjlib/src/pj/sock_common.c b/pjlib/src/pj/sock_common.c index 78d5968189..fd2536fd67 100644 --- a/pjlib/src/pj/sock_common.c +++ b/pjlib/src/pj/sock_common.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,7 +31,7 @@ /* Enable some tracing */ #include #define THIS_FILE "sock_common.c" - #define TRACE_(arg) PJ_LOG(4,arg) + #define TRACE_(arg) PJ_LOG(4,arg) #else #define TRACE_(arg) #endif @@ -62,7 +61,7 @@ PJ_DEF(pj_in_addr) pj_inet_addr2(const char *cp) * Get text representation. */ PJ_DEF(char*) pj_inet_ntop2( int af, const void *src, - char *dst, int size) + char *dst, int size) { pj_status_t status; @@ -74,12 +73,12 @@ PJ_DEF(char*) pj_inet_ntop2( int af, const void *src, * Print socket address. */ PJ_DEF(char*) pj_sockaddr_print( const pj_sockaddr_t *addr, - char *buf, int size, - unsigned flags) + char *buf, int size, + unsigned flags) { enum { - WITH_PORT = 1, - WITH_BRACKETS = 2 + WITH_PORT = 1, + WITH_BRACKETS = 2 }; char txt[PJ_INET6_ADDRSTRLEN]; @@ -89,25 +88,25 @@ PJ_DEF(char*) pj_sockaddr_print( const pj_sockaddr_t *addr, pj_status_t status; status = pj_inet_ntop(h->sa_family, pj_sockaddr_get_addr(addr), - txt, sizeof(txt)); + txt, sizeof(txt)); if (status != PJ_SUCCESS) - return ""; + return ""; if (h->sa_family != PJ_AF_INET6 || (flags & WITH_BRACKETS)==0) { - bquote = ""; equote = ""; + bquote = ""; equote = ""; } else { - bquote = "["; equote = "]"; + bquote = "["; equote = "]"; } if (flags & WITH_PORT) { - pj_ansi_snprintf(port, sizeof(port), ":%d", - pj_sockaddr_get_port(addr)); + pj_ansi_snprintf(port, sizeof(port), ":%d", + pj_sockaddr_get_port(addr)); } else { - port[0] = '\0'; + port[0] = '\0'; } pj_ansi_snprintf(buf, size, "%s%s%s%s", - bquote, txt, equote, port); + bquote, txt, equote, port); return buf; } @@ -120,7 +119,7 @@ PJ_DEF(char*) pj_sockaddr_print( const pj_sockaddr_t *addr, * address. */ PJ_DEF(pj_status_t) pj_sockaddr_in_set_str_addr( pj_sockaddr_in *addr, - const pj_str_t *str_addr) + const pj_str_t *str_addr) { PJ_CHECK_STACK(); @@ -132,23 +131,23 @@ PJ_DEF(pj_status_t) pj_sockaddr_in_set_str_addr( pj_sockaddr_in *addr, pj_bzero(addr->sin_zero_pad, sizeof(addr->sin_zero_pad)); if (str_addr && str_addr->slen) { - addr->sin_addr = pj_inet_addr(str_addr); - if (addr->sin_addr.s_addr == PJ_INADDR_NONE) { - pj_addrinfo ai; - unsigned count = 1; - pj_status_t status; - - status = pj_getaddrinfo(pj_AF_INET(), str_addr, &count, &ai); - if (status==PJ_SUCCESS) { - pj_memcpy(&addr->sin_addr, &ai.ai_addr.ipv4.sin_addr, - sizeof(addr->sin_addr)); - } else { - return status; - } - } + addr->sin_addr = pj_inet_addr(str_addr); + if (addr->sin_addr.s_addr == PJ_INADDR_NONE) { + pj_addrinfo ai; + unsigned count = 1; + pj_status_t status; + + status = pj_getaddrinfo(pj_AF_INET(), str_addr, &count, &ai); + if (status==PJ_SUCCESS) { + pj_memcpy(&addr->sin_addr, &ai.ai_addr.ipv4.sin_addr, + sizeof(addr->sin_addr)); + } else { + return status; + } + } } else { - addr->sin_addr.s_addr = 0; + addr->sin_addr.s_addr = 0; } return PJ_SUCCESS; @@ -156,13 +155,13 @@ PJ_DEF(pj_status_t) pj_sockaddr_in_set_str_addr( pj_sockaddr_in *addr, /* Set address from a name */ PJ_DEF(pj_status_t) pj_sockaddr_set_str_addr(int af, - pj_sockaddr *addr, - const pj_str_t *str_addr) + pj_sockaddr *addr, + const pj_str_t *str_addr) { pj_status_t status; if (af == PJ_AF_INET) { - return pj_sockaddr_in_set_str_addr(&addr->ipv4, str_addr); + return pj_sockaddr_in_set_str_addr(&addr->ipv4, str_addr); } PJ_ASSERT_RETURN(af==PJ_AF_INET6, PJ_EAFNOTSUP); @@ -174,23 +173,23 @@ PJ_DEF(pj_status_t) pj_sockaddr_set_str_addr(int af, if (str_addr && str_addr->slen) { #if defined(PJ_SOCKADDR_USE_GETADDRINFO) && PJ_SOCKADDR_USE_GETADDRINFO!=0 - if (1) { + if (1) { #else - status = pj_inet_pton(PJ_AF_INET6, str_addr, &addr->ipv6.sin6_addr); - if (status != PJ_SUCCESS) { + status = pj_inet_pton(PJ_AF_INET6, str_addr, &addr->ipv6.sin6_addr); + if (status != PJ_SUCCESS) { #endif - pj_addrinfo ai; - unsigned count = 1; - - status = pj_getaddrinfo(PJ_AF_INET6, str_addr, &count, &ai); - if (status==PJ_SUCCESS) { - pj_memcpy(&addr->ipv6.sin6_addr, &ai.ai_addr.ipv6.sin6_addr, - sizeof(addr->ipv6.sin6_addr)); - addr->ipv6.sin6_scope_id = ai.ai_addr.ipv6.sin6_scope_id; - } - } + pj_addrinfo ai; + unsigned count = 1; + + status = pj_getaddrinfo(PJ_AF_INET6, str_addr, &count, &ai); + if (status==PJ_SUCCESS) { + pj_memcpy(&addr->ipv6.sin6_addr, &ai.ai_addr.ipv6.sin6_addr, + sizeof(addr->ipv6.sin6_addr)); + addr->ipv6.sin6_scope_id = ai.ai_addr.ipv6.sin6_scope_id; + } + } } else { - status = PJ_SUCCESS; + status = PJ_SUCCESS; } return status; @@ -203,8 +202,8 @@ PJ_DEF(pj_status_t) pj_sockaddr_set_str_addr(int af, * resolve the host into the IP address. */ PJ_DEF(pj_status_t) pj_sockaddr_in_init( pj_sockaddr_in *addr, - const pj_str_t *str_addr, - pj_uint16_t port) + const pj_str_t *str_addr, + pj_uint16_t port) { PJ_ASSERT_RETURN(addr, (addr->sin_addr.s_addr=PJ_INADDR_NONE, PJ_EINVAL)); @@ -219,14 +218,14 @@ PJ_DEF(pj_status_t) pj_sockaddr_in_init( pj_sockaddr_in *addr, * Initialize IP socket address based on the address and port info. */ PJ_DEF(pj_status_t) pj_sockaddr_init(int af, - pj_sockaddr *addr, - const pj_str_t *cp, - pj_uint16_t port) + pj_sockaddr *addr, + const pj_str_t *cp, + pj_uint16_t port) { pj_status_t status; if (af == PJ_AF_INET) { - return pj_sockaddr_in_init(&addr->ipv4, cp, port); + return pj_sockaddr_in_init(&addr->ipv4, cp, port); } /* IPv6 specific */ @@ -237,7 +236,7 @@ PJ_DEF(pj_status_t) pj_sockaddr_init(int af, status = pj_sockaddr_set_str_addr(af, addr, cp); if (status != PJ_SUCCESS) - return status; + return status; addr->ipv6.sin6_port = pj_htons(port); return PJ_SUCCESS; @@ -247,7 +246,7 @@ PJ_DEF(pj_status_t) pj_sockaddr_init(int af, * Compare two socket addresses. */ PJ_DEF(int) pj_sockaddr_cmp( const pj_sockaddr_t *addr1, - const pj_sockaddr_t *addr2) + const pj_sockaddr_t *addr2) { const pj_sockaddr *a1 = (const pj_sockaddr*) addr1; const pj_sockaddr *a2 = (const pj_sockaddr*) addr2; @@ -256,28 +255,28 @@ PJ_DEF(int) pj_sockaddr_cmp( const pj_sockaddr_t *addr1, /* Compare address family */ if (a1->addr.sa_family < a2->addr.sa_family) - return -1; + return -1; else if (a1->addr.sa_family > a2->addr.sa_family) - return 1; + return 1; /* Compare addresses */ result = pj_memcmp(pj_sockaddr_get_addr(a1), - pj_sockaddr_get_addr(a2), - pj_sockaddr_get_addr_len(a1)); + pj_sockaddr_get_addr(a2), + pj_sockaddr_get_addr_len(a1)); if (result != 0) - return result; + return result; /* Compare port number */ port1 = pj_sockaddr_get_port(a1); port2 = pj_sockaddr_get_port(a2); if (port1 < port2) - return -1; + return -1; else if (port1 > port2) - return 1; + return 1; /* TODO: - * Do we need to compare flow label and scope id in IPv6? + * Do we need to compare flow label and scope id in IPv6? */ /* Looks equal */ @@ -312,12 +311,12 @@ PJ_DEF(void*) pj_sockaddr_get_addr(const pj_sockaddr_t *addr) const pj_sockaddr *a = (const pj_sockaddr*)addr; PJ_ASSERT_RETURN(a->addr.sa_family == PJ_AF_INET || - a->addr.sa_family == PJ_AF_INET6, NULL); + a->addr.sa_family == PJ_AF_INET6, NULL); if (a->addr.sa_family == PJ_AF_INET6) - return (void*) &a->ipv6.sin6_addr; + return (void*) &a->ipv6.sin6_addr; else - return (void*) &a->ipv4.sin_addr; + return (void*) &a->ipv4.sin_addr; } /* @@ -333,11 +332,11 @@ PJ_DEF(pj_bool_t) pj_sockaddr_has_addr(const pj_sockaddr_t *addr) * * The reason is because application may need to distinguish * these three conditions with sockaddr: - * a) sockaddr is not initialized. This is by convention - * indicated by sa_family==0. - * b) sockaddr is initialized with zero address. This is - * indicated with the address field having zero address. - * c) sockaddr is initialized with valid address/port. + * a) sockaddr is not initialized. This is by convention + * indicated by sa_family==0. + * b) sockaddr is initialized with zero address. This is + * indicated with the address field having zero address. + * c) sockaddr is initialized with valid address/port. * * If we enable this assertion, then application will loose * the capability to specify condition a), since it will be @@ -345,17 +344,17 @@ PJ_DEF(pj_bool_t) pj_sockaddr_has_addr(const pj_sockaddr_t *addr) * This may break some parts of upper layer libraries. */ //PJ_ASSERT_RETURN(a->addr.sa_family == PJ_AF_INET || - // a->addr.sa_family == PJ_AF_INET6, PJ_FALSE); + // a->addr.sa_family == PJ_AF_INET6, PJ_FALSE); if (a->addr.sa_family!=PJ_AF_INET && a->addr.sa_family!=PJ_AF_INET6) { - return PJ_FALSE; + return PJ_FALSE; } else if (a->addr.sa_family == PJ_AF_INET6) { - pj_uint8_t zero[24]; - pj_bzero(zero, sizeof(zero)); - return pj_memcmp(a->ipv6.sin6_addr.s6_addr, zero, - sizeof(pj_in6_addr)) != 0; + pj_uint8_t zero[24]; + pj_bzero(zero, sizeof(zero)); + return pj_memcmp(a->ipv6.sin6_addr.s6_addr, zero, + sizeof(pj_in6_addr)) != 0; } else - return a->ipv4.sin_addr.s_addr != PJ_INADDR_ANY; + return a->ipv4.sin_addr.s_addr != PJ_INADDR_ANY; } /* @@ -366,10 +365,10 @@ PJ_DEF(pj_uint16_t) pj_sockaddr_get_port(const pj_sockaddr_t *addr) const pj_sockaddr *a = (const pj_sockaddr*) addr; PJ_ASSERT_RETURN(a->addr.sa_family == PJ_AF_INET || - a->addr.sa_family == PJ_AF_INET6, (pj_uint16_t)0xFFFF); + a->addr.sa_family == PJ_AF_INET6, (pj_uint16_t)0xFFFF); return pj_ntohs((pj_uint16_t)(a->addr.sa_family == PJ_AF_INET6 ? - a->ipv6.sin6_port : a->ipv4.sin_port)); + a->ipv6.sin6_port : a->ipv4.sin_port)); } /* @@ -379,9 +378,9 @@ PJ_DEF(unsigned) pj_sockaddr_get_addr_len(const pj_sockaddr_t *addr) { const pj_sockaddr *a = (const pj_sockaddr*) addr; PJ_ASSERT_RETURN(a->addr.sa_family == PJ_AF_INET || - a->addr.sa_family == PJ_AF_INET6, 0); + a->addr.sa_family == PJ_AF_INET6, 0); return a->addr.sa_family == PJ_AF_INET6 ? - sizeof(pj_in6_addr) : sizeof(pj_in_addr); + sizeof(pj_in6_addr) : sizeof(pj_in_addr); } /* @@ -391,16 +390,16 @@ PJ_DEF(unsigned) pj_sockaddr_get_len(const pj_sockaddr_t *addr) { const pj_sockaddr *a = (const pj_sockaddr*) addr; PJ_ASSERT_RETURN(a->addr.sa_family == PJ_AF_INET || - a->addr.sa_family == PJ_AF_INET6, 0); + a->addr.sa_family == PJ_AF_INET6, 0); return a->addr.sa_family == PJ_AF_INET6 ? - sizeof(pj_sockaddr_in6) : sizeof(pj_sockaddr_in); + sizeof(pj_sockaddr_in6) : sizeof(pj_sockaddr_in); } /* * Copy only the address part (sin_addr/sin6_addr) of a socket address. */ PJ_DEF(void) pj_sockaddr_copy_addr( pj_sockaddr *dst, - const pj_sockaddr *src) + const pj_sockaddr *src) { /* Destination sockaddr might not be initialized */ const char *srcbuf = (char*)pj_sockaddr_get_addr(src); @@ -420,8 +419,8 @@ PJ_DEF(void) pj_sockaddr_cp(pj_sockaddr_t *dst, const pj_sockaddr_t *src) * Synthesize address. */ PJ_DEF(pj_status_t) pj_sockaddr_synthesize(int dst_af, - pj_sockaddr_t *dst, - const pj_sockaddr_t *src) + pj_sockaddr_t *dst, + const pj_sockaddr_t *src) { char ip_addr_buf[PJ_INET6_ADDRSTRLEN]; unsigned int count = 1; @@ -443,8 +442,8 @@ PJ_DEF(pj_status_t) pj_sockaddr_synthesize(int dst_af, /* Try to synthesize address using pj_getaddrinfo(). */ status = pj_getaddrinfo(dst_af, &ip_addr, &count, ai); if (status == PJ_SUCCESS && count > 0) { - pj_sockaddr_cp(dst, &ai[0].ai_addr); - pj_sockaddr_set_port(dst, pj_sockaddr_get_port(src)); + pj_sockaddr_cp(dst, &ai[0].ai_addr); + pj_sockaddr_set_port(dst, pj_sockaddr_get_port(src)); } return status; @@ -454,7 +453,7 @@ PJ_DEF(pj_status_t) pj_sockaddr_synthesize(int dst_af, * Set port number of pj_sockaddr_in */ PJ_DEF(void) pj_sockaddr_in_set_port(pj_sockaddr_in *addr, - pj_uint16_t hostport) + pj_uint16_t hostport) { addr->sin_port = pj_htons(hostport); } @@ -463,16 +462,16 @@ PJ_DEF(void) pj_sockaddr_in_set_port(pj_sockaddr_in *addr, * Set port number of pj_sockaddr */ PJ_DEF(pj_status_t) pj_sockaddr_set_port(pj_sockaddr *addr, - pj_uint16_t hostport) + pj_uint16_t hostport) { int af = addr->addr.sa_family; PJ_ASSERT_RETURN(af==PJ_AF_INET || af==PJ_AF_INET6, PJ_EINVAL); if (af == PJ_AF_INET6) - addr->ipv6.sin6_port = pj_htons(hostport); + addr->ipv6.sin6_port = pj_htons(hostport); else - addr->ipv4.sin_port = pj_htons(hostport); + addr->ipv4.sin_port = pj_htons(hostport); return PJ_SUCCESS; } @@ -491,7 +490,7 @@ PJ_DEF(pj_in_addr) pj_sockaddr_in_get_addr(const pj_sockaddr_in *addr) * Set IPv4 address */ PJ_DEF(void) pj_sockaddr_in_set_addr(pj_sockaddr_in *addr, - pj_uint32_t hostaddr) + pj_uint32_t hostaddr) { addr->sin_addr.s_addr = pj_htonl(hostaddr); } @@ -500,10 +499,10 @@ PJ_DEF(void) pj_sockaddr_in_set_addr(pj_sockaddr_in *addr, * Parse address */ PJ_DEF(pj_status_t) pj_sockaddr_parse2(int af, unsigned options, - const pj_str_t *str, - pj_str_t *p_hostpart, - pj_uint16_t *p_port, - int *raf) + const pj_str_t *str, + pj_str_t *p_hostpart, + pj_uint16_t *p_port, + int *raf) { const char *end = str->ptr + str->slen; const char *last_colon_pos = NULL; @@ -511,151 +510,151 @@ PJ_DEF(pj_status_t) pj_sockaddr_parse2(int af, unsigned options, const char *p; PJ_ASSERT_RETURN((af==PJ_AF_INET || af==PJ_AF_INET6 || af==PJ_AF_UNSPEC) && - options==0 && - str!=NULL, PJ_EINVAL); + options==0 && + str!=NULL, PJ_EINVAL); /* Special handling for empty input */ if (str->slen==0 || str->ptr==NULL) { - if (p_hostpart) - p_hostpart->slen = 0; - if (p_port) - *p_port = 0; - if (raf) - *raf = PJ_AF_INET; - return PJ_SUCCESS; + if (p_hostpart) + p_hostpart->slen = 0; + if (p_port) + *p_port = 0; + if (raf) + *raf = PJ_AF_INET; + return PJ_SUCCESS; } /* Count the colon and get the last colon */ for (p=str->ptr; p!=end; ++p) { - if (*p == ':') { - ++colon_cnt; - last_colon_pos = p; - } + if (*p == ':') { + ++colon_cnt; + last_colon_pos = p; + } } /* Deduce address family if it's not given */ if (af == PJ_AF_UNSPEC) { - if (colon_cnt > 1) - af = PJ_AF_INET6; - else - af = PJ_AF_INET; + if (colon_cnt > 1) + af = PJ_AF_INET6; + else + af = PJ_AF_INET; } else if (af == PJ_AF_INET && colon_cnt > 1) - return PJ_EINVAL; + return PJ_EINVAL; if (raf) - *raf = af; + *raf = af; if (af == PJ_AF_INET) { - /* Parse as IPv4. Supported formats: - * - "10.0.0.1:80" - * - "10.0.0.1" - * - "10.0.0.1:" - * - ":80" - * - ":" - */ - pj_str_t hostpart; - unsigned long port; - - hostpart.ptr = (char*)str->ptr; - - if (last_colon_pos) { - pj_str_t port_part; - int i; - - hostpart.slen = last_colon_pos - str->ptr; - - port_part.ptr = (char*)last_colon_pos + 1; - port_part.slen = end - port_part.ptr; - - /* Make sure port number is valid */ - for (i=0; i 65535) - return PJ_EINVAL; - } else { - hostpart.slen = str->slen; - port = 0; - } - - if (p_hostpart) - *p_hostpart = hostpart; - if (p_port) - *p_port = (pj_uint16_t)port; - - return PJ_SUCCESS; + /* Parse as IPv4. Supported formats: + * - "10.0.0.1:80" + * - "10.0.0.1" + * - "10.0.0.1:" + * - ":80" + * - ":" + */ + pj_str_t hostpart; + unsigned long port; + + hostpart.ptr = (char*)str->ptr; + + if (last_colon_pos) { + pj_str_t port_part; + int i; + + hostpart.slen = last_colon_pos - str->ptr; + + port_part.ptr = (char*)last_colon_pos + 1; + port_part.slen = end - port_part.ptr; + + /* Make sure port number is valid */ + for (i=0; i 65535) + return PJ_EINVAL; + } else { + hostpart.slen = str->slen; + port = 0; + } + + if (p_hostpart) + *p_hostpart = hostpart; + if (p_port) + *p_port = (pj_uint16_t)port; + + return PJ_SUCCESS; } else if (af == PJ_AF_INET6) { - /* Parse as IPv6. Supported formats: - * - "fe::01:80" ==> note: port number is zero in this case, not 80! - * - "[fe::01]:80" - * - "fe::01" - * - "fe::01:" - * - "[fe::01]" - * - "[fe::01]:" - * - "[::]:80" - * - ":::80" - * - "[::]" - * - "[::]:" - * - ":::" - * - "::" - */ - pj_str_t hostpart, port_part; - - if (*str->ptr == '[') { - char *end_bracket; - int i; - unsigned long port; - - if (last_colon_pos == NULL) - return PJ_EINVAL; - - end_bracket = pj_strchr(str, ']'); - if (end_bracket == NULL) - return PJ_EINVAL; - - hostpart.ptr = (char*)str->ptr + 1; - hostpart.slen = end_bracket - hostpart.ptr; - - if (last_colon_pos < end_bracket) { - port_part.ptr = NULL; - port_part.slen = 0; - } else { - port_part.ptr = (char*)last_colon_pos + 1; - port_part.slen = end - port_part.ptr; - } - - /* Make sure port number is valid */ - for (i=0; i 65535) - return PJ_EINVAL; - - if (p_hostpart) - *p_hostpart = hostpart; - if (p_port) - *p_port = (pj_uint16_t)port; - - return PJ_SUCCESS; - - } else { - /* Treat everything as part of the IPv6 IP address */ - if (p_hostpart) - *p_hostpart = *str; - if (p_port) - *p_port = 0; - - return PJ_SUCCESS; - } + /* Parse as IPv6. Supported formats: + * - "fe::01:80" ==> note: port number is zero in this case, not 80! + * - "[fe::01]:80" + * - "fe::01" + * - "fe::01:" + * - "[fe::01]" + * - "[fe::01]:" + * - "[::]:80" + * - ":::80" + * - "[::]" + * - "[::]:" + * - ":::" + * - "::" + */ + pj_str_t hostpart, port_part; + + if (*str->ptr == '[') { + char *end_bracket; + int i; + unsigned long port; + + if (last_colon_pos == NULL) + return PJ_EINVAL; + + end_bracket = pj_strchr(str, ']'); + if (end_bracket == NULL) + return PJ_EINVAL; + + hostpart.ptr = (char*)str->ptr + 1; + hostpart.slen = end_bracket - hostpart.ptr; + + if (last_colon_pos < end_bracket) { + port_part.ptr = NULL; + port_part.slen = 0; + } else { + port_part.ptr = (char*)last_colon_pos + 1; + port_part.slen = end - port_part.ptr; + } + + /* Make sure port number is valid */ + for (i=0; i 65535) + return PJ_EINVAL; + + if (p_hostpart) + *p_hostpart = hostpart; + if (p_port) + *p_port = (pj_uint16_t)port; + + return PJ_SUCCESS; + + } else { + /* Treat everything as part of the IPv6 IP address */ + if (p_hostpart) + *p_hostpart = *str; + if (p_port) + *p_port = 0; + + return PJ_SUCCESS; + } } else { - return PJ_EAFNOTSUP; + return PJ_EAFNOTSUP; } } @@ -664,8 +663,8 @@ PJ_DEF(pj_status_t) pj_sockaddr_parse2(int af, unsigned options, * Parse address */ PJ_DEF(pj_status_t) pj_sockaddr_parse( int af, unsigned options, - const pj_str_t *str, - pj_sockaddr *addr) + const pj_str_t *str, + pj_sockaddr *addr) { pj_str_t hostpart; pj_uint16_t port; @@ -673,58 +672,58 @@ PJ_DEF(pj_status_t) pj_sockaddr_parse( int af, unsigned options, PJ_ASSERT_RETURN(addr, PJ_EINVAL); PJ_ASSERT_RETURN(af==PJ_AF_UNSPEC || - af==PJ_AF_INET || - af==PJ_AF_INET6, PJ_EINVAL); + af==PJ_AF_INET || + af==PJ_AF_INET6, PJ_EINVAL); PJ_ASSERT_RETURN(options == 0, PJ_EINVAL); status = pj_sockaddr_parse2(af, options, str, &hostpart, &port, &af); if (status != PJ_SUCCESS) - return status; + return status; #if !defined(PJ_HAS_IPV6) || !PJ_HAS_IPV6 if (af==PJ_AF_INET6) - return PJ_EIPV6NOTSUP; + return PJ_EIPV6NOTSUP; #endif status = pj_sockaddr_init(af, addr, &hostpart, port); #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6 if (status != PJ_SUCCESS && af == PJ_AF_INET6) { - /* Parsing does not yield valid address. Try to treat the last - * portion after the colon as port number. - */ - const char *last_colon_pos=NULL, *p; - const char *end = str->ptr + str->slen; - unsigned long long_port; - pj_str_t port_part; - int i; - - /* Parse as IPv6:port */ - for (p=str->ptr; p!=end; ++p) { - if (*p == ':') - last_colon_pos = p; - } - - if (last_colon_pos == NULL) - return status; - - hostpart.ptr = (char*)str->ptr; - hostpart.slen = last_colon_pos - str->ptr; - - port_part.ptr = (char*)last_colon_pos + 1; - port_part.slen = end - port_part.ptr; - - /* Make sure port number is valid */ - for (i=0; i 65535) - return status; - - port = (pj_uint16_t)long_port; - - status = pj_sockaddr_init(PJ_AF_INET6, addr, &hostpart, port); + /* Parsing does not yield valid address. Try to treat the last + * portion after the colon as port number. + */ + const char *last_colon_pos=NULL, *p; + const char *end = str->ptr + str->slen; + unsigned long long_port; + pj_str_t port_part; + int i; + + /* Parse as IPv6:port */ + for (p=str->ptr; p!=end; ++p) { + if (*p == ':') + last_colon_pos = p; + } + + if (last_colon_pos == NULL) + return status; + + hostpart.ptr = (char*)str->ptr; + hostpart.slen = last_colon_pos - str->ptr; + + port_part.ptr = (char*)last_colon_pos + 1; + port_part.slen = end - port_part.ptr; + + /* Make sure port number is valid */ + for (i=0; i 65535) + return status; + + port = (pj_uint16_t)long_port; + + status = pj_sockaddr_init(PJ_AF_INET6, addr, &hostpart, port); } #endif @@ -736,72 +735,72 @@ PJ_DEF(pj_status_t) pj_gethostip(int af, pj_sockaddr *addr) { unsigned i, count, cand_cnt; enum { - CAND_CNT = 8, + CAND_CNT = 8, - /* Weighting to be applied to found addresses */ - WEIGHT_HOSTNAME = 1, /* hostname IP is not always valid! */ - WEIGHT_DEF_ROUTE = 2, - WEIGHT_INTERFACE = 1, - WEIGHT_LOOPBACK = -5, - WEIGHT_LINK_LOCAL = -4, - WEIGHT_DISABLED = -50, + /* Weighting to be applied to found addresses */ + WEIGHT_HOSTNAME = 1, /* hostname IP is not always valid! */ + WEIGHT_DEF_ROUTE = 2, + WEIGHT_INTERFACE = 1, + WEIGHT_LOOPBACK = -5, + WEIGHT_LINK_LOCAL = -4, + WEIGHT_DISABLED = -50, - MIN_WEIGHT = WEIGHT_DISABLED+1 /* minimum weight to use */ + MIN_WEIGHT = WEIGHT_DISABLED+1 /* minimum weight to use */ }; /* candidates: */ pj_sockaddr cand_addr[CAND_CNT]; - int cand_weight[CAND_CNT]; - int selected_cand; - char strip[PJ_INET6_ADDRSTRLEN+10]; + int cand_weight[CAND_CNT]; + int selected_cand; + char strip[PJ_INET6_ADDRSTRLEN+10]; /* Special IPv4 addresses. */ struct spec_ipv4_t { - pj_uint32_t addr; - pj_uint32_t mask; - int weight; + pj_uint32_t addr; + pj_uint32_t mask; + int weight; } spec_ipv4[] = { - /* 127.0.0.0/8, loopback addr will be used if there is no other - * addresses. - */ - { 0x7f000000, 0xFF000000, WEIGHT_LOOPBACK }, - - /* 0.0.0.0/8, special IP that doesn't seem to be practically useful */ - { 0x00000000, 0xFF000000, WEIGHT_DISABLED }, - - /* 169.254.0.0/16, a zeroconf/link-local address, which has higher - * priority than loopback and will be used if there is no other - * valid addresses. - */ - { 0xa9fe0000, 0xFFFF0000, WEIGHT_LINK_LOCAL } + /* 127.0.0.0/8, loopback addr will be used if there is no other + * addresses. + */ + { 0x7f000000, 0xFF000000, WEIGHT_LOOPBACK }, + + /* 0.0.0.0/8, special IP that doesn't seem to be practically useful */ + { 0x00000000, 0xFF000000, WEIGHT_DISABLED }, + + /* 169.254.0.0/16, a zeroconf/link-local address, which has higher + * priority than loopback and will be used if there is no other + * valid addresses. + */ + { 0xa9fe0000, 0xFFFF0000, WEIGHT_LINK_LOCAL } }; /* Special IPv6 addresses */ struct spec_ipv6_t { - pj_uint8_t addr[16]; - pj_uint8_t mask[16]; - int weight; + pj_uint8_t addr[16]; + pj_uint8_t mask[16]; + int weight; } spec_ipv6[] = { - /* Loopback address, ::1/128 */ - { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, - {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff}, - WEIGHT_LOOPBACK - }, - - /* Link local, fe80::/10 */ - { {0xfe,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {0xff,0xc0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - WEIGHT_LINK_LOCAL - }, - - /* Disabled, ::/128 */ - { {0x0,0x0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - { 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff}, - WEIGHT_DISABLED - } + /* Loopback address, ::1/128 */ + { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, + 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff}, + WEIGHT_LOOPBACK + }, + + /* Link local, fe80::/10 */ + { {0xfe,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, + {0xff,0xc0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, + WEIGHT_LINK_LOCAL + }, + + /* Disabled, ::/128 */ + { {0x0,0x0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, + { 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, + 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff}, + WEIGHT_DISABLED + } }; pj_addrinfo ai; pj_status_t status; @@ -818,8 +817,8 @@ PJ_DEF(pj_status_t) pj_gethostip(int af, pj_sockaddr *addr) pj_bzero(cand_addr, sizeof(cand_addr)); pj_bzero(cand_weight, sizeof(cand_weight)); for (i=0; iaddr.sa_family = (pj_uint16_t)af; @@ -829,24 +828,24 @@ PJ_DEF(pj_status_t) pj_gethostip(int af, pj_sockaddr *addr) PJ_GETHOSTIP_DISABLE_LOCAL_RESOLUTION == 0 /* Get hostname's IP address */ { - const pj_str_t *hostname = pj_gethostname(); - count = 1; - - if (hostname->slen > 0) - status = pj_getaddrinfo(af, hostname, &count, &ai); - else - status = PJ_ERESOLVE; - - if (status == PJ_SUCCESS) { - pj_assert(ai.ai_addr.addr.sa_family == (pj_uint16_t)af); - pj_sockaddr_copy_addr(&cand_addr[cand_cnt], &ai.ai_addr); - pj_sockaddr_set_port(&cand_addr[cand_cnt], 0); - cand_weight[cand_cnt] += WEIGHT_HOSTNAME; - ++cand_cnt; - - TRACE_((THIS_FILE, "hostname IP is %s", - pj_sockaddr_print(&ai.ai_addr, strip, sizeof(strip), 3))); - } + const pj_str_t *hostname = pj_gethostname(); + count = 1; + + if (hostname->slen > 0) + status = pj_getaddrinfo(af, hostname, &count, &ai); + else + status = PJ_ERESOLVE; + + if (status == PJ_SUCCESS) { + pj_assert(ai.ai_addr.addr.sa_family == (pj_uint16_t)af); + pj_sockaddr_copy_addr(&cand_addr[cand_cnt], &ai.ai_addr); + pj_sockaddr_set_port(&cand_addr[cand_cnt], 0); + cand_weight[cand_cnt] += WEIGHT_HOSTNAME; + ++cand_cnt; + + TRACE_((THIS_FILE, "hostname IP is %s", + pj_sockaddr_print(&ai.ai_addr, strip, sizeof(strip), 3))); + } } #else PJ_UNUSED_ARG(ai); @@ -854,153 +853,153 @@ PJ_DEF(pj_status_t) pj_gethostip(int af, pj_sockaddr *addr) /* Get default interface (interface for default route) */ if (cand_cnt < PJ_ARRAY_SIZE(cand_addr)) { - status = pj_getdefaultipinterface(af, addr); - if (status == PJ_SUCCESS) { - TRACE_((THIS_FILE, "default IP is %s", - pj_sockaddr_print(addr, strip, sizeof(strip), 3))); - - pj_sockaddr_set_port(addr, 0); - for (i=0; i= cand_cnt) { - pj_sockaddr_copy_addr(&cand_addr[i], addr); - ++cand_cnt; - } - } + status = pj_getdefaultipinterface(af, addr); + if (status == PJ_SUCCESS) { + TRACE_((THIS_FILE, "default IP is %s", + pj_sockaddr_print(addr, strip, sizeof(strip), 3))); + + pj_sockaddr_set_port(addr, 0); + for (i=0; i= cand_cnt) { + pj_sockaddr_copy_addr(&cand_addr[i], addr); + ++cand_cnt; + } + } } /* Enumerate IP interfaces */ if (cand_cnt < PJ_ARRAY_SIZE(cand_addr)) { - unsigned start_if = cand_cnt; - count = PJ_ARRAY_SIZE(cand_addr) - start_if; - - status = pj_enum_ip_interface(af, &count, &cand_addr[start_if]); - if (status == PJ_SUCCESS && count) { - /* Clear the port number */ - for (i=0; i cand_weight[selected_cand]) - selected_cand = i; + TRACE_((THIS_FILE, "Checking candidate IP %s, weight=%d", + pj_sockaddr_print(&cand_addr[i], strip, sizeof(strip), 3), + cand_weight[i])); + + if (cand_weight[i] < MIN_WEIGHT) { + continue; + } + + if (selected_cand == -1) + selected_cand = i; + else if (cand_weight[i] > cand_weight[selected_cand]) + selected_cand = i; } /* If else fails, returns loopback interface as the last resort */ if (selected_cand == -1) { - if (af==PJ_AF_INET) { - addr->ipv4.sin_addr.s_addr = pj_htonl (0x7f000001); - } else { - pj_in6_addr *s6_addr_; - - s6_addr_ = (pj_in6_addr*) pj_sockaddr_get_addr(addr); - pj_bzero(s6_addr_, sizeof(pj_in6_addr)); - s6_addr_->s6_addr[15] = 1; - } - TRACE_((THIS_FILE, "Loopback IP %s returned", - pj_sockaddr_print(addr, strip, sizeof(strip), 3))); + if (af==PJ_AF_INET) { + addr->ipv4.sin_addr.s_addr = pj_htonl (0x7f000001); + } else { + pj_in6_addr *s6_addr_; + + s6_addr_ = (pj_in6_addr*) pj_sockaddr_get_addr(addr); + pj_bzero(s6_addr_, sizeof(pj_in6_addr)); + s6_addr_->s6_addr[15] = 1; + } + TRACE_((THIS_FILE, "Loopback IP %s returned", + pj_sockaddr_print(addr, strip, sizeof(strip), 3))); } else { - pj_sockaddr_copy_addr(addr, &cand_addr[selected_cand]); - TRACE_((THIS_FILE, "Candidate %s selected", - pj_sockaddr_print(addr, strip, sizeof(strip), 3))); + pj_sockaddr_copy_addr(addr, &cand_addr[selected_cand]); + TRACE_((THIS_FILE, "Candidate %s selected", + pj_sockaddr_print(addr, strip, sizeof(strip), 3))); } return PJ_SUCCESS; @@ -1022,41 +1021,41 @@ PJ_DEF(pj_status_t) pj_getipinterface(int af, pj_sockaddr_init(af, &dst_addr, NULL, 53); status = pj_inet_pton(af, dst, pj_sockaddr_get_addr(&dst_addr)); if (status != PJ_SUCCESS) { - /* "dst" is not an IP address. */ - if (allow_resolve) { - status = pj_sockaddr_init(af, &dst_addr, dst, 53); - } else { - pj_str_t cp; - - if (af == PJ_AF_INET) { - cp = pj_str("1.1.1.1"); - } else { - cp = pj_str("1::1"); - } - status = pj_sockaddr_init(af, &dst_addr, &cp, 53); - } - - if (status != PJ_SUCCESS) - return status; + /* "dst" is not an IP address. */ + if (allow_resolve) { + status = pj_sockaddr_init(af, &dst_addr, dst, 53); + } else { + pj_str_t cp; + + if (af == PJ_AF_INET) { + cp = pj_str("1.1.1.1"); + } else { + cp = pj_str("1::1"); + } + status = pj_sockaddr_init(af, &dst_addr, &cp, 53); + } + + if (status != PJ_SUCCESS) + return status; } /* Create UDP socket and connect() to the destination IP */ status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &fd); if (status != PJ_SUCCESS) { - return status; + return status; } status = pj_sock_connect(fd, &dst_addr, pj_sockaddr_get_len(&dst_addr)); if (status != PJ_SUCCESS) { - pj_sock_close(fd); - return status; + pj_sock_close(fd); + return status; } len = sizeof(*itf_addr); status = pj_sock_getsockname(fd, itf_addr, &len); if (status != PJ_SUCCESS) { - pj_sock_close(fd); - return status; + pj_sock_close(fd); + return status; } pj_sock_close(fd); @@ -1064,13 +1063,13 @@ PJ_DEF(pj_status_t) pj_getipinterface(int af, /* Check that the address returned is not zero */ pj_bzero(zero, sizeof(zero)); if (pj_memcmp(pj_sockaddr_get_addr(itf_addr), zero, - pj_sockaddr_get_addr_len(itf_addr))==0) + pj_sockaddr_get_addr_len(itf_addr))==0) { - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; } if (p_dst_addr) - *p_dst_addr = dst_addr; + *p_dst_addr = dst_addr; return PJ_SUCCESS; } @@ -1081,9 +1080,9 @@ PJ_DEF(pj_status_t) pj_getdefaultipinterface(int af, pj_sockaddr *addr) pj_str_t cp; if (af == PJ_AF_INET) { - cp = pj_str("1.1.1.1"); + cp = pj_str("1.1.1.1"); } else { - cp = pj_str("1::1"); + cp = pj_str("1::1"); } return pj_getipinterface(af, &cp, addr, PJ_FALSE, NULL); @@ -1094,9 +1093,9 @@ PJ_DEF(pj_status_t) pj_getdefaultipinterface(int af, pj_sockaddr *addr) * Bind socket at random port. */ PJ_DEF(pj_status_t) pj_sock_bind_random( pj_sock_t sockfd, - const pj_sockaddr_t *addr, - pj_uint16_t port_range, - pj_uint16_t max_try) + const pj_sockaddr_t *addr, + pj_uint16_t port_range, + pj_uint16_t max_try) { pj_sockaddr bind_addr; int addr_len; @@ -1112,16 +1111,16 @@ PJ_DEF(pj_status_t) pj_sock_bind_random( pj_sock_t sockfd, base_port = pj_sockaddr_get_port(addr); if (base_port == 0 || port_range == 0) { - return pj_sock_bind(sockfd, &bind_addr, addr_len); + return pj_sock_bind(sockfd, &bind_addr, addr_len); } for (; max_try; --max_try) { - pj_uint16_t port; - port = (pj_uint16_t)(base_port + pj_rand() % (port_range + 1)); - pj_sockaddr_set_port(&bind_addr, port); - status = pj_sock_bind(sockfd, &bind_addr, addr_len); - if (status == PJ_SUCCESS) - break; + pj_uint16_t port; + port = (pj_uint16_t)(base_port + pj_rand() % (port_range + 1)); + pj_sockaddr_set_port(&bind_addr, port); + status = pj_sock_bind(sockfd, &bind_addr, addr_len); + if (status == PJ_SUCCESS) + break; } return status; @@ -1132,9 +1131,9 @@ PJ_DEF(pj_status_t) pj_sock_bind_random( pj_sock_t sockfd, * Adjust socket send/receive buffer size. */ PJ_DEF(pj_status_t) pj_sock_setsockopt_sobuf( pj_sock_t sockfd, - pj_uint16_t optname, - pj_bool_t auto_retry, - unsigned *buf_size) + pj_uint16_t optname, + pj_bool_t auto_retry, + unsigned *buf_size) { pj_status_t status; int try_size, cur_size, i, step, size_len; @@ -1143,48 +1142,48 @@ PJ_DEF(pj_status_t) pj_sock_setsockopt_sobuf( pj_sock_t sockfd, PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sockfd != PJ_INVALID_SOCKET && - buf_size && - *buf_size > 0 && - (optname == pj_SO_RCVBUF() || - optname == pj_SO_SNDBUF()), - PJ_EINVAL); + buf_size && + *buf_size > 0 && + (optname == pj_SO_RCVBUF() || + optname == pj_SO_SNDBUF()), + PJ_EINVAL); size_len = sizeof(cur_size); status = pj_sock_getsockopt(sockfd, pj_SOL_SOCKET(), optname, - &cur_size, &size_len); + &cur_size, &size_len); if (status != PJ_SUCCESS) - return status; + return status; try_size = *buf_size; step = (try_size - cur_size) / MAX_TRY; if (step < 4096) - step = 4096; + step = 4096; for (i = 0; i < (MAX_TRY-1); ++i) { - if (try_size <= cur_size) { - /* Done, return current size */ - *buf_size = cur_size; - break; - } - - status = pj_sock_setsockopt(sockfd, pj_SOL_SOCKET(), optname, - &try_size, sizeof(try_size)); - if (status == PJ_SUCCESS) { - status = pj_sock_getsockopt(sockfd, pj_SOL_SOCKET(), optname, - &cur_size, &size_len); - if (status != PJ_SUCCESS) { - /* Ops! No info about current size, just return last try size - * and quit. - */ - *buf_size = try_size; - break; - } - } - - if (!auto_retry) - break; - - try_size -= step; + if (try_size <= cur_size) { + /* Done, return current size */ + *buf_size = cur_size; + break; + } + + status = pj_sock_setsockopt(sockfd, pj_SOL_SOCKET(), optname, + &try_size, sizeof(try_size)); + if (status == PJ_SUCCESS) { + status = pj_sock_getsockopt(sockfd, pj_SOL_SOCKET(), optname, + &cur_size, &size_len); + if (status != PJ_SUCCESS) { + /* Ops! No info about current size, just return last try size + * and quit. + */ + *buf_size = try_size; + break; + } + } + + if (!auto_retry) + break; + + try_size -= step; } return status; @@ -1192,10 +1191,10 @@ PJ_DEF(pj_status_t) pj_sock_setsockopt_sobuf( pj_sock_t sockfd, PJ_DEF(char *) pj_addr_str_print( const pj_str_t *host_str, int port, - char *buf, int size, unsigned flag) + char *buf, int size, unsigned flag) { enum { - WITH_PORT = 1 + WITH_PORT = 1 }; char *bquote, *equote; int af = pj_AF_UNSPEC(); @@ -1203,23 +1202,23 @@ PJ_DEF(char *) pj_addr_str_print( const pj_str_t *host_str, int port, /* Check if this is an IPv6 address */ if (pj_inet_pton(pj_AF_INET6(), host_str, &dummy6) == PJ_SUCCESS) - af = pj_AF_INET6(); + af = pj_AF_INET6(); if (af == pj_AF_INET6()) { - bquote = "["; - equote = "]"; + bquote = "["; + equote = "]"; } else { - bquote = ""; - equote = ""; + bquote = ""; + equote = ""; } if (flag & WITH_PORT) { - pj_ansi_snprintf(buf, size, "%s%.*s%s:%d", - bquote, (int)host_str->slen, host_str->ptr, equote, - port); + pj_ansi_snprintf(buf, size, "%s%.*s%s:%d", + bquote, (int)host_str->slen, host_str->ptr, equote, + port); } else { - pj_ansi_snprintf(buf, size, "%s%.*s%s", - bquote, (int)host_str->slen, host_str->ptr, equote); + pj_ansi_snprintf(buf, size, "%s%.*s%s", + bquote, (int)host_str->slen, host_str->ptr, equote); } return buf; } @@ -1229,9 +1228,9 @@ PJ_DEF(char *) pj_addr_str_print( const pj_str_t *host_str, int port, * Use a pair of IPv4/IPv6 local sockets (listening on 127.0.0.1/::1) */ static pj_status_t socketpair_imp(int family, - int type, - int protocol, - pj_sock_t sv[2]) + int type, + int protocol, + pj_sock_t sv[2]) { pj_status_t status; pj_sock_t lfd = PJ_INVALID_SOCKET; @@ -1242,66 +1241,66 @@ static pj_status_t socketpair_imp(int family, #if PJ_HAS_TCP PJ_ASSERT_RETURN(type == pj_SOCK_DGRAM() || type == pj_SOCK_STREAM(), - PJ_EINVAL); + PJ_EINVAL); #else PJ_ASSERT_RETURN(type == pj_SOCK_DGRAM(), PJ_EINVAL); #endif PJ_ASSERT_RETURN(family == pj_AF_INET() || family == pj_AF_INET6(), - PJ_EINVAL); + PJ_EINVAL); loopback = family == pj_AF_INET() ? pj_str("127.0.0.1") : pj_str("::1"); /* listen */ status = pj_sock_socket(family, type, protocol, &lfd); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; pj_sockaddr_init(family, &sa, &loopback, 0); salen = pj_sockaddr_get_len(&sa); status = pj_sock_bind(lfd, &sa, salen); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_sock_getsockname(lfd, &sa, &salen); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #if PJ_HAS_TCP if (type == pj_SOCK_STREAM()) { - status = pj_sock_listen(lfd, 1); - if (status != PJ_SUCCESS) - goto on_error; + status = pj_sock_listen(lfd, 1); + if (status != PJ_SUCCESS) + goto on_error; } #endif /* connect to listen fd */ status = pj_sock_socket(family, type, protocol, &cfd); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_sock_connect(cfd, &sa, salen); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; if (type == pj_SOCK_DGRAM()) { - status = pj_sock_getsockname(cfd, &sa, &salen); - if (status != PJ_SUCCESS) - goto on_error; - status = pj_sock_connect(lfd, &sa, salen); - if (status != PJ_SUCCESS) - goto on_error; - sv[0] = lfd; - sv[1] = cfd; + status = pj_sock_getsockname(cfd, &sa, &salen); + if (status != PJ_SUCCESS) + goto on_error; + status = pj_sock_connect(lfd, &sa, salen); + if (status != PJ_SUCCESS) + goto on_error; + sv[0] = lfd; + sv[1] = cfd; } #if PJ_HAS_TCP else if (type == pj_SOCK_STREAM()) { - pj_sock_t newfd = PJ_INVALID_SOCKET; - status = pj_sock_accept(lfd, &newfd, NULL, NULL); - if (status != PJ_SUCCESS) - goto on_error; - pj_sock_close(lfd); - sv[0] = newfd; - sv[1] = cfd; + pj_sock_t newfd = PJ_INVALID_SOCKET; + status = pj_sock_accept(lfd, &newfd, NULL, NULL); + if (status != PJ_SUCCESS) + goto on_error; + pj_sock_close(lfd); + sv[0] = newfd; + sv[1] = cfd; } #endif @@ -1309,17 +1308,17 @@ static pj_status_t socketpair_imp(int family, on_error: if (lfd != PJ_INVALID_SOCKET) - pj_sock_close(lfd); + pj_sock_close(lfd); if (cfd != PJ_INVALID_SOCKET) - pj_sock_close(cfd); + pj_sock_close(cfd); return status; } #if defined(PJ_SOCK_HAS_SOCKETPAIR) && PJ_SOCK_HAS_SOCKETPAIR != 0 PJ_DEF(pj_status_t) pj_sock_socketpair(int family, - int type, - int protocol, - pj_sock_t sv[2]) + int type, + int protocol, + pj_sock_t sv[2]) { int status; int tmp_sv[2]; @@ -1328,11 +1327,11 @@ PJ_DEF(pj_status_t) pj_sock_socketpair(int family, status = socketpair(family, type, protocol, tmp_sv); if (status != PJ_SUCCESS) { - if (errno == EOPNOTSUPP) { - return socketpair_imp(family, type, protocol, sv); - } - status = PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); - return status; + if (errno == EOPNOTSUPP) { + return socketpair_imp(family, type, protocol, sv); + } + status = PJ_RETURN_OS_ERROR(pj_get_native_netos_error()); + return status; } sv[0] = tmp_sv[0]; sv[1] = tmp_sv[1]; @@ -1340,9 +1339,9 @@ PJ_DEF(pj_status_t) pj_sock_socketpair(int family, } #else PJ_DEF(pj_status_t) pj_sock_socketpair(int family, - int type, - int protocol, - pj_sock_t sv[2]) + int type, + int protocol, + pj_sock_t sv[2]) { PJ_CHECK_STACK(); return socketpair_imp(family, type, protocol, sv); @@ -1533,5 +1532,5 @@ PJ_DEF(int) pj_MSG_DONTROUTE(void) return PJ_MSG_DONTROUTE; } -#endif /* PJ_DLL */ +#endif /* PJ_DLL */ diff --git a/pjlib/src/pj/sock_qos_bsd.c b/pjlib/src/pj/sock_qos_bsd.c index 5609e8221a..489036176c 100644 --- a/pjlib/src/pj/sock_qos_bsd.c +++ b/pjlib/src/pj/sock_qos_bsd.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -27,80 +26,80 @@ #if !defined(PJ_QOS_IMPLEMENTATION) || PJ_QOS_IMPLEMENTATION==PJ_QOS_BSD PJ_DEF(pj_status_t) pj_sock_set_qos_params(pj_sock_t sock, - pj_qos_params *param) + pj_qos_params *param) { pj_status_t last_err = PJ_ENOTSUP; pj_status_t status; /* No op? */ if (!param->flags) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Clear WMM field since we don't support it */ param->flags &= ~(PJ_QOS_PARAM_HAS_WMM); /* Set TOS/DSCP */ if (param->flags & PJ_QOS_PARAM_HAS_DSCP) { - /* We need to know if the socket is IPv4 or IPv6 */ - pj_sockaddr sa; - int salen = sizeof(salen); - - /* Value is dscp_val << 2 */ - int val = (param->dscp_val << 2); - - status = pj_sock_getsockname(sock, &sa, &salen); - if (status != PJ_SUCCESS) - return status; - - if (sa.addr.sa_family == pj_AF_INET()) { - /* In IPv4, the DS field goes in the TOS field */ - status = pj_sock_setsockopt(sock, pj_SOL_IP(), pj_IP_TOS(), - &val, sizeof(val)); - } else if (sa.addr.sa_family == pj_AF_INET6()) { - /* In IPv6, the DS field goes in the Traffic Class field */ - status = pj_sock_setsockopt(sock, pj_SOL_IPV6(), - pj_IPV6_TCLASS(), - &val, sizeof(val)); - } else { - status = PJ_EINVAL; - } - - if (status != PJ_SUCCESS) { - param->flags &= ~(PJ_QOS_PARAM_HAS_DSCP); - last_err = status; - } + /* We need to know if the socket is IPv4 or IPv6 */ + pj_sockaddr sa; + int salen = sizeof(salen); + + /* Value is dscp_val << 2 */ + int val = (param->dscp_val << 2); + + status = pj_sock_getsockname(sock, &sa, &salen); + if (status != PJ_SUCCESS) + return status; + + if (sa.addr.sa_family == pj_AF_INET()) { + /* In IPv4, the DS field goes in the TOS field */ + status = pj_sock_setsockopt(sock, pj_SOL_IP(), pj_IP_TOS(), + &val, sizeof(val)); + } else if (sa.addr.sa_family == pj_AF_INET6()) { + /* In IPv6, the DS field goes in the Traffic Class field */ + status = pj_sock_setsockopt(sock, pj_SOL_IPV6(), + pj_IPV6_TCLASS(), + &val, sizeof(val)); + } else { + status = PJ_EINVAL; + } + + if (status != PJ_SUCCESS) { + param->flags &= ~(PJ_QOS_PARAM_HAS_DSCP); + last_err = status; + } } /* Set SO_PRIORITY */ if (param->flags & PJ_QOS_PARAM_HAS_SO_PRIO) { - int val = param->so_prio; - status = pj_sock_setsockopt(sock, pj_SOL_SOCKET(), pj_SO_PRIORITY(), - &val, sizeof(val)); - if (status != PJ_SUCCESS) { - param->flags &= ~(PJ_QOS_PARAM_HAS_SO_PRIO); - last_err = status; - } + int val = param->so_prio; + status = pj_sock_setsockopt(sock, pj_SOL_SOCKET(), pj_SO_PRIORITY(), + &val, sizeof(val)); + if (status != PJ_SUCCESS) { + param->flags &= ~(PJ_QOS_PARAM_HAS_SO_PRIO); + last_err = status; + } } return param->flags ? PJ_SUCCESS : last_err; } PJ_DEF(pj_status_t) pj_sock_set_qos_type(pj_sock_t sock, - pj_qos_type type) + pj_qos_type type) { pj_qos_params param; pj_status_t status; status = pj_qos_get_params(type, ¶m); if (status != PJ_SUCCESS) - return status; + return status; return pj_sock_set_qos_params(sock, ¶m); } PJ_DEF(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, - pj_qos_params *p_param) + pj_qos_params *p_param) { pj_status_t last_err = PJ_ENOTSUP; int val = 0, optlen; @@ -113,37 +112,37 @@ PJ_DEF(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, /* Get DSCP/TOS value */ status = pj_sock_getsockname(sock, &sa, &salen); if (status == PJ_SUCCESS) { - optlen = sizeof(val); - if (sa.addr.sa_family == pj_AF_INET()) { - status = pj_sock_getsockopt(sock, pj_SOL_IP(), pj_IP_TOS(), - &val, &optlen); - } else if (sa.addr.sa_family == pj_AF_INET6()) { - status = pj_sock_getsockopt(sock, pj_SOL_IPV6(), - pj_IPV6_TCLASS(), - &val, &optlen); - } else { - status = PJ_EINVAL; - } + optlen = sizeof(val); + if (sa.addr.sa_family == pj_AF_INET()) { + status = pj_sock_getsockopt(sock, pj_SOL_IP(), pj_IP_TOS(), + &val, &optlen); + } else if (sa.addr.sa_family == pj_AF_INET6()) { + status = pj_sock_getsockopt(sock, pj_SOL_IPV6(), + pj_IPV6_TCLASS(), + &val, &optlen); + } else { + status = PJ_EINVAL; + } if (status == PJ_SUCCESS) { - p_param->flags |= PJ_QOS_PARAM_HAS_DSCP; - p_param->dscp_val = (pj_uint8_t)(val >> 2); - } else { - last_err = status; - } + p_param->flags |= PJ_QOS_PARAM_HAS_DSCP; + p_param->dscp_val = (pj_uint8_t)(val >> 2); + } else { + last_err = status; + } } else { - last_err = status; + last_err = status; } /* Get SO_PRIORITY */ optlen = sizeof(val); status = pj_sock_getsockopt(sock, pj_SOL_SOCKET(), pj_SO_PRIORITY(), - &val, &optlen); + &val, &optlen); if (status == PJ_SUCCESS) { - p_param->flags |= PJ_QOS_PARAM_HAS_SO_PRIO; - p_param->so_prio = (pj_uint8_t)val; + p_param->flags |= PJ_QOS_PARAM_HAS_SO_PRIO; + p_param->so_prio = (pj_uint8_t)val; } else { - last_err = status; + last_err = status; } /* WMM is not supported */ @@ -152,17 +151,17 @@ PJ_DEF(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, } PJ_DEF(pj_status_t) pj_sock_get_qos_type(pj_sock_t sock, - pj_qos_type *p_type) + pj_qos_type *p_type) { pj_qos_params param; pj_status_t status; status = pj_sock_get_qos_params(sock, ¶m); if (status != PJ_SUCCESS) - return status; + return status; return pj_qos_get_type(¶m, p_type); } -#endif /* PJ_QOS_IMPLEMENTATION */ +#endif /* PJ_QOS_IMPLEMENTATION */ diff --git a/pjlib/src/pj/sock_qos_common.c b/pjlib/src/pj/sock_qos_common.c index 2f3eb95932..4b0e1979d9 100644 --- a/pjlib/src/pj/sock_qos_common.c +++ b/pjlib/src/pj/sock_qos_common.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -29,19 +28,19 @@ /* "Standard" mapping between traffic type and QoS params */ static const pj_qos_params qos_map[] = { - /* flags dscp prio wmm_prio */ + /* flags dscp prio wmm_prio */ {ALL_FLAGS, 0x00, 0, PJ_QOS_WMM_PRIO_BULK_EFFORT}, /* BE */ - {ALL_FLAGS, 0x08, 2, PJ_QOS_WMM_PRIO_BULK}, /* BK */ - {ALL_FLAGS, 0x28, 5, PJ_QOS_WMM_PRIO_VIDEO}, /* VI */ - {ALL_FLAGS, 0x30, 6, PJ_QOS_WMM_PRIO_VOICE}, /* VO */ - {ALL_FLAGS, 0x38, 7, PJ_QOS_WMM_PRIO_VOICE}, /* CO */ - {ALL_FLAGS, 0x28, 5, PJ_QOS_WMM_PRIO_VIDEO} /* SIG */ + {ALL_FLAGS, 0x08, 2, PJ_QOS_WMM_PRIO_BULK}, /* BK */ + {ALL_FLAGS, 0x28, 5, PJ_QOS_WMM_PRIO_VIDEO}, /* VI */ + {ALL_FLAGS, 0x30, 6, PJ_QOS_WMM_PRIO_VOICE}, /* VO */ + {ALL_FLAGS, 0x38, 7, PJ_QOS_WMM_PRIO_VOICE}, /* CO */ + {ALL_FLAGS, 0x28, 5, PJ_QOS_WMM_PRIO_VIDEO} /* SIG */ }; /* Retrieve the mapping for the specified type */ PJ_DEF(pj_status_t) pj_qos_get_params(pj_qos_type type, - pj_qos_params *p_param) + pj_qos_params *p_param) { PJ_ASSERT_RETURN(type<=PJ_QOS_TYPE_SIGNALLING && p_param, PJ_EINVAL); pj_memcpy(p_param, &qos_map[type], sizeof(*p_param)); @@ -50,103 +49,103 @@ PJ_DEF(pj_status_t) pj_qos_get_params(pj_qos_type type, /* Get the matching traffic type */ PJ_DEF(pj_status_t) pj_qos_get_type( const pj_qos_params *param, - pj_qos_type *p_type) + pj_qos_type *p_type) { unsigned dscp_type = PJ_QOS_TYPE_BEST_EFFORT, - prio_type = PJ_QOS_TYPE_BEST_EFFORT, - wmm_type = PJ_QOS_TYPE_BEST_EFFORT; + prio_type = PJ_QOS_TYPE_BEST_EFFORT, + wmm_type = PJ_QOS_TYPE_BEST_EFFORT; unsigned i, count=0; PJ_ASSERT_RETURN(param && p_type, PJ_EINVAL); if (param->flags & PJ_QOS_PARAM_HAS_DSCP) { - for (i=0; i<=PJ_QOS_TYPE_CONTROL; ++i) { - if (param->dscp_val >= qos_map[i].dscp_val) - dscp_type = (pj_qos_type)i; - } - ++count; + for (i=0; i<=PJ_QOS_TYPE_CONTROL; ++i) { + if (param->dscp_val >= qos_map[i].dscp_val) + dscp_type = (pj_qos_type)i; + } + ++count; } if (param->flags & PJ_QOS_PARAM_HAS_SO_PRIO) { - for (i=0; i<=PJ_QOS_TYPE_CONTROL; ++i) { - if (param->so_prio >= qos_map[i].so_prio) - prio_type = (pj_qos_type)i; - } - ++count; + for (i=0; i<=PJ_QOS_TYPE_CONTROL; ++i) { + if (param->so_prio >= qos_map[i].so_prio) + prio_type = (pj_qos_type)i; + } + ++count; } if (param->flags & PJ_QOS_PARAM_HAS_WMM) { - for (i=0; i<=PJ_QOS_TYPE_CONTROL; ++i) { - if (param->wmm_prio >= qos_map[i].wmm_prio) - wmm_type = (pj_qos_type)i; - } - ++count; + for (i=0; i<=PJ_QOS_TYPE_CONTROL; ++i) { + if (param->wmm_prio >= qos_map[i].wmm_prio) + wmm_type = (pj_qos_type)i; + } + ++count; } if (count) - *p_type = (pj_qos_type)((dscp_type + prio_type + wmm_type) / count); + *p_type = (pj_qos_type)((dscp_type + prio_type + wmm_type) / count); else - *p_type = PJ_QOS_TYPE_BEST_EFFORT; + *p_type = PJ_QOS_TYPE_BEST_EFFORT; return PJ_SUCCESS; } /* Apply QoS */ PJ_DEF(pj_status_t) pj_sock_apply_qos( pj_sock_t sock, - pj_qos_type qos_type, - pj_qos_params *qos_params, - unsigned log_level, - const char *log_sender, - const char *sock_name) + pj_qos_type qos_type, + pj_qos_params *qos_params, + unsigned log_level, + const char *log_sender, + const char *sock_name) { pj_status_t qos_type_rc = PJ_SUCCESS, - qos_params_rc = PJ_SUCCESS; + qos_params_rc = PJ_SUCCESS; if (!log_sender) - log_sender = THIS_FILE; + log_sender = THIS_FILE; if (!sock_name) - sock_name = "socket"; + sock_name = "socket"; if (qos_type != PJ_QOS_TYPE_BEST_EFFORT) { - qos_type_rc = pj_sock_set_qos_type(sock, qos_type); + qos_type_rc = pj_sock_set_qos_type(sock, qos_type); - if (qos_type_rc != PJ_SUCCESS) { - pj_perror(log_level, log_sender, qos_type_rc, - "Error setting QoS type %d to %s", - qos_type, sock_name); - } + if (qos_type_rc != PJ_SUCCESS) { + pj_perror(log_level, log_sender, qos_type_rc, + "Error setting QoS type %d to %s", + qos_type, sock_name); + } } if (qos_params && qos_params->flags) { - qos_params_rc = pj_sock_set_qos_params(sock, qos_params); - if (qos_params_rc != PJ_SUCCESS) { - pj_perror(log_level, log_sender, qos_params_rc, - "Error setting QoS params (flags=%d) to %s", - qos_params->flags, sock_name); - if (qos_type_rc != PJ_SUCCESS) - return qos_params_rc; - } + qos_params_rc = pj_sock_set_qos_params(sock, qos_params); + if (qos_params_rc != PJ_SUCCESS) { + pj_perror(log_level, log_sender, qos_params_rc, + "Error setting QoS params (flags=%d) to %s", + qos_params->flags, sock_name); + if (qos_type_rc != PJ_SUCCESS) + return qos_params_rc; + } } else if (qos_type_rc != PJ_SUCCESS) - return qos_type_rc; + return qos_type_rc; return PJ_SUCCESS; } PJ_DEF(pj_status_t) pj_sock_apply_qos2( pj_sock_t sock, - pj_qos_type qos_type, - const pj_qos_params *qos_params, - unsigned log_level, - const char *log_sender, - const char *sock_name) + pj_qos_type qos_type, + const pj_qos_params *qos_params, + unsigned log_level, + const char *log_sender, + const char *sock_name) { pj_qos_params qos_params_buf, *qos_params_copy = NULL; if (qos_params) { - pj_memcpy(&qos_params_buf, qos_params, sizeof(*qos_params)); - qos_params_copy = &qos_params_buf; + pj_memcpy(&qos_params_buf, qos_params, sizeof(*qos_params)); + qos_params_copy = &qos_params_buf; } return pj_sock_apply_qos(sock, qos_type, qos_params_copy, - log_level, log_sender, sock_name); + log_level, log_sender, sock_name); } diff --git a/pjlib/src/pj/sock_qos_darwin.c b/pjlib/src/pj/sock_qos_darwin.c index faa9231629..fc5802121c 100644 --- a/pjlib/src/pj/sock_qos_darwin.c +++ b/pjlib/src/pj/sock_qos_darwin.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -36,38 +35,38 @@ static pj_status_t sock_set_net_service_type(pj_sock_t sock, int val) pj_status_t status; status = pj_sock_setsockopt(sock, pj_SOL_SOCKET(), SO_NET_SERVICE_TYPE, - &val, sizeof(val)); + &val, sizeof(val)); if (status == PJ_STATUS_FROM_OS(OSERR_ENOPROTOOPT)) - status = PJ_ENOTSUP; + status = PJ_ENOTSUP; return status; } #endif static pj_status_t sock_set_net_service_type_type(pj_sock_t sock, - pj_qos_type type) + pj_qos_type type) { #ifdef SO_NET_SERVICE_TYPE int val = NET_SERVICE_TYPE_BE; switch (type) { - case PJ_QOS_TYPE_BEST_EFFORT: - val = NET_SERVICE_TYPE_BE; - break; - case PJ_QOS_TYPE_BACKGROUND: - val = NET_SERVICE_TYPE_BK; - break; - case PJ_QOS_TYPE_SIGNALLING: - val = NET_SERVICE_TYPE_SIG; - break; - case PJ_QOS_TYPE_VIDEO: - val = NET_SERVICE_TYPE_VI; - break; - case PJ_QOS_TYPE_VOICE: - case PJ_QOS_TYPE_CONTROL: - default: - val = NET_SERVICE_TYPE_VO; - break; + case PJ_QOS_TYPE_BEST_EFFORT: + val = NET_SERVICE_TYPE_BE; + break; + case PJ_QOS_TYPE_BACKGROUND: + val = NET_SERVICE_TYPE_BK; + break; + case PJ_QOS_TYPE_SIGNALLING: + val = NET_SERVICE_TYPE_SIG; + break; + case PJ_QOS_TYPE_VIDEO: + val = NET_SERVICE_TYPE_VI; + break; + case PJ_QOS_TYPE_VOICE: + case PJ_QOS_TYPE_CONTROL: + default: + val = NET_SERVICE_TYPE_VO; + break; } return sock_set_net_service_type(sock, val); @@ -77,7 +76,7 @@ static pj_status_t sock_set_net_service_type_type(pj_sock_t sock, } static pj_status_t sock_set_net_service_type_params(pj_sock_t sock, - pj_qos_params *param) + pj_qos_params *param) { #ifdef SO_NET_SERVICE_TYPE pj_status_t status; @@ -91,52 +90,52 @@ static pj_status_t sock_set_net_service_type_params(pj_sock_t sock, * - iOS 10 SDK, sys/socket.h */ if (val == -1 && param->flags & PJ_QOS_PARAM_HAS_DSCP) { - if (param->dscp_val == 0) /* DF */ - val = NET_SERVICE_TYPE_BE; - else if (param->dscp_val < 0x10) /* CS1, AF11, AF12, AF13 */ - val = NET_SERVICE_TYPE_BK; - else if (param->dscp_val == 0x10) /* CS2 */ - val = NET_SERVICE_TYPE_OAM; - else if (param->dscp_val < 0x18) /* AF21, AF22, AF23 */ - val = NET_SERVICE_TYPE_RD; - else if (param->dscp_val < 0x20) /* CS3, AF31, AF32, AF33 */ - val = NET_SERVICE_TYPE_AV; - else if (param->dscp_val == 0x20) /* CS4 */ - val = NET_SERVICE_TYPE_RD; - else if (param->dscp_val < 0x28) /* AF41, AF42, AF43 */ - val = NET_SERVICE_TYPE_VI; - else if (param->dscp_val == 0x28) /* CS5 */ - val = NET_SERVICE_TYPE_SIG; - else - val = NET_SERVICE_TYPE_VO; /* VOICE-ADMIT, EF, CS6, etc. */ + if (param->dscp_val == 0) /* DF */ + val = NET_SERVICE_TYPE_BE; + else if (param->dscp_val < 0x10) /* CS1, AF11, AF12, AF13 */ + val = NET_SERVICE_TYPE_BK; + else if (param->dscp_val == 0x10) /* CS2 */ + val = NET_SERVICE_TYPE_OAM; + else if (param->dscp_val < 0x18) /* AF21, AF22, AF23 */ + val = NET_SERVICE_TYPE_RD; + else if (param->dscp_val < 0x20) /* CS3, AF31, AF32, AF33 */ + val = NET_SERVICE_TYPE_AV; + else if (param->dscp_val == 0x20) /* CS4 */ + val = NET_SERVICE_TYPE_RD; + else if (param->dscp_val < 0x28) /* AF41, AF42, AF43 */ + val = NET_SERVICE_TYPE_VI; + else if (param->dscp_val == 0x28) /* CS5 */ + val = NET_SERVICE_TYPE_SIG; + else + val = NET_SERVICE_TYPE_VO; /* VOICE-ADMIT, EF, CS6, etc. */ } if (val == -1 && param->flags & PJ_QOS_PARAM_HAS_WMM) { - switch (param->wmm_prio) { - case PJ_QOS_WMM_PRIO_BULK_EFFORT: - val = NET_SERVICE_TYPE_BE; - break; - case PJ_QOS_WMM_PRIO_BULK: - val = NET_SERVICE_TYPE_BK; - break; - case PJ_QOS_WMM_PRIO_VIDEO: - val = NET_SERVICE_TYPE_VI; - break; - case PJ_QOS_WMM_PRIO_VOICE: - val = NET_SERVICE_TYPE_VO; - break; - } + switch (param->wmm_prio) { + case PJ_QOS_WMM_PRIO_BULK_EFFORT: + val = NET_SERVICE_TYPE_BE; + break; + case PJ_QOS_WMM_PRIO_BULK: + val = NET_SERVICE_TYPE_BK; + break; + case PJ_QOS_WMM_PRIO_VIDEO: + val = NET_SERVICE_TYPE_VI; + break; + case PJ_QOS_WMM_PRIO_VOICE: + val = NET_SERVICE_TYPE_VO; + break; + } } if (val == -1) { - pj_qos_type type; + pj_qos_type type; - status = pj_qos_get_type(param, &type); + status = pj_qos_get_type(param, &type); - if (status == PJ_SUCCESS) - return sock_set_net_service_type_type(sock, type); + if (status == PJ_SUCCESS) + return sock_set_net_service_type_type(sock, type); - val = NET_SERVICE_TYPE_BE; + val = NET_SERVICE_TYPE_BE; } return sock_set_net_service_type(sock, val); @@ -152,39 +151,39 @@ static pj_status_t sock_set_ip_ds(pj_sock_t sock, pj_qos_params *param) PJ_ASSERT_RETURN(param, PJ_EINVAL); if (param->flags & PJ_QOS_PARAM_HAS_DSCP) { - /* We need to know if the socket is IPv4 or IPv6 */ - pj_sockaddr sa; - int salen = sizeof(salen); - - /* Value is dscp_val << 2 */ - int val = (param->dscp_val << 2); - - status = pj_sock_getsockname(sock, &sa, &salen); - if (status != PJ_SUCCESS) - return status; - - if (sa.addr.sa_family == pj_AF_INET()) { - /* In IPv4, the DS field goes in the TOS field */ - status = pj_sock_setsockopt(sock, pj_SOL_IP(), pj_IP_TOS(), - &val, sizeof(val)); - } else if (sa.addr.sa_family == pj_AF_INET6()) { - /* In IPv6, the DS field goes in the Traffic Class field */ - status = pj_sock_setsockopt(sock, pj_SOL_IPV6(), - pj_IPV6_TCLASS(), - &val, sizeof(val)); - } else - status = PJ_EINVAL; - - if (status != PJ_SUCCESS) { - param->flags &= ~(PJ_QOS_PARAM_HAS_DSCP); - } + /* We need to know if the socket is IPv4 or IPv6 */ + pj_sockaddr sa; + int salen = sizeof(salen); + + /* Value is dscp_val << 2 */ + int val = (param->dscp_val << 2); + + status = pj_sock_getsockname(sock, &sa, &salen); + if (status != PJ_SUCCESS) + return status; + + if (sa.addr.sa_family == pj_AF_INET()) { + /* In IPv4, the DS field goes in the TOS field */ + status = pj_sock_setsockopt(sock, pj_SOL_IP(), pj_IP_TOS(), + &val, sizeof(val)); + } else if (sa.addr.sa_family == pj_AF_INET6()) { + /* In IPv6, the DS field goes in the Traffic Class field */ + status = pj_sock_setsockopt(sock, pj_SOL_IPV6(), + pj_IPV6_TCLASS(), + &val, sizeof(val)); + } else + status = PJ_EINVAL; + + if (status != PJ_SUCCESS) { + param->flags &= ~(PJ_QOS_PARAM_HAS_DSCP); + } } return status; } PJ_DEF(pj_status_t) pj_sock_set_qos_params(pj_sock_t sock, - pj_qos_params *param) + pj_qos_params *param) { pj_status_t status; @@ -192,7 +191,7 @@ PJ_DEF(pj_status_t) pj_sock_set_qos_params(pj_sock_t sock, /* No op? */ if (!param->flags) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Clear prio field since we don't support it */ param->flags &= ~(PJ_QOS_PARAM_HAS_SO_PRIO); @@ -200,13 +199,13 @@ PJ_DEF(pj_status_t) pj_sock_set_qos_params(pj_sock_t sock, /* Try SO_NET_SERVICE_TYPE */ status = sock_set_net_service_type_params(sock, param); if (status == PJ_SUCCESS) - return status; + return status; if (status != PJ_ENOTSUP) { - /* SO_NET_SERVICE_TYPE sets both DSCP and WMM */ - param->flags &= ~(PJ_QOS_PARAM_HAS_DSCP); - param->flags &= ~(PJ_QOS_PARAM_HAS_WMM); - return status; + /* SO_NET_SERVICE_TYPE sets both DSCP and WMM */ + param->flags &= ~(PJ_QOS_PARAM_HAS_DSCP); + param->flags &= ~(PJ_QOS_PARAM_HAS_WMM); + return status; } /* Fall back to IP_TOS/IPV6_TCLASS */ @@ -214,7 +213,7 @@ PJ_DEF(pj_status_t) pj_sock_set_qos_params(pj_sock_t sock, } PJ_DEF(pj_status_t) pj_sock_set_qos_type(pj_sock_t sock, - pj_qos_type type) + pj_qos_type type) { pj_status_t status; pj_qos_params param; @@ -222,12 +221,12 @@ PJ_DEF(pj_status_t) pj_sock_set_qos_type(pj_sock_t sock, /* Try SO_NET_SERVICE_TYPE */ status = sock_set_net_service_type_type(sock, type); if (status == PJ_SUCCESS || status != PJ_ENOTSUP) - return status; + return status; /* Fall back to IP_TOS/IPV6_TCLASS */ status = pj_qos_get_params(type, ¶m); if (status != PJ_SUCCESS) - return status; + return status; return sock_set_ip_ds(sock, ¶m); } @@ -241,16 +240,16 @@ static pj_status_t sock_get_net_service_type(pj_sock_t sock, int *p_val) PJ_ASSERT_RETURN(p_val, PJ_EINVAL); status = pj_sock_getsockopt(sock, pj_SOL_SOCKET(), SO_NET_SERVICE_TYPE, - p_val, &optlen); + p_val, &optlen); if (status == PJ_STATUS_FROM_OS(OSERR_ENOPROTOOPT)) - status = PJ_ENOTSUP; + status = PJ_ENOTSUP; return status; } #endif static pj_status_t sock_get_net_service_type_type(pj_sock_t sock, - pj_qos_type *p_type) + pj_qos_type *p_type) { #ifdef SO_NET_SERVICE_TYPE pj_status_t status; @@ -260,28 +259,28 @@ static pj_status_t sock_get_net_service_type_type(pj_sock_t sock, status = sock_get_net_service_type(sock, &val); if (status == PJ_SUCCESS) { - switch (val) { - default: - case NET_SERVICE_TYPE_BE: - *p_type = PJ_QOS_TYPE_BEST_EFFORT; - break; - case NET_SERVICE_TYPE_BK: - *p_type = PJ_QOS_TYPE_BACKGROUND; - break; - case NET_SERVICE_TYPE_SIG: - *p_type = PJ_QOS_TYPE_SIGNALLING; - break; - case NET_SERVICE_TYPE_VI: - case NET_SERVICE_TYPE_RV: - case NET_SERVICE_TYPE_AV: - case NET_SERVICE_TYPE_OAM: - case NET_SERVICE_TYPE_RD: - *p_type = PJ_QOS_TYPE_VIDEO; - break; - case NET_SERVICE_TYPE_VO: - *p_type = PJ_QOS_TYPE_VOICE; - break; - } + switch (val) { + default: + case NET_SERVICE_TYPE_BE: + *p_type = PJ_QOS_TYPE_BEST_EFFORT; + break; + case NET_SERVICE_TYPE_BK: + *p_type = PJ_QOS_TYPE_BACKGROUND; + break; + case NET_SERVICE_TYPE_SIG: + *p_type = PJ_QOS_TYPE_SIGNALLING; + break; + case NET_SERVICE_TYPE_VI: + case NET_SERVICE_TYPE_RV: + case NET_SERVICE_TYPE_AV: + case NET_SERVICE_TYPE_OAM: + case NET_SERVICE_TYPE_RD: + *p_type = PJ_QOS_TYPE_VIDEO; + break; + case NET_SERVICE_TYPE_VO: + *p_type = PJ_QOS_TYPE_VOICE; + break; + } } return status; @@ -291,7 +290,7 @@ static pj_status_t sock_get_net_service_type_type(pj_sock_t sock, } static pj_status_t sock_get_net_service_type_params(pj_sock_t sock, - pj_qos_params *p_param) + pj_qos_params *p_param) { #ifdef SO_NET_SERVICE_TYPE pj_status_t status; @@ -301,63 +300,63 @@ static pj_status_t sock_get_net_service_type_params(pj_sock_t sock, status = sock_get_net_service_type(sock, &val); if (status == PJ_SUCCESS) { - pj_bzero(p_param, sizeof(*p_param)); - - /* Note: these are just educated guesses, chosen for symmetry with - * sock_set_net_service_type_params: we can't know the actual values - * chosen by the OS, or even if DSCP/WMM are used at all. - * - * The source for mapping DSCP to WMM is: - * - IETF draft-szigeti-tsvwg-ieee-802-11e-01 - */ - switch (val) { - default: - case NET_SERVICE_TYPE_BE: - p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; - p_param->dscp_val = 0; /* DF */ - p_param->wmm_prio = PJ_QOS_WMM_PRIO_BULK_EFFORT; /* AC_BE */ - break; - case NET_SERVICE_TYPE_BK: - p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; - p_param->dscp_val = 0x08; /* CS1 */ - p_param->wmm_prio = PJ_QOS_WMM_PRIO_BULK; /* AC_BK */ - break; - case NET_SERVICE_TYPE_SIG: - p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; - p_param->dscp_val = 0x28; /* CS5 */ - p_param->wmm_prio = PJ_QOS_WMM_PRIO_VIDEO; /* AC_VI */ - break; - case NET_SERVICE_TYPE_VI: - p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; - p_param->dscp_val = 0x22; /* AF41 */ - p_param->wmm_prio = PJ_QOS_WMM_PRIO_VIDEO; /* AC_VI */ - break; - case NET_SERVICE_TYPE_VO: - p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; - p_param->dscp_val = 0x30; /* CS6 */ - p_param->wmm_prio = PJ_QOS_WMM_PRIO_VOICE; /* AC_VO */ - break; - case NET_SERVICE_TYPE_RV: - p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; - p_param->dscp_val = 0x22; /* AF41 */ - p_param->wmm_prio = PJ_QOS_WMM_PRIO_VIDEO; /* AC_VI */ - break; - case NET_SERVICE_TYPE_AV: - p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; - p_param->dscp_val = 0x18; /* CS3 */ - p_param->wmm_prio = PJ_QOS_WMM_PRIO_VIDEO; /* AC_VI */ - break; - case NET_SERVICE_TYPE_OAM: - p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; - p_param->dscp_val = 0x10; /* CS2 */ - p_param->wmm_prio = PJ_QOS_WMM_PRIO_BULK_EFFORT; /* AC_BE */ - break; - case NET_SERVICE_TYPE_RD: - p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; - p_param->dscp_val = 0x20; /* CS4 */ - p_param->wmm_prio = PJ_QOS_WMM_PRIO_VIDEO; /* AC_VI */ - break; - } + pj_bzero(p_param, sizeof(*p_param)); + + /* Note: these are just educated guesses, chosen for symmetry with + * sock_set_net_service_type_params: we can't know the actual values + * chosen by the OS, or even if DSCP/WMM are used at all. + * + * The source for mapping DSCP to WMM is: + * - IETF draft-szigeti-tsvwg-ieee-802-11e-01 + */ + switch (val) { + default: + case NET_SERVICE_TYPE_BE: + p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; + p_param->dscp_val = 0; /* DF */ + p_param->wmm_prio = PJ_QOS_WMM_PRIO_BULK_EFFORT; /* AC_BE */ + break; + case NET_SERVICE_TYPE_BK: + p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; + p_param->dscp_val = 0x08; /* CS1 */ + p_param->wmm_prio = PJ_QOS_WMM_PRIO_BULK; /* AC_BK */ + break; + case NET_SERVICE_TYPE_SIG: + p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; + p_param->dscp_val = 0x28; /* CS5 */ + p_param->wmm_prio = PJ_QOS_WMM_PRIO_VIDEO; /* AC_VI */ + break; + case NET_SERVICE_TYPE_VI: + p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; + p_param->dscp_val = 0x22; /* AF41 */ + p_param->wmm_prio = PJ_QOS_WMM_PRIO_VIDEO; /* AC_VI */ + break; + case NET_SERVICE_TYPE_VO: + p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; + p_param->dscp_val = 0x30; /* CS6 */ + p_param->wmm_prio = PJ_QOS_WMM_PRIO_VOICE; /* AC_VO */ + break; + case NET_SERVICE_TYPE_RV: + p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; + p_param->dscp_val = 0x22; /* AF41 */ + p_param->wmm_prio = PJ_QOS_WMM_PRIO_VIDEO; /* AC_VI */ + break; + case NET_SERVICE_TYPE_AV: + p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; + p_param->dscp_val = 0x18; /* CS3 */ + p_param->wmm_prio = PJ_QOS_WMM_PRIO_VIDEO; /* AC_VI */ + break; + case NET_SERVICE_TYPE_OAM: + p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; + p_param->dscp_val = 0x10; /* CS2 */ + p_param->wmm_prio = PJ_QOS_WMM_PRIO_BULK_EFFORT; /* AC_BE */ + break; + case NET_SERVICE_TYPE_RD: + p_param->flags = PJ_QOS_PARAM_HAS_DSCP | PJ_QOS_PARAM_HAS_WMM; + p_param->dscp_val = 0x20; /* CS4 */ + p_param->wmm_prio = PJ_QOS_WMM_PRIO_VIDEO; /* AC_VI */ + break; + } } return status; @@ -367,7 +366,7 @@ static pj_status_t sock_get_net_service_type_params(pj_sock_t sock, } PJ_DEF(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, - pj_qos_params *p_param) + pj_qos_params *p_param) { pj_status_t status; int val, optlen; @@ -381,32 +380,32 @@ PJ_DEF(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, /* Try SO_NET_SERVICE_TYPE */ status = sock_get_net_service_type_params(sock, p_param); if (status != PJ_ENOTSUP) - return status; + return status; /* Fall back to IP_TOS/IPV6_TCLASS */ status = pj_sock_getsockname(sock, &sa, &salen); if (status != PJ_SUCCESS) - return status; + return status; optlen = sizeof(val); if (sa.addr.sa_family == pj_AF_INET()) { - status = pj_sock_getsockopt(sock, pj_SOL_IP(), pj_IP_TOS(), - &val, &optlen); + status = pj_sock_getsockopt(sock, pj_SOL_IP(), pj_IP_TOS(), + &val, &optlen); } else if (sa.addr.sa_family == pj_AF_INET6()) { - status = pj_sock_getsockopt(sock, pj_SOL_IPV6(), pj_IPV6_TCLASS(), - &val, &optlen); + status = pj_sock_getsockopt(sock, pj_SOL_IPV6(), pj_IPV6_TCLASS(), + &val, &optlen); } else - status = PJ_EINVAL; + status = PJ_EINVAL; if (status == PJ_SUCCESS) { - p_param->flags |= PJ_QOS_PARAM_HAS_DSCP; - p_param->dscp_val = (pj_uint8_t)(val >> 2); + p_param->flags |= PJ_QOS_PARAM_HAS_DSCP; + p_param->dscp_val = (pj_uint8_t)(val >> 2); } return status; } PJ_DEF(pj_status_t) pj_sock_get_qos_type(pj_sock_t sock, - pj_qos_type *p_type) + pj_qos_type *p_type) { pj_qos_params param; pj_status_t status; @@ -415,13 +414,13 @@ PJ_DEF(pj_status_t) pj_sock_get_qos_type(pj_sock_t sock, status = sock_get_net_service_type_type(sock, p_type); if (status != PJ_ENOTSUP) - return status; + return status; status = pj_sock_get_qos_params(sock, ¶m); if (status != PJ_SUCCESS) - return status; + return status; return pj_qos_get_type(¶m, p_type); } -#endif /* PJ_QOS_IMPLEMENTATION */ +#endif /* PJ_QOS_IMPLEMENTATION */ diff --git a/pjlib/src/pj/sock_qos_dummy.c b/pjlib/src/pj/sock_qos_dummy.c index ad0dab36e2..62ab182303 100644 --- a/pjlib/src/pj/sock_qos_dummy.c +++ b/pjlib/src/pj/sock_qos_dummy.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * @@ -29,48 +28,48 @@ PJ_DEF(pj_status_t) pj_sock_set_qos_params(pj_sock_t sock, - pj_qos_params *param) + pj_qos_params *param) { PJ_UNUSED_ARG(sock); PJ_UNUSED_ARG(param); PJ_LOG(4,(THIS_FILE, "pj_sock_set_qos_params() is not implemented " - "for this platform")); + "for this platform")); return PJ_ENOTSUP; } PJ_DEF(pj_status_t) pj_sock_set_qos_type(pj_sock_t sock, - pj_qos_type type) + pj_qos_type type) { PJ_UNUSED_ARG(sock); PJ_UNUSED_ARG(type); PJ_LOG(4,(THIS_FILE, "pj_sock_set_qos_type() is not implemented " - "for this platform")); + "for this platform")); return PJ_ENOTSUP; } PJ_DEF(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, - pj_qos_params *p_param) + pj_qos_params *p_param) { PJ_UNUSED_ARG(sock); PJ_UNUSED_ARG(p_param); PJ_LOG(4,(THIS_FILE, "pj_sock_get_qos_params() is not implemented " - "for this platform")); + "for this platform")); return PJ_ENOTSUP; } PJ_DEF(pj_status_t) pj_sock_get_qos_type(pj_sock_t sock, - pj_qos_type *p_type) + pj_qos_type *p_type) { PJ_UNUSED_ARG(sock); PJ_UNUSED_ARG(p_type); PJ_LOG(4,(THIS_FILE, "pj_sock_get_qos_type() is not implemented " - "for this platform")); + "for this platform")); return PJ_ENOTSUP; } -#endif /* PJ_QOS_DUMMY */ +#endif /* PJ_QOS_DUMMY */ diff --git a/pjlib/src/pj/sock_qos_symbian.cpp b/pjlib/src/pj/sock_qos_symbian.cpp index 7d350ed6bb..48773e8839 100644 --- a/pjlib/src/pj/sock_qos_symbian.cpp +++ b/pjlib/src/pj/sock_qos_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * @@ -20,7 +19,7 @@ #include "os_symbian.h" PJ_DEF(pj_status_t) pj_sock_set_qos_params(pj_sock_t sock, - pj_qos_params *param) + pj_qos_params *param) { PJ_ASSERT_RETURN(sock!=0 && sock!=PJ_INVALID_SOCKET, PJ_EINVAL); @@ -32,35 +31,35 @@ PJ_DEF(pj_status_t) pj_sock_set_qos_params(pj_sock_t sock, param->flags &= ~(PJ_QOS_PARAM_HAS_SO_PRIO | PJ_QOS_PARAM_HAS_WMM); if (param->flags & PJ_QOS_PARAM_HAS_DSCP) { - TInt err; - - err = rsock.SetOpt(KSoIpTOS, KProtocolInetIp, - (param->dscp_val << 2)); - if (err != KErrNone) { - last_err = PJ_RETURN_OS_ERROR(err); - param->flags &= ~(PJ_QOS_PARAM_HAS_DSCP); - } + TInt err; + + err = rsock.SetOpt(KSoIpTOS, KProtocolInetIp, + (param->dscp_val << 2)); + if (err != KErrNone) { + last_err = PJ_RETURN_OS_ERROR(err); + param->flags &= ~(PJ_QOS_PARAM_HAS_DSCP); + } } return param->flags ? PJ_SUCCESS : last_err; } PJ_DEF(pj_status_t) pj_sock_set_qos_type(pj_sock_t sock, - pj_qos_type type) + pj_qos_type type) { pj_qos_params param; pj_status_t status; status = pj_qos_get_params(type, ¶m); if (status != PJ_SUCCESS) - return status; + return status; return pj_sock_set_qos_params(sock, ¶m); } PJ_DEF(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, - pj_qos_params *p_param) + pj_qos_params *p_param) { PJ_ASSERT_RETURN(sock!=0 && sock!=PJ_INVALID_SOCKET, PJ_EINVAL); @@ -72,23 +71,23 @@ PJ_DEF(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, err = rsock.GetOpt(KSoIpTOS, KProtocolInetIp, dscp); if (err == KErrNone) { - p_param->flags |= PJ_QOS_PARAM_HAS_DSCP; - p_param->dscp_val = (dscp >> 2); - return PJ_SUCCESS; + p_param->flags |= PJ_QOS_PARAM_HAS_DSCP; + p_param->dscp_val = (dscp >> 2); + return PJ_SUCCESS; } else { - return PJ_RETURN_OS_ERROR(err); + return PJ_RETURN_OS_ERROR(err); } } PJ_DEF(pj_status_t) pj_sock_get_qos_type(pj_sock_t sock, - pj_qos_type *p_type) + pj_qos_type *p_type) { pj_qos_params param; pj_status_t status; status = pj_sock_get_qos_params(sock, ¶m); if (status != PJ_SUCCESS) - return status; + return status; return pj_qos_get_type(¶m, p_type); } diff --git a/pjlib/src/pj/sock_qos_wm.c b/pjlib/src/pj/sock_qos_wm.c index 46eb3e2511..8c90fc2974 100644 --- a/pjlib/src/pj/sock_qos_wm.c +++ b/pjlib/src/pj/sock_qos_wm.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * @@ -41,18 +40,18 @@ static const int dscp_map[] = }; PJ_DEF(pj_status_t) pj_sock_set_qos_params(pj_sock_t sock, - pj_qos_params *param) + pj_qos_params *param) { PJ_UNUSED_ARG(sock); PJ_UNUSED_ARG(param); PJ_LOG(4,(THIS_FILE, "pj_sock_set_qos_params() is not implemented " - "for this platform")); + "for this platform")); return PJ_ENOTSUP; } PJ_DEF(pj_status_t) pj_sock_set_qos_type(pj_sock_t sock, - pj_qos_type type) + pj_qos_type type) { int value; @@ -60,23 +59,23 @@ PJ_DEF(pj_status_t) pj_sock_set_qos_type(pj_sock_t sock, value = dscp_map[type]; return pj_sock_setsockopt(sock, IPPROTO_IP, IP_DSCP_TRAFFIC_TYPE, - &value, sizeof(value)); + &value, sizeof(value)); } PJ_DEF(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, - pj_qos_params *p_param) + pj_qos_params *p_param) { PJ_UNUSED_ARG(sock); PJ_UNUSED_ARG(p_param); PJ_LOG(4,(THIS_FILE, "pj_sock_get_qos_params() is not implemented " - "for this platform")); + "for this platform")); return PJ_ENOTSUP; } PJ_DEF(pj_status_t) pj_sock_get_qos_type(pj_sock_t sock, - pj_qos_type *p_type) + pj_qos_type *p_type) { pj_status_t status; int value, optlen; @@ -85,19 +84,19 @@ PJ_DEF(pj_status_t) pj_sock_get_qos_type(pj_sock_t sock, optlen = sizeof(value); value = 0; status = pj_sock_getsockopt(sock, IPPROTO_IP, IP_DSCP_TRAFFIC_TYPE, - &value, &optlen); + &value, &optlen); if (status != PJ_SUCCESS) - return status; + return status; *p_type = PJ_QOS_TYPE_BEST_EFFORT; for (i=0; i @@ -36,9 +35,9 @@ # pragma warning(disable: 4389) // Signed/unsigned mismatch in FD_* #endif -#define PART_FDSET(ps) ((fd_set*)&ps->data[1]) -#define PART_FDSET_OR_NULL(ps) (ps ? PART_FDSET(ps) : NULL) -#define PART_COUNT(ps) (ps->data[0]) +#define PART_FDSET(ps) ((fd_set*)&ps->data[1]) +#define PART_FDSET_OR_NULL(ps) (ps ? PART_FDSET(ps) : NULL) +#define PART_COUNT(ps) (ps->data[0]) PJ_DEF(void) PJ_FD_ZERO(pj_fd_set_t *fdsetp) { @@ -87,10 +86,10 @@ PJ_DEF(pj_size_t) PJ_FD_COUNT(const pj_fd_set_t *fdsetp) } PJ_DEF(int) pj_sock_select( int n, - pj_fd_set_t *readfds, - pj_fd_set_t *writefds, - pj_fd_set_t *exceptfds, - const pj_time_val *timeout) + pj_fd_set_t *readfds, + pj_fd_set_t *writefds, + pj_fd_set_t *exceptfds, + const pj_time_val *timeout) { struct timeval os_timeout, *p_os_timeout; @@ -100,14 +99,14 @@ PJ_DEF(int) pj_sock_select( int n, PJ_EBUG); if (timeout) { - os_timeout.tv_sec = timeout->sec; - os_timeout.tv_usec = timeout->msec * 1000; - p_os_timeout = &os_timeout; + os_timeout.tv_sec = timeout->sec; + os_timeout.tv_usec = timeout->msec * 1000; + p_os_timeout = &os_timeout; } else { - p_os_timeout = NULL; + p_os_timeout = NULL; } return select(n, PART_FDSET_OR_NULL(readfds), PART_FDSET_OR_NULL(writefds), - PART_FDSET_OR_NULL(exceptfds), p_os_timeout); + PART_FDSET_OR_NULL(exceptfds), p_os_timeout); } diff --git a/pjlib/src/pj/sock_select_symbian.cpp b/pjlib/src/pj/sock_select_symbian.cpp index 8ac6948d5f..352b15948d 100644 --- a/pjlib/src/pj/sock_select_symbian.cpp +++ b/pjlib/src/pj/sock_select_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -26,8 +25,8 @@ struct symbian_fd_set { - unsigned count; - CPjSocket *sock[PJ_IOQUEUE_MAX_HANDLES]; + unsigned count; + CPjSocket *sock[PJ_IOQUEUE_MAX_HANDLES]; }; @@ -53,11 +52,11 @@ PJ_DEF(void) PJ_FD_CLR(pj_sock_t fd, pj_fd_set_t *fdsetp) unsigned i; for (i=0; icount; ++i) { - if (fds->sock[i] == (CPjSocket*)fd) { - pj_array_erase(fds->sock, sizeof(fds->sock[0]), fds->count, i); - --fds->count; - return; - } + if (fds->sock[i] == (CPjSocket*)fd) { + pj_array_erase(fds->sock, sizeof(fds->sock[0]), fds->count, i); + --fds->count; + return; + } } } @@ -68,9 +67,9 @@ PJ_DEF(pj_bool_t) PJ_FD_ISSET(pj_sock_t fd, const pj_fd_set_t *fdsetp) unsigned i; for (i=0; icount; ++i) { - if (fds->sock[i] == (CPjSocket*)fd) { - return PJ_TRUE; - } + if (fds->sock[i] == (CPjSocket*)fd) { + return PJ_TRUE; + } } return PJ_FALSE; @@ -84,10 +83,10 @@ PJ_DEF(pj_size_t) PJ_FD_COUNT(const pj_fd_set_t *fdsetp) PJ_DEF(int) pj_sock_select( int n, - pj_fd_set_t *readfds, - pj_fd_set_t *writefds, - pj_fd_set_t *exceptfds, - const pj_time_val *timeout) + pj_fd_set_t *readfds, + pj_fd_set_t *writefds, + pj_fd_set_t *exceptfds, + const pj_time_val *timeout) { CPjTimeoutTimer *pjTimer; unsigned i; @@ -97,66 +96,66 @@ PJ_DEF(int) pj_sock_select( int n, PJ_UNUSED_ARG(exceptfds); if (timeout) { - pjTimer = PjSymbianOS::Instance()->SelectTimeoutTimer(); - pjTimer->StartTimer(timeout->sec*1000 + timeout->msec); + pjTimer = PjSymbianOS::Instance()->SelectTimeoutTimer(); + pjTimer->StartTimer(timeout->sec*1000 + timeout->msec); } else { - pjTimer = NULL; + pjTimer = NULL; } /* Scan for readable sockets */ if (readfds) { - symbian_fd_set *fds = (symbian_fd_set *)readfds; + symbian_fd_set *fds = (symbian_fd_set *)readfds; - do { - /* Scan sockets for readily available data */ - for (i=0; icount; ++i) { - CPjSocket *pjsock = fds->sock[i]; + do { + /* Scan sockets for readily available data */ + for (i=0; icount; ++i) { + CPjSocket *pjsock = fds->sock[i]; - if (pjsock->Reader()) { - if (pjsock->Reader()->HasData() && !pjsock->Reader()->IsActive()) { + if (pjsock->Reader()) { + if (pjsock->Reader()->HasData() && !pjsock->Reader()->IsActive()) { - /* Found socket with data ready */ - PJ_FD_ZERO(readfds); - PJ_FD_SET((pj_sock_t)pjsock, readfds); + /* Found socket with data ready */ + PJ_FD_ZERO(readfds); + PJ_FD_SET((pj_sock_t)pjsock, readfds); - /* Cancel timer, if any */ - if (pjTimer) { - pjTimer->Cancel(); - } + /* Cancel timer, if any */ + if (pjTimer) { + pjTimer->Cancel(); + } - /* Clear writable and exception fd_set */ - if (writefds) - PJ_FD_ZERO(writefds); - if (exceptfds) - PJ_FD_ZERO(exceptfds); + /* Clear writable and exception fd_set */ + if (writefds) + PJ_FD_ZERO(writefds); + if (exceptfds) + PJ_FD_ZERO(exceptfds); - return 1; + return 1; - } else if (!pjsock->Reader()->IsActive()) - pjsock->Reader()->StartRecvFrom(); + } else if (!pjsock->Reader()->IsActive()) + pjsock->Reader()->StartRecvFrom(); - } else { - pjsock->CreateReader(); - pjsock->Reader()->StartRecvFrom(); - } - } + } else { + pjsock->CreateReader(); + pjsock->Reader()->StartRecvFrom(); + } + } - PjSymbianOS::Instance()->WaitForActiveObjects(); + PjSymbianOS::Instance()->WaitForActiveObjects(); - } while (pjTimer==NULL || !pjTimer->HasTimedOut()); + } while (pjTimer==NULL || !pjTimer->HasTimedOut()); } /* Timeout */ if (readfds) - PJ_FD_ZERO(readfds); + PJ_FD_ZERO(readfds); if (writefds) - PJ_FD_ZERO(writefds); + PJ_FD_ZERO(writefds); if (exceptfds) - PJ_FD_ZERO(exceptfds); + PJ_FD_ZERO(exceptfds); return 0; } diff --git a/pjlib/src/pj/sock_symbian.cpp b/pjlib/src/pj/sock_symbian.cpp index e72bbdad79..00c303fe52 100644 --- a/pjlib/src/pj/sock_symbian.cpp +++ b/pjlib/src/pj/sock_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,36 +30,36 @@ /* * Address families. */ -const pj_uint16_t PJ_AF_UNSPEC = KAFUnspec; -const pj_uint16_t PJ_AF_UNIX = 0xFFFF; -const pj_uint16_t PJ_AF_INET = KAfInet; -const pj_uint16_t PJ_AF_INET6 = KAfInet6; -const pj_uint16_t PJ_AF_PACKET = 0xFFFF; -const pj_uint16_t PJ_AF_IRDA = 0xFFFF; +const pj_uint16_t PJ_AF_UNSPEC = KAFUnspec; +const pj_uint16_t PJ_AF_UNIX = 0xFFFF; +const pj_uint16_t PJ_AF_INET = KAfInet; +const pj_uint16_t PJ_AF_INET6 = KAfInet6; +const pj_uint16_t PJ_AF_PACKET = 0xFFFF; +const pj_uint16_t PJ_AF_IRDA = 0xFFFF; /* * Socket types conversion. * The values here are indexed based on pj_sock_type */ const pj_uint16_t PJ_SOCK_STREAM= KSockStream; -const pj_uint16_t PJ_SOCK_DGRAM = KSockDatagram; -const pj_uint16_t PJ_SOCK_RAW = 0xFFFF; -const pj_uint16_t PJ_SOCK_RDM = 0xFFFF; +const pj_uint16_t PJ_SOCK_DGRAM = KSockDatagram; +const pj_uint16_t PJ_SOCK_RAW = 0xFFFF; +const pj_uint16_t PJ_SOCK_RDM = 0xFFFF; /* we don't support setsockopt(), these are just dummy values */ -const pj_uint16_t PJ_SOL_SOCKET = 0xFFFF; -const pj_uint16_t PJ_SOL_IP = 0xFFFF; -const pj_uint16_t PJ_SOL_TCP = 0xFFFF; -const pj_uint16_t PJ_SOL_UDP = 0xFFFF; -const pj_uint16_t PJ_SOL_IPV6 = 0xFFFF; +const pj_uint16_t PJ_SOL_SOCKET = 0xFFFF; +const pj_uint16_t PJ_SOL_IP = 0xFFFF; +const pj_uint16_t PJ_SOL_TCP = 0xFFFF; +const pj_uint16_t PJ_SOL_UDP = 0xFFFF; +const pj_uint16_t PJ_SOL_IPV6 = 0xFFFF; const pj_uint16_t PJ_SO_NOSIGPIPE = 0xFFFF; /* TOS */ -const pj_uint16_t PJ_IP_TOS = 0; -const pj_uint16_t PJ_IPTOS_LOWDELAY = 0; -const pj_uint16_t PJ_IPTOS_THROUGHPUT = 0; -const pj_uint16_t PJ_IPTOS_RELIABILITY = 0; -const pj_uint16_t PJ_IPTOS_MINCOST = 0; +const pj_uint16_t PJ_IP_TOS = 0; +const pj_uint16_t PJ_IPTOS_LOWDELAY = 0; +const pj_uint16_t PJ_IPTOS_THROUGHPUT = 0; +const pj_uint16_t PJ_IPTOS_RELIABILITY = 0; +const pj_uint16_t PJ_IPTOS_MINCOST = 0; /* Misc */ const pj_uint16_t PJ_TCP_NODELAY = 0xFFFF; @@ -80,8 +79,8 @@ const pj_uint16_t PJ_IP_ADD_MEMBERSHIP = 0xFFFF; const pj_uint16_t PJ_IP_DROP_MEMBERSHIP = 0xFFFF; /* Flags */ -const int PJ_MSG_OOB = 0; -const int PJ_MSG_PEEK = KSockReadPeek; +const int PJ_MSG_OOB = 0; +const int PJ_MSG_PEEK = KSockReadPeek; const int PJ_MSG_DONTROUTE = 0; ///////////////////////////////////////////////////////////////////////////// @@ -108,9 +107,9 @@ CPjSocketReader *CPjSocket::CreateReader(unsigned max_len) void CPjSocket::DestroyReader() { if (sockReader_) { - sockReader_->Cancel(); - delete sockReader_; - sockReader_ = NULL; + sockReader_->Cancel(); + delete sockReader_; + sockReader_ = NULL; } } @@ -156,18 +155,18 @@ CPjSocketReader::~CPjSocketReader() } void CPjSocketReader::StartRecv(void (*cb)(void *key), - void *key, - TDes8 *aDesc, - TUint flags) + void *key, + TDes8 *aDesc, + TUint flags) { StartRecvFrom(cb, key, aDesc, flags, NULL); } void CPjSocketReader::StartRecvFrom(void (*cb)(void *key), - void *key, - TDes8 *aDesc, - TUint flags, - TSockAddr *fromAddr) + void *key, + TDes8 *aDesc, + TUint flags, + TSockAddr *fromAddr) { readCb_ = cb; key_ = key; @@ -193,7 +192,7 @@ void CPjSocketReader::RunL() key_ = NULL; if (old_cb) { - (*old_cb)(old_key); + (*old_cb)(old_key); } } @@ -202,24 +201,24 @@ void CPjSocketReader::RunL() void CPjSocketReader::ReadData(TDes8 &aDesc, TInetAddr *addr) { if (isDatagram_) - aDesc.Zero(); + aDesc.Zero(); if (buffer_.Length() == 0) - return; + return; TInt size_to_copy = aDesc.MaxLength() - aDesc.Length(); if (size_to_copy > buffer_.Length()) - size_to_copy = buffer_.Length(); + size_to_copy = buffer_.Length(); aDesc.Append(buffer_.Ptr(), size_to_copy); if (isDatagram_) - buffer_.Zero(); + buffer_.Zero(); else - buffer_.Delete(0, size_to_copy); + buffer_.Delete(0, size_to_copy); if (addr) - *addr = recvAddr_; + *addr = recvAddr_; } @@ -283,7 +282,7 @@ PJ_DEF(pj_uint32_t) pj_htonl(pj_uint32_t hostlong) */ PJ_DEF(char*) pj_inet_ntoa(pj_in_addr inaddr) { - static char str8[PJ_INET_ADDRSTRLEN]; + static char str8[PJ_INET_ADDRSTRLEN]; TBuf str16(0); /* (Symbian IP address is in host byte order) */ @@ -291,7 +290,7 @@ PJ_DEF(char*) pj_inet_ntoa(pj_in_addr inaddr) temp_addr.Output(str16); return pj_unicode_to_ansi((const wchar_t*)str16.PtrZ(), str16.Length(), - str8, sizeof(str8)); + str8, sizeof(str8)); } /* @@ -310,12 +309,12 @@ PJ_DEF(int) pj_inet_aton(const pj_str_t *cp, pj_in_addr *inp) inp->s_addr = PJ_INADDR_NONE; /* Caution: - * this function might be called with cp->slen >= 16 + * this function might be called with cp->slen >= 16 * (i.e. when called with hostname to check if it's an IP addr). */ PJ_ASSERT_RETURN(cp && cp->slen && inp, 0); if (cp->slen >= 16) { - return 0; + return 0; } char tempaddr8[MAXIPLEN]; @@ -324,19 +323,19 @@ PJ_DEF(int) pj_inet_aton(const pj_str_t *cp, pj_in_addr *inp) wchar_t tempaddr16[MAXIPLEN]; pj_ansi_to_unicode(tempaddr8, pj_ansi_strlen(tempaddr8), - tempaddr16, sizeof(tempaddr16)); + tempaddr16, sizeof(tempaddr16)); TBuf ip_addr((const TText*)tempaddr16); TInetAddr addr; addr.Init(KAfInet); if (addr.Input(ip_addr) == KErrNone) { - /* Success (Symbian IP address is in host byte order) */ - inp->s_addr = pj_htonl(addr.Address()); - return 1; + /* Success (Symbian IP address is in host byte order) */ + inp->s_addr = pj_htonl(addr.Address()); + return 1; } else { - /* Error */ - return 0; + /* Error */ + return 0; } } @@ -354,15 +353,15 @@ PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) * compatible with pj_inet_aton() */ if (af==PJ_AF_INET) { - ((pj_in_addr*)dst)->s_addr = PJ_INADDR_NONE; + ((pj_in_addr*)dst)->s_addr = PJ_INADDR_NONE; } /* Caution: - * this function might be called with cp->slen >= 46 + * this function might be called with cp->slen >= 46 * (i.e. when called with hostname to check if it's an IP addr). */ if (src->slen >= PJ_INET6_ADDRSTRLEN) { - return PJ_ENAMETOOLONG; + return PJ_ENAMETOOLONG; } pj_memcpy(tempaddr, src->ptr, src->slen); @@ -371,28 +370,28 @@ PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) wchar_t tempaddr16[PJ_INET6_ADDRSTRLEN]; pj_ansi_to_unicode(tempaddr, pj_ansi_strlen(tempaddr), - tempaddr16, sizeof(tempaddr16)); + tempaddr16, sizeof(tempaddr16)); TBuf ip_addr((const TText*)tempaddr16); TInetAddr addr; addr.Init(KAfInet6); if (addr.Input(ip_addr) == KErrNone) { - if (af==PJ_AF_INET) { - /* Success (Symbian IP address is in host byte order) */ - pj_uint32_t ip = pj_htonl(addr.Address()); - pj_memcpy(dst, &ip, 4); - } else if (af==PJ_AF_INET6) { - const TIp6Addr & ip6 = addr.Ip6Address(); - pj_memcpy(dst, ip6.u.iAddr8, 16); - } else { - pj_assert(!"Unexpected!"); - return PJ_EBUG; - } - return PJ_SUCCESS; + if (af==PJ_AF_INET) { + /* Success (Symbian IP address is in host byte order) */ + pj_uint32_t ip = pj_htonl(addr.Address()); + pj_memcpy(dst, &ip, 4); + } else if (af==PJ_AF_INET6) { + const TIp6Addr & ip6 = addr.Ip6Address(); + pj_memcpy(dst, ip6.u.iAddr8, 16); + } else { + pj_assert(!"Unexpected!"); + return PJ_EBUG; + } + return PJ_SUCCESS; } else { - /* Error */ - return PJ_EINVAL; + /* Error */ + return PJ_EINVAL; } } @@ -400,7 +399,7 @@ PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) * Convert IPv4/IPv6 address to text. */ PJ_DEF(pj_status_t) pj_inet_ntop(int af, const void *src, - char *dst, int size) + char *dst, int size) { PJ_ASSERT_RETURN(src && dst && size, PJ_EINVAL); @@ -409,41 +408,41 @@ PJ_DEF(pj_status_t) pj_inet_ntop(int af, const void *src, if (af==PJ_AF_INET) { - TBuf str16; - pj_in_addr inaddr; + TBuf str16; + pj_in_addr inaddr; - if (size < PJ_INET_ADDRSTRLEN) - return PJ_ETOOSMALL; + if (size < PJ_INET_ADDRSTRLEN) + return PJ_ETOOSMALL; - pj_memcpy(&inaddr, src, 4); + pj_memcpy(&inaddr, src, 4); - /* Symbian IP address is in host byte order */ - TInetAddr temp_addr((TUint32)pj_ntohl(inaddr.s_addr), (TUint)0); - temp_addr.Output(str16); + /* Symbian IP address is in host byte order */ + TInetAddr temp_addr((TUint32)pj_ntohl(inaddr.s_addr), (TUint)0); + temp_addr.Output(str16); - pj_unicode_to_ansi((const wchar_t*)str16.PtrZ(), str16.Length(), - dst, size); - return PJ_SUCCESS; + pj_unicode_to_ansi((const wchar_t*)str16.PtrZ(), str16.Length(), + dst, size); + return PJ_SUCCESS; } else if (af==PJ_AF_INET6) { - TBuf str16; + TBuf str16; - if (size < PJ_INET6_ADDRSTRLEN) - return PJ_ETOOSMALL; + if (size < PJ_INET6_ADDRSTRLEN) + return PJ_ETOOSMALL; - TIp6Addr ip6; - pj_memcpy(ip6.u.iAddr8, src, 16); + TIp6Addr ip6; + pj_memcpy(ip6.u.iAddr8, src, 16); - TInetAddr temp_addr(ip6, (TUint)0); - temp_addr.Output(str16); + TInetAddr temp_addr(ip6, (TUint)0); + temp_addr.Output(str16); - pj_unicode_to_ansi((const wchar_t*)str16.PtrZ(), str16.Length(), - dst, size); - return PJ_SUCCESS; + pj_unicode_to_ansi((const wchar_t*)str16.PtrZ(), str16.Length(), + dst, size); + return PJ_SUCCESS; } else { - pj_assert(!"Unsupport address family"); - return PJ_EINVAL; + pj_assert(!"Unsupport address family"); + return PJ_EINVAL; } } @@ -459,19 +458,19 @@ PJ_DEF(const pj_str_t*) pj_gethostname(void) PJ_CHECK_STACK(); if (hostname.ptr == NULL) { - RHostResolver &resv = PjSymbianOS::Instance()->GetResolver(PJ_AF_INET); - TRequestStatus reqStatus; - THostName tmpName; + RHostResolver &resv = PjSymbianOS::Instance()->GetResolver(PJ_AF_INET); + TRequestStatus reqStatus; + THostName tmpName; - // Return empty hostname if access point is marked as down by app. - PJ_SYMBIAN_CHECK_CONNECTION2(&hostname); + // Return empty hostname if access point is marked as down by app. + PJ_SYMBIAN_CHECK_CONNECTION2(&hostname); - resv.GetHostName(tmpName, reqStatus); - User::WaitForRequest(reqStatus); + resv.GetHostName(tmpName, reqStatus); + User::WaitForRequest(reqStatus); - hostname.ptr = pj_unicode_to_ansi((const wchar_t*)tmpName.Ptr(), tmpName.Length(), - buf, sizeof(buf)); - hostname.slen = tmpName.Length(); + hostname.ptr = pj_unicode_to_ansi((const wchar_t*)tmpName.Ptr(), tmpName.Length(), + buf, sizeof(buf)); + hostname.slen = tmpName.Length(); } return &hostname; } @@ -480,9 +479,9 @@ PJ_DEF(const pj_str_t*) pj_gethostname(void) * Create new socket/endpoint for communication and returns a descriptor. */ PJ_DEF(pj_status_t) pj_sock_socket(int af, - int type, - int proto, - pj_sock_t *p_sock) + int type, + int proto, + pj_sock_t *p_sock) { TInt rc; @@ -496,24 +495,24 @@ PJ_DEF(pj_status_t) pj_sock_socket(int af, /* Set proto if none is specified. */ if (proto == 0) { - if (type == pj_SOCK_STREAM()) - proto = KProtocolInetTcp; - else if (type == pj_SOCK_DGRAM()) - proto = KProtocolInetUdp; + if (type == pj_SOCK_STREAM()) + proto = KProtocolInetTcp; + else if (type == pj_SOCK_DGRAM()) + proto = KProtocolInetUdp; } /* Create Symbian RSocket */ RSocket rSock; if (PjSymbianOS::Instance()->Connection()) - rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), - af, type, proto, - *PjSymbianOS::Instance()->Connection()); + rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), + af, type, proto, + *PjSymbianOS::Instance()->Connection()); else - rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), - af, type, proto); + rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), + af, type, proto); if (rc != KErrNone) - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR(rc); /* Wrap Symbian RSocket into PJLIB's CPjSocket, and return to caller */ @@ -528,8 +527,8 @@ PJ_DEF(pj_status_t) pj_sock_socket(int af, * Bind socket. */ PJ_DEF(pj_status_t) pj_sock_bind( pj_sock_t sock, - const pj_sockaddr_t *addr, - int len) + const pj_sockaddr_t *addr, + int len) { pj_status_t status; TInt rc; @@ -543,7 +542,7 @@ PJ_DEF(pj_status_t) pj_sock_bind( pj_sock_t sock, TInetAddr inetAddr; status = PjSymbianOS::pj2Addr(*(pj_sockaddr*)addr, len, inetAddr); if (status != PJ_SUCCESS) - return status; + return status; // Get the RSocket instance RSocket &rSock = ((CPjSocket*)sock)->Socket(); @@ -559,8 +558,8 @@ PJ_DEF(pj_status_t) pj_sock_bind( pj_sock_t sock, * Bind socket. */ PJ_DEF(pj_status_t) pj_sock_bind_in( pj_sock_t sock, - pj_uint32_t addr32, - pj_uint16_t port) + pj_uint32_t addr32, + pj_uint16_t port) { pj_sockaddr_in addr; @@ -596,13 +595,13 @@ PJ_DEF(pj_status_t) pj_sock_close(pj_sock_t sock) * Get remote's name. */ PJ_DEF(pj_status_t) pj_sock_getpeername( pj_sock_t sock, - pj_sockaddr_t *addr, - int *namelen) + pj_sockaddr_t *addr, + int *namelen) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sock && addr && namelen && - *namelen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); + *namelen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); CPjSocket *pjSock = (CPjSocket*)sock; RSocket &rSock = pjSock->Socket(); @@ -620,13 +619,13 @@ PJ_DEF(pj_status_t) pj_sock_getpeername( pj_sock_t sock, * Get socket name. */ PJ_DEF(pj_status_t) pj_sock_getsockname( pj_sock_t sock, - pj_sockaddr_t *addr, - int *namelen) + pj_sockaddr_t *addr, + int *namelen) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sock && addr && namelen && - *namelen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); + *namelen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); CPjSocket *pjSock = (CPjSocket*)sock; RSocket &rSock = pjSock->Socket(); @@ -641,9 +640,9 @@ PJ_DEF(pj_status_t) pj_sock_getsockname( pj_sock_t sock, * Send data */ PJ_DEF(pj_status_t) pj_sock_send(pj_sock_t sock, - const void *buf, - pj_ssize_t *len, - unsigned flags) + const void *buf, + pj_ssize_t *len, + unsigned flags) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sock && buf && len, PJ_EINVAL); @@ -665,10 +664,10 @@ PJ_DEF(pj_status_t) pj_sock_send(pj_sock_t sock, User::WaitForRequest(reqStatus); if (reqStatus.Int()==KErrNone) { - //*len = (TInt) sentLen.Length(); - return PJ_SUCCESS; + //*len = (TInt) sentLen.Length(); + return PJ_SUCCESS; } else - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR(reqStatus.Int()); } @@ -676,11 +675,11 @@ PJ_DEF(pj_status_t) pj_sock_send(pj_sock_t sock, * Send data. */ PJ_DEF(pj_status_t) pj_sock_sendto(pj_sock_t sock, - const void *buf, - pj_ssize_t *len, - unsigned flags, - const pj_sockaddr_t *to, - int tolen) + const void *buf, + pj_ssize_t *len, + unsigned flags, + const pj_sockaddr_t *to, + int tolen) { pj_status_t status; @@ -699,7 +698,7 @@ PJ_DEF(pj_status_t) pj_sock_sendto(pj_sock_t sock, TInetAddr inetAddr; status = PjSymbianOS::pj2Addr(*(pj_sockaddr*)to, tolen, inetAddr); if (status != PJ_SUCCESS) - return status; + return status; TPtrC8 data((const TUint8*)buf, (TInt)*len); TRequestStatus reqStatus; @@ -709,20 +708,20 @@ PJ_DEF(pj_status_t) pj_sock_sendto(pj_sock_t sock, User::WaitForRequest(reqStatus); if (reqStatus.Int()==KErrNone) { - //For some reason TSockXfrLength is not returning correctly! - //*len = (TInt) sentLen.Length(); - return PJ_SUCCESS; + //For some reason TSockXfrLength is not returning correctly! + //*len = (TInt) sentLen.Length(); + return PJ_SUCCESS; } else - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR(reqStatus.Int()); } /* * Receive data. */ PJ_DEF(pj_status_t) pj_sock_recv(pj_sock_t sock, - void *buf, - pj_ssize_t *len, - unsigned flags) + void *buf, + pj_ssize_t *len, + unsigned flags) { PJ_CHECK_STACK(); @@ -735,21 +734,21 @@ PJ_DEF(pj_status_t) pj_sock_recv(pj_sock_t sock, CPjSocket *pjSock = (CPjSocket*)sock; if (pjSock->Reader()) { - CPjSocketReader *reader = pjSock->Reader(); + CPjSocketReader *reader = pjSock->Reader(); - while (reader->IsActive() && !reader->HasData()) { - User::WaitForAnyRequest(); - } + while (reader->IsActive() && !reader->HasData()) { + User::WaitForAnyRequest(); + } - if (reader->HasData()) { - TPtr8 data((TUint8*)buf, (TInt)*len); - TInetAddr inetAddr; + if (reader->HasData()) { + TPtr8 data((TUint8*)buf, (TInt)*len); + TInetAddr inetAddr; - reader->ReadData(data, &inetAddr); + reader->ReadData(data, &inetAddr); - *len = data.Length(); - return PJ_SUCCESS; - } + *len = data.Length(); + return PJ_SUCCESS; + } } TRequestStatus reqStatus; @@ -757,23 +756,23 @@ PJ_DEF(pj_status_t) pj_sock_recv(pj_sock_t sock, TPtr8 data((TUint8*)buf, (TInt)*len, (TInt)*len); if (pjSock->IsDatagram()) { - pjSock->Socket().Recv(data, flags, reqStatus); + pjSock->Socket().Recv(data, flags, reqStatus); } else { - // Using static like this is not pretty, but we don't need to use - // the value anyway, hence doing it like this is probably most - // optimal. - static TSockXfrLength len; - pjSock->Socket().RecvOneOrMore(data, flags, reqStatus, len); + // Using static like this is not pretty, but we don't need to use + // the value anyway, hence doing it like this is probably most + // optimal. + static TSockXfrLength len; + pjSock->Socket().RecvOneOrMore(data, flags, reqStatus, len); } User::WaitForRequest(reqStatus); if (reqStatus == KErrNone) { - //*len = (TInt)recvLen.Length(); - *len = data.Length(); - return PJ_SUCCESS; + //*len = (TInt)recvLen.Length(); + *len = data.Length(); + return PJ_SUCCESS; } else { - *len = -1; - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + *len = -1; + return PJ_RETURN_OS_ERROR(reqStatus.Int()); } } @@ -781,11 +780,11 @@ PJ_DEF(pj_status_t) pj_sock_recv(pj_sock_t sock, * Receive data. */ PJ_DEF(pj_status_t) pj_sock_recvfrom(pj_sock_t sock, - void *buf, - pj_ssize_t *len, - unsigned flags, - pj_sockaddr_t *from, - int *fromlen) + void *buf, + pj_ssize_t *len, + unsigned flags, + pj_sockaddr_t *from, + int *fromlen) { PJ_CHECK_STACK(); @@ -800,27 +799,27 @@ PJ_DEF(pj_status_t) pj_sock_recvfrom(pj_sock_t sock, RSocket &rSock = pjSock->Socket(); if (pjSock->Reader()) { - CPjSocketReader *reader = pjSock->Reader(); + CPjSocketReader *reader = pjSock->Reader(); - while (reader->IsActive() && !reader->HasData()) { - User::WaitForAnyRequest(); - } + while (reader->IsActive() && !reader->HasData()) { + User::WaitForAnyRequest(); + } - if (reader->HasData()) { - TPtr8 data((TUint8*)buf, (TInt)*len); - TInetAddr inetAddr; + if (reader->HasData()) { + TPtr8 data((TUint8*)buf, (TInt)*len); + TInetAddr inetAddr; - reader->ReadData(data, &inetAddr); + reader->ReadData(data, &inetAddr); - *len = data.Length(); + *len = data.Length(); - if (from && fromlen) { - return PjSymbianOS::Addr2pj(inetAddr, *(pj_sockaddr*)from, - fromlen); - } else { - return PJ_SUCCESS; - } - } + if (from && fromlen) { + return PjSymbianOS::Addr2pj(inetAddr, *(pj_sockaddr*)from, + fromlen); + } else { + return PJ_SUCCESS; + } + } } TInetAddr inetAddr; @@ -832,13 +831,13 @@ PJ_DEF(pj_status_t) pj_sock_recvfrom(pj_sock_t sock, User::WaitForRequest(reqStatus); if (reqStatus == KErrNone) { - //*len = (TInt)recvLen.Length(); - *len = data.Length(); - return PjSymbianOS::Addr2pj(inetAddr, *(pj_sockaddr*)from, fromlen); + //*len = (TInt)recvLen.Length(); + *len = data.Length(); + return PjSymbianOS::Addr2pj(inetAddr, *(pj_sockaddr*)from, fromlen); } else { - *len = -1; - *fromlen = -1; - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + *len = -1; + *fromlen = -1; + return PJ_RETURN_OS_ERROR(reqStatus.Int()); } } @@ -846,10 +845,10 @@ PJ_DEF(pj_status_t) pj_sock_recvfrom(pj_sock_t sock, * Get socket option. */ PJ_DEF(pj_status_t) pj_sock_getsockopt( pj_sock_t sock, - pj_uint16_t level, - pj_uint16_t optname, - void *optval, - int *optlen) + pj_uint16_t level, + pj_uint16_t optname, + void *optval, + int *optlen) { // Not supported for now. PJ_UNUSED_ARG(sock); @@ -864,10 +863,10 @@ PJ_DEF(pj_status_t) pj_sock_getsockopt( pj_sock_t sock, * Set socket option. */ PJ_DEF(pj_status_t) pj_sock_setsockopt( pj_sock_t sock, - pj_uint16_t level, - pj_uint16_t optname, - const void *optval, - int optlen) + pj_uint16_t level, + pj_uint16_t optname, + const void *optval, + int optlen) { // Not supported for now. PJ_UNUSED_ARG(sock); @@ -882,8 +881,8 @@ PJ_DEF(pj_status_t) pj_sock_setsockopt( pj_sock_t sock, * Connect socket. */ PJ_DEF(pj_status_t) pj_sock_connect( pj_sock_t sock, - const pj_sockaddr_t *addr, - int namelen) + const pj_sockaddr_t *addr, + int namelen) { pj_status_t status; @@ -891,7 +890,7 @@ PJ_DEF(pj_status_t) pj_sock_connect( pj_sock_t sock, PJ_ASSERT_RETURN(sock && addr && namelen, PJ_EINVAL); PJ_ASSERT_RETURN(((pj_sockaddr*)addr)->addr.sa_family == PJ_AF_INET, - PJ_EINVAL); + PJ_EINVAL); // Return failure if access point is marked as down by app. PJ_SYMBIAN_CHECK_CONNECTION(); @@ -904,16 +903,16 @@ PJ_DEF(pj_status_t) pj_sock_connect( pj_sock_t sock, status = PjSymbianOS::pj2Addr(*(pj_sockaddr*)addr, namelen, inetAddr); if (status != PJ_SUCCESS) - return status; + return status; rSock.Connect(inetAddr, reqStatus); User::WaitForRequest(reqStatus); if (reqStatus == KErrNone) { - pjSock->SetConnected(true); - return PJ_SUCCESS; + pjSock->SetConnected(true); + return PJ_SUCCESS; } else { - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR(reqStatus.Int()); } } @@ -923,7 +922,7 @@ PJ_DEF(pj_status_t) pj_sock_connect( pj_sock_t sock, */ #if PJ_HAS_TCP PJ_DEF(pj_status_t) pj_sock_shutdown( pj_sock_t sock, - int how) + int how) { PJ_CHECK_STACK(); @@ -934,11 +933,11 @@ PJ_DEF(pj_status_t) pj_sock_shutdown( pj_sock_t sock, RSocket::TShutdown aHow; if (how == PJ_SD_RECEIVE) - aHow = RSocket::EStopInput; + aHow = RSocket::EStopInput; else if (how == PJ_SHUT_WR) - aHow = RSocket::EStopOutput; + aHow = RSocket::EStopOutput; else - aHow = RSocket::ENormal; + aHow = RSocket::ENormal; TRequestStatus reqStatus; @@ -946,9 +945,9 @@ PJ_DEF(pj_status_t) pj_sock_shutdown( pj_sock_t sock, User::WaitForRequest(reqStatus); if (reqStatus == KErrNone) { - return PJ_SUCCESS; + return PJ_SUCCESS; } else { - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR(reqStatus.Int()); } } @@ -956,7 +955,7 @@ PJ_DEF(pj_status_t) pj_sock_shutdown( pj_sock_t sock, * Start listening to incoming connections. */ PJ_DEF(pj_status_t) pj_sock_listen( pj_sock_t sock, - int backlog) + int backlog) { PJ_CHECK_STACK(); @@ -968,9 +967,9 @@ PJ_DEF(pj_status_t) pj_sock_listen( pj_sock_t sock, TInt rc = rSock.Listen((TUint)backlog); if (rc == KErrNone) { - return PJ_SUCCESS; + return PJ_SUCCESS; } else { - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR(rc); } } @@ -978,9 +977,9 @@ PJ_DEF(pj_status_t) pj_sock_listen( pj_sock_t sock, * Accept incoming connections */ PJ_DEF(pj_status_t) pj_sock_accept( pj_sock_t serverfd, - pj_sock_t *newsock, - pj_sockaddr_t *addr, - int *addrlen) + pj_sock_t *newsock, + pj_sockaddr_t *addr, + int *addrlen) { PJ_CHECK_STACK(); @@ -1000,22 +999,22 @@ PJ_DEF(pj_status_t) pj_sock_accept( pj_sock_t serverfd, User::WaitForRequest(reqStatus); if (reqStatus != KErrNone) { - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR(reqStatus.Int()); } // Create PJ socket CPjSocket *newPjSock = new CPjSocket(pjSock->GetAf(), pjSock->GetSockType(), - newSock); + newSock); newPjSock->SetConnected(true); *newsock = (pj_sock_t) newPjSock; if (addr && addrlen) { - return pj_sock_getpeername(*newsock, addr, addrlen); + return pj_sock_getpeername(*newsock, addr, addrlen); } return PJ_SUCCESS; } -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ diff --git a/pjlib/src/pj/sock_uwp.cpp b/pjlib/src/pj/sock_uwp.cpp index 40250bf8de..f91cea1816 100644 --- a/pjlib/src/pj/sock_uwp.cpp +++ b/pjlib/src/pj/sock_uwp.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2016 Teluu Inc. (http://www.teluu.com) * @@ -25,7 +24,7 @@ #include #include -#define THIS_FILE "sock_uwp.cpp" +#define THIS_FILE "sock_uwp.cpp" #include "sock_uwp.h" @@ -33,19 +32,19 @@ * Address families conversion. * The values here are indexed based on pj_addr_family. */ -const pj_uint16_t PJ_AF_UNSPEC = AF_UNSPEC; -const pj_uint16_t PJ_AF_UNIX = AF_UNIX; -const pj_uint16_t PJ_AF_INET = AF_INET; -const pj_uint16_t PJ_AF_INET6 = AF_INET6; +const pj_uint16_t PJ_AF_UNSPEC = AF_UNSPEC; +const pj_uint16_t PJ_AF_UNIX = AF_UNIX; +const pj_uint16_t PJ_AF_INET = AF_INET; +const pj_uint16_t PJ_AF_INET6 = AF_INET6; #ifdef AF_PACKET -const pj_uint16_t PJ_AF_PACKET = AF_PACKET; +const pj_uint16_t PJ_AF_PACKET = AF_PACKET; #else -const pj_uint16_t PJ_AF_PACKET = 0xFFFF; +const pj_uint16_t PJ_AF_PACKET = 0xFFFF; #endif #ifdef AF_IRDA -const pj_uint16_t PJ_AF_IRDA = AF_IRDA; +const pj_uint16_t PJ_AF_IRDA = AF_IRDA; #else -const pj_uint16_t PJ_AF_IRDA = 0xFFFF; +const pj_uint16_t PJ_AF_IRDA = 0xFFFF; #endif /* @@ -53,82 +52,82 @@ const pj_uint16_t PJ_AF_IRDA = 0xFFFF; * The values here are indexed based on pj_sock_type */ const pj_uint16_t PJ_SOCK_STREAM= SOCK_STREAM; -const pj_uint16_t PJ_SOCK_DGRAM = SOCK_DGRAM; -const pj_uint16_t PJ_SOCK_RAW = SOCK_RAW; -const pj_uint16_t PJ_SOCK_RDM = SOCK_RDM; +const pj_uint16_t PJ_SOCK_DGRAM = SOCK_DGRAM; +const pj_uint16_t PJ_SOCK_RAW = SOCK_RAW; +const pj_uint16_t PJ_SOCK_RDM = SOCK_RDM; /* * Socket level values. */ -const pj_uint16_t PJ_SOL_SOCKET = SOL_SOCKET; +const pj_uint16_t PJ_SOL_SOCKET = SOL_SOCKET; #ifdef SOL_IP -const pj_uint16_t PJ_SOL_IP = SOL_IP; +const pj_uint16_t PJ_SOL_IP = SOL_IP; #elif (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64) -const pj_uint16_t PJ_SOL_IP = IPPROTO_IP; +const pj_uint16_t PJ_SOL_IP = IPPROTO_IP; #else -const pj_uint16_t PJ_SOL_IP = 0; +const pj_uint16_t PJ_SOL_IP = 0; #endif /* SOL_IP */ #if defined(SOL_TCP) -const pj_uint16_t PJ_SOL_TCP = SOL_TCP; +const pj_uint16_t PJ_SOL_TCP = SOL_TCP; #elif defined(IPPROTO_TCP) -const pj_uint16_t PJ_SOL_TCP = IPPROTO_TCP; +const pj_uint16_t PJ_SOL_TCP = IPPROTO_TCP; #elif (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64) -const pj_uint16_t PJ_SOL_TCP = IPPROTO_TCP; +const pj_uint16_t PJ_SOL_TCP = IPPROTO_TCP; #else -const pj_uint16_t PJ_SOL_TCP = 6; +const pj_uint16_t PJ_SOL_TCP = 6; #endif /* SOL_TCP */ #ifdef SOL_UDP -const pj_uint16_t PJ_SOL_UDP = SOL_UDP; +const pj_uint16_t PJ_SOL_UDP = SOL_UDP; #elif defined(IPPROTO_UDP) -const pj_uint16_t PJ_SOL_UDP = IPPROTO_UDP; +const pj_uint16_t PJ_SOL_UDP = IPPROTO_UDP; #elif (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64) -const pj_uint16_t PJ_SOL_UDP = IPPROTO_UDP; +const pj_uint16_t PJ_SOL_UDP = IPPROTO_UDP; #else -const pj_uint16_t PJ_SOL_UDP = 17; +const pj_uint16_t PJ_SOL_UDP = 17; #endif /* SOL_UDP */ #ifdef SOL_IPV6 -const pj_uint16_t PJ_SOL_IPV6 = SOL_IPV6; +const pj_uint16_t PJ_SOL_IPV6 = SOL_IPV6; #elif (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64) # if defined(IPPROTO_IPV6) || (_WIN32_WINNT >= 0x0501) -const pj_uint16_t PJ_SOL_IPV6 = IPPROTO_IPV6; +const pj_uint16_t PJ_SOL_IPV6 = IPPROTO_IPV6; # else -const pj_uint16_t PJ_SOL_IPV6 = 41; +const pj_uint16_t PJ_SOL_IPV6 = 41; # endif #else -const pj_uint16_t PJ_SOL_IPV6 = 41; +const pj_uint16_t PJ_SOL_IPV6 = 41; #endif /* SOL_IPV6 */ /* IP_TOS */ #ifdef IP_TOS -const pj_uint16_t PJ_IP_TOS = IP_TOS; +const pj_uint16_t PJ_IP_TOS = IP_TOS; #else -const pj_uint16_t PJ_IP_TOS = 1; +const pj_uint16_t PJ_IP_TOS = 1; #endif /* TOS settings (declared in netinet/ip.h) */ #ifdef IPTOS_LOWDELAY -const pj_uint16_t PJ_IPTOS_LOWDELAY = IPTOS_LOWDELAY; +const pj_uint16_t PJ_IPTOS_LOWDELAY = IPTOS_LOWDELAY; #else -const pj_uint16_t PJ_IPTOS_LOWDELAY = 0x10; +const pj_uint16_t PJ_IPTOS_LOWDELAY = 0x10; #endif #ifdef IPTOS_THROUGHPUT -const pj_uint16_t PJ_IPTOS_THROUGHPUT = IPTOS_THROUGHPUT; +const pj_uint16_t PJ_IPTOS_THROUGHPUT = IPTOS_THROUGHPUT; #else -const pj_uint16_t PJ_IPTOS_THROUGHPUT = 0x08; +const pj_uint16_t PJ_IPTOS_THROUGHPUT = 0x08; #endif #ifdef IPTOS_RELIABILITY -const pj_uint16_t PJ_IPTOS_RELIABILITY = IPTOS_RELIABILITY; +const pj_uint16_t PJ_IPTOS_RELIABILITY = IPTOS_RELIABILITY; #else -const pj_uint16_t PJ_IPTOS_RELIABILITY = 0x04; +const pj_uint16_t PJ_IPTOS_RELIABILITY = 0x04; #endif #ifdef IPTOS_MINCOST -const pj_uint16_t PJ_IPTOS_MINCOST = IPTOS_MINCOST; +const pj_uint16_t PJ_IPTOS_MINCOST = IPTOS_MINCOST; #else -const pj_uint16_t PJ_IPTOS_MINCOST = 0x02; +const pj_uint16_t PJ_IPTOS_MINCOST = 0x02; #endif @@ -166,9 +165,9 @@ const pj_uint16_t PJ_IP_DROP_MEMBERSHIP = 0xFFFF; #endif /* recv() and send() flags */ -const int PJ_MSG_OOB = MSG_OOB; -const int PJ_MSG_PEEK = MSG_PEEK; -const int PJ_MSG_DONTROUTE = MSG_DONTROUTE; +const int PJ_MSG_OOB = MSG_OOB; +const int PJ_MSG_PEEK = MSG_PEEK; +const int PJ_MSG_DONTROUTE = MSG_DONTROUTE; @@ -183,70 +182,70 @@ ref class PjUwpSocketDatagramRecvHelper sealed { internal: PjUwpSocketDatagramRecvHelper(PjUwpSocket* uwp_sock_) : - uwp_sock(uwp_sock_), avail_data_len(0), recv_args(nullptr) + uwp_sock(uwp_sock_), avail_data_len(0), recv_args(nullptr) { - recv_wait = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS); - event_token = uwp_sock->datagram_sock->MessageReceived += - ref new TypedEventHandler - (this, &PjUwpSocketDatagramRecvHelper::OnMessageReceived); + recv_wait = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS); + event_token = uwp_sock->datagram_sock->MessageReceived += + ref new TypedEventHandler + (this, &PjUwpSocketDatagramRecvHelper::OnMessageReceived); } void OnMessageReceived(DatagramSocket ^sender, - DatagramSocketMessageReceivedEventArgs ^args) + DatagramSocketMessageReceivedEventArgs ^args) { - try { - if (uwp_sock->sock_state >= SOCKSTATE_DISCONNECTED) - return; + try { + if (uwp_sock->sock_state >= SOCKSTATE_DISCONNECTED) + return; - recv_args = args; - avail_data_len = args->GetDataReader()->UnconsumedBufferLength; + recv_args = args; + avail_data_len = args->GetDataReader()->UnconsumedBufferLength; - if (uwp_sock->cb.on_read) { - (*uwp_sock->cb.on_read)(uwp_sock, avail_data_len); - } + if (uwp_sock->cb.on_read) { + (*uwp_sock->cb.on_read)(uwp_sock, avail_data_len); + } - WaitForSingleObjectEx(recv_wait, INFINITE, false); - } catch (...) {} + WaitForSingleObjectEx(recv_wait, INFINITE, false); + } catch (...) {} } pj_status_t ReadDataIfAvailable(void *buf, pj_ssize_t *len, - pj_sockaddr_t *from) + pj_sockaddr_t *from) { - if (avail_data_len <= 0) - return PJ_ENOTFOUND; + if (avail_data_len <= 0) + return PJ_ENOTFOUND; - if (*len < avail_data_len) - return PJ_ETOOSMALL; + if (*len < avail_data_len) + return PJ_ETOOSMALL; - // Read data - auto reader = recv_args->GetDataReader(); - auto buffer = reader->ReadBuffer(avail_data_len); - unsigned char *p; - GetRawBufferFromIBuffer(buffer, &p); - pj_memcpy((void*) buf, p, avail_data_len); - *len = avail_data_len; + // Read data + auto reader = recv_args->GetDataReader(); + auto buffer = reader->ReadBuffer(avail_data_len); + unsigned char *p; + GetRawBufferFromIBuffer(buffer, &p); + pj_memcpy((void*) buf, p, avail_data_len); + *len = avail_data_len; - // Get source address - wstr_addr_to_sockaddr(recv_args->RemoteAddress->CanonicalName->Data(), - recv_args->RemotePort->Data(), from); + // Get source address + wstr_addr_to_sockaddr(recv_args->RemoteAddress->CanonicalName->Data(), + recv_args->RemotePort->Data(), from); - // finally - avail_data_len = 0; - SetEvent(recv_wait); + // finally + avail_data_len = 0; + SetEvent(recv_wait); - return PJ_SUCCESS; + return PJ_SUCCESS; } private: ~PjUwpSocketDatagramRecvHelper() { - if (uwp_sock->datagram_sock) - uwp_sock->datagram_sock->MessageReceived -= event_token; + if (uwp_sock->datagram_sock) + uwp_sock->datagram_sock->MessageReceived -= event_token; - SetEvent(recv_wait); - CloseHandle(recv_wait); + SetEvent(recv_wait); + CloseHandle(recv_wait); } PjUwpSocket* uwp_sock; @@ -261,51 +260,51 @@ ref class PjUwpSocketListenerHelper sealed { internal: PjUwpSocketListenerHelper(PjUwpSocket* uwp_sock_) : - uwp_sock(uwp_sock_), conn_args(nullptr) + uwp_sock(uwp_sock_), conn_args(nullptr) { - conn_wait = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS); - event_token = uwp_sock->listener_sock->ConnectionReceived += - ref new TypedEventHandler - (this, &PjUwpSocketListenerHelper::OnConnectionReceived); + conn_wait = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS); + event_token = uwp_sock->listener_sock->ConnectionReceived += + ref new TypedEventHandler + (this, &PjUwpSocketListenerHelper::OnConnectionReceived); } void OnConnectionReceived(StreamSocketListener ^sender, - StreamSocketListenerConnectionReceivedEventArgs ^args) + StreamSocketListenerConnectionReceivedEventArgs ^args) { - try { - conn_args = args; + try { + conn_args = args; - if (uwp_sock->cb.on_accept) { - (*uwp_sock->cb.on_accept)(uwp_sock); - } + if (uwp_sock->cb.on_accept) { + (*uwp_sock->cb.on_accept)(uwp_sock); + } - WaitForSingleObjectEx(conn_wait, INFINITE, false); - } catch (Exception^ e) {} + WaitForSingleObjectEx(conn_wait, INFINITE, false); + } catch (Exception^ e) {} } pj_status_t GetAcceptedSocket(StreamSocket^& stream_sock) { - if (conn_args == nullptr) - return PJ_ENOTFOUND; + if (conn_args == nullptr) + return PJ_ENOTFOUND; - stream_sock = conn_args->Socket; + stream_sock = conn_args->Socket; - // finally - conn_args = nullptr; - SetEvent(conn_wait); + // finally + conn_args = nullptr; + SetEvent(conn_wait); - return PJ_SUCCESS; + return PJ_SUCCESS; } private: ~PjUwpSocketListenerHelper() { - if (uwp_sock->listener_sock) - uwp_sock->listener_sock->ConnectionReceived -= event_token; + if (uwp_sock->listener_sock) + uwp_sock->listener_sock->ConnectionReceived -= event_token; - SetEvent(conn_wait); - CloseHandle(conn_wait); + SetEvent(conn_wait); + CloseHandle(conn_wait); } PjUwpSocket* uwp_sock; @@ -347,11 +346,11 @@ PjUwpSocket* PjUwpSocket::CreateAcceptSocket(Windows::Networking::Sockets::Strea // Update local & remote address wstr_addr_to_sockaddr(stream_sock_->Information->RemoteAddress->CanonicalName->Data(), - stream_sock_->Information->RemotePort->Data(), - &new_sock->remote_addr); + stream_sock_->Information->RemotePort->Data(), + &new_sock->remote_addr); wstr_addr_to_sockaddr(stream_sock_->Information->LocalAddress->CanonicalName->Data(), - stream_sock_->Information->LocalPort->Data(), - &new_sock->local_addr); + stream_sock_->Information->LocalPort->Data(), + &new_sock->local_addr); return new_sock; } @@ -363,18 +362,18 @@ pj_status_t PjUwpSocket::InitSocket(enum PjUwpSocketType sock_type_) sock_type = sock_type_; if (sock_type == SOCKTYPE_LISTENER) { - listener_sock = ref new StreamSocketListener(); + listener_sock = ref new StreamSocketListener(); } else if (sock_type == SOCKTYPE_STREAM) { - stream_sock = ref new StreamSocket(); + stream_sock = ref new StreamSocket(); } else if (sock_type == SOCKTYPE_DATAGRAM) { - datagram_sock = ref new DatagramSocket(); + datagram_sock = ref new DatagramSocket(); } else { - pj_assert(!"Invalid socket type"); - return PJ_EINVAL; + pj_assert(!"Invalid socket type"); + return PJ_EINVAL; } if (sock_type == SOCKTYPE_DATAGRAM || sock_type == SOCKTYPE_STREAM) { - send_buffer = ref new Buffer(SEND_BUFFER_SIZE); + send_buffer = ref new Buffer(SEND_BUFFER_SIZE); } sock_state = SOCKSTATE_INITIALIZED; @@ -386,13 +385,13 @@ pj_status_t PjUwpSocket::InitSocket(enum PjUwpSocketType sock_type_) void PjUwpSocket::DeinitSocket() { if (stream_sock) { - concurrency::create_task(stream_sock->CancelIOAsync()).wait(); + concurrency::create_task(stream_sock->CancelIOAsync()).wait(); } if (datagram_sock && has_pending_send) { - concurrency::create_task(datagram_sock->CancelIOAsync()).wait(); + concurrency::create_task(datagram_sock->CancelIOAsync()).wait(); } if (listener_sock) { - concurrency::create_task(listener_sock->CancelIOAsync()).wait(); + concurrency::create_task(listener_sock->CancelIOAsync()).wait(); } while (has_pending_recv) pj_thread_sleep(10); @@ -412,53 +411,53 @@ pj_status_t PjUwpSocket::Bind(const pj_sockaddr_t *addr) * whether it is a stream or a listener. */ if (sock_state < SOCKSTATE_INITIALIZED) { - pj_sockaddr_cp(&local_addr, addr); - has_pending_bind = PJ_TRUE; - return PJ_SUCCESS; + pj_sockaddr_cp(&local_addr, addr); + has_pending_bind = PJ_TRUE; + return PJ_SUCCESS; } PJ_ASSERT_RETURN(sock_state == SOCKSTATE_INITIALIZED, PJ_EINVALIDOP); if (sock_type != SOCKTYPE_DATAGRAM && sock_type != SOCKTYPE_LISTENER) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; if (has_pending_bind) { - has_pending_bind = PJ_FALSE; - if (!addr) - addr = &local_addr; + has_pending_bind = PJ_FALSE; + if (!addr) + addr = &local_addr; } /* If no bound address is set, just return */ if (!pj_sockaddr_has_addr(addr) && !pj_sockaddr_get_port(addr)) - return PJ_SUCCESS; + return PJ_SUCCESS; if (addr != &local_addr) - pj_sockaddr_cp(&local_addr, addr); + pj_sockaddr_cp(&local_addr, addr); HRESULT err = 0; concurrency::create_task([this, addr, &err]() { - HostName ^host; - int port; - - sockaddr_to_hostname_port(addr, host, &port); - if (pj_sockaddr_has_addr(addr)) { - if (sock_type == SOCKTYPE_DATAGRAM) - return datagram_sock->BindEndpointAsync(host, port.ToString()); - else - return listener_sock->BindEndpointAsync(host, port.ToString()); - } else /* if (pj_sockaddr_get_port(addr) != 0) */ { - if (sock_type == SOCKTYPE_DATAGRAM) - return datagram_sock->BindServiceNameAsync(port.ToString()); - else - return listener_sock->BindServiceNameAsync(port.ToString()); - } + HostName ^host; + int port; + + sockaddr_to_hostname_port(addr, host, &port); + if (pj_sockaddr_has_addr(addr)) { + if (sock_type == SOCKTYPE_DATAGRAM) + return datagram_sock->BindEndpointAsync(host, port.ToString()); + else + return listener_sock->BindEndpointAsync(host, port.ToString()); + } else /* if (pj_sockaddr_get_port(addr) != 0) */ { + if (sock_type == SOCKTYPE_DATAGRAM) + return datagram_sock->BindServiceNameAsync(port.ToString()); + else + return listener_sock->BindServiceNameAsync(port.ToString()); + } }).then([this, &err](concurrency::task t) { - try { - if (!err) - t.get(); - } catch (Exception^ e) { - err = e->HResult; - } + try { + if (!err) + t.get(); + } catch (Exception^ e) { + err = e->HResult; + } }).get(); return (err? PJ_RETURN_OS_ERROR(err) : PJ_SUCCESS); @@ -468,10 +467,10 @@ pj_status_t PjUwpSocket::Bind(const pj_sockaddr_t *addr) pj_status_t PjUwpSocket::SendImp(const void *buf, pj_ssize_t *len) { if (has_pending_send) - return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL); + return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL); if (*len > (pj_ssize_t)send_buffer->Capacity) - return PJ_ETOOBIG; + return PJ_ETOOBIG; CopyToIBuffer((unsigned char*)buf, *len, send_buffer); send_buffer->Length = *len; @@ -479,52 +478,52 @@ pj_status_t PjUwpSocket::SendImp(const void *buf, pj_ssize_t *len) /* Blocking version */ if (is_blocking) { - pj_status_t status = PJ_SUCCESS; - concurrency::cancellation_token_source cts; - auto cts_token = cts.get_token(); - auto t = concurrency::create_task(socket_writer->StoreAsync(), - cts_token); - *len = cancel_after_timeout(t, cts, (unsigned int)WRITE_TIMEOUT). - then([cts_token, &status](concurrency::task t_) - { - int sent = 0; - try { - if (cts_token.is_canceled()) - status = PJ_ETIMEDOUT; - else - sent = t_.get(); - } catch (Exception^ e) { - status = PJ_RETURN_OS_ERROR(e->HResult); - } - return sent; - }).get(); - - return status; + pj_status_t status = PJ_SUCCESS; + concurrency::cancellation_token_source cts; + auto cts_token = cts.get_token(); + auto t = concurrency::create_task(socket_writer->StoreAsync(), + cts_token); + *len = cancel_after_timeout(t, cts, (unsigned int)WRITE_TIMEOUT). + then([cts_token, &status](concurrency::task t_) + { + int sent = 0; + try { + if (cts_token.is_canceled()) + status = PJ_ETIMEDOUT; + else + sent = t_.get(); + } catch (Exception^ e) { + status = PJ_RETURN_OS_ERROR(e->HResult); + } + return sent; + }).get(); + + return status; } /* Non-blocking version */ has_pending_send = PJ_TRUE; concurrency::create_task(socket_writer->StoreAsync()). - then([this](concurrency::task t_) + then([this](concurrency::task t_) { - try { - unsigned int l = t_.get(); - has_pending_send = PJ_FALSE; - - // invoke callback - if (cb.on_write) { - (*cb.on_write)(this, l); - } - } catch (...) { - has_pending_send = PJ_FALSE; - sock_state = SOCKSTATE_ERROR; - DeinitSocket(); - - // invoke callback - if (cb.on_write) { - (*cb.on_write)(this, -PJ_EUNKNOWN); - } - } + try { + unsigned int l = t_.get(); + has_pending_send = PJ_FALSE; + + // invoke callback + if (cb.on_write) { + (*cb.on_write)(this, l); + } + } catch (...) { + has_pending_send = PJ_FALSE; + sock_state = SOCKSTATE_ERROR; + DeinitSocket(); + + // invoke callback + if (cb.on_write) { + (*cb.on_write)(this, -PJ_EUNKNOWN); + } + } }); return PJ_SUCCESS; @@ -534,14 +533,14 @@ pj_status_t PjUwpSocket::SendImp(const void *buf, pj_ssize_t *len) pj_status_t PjUwpSocket::Send(const void *buf, pj_ssize_t *len) { if ((sock_type!=SOCKTYPE_STREAM && sock_type!=SOCKTYPE_DATAGRAM) || - (sock_state!=SOCKSTATE_CONNECTED)) + (sock_state!=SOCKSTATE_CONNECTED)) { - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; } /* Sending for SOCKTYPE_DATAGRAM is implemented in pj_sock_sendto() */ if (sock_type == SOCKTYPE_DATAGRAM) { - return SendTo(buf, len, &remote_addr); + return SendTo(buf, len, &remote_addr); } return SendImp(buf, len); @@ -549,19 +548,19 @@ pj_status_t PjUwpSocket::Send(const void *buf, pj_ssize_t *len) pj_status_t PjUwpSocket::SendTo(const void *buf, pj_ssize_t *len, - const pj_sockaddr_t *to) + const pj_sockaddr_t *to) { if (sock_type != SOCKTYPE_DATAGRAM || sock_state < SOCKSTATE_INITIALIZED - || sock_state >= SOCKSTATE_DISCONNECTED) + || sock_state >= SOCKSTATE_DISCONNECTED) { - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; } if (has_pending_send) - return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL); + return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL); if (*len > (pj_ssize_t)send_buffer->Capacity) - return PJ_ETOOBIG; + return PJ_ETOOBIG; HostName ^hostname; int port; @@ -570,32 +569,32 @@ pj_status_t PjUwpSocket::SendTo(const void *buf, pj_ssize_t *len, concurrency::cancellation_token_source cts; auto cts_token = cts.get_token(); auto t = concurrency::create_task(datagram_sock->GetOutputStreamAsync( - hostname, port.ToString()), cts_token); + hostname, port.ToString()), cts_token); pj_status_t status = PJ_SUCCESS; cancel_after_timeout(t, cts, (unsigned int)WRITE_TIMEOUT). - then([this, cts_token, &status](concurrency::task t_) + then([this, cts_token, &status](concurrency::task t_) { - try { - if (cts_token.is_canceled()) { - status = PJ_ETIMEDOUT; - } else { - IOutputStream^ outstream = t_.get(); - socket_writer = ref new DataWriter(outstream); - } - } catch (Exception^ e) { - status = PJ_RETURN_OS_ERROR(e->HResult); - } + try { + if (cts_token.is_canceled()) { + status = PJ_ETIMEDOUT; + } else { + IOutputStream^ outstream = t_.get(); + socket_writer = ref new DataWriter(outstream); + } + } catch (Exception^ e) { + status = PJ_RETURN_OS_ERROR(e->HResult); + } }).get(); if (status != PJ_SUCCESS) - return status; + return status; status = SendImp(buf, len); if ((status == PJ_SUCCESS || status == PJ_EPENDING) && - sock_state < SOCKSTATE_CONNECTED) + sock_state < SOCKSTATE_CONNECTED) { - sock_state = SOCKSTATE_CONNECTED; + sock_state = SOCKSTATE_CONNECTED; } return status; @@ -605,7 +604,7 @@ pj_status_t PjUwpSocket::SendTo(const void *buf, pj_ssize_t *len, int PjUwpSocket::ConsumeReadBuffer(void *buf, int max_len) { if (socket_reader->UnconsumedBufferLength == 0) - return 0; + return 0; int read_len = PJ_MIN((int)socket_reader->UnconsumedBufferLength,max_len); IBuffer^ buffer = socket_reader->ReadBuffer(read_len); @@ -619,50 +618,50 @@ pj_status_t PjUwpSocket::Recv(void *buf, pj_ssize_t *len) { /* Only for TCP, at least for now! */ if (sock_type == SOCKTYPE_DATAGRAM) - return PJ_ENOTSUP; + return PJ_ENOTSUP; if (sock_type != SOCKTYPE_STREAM || sock_state != SOCKSTATE_CONNECTED) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; if (has_pending_recv) - return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL); + return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL); /* First check if there is already some data in the read buffer */ if (buf) { - int avail_len = ConsumeReadBuffer(buf, *len); - if (avail_len > 0) { - *len = avail_len; - return PJ_SUCCESS; - } + int avail_len = ConsumeReadBuffer(buf, *len); + if (avail_len > 0) { + *len = avail_len; + return PJ_SUCCESS; + } } /* Blocking version */ if (is_blocking) { - pj_status_t status = PJ_SUCCESS; - concurrency::cancellation_token_source cts; - auto cts_token = cts.get_token(); - auto t = concurrency::create_task(socket_reader->LoadAsync(*len), - cts_token); - *len = cancel_after_timeout(t, cts, READ_TIMEOUT) - .then([this, len, buf, cts_token, &status] - (concurrency::task t_) - { - try { - if (cts_token.is_canceled()) { - status = PJ_ETIMEDOUT; - return 0; - } - t_.get(); - } catch (Exception^) { - status = PJ_ETIMEDOUT; - return 0; - } - - *len = ConsumeReadBuffer(buf, *len); - return (int)*len; - }).get(); - - return status; + pj_status_t status = PJ_SUCCESS; + concurrency::cancellation_token_source cts; + auto cts_token = cts.get_token(); + auto t = concurrency::create_task(socket_reader->LoadAsync(*len), + cts_token); + *len = cancel_after_timeout(t, cts, READ_TIMEOUT) + .then([this, len, buf, cts_token, &status] + (concurrency::task t_) + { + try { + if (cts_token.is_canceled()) { + status = PJ_ETIMEDOUT; + return 0; + } + t_.get(); + } catch (Exception^) { + status = PJ_ETIMEDOUT; + return 0; + } + + *len = ConsumeReadBuffer(buf, *len); + return (int)*len; + }).get(); + + return status; } /* Non-blocking version */ @@ -672,35 +671,35 @@ pj_status_t PjUwpSocket::Recv(void *buf, pj_ssize_t *len) has_pending_recv = PJ_TRUE; concurrency::create_task(socket_reader->LoadAsync(*len), cts_token) - .then([this, cts_token](concurrency::task t_) + .then([this, cts_token](concurrency::task t_) { - try { - if (cts_token.is_canceled()) { - has_pending_recv = PJ_FALSE; - - // invoke callback - if (cb.on_read) { - (*cb.on_read)(this, -PJ_EUNKNOWN); - } - return; - } - - t_.get(); - has_pending_recv = PJ_FALSE; - - // invoke callback - int read_len = socket_reader->UnconsumedBufferLength; - if (read_len > 0 && cb.on_read) { - (*cb.on_read)(this, read_len); - } - } catch (...) { - has_pending_recv = PJ_FALSE; - - // invoke callback - if (cb.on_read) { - (*cb.on_read)(this, -PJ_EUNKNOWN); - } - } + try { + if (cts_token.is_canceled()) { + has_pending_recv = PJ_FALSE; + + // invoke callback + if (cb.on_read) { + (*cb.on_read)(this, -PJ_EUNKNOWN); + } + return; + } + + t_.get(); + has_pending_recv = PJ_FALSE; + + // invoke callback + int read_len = socket_reader->UnconsumedBufferLength; + if (read_len > 0 && cb.on_read) { + (*cb.on_read)(this, read_len); + } + } catch (...) { + has_pending_recv = PJ_FALSE; + + // invoke callback + if (cb.on_read) { + (*cb.on_read)(this, -PJ_EUNKNOWN); + } + } }); return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL); @@ -708,41 +707,41 @@ pj_status_t PjUwpSocket::Recv(void *buf, pj_ssize_t *len) pj_status_t PjUwpSocket::RecvFrom(void *buf, pj_ssize_t *len, - pj_sockaddr_t *from) + pj_sockaddr_t *from) { if (sock_type != SOCKTYPE_DATAGRAM || sock_state < SOCKSTATE_INITIALIZED - || sock_state >= SOCKSTATE_DISCONNECTED) + || sock_state >= SOCKSTATE_DISCONNECTED) { - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; } /* Start receive, if not yet */ if (dgram_recv_helper == nullptr) { - dgram_recv_helper = ref new PjUwpSocketDatagramRecvHelper(this); + dgram_recv_helper = ref new PjUwpSocketDatagramRecvHelper(this); } /* Try to read any available data first */ if (buf || is_blocking) { - pj_status_t status; - status = dgram_recv_helper->ReadDataIfAvailable(buf, len, from); - if (status != PJ_ENOTFOUND) - return status; + pj_status_t status; + status = dgram_recv_helper->ReadDataIfAvailable(buf, len, from); + if (status != PJ_ENOTFOUND) + return status; } /* Blocking version */ if (is_blocking) { - int max_loop = 0; - pj_status_t status = PJ_ENOTFOUND; - while (status == PJ_ENOTFOUND && sock_state <= SOCKSTATE_CONNECTED) - { - status = dgram_recv_helper->ReadDataIfAvailable(buf, len, from); - if (status != PJ_SUCCESS) - pj_thread_sleep(100); - - if (++max_loop > 10) - return PJ_ETIMEDOUT; - } - return status; + int max_loop = 0; + pj_status_t status = PJ_ENOTFOUND; + while (status == PJ_ENOTFOUND && sock_state <= SOCKSTATE_CONNECTED) + { + status = dgram_recv_helper->ReadDataIfAvailable(buf, len, from); + if (status != PJ_SUCCESS) + pj_thread_sleep(100); + + if (++max_loop > 10) + return PJ_ETIMEDOUT; + } + return status; } /* For non-blocking version, just return PJ_EPENDING */ @@ -755,90 +754,90 @@ pj_status_t PjUwpSocket::Connect(const pj_sockaddr_t *addr) pj_status_t status; PJ_ASSERT_RETURN((sock_type == SOCKTYPE_UNKNOWN && sock_state == SOCKSTATE_NULL) || - (sock_type == SOCKTYPE_DATAGRAM && sock_state == SOCKSTATE_INITIALIZED), - PJ_EINVALIDOP); + (sock_type == SOCKTYPE_DATAGRAM && sock_state == SOCKSTATE_INITIALIZED), + PJ_EINVALIDOP); if (sock_type == SOCKTYPE_UNKNOWN) { - InitSocket(SOCKTYPE_STREAM); - // No need to check pending bind, no bind for TCP client socket + InitSocket(SOCKTYPE_STREAM); + // No need to check pending bind, no bind for TCP client socket } pj_sockaddr_cp(&remote_addr, addr); auto t = concurrency::create_task([this, addr]() { - HostName ^hostname; - int port; - sockaddr_to_hostname_port(&remote_addr, hostname, &port); - if (sock_type == SOCKTYPE_STREAM) - return stream_sock->ConnectAsync(hostname, port.ToString(), - SocketProtectionLevel::PlainSocket); - else - return datagram_sock->ConnectAsync(hostname, port.ToString()); + HostName ^hostname; + int port; + sockaddr_to_hostname_port(&remote_addr, hostname, &port); + if (sock_type == SOCKTYPE_STREAM) + return stream_sock->ConnectAsync(hostname, port.ToString(), + SocketProtectionLevel::PlainSocket); + else + return datagram_sock->ConnectAsync(hostname, port.ToString()); }).then([=](concurrency::task t_) { - try { - t_.get(); - - sock_state = SOCKSTATE_CONNECTED; - - // Update local & remote address - HostName^ local_address; - String^ local_port; - - if (sock_type == SOCKTYPE_STREAM) { - local_address = stream_sock->Information->LocalAddress; - local_port = stream_sock->Information->LocalPort; - - socket_reader = ref new DataReader(stream_sock->InputStream); - socket_writer = ref new DataWriter(stream_sock->OutputStream); - socket_reader->InputStreamOptions = InputStreamOptions::Partial; - } else { - local_address = datagram_sock->Information->LocalAddress; - local_port = datagram_sock->Information->LocalPort; - } - if (local_address && local_port) { - wstr_addr_to_sockaddr(local_address->CanonicalName->Data(), - local_port->Data(), - &local_addr); - } - - if (!is_blocking && cb.on_connect) { - (*cb.on_connect)(this, PJ_SUCCESS); - } - return (pj_status_t)PJ_SUCCESS; - - } catch (Exception^ ex) { - - SocketErrorStatus status = SocketError::GetStatus(ex->HResult); - - switch (status) - { - case SocketErrorStatus::UnreachableHost: - break; - case SocketErrorStatus::ConnectionTimedOut: - break; - case SocketErrorStatus::ConnectionRefused: - break; - default: - break; - } - - if (!is_blocking && cb.on_connect) { - (*cb.on_connect)(this, PJ_EUNKNOWN); - } - - return (pj_status_t)PJ_EUNKNOWN; - } + try { + t_.get(); + + sock_state = SOCKSTATE_CONNECTED; + + // Update local & remote address + HostName^ local_address; + String^ local_port; + + if (sock_type == SOCKTYPE_STREAM) { + local_address = stream_sock->Information->LocalAddress; + local_port = stream_sock->Information->LocalPort; + + socket_reader = ref new DataReader(stream_sock->InputStream); + socket_writer = ref new DataWriter(stream_sock->OutputStream); + socket_reader->InputStreamOptions = InputStreamOptions::Partial; + } else { + local_address = datagram_sock->Information->LocalAddress; + local_port = datagram_sock->Information->LocalPort; + } + if (local_address && local_port) { + wstr_addr_to_sockaddr(local_address->CanonicalName->Data(), + local_port->Data(), + &local_addr); + } + + if (!is_blocking && cb.on_connect) { + (*cb.on_connect)(this, PJ_SUCCESS); + } + return (pj_status_t)PJ_SUCCESS; + + } catch (Exception^ ex) { + + SocketErrorStatus status = SocketError::GetStatus(ex->HResult); + + switch (status) + { + case SocketErrorStatus::UnreachableHost: + break; + case SocketErrorStatus::ConnectionTimedOut: + break; + case SocketErrorStatus::ConnectionRefused: + break; + default: + break; + } + + if (!is_blocking && cb.on_connect) { + (*cb.on_connect)(this, PJ_EUNKNOWN); + } + + return (pj_status_t)PJ_EUNKNOWN; + } }); if (!is_blocking) - return PJ_RETURN_OS_ERROR(PJ_BLOCKING_CONNECT_ERROR_VAL); + return PJ_RETURN_OS_ERROR(PJ_BLOCKING_CONNECT_ERROR_VAL); try { - status = t.get(); + status = t.get(); } catch (Exception^) { - return PJ_EUNKNOWN; + return PJ_EUNKNOWN; } return status; } @@ -846,19 +845,19 @@ pj_status_t PjUwpSocket::Connect(const pj_sockaddr_t *addr) pj_status_t PjUwpSocket::Listen() { PJ_ASSERT_RETURN((sock_type == SOCKTYPE_UNKNOWN) || - (sock_type == SOCKTYPE_LISTENER && - sock_state == SOCKSTATE_INITIALIZED), - PJ_EINVALIDOP); + (sock_type == SOCKTYPE_LISTENER && + sock_state == SOCKSTATE_INITIALIZED), + PJ_EINVALIDOP); if (sock_type == SOCKTYPE_UNKNOWN) - InitSocket(SOCKTYPE_LISTENER); + InitSocket(SOCKTYPE_LISTENER); if (has_pending_bind) - Bind(); + Bind(); /* Start listen */ if (listener_helper == nullptr) { - listener_helper = ref new PjUwpSocketListenerHelper(this); + listener_helper = ref new PjUwpSocketListenerHelper(this); } return PJ_SUCCESS; @@ -867,15 +866,15 @@ pj_status_t PjUwpSocket::Listen() pj_status_t PjUwpSocket::Accept(PjUwpSocket **new_sock) { if (sock_type != SOCKTYPE_LISTENER || sock_state != SOCKSTATE_INITIALIZED) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; StreamSocket^ accepted_sock; pj_status_t status = listener_helper->GetAcceptedSocket(accepted_sock); if (status == PJ_ENOTFOUND) - return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL); + return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL); if (status != PJ_SUCCESS) - return status; + return status; *new_sock = CreateAcceptSocket(accepted_sock); return PJ_SUCCESS; @@ -944,12 +943,12 @@ PJ_DEF(int) pj_inet_aton(const pj_str_t *cp, pj_in_addr *inp) inp->s_addr = PJ_INADDR_NONE; /* Caution: - * this function might be called with cp->slen >= 16 + * this function might be called with cp->slen >= 16 * (i.e. when called with hostname to check if it's an IP addr). */ PJ_ASSERT_RETURN(cp && cp->slen && inp, 0); if (cp->slen >= PJ_INET_ADDRSTRLEN) { - return 0; + return 0; } pj_memcpy(tempaddr, cp->ptr, cp->slen); @@ -977,15 +976,15 @@ PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) * compatible with pj_inet_aton() */ if (af == PJ_AF_INET) { - ((pj_in_addr*)dst)->s_addr = PJ_INADDR_NONE; + ((pj_in_addr*)dst)->s_addr = PJ_INADDR_NONE; } /* Caution: - * this function might be called with cp->slen >= 46 + * this function might be called with cp->slen >= 46 * (i.e. when called with hostname to check if it's an IP addr). */ if (src->slen >= PJ_INET6_ADDRSTRLEN) { - return PJ_ENAMETOOLONG; + return PJ_ENAMETOOLONG; } pj_memcpy(tempaddr, src->ptr, src->slen); @@ -996,11 +995,11 @@ PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) * Implementation using inet_pton() */ if (inet_pton(af, tempaddr, dst) != 1) { - pj_status_t status = pj_get_netos_error(); - if (status == PJ_SUCCESS) - status = PJ_EUNKNOWN; + pj_status_t status = pj_get_netos_error(); + if (status == PJ_SUCCESS) + status = PJ_EUNKNOWN; - return status; + return status; } return PJ_SUCCESS; @@ -1011,39 +1010,39 @@ PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) * Should also work on Unicode systems. */ { - PJ_DECL_UNICODE_TEMP_BUF(wtempaddr, PJ_INET6_ADDRSTRLEN) - pj_sockaddr sock_addr; - int addr_len = sizeof(sock_addr); - int rc; - - sock_addr.addr.sa_family = (pj_uint16_t)af; - rc = WSAStringToAddress( - PJ_STRING_TO_NATIVE(tempaddr, wtempaddr, sizeof(wtempaddr)), - af, NULL, (LPSOCKADDR)&sock_addr, &addr_len); - if (rc != 0) { - /* If you get rc 130022 Invalid argument (WSAEINVAL) with IPv6, - * check that you have IPv6 enabled (install it in the network - * adapter). - */ - pj_status_t status = pj_get_netos_error(); - if (status == PJ_SUCCESS) - status = PJ_EUNKNOWN; - - return status; - } - - if (sock_addr.addr.sa_family == PJ_AF_INET) { - pj_memcpy(dst, &sock_addr.ipv4.sin_addr, 4); - return PJ_SUCCESS; - } - else if (sock_addr.addr.sa_family == PJ_AF_INET6) { - pj_memcpy(dst, &sock_addr.ipv6.sin6_addr, 16); - return PJ_SUCCESS; - } - else { - pj_assert(!"Shouldn't happen"); - return PJ_EBUG; - } + PJ_DECL_UNICODE_TEMP_BUF(wtempaddr, PJ_INET6_ADDRSTRLEN) + pj_sockaddr sock_addr; + int addr_len = sizeof(sock_addr); + int rc; + + sock_addr.addr.sa_family = (pj_uint16_t)af; + rc = WSAStringToAddress( + PJ_STRING_TO_NATIVE(tempaddr, wtempaddr, sizeof(wtempaddr)), + af, NULL, (LPSOCKADDR)&sock_addr, &addr_len); + if (rc != 0) { + /* If you get rc 130022 Invalid argument (WSAEINVAL) with IPv6, + * check that you have IPv6 enabled (install it in the network + * adapter). + */ + pj_status_t status = pj_get_netos_error(); + if (status == PJ_SUCCESS) + status = PJ_EUNKNOWN; + + return status; + } + + if (sock_addr.addr.sa_family == PJ_AF_INET) { + pj_memcpy(dst, &sock_addr.ipv4.sin_addr, 4); + return PJ_SUCCESS; + } + else if (sock_addr.addr.sa_family == PJ_AF_INET6) { + pj_memcpy(dst, &sock_addr.ipv6.sin6_addr, 16); + return PJ_SUCCESS; + } + else { + pj_assert(!"Shouldn't happen"); + return PJ_EBUG; + } } #elif !defined(PJ_HAS_IPV6) || PJ_HAS_IPV6==0 /* IPv6 support is disabled, just return error without raising assertion */ @@ -1058,7 +1057,7 @@ PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) * Convert IPv4/IPv6 address to text. */ PJ_DEF(pj_status_t) pj_inet_ntop(int af, const void *src, - char *dst, int size) + char *dst, int size) { PJ_ASSERT_RETURN(src && dst && size, PJ_EINVAL); @@ -1071,11 +1070,11 @@ PJ_DEF(pj_status_t) pj_inet_ntop(int af, const void *src, * Implementation using inet_ntop() */ if (inet_ntop(af, src, dst, size) == NULL) { - pj_status_t status = pj_get_netos_error(); - if (status == PJ_SUCCESS) - status = PJ_EUNKNOWN; + pj_status_t status = pj_get_netos_error(); + if (status == PJ_SUCCESS) + status = PJ_EUNKNOWN; - return status; + return status; } return PJ_SUCCESS; @@ -1086,52 +1085,52 @@ PJ_DEF(pj_status_t) pj_inet_ntop(int af, const void *src, * Should also work on Unicode systems. */ { - PJ_DECL_UNICODE_TEMP_BUF(wtempaddr, PJ_INET6_ADDRSTRLEN) - pj_sockaddr sock_addr; - DWORD addr_len, addr_str_len; - int rc; - - pj_bzero(&sock_addr, sizeof(sock_addr)); - sock_addr.addr.sa_family = (pj_uint16_t)af; - if (af == PJ_AF_INET) { - if (size < PJ_INET_ADDRSTRLEN) - return PJ_ETOOSMALL; - pj_memcpy(&sock_addr.ipv4.sin_addr, src, 4); - addr_len = sizeof(pj_sockaddr_in); - addr_str_len = PJ_INET_ADDRSTRLEN; - } - else if (af == PJ_AF_INET6) { - if (size < PJ_INET6_ADDRSTRLEN) - return PJ_ETOOSMALL; - pj_memcpy(&sock_addr.ipv6.sin6_addr, src, 16); - addr_len = sizeof(pj_sockaddr_in6); - addr_str_len = PJ_INET6_ADDRSTRLEN; - } - else { - pj_assert(!"Unsupported address family"); - return PJ_EAFNOTSUP; - } + PJ_DECL_UNICODE_TEMP_BUF(wtempaddr, PJ_INET6_ADDRSTRLEN) + pj_sockaddr sock_addr; + DWORD addr_len, addr_str_len; + int rc; + + pj_bzero(&sock_addr, sizeof(sock_addr)); + sock_addr.addr.sa_family = (pj_uint16_t)af; + if (af == PJ_AF_INET) { + if (size < PJ_INET_ADDRSTRLEN) + return PJ_ETOOSMALL; + pj_memcpy(&sock_addr.ipv4.sin_addr, src, 4); + addr_len = sizeof(pj_sockaddr_in); + addr_str_len = PJ_INET_ADDRSTRLEN; + } + else if (af == PJ_AF_INET6) { + if (size < PJ_INET6_ADDRSTRLEN) + return PJ_ETOOSMALL; + pj_memcpy(&sock_addr.ipv6.sin6_addr, src, 16); + addr_len = sizeof(pj_sockaddr_in6); + addr_str_len = PJ_INET6_ADDRSTRLEN; + } + else { + pj_assert(!"Unsupported address family"); + return PJ_EAFNOTSUP; + } #if PJ_NATIVE_STRING_IS_UNICODE - rc = WSAAddressToString((LPSOCKADDR)&sock_addr, addr_len, - NULL, wtempaddr, &addr_str_len); - if (rc == 0) { - pj_unicode_to_ansi(wtempaddr, wcslen(wtempaddr), dst, size); - } + rc = WSAAddressToString((LPSOCKADDR)&sock_addr, addr_len, + NULL, wtempaddr, &addr_str_len); + if (rc == 0) { + pj_unicode_to_ansi(wtempaddr, wcslen(wtempaddr), dst, size); + } #else - rc = WSAAddressToString((LPSOCKADDR)&sock_addr, addr_len, - NULL, dst, &addr_str_len); + rc = WSAAddressToString((LPSOCKADDR)&sock_addr, addr_len, + NULL, dst, &addr_str_len); #endif - if (rc != 0) { - pj_status_t status = pj_get_netos_error(); - if (status == PJ_SUCCESS) - status = PJ_EUNKNOWN; + if (rc != 0) { + pj_status_t status = pj_get_netos_error(); + if (status == PJ_SUCCESS) + status = PJ_EUNKNOWN; - return status; - } + return status; + } - return PJ_SUCCESS; + return PJ_SUCCESS; } #elif !defined(PJ_HAS_IPV6) || PJ_HAS_IPV6==0 @@ -1154,14 +1153,14 @@ PJ_DEF(const pj_str_t*) pj_gethostname(void) PJ_CHECK_STACK(); if (hostname.ptr == NULL) { - hostname.ptr = buf; - if (gethostname(buf, sizeof(buf)) != 0) { - hostname.ptr[0] = '\0'; - hostname.slen = 0; - } - else { - hostname.slen = strlen(buf); - } + hostname.ptr = buf; + if (gethostname(buf, sizeof(buf)) != 0) { + hostname.ptr[0] = '\0'; + hostname.slen = 0; + } + else { + hostname.slen = strlen(buf); + } } return &hostname; } @@ -1170,9 +1169,9 @@ PJ_DEF(const pj_str_t*) pj_gethostname(void) * Create new socket/endpoint for communication and returns a descriptor. */ PJ_DEF(pj_status_t) pj_sock_socket(int af, - int type, - int proto, - pj_sock_t *p_sock) + int type, + int proto, + pj_sock_t *p_sock) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(p_sock!=NULL, PJ_EINVAL); @@ -1181,7 +1180,7 @@ PJ_DEF(pj_status_t) pj_sock_socket(int af, /* Init UDP socket here */ if (type == pj_SOCK_DGRAM()) { - s->InitSocket(SOCKTYPE_DATAGRAM); + s->InitSocket(SOCKTYPE_DATAGRAM); } *p_sock = (pj_sock_t)s; @@ -1193,8 +1192,8 @@ PJ_DEF(pj_status_t) pj_sock_socket(int af, * Bind socket. */ PJ_DEF(pj_status_t) pj_sock_bind( pj_sock_t sock, - const pj_sockaddr_t *addr, - int len) + const pj_sockaddr_t *addr, + int len) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sock, PJ_EINVAL); @@ -1208,8 +1207,8 @@ PJ_DEF(pj_status_t) pj_sock_bind( pj_sock_t sock, * Bind socket. */ PJ_DEF(pj_status_t) pj_sock_bind_in( pj_sock_t sock, - pj_uint32_t addr32, - pj_uint16_t port) + pj_uint32_t addr32, + pj_uint16_t port) { pj_sockaddr_in addr; @@ -1233,7 +1232,7 @@ PJ_DEF(pj_status_t) pj_sock_close(pj_sock_t sock) PJ_ASSERT_RETURN(sock, PJ_EINVAL); if (sock == PJ_INVALID_SOCKET) - return PJ_SUCCESS; + return PJ_SUCCESS; PjUwpSocket *s = (PjUwpSocket*)sock; delete s; @@ -1245,12 +1244,12 @@ PJ_DEF(pj_status_t) pj_sock_close(pj_sock_t sock) * Get remote's name. */ PJ_DEF(pj_status_t) pj_sock_getpeername( pj_sock_t sock, - pj_sockaddr_t *addr, - int *namelen) + pj_sockaddr_t *addr, + int *namelen) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sock && addr && namelen && - *namelen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); + *namelen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); PjUwpSocket *s = (PjUwpSocket*)sock; pj_sockaddr_cp(addr, s->GetRemoteAddr()); @@ -1263,12 +1262,12 @@ PJ_DEF(pj_status_t) pj_sock_getpeername( pj_sock_t sock, * Get socket name. */ PJ_DEF(pj_status_t) pj_sock_getsockname( pj_sock_t sock, - pj_sockaddr_t *addr, - int *namelen) + pj_sockaddr_t *addr, + int *namelen) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sock && addr && namelen && - *namelen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); + *namelen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); PjUwpSocket *s = (PjUwpSocket*)sock; pj_sockaddr_cp(addr, s->GetLocalAddr()); @@ -1282,9 +1281,9 @@ PJ_DEF(pj_status_t) pj_sock_getsockname( pj_sock_t sock, * Send data */ PJ_DEF(pj_status_t) pj_sock_send(pj_sock_t sock, - const void *buf, - pj_ssize_t *len, - unsigned flags) + const void *buf, + pj_ssize_t *len, + unsigned flags) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sock && buf && len, PJ_EINVAL); @@ -1299,11 +1298,11 @@ PJ_DEF(pj_status_t) pj_sock_send(pj_sock_t sock, * Send data. */ PJ_DEF(pj_status_t) pj_sock_sendto(pj_sock_t sock, - const void *buf, - pj_ssize_t *len, - unsigned flags, - const pj_sockaddr_t *to, - int tolen) + const void *buf, + pj_ssize_t *len, + unsigned flags, + const pj_sockaddr_t *to, + int tolen) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sock && buf && len, PJ_EINVAL); @@ -1319,9 +1318,9 @@ PJ_DEF(pj_status_t) pj_sock_sendto(pj_sock_t sock, * Receive data. */ PJ_DEF(pj_status_t) pj_sock_recv(pj_sock_t sock, - void *buf, - pj_ssize_t *len, - unsigned flags) + void *buf, + pj_ssize_t *len, + unsigned flags) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sock && len && *len > 0, PJ_EINVAL); @@ -1336,11 +1335,11 @@ PJ_DEF(pj_status_t) pj_sock_recv(pj_sock_t sock, * Receive data. */ PJ_DEF(pj_status_t) pj_sock_recvfrom(pj_sock_t sock, - void *buf, - pj_ssize_t *len, - unsigned flags, - pj_sockaddr_t *from, - int *fromlen) + void *buf, + pj_ssize_t *len, + unsigned flags, + pj_sockaddr_t *from, + int *fromlen) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sock && buf && len && from && fromlen, PJ_EINVAL); @@ -1352,7 +1351,7 @@ PJ_DEF(pj_status_t) pj_sock_recvfrom(pj_sock_t sock, PjUwpSocket *s = (PjUwpSocket*)sock; pj_status_t status = s->RecvFrom(buf, len, from); if (status == PJ_SUCCESS) - *fromlen = pj_sockaddr_get_len(from); + *fromlen = pj_sockaddr_get_len(from); return status; } @@ -1360,10 +1359,10 @@ PJ_DEF(pj_status_t) pj_sock_recvfrom(pj_sock_t sock, * Get socket option. */ PJ_DEF(pj_status_t) pj_sock_getsockopt( pj_sock_t sock, - pj_uint16_t level, - pj_uint16_t optname, - void *optval, - int *optlen) + pj_uint16_t level, + pj_uint16_t optname, + void *optval, + int *optlen) { // Not supported for now. PJ_UNUSED_ARG(sock); @@ -1379,10 +1378,10 @@ PJ_DEF(pj_status_t) pj_sock_getsockopt( pj_sock_t sock, * Set socket option. */ PJ_DEF(pj_status_t) pj_sock_setsockopt( pj_sock_t sock, - pj_uint16_t level, - pj_uint16_t optname, - const void *optval, - int optlen) + pj_uint16_t level, + pj_uint16_t optname, + const void *optval, + int optlen) { // Not supported for now. PJ_UNUSED_ARG(sock); @@ -1406,17 +1405,17 @@ PJ_DEF(pj_status_t) pj_sock_setsockopt_params( pj_sock_t sockfd, PJ_ASSERT_RETURN(params, PJ_EINVAL); for (;icnt && ioptions[i].level, - (pj_uint16_t)params->options[i].optname, - params->options[i].optval, - params->options[i].optlen); - if (status != PJ_SUCCESS) { - retval = status; - PJ_PERROR(4,(THIS_FILE, status, - "Warning: error applying sock opt %d", - params->options[i].optname)); - } + pj_status_t status = pj_sock_setsockopt(sockfd, + (pj_uint16_t)params->options[i].level, + (pj_uint16_t)params->options[i].optname, + params->options[i].optval, + params->options[i].optlen); + if (status != PJ_SUCCESS) { + retval = status; + PJ_PERROR(4,(THIS_FILE, status, + "Warning: error applying sock opt %d", + params->options[i].optname)); + } } return retval; @@ -1427,8 +1426,8 @@ PJ_DEF(pj_status_t) pj_sock_setsockopt_params( pj_sock_t sockfd, * Connect socket. */ PJ_DEF(pj_status_t) pj_sock_connect( pj_sock_t sock, - const pj_sockaddr_t *addr, - int namelen) + const pj_sockaddr_t *addr, + int namelen) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sock && addr, PJ_EINVAL); @@ -1444,7 +1443,7 @@ PJ_DEF(pj_status_t) pj_sock_connect( pj_sock_t sock, */ #if PJ_HAS_TCP PJ_DEF(pj_status_t) pj_sock_shutdown( pj_sock_t sock, - int how) + int how) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sock, PJ_EINVAL); @@ -1457,7 +1456,7 @@ PJ_DEF(pj_status_t) pj_sock_shutdown( pj_sock_t sock, * Start listening to incoming connections. */ PJ_DEF(pj_status_t) pj_sock_listen( pj_sock_t sock, - int backlog) + int backlog) { PJ_CHECK_STACK(); PJ_UNUSED_ARG(backlog); @@ -1471,9 +1470,9 @@ PJ_DEF(pj_status_t) pj_sock_listen( pj_sock_t sock, * Accept incoming connections */ PJ_DEF(pj_status_t) pj_sock_accept( pj_sock_t serverfd, - pj_sock_t *newsock, - pj_sockaddr_t *addr, - int *addrlen) + pj_sock_t *newsock, + pj_sockaddr_t *addr, + int *addrlen) { pj_status_t status; @@ -1485,18 +1484,18 @@ PJ_DEF(pj_status_t) pj_sock_accept( pj_sock_t serverfd, status = s->Accept(&new_uwp_sock); if (status != PJ_SUCCESS) - return status; + return status; if (newsock == NULL) - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; *newsock = (pj_sock_t)new_uwp_sock; if (addr) - pj_sockaddr_cp(addr, new_uwp_sock->GetRemoteAddr()); + pj_sockaddr_cp(addr, new_uwp_sock->GetRemoteAddr()); if (addrlen) - *addrlen = pj_sockaddr_get_len(addr); + *addrlen = pj_sockaddr_get_len(addr); return PJ_SUCCESS; } -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ diff --git a/pjlib/src/pj/sock_uwp.h b/pjlib/src/pj/sock_uwp.h index 6647f3acba..c981ba1d0e 100644 --- a/pjlib/src/pj/sock_uwp.h +++ b/pjlib/src/pj/sock_uwp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2016 Teluu Inc. (http://www.teluu.com) * @@ -26,9 +25,9 @@ enum { - READ_TIMEOUT = 60 * 1000, - WRITE_TIMEOUT = 60 * 1000, - SEND_BUFFER_SIZE = 128 * 1024, + READ_TIMEOUT = 60 * 1000, + WRITE_TIMEOUT = 60 * 1000, + SEND_BUFFER_SIZE = 128 * 1024, }; enum PjUwpSocketType { @@ -69,9 +68,9 @@ class PjUwpSocket void* GetUserData() { return user_data; } void SetNonBlocking(const PjUwpSocketCallback *cb_, void *user_data_) { - is_blocking = PJ_FALSE; - cb=*cb_; - user_data = user_data_; + is_blocking = PJ_FALSE; + cb=*cb_; + user_data = user_data_; } enum PjUwpSocketType GetType() { return sock_type; } @@ -136,8 +135,8 @@ class PjUwpSocket inline pj_status_t wstr_addr_to_sockaddr(const wchar_t *waddr, - const wchar_t *wport, - pj_sockaddr_t *sockaddr) + const wchar_t *wport, + pj_sockaddr_t *sockaddr) { #if 0 char tmp_str_buf[PJ_INET6_ADDRSTRLEN+1]; @@ -159,18 +158,18 @@ inline pj_status_t wstr_addr_to_sockaddr(const wchar_t *waddr, pj_bool_t got_addr = PJ_FALSE; if (pj_inet_pton(PJ_AF_INET, &remote_host, &addr->ipv4.sin_addr) - == PJ_SUCCESS) + == PJ_SUCCESS) { - addr->addr.sa_family = PJ_AF_INET; - got_addr = PJ_TRUE; + addr->addr.sa_family = PJ_AF_INET; + got_addr = PJ_TRUE; } else if (pj_inet_pton(PJ_AF_INET6, &remote_host, &addr->ipv6.sin6_addr) - == PJ_SUCCESS) + == PJ_SUCCESS) { - addr->addr.sa_family = PJ_AF_INET6; - got_addr = PJ_TRUE; + addr->addr.sa_family = PJ_AF_INET6; + got_addr = PJ_TRUE; } if (!got_addr) - return PJ_EINVAL; + return PJ_EINVAL; pj_sockaddr_set_port(addr, (pj_uint16_t)_wtoi(wport)); return PJ_SUCCESS; @@ -178,14 +177,14 @@ inline pj_status_t wstr_addr_to_sockaddr(const wchar_t *waddr, inline pj_status_t sockaddr_to_hostname_port(const pj_sockaddr_t *sockaddr, - Windows::Networking::HostName ^&hostname, - int *port) + Windows::Networking::HostName ^&hostname, + int *port) { char tmp[PJ_INET6_ADDRSTRLEN]; wchar_t wtmp[PJ_INET6_ADDRSTRLEN]; pj_sockaddr_print(sockaddr, tmp, PJ_INET6_ADDRSTRLEN, 0); pj_ansi_to_unicode(tmp, pj_ansi_strlen(tmp), wtmp, - PJ_INET6_ADDRSTRLEN); + PJ_INET6_ADDRSTRLEN); hostname = ref new Windows::Networking::HostName(ref new Platform::String(wtmp)); *port = pj_sockaddr_get_port(sockaddr); @@ -258,7 +257,7 @@ inline concurrency::task complete_after(unsigned int timeout) // Create a call object that sets the completion event after the timer fires. auto callback = new concurrency::call([tce](int) { - tce.set(); + tce.set(); }); // Connect the timer to the callback and start the timer. @@ -272,8 +271,8 @@ inline concurrency::task complete_after(unsigned int timeout) // and return that continuation task. return event_set.then([callback, fire_once]() { - delete callback; - delete fire_once; + delete callback; + delete fire_once; }); } @@ -285,27 +284,27 @@ inline concurrency::task cancel_after_timeout(concurrency::task t, concurr // Create a task that returns true after the specified task completes. concurrency::task success_task = t.then([](T) { - return true; + return true; }); // Create a task that returns false after the specified timeout. concurrency::task failure_task = complete_after(timeout).then([] { - return false; + return false; }); // Create a continuation task that cancels the overall task // if the timeout task finishes first. return (failure_task || success_task).then([t, cts](bool success) { - if (!success) - { - // Set the cancellation token. The task that is passed as the - // t parameter should respond to the cancellation and stop - // as soon as it can. - cts.cancel(); - } - - // Return the original task. - return t; + if (!success) + { + // Set the cancellation token. The task that is passed as the + // t parameter should respond to the cancellation and stop + // as soon as it can. + cts.cancel(); + } + + // Return the original task. + return t; }); } diff --git a/pjlib/src/pj/ssl_sock_apple.m b/pjlib/src/pj/ssl_sock_apple.m index 89e2206cc6..c5251681d7 100644 --- a/pjlib/src/pj/ssl_sock_apple.m +++ b/pjlib/src/pj/ssl_sock_apple.m @@ -58,18 +58,18 @@ /* Secure socket structure definition. */ typedef struct applessl_sock_t { - pj_ssl_sock_t base; - - nw_listener_t listener; - nw_listener_state_t lis_state; - nw_connection_t connection; - nw_connection_state_t con_state; - dispatch_queue_t queue; - dispatch_semaphore_t ev_semaphore; - - SecTrustRef trust; - tls_ciphersuite_t cipher; - sec_identity_t identity; + pj_ssl_sock_t base; + + nw_listener_t listener; + nw_listener_state_t lis_state; + nw_connection_t connection; + nw_connection_state_t con_state; + dispatch_queue_t queue; + dispatch_semaphore_t ev_semaphore; + + SecTrustRef trust; + tls_ciphersuite_t cipher; + sec_identity_t identity; } applessl_sock_t; @@ -94,42 +94,42 @@ { PJ_DECL_LIST_MEMBER(struct event_t); - event_id type; - pj_ssl_sock_t *ssock; - pj_bool_t async; + event_id type; + pj_ssl_sock_t *ssock; + pj_bool_t async; union { struct { - nw_connection_t newconn; - pj_sockaddr src_addr; - int src_addr_len; - pj_status_t status; + nw_connection_t newconn; + pj_sockaddr src_addr; + int src_addr_len; + pj_status_t status; } accept_ev; struct { - pj_status_t status; + pj_status_t status; } connect_ev; - struct + struct { - pj_status_t status; + pj_status_t status; } handshake_ev; struct { pj_ioqueue_op_key_t *send_key; - pj_ssize_t sent; + pj_ssize_t sent; } data_sent_ev; struct { - void *data; - pj_size_t size; - pj_status_t status; - pj_size_t remainder; + void *data; + pj_size_t size; + pj_status_t status; + pj_size_t remainder; } data_read_ev; } body; @@ -137,9 +137,9 @@ typedef struct event_manager { - NSLock *lock; - event_t event_list; - event_t free_event_list; + NSLock *lock; + event_t event_list; + event_t free_event_list; } event_manager; static event_manager *event_mgr = NULL; @@ -164,13 +164,13 @@ static void event_manager_destroy() event_mgr = NULL; while (!pj_list_empty(&mgr->free_event_list)) { - event_t *event = mgr->free_event_list.next; + event_t *event = mgr->free_event_list.next; pj_list_erase(event); free(event); } while (!pj_list_empty(&mgr->event_list)) { - event_t *event = mgr->event_list.next; + event_t *event = mgr->event_list.next; pj_list_erase(event); free(event); } @@ -185,7 +185,7 @@ static pj_status_t event_manager_create() event_manager *mgr; if (event_mgr) - return PJ_SUCCESS; + return PJ_SUCCESS; mgr = malloc(sizeof(event_manager)); if (!mgr) return PJ_ENOMEM; @@ -204,22 +204,22 @@ static pj_status_t event_manager_create() * synchronously, the function will wait until the event is processed. */ static pj_status_t event_manager_post_event(pj_ssl_sock_t *ssock, - event_t *event_item, - pj_bool_t async) + event_t *event_item, + pj_bool_t async) { event_manager *mgr = event_mgr; event_t *event; #if SSL_DEBUG if (!pj_thread_is_registered()) { - pj_bzero(queue_th_desc, sizeof(pj_thread_desc)); - pj_thread_register("sslq", queue_th_desc, &queue_th); + pj_bzero(queue_th_desc, sizeof(pj_thread_desc)); + pj_thread_register("sslq", queue_th_desc, &queue_th); } PJ_LOG(3, (THIS_FILE, "Posting event %p %d", ssock, event_item->type)); #endif if (ssock->is_closing || !ssock->pool || !mgr) - return PJ_EGONE; + return PJ_EGONE; #if SSL_DEBUG PJ_LOG(3,(THIS_FILE, "Post event success %p %d",ssock, event_item->type)); @@ -242,8 +242,8 @@ static pj_status_t event_manager_post_event(pj_ssl_sock_t *ssock, [mgr->lock unlock]; if (!async) { - dispatch_semaphore_wait(((applessl_sock_t *)ssock)->ev_semaphore, - DISPATCH_TIME_FOREVER); + dispatch_semaphore_wait(((applessl_sock_t *)ssock)->ev_semaphore, + DISPATCH_TIME_FOREVER); } return PJ_SUCCESS; @@ -253,22 +253,22 @@ static pj_status_t event_manager_post_event(pj_ssl_sock_t *ssock, static void event_manager_remove_events(pj_ssl_sock_t *ssock) { event_t *event; - + [event_mgr->lock lock]; event = event_mgr->event_list.next; while (event != &event_mgr->event_list) { - event_t *event_ = event; - - event = event->next; - if (event_->ssock == ssock) { - pj_list_erase(event_); - /* If not async, signal the waiting socket */ - if (!event_->async) { - applessl_sock_t * assock; - assock = (applessl_sock_t *)event_->ssock; - dispatch_semaphore_signal(assock->ev_semaphore); - } - } + event_t *event_ = event; + + event = event->next; + if (event_->ssock == ssock) { + pj_list_erase(event_); + /* If not async, signal the waiting socket */ + if (!event_->async) { + applessl_sock_t * assock; + assock = (applessl_sock_t *)event_->ssock; + dispatch_semaphore_signal(assock->ev_semaphore); + } + } } [event_mgr->lock unlock]; } @@ -276,33 +276,33 @@ static void event_manager_remove_events(pj_ssl_sock_t *ssock) pj_status_t ssl_network_event_poll() { if (!event_mgr) - return PJ_SUCCESS; + return PJ_SUCCESS; while (!pj_list_empty(&event_mgr->event_list)) { pj_ssl_sock_t *ssock; - applessl_sock_t * assock; - event_t *event; - pj_bool_t ret = PJ_TRUE, add_ref = PJ_FALSE; - - [event_mgr->lock lock]; - /* Check again, this time by holding the lock */ - if (pj_list_empty(&event_mgr->event_list)) { - [event_mgr->lock unlock]; - break; - } - event = event_mgr->event_list.next; - ssock = event->ssock; - assock = (applessl_sock_t *)ssock; - pj_list_erase(event); - - if (ssock->is_closing || !ssock->pool || - (!ssock->is_server && !assock->connection) || - (ssock->is_server && !assock->listener)) - { + applessl_sock_t * assock; + event_t *event; + pj_bool_t ret = PJ_TRUE, add_ref = PJ_FALSE; + + [event_mgr->lock lock]; + /* Check again, this time by holding the lock */ + if (pj_list_empty(&event_mgr->event_list)) { + [event_mgr->lock unlock]; + break; + } + event = event_mgr->event_list.next; + ssock = event->ssock; + assock = (applessl_sock_t *)ssock; + pj_list_erase(event); + + if (ssock->is_closing || !ssock->pool || + (!ssock->is_server && !assock->connection) || + (ssock->is_server && !assock->listener)) + { PJ_LOG(3, (THIS_FILE, "Warning: Discarding SSL event type %d of " - "a closing socket %p", event->type, ssock)); + "a closing socket %p", event->type, ssock)); event->type = EVENT_DISCARD; - } else if (ssock->param.grp_lock) { + } else if (ssock->param.grp_lock) { if (pj_grp_lock_get_ref(ssock->param.grp_lock) > 0) { /* Prevent ssock from being destroyed while * we are calling the callback. @@ -310,63 +310,63 @@ pj_status_t ssl_network_event_poll() add_ref = PJ_TRUE; pj_grp_lock_add_ref(ssock->param.grp_lock); } else { - PJ_LOG(3, (THIS_FILE, "Warning: Discarding SSL event type %d " - " of a destroyed socket %p", event->type, ssock)); + PJ_LOG(3, (THIS_FILE, "Warning: Discarding SSL event type %d " + " of a destroyed socket %p", event->type, ssock)); event->type = EVENT_DISCARD; } } - [event_mgr->lock unlock]; - - switch (event->type) { - case EVENT_ACCEPT: - ret = ssock_on_accept_complete(event->ssock, - PJ_INVALID_SOCKET, - event->body.accept_ev.newconn, - &event->body.accept_ev.src_addr, - event->body.accept_ev.src_addr_len, - event->body.accept_ev.status); - break; - case EVENT_CONNECT: - ret = ssock_on_connect_complete(event->ssock, - event->body.connect_ev.status); - break; - case EVENT_VERIFY_CERT: - verify_cert(assock, event->ssock->cert); - break; - case EVENT_HANDSHAKE_COMPLETE: - event->ssock->ssl_state = SSL_STATE_ESTABLISHED; - ret = on_handshake_complete(event->ssock, - event->body.handshake_ev.status); - break; - case EVENT_DATA_SENT: - ret = ssock_on_data_sent(event->ssock, - event->body.data_sent_ev.send_key, - event->body.data_sent_ev.sent); - break; - case EVENT_DATA_READ: - ret = ssock_on_data_read(event->ssock, - event->body.data_read_ev.data, - event->body.data_read_ev.size, - event->body.data_read_ev.status, - &event->body.data_read_ev.remainder); - break; - default: - break; - } - - /* If not async and not destroyed, signal the waiting socket */ - if (event->type != EVENT_DISCARD && ret && !event->async && ret) { - dispatch_semaphore_signal(assock->ev_semaphore); - } - - /* Put the event into the free list to be reused */ - [event_mgr->lock lock]; + [event_mgr->lock unlock]; + + switch (event->type) { + case EVENT_ACCEPT: + ret = ssock_on_accept_complete(event->ssock, + PJ_INVALID_SOCKET, + event->body.accept_ev.newconn, + &event->body.accept_ev.src_addr, + event->body.accept_ev.src_addr_len, + event->body.accept_ev.status); + break; + case EVENT_CONNECT: + ret = ssock_on_connect_complete(event->ssock, + event->body.connect_ev.status); + break; + case EVENT_VERIFY_CERT: + verify_cert(assock, event->ssock->cert); + break; + case EVENT_HANDSHAKE_COMPLETE: + event->ssock->ssl_state = SSL_STATE_ESTABLISHED; + ret = on_handshake_complete(event->ssock, + event->body.handshake_ev.status); + break; + case EVENT_DATA_SENT: + ret = ssock_on_data_sent(event->ssock, + event->body.data_sent_ev.send_key, + event->body.data_sent_ev.sent); + break; + case EVENT_DATA_READ: + ret = ssock_on_data_read(event->ssock, + event->body.data_read_ev.data, + event->body.data_read_ev.size, + event->body.data_read_ev.status, + &event->body.data_read_ev.remainder); + break; + default: + break; + } + + /* If not async and not destroyed, signal the waiting socket */ + if (event->type != EVENT_DISCARD && ret && !event->async && ret) { + dispatch_semaphore_signal(assock->ev_semaphore); + } + + /* Put the event into the free list to be reused */ + [event_mgr->lock lock]; if (add_ref) { pj_grp_lock_dec_ref(ssock->param.grp_lock); } - pj_list_push_back(&event_mgr->free_event_list, event); - [event_mgr->lock unlock]; + pj_list_push_back(&event_mgr->free_event_list, event); + [event_mgr->lock unlock]; } return 0; @@ -378,27 +378,27 @@ pj_status_t ssl_network_event_poll() ******************************************************************* */ -#define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + \ - PJ_ERRNO_SPACE_SIZE*6) +#define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + \ + PJ_ERRNO_SPACE_SIZE*6) -#define PJ_SSL_ERRNO_SPACE_SIZE PJ_ERRNO_SPACE_SIZE +#define PJ_SSL_ERRNO_SPACE_SIZE PJ_ERRNO_SPACE_SIZE /* Convert from Apple SSL error to pj_status_t. */ static pj_status_t pj_status_from_err(applessl_sock_t *assock, - const char *msg, - OSStatus err) + const char *msg, + OSStatus err) { pj_status_t status = (pj_status_t)-err; CFStringRef errmsg; errmsg = SecCopyErrorMessageString(err, NULL); PJ_LOG(3, (THIS_FILE, "Apple SSL error %s [%d]: %s", - (msg? msg: ""), err, - CFStringGetCStringPtr(errmsg, kCFStringEncodingUTF8))); + (msg? msg: ""), err, + CFStringGetCStringPtr(errmsg, kCFStringEncodingUTF8))); CFRelease(errmsg); if (status > PJ_SSL_ERRNO_SPACE_SIZE) - status = PJ_SSL_ERRNO_SPACE_SIZE; + status = PJ_SSL_ERRNO_SPACE_SIZE; status += PJ_SSL_ERRNO_START; if (assock) @@ -409,7 +409,7 @@ static pj_status_t pj_status_from_err(applessl_sock_t *assock, /* Read cert or key file */ static pj_status_t create_data_from_file(CFDataRef *data, - pj_str_t *fname, pj_str_t *path) + pj_str_t *fname, pj_str_t *path) { CFURLRef file; CFReadStreamRef read_stream; @@ -421,30 +421,30 @@ static pj_status_t create_data_from_file(CFDataRef *data, CFStringRef path_str; path_str = CFStringCreateWithBytes(NULL, (const UInt8 *)path->ptr, - path->slen, - kCFStringEncodingUTF8, false); + path->slen, + kCFStringEncodingUTF8, false); if (!path_str) return PJ_ENOMEM; filepath = CFURLCreateWithFileSystemPath(NULL, path_str, - kCFURLPOSIXPathStyle, true); + kCFURLPOSIXPathStyle, true); CFRelease(path_str); if (!filepath) return PJ_ENOMEM; path_str = CFStringCreateWithBytes(NULL, (const UInt8 *)fname->ptr, - fname->slen, - kCFStringEncodingUTF8, false); + fname->slen, + kCFStringEncodingUTF8, false); if (!path_str) { - CFRelease(filepath); - return PJ_ENOMEM; + CFRelease(filepath); + return PJ_ENOMEM; } file = CFURLCreateCopyAppendingPathComponent(NULL, filepath, - path_str, false); + path_str, false); CFRelease(path_str); CFRelease(filepath); } else { file = CFURLCreateFromFileSystemRepresentation(NULL, - (const UInt8 *)fname->ptr, fname->slen, false); + (const UInt8 *)fname->ptr, fname->slen, false); } if (!file) @@ -463,11 +463,11 @@ static pj_status_t create_data_from_file(CFDataRef *data, } nbytes = CFReadStreamRead(read_stream, data_buf, - sizeof(data_buf)); + sizeof(data_buf)); if (nbytes > 0) *data = CFDataCreate(NULL, data_buf, nbytes); else - *data = NULL; + *data = NULL; CFReadStreamClose(read_stream); CFRelease(read_stream); @@ -476,8 +476,8 @@ static pj_status_t create_data_from_file(CFDataRef *data, } static pj_status_t create_identity_from_cert(applessl_sock_t *assock, - pj_ssl_cert_t *cert, - sec_identity_t *p_identity) + pj_ssl_cert_t *cert, + sec_identity_t *p_identity) { CFStringRef password = NULL; CFDataRef cert_data = NULL; @@ -494,116 +494,116 @@ static pj_status_t create_identity_from_cert(applessl_sock_t *assock, *p_identity = NULL; if (cert->privkey_file.slen || cert->privkey_buf.slen || - cert->privkey_pass.slen) + cert->privkey_pass.slen) { - PJ_LOG(5, (THIS_FILE, "Ignoring supplied private key. Private key " - "must be placed in the keychain instead.")); + PJ_LOG(5, (THIS_FILE, "Ignoring supplied private key. Private key " + "must be placed in the keychain instead.")); } if (cert->cert_file.slen) { - status = create_data_from_file(&cert_data, &cert->cert_file, NULL); - if (status != PJ_SUCCESS) { - PJ_PERROR(2, (THIS_FILE, status, "Failed reading cert file")); - return status; - } + status = create_data_from_file(&cert_data, &cert->cert_file, NULL); + if (status != PJ_SUCCESS) { + PJ_PERROR(2, (THIS_FILE, status, "Failed reading cert file")); + return status; + } } else if (cert->cert_buf.slen) { - cert_data = CFDataCreate(NULL, (const UInt8 *)cert->cert_buf.ptr, - cert->cert_buf.slen); - if (!cert_data) - return PJ_ENOMEM; + cert_data = CFDataCreate(NULL, (const UInt8 *)cert->cert_buf.ptr, + cert->cert_buf.slen); + if (!cert_data) + return PJ_ENOMEM; } if (cert_data) { if (cert->privkey_pass.slen) { - password = CFStringCreateWithBytes(NULL, - (const UInt8 *)cert->privkey_pass.ptr, - cert->privkey_pass.slen, - kCFStringEncodingUTF8, - false); - keys[0] = (void *)kSecImportExportPassphrase; - values[0] = (void *)password; + password = CFStringCreateWithBytes(NULL, + (const UInt8 *)cert->privkey_pass.ptr, + cert->privkey_pass.slen, + kCFStringEncodingUTF8, + false); + keys[0] = (void *)kSecImportExportPassphrase; + values[0] = (void *)password; } options = CFDictionaryCreate(NULL, (const void **)keys, - (const void **)values, - (password? 1: 0), NULL, NULL); + (const void **)values, + (password? 1: 0), NULL, NULL); if (!options) - return PJ_ENOMEM; + return PJ_ENOMEM; #if TARGET_OS_IPHONE err = SecPKCS12Import(cert_data, options, &items); #else { - SecExternalFormat ext_format[3] = {kSecFormatPKCS12, - kSecFormatPEMSequence, - kSecFormatX509Cert/* DER */}; - SecExternalItemType ext_type = kSecItemTypeCertificate; - SecItemImportExportKeyParameters key_params; + SecExternalFormat ext_format[3] = {kSecFormatPKCS12, + kSecFormatPEMSequence, + kSecFormatX509Cert/* DER */}; + SecExternalItemType ext_type = kSecItemTypeCertificate; + SecItemImportExportKeyParameters key_params; - pj_bzero(&key_params, sizeof(key_params)); - key_params.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; - key_params.passphrase = password; + pj_bzero(&key_params, sizeof(key_params)); + key_params.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; + key_params.passphrase = password; - for (i = 0; i < PJ_ARRAY_SIZE(ext_format); i++) { - items = NULL; - err = SecItemImport(cert_data, NULL, &ext_format[i], - &ext_type, 0, &key_params, NULL, &items); - if (err == noErr && items) { - break; - } - } + for (i = 0; i < PJ_ARRAY_SIZE(ext_format); i++) { + items = NULL; + err = SecItemImport(cert_data, NULL, &ext_format[i], + &ext_type, 0, &key_params, NULL, &items); + if (err == noErr && items) { + break; + } + } } #endif CFRelease(options); if (password) - CFRelease(password); + CFRelease(password); CFRelease(cert_data); if (err != noErr || !items) { - return pj_status_from_err(assock, "SecItemImport", err); + return pj_status_from_err(assock, "SecItemImport", err); } count = CFArrayGetCount(items); for (i = 0; i < count; i++) { - CFTypeRef item; - CFTypeID item_id; - - item = (CFTypeRef) CFArrayGetValueAtIndex(items, i); - item_id = CFGetTypeID(item); + CFTypeRef item; + CFTypeID item_id; + + item = (CFTypeRef) CFArrayGetValueAtIndex(items, i); + item_id = CFGetTypeID(item); - if (item_id == CFDictionaryGetTypeID()) { - identity = (SecIdentityRef) - CFDictionaryGetValue((CFDictionaryRef) item, - kSecImportItemIdentity); - break; - } + if (item_id == CFDictionaryGetTypeID()) { + identity = (SecIdentityRef) + CFDictionaryGetValue((CFDictionaryRef) item, + kSecImportItemIdentity); + break; + } #if !TARGET_OS_IPHONE - else if (item_id == SecCertificateGetTypeID()) { - err = SecIdentityCreateWithCertificate(NULL, - (SecCertificateRef) item, &identity); - if (err != noErr) { - pj_status_from_err(assock, "SecIdentityCreate", err); - if (err == errSecItemNotFound) { - PJ_LOG(2, (THIS_FILE, "Private key must be placed in " - "the keychain")); - } - } else { - break; - } - } + else if (item_id == SecCertificateGetTypeID()) { + err = SecIdentityCreateWithCertificate(NULL, + (SecCertificateRef) item, &identity); + if (err != noErr) { + pj_status_from_err(assock, "SecIdentityCreate", err); + if (err == errSecItemNotFound) { + PJ_LOG(2, (THIS_FILE, "Private key must be placed in " + "the keychain")); + } + } else { + break; + } + } #endif } CFRelease(items); if (!identity) { - PJ_LOG(2, (THIS_FILE, "Failed extracting identity from " - "the cert file")); - return PJ_EINVAL; + PJ_LOG(2, (THIS_FILE, "Failed extracting identity from " + "the cert file")); + return PJ_EINVAL; } - *p_identity = sec_identity_create(identity); + *p_identity = sec_identity_create(identity); CFRelease(identity); } @@ -621,91 +621,91 @@ static pj_status_t verify_cert(applessl_sock_t *assock, pj_ssl_cert_t *cert) OSStatus err = noErr; if (trust && cert && cert->CA_file.slen) { - status = create_data_from_file(&ca_data, &cert->CA_file, - (cert->CA_path.slen? &cert->CA_path: - NULL)); - if (status != PJ_SUCCESS) - PJ_LOG(2, (THIS_FILE, "Failed reading CA file")); + status = create_data_from_file(&ca_data, &cert->CA_file, + (cert->CA_path.slen? &cert->CA_path: + NULL)); + if (status != PJ_SUCCESS) + PJ_LOG(2, (THIS_FILE, "Failed reading CA file")); } else if (trust && cert && cert->CA_buf.slen) { - ca_data = CFDataCreate(NULL, (const UInt8 *)cert->CA_buf.ptr, - cert->CA_buf.slen); - if (!ca_data) - PJ_LOG(2, (THIS_FILE, "Not enough memory for CA buffer")); + ca_data = CFDataCreate(NULL, (const UInt8 *)cert->CA_buf.ptr, + cert->CA_buf.slen); + if (!ca_data) + PJ_LOG(2, (THIS_FILE, "Not enough memory for CA buffer")); } if (ca_data) { SecCertificateRef ca_cert; CFMutableArrayRef ca_array; - ca_cert = SecCertificateCreateWithData(NULL, ca_data); - CFRelease(ca_data); - if (!ca_cert) { - PJ_LOG(2, (THIS_FILE, "Failed creating certificate from " - "CA file/buffer. It has to be " - "in DER format.")); - status = PJ_EINVAL; - goto on_return; - } + ca_cert = SecCertificateCreateWithData(NULL, ca_data); + CFRelease(ca_data); + if (!ca_cert) { + PJ_LOG(2, (THIS_FILE, "Failed creating certificate from " + "CA file/buffer. It has to be " + "in DER format.")); + status = PJ_EINVAL; + goto on_return; + } - ca_array = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); - if (!ca_array) { - PJ_LOG(2, (THIS_FILE, "Not enough memory for CA array")); - CFRelease(ca_cert); - status = PJ_ENOMEM; - goto on_return; - } - - CFArrayAppendValue(ca_array, ca_cert); - CFRelease(ca_cert); - - err = SecTrustSetAnchorCertificates(trust, ca_array); - CFRelease(ca_array); - if (err != noErr) - pj_status_from_err(assock, "SetAnchorCerts", err); - - err = SecTrustSetAnchorCertificatesOnly(trust, true); - if (err != noErr) - pj_status_from_err(assock, "SetAnchorCertsOnly", err); + ca_array = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); + if (!ca_array) { + PJ_LOG(2, (THIS_FILE, "Not enough memory for CA array")); + CFRelease(ca_cert); + status = PJ_ENOMEM; + goto on_return; + } + + CFArrayAppendValue(ca_array, ca_cert); + CFRelease(ca_cert); + + err = SecTrustSetAnchorCertificates(trust, ca_array); + CFRelease(ca_array); + if (err != noErr) + pj_status_from_err(assock, "SetAnchorCerts", err); + + err = SecTrustSetAnchorCertificatesOnly(trust, true); + if (err != noErr) + pj_status_from_err(assock, "SetAnchorCertsOnly", err); } result = SecTrustEvaluateWithError(trust, &error); if (!result) { pj_ssl_sock_t *ssock = &assock->base; - SecTrustResultType trust_result; + SecTrustResultType trust_result; err = SecTrustGetTrustResult(trust, &trust_result); if (err == noErr) { #if SSL_DEBUG PJ_LOG(3, (THIS_FILE, "SSL trust evaluation: %d", trust_result)); #endif - switch (trust_result) { - case kSecTrustResultInvalid: - ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT; - break; - - case kSecTrustResultDeny: - case kSecTrustResultFatalTrustFailure: - ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED; - break; - - case kSecTrustResultRecoverableTrustFailure: - /* Doc: "If you receive this result, you can retry - * after changing settings. For example, if trust is - * denied because the certificate has expired, ..." - * But this error can also mean another (recoverable) - * failure, though. - */ - ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD; - break; - - case kSecTrustResultOtherError: - ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN; - break; - - default: - break; - } - } + switch (trust_result) { + case kSecTrustResultInvalid: + ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT; + break; + + case kSecTrustResultDeny: + case kSecTrustResultFatalTrustFailure: + ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED; + break; + + case kSecTrustResultRecoverableTrustFailure: + /* Doc: "If you receive this result, you can retry + * after changing settings. For example, if trust is + * denied because the certificate has expired, ..." + * But this error can also mean another (recoverable) + * failure, though. + */ + ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD; + break; + + case kSecTrustResultOtherError: + ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN; + break; + + default: + break; + } + } if (error) CFRelease(error); @@ -716,7 +716,7 @@ static pj_status_t verify_cert(applessl_sock_t *assock, pj_ssl_cert_t *cert) on_return: if (status != PJ_SUCCESS && assock->base.verify_status == 0) - assock->base.verify_status |= PJ_SSL_CERT_EUNKNOWN; + assock->base.verify_status |= PJ_SSL_CERT_EUNKNOWN; return status; } @@ -730,47 +730,47 @@ static pj_status_t verify_cert(applessl_sock_t *assock, pj_ssl_cert_t *cert) /* Send data. */ static pj_status_t network_send(pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t *size, - unsigned flags) + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t *size, + unsigned flags) { applessl_sock_t *assock = (applessl_sock_t *)ssock; dispatch_data_t content; if (!assock->connection) - return PJ_EGONE; + return PJ_EGONE; content = dispatch_data_create(data, *size, assock->queue, - DISPATCH_DATA_DESTRUCTOR_DEFAULT); + DISPATCH_DATA_DESTRUCTOR_DEFAULT); if (!content) - return PJ_ENOMEM; + return PJ_ENOMEM; nw_connection_send(assock->connection, content, - NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, - ^(nw_error_t error) + NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, + ^(nw_error_t error) { - event_t event; - - if (error != NULL) { - errno = nw_error_get_error_code(error); - if (errno == 89) { - /* Error 89 is network cancelled, not a send error. */ - return; - } else { - warn("Send error"); - } + event_t event; + + if (error != NULL) { + errno = nw_error_get_error_code(error); + if (errno == 89) { + /* Error 89 is network cancelled, not a send error. */ + return; + } else { + warn("Send error"); + } } - event.type = EVENT_DATA_SENT; - event.body.data_sent_ev.send_key = send_key; - if (error != NULL) { - event.body.data_sent_ev.sent = (errno > 0)? -errno: errno; - } else { - event.body.data_sent_ev.sent = dispatch_data_get_size(content); - } + event.type = EVENT_DATA_SENT; + event.body.data_sent_ev.send_key = send_key; + if (error != NULL) { + event.body.data_sent_ev.sent = (errno > 0)? -errno: errno; + } else { + event.body.data_sent_ev.sent = dispatch_data_get_size(content); + } - event_manager_post_event(ssock, &event, PJ_TRUE); + event_manager_post_event(ssock, &event, PJ_TRUE); }); dispatch_release(content); @@ -778,106 +778,106 @@ static pj_status_t network_send(pj_ssl_sock_t *ssock, } static pj_status_t network_start_read(pj_ssl_sock_t *ssock, - unsigned async_count, - unsigned buff_size, - void *readbuf[], - pj_uint32_t flags) + unsigned async_count, + unsigned buff_size, + void *readbuf[], + pj_uint32_t flags) { applessl_sock_t *assock = (applessl_sock_t *)ssock; unsigned i; if (!assock->connection) - return PJ_EGONE; + return PJ_EGONE; for (i = 0; i < async_count; i++) { - nw_connection_receive(assock->connection, 1, buff_size, - ^(dispatch_data_t content, nw_content_context_t context, - bool is_complete, nw_error_t error) - { - pj_status_t status = PJ_SUCCESS; - - /* If the context is marked as complete, and is the final context, - * we're read-closed. - */ - if (is_complete && - (context == NULL || nw_content_context_get_is_final(context))) - { - return; - } - - if (error != NULL) { - errno = nw_error_get_error_code(error); - if (errno == 89) { - /* Since error 89 is network intentionally cancelled by - * us, we immediately return. - */ - return; - } else { - warn("Read error, stopping further receives"); - status = PJ_EEOF; - } + nw_connection_receive(assock->connection, 1, buff_size, + ^(dispatch_data_t content, nw_content_context_t context, + bool is_complete, nw_error_t error) + { + pj_status_t status = PJ_SUCCESS; + + /* If the context is marked as complete, and is the final context, + * we're read-closed. + */ + if (is_complete && + (context == NULL || nw_content_context_get_is_final(context))) + { + return; + } + + if (error != NULL) { + errno = nw_error_get_error_code(error); + if (errno == 89) { + /* Since error 89 is network intentionally cancelled by + * us, we immediately return. + */ + return; + } else { + warn("Read error, stopping further receives"); + status = PJ_EEOF; + } } - dispatch_block_t schedule_next_receive = - ^{ - /* If there was no error in receiving, request more data. */ - if (!error && !is_complete && assock->connection) { - network_start_read(ssock, async_count, buff_size, - readbuf, flags); - } - }; + dispatch_block_t schedule_next_receive = + ^{ + /* If there was no error in receiving, request more data. */ + if (!error && !is_complete && assock->connection) { + network_start_read(ssock, async_count, buff_size, + readbuf, flags); + } + }; if (content) { - dispatch_data_apply(content, + dispatch_data_apply(content, ^(dispatch_data_t region, size_t offset, const void *buffer, size_t inSize) - { - /* This block can be invoked multiple times, - * each for every contiguous memory region in the content. - */ - event_t event; + { + /* This block can be invoked multiple times, + * each for every contiguous memory region in the content. + */ + event_t event; - memcpy(ssock->asock_rbuf[i], buffer, inSize); + memcpy(ssock->asock_rbuf[i], buffer, inSize); - event.type = EVENT_DATA_READ; - event.body.data_read_ev.data = ssock->asock_rbuf[i]; - event.body.data_read_ev.size = inSize; - event.body.data_read_ev.status = status; - event.body.data_read_ev.remainder = 0; + event.type = EVENT_DATA_READ; + event.body.data_read_ev.data = ssock->asock_rbuf[i]; + event.body.data_read_ev.size = inSize; + event.body.data_read_ev.status = status; + event.body.data_read_ev.remainder = 0; - event_manager_post_event(ssock, &event, PJ_FALSE); + event_manager_post_event(ssock, &event, PJ_FALSE); return (bool)true; }); - schedule_next_receive(); + schedule_next_receive(); } else { - if (status != PJ_SUCCESS) { - event_t event; - - /* Report read error to application */ - event.type = EVENT_DATA_READ; - event.body.data_read_ev.data = NULL; - event.body.data_read_ev.size = 0; - event.body.data_read_ev.status = status; - event.body.data_read_ev.remainder = 0; - - event_manager_post_event(ssock, &event, PJ_TRUE); - } + if (status != PJ_SUCCESS) { + event_t event; + + /* Report read error to application */ + event.type = EVENT_DATA_READ; + event.body.data_read_ev.data = NULL; + event.body.data_read_ev.size = 0; + event.body.data_read_ev.status = status; + event.body.data_read_ev.remainder = 0; + + event_manager_post_event(ssock, &event, PJ_TRUE); + } - schedule_next_receive(); - } + schedule_next_receive(); + } }); } - + return PJ_SUCCESS; } /* Get address of local endpoint */ static pj_status_t network_get_localaddr(pj_ssl_sock_t *ssock, - pj_sockaddr_t *addr, - int *namelen) + pj_sockaddr_t *addr, + int *namelen) { applessl_sock_t *assock = (applessl_sock_t *)ssock; nw_path_t path; @@ -886,17 +886,17 @@ static pj_status_t network_get_localaddr(pj_ssl_sock_t *ssock, path = nw_connection_copy_current_path(assock->connection); if (!path) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; endpoint = nw_path_copy_effective_local_endpoint(path); nw_release(path); if (!endpoint) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; address = nw_endpoint_get_address(endpoint); if (address) { - pj_sockaddr_cp(addr, address); - *namelen = pj_sockaddr_get_addr_len(addr); + pj_sockaddr_cp(addr, address); + *namelen = pj_sockaddr_get_addr_len(addr); } nw_release(endpoint); @@ -904,9 +904,9 @@ static pj_status_t network_get_localaddr(pj_ssl_sock_t *ssock, } static pj_status_t network_create_params(pj_ssl_sock_t * ssock, - const pj_sockaddr_t *localaddr, - pj_uint16_t port_range, - nw_parameters_t *p_params) + const pj_sockaddr_t *localaddr, + pj_uint16_t port_range, + nw_parameters_t *p_params) { applessl_sock_t *assock = (applessl_sock_t *)ssock; char ip_addr[PJ_INET6_ADDRSTRLEN]; @@ -922,164 +922,164 @@ static pj_status_t network_create_params(pj_ssl_sock_t * ssock, /* Set min and max protocol version */ if (ssock->param.proto == PJ_SSL_SOCK_PROTO_DEFAULT) { - ssock->param.proto = PJ_SSL_SOCK_PROTO_TLS1 | - PJ_SSL_SOCK_PROTO_TLS1_1 | - PJ_SSL_SOCK_PROTO_TLS1_2 | - PJ_SSL_SOCK_PROTO_TLS1_3; + ssock->param.proto = PJ_SSL_SOCK_PROTO_TLS1 | + PJ_SSL_SOCK_PROTO_TLS1_1 | + PJ_SSL_SOCK_PROTO_TLS1_2 | + PJ_SSL_SOCK_PROTO_TLS1_3; } if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_3) { - max_proto = tls_protocol_version_TLSv13; + max_proto = tls_protocol_version_TLSv13; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_2) { - max_proto = tls_protocol_version_TLSv12; + max_proto = tls_protocol_version_TLSv12; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_1) { - max_proto = tls_protocol_version_TLSv11; + max_proto = tls_protocol_version_TLSv11; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1) { - max_proto = tls_protocol_version_TLSv10; + max_proto = tls_protocol_version_TLSv10; } else { - PJ_LOG(3, (THIS_FILE, "Unsupported TLS protocol")); - return PJ_EINVAL; + PJ_LOG(3, (THIS_FILE, "Unsupported TLS protocol")); + return PJ_EINVAL; } if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1) { - min_proto = tls_protocol_version_TLSv10; + min_proto = tls_protocol_version_TLSv10; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_1) { - min_proto = tls_protocol_version_TLSv11; + min_proto = tls_protocol_version_TLSv11; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_2) { - min_proto = tls_protocol_version_TLSv12; + min_proto = tls_protocol_version_TLSv12; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_3) { - min_proto = tls_protocol_version_TLSv13; + min_proto = tls_protocol_version_TLSv13; } /* Set certificate */ if (ssock->cert) { - pj_status_t status = create_identity_from_cert(assock, ssock->cert, - &assock->identity); - if (status != PJ_SUCCESS) - return status; + pj_status_t status = create_identity_from_cert(assock, ssock->cert, + &assock->identity); + if (status != PJ_SUCCESS) + return status; } configure_tls = ^(nw_protocol_options_t tls_options) { - sec_protocol_options_t sec_options; - - sec_options = nw_tls_copy_sec_protocol_options(tls_options); - - /* Set identity */ - if (ssock->cert && assock->identity) { - sec_protocol_options_set_local_identity(sec_options, - assock->identity); - } - - sec_protocol_options_set_min_tls_protocol_version(sec_options, - min_proto); - sec_protocol_options_set_max_tls_protocol_version(sec_options, - max_proto); - - /* Set cipher list */ - if (ssock->param.ciphers_num > 0) { - unsigned i; - for (i = 0; i < ssock->param.ciphers_num; i++) { - sec_protocol_options_append_tls_ciphersuite(sec_options, - (tls_ciphersuite_t)ssock->param.ciphers[i]); - } - } + sec_protocol_options_t sec_options; + + sec_options = nw_tls_copy_sec_protocol_options(tls_options); + + /* Set identity */ + if (ssock->cert && assock->identity) { + sec_protocol_options_set_local_identity(sec_options, + assock->identity); + } + + sec_protocol_options_set_min_tls_protocol_version(sec_options, + min_proto); + sec_protocol_options_set_max_tls_protocol_version(sec_options, + max_proto); + + /* Set cipher list */ + if (ssock->param.ciphers_num > 0) { + unsigned i; + for (i = 0; i < ssock->param.ciphers_num; i++) { + sec_protocol_options_append_tls_ciphersuite(sec_options, + (tls_ciphersuite_t)ssock->param.ciphers[i]); + } + } - if (!ssock->is_server && ssock->param.server_name.slen) { - sec_protocol_options_set_tls_server_name(sec_options, - ssock->param.server_name.ptr); - } - - sec_protocol_options_set_tls_renegotiation_enabled(sec_options, - true); - /* This must be disabled, otherwise server may think this is - * a resumption of a previously closed connection, and our - * verify block may never be invoked! - */ - sec_protocol_options_set_tls_resumption_enabled(sec_options, false); - - /* SSL verification options */ - sec_protocol_options_set_peer_authentication_required(sec_options, - true); - - /* Handshake flow: - * 1. Server's challenge block, provide server's trust - * 2. Client's verify block, to verify server's trust - * 3. Client's challenge block, provide client's trust - * 4. Only if client's trust is not NULL, server's verify block, - * to verify client's trust. - */ + if (!ssock->is_server && ssock->param.server_name.slen) { + sec_protocol_options_set_tls_server_name(sec_options, + ssock->param.server_name.ptr); + } + + sec_protocol_options_set_tls_renegotiation_enabled(sec_options, + true); + /* This must be disabled, otherwise server may think this is + * a resumption of a previously closed connection, and our + * verify block may never be invoked! + */ + sec_protocol_options_set_tls_resumption_enabled(sec_options, false); + + /* SSL verification options */ + sec_protocol_options_set_peer_authentication_required(sec_options, + true); + + /* Handshake flow: + * 1. Server's challenge block, provide server's trust + * 2. Client's verify block, to verify server's trust + * 3. Client's challenge block, provide client's trust + * 4. Only if client's trust is not NULL, server's verify block, + * to verify client's trust. + */ sec_protocol_options_set_challenge_block(sec_options, - ^(sec_protocol_metadata_t metadata, - sec_protocol_challenge_complete_t complete) - { - complete(assock->identity); - }, assock->queue); - - sec_protocol_options_set_verify_block(sec_options, - ^(sec_protocol_metadata_t metadata, sec_trust_t trust_ref, - sec_protocol_verify_complete_t complete) - { - event_t event; - pj_status_t status; - bool result = true; - - assock->trust = trust_ref? sec_trust_copy_ref(trust_ref): nil; - - assock->cipher = - sec_protocol_metadata_get_negotiated_tls_ciphersuite(metadata); - - /* For client, call on_connect_complete() callback first. */ - if (!ssock->is_server && ssock->ssl_state == SSL_STATE_NULL) { - if (!assock->connection) - complete(false); - - event.type = EVENT_CONNECT; - event.body.connect_ev.status = PJ_SUCCESS; - status = event_manager_post_event(ssock, &event, PJ_FALSE); - if (status == PJ_EGONE) - complete(false); - } - - event.type = EVENT_VERIFY_CERT; - status = event_manager_post_event(ssock, &event, PJ_FALSE); - if (status == PJ_EGONE) - complete(false); - - /* Check the result of cert verification. */ - if (ssock->verify_status != PJ_SSL_CERT_ESUCCESS) { - if (ssock->param.verify_peer) { - /* Verification failed. */ - result = false; - } else { - /* When verification is not requested just return ok here, - * however application can still get the verification status. - */ - result = true; - } - } - - complete(result); + ^(sec_protocol_metadata_t metadata, + sec_protocol_challenge_complete_t complete) + { + complete(assock->identity); + }, assock->queue); + + sec_protocol_options_set_verify_block(sec_options, + ^(sec_protocol_metadata_t metadata, sec_trust_t trust_ref, + sec_protocol_verify_complete_t complete) + { + event_t event; + pj_status_t status; + bool result = true; + + assock->trust = trust_ref? sec_trust_copy_ref(trust_ref): nil; + + assock->cipher = + sec_protocol_metadata_get_negotiated_tls_ciphersuite(metadata); + + /* For client, call on_connect_complete() callback first. */ + if (!ssock->is_server && ssock->ssl_state == SSL_STATE_NULL) { + if (!assock->connection) + complete(false); + + event.type = EVENT_CONNECT; + event.body.connect_ev.status = PJ_SUCCESS; + status = event_manager_post_event(ssock, &event, PJ_FALSE); + if (status == PJ_EGONE) + complete(false); + } + + event.type = EVENT_VERIFY_CERT; + status = event_manager_post_event(ssock, &event, PJ_FALSE); + if (status == PJ_EGONE) + complete(false); + + /* Check the result of cert verification. */ + if (ssock->verify_status != PJ_SSL_CERT_ESUCCESS) { + if (ssock->param.verify_peer) { + /* Verification failed. */ + result = false; + } else { + /* When verification is not requested just return ok here, + * however application can still get the verification status. + */ + result = true; + } + } + + complete(result); }, assock->queue); - nw_release(sec_options); + nw_release(sec_options); }; parameters = nw_parameters_create_secure_tcp(configure_tls, - NW_PARAMETERS_DEFAULT_CONFIGURATION); + NW_PARAMETERS_DEFAULT_CONFIGURATION); protocol_stack = nw_parameters_copy_default_protocol_stack(parameters); ip_options = nw_protocol_stack_copy_internet_protocol(protocol_stack); if (ssock->param.sock_af == pj_AF_INET()) { - nw_ip_options_set_version(ip_options, nw_ip_version_4); + nw_ip_options_set_version(ip_options, nw_ip_version_4); } else if (ssock->param.sock_af == pj_AF_INET6()) { - nw_ip_options_set_version(ip_options, nw_ip_version_6); + nw_ip_options_set_version(ip_options, nw_ip_version_6); } nw_release(ip_options); nw_release(protocol_stack); if (ssock->is_server && ssock->param.reuse_addr) { - nw_parameters_set_reuse_local_address(parameters, true); + nw_parameters_set_reuse_local_address(parameters, true); } /* Create local endpoint. @@ -1088,32 +1088,32 @@ static pj_status_t network_create_params(pj_ssl_sock_t * ssock, pj_sockaddr_print(localaddr, ip_addr,sizeof(ip_addr),0); if (port_range) { - pj_uint16_t max_try = MAX_BIND_RETRY; - - if (port_range && port_range < max_try) { - max_try = port_range; - } - for (; max_try; --max_try) { - pj_uint16_t base_port; - - base_port = pj_sockaddr_get_port(localaddr); - port = (pj_uint16_t)(base_port + pj_rand() % (port_range + 1)); - pj_utoa(port, port_str); - - local_endpoint = nw_endpoint_create_host(ip_addr, port_str); - if (local_endpoint) - break; - } + pj_uint16_t max_try = MAX_BIND_RETRY; + + if (port_range && port_range < max_try) { + max_try = port_range; + } + for (; max_try; --max_try) { + pj_uint16_t base_port; + + base_port = pj_sockaddr_get_port(localaddr); + port = (pj_uint16_t)(base_port + pj_rand() % (port_range + 1)); + pj_utoa(port, port_str); + + local_endpoint = nw_endpoint_create_host(ip_addr, port_str); + if (local_endpoint) + break; + } } else { - port = pj_sockaddr_get_port(localaddr); - pj_utoa(port, port_str); + port = pj_sockaddr_get_port(localaddr); + pj_utoa(port, port_str); - local_endpoint = nw_endpoint_create_host(ip_addr, port_str); + local_endpoint = nw_endpoint_create_host(ip_addr, port_str); } if (!local_endpoint) { PJ_LOG(2, (THIS_FILE, "Failed creating local endpoint")); - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; } nw_parameters_set_local_endpoint(parameters, local_endpoint); @@ -1125,7 +1125,7 @@ static pj_status_t network_create_params(pj_ssl_sock_t * ssock, /* Setup assock's connection state callback and start the connection */ static pj_status_t network_setup_connection(pj_ssl_sock_t *ssock, - void *connection) + void *connection) { applessl_sock_t *assock = (applessl_sock_t *)ssock; assock->connection = (nw_connection_t)connection; @@ -1145,73 +1145,73 @@ static pj_status_t network_setup_connection(pj_ssl_sock_t *ssock, assock->con_state = nw_connection_state_invalid; nw_connection_set_state_changed_handler(assock->connection, - ^(nw_connection_state_t state, nw_error_t error) + ^(nw_connection_state_t state, nw_error_t error) { - pj_status_t status = PJ_SUCCESS; - pj_bool_t call_cb = PJ_FALSE; + pj_status_t status = PJ_SUCCESS; + pj_bool_t call_cb = PJ_FALSE; #if SSL_DEBUG - if (!pj_thread_is_registered()) { - pj_bzero(queue_th_desc, sizeof(pj_thread_desc)); - pj_thread_register("sslq", queue_th_desc, &queue_th); + if (!pj_thread_is_registered()) { + pj_bzero(queue_th_desc, sizeof(pj_thread_desc)); + pj_thread_register("sslq", queue_th_desc, &queue_th); } PJ_LOG(3, (THIS_FILE, "SSL state change %p %d", assock, state)); #endif - if (error && state != nw_connection_state_cancelled) { - errno = nw_error_get_error_code(error); + if (error && state != nw_connection_state_cancelled) { + errno = nw_error_get_error_code(error); warn("Connection failed %p", assock); status = PJ_STATUS_FROM_OS(errno); #if SSL_DEBUG PJ_LOG(3, (THIS_FILE, "SSL state and errno %d %d", state, errno)); #endif - call_cb = PJ_TRUE; - } - - if (state == nw_connection_state_ready) { - if (ssock->is_server) { - nw_protocol_definition_t tls_def; - nw_protocol_metadata_t prot_meta; - sec_protocol_metadata_t meta; - - tls_def = nw_protocol_copy_tls_definition(); - prot_meta = nw_connection_copy_protocol_metadata(connection, - tls_def); - meta = nw_tls_copy_sec_protocol_metadata(prot_meta); - assock->cipher = - sec_protocol_metadata_get_negotiated_tls_ciphersuite(meta); - - if (ssock->param.require_client_cert && - !sec_protocol_metadata_access_peer_certificate_chain( - meta, ^(sec_certificate_t certificate) {} )) - { - status = PJ_EEOF; - } - nw_release(tls_def); - nw_release(prot_meta); - nw_release(meta); - } - call_cb = PJ_TRUE; - } else if (state == nw_connection_state_cancelled) { - /* We release the reference in ssl_destroy() */ - // nw_release(assock->connection); - // assock->connection = nil; - } - - if (call_cb) { - event_t event; - - event.type = EVENT_HANDSHAKE_COMPLETE; - event.body.handshake_ev.status = status; - event_manager_post_event(ssock, &event, PJ_TRUE); - - if (ssock->is_server && status == PJ_SUCCESS) { - status = network_start_read(ssock, ssock->param.async_cnt, - (unsigned)ssock->param.read_buffer_size, - ssock->asock_rbuf, 0); - } - } - - assock->con_state = state; + call_cb = PJ_TRUE; + } + + if (state == nw_connection_state_ready) { + if (ssock->is_server) { + nw_protocol_definition_t tls_def; + nw_protocol_metadata_t prot_meta; + sec_protocol_metadata_t meta; + + tls_def = nw_protocol_copy_tls_definition(); + prot_meta = nw_connection_copy_protocol_metadata(connection, + tls_def); + meta = nw_tls_copy_sec_protocol_metadata(prot_meta); + assock->cipher = + sec_protocol_metadata_get_negotiated_tls_ciphersuite(meta); + + if (ssock->param.require_client_cert && + !sec_protocol_metadata_access_peer_certificate_chain( + meta, ^(sec_certificate_t certificate) {} )) + { + status = PJ_EEOF; + } + nw_release(tls_def); + nw_release(prot_meta); + nw_release(meta); + } + call_cb = PJ_TRUE; + } else if (state == nw_connection_state_cancelled) { + /* We release the reference in ssl_destroy() */ + // nw_release(assock->connection); + // assock->connection = nil; + } + + if (call_cb) { + event_t event; + + event.type = EVENT_HANDSHAKE_COMPLETE; + event.body.handshake_ev.status = status; + event_manager_post_event(ssock, &event, PJ_TRUE); + + if (ssock->is_server && status == PJ_SUCCESS) { + status = network_start_read(ssock, ssock->param.async_cnt, + (unsigned)ssock->param.read_buffer_size, + ssock->asock_rbuf, 0); + } + } + + assock->con_state = state; }); nw_connection_start(assock->connection); @@ -1220,10 +1220,10 @@ static pj_status_t network_setup_connection(pj_ssl_sock_t *ssock, } static pj_status_t network_start_accept(pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_sockaddr_t *localaddr, - int addr_len, - const pj_ssl_sock_param *newsock_param) + pj_pool_t *pool, + const pj_sockaddr_t *localaddr, + int addr_len, + const pj_ssl_sock_param *newsock_param) { applessl_sock_t *assock = (applessl_sock_t *)ssock; pj_status_t status; @@ -1231,14 +1231,14 @@ static pj_status_t network_start_accept(pj_ssl_sock_t *ssock, status = network_create_params(ssock, localaddr, 0, ¶meters); if (status != PJ_SUCCESS) - return status; + return status; /* Create listener */ assock->listener = nw_listener_create(parameters); nw_release(parameters); if (!assock->listener) { PJ_LOG(2, (THIS_FILE, "Failed creating listener")); - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; } nw_listener_set_queue(assock->listener, assock->queue); @@ -1249,44 +1249,44 @@ static pj_status_t network_start_accept(pj_ssl_sock_t *ssock, nw_listener_set_state_changed_handler(assock->listener, ^(nw_listener_state_t state, nw_error_t error) { - errno = error ? nw_error_get_error_code(error) : 0; - - if (state == nw_listener_state_failed) { - warn("listener failed\n"); - pj_sockaddr_set_port(&ssock->local_addr, 0); - dispatch_semaphore_signal(assock->ev_semaphore); - } else if (state == nw_listener_state_ready) { - /* Update local port */ - pj_sockaddr_set_port(&ssock->local_addr, - nw_listener_get_port(assock->listener)); - dispatch_semaphore_signal(assock->ev_semaphore); - } else if (state == nw_listener_state_cancelled) { - /* We release the reference in ssl_destroy() */ - // nw_release(assock->listener); - // assock->listener = nil; - } - assock->lis_state = state; + errno = error ? nw_error_get_error_code(error) : 0; + + if (state == nw_listener_state_failed) { + warn("listener failed\n"); + pj_sockaddr_set_port(&ssock->local_addr, 0); + dispatch_semaphore_signal(assock->ev_semaphore); + } else if (state == nw_listener_state_ready) { + /* Update local port */ + pj_sockaddr_set_port(&ssock->local_addr, + nw_listener_get_port(assock->listener)); + dispatch_semaphore_signal(assock->ev_semaphore); + } else if (state == nw_listener_state_cancelled) { + /* We release the reference in ssl_destroy() */ + // nw_release(assock->listener); + // assock->listener = nil; + } + assock->lis_state = state; }); nw_listener_set_new_connection_handler(assock->listener, - ^(nw_connection_t connection) + ^(nw_connection_t connection) { - nw_endpoint_t endpoint = nw_connection_copy_endpoint(connection); - const struct sockaddr *address; - event_t event; - - address = nw_endpoint_get_address(endpoint); - - event.type = EVENT_ACCEPT; - event.body.accept_ev.newconn = connection; - pj_sockaddr_cp(&event.body.accept_ev.src_addr, address); - event.body.accept_ev.src_addr_len = pj_sockaddr_get_addr_len(address); - event.body.accept_ev.status = PJ_SUCCESS; - - nw_retain(connection); - event_manager_post_event(ssock, &event, PJ_TRUE); - - nw_release(endpoint); + nw_endpoint_t endpoint = nw_connection_copy_endpoint(connection); + const struct sockaddr *address; + event_t event; + + address = nw_endpoint_get_address(endpoint); + + event.type = EVENT_ACCEPT; + event.body.accept_ev.newconn = connection; + pj_sockaddr_cp(&event.body.accept_ev.src_addr, address); + event.body.accept_ev.src_addr_len = pj_sockaddr_get_addr_len(address); + event.body.accept_ev.status = PJ_SUCCESS; + + nw_retain(connection); + event_manager_post_event(ssock, &event, PJ_TRUE); + + nw_release(endpoint); }); /* Update local address */ @@ -1303,9 +1303,9 @@ static pj_status_t network_start_accept(pj_ssl_sock_t *ssock, dispatch_semaphore_wait(assock->ev_semaphore, DISPATCH_TIME_FOREVER); if (pj_sockaddr_get_port(&ssock->local_addr) == 0) { - /* Failed. */ - status = PJ_EEOF; - goto on_error; + /* Failed. */ + status = PJ_EEOF; + goto on_error; } return PJ_SUCCESS; @@ -1317,7 +1317,7 @@ static pj_status_t network_start_accept(pj_ssl_sock_t *ssock, static pj_status_t network_start_connect(pj_ssl_sock_t *ssock, - pj_ssl_start_connect_param *connect_param) + pj_ssl_start_connect_param *connect_param) { char ip_addr[PJ_INET6_ADDRSTRLEN]; unsigned port; @@ -1334,12 +1334,12 @@ static pj_status_t network_start_connect(pj_ssl_sock_t *ssock, int addr_len = connect_param->addr_len; PJ_ASSERT_RETURN(ssock && pool && localaddr && remaddr && addr_len, - PJ_EINVAL); + PJ_EINVAL); status = network_create_params(ssock, localaddr, port_range, - ¶meters); + ¶meters); if (status != PJ_SUCCESS) - return status; + return status; /* Create remote endpoint */ pj_sockaddr_print(remaddr, ip_addr,sizeof(ip_addr),0); @@ -1349,8 +1349,8 @@ static pj_status_t network_start_connect(pj_ssl_sock_t *ssock, endpoint = nw_endpoint_create_host(ip_addr, port_str); if (!endpoint) { PJ_LOG(2, (THIS_FILE, "Failed creating remote endpoint")); - nw_release(parameters); - return PJ_EINVALIDOP; + nw_release(parameters); + return PJ_EINVALIDOP; } connection = nw_connection_create(endpoint, parameters); @@ -1358,7 +1358,7 @@ static pj_status_t network_start_connect(pj_ssl_sock_t *ssock, nw_release(parameters); if (!connection) { PJ_LOG(2, (THIS_FILE, "Failed creating connection")); - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; } /* Hold a reference until cancelled */ @@ -1366,7 +1366,7 @@ static pj_status_t network_start_connect(pj_ssl_sock_t *ssock, status = network_setup_connection(ssock, connection); if (status != PJ_SUCCESS) - return status; + return status; /* Save remote address */ pj_sockaddr_cp(&ssock->rem_addr, remaddr); @@ -1391,15 +1391,15 @@ static pj_status_t network_start_connect(pj_ssl_sock_t *ssock, /* Create event manager */ if (event_manager_create() != PJ_SUCCESS) - return NULL; + return NULL; assock = PJ_POOL_ZALLOC_T(pool, applessl_sock_t); assock->queue = dispatch_queue_create("ssl_queue", DISPATCH_QUEUE_SERIAL); assock->ev_semaphore = dispatch_semaphore_create(0); if (!assock->queue || !assock->ev_semaphore) { - ssl_destroy(&assock->base); - return NULL; + ssl_destroy(&assock->base); + return NULL; } return (pj_ssl_sock_t *)assock; @@ -1416,31 +1416,31 @@ static pj_status_t ssl_create(pj_ssl_sock_t *ssock) static void close_connection(applessl_sock_t *assock) { if (assock->connection) { - unsigned i; - nw_connection_t conn = assock->connection; - - assock->connection = nil; - nw_connection_force_cancel(conn); - nw_release(conn); - - /* We need to wait until the connection is at cancelled state, - * otherwise events will still be delivered even though we - * already force cancel and release the connection. - */ - for (i = 0; i < 40; i++) { - if (assock->con_state == nw_connection_state_cancelled) break; - pj_thread_sleep(50); - } - - event_manager_remove_events(&assock->base); - - if (assock->con_state != nw_connection_state_cancelled) { - PJ_LOG(3, (THIS_FILE, "Warning: Failed to cancel SSL connection " - "%p %d", assock, assock->con_state)); - } + unsigned i; + nw_connection_t conn = assock->connection; + + assock->connection = nil; + nw_connection_force_cancel(conn); + nw_release(conn); + + /* We need to wait until the connection is at cancelled state, + * otherwise events will still be delivered even though we + * already force cancel and release the connection. + */ + for (i = 0; i < 40; i++) { + if (assock->con_state == nw_connection_state_cancelled) break; + pj_thread_sleep(50); + } + + event_manager_remove_events(&assock->base); + + if (assock->con_state != nw_connection_state_cancelled) { + PJ_LOG(3, (THIS_FILE, "Warning: Failed to cancel SSL connection " + "%p %d", assock, assock->con_state)); + } #if SSL_DEBUG - PJ_LOG(3, (THIS_FILE, "SSL connection %p closed", assock)); + PJ_LOG(3, (THIS_FILE, "SSL connection %p closed", assock)); #endif } @@ -1452,18 +1452,18 @@ static void ssl_close_sockets(pj_ssl_sock_t *ssock) applessl_sock_t *assock = (applessl_sock_t *)ssock; if (assock->identity) { - nw_release(assock->identity); - assock->identity = nil; + nw_release(assock->identity); + assock->identity = nil; } if (assock->trust) { - nw_release(assock->trust); - assock->trust = nil; + nw_release(assock->trust); + assock->trust = nil; } /* This can happen when pj_ssl_sock_create() fails. */ if (!ssock->write_mutex) - return; + return; pj_lock_acquire(ssock->write_mutex); close_connection(assock); @@ -1478,21 +1478,21 @@ static void ssl_destroy(pj_ssl_sock_t *ssock) close_connection(assock); if (assock->listener) { - unsigned i; - - nw_listener_set_new_connection_handler(assock->listener, nil); - nw_listener_cancel(assock->listener); - - for (i = 0; i < 20; i++) { - if (assock->lis_state == nw_listener_state_cancelled) break; - pj_thread_sleep(50); - } - if (assock->lis_state != nw_listener_state_cancelled) { - PJ_LOG(3, (THIS_FILE, "Warning: Failed to cancel SSL listener " - "%p %d", assock, assock->lis_state)); - } - nw_release(assock->listener); - assock->listener = nil; + unsigned i; + + nw_listener_set_new_connection_handler(assock->listener, nil); + nw_listener_cancel(assock->listener); + + for (i = 0; i < 20; i++) { + if (assock->lis_state == nw_listener_state_cancelled) break; + pj_thread_sleep(50); + } + if (assock->lis_state != nw_listener_state_cancelled) { + PJ_LOG(3, (THIS_FILE, "Warning: Failed to cancel SSL listener " + "%p %d", assock, assock->lis_state)); + } + nw_release(assock->listener); + assock->listener = nil; } event_manager_remove_events(ssock); @@ -1501,17 +1501,17 @@ static void ssl_destroy(pj_ssl_sock_t *ssock) * we need to signal it before destroying ourselves. */ if (assock->ev_semaphore) { - dispatch_semaphore_signal(assock->ev_semaphore); + dispatch_semaphore_signal(assock->ev_semaphore); } if (assock->queue) { - dispatch_release(assock->queue); - assock->queue = NULL; + dispatch_release(assock->queue); + assock->queue = NULL; } if (assock->ev_semaphore) { - dispatch_release(assock->ev_semaphore); - assock->ev_semaphore = nil; + dispatch_release(assock->ev_semaphore); + assock->ev_semaphore = nil; } /* Destroy circular buffers */ @@ -1707,18 +1707,18 @@ static void ssl_reset_sock_state(pj_ssl_sock_t *ssock) case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: return "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"; - case TLS_AES_128_GCM_SHA256: - return "TLS_AES_128_GCM_SHA256"; - case TLS_AES_256_GCM_SHA384: - return "TLS_AES_256_GCM_SHA384"; - case TLS_CHACHA20_POLY1305_SHA256: - return "TLS_CHACHA20_POLY1305_SHA256"; - case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: - return "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"; - case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: - return "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"; - case TLS_RSA_WITH_3DES_EDE_CBC_SHA: - return "TLS_RSA_WITH_3DES_EDE_CBC_SHA"; + case TLS_AES_128_GCM_SHA256: + return "TLS_AES_128_GCM_SHA256"; + case TLS_AES_256_GCM_SHA384: + return "TLS_AES_256_GCM_SHA384"; + case TLS_CHACHA20_POLY1305_SHA256: + return "TLS_CHACHA20_POLY1305_SHA256"; + case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: + return "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"; + case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: + return "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"; + case TLS_RSA_WITH_3DES_EDE_CBC_SHA: + return "TLS_RSA_WITH_3DES_EDE_CBC_SHA"; default: return "TLS_CIPHER_STRING_UNKNOWN"; @@ -1732,41 +1732,41 @@ static void ssl_ciphers_populate(void) * taken from the tls_ciphersuite_t doc. */ tls_ciphersuite_t ciphers[] = { - tls_ciphersuite_AES_128_GCM_SHA256, - tls_ciphersuite_AES_256_GCM_SHA384, - tls_ciphersuite_CHACHA20_POLY1305_SHA256, - tls_ciphersuite_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, - tls_ciphersuite_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - tls_ciphersuite_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, - tls_ciphersuite_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - tls_ciphersuite_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - tls_ciphersuite_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, - tls_ciphersuite_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, - tls_ciphersuite_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, - tls_ciphersuite_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, - tls_ciphersuite_ECDHE_RSA_WITH_AES_128_CBC_SHA, - tls_ciphersuite_ECDHE_RSA_WITH_AES_128_CBC_SHA256, - tls_ciphersuite_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - tls_ciphersuite_ECDHE_RSA_WITH_AES_256_CBC_SHA, - tls_ciphersuite_ECDHE_RSA_WITH_AES_256_CBC_SHA384, - tls_ciphersuite_ECDHE_RSA_WITH_AES_256_GCM_SHA384, - tls_ciphersuite_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, - tls_ciphersuite_RSA_WITH_3DES_EDE_CBC_SHA, - tls_ciphersuite_RSA_WITH_AES_128_CBC_SHA, - tls_ciphersuite_RSA_WITH_AES_128_CBC_SHA256, - tls_ciphersuite_RSA_WITH_AES_128_GCM_SHA256, - tls_ciphersuite_RSA_WITH_AES_256_CBC_SHA, - tls_ciphersuite_RSA_WITH_AES_256_CBC_SHA256, - tls_ciphersuite_RSA_WITH_AES_256_GCM_SHA384 + tls_ciphersuite_AES_128_GCM_SHA256, + tls_ciphersuite_AES_256_GCM_SHA384, + tls_ciphersuite_CHACHA20_POLY1305_SHA256, + tls_ciphersuite_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, + tls_ciphersuite_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, + tls_ciphersuite_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, + tls_ciphersuite_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + tls_ciphersuite_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, + tls_ciphersuite_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, + tls_ciphersuite_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, + tls_ciphersuite_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, + tls_ciphersuite_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, + tls_ciphersuite_ECDHE_RSA_WITH_AES_128_CBC_SHA, + tls_ciphersuite_ECDHE_RSA_WITH_AES_128_CBC_SHA256, + tls_ciphersuite_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + tls_ciphersuite_ECDHE_RSA_WITH_AES_256_CBC_SHA, + tls_ciphersuite_ECDHE_RSA_WITH_AES_256_CBC_SHA384, + tls_ciphersuite_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + tls_ciphersuite_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, + tls_ciphersuite_RSA_WITH_3DES_EDE_CBC_SHA, + tls_ciphersuite_RSA_WITH_AES_128_CBC_SHA, + tls_ciphersuite_RSA_WITH_AES_128_CBC_SHA256, + tls_ciphersuite_RSA_WITH_AES_128_GCM_SHA256, + tls_ciphersuite_RSA_WITH_AES_256_CBC_SHA, + tls_ciphersuite_RSA_WITH_AES_256_CBC_SHA256, + tls_ciphersuite_RSA_WITH_AES_256_GCM_SHA384 }; if (!ssl_cipher_num) { - unsigned i; - - ssl_cipher_num = sizeof(ciphers)/sizeof(ciphers[0]); - for (i = 0; i < ssl_cipher_num; i++) { - ssl_ciphers[i].id = (pj_ssl_cipher)ciphers[i]; - ssl_ciphers[i].name = sslGetCipherSuiteString(ciphers[i]); - } + unsigned i; + + ssl_cipher_num = sizeof(ciphers)/sizeof(ciphers[0]); + for (i = 0; i < ssl_cipher_num; i++) { + ssl_ciphers[i].id = (pj_ssl_cipher)ciphers[i]; + ssl_ciphers[i].name = sslGetCipherSuiteString(ciphers[i]); + } } } @@ -1781,11 +1781,11 @@ static pj_ssl_cipher ssl_get_cipher(pj_ssl_sock_t *ssock) #if !TARGET_OS_IPHONE static void get_info_and_cn(CFArrayRef array, CFMutableStringRef info, - CFStringRef *cn) + CFStringRef *cn) { const void *keys[] = {kSecOIDOrganizationalUnitName, kSecOIDCountryName, - kSecOIDStateProvinceName, kSecOIDLocalityName, - kSecOIDOrganizationName, kSecOIDCommonName}; + kSecOIDStateProvinceName, kSecOIDLocalityName, + kSecOIDOrganizationName, kSecOIDCommonName}; const char *labels[] = { "OU=", "C=", "ST=", "L=", "O=", "CN="}; pj_bool_t add_separator = PJ_FALSE; int i, n; @@ -1804,25 +1804,25 @@ static void get_info_and_cn(CFArrayRef array, CFMutableStringRef info, if (!CFEqual(dictkey, keys[i])) continue; str = (CFStringRef) CFDictionaryGetValue(dict, - kSecPropertyKeyValue); - + kSecPropertyKeyValue); + if (CFStringGetLength(str) > 0) { - if (add_separator) { + if (add_separator) { CFStringAppendCString(info, "/", kCFStringEncodingUTF8); } CFStringAppendCString(info, labels[i], kCFStringEncodingUTF8); CFStringAppend(info, str); - add_separator = PJ_TRUE; - - if (CFEqual(keys[i], kSecOIDCommonName)) - *cn = str; + add_separator = PJ_TRUE; + + if (CFEqual(keys[i], kSecOIDCommonName)) + *cn = str; } } } } static CFDictionaryRef get_cert_oid(SecCertificateRef cert, CFStringRef oid, - CFTypeRef *value) + CFTypeRef *value) { void *key[1]; CFArrayRef key_arr; @@ -1830,14 +1830,14 @@ static CFDictionaryRef get_cert_oid(SecCertificateRef cert, CFStringRef oid, key[0] = (void *)oid; key_arr = CFArrayCreate(NULL, (const void **)key, 1, - &kCFTypeArrayCallBacks); + &kCFTypeArrayCallBacks); vals = SecCertificateCopyValues(cert, key_arr, NULL); dict = CFDictionaryGetValue(vals, key[0]); if (!dict) { - CFRelease(key_arr); - CFRelease(vals); - return NULL; + CFRelease(key_arr); + CFRelease(vals); + return NULL; } *value = CFDictionaryGetValue(dict, kSecPropertyKeyValue); @@ -1854,7 +1854,7 @@ static CFDictionaryRef get_cert_oid(SecCertificateRef cert, CFStringRef oid, * issuer and the serial number. */ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, - SecCertificateRef cert) + SecCertificateRef cert) { pj_bool_t update_needed; char buf[512]; @@ -1882,12 +1882,12 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, CFArrayRef issuer_vals; dict = get_cert_oid(cert, kSecOIDX509V1IssuerName, - (CFTypeRef *)&issuer_vals); + (CFTypeRef *)&issuer_vals); if (dict) { - get_info_and_cn(issuer_vals, issuer_info, &issuer_cn); - if (issuer_cn) - issuer_cn = CFStringCreateCopy(NULL, issuer_cn); - CFRelease(dict); + get_info_and_cn(issuer_vals, issuer_info, &issuer_cn); + if (issuer_cn) + issuer_cn = CFStringCreateCopy(NULL, issuer_cn); + CFRelease(dict); } } #endif @@ -1895,11 +1895,11 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, /* Get serial no */ if (__builtin_available(macOS 10.13, iOS 11.0, *)) { - serial = SecCertificateCopySerialNumberData(cert, NULL); - if (serial) { - serial_no = CFDataGetBytePtr(serial); - serialsize = CFDataGetLength(serial); - } + serial = SecCertificateCopySerialNumberData(cert, NULL); + if (serial) { + serial_no = CFDataGetBytePtr(serial); + serialsize = CFDataGetLength(serial); + } } /* Check if the contents need to be updated */ @@ -1920,10 +1920,10 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, CFStringRef version; dict = get_cert_oid(cert, kSecOIDX509V1Version, - (CFTypeRef *)&version); + (CFTypeRef *)&version); if (dict) { - ci->version = CFStringGetIntValue(version); - CFRelease(dict); + ci->version = CFStringGetIntValue(version); + CFRelease(dict); } } #endif @@ -1932,19 +1932,19 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, pj_strdup2(pool, &ci->issuer.info, buf); #if !TARGET_OS_IPHONE if (issuer_cn) { - CFStringGetCString(issuer_cn, buf, bufsize, kCFStringEncodingUTF8); - pj_strdup2(pool, &ci->issuer.cn, buf); - CFRelease(issuer_cn); + CFStringGetCString(issuer_cn, buf, bufsize, kCFStringEncodingUTF8); + pj_strdup2(pool, &ci->issuer.cn, buf); + CFRelease(issuer_cn); } #endif CFRelease(issuer_info); /* Serial number */ if (serial) { - if (serialsize > sizeof(ci->serial_no)) - serialsize = sizeof(ci->serial_no); - pj_memcpy(ci->serial_no, serial_no, serialsize); - CFRelease(serial); + if (serialsize > sizeof(ci->serial_no)) + serialsize = sizeof(ci->serial_no); + pj_memcpy(ci->serial_no, serial_no, serialsize); + CFRelease(serial); } /* Subject */ @@ -1958,17 +1958,17 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, CFMutableStringRef subject_info; dict = get_cert_oid(cert, kSecOIDX509V1SubjectName, - (CFTypeRef *)&subject); + (CFTypeRef *)&subject); if (dict) { - subject_info = CFStringCreateMutable(NULL, 0); + subject_info = CFStringCreateMutable(NULL, 0); - get_info_and_cn(subject, subject_info, &str); + get_info_and_cn(subject, subject_info, &str); - CFStringGetCString(subject_info, buf, bufsize, kCFStringEncodingUTF8); - pj_strdup2(pool, &ci->subject.info, buf); + CFStringGetCString(subject_info, buf, bufsize, kCFStringEncodingUTF8); + pj_strdup2(pool, &ci->subject.info, buf); - CFRelease(dict); - CFRelease(subject_info); + CFRelease(dict); + CFRelease(subject_info); } } #endif @@ -1980,26 +1980,26 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, double interval; dict = get_cert_oid(cert, kSecOIDX509V1ValidityNotBefore, - (CFTypeRef *)&validity); + (CFTypeRef *)&validity); if (dict) { if (CFNumberGetValue(validity, CFNumberGetType(validity), - &interval)) + &interval)) { /* Darwin's absolute reference date is 1 Jan 2001 00:00:00 GMT */ - ci->validity.start.sec = (unsigned long)interval + 978278400L; - } - CFRelease(dict); + ci->validity.start.sec = (unsigned long)interval + 978278400L; + } + CFRelease(dict); } dict = get_cert_oid(cert, kSecOIDX509V1ValidityNotAfter, - (CFTypeRef *)&validity); + (CFTypeRef *)&validity); if (dict) { - if (CFNumberGetValue(validity, CFNumberGetType(validity), - &interval)) - { - ci->validity.end.sec = (unsigned long)interval + 978278400L; - } - CFRelease(dict); + if (CFNumberGetValue(validity, CFNumberGetType(validity), + &interval)) + { + ci->validity.end.sec = (unsigned long)interval + 978278400L; + } + CFRelease(dict); } } #endif @@ -2012,78 +2012,78 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, dict = get_cert_oid(cert, kSecOIDSubjectAltName, (CFTypeRef *)&altname); if (!dict || !CFArrayGetCount(altname)) - return; + return; ci->subj_alt_name.entry = pj_pool_calloc(pool, CFArrayGetCount(altname), - sizeof(*ci->subj_alt_name.entry)); + sizeof(*ci->subj_alt_name.entry)); for (i = 0; i < CFArrayGetCount(altname); ++i) { - CFDictionaryRef item; - CFStringRef label, value; - pj_ssl_cert_name_type type = PJ_SSL_CERT_NAME_UNKNOWN; + CFDictionaryRef item; + CFStringRef label, value; + pj_ssl_cert_name_type type = PJ_SSL_CERT_NAME_UNKNOWN; item = CFArrayGetValueAtIndex(altname, i); if (CFGetTypeID(item) != CFDictionaryGetTypeID()) continue; label = (CFStringRef)CFDictionaryGetValue(item, kSecPropertyKeyLabel); - if (CFGetTypeID(label) != CFStringGetTypeID()) - continue; + if (CFGetTypeID(label) != CFStringGetTypeID()) + continue; value = (CFStringRef)CFDictionaryGetValue(item, kSecPropertyKeyValue); - if (!CFStringCompare(label, CFSTR("DNS Name"), - kCFCompareCaseInsensitive)) - { - if (CFGetTypeID(value) != CFStringGetTypeID()) - continue; - CFStringGetCString(value, buf, bufsize, kCFStringEncodingUTF8); - type = PJ_SSL_CERT_NAME_DNS; - } else if (!CFStringCompare(label, CFSTR("IP Address"), - kCFCompareCaseInsensitive)) - { - if (CFGetTypeID(value) != CFStringGetTypeID()) - continue; - CFStringGetCString(value, buf, bufsize, kCFStringEncodingUTF8); - type = PJ_SSL_CERT_NAME_IP; - } else if (!CFStringCompare(label, CFSTR("Email Address"), - kCFCompareCaseInsensitive)) - { - if (CFGetTypeID(value) != CFStringGetTypeID()) - continue; - CFStringGetCString(value, buf, bufsize, kCFStringEncodingUTF8); - type = PJ_SSL_CERT_NAME_RFC822; - } else if (!CFStringCompare(label, CFSTR("URI"), - kCFCompareCaseInsensitive)) - { - CFStringRef uri; - - if (CFGetTypeID(value) != CFURLGetTypeID()) - continue; - uri = CFURLGetString((CFURLRef)value); - CFStringGetCString(uri, buf, bufsize, kCFStringEncodingUTF8); - type = PJ_SSL_CERT_NAME_URI; - } - - if (type != PJ_SSL_CERT_NAME_UNKNOWN) { - ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type; - if (type == PJ_SSL_CERT_NAME_IP) { - char ip_buf[PJ_INET6_ADDRSTRLEN+10]; - int len = CFStringGetLength(value); - int af = pj_AF_INET(); - - if (len == sizeof(pj_in6_addr)) af = pj_AF_INET6(); - pj_inet_ntop2(af, buf, ip_buf, sizeof(ip_buf)); - pj_strdup2(pool, - &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, - ip_buf); - } else { - pj_strdup2(pool, - &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, - buf); - } - ci->subj_alt_name.cnt++; - } + if (!CFStringCompare(label, CFSTR("DNS Name"), + kCFCompareCaseInsensitive)) + { + if (CFGetTypeID(value) != CFStringGetTypeID()) + continue; + CFStringGetCString(value, buf, bufsize, kCFStringEncodingUTF8); + type = PJ_SSL_CERT_NAME_DNS; + } else if (!CFStringCompare(label, CFSTR("IP Address"), + kCFCompareCaseInsensitive)) + { + if (CFGetTypeID(value) != CFStringGetTypeID()) + continue; + CFStringGetCString(value, buf, bufsize, kCFStringEncodingUTF8); + type = PJ_SSL_CERT_NAME_IP; + } else if (!CFStringCompare(label, CFSTR("Email Address"), + kCFCompareCaseInsensitive)) + { + if (CFGetTypeID(value) != CFStringGetTypeID()) + continue; + CFStringGetCString(value, buf, bufsize, kCFStringEncodingUTF8); + type = PJ_SSL_CERT_NAME_RFC822; + } else if (!CFStringCompare(label, CFSTR("URI"), + kCFCompareCaseInsensitive)) + { + CFStringRef uri; + + if (CFGetTypeID(value) != CFURLGetTypeID()) + continue; + uri = CFURLGetString((CFURLRef)value); + CFStringGetCString(uri, buf, bufsize, kCFStringEncodingUTF8); + type = PJ_SSL_CERT_NAME_URI; + } + + if (type != PJ_SSL_CERT_NAME_UNKNOWN) { + ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type; + if (type == PJ_SSL_CERT_NAME_IP) { + char ip_buf[PJ_INET6_ADDRSTRLEN+10]; + int len = CFStringGetLength(value); + int af = pj_AF_INET(); + + if (len == sizeof(pj_in6_addr)) af = pj_AF_INET6(); + pj_inet_ntop2(af, buf, ip_buf, sizeof(ip_buf)); + pj_strdup2(pool, + &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, + ip_buf); + } else { + pj_strdup2(pool, + &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, + buf); + } + ci->subj_alt_name.cnt++; + } } CFRelease(dict); @@ -2107,29 +2107,29 @@ static void ssl_update_certs_info(pj_ssl_sock_t *ssock) if (assock->identity) { CFArrayRef cert_arr; - cert_arr = sec_identity_copy_certificates_ref(assock->identity); - if (cert_arr) { - count = CFArrayGetCount(cert_arr); - if (count > 0) { - CFTypeRef elmt; - - elmt = (CFTypeRef) CFArrayGetValueAtIndex(cert_arr, 0); - if (CFGetTypeID(elmt) == SecCertificateGetTypeID()) { - cert = (SecCertificateRef)elmt; - get_cert_info(ssock->pool, &ssock->local_cert_info, cert); - } - } - CFRelease(cert_arr); - } + cert_arr = sec_identity_copy_certificates_ref(assock->identity); + if (cert_arr) { + count = CFArrayGetCount(cert_arr); + if (count > 0) { + CFTypeRef elmt; + + elmt = (CFTypeRef) CFArrayGetValueAtIndex(cert_arr, 0); + if (CFGetTypeID(elmt) == SecCertificateGetTypeID()) { + cert = (SecCertificateRef)elmt; + get_cert_info(ssock->pool, &ssock->local_cert_info, cert); + } + } + CFRelease(cert_arr); + } } /* Get active remote certificate */ if (trust) { - count = SecTrustGetCertificateCount(trust); - if (count > 0) { - cert = SecTrustGetCertificateAtIndex(trust, 0); - get_cert_info(ssock->pool, &ssock->remote_cert_info, cert); - } + count = SecTrustGetCertificateCount(trust); + if (count > 0) { + cert = SecTrustGetCertificateAtIndex(trust, 0); + get_cert_info(ssock->pool, &ssock->remote_cert_info, cert); + } } } @@ -2165,7 +2165,7 @@ static pj_status_t ssl_read(pj_ssl_sock_t *ssock, void *data, int *size) if (circ_empty(&ssock->circ_buf_input)) { pj_lock_release(ssock->circ_buf_input_mutex); *size = 0; - return PJ_SUCCESS; + return PJ_SUCCESS; } circ_buf_size = circ_size(&ssock->circ_buf_input); @@ -2185,7 +2185,7 @@ static pj_status_t ssl_read(pj_ssl_sock_t *ssock, void *data, int *size) * sending. */ static pj_status_t ssl_write(pj_ssl_sock_t *ssock, const void *data, - pj_ssize_t size, int *nwritten) + pj_ssize_t size, int *nwritten) { pj_status_t status; diff --git a/pjlib/src/pj/ssl_sock_common.c b/pjlib/src/pj/ssl_sock_common.c index bf8e1dee46..68804f18d7 100644 --- a/pjlib/src/pj/ssl_sock_common.c +++ b/pjlib/src/pj/ssl_sock_common.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * @@ -58,26 +57,26 @@ PJ_DEF(void) pj_ssl_sock_param_default(pj_ssl_sock_param *param) * Duplicate SSL socket parameter. */ PJ_DEF(void) pj_ssl_sock_param_copy( pj_pool_t *pool, - pj_ssl_sock_param *dst, - const pj_ssl_sock_param *src) + pj_ssl_sock_param *dst, + const pj_ssl_sock_param *src) { /* Init secure socket param */ pj_memcpy(dst, src, sizeof(*dst)); if (src->ciphers_num > 0) { - unsigned i; - dst->ciphers = (pj_ssl_cipher*) - pj_pool_calloc(pool, src->ciphers_num, - sizeof(pj_ssl_cipher)); - for (i = 0; i < src->ciphers_num; ++i) - dst->ciphers[i] = src->ciphers[i]; + unsigned i; + dst->ciphers = (pj_ssl_cipher*) + pj_pool_calloc(pool, src->ciphers_num, + sizeof(pj_ssl_cipher)); + for (i = 0; i < src->ciphers_num; ++i) + dst->ciphers[i] = src->ciphers[i]; } if (src->curves_num > 0) { - unsigned i; - dst->curves = (pj_ssl_curve *)pj_pool_calloc(pool, src->curves_num, - sizeof(pj_ssl_curve)); - for (i = 0; i < src->curves_num; ++i) - dst->curves[i] = src->curves[i]; + unsigned i; + dst->curves = (pj_ssl_curve *)pj_pool_calloc(pool, src->curves_num, + sizeof(pj_ssl_curve)); + for (i = 0; i < src->curves_num; ++i) + dst->curves[i] = src->curves[i]; } if (src->server_name.slen) { @@ -86,21 +85,21 @@ PJ_DEF(void) pj_ssl_sock_param_copy( pj_pool_t *pool, } if (src->sigalgs.slen) { - /* Sigalgs name must be null-terminated */ - pj_strdup_with_null(pool, &dst->sigalgs, &src->sigalgs); + /* Sigalgs name must be null-terminated */ + pj_strdup_with_null(pool, &dst->sigalgs, &src->sigalgs); } if (src->entropy_path.slen) { - /* Path name must be null-terminated */ - pj_strdup_with_null(pool, &dst->entropy_path, &src->entropy_path); + /* Path name must be null-terminated */ + pj_strdup_with_null(pool, &dst->entropy_path, &src->entropy_path); } } PJ_DEF(pj_status_t) pj_ssl_cert_get_verify_status_strings( - pj_uint32_t verify_status, - const char *error_strings[], - unsigned *count) + pj_uint32_t verify_status, + const char *error_strings[], + unsigned *count) { unsigned i = 0, shift_idx = 0; unsigned unknown = 0; @@ -109,79 +108,79 @@ PJ_DEF(pj_status_t) pj_ssl_cert_get_verify_status_strings( PJ_ASSERT_RETURN(error_strings && count, PJ_EINVAL); if (verify_status == PJ_SSL_CERT_ESUCCESS && *count) { - error_strings[0] = "OK"; - *count = 1; - return PJ_SUCCESS; + error_strings[0] = "OK"; + *count = 1; + return PJ_SUCCESS; } errs = verify_status; while (errs && i < *count) { - pj_uint32_t err; - const char *p = NULL; - - if ((errs & 1) == 0) { - shift_idx++; - errs >>= 1; - continue; - } - - err = (1 << shift_idx); - - switch (err) { - case PJ_SSL_CERT_EISSUER_NOT_FOUND: - p = "The issuer certificate cannot be found"; - break; - case PJ_SSL_CERT_EUNTRUSTED: - p = "The certificate is untrusted"; - break; - case PJ_SSL_CERT_EVALIDITY_PERIOD: - p = "The certificate has expired or not yet valid"; - break; - case PJ_SSL_CERT_EINVALID_FORMAT: - p = "One or more fields of the certificate cannot be decoded " - "due to invalid format"; - break; - case PJ_SSL_CERT_EISSUER_MISMATCH: - p = "The issuer info in the certificate does not match to the " - "(candidate) issuer certificate"; - break; - case PJ_SSL_CERT_ECRL_FAILURE: - p = "The CRL certificate cannot be found or cannot be read " - "properly"; - break; - case PJ_SSL_CERT_EREVOKED: - p = "The certificate has been revoked"; - break; - case PJ_SSL_CERT_EINVALID_PURPOSE: - p = "The certificate or CA certificate cannot be used for the " - "specified purpose"; - break; - case PJ_SSL_CERT_ECHAIN_TOO_LONG: - p = "The certificate chain length is too long"; - break; - case PJ_SSL_CERT_EIDENTITY_NOT_MATCH: - p = "The server identity does not match to any identities " - "specified in the certificate"; - break; - case PJ_SSL_CERT_EUNKNOWN: - default: - unknown++; - break; - } - - /* Set error string */ - if (p) - error_strings[i++] = p; - - /* Next */ - shift_idx++; - errs >>= 1; + pj_uint32_t err; + const char *p = NULL; + + if ((errs & 1) == 0) { + shift_idx++; + errs >>= 1; + continue; + } + + err = (1 << shift_idx); + + switch (err) { + case PJ_SSL_CERT_EISSUER_NOT_FOUND: + p = "The issuer certificate cannot be found"; + break; + case PJ_SSL_CERT_EUNTRUSTED: + p = "The certificate is untrusted"; + break; + case PJ_SSL_CERT_EVALIDITY_PERIOD: + p = "The certificate has expired or not yet valid"; + break; + case PJ_SSL_CERT_EINVALID_FORMAT: + p = "One or more fields of the certificate cannot be decoded " + "due to invalid format"; + break; + case PJ_SSL_CERT_EISSUER_MISMATCH: + p = "The issuer info in the certificate does not match to the " + "(candidate) issuer certificate"; + break; + case PJ_SSL_CERT_ECRL_FAILURE: + p = "The CRL certificate cannot be found or cannot be read " + "properly"; + break; + case PJ_SSL_CERT_EREVOKED: + p = "The certificate has been revoked"; + break; + case PJ_SSL_CERT_EINVALID_PURPOSE: + p = "The certificate or CA certificate cannot be used for the " + "specified purpose"; + break; + case PJ_SSL_CERT_ECHAIN_TOO_LONG: + p = "The certificate chain length is too long"; + break; + case PJ_SSL_CERT_EIDENTITY_NOT_MATCH: + p = "The server identity does not match to any identities " + "specified in the certificate"; + break; + case PJ_SSL_CERT_EUNKNOWN: + default: + unknown++; + break; + } + + /* Set error string */ + if (p) + error_strings[i++] = p; + + /* Next */ + shift_idx++; + errs >>= 1; } /* Unknown error */ if (unknown && i < *count) - error_strings[i++] = "Unknown verification error"; + error_strings[i++] = "Unknown verification error"; *count = i; diff --git a/pjlib/src/pj/ssl_sock_darwin.c b/pjlib/src/pj/ssl_sock_darwin.c index eaa3c19163..d6910fdfef 100644 --- a/pjlib/src/pj/ssl_sock_darwin.c +++ b/pjlib/src/pj/ssl_sock_darwin.c @@ -54,9 +54,9 @@ /* Secure socket structure definition. */ typedef struct darwinssl_sock_t { - pj_ssl_sock_t base; + pj_ssl_sock_t base; - SSLContextRef ssl_ctx; + SSLContextRef ssl_ctx; } darwinssl_sock_t; @@ -66,15 +66,15 @@ typedef struct darwinssl_sock_t { ******************************************************************* */ -#define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + \ - PJ_ERRNO_SPACE_SIZE*6) +#define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + \ + PJ_ERRNO_SPACE_SIZE*6) -#define PJ_SSL_ERRNO_SPACE_SIZE PJ_ERRNO_SPACE_SIZE +#define PJ_SSL_ERRNO_SPACE_SIZE PJ_ERRNO_SPACE_SIZE /* Convert from Darwin SSL error to pj_status_t. */ static pj_status_t pj_status_from_err(darwinssl_sock_t *dssock, - const char *msg, - OSStatus err) + const char *msg, + OSStatus err) { pj_status_t status = (pj_status_t)-err; @@ -83,13 +83,13 @@ static pj_status_t pj_status_from_err(darwinssl_sock_t *dssock, errmsg = SecCopyErrorMessageString(err, NULL); PJ_LOG(3, (THIS_FILE, "Darwin SSL error %s [%d]: %s", - (msg? msg: ""), err, - CFStringGetCStringPtr(errmsg, kCFStringEncodingUTF8))); + (msg? msg: ""), err, + CFStringGetCStringPtr(errmsg, kCFStringEncodingUTF8))); CFRelease(errmsg); } if (status > PJ_SSL_ERRNO_SPACE_SIZE) - status = PJ_SSL_ERRNO_SPACE_SIZE; + status = PJ_SSL_ERRNO_SPACE_SIZE; status += PJ_SSL_ERRNO_START; if (dssock) @@ -111,7 +111,7 @@ static OSStatus SocketWrite(SSLConnectionRef connection, pj_lock_acquire(ssock->write_mutex); if (circ_write(&ssock->circ_buf_output, data, len) != PJ_SUCCESS) { pj_lock_release(ssock->write_mutex); - *dataLength = 0; + *dataLength = 0; return errSSLInternal; } pj_lock_release(ssock->write_mutex); @@ -135,7 +135,7 @@ static OSStatus SocketRead(SSLConnectionRef connection, /* Data buffers not yet filled */ *dataLength = 0; - return errSSLWouldBlock; + return errSSLWouldBlock; } pj_size_t circ_buf_size = circ_size(&ssock->circ_buf_input); @@ -156,7 +156,7 @@ static pj_ssl_sock_t *ssl_alloc(pj_pool_t *pool) } static pj_status_t create_data_from_file(CFDataRef *data, - pj_str_t *fname, pj_str_t *path) + pj_str_t *fname, pj_str_t *path) { CFURLRef file; CFReadStreamRef read_stream; @@ -168,30 +168,30 @@ static pj_status_t create_data_from_file(CFDataRef *data, CFStringRef path_str; path_str = CFStringCreateWithBytes(NULL, (const UInt8 *)path->ptr, - path->slen, - kCFStringEncodingUTF8, false); + path->slen, + kCFStringEncodingUTF8, false); if (!path_str) return PJ_ENOMEM; filepath = CFURLCreateWithFileSystemPath(NULL, path_str, - kCFURLPOSIXPathStyle, true); + kCFURLPOSIXPathStyle, true); CFRelease(path_str); if (!filepath) return PJ_ENOMEM; path_str = CFStringCreateWithBytes(NULL, (const UInt8 *)fname->ptr, - fname->slen, - kCFStringEncodingUTF8, false); + fname->slen, + kCFStringEncodingUTF8, false); if (!path_str) { - CFRelease(filepath); - return PJ_ENOMEM; + CFRelease(filepath); + return PJ_ENOMEM; } file = CFURLCreateCopyAppendingPathComponent(NULL, filepath, - path_str, false); + path_str, false); CFRelease(path_str); CFRelease(filepath); } else { file = CFURLCreateFromFileSystemRepresentation(NULL, - (const UInt8 *)fname->ptr, fname->slen, false); + (const UInt8 *)fname->ptr, fname->slen, false); } if (!file) @@ -210,11 +210,11 @@ static pj_status_t create_data_from_file(CFDataRef *data, } nbytes = CFReadStreamRead(read_stream, data_buf, - sizeof(data_buf)); + sizeof(data_buf)); if (nbytes > 0) *data = CFDataCreate(NULL, data_buf, nbytes); else - *data = NULL; + *data = NULL; CFReadStreamClose(read_stream); CFRelease(read_stream); @@ -239,128 +239,128 @@ static pj_status_t set_cert(darwinssl_sock_t *dssock, pj_ssl_cert_t *cert) if (cert->privkey_file.slen || cert->privkey_buf.slen || - cert->privkey_pass.slen) + cert->privkey_pass.slen) { - PJ_LOG(3, (THIS_FILE, "Ignoring supplied private key. Private key " - "must be placed in the keychain instead.")); + PJ_LOG(3, (THIS_FILE, "Ignoring supplied private key. Private key " + "must be placed in the keychain instead.")); } if (cert->cert_file.slen) { - status = create_data_from_file(&cert_data, &cert->cert_file, NULL); - if (status != PJ_SUCCESS) { - PJ_LOG(2, (THIS_FILE, "Failed reading cert file")); - return status; - } + status = create_data_from_file(&cert_data, &cert->cert_file, NULL); + if (status != PJ_SUCCESS) { + PJ_LOG(2, (THIS_FILE, "Failed reading cert file")); + return status; + } } else if (cert->cert_buf.slen) { - cert_data = CFDataCreate(NULL, (const UInt8 *)cert->cert_buf.ptr, - cert->cert_buf.slen); - if (!cert_data) - return PJ_ENOMEM; + cert_data = CFDataCreate(NULL, (const UInt8 *)cert->cert_buf.ptr, + cert->cert_buf.slen); + if (!cert_data) + return PJ_ENOMEM; } if (cert_data) { if (cert->privkey_pass.slen) { - password = CFStringCreateWithBytes(NULL, - (const UInt8 *)cert->privkey_pass.ptr, - cert->privkey_pass.slen, - kCFStringEncodingUTF8, - false); - keys[0] = (void *)kSecImportExportPassphrase; - values[0] = (void *)password; + password = CFStringCreateWithBytes(NULL, + (const UInt8 *)cert->privkey_pass.ptr, + cert->privkey_pass.slen, + kCFStringEncodingUTF8, + false); + keys[0] = (void *)kSecImportExportPassphrase; + values[0] = (void *)password; } options = CFDictionaryCreate(NULL, (const void **)keys, - (const void **)values, - (password? 1: 0), NULL, NULL); + (const void **)values, + (password? 1: 0), NULL, NULL); if (!options) - return PJ_ENOMEM; + return PJ_ENOMEM; #if TARGET_OS_IPHONE err = SecPKCS12Import(cert_data, options, &items); #else { - SecExternalFormat ext_format[3] = {kSecFormatPKCS12, - kSecFormatPEMSequence, - kSecFormatX509Cert/* DER */}; - SecExternalItemType ext_type = kSecItemTypeCertificate; - SecItemImportExportKeyParameters key_params; + SecExternalFormat ext_format[3] = {kSecFormatPKCS12, + kSecFormatPEMSequence, + kSecFormatX509Cert/* DER */}; + SecExternalItemType ext_type = kSecItemTypeCertificate; + SecItemImportExportKeyParameters key_params; - pj_bzero(&key_params, sizeof(key_params)); - key_params.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; - key_params.passphrase = password; + pj_bzero(&key_params, sizeof(key_params)); + key_params.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; + key_params.passphrase = password; - for (i = 0; i < PJ_ARRAY_SIZE(ext_format); i++) { - items = NULL; - err = SecItemImport(cert_data, NULL, &ext_format[i], - &ext_type, 0, &key_params, NULL, &items); - if (err == noErr && items) { - break; - } - } + for (i = 0; i < PJ_ARRAY_SIZE(ext_format); i++) { + items = NULL; + err = SecItemImport(cert_data, NULL, &ext_format[i], + &ext_type, 0, &key_params, NULL, &items); + if (err == noErr && items) { + break; + } + } } #endif CFRelease(options); if (password) - CFRelease(password); + CFRelease(password); CFRelease(cert_data); if (err != noErr || !items) { - return pj_status_from_err(dssock, "SecItemImport", err); + return pj_status_from_err(dssock, "SecItemImport", err); } count = CFArrayGetCount(items); for (i = 0; i < count; i++) { - CFTypeRef item; - CFTypeID item_id; - - item = (CFTypeRef) CFArrayGetValueAtIndex(items, i); - item_id = CFGetTypeID(item); + CFTypeRef item; + CFTypeID item_id; + + item = (CFTypeRef) CFArrayGetValueAtIndex(items, i); + item_id = CFGetTypeID(item); - if (item_id == CFDictionaryGetTypeID()) { - identity = (SecIdentityRef) - CFDictionaryGetValue((CFDictionaryRef) item, - kSecImportItemIdentity); - break; - } + if (item_id == CFDictionaryGetTypeID()) { + identity = (SecIdentityRef) + CFDictionaryGetValue((CFDictionaryRef) item, + kSecImportItemIdentity); + break; + } #if !TARGET_OS_IPHONE - else if (item_id == SecCertificateGetTypeID()) { - err = SecIdentityCreateWithCertificate(NULL, - (SecCertificateRef) item, &identity); - if (err != noErr) { - pj_status_from_err(dssock, "SecIdentityCreate", err); - if (err == errSecItemNotFound) { - PJ_LOG(2, (THIS_FILE, "Private key must be placed in " - "the keychain")); - } - } else { - break; - } - } + else if (item_id == SecCertificateGetTypeID()) { + err = SecIdentityCreateWithCertificate(NULL, + (SecCertificateRef) item, &identity); + if (err != noErr) { + pj_status_from_err(dssock, "SecIdentityCreate", err); + if (err == errSecItemNotFound) { + PJ_LOG(2, (THIS_FILE, "Private key must be placed in " + "the keychain")); + } + } else { + break; + } + } #endif } CFRelease(items); if (!identity) { - PJ_LOG(2, (THIS_FILE, "Failed extracting identity from " - "the cert file")); - return PJ_EINVAL; + PJ_LOG(2, (THIS_FILE, "Failed extracting identity from " + "the cert file")); + return PJ_EINVAL; } cert_arr[0] = identity; cert_refs = CFArrayCreate(NULL, (const void **)cert_arr, 1, - &kCFTypeArrayCallBacks); + &kCFTypeArrayCallBacks); if (!cert_refs) - return PJ_ENOMEM; + return PJ_ENOMEM; err = SSLSetCertificate(dssock->ssl_ctx, cert_refs); CFRelease(cert_refs); CFRelease(identity); if (err != noErr) - return pj_status_from_err(dssock, "SetCertificate", err); + return pj_status_from_err(dssock, "SetCertificate", err); } return PJ_SUCCESS; @@ -388,51 +388,51 @@ static pj_status_t ssl_create(pj_ssl_sock_t *ssock) /* Create SSL context */ ssl_ctx = SSLCreateContext(NULL, (ssock->is_server? kSSLServerSide: - kSSLClientSide), kSSLStreamType); + kSSLClientSide), kSSLStreamType); if (ssl_ctx == NULL) - return PJ_ENOMEM; + return PJ_ENOMEM; dssock->ssl_ctx = ssl_ctx; /* Set certificate */ if (ssock->cert) { - status = set_cert(dssock, ssock->cert); - if (status != PJ_SUCCESS) - return status; + status = set_cert(dssock, ssock->cert); + if (status != PJ_SUCCESS) + return status; } /* Set min and max protocol version */ if (ssock->param.proto == PJ_SSL_SOCK_PROTO_DEFAULT) { /* SSL 2.0 is deprecated. */ - ssock->param.proto = PJ_SSL_SOCK_PROTO_ALL & - ~PJ_SSL_SOCK_PROTO_SSL2; + ssock->param.proto = PJ_SSL_SOCK_PROTO_ALL & + ~PJ_SSL_SOCK_PROTO_SSL2; } if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_3) { - max_proto = kTLSProtocol13; + max_proto = kTLSProtocol13; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_2) { - max_proto = kTLSProtocol12; + max_proto = kTLSProtocol12; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_1) { - max_proto = kTLSProtocol11; + max_proto = kTLSProtocol11; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1) { - max_proto = kTLSProtocol1; + max_proto = kTLSProtocol1; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_SSL3) { - max_proto = kSSLProtocol3; + max_proto = kSSLProtocol3; } else { - PJ_LOG(3, (THIS_FILE, "Unsupported TLS/SSL protocol")); - return PJ_EINVAL; + PJ_LOG(3, (THIS_FILE, "Unsupported TLS/SSL protocol")); + return PJ_EINVAL; } if (ssock->param.proto & PJ_SSL_SOCK_PROTO_SSL3) { - min_proto = kSSLProtocol3; + min_proto = kSSLProtocol3; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1) { - min_proto = kTLSProtocol1; + min_proto = kTLSProtocol1; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_1) { - min_proto = kTLSProtocol11; + min_proto = kTLSProtocol11; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_2) { - min_proto = kTLSProtocol12; + min_proto = kTLSProtocol12; } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_3) { - min_proto = kTLSProtocol13; + min_proto = kTLSProtocol13; } /* According to the doc, we can't set min/max proto for TLS protocol @@ -450,48 +450,48 @@ static pj_status_t ssl_create(pj_ssl_sock_t *ssock) /* SSL verification options */ if (!ssock->is_server && !ssock->param.verify_peer) { - err = SSLSetSessionOption(ssl_ctx, kSSLSessionOptionBreakOnServerAuth, + err = SSLSetSessionOption(ssl_ctx, kSSLSessionOptionBreakOnServerAuth, true); - if (err != noErr) - pj_status_from_err(dssock, "BreakOnServerAuth", err); + if (err != noErr) + pj_status_from_err(dssock, "BreakOnServerAuth", err); } else if (ssock->is_server && ssock->param.require_client_cert) { - err = SSLSetClientSideAuthenticate(ssl_ctx, kAlwaysAuthenticate); + err = SSLSetClientSideAuthenticate(ssl_ctx, kAlwaysAuthenticate); if (err != noErr) - pj_status_from_err(dssock, "SetClientSideAuth", err); + pj_status_from_err(dssock, "SetClientSideAuth", err); - if (!ssock->param.verify_peer) { - err = SSLSetSessionOption(ssl_ctx, - kSSLSessionOptionBreakOnClientAuth, - true); + if (!ssock->param.verify_peer) { + err = SSLSetSessionOption(ssl_ctx, + kSSLSessionOptionBreakOnClientAuth, + true); if (err != noErr) - pj_status_from_err(dssock, "BreakOnClientAuth", err); + pj_status_from_err(dssock, "BreakOnClientAuth", err); } } /* Set cipher list */ if (ssock->param.ciphers_num > 0) { - int i, n = ssock->param.ciphers_num; - SSLCipherSuite ciphers[MAX_CIPHERS]; - - if (n > PJ_ARRAY_SIZE(ciphers)) - n = PJ_ARRAY_SIZE(ciphers); - for (i = 0; i < n; i++) - ciphers[i] = (SSLCipherSuite)ssock->param.ciphers[i]; + int i, n = ssock->param.ciphers_num; + SSLCipherSuite ciphers[MAX_CIPHERS]; + + if (n > PJ_ARRAY_SIZE(ciphers)) + n = PJ_ARRAY_SIZE(ciphers); + for (i = 0; i < n; i++) + ciphers[i] = (SSLCipherSuite)ssock->param.ciphers[i]; - err = SSLSetEnabledCiphers(ssl_ctx, ciphers, n); - if (err != noErr) - return pj_status_from_err(dssock, "SetEnabledCiphers", err); + err = SSLSetEnabledCiphers(ssl_ctx, ciphers, n); + if (err != noErr) + return pj_status_from_err(dssock, "SetEnabledCiphers", err); } /* Register I/O functions */ err = SSLSetIOFuncs(ssl_ctx, SocketRead, SocketWrite); if (err != noErr) - return pj_status_from_err(dssock, "SetIOFuncs", err); + return pj_status_from_err(dssock, "SetIOFuncs", err); /* Establish a connection */ err = SSLSetConnection(ssl_ctx, ssock); if (err != noErr) - return pj_status_from_err(dssock, "SetConnection", err); + return pj_status_from_err(dssock, "SetConnection", err); return PJ_SUCCESS; } @@ -504,10 +504,10 @@ static void ssl_destroy(pj_ssl_sock_t *ssock) /* Close the connection and free SSL context */ if (dssock->ssl_ctx) { - SSLClose(dssock->ssl_ctx); + SSLClose(dssock->ssl_ctx); - CFRelease(dssock->ssl_ctx); - dssock->ssl_ctx = NULL; + CFRelease(dssock->ssl_ctx); + dssock->ssl_ctx = NULL; } /* Destroy circular buffers */ @@ -783,31 +783,31 @@ const char *sslGetCipherSuiteString(SSLCipherSuite cs) static void ssl_ciphers_populate(void) { if (!ssl_cipher_num) { - SSLContextRef ssl_ctx; - SSLCipherSuite ciphers[MAX_CIPHERS]; - size_t i, n; - OSStatus err; - - ssl_ctx = SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType); - if (ssl_ctx == NULL) return; - - err = SSLGetNumberSupportedCiphers(ssl_ctx, &n); - if (err != noErr) goto on_error; - if (n > PJ_ARRAY_SIZE(ssl_ciphers)) - n = PJ_ARRAY_SIZE(ssl_ciphers); - - err = SSLGetSupportedCiphers(ssl_ctx, ciphers, &n); - if (err != noErr) goto on_error; - - for (i = 0; i < n; i++) { - ssl_ciphers[i].id = ciphers[i]; - ssl_ciphers[i].name = sslGetCipherSuiteString(ciphers[i]); - } - - ssl_cipher_num = n; + SSLContextRef ssl_ctx; + SSLCipherSuite ciphers[MAX_CIPHERS]; + size_t i, n; + OSStatus err; + + ssl_ctx = SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType); + if (ssl_ctx == NULL) return; + + err = SSLGetNumberSupportedCiphers(ssl_ctx, &n); + if (err != noErr) goto on_error; + if (n > PJ_ARRAY_SIZE(ssl_ciphers)) + n = PJ_ARRAY_SIZE(ssl_ciphers); + + err = SSLGetSupportedCiphers(ssl_ctx, ciphers, &n); + if (err != noErr) goto on_error; + + for (i = 0; i < n; i++) { + ssl_ciphers[i].id = ciphers[i]; + ssl_ciphers[i].name = sslGetCipherSuiteString(ciphers[i]); + } + + ssl_cipher_num = n; on_error: - CFRelease(ssl_ctx); + CFRelease(ssl_ctx); } } @@ -825,11 +825,11 @@ static pj_ssl_cipher ssl_get_cipher(pj_ssl_sock_t *ssock) #if !TARGET_OS_IPHONE static void get_info_and_cn(CFArrayRef array, CFMutableStringRef info, - CFStringRef *cn) + CFStringRef *cn) { const void *keys[] = {kSecOIDOrganizationalUnitName, kSecOIDCountryName, - kSecOIDStateProvinceName, kSecOIDLocalityName, - kSecOIDOrganizationName, kSecOIDCommonName}; + kSecOIDStateProvinceName, kSecOIDLocalityName, + kSecOIDOrganizationName, kSecOIDCommonName}; const char *labels[] = { "OU=", "C=", "ST=", "L=", "O=", "CN="}; pj_bool_t add_separator = PJ_FALSE; int i, n; @@ -848,25 +848,25 @@ static void get_info_and_cn(CFArrayRef array, CFMutableStringRef info, if (!CFEqual(dictkey, keys[i])) continue; str = (CFStringRef) CFDictionaryGetValue(dict, - kSecPropertyKeyValue); - + kSecPropertyKeyValue); + if (CFStringGetLength(str) > 0) { - if (add_separator) { + if (add_separator) { CFStringAppendCString(info, "/", kCFStringEncodingUTF8); } CFStringAppendCString(info, labels[i], kCFStringEncodingUTF8); CFStringAppend(info, str); - add_separator = PJ_TRUE; - - if (CFEqual(keys[i], kSecOIDCommonName)) - *cn = str; + add_separator = PJ_TRUE; + + if (CFEqual(keys[i], kSecOIDCommonName)) + *cn = str; } } } } static CFDictionaryRef get_cert_oid(SecCertificateRef cert, CFStringRef oid, - CFTypeRef *value) + CFTypeRef *value) { void *key[1]; CFArrayRef key_arr; @@ -874,7 +874,7 @@ static CFDictionaryRef get_cert_oid(SecCertificateRef cert, CFStringRef oid, key[0] = (void *)oid; key_arr = CFArrayCreate(NULL, (const void **)key, 1, - &kCFTypeArrayCallBacks); + &kCFTypeArrayCallBacks); vals = SecCertificateCopyValues(cert, key_arr, NULL); dict = CFDictionaryGetValue(vals, key[0]); @@ -891,7 +891,7 @@ static CFDictionaryRef get_cert_oid(SecCertificateRef cert, CFStringRef oid, * this function will check if the contents need updating by inspecting the * issuer and the serial number. */ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, - SecCertificateRef cert) + SecCertificateRef cert) { pj_bool_t update_needed; char buf[512]; @@ -919,12 +919,12 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, CFArrayRef issuer_vals; dict = get_cert_oid(cert, kSecOIDX509V1IssuerName, - (CFTypeRef *)&issuer_vals); + (CFTypeRef *)&issuer_vals); if (dict) { - get_info_and_cn(issuer_vals, issuer_info, &issuer_cn); - if (issuer_cn) - issuer_cn = CFStringCreateCopy(NULL, issuer_cn); - CFRelease(dict); + get_info_and_cn(issuer_vals, issuer_info, &issuer_cn); + if (issuer_cn) + issuer_cn = CFStringCreateCopy(NULL, issuer_cn); + CFRelease(dict); } } #endif @@ -932,11 +932,11 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, /* Get serial no */ if (__builtin_available(macOS 10.13, iOS 11.0, *)) { - serial = SecCertificateCopySerialNumberData(cert, NULL); - if (serial) { - serial_no = CFDataGetBytePtr(serial); - serialsize = CFDataGetLength(serial); - } + serial = SecCertificateCopySerialNumberData(cert, NULL); + if (serial) { + serial_no = CFDataGetBytePtr(serial); + serialsize = CFDataGetLength(serial); + } } /* Check if the contents need to be updated */ @@ -957,10 +957,10 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, CFStringRef version; dict = get_cert_oid(cert, kSecOIDX509V1Version, - (CFTypeRef *)&version); + (CFTypeRef *)&version); if (dict) { - ci->version = CFStringGetIntValue(version); - CFRelease(dict); + ci->version = CFStringGetIntValue(version); + CFRelease(dict); } } #endif @@ -969,19 +969,19 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, pj_strdup2(pool, &ci->issuer.info, buf); #if !TARGET_OS_IPHONE if (issuer_cn) { - CFStringGetCString(issuer_cn, buf, bufsize, kCFStringEncodingUTF8); - pj_strdup2(pool, &ci->issuer.cn, buf); - CFRelease(issuer_cn); + CFStringGetCString(issuer_cn, buf, bufsize, kCFStringEncodingUTF8); + pj_strdup2(pool, &ci->issuer.cn, buf); + CFRelease(issuer_cn); } #endif CFRelease(issuer_info); /* Serial number */ if (serial) { - if (serialsize > sizeof(ci->serial_no)) - serialsize = sizeof(ci->serial_no); - pj_memcpy(ci->serial_no, serial_no, serialsize); - CFRelease(serial); + if (serialsize > sizeof(ci->serial_no)) + serialsize = sizeof(ci->serial_no); + pj_memcpy(ci->serial_no, serial_no, serialsize); + CFRelease(serial); } /* Subject */ @@ -995,17 +995,17 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, CFMutableStringRef subject_info; dict = get_cert_oid(cert, kSecOIDX509V1SubjectName, - (CFTypeRef *)&subject); + (CFTypeRef *)&subject); if (dict) { - subject_info = CFStringCreateMutable(NULL, 0); + subject_info = CFStringCreateMutable(NULL, 0); - get_info_and_cn(subject, subject_info, &str); + get_info_and_cn(subject, subject_info, &str); - CFStringGetCString(subject_info, buf, bufsize, kCFStringEncodingUTF8); - pj_strdup2(pool, &ci->subject.info, buf); + CFStringGetCString(subject_info, buf, bufsize, kCFStringEncodingUTF8); + pj_strdup2(pool, &ci->subject.info, buf); - CFRelease(dict); - CFRelease(subject_info); + CFRelease(dict); + CFRelease(subject_info); } } #endif @@ -1017,26 +1017,26 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, double interval; dict = get_cert_oid(cert, kSecOIDX509V1ValidityNotBefore, - (CFTypeRef *)&validity); + (CFTypeRef *)&validity); if (dict) { if (CFNumberGetValue(validity, CFNumberGetType(validity), - &interval)) + &interval)) { /* Darwin's absolute reference date is 1 Jan 2001 00:00:00 GMT */ - ci->validity.start.sec = (unsigned long)interval + 978278400L; - } - CFRelease(dict); + ci->validity.start.sec = (unsigned long)interval + 978278400L; + } + CFRelease(dict); } dict = get_cert_oid(cert, kSecOIDX509V1ValidityNotAfter, - (CFTypeRef *)&validity); + (CFTypeRef *)&validity); if (dict) { - if (CFNumberGetValue(validity, CFNumberGetType(validity), - &interval)) - { - ci->validity.end.sec = (unsigned long)interval + 978278400L; - } - CFRelease(dict); + if (CFNumberGetValue(validity, CFNumberGetType(validity), + &interval)) + { + ci->validity.end.sec = (unsigned long)interval + 978278400L; + } + CFRelease(dict); } } #endif @@ -1049,78 +1049,78 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, dict = get_cert_oid(cert, kSecOIDSubjectAltName, (CFTypeRef *)&altname); if (!dict || !CFArrayGetCount(altname)) - return; + return; ci->subj_alt_name.entry = pj_pool_calloc(pool, CFArrayGetCount(altname), - sizeof(*ci->subj_alt_name.entry)); + sizeof(*ci->subj_alt_name.entry)); for (i = 0; i < CFArrayGetCount(altname); ++i) { - CFDictionaryRef item; - CFStringRef label, value; - pj_ssl_cert_name_type type = PJ_SSL_CERT_NAME_UNKNOWN; + CFDictionaryRef item; + CFStringRef label, value; + pj_ssl_cert_name_type type = PJ_SSL_CERT_NAME_UNKNOWN; item = CFArrayGetValueAtIndex(altname, i); if (CFGetTypeID(item) != CFDictionaryGetTypeID()) continue; label = (CFStringRef)CFDictionaryGetValue(item, kSecPropertyKeyLabel); - if (CFGetTypeID(label) != CFStringGetTypeID()) - continue; + if (CFGetTypeID(label) != CFStringGetTypeID()) + continue; value = (CFStringRef)CFDictionaryGetValue(item, kSecPropertyKeyValue); - if (!CFStringCompare(label, CFSTR("DNS Name"), - kCFCompareCaseInsensitive)) - { - if (CFGetTypeID(value) != CFStringGetTypeID()) - continue; - CFStringGetCString(value, buf, bufsize, kCFStringEncodingUTF8); - type = PJ_SSL_CERT_NAME_DNS; - } else if (!CFStringCompare(label, CFSTR("IP Address"), - kCFCompareCaseInsensitive)) - { - if (CFGetTypeID(value) != CFStringGetTypeID()) - continue; - CFStringGetCString(value, buf, bufsize, kCFStringEncodingUTF8); - type = PJ_SSL_CERT_NAME_IP; - } else if (!CFStringCompare(label, CFSTR("Email Address"), - kCFCompareCaseInsensitive)) - { - if (CFGetTypeID(value) != CFStringGetTypeID()) - continue; - CFStringGetCString(value, buf, bufsize, kCFStringEncodingUTF8); - type = PJ_SSL_CERT_NAME_RFC822; - } else if (!CFStringCompare(label, CFSTR("URI"), - kCFCompareCaseInsensitive)) - { - CFStringRef uri; - - if (CFGetTypeID(value) != CFURLGetTypeID()) - continue; - uri = CFURLGetString((CFURLRef)value); - CFStringGetCString(uri, buf, bufsize, kCFStringEncodingUTF8); - type = PJ_SSL_CERT_NAME_URI; - } - - if (type != PJ_SSL_CERT_NAME_UNKNOWN) { - ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type; - if (type == PJ_SSL_CERT_NAME_IP) { - char ip_buf[PJ_INET6_ADDRSTRLEN+10]; - int len = CFStringGetLength(value); - int af = pj_AF_INET(); - - if (len == sizeof(pj_in6_addr)) af = pj_AF_INET6(); - pj_inet_ntop2(af, buf, ip_buf, sizeof(ip_buf)); - pj_strdup2(pool, - &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, - ip_buf); - } else { - pj_strdup2(pool, - &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, - buf); - } - ci->subj_alt_name.cnt++; - } + if (!CFStringCompare(label, CFSTR("DNS Name"), + kCFCompareCaseInsensitive)) + { + if (CFGetTypeID(value) != CFStringGetTypeID()) + continue; + CFStringGetCString(value, buf, bufsize, kCFStringEncodingUTF8); + type = PJ_SSL_CERT_NAME_DNS; + } else if (!CFStringCompare(label, CFSTR("IP Address"), + kCFCompareCaseInsensitive)) + { + if (CFGetTypeID(value) != CFStringGetTypeID()) + continue; + CFStringGetCString(value, buf, bufsize, kCFStringEncodingUTF8); + type = PJ_SSL_CERT_NAME_IP; + } else if (!CFStringCompare(label, CFSTR("Email Address"), + kCFCompareCaseInsensitive)) + { + if (CFGetTypeID(value) != CFStringGetTypeID()) + continue; + CFStringGetCString(value, buf, bufsize, kCFStringEncodingUTF8); + type = PJ_SSL_CERT_NAME_RFC822; + } else if (!CFStringCompare(label, CFSTR("URI"), + kCFCompareCaseInsensitive)) + { + CFStringRef uri; + + if (CFGetTypeID(value) != CFURLGetTypeID()) + continue; + uri = CFURLGetString((CFURLRef)value); + CFStringGetCString(uri, buf, bufsize, kCFStringEncodingUTF8); + type = PJ_SSL_CERT_NAME_URI; + } + + if (type != PJ_SSL_CERT_NAME_UNKNOWN) { + ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type; + if (type == PJ_SSL_CERT_NAME_IP) { + char ip_buf[PJ_INET6_ADDRSTRLEN+10]; + int len = CFStringGetLength(value); + int af = pj_AF_INET(); + + if (len == sizeof(pj_in6_addr)) af = pj_AF_INET6(); + pj_inet_ntop2(af, buf, ip_buf, sizeof(ip_buf)); + pj_strdup2(pool, + &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, + ip_buf); + } else { + pj_strdup2(pool, + &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, + buf); + } + ci->subj_alt_name.cnt++; + } } CFRelease(dict); @@ -1147,14 +1147,14 @@ static void ssl_update_certs_info(pj_ssl_sock_t *ssock) err = SSLCopyPeerTrust(dssock->ssl_ctx, &trust); if (err == noErr && trust) { - count = SecTrustGetCertificateCount(trust); - if (count > 0) { - cert = SecTrustGetCertificateAtIndex(trust, 0); - get_cert_info(ssock->pool, &ssock->remote_cert_info, cert); - } - CFRelease(trust); + count = SecTrustGetCertificateCount(trust); + if (count > 0) { + cert = SecTrustGetCertificateAtIndex(trust, 0); + get_cert_info(ssock->pool, &ssock->remote_cert_info, cert); + } + CFRelease(trust); } else if (err != noErr) { - pj_status_from_err(dssock, "CopyPeerTrust", err); + pj_status_from_err(dssock, "CopyPeerTrust", err); } } @@ -1174,11 +1174,11 @@ static void ssl_set_peer_name(pj_ssl_sock_t *ssock) { OSStatus err; - err = SSLSetPeerDomainName(dssock->ssl_ctx, - ssock->param.server_name.ptr, - ssock->param.server_name.slen); - if (err != noErr) { - pj_status_from_err(dssock, "SetPeerDomainName", err); + err = SSLSetPeerDomainName(dssock->ssl_ctx, + ssock->param.server_name.ptr, + ssock->param.server_name.slen); + if (err != noErr) { + pj_status_from_err(dssock, "SetPeerDomainName", err); } } } @@ -1190,22 +1190,22 @@ static void auto_verify_result(pj_ssl_sock_t *ssock, OSStatus ret) case errSSLPeerBadCert: case errSSLBadCertificateStatusResponse: case errSSLPeerUnsupportedCert: - ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT; - break; + ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT; + break; case errSSLCertNotYetValid: case errSSLCertExpired: case errSSLPeerCertExpired: - ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD; - break; + ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD; + break; case errSSLPeerCertRevoked: - ssock->verify_status |= PJ_SSL_CERT_EREVOKED; - break; + ssock->verify_status |= PJ_SSL_CERT_EREVOKED; + break; case errSSLHostNameMismatch: - ssock->verify_status |= PJ_SSL_CERT_EIDENTITY_NOT_MATCH; - break; + ssock->verify_status |= PJ_SSL_CERT_EIDENTITY_NOT_MATCH; + break; case errSSLPeerCertUnknown: case errSSLUnknownRootCert: @@ -1213,8 +1213,8 @@ static void auto_verify_result(pj_ssl_sock_t *ssock, OSStatus ret) case errSSLPeerUnknownCA: case errSSLXCertChainInvalid: case errSSLUnrecognizedName: - ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED; - break; + ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED; + break; } } @@ -1227,111 +1227,111 @@ static pj_status_t verify_cert(darwinssl_sock_t * dssock, pj_ssl_cert_t *cert) err = SSLCopyPeerTrust(dssock->ssl_ctx, &trust); if (err != noErr || !trust) { - return pj_status_from_err(dssock, "SSLHandshake-CopyPeerTrust", err); + return pj_status_from_err(dssock, "SSLHandshake-CopyPeerTrust", err); } if (cert && cert->CA_file.slen) { - status = create_data_from_file(&ca_data, &cert->CA_file, - (cert->CA_path.slen? &cert->CA_path: - NULL)); - if (status != PJ_SUCCESS) - PJ_LOG(2, (THIS_FILE, "Failed reading CA file")); + status = create_data_from_file(&ca_data, &cert->CA_file, + (cert->CA_path.slen? &cert->CA_path: + NULL)); + if (status != PJ_SUCCESS) + PJ_LOG(2, (THIS_FILE, "Failed reading CA file")); } else if (cert && cert->CA_buf.slen) { - ca_data = CFDataCreate(NULL, (const UInt8 *)cert->CA_buf.ptr, - cert->CA_buf.slen); - if (!ca_data) - PJ_LOG(2, (THIS_FILE, "Not enough memory for CA buffer")); + ca_data = CFDataCreate(NULL, (const UInt8 *)cert->CA_buf.ptr, + cert->CA_buf.slen); + if (!ca_data) + PJ_LOG(2, (THIS_FILE, "Not enough memory for CA buffer")); } if (ca_data) { - SecCertificateRef ca_cert; - CFMutableArrayRef ca_array; - - ca_array = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); - if (!ca_array) { - CFRelease(ca_data); - PJ_LOG(2, (THIS_FILE, "Not enough memory for CA array")); - return PJ_ENOMEM; - } - - ca_cert = SecCertificateCreateWithData(NULL, ca_data); - CFRelease(ca_data); - - if (!ca_cert) { - PJ_LOG(2, (THIS_FILE, "Failed creating certificate from " - "CA file/buffer. It has to be " - "in DER format.")); - } else { - - CFArrayAppendValue(ca_array, ca_cert); - CFRelease(ca_cert); - - err = SecTrustSetAnchorCertificates(trust, ca_array); - CFRelease(ca_array); - if (err != noErr) - pj_status_from_err(dssock, "SetAnchorCerts", err); - - err = SecTrustSetAnchorCertificatesOnly(trust, true); - if (err != noErr) - pj_status_from_err(dssock, "SetAnchorCertsOnly", err); - } + SecCertificateRef ca_cert; + CFMutableArrayRef ca_array; + + ca_array = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); + if (!ca_array) { + CFRelease(ca_data); + PJ_LOG(2, (THIS_FILE, "Not enough memory for CA array")); + return PJ_ENOMEM; + } + + ca_cert = SecCertificateCreateWithData(NULL, ca_data); + CFRelease(ca_data); + + if (!ca_cert) { + PJ_LOG(2, (THIS_FILE, "Failed creating certificate from " + "CA file/buffer. It has to be " + "in DER format.")); + } else { + + CFArrayAppendValue(ca_array, ca_cert); + CFRelease(ca_cert); + + err = SecTrustSetAnchorCertificates(trust, ca_array); + CFRelease(ca_array); + if (err != noErr) + pj_status_from_err(dssock, "SetAnchorCerts", err); + + err = SecTrustSetAnchorCertificatesOnly(trust, true); + if (err != noErr) + pj_status_from_err(dssock, "SetAnchorCertsOnly", err); + } } err = SecTrustEvaluateAsync(trust, - dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(SecTrustRef trust, SecTrustResultType trust_result) { - /* Unfortunately SecTrustEvaluate() cannot seem to get us - * more specific verification result like the original - * error status returned directly by SSLHandshake() - * (see auto_verify_result() above). - * - * If we wish to obtain more info, we can use - * SecTrustCopyProperties()/SecTrustCopyResult(). However, - * the return value will be a dictionary of strings, which - * cannot be easily checked and compared to, due to - * lack of documented possibilites as well as possible - * changes of the strings themselves. - */ - pj_ssl_sock_t *ssock = (pj_ssl_sock_t *)dssock; - - switch (trust_result) { - case kSecTrustResultInvalid: - ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT; - break; - - case kSecTrustResultDeny: - case kSecTrustResultFatalTrustFailure: - ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED; - break; - - case kSecTrustResultRecoverableTrustFailure: - /* Doc: "If you receive this result, you can retry - * after changing settings. For example, if trust is - * denied because the certificate has expired, ..." - * But this error can also mean another (recoverable) - * failure, though. - */ - ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD; - break; - - case kSecTrustResultOtherError: - ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN; - break; - - case kSecTrustResultUnspecified: - case kSecTrustResultProceed: - /* The doc says that if the trust result is proceed or - * unspecified, it means that the evaluation succeeded. - */ - break; - } - }); + /* Unfortunately SecTrustEvaluate() cannot seem to get us + * more specific verification result like the original + * error status returned directly by SSLHandshake() + * (see auto_verify_result() above). + * + * If we wish to obtain more info, we can use + * SecTrustCopyProperties()/SecTrustCopyResult(). However, + * the return value will be a dictionary of strings, which + * cannot be easily checked and compared to, due to + * lack of documented possibilites as well as possible + * changes of the strings themselves. + */ + pj_ssl_sock_t *ssock = (pj_ssl_sock_t *)dssock; + + switch (trust_result) { + case kSecTrustResultInvalid: + ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT; + break; + + case kSecTrustResultDeny: + case kSecTrustResultFatalTrustFailure: + ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED; + break; + + case kSecTrustResultRecoverableTrustFailure: + /* Doc: "If you receive this result, you can retry + * after changing settings. For example, if trust is + * denied because the certificate has expired, ..." + * But this error can also mean another (recoverable) + * failure, though. + */ + ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD; + break; + + case kSecTrustResultOtherError: + ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN; + break; + + case kSecTrustResultUnspecified: + case kSecTrustResultProceed: + /* The doc says that if the trust result is proceed or + * unspecified, it means that the evaluation succeeded. + */ + break; + } + }); CFRelease(trust); if (err != noErr) - return pj_status_from_err(dssock, "SecTrustEvaluateAsync", err); + return pj_status_from_err(dssock, "SecTrustEvaluateAsync", err); return PJ_SUCCESS; } @@ -1347,7 +1347,7 @@ static pj_status_t ssl_do_handshake(pj_ssl_sock_t *ssock) pj_lock_acquire(ssock->write_mutex); ret = SSLHandshake(dssock->ssl_ctx); if (ret == errSSLServerAuthCompleted || - ret == errSSLClientAuthCompleted) + ret == errSSLClientAuthCompleted) { /* Setting kSSLSessionOptionBreakOnServerAuth or * kSSLSessionOptionBreakOnClientAuth enables returning from @@ -1361,13 +1361,13 @@ static pj_status_t ssl_do_handshake(pj_ssl_sock_t *ssock) /* Here we just continue the handshake and let the application * verify the certificate later. */ - ret = SSLHandshake(dssock->ssl_ctx); + ret = SSLHandshake(dssock->ssl_ctx); } pj_lock_release(ssock->write_mutex); status = flush_circ_buf_output(ssock, &ssock->handshake_op_key, 0, 0); if (status != PJ_SUCCESS && status != PJ_EPENDING) { - return status; + return status; } if (ret == noErr) { @@ -1403,7 +1403,7 @@ static pj_status_t ssl_read(pj_ssl_sock_t *ssock, void *data, int *size) * and call SocketWrite. */ static pj_status_t ssl_write(pj_ssl_sock_t *ssock, const void *data, - pj_ssize_t size, int *nwritten) + pj_ssize_t size, int *nwritten) { darwinssl_sock_t *dssock = (darwinssl_sock_t *)ssock; pj_size_t processed; @@ -1414,7 +1414,7 @@ static pj_status_t ssl_write(pj_ssl_sock_t *ssock, const void *data, if (err != noErr) { return pj_status_from_err(dssock, "SSLWrite", err); } else if (processed < size) { - return PJ_ENOMEM; + return PJ_ENOMEM; } return PJ_SUCCESS; diff --git a/pjlib/src/pj/ssl_sock_dump.c b/pjlib/src/pj/ssl_sock_dump.c index 68830f72f9..afac2c59ae 100644 --- a/pjlib/src/pj/ssl_sock_dump.c +++ b/pjlib/src/pj/ssl_sock_dump.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * @@ -25,19 +24,19 @@ /* Only build when PJ_HAS_SSL_SOCK is enabled */ #if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK!=0 -#define THIS_FILE "ssl_sock_dump.c" +#define THIS_FILE "ssl_sock_dump.c" -#define CHECK_BUF_LEN() \ - if ((len < 0) || (len >= end-p)) { \ - *p = '\0'; \ - return -1; \ - } \ +#define CHECK_BUF_LEN() \ + if ((len < 0) || (len >= end-p)) { \ + *p = '\0'; \ + return -1; \ + } \ p += len; PJ_DEF(pj_ssize_t) pj_ssl_cert_info_dump(const pj_ssl_cert_info *ci, - const char *indent, - char *buf, - pj_size_t buf_size) + const char *indent, + char *buf, + pj_size_t buf_size) { const char *wdays[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; pj_parsed_time pt1; @@ -54,7 +53,7 @@ PJ_DEF(pj_ssize_t) pj_ssl_cert_info_dump(const pj_ssl_cert_info *ci, /* Version */ len = pj_ansi_snprintf(p, end-p, "%sVersion : v%d\n", - indent, ci->version); + indent, ci->version); CHECK_BUF_LEN(); /* Serial number */ @@ -63,79 +62,79 @@ PJ_DEF(pj_ssize_t) pj_ssl_cert_info_dump(const pj_ssl_cert_info *ci, for (i = 0; i < sizeof(ci->serial_no) && !ci->serial_no[i]; ++i); for (; i < sizeof(ci->serial_no); ++i) { - len = pj_ansi_snprintf(p, end-p, "%02X ", ci->serial_no[i] & 0xFF); - CHECK_BUF_LEN(); + len = pj_ansi_snprintf(p, end-p, "%02X ", ci->serial_no[i] & 0xFF); + CHECK_BUF_LEN(); } *(p-1) = '\n'; /* Subject */ len = pj_ansi_snprintf( p, end-p, "%sSubject : %.*s\n", indent, - (int)ci->subject.cn.slen, - ci->subject.cn.ptr); + (int)ci->subject.cn.slen, + ci->subject.cn.ptr); CHECK_BUF_LEN(); len = pj_ansi_snprintf( p, end-p, "%s %.*s\n", indent, - (int)ci->subject.info.slen, - ci->subject.info.ptr); + (int)ci->subject.info.slen, + ci->subject.info.ptr); CHECK_BUF_LEN(); /* Issuer */ len = pj_ansi_snprintf( p, end-p, "%sIssuer : %.*s\n", indent, - (int)ci->issuer.cn.slen, - ci->issuer.cn.ptr); + (int)ci->issuer.cn.slen, + ci->issuer.cn.ptr); CHECK_BUF_LEN(); len = pj_ansi_snprintf( p, end-p, "%s %.*s\n", indent, - (int)ci->issuer.info.slen, - ci->issuer.info.ptr); + (int)ci->issuer.info.slen, + ci->issuer.info.ptr); CHECK_BUF_LEN(); /* Validity period */ len = pj_ansi_snprintf( p, end-p, "%sValid from : %s %4d-%02d-%02d " - "%02d:%02d:%02d.%03d %s\n", indent, - wdays[pt1.wday], pt1.year, pt1.mon+1, pt1.day, - pt1.hour, pt1.min, pt1.sec, pt1.msec, - (ci->validity.gmt? "GMT":"")); + "%02d:%02d:%02d.%03d %s\n", indent, + wdays[pt1.wday], pt1.year, pt1.mon+1, pt1.day, + pt1.hour, pt1.min, pt1.sec, pt1.msec, + (ci->validity.gmt? "GMT":"")); CHECK_BUF_LEN(); len = pj_ansi_snprintf( p, end-p, "%sValid to : %s %4d-%02d-%02d " - "%02d:%02d:%02d.%03d %s\n", indent, - wdays[pt2.wday], pt2.year, pt2.mon+1, pt2.day, - pt2.hour, pt2.min, pt2.sec, pt2.msec, - (ci->validity.gmt? "GMT":"")); + "%02d:%02d:%02d.%03d %s\n", indent, + wdays[pt2.wday], pt2.year, pt2.mon+1, pt2.day, + pt2.hour, pt2.min, pt2.sec, pt2.msec, + (ci->validity.gmt? "GMT":"")); CHECK_BUF_LEN(); /* Subject alternative name extension */ if (ci->subj_alt_name.cnt) { - len = pj_ansi_snprintf(p, end-p, "%ssubjectAltName extension\n", - indent); - CHECK_BUF_LEN(); - - for (i = 0; i < ci->subj_alt_name.cnt; ++i) { - const char *type = NULL; - - switch(ci->subj_alt_name.entry[i].type) { - case PJ_SSL_CERT_NAME_RFC822: - type = "MAIL"; - break; - case PJ_SSL_CERT_NAME_DNS: - type = " DNS"; - break; - case PJ_SSL_CERT_NAME_URI: - type = " URI"; - break; - case PJ_SSL_CERT_NAME_IP: - type = " IP"; - break; - default: - break; - } - if (type) { - len = pj_ansi_snprintf( p, end-p, "%s %s : %.*s\n", indent, - type, - (int)ci->subj_alt_name.entry[i].name.slen, - ci->subj_alt_name.entry[i].name.ptr); - CHECK_BUF_LEN(); - } - } + len = pj_ansi_snprintf(p, end-p, "%ssubjectAltName extension\n", + indent); + CHECK_BUF_LEN(); + + for (i = 0; i < ci->subj_alt_name.cnt; ++i) { + const char *type = NULL; + + switch(ci->subj_alt_name.entry[i].type) { + case PJ_SSL_CERT_NAME_RFC822: + type = "MAIL"; + break; + case PJ_SSL_CERT_NAME_DNS: + type = " DNS"; + break; + case PJ_SSL_CERT_NAME_URI: + type = " URI"; + break; + case PJ_SSL_CERT_NAME_IP: + type = " IP"; + break; + default: + break; + } + if (type) { + len = pj_ansi_snprintf( p, end-p, "%s %s : %.*s\n", indent, + type, + (int)ci->subj_alt_name.entry[i].name.slen, + ci->subj_alt_name.entry[i].name.ptr); + CHECK_BUF_LEN(); + } + } } return (p-buf); diff --git a/pjlib/src/pj/ssl_sock_gtls.c b/pjlib/src/pj/ssl_sock_gtls.c index d08a23c9c9..a3d091a1d0 100644 --- a/pjlib/src/pj/ssl_sock_gtls.c +++ b/pjlib/src/pj/ssl_sock_gtls.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2018-2018 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2014-2017 Savoir-faire Linux. @@ -73,7 +72,7 @@ /* Secure socket structure definition. */ typedef struct gnutls_sock_t { - pj_ssl_sock_t base; + pj_ssl_sock_t base; gnutls_session_t session; gnutls_certificate_credentials_t xcred; @@ -329,7 +328,7 @@ static int tls_cert_verify_cb(gnutls_session_t session) goto out; } ret = gnutls_x509_crt_check_hostname(cert, - ssock->param.server_name.ptr); + ssock->param.server_name.ptr); if (ret < 0) goto out; @@ -567,8 +566,8 @@ static pj_status_t tls_trust_set(pj_ssl_sock_t *ssock) #endif static int gnutls_certificate_set_x509_trust_dir( - gnutls_certificate_credentials_t cred, - const char *dirname, unsigned type) + gnutls_certificate_credentials_t cred, + const char *dirname, unsigned type) { DIR *dirp; struct dirent *d; @@ -595,7 +594,7 @@ static int gnutls_certificate_set_x509_trust_dir( ) { #endif snprintf(path, sizeof(path), "%s/%s", - dirname, d->d_name); + dirname, d->d_name); ret = gnutls_certificate_set_x509_trust_file(cred, path, type); if (ret >= 0) @@ -690,7 +689,7 @@ static pj_status_t ssl_create(pj_ssl_sock_t *ssock) GNUTLS_X509_FMT_PEM); if (ret < 0) ret = gnutls_certificate_set_x509_trust_file( - gssock->xcred, + gssock->xcred, cert->CA_file.ptr, GNUTLS_X509_FMT_DER); if (ret < 0) @@ -702,7 +701,7 @@ static pj_status_t ssl_create(pj_ssl_sock_t *ssock) GNUTLS_X509_FMT_PEM); if (ret < 0) ret = gnutls_certificate_set_x509_trust_dir( - gssock->xcred, + gssock->xcred, cert->CA_path.ptr, GNUTLS_X509_FMT_DER); if (ret < 0) @@ -741,7 +740,7 @@ static pj_status_t ssl_create(pj_ssl_sock_t *ssock) GNUTLS_X509_FMT_PEM); if (ret < 0) ret = gnutls_certificate_set_x509_trust_mem( - gssock->xcred, &ca, GNUTLS_X509_FMT_DER); + gssock->xcred, &ca, GNUTLS_X509_FMT_DER); if (ret < 0) goto out; } @@ -898,7 +897,7 @@ static void tls_cert_get_cn(const pj_str_t *gen_name, pj_str_t *cn) * this function will check if the contents need updating by inspecting the * issuer and the serial number. */ static void tls_cert_get_info(pj_pool_t *pool, pj_ssl_cert_info *ci, - gnutls_x509_crt_t cert) + gnutls_x509_crt_t cert) { pj_bool_t update_needed; char buf[512] = { 0 }; @@ -961,7 +960,7 @@ static void tls_cert_get_info(pj_pool_t *pool, pj_ssl_cert_info *ci, } ci->subj_alt_name.entry = pj_pool_calloc(pool, seq, - sizeof(*ci->subj_alt_name.entry)); + sizeof(*ci->subj_alt_name.entry)); if (!ci->subj_alt_name.entry) { tls_last_error = GNUTLS_E_MEMORY_ERROR; return; @@ -971,7 +970,7 @@ static void tls_cert_get_info(pj_pool_t *pool, pj_ssl_cert_info *ci, for (i = 0; i < seq; i++) { len = sizeof(out) - 1; ret = gnutls_x509_crt_get_subject_alt_name(cert, i, out, - &len, NULL); + &len, NULL); switch (ret) { case GNUTLS_SAN_IPADDRESS: @@ -997,7 +996,7 @@ static void tls_cert_get_info(pj_pool_t *pool, pj_ssl_cert_info *ci, if (len && type != PJ_SSL_CERT_NAME_UNKNOWN) { ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type; pj_strdup2(pool, - &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, + &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, type == PJ_SSL_CERT_NAME_IP ? buf : out); ci->subj_alt_name.cnt++; } @@ -1008,16 +1007,16 @@ static void tls_cert_get_info(pj_pool_t *pool, pj_ssl_cert_info *ci, } static void tls_cert_get_chain_raw(pj_pool_t *pool, pj_ssl_cert_info *ci, - const gnutls_datum_t *certs, - size_t certs_num) + const gnutls_datum_t *certs, + size_t certs_num) { size_t i=0; ci->raw_chain.cert_raw = pj_pool_calloc(pool, certs_num, - sizeof(*ci->raw_chain.cert_raw)); + sizeof(*ci->raw_chain.cert_raw)); ci->raw_chain.cnt = certs_num; for (i=0; i < certs_num; ++i) { const pj_str_t crt_raw = {(char*)certs[i].data, - (pj_ssize_t)certs[i].size}; + (pj_ssize_t)certs[i].size}; pj_strdup(pool, ci->raw_chain.cert_raw+i, &crt_raw); } } @@ -1080,7 +1079,7 @@ static void ssl_update_certs_info(pj_ssl_sock_t *ssock) tls_cert_get_info(ssock->pool, &ssock->remote_cert_info, cert); pj_pool_reset(ssock->info_pool); tls_cert_get_chain_raw(ssock->info_pool, &ssock->remote_cert_info, certs, - certslen); + certslen); peer_out: tls_last_error = ret; @@ -1164,12 +1163,12 @@ static pj_status_t ssl_read(pj_ssl_sock_t *ssock, void *data, int *size) /* Nothing more to read */ return PJ_SUCCESS; } else if (decrypted_size == GNUTLS_E_REHANDSHAKE) { - return PJ_EEOF; + return PJ_EEOF; } else if (decrypted_size == GNUTLS_E_AGAIN || decrypted_size == GNUTLS_E_INTERRUPTED || !gnutls_error_is_fatal(decrypted_size)) { - /* non-fatal error, let's just continue */ + /* non-fatal error, let's just continue */ return PJ_SUCCESS; } else { return PJ_ECANCELLED; @@ -1182,7 +1181,7 @@ static pj_status_t ssl_read(pj_ssl_sock_t *ssock, void *data, int *size) * sending data should be delayed until re-negotiation is completed. */ static pj_status_t ssl_write(pj_ssl_sock_t *ssock, const void *data, - pj_ssize_t size, int *nwritten) + pj_ssize_t size, int *nwritten) { gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; int nwritten_; @@ -1196,7 +1195,7 @@ static pj_status_t ssl_write(pj_ssl_sock_t *ssock, const void *data, while (total_written < size) { /* Try encrypting using GnuTLS */ nwritten_ = gnutls_record_send(gssock->session, - ((read_data_t *)data) + total_written, + ((read_data_t *)data) + total_written, size - total_written); if (nwritten_ > 0) { diff --git a/pjlib/src/pj/ssl_sock_imp_common.c b/pjlib/src/pj/ssl_sock_imp_common.c index ae2f1136ee..0325ed5cf1 100644 --- a/pjlib/src/pj/ssl_sock_imp_common.c +++ b/pjlib/src/pj/ssl_sock_imp_common.c @@ -27,21 +27,21 @@ /* Workaround for ticket #985 and #1930 */ #ifndef PJ_SSL_SOCK_DELAYED_CLOSE_TIMEOUT -# define PJ_SSL_SOCK_DELAYED_CLOSE_TIMEOUT 500 +# define PJ_SSL_SOCK_DELAYED_CLOSE_TIMEOUT 500 #endif enum { MAX_BIND_RETRY = 100 }; #ifndef SSL_SOCK_IMP_USE_OWN_NETWORK static pj_bool_t asock_on_data_read (pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder); + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder); static pj_bool_t asock_on_data_sent (pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent); + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent); #endif #ifdef SSL_SOCK_IMP_USE_CIRC_BUF @@ -194,11 +194,11 @@ static int get_ip_addr_ver(const pj_str_t *host) /* First check if this is an IPv4 address */ if (pj_inet_pton(pj_AF_INET(), host, &dummy) == PJ_SUCCESS) - return 4; + return 4; /* Then check if this is an IPv6 address */ if (pj_inet_pton(pj_AF_INET6(), host, &dummy6) == PJ_SUCCESS) - return 6; + return 6; /* Not an IP address */ return 0; @@ -212,7 +212,7 @@ static void ssl_close_sockets(pj_ssl_sock_t *ssock) /* This can happen when pj_ssl_sock_create() fails. */ if (!ssock->write_mutex) - return; + return; pj_lock_acquire(ssock->write_mutex); asock = ssock->asock; @@ -242,130 +242,130 @@ static void ssl_close_sockets(pj_ssl_sock_t *ssock) * - return PJ_FALSE when SSL socket instance is destroyed by application. */ static pj_bool_t on_handshake_complete(pj_ssl_sock_t *ssock, - pj_status_t status) + pj_status_t status) { /* Cancel handshake timer */ if (ssock->timer.id == TIMER_HANDSHAKE_TIMEOUT) { - pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer); - ssock->timer.id = TIMER_NONE; + pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer); + ssock->timer.id = TIMER_NONE; } /* Update certificates info on successful handshake */ if (status == PJ_SUCCESS) - ssl_update_certs_info(ssock); + ssl_update_certs_info(ssock); /* Accepting */ if (ssock->is_server) { - pj_bool_t ret = PJ_TRUE; + pj_bool_t ret = PJ_TRUE; - if (status != PJ_SUCCESS) { - /* Handshake failed in accepting, destroy our self silently. */ + if (status != PJ_SUCCESS) { + /* Handshake failed in accepting, destroy our self silently. */ - char buf[PJ_INET6_ADDRSTRLEN+10]; + char buf[PJ_INET6_ADDRSTRLEN+10]; if (pj_sockaddr_has_addr(&ssock->rem_addr)) { PJ_PERROR(3,(ssock->pool->obj_name, status, - "Handshake failed in accepting %s", - pj_sockaddr_print(&ssock->rem_addr, buf, - sizeof(buf), 3))); + "Handshake failed in accepting %s", + pj_sockaddr_print(&ssock->rem_addr, buf, + sizeof(buf), 3))); } - if (ssock->param.cb.on_accept_complete2) { - (*ssock->param.cb.on_accept_complete2) - (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr, - pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr), - status); - } - - /* Decrement ref count of parent */ - if (ssock->parent->param.grp_lock) { - pj_grp_lock_dec_ref(ssock->parent->param.grp_lock); - ssock->parent = NULL; - } - - /* Originally, this is a workaround for ticket #985. However, - * a race condition may occur in multiple worker threads - * environment when we are destroying SSL objects while other - * threads are still accessing them. - * Please see ticket #1930 for more info. - */ + if (ssock->param.cb.on_accept_complete2) { + (*ssock->param.cb.on_accept_complete2) + (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr, + pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr), + status); + } + + /* Decrement ref count of parent */ + if (ssock->parent->param.grp_lock) { + pj_grp_lock_dec_ref(ssock->parent->param.grp_lock); + ssock->parent = NULL; + } + + /* Originally, this is a workaround for ticket #985. However, + * a race condition may occur in multiple worker threads + * environment when we are destroying SSL objects while other + * threads are still accessing them. + * Please see ticket #1930 for more info. + */ #if 1 //(defined(PJ_WIN32) && PJ_WIN32!=0)||(defined(PJ_WIN64) && PJ_WIN64!=0) - if (ssock->param.timer_heap) { - pj_time_val interval = {0, PJ_SSL_SOCK_DELAYED_CLOSE_TIMEOUT}; - pj_status_t status1; - - ssock->ssl_state = SSL_STATE_NULL; - ssl_close_sockets(ssock); - - if (ssock->timer.id != TIMER_NONE) { - pj_timer_heap_cancel(ssock->param.timer_heap, - &ssock->timer); - } - pj_time_val_normalize(&interval); - status1 = pj_timer_heap_schedule_w_grp_lock( - ssock->param.timer_heap, - &ssock->timer, - &interval, - TIMER_CLOSE, - ssock->param.grp_lock); - if (status1 != PJ_SUCCESS) { - PJ_PERROR(3,(ssock->pool->obj_name, status, - "Failed to schedule a delayed close. " - "Race condition may occur.")); - ssock->timer.id = TIMER_NONE; - pj_ssl_sock_close(ssock); - } - } else { - pj_ssl_sock_close(ssock); - } + if (ssock->param.timer_heap) { + pj_time_val interval = {0, PJ_SSL_SOCK_DELAYED_CLOSE_TIMEOUT}; + pj_status_t status1; + + ssock->ssl_state = SSL_STATE_NULL; + ssl_close_sockets(ssock); + + if (ssock->timer.id != TIMER_NONE) { + pj_timer_heap_cancel(ssock->param.timer_heap, + &ssock->timer); + } + pj_time_val_normalize(&interval); + status1 = pj_timer_heap_schedule_w_grp_lock( + ssock->param.timer_heap, + &ssock->timer, + &interval, + TIMER_CLOSE, + ssock->param.grp_lock); + if (status1 != PJ_SUCCESS) { + PJ_PERROR(3,(ssock->pool->obj_name, status, + "Failed to schedule a delayed close. " + "Race condition may occur.")); + ssock->timer.id = TIMER_NONE; + pj_ssl_sock_close(ssock); + } + } else { + pj_ssl_sock_close(ssock); + } #else - { - pj_ssl_sock_close(ssock); - } + { + pj_ssl_sock_close(ssock); + } #endif - return PJ_FALSE; - } - - /* Notify application the newly accepted SSL socket */ - if (ssock->param.cb.on_accept_complete2) { - ret = (*ssock->param.cb.on_accept_complete2) - (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr, - pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr), - status); - } else if (ssock->param.cb.on_accept_complete) { - ret = (*ssock->param.cb.on_accept_complete) - (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr, - pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr)); - } - - /* Decrement ref count of parent and reset parent (we don't need it - * anymore, right?). - */ - if (ssock->parent->param.grp_lock) { - pj_grp_lock_dec_ref(ssock->parent->param.grp_lock); - ssock->parent = NULL; - } - - if (ret == PJ_FALSE) - return PJ_FALSE; + return PJ_FALSE; + } + + /* Notify application the newly accepted SSL socket */ + if (ssock->param.cb.on_accept_complete2) { + ret = (*ssock->param.cb.on_accept_complete2) + (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr, + pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr), + status); + } else if (ssock->param.cb.on_accept_complete) { + ret = (*ssock->param.cb.on_accept_complete) + (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr, + pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr)); + } + + /* Decrement ref count of parent and reset parent (we don't need it + * anymore, right?). + */ + if (ssock->parent->param.grp_lock) { + pj_grp_lock_dec_ref(ssock->parent->param.grp_lock); + ssock->parent = NULL; + } + + if (ret == PJ_FALSE) + return PJ_FALSE; } /* Connecting */ else { - /* On failure, reset SSL socket state first, as app may try to - * reconnect in the callback. - */ - if (status != PJ_SUCCESS) { - /* Server disconnected us, possibly due to SSL nego failure */ - ssl_reset_sock_state(ssock); - } - if (ssock->param.cb.on_connect_complete) { - pj_bool_t ret; - ret = (*ssock->param.cb.on_connect_complete)(ssock, status); - if (ret == PJ_FALSE) - return PJ_FALSE; - } + /* On failure, reset SSL socket state first, as app may try to + * reconnect in the callback. + */ + if (status != PJ_SUCCESS) { + /* Server disconnected us, possibly due to SSL nego failure */ + ssl_reset_sock_state(ssock); + } + if (ssock->param.cb.on_connect_complete) { + pj_bool_t ret; + ret = (*ssock->param.cb.on_connect_complete)(ssock, status); + if (ret == PJ_FALSE) + return PJ_FALSE; + } } return PJ_TRUE; @@ -382,14 +382,14 @@ static write_data_t* alloc_send_data(pj_ssl_sock_t *ssock, pj_size_t len) /* Check buffer availability */ avail_len = send_buf->max_len - send_buf->len; if (avail_len < len) - return NULL; + return NULL; /* If buffer empty, reset start pointer and return it */ if (send_buf->len == 0) { - send_buf->start = send_buf->buf; - send_buf->len = len; - p = (write_data_t*)send_buf->start; - goto init_send_data; + send_buf->start = send_buf->buf; + send_buf->len = len; + p = (write_data_t*)send_buf->start; + goto init_send_data; } /* Free space may be wrapped/splitted into two regions, so let's @@ -397,15 +397,15 @@ static write_data_t* alloc_send_data(pj_ssl_sock_t *ssock, pj_size_t len) */ reg1 = send_buf->start + send_buf->len; if (reg1 >= send_buf->buf + send_buf->max_len) - reg1 -= send_buf->max_len; + reg1 -= send_buf->max_len; reg1_len = send_buf->max_len - send_buf->len; if (reg1 + reg1_len > send_buf->buf + send_buf->max_len) { - reg1_len = send_buf->buf + send_buf->max_len - reg1; - reg2 = send_buf->buf; - reg2_len = send_buf->start - send_buf->buf; + reg1_len = send_buf->buf + send_buf->max_len - reg1; + reg2 = send_buf->buf; + reg2_len = send_buf->start - send_buf->buf; } else { - reg2 = NULL; - reg2_len = 0; + reg2 = NULL; + reg2_len = 0; } /* More buffer availability check, note that the write data must be in @@ -413,14 +413,14 @@ static write_data_t* alloc_send_data(pj_ssl_sock_t *ssock, pj_size_t len) */ avail_len = PJ_MAX(reg1_len, reg2_len); if (avail_len < len) - return NULL; + return NULL; /* Get the data slot */ if (reg1_len >= len) { - p = (write_data_t*)reg1; + p = (write_data_t*)reg1; } else { - p = (write_data_t*)reg2; - skipped_len = reg1_len; + p = (write_data_t*)reg2; + skipped_len = reg1_len; } /* Update buffer length */ @@ -444,38 +444,38 @@ static void free_send_data(pj_ssl_sock_t *ssock, write_data_t *wdata) /* Free slot from the buffer */ if (spl->next == wdata && spl->prev == wdata) { - /* This is the only data, reset the buffer */ - buf->start = buf->buf; - buf->len = 0; + /* This is the only data, reset the buffer */ + buf->start = buf->buf; + buf->len = 0; } else if (spl->next == wdata) { - /* This is the first data, shift start pointer of the buffer and - * adjust the buffer length. - */ - buf->start = (char*)wdata->next; - if (wdata->next > wdata) { - buf->len -= ((char*)wdata->next - buf->start); - } else { - /* Overlapped */ - pj_size_t right_len, left_len; - right_len = buf->buf + buf->max_len - (char*)wdata; - left_len = (char*)wdata->next - buf->buf; - buf->len -= (right_len + left_len); - } + /* This is the first data, shift start pointer of the buffer and + * adjust the buffer length. + */ + buf->start = (char*)wdata->next; + if (wdata->next > wdata) { + buf->len -= ((char*)wdata->next - buf->start); + } else { + /* Overlapped */ + pj_size_t right_len, left_len; + right_len = buf->buf + buf->max_len - (char*)wdata; + left_len = (char*)wdata->next - buf->buf; + buf->len -= (right_len + left_len); + } } else if (spl->prev == wdata) { - /* This is the last data, just adjust the buffer length */ - if (wdata->prev < wdata) { - pj_size_t jump_len; - jump_len = (char*)wdata - - ((char*)wdata->prev + wdata->prev->record_len); - buf->len -= (wdata->record_len + jump_len); - } else { - /* Overlapped */ - pj_size_t right_len, left_len; - right_len = buf->buf + buf->max_len - - ((char*)wdata->prev + wdata->prev->record_len); - left_len = (char*)wdata + wdata->record_len - buf->buf; - buf->len -= (right_len + left_len); - } + /* This is the last data, just adjust the buffer length */ + if (wdata->prev < wdata) { + pj_size_t jump_len; + jump_len = (char*)wdata - + ((char*)wdata->prev + wdata->prev->record_len); + buf->len -= (wdata->record_len + jump_len); + } else { + /* Overlapped */ + pj_size_t right_len, left_len; + right_len = buf->buf + buf->max_len - + ((char*)wdata->prev + wdata->prev->record_len); + left_len = (char*)wdata + wdata->record_len - buf->buf; + buf->len -= (right_len + left_len); + } } /* For data in the middle buffer, just do nothing on the buffer. The slot * will be freed later when freeing the first/last data. @@ -499,15 +499,15 @@ static pj_status_t flush_circ_buf_output(pj_ssl_sock_t *ssock, /* Check if there is data in the circular buffer, flush it if any */ if (io_empty(ssock, &ssock->circ_buf_output)) { - pj_lock_release(ssock->write_mutex); - return PJ_SUCCESS; + pj_lock_release(ssock->write_mutex); + return PJ_SUCCESS; } /* Get data and its length */ len = io_size(ssock, &ssock->circ_buf_output); if (len == 0) { - pj_lock_release(ssock->write_mutex); - return PJ_SUCCESS; + pj_lock_release(ssock->write_mutex); + return PJ_SUCCESS; } /* Calculate buffer size needed, and align it to 8 */ @@ -517,15 +517,15 @@ static pj_status_t flush_circ_buf_output(pj_ssl_sock_t *ssock, /* Allocate buffer for send data */ wdata = alloc_send_data(ssock, needed_len); if (wdata == NULL) { - /* Oops, the send buffer is full, let's just - * queue it for sending and return PJ_EPENDING. - */ - ssock->send_buf_pending.data_len = needed_len; - ssock->send_buf_pending.app_key = send_key; - ssock->send_buf_pending.flags = flags; - ssock->send_buf_pending.plain_data_len = orig_len; - pj_lock_release(ssock->write_mutex); - return PJ_EPENDING; + /* Oops, the send buffer is full, let's just + * queue it for sending and return PJ_EPENDING. + */ + ssock->send_buf_pending.data_len = needed_len; + ssock->send_buf_pending.app_key = send_key; + ssock->send_buf_pending.flags = flags; + ssock->send_buf_pending.plain_data_len = orig_len; + pj_lock_release(ssock->write_mutex); + return PJ_EPENDING; } /* Copy the data and set its properties into the send data */ @@ -544,28 +544,28 @@ static pj_status_t flush_circ_buf_output(pj_ssl_sock_t *ssock, /* Send it */ #ifdef SSL_SOCK_IMP_USE_OWN_NETWORK status = network_send(ssock, &wdata->key, wdata->data.content, &len, - flags); + flags); #else if (ssock->param.sock_type == pj_SOCK_STREAM()) { - status = pj_activesock_send(ssock->asock, &wdata->key, - wdata->data.content, &len, - flags); + status = pj_activesock_send(ssock->asock, &wdata->key, + wdata->data.content, &len, + flags); } else { - status = pj_activesock_sendto(ssock->asock, &wdata->key, - wdata->data.content, &len, - flags, - (pj_sockaddr_t*)&ssock->rem_addr, - ssock->addr_len); + status = pj_activesock_sendto(ssock->asock, &wdata->key, + wdata->data.content, &len, + flags, + (pj_sockaddr_t*)&ssock->rem_addr, + ssock->addr_len); } #endif if (status != PJ_EPENDING) { - /* When the sending is not pending, remove the wdata from send - * pending list. - */ - pj_lock_acquire(ssock->write_mutex); - free_send_data(ssock, wdata); - pj_lock_release(ssock->write_mutex); + /* When the sending is not pending, remove the wdata from send + * pending list. + */ + pj_lock_acquire(ssock->write_mutex); + free_send_data(ssock, wdata); + pj_lock_release(ssock->write_mutex); } return status; @@ -590,39 +590,39 @@ pj_status_t pj_ssl_sock_ossl_test_send_buf(pj_pool_t *pool) pj_ssl_sock_param_default(¶m); status = pj_ssl_sock_create(pool, ¶m, &ssock); if (status != PJ_SUCCESS) { - return status; + return status; } if (ssock->send_buf.max_len == 0) { - ssock->send_buf.buf = (char*) - pj_pool_alloc(ssock->pool, - ssock->param.send_buffer_size); - ssock->send_buf.max_len = ssock->param.send_buffer_size; - ssock->send_buf.start = ssock->send_buf.buf; - ssock->send_buf.len = 0; + ssock->send_buf.buf = (char*) + pj_pool_alloc(ssock->pool, + ssock->param.send_buffer_size); + ssock->send_buf.max_len = ssock->param.send_buffer_size; + ssock->send_buf.start = ssock->send_buf.buf; + ssock->send_buf.len = 0; } chunk_size = ssock->param.send_buffer_size / MAX_CHUNK_NUM / 2; chunk_cnt = 0; for (i = 0; i < MAX_CHUNK_NUM; i++) { - wdata[i] = alloc_send_data(ssock, pj_rand() % chunk_size + 321); - if (wdata[i]) - chunk_cnt++; - else - break; + wdata[i] = alloc_send_data(ssock, pj_rand() % chunk_size + 321); + if (wdata[i]) + chunk_cnt++; + else + break; } while (chunk_cnt) { - i = pj_rand() % MAX_CHUNK_NUM; - if (wdata[i]) { - free_send_data(ssock, wdata[i]); - wdata[i] = NULL; - chunk_cnt--; - } + i = pj_rand() % MAX_CHUNK_NUM; + if (wdata[i]) { + free_send_data(ssock, wdata[i]); + wdata[i] = NULL; + chunk_cnt--; + } } if (ssock->send_buf.len != 0) - status = PJ_EBUG; + status = PJ_EBUG; pj_ssl_sock_close(ssock); return status; @@ -640,17 +640,17 @@ static void on_timer(pj_timer_heap_t *th, struct pj_timer_entry *te) switch (timer_id) { case TIMER_HANDSHAKE_TIMEOUT: - PJ_LOG(1,(ssock->pool->obj_name, "SSL timeout after %d.%ds", - ssock->param.timeout.sec, ssock->param.timeout.msec)); + PJ_LOG(1,(ssock->pool->obj_name, "SSL timeout after %d.%ds", + ssock->param.timeout.sec, ssock->param.timeout.msec)); - on_handshake_complete(ssock, PJ_ETIMEDOUT); - break; + on_handshake_complete(ssock, PJ_ETIMEDOUT); + break; case TIMER_CLOSE: - pj_ssl_sock_close(ssock); - break; + pj_ssl_sock_close(ssock); + break; default: - pj_assert(!"Unknown timer"); - break; + pj_assert(!"Unknown timer"); + break; } } @@ -662,13 +662,13 @@ static void ssl_on_destroy(void *arg) if (ssock->circ_buf_input_mutex) { pj_lock_destroy(ssock->circ_buf_input_mutex); - ssock->circ_buf_input_mutex = NULL; + ssock->circ_buf_input_mutex = NULL; } if (ssock->circ_buf_output_mutex) { pj_lock_destroy(ssock->circ_buf_output_mutex); - ssock->circ_buf_output_mutex = NULL; - ssock->write_mutex = NULL; + ssock->circ_buf_output_mutex = NULL; + ssock->write_mutex = NULL; } /* Secure release pool, i.e: all memory blocks will be zeroed first */ @@ -693,148 +693,148 @@ static void ssl_on_destroy(void *arg) * read-buffer. */ #define OFFSET_OF_READ_DATA_PTR(ssock, asock_rbuf) \ - (read_data_t**) \ - ((pj_int8_t*)(asock_rbuf) + \ - ssock->param.read_buffer_size) + (read_data_t**) \ + ((pj_int8_t*)(asock_rbuf) + \ + ssock->param.read_buffer_size) static pj_bool_t ssock_on_data_read (pj_ssl_sock_t *ssock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { if (status != PJ_SUCCESS) - goto on_error; + goto on_error; if (data && size > 0) { - pj_status_t status_; + pj_status_t status_; - /* Consume the whole data */ + /* Consume the whole data */ if (ssock->circ_buf_input_mutex) - pj_lock_acquire(ssock->circ_buf_input_mutex); + pj_lock_acquire(ssock->circ_buf_input_mutex); status_ = io_write(ssock,&ssock->circ_buf_input, data, size); if (ssock->circ_buf_input_mutex) pj_lock_release(ssock->circ_buf_input_mutex); if (status_ != PJ_SUCCESS) { status = status_; - goto on_error; - } + goto on_error; + } } /* Check if SSL handshake hasn't finished yet */ if (ssock->ssl_state == SSL_STATE_HANDSHAKING) { - pj_bool_t ret = PJ_TRUE; + pj_bool_t ret = PJ_TRUE; - if (status == PJ_SUCCESS) - status = ssl_do_handshake(ssock); + if (status == PJ_SUCCESS) + status = ssl_do_handshake(ssock); - /* Not pending is either success or failed */ - if (status != PJ_EPENDING) - ret = on_handshake_complete(ssock, status); + /* Not pending is either success or failed */ + if (status != PJ_EPENDING) + ret = on_handshake_complete(ssock, status); - return ret; + return ret; } /* See if there is any decrypted data for the application */ if (ssock->read_started) { - do { - read_data_t *buf = *(OFFSET_OF_READ_DATA_PTR(ssock, data)); - void *data_ = (pj_int8_t*)buf->data + buf->len; - int size_ = (int)(ssock->read_size - buf->len); - pj_status_t status_; - - status_ = ssl_read(ssock, data_, &size_); - - if (size_ > 0 || status != PJ_SUCCESS) { - if (ssock->param.cb.on_data_read) { - pj_bool_t ret; - pj_size_t remainder_ = 0; - - if (size_ > 0) - buf->len += size_; - + do { + read_data_t *buf = *(OFFSET_OF_READ_DATA_PTR(ssock, data)); + void *data_ = (pj_int8_t*)buf->data + buf->len; + int size_ = (int)(ssock->read_size - buf->len); + pj_status_t status_; + + status_ = ssl_read(ssock, data_, &size_); + + if (size_ > 0 || status != PJ_SUCCESS) { + if (ssock->param.cb.on_data_read) { + pj_bool_t ret; + pj_size_t remainder_ = 0; + + if (size_ > 0) + buf->len += size_; + if (status != PJ_SUCCESS) { ssock->ssl_state = SSL_STATE_ERROR; } - ret = (*ssock->param.cb.on_data_read)(ssock, buf->data, - buf->len, status, - &remainder_); - if (!ret) { - /* We've been destroyed */ - return PJ_FALSE; - } - - /* Application may have left some data to be consumed - * later. - */ - buf->len = remainder_; - } - - /* Active socket signalled connection closed/error, this has - * been signalled to the application along with any remaining - * buffer. So, let's just reset SSL socket now. - */ - if (status != PJ_SUCCESS) { - ssl_reset_sock_state(ssock); - return PJ_FALSE; - } - - } else if (status_ == PJ_SUCCESS) { - break; - } else if (status_ == PJ_EEOF) { - status = ssl_do_handshake(ssock); - if (status == PJ_SUCCESS) { - /* Renegotiation completed */ - - /* Update certificates */ - ssl_update_certs_info(ssock); - - // Ticket #1573: Don't hold mutex while calling - // PJLIB socket send(). - //pj_lock_acquire(ssock->write_mutex); - status = flush_delayed_send(ssock); - //pj_lock_release(ssock->write_mutex); - - /* If flushing is ongoing, treat it as success */ - if (status == PJ_EBUSY) - status = PJ_SUCCESS; - - if (status != PJ_SUCCESS && status != PJ_EPENDING) { - PJ_PERROR(1,(ssock->pool->obj_name, status, - "Failed to flush delayed send")); - goto on_error; - } - } else if (status != PJ_EPENDING) { - PJ_PERROR(1,(ssock->pool->obj_name, status, - "Renegotiation failed")); - goto on_error; - } - - break; - } else { - /* Error */ - status = status_; - goto on_error; - } - - } while (1); + ret = (*ssock->param.cb.on_data_read)(ssock, buf->data, + buf->len, status, + &remainder_); + if (!ret) { + /* We've been destroyed */ + return PJ_FALSE; + } + + /* Application may have left some data to be consumed + * later. + */ + buf->len = remainder_; + } + + /* Active socket signalled connection closed/error, this has + * been signalled to the application along with any remaining + * buffer. So, let's just reset SSL socket now. + */ + if (status != PJ_SUCCESS) { + ssl_reset_sock_state(ssock); + return PJ_FALSE; + } + + } else if (status_ == PJ_SUCCESS) { + break; + } else if (status_ == PJ_EEOF) { + status = ssl_do_handshake(ssock); + if (status == PJ_SUCCESS) { + /* Renegotiation completed */ + + /* Update certificates */ + ssl_update_certs_info(ssock); + + // Ticket #1573: Don't hold mutex while calling + // PJLIB socket send(). + //pj_lock_acquire(ssock->write_mutex); + status = flush_delayed_send(ssock); + //pj_lock_release(ssock->write_mutex); + + /* If flushing is ongoing, treat it as success */ + if (status == PJ_EBUSY) + status = PJ_SUCCESS; + + if (status != PJ_SUCCESS && status != PJ_EPENDING) { + PJ_PERROR(1,(ssock->pool->obj_name, status, + "Failed to flush delayed send")); + goto on_error; + } + } else if (status != PJ_EPENDING) { + PJ_PERROR(1,(ssock->pool->obj_name, status, + "Renegotiation failed")); + goto on_error; + } + + break; + } else { + /* Error */ + status = status_; + goto on_error; + } + + } while (1); } return PJ_TRUE; on_error: if (ssock->ssl_state == SSL_STATE_HANDSHAKING) - return on_handshake_complete(ssock, status); + return on_handshake_complete(ssock, status); if (ssock->read_started && ssock->param.cb.on_data_read) { - pj_bool_t ret; - ret = (*ssock->param.cb.on_data_read)(ssock, NULL, 0, status, - remainder); - if (!ret) { - /* We've been destroyed */ - return PJ_FALSE; - } + pj_bool_t ret; + ret = (*ssock->param.cb.on_data_read)(ssock, NULL, 0, status, + remainder); + if (!ret) { + /* We've been destroyed */ + return PJ_FALSE; + } } ssl_reset_sock_state(ssock); @@ -842,8 +842,8 @@ static pj_bool_t ssock_on_data_read (pj_ssl_sock_t *ssock, } static pj_bool_t ssock_on_data_sent (pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent) + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent) { write_data_t *wdata = (write_data_t*)send_key->user_data; pj_ioqueue_op_key_t *app_key = wdata->app_key; @@ -858,66 +858,66 @@ static pj_bool_t ssock_on_data_sent (pj_ssl_sock_t *ssock, wdata = NULL; if (ssock->ssl_state == SSL_STATE_HANDSHAKING) { - /* Initial handshaking */ - pj_status_t status; - - status = ssl_do_handshake(ssock); - /* Not pending is either success or failed */ - if (status != PJ_EPENDING) - return on_handshake_complete(ssock, status); + /* Initial handshaking */ + pj_status_t status; + + status = ssl_do_handshake(ssock); + /* Not pending is either success or failed */ + if (status != PJ_EPENDING) + return on_handshake_complete(ssock, status); } else if (send_key != &ssock->handshake_op_key) { - /* Some data has been sent, notify application */ - if (ssock->param.cb.on_data_sent) { - pj_bool_t ret; - ret = (*ssock->param.cb.on_data_sent)(ssock, app_key, - sent_len); - if (!ret) { - /* We've been destroyed */ - return PJ_FALSE; - } - } + /* Some data has been sent, notify application */ + if (ssock->param.cb.on_data_sent) { + pj_bool_t ret; + ret = (*ssock->param.cb.on_data_sent)(ssock, app_key, + sent_len); + if (!ret) { + /* We've been destroyed */ + return PJ_FALSE; + } + } } else { - /* SSL re-negotiation is on-progress, just do nothing */ + /* SSL re-negotiation is on-progress, just do nothing */ } /* Send buffer has been updated, let's try to send any pending data */ if (ssock->send_buf_pending.data_len) { - pj_status_t status; - status = flush_circ_buf_output(ssock, ssock->send_buf_pending.app_key, - ssock->send_buf_pending.plain_data_len, - ssock->send_buf_pending.flags); - if (status == PJ_SUCCESS || status == PJ_EPENDING) { - ssock->send_buf_pending.data_len = 0; - } + pj_status_t status; + status = flush_circ_buf_output(ssock, ssock->send_buf_pending.app_key, + ssock->send_buf_pending.plain_data_len, + ssock->send_buf_pending.flags); + if (status == PJ_SUCCESS || status == PJ_EPENDING) { + ssock->send_buf_pending.data_len = 0; + } } return PJ_TRUE; } static pj_status_t get_localaddr(pj_ssl_sock_t *ssock, - pj_sockaddr_t *addr, - int *namelen) + pj_sockaddr_t *addr, + int *namelen) { PJ_UNUSED_ARG(addr); PJ_UNUSED_ARG(namelen); #ifdef SSL_SOCK_IMP_USE_OWN_NETWORK return network_get_localaddr(ssock, &ssock->local_addr, - &ssock->addr_len); + &ssock->addr_len); #else return pj_sock_getsockname(ssock->sock, &ssock->local_addr, - &ssock->addr_len); + &ssock->addr_len); #endif } static pj_bool_t ssock_on_accept_complete (pj_ssl_sock_t *ssock_parent, - pj_sock_t newsock, - void *newconn, - const pj_sockaddr_t *src_addr, - int src_addr_len, - pj_status_t accept_status) + pj_sock_t newsock, + void *newconn, + const pj_sockaddr_t *src_addr, + int src_addr_len, + pj_status_t accept_status) { pj_ssl_sock_t *ssock; #ifndef SSL_SOCK_IMP_USE_OWN_NETWORK @@ -932,34 +932,34 @@ static pj_bool_t ssock_on_accept_complete (pj_ssl_sock_t *ssock_parent, #endif if (accept_status != PJ_SUCCESS) { - if (ssock_parent->param.cb.on_accept_complete2) { - (*ssock_parent->param.cb.on_accept_complete2)(ssock_parent, NULL, - src_addr, - src_addr_len, - accept_status); - } - return PJ_TRUE; + if (ssock_parent->param.cb.on_accept_complete2) { + (*ssock_parent->param.cb.on_accept_complete2)(ssock_parent, NULL, + src_addr, + src_addr_len, + accept_status); + } + return PJ_TRUE; } /* Create new SSL socket instance */ status = pj_ssl_sock_create(ssock_parent->pool, - &ssock_parent->newsock_param, &ssock); + &ssock_parent->newsock_param, &ssock); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Set parent and add ref count (avoid parent destroy during handshake) */ ssock->parent = ssock_parent; if (ssock->parent->param.grp_lock) - pj_grp_lock_add_ref(ssock->parent->param.grp_lock); + pj_grp_lock_add_ref(ssock->parent->param.grp_lock); /* Update new SSL socket attributes */ ssock->sock = newsock; ssock->is_server = PJ_TRUE; if (ssock_parent->cert) { - status = pj_ssl_sock_set_certificate(ssock, ssock->pool, - ssock_parent->cert); - if (status != PJ_SUCCESS) - goto on_return; + status = pj_ssl_sock_set_certificate(ssock, ssock->pool, + ssock_parent->cert); + if (status != PJ_SUCCESS) + goto on_return; } /* Set local address */ @@ -972,66 +972,66 @@ static pj_bool_t ssock_on_accept_complete (pj_ssl_sock_t *ssock_parent, /* Create SSL context */ status = ssl_create(ssock); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Set peer name */ ssl_set_peer_name(ssock); /* Prepare read buffer */ ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool, - ssock->param.async_cnt, - sizeof(void*)); + ssock->param.async_cnt, + sizeof(void*)); if (!ssock->asock_rbuf) { - status = PJ_ENOMEM; - goto on_return; + status = PJ_ENOMEM; + goto on_return; } for (i = 0; iparam.async_cnt; ++i) { - ssock->asock_rbuf[i] = (void*) pj_pool_alloc( - ssock->pool, - ssock->param.read_buffer_size + - sizeof(read_data_t*)); - if (!ssock->asock_rbuf[i]) { - status = PJ_ENOMEM; - goto on_return; - } + ssock->asock_rbuf[i] = (void*) pj_pool_alloc( + ssock->pool, + ssock->param.read_buffer_size + + sizeof(read_data_t*)); + if (!ssock->asock_rbuf[i]) { + status = PJ_ENOMEM; + goto on_return; + } } /* If listener socket has group lock, automatically create group lock * for the new socket. */ if (ssock_parent->param.grp_lock) { - pj_grp_lock_t *glock; + pj_grp_lock_t *glock; - status = pj_grp_lock_create(ssock->pool, NULL, &glock); - if (status != PJ_SUCCESS) - goto on_return; + status = pj_grp_lock_create(ssock->pool, NULL, &glock); + if (status != PJ_SUCCESS) + goto on_return; - pj_grp_lock_add_ref(glock); - ssock->param.grp_lock = glock; - pj_grp_lock_add_handler(ssock->param.grp_lock, ssock->pool, ssock, - ssl_on_destroy); + pj_grp_lock_add_ref(glock); + ssock->param.grp_lock = glock; + pj_grp_lock_add_handler(ssock->param.grp_lock, ssock->pool, ssock, + ssl_on_destroy); } #ifdef SSL_SOCK_IMP_USE_OWN_NETWORK status = network_setup_connection(ssock, newconn); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; #else /* Apply QoS, if specified */ status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type, - &ssock->param.qos_params, 1, - ssock->pool->obj_name, NULL); + &ssock->param.qos_params, 1, + ssock->pool->obj_name, NULL); if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error) - goto on_return; + goto on_return; /* Apply socket options, if specified */ if (ssock->param.sockopt_params.cnt) { - status = pj_sock_setsockopt_params(ssock->sock, - &ssock->param.sockopt_params); - if (status != PJ_SUCCESS && !ssock->param.sockopt_ignore_error) - goto on_return; + status = pj_sock_setsockopt_params(ssock->sock, + &ssock->param.sockopt_params); + if (status != PJ_SUCCESS && !ssock->param.sockopt_ignore_error) + goto on_return; } /* Create active socket */ @@ -1046,40 +1046,40 @@ static pj_bool_t ssock_on_accept_complete (pj_ssl_sock_t *ssock_parent, asock_cb.on_data_sent = asock_on_data_sent; status = pj_activesock_create(ssock->pool, - ssock->sock, - ssock->param.sock_type, - &asock_cfg, - ssock->param.ioqueue, - &asock_cb, - ssock, - &ssock->asock); + ssock->sock, + ssock->param.sock_type, + &asock_cfg, + ssock->param.ioqueue, + &asock_cb, + ssock, + &ssock->asock); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Start read */ status = pj_activesock_start_read2(ssock->asock, ssock->pool, - (unsigned)ssock->param.read_buffer_size, - ssock->asock_rbuf, - PJ_IOQUEUE_ALWAYS_ASYNC); + (unsigned)ssock->param.read_buffer_size, + ssock->asock_rbuf, + PJ_IOQUEUE_ALWAYS_ASYNC); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; #endif /* Update local address */ status = get_localaddr(ssock, &ssock->local_addr, &ssock->addr_len); if (status != PJ_SUCCESS) { - /* This fails on few envs, e.g: win IOCP, just tolerate this and - * use parent local address instead. - */ - pj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr); + /* This fails on few envs, e.g: win IOCP, just tolerate this and + * use parent local address instead. + */ + pj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr); } /* Prepare write/send state */ pj_assert(ssock->send_buf.max_len == 0); ssock->send_buf.buf = (char*) - pj_pool_alloc(ssock->pool, - ssock->param.send_buffer_size); + pj_pool_alloc(ssock->pool, + ssock->param.send_buffer_size); if (!ssock->send_buf.buf) return PJ_ENOMEM; @@ -1089,18 +1089,18 @@ static pj_bool_t ssock_on_accept_complete (pj_ssl_sock_t *ssock_parent, /* Start handshake timer */ if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 || - ssock->param.timeout.msec != 0)) + ssock->param.timeout.msec != 0)) { - pj_assert(ssock->timer.id == TIMER_NONE); - status = pj_timer_heap_schedule_w_grp_lock(ssock->param.timer_heap, - &ssock->timer, - &ssock->param.timeout, - TIMER_HANDSHAKE_TIMEOUT, - ssock->param.grp_lock); - if (status != PJ_SUCCESS) { - ssock->timer.id = TIMER_NONE; - status = PJ_SUCCESS; - } + pj_assert(ssock->timer.id == TIMER_NONE); + status = pj_timer_heap_schedule_w_grp_lock(ssock->param.timer_heap, + &ssock->timer, + &ssock->param.timeout, + TIMER_HANDSHAKE_TIMEOUT, + ssock->param.grp_lock); + if (status != PJ_SUCCESS) { + ssock->timer.id = TIMER_NONE; + status = PJ_SUCCESS; + } } /* Start SSL handshake */ @@ -1110,7 +1110,7 @@ static pj_bool_t ssock_on_accept_complete (pj_ssl_sock_t *ssock_parent, on_return: if (ssock && status != PJ_EPENDING) { - on_handshake_complete(ssock, status); + on_handshake_complete(ssock, status); } /* Must return PJ_TRUE whatever happened, as we must continue listening */ @@ -1118,36 +1118,36 @@ static pj_bool_t ssock_on_accept_complete (pj_ssl_sock_t *ssock_parent, } static pj_bool_t ssock_on_connect_complete (pj_ssl_sock_t *ssock, - pj_status_t status) + pj_status_t status) { unsigned i; if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Update local address */ ssock->addr_len = sizeof(pj_sockaddr); status = get_localaddr(ssock, &ssock->local_addr, &ssock->addr_len); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create SSL context */ status = ssl_create(ssock); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Prepare read buffer */ ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool, - ssock->param.async_cnt, - sizeof(void*)); + ssock->param.async_cnt, + sizeof(void*)); if (!ssock->asock_rbuf) return PJ_ENOMEM; for (i = 0; iparam.async_cnt; ++i) { - ssock->asock_rbuf[i] = (void*) pj_pool_alloc( - ssock->pool, - ssock->param.read_buffer_size + - sizeof(read_data_t*)); + ssock->asock_rbuf[i] = (void*) pj_pool_alloc( + ssock->pool, + ssock->param.read_buffer_size + + sizeof(read_data_t*)); if (!ssock->asock_rbuf[i]) return PJ_ENOMEM; } @@ -1155,22 +1155,22 @@ static pj_bool_t ssock_on_connect_complete (pj_ssl_sock_t *ssock, /* Start read */ #ifdef SSL_SOCK_IMP_USE_OWN_NETWORK status = network_start_read(ssock, ssock->param.async_cnt, - (unsigned)ssock->param.read_buffer_size, - ssock->asock_rbuf, 0); + (unsigned)ssock->param.read_buffer_size, + ssock->asock_rbuf, 0); #else status = pj_activesock_start_read2(ssock->asock, ssock->pool, - (unsigned)ssock->param.read_buffer_size, - ssock->asock_rbuf, - PJ_IOQUEUE_ALWAYS_ASYNC); + (unsigned)ssock->param.read_buffer_size, + ssock->asock_rbuf, + PJ_IOQUEUE_ALWAYS_ASYNC); #endif if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Prepare write/send state */ pj_assert(ssock->send_buf.max_len == 0); ssock->send_buf.buf = (char*) - pj_pool_alloc(ssock->pool, - ssock->param.send_buffer_size); + pj_pool_alloc(ssock->pool, + ssock->param.send_buffer_size); if (!ssock->send_buf.buf) return PJ_ENOMEM; @@ -1187,7 +1187,7 @@ static pj_bool_t ssock_on_connect_complete (pj_ssl_sock_t *ssock, status = ssl_do_handshake(ssock); if (status != PJ_EPENDING) - goto on_return; + goto on_return; return PJ_TRUE; @@ -1197,45 +1197,45 @@ static pj_bool_t ssock_on_connect_complete (pj_ssl_sock_t *ssock, #ifndef SSL_SOCK_IMP_USE_OWN_NETWORK static pj_bool_t asock_on_data_read (pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { pj_ssl_sock_t *ssock = (pj_ssl_sock_t*) - pj_activesock_get_user_data(asock); + pj_activesock_get_user_data(asock); return ssock_on_data_read(ssock, data, size, status, remainder); } static pj_bool_t asock_on_data_sent (pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent) + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent) { pj_ssl_sock_t *ssock = (pj_ssl_sock_t*) - pj_activesock_get_user_data(asock); + pj_activesock_get_user_data(asock); return ssock_on_data_sent(ssock, send_key, sent); } static pj_bool_t asock_on_accept_complete2(pj_activesock_t *asock, - pj_sock_t newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len, - pj_status_t status) + pj_sock_t newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len, + pj_status_t status) { pj_ssl_sock_t *ssock = (pj_ssl_sock_t*) - pj_activesock_get_user_data(asock); + pj_activesock_get_user_data(asock); return ssock_on_accept_complete(ssock, newsock, NULL, - src_addr, src_addr_len, status); + src_addr, src_addr_len, status); } static pj_bool_t asock_on_connect_complete (pj_activesock_t *asock, - pj_status_t status) + pj_status_t status) { pj_ssl_sock_t *ssock = (pj_ssl_sock_t*) - pj_activesock_get_user_data(asock); + pj_activesock_get_user_data(asock); return ssock_on_connect_complete(ssock, status); } @@ -1249,7 +1249,7 @@ static pj_bool_t asock_on_connect_complete (pj_activesock_t *asock, /* Get available ciphers. */ PJ_DEF(pj_status_t) pj_ssl_cipher_get_availables(pj_ssl_cipher ciphers[], - unsigned *cipher_num) + unsigned *cipher_num) { unsigned i; @@ -1258,14 +1258,14 @@ PJ_DEF(pj_status_t) pj_ssl_cipher_get_availables(pj_ssl_cipher ciphers[], ssl_ciphers_populate(); if (ssl_cipher_num == 0) { - *cipher_num = 0; - return PJ_ENOTFOUND; + *cipher_num = 0; + return PJ_ENOTFOUND; } *cipher_num = PJ_MIN(*cipher_num, ssl_cipher_num); for (i = 0; i < *cipher_num; ++i) - ciphers[i] = ssl_ciphers[i].id; + ciphers[i] = ssl_ciphers[i].id; return PJ_SUCCESS; } @@ -1278,8 +1278,8 @@ PJ_DEF(const char*) pj_ssl_cipher_name(pj_ssl_cipher cipher) ssl_ciphers_populate(); for (i = 0; i < ssl_cipher_num; ++i) { - if (cipher == ssl_ciphers[i].id) - return ssl_ciphers[i].name; + if (cipher == ssl_ciphers[i].id) + return ssl_ciphers[i].name; } return NULL; @@ -1308,8 +1308,8 @@ PJ_DEF(pj_bool_t) pj_ssl_cipher_is_supported(pj_ssl_cipher cipher) ssl_ciphers_populate(); for (i = 0; i < ssl_cipher_num; ++i) { - if (cipher == ssl_ciphers[i].id) - return PJ_TRUE; + if (cipher == ssl_ciphers[i].id) + return PJ_TRUE; } return PJ_FALSE; @@ -1317,7 +1317,7 @@ PJ_DEF(pj_bool_t) pj_ssl_cipher_is_supported(pj_ssl_cipher cipher) /* Get available curves. */ PJ_DEF(pj_status_t) pj_ssl_curve_get_availables(pj_ssl_curve curves[], - unsigned *curve_num) + unsigned *curve_num) { unsigned i; @@ -1326,14 +1326,14 @@ PJ_DEF(pj_status_t) pj_ssl_curve_get_availables(pj_ssl_curve curves[], ssl_ciphers_populate(); if (ssl_curves_num == 0) { - *curve_num = 0; - return PJ_ENOTFOUND; + *curve_num = 0; + return PJ_ENOTFOUND; } *curve_num = PJ_MIN(*curve_num, ssl_curves_num); for (i = 0; i < *curve_num; ++i) - curves[i] = ssl_curves[i].id; + curves[i] = ssl_curves[i].id; return PJ_SUCCESS; } @@ -1346,8 +1346,8 @@ PJ_DEF(const char*) pj_ssl_curve_name(pj_ssl_curve curve) ssl_ciphers_populate(); for (i = 0; i < ssl_curves_num; ++i) { - if (curve == ssl_curves[i].id) - return ssl_curves[i].name; + if (curve == ssl_curves[i].id) + return ssl_curves[i].name; } return NULL; @@ -1362,7 +1362,7 @@ PJ_DEF(pj_ssl_curve) pj_ssl_curve_id(const char *curve_name) for (i = 0; i < ssl_curves_num; ++i) { if (ssl_curves[i].name && - !pj_ansi_stricmp(ssl_curves[i].name, curve_name)) + !pj_ansi_stricmp(ssl_curves[i].name, curve_name)) { return ssl_curves[i].id; } @@ -1379,8 +1379,8 @@ PJ_DEF(pj_bool_t) pj_ssl_curve_is_supported(pj_ssl_curve curve) ssl_ciphers_populate(); for (i = 0; i < ssl_curves_num; ++i) { - if (curve == ssl_curves[i].id) - return PJ_TRUE; + if (curve == ssl_curves[i].id) + return PJ_TRUE; } return PJ_FALSE; @@ -1390,8 +1390,8 @@ PJ_DEF(pj_bool_t) pj_ssl_curve_is_supported(pj_ssl_curve curve) * Create SSL socket instance. */ PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool, - const pj_ssl_sock_param *param, - pj_ssl_sock_t **p_ssock) + const pj_ssl_sock_param *param, + pj_ssl_sock_t **p_ssock) { pj_ssl_sock_t *ssock; pj_status_t status; @@ -1406,7 +1406,7 @@ PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool, /* Create secure socket */ ssock = ssl_alloc(pool); if (!ssock) - return PJ_ENOMEM; + return PJ_ENOMEM; ssock->pool = pool; ssock->info_pool = info_pool; ssock->sock = PJ_INVALID_SOCKET; @@ -1418,9 +1418,9 @@ PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool, pj_list_init(&ssock->send_pending); pj_timer_entry_init(&ssock->timer, 0, ssock, &on_timer); pj_ioqueue_op_key_init(&ssock->handshake_op_key, - sizeof(pj_ioqueue_op_key_t)); + sizeof(pj_ioqueue_op_key_t)); pj_ioqueue_op_key_init(&ssock->shutdown_op_key, - sizeof(pj_ioqueue_op_key_t)); + sizeof(pj_ioqueue_op_key_t)); /* Create secure socket mutex */ status = pj_lock_create_recursive_mutex(pool, pool->obj_name, @@ -1439,17 +1439,17 @@ PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool, pj_ssl_sock_param_copy(pool, &ssock->param, param); if (ssock->param.grp_lock) { - pj_grp_lock_add_ref(ssock->param.grp_lock); - pj_grp_lock_add_handler(ssock->param.grp_lock, pool, ssock, - ssl_on_destroy); + pj_grp_lock_add_ref(ssock->param.grp_lock); + pj_grp_lock_add_handler(ssock->param.grp_lock, pool, ssock, + ssl_on_destroy); } ssock->param.read_buffer_size = ((ssock->param.read_buffer_size+7)>>3)<<3; if (!ssock->param.timer_heap) { - PJ_LOG(3,(ssock->pool->obj_name, "Warning: timer heap is not " - "available. It is recommended to supply one to avoid " - "a race condition if more than one worker threads " - "are used.")); + PJ_LOG(3,(ssock->pool->obj_name, "Warning: timer heap is not " + "available. It is recommended to supply one to avoid " + "a race condition if more than one worker threads " + "are used.")); } /* Finally */ @@ -1468,27 +1468,27 @@ PJ_DEF(pj_status_t) pj_ssl_sock_close(pj_ssl_sock_t *ssock) PJ_ASSERT_RETURN(ssock, PJ_EINVAL); if (!ssock->pool || ssock->is_closing) - return PJ_SUCCESS; + return PJ_SUCCESS; ssock->is_closing = PJ_TRUE; if (ssock->timer.id != TIMER_NONE) { - pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer); - ssock->timer.id = TIMER_NONE; + pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer); + ssock->timer.id = TIMER_NONE; } ssl_reset_sock_state(ssock); /* Wipe out cert & key buffer. */ if (ssock->cert) { - pj_ssl_cert_wipe_keys(ssock->cert); - ssock->cert = NULL; + pj_ssl_cert_wipe_keys(ssock->cert); + ssock->cert = NULL; } if (ssock->param.grp_lock) { - pj_grp_lock_dec_ref(ssock->param.grp_lock); + pj_grp_lock_dec_ref(ssock->param.grp_lock); } else { - ssl_on_destroy(ssock); + ssl_on_destroy(ssock); } return PJ_SUCCESS; @@ -1499,7 +1499,7 @@ PJ_DEF(pj_status_t) pj_ssl_sock_close(pj_ssl_sock_t *ssock) * Associate arbitrary data with the secure socket. */ PJ_DEF(pj_status_t) pj_ssl_sock_set_user_data(pj_ssl_sock_t *ssock, - void *user_data) + void *user_data) { PJ_ASSERT_RETURN(ssock, PJ_EINVAL); @@ -1523,7 +1523,7 @@ PJ_DEF(void*) pj_ssl_sock_get_user_data(pj_ssl_sock_t *ssock) * Retrieve the local address and port used by specified SSL socket. */ PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock, - pj_ssl_sock_info *info) + pj_ssl_sock_info *info) { pj_bzero(info, sizeof(*info)); @@ -1542,13 +1542,13 @@ PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock, /* Remote address */ if (pj_sockaddr_has_addr(&ssock->rem_addr)) - pj_sockaddr_cp(&info->remote_addr, &ssock->rem_addr); + pj_sockaddr_cp(&info->remote_addr, &ssock->rem_addr); if (info->established) { - info->cipher = ssl_get_cipher(ssock); + info->cipher = ssl_get_cipher(ssock); - /* Verification status */ - info->verify_status = ssock->verify_status; + /* Verification status */ + info->verify_status = ssock->verify_status; } /* Last known SSL error code */ @@ -1565,9 +1565,9 @@ PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock, * Starts read operation on this secure socket. */ PJ_DEF(pj_status_t) pj_ssl_sock_start_read (pj_ssl_sock_t *ssock, - pj_pool_t *pool, - unsigned buff_size, - pj_uint32_t flags) + pj_pool_t *pool, + unsigned buff_size, + pj_uint32_t flags) { void **readbuf; unsigned i; @@ -1575,21 +1575,21 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_read (pj_ssl_sock_t *ssock, PJ_ASSERT_RETURN(ssock && pool && buff_size, PJ_EINVAL); if (ssock->ssl_state != SSL_STATE_ESTABLISHED) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; readbuf = (void**) pj_pool_calloc(pool, ssock->param.async_cnt, - sizeof(void*)); + sizeof(void*)); if (!readbuf) return PJ_ENOMEM; for (i=0; iparam.async_cnt; ++i) { - readbuf[i] = pj_pool_alloc(pool, buff_size); + readbuf[i] = pj_pool_alloc(pool, buff_size); if (!readbuf[i]) return PJ_ENOMEM; } return pj_ssl_sock_start_read2(ssock, pool, buff_size, - readbuf, flags); + readbuf, flags); } @@ -1599,34 +1599,34 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_read (pj_ssl_sock_t *ssock, * does not have to allocate the buffers. */ PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock, - pj_pool_t *pool, - unsigned buff_size, - void *readbuf[], - pj_uint32_t flags) + pj_pool_t *pool, + unsigned buff_size, + void *readbuf[], + pj_uint32_t flags) { unsigned i; PJ_ASSERT_RETURN(ssock && pool && buff_size && readbuf, PJ_EINVAL); if (ssock->ssl_state != SSL_STATE_ESTABLISHED) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; /* Create SSL socket read buffer */ ssock->ssock_rbuf = (read_data_t*)pj_pool_calloc(pool, - ssock->param.async_cnt, - sizeof(read_data_t)); + ssock->param.async_cnt, + sizeof(read_data_t)); if (!ssock->ssock_rbuf) return PJ_ENOMEM; /* Store SSL socket read buffer pointer in the activesock read buffer */ for (i=0; iparam.async_cnt; ++i) { - read_data_t **p_ssock_rbuf = - OFFSET_OF_READ_DATA_PTR(ssock, ssock->asock_rbuf[i]); + read_data_t **p_ssock_rbuf = + OFFSET_OF_READ_DATA_PTR(ssock, ssock->asock_rbuf[i]); - ssock->ssock_rbuf[i].data = readbuf[i]; - ssock->ssock_rbuf[i].len = 0; + ssock->ssock_rbuf[i].data = readbuf[i]; + ssock->ssock_rbuf[i].len = 0; - *p_ssock_rbuf = &ssock->ssock_rbuf[i]; + *p_ssock_rbuf = &ssock->ssock_rbuf[i]; } ssock->read_size = buff_size; @@ -1634,11 +1634,11 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock, ssock->read_flags = flags; for (i=0; iparam.async_cnt; ++i) { - if (ssock->asock_rbuf[i]) { - pj_size_t remainder = 0; - ssock_on_data_read(ssock, ssock->asock_rbuf[i], 0, - PJ_SUCCESS, &remainder); - } + if (ssock->asock_rbuf[i]) { + pj_size_t remainder = 0; + ssock_on_data_read(ssock, ssock->asock_rbuf[i], 0, + PJ_SUCCESS, &remainder); + } } return PJ_SUCCESS; @@ -1651,9 +1651,9 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock, * callback instead. */ PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom (pj_ssl_sock_t *ssock, - pj_pool_t *pool, - unsigned buff_size, - pj_uint32_t flags) + pj_pool_t *pool, + unsigned buff_size, + pj_uint32_t flags) { PJ_UNUSED_ARG(ssock); PJ_UNUSED_ARG(pool); @@ -1670,10 +1670,10 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom (pj_ssl_sock_t *ssock, * new ones. */ PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom2 (pj_ssl_sock_t *ssock, - pj_pool_t *pool, - unsigned buff_size, - void *readbuf[], - pj_uint32_t flags) + pj_pool_t *pool, + unsigned buff_size, + void *readbuf[], + pj_uint32_t flags) { PJ_UNUSED_ARG(ssock); PJ_UNUSED_ARG(pool); @@ -1687,10 +1687,10 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom2 (pj_ssl_sock_t *ssock, /* Write plain data to SSL and flush the buffer. */ static pj_status_t ssl_send (pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t size, - unsigned flags) + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t size, + unsigned flags) { pj_status_t status; int nwritten; @@ -1705,22 +1705,22 @@ static pj_status_t ssl_send (pj_ssl_sock_t *ssock, * write buffer already, just return PJ_ENOMEM. */ if (ssock->send_buf_pending.data_len) { - pj_lock_release(ssock->write_mutex); - return PJ_ENOMEM; + pj_lock_release(ssock->write_mutex); + return PJ_ENOMEM; } status = ssl_write(ssock, data, size, &nwritten); pj_lock_release(ssock->write_mutex); if (status == PJ_SUCCESS && nwritten == size) { - /* All data written, flush write buffer to network socket */ - status = flush_circ_buf_output(ssock, send_key, size, flags); + /* All data written, flush write buffer to network socket */ + status = flush_circ_buf_output(ssock, send_key, size, flags); } else if (status == PJ_EEOF) { /* Re-negotiation is on progress, flush re-negotiation data */ - status = flush_circ_buf_output(ssock, &ssock->handshake_op_key, 0, 0); - if (status == PJ_SUCCESS || status == PJ_EPENDING) { - /* Just return PJ_EBUSY when re-negotiation is on progress */ - status = PJ_EBUSY; - } + status = flush_circ_buf_output(ssock, &ssock->handshake_op_key, 0, 0); + if (status == PJ_SUCCESS || status == PJ_EPENDING) { + /* Just return PJ_EBUSY when re-negotiation is on progress */ + status = PJ_EBUSY; + } } return status; @@ -1731,14 +1731,14 @@ static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock) { /* Check for another ongoing flush */ if (ssock->flushing_write_pend) - return PJ_EBUSY; + return PJ_EBUSY; pj_lock_acquire(ssock->write_mutex); /* Again, check for another ongoing flush */ if (ssock->flushing_write_pend) { - pj_lock_release(ssock->write_mutex); - return PJ_EBUSY; + pj_lock_release(ssock->write_mutex); + return PJ_EBUSY; } /* Set ongoing flush flag */ @@ -1746,24 +1746,24 @@ static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock) while (!pj_list_empty(&ssock->write_pending)) { write_data_t *wp; - pj_status_t status; + pj_status_t status; - wp = ssock->write_pending.next; + wp = ssock->write_pending.next; - /* Ticket #1573: Don't hold mutex while calling socket send. */ - pj_lock_release(ssock->write_mutex); + /* Ticket #1573: Don't hold mutex while calling socket send. */ + pj_lock_release(ssock->write_mutex); - status = ssl_send (ssock, &wp->key, wp->data.ptr, - wp->plain_data_len, wp->flags); - if (status != PJ_SUCCESS) { - /* Reset ongoing flush flag first. */ - ssock->flushing_write_pend = PJ_FALSE; - return status; - } + status = ssl_send (ssock, &wp->key, wp->data.ptr, + wp->plain_data_len, wp->flags); + if (status != PJ_SUCCESS) { + /* Reset ongoing flush flag first. */ + ssock->flushing_write_pend = PJ_FALSE; + return status; + } - pj_lock_acquire(ssock->write_mutex); - pj_list_erase(wp); - pj_list_push_back(&ssock->write_pending_empty, wp); + pj_lock_acquire(ssock->write_mutex); + pj_list_erase(wp); + pj_list_push_back(&ssock->write_pending_empty, wp); } /* Reset ongoing flush flag */ @@ -1776,10 +1776,10 @@ static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock) /* Sending is delayed, push back the sending data into pending list. */ static pj_status_t delay_send (pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t size, - unsigned flags) + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t size, + unsigned flags) { write_data_t *wp; @@ -1787,10 +1787,10 @@ static pj_status_t delay_send (pj_ssl_sock_t *ssock, /* Init write pending instance */ if (!pj_list_empty(&ssock->write_pending_empty)) { - wp = ssock->write_pending_empty.next; - pj_list_erase(wp); + wp = ssock->write_pending_empty.next; + pj_list_erase(wp); } else { - wp = PJ_POOL_ZALLOC_T(ssock->pool, write_data_t); + wp = PJ_POOL_ZALLOC_T(ssock->pool, write_data_t); } wp->app_key = send_key; @@ -1811,17 +1811,17 @@ static pj_status_t delay_send (pj_ssl_sock_t *ssock, * Send data using the socket. */ PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t *size, - unsigned flags) + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t *size, + unsigned flags) { pj_status_t status; PJ_ASSERT_RETURN(ssock && data && size && (*size>0), PJ_EINVAL); if (ssock->ssl_state != SSL_STATE_ESTABLISHED) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; // Ticket #1573: Don't hold mutex while calling PJLIB socket send(). //pj_lock_acquire(ssock->write_mutex); @@ -1831,18 +1831,18 @@ PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock, */ status = flush_delayed_send(ssock); if (status == PJ_EBUSY) { - /* Re-negotiation or flushing is on progress, delay sending */ - status = delay_send(ssock, send_key, data, *size, flags); - goto on_return; + /* Re-negotiation or flushing is on progress, delay sending */ + status = delay_send(ssock, send_key, data, *size, flags); + goto on_return; } else if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Write data to SSL */ status = ssl_send(ssock, send_key, data, *size, flags); if (status == PJ_EBUSY) { - /* Re-negotiation is on progress, delay sending */ - status = delay_send(ssock, send_key, data, *size, flags); + /* Re-negotiation is on progress, delay sending */ + status = delay_send(ssock, send_key, data, *size, flags); } on_return: @@ -1855,12 +1855,12 @@ PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock, * Send datagram using the socket. */ PJ_DEF(pj_status_t) pj_ssl_sock_sendto (pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t *size, - unsigned flags, - const pj_sockaddr_t *addr, - int addr_len) + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t *size, + unsigned flags, + const pj_sockaddr_t *addr, + int addr_len) { PJ_UNUSED_ARG(ssock); PJ_UNUSED_ARG(send_key); @@ -1878,12 +1878,12 @@ PJ_DEF(pj_status_t) pj_ssl_sock_sendto (pj_ssl_sock_t *ssock, * Starts asynchronous socket accept() operations on this secure socket. */ PJ_DEF(pj_status_t) pj_ssl_sock_start_accept (pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_sockaddr_t *localaddr, - int addr_len) + pj_pool_t *pool, + const pj_sockaddr_t *localaddr, + int addr_len) { return pj_ssl_sock_start_accept2(ssock, pool, localaddr, addr_len, - &ssock->param); + &ssock->param); } @@ -1893,10 +1893,10 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_accept (pj_ssl_sock_t *ssock, */ PJ_DEF(pj_status_t) pj_ssl_sock_start_accept2(pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_sockaddr_t *localaddr, - int addr_len, - const pj_ssl_sock_param *newsock_param) + pj_pool_t *pool, + const pj_sockaddr_t *localaddr, + int addr_len, + const pj_ssl_sock_param *newsock_param) { pj_status_t status; #ifndef SSL_SOCK_IMP_USE_OWN_NETWORK @@ -1918,53 +1918,53 @@ pj_ssl_sock_start_accept2(pj_ssl_sock_t *ssock, #ifdef SSL_SOCK_IMP_USE_OWN_NETWORK status = network_start_accept(ssock, pool, localaddr, addr_len, - newsock_param); + newsock_param); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #else /* Create socket */ status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0, - &ssock->sock); + &ssock->sock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Apply SO_REUSEADDR */ if (ssock->param.reuse_addr) { - int enabled = 1; - status = pj_sock_setsockopt(ssock->sock, pj_SOL_SOCKET(), - pj_SO_REUSEADDR(), - &enabled, sizeof(enabled)); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(ssock->pool->obj_name, status, - "Warning: error applying SO_REUSEADDR")); - } + int enabled = 1; + status = pj_sock_setsockopt(ssock->sock, pj_SOL_SOCKET(), + pj_SO_REUSEADDR(), + &enabled, sizeof(enabled)); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(ssock->pool->obj_name, status, + "Warning: error applying SO_REUSEADDR")); + } } /* Apply QoS, if specified */ status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type, - &ssock->param.qos_params, 2, - ssock->pool->obj_name, NULL); + &ssock->param.qos_params, 2, + ssock->pool->obj_name, NULL); if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error) - goto on_error; + goto on_error; /* Apply socket options, if specified */ if (ssock->param.sockopt_params.cnt) { - status = pj_sock_setsockopt_params(ssock->sock, - &ssock->param.sockopt_params); + status = pj_sock_setsockopt_params(ssock->sock, + &ssock->param.sockopt_params); - if (status != PJ_SUCCESS && !ssock->param.sockopt_ignore_error) - goto on_error; + if (status != PJ_SUCCESS && !ssock->param.sockopt_ignore_error) + goto on_error; } /* Bind socket */ status = pj_sock_bind(ssock->sock, localaddr, addr_len); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Start listening to the address */ status = pj_sock_listen(ssock->sock, PJ_SOMAXCONN); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create active socket */ pj_activesock_cfg_default(&asock_cfg); @@ -1978,30 +1978,30 @@ pj_ssl_sock_start_accept2(pj_ssl_sock_t *ssock, asock_cb.on_accept_complete2 = asock_on_accept_complete2; status = pj_activesock_create(pool, - ssock->sock, - ssock->param.sock_type, - &asock_cfg, - ssock->param.ioqueue, - &asock_cb, - ssock, - &ssock->asock); + ssock->sock, + ssock->param.sock_type, + &asock_cfg, + ssock->param.ioqueue, + &asock_cb, + ssock, + &ssock->asock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Start accepting */ pj_ssl_sock_param_copy(pool, &ssock->newsock_param, newsock_param); ssock->newsock_param.grp_lock = NULL; status = pj_activesock_start_accept(ssock->asock, pool); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Update local address */ ssock->addr_len = addr_len; status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, - &ssock->addr_len); + &ssock->addr_len); if (status != PJ_SUCCESS) - pj_sockaddr_cp(&ssock->local_addr, localaddr); + pj_sockaddr_cp(&ssock->local_addr, localaddr); #endif return PJ_SUCCESS; @@ -2016,10 +2016,10 @@ pj_ssl_sock_start_accept2(pj_ssl_sock_t *ssock, * Starts asynchronous socket connect() operation. */ PJ_DEF(pj_status_t) pj_ssl_sock_start_connect(pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_sockaddr_t *localaddr, - const pj_sockaddr_t *remaddr, - int addr_len) + pj_pool_t *pool, + const pj_sockaddr_t *localaddr, + const pj_sockaddr_t *remaddr, + int addr_len) { pj_ssl_start_connect_param param; param.pool = pool; @@ -2032,14 +2032,14 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_connect(pj_ssl_sock_t *ssock, } PJ_DEF(pj_status_t) pj_ssl_sock_start_connect2( - pj_ssl_sock_t *ssock, - pj_ssl_start_connect_param *connect_param) + pj_ssl_sock_t *ssock, + pj_ssl_start_connect_param *connect_param) { pj_status_t status; #ifdef SSL_SOCK_IMP_USE_OWN_NETWORK status = network_start_connect(ssock, connect_param); if (status != PJ_EPENDING) - goto on_error; + goto on_error; #else pj_activesock_cb asock_cb; pj_activesock_cfg asock_cfg; @@ -2051,45 +2051,45 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_connect2( int addr_len = connect_param->addr_len; PJ_ASSERT_RETURN(ssock && pool && localaddr && remaddr && addr_len, - PJ_EINVAL); + PJ_EINVAL); /* Create socket */ status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0, - &ssock->sock); + &ssock->sock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Apply QoS, if specified */ status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type, - &ssock->param.qos_params, 2, - ssock->pool->obj_name, NULL); + &ssock->param.qos_params, 2, + ssock->pool->obj_name, NULL); if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error) - goto on_error; + goto on_error; /* Apply socket options, if specified */ if (ssock->param.sockopt_params.cnt) { - status = pj_sock_setsockopt_params(ssock->sock, - &ssock->param.sockopt_params); + status = pj_sock_setsockopt_params(ssock->sock, + &ssock->param.sockopt_params); - if (status != PJ_SUCCESS && !ssock->param.sockopt_ignore_error) - goto on_error; + if (status != PJ_SUCCESS && !ssock->param.sockopt_ignore_error) + goto on_error; } /* Bind socket */ if (port_range) { - pj_uint16_t max_bind_retry = MAX_BIND_RETRY; - if (port_range && port_range < max_bind_retry) - { - max_bind_retry = port_range; - } - status = pj_sock_bind_random(ssock->sock, localaddr, port_range, - max_bind_retry); + pj_uint16_t max_bind_retry = MAX_BIND_RETRY; + if (port_range && port_range < max_bind_retry) + { + max_bind_retry = port_range; + } + status = pj_sock_bind_random(ssock->sock, localaddr, port_range, + max_bind_retry); } else { - status = pj_sock_bind(ssock->sock, localaddr, addr_len); + status = pj_sock_bind(ssock->sock, localaddr, addr_len); } if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create active socket */ pj_activesock_cfg_default(&asock_cfg); @@ -2104,32 +2104,32 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_connect2( asock_cb.on_data_sent = asock_on_data_sent; status = pj_activesock_create(pool, - ssock->sock, - ssock->param.sock_type, - &asock_cfg, - ssock->param.ioqueue, - &asock_cb, - ssock, - &ssock->asock); + ssock->sock, + ssock->param.sock_type, + &asock_cfg, + ssock->param.ioqueue, + &asock_cb, + ssock, + &ssock->asock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Save remote address */ pj_sockaddr_cp(&ssock->rem_addr, remaddr); status = pj_activesock_start_connect(ssock->asock, pool, remaddr, - addr_len); + addr_len); if (status == PJ_SUCCESS) - asock_on_connect_complete(ssock->asock, PJ_SUCCESS); + asock_on_connect_complete(ssock->asock, PJ_SUCCESS); else if (status != PJ_EPENDING) - goto on_error; + goto on_error; /* Update local address */ ssock->addr_len = addr_len; status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, - &ssock->addr_len); + &ssock->addr_len); /* Note that we may not get an IP address here. This can * happen for example on Windows, where getsockname() * would return 0.0.0.0 if socket has just started the @@ -2144,16 +2144,16 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_connect2( if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 || ssock->param.timeout.msec != 0)) { - pj_assert(ssock->timer.id == TIMER_NONE); - status = pj_timer_heap_schedule_w_grp_lock(ssock->param.timer_heap, - &ssock->timer, - &ssock->param.timeout, - TIMER_HANDSHAKE_TIMEOUT, - ssock->param.grp_lock); - if (status != PJ_SUCCESS) { - ssock->timer.id = TIMER_NONE; - status = PJ_SUCCESS; - } + pj_assert(ssock->timer.id == TIMER_NONE); + status = pj_timer_heap_schedule_w_grp_lock(ssock->param.timer_heap, + &ssock->timer, + &ssock->param.timeout, + TIMER_HANDSHAKE_TIMEOUT, + ssock->param.grp_lock); + if (status != PJ_SUCCESS) { + ssock->timer.id = TIMER_NONE; + status = PJ_SUCCESS; + } } /* Update SSL state */ @@ -2174,11 +2174,11 @@ PJ_DEF(pj_status_t) pj_ssl_sock_renegotiate(pj_ssl_sock_t *ssock) PJ_ASSERT_RETURN(ssock, PJ_EINVAL); if (ssock->ssl_state != SSL_STATE_ESTABLISHED) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; status = ssl_renegotiate(ssock); if (status == PJ_SUCCESS) { - status = ssl_do_handshake(ssock); + status = ssl_do_handshake(ssock); } return status; @@ -2195,49 +2195,49 @@ static void wipe_buf(pj_str_t *buf) PJ_DEF(void) pj_ssl_cert_wipe_keys(pj_ssl_cert_t *cert) { if (cert) { - wipe_buf(&cert->CA_file); - wipe_buf(&cert->CA_path); - wipe_buf(&cert->cert_file); - wipe_buf(&cert->privkey_file); - wipe_buf(&cert->privkey_pass); - wipe_buf(&cert->CA_buf); - wipe_buf(&cert->cert_buf); - wipe_buf(&cert->privkey_buf); + wipe_buf(&cert->CA_file); + wipe_buf(&cert->CA_path); + wipe_buf(&cert->cert_file); + wipe_buf(&cert->privkey_file); + wipe_buf(&cert->privkey_pass); + wipe_buf(&cert->CA_buf); + wipe_buf(&cert->cert_buf); + wipe_buf(&cert->privkey_buf); } } /* Load credentials from files. */ PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files (pj_pool_t *pool, - const pj_str_t *CA_file, - const pj_str_t *cert_file, - const pj_str_t *privkey_file, - const pj_str_t *privkey_pass, - pj_ssl_cert_t **p_cert) + const pj_str_t *CA_file, + const pj_str_t *cert_file, + const pj_str_t *privkey_file, + const pj_str_t *privkey_pass, + pj_ssl_cert_t **p_cert) { return pj_ssl_cert_load_from_files2(pool, CA_file, NULL, cert_file, - privkey_file, privkey_pass, p_cert); + privkey_file, privkey_pass, p_cert); } PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files2(pj_pool_t *pool, - const pj_str_t *CA_file, - const pj_str_t *CA_path, - const pj_str_t *cert_file, - const pj_str_t *privkey_file, - const pj_str_t *privkey_pass, - pj_ssl_cert_t **p_cert) + const pj_str_t *CA_file, + const pj_str_t *CA_path, + const pj_str_t *cert_file, + const pj_str_t *privkey_file, + const pj_str_t *privkey_pass, + pj_ssl_cert_t **p_cert) { pj_ssl_cert_t *cert; PJ_ASSERT_RETURN(pool && (CA_file || CA_path) && cert_file && - privkey_file, - PJ_EINVAL); + privkey_file, + PJ_EINVAL); cert = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t); if (CA_file) { - pj_strdup_with_null(pool, &cert->CA_file, CA_file); + pj_strdup_with_null(pool, &cert->CA_file, CA_file); } if (CA_path) { - pj_strdup_with_null(pool, &cert->CA_path, CA_path); + pj_strdup_with_null(pool, &cert->CA_path, CA_path); } pj_strdup_with_null(pool, &cert->cert_file, cert_file); pj_strdup_with_null(pool, &cert->privkey_file, privkey_file); @@ -2249,11 +2249,11 @@ PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files2(pj_pool_t *pool, } PJ_DEF(pj_status_t) pj_ssl_cert_load_from_buffer(pj_pool_t *pool, - const pj_ssl_cert_buffer *CA_buf, - const pj_ssl_cert_buffer *cert_buf, - const pj_ssl_cert_buffer *privkey_buf, - const pj_str_t *privkey_pass, - pj_ssl_cert_t **p_cert) + const pj_ssl_cert_buffer *CA_buf, + const pj_ssl_cert_buffer *cert_buf, + const pj_ssl_cert_buffer *privkey_buf, + const pj_str_t *privkey_pass, + pj_ssl_cert_t **p_cert) { pj_ssl_cert_t *cert; @@ -2272,9 +2272,9 @@ PJ_DEF(pj_status_t) pj_ssl_cert_load_from_buffer(pj_pool_t *pool, /* Set SSL socket credentials. */ PJ_DEF(pj_status_t) pj_ssl_sock_set_certificate( - pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_ssl_cert_t *cert) + pj_ssl_sock_t *ssock, + pj_pool_t *pool, + const pj_ssl_cert_t *cert) { pj_ssl_cert_t *cert_; diff --git a/pjlib/src/pj/ssl_sock_imp_common.h b/pjlib/src/pj/ssl_sock_imp_common.h index cba28dbd3b..56cce41ba3 100644 --- a/pjlib/src/pj/ssl_sock_imp_common.h +++ b/pjlib/src/pj/ssl_sock_imp_common.h @@ -47,8 +47,8 @@ enum timer_id */ typedef struct read_data_t { - void *data; - pj_size_t len; + void *data; + pj_size_t len; } read_data_t; /* @@ -56,15 +56,15 @@ typedef struct read_data_t */ typedef struct write_data_t { PJ_DECL_LIST_MEMBER(struct write_data_t); - pj_ioqueue_op_key_t key; - pj_size_t record_len; - pj_ioqueue_op_key_t *app_key; - pj_size_t plain_data_len; - pj_size_t data_len; - unsigned flags; + pj_ioqueue_op_key_t key; + pj_size_t record_len; + pj_ioqueue_op_key_t *app_key; + pj_size_t plain_data_len; + pj_size_t data_len; + unsigned flags; union { - char content[1]; - const char *ptr; + char content[1]; + const char *ptr; } data; } write_data_t; @@ -72,10 +72,10 @@ typedef struct write_data_t { * Structure of SSL socket write buffer (circular buffer). */ typedef struct send_buf_t { - char *buf; - pj_size_t max_len; - char *start; - pj_size_t len; + char *buf; + pj_size_t max_len; + char *start; + pj_size_t len; } send_buf_t; /* Circular buffer object */ @@ -94,49 +94,49 @@ typedef struct circ_buf_t { */ struct pj_ssl_sock_t { - pj_pool_t *pool; - pj_pool_t *info_pool; /* this is for certificate chain - * information allocation. Don't use for - * other purposes. */ - pj_ssl_sock_t *parent; - pj_ssl_sock_param param; - pj_ssl_sock_param newsock_param; - pj_ssl_cert_t *cert; + pj_pool_t *pool; + pj_pool_t *info_pool; /* this is for certificate chain + * information allocation. Don't use for + * other purposes. */ + pj_ssl_sock_t *parent; + pj_ssl_sock_param param; + pj_ssl_sock_param newsock_param; + pj_ssl_cert_t *cert; - pj_ssl_cert_info local_cert_info; - pj_ssl_cert_info remote_cert_info; + pj_ssl_cert_info local_cert_info; + pj_ssl_cert_info remote_cert_info; - pj_bool_t is_server; - enum ssl_state ssl_state; - pj_ioqueue_op_key_t handshake_op_key; - pj_ioqueue_op_key_t shutdown_op_key; - pj_timer_entry timer; - pj_status_t verify_status; + pj_bool_t is_server; + enum ssl_state ssl_state; + pj_ioqueue_op_key_t handshake_op_key; + pj_ioqueue_op_key_t shutdown_op_key; + pj_timer_entry timer; + pj_status_t verify_status; - pj_bool_t is_closing; - unsigned long last_err; + pj_bool_t is_closing; + unsigned long last_err; - pj_sock_t sock; - pj_activesock_t *asock; + pj_sock_t sock; + pj_activesock_t *asock; - pj_sockaddr local_addr; - pj_sockaddr rem_addr; - int addr_len; + pj_sockaddr local_addr; + pj_sockaddr rem_addr; + int addr_len; - pj_bool_t read_started; - pj_size_t read_size; - pj_uint32_t read_flags; - void **asock_rbuf; - read_data_t *ssock_rbuf; - - write_data_t write_pending;/* list of pending write to ssl */ - write_data_t write_pending_empty; /* cache for write_pending */ - pj_bool_t flushing_write_pend; /* flag of flushing is ongoing*/ - send_buf_t send_buf; - write_data_t send_buf_pending; /* send buffer is full but some - * data is queuing in wbio. */ - write_data_t send_pending; /* list of pending write to network */ - pj_lock_t *write_mutex; /* protect write BIO and send_buf */ + pj_bool_t read_started; + pj_size_t read_size; + pj_uint32_t read_flags; + void **asock_rbuf; + read_data_t *ssock_rbuf; + + write_data_t write_pending;/* list of pending write to ssl */ + write_data_t write_pending_empty; /* cache for write_pending */ + pj_bool_t flushing_write_pend; /* flag of flushing is ongoing*/ + send_buf_t send_buf; + write_data_t send_buf_pending; /* send buffer is full but some + * data is queuing in wbio. */ + write_data_t send_pending; /* list of pending write to network */ + pj_lock_t *write_mutex; /* protect write BIO and send_buf */ circ_buf_t circ_buf_input; pj_lock_t *circ_buf_input_mutex; @@ -167,14 +167,14 @@ struct pj_ssl_cert_t static unsigned ssl_cipher_num; static struct ssl_ciphers_t { pj_ssl_cipher id; - const char *name; + const char *name; } ssl_ciphers[PJ_SSL_SOCK_MAX_CIPHERS]; /* ssl available curves */ static unsigned ssl_curves_num; static struct ssl_curves_t { pj_ssl_curve id; - const char *name; + const char *name; } ssl_curves[PJ_SSL_SOCK_MAX_CURVES]; /* @@ -186,7 +186,7 @@ static struct ssl_curves_t { static pj_bool_t io_empty(pj_ssl_sock_t *ssock, circ_buf_t *cb); static pj_size_t io_size(pj_ssl_sock_t *ssock, circ_buf_t *cb); static void io_read(pj_ssl_sock_t *ssock, circ_buf_t *cb, - pj_uint8_t *dst, pj_size_t len); + pj_uint8_t *dst, pj_size_t len); static pj_status_t io_write(pj_ssl_sock_t *ssock, circ_buf_t *cb, const pj_uint8_t *src, pj_size_t len); @@ -220,7 +220,7 @@ inline static pj_size_t io_size(pj_ssl_sock_t *ssock, circ_buf_t *cb) } inline static void io_reset(pj_ssl_sock_t *ssock, circ_buf_t *cb) {} inline static void io_read(pj_ssl_sock_t *ssock, circ_buf_t *cb, - pj_uint8_t *dst, pj_size_t len) + pj_uint8_t *dst, pj_size_t len) { return circ_read(cb, dst, len); } @@ -261,34 +261,34 @@ static pj_status_t ssl_do_handshake(pj_ssl_sock_t *ssock); static pj_status_t ssl_renegotiate(pj_ssl_sock_t *ssock); static pj_status_t ssl_read(pj_ssl_sock_t *ssock, void *data, int *size); static pj_status_t ssl_write(pj_ssl_sock_t *ssock, const void *data, - pj_ssize_t size, int *nwritten); + pj_ssize_t size, int *nwritten); #ifdef SSL_SOCK_IMP_USE_OWN_NETWORK static void ssl_close_sockets(pj_ssl_sock_t *ssock); static pj_status_t network_send(pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t *size, - unsigned flags); + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t *size, + unsigned flags); static pj_status_t network_start_read(pj_ssl_sock_t *ssock, - unsigned async_count, - unsigned buff_size, - void *readbuf[], - pj_uint32_t flags); + unsigned async_count, + unsigned buff_size, + void *readbuf[], + pj_uint32_t flags); static pj_status_t network_start_accept(pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_sockaddr_t *localaddr, - int addr_len, - const pj_ssl_sock_param *newsock_param); + pj_pool_t *pool, + const pj_sockaddr_t *localaddr, + int addr_len, + const pj_ssl_sock_param *newsock_param); static pj_status_t network_start_connect(pj_ssl_sock_t *ssock, - pj_ssl_start_connect_param *connect_param); + pj_ssl_start_connect_param *connect_param); static pj_status_t network_setup_connection(pj_ssl_sock_t *ssock, - void *connection); + void *connection); static pj_status_t network_get_localaddr(pj_ssl_sock_t *ssock, - pj_sockaddr_t *addr, - int *namelen); + pj_sockaddr_t *addr, + int *namelen); #endif diff --git a/pjlib/src/pj/ssl_sock_ossl.c b/pjlib/src/pj/ssl_sock_ossl.c index a61f945ea0..7d1730236f 100644 --- a/pjlib/src/pj/ssl_sock_ossl.c +++ b/pjlib/src/pj/ssl_sock_ossl.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * @@ -39,7 +38,7 @@ #include "ssl_sock_imp_common.c" -#define THIS_FILE "ssl_sock_ossl.c" +#define THIS_FILE "ssl_sock_ossl.c" /* * Include OpenSSL headers @@ -72,16 +71,16 @@ * exported sessions. */ #ifndef SERVER_SESSION_ID_CONTEXT -# define SERVER_SESSION_ID_CONTEXT 999 +# define SERVER_SESSION_ID_CONTEXT 999 #endif /* Server session timeout duration. Default is 300 sec. */ #define SERVER_SESSION_TIMEOUT 300 #if defined(LIBRESSL_VERSION_NUMBER) -# define USING_LIBRESSL 1 +# define USING_LIBRESSL 1 #else -# define USING_LIBRESSL 0 +# define USING_LIBRESSL 0 #endif #if defined(OPENSSL_IS_BORINGSSL) @@ -97,7 +96,7 @@ #endif #if !USING_LIBRESSL && !defined(OPENSSL_NO_EC) \ - && OPENSSL_VERSION_NUMBER >= 0x1000200fL + && OPENSSL_VERSION_NUMBER >= 0x1000200fL # include @@ -136,10 +135,10 @@ static unsigned get_cid_from_nid(unsigned nid) { unsigned i, cid = 0; for (i=0; i PJ_ARRAY_SIZE(nid_cid_map))) - return 0; + return 0; return nid_cid_map[cid-1]; } @@ -155,21 +154,21 @@ static unsigned get_nid_from_cid(unsigned cid) #endif static void update_certs_info(pj_ssl_sock_t* ssock, - X509_STORE_CTX* ctx, - pj_ssl_cert_info *local_cert_info, - pj_ssl_cert_info *remote_cert_info, - pj_bool_t is_verify); + X509_STORE_CTX* ctx, + pj_ssl_cert_info *local_cert_info, + pj_ssl_cert_info *remote_cert_info, + pj_bool_t is_verify); #if !USING_LIBRESSL && OPENSSL_VERSION_NUMBER >= 0x10100000L -# define OPENSSL_NO_SSL2 /* seems to be removed in 1.1.0 */ -# define M_ASN1_STRING_data(x) ASN1_STRING_get0_data(x) +# define OPENSSL_NO_SSL2 /* seems to be removed in 1.1.0 */ +# define M_ASN1_STRING_data(x) ASN1_STRING_get0_data(x) # define M_ASN1_STRING_length(x) ASN1_STRING_length(x) # if defined(OPENSSL_API_COMPAT) && OPENSSL_API_COMPAT >= 0x10100000L # define X509_get_notBefore(x) X509_get0_notBefore(x) # define X509_get_notAfter(x) X509_get0_notAfter(x) # endif #elif !USING_LIBRESSL -# define SSL_CIPHER_get_id(c) (c)->id +# define SSL_CIPHER_get_id(c) (c)->id # define SSL_set_session(ssl, s) (ssl)->session = (s) # define X509_STORE_CTX_get0_cert(ctx) ((ctx)->cert) #endif @@ -211,51 +210,51 @@ static void update_certs_info(pj_ssl_sock_t* ssock, */ typedef struct ossl_sock_t { - pj_ssl_sock_t base; + pj_ssl_sock_t base; - SSL_CTX *ossl_ctx; - pj_bool_t own_ctx; - SSL *ossl_ssl; - BIO *ossl_rbio; - BIO *ossl_wbio; + SSL_CTX *ossl_ctx; + pj_bool_t own_ctx; + SSL *ossl_ssl; + BIO *ossl_rbio; + BIO *ossl_wbio; } ossl_sock_t; /** * Mapping from OpenSSL error codes to pjlib error space. */ -#define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + \ - PJ_ERRNO_SPACE_SIZE*6) +#define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + \ + PJ_ERRNO_SPACE_SIZE*6) -#define PJ_SSL_ERRNO_SPACE_SIZE PJ_ERRNO_SPACE_SIZE +#define PJ_SSL_ERRNO_SPACE_SIZE PJ_ERRNO_SPACE_SIZE /* Expected maximum value of reason component in OpenSSL error code */ -#define MAX_OSSL_ERR_REASON 1200 +#define MAX_OSSL_ERR_REASON 1200 static char *SSLErrorString (int err) { switch (err) { case SSL_ERROR_NONE: - return "SSL_ERROR_NONE"; + return "SSL_ERROR_NONE"; case SSL_ERROR_ZERO_RETURN: - return "SSL_ERROR_ZERO_RETURN"; + return "SSL_ERROR_ZERO_RETURN"; case SSL_ERROR_WANT_READ: - return "SSL_ERROR_WANT_READ"; + return "SSL_ERROR_WANT_READ"; case SSL_ERROR_WANT_WRITE: - return "SSL_ERROR_WANT_WRITE"; + return "SSL_ERROR_WANT_WRITE"; case SSL_ERROR_WANT_CONNECT: - return "SSL_ERROR_WANT_CONNECT"; + return "SSL_ERROR_WANT_CONNECT"; case SSL_ERROR_WANT_ACCEPT: - return "SSL_ERROR_WANT_ACCEPT"; + return "SSL_ERROR_WANT_ACCEPT"; case SSL_ERROR_WANT_X509_LOOKUP: - return "SSL_ERROR_WANT_X509_LOOKUP"; + return "SSL_ERROR_WANT_X509_LOOKUP"; case SSL_ERROR_SYSCALL: - return "SSL_ERROR_SYSCALL"; + return "SSL_ERROR_SYSCALL"; case SSL_ERROR_SSL: - return "SSL_ERROR_SSL"; + return "SSL_ERROR_SSL"; default: - return "SSL_ERROR_UNKNOWN"; + return "SSL_ERROR_UNKNOWN"; } } @@ -266,89 +265,89 @@ static char *SSLErrorString (int err) char buf[PJ_INET6_ADDRSTRLEN + 10]; \ ERR_error_string_n(err, err_str, sizeof(err_str)); \ PJ_LOG(2,("SSL", "%s (%s): Level: %d err: <%lu> <%s> len: %d peer: %s", \ - msg, action, level, err, err_str, len, \ - (ssock && pj_sockaddr_has_addr(&ssock->rem_addr)? \ - pj_sockaddr_print(&ssock->rem_addr, buf, sizeof(buf), 3):"???")));\ + msg, action, level, err, err_str, len, \ + (ssock && pj_sockaddr_has_addr(&ssock->rem_addr)? \ + pj_sockaddr_print(&ssock->rem_addr, buf, sizeof(buf), 3):"???")));\ } # else #define ERROR_LOG(msg, err, ssock) \ { \ char buf[PJ_INET6_ADDRSTRLEN+10]; \ PJ_LOG(2,("SSL", "%s (%s): Level: %d err: <%lu> <%s-%s-%s> len: %d " \ - "peer: %s", \ - msg, action, level, err, \ - (ERR_lib_error_string(err)? ERR_lib_error_string(err): "???"), \ - (ERR_func_error_string(err)? ERR_func_error_string(err):"???"),\ - (ERR_reason_error_string(err)? \ - ERR_reason_error_string(err): "???"), len, \ - (ssock && pj_sockaddr_has_addr(&ssock->rem_addr)? \ - pj_sockaddr_print(&ssock->rem_addr, buf, sizeof(buf), 3):"???")));\ + "peer: %s", \ + msg, action, level, err, \ + (ERR_lib_error_string(err)? ERR_lib_error_string(err): "???"), \ + (ERR_func_error_string(err)? ERR_func_error_string(err):"???"),\ + (ERR_reason_error_string(err)? \ + ERR_reason_error_string(err): "???"), len, \ + (ssock && pj_sockaddr_has_addr(&ssock->rem_addr)? \ + pj_sockaddr_print(&ssock->rem_addr, buf, sizeof(buf), 3):"???")));\ } # endif static void SSLLogErrors(char * action, int ret, int ssl_err, int len, - pj_ssl_sock_t *ssock) + pj_ssl_sock_t *ssock) { char *ssl_err_str = SSLErrorString(ssl_err); if (!action) { - action = "UNKNOWN"; + action = "UNKNOWN"; } switch (ssl_err) { case SSL_ERROR_SYSCALL: { - unsigned long err2 = ERR_get_error(); - if (err2) { - int level = 0; - while (err2) { - ERROR_LOG("SSL_ERROR_SYSCALL", err2, ssock); - level++; - err2 = ERR_get_error(); - } - } else if (ret == 0) { - /* An EOF was observed that violates the protocol */ - - /* The TLS/SSL handshake was not successful but was shut down - * controlled and by the specifications of the TLS/SSL protocol. - */ - } else if (ret == -1) { - /* BIO error - look for more info in errno... */ - char errStr[250] = ""; - strerror_r(errno, errStr, sizeof(errStr)); - /* for now - continue logging these if they occur.... */ - PJ_LOG(4,("SSL", "BIO error, SSL_ERROR_SYSCALL (%s): " - "errno: <%d> <%s> len: %d", - action, errno, errStr, len)); - } else { - /* ret!=0 & ret!=-1 & nothing on error stack - is this valid??? */ - PJ_LOG(2,("SSL", "SSL_ERROR_SYSCALL (%s) ret: %d len: %d", - action, ret, len)); - } - break; + unsigned long err2 = ERR_get_error(); + if (err2) { + int level = 0; + while (err2) { + ERROR_LOG("SSL_ERROR_SYSCALL", err2, ssock); + level++; + err2 = ERR_get_error(); + } + } else if (ret == 0) { + /* An EOF was observed that violates the protocol */ + + /* The TLS/SSL handshake was not successful but was shut down + * controlled and by the specifications of the TLS/SSL protocol. + */ + } else if (ret == -1) { + /* BIO error - look for more info in errno... */ + char errStr[250] = ""; + strerror_r(errno, errStr, sizeof(errStr)); + /* for now - continue logging these if they occur.... */ + PJ_LOG(4,("SSL", "BIO error, SSL_ERROR_SYSCALL (%s): " + "errno: <%d> <%s> len: %d", + action, errno, errStr, len)); + } else { + /* ret!=0 & ret!=-1 & nothing on error stack - is this valid??? */ + PJ_LOG(2,("SSL", "SSL_ERROR_SYSCALL (%s) ret: %d len: %d", + action, ret, len)); + } + break; } case SSL_ERROR_SSL: { - unsigned long err2 = ERR_get_error(); - int level = 0; + unsigned long err2 = ERR_get_error(); + int level = 0; - while (err2) { - unsigned long next_err; + while (err2) { + unsigned long next_err; - ERROR_LOG("SSL_ERROR_SSL", err2, ssock); - level++; + ERROR_LOG("SSL_ERROR_SSL", err2, ssock); + level++; - do { - next_err = ERR_get_error(); - } while (next_err == err2); - err2 = next_err; - } - break; + do { + next_err = ERR_get_error(); + } while (next_err == err2); + err2 = next_err; + } + break; } default: - PJ_LOG(2,("SSL", "%lu [%s] (%s) ret: %d len: %d", - ssl_err, ssl_err_str, action, ret, len)); - break; + PJ_LOG(2,("SSL", "%lu [%s] (%s) ret: %d len: %d", + ssl_err, ssl_err_str, action, ret, len)); + break; } } @@ -364,7 +363,7 @@ static pj_status_t GET_STATUS_FROM_SSL_ERR(unsigned long err) */ status = ERR_GET_LIB(err)*MAX_OSSL_ERR_REASON + ERR_GET_REASON(err); if (status > PJ_SSL_ERRNO_SPACE_SIZE) - status = ERR_GET_REASON(err); + status = ERR_GET_REASON(err); status += PJ_SSL_ERRNO_START; return status; @@ -372,7 +371,7 @@ static pj_status_t GET_STATUS_FROM_SSL_ERR(unsigned long err) /* err contains ERR_get_error() status */ static pj_status_t STATUS_FROM_SSL_ERR(char *action, pj_ssl_sock_t *ssock, - unsigned long err) + unsigned long err) { int level = 0; int len = 0; //dummy @@ -382,30 +381,30 @@ static pj_status_t STATUS_FROM_SSL_ERR(char *action, pj_ssl_sock_t *ssock, /* General SSL error, dig more from OpenSSL error queue */ if (err == SSL_ERROR_SSL) { - err = ERR_get_error(); - ERROR_LOG("STATUS_FROM_SSL_ERR", err, ssock); + err = ERR_get_error(); + ERROR_LOG("STATUS_FROM_SSL_ERR", err, ssock); } if (ssock) - ssock->last_err = err; + ssock->last_err = err; return GET_STATUS_FROM_SSL_ERR(err); } /* err contains SSL_get_error() status */ static pj_status_t STATUS_FROM_SSL_ERR2(char *action, pj_ssl_sock_t *ssock, - int ret, int err, int len) + int ret, int err, int len) { unsigned long ssl_err = err; if (err == SSL_ERROR_SSL) { - ssl_err = ERR_peek_error(); + ssl_err = ERR_peek_error(); } /* Dig for more from OpenSSL error queue */ SSLLogErrors(action, ret, err, len, ssock); if (ssock) - ssock->last_err = ssl_err; + ssock->last_err = ssl_err; return GET_STATUS_FROM_SSL_ERR(ssl_err); } @@ -419,43 +418,43 @@ static pj_status_t GET_SSL_STATUS(pj_ssl_sock_t *ssock) * Get error string of OpenSSL. */ static pj_str_t ssl_strerror(pj_status_t status, - char *buf, pj_size_t bufsize) + char *buf, pj_size_t bufsize) { pj_str_t errstr; unsigned long ssl_err = status; if (ssl_err) { - unsigned long l, r; - ssl_err -= PJ_SSL_ERRNO_START; - l = ssl_err / MAX_OSSL_ERR_REASON; - r = ssl_err % MAX_OSSL_ERR_REASON; + unsigned long l, r; + ssl_err -= PJ_SSL_ERRNO_START; + l = ssl_err / MAX_OSSL_ERR_REASON; + r = ssl_err % MAX_OSSL_ERR_REASON; #if USING_BORINGSSL ssl_err = ERR_PACK(l, r); #else - ssl_err = ERR_PACK(l, 0, r); + ssl_err = ERR_PACK(l, 0, r); #endif } #if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0) { - const char *tmp = NULL; - tmp = ERR_reason_error_string(ssl_err); - if (tmp) { - pj_ansi_strncpy(buf, tmp, bufsize); - errstr = pj_str(buf); - return errstr; - } + const char *tmp = NULL; + tmp = ERR_reason_error_string(ssl_err); + if (tmp) { + pj_ansi_strncpy(buf, tmp, bufsize); + errstr = pj_str(buf); + return errstr; + } } -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ errstr.ptr = buf; errstr.slen = pj_ansi_snprintf(buf, bufsize, - "Unknown OpenSSL error %lu", - ssl_err); + "Unknown OpenSSL error %lu", + ssl_err); if (errstr.slen < 1 || errstr.slen >= (int)bufsize) - errstr.slen = bufsize - 1; + errstr.slen = bufsize - 1; return errstr; } @@ -502,7 +501,7 @@ static pj_size_t io_size(pj_ssl_sock_t *ssock, circ_buf_t *cb) } static void io_read(pj_ssl_sock_t *ssock, circ_buf_t *cb, - pj_uint8_t *dst, pj_size_t len) + pj_uint8_t *dst, pj_size_t len) { ossl_sock_t *ossock = (ossl_sock_t *)ssock; char *data; @@ -540,8 +539,8 @@ static int sslsock_idx; PJ_SSL_SOCK_OSSL_USE_THREAD_CB != 0 && OPENSSL_VERSION_NUMBER < 0x10100000L /* Thread lock pool.*/ -static pj_caching_pool cp; -static pj_pool_t *lock_pool; +static pj_caching_pool cp; +static pj_pool_t *lock_pool; /* OpenSSL locking list. */ static pj_lock_t **ossl_locks; @@ -675,15 +674,15 @@ static pj_status_t init_openssl(void) pj_status_t status; if (openssl_init_count) - return PJ_SUCCESS; + return PJ_SUCCESS; openssl_init_count = 1; PJ_LOG(4, (THIS_FILE, "OpenSSL version : %x", OPENSSL_VERSION_NUMBER)); /* Register error subsystem */ status = pj_register_strerror(PJ_SSL_ERRNO_START, - PJ_SSL_ERRNO_SPACE_SIZE, - &ssl_strerror); + PJ_SSL_ERRNO_SPACE_SIZE, + &ssl_strerror); pj_assert(status == PJ_SUCCESS); /* Init OpenSSL lib */ @@ -700,177 +699,177 @@ static pj_status_t init_openssl(void) /* Init available ciphers */ if (ssl_cipher_num == 0 || ssl_curves_num == 0) { - SSL_METHOD *meth = NULL; - SSL_CTX *ctx; - SSL *ssl; - STACK_OF(SSL_CIPHER) *sk_cipher; - SSL_SESSION *ssl_sess; - unsigned i, n; - int nid; - const char *cname; + SSL_METHOD *meth = NULL; + SSL_CTX *ctx; + SSL *ssl; + STACK_OF(SSL_CIPHER) *sk_cipher; + SSL_SESSION *ssl_sess; + unsigned i, n; + int nid; + const char *cname; #if (USING_LIBRESSL && LIBRESSL_VERSION_NUMBER < 0x2020100fL)\ || OPENSSL_VERSION_NUMBER < 0x10100000L - meth = (SSL_METHOD*)SSLv23_server_method(); - if (!meth) - meth = (SSL_METHOD*)TLSv1_server_method(); + meth = (SSL_METHOD*)SSLv23_server_method(); + if (!meth) + meth = (SSL_METHOD*)TLSv1_server_method(); #ifndef OPENSSL_NO_SSL3_METHOD - if (!meth) - meth = (SSL_METHOD*)SSLv3_server_method(); + if (!meth) + meth = (SSL_METHOD*)SSLv3_server_method(); #endif #ifndef OPENSSL_NO_SSL2 - if (!meth) - meth = (SSL_METHOD*)SSLv2_server_method(); + if (!meth) + meth = (SSL_METHOD*)SSLv2_server_method(); #endif #else - /* Specific version methods are deprecated in 1.1.0 */ - meth = (SSL_METHOD*)TLS_method(); + /* Specific version methods are deprecated in 1.1.0 */ + meth = (SSL_METHOD*)TLS_method(); #endif - pj_assert(meth); + pj_assert(meth); - ctx=SSL_CTX_new(meth); - SSL_CTX_set_cipher_list(ctx, "ALL:COMPLEMENTOFALL"); + ctx=SSL_CTX_new(meth); + SSL_CTX_set_cipher_list(ctx, "ALL:COMPLEMENTOFALL"); - ssl = SSL_new(ctx); + ssl = SSL_new(ctx); - sk_cipher = SSL_get_ciphers(ssl); + sk_cipher = SSL_get_ciphers(ssl); - n = sk_SSL_CIPHER_num(sk_cipher); - if (n > PJ_ARRAY_SIZE(ssl_ciphers) - ADDITIONAL_CIPHER_COUNT) - n = PJ_ARRAY_SIZE(ssl_ciphers) - ADDITIONAL_CIPHER_COUNT; + n = sk_SSL_CIPHER_num(sk_cipher); + if (n > PJ_ARRAY_SIZE(ssl_ciphers) - ADDITIONAL_CIPHER_COUNT) + n = PJ_ARRAY_SIZE(ssl_ciphers) - ADDITIONAL_CIPHER_COUNT; - for (i = 0; i < n; ++i) { - const SSL_CIPHER *c; - c = sk_SSL_CIPHER_value(sk_cipher,i); - ssl_ciphers[i].id = (pj_ssl_cipher) - (pj_uint32_t)SSL_CIPHER_get_id(c) & - 0x00FFFFFF; - ssl_ciphers[i].name = SSL_CIPHER_get_name(c); - } + for (i = 0; i < n; ++i) { + const SSL_CIPHER *c; + c = sk_SSL_CIPHER_value(sk_cipher,i); + ssl_ciphers[i].id = (pj_ssl_cipher) + (pj_uint32_t)SSL_CIPHER_get_id(c) & + 0x00FFFFFF; + ssl_ciphers[i].name = SSL_CIPHER_get_name(c); + } - /* Add cipher aliases not returned from SSL_get_ciphers() */ - for (i = 0; i < ADDITIONAL_CIPHER_COUNT; ++i) { - ssl_ciphers[n++] = ADDITIONAL_CIPHERS[i]; - } - ssl_cipher_num = n; + /* Add cipher aliases not returned from SSL_get_ciphers() */ + for (i = 0; i < ADDITIONAL_CIPHER_COUNT; ++i) { + ssl_ciphers[n++] = ADDITIONAL_CIPHERS[i]; + } + ssl_cipher_num = n; #if USING_BORINGSSL - ssl_sess = SSL_SESSION_new(ctx); + ssl_sess = SSL_SESSION_new(ctx); #else - ssl_sess = SSL_SESSION_new(); + ssl_sess = SSL_SESSION_new(); #endif - SSL_set_session(ssl, ssl_sess); + SSL_set_session(ssl, ssl_sess); #if !USING_LIBRESSL && !defined(OPENSSL_NO_EC) \ && OPENSSL_VERSION_NUMBER >= 0x1000200fL #if OPENSSL_VERSION_NUMBER >= 0x1010100fL - ssl_curves_num = EC_get_builtin_curves(NULL, 0); + ssl_curves_num = EC_get_builtin_curves(NULL, 0); #else #if USING_BORINGSSL ssl_curves_num = SSL_get_curve_id(ssl); #else - ssl_curves_num = SSL_get_shared_curve(ssl,-1); + ssl_curves_num = SSL_get_shared_curve(ssl,-1); #endif - if (ssl_curves_num > PJ_ARRAY_SIZE(ssl_curves)) - ssl_curves_num = PJ_ARRAY_SIZE(ssl_curves); + if (ssl_curves_num > PJ_ARRAY_SIZE(ssl_curves)) + ssl_curves_num = PJ_ARRAY_SIZE(ssl_curves); #endif - if( ssl_curves_num > 0 ) { + if( ssl_curves_num > 0 ) { #if OPENSSL_VERSION_NUMBER >= 0x1010100fL - EC_builtin_curve * curves = NULL; + EC_builtin_curve * curves = NULL; - curves = OPENSSL_malloc((int)sizeof(*curves) * ssl_curves_num); - if (!EC_get_builtin_curves(curves, ssl_curves_num)) { - OPENSSL_free(curves); - curves = NULL; - ssl_curves_num = 0; - } + curves = OPENSSL_malloc((int)sizeof(*curves) * ssl_curves_num); + if (!EC_get_builtin_curves(curves, ssl_curves_num)) { + OPENSSL_free(curves); + curves = NULL; + ssl_curves_num = 0; + } - n = ssl_curves_num; - ssl_curves_num = 0; + n = ssl_curves_num; + ssl_curves_num = 0; - for (i = 0; i < n; i++) { - nid = curves[i].nid; + for (i = 0; i < n; i++) { + nid = curves[i].nid; - if ( 0 != get_cid_from_nid(nid) ) { - cname = OBJ_nid2sn(nid); + if ( 0 != get_cid_from_nid(nid) ) { + cname = OBJ_nid2sn(nid); - if (!cname) - cname = OBJ_nid2sn(nid); + if (!cname) + cname = OBJ_nid2sn(nid); - if (cname) { - ssl_curves[ssl_curves_num].id = get_cid_from_nid(nid); - ssl_curves[ssl_curves_num].name = cname; + if (cname) { + ssl_curves[ssl_curves_num].id = get_cid_from_nid(nid); + ssl_curves[ssl_curves_num].name = cname; - ssl_curves_num++; + ssl_curves_num++; - if (ssl_curves_num >= PJ_SSL_SOCK_MAX_CURVES ) - break; - } - } - } + if (ssl_curves_num >= PJ_SSL_SOCK_MAX_CURVES ) + break; + } + } + } - if(curves) - OPENSSL_free(curves); + if(curves) + OPENSSL_free(curves); #else - for (i = 0; i < ssl_curves_num; i++) { + for (i = 0; i < ssl_curves_num; i++) { #if USING_BORINGSSL nid = SSL_get_curve_id(ssl); #else - nid = SSL_get_shared_curve(ssl, i); + nid = SSL_get_shared_curve(ssl, i); #endif - if (nid & TLSEXT_nid_unknown) { - cname = "curve unknown"; - nid &= 0xFFFF; - } else { - cname = EC_curve_nid2nist(nid); - if (!cname) - cname = OBJ_nid2sn(nid); - } - - ssl_curves[i].id = get_cid_from_nid(nid); - ssl_curves[i].name = cname; - } + if (nid & TLSEXT_nid_unknown) { + cname = "curve unknown"; + nid &= 0xFFFF; + } else { + cname = EC_curve_nid2nist(nid); + if (!cname) + cname = OBJ_nid2sn(nid); + } + + ssl_curves[i].id = get_cid_from_nid(nid); + ssl_curves[i].name = cname; + } #endif - } + } #else - PJ_UNUSED_ARG(nid); - PJ_UNUSED_ARG(cname); - ssl_curves_num = 0; + PJ_UNUSED_ARG(nid); + PJ_UNUSED_ARG(cname); + ssl_curves_num = 0; #endif - SSL_free(ssl); + SSL_free(ssl); - /* On OpenSSL 1.1.1, omitting SSL_SESSION_free() will cause - * memory leak (e.g: as reported by Address Sanitizer). But using - * SSL_SESSION_free() may cause crash (due to double free?) on 1.0.x. - * As OpenSSL docs specifies to not calling SSL_SESSION_free() after - * SSL_free(), perhaps it is safer to obey this, the leak amount seems - * to be relatively small (<500 bytes) and should occur once only in - * the library lifetime. + /* On OpenSSL 1.1.1, omitting SSL_SESSION_free() will cause + * memory leak (e.g: as reported by Address Sanitizer). But using + * SSL_SESSION_free() may cause crash (due to double free?) on 1.0.x. + * As OpenSSL docs specifies to not calling SSL_SESSION_free() after + * SSL_free(), perhaps it is safer to obey this, the leak amount seems + * to be relatively small (<500 bytes) and should occur once only in + * the library lifetime. #if OPENSSL_VERSION_NUMBER >= 0x10101000L - SSL_SESSION_free(ssl_sess); + SSL_SESSION_free(ssl_sess); #endif - */ + */ - SSL_CTX_free(ctx); + SSL_CTX_free(ctx); } /* Create OpenSSL application data index for SSL socket */ sslsock_idx = SSL_get_ex_new_index(0, "SSL socket", NULL, NULL, NULL); if (sslsock_idx == -1) { - status = STATUS_FROM_SSL_ERR2("Init", NULL, -1, ERR_get_error(), 0); - PJ_LOG(1,(THIS_FILE, - "Fatal error: failed to get application data index for " - "SSL socket")); - return status; + status = STATUS_FROM_SSL_ERR2("Init", NULL, -1, ERR_get_error(), 0); + PJ_LOG(1,(THIS_FILE, + "Fatal error: failed to get application data index for " + "SSL socket")); + return status; } #if defined(PJ_SSL_SOCK_OSSL_USE_THREAD_CB) && \ @@ -898,7 +897,7 @@ static int password_cb(char *buf, int num, int rwflag, void *user_data) PJ_UNUSED_ARG(rwflag); if(num < cert->privkey_pass.slen) - return 0; + return 0; pj_memcpy(buf, cert->privkey_pass.ptr, cert->privkey_pass.slen); return (int)cert->privkey_pass.slen; @@ -919,53 +918,53 @@ static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx) /* Get SSL instance */ ossl_ssl = X509_STORE_CTX_get_ex_data(x509_ctx, - SSL_get_ex_data_X509_STORE_CTX_idx()); + SSL_get_ex_data_X509_STORE_CTX_idx()); if (!ossl_ssl) { - PJ_LOG(1,(THIS_FILE, - "SSL verification callback failed to get SSL instance")); - goto on_return; + PJ_LOG(1,(THIS_FILE, + "SSL verification callback failed to get SSL instance")); + goto on_return; } /* Get SSL socket instance */ ssock = SSL_get_ex_data(ossl_ssl, sslsock_idx); if (!ssock) { - /* SSL socket may have been destroyed */ - PJ_LOG(1,(THIS_FILE, - "SSL verification callback failed to get SSL socket " - "instance (sslsock_idx=%d).", sslsock_idx)); - goto on_return; + /* SSL socket may have been destroyed */ + PJ_LOG(1,(THIS_FILE, + "SSL verification callback failed to get SSL socket " + "instance (sslsock_idx=%d).", sslsock_idx)); + goto on_return; } if (ssock->param.cb.on_verify_cb) { - update_certs_info(ssock, x509_ctx, &ssock->local_cert_info, - &ssock->remote_cert_info, PJ_TRUE); - preverify_ok = (*ssock->param.cb.on_verify_cb)(ssock, - ssock->is_server); + update_certs_info(ssock, x509_ctx, &ssock->local_cert_info, + &ssock->remote_cert_info, PJ_TRUE); + preverify_ok = (*ssock->param.cb.on_verify_cb)(ssock, + ssock->is_server); - goto on_return; + goto on_return; } /* Store verification status */ err = X509_STORE_CTX_get_error(x509_ctx); switch (err) { case X509_V_OK: - break; + break; case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: - ssock->verify_status |= PJ_SSL_CERT_EISSUER_NOT_FOUND; - break; + ssock->verify_status |= PJ_SSL_CERT_EISSUER_NOT_FOUND; + break; case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: - ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT; - break; + ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT; + break; case X509_V_ERR_CERT_NOT_YET_VALID: case X509_V_ERR_CERT_HAS_EXPIRED: - ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD; - break; + ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD; + break; case X509_V_ERR_UNABLE_TO_GET_CRL: case X509_V_ERR_CRL_NOT_YET_VALID: @@ -974,15 +973,15 @@ static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx) case X509_V_ERR_CRL_SIGNATURE_FAILURE: case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: - ssock->verify_status |= PJ_SSL_CERT_ECRL_FAILURE; - break; + ssock->verify_status |= PJ_SSL_CERT_ECRL_FAILURE; + break; case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case X509_V_ERR_CERT_UNTRUSTED: case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: - ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED; - break; + ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED; + break; case X509_V_ERR_CERT_SIGNATURE_FAILURE: case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: @@ -990,36 +989,36 @@ static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx) case X509_V_ERR_AKID_SKID_MISMATCH: case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: case X509_V_ERR_KEYUSAGE_NO_CERTSIGN: - ssock->verify_status |= PJ_SSL_CERT_EISSUER_MISMATCH; - break; + ssock->verify_status |= PJ_SSL_CERT_EISSUER_MISMATCH; + break; case X509_V_ERR_CERT_REVOKED: - ssock->verify_status |= PJ_SSL_CERT_EREVOKED; - break; + ssock->verify_status |= PJ_SSL_CERT_EREVOKED; + break; case X509_V_ERR_INVALID_PURPOSE: case X509_V_ERR_CERT_REJECTED: case X509_V_ERR_INVALID_CA: - ssock->verify_status |= PJ_SSL_CERT_EINVALID_PURPOSE; - break; + ssock->verify_status |= PJ_SSL_CERT_EINVALID_PURPOSE; + break; case X509_V_ERR_CERT_CHAIN_TOO_LONG: /* not really used */ case X509_V_ERR_PATH_LENGTH_EXCEEDED: - ssock->verify_status |= PJ_SSL_CERT_ECHAIN_TOO_LONG; - break; + ssock->verify_status |= PJ_SSL_CERT_ECHAIN_TOO_LONG; + break; /* Unknown errors */ case X509_V_ERR_OUT_OF_MEM: default: - ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN; - break; + ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN; + break; } /* When verification is not requested just return ok here, however * application can still get the verification status. */ if (PJ_FALSE == ssock->param.verify_peer) - preverify_ok = 1; + preverify_ok = 1; on_return: return preverify_ok; @@ -1059,24 +1058,24 @@ static int xname_cmp(const X509_NAME **a, const X509_NAME **b) { static void set_option(const pj_ssl_sock_t* ssock, SSL_CTX* ctx) { unsigned long options = SSL_OP_CIPHER_SERVER_PREFERENCE | #if !defined(OPENSSL_NO_ECDH) && OPENSSL_VERSION_NUMBER >= 0x10000000L - SSL_OP_SINGLE_ECDH_USE | + SSL_OP_SINGLE_ECDH_USE | #endif - SSL_OP_SINGLE_DH_USE; + SSL_OP_SINGLE_DH_USE; options = SSL_CTX_set_options(ctx, options); PJ_LOG(4, (ssock->pool->obj_name, "SSL DH " - "initialized, PFS cipher-suites enabled")); + "initialized, PFS cipher-suites enabled")); } static void set_dh_use_option(BIO *bio, const pj_ssl_sock_t* ssock, - const pj_str_t *pass, SSL_CTX* ctx) + const pj_str_t *pass, SSL_CTX* ctx) { #if OPENSSL_VERSION_NUMBER < 0x30000000L DH* dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); if (dh != NULL) { - if (SSL_CTX_set_tmp_dh(ctx, dh)) { - set_option(ssock, ctx); - } - DH_free(dh); + if (SSL_CTX_set_tmp_dh(ctx, dh)) { + set_option(ssock, ctx); + } + DH_free(dh); } PJ_UNUSED_ARG(pass); #else @@ -1087,20 +1086,20 @@ static void set_dh_use_option(BIO *bio, const pj_ssl_sock_t* ssock, const char* keytype = NULL; dctx = OSSL_DECODER_CTX_new_for_pkey(&dh_pkey, format, structure, keytype, - 0, NULL, NULL); + 0, NULL, NULL); if (dctx != NULL) { - if (pass->slen) { - OSSL_DECODER_CTX_set_passphrase(dctx, - (const unsigned char*)pass->ptr, - pass->slen); - } - - if (OSSL_DECODER_from_bio(dctx, bio)) { - if (SSL_CTX_set0_tmp_dh_pkey(ctx, dh_pkey)) { - set_option(ssock, ctx); - } - } - OSSL_DECODER_CTX_free(dctx); + if (pass->slen) { + OSSL_DECODER_CTX_set_passphrase(dctx, + (const unsigned char*)pass->ptr, + pass->slen); + } + + if (OSSL_DECODER_from_bio(dctx, bio)) { + if (SSL_CTX_set0_tmp_dh_pkey(ctx, dh_pkey)) { + set_option(ssock, ctx); + } + } + OSSL_DECODER_CTX_free(dctx); } #endif } @@ -1119,7 +1118,7 @@ static pj_status_t init_ossl_ctx(pj_ssl_sock_t *ssock) pj_status_t status; if (ssock->param.proto == PJ_SSL_SOCK_PROTO_DEFAULT) - ssock->param.proto = PJ_SSL_SOCK_PROTO_SSL23; + ssock->param.proto = PJ_SSL_SOCK_PROTO_SSL23; /* Determine SSL method to use */ /* Specific version methods are deprecated since 1.1.0 */ @@ -1127,397 +1126,397 @@ static pj_status_t init_ossl_ctx(pj_ssl_sock_t *ssock) || OPENSSL_VERSION_NUMBER < 0x10100000L switch (ssock->param.proto) { case PJ_SSL_SOCK_PROTO_TLS1: - ssl_method = (SSL_METHOD*)TLSv1_method(); - break; + ssl_method = (SSL_METHOD*)TLSv1_method(); + break; #ifndef OPENSSL_NO_SSL2 case PJ_SSL_SOCK_PROTO_SSL2: - ssl_method = (SSL_METHOD*)SSLv2_method(); - break; + ssl_method = (SSL_METHOD*)SSLv2_method(); + break; #endif #ifndef OPENSSL_NO_SSL3_METHOD case PJ_SSL_SOCK_PROTO_SSL3: - ssl_method = (SSL_METHOD*)SSLv3_method(); + ssl_method = (SSL_METHOD*)SSLv3_method(); #endif - break; + break; } #endif if (!ssl_method) { #if (USING_LIBRESSL && LIBRESSL_VERSION_NUMBER < 0x2020100fL)\ || OPENSSL_VERSION_NUMBER < 0x10100000L - ssl_method = (SSL_METHOD*)SSLv23_method(); + ssl_method = (SSL_METHOD*)SSLv23_method(); #else - ssl_method = (SSL_METHOD*)TLS_method(); + ssl_method = (SSL_METHOD*)TLS_method(); #endif #ifdef SSL_OP_NO_SSLv2 - /** Check if SSLv2 is enabled */ - ssl_opt |= ((ssock->param.proto & PJ_SSL_SOCK_PROTO_SSL2)==0)? - SSL_OP_NO_SSLv2:0; + /** Check if SSLv2 is enabled */ + ssl_opt |= ((ssock->param.proto & PJ_SSL_SOCK_PROTO_SSL2)==0)? + SSL_OP_NO_SSLv2:0; #endif #ifdef SSL_OP_NO_SSLv3 - /** Check if SSLv3 is enabled */ - ssl_opt |= ((ssock->param.proto & PJ_SSL_SOCK_PROTO_SSL3)==0)? - SSL_OP_NO_SSLv3:0; + /** Check if SSLv3 is enabled */ + ssl_opt |= ((ssock->param.proto & PJ_SSL_SOCK_PROTO_SSL3)==0)? + SSL_OP_NO_SSLv3:0; #endif #ifdef SSL_OP_NO_TLSv1 - /** Check if TLSv1 is enabled */ - ssl_opt |= ((ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1)==0)? - SSL_OP_NO_TLSv1:0; + /** Check if TLSv1 is enabled */ + ssl_opt |= ((ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1)==0)? + SSL_OP_NO_TLSv1:0; #endif #ifdef SSL_OP_NO_TLSv1_1 - /** Check if TLSv1_1 is enabled */ - ssl_opt |= ((ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_1)==0)? - SSL_OP_NO_TLSv1_1:0; + /** Check if TLSv1_1 is enabled */ + ssl_opt |= ((ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_1)==0)? + SSL_OP_NO_TLSv1_1:0; #endif #ifdef SSL_OP_NO_TLSv1_2 - /** Check if TLSv1_2 is enabled */ - ssl_opt |= ((ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_2)==0)? - SSL_OP_NO_TLSv1_2:0; + /** Check if TLSv1_2 is enabled */ + ssl_opt |= ((ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_2)==0)? + SSL_OP_NO_TLSv1_2:0; #endif #ifdef SSL_OP_NO_TLSv1_3 - /** Check if TLSv1_3 is enabled */ - ssl_opt |= ((ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_3)==0)? - SSL_OP_NO_TLSv1_3:0; + /** Check if TLSv1_3 is enabled */ + ssl_opt |= ((ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_3)==0)? + SSL_OP_NO_TLSv1_3:0; #endif } ossock->ossl_ctx = ctx = SSL_CTX_new(ssl_method); if (ctx == NULL) { - return GET_SSL_STATUS(ssock); + return GET_SSL_STATUS(ssock); } #if OPENSSL_VERSION_NUMBER >= 0x30000000L if (ssock->param.proto <= PJ_SSL_SOCK_PROTO_TLS1_1) { /* TLS 1.0, TLS 1.1 no longer working at the default security - * level of 1 and instead requires security level 0. */ - SSL_CTX_set_security_level(ossock->ossl_ctx, 0); + * level of 1 and instead requires security level 0. */ + SSL_CTX_set_security_level(ossock->ossl_ctx, 0); } #endif if (ssock->is_server) { - unsigned int sid_ctx = SERVER_SESSION_ID_CONTEXT; + unsigned int sid_ctx = SERVER_SESSION_ID_CONTEXT; #if SERVER_DISABLE_SESSION_TICKETS - /* Disable session tickets for TLSv1.2 and below. */ - ssl_opt |= SSL_OP_NO_TICKET; + /* Disable session tickets for TLSv1.2 and below. */ + ssl_opt |= SSL_OP_NO_TICKET; #ifdef SSL_CTX_set_num_tickets - /* Set the number of TLSv1.3 session tickets issued to 0. */ - SSL_CTX_set_num_tickets(ctx, 0); + /* Set the number of TLSv1.3 session tickets issued to 0. */ + SSL_CTX_set_num_tickets(ctx, 0); #endif #endif - SSL_CTX_set_timeout(ctx, SERVER_SESSION_TIMEOUT); - if (!SSL_CTX_set_session_id_context(ctx, - (const unsigned char *)&sid_ctx, sizeof(sid_ctx))) - { + SSL_CTX_set_timeout(ctx, SERVER_SESSION_TIMEOUT); + if (!SSL_CTX_set_session_id_context(ctx, + (const unsigned char *)&sid_ctx, sizeof(sid_ctx))) + { PJ_LOG(1, (THIS_FILE, "Warning! Unable to set server session id " - "context. Session reuse will not work.")); - } + "context. Session reuse will not work.")); + } } if (ssl_opt) - SSL_CTX_set_options(ctx, ssl_opt); + SSL_CTX_set_options(ctx, ssl_opt); /* Set cipher list */ status = set_cipher_list(ssock); if (status != PJ_SUCCESS) { - SSL_CTX_free(ctx); - ossock->ossl_ctx = NULL; + SSL_CTX_free(ctx); + ossock->ossl_ctx = NULL; return status; } /* Apply credentials */ if (cert) { - /* Load CA list if one is specified. */ - if (cert->CA_file.slen || cert->CA_path.slen) { - - rc = SSL_CTX_load_verify_locations( - ctx, - cert->CA_file.slen == 0 ? NULL : cert->CA_file.ptr, - cert->CA_path.slen == 0 ? NULL : cert->CA_path.ptr); - - if (rc != 1) { - status = GET_SSL_STATUS(ssock); - if (cert->CA_file.slen) { - PJ_PERROR(1,(ssock->pool->obj_name, status, - "Error loading CA list file '%s'", - cert->CA_file.ptr)); - } - if (cert->CA_path.slen) { - PJ_PERROR(1,(ssock->pool->obj_name, status, - "Error loading CA path '%s'", - cert->CA_path.ptr)); - } - SSL_CTX_free(ctx); - ossock->ossl_ctx = NULL; - return status; - } else { - PJ_LOG(4,(ssock->pool->obj_name, - "CA certificates loaded from '%s%s%s'", - cert->CA_file.ptr, - ((cert->CA_file.slen && cert->CA_path.slen)? - " + ":""), - cert->CA_path.ptr)); - } - } + /* Load CA list if one is specified. */ + if (cert->CA_file.slen || cert->CA_path.slen) { + + rc = SSL_CTX_load_verify_locations( + ctx, + cert->CA_file.slen == 0 ? NULL : cert->CA_file.ptr, + cert->CA_path.slen == 0 ? NULL : cert->CA_path.ptr); + + if (rc != 1) { + status = GET_SSL_STATUS(ssock); + if (cert->CA_file.slen) { + PJ_PERROR(1,(ssock->pool->obj_name, status, + "Error loading CA list file '%s'", + cert->CA_file.ptr)); + } + if (cert->CA_path.slen) { + PJ_PERROR(1,(ssock->pool->obj_name, status, + "Error loading CA path '%s'", + cert->CA_path.ptr)); + } + SSL_CTX_free(ctx); + ossock->ossl_ctx = NULL; + return status; + } else { + PJ_LOG(4,(ssock->pool->obj_name, + "CA certificates loaded from '%s%s%s'", + cert->CA_file.ptr, + ((cert->CA_file.slen && cert->CA_path.slen)? + " + ":""), + cert->CA_path.ptr)); + } + } - /* Set password callback */ - if (cert->privkey_pass.slen) { - SSL_CTX_set_default_passwd_cb(ctx, password_cb); - SSL_CTX_set_default_passwd_cb_userdata(ctx, cert); - } - - - /* Load certificate if one is specified */ - if (cert->cert_file.slen) { - - /* Load certificate chain from file into ctx */ - rc = SSL_CTX_use_certificate_chain_file(ctx, cert->cert_file.ptr); - - if(rc != 1) { - status = GET_SSL_STATUS(ssock); - PJ_PERROR(1,(ssock->pool->obj_name, status, - "Error loading certificate chain file '%s'", - cert->cert_file.ptr)); - SSL_CTX_free(ctx); - ossock->ossl_ctx = NULL; - return status; - } else { - PJ_LOG(4,(ssock->pool->obj_name, - "Certificate chain loaded from '%s'", - cert->cert_file.ptr)); - } - } - - - /* Load private key if one is specified */ - if (cert->privkey_file.slen) { - /* Adds the first private key found in file to ctx */ - rc = SSL_CTX_use_PrivateKey_file(ctx, cert->privkey_file.ptr, - SSL_FILETYPE_PEM); - - if(rc != 1) { - status = GET_SSL_STATUS(ssock); - PJ_PERROR(1,(ssock->pool->obj_name, status, - "Error adding private key from '%s'", - cert->privkey_file.ptr)); - SSL_CTX_free(ctx); - ossock->ossl_ctx = NULL; - return status; - } else { - PJ_LOG(4,(ssock->pool->obj_name, - "Private key loaded from '%s'", - cert->privkey_file.ptr)); - } + /* Set password callback */ + if (cert->privkey_pass.slen) { + SSL_CTX_set_default_passwd_cb(ctx, password_cb); + SSL_CTX_set_default_passwd_cb_userdata(ctx, cert); + } + + + /* Load certificate if one is specified */ + if (cert->cert_file.slen) { + + /* Load certificate chain from file into ctx */ + rc = SSL_CTX_use_certificate_chain_file(ctx, cert->cert_file.ptr); + + if(rc != 1) { + status = GET_SSL_STATUS(ssock); + PJ_PERROR(1,(ssock->pool->obj_name, status, + "Error loading certificate chain file '%s'", + cert->cert_file.ptr)); + SSL_CTX_free(ctx); + ossock->ossl_ctx = NULL; + return status; + } else { + PJ_LOG(4,(ssock->pool->obj_name, + "Certificate chain loaded from '%s'", + cert->cert_file.ptr)); + } + } + + + /* Load private key if one is specified */ + if (cert->privkey_file.slen) { + /* Adds the first private key found in file to ctx */ + rc = SSL_CTX_use_PrivateKey_file(ctx, cert->privkey_file.ptr, + SSL_FILETYPE_PEM); + + if(rc != 1) { + status = GET_SSL_STATUS(ssock); + PJ_PERROR(1,(ssock->pool->obj_name, status, + "Error adding private key from '%s'", + cert->privkey_file.ptr)); + SSL_CTX_free(ctx); + ossock->ossl_ctx = NULL; + return status; + } else { + PJ_LOG(4,(ssock->pool->obj_name, + "Private key loaded from '%s'", + cert->privkey_file.ptr)); + } #if !defined(OPENSSL_NO_DH) - if (ssock->is_server) { - BIO *bio = BIO_new_file(cert->privkey_file.ptr, "r"); - if (bio != NULL) { - set_dh_use_option(bio, ssock, &cert->privkey_pass, ctx); - BIO_free(bio); - } - } + if (ssock->is_server) { + BIO *bio = BIO_new_file(cert->privkey_file.ptr, "r"); + if (bio != NULL) { + set_dh_use_option(bio, ssock, &cert->privkey_pass, ctx); + BIO_free(bio); + } + } #endif - } - - /* Load from buffer. */ - if (cert->cert_buf.slen) { - BIO *cbio; - X509 *xcert = NULL; - - cbio = BIO_new_mem_buf((void*)cert->cert_buf.ptr, - cert->cert_buf.slen); - if (cbio != NULL) { - xcert = PEM_read_bio_X509(cbio, NULL, 0, NULL); - if (xcert != NULL) { - rc = SSL_CTX_use_certificate(ctx, xcert); - if (rc != 1) { - status = GET_SSL_STATUS(ssock); - PJ_PERROR(1,(ssock->pool->obj_name, status, - "Error loading chain certificate from buffer")); - X509_free(xcert); - BIO_free(cbio); - SSL_CTX_free(ctx); - ossock->ossl_ctx = NULL; - return status; - } else { - PJ_LOG(4,(ssock->pool->obj_name, - "Certificate chain loaded from buffer")); - } - X509_free(xcert); - } - BIO_free(cbio); - } - } - - if (cert->CA_buf.slen) { - BIO *cbio = BIO_new_mem_buf((void*)cert->CA_buf.ptr, - cert->CA_buf.slen); - X509_STORE *cts = SSL_CTX_get_cert_store(ctx); - - if (cbio && cts) { - STACK_OF(X509_INFO) *inf = PEM_X509_INFO_read_bio(cbio, NULL, - NULL, NULL); - - if (inf != NULL) { - int i = 0, cnt = 0; - for (; i < sk_X509_INFO_num(inf); i++) { - X509_INFO *itmp = sk_X509_INFO_value(inf, i); - if (!itmp->x509) - continue; - - rc = X509_STORE_add_cert(cts, itmp->x509); - if (rc == 1) { - ++cnt; - } else { + } + + /* Load from buffer. */ + if (cert->cert_buf.slen) { + BIO *cbio; + X509 *xcert = NULL; + + cbio = BIO_new_mem_buf((void*)cert->cert_buf.ptr, + cert->cert_buf.slen); + if (cbio != NULL) { + xcert = PEM_read_bio_X509(cbio, NULL, 0, NULL); + if (xcert != NULL) { + rc = SSL_CTX_use_certificate(ctx, xcert); + if (rc != 1) { + status = GET_SSL_STATUS(ssock); + PJ_PERROR(1,(ssock->pool->obj_name, status, + "Error loading chain certificate from buffer")); + X509_free(xcert); + BIO_free(cbio); + SSL_CTX_free(ctx); + ossock->ossl_ctx = NULL; + return status; + } else { + PJ_LOG(4,(ssock->pool->obj_name, + "Certificate chain loaded from buffer")); + } + X509_free(xcert); + } + BIO_free(cbio); + } + } + + if (cert->CA_buf.slen) { + BIO *cbio = BIO_new_mem_buf((void*)cert->CA_buf.ptr, + cert->CA_buf.slen); + X509_STORE *cts = SSL_CTX_get_cert_store(ctx); + + if (cbio && cts) { + STACK_OF(X509_INFO) *inf = PEM_X509_INFO_read_bio(cbio, NULL, + NULL, NULL); + + if (inf != NULL) { + int i = 0, cnt = 0; + for (; i < sk_X509_INFO_num(inf); i++) { + X509_INFO *itmp = sk_X509_INFO_value(inf, i); + if (!itmp->x509) + continue; + + rc = X509_STORE_add_cert(cts, itmp->x509); + if (rc == 1) { + ++cnt; + } else { #if PJ_LOG_MAX_LEVEL >= 4 - char buf[256]; - PJ_LOG(4,(ssock->pool->obj_name, - "Error adding CA cert: %s", - X509_NAME_oneline( - X509_get_subject_name(itmp->x509), - buf, sizeof(buf)))); + char buf[256]; + PJ_LOG(4,(ssock->pool->obj_name, + "Error adding CA cert: %s", + X509_NAME_oneline( + X509_get_subject_name(itmp->x509), + buf, sizeof(buf)))); #endif - } - } - PJ_LOG(4,(ssock->pool->obj_name, - "CA certificates loaded from buffer (cnt=%d)", - cnt)); - } - sk_X509_INFO_pop_free(inf, X509_INFO_free); - BIO_free(cbio); - } - } - - if (cert->privkey_buf.slen) { - BIO *kbio; - EVP_PKEY *pkey = NULL; - - kbio = BIO_new_mem_buf((void*)cert->privkey_buf.ptr, - cert->privkey_buf.slen); - if (kbio != NULL) { - pkey = PEM_read_bio_PrivateKey(kbio, NULL, &password_cb, - cert); - if (pkey) { - rc = SSL_CTX_use_PrivateKey(ctx, pkey); - if (rc != 1) { - status = GET_SSL_STATUS(ssock); - PJ_PERROR(1,(ssock->pool->obj_name, status, - "Error adding private key from buffer")); - EVP_PKEY_free(pkey); - BIO_free(kbio); - SSL_CTX_free(ctx); - ossock->ossl_ctx = NULL; - return status; - } else { - PJ_LOG(4,(ssock->pool->obj_name, - "Private key loaded from buffer")); - } - EVP_PKEY_free(pkey); - } else { - PJ_LOG(1,(ssock->pool->obj_name, - "Error reading private key from buffer")); - } - - if (ssock->is_server) { - set_dh_use_option(kbio, ssock, &cert->privkey_pass, ctx); - } - BIO_free(kbio); - } - } + } + } + PJ_LOG(4,(ssock->pool->obj_name, + "CA certificates loaded from buffer (cnt=%d)", + cnt)); + } + sk_X509_INFO_pop_free(inf, X509_INFO_free); + BIO_free(cbio); + } + } + + if (cert->privkey_buf.slen) { + BIO *kbio; + EVP_PKEY *pkey = NULL; + + kbio = BIO_new_mem_buf((void*)cert->privkey_buf.ptr, + cert->privkey_buf.slen); + if (kbio != NULL) { + pkey = PEM_read_bio_PrivateKey(kbio, NULL, &password_cb, + cert); + if (pkey) { + rc = SSL_CTX_use_PrivateKey(ctx, pkey); + if (rc != 1) { + status = GET_SSL_STATUS(ssock); + PJ_PERROR(1,(ssock->pool->obj_name, status, + "Error adding private key from buffer")); + EVP_PKEY_free(pkey); + BIO_free(kbio); + SSL_CTX_free(ctx); + ossock->ossl_ctx = NULL; + return status; + } else { + PJ_LOG(4,(ssock->pool->obj_name, + "Private key loaded from buffer")); + } + EVP_PKEY_free(pkey); + } else { + PJ_LOG(1,(ssock->pool->obj_name, + "Error reading private key from buffer")); + } + + if (ssock->is_server) { + set_dh_use_option(kbio, ssock, &cert->privkey_pass, ctx); + } + BIO_free(kbio); + } + } } if (ssock->is_server) { - char *p = NULL; - - /* If certificate file name contains "_rsa.", let's check if there are - * ecc and dsa certificates too. - */ - if (cert && cert->cert_file.slen) { - const pj_str_t RSA = {"_rsa.", 5}; - p = pj_strstr(&cert->cert_file, &RSA); - if (p) p++; /* Skip underscore */ - } - if (p) { - /* Certificate type string length must be exactly 3 */ - enum { CERT_TYPE_LEN = 3 }; - const char* cert_types[] = { "ecc", "dsa" }; - char *cf = cert->cert_file.ptr; - int i; - - /* Check and load ECC & DSA certificates & private keys */ - for (i = 0; i < PJ_ARRAY_SIZE(cert_types); ++i) { - int err; - - pj_memcpy(p, cert_types[i], CERT_TYPE_LEN); - if (!pj_file_exists(cf)) - continue; - - err = SSL_CTX_use_certificate_chain_file(ctx, cf); - if (err == 1) - err = SSL_CTX_use_PrivateKey_file(ctx, cf, - SSL_FILETYPE_PEM); - if (err == 1) { - PJ_LOG(4,(ssock->pool->obj_name, - "Additional certificate '%s' loaded.", cf)); - } else { - PJ_PERROR(1,(ssock->pool->obj_name, GET_SSL_STATUS(ssock), - "Error loading certificate file '%s'", cf)); - ERR_clear_error(); - } - } - - /* Put back original name */ - pj_memcpy(p, "rsa", CERT_TYPE_LEN); - } + char *p = NULL; + + /* If certificate file name contains "_rsa.", let's check if there are + * ecc and dsa certificates too. + */ + if (cert && cert->cert_file.slen) { + const pj_str_t RSA = {"_rsa.", 5}; + p = pj_strstr(&cert->cert_file, &RSA); + if (p) p++; /* Skip underscore */ + } + if (p) { + /* Certificate type string length must be exactly 3 */ + enum { CERT_TYPE_LEN = 3 }; + const char* cert_types[] = { "ecc", "dsa" }; + char *cf = cert->cert_file.ptr; + int i; + + /* Check and load ECC & DSA certificates & private keys */ + for (i = 0; i < PJ_ARRAY_SIZE(cert_types); ++i) { + int err; + + pj_memcpy(p, cert_types[i], CERT_TYPE_LEN); + if (!pj_file_exists(cf)) + continue; + + err = SSL_CTX_use_certificate_chain_file(ctx, cf); + if (err == 1) + err = SSL_CTX_use_PrivateKey_file(ctx, cf, + SSL_FILETYPE_PEM); + if (err == 1) { + PJ_LOG(4,(ssock->pool->obj_name, + "Additional certificate '%s' loaded.", cf)); + } else { + PJ_PERROR(1,(ssock->pool->obj_name, GET_SSL_STATUS(ssock), + "Error loading certificate file '%s'", cf)); + ERR_clear_error(); + } + } + + /* Put back original name */ + pj_memcpy(p, "rsa", CERT_TYPE_LEN); + } #if USING_BORINGSSL if (SSL_CTX_set_mode(ctx, SSL_CTRL_SET_ECDH_AUTO)) { #else #ifndef SSL_CTRL_SET_ECDH_AUTO - #define SSL_CTRL_SET_ECDH_AUTO 94 + #define SSL_CTRL_SET_ECDH_AUTO 94 #endif - /* SSL_CTX_set_ecdh_auto(ctx,on) requires OpenSSL 1.0.2 which wraps: */ - if (SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) { + /* SSL_CTX_set_ecdh_auto(ctx,on) requires OpenSSL 1.0.2 which wraps: */ + if (SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) { #endif - PJ_LOG(4,(ssock->pool->obj_name, "SSL ECDH initialized " - "(automatic), faster PFS ciphers enabled")); + PJ_LOG(4,(ssock->pool->obj_name, "SSL ECDH initialized " + "(automatic), faster PFS ciphers enabled")); #if !defined(OPENSSL_NO_ECDH) && OPENSSL_VERSION_NUMBER >= 0x10000000L && \ - OPENSSL_VERSION_NUMBER < 0x10100000L - } else { - /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */ - EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); - if (ecdh != NULL) { - if (SSL_CTX_set_tmp_ecdh(ctx, ecdh)) { - PJ_LOG(4,(ssock->pool->obj_name, "SSL ECDH initialized " - "(secp256r1), faster PFS cipher-suites enabled")); - } - EC_KEY_free(ecdh); - } + OPENSSL_VERSION_NUMBER < 0x10100000L + } else { + /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */ + EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); + if (ecdh != NULL) { + if (SSL_CTX_set_tmp_ecdh(ctx, ecdh)) { + PJ_LOG(4,(ssock->pool->obj_name, "SSL ECDH initialized " + "(secp256r1), faster PFS cipher-suites enabled")); + } + EC_KEY_free(ecdh); + } #endif - } + } } else { - X509_STORE *pkix_validation_store = SSL_CTX_get_cert_store(ctx); - if (NULL != pkix_validation_store) { + X509_STORE *pkix_validation_store = SSL_CTX_get_cert_store(ctx); + if (NULL != pkix_validation_store) { #if defined(X509_V_FLAG_TRUSTED_FIRST) - X509_STORE_set_flags(pkix_validation_store, - X509_V_FLAG_TRUSTED_FIRST); + X509_STORE_set_flags(pkix_validation_store, + X509_V_FLAG_TRUSTED_FIRST); #endif #if defined(X509_V_FLAG_PARTIAL_CHAIN) - X509_STORE_set_flags(pkix_validation_store, - X509_V_FLAG_PARTIAL_CHAIN); + X509_STORE_set_flags(pkix_validation_store, + X509_V_FLAG_PARTIAL_CHAIN); #endif - } + } } /* Add certificate authorities for clients from CA. @@ -1533,7 +1532,7 @@ static pj_status_t init_ossl_ctx(pj_ssl_sock_t *ssock) X509_NAME *xn = NULL; STACK_OF(X509_NAME) *sk = NULL; BIO *new_bio = BIO_new_mem_buf((void*)cert->CA_buf.ptr, - cert->CA_buf.slen); + cert->CA_buf.slen); sk = sk_X509_NAME_new(xname_cmp); @@ -1562,21 +1561,21 @@ static pj_status_t init_ossl_ctx(pj_ssl_sock_t *ssock) } } if (sk != NULL) - ca_dn = sk; + ca_dn = sk; if (new_bio != NULL) BIO_free(new_bio); } - if (ca_dn != NULL) { - SSL_CTX_set_client_CA_list(ctx, ca_dn); - PJ_LOG(4,(ssock->pool->obj_name, - "CA certificates loaded from %s", - (cert->CA_file.slen?cert->CA_file.ptr:"buffer"))); - } else { - PJ_LOG(1,(ssock->pool->obj_name, - "Error reading CA certificates from %s", - (cert->CA_file.slen?cert->CA_file.ptr:"buffer"))); - } + if (ca_dn != NULL) { + SSL_CTX_set_client_CA_list(ctx, ca_dn); + PJ_LOG(4,(ssock->pool->obj_name, + "CA certificates loaded from %s", + (cert->CA_file.slen?cert->CA_file.ptr:"buffer"))); + } else { + PJ_LOG(1,(ssock->pool->obj_name, + "Error reading CA certificates from %s", + (cert->CA_file.slen?cert->CA_file.ptr:"buffer"))); + } } /* Early sensitive data cleanup after OpenSSL context setup. However, @@ -1584,7 +1583,7 @@ static pj_status_t init_ossl_ctx(pj_ssl_sock_t *ssock) * be needed by accepted sockets. */ if (cert && (!ssock->is_server || ssock->parent)) { - pj_ssl_cert_wipe_keys(cert); + pj_ssl_cert_wipe_keys(cert); } return PJ_SUCCESS; @@ -1606,31 +1605,31 @@ static pj_status_t ssl_create(pj_ssl_sock_t *ssock) set_entropy(ssock); if (ssock->param.proto == PJ_SSL_SOCK_PROTO_DEFAULT) - ssock->param.proto = PJ_SSL_SOCK_PROTO_SSL23; + ssock->param.proto = PJ_SSL_SOCK_PROTO_SSL23; /* Create SSL context */ if (SERVER_SUPPORT_SESSION_REUSE && ssock->is_server) { - SSL_CTX *server_ctx = ((ossl_sock_t *)ssock->parent)->ossl_ctx; + SSL_CTX *server_ctx = ((ossl_sock_t *)ssock->parent)->ossl_ctx; - if (!server_ctx) { - status = init_ossl_ctx(ssock->parent); - if (status != PJ_SUCCESS) - return status; + if (!server_ctx) { + status = init_ossl_ctx(ssock->parent); + if (status != PJ_SUCCESS) + return status; - server_ctx = ((ossl_sock_t *)ssock->parent)->ossl_ctx; - ((ossl_sock_t *)ssock->parent)->own_ctx = PJ_TRUE; - } - ossock->ossl_ctx = server_ctx; + server_ctx = ((ossl_sock_t *)ssock->parent)->ossl_ctx; + ((ossl_sock_t *)ssock->parent)->own_ctx = PJ_TRUE; + } + ossock->ossl_ctx = server_ctx; } else { - status = init_ossl_ctx(ssock); - if (status != PJ_SUCCESS) - return status; + status = init_ossl_ctx(ssock); + if (status != PJ_SUCCESS) + return status; } /* Create SSL instance */ ossock->ossl_ssl = SSL_new(ossock->ossl_ctx); if (ossock->ossl_ssl == NULL) { - return GET_SSL_STATUS(ssock); + return GET_SSL_STATUS(ssock); } /* Set SSL sock as application data of SSL instance */ @@ -1639,19 +1638,19 @@ static pj_status_t ssl_create(pj_ssl_sock_t *ssock) /* SSL verification options */ mode = SSL_VERIFY_PEER; if (ssock->is_server && ssock->param.require_client_cert) - mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; + mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; SSL_set_verify(ossock->ossl_ssl, mode, &verify_cb); /* Set curve list */ status = set_curves_list(ssock); if (status != PJ_SUCCESS) - return status; + return status; /* Set sigalg list */ status = set_sigalgs(ssock); if (status != PJ_SUCCESS) - return status; + return status; /* Setup SSL BIOs */ ossock->ossl_rbio = BIO_new(BIO_s_mem()); @@ -1671,19 +1670,19 @@ static void ssl_destroy(pj_ssl_sock_t *ssock) /* Destroy SSL instance */ if (ossock->ossl_ssl) { - SSL_free(ossock->ossl_ssl); /* this will also close BIOs */ - ossock->ossl_ssl = NULL; + SSL_free(ossock->ossl_ssl); /* this will also close BIOs */ + ossock->ossl_ssl = NULL; } /* Destroy SSL context */ if (ossock->ossl_ctx) { - if (ssock->is_server) { - if (!SERVER_SUPPORT_SESSION_REUSE || ossock->own_ctx) - SSL_CTX_free(ossock->ossl_ctx); - } else { - SSL_CTX_free(ossock->ossl_ctx); - } - ossock->ossl_ctx = NULL; + if (ssock->is_server) { + if (!SERVER_SUPPORT_SESSION_REUSE || ossock->own_ctx) + SSL_CTX_free(ossock->ossl_ctx); + } else { + SSL_CTX_free(ossock->ossl_ctx); + } + ossock->ossl_ctx = NULL; } /* Potentially shutdown OpenSSL library if this is the last @@ -1700,7 +1699,7 @@ static void ssl_reset_sock_state(pj_ssl_sock_t *ssock) /* Detach from SSL instance */ if (ossock->ossl_ssl) { - SSL_set_ex_data(ossock->ossl_ssl, sslsock_idx, NULL); + SSL_set_ex_data(ossock->ossl_ssl, sslsock_idx, NULL); } /** @@ -1709,11 +1708,11 @@ static void ssl_reset_sock_state(pj_ssl_sock_t *ssock) * SSL handshake, while previous versions always return 0. */ if (ossock->ossl_ssl && SSL_in_init(ossock->ossl_ssl) == 0) { - int ret = SSL_shutdown(ossock->ossl_ssl); - if (ret == 0) { - /* Flush data to send close notify. */ - flush_circ_buf_output(ssock, &ssock->shutdown_op_key, 0, 0); - } + int ret = SSL_shutdown(ossock->ossl_ssl); + if (ret == 0) { + /* Flush data to send close notify. */ + flush_circ_buf_output(ssock, &ssock->shutdown_op_key, 0, 0); + } } pj_lock_acquire(ssock->write_mutex); @@ -1735,8 +1734,8 @@ static void ssl_reset_sock_state(pj_ssl_sock_t *ssock) static void ssl_ciphers_populate() { if (ssl_cipher_num == 0 || ssl_curves_num == 0) { - init_openssl(); - shutdown_openssl(); + init_openssl(); + shutdown_openssl(); } } @@ -1748,9 +1747,9 @@ static pj_ssl_cipher ssl_get_cipher(pj_ssl_sock_t *ssock) /* Current cipher */ cipher = SSL_get_current_cipher(ossock->ossl_ssl); if (cipher) { - return (SSL_CIPHER_get_id(cipher) & 0x00FFFFFF); + return (SSL_CIPHER_get_id(cipher) & 0x00FFFFFF); } else { - return PJ_TLS_UNKNOWN_CIPHER; + return PJ_TLS_UNKNOWN_CIPHER; } } @@ -1766,19 +1765,19 @@ static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock) int ret; if (ssock->param.ciphers_num == 0) { - ret = SSL_CTX_set_cipher_list(ossock->ossl_ctx, PJ_SSL_SOCK_OSSL_CIPHERS); - if (ret < 1) { - return GET_SSL_STATUS(ssock); - } - - return PJ_SUCCESS; + ret = SSL_CTX_set_cipher_list(ossock->ossl_ctx, PJ_SSL_SOCK_OSSL_CIPHERS); + if (ret < 1) { + return GET_SSL_STATUS(ssock); + } + + return PJ_SUCCESS; } /* Create temporary pool. */ tmp_pool = pj_pool_create(ssock->pool->factory, "ciphpool", BUF_SIZE, - BUF_SIZE/2 , NULL); + BUF_SIZE/2 , NULL); if (!tmp_pool) - return PJ_ENOMEM; + return PJ_ENOMEM; buf = (char *)pj_pool_zalloc(tmp_pool, BUF_SIZE); @@ -1786,28 +1785,28 @@ static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock) /* Generate user specified cipher list in OpenSSL format */ for (i = 0; i < ssock->param.ciphers_num; ++i) { - for (j = 0; j < ssl_cipher_num; ++j) { - if (ssock->param.ciphers[i] == ssl_ciphers[j].id) - { - const char *c_name = ssl_ciphers[j].name; - - /* Check buffer size */ - if (cipher_list.slen + pj_ansi_strlen(c_name) + 2 > - BUF_SIZE) - { - pj_assert(!"Insufficient temporary buffer for cipher"); - return PJ_ETOOMANY; - } - - /* Add colon separator */ - if (cipher_list.slen) - pj_strcat2(&cipher_list, ":"); - - /* Add the cipher */ - pj_strcat2(&cipher_list, c_name); - break; - } - } + for (j = 0; j < ssl_cipher_num; ++j) { + if (ssock->param.ciphers[i] == ssl_ciphers[j].id) + { + const char *c_name = ssl_ciphers[j].name; + + /* Check buffer size */ + if (cipher_list.slen + pj_ansi_strlen(c_name) + 2 > + BUF_SIZE) + { + pj_assert(!"Insufficient temporary buffer for cipher"); + return PJ_ETOOMANY; + } + + /* Add colon separator */ + if (cipher_list.slen) + pj_strcat2(&cipher_list, ":"); + + /* Add the cipher */ + pj_strcat2(&cipher_list, c_name); + break; + } + } } /* Put NULL termination in the generated cipher list */ @@ -1816,8 +1815,8 @@ static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock) /* Finally, set chosen cipher list */ ret = SSL_CTX_set_cipher_list(ossock->ossl_ctx, buf); if (ret < 1) { - pj_pool_release(tmp_pool); - return GET_SSL_STATUS(ssock); + pj_pool_release(tmp_pool); + return GET_SSL_STATUS(ssock); } pj_pool_release(tmp_pool); @@ -1834,22 +1833,22 @@ static pj_status_t set_curves_list(pj_ssl_sock_t *ssock) unsigned cnt; if (ssock->param.curves_num == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; for (cnt = 0; cnt < ssock->param.curves_num; cnt++) { - curves[cnt] = get_nid_from_cid(ssock->param.curves[cnt]); + curves[cnt] = get_nid_from_cid(ssock->param.curves[cnt]); } if( SSL_is_server(ossock->ossl_ssl) ) { - ret = SSL_set1_curves(ossock->ossl_ssl, curves, - ssock->param.curves_num); - if (ret < 1) - return GET_SSL_STATUS(ssock); + ret = SSL_set1_curves(ossock->ossl_ssl, curves, + ssock->param.curves_num); + if (ret < 1) + return GET_SSL_STATUS(ssock); } else { - ret = SSL_CTX_set1_curves(ossock->ossl_ctx, curves, - ssock->param.curves_num); - if (ret < 1) - return GET_SSL_STATUS(ssock); + ret = SSL_CTX_set1_curves(ossock->ossl_ctx, curves, + ssock->param.curves_num); + if (ret < 1) + return GET_SSL_STATUS(ssock); } #else PJ_UNUSED_ARG(ssock); @@ -1865,20 +1864,20 @@ static pj_status_t set_sigalgs(pj_ssl_sock_t *ssock) if (ssock->param.sigalgs.ptr && ssock->param.sigalgs.slen) { #if !USING_BORINGSSL - if (ssock->is_server) { - ret = SSL_set1_client_sigalgs_list(ossock->ossl_ssl, - ssock->param.sigalgs.ptr); - } else { - ret = SSL_set1_sigalgs_list(ossock->ossl_ssl, - ssock->param.sigalgs.ptr); - } + if (ssock->is_server) { + ret = SSL_set1_client_sigalgs_list(ossock->ossl_ssl, + ssock->param.sigalgs.ptr); + } else { + ret = SSL_set1_sigalgs_list(ossock->ossl_ssl, + ssock->param.sigalgs.ptr); + } #else - ret = SSL_set1_sigalgs_list(ossock->ossl_ssl, - ssock->param.sigalgs.ptr); + ret = SSL_set1_sigalgs_list(ossock->ossl_ssl, + ssock->param.sigalgs.ptr); #endif - if (ret < 1) - return GET_SSL_STATUS(ssock); + if (ret < 1) + return GET_SSL_STATUS(ssock); } #else PJ_UNUSED_ARG(ssock); @@ -1892,35 +1891,35 @@ static void set_entropy(pj_ssl_sock_t *ssock) switch (ssock->param.entropy_type) { #ifndef OPENSSL_NO_EGD - case PJ_SSL_ENTROPY_EGD: - ret = RAND_egd(ssock->param.entropy_path.ptr); - break; + case PJ_SSL_ENTROPY_EGD: + ret = RAND_egd(ssock->param.entropy_path.ptr); + break; #endif - case PJ_SSL_ENTROPY_RANDOM: - ret = RAND_load_file("/dev/random",255); - break; - case PJ_SSL_ENTROPY_URANDOM: - ret = RAND_load_file("/dev/urandom",255); - break; - case PJ_SSL_ENTROPY_FILE: - ret = RAND_load_file(ssock->param.entropy_path.ptr,255); - break; - case PJ_SSL_ENTROPY_NONE: - default: - break; + case PJ_SSL_ENTROPY_RANDOM: + ret = RAND_load_file("/dev/random",255); + break; + case PJ_SSL_ENTROPY_URANDOM: + ret = RAND_load_file("/dev/urandom",255); + break; + case PJ_SSL_ENTROPY_FILE: + ret = RAND_load_file(ssock->param.entropy_path.ptr,255); + break; + case PJ_SSL_ENTROPY_NONE: + default: + break; } if (ret < 0) { - PJ_LOG(3, (ssock->pool->obj_name, - "SSL failed to reseed with entropy type %d " - "[native err=%d]", - ssock->param.entropy_type, ret)); + PJ_LOG(3, (ssock->pool->obj_name, + "SSL failed to reseed with entropy type %d " + "[native err=%d]", + ssock->param.entropy_type, ret)); } } /* Parse OpenSSL ASN1_TIME to pj_time_val and GMT info */ static pj_bool_t parse_ossl_asn1_time(pj_time_val *tv, pj_bool_t *gmt, - const ASN1_TIME *tm) + const ASN1_TIME *tm) { unsigned long parts[7] = {0}; char *p, *end; @@ -1939,29 +1938,29 @@ static pj_bool_t parse_ossl_asn1_time(pj_time_val *tv, pj_bool_t *gmt, /* parse parts */ for (i = 0; i < 7 && p < end; ++i) { - pj_str_t st; - - if (i==0 && !utc) { - /* 4 digits year part for non-UTC time format */ - st.slen = 4; - } else if (i==6) { - /* fraction of seconds */ - if (*p == '.') ++p; - st.slen = end - p + 1; - } else { - /* other parts always 2 digits length */ - st.slen = 2; - } - st.ptr = p; + pj_str_t st; + + if (i==0 && !utc) { + /* 4 digits year part for non-UTC time format */ + st.slen = 4; + } else if (i==6) { + /* fraction of seconds */ + if (*p == '.') ++p; + st.slen = end - p + 1; + } else { + /* other parts always 2 digits length */ + st.slen = 2; + } + st.ptr = p; - parts[i] = pj_strtoul(&st); - p += st.slen; + parts[i] = pj_strtoul(&st); + p += st.slen; } /* encode parts to pj_time_val */ pt.year = parts[0]; if (utc) - pt.year += (pt.year < 50)? 2000:1900; + pt.year += (pt.year < 50)? 2000:1900; pt.mon = parts[1] - 1; pt.day = parts[2]; pt.hour = parts[3]; @@ -1984,17 +1983,17 @@ static void get_cn_from_gen_name(const pj_str_t *gen_name, pj_str_t *cn) pj_bzero(cn, sizeof(pj_str_t)); if (!gen_name->slen) - return; + return; p = pj_strstr(gen_name, &CN_sign); if (!p) - return; + return; p += 4; /* shift pointer to value part */ pj_strset(cn, p, gen_name->slen - (p - gen_name->ptr)); q = pj_strchr(cn, '/'); if (q) - cn->slen = q - p; + cn->slen = q - p; } @@ -2003,7 +2002,7 @@ static void get_cn_from_gen_name(const pj_str_t *gen_name, pj_str_t *cn) * to be updated by inspecting the issuer and the serial number. */ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, X509 *x, - pj_bool_t get_pem) + pj_bool_t get_pem) { pj_bool_t update_needed; char buf[512]; @@ -2021,14 +2020,14 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, X509 *x, q = (const pj_uint8_t*) M_ASN1_STRING_data(X509_get_serialNumber(x)); len = M_ASN1_STRING_length(X509_get_serialNumber(x)); if (len > sizeof(ci->serial_no)) - len = sizeof(ci->serial_no); + len = sizeof(ci->serial_no); pj_memcpy(serial_no + sizeof(ci->serial_no) - len, q, len); /* Check if the contents need to be updated. */ update_needed = pj_strcmp2(&ci->issuer.info, buf) || - pj_memcmp(ci->serial_no, serial_no, sizeof(ci->serial_no)); + pj_memcmp(ci->serial_no, serial_no, sizeof(ci->serial_no)); if (!update_needed) - return; + return; /* Update cert info */ @@ -2046,105 +2045,105 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, X509 *x, /* Subject */ pj_strdup2(pool, &ci->subject.info, - X509_NAME_oneline(X509_get_subject_name(x), - buf, sizeof(buf))); + X509_NAME_oneline(X509_get_subject_name(x), + buf, sizeof(buf))); get_cn_from_gen_name(&ci->subject.info, &ci->subject.cn); /* Validity */ parse_ossl_asn1_time(&ci->validity.start, &ci->validity.gmt, - X509_get_notBefore(x)); + X509_get_notBefore(x)); parse_ossl_asn1_time(&ci->validity.end, &ci->validity.gmt, - X509_get_notAfter(x)); + X509_get_notAfter(x)); /* Subject Alternative Name extension */ if (ci->version >= 3) { - names = (GENERAL_NAMES*) X509_get_ext_d2i(x, NID_subject_alt_name, - NULL, NULL); + names = (GENERAL_NAMES*) X509_get_ext_d2i(x, NID_subject_alt_name, + NULL, NULL); } if (names) { unsigned i, cnt; cnt = sk_GENERAL_NAME_num(names); - ci->subj_alt_name.entry = pj_pool_calloc(pool, cnt, - sizeof(*ci->subj_alt_name.entry)); + ci->subj_alt_name.entry = pj_pool_calloc(pool, cnt, + sizeof(*ci->subj_alt_name.entry)); for (i = 0; i < cnt; ++i) { - unsigned char *p = 0; - pj_ssl_cert_name_type type = PJ_SSL_CERT_NAME_UNKNOWN; + unsigned char *p = 0; + pj_ssl_cert_name_type type = PJ_SSL_CERT_NAME_UNKNOWN; const GENERAL_NAME *name; - - name = sk_GENERAL_NAME_value(names, i); + + name = sk_GENERAL_NAME_value(names, i); switch (name->type) { case GEN_EMAIL: len = ASN1_STRING_to_UTF8(&p, name->d.ia5); - type = PJ_SSL_CERT_NAME_RFC822; + type = PJ_SSL_CERT_NAME_RFC822; break; case GEN_DNS: len = ASN1_STRING_to_UTF8(&p, name->d.ia5); - type = PJ_SSL_CERT_NAME_DNS; + type = PJ_SSL_CERT_NAME_DNS; break; case GEN_URI: len = ASN1_STRING_to_UTF8(&p, name->d.ia5); - type = PJ_SSL_CERT_NAME_URI; + type = PJ_SSL_CERT_NAME_URI; break; case GEN_IPADD: - p = (unsigned char*)M_ASN1_STRING_data(name->d.ip); - len = M_ASN1_STRING_length(name->d.ip); - type = PJ_SSL_CERT_NAME_IP; + p = (unsigned char*)M_ASN1_STRING_data(name->d.ip); + len = M_ASN1_STRING_length(name->d.ip); + type = PJ_SSL_CERT_NAME_IP; + break; + default: break; - default: - break; } - if (p && len && type != PJ_SSL_CERT_NAME_UNKNOWN) { - ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type; - if (type == PJ_SSL_CERT_NAME_IP) { - int af = pj_AF_INET(); - if (len == sizeof(pj_in6_addr)) af = pj_AF_INET6(); - pj_inet_ntop2(af, p, buf, sizeof(buf)); - pj_strdup2(pool, - &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, - buf); - } else { - pj_strdup2(pool, - &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, - (char*)p); - OPENSSL_free(p); - } - ci->subj_alt_name.cnt++; - } + if (p && len && type != PJ_SSL_CERT_NAME_UNKNOWN) { + ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type; + if (type == PJ_SSL_CERT_NAME_IP) { + int af = pj_AF_INET(); + if (len == sizeof(pj_in6_addr)) af = pj_AF_INET6(); + pj_inet_ntop2(af, p, buf, sizeof(buf)); + pj_strdup2(pool, + &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, + buf); + } else { + pj_strdup2(pool, + &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, + (char*)p); + OPENSSL_free(p); + } + ci->subj_alt_name.cnt++; + } } GENERAL_NAMES_free(names); names = NULL; } if (get_pem) { - /* Update raw Certificate info in PEM format. */ - BIO *bio; - BUF_MEM *ptr; - - bio = BIO_new(BIO_s_mem()); - if (!PEM_write_bio_X509(bio, x)) { - PJ_LOG(3,(THIS_FILE, "Error retrieving raw certificate info")); - ci->raw.ptr = NULL; - ci->raw.slen = 0; - } else { - BIO_write(bio, "\0", 1); - BIO_get_mem_ptr(bio, &ptr); - pj_strdup2(pool, &ci->raw, ptr->data); - } - BIO_free(bio); - } + /* Update raw Certificate info in PEM format. */ + BIO *bio; + BUF_MEM *ptr; + + bio = BIO_new(BIO_s_mem()); + if (!PEM_write_bio_X509(bio, x)) { + PJ_LOG(3,(THIS_FILE, "Error retrieving raw certificate info")); + ci->raw.ptr = NULL; + ci->raw.slen = 0; + } else { + BIO_write(bio, "\0", 1); + BIO_get_mem_ptr(bio, &ptr); + pj_strdup2(pool, &ci->raw, ptr->data); + } + BIO_free(bio); + } } /* Update remote certificates chain info. This function should be * called after handshake or renegotiation successfully completed. */ static void ssl_update_remote_cert_chain_info(pj_pool_t *pool, - pj_ssl_cert_info *ci, - STACK_OF(X509) *chain, - pj_bool_t get_pem) + pj_ssl_cert_info *ci, + STACK_OF(X509) *chain, + pj_bool_t get_pem) { int i; @@ -2153,14 +2152,14 @@ static void ssl_update_remote_cert_chain_info(pj_pool_t *pool, PJ_UNUSED_ARG(get_pem); ci->raw_chain.cert_raw = (pj_str_t *)pj_pool_calloc(pool, - sk_X509_num(chain), - sizeof(pj_str_t)); + sk_X509_num(chain), + sizeof(pj_str_t)); ci->raw_chain.cnt = sk_X509_num(chain); for (i = 0; i < sk_X509_num(chain); i++) { BIO *bio; BUF_MEM *ptr; - X509 *x = sk_X509_value(chain, i); + X509 *x = sk_X509_value(chain, i); bio = BIO_new(BIO_s_mem()); @@ -2186,15 +2185,15 @@ static void ssl_update_certs_info(pj_ssl_sock_t *ssock) pj_assert(ssock->ssl_state == SSL_STATE_ESTABLISHED); update_certs_info(ssock, NULL, &ssock->local_cert_info, - &ssock->remote_cert_info, PJ_FALSE); + &ssock->remote_cert_info, PJ_FALSE); } static void update_certs_info(pj_ssl_sock_t* ssock, - X509_STORE_CTX* ctx, - pj_ssl_cert_info *local_cert_info, - pj_ssl_cert_info *remote_cert_info, - pj_bool_t is_verify) + X509_STORE_CTX* ctx, + pj_ssl_cert_info *local_cert_info, + pj_ssl_cert_info *remote_cert_info, + pj_bool_t is_verify) { ossl_sock_t* ossock = (ossl_sock_t*)ssock; X509* x; @@ -2203,47 +2202,47 @@ static void update_certs_info(pj_ssl_sock_t* ssock, /* Active local certificate */ x = SSL_get_certificate(ossock->ossl_ssl); if (x) { - get_cert_info(ssock->pool, local_cert_info, x, PJ_FALSE); - /* Don't free local's X509! */ + get_cert_info(ssock->pool, local_cert_info, x, PJ_FALSE); + /* Don't free local's X509! */ } else { - pj_bzero(local_cert_info, sizeof(pj_ssl_cert_info)); + pj_bzero(local_cert_info, sizeof(pj_ssl_cert_info)); } /* Active remote certificate */ if (is_verify) { - x = X509_STORE_CTX_get0_cert(ctx); + x = X509_STORE_CTX_get0_cert(ctx); } else { - x = SSL_get_peer_certificate(ossock->ossl_ssl); + x = SSL_get_peer_certificate(ossock->ossl_ssl); } if (x) { - get_cert_info(ssock->pool, remote_cert_info, x, PJ_TRUE); - if (!is_verify) { - /* Free peer's X509 */ - X509_free(x); - } + get_cert_info(ssock->pool, remote_cert_info, x, PJ_TRUE); + if (!is_verify) { + /* Free peer's X509 */ + X509_free(x); + } } else { - pj_bzero(remote_cert_info, sizeof(pj_ssl_cert_info)); + pj_bzero(remote_cert_info, sizeof(pj_ssl_cert_info)); } if (is_verify) { - chain = X509_STORE_CTX_get1_chain(ctx); + chain = X509_STORE_CTX_get1_chain(ctx); } else { - chain = SSL_get_peer_cert_chain(ossock->ossl_ssl); + chain = SSL_get_peer_cert_chain(ossock->ossl_ssl); } if (chain) { - pj_pool_reset(ssock->info_pool); - ssl_update_remote_cert_chain_info(ssock->info_pool, - remote_cert_info, - chain, PJ_TRUE); - /* Only free the chain returned by X509_STORE_CTX_get1_chain(). - * The reference count of each cert returned by - * SSL_get_peer_cert_chain() is not incremented. - */ - if (is_verify) { - sk_X509_pop_free(chain, X509_free); - } + pj_pool_reset(ssock->info_pool); + ssl_update_remote_cert_chain_info(ssock->info_pool, + remote_cert_info, + chain, PJ_TRUE); + /* Only free the chain returned by X509_STORE_CTX_get1_chain(). + * The reference count of each cert returned by + * SSL_get_peer_cert_chain() is not incremented. + */ + if (is_verify) { + sk_X509_pop_free(chain, X509_free); + } } else { - remote_cert_info->raw_chain.cnt = 0; + remote_cert_info->raw_chain.cnt = 0; } } @@ -2265,7 +2264,7 @@ static void ssl_set_state(pj_ssl_sock_t *ssock, pj_bool_t is_server) if (is_server) { SSL_set_accept_state(ossock->ossl_ssl); } else { - SSL_set_connect_state(ossock->ossl_ssl); + SSL_set_connect_state(ossock->ossl_ssl); } } @@ -2280,8 +2279,8 @@ static int sni_cb(SSL *ssl, int *al, void *arg) sname = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); if (!sname || pj_stricmp2(&ssock->param.server_name, sname)) { - PJ_LOG(4, (THIS_FILE, "Client SNI rejected: %s", sname)); - return SSL_TLSEXT_ERR_ALERT_FATAL; + PJ_LOG(4, (THIS_FILE, "Client SNI rejected: %s", sname)); + return SSL_TLSEXT_ERR_ALERT_FATAL; } return SSL_TLSEXT_ERR_OK; @@ -2295,28 +2294,28 @@ static void ssl_set_peer_name(pj_ssl_sock_t *ssock) if (ssock->param.server_name.slen && get_ip_addr_ver(&ssock->param.server_name) == 0) { - if (ssock->is_server) { + if (ssock->is_server) { #if defined(SSL_CTX_set_tlsext_servername_callback) && \ defined(SSL_CTX_set_tlsext_servername_arg) - SSL_CTX_set_tlsext_servername_callback(ossock->ossl_ctx, &sni_cb); - SSL_CTX_set_tlsext_servername_arg(ossock->ossl_ctx, ssock); + SSL_CTX_set_tlsext_servername_callback(ossock->ossl_ctx, &sni_cb); + SSL_CTX_set_tlsext_servername_arg(ossock->ossl_ctx, ssock); #endif - } else { + } else { #ifdef SSL_set_tlsext_host_name - /* Server name is null terminated already */ - if (!SSL_set_tlsext_host_name(ossock->ossl_ssl, - ssock->param.server_name.ptr)) - { - char err_str[PJ_ERR_MSG_SIZE]; - - ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str)); - PJ_LOG(3,(ssock->pool->obj_name, "SSL_set_tlsext_host_name() " - "failed: %s", err_str)); - } + /* Server name is null terminated already */ + if (!SSL_set_tlsext_host_name(ossock->ossl_ssl, + ssock->param.server_name.ptr)) + { + char err_str[PJ_ERR_MSG_SIZE]; + + ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str)); + PJ_LOG(3,(ssock->pool->obj_name, "SSL_set_tlsext_host_name() " + "failed: %s", err_str)); + } #endif - } + } } } @@ -2338,65 +2337,65 @@ static pj_status_t ssl_do_handshake(pj_ssl_sock_t *ssock) */ status = flush_circ_buf_output(ssock, &ssock->handshake_op_key, 0, 0); if (status != PJ_SUCCESS && status != PJ_EPENDING) { - return status; + return status; } if (err < 0) { - int err2 = SSL_get_error(ossock->ossl_ssl, err); - if (err2 != SSL_ERROR_NONE && err2 != SSL_ERROR_WANT_READ) - { - /* Handshake fails */ - status = STATUS_FROM_SSL_ERR2("Handshake", ssock, err, err2, 0); - return status; - } + int err2 = SSL_get_error(ossock->ossl_ssl, err); + if (err2 != SSL_ERROR_NONE && err2 != SSL_ERROR_WANT_READ) + { + /* Handshake fails */ + status = STATUS_FROM_SSL_ERR2("Handshake", ssock, err, err2, 0); + return status; + } } /* Check if handshake has been completed */ if (SSL_is_init_finished(ossock->ossl_ssl)) { #if OPENSSL_VERSION_NUMBER >= 0x10100000L - if (ssock->is_server && ssock->ssl_state != SSL_STATE_ESTABLISHED) { - enum {BUF_SIZE = 64}; - unsigned int len = 0, i; - const unsigned char *sctx, *sid; - char buf[BUF_SIZE+1]; - SSL_SESSION *sess; - - sess = SSL_get_session(ossock->ossl_ssl); + if (ssock->is_server && ssock->ssl_state != SSL_STATE_ESTABLISHED) { + enum {BUF_SIZE = 64}; + unsigned int len = 0, i; + const unsigned char *sctx, *sid; + char buf[BUF_SIZE+1]; + SSL_SESSION *sess; + + sess = SSL_get_session(ossock->ossl_ssl); #if OPENSSL_VERSION_NUMBER >= 0x1010100fL - PJ_LOG(5, (THIS_FILE, "Session info: reused=%d, resumable=%d, " - "timeout=%d", - SSL_session_reused(ossock->ossl_ssl), - SSL_SESSION_is_resumable(sess), - SSL_SESSION_get_timeout(sess))); + PJ_LOG(5, (THIS_FILE, "Session info: reused=%d, resumable=%d, " + "timeout=%d", + SSL_session_reused(ossock->ossl_ssl), + SSL_SESSION_is_resumable(sess), + SSL_SESSION_get_timeout(sess))); #else - PJ_LOG(5, (THIS_FILE, "Session info: reused=%d, resumable=%d, " - "timeout=%d", - SSL_session_reused(ossock->ossl_ssl), - -1, - SSL_SESSION_get_timeout(sess))); + PJ_LOG(5, (THIS_FILE, "Session info: reused=%d, resumable=%d, " + "timeout=%d", + SSL_session_reused(ossock->ossl_ssl), + -1, + SSL_SESSION_get_timeout(sess))); #endif - sid = SSL_SESSION_get_id(sess, &len); - len *= 2; - if (len >= BUF_SIZE) len = BUF_SIZE; - for (i = 0; i < len; i+=2) - pj_ansi_sprintf(buf+i, "%02X", sid[i/2]); - buf[len] = '\0'; - PJ_LOG(5, (THIS_FILE, "Session id: %s", buf)); - - sctx = SSL_SESSION_get0_id_context(sess, &len); - if (len >= BUF_SIZE) len = BUF_SIZE; - for (i = 0; i < len; i++) - pj_ansi_sprintf(buf + i, "%d", sctx[i]); - buf[len] = '\0'; - PJ_LOG(5, (THIS_FILE, "Session id context: %s", buf)); - } + sid = SSL_SESSION_get_id(sess, &len); + len *= 2; + if (len >= BUF_SIZE) len = BUF_SIZE; + for (i = 0; i < len; i+=2) + pj_ansi_sprintf(buf+i, "%02X", sid[i/2]); + buf[len] = '\0'; + PJ_LOG(5, (THIS_FILE, "Session id: %s", buf)); + + sctx = SSL_SESSION_get0_id_context(sess, &len); + if (len >= BUF_SIZE) len = BUF_SIZE; + for (i = 0; i < len; i++) + pj_ansi_sprintf(buf + i, "%d", sctx[i]); + buf[len] = '\0'; + PJ_LOG(5, (THIS_FILE, "Session id context: %s", buf)); + } #endif - ssock->ssl_state = SSL_STATE_ESTABLISHED; - return PJ_SUCCESS; + ssock->ssl_state = SSL_STATE_ESTABLISHED; + return PJ_SUCCESS; } return PJ_EPENDING; @@ -2417,33 +2416,33 @@ static pj_status_t ssl_read(pj_ssl_sock_t *ssock, void *data, int *size) pj_lock_release(ssock->write_mutex); if (size_ <= 0) { - pj_status_t status; - int err = SSL_get_error(ossock->ossl_ssl, size_); - - /* SSL might just return SSL_ERROR_WANT_READ in - * re-negotiation. - */ - if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ) { - if (err == SSL_ERROR_SYSCALL && size_ == -1 && - ERR_peek_error() == 0 && errno == 0) - { - status = STATUS_FROM_SSL_ERR2("Read", ssock, size_, - err, len); - PJ_LOG(4,("SSL", "SSL_read() = -1, with " - "SSL_ERROR_SYSCALL, no SSL error, " - "and errno = 0 - skip BIO error")); - /* Ignore these errors */ - } else { - /* Reset SSL socket state, then return PJ_FALSE */ - status = STATUS_FROM_SSL_ERR2("Read", ssock, size_, - err, len); - ssl_reset_sock_state(ssock); - return status; - } - } - - /* Need renegotiation */ - return PJ_EEOF; + pj_status_t status; + int err = SSL_get_error(ossock->ossl_ssl, size_); + + /* SSL might just return SSL_ERROR_WANT_READ in + * re-negotiation. + */ + if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ) { + if (err == SSL_ERROR_SYSCALL && size_ == -1 && + ERR_peek_error() == 0 && errno == 0) + { + status = STATUS_FROM_SSL_ERR2("Read", ssock, size_, + err, len); + PJ_LOG(4,("SSL", "SSL_read() = -1, with " + "SSL_ERROR_SYSCALL, no SSL error, " + "and errno = 0 - skip BIO error")); + /* Ignore these errors */ + } else { + /* Reset SSL socket state, then return PJ_FALSE */ + status = STATUS_FROM_SSL_ERR2("Read", ssock, size_, + err, len); + ssl_reset_sock_state(ssock); + return status; + } + } + + /* Need renegotiation */ + return PJ_EEOF; } return PJ_SUCCESS; @@ -2452,30 +2451,30 @@ static pj_status_t ssl_read(pj_ssl_sock_t *ssock, void *data, int *size) /* Write plain data to SSL and flush write BIO. */ static pj_status_t ssl_write(pj_ssl_sock_t *ssock, const void *data, - pj_ssize_t size, int *nwritten) + pj_ssize_t size, int *nwritten) { ossl_sock_t *ossock = (ossl_sock_t *)ssock; pj_status_t status = PJ_SUCCESS; *nwritten = SSL_write(ossock->ossl_ssl, data, (int)size); if (*nwritten <= 0) { - /* SSL failed to process the data, it may just that re-negotiation - * is on progress. - */ - int err; - err = SSL_get_error(ossock->ossl_ssl, *nwritten); - if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_NONE) { - status = PJ_EEOF; - } else { - /* Some problem occured */ - status = STATUS_FROM_SSL_ERR2("Write", ssock, *nwritten, - err, size); - } + /* SSL failed to process the data, it may just that re-negotiation + * is on progress. + */ + int err; + err = SSL_get_error(ossock->ossl_ssl, *nwritten); + if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_NONE) { + status = PJ_EEOF; + } else { + /* Some problem occured */ + status = STATUS_FROM_SSL_ERR2("Write", ssock, *nwritten, + err, size); + } } else if (*nwritten < size) { - /* nwritten < size, shouldn't happen, unless write BIO cannot hold - * the whole secured data, perhaps because of insufficient memory. - */ - status = PJ_ENOMEM; + /* nwritten < size, shouldn't happen, unless write BIO cannot hold + * the whole secured data, perhaps because of insufficient memory. + */ + status = PJ_ENOMEM; } return status; @@ -2489,11 +2488,11 @@ static pj_status_t ssl_renegotiate(pj_ssl_sock_t *ssock) int ret; if (SSL_renegotiate_pending(ossock->ossl_ssl)) - return PJ_EPENDING; + return PJ_EPENDING; ret = SSL_renegotiate(ossock->ossl_ssl); if (ret <= 0) { - status = GET_SSL_STATUS(ssock); + status = GET_SSL_STATUS(ssock); } return status; diff --git a/pjlib/src/pj/ssl_sock_symbian.cpp b/pjlib/src/pj/ssl_sock_symbian.cpp index 1c7aadf000..5f66ecba86 100644 --- a/pjlib/src/pj/ssl_sock_symbian.cpp +++ b/pjlib/src/pj/ssl_sock_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * @@ -36,7 +35,7 @@ /* Cipher name structure */ typedef struct cipher_name_t { pj_ssl_cipher cipher; - const char *name; + const char *name; } cipher_name_t; /* Cipher name constants */ @@ -138,51 +137,51 @@ class CPjSSLSocketReader : public CActive public: static CPjSSLSocketReader *NewL(CSecureSocket &sock) { - CPjSSLSocketReader *self = new (ELeave) - CPjSSLSocketReader(sock); - CleanupStack::PushL(self); - self->ConstructL(); - CleanupStack::Pop(self); - return self; + CPjSSLSocketReader *self = new (ELeave) + CPjSSLSocketReader(sock); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(self); + return self; } ~CPjSSLSocketReader() { - Cancel(); + Cancel(); } /* Asynchronous read from the socket. */ int Read(CPjSSLSocket_cb cb, void *key, TPtr8 &data, TUint flags) { - PJ_ASSERT_RETURN(!IsActive(), PJ_EBUSY); - - cb_ = cb; - key_ = key; - sock_.RecvOneOrMore(data, iStatus, len_received_); - SetActive(); - - return PJ_EPENDING; + PJ_ASSERT_RETURN(!IsActive(), PJ_EBUSY); + + cb_ = cb; + key_ = key; + sock_.RecvOneOrMore(data, iStatus, len_received_); + SetActive(); + + return PJ_EPENDING; } private: - CSecureSocket &sock_; - CPjSSLSocket_cb cb_; - void *key_; - TSockXfrLength len_received_; /* not really useful? */ + CSecureSocket &sock_; + CPjSSLSocket_cb cb_; + void *key_; + TSockXfrLength len_received_; /* not really useful? */ void DoCancel() { - sock_.CancelAll(); + sock_.CancelAll(); } void RunL() { - (*cb_)(iStatus.Int(), key_); + (*cb_)(iStatus.Int(), key_); } CPjSSLSocketReader(CSecureSocket &sock) : - CActive(0), sock_(sock), cb_(NULL), key_(NULL) + CActive(0), sock_(sock), cb_(NULL), key_(NULL) {} void ConstructL() { - CActiveScheduler::Add(this); + CActiveScheduler::Add(this); } }; @@ -190,32 +189,32 @@ class CPjSSLSocket : public CActive { public: enum ssl_state { - SSL_STATE_NULL, - SSL_STATE_CONNECTING, - SSL_STATE_HANDSHAKING, - SSL_STATE_ESTABLISHED + SSL_STATE_NULL, + SSL_STATE_CONNECTING, + SSL_STATE_HANDSHAKING, + SSL_STATE_ESTABLISHED }; static CPjSSLSocket *NewL(const TDesC8 &ssl_proto, - pj_qos_type qos_type, - const pj_qos_params &qos_params) + pj_qos_type qos_type, + const pj_qos_params &qos_params) { - CPjSSLSocket *self = new (ELeave) CPjSSLSocket(qos_type, qos_params); - CleanupStack::PushL(self); - self->ConstructL(ssl_proto); - CleanupStack::Pop(self); - return self; + CPjSSLSocket *self = new (ELeave) CPjSSLSocket(qos_type, qos_params); + CleanupStack::PushL(self); + self->ConstructL(ssl_proto); + CleanupStack::Pop(self); + return self; } ~CPjSSLSocket() { - Cancel(); - CleanupSubObjects(); + Cancel(); + CleanupSubObjects(); } int Connect(CPjSSLSocket_cb cb, void *key, const TInetAddr &local_addr, - const TInetAddr &rem_addr, - const TDesC8 &servername = TPtrC8(NULL,0), - const TDesC8 &ciphers = TPtrC8(NULL,0)); + const TInetAddr &rem_addr, + const TDesC8 &servername = TPtrC8(NULL,0), + const TDesC8 &ciphers = TPtrC8(NULL,0)); int Send(CPjSSLSocket_cb cb, void *key, const TDesC8 &aDesc, TUint flags); int SendSync(const TDesC8 &aDesc, TUint flags); @@ -223,72 +222,72 @@ class CPjSSLSocket : public CActive enum ssl_state GetState() const { return state_; } const TInetAddr* GetLocalAddr() const { return &local_addr_; } int GetCipher(TDes8 &cipher) const { - if (securesock_) - return securesock_->CurrentCipherSuite(cipher); - return KErrNotFound; + if (securesock_) + return securesock_->CurrentCipherSuite(cipher); + return KErrNotFound; } const CX509Certificate *GetPeerCert() { - if (securesock_) - return securesock_->ServerCert(); - return NULL; + if (securesock_) + return securesock_->ServerCert(); + return NULL; } private: - enum ssl_state state_; - pj_sock_t sock_; - CSecureSocket *securesock_; - bool is_connected_; - - pj_qos_type qos_type_; - pj_qos_params qos_params_; - + enum ssl_state state_; + pj_sock_t sock_; + CSecureSocket *securesock_; + bool is_connected_; + + pj_qos_type qos_type_; + pj_qos_params qos_params_; + CPjSSLSocketReader *reader_; - TBuf<32> ssl_proto_; - TInetAddr rem_addr_; - TPtrC8 servername_; - TPtrC8 ciphers_; - TInetAddr local_addr_; - TSockXfrLength sent_len_; + TBuf<32> ssl_proto_; + TInetAddr rem_addr_; + TPtrC8 servername_; + TPtrC8 ciphers_; + TInetAddr local_addr_; + TSockXfrLength sent_len_; - CPjSSLSocket_cb cb_; - void *key_; + CPjSSLSocket_cb cb_; + void *key_; void DoCancel(); void RunL(); CPjSSLSocket(pj_qos_type qos_type, const pj_qos_params &qos_params) : - CActive(0), state_(SSL_STATE_NULL), sock_(PJ_INVALID_SOCKET), - securesock_(NULL), is_connected_(false), - qos_type_(qos_type), qos_params_(qos_params), - reader_(NULL), cb_(NULL), key_(NULL) + CActive(0), state_(SSL_STATE_NULL), sock_(PJ_INVALID_SOCKET), + securesock_(NULL), is_connected_(false), + qos_type_(qos_type), qos_params_(qos_params), + reader_(NULL), cb_(NULL), key_(NULL) {} void ConstructL(const TDesC8 &ssl_proto) { - ssl_proto_.Copy(ssl_proto); - CActiveScheduler::Add(this); + ssl_proto_.Copy(ssl_proto); + CActiveScheduler::Add(this); } void CleanupSubObjects() { - delete reader_; - reader_ = NULL; - if (securesock_) { - if (state_ == SSL_STATE_ESTABLISHED) - securesock_->Close(); - delete securesock_; - securesock_ = NULL; - } - if (sock_ != PJ_INVALID_SOCKET) { - pj_sock_close(sock_); - sock_ = PJ_INVALID_SOCKET; - } + delete reader_; + reader_ = NULL; + if (securesock_) { + if (state_ == SSL_STATE_ESTABLISHED) + securesock_->Close(); + delete securesock_; + securesock_ = NULL; + } + if (sock_ != PJ_INVALID_SOCKET) { + pj_sock_close(sock_); + sock_ = PJ_INVALID_SOCKET; + } } }; int CPjSSLSocket::Connect(CPjSSLSocket_cb cb, void *key, - const TInetAddr &local_addr, - const TInetAddr &rem_addr, - const TDesC8 &servername, - const TDesC8 &ciphers) + const TInetAddr &local_addr, + const TInetAddr &rem_addr, + const TDesC8 &servername, + const TDesC8 &ciphers) { pj_status_t status; @@ -296,20 +295,20 @@ int CPjSSLSocket::Connect(CPjSSLSocket_cb cb, void *key, status = pj_sock_socket(rem_addr.Family(), pj_SOCK_STREAM(), 0, &sock_); if (status != PJ_SUCCESS) - return status; + return status; // Apply QoS status = pj_sock_apply_qos2(sock_, qos_type_, &qos_params_, - 2, THIS_FILE, NULL); + 2, THIS_FILE, NULL); RSocket &rSock = ((CPjSocket*)sock_)->Socket(); local_addr_ = local_addr; if (!local_addr_.IsUnspecified()) { - TInt err = rSock.Bind(local_addr_); - if (err != KErrNone) - return PJ_RETURN_OS_ERROR(err); + TInt err = rSock.Bind(local_addr_); + if (err != KErrNone) + return PJ_RETURN_OS_ERROR(err); } cb_ = cb; @@ -330,14 +329,14 @@ int CPjSSLSocket::Connect(CPjSSLSocket_cb cb, void *key, } int CPjSSLSocket::Send(CPjSSLSocket_cb cb, void *key, const TDesC8 &aDesc, - TUint flags) + TUint flags) { PJ_UNUSED_ARG(flags); PJ_ASSERT_RETURN(state_ == SSL_STATE_ESTABLISHED, PJ_EINVALIDOP); if (IsActive()) - return PJ_EBUSY; + return PJ_EBUSY; cb_ = cb; key_ = key; @@ -366,11 +365,11 @@ CPjSSLSocketReader* CPjSSLSocket::GetReader() PJ_ASSERT_RETURN(state_ == SSL_STATE_ESTABLISHED, NULL); if (reader_) - return reader_; + return reader_; - TRAPD(err, reader_ = CPjSSLSocketReader::NewL(*securesock_)); + TRAPD(err, reader_ = CPjSSLSocketReader::NewL(*securesock_)); if (err != KErrNone) - return NULL; + return NULL; return reader_; } @@ -380,26 +379,26 @@ void CPjSSLSocket::DoCancel() /* Operation to be cancelled depends on current state */ switch (state_) { case SSL_STATE_CONNECTING: - { - RSocket &rSock = ((CPjSocket*)sock_)->Socket(); - - rSock.CancelConnect(); - CleanupSubObjects(); - state_ = SSL_STATE_NULL; - } - break; + { + RSocket &rSock = ((CPjSocket*)sock_)->Socket(); + + rSock.CancelConnect(); + CleanupSubObjects(); + state_ = SSL_STATE_NULL; + } + break; case SSL_STATE_HANDSHAKING: - { - securesock_->CancelHandshake(); - CleanupSubObjects(); - state_ = SSL_STATE_NULL; - } - break; + { + securesock_->CancelHandshake(); + CleanupSubObjects(); + state_ = SSL_STATE_NULL; + } + break; case SSL_STATE_ESTABLISHED: - securesock_->CancelSend(); - break; + securesock_->CancelSend(); + break; default: - break; + break; } } @@ -407,56 +406,56 @@ void CPjSSLSocket::RunL() { switch (state_) { case SSL_STATE_CONNECTING: - if (iStatus != KErrNone) { - CleanupSubObjects(); - state_ = SSL_STATE_NULL; - /* Dispatch connect failure notification */ - if (cb_) (*cb_)(iStatus.Int(), key_); - } else { - RSocket &rSock = ((CPjSocket*)sock_)->Socket(); - - /* Get local addr */ - rSock.LocalName(local_addr_); - - /* Prepare and start handshake */ - securesock_ = CSecureSocket::NewL(rSock, ssl_proto_); - securesock_->SetDialogMode(EDialogModeAttended); - if (servername_.Length() > 0) - securesock_->SetOpt(KSoSSLDomainName, KSolInetSSL, - servername_); - if (ciphers_.Length() > 0) - securesock_->SetAvailableCipherSuites(ciphers_); - - // FlushSessionCache() seems to also fire signals to all - // completed AOs (something like CActiveScheduler::RunIfReady()) - // which may cause problem, e.g: we've experienced that when - // SSL timeout is set to 1s, the SSL timeout timer fires up - // at this point and securesock_ instance gets deleted here! - // So be careful using this. And we don't think we need it here. - //securesock_->FlushSessionCache(); - - securesock_->StartClientHandshake(iStatus); - SetActive(); - state_ = SSL_STATE_HANDSHAKING; - } - break; + if (iStatus != KErrNone) { + CleanupSubObjects(); + state_ = SSL_STATE_NULL; + /* Dispatch connect failure notification */ + if (cb_) (*cb_)(iStatus.Int(), key_); + } else { + RSocket &rSock = ((CPjSocket*)sock_)->Socket(); + + /* Get local addr */ + rSock.LocalName(local_addr_); + + /* Prepare and start handshake */ + securesock_ = CSecureSocket::NewL(rSock, ssl_proto_); + securesock_->SetDialogMode(EDialogModeAttended); + if (servername_.Length() > 0) + securesock_->SetOpt(KSoSSLDomainName, KSolInetSSL, + servername_); + if (ciphers_.Length() > 0) + securesock_->SetAvailableCipherSuites(ciphers_); + + // FlushSessionCache() seems to also fire signals to all + // completed AOs (something like CActiveScheduler::RunIfReady()) + // which may cause problem, e.g: we've experienced that when + // SSL timeout is set to 1s, the SSL timeout timer fires up + // at this point and securesock_ instance gets deleted here! + // So be careful using this. And we don't think we need it here. + //securesock_->FlushSessionCache(); + + securesock_->StartClientHandshake(iStatus); + SetActive(); + state_ = SSL_STATE_HANDSHAKING; + } + break; case SSL_STATE_HANDSHAKING: - if (iStatus == KErrNone) { - state_ = SSL_STATE_ESTABLISHED; - } else { - state_ = SSL_STATE_NULL; - CleanupSubObjects(); - } - /* Dispatch connect status notification */ - if (cb_) (*cb_)(iStatus.Int(), key_); - break; + if (iStatus == KErrNone) { + state_ = SSL_STATE_ESTABLISHED; + } else { + state_ = SSL_STATE_NULL; + CleanupSubObjects(); + } + /* Dispatch connect status notification */ + if (cb_) (*cb_)(iStatus.Int(), key_); + break; case SSL_STATE_ESTABLISHED: - /* Dispatch data sent notification */ - if (cb_) (*cb_)(iStatus.Int(), key_); - break; + /* Dispatch data sent notification */ + if (cb_) (*cb_)(iStatus.Int(), key_); + break; default: - pj_assert(0); - break; + pj_assert(0); + break; } } @@ -466,25 +465,25 @@ class CPjTimer : public CActive { public: CPjTimer(const pj_time_val *delay, CPjTimer_cb cb, void *user_data) : - CActive(0), cb_(cb), user_data_(user_data) + CActive(0), cb_(cb), user_data_(user_data) { - CActiveScheduler::Add(this); - - rtimer_.CreateLocal(); - pj_int32_t interval = PJ_TIME_VAL_MSEC(*delay) * 1000; - if (interval < 0) { - interval = 0; - } - rtimer_.After(iStatus, interval); - SetActive(); + CActiveScheduler::Add(this); + + rtimer_.CreateLocal(); + pj_int32_t interval = PJ_TIME_VAL_MSEC(*delay) * 1000; + if (interval < 0) { + interval = 0; + } + rtimer_.After(iStatus, interval); + SetActive(); } ~CPjTimer() { Cancel(); } -private: - RTimer rtimer_; - CPjTimer_cb cb_; - void *user_data_; +private: + RTimer rtimer_; + CPjTimer_cb cb_; + void *user_data_; void RunL() { if (cb_) (*cb_)(user_data_); } void DoCancel() { rtimer_.Cancel(); } @@ -494,31 +493,31 @@ class CPjTimer : public CActive * Structure of recv/read state. */ typedef struct read_state_t { - TPtr8 *read_buf; - TPtr8 *orig_buf; - pj_uint32_t flags; + TPtr8 *read_buf; + TPtr8 *orig_buf; + pj_uint32_t flags; } read_state_t; /* * Structure of send/write data. */ typedef struct write_data_t { - pj_size_t len; - pj_ioqueue_op_key_t *key; - pj_size_t data_len; - char data[1]; + pj_size_t len; + pj_ioqueue_op_key_t *key; + pj_size_t data_len; + char data[1]; } write_data_t; /* * Structure of send/write state. */ typedef struct write_state_t { - char *buf; - pj_size_t max_len; - char *start; - pj_size_t len; - write_data_t *current_data; - TPtrC8 send_ptr; + char *buf; + pj_size_t max_len; + char *start; + pj_size_t len; + write_data_t *current_data; + TPtrC8 send_ptr; } write_state_t; /* @@ -526,32 +525,32 @@ typedef struct write_state_t { */ struct pj_ssl_sock_t { - pj_pool_t *pool; - pj_ssl_sock_cb cb; - void *user_data; + pj_pool_t *pool; + pj_ssl_sock_cb cb; + void *user_data; - pj_bool_t established; - write_state_t write_state; - read_state_t read_state; - CPjTimer *connect_timer; + pj_bool_t established; + write_state_t write_state; + read_state_t read_state; + CPjTimer *connect_timer; - CPjSSLSocket *sock; - int sock_af; - int sock_type; - pj_sockaddr local_addr; - pj_sockaddr rem_addr; + CPjSSLSocket *sock; + int sock_af; + int sock_type; + pj_sockaddr local_addr; + pj_sockaddr rem_addr; /* QoS settings */ - pj_qos_type qos_type; - pj_qos_params qos_params; - pj_bool_t qos_ignore_error; + pj_qos_type qos_type; + pj_qos_params qos_params; + pj_bool_t qos_ignore_error; - pj_ssl_sock_proto proto; - pj_time_val timeout; - pj_str_t servername; - pj_str_t ciphers; - pj_ssl_cert_info remote_cert_info; + pj_ssl_sock_proto proto; + pj_time_val timeout; + pj_str_t servername; + pj_str_t ciphers; + pj_ssl_cert_info remote_cert_info; }; @@ -564,29 +563,29 @@ static pj_str_t get_cert_name(char *buf, unsigned buf_len, p = (TUint8*)buf; for(i = 0; i < name.Count(); ++i) { - const CX520AttributeTypeAndValue &attr = name.Element(i); - - /* Print element separator */ - *p++ = '/'; - if (0 == --l) break; - - /* Print the type. */ - TPtr8 type(p, l); - type.Copy(attr.Type()); - p += type.Length(); - l -= type.Length(); - if (0 >= --l) break; - - /* Print equal sign */ - *p++ = '='; - if (0 == --l) break; - - /* Print the value. Let's just get the raw data here */ - TPtr8 value(p, l); - value.Copy(attr.EncodedValue().Mid(2)); - p += value.Length(); - l -= value.Length(); - if (0 >= --l) break; + const CX520AttributeTypeAndValue &attr = name.Element(i); + + /* Print element separator */ + *p++ = '/'; + if (0 == --l) break; + + /* Print the type. */ + TPtr8 type(p, l); + type.Copy(attr.Type()); + p += type.Length(); + l -= type.Length(); + if (0 >= --l) break; + + /* Print equal sign */ + *p++ = '='; + if (0 == --l) break; + + /* Print the value. Let's just get the raw data here */ + TPtr8 value(p, l); + value.Copy(attr.EncodedValue().Mid(2)); + p += value.Length(); + l -= value.Length(); + if (0 >= --l) break; } pj_str_t src; @@ -616,40 +615,40 @@ static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, /* Serial number */ len = x->SerialNumber().Length(); if (len > sizeof(ci->serial_no)) - len = sizeof(ci->serial_no); + len = sizeof(ci->serial_no); pj_memcpy(ci->serial_no + sizeof(ci->serial_no) - len, x->SerialNumber().Ptr(), len); /* Subject */ { - HBufC *subject = NULL; - TRAPD(err, subject = x->SubjectL()); - if (err == KErrNone) { - TPtr16 ptr16(subject->Des()); - len = ptr16.Length(); - TPtr8 ptr8((TUint8*)pj_pool_alloc(pool, len), len); - ptr8.Copy(ptr16); - pj_strset(&ci->subject.cn, (char*)ptr8.Ptr(), ptr8.Length()); - } - pj_str_t tmp = get_cert_name(tmp_buf, tmp_buf_len, - x->SubjectName()); - pj_strdup(pool, &ci->subject.info, &tmp); + HBufC *subject = NULL; + TRAPD(err, subject = x->SubjectL()); + if (err == KErrNone) { + TPtr16 ptr16(subject->Des()); + len = ptr16.Length(); + TPtr8 ptr8((TUint8*)pj_pool_alloc(pool, len), len); + ptr8.Copy(ptr16); + pj_strset(&ci->subject.cn, (char*)ptr8.Ptr(), ptr8.Length()); + } + pj_str_t tmp = get_cert_name(tmp_buf, tmp_buf_len, + x->SubjectName()); + pj_strdup(pool, &ci->subject.info, &tmp); } /* Issuer */ { - HBufC *issuer = NULL; - TRAPD(err, issuer = x->IssuerL()); - if (err == KErrNone) { - TPtr16 ptr16(issuer->Des()); - len = ptr16.Length(); - TPtr8 ptr8((TUint8*)pj_pool_alloc(pool, len), len); - ptr8.Copy(ptr16); - pj_strset(&ci->issuer.cn, (char*)ptr8.Ptr(), ptr8.Length()); - } - pj_str_t tmp = get_cert_name(tmp_buf, tmp_buf_len, - x->IssuerName()); - pj_strdup(pool, &ci->issuer.info, &tmp); + HBufC *issuer = NULL; + TRAPD(err, issuer = x->IssuerL()); + if (err == KErrNone) { + TPtr16 ptr16(issuer->Des()); + len = ptr16.Length(); + TPtr8 ptr8((TUint8*)pj_pool_alloc(pool, len), len); + ptr8.Copy(ptr16); + pj_strset(&ci->issuer.cn, (char*)ptr8.Ptr(), ptr8.Length()); + } + pj_str_t tmp = get_cert_name(tmp_buf, tmp_buf_len, + x->IssuerName()); + pj_strdup(pool, &ci->issuer.info, &tmp); } /* Validity */ @@ -679,9 +678,9 @@ static void update_certs_info(pj_ssl_sock_t *ssock) /* Active remote certificate */ x = ssock->sock->GetPeerCert(); if (x) { - get_cert_info(ssock->pool, &ssock->remote_cert_info, x); + get_cert_info(ssock->pool, &ssock->remote_cert_info, x); } else { - pj_bzero(&ssock->remote_cert_info, sizeof(pj_ssl_cert_info)); + pj_bzero(&ssock->remote_cert_info, sizeof(pj_ssl_cert_info)); } } @@ -691,14 +690,14 @@ static unsigned ciphers_num_ = 0; static struct ciphers_t { pj_ssl_cipher id; - const char *name; + const char *name; } ciphers_[64]; /* * Get cipher list supported by SSL/TLS backend. */ PJ_DEF(pj_status_t) pj_ssl_cipher_get_availables (pj_ssl_cipher ciphers[], - unsigned *cipher_num) + unsigned *cipher_num) { unsigned i; @@ -716,20 +715,20 @@ PJ_DEF(pj_status_t) pj_ssl_cipher_get_availables (pj_ssl_cipher ciphers[], ciphers_num_ = ciphers_buf.Length() / 2; if (ciphers_num_ > PJ_ARRAY_SIZE(ciphers_)) - ciphers_num_ = PJ_ARRAY_SIZE(ciphers_); + ciphers_num_ = PJ_ARRAY_SIZE(ciphers_); for (i = 0; i < ciphers_num_; ++i) { ciphers_[i].id = (pj_ssl_cipher)(ciphers_buf[i*2]*10 + - ciphers_buf[i*2+1]); - ciphers_[i].name = get_cipher_name(ciphers_[i].id); - } + ciphers_buf[i*2+1]); + ciphers_[i].name = get_cipher_name(ciphers_[i].id); + } } delete secure_sock; } if (ciphers_num_ == 0) { - *cipher_num = 0; - return PJ_ENOTFOUND; + *cipher_num = 0; + return PJ_ENOTFOUND; } *cipher_num = PJ_MIN(*cipher_num, ciphers_num_); @@ -746,14 +745,14 @@ PJ_DEF(const char*) pj_ssl_cipher_name(pj_ssl_cipher cipher) unsigned i; if (ciphers_num_ == 0) { - pj_ssl_cipher c[1]; - i = 0; - pj_ssl_cipher_get_availables(c, &i); + pj_ssl_cipher c[1]; + i = 0; + pj_ssl_cipher_get_availables(c, &i); } - + for (i = 0; i < ciphers_num_; ++i) { - if (cipher == ciphers_[i].id) - return ciphers_[i].name; + if (cipher == ciphers_[i].id) + return ciphers_[i].name; } return NULL; @@ -766,9 +765,9 @@ PJ_DEF(pj_ssl_cipher) pj_ssl_cipher_id(const char *cipher_name) unsigned i; if (ciphers_num_ == 0) { - pj_ssl_cipher c[1]; - i = 0; - pj_ssl_cipher_get_availables(c, &i); + pj_ssl_cipher c[1]; + i = 0; + pj_ssl_cipher_get_availables(c, &i); } for (i = 0; i < ciphers_num_; ++i) { @@ -786,14 +785,14 @@ PJ_DEF(pj_bool_t) pj_ssl_cipher_is_supported(pj_ssl_cipher cipher) unsigned i; if (ciphers_num_ == 0) { - pj_ssl_cipher c[1]; - i = 0; - pj_ssl_cipher_get_availables(c, &i); + pj_ssl_cipher c[1]; + i = 0; + pj_ssl_cipher_get_availables(c, &i); } - + for (i = 0; i < ciphers_num_; ++i) { - if (cipher == ciphers_[i].id) - return PJ_TRUE; + if (cipher == ciphers_[i].id) + return PJ_TRUE; } return PJ_FALSE; @@ -804,8 +803,8 @@ PJ_DEF(pj_bool_t) pj_ssl_cipher_is_supported(pj_ssl_cipher cipher) * Create SSL socket instance. */ PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool, - const pj_ssl_sock_param *param, - pj_ssl_sock_t **p_ssock) + const pj_ssl_sock_param *param, + pj_ssl_sock_t **p_ssock) { pj_ssl_sock_t *ssock; @@ -817,7 +816,7 @@ PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool, /* Allocate write buffer */ ssock->write_state.buf = (char*)pj_pool_alloc(pool, - param->send_buffer_size); + param->send_buffer_size); ssock->write_state.max_len = param->send_buffer_size; ssock->write_state.start = ssock->write_state.buf; @@ -829,21 +828,21 @@ PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool, ssock->user_data = param->user_data; ssock->timeout = param->timeout; if (param->ciphers_num > 0) { - /* Cipher list in Symbian is represented as array of two-octets. */ - ssock->ciphers.slen = param->ciphers_num*2; - ssock->ciphers.ptr = (char*)pj_pool_alloc(pool, ssock->ciphers.slen); - pj_uint8_t *c = (pj_uint8_t*)ssock->ciphers.ptr; - for (unsigned i = 0; i < param->ciphers_num; ++i) { - *c++ = (pj_uint8_t)(param->ciphers[i] & 0xFF00) >> 8; - *c++ = (pj_uint8_t)(param->ciphers[i] & 0xFF); - } + /* Cipher list in Symbian is represented as array of two-octets. */ + ssock->ciphers.slen = param->ciphers_num*2; + ssock->ciphers.ptr = (char*)pj_pool_alloc(pool, ssock->ciphers.slen); + pj_uint8_t *c = (pj_uint8_t*)ssock->ciphers.ptr; + for (unsigned i = 0; i < param->ciphers_num; ++i) { + *c++ = (pj_uint8_t)(param->ciphers[i] & 0xFF00) >> 8; + *c++ = (pj_uint8_t)(param->ciphers[i] & 0xFF); + } } pj_strdup_with_null(pool, &ssock->servername, ¶m->server_name); ssock->qos_type = param->qos_type; ssock->qos_ignore_error = param->qos_ignore_error; pj_memcpy(&ssock->qos_params, ¶m->qos_params, - sizeof(param->qos_params)); + sizeof(param->qos_params)); /* Finally */ *p_ssock = ssock; @@ -853,23 +852,23 @@ PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool, PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files(pj_pool_t *pool, - const pj_str_t *CA_file, - const pj_str_t *cert_file, - const pj_str_t *privkey_file, - const pj_str_t *privkey_pass, - pj_ssl_cert_t **p_cert) + const pj_str_t *CA_file, + const pj_str_t *cert_file, + const pj_str_t *privkey_file, + const pj_str_t *privkey_pass, + pj_ssl_cert_t **p_cert) { return pj_ssl_cert_load_from_files2(pool, CA_file, NULL, cert_file, - privkey_file, privkey_pass, p_cert); + privkey_file, privkey_pass, p_cert); } PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files2(pj_pool_t *pool, - const pj_str_t *CA_file, - const pj_str_t *CA_path, - const pj_str_t *cert_file, - const pj_str_t *privkey_file, - const pj_str_t *privkey_pass, - pj_ssl_cert_t **p_cert) + const pj_str_t *CA_file, + const pj_str_t *CA_path, + const pj_str_t *cert_file, + const pj_str_t *privkey_file, + const pj_str_t *privkey_pass, + pj_ssl_cert_t **p_cert) { PJ_UNUSED_ARG(pool); PJ_UNUSED_ARG(CA_file); @@ -885,9 +884,9 @@ PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files2(pj_pool_t *pool, * Set SSL socket credential. */ PJ_DEF(pj_status_t) pj_ssl_sock_set_certificate( - pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_ssl_cert_t *cert) + pj_ssl_sock_t *ssock, + pj_pool_t *pool, + const pj_ssl_cert_t *cert) { PJ_UNUSED_ARG(ssock); PJ_UNUSED_ARG(pool); @@ -921,7 +920,7 @@ PJ_DEF(pj_status_t) pj_ssl_sock_close(pj_ssl_sock_t *ssock) * Associate arbitrary data with the SSL socket. */ PJ_DEF(pj_status_t) pj_ssl_sock_set_user_data (pj_ssl_sock_t *ssock, - void *user_data) + void *user_data) { PJ_ASSERT_RETURN(ssock, PJ_EINVAL); @@ -929,7 +928,7 @@ PJ_DEF(pj_status_t) pj_ssl_sock_set_user_data (pj_ssl_sock_t *ssock, return PJ_SUCCESS; } - + /* * Retrieve the user data previously associated with this SSL @@ -947,7 +946,7 @@ PJ_DEF(void*) pj_ssl_sock_get_user_data(pj_ssl_sock_t *ssock) * Retrieve the local address and port used by specified SSL socket. */ PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock, - pj_ssl_sock_info *info) + pj_ssl_sock_info *info) { PJ_ASSERT_RETURN(ssock && info, PJ_EINVAL); @@ -957,27 +956,27 @@ PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock, /* Local address */ if (ssock->sock) { - const TInetAddr* local_addr_ = ssock->sock->GetLocalAddr(); - int addrlen = sizeof(pj_sockaddr); - pj_status_t status; - - status = PjSymbianOS::Addr2pj(*local_addr_, info->local_addr, &addrlen); - if (status != PJ_SUCCESS) - return status; + const TInetAddr* local_addr_ = ssock->sock->GetLocalAddr(); + int addrlen = sizeof(pj_sockaddr); + pj_status_t status; + + status = PjSymbianOS::Addr2pj(*local_addr_, info->local_addr, &addrlen); + if (status != PJ_SUCCESS) + return status; } else { - pj_sockaddr_cp(&info->local_addr, &ssock->local_addr); + pj_sockaddr_cp(&info->local_addr, &ssock->local_addr); } if (info->established) { - /* Cipher suite */ - TBuf8<4> cipher; - if (ssock->sock->GetCipher(cipher) == KErrNone) { - info->cipher = (pj_ssl_cipher)cipher[1]; - } + /* Cipher suite */ + TBuf8<4> cipher; + if (ssock->sock->GetCipher(cipher) == KErrNone) { + info->cipher = (pj_ssl_cipher)cipher[1]; + } - /* Remote address */ + /* Remote address */ pj_sockaddr_cp((pj_sockaddr_t*)&info->remote_addr, - (pj_sockaddr_t*)&ssock->rem_addr); + (pj_sockaddr_t*)&ssock->rem_addr); /* Certificates info */ info->remote_cert_info = &ssock->remote_cert_info; @@ -994,16 +993,16 @@ PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock, * Starts read operation on this SSL socket. */ PJ_DEF(pj_status_t) pj_ssl_sock_start_read (pj_ssl_sock_t *ssock, - pj_pool_t *pool, - unsigned buff_size, - pj_uint32_t flags) + pj_pool_t *pool, + unsigned buff_size, + pj_uint32_t flags) { PJ_ASSERT_RETURN(ssock && pool && buff_size, PJ_EINVAL); PJ_ASSERT_RETURN(ssock->established, PJ_EINVALIDOP); /* Reading is already started */ if (ssock->read_state.orig_buf) { - return PJ_SUCCESS; + return PJ_SUCCESS; } void *readbuf[1]; @@ -1020,70 +1019,70 @@ static void read_cb(int err, void *key) /* Check connection status */ if (err == KErrEof || !PjSymbianOS::Instance()->IsConnectionUp() || - !ssock->established) + !ssock->established) { - status = PJ_EEOF; + status = PJ_EEOF; } /* Notify data arrival */ if (ssock->cb.on_data_read) { - pj_size_t remainder = 0; - char *data = (char*)ssock->read_state.orig_buf->Ptr(); - pj_size_t data_len = ssock->read_state.read_buf->Length() + - ssock->read_state.read_buf->Ptr() - - ssock->read_state.orig_buf->Ptr(); - - if (data_len > 0) { - /* Notify received data */ - pj_bool_t ret = (*ssock->cb.on_data_read)(ssock, data, data_len, - status, &remainder); - if (!ret) { - /* We've been destroyed */ - return; - } - - /* Calculate available data for next READ operation */ - if (remainder > 0) { - pj_size_t data_maxlen = ssock->read_state.orig_buf->MaxLength(); - - /* There is some data left unconsumed by application, we give - * smaller buffer for next READ operation. - */ - ssock->read_state.read_buf->Set((TUint8*)data+remainder, 0, - data_maxlen - remainder); - } else { - /* Give all buffer for next READ operation. - */ - ssock->read_state.read_buf->Set(*ssock->read_state.orig_buf); - } - } + pj_size_t remainder = 0; + char *data = (char*)ssock->read_state.orig_buf->Ptr(); + pj_size_t data_len = ssock->read_state.read_buf->Length() + + ssock->read_state.read_buf->Ptr() - + ssock->read_state.orig_buf->Ptr(); + + if (data_len > 0) { + /* Notify received data */ + pj_bool_t ret = (*ssock->cb.on_data_read)(ssock, data, data_len, + status, &remainder); + if (!ret) { + /* We've been destroyed */ + return; + } + + /* Calculate available data for next READ operation */ + if (remainder > 0) { + pj_size_t data_maxlen = ssock->read_state.orig_buf->MaxLength(); + + /* There is some data left unconsumed by application, we give + * smaller buffer for next READ operation. + */ + ssock->read_state.read_buf->Set((TUint8*)data+remainder, 0, + data_maxlen - remainder); + } else { + /* Give all buffer for next READ operation. + */ + ssock->read_state.read_buf->Set(*ssock->read_state.orig_buf); + } + } } if (status == PJ_SUCCESS) { - /* Perform the "next" READ operation */ - CPjSSLSocketReader *reader = ssock->sock->GetReader(); - ssock->read_state.read_buf->SetLength(0); - status = reader->Read(&read_cb, ssock, *ssock->read_state.read_buf, - ssock->read_state.flags); + /* Perform the "next" READ operation */ + CPjSSLSocketReader *reader = ssock->sock->GetReader(); + ssock->read_state.read_buf->SetLength(0); + status = reader->Read(&read_cb, ssock, *ssock->read_state.read_buf, + ssock->read_state.flags); } /* Connection closed or something goes wrong */ if (status != PJ_SUCCESS && status != PJ_EPENDING) { - /* Notify error */ - if (ssock->cb.on_data_read) { - pj_bool_t ret = (*ssock->cb.on_data_read)(ssock, NULL, 0, - status, NULL); - if (!ret) { - /* We've been destroyed */ - return; - } - } - - delete ssock->read_state.read_buf; - delete ssock->read_state.orig_buf; - ssock->read_state.read_buf = NULL; - ssock->read_state.orig_buf = NULL; - ssock->established = PJ_FALSE; + /* Notify error */ + if (ssock->cb.on_data_read) { + pj_bool_t ret = (*ssock->cb.on_data_read)(ssock, NULL, 0, + status, NULL); + if (!ret) { + /* We've been destroyed */ + return; + } + } + + delete ssock->read_state.read_buf; + delete ssock->read_state.orig_buf; + ssock->read_state.read_buf = NULL; + ssock->read_state.orig_buf = NULL; + ssock->established = PJ_FALSE; } } @@ -1093,10 +1092,10 @@ static void read_cb(int err, void *key) * does not have to allocate the buffers. */ PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock, - pj_pool_t *pool, - unsigned buff_size, - void *readbuf[], - pj_uint32_t flags) + pj_pool_t *pool, + unsigned buff_size, + void *readbuf[], + pj_uint32_t flags) { PJ_ASSERT_RETURN(ssock && buff_size && readbuf, PJ_EINVAL); PJ_ASSERT_RETURN(ssock->established, PJ_EINVALIDOP); @@ -1106,7 +1105,7 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock, /* Reading is already started */ if (ssock->read_state.orig_buf) { - return PJ_SUCCESS; + return PJ_SUCCESS; } PJ_UNUSED_ARG(pool); @@ -1114,7 +1113,7 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock, /* Get reader instance */ CPjSSLSocketReader *reader = ssock->sock->GetReader(); if (!reader) - return PJ_ENOMEM; + return PJ_ENOMEM; /* We manage two buffer pointers here: * 1. orig_buf keeps the orginal buffer address (and its max length). @@ -1127,15 +1126,15 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock, pj_status_t status; status = reader->Read(&read_cb, ssock, *ssock->read_state.read_buf, - ssock->read_state.flags); + ssock->read_state.flags); if (status != PJ_SUCCESS && status != PJ_EPENDING) { - delete ssock->read_state.read_buf; - delete ssock->read_state.orig_buf; - ssock->read_state.read_buf = NULL; - ssock->read_state.orig_buf = NULL; - - return status; + delete ssock->read_state.read_buf; + delete ssock->read_state.orig_buf; + ssock->read_state.read_buf = NULL; + ssock->read_state.orig_buf = NULL; + + return status; } return PJ_SUCCESS; @@ -1147,9 +1146,9 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock, * callback instead. */ PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom (pj_ssl_sock_t *ssock, - pj_pool_t *pool, - unsigned buff_size, - pj_uint32_t flags) + pj_pool_t *pool, + unsigned buff_size, + pj_uint32_t flags) { PJ_UNUSED_ARG(ssock); PJ_UNUSED_ARG(pool); @@ -1164,10 +1163,10 @@ PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom (pj_ssl_sock_t *ssock, * new ones. */ PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom2 (pj_ssl_sock_t *ssock, - pj_pool_t *pool, - unsigned buff_size, - void *readbuf[], - pj_uint32_t flags) + pj_pool_t *pool, + unsigned buff_size, + void *readbuf[], + pj_uint32_t flags) { PJ_UNUSED_ARG(ssock); PJ_UNUSED_ARG(pool); @@ -1184,10 +1183,10 @@ static void send_cb(int err, void *key) /* Check connection status */ if (err != KErrNone || !PjSymbianOS::Instance()->IsConnectionUp() || - !ssock->established) + !ssock->established) { - ssock->established = PJ_FALSE; - return; + ssock->established = PJ_FALSE; + return; } /* Remove sent data from buffer */ @@ -1199,17 +1198,17 @@ static void send_cb(int err, void *key) /* Let's check if there is pending data to send */ if (st->len) { - write_data_t *wdata = (write_data_t*)st->start; - pj_status_t status; - - st->send_ptr.Set((TUint8*)wdata->data, (TInt)wdata->data_len); - st->current_data = wdata; - status = ssock->sock->Send(&send_cb, ssock, st->send_ptr, 0); - if (status != PJ_EPENDING) { - ssock->established = PJ_FALSE; - st->len = 0; - return; - } + write_data_t *wdata = (write_data_t*)st->start; + pj_status_t status; + + st->send_ptr.Set((TUint8*)wdata->data, (TInt)wdata->data_len); + st->current_data = wdata; + status = ssock->sock->Send(&send_cb, ssock, st->send_ptr, 0); + if (status != PJ_EPENDING) { + ssock->established = PJ_FALSE; + st->len = 0; + return; + } } else { /* Buffer empty, reset the start position */ st->start = st->buf; @@ -1220,30 +1219,30 @@ static void send_cb(int err, void *key) * Send data using the socket. */ PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t *size, - unsigned flags) + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t *size, + unsigned flags) { PJ_CHECK_STACK(); PJ_ASSERT_RETURN(ssock && data && size, PJ_EINVAL); PJ_ASSERT_RETURN(ssock->write_state.max_len == 0 || - ssock->write_state.max_len >= (pj_size_t)*size, - PJ_ETOOSMALL); + ssock->write_state.max_len >= (pj_size_t)*size, + PJ_ETOOSMALL); /* Check connection status */ if (!PjSymbianOS::Instance()->IsConnectionUp() || !ssock->established) { - ssock->established = PJ_FALSE; - return PJ_ECANCELLED; + ssock->established = PJ_FALSE; + return PJ_ECANCELLED; } write_state_t *st = &ssock->write_state; /* Synchronous mode */ if (st->max_len == 0) { - st->send_ptr.Set((TUint8*)data, (TInt)*size); - return ssock->sock->SendSync(st->send_ptr, flags); + st->send_ptr.Set((TUint8*)data, (TInt)*size); + return ssock->sock->SendSync(st->send_ptr, flags); } /* CSecureSocket only allows one outstanding send operation, so @@ -1258,7 +1257,7 @@ PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock, /* Block until there is buffer slot available and contiguous! */ while (st->start + st->len + needed_len > st->buf + st->max_len) { - pj_symbianos_poll(-1, -1); + pj_symbianos_poll(-1, -1); } /* Push back the send data into the buffer */ @@ -1272,17 +1271,17 @@ PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock, /* If no outstanding send, send it */ if (st->current_data == NULL) { - pj_status_t status; - - wdata = (write_data_t*)st->start; - st->current_data = wdata; - st->send_ptr.Set((TUint8*)wdata->data, (TInt)wdata->data_len); - status = ssock->sock->Send(&send_cb, ssock, st->send_ptr, flags); - - if (status != PJ_EPENDING) { - *size = -status; - return status; - } + pj_status_t status; + + wdata = (write_data_t*)st->start; + st->current_data = wdata; + st->send_ptr.Set((TUint8*)wdata->data, (TInt)wdata->data_len); + status = ssock->sock->Send(&send_cb, ssock, st->send_ptr, flags); + + if (status != PJ_EPENDING) { + *size = -status; + return status; + } } return PJ_SUCCESS; @@ -1292,12 +1291,12 @@ PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock, * Send datagram using the socket. */ PJ_DEF(pj_status_t) pj_ssl_sock_sendto (pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - const void *data, - pj_ssize_t *size, - unsigned flags, - const pj_sockaddr_t *addr, - int addr_len) + pj_ioqueue_op_key_t *send_key, + const void *data, + pj_ssize_t *size, + unsigned flags, + const pj_sockaddr_t *addr, + int addr_len) { PJ_UNUSED_ARG(ssock); PJ_UNUSED_ARG(send_key); @@ -1313,9 +1312,9 @@ PJ_DEF(pj_status_t) pj_ssl_sock_sendto (pj_ssl_sock_t *ssock, * Starts asynchronous socket accept() operations on this SSL socket. */ PJ_DEF(pj_status_t) pj_ssl_sock_start_accept (pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_sockaddr_t *local_addr, - int addr_len) + pj_pool_t *pool, + const pj_sockaddr_t *local_addr, + int addr_len) { PJ_UNUSED_ARG(ssock); PJ_UNUSED_ARG(pool); @@ -1331,26 +1330,26 @@ static void connect_cb(int err, void *key) pj_status_t status; if (ssock->connect_timer) { - delete ssock->connect_timer; - ssock->connect_timer = NULL; + delete ssock->connect_timer; + ssock->connect_timer = NULL; } status = (err == KErrNone)? PJ_SUCCESS : PJ_RETURN_OS_ERROR(err); if (status == PJ_SUCCESS) { - ssock->established = PJ_TRUE; - update_certs_info(ssock); + ssock->established = PJ_TRUE; + update_certs_info(ssock); } else { - delete ssock->sock; - ssock->sock = NULL; - if (err == KErrTimedOut) status = PJ_ETIMEDOUT; + delete ssock->sock; + ssock->sock = NULL; + if (err == KErrTimedOut) status = PJ_ETIMEDOUT; } if (ssock->cb.on_connect_complete) { - pj_bool_t ret = (*ssock->cb.on_connect_complete)(ssock, status); - if (!ret) { - /* We've been destroyed */ - return; - } + pj_bool_t ret = (*ssock->cb.on_connect_complete)(ssock, status); + if (!ret) { + /* We've been destroyed */ + return; + } } } @@ -1365,84 +1364,84 @@ static void connect_timer_cb(void *key) * the \a on_connect_complete() callback will be called. */ PJ_DEF(pj_status_t) pj_ssl_sock_start_connect (pj_ssl_sock_t *ssock, - pj_pool_t *pool, - const pj_sockaddr_t *localaddr, - const pj_sockaddr_t *remaddr, - int addr_len) + pj_pool_t *pool, + const pj_sockaddr_t *localaddr, + const pj_sockaddr_t *remaddr, + int addr_len) { CPjSSLSocket *sock = NULL; pj_status_t status; PJ_ASSERT_RETURN(ssock && pool && localaddr && remaddr && addr_len, - PJ_EINVAL); + PJ_EINVAL); /* Check connection status */ PJ_SYMBIAN_CHECK_CONNECTION(); if (ssock->sock != NULL) { - CPjSSLSocket::ssl_state state = ssock->sock->GetState(); - switch (state) { - case CPjSSLSocket::SSL_STATE_ESTABLISHED: - return PJ_SUCCESS; - default: - return PJ_EPENDING; - } + CPjSSLSocket::ssl_state state = ssock->sock->GetState(); + switch (state) { + case CPjSSLSocket::SSL_STATE_ESTABLISHED: + return PJ_SUCCESS; + default: + return PJ_EPENDING; + } } /* Set SSL protocol */ TPtrC8 proto; if (ssock->proto == PJ_SSL_SOCK_PROTO_DEFAULT) - ssock->proto = PJ_SSL_SOCK_PROTO_TLS1; + ssock->proto = PJ_SSL_SOCK_PROTO_TLS1; /* CSecureSocket only support TLS1.0 and SSL3.0 */ if (ssock->proto & PJ_SSL_SOCK_PROTO_TLS1==PJ_SSL_SOCK_PROTO_TLS1) { - proto.Set((const TUint8*)"TLS1.0", 6); + proto.Set((const TUint8*)"TLS1.0", 6); } else if (ssock->proto & PJ_SSL_SOCK_PROTO_SSL3==PJ_SSL_SOCK_PROTO_SSL3) { - proto.Set((const TUint8*)"SSL3.0", 6); + proto.Set((const TUint8*)"SSL3.0", 6); } else { - return PJ_ENOTSUP; + return PJ_ENOTSUP; } /* Prepare addresses */ TInetAddr localaddr_, remaddr_; status = PjSymbianOS::pj2Addr(*(pj_sockaddr*)localaddr, addr_len, - localaddr_); + localaddr_); if (status != PJ_SUCCESS) - return status; + return status; status = PjSymbianOS::pj2Addr(*(pj_sockaddr*)remaddr, addr_len, - remaddr_); + remaddr_); if (status != PJ_SUCCESS) - return status; + return status; pj_sockaddr_cp((pj_sockaddr_t*)&ssock->rem_addr, remaddr); /* Init SSL engine */ TRAPD(err, sock = CPjSSLSocket::NewL(proto, ssock->qos_type, - ssock->qos_params)); + ssock->qos_params)); if (err != KErrNone) - return PJ_ENOMEM; + return PJ_ENOMEM; if (ssock->timeout.sec != 0 || ssock->timeout.msec != 0) { - ssock->connect_timer = new CPjTimer(&ssock->timeout, - &connect_timer_cb, ssock); + ssock->connect_timer = new CPjTimer(&ssock->timeout, + &connect_timer_cb, ssock); } /* Convert server name to Symbian descriptor */ TPtrC8 servername_((TUint8*)ssock->servername.ptr, - ssock->servername.slen); + ssock->servername.slen); /* Convert cipher list to Symbian descriptor */ TPtrC8 ciphers_((TUint8*)ssock->ciphers.ptr, - ssock->ciphers.slen); + ssock->ciphers.slen); /* Try to connect */ status = sock->Connect(&connect_cb, ssock, localaddr_, remaddr_, - servername_, ciphers_); + servername_, ciphers_); if (status != PJ_SUCCESS && status != PJ_EPENDING) { - delete sock; - return status; + delete sock; + return status; } ssock->sock = sock; diff --git a/pjlib/src/pj/string.c b/pjlib/src/pj/string.c index d4a5bf4d1e..72900794c6 100644 --- a/pjlib/src/pj/string.c +++ b/pjlib/src/pj/string.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,13 +34,13 @@ PJ_DEF(pj_ssize_t) pj_strspn(const pj_str_t *str, const pj_str_t *set_char) { pj_ssize_t i, j, count = 0; for (i = 0; i < str->slen; i++) { - if (count != i) - break; + if (count != i) + break; - for (j = 0; j < set_char->slen; j++) { - if (str->ptr[i] == set_char->ptr[j]) - count++; - } + for (j = 0; j < set_char->slen; j++) { + if (str->ptr[i] == set_char->ptr[j]) + count++; + } } return count; } @@ -51,13 +50,13 @@ PJ_DEF(pj_ssize_t) pj_strspn2(const pj_str_t *str, const char *set_char) { pj_ssize_t i, j, count = 0; for (i = 0; i < str->slen; i++) { - if (count != i) - break; + if (count != i) + break; - for (j = 0; set_char[j] != 0; j++) { - if (str->ptr[i] == set_char[j]) - count++; - } + for (j = 0; set_char[j] != 0; j++) { + if (str->ptr[i] == set_char[j]) + count++; + } } return count; } @@ -67,10 +66,10 @@ PJ_DEF(pj_ssize_t) pj_strcspn(const pj_str_t *str, const pj_str_t *set_char) { pj_ssize_t i, j; for (i = 0; i < str->slen; i++) { - for (j = 0; j < set_char->slen; j++) { - if (str->ptr[i] == set_char->ptr[j]) - return i; - } + for (j = 0; j < set_char->slen; j++) { + if (str->ptr[i] == set_char->ptr[j]) + return i; + } } return i; } @@ -80,17 +79,17 @@ PJ_DEF(pj_ssize_t) pj_strcspn2(const pj_str_t *str, const char *set_char) { pj_ssize_t i, j; for (i = 0; i < str->slen; i++) { - for (j = 0; set_char[j] != 0; j++) { - if (str->ptr[i] == set_char[j]) - return i; - } + for (j = 0; set_char[j] != 0; j++) { + if (str->ptr[i] == set_char[j]) + return i; + } } return i; } PJ_DEF(pj_ssize_t) pj_strtok(const pj_str_t *str, const pj_str_t *delim, - pj_str_t *tok, pj_size_t start_idx) + pj_str_t *tok, pj_size_t start_idx) { pj_ssize_t str_idx; @@ -99,7 +98,7 @@ PJ_DEF(pj_ssize_t) pj_strtok(const pj_str_t *str, const pj_str_t *delim, tok->slen = 0; if ((str->slen <= 0) || ((pj_size_t)str->slen < start_idx)) { - return str->slen; + return str->slen; } tok->ptr = str->ptr + start_idx; @@ -107,7 +106,7 @@ PJ_DEF(pj_ssize_t) pj_strtok(const pj_str_t *str, const pj_str_t *delim, str_idx = pj_strspn(tok, delim); if (start_idx+str_idx == (pj_size_t)str->slen) { - return str->slen; + return str->slen; } tok->ptr += str_idx; tok->slen -= str_idx; @@ -118,7 +117,7 @@ PJ_DEF(pj_ssize_t) pj_strtok(const pj_str_t *str, const pj_str_t *delim, PJ_DEF(pj_ssize_t) pj_strtok2(const pj_str_t *str, const char *delim, - pj_str_t *tok, pj_size_t start_idx) + pj_str_t *tok, pj_size_t start_idx) { pj_ssize_t str_idx; @@ -126,7 +125,7 @@ PJ_DEF(pj_ssize_t) pj_strtok2(const pj_str_t *str, const char *delim, tok->slen = 0; if ((str->slen <= 0) || ((pj_size_t)str->slen < start_idx)) { - return str->slen; + return str->slen; } tok->ptr = str->ptr + start_idx; @@ -134,7 +133,7 @@ PJ_DEF(pj_ssize_t) pj_strtok2(const pj_str_t *str, const char *delim, str_idx = pj_strspn2(tok, delim); if (start_idx + str_idx == (pj_size_t)str->slen) { - return str->slen; + return str->slen; } tok->ptr += str_idx; tok->slen -= str_idx; @@ -152,18 +151,18 @@ PJ_DEF(char*) pj_strstr(const pj_str_t *str, const pj_str_t *substr) /* Check if the string is empty */ if (str->slen <= 0) - return NULL; + return NULL; /* Special case when substr is empty */ if (substr->slen <= 0) { - return (char*)str->ptr; + return (char*)str->ptr; } s = str->ptr; ends = str->ptr + str->slen - substr->slen; for (; s<=ends; ++s) { - if (pj_ansi_strncmp(s, substr->ptr, substr->slen)==0) - return (char*)s; + if (pj_ansi_strncmp(s, substr->ptr, substr->slen)==0) + return (char*)s; } return NULL; } @@ -177,18 +176,18 @@ PJ_DEF(char*) pj_stristr(const pj_str_t *str, const pj_str_t *substr) /* Check if the string is empty */ if (str->slen <= 0) - return NULL; + return NULL; /* Special case when substr is empty */ if (substr->slen == 0) { - return (char*)str->ptr; + return (char*)str->ptr; } s = str->ptr; ends = str->ptr + str->slen - substr->slen; for (; s<=ends; ++s) { - if (pj_ansi_strnicmp(s, substr->ptr, substr->slen)==0) - return (char*)s; + if (pj_ansi_strnicmp(s, substr->ptr, substr->slen)==0) + return (char*)s; } return NULL; } @@ -202,7 +201,7 @@ PJ_DEF(pj_str_t*) pj_strltrim( pj_str_t *str ) pj_assert(str->slen >= 0); while (p < end && pj_isspace(*p)) - ++p; + ++p; str->slen -= (p - str->ptr); str->ptr = p; return str; @@ -229,15 +228,15 @@ PJ_DEF(char*) pj_create_random_string(char *str, pj_size_t len) PJ_CHECK_STACK(); for (i=0; i> 24, p+0 ); - pj_val_to_hex_digit( (val & 0x00FF0000) >> 16, p+2 ); - pj_val_to_hex_digit( (val & 0x0000FF00) >> 8, p+4 ); - pj_val_to_hex_digit( (val & 0x000000FF) >> 0, p+6 ); - p += 8; + pj_uint32_t val = pj_rand(); + pj_val_to_hex_digit( (val & 0xFF000000) >> 24, p+0 ); + pj_val_to_hex_digit( (val & 0x00FF0000) >> 16, p+2 ); + pj_val_to_hex_digit( (val & 0x0000FF00) >> 8, p+4 ); + pj_val_to_hex_digit( (val & 0x000000FF) >> 0, p+6 ); + p += 8; } for (i=i * 8; islen; ++i) { - if (!pj_isdigit(str->ptr[i])) - break; - value = value * 10 + (str->ptr[i] - '0'); + if (!pj_isdigit(str->ptr[i])) + break; + value = value * 10 + (str->ptr[i] - '0'); } return value; } PJ_DEF(unsigned long) pj_strtoul2(const pj_str_t *str, pj_str_t *endptr, - unsigned base) + unsigned base) { unsigned long value; unsigned i; @@ -337,34 +336,34 @@ PJ_DEF(unsigned long) pj_strtoul2(const pj_str_t *str, pj_str_t *endptr, value = 0; if (base <= 10) { - for (i=0; i<(unsigned)str->slen; ++i) { - unsigned c = (str->ptr[i] - '0'); - if (c >= base) - break; - value = value * base + c; - } + for (i=0; i<(unsigned)str->slen; ++i) { + unsigned c = (str->ptr[i] - '0'); + if (c >= base) + break; + value = value * base + c; + } } else if (base == 16) { - for (i=0; i<(unsigned)str->slen; ++i) { - if (!pj_isxdigit(str->ptr[i])) - break; - value = value * 16 + pj_hex_digit_to_val(str->ptr[i]); - } + for (i=0; i<(unsigned)str->slen; ++i) { + if (!pj_isxdigit(str->ptr[i])) + break; + value = value * 16 + pj_hex_digit_to_val(str->ptr[i]); + } } else { - pj_assert(!"Unsupported base"); - i = 0; - value = 0xFFFFFFFFUL; + pj_assert(!"Unsupported base"); + i = 0; + value = 0xFFFFFFFFUL; } if (endptr) { - endptr->ptr = str->ptr + i; - endptr->slen = (str->slen < 0)? 0: (str->slen - i); + endptr->ptr = str->ptr + i; + endptr->slen = (str->slen < 0)? 0: (str->slen - i); } return value; } PJ_DEF(pj_status_t) pj_strtoul3(const pj_str_t *str, unsigned long *value, - unsigned base) + unsigned base) { pj_str_t s; unsigned i; @@ -381,51 +380,51 @@ PJ_DEF(pj_status_t) pj_strtoul3(const pj_str_t *str, unsigned long *value, pj_strltrim(&s); if (s.slen == 0 || s.ptr[0] < '0' || - (base <= 10 && (unsigned)s.ptr[0] > ('0' - 1) + base) || - (base == 16 && !pj_isxdigit(s.ptr[0]))) + (base <= 10 && (unsigned)s.ptr[0] > ('0' - 1) + base) || + (base == 16 && !pj_isxdigit(s.ptr[0]))) { return PJ_EINVAL; } *value = 0; if (base <= 10) { - for (i=0; i<(unsigned)s.slen; ++i) { - unsigned c = s.ptr[i] - '0'; - if (s.ptr[i] < '0' || (unsigned)s.ptr[i] > ('0' - 1) + base) { - break; - } - if (*value > PJ_MAXULONG / base) { - *value = PJ_MAXULONG; - return PJ_ETOOBIG; - } - - *value *= base; - if ((PJ_MAXULONG - *value) < c) { - *value = PJ_MAXULONG; - return PJ_ETOOBIG; - } - *value += c; - } + for (i=0; i<(unsigned)s.slen; ++i) { + unsigned c = s.ptr[i] - '0'; + if (s.ptr[i] < '0' || (unsigned)s.ptr[i] > ('0' - 1) + base) { + break; + } + if (*value > PJ_MAXULONG / base) { + *value = PJ_MAXULONG; + return PJ_ETOOBIG; + } + + *value *= base; + if ((PJ_MAXULONG - *value) < c) { + *value = PJ_MAXULONG; + return PJ_ETOOBIG; + } + *value += c; + } } else if (base == 16) { - for (i=0; i<(unsigned)s.slen; ++i) { - unsigned c = pj_hex_digit_to_val(s.ptr[i]); - if (!pj_isxdigit(s.ptr[i])) - break; - - if (*value > PJ_MAXULONG / base) { - *value = PJ_MAXULONG; - return PJ_ETOOBIG; - } - *value *= base; - if ((PJ_MAXULONG - *value) < c) { - *value = PJ_MAXULONG; - return PJ_ETOOBIG; - } - *value += c; - } + for (i=0; i<(unsigned)s.slen; ++i) { + unsigned c = pj_hex_digit_to_val(s.ptr[i]); + if (!pj_isxdigit(s.ptr[i])) + break; + + if (*value > PJ_MAXULONG / base) { + *value = PJ_MAXULONG; + return PJ_ETOOBIG; + } + *value *= base; + if ((PJ_MAXULONG - *value) < c) { + *value = PJ_MAXULONG; + return PJ_ETOOBIG; + } + *value += c; + } } else { - pj_assert(!"Unsupported base"); - return PJ_EINVAL; + pj_assert(!"Unsupported base"); + return PJ_EINVAL; } return PJ_SUCCESS; } @@ -439,33 +438,33 @@ PJ_DEF(float) pj_strtof(const pj_str_t *str) pj_assert(str->slen >= 0); if (str->slen <= 0) - return 0; + return 0; pdot = (char*)pj_memchr(str->ptr, '.', str->slen); part.ptr = str->ptr; part.slen = pdot ? pdot - str->ptr : str->slen; if (part.slen) - val = (float)pj_strtol(&part); + val = (float)pj_strtol(&part); else - val = 0; + val = 0; if (pdot) { - part.ptr = pdot + 1; - part.slen = (str->ptr + str->slen - pdot - 1); - if (part.slen) { - pj_str_t endptr; - float fpart, fdiv; - int i; - fpart = (float)pj_strtoul2(&part, &endptr, 10); - fdiv = 1.0; - for (i=0; i<(part.slen - endptr.slen); ++i) - fdiv = fdiv * 10; - if (val >= 0) - val += (fpart / fdiv); - else - val -= (fpart / fdiv); - } + part.ptr = pdot + 1; + part.slen = (str->ptr + str->slen - pdot - 1); + if (part.slen) { + pj_str_t endptr; + float fpart, fdiv; + int i; + fpart = (float)pj_strtoul2(&part, &endptr, 10); + fdiv = 1.0; + for (i=0; i<(part.slen - endptr.slen); ++i) + fdiv = fdiv * 10; + if (val >= 0) + val += (fpart / fdiv); + else + val -= (fpart / fdiv); + } } return val; } @@ -491,8 +490,8 @@ PJ_DEF(int) pj_utoa_pad( unsigned long val, char *buf, int min_dig, int pad) len = (int)(p-buf); while (len < min_dig) { - *p++ = (char)pad; - ++len; + *p++ = (char)pad; + ++len; } *p-- = '\0'; diff --git a/pjlib/src/pj/symbols.c b/pjlib/src/pj/symbols.c index ab83af956a..473c176ef7 100644 --- a/pjlib/src/pj/symbols.c +++ b/pjlib/src/pj/symbols.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,7 +34,7 @@ PJ_EXPORT_SYMBOL(pj_array_find) * config.h */ PJ_EXPORT_SYMBOL(pj_dump_config) - + /* * errno.h */ @@ -206,7 +205,7 @@ PJ_EXPORT_SYMBOL(pj_elapsed_nanosec) PJ_EXPORT_SYMBOL(pj_elapsed_cycle) #endif - + /* * pool.h */ diff --git a/pjlib/src/pj/timer.c b/pjlib/src/pj/timer.c index af9a8ef1f3..bf395222a0 100644 --- a/pjlib/src/pj/timer.c +++ b/pjlib/src/pj/timer.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * The PJLIB's timer heap is based (or more correctly, copied and modied) * from ACE library by Douglas C. Schmidt. ACE is an excellent OO framework @@ -38,10 +37,10 @@ #include #include -#define THIS_FILE "timer.c" +#define THIS_FILE "timer.c" -#define HEAP_PARENT(X) (X == 0 ? 0 : (((X) - 1) / 2)) -#define HEAP_LEFT(X) (((X)+(X))+1) +#define HEAP_PARENT(X) (X == 0 ? 0 : (((X) - 1) / 2)) +#define HEAP_LEFT(X) (((X)+(X))+1) #define DEFAULT_MAX_TIMED_OUT_PER_POLL (64) @@ -77,7 +76,7 @@ typedef struct pj_timer_entry_dup /** * The duplicate copy. */ - pj_timer_entry dup; + pj_timer_entry dup; /** * Pointer of the original timer entry. @@ -97,8 +96,8 @@ typedef struct pj_timer_entry_dup pj_grp_lock_t *_grp_lock; #if PJ_TIMER_DEBUG - const char *src_file; - int src_line; + const char *src_file; + int src_line; #endif } pj_timer_entry_dup; @@ -189,20 +188,20 @@ struct pj_timer_heap_t PJ_INLINE(void) lock_timer_heap( pj_timer_heap_t *ht ) { if (ht->lock) { - pj_lock_acquire(ht->lock); + pj_lock_acquire(ht->lock); } } PJ_INLINE(void) unlock_timer_heap( pj_timer_heap_t *ht ) { if (ht->lock) { - pj_lock_release(ht->lock); + pj_lock_release(ht->lock); } } static void copy_node( pj_timer_heap_t *ht, pj_size_t slot, - pj_timer_entry_dup *moved_node ) + pj_timer_entry_dup *moved_node ) { PJ_CHECK_STACK(); @@ -223,7 +222,7 @@ static pj_timer_id_t pop_freelist( pj_timer_heap_t *ht ) // The freelist values in the are negative, so we need // to negate them to get the next freelist "pointer." ht->timer_ids_freelist = - -ht->timer_ids[ht->timer_ids_freelist]; + -ht->timer_ids[ht->timer_ids_freelist]; return new_id; @@ -249,49 +248,49 @@ static void reheap_down(pj_timer_heap_t *ht, pj_timer_entry_dup *moved_node, while (child < ht->cur_size) { - // Choose the smaller of the two children. - if (child + 1 < ht->cur_size && - PJ_TIME_VAL_LT(ht->heap[child + 1]->_timer_value, - ht->heap[child]->_timer_value)) - { - child++; - } - - // Perform a if the child has a larger timeout value than - // the . - if (PJ_TIME_VAL_LT(ht->heap[child]->_timer_value, - moved_node->_timer_value)) + // Choose the smaller of the two children. + if (child + 1 < ht->cur_size && + PJ_TIME_VAL_LT(ht->heap[child + 1]->_timer_value, + ht->heap[child]->_timer_value)) { - copy_node( ht, slot, ht->heap[child]); - slot = child; - child = HEAP_LEFT(child); + child++; } - else - // We've found our location in the heap. - break; + + // Perform a if the child has a larger timeout value than + // the . + if (PJ_TIME_VAL_LT(ht->heap[child]->_timer_value, + moved_node->_timer_value)) + { + copy_node( ht, slot, ht->heap[child]); + slot = child; + child = HEAP_LEFT(child); + } + else + // We've found our location in the heap. + break; } copy_node( ht, slot, moved_node); } static void reheap_up( pj_timer_heap_t *ht, pj_timer_entry_dup *moved_node, - size_t slot, size_t parent) + size_t slot, size_t parent) { // Restore the heap property after an insertion. while (slot > 0) { - // If the parent node is greater than the we need - // to copy it down. - if (PJ_TIME_VAL_LT(moved_node->_timer_value, - ht->heap[parent]->_timer_value)) + // If the parent node is greater than the we need + // to copy it down. + if (PJ_TIME_VAL_LT(moved_node->_timer_value, + ht->heap[parent]->_timer_value)) { - copy_node(ht, slot, ht->heap[parent]); - slot = parent; - parent = HEAP_PARENT(slot); + copy_node(ht, slot, ht->heap[parent]); + slot = parent; + parent = HEAP_PARENT(slot); } - else - break; + else + break; } // Insert the new node into its proper resting place in the heap and @@ -313,23 +312,23 @@ static pj_timer_entry_dup * remove_node( pj_timer_heap_t *ht, size_t slot) // Set the ID if (GET_FIELD(removed_node, _timer_id) != - GET_ENTRY(removed_node)->_timer_id) + GET_ENTRY(removed_node)->_timer_id) { #if PJ_TIMER_DEBUG - PJ_LOG(3,(THIS_FILE, "Bug! Trying to remove entry %p from %s " - "line %d, which has been deallocated " - "without being cancelled", - GET_ENTRY(removed_node), - removed_node->src_file, - removed_node->src_line)); + PJ_LOG(3,(THIS_FILE, "Bug! Trying to remove entry %p from %s " + "line %d, which has been deallocated " + "without being cancelled", + GET_ENTRY(removed_node), + removed_node->src_file, + removed_node->src_line)); #else - PJ_LOG(3,(THIS_FILE, "Bug! Trying to remove entry %p " - "which has been deallocated " - "without being cancelled", - GET_ENTRY(removed_node))); + PJ_LOG(3,(THIS_FILE, "Bug! Trying to remove entry %p " + "which has been deallocated " + "without being cancelled", + GET_ENTRY(removed_node))); #endif #if ASSERT_IF_ENTRY_DESTROYED - pj_assert(removed_node->dup._timer_id==removed_node->entry->_timer_id); + pj_assert(removed_node->dup._timer_id==removed_node->entry->_timer_id); #endif } GET_ENTRY(removed_node)->_timer_id = -1; @@ -340,24 +339,24 @@ static pj_timer_entry_dup * remove_node( pj_timer_heap_t *ht, size_t slot) if (slot < ht->cur_size) { - pj_size_t parent; - pj_timer_entry_dup *moved_node = ht->heap[ht->cur_size]; - - // Move the end node to the location being removed and update - // the corresponding slot in the parallel array. - copy_node( ht, slot, moved_node); - - // If the time_value_> is great than or equal its - // parent it needs be moved down the heap. - parent = HEAP_PARENT (slot); - - if (PJ_TIME_VAL_GTE(moved_node->_timer_value, - ht->heap[parent]->_timer_value)) - { - reheap_down( ht, moved_node, slot, HEAP_LEFT(slot)); - } else { - reheap_up( ht, moved_node, slot, parent); - } + pj_size_t parent; + pj_timer_entry_dup *moved_node = ht->heap[ht->cur_size]; + + // Move the end node to the location being removed and update + // the corresponding slot in the parallel array. + copy_node( ht, slot, moved_node); + + // If the time_value_> is great than or equal its + // parent it needs be moved down the heap. + parent = HEAP_PARENT (slot); + + if (PJ_TIME_VAL_GTE(moved_node->_timer_value, + ht->heap[parent]->_timer_value)) + { + reheap_down( ht, moved_node, slot, HEAP_LEFT(slot)); + } else { + reheap_up( ht, moved_node, slot, parent); + } } #else pj_list_erase(removed_node); @@ -383,30 +382,30 @@ static pj_status_t grow_heap(pj_timer_heap_t *ht) #endif PJ_LOG(6,(THIS_FILE, "Growing heap size from %d to %d", - ht->max_size, new_size)); + ht->max_size, new_size)); // First grow the heap itself. new_heap = (pj_timer_entry_dup**) - pj_pool_calloc(ht->pool, new_size, sizeof(pj_timer_entry_dup*)); + pj_pool_calloc(ht->pool, new_size, sizeof(pj_timer_entry_dup*)); if (!new_heap) - return PJ_ENOMEM; + return PJ_ENOMEM; #if PJ_TIMER_USE_COPY // Grow the array of timer copies. new_timer_dups = (pj_timer_entry_dup*) - pj_pool_alloc(ht->pool, - sizeof(pj_timer_entry_dup) * new_size); + pj_pool_alloc(ht->pool, + sizeof(pj_timer_entry_dup) * new_size); if (!new_timer_dups) - return PJ_ENOMEM; + return PJ_ENOMEM; memcpy(new_timer_dups, ht->timer_dups, - ht->max_size * sizeof(pj_timer_entry_dup)); + ht->max_size * sizeof(pj_timer_entry_dup)); for (i = 0; i < ht->cur_size; i++) { - int idx = (int)(ht->heap[i] - ht->timer_dups); + int idx = (int)(ht->heap[i] - ht->timer_dups); // Point to the address in the new array pj_assert(idx >= 0 && idx < (int)ht->max_size); - new_heap[i] = &new_timer_dups[idx]; + new_heap[i] = &new_timer_dups[idx]; } ht->timer_dups = new_timer_dups; #else @@ -418,9 +417,9 @@ static pj_status_t grow_heap(pj_timer_heap_t *ht) pj_list_init(&ht->head_list); for (; tmp_dup != &ht->head_list; tmp_dup = tmp_dup->next) { - int slot = ht->timer_ids[GET_FIELD(tmp_dup, _timer_id)]; - new_dup = new_heap[slot]; - pj_list_push_back(&ht->head_list, new_dup); + int slot = ht->timer_ids[GET_FIELD(tmp_dup, _timer_id)]; + new_dup = new_heap[slot]; + pj_list_push_back(&ht->head_list, new_dup); } #endif @@ -430,9 +429,9 @@ static pj_status_t grow_heap(pj_timer_heap_t *ht) new_timer_ids = 0; new_timer_ids = (pj_timer_id_t*) - pj_pool_alloc(ht->pool, new_size * sizeof(pj_timer_id_t)); + pj_pool_alloc(ht->pool, new_size * sizeof(pj_timer_id_t)); if (!new_timer_ids) - return PJ_ENOMEM; + return PJ_ENOMEM; memcpy( new_timer_ids, ht->timer_ids, ht->max_size * sizeof(pj_timer_id_t)); @@ -441,7 +440,7 @@ static pj_status_t grow_heap(pj_timer_heap_t *ht) // And add the new elements to the end of the "freelist". for (i = ht->max_size; i < new_size; i++) - ht->timer_ids[i] = -((pj_timer_id_t) (i + 1)); + ht->timer_ids[i] = -((pj_timer_id_t) (i + 1)); ht->max_size = new_size; @@ -449,8 +448,8 @@ static pj_status_t grow_heap(pj_timer_heap_t *ht) } static pj_status_t insert_node(pj_timer_heap_t *ht, - pj_timer_entry *new_node, - const pj_time_val *future_time) + pj_timer_entry *new_node, + const pj_time_val *future_time) { pj_timer_entry_dup *timer_copy; @@ -459,9 +458,9 @@ static pj_status_t insert_node(pj_timer_heap_t *ht, #endif if (ht->cur_size + 2 >= ht->max_size) { - pj_status_t status = grow_heap(ht); - if (status != PJ_SUCCESS) - return status; + pj_status_t status = grow_heap(ht); + if (status != PJ_SUCCESS) + return status; } timer_copy = GET_TIMER(ht, new_node); @@ -482,24 +481,24 @@ static pj_status_t insert_node(pj_timer_heap_t *ht, reheap_up(ht, timer_copy, ht->cur_size, HEAP_PARENT(ht->cur_size)); #else if (ht->cur_size == 0) { - pj_list_push_back(&ht->head_list, timer_copy); + pj_list_push_back(&ht->head_list, timer_copy); } else if (PJ_TIME_VAL_GTE(*future_time, - ht->head_list.prev->_timer_value)) + ht->head_list.prev->_timer_value)) { - /* Insert the max value to the end of the list. */ - pj_list_insert_before(&ht->head_list, timer_copy); + /* Insert the max value to the end of the list. */ + pj_list_insert_before(&ht->head_list, timer_copy); } else { - tmp_node = ht->head_list.next; - while (tmp_node->next != &ht->head_list && - PJ_TIME_VAL_GT(*future_time, tmp_node->_timer_value)) - { - tmp_node = tmp_node->next; - } - if (PJ_TIME_VAL_LT(*future_time, tmp_node->_timer_value)) { - pj_list_insert_before(tmp_node, timer_copy); - } else { - pj_list_insert_after(tmp_node, timer_copy); - } + tmp_node = ht->head_list.next; + while (tmp_node->next != &ht->head_list && + PJ_TIME_VAL_GT(*future_time, tmp_node->_timer_value)) + { + tmp_node = tmp_node->next; + } + if (PJ_TIME_VAL_LT(*future_time, tmp_node->_timer_value)) { + pj_list_insert_before(tmp_node, timer_copy); + } else { + pj_list_insert_after(tmp_node, timer_copy); + } } copy_node(ht, new_node->_timer_id-1, timer_copy); #endif @@ -510,25 +509,25 @@ static pj_status_t insert_node(pj_timer_heap_t *ht, static pj_status_t schedule_entry( pj_timer_heap_t *ht, - pj_timer_entry *entry, - const pj_time_val *future_time ) + pj_timer_entry *entry, + const pj_time_val *future_time ) { if (ht->cur_size < ht->max_size) { - // Obtain the next unique sequence number. - // Set the entry - entry->_timer_id = pop_freelist(ht); + // Obtain the next unique sequence number. + // Set the entry + entry->_timer_id = pop_freelist(ht); - return insert_node( ht, entry, future_time ); + return insert_node( ht, entry, future_time ); } else - return -1; + return -1; } static int cancel( pj_timer_heap_t *ht, - pj_timer_entry *entry, - unsigned flags) + pj_timer_entry *entry, + unsigned flags) { long timer_node_slot; @@ -536,30 +535,30 @@ static int cancel( pj_timer_heap_t *ht, // Check to see if the timer_id is out of range if (entry->_timer_id < 1 || (pj_size_t)entry->_timer_id >= ht->max_size) { - entry->_timer_id = -1; - return 0; + entry->_timer_id = -1; + return 0; } timer_node_slot = ht->timer_ids[entry->_timer_id]; if (timer_node_slot < 0) { // Check to see if timer_id is still valid. - entry->_timer_id = -1; - return 0; + entry->_timer_id = -1; + return 0; } if (entry != GET_ENTRY(ht->heap[timer_node_slot])) { - if ((flags & F_DONT_ASSERT) == 0) - pj_assert(entry == GET_ENTRY(ht->heap[timer_node_slot])); + if ((flags & F_DONT_ASSERT) == 0) + pj_assert(entry == GET_ENTRY(ht->heap[timer_node_slot])); entry->_timer_id = -1; - return 0; + return 0; } else { - remove_node( ht, timer_node_slot); + remove_node( ht, timer_node_slot); - if ((flags & F_DONT_CALL) == 0) { + if ((flags & F_DONT_CALL) == 0) { // Call the close hook. - (*ht->callback)(ht, entry); - } - return 1; + (*ht->callback)(ht, entry); + } + return 1; } } @@ -582,7 +581,7 @@ PJ_DEF(pj_size_t) pj_timer_heap_mem_size(pj_size_t count) * Create a new timer heap. */ PJ_DEF(pj_status_t) pj_timer_heap_create( pj_pool_t *pool, - pj_size_t size, + pj_size_t size, pj_timer_heap_t **p_heap) { pj_timer_heap_t *ht; @@ -613,21 +612,21 @@ PJ_DEF(pj_status_t) pj_timer_heap_create( pj_pool_t *pool, // Create the heap array. ht->heap = (pj_timer_entry_dup**) - pj_pool_calloc(pool, size, sizeof(pj_timer_entry_dup*)); + pj_pool_calloc(pool, size, sizeof(pj_timer_entry_dup*)); if (!ht->heap) return PJ_ENOMEM; #if PJ_TIMER_USE_COPY // Create the timer entry copies array. ht->timer_dups = (pj_timer_entry_dup*) - pj_pool_alloc(pool, sizeof(pj_timer_entry_dup) * size); + pj_pool_alloc(pool, sizeof(pj_timer_entry_dup) * size); if (!ht->timer_dups) return PJ_ENOMEM; #endif // Create the parallel ht->timer_ids = (pj_timer_id_t *) - pj_pool_alloc( pool, sizeof(pj_timer_id_t) * size); + pj_pool_alloc( pool, sizeof(pj_timer_id_t) * size); if (!ht->timer_ids) return PJ_ENOMEM; @@ -635,7 +634,7 @@ PJ_DEF(pj_status_t) pj_timer_heap_create( pj_pool_t *pool, // distinguish freelist elements from "pointers" into the // array. for (i=0; itimer_ids[i] = -((pj_timer_id_t) (i + 1)); + ht->timer_ids[i] = -((pj_timer_id_t) (i + 1)); #if PJ_TIMER_USE_LINKED_LIST pj_list_init(&ht->head_list); @@ -702,9 +701,9 @@ static pj_status_t schedule_w_grp_lock_dbg(pj_timer_heap_t *ht, const pj_time_val *delay, pj_bool_t set_id, int id_val, - pj_grp_lock_t *grp_lock, - const char *src_file, - int src_line) + pj_grp_lock_t *grp_lock, + const char *src_file, + int src_line) #else static pj_status_t schedule_w_grp_lock(pj_timer_heap_t *ht, pj_timer_entry *entry, @@ -730,25 +729,25 @@ static pj_status_t schedule_w_grp_lock(pj_timer_heap_t *ht, /* Prevent same entry from being scheduled more than once */ if (pj_timer_entry_running(entry)) { - unlock_timer_heap(ht); - PJ_LOG(3,(THIS_FILE, "Warning! Rescheduling outstanding entry (%p)", - entry)); - return PJ_EINVALIDOP; + unlock_timer_heap(ht); + PJ_LOG(3,(THIS_FILE, "Warning! Rescheduling outstanding entry (%p)", + entry)); + return PJ_EINVALIDOP; } status = schedule_entry(ht, entry, &expires); if (status == PJ_SUCCESS) { - pj_timer_entry_dup *timer_copy = GET_TIMER(ht, entry); - - if (set_id) - GET_FIELD(timer_copy, id) = entry->id = id_val; - timer_copy->_grp_lock = grp_lock; - if (timer_copy->_grp_lock) { - pj_grp_lock_add_ref(timer_copy->_grp_lock); - } + pj_timer_entry_dup *timer_copy = GET_TIMER(ht, entry); + + if (set_id) + GET_FIELD(timer_copy, id) = entry->id = id_val; + timer_copy->_grp_lock = grp_lock; + if (timer_copy->_grp_lock) { + pj_grp_lock_add_ref(timer_copy->_grp_lock); + } #if PJ_TIMER_DEBUG - timer_copy->src_file = src_file; - timer_copy->src_line = src_line; + timer_copy->src_file = src_file; + timer_copy->src_line = src_line; #endif } unlock_timer_heap(ht); @@ -759,23 +758,23 @@ static pj_status_t schedule_w_grp_lock(pj_timer_heap_t *ht, #if PJ_TIMER_DEBUG PJ_DEF(pj_status_t) pj_timer_heap_schedule_dbg( pj_timer_heap_t *ht, - pj_timer_entry *entry, - const pj_time_val *delay, - const char *src_file, - int src_line) + pj_timer_entry *entry, + const pj_time_val *delay, + const char *src_file, + int src_line) { return schedule_w_grp_lock_dbg(ht, entry, delay, PJ_FALSE, 1, NULL, src_file, src_line); } PJ_DEF(pj_status_t) pj_timer_heap_schedule_w_grp_lock_dbg( - pj_timer_heap_t *ht, - pj_timer_entry *entry, - const pj_time_val *delay, - int id_val, + pj_timer_heap_t *ht, + pj_timer_entry *entry, + const pj_time_val *delay, + int id_val, pj_grp_lock_t *grp_lock, - const char *src_file, - int src_line) + const char *src_file, + int src_line) { return schedule_w_grp_lock_dbg(ht, entry, delay, PJ_TRUE, id_val, grp_lock, src_file, src_line); @@ -800,9 +799,9 @@ PJ_DEF(pj_status_t) pj_timer_heap_schedule_w_grp_lock(pj_timer_heap_t *ht, #endif static int cancel_timer(pj_timer_heap_t *ht, - pj_timer_entry *entry, - unsigned flags, - int id_val) + pj_timer_entry *entry, + unsigned flags, + int id_val) { pj_timer_entry_dup *timer_copy; pj_grp_lock_t *grp_lock; @@ -816,13 +815,13 @@ static int cancel_timer(pj_timer_heap_t *ht, count = cancel(ht, entry, flags | F_DONT_CALL); if (count > 0) { - /* Timer entry found & cancelled */ - if (flags & F_SET_ID) { - entry->id = id_val; - } - if (grp_lock) { - pj_grp_lock_dec_ref(grp_lock); - } + /* Timer entry found & cancelled */ + if (flags & F_SET_ID) { + entry->id = id_val; + } + if (grp_lock) { + pj_grp_lock_dec_ref(grp_lock); + } } unlock_timer_heap(ht); @@ -830,7 +829,7 @@ static int cancel_timer(pj_timer_heap_t *ht, } PJ_DEF(int) pj_timer_heap_cancel( pj_timer_heap_t *ht, - pj_timer_entry *entry) + pj_timer_entry *entry) { return cancel_timer(ht, entry, 0, 0); } @@ -854,9 +853,9 @@ PJ_DEF(unsigned) pj_timer_heap_poll( pj_timer_heap_t *ht, lock_timer_heap(ht); if (!ht->cur_size && next_delay) { - next_delay->sec = next_delay->msec = PJ_MAXINT32; + next_delay->sec = next_delay->msec = PJ_MAXINT32; unlock_timer_heap(ht); - return 0; + return 0; } count = 0; @@ -864,75 +863,75 @@ PJ_DEF(unsigned) pj_timer_heap_poll( pj_timer_heap_t *ht, if (ht->cur_size) { #if PJ_TIMER_USE_LINKED_LIST - slot = ht->timer_ids[GET_FIELD(ht->head_list.next, _timer_id)]; + slot = ht->timer_ids[GET_FIELD(ht->head_list.next, _timer_id)]; #endif - min_time_node = ht->heap[slot]->_timer_value; + min_time_node = ht->heap[slot]->_timer_value; } while ( ht->cur_size && - PJ_TIME_VAL_LTE(min_time_node, now) && + PJ_TIME_VAL_LTE(min_time_node, now) && count < ht->max_entries_per_poll ) { - pj_timer_entry_dup *node = remove_node(ht, slot); - pj_timer_entry *entry = GET_ENTRY(node); - /* Avoid re-use of this timer until the callback is done. */ - ///Not necessary, even causes problem (see also #2176). - ///pj_timer_id_t node_timer_id = pop_freelist(ht); - pj_grp_lock_t *grp_lock; - pj_bool_t valid = PJ_TRUE; - - ++count; - - grp_lock = node->_grp_lock; - node->_grp_lock = NULL; - if (GET_FIELD(node, cb) != entry->cb || - GET_FIELD(node, user_data) != entry->user_data) - { - valid = PJ_FALSE; + pj_timer_entry_dup *node = remove_node(ht, slot); + pj_timer_entry *entry = GET_ENTRY(node); + /* Avoid re-use of this timer until the callback is done. */ + ///Not necessary, even causes problem (see also #2176). + ///pj_timer_id_t node_timer_id = pop_freelist(ht); + pj_grp_lock_t *grp_lock; + pj_bool_t valid = PJ_TRUE; + + ++count; + + grp_lock = node->_grp_lock; + node->_grp_lock = NULL; + if (GET_FIELD(node, cb) != entry->cb || + GET_FIELD(node, user_data) != entry->user_data) + { + valid = PJ_FALSE; #if PJ_TIMER_DEBUG - PJ_LOG(3,(THIS_FILE, "Bug! Polling entry %p from %s line %d has " - "been deallocated without being cancelled", - GET_ENTRY(node), - node->src_file, node->src_line)); + PJ_LOG(3,(THIS_FILE, "Bug! Polling entry %p from %s line %d has " + "been deallocated without being cancelled", + GET_ENTRY(node), + node->src_file, node->src_line)); #else - PJ_LOG(3,(THIS_FILE, "Bug! Polling entry %p has " - "been deallocated without being cancelled", - GET_ENTRY(node))); + PJ_LOG(3,(THIS_FILE, "Bug! Polling entry %p has " + "been deallocated without being cancelled", + GET_ENTRY(node))); #endif #if ASSERT_IF_ENTRY_DESTROYED - pj_assert(node->dup.cb == entry->cb); - pj_assert(node->dup.user_data == entry->user_data); + pj_assert(node->dup.cb == entry->cb); + pj_assert(node->dup.user_data == entry->user_data); #endif - } + } - unlock_timer_heap(ht); + unlock_timer_heap(ht); - PJ_RACE_ME(5); + PJ_RACE_ME(5); - if (valid && entry->cb) - (*entry->cb)(ht, entry); + if (valid && entry->cb) + (*entry->cb)(ht, entry); - if (valid && grp_lock) - pj_grp_lock_dec_ref(grp_lock); + if (valid && grp_lock) + pj_grp_lock_dec_ref(grp_lock); - lock_timer_heap(ht); - /* Now, the timer is really free for re-use. */ - ///push_freelist(ht, node_timer_id); + lock_timer_heap(ht); + /* Now, the timer is really free for re-use. */ + ///push_freelist(ht, node_timer_id); - if (ht->cur_size) { + if (ht->cur_size) { #if PJ_TIMER_USE_LINKED_LIST - slot = ht->timer_ids[GET_FIELD(ht->head_list.next, _timer_id)]; + slot = ht->timer_ids[GET_FIELD(ht->head_list.next, _timer_id)]; #endif - min_time_node = ht->heap[slot]->_timer_value; - } + min_time_node = ht->heap[slot]->_timer_value; + } } if (ht->cur_size && next_delay) { - *next_delay = ht->heap[0]->_timer_value; - PJ_TIME_VAL_SUB(*next_delay, now); - if (next_delay->sec < 0 || next_delay->msec < 0) - next_delay->sec = next_delay->msec = 0; + *next_delay = ht->heap[0]->_timer_value; + PJ_TIME_VAL_SUB(*next_delay, now); + if (next_delay->sec < 0 || next_delay->msec < 0) + next_delay->sec = next_delay->msec = 0; } else if (next_delay) { - next_delay->sec = next_delay->msec = PJ_MAXINT32; + next_delay->sec = next_delay->msec = PJ_MAXINT32; } unlock_timer_heap(ht); @@ -947,7 +946,7 @@ PJ_DEF(pj_size_t) pj_timer_heap_count( pj_timer_heap_t *ht ) } PJ_DEF(pj_status_t) pj_timer_heap_earliest_time( pj_timer_heap_t * ht, - pj_time_val *timeval) + pj_time_val *timeval) { pj_assert(ht->cur_size != 0); if (ht->cur_size == 0) @@ -967,47 +966,47 @@ PJ_DEF(void) pj_timer_heap_dump(pj_timer_heap_t *ht) PJ_LOG(3,(THIS_FILE, "Dumping timer heap:")); PJ_LOG(3,(THIS_FILE, " Cur size: %d entries, max: %d", - (int)ht->cur_size, (int)ht->max_size)); + (int)ht->cur_size, (int)ht->max_size)); if (ht->cur_size) { #if PJ_TIMER_USE_LINKED_LIST - pj_timer_entry_dup *tmp_dup; + pj_timer_entry_dup *tmp_dup; #else - unsigned i; + unsigned i; #endif - pj_time_val now; + pj_time_val now; - PJ_LOG(3,(THIS_FILE, " Entries: ")); - PJ_LOG(3,(THIS_FILE, " _id\tId\tElapsed\tSource")); - PJ_LOG(3,(THIS_FILE, " ----------------------------------")); + PJ_LOG(3,(THIS_FILE, " Entries: ")); + PJ_LOG(3,(THIS_FILE, " _id\tId\tElapsed\tSource")); + PJ_LOG(3,(THIS_FILE, " ----------------------------------")); - pj_gettickcount(&now); + pj_gettickcount(&now); #if !PJ_TIMER_USE_LINKED_LIST - for (i=0; i<(unsigned)ht->cur_size; ++i) - { - pj_timer_entry_dup *e = ht->heap[i]; + for (i=0; i<(unsigned)ht->cur_size; ++i) + { + pj_timer_entry_dup *e = ht->heap[i]; #else - for (tmp_dup = ht->head_list.next; tmp_dup != &ht->head_list; - tmp_dup = tmp_dup->next) - { - pj_timer_entry_dup *e = tmp_dup; + for (tmp_dup = ht->head_list.next; tmp_dup != &ht->head_list; + tmp_dup = tmp_dup->next) + { + pj_timer_entry_dup *e = tmp_dup; #endif - pj_time_val delta; + pj_time_val delta; - if (PJ_TIME_VAL_LTE(e->_timer_value, now)) - delta.sec = delta.msec = 0; - else { - delta = e->_timer_value; - PJ_TIME_VAL_SUB(delta, now); - } + if (PJ_TIME_VAL_LTE(e->_timer_value, now)) + delta.sec = delta.msec = 0; + else { + delta = e->_timer_value; + PJ_TIME_VAL_SUB(delta, now); + } - PJ_LOG(3,(THIS_FILE, " %d\t%d\t%d.%03d\t%s:%d", - GET_FIELD(e, _timer_id), GET_FIELD(e, id), - (int)delta.sec, (int)delta.msec, - e->src_file, e->src_line)); - } + PJ_LOG(3,(THIS_FILE, " %d\t%d\t%d.%03d\t%s:%d", + GET_FIELD(e, _timer_id), GET_FIELD(e, id), + (int)delta.sec, (int)delta.msec, + e->src_file, e->src_line)); + } } unlock_timer_heap(ht); diff --git a/pjlib/src/pj/timer_symbian.cpp b/pjlib/src/pj/timer_symbian.cpp index 4b1d61ba41..6b6b56933b 100644 --- a/pjlib/src/pj/timer_symbian.cpp +++ b/pjlib/src/pj/timer_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,15 +28,15 @@ #define DEFAULT_MAX_TIMED_OUT_PER_POLL (64) // Maximum number of miliseconds that RTimer.At() supports -#define MAX_RTIMER_INTERVAL 2147 +#define MAX_RTIMER_INTERVAL 2147 /* Absolute maximum number of timer entries */ #ifndef PJ_SYMBIAN_TIMER_MAX_COUNT -# define PJ_SYMBIAN_TIMER_MAX_COUNT 65535 +# define PJ_SYMBIAN_TIMER_MAX_COUNT 65535 #endif /* Get the number of free slots in the timer heap */ -#define FREECNT(th) (th->max_size - th->cur_size) +#define FREECNT(th) (th->max_size - th->cur_size) // Forward declaration class CPjTimerEntry; @@ -70,19 +69,19 @@ class CPjTimerEntry : public CActive public: pj_timer_entry *entry_; - static CPjTimerEntry* NewL( pj_timer_heap_t *timer_heap, - pj_timer_entry *entry, - const pj_time_val *delay); + static CPjTimerEntry* NewL( pj_timer_heap_t *timer_heap, + pj_timer_entry *entry, + const pj_time_val *delay); ~CPjTimerEntry(); virtual void RunL(); virtual void DoCancel(); -private: +private: pj_timer_heap_t *timer_heap_; - RTimer rtimer_; - pj_uint32_t interval_left_; + RTimer rtimer_; + pj_uint32_t interval_left_; CPjTimerEntry(pj_timer_heap_t *timer_heap, pj_timer_entry *entry); void ConstructL(const pj_time_val *delay); @@ -103,36 +102,36 @@ static pj_status_t realloc_timer_heap(pj_timer_heap_t *th, pj_size_t new_size) unsigned i, j; if (new_size > PJ_SYMBIAN_TIMER_MAX_COUNT) { - /* Just some sanity limit */ - new_size = PJ_SYMBIAN_TIMER_MAX_COUNT; - if (new_size <= th->max_size) { - /* We've grown large enough */ - pj_assert(!"Too many timer heap entries"); - return PJ_ETOOMANY; - } + /* Just some sanity limit */ + new_size = PJ_SYMBIAN_TIMER_MAX_COUNT; + if (new_size <= th->max_size) { + /* We've grown large enough */ + pj_assert(!"Too many timer heap entries"); + return PJ_ETOOMANY; + } } /* Allocate entries, move entries from the old array if there is one */ entries = new entry_ptr[new_size]; if (th->entries) { - pj_memcpy(entries, th->entries, th->max_size * sizeof(th->entries[0])); + pj_memcpy(entries, th->entries, th->max_size * sizeof(th->entries[0])); } /* Initialize the remaining new area */ pj_bzero(&entries[th->max_size], - (new_size - th->max_size) * sizeof(th->entries[0])); + (new_size - th->max_size) * sizeof(th->entries[0])); /* Allocate free slots array */ free_slots = new int[new_size]; if (th->free_slots) { - pj_memcpy(free_slots, th->free_slots, - FREECNT(th) * sizeof(th->free_slots[0])); + pj_memcpy(free_slots, th->free_slots, + FREECNT(th) * sizeof(th->free_slots[0])); } /* Initialize the remaining new area */ for (i=FREECNT(th), j=th->max_size; jmax_size * 2); - if (status != PJ_SUCCESS) - return status; + // Grow the timer heap twice the capacity + status = realloc_timer_heap(th, th->max_size * 2); + if (status != PJ_SUCCESS) + return status; } /* Allocate one free slot. Use LIFO */ slot = th->free_slots[FREECNT(th)-1]; PJ_ASSERT_RETURN((slot >= 0) && (slot < (int)th->max_size) && - (th->entries[slot]==NULL), PJ_EBUG); + (th->entries[slot]==NULL), PJ_EBUG); th->free_slots[FREECNT(th)-1] = -1; th->entries[slot] = entry; @@ -192,7 +191,7 @@ static pj_status_t remove_entry(pj_timer_heap_t *th, CPjTimerEntry *entry) CPjTimerEntry::CPjTimerEntry(pj_timer_heap_t *timer_heap, - pj_timer_entry *entry) + pj_timer_entry *entry) : CActive(PJ_SYMBIAN_TIMER_PRIORITY), entry_(entry), timer_heap_(timer_heap), interval_left_(0) { @@ -209,9 +208,9 @@ void CPjTimerEntry::Schedule() pj_int32_t interval; if (interval_left_ > MAX_RTIMER_INTERVAL) { - interval = MAX_RTIMER_INTERVAL; + interval = MAX_RTIMER_INTERVAL; } else { - interval = interval_left_; + interval = interval_left_; } interval_left_ -= interval; @@ -229,8 +228,8 @@ void CPjTimerEntry::ConstructL(const pj_time_val *delay) } CPjTimerEntry* CPjTimerEntry::NewL(pj_timer_heap_t *timer_heap, - pj_timer_entry *entry, - const pj_time_val *delay) + pj_timer_entry *entry, + const pj_time_val *delay) { CPjTimerEntry *self = new CPjTimerEntry(timer_heap, entry); CleanupStack::PushL(self); @@ -243,8 +242,8 @@ CPjTimerEntry* CPjTimerEntry::NewL(pj_timer_heap_t *timer_heap, void CPjTimerEntry::RunL() { if (interval_left_ > 0) { - Schedule(); - return; + Schedule(); + return; } remove_entry(timer_heap_, this); @@ -261,7 +260,7 @@ void CPjTimerEntry::DoCancel() * it. */ if (entry_ && entry_->_timer_id != -1) - remove_entry(timer_heap_, this); + remove_entry(timer_heap_, this); rtimer_.Cancel(); } @@ -287,7 +286,7 @@ PJ_DEF(pj_size_t) pj_timer_heap_mem_size(pj_size_t count) * Create a new timer heap. */ PJ_DEF(pj_status_t) pj_timer_heap_create( pj_pool_t *pool, - pj_size_t size, + pj_size_t size, pj_timer_heap_t **p_heap) { pj_timer_heap_t *ht; @@ -305,7 +304,7 @@ PJ_DEF(pj_status_t) pj_timer_heap_create( pj_pool_t *pool, /* Allocate slots */ status = realloc_timer_heap(ht, size); if (status != PJ_SUCCESS) - return status; + return status; *p_heap = ht; return PJ_SUCCESS; @@ -315,15 +314,15 @@ PJ_DEF(void) pj_timer_heap_destroy( pj_timer_heap_t *ht ) { /* Cancel and delete pending active objects */ if (ht->entries) { - unsigned i; - for (i=0; imax_size; ++i) { - if (ht->entries[i]) { - ht->entries[i]->entry_ = NULL; - ht->entries[i]->Cancel(); - delete ht->entries[i]; - ht->entries[i] = NULL; - } - } + unsigned i; + for (i=0; imax_size; ++i) { + if (ht->entries[i]) { + ht->entries[i]->entry_ = NULL; + ht->entries[i]->Cancel(); + delete ht->entries[i]; + ht->entries[i] = NULL; + } + } } delete [] ht->entries; @@ -339,7 +338,7 @@ PJ_DEF(void) pj_timer_heap_set_lock( pj_timer_heap_t *ht, { PJ_UNUSED_ARG(ht); if (auto_del) - pj_lock_destroy(lock); + pj_lock_destroy(lock); } @@ -367,8 +366,8 @@ PJ_DEF(pj_timer_entry*) pj_timer_entry_init( pj_timer_entry *entry, } PJ_DEF(pj_status_t) pj_timer_heap_schedule( pj_timer_heap_t *ht, - pj_timer_entry *entry, - const pj_time_val *delay) + pj_timer_entry *entry, + const pj_time_val *delay) { CPjTimerEntry *timerObj; pj_status_t status; @@ -384,9 +383,9 @@ PJ_DEF(pj_status_t) pj_timer_heap_schedule( pj_timer_heap_t *ht, timerObj = CPjTimerEntry::NewL(ht, entry, delay); status = add_entry(ht, timerObj); if (status != PJ_SUCCESS) { - timerObj->Cancel(); - delete timerObj; - return status; + timerObj->Cancel(); + delete timerObj; + return status; } return PJ_SUCCESS; @@ -399,33 +398,33 @@ PJ_DEF(pj_status_t) pj_timer_heap_schedule_w_grp_lock(pj_timer_heap_t *ht, pj_grp_lock_t *grp_lock) { pj_status_t status; - + PJ_UNUSED_ARG(grp_lock); status = pj_timer_heap_schedule(ht, entry, delay); if (status == PJ_SUCCESS) - entry->id = id_val; + entry->id = id_val; return status; } PJ_DEF(int) pj_timer_heap_cancel( pj_timer_heap_t *ht, - pj_timer_entry *entry) + pj_timer_entry *entry) { PJ_ASSERT_RETURN(ht && entry, PJ_EINVAL); if (entry->_timer_id >= 0 && entry->_timer_id < (int)ht->max_size) { - CPjTimerEntry *timerObj = ht->entries[entry->_timer_id]; - if (timerObj) { - timerObj->Cancel(); - delete timerObj; - return 1; - } else { - return 0; - } + CPjTimerEntry *timerObj = ht->entries[entry->_timer_id]; + if (timerObj) { + timerObj->Cancel(); + delete timerObj; + return 1; + } else { + return 0; + } } else { - return 0; + return 0; } } @@ -435,7 +434,7 @@ PJ_DEF(int) pj_timer_heap_cancel_if_active(pj_timer_heap_t *ht, { int count = pj_timer_heap_cancel(ht, entry); if (count == 1) - entry->id = id_val; + entry->id = id_val; return count; } @@ -448,8 +447,8 @@ PJ_DEF(unsigned) pj_timer_heap_poll( pj_timer_heap_t *ht, */ PJ_UNUSED_ARG(ht); if (next_delay) { - next_delay->sec = 1; - next_delay->msec = 0; + next_delay->sec = 1; + next_delay->msec = 0; } return 0; } @@ -462,7 +461,7 @@ PJ_DEF(pj_size_t) pj_timer_heap_count( pj_timer_heap_t *ht ) } PJ_DEF(pj_status_t) pj_timer_heap_earliest_time( pj_timer_heap_t * ht, - pj_time_val *timeval) + pj_time_val *timeval) { /* We don't support this! */ PJ_UNUSED_ARG(ht); diff --git a/pjlib/src/pj/types.c b/pjlib/src/pj/types.c index 89cb36e829..a26525784b 100644 --- a/pjlib/src/pj/types.c +++ b/pjlib/src/pj/types.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,22 +24,22 @@ PJ_DEF(void) pj_time_val_normalize(pj_time_val *t) PJ_CHECK_STACK(); if (t->msec >= 1000) { - t->sec += (t->msec / 1000); - t->msec = (t->msec % 1000); + t->sec += (t->msec / 1000); + t->msec = (t->msec % 1000); } else if (t->msec <= -1000) { - do { - t->sec--; - t->msec += 1000; + do { + t->sec--; + t->msec += 1000; } while (t->msec <= -1000); } if (t->sec >= 1 && t->msec < 0) { - t->sec--; - t->msec += 1000; + t->sec--; + t->msec += 1000; } else if (t->sec < 0 && t->msec > 0) { - t->sec++; - t->msec -= 1000; + t->sec++; + t->msec -= 1000; } } diff --git a/pjlib/src/pj/unicode_symbian.cpp b/pjlib/src/pj/unicode_symbian.cpp index f4b598f50b..f65e830618 100644 --- a/pjlib/src/pj/unicode_symbian.cpp +++ b/pjlib/src/pj/unicode_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -26,7 +25,7 @@ * Convert ANSI strings to Unicode strings. */ PJ_DEF(wchar_t*) pj_ansi_to_unicode( const char *str, pj_size_t len, - wchar_t *wbuf, pj_size_t wbuf_count) + wchar_t *wbuf, pj_size_t wbuf_count) { TPtrC8 aForeign((const TUint8*)str, (TInt)len); TPtr16 aUnicode((TUint16*)wbuf, (TInt)(wbuf_count-1)); @@ -35,13 +34,13 @@ PJ_DEF(wchar_t*) pj_ansi_to_unicode( const char *str, pj_size_t len, left = PjSymbianOS::Instance()->ConvertToUnicode(aUnicode, aForeign); if (left != 0) { - // Error, or there are unconvertable characters - *wbuf = 0; + // Error, or there are unconvertable characters + *wbuf = 0; } else { - if (len < wbuf_count) - wbuf[len] = 0; - else - wbuf[len-1] = 0; + if (len < wbuf_count) + wbuf[len] = 0; + else + wbuf[len-1] = 0; } return wbuf; @@ -52,7 +51,7 @@ PJ_DEF(wchar_t*) pj_ansi_to_unicode( const char *str, pj_size_t len, * Convert Unicode string to ANSI string. */ PJ_DEF(char*) pj_unicode_to_ansi( const wchar_t *wstr, pj_size_t len, - char *buf, pj_size_t buf_size) + char *buf, pj_size_t buf_size) { TPtrC16 aUnicode((const TUint16*)wstr, (TInt)len); TPtr8 aForeign((TUint8*)buf, (TInt)(buf_size-1)); @@ -61,13 +60,13 @@ PJ_DEF(char*) pj_unicode_to_ansi( const wchar_t *wstr, pj_size_t len, left = PjSymbianOS::Instance()->ConvertFromUnicode(aForeign, aUnicode); if (left != 0) { - // Error, or there are unconvertable characters - buf[0] = '\0'; + // Error, or there are unconvertable characters + buf[0] = '\0'; } else { - if (len < buf_size) - buf[len] = '\0'; - else - buf[len-1] = '\0'; + if (len < buf_size) + buf[len] = '\0'; + else + buf[len-1] = '\0'; } return buf; diff --git a/pjlib/src/pj/unicode_win32.c b/pjlib/src/pj/unicode_win32.c index 7718f65b43..2e85864e7d 100644 --- a/pjlib/src/pj/unicode_win32.c +++ b/pjlib/src/pj/unicode_win32.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,17 +23,17 @@ PJ_DEF(wchar_t*) pj_ansi_to_unicode(const char *s, int len, - wchar_t *buf, int buf_count) + wchar_t *buf, int buf_count) { PJ_ASSERT_RETURN(s && buf, NULL); len = MultiByteToWideChar(CP_ACP, 0, s, len, - buf, buf_count); + buf, buf_count); if (buf_count) { - if (len < buf_count) - buf[len] = 0; - else - buf[len-1] = 0; + if (len < buf_count) + buf[len] = 0; + else + buf[len-1] = 0; } return buf; @@ -42,17 +41,17 @@ PJ_DEF(wchar_t*) pj_ansi_to_unicode(const char *s, int len, PJ_DEF(char*) pj_unicode_to_ansi( const wchar_t *wstr, pj_ssize_t len, - char *buf, int buf_size) + char *buf, int buf_size) { PJ_ASSERT_RETURN(wstr && buf, NULL); len = WideCharToMultiByte(CP_ACP, 0, wstr, (int)len, buf, buf_size, - NULL, NULL); + NULL, NULL); if (buf_size) { - if (len < buf_size) - buf[len] = '\0'; - else - buf[len-1] = '\0'; + if (len < buf_size) + buf[len] = '\0'; + else + buf[len-1] = '\0'; } return buf; diff --git a/pjlib/src/pjlib-samples/except.c b/pjlib/src/pjlib-samples/except.c index ffc0d8ed17..918294a42a 100644 --- a/pjlib/src/pjlib-samples/except.c +++ b/pjlib/src/pjlib-samples/except.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pjlib-samples/list.c b/pjlib/src/pjlib-samples/list.c index ec55405555..235fe8d864 100644 --- a/pjlib/src/pjlib-samples/list.c +++ b/pjlib/src/pjlib-samples/list.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pjlib-samples/log.c b/pjlib/src/pjlib-samples/log.c index cefec10a25..8b552c4a63 100644 --- a/pjlib/src/pjlib-samples/log.c +++ b/pjlib/src/pjlib-samples/log.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pjlib-test/activesock.c b/pjlib/src/pjlib-test/activesock.c index 560f0c665d..54733fbb57 100644 --- a/pjlib/src/pjlib-test/activesock.c +++ b/pjlib/src/pjlib-test/activesock.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,13 +37,13 @@ */ struct udp_echo_srv { - pj_activesock_t *asock; - pj_bool_t echo_enabled; - pj_uint16_t port; - pj_ioqueue_op_key_t send_key; - pj_status_t status; - unsigned rx_cnt; - unsigned rx_err_cnt, tx_err_cnt; + pj_activesock_t *asock; + pj_bool_t echo_enabled; + pj_uint16_t port; + pj_ioqueue_op_key_t send_key; + pj_status_t status; + unsigned rx_cnt; + unsigned rx_err_cnt, tx_err_cnt; }; static void udp_echo_err(const char *title, pj_status_t status) @@ -56,11 +55,11 @@ static void udp_echo_err(const char *title, pj_status_t status) } static pj_bool_t udp_echo_srv_on_data_recvfrom(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status) + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status) { struct udp_echo_srv *srv; pj_ssize_t sent; @@ -69,24 +68,24 @@ static pj_bool_t udp_echo_srv_on_data_recvfrom(pj_activesock_t *asock, srv = (struct udp_echo_srv*) pj_activesock_get_user_data(asock); if (status != PJ_SUCCESS) { - srv->status = status; - srv->rx_err_cnt++; - udp_echo_err("recvfrom() callback", status); - return PJ_TRUE; + srv->status = status; + srv->rx_err_cnt++; + udp_echo_err("recvfrom() callback", status); + return PJ_TRUE; } srv->rx_cnt++; /* Send back if echo is enabled */ if (srv->echo_enabled) { - sent = size; - srv->status = pj_activesock_sendto(asock, &srv->send_key, data, - &sent, 0, - src_addr, addr_len); - if (srv->status != PJ_SUCCESS) { - srv->tx_err_cnt++; - udp_echo_err("sendto()", status); - } + sent = size; + srv->status = pj_activesock_sendto(asock, &srv->send_key, data, + &sent, 0, + src_addr, addr_len); + if (srv->status != PJ_SUCCESS) { + srv->tx_err_cnt++; + udp_echo_err("sendto()", status); + } } return PJ_TRUE; @@ -94,9 +93,9 @@ static pj_bool_t udp_echo_srv_on_data_recvfrom(pj_activesock_t *asock, static pj_status_t udp_echo_srv_create(pj_pool_t *pool, - pj_ioqueue_t *ioqueue, - pj_bool_t enable_echo, - struct udp_echo_srv **p_srv) + pj_ioqueue_t *ioqueue, + pj_bool_t enable_echo, + struct udp_echo_srv **p_srv) { struct udp_echo_srv *srv; pj_sock_t sock_fd = PJ_INVALID_SOCKET; @@ -113,11 +112,11 @@ static pj_status_t udp_echo_srv_create(pj_pool_t *pool, activesock_cb.on_data_recvfrom = &udp_echo_srv_on_data_recvfrom; status = pj_activesock_create_udp(pool, &addr, NULL, ioqueue, &activesock_cb, - srv, &srv->asock, &addr); + srv, &srv->asock, &addr); if (status != PJ_SUCCESS) { - pj_sock_close(sock_fd); - udp_echo_err("pj_activesock_create()", status); - return status; + pj_sock_close(sock_fd); + udp_echo_err("pj_activesock_create()", status); + return status; } srv->port = pj_ntohs(addr.ipv4.sin_port); @@ -126,9 +125,9 @@ static pj_status_t udp_echo_srv_create(pj_pool_t *pool, status = pj_activesock_start_recvfrom(srv->asock, pool, 32, 0); if (status != PJ_SUCCESS) { - pj_activesock_close(srv->asock); - udp_echo_err("pj_activesock_start_recvfrom()", status); - return status; + pj_activesock_close(srv->asock); + udp_echo_err("pj_activesock_start_recvfrom()", status); + return status; } @@ -157,94 +156,94 @@ static int udp_ping_pong_test(void) pool = pj_pool_create(mem, "pingpong", 512, 512, NULL); if (!pool) - return -10; + return -10; status = pj_ioqueue_create(pool, 4, &ioqueue); if (status != PJ_SUCCESS) { - ret = -20; - udp_echo_err("pj_ioqueue_create()", status); - goto on_return; + ret = -20; + udp_echo_err("pj_ioqueue_create()", status); + goto on_return; } status = udp_echo_srv_create(pool, ioqueue, PJ_TRUE, &srv1); if (status != PJ_SUCCESS) { - ret = -30; - goto on_return; + ret = -30; + goto on_return; } status = udp_echo_srv_create(pool, ioqueue, PJ_TRUE, &srv2); if (status != PJ_SUCCESS) { - ret = -40; - goto on_return; + ret = -40; + goto on_return; } /* initiate the first send */ for (count=0; count<1000; ++count) { - unsigned last_rx1, last_rx2; - unsigned i; - - if (need_send) { - pj_str_t loopback; - pj_sockaddr_in addr; - pj_ssize_t sent; - - ++data; - - sent = sizeof(data); - loopback = pj_str("127.0.0.1"); - pj_sockaddr_in_init(&addr, &loopback, srv2->port); - status = pj_activesock_sendto(srv1->asock, &srv1->send_key, - &data, &sent, 0, - &addr, sizeof(addr)); - if (status != PJ_SUCCESS && status != PJ_EPENDING) { - ret = -50; - udp_echo_err("sendto()", status); - goto on_return; - } - - need_send = PJ_FALSE; - } - - last_rx1 = srv1->rx_cnt; - last_rx2 = srv2->rx_cnt; - - for (i=0; i<10 && last_rx1 == srv1->rx_cnt && last_rx2 == srv2->rx_cnt; ++i) { - pj_time_val delay = {0, 10}; + unsigned last_rx1, last_rx2; + unsigned i; + + if (need_send) { + pj_str_t loopback; + pj_sockaddr_in addr; + pj_ssize_t sent; + + ++data; + + sent = sizeof(data); + loopback = pj_str("127.0.0.1"); + pj_sockaddr_in_init(&addr, &loopback, srv2->port); + status = pj_activesock_sendto(srv1->asock, &srv1->send_key, + &data, &sent, 0, + &addr, sizeof(addr)); + if (status != PJ_SUCCESS && status != PJ_EPENDING) { + ret = -50; + udp_echo_err("sendto()", status); + goto on_return; + } + + need_send = PJ_FALSE; + } + + last_rx1 = srv1->rx_cnt; + last_rx2 = srv2->rx_cnt; + + for (i=0; i<10 && last_rx1 == srv1->rx_cnt && last_rx2 == srv2->rx_cnt; ++i) { + pj_time_val delay = {0, 10}; #ifdef PJ_SYMBIAN - PJ_UNUSED_ARG(delay); - pj_symbianos_poll(-1, 100); + PJ_UNUSED_ARG(delay); + pj_symbianos_poll(-1, 100); #else - pj_ioqueue_poll(ioqueue, &delay); + pj_ioqueue_poll(ioqueue, &delay); #endif - } - - if (srv1->rx_err_cnt+srv1->tx_err_cnt != 0 || - srv2->rx_err_cnt+srv2->tx_err_cnt != 0) - { - /* Got error */ - ret = -60; - goto on_return; - } - - if (last_rx1 == srv1->rx_cnt && last_rx2 == srv2->rx_cnt) { - /* Packet lost */ - ret = -70; - udp_echo_err("packets have been lost", PJ_ETIMEDOUT); - goto on_return; - } + } + + if (srv1->rx_err_cnt+srv1->tx_err_cnt != 0 || + srv2->rx_err_cnt+srv2->tx_err_cnt != 0) + { + /* Got error */ + ret = -60; + goto on_return; + } + + if (last_rx1 == srv1->rx_cnt && last_rx2 == srv2->rx_cnt) { + /* Packet lost */ + ret = -70; + udp_echo_err("packets have been lost", PJ_ETIMEDOUT); + goto on_return; + } } ret = 0; on_return: if (srv2) - udp_echo_srv_destroy(srv2); + udp_echo_srv_destroy(srv2); if (srv1) - udp_echo_srv_destroy(srv1); + udp_echo_srv_destroy(srv1); if (ioqueue) - pj_ioqueue_destroy(ioqueue); + pj_ioqueue_destroy(ioqueue); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return ret; } @@ -254,71 +253,71 @@ static int udp_ping_pong_test(void) #define SIGNATURE 0xdeadbeef struct tcp_pkt { - pj_uint32_t signature; - pj_uint32_t seq; - char fill[513]; + pj_uint32_t signature; + pj_uint32_t seq; + char fill[513]; }; struct tcp_state { - pj_bool_t err; - pj_bool_t sent; - pj_uint32_t next_recv_seq; - pj_uint8_t pkt[600]; + pj_bool_t err; + pj_bool_t sent; + pj_uint32_t next_recv_seq; + pj_uint8_t pkt[600]; }; struct send_key { - pj_ioqueue_op_key_t op_key; + pj_ioqueue_op_key_t op_key; }; static pj_bool_t tcp_on_data_read(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { struct tcp_state *st = (struct tcp_state*) pj_activesock_get_user_data(asock); char *next = (char*) data; if (status != PJ_SUCCESS && status != PJ_EPENDING) { - PJ_LOG(1,("", " err: status=%d", status)); - st->err = PJ_TRUE; - return PJ_FALSE; + PJ_LOG(1,("", " err: status=%d", status)); + st->err = PJ_TRUE; + return PJ_FALSE; } while (size >= sizeof(struct tcp_pkt)) { - struct tcp_pkt *tcp_pkt = (struct tcp_pkt*) next; - - if (tcp_pkt->signature != SIGNATURE) { - PJ_LOG(1,("", " err: invalid signature at seq=%d", - st->next_recv_seq)); - st->err = PJ_TRUE; - return PJ_FALSE; - } - if (tcp_pkt->seq != st->next_recv_seq) { - PJ_LOG(1,("", " err: wrong sequence")); - st->err = PJ_TRUE; - return PJ_FALSE; - } - - st->next_recv_seq++; - next += sizeof(struct tcp_pkt); - size -= sizeof(struct tcp_pkt); + struct tcp_pkt *tcp_pkt = (struct tcp_pkt*) next; + + if (tcp_pkt->signature != SIGNATURE) { + PJ_LOG(1,("", " err: invalid signature at seq=%d", + st->next_recv_seq)); + st->err = PJ_TRUE; + return PJ_FALSE; + } + if (tcp_pkt->seq != st->next_recv_seq) { + PJ_LOG(1,("", " err: wrong sequence")); + st->err = PJ_TRUE; + return PJ_FALSE; + } + + st->next_recv_seq++; + next += sizeof(struct tcp_pkt); + size -= sizeof(struct tcp_pkt); } if (size) { - pj_memmove(data, next, size); - *remainder = size; + pj_memmove(data, next, size); + *remainder = size; } return PJ_TRUE; } static pj_bool_t tcp_on_data_sent(pj_activesock_t *asock, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t sent) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t sent) { struct tcp_state *st=(struct tcp_state*)pj_activesock_get_user_data(asock); @@ -327,8 +326,8 @@ static pj_bool_t tcp_on_data_sent(pj_activesock_t *asock, st->sent = 1; if (sent < 1) { - st->err = PJ_TRUE; - return PJ_FALSE; + st->err = PJ_TRUE; + return PJ_FALSE; } return PJ_TRUE; @@ -349,16 +348,16 @@ static int tcp_perf_test(void) pool = pj_pool_create(mem, "tcpperf", 256, 256, NULL); status = app_socketpair(pj_AF_INET(), pj_SOCK_STREAM(), 0, &sock1, - &sock2); + &sock2); if (status != PJ_SUCCESS) { - status = -100; - goto on_return; + status = -100; + goto on_return; } status = pj_ioqueue_create(pool, 4, &ioqueue); if (status != PJ_SUCCESS) { - status = -110; - goto on_return; + status = -110; + goto on_return; } pj_bzero(&cb, sizeof(cb)); @@ -367,81 +366,81 @@ static int tcp_perf_test(void) state1 = PJ_POOL_ZALLOC_T(pool, struct tcp_state); status = pj_activesock_create(pool, sock1, pj_SOCK_STREAM(), NULL, ioqueue, - &cb, state1, &asock1); + &cb, state1, &asock1); if (status != PJ_SUCCESS) { - status = -120; - goto on_return; + status = -120; + goto on_return; } state2 = PJ_POOL_ZALLOC_T(pool, struct tcp_state); status = pj_activesock_create(pool, sock2, pj_SOCK_STREAM(), NULL, ioqueue, - &cb, state2, &asock2); + &cb, state2, &asock2); if (status != PJ_SUCCESS) { - status = -130; - goto on_return; + status = -130; + goto on_return; } status = pj_activesock_start_read(asock1, pool, 1000, 0); if (status != PJ_SUCCESS) { - status = -140; - goto on_return; + status = -140; + goto on_return; } /* Send packet as quickly as possible */ for (i=0; ierr && !state2->err; ++i) { - struct tcp_pkt *pkt; - struct send_key send_key[2], *op_key; - pj_ssize_t len; - - pkt = (struct tcp_pkt*)state2->pkt; - pkt->signature = SIGNATURE; - pkt->seq = i; - pj_memset(pkt->fill, 'a', sizeof(pkt->fill)); - - op_key = &send_key[i%2]; - pj_ioqueue_op_key_init(&op_key->op_key, sizeof(*op_key)); - - state2->sent = PJ_FALSE; - len = sizeof(*pkt); - status = pj_activesock_send(asock2, &op_key->op_key, pkt, &len, 0); - if (status == PJ_EPENDING) { - do { + struct tcp_pkt *pkt; + struct send_key send_key[2], *op_key; + pj_ssize_t len; + + pkt = (struct tcp_pkt*)state2->pkt; + pkt->signature = SIGNATURE; + pkt->seq = i; + pj_memset(pkt->fill, 'a', sizeof(pkt->fill)); + + op_key = &send_key[i%2]; + pj_ioqueue_op_key_init(&op_key->op_key, sizeof(*op_key)); + + state2->sent = PJ_FALSE; + len = sizeof(*pkt); + status = pj_activesock_send(asock2, &op_key->op_key, pkt, &len, 0); + if (status == PJ_EPENDING) { + do { #if PJ_SYMBIAN - pj_symbianos_poll(-1, -1); + pj_symbianos_poll(-1, -1); #else - pj_ioqueue_poll(ioqueue, NULL); + pj_ioqueue_poll(ioqueue, NULL); #endif - } while (!state2->sent); - } else { + } while (!state2->sent); + } else { #if PJ_SYMBIAN - /* The Symbian socket always returns PJ_SUCCESS for TCP send, - * eventhough the remote end hasn't received the data yet. - * If we continue sending, eventually send() will block, - * possibly because the send buffer is full. So we need to - * poll the ioqueue periodically, to let receiver gets the - * data. - */ - pj_symbianos_poll(-1, 0); + /* The Symbian socket always returns PJ_SUCCESS for TCP send, + * eventhough the remote end hasn't received the data yet. + * If we continue sending, eventually send() will block, + * possibly because the send buffer is full. So we need to + * poll the ioqueue periodically, to let receiver gets the + * data. + */ + pj_symbianos_poll(-1, 0); #endif - if (status != PJ_SUCCESS) { - PJ_LOG(1,("", " err: send status=%d", status)); - status = -180; - break; - } else if (status == PJ_SUCCESS) { - if (len != sizeof(*pkt)) { - PJ_LOG(1,("", " err: shouldn't report partial sent")); - status = -190; - break; - } - } - } + if (status != PJ_SUCCESS) { + PJ_LOG(1,("", " err: send status=%d", status)); + status = -180; + break; + } else if (status == PJ_SUCCESS) { + if (len != sizeof(*pkt)) { + PJ_LOG(1,("", " err: shouldn't report partial sent")); + status = -190; + break; + } + } + } #ifndef PJ_SYMBIAN - for (;;) { - pj_time_val timeout = {0, 10}; - if (pj_ioqueue_poll(ioqueue, &timeout) < 1) - break; - } + for (;;) { + pj_time_val timeout = {0, 10}; + if (pj_ioqueue_poll(ioqueue, &timeout) < 1) + break; + } #endif } @@ -449,45 +448,45 @@ static int tcp_perf_test(void) /* Wait until everything has been sent/received */ if (state1->next_recv_seq < COUNT) { #ifdef PJ_SYMBIAN - while (pj_symbianos_poll(-1, 1000) == PJ_TRUE) - ; + while (pj_symbianos_poll(-1, 1000) == PJ_TRUE) + ; #else - pj_time_val delay = {0, 100}; - while (pj_ioqueue_poll(ioqueue, &delay) > 0) - ; + pj_time_val delay = {0, 100}; + while (pj_ioqueue_poll(ioqueue, &delay) > 0) + ; #endif } if (status == PJ_EPENDING) - status = PJ_SUCCESS; + status = PJ_SUCCESS; if (status != 0) - goto on_return; + goto on_return; if (state1->err) { - status = -183; - goto on_return; + status = -183; + goto on_return; } if (state2->err) { - status = -186; - goto on_return; + status = -186; + goto on_return; } if (state1->next_recv_seq != COUNT) { - PJ_LOG(3,("", " err: only %u packets received, expecting %u", - state1->next_recv_seq, COUNT)); - status = -195; - goto on_return; + PJ_LOG(3,("", " err: only %u packets received, expecting %u", + state1->next_recv_seq, COUNT)); + status = -195; + goto on_return; } on_return: if (asock2) - pj_activesock_close(asock2); + pj_activesock_close(asock2); if (asock1) - pj_activesock_close(asock1); + pj_activesock_close(asock1); if (ioqueue) - pj_ioqueue_destroy(ioqueue); + pj_ioqueue_destroy(ioqueue); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return status; } @@ -501,20 +500,20 @@ int activesock_test(void) PJ_LOG(3,("", "..udp ping/pong test")); ret = udp_ping_pong_test(); if (ret != 0) - return ret; + return ret; PJ_LOG(3,("", "..tcp perf test")); ret = tcp_perf_test(); if (ret != 0) - return ret; + return ret; return 0; } -#else /* INCLUDE_ACTIVESOCK_TEST */ +#else /* INCLUDE_ACTIVESOCK_TEST */ /* To prevent warning about "translation unit is empty" * when this test is disabled. */ int dummy_active_sock_test; -#endif /* INCLUDE_ACTIVESOCK_TEST */ +#endif /* INCLUDE_ACTIVESOCK_TEST */ diff --git a/pjlib/src/pjlib-test/atomic.c b/pjlib/src/pjlib-test/atomic.c index d94f5905da..8bd0a5a222 100644 --- a/pjlib/src/pjlib-test/atomic.c +++ b/pjlib/src/pjlib-test/atomic.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pjlib-test/echo_clt.c b/pjlib/src/pjlib-test/echo_clt.c index 6fd5eb8ecf..e36c0da556 100644 --- a/pjlib/src/pjlib-test/echo_clt.c +++ b/pjlib/src/pjlib-test/echo_clt.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -88,9 +87,9 @@ static int echo_client_thread(void *arg) } PJ_LOG(3,("", "...socket connected to %s:%d", - pj_inet_ntop2(pj_AF_INET(), &addr.sin_addr, - addr, sizeof(addr)), - pj_ntohs(addr.sin_port))); + pj_inet_ntop2(pj_AF_INET(), &addr.sin_addr, + addr, sizeof(addr)), + pj_ntohs(addr.sin_port))); pj_memset(send_buf, 'A', BUF_SIZE); send_buf[BUF_SIZE-1]='\0'; @@ -109,14 +108,14 @@ static int echo_client_thread(void *arg) int rc; pj_ssize_t bytes; - ++counter; + ++counter; - //while (wait_socket(sock,0) > 0) - // ; + //while (wait_socket(sock,0) > 0) + // ; /* Send a packet. */ bytes = BUF_SIZE; - *(pj_uint32_t*)(send_buf+4) = ++buffer_counter; + *(pj_uint32_t*)(send_buf+4) = ++buffer_counter; rc = pj_sock_send(sock, send_buf, &bytes, 0); if (rc != PJ_SUCCESS || bytes != BUF_SIZE) { if (rc != last_send_err) { @@ -131,12 +130,12 @@ static int echo_client_thread(void *arg) rc = wait_socket(sock, 500); if (rc == 0) { PJ_LOG(3,("", "...timeout")); - bytes = 0; - pj_atomic_inc(timeout_counter); - } else if (rc < 0) { - rc = pj_get_netos_error(); - app_perror("...select() error", rc); - break; + bytes = 0; + pj_atomic_inc(timeout_counter); + } else if (rc < 0) { + rc = pj_get_netos_error(); + app_perror("...select() error", rc); + break; } else { /* Receive back the original packet. */ bytes = 0; @@ -151,7 +150,7 @@ static int echo_client_thread(void *arg) pj_thread_sleep(100); } bytes = 0; - received = 0; + received = 0; break; } bytes += received; @@ -162,16 +161,16 @@ static int echo_client_thread(void *arg) continue; if (pj_memcmp(send_buf, recv_buf, BUF_SIZE) != 0) { - recv_buf[BUF_SIZE-1] = '\0'; + recv_buf[BUF_SIZE-1] = '\0'; PJ_LOG(3,("", "...error: buffer %u has changed!\n" - "send_buf=%s\n" - "recv_buf=%s\n", - counter, send_buf, recv_buf)); - pj_atomic_inc(invalid_counter); + "send_buf=%s\n" + "recv_buf=%s\n", + counter, send_buf, recv_buf)); + pj_atomic_inc(invalid_counter); } /* Accumulate total received. */ - pj_atomic_add(totalBytes, bytes); + pj_atomic_add(totalBytes, bytes); } pj_sock_close(sock); @@ -221,40 +220,40 @@ int echo_client(int sock_type, const char *server, int port) pj_get_timestamp(&last_report); for (;;) { - pj_timestamp now; - unsigned long received, cur_received; - unsigned msec; - pj_highprec_t bw; - pj_time_val elapsed; - unsigned bw32; - pj_uint32_t timeout, invalid; - - pj_thread_sleep(1000); - - pj_get_timestamp(&now); - elapsed = pj_elapsed_time(&last_report, &now); - msec = PJ_TIME_VAL_MSEC(elapsed); - - received = pj_atomic_get(totalBytes); - cur_received = received - last_received; - - bw = cur_received; - pj_highprec_mul(bw, 1000); - pj_highprec_div(bw, msec); - - bw32 = (unsigned)bw; - - last_report = now; - last_received = received; - - timeout = pj_atomic_get(timeout_counter); - invalid = pj_atomic_get(invalid_counter); + pj_timestamp now; + unsigned long received, cur_received; + unsigned msec; + pj_highprec_t bw; + pj_time_val elapsed; + unsigned bw32; + pj_uint32_t timeout, invalid; + + pj_thread_sleep(1000); + + pj_get_timestamp(&now); + elapsed = pj_elapsed_time(&last_report, &now); + msec = PJ_TIME_VAL_MSEC(elapsed); + + received = pj_atomic_get(totalBytes); + cur_received = received - last_received; + + bw = cur_received; + pj_highprec_mul(bw, 1000); + pj_highprec_div(bw, msec); + + bw32 = (unsigned)bw; + + last_report = now; + last_received = received; + + timeout = pj_atomic_get(timeout_counter); + invalid = pj_atomic_get(invalid_counter); PJ_LOG(3,("", - "...%d threads, total bandwidth: %d KB/s, " - "timeout=%d, invalid=%d", + "...%d threads, total bandwidth: %d KB/s, " + "timeout=%d, invalid=%d", ECHO_CLIENT_MAX_THREADS, bw32/1000, - timeout, invalid)); + timeout, invalid)); } for (i=0; i @@ -169,6 +168,6 @@ int errno_test(void) } -#endif /* INCLUDE_ERRNO_TEST */ +#endif /* INCLUDE_ERRNO_TEST */ diff --git a/pjlib/src/pjlib-test/exception.c b/pjlib/src/pjlib-test/exception.c index 8d9f44bc93..a51a550248 100644 --- a/pjlib/src/pjlib-test/exception.c +++ b/pjlib/src/pjlib-test/exception.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -48,12 +47,12 @@ #include -#ifdef _MSC_VER +#ifdef _MSC_VER #pragma warning(disable:4702) // warning C4702: unreachable code #endif -#define ID_1 1 -#define ID_2 2 +#define ID_1 1 +#define ID_2 2 static int throw_id_1(void) { @@ -73,10 +72,10 @@ static int try_catch_test(void) int rc = -200; PJ_TRY { - PJ_THROW(ID_1); + PJ_THROW(ID_1); } PJ_CATCH_ANY { - rc = 0; + rc = 0; } PJ_END; return rc; @@ -88,13 +87,13 @@ static int throw_in_handler(void) int rc = 0; PJ_TRY { - PJ_THROW(ID_1); + PJ_THROW(ID_1); } PJ_CATCH_ANY { - if (PJ_GET_EXCEPTION() != ID_1) - rc = -300; - else - PJ_THROW(ID_2); + if (PJ_GET_EXCEPTION() != ID_1) + rc = -300; + else + PJ_THROW(ID_2); } PJ_END; return rc; @@ -105,10 +104,10 @@ static int return_in_handler(void) PJ_USE_EXCEPTION; PJ_TRY { - PJ_THROW(ID_1); + PJ_THROW(ID_1); } PJ_CATCH_ANY { - return 0; + return 0; } PJ_END; return -400; @@ -132,115 +131,115 @@ static int test(void) PJ_END; if (rc != 0) - return rc; + return rc; /* * Basic TRY/CATCH */ PJ_TRY { - rc = throw_id_1(); + rc = throw_id_1(); - // should not reach here. - rc = -10; + // should not reach here. + rc = -10; } PJ_CATCH_ANY { int id = PJ_GET_EXCEPTION(); - if (id != ID_1) { - PJ_LOG(3,("", "...error: got unexpected exception %d (%s)", - id, pj_exception_id_name(id))); - if (!rc) rc = -20; - } + if (id != ID_1) { + PJ_LOG(3,("", "...error: got unexpected exception %d (%s)", + id, pj_exception_id_name(id))); + if (!rc) rc = -20; + } } PJ_END; if (rc != 0) - return rc; + return rc; /* * Multiple exceptions handlers */ PJ_TRY { - rc = throw_id_2(); - // should not reach here. - rc = -25; + rc = throw_id_2(); + // should not reach here. + rc = -25; } PJ_CATCH_ANY { - switch (PJ_GET_EXCEPTION()) { - case ID_1: - if (!rc) rc = -30; - break; - case ID_2: - if (!rc) rc = 0; - break; - default: - if (!rc) rc = -40; - break; - } + switch (PJ_GET_EXCEPTION()) { + case ID_1: + if (!rc) rc = -30; + break; + case ID_2: + if (!rc) rc = 0; + break; + default: + if (!rc) rc = -40; + break; + } } PJ_END; if (rc != 0) - return rc; + return rc; /* * Test default handler. */ PJ_TRY { - rc = throw_id_1(); - // should not reach here - rc = -50; + rc = throw_id_1(); + // should not reach here + rc = -50; } PJ_CATCH_ANY { - switch (PJ_GET_EXCEPTION()) { - case ID_1: - if (!rc) rc = 0; - break; - default: - if (!rc) rc = -60; - break; - } + switch (PJ_GET_EXCEPTION()) { + case ID_1: + if (!rc) rc = 0; + break; + default: + if (!rc) rc = -60; + break; + } } PJ_END; if (rc != 0) - return rc; + return rc; /* * Nested handlers */ PJ_TRY { - rc = try_catch_test(); + rc = try_catch_test(); } PJ_CATCH_ANY { - rc = -70; + rc = -70; } PJ_END; if (rc != 0) - return rc; + return rc; /* * Throwing exception inside handler */ rc = -80; PJ_TRY { - int rc2; - rc2 = throw_in_handler(); - if (rc2) - rc = rc2; + int rc2; + rc2 = throw_in_handler(); + if (rc2) + rc = rc2; } PJ_CATCH_ANY { - if (PJ_GET_EXCEPTION() == ID_2) { - rc = 0; - } else { - rc = -90; - } + if (PJ_GET_EXCEPTION() == ID_2) { + rc = 0; + } else { + rc = -90; + } } PJ_END; if (rc != 0) - return rc; + return rc; /* @@ -250,13 +249,13 @@ static int test(void) * is cleaned up properly, but not sure how to do this. */ PJ_TRY { - int rc2; - rc2 = return_in_handler(); - if (rc2) - rc = rc2; + int rc2; + rc2 = return_in_handler(); + if (rc2) + rc = rc2; } PJ_CATCH_ANY { - rc = -100; + rc = -100; } PJ_END; @@ -270,10 +269,10 @@ int exception_test(void) enum { LOOP = 10 }; for (i=0; i @@ -31,8 +30,8 @@ int dummy_fifobuf_test; int fifobuf_test() { enum { SIZE = 1024, MAX_ENTRIES = 128, - MIN_SIZE = 4, MAX_SIZE = 64, - LOOP=10000 }; + MIN_SIZE = 4, MAX_SIZE = 64, + LOOP=10000 }; pj_pool_t *pool; pj_fifobuf_t fifo; unsigned available = SIZE; @@ -42,76 +41,76 @@ int fifobuf_test() pool = pj_pool_create(mem, NULL, SIZE+256, 0, NULL); if (!pool) - return -10; + return -10; buffer = pj_pool_alloc(pool, SIZE); if (!buffer) - return -20; + return -20; pj_fifobuf_init (&fifo, buffer, SIZE); // Test 1 for (i=0; i=MIN_SIZE+4 && count < MAX_ENTRIES;) { - int size = MIN_SIZE+(pj_rand() % MAX_SIZE); - entries[count] = pj_fifobuf_alloc (&fifo, size); - if (entries[count]) { - available -= (size+4); - ++count; - } - } - for (j=0; j=MIN_SIZE+4 && count < MAX_ENTRIES;) { + int size = MIN_SIZE+(pj_rand() % MAX_SIZE); + entries[count] = pj_fifobuf_alloc (&fifo, size); + if (entries[count]) { + available -= (size+4); + ++count; + } + } + for (j=0; j @@ -27,7 +26,7 @@ #define INCLUDE_FILE_TIME_TEST 0 static char buffer[11] = {'H', 'e', 'l', 'l', 'o', ' ', - 'W', 'o', 'r', 'l', 'd' }; + 'W', 'o', 'r', 'l', 'd' }; static int file_test_internal(void) { @@ -131,8 +130,8 @@ static int file_test_internal(void) read = 1; status = pj_file_read(fd, &readbuf[size], &read); if (status != PJ_SUCCESS) { - PJ_LOG(3,("", "...error reading file after %d bytes (error follows)", - size)); + PJ_LOG(3,("", "...error reading file after %d bytes (error follows)", + size)); app_perror("...error", status); return -110; } diff --git a/pjlib/src/pjlib-test/hash_test.c b/pjlib/src/pjlib-test/hash_test.c index c1ce4ad9ad..fb59331309 100644 --- a/pjlib/src/pjlib-test/hash_test.c +++ b/pjlib/src/pjlib-test/hash_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,48 +35,48 @@ static int hash_test_with_key(pj_pool_t *pool, unsigned char key) ht = pj_hash_create(pool, HASH_COUNT); if (!ht) - return -10; + return -10; pj_hash_set(pool, ht, &key, sizeof(key), 0, &value); entry = (unsigned*) pj_hash_get(ht, &key, sizeof(key), NULL); if (!entry) - return -20; + return -20; if (*entry != value) - return -30; + return -30; if (pj_hash_count(ht) != 1) - return -30; + return -30; it = pj_hash_first(ht, &it_buf); if (it == NULL) - return -40; + return -40; entry = (unsigned*) pj_hash_this(ht, it); if (!entry) - return -50; + return -50; if (*entry != value) - return -60; + return -60; it = pj_hash_next(ht, it); if (it != NULL) - return -70; + return -70; /* Erase item */ pj_hash_set(NULL, ht, &key, sizeof(key), 0, NULL); if (pj_hash_get(ht, &key, sizeof(key), NULL) != NULL) - return -80; + return -80; if (pj_hash_count(ht) != 0) - return -90; + return -90; it = pj_hash_first(ht, &it_buf); if (it != NULL) - return -100; + return -100; return 0; } @@ -86,7 +85,7 @@ static int hash_test_with_key(pj_pool_t *pool, unsigned char key) static int hash_collision_test(pj_pool_t *pool) { enum { - COUNT = HASH_COUNT * 4 + COUNT = HASH_COUNT * 4 }; pj_hash_table_t *ht; pj_hash_iterator_t it_buf, *it; @@ -95,36 +94,36 @@ static int hash_collision_test(pj_pool_t *pool) ht = pj_hash_create(pool, HASH_COUNT); if (!ht) - return -200; + return -200; values = (unsigned char*) pj_pool_alloc(pool, COUNT); for (i=0; i @@ -39,8 +38,8 @@ # pragma warning ( disable: 4204) // non-constant aggregate initializer #endif -#define THIS_FILE "ioq_perf" -//#define TRACE_(expr) PJ_LOG(3,expr) +#define THIS_FILE "ioq_perf" +//#define TRACE_(expr) PJ_LOG(3,expr) #define TRACE_(expr) @@ -55,19 +54,19 @@ static unsigned last_error_counter; * b) any thread that first reaches this value will cause other threads to * quit, even if that other threads have not processed anything. */ -//#define LIMIT_TRANSFER 10000 -#define LIMIT_TRANSFER 0 +//#define LIMIT_TRANSFER 10000 +#define LIMIT_TRANSFER 0 /* Silenced error(s): * -Linux/Unix: EAGAIN (Resource temporarily unavailable) * -Windows: WSAEWOULDBLOCK */ -#define IS_ERROR_SILENCED(e) ((e)==PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) +#define IS_ERROR_SILENCED(e) ((e)==PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) /* Descriptor for each producer/consumer pair. */ typedef struct test_item { - const char *type_name; + const char *type_name; pj_sock_t server_fd, client_fd; pj_ioqueue_t *ioqueue; @@ -103,31 +102,31 @@ static void on_read_complete(pj_ioqueue_key_t *key, if (bytes_read < 0) { char errmsg[PJ_ERR_MSG_SIZE]; - rc = (pj_status_t)-bytes_read; - if (rc != last_error) { - //last_error = rc; - - /* Note: - * we can receive EAGAIN (on Linux/Unix) or EWOULDBLOCK (on Win) - * when we have more than one threads competing to do recv(). - * This is a normal situation even when EPOLLEXCLUSIVE is used - * (e.g two packets arrive at the same time, causing both - * threads to wake up, but thread A greedily read the packets) - * therefore we silence the error here. - */ - if (!IS_ERROR_SILENCED(rc)) { - pj_strerror(rc, errmsg, sizeof(errmsg)); - PJ_LOG(3,(THIS_FILE,"...error: read error, bytes_read=%d (%s)", - bytes_read, errmsg)); - PJ_LOG(3,(THIS_FILE, - ".....additional info: type=%s, total read=%u, " - "total sent=%u", - item->type_name, item->bytes_recv, - item->bytes_sent)); - } - } else { - last_error_counter++; - } + rc = (pj_status_t)-bytes_read; + if (rc != last_error) { + //last_error = rc; + + /* Note: + * we can receive EAGAIN (on Linux/Unix) or EWOULDBLOCK (on Win) + * when we have more than one threads competing to do recv(). + * This is a normal situation even when EPOLLEXCLUSIVE is used + * (e.g two packets arrive at the same time, causing both + * threads to wake up, but thread A greedily read the packets) + * therefore we silence the error here. + */ + if (!IS_ERROR_SILENCED(rc)) { + pj_strerror(rc, errmsg, sizeof(errmsg)); + PJ_LOG(3,(THIS_FILE,"...error: read error, bytes_read=%d (%s)", + bytes_read, errmsg)); + PJ_LOG(3,(THIS_FILE, + ".....additional info: type=%s, total read=%u, " + "total sent=%u", + item->type_name, item->bytes_recv, + item->bytes_sent)); + } + } else { + last_error_counter++; + } bytes_read = 0; } else if (bytes_read == 0) { @@ -140,7 +139,7 @@ static void on_read_complete(pj_ioqueue_key_t *key, * doesn't have time to run. */ if (LIMIT_TRANSFER && item->bytes_recv>item->buffer_size*LIMIT_TRANSFER) - thread_quit_flag = 1; + thread_quit_flag = 1; bytes_read = item->buffer_size; rc = pj_ioqueue_recv( key, op_key, @@ -152,12 +151,12 @@ static void on_read_complete(pj_ioqueue_key_t *key, data_is_available = 0; } else { data_is_available = 0; - if (rc != last_error) { - last_error = rc; - app_perror("...error: read error(1)", rc); - } else { - last_error_counter++; - } + if (rc != last_error) { + last_error = rc; + app_perror("...error: read error(1)", rc); + } else { + last_error_counter++; + } } if (!item->has_pending_send) { @@ -167,7 +166,7 @@ static void on_read_complete(pj_ioqueue_key_t *key, if (rc != PJ_SUCCESS && rc != PJ_EPENDING) { app_perror("...error: write error", rc); } else if (rc == PJ_SUCCESS) { - item->bytes_sent += sent; + item->bytes_sent += sent; } item->has_pending_send = (rc==PJ_EPENDING); @@ -191,12 +190,12 @@ static void on_write_complete(pj_ioqueue_key_t *key, return; if (bytes_sent <= 0) { - if (!IS_ERROR_SILENCED(-bytes_sent)) { - PJ_PERROR(3, (THIS_FILE, (pj_status_t)-bytes_sent, - "...error: sending stopped. bytes_sent=%d", - -bytes_sent)); - } - item->has_pending_send = 0; + if (!IS_ERROR_SILENCED(-bytes_sent)) { + PJ_PERROR(3, (THIS_FILE, (pj_status_t)-bytes_sent, + "...error: sending stopped. bytes_sent=%d", + -bytes_sent)); + } + item->has_pending_send = 0; } else if (!item->has_pending_send) { pj_status_t rc; @@ -217,11 +216,11 @@ static void on_write_complete(pj_ioqueue_key_t *key, struct thread_arg { - int id; + int id; pj_ioqueue_t *ioqueue; - unsigned loop_cnt, - err_cnt, - event_cnt; + unsigned loop_cnt, + err_cnt, + event_cnt; }; /* The worker thread. */ @@ -233,16 +232,16 @@ static int worker_thread(void *p) while (!thread_quit_flag) { - ++arg->loop_cnt; + ++arg->loop_cnt; rc = pj_ioqueue_poll(arg->ioqueue, &timeout); - //TRACE_((THIS_FILE, " thread: poll returned rc=%d", rc)); + //TRACE_((THIS_FILE, " thread: poll returned rc=%d", rc)); if (rc < 0) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(-rc, errmsg, sizeof(errmsg)); + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(-rc, errmsg, sizeof(errmsg)); PJ_LOG(3, (THIS_FILE, - "...error in pj_ioqueue_poll() in thread %d " - "after %d loop: %s [pj_status_t=%d]", - arg->id, arg->loop_cnt, errmsg, -rc)); + "...error in pj_ioqueue_poll() in thread %d " + "after %d loop: %s [pj_status_t=%d]", + arg->id, arg->loop_cnt, errmsg, -rc)); //return -1; ++arg->err_cnt; } else if (rc > 0) { @@ -264,10 +263,10 @@ static int worker_thread(void *p) * period of time. */ static int perform_test(const pj_ioqueue_cfg *cfg, - int sock_type, const char *type_name, + int sock_type, const char *type_name, unsigned thread_cnt, unsigned sockpair_cnt, pj_size_t buffer_size, - pj_bool_t display_report, + pj_bool_t display_report, pj_size_t *p_bandwidth) { enum { MSEC_DURATION = 5000 }; @@ -296,7 +295,7 @@ static int perform_test(const pj_ioqueue_cfg *cfg, items = (test_item*) pj_pool_calloc(pool, sockpair_cnt, sizeof(test_item)); thread = (pj_thread_t**) - pj_pool_alloc(pool, thread_cnt*sizeof(pj_thread_t*)); + pj_pool_alloc(pool, thread_cnt*sizeof(pj_thread_t*)); TRACE_((THIS_FILE, " creating ioqueue..")); rc = pj_ioqueue_create2(pool, sockpair_cnt*2, cfg, &ioqueue); @@ -324,7 +323,7 @@ static int perform_test(const pj_ioqueue_cfg *cfg, pj_ioqueue_op_key_init(&items[i].send_op, sizeof(items[i].send_op)); /* Create socket pair. */ - TRACE_((THIS_FILE, " calling socketpair..")); + TRACE_((THIS_FILE, " calling socketpair..")); rc = app_socketpair(pj_AF_INET(), sock_type, 0, &items[i].server_fd, &items[i].client_fd); if (rc != PJ_SUCCESS) { @@ -333,7 +332,7 @@ static int perform_test(const pj_ioqueue_cfg *cfg, } /* Register server socket to ioqueue. */ - TRACE_((THIS_FILE, " register(1)..")); + TRACE_((THIS_FILE, " register(1)..")); rc = pj_ioqueue_register_sock(pool, ioqueue, items[i].server_fd, &items[i], &ioqueue_callback, @@ -344,7 +343,7 @@ static int perform_test(const pj_ioqueue_cfg *cfg, } /* Register client socket to ioqueue. */ - TRACE_((THIS_FILE, " register(2)..")); + TRACE_((THIS_FILE, " register(2)..")); rc = pj_ioqueue_register_sock(pool, ioqueue, items[i].client_fd, &items[i], &ioqueue_callback, @@ -355,18 +354,18 @@ static int perform_test(const pj_ioqueue_cfg *cfg, } /* Start reading. */ - TRACE_((THIS_FILE, " pj_ioqueue_recv..")); + TRACE_((THIS_FILE, " pj_ioqueue_recv..")); bytes = items[i].buffer_size; rc = pj_ioqueue_recv(items[i].server_key, &items[i].recv_op, items[i].incoming_buffer, &bytes, - 0); + 0); if (rc != PJ_EPENDING) { app_perror("...error: pj_ioqueue_recv", rc); return -73; } /* Start writing. */ - TRACE_((THIS_FILE, " pj_ioqueue_write..")); + TRACE_((THIS_FILE, " pj_ioqueue_write..")); bytes = items[i].buffer_size; rc = pj_ioqueue_send(items[i].client_key, &items[i].send_op, items[i].outgoing_buffer, &bytes, 0); @@ -382,11 +381,11 @@ static int perform_test(const pj_ioqueue_cfg *cfg, /* Create the threads. */ args = (struct thread_arg*) pj_pool_calloc(pool, thread_cnt, - sizeof(struct thread_arg)); + sizeof(struct thread_arg)); for (i=0; iid = i; - arg->ioqueue = ioqueue; + struct thread_arg *arg = &args[i]; + arg->id = i; + arg->ioqueue = ioqueue; rc = pj_thread_create( pool, NULL, &worker_thread, @@ -419,20 +418,20 @@ static int perform_test(const pj_ioqueue_cfg *cfg, */ TRACE_((THIS_FILE, " wait for few seconds..")); do { - pj_thread_sleep(1); + pj_thread_sleep(1); - /* Mark end time. */ - rc = pj_get_timestamp(&stop); + /* Mark end time. */ + rc = pj_get_timestamp(&stop); - if (thread_quit_flag) { - TRACE_((THIS_FILE, " transfer limit reached..")); - break; - } + if (thread_quit_flag) { + TRACE_((THIS_FILE, " transfer limit reached..")); + break; + } - if (pj_elapsed_usec(&start,&stop) > MSEC_DURATION * 1000) { - TRACE_((THIS_FILE, " time limit reached..")); - break; - } + if (pj_elapsed_usec(&start,&stop) > MSEC_DURATION * 1000) { + TRACE_((THIS_FILE, " time limit reached..")); + break; + } } while (1); @@ -441,7 +440,7 @@ static int perform_test(const pj_ioqueue_cfg *cfg, thread_quit_flag = 1; for (i=0; iid, arg->loop_cnt, arg->event_cnt, arg->err_cnt)); - } - PJ_LOG(3,(THIS_FILE, " =============================")); - PJ_LOG(3,(THIS_FILE, " Socket-pair statistics:")); - PJ_LOG(3,(THIS_FILE, " ===================================")); - PJ_LOG(3,(THIS_FILE, " Pair Sent Recv Pct total")); - PJ_LOG(3,(THIS_FILE, " ===================================")); - for (i=0; ibytes_sent/1000000.0, - item->bytes_recv/1000000.0, - item->bytes_recv*100.0/total_received)); - } + PJ_LOG(3,(THIS_FILE, " %s %d threads, %d pairs", type_name, + thread_cnt, sockpair_cnt)); + PJ_LOG(3,(THIS_FILE, " Elapsed : %u msec", total_elapsed_usec/1000)); + PJ_LOG(3,(THIS_FILE, " Bandwidth: %d KB/s", *p_bandwidth)); + PJ_LOG(3,(THIS_FILE, " Threads statistics:")); + PJ_LOG(3,(THIS_FILE, " =============================")); + PJ_LOG(3,(THIS_FILE, " Thread Loops Events Errors")); + PJ_LOG(3,(THIS_FILE, " =============================")); + for (i=0; iid, arg->loop_cnt, arg->event_cnt, arg->err_cnt)); + } + PJ_LOG(3,(THIS_FILE, " =============================")); + PJ_LOG(3,(THIS_FILE, " Socket-pair statistics:")); + PJ_LOG(3,(THIS_FILE, " ===================================")); + PJ_LOG(3,(THIS_FILE, " Pair Sent Recv Pct total")); + PJ_LOG(3,(THIS_FILE, " ===================================")); + for (i=0; ibytes_sent/1000000.0, + item->bytes_recv/1000000.0, + item->bytes_recv*100.0/total_received)); + } } else { - PJ_LOG(3,(THIS_FILE, " %.4s %2d %2d %8d KB/s", - type_name, thread_cnt, sockpair_cnt, - *p_bandwidth)); + PJ_LOG(3,(THIS_FILE, " %.4s %2d %2d %8d KB/s", + type_name, thread_cnt, sockpair_cnt, + *p_bandwidth)); } /* Done. */ @@ -536,15 +535,15 @@ static int ioqueue_perf_test_imp(const pj_ioqueue_cfg *cfg) { pj_SOCK_STREAM(), "tcp", 1, 1}, { pj_SOCK_STREAM(), "tcp", 2, 2}, { pj_SOCK_STREAM(), "tcp", 4, 4}, - { pj_SOCK_STREAM(), "tcp", 8, 8}, - { pj_SOCK_STREAM(), "tcp", 16, 16}, + { pj_SOCK_STREAM(), "tcp", 8, 8}, + { pj_SOCK_STREAM(), "tcp", 16, 16}, }; pj_size_t best_bandwidth; int best_index = 0; PJ_LOG(3,(THIS_FILE, " Benchmarking %s ioqueue:", pj_ioqueue_name())); PJ_LOG(3,(THIS_FILE, " Testing with concurency=%d, epoll_flags=0x%x", - cfg->default_concurrency, cfg->epoll_flags)); + cfg->default_concurrency, cfg->epoll_flags)); PJ_LOG(3,(THIS_FILE, " =======================================")); PJ_LOG(3,(THIS_FILE, " Type Threads Skt.Pairs Bandwidth")); PJ_LOG(3,(THIS_FILE, " =======================================")); @@ -554,12 +553,12 @@ static int ioqueue_perf_test_imp(const pj_ioqueue_cfg *cfg) pj_size_t bandwidth; rc = perform_test(cfg, - test_param[i].type, + test_param[i].type, test_param[i].type_name, test_param[i].thread_cnt, test_param[i].sockpair_cnt, BUF_SIZE, - PJ_FALSE, + PJ_FALSE, &bandwidth); if (rc != 0) return rc; @@ -568,8 +567,8 @@ static int ioqueue_perf_test_imp(const pj_ioqueue_cfg *cfg) best_bandwidth = bandwidth, best_index = i; /* Give it a rest before next test, to allow system to close the - * sockets properly. - */ + * sockets properly. + */ pj_thread_sleep(500); } @@ -580,7 +579,7 @@ static int ioqueue_perf_test_imp(const pj_ioqueue_cfg *cfg) test_param[best_index].sockpair_cnt, best_bandwidth)); PJ_LOG(3,(THIS_FILE, " (Note: packet size=%d, total errors=%u)", - BUF_SIZE, last_error_counter)); + BUF_SIZE, last_error_counter)); return 0; } @@ -591,9 +590,9 @@ int ioqueue_perf_test(void) { pj_ioqueue_epoll_flag epoll_flags[] = { #if PJ_HAS_LINUX_EPOLL - PJ_IOQUEUE_EPOLL_EXCLUSIVE, - PJ_IOQUEUE_EPOLL_ONESHOT, - 0, + PJ_IOQUEUE_EPOLL_EXCLUSIVE, + PJ_IOQUEUE_EPOLL_ONESHOT, + 0, #else PJ_IOQUEUE_EPOLL_AUTO, #endif @@ -604,50 +603,50 @@ int ioqueue_perf_test(void) /* Defailed performance report (concurrency=1) */ for (i=0; i -#define THIS_FILE "ioq_stress_test.c" -#define MAX_THREADS 16 -#define TRACE(log) PJ_LOG(3,log) -#define MAX_ASYNC 16 +#define THIS_FILE "ioq_stress_test.c" +#define MAX_THREADS 16 +#define TRACE(log) PJ_LOG(3,log) +#define MAX_ASYNC 16 -#define RETCODE_CONNECT_FAILED 650 +#define RETCODE_CONNECT_FAILED 650 /* index in socks[], keys[] array */ -#define SERVER 0 -#define CLIENT 1 +#define SERVER 0 +#define CLIENT 1 /* epoll errors that can be ignored */ -#define IGNORE_ERROR(e) (((e)==PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL))) +#define IGNORE_ERROR(e) (((e)==PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL))) typedef struct test_desc test_desc; /* op_key user data */ typedef union op_key_user_data { struct { - int side; /* CLIENT or SERVER */ - pj_status_t status; /* PJ_SUCCESS: idle, PJ_EPENDING: pending, other: error */ - unsigned count; /* how many times were used */ + int side; /* CLIENT or SERVER */ + pj_status_t status; /* PJ_SUCCESS: idle, PJ_EPENDING: pending, other: error */ + unsigned count; /* how many times were used */ } common; struct { - int side; - pj_status_t status; - unsigned count; + int side; + pj_status_t status; + unsigned count; - pj_sock_t new_sock; - pj_ioqueue_op_key_t recv_op; - unsigned *recv_buf; + pj_sock_t new_sock; + pj_ioqueue_op_key_t recv_op; + unsigned *recv_buf; } server; struct { - int side; - pj_status_t status; - unsigned count; + int side; + pj_status_t status; + unsigned count; - pj_ioqueue_op_key_t connect_op; - pj_ioqueue_op_key_t send_op; - unsigned *send_buf; + pj_ioqueue_op_key_t connect_op; + pj_ioqueue_op_key_t send_op; + unsigned *send_buf; } client; } op_key_user_data; @@ -85,45 +84,45 @@ typedef union op_key_user_data { struct test_desc { struct { - const char *title; - int expected_ret_code; - int max_fd; /* ioqueue's max_fd */ - pj_bool_t allow_concur; /* ioqueue's allow_concur setting */ - unsigned epoll_flags; /* epoll_flags: EXCLUSIVE, ONESHOT */ - int sock_type; /* tcp or udp? */ - int n_threads; /* number of worker threads polling ioqueue */ - - pj_bool_t cancel_connect; /* TCP connect then cancel immediately */ - pj_bool_t failed_connect; /* TCP connect to nowhere */ - pj_bool_t reject_connect; /* close previously listen() without calling accept */ - unsigned tx_so_buf_size; /* SO_SNDBUF in multples of sizeof(int) */ - unsigned rx_so_buf_size; /* SO_RCVBUF in multples of sizeof(int) */ - unsigned pkt_len; /* size of each send()/recv() in mult. sizeof(int) */ - unsigned tx_cnt; /* total number of ints to send */ - unsigned rx_cnt; /* total number of ints to read */ - unsigned n_servers; /* number of servers (=parallel recv) to instantiate */ - unsigned n_clients; /* number of clients (=parallel send) to instantiate */ - pj_bool_t sequenced; /* incoming packets must be in sequence */ - unsigned repeat; + const char *title; + int expected_ret_code; + int max_fd; /* ioqueue's max_fd */ + pj_bool_t allow_concur; /* ioqueue's allow_concur setting */ + unsigned epoll_flags; /* epoll_flags: EXCLUSIVE, ONESHOT */ + int sock_type; /* tcp or udp? */ + int n_threads; /* number of worker threads polling ioqueue */ + + pj_bool_t cancel_connect; /* TCP connect then cancel immediately */ + pj_bool_t failed_connect; /* TCP connect to nowhere */ + pj_bool_t reject_connect; /* close previously listen() without calling accept */ + unsigned tx_so_buf_size; /* SO_SNDBUF in multples of sizeof(int) */ + unsigned rx_so_buf_size; /* SO_RCVBUF in multples of sizeof(int) */ + unsigned pkt_len; /* size of each send()/recv() in mult. sizeof(int) */ + unsigned tx_cnt; /* total number of ints to send */ + unsigned rx_cnt; /* total number of ints to read */ + unsigned n_servers; /* number of servers (=parallel recv) to instantiate */ + unsigned n_clients; /* number of clients (=parallel send) to instantiate */ + pj_bool_t sequenced; /* incoming packets must be in sequence */ + unsigned repeat; } cfg; struct { - pj_pool_t *pool; - pj_ioqueue_t *ioq; - pj_grp_lock_t *grp_lock; - pj_sock_t listen_sock; /* tcp listening socket */ - pj_ioqueue_key_t *listen_key;/* tcp listening key */ + pj_pool_t *pool; + pj_ioqueue_t *ioq; + pj_grp_lock_t *grp_lock; + pj_sock_t listen_sock; /* tcp listening socket */ + pj_ioqueue_key_t *listen_key;/* tcp listening key */ - pj_sock_t socks[2]; /* server/client sockets */ - unsigned cnt[2]; /* number of packets sent/received */ - pj_ioqueue_key_t *keys[2]; /* server/client keys */ - pj_status_t connect_status; + pj_sock_t socks[2]; /* server/client sockets */ + unsigned cnt[2]; /* number of packets sent/received */ + pj_ioqueue_key_t *keys[2]; /* server/client keys */ + pj_status_t connect_status; - int retcode; /* test retcode. non-zero will abort. */ + int retcode; /* test retcode. non-zero will abort. */ - /* okud: op_key user data */ - unsigned okuds_cnt[2]; - op_key_user_data okuds[2][MAX_ASYNC]; + /* okud: op_key user data */ + unsigned okuds_cnt[2]; + op_key_user_data okuds[2][MAX_ASYNC]; } state; }; @@ -152,89 +151,89 @@ static void on_read_complete(pj_ioqueue_key_t *key, assert(okud->common.side == SERVER); do { - unsigned counter = test->state.cnt[SERVER]; - - /* can only handle multiple of ints,*/ - PJ_ASSERT_ON_FAIL(bytes_read<0 || bytes_read%sizeof(int)==0, - { - test->state.retcode = 410; - okud->server.status = PJ_EBUG; - return; - }); - - if (bytes_read != -12345 && bytes_read <= 0 && !IGNORE_ERROR(-bytes_read)) { - TRACE((THIS_FILE, "op_key:%p: stopping due to read=%d", - op_key, bytes_read)); - PJ_PERROR(1,(THIS_FILE, (pj_status_t)-bytes_read, "%d is", -bytes_read)); - okud->server.status = (bytes_read == 0)? PJ_RETURN_OS_ERROR(OSERR_ENOTCONN) : - (pj_status_t)-bytes_read; - break; - } - - if (bytes_read > 0) { - pj_lock_acquire((pj_lock_t*)test->state.grp_lock); - if (test->cfg.sequenced) { - unsigned *p, *start, *end; - pj_bool_t has_error = PJ_FALSE; - - start = okud->server.recv_buf; - end = start + (bytes_read / sizeof(int)); - - for (p=start; p!=end; ++p) { - counter = test->state.cnt[SERVER]++; - if (*p != counter && test->cfg.sock_type==pj_SOCK_STREAM()) { - PJ_LOG(3,(THIS_FILE, " Error: TCP RX sequence mismatch at idx=%d. Expecting %d, got %d", - p-start, counter, *p)); - test->state.retcode = 412; - okud->server.status = PJ_EBUG; - pj_lock_release((pj_lock_t*)test->state.grp_lock); - return; - } else if (test->cfg.sock_type==pj_SOCK_DGRAM()) { - if (*p < counter && !has_error) { - /* As it turns out, this could happen sometimes - * with UDP even when allow_concurrent is set to FALSE. - * Maybe the kernel allows the packet to be out of - * order? (tested on Linux epoll). Or could there be - * bug somewhere? - */ - PJ_LOG(3,(THIS_FILE, " UDP RX sequence mismatch at idx=%d. Expecting %d, got %d", - p-start, counter, *p)); - //test->state.retcode = 413; - //okud->server.status = PJ_EBUG; - //pj_lock_release((pj_lock_t*)test->state.grp_lock); - //return; - has_error = PJ_TRUE; - } else if (*p > counter) { - test->state.cnt[SERVER] = *p; - } - } - } - } else { - test->state.cnt[SERVER] += (unsigned)(bytes_read / 4); - } - pj_lock_release((pj_lock_t*)test->state.grp_lock); - } - - if (counter >= test->cfg.rx_cnt) { - //TRACE((THIS_FILE, "op_key:%p: RX counter reached (%d)", - // op_key, counter)); - okud->server.status = PJ_SUCCESS; - break; - } - - /* next read */ - bytes_read = test->cfg.pkt_len * sizeof(int); - okud->server.status = pj_ioqueue_recv(key, op_key, okud->server.recv_buf, - &bytes_read, 0); - if (okud->server.status != PJ_SUCCESS && okud->server.status != PJ_EPENDING) { - PJ_PERROR(1,(THIS_FILE, okud->server.status, "pj_ioqueue_recv() error")); - test->state.retcode = 420; - return; - } + unsigned counter = test->state.cnt[SERVER]; + + /* can only handle multiple of ints,*/ + PJ_ASSERT_ON_FAIL(bytes_read<0 || bytes_read%sizeof(int)==0, + { + test->state.retcode = 410; + okud->server.status = PJ_EBUG; + return; + }); + + if (bytes_read != -12345 && bytes_read <= 0 && !IGNORE_ERROR(-bytes_read)) { + TRACE((THIS_FILE, "op_key:%p: stopping due to read=%d", + op_key, bytes_read)); + PJ_PERROR(1,(THIS_FILE, (pj_status_t)-bytes_read, "%d is", -bytes_read)); + okud->server.status = (bytes_read == 0)? PJ_RETURN_OS_ERROR(OSERR_ENOTCONN) : + (pj_status_t)-bytes_read; + break; + } + + if (bytes_read > 0) { + pj_lock_acquire((pj_lock_t*)test->state.grp_lock); + if (test->cfg.sequenced) { + unsigned *p, *start, *end; + pj_bool_t has_error = PJ_FALSE; + + start = okud->server.recv_buf; + end = start + (bytes_read / sizeof(int)); + + for (p=start; p!=end; ++p) { + counter = test->state.cnt[SERVER]++; + if (*p != counter && test->cfg.sock_type==pj_SOCK_STREAM()) { + PJ_LOG(3,(THIS_FILE, " Error: TCP RX sequence mismatch at idx=%d. Expecting %d, got %d", + p-start, counter, *p)); + test->state.retcode = 412; + okud->server.status = PJ_EBUG; + pj_lock_release((pj_lock_t*)test->state.grp_lock); + return; + } else if (test->cfg.sock_type==pj_SOCK_DGRAM()) { + if (*p < counter && !has_error) { + /* As it turns out, this could happen sometimes + * with UDP even when allow_concurrent is set to FALSE. + * Maybe the kernel allows the packet to be out of + * order? (tested on Linux epoll). Or could there be + * bug somewhere? + */ + PJ_LOG(3,(THIS_FILE, " UDP RX sequence mismatch at idx=%d. Expecting %d, got %d", + p-start, counter, *p)); + //test->state.retcode = 413; + //okud->server.status = PJ_EBUG; + //pj_lock_release((pj_lock_t*)test->state.grp_lock); + //return; + has_error = PJ_TRUE; + } else if (*p > counter) { + test->state.cnt[SERVER] = *p; + } + } + } + } else { + test->state.cnt[SERVER] += (unsigned)(bytes_read / 4); + } + pj_lock_release((pj_lock_t*)test->state.grp_lock); + } + + if (counter >= test->cfg.rx_cnt) { + //TRACE((THIS_FILE, "op_key:%p: RX counter reached (%d)", + // op_key, counter)); + okud->server.status = PJ_SUCCESS; + break; + } + + /* next read */ + bytes_read = test->cfg.pkt_len * sizeof(int); + okud->server.status = pj_ioqueue_recv(key, op_key, okud->server.recv_buf, + &bytes_read, 0); + if (okud->server.status != PJ_SUCCESS && okud->server.status != PJ_EPENDING) { + PJ_PERROR(1,(THIS_FILE, okud->server.status, "pj_ioqueue_recv() error")); + test->state.retcode = 420; + return; + } } while (okud->server.status==PJ_SUCCESS && - test->state.retcode==0 // <= this can be set by other thread - ); + test->state.retcode==0 // <= this can be set by other thread + ); } static void on_write_complete(pj_ioqueue_key_t *key, @@ -250,18 +249,18 @@ static void on_write_complete(pj_ioqueue_key_t *key, assert(okud->common.side == CLIENT); PJ_ASSERT_ON_FAIL(bytes_sent<0 || bytes_sent%sizeof(int)==0, - { - test->state.retcode = 501; - okud->client.status = PJ_EBUG; - return; - }); + { + test->state.retcode = 501; + okud->client.status = PJ_EBUG; + return; + }); if (bytes_sent != -12345 && bytes_sent <= 0 && !IGNORE_ERROR(-bytes_sent)) { - TRACE((THIS_FILE, "op_key:%p: stopping due to sent=%d", - op_key, bytes_sent)); - okud->client.status = (bytes_sent == 0)? PJ_RETURN_OS_ERROR(OSERR_ENOTCONN) : - (pj_status_t)-bytes_sent; - return; + TRACE((THIS_FILE, "op_key:%p: stopping due to sent=%d", + op_key, bytes_sent)); + okud->client.status = (bytes_sent == 0)? PJ_RETURN_OS_ERROR(OSERR_ENOTCONN) : + (pj_status_t)-bytes_sent; + return; } /* for TCP, client stop transmission when number of transmitted @@ -270,10 +269,10 @@ static void on_write_complete(pj_ioqueue_key_t *key, */ counter = test->state.cnt[CLIENT]; if (test->cfg.sock_type==pj_SOCK_STREAM() && counter >= test->cfg.tx_cnt) { - //TRACE((THIS_FILE, "op_key:%p: TX counter reached (%d)", - // op_key, counter)); - okud->client.status = PJ_SUCCESS; - return; + //TRACE((THIS_FILE, "op_key:%p: TX counter reached (%d)", + // op_key, counter)); + okud->client.status = PJ_SUCCESS; + return; } /* construct buffer as int sequence. @@ -284,21 +283,21 @@ static void on_write_complete(pj_ioqueue_key_t *key, p = okud->client.send_buf; end = p + test->cfg.pkt_len; while (p != end) - *p++ = test->state.cnt[CLIENT]++; + *p++ = test->state.cnt[CLIENT]++; /* next write */ bytes_sent = test->cfg.pkt_len * sizeof(int); okud->client.status = pj_ioqueue_send(key, op_key, okud->client.send_buf, - &bytes_sent, 0); + &bytes_sent, 0); if (okud->client.status != PJ_SUCCESS && okud->client.status != PJ_EPENDING) { - PJ_PERROR(1,(THIS_FILE, okud->client.status, "pj_ioqueue_send() error")); - test->state.retcode = 520; + PJ_PERROR(1,(THIS_FILE, okud->client.status, "pj_ioqueue_send() error")); + test->state.retcode = 520; } else if (okud->client.status == PJ_SUCCESS) { - counter = test->state.cnt[CLIENT]; - if (test->cfg.sock_type==pj_SOCK_STREAM() && counter >= test->cfg.tx_cnt) { - //TRACE((THIS_FILE, "op_key:%p: TX counter reached (%d)", - // op_key, counter)); - } + counter = test->state.cnt[CLIENT]; + if (test->cfg.sock_type==pj_SOCK_STREAM() && counter >= test->cfg.tx_cnt) { + //TRACE((THIS_FILE, "op_key:%p: TX counter reached (%d)", + // op_key, counter)); + } } pj_lock_release((pj_lock_t*)test->state.grp_lock); @@ -315,38 +314,38 @@ static void on_accept_complete(pj_ioqueue_key_t *key, assert(okud->common.side == SERVER); if (status != PJ_SUCCESS) { - okud->server.status = status; - return; + okud->server.status = status; + return; } test->state.socks[SERVER] = sock; pj_lock_acquire((pj_lock_t*)test->state.grp_lock); if (test->cfg.rx_so_buf_size) { - int value = test->cfg.rx_so_buf_size * sizeof(int); - okud->server.status = pj_sock_setsockopt(sock, - pj_SOL_SOCKET(), - pj_SO_RCVBUF(), - &value, sizeof(value)); + int value = test->cfg.rx_so_buf_size * sizeof(int); + okud->server.status = pj_sock_setsockopt(sock, + pj_SOL_SOCKET(), + pj_SO_RCVBUF(), + &value, sizeof(value)); } status = pj_ioqueue_register_sock2(test->state.pool, - test->state.ioq, - test->state.socks[SERVER], - test->state.grp_lock, - test, - &test_cb, - &test->state.keys[SERVER]); + test->state.ioq, + test->state.socks[SERVER], + test->state.grp_lock, + test, + &test_cb, + &test->state.keys[SERVER]); if (status != PJ_SUCCESS) { - pj_lock_release((pj_lock_t*)test->state.grp_lock); - PJ_PERROR(1,(THIS_FILE, status, "pj_ioqueue_register_sock2 error")); - test->state.retcode = 605; - return; + pj_lock_release((pj_lock_t*)test->state.grp_lock); + PJ_PERROR(1,(THIS_FILE, status, "pj_ioqueue_register_sock2 error")); + test->state.retcode = 605; + return; } if (!okud->server.recv_buf) { - okud->server.recv_buf = pj_pool_calloc(test->state.pool, test->cfg.pkt_len, - sizeof(int)); + okud->server.recv_buf = pj_pool_calloc(test->state.pool, test->cfg.pkt_len, + sizeof(int)); } pj_ioqueue_op_key_init(&okud->server.recv_op, sizeof(pj_ioqueue_op_key_t)); @@ -364,44 +363,44 @@ static void on_connect_complete(pj_ioqueue_key_t *key, #if PJ_WIN64 || PJ_WIN32 if (test->cfg.expected_ret_code==RETCODE_CONNECT_FAILED && - status==PJ_SUCCESS) + status==PJ_SUCCESS) { - /* On Windows, when the server socket is closed even without accept(), - * connect() returns success but subsequent write will return - * error - */ - pj_ioqueue_op_key_t op_key; - int send_buf = 0; - pj_ssize_t bytes_sent = sizeof(send_buf); - - status = pj_ioqueue_send(key, &op_key, &send_buf, &bytes_sent, 0); + /* On Windows, when the server socket is closed even without accept(), + * connect() returns success but subsequent write will return + * error + */ + pj_ioqueue_op_key_t op_key; + int send_buf = 0; + pj_ssize_t bytes_sent = sizeof(send_buf); + + status = pj_ioqueue_send(key, &op_key, &send_buf, &bytes_sent, 0); } #endif test->state.connect_status = status; if (status != PJ_SUCCESS) { - if (test->cfg.expected_ret_code != RETCODE_CONNECT_FAILED) - PJ_PERROR(1, (THIS_FILE, status, "async connect failed")); - test->state.retcode = RETCODE_CONNECT_FAILED; - return; + if (test->cfg.expected_ret_code != RETCODE_CONNECT_FAILED) + PJ_PERROR(1, (THIS_FILE, status, "async connect failed")); + test->state.retcode = RETCODE_CONNECT_FAILED; + return; } for (i=0; icfg.n_clients; ++i) { - op_key_user_data *okud; + op_key_user_data *okud; - pj_lock_acquire((pj_lock_t*)test->state.grp_lock); - okud = alloc_okud(test, CLIENT); - if (!okud->client.send_buf) { - okud->client.send_buf = pj_pool_calloc(test->state.pool, - test->cfg.pkt_len, - sizeof(int)); - } + pj_lock_acquire((pj_lock_t*)test->state.grp_lock); + okud = alloc_okud(test, CLIENT); + if (!okud->client.send_buf) { + okud->client.send_buf = pj_pool_calloc(test->state.pool, + test->cfg.pkt_len, + sizeof(int)); + } - pj_ioqueue_op_key_init(&okud->client.send_op, sizeof(pj_ioqueue_op_key_t)); - okud->client.send_op.user_data = okud; - pj_lock_release((pj_lock_t*)test->state.grp_lock); + pj_ioqueue_op_key_init(&okud->client.send_op, sizeof(pj_ioqueue_op_key_t)); + okud->client.send_op.user_data = okud; + pj_lock_release((pj_lock_t*)test->state.grp_lock); - on_write_complete(key, &okud->client.send_op, -12345); + on_write_complete(key, &okud->client.send_op, -12345); } }; @@ -417,66 +416,66 @@ static int worker_thread(void *p) pj_log_set_indent(3); while (test->state.retcode==0) { - unsigned i; - pj_time_val timeout = {0, 10}; - - int rc = pj_ioqueue_poll(test->state.ioq, &timeout); - if (rc < 0) { - PJ_PERROR(1,(THIS_FILE, -rc, "pj_ioqueue_poll() error")); - } - - if (rc > 0) - n_events += rc; - - if (test->state.cnt[CLIENT] >= test->cfg.tx_cnt && - test->state.cnt[SERVER] >= test->cfg.rx_cnt) - { - /* Done. Success */ - break; - } - - /* Check if client needs to send. UDP client needs to send until - * server receives enough packet (because packets can be lost). - * TCP client stops after enough packets are transmitted. - */ - for (i=0; istate.okuds_cnt[CLIENT] && - (test->cfg.sock_type == pj_SOCK_DGRAM() || - test->state.cnt[CLIENT] < test->cfg.tx_cnt); ++i) - { - op_key_user_data *okud = &test->state.okuds[CLIENT][i]; - pj_lock_acquire((pj_lock_t*)test->state.grp_lock); - if (!pj_ioqueue_is_pending(test->state.keys[CLIENT], - &okud->client.send_op)) { - on_write_complete(test->state.keys[CLIENT], - &okud->client.send_op, -12345); - } - pj_lock_release((pj_lock_t*)test->state.grp_lock); - } - - if (test->state.connect_status != PJ_SUCCESS && - test->state.connect_status != PJ_EPENDING) - { - break; - } + unsigned i; + pj_time_val timeout = {0, 10}; + + int rc = pj_ioqueue_poll(test->state.ioq, &timeout); + if (rc < 0) { + PJ_PERROR(1,(THIS_FILE, -rc, "pj_ioqueue_poll() error")); + } + + if (rc > 0) + n_events += rc; + + if (test->state.cnt[CLIENT] >= test->cfg.tx_cnt && + test->state.cnt[SERVER] >= test->cfg.rx_cnt) + { + /* Done. Success */ + break; + } + + /* Check if client needs to send. UDP client needs to send until + * server receives enough packet (because packets can be lost). + * TCP client stops after enough packets are transmitted. + */ + for (i=0; istate.okuds_cnt[CLIENT] && + (test->cfg.sock_type == pj_SOCK_DGRAM() || + test->state.cnt[CLIENT] < test->cfg.tx_cnt); ++i) + { + op_key_user_data *okud = &test->state.okuds[CLIENT][i]; + pj_lock_acquire((pj_lock_t*)test->state.grp_lock); + if (!pj_ioqueue_is_pending(test->state.keys[CLIENT], + &okud->client.send_op)) { + on_write_complete(test->state.keys[CLIENT], + &okud->client.send_op, -12345); + } + pj_lock_release((pj_lock_t*)test->state.grp_lock); + } + + if (test->state.connect_status != PJ_SUCCESS && + test->state.connect_status != PJ_EPENDING) + { + break; + } } /* Flush events. Check if polling is blocked (it should). */ if (test->state.retcode==test->cfg.expected_ret_code) { - pj_timestamp t0, t1; - unsigned i, msec; - - pj_get_timestamp(&t0); - for (i=0; i<10; ++i) { - pj_time_val timeout = {0, 100}; - n_events += pj_ioqueue_poll(test->state.ioq, &timeout); - pj_thread_sleep(10); - } - pj_get_timestamp(&t1); - msec = pj_elapsed_msec(&t0, &t1); - if (msec <= 500) { - test->state.retcode = 5000; - PJ_LOG(1,(THIS_FILE, "Error: pj_ioqueue_poll is not blocking")); - } + pj_timestamp t0, t1; + unsigned i, msec; + + pj_get_timestamp(&t0); + for (i=0; i<10; ++i) { + pj_time_val timeout = {0, 100}; + n_events += pj_ioqueue_poll(test->state.ioq, &timeout); + pj_thread_sleep(10); + } + pj_get_timestamp(&t1); + msec = pj_elapsed_msec(&t0, &t1); + if (msec <= 500) { + test->state.retcode = 5000; + PJ_LOG(1,(THIS_FILE, "Error: pj_ioqueue_poll is not blocking")); + } } TRACE((THIS_FILE, "thread exiting, n_events=%d", n_events)); @@ -499,89 +498,89 @@ static int perform_single_pass(test_desc *test) test->state.listen_key = NULL; test->state.listen_sock = PJ_INVALID_SOCKET; for (i=0; i<2; ++i) { - int j; + int j; - test->state.socks[i] = PJ_INVALID_SOCKET; - test->state.keys[i] = NULL; - test->state.cnt[i] = 0; - test->state.okuds_cnt[i] = 0; + test->state.socks[i] = PJ_INVALID_SOCKET; + test->state.keys[i] = NULL; + test->state.cnt[i] = 0; + test->state.okuds_cnt[i] = 0; - for (j=0; jstate.okuds[i][j].common.status = PJ_EPENDING; - } + for (j=0; jstate.okuds[i][j].common.status = PJ_EPENDING; + } } /* * Init server side */ if (test->cfg.sock_type == pj_SOCK_STREAM()) { - CHECK(20, pj_sock_socket(pj_AF_INET(), test->cfg.sock_type, 0, - &test->state.listen_sock)); - CHECK(21, pj_sock_bind_in(test->state.listen_sock, 0, 0)); - CHECK(22, pj_sock_getsockname(test->state.listen_sock, &addr, &namelen)); - CHECK(23, pj_sock_listen(test->state.listen_sock, 5)); - CHECK(24, pj_ioqueue_register_sock2(test->state.pool, - test->state.ioq, - test->state.listen_sock, - test->state.grp_lock, - test, - &test_cb, - &test->state.listen_key)); - if (!test->cfg.reject_connect) { - /* kick off parallel accepts */ - for (i=0; icfg.n_servers; ++i) { - op_key_user_data *okud; - - okud = alloc_okud(test, SERVER); - pj_ioqueue_op_key_init(&okud->server.recv_op, - sizeof(okud->server.recv_op)); - okud->server.recv_op.user_data = okud; - okud->server.status = pj_ioqueue_accept(test->state.listen_key, - &okud->server.recv_op, - &okud->server.new_sock, - NULL, - NULL, - NULL); - CHECK(26, okud->server.status); - } - } + CHECK(20, pj_sock_socket(pj_AF_INET(), test->cfg.sock_type, 0, + &test->state.listen_sock)); + CHECK(21, pj_sock_bind_in(test->state.listen_sock, 0, 0)); + CHECK(22, pj_sock_getsockname(test->state.listen_sock, &addr, &namelen)); + CHECK(23, pj_sock_listen(test->state.listen_sock, 5)); + CHECK(24, pj_ioqueue_register_sock2(test->state.pool, + test->state.ioq, + test->state.listen_sock, + test->state.grp_lock, + test, + &test_cb, + &test->state.listen_key)); + if (!test->cfg.reject_connect) { + /* kick off parallel accepts */ + for (i=0; icfg.n_servers; ++i) { + op_key_user_data *okud; + + okud = alloc_okud(test, SERVER); + pj_ioqueue_op_key_init(&okud->server.recv_op, + sizeof(okud->server.recv_op)); + okud->server.recv_op.user_data = okud; + okud->server.status = pj_ioqueue_accept(test->state.listen_key, + &okud->server.recv_op, + &okud->server.new_sock, + NULL, + NULL, + NULL); + CHECK(26, okud->server.status); + } + } } else { - CHECK(30, pj_sock_socket(pj_AF_INET(), test->cfg.sock_type, 0, - &test->state.socks[SERVER])); - CHECK(31, pj_sock_bind_in(test->state.socks[SERVER], 0, 0)); - CHECK(32, pj_sock_getsockname(test->state.socks[SERVER], &addr, &namelen)); - CHECK(33, pj_ioqueue_register_sock2(test->state.pool, - test->state.ioq, - test->state.socks[SERVER], - test->state.grp_lock, - test, - &test_cb, - &test->state.keys[SERVER])); - - if (test->cfg.rx_so_buf_size) { - int value = test->cfg.rx_so_buf_size * sizeof(int); - CHECK(34, pj_sock_setsockopt(test->state.socks[SERVER], - pj_SOL_SOCKET(), - pj_SO_RCVBUF(), - &value, sizeof(value))); - } - - /* kick off parallel recvs */ - for (i=0; icfg.n_servers; ++i) { - op_key_user_data *okud; - - okud = alloc_okud(test, SERVER); - if (!okud->server.recv_buf) { - okud->server.recv_buf = pj_pool_calloc(test->state.pool, - test->cfg.pkt_len, - sizeof(int)); - } - pj_ioqueue_op_key_init(&okud->server.recv_op, sizeof(pj_ioqueue_op_key_t)); - okud->server.recv_op.user_data = okud; - - on_read_complete(test->state.keys[SERVER], &okud->server.recv_op, - -12345); - } + CHECK(30, pj_sock_socket(pj_AF_INET(), test->cfg.sock_type, 0, + &test->state.socks[SERVER])); + CHECK(31, pj_sock_bind_in(test->state.socks[SERVER], 0, 0)); + CHECK(32, pj_sock_getsockname(test->state.socks[SERVER], &addr, &namelen)); + CHECK(33, pj_ioqueue_register_sock2(test->state.pool, + test->state.ioq, + test->state.socks[SERVER], + test->state.grp_lock, + test, + &test_cb, + &test->state.keys[SERVER])); + + if (test->cfg.rx_so_buf_size) { + int value = test->cfg.rx_so_buf_size * sizeof(int); + CHECK(34, pj_sock_setsockopt(test->state.socks[SERVER], + pj_SOL_SOCKET(), + pj_SO_RCVBUF(), + &value, sizeof(value))); + } + + /* kick off parallel recvs */ + for (i=0; icfg.n_servers; ++i) { + op_key_user_data *okud; + + okud = alloc_okud(test, SERVER); + if (!okud->server.recv_buf) { + okud->server.recv_buf = pj_pool_calloc(test->state.pool, + test->cfg.pkt_len, + sizeof(int)); + } + pj_ioqueue_op_key_init(&okud->server.recv_op, sizeof(pj_ioqueue_op_key_t)); + okud->server.recv_op.user_data = okud; + + on_read_complete(test->state.keys[SERVER], &okud->server.recv_op, + -12345); + } } @@ -589,104 +588,104 @@ static int perform_single_pass(test_desc *test) * Client side */ CHECK(40, pj_sock_socket(pj_AF_INET(), test->cfg.sock_type, 0, - &test->state.socks[CLIENT])); + &test->state.socks[CLIENT])); addr.ipv4.sin_addr = pj_inet_addr(&localhost); if (test->cfg.tx_so_buf_size) { - int value = test->cfg.tx_so_buf_size * sizeof(int); - CHECK(41, pj_sock_setsockopt(test->state.socks[CLIENT], - pj_SOL_SOCKET(), - pj_SO_RCVBUF(), - &value, sizeof(value))); + int value = test->cfg.tx_so_buf_size * sizeof(int); + CHECK(41, pj_sock_setsockopt(test->state.socks[CLIENT], + pj_SOL_SOCKET(), + pj_SO_RCVBUF(), + &value, sizeof(value))); } CHECK(42, pj_ioqueue_register_sock2(test->state.pool, - test->state.ioq, - test->state.socks[CLIENT], - test->state.grp_lock, - test, - &test_cb, - &test->state.keys[CLIENT])); + test->state.ioq, + test->state.socks[CLIENT], + test->state.grp_lock, + test, + &test_cb, + &test->state.keys[CLIENT])); if (test->cfg.sock_type == pj_SOCK_STREAM()) { - if (test->cfg.failed_connect) { - pj_sockaddr_in_init((pj_sockaddr_in*)&addr, &localhost, 39275); - test->state.connect_status = pj_ioqueue_connect(test->state.keys[CLIENT], - &addr, - sizeof(pj_sockaddr_in)); - if (test->state.connect_status && test->state.connect_status!=PJ_EPENDING) - PJ_PERROR(1,(THIS_FILE, test->state.connect_status, - "TCP connect() error")); - CHECK(44, test->state.connect_status); - } else { - test->state.connect_status = pj_ioqueue_connect(test->state.keys[CLIENT], - &addr, namelen); - CHECK(45, test->state.connect_status); - } - /* To be continued when socket is connected (or fails) */ + if (test->cfg.failed_connect) { + pj_sockaddr_in_init((pj_sockaddr_in*)&addr, &localhost, 39275); + test->state.connect_status = pj_ioqueue_connect(test->state.keys[CLIENT], + &addr, + sizeof(pj_sockaddr_in)); + if (test->state.connect_status && test->state.connect_status!=PJ_EPENDING) + PJ_PERROR(1,(THIS_FILE, test->state.connect_status, + "TCP connect() error")); + CHECK(44, test->state.connect_status); + } else { + test->state.connect_status = pj_ioqueue_connect(test->state.keys[CLIENT], + &addr, namelen); + CHECK(45, test->state.connect_status); + } + /* To be continued when socket is connected (or fails) */ } else { - /* UDP connect */ - CHECK(46, pj_ioqueue_connect(test->state.keys[CLIENT], - &addr, namelen)); - /* kick off parallel send */ - for (i=0; icfg.n_clients; ++i) { - op_key_user_data *okud; - - okud = alloc_okud(test, CLIENT); - if (!okud->client.send_buf) { - okud->client.send_buf = pj_pool_calloc(test->state.pool, - test->cfg.pkt_len, - sizeof(int)); - } - pj_ioqueue_op_key_init(&okud->client.send_op, sizeof(pj_ioqueue_op_key_t)); - okud->client.send_op.user_data = okud; - - on_write_complete(test->state.keys[CLIENT], &okud->client.send_op, - -12345); - } + /* UDP connect */ + CHECK(46, pj_ioqueue_connect(test->state.keys[CLIENT], + &addr, namelen)); + /* kick off parallel send */ + for (i=0; icfg.n_clients; ++i) { + op_key_user_data *okud; + + okud = alloc_okud(test, CLIENT); + if (!okud->client.send_buf) { + okud->client.send_buf = pj_pool_calloc(test->state.pool, + test->cfg.pkt_len, + sizeof(int)); + } + pj_ioqueue_op_key_init(&okud->client.send_op, sizeof(pj_ioqueue_op_key_t)); + okud->client.send_op.user_data = okud; + + on_write_complete(test->state.keys[CLIENT], &okud->client.send_op, + -12345); + } } if (test->cfg.reject_connect) { - CHECK(47, pj_ioqueue_unregister(test->state.listen_key)); - test->state.listen_key = NULL; - test->state.listen_sock = PJ_INVALID_SOCKET; + CHECK(47, pj_ioqueue_unregister(test->state.listen_key)); + test->state.listen_key = NULL; + test->state.listen_sock = PJ_INVALID_SOCKET; } else if (test->cfg.cancel_connect) { - CHECK(48, pj_ioqueue_unregister(test->state.keys[CLIENT])); + CHECK(48, pj_ioqueue_unregister(test->state.keys[CLIENT])); } pj_log_push_indent(); if (test->cfg.n_threads==0) - worker_thread(test); + worker_thread(test); else { - unsigned n_threads = test->cfg.n_threads; - pj_thread_t *threads[MAX_THREADS]; - - for (i=0; istate.pool, "ioq_stress_test", - &worker_thread, test, - 0, PJ_THREAD_SUSPENDED, - &threads[i])); - } - - for (i=0; icfg.n_threads; + pj_thread_t *threads[MAX_THREADS]; + + for (i=0; istate.pool, "ioq_stress_test", + &worker_thread, test, + 0, PJ_THREAD_SUSPENDED, + &threads[i])); + } + + for (i=0; istate.retcode; on_return: if (test->state.listen_key) - pj_ioqueue_unregister(test->state.listen_key); + pj_ioqueue_unregister(test->state.listen_key); for (i=0; i<2; ++i) { - if (test->state.keys[i]) - pj_ioqueue_unregister(test->state.keys[i]); + if (test->state.keys[i]) + pj_ioqueue_unregister(test->state.keys[i]); } pj_log_pop_indent(); @@ -715,27 +714,27 @@ static int perform_test(test_desc *test) ioqueue_cfg.epoll_flags = test->cfg.epoll_flags; CHECK(10, pj_ioqueue_create2(test->state.pool, test->cfg.max_fd, - &ioqueue_cfg, &test->state.ioq)); + &ioqueue_cfg, &test->state.ioq)); CHECK(11, pj_ioqueue_set_default_concurrency(test->state.ioq, - test->cfg.allow_concur)); + test->cfg.allow_concur)); CHECK(20, pj_grp_lock_create(test->state.pool, NULL, &test->state.grp_lock)); CHECK(21, pj_grp_lock_add_ref(test->state.grp_lock)); for (rep=0, retcode=0; repcfg.repeat && !retcode; ++rep) { - TRACE((THIS_FILE, "repeat %d/%d", rep+1, test->cfg.repeat)); - retcode = perform_single_pass(test); + TRACE((THIS_FILE, "repeat %d/%d", rep+1, test->cfg.repeat)); + retcode = perform_single_pass(test); } on_return: if (test->state.ioq) - pj_ioqueue_destroy(test->state.ioq); + pj_ioqueue_destroy(test->state.ioq); pj_grp_lock_dec_ref(test->state.grp_lock); test->state.grp_lock = NULL; if (test->state.pool) - pj_pool_release(test->state.pool); + pj_pool_release(test->state.pool); if (retcode) { - PJ_LOG(3,(THIS_FILE, "test failed (retcode=%d)", retcode)); + PJ_LOG(3,(THIS_FILE, "test failed (retcode=%d)", retcode)); } pj_log_pop_indent(); return retcode; @@ -748,61 +747,61 @@ static test_desc tests[128] = { * unregistration. */ { - .cfg.title = "basic udp (single thread)", - .cfg.max_fd = 4, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, - .cfg.sock_type = SOCK_DGRAM, /* cannot use pj_SOCK_DGRAM (not constant) */ - .cfg.n_threads = 0, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 512, - .cfg.rx_cnt = 512, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 4 + .cfg.title = "basic udp (single thread)", + .cfg.max_fd = 4, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, + .cfg.sock_type = SOCK_DGRAM, /* cannot use pj_SOCK_DGRAM (not constant) */ + .cfg.n_threads = 0, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 512, + .cfg.rx_cnt = 512, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 4 }, #if PJ_HAS_LINUX_EPOLL { - .cfg.title = "basic udp (single thread, EPOLLEXCLUSIVE)", - .cfg.max_fd = 4, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_EXCLUSIVE, - .cfg.sock_type = SOCK_DGRAM, - .cfg.n_threads = 0, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 512, - .cfg.rx_cnt = 512, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 4 + .cfg.title = "basic udp (single thread, EPOLLEXCLUSIVE)", + .cfg.max_fd = 4, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_EXCLUSIVE, + .cfg.sock_type = SOCK_DGRAM, + .cfg.n_threads = 0, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 512, + .cfg.rx_cnt = 512, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 4 }, { - .cfg.title = "basic udp (single thread, EPOLLONESHOT)", - .cfg.max_fd = 4, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_ONESHOT, - .cfg.sock_type = SOCK_DGRAM, - .cfg.n_threads = 0, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 512, - .cfg.rx_cnt = 512, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 4 + .cfg.title = "basic udp (single thread, EPOLLONESHOT)", + .cfg.max_fd = 4, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_ONESHOT, + .cfg.sock_type = SOCK_DGRAM, + .cfg.n_threads = 0, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 512, + .cfg.rx_cnt = 512, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 4 }, { - .cfg.title = "basic udp (single thread, epoll plain)", - .cfg.max_fd = 4, - .cfg.allow_concur = 1, - .cfg.epoll_flags = 0, - .cfg.sock_type = SOCK_DGRAM, - .cfg.n_threads = 0, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 512, - .cfg.rx_cnt = 512, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 4 + .cfg.title = "basic udp (single thread, epoll plain)", + .cfg.max_fd = 4, + .cfg.allow_concur = 1, + .cfg.epoll_flags = 0, + .cfg.sock_type = SOCK_DGRAM, + .cfg.n_threads = 0, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 512, + .cfg.rx_cnt = 512, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 4 }, #endif /* simplest test (tcp), no threads, no parallel send/recv, it's good for debugging. @@ -810,218 +809,218 @@ static test_desc tests[128] = { * unregistration. */ { - .cfg.title = "basic tcp (single thread)", - .cfg.max_fd = 6, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = 0, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 20, - .cfg.rx_cnt = 20, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 4 + .cfg.title = "basic tcp (single thread)", + .cfg.max_fd = 6, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = 0, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 20, + .cfg.rx_cnt = 20, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 4 }, #if PJ_HAS_LINUX_EPOLL { - .cfg.title = "basic tcp (single thread, EPOLLEXCLUSIVE)", - .cfg.max_fd = 6, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, - .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_EXCLUSIVE, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = 0, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 20, - .cfg.rx_cnt = 20, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 4 + .cfg.title = "basic tcp (single thread, EPOLLEXCLUSIVE)", + .cfg.max_fd = 6, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, + .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_EXCLUSIVE, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = 0, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 20, + .cfg.rx_cnt = 20, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 4 }, { - .cfg.title = "basic tcp (single thread, EPOLLONESHOT)", - .cfg.max_fd = 6, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_ONESHOT, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = 0, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 20, - .cfg.rx_cnt = 20, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 4 + .cfg.title = "basic tcp (single thread, EPOLLONESHOT)", + .cfg.max_fd = 6, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_ONESHOT, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = 0, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 20, + .cfg.rx_cnt = 20, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 4 }, { - .cfg.title = "basic tcp (single thread, plain)", - .cfg.max_fd = 6, - .cfg.allow_concur = 1, - .cfg.epoll_flags = 0, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = 0, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 20, - .cfg.rx_cnt = 20, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 4 + .cfg.title = "basic tcp (single thread, plain)", + .cfg.max_fd = 6, + .cfg.allow_concur = 1, + .cfg.epoll_flags = 0, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = 0, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 20, + .cfg.rx_cnt = 20, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 4 }, #endif /* failed TCP connect(). */ { - .cfg.title = "failed tcp connect (pls wait)", - .cfg.expected_ret_code = RETCODE_CONNECT_FAILED, - .cfg.max_fd = 6, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, - .cfg.failed_connect = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 20, - .cfg.rx_cnt = 20, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 2 + .cfg.title = "failed tcp connect (pls wait)", + .cfg.expected_ret_code = RETCODE_CONNECT_FAILED, + .cfg.max_fd = 6, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, + .cfg.failed_connect = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 20, + .cfg.rx_cnt = 20, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 2 }, #if PJ_HAS_LINUX_EPOLL { - .cfg.title = "failed tcp connect (EPOLLEXCLUSIVE)", - .cfg.expected_ret_code = RETCODE_CONNECT_FAILED, - .cfg.max_fd = 6, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_EXCLUSIVE, - .cfg.failed_connect = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 20, - .cfg.rx_cnt = 20, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 2 + .cfg.title = "failed tcp connect (EPOLLEXCLUSIVE)", + .cfg.expected_ret_code = RETCODE_CONNECT_FAILED, + .cfg.max_fd = 6, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_EXCLUSIVE, + .cfg.failed_connect = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 20, + .cfg.rx_cnt = 20, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 2 }, { - .cfg.title = "failed tcp connect (EPOLLONESHOT)", - .cfg.expected_ret_code = RETCODE_CONNECT_FAILED, - .cfg.max_fd = 6, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_ONESHOT, - .cfg.failed_connect = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 20, - .cfg.rx_cnt = 20, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 2 + .cfg.title = "failed tcp connect (EPOLLONESHOT)", + .cfg.expected_ret_code = RETCODE_CONNECT_FAILED, + .cfg.max_fd = 6, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_ONESHOT, + .cfg.failed_connect = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 20, + .cfg.rx_cnt = 20, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 2 }, { - .cfg.title = "failed tcp connect (plain)", - .cfg.expected_ret_code = RETCODE_CONNECT_FAILED, - .cfg.max_fd = 6, - .cfg.allow_concur = 1, - .cfg.epoll_flags = 0, - .cfg.failed_connect = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 20, - .cfg.rx_cnt = 20, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 2 + .cfg.title = "failed tcp connect (plain)", + .cfg.expected_ret_code = RETCODE_CONNECT_FAILED, + .cfg.max_fd = 6, + .cfg.allow_concur = 1, + .cfg.epoll_flags = 0, + .cfg.failed_connect = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 20, + .cfg.rx_cnt = 20, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 2 }, #endif /* reject TCP connect(). */ { - .cfg.title = "tcp connect rejected", - .cfg.expected_ret_code = RETCODE_CONNECT_FAILED, - .cfg.max_fd = 6, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, - .cfg.reject_connect = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 20, - .cfg.rx_cnt = 20, - .cfg.n_servers = 1, - .cfg.n_clients = 1, - .cfg.repeat = 2 + .cfg.title = "tcp connect rejected", + .cfg.expected_ret_code = RETCODE_CONNECT_FAILED, + .cfg.max_fd = 6, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, + .cfg.reject_connect = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 20, + .cfg.rx_cnt = 20, + .cfg.n_servers = 1, + .cfg.n_clients = 1, + .cfg.repeat = 2 }, /* quite involved test (udp). Multithreads, parallel send/recv operations, * limitation in recv buffer. max_fd is very limited to test management of * closing keys in ioqueue safe unregistration. */ { - .cfg.title = "udp (multithreads)", - .cfg.max_fd = 4, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, - .cfg.sock_type = SOCK_DGRAM, - .cfg.n_threads = MAX_THREADS, - .cfg.rx_so_buf_size = MAX_THREADS, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*8*512, - .cfg.rx_cnt = 4*8*512, - .cfg.n_servers = MAX_ASYNC, - .cfg.n_clients = MAX_ASYNC, - .cfg.repeat = 4 + .cfg.title = "udp (multithreads)", + .cfg.max_fd = 4, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, + .cfg.sock_type = SOCK_DGRAM, + .cfg.n_threads = MAX_THREADS, + .cfg.rx_so_buf_size = MAX_THREADS, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*8*512, + .cfg.rx_cnt = 4*8*512, + .cfg.n_servers = MAX_ASYNC, + .cfg.n_clients = MAX_ASYNC, + .cfg.repeat = 4 }, #if PJ_HAS_LINUX_EPOLL /* EPOLLEXCLUSIVE (udp). */ { - .cfg.title = "udp (multithreads, EPOLLEXCLUSIVE)", - .cfg.max_fd = 4, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_EXCLUSIVE, - .cfg.sock_type = SOCK_DGRAM, - .cfg.n_threads = MAX_THREADS, - .cfg.rx_so_buf_size = MAX_THREADS, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*8*512, - .cfg.rx_cnt = 4*8*512, - .cfg.n_servers = MAX_ASYNC, - .cfg.n_clients = MAX_ASYNC, - .cfg.repeat = 4 + .cfg.title = "udp (multithreads, EPOLLEXCLUSIVE)", + .cfg.max_fd = 4, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_EXCLUSIVE, + .cfg.sock_type = SOCK_DGRAM, + .cfg.n_threads = MAX_THREADS, + .cfg.rx_so_buf_size = MAX_THREADS, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*8*512, + .cfg.rx_cnt = 4*8*512, + .cfg.n_servers = MAX_ASYNC, + .cfg.n_clients = MAX_ASYNC, + .cfg.repeat = 4 }, /* EPOLLONESHOT (udp). */ { - .cfg.title = "udp (multithreads, EPOLLONESHOT)", - .cfg.max_fd = 4, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_ONESHOT, - .cfg.sock_type = SOCK_DGRAM, - .cfg.n_threads = 2, - .cfg.rx_so_buf_size = 2, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*8*512, - .cfg.rx_cnt = 4*8*512, - .cfg.n_servers = 2, - .cfg.n_clients = 2, - .cfg.repeat = 4 + .cfg.title = "udp (multithreads, EPOLLONESHOT)", + .cfg.max_fd = 4, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_ONESHOT, + .cfg.sock_type = SOCK_DGRAM, + .cfg.n_threads = 2, + .cfg.rx_so_buf_size = 2, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*8*512, + .cfg.rx_cnt = 4*8*512, + .cfg.n_servers = 2, + .cfg.n_clients = 2, + .cfg.repeat = 4 }, { - .cfg.title = "udp (multithreads, plain epoll)", - .cfg.max_fd = 4, - .cfg.allow_concur = 1, - .cfg.epoll_flags = 0, - .cfg.sock_type = SOCK_DGRAM, - .cfg.n_threads = 2, - .cfg.rx_so_buf_size = 2, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*8*512, - .cfg.rx_cnt = 4*8*512, - .cfg.n_servers = 2, - .cfg.n_clients = 2, - .cfg.repeat = 4 + .cfg.title = "udp (multithreads, plain epoll)", + .cfg.max_fd = 4, + .cfg.allow_concur = 1, + .cfg.epoll_flags = 0, + .cfg.sock_type = SOCK_DGRAM, + .cfg.n_threads = 2, + .cfg.rx_so_buf_size = 2, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*8*512, + .cfg.rx_cnt = 4*8*512, + .cfg.n_servers = 2, + .cfg.n_clients = 2, + .cfg.repeat = 4 }, #endif /* quite involved test (tcp). Multithreads, parallel send/recv operations, @@ -1029,142 +1028,142 @@ static test_desc tests[128] = { * closing keys in ioqueue safe unregistration. */ { - .cfg.title = "tcp (multithreads)", - .cfg.max_fd = 6, - .cfg.allow_concur = 1, - .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ - .cfg.tx_so_buf_size = MAX_ASYNC, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*MAX_THREADS*512, - .cfg.rx_cnt = 4*MAX_THREADS*512, - .cfg.n_servers = MAX_ASYNC, - .cfg.n_clients = MAX_ASYNC, - .cfg.repeat = 4 + .cfg.title = "tcp (multithreads)", + .cfg.max_fd = 6, + .cfg.allow_concur = 1, + .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ + .cfg.tx_so_buf_size = MAX_ASYNC, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*MAX_THREADS*512, + .cfg.rx_cnt = 4*MAX_THREADS*512, + .cfg.n_servers = MAX_ASYNC, + .cfg.n_clients = MAX_ASYNC, + .cfg.repeat = 4 }, #if PJ_HAS_LINUX_EPOLL { - .cfg.title = "tcp (multithreads, EPOLLEXCLUSIVE)", - .cfg.max_fd = 6, - .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_EXCLUSIVE, - .cfg.allow_concur = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ - .cfg.tx_so_buf_size = MAX_ASYNC, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*MAX_THREADS*512, - .cfg.rx_cnt = 4*MAX_THREADS*512, - .cfg.n_servers = MAX_ASYNC, - .cfg.n_clients = MAX_ASYNC, - .cfg.repeat = 4 + .cfg.title = "tcp (multithreads, EPOLLEXCLUSIVE)", + .cfg.max_fd = 6, + .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_EXCLUSIVE, + .cfg.allow_concur = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ + .cfg.tx_so_buf_size = MAX_ASYNC, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*MAX_THREADS*512, + .cfg.rx_cnt = 4*MAX_THREADS*512, + .cfg.n_servers = MAX_ASYNC, + .cfg.n_clients = MAX_ASYNC, + .cfg.repeat = 4 }, { - .cfg.title = "tcp (multithreads, EPOLLONESHOT)", - .cfg.max_fd = 6, - .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_ONESHOT, - .cfg.allow_concur = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ - .cfg.tx_so_buf_size = MAX_ASYNC, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*MAX_THREADS*512, - .cfg.rx_cnt = 4*MAX_THREADS*512, - .cfg.n_servers = MAX_ASYNC, - .cfg.n_clients = MAX_ASYNC, - .cfg.repeat = 4 + .cfg.title = "tcp (multithreads, EPOLLONESHOT)", + .cfg.max_fd = 6, + .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_ONESHOT, + .cfg.allow_concur = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ + .cfg.tx_so_buf_size = MAX_ASYNC, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*MAX_THREADS*512, + .cfg.rx_cnt = 4*MAX_THREADS*512, + .cfg.n_servers = MAX_ASYNC, + .cfg.n_clients = MAX_ASYNC, + .cfg.repeat = 4 }, { - .cfg.title = "tcp (multithreads, plain epoll)", - .cfg.max_fd = 6, - .cfg.epoll_flags = 0, - .cfg.allow_concur = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ - .cfg.tx_so_buf_size = MAX_ASYNC, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*MAX_THREADS*512, - .cfg.rx_cnt = 4*MAX_THREADS*512, - .cfg.n_servers = MAX_ASYNC, - .cfg.n_clients = MAX_ASYNC, - .cfg.repeat = 4 + .cfg.title = "tcp (multithreads, plain epoll)", + .cfg.max_fd = 6, + .cfg.epoll_flags = 0, + .cfg.allow_concur = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ + .cfg.tx_so_buf_size = MAX_ASYNC, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*MAX_THREADS*512, + .cfg.rx_cnt = 4*MAX_THREADS*512, + .cfg.n_servers = MAX_ASYNC, + .cfg.n_clients = MAX_ASYNC, + .cfg.repeat = 4 }, #endif /* when concurrency is disabled, TCP packets should be received in correct * order */ { - .cfg.title = "tcp (multithreads, sequenced, concur=0)", - .cfg.max_fd = 6, - .cfg.allow_concur = 0, - .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, - .cfg.sequenced = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ - .cfg.tx_so_buf_size = MAX_ASYNC, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*MAX_THREADS*512, - .cfg.rx_cnt = 4*MAX_THREADS*512, - .cfg.n_servers = MAX_ASYNC, - .cfg.n_clients = MAX_ASYNC, - .cfg.repeat = 4 + .cfg.title = "tcp (multithreads, sequenced, concur=0)", + .cfg.max_fd = 6, + .cfg.allow_concur = 0, + .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, + .cfg.sequenced = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ + .cfg.tx_so_buf_size = MAX_ASYNC, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*MAX_THREADS*512, + .cfg.rx_cnt = 4*MAX_THREADS*512, + .cfg.n_servers = MAX_ASYNC, + .cfg.n_clients = MAX_ASYNC, + .cfg.repeat = 4 }, #if PJ_HAS_LINUX_EPOLL { - .cfg.title = "tcp (multithreads, sequenced, concur=0, EPOLLEXCLUSIVE)", - .cfg.max_fd = 6, - .cfg.allow_concur = 0, - .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_EXCLUSIVE, - .cfg.sequenced = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ - .cfg.tx_so_buf_size = MAX_ASYNC, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*MAX_THREADS*512, - .cfg.rx_cnt = 4*MAX_THREADS*512, - .cfg.n_servers = MAX_ASYNC, - .cfg.n_clients = MAX_ASYNC, - .cfg.repeat = 4 + .cfg.title = "tcp (multithreads, sequenced, concur=0, EPOLLEXCLUSIVE)", + .cfg.max_fd = 6, + .cfg.allow_concur = 0, + .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_EXCLUSIVE, + .cfg.sequenced = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ + .cfg.tx_so_buf_size = MAX_ASYNC, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*MAX_THREADS*512, + .cfg.rx_cnt = 4*MAX_THREADS*512, + .cfg.n_servers = MAX_ASYNC, + .cfg.n_clients = MAX_ASYNC, + .cfg.repeat = 4 }, { - .cfg.title = "tcp (multithreads, sequenced, concur=0, EPOLLONESHOT)", - .cfg.max_fd = 6, - .cfg.allow_concur = 0, - .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_ONESHOT, - .cfg.sequenced = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ - .cfg.tx_so_buf_size = MAX_ASYNC, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*MAX_THREADS*512, - .cfg.rx_cnt = 4*MAX_THREADS*512, - .cfg.n_servers = MAX_ASYNC, - .cfg.n_clients = MAX_ASYNC, - .cfg.repeat = 4 + .cfg.title = "tcp (multithreads, sequenced, concur=0, EPOLLONESHOT)", + .cfg.max_fd = 6, + .cfg.allow_concur = 0, + .cfg.epoll_flags = PJ_IOQUEUE_EPOLL_ONESHOT, + .cfg.sequenced = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ + .cfg.tx_so_buf_size = MAX_ASYNC, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*MAX_THREADS*512, + .cfg.rx_cnt = 4*MAX_THREADS*512, + .cfg.n_servers = MAX_ASYNC, + .cfg.n_clients = MAX_ASYNC, + .cfg.repeat = 4 }, { - .cfg.title = "tcp (multithreads, sequenced, concur=0, epoll plain)", - .cfg.max_fd = 6, - .cfg.allow_concur = 0, - .cfg.epoll_flags = 0, - .cfg.sequenced = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ - .cfg.tx_so_buf_size = MAX_ASYNC, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*MAX_THREADS*512, - .cfg.rx_cnt = 4*MAX_THREADS*512, - .cfg.n_servers = MAX_ASYNC, - .cfg.n_clients = MAX_ASYNC, - .cfg.repeat = 4 + .cfg.title = "tcp (multithreads, sequenced, concur=0, epoll plain)", + .cfg.max_fd = 6, + .cfg.allow_concur = 0, + .cfg.epoll_flags = 0, + .cfg.sequenced = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ + .cfg.tx_so_buf_size = MAX_ASYNC, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*MAX_THREADS*512, + .cfg.rx_cnt = 4*MAX_THREADS*512, + .cfg.n_servers = MAX_ASYNC, + .cfg.n_clients = MAX_ASYNC, + .cfg.repeat = 4 }, #endif /* when concurrency is *enabled*, TCP packets are received in correct @@ -1172,21 +1171,21 @@ static test_desc tests[128] = { * all backends) */ { - .cfg.title = "tcp (multithreads, sequenced, concur=1)", - .cfg.max_fd = 6, - .cfg.allow_concur = 1, /* enabled */ - .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, - .cfg.sequenced = 1, - .cfg.sock_type = SOCK_STREAM, - .cfg.n_threads = MAX_THREADS, - .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ - .cfg.tx_so_buf_size = MAX_ASYNC, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*MAX_THREADS*512, - .cfg.rx_cnt = 4*MAX_THREADS*512, - .cfg.n_servers = MAX_ASYNC, - .cfg.n_clients = MAX_ASYNC, - .cfg.repeat = 4 + .cfg.title = "tcp (multithreads, sequenced, concur=1)", + .cfg.max_fd = 6, + .cfg.allow_concur = 1, /* enabled */ + .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, + .cfg.sequenced = 1, + .cfg.sock_type = SOCK_STREAM, + .cfg.n_threads = MAX_THREADS, + .cfg.rx_so_buf_size = 2, /* Set to small to control flow of tcp */ + .cfg.tx_so_buf_size = MAX_ASYNC, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*MAX_THREADS*512, + .cfg.rx_cnt = 4*MAX_THREADS*512, + .cfg.n_servers = MAX_ASYNC, + .cfg.n_clients = MAX_ASYNC, + .cfg.repeat = 4 }, /* when concurrency is disabled, UDP packets should be received in increasing * order (although some packets may be lost). Edit: it turns out packets @@ -1194,21 +1193,21 @@ static test_desc tests[128] = { * in the callback (only warning will be printed). */ { - .cfg.title = "udp (multithreads, sequenced, concur=0)", - .cfg.max_fd = 6, - .cfg.allow_concur = 0, - .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, - .cfg.sequenced = 1, - .cfg.sock_type = SOCK_DGRAM, - .cfg.n_threads = MAX_THREADS, - .cfg.rx_so_buf_size = MAX_ASYNC, /* Set to small so some packets will be dropped */ - .cfg.tx_so_buf_size = MAX_ASYNC, - .cfg.pkt_len = 4, - .cfg.tx_cnt = 4*MAX_THREADS*512, - .cfg.rx_cnt = 4*MAX_THREADS*512, - .cfg.n_servers = MAX_ASYNC, - .cfg.n_clients = MAX_ASYNC, - .cfg.repeat = 4 + .cfg.title = "udp (multithreads, sequenced, concur=0)", + .cfg.max_fd = 6, + .cfg.allow_concur = 0, + .cfg.epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS, + .cfg.sequenced = 1, + .cfg.sock_type = SOCK_DGRAM, + .cfg.n_threads = MAX_THREADS, + .cfg.rx_so_buf_size = MAX_ASYNC, /* Set to small so some packets will be dropped */ + .cfg.tx_so_buf_size = MAX_ASYNC, + .cfg.pkt_len = 4, + .cfg.tx_cnt = 4*MAX_THREADS*512, + .cfg.rx_cnt = 4*MAX_THREADS*512, + .cfg.n_servers = MAX_ASYNC, + .cfg.n_clients = MAX_ASYNC, + .cfg.repeat = 4 }, }; @@ -1225,15 +1224,15 @@ int ioqueue_stress_test(void) test_cb.on_connect_complete = on_connect_complete; for (i=0; icfg.title) - break; + test_desc *test = &tests[i]; + if (!test->cfg.title) + break; - r = perform_test(&tests[i]); - if (r && !retcode) - retcode = r; + r = perform_test(&tests[i]); + if (r && !retcode) + retcode = r; } pj_log_pop_indent(); diff --git a/pjlib/src/pjlib-test/ioq_tcp.c b/pjlib/src/pjlib-test/ioq_tcp.c index 9cea956464..c6a44ec708 100644 --- a/pjlib/src/pjlib-test/ioq_tcp.c +++ b/pjlib/src/pjlib-test/ioq_tcp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,20 +37,20 @@ #if PJ_HAS_TCP -#define THIS_FILE "test_tcp" +#define THIS_FILE "test_tcp" #define NON_EXISTANT_PORT 50123 -#define LOOP 100 -#define BUF_MIN_SIZE 32 -#define BUF_MAX_SIZE 2048 +#define LOOP 100 +#define BUF_MIN_SIZE 32 +#define BUF_MAX_SIZE 2048 #define SOCK_INACTIVE_MIN (4-2) #define SOCK_INACTIVE_MAX (PJ_IOQUEUE_MAX_HANDLES - 2) -#define POOL_SIZE (2*BUF_MAX_SIZE + SOCK_INACTIVE_MAX*128 + 2048) +#define POOL_SIZE (2*BUF_MAX_SIZE + SOCK_INACTIVE_MAX*128 + 2048) -static pj_ssize_t callback_read_size, +static pj_ssize_t callback_read_size, callback_write_size, callback_accept_status, callback_connect_status; -static unsigned callback_call_count; +static unsigned callback_call_count; static pj_ioqueue_key_t *callback_read_key, *callback_write_key, *callback_accept_key, @@ -87,15 +86,15 @@ static void on_ioqueue_accept(pj_ioqueue_key_t *key, { if (sock == PJ_INVALID_SOCKET) { - if (status != PJ_SUCCESS) { - /* Ignore. Could be blocking error */ - app_perror(".....warning: received error in on_ioqueue_accept() callback", - status); - } else { - callback_accept_status = -61; - PJ_LOG(3,("", "..... on_ioqueue_accept() callback was given " - "invalid socket and status is %d", status)); - } + if (status != PJ_SUCCESS) { + /* Ignore. Could be blocking error */ + app_perror(".....warning: received error in on_ioqueue_accept() callback", + status); + } else { + callback_accept_status = -61; + PJ_LOG(3,("", "..... on_ioqueue_accept() callback was given " + "invalid socket and status is %d", status)); + } } else { pj_sockaddr addr; int client_addr_len; @@ -106,10 +105,10 @@ static void on_ioqueue_accept(pj_ioqueue_key_t *key, app_perror("...ERROR in pj_sock_getsockname()", status); } - callback_accept_key = key; - callback_accept_op = op_key; - callback_accept_status = status; - callback_call_count++; + callback_accept_key = key; + callback_accept_op = op_key; + callback_accept_status = status; + callback_call_count++; } } @@ -129,12 +128,12 @@ static pj_ioqueue_callback test_cb = }; static int send_recv_test(pj_ioqueue_t *ioque, - pj_ioqueue_key_t *skey, - pj_ioqueue_key_t *ckey, - void *send_buf, - void *recv_buf, - pj_ssize_t bufsize, - pj_timestamp *t_elapsed) + pj_ioqueue_key_t *skey, + pj_ioqueue_key_t *ckey, + void *send_buf, + void *recv_buf, + pj_ssize_t bufsize, + pj_timestamp *t_elapsed) { pj_status_t status; pj_ssize_t bytes; @@ -152,7 +151,7 @@ static int send_recv_test(pj_ioqueue_t *ioque, status = pj_ioqueue_recv(skey, &read_op, recv_buf, &bytes, 0); if (status != PJ_SUCCESS && status != PJ_EPENDING) { app_perror("...pj_ioqueue_recv error", status); - return -100; + return -100; } if (status == PJ_EPENDING) @@ -169,10 +168,10 @@ static int send_recv_test(pj_ioqueue_t *ioque, bytes = bufsize; status = pj_ioqueue_send(ckey, &write_op, send_buf, &bytes, 0); if (status != PJ_SUCCESS && bytes != PJ_EPENDING) { - return -120; + return -120; } if (status == PJ_EPENDING) { - ++pending_op; + ++pending_op; } // Begin time. @@ -188,12 +187,12 @@ static int send_recv_test(pj_ioqueue_t *ioque, while (pending_op > 0) { timeout.sec = 1; timeout.msec = 0; #ifdef PJ_SYMBIAN - PJ_UNUSED_ARG(ioque); - status = pj_symbianos_poll(-1, 1000); + PJ_UNUSED_ARG(ioque); + status = pj_symbianos_poll(-1, 1000); #else - status = pj_ioqueue_poll(ioque, &timeout); + status = pj_ioqueue_poll(ioque, &timeout); #endif - if (status > 0) { + if (status > 0) { if (callback_read_size) { if (callback_read_size != bufsize) return -160; @@ -208,28 +207,28 @@ static int send_recv_test(pj_ioqueue_t *ioque, if (callback_write_op != &write_op) return -164; } - pending_op -= status; - } + pending_op -= status; + } if (status == 0) { PJ_LOG(3,("", "...error: timed out")); } - if (status < 0) { - return -170; - } + if (status < 0) { + return -170; + } } // Pending op is zero. // Subsequent poll should yield zero too. for (i=0; i<10; ++i) { - timeout.sec = 0; - timeout.msec = 50; + timeout.sec = 0; + timeout.msec = 50; #ifdef PJ_SYMBIAN - status = pj_symbianos_poll(-1, 1); + status = pj_symbianos_poll(-1, 1); #else - status = pj_ioqueue_poll(ioque, &timeout); + status = pj_ioqueue_poll(ioque, &timeout); #endif - if (status != 0) - return -173; + if (status != 0) + return -173; } // End time. @@ -238,7 +237,7 @@ static int send_recv_test(pj_ioqueue_t *ioque, // Compare recv buffer with send buffer. if (pj_memcmp(send_buf, recv_buf, bufsize) != 0) { - return -180; + return -180; } // Success @@ -283,14 +282,14 @@ static int compliance_test_0(const pj_ioqueue_cfg *cfg) rc = pj_sock_socket(pj_AF_INET(), pj_SOCK_STREAM(), 0, &csock1); if (rc != PJ_SUCCESS) { app_perror("...error creating socket", rc); - status=-1; goto on_error; + status=-1; goto on_error; } // Bind server socket. pj_sockaddr_in_init(&addr, 0, 0); if ((rc=pj_sock_bind(ssock, &addr, sizeof(addr))) != 0 ) { app_perror("...bind error", rc); - status=-10; goto on_error; + status=-10; goto on_error; } // Get server address. @@ -298,7 +297,7 @@ static int compliance_test_0(const pj_ioqueue_cfg *cfg) rc = pj_sock_getsockname(ssock, &addr, &client_addr_len); if (rc != PJ_SUCCESS) { app_perror("...ERROR in pj_sock_getsockname()", rc); - status=-15; goto on_error; + status=-15; goto on_error; } addr.sin_addr = pj_inet_addr(pj_cstr(&s, "127.0.0.1")); @@ -306,7 +305,7 @@ static int compliance_test_0(const pj_ioqueue_cfg *cfg) rc = pj_ioqueue_create2(pool, PJ_IOQUEUE_MAX_HANDLES, cfg, &ioque); if (rc != PJ_SUCCESS) { app_perror("...ERROR in pj_ioqueue_create()", rc); - status=-20; goto on_error; + status=-20; goto on_error; } // Init operation key. @@ -321,13 +320,13 @@ static int compliance_test_0(const pj_ioqueue_cfg *cfg) ckey1 = NULL; if (rc != PJ_SUCCESS) { app_perror("...ERROR in pj_ioqueue_register_sock()", rc); - status=-23; goto on_error; + status=-23; goto on_error; } // Server socket listen(). if (pj_sock_listen(ssock, 5)) { app_perror("...ERROR in pj_sock_listen()", rc); - status=-25; goto on_error; + status=-25; goto on_error; } // Server socket accept() @@ -336,20 +335,20 @@ static int compliance_test_0(const pj_ioqueue_cfg *cfg) &client_addr, &rmt_addr, &client_addr_len); if (status != PJ_EPENDING) { app_perror("...ERROR in pj_ioqueue_accept()", rc); - status=-30; goto on_error; + status=-30; goto on_error; } if (status==PJ_EPENDING) { - ++pending_op; + ++pending_op; } // Client socket connect() status = pj_ioqueue_connect(ckey1, &addr, sizeof(addr)); if (status!=PJ_SUCCESS && status != PJ_EPENDING) { app_perror("...ERROR in pj_ioqueue_connect()", rc); - status=-40; goto on_error; + status=-40; goto on_error; } if (status==PJ_EPENDING) { - ++pending_op; + ++pending_op; } // Poll until connected @@ -362,16 +361,16 @@ static int compliance_test_0(const pj_ioqueue_cfg *cfg) callback_accept_op = callback_read_op = callback_write_op = NULL; while (pending_op) { - pj_time_val timeout = {1, 0}; + pj_time_val timeout = {1, 0}; #ifdef PJ_SYMBIAN - callback_call_count = 0; - pj_symbianos_poll(-1, PJ_TIME_VAL_MSEC(timeout)); - status = callback_call_count; + callback_call_count = 0; + pj_symbianos_poll(-1, PJ_TIME_VAL_MSEC(timeout)); + status = callback_call_count; #else - status = pj_ioqueue_poll(ioque, &timeout); + status = pj_ioqueue_poll(ioque, &timeout); #endif - if (status > 0) { + if (status > 0) { if (callback_accept_status != -2) { if (callback_accept_status != 0) { status=-41; goto on_error; @@ -395,44 +394,44 @@ static int compliance_test_0(const pj_ioqueue_cfg *cfg) callback_connect_status = -2; } - if (status > pending_op) { - PJ_LOG(3,(THIS_FILE, - "...error: pj_ioqueue_poll() returned %d " - "(only expecting %d)", - status, pending_op)); - return -52; - } - pending_op -= status; + if (status > pending_op) { + PJ_LOG(3,(THIS_FILE, + "...error: pj_ioqueue_poll() returned %d " + "(only expecting %d)", + status, pending_op)); + return -52; + } + pending_op -= status; - if (pending_op == 0) { - status = 0; - } - } + if (pending_op == 0) { + status = 0; + } + } } // There's no pending operation. // When we poll the ioqueue, there must not be events. if (pending_op == 0) { - unsigned i; + unsigned i; - for (i=0; i<10; ++i) { - pj_time_val timeout = {0, 50}; + for (i=0; i<10; ++i) { + pj_time_val timeout = {0, 50}; #ifdef PJ_SYMBIAN - status = pj_symbianos_poll(-1, PJ_TIME_VAL_MSEC(timeout)); + status = pj_symbianos_poll(-1, PJ_TIME_VAL_MSEC(timeout)); #else - status = pj_ioqueue_poll(ioque, &timeout); + status = pj_ioqueue_poll(ioque, &timeout); #endif - if (status != 0) { - status=-60; goto on_error; - } - } + if (status != 0) { + status=-60; goto on_error; + } + } } // Check accepted socket. if (csock0 == PJ_INVALID_SOCKET) { - status = -69; + status = -69; app_perror("...accept() error", pj_get_os_error()); - goto on_error; + goto on_error; } // Register newly accepted socket. @@ -440,8 +439,8 @@ static int compliance_test_0(const pj_ioqueue_cfg *cfg) &test_cb, &ckey0); if (rc != PJ_SUCCESS) { app_perror("...ERROR in pj_ioqueue_register_sock", rc); - status = -70; - goto on_error; + status = -70; + goto on_error; } // Test send and receive. @@ -449,7 +448,7 @@ static int compliance_test_0(const pj_ioqueue_cfg *cfg) status = send_recv_test(ioque, ckey0, ckey1, send_buf, recv_buf, bufsize, &t_elapsed); if (status != 0) { - goto on_error; + goto on_error; } // Success @@ -457,22 +456,22 @@ static int compliance_test_0(const pj_ioqueue_cfg *cfg) on_error: if (skey != NULL) - pj_ioqueue_unregister(skey); + pj_ioqueue_unregister(skey); else if (ssock != PJ_INVALID_SOCKET) - pj_sock_close(ssock); + pj_sock_close(ssock); if (ckey1 != NULL) - pj_ioqueue_unregister(ckey1); + pj_ioqueue_unregister(ckey1); else if (csock1 != PJ_INVALID_SOCKET) - pj_sock_close(csock1); + pj_sock_close(csock1); if (ckey0 != NULL) - pj_ioqueue_unregister(ckey0); + pj_ioqueue_unregister(ckey0); else if (csock0 != PJ_INVALID_SOCKET) - pj_sock_close(csock0); + pj_sock_close(csock0); if (ioque != NULL) - pj_ioqueue_destroy(ioque); + pj_ioqueue_destroy(ioque); pj_pool_release(pool); return status; @@ -500,14 +499,14 @@ static int compliance_test_1(const pj_ioqueue_cfg *cfg) // Create I/O Queue. rc = pj_ioqueue_create2(pool, PJ_IOQUEUE_MAX_HANDLES, cfg, &ioque); if (!ioque) { - status=-20; goto on_error; + status=-20; goto on_error; } // Create client socket rc = pj_sock_socket(pj_AF_INET(), pj_SOCK_STREAM(), 0, &csock1); if (rc != PJ_SUCCESS) { app_perror("...ERROR in pj_sock_socket()", rc); - status=-1; goto on_error; + status=-1; goto on_error; } // Register client socket. @@ -515,7 +514,7 @@ static int compliance_test_1(const pj_ioqueue_cfg *cfg) &test_cb, &ckey1); if (rc != PJ_SUCCESS) { app_perror("...ERROR in pj_ioqueue_register_sock()", rc); - status=-23; goto on_error; + status=-23; goto on_error; } // Initialize remote address. @@ -524,14 +523,14 @@ static int compliance_test_1(const pj_ioqueue_cfg *cfg) // Client socket connect() status = pj_ioqueue_connect(ckey1, &addr, sizeof(addr)); if (status==PJ_SUCCESS) { - // unexpectedly success! - status = -30; - goto on_error; + // unexpectedly success! + status = -30; + goto on_error; } if (status != PJ_EPENDING) { - // success + // success } else { - ++pending_op; + ++pending_op; } callback_connect_status = -2; @@ -539,55 +538,55 @@ static int compliance_test_1(const pj_ioqueue_cfg *cfg) // Poll until we've got result while (pending_op) { - pj_time_val timeout = {1, 0}; + pj_time_val timeout = {1, 0}; #ifdef PJ_SYMBIAN - callback_call_count = 0; - pj_symbianos_poll(-1, PJ_TIME_VAL_MSEC(timeout)); - status = callback_call_count; + callback_call_count = 0; + pj_symbianos_poll(-1, PJ_TIME_VAL_MSEC(timeout)); + status = callback_call_count; #else - status = pj_ioqueue_poll(ioque, &timeout); + status = pj_ioqueue_poll(ioque, &timeout); #endif - if (status > 0) { + if (status > 0) { if (callback_connect_key==ckey1) { - if (callback_connect_status == 0) { - // unexpectedly connected! - status = -50; - goto on_error; - } - } - - if (status > pending_op) { - PJ_LOG(3,(THIS_FILE, - "...error: pj_ioqueue_poll() returned %d " - "(only expecting %d)", - status, pending_op)); - return -552; - } - - pending_op -= status; - if (pending_op == 0) { - status = 0; - } - } + if (callback_connect_status == 0) { + // unexpectedly connected! + status = -50; + goto on_error; + } + } + + if (status > pending_op) { + PJ_LOG(3,(THIS_FILE, + "...error: pj_ioqueue_poll() returned %d " + "(only expecting %d)", + status, pending_op)); + return -552; + } + + pending_op -= status; + if (pending_op == 0) { + status = 0; + } + } } // There's no pending operation. // When we poll the ioqueue, there must not be events. if (pending_op == 0) { - unsigned i; + unsigned i; - for (i=0; i<10; ++i) { - pj_time_val timeout = {0, 50}; + for (i=0; i<10; ++i) { + pj_time_val timeout = {0, 50}; #ifdef PJ_SYMBIAN - status = pj_symbianos_poll(-1, PJ_TIME_VAL_MSEC(timeout)); + status = pj_symbianos_poll(-1, PJ_TIME_VAL_MSEC(timeout)); #else - status = pj_ioqueue_poll(ioque, &timeout); + status = pj_ioqueue_poll(ioque, &timeout); #endif - if (status != 0) { - status=-60; goto on_error; - } - } + if (status != 0) { + status=-60; goto on_error; + } + } } // Success @@ -595,12 +594,12 @@ static int compliance_test_1(const pj_ioqueue_cfg *cfg) on_error: if (ckey1 != NULL) - pj_ioqueue_unregister(ckey1); + pj_ioqueue_unregister(ckey1); else if (csock1 != PJ_INVALID_SOCKET) - pj_sock_close(csock1); + pj_sock_close(csock1); if (ioque != NULL) - pj_ioqueue_destroy(ioque); + pj_ioqueue_destroy(ioque); pj_pool_release(pool); return status; } @@ -619,26 +618,26 @@ static int compliance_test_2(const pj_ioqueue_cfg *cfg) struct listener { - pj_sock_t sock; - pj_ioqueue_key_t *key; - pj_sockaddr_in addr; - int addr_len; + pj_sock_t sock; + pj_ioqueue_key_t *key; + pj_sockaddr_in addr; + int addr_len; } listener; struct server { - pj_sock_t sock; - pj_ioqueue_key_t *key; - pj_sockaddr_in local_addr; - pj_sockaddr_in rem_addr; - int rem_addr_len; - pj_ioqueue_op_key_t accept_op; + pj_sock_t sock; + pj_ioqueue_key_t *key; + pj_sockaddr_in local_addr; + pj_sockaddr_in rem_addr; + int rem_addr_len; + pj_ioqueue_op_key_t accept_op; } server[MAX_PAIR]; struct client { - pj_sock_t sock; - pj_ioqueue_key_t *key; + pj_sock_t sock; + pj_ioqueue_key_t *key; } client[MAX_PAIR]; pj_pool_t *pool = NULL; @@ -655,13 +654,13 @@ static int compliance_test_2(const pj_ioqueue_cfg *cfg) listener.key = NULL; for (i=0; i 0) { - if (status > pending_op) { - PJ_LOG(3,(THIS_FILE, - "...error: pj_ioqueue_poll() returned %d " - "(only expecting %d)", - status, pending_op)); - return -110; - } - pending_op -= status; - - if (pending_op == 0) { - status = 0; - } - } - } - } - - // There's no pending operation. - // When we poll the ioqueue, there must not be events. - if (pending_op == 0) { - for (i=0; i<10; ++i) { - pj_time_val timeout = {0, 50}; + if (status > 0) { + if (status > pending_op) { + PJ_LOG(3,(THIS_FILE, + "...error: pj_ioqueue_poll() returned %d " + "(only expecting %d)", + status, pending_op)); + return -110; + } + pending_op -= status; + + if (pending_op == 0) { + status = 0; + } + } + } + } + + // There's no pending operation. + // When we poll the ioqueue, there must not be events. + if (pending_op == 0) { + for (i=0; i<10; ++i) { + pj_time_val timeout = {0, 50}; #ifdef PJ_SYMBIAN - status = pj_symbianos_poll(-1, PJ_TIME_VAL_MSEC(timeout)); + status = pj_symbianos_poll(-1, PJ_TIME_VAL_MSEC(timeout)); #else - status = pj_ioqueue_poll(ioque, &timeout); + status = pj_ioqueue_poll(ioque, &timeout); #endif - if (status != 0) { - status=-120; goto on_error; - } - } - } - - for (i=0; idefault_concurrency, - cfg->epoll_flags); + pj_ioqueue_name(), cfg->default_concurrency, + cfg->epoll_flags); PJ_LOG(3, (THIS_FILE, "..%s compliance test 0 (success scenario)", - title)); + title)); if ((status=compliance_test_0(cfg)) != 0) { - PJ_LOG(1, (THIS_FILE, "....FAILED (status=%d)\n", status)); - return status; + PJ_LOG(1, (THIS_FILE, "....FAILED (status=%d)\n", status)); + return status; } PJ_LOG(3, (THIS_FILE, "..%s compliance test 1 (failed scenario)", - title)); + title)); if ((status=compliance_test_1(cfg)) != 0) { - PJ_LOG(1, (THIS_FILE, "....FAILED (status=%d)\n", status)); - return status; + PJ_LOG(1, (THIS_FILE, "....FAILED (status=%d)\n", status)); + return status; } PJ_LOG(3, (THIS_FILE, "..%s compliance test 2 (repeated accept)", - title)); + title)); if ((status=compliance_test_2(cfg)) != 0) { - PJ_LOG(1, (THIS_FILE, "....FAILED (status=%d)\n", status)); - return status; + PJ_LOG(1, (THIS_FILE, "....FAILED (status=%d)\n", status)); + return status; } return 0; @@ -952,46 +951,46 @@ int tcp_ioqueue_test() pj_ioqueue_epoll_flag epoll_flags[] = { PJ_IOQUEUE_EPOLL_AUTO, #if PJ_HAS_LINUX_EPOLL - PJ_IOQUEUE_EPOLL_EXCLUSIVE, - PJ_IOQUEUE_EPOLL_ONESHOT, - 0 + PJ_IOQUEUE_EPOLL_EXCLUSIVE, + PJ_IOQUEUE_EPOLL_ONESHOT, + 0 #endif }; pj_bool_t concurs[] = { PJ_TRUE, PJ_FALSE }; int i, rc; for (i=0; i @@ -39,21 +38,21 @@ #include -#define THIS_FILE "test_udp" -#define PORT 51233 -#define LOOP 2 -///#define LOOP 2 -#define BUF_MIN_SIZE 32 -#define BUF_MAX_SIZE 2048 +#define THIS_FILE "test_udp" +#define PORT 51233 +#define LOOP 2 +///#define LOOP 2 +#define BUF_MIN_SIZE 32 +#define BUF_MAX_SIZE 2048 #define SOCK_INACTIVE_MIN (1) #define SOCK_INACTIVE_MAX (PJ_IOQUEUE_MAX_HANDLES - 2) -#define POOL_SIZE (2*BUF_MAX_SIZE + SOCK_INACTIVE_MAX*128 + 2048) +#define POOL_SIZE (2*BUF_MAX_SIZE + SOCK_INACTIVE_MAX*128 + 2048) #undef TRACE_ -#define TRACE_(msg) PJ_LOG(3,(THIS_FILE,"....." msg)) +#define TRACE_(msg) PJ_LOG(3,(THIS_FILE,"....." msg)) #if 0 -# define TRACE__(args) PJ_LOG(3,args) +# define TRACE__(args) PJ_LOG(3,args) #else # define TRACE__(args) #endif @@ -79,7 +78,7 @@ static void on_ioqueue_read(pj_ioqueue_key_t *key, callback_read_op = op_key; callback_read_size = bytes_read; TRACE__((THIS_FILE, " callback_read_key = %p, bytes=%d", - key, bytes_read)); + key, bytes_read)); } static void on_ioqueue_write(pj_ioqueue_key_t *key, @@ -161,7 +160,7 @@ static int compliance_test(const pj_ioqueue_cfg *cfg) csock = PJ_INVALID_SOCKET; if (rc != PJ_SUCCESS) { app_perror("...ERROR in pj_sock_socket()", rc); - status=-1; goto on_error; + status=-1; goto on_error; } // Bind server socket. @@ -170,14 +169,14 @@ static int compliance_test(const pj_ioqueue_cfg *cfg) addr.sin_family = pj_AF_INET(); addr.sin_port = pj_htons(PORT); if (pj_sock_bind(ssock, &addr, sizeof(addr))) { - status=-10; goto on_error; + status=-10; goto on_error; } // Create I/O Queue. TRACE_("create ioqueue..."); rc = pj_ioqueue_create2(pool, PJ_IOQUEUE_MAX_HANDLES, cfg, &ioque); if (rc != PJ_SUCCESS) { - status=-20; goto on_error; + status=-20; goto on_error; } // Register server and client socket. @@ -185,17 +184,17 @@ static int compliance_test(const pj_ioqueue_cfg *cfg) // worst waiting time. TRACE_("registering first sockets..."); rc = pj_ioqueue_register_sock(pool, ioque, ssock, NULL, - &test_cb, &skey); + &test_cb, &skey); if (rc != PJ_SUCCESS) { - app_perror("...error(10): ioqueue_register error", rc); - status=-25; goto on_error; + app_perror("...error(10): ioqueue_register error", rc); + status=-25; goto on_error; } TRACE_("registering second sockets..."); rc = pj_ioqueue_register_sock( pool, ioque, csock, NULL, - &test_cb, &ckey); + &test_cb, &ckey); if (rc != PJ_SUCCESS) { - app_perror("...error(11): ioqueue_register error", rc); - status=-26; goto on_error; + app_perror("...error(11): ioqueue_register error", rc); + status=-26; goto on_error; } // Randomize send_buf. @@ -211,44 +210,44 @@ static int compliance_test(const pj_ioqueue_cfg *cfg) addrlen = sizeof(addr); bytes = bufsize; rc = pj_ioqueue_recvfrom(skey, &read_op, recv_buf, &bytes, 0, - &addr, &addrlen); + &addr, &addrlen); if (rc != PJ_SUCCESS && rc != PJ_EPENDING) { app_perror("...error: pj_ioqueue_recvfrom", rc); - status=-28; goto on_error; + status=-28; goto on_error; } else if (rc == PJ_EPENDING) { - recv_pending = 1; - PJ_LOG(3, (THIS_FILE, - "......ok: recvfrom returned pending")); + recv_pending = 1; + PJ_LOG(3, (THIS_FILE, + "......ok: recvfrom returned pending")); } else { - PJ_LOG(3, (THIS_FILE, - "......error: recvfrom returned immediate ok!")); - status=-29; goto on_error; + PJ_LOG(3, (THIS_FILE, + "......error: recvfrom returned immediate ok!")); + status=-29; goto on_error; } // Set destination address to send the packet. TRACE_("set destination address..."); temp = pj_str("127.0.0.1"); if ((rc=pj_sockaddr_in_init(&dst_addr, &temp, PORT)) != 0) { - app_perror("...error: unable to resolve 127.0.0.1", rc); - status=-290; goto on_error; + app_perror("...error: unable to resolve 127.0.0.1", rc); + status=-290; goto on_error; } // Write must return the number of bytes. TRACE_("start sendto..."); bytes = bufsize; rc = pj_ioqueue_sendto(ckey, &write_op, send_buf, &bytes, 0, &dst_addr, - sizeof(dst_addr)); + sizeof(dst_addr)); if (rc != PJ_SUCCESS && rc != PJ_EPENDING) { app_perror("...error: pj_ioqueue_sendto", rc); - status=-30; goto on_error; + status=-30; goto on_error; } else if (rc == PJ_EPENDING) { - send_pending = 1; - PJ_LOG(3, (THIS_FILE, - "......ok: sendto returned pending")); + send_pending = 1; + PJ_LOG(3, (THIS_FILE, + "......ok: sendto returned pending")); } else { - send_pending = 0; - PJ_LOG(3, (THIS_FILE, - "......ok: sendto returned immediate success")); + send_pending = 0; + PJ_LOG(3, (THIS_FILE, + "......ok: sendto returned immediate success")); } // reset callback variables. @@ -260,25 +259,25 @@ static int compliance_test(const pj_ioqueue_cfg *cfg) // Poll if pending. while (send_pending || recv_pending) { - int ret; - pj_time_val timeout = { 5, 0 }; + int ret; + pj_time_val timeout = { 5, 0 }; - TRACE_("poll..."); + TRACE_("poll..."); #ifdef PJ_SYMBIAN - ret = pj_symbianos_poll(-1, PJ_TIME_VAL_MSEC(timeout)); + ret = pj_symbianos_poll(-1, PJ_TIME_VAL_MSEC(timeout)); #else - ret = pj_ioqueue_poll(ioque, &timeout); + ret = pj_ioqueue_poll(ioque, &timeout); #endif - if (ret == 0) { - PJ_LOG(1,(THIS_FILE, "...ERROR: timed out...")); - status=-45; goto on_error; + if (ret == 0) { + PJ_LOG(1,(THIS_FILE, "...ERROR: timed out...")); + status=-45; goto on_error; } else if (ret < 0) { app_perror("...ERROR in ioqueue_poll()", -ret); - status=-50; goto on_error; - } + status=-50; goto on_error; + } - if (callback_read_key != NULL) { + if (callback_read_key != NULL) { if (callback_read_size != bufsize) { status=-61; goto on_error; } @@ -289,19 +288,19 @@ static int compliance_test(const pj_ioqueue_cfg *cfg) status=-66; goto on_error; } - if (pj_memcmp(send_buf, recv_buf, bufsize) != 0) { - status=-67; goto on_error; - } - if (addrlen != sizeof(pj_sockaddr_in)) { - status=-68; goto on_error; - } - if (addr.sin_family != pj_AF_INET()) { - status=-69; goto on_error; - } + if (pj_memcmp(send_buf, recv_buf, bufsize) != 0) { + status=-67; goto on_error; + } + if (addrlen != sizeof(pj_sockaddr_in)) { + status=-68; goto on_error; + } + if (addr.sin_family != pj_AF_INET()) { + status=-69; goto on_error; + } - recv_pending = 0; - } + recv_pending = 0; + } if (callback_write_key != NULL) { if (callback_write_size != bufsize) { @@ -315,7 +314,7 @@ static int compliance_test(const pj_ioqueue_cfg *cfg) } send_pending = 0; - } + } } // Success @@ -323,17 +322,17 @@ static int compliance_test(const pj_ioqueue_cfg *cfg) on_error: if (skey) - pj_ioqueue_unregister(skey); + pj_ioqueue_unregister(skey); else if (ssock != -1) - pj_sock_close(ssock); + pj_sock_close(ssock); if (ckey) - pj_ioqueue_unregister(ckey); + pj_ioqueue_unregister(ckey); else if (csock != -1) - pj_sock_close(csock); + pj_sock_close(csock); if (ioque != NULL) - pj_ioqueue_destroy(ioque); + pj_ioqueue_destroy(ioque); pj_pool_release(pool); return status; @@ -378,28 +377,28 @@ static int unregister_test(const pj_ioqueue_cfg *cfg) pool = pj_pool_create(mem, "test", 4000, 4000, NULL); if (!pool) { - app_perror("Unable to create pool", PJ_ENOMEM); - return -100; + app_perror("Unable to create pool", PJ_ENOMEM); + return -100; } status = pj_ioqueue_create2(pool, 1, cfg, &ioqueue); if (status != PJ_SUCCESS) { - app_perror("Error creating ioqueue", status); - return -110; + app_perror("Error creating ioqueue", status); + return -110; } /* Create sender socket */ status = app_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, SPORT, &ssock); if (status != PJ_SUCCESS) { - app_perror("Error initializing socket", status); - return -120; + app_perror("Error initializing socket", status); + return -120; } /* Create receiver socket. */ status = app_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, RPORT, &rsock); if (status != PJ_SUCCESS) { - app_perror("Error initializing socket", status); - return -130; + app_perror("Error initializing socket", status); + return -130; } /* Register rsock to ioqueue. */ @@ -407,10 +406,10 @@ static int unregister_test(const pj_ioqueue_cfg *cfg) cb.on_read_complete = &on_read_complete; packet_cnt = 0; status = pj_ioqueue_register_sock(pool, ioqueue, rsock, &packet_cnt, - &cb, &key); + &cb, &key); if (status != PJ_SUCCESS) { - app_perror("Error registering to ioqueue", status); - return -140; + app_perror("Error registering to ioqueue", status); + return -140; } /* Init operation key. */ @@ -420,16 +419,16 @@ static int unregister_test(const pj_ioqueue_cfg *cfg) bytes = sizeof(recvbuf); status = pj_ioqueue_recv( key, &opkey, recvbuf, &bytes, 0); if (status != PJ_EPENDING) { - app_perror("Expecting PJ_EPENDING, but got this", status); - return -150; + app_perror("Expecting PJ_EPENDING, but got this", status); + return -150; } /* Init destination address. */ addrlen = sizeof(addr); status = pj_sock_getsockname(rsock, &addr, &addrlen); if (status != PJ_SUCCESS) { - app_perror("getsockname error", status); - return -160; + app_perror("getsockname error", status); + return -160; } /* Override address with 127.0.0.1, since getsockname will return @@ -443,11 +442,11 @@ static int unregister_test(const pj_ioqueue_cfg *cfg) /* Send one packet. */ bytes = sizeof(sendbuf); status = pj_sock_sendto(ssock, sendbuf, &bytes, 0, - &addr, sizeof(addr)); + &addr, sizeof(addr)); if (status != PJ_SUCCESS) { - app_perror("sendto error", status); - return -170; + app_perror("sendto error", status); + return -170; } /* Check if packet is received. */ @@ -459,7 +458,7 @@ static int unregister_test(const pj_ioqueue_cfg *cfg) #endif if (packet_cnt != 1) { - return -180; + return -180; } /* Just to make sure things are settled.. */ @@ -469,8 +468,8 @@ static int unregister_test(const pj_ioqueue_cfg *cfg) bytes = sizeof(recvbuf); status = pj_ioqueue_recv( key, &opkey, recvbuf, &bytes, 0); if (status != PJ_EPENDING) { - app_perror("Expecting PJ_EPENDING, but got this", status); - return -190; + app_perror("Expecting PJ_EPENDING, but got this", status); + return -190; } /* Reset packet counter */ @@ -479,50 +478,50 @@ static int unregister_test(const pj_ioqueue_cfg *cfg) /* Send one packet. */ bytes = sizeof(sendbuf); status = pj_sock_sendto(ssock, sendbuf, &bytes, 0, - &addr, sizeof(addr)); + &addr, sizeof(addr)); if (status != PJ_SUCCESS) { - app_perror("sendto error", status); - return -200; + app_perror("sendto error", status); + return -200; } /* Now unregister and close socket. */ status = pj_ioqueue_unregister(key); if (status != PJ_SUCCESS) { - app_perror("pj_ioqueue_unregister error", status); - return -201; + app_perror("pj_ioqueue_unregister error", status); + return -201; } /* Poll ioqueue. */ for (i=0; i<10; ++i) { #ifdef PJ_SYMBIAN - pj_symbianos_poll(-1, 100); + pj_symbianos_poll(-1, 100); #else - timeout.sec = 0; timeout.msec = 100; - pj_ioqueue_poll(ioqueue, &timeout); + timeout.sec = 0; timeout.msec = 100; + pj_ioqueue_poll(ioqueue, &timeout); #endif } /* Must NOT receive any packets after socket is closed! */ if (packet_cnt > 0) { - PJ_LOG(3,(THIS_FILE, "....errror: not expecting to receive packet " - "after socket has been closed")); - return -210; + PJ_LOG(3,(THIS_FILE, "....errror: not expecting to receive packet " + "after socket has been closed")); + return -210; } /* Now unregister again, immediately and after PJ_IOQUEUE_KEY_FREE_DELAY. * It should return error, and most importantly, it must not crash.. */ for (i=0; i<2; ++i) { - status = pj_ioqueue_unregister(key); - /* - * as it turns out, double unregistration returns PJ_SUCCESS - if (status == PJ_SUCCESS) { - PJ_LOG(1, (THIS_FILE, - "Expecting pj_ioqueue_unregister() error (i=%d)", i)); - return -220; - } - */ - pj_thread_sleep(PJ_IOQUEUE_KEY_FREE_DELAY + 100); + status = pj_ioqueue_unregister(key); + /* + * as it turns out, double unregistration returns PJ_SUCCESS + if (status == PJ_SUCCESS) { + PJ_LOG(1, (THIS_FILE, + "Expecting pj_ioqueue_unregister() error (i=%d)", i)); + return -220; + } + */ + pj_thread_sleep(PJ_IOQUEUE_KEY_FREE_DELAY + 100); } /* @@ -531,16 +530,16 @@ static int unregister_test(const pj_ioqueue_cfg *cfg) */ status = app_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, RPORT, &rsock2); if (status != PJ_SUCCESS) { - app_perror("Error initializing socket (2)", status); - return -330; + app_perror("Error initializing socket (2)", status); + return -330; } /* Register rsock to ioqueue. */ status = pj_ioqueue_register_sock(pool, ioqueue, rsock2, user_data2, - &cb, &key2); + &cb, &key2); if (status != PJ_SUCCESS) { - app_perror("Error registering to ioqueue (2)", status); - return -340; + app_perror("Error registering to ioqueue (2)", status); + return -340; } @@ -558,7 +557,7 @@ static int unregister_test(const pj_ioqueue_cfg *cfg) */ status = pj_ioqueue_unregister(key); if (status == PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, "....info: unregistering dead key was successful")); + PJ_LOG(3,(THIS_FILE, "....info: unregistering dead key was successful")); } /* Success */ @@ -590,36 +589,36 @@ static int many_handles_test(const pj_ioqueue_cfg *cfg) pool = pj_pool_create(mem, NULL, 4000, 4000, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; key = (pj_ioqueue_key_t**) - pj_pool_alloc(pool, MAX*sizeof(pj_ioqueue_key_t*)); + pj_pool_alloc(pool, MAX*sizeof(pj_ioqueue_key_t*)); sock = (pj_sock_t*) pj_pool_alloc(pool, MAX*sizeof(pj_sock_t)); /* Create IOQueue */ rc = pj_ioqueue_create2(pool, MAX, cfg, &ioqueue); if (rc != PJ_SUCCESS || ioqueue == NULL) { - app_perror("...error in pj_ioqueue_create", rc); - return -10; + app_perror("...error in pj_ioqueue_create", rc); + return -10; } /* Register as many sockets. */ for (count=0; count=0; --i) { ///for (i=0; iuser_data; if (bytes_read < 0) { - pj_status_t status = (pj_status_t)-bytes_read; - - if (status==PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) { - TRACE__((THIS_FILE, "......recv() fail with status=%d, retrying", - status)); - ud->len = bytes_read = sizeof(ud->buffer); - status = pj_ioqueue_recv(key, op_key, &ud->buffer, &ud->len, 0); - if (status == PJ_EPENDING) - return; - } - - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, "......status=%d", status)); - return; - } + pj_status_t status = (pj_status_t)-bytes_read; + + if (status==PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) { + TRACE__((THIS_FILE, "......recv() fail with status=%d, retrying", + status)); + ud->len = bytes_read = sizeof(ud->buffer); + status = pj_ioqueue_recv(key, op_key, &ud->buffer, &ud->len, 0); + if (status == PJ_EPENDING) + return; + } + + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(THIS_FILE, status, "......status=%d", status)); + return; + } } assert (bytes_read==sizeof(unsigned)); if (ud->buffer != *p_packet_cnt) { - PJ_LOG(1,(THIS_FILE, "......error: invalid packet sequence " - "(expecting %d, got %d)", - *p_packet_cnt, ud->buffer)); + PJ_LOG(1,(THIS_FILE, "......error: invalid packet sequence " + "(expecting %d, got %d)", + *p_packet_cnt, ud->buffer)); } else { - TRACE__((THIS_FILE, "......recv() sequence %d", ud->buffer)); + TRACE__((THIS_FILE, "......recv() sequence %d", ud->buffer)); } (*p_packet_cnt)++; @@ -717,28 +716,28 @@ static int parallel_worker_thread(void *p) t_end.sec += arg->timeout; while (!arg->quit_flag) { - pj_time_val timeout = {0, 0}; - int rc; - - timeout.sec = arg->timeout; - rc = pj_ioqueue_poll(arg->ioqueue, &timeout); - if (rc >= 1) { - assert(rc==1); /* we should receive packet one by one! */ - TRACE__((THIS_FILE, "......thread %d got event (total=%d)", - arg->id, arg->wakeup_cnt)); - ++arg->wakeup_cnt; - arg->event_cnt += rc; - } else if (rc == 0) { - if (!arg->quit_flag) { - TRACE__((THIS_FILE, "......thread %d wakeup, no event (total=%d)", - arg->id, arg->wakeup_cnt)); - ++arg->wakeup_cnt; - } - } else if (rc < 0) { - TRACE__((THIS_FILE, "......thread %d got error", arg->id)); - ++arg->wakeup_cnt; - ++arg->err_cnt; - } + pj_time_val timeout = {0, 0}; + int rc; + + timeout.sec = arg->timeout; + rc = pj_ioqueue_poll(arg->ioqueue, &timeout); + if (rc >= 1) { + assert(rc==1); /* we should receive packet one by one! */ + TRACE__((THIS_FILE, "......thread %d got event (total=%d)", + arg->id, arg->wakeup_cnt)); + ++arg->wakeup_cnt; + arg->event_cnt += rc; + } else if (rc == 0) { + if (!arg->quit_flag) { + TRACE__((THIS_FILE, "......thread %d wakeup, no event (total=%d)", + arg->id, arg->wakeup_cnt)); + ++arg->wakeup_cnt; + } + } else if (rc < 0) { + TRACE__((THIS_FILE, "......thread %d got error", arg->id)); + ++arg->wakeup_cnt; + ++arg->err_cnt; + } } return 0; @@ -761,10 +760,10 @@ static int parallel_recv_test(const pj_ioqueue_cfg *cfg) pj_ioqueue_key_t *skey = NULL; pj_ioqueue_callback cb; enum { - ASYNC_CNT = 16, - PKT_SIZE = 16, - SEND_DELAY_MSECS = 250, - TIMEOUT_SECS = (SEND_DELAY_MSECS*ASYNC_CNT/1000)+2, + ASYNC_CNT = 16, + PKT_SIZE = 16, + SEND_DELAY_MSECS = 250, + TIMEOUT_SECS = (SEND_DELAY_MSECS*ASYNC_CNT/1000)+2, }; typedef int packet_t; pj_thread_t *threads[ASYNC_CNT]; @@ -776,40 +775,40 @@ static int parallel_recv_test(const pj_ioqueue_cfg *cfg) pool = pj_pool_create(mem, "test", 4000, 4000, NULL); if (!pool) { - app_perror("Unable to create pool", PJ_ENOMEM); - return -100; + app_perror("Unable to create pool", PJ_ENOMEM); + return -100; } CHECK(-110, app_socketpair(pj_AF_INET(), pj_SOCK_STREAM(), 0, - &ssock, &csock)); + &ssock, &csock)); CHECK(-120, pj_ioqueue_create2(pool, 2, cfg, &ioqueue)); pj_bzero(&cb, sizeof(cb)); cb.on_read_complete = &on_read_complete2; CHECK(-130, pj_ioqueue_register_sock(pool, ioqueue, ssock, &recv_packet_count, - &cb, &skey)); + &cb, &skey)); /* spawn parallel recv()s */ pj_bzero(recv_datas, sizeof(recv_datas)); for (i=0; iioqueue = ioqueue; - arg->id = i; - arg->timeout = TIMEOUT_SECS; - - CHECK(-150, pj_thread_create(pool, "parallel_thread", - parallel_worker_thread, arg, - 0, 0,&threads[i])); + parallel_thread_data *arg = &thread_datas[i]; + arg->ioqueue = ioqueue; + arg->id = i; + arg->timeout = TIMEOUT_SECS; + + CHECK(-150, pj_thread_create(pool, "parallel_thread", + parallel_worker_thread, arg, + 0, 0,&threads[i])); } /* now slowly send packet one by one. Let's hope the OS doesn't drop @@ -817,33 +816,33 @@ static int parallel_recv_test(const pj_ioqueue_cfg *cfg) */ pj_thread_sleep(100); /* allow thread to start */ for (i=0; i0)*SEND_DELAY_MSECS); - TRACE__((THIS_FILE, "....sending")); - status = pj_sock_send(csock, &send_buf, &len, 0); - if (status==PJ_EPENDING) { - ++async_send; - TRACE__((THIS_FILE, "......(was async sent)")); - } else if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "......send error")); - retcode = -160; - goto on_return; - } + packet_t send_buf = i; + pj_ssize_t len = sizeof(send_buf); + pj_status_t status; + + pj_thread_sleep((i>0)*SEND_DELAY_MSECS); + TRACE__((THIS_FILE, "....sending")); + status = pj_sock_send(csock, &send_buf, &len, 0); + if (status==PJ_EPENDING) { + ++async_send; + TRACE__((THIS_FILE, "......(was async sent)")); + } else if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, "......send error")); + retcode = -160; + goto on_return; + } } /* Signal threads that it's done */ for (i=0; iquit_flag = 1; + parallel_thread_data *arg = &thread_datas[i]; + arg->quit_flag = 1; } /* Wait until all threads quits */ for (i=0; iwakeup_cnt; - threads_total.event_cnt += arg->event_cnt; - threads_total.err_cnt += arg->err_cnt; + threads_total.wakeup_cnt += arg->wakeup_cnt; + threads_total.event_cnt += arg->event_cnt; + threads_total.err_cnt += arg->err_cnt; - PJ_LOG(3,(THIS_FILE, " %6d %6d %6d %6d", - arg->id, arg->wakeup_cnt, arg->event_cnt, arg->err_cnt)); + PJ_LOG(3,(THIS_FILE, " %6d %6d %6d %6d", + arg->id, arg->wakeup_cnt, arg->event_cnt, arg->err_cnt)); } retcode = 0; @@ -868,32 +867,32 @@ static int parallel_recv_test(const pj_ioqueue_cfg *cfg) /* Analyze results */ //assert(threads_total.event_cnt == recv_packet_count); if (recv_packet_count != ASYNC_CNT) { - PJ_LOG(1,(THIS_FILE, "....error: rx packet count is %d (expecting %d)", - recv_packet_count, ASYNC_CNT)); - retcode = -500; + PJ_LOG(1,(THIS_FILE, "....error: rx packet count is %d (expecting %d)", + recv_packet_count, ASYNC_CNT)); + retcode = -500; } if (threads_total.wakeup_cnt > ASYNC_CNT+async_send) { - PJ_LOG(3,(THIS_FILE, "....info: total wakeup count is %d " - "(the perfect count is %d). This shows that " - "threads are woken up without getting any events", - threads_total.wakeup_cnt, ASYNC_CNT+async_send)); + PJ_LOG(3,(THIS_FILE, "....info: total wakeup count is %d " + "(the perfect count is %d). This shows that " + "threads are woken up without getting any events", + threads_total.wakeup_cnt, ASYNC_CNT+async_send)); } if (threads_total.err_cnt > 0) { - PJ_LOG(3,(THIS_FILE, "....info: total error count is %d " - "(it should be 0)", - threads_total.err_cnt)); + PJ_LOG(3,(THIS_FILE, "....info: total error count is %d " + "(it should be 0)", + threads_total.err_cnt)); } if (retcode==0) - PJ_LOG(3,(THIS_FILE, "....success")); + PJ_LOG(3,(THIS_FILE, "....success")); on_return: if (skey) - pj_ioqueue_unregister(skey); + pj_ioqueue_unregister(skey); if (csock != PJ_INVALID_SOCKET) - pj_sock_close(csock); + pj_sock_close(csock); if (ioqueue) - pj_ioqueue_destroy(ioqueue); + pj_ioqueue_destroy(ioqueue); pj_pool_release(pool); return retcode; } @@ -908,7 +907,7 @@ static int parallel_recv_test(const pj_ioqueue_cfg *cfg) * Benchmarking IOQueue */ static int bench_test(const pj_ioqueue_cfg *cfg, int bufsize, - int inactive_sock_count) + int inactive_sock_count) { pj_sock_t ssock=-1, csock=-1; pj_sockaddr_in addr; @@ -939,8 +938,8 @@ static int bench_test(const pj_ioqueue_cfg *cfg, int bufsize, } else csock = PJ_INVALID_SOCKET; if (rc != PJ_SUCCESS) { - app_perror("...error: pj_sock_socket()", rc); - goto on_error; + app_perror("...error: pj_sock_socket()", rc); + goto on_error; } // Bind server socket. @@ -948,21 +947,21 @@ static int bench_test(const pj_ioqueue_cfg *cfg, int bufsize, addr.sin_family = pj_AF_INET(); addr.sin_port = pj_htons(PORT); if (pj_sock_bind(ssock, &addr, sizeof(addr))) - goto on_error; + goto on_error; pj_assert(inactive_sock_count+2 <= PJ_IOQUEUE_MAX_HANDLES); // Create I/O Queue. rc = pj_ioqueue_create2(pool, PJ_IOQUEUE_MAX_HANDLES, cfg, &ioque); if (rc != PJ_SUCCESS) { - app_perror("...error: pj_ioqueue_create()", rc); - goto on_error; + app_perror("...error: pj_ioqueue_create()", rc); + goto on_error; } // Allocate inactive sockets, and bind them to some arbitrary address. // Then register them to the I/O queue, and start a read operation. inactive_sock = (pj_sock_t*)pj_pool_alloc(pool, - inactive_sock_count*sizeof(pj_sock_t)); + inactive_sock_count*sizeof(pj_sock_t)); inactive_read_op = (pj_ioqueue_op_key_t*)pj_pool_alloc(pool, inactive_sock_count*sizeof(pj_ioqueue_op_key_t)); pj_bzero(&addr, sizeof(addr)); @@ -970,53 +969,53 @@ static int bench_test(const pj_ioqueue_cfg *cfg, int bufsize, for (i=0; i= 0 && callback_read_key != skey); - - // End time. - pj_get_timestamp(&t2); - t_elapsed.u64 += (t2.u64 - t1.u64); - - if (rc < 0) { - app_perror(" error: pj_ioqueue_poll", -rc); - break; - } - - // Compare recv buffer with send buffer. - if (callback_read_size != bufsize || - pj_memcmp(send_buf, recv_buf, bufsize)) - { - rc = -10; - PJ_LOG(3,(THIS_FILE, " error: size/buffer mismatch")); - break; - } - - // Poll until all events are exhausted, before we start the next loop. - do { - pj_time_val timeout = { 0, 10 }; + TRACE__((THIS_FILE, " poll rc=%d", rc)); + } while (rc >= 0 && callback_read_key != skey); + + // End time. + pj_get_timestamp(&t2); + t_elapsed.u64 += (t2.u64 - t1.u64); + + if (rc < 0) { + app_perror(" error: pj_ioqueue_poll", -rc); + break; + } + + // Compare recv buffer with send buffer. + if (callback_read_size != bufsize || + pj_memcmp(send_buf, recv_buf, bufsize)) + { + rc = -10; + PJ_LOG(3,(THIS_FILE, " error: size/buffer mismatch")); + break; + } + + // Poll until all events are exhausted, before we start the next loop. + do { + pj_time_val timeout = { 0, 10 }; #ifdef PJ_SYMBIAN - PJ_UNUSED_ARG(timeout); - rc = pj_symbianos_poll(-1, 100); -#else - rc = pj_ioqueue_poll(ioque, &timeout); + PJ_UNUSED_ARG(timeout); + rc = pj_symbianos_poll(-1, 100); +#else + rc = pj_ioqueue_poll(ioque, &timeout); #endif - } while (rc>0); + } while (rc>0); - rc = 0; + rc = 0; } // Print results if (rc == 0) { - pj_timestamp tzero; - pj_uint32_t usec_delay; + pj_timestamp tzero; + pj_uint32_t usec_delay; - tzero.u32.hi = tzero.u32.lo = 0; - usec_delay = pj_elapsed_usec( &tzero, &t_elapsed); + tzero.u32.hi = tzero.u32.lo = 0; + usec_delay = pj_elapsed_usec( &tzero, &t_elapsed); - PJ_LOG(3, (THIS_FILE, "...%10d %15d % 9d", - bufsize, inactive_sock_count, usec_delay)); + PJ_LOG(3, (THIS_FILE, "...%10d %15d % 9d", + bufsize, inactive_sock_count, usec_delay)); } else { - PJ_LOG(2, (THIS_FILE, "...ERROR rc=%d (buf:%d, fds:%d)", - rc, bufsize, inactive_sock_count+2)); + PJ_LOG(2, (THIS_FILE, "...ERROR rc=%d (buf:%d, fds:%d)", + rc, bufsize, inactive_sock_count+2)); } // Cleaning up. for (i=inactive_sock_count-1; i>=0; --i) { - pj_ioqueue_unregister(keys[i]); + pj_ioqueue_unregister(keys[i]); } pj_ioqueue_unregister(skey); @@ -1138,18 +1137,18 @@ static int bench_test(const pj_ioqueue_cfg *cfg, int bufsize, on_error: PJ_LOG(1,(THIS_FILE, "...ERROR: %s", - pj_strerror(pj_get_netos_error(), errbuf, sizeof(errbuf)))); + pj_strerror(pj_get_netos_error(), errbuf, sizeof(errbuf)))); if (ssock) - pj_sock_close(ssock); + pj_sock_close(ssock); if (csock) - pj_sock_close(csock); + pj_sock_close(csock); for (i=0; idefault_concurrency, - cfg->epoll_flags); + pj_ioqueue_name(), cfg->default_concurrency, + cfg->epoll_flags); //goto pass1; PJ_LOG(3, (THIS_FILE, "...compliance test (%s)", title)); if ((status=compliance_test(cfg)) != 0) { - return status; + return status; } PJ_LOG(3, (THIS_FILE, "....compliance test ok")); PJ_LOG(3, (THIS_FILE, "...unregister test (%s)", title)); if ((status=unregister_test(cfg)) != 0) { - return status; + return status; } PJ_LOG(3, (THIS_FILE, "....unregister test ok")); if ((status=many_handles_test(cfg)) != 0) { - return status; + return status; } //return 0; PJ_LOG(4, (THIS_FILE, "...benchmarking different buffer size:")); PJ_LOG(4, (THIS_FILE, "... note: buf=bytes sent, fds=# of fds, " - "elapsed=in timer ticks")); + "elapsed=in timer ticks")); //pass1: PJ_LOG(3, (THIS_FILE, "...Benchmarking poll times for %s:", title)); @@ -1198,18 +1197,18 @@ static int udp_ioqueue_test_imp(const pj_ioqueue_cfg *cfg) //goto pass2; for (bufsize=BUF_MIN_SIZE; bufsize <= BUF_MAX_SIZE; bufsize *= 2) { - if ((status=bench_test(cfg, bufsize, SOCK_INACTIVE_MIN)) != 0) - return status; + if ((status=bench_test(cfg, bufsize, SOCK_INACTIVE_MIN)) != 0) + return status; } //pass2: bufsize = 512; for (sock_count=SOCK_INACTIVE_MIN+2; - sock_count<=SOCK_INACTIVE_MAX+2; - sock_count *= 2) + sock_count<=SOCK_INACTIVE_MAX+2; + sock_count *= 2) { - //PJ_LOG(3,(THIS_FILE, "...testing with %d fds", sock_count)); - if ((status=bench_test(cfg, bufsize, sock_count-2)) != 0) - return status; + //PJ_LOG(3,(THIS_FILE, "...testing with %d fds", sock_count)); + if ((status=bench_test(cfg, bufsize, sock_count-2)) != 0) + return status; } return 0; } @@ -1219,9 +1218,9 @@ int udp_ioqueue_test() pj_ioqueue_epoll_flag epoll_flags[] = { #if PJ_HAS_LINUX_EPOLL PJ_IOQUEUE_EPOLL_AUTO, - PJ_IOQUEUE_EPOLL_EXCLUSIVE, - PJ_IOQUEUE_EPOLL_ONESHOT, - 0, + PJ_IOQUEUE_EPOLL_EXCLUSIVE, + PJ_IOQUEUE_EPOLL_ONESHOT, + 0, #else PJ_IOQUEUE_EPOLL_AUTO, #endif @@ -1230,46 +1229,46 @@ int udp_ioqueue_test() int i, rc, err = 0; for (i=0; i @@ -51,16 +50,16 @@ static pj_time_val time_to_unregister; struct sock_data { - pj_sock_t sock; - pj_sock_t csock; - pj_pool_t *pool; - pj_ioqueue_key_t *key; - pj_mutex_t *mutex; - pj_ioqueue_op_key_t *op_key; - char *buffer; - pj_size_t bufsize; - pj_bool_t unregistered; - pj_ssize_t received; + pj_sock_t sock; + pj_sock_t csock; + pj_pool_t *pool; + pj_ioqueue_key_t *key; + pj_mutex_t *mutex; + pj_ioqueue_op_key_t *op_key; + char *buffer; + pj_size_t bufsize; + pj_bool_t unregistered; + pj_ssize_t received; } sock_data; static void on_read_complete(pj_ioqueue_key_t *key, @@ -72,47 +71,47 @@ static void on_read_complete(pj_ioqueue_key_t *key, pj_status_t status; TRACE((THIS_FILE, "......on_read_complete(): unregistered=%d, bytes=%d", - sock_data.unregistered, bytes_read)); + sock_data.unregistered, bytes_read)); if (sock_data.unregistered) { - TRACE((THIS_FILE, "........bailing out")); - return; + TRACE((THIS_FILE, "........bailing out")); + return; } pj_mutex_lock(sock_data.mutex); if (sock_data.unregistered) { - TRACE((THIS_FILE, "........bailing out")); - pj_mutex_unlock(sock_data.mutex); - return; + TRACE((THIS_FILE, "........bailing out")); + pj_mutex_unlock(sock_data.mutex); + return; } if (bytes_read < 0) { - if (-bytes_read != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) - app_perror("ioqueue reported recv error", (pj_status_t)-bytes_read); + if (-bytes_read != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) + app_perror("ioqueue reported recv error", (pj_status_t)-bytes_read); } else { - sock_data.received += bytes_read; + sock_data.received += bytes_read; } if (test_method == UNREGISTER_IN_CALLBACK) { - pj_time_val now; - - pj_gettimeofday(&now); - if (PJ_TIME_VAL_GTE(now, time_to_unregister)) { - sock_data.unregistered = 1; - TRACE((THIS_FILE, "......on_read_complete(): unregistering")); - pj_ioqueue_unregister(key); - pj_mutex_unlock(sock_data.mutex); - return; - } + pj_time_val now; + + pj_gettimeofday(&now); + if (PJ_TIME_VAL_GTE(now, time_to_unregister)) { + sock_data.unregistered = 1; + TRACE((THIS_FILE, "......on_read_complete(): unregistering")); + pj_ioqueue_unregister(key); + pj_mutex_unlock(sock_data.mutex); + return; + } } do { - size = sock_data.bufsize; - status = pj_ioqueue_recv(key, op_key, sock_data.buffer, &size, 0); - TRACE((THIS_FILE, "........recv, status=%d", status)); - if (status != PJ_EPENDING && status != PJ_SUCCESS) - app_perror("recv() error", status); + size = sock_data.bufsize; + status = pj_ioqueue_recv(key, op_key, sock_data.buffer, &size, 0); + TRACE((THIS_FILE, "........recv, status=%d", status)); + if (status != PJ_EPENDING && status != PJ_SUCCESS) + app_perror("recv() error", status); } while (status == PJ_SUCCESS); @@ -121,12 +120,12 @@ static void on_read_complete(pj_ioqueue_key_t *key, size = pj_ansi_strlen(sendbuf); status = pj_sock_send(sock_data.csock, sendbuf, &size, 0); if (status != PJ_SUCCESS) - app_perror("send() error", status); + app_perror("send() error", status); size = pj_ansi_strlen(sendbuf); status = pj_sock_send(sock_data.csock, sendbuf, &size, 0); if (status != PJ_SUCCESS) - app_perror("send() error", status); + app_perror("send() error", status); TRACE((THIS_FILE, "........done")); } @@ -136,8 +135,8 @@ static int worker_thread(void *arg) pj_ioqueue_t *ioqueue = (pj_ioqueue_t*) arg; while (!thread_quitting) { - pj_time_val timeout = { 0, 200 }; - pj_ioqueue_poll(ioqueue, &timeout); + pj_time_val timeout = { 0, 200 }; + pj_ioqueue_poll(ioqueue, &timeout); } return 0; @@ -151,9 +150,9 @@ static int worker_thread(void *arg) * unregister and destroy the server socket after some period of time. */ static int perform_unreg_test(pj_ioqueue_t *ioqueue, - pj_pool_t *test_pool, - const char *title, - pj_bool_t other_socket) + pj_pool_t *test_pool, + const char *title, + pj_bool_t other_socket) { enum { WORKER_CNT = 1, MSEC = 500, QUIT_MSEC = 500 }; int i; @@ -169,23 +168,23 @@ static int perform_unreg_test(pj_ioqueue_t *ioqueue, * will return from the poll early. */ if (other_socket) { - status = app_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, 56127, &osd.sock); - if (status != PJ_SUCCESS) { - app_perror("Error creating other socket", status); - return -12; - } - - pj_bzero(&callback, sizeof(callback)); - status = pj_ioqueue_register_sock(test_pool, ioqueue, osd.sock, - NULL, &callback, &osd.key); - if (status != PJ_SUCCESS) { - app_perror("Error registering other socket", status); - return -13; - } + status = app_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, 56127, &osd.sock); + if (status != PJ_SUCCESS) { + app_perror("Error creating other socket", status); + return -12; + } + + pj_bzero(&callback, sizeof(callback)); + status = pj_ioqueue_register_sock(test_pool, ioqueue, osd.sock, + NULL, &callback, &osd.key); + if (status != PJ_SUCCESS) { + app_perror("Error registering other socket", status); + return -13; + } } else { - osd.key = NULL; - osd.sock = PJ_INVALID_SOCKET; + osd.key = NULL; + osd.sock = PJ_INVALID_SOCKET; } /* Init both time duration of testing */ @@ -201,20 +200,20 @@ static int perform_unreg_test(pj_ioqueue_t *ioqueue, /* Create polling thread */ for (i=0; i @@ -60,7 +59,7 @@ static int compare_node(void *value, const pj_list_type *nd) return ((long)(pj_ssize_t)value == node->value) ? 0 : -1; } -#define PJ_SIGNED_ARRAY_SIZE(a) ((int)PJ_ARRAY_SIZE(a)) +#define PJ_SIGNED_ARRAY_SIZE(a) ((int)PJ_ARRAY_SIZE(a)) int list_test() { @@ -76,15 +75,15 @@ int list_test() list.value = (unsigned)-1; pj_list_init(&list); for (i=0; inext) { - pj_assert(p->value == i); - if (p->value != i) { - return -1; - } + pj_assert(p->value == i); + if (p->value != i) { + return -1; + } } // @@ -92,14 +91,14 @@ int list_test() // pj_list_init(&list); for (i=PJ_SIGNED_ARRAY_SIZE(nodes)-1; i>=0; --i) { - pj_list_insert_after(&list, &nodes[i]); + pj_list_insert_after(&list, &nodes[i]); } // check. for (i=0, p=list.next; inext) { - pj_assert(p->value == i); - if (p->value != i) { - return -1; - } + pj_assert(p->value == i); + if (p->value != i) { + return -1; + } } // @@ -109,24 +108,24 @@ int list_test() pj_list_init(&list); pj_list_init(&list2); for (i=0; inext) { - pj_assert(p->value == i); - if (p->value != i) { - return -1; - } + pj_assert(p->value == i); + if (p->value != i) { + return -1; + } } // check list is empty pj_assert( pj_list_empty(&list2) ); if (!pj_list_empty(&list2)) { - return -1; + return -1; } // @@ -135,24 +134,24 @@ int list_test() pj_list_init(&list); pj_list_init(&list2); for (i=0; inext) { - pj_assert(p->value == i); - if (p->value != i) { - return -1; - } + pj_assert(p->value == i); + if (p->value != i) { + return -1; + } } // check list is empty pj_assert( pj_list_empty(&list) ); if (!pj_list_empty(&list)) { - return -1; + return -1; } // @@ -161,58 +160,58 @@ int list_test() // init list pj_list_init(&list); for (i=0; inext) { - pj_assert(p->value == i); - if (p->value != i) { - return -1; - } + pj_assert(p->value == i); + if (p->value != i) { + return -1; + } } // erase test. pj_list_init(&list); for (i=0; i=0; --i) { - int j; - pj_list_erase(&nodes[i]); - for (j=0, p=list.next; jnext) { - pj_assert(p->value == j); - if (p->value != j) { - return -1; - } - } + int j; + pj_list_erase(&nodes[i]); + for (j=0, p=list.next; jnext) { + pj_assert(p->value == j); + if (p->value != j) { + return -1; + } + } } // find and search pj_list_init(&list); for (i=0; i @@ -93,12 +92,12 @@ int main(int argc, char *argv[]) while (argc > 1) { char *arg = argv[--argc]; - if (*arg=='-' && *(arg+1)=='i') { - interractive = 1; + if (*arg=='-' && *(arg+1)=='i') { + interractive = 1; - } else if (*arg=='-' && *(arg+1)=='n') { - no_trap = 1; - } else if (*arg=='-' && *(arg+1)=='p') { + } else if (*arg=='-' && *(arg+1)=='n') { + no_trap = 1; + } else if (*arg=='-' && *(arg+1)=='p') { pj_str_t port = pj_str(argv[--argc]); param_echo_port = pj_strtoul(&port); @@ -121,17 +120,17 @@ int main(int argc, char *argv[]) } if (!no_trap) { - init_signals(); + init_signals(); } rc = test_main(); if (interractive) { - char s[10]; - puts(""); - puts("Press to exit"); - if (!fgets(s, sizeof(s), stdin)) - return rc; + char s[10]; + puts(""); + puts("Press to exit"); + if (!fgets(s, sizeof(s), stdin)) + return rc; } return rc; diff --git a/pjlib/src/pjlib-test/main_mod.c b/pjlib/src/pjlib-test/main_mod.c index e82b1bc9cf..20b7fc1e94 100644 --- a/pjlib/src/pjlib-test/main_mod.c +++ b/pjlib/src/pjlib-test/main_mod.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pjlib-test/main_rtems.c b/pjlib/src/pjlib-test/main_rtems.c index 934a22ab9f..8fa0102f81 100644 --- a/pjlib/src/pjlib-test/main_rtems.c +++ b/pjlib/src/pjlib-test/main_rtems.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -51,18 +50,18 @@ extern int param_echo_port; #define CONFIGURE_POSIX_INIT_THREAD_TABLE -#define CONFIGURE_MAXIMUM_POSIX_MUTEXES rtems_resource_unlimited(16) +#define CONFIGURE_MAXIMUM_POSIX_MUTEXES rtems_resource_unlimited(16) #define CONFIGURE_MAXIMUM_POSIX_CONDITION_VARIABLES rtems_resource_unlimited(5) #define CONFIGURE_MAXIMUM_POSIX_SEMAPHORES rtems_resource_unlimited(16) -#define CONFIGURE_MAXIMUM_POSIX_TIMERS rtems_resource_unlimited(5) -#define CONFIGURE_MAXIMUM_POSIX_THREADS rtems_resource_unlimited(16) -#define CONFIGURE_MAXIMUM_POSIX_KEYS rtems_resource_unlimited(16) +#define CONFIGURE_MAXIMUM_POSIX_TIMERS rtems_resource_unlimited(5) +#define CONFIGURE_MAXIMUM_POSIX_THREADS rtems_resource_unlimited(16) +#define CONFIGURE_MAXIMUM_POSIX_KEYS rtems_resource_unlimited(16) -#define CONFIGURE_POSIX_INIT_THREAD_STACK_SIZE 4096 +#define CONFIGURE_POSIX_INIT_THREAD_STACK_SIZE 4096 /* Make sure that stack size is at least 4096 */ -#define SZ (4096-RTEMS_MINIMUM_STACK_SIZE) -#define CONFIGURE_EXTRA_TASK_STACKS ((SZ)<0 ? 0 : (SZ)) +#define SZ (4096-RTEMS_MINIMUM_STACK_SIZE) +#define CONFIGURE_EXTRA_TASK_STACKS ((SZ)<0 ? 0 : (SZ)) #define CONFIGURE_INIT #define STACK_CHECKER_ON @@ -98,22 +97,22 @@ static void my_perror(pj_status_t status, const char *title) } #define TEST(expr) { int rc;\ - /*PJ_LOG(3,(THIS_FILE,"%s", #expr));*/ \ - /*sleep(1);*/ \ - rc=expr; \ - if (rc) my_perror(PJ_STATUS_FROM_OS(rc),#expr); } + /*PJ_LOG(3,(THIS_FILE,"%s", #expr));*/ \ + /*sleep(1);*/ \ + rc=expr; \ + if (rc) my_perror(PJ_STATUS_FROM_OS(rc),#expr); } //rtems_task Init(rtems_task_argument Argument) void *POSIX_Init(void *argument) { - pthread_attr_t threadAttr; - pthread_t theThread; - struct sched_param sched_param; - size_t stack_size; - int result; - char data[1000]; + pthread_attr_t threadAttr; + pthread_t theThread; + struct sched_param sched_param; + size_t stack_size; + int result; + char data[1000]; memset(data, 1, sizeof(data)); @@ -123,8 +122,8 @@ void *POSIX_Init(void *argument) if (RTEMS_SUCCESSFUL != rtems_clock_set(&fakeTime)) { - assert(0); - } + assert(0); + } /* Bring up the network stack so we can run the socket tests. */ initialize_network(); @@ -159,15 +158,15 @@ void *POSIX_Init(void *argument) */ TEST( pthread_attr_getstacksize(&threadAttr, &stack_size)); if (stack_size < 8192) - TEST( pthread_attr_setstacksize(&threadAttr, 8192)); + TEST( pthread_attr_setstacksize(&threadAttr, 8192)); /* Create the thread for application */ result = pthread_create(&theThread, &threadAttr, &pjlib_test_main, NULL); if (result != 0) { - my_perror(PJ_STATUS_FROM_OS(result), - "Error creating pjlib_test_main thread"); - assert(!"Error creating main thread"); + my_perror(PJ_STATUS_FROM_OS(result), + "Error creating pjlib_test_main thread"); + assert(!"Error creating main thread"); } return NULL; @@ -224,9 +223,9 @@ send_udp(const char *target) struct sockaddr_in addr; PJ_LOG(3,("main_rtems.c", "IP addr=%s/%s, gw=%s", - DEFAULT_IP_ADDRESS_STRING, - DEFAULT_NETMASK_STRING, - DEFAULT_GATEWAY_STRING)); + DEFAULT_IP_ADDRESS_STRING, + DEFAULT_NETMASK_STRING, + DEFAULT_GATEWAY_STRING)); sock = socket(AF_INET, SOCK_DGRAM, 0); assert(sock > 0); @@ -241,11 +240,11 @@ send_udp(const char *target) addr.sin_port = htons(4444); while(1) { - const char *data = "hello"; + const char *data = "hello"; - rc = sendto(sock, data, 5, 0, (struct sockaddr*)&addr, sizeof(addr)); - PJ_LOG(3,("main_rtems.c", "pinging %s..(rc=%d)", target, rc)); - sleep(1); + rc = sendto(sock, data, 5, 0, (struct sockaddr*)&addr, sizeof(addr)); + PJ_LOG(3,("main_rtems.c", "pinging %s..(rc=%d)", target, rc)); + sleep(1); } } @@ -258,8 +257,8 @@ static void test_sock(void) sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { - printf("socket() error\n"); - goto end; + printf("socket() error\n"); + goto end; } memset(&addr, 0, sizeof(addr)); @@ -269,9 +268,9 @@ static void test_sock(void) rc = bind(sock, (struct sockaddr*)&addr, sizeof(addr)); if (rc != 0) { - printf("bind() error %d\n", rc); - close(sock); - goto end; + printf("bind() error %d\n", rc); + close(sock); + goto end; } puts("Bind socket success"); @@ -300,9 +299,9 @@ initialize_network() result = write(fd, "hosts,bind\n", 11); result = close(fd); fd = open("/etc/hosts", O_RDWR | O_CREAT, 0744); - result = write(fd, "127.0.0.1 localhost\n", 41); + result = write(fd, "127.0.0.1 localhost\n", 41); result = write(fd, ip_address_string, strlen(ip_address_string)); - result = write(fd, " pjsip-test\n", 32); + result = write(fd, " pjsip-test\n", 32); result = close(fd); netdriver_config.ip_address = ip_address_string; @@ -310,12 +309,12 @@ initialize_network() rtems_bsdnet_config.gateway = gateway_string; if (0 != rtems_bsdnet_initialize_network()) - PJ_LOG(3,(THIS_FILE, "Error: Unable to initialize network stack!")); + PJ_LOG(3,(THIS_FILE, "Error: Unable to initialize network stack!")); else - PJ_LOG(3,(THIS_FILE, "IP addr=%s/%s, gw=%s", - ip_address_string, - netmask_string, - gateway_string)); + PJ_LOG(3,(THIS_FILE, "IP addr=%s/%s, gw=%s", + ip_address_string, + netmask_string, + gateway_string)); //rtems_rdbg_initialize(); //enterRdbg(); diff --git a/pjlib/src/pjlib-test/main_symbian.cpp b/pjlib/src/pjlib-test/main_symbian.cpp index a91b671f2c..f9a7c42a56 100644 --- a/pjlib/src/pjlib-test/main_symbian.cpp +++ b/pjlib/src/pjlib-test/main_symbian.cpp @@ -25,7 +25,7 @@ int main() //err = test_main(); if (err) - return err; + return err; return exp; //return 0; } @@ -129,5 +129,5 @@ GLDEF_C TInt E32Main() return KErrNone; } -#endif /* if 0 */ +#endif /* if 0 */ diff --git a/pjlib/src/pjlib-test/main_win32.c b/pjlib/src/pjlib-test/main_win32.c index fa79968f48..1a89f41a15 100644 --- a/pjlib/src/pjlib-test/main_win32.c +++ b/pjlib/src/pjlib-test/main_win32.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,23 +29,23 @@ #include #include -#define MAX_LOADSTRING 100 -#define THIS_FILE "main_win32.c" +#define MAX_LOADSTRING 100 +#define THIS_FILE "main_win32.c" -#define IDC_HELLO_WINCE 3 -#define ID_LOGWINDOW 104 +#define IDC_HELLO_WINCE 3 +#define ID_LOGWINDOW 104 -ATOM MyRegisterClass (HINSTANCE, LPTSTR); -BOOL InitInstance (HINSTANCE, int); -LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM); +ATOM MyRegisterClass (HINSTANCE, LPTSTR); +BOOL InitInstance (HINSTANCE, int); +LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM); -extern int param_log_decor; // in test.c +extern int param_log_decor; // in test.c -static HINSTANCE hInst; -static HWND hwndLog; -static HFONT hFixedFont; +static HINSTANCE hInst; +static HWND hwndLog; +static HFONT hFixedFont; static void write_log(int level, const char *data, int len) @@ -56,12 +55,12 @@ static void write_log(int level, const char *data, int len) PJ_UNUSED_ARG(level); PJ_UNUSED_ARG(len); SendMessage(hwndLog, EM_REPLACESEL, FALSE, - (LPARAM)PJ_STRING_TO_NATIVE(data,wdata,256)); + (LPARAM)PJ_STRING_TO_NATIVE(data,wdata,256)); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, int nCmdShow) + LPTSTR lpCmdLine, int nCmdShow) { MSG msg; @@ -70,7 +69,7 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, if (!InitInstance (hInstance, nCmdShow)) - return FALSE; + return FALSE; pj_log_set_log_func( &write_log ); param_log_decor = PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_CR; @@ -83,8 +82,8 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, // Message loop, waiting to quit. while (GetMessage(&msg, NULL, 0, 0)) { - TranslateMessage(&msg); - DispatchMessage(&msg); + TranslateMessage(&msg); + DispatchMessage(&msg); } DeleteObject(hFixedFont); @@ -102,19 +101,19 @@ int main() ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass) { - WNDCLASS wc; + WNDCLASS wc; - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.lpfnWndProc = (WNDPROC) WndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = hInstance; - ///wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_HELLO_WINCE)); - wc.hIcon = NULL; - wc.hCursor = 0; - wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); - wc.lpszMenuName = 0; - wc.lpszClassName = szWindowClass; + wc.style = CS_HREDRAW | CS_VREDRAW; + wc.lpfnWndProc = (WNDPROC) WndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = hInstance; + ///wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_HELLO_WINCE)); + wc.hIcon = NULL; + wc.hCursor = 0; + wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); + wc.lpszMenuName = 0; + wc.lpszClassName = szWindowClass; return RegisterClass(&wc); } @@ -122,10 +121,10 @@ ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass) BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { - HWND hWnd; - TCHAR *szTitle = _T("PJSIP Test"); - TCHAR *szWindowClass = _T("PJSIP_TEST"); - LOGFONT lf; + HWND hWnd; + TCHAR *szTitle = _T("PJSIP Test"); + TCHAR *szWindowClass = _T("PJSIP_TEST"); + LOGFONT lf; memset(&lf, 0, sizeof(lf)); @@ -138,25 +137,25 @@ BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) hFixedFont = CreateFontIndirect(&lf); if (!hFixedFont) - return FALSE; + return FALSE; hInst = hInstance; MyRegisterClass(hInstance, szWindowClass); hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, - CW_USEDEFAULT, NULL, NULL, hInstance, NULL); + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, + CW_USEDEFAULT, NULL, NULL, hInstance, NULL); if (!hWnd) - return FALSE; + return FALSE; ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); if (hwndLog) { - SendMessage(hwndLog, WM_SETFONT, (WPARAM) hFixedFont, (LPARAM) 0); - ShowWindow(hwndLog, TRUE); + SendMessage(hwndLog, WM_SETFONT, (WPARAM) hFixedFont, (LPARAM) 0); + ShowWindow(hwndLog, TRUE); } return TRUE; @@ -171,40 +170,40 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) switch (message) { case WM_CREATE: - // Create text control. - GetClientRect(hWnd, &rt); - dwStyle = WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL | - WS_BORDER | ES_LEFT | ES_MULTILINE | ES_NOHIDESEL | - ES_AUTOHSCROLL | ES_AUTOVSCROLL | ES_READONLY; - hwndLog = CreateWindow( TEXT("edit"), // class - NULL, // window text - dwStyle, // style - 0, // x-left - 0, // y-top - rt.right-rt.left, // w - rt.bottom-rt.top, // h - hWnd, // parent - (HMENU)ID_LOGWINDOW,// id - hInst, // instance - NULL); // NULL for control. - break; + // Create text control. + GetClientRect(hWnd, &rt); + dwStyle = WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL | + WS_BORDER | ES_LEFT | ES_MULTILINE | ES_NOHIDESEL | + ES_AUTOHSCROLL | ES_AUTOVSCROLL | ES_READONLY; + hwndLog = CreateWindow( TEXT("edit"), // class + NULL, // window text + dwStyle, // style + 0, // x-left + 0, // y-top + rt.right-rt.left, // w + rt.bottom-rt.top, // h + hWnd, // parent + (HMENU)ID_LOGWINDOW,// id + hInst, // instance + NULL); // NULL for control. + break; case WM_ACTIVATE: - if (LOWORD(wParam) == WA_INACTIVE) - DestroyWindow(hWnd); - break; + if (LOWORD(wParam) == WA_INACTIVE) + DestroyWindow(hWnd); + break; case WM_CHAR: - if (wParam == 27) { - DestroyWindow(hWnd); - } - break; + if (wParam == 27) { + DestroyWindow(hWnd); + } + break; case WM_CLOSE: - DestroyWindow(hWnd); - break; + DestroyWindow(hWnd); + break; case WM_DESTROY: - PostQuitMessage(0); - break; + PostQuitMessage(0); + break; default: - return DefWindowProc(hWnd, message, wParam, lParam); + return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } diff --git a/pjlib/src/pjlib-test/mutex.c b/pjlib/src/pjlib-test/mutex.c index e9905f3dad..e1d765220e 100644 --- a/pjlib/src/pjlib-test/mutex.c +++ b/pjlib/src/pjlib-test/mutex.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,22 +37,22 @@ static int simple_mutex_test(pj_pool_t *pool) TRACE_(("", "....create mutex")); rc = pj_mutex_create( pool, "", PJ_MUTEX_SIMPLE, &mutex); if (rc != PJ_SUCCESS) { - app_perror("...error: pj_mutex_create", rc); - return -10; + app_perror("...error: pj_mutex_create", rc); + return -10; } /* Normal lock/unlock cycle. */ TRACE_(("", "....lock mutex")); rc = pj_mutex_lock(mutex); if (rc != PJ_SUCCESS) { - app_perror("...error: pj_mutex_lock", rc); - return -20; + app_perror("...error: pj_mutex_lock", rc); + return -20; } TRACE_(("", "....unlock mutex")); rc = pj_mutex_unlock(mutex); if (rc != PJ_SUCCESS) { - app_perror("...error: pj_mutex_unlock", rc); - return -30; + app_perror("...error: pj_mutex_unlock", rc); + return -30; } /* Lock again. */ @@ -65,7 +64,7 @@ static int simple_mutex_test(pj_pool_t *pool) TRACE_(("", "....trylock mutex")); rc = pj_mutex_trylock(mutex); if (rc == PJ_SUCCESS) - PJ_LOG(3,("", "...info: looks like simple mutex is recursive")); + PJ_LOG(3,("", "...info: looks like simple mutex is recursive")); /* Unlock and done. */ TRACE_(("", "....unlock mutex")); @@ -93,22 +92,22 @@ static int recursive_mutex_test(pj_pool_t *pool) TRACE_(("", "....create mutex")); rc = pj_mutex_create( pool, "", PJ_MUTEX_RECURSE, &mutex); if (rc != PJ_SUCCESS) { - app_perror("...error: pj_mutex_create", rc); - return -10; + app_perror("...error: pj_mutex_create", rc); + return -10; } /* Normal lock/unlock cycle. */ TRACE_(("", "....lock mutex")); rc = pj_mutex_lock(mutex); if (rc != PJ_SUCCESS) { - app_perror("...error: pj_mutex_lock", rc); - return -20; + app_perror("...error: pj_mutex_lock", rc); + return -20; } TRACE_(("", "....unlock mutex")); rc = pj_mutex_unlock(mutex); if (rc != PJ_SUCCESS) { - app_perror("...error: pj_mutex_unlock", rc); - return -30; + app_perror("...error: pj_mutex_unlock", rc); + return -30; } /* Lock again. */ @@ -120,16 +119,16 @@ static int recursive_mutex_test(pj_pool_t *pool) TRACE_(("", "....trylock mutex")); rc = pj_mutex_trylock(mutex); if (rc != PJ_SUCCESS) { - app_perror("...error: recursive mutex is not recursive!", rc); - return -40; + app_perror("...error: recursive mutex is not recursive!", rc); + return -40; } /* Locking again should not fail. */ TRACE_(("", "....lock mutex")); rc = pj_mutex_lock(mutex); if (rc != PJ_SUCCESS) { - app_perror("...error: recursive mutex is not recursive!", rc); - return -45; + app_perror("...error: recursive mutex is not recursive!", rc); + return -45; } /* Unlock several times and done. */ @@ -159,47 +158,47 @@ static int semaphore_test(pj_pool_t *pool) status = pj_sem_create(pool, NULL, 0, 1, &sem); if (status != PJ_SUCCESS) { - app_perror("...error: pj_sem_create()", status); - return -151; + app_perror("...error: pj_sem_create()", status); + return -151; } status = pj_sem_post(sem); if (status != PJ_SUCCESS) { - app_perror("...error: pj_sem_post()", status); - pj_sem_destroy(sem); - return -153; + app_perror("...error: pj_sem_post()", status); + pj_sem_destroy(sem); + return -153; } status = pj_sem_trywait(sem); if (status != PJ_SUCCESS) { - app_perror("...error: pj_sem_trywait()", status); - pj_sem_destroy(sem); - return -156; + app_perror("...error: pj_sem_trywait()", status); + pj_sem_destroy(sem); + return -156; } status = pj_sem_post(sem); if (status != PJ_SUCCESS) { - app_perror("...error: pj_sem_post()", status); - pj_sem_destroy(sem); - return -159; + app_perror("...error: pj_sem_post()", status); + pj_sem_destroy(sem); + return -159; } status = pj_sem_wait(sem); if (status != PJ_SUCCESS) { - app_perror("...error: pj_sem_wait()", status); - pj_sem_destroy(sem); - return -161; + app_perror("...error: pj_sem_wait()", status); + pj_sem_destroy(sem); + return -161; } status = pj_sem_destroy(sem); if (status != PJ_SUCCESS) { - app_perror("...error: pj_sem_destroy()", status); - return -163; + app_perror("...error: pj_sem_destroy()", status); + return -163; } return 0; } -#endif /* PJ_HAS_SEMAPHORE */ +#endif /* PJ_HAS_SEMAPHORE */ int mutex_test(void) @@ -211,16 +210,16 @@ int mutex_test(void) rc = simple_mutex_test(pool); if (rc != 0) - return rc; + return rc; rc = recursive_mutex_test(pool); if (rc != 0) - return rc; + return rc; #if PJ_HAS_SEMAPHORE rc = semaphore_test(pool); if (rc != 0) - return rc; + return rc; #endif pj_pool_release(pool); diff --git a/pjlib/src/pjlib-test/os.c b/pjlib/src/pjlib-test/os.c index d5b1879c06..3bc1de8ebb 100644 --- a/pjlib/src/pjlib-test/os.c +++ b/pjlib/src/pjlib-test/os.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -26,9 +25,9 @@ static int endianness_test32(void) { union t { - pj_uint32_t u32; - pj_uint16_t u16[2]; - pj_uint8_t u8[4]; + pj_uint32_t u32; + pj_uint16_t u16[2]; + pj_uint8_t u8[4]; } t; PJ_LOG(3,("", " Testing endianness..")); @@ -43,40 +42,40 @@ static int endianness_test32(void) # endif if ((t.u16[0] & 0xFFFF) != 0x3344 || - (t.u16[1] & 0xFFFF) != 0x1122) + (t.u16[1] & 0xFFFF) != 0x1122) { - PJ_LOG(3,("", " Error: wrong 16bit values 0x%x and 0x%x", - (t.u16[0] & 0xFFFF), (t.u16[1] & 0xFFFF))); - return 10; + PJ_LOG(3,("", " Error: wrong 16bit values 0x%x and 0x%x", + (t.u16[0] & 0xFFFF), (t.u16[1] & 0xFFFF))); + return 10; } if ((t.u8[0] & 0xFF) != 0x44 || - (t.u8[1] & 0xFF) != 0x33 || - (t.u8[2] & 0xFF) != 0x22 || - (t.u8[3] & 0xFF) != 0x11) + (t.u8[1] & 0xFF) != 0x33 || + (t.u8[2] & 0xFF) != 0x22 || + (t.u8[3] & 0xFF) != 0x11) { - PJ_LOG(3,("", " Error: wrong 8bit values")); - return 12; + PJ_LOG(3,("", " Error: wrong 8bit values")); + return 12; } #elif defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN PJ_LOG(3,("", " Library is set to big endian")); if ((t.u16[0] & 0xFFFF) != 0x1122 || - (t.u16[1] & 0xFFFF) != 0x3344) + (t.u16[1] & 0xFFFF) != 0x3344) { - PJ_LOG(3,("", " Error: wrong 16bit values 0x%x and 0x%x", - (t.u16[0] & 0xFFFF), (t.u16[1] & 0xFFFF))); - return 20; + PJ_LOG(3,("", " Error: wrong 16bit values 0x%x and 0x%x", + (t.u16[0] & 0xFFFF), (t.u16[1] & 0xFFFF))); + return 20; } if ((t.u8[0] & 0xFF) != 0x11 || - (t.u8[1] & 0xFF) != 0x22 || - (t.u8[2] & 0xFF) != 0x33 || - (t.u8[3] & 0xFF) != 0x44) + (t.u8[1] & 0xFF) != 0x22 || + (t.u8[2] & 0xFF) != 0x33 || + (t.u8[3] & 0xFF) != 0x44) { - PJ_LOG(3,("", " Error: wrong 8bit values")); - return 22; + PJ_LOG(3,("", " Error: wrong 8bit values")); + return 22; } # if defined(PJ_IS_LITTLE_ENDIAN) && PJ_IS_LITTLE_ENDIAN diff --git a/pjlib/src/pjlib-test/pool.c b/pjlib/src/pjlib-test/pool.c index 581ccc69dc..4375cc6956 100644 --- a/pjlib/src/pjlib-test/pool.c +++ b/pjlib/src/pjlib-test/pool.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,7 +38,7 @@ #if INCLUDE_POOL_TEST -#define SIZE 4096 +#define SIZE 4096 /* Normally we should throw exception when memory alloc fails. * Here we do nothing so that the flow will go back to original caller, @@ -52,7 +51,7 @@ static void null_callback(pj_pool_t *pool, pj_size_t size) PJ_UNUSED_ARG(size); } -#define GET_FREE(p) (pj_pool_get_capacity(p)-pj_pool_get_used_size(p)) +#define GET_FREE(p) (pj_pool_get_capacity(p)-pj_pool_get_used_size(p)) /* Test that the capacity and used size reported by the pool is correct. */ @@ -64,15 +63,15 @@ static int capacity_test(void) PJ_LOG(3,("test", "...capacity_test()")); if (!pool) - return -200; + return -200; freesize = GET_FREE(pool); if (pj_pool_alloc(pool, freesize) == NULL) { - PJ_LOG(3,("test", "...error: wrong freesize %u reported", - freesize)); - pj_pool_release(pool); - return -210; + PJ_LOG(3,("test", "...error: wrong freesize %u reported", + freesize)); + pj_pool_release(pool); + return -210; } pj_pool_release(pool); @@ -91,35 +90,35 @@ static int pool_alignment_test(void) pool = pj_pool_create(mem, NULL, PJ_POOL_SIZE+MEMSIZE, MEMSIZE, NULL); if (!pool) - return -300; + return -300; -#define IS_ALIGNED(p) ((((unsigned long)(pj_ssize_t)p) & \ - (PJ_POOL_ALIGNMENT-1)) == 0) +#define IS_ALIGNED(p) ((((unsigned long)(pj_ssize_t)p) & \ + (PJ_POOL_ALIGNMENT-1)) == 0) for (i=0; i 0) { - int size2; + int size2; - if (freesize > 255) - size2 = ((pj_rand() & 0x000000FF) + PJ_POOL_ALIGNMENT) & - ~(PJ_POOL_ALIGNMENT - 1); - else - size2 = (int)freesize; + if (freesize > 255) + size2 = ((pj_rand() & 0x000000FF) + PJ_POOL_ALIGNMENT) & + ~(PJ_POOL_ALIGNMENT - 1); + else + size2 = (int)freesize; - p = pj_pool_alloc(pool, size2); - if (!p) { - status=-20; goto on_error; - } + p = pj_pool_alloc(pool, size2); + if (!p) { + status=-20; goto on_error; + } - freesize -= size2; + freesize -= size2; } /* Check that capacity is zero. */ if (GET_FREE(pool) != 0) { - PJ_LOG(3,("test", "....error: returned free=%u (expecting 0)", - GET_FREE(pool))); - status=-30; goto on_error; + PJ_LOG(3,("test", "....error: returned free=%u (expecting 0)", + GET_FREE(pool))); + status=-30; goto on_error; } /* Try to allocate once more */ p = pj_pool_alloc(pool, 257); if (!p) { - status=-40; goto on_error; + status=-40; goto on_error; } /* Check that capacity is NOT zero. */ if (GET_FREE(pool) == 0) { - status=-50; goto on_error; + status=-50; goto on_error; } @@ -236,7 +235,7 @@ static int pool_buf_test(void) enum { STATIC_BUF_SIZE = 40 }; /* 16 is the internal struct in pool_buf */ static char buf[ STATIC_BUF_SIZE + sizeof(pj_pool_t) + - sizeof(pj_pool_block) + 2 * PJ_POOL_ALIGNMENT]; + sizeof(pj_pool_block) + 2 * PJ_POOL_ALIGNMENT]; pj_pool_t *pool; void *p; PJ_USE_EXCEPTION; @@ -245,31 +244,31 @@ static int pool_buf_test(void) pool = pj_pool_create_on_buf("no name", buf, sizeof(buf)); if (!pool) - return -70; + return -70; /* Drain the pool */ PJ_TRY { - if ((p=pj_pool_alloc(pool, STATIC_BUF_SIZE/2)) == NULL) - return -75; + if ((p=pj_pool_alloc(pool, STATIC_BUF_SIZE/2)) == NULL) + return -75; - if ((p=pj_pool_alloc(pool, STATIC_BUF_SIZE/2)) == NULL) - return -76; + if ((p=pj_pool_alloc(pool, STATIC_BUF_SIZE/2)) == NULL) + return -76; } PJ_CATCH_ANY { - return -77; + return -77; } PJ_END; /* On the next alloc, exception should be thrown */ PJ_TRY { - p = pj_pool_alloc(pool, STATIC_BUF_SIZE); - if (p != NULL) { - /* This is unexpected, the alloc should fail */ - return -78; - } + p = pj_pool_alloc(pool, STATIC_BUF_SIZE); + if (p != NULL) { + /* This is unexpected, the alloc should fail */ + return -78; + } } PJ_CATCH_ANY { - /* This is the expected result */ + /* This is the expected result */ } PJ_END; @@ -294,20 +293,20 @@ int pool_test(void) if (rc) return rc; for (loop=0; loop @@ -30,10 +29,10 @@ #define THIS_FILE "test" -#define LOOP 10 -#define COUNT 1024 -static unsigned sizes[COUNT]; -static char *p[COUNT]; +#define LOOP 10 +#define COUNT 1024 +static unsigned sizes[COUNT]; +static char *p[COUNT]; #define MIN_SIZE 4 #define MAX_SIZE 512 static unsigned total_size; @@ -44,17 +43,17 @@ static int pool_test_pool() int i; pj_pool_t *pool = pj_pool_create(mem, NULL, total_size + 4*COUNT, 0, NULL); if (!pool) - return -1; + return -1; for (i=0; i= 0) { - delete [] p[i]; - --i; - } - return -1; - } - *p[i] = '\0'; + p[i] = new char[sizes[i]]; + if (!p[i]) { + PJ_LOG(3,(THIS_FILE," error: malloc failed to allocate %d bytes", + sizes[i])); + --i; + while (i >= 0) { + delete [] p[i]; + --i; + } + return -1; + } + *p[i] = '\0'; } for (i=0; i= 0) - free(p[i]), --i; - return -1; - } - *p[i] = '\0'; + p[i] = (char*)malloc(sizes[i]); + if (!p[i]) { + PJ_LOG(3,(THIS_FILE," error: malloc failed to allocate %d bytes", + sizes[i])); + --i; + while (i >= 0) + free(p[i]), --i; + return -1; + } + *p[i] = '\0'; } for (i=0; i @@ -35,20 +34,20 @@ int rand_test(void) int i; for (i=0; i @@ -23,10 +22,10 @@ #include -#define LOOP 32 +#define LOOP 32 #define MIN_COUNT 64 #define MAX_COUNT (LOOP * MIN_COUNT) -#define STRSIZE 16 +#define STRSIZE 16 #define THIS_FILE "rbtree_test" typedef struct node_key @@ -38,9 +37,9 @@ typedef struct node_key static int compare_node(const node_key *k1, const node_key *k2) { if (k1->hash == k2->hash) { - return strcmp(k1->str, k2->str); + return strcmp(k1->str, k2->str); } else { - return k1->hash < k2->hash ? -1 : 1; + return k1->hash < k2->hash ? -1 : 1; } } @@ -48,7 +47,7 @@ void randomize_string(char *str, int len) { int i; for (i=0; ikey,(node_key*)it->key)>=0) { - ++err; - PJ_LOG(3, (THIS_FILE, "Error: %s >= %s", - (char*)prev->user_data, (char*)it->user_data)); - } - } - prev = it; - it = pj_rbtree_next(&rb, it); - } - - // Search. - for (j=0; j MAX_COUNT) - break; + int j; + pj_rbtree_node *prev, *it; + pj_timestamp t1, t2, t_setup, t_insert, t_search, t_erase; + + pj_assert(rb.size == 0); + + t_setup.u32.lo = t_insert.u32.lo = t_search.u32.lo = t_erase.u32.lo = 0; + + for (j=0; jkey,(node_key*)it->key)>=0) { + ++err; + PJ_LOG(3, (THIS_FILE, "Error: %s >= %s", + (char*)prev->user_data, (char*)it->user_data)); + } + } + prev = it; + it = pj_rbtree_next(&rb, it); + } + + // Search. + for (j=0; j MAX_COUNT) + break; } pj_pool_release(pool); @@ -163,6 +162,6 @@ int rbtree_test() return test(); } -#endif /* INCLUDE_RBTREE_TEST */ +#endif /* INCLUDE_RBTREE_TEST */ diff --git a/pjlib/src/pjlib-test/rtems_network_config.h b/pjlib/src/pjlib-test/rtems_network_config.h index 48f354d905..10335935e3 100644 --- a/pjlib/src/pjlib-test/rtems_network_config.h +++ b/pjlib/src/pjlib-test/rtems_network_config.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -81,11 +80,11 @@ static char ethernet_address[6] = { 0x00, 0x80, 0x7F, 0x22, 0x61, 0x77 }; */ extern int rtems_bsdnet_loopattach(struct rtems_bsdnet_ifconfig* dummy, int unused); static struct rtems_bsdnet_ifconfig loopback_config = { - "lo0", /* name */ - rtems_bsdnet_loopattach, /* attach function */ - NULL, /* link to next interface */ - "127.0.0.1", /* IP address */ - "255.0.0.0", /* IP net mask */ + "lo0", /* name */ + rtems_bsdnet_loopattach, /* attach function */ + NULL, /* link to next interface */ + "127.0.0.1", /* IP address */ + "255.0.0.0", /* IP net mask */ }; #endif @@ -93,57 +92,57 @@ static struct rtems_bsdnet_ifconfig loopback_config = { * Default network interface */ static struct rtems_bsdnet_ifconfig netdriver_config = { - RTEMS_BSP_NETWORK_DRIVER_NAME, /* name */ - RTEMS_BSP_NETWORK_DRIVER_ATTACH, /* attach function */ + RTEMS_BSP_NETWORK_DRIVER_NAME, /* name */ + RTEMS_BSP_NETWORK_DRIVER_ATTACH, /* attach function */ #ifdef RTEMS_USE_LOOPBACK - &loopback_config, /* link to next interface */ + &loopback_config, /* link to next interface */ #else - NULL, /* No more interfaces */ + NULL, /* No more interfaces */ #endif #if (defined (RTEMS_USE_BOOTP)) - NULL, /* BOOTP supplies IP address */ - NULL, /* BOOTP supplies IP net mask */ + NULL, /* BOOTP supplies IP address */ + NULL, /* BOOTP supplies IP net mask */ #else - "192.168.0.33", /* IP address */ - "255.255.255.0", /* IP net mask */ + "192.168.0.33", /* IP address */ + "255.255.255.0", /* IP net mask */ #endif /* !RTEMS_USE_BOOTP */ #if (defined (RTEMS_SET_ETHERNET_ADDRESS)) - ethernet_address, /* Ethernet hardware address */ + ethernet_address, /* Ethernet hardware address */ #else - NULL, /* Driver supplies hardware address */ + NULL, /* Driver supplies hardware address */ #endif - 0 /* Use default driver parameters */ + 0 /* Use default driver parameters */ }; /* * Network configuration */ struct rtems_bsdnet_config rtems_bsdnet_config = { - &netdriver_config, + &netdriver_config, #if (defined (RTEMS_USE_BOOTP)) - rtems_bsdnet_do_bootp, + rtems_bsdnet_do_bootp, #else - NULL, + NULL, #endif - NETWORK_STACK_PRIORITY, /* Default network task priority */ - 1048576, /* Default mbuf capacity */ - 1048576, /* Default mbuf cluster capacity */ + NETWORK_STACK_PRIORITY, /* Default network task priority */ + 1048576, /* Default mbuf capacity */ + 1048576, /* Default mbuf cluster capacity */ #if (!defined (RTEMS_USE_BOOTP)) - "testnode", /* Host name */ - "example.org", /* Domain name */ - "192.168.6.9", /* Gateway */ - "192.168.7.41", /* Log host */ - {"198.137.231.1" }, /* Name server(s) */ - {"207.202.190.162" }, /* NTP server(s) */ + "testnode", /* Host name */ + "example.org", /* Domain name */ + "192.168.6.9", /* Gateway */ + "192.168.7.41", /* Log host */ + {"198.137.231.1" }, /* Name server(s) */ + {"207.202.190.162" }, /* NTP server(s) */ #endif /* !RTEMS_USE_BOOTP */ }; -#endif /* _RTEMS_NETWORKCONFIG_H_ */ +#endif /* _RTEMS_NETWORKCONFIG_H_ */ diff --git a/pjlib/src/pjlib-test/select.c b/pjlib/src/pjlib-test/select.c index 74f375690f..2aa1850326 100644 --- a/pjlib/src/pjlib-test/select.c +++ b/pjlib/src/pjlib-test/select.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -59,7 +58,7 @@ enum * are signalled. */ static int do_select( pj_sock_t sock1, pj_sock_t sock2, - int setcount[]) + int setcount[]) { pj_fd_set_t fds[3]; pj_time_val timeout; @@ -76,7 +75,7 @@ static int do_select( pj_sock_t sock1, pj_sock_t sock2, timeout.msec = 0; n = pj_sock_select(PJ_IOQUEUE_MAX_HANDLES, &fds[0], &fds[1], &fds[2], - &timeout); + &timeout); if (n < 0) return n; if (n == 0) @@ -86,7 +85,7 @@ static int do_select( pj_sock_t sock1, pj_sock_t sock2, if (PJ_FD_ISSET(sock1, &fds[i])) setcount[i]++; if (PJ_FD_ISSET(sock2, &fds[i])) - setcount[i]++; + setcount[i]++; } return n; @@ -116,12 +115,12 @@ int select_test() rc = pj_sock_socket( pj_AF_INET(), pj_SOCK_DGRAM(), 0, &udp1); if (rc != PJ_SUCCESS) { app_perror("...error: unable to create socket", rc); - status=-10; goto on_return; + status=-10; goto on_return; } rc = pj_sock_socket( pj_AF_INET(), pj_SOCK_DGRAM(), 0, &udp2); if (udp2 == PJ_INVALID_SOCKET) { app_perror("...error: unable to create socket", rc); - status=-20; goto on_return; + status=-20; goto on_return; } // Bind one of the UDP socket. @@ -131,7 +130,7 @@ int select_test() udp_addr.sin_addr = pj_inet_addr(pj_cstr(&s, "127.0.0.1")); if (pj_sock_bind(udp2, &udp_addr, sizeof(udp_addr))) { - status=-30; goto on_return; + status=-30; goto on_return; } // Send data. @@ -139,7 +138,7 @@ int select_test() rc = pj_sock_sendto(udp1, data, &sent, 0, &udp_addr, sizeof(udp_addr)); if (rc != PJ_SUCCESS || sent != datalen) { app_perror("...error: sendto() error", rc); - status=-40; goto on_return; + status=-40; goto on_return; } // Sleep a bit. See https://github.com/pjsip/pjproject/issues/890 @@ -149,37 +148,37 @@ int select_test() // Note that select() may also report that sockets are writable. status = do_select(udp1, udp2, setcount); if (status < 0) { - char errbuf[128]; + char errbuf[128]; pj_strerror(pj_get_netos_error(), errbuf, sizeof(errbuf)); - PJ_LOG(1,(THIS_FILE, "...error: %s", errbuf)); - status=-50; goto on_return; + PJ_LOG(1,(THIS_FILE, "...error: %s", errbuf)); + status=-50; goto on_return; } if (status == 0) { - status=-60; goto on_return; + status=-60; goto on_return; } if (setcount[READ_FDS] != 1) { - status=-70; goto on_return; + status=-70; goto on_return; } if (setcount[WRITE_FDS] != 0) { - if (setcount[WRITE_FDS] == 2) { - PJ_LOG(3,(THIS_FILE, "...info: system reports writable sockets")); - } else { - status=-80; goto on_return; - } + if (setcount[WRITE_FDS] == 2) { + PJ_LOG(3,(THIS_FILE, "...info: system reports writable sockets")); + } else { + status=-80; goto on_return; + } } else { - PJ_LOG(3,(THIS_FILE, - "...info: system doesn't report writable sockets")); + PJ_LOG(3,(THIS_FILE, + "...info: system doesn't report writable sockets")); } if (setcount[EXCEPT_FDS] != 0) { - status=-90; goto on_return; + status=-90; goto on_return; } // Read the socket to clear readable sockets. received = sizeof(buf); rc = pj_sock_recv(udp2, buf, &received, 0); if (rc != PJ_SUCCESS || received != 5) { - status=-100; goto on_return; + status=-100; goto on_return; } status = 0; @@ -190,24 +189,24 @@ int select_test() setcount[0] = setcount[1] = setcount[2] = 0; status = do_select(udp1, udp2, setcount); if (status != 0 && status != setcount[WRITE_FDS]) { - PJ_LOG(3,(THIS_FILE, "...error: expecting timeout but got %d sks set", - status)); - PJ_LOG(3,(THIS_FILE, " rdset: %d, wrset: %d, exset: %d", - setcount[0], setcount[1], setcount[2])); - status = -110; goto on_return; + PJ_LOG(3,(THIS_FILE, "...error: expecting timeout but got %d sks set", + status)); + PJ_LOG(3,(THIS_FILE, " rdset: %d, wrset: %d, exset: %d", + setcount[0], setcount[1], setcount[2])); + status = -110; goto on_return; } if (setcount[READ_FDS] != 0) { - PJ_LOG(3,(THIS_FILE, "...error: readable socket not expected")); - status = -120; goto on_return; + PJ_LOG(3,(THIS_FILE, "...error: readable socket not expected")); + status = -120; goto on_return; } status = 0; on_return: if (udp1 != PJ_INVALID_SOCKET) - pj_sock_close(udp1); + pj_sock_close(udp1); if (udp2 != PJ_INVALID_SOCKET) - pj_sock_close(udp2); + pj_sock_close(udp2); return status; } @@ -216,6 +215,6 @@ int select_test() * when this test is disabled. */ int dummy_select_test; -#endif /* INCLUDE_SELECT_TEST */ +#endif /* INCLUDE_SELECT_TEST */ diff --git a/pjlib/src/pjlib-test/sleep.c b/pjlib/src/pjlib-test/sleep.c index 72dfba7bbd..e42a119460 100644 --- a/pjlib/src/pjlib-test/sleep.c +++ b/pjlib/src/pjlib-test/sleep.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -62,27 +61,27 @@ static int simple_sleep_test(void) PJ_LOG(3,(THIS_FILE, "..will write messages every 1 second:")); for (i=0; i duration[i] * (100+MIS)/100) - { - PJ_LOG(3,(THIS_FILE, - "...error: slept for %d ms instead of %d ms " - "(outside %d%% err window)", - msec, duration[i], MIS)); - return -30; - } + /* Convert to msec. */ + msec = PJ_TIME_VAL_MSEC(stop); + + /* Check if it's within range. */ + if (msec < duration[i] * (100-MIS)/100 || + msec > duration[i] * (100+MIS)/100) + { + PJ_LOG(3,(THIS_FILE, + "...error: slept for %d ms instead of %d ms " + "(outside %d%% err window)", + msec, duration[i], MIS)); + return -30; + } } /* Test pj_thread_sleep() and pj_get_timestamp() and friends */ for (i=0; i duration[i] * (100+MIS)/100) - { - PJ_LOG(3,(THIS_FILE, - "...error: slept for %d ms instead of %d ms " - "(outside %d%% err window)", - msec, duration[i], MIS)); - PJ_TIME_VAL_SUB(t2, t1); - PJ_LOG(3,(THIS_FILE, - "...info: gettimeofday() reported duration is " - "%d msec", - PJ_TIME_VAL_MSEC(t2))); - - return -76; - } + /* Check if it's within range. */ + if (msec < duration[i] * (100-MIS)/100 || + msec > duration[i] * (100+MIS)/100) + { + PJ_LOG(3,(THIS_FILE, + "...error: slept for %d ms instead of %d ms " + "(outside %d%% err window)", + msec, duration[i], MIS)); + PJ_TIME_VAL_SUB(t2, t1); + PJ_LOG(3,(THIS_FILE, + "...info: gettimeofday() reported duration is " + "%d msec", + PJ_TIME_VAL_MSEC(t2))); + + return -76; + } } /* All done. */ @@ -207,11 +206,11 @@ int sleep_test() rc = simple_sleep_test(); if (rc != PJ_SUCCESS) - return rc; + return rc; rc = sleep_duration_test(); if (rc != PJ_SUCCESS) - return rc; + return rc; return 0; } diff --git a/pjlib/src/pjlib-test/sock.c b/pjlib/src/pjlib-test/sock.c index 9502fba53f..5ccfa81777 100644 --- a/pjlib/src/pjlib-test/sock.c +++ b/pjlib/src/pjlib-test/sock.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -64,10 +63,10 @@ #if INCLUDE_SOCK_TEST -#define UDP_PORT 51234 +#define UDP_PORT 51234 #define TCP_PORT (UDP_PORT+10) -#define BIG_DATA_LEN 8192 -#define ADDRESS "127.0.0.1" +#define BIG_DATA_LEN 8192 +#define ADDRESS "127.0.0.1" static char bigdata[BIG_DATA_LEN]; static char bigbuffer[BIG_DATA_LEN]; @@ -77,8 +76,8 @@ static char bigbuffer[BIG_DATA_LEN]; */ #if defined(PJ_SOCKADDR_HAS_LEN) && PJ_SOCKADDR_HAS_LEN!=0 # define CHECK_SA_ZERO_LEN(addr, ret) \ - if (((pj_addr_hdr*)(addr))->sa_zero_len != 0) \ - return ret + if (((pj_addr_hdr*)(addr))->sa_zero_len != 0) \ + return ret #else # define CHECK_SA_ZERO_LEN(addr, ret) #endif @@ -98,68 +97,68 @@ static int format_test(void) /* pj_inet_aton() */ if (pj_inet_aton(&s, &addr) != 1) - return -10; + return -10; /* Check the result. */ p = (unsigned char*)&addr; if (p[0]!=A[0] || p[1]!=A[1] || p[2]!=A[2] || p[3]!=A[3]) { - PJ_LOG(3,("test", " error: mismatched address. p0=%d, p1=%d, " - "p2=%d, p3=%d", p[0] & 0xFF, p[1] & 0xFF, - p[2] & 0xFF, p[3] & 0xFF)); - return -15; + PJ_LOG(3,("test", " error: mismatched address. p0=%d, p1=%d, " + "p2=%d, p3=%d", p[0] & 0xFF, p[1] & 0xFF, + p[2] & 0xFF, p[3] & 0xFF)); + return -15; } /* pj_inet_ntoa() */ p = (unsigned char*) pj_inet_ntoa(addr); if (!p) - return -20; + return -20; if (pj_strcmp2(&s, (char*)p) != 0) - return -22; + return -22; #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6!=0 /* pj_inet_pton() */ /* pj_inet_ntop() */ { - const pj_str_t s_ipv4 = pj_str("127.0.0.1"); - const pj_str_t s_ipv6 = pj_str("fe80::2ff:83ff:fe7c:8b42"); - char buf_ipv4[PJ_INET_ADDRSTRLEN]; - char buf_ipv6[PJ_INET6_ADDRSTRLEN]; - pj_in_addr ipv4; - pj_in6_addr ipv6; - - if (pj_inet_pton(pj_AF_INET(), &s_ipv4, &ipv4) != PJ_SUCCESS) - return -24; - - p = (unsigned char*)&ipv4; - if (p[0]!=A[0] || p[1]!=A[1] || p[2]!=A[2] || p[3]!=A[3]) { - return -25; - } - - if (pj_inet_pton(pj_AF_INET6(), &s_ipv6, &ipv6) != PJ_SUCCESS) - return -26; - - p = (unsigned char*)&ipv6; - if (p[0] != 0xfe || p[1] != 0x80 || p[2] != 0 || p[3] != 0 || - p[4] != 0 || p[5] != 0 || p[6] != 0 || p[7] != 0 || - p[8] != 0x02 || p[9] != 0xff || p[10] != 0x83 || p[11] != 0xff || - p[12]!=0xfe || p[13]!=0x7c || p[14] != 0x8b || p[15]!=0x42) - { - return -27; - } - - if (pj_inet_ntop(pj_AF_INET(), &ipv4, buf_ipv4, sizeof(buf_ipv4)) != PJ_SUCCESS) - return -28; - if (pj_stricmp2(&s_ipv4, buf_ipv4) != 0) - return -29; - - if (pj_inet_ntop(pj_AF_INET6(), &ipv6, buf_ipv6, sizeof(buf_ipv6)) != PJ_SUCCESS) - return -30; - if (pj_stricmp2(&s_ipv6, buf_ipv6) != 0) - return -31; + const pj_str_t s_ipv4 = pj_str("127.0.0.1"); + const pj_str_t s_ipv6 = pj_str("fe80::2ff:83ff:fe7c:8b42"); + char buf_ipv4[PJ_INET_ADDRSTRLEN]; + char buf_ipv6[PJ_INET6_ADDRSTRLEN]; + pj_in_addr ipv4; + pj_in6_addr ipv6; + + if (pj_inet_pton(pj_AF_INET(), &s_ipv4, &ipv4) != PJ_SUCCESS) + return -24; + + p = (unsigned char*)&ipv4; + if (p[0]!=A[0] || p[1]!=A[1] || p[2]!=A[2] || p[3]!=A[3]) { + return -25; + } + + if (pj_inet_pton(pj_AF_INET6(), &s_ipv6, &ipv6) != PJ_SUCCESS) + return -26; + + p = (unsigned char*)&ipv6; + if (p[0] != 0xfe || p[1] != 0x80 || p[2] != 0 || p[3] != 0 || + p[4] != 0 || p[5] != 0 || p[6] != 0 || p[7] != 0 || + p[8] != 0x02 || p[9] != 0xff || p[10] != 0x83 || p[11] != 0xff || + p[12]!=0xfe || p[13]!=0x7c || p[14] != 0x8b || p[15]!=0x42) + { + return -27; + } + + if (pj_inet_ntop(pj_AF_INET(), &ipv4, buf_ipv4, sizeof(buf_ipv4)) != PJ_SUCCESS) + return -28; + if (pj_stricmp2(&s_ipv4, buf_ipv4) != 0) + return -29; + + if (pj_inet_ntop(pj_AF_INET6(), &ipv6, buf_ipv6, sizeof(buf_ipv6)) != PJ_SUCCESS) + return -30; + if (pj_stricmp2(&s_ipv6, buf_ipv6) != 0) + return -31; } -#endif /* PJ_HAS_IPV6 */ +#endif /* PJ_HAS_IPV6 */ /* Test that pj_sockaddr_in_init() initialize the whole structure, * including sin_zero_pad. @@ -167,15 +166,15 @@ static int format_test(void) pj_sockaddr_in_init(&addr2, 0, 1000); pj_bzero(zero, sizeof(zero)); if (pj_memcmp(addr2.sin_zero_pad, zero, sizeof(addr2.sin_zero_pad)) != 0) - return -35; + return -35; /* pj_gethostname() */ hostname = pj_gethostname(); if (!hostname || !hostname->ptr || !hostname->slen) - return -40; + return -40; PJ_LOG(3,("test", "....hostname is %.*s", - (int)hostname->slen, hostname->ptr)); + (int)hostname->slen, hostname->ptr)); /* pj_gethostaddr() */ @@ -207,63 +206,63 @@ static int format_test(void) static int parse_test(void) { -#define IPv4 1 -#define IPv6 2 +#define IPv4 1 +#define IPv6 2 struct test_t { - const char *input; - int result_af; - const char *result_ip; - pj_uint16_t result_port; + const char *input; + int result_af; + const char *result_ip; + pj_uint16_t result_port; }; struct test_t valid_tests[] = { - /* IPv4 */ - { "10.0.0.1:80", IPv4, "10.0.0.1", 80}, - { "10.0.0.1", IPv4, "10.0.0.1", 0}, - { "10.0.0.1:", IPv4, "10.0.0.1", 0}, - { "10.0.0.1:0", IPv4, "10.0.0.1", 0}, - { ":80", IPv4, "0.0.0.0", 80}, - { ":", IPv4, "0.0.0.0", 0}, + /* IPv4 */ + { "10.0.0.1:80", IPv4, "10.0.0.1", 80}, + { "10.0.0.1", IPv4, "10.0.0.1", 0}, + { "10.0.0.1:", IPv4, "10.0.0.1", 0}, + { "10.0.0.1:0", IPv4, "10.0.0.1", 0}, + { ":80", IPv4, "0.0.0.0", 80}, + { ":", IPv4, "0.0.0.0", 0}, #if !PJ_SYMBIAN - { "localhost", IPv4, "127.0.0.1", 0}, - { "localhost:", IPv4, "127.0.0.1", 0}, - { "localhost:80", IPv4, "127.0.0.1", 80}, + { "localhost", IPv4, "127.0.0.1", 0}, + { "localhost:", IPv4, "127.0.0.1", 0}, + { "localhost:80", IPv4, "127.0.0.1", 80}, #endif #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6 - { "fe::01:80", IPv6, "fe::01:80", 0}, - { "[fe::01]:80", IPv6, "fe::01", 80}, - { "fe::01", IPv6, "fe::01", 0}, - { "[fe::01]", IPv6, "fe::01", 0}, - { "fe::01:", IPv6, "fe::01", 0}, - { "[fe::01]:", IPv6, "fe::01", 0}, - { "::", IPv6, "::0", 0}, - { "[::]", IPv6, "::", 0}, - { ":::", IPv6, "::", 0}, - { "[::]:", IPv6, "::", 0}, - { ":::80", IPv6, "::", 80}, - { "[::]:80", IPv6, "::", 80}, + { "fe::01:80", IPv6, "fe::01:80", 0}, + { "[fe::01]:80", IPv6, "fe::01", 80}, + { "fe::01", IPv6, "fe::01", 0}, + { "[fe::01]", IPv6, "fe::01", 0}, + { "fe::01:", IPv6, "fe::01", 0}, + { "[fe::01]:", IPv6, "fe::01", 0}, + { "::", IPv6, "::0", 0}, + { "[::]", IPv6, "::", 0}, + { ":::", IPv6, "::", 0}, + { "[::]:", IPv6, "::", 0}, + { ":::80", IPv6, "::", 80}, + { "[::]:80", IPv6, "::", 80}, #endif }; struct test_t invalid_tests[] = { - /* IPv4 */ - { "10.0.0.1:abcd", IPv4}, /* port not numeric */ - { "10.0.0.1:-1", IPv4}, /* port contains illegal character */ - { "10.0.0.1:123456", IPv4}, /* port too big */ - //this actually is fine on my Mac OS 10.9 - //it will be resolved with gethostbyname() and something is returned! - //{ "1.2.3.4.5:80", IPv4}, /* invalid IP */ - { "10:0:80", IPv4}, /* hostname has colon */ + /* IPv4 */ + { "10.0.0.1:abcd", IPv4}, /* port not numeric */ + { "10.0.0.1:-1", IPv4}, /* port contains illegal character */ + { "10.0.0.1:123456", IPv4}, /* port too big */ + //this actually is fine on my Mac OS 10.9 + //it will be resolved with gethostbyname() and something is returned! + //{ "1.2.3.4.5:80", IPv4}, /* invalid IP */ + { "10:0:80", IPv4}, /* hostname has colon */ #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6 - { "[fe::01]:abcd", IPv6}, /* port not numeric */ - { "[fe::01]:-1", IPv6}, /* port contains illegal character */ - { "[fe::01]:123456", IPv6}, /* port too big */ - { "fe::01:02::03:04:80", IPv6}, /* invalid IP */ - { "[fe::01:02::03:04]:80", IPv6}, /* invalid IP */ - { "[fe:01", IPv6}, /* Unterminated bracket */ + { "[fe::01]:abcd", IPv6}, /* port not numeric */ + { "[fe::01]:-1", IPv6}, /* port contains illegal character */ + { "[fe::01]:123456", IPv6}, /* port too big */ + { "fe::01:02::03:04:80", IPv6}, /* invalid IP */ + { "[fe::01:02::03:04]:80", IPv6}, /* invalid IP */ + { "[fe:01", IPv6}, /* Unterminated bracket */ #endif }; @@ -272,100 +271,100 @@ static int parse_test(void) PJ_LOG(3,("test", "...IP address parsing")); for (i=0; isin_addr)); - strcpy(addr_str, pj_inet_ntoa(addr.sin_addr)); - PJ_LOG(3,("test", "...error: src address mismatch (original=%s, " - "recvfrom addr=%s)", - srcaddr_str, addr_str)); - return -152; - } - + rc = pj_sock_recvfrom(ss, recvdata, &received, 0, &addr, &srclen); + if (rc != PJ_SUCCESS || received != DATA_LEN) { + app_perror("...recvfrom error", rc); + rc = -150; goto on_error; + } + if (srclen != addrlen) + return -151; + if (pj_sockaddr_cmp(&addr, srcaddr) != 0) { + char srcaddr_str[32], addr_str[32]; + strcpy(srcaddr_str, pj_inet_ntoa(srcaddr->sin_addr)); + strcpy(addr_str, pj_inet_ntoa(addr.sin_addr)); + PJ_LOG(3,("test", "...error: src address mismatch (original=%s, " + "recvfrom addr=%s)", + srcaddr_str, addr_str)); + return -152; + } + } else { /* Repeat recv() until all data is received. * This applies only for non-UDP of course, since for UDP @@ -530,33 +529,33 @@ static int send_recv_test(int sock_type, total_received = 0; do { received = DATA_LEN-total_received; - rc = pj_sock_recv(ss, recvdata+total_received, &received, 0); - if (rc != PJ_SUCCESS) { - app_perror("...recv error", rc); - rc = -155; goto on_error; - } + rc = pj_sock_recv(ss, recvdata+total_received, &received, 0); + if (rc != PJ_SUCCESS) { + app_perror("...recv error", rc); + rc = -155; goto on_error; + } if (received <= 0) { PJ_LOG(3,("", "...error: socket has closed! (received=%d)", received)); rc = -156; goto on_error; } - if (received != DATA_LEN-total_received) { + if (received != DATA_LEN-total_received) { if (sock_type != pj_SOCK_STREAM()) { - PJ_LOG(3,("", "...error: expecting %u bytes, got %u bytes", + PJ_LOG(3,("", "...error: expecting %u bytes, got %u bytes", DATA_LEN-total_received, received)); - rc = -157; goto on_error; + rc = -157; goto on_error; } - } + } total_received += received; } while (total_received < DATA_LEN); } TRACE_(("test", "....memcmp()")); if (pj_memcmp(senddata, recvdata, DATA_LEN) != 0) { - PJ_LOG(3,("","...error: received data mismatch " - "(got:'%s' expecting:'%s'", - recvdata, senddata)); - rc = -160; goto on_error; + PJ_LOG(3,("","...error: received data mismatch " + "(got:'%s' expecting:'%s'", + recvdata, senddata)); + rc = -160; goto on_error; } /* @@ -565,18 +564,18 @@ static int send_recv_test(int sock_type, TRACE_(("test", "....sendto()")); if (dstaddr) { sent = BIG_DATA_LEN; - rc = pj_sock_sendto(cs, bigdata, &sent, 0, dstaddr, addrlen); - if (rc != PJ_SUCCESS || sent != BIG_DATA_LEN) { - app_perror("...sendto error", rc); - rc = -161; goto on_error; - } + rc = pj_sock_sendto(cs, bigdata, &sent, 0, dstaddr, addrlen); + if (rc != PJ_SUCCESS || sent != BIG_DATA_LEN) { + app_perror("...sendto error", rc); + rc = -161; goto on_error; + } } else { sent = BIG_DATA_LEN; - rc = pj_sock_send(cs, bigdata, &sent, 0); - if (rc != PJ_SUCCESS || sent != BIG_DATA_LEN) { - app_perror("...send error", rc); - rc = -165; goto on_error; - } + rc = pj_sock_send(cs, bigdata, &sent, 0); + if (rc != PJ_SUCCESS || sent != BIG_DATA_LEN) { + app_perror("...send error", rc); + rc = -165; goto on_error; + } } TRACE_(("test", "....recv()")); @@ -588,30 +587,30 @@ static int send_recv_test(int sock_type, total_received = 0; do { received = BIG_DATA_LEN-total_received; - rc = pj_sock_recv(ss, bigbuffer+total_received, &received, 0); - if (rc != PJ_SUCCESS) { - app_perror("...recv error", rc); - rc = -170; goto on_error; - } + rc = pj_sock_recv(ss, bigbuffer+total_received, &received, 0); + if (rc != PJ_SUCCESS) { + app_perror("...recv error", rc); + rc = -170; goto on_error; + } if (received <= 0) { PJ_LOG(3,("", "...error: socket has closed! (received=%d)", received)); rc = -173; goto on_error; } - if (received != BIG_DATA_LEN-total_received) { + if (received != BIG_DATA_LEN-total_received) { if (sock_type != pj_SOCK_STREAM()) { - PJ_LOG(3,("", "...error: expecting %u bytes, got %u bytes", + PJ_LOG(3,("", "...error: expecting %u bytes, got %u bytes", BIG_DATA_LEN-total_received, received)); - rc = -176; goto on_error; + rc = -176; goto on_error; } - } + } total_received += received; } while (total_received < BIG_DATA_LEN); TRACE_(("test", "....memcmp()")); if (pj_memcmp(bigdata, bigbuffer, BIG_DATA_LEN) != 0) { PJ_LOG(3,("", "...error: received data has been altered!")); - rc = -180; goto on_error; + rc = -180; goto on_error; } rc = 0; @@ -631,13 +630,13 @@ static int udp_test(void) rc = pj_sock_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, &ss); if (rc != 0) { - app_perror("...error: unable to create socket", rc); - return -100; + app_perror("...error: unable to create socket", rc); + return -100; } rc = pj_sock_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, &cs); if (rc != 0) - return -110; + return -110; /* Bind server socket. */ pj_bzero(&dstaddr, sizeof(dstaddr)); @@ -646,8 +645,8 @@ static int udp_test(void) dstaddr.sin_addr = pj_inet_addr(pj_cstr(&s, ADDRESS)); if ((rc=pj_sock_bind(ss, &dstaddr, sizeof(dstaddr))) != 0) { - app_perror("...bind error udp:"ADDRESS, rc); - rc = -120; goto on_error; + app_perror("...bind error udp:"ADDRESS, rc); + rc = -120; goto on_error; } /* Bind client socket. */ @@ -657,21 +656,21 @@ static int udp_test(void) srcaddr.sin_addr = pj_inet_addr(pj_cstr(&s, ADDRESS)); if ((rc=pj_sock_bind(cs, &srcaddr, sizeof(srcaddr))) != 0) { - app_perror("...bind error", rc); - rc = -121; goto on_error; + app_perror("...bind error", rc); + rc = -121; goto on_error; } - + /* Test send/recv, with sendto */ rc = send_recv_test(pj_SOCK_DGRAM(), ss, cs, &dstaddr, NULL, sizeof(dstaddr)); if (rc != 0) - goto on_error; + goto on_error; /* Test send/recv, with sendto and recvfrom */ rc = send_recv_test(pj_SOCK_DGRAM(), ss, cs, &dstaddr, &srcaddr, sizeof(dstaddr)); if (rc != 0) - goto on_error; + goto on_error; /* Disable this test on Symbian since UDP connect()/send() failed * with S60 3rd edition (including MR2). @@ -681,20 +680,20 @@ static int udp_test(void) /* connect() the sockets. */ rc = pj_sock_connect(cs, &dstaddr, sizeof(dstaddr)); if (rc != 0) { - app_perror("...connect() error", rc); - rc = -122; goto on_error; + app_perror("...connect() error", rc); + rc = -122; goto on_error; } /* Test send/recv with send() */ rc = send_recv_test(pj_SOCK_DGRAM(), ss, cs, NULL, NULL, 0); if (rc != 0) - goto on_error; + goto on_error; /* Test send/recv with send() and recvfrom */ rc = send_recv_test(pj_SOCK_DGRAM(), ss, cs, NULL, &srcaddr, sizeof(srcaddr)); if (rc != 0) - goto on_error; + goto on_error; #endif on_error: @@ -767,79 +766,79 @@ static int gethostbyname_test(void) /* Must return failure! */ if (status == PJ_SUCCESS) - return -20100; + return -20100; else - return 0; + return 0; } #if 0 #include "../pj/os_symbian.h" static int connect_test() { - RSocketServ rSockServ; - RSocket rSock; - TInetAddr inetAddr; - TRequestStatus reqStatus; - char buffer[16]; - TPtrC8 data((const TUint8*)buffer, (TInt)sizeof(buffer)); - int rc; - - rc = rSockServ.Connect(); - if (rc != KErrNone) - return rc; - - rc = rSock.Open(rSockServ, KAfInet, KSockDatagram, KProtocolInetUdp); - if (rc != KErrNone) - { - rSockServ.Close(); - return rc; - } - - inetAddr.Init(KAfInet); - inetAddr.Input(_L("127.0.0.1")); - inetAddr.SetPort(80); - - rSock.Connect(inetAddr, reqStatus); - User::WaitForRequest(reqStatus); - - if (reqStatus != KErrNone) { - rSock.Close(); - rSockServ.Close(); - return rc; - } + RSocketServ rSockServ; + RSocket rSock; + TInetAddr inetAddr; + TRequestStatus reqStatus; + char buffer[16]; + TPtrC8 data((const TUint8*)buffer, (TInt)sizeof(buffer)); + int rc; + + rc = rSockServ.Connect(); + if (rc != KErrNone) + return rc; + + rc = rSock.Open(rSockServ, KAfInet, KSockDatagram, KProtocolInetUdp); + if (rc != KErrNone) + { + rSockServ.Close(); + return rc; + } + + inetAddr.Init(KAfInet); + inetAddr.Input(_L("127.0.0.1")); + inetAddr.SetPort(80); + + rSock.Connect(inetAddr, reqStatus); + User::WaitForRequest(reqStatus); + + if (reqStatus != KErrNone) { + rSock.Close(); + rSockServ.Close(); + return rc; + } - rSock.Send(data, 0, reqStatus); - User::WaitForRequest(reqStatus); - - if (reqStatus!=KErrNone) { - rSock.Close(); - rSockServ.Close(); - return rc; - } - - rSock.Close(); - rSockServ.Close(); - return KErrNone; + rSock.Send(data, 0, reqStatus); + User::WaitForRequest(reqStatus); + + if (reqStatus!=KErrNone) { + rSock.Close(); + rSockServ.Close(); + return rc; + } + + rSock.Close(); + rSockServ.Close(); + return KErrNone; } #endif static const char *family2str(int f) { if (f == pj_AF_UNIX()) - return "AF_UNIX"; + return "AF_UNIX"; if (f == pj_AF_INET()) - return "AF_INET"; + return "AF_INET"; if (f == pj_AF_INET6()) - return "AF_INET6"; + return "AF_INET6"; return "?"; } static const char *type2str(int type) { if (type == pj_SOCK_DGRAM()) - return "SOCK_DGRAM"; + return "SOCK_DGRAM"; if (type == pj_SOCK_STREAM()) - return "SOCK_STREAM"; + return "SOCK_STREAM"; return "?"; } @@ -851,46 +850,46 @@ static int do_sockpair_tst(int family, int type, int proto) pj_ssize_t len; PJ_LOG(3, ("test", "#Test socketpair, family: %s, type: %s", - family2str(family), type2str(type))); + family2str(family), type2str(type))); rc = pj_sock_socketpair(family, type, proto, sv); if (rc != PJ_SUCCESS) - goto on_error; + goto on_error; /* sv[0] send text to sv[1] */ len = pj_ansi_snprintf(buf, sizeof(buf), "hello, %ld->%ld", sv[0], sv[1]); rc = pj_sock_send(sv[0], buf, &len, 0); if (rc != PJ_SUCCESS) - goto on_error; + goto on_error; PJ_LOG(3, ("test", "send: %.*s", (int)len, buf)); len = sizeof(buf); rc = pj_sock_recv(sv[1], buf, &len, 0); if (rc != PJ_SUCCESS) - goto on_error; + goto on_error; PJ_LOG(3, ("test", "recv: %.*s", (int)len, buf)); /* sv[1] send text to sv[0] */ len = pj_ansi_snprintf(buf, sizeof(buf), "hello, %ld->%ld", sv[1], sv[0]); rc = pj_sock_send(sv[1], buf, &len, 0); if (rc != PJ_SUCCESS) - goto on_error; + goto on_error; PJ_LOG(3, ("test", "send: %.*s", (int)len, buf)); len = sizeof(buf); rc = pj_sock_recv(sv[0], buf, &len, 0); if (rc != PJ_SUCCESS) - goto on_error; + goto on_error; PJ_LOG(3, ("test", "recv: %.*s", (int)len, buf)); on_error: if (sv[0] > 0) - pj_sock_close(sv[0]); + pj_sock_close(sv[0]); if (sv[1] > 0) - pj_sock_close(sv[1]); + pj_sock_close(sv[1]); if (rc != PJ_SUCCESS) { - PJ_PERROR(1, ("test", rc, "error")); + PJ_PERROR(1, ("test", rc, "error")); } return rc; @@ -906,11 +905,11 @@ static int socketpair_test() #if (defined(PJ_SOCK_HAS_SOCKETPAIR) && PJ_SOCK_HAS_SOCKETPAIR) rc = do_sockpair_tst(pj_AF_UNIX(), pj_SOCK_DGRAM(), 0); if (rc != PJ_SUCCESS) - return rc; + return rc; rc = do_sockpair_tst(pj_AF_UNIX(), pj_SOCK_STREAM(), 0); if (rc != PJ_SUCCESS) - return rc; + return rc; #else PJ_LOG(2, ("test", "Not support AF_UNIX")); #endif @@ -918,21 +917,21 @@ static int socketpair_test() /* AF_INET */ rc = do_sockpair_tst(pj_AF_INET(), pj_SOCK_DGRAM(), 0); if (rc != PJ_SUCCESS) - return rc; + return rc; #if PJ_HAS_TCP rc = do_sockpair_tst(pj_AF_INET(), pj_SOCK_STREAM(), 0); if (rc != PJ_SUCCESS) - return rc; + return rc; #endif /* AF_INET6 */ rc = do_sockpair_tst(pj_AF_INET6(), pj_SOCK_DGRAM(), 0); if (rc != PJ_SUCCESS) - return rc; + return rc; #if PJ_HAS_TCP rc = do_sockpair_tst(pj_AF_INET6(), pj_SOCK_STREAM(), 0); if (rc != PJ_SUCCESS) - return rc; + return rc; #endif return 0; @@ -948,44 +947,44 @@ int sock_test() #if 0 rc = connect_test(); if (rc != 0) - return rc; + return rc; #endif rc = format_test(); if (rc != 0) - return rc; + return rc; rc = parse_test(); if (rc != 0) - return rc; + return rc; rc = purity_test(); if (rc != 0) - return rc; + return rc; rc = gethostbyname_test(); if (rc != 0) - return rc; + return rc; rc = simple_sock_test(); if (rc != 0) - return rc; + return rc; rc = ioctl_test(); if (rc != 0) - return rc; + return rc; rc = udp_test(); if (rc != 0) - return rc; + return rc; rc = tcp_test(); if (rc != 0) - return rc; + return rc; rc = socketpair_test(); if (rc != 0) - return rc; + return rc; return 0; } @@ -996,5 +995,5 @@ int sock_test() * when this test is disabled. */ int dummy_sock_test; -#endif /* INCLUDE_SOCK_TEST */ +#endif /* INCLUDE_SOCK_TEST */ diff --git a/pjlib/src/pjlib-test/sock_perf.c b/pjlib/src/pjlib-test/sock_perf.c index cf746be5a6..d192f1db1c 100644 --- a/pjlib/src/pjlib-test/sock_perf.c +++ b/pjlib/src/pjlib-test/sock_perf.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -78,7 +77,7 @@ static int sock_producer_consumer(int sock_type, total_received = 0; for (i=0; i 10) - break; + /* Stop test if it's been runnign for more than 10 secs. */ + pj_get_timestamp(&stop); + delay = pj_elapsed_time(&start, &stop); + if (delay.sec > 10) + break; } /* Stop timer. */ diff --git a/pjlib/src/pjlib-test/ssl_sock.c b/pjlib/src/pjlib-test/ssl_sock.c index 0528f1cd59..888b11dac9 100644 --- a/pjlib/src/pjlib-test/ssl_sock.c +++ b/pjlib/src/pjlib-test/ssl_sock.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,17 +20,17 @@ #include -#define CERT_DIR "../build/" +#define CERT_DIR "../build/" #if (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_DARWIN) || \ (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_APPLE) /* If we use Darwin SSL, use the cert in DER format. */ -# define CERT_CA_FILE CERT_DIR "cacert.der" +# define CERT_CA_FILE CERT_DIR "cacert.der" #else -# define CERT_CA_FILE CERT_DIR "cacert.pem" +# define CERT_CA_FILE CERT_DIR "cacert.pem" #endif -#define CERT_FILE CERT_DIR "cacert.pem" -#define CERT_PRIVKEY_FILE CERT_DIR "privkey.pem" -#define CERT_PRIVKEY_PASS "privkeypass" +#define CERT_FILE CERT_DIR "cacert.pem" +#define CERT_PRIVKEY_FILE CERT_DIR "privkey.pem" +#define CERT_PRIVKEY_PASS "privkeypass" #define TEST_LOAD_FROM_FILES 1 @@ -41,7 +40,7 @@ static int clients_num; struct send_key { - pj_ioqueue_op_key_t op_key; + pj_ioqueue_op_key_t op_key; }; @@ -54,18 +53,18 @@ static int get_cipher_list(void) { cipher_num = PJ_ARRAY_SIZE(ciphers); status = pj_ssl_cipher_get_availables(ciphers, &cipher_num); if (status != PJ_SUCCESS) { - app_perror("...FAILED to get available ciphers", status); - return status; + app_perror("...FAILED to get available ciphers", status); + return status; } PJ_LOG(3, ("", "...Found %u ciphers:", cipher_num)); for (i = 0; i < cipher_num; ++i) { - const char* st; - st = pj_ssl_cipher_name(ciphers[i]); - if (st == NULL) - st = "[Unknown]"; + const char* st; + st = pj_ssl_cipher_name(ciphers[i]); + if (st == NULL) + st = "[Unknown]"; - PJ_LOG(3, ("", "...%3u: 0x%08x=%s", i+1, ciphers[i], st)); + PJ_LOG(3, ("", "...%3u: 0x%08x=%s", i+1, ciphers[i], st)); } return PJ_SUCCESS; @@ -74,21 +73,21 @@ static int get_cipher_list(void) { struct test_state { - pj_pool_t *pool; /* pool */ - pj_ioqueue_t *ioqueue; /* ioqueue */ - pj_bool_t is_server; /* server role flag */ - pj_bool_t is_verbose; /* verbose flag, e.g: cert info */ - pj_bool_t echo; /* echo received data */ - pj_status_t err; /* error flag */ - pj_size_t sent; /* bytes sent */ - pj_size_t recv; /* bytes received */ - pj_uint8_t read_buf[256]; /* read buffer */ - pj_bool_t done; /* test done flag */ - char *send_str; /* data to send once connected */ - pj_size_t send_str_len; /* send data length */ - pj_bool_t check_echo; /* flag to compare sent & echoed data */ - const char *check_echo_ptr; /* pointer/cursor for comparing data */ - struct send_key send_key; /* send op key */ + pj_pool_t *pool; /* pool */ + pj_ioqueue_t *ioqueue; /* ioqueue */ + pj_bool_t is_server; /* server role flag */ + pj_bool_t is_verbose; /* verbose flag, e.g: cert info */ + pj_bool_t echo; /* echo received data */ + pj_status_t err; /* error flag */ + pj_size_t sent; /* bytes sent */ + pj_size_t recv; /* bytes received */ + pj_uint8_t read_buf[256]; /* read buffer */ + pj_bool_t done; /* test done flag */ + char *send_str; /* data to send once connected */ + pj_size_t send_str_len; /* send data length */ + pj_bool_t check_echo; /* flag to compare sent & echoed data */ + const char *check_echo_ptr; /* pointer/cursor for comparing data */ + struct send_key send_key; /* send op key */ }; static void dump_ssl_info(const pj_ssl_sock_info *si) @@ -98,54 +97,54 @@ static void dump_ssl_info(const pj_ssl_sock_info *si) /* Print cipher name */ tmp_st = pj_ssl_cipher_name(si->cipher); if (tmp_st == NULL) - tmp_st = "[Unknown]"; + tmp_st = "[Unknown]"; PJ_LOG(3, ("", ".....Cipher: %s", tmp_st)); /* Print remote certificate info and verification result */ if (si->remote_cert_info && si->remote_cert_info->subject.info.slen) { - char buf[2048]; - const char *verif_msgs[32]; - unsigned verif_msg_cnt; - - /* Dump remote TLS certificate info */ - PJ_LOG(3, ("", ".....Remote certificate info:")); - pj_ssl_cert_info_dump(si->remote_cert_info, " ", buf, sizeof(buf)); - PJ_LOG(3,("", "\n%s", buf)); - - /* Dump remote TLS certificate verification result */ - verif_msg_cnt = PJ_ARRAY_SIZE(verif_msgs); - pj_ssl_cert_get_verify_status_strings(si->verify_status, - verif_msgs, &verif_msg_cnt); - PJ_LOG(3,("", ".....Remote certificate verification result: %s", - (verif_msg_cnt == 1? verif_msgs[0]:""))); - if (verif_msg_cnt > 1) { - unsigned i; - for (i = 0; i < verif_msg_cnt; ++i) - PJ_LOG(3,("", "..... - %s", verif_msgs[i])); - } + char buf[2048]; + const char *verif_msgs[32]; + unsigned verif_msg_cnt; + + /* Dump remote TLS certificate info */ + PJ_LOG(3, ("", ".....Remote certificate info:")); + pj_ssl_cert_info_dump(si->remote_cert_info, " ", buf, sizeof(buf)); + PJ_LOG(3,("", "\n%s", buf)); + + /* Dump remote TLS certificate verification result */ + verif_msg_cnt = PJ_ARRAY_SIZE(verif_msgs); + pj_ssl_cert_get_verify_status_strings(si->verify_status, + verif_msgs, &verif_msg_cnt); + PJ_LOG(3,("", ".....Remote certificate verification result: %s", + (verif_msg_cnt == 1? verif_msgs[0]:""))); + if (verif_msg_cnt > 1) { + unsigned i; + for (i = 0; i < verif_msg_cnt; ++i) + PJ_LOG(3,("", "..... - %s", verif_msgs[i])); + } } } static pj_bool_t ssl_on_connect_complete(pj_ssl_sock_t *ssock, - pj_status_t status) + pj_status_t status) { struct test_state *st = (struct test_state*) - pj_ssl_sock_get_user_data(ssock); + pj_ssl_sock_get_user_data(ssock); void *read_buf[1]; pj_ssl_sock_info info; char buf1[64], buf2[64]; if (status != PJ_SUCCESS) { - app_perror("...ERROR ssl_on_connect_complete()", status); - goto on_return; + app_perror("...ERROR ssl_on_connect_complete()", status); + goto on_return; } status = pj_ssl_sock_get_info(ssock, &info); if (status != PJ_SUCCESS) { - app_perror("...ERROR pj_ssl_sock_get_info()", status); - goto on_return; + app_perror("...ERROR pj_ssl_sock_get_info()", status); + goto on_return; } pj_sockaddr_print((pj_sockaddr_t*)&info.local_addr, buf1, sizeof(buf1), 1); @@ -153,44 +152,44 @@ static pj_bool_t ssl_on_connect_complete(pj_ssl_sock_t *ssock, PJ_LOG(3, ("", "...Connected %s -> %s!", buf1, buf2)); if (st->is_verbose) - dump_ssl_info(&info); + dump_ssl_info(&info); /* Start reading data */ read_buf[0] = st->read_buf; status = pj_ssl_sock_start_read2(ssock, st->pool, sizeof(st->read_buf), (void**)read_buf, 0); if (status != PJ_SUCCESS) { - app_perror("...ERROR pj_ssl_sock_start_read2()", status); - goto on_return; + app_perror("...ERROR pj_ssl_sock_start_read2()", status); + goto on_return; } /* Start sending data */ while (st->sent < st->send_str_len) { - pj_ssize_t size; + pj_ssize_t size; - size = st->send_str_len - st->sent; - status = pj_ssl_sock_send(ssock, (pj_ioqueue_op_key_t*)&st->send_key, - st->send_str + st->sent, &size, 0); - if (status != PJ_SUCCESS && status != PJ_EPENDING) { - app_perror("...ERROR pj_ssl_sock_send()", status); - goto on_return; - } + size = st->send_str_len - st->sent; + status = pj_ssl_sock_send(ssock, (pj_ioqueue_op_key_t*)&st->send_key, + st->send_str + st->sent, &size, 0); + if (status != PJ_SUCCESS && status != PJ_EPENDING) { + app_perror("...ERROR pj_ssl_sock_send()", status); + goto on_return; + } - if (status == PJ_SUCCESS) { - st->sent += size; - } else { - if (status == PJ_EPENDING) - status = PJ_SUCCESS; - break; - } + if (status == PJ_SUCCESS) { + st->sent += size; + } else { + if (status == PJ_EPENDING) + status = PJ_SUCCESS; + break; + } } on_return: st->err = status; if (st->err != PJ_SUCCESS) { - pj_ssl_sock_close(ssock); - clients_num--; - return PJ_FALSE; + pj_ssl_sock_close(ssock); + clients_num--; + return PJ_FALSE; } return PJ_TRUE; @@ -198,13 +197,13 @@ static pj_bool_t ssl_on_connect_complete(pj_ssl_sock_t *ssock, static pj_bool_t ssl_on_accept_complete(pj_ssl_sock_t *ssock, - pj_ssl_sock_t *newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len, - pj_status_t accept_status) + pj_ssl_sock_t *newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len, + pj_status_t accept_status) { struct test_state *parent_st = (struct test_state*) - pj_ssl_sock_get_user_data(ssock); + pj_ssl_sock_get_user_data(ssock); struct test_state *st; void *read_buf[1]; pj_ssl_sock_info info; @@ -214,11 +213,11 @@ static pj_bool_t ssl_on_accept_complete(pj_ssl_sock_t *ssock, PJ_UNUSED_ARG(src_addr_len); if (accept_status != PJ_SUCCESS) { - if (newsock) { - st = (struct test_state*) pj_ssl_sock_get_user_data(newsock); - st->err = accept_status; - } - return PJ_FALSE; + if (newsock) { + st = (struct test_state*) pj_ssl_sock_get_user_data(newsock); + st->err = accept_status; + } + return PJ_FALSE; } /* Duplicate parent test state to newly accepted test state */ @@ -228,204 +227,204 @@ static pj_bool_t ssl_on_accept_complete(pj_ssl_sock_t *ssock, status = pj_ssl_sock_get_info(newsock, &info); if (status != PJ_SUCCESS) { - app_perror("...ERROR pj_ssl_sock_get_info()", status); - goto on_return; + app_perror("...ERROR pj_ssl_sock_get_info()", status); + goto on_return; } pj_sockaddr_print(src_addr, buf, sizeof(buf), 1); PJ_LOG(3, ("", "...Accepted connection from %s", buf)); if (st->is_verbose) - dump_ssl_info(&info); + dump_ssl_info(&info); /* Start reading data */ read_buf[0] = st->read_buf; status = pj_ssl_sock_start_read2(newsock, st->pool, sizeof(st->read_buf), (void**)read_buf, 0); if (status != PJ_SUCCESS) { - app_perror("...ERROR pj_ssl_sock_start_read2()", status); - goto on_return; + app_perror("...ERROR pj_ssl_sock_start_read2()", status); + goto on_return; } /* Start sending data */ while (st->sent < st->send_str_len) { - pj_ssize_t size; + pj_ssize_t size; - size = st->send_str_len - st->sent; - status = pj_ssl_sock_send(newsock, (pj_ioqueue_op_key_t*)&st->send_key, - st->send_str + st->sent, &size, 0); - if (status != PJ_SUCCESS && status != PJ_EPENDING) { - app_perror("...ERROR pj_ssl_sock_send()", status); - goto on_return; - } + size = st->send_str_len - st->sent; + status = pj_ssl_sock_send(newsock, (pj_ioqueue_op_key_t*)&st->send_key, + st->send_str + st->sent, &size, 0); + if (status != PJ_SUCCESS && status != PJ_EPENDING) { + app_perror("...ERROR pj_ssl_sock_send()", status); + goto on_return; + } - if (status == PJ_SUCCESS) { - st->sent += size; - } else { - if (status == PJ_EPENDING) - status = PJ_SUCCESS; - break; - } + if (status == PJ_SUCCESS) { + st->sent += size; + } else { + if (status == PJ_EPENDING) + status = PJ_SUCCESS; + break; + } } on_return: st->err = status; if (st->err != PJ_SUCCESS) { - pj_ssl_sock_close(newsock); - return PJ_FALSE; + pj_ssl_sock_close(newsock); + return PJ_FALSE; } return PJ_TRUE; } static pj_bool_t ssl_on_data_read(pj_ssl_sock_t *ssock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { struct test_state *st = (struct test_state*) - pj_ssl_sock_get_user_data(ssock); + pj_ssl_sock_get_user_data(ssock); PJ_UNUSED_ARG(remainder); PJ_UNUSED_ARG(data); if (size > 0) { - pj_size_t consumed; - - /* Set random remainder */ - *remainder = pj_rand() % 100; - - /* Apply zero remainder if: - * - remainder is less than size, or - * - connection closed/error - * - echo/check_eco set - */ - if (*remainder > size || status != PJ_SUCCESS || st->echo || st->check_echo) - *remainder = 0; - - consumed = size - *remainder; - st->recv += consumed; - - //printf("%.*s", consumed, (char*)data); - - pj_memmove(data, (char*)data + consumed, *remainder); - - /* Echo data when specified to */ - if (st->echo) { - pj_ssize_t size_ = consumed; - status = pj_ssl_sock_send(ssock, (pj_ioqueue_op_key_t*)&st->send_key, data, &size_, 0); - if (status != PJ_SUCCESS && status != PJ_EPENDING) { - app_perror("...ERROR pj_ssl_sock_send()", status); - goto on_return; - } - - if (status == PJ_SUCCESS) { - st->sent += size_; - } else if (status == PJ_EPENDING) { - status = PJ_SUCCESS; - } - } - - /* Verify echoed data when specified to */ - if (st->check_echo) { - if (!st->check_echo_ptr) - st->check_echo_ptr = st->send_str; - - if (pj_memcmp(st->check_echo_ptr, data, consumed)) { - status = PJ_EINVAL; - app_perror("...ERROR echoed data not exact", status); - goto on_return; - } - st->check_echo_ptr += consumed; - - /* Echo received completely */ - if (st->send_str_len == st->recv) { - pj_ssl_sock_info info; - char buf[64]; - - status = pj_ssl_sock_get_info(ssock, &info); - if (status != PJ_SUCCESS) { - app_perror("...ERROR pj_ssl_sock_get_info()", status); - goto on_return; - } - - pj_sockaddr_print((pj_sockaddr_t*)&info.local_addr, buf, sizeof(buf), 1); - PJ_LOG(3, ("", "...%s successfully recv %d bytes echo", buf, st->recv)); - st->done = PJ_TRUE; - } - } + pj_size_t consumed; + + /* Set random remainder */ + *remainder = pj_rand() % 100; + + /* Apply zero remainder if: + * - remainder is less than size, or + * - connection closed/error + * - echo/check_eco set + */ + if (*remainder > size || status != PJ_SUCCESS || st->echo || st->check_echo) + *remainder = 0; + + consumed = size - *remainder; + st->recv += consumed; + + //printf("%.*s", consumed, (char*)data); + + pj_memmove(data, (char*)data + consumed, *remainder); + + /* Echo data when specified to */ + if (st->echo) { + pj_ssize_t size_ = consumed; + status = pj_ssl_sock_send(ssock, (pj_ioqueue_op_key_t*)&st->send_key, data, &size_, 0); + if (status != PJ_SUCCESS && status != PJ_EPENDING) { + app_perror("...ERROR pj_ssl_sock_send()", status); + goto on_return; + } + + if (status == PJ_SUCCESS) { + st->sent += size_; + } else if (status == PJ_EPENDING) { + status = PJ_SUCCESS; + } + } + + /* Verify echoed data when specified to */ + if (st->check_echo) { + if (!st->check_echo_ptr) + st->check_echo_ptr = st->send_str; + + if (pj_memcmp(st->check_echo_ptr, data, consumed)) { + status = PJ_EINVAL; + app_perror("...ERROR echoed data not exact", status); + goto on_return; + } + st->check_echo_ptr += consumed; + + /* Echo received completely */ + if (st->send_str_len == st->recv) { + pj_ssl_sock_info info; + char buf[64]; + + status = pj_ssl_sock_get_info(ssock, &info); + if (status != PJ_SUCCESS) { + app_perror("...ERROR pj_ssl_sock_get_info()", status); + goto on_return; + } + + pj_sockaddr_print((pj_sockaddr_t*)&info.local_addr, buf, sizeof(buf), 1); + PJ_LOG(3, ("", "...%s successfully recv %d bytes echo", buf, st->recv)); + st->done = PJ_TRUE; + } + } } if (status != PJ_SUCCESS) { - if (status == PJ_EEOF) { - status = PJ_SUCCESS; - st->done = PJ_TRUE; - } else { - app_perror("...ERROR ssl_on_data_read()", status); - } + if (status == PJ_EEOF) { + status = PJ_SUCCESS; + st->done = PJ_TRUE; + } else { + app_perror("...ERROR ssl_on_data_read()", status); + } } on_return: st->err = status; if (st->err != PJ_SUCCESS || st->done) { - pj_ssl_sock_close(ssock); - if (!st->is_server) - clients_num--; - return PJ_FALSE; + pj_ssl_sock_close(ssock); + if (!st->is_server) + clients_num--; + return PJ_FALSE; } return PJ_TRUE; } static pj_bool_t ssl_on_data_sent(pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t sent) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t sent) { struct test_state *st = (struct test_state*) - pj_ssl_sock_get_user_data(ssock); + pj_ssl_sock_get_user_data(ssock); PJ_UNUSED_ARG(op_key); if (sent < 0) { - st->err = (pj_status_t)-sent; + st->err = (pj_status_t)-sent; } else { - st->sent += sent; + st->sent += sent; - /* Send more if any */ - while (st->sent < st->send_str_len) { - pj_ssize_t size; - pj_status_t status; + /* Send more if any */ + while (st->sent < st->send_str_len) { + pj_ssize_t size; + pj_status_t status; - size = st->send_str_len - st->sent; - status = pj_ssl_sock_send(ssock, (pj_ioqueue_op_key_t*)&st->send_key, - st->send_str + st->sent, &size, 0); - if (status != PJ_SUCCESS && status != PJ_EPENDING) { - app_perror("...ERROR pj_ssl_sock_send()", status); - st->err = status; - break; - } + size = st->send_str_len - st->sent; + status = pj_ssl_sock_send(ssock, (pj_ioqueue_op_key_t*)&st->send_key, + st->send_str + st->sent, &size, 0); + if (status != PJ_SUCCESS && status != PJ_EPENDING) { + app_perror("...ERROR pj_ssl_sock_send()", status); + st->err = status; + break; + } - if (status == PJ_SUCCESS) - st->sent += size; - else - break; - } + if (status == PJ_SUCCESS) + st->sent += size; + else + break; + } } if (st->err != PJ_SUCCESS) { - pj_ssl_sock_close(ssock); - if (!st->is_server) - clients_num--; - return PJ_FALSE; + pj_ssl_sock_close(ssock); + if (!st->is_server) + clients_num--; + return PJ_FALSE; } return PJ_TRUE; } -#define HTTP_SERVER_ADDR "trac.pjsip.org" -#define HTTP_SERVER_PORT 443 -#define HTTP_REQ "GET https://" HTTP_SERVER_ADDR "/ HTTP/1.0\r\n\r\n"; +#define HTTP_SERVER_ADDR "trac.pjsip.org" +#define HTTP_SERVER_PORT 443 +#define HTTP_REQ "GET https://" HTTP_SERVER_ADDR "/ HTTP/1.0\r\n\r\n"; static int https_client_test(unsigned ms_timeout) { @@ -443,12 +442,12 @@ static int https_client_test(unsigned ms_timeout) status = pj_ioqueue_create(pool, 4, &ioqueue); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } status = pj_timer_heap_create(pool, 4, &timer); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } state.pool = pool; @@ -471,34 +470,34 @@ static int https_client_test(unsigned ms_timeout) status = pj_ssl_sock_create(pool, ¶m, &ssock); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } pj_sockaddr_init(PJ_AF_INET, &local_addr, pj_strset2(&tmp_st, "0.0.0.0"), 0); pj_sockaddr_init(PJ_AF_INET, &rem_addr, pj_strset2(&tmp_st, HTTP_SERVER_ADDR), HTTP_SERVER_PORT); status = pj_ssl_sock_start_connect(ssock, pool, &local_addr, &rem_addr, sizeof(rem_addr)); if (status == PJ_SUCCESS) { - ssl_on_connect_complete(ssock, PJ_SUCCESS); + ssl_on_connect_complete(ssock, PJ_SUCCESS); } else if (status == PJ_EPENDING) { - status = PJ_SUCCESS; + status = PJ_SUCCESS; } else { - goto on_return; + goto on_return; } /* Wait until everything has been sent/received */ while (state.err == PJ_SUCCESS && !state.done) { #ifdef PJ_SYMBIAN - pj_symbianos_poll(-1, 1000); + pj_symbianos_poll(-1, 1000); #else - pj_time_val delay = {0, 100}; - pj_ioqueue_poll(ioqueue, &delay); - pj_timer_heap_poll(timer, &delay); + pj_time_val delay = {0, 100}; + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer, &delay); #endif } if (state.err) { - status = state.err; - goto on_return; + status = state.err; + goto on_return; } PJ_LOG(3, ("", "...Done!")); @@ -506,20 +505,20 @@ static int https_client_test(unsigned ms_timeout) on_return: if (ssock && !state.err && !state.done) - pj_ssl_sock_close(ssock); + pj_ssl_sock_close(ssock); if (ioqueue) - pj_ioqueue_destroy(ioqueue); + pj_ioqueue_destroy(ioqueue); if (timer) - pj_timer_heap_destroy(timer); + pj_timer_heap_destroy(timer); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return status; } #if !(defined(TEST_LOAD_FROM_FILES) && TEST_LOAD_FROM_FILES==1) static pj_status_t load_cert_to_buf(pj_pool_t *pool, const pj_str_t *file_name, - pj_ssl_cert_buffer *buf) + pj_ssl_cert_buffer *buf) { pj_status_t status; pj_oshandle_t fd = 0; @@ -527,7 +526,7 @@ static pj_status_t load_cert_to_buf(pj_pool_t *pool, const pj_str_t *file_name, status = pj_file_open(pool, file_name->ptr, PJ_O_RDONLY, &fd); if (status != PJ_SUCCESS) - return status; + return status; buf->ptr = (char*)pj_pool_zalloc(pool, size+1); status = pj_file_read(fd, buf->ptr, &size); @@ -540,8 +539,8 @@ static pj_status_t load_cert_to_buf(pj_pool_t *pool, const pj_str_t *file_name, #endif static int echo_test(pj_ssl_sock_proto srv_proto, pj_ssl_sock_proto cli_proto, - pj_ssl_cipher srv_cipher, pj_ssl_cipher cli_cipher, - pj_bool_t req_client_cert, pj_bool_t client_provide_cert) + pj_ssl_cipher srv_cipher, pj_ssl_cipher cli_cipher, + pj_bool_t req_client_cert, pj_bool_t client_provide_cert) { pj_pool_t *pool = NULL; pj_ioqueue_t *ioqueue = NULL; @@ -560,12 +559,12 @@ static int echo_test(pj_ssl_sock_proto srv_proto, pj_ssl_sock_proto cli_proto, status = pj_ioqueue_create(pool, 4, &ioqueue); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } status = pj_timer_heap_create(pool, 4, &timer); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } pj_ssl_sock_param_default(¶m); @@ -579,8 +578,8 @@ static int echo_test(pj_ssl_sock_proto srv_proto, pj_ssl_sock_proto cli_proto, /* Init default bind address */ { - pj_str_t tmp_st; - pj_sockaddr_init(PJ_AF_INET, &addr, pj_strset2(&tmp_st, "127.0.0.1"), 0); + pj_str_t tmp_st; + pj_sockaddr_init(PJ_AF_INET, &addr, pj_strset2(&tmp_st, "127.0.0.1"), 0); } /* === SERVER === */ @@ -597,63 +596,63 @@ static int echo_test(pj_ssl_sock_proto srv_proto, pj_ssl_sock_proto cli_proto, status = pj_ssl_sock_create(pool, ¶m, &ssock_serv); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Set server cert */ { - pj_str_t ca_file = pj_str(CERT_CA_FILE); - pj_str_t cert_file = pj_str(CERT_FILE); - pj_str_t privkey_file = pj_str(CERT_PRIVKEY_FILE); - pj_str_t privkey_pass = pj_str(CERT_PRIVKEY_PASS); + pj_str_t ca_file = pj_str(CERT_CA_FILE); + pj_str_t cert_file = pj_str(CERT_FILE); + pj_str_t privkey_file = pj_str(CERT_PRIVKEY_FILE); + pj_str_t privkey_pass = pj_str(CERT_PRIVKEY_PASS); #if (defined(TEST_LOAD_FROM_FILES) && TEST_LOAD_FROM_FILES==1) - status = pj_ssl_cert_load_from_files(pool, &ca_file, &cert_file, - &privkey_file, &privkey_pass, - &cert); + status = pj_ssl_cert_load_from_files(pool, &ca_file, &cert_file, + &privkey_file, &privkey_pass, + &cert); #else - pj_ssl_cert_buffer ca_buf, cert_buf, privkey_buf; - - status = load_cert_to_buf(pool, &ca_file, &ca_buf); - if (status != PJ_SUCCESS) { - goto on_return; - } - - status = load_cert_to_buf(pool, &cert_file, &cert_buf); - if (status != PJ_SUCCESS) { - goto on_return; - } - - status = load_cert_to_buf(pool, &privkey_file, &privkey_buf); - if (status != PJ_SUCCESS) { - goto on_return; - } - - status = pj_ssl_cert_load_from_buffer(pool, &ca_buf, &cert_buf, - &privkey_buf, &privkey_pass, - &cert); + pj_ssl_cert_buffer ca_buf, cert_buf, privkey_buf; + + status = load_cert_to_buf(pool, &ca_file, &ca_buf); + if (status != PJ_SUCCESS) { + goto on_return; + } + + status = load_cert_to_buf(pool, &cert_file, &cert_buf); + if (status != PJ_SUCCESS) { + goto on_return; + } + + status = load_cert_to_buf(pool, &privkey_file, &privkey_buf); + if (status != PJ_SUCCESS) { + goto on_return; + } + + status = pj_ssl_cert_load_from_buffer(pool, &ca_buf, &cert_buf, + &privkey_buf, &privkey_pass, + &cert); #endif - if (status != PJ_SUCCESS) { - goto on_return; - } + if (status != PJ_SUCCESS) { + goto on_return; + } - status = pj_ssl_sock_set_certificate(ssock_serv, pool, cert); - if (status != PJ_SUCCESS) { - goto on_return; - } + status = pj_ssl_sock_set_certificate(ssock_serv, pool, cert); + if (status != PJ_SUCCESS) { + goto on_return; + } } status = pj_ssl_sock_start_accept(ssock_serv, pool, &addr, pj_sockaddr_get_len(&addr)); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Get listener address */ { - pj_ssl_sock_info info; + pj_ssl_sock_info info; - pj_ssl_sock_get_info(ssock_serv, &info); - pj_sockaddr_cp(&listen_addr, &info.local_addr); + pj_ssl_sock_get_info(ssock_serv, &info); + pj_sockaddr_cp(&listen_addr, &info.local_addr); } /* === CLIENT === */ @@ -667,92 +666,92 @@ static int echo_test(pj_ssl_sock_proto srv_proto, pj_ssl_sock_proto cli_proto, state_cli.is_verbose = PJ_TRUE; { - pj_time_val now; + pj_time_val now; - pj_gettimeofday(&now); - pj_srand((unsigned)now.sec); - state_cli.send_str_len = (pj_rand() % 5 + 1) * 1024 + pj_rand() % 1024; + pj_gettimeofday(&now); + pj_srand((unsigned)now.sec); + state_cli.send_str_len = (pj_rand() % 5 + 1) * 1024 + pj_rand() % 1024; } state_cli.send_str = (char*)pj_pool_alloc(pool, state_cli.send_str_len); { - unsigned i; - for (i = 0; i < state_cli.send_str_len; ++i) - state_cli.send_str[i] = (char)(pj_rand() % 256); + unsigned i; + for (i = 0; i < state_cli.send_str_len; ++i) + state_cli.send_str[i] = (char)(pj_rand() % 256); } status = pj_ssl_sock_create(pool, ¶m, &ssock_cli); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Set cert for client */ { - if (!client_provide_cert) { - pj_str_t ca_file = pj_str(CERT_CA_FILE); - pj_str_t null_str = pj_str(""); + if (!client_provide_cert) { + pj_str_t ca_file = pj_str(CERT_CA_FILE); + pj_str_t null_str = pj_str(""); #if (defined(TEST_LOAD_FROM_FILES) && TEST_LOAD_FROM_FILES==1) - status = pj_ssl_cert_load_from_files(pool, &ca_file, &null_str, - &null_str, &null_str, &cert); + status = pj_ssl_cert_load_from_files(pool, &ca_file, &null_str, + &null_str, &null_str, &cert); #else - pj_ssl_cert_buffer null_buf, ca_buf; + pj_ssl_cert_buffer null_buf, ca_buf; - null_buf.slen = 0; + null_buf.slen = 0; - status = load_cert_to_buf(pool, &ca_file, &ca_buf); - if (status != PJ_SUCCESS) { - goto on_return; - } + status = load_cert_to_buf(pool, &ca_file, &ca_buf); + if (status != PJ_SUCCESS) { + goto on_return; + } - status = pj_ssl_cert_load_from_buffer(pool, &ca_buf, &null_buf, - &null_buf, &null_str, &cert); + status = pj_ssl_cert_load_from_buffer(pool, &ca_buf, &null_buf, + &null_buf, &null_str, &cert); #endif - if (status != PJ_SUCCESS) { - goto on_return; - } + if (status != PJ_SUCCESS) { + goto on_return; + } - } + } - status = pj_ssl_sock_set_certificate(ssock_cli, pool, cert); - if (status != PJ_SUCCESS) { - goto on_return; - } + status = pj_ssl_sock_set_certificate(ssock_cli, pool, cert); + if (status != PJ_SUCCESS) { + goto on_return; + } } status = pj_ssl_sock_start_connect(ssock_cli, pool, &addr, &listen_addr, pj_sockaddr_get_len(&addr)); if (status == PJ_SUCCESS) { - ssl_on_connect_complete(ssock_cli, PJ_SUCCESS); + ssl_on_connect_complete(ssock_cli, PJ_SUCCESS); } else if (status == PJ_EPENDING) { - status = PJ_SUCCESS; + status = PJ_SUCCESS; } else { - goto on_return; + goto on_return; } /* Wait until everything has been sent/received or error */ while (!state_serv.err && !state_cli.err && !state_serv.done && !state_cli.done) { #ifdef PJ_SYMBIAN - pj_symbianos_poll(-1, 1000); + pj_symbianos_poll(-1, 1000); #else - pj_time_val delay = {0, 100}; - pj_ioqueue_poll(ioqueue, &delay); + pj_time_val delay = {0, 100}; + pj_ioqueue_poll(ioqueue, &delay); #endif } /* Clean up sockets */ { - pj_time_val delay = {0, 100}; - while (pj_ioqueue_poll(ioqueue, &delay) > 0); + pj_time_val delay = {0, 100}; + while (pj_ioqueue_poll(ioqueue, &delay) > 0); } if (state_serv.err || state_cli.err) { - if (state_serv.err != PJ_SUCCESS) - status = state_serv.err; - else - status = state_cli.err; + if (state_serv.err != PJ_SUCCESS) + status = state_serv.err; + else + status = state_cli.err; - goto on_return; + goto on_return; } PJ_LOG(3, ("", "...Done!")); @@ -762,58 +761,58 @@ static int echo_test(pj_ssl_sock_proto srv_proto, pj_ssl_sock_proto cli_proto, #if (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_DARWIN) || \ (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_APPLE) if (status != PJ_SUCCESS) { - PJ_LOG(3, ("", "Apple SSL requires the private key to be " - "inside the Keychain. So double click on " - "the file pjlib/build/privkey.p12 to " - "place it in the Keychain. " - "The password is \"pjsip\".")); + PJ_LOG(3, ("", "Apple SSL requires the private key to be " + "inside the Keychain. So double click on " + "the file pjlib/build/privkey.p12 to " + "place it in the Keychain. " + "The password is \"pjsip\".")); } #endif if (ssock_serv) - pj_ssl_sock_close(ssock_serv); + pj_ssl_sock_close(ssock_serv); if (ssock_cli && !state_cli.err && !state_cli.done) - pj_ssl_sock_close(ssock_cli); + pj_ssl_sock_close(ssock_cli); if (ioqueue) - pj_ioqueue_destroy(ioqueue); + pj_ioqueue_destroy(ioqueue); if (timer) - pj_timer_heap_destroy(timer); + pj_timer_heap_destroy(timer); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return status; } static pj_bool_t asock_on_data_read(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { struct test_state *st = (struct test_state*) - pj_activesock_get_user_data(asock); + pj_activesock_get_user_data(asock); PJ_UNUSED_ARG(data); PJ_UNUSED_ARG(size); PJ_UNUSED_ARG(remainder); if (status != PJ_SUCCESS) { - if (status == PJ_EEOF) { - status = PJ_SUCCESS; - st->done = PJ_TRUE; - } else { - app_perror("...ERROR asock_on_data_read()", status); - } + if (status == PJ_EEOF) { + status = PJ_SUCCESS; + st->done = PJ_TRUE; + } else { + app_perror("...ERROR asock_on_data_read()", status); + } } st->err = status; if (st->err != PJ_SUCCESS || st->done) { - pj_activesock_close(asock); - if (!st->is_server) - clients_num--; - return PJ_FALSE; + pj_activesock_close(asock); + if (!st->is_server) + clients_num--; + return PJ_FALSE; } return PJ_TRUE; @@ -821,38 +820,38 @@ static pj_bool_t asock_on_data_read(pj_activesock_t *asock, static pj_bool_t asock_on_connect_complete(pj_activesock_t *asock, - pj_status_t status) + pj_status_t status) { struct test_state *st = (struct test_state*) - pj_activesock_get_user_data(asock); + pj_activesock_get_user_data(asock); if (status == PJ_SUCCESS) { - void *read_buf[1]; + void *read_buf[1]; - /* Start reading data */ - read_buf[0] = st->read_buf; - status = pj_activesock_start_read2(asock, st->pool, sizeof(st->read_buf), (void**)read_buf, 0); - if (status != PJ_SUCCESS) { - app_perror("...ERROR pj_ssl_sock_start_read2()", status); - } + /* Start reading data */ + read_buf[0] = st->read_buf; + status = pj_activesock_start_read2(asock, st->pool, sizeof(st->read_buf), (void**)read_buf, 0); + if (status != PJ_SUCCESS) { + app_perror("...ERROR pj_ssl_sock_start_read2()", status); + } } st->err = status; if (st->err != PJ_SUCCESS) { - pj_activesock_close(asock); - if (!st->is_server) - clients_num--; - return PJ_FALSE; + pj_activesock_close(asock); + if (!st->is_server) + clients_num--; + return PJ_FALSE; } return PJ_TRUE; } static pj_bool_t asock_on_accept_complete(pj_activesock_t *asock, - pj_sock_t newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len) + pj_sock_t newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len) { struct test_state *st; void *read_buf[1]; @@ -867,25 +866,25 @@ static pj_bool_t asock_on_accept_complete(pj_activesock_t *asock, asock_cb.on_data_read = &asock_on_data_read; status = pj_activesock_create(st->pool, newsock, pj_SOCK_STREAM(), NULL, - st->ioqueue, &asock_cb, st, &new_asock); + st->ioqueue, &asock_cb, st, &new_asock); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Start reading data */ read_buf[0] = st->read_buf; status = pj_activesock_start_read2(new_asock, st->pool, - sizeof(st->read_buf), - (void**)read_buf, 0); + sizeof(st->read_buf), + (void**)read_buf, 0); if (status != PJ_SUCCESS) { - app_perror("...ERROR pj_ssl_sock_start_read2()", status); + app_perror("...ERROR pj_ssl_sock_start_read2()", status); } on_return: st->err = status; if (st->err != PJ_SUCCESS) - pj_activesock_close(new_asock); + pj_activesock_close(new_asock); return PJ_TRUE; } @@ -916,50 +915,50 @@ static int client_non_ssl(unsigned ms_timeout) status = pj_ioqueue_create(pool, 4, &ioqueue); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } status = pj_timer_heap_create(pool, 4, &timer); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Set cert */ { - pj_str_t ca_file = pj_str(CERT_CA_FILE); - pj_str_t cert_file = pj_str(CERT_FILE); - pj_str_t privkey_file = pj_str(CERT_PRIVKEY_FILE); - pj_str_t privkey_pass = pj_str(CERT_PRIVKEY_PASS); + pj_str_t ca_file = pj_str(CERT_CA_FILE); + pj_str_t cert_file = pj_str(CERT_FILE); + pj_str_t privkey_file = pj_str(CERT_PRIVKEY_FILE); + pj_str_t privkey_pass = pj_str(CERT_PRIVKEY_PASS); #if (defined(TEST_LOAD_FROM_FILES) && TEST_LOAD_FROM_FILES==1) - status = pj_ssl_cert_load_from_files(pool, &ca_file, &cert_file, - &privkey_file, &privkey_pass, - &cert); + status = pj_ssl_cert_load_from_files(pool, &ca_file, &cert_file, + &privkey_file, &privkey_pass, + &cert); #else - pj_ssl_cert_buffer ca_buf, cert_buf, privkey_buf; - - status = load_cert_to_buf(pool, &ca_file, &ca_buf); - if (status != PJ_SUCCESS) { - goto on_return; - } - - status = load_cert_to_buf(pool, &cert_file, &cert_buf); - if (status != PJ_SUCCESS) { - goto on_return; - } - - status = load_cert_to_buf(pool, &privkey_file, &privkey_buf); - if (status != PJ_SUCCESS) { - goto on_return; - } - - status = pj_ssl_cert_load_from_buffer(pool, &ca_buf, &cert_buf, - &privkey_buf, &privkey_pass, - &cert); + pj_ssl_cert_buffer ca_buf, cert_buf, privkey_buf; + + status = load_cert_to_buf(pool, &ca_file, &ca_buf); + if (status != PJ_SUCCESS) { + goto on_return; + } + + status = load_cert_to_buf(pool, &cert_file, &cert_buf); + if (status != PJ_SUCCESS) { + goto on_return; + } + + status = load_cert_to_buf(pool, &privkey_file, &privkey_buf); + if (status != PJ_SUCCESS) { + goto on_return; + } + + status = pj_ssl_cert_load_from_buffer(pool, &ca_buf, &cert_buf, + &privkey_buf, &privkey_pass, + &cert); #endif - if (status != PJ_SUCCESS) { - goto on_return; - } + if (status != PJ_SUCCESS) { + goto on_return; + } } pj_ssl_sock_param_default(¶m); @@ -980,92 +979,92 @@ static int client_non_ssl(unsigned ms_timeout) status = pj_ssl_sock_create(pool, ¶m, &ssock_serv); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } status = pj_ssl_sock_set_certificate(ssock_serv, pool, cert); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Init bind address */ { - pj_str_t tmp_st; - pj_sockaddr_init(PJ_AF_INET, &listen_addr, pj_strset2(&tmp_st, "127.0.0.1"), 0); + pj_str_t tmp_st; + pj_sockaddr_init(PJ_AF_INET, &listen_addr, pj_strset2(&tmp_st, "127.0.0.1"), 0); } status = pj_ssl_sock_start_accept(ssock_serv, pool, &listen_addr, pj_sockaddr_get_len(&listen_addr)); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Update listener address */ { - pj_ssl_sock_info info; + pj_ssl_sock_info info; - pj_ssl_sock_get_info(ssock_serv, &info); - pj_sockaddr_cp(&listen_addr, &info.local_addr); + pj_ssl_sock_get_info(ssock_serv, &info); + pj_sockaddr_cp(&listen_addr, &info.local_addr); } /* CLIENT */ state_cli.pool = pool; status = pj_sock_socket(pj_AF_INET(), pj_SOCK_STREAM(), 0, &sock); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } asock_cb.on_connect_complete = &asock_on_connect_complete; asock_cb.on_data_read = &asock_on_data_read; status = pj_activesock_create(pool, sock, pj_SOCK_STREAM(), NULL, - ioqueue, &asock_cb, &state_cli, &asock_cli); + ioqueue, &asock_cb, &state_cli, &asock_cli); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } status = pj_activesock_start_connect(asock_cli, pool, (pj_sockaddr_t*)&listen_addr, - pj_sockaddr_get_len(&listen_addr)); + pj_sockaddr_get_len(&listen_addr)); if (status == PJ_SUCCESS) { - asock_on_connect_complete(asock_cli, PJ_SUCCESS); + asock_on_connect_complete(asock_cli, PJ_SUCCESS); } else if (status == PJ_EPENDING) { - status = PJ_SUCCESS; + status = PJ_SUCCESS; } else { - goto on_return; + goto on_return; } /* Wait until everything has been sent/received or error */ while (!state_serv.err && !state_cli.err && !state_serv.done && !state_cli.done) { #ifdef PJ_SYMBIAN - pj_symbianos_poll(-1, 1000); + pj_symbianos_poll(-1, 1000); #else - pj_time_val delay = {0, 100}; - pj_ioqueue_poll(ioqueue, &delay); - pj_timer_heap_poll(timer, &delay); + pj_time_val delay = {0, 100}; + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer, &delay); #endif } if (state_serv.err || state_cli.err) { - if (state_serv.err != PJ_SUCCESS) - status = state_serv.err; - else - status = state_cli.err; + if (state_serv.err != PJ_SUCCESS) + status = state_serv.err; + else + status = state_cli.err; - goto on_return; + goto on_return; } PJ_LOG(3, ("", "...Done!")); on_return: if (ssock_serv) - pj_ssl_sock_close(ssock_serv); + pj_ssl_sock_close(ssock_serv); if (asock_cli && !state_cli.err && !state_cli.done) - pj_activesock_close(asock_cli); + pj_activesock_close(asock_cli); if (timer) - pj_timer_heap_destroy(timer); + pj_timer_heap_destroy(timer); if (ioqueue) - pj_ioqueue_destroy(ioqueue); + pj_ioqueue_destroy(ioqueue); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return status; } @@ -1096,12 +1095,12 @@ static int server_non_ssl(unsigned ms_timeout) status = pj_ioqueue_create(pool, 4, &ioqueue); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } status = pj_timer_heap_create(pool, 4, &timer); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* SERVER */ @@ -1110,43 +1109,43 @@ static int server_non_ssl(unsigned ms_timeout) status = pj_sock_socket(pj_AF_INET(), pj_SOCK_STREAM(), 0, &sock); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Init bind address */ { - pj_str_t tmp_st; - pj_sockaddr_init(PJ_AF_INET, &listen_addr, pj_strset2(&tmp_st, "127.0.0.1"), 0); + pj_str_t tmp_st; + pj_sockaddr_init(PJ_AF_INET, &listen_addr, pj_strset2(&tmp_st, "127.0.0.1"), 0); } status = pj_sock_bind(sock, (pj_sockaddr_t*)&listen_addr, - pj_sockaddr_get_len((pj_sockaddr_t*)&listen_addr)); + pj_sockaddr_get_len((pj_sockaddr_t*)&listen_addr)); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } status = pj_sock_listen(sock, PJ_SOMAXCONN); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } asock_cb.on_accept_complete = &asock_on_accept_complete; status = pj_activesock_create(pool, sock, pj_SOCK_STREAM(), NULL, - ioqueue, &asock_cb, &state_serv, &asock_serv); + ioqueue, &asock_cb, &state_serv, &asock_serv); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } status = pj_activesock_start_accept(asock_serv, pool); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Update listener address */ { - int addr_len; + int addr_len; - addr_len = sizeof(listen_addr); - pj_sock_getsockname(sock, (pj_sockaddr_t*)&listen_addr, &addr_len); + addr_len = sizeof(listen_addr); + pj_sock_getsockname(sock, (pj_sockaddr_t*)&listen_addr, &addr_len); } /* CLIENT */ @@ -1167,57 +1166,57 @@ static int server_non_ssl(unsigned ms_timeout) status = pj_ssl_sock_create(pool, ¶m, &ssock_cli); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Init default bind address */ { - pj_str_t tmp_st; - pj_sockaddr_init(PJ_AF_INET, &addr, pj_strset2(&tmp_st, "127.0.0.1"), 0); + pj_str_t tmp_st; + pj_sockaddr_init(PJ_AF_INET, &addr, pj_strset2(&tmp_st, "127.0.0.1"), 0); } status = pj_ssl_sock_start_connect(ssock_cli, pool, - (pj_sockaddr_t*)&addr, - (pj_sockaddr_t*)&listen_addr, - pj_sockaddr_get_len(&listen_addr)); + (pj_sockaddr_t*)&addr, + (pj_sockaddr_t*)&listen_addr, + pj_sockaddr_get_len(&listen_addr)); if (status != PJ_EPENDING) { - goto on_return; + goto on_return; } /* Wait until everything has been sent/received or error */ while ((!state_serv.err && !state_serv.done) || (!state_cli.err && !state_cli.done)) { #ifdef PJ_SYMBIAN - pj_symbianos_poll(-1, 1000); + pj_symbianos_poll(-1, 1000); #else - pj_time_val delay = {0, 100}; - pj_ioqueue_poll(ioqueue, &delay); - pj_timer_heap_poll(timer, &delay); + pj_time_val delay = {0, 100}; + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer, &delay); #endif } if (state_serv.err || state_cli.err) { - if (state_cli.err != PJ_SUCCESS) - status = state_cli.err; - else - status = state_serv.err; + if (state_cli.err != PJ_SUCCESS) + status = state_cli.err; + else + status = state_serv.err; - goto on_return; + goto on_return; } PJ_LOG(3, ("", "...Done!")); on_return: if (asock_serv) - pj_activesock_close(asock_serv); + pj_activesock_close(asock_serv); if (ssock_cli && !state_cli.err && !state_cli.done) - pj_ssl_sock_close(ssock_cli); + pj_ssl_sock_close(ssock_cli); if (timer) - pj_timer_heap_destroy(timer); + pj_timer_heap_destroy(timer); if (ioqueue) - pj_ioqueue_destroy(ioqueue); + pj_ioqueue_destroy(ioqueue); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return status; } @@ -1248,50 +1247,50 @@ static int perf_test(unsigned clients, unsigned ms_handshake_timeout) status = pj_ioqueue_create(pool, PJ_IOQUEUE_MAX_HANDLES, &ioqueue); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } status = pj_timer_heap_create(pool, PJ_IOQUEUE_MAX_HANDLES, &timer); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Set cert */ { - pj_str_t ca_file = pj_str(CERT_CA_FILE); - pj_str_t cert_file = pj_str(CERT_FILE); - pj_str_t privkey_file = pj_str(CERT_PRIVKEY_FILE); - pj_str_t privkey_pass = pj_str(CERT_PRIVKEY_PASS); + pj_str_t ca_file = pj_str(CERT_CA_FILE); + pj_str_t cert_file = pj_str(CERT_FILE); + pj_str_t privkey_file = pj_str(CERT_PRIVKEY_FILE); + pj_str_t privkey_pass = pj_str(CERT_PRIVKEY_PASS); #if (defined(TEST_LOAD_FROM_FILES) && TEST_LOAD_FROM_FILES==1) - status = pj_ssl_cert_load_from_files(pool, &ca_file, &cert_file, - &privkey_file, &privkey_pass, - &cert); + status = pj_ssl_cert_load_from_files(pool, &ca_file, &cert_file, + &privkey_file, &privkey_pass, + &cert); #else - pj_ssl_cert_buffer ca_buf, cert_buf, privkey_buf; - - status = load_cert_to_buf(pool, &ca_file, &ca_buf); - if (status != PJ_SUCCESS) { - goto on_return; - } - - status = load_cert_to_buf(pool, &cert_file, &cert_buf); - if (status != PJ_SUCCESS) { - goto on_return; - } - - status = load_cert_to_buf(pool, &privkey_file, &privkey_buf); - if (status != PJ_SUCCESS) { - goto on_return; - } - - status = pj_ssl_cert_load_from_buffer(pool, &ca_buf, &cert_buf, - &privkey_buf, &privkey_pass, - &cert); + pj_ssl_cert_buffer ca_buf, cert_buf, privkey_buf; + + status = load_cert_to_buf(pool, &ca_file, &ca_buf); + if (status != PJ_SUCCESS) { + goto on_return; + } + + status = load_cert_to_buf(pool, &cert_file, &cert_buf); + if (status != PJ_SUCCESS) { + goto on_return; + } + + status = load_cert_to_buf(pool, &privkey_file, &privkey_buf); + if (status != PJ_SUCCESS) { + goto on_return; + } + + status = pj_ssl_cert_load_from_buffer(pool, &ca_buf, &cert_buf, + &privkey_buf, &privkey_pass, + &cert); #endif - if (status != PJ_SUCCESS) { - goto on_return; - } + if (status != PJ_SUCCESS) { + goto on_return; + } } pj_ssl_sock_param_default(¶m); @@ -1307,8 +1306,8 @@ static int perf_test(unsigned clients, unsigned ms_handshake_timeout) /* Init default bind address */ { - pj_str_t tmp_st; - pj_sockaddr_init(PJ_AF_INET, &addr, pj_strset2(&tmp_st, "127.0.0.1"), 0); + pj_str_t tmp_st; + pj_sockaddr_init(PJ_AF_INET, &addr, pj_strset2(&tmp_st, "127.0.0.1"), 0); } /* SERVER */ @@ -1320,29 +1319,29 @@ static int perf_test(unsigned clients, unsigned ms_handshake_timeout) status = pj_ssl_sock_create(pool, ¶m, &ssock_serv); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } status = pj_ssl_sock_set_certificate(ssock_serv, pool, cert); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } status = pj_ssl_sock_start_accept(ssock_serv, pool, &addr, pj_sockaddr_get_len(&addr)); if (status != PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Get listening address for clients to connect to */ { - pj_ssl_sock_info info; - char buf[64]; + pj_ssl_sock_info info; + char buf[64]; - pj_ssl_sock_get_info(ssock_serv, &info); - pj_sockaddr_cp(&listen_addr, &info.local_addr); + pj_ssl_sock_get_info(ssock_serv, &info); + pj_sockaddr_cp(&listen_addr, &info.local_addr); - pj_sockaddr_print((pj_sockaddr_t*)&listen_addr, buf, sizeof(buf), 1); - PJ_LOG(3, ("", "...Listener ready at %s", buf)); + pj_sockaddr_print((pj_sockaddr_t*)&listen_addr, buf, sizeof(buf), 1); + PJ_LOG(3, ("", "...Listener ready at %s", buf)); } @@ -1353,10 +1352,10 @@ static int perf_test(unsigned clients, unsigned ms_handshake_timeout) /* Init random seed */ { - pj_time_val now; + pj_time_val now; - pj_gettimeofday(&now); - pj_srand((unsigned)now.sec); + pj_gettimeofday(&now); + pj_srand((unsigned)now.sec); } /* Allocate SSL socket pointers and test state */ @@ -1368,97 +1367,97 @@ static int perf_test(unsigned clients, unsigned ms_handshake_timeout) /* Setup clients */ for (i = 0; i < clients; ++i) { - param.user_data = &state_cli[i]; - - state_cli[i].pool = pool; - state_cli[i].check_echo = PJ_TRUE; - state_cli[i].send_str_len = (pj_rand() % 5 + 1) * 1024 + pj_rand() % 1024; - state_cli[i].send_str = (char*)pj_pool_alloc(pool, state_cli[i].send_str_len); - { - unsigned j; - for (j = 0; j < state_cli[i].send_str_len; ++j) - state_cli[i].send_str[j] = (char)(pj_rand() % 256); - } - - status = pj_ssl_sock_create(pool, ¶m, &ssock_cli[i]); - if (status != PJ_SUCCESS) { - app_perror("...ERROR pj_ssl_sock_create()", status); - cli_err++; - clients_num--; - continue; - } - - status = pj_ssl_sock_start_connect(ssock_cli[i], pool, &addr, &listen_addr, pj_sockaddr_get_len(&addr)); - if (status == PJ_SUCCESS) { - ssl_on_connect_complete(ssock_cli[i], PJ_SUCCESS); - } else if (status == PJ_EPENDING) { - status = PJ_SUCCESS; - } else { - app_perror("...ERROR pj_ssl_sock_create()", status); - pj_ssl_sock_close(ssock_cli[i]); - ssock_cli[i] = NULL; - clients_num--; - cli_err++; - continue; - } - - /* Give chance to server to accept this client */ - { - unsigned n = 5; + param.user_data = &state_cli[i]; + + state_cli[i].pool = pool; + state_cli[i].check_echo = PJ_TRUE; + state_cli[i].send_str_len = (pj_rand() % 5 + 1) * 1024 + pj_rand() % 1024; + state_cli[i].send_str = (char*)pj_pool_alloc(pool, state_cli[i].send_str_len); + { + unsigned j; + for (j = 0; j < state_cli[i].send_str_len; ++j) + state_cli[i].send_str[j] = (char)(pj_rand() % 256); + } + + status = pj_ssl_sock_create(pool, ¶m, &ssock_cli[i]); + if (status != PJ_SUCCESS) { + app_perror("...ERROR pj_ssl_sock_create()", status); + cli_err++; + clients_num--; + continue; + } + + status = pj_ssl_sock_start_connect(ssock_cli[i], pool, &addr, &listen_addr, pj_sockaddr_get_len(&addr)); + if (status == PJ_SUCCESS) { + ssl_on_connect_complete(ssock_cli[i], PJ_SUCCESS); + } else if (status == PJ_EPENDING) { + status = PJ_SUCCESS; + } else { + app_perror("...ERROR pj_ssl_sock_create()", status); + pj_ssl_sock_close(ssock_cli[i]); + ssock_cli[i] = NULL; + clients_num--; + cli_err++; + continue; + } + + /* Give chance to server to accept this client */ + { + unsigned n = 5; #ifdef PJ_SYMBIAN - while(n && pj_symbianos_poll(-1, 1000)) - n--; + while(n && pj_symbianos_poll(-1, 1000)) + n--; #else - pj_time_val delay = {0, 100}; - while(n && pj_ioqueue_poll(ioqueue, &delay) > 0) - n--; + pj_time_val delay = {0, 100}; + while(n && pj_ioqueue_poll(ioqueue, &delay) > 0) + n--; #endif - } + } } /* Wait until everything has been sent/received or error */ while (clients_num) { #ifdef PJ_SYMBIAN - pj_symbianos_poll(-1, 1000); + pj_symbianos_poll(-1, 1000); #else - pj_time_val delay = {0, 100}; - pj_ioqueue_poll(ioqueue, &delay); - pj_timer_heap_poll(timer, &delay); + pj_time_val delay = {0, 100}; + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer, &delay); #endif } /* Clean up sockets */ { - pj_time_val delay = {0, 500}; - while (pj_ioqueue_poll(ioqueue, &delay) > 0); + pj_time_val delay = {0, 500}; + while (pj_ioqueue_poll(ioqueue, &delay) > 0); } if (state_serv.err != PJ_SUCCESS) { - status = state_serv.err; - goto on_return; + status = state_serv.err; + goto on_return; } PJ_LOG(3, ("", "...Done!")); /* SSL setup and data transfer duration */ { - pj_time_val stop; - - pj_gettimeofday(&stop); - PJ_TIME_VAL_SUB(stop, start); + pj_time_val stop; + + pj_gettimeofday(&stop); + PJ_TIME_VAL_SUB(stop, start); - PJ_LOG(3, ("", ".....Setup & data transfer duration: %d.%03ds", stop.sec, stop.msec)); + PJ_LOG(3, ("", ".....Setup & data transfer duration: %d.%03ds", stop.sec, stop.msec)); } /* Check clients status */ for (i = 0; i < clients; ++i) { - if (state_cli[i].err != PJ_SUCCESS) - cli_err++; + if (state_cli[i].err != PJ_SUCCESS) + cli_err++; - tot_sent += state_cli[1].sent; - tot_recv += state_cli[1].recv; + tot_sent += state_cli[1].sent; + tot_recv += state_cli[1].recv; } PJ_LOG(3, ("", ".....Clients: %d (%d errors)", clients, cli_err)); @@ -1466,18 +1465,18 @@ static int perf_test(unsigned clients, unsigned ms_handshake_timeout) on_return: if (ssock_serv) - pj_ssl_sock_close(ssock_serv); + pj_ssl_sock_close(ssock_serv); if (ssock_cli && state_cli) { for (i = 0; i < clients; ++i) { - if (ssock_cli[i] && !state_cli[i].err && !state_cli[i].done) - pj_ssl_sock_close(ssock_cli[i]); - } + if (ssock_cli[i] && !state_cli[i].err && !state_cli[i].done) + pj_ssl_sock_close(ssock_cli[i]); + } } if (ioqueue) - pj_ioqueue_destroy(ioqueue); + pj_ioqueue_destroy(ioqueue); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return status; } @@ -1509,18 +1508,18 @@ int ssl_sock_test(void) PJ_LOG(3,("", "..test ossl send buf")); ret = ossl_test_send_buf(); if (ret != 0) - return ret; + return ret; PJ_LOG(3,("", "..get cipher list test")); ret = get_cipher_list(); if (ret != 0) - return ret; + return ret; PJ_LOG(3,("", "..https client test")); ret = https_client_test(30000); // Ignore test result as internet connection may not be available. //if (ret != 0) - //return ret; + //return ret; #ifndef PJ_SYMBIAN @@ -1531,47 +1530,47 @@ int ssl_sock_test(void) PJ_LOG(3,("", "..echo test w/ TLSv1 and PJ_TLS_RSA_WITH_AES_256_CBC_SHA cipher")); ret = echo_test(PJ_SSL_SOCK_PROTO_TLS1, PJ_SSL_SOCK_PROTO_TLS1, - PJ_TLS_RSA_WITH_AES_256_CBC_SHA, PJ_TLS_RSA_WITH_AES_256_CBC_SHA, - PJ_FALSE, PJ_FALSE); + PJ_TLS_RSA_WITH_AES_256_CBC_SHA, PJ_TLS_RSA_WITH_AES_256_CBC_SHA, + PJ_FALSE, PJ_FALSE); if (ret != 0) - return ret; + return ret; PJ_LOG(3,("", "..echo test w/ SSLv23 and PJ_TLS_RSA_WITH_AES_256_CBC_SHA cipher")); ret = echo_test(PJ_SSL_SOCK_PROTO_SSL23, PJ_SSL_SOCK_PROTO_SSL23, - PJ_TLS_RSA_WITH_AES_256_CBC_SHA, PJ_TLS_RSA_WITH_AES_256_CBC_SHA, - PJ_FALSE, PJ_FALSE); + PJ_TLS_RSA_WITH_AES_256_CBC_SHA, PJ_TLS_RSA_WITH_AES_256_CBC_SHA, + PJ_FALSE, PJ_FALSE); if (ret != 0) - return ret; + return ret; PJ_LOG(3,("", "..echo test w/ compatible proto: server TLSv1.2 vs client TLSv1.2")); ret = echo_test(PJ_SSL_SOCK_PROTO_TLS1_2, PJ_SSL_SOCK_PROTO_TLS1_2, - -1, -1, - PJ_FALSE, PJ_FALSE); + -1, -1, + PJ_FALSE, PJ_FALSE); if (ret != 0) - return ret; + return ret; PJ_LOG(3,("", "..echo test w/ compatible proto: server TLSv1.2+1.3 vs client TLSv1.3")); ret = echo_test(PJ_SSL_SOCK_PROTO_TLS1_2 | PJ_SSL_SOCK_PROTO_TLS1_3, PJ_SSL_SOCK_PROTO_TLS1_3, - -1, -1, - PJ_FALSE, PJ_FALSE); + -1, -1, + PJ_FALSE, PJ_FALSE); if (ret != 0) - return ret; + return ret; PJ_LOG(3,("", "..echo test w/ incompatible proto: server TLSv1 vs client SSL3")); ret = echo_test(PJ_SSL_SOCK_PROTO_TLS1, PJ_SSL_SOCK_PROTO_SSL3, - PJ_TLS_RSA_WITH_DES_CBC_SHA, PJ_TLS_RSA_WITH_DES_CBC_SHA, - PJ_FALSE, PJ_FALSE); + PJ_TLS_RSA_WITH_DES_CBC_SHA, PJ_TLS_RSA_WITH_DES_CBC_SHA, + PJ_FALSE, PJ_FALSE); if (ret == 0) - return PJ_EBUG; + return PJ_EBUG; /* We can't set min/max proto for TLS protocol higher than 1.0. */ #if (PJ_SSL_SOCK_IMP != PJ_SSL_SOCK_IMP_DARWIN) PJ_LOG(3,("", "..echo test w/ incompatible proto: server TLSv1.2 vs client TLSv1.3")); ret = echo_test(PJ_SSL_SOCK_PROTO_TLS1_2, PJ_SSL_SOCK_PROTO_TLS1_3, - -1, -1, - PJ_FALSE, PJ_FALSE); + -1, -1, + PJ_FALSE, PJ_FALSE); if (ret == 0) - return PJ_EBUG; + return PJ_EBUG; #endif /* We can't seem to enable certain ciphers only. SSLSetEnabledCiphers() is @@ -1581,52 +1580,52 @@ int ssl_sock_test(void) #if (PJ_SSL_SOCK_IMP != PJ_SSL_SOCK_IMP_APPLE) PJ_LOG(3,("", "..echo test w/ incompatible ciphers")); ret = echo_test(PJ_SSL_SOCK_PROTO_DEFAULT, PJ_SSL_SOCK_PROTO_DEFAULT, - PJ_TLS_RSA_WITH_DES_CBC_SHA, PJ_TLS_RSA_WITH_AES_256_CBC_SHA, - PJ_FALSE, PJ_FALSE); + PJ_TLS_RSA_WITH_DES_CBC_SHA, PJ_TLS_RSA_WITH_AES_256_CBC_SHA, + PJ_FALSE, PJ_FALSE); if (ret == 0) - return PJ_EBUG; + return PJ_EBUG; #endif PJ_LOG(3,("", "..echo test w/ client cert required but not provided")); ret = echo_test(PJ_SSL_SOCK_PROTO_DEFAULT, PJ_SSL_SOCK_PROTO_DEFAULT, - PJ_TLS_RSA_WITH_AES_256_CBC_SHA, PJ_TLS_RSA_WITH_AES_256_CBC_SHA, - PJ_TRUE, PJ_FALSE); + PJ_TLS_RSA_WITH_AES_256_CBC_SHA, PJ_TLS_RSA_WITH_AES_256_CBC_SHA, + PJ_TRUE, PJ_FALSE); if (ret == 0) - return PJ_EBUG; + return PJ_EBUG; PJ_LOG(3,("", "..echo test w/ client cert required and provided")); ret = echo_test(PJ_SSL_SOCK_PROTO_DEFAULT, PJ_SSL_SOCK_PROTO_DEFAULT, - PJ_TLS_RSA_WITH_AES_256_CBC_SHA, PJ_TLS_RSA_WITH_AES_256_CBC_SHA, - PJ_TRUE, PJ_TRUE); + PJ_TLS_RSA_WITH_AES_256_CBC_SHA, PJ_TLS_RSA_WITH_AES_256_CBC_SHA, + PJ_TRUE, PJ_TRUE); if (ret != 0) - return ret; + return ret; #if WITH_BENCHMARK PJ_LOG(3,("", "..performance test")); ret = perf_test(PJ_IOQUEUE_MAX_HANDLES/2 - 1, 0); if (ret != 0) - return ret; + return ret; #endif PJ_LOG(3,("", "..client non-SSL (handshake timeout 5 secs)")); ret = client_non_ssl(5000); if (ret != PJ_ETIMEDOUT) - return ret; + return ret; #endif PJ_LOG(3,("", "..server non-SSL (handshake timeout 5 secs)")); ret = server_non_ssl(5000); if (ret != PJ_ETIMEDOUT) - return ret; + return ret; return 0; } -#else /* INCLUDE_SSLSOCK_TEST */ +#else /* INCLUDE_SSLSOCK_TEST */ /* To prevent warning about "translation unit is empty" * when this test is disabled. */ int dummy_ssl_sock_test; -#endif /* INCLUDE_SSLSOCK_TEST */ +#endif /* INCLUDE_SSLSOCK_TEST */ diff --git a/pjlib/src/pjlib-test/string.c b/pjlib/src/pjlib-test/string.c index 5a5c394825..f5c7c79f05 100644 --- a/pjlib/src/pjlib-test/string.c +++ b/pjlib/src/pjlib-test/string.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -23,7 +22,7 @@ #include #include "test.h" -#define THIS_FILE "string.c" +#define THIS_FILE "string.c" /** * \page page_pjlib_string_test Test: String @@ -64,11 +63,11 @@ # pragma warning(disable: 4204) #endif -#define HELLO_WORLD "Hello World" -#define HELLO_WORLD_LEN 11 -#define JUST_HELLO "Hello" -#define JUST_HELLO_LEN 5 -#define UL_VALUE 3456789012UL +#define HELLO_WORLD "Hello World" +#define HELLO_WORLD_LEN 11 +#define JUST_HELLO "Hello" +#define JUST_HELLO_LEN 5 +#define UL_VALUE 3456789012UL #if 1 /* See if both integers have the same sign */ @@ -76,7 +75,7 @@ PJ_INLINE(int) cmp(const char *expr, int i, int j) { int r = !((i>0 && j>0) || (i<0 && j<0) || (i==0 && j==0)); if (r) { - PJ_LOG(3,(THIS_FILE," error: %s: expecting %d, got %d", expr, j, i)); + PJ_LOG(3,(THIS_FILE," error: %s: expecting %d, got %d", expr, j, i)); } return r; } @@ -89,7 +88,7 @@ PJ_INLINE(int) cmp(const char *expr, int i, int j) } #endif -#define C(expr, res) cmp(#expr, expr, res) +#define C(expr, res) cmp(#expr, expr, res) static int stricmp_test(void) { @@ -97,24 +96,24 @@ static int stricmp_test(void) * In addition, it also tests pj_stricmp2(), pj_strnicmp(), and * pj_strnicmp2(). */ -#define STRTEST(res,res2,S1,S2,code) \ - do { \ - s1.ptr=S1; s1.slen=(S1)?len:0; \ - s2.ptr=S2; s2.slen=(S2)?len:0; \ - pj_get_timestamp(&t1); \ - if (C(pj_stricmp(&s1,&s2),res)) return code; \ - pj_get_timestamp(&t2); \ - pj_sub_timestamp(&t2, &t1); \ - pj_add_timestamp(&e1, &t2); \ - pj_get_timestamp(&t1); \ - if (C(pj_stricmp_alnum(&s1,&s2),res)) return code-1; \ - pj_get_timestamp(&t2); \ - pj_sub_timestamp(&t2, &t1); \ - pj_add_timestamp(&e2, &t2); \ - if (C(pj_stricmp2(&s1,S2),res2)) return code*10; \ - if (C(pj_strnicmp(&s1,&s2,len),res)) return code*100; \ - if (C(pj_strnicmp2(&s1,S2,len),res)) return code*1000; \ - } while (0) +#define STRTEST(res,res2,S1,S2,code) \ + do { \ + s1.ptr=S1; s1.slen=(S1)?len:0; \ + s2.ptr=S2; s2.slen=(S2)?len:0; \ + pj_get_timestamp(&t1); \ + if (C(pj_stricmp(&s1,&s2),res)) return code; \ + pj_get_timestamp(&t2); \ + pj_sub_timestamp(&t2, &t1); \ + pj_add_timestamp(&e1, &t2); \ + pj_get_timestamp(&t1); \ + if (C(pj_stricmp_alnum(&s1,&s2),res)) return code-1; \ + pj_get_timestamp(&t2); \ + pj_sub_timestamp(&t2, &t1); \ + pj_add_timestamp(&e2, &t2); \ + if (C(pj_stricmp2(&s1,S2),res2)) return code*10; \ + if (C(pj_strnicmp(&s1,&s2,len),res)) return code*100; \ + if (C(pj_strnicmp2(&s1,S2,len),res)) return code*1000; \ + } while (0) char *buf; pj_str_t s1, s2; @@ -237,17 +236,17 @@ static int stricmp_test(void) c2 = pj_elapsed_cycle(&zero, &e2); if (c1 < c2) { - PJ_LOG(3,("", " info: pj_stricmp_alnum is slower than pj_stricmp!")); - //return -700; + PJ_LOG(3,("", " info: pj_stricmp_alnum is slower than pj_stricmp!")); + //return -700; } /* Avoid division by zero */ if (c2 == 0) c2=1; PJ_LOG(3, ("", " time: stricmp=%u, stricmp_alnum=%u (speedup=%d.%02dx)", - c1, c2, - (c1 * 100 / c2) / 100, - (c1 * 100 / c2) % 100)); + c1, c2, + (c1 * 100 / c2) / 100, + (c1 * 100 / c2) % 100)); return 0; #undef STRTEST } @@ -256,14 +255,14 @@ static int stricmp_test(void) static int strcmp_test(void) { #define STR_TEST(res,S1,S2,code) \ - do { \ - s1.ptr=S1; s1.slen=S1?len:0; \ - s2.ptr=S2; s2.slen=S2?len:0; \ - if (C(pj_strcmp(&s1,&s2),res)) return code; \ - if (C(pj_strcmp2(&s1,S2),res)) return code-1; \ - if (C(pj_strncmp(&s1,&s2,len),res)) return code-2; \ - if (C(pj_strncmp2(&s1,S2,len),res)) return code-3; \ - } while (0) + do { \ + s1.ptr=S1; s1.slen=S1?len:0; \ + s2.ptr=S2; s2.slen=S2?len:0; \ + if (C(pj_strcmp(&s1,&s2),res)) return code; \ + if (C(pj_strcmp2(&s1,S2),res)) return code-1; \ + if (C(pj_strncmp(&s1,&s2,len),res)) return code-2; \ + if (C(pj_strncmp2(&s1,S2,len),res)) return code-3; \ + } while (0) pj_str_t s1, s2; int len; @@ -309,41 +308,41 @@ int string_test(void) */ s1 = pj_str(HELLO_WORLD); if (pj_strcmp(&s1, &hello_world) != 0) - return -10; + return -10; if (pj_stricmp(&s1, &hello_world) != 0) - return -20; + return -20; if (pj_strcmp(&s1, &just_hello) <= 0) - return -30; + return -30; if (pj_stricmp(&s1, &just_hello) <= 0) - return -40; + return -40; if (pj_strlen(&s1) != strlen(HELLO_WORLD)) - return -50; + return -50; if (pj_strncmp(&s1, &hello_world, 5) != 0) - return -60; + return -60; if (pj_strnicmp(&s1, &hello_world, 5) != 0) - return -70; + return -70; if (pj_strchr(&s1, HELLO_WORLD[1]) != s1.ptr+1) - return -80; + return -80; /* * pj_strdup() */ if (!pj_strdup(pool, &s2, &s1)) - return -100; + return -100; if (pj_strcmp(&s1, &s2) != 0) - return -110; + return -110; /* * pj_strcpy(), pj_strcat() */ s3.ptr = (char*) pj_pool_alloc(pool, 256); if (!s3.ptr) - return -200; + return -200; pj_strcpy(&s3, &s2); pj_strcat(&s3, &just_hello); if (pj_strcmp2(&s3, HELLO_WORLD JUST_HELLO) != 0) - return -210; + return -210; /* * pj_strdup2(), pj_strtrim(). @@ -351,66 +350,66 @@ int string_test(void) pj_strdup2(pool, &s4, " " HELLO_WORLD "\t "); pj_strtrim(&s4); if (pj_strcmp2(&s4, HELLO_WORLD) != 0) - return -250; + return -250; /* * pj_utoa() */ s5.ptr = (char*) pj_pool_alloc(pool, 16); if (!s5.ptr) - return -270; + return -270; s5.slen = pj_utoa(UL_VALUE, s5.ptr); /* * pj_strtoul() */ if (pj_strtoul(&s5) != UL_VALUE) - return -280; + return -280; /* * pj_strtoul2() */ s5 = pj_str("123456"); - pj_strtoul2(&s5, SNULL, 10); /* Crash test */ + pj_strtoul2(&s5, SNULL, 10); /* Crash test */ if (pj_strtoul2(&s5, &s4, 10) != 123456UL) - return -290; + return -290; if (s4.slen != 0) - return -291; + return -291; if (pj_strtoul2(&s5, &s4, 16) != 0x123456UL) - return -292; + return -292; s5 = pj_str("0123ABCD"); if (pj_strtoul2(&s5, &s4, 10) != 123) - return -293; + return -293; if (s4.slen != 4) - return -294; + return -294; if (s4.ptr == SNULL || *s4.ptr != 'A') - return -295; + return -295; if (pj_strtoul2(&s5, &s4, 16) != 0x123ABCDUL) - return -296; + return -296; if (s4.slen != 0) - return -297; + return -297; /* * pj_create_random_string() * Check that no duplicate strings are returned. */ for (i=0; i @@ -33,14 +32,14 @@ #endif -#define DO_TEST(test) do { \ - PJ_LOG(3, ("test", "Running %s...", #test)); \ - rc = test; \ - PJ_LOG(3, ("test", \ - "%s(%d)", \ - (rc ? "..ERROR" : "..success"), rc)); \ - if (rc!=0) goto on_return; \ - } while (0) +#define DO_TEST(test) do { \ + PJ_LOG(3, ("test", "Running %s...", #test)); \ + rc = test; \ + PJ_LOG(3, ("test", \ + "%s(%d)", \ + (rc ? "..ERROR" : "..success"), rc)); \ + if (rc!=0) goto on_return; \ + } while (0) pj_pool_factory *mem; @@ -49,7 +48,7 @@ int param_echo_sock_type; const char *param_echo_server = ECHO_SERVER_ADDRESS; int param_echo_port = ECHO_SERVER_START_PORT; int param_log_decor = PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_TIME | - PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_INDENT; + PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_INDENT; int null_func() { @@ -70,8 +69,8 @@ int test_inner(void) rc = pj_init(); if (rc != 0) { - app_perror("pj_init() error!!", rc); - return rc; + app_perror("pj_init() error!!", rc); + return rc; } //pj_dump_config(); @@ -213,12 +212,12 @@ int test_inner(void) pj_thread_get_stack_info(pj_thread_this(), &filename, &line); PJ_LOG(3,("test", "Stack max usage: %u, deepest: %s:%u", - pj_thread_get_stack_max_usage(pj_thread_this()), - filename, line)); + pj_thread_get_stack_max_usage(pj_thread_this()), + filename, line)); if (rc == 0) - PJ_LOG(3,("test", "Looks like everything is okay!..")); + PJ_LOG(3,("test", "Looks like everything is okay!..")); else - PJ_LOG(3,("test", "Test completed with error(s)")); + PJ_LOG(3,("test", "Test completed with error(s)")); pj_shutdown(); diff --git a/pjlib/src/pjlib-test/test.h b/pjlib/src/pjlib-test/test.h index fdd951c079..24d7e29f0c 100644 --- a/pjlib/src/pjlib-test/test.h +++ b/pjlib/src/pjlib-test/test.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -22,7 +21,7 @@ #include -#define TEST_DEFAULT 1 +#define TEST_DEFAULT 1 #define GROUP_LIBC TEST_DEFAULT #define GROUP_OS TEST_DEFAULT @@ -35,36 +34,36 @@ #endif #if defined(PJ_EXCLUDE_BENCHMARK_TESTS) && (PJ_EXCLUDE_BENCHMARK_TESTS==1) -# define WITH_BENCHMARK 0 +# define WITH_BENCHMARK 0 #else -# define WITH_BENCHMARK 1 +# define WITH_BENCHMARK 1 #endif #define INCLUDE_ERRNO_TEST GROUP_LIBC #define INCLUDE_TIMESTAMP_TEST GROUP_OS -#define INCLUDE_EXCEPTION_TEST GROUP_LIBC -#define INCLUDE_RAND_TEST GROUP_LIBC -#define INCLUDE_LIST_TEST GROUP_DATA_STRUCTURE -#define INCLUDE_HASH_TEST GROUP_DATA_STRUCTURE -#define INCLUDE_POOL_TEST GROUP_LIBC -#define INCLUDE_POOL_PERF_TEST (GROUP_LIBC && WITH_BENCHMARK) -#define INCLUDE_STRING_TEST GROUP_DATA_STRUCTURE -#define INCLUDE_FIFOBUF_TEST GROUP_DATA_STRUCTURE -#define INCLUDE_RBTREE_TEST GROUP_DATA_STRUCTURE -#define INCLUDE_TIMER_TEST GROUP_DATA_STRUCTURE +#define INCLUDE_EXCEPTION_TEST GROUP_LIBC +#define INCLUDE_RAND_TEST GROUP_LIBC +#define INCLUDE_LIST_TEST GROUP_DATA_STRUCTURE +#define INCLUDE_HASH_TEST GROUP_DATA_STRUCTURE +#define INCLUDE_POOL_TEST GROUP_LIBC +#define INCLUDE_POOL_PERF_TEST (GROUP_LIBC && WITH_BENCHMARK) +#define INCLUDE_STRING_TEST GROUP_DATA_STRUCTURE +#define INCLUDE_FIFOBUF_TEST GROUP_DATA_STRUCTURE +#define INCLUDE_RBTREE_TEST GROUP_DATA_STRUCTURE +#define INCLUDE_TIMER_TEST GROUP_DATA_STRUCTURE #define INCLUDE_ATOMIC_TEST GROUP_OS -#define INCLUDE_MUTEX_TEST (PJ_HAS_THREADS && GROUP_OS) +#define INCLUDE_MUTEX_TEST (PJ_HAS_THREADS && GROUP_OS) #define INCLUDE_SLEEP_TEST GROUP_OS #define INCLUDE_OS_TEST GROUP_OS #define INCLUDE_THREAD_TEST (PJ_HAS_THREADS && GROUP_OS) -#define INCLUDE_SOCK_TEST GROUP_NETWORK -#define INCLUDE_SOCK_PERF_TEST (GROUP_NETWORK && WITH_BENCHMARK) -#define INCLUDE_SELECT_TEST GROUP_NETWORK +#define INCLUDE_SOCK_TEST GROUP_NETWORK +#define INCLUDE_SOCK_PERF_TEST (GROUP_NETWORK && WITH_BENCHMARK) +#define INCLUDE_SELECT_TEST GROUP_NETWORK #define INCLUDE_IOQUEUE_STRESS_TEST (PJ_HAS_THREADS && GROUP_NETWORK) #define INCLUDE_UDP_IOQUEUE_TEST GROUP_NETWORK #define INCLUDE_TCP_IOQUEUE_TEST GROUP_NETWORK -#define INCLUDE_ACTIVESOCK_TEST GROUP_NETWORK -#define INCLUDE_SSLSOCK_TEST (PJ_HAS_SSL_SOCK && GROUP_NETWORK) +#define INCLUDE_ACTIVESOCK_TEST GROUP_NETWORK +#define INCLUDE_SSLSOCK_TEST (PJ_HAS_SSL_SOCK && GROUP_NETWORK) #define INCLUDE_IOQUEUE_PERF_TEST (PJ_HAS_THREADS && GROUP_NETWORK && WITH_BENCHMARK) #define INCLUDE_IOQUEUE_UNREG_TEST (PJ_HAS_THREADS && GROUP_NETWORK) #define INCLUDE_FILE_TEST GROUP_FILE @@ -127,22 +126,22 @@ extern pj_status_t app_socket(int family, int type, int proto, int port, pj_sock_t *ptr_sock); extern pj_status_t app_socketpair(int family, int type, int protocol, pj_sock_t *server, pj_sock_t *client); -extern int null_func(void); +extern int null_func(void); /* #define TRACE_(expr) PJ_LOG(3,expr) */ #define TRACE_(expr) #define HALT(msg) { PJ_LOG(3,(THIS_FILE,"%s halted",msg)); for(;;) sleep(1); } -#define CHECK(r,expr) do { \ - pj_status_t st = expr; \ - if (st!=PJ_SUCCESS && st!=PJ_EPENDING) { \ - PJ_PERROR(1,(THIS_FILE, st, #expr)); \ - retcode = r; \ - goto on_return; \ - } \ - } while (0) +#define CHECK(r,expr) do { \ + pj_status_t st = expr; \ + if (st!=PJ_SUCCESS && st!=PJ_EPENDING) { \ + PJ_PERROR(1,(THIS_FILE, st, #expr)); \ + retcode = r; \ + goto on_return; \ + } \ + } while (0) PJ_END_DECL -#endif /* __PJLIB_TEST_H__ */ +#endif /* __PJLIB_TEST_H__ */ diff --git a/pjlib/src/pjlib-test/test_wrap.cpp b/pjlib/src/pjlib-test/test_wrap.cpp index c5baab758b..a883bc2e36 100644 --- a/pjlib/src/pjlib-test/test_wrap.cpp +++ b/pjlib/src/pjlib-test/test_wrap.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjlib/src/pjlib-test/thread.c b/pjlib/src/pjlib-test/thread.c index f2ae976c37..0898da5b27 100644 --- a/pjlib/src/pjlib-test/thread.c +++ b/pjlib/src/pjlib-test/thread.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -56,7 +55,7 @@ static volatile int quit_flag=0; #if 0 -# define TRACE__(args) PJ_LOG(3,args) +# define TRACE__(args) PJ_LOG(3,args) #else # define TRACE__(args) #endif @@ -103,9 +102,9 @@ static void* thread_proc(pj_uint32_t *pcounter) /* Main loop */ for (;!quit_flag;) { - (*pcounter)++; + (*pcounter)++; //Must sleep if platform doesn't do time-slicing. - //pj_thread_sleep(0); + //pj_thread_sleep(0); } TRACE__((THIS_FILE, " thread %d quitting..", id)); @@ -126,20 +125,20 @@ static int simple_thread(const char *title, unsigned flags) pool = pj_pool_create(mem, NULL, 4000, 4000, NULL); if (!pool) - return -1000; + return -1000; quit_flag = 0; TRACE__((THIS_FILE, " Creating thread 0..")); rc = pj_thread_create(pool, "thread", (pj_thread_proc*)&thread_proc, - &counter, - PJ_THREAD_DEFAULT_STACK_SIZE, - flags, - &thread); + &counter, + PJ_THREAD_DEFAULT_STACK_SIZE, + flags, + &thread); if (rc != PJ_SUCCESS) { - app_perror("...error: unable to create thread", rc); - return -1010; + app_perror("...error: unable to create thread", rc); + return -1010; } TRACE__((THIS_FILE, " Main thread waiting..")); @@ -148,17 +147,17 @@ static int simple_thread(const char *title, unsigned flags) if (flags & PJ_THREAD_SUSPENDED) { - /* Check that counter is still zero */ - if (counter != 0) { - PJ_LOG(3,(THIS_FILE, "...error: thread is not suspended")); - return -1015; - } - - rc = pj_thread_resume(thread); - if (rc != PJ_SUCCESS) { - app_perror("...error: resume thread error", rc); - return -1020; - } + /* Check that counter is still zero */ + if (counter != 0) { + PJ_LOG(3,(THIS_FILE, "...error: thread is not suspended")); + return -1015; + } + + rc = pj_thread_resume(thread); + if (rc != PJ_SUCCESS) { + app_perror("...error: resume thread error", rc); + return -1020; + } } PJ_LOG(3,(THIS_FILE, "..waiting for thread to quit..")); @@ -171,8 +170,8 @@ static int simple_thread(const char *title, unsigned flags) pj_pool_release(pool); if (counter == 0) { - PJ_LOG(3,(THIS_FILE, "...error: thread is not running")); - return -1025; + PJ_LOG(3,(THIS_FILE, "...error: thread is not running")); + return -1025; } PJ_LOG(3,(THIS_FILE, "...%s success", title)); @@ -204,7 +203,7 @@ static int timeslice_test(void) for (i=0; i i) { PJ_LOG(3,(THIS_FILE, "....ERROR! Thread %d-th is not suspended!", - i)); + i)); return -30; } } /* Now resume all threads. */ for (i=0; i= 50) { PJ_LOG(3,(THIS_FILE, - "...ERROR: thread didn't have equal timeslice!")); + "...ERROR: thread didn't have equal timeslice!")); PJ_LOG(3,(THIS_FILE, - ".....lowest counter=%u, highest counter=%u, diff=%u%%", + ".....lowest counter=%u, highest counter=%u, diff=%u%%", lowest, highest, diff)); return -80; } else { @@ -314,15 +313,15 @@ int thread_test(void) rc = simple_thread("simple thread test", 0); if (rc != PJ_SUCCESS) - return rc; + return rc; rc = simple_thread("suspended thread test", PJ_THREAD_SUSPENDED); if (rc != PJ_SUCCESS) - return rc; + return rc; rc = timeslice_test(); if (rc != PJ_SUCCESS) - return rc; + return rc; return rc; } @@ -332,6 +331,6 @@ int thread_test(void) * when this test is disabled. */ int dummy_thread_test; -#endif /* INCLUDE_THREAD_TEST */ +#endif /* INCLUDE_THREAD_TEST */ diff --git a/pjlib/src/pjlib-test/timer.c b/pjlib/src/pjlib-test/timer.c index 419449657a..444aed055c 100644 --- a/pjlib/src/pjlib-test/timer.c +++ b/pjlib/src/pjlib-test/timer.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,13 +35,13 @@ #include -#define LOOP 16 -#define MIN_COUNT 250 -#define MAX_COUNT (LOOP * MIN_COUNT) -#define MIN_DELAY 2 -#define D (MAX_COUNT / 32000) -#define DELAY (D < MIN_DELAY ? MIN_DELAY : D) -#define THIS_FILE "timer_test" +#define LOOP 16 +#define MIN_COUNT 250 +#define MAX_COUNT (LOOP * MIN_COUNT) +#define MIN_DELAY 2 +#define D (MAX_COUNT / 32000) +#define DELAY (D < MIN_DELAY ? MIN_DELAY : D) +#define THIS_FILE "timer_test" static void timer_callback(pj_timer_heap_t *ht, pj_timer_entry *e) @@ -68,116 +67,116 @@ static int test_timer_heap(void) size = pj_timer_heap_mem_size(MAX_COUNT)+MAX_COUNT*sizeof(pj_timer_entry); pool = pj_pool_create( mem, NULL, size, 4000, NULL); if (!pool) { - PJ_LOG(3,("test", "...error: unable to create pool of %u bytes", - size)); - return -10; + PJ_LOG(3,("test", "...error: unable to create pool of %u bytes", + size)); + return -10; } entry = (pj_timer_entry*)pj_pool_calloc(pool, MAX_COUNT, sizeof(*entry)); if (!entry) - return -20; + return -20; for (i=0; i 0) { - t_poll.u32.lo += (t2.u32.lo - t1.u32.lo); - early += rc; - } - } - - // Set the time where all timers should finish - pj_gettimeofday(&expire); - delay.sec = DELAY; - delay.msec = 0; - PJ_TIME_VAL_ADD(expire, delay); - - // Wait unfil all timers finish, cancel some of them. - do { - int index = pj_rand() % count; - pj_get_timestamp(&t1); - rc = pj_timer_heap_cancel(timer, &entry[index]); - pj_get_timestamp(&t2); - if (rc > 0) { - cancelled += rc; - t_cancel.u32.lo += (t2.u32.lo - t1.u32.lo); - } - - pj_gettimeofday(&now); - - pj_get_timestamp(&t1); + int early = 0; + //int done=0; + int cancelled=0; + int rc; + pj_timestamp t1, t2, t_sched, t_cancel, t_poll; + pj_time_val now, expire; + + pj_gettimeofday(&now); + pj_srand(now.sec); + t_sched.u32.lo = t_cancel.u32.lo = t_poll.u32.lo = 0; + + // Register timers + for (j=0; j<(int)count; ++j) { + delay.sec = pj_rand() % DELAY; + delay.msec = pj_rand() % 1000; + + // Schedule timer + pj_get_timestamp(&t1); + rc = pj_timer_heap_schedule(timer, &entry[j], &delay); + if (rc != 0) + return -40; + pj_get_timestamp(&t2); + + t_sched.u32.lo += (t2.u32.lo - t1.u32.lo); + + // Poll timers. + pj_get_timestamp(&t1); + rc = pj_timer_heap_poll(timer, NULL); + pj_get_timestamp(&t2); + if (rc > 0) { + t_poll.u32.lo += (t2.u32.lo - t1.u32.lo); + early += rc; + } + } + + // Set the time where all timers should finish + pj_gettimeofday(&expire); + delay.sec = DELAY; + delay.msec = 0; + PJ_TIME_VAL_ADD(expire, delay); + + // Wait unfil all timers finish, cancel some of them. + do { + int index = pj_rand() % count; + pj_get_timestamp(&t1); + rc = pj_timer_heap_cancel(timer, &entry[index]); + pj_get_timestamp(&t2); + if (rc > 0) { + cancelled += rc; + t_cancel.u32.lo += (t2.u32.lo - t1.u32.lo); + } + + pj_gettimeofday(&now); + + pj_get_timestamp(&t1); #if defined(PJ_SYMBIAN) && PJ_SYMBIAN!=0 - /* On Symbian, we must use OS poll (Active Scheduler poll) since - * timer is implemented using Active Object. - */ - rc = 0; - while (pj_symbianos_poll(-1, 0)) - ++rc; + /* On Symbian, we must use OS poll (Active Scheduler poll) since + * timer is implemented using Active Object. + */ + rc = 0; + while (pj_symbianos_poll(-1, 0)) + ++rc; #else - rc = pj_timer_heap_poll(timer, NULL); + rc = pj_timer_heap_poll(timer, NULL); #endif - pj_get_timestamp(&t2); - if (rc > 0) { - //done += rc; - t_poll.u32.lo += (t2.u32.lo - t1.u32.lo); - } - - } while (PJ_TIME_VAL_LTE(now, expire)&&pj_timer_heap_count(timer) > 0); - - if (pj_timer_heap_count(timer)) { - PJ_LOG(3, (THIS_FILE, "ERROR: %d timers left", - pj_timer_heap_count(timer))); - ++err; - } - t_sched.u32.lo /= count; - t_cancel.u32.lo /= count; - t_poll.u32.lo /= count; - PJ_LOG(4, (THIS_FILE, - "...ok (count:%d, early:%d, cancelled:%d, " - "sched:%d, cancel:%d poll:%d)", - count, early, cancelled, t_sched.u32.lo, t_cancel.u32.lo, - t_poll.u32.lo)); - - count = count * 2; - if (count > MAX_COUNT) - break; + pj_get_timestamp(&t2); + if (rc > 0) { + //done += rc; + t_poll.u32.lo += (t2.u32.lo - t1.u32.lo); + } + + } while (PJ_TIME_VAL_LTE(now, expire)&&pj_timer_heap_count(timer) > 0); + + if (pj_timer_heap_count(timer)) { + PJ_LOG(3, (THIS_FILE, "ERROR: %d timers left", + pj_timer_heap_count(timer))); + ++err; + } + t_sched.u32.lo /= count; + t_cancel.u32.lo /= count; + t_poll.u32.lo /= count; + PJ_LOG(4, (THIS_FILE, + "...ok (count:%d, early:%d, cancelled:%d, " + "sched:%d, cancel:%d poll:%d)", + count, early, cancelled, t_sched.u32.lo, t_cancel.u32.lo, + t_poll.u32.lo)); + + count = count * 2; + if (count > MAX_COUNT) + break; } pj_pool_release(pool); @@ -207,21 +206,21 @@ static int test_timer_heap(void) * bug in the implementation (note that race message is ok). */ #define RANDOMIZED_TEST 1 -#define SIMULATE_CRASH PJ_TIMER_USE_COPY +#define SIMULATE_CRASH PJ_TIMER_USE_COPY #if RANDOMIZED_TEST - #define ST_STRESS_THREAD_COUNT 20 - #define ST_POLL_THREAD_COUNT 0 - #define ST_CANCEL_THREAD_COUNT 0 + #define ST_STRESS_THREAD_COUNT 20 + #define ST_POLL_THREAD_COUNT 0 + #define ST_CANCEL_THREAD_COUNT 0 #else - #define ST_STRESS_THREAD_COUNT 0 - #define ST_POLL_THREAD_COUNT 10 - #define ST_CANCEL_THREAD_COUNT 10 + #define ST_STRESS_THREAD_COUNT 0 + #define ST_POLL_THREAD_COUNT 10 + #define ST_CANCEL_THREAD_COUNT 10 #endif -#define ST_ENTRY_COUNT 10000 -#define ST_DURATION 30000 -#define ST_ENTRY_MAX_TIMEOUT_MS ST_DURATION/10 +#define ST_ENTRY_COUNT 10000 +#define ST_DURATION 30000 +#define ST_ENTRY_MAX_TIMEOUT_MS ST_DURATION/10 /* Number of group lock, may be zero, shared by timer entries, group lock * can be useful to evaluate poll vs cancel race condition scenario, i.e: @@ -248,8 +247,8 @@ struct thread_param pj_atomic_t *idx; struct { - pj_bool_t is_poll; - unsigned cnt; + pj_bool_t is_poll; + unsigned cnt; } stat[ST_POLL_THREAD_COUNT + ST_CANCEL_THREAD_COUNT + 1]; /* Plus one here to avoid compile warning of zero-sized array */ }; @@ -262,8 +261,8 @@ static pj_status_t st_schedule_entry(pj_timer_heap_t *ht, pj_timer_entry *e) struct thread_param *tparam = (struct thread_param *)e->user_data; if (ST_ENTRY_GROUP_LOCK_COUNT && pj_rand() % 10) { - /* About 90% of entries should have group lock */ - grp_lock = tparam->grp_locks[pj_rand() % ST_ENTRY_GROUP_LOCK_COUNT]; + /* About 90% of entries should have group lock */ + grp_lock = tparam->grp_locks[pj_rand() % ST_ENTRY_GROUP_LOCK_COUNT]; } delay.msec = pj_rand() % ST_ENTRY_MAX_TIMEOUT_MS; @@ -285,7 +284,7 @@ static void st_entry_callback(pj_timer_heap_t *ht, pj_timer_entry *e) #if RANDOMIZED_TEST /* Make sure the flag has been set. */ while (pj_atomic_get(tparam->status[e - tparam->entries]) != 1) - pj_thread_sleep(10); + pj_thread_sleep(10); pj_atomic_set(tparam->status[e - tparam->entries], 0); #endif @@ -297,7 +296,7 @@ static void st_entry_callback(pj_timer_heap_t *ht, pj_timer_entry *e) /* reschedule entry */ if (!ST_STRESS_THREAD_COUNT) - st_schedule_entry(ht, e); + st_schedule_entry(ht, e); } /* Randomized stress worker thread function. */ @@ -305,10 +304,10 @@ static int stress_worker(void *arg) { /* Enumeration of possible task. */ enum { - SCHEDULING = 0, - CANCELLING = 1, - POLLING = 2, - NOTHING = 3 + SCHEDULING = 0, + CANCELLING = 1, + POLLING = 2, + NOTHING = 3 }; /* Probability of a certain task being chosen. * The first number indicates the probability of the first task, @@ -321,89 +320,89 @@ static int stress_worker(void *arg) t_idx = pj_atomic_inc_and_get(tparam->idx); PJ_LOG(4,("test", "...thread #%d (random) started", t_idx)); while (!tparam->stopping) { - int job, task; - int idx, count; - pj_status_t prev_status, status; - - /* Randomly choose which task to do */ - job = pj_rand() % 100; - if (job < prob[0]) task = SCHEDULING; - else if (job < (prob[0] + prob[1])) task = CANCELLING; - else if (job < (prob[0] + prob[1] + prob[2])) task = POLLING; - else task = NOTHING; + int job, task; + int idx, count; + pj_status_t prev_status, status; + + /* Randomly choose which task to do */ + job = pj_rand() % 100; + if (job < prob[0]) task = SCHEDULING; + else if (job < (prob[0] + prob[1])) task = CANCELLING; + else if (job < (prob[0] + prob[1] + prob[2])) task = POLLING; + else task = NOTHING; - idx = pj_rand() % ST_ENTRY_COUNT; - prev_status = pj_atomic_get(tparam->status[idx]); - if (task == SCHEDULING) { - if (prev_status != 0) continue; - status = st_schedule_entry(tparam->timer, &tparam->entries[idx]); - if (prev_status == 0 && status != PJ_SUCCESS) { - /* To make sure the flag has been set. */ - pj_thread_sleep(20); - if (pj_atomic_get(tparam->status[idx]) == 1) { - /* Race condition with another scheduling. */ - PJ_LOG(3,("test", "race schedule-schedule %d: %p", - idx, &tparam->entries[idx])); - } else { - if (tparam->err != 0) tparam->err = -210; - PJ_LOG(3,("test", "error: failed to schedule entry %d: %p", - idx, &tparam->entries[idx])); - } - } else if (prev_status == 1 && status == PJ_SUCCESS) { - /* Race condition with another cancellation or - * timer poll. - */ - pj_thread_sleep(20); - PJ_LOG(3,("test", "race schedule-cancel/poll %d: %p", - idx, &tparam->entries[idx])); - } - if (status == PJ_SUCCESS) { - pj_atomic_set(tparam->status[idx], 1); - pj_atomic_inc(tparam->n_sched); - } - } else if (task == CANCELLING) { - count = pj_timer_heap_cancel_if_active(tparam->timer, - &tparam->entries[idx], 10); - if (prev_status == 0 && count > 0) { - /* To make sure the flag has been set. */ - pj_thread_sleep(20); - if (pj_atomic_get(tparam->status[idx]) == 1) { - /* Race condition with scheduling. */ - PJ_LOG(3,("test", "race cancel-schedule %d: %p", - idx, &tparam->entries[idx])); - } else { - if (tparam->err != 0) tparam->err = -220; - PJ_LOG(3,("test", "error: cancelling invalid entry %d: %p", - idx, &tparam->entries[idx])); - } - } else if (prev_status == 1 && count == 0) { - /* To make sure the flag has been cleared. */ - pj_thread_sleep(20); - if (pj_atomic_get(tparam->status[idx]) == 0) { - /* Race condition with polling. */ - PJ_LOG(3,("test", "race cancel-poll %d: %p", - idx, &tparam->entries[idx])); - } else { - if (tparam->err != 0) tparam->err = -230; - PJ_LOG(3,("test", "error: failed to cancel entry %d: %p", - idx, &tparam->entries[idx])); - } - } - if (count > 0) { - /* Make sure the flag has been set. */ - while (pj_atomic_get(tparam->status[idx]) != 1) - pj_thread_sleep(10); - pj_atomic_set(tparam->status[idx], 0); - pj_atomic_inc(tparam->n_cancel); - } - } else if (task == POLLING) { - count = pj_timer_heap_poll(tparam->timer, NULL); - for (i = 0; i < count; i++) { - pj_atomic_inc_and_get(tparam->n_poll); - } - } else { - pj_thread_sleep(10); - } + idx = pj_rand() % ST_ENTRY_COUNT; + prev_status = pj_atomic_get(tparam->status[idx]); + if (task == SCHEDULING) { + if (prev_status != 0) continue; + status = st_schedule_entry(tparam->timer, &tparam->entries[idx]); + if (prev_status == 0 && status != PJ_SUCCESS) { + /* To make sure the flag has been set. */ + pj_thread_sleep(20); + if (pj_atomic_get(tparam->status[idx]) == 1) { + /* Race condition with another scheduling. */ + PJ_LOG(3,("test", "race schedule-schedule %d: %p", + idx, &tparam->entries[idx])); + } else { + if (tparam->err != 0) tparam->err = -210; + PJ_LOG(3,("test", "error: failed to schedule entry %d: %p", + idx, &tparam->entries[idx])); + } + } else if (prev_status == 1 && status == PJ_SUCCESS) { + /* Race condition with another cancellation or + * timer poll. + */ + pj_thread_sleep(20); + PJ_LOG(3,("test", "race schedule-cancel/poll %d: %p", + idx, &tparam->entries[idx])); + } + if (status == PJ_SUCCESS) { + pj_atomic_set(tparam->status[idx], 1); + pj_atomic_inc(tparam->n_sched); + } + } else if (task == CANCELLING) { + count = pj_timer_heap_cancel_if_active(tparam->timer, + &tparam->entries[idx], 10); + if (prev_status == 0 && count > 0) { + /* To make sure the flag has been set. */ + pj_thread_sleep(20); + if (pj_atomic_get(tparam->status[idx]) == 1) { + /* Race condition with scheduling. */ + PJ_LOG(3,("test", "race cancel-schedule %d: %p", + idx, &tparam->entries[idx])); + } else { + if (tparam->err != 0) tparam->err = -220; + PJ_LOG(3,("test", "error: cancelling invalid entry %d: %p", + idx, &tparam->entries[idx])); + } + } else if (prev_status == 1 && count == 0) { + /* To make sure the flag has been cleared. */ + pj_thread_sleep(20); + if (pj_atomic_get(tparam->status[idx]) == 0) { + /* Race condition with polling. */ + PJ_LOG(3,("test", "race cancel-poll %d: %p", + idx, &tparam->entries[idx])); + } else { + if (tparam->err != 0) tparam->err = -230; + PJ_LOG(3,("test", "error: failed to cancel entry %d: %p", + idx, &tparam->entries[idx])); + } + } + if (count > 0) { + /* Make sure the flag has been set. */ + while (pj_atomic_get(tparam->status[idx]) != 1) + pj_thread_sleep(10); + pj_atomic_set(tparam->status[idx], 0); + pj_atomic_inc(tparam->n_cancel); + } + } else if (task == POLLING) { + count = pj_timer_heap_poll(tparam->timer, NULL); + for (i = 0; i < count; i++) { + pj_atomic_inc_and_get(tparam->n_poll); + } + } else { + pj_thread_sleep(10); + } } PJ_LOG(4,("test", "...thread #%d (poll) stopped", t_idx)); @@ -421,16 +420,16 @@ static int poll_worker(void *arg) PJ_LOG(4,("test", "...thread #%d (poll) started", idx)); while (!tparam->stopping) { - unsigned count; - count = pj_timer_heap_poll(tparam->timer, NULL); - if (count > 0) { - /* Count expired entries */ - PJ_LOG(5,("test", "...thread #%d called %d entries", - idx, count)); - tparam->stat[idx].cnt += count; - } else { - pj_thread_sleep(10); - } + unsigned count; + count = pj_timer_heap_poll(tparam->timer, NULL); + if (count > 0) { + /* Count expired entries */ + PJ_LOG(5,("test", "...thread #%d called %d entries", + idx, count)); + tparam->stat[idx].cnt += count; + } else { + pj_thread_sleep(10); + } } PJ_LOG(4,("test", "...thread #%d (poll) stopped", idx)); @@ -448,20 +447,20 @@ static int cancel_worker(void *arg) PJ_LOG(4,("test", "...thread #%d (cancel) started", idx)); while (!tparam->stopping) { - int count; - pj_timer_entry *e = &tparam->entries[pj_rand() % ST_ENTRY_COUNT]; - - count = pj_timer_heap_cancel_if_active(tparam->timer, e, 2); - if (count > 0) { - /* Count cancelled entries */ - PJ_LOG(5,("test", "...thread #%d cancelled %d entries", - idx, count)); - tparam->stat[idx].cnt += count; - - /* Reschedule entry after some delay */ - pj_thread_sleep(pj_rand() % 100); - st_schedule_entry(tparam->timer, e); - } + int count; + pj_timer_entry *e = &tparam->entries[pj_rand() % ST_ENTRY_COUNT]; + + count = pj_timer_heap_cancel_if_active(tparam->timer, e, 2); + if (count > 0) { + /* Count cancelled entries */ + PJ_LOG(5,("test", "...thread #%d cancelled %d entries", + idx, count)); + tparam->stat[idx].cnt += count; + + /* Reschedule entry after some delay */ + pj_thread_sleep(pj_rand() % 100); + st_schedule_entry(tparam->timer, e); + } } PJ_LOG(4,("test", "...thread #%d (cancel) stopped", idx)); @@ -473,7 +472,7 @@ static int timer_stress_test(void) unsigned count = 0, n_sched = 0, n_cancel = 0, n_poll = 0; int i; pj_timer_entry *entries = NULL; - pj_atomic_t **entries_status = NULL; + pj_atomic_t **entries_status = NULL; pj_grp_lock_t **grp_locks = NULL; pj_pool_t *pool; pj_timer_heap_t *timer = NULL; @@ -498,9 +497,9 @@ static int timer_stress_test(void) pool = pj_pool_create( mem, NULL, 128, 128, NULL); if (!pool) { - PJ_LOG(3,("test", "...error: unable to create pool")); - err = -10; - goto on_return; + PJ_LOG(3,("test", "...error: unable to create pool")); + err = -10; + goto on_return; } /* Create timer heap. @@ -510,69 +509,69 @@ static int timer_stress_test(void) status = pj_timer_heap_create(pool, ST_ENTRY_COUNT/64, &timer); if (status != PJ_SUCCESS) { app_perror("...error: unable to create timer heap", status); - err = -20; - goto on_return; + err = -20; + goto on_return; } /* Set recursive lock for the timer heap. */ status = pj_lock_create_recursive_mutex( pool, "lock", &timer_lock); if (status != PJ_SUCCESS) { app_perror("...error: unable to create lock", status); - err = -30; - goto on_return; + err = -30; + goto on_return; } pj_timer_heap_set_lock(timer, timer_lock, PJ_TRUE); /* Create group locks for the timer entry. */ if (ST_ENTRY_GROUP_LOCK_COUNT) { - grp_locks = (pj_grp_lock_t**) - pj_pool_calloc(pool, ST_ENTRY_GROUP_LOCK_COUNT, - sizeof(pj_grp_lock_t*)); - tparam.grp_locks = grp_locks; + grp_locks = (pj_grp_lock_t**) + pj_pool_calloc(pool, ST_ENTRY_GROUP_LOCK_COUNT, + sizeof(pj_grp_lock_t*)); + tparam.grp_locks = grp_locks; } for (i=0; i 0 && ((j-1) % mult != 0)) { - print_bench(test_type, freq, t1, i, j); + print_bench(test_type, freq, t1, i, j); } return 0; } @@ -893,61 +892,61 @@ static int timer_bench_test(void) status = pj_get_timestamp_freq(&freq); if (status != PJ_SUCCESS) { - PJ_LOG(3,("test", "...error: unable to get timestamp freq")); - err = -10; - goto on_return; + PJ_LOG(3,("test", "...error: unable to get timestamp freq")); + err = -10; + goto on_return; } pool = pj_pool_create( mem, NULL, 128, 128, NULL); if (!pool) { - PJ_LOG(3,("test", "...error: unable to create pool")); - err = -20; - goto on_return; + PJ_LOG(3,("test", "...error: unable to create pool")); + err = -20; + goto on_return; } /* Create timer heap.*/ status = pj_timer_heap_create(pool, BT_ENTRY_COUNT/64, &timer); if (status != PJ_SUCCESS) { app_perror("...error: unable to create timer heap", status); - err = -30; - goto on_return; + err = -30; + goto on_return; } /* Create and schedule timer entries */ entries = (pj_timer_entry*)pj_pool_calloc(pool, BT_ENTRY_COUNT, - sizeof(*entries)); + sizeof(*entries)); if (!entries) { - err = -40; - goto on_return; + err = -40; + goto on_return; } PJ_LOG(3,("test", "....random scheduling/cancelling test..")); for (i = 0; i < BT_REPEAT_RANDOM_TEST; ++i) { - PJ_LOG(3,("test", " test %d of %d..", i+1, BT_REPEAT_RANDOM_TEST)); - err = bench_test(timer, entries, freq, RANDOM_SCH); - if (err < 0) - goto on_return; + PJ_LOG(3,("test", " test %d of %d..", i+1, BT_REPEAT_RANDOM_TEST)); + err = bench_test(timer, entries, freq, RANDOM_SCH); + if (err < 0) + goto on_return; - err = bench_test(timer, entries, freq, RANDOM_CAN); - if (err < 0) - goto on_return; + err = bench_test(timer, entries, freq, RANDOM_CAN); + if (err < 0) + goto on_return; } PJ_LOG(3,("test", "....increment scheduling/cancelling test..")); for (i = 0; i < BT_REPEAT_INC_TEST; ++i) { - PJ_LOG(3,("test", " test %d of %d..", i+1, BT_REPEAT_INC_TEST)); - err = bench_test(timer, entries, freq, INCREMENT_SCH); - if (err < 0) - goto on_return; + PJ_LOG(3,("test", " test %d of %d..", i+1, BT_REPEAT_INC_TEST)); + err = bench_test(timer, entries, freq, INCREMENT_SCH); + if (err < 0) + goto on_return; - err = bench_test(timer, entries, freq, INCREMENT_CAN); - if (err < 0) - goto on_return; + err = bench_test(timer, entries, freq, INCREMENT_CAN); + if (err < 0) + goto on_return; } on_return: PJ_LOG(3,("test", "...Cleaning up resources")); if (pool) - pj_pool_safe_release(&pool); + pj_pool_safe_release(&pool); return err; } @@ -957,16 +956,16 @@ int timer_test() rc = test_timer_heap(); if (rc != 0) - return rc; + return rc; rc = timer_stress_test(); if (rc != 0) - return rc; + return rc; #if WITH_BENCHMARK rc = timer_bench_test(); if (rc != 0) - return rc; + return rc; #endif return 0; @@ -977,6 +976,6 @@ int timer_test() * when this test is disabled. */ int dummy_timer_test; -#endif /* INCLUDE_TIMER_TEST */ +#endif /* INCLUDE_TIMER_TEST */ diff --git a/pjlib/src/pjlib-test/timestamp.c b/pjlib/src/pjlib-test/timestamp.c index ac0ee836b1..b070240720 100644 --- a/pjlib/src/pjlib-test/timestamp.c +++ b/pjlib/src/pjlib-test/timestamp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -62,7 +61,7 @@ static int timestamp_accuracy() /* Get the start time */ pj_gettimeofday(&tvtmp); do { - pj_gettimeofday(&tv1); + pj_gettimeofday(&tv1); } while (PJ_TIME_VAL_EQ(tvtmp, tv1)); pj_get_timestamp(&t1); @@ -72,7 +71,7 @@ static int timestamp_accuracy() /* Get end time */ pj_gettimeofday(&tvtmp); do { - pj_gettimeofday(&tv2); + pj_gettimeofday(&tv2); } while (PJ_TIME_VAL_EQ(tvtmp, tv2)); pj_get_timestamp(&t2); @@ -84,25 +83,25 @@ static int timestamp_accuracy() tics = t2.u64 - t1.u64; diff = tics - (msec * freq.u64 / 1000); if (diff < 0) - diff = -diff; + diff = -diff; /* Only allow 1 msec mismatch */ if (diff > (pj_int64_t)(freq.u64 / 1000)) { - PJ_LOG(3,(THIS_FILE, "....error: timestamp drifted by %d usec after " - "%d msec", - (pj_uint32_t)(diff * 1000000 / freq.u64), - msec)); - return -2000; + PJ_LOG(3,(THIS_FILE, "....error: timestamp drifted by %d usec after " + "%d msec", + (pj_uint32_t)(diff * 1000000 / freq.u64), + msec)); + return -2000; /* Otherwise just print warning if timestamp drifted by >1 usec */ } else if (diff > (pj_int64_t)(freq.u64 / 1000000)) { - PJ_LOG(3,(THIS_FILE, "....warning: timestamp drifted by %d usec after " - "%d msec", - (pj_uint32_t)(diff * 1000000 / freq.u64), - msec)); + PJ_LOG(3,(THIS_FILE, "....warning: timestamp drifted by %d usec after " + "%d msec", + (pj_uint32_t)(diff * 1000000 / freq.u64), + msec)); } else { - PJ_LOG(3,(THIS_FILE, "....good. Timestamp is accurate down to" - " nearest usec.")); + PJ_LOG(3,(THIS_FILE, "....good. Timestamp is accurate down to" + " nearest usec.")); } return 0; @@ -122,12 +121,12 @@ int timestamp_test(void) /* Get and display timestamp frequency. */ if ((rc=pj_get_timestamp_freq(&freq)) != PJ_SUCCESS) { - app_perror("...ERROR: get timestamp freq", rc); - return -1000; + app_perror("...ERROR: get timestamp freq", rc); + return -1000; } PJ_LOG(3,(THIS_FILE, "....frequency: hiword=%lu loword=%lu", - freq.u32.hi, freq.u32.lo)); + freq.u32.hi, freq.u32.lo)); PJ_LOG(3,(THIS_FILE, "...checking if time can run backwards (pls wait)..")); @@ -138,42 +137,42 @@ int timestamp_test(void) */ rc = pj_get_timestamp(&t1); if (rc != PJ_SUCCESS) { - app_perror("...ERROR: pj_get_timestamp", rc); - return -1001; + app_perror("...ERROR: pj_get_timestamp", rc); + return -1001; } rc = pj_gettimeofday(&tv1); if (rc != PJ_SUCCESS) { - app_perror("...ERROR: pj_gettimeofday", rc); - return -1002; + app_perror("...ERROR: pj_gettimeofday", rc); + return -1002; } for (i=0; i= t1. */ - if (t2.u32.hi < t1.u32.hi || - (t2.u32.hi == t1.u32.hi && t2.u32.lo < t1.u32.lo)) - { - PJ_LOG(3,(THIS_FILE, "...ERROR: timestamp run backwards!")); - return -1005; - } - - /* compare tv2 with tv1, expecting tv2 >= tv1. */ - if (PJ_TIME_VAL_LT(tv2, tv1)) { - PJ_LOG(3,(THIS_FILE, "...ERROR: time run backwards!")); - return -1006; - } + rc = pj_get_timestamp(&t2); + if (rc != PJ_SUCCESS) { + app_perror("...ERROR: pj_get_timestamp", rc); + return -1003; + } + rc = pj_gettimeofday(&tv2); + if (rc != PJ_SUCCESS) { + app_perror("...ERROR: pj_gettimeofday", rc); + return -1004; + } + + /* compare t2 with t1, expecting t2 >= t1. */ + if (t2.u32.hi < t1.u32.hi || + (t2.u32.hi == t1.u32.hi && t2.u32.lo < t1.u32.lo)) + { + PJ_LOG(3,(THIS_FILE, "...ERROR: timestamp run backwards!")); + return -1005; + } + + /* compare tv2 with tv1, expecting tv2 >= tv1. */ + if (PJ_TIME_VAL_LT(tv2, tv1)) { + PJ_LOG(3,(THIS_FILE, "...ERROR: time run backwards!")); + return -1006; + } } /* @@ -184,16 +183,16 @@ int timestamp_test(void) /* Mark start time. */ if ((rc=pj_get_timestamp(&t1)) != PJ_SUCCESS) { - app_perror("....error: cat't get timestamp", rc); - return -1010; + app_perror("....error: cat't get timestamp", rc); + return -1010; } /* Loop.. */ for (i=0; i<1000000; ++i) { - /* Try to do something so that smart compilers wont - * remove this silly loop. - */ - null_func(); + /* Try to do something so that smart compilers wont + * remove this silly loop. + */ + null_func(); } pj_thread_sleep(0); @@ -209,18 +208,18 @@ int timestamp_test(void) * This should be good even on 50Mhz embedded powerpc. */ if (elapsed < 1 || elapsed > 1000000) { - PJ_LOG(3,(THIS_FILE, "....error: elapsed time outside window (%u, " - "t1.u32.hi=%u, t1.u32.lo=%u, " - "t2.u32.hi=%u, t2.u32.lo=%u)", - elapsed, - t1.u32.hi, t1.u32.lo, t2.u32.hi, t2.u32.lo)); - return -1030; + PJ_LOG(3,(THIS_FILE, "....error: elapsed time outside window (%u, " + "t1.u32.hi=%u, t1.u32.lo=%u, " + "t2.u32.hi=%u, t2.u32.lo=%u)", + elapsed, + t1.u32.hi, t1.u32.lo, t2.u32.hi, t2.u32.lo)); + return -1030; } /* Testing time/timestamp accuracy */ rc = timestamp_accuracy(); if (rc != 0) - return rc; + return rc; return 0; } @@ -231,5 +230,5 @@ int timestamp_test(void) * when this test is disabled. */ int dummy_timestamp_test; -#endif /* INCLUDE_TIMESTAMP_TEST */ +#endif /* INCLUDE_TIMESTAMP_TEST */ diff --git a/pjlib/src/pjlib-test/udp_echo_srv_ioqueue.c b/pjlib/src/pjlib-test/udp_echo_srv_ioqueue.c index 445c9d7d7b..6461cd25e1 100644 --- a/pjlib/src/pjlib-test/udp_echo_srv_ioqueue.c +++ b/pjlib/src/pjlib-test/udp_echo_srv_ioqueue.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjlib/src/pjlib-test/udp_echo_srv_sync.c b/pjlib/src/pjlib-test/udp_echo_srv_sync.c index 5e9fdf6bd8..b117283c55 100644 --- a/pjlib/src/pjlib-test/udp_echo_srv_sync.c +++ b/pjlib/src/pjlib-test/udp_echo_srv_sync.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,7 +45,7 @@ static int worker_thread(void *arg) continue; } - pj_atomic_add(total_bytes, (pj_atomic_value_t)len); + pj_atomic_add(total_bytes, (pj_atomic_value_t)len); rc = pj_sock_sendto(sock, buf, &len, 0, &addr, addrlen); if (rc != PJ_SUCCESS) { @@ -144,7 +143,7 @@ int echo_srv_common_loop(pj_atomic_t *bytes_counter) count++; PJ_LOG(3,("", "%s UDP (%d threads): %u KB/s (avg=%u KB/s) %s", - ioqueue_name, + ioqueue_name, ECHO_SERVER_MAX_THREADS, (unsigned)(bw / 1000), (unsigned)(avg_bw / count / 1000), diff --git a/pjlib/src/pjlib-test/util.c b/pjlib/src/pjlib-test/util.c index 68a5680fce..ae5f763b54 100644 --- a/pjlib/src/pjlib-test/util.c +++ b/pjlib/src/pjlib-test/util.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -73,8 +72,8 @@ pj_status_t app_socketpair(int family, int type, int protocol, status = pj_sock_socketpair(family, type, protocol, sv); if (status != PJ_SUCCESS) { - PJ_PERROR(1, (THIS_FILE, status, "socketpair error")); - return status; + PJ_PERROR(1, (THIS_FILE, status, "socketpair error")); + return status; } *serverfd = sv[0]; diff --git a/pjmedia/build/os-auto.mak.in b/pjmedia/build/os-auto.mak.in index 27015eb845..af9f8b8e4d 100644 --- a/pjmedia/build/os-auto.mak.in +++ b/pjmedia/build/os-auto.mak.in @@ -45,19 +45,19 @@ VPX_LDFLAGS = @ac_vpx_ldflags@ # PJMEDIA features exclusion export CFLAGS += @ac_no_small_filter@ @ac_no_large_filter@ @ac_no_speex_aec@ \ - $(SDL_CFLAGS) $(FFMPEG_CFLAGS) $(V4L2_CFLAGS) $(DSHOW_CFLAGS) $(QT_CFLAGS) \ - $(DARWIN_CFLAGS) $(ANDROID_CFLAGS) \ - $(OPENH264_CFLAGS) $(VPX_CFLAGS) $(OBOE_CFLAGS) + $(SDL_CFLAGS) $(FFMPEG_CFLAGS) $(V4L2_CFLAGS) $(DSHOW_CFLAGS) $(QT_CFLAGS) \ + $(DARWIN_CFLAGS) $(ANDROID_CFLAGS) \ + $(OPENH264_CFLAGS) $(VPX_CFLAGS) $(OBOE_CFLAGS) export LDFLAGS += $(SDL_LDFLAGS) $(FFMPEG_LDFLAGS) $(V4L2_LDFLAGS) $(DSHOW_LDFLAGS) \ - $(OPENH264_LDFLAGS) $(VPX_LDFLAGS) $(OBOE_LDFLAGS) + $(OPENH264_LDFLAGS) $(VPX_LDFLAGS) $(OBOE_LDFLAGS) # Define the desired sound device backend # Valid values are: -# - win32: Win32 MME (wmme_dev.c) -# - coreaudio: MaxOSX CoreAudio (coreaudio_dev.m) -# - alsa: Unix ALSA (alsa_dev.c) -# - null: Null sound device (nullsound.c) -# - external: Link with no sounddev (app will provide) +# - win32: Win32 MME (wmme_dev.c) +# - coreaudio: MaxOSX CoreAudio (coreaudio_dev.m) +# - alsa: Unix ALSA (alsa_dev.c) +# - null: Null sound device (nullsound.c) +# - external: Link with no sounddev (app will provide) AC_PJMEDIA_SND=@ac_pjmedia_snd@ # @@ -160,12 +160,12 @@ ifneq (@ac_external_srtp@,0) export CFLAGS += -DPJMEDIA_EXTERNAL_SRTP=@ac_external_srtp@ # SRTP srtp_deinit()/srtp_shutdown() API availability settings export CFLAGS += -DPJMEDIA_SRTP_HAS_DEINIT=@ac_srtp_deinit_present@ \ - -DPJMEDIA_SRTP_HAS_SHUTDOWN=@ac_srtp_shutdown_present@ + -DPJMEDIA_SRTP_HAS_SHUTDOWN=@ac_srtp_shutdown_present@ else # Our SRTP in third_party export CFLAGS += -I$(THIRD_PARTY)/build/srtp \ - -I$(THIRD_PARTY)/srtp/crypto/include \ - -I$(THIRD_PARTY)/srtp/include + -I$(THIRD_PARTY)/srtp/crypto/include \ + -I$(THIRD_PARTY)/srtp/include endif @@ -197,7 +197,7 @@ endif ifeq (@ac_external_pa@,1) # External PA export CFLAGS += -DPJMEDIA_AUDIO_DEV_HAS_PORTAUDIO=1 \ - -DPJMEDIA_AUDIO_DEV_HAS_WMME=0 + -DPJMEDIA_AUDIO_DEV_HAS_WMME=0 endif # @@ -247,8 +247,8 @@ endif # ifneq ($(findstring coreaudio,$(AC_PJMEDIA_SND)),) export CFLAGS += -DPJMEDIA_AUDIO_DEV_HAS_COREAUDIO=1 \ - -DPJMEDIA_AUDIO_DEV_HAS_PORTAUDIO=0 \ - -DPJMEDIA_AUDIO_DEV_HAS_WMME=0 + -DPJMEDIA_AUDIO_DEV_HAS_PORTAUDIO=0 \ + -DPJMEDIA_AUDIO_DEV_HAS_WMME=0 endif # @@ -256,8 +256,8 @@ endif # ifneq ($(findstring alsa,$(AC_PJMEDIA_SND)),) export CFLAGS += -DPJMEDIA_AUDIO_DEV_HAS_ALSA=1 \ - -DPJMEDIA_AUDIO_DEV_HAS_PORTAUDIO=0 \ - -DPJMEDIA_AUDIO_DEV_HAS_WMME=0 + -DPJMEDIA_AUDIO_DEV_HAS_PORTAUDIO=0 \ + -DPJMEDIA_AUDIO_DEV_HAS_WMME=0 endif # @@ -265,7 +265,7 @@ endif # ifneq ($(findstring win32,$(AC_PJMEDIA_SND)),) export CFLAGS += -DPJMEDIA_AUDIO_DEV_HAS_WMME=1 \ - -DPJMEDIA_AUDIO_DEV_HAS_PORTAUDIO=0 + -DPJMEDIA_AUDIO_DEV_HAS_PORTAUDIO=0 else export CFLAGS += -DPJMEDIA_AUDIO_DEV_HAS_WMME=0 endif @@ -275,7 +275,7 @@ endif # ifeq ($(AC_PJMEDIA_SND),null) export CFLAGS += -DPJMEDIA_AUDIO_DEV_HAS_PORTAUDIO=0 \ - -DPJMEDIA_AUDIO_DEV_HAS_WMME=0 + -DPJMEDIA_AUDIO_DEV_HAS_WMME=0 endif # @@ -283,7 +283,7 @@ endif # ifeq ($(AC_PJMEDIA_SND),external) export CFLAGS += -DPJMEDIA_AUDIO_DEV_HAS_PORTAUDIO=0 \ - -DPJMEDIA_AUDIO_DEV_HAS_WMME=0 + -DPJMEDIA_AUDIO_DEV_HAS_WMME=0 endif # diff --git a/pjmedia/include/pjmedia-audiodev/audiodev.h b/pjmedia/include/pjmedia-audiodev/audiodev.h index 30c54e6d9d..7d80be9726 100644 --- a/pjmedia/include/pjmedia-audiodev/audiodev.h +++ b/pjmedia/include/pjmedia-audiodev/audiodev.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,10 +43,10 @@ PJ_BEGIN_DECL * more than once, but each call to this function must have the * corresponding #pjmedia_aud_subsys_shutdown() call. * - * @param pf The pool factory. + * @param pf The pool factory. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_subsys_init(pj_pool_factory *pf); @@ -55,7 +54,7 @@ PJ_DECL(pj_status_t) pjmedia_aud_subsys_init(pj_pool_factory *pf); /** * Get the pool factory registered to the audio subsystem. * - * @return The pool factory. + * @return The pool factory. */ PJ_DECL(pj_pool_factory*) pjmedia_aud_subsys_get_pool_factory(void); @@ -66,8 +65,8 @@ PJ_DECL(pj_pool_factory*) pjmedia_aud_subsys_get_pool_factory(void); * may or may not be closed, depending on the implementation of the audio * device factories. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_subsys_shutdown(void); @@ -76,10 +75,10 @@ PJ_DECL(pj_status_t) pjmedia_aud_subsys_shutdown(void); * Register a supported audio device factory to the audio subsystem. This * function can only be called after calling #pjmedia_aud_subsys_init(). * - * @param adf The audio device factory. + * @param adf The audio device factory. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_register_factory(pjmedia_aud_dev_factory_create_func_ptr adf); @@ -91,10 +90,10 @@ pjmedia_aud_register_factory(pjmedia_aud_dev_factory_create_func_ptr adf); * Devices from this factory will be unlisted. If a device from this factory * is currently in use, then the behavior is undefined. * - * @param adf The audio device factory. + * @param adf The audio device factory. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_unregister_factory(pjmedia_aud_dev_factory_create_func_ptr adf); @@ -107,5 +106,5 @@ pjmedia_aud_unregister_factory(pjmedia_aud_dev_factory_create_func_ptr adf); PJ_END_DECL -#endif /* __PJMEDIA_AUDIODEV_AUDIODEV_H__ */ +#endif /* __PJMEDIA_AUDIODEV_AUDIODEV_H__ */ diff --git a/pjmedia/include/pjmedia-audiodev/audiodev_imp.h b/pjmedia/include/pjmedia-audiodev/audiodev_imp.h index 54de850d1c..b8915f6035 100644 --- a/pjmedia/include/pjmedia-audiodev/audiodev_imp.h +++ b/pjmedia/include/pjmedia-audiodev/audiodev_imp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -37,7 +36,7 @@ typedef struct pjmedia_aud_dev_factory_op /** * Initialize the audio device factory. * - * @param f The audio device factory. + * @param f The audio device factory. */ pj_status_t (*init)(pjmedia_aud_dev_factory *f); @@ -45,57 +44,57 @@ typedef struct pjmedia_aud_dev_factory_op * Close this audio device factory and release all resources back to the * operating system. * - * @param f The audio device factory. + * @param f The audio device factory. */ pj_status_t (*destroy)(pjmedia_aud_dev_factory *f); /** * Get the number of audio devices installed in the system. * - * @param f The audio device factory. + * @param f The audio device factory. */ unsigned (*get_dev_count)(pjmedia_aud_dev_factory *f); /** * Get the audio device information and capabilities. * - * @param f The audio device factory. - * @param index Device index. - * @param info The audio device information structure which will be - * initialized by this function once it returns - * successfully. + * @param f The audio device factory. + * @param index Device index. + * @param info The audio device information structure which will be + * initialized by this function once it returns + * successfully. */ - pj_status_t (*get_dev_info)(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); + pj_status_t (*get_dev_info)(pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_dev_info *info); /** * Initialize the specified audio device parameter with the default * values for the specified device. * - * @param f The audio device factory. - * @param index Device index. - * @param param The audio device parameter. + * @param f The audio device factory. + * @param index Device index. + * @param param The audio device parameter. */ pj_status_t (*default_param)(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); + unsigned index, + pjmedia_aud_param *param); /** * Open the audio device and create audio stream. See * #pjmedia_aud_stream_create() */ pj_status_t (*create_stream)(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); /** * Refresh the list of audio devices installed in the system. * - * @param f The audio device factory. + * @param f The audio device factory. */ pj_status_t (*refresh)(pjmedia_aud_dev_factory *f); @@ -109,8 +108,8 @@ struct pjmedia_aud_dev_factory { /** Internal data to be initialized by audio subsystem. */ struct { - /** Driver index */ - unsigned drv_idx; + /** Driver index */ + unsigned drv_idx; } sys; /** Operations */ @@ -127,21 +126,21 @@ typedef struct pjmedia_aud_stream_op * See #pjmedia_aud_stream_get_param() */ pj_status_t (*get_param)(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); + pjmedia_aud_param *param); /** * See #pjmedia_aud_stream_get_cap() */ pj_status_t (*get_cap)(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); + pjmedia_aud_dev_cap cap, + void *value); /** * See #pjmedia_aud_stream_set_cap() */ pj_status_t (*set_cap)(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); + pjmedia_aud_dev_cap cap, + const void *value); /** * See #pjmedia_aud_stream_start() @@ -168,8 +167,8 @@ struct pjmedia_aud_stream { /** Internal data to be initialized by audio subsystem */ struct { - /** Driver index */ - unsigned drv_idx; + /** Driver index */ + unsigned drv_idx; } sys; /** Operations */ diff --git a/pjmedia/include/pjmedia-audiodev/audiotest.h b/pjmedia/include/pjmedia-audiodev/audiotest.h index 523cf19a2d..a3b372d35d 100644 --- a/pjmedia/include/pjmedia-audiodev/audiotest.h +++ b/pjmedia/include/pjmedia-audiodev/audiotest.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -102,7 +101,7 @@ typedef struct pjmedia_aud_test_results * Perform audio device testing. */ PJ_DECL(pj_status_t) pjmedia_aud_test(const pjmedia_aud_param *param, - pjmedia_aud_test_results *result); + pjmedia_aud_test_results *result); /** * @} @@ -111,6 +110,6 @@ PJ_DECL(pj_status_t) pjmedia_aud_test(const pjmedia_aud_param *param, PJ_END_DECL -#endif /* __PJMEDIA_AUDIODEV_AUDIOTEST_H__ */ +#endif /* __PJMEDIA_AUDIODEV_AUDIOTEST_H__ */ diff --git a/pjmedia/include/pjmedia-audiodev/config.h b/pjmedia/include/pjmedia-audiodev/config.h index ae65badc8a..2c5a1d65be 100644 --- a/pjmedia/include/pjmedia-audiodev/config.h +++ b/pjmedia/include/pjmedia-audiodev/config.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -50,9 +49,9 @@ PJ_BEGIN_DECL #ifndef PJMEDIA_AUD_DEV_INFO_NAME_LEN # if (defined(PJ_WIN32) && PJ_WIN32!=0) || \ (defined(PJ_WIN64) && PJ_WIN64!=0) -# define PJMEDIA_AUD_DEV_INFO_NAME_LEN 128 +# define PJMEDIA_AUD_DEV_INFO_NAME_LEN 128 # else -# define PJMEDIA_AUD_DEV_INFO_NAME_LEN 64 +# define PJMEDIA_AUD_DEV_INFO_NAME_LEN 64 # endif #endif @@ -62,7 +61,7 @@ PJ_BEGIN_DECL * By default it is disabled. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO -# define PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO 0 +# define PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO 0 #endif /** @@ -70,7 +69,7 @@ PJ_BEGIN_DECL * included. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_OPENSL -# define PJMEDIA_AUDIO_DEV_HAS_OPENSL 0 +# define PJMEDIA_AUDIO_DEV_HAS_OPENSL 0 #endif /** @@ -86,7 +85,7 @@ PJ_BEGIN_DECL * included. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_OBOE -# define PJMEDIA_AUDIO_DEV_HAS_OBOE 0 +# define PJMEDIA_AUDIO_DEV_HAS_OBOE 0 #endif /** @@ -94,14 +93,14 @@ PJ_BEGIN_DECL * should be included. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_BB10 -# define PJMEDIA_AUDIO_DEV_HAS_BB10 0 +# define PJMEDIA_AUDIO_DEV_HAS_BB10 0 #endif /** * This setting controls whether native ALSA support should be included. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_ALSA -# define PJMEDIA_AUDIO_DEV_HAS_ALSA 0 +# define PJMEDIA_AUDIO_DEV_HAS_ALSA 0 #endif @@ -109,7 +108,7 @@ PJ_BEGIN_DECL * This setting controls whether null audio support should be included. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_NULL_AUDIO -# define PJMEDIA_AUDIO_DEV_HAS_NULL_AUDIO 0 +# define PJMEDIA_AUDIO_DEV_HAS_NULL_AUDIO 0 #endif @@ -117,7 +116,7 @@ PJ_BEGIN_DECL * This setting controls whether coreaudio support should be included. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_COREAUDIO -# define PJMEDIA_AUDIO_DEV_HAS_COREAUDIO 0 +# define PJMEDIA_AUDIO_DEV_HAS_COREAUDIO 0 #endif @@ -127,9 +126,9 @@ PJ_BEGIN_DECL #ifndef PJMEDIA_AUDIO_DEV_HAS_WMME # if (defined(PJ_WIN32_UWP) && PJ_WIN32_UWP!=0) || \ (defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8!=0) -# define PJMEDIA_AUDIO_DEV_HAS_WMME 0 +# define PJMEDIA_AUDIO_DEV_HAS_WMME 0 # else -# define PJMEDIA_AUDIO_DEV_HAS_WMME 1 +# define PJMEDIA_AUDIO_DEV_HAS_WMME 1 # endif #endif @@ -141,9 +140,9 @@ PJ_BEGIN_DECL #ifndef PJMEDIA_AUDIO_DEV_HAS_WASAPI # if (defined(PJ_WIN32_UWP) && PJ_WIN32_UWP!=0) || \ (defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8!=0) -# define PJMEDIA_AUDIO_DEV_HAS_WASAPI 1 +# define PJMEDIA_AUDIO_DEV_HAS_WASAPI 1 # else -# define PJMEDIA_AUDIO_DEV_HAS_WASAPI 0 +# define PJMEDIA_AUDIO_DEV_HAS_WASAPI 0 # endif #endif @@ -152,7 +151,7 @@ PJ_BEGIN_DECL * This setting controls whether BDIMAD support should be included. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_BDIMAD -# define PJMEDIA_AUDIO_DEV_HAS_BDIMAD 0 +# define PJMEDIA_AUDIO_DEV_HAS_BDIMAD 0 #endif @@ -160,7 +159,7 @@ PJ_BEGIN_DECL * This setting controls whether Symbian APS support should be included. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_SYMB_APS -# define PJMEDIA_AUDIO_DEV_HAS_SYMB_APS 0 +# define PJMEDIA_AUDIO_DEV_HAS_SYMB_APS 0 #endif @@ -187,7 +186,7 @@ PJ_BEGIN_DECL * This setting controls whether Symbian VAS support should be included. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_SYMB_VAS -# define PJMEDIA_AUDIO_DEV_HAS_SYMB_VAS 0 +# define PJMEDIA_AUDIO_DEV_HAS_SYMB_VAS 0 #endif /** @@ -197,7 +196,7 @@ PJ_BEGIN_DECL * Default: 1 (VAS version 1.0) */ #ifndef PJMEDIA_AUDIO_DEV_SYMB_VAS_VERSION -# define PJMEDIA_AUDIO_DEV_SYMB_VAS_VERSION 1 +# define PJMEDIA_AUDIO_DEV_SYMB_VAS_VERSION 1 #endif @@ -206,7 +205,7 @@ PJ_BEGIN_DECL * framework) support should be included. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_SYMB_MDA -# define PJMEDIA_AUDIO_DEV_HAS_SYMB_MDA PJ_SYMBIAN +# define PJMEDIA_AUDIO_DEV_HAS_SYMB_MDA PJ_SYMBIAN #endif @@ -221,7 +220,7 @@ PJ_BEGIN_DECL * Default: 1 (yes) */ #ifndef PJMEDIA_AUDIO_DEV_MDA_USE_SYNC_START -# define PJMEDIA_AUDIO_DEV_MDA_USE_SYNC_START 1 +# define PJMEDIA_AUDIO_DEV_MDA_USE_SYNC_START 1 #endif @@ -240,7 +239,7 @@ PJ_BEGIN_DECL * info. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_LEGACY_DEVICE -# define PJMEDIA_AUDIO_DEV_HAS_LEGACY_DEVICE 0 +# define PJMEDIA_AUDIO_DEV_HAS_LEGACY_DEVICE 0 #endif @@ -251,7 +250,7 @@ PJ_BEGIN_DECL PJ_END_DECL -#endif /* __PJMEDIA_AUDIODEV_CONFIG_H__ */ +#endif /* __PJMEDIA_AUDIODEV_CONFIG_H__ */ /* --------------------- DOCUMENTATION FOLLOWS --------------------------- @@ -357,12 +356,12 @@ contains many enhancements: printf("Got %d audio devices\n", dev_count); for (dev_idx=0; dev_idx= err >= -10000 */ #define PJMEDIA_AUDIODEV_ERRNO_FROM_PORTAUDIO(err) \ - ((int)PJMEDIA_AUDIODEV_PORTAUDIO_ERRNO_START-err) + ((int)PJMEDIA_AUDIODEV_PORTAUDIO_ERRNO_START-err) /** * Mapping from Windows multimedia WaveIn error codes. */ -#define PJMEDIA_AUDIODEV_WMME_IN_ERROR_START \ - (PJMEDIA_AUDIODEV_ERRNO_START + 30000) -#define PJMEDIA_AUDIODEV_WMME_IN_ERROR_END \ - (PJMEDIA_AUDIODEV_WMME_IN_ERROR_START + 1000 - 1) +#define PJMEDIA_AUDIODEV_WMME_IN_ERROR_START \ + (PJMEDIA_AUDIODEV_ERRNO_START + 30000) +#define PJMEDIA_AUDIODEV_WMME_IN_ERROR_END \ + (PJMEDIA_AUDIODEV_WMME_IN_ERROR_START + 1000 - 1) /** * Convert WaveIn operation error codes to PJLIB error space. */ #define PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(err) \ - ((int)PJMEDIA_AUDIODEV_WMME_IN_ERROR_START+err) + ((int)PJMEDIA_AUDIODEV_WMME_IN_ERROR_START+err) /** * Mapping from Windows multimedia WaveOut error codes. */ -#define PJMEDIA_AUDIODEV_WMME_OUT_ERROR_START \ - (PJMEDIA_AUDIODEV_WMME_IN_ERROR_END + 1000) -#define PJMEDIA_AUDIODEV_WMME_OUT_ERROR_END \ - (PJMEDIA_AUDIODEV_WMME_OUT_ERROR_START + 1000) +#define PJMEDIA_AUDIODEV_WMME_OUT_ERROR_START \ + (PJMEDIA_AUDIODEV_WMME_IN_ERROR_END + 1000) +#define PJMEDIA_AUDIODEV_WMME_OUT_ERROR_END \ + (PJMEDIA_AUDIODEV_WMME_OUT_ERROR_START + 1000) /** * Convert WaveOut operation error codes to PJLIB error space. */ #define PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(err) \ - ((int)PJMEDIA_AUDIODEV_WMME_OUT_ERROR_START+err) + ((int)PJMEDIA_AUDIODEV_WMME_OUT_ERROR_START+err) /** * Mapping from CoreAudio error codes to pjmedia error space. */ #define PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_START \ - (PJMEDIA_AUDIODEV_ERRNO_START+20000) + (PJMEDIA_AUDIODEV_ERRNO_START+20000) #define PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_END \ - (PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_START + 20000 -1) + (PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_START + 20000 -1) /** * Convert CoreAudio error code to PJLIB error code. * CoreAudio error code range: 0 >= err >= -10000 */ #define PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(err) \ - ((int)PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_START-err) + ((int)PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_START-err) /** * Mapping from BDIMAD error codes to pjmedia error space. */ -#define PJMEDIA_AUDIODEV_BDIMAD_ERROR_START \ - (PJMEDIA_AUDIODEV_ERRNO_START + 40000) -#define PJMEDIA_AUDIODEV_BDIMAD_ERROR_END \ - (PJMEDIA_AUDIODEV_BDIMAD_ERROR_START + 2000 - 1) +#define PJMEDIA_AUDIODEV_BDIMAD_ERROR_START \ + (PJMEDIA_AUDIODEV_ERRNO_START + 40000) +#define PJMEDIA_AUDIODEV_BDIMAD_ERROR_END \ + (PJMEDIA_AUDIODEV_BDIMAD_ERROR_START + 2000 - 1) /** * Convert BDIMAD error codes to PJLIB error space. */ #define PJMEDIA_AUDIODEV_ERRNO_FROM_BDIMAD(err) \ - ((int)PJMEDIA_AUDIODEV_BDIMAD_ERROR_START+err) + ((int)PJMEDIA_AUDIODEV_BDIMAD_ERROR_START+err) /************************************************************ * Audio Device API error codes @@ -124,80 +123,80 @@ PJ_BEGIN_DECL * @hideinitializer * General/unknown error. */ -#define PJMEDIA_EAUD_ERR (PJMEDIA_AUDIODEV_ERRNO_START+1) /* 420001 */ +#define PJMEDIA_EAUD_ERR (PJMEDIA_AUDIODEV_ERRNO_START+1) /* 420001 */ /** * @hideinitializer * Unknown error from audio driver */ -#define PJMEDIA_EAUD_SYSERR (PJMEDIA_AUDIODEV_ERRNO_START+2) /* 420002 */ +#define PJMEDIA_EAUD_SYSERR (PJMEDIA_AUDIODEV_ERRNO_START+2) /* 420002 */ /** * @hideinitializer * Audio subsystem not initialized */ -#define PJMEDIA_EAUD_INIT (PJMEDIA_AUDIODEV_ERRNO_START+3) /* 420003 */ +#define PJMEDIA_EAUD_INIT (PJMEDIA_AUDIODEV_ERRNO_START+3) /* 420003 */ /** * @hideinitializer * Invalid audio device */ -#define PJMEDIA_EAUD_INVDEV (PJMEDIA_AUDIODEV_ERRNO_START+4) /* 420004 */ +#define PJMEDIA_EAUD_INVDEV (PJMEDIA_AUDIODEV_ERRNO_START+4) /* 420004 */ /** * @hideinitializer * Found no devices */ -#define PJMEDIA_EAUD_NODEV (PJMEDIA_AUDIODEV_ERRNO_START+5) /* 420005 */ +#define PJMEDIA_EAUD_NODEV (PJMEDIA_AUDIODEV_ERRNO_START+5) /* 420005 */ /** * @hideinitializer * Unable to find default device */ -#define PJMEDIA_EAUD_NODEFDEV (PJMEDIA_AUDIODEV_ERRNO_START+6) /* 420006 */ +#define PJMEDIA_EAUD_NODEFDEV (PJMEDIA_AUDIODEV_ERRNO_START+6) /* 420006 */ /** * @hideinitializer * Device not ready */ -#define PJMEDIA_EAUD_NOTREADY (PJMEDIA_AUDIODEV_ERRNO_START+7) /* 420007 */ +#define PJMEDIA_EAUD_NOTREADY (PJMEDIA_AUDIODEV_ERRNO_START+7) /* 420007 */ /** * @hideinitializer * The audio capability is invalid or not supported */ -#define PJMEDIA_EAUD_INVCAP (PJMEDIA_AUDIODEV_ERRNO_START+8) /* 420008 */ +#define PJMEDIA_EAUD_INVCAP (PJMEDIA_AUDIODEV_ERRNO_START+8) /* 420008 */ /** * @hideinitializer * The operation is invalid or not supported */ -#define PJMEDIA_EAUD_INVOP (PJMEDIA_AUDIODEV_ERRNO_START+9) /* 420009 */ +#define PJMEDIA_EAUD_INVOP (PJMEDIA_AUDIODEV_ERRNO_START+9) /* 420009 */ /** * @hideinitializer * Bad or invalid audio device format */ -#define PJMEDIA_EAUD_BADFORMAT (PJMEDIA_AUDIODEV_ERRNO_START+10) /* 4200010 */ +#define PJMEDIA_EAUD_BADFORMAT (PJMEDIA_AUDIODEV_ERRNO_START+10) /* 4200010 */ /** * @hideinitializer * Invalid audio device sample format */ -#define PJMEDIA_EAUD_SAMPFORMAT (PJMEDIA_AUDIODEV_ERRNO_START+11) /* 4200011 */ +#define PJMEDIA_EAUD_SAMPFORMAT (PJMEDIA_AUDIODEV_ERRNO_START+11) /* 4200011 */ /** * @hideinitializer * Bad latency setting */ -#define PJMEDIA_EAUD_BADLATENCY (PJMEDIA_AUDIODEV_ERRNO_START+12) /* 4200012 */ +#define PJMEDIA_EAUD_BADLATENCY (PJMEDIA_AUDIODEV_ERRNO_START+12) /* 4200012 */ /** * @hideinitializer * General WASAPI error */ #define PJMEDIA_EAUD_WASAPI_ERROR \ - (PJMEDIA_AUDIODEV_ERRNO_START+13) /* 4200013 */ + (PJMEDIA_AUDIODEV_ERRNO_START+13) /* 4200013 */ /** * Get error message for the specified error code. Note that this @@ -210,11 +209,11 @@ PJ_BEGIN_DECL * @param buffer The buffer where to put the error message. * @param bufsize Size of the buffer. * - * @return The error message as NULL terminated string, + * @return The error message as NULL terminated string, * wrapped with pj_str_t. */ PJ_DECL(pj_str_t) pjmedia_audiodev_strerror(pj_status_t status, char *buffer, - pj_size_t bufsize); + pj_size_t bufsize); PJ_END_DECL @@ -224,5 +223,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_AUDIODEV_AUDIODEV_ERRNO_H__ */ +#endif /* __PJMEDIA_AUDIODEV_AUDIODEV_ERRNO_H__ */ diff --git a/pjmedia/include/pjmedia-codec.h b/pjmedia/include/pjmedia-codec.h index e818ebc5de..6609458087 100644 --- a/pjmedia/include/pjmedia-codec.h +++ b/pjmedia/include/pjmedia-codec.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,5 +43,5 @@ #include #include -#endif /* __PJMEDIA_CODEC_PJMEDIA_CODEC_H__ */ +#endif /* __PJMEDIA_CODEC_PJMEDIA_CODEC_H__ */ diff --git a/pjmedia/include/pjmedia-codec/amr_helper.h b/pjmedia/include/pjmedia-codec/amr_helper.h index f1ead9de16..be0ac078a4 100644 --- a/pjmedia/include/pjmedia-codec/amr_helper.h +++ b/pjmedia/include/pjmedia-codec/amr_helper.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -602,11 +601,11 @@ const pj_uint16_t pjmedia_codec_amrwb_bitrates[9] = */ #pragma pack(1) typedef struct pjmedia_codec_amr_bit_info { - pj_uint8_t frame_type; /**< AMR frame type. */ - pj_int8_t mode; /**< AMR mode. */ - pj_uint8_t start_bit; /**< Frame start bit. */ - pj_uint8_t good_quality:1; /**< Flag if frame is good/degraded. */ - pj_uint8_t STI:1; /**< STI mode (first/update). */ + pj_uint8_t frame_type; /**< AMR frame type. */ + pj_int8_t mode; /**< AMR mode. */ + pj_uint8_t start_bit; /**< Frame start bit. */ + pj_uint8_t good_quality:1; /**< Flag if frame is good/degraded. */ + pj_uint8_t STI:1; /**< STI mode (first/update). */ } pjmedia_codec_amr_bit_info; #pragma pack() @@ -615,14 +614,14 @@ typedef struct pjmedia_codec_amr_bit_info { * This structure describes AMR settings. */ typedef struct pjmedia_codec_amr_pack_setting { - pj_uint8_t amr_nb:1; /**< Set 1 for AMR-NB, 0 for AMR-WB. */ - pj_uint8_t reorder:1; /**< Reorder bitstream into descending - sensitivity order or vice versa. */ - pj_uint8_t octet_aligned:1; /**< TRUE if payload is in octet-aligned mode, - FALSE if payload is in bandwidth - efficient mode. */ - pj_uint8_t cmr:4; /**< Change Mode Request for remote - encoder. */ + pj_uint8_t amr_nb:1; /**< Set 1 for AMR-NB, 0 for AMR-WB. */ + pj_uint8_t reorder:1; /**< Reorder bitstream into descending + sensitivity order or vice versa. */ + pj_uint8_t octet_aligned:1; /**< TRUE if payload is in octet-aligned mode, + FALSE if payload is in bandwidth + efficient mode. */ + pj_uint8_t cmr:4; /**< Change Mode Request for remote + encoder. */ } pjmedia_codec_amr_pack_setting; @@ -631,48 +630,48 @@ typedef struct pjmedia_codec_amr_pack_setting { * * @param bitrate AMR bitrate. * - * @return AMR mode. + * @return AMR mode. */ PJ_INLINE(pj_int8_t) pjmedia_codec_amr_get_mode(unsigned bitrate) { pj_int8_t mode = -1; if(bitrate==4750){ - mode = 0; + mode = 0; } else if(bitrate==5150){ - mode = 1; + mode = 1; } else if(bitrate==5900){ - mode = 2; + mode = 2; } else if(bitrate==6700){ - mode = 3; + mode = 3; } else if(bitrate==7400){ - mode = 4; + mode = 4; } else if(bitrate==7950){ - mode = 5; + mode = 5; } else if(bitrate==10200){ - mode = 6; + mode = 6; } else if(bitrate==12200){ - mode = 7; + mode = 7; /* AMRWB */ } else if(bitrate==6600){ - mode = 0; + mode = 0; } else if(bitrate==8850){ - mode = 1; + mode = 1; } else if(bitrate==12650){ - mode = 2; + mode = 2; } else if(bitrate==14250){ - mode = 3; + mode = 3; } else if(bitrate==15850){ - mode = 4; + mode = 4; } else if(bitrate==18250){ - mode = 5; + mode = 5; } else if(bitrate==19850){ - mode = 6; + mode = 6; } else if(bitrate==23050){ - mode = 7; + mode = 7; } else if(bitrate==23850){ - mode = 8; + mode = 8; } return mode; } @@ -680,26 +679,26 @@ PJ_INLINE(pj_int8_t) pjmedia_codec_amr_get_mode(unsigned bitrate) /** * Get AMR mode based on frame length. * - * @param amrnb Set to PJ_TRUE for AMR-NB domain or PJ_FALSE for AMR-WB. + * @param amrnb Set to PJ_TRUE for AMR-NB domain or PJ_FALSE for AMR-WB. * @param frame_len The frame length. * - * @return AMR mode. + * @return AMR mode. */ PJ_INLINE(pj_int8_t) pjmedia_codec_amr_get_mode2(pj_bool_t amrnb, - unsigned frame_len) + unsigned frame_len) { int i; if (amrnb) { - for (i = 0; i < 9; ++i) - if (frame_len == pjmedia_codec_amrnb_framelen[i]) - return (pj_int8_t)i; + for (i = 0; i < 9; ++i) + if (frame_len == pjmedia_codec_amrnb_framelen[i]) + return (pj_int8_t)i; } else { - for (i = 0; i < 10; ++i) { - if (frame_len == pjmedia_codec_amrwb_framelen[i]) - return (pj_int8_t)i; - } + for (i = 0; i < 10; ++i) { + if (frame_len == pjmedia_codec_amrwb_framelen[i]) + return (pj_int8_t)i; + } } pj_assert(!"Invalid AMR frame length"); @@ -713,16 +712,16 @@ PJ_INLINE(pj_int8_t) pjmedia_codec_amr_get_mode2(pj_bool_t amrnb, * 'setting' by setting/resetting field 'reorder'. * - align left the start bit (make the start_bit to be 0). * - * @param in Input frame. + * @param in Input frame. * @param setting Settings, see #pjmedia_codec_amr_pack_setting. - * @param out Output frame. + * @param out Output frame. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_codec_amr_predecode( - const pjmedia_frame *in, - const pjmedia_codec_amr_pack_setting *setting, - pjmedia_frame *out) + const pjmedia_frame *in, + const pjmedia_codec_amr_pack_setting *setting, + pjmedia_frame *out) { pj_int8_t amr_bits[477 + 7] = {0}; pj_int8_t *p_amr_bits = &amr_bits[0]; @@ -731,116 +730,116 @@ PJ_INLINE(pj_status_t) pjmedia_codec_amr_predecode( pj_uint8_t *w = (pj_uint8_t*) out->buf; /* write cursor */ /* env vars for AMR or AMRWB */ - pj_uint8_t SID_FT; - const pj_uint8_t *framelen_tbl; - const pj_uint16_t *framelenbit_tbl; - const pj_uint16_t *bitrate_tbl; + pj_uint8_t SID_FT; + const pj_uint8_t *framelen_tbl; + const pj_uint16_t *framelenbit_tbl; + const pj_uint16_t *bitrate_tbl; const pj_int16_t* const *order_maps; pjmedia_codec_amr_bit_info *in_info = - (pjmedia_codec_amr_bit_info*) &in->bit_info; + (pjmedia_codec_amr_bit_info*) &in->bit_info; pjmedia_codec_amr_bit_info *out_info = - (pjmedia_codec_amr_bit_info*) &out->bit_info; + (pjmedia_codec_amr_bit_info*) &out->bit_info; unsigned i; *out_info = *in_info; if (setting->amr_nb) { - SID_FT = 8; - framelen_tbl = pjmedia_codec_amrnb_framelen; - framelenbit_tbl = pjmedia_codec_amrnb_framelenbits; - bitrate_tbl = pjmedia_codec_amrnb_bitrates; - order_maps = pjmedia_codec_amrnb_ordermaps; + SID_FT = 8; + framelen_tbl = pjmedia_codec_amrnb_framelen; + framelenbit_tbl = pjmedia_codec_amrnb_framelenbits; + bitrate_tbl = pjmedia_codec_amrnb_bitrates; + order_maps = pjmedia_codec_amrnb_ordermaps; } else { - SID_FT = 9; - framelen_tbl = pjmedia_codec_amrwb_framelen; - framelenbit_tbl = pjmedia_codec_amrwb_framelenbits; - bitrate_tbl = pjmedia_codec_amrwb_bitrates; - order_maps = pjmedia_codec_amrwb_ordermaps; + SID_FT = 9; + framelen_tbl = pjmedia_codec_amrwb_framelen; + framelenbit_tbl = pjmedia_codec_amrwb_framelenbits; + bitrate_tbl = pjmedia_codec_amrwb_bitrates; + order_maps = pjmedia_codec_amrwb_ordermaps; } PJ_UNUSED_ARG(bitrate_tbl); /* unpack AMR bitstream if there is any data */ if (in_info->frame_type <= SID_FT) { - i = 0; - if (in_info->start_bit) { - for (; i < (unsigned)(8-in_info->start_bit); ++i) - *p_amr_bits++ = (pj_uint8_t) - ((*r >> (7-in_info->start_bit-i)) & 1); - ++r; - } - for(; i < framelenbit_tbl[in_info->frame_type]; i += 8, ++r) { - *p_amr_bits++ = (pj_uint8_t)((*r >> 7) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r >> 6) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r >> 5) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r >> 4) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r >> 3) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r >> 2) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r >> 1) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r ) & 1); - } + i = 0; + if (in_info->start_bit) { + for (; i < (unsigned)(8-in_info->start_bit); ++i) + *p_amr_bits++ = (pj_uint8_t) + ((*r >> (7-in_info->start_bit-i)) & 1); + ++r; + } + for(; i < framelenbit_tbl[in_info->frame_type]; i += 8, ++r) { + *p_amr_bits++ = (pj_uint8_t)((*r >> 7) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r >> 6) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r >> 5) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r >> 4) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r >> 3) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r >> 2) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r >> 1) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r ) & 1); + } } if (in_info->frame_type < SID_FT) { - /* Speech */ - out_info->mode = in_info->frame_type; - out->size = framelen_tbl[out_info->mode]; - - pj_bzero(out->buf, out->size); - - if (setting->reorder) { - const pj_int16_t *order_map; - - order_map = order_maps[out_info->mode]; - for(i = 0; i < framelenbit_tbl[out_info->mode]; ++i) { - if (amr_bits[i]) { - pj_uint16_t bitpos; - bitpos = order_map[i]; - w[bitpos>>3] |= 1 << (7 - (bitpos % 8)); - } - } - } else { - for(i = 0; i < framelenbit_tbl[out_info->mode]; ++i) { - if (amr_bits[i]) - w[i >> 3] |= 1 << (7 - (i % 8)); - } - } + /* Speech */ + out_info->mode = in_info->frame_type; + out->size = framelen_tbl[out_info->mode]; + + pj_bzero(out->buf, out->size); + + if (setting->reorder) { + const pj_int16_t *order_map; + + order_map = order_maps[out_info->mode]; + for(i = 0; i < framelenbit_tbl[out_info->mode]; ++i) { + if (amr_bits[i]) { + pj_uint16_t bitpos; + bitpos = order_map[i]; + w[bitpos>>3] |= 1 << (7 - (bitpos % 8)); + } + } + } else { + for(i = 0; i < framelenbit_tbl[out_info->mode]; ++i) { + if (amr_bits[i]) + w[i >> 3] |= 1 << (7 - (i % 8)); + } + } } else if (in_info->frame_type == SID_FT) { - /* SID */ - pj_uint8_t w_bitptr = 0; - pj_uint8_t FT_; + /* SID */ + pj_uint8_t w_bitptr = 0; + pj_uint8_t FT_; - if (setting->amr_nb) - FT_ = (pj_uint8_t)((amr_bits[36] << 2) | (amr_bits[37] << 1) | - amr_bits[38]); - else - FT_ = (pj_uint8_t)((amr_bits[36] << 3) | (amr_bits[37] << 2) | - (amr_bits[38] << 1) | amr_bits[39]); + if (setting->amr_nb) + FT_ = (pj_uint8_t)((amr_bits[36] << 2) | (amr_bits[37] << 1) | + amr_bits[38]); + else + FT_ = (pj_uint8_t)((amr_bits[36] << 3) | (amr_bits[37] << 2) | + (amr_bits[38] << 1) | amr_bits[39]); - out_info->mode = FT_; - out->size = 5; + out_info->mode = FT_; + out->size = 5; - pj_bzero(out->buf, out->size); - for(i = 0; i < framelenbit_tbl[SID_FT]; ++i) { - if (amr_bits[i]) - *w |= (1 << (7-w_bitptr)); + pj_bzero(out->buf, out->size); + for(i = 0; i < framelenbit_tbl[SID_FT]; ++i) { + if (amr_bits[i]) + *w |= (1 << (7-w_bitptr)); - if (++w_bitptr == 8) { - ++w; - w_bitptr = 0; - } - } + if (++w_bitptr == 8) { + ++w; + w_bitptr = 0; + } + } } else { - /* NO DATA */ - out->size = 0; - out_info->mode = -1; + /* NO DATA */ + out->size = 0; + out_info->mode = -1; } out_info->start_bit = 0; @@ -855,18 +854,18 @@ PJ_INLINE(pj_status_t) pjmedia_codec_amr_predecode( * @param frames AMR frames to be packed. * @param nframes Number of frames to be packed. * @param setting Settings, see #pjmedia_codec_amr_pack_setting. - * @param pkt Payload. + * @param pkt Payload. * @param pkt_size Payload size, as input this specifies payload maximum size, - * as output this specifies payload packed size. + * as output this specifies payload packed size. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE (pj_status_t) pjmedia_codec_amr_pack( - const pjmedia_frame frames[], - unsigned nframes, - const pjmedia_codec_amr_pack_setting *setting, - void *pkt, - pj_size_t *pkt_size) + const pjmedia_frame frames[], + unsigned nframes, + const pjmedia_codec_amr_pack_setting *setting, + void *pkt, + pj_size_t *pkt_size) { /* Write cursor */ pj_uint8_t *w = (pj_uint8_t*)pkt; @@ -876,10 +875,10 @@ PJ_INLINE (pj_status_t) pjmedia_codec_amr_pack( pj_uint8_t *r; /* env vars for AMR or AMRWB */ - pj_uint8_t SID_FT; - const pj_uint8_t *framelen_tbl; - const pj_uint16_t *framelenbit_tbl; - const pj_uint16_t *bitrate_tbl; + pj_uint8_t SID_FT; + const pj_uint8_t *framelen_tbl; + const pj_uint16_t *framelenbit_tbl; + const pj_uint16_t *bitrate_tbl; const pj_int16_t* const *order_maps; /* frame info */ @@ -890,17 +889,17 @@ PJ_INLINE (pj_status_t) pjmedia_codec_amr_pack( max_pkt_size = (unsigned)*pkt_size; if (setting->amr_nb) { - SID_FT = 8; - framelen_tbl = pjmedia_codec_amrnb_framelen; - framelenbit_tbl = pjmedia_codec_amrnb_framelenbits; - bitrate_tbl = pjmedia_codec_amrnb_bitrates; - order_maps = pjmedia_codec_amrnb_ordermaps; + SID_FT = 8; + framelen_tbl = pjmedia_codec_amrnb_framelen; + framelenbit_tbl = pjmedia_codec_amrnb_framelenbits; + bitrate_tbl = pjmedia_codec_amrnb_bitrates; + order_maps = pjmedia_codec_amrnb_ordermaps; } else { - SID_FT = 9; - framelen_tbl = pjmedia_codec_amrwb_framelen; - framelenbit_tbl = pjmedia_codec_amrwb_framelenbits; - bitrate_tbl = pjmedia_codec_amrwb_bitrates; - order_maps = pjmedia_codec_amrwb_ordermaps; + SID_FT = 9; + framelen_tbl = pjmedia_codec_amrwb_framelen; + framelenbit_tbl = pjmedia_codec_amrwb_framelenbits; + bitrate_tbl = pjmedia_codec_amrwb_bitrates; + order_maps = pjmedia_codec_amrwb_ordermaps; } PJ_UNUSED_ARG(bitrate_tbl); @@ -909,157 +908,157 @@ PJ_INLINE (pj_status_t) pjmedia_codec_amr_pack( *w = (pj_uint8_t)(setting->cmr << 4); w_bitptr = 4; if (setting->octet_aligned) { - ++w; - w_bitptr = 0; + ++w; + w_bitptr = 0; } /* Table Of Contents, 6 bits each */ for (i = 0; i < nframes; ++i) { - pj_uint8_t TOC, FT, Q; - pj_bool_t F; - - info = (pjmedia_codec_amr_bit_info*)&frames[i].bit_info; - - F = (i != nframes-1); - FT = info->frame_type; - Q = (pj_uint8_t)(info->good_quality == 1); - pj_assert(FT <= SID_FT || FT == 14 || FT == 15); - - /* Check buffer availability */ - *pkt_size = w - (pj_uint8_t*)pkt + 1; - PJ_ASSERT_RETURN(*pkt_size <= max_pkt_size, PJ_ETOOSMALL); - - TOC = (pj_uint8_t)((F<<5) | (FT<<1) | Q); - if (w_bitptr == 0) { - *w = (pj_uint8_t)(TOC<<2); - w_bitptr = 6; - } else if (w_bitptr == 2) { - *w++ |= TOC; - w_bitptr = 0; - } else if (w_bitptr == 4) { - *w++ |= TOC>>2; - *w = (pj_uint8_t)(TOC<<6); - w_bitptr = 2; - } else if (w_bitptr == 6) { - *w++ |= TOC>>4; - *w = (pj_uint8_t)(TOC<<4); - w_bitptr = 4; - } - if (setting->octet_aligned) { - ++w; - w_bitptr = 0; - } + pj_uint8_t TOC, FT, Q; + pj_bool_t F; + + info = (pjmedia_codec_amr_bit_info*)&frames[i].bit_info; + + F = (i != nframes-1); + FT = info->frame_type; + Q = (pj_uint8_t)(info->good_quality == 1); + pj_assert(FT <= SID_FT || FT == 14 || FT == 15); + + /* Check buffer availability */ + *pkt_size = w - (pj_uint8_t*)pkt + 1; + PJ_ASSERT_RETURN(*pkt_size <= max_pkt_size, PJ_ETOOSMALL); + + TOC = (pj_uint8_t)((F<<5) | (FT<<1) | Q); + if (w_bitptr == 0) { + *w = (pj_uint8_t)(TOC<<2); + w_bitptr = 6; + } else if (w_bitptr == 2) { + *w++ |= TOC; + w_bitptr = 0; + } else if (w_bitptr == 4) { + *w++ |= TOC>>2; + *w = (pj_uint8_t)(TOC<<6); + w_bitptr = 2; + } else if (w_bitptr == 6) { + *w++ |= TOC>>4; + *w = (pj_uint8_t)(TOC<<4); + w_bitptr = 4; + } + if (setting->octet_aligned) { + ++w; + w_bitptr = 0; + } } /* Encoded data */ for (i = 0; i < nframes; ++i) { - pj_int8_t amr_bits[477 + 7] = {0}; - pj_int8_t *p_amr_bits = &amr_bits[0]; - unsigned j; - - info = (pjmedia_codec_amr_bit_info*)&frames[i].bit_info; - - /* Check buffer availability */ - *pkt_size = w - (pj_uint8_t*)pkt; - if (info->frame_type <= SID_FT) - *pkt_size += framelen_tbl[info->frame_type] + 1; - PJ_ASSERT_RETURN(*pkt_size <= max_pkt_size, PJ_ETOOSMALL); - - /* Skip if there is no data */ - if (info->frame_type > SID_FT) - continue; - - /* Unpack bits */ - r = (pj_uint8_t*) frames[i].buf; - j = 0; - if (info->start_bit) { - for (; j < (unsigned)(8-info->start_bit); ++j) - *p_amr_bits++ = (pj_uint8_t) - ((*r >> (7-info->start_bit-j)) & 1); - ++r; - } - for(; j < framelenbit_tbl[info->frame_type]; j+=8, ++r) { - *p_amr_bits++ = (pj_uint8_t)((*r >> 7) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r >> 6) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r >> 5) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r >> 4) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r >> 3) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r >> 2) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r >> 1) & 1); - *p_amr_bits++ = (pj_uint8_t)((*r ) & 1); - } - - if (info->frame_type < SID_FT) { - - /* Speech */ - if (w_bitptr == 0) *w = 0; - - if (setting->reorder) { - const pj_int16_t *order_map; - - /* Put bits in the packet, sensitivity descending ordered */ - order_map = order_maps[info->frame_type]; - for(j = 0; j < framelenbit_tbl[info->frame_type]; ++j) { - if (amr_bits[order_map[j]]) - *w |= (1 << (7-w_bitptr)); - - if (++w_bitptr == 8) { - w_bitptr = 0; - ++w; - *w = 0; - } - } - } else { - for(j = 0; j < framelenbit_tbl[info->frame_type]; ++j) { - if (amr_bits[j]) - *w |= (1 << (7-w_bitptr)); - - if (++w_bitptr == 8) { - w_bitptr = 0; - ++w; - *w = 0; - } - } - } - - } else if (info->frame_type == SID_FT) { - - /* SID */ - amr_bits[35] |= info->STI; - - if (setting->amr_nb) { - amr_bits[36] = (pj_uint8_t)((info->mode >> 2) & 1); - amr_bits[37] = (pj_uint8_t)((info->mode >> 1) & 1); - amr_bits[38] = (pj_uint8_t)((info->mode) & 1); - } else { - amr_bits[36] = (pj_uint8_t)((info->mode >> 3) & 1); - amr_bits[37] = (pj_uint8_t)((info->mode >> 2) & 1); - amr_bits[38] = (pj_uint8_t)((info->mode >> 1) & 1); - amr_bits[39] = (pj_uint8_t)((info->mode) & 1); - } - - if (w_bitptr == 0) *w = 0; - for(j = 0; j < framelenbit_tbl[info->frame_type]; ++j) { - if (amr_bits[j]) - *w |= (1 << (7-w_bitptr)); - - if (++w_bitptr == 8) { - w_bitptr = 0; - ++w; - *w = 0; - } - } - } - - if (setting->octet_aligned) { - ++w; - w_bitptr = 0; - } + pj_int8_t amr_bits[477 + 7] = {0}; + pj_int8_t *p_amr_bits = &amr_bits[0]; + unsigned j; + + info = (pjmedia_codec_amr_bit_info*)&frames[i].bit_info; + + /* Check buffer availability */ + *pkt_size = w - (pj_uint8_t*)pkt; + if (info->frame_type <= SID_FT) + *pkt_size += framelen_tbl[info->frame_type] + 1; + PJ_ASSERT_RETURN(*pkt_size <= max_pkt_size, PJ_ETOOSMALL); + + /* Skip if there is no data */ + if (info->frame_type > SID_FT) + continue; + + /* Unpack bits */ + r = (pj_uint8_t*) frames[i].buf; + j = 0; + if (info->start_bit) { + for (; j < (unsigned)(8-info->start_bit); ++j) + *p_amr_bits++ = (pj_uint8_t) + ((*r >> (7-info->start_bit-j)) & 1); + ++r; + } + for(; j < framelenbit_tbl[info->frame_type]; j+=8, ++r) { + *p_amr_bits++ = (pj_uint8_t)((*r >> 7) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r >> 6) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r >> 5) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r >> 4) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r >> 3) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r >> 2) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r >> 1) & 1); + *p_amr_bits++ = (pj_uint8_t)((*r ) & 1); + } + + if (info->frame_type < SID_FT) { + + /* Speech */ + if (w_bitptr == 0) *w = 0; + + if (setting->reorder) { + const pj_int16_t *order_map; + + /* Put bits in the packet, sensitivity descending ordered */ + order_map = order_maps[info->frame_type]; + for(j = 0; j < framelenbit_tbl[info->frame_type]; ++j) { + if (amr_bits[order_map[j]]) + *w |= (1 << (7-w_bitptr)); + + if (++w_bitptr == 8) { + w_bitptr = 0; + ++w; + *w = 0; + } + } + } else { + for(j = 0; j < framelenbit_tbl[info->frame_type]; ++j) { + if (amr_bits[j]) + *w |= (1 << (7-w_bitptr)); + + if (++w_bitptr == 8) { + w_bitptr = 0; + ++w; + *w = 0; + } + } + } + + } else if (info->frame_type == SID_FT) { + + /* SID */ + amr_bits[35] |= info->STI; + + if (setting->amr_nb) { + amr_bits[36] = (pj_uint8_t)((info->mode >> 2) & 1); + amr_bits[37] = (pj_uint8_t)((info->mode >> 1) & 1); + amr_bits[38] = (pj_uint8_t)((info->mode) & 1); + } else { + amr_bits[36] = (pj_uint8_t)((info->mode >> 3) & 1); + amr_bits[37] = (pj_uint8_t)((info->mode >> 2) & 1); + amr_bits[38] = (pj_uint8_t)((info->mode >> 1) & 1); + amr_bits[39] = (pj_uint8_t)((info->mode) & 1); + } + + if (w_bitptr == 0) *w = 0; + for(j = 0; j < framelenbit_tbl[info->frame_type]; ++j) { + if (amr_bits[j]) + *w |= (1 << (7-w_bitptr)); + + if (++w_bitptr == 8) { + w_bitptr = 0; + ++w; + *w = 0; + } + } + } + + if (setting->octet_aligned) { + ++w; + w_bitptr = 0; + } } *pkt_size = w - (pj_uint8_t*)pkt; if (w_bitptr) - *pkt_size += 1; + *pkt_size += 1; return PJ_SUCCESS; } @@ -1068,24 +1067,24 @@ PJ_INLINE (pj_status_t) pjmedia_codec_amr_pack( /** * Parse AMR payload into frames. * - * @param pkt Payload. + * @param pkt Payload. * @param pkt_size Payload size. - * @param ts Base timestamp. + * @param ts Base timestamp. * @param setting Settings, see #pjmedia_codec_amr_pack_setting. * @param frames Frames parsed. * @param nframes Number of frames parsed. - * @param cmr Change Mode Request message for local encoder. + * @param cmr Change Mode Request message for local encoder. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_codec_amr_parse( - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - const pjmedia_codec_amr_pack_setting* setting, - pjmedia_frame frames[], - unsigned *nframes, - pj_uint8_t *cmr) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + const pjmedia_codec_amr_pack_setting* setting, + pjmedia_frame frames[], + unsigned *nframes, + pj_uint8_t *cmr) { unsigned cnt = 0; pj_timestamp ts_ = *ts; @@ -1095,24 +1094,24 @@ PJ_INLINE(pj_status_t) pjmedia_codec_amr_parse( pj_uint8_t *r = (pj_uint8_t*)pkt; /* env vars for AMR or AMRWB */ - pj_uint8_t SID_FT; - const pj_uint8_t *framelen_tbl; - const pj_uint16_t *framelenbit_tbl; + pj_uint8_t SID_FT; + const pj_uint8_t *framelen_tbl; + const pj_uint16_t *framelenbit_tbl; const pj_int16_t* const *order_maps; /* frame info */ pjmedia_codec_amr_bit_info *info; if (setting->amr_nb) { - SID_FT = 8; - framelen_tbl = pjmedia_codec_amrnb_framelen; - framelenbit_tbl = pjmedia_codec_amrnb_framelenbits; - order_maps = pjmedia_codec_amrnb_ordermaps; + SID_FT = 8; + framelen_tbl = pjmedia_codec_amrnb_framelen; + framelenbit_tbl = pjmedia_codec_amrnb_framelenbits; + order_maps = pjmedia_codec_amrnb_ordermaps; } else { - SID_FT = 9; - framelen_tbl = pjmedia_codec_amrwb_framelen; - framelenbit_tbl = pjmedia_codec_amrwb_framelenbits; - order_maps = pjmedia_codec_amrwb_ordermaps; + SID_FT = 9; + framelen_tbl = pjmedia_codec_amrwb_framelen; + framelenbit_tbl = pjmedia_codec_amrwb_framelenbits; + order_maps = pjmedia_codec_amrwb_ordermaps; } PJ_UNUSED_ARG(pkt_size); @@ -1122,64 +1121,64 @@ PJ_INLINE(pj_status_t) pjmedia_codec_amr_parse( *cmr = (pj_uint8_t)((*r >> 4) & 0x0F); r_bitptr = 4; if (setting->octet_aligned) { - ++r; - r_bitptr = 0; + ++r; + r_bitptr = 0; } /* Table Of Contents, 6 bits each */ for (;;) { - pj_uint8_t TOC = 0; - pj_uint8_t F, FT, Q; - - if (r_bitptr == 0) { - TOC = (pj_uint8_t)(*r >> 2); - r_bitptr = 6; - } else if (r_bitptr == 2) { - TOC = (pj_uint8_t)(*r++ & 0x3F); - r_bitptr = 0; - } else if (r_bitptr == 4) { - TOC = (pj_uint8_t)((*r++ & 0x0f) << 2); - TOC |= *r >> 6; - r_bitptr = 2; - } else if (r_bitptr == 6) { - TOC = (pj_uint8_t)((*r++ & 0x03) << 4); - TOC |= *r >> 4; - r_bitptr = 4; - } - - F = (pj_uint8_t)(TOC >> 5); - FT = (pj_uint8_t)((TOC >> 1) & 0x0F); - Q = (pj_uint8_t)(TOC & 1); - - if (FT > SID_FT && FT < 14) { - /* Discard the whole packet (RFC4867 4.3.2) */ - //pj_assert(!"Invalid AMR frametype, stream may be corrupted!"); - cnt = 0; - PJ_LOG(4, ("AMR parser", "Invalid AMR frametype, stream may be " - "corrupted!")); - break; - } - - if (setting->octet_aligned) { - ++r; - r_bitptr = 0; - } - - /* Set frame attributes */ - info = (pjmedia_codec_amr_bit_info*) &frames[cnt].bit_info; - info->frame_type = FT; - info->mode = (pj_int8_t)((FT < SID_FT)? FT : -1); - info->good_quality = (pj_uint8_t)(Q == 1); - info->start_bit = 0; - info->STI = 0; - frames[cnt].timestamp = ts_; - frames[cnt].type = PJMEDIA_FRAME_TYPE_AUDIO; - - /* AMR frame length is 20ms */ - ts_.u64 += setting->amr_nb? 160 : 320; - - if (++cnt == *nframes || !F) - break; + pj_uint8_t TOC = 0; + pj_uint8_t F, FT, Q; + + if (r_bitptr == 0) { + TOC = (pj_uint8_t)(*r >> 2); + r_bitptr = 6; + } else if (r_bitptr == 2) { + TOC = (pj_uint8_t)(*r++ & 0x3F); + r_bitptr = 0; + } else if (r_bitptr == 4) { + TOC = (pj_uint8_t)((*r++ & 0x0f) << 2); + TOC |= *r >> 6; + r_bitptr = 2; + } else if (r_bitptr == 6) { + TOC = (pj_uint8_t)((*r++ & 0x03) << 4); + TOC |= *r >> 4; + r_bitptr = 4; + } + + F = (pj_uint8_t)(TOC >> 5); + FT = (pj_uint8_t)((TOC >> 1) & 0x0F); + Q = (pj_uint8_t)(TOC & 1); + + if (FT > SID_FT && FT < 14) { + /* Discard the whole packet (RFC4867 4.3.2) */ + //pj_assert(!"Invalid AMR frametype, stream may be corrupted!"); + cnt = 0; + PJ_LOG(4, ("AMR parser", "Invalid AMR frametype, stream may be " + "corrupted!")); + break; + } + + if (setting->octet_aligned) { + ++r; + r_bitptr = 0; + } + + /* Set frame attributes */ + info = (pjmedia_codec_amr_bit_info*) &frames[cnt].bit_info; + info->frame_type = FT; + info->mode = (pj_int8_t)((FT < SID_FT)? FT : -1); + info->good_quality = (pj_uint8_t)(Q == 1); + info->start_bit = 0; + info->STI = 0; + frames[cnt].timestamp = ts_; + frames[cnt].type = PJMEDIA_FRAME_TYPE_AUDIO; + + /* AMR frame length is 20ms */ + ts_.u64 += setting->amr_nb? 160 : 320; + + if (++cnt == *nframes || !F) + break; } *nframes = cnt; @@ -1187,41 +1186,41 @@ PJ_INLINE(pj_status_t) pjmedia_codec_amr_parse( /* Speech frames */ while (cnt < *nframes) { - pj_uint8_t FT; - - info = (pjmedia_codec_amr_bit_info*) &frames[cnt].bit_info; - FT = info->frame_type; - - frames[cnt].buf = r; - info->start_bit = r_bitptr; - - if (FT == SID_FT) { - unsigned sti_bitptr; - sti_bitptr = r_bitptr + 35; - info->STI = (pj_uint8_t) - (r[sti_bitptr >> 3] >> (7 - (sti_bitptr % 8))) & 1; - } - - if (setting->octet_aligned) { - r += framelen_tbl[FT]; - frames[cnt].size = framelen_tbl[FT]; - } else { - if (FT == 14 || FT == 15) { - /* NO DATA */ - frames[cnt].size = 0; - } else { - unsigned adv_bit; - - adv_bit = framelenbit_tbl[FT] + r_bitptr; - r += adv_bit >> 3; - r_bitptr = (pj_uint8_t)(adv_bit % 8); - - frames[cnt].size = adv_bit >> 3; - if (r_bitptr) - ++frames[cnt].size; - } - } - ++cnt; + pj_uint8_t FT; + + info = (pjmedia_codec_amr_bit_info*) &frames[cnt].bit_info; + FT = info->frame_type; + + frames[cnt].buf = r; + info->start_bit = r_bitptr; + + if (FT == SID_FT) { + unsigned sti_bitptr; + sti_bitptr = r_bitptr + 35; + info->STI = (pj_uint8_t) + (r[sti_bitptr >> 3] >> (7 - (sti_bitptr % 8))) & 1; + } + + if (setting->octet_aligned) { + r += framelen_tbl[FT]; + frames[cnt].size = framelen_tbl[FT]; + } else { + if (FT == 14 || FT == 15) { + /* NO DATA */ + frames[cnt].size = 0; + } else { + unsigned adv_bit; + + adv_bit = framelenbit_tbl[FT] + r_bitptr; + r += adv_bit >> 3; + r_bitptr = (pj_uint8_t)(adv_bit % 8); + + frames[cnt].size = adv_bit >> 3; + if (r_bitptr) + ++frames[cnt].size; + } + } + ++cnt; } return PJ_SUCCESS; diff --git a/pjmedia/include/pjmedia-codec/amr_sdp_match.h b/pjmedia/include/pjmedia-codec/amr_sdp_match.h index 73e5ecd7bd..e500d330e2 100644 --- a/pjmedia/include/pjmedia-codec/amr_sdp_match.h +++ b/pjmedia/include/pjmedia-codec/amr_sdp_match.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -37,25 +36,25 @@ PJ_BEGIN_DECL * if octet-align mode needs to be adaptable to offerer setting, application * should set #PJMEDIA_SDP_NEG_FMT_MATCH_ALLOW_MODIFY_ANSWER in the option. * - * @param pool The memory pool. - * @param offer The SDP media offer. - * @param o_fmt_idx Index of the AMR format in the SDP media offer. - * @param answer The SDP media answer. - * @param a_fmt_idx Index of the AMR format in the SDP media answer. - * @param option The format matching option, see - * #pjmedia_sdp_neg_fmt_match_flag. + * @param pool The memory pool. + * @param offer The SDP media offer. + * @param o_fmt_idx Index of the AMR format in the SDP media offer. + * @param answer The SDP media answer. + * @param a_fmt_idx Index of the AMR format in the SDP media answer. + * @param option The format matching option, see + * #pjmedia_sdp_neg_fmt_match_flag. * - * @return PJ_SUCCESS when the formats in offer and answer match. + * @return PJ_SUCCESS when the formats in offer and answer match. */ PJ_DECL(pj_status_t) pjmedia_codec_amr_match_sdp( pj_pool_t *pool, - pjmedia_sdp_media *offer, - unsigned o_fmt_idx, - pjmedia_sdp_media *answer, - unsigned a_fmt_idx, - unsigned option); + pjmedia_sdp_media *offer, + unsigned o_fmt_idx, + pjmedia_sdp_media *answer, + unsigned a_fmt_idx, + unsigned option); PJ_END_DECL -#endif /* __PJMEDIA_CODEC_AMR_SDP_MATCH_H__ */ +#endif /* __PJMEDIA_CODEC_AMR_SDP_MATCH_H__ */ diff --git a/pjmedia/include/pjmedia-codec/and_aud_mediacodec.h b/pjmedia/include/pjmedia-codec/and_aud_mediacodec.h index 965ebfebd8..4fa5bd2fff 100644 --- a/pjmedia/include/pjmedia-codec/and_aud_mediacodec.h +++ b/pjmedia/include/pjmedia-codec/and_aud_mediacodec.h @@ -108,9 +108,9 @@ PJ_BEGIN_DECL * Initialize and register Android audio MediaCodec factory to pjmedia * endpoint. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_and_media_aud_init( pjmedia_endpt *endpt ); @@ -118,7 +118,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_and_media_aud_init( pjmedia_endpt *endpt ); * Unregister Android audio MediaCodec factory from pjmedia endpoint * and deinitialize the codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_and_media_aud_deinit( void ); @@ -128,4 +128,4 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODEC_AND_AUD_MEDIACODEC_H__ */ +#endif /* __PJMEDIA_CODEC_AND_AUD_MEDIACODEC_H__ */ diff --git a/pjmedia/include/pjmedia-codec/and_vid_mediacodec.h b/pjmedia/include/pjmedia-codec/and_vid_mediacodec.h index e1ee6e2c8f..138c0896fa 100644 --- a/pjmedia/include/pjmedia-codec/and_vid_mediacodec.h +++ b/pjmedia/include/pjmedia-codec/and_vid_mediacodec.h @@ -46,23 +46,23 @@ PJ_BEGIN_DECL /** * Initialize and register Android Mediacodec video codec factory. * - * @param mgr The video codec manager instance where this codec will - * be registered to. Specify NULL to use default instance - * (in that case, an instance of video codec manager must - * have been created beforehand). - * @param pf Pool factory. + * @param mgr The video codec manager instance where this codec will + * be registered to. Specify NULL to use default instance + * (in that case, an instance of video codec manager must + * have been created beforehand). + * @param pf Pool factory. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_and_media_vid_init( - pjmedia_vid_codec_mgr *mgr, + pjmedia_vid_codec_mgr *mgr, pj_pool_factory *pf); /** * Unregister Android Mediacodec video codecs factory from the video codec * manager and deinitialize the codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_and_media_vid_deinit(void); @@ -74,4 +74,4 @@ PJ_DECL(pj_status_t) pjmedia_codec_and_media_vid_deinit(void); PJ_END_DECL -#endif /* __PJMEDIA_CODEC_AND_VID_MEDIACODEC_H__ */ +#endif /* __PJMEDIA_CODEC_AND_VID_MEDIACODEC_H__ */ diff --git a/pjmedia/include/pjmedia-codec/audio_codecs.h b/pjmedia/include/pjmedia-codec/audio_codecs.h index 28367f7420..1a7153d536 100644 --- a/pjmedia/include/pjmedia-codec/audio_codecs.h +++ b/pjmedia/include/pjmedia-codec/audio_codecs.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011-2011 Teluu Inc. (http://www.teluu.com) * @@ -47,19 +46,19 @@ typedef struct pjmedia_audio_codec_config { /** Speex codec settings. See #pjmedia_codec_speex_init() for more info */ struct { - unsigned option; /**< Bitmask of options. */ - int quality; /**< Codec quality. */ - int complexity; /**< Codec complexity. */ + unsigned option; /**< Bitmask of options. */ + int quality; /**< Codec quality. */ + int complexity; /**< Codec complexity. */ } speex; /** iLBC settings */ struct { - unsigned mode; /**< iLBC mode. */ + unsigned mode; /**< iLBC mode. */ } ilbc; /** Passthrough */ struct { - pjmedia_codec_passthrough_setting setting; /**< Passthrough */ + pjmedia_codec_passthrough_setting setting; /**< Passthrough */ } passthrough; } pjmedia_audio_codec_config; @@ -68,7 +67,7 @@ typedef struct pjmedia_audio_codec_config /** * Initialize pjmedia_audio_codec_config structure with default values. * - * @param cfg The codec config to be initialized. + * @param cfg The codec config to be initialized. */ PJ_DECL(void) pjmedia_audio_codec_config_default(pjmedia_audio_codec_config *cfg); @@ -77,11 +76,11 @@ pjmedia_audio_codec_config_default(pjmedia_audio_codec_config *cfg); * Register all known audio codecs implemented in PJMEDA-CODEC library to the * specified media endpoint. * - * @param endpt The media endpoint. - * @param c Optional codec configuration, or NULL to use default - * values. + * @param endpt The media endpoint. + * @param c Optional codec configuration, or NULL to use default + * values. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_codec_register_audio_codecs(pjmedia_endpt *endpt, @@ -95,4 +94,4 @@ pjmedia_codec_register_audio_codecs(pjmedia_endpt *endpt, PJ_END_DECL -#endif /* __PJMEDIA_CODEC_ALL_CODECS_H__ */ +#endif /* __PJMEDIA_CODEC_ALL_CODECS_H__ */ diff --git a/pjmedia/include/pjmedia-codec/bcg729.h b/pjmedia/include/pjmedia-codec/bcg729.h index 03ab407a28..8634b33536 100644 --- a/pjmedia/include/pjmedia-codec/bcg729.h +++ b/pjmedia/include/pjmedia-codec/bcg729.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2017 Teluu Inc. (http://www.teluu.com) * @@ -95,9 +94,9 @@ PJ_BEGIN_DECL /** * Initialize and register BCG729 codec factory to pjmedia endpoint. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_bcg729_init(pjmedia_endpt *endpt); @@ -105,7 +104,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_bcg729_init(pjmedia_endpt *endpt); * Unregister BCG729 codec factory from pjmedia endpoint and deinitialize * the BCG729 codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_bcg729_deinit(void); @@ -117,5 +116,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODEC_BCG729_H__ */ +#endif /* __PJMEDIA_CODEC_BCG729_H__ */ diff --git a/pjmedia/include/pjmedia-codec/config.h b/pjmedia/include/pjmedia-codec/config.h index 2d01b806d6..048ba2935b 100644 --- a/pjmedia/include/pjmedia-codec/config.h +++ b/pjmedia/include/pjmedia-codec/config.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -54,7 +53,7 @@ * Settings to enable L16 codec 8KHz, mono. By default it is disabled. */ #ifndef PJMEDIA_CODEC_L16_HAS_8KHZ_MONO -# define PJMEDIA_CODEC_L16_HAS_8KHZ_MONO 0 +# define PJMEDIA_CODEC_L16_HAS_8KHZ_MONO 0 #endif @@ -62,7 +61,7 @@ * Settings to enable L16 codec 8KHz, stereo. By default it is disabled. */ #ifndef PJMEDIA_CODEC_L16_HAS_8KHZ_STEREO -# define PJMEDIA_CODEC_L16_HAS_8KHZ_STEREO 0 +# define PJMEDIA_CODEC_L16_HAS_8KHZ_STEREO 0 #endif @@ -70,7 +69,7 @@ * Settings to enable L16 codec 16KHz, mono. By default it is disabled. */ #ifndef PJMEDIA_CODEC_L16_HAS_16KHZ_MONO -# define PJMEDIA_CODEC_L16_HAS_16KHZ_MONO 0 +# define PJMEDIA_CODEC_L16_HAS_16KHZ_MONO 0 #endif @@ -78,7 +77,7 @@ * Settings to enable L16 codec 16KHz, stereo. By default it is disabled. */ #ifndef PJMEDIA_CODEC_L16_HAS_16KHZ_STEREO -# define PJMEDIA_CODEC_L16_HAS_16KHZ_STEREO 0 +# define PJMEDIA_CODEC_L16_HAS_16KHZ_STEREO 0 #endif @@ -86,7 +85,7 @@ * Settings to enable L16 codec 48KHz, mono. By default it is disabled. */ #ifndef PJMEDIA_CODEC_L16_HAS_48KHZ_MONO -# define PJMEDIA_CODEC_L16_HAS_48KHZ_MONO 0 +# define PJMEDIA_CODEC_L16_HAS_48KHZ_MONO 0 #endif @@ -94,7 +93,7 @@ * Settings to enable L16 codec 48KHz, stereo. By default it is disabled. */ #ifndef PJMEDIA_CODEC_L16_HAS_48KHZ_STEREO -# define PJMEDIA_CODEC_L16_HAS_48KHZ_STEREO 0 +# define PJMEDIA_CODEC_L16_HAS_48KHZ_STEREO 0 #endif @@ -125,7 +124,7 @@ * this setting via its codec quality setting (i.e PJSUA_DEFAULT_CODEC_QUALITY). */ #ifndef PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY -# define PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY 8 +# define PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY 8 #endif @@ -172,7 +171,7 @@ * Default: 2. */ #ifndef PJMEDIA_G722_DEFAULT_PCM_SHIFT -# define PJMEDIA_G722_DEFAULT_PCM_SHIFT 2 +# define PJMEDIA_G722_DEFAULT_PCM_SHIFT 2 #endif @@ -201,7 +200,7 @@ * Intel IPP with PJMEDIA. */ #ifndef PJMEDIA_HAS_INTEL_IPP -# define PJMEDIA_HAS_INTEL_IPP 0 +# define PJMEDIA_HAS_INTEL_IPP 0 #endif @@ -220,7 +219,7 @@ * Default 1. */ #ifndef PJMEDIA_AUTO_LINK_IPP_LIBS -# define PJMEDIA_AUTO_LINK_IPP_LIBS 1 +# define PJMEDIA_AUTO_LINK_IPP_LIBS 1 #endif @@ -232,7 +231,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_INTEL_IPP_CODEC_AMR -# define PJMEDIA_HAS_INTEL_IPP_CODEC_AMR 1 +# define PJMEDIA_HAS_INTEL_IPP_CODEC_AMR 1 #endif @@ -244,7 +243,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_INTEL_IPP_CODEC_AMRWB -# define PJMEDIA_HAS_INTEL_IPP_CODEC_AMRWB 1 +# define PJMEDIA_HAS_INTEL_IPP_CODEC_AMRWB 1 #endif @@ -255,7 +254,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_INTEL_IPP_CODEC_G729 -# define PJMEDIA_HAS_INTEL_IPP_CODEC_G729 1 +# define PJMEDIA_HAS_INTEL_IPP_CODEC_G729 1 #endif @@ -266,7 +265,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_INTEL_IPP_CODEC_G723_1 -# define PJMEDIA_HAS_INTEL_IPP_CODEC_G723_1 1 +# define PJMEDIA_HAS_INTEL_IPP_CODEC_G723_1 1 #endif @@ -277,7 +276,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_INTEL_IPP_CODEC_G726 -# define PJMEDIA_HAS_INTEL_IPP_CODEC_G726 1 +# define PJMEDIA_HAS_INTEL_IPP_CODEC_G726 1 #endif @@ -288,7 +287,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_INTEL_IPP_CODEC_G728 -# define PJMEDIA_HAS_INTEL_IPP_CODEC_G728 1 +# define PJMEDIA_HAS_INTEL_IPP_CODEC_G728 1 #endif @@ -299,7 +298,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1 -# define PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1 1 +# define PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1 1 #endif /** @@ -308,7 +307,7 @@ * Default: 0 */ #ifndef PJMEDIA_HAS_PASSTHROUGH_CODECS -# define PJMEDIA_HAS_PASSTHROUGH_CODECS 0 +# define PJMEDIA_HAS_PASSTHROUGH_CODECS 0 #endif /** @@ -317,7 +316,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR -# define PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR 1 +# define PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR 1 #endif /** @@ -326,7 +325,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_PASSTHROUGH_CODEC_G729 -# define PJMEDIA_HAS_PASSTHROUGH_CODEC_G729 1 +# define PJMEDIA_HAS_PASSTHROUGH_CODEC_G729 1 #endif /** @@ -335,7 +334,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_PASSTHROUGH_CODEC_ILBC -# define PJMEDIA_HAS_PASSTHROUGH_CODEC_ILBC 1 +# define PJMEDIA_HAS_PASSTHROUGH_CODEC_ILBC 1 #endif /** @@ -344,7 +343,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMU -# define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMU 1 +# define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMU 1 #endif /** @@ -353,7 +352,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMA -# define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMA 1 +# define PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMA 1 #endif /* If passthrough and PCMU/PCMA are enabled, disable the software @@ -362,7 +361,7 @@ #if PJMEDIA_HAS_PASSTHROUGH_CODECS && \ (PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMU || PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMA) # undef PJMEDIA_HAS_G711_CODEC -# define PJMEDIA_HAS_G711_CODEC 0 +# define PJMEDIA_HAS_G711_CODEC 0 #endif @@ -370,7 +369,7 @@ * G.722.1 codec is disabled by default. */ #ifndef PJMEDIA_HAS_G7221_CODEC -# define PJMEDIA_HAS_G7221_CODEC 0 +# define PJMEDIA_HAS_G7221_CODEC 0 #endif /** @@ -380,7 +379,7 @@ * Default: 0 */ #ifndef PJMEDIA_HAS_OPENCORE_AMRNB_CODEC -# define PJMEDIA_HAS_OPENCORE_AMRNB_CODEC 0 +# define PJMEDIA_HAS_OPENCORE_AMRNB_CODEC 0 #endif /** @@ -390,7 +389,7 @@ * Default: 0 */ #ifndef PJMEDIA_HAS_OPENCORE_AMRWB_CODEC -# define PJMEDIA_HAS_OPENCORE_AMRWB_CODEC 0 +# define PJMEDIA_HAS_OPENCORE_AMRWB_CODEC 0 #endif /** @@ -401,7 +400,7 @@ * Default: 1 */ #ifndef PJMEDIA_AUTO_LINK_OPENCORE_AMR_LIBS -# define PJMEDIA_AUTO_LINK_OPENCORE_AMR_LIBS 1 +# define PJMEDIA_AUTO_LINK_OPENCORE_AMR_LIBS 1 #endif /** @@ -412,7 +411,7 @@ * Default: 1 */ #ifndef PJMEDIA_OPENCORE_AMR_BUILT_WITH_GCC -# define PJMEDIA_OPENCORE_AMR_BUILT_WITH_GCC 1 +# define PJMEDIA_OPENCORE_AMR_BUILT_WITH_GCC 1 #endif @@ -426,7 +425,7 @@ * #pjmedia_codec_g7221_set_pcm_shift(). */ #ifndef PJMEDIA_G7221_DEFAULT_PCM_SHIFT -# define PJMEDIA_G7221_DEFAULT_PCM_SHIFT 1 +# define PJMEDIA_G7221_DEFAULT_PCM_SHIFT 1 #endif @@ -442,9 +441,9 @@ #if (PJMEDIA_HAS_G7221_CODEC != 0) && (PJMEDIA_HAS_INTEL_IPP != 0) && \ (PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1 != 0) # error Only one G.722.1 implementation can be enabled at the same time. \ - Please use PJMEDIA_HAS_G7221_CODEC and \ - PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1 in your config_site.h \ - to control which implementation to be used. + Please use PJMEDIA_HAS_G7221_CODEC and \ + PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1 in your config_site.h \ + to control which implementation to be used. #endif @@ -454,7 +453,7 @@ * Default: 0 */ #ifndef PJMEDIA_HAS_SILK_CODEC -# define PJMEDIA_HAS_SILK_CODEC 0 +# define PJMEDIA_HAS_SILK_CODEC 0 #endif @@ -476,7 +475,7 @@ * Default: 10 */ #ifndef PJMEDIA_CODEC_SILK_DEFAULT_QUALITY -# define PJMEDIA_CODEC_SILK_DEFAULT_QUALITY 10 +# define PJMEDIA_CODEC_SILK_DEFAULT_QUALITY 10 #endif @@ -486,7 +485,7 @@ * Default: 0 */ #ifndef PJMEDIA_HAS_OPUS_CODEC -# define PJMEDIA_HAS_OPUS_CODEC 0 +# define PJMEDIA_HAS_OPUS_CODEC 0 #endif /** @@ -495,7 +494,7 @@ * Default: 48000 */ #ifndef PJMEDIA_CODEC_OPUS_DEFAULT_SAMPLE_RATE -# define PJMEDIA_CODEC_OPUS_DEFAULT_SAMPLE_RATE 48000 +# define PJMEDIA_CODEC_OPUS_DEFAULT_SAMPLE_RATE 48000 #endif /** @@ -506,7 +505,7 @@ * rate, channel count, etc). */ #ifndef PJMEDIA_CODEC_OPUS_DEFAULT_BIT_RATE -# define PJMEDIA_CODEC_OPUS_DEFAULT_BIT_RATE 0 +# define PJMEDIA_CODEC_OPUS_DEFAULT_BIT_RATE 0 #endif @@ -517,7 +516,7 @@ * Default: 5 */ #ifndef PJMEDIA_CODEC_OPUS_DEFAULT_COMPLEXITY -# define PJMEDIA_CODEC_OPUS_DEFAULT_COMPLEXITY 5 +# define PJMEDIA_CODEC_OPUS_DEFAULT_COMPLEXITY 5 #endif @@ -527,7 +526,7 @@ * Default: PJ_FALSE (which means Opus will use VBR (variable bit rate)) */ #ifndef PJMEDIA_CODEC_OPUS_DEFAULT_CBR -# define PJMEDIA_CODEC_OPUS_DEFAULT_CBR PJ_FALSE +# define PJMEDIA_CODEC_OPUS_DEFAULT_CBR PJ_FALSE #endif @@ -537,7 +536,7 @@ * Default: 0 */ #ifndef PJMEDIA_HAS_BCG729 -# define PJMEDIA_HAS_BCG729 0 +# define PJMEDIA_HAS_BCG729 0 #endif @@ -547,7 +546,7 @@ * Default: PJMEDIA_HAS_LIBAVFORMAT */ #ifndef PJMEDIA_HAS_FFMPEG_CODEC -# define PJMEDIA_HAS_FFMPEG_CODEC PJMEDIA_HAS_LIBAVFORMAT +# define PJMEDIA_HAS_FFMPEG_CODEC PJMEDIA_HAS_LIBAVFORMAT #endif @@ -557,7 +556,7 @@ * Default: PJMEDIA_HAS_FFMPEG_CODEC */ #ifndef PJMEDIA_HAS_FFMPEG_VID_CODEC -# define PJMEDIA_HAS_FFMPEG_VID_CODEC PJMEDIA_HAS_FFMPEG_CODEC +# define PJMEDIA_HAS_FFMPEG_VID_CODEC PJMEDIA_HAS_FFMPEG_CODEC #endif /** @@ -566,7 +565,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_FFMPEG_CODEC_H263P -# define PJMEDIA_HAS_FFMPEG_CODEC_H263P PJMEDIA_HAS_FFMPEG_VID_CODEC +# define PJMEDIA_HAS_FFMPEG_CODEC_H263P PJMEDIA_HAS_FFMPEG_VID_CODEC #endif /** @@ -577,9 +576,9 @@ */ #ifndef PJMEDIA_HAS_FFMPEG_CODEC_H264 # if defined(PJMEDIA_HAS_OPENH264_CODEC) && PJMEDIA_HAS_OPENH264_CODEC != 0 -# define PJMEDIA_HAS_FFMPEG_CODEC_H264 0 +# define PJMEDIA_HAS_FFMPEG_CODEC_H264 0 # else -# define PJMEDIA_HAS_FFMPEG_CODEC_H264 PJMEDIA_HAS_FFMPEG_VID_CODEC +# define PJMEDIA_HAS_FFMPEG_CODEC_H264 PJMEDIA_HAS_FFMPEG_VID_CODEC # endif #endif @@ -588,17 +587,17 @@ */ #ifndef PJMEDIA_HAS_FFMPEG_CODEC_VP8 # if defined(PJMEDIA_HAS_VPX_CODEC) && PJMEDIA_HAS_VPX_CODEC != 0 -# define PJMEDIA_HAS_FFMPEG_CODEC_VP8 0 +# define PJMEDIA_HAS_FFMPEG_CODEC_VP8 0 # else -# define PJMEDIA_HAS_FFMPEG_CODEC_VP8 1 +# define PJMEDIA_HAS_FFMPEG_CODEC_VP8 1 # endif #endif #ifndef PJMEDIA_HAS_FFMPEG_CODEC_VP9 # if defined(PJMEDIA_HAS_VPX_CODEC) && PJMEDIA_HAS_VPX_CODEC != 0 -# define PJMEDIA_HAS_FFMPEG_CODEC_VP9 0 +# define PJMEDIA_HAS_FFMPEG_CODEC_VP9 0 # else -# define PJMEDIA_HAS_FFMPEG_CODEC_VP9 1 +# define PJMEDIA_HAS_FFMPEG_CODEC_VP9 1 # endif #endif @@ -620,7 +619,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_VPX_CODEC_VP8 -# define PJMEDIA_HAS_VPX_CODEC_VP8 1 +# define PJMEDIA_HAS_VPX_CODEC_VP8 1 #endif /** @@ -629,7 +628,7 @@ * Default: 0 (disabled) */ #ifndef PJMEDIA_HAS_VPX_CODEC_VP9 -# define PJMEDIA_HAS_VPX_CODEC_VP9 0 +# define PJMEDIA_HAS_VPX_CODEC_VP9 0 #endif /** @@ -638,7 +637,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_AND_MEDIA_AMRNB -# define PJMEDIA_HAS_AND_MEDIA_AMRNB 1 +# define PJMEDIA_HAS_AND_MEDIA_AMRNB 1 #endif /** @@ -647,7 +646,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_AND_MEDIA_AMRWB -# define PJMEDIA_HAS_AND_MEDIA_AMRWB 1 +# define PJMEDIA_HAS_AND_MEDIA_AMRWB 1 #endif /** @@ -656,7 +655,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_AND_MEDIA_H264 -# define PJMEDIA_HAS_AND_MEDIA_H264 1 +# define PJMEDIA_HAS_AND_MEDIA_H264 1 #endif /** @@ -665,7 +664,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_AND_MEDIA_VP8 -# define PJMEDIA_HAS_AND_MEDIA_VP8 1 +# define PJMEDIA_HAS_AND_MEDIA_VP8 1 #endif /** @@ -674,7 +673,7 @@ * Default: 1 */ #ifndef PJMEDIA_HAS_AND_MEDIA_VP9 -# define PJMEDIA_HAS_AND_MEDIA_VP9 1 +# define PJMEDIA_HAS_AND_MEDIA_VP9 1 #endif /** @@ -686,7 +685,7 @@ * Default: 1 */ #ifndef PJMEDIA_AND_MEDIA_PRIO_SW_VID_ENC -# define PJMEDIA_AND_MEDIA_PRIO_SW_VID_ENC 1 +# define PJMEDIA_AND_MEDIA_PRIO_SW_VID_ENC 1 #endif /** @@ -698,7 +697,7 @@ * Default: 1 */ #ifndef PJMEDIA_AND_MEDIA_PRIO_SW_VID_DEC -# define PJMEDIA_AND_MEDIA_PRIO_SW_VID_DEC 1 +# define PJMEDIA_AND_MEDIA_PRIO_SW_VID_DEC 1 #endif @@ -709,7 +708,7 @@ * Default: 5 (seconds) */ #ifndef PJMEDIA_CODEC_VID_TOOLBOX_MAX_KEYFRAME_INTERVAL -# define PJMEDIA_CODEC_VID_TOOLBOX_MAX_KEYFRAME_INTERVAL 5 +# define PJMEDIA_CODEC_VID_TOOLBOX_MAX_KEYFRAME_INTERVAL 5 #endif /** @@ -718,4 +717,4 @@ -#endif /* __PJMEDIA_CODEC_CONFIG_H__ */ +#endif /* __PJMEDIA_CODEC_CONFIG_H__ */ diff --git a/pjmedia/include/pjmedia-codec/config_auto.h.in b/pjmedia/include/pjmedia-codec/config_auto.h.in index 5a442eb042..3cc91263ef 100644 --- a/pjmedia/include/pjmedia-codec/config_auto.h.in +++ b/pjmedia/include/pjmedia-codec/config_auto.h.in @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,8 +26,8 @@ /* * Note: - * The configuration in config_site.h overrides any other settings, - * including the setting as detected by autoconf. + * The configuration in config_site.h overrides any other settings, + * including the setting as detected by autoconf. */ /* L16 codec */ @@ -99,6 +98,6 @@ #undef PJMEDIA_HAS_ANDROID_MEDIACODEC #endif -#endif /* __PJMEDIA_CODEC_CONFIG_AUTO_H_ */ +#endif /* __PJMEDIA_CODEC_CONFIG_AUTO_H_ */ diff --git a/pjmedia/include/pjmedia-codec/ffmpeg_vid_codecs.h b/pjmedia/include/pjmedia-codec/ffmpeg_vid_codecs.h index b27da310ab..08f0293b29 100644 --- a/pjmedia/include/pjmedia-codec/ffmpeg_vid_codecs.h +++ b/pjmedia/include/pjmedia-codec/ffmpeg_vid_codecs.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,13 +34,13 @@ PJ_BEGIN_DECL /** * Initialize and register FFMPEG video codecs factory to pjmedia endpoint. * - * @param mgr The video codec manager instance where this codec will - * be registered to. Specify NULL to use default instance - * (in that case, an instance of video codec manager must - * have been created beforehand). - * @param pf Pool factory. + * @param mgr The video codec manager instance where this codec will + * be registered to. Specify NULL to use default instance + * (in that case, an instance of video codec manager must + * have been created beforehand). + * @param pf Pool factory. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_ffmpeg_vid_init(pjmedia_vid_codec_mgr *mgr, pj_pool_factory *pf); @@ -51,7 +50,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_ffmpeg_vid_init(pjmedia_vid_codec_mgr *mgr, * Unregister FFMPEG video codecs factory from the video codec manager and * deinitialize the codecs library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_ffmpeg_vid_deinit(void); @@ -63,5 +62,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODECS_FFMPEG_VID_H__ */ +#endif /* __PJMEDIA_CODECS_FFMPEG_VID_H__ */ diff --git a/pjmedia/include/pjmedia-codec/g722.h b/pjmedia/include/pjmedia-codec/g722.h index c201a5f486..feec433fe7 100644 --- a/pjmedia/include/pjmedia-codec/g722.h +++ b/pjmedia/include/pjmedia-codec/g722.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -62,9 +61,9 @@ PJ_BEGIN_DECL /** * Initialize and register G.722 codec factory to pjmedia endpoint. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_g722_init(pjmedia_endpt *endpt); @@ -73,7 +72,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_g722_init(pjmedia_endpt *endpt); * Unregister G.722 codec factory from pjmedia endpoint and cleanup * resources allocated by the factory. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_g722_deinit(void); @@ -86,9 +85,9 @@ PJ_DECL(pj_status_t) pjmedia_codec_g722_deinit(void); * * Default value is PJMEDIA_G722_DEFAULT_PCM_SHIFT. * - * @param val The value + * @param val The value * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_g722_set_pcm_shift(unsigned val); diff --git a/pjmedia/include/pjmedia-codec/g7221.h b/pjmedia/include/pjmedia-codec/g7221.h index 7be8f9460b..18c550dfbb 100644 --- a/pjmedia/include/pjmedia-codec/g7221.h +++ b/pjmedia/include/pjmedia-codec/g7221.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -97,9 +96,9 @@ PJ_BEGIN_DECL /** * Initialize and register G.722.1 codec factory to pjmedia endpoint. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_g7221_init( pjmedia_endpt *endpt ); @@ -113,18 +112,18 @@ PJ_DECL(pj_status_t) pjmedia_codec_g7221_init( pjmedia_endpt *endpt ); * Note that currently only up to two non-standard modes can be enabled * at one time. * - * @param sample_rate PCM sampling rate, in Hz, valid values are only - * 16000 and 32000. - * @param bitrate G722.1 bitrate, in bps, the valid values are - * standard and non-standard bitrates as described - * above. - * @param enabled PJ_TRUE for enabling specified mode. + * @param sample_rate PCM sampling rate, in Hz, valid values are only + * 16000 and 32000. + * @param bitrate G722.1 bitrate, in bps, the valid values are + * standard and non-standard bitrates as described + * above. + * @param enabled PJ_TRUE for enabling specified mode. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_g7221_set_mode(unsigned sample_rate, - unsigned bitrate, - pj_bool_t enabled); + unsigned bitrate, + pj_bool_t enabled); /** * Set the G.722.1 codec encoder and decoder level adjustment. @@ -138,9 +137,9 @@ PJ_DECL(pj_status_t) pjmedia_codec_g7221_set_mode(unsigned sample_rate, * * Default value is PJMEDIA_G7221_DEFAULT_PCM_SHIFT. * - * @param val The value + * @param val The value * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_g7221_set_pcm_shift(int val); @@ -149,7 +148,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_g7221_set_pcm_shift(int val); /** * Unregister G.722.1 codecs factory from pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_g7221_deinit(void); @@ -161,5 +160,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODECS_G7221_H__ */ +#endif /* __PJMEDIA_CODECS_G7221_H__ */ diff --git a/pjmedia/include/pjmedia-codec/g7221_sdp_match.h b/pjmedia/include/pjmedia-codec/g7221_sdp_match.h index a4dca0bd9a..0560ca7f0d 100644 --- a/pjmedia/include/pjmedia-codec/g7221_sdp_match.h +++ b/pjmedia/include/pjmedia-codec/g7221_sdp_match.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,25 +34,25 @@ PJ_BEGIN_DECL * will match G.722.1 bitrate setting in the SDP format parameter of * offer and answer. * - * @param pool The memory pool. - * @param offer The SDP media offer. - * @param o_fmt_idx Index of the G.722.1 format in the SDP media offer. - * @param answer The SDP media answer. - * @param a_fmt_idx Index of the G.722.1 format in the SDP media answer. - * @param option The format matching option, see - * #pjmedia_sdp_neg_fmt_match_flag. + * @param pool The memory pool. + * @param offer The SDP media offer. + * @param o_fmt_idx Index of the G.722.1 format in the SDP media offer. + * @param answer The SDP media answer. + * @param a_fmt_idx Index of the G.722.1 format in the SDP media answer. + * @param option The format matching option, see + * #pjmedia_sdp_neg_fmt_match_flag. * - * @return PJ_SUCCESS when the formats in offer and answer match. + * @return PJ_SUCCESS when the formats in offer and answer match. */ PJ_DECL(pj_status_t) pjmedia_codec_g7221_match_sdp( pj_pool_t *pool, - pjmedia_sdp_media *offer, - unsigned o_fmt_idx, - pjmedia_sdp_media *answer, - unsigned a_fmt_idx, - unsigned option); + pjmedia_sdp_media *offer, + unsigned o_fmt_idx, + pjmedia_sdp_media *answer, + unsigned a_fmt_idx, + unsigned option); PJ_END_DECL -#endif /* __PJMEDIA_CODEC_G7221_SDP_MATCH_H__ */ +#endif /* __PJMEDIA_CODEC_G7221_SDP_MATCH_H__ */ diff --git a/pjmedia/include/pjmedia-codec/gsm.h b/pjmedia/include/pjmedia-codec/gsm.h index 2e213806e3..2c47b146ff 100644 --- a/pjmedia/include/pjmedia-codec/gsm.h +++ b/pjmedia/include/pjmedia-codec/gsm.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -59,9 +58,9 @@ PJ_BEGIN_DECL /** * Initialize and register GSM codec factory to pjmedia endpoint. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_gsm_init( pjmedia_endpt *endpt ); @@ -71,7 +70,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_gsm_init( pjmedia_endpt *endpt ); * Unregister GSM codec factory from pjmedia endpoint and deinitialize * the GSM codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_gsm_deinit(void); @@ -83,5 +82,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODEC_GSM_H__ */ +#endif /* __PJMEDIA_CODEC_GSM_H__ */ diff --git a/pjmedia/include/pjmedia-codec/h263_packetizer.h b/pjmedia/include/pjmedia-codec/h263_packetizer.h index 1bf7009be4..5f57fd77ae 100644 --- a/pjmedia/include/pjmedia-codec/h263_packetizer.h +++ b/pjmedia/include/pjmedia-codec/h263_packetizer.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -65,7 +64,7 @@ typedef struct pjmedia_h263_packetizer_cfg * Maximum payload length. * Default: PJMEDIA_MAX_MTU */ - int mtu; + int mtu; /** * Packetization mode. @@ -79,17 +78,17 @@ typedef struct pjmedia_h263_packetizer_cfg /** * Create H.263 packetizer. * - * @param pool The memory pool. - * @param cfg Packetizer settings, if NULL, default setting - * will be used. - * @param p_pktz Pointer to receive the packetizer. + * @param pool The memory pool. + * @param cfg Packetizer settings, if NULL, default setting + * will be used. + * @param p_pktz Pointer to receive the packetizer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_h263_packetizer_create( - pj_pool_t *pool, - const pjmedia_h263_packetizer_cfg *cfg, - pjmedia_h263_packetizer **p_pktz); + pj_pool_t *pool, + const pjmedia_h263_packetizer_cfg *cfg, + pjmedia_h263_packetizer **p_pktz); /** @@ -97,17 +96,17 @@ PJ_DECL(pj_status_t) pjmedia_h263_packetizer_create( * function will apply in-place processing, so the bitstream may be modified * during the packetization. * - * @param pktz The packetizer. - * @param bits The picture bitstream to be packetized. - * @param bits_len The length of the bitstream. - * @param bits_pos The bitstream offset to be packetized. - * @param payload The output payload. - * @param payload_len The output payload length. + * @param pktz The packetizer. + * @param bits The picture bitstream to be packetized. + * @param bits_len The length of the bitstream. + * @param bits_pos The bitstream offset to be packetized. + * @param payload The output payload. + * @param payload_len The output payload length. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_h263_packetize(pjmedia_h263_packetizer *pktz, - pj_uint8_t *bits, + pj_uint8_t *bits, pj_size_t bits_len, unsigned *bits_pos, const pj_uint8_t **payload, @@ -120,27 +119,27 @@ PJ_DECL(pj_status_t) pjmedia_h263_packetize(pjmedia_h263_packetizer *pktz, * payload pointer set to NULL, as the packetizer need to update its internal * state. * - * @param pktz The packetizer. - * @param payload The payload to be unpacketized. - * @param payload_len The payload length. - * @param bits The bitstream buffer. - * @param bits_size The bitstream buffer size. - * @param bits_pos The bitstream offset to put the unpacketized payload - * in the bitstream, upon return, this will be updated - * to the latest offset as a result of the unpacketized - * payload. + * @param pktz The packetizer. + * @param payload The payload to be unpacketized. + * @param payload_len The payload length. + * @param bits The bitstream buffer. + * @param bits_size The bitstream buffer size. + * @param bits_pos The bitstream offset to put the unpacketized payload + * in the bitstream, upon return, this will be updated + * to the latest offset as a result of the unpacketized + * payload. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_h263_unpacketize(pjmedia_h263_packetizer *pktz, - const pj_uint8_t *payload, + const pj_uint8_t *payload, pj_size_t payload_len, pj_uint8_t *bits, pj_size_t bits_size, - unsigned *bits_pos); + unsigned *bits_pos); PJ_END_DECL -#endif /* __PJMEDIA_H263_PACKETIZER_H__ */ +#endif /* __PJMEDIA_H263_PACKETIZER_H__ */ diff --git a/pjmedia/include/pjmedia-codec/h264_packetizer.h b/pjmedia/include/pjmedia-codec/h264_packetizer.h index a2403b51b7..ecddcb070b 100644 --- a/pjmedia/include/pjmedia-codec/h264_packetizer.h +++ b/pjmedia/include/pjmedia-codec/h264_packetizer.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011 Teluu Inc. (http://www.teluu.com) * @@ -77,7 +76,7 @@ typedef struct pjmedia_h264_packetizer_cfg * Maximum payload length. * Default: PJMEDIA_MAX_MTU */ - int mtu; + int mtu; /** * Packetization mode. @@ -98,17 +97,17 @@ pjmedia_h264_packetizer_cfg; /** * Create H.264 packetizer. * - * @param pool The memory pool. - * @param cfg Packetizer settings, if NULL, default setting - * will be used. - * @param p_pktz Pointer to receive the packetizer. + * @param pool The memory pool. + * @param cfg Packetizer settings, if NULL, default setting + * will be used. + * @param p_pktz Pointer to receive the packetizer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_h264_packetizer_create( - pj_pool_t *pool, - const pjmedia_h264_packetizer_cfg *cfg, - pjmedia_h264_packetizer **p_pktz); + pj_pool_t *pool, + const pjmedia_h264_packetizer_cfg *cfg, + pjmedia_h264_packetizer **p_pktz); /** @@ -116,17 +115,17 @@ PJ_DECL(pj_status_t) pjmedia_h264_packetizer_create( * function will apply in-place processing, so the bitstream may be modified * during the packetization. * - * @param pktz The packetizer. - * @param bits The picture bitstream to be packetized. - * @param bits_len The length of the bitstream. - * @param bits_pos The bitstream offset to be packetized. - * @param payload The output payload. - * @param payload_len The output payload length. + * @param pktz The packetizer. + * @param bits The picture bitstream to be packetized. + * @param bits_len The length of the bitstream. + * @param bits_pos The bitstream offset to be packetized. + * @param payload The output payload. + * @param payload_len The output payload length. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_h264_packetize(pjmedia_h264_packetizer *pktz, - pj_uint8_t *bits, + pj_uint8_t *bits, pj_size_t bits_len, unsigned *bits_pos, const pj_uint8_t **payload, @@ -139,26 +138,26 @@ PJ_DECL(pj_status_t) pjmedia_h264_packetize(pjmedia_h264_packetizer *pktz, * payload pointer set to NULL, as the packetizer need to update its internal * state. * - * @param pktz The packetizer. - * @param payload The payload to be unpacketized. - * @param payload_len The payload length. - * @param bits The bitstream buffer. - * @param bits_len The bitstream buffer size. - * @param bits_pos The bitstream offset to put the unpacketized payload - * in the bitstream, upon return, this will be updated - * to the latest offset as a result of the unpacketized - * payload. + * @param pktz The packetizer. + * @param payload The payload to be unpacketized. + * @param payload_len The payload length. + * @param bits The bitstream buffer. + * @param bits_len The bitstream buffer size. + * @param bits_pos The bitstream offset to put the unpacketized payload + * in the bitstream, upon return, this will be updated + * to the latest offset as a result of the unpacketized + * payload. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_h264_unpacketize(pjmedia_h264_packetizer *pktz, - const pj_uint8_t *payload, + const pj_uint8_t *payload, pj_size_t payload_len, pj_uint8_t *bits, pj_size_t bits_len, - unsigned *bits_pos); + unsigned *bits_pos); PJ_END_DECL -#endif /* __PJMEDIA_H264_PACKETIZER_H__ */ +#endif /* __PJMEDIA_H264_PACKETIZER_H__ */ diff --git a/pjmedia/include/pjmedia-codec/ilbc.h b/pjmedia/include/pjmedia-codec/ilbc.h index 0cd217a169..5910b8f69c 100644 --- a/pjmedia/include/pjmedia-codec/ilbc.h +++ b/pjmedia/include/pjmedia-codec/ilbc.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -87,15 +86,15 @@ PJ_BEGIN_DECL /** * Initialize and register iLBC codec factory to pjmedia endpoint. * - * @param endpt The pjmedia endpoint. - * @param mode Default decoder mode to be used. Valid values are - * 20 and 30 ms. Note that encoder mode follows the - * setting advertised in the remote's SDP. + * @param endpt The pjmedia endpoint. + * @param mode Default decoder mode to be used. Valid values are + * 20 and 30 ms. Note that encoder mode follows the + * setting advertised in the remote's SDP. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_ilbc_init( pjmedia_endpt *endpt, - int mode ); + int mode ); @@ -103,7 +102,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_ilbc_init( pjmedia_endpt *endpt, * Unregister iLBC codec factory from pjmedia endpoint and deinitialize * the iLBC codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_ilbc_deinit(void); @@ -115,5 +114,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODEC_ILBC_H__ */ +#endif /* __PJMEDIA_CODEC_ILBC_H__ */ diff --git a/pjmedia/include/pjmedia-codec/ipp_codecs.h b/pjmedia/include/pjmedia-codec/ipp_codecs.h index d38f9a6596..a1b8f1a850 100644 --- a/pjmedia/include/pjmedia-codec/ipp_codecs.h +++ b/pjmedia/include/pjmedia-codec/ipp_codecs.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -295,9 +294,9 @@ PJ_BEGIN_DECL /** * Initialize and register IPP codecs factory to pjmedia endpoint. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_ipp_init( pjmedia_endpt *endpt ); @@ -306,7 +305,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_ipp_init( pjmedia_endpt *endpt ); * Unregister IPP codecs factory from pjmedia endpoint and deinitialize * the IPP codecs library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_ipp_deinit(void); @@ -318,5 +317,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODECS_IPP_H__ */ +#endif /* __PJMEDIA_CODECS_IPP_H__ */ diff --git a/pjmedia/include/pjmedia-codec/l16.h b/pjmedia/include/pjmedia-codec/l16.h index f99d0429a3..d0034f4868 100644 --- a/pjmedia/include/pjmedia-codec/l16.h +++ b/pjmedia/include/pjmedia-codec/l16.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -56,20 +55,20 @@ PJ_BEGIN_DECL /** * Initialize and register L16 codec factory to pjmedia endpoint. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * @param options Must be zero for now. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_l16_init( pjmedia_endpt *endpt, - unsigned options); + unsigned options); /** * Unregister L16 codec factory from pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_l16_deinit(void); @@ -80,5 +79,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODEC_L16_H__ */ +#endif /* __PJMEDIA_CODEC_L16_H__ */ diff --git a/pjmedia/include/pjmedia-codec/opencore_amr.h b/pjmedia/include/pjmedia-codec/opencore_amr.h index 067250b016..e2fa9f107c 100644 --- a/pjmedia/include/pjmedia-codec/opencore_amr.h +++ b/pjmedia/include/pjmedia-codec/opencore_amr.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011-2013 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2011 Dan Arrhenius @@ -36,8 +35,8 @@ PJ_BEGIN_DECL */ enum pjmedia_amr_options { - PJMEDIA_AMR_NO_NB = 1, /**< Disable narrowband mode. */ - PJMEDIA_AMR_NO_WB = 2, /**< Disable wideband mode. */ + PJMEDIA_AMR_NO_NB = 1, /**< Disable narrowband mode. */ + PJMEDIA_AMR_NO_WB = 2, /**< Disable wideband mode. */ }; /** @@ -78,7 +77,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_opencore_amr_init(pjmedia_endpt* endpt, * * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_opencore_amr_init_default(pjmedia_endpt* endpt); @@ -87,7 +86,7 @@ pjmedia_codec_opencore_amr_init_default(pjmedia_endpt* endpt); * Unregister AMR codec factory from pjmedia endpoint and deinitialize * the OpenCORE codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_opencore_amr_deinit(void); @@ -99,9 +98,9 @@ PJ_DECL(pj_status_t) pjmedia_codec_opencore_amr_deinit(void); * should call #pjmedia_codec_opencore_amr_init() instead if wishing to use * both modes. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_opencore_amrnb_init(pjmedia_endpt* endpt); @@ -109,7 +108,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_opencore_amrnb_init(pjmedia_endpt* endpt); * Unregister AMR-NB codec factory from pjmedia endpoint and deinitialize * the OpenCORE codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_opencore_amrnb_deinit(void); @@ -117,20 +116,20 @@ PJ_DECL(pj_status_t) pjmedia_codec_opencore_amrnb_deinit(void); /** * Set AMR-NB parameters. * - * @param cfg The settings; + * @param cfg The settings; * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_opencore_amrnb_set_config( - const pjmedia_codec_amrnb_config* cfg); + const pjmedia_codec_amrnb_config* cfg); /** * Set AMR-WB parameters. * - * @param cfg The settings; + * @param cfg The settings; * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_opencore_amrwb_set_config( const pjmedia_codec_amrwb_config* cfg); @@ -142,5 +141,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODEC_OPENCORE_AMRNB_H__ */ +#endif /* __PJMEDIA_CODEC_OPENCORE_AMRNB_H__ */ diff --git a/pjmedia/include/pjmedia-codec/openh264.h b/pjmedia/include/pjmedia-codec/openh264.h index d41ea4283a..1d78e5f896 100644 --- a/pjmedia/include/pjmedia-codec/openh264.h +++ b/pjmedia/include/pjmedia-codec/openh264.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2014 Teluu Inc. (http://www.teluu.com) * @@ -39,13 +38,13 @@ PJ_BEGIN_DECL /** * Initialize and register OpenH264 codec factory. * - * @param mgr The video codec manager instance where this codec will - * be registered to. Specify NULL to use default instance - * (in that case, an instance of video codec manager must - * have been created beforehand). - * @param pf Pool factory. + * @param mgr The video codec manager instance where this codec will + * be registered to. Specify NULL to use default instance + * (in that case, an instance of video codec manager must + * have been created beforehand). + * @param pf Pool factory. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_openh264_vid_init(pjmedia_vid_codec_mgr *mgr, pj_pool_factory *pf); @@ -54,7 +53,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_openh264_vid_init(pjmedia_vid_codec_mgr *mgr, * Unregister OpenH264 video codecs factory from the video codec manager and * deinitialize the codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_openh264_vid_deinit(void); @@ -66,4 +65,4 @@ PJ_DECL(pj_status_t) pjmedia_codec_openh264_vid_deinit(void); PJ_END_DECL -#endif /* __PJMEDIA_CODEC_OPENH264_H__ */ +#endif /* __PJMEDIA_CODEC_OPENH264_H__ */ diff --git a/pjmedia/include/pjmedia-codec/opus.h b/pjmedia/include/pjmedia-codec/opus.h index 38154a3e4d..9438c7daa1 100644 --- a/pjmedia/include/pjmedia-codec/opus.h +++ b/pjmedia/include/pjmedia-codec/opus.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2015-2016 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2012-2015 Zaark Technology AB @@ -99,20 +98,20 @@ typedef struct pjmedia_codec_opus_config { unsigned sample_rate; /**< Sample rate in Hz. */ unsigned channel_cnt; /**< Number of channels. */ - unsigned frm_ptime; /**< Frame time in msec. */ - unsigned bit_rate; /**< Encoder bit rate in bps. */ - unsigned packet_loss; /**< Encoder's expected packet loss pct. */ + unsigned frm_ptime; /**< Frame time in msec. */ + unsigned bit_rate; /**< Encoder bit rate in bps. */ + unsigned packet_loss; /**< Encoder's expected packet loss pct. */ unsigned complexity; /**< Encoder complexity, 0-10(10 is highest)*/ - pj_bool_t cbr; /**< Constant bit rate? */ + pj_bool_t cbr; /**< Constant bit rate? */ } pjmedia_codec_opus_config; /** * Initialize and register Opus codec factory to pjmedia endpoint. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_opus_init( pjmedia_endpt *endpt ); @@ -120,16 +119,16 @@ PJ_DECL(pj_status_t) pjmedia_codec_opus_init( pjmedia_endpt *endpt ); * Unregister Opus codec factory from pjmedia endpoint and deinitialize * the Opus codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_opus_deinit( void ); /** * Get the default Opus configuration. * - * @param cfg Opus codec configuration. + * @param cfg Opus codec configuration. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_opus_get_config( pjmedia_codec_opus_config *cfg ); @@ -138,18 +137,18 @@ pjmedia_codec_opus_get_config( pjmedia_codec_opus_config *cfg ); * Set the default Opus configuration and set the default Opus codec param. * Note that the function will call #pjmedia_codec_mgr_set_default_param(). * - * @param cfg Opus codec configuration. - * @param param On input, the default Opus codec parameter to be set. - * On output, the current default Opus codec parameter - * after setting. This may be different from the input - * because some settings can be rejected, or overwritten - * by the Opus codec configuration above. + * @param cfg Opus codec configuration. + * @param param On input, the default Opus codec parameter to be set. + * On output, the current default Opus codec parameter + * after setting. This may be different from the input + * because some settings can be rejected, or overwritten + * by the Opus codec configuration above. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_opus_set_default_param(const pjmedia_codec_opus_config *cfg, - pjmedia_codec_param *param ); + pjmedia_codec_param *param ); PJ_END_DECL @@ -157,4 +156,4 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODEC_OPUS_H__ */ +#endif /* __PJMEDIA_CODEC_OPUS_H__ */ diff --git a/pjmedia/include/pjmedia-codec/passthrough.h b/pjmedia/include/pjmedia-codec/passthrough.h index c2d2b2f6ab..94b8c850a0 100644 --- a/pjmedia/include/pjmedia-codec/passthrough.h +++ b/pjmedia/include/pjmedia-codec/passthrough.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -225,11 +224,11 @@ PJ_BEGIN_DECL */ typedef struct pjmedia_codec_passthrough_setting { - unsigned fmt_cnt; /**< Number of encoding formats - to be enabled. */ - pjmedia_format *fmts; /**< Encoding formats to be - enabled. */ - unsigned ilbc_mode; /**< iLBC default mode. */ + unsigned fmt_cnt; /**< Number of encoding formats + to be enabled. */ + pjmedia_format *fmts; /**< Encoding formats to be + enabled. */ + unsigned ilbc_mode; /**< iLBC default mode. */ } pjmedia_codec_passthrough_setting; @@ -237,9 +236,9 @@ typedef struct pjmedia_codec_passthrough_setting * Initialize and register passthrough codecs factory to pjmedia endpoint, * all supported encoding formats will be enabled. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_passthrough_init( pjmedia_endpt *endpt ); @@ -248,20 +247,20 @@ PJ_DECL(pj_status_t) pjmedia_codec_passthrough_init( pjmedia_endpt *endpt ); * Initialize and register passthrough codecs factory to pjmedia endpoint * with only specified encoding formats enabled. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * @param setting The settings. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_passthrough_init2( - pjmedia_endpt *endpt, - const pjmedia_codec_passthrough_setting *setting); + pjmedia_endpt *endpt, + const pjmedia_codec_passthrough_setting *setting); /** * Unregister passthrough codecs factory from pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_passthrough_deinit(void); @@ -273,5 +272,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODECS_PASSTHROUGH_H__ */ +#endif /* __PJMEDIA_CODECS_PASSTHROUGH_H__ */ diff --git a/pjmedia/include/pjmedia-codec/silk.h b/pjmedia/include/pjmedia-codec/silk.h index e6d09b42c9..3d8819b4f0 100644 --- a/pjmedia/include/pjmedia-codec/silk.h +++ b/pjmedia/include/pjmedia-codec/silk.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2012-2012 Teluu Inc. (http://www.teluu.com) * Contributed by Regis Montoya (aka r3gis - www.r3gis.fr) @@ -68,11 +67,11 @@ PJ_BEGIN_DECL typedef struct pjmedia_codec_silk_setting { - pj_bool_t enabled; /**< Enable/disable. */ - int quality; /**< Encoding quality, or use -1 for default - (@see PJMEDIA_CODEC_SILK_DEFAULT_QUALITY). */ - int complexity; /**< Encoding complexity, or use -1 for default - (@see PJMEDIA_CODEC_SILK_DEFAULT_COMPLEXITY)*/ + pj_bool_t enabled; /**< Enable/disable. */ + int quality; /**< Encoding quality, or use -1 for default + (@see PJMEDIA_CODEC_SILK_DEFAULT_QUALITY). */ + int complexity; /**< Encoding complexity, or use -1 for default + (@see PJMEDIA_CODEC_SILK_DEFAULT_COMPLEXITY)*/ } pjmedia_codec_silk_setting; @@ -84,9 +83,9 @@ typedef struct pjmedia_codec_silk_setting * and #PJMEDIA_CODEC_SILK_DEFAULT_COMPLEXITY), application may modify these * settings via #pjmedia_codec_silk_set_config(). * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_silk_init(pjmedia_endpt *endpt); @@ -95,23 +94,23 @@ PJ_DECL(pj_status_t) pjmedia_codec_silk_init(pjmedia_endpt *endpt); * Change the configuration setting of the SILK codec for the specified * clock rate. * - * @param clock_rate PCM sampling rate, in Hz, valid values are 8000, - * 12000, 16000 and 24000. - * @param opt The setting to be applied for the specified - * clock rate. + * @param clock_rate PCM sampling rate, in Hz, valid values are 8000, + * 12000, 16000 and 24000. + * @param opt The setting to be applied for the specified + * clock rate. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_silk_set_config( - unsigned clock_rate, - const pjmedia_codec_silk_setting *opt); + unsigned clock_rate, + const pjmedia_codec_silk_setting *opt); /** * Unregister SILK codec factory from pjmedia endpoint and deinitialize * the SILK codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_silk_deinit(void); @@ -123,5 +122,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODEC_SILK_H__ */ +#endif /* __PJMEDIA_CODEC_SILK_H__ */ diff --git a/pjmedia/include/pjmedia-codec/speex.h b/pjmedia/include/pjmedia-codec/speex.h index 99db020c6b..c51664ffab 100644 --- a/pjmedia/include/pjmedia-codec/speex.h +++ b/pjmedia/include/pjmedia-codec/speex.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -80,37 +79,37 @@ PJ_BEGIN_DECL */ enum pjmedia_speex_options { - PJMEDIA_SPEEX_NO_NB = 1, /**< Disable narrowband mode. */ - PJMEDIA_SPEEX_NO_WB = 2, /**< Disable wideband mode. */ - PJMEDIA_SPEEX_NO_UWB = 4, /**< Disable ultra-wideband mode. */ + PJMEDIA_SPEEX_NO_NB = 1, /**< Disable narrowband mode. */ + PJMEDIA_SPEEX_NO_WB = 2, /**< Disable wideband mode. */ + PJMEDIA_SPEEX_NO_UWB = 4, /**< Disable ultra-wideband mode. */ }; /** * Initialize and register Speex codec factory to pjmedia endpoint. * - * @param endpt The pjmedia endpoint. - * @param options Bitmask of pjmedia_speex_options (default=0). - * @param quality Specify encoding quality, or use -1 for default - * (@see PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY). - * @param complexity Specify encoding complexity , or use -1 for default - * (@see PJMEDIA_CODEC_SPEEX_DEFAULT_COMPLEXITY). + * @param endpt The pjmedia endpoint. + * @param options Bitmask of pjmedia_speex_options (default=0). + * @param quality Specify encoding quality, or use -1 for default + * (@see PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY). + * @param complexity Specify encoding complexity , or use -1 for default + * (@see PJMEDIA_CODEC_SPEEX_DEFAULT_COMPLEXITY). * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_speex_init( pjmedia_endpt *endpt, - unsigned options, - int quality, - int complexity ); + unsigned options, + int quality, + int complexity ); /** * Initialize Speex codec factory using default settings and register to * pjmedia endpoint. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_speex_init_default(pjmedia_endpt *endpt); @@ -118,24 +117,24 @@ PJ_DECL(pj_status_t) pjmedia_codec_speex_init_default(pjmedia_endpt *endpt); /** * Change the settings of Speex codec. * - * @param clock_rate Clock rate of Speex mode to be set. - * @param quality Specify encoding quality, or use -1 for default - * (@see PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY). - * @param complexity Specify encoding complexity , or use -1 for default - * (@see PJMEDIA_CODEC_SPEEX_DEFAULT_COMPLEXITY). + * @param clock_rate Clock rate of Speex mode to be set. + * @param quality Specify encoding quality, or use -1 for default + * (@see PJMEDIA_CODEC_SPEEX_DEFAULT_QUALITY). + * @param complexity Specify encoding complexity , or use -1 for default + * (@see PJMEDIA_CODEC_SPEEX_DEFAULT_COMPLEXITY). * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_speex_set_param(unsigned clock_rate, - int quality, - int complexity); + int quality, + int complexity); /** * Unregister Speex codec factory from pjmedia endpoint and deinitialize * the Speex codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_speex_deinit(void); @@ -146,5 +145,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_CODEC_SPEEX_H__ */ +#endif /* __PJMEDIA_CODEC_SPEEX_H__ */ diff --git a/pjmedia/include/pjmedia-codec/types.h b/pjmedia/include/pjmedia-codec/types.h index fd78a1c1e0..f03b06ceed 100644 --- a/pjmedia/include/pjmedia-codec/types.h +++ b/pjmedia/include/pjmedia-codec/types.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -60,53 +59,53 @@ enum pjmedia_audio_pt */ PJMEDIA_RTP_PT_START = (PJMEDIA_RTP_PT_DYNAMIC-1), - PJMEDIA_RTP_PT_SPEEX_NB, /**< Speex narrowband/8KHz */ - PJMEDIA_RTP_PT_SPEEX_WB, /**< Speex wideband/16KHz */ - PJMEDIA_RTP_PT_SPEEX_UWB, /**< Speex 32KHz */ - PJMEDIA_RTP_PT_SILK_NB, /**< SILK narrowband/8KHz */ - PJMEDIA_RTP_PT_SILK_MB, /**< SILK mediumband/12KHz */ - PJMEDIA_RTP_PT_SILK_WB, /**< SILK wideband/16KHz */ - PJMEDIA_RTP_PT_SILK_SWB, /**< SILK 24KHz */ - PJMEDIA_RTP_PT_ILBC, /**< iLBC (13.3/15.2Kbps) */ - PJMEDIA_RTP_PT_AMR, /**< AMR (4.75 - 12.2Kbps) */ - PJMEDIA_RTP_PT_AMRWB, /**< AMRWB (6.6 - 23.85Kbps)*/ - PJMEDIA_RTP_PT_AMRWBE, /**< AMRWBE */ - PJMEDIA_RTP_PT_G726_16, /**< G726 @ 16Kbps */ - PJMEDIA_RTP_PT_G726_24, /**< G726 @ 24Kbps */ - PJMEDIA_RTP_PT_G726_32, /**< G726 @ 32Kbps */ - PJMEDIA_RTP_PT_G726_40, /**< G726 @ 40Kbps */ - PJMEDIA_RTP_PT_G722_1_16, /**< G722.1 (16Kbps) */ - PJMEDIA_RTP_PT_G722_1_24, /**< G722.1 (24Kbps) */ - PJMEDIA_RTP_PT_G722_1_32, /**< G722.1 (32Kbps) */ - PJMEDIA_RTP_PT_G7221C_24, /**< G722.1 Annex C (24Kbps)*/ - PJMEDIA_RTP_PT_G7221C_32, /**< G722.1 Annex C (32Kbps)*/ - PJMEDIA_RTP_PT_G7221C_48, /**< G722.1 Annex C (48Kbps)*/ - PJMEDIA_RTP_PT_G7221_RSV1, /**< G722.1 reserve */ - PJMEDIA_RTP_PT_G7221_RSV2, /**< G722.1 reserve */ - PJMEDIA_RTP_PT_OPUS, /**< OPUS */ + PJMEDIA_RTP_PT_SPEEX_NB, /**< Speex narrowband/8KHz */ + PJMEDIA_RTP_PT_SPEEX_WB, /**< Speex wideband/16KHz */ + PJMEDIA_RTP_PT_SPEEX_UWB, /**< Speex 32KHz */ + PJMEDIA_RTP_PT_SILK_NB, /**< SILK narrowband/8KHz */ + PJMEDIA_RTP_PT_SILK_MB, /**< SILK mediumband/12KHz */ + PJMEDIA_RTP_PT_SILK_WB, /**< SILK wideband/16KHz */ + PJMEDIA_RTP_PT_SILK_SWB, /**< SILK 24KHz */ + PJMEDIA_RTP_PT_ILBC, /**< iLBC (13.3/15.2Kbps) */ + PJMEDIA_RTP_PT_AMR, /**< AMR (4.75 - 12.2Kbps) */ + PJMEDIA_RTP_PT_AMRWB, /**< AMRWB (6.6 - 23.85Kbps)*/ + PJMEDIA_RTP_PT_AMRWBE, /**< AMRWBE */ + PJMEDIA_RTP_PT_G726_16, /**< G726 @ 16Kbps */ + PJMEDIA_RTP_PT_G726_24, /**< G726 @ 24Kbps */ + PJMEDIA_RTP_PT_G726_32, /**< G726 @ 32Kbps */ + PJMEDIA_RTP_PT_G726_40, /**< G726 @ 40Kbps */ + PJMEDIA_RTP_PT_G722_1_16, /**< G722.1 (16Kbps) */ + PJMEDIA_RTP_PT_G722_1_24, /**< G722.1 (24Kbps) */ + PJMEDIA_RTP_PT_G722_1_32, /**< G722.1 (32Kbps) */ + PJMEDIA_RTP_PT_G7221C_24, /**< G722.1 Annex C (24Kbps)*/ + PJMEDIA_RTP_PT_G7221C_32, /**< G722.1 Annex C (32Kbps)*/ + PJMEDIA_RTP_PT_G7221C_48, /**< G722.1 Annex C (48Kbps)*/ + PJMEDIA_RTP_PT_G7221_RSV1, /**< G722.1 reserve */ + PJMEDIA_RTP_PT_G7221_RSV2, /**< G722.1 reserve */ + PJMEDIA_RTP_PT_OPUS, /**< OPUS */ #if PJMEDIA_CODEC_L16_HAS_8KHZ_MONO - PJMEDIA_RTP_PT_L16_8KHZ_MONO, /**< L16 @ 8KHz, mono */ + PJMEDIA_RTP_PT_L16_8KHZ_MONO, /**< L16 @ 8KHz, mono */ #endif #if PJMEDIA_CODEC_L16_HAS_8KHZ_STEREO - PJMEDIA_RTP_PT_L16_8KHZ_STEREO, /**< L16 @ 8KHz, stereo */ + PJMEDIA_RTP_PT_L16_8KHZ_STEREO, /**< L16 @ 8KHz, stereo */ #endif - //PJMEDIA_RTP_PT_L16_11KHZ_MONO, /**< L16 @ 11KHz, mono */ - //PJMEDIA_RTP_PT_L16_11KHZ_STEREO, /**< L16 @ 11KHz, stereo */ + //PJMEDIA_RTP_PT_L16_11KHZ_MONO, /**< L16 @ 11KHz, mono */ + //PJMEDIA_RTP_PT_L16_11KHZ_STEREO, /**< L16 @ 11KHz, stereo */ #if PJMEDIA_CODEC_L16_HAS_16KHZ_MONO - PJMEDIA_RTP_PT_L16_16KHZ_MONO, /**< L16 @ 16KHz, mono */ + PJMEDIA_RTP_PT_L16_16KHZ_MONO, /**< L16 @ 16KHz, mono */ #endif #if PJMEDIA_CODEC_L16_HAS_16KHZ_STEREO - PJMEDIA_RTP_PT_L16_16KHZ_STEREO, /**< L16 @ 16KHz, stereo */ + PJMEDIA_RTP_PT_L16_16KHZ_STEREO, /**< L16 @ 16KHz, stereo */ #endif - //PJMEDIA_RTP_PT_L16_22KHZ_MONO, /**< L16 @ 22KHz, mono */ - //PJMEDIA_RTP_PT_L16_22KHZ_STEREO, /**< L16 @ 22KHz, stereo */ - //PJMEDIA_RTP_PT_L16_32KHZ_MONO, /**< L16 @ 32KHz, mono */ - //PJMEDIA_RTP_PT_L16_32KHZ_STEREO, /**< L16 @ 32KHz, stereo */ + //PJMEDIA_RTP_PT_L16_22KHZ_MONO, /**< L16 @ 22KHz, mono */ + //PJMEDIA_RTP_PT_L16_22KHZ_STEREO, /**< L16 @ 22KHz, stereo */ + //PJMEDIA_RTP_PT_L16_32KHZ_MONO, /**< L16 @ 32KHz, mono */ + //PJMEDIA_RTP_PT_L16_32KHZ_STEREO, /**< L16 @ 32KHz, stereo */ #if PJMEDIA_CODEC_L16_HAS_48KHZ_MONO - PJMEDIA_RTP_PT_L16_48KHZ_MONO, /**< L16 @ 48KHz, mono */ + PJMEDIA_RTP_PT_L16_48KHZ_MONO, /**< L16 @ 48KHz, mono */ #endif #if PJMEDIA_CODEC_L16_HAS_48KHZ_STEREO - PJMEDIA_RTP_PT_L16_48KHZ_STEREO, /**< L16 @ 48KHz, stereo */ + PJMEDIA_RTP_PT_L16_48KHZ_STEREO, /**< L16 @ 48KHz, stereo */ #endif }; @@ -143,4 +142,4 @@ enum pjmedia_video_pt */ -#endif /* __PJMEDIA_CODEC_TYPES_H__ */ +#endif /* __PJMEDIA_CODEC_TYPES_H__ */ diff --git a/pjmedia/include/pjmedia-codec/vid_toolbox.h b/pjmedia/include/pjmedia-codec/vid_toolbox.h index 8e83eaf60e..45fcc49925 100644 --- a/pjmedia/include/pjmedia-codec/vid_toolbox.h +++ b/pjmedia/include/pjmedia-codec/vid_toolbox.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2017 Teluu Inc. (http://www.teluu.com) * @@ -41,13 +40,13 @@ PJ_BEGIN_DECL /** * Initialize and register Video Toolbox codec factory. * - * @param mgr The video codec manager instance where this codec will - * be registered to. Specify NULL to use default instance - * (in that case, an instance of video codec manager must - * have been created beforehand). - * @param pf Pool factory. + * @param mgr The video codec manager instance where this codec will + * be registered to. Specify NULL to use default instance + * (in that case, an instance of video codec manager must + * have been created beforehand). + * @param pf Pool factory. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_vid_toolbox_init(pjmedia_vid_codec_mgr *mgr, pj_pool_factory *pf); @@ -56,7 +55,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_vid_toolbox_init(pjmedia_vid_codec_mgr *mgr, * Unregister Video Toolbox video codecs factory from the video codec manager * and deinitialize the codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_vid_toolbox_deinit(void); @@ -68,4 +67,4 @@ PJ_DECL(pj_status_t) pjmedia_codec_vid_toolbox_deinit(void); PJ_END_DECL -#endif /* __PJMEDIA_CODEC_VID_TOOLBOX_H__ */ +#endif /* __PJMEDIA_CODEC_VID_TOOLBOX_H__ */ diff --git a/pjmedia/include/pjmedia-codec/vpx.h b/pjmedia/include/pjmedia-codec/vpx.h index 913ea0ee2c..564a12988d 100644 --- a/pjmedia/include/pjmedia-codec/vpx.h +++ b/pjmedia/include/pjmedia-codec/vpx.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2019 Teluu Inc. (http://www.teluu.com) * @@ -39,13 +38,13 @@ PJ_BEGIN_DECL /** * Initialize and register VPX codec factory. * - * @param mgr The video codec manager instance where this codec will - * be registered to. Specify NULL to use default instance - * (in that case, an instance of video codec manager must - * have been created beforehand). - * @param pf Pool factory. + * @param mgr The video codec manager instance where this codec will + * be registered to. Specify NULL to use default instance + * (in that case, an instance of video codec manager must + * have been created beforehand). + * @param pf Pool factory. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_vpx_vid_init(pjmedia_vid_codec_mgr *mgr, pj_pool_factory *pf); @@ -54,7 +53,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_vpx_vid_init(pjmedia_vid_codec_mgr *mgr, * Unregister VPX video codecs factory from the video codec manager and * deinitialize the codec library. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_vpx_vid_deinit(void); @@ -66,4 +65,4 @@ PJ_DECL(pj_status_t) pjmedia_codec_vpx_vid_deinit(void); PJ_END_DECL -#endif /* __PJMEDIA_CODEC_VPX_H__ */ +#endif /* __PJMEDIA_CODEC_VPX_H__ */ diff --git a/pjmedia/include/pjmedia-codec/vpx_packetizer.h b/pjmedia/include/pjmedia-codec/vpx_packetizer.h index 8a3d547307..aff225a8a0 100644 --- a/pjmedia/include/pjmedia-codec/vpx_packetizer.h +++ b/pjmedia/include/pjmedia-codec/vpx_packetizer.h @@ -42,7 +42,7 @@ typedef struct pjmedia_vpx_packetizer_cfg * VPX format id. * Default: PJMEDIA_FORMAT_VP8 */ - pj_uint32_t fmt_id; + pj_uint32_t fmt_id; /** * MTU size. @@ -55,26 +55,26 @@ pjmedia_vpx_packetizer_cfg; /** * Use this function to initialize VPX packetizer config. * - * @param cfg The VPX packetizer config to be initialized. + * @param cfg The VPX packetizer config to be initialized. */ PJ_DECL(void) pjmedia_vpx_packetizer_cfg_default( - pjmedia_vpx_packetizer_cfg *cfg); + pjmedia_vpx_packetizer_cfg *cfg); /** * Create VPX packetizer. * - * @param pool The memory pool. - * @param cfg Packetizer settings, if NULL, default setting - * will be used. - * @param p_pktz Pointer to receive the packetizer. + * @param pool The memory pool. + * @param cfg Packetizer settings, if NULL, default setting + * will be used. + * @param p_pktz Pointer to receive the packetizer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vpx_packetizer_create( - pj_pool_t *pool, - const pjmedia_vpx_packetizer_cfg *cfg, - pjmedia_vpx_packetizer **p_pktz); + pj_pool_t *pool, + const pjmedia_vpx_packetizer_cfg *cfg, + pjmedia_vpx_packetizer **p_pktz); /** @@ -82,18 +82,18 @@ PJ_DECL(pj_status_t) pjmedia_vpx_packetizer_create( * function will apply in-place processing, so the bitstream may be modified * during the packetization. * - * @param pktz The packetizer. - * @param bits_len The length of the bitstream. - * @param bits_pos The bitstream offset to be packetized. - * @param is_keyframe The frame is keyframe. - * @param payload The output payload. - * @param payload_len The output payload length, on input it represents max + * @param pktz The packetizer. + * @param bits_len The length of the bitstream. + * @param bits_pos The bitstream offset to be packetized. + * @param is_keyframe The frame is keyframe. + * @param payload The output payload. + * @param payload_len The output payload length, on input it represents max * payload length. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vpx_packetize(const pjmedia_vpx_packetizer *pktz, - pj_size_t bits_len, + pj_size_t bits_len, unsigned *bits_pos, pj_bool_t is_keyframe, pj_uint8_t **payload, @@ -106,18 +106,18 @@ PJ_DECL(pj_status_t) pjmedia_vpx_packetize(const pjmedia_vpx_packetizer *pktz, * payload pointer set to NULL, as the packetizer need to update its internal * state. * - * @param pktz The packetizer. - * @param payload The payload to be unpacketized. - * @param payload_len The payload length. + * @param pktz The packetizer. + * @param payload The payload to be unpacketized. + * @param payload_len The payload length. * @param payload_desc_len The payload description length. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vpx_unpacketize(pjmedia_vpx_packetizer *pktz, - const pj_uint8_t *payload, + const pj_uint8_t *payload, pj_size_t payload_len, - unsigned *payload_desc_len); + unsigned *payload_desc_len); PJ_END_DECL -#endif /* __PJMEDIA_VPX_PACKETIZER_H__ */ +#endif /* __PJMEDIA_VPX_PACKETIZER_H__ */ diff --git a/pjmedia/include/pjmedia-videodev/avi_dev.h b/pjmedia/include/pjmedia-videodev/avi_dev.h index 7b1ec6a151..f5e5983091 100644 --- a/pjmedia/include/pjmedia-videodev/avi_dev.h +++ b/pjmedia/include/pjmedia-videodev/avi_dev.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -46,14 +45,14 @@ typedef struct pjmedia_avi_dev_param /** * Specifies the full path of the AVI file to be played. */ - pj_str_t path; + pj_str_t path; /** * If this setting is specified when setting the device, this specifies * the title to be assigned as the device name. If this setting not * specified, the filename part of the path will be used. */ - pj_str_t title; + pj_str_t title; /** * The underlying AVI streams created by the device. If the value is NULL, @@ -70,7 +69,7 @@ typedef struct pjmedia_avi_dev_param * Reset pjmedia_avi_dev_param with the default settings. This mostly will * reset all values to NULL or zero. * - * @param p The parameter to be initialized. + * @param p The parameter to be initialized. */ PJ_DECL(void) pjmedia_avi_dev_param_default(pjmedia_avi_dev_param *p); @@ -81,29 +80,29 @@ PJ_DECL(void) pjmedia_avi_dev_param_default(pjmedia_avi_dev_param *p); * device can be allocated and used, and normally only one factory is * needed per application. * - * @param pf Pool factory to be used. - * @param max_dev Number of devices to be reserved. - * @param p_ret Pointer to return the factory instance, to be - * used when allocating a virtual device. + * @param pf Pool factory to be used. + * @param max_dev Number of devices to be reserved. + * @param p_ret Pointer to return the factory instance, to be + * used when allocating a virtual device. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_avi_dev_create_factory( - pj_pool_factory *pf, - unsigned max_dev, - pjmedia_vid_dev_factory **p_ret); + pj_pool_factory *pf, + unsigned max_dev, + pjmedia_vid_dev_factory **p_ret); /** * Allocate one device ID to be used to play the specified AVI file in * the parameter. * - * @param f The factory. - * @param param The parameter, with at least the AVI file path - * set. - * @param p_id Optional pointer to receive device ID to play - * the file. + * @param f The factory. + * @param param The parameter, with at least the AVI file path + * set. + * @param p_id Optional pointer to receive device ID to play + * the file. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. * */ PJ_DECL(pj_status_t) pjmedia_avi_dev_alloc(pjmedia_vid_dev_factory *f, @@ -113,10 +112,10 @@ PJ_DECL(pj_status_t) pjmedia_avi_dev_alloc(pjmedia_vid_dev_factory *f, /** * Retrieve the parameters set for the virtual device. * - * @param id Device ID. - * @param param Structure to receive the settings. + * @param id Device ID. + * @param param Structure to receive the settings. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_avi_dev_get_param(pjmedia_vid_dev_index id, pjmedia_avi_dev_param *param); @@ -124,9 +123,9 @@ PJ_DECL(pj_status_t) pjmedia_avi_dev_get_param(pjmedia_vid_dev_index id, /** * Free the resources associated with the virtual device. * - * @param id The device ID. + * @param id The device ID. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_avi_dev_free(pjmedia_vid_dev_index id); diff --git a/pjmedia/include/pjmedia-videodev/config.h b/pjmedia/include/pjmedia-videodev/config.h index 670a265ed7..280c0a9863 100644 --- a/pjmedia/include/pjmedia-videodev/config.h +++ b/pjmedia/include/pjmedia-videodev/config.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -83,12 +82,12 @@ PJ_BEGIN_DECL * Default: 0 (or detected by configure) */ #ifndef PJMEDIA_VIDEO_DEV_HAS_IOS_OPENGL -# define PJMEDIA_VIDEO_DEV_HAS_IOS_OPENGL 0 +# define PJMEDIA_VIDEO_DEV_HAS_IOS_OPENGL 0 #else # if defined(PJMEDIA_VIDEO_DEV_HAS_IOS_OPENGL) && \ - PJMEDIA_VIDEO_DEV_HAS_IOS_OPENGL != 0 + PJMEDIA_VIDEO_DEV_HAS_IOS_OPENGL != 0 # undef PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES -# define PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES 1 +# define PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES 1 # endif #endif @@ -99,12 +98,12 @@ PJ_BEGIN_DECL * Default: 0 (or detected by configure) */ #ifndef PJMEDIA_VIDEO_DEV_HAS_ANDROID_OPENGL -# define PJMEDIA_VIDEO_DEV_HAS_ANDROID_OPENGL 0 +# define PJMEDIA_VIDEO_DEV_HAS_ANDROID_OPENGL 0 #else # if defined(PJMEDIA_VIDEO_DEV_HAS_ANDROID_OPENGL) && \ - PJMEDIA_VIDEO_DEV_HAS_ANDROID_OPENGL != 0 + PJMEDIA_VIDEO_DEV_HAS_ANDROID_OPENGL != 0 # undef PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES -# define PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES 1 +# define PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES 1 # endif #endif @@ -115,12 +114,12 @@ PJ_BEGIN_DECL * Default: 0 (or detected by configure) */ #ifndef PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES -# define PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES 0 +# define PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES 0 #else # if defined(PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES) && \ - PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES != 0 + PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES != 0 # undef PJMEDIA_VIDEO_DEV_HAS_OPENGL -# define PJMEDIA_VIDEO_DEV_HAS_OPENGL 1 +# define PJMEDIA_VIDEO_DEV_HAS_OPENGL 1 # endif #endif @@ -133,12 +132,12 @@ PJ_BEGIN_DECL * Default: 0 (or detected by configure) */ #ifndef PJMEDIA_VIDEO_DEV_HAS_OPENGL -# define PJMEDIA_VIDEO_DEV_HAS_OPENGL 0 +# define PJMEDIA_VIDEO_DEV_HAS_OPENGL 0 #else # if defined(PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES) && \ - PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES == 0 + PJMEDIA_VIDEO_DEV_HAS_OPENGL_ES == 0 # undef PJMEDIA_VIDEO_DEV_HAS_OPENGL -# define PJMEDIA_VIDEO_DEV_HAS_OPENGL 0 +# define PJMEDIA_VIDEO_DEV_HAS_OPENGL 0 # endif #endif @@ -149,7 +148,7 @@ PJ_BEGIN_DECL * Default: 0 (or detected by configure) */ #ifndef PJMEDIA_VIDEO_DEV_HAS_SDL -# define PJMEDIA_VIDEO_DEV_HAS_SDL 0 +# define PJMEDIA_VIDEO_DEV_HAS_SDL 0 #endif @@ -159,7 +158,7 @@ PJ_BEGIN_DECL * Default: 0 */ #ifndef PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL -# define PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL 0 +# define PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL 0 #endif @@ -169,7 +168,7 @@ PJ_BEGIN_DECL * Default: 0 (or detected by configure) */ #ifndef PJMEDIA_VIDEO_DEV_HAS_QT -# define PJMEDIA_VIDEO_DEV_HAS_QT 0 +# define PJMEDIA_VIDEO_DEV_HAS_QT 0 #endif @@ -179,7 +178,7 @@ PJ_BEGIN_DECL * Default: 0 (or detected by configure) */ #ifndef PJMEDIA_VIDEO_DEV_HAS_IOS -# define PJMEDIA_VIDEO_DEV_HAS_IOS 0 +# define PJMEDIA_VIDEO_DEV_HAS_IOS 0 #endif @@ -189,7 +188,7 @@ PJ_BEGIN_DECL * Default: 0 (unfinished) */ #ifndef PJMEDIA_VIDEO_DEV_HAS_DSHOW -# define PJMEDIA_VIDEO_DEV_HAS_DSHOW 0 //PJ_WIN32 +# define PJMEDIA_VIDEO_DEV_HAS_DSHOW 0 //PJ_WIN32 #endif @@ -199,7 +198,7 @@ PJ_BEGIN_DECL * Default: 1 */ #ifndef PJMEDIA_VIDEO_DEV_HAS_CBAR_SRC -# define PJMEDIA_VIDEO_DEV_HAS_CBAR_SRC 1 +# define PJMEDIA_VIDEO_DEV_HAS_CBAR_SRC 1 #endif @@ -209,7 +208,7 @@ PJ_BEGIN_DECL * Default: 0 (unfinished) */ #ifndef PJMEDIA_VIDEO_DEV_HAS_FFMPEG -# define PJMEDIA_VIDEO_DEV_HAS_FFMPEG 0 +# define PJMEDIA_VIDEO_DEV_HAS_FFMPEG 0 #endif @@ -219,7 +218,7 @@ PJ_BEGIN_DECL * Default: 0 (or detected by configure) */ #ifndef PJMEDIA_VIDEO_DEV_HAS_V4L2 -# define PJMEDIA_VIDEO_DEV_HAS_V4L2 0 +# define PJMEDIA_VIDEO_DEV_HAS_V4L2 0 #endif @@ -229,7 +228,7 @@ PJ_BEGIN_DECL * Default: 1 */ #ifndef PJMEDIA_VIDEO_DEV_HAS_AVI -# define PJMEDIA_VIDEO_DEV_HAS_AVI 1 +# define PJMEDIA_VIDEO_DEV_HAS_AVI 1 #endif @@ -239,7 +238,7 @@ PJ_BEGIN_DECL * Default: 0 (or detected by configure) */ #ifndef PJMEDIA_VIDEO_DEV_HAS_ANDROID -# define PJMEDIA_VIDEO_DEV_HAS_ANDROID 0 +# define PJMEDIA_VIDEO_DEV_HAS_ANDROID 0 #endif @@ -264,7 +263,7 @@ PJ_BEGIN_DECL PJ_END_DECL -#endif /* __PJMEDIA_VIDEODEV_CONFIG_H__ */ +#endif /* __PJMEDIA_VIDEODEV_CONFIG_H__ */ /* --------------------- DOCUMENTATION FOLLOWS --------------------------- diff --git a/pjmedia/include/pjmedia-videodev/errno.h b/pjmedia/include/pjmedia-videodev/errno.h index 82fd5cda6a..13cb123626 100644 --- a/pjmedia/include/pjmedia-videodev/errno.h +++ b/pjmedia/include/pjmedia-videodev/errno.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -43,9 +42,9 @@ PJ_BEGIN_DECL * This value is 520000. */ #define PJMEDIA_VIDEODEV_ERRNO_START \ - (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*7) + (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*7) #define PJMEDIA_VIDEODEV_ERRNO_END \ - (PJMEDIA_VIDEODEV_ERRNO_START + PJ_ERRNO_SPACE_SIZE - 1) + (PJMEDIA_VIDEODEV_ERRNO_START + PJ_ERRNO_SPACE_SIZE - 1) /************************************************************ @@ -55,79 +54,79 @@ PJ_BEGIN_DECL * @hideinitializer * General/unknown error. */ -#define PJMEDIA_EVID_ERR (PJMEDIA_VIDEODEV_ERRNO_START+1) /* 520001 */ +#define PJMEDIA_EVID_ERR (PJMEDIA_VIDEODEV_ERRNO_START+1) /* 520001 */ /** * @hideinitializer * Unknown error from video driver */ -#define PJMEDIA_EVID_SYSERR (PJMEDIA_VIDEODEV_ERRNO_START+2) /* 520002 */ +#define PJMEDIA_EVID_SYSERR (PJMEDIA_VIDEODEV_ERRNO_START+2) /* 520002 */ /** * @hideinitializer * Video subsystem not initialized */ -#define PJMEDIA_EVID_INIT (PJMEDIA_VIDEODEV_ERRNO_START+3) /* 520003 */ +#define PJMEDIA_EVID_INIT (PJMEDIA_VIDEODEV_ERRNO_START+3) /* 520003 */ /** * @hideinitializer * Invalid video device */ -#define PJMEDIA_EVID_INVDEV (PJMEDIA_VIDEODEV_ERRNO_START+4) /* 520004 */ +#define PJMEDIA_EVID_INVDEV (PJMEDIA_VIDEODEV_ERRNO_START+4) /* 520004 */ /** * @hideinitializer * Found no devices */ -#define PJMEDIA_EVID_NODEV (PJMEDIA_VIDEODEV_ERRNO_START+5) /* 520005 */ +#define PJMEDIA_EVID_NODEV (PJMEDIA_VIDEODEV_ERRNO_START+5) /* 520005 */ /** * @hideinitializer * Unable to find default device */ -#define PJMEDIA_EVID_NODEFDEV (PJMEDIA_VIDEODEV_ERRNO_START+6) /* 520006 */ +#define PJMEDIA_EVID_NODEFDEV (PJMEDIA_VIDEODEV_ERRNO_START+6) /* 520006 */ /** * @hideinitializer * Device not ready */ -#define PJMEDIA_EVID_NOTREADY (PJMEDIA_VIDEODEV_ERRNO_START+7) /* 520007 */ +#define PJMEDIA_EVID_NOTREADY (PJMEDIA_VIDEODEV_ERRNO_START+7) /* 520007 */ /** * @hideinitializer * The video capability is invalid or not supported */ -#define PJMEDIA_EVID_INVCAP (PJMEDIA_VIDEODEV_ERRNO_START+8) /* 520008 */ +#define PJMEDIA_EVID_INVCAP (PJMEDIA_VIDEODEV_ERRNO_START+8) /* 520008 */ /** * @hideinitializer * The operation is invalid or not supported */ -#define PJMEDIA_EVID_INVOP (PJMEDIA_VIDEODEV_ERRNO_START+9) /* 520009 */ +#define PJMEDIA_EVID_INVOP (PJMEDIA_VIDEODEV_ERRNO_START+9) /* 520009 */ /** * @hideinitializer * Bad or invalid video device format */ -#define PJMEDIA_EVID_BADFORMAT (PJMEDIA_VIDEODEV_ERRNO_START+10) /* 520010 */ +#define PJMEDIA_EVID_BADFORMAT (PJMEDIA_VIDEODEV_ERRNO_START+10) /* 520010 */ /** * @hideinitializer * Invalid video device sample format */ -#define PJMEDIA_EVID_SAMPFORMAT (PJMEDIA_VIDEODEV_ERRNO_START+11) /* 520011 */ +#define PJMEDIA_EVID_SAMPFORMAT (PJMEDIA_VIDEODEV_ERRNO_START+11) /* 520011 */ /** * @hideinitializer * Bad latency setting */ -#define PJMEDIA_EVID_BADLATENCY (PJMEDIA_VIDEODEV_ERRNO_START+12) /* 520012 */ +#define PJMEDIA_EVID_BADLATENCY (PJMEDIA_VIDEODEV_ERRNO_START+12) /* 520012 */ /** * @hideinitializer * Bad/unsupported video size */ -#define PJMEDIA_EVID_BADSIZE (PJMEDIA_VIDEODEV_ERRNO_START+13) /* 520013 */ +#define PJMEDIA_EVID_BADSIZE (PJMEDIA_VIDEODEV_ERRNO_START+13) /* 520013 */ /** @@ -141,11 +140,11 @@ PJ_BEGIN_DECL * @param buffer The buffer where to put the error message. * @param bufsize Size of the buffer. * - * @return The error message as NULL terminated string, + * @return The error message as NULL terminated string, * wrapped with pj_str_t. */ PJ_DECL(pj_str_t) pjmedia_videodev_strerror(pj_status_t status, char *buffer, - pj_size_t bufsize); + pj_size_t bufsize); PJ_END_DECL @@ -155,5 +154,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_VIDEODEV_VIDEODEV_ERRNO_H__ */ +#endif /* __PJMEDIA_VIDEODEV_VIDEODEV_ERRNO_H__ */ diff --git a/pjmedia/include/pjmedia-videodev/opengl_dev.h b/pjmedia/include/pjmedia-videodev/opengl_dev.h index de2ca10d62..98814e00f8 100644 --- a/pjmedia/include/pjmedia-videodev/opengl_dev.h +++ b/pjmedia/include/pjmedia-videodev/opengl_dev.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013-2014 Teluu Inc. (http://www.teluu.com) * diff --git a/pjmedia/include/pjmedia-videodev/videodev.h b/pjmedia/include/pjmedia-videodev/videodev.h index a765422f06..df6bb75db8 100644 --- a/pjmedia/include/pjmedia-videodev/videodev.h +++ b/pjmedia/include/pjmedia-videodev/videodev.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -79,9 +78,9 @@ PJ_DECL(pj_status_t) pjmedia_vid_dev_subsys_shutdown(void); * #pjmedia_vid_dev_subsys_init(). * * @param vdf The factory creation function. Either vdf or factory - * argument must be specified. + * argument must be specified. * @param factory Factory instance. Either vdf or factory - * argument must be specified. + * argument must be specified. * * @return PJ_SUCCESS on successful operation or the appropriate * error code. @@ -98,9 +97,9 @@ pjmedia_vid_register_factory(pjmedia_vid_dev_factory_create_func_ptr vdf, * is currently in use, then the behavior is undefined. * * @param vdf The video device factory. Either vdf or factory argument - * must be specified. + * must be specified. * @param factory The factory instance. Either vdf or factory argument - * must be specified. + * must be specified. * * @return PJ_SUCCESS on successful operation or the appropriate * error code. diff --git a/pjmedia/include/pjmedia-videodev/videodev_imp.h b/pjmedia/include/pjmedia-videodev/videodev_imp.h index e0ef520577..fb93cab7f6 100644 --- a/pjmedia/include/pjmedia-videodev/videodev_imp.h +++ b/pjmedia/include/pjmedia-videodev/videodev_imp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -36,7 +35,7 @@ typedef struct pjmedia_vid_dev_factory_op /** * Initialize the video device factory. * - * @param f The video device factory. + * @param f The video device factory. */ pj_status_t (*init)(pjmedia_vid_dev_factory *f); @@ -44,57 +43,57 @@ typedef struct pjmedia_vid_dev_factory_op * Close this video device factory and release all resources back to the * operating system. * - * @param f The video device factory. + * @param f The video device factory. */ pj_status_t (*destroy)(pjmedia_vid_dev_factory *f); /** * Get the number of video devices installed in the system. * - * @param f The video device factory. + * @param f The video device factory. */ unsigned (*get_dev_count)(pjmedia_vid_dev_factory *f); /** * Get the video device information and capabilities. * - * @param f The video device factory. - * @param index Device index. - * @param info The video device information structure which will be - * initialized by this function once it returns - * successfully. + * @param f The video device factory. + * @param index Device index. + * @param info The video device information structure which will be + * initialized by this function once it returns + * successfully. */ - pj_status_t (*get_dev_info)(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info); + pj_status_t (*get_dev_info)(pjmedia_vid_dev_factory *f, + unsigned index, + pjmedia_vid_dev_info *info); /** * Initialize the specified video device parameter with the default * values for the specified device. * - * @param f The video device factory. - * @param index Device index. - * @param param The video device parameter. + * @param f The video device factory. + * @param index Device index. + * @param param The video device parameter. */ pj_status_t (*default_param)(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param); + unsigned index, + pjmedia_vid_dev_param *param); /** * Open the video device and create video stream. See * #pjmedia_vid_dev_stream_create() */ pj_status_t (*create_stream)(pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm); + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm); /** * Refresh the list of video devices installed in the system. * - * @param f The video device factory. + * @param f The video device factory. */ pj_status_t (*refresh)(pjmedia_vid_dev_factory *f); @@ -108,8 +107,8 @@ struct pjmedia_vid_dev_factory { /** Internal data to be initialized by video subsystem. */ struct { - /** Driver index */ - unsigned drv_idx; + /** Driver index */ + unsigned drv_idx; } sys; /** Operations */ @@ -126,21 +125,21 @@ typedef struct pjmedia_vid_dev_stream_op * See #pjmedia_vid_dev_stream_get_param() */ pj_status_t (*get_param)(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_param *param); + pjmedia_vid_dev_param *param); /** * See #pjmedia_vid_dev_stream_get_cap() */ pj_status_t (*get_cap)(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - void *value); + pjmedia_vid_dev_cap cap, + void *value); /** * See #pjmedia_vid_dev_stream_set_cap() */ pj_status_t (*set_cap)(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - const void *value); + pjmedia_vid_dev_cap cap, + const void *value); /** * See #pjmedia_vid_dev_stream_start() @@ -179,11 +178,11 @@ struct pjmedia_vid_dev_stream { /** Internal data to be initialized by video subsystem */ struct { - /** Driver index */ - unsigned drv_idx; + /** Driver index */ + unsigned drv_idx; - /** Has it been started? */ - pj_bool_t is_running; + /** Has it been started? */ + pj_bool_t is_running; } sys; /** Operations */ @@ -195,11 +194,11 @@ struct pjmedia_vid_dev_stream * Internal API: return the factory instance and device index that's local * to the factory for a given device ID. * - * @param id Device id. - * @param p_f Out: factory instance + * @param id Device id. + * @param p_f Out: factory instance * @param p_local_index Out: device index within the factory * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_dev_get_local_index(pjmedia_vid_dev_index id, @@ -210,11 +209,11 @@ pjmedia_vid_dev_get_local_index(pjmedia_vid_dev_index id, * Internal API: return the global device index given a factory instance and * a local device index. * - * @param f Factory. - * @param local_idx Local index. - * @param pid Returned global index. + * @param f Factory. + * @param local_idx Local index. + * @param pid Returned global index. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DEF(pj_status_t) pjmedia_vid_dev_get_global_index(const pjmedia_vid_dev_factory *f, diff --git a/pjmedia/include/pjmedia.h b/pjmedia/include/pjmedia.h index 0adb954d5e..d37c28e736 100644 --- a/pjmedia/include/pjmedia.h +++ b/pjmedia/include/pjmedia.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -78,5 +77,5 @@ #include #include -#endif /* __PJMEDIA_H__ */ +#endif /* __PJMEDIA_H__ */ diff --git a/pjmedia/include/pjmedia/alaw_ulaw.h b/pjmedia/include/pjmedia/alaw_ulaw.h index 887a1b5d2b..0ecf09360e 100644 --- a/pjmedia/include/pjmedia/alaw_ulaw.h +++ b/pjmedia/include/pjmedia/alaw_ulaw.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,55 +35,55 @@ extern const pj_int16_t pjmedia_alaw2linear_tab[256]; * Convert 16-bit linear PCM value to 8-bit A-Law. * * @param pcm_val 16-bit linear PCM value. - * @return 8-bit A-Law value. + * @return 8-bit A-Law value. */ -#define pjmedia_linear2alaw(pcm_val) \ - pjmedia_linear2alaw_tab[(((pj_int16_t)pcm_val) >> 2) & 0x3fff] +#define pjmedia_linear2alaw(pcm_val) \ + pjmedia_linear2alaw_tab[(((pj_int16_t)pcm_val) >> 2) & 0x3fff] /** * Convert 8-bit A-Law value to 16-bit linear PCM value. * * @param chara_val 8-bit A-Law value. - * @return 16-bit linear PCM value. + * @return 16-bit linear PCM value. */ -#define pjmedia_alaw2linear(chara_val) \ - pjmedia_alaw2linear_tab[chara_val] +#define pjmedia_alaw2linear(chara_val) \ + pjmedia_alaw2linear_tab[chara_val] /** * Convert 16-bit linear PCM value to 8-bit U-Law. * * @param pcm_val 16-bit linear PCM value. - * @return U-bit A-Law value. + * @return U-bit A-Law value. */ -#define pjmedia_linear2ulaw(pcm_val) \ - pjmedia_linear2ulaw_tab[(((pj_int16_t)pcm_val) >> 2) & 0x3fff] +#define pjmedia_linear2ulaw(pcm_val) \ + pjmedia_linear2ulaw_tab[(((pj_int16_t)pcm_val) >> 2) & 0x3fff] /** * Convert 8-bit U-Law value to 16-bit linear PCM value. * - * @param u_val 8-bit U-Law value. - * @return 16-bit linear PCM value. + * @param u_val 8-bit U-Law value. + * @return 16-bit linear PCM value. */ -#define pjmedia_ulaw2linear(u_val) \ - pjmedia_ulaw2linear_tab[u_val] +#define pjmedia_ulaw2linear(u_val) \ + pjmedia_ulaw2linear_tab[u_val] /** * Convert 8-bit A-Law value to 8-bit U-Law value. * - * @param aval 8-bit A-Law value. - * @return 8-bit U-Law value. + * @param aval 8-bit A-Law value. + * @return 8-bit U-Law value. */ -#define pjmedia_alaw2ulaw(aval) \ - pjmedia_linear2ulaw(pjmedia_alaw2linear(aval)) +#define pjmedia_alaw2ulaw(aval) \ + pjmedia_linear2ulaw(pjmedia_alaw2linear(aval)) /** * Convert 8-bit U-Law value to 8-bit A-Law value. * - * @param uval 8-bit U-Law value. - * @return 8-bit A-Law value. + * @param uval 8-bit U-Law value. + * @return 8-bit A-Law value. */ -#define pjmedia_ulaw2alaw(uval) \ - pjmedia_linear2alaw(pjmedia_ulaw2linear(uval)) +#define pjmedia_ulaw2alaw(uval) \ + pjmedia_linear2alaw(pjmedia_ulaw2linear(uval)) #else @@ -93,7 +92,7 @@ extern const pj_int16_t pjmedia_alaw2linear_tab[256]; * Convert 16-bit linear PCM value to 8-bit A-Law. * * @param pcm_val 16-bit linear PCM value. - * @return 8-bit A-Law value. + * @return 8-bit A-Law value. */ PJ_DECL(pj_uint8_t) pjmedia_linear2alaw(int pcm_val); @@ -101,7 +100,7 @@ PJ_DECL(pj_uint8_t) pjmedia_linear2alaw(int pcm_val); * Convert 8-bit A-Law value to 16-bit linear PCM value. * * @param chara_val 8-bit A-Law value. - * @return 16-bit linear PCM value. + * @return 16-bit linear PCM value. */ PJ_DECL(int) pjmedia_alaw2linear(unsigned chara_val); @@ -109,31 +108,31 @@ PJ_DECL(int) pjmedia_alaw2linear(unsigned chara_val); * Convert 16-bit linear PCM value to 8-bit U-Law. * * @param pcm_val 16-bit linear PCM value. - * @return U-bit A-Law value. + * @return U-bit A-Law value. */ PJ_DECL(unsigned char) pjmedia_linear2ulaw(int pcm_val); /** * Convert 8-bit U-Law value to 16-bit linear PCM value. * - * @param u_val 8-bit U-Law value. - * @return 16-bit linear PCM value. + * @param u_val 8-bit U-Law value. + * @return 16-bit linear PCM value. */ PJ_DECL(int) pjmedia_ulaw2linear(unsigned char u_val); /** * Convert 8-bit A-Law value to 8-bit U-Law value. * - * @param aval 8-bit A-Law value. - * @return 8-bit U-Law value. + * @param aval 8-bit A-Law value. + * @return 8-bit U-Law value. */ PJ_DECL(unsigned char) pjmedia_alaw2ulaw(unsigned char aval); /** * Convert 8-bit U-Law value to 8-bit A-Law value. * - * @param uval 8-bit U-Law value. - * @return 8-bit A-Law value. + * @param uval 8-bit U-Law value. + * @return 8-bit A-Law value. */ PJ_DECL(unsigned char) pjmedia_ulaw2alaw(unsigned char uval); @@ -142,72 +141,72 @@ PJ_DECL(unsigned char) pjmedia_ulaw2alaw(unsigned char uval); /** * Encode 16-bit linear PCM data to 8-bit U-Law data. * - * @param dst Destination buffer for 8-bit U-Law data. - * @param src Source, 16-bit linear PCM data. - * @param count Number of samples. + * @param dst Destination buffer for 8-bit U-Law data. + * @param src Source, 16-bit linear PCM data. + * @param count Number of samples. */ PJ_INLINE(void) pjmedia_ulaw_encode(pj_uint8_t *dst, const pj_int16_t *src, - pj_size_t count) + pj_size_t count) { const pj_int16_t *end = src + count; while (src < end) { - *dst++ = pjmedia_linear2ulaw(*src++); + *dst++ = pjmedia_linear2ulaw(*src++); } } /** * Encode 16-bit linear PCM data to 8-bit A-Law data. * - * @param dst Destination buffer for 8-bit A-Law data. - * @param src Source, 16-bit linear PCM data. - * @param count Number of samples. + * @param dst Destination buffer for 8-bit A-Law data. + * @param src Source, 16-bit linear PCM data. + * @param count Number of samples. */ PJ_INLINE(void) pjmedia_alaw_encode(pj_uint8_t *dst, const pj_int16_t *src, - pj_size_t count) + pj_size_t count) { const pj_int16_t *end = src + count; while (src < end) { - *dst++ = pjmedia_linear2alaw(*src++); + *dst++ = pjmedia_linear2alaw(*src++); } } /** * Decode 8-bit U-Law data to 16-bit linear PCM data. * - * @param dst Destination buffer for 16-bit PCM data. - * @param src Source, 8-bit U-Law data. - * @param len Encoded frame/source length in bytes. + * @param dst Destination buffer for 16-bit PCM data. + * @param src Source, 8-bit U-Law data. + * @param len Encoded frame/source length in bytes. */ PJ_INLINE(void) pjmedia_ulaw_decode(pj_int16_t *dst, const pj_uint8_t *src, - pj_size_t len) + pj_size_t len) { const pj_uint8_t *end = src + len; while (src < end) { - *dst++ = pjmedia_ulaw2linear(*src++); + *dst++ = pjmedia_ulaw2linear(*src++); } } /** * Decode 8-bit A-Law data to 16-bit linear PCM data. * - * @param dst Destination buffer for 16-bit PCM data. - * @param src Source, 8-bit A-Law data. - * @param len Encoded frame/source length in bytes. + * @param dst Destination buffer for 16-bit PCM data. + * @param src Source, 8-bit A-Law data. + * @param len Encoded frame/source length in bytes. */ PJ_INLINE(void) pjmedia_alaw_decode(pj_int16_t *dst, const pj_uint8_t *src, - pj_size_t len) + pj_size_t len) { const pj_uint8_t *end = src + len; while (src < end) { - *dst++ = pjmedia_alaw2linear(*src++); + *dst++ = pjmedia_alaw2linear(*src++); } } PJ_END_DECL -#endif /* __PJMEDIA_ALAW_ULAW_H__ */ +#endif /* __PJMEDIA_ALAW_ULAW_H__ */ diff --git a/pjmedia/include/pjmedia/audiodev.h b/pjmedia/include/pjmedia/audiodev.h index 4f276026a1..e31041a72f 100644 --- a/pjmedia/include/pjmedia/audiodev.h +++ b/pjmedia/include/pjmedia/audiodev.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -77,10 +76,10 @@ typedef pj_int32_t pjmedia_aud_dev_index; /** * Constant to denote invalid device index. */ -#define PJMEDIA_AUD_INVALID_DEV -3 +#define PJMEDIA_AUD_INVALID_DEV -3 -#define PJMEDIA_AUD_MAX_DRIVERS 16 -#define PJMEDIA_AUD_MAX_DEVS 64 +#define PJMEDIA_AUD_MAX_DRIVERS 16 +#define PJMEDIA_AUD_MAX_DEVS 64 /** Forward declaration for pjmedia_aud_stream */ @@ -98,27 +97,27 @@ typedef pjmedia_aud_dev_factory* typedef struct pjmedia_aud_driver { pjmedia_aud_dev_factory_create_func_ptr create; /* Creation function */ - pjmedia_aud_dev_factory *f; /* Factory instance */ - char name[32]; /* Driver name */ - unsigned dev_cnt; /* Number of devices */ - unsigned start_idx; /* Start index in global list */ - int rec_dev_idx; /* Default capture device. */ - int play_dev_idx;/* Default playback device */ - int dev_idx; /* Default device. */ + pjmedia_aud_dev_factory *f; /* Factory instance */ + char name[32]; /* Driver name */ + unsigned dev_cnt; /* Number of devices */ + unsigned start_idx; /* Start index in global list */ + int rec_dev_idx; /* Default capture device. */ + int play_dev_idx;/* Default playback device */ + int dev_idx; /* Default device. */ } pjmedia_aud_driver; /* Audio subsystem structure */ typedef struct pjmedia_aud_subsys { - unsigned init_count; /* How many times init() is called */ - pj_pool_factory *pf; /* The pool factory. */ + unsigned init_count; /* How many times init() is called */ + pj_pool_factory *pf; /* The pool factory. */ - unsigned drv_cnt; /* Number of drivers. */ + unsigned drv_cnt; /* Number of drivers. */ pjmedia_aud_driver drv[PJMEDIA_AUD_MAX_DRIVERS];/* Array of drivers. */ - unsigned dev_cnt; /* Total number of devices. */ - pj_uint32_t dev_list[PJMEDIA_AUD_MAX_DEVS];/* Array of dev IDs. */ + unsigned dev_cnt; /* Total number of devices. */ + pj_uint32_t dev_list[PJMEDIA_AUD_MAX_DEVS];/* Array of dev IDs. */ } pjmedia_aud_subsys; @@ -280,7 +279,7 @@ typedef enum pjmedia_aud_dev_route * // 6 is VOICE_RECOGNITION * unsigned aud_source = PJMEDIA_AUD_DEV_ROUTE_CUSTOM | 6; * pjmedia_aud_param_set_cap(¶m, PJMEDIA_AUD_DEV_CAP_INPUT_SOURCE, - * &aud_source); + * &aud_source); */ PJMEDIA_AUD_DEV_ROUTE_CUSTOM = 128 @@ -354,33 +353,33 @@ typedef struct pjmedia_aud_dev_info * buffer with audio samples. * * The frame argument contains the following values: - * - timestamp Playback timestamp, in samples. - * - buf Buffer to be filled out by application. - * - size The size requested in bytes, which will be equal to - * the size of one whole packet. + * - timestamp Playback timestamp, in samples. + * - buf Buffer to be filled out by application. + * - size The size requested in bytes, which will be equal to + * the size of one whole packet. * * @param user_data User data associated with the stream. - * @param frame Audio frame, which buffer is to be filled in by - * the application. + * @param frame Audio frame, which buffer is to be filled in by + * the application. * - * @return Returning non-PJ_SUCCESS will cause the audio stream - * to stop + * @return Returning non-PJ_SUCCESS will cause the audio stream + * to stop */ typedef pj_status_t (*pjmedia_aud_play_cb)(void *user_data, - pjmedia_frame *frame); + pjmedia_frame *frame); /** * This callback is called by recorder stream when it has captured the whole * packet worth of audio samples. * * @param user_data User data associated with the stream. - * @param frame Captured frame. + * @param frame Captured frame. * - * @return Returning non-PJ_SUCCESS will cause the audio stream - * to stop + * @return Returning non-PJ_SUCCESS will cause the audio stream + * to stop */ typedef pj_status_t (*pjmedia_aud_rec_cb)(void *user_data, - pjmedia_frame *frame); + pjmedia_frame *frame); /** * This structure specifies the parameters to open the audio stream. @@ -513,26 +512,26 @@ typedef struct pjmedia_aud_param /** * Get the audio subsystem. * - * @return The audio subsystem. + * @return The audio subsystem. */ PJ_DECL(pjmedia_aud_subsys*) pjmedia_get_aud_subsys(void); /** * Initialize the audio driver. * - * @param drv_idx The index of the audio driver. - * @param refresh Specify non-zero to refresh the audio driver. + * @param drv_idx The index of the audio driver. + * @param refresh Specify non-zero to refresh the audio driver. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_driver_init(unsigned drv_idx, - pj_bool_t refresh); + pj_bool_t refresh); /** * Deinitialize the audio driver. * - * @param drv_idx The index of the audio driver. + * @param drv_idx The index of the audio driver. */ PJ_DECL(void) pjmedia_aud_driver_deinit(unsigned drv_idx); @@ -540,31 +539,31 @@ PJ_DECL(void) pjmedia_aud_driver_deinit(unsigned drv_idx); /** * Get string info for the specified capability. * - * @param cap The capability ID. - * @param p_desc Optional pointer which will be filled with longer - * description about the capability. + * @param cap The capability ID. + * @param p_desc Optional pointer which will be filled with longer + * description about the capability. * - * @return Capability name. + * @return Capability name. */ PJ_DECL(const char*) pjmedia_aud_dev_cap_name(pjmedia_aud_dev_cap cap, - const char **p_desc); + const char **p_desc); /** * Set a capability field value in #pjmedia_aud_param structure. This will * also set the flags field for the specified capability in the structure. * - * @param param The structure. - * @param cap The audio capability which value is to be set. - * @param pval Pointer to value. Please see the type of value to - * be supplied in the pjmedia_aud_dev_cap documentation. + * @param param The structure. + * @param cap The audio capability which value is to be set. + * @param pval Pointer to value. Please see the type of value to + * be supplied in the pjmedia_aud_dev_cap documentation. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_param_set_cap(pjmedia_aud_param *param, - pjmedia_aud_dev_cap cap, - const void *pval); + pjmedia_aud_dev_cap cap, + const void *pval); /** @@ -572,17 +571,17 @@ PJ_DECL(pj_status_t) pjmedia_aud_param_set_cap(pjmedia_aud_param *param, * function will return PJMEDIA_EAUD_INVCAP error if the flag for that * capability is not set in the flags field in the structure. * - * @param param The structure. - * @param cap The audio capability which value is to be retrieved. - * @param pval Pointer to value. Please see the type of value to - * be supplied in the pjmedia_aud_dev_cap documentation. + * @param param The structure. + * @param cap The audio capability which value is to be retrieved. + * @param pval Pointer to value. Please see the type of value to + * be supplied in the pjmedia_aud_dev_cap documentation. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_param_get_cap(const pjmedia_aud_param *param, - pjmedia_aud_dev_cap cap, - void *pval); + pjmedia_aud_dev_cap cap, + void *pval); /** @@ -593,8 +592,8 @@ PJ_DECL(pj_status_t) pjmedia_aud_param_get_cap(const pjmedia_aud_param *param, * pjmedia_aud_dev_index) before calling any function that accepts audio device * index as its parameter. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_dev_refresh(void); @@ -602,7 +601,7 @@ PJ_DECL(pj_status_t) pjmedia_aud_dev_refresh(void); /** * Get the number of sound devices installed in the system. * - * @return The number of sound devices installed in the system. + * @return The number of sound devices installed in the system. */ PJ_DECL(unsigned) pjmedia_aud_dev_count(void); @@ -610,138 +609,138 @@ PJ_DECL(unsigned) pjmedia_aud_dev_count(void); /** * Get device information. * - * @param id The audio device ID. - * @param info The device information which will be filled in by this - * function once it returns successfully. + * @param id The audio device ID. + * @param info The device information which will be filled in by this + * function once it returns successfully. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_dev_get_info(pjmedia_aud_dev_index id, - pjmedia_aud_dev_info *info); + pjmedia_aud_dev_info *info); /** * Lookup device index based on the driver and device name. * - * @param drv_name The driver name. - * @param dev_name The device name. - * @param id Pointer to store the returned device ID. + * @param drv_name The driver name. + * @param dev_name The device name. + * @param id Pointer to store the returned device ID. * - * @return PJ_SUCCESS if the device can be found. + * @return PJ_SUCCESS if the device can be found. */ PJ_DECL(pj_status_t) pjmedia_aud_dev_lookup(const char *drv_name, - const char *dev_name, - pjmedia_aud_dev_index *id); + const char *dev_name, + pjmedia_aud_dev_index *id); /** * Initialize the audio device parameters with default values for the * specified device. * - * @param id The audio device ID. - * @param param The audio device parameters which will be initialized - * by this function once it returns successfully. + * @param id The audio device ID. + * @param param The audio device parameters which will be initialized + * by this function once it returns successfully. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_dev_default_param(pjmedia_aud_dev_index id, - pjmedia_aud_param *param); + pjmedia_aud_param *param); /** * Open audio stream object using the specified parameters. * - * @param param Sound device parameters to be used for the stream. - * @param rec_cb Callback to be called on every input frame captured. - * @param play_cb Callback to be called everytime the sound device needs - * audio frames to be played back. - * @param user_data Arbitrary user data, which will be given back in the - * callbacks. - * @param p_strm Pointer to receive the audio stream. + * @param param Sound device parameters to be used for the stream. + * @param rec_cb Callback to be called on every input frame captured. + * @param play_cb Callback to be called everytime the sound device needs + * audio frames to be played back. + * @param user_data Arbitrary user data, which will be given back in the + * callbacks. + * @param p_strm Pointer to receive the audio stream. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_stream_create(const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_strm); + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_strm); /** * Get the running parameters for the specified audio stream. * - * @param strm The audio stream. - * @param param Audio stream parameters to be filled in by this - * function once it returns successfully. + * @param strm The audio stream. + * @param param Audio stream parameters to be filled in by this + * function once it returns successfully. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); + pjmedia_aud_param *param); /** * Get the value of a specific capability of the audio stream. * - * @param strm The audio stream. - * @param cap The audio capability which value is to be retrieved. - * @param value Pointer to value to be filled in by this function - * once it returns successfully. Please see the type - * of value to be supplied in the pjmedia_aud_dev_cap - * documentation. + * @param strm The audio stream. + * @param cap The audio capability which value is to be retrieved. + * @param value Pointer to value to be filled in by this function + * once it returns successfully. Please see the type + * of value to be supplied in the pjmedia_aud_dev_cap + * documentation. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); + pjmedia_aud_dev_cap cap, + void *value); /** * Set the value of a specific capability of the audio stream. * - * @param strm The audio stream. - * @param cap The audio capability which value is to be set. - * @param value Pointer to value. Please see the type of value to - * be supplied in the pjmedia_aud_dev_cap documentation. + * @param strm The audio stream. + * @param cap The audio capability which value is to be set. + * @param value Pointer to value. Please see the type of value to + * be supplied in the pjmedia_aud_dev_cap documentation. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); + pjmedia_aud_dev_cap cap, + const void *value); /** * Start the stream. * - * @param strm The audio stream. + * @param strm The audio stream. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_stream_start(pjmedia_aud_stream *strm); /** * Stop the stream. * - * @param strm The audio stream. + * @param strm The audio stream. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_stream_stop(pjmedia_aud_stream *strm); /** * Destroy the stream. * - * @param strm The audio stream. + * @param strm The audio stream. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_aud_stream_destroy(pjmedia_aud_stream *strm); @@ -753,5 +752,5 @@ PJ_DECL(pj_status_t) pjmedia_aud_stream_destroy(pjmedia_aud_stream *strm); PJ_END_DECL -#endif /* __PJMEDIA_AUDIO_DEV_H__ */ +#endif /* __PJMEDIA_AUDIO_DEV_H__ */ diff --git a/pjmedia/include/pjmedia/avi.h b/pjmedia/include/pjmedia/avi.h index 4ed0a85f2c..c89c08b28c 100644 --- a/pjmedia/include/pjmedia/avi.h +++ b/pjmedia/include/pjmedia/avi.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -80,9 +79,9 @@ typedef enum { /** This structure describes RIFF AVI file header */ typedef struct riff_hdr_t { - pj_uint32_t riff; /**< "RIFF" ASCII tag. */ - pj_uint32_t file_len; /**< File length minus 8 bytes */ - pj_uint32_t avi; /**< "AVI" ASCII tag. */ + pj_uint32_t riff; /**< "RIFF" ASCII tag. */ + pj_uint32_t file_len; /**< File length minus 8 bytes */ + pj_uint32_t avi; /**< "AVI" ASCII tag. */ } riff_hdr_t; /** This structure describes avih header */ @@ -131,12 +130,12 @@ typedef struct strl_hdr_t { typedef struct { pj_uint32_t strf; pj_uint32_t strf_size; - pj_uint16_t fmt_tag; /**< 1 for PCM */ - pj_uint16_t nchannels; /**< Number of channels. */ - pj_uint32_t sample_rate; /**< Sampling rate. */ - pj_uint32_t bytes_per_sec; /**< Average bytes per second. */ - pj_uint16_t block_align; /**< nchannels * bits / 8 */ - pj_uint16_t bits_per_sample; /**< Bits per sample. */ + pj_uint16_t fmt_tag; /**< 1 for PCM */ + pj_uint16_t nchannels; /**< Number of channels. */ + pj_uint32_t sample_rate; /**< Sampling rate. */ + pj_uint32_t bytes_per_sec; /**< Average bytes per second. */ + pj_uint16_t block_align; /**< nchannels * bits / 8 */ + pj_uint16_t bits_per_sample; /**< Bits per sample. */ pj_uint16_t extra_size; } strf_audio_hdr_t; @@ -187,8 +186,8 @@ typedef struct pjmedia_avi_hdr pjmedia_avi_hdr; */ typedef struct pjmedia_avi_subchunk { - pj_uint32_t id; /**< Subchunk ASCII tag. */ - pj_uint32_t len; /**< Length following this field */ + pj_uint32_t id; /**< Subchunk ASCII tag. */ + pj_uint32_t len; /**< Length following this field */ } pjmedia_avi_subchunk; @@ -199,4 +198,4 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_AVI_H__ */ +#endif /* __PJMEDIA_AVI_H__ */ diff --git a/pjmedia/include/pjmedia/avi_stream.h b/pjmedia/include/pjmedia/avi_stream.h index c70fe81074..17839b469e 100644 --- a/pjmedia/include/pjmedia/avi_stream.h +++ b/pjmedia/include/pjmedia/avi_stream.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -65,12 +64,12 @@ typedef struct pjmedia_avi_streams pjmedia_avi_streams; * reading AVI file with uncompressed video format and * 16 bit PCM or compressed G.711 A-law/U-law audio format. * - * @param pool Pool to create the streams. - * @param filename File name to open. - * @param flags Avi streams creation flags. - * @param p_streams Pointer to receive the avi streams instance. + * @param pool Pool to create the streams. + * @param filename File name to open. + * @param flags Avi streams creation flags. + * @param p_streams Pointer to receive the avi streams instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_avi_player_create_streams(pj_pool_t *pool, @@ -81,9 +80,9 @@ pjmedia_avi_player_create_streams(pj_pool_t *pool, /** * Get the number of AVI stream. * - * @param streams The AVI streams. + * @param streams The AVI streams. * - * @return The number of AVI stream. + * @return The number of AVI stream. */ PJ_DECL(unsigned) pjmedia_avi_streams_get_num_streams(pjmedia_avi_streams *streams); @@ -91,10 +90,10 @@ pjmedia_avi_streams_get_num_streams(pjmedia_avi_streams *streams); /** * Return the idx-th stream of the AVI streams. * - * @param streams The AVI streams. - * @param idx The stream index. + * @param streams The AVI streams. + * @param idx The stream index. * - * @return The AVI stream or NULL if it does not exist. + * @return The AVI stream or NULL if it does not exist. */ PJ_DECL(pjmedia_avi_stream *) pjmedia_avi_streams_get_stream(pjmedia_avi_streams *streams, @@ -103,11 +102,11 @@ pjmedia_avi_streams_get_stream(pjmedia_avi_streams *streams, /** * Return an AVI stream with a certain media type from the AVI streams. * - * @param streams The AVI streams. + * @param streams The AVI streams. * @param start_idx The starting index. * @param media_type The media type of the stream. * - * @return The AVI stream or NULL if it does not exist. + * @return The AVI stream or NULL if it does not exist. */ PJ_DECL(pjmedia_avi_stream *) pjmedia_avi_streams_get_stream_by_media(pjmedia_avi_streams *streams, @@ -117,9 +116,9 @@ pjmedia_avi_streams_get_stream_by_media(pjmedia_avi_streams *streams, /** * Return the media port of an AVI stream. * - * @param stream The AVI stream. + * @param stream The AVI stream. * - * @return The media port. + * @return The media port. */ PJ_INLINE(pjmedia_port *) pjmedia_avi_stream_get_port(pjmedia_avi_stream *stream) @@ -132,8 +131,8 @@ pjmedia_avi_stream_get_port(pjmedia_avi_stream *stream) * * @param stream The AVI stream. * - * @return The length of the data, in bytes. Upon error it will - * return negative value. + * @return The length of the data, in bytes. Upon error it will + * return negative value. */ PJ_DECL(pj_ssize_t) pjmedia_avi_stream_get_len(pjmedia_avi_stream *stream); @@ -145,20 +144,20 @@ PJ_DECL(pj_ssize_t) pjmedia_avi_stream_get_len(pjmedia_avi_stream *stream); * will be called multiple times. Note that only one callback can be * registered for each AVI stream. * - * @param stream The AVI stream. - * @param user_data User data to be specified in the callback - * @param cb Callback to be called. If the callback returns non- - * PJ_SUCCESS, the playback will stop. Note that if - * application destroys the file port in the callback, - * it must return non-PJ_SUCCESS here. + * @param stream The AVI stream. + * @param user_data User data to be specified in the callback + * @param cb Callback to be called. If the callback returns non- + * PJ_SUCCESS, the playback will stop. Note that if + * application destroys the file port in the callback, + * it must return non-PJ_SUCCESS here. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_avi_stream_set_eof_cb(pjmedia_avi_stream *stream, - void *user_data, - pj_status_t (*cb)(pjmedia_avi_stream *stream, - void *usr_data)); + void *user_data, + pj_status_t (*cb)(pjmedia_avi_stream *stream, + void *usr_data)); #endif @@ -168,21 +167,21 @@ pjmedia_avi_stream_set_eof_cb(pjmedia_avi_stream *stream, * will be called multiple times. Note that only one callback can be * registered for each AVI stream. * - * @param stream The AVI stream. - * @param user_data User data to be specified in the callback - * @param cb Callback to be called. Note that if - * application wishes to stop the playback, it - * can disconnect the port in the callback, and - * only after all connections have been removed - * could the application safely destroy the port. - * - * @return PJ_SUCCESS on success. + * @param stream The AVI stream. + * @param user_data User data to be specified in the callback + * @param cb Callback to be called. Note that if + * application wishes to stop the playback, it + * can disconnect the port in the callback, and + * only after all connections have been removed + * could the application safely destroy the port. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_avi_stream_set_eof_cb2(pjmedia_avi_stream *stream, - void *user_data, - void (*cb)(pjmedia_avi_stream *stream, - void *usr_data)); + void *user_data, + void (*cb)(pjmedia_avi_stream *stream, + void *usr_data)); /** @@ -193,4 +192,4 @@ pjmedia_avi_stream_set_eof_cb2(pjmedia_avi_stream *stream, PJ_END_DECL -#endif /* __PJMEDIA_AVI_STREAM_H__ */ +#endif /* __PJMEDIA_AVI_STREAM_H__ */ diff --git a/pjmedia/include/pjmedia/bidirectional.h b/pjmedia/include/pjmedia/bidirectional.h index 85b2214b8f..9addeb2e07 100644 --- a/pjmedia/include/pjmedia/bidirectional.h +++ b/pjmedia/include/pjmedia/bidirectional.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -42,17 +41,17 @@ PJ_BEGIN_DECL /** * Create bidirectional port from two unidirectional ports * - * @param pool Pool to allocate memory. - * @param get_port Port where get_frame() will be directed to. - * @param put_port Port where put_frame() will be directed to. - * @param p_port Pointer to receive the port instance. + * @param pool Pool to allocate memory. + * @param get_port Port where get_frame() will be directed to. + * @param put_port Port where put_frame() will be directed to. + * @param p_port Pointer to receive the port instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_bidirectional_port_create(pj_pool_t *pool, - pjmedia_port *get_port, - pjmedia_port *put_port, - pjmedia_port **p_port ); + pjmedia_port *get_port, + pjmedia_port *put_port, + pjmedia_port **p_port ); @@ -63,5 +62,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_BIDIRECTIONAL_H__ */ +#endif /* __PJMEDIA_BIDIRECTIONAL_H__ */ diff --git a/pjmedia/include/pjmedia/circbuf.h b/pjmedia/include/pjmedia/circbuf.h index de23e6cc61..d6caabfa24 100644 --- a/pjmedia/include/pjmedia/circbuf.h +++ b/pjmedia/include/pjmedia/circbuf.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -58,36 +57,36 @@ PJ_BEGIN_DECL * Circular buffer structure */ typedef struct pjmedia_circ_buf { - pj_int16_t *buf; /**< The buffer */ - unsigned capacity; /**< Buffer capacity, in samples */ + pj_int16_t *buf; /**< The buffer */ + unsigned capacity; /**< Buffer capacity, in samples */ - pj_int16_t *start; /**< Pointer to the first sample */ - unsigned len; /**< Audio samples length, - in samples */ + pj_int16_t *start; /**< Pointer to the first sample */ + unsigned len; /**< Audio samples length, + in samples */ } pjmedia_circ_buf; /** * Create the circular buffer. * - * @param pool Pool where the circular buffer will be allocated - * from. - * @param capacity Capacity of the buffer, in samples. - * @param p_cb Pointer to receive the circular buffer instance. + * @param pool Pool where the circular buffer will be allocated + * from. + * @param capacity Capacity of the buffer, in samples. + * @param p_cb Pointer to receive the circular buffer instance. * - * @return PJ_SUCCESS if the circular buffer has been - * created successfully, otherwise the appropriate - * error will be returned. + * @return PJ_SUCCESS if the circular buffer has been + * created successfully, otherwise the appropriate + * error will be returned. */ PJ_INLINE(pj_status_t) pjmedia_circ_buf_create(pj_pool_t *pool, - unsigned capacity, - pjmedia_circ_buf **p_cb) + unsigned capacity, + pjmedia_circ_buf **p_cb) { pjmedia_circ_buf *cbuf; cbuf = PJ_POOL_ZALLOC_T(pool, pjmedia_circ_buf); cbuf->buf = (pj_int16_t*) pj_pool_calloc(pool, capacity, - sizeof(pj_int16_t)); + sizeof(pj_int16_t)); cbuf->capacity = capacity; cbuf->start = cbuf->buf; cbuf->len = 0; @@ -101,9 +100,9 @@ PJ_INLINE(pj_status_t) pjmedia_circ_buf_create(pj_pool_t *pool, /** * Reset the circular buffer. * - * @param circbuf The circular buffer. + * @param circbuf The circular buffer. * - * @return PJ_SUCCESS when successful. + * @return PJ_SUCCESS when successful. */ PJ_INLINE(pj_status_t) pjmedia_circ_buf_reset(pjmedia_circ_buf *circbuf) { @@ -118,9 +117,9 @@ PJ_INLINE(pj_status_t) pjmedia_circ_buf_reset(pjmedia_circ_buf *circbuf) * Get the circular buffer length, it is number of samples buffered in the * circular buffer. * - * @param circbuf The circular buffer. + * @param circbuf The circular buffer. * - * @return The buffer length. + * @return The buffer length. */ PJ_INLINE(unsigned) pjmedia_circ_buf_get_len(pjmedia_circ_buf *circbuf) { @@ -132,11 +131,11 @@ PJ_INLINE(unsigned) pjmedia_circ_buf_get_len(pjmedia_circ_buf *circbuf) * Set circular buffer length. This is useful when audio buffer is manually * manipulated by the user, e.g: shrinked, expanded. * - * @param circbuf The circular buffer. - * @param len The new buffer length. + * @param circbuf The circular buffer. + * @param len The new buffer length. */ PJ_INLINE(void) pjmedia_circ_buf_set_len(pjmedia_circ_buf *circbuf, - unsigned len) + unsigned len) { PJMEDIA_CIRC_BUF_CHECK(len <= circbuf->capacity); circbuf->len = len; @@ -148,24 +147,24 @@ PJ_INLINE(void) pjmedia_circ_buf_set_len(pjmedia_circ_buf *circbuf, * the skipped samples while advancing the read pointer, thus reducing * the buffer length. * - * @param circbuf The circular buffer. - * @param count Distance from current read pointer, can only be - * possitive number, in samples. + * @param circbuf The circular buffer. + * @param count Distance from current read pointer, can only be + * possitive number, in samples. * - * @return PJ_SUCCESS when successful, otherwise - * the appropriate error will be returned. + * @return PJ_SUCCESS when successful, otherwise + * the appropriate error will be returned. */ PJ_INLINE(pj_status_t) pjmedia_circ_buf_adv_read_ptr(pjmedia_circ_buf *circbuf, - unsigned count) + unsigned count) { if (count >= circbuf->len) - return pjmedia_circ_buf_reset(circbuf); + return pjmedia_circ_buf_reset(circbuf); PJMEDIA_CIRC_BUF_CHECK(count <= circbuf->len); circbuf->start += count; if (circbuf->start >= circbuf->buf + circbuf->capacity) - circbuf->start -= circbuf->capacity; + circbuf->start -= circbuf->capacity; circbuf->len -= count; return PJ_SUCCESS; @@ -177,18 +176,18 @@ PJ_INLINE(pj_status_t) pjmedia_circ_buf_adv_read_ptr(pjmedia_circ_buf *circbuf, * pointing to a sample after the end of sample, so this function also means * increasing the buffer length. * - * @param circbuf The circular buffer. - * @param count Distance from current write pointer, can only be - * possitive number, in samples. + * @param circbuf The circular buffer. + * @param count Distance from current write pointer, can only be + * possitive number, in samples. * - * @return PJ_SUCCESS when successful, otherwise - * the appropriate error will be returned. + * @return PJ_SUCCESS when successful, otherwise + * the appropriate error will be returned. */ PJ_INLINE(pj_status_t) pjmedia_circ_buf_adv_write_ptr(pjmedia_circ_buf *circbuf, - unsigned count) + unsigned count) { if (count + circbuf->len > circbuf->capacity) - return PJ_ETOOBIG; + return PJ_ETOOBIG; circbuf->len += count; @@ -199,34 +198,34 @@ PJ_INLINE(pj_status_t) pjmedia_circ_buf_adv_write_ptr(pjmedia_circ_buf *circbuf, /** * Get the real buffer addresses containing the audio samples. * - * @param circbuf The circular buffer. - * @param reg1 Pointer to store the first buffer address. - * @param reg1_len Pointer to store the length of the first buffer, - * in samples. - * @param reg2 Pointer to store the second buffer address. - * @param reg2_len Pointer to store the length of the second buffer, - * in samples. + * @param circbuf The circular buffer. + * @param reg1 Pointer to store the first buffer address. + * @param reg1_len Pointer to store the length of the first buffer, + * in samples. + * @param reg2 Pointer to store the second buffer address. + * @param reg2_len Pointer to store the length of the second buffer, + * in samples. */ PJ_INLINE(void) pjmedia_circ_buf_get_read_regions(pjmedia_circ_buf *circbuf, - pj_int16_t **reg1, - unsigned *reg1_len, - pj_int16_t **reg2, - unsigned *reg2_len) + pj_int16_t **reg1, + unsigned *reg1_len, + pj_int16_t **reg2, + unsigned *reg2_len) { *reg1 = circbuf->start; *reg1_len = circbuf->len; if (*reg1 + *reg1_len > circbuf->buf + circbuf->capacity) { - *reg1_len = (unsigned)(circbuf->buf + circbuf->capacity - - circbuf->start); - *reg2 = circbuf->buf; - *reg2_len = circbuf->len - *reg1_len; + *reg1_len = (unsigned)(circbuf->buf + circbuf->capacity - + circbuf->start); + *reg2 = circbuf->buf; + *reg2_len = circbuf->len - *reg1_len; } else { - *reg2 = NULL; - *reg2_len = 0; + *reg2 = NULL; + *reg2_len = 0; } PJMEDIA_CIRC_BUF_CHECK(*reg1_len != 0 || (*reg1_len == 0 && - circbuf->len == 0)); + circbuf->len == 0)); PJMEDIA_CIRC_BUF_CHECK(*reg1_len + *reg2_len == circbuf->len); } @@ -234,68 +233,68 @@ PJ_INLINE(void) pjmedia_circ_buf_get_read_regions(pjmedia_circ_buf *circbuf, /** * Get the real buffer addresses that is empty or writeable. * - * @param circbuf The circular buffer. - * @param reg1 Pointer to store the first buffer address. - * @param reg1_len Pointer to store the length of the first buffer, - * in samples. - * @param reg2 Pointer to store the second buffer address. - * @param reg2_len Pointer to store the length of the second buffer, - * in samples. + * @param circbuf The circular buffer. + * @param reg1 Pointer to store the first buffer address. + * @param reg1_len Pointer to store the length of the first buffer, + * in samples. + * @param reg2 Pointer to store the second buffer address. + * @param reg2_len Pointer to store the length of the second buffer, + * in samples. */ PJ_INLINE(void) pjmedia_circ_buf_get_write_regions(pjmedia_circ_buf *circbuf, - pj_int16_t **reg1, - unsigned *reg1_len, - pj_int16_t **reg2, - unsigned *reg2_len) + pj_int16_t **reg1, + unsigned *reg1_len, + pj_int16_t **reg2, + unsigned *reg2_len) { *reg1 = circbuf->start + circbuf->len; if (*reg1 >= circbuf->buf + circbuf->capacity) - *reg1 -= circbuf->capacity; + *reg1 -= circbuf->capacity; *reg1_len = circbuf->capacity - circbuf->len; if (*reg1 + *reg1_len > circbuf->buf + circbuf->capacity) { - *reg1_len = (unsigned)(circbuf->buf + circbuf->capacity - *reg1); - *reg2 = circbuf->buf; - *reg2_len = (unsigned)(circbuf->start - circbuf->buf); + *reg1_len = (unsigned)(circbuf->buf + circbuf->capacity - *reg1); + *reg2 = circbuf->buf; + *reg2_len = (unsigned)(circbuf->start - circbuf->buf); } else { - *reg2 = NULL; - *reg2_len = 0; + *reg2 = NULL; + *reg2_len = 0; } PJMEDIA_CIRC_BUF_CHECK(*reg1_len != 0 || (*reg1_len == 0 && - circbuf->len == 0)); + circbuf->len == 0)); PJMEDIA_CIRC_BUF_CHECK(*reg1_len + *reg2_len == circbuf->capacity - - circbuf->len); + circbuf->len); } /** * Read audio samples from the circular buffer. * - * @param circbuf The circular buffer. - * @param data Buffer to store the read audio samples. - * @param count Number of samples being read. + * @param circbuf The circular buffer. + * @param data Buffer to store the read audio samples. + * @param count Number of samples being read. * - * @return PJ_SUCCESS when successful, otherwise - * the appropriate error will be returned. + * @return PJ_SUCCESS when successful, otherwise + * the appropriate error will be returned. */ PJ_INLINE(pj_status_t) pjmedia_circ_buf_read(pjmedia_circ_buf *circbuf, - pj_int16_t *data, - unsigned count) + pj_int16_t *data, + unsigned count) { pj_int16_t *reg1, *reg2; unsigned reg1cnt, reg2cnt; /* Data in the buffer is less than requested */ if (count > circbuf->len) - return PJ_ETOOBIG; + return PJ_ETOOBIG; pjmedia_circ_buf_get_read_regions(circbuf, ®1, ®1cnt, - ®2, ®2cnt); + ®2, ®2cnt); if (reg1cnt >= count) { - pjmedia_copy_samples(data, reg1, count); + pjmedia_copy_samples(data, reg1, count); } else { - pjmedia_copy_samples(data, reg1, reg1cnt); - pjmedia_copy_samples(data + reg1cnt, reg2, count - reg1cnt); + pjmedia_copy_samples(data, reg1, reg1cnt); + pjmedia_copy_samples(data + reg1cnt, reg2, count - reg1cnt); } return pjmedia_circ_buf_adv_read_ptr(circbuf, count); @@ -305,31 +304,31 @@ PJ_INLINE(pj_status_t) pjmedia_circ_buf_read(pjmedia_circ_buf *circbuf, /** * Write audio samples to the circular buffer. * - * @param circbuf The circular buffer. - * @param data Audio samples to be written. - * @param count Number of samples being written. + * @param circbuf The circular buffer. + * @param data Audio samples to be written. + * @param count Number of samples being written. * - * @return PJ_SUCCESS when successful, otherwise - * the appropriate error will be returned. + * @return PJ_SUCCESS when successful, otherwise + * the appropriate error will be returned. */ PJ_INLINE(pj_status_t) pjmedia_circ_buf_write(pjmedia_circ_buf *circbuf, - pj_int16_t *data, - unsigned count) + pj_int16_t *data, + unsigned count) { pj_int16_t *reg1, *reg2; unsigned reg1cnt, reg2cnt; /* Data to write is larger than buffer can store */ if (count > circbuf->capacity - circbuf->len) - return PJ_ETOOBIG; + return PJ_ETOOBIG; pjmedia_circ_buf_get_write_regions(circbuf, ®1, ®1cnt, - ®2, ®2cnt); + ®2, ®2cnt); if (reg1cnt >= count) { - pjmedia_copy_samples(reg1, data, count); + pjmedia_copy_samples(reg1, data, count); } else { - pjmedia_copy_samples(reg1, data, reg1cnt); - pjmedia_copy_samples(reg2, data + reg1cnt, count - reg1cnt); + pjmedia_copy_samples(reg1, data, reg1cnt); + pjmedia_copy_samples(reg2, data + reg1cnt, count - reg1cnt); } return pjmedia_circ_buf_adv_write_ptr(circbuf, count); @@ -339,38 +338,38 @@ PJ_INLINE(pj_status_t) pjmedia_circ_buf_write(pjmedia_circ_buf *circbuf, /** * Copy audio samples from the circular buffer without changing its state. * - * @param circbuf The circular buffer. - * @param start_idx Starting sample index to be copied. - * @param data Buffer to store the read audio samples. - * @param count Number of samples being read. + * @param circbuf The circular buffer. + * @param start_idx Starting sample index to be copied. + * @param data Buffer to store the read audio samples. + * @param count Number of samples being read. * - * @return PJ_SUCCESS when successful, otherwise - * the appropriate error will be returned. + * @return PJ_SUCCESS when successful, otherwise + * the appropriate error will be returned. */ PJ_INLINE(pj_status_t) pjmedia_circ_buf_copy(pjmedia_circ_buf *circbuf, - unsigned start_idx, - pj_int16_t *data, - unsigned count) + unsigned start_idx, + pj_int16_t *data, + unsigned count) { pj_int16_t *reg1, *reg2; unsigned reg1cnt, reg2cnt; /* Data in the buffer is less than requested */ if (count + start_idx > circbuf->len) - return PJ_ETOOBIG; + return PJ_ETOOBIG; pjmedia_circ_buf_get_read_regions(circbuf, ®1, ®1cnt, - ®2, ®2cnt); + ®2, ®2cnt); if (reg1cnt > start_idx) { - unsigned tmp_len; - tmp_len = reg1cnt - start_idx; - if (tmp_len > count) - tmp_len = count; - pjmedia_copy_samples(data, reg1 + start_idx, tmp_len); - if (tmp_len < count) - pjmedia_copy_samples(data + tmp_len, reg2, count - tmp_len); + unsigned tmp_len; + tmp_len = reg1cnt - start_idx; + if (tmp_len > count) + tmp_len = count; + pjmedia_copy_samples(data, reg1 + start_idx, tmp_len); + if (tmp_len < count) + pjmedia_copy_samples(data + tmp_len, reg2, count - tmp_len); } else { - pjmedia_copy_samples(data, reg2 + start_idx - reg1cnt, count); + pjmedia_copy_samples(data, reg2 + start_idx - reg1cnt, count); } return PJ_SUCCESS; @@ -381,10 +380,10 @@ PJ_INLINE(pj_status_t) pjmedia_circ_buf_copy(pjmedia_circ_buf *circbuf, * Pack the buffer so the first sample will be in the beginning of the buffer. * This will also make the buffer contiguous. * - * @param circbuf The circular buffer. + * @param circbuf The circular buffer. * - * @return PJ_SUCCESS when successful, otherwise - * the appropriate error will be returned. + * @return PJ_SUCCESS when successful, otherwise + * the appropriate error will be returned. */ PJ_INLINE(pj_status_t) pjmedia_circ_buf_pack_buffer(pjmedia_circ_buf *circbuf) { @@ -393,35 +392,35 @@ PJ_INLINE(pj_status_t) pjmedia_circ_buf_pack_buffer(pjmedia_circ_buf *circbuf) unsigned gap; pjmedia_circ_buf_get_read_regions(circbuf, ®1, ®1cnt, - ®2, ®2cnt); + ®2, ®2cnt); /* Check if not contigue */ if (reg2cnt != 0) { - /* Check if no space left to roll the buffer - * (or should this function provide temporary buffer?) - */ - gap = circbuf->capacity - pjmedia_circ_buf_get_len(circbuf); - if (gap == 0) - return PJ_ETOOBIG; - - /* Roll buffer left using the gap until reg2cnt == 0 */ - do { - if (gap > reg2cnt) - gap = reg2cnt; - pjmedia_move_samples(reg1 - gap, reg1, reg1cnt); - pjmedia_copy_samples(reg1 + reg1cnt - gap, reg2, gap); - if (gap < reg2cnt) - pjmedia_move_samples(reg2, reg2 + gap, reg2cnt - gap); - reg1 -= gap; - reg1cnt += gap; - reg2cnt -= gap; - } while (reg2cnt > 0); + /* Check if no space left to roll the buffer + * (or should this function provide temporary buffer?) + */ + gap = circbuf->capacity - pjmedia_circ_buf_get_len(circbuf); + if (gap == 0) + return PJ_ETOOBIG; + + /* Roll buffer left using the gap until reg2cnt == 0 */ + do { + if (gap > reg2cnt) + gap = reg2cnt; + pjmedia_move_samples(reg1 - gap, reg1, reg1cnt); + pjmedia_copy_samples(reg1 + reg1cnt - gap, reg2, gap); + if (gap < reg2cnt) + pjmedia_move_samples(reg2, reg2 + gap, reg2cnt - gap); + reg1 -= gap; + reg1cnt += gap; + reg2cnt -= gap; + } while (reg2cnt > 0); } /* Finally, Shift samples to the left edge */ if (reg1 != circbuf->buf) - pjmedia_move_samples(circbuf->buf, reg1, - pjmedia_circ_buf_get_len(circbuf)); + pjmedia_move_samples(circbuf->buf, reg1, + pjmedia_circ_buf_get_len(circbuf)); circbuf->start = circbuf->buf; return PJ_SUCCESS; diff --git a/pjmedia/include/pjmedia/clock.h b/pjmedia/include/pjmedia/clock.h index bd2b4e5b15..1da5fa1e22 100644 --- a/pjmedia/include/pjmedia/clock.h +++ b/pjmedia/include/pjmedia/clock.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -105,10 +104,10 @@ typedef struct pjmedia_clock_src * * @param clocksrc The clock source to be initialized. * @param media_type The media type. - * @param clock_rate The clock rate. + * @param clock_rate The clock rate. * @param ptime_usec Media frame interval (in usec). * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_clock_src_init( pjmedia_clock_src *clocksrc, pjmedia_type media_type, @@ -125,7 +124,7 @@ PJ_DECL(pj_status_t) pjmedia_clock_src_init( pjmedia_clock_src *clocksrc, * timestamp does not change (in this case it * will only update the last_update field). * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_clock_src_update( pjmedia_clock_src *clocksrc, const pj_timestamp *timestamp ); @@ -139,7 +138,7 @@ PJ_DECL(pj_status_t) pjmedia_clock_src_update( pjmedia_clock_src *clocksrc, * @param clocksrc The clock source. * @param timestamp Argument to receive the current timestamp * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_clock_src_get_current_timestamp( const pjmedia_clock_src *clocksrc, @@ -150,7 +149,7 @@ pjmedia_clock_src_get_current_timestamp( const pjmedia_clock_src *clocksrc, * * @param clocksrc The clock source. * - * @return The clock source's time (in msec). + * @return The clock source's time (in msec). */ PJ_DECL(pj_uint32_t) pjmedia_clock_src_get_time_msec( const pjmedia_clock_src *clocksrc ); @@ -197,12 +196,12 @@ typedef struct pjmedia_clock_param /** * Type of media clock callback. * - * @param ts Current timestamp, in samples. - * @param user_data Application data that is passed when - * the clock was created. + * @param ts Current timestamp, in samples. + * @param user_data Application data that is passed when + * the clock was created. */ typedef void pjmedia_clock_callback(const pj_timestamp *ts, - void *user_data); + void *user_data); @@ -214,28 +213,28 @@ typedef void pjmedia_clock_callback(const pj_timestamp *ts, * * @see pjmedia_clock_create2() * - * @param pool Pool to allocate memory. - * @param clock_rate Number of samples per second. - * @param channel_count Number of channel. + * @param pool Pool to allocate memory. + * @param clock_rate Number of samples per second. + * @param channel_count Number of channel. * @param samples_per_frame Number of samples per frame. This argument - * along with clock_rate and channel_count, specifies - * the interval of each clock run (or clock ticks). - * @param options Bitmask of pjmedia_clock_options. - * @param cb Callback to be called for each clock tick. - * @param user_data User data, which will be passed to the callback. - * @param p_clock Pointer to receive the clock instance. + * along with clock_rate and channel_count, specifies + * the interval of each clock run (or clock ticks). + * @param options Bitmask of pjmedia_clock_options. + * @param cb Callback to be called for each clock tick. + * @param user_data User data, which will be passed to the callback. + * @param p_clock Pointer to receive the clock instance. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_clock_create( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned options, - pjmedia_clock_callback *cb, - void *user_data, - pjmedia_clock **p_clock); + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned options, + pjmedia_clock_callback *cb, + void *user_data, + pjmedia_clock **p_clock); /** @@ -243,31 +242,31 @@ PJ_DECL(pj_status_t) pjmedia_clock_create( pj_pool_t *pool, * periodically at the specified interval. Once created, application must * call #pjmedia_clock_start() to actually start the clock. * - * @param pool Pool to allocate memory. - * @param param The clock parameter. - * @param options Bitmask of pjmedia_clock_options. - * @param cb Callback to be called for each clock tick. - * @param user_data User data, which will be passed to the callback. - * @param p_clock Pointer to receive the clock instance. + * @param pool Pool to allocate memory. + * @param param The clock parameter. + * @param options Bitmask of pjmedia_clock_options. + * @param cb Callback to be called for each clock tick. + * @param user_data User data, which will be passed to the callback. + * @param p_clock Pointer to receive the clock instance. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_clock_create2(pj_pool_t *pool, const pjmedia_clock_param *param, - unsigned options, - pjmedia_clock_callback *cb, - void *user_data, - pjmedia_clock **p_clock); + unsigned options, + pjmedia_clock_callback *cb, + void *user_data, + pjmedia_clock **p_clock); /** * Start the clock. For clock created with asynchronous flag set to TRUE, * this may start a worker thread for the clock (depending on the * backend clock implementation being used). * - * @param clock The media clock. + * @param clock The media clock. * - * @return PJ_SUCCES on success. + * @return PJ_SUCCES on success. */ PJ_DECL(pj_status_t) pjmedia_clock_start(pjmedia_clock *clock); @@ -275,9 +274,9 @@ PJ_DECL(pj_status_t) pjmedia_clock_start(pjmedia_clock *clock); /** * Stop the clock. * - * @param clock The media clock. + * @param clock The media clock. * - * @return PJ_SUCCES on success. + * @return PJ_SUCCES on success. */ PJ_DECL(pj_status_t) pjmedia_clock_stop(pjmedia_clock *clock); @@ -285,9 +284,9 @@ PJ_DECL(pj_status_t) pjmedia_clock_stop(pjmedia_clock *clock); /** * Modify the clock's parameter. * - * @param clock The media clock. - * @param param The clock's new parameter. - * @return PJ_SUCCES on success. + * @param clock The media clock. + * @param param The clock's new parameter. + * @return PJ_SUCCES on success. */ PJ_DECL(pj_status_t) pjmedia_clock_modify(pjmedia_clock *clock, const pjmedia_clock_param *param); @@ -298,27 +297,27 @@ PJ_DECL(pj_status_t) pjmedia_clock_modify(pjmedia_clock *clock, * elapsed. This operation is only valid if the clock is created with async * flag set to FALSE. * - * @param clock The media clock. - * @param wait If non-zero, then the function will block until - * a clock tick elapsed and callback has been called. - * @param ts Optional argument to receive the current - * timestamp. + * @param clock The media clock. + * @param wait If non-zero, then the function will block until + * a clock tick elapsed and callback has been called. + * @param ts Optional argument to receive the current + * timestamp. * - * @return Non-zero if clock tick has elapsed, or FALSE if - * the function returns before a clock tick has - * elapsed. + * @return Non-zero if clock tick has elapsed, or FALSE if + * the function returns before a clock tick has + * elapsed. */ PJ_DECL(pj_bool_t) pjmedia_clock_wait(pjmedia_clock *clock, - pj_bool_t wait, - pj_timestamp *ts); + pj_bool_t wait, + pj_timestamp *ts); /** * Destroy the clock. * - * @param clock The media clock. + * @param clock The media clock. * - * @return PJ_SUCCES on success. + * @return PJ_SUCCES on success. */ PJ_DECL(pj_status_t) pjmedia_clock_destroy(pjmedia_clock *clock); @@ -331,5 +330,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_CLOCK_H__ */ +#endif /* __PJMEDIA_CLOCK_H__ */ diff --git a/pjmedia/include/pjmedia/codec.h b/pjmedia/include/pjmedia/codec.h index 02c8fef9ca..3bc5539967 100644 --- a/pjmedia/include/pjmedia/codec.h +++ b/pjmedia/include/pjmedia/codec.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -124,7 +123,7 @@ PJ_BEGIN_DECL // Find codec info for the specified coded ID (i.e. "pcma"). status = pjmedia_codec_mgr_find_codecs_by_id( codec_mgr, &codec_id, - &count, &codec_info, NULL); + &count, &codec_info, NULL); // Allocate the codec. status = pjmedia_codec_mgr_alloc_codec( codec_mgr, codec_info, &codec ); @@ -151,7 +150,7 @@ PJ_BEGIN_DECL // Retrieve default codec param for the specified codec. pjmedia_codec_mgr_get_default_param(codec_mgr, codec_info, - ¶m); + ¶m); // Application may change the "settings" part of codec param, // for example, to disable VAD @@ -196,34 +195,34 @@ PJ_BEGIN_DECL */ enum pjmedia_rtp_pt { - PJMEDIA_RTP_PT_PCMU = 0, /**< audio PCMU */ - PJMEDIA_RTP_PT_G721 = 2, /**< audio G721 (old def for G726-32) */ - PJMEDIA_RTP_PT_GSM = 3, /**< audio GSM */ - PJMEDIA_RTP_PT_G723 = 4, /**< audio G723 */ - PJMEDIA_RTP_PT_DVI4_8K = 5, /**< audio DVI4 8KHz */ - PJMEDIA_RTP_PT_DVI4_16K = 6, /**< audio DVI4 16Khz */ - PJMEDIA_RTP_PT_LPC = 7, /**< audio LPC */ - PJMEDIA_RTP_PT_PCMA = 8, /**< audio PCMA */ - PJMEDIA_RTP_PT_G722 = 9, /**< audio G722 */ - PJMEDIA_RTP_PT_L16_2 = 10, /**< audio 16bit linear 44.1KHz stereo */ - PJMEDIA_RTP_PT_L16_1 = 11, /**< audio 16bit linear 44.1KHz mono */ - PJMEDIA_RTP_PT_QCELP = 12, /**< audio QCELP */ - PJMEDIA_RTP_PT_CN = 13, /**< audio Comfort Noise */ - PJMEDIA_RTP_PT_MPA = 14, /**< audio MPEG1/MPEG2 elemetr. streams */ - PJMEDIA_RTP_PT_G728 = 15, /**< audio G728 */ - PJMEDIA_RTP_PT_DVI4_11K = 16, /**< audio DVI4 11.025KHz mono */ - PJMEDIA_RTP_PT_DVI4_22K = 17, /**< audio DVI4 22.050KHz mono */ - PJMEDIA_RTP_PT_G729 = 18, /**< audio G729 */ - - PJMEDIA_RTP_PT_CELB = 25, /**< video/comb Cell-B by Sun (RFC2029) */ - PJMEDIA_RTP_PT_JPEG = 26, /**< video JPEG */ - PJMEDIA_RTP_PT_NV = 28, /**< video NV by nv program by Xerox */ - PJMEDIA_RTP_PT_H261 = 31, /**< video H261 */ - PJMEDIA_RTP_PT_MPV = 32, /**< video MPEG1 or MPEG2 elementary */ - PJMEDIA_RTP_PT_MP2T = 33, /**< video MPEG2 transport */ - PJMEDIA_RTP_PT_H263 = 34, /**< video H263 */ - - PJMEDIA_RTP_PT_DYNAMIC = 96 /**< start of dynamic RTP payload */ + PJMEDIA_RTP_PT_PCMU = 0, /**< audio PCMU */ + PJMEDIA_RTP_PT_G721 = 2, /**< audio G721 (old def for G726-32) */ + PJMEDIA_RTP_PT_GSM = 3, /**< audio GSM */ + PJMEDIA_RTP_PT_G723 = 4, /**< audio G723 */ + PJMEDIA_RTP_PT_DVI4_8K = 5, /**< audio DVI4 8KHz */ + PJMEDIA_RTP_PT_DVI4_16K = 6, /**< audio DVI4 16Khz */ + PJMEDIA_RTP_PT_LPC = 7, /**< audio LPC */ + PJMEDIA_RTP_PT_PCMA = 8, /**< audio PCMA */ + PJMEDIA_RTP_PT_G722 = 9, /**< audio G722 */ + PJMEDIA_RTP_PT_L16_2 = 10, /**< audio 16bit linear 44.1KHz stereo */ + PJMEDIA_RTP_PT_L16_1 = 11, /**< audio 16bit linear 44.1KHz mono */ + PJMEDIA_RTP_PT_QCELP = 12, /**< audio QCELP */ + PJMEDIA_RTP_PT_CN = 13, /**< audio Comfort Noise */ + PJMEDIA_RTP_PT_MPA = 14, /**< audio MPEG1/MPEG2 elemetr. streams */ + PJMEDIA_RTP_PT_G728 = 15, /**< audio G728 */ + PJMEDIA_RTP_PT_DVI4_11K = 16, /**< audio DVI4 11.025KHz mono */ + PJMEDIA_RTP_PT_DVI4_22K = 17, /**< audio DVI4 22.050KHz mono */ + PJMEDIA_RTP_PT_G729 = 18, /**< audio G729 */ + + PJMEDIA_RTP_PT_CELB = 25, /**< video/comb Cell-B by Sun (RFC2029) */ + PJMEDIA_RTP_PT_JPEG = 26, /**< video JPEG */ + PJMEDIA_RTP_PT_NV = 28, /**< video NV by nv program by Xerox */ + PJMEDIA_RTP_PT_H261 = 31, /**< video H261 */ + PJMEDIA_RTP_PT_MPV = 32, /**< video MPEG1 or MPEG2 elementary */ + PJMEDIA_RTP_PT_MP2T = 33, /**< video MPEG2 transport */ + PJMEDIA_RTP_PT_H263 = 34, /**< video H263 */ + + PJMEDIA_RTP_PT_DYNAMIC = 96 /**< start of dynamic RTP payload */ }; @@ -234,11 +233,11 @@ enum pjmedia_rtp_pt */ typedef struct pjmedia_codec_info { - pjmedia_type type; /**< Media type. */ - unsigned pt; /**< Payload type (can be dynamic). */ - pj_str_t encoding_name; /**< Encoding name. */ - unsigned clock_rate; /**< Sampling rate. */ - unsigned channel_cnt; /**< Channel count. */ + pjmedia_type type; /**< Media type. */ + unsigned pt; /**< Payload type (can be dynamic). */ + pj_str_t encoding_name; /**< Encoding name. */ + unsigned clock_rate; /**< Sampling rate. */ + unsigned channel_cnt; /**< Channel count. */ } pjmedia_codec_info; /** @@ -248,11 +247,11 @@ typedef struct pjmedia_codec_info */ typedef struct pjmedia_codec_fmtp { - pj_uint8_t cnt; /**< Number of parameters. */ + pj_uint8_t cnt; /**< Number of parameters. */ struct param { - pj_str_t name; /**< Parameter name. */ - pj_str_t val; /**< Parameter value. */ - } param [PJMEDIA_CODEC_MAX_FMTP_CNT]; /**< The parameters. */ + pj_str_t name; /**< Parameter name. */ + pj_str_t val; /**< Parameter value. */ + } param [PJMEDIA_CODEC_MAX_FMTP_CNT]; /**< The parameters. */ } pjmedia_codec_fmtp; /** @@ -272,19 +271,19 @@ typedef struct pjmedia_codec_param * and is recommended not to be modified unless necessary. */ struct { - unsigned clock_rate; /**< Sampling rate in Hz */ - unsigned channel_cnt; /**< Channel count. */ - pj_uint32_t avg_bps; /**< Average bandwidth in bits/sec */ - pj_uint32_t max_bps; /**< Maximum bandwidth in bits/sec */ + unsigned clock_rate; /**< Sampling rate in Hz */ + unsigned channel_cnt; /**< Channel count. */ + pj_uint32_t avg_bps; /**< Average bandwidth in bits/sec */ + pj_uint32_t max_bps; /**< Maximum bandwidth in bits/sec */ unsigned max_rx_frame_size; /**< Maximum frame size */ - pj_uint16_t frm_ptime; /**< Decoder frame ptime in msec. */ - pj_uint16_t enc_ptime; /**< Encoder ptime, or zero if it's - equal to decoder ptime. */ - pj_uint8_t pcm_bits_per_sample; /**< Bits/sample in the PCM side */ - pj_uint8_t pt; /**< Payload type. */ - pjmedia_format_id fmt_id; /**< Source format, it's format of - encoder input and decoder - output. */ + pj_uint16_t frm_ptime; /**< Decoder frame ptime in msec. */ + pj_uint16_t enc_ptime; /**< Encoder ptime, or zero if it's + equal to decoder ptime. */ + pj_uint8_t pcm_bits_per_sample; /**< Bits/sample in the PCM side */ + pj_uint8_t pt; /**< Payload type. */ + pjmedia_format_id fmt_id; /**< Source format, it's format of + encoder input and decoder + output. */ } info; /** @@ -297,17 +296,17 @@ typedef struct pjmedia_codec_param * settings here before instantiating or modifying the codec. */ struct { - pj_uint8_t frm_per_pkt; /**< Number of frames per packet. */ - unsigned vad:1; /**< Voice Activity Detector. */ - unsigned cng:1; /**< Comfort Noise Generator. */ - unsigned penh:1; /**< Perceptual Enhancement */ - unsigned plc:1; /**< Packet loss concealment */ - unsigned reserved:1; /**< Reserved, must be zero. */ - pjmedia_codec_fmtp enc_fmtp;/**< Encoder's fmtp params. */ - pjmedia_codec_fmtp dec_fmtp;/**< Decoder's fmtp params. */ - unsigned packet_loss; /**< Encoder's expected pkt loss %. */ - unsigned complexity; /**< Encoder complexity, 0-10(max). */ - pj_bool_t cbr; /**< Constant bit rate? */ + pj_uint8_t frm_per_pkt; /**< Number of frames per packet. */ + unsigned vad:1; /**< Voice Activity Detector. */ + unsigned cng:1; /**< Comfort Noise Generator. */ + unsigned penh:1; /**< Perceptual Enhancement */ + unsigned plc:1; /**< Packet loss concealment */ + unsigned reserved:1; /**< Reserved, must be zero. */ + pjmedia_codec_fmtp enc_fmtp;/**< Encoder's fmtp params. */ + pjmedia_codec_fmtp dec_fmtp;/**< Decoder's fmtp params. */ + unsigned packet_loss; /**< Encoder's expected pkt loss %. */ + unsigned complexity; /**< Encoder complexity, 0-10(max). */ + pj_bool_t cbr; /**< Constant bit rate? */ } setting; } pjmedia_codec_param; @@ -315,14 +314,14 @@ typedef struct pjmedia_codec_param /** * Duplicate codec parameter. * - * @param pool The pool. - * @param src The codec parameter to be duplicated. + * @param pool The pool. + * @param src The codec parameter to be duplicated. * - * @return Duplicated codec parameter. + * @return Duplicated codec parameter. */ PJ_DECL(pjmedia_codec_param*) pjmedia_codec_param_clone( - pj_pool_t *pool, - const pjmedia_codec_param *src); + pj_pool_t *pool, + const pjmedia_codec_param *src); /* @@ -343,14 +342,14 @@ typedef struct pjmedia_codec_op * Application should call #pjmedia_codec_init() instead of * calling this function directly. * - * @param codec The codec instance. - * @param pool Pool to use when the codec needs to allocate - * some memory. + * @param codec The codec instance. + * @param pool Pool to use when the codec needs to allocate + * some memory. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ - pj_status_t (*init)(pjmedia_codec *codec, - pj_pool_t *pool ); + pj_status_t (*init)(pjmedia_codec *codec, + pj_pool_t *pool ); /** * Open the codec and initialize with the specified parameter. @@ -361,13 +360,13 @@ typedef struct pjmedia_codec_op * Application should call #pjmedia_codec_open() instead of * calling this function directly. * - * @param codec The codec instance. - * @param param Codec initialization parameter. + * @param codec The codec instance. + * @param param Codec initialization parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ - pj_status_t (*open)(pjmedia_codec *codec, - pjmedia_codec_param *param ); + pj_status_t (*open)(pjmedia_codec *codec, + pjmedia_codec_param *param ); /** * Close and shutdown codec, releasing all resources allocated by @@ -376,9 +375,9 @@ typedef struct pjmedia_codec_op * Application should call #pjmedia_codec_close() instead of * calling this function directly. * - * @param codec The codec instance. + * @param codec The codec instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ pj_status_t (*close)(pjmedia_codec *codec); @@ -392,13 +391,13 @@ typedef struct pjmedia_codec_op * Application should call #pjmedia_codec_modify() instead of * calling this function directly. * - * @param codec The codec instance. - * @param param The new codec parameter. + * @param codec The codec instance. + * @param param The new codec parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ - pj_status_t (*modify)(pjmedia_codec *codec, - const pjmedia_codec_param *param ); + pj_status_t (*modify)(pjmedia_codec *codec, + const pjmedia_codec_param *param ); /** * Instruct the codec to inspect the specified payload/packet and @@ -409,24 +408,24 @@ typedef struct pjmedia_codec_op * Application should call #pjmedia_codec_parse() instead of * calling this function directly. * - * @param codec The codec instance - * @param pkt The input packet. - * @param pkt_size Size of the packet. - * @param timestamp The timestamp of the first sample in the packet. - * @param frame_cnt On input, specifies the maximum number of frames - * in the array. On output, the codec must fill - * with number of frames detected in the packet. - * @param frames On output, specifies the frames that have been - * detected in the packet. + * @param codec The codec instance + * @param pkt The input packet. + * @param pkt_size Size of the packet. + * @param timestamp The timestamp of the first sample in the packet. + * @param frame_cnt On input, specifies the maximum number of frames + * in the array. On output, the codec must fill + * with number of frames detected in the packet. + * @param frames On output, specifies the frames that have been + * detected in the packet. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ pj_status_t (*parse)( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *timestamp, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *timestamp, + unsigned *frame_cnt, + pjmedia_frame frames[]); /** * Instruct the codec to encode the specified input frame. The input @@ -436,17 +435,17 @@ typedef struct pjmedia_codec_op * Application should call #pjmedia_codec_encode() instead of * calling this function directly. * - * @param codec The codec instance. - * @param input The input frame. - * @param out_size The length of buffer in the output frame. - * @param output The output frame. + * @param codec The codec instance. + * @param input The input frame. + * @param out_size The length of buffer in the output frame. + * @param output The output frame. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ pj_status_t (*encode)(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned out_size, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned out_size, + struct pjmedia_frame *output); /** * Instruct the codec to decode the specified input frame. The input @@ -458,17 +457,17 @@ typedef struct pjmedia_codec_op * Application should call #pjmedia_codec_decode() instead of * calling this function directly. * - * @param codec The codec instance. - * @param input The input frame. - * @param out_size The length of buffer in the output frame. - * @param output The output frame. + * @param codec The codec instance. + * @param input The input frame. + * @param out_size The length of buffer in the output frame. + * @param output The output frame. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ pj_status_t (*decode)(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned out_size, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned out_size, + struct pjmedia_frame *output); /** * Instruct the codec to recover a missing frame. @@ -476,16 +475,16 @@ typedef struct pjmedia_codec_op * Application should call #pjmedia_codec_recover() instead of * calling this function directly. * - * @param codec The codec instance. - * @param out_size The length of buffer in the output frame. - * @param output The output frame where generated signal - * will be placed. + * @param codec The codec instance. + * @param out_size The length of buffer in the output frame. + * @param output The output frame where generated signal + * will be placed. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ pj_status_t (*recover)(pjmedia_codec *codec, - unsigned out_size, - struct pjmedia_frame *output); + unsigned out_size, + struct pjmedia_frame *output); } pjmedia_codec_op; @@ -505,13 +504,13 @@ struct pjmedia_codec PJ_DECL_LIST_MEMBER(struct pjmedia_codec); /** Codec's private data. */ - void *codec_data; + void *codec_data; /** Codec factory where this codec was allocated. */ pjmedia_codec_factory *factory; /** Operations to codec. */ - pjmedia_codec_op *op; + pjmedia_codec_op *op; }; @@ -526,70 +525,70 @@ typedef struct pjmedia_codec_factory_op * Check whether the factory can create codec with the specified * codec info. * - * @param factory The codec factory. - * @param info The codec info. + * @param factory The codec factory. + * @param info The codec info. * - * @return PJ_SUCCESS if this factory is able to create an - * instance of codec with the specified info. + * @return PJ_SUCCESS if this factory is able to create an + * instance of codec with the specified info. */ - pj_status_t (*test_alloc)(pjmedia_codec_factory *factory, - const pjmedia_codec_info *info ); + pj_status_t (*test_alloc)(pjmedia_codec_factory *factory, + const pjmedia_codec_info *info ); /** * Create default attributes for the specified codec ID. This function * can be called by application to get the capability of the codec. * - * @param factory The codec factory. - * @param info The codec info. - * @param attr The attribute to be initialized. + * @param factory The codec factory. + * @param info The codec info. + * @param attr The attribute to be initialized. * - * @return PJ_SUCCESS if success. + * @return PJ_SUCCESS if success. */ pj_status_t (*default_attr)(pjmedia_codec_factory *factory, - const pjmedia_codec_info *info, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *info, + pjmedia_codec_param *attr ); /** * Enumerate supported codecs that can be created using this factory. * - * @param factory The codec factory. - * @param count On input, specifies the number of elements in - * the array. On output, the value will be set to - * the number of elements that have been initialized - * by this function. - * @param info The codec info array, which contents will be - * initialized upon return. + * @param factory The codec factory. + * @param count On input, specifies the number of elements in + * the array. On output, the value will be set to + * the number of elements that have been initialized + * by this function. + * @param info The codec info array, which contents will be + * initialized upon return. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ pj_status_t (*enum_info)(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); /** * Create one instance of the codec with the specified codec info. * - * @param factory The codec factory. - * @param info The codec info. - * @param p_codec Pointer to receive the codec instance. + * @param factory The codec factory. + * @param info The codec info. + * @param p_codec Pointer to receive the codec instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ pj_status_t (*alloc_codec)(pjmedia_codec_factory *factory, - const pjmedia_codec_info *info, - pjmedia_codec **p_codec); + const pjmedia_codec_info *info, + pjmedia_codec **p_codec); /** * This function is called by codec manager to return a particular * instance of codec back to the codec factory. * - * @param factory The codec factory. - * @param codec The codec instance to be returned. + * @param factory The codec factory. + * @param codec The codec instance to be returned. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ pj_status_t (*dealloc_codec)(pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /** * This callback will be called to deinitialize and destroy this factory. @@ -611,7 +610,7 @@ struct pjmedia_codec_factory PJ_DECL_LIST_MEMBER(struct pjmedia_codec_factory); /** The factory's private data. */ - void *factory_data; + void *factory_data; /** Operations to the factory. */ pjmedia_codec_factory_op *op; @@ -622,7 +621,7 @@ struct pjmedia_codec_factory /** * Declare maximum codecs */ -#define PJMEDIA_CODEC_MGR_MAX_CODECS 32 +#define PJMEDIA_CODEC_MGR_MAX_CODECS 32 /** @@ -688,12 +687,12 @@ typedef struct pjmedia_codec_default_param pjmedia_codec_default_param; */ struct pjmedia_codec_desc { - pjmedia_codec_info info; /**< Codec info. */ - pjmedia_codec_id id; /**< Fully qualified name */ - pjmedia_codec_priority prio; /**< Priority. */ - pjmedia_codec_factory *factory; /**< The factory. */ + pjmedia_codec_info info; /**< Codec info. */ + pjmedia_codec_id id; /**< Fully qualified name */ + pjmedia_codec_priority prio; /**< Priority. */ + pjmedia_codec_factory *factory; /**< The factory. */ pjmedia_codec_default_param *param; /**< Default codecs - parameters. */ + parameters. */ }; @@ -705,22 +704,22 @@ struct pjmedia_codec_desc typedef struct pjmedia_codec_mgr { /** Media endpoint instance. */ - pj_pool_factory *pf; + pj_pool_factory *pf; /** Codec manager pool. */ - pj_pool_t *pool; + pj_pool_t *pool; /** Codec manager mutex. */ - pj_mutex_t *mutex; + pj_mutex_t *mutex; /** List of codec factories registered to codec manager. */ - pjmedia_codec_factory factory_list; + pjmedia_codec_factory factory_list; /** Number of supported codecs. */ - unsigned codec_cnt; + unsigned codec_cnt; /** Array of codec descriptor. */ - struct pjmedia_codec_desc codec_desc[PJMEDIA_CODEC_MGR_MAX_CODECS]; + struct pjmedia_codec_desc codec_desc[PJMEDIA_CODEC_MGR_MAX_CODECS]; } pjmedia_codec_mgr; @@ -730,22 +729,22 @@ typedef struct pjmedia_codec_mgr * Initialize codec manager. Normally this function is called by pjmedia * endpoint's initialization code. * - * @param mgr Codec manager instance. - * @param pf Pool factory instance. + * @param mgr Codec manager instance. + * @param pf Pool factory instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_mgr_init(pjmedia_codec_mgr *mgr, - pj_pool_factory *pf); + pj_pool_factory *pf); /** * Destroy codec manager. Normally this function is called by pjmedia * endpoint's deinitialization code. * - * @param mgr Codec manager instance. + * @param mgr Codec manager instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_mgr_destroy(pjmedia_codec_mgr *mgr); @@ -754,15 +753,15 @@ PJ_DECL(pj_status_t) pjmedia_codec_mgr_destroy(pjmedia_codec_mgr *mgr); * Register codec factory to codec manager. This will also register * all supported codecs in the factory to the codec manager. * - * @param mgr The codec manager instance. Application can get the - * instance by calling #pjmedia_endpt_get_codec_mgr(). + * @param mgr The codec manager instance. Application can get the + * instance by calling #pjmedia_endpt_get_codec_mgr(). * @param factory The codec factory to be registered. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_mgr_register_factory( pjmedia_codec_mgr *mgr, - pjmedia_codec_factory *factory); + pjmedia_codec_factory *factory); /** * Unregister codec factory from the codec manager. This will also @@ -770,36 +769,36 @@ pjmedia_codec_mgr_register_factory( pjmedia_codec_mgr *mgr, * codec manager's list of supported codecs. This function should * only be called by the codec implementers and not by application. * - * @param mgr The codec manager instance, use - * #pjmedia_endpt_get_codec_mgr(). + * @param mgr The codec manager instance, use + * #pjmedia_endpt_get_codec_mgr(). * @param factory The codec factory to be unregistered. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_mgr_unregister_factory( pjmedia_codec_mgr *mgr, - pjmedia_codec_factory *factory); + pjmedia_codec_factory *factory); /** * Enumerate all supported codecs that have been registered to the * codec manager by codec factories. * - * @param mgr The codec manager instance. Application can get the - * instance by calling #pjmedia_endpt_get_codec_mgr(). - * @param count On input, specifies the number of elements in - * the array. On output, the value will be set to - * the number of elements that have been initialized - * by this function. - * @param info The codec info array, which contents will be - * initialized upon return. - * @param prio Optional pointer to receive array of codec priorities. - * - * @return PJ_SUCCESS on success. + * @param mgr The codec manager instance. Application can get the + * instance by calling #pjmedia_endpt_get_codec_mgr(). + * @param count On input, specifies the number of elements in + * the array. On output, the value will be set to + * the number of elements that have been initialized + * by this function. + * @param info The codec info array, which contents will be + * initialized upon return. + * @param prio Optional pointer to receive array of codec priorities. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_mgr_enum_codecs( pjmedia_codec_mgr *mgr, - unsigned *count, - pjmedia_codec_info info[], - unsigned *prio); + unsigned *count, + pjmedia_codec_info info[], + unsigned *prio); /** * Get codec info for the specified static payload type. Note that @@ -807,31 +806,31 @@ PJ_DECL(pj_status_t) pjmedia_codec_mgr_enum_codecs( pjmedia_codec_mgr *mgr, * be used to find codec info for a payload type inside SDP which doesn't * have the corresponding rtpmap attribute. * - * @param mgr The codec manager instance. Application can get the - * instance by calling #pjmedia_endpt_get_codec_mgr(). - * @param pt Static payload type/number. - * @param inf Pointer to receive codec info. + * @param mgr The codec manager instance. Application can get the + * instance by calling #pjmedia_endpt_get_codec_mgr(). + * @param pt Static payload type/number. + * @param inf Pointer to receive codec info. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_mgr_get_codec_info( pjmedia_codec_mgr *mgr, - unsigned pt, - const pjmedia_codec_info **inf); + unsigned pt, + const pjmedia_codec_info **inf); /** * Convert codec info struct into a unique codec identifier. * A codec identifier looks something like "L16/44100/2". * - * @param info The codec info - * @param id Buffer to put the codec info string. + * @param info The codec info + * @param id Buffer to put the codec info string. * @param max_len The length of the buffer. * - * @return The null terminated codec info string, or NULL if - * the buffer is not long enough. + * @return The null terminated codec info string, or NULL if + * the buffer is not long enough. */ PJ_DECL(char*) pjmedia_codec_info_to_id(const pjmedia_codec_info *info, - char *id, unsigned max_len ); + char *id, unsigned max_len ); /** @@ -840,25 +839,25 @@ PJ_DECL(char*) pjmedia_codec_info_to_id(const pjmedia_codec_info *info, * "L16" is specified, then it will find "L16/8000/1", "L16/16000/1", * and so on, up to the maximum count specified in the argument. * - * @param mgr The codec manager instance. Application can get the - * instance by calling #pjmedia_endpt_get_codec_mgr(). + * @param mgr The codec manager instance. Application can get the + * instance by calling #pjmedia_endpt_get_codec_mgr(). * @param codec_id The full codec ID or codec ID prefix. If an empty - * string is given, it will match all codecs. - * @param count Maximum number of codecs to find. On return, it - * contains the actual number of codecs found. + * string is given, it will match all codecs. + * @param count Maximum number of codecs to find. On return, it + * contains the actual number of codecs found. * @param p_info Array of pointer to codec info to be filled. This - * argument may be NULL, which in this case, only - * codec count will be returned. - * @param prio Optional array of codec priorities. + * argument may be NULL, which in this case, only + * codec count will be returned. + * @param prio Optional array of codec priorities. * - * @return PJ_SUCCESS if at least one codec info is found. + * @return PJ_SUCCESS if at least one codec info is found. */ PJ_DECL(pj_status_t) pjmedia_codec_mgr_find_codecs_by_id( pjmedia_codec_mgr *mgr, - const pj_str_t *codec_id, - unsigned *count, - const pjmedia_codec_info *p_info[], - unsigned prio[]); + const pj_str_t *codec_id, + unsigned *count, + const pjmedia_codec_info *p_info[], + unsigned prio[]); /** @@ -867,56 +866,56 @@ pjmedia_codec_mgr_find_codecs_by_id( pjmedia_codec_mgr *mgr, * are found with the same codec_id prefix, then the function sets the * priorities of all those codecs. * - * @param mgr The codec manager instance. Application can get the - * instance by calling #pjmedia_endpt_get_codec_mgr(). + * @param mgr The codec manager instance. Application can get the + * instance by calling #pjmedia_endpt_get_codec_mgr(). * @param codec_id The full codec ID or codec ID prefix. If an empty - * string is given, it will match all codecs. - * @param prio Priority to be set. The priority can have any value - * between 1 to 255. When the priority is set to zero, - * the codec will be disabled. + * string is given, it will match all codecs. + * @param prio Priority to be set. The priority can have any value + * between 1 to 255. When the priority is set to zero, + * the codec will be disabled. * - * @return PJ_SUCCESS if at least one codec info is found. + * @return PJ_SUCCESS if at least one codec info is found. */ PJ_DECL(pj_status_t) pjmedia_codec_mgr_set_codec_priority(pjmedia_codec_mgr *mgr, - const pj_str_t *codec_id, - pj_uint8_t prio); + const pj_str_t *codec_id, + pj_uint8_t prio); /** * Get default codec param for the specified codec info. * - * @param mgr The codec manager instance. Application can get the - * instance by calling #pjmedia_endpt_get_codec_mgr(). - * @param info The codec info, which default parameter's is being - * queried. - * @param param On return, will be filled with the default codec - * parameter. + * @param mgr The codec manager instance. Application can get the + * instance by calling #pjmedia_endpt_get_codec_mgr(). + * @param info The codec info, which default parameter's is being + * queried. + * @param param On return, will be filled with the default codec + * parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_mgr_get_default_param( pjmedia_codec_mgr *mgr, - const pjmedia_codec_info *info, - pjmedia_codec_param *param ); + const pjmedia_codec_info *info, + pjmedia_codec_param *param ); /** * Set default codec param for the specified codec info. * - * @param mgr The codec manager instance. Application can get the - * instance by calling #pjmedia_endpt_get_codec_mgr(). - * @param info The codec info, which default parameter's is being - * updated. - * @param param The new default codec parameter. Set to NULL to reset - * codec parameter to library default settings. + * @param mgr The codec manager instance. Application can get the + * instance by calling #pjmedia_endpt_get_codec_mgr(). + * @param info The codec info, which default parameter's is being + * updated. + * @param param The new default codec parameter. Set to NULL to reset + * codec parameter to library default settings. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_mgr_set_default_param( pjmedia_codec_mgr *mgr, - const pjmedia_codec_info *info, - const pjmedia_codec_param *param ); + const pjmedia_codec_info *info, + const pjmedia_codec_param *param ); /** @@ -924,43 +923,43 @@ pjmedia_codec_mgr_set_default_param( pjmedia_codec_mgr *mgr, * specified codec info. The codec will enumerate all codec factories * until it finds factory that is able to create the specified codec. * - * @param mgr The codec manager instance. Application can get the - * instance by calling #pjmedia_endpt_get_codec_mgr(). - * @param info The information about the codec to be created. + * @param mgr The codec manager instance. Application can get the + * instance by calling #pjmedia_endpt_get_codec_mgr(). + * @param info The information about the codec to be created. * @param p_codec Pointer to receive the codec instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_mgr_alloc_codec( pjmedia_codec_mgr *mgr, - const pjmedia_codec_info *info, - pjmedia_codec **p_codec); + const pjmedia_codec_info *info, + pjmedia_codec **p_codec); /** * Deallocate the specified codec instance. The codec manager will return * the instance of the codec back to its factory. * - * @param mgr The codec manager instance. Application can get the - * instance by calling #pjmedia_endpt_get_codec_mgr(). - * @param codec The codec instance. + * @param mgr The codec manager instance. Application can get the + * instance by calling #pjmedia_endpt_get_codec_mgr(). + * @param codec The codec instance. * - * @return PJ_SUCESS on success. + * @return PJ_SUCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_mgr_dealloc_codec(pjmedia_codec_mgr *mgr, - pjmedia_codec *codec); + pjmedia_codec *codec); /** * Initialize codec using the specified attribute. * - * @param codec The codec instance. - * @param pool Pool to use when the codec needs to allocate some memory. + * @param codec The codec instance. + * @param pool Pool to use when the codec needs to allocate some memory. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_codec_init( pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { return (*codec->op->init)(codec, pool); } @@ -972,13 +971,13 @@ PJ_INLINE(pj_status_t) pjmedia_codec_init( pjmedia_codec *codec, * and fills in the unspecified values (such as enc_ptime, when * encoder ptime is different than decoder ptime). * - * @param codec The codec instance. - * @param param Codec initialization parameter. + * @param codec The codec instance. + * @param param Codec initialization parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_codec_open( pjmedia_codec *codec, - pjmedia_codec_param *param ) + pjmedia_codec_param *param ) { return (*codec->op->open)(codec, param); } @@ -988,9 +987,9 @@ PJ_INLINE(pj_status_t) pjmedia_codec_open( pjmedia_codec *codec, * Close and shutdown codec, releasing all resources allocated by * this codec, if any. * - * @param codec The codec instance. + * @param codec The codec instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_codec_close( pjmedia_codec *codec ) { @@ -1005,13 +1004,13 @@ PJ_INLINE(pj_status_t) pjmedia_codec_close( pjmedia_codec *codec ) * such as bitrate and bandwidth, while other codecs may only be able to * modify minor settings such as VAD or PLC. * - * @param codec The codec instance. - * @param param The new codec parameter. + * @param codec The codec instance. + * @param param The new codec parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *param) + const pjmedia_codec_param *param) { return (*codec->op->modify)(codec, param); } @@ -1023,27 +1022,27 @@ PJ_INLINE(pj_status_t) pjmedia_codec_modify(pjmedia_codec *codec, * have ptime that is equal to basic frame ptime (i.e. the value of * info.frm_ptime in #pjmedia_codec_param). * - * @param codec The codec instance - * @param pkt The input packet. + * @param codec The codec instance + * @param pkt The input packet. * @param pkt_size Size of the packet. * @param timestamp The timestamp of the first sample in the packet. * @param frame_cnt On input, specifies the maximum number of frames - * in the array. On output, the codec must fill - * with number of frames detected in the packet. + * in the array. On output, the codec must fill + * with number of frames detected in the packet. * @param frames On output, specifies the frames that have been - * detected in the packet. + * detected in the packet. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *timestamp, - unsigned *frame_cnt, - pjmedia_frame frames[] ) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *timestamp, + unsigned *frame_cnt, + pjmedia_frame frames[] ) { return (*codec->op->parse)(codec, pkt, pkt_size, timestamp, - frame_cnt, frames); + frame_cnt, frames); } @@ -1052,18 +1051,18 @@ PJ_INLINE(pj_status_t) pjmedia_codec_parse( pjmedia_codec *codec, * PCM samples MUST have ptime that is multiplication of base frame * ptime (i.e. the value of info.frm_ptime in #pjmedia_codec_param). * - * @param codec The codec instance. - * @param input The input frame. - * @param out_size The length of buffer in the output frame. - * @param output The output frame. + * @param codec The codec instance. + * @param input The input frame. + * @param out_size The length of buffer in the output frame. + * @param output The output frame. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ PJ_INLINE(pj_status_t) pjmedia_codec_encode( - pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned out_size, - struct pjmedia_frame *output ) + pjmedia_codec *codec, + const struct pjmedia_frame *input, + unsigned out_size, + struct pjmedia_frame *output ) { return (*codec->op->encode)(codec, input, out_size, output); } @@ -1076,18 +1075,18 @@ PJ_INLINE(pj_status_t) pjmedia_codec_encode( * Application can achieve this by parsing the packet into base * frames before decoding each frame. * - * @param codec The codec instance. - * @param input The input frame. - * @param out_size The length of buffer in the output frame. - * @param output The output frame. + * @param codec The codec instance. + * @param input The input frame. + * @param out_size The length of buffer in the output frame. + * @param output The output frame. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ PJ_INLINE(pj_status_t) pjmedia_codec_decode( - pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned out_size, - struct pjmedia_frame *output ) + pjmedia_codec *codec, + const struct pjmedia_frame *input, + unsigned out_size, + struct pjmedia_frame *output ) { return (*codec->op->decode)(codec, input, out_size, output); } @@ -1096,21 +1095,21 @@ PJ_INLINE(pj_status_t) pjmedia_codec_decode( /** * Instruct the codec to recover a missing frame. * - * @param codec The codec instance. - * @param out_size The length of buffer in the output frame. - * @param output The output frame where generated signal - * will be placed. + * @param codec The codec instance. + * @param out_size The length of buffer in the output frame. + * @param output The output frame where generated signal + * will be placed. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ PJ_INLINE(pj_status_t) pjmedia_codec_recover( pjmedia_codec *codec, - unsigned out_size, - struct pjmedia_frame *output ) + unsigned out_size, + struct pjmedia_frame *output ) { if (codec->op && codec->op->recover) - return (*codec->op->recover)(codec, out_size, output); + return (*codec->op->recover)(codec, out_size, output); else - return PJ_ENOTSUP; + return PJ_ENOTSUP; } @@ -1135,4 +1134,4 @@ PJ_INLINE(pj_status_t) pjmedia_codec_recover( pjmedia_codec *codec, PJ_END_DECL -#endif /* __PJMEDIA_CODEC_H__ */ +#endif /* __PJMEDIA_CODEC_H__ */ diff --git a/pjmedia/include/pjmedia/conference.h b/pjmedia/include/pjmedia/conference.h index 605d9038b0..9c1b4b4535 100644 --- a/pjmedia/include/pjmedia/conference.h +++ b/pjmedia/include/pjmedia/conference.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -48,18 +47,18 @@ PJ_BEGIN_DECL * See also https://github.com/pjsip/pjproject/issues/2234. */ #ifndef DEPRECATED_FOR_TICKET_2234 -# define DEPRECATED_FOR_TICKET_2234 1 +# define DEPRECATED_FOR_TICKET_2234 1 #endif /** * The conference bridge signature in pjmedia_port_info. */ -#define PJMEDIA_CONF_BRIDGE_SIGNATURE PJMEDIA_SIG_PORT_CONF +#define PJMEDIA_CONF_BRIDGE_SIGNATURE PJMEDIA_SIG_PORT_CONF /** * The audio switchboard signature in pjmedia_port_info. */ -#define PJMEDIA_CONF_SWITCH_SIGNATURE PJMEDIA_SIG_PORT_CONF_SWITCH +#define PJMEDIA_CONF_SWITCH_SIGNATURE PJMEDIA_SIG_PORT_CONF_SWITCH /** @@ -72,22 +71,22 @@ typedef struct pjmedia_conf pjmedia_conf; */ typedef struct pjmedia_conf_port_info { - unsigned slot; /**< Slot number. */ - pj_str_t name; /**< Port name. */ - pjmedia_format format; /**< Format. */ - pjmedia_port_op tx_setting; /**< Transmit settings. */ - pjmedia_port_op rx_setting; /**< Receive settings. */ - unsigned listener_cnt; /**< Number of listeners. */ - unsigned *listener_slots; /**< Array of listeners. */ - unsigned *listener_adj_level; /**< Array of listeners' level - adjustment */ - unsigned transmitter_cnt; /**< Number of transmitter. */ - unsigned clock_rate; /**< Clock rate of the port. */ - unsigned channel_count; /**< Number of channels. */ - unsigned samples_per_frame; /**< Samples per frame */ - unsigned bits_per_sample; /**< Bits per sample. */ - int tx_adj_level; /**< Tx level adjustment. */ - int rx_adj_level; /**< Rx level adjustment. */ + unsigned slot; /**< Slot number. */ + pj_str_t name; /**< Port name. */ + pjmedia_format format; /**< Format. */ + pjmedia_port_op tx_setting; /**< Transmit settings. */ + pjmedia_port_op rx_setting; /**< Receive settings. */ + unsigned listener_cnt; /**< Number of listeners. */ + unsigned *listener_slots; /**< Array of listeners. */ + unsigned *listener_adj_level; /**< Array of listeners' level + adjustment */ + unsigned transmitter_cnt; /**< Number of transmitter. */ + unsigned clock_rate; /**< Clock rate of the port. */ + unsigned channel_count; /**< Number of channels. */ + unsigned samples_per_frame; /**< Samples per frame */ + unsigned bits_per_sample; /**< Bits per sample. */ + int tx_adj_level; /**< Tx level adjustment. */ + int rx_adj_level; /**< Rx level adjustment. */ } pjmedia_conf_port_info; @@ -97,12 +96,12 @@ typedef struct pjmedia_conf_port_info */ enum pjmedia_conf_option { - PJMEDIA_CONF_NO_MIC = 1, /**< Disable audio streams from the - microphone device. */ - PJMEDIA_CONF_NO_DEVICE = 2, /**< Do not create sound device. */ + PJMEDIA_CONF_NO_MIC = 1, /**< Disable audio streams from the + microphone device. */ + PJMEDIA_CONF_NO_DEVICE = 2, /**< Do not create sound device. */ PJMEDIA_CONF_SMALL_FILTER=4,/**< Use small filter table when resampling */ - PJMEDIA_CONF_USE_LINEAR=8 /**< Use linear resampling instead of filter - based. */ + PJMEDIA_CONF_USE_LINEAR=8 /**< Use linear resampling instead of filter + based. */ }; @@ -135,49 +134,49 @@ enum pjmedia_conf_option * frames periodically. Internally, the bridge runs when get_frame() to * port zero is called. * - * @param pool Pool to use to allocate the bridge and - * additional buffers for the sound device. - * @param max_slots Maximum number of slots/ports to be created in - * the bridge. Note that the bridge internally uses - * one port for the sound device, so the actual - * maximum number of ports will be less one than - * this value. - * @param sampling_rate Set the sampling rate of the bridge. This value - * is also used to set the sampling rate of the - * sound device. - * @param channel_count Number of channels in the PCM stream. Normally - * the value will be 1 for mono, but application may - * specify a value of 2 for stereo. Note that all - * ports that will be connected to the bridge MUST - * have the same number of channels as the bridge. + * @param pool Pool to use to allocate the bridge and + * additional buffers for the sound device. + * @param max_slots Maximum number of slots/ports to be created in + * the bridge. Note that the bridge internally uses + * one port for the sound device, so the actual + * maximum number of ports will be less one than + * this value. + * @param sampling_rate Set the sampling rate of the bridge. This value + * is also used to set the sampling rate of the + * sound device. + * @param channel_count Number of channels in the PCM stream. Normally + * the value will be 1 for mono, but application may + * specify a value of 2 for stereo. Note that all + * ports that will be connected to the bridge MUST + * have the same number of channels as the bridge. * @param samples_per_frame Set the number of samples per frame. This value - * is also used to set the sound device. + * is also used to set the sound device. * @param bits_per_sample Set the number of bits per sample. This value - * is also used to set the sound device. Currently - * only 16bit per sample is supported. - * @param options Bitmask options to be set for the bridge. The - * options are constructed from #pjmedia_conf_option - * enumeration. - * @param p_conf Pointer to receive the conference bridge instance. - * - * @return PJ_SUCCESS if conference bridge can be created. + * is also used to set the sound device. Currently + * only 16bit per sample is supported. + * @param options Bitmask options to be set for the bridge. The + * options are constructed from #pjmedia_conf_option + * enumeration. + * @param p_conf Pointer to receive the conference bridge instance. + * + * @return PJ_SUCCESS if conference bridge can be created. */ PJ_DECL(pj_status_t) pjmedia_conf_create( pj_pool_t *pool, - unsigned max_slots, - unsigned sampling_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_conf **p_conf ); + unsigned max_slots, + unsigned sampling_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_conf **p_conf ); /** * Destroy conference bridge. * - * @param conf The conference bridge. + * @param conf The conference bridge. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_destroy( pjmedia_conf *conf ); @@ -194,11 +193,11 @@ PJ_DECL(pj_status_t) pjmedia_conf_destroy( pjmedia_conf *conf ); * Application can connect the port returned by this function to a * sound device by calling #pjmedia_snd_port_connect(). * - * @param conf The conference bridge. + * @param conf The conference bridge. * - * @return The port interface of port zero of the bridge, - * only when PJMEDIA_CONF_NO_DEVICE options was - * specified when the bridge was created. + * @return The port interface of port zero of the bridge, + * only when PJMEDIA_CONF_NO_DEVICE options was + * specified when the bridge was created. */ PJ_DECL(pjmedia_port*) pjmedia_conf_get_master_port(pjmedia_conf *conf); @@ -206,13 +205,13 @@ PJ_DECL(pjmedia_port*) pjmedia_conf_get_master_port(pjmedia_conf *conf); /** * Set master port name. * - * @param conf The conference bridge. - * @param name Name to be assigned. + * @param conf The conference bridge. + * @param name Name to be assigned. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_set_port0_name(pjmedia_conf *conf, - const pj_str_t *name); + const pj_str_t *name); /** @@ -227,22 +226,22 @@ PJ_DECL(pj_status_t) pjmedia_conf_set_port0_name(pjmedia_conf *conf, * the bridge will continuosly call get_frame() and put_frame() to the * port, allowing media to flow to/from the port. * - * @param conf The conference bridge. - * @param pool Pool to allocate buffers for this port. - * @param strm_port Stream port interface. - * @param name Optional name for the port. If this value is NULL, - * the name will be taken from the name in the port - * info. - * @param p_slot Pointer to receive the slot index of the port in - * the conference bridge. + * @param conf The conference bridge. + * @param pool Pool to allocate buffers for this port. + * @param strm_port Stream port interface. + * @param name Optional name for the port. If this value is NULL, + * the name will be taken from the name in the port + * info. + * @param p_slot Pointer to receive the slot index of the port in + * the conference bridge. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, - pj_pool_t *pool, - pjmedia_port *strm_port, - const pj_str_t *name, - unsigned *p_slot ); + pj_pool_t *pool, + pjmedia_port *strm_port, + const pj_str_t *name, + unsigned *p_slot ); #if !DEPRECATED_FOR_TICKET_2234 @@ -262,48 +261,48 @@ PJ_DECL(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, * port where application MUST start calling get_frame() and put_frame() * to the port. * - * @param conf The conference bridge. - * @param pool Pool to allocate buffers etc for this port. - * @param name Name to be assigned to the port. - * @param clock_rate Clock rate/sampling rate. - * @param channel_count Number of channels. + * @param conf The conference bridge. + * @param pool Pool to allocate buffers etc for this port. + * @param name Name to be assigned to the port. + * @param clock_rate Clock rate/sampling rate. + * @param channel_count Number of channels. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Number of bits per sample. - * @param options Options (should be zero at the moment). - * @param p_slot Pointer to receive the slot index of the port in - * the conference bridge. - * @param p_port Pointer to receive the port instance. + * @param options Options (should be zero at the moment). + * @param p_slot Pointer to receive the slot index of the port in + * the conference bridge. + * @param p_port Pointer to receive the port instance. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_conf_add_passive_port( pjmedia_conf *conf, - pj_pool_t *pool, - const pj_str_t *name, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - unsigned *p_slot, - pjmedia_port **p_port ); + pj_pool_t *pool, + const pj_str_t *name, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + unsigned *p_slot, + pjmedia_port **p_port ); #endif /** * Change TX and RX settings for the port. * - * @param conf The conference bridge. - * @param slot Port number/slot in the conference bridge. - * @param tx Settings for the transmission TO this port. - * @param rx Settings for the receipt FROM this port. + * @param conf The conference bridge. + * @param slot Port number/slot in the conference bridge. + * @param tx Settings for the transmission TO this port. + * @param rx Settings for the receipt FROM this port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_configure_port( pjmedia_conf *conf, - unsigned slot, - pjmedia_port_op tx, - pjmedia_port_op rx); + unsigned slot, + pjmedia_port_op tx, + pjmedia_port_op rx); /** @@ -327,72 +326,72 @@ PJ_DECL(pj_status_t) pjmedia_conf_configure_port( pjmedia_conf *conf, * via this API, and finally with the level specified to the sink's * pjmedia_conf_adjust_tx_level(). * - * @param conf The conference bridge. - * @param src_slot Source slot. - * @param sink_slot Sink slot. - * @param adj_level Adjustment level, which must be greater than or equal - * to -128. A value of zero means there is no level - * adjustment to be made, the value -128 will mute the - * signal, and the value of +128 will make the signal - * 100% louder, +256 will make it 200% louder, etc. - * See the function description for the formula. - * - * @return PJ_SUCCES on success. + * @param conf The conference bridge. + * @param src_slot Source slot. + * @param sink_slot Sink slot. + * @param adj_level Adjustment level, which must be greater than or equal + * to -128. A value of zero means there is no level + * adjustment to be made, the value -128 will mute the + * signal, and the value of +128 will make the signal + * 100% louder, +256 will make it 200% louder, etc. + * See the function description for the formula. + * + * @return PJ_SUCCES on success. */ PJ_DECL(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, - unsigned src_slot, - unsigned sink_slot, - int adj_level ); + unsigned src_slot, + unsigned sink_slot, + int adj_level ); /** * Disconnect unidirectional audio from the specified source to the specified * sink slot. * - * @param conf The conference bridge. - * @param src_slot Source slot. - * @param sink_slot Sink slot. + * @param conf The conference bridge. + * @param src_slot Source slot. + * @param sink_slot Sink slot. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_disconnect_port( pjmedia_conf *conf, - unsigned src_slot, - unsigned sink_slot ); + unsigned src_slot, + unsigned sink_slot ); /** * Disconnect unidirectional audio from all sources to the specified sink slot. * - * @param conf The conference bridge. - * @param sink_slot Sink slot. + * @param conf The conference bridge. + * @param sink_slot Sink slot. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_disconnect_port_from_sources( pjmedia_conf *conf, - unsigned sink_slot); + unsigned sink_slot); /** * Disconnect unidirectional audio from the specified source to all sink slots. * - * @param conf The conference bridge. - * @param src_slot Source slot. + * @param conf The conference bridge. + * @param src_slot Source slot. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_disconnect_port_from_sinks( pjmedia_conf *conf, - unsigned src_slot); + unsigned src_slot); /** * Get number of ports currently registered to the conference bridge. * - * @param conf The conference bridge. + * @param conf The conference bridge. * - * @return Number of ports currently registered to the conference - * bridge. + * @return Number of ports currently registered to the conference + * bridge. */ PJ_DECL(unsigned) pjmedia_conf_get_port_count(pjmedia_conf *conf); @@ -400,9 +399,9 @@ PJ_DECL(unsigned) pjmedia_conf_get_port_count(pjmedia_conf *conf); /** * Get total number of ports connections currently set up in the bridge. * - * @param conf The conference bridge. + * @param conf The conference bridge. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(unsigned) pjmedia_conf_get_connect_count(pjmedia_conf *conf); @@ -410,61 +409,61 @@ PJ_DECL(unsigned) pjmedia_conf_get_connect_count(pjmedia_conf *conf); /** * Remove the specified port from the conference bridge. * - * @param conf The conference bridge. - * @param slot The port index to be removed. + * @param conf The conference bridge. + * @param slot The port index to be removed. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_remove_port( pjmedia_conf *conf, - unsigned slot ); + unsigned slot ); /** * Enumerate occupied ports in the bridge. * - * @param conf The conference bridge. - * @param ports Array of port numbers to be filled in. - * @param count On input, specifies the maximum number of ports - * in the array. On return, it will be filled with - * the actual number of ports. + * @param conf The conference bridge. + * @param ports Array of port numbers to be filled in. + * @param count On input, specifies the maximum number of ports + * in the array. On return, it will be filled with + * the actual number of ports. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_enum_ports( pjmedia_conf *conf, - unsigned ports[], - unsigned *count ); + unsigned ports[], + unsigned *count ); /** * Get port info. * - * @param conf The conference bridge. - * @param slot Port index. - * @param info Pointer to receive the info. + * @param conf The conference bridge. + * @param slot Port index. + * @param info Pointer to receive the info. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_get_port_info( pjmedia_conf *conf, - unsigned slot, - pjmedia_conf_port_info *info); + unsigned slot, + pjmedia_conf_port_info *info); /** * Get occupied ports info. * - * @param conf The conference bridge. - * @param size On input, contains maximum number of infos - * to be retrieved. On output, contains the actual - * number of infos that have been copied. - * @param info Array of info. + * @param conf The conference bridge. + * @param size On input, contains maximum number of infos + * to be retrieved. On output, contains the actual + * number of infos that have been copied. + * @param info Array of info. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_get_ports_info(pjmedia_conf *conf, - unsigned *size, - pjmedia_conf_port_info info[] - ); + unsigned *size, + pjmedia_conf_port_info info[] + ); /** @@ -476,21 +475,21 @@ PJ_DECL(pj_status_t) pjmedia_conf_get_ports_info(pjmedia_conf *conf, * The signal level is an integer value in zero to 255, with zero indicates * no signal, and 255 indicates the loudest signal level. * - * @param conf The conference bridge. - * @param slot Slot number. - * @param tx_level Optional argument to receive the level of signal - * transmitted to the specified port (i.e. the direction - * is from the bridge to the port). - * @param rx_level Optional argument to receive the level of signal - * received from the port (i.e. the direction is from the - * port to the bridge). + * @param conf The conference bridge. + * @param slot Slot number. + * @param tx_level Optional argument to receive the level of signal + * transmitted to the specified port (i.e. the direction + * is from the bridge to the port). + * @param rx_level Optional argument to receive the level of signal + * received from the port (i.e. the direction is from the + * port to the bridge). * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_get_signal_level(pjmedia_conf *conf, - unsigned slot, - unsigned *tx_level, - unsigned *rx_level); + unsigned slot, + unsigned *tx_level, + unsigned *rx_level); /** @@ -507,20 +506,20 @@ PJ_DECL(pj_status_t) pjmedia_conf_get_signal_level(pjmedia_conf *conf, * level adjustment value is reported in the media port info when * the #pjmedia_conf_get_port_info() function is called. * - * @param conf The conference bridge. - * @param slot Slot number of the port. - * @param adj_level Adjustment level, which must be greater than or equal - * to -128. A value of zero means there is no level - * adjustment to be made, the value -128 will mute the - * signal, and the value of +128 will make the signal - * 100% louder, +256 will make it 200% louder, etc. - * See the function description for the formula. + * @param conf The conference bridge. + * @param slot Slot number of the port. + * @param adj_level Adjustment level, which must be greater than or equal + * to -128. A value of zero means there is no level + * adjustment to be made, the value -128 will mute the + * signal, and the value of +128 will make the signal + * 100% louder, +256 will make it 200% louder, etc. + * See the function description for the formula. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_adjust_rx_level( pjmedia_conf *conf, - unsigned slot, - int adj_level ); + unsigned slot, + int adj_level ); /** @@ -537,20 +536,20 @@ PJ_DECL(pj_status_t) pjmedia_conf_adjust_rx_level( pjmedia_conf *conf, * level adjustment value is reported in the media port info when * the #pjmedia_conf_get_port_info() function is called. * - * @param conf The conference bridge. - * @param slot Slot number of the port. - * @param adj_level Adjustment level, which must be greater than or equal - * to -128. A value of zero means there is no level - * adjustment to be made, the value -128 will mute the - * signal, and the value of +128 will make the signal - * 100% louder, +256 will make it 200% louder, etc. - * See the function description for the formula. + * @param conf The conference bridge. + * @param slot Slot number of the port. + * @param adj_level Adjustment level, which must be greater than or equal + * to -128. A value of zero means there is no level + * adjustment to be made, the value -128 will mute the + * signal, and the value of +128 will make the signal + * 100% louder, +256 will make it 200% louder, etc. + * See the function description for the formula. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_adjust_tx_level( pjmedia_conf *conf, - unsigned slot, - int adj_level ); + unsigned slot, + int adj_level ); /** @@ -569,22 +568,22 @@ PJ_DECL(pj_status_t) pjmedia_conf_adjust_tx_level( pjmedia_conf *conf, * adjustment value is reported in the media port info when the * #pjmedia_conf_get_port_info() function is called. * - * @param conf The conference bridge. - * @param src_slot Source slot. - * @param sink_slot Sink slot. - * @param adj_level Adjustment level, which must be greater than or equal - * to -128. A value of zero means there is no level - * adjustment to be made, the value -128 will mute the - * signal, and the value of +128 will make the signal - * 100% louder, +256 will make it 200% louder, etc. - * See the function description for the formula. - * - * @return PJ_SUCCESS on success. + * @param conf The conference bridge. + * @param src_slot Source slot. + * @param sink_slot Sink slot. + * @param adj_level Adjustment level, which must be greater than or equal + * to -128. A value of zero means there is no level + * adjustment to be made, the value -128 will mute the + * signal, and the value of +128 will make the signal + * 100% louder, +256 will make it 200% louder, etc. + * See the function description for the formula. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_conf_adjust_conn_level( pjmedia_conf *conf, - unsigned src_slot, - unsigned sink_slot, - int adj_level ); + unsigned src_slot, + unsigned sink_slot, + int adj_level ); @@ -596,5 +595,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_CONF_H__ */ +#endif /* __PJMEDIA_CONF_H__ */ diff --git a/pjmedia/include/pjmedia/config.h b/pjmedia/include/pjmedia/config.h index 4269fe1593..c17a62e6ea 100644 --- a/pjmedia/include/pjmedia/config.h +++ b/pjmedia/include/pjmedia/config.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -48,28 +47,28 @@ * Initial memory block for media endpoint. */ #ifndef PJMEDIA_POOL_LEN_ENDPT -# define PJMEDIA_POOL_LEN_ENDPT 512 +# define PJMEDIA_POOL_LEN_ENDPT 512 #endif /** * Memory increment for media endpoint. */ #ifndef PJMEDIA_POOL_INC_ENDPT -# define PJMEDIA_POOL_INC_ENDPT 512 +# define PJMEDIA_POOL_INC_ENDPT 512 #endif /** * Initial memory block for event manager. */ #ifndef PJMEDIA_POOL_LEN_EVTMGR -# define PJMEDIA_POOL_LEN_EVTMGR 500 +# define PJMEDIA_POOL_LEN_EVTMGR 500 #endif /** * Memory increment for evnt manager. */ #ifndef PJMEDIA_POOL_INC_EVTMGR -# define PJMEDIA_POOL_INC_EVTMGR 500 +# define PJMEDIA_POOL_INC_EVTMGR 500 #endif /** @@ -109,7 +108,7 @@ * Default: 1 (enabled) */ #ifndef PJMEDIA_CONF_USE_AGC -# define PJMEDIA_CONF_USE_AGC 1 +# define PJMEDIA_CONF_USE_AGC 1 #endif @@ -145,7 +144,7 @@ * info. */ #ifndef PJMEDIA_HAS_LEGACY_SOUND_API -# define PJMEDIA_HAS_LEGACY_SOUND_API 1 +# define PJMEDIA_HAS_LEGACY_SOUND_API 1 #endif /** @@ -162,9 +161,9 @@ */ #ifndef PJMEDIA_SND_DEFAULT_PLAY_LATENCY # if defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE!=0 -# define PJMEDIA_SND_DEFAULT_PLAY_LATENCY 160 +# define PJMEDIA_SND_DEFAULT_PLAY_LATENCY 160 # else -# define PJMEDIA_SND_DEFAULT_PLAY_LATENCY 140 +# define PJMEDIA_SND_DEFAULT_PLAY_LATENCY 140 # endif #endif @@ -181,7 +180,7 @@ * This type of implementation may be used as it requires the least * processing power. */ -#define PJMEDIA_WSOLA_IMP_NULL 0 +#define PJMEDIA_WSOLA_IMP_NULL 0 /** * This denotes implementation of WSOLA using fixed or floating point WSOLA @@ -189,14 +188,14 @@ * at the expense of one frame delay and intensive processing power * requirement. */ -#define PJMEDIA_WSOLA_IMP_WSOLA 1 +#define PJMEDIA_WSOLA_IMP_WSOLA 1 /** * This denotes implementation of WSOLA algorithm with faster waveform * similarity calculation. This implementation provides fair quality of * the result with the main advantage of low processing power requirement. */ -#define PJMEDIA_WSOLA_IMP_WSOLA_LITE 2 +#define PJMEDIA_WSOLA_IMP_WSOLA_LITE 2 /** * Specify type of Waveform based Similarity Overlap and Add (WSOLA) backend @@ -207,7 +206,7 @@ * Default is PJMEDIA_WSOLA_IMP_WSOLA */ #ifndef PJMEDIA_WSOLA_IMP -# define PJMEDIA_WSOLA_IMP PJMEDIA_WSOLA_IMP_WSOLA +# define PJMEDIA_WSOLA_IMP PJMEDIA_WSOLA_IMP_WSOLA #endif @@ -236,7 +235,7 @@ * Default: 5 */ #ifndef PJMEDIA_WSOLA_TEMPLATE_LENGTH_MSEC -# define PJMEDIA_WSOLA_TEMPLATE_LENGTH_MSEC 5 +# define PJMEDIA_WSOLA_TEMPLATE_LENGTH_MSEC 5 #endif @@ -250,7 +249,7 @@ * Default: 5 */ #ifndef PJMEDIA_WSOLA_DELAY_MSEC -# define PJMEDIA_WSOLA_DELAY_MSEC 5 +# define PJMEDIA_WSOLA_DELAY_MSEC 5 #endif @@ -265,7 +264,7 @@ * Default: 0 */ #ifndef PJMEDIA_WSOLA_PLC_NO_FADING -# define PJMEDIA_WSOLA_PLC_NO_FADING 0 +# define PJMEDIA_WSOLA_PLC_NO_FADING 0 #endif @@ -299,7 +298,7 @@ * Default: (PJMEDIA_SND_DEFAULT_PLAY_LATENCY+20)/20 */ #ifndef PJMEDIA_SOUND_BUFFER_COUNT -# define PJMEDIA_SOUND_BUFFER_COUNT ((PJMEDIA_SND_DEFAULT_PLAY_LATENCY+20)/20) +# define PJMEDIA_SOUND_BUFFER_COUNT ((PJMEDIA_SND_DEFAULT_PLAY_LATENCY+20)/20) #endif @@ -310,7 +309,7 @@ * If this option is disabled, a smaller but slower algorithm will be used. */ #ifndef PJMEDIA_HAS_ALAW_ULAW_TABLE -# define PJMEDIA_HAS_ALAW_ULAW_TABLE 1 +# define PJMEDIA_HAS_ALAW_ULAW_TABLE 1 #endif @@ -318,7 +317,7 @@ * Unless specified otherwise, G711 codec is included by default. */ #ifndef PJMEDIA_HAS_G711_CODEC -# define PJMEDIA_HAS_G711_CODEC 1 +# define PJMEDIA_HAS_G711_CODEC 1 #endif @@ -329,10 +328,10 @@ */ #if defined(PJMEDIA_HAS_SMALL_FILTER) # ifdef _MSC_VER -# pragma message("Warning: PJMEDIA_HAS_SMALL_FILTER macro is deprecated"\ - " and has no effect") +# pragma message("Warning: PJMEDIA_HAS_SMALL_FILTER macro is deprecated"\ + " and has no effect") # else -# warning "PJMEDIA_HAS_SMALL_FILTER macro is deprecated and has no effect" +# warning "PJMEDIA_HAS_SMALL_FILTER macro is deprecated and has no effect" # endif #endif @@ -344,10 +343,10 @@ */ #if defined(PJMEDIA_HAS_LARGE_FILTER) # ifdef _MSC_VER -# pragma message("Warning: PJMEDIA_HAS_LARGE_FILTER macro is deprecated"\ - " and has no effect") +# pragma message("Warning: PJMEDIA_HAS_LARGE_FILTER macro is deprecated"\ + " and has no effect") # else -# warning "PJMEDIA_HAS_LARGE_FILTER macro is deprecated" +# warning "PJMEDIA_HAS_LARGE_FILTER macro is deprecated" # endif #endif @@ -370,15 +369,15 @@ * Sample rate conversion backends. * Select one of these backends in PJMEDIA_RESAMPLE_IMP. */ -#define PJMEDIA_RESAMPLE_NONE 1 /**< No resampling. */ -#define PJMEDIA_RESAMPLE_LIBRESAMPLE 2 /**< Sample rate conversion - using libresample. */ -#define PJMEDIA_RESAMPLE_SPEEX 3 /**< Sample rate conversion - using Speex. */ -#define PJMEDIA_RESAMPLE_LIBSAMPLERATE 4 /**< Sample rate conversion - using libsamplerate - (a.k.a Secret Rabbit Code) - */ +#define PJMEDIA_RESAMPLE_NONE 1 /**< No resampling. */ +#define PJMEDIA_RESAMPLE_LIBRESAMPLE 2 /**< Sample rate conversion + using libresample. */ +#define PJMEDIA_RESAMPLE_SPEEX 3 /**< Sample rate conversion + using Speex. */ +#define PJMEDIA_RESAMPLE_LIBSAMPLERATE 4 /**< Sample rate conversion + using libsamplerate + (a.k.a Secret Rabbit Code) + */ /** * Select which resample implementation to use. Currently pjmedia supports: @@ -393,7 +392,7 @@ * Default is PJMEDIA_RESAMPLE_LIBRESAMPLE */ #ifndef PJMEDIA_RESAMPLE_IMP -# define PJMEDIA_RESAMPLE_IMP PJMEDIA_RESAMPLE_LIBRESAMPLE +# define PJMEDIA_RESAMPLE_IMP PJMEDIA_RESAMPLE_LIBRESAMPLE #endif @@ -408,7 +407,7 @@ * Default file player/writer buffer size. */ #ifndef PJMEDIA_FILE_PORT_BUFSIZE -# define PJMEDIA_FILE_PORT_BUFSIZE 4000 +# define PJMEDIA_FILE_PORT_BUFSIZE 4000 #endif @@ -418,23 +417,23 @@ * for outgoing packets. */ #ifndef PJMEDIA_MAX_FRAME_DURATION_MS -# define PJMEDIA_MAX_FRAME_DURATION_MS 200 +# define PJMEDIA_MAX_FRAME_DURATION_MS 200 #endif /** * Max packet size for transmitting direction. */ -#ifndef PJMEDIA_MAX_MTU -# define PJMEDIA_MAX_MTU 1500 +#ifndef PJMEDIA_MAX_MTU +# define PJMEDIA_MAX_MTU 1500 #endif /** * Max packet size for receiving direction. */ -#ifndef PJMEDIA_MAX_MRU -# define PJMEDIA_MAX_MRU 2000 +#ifndef PJMEDIA_MAX_MRU +# define PJMEDIA_MAX_MRU 2000 #endif @@ -442,8 +441,8 @@ * DTMF/telephone-event duration, in timestamp. To specify the duration in * milliseconds, use the setting PJMEDIA_DTMF_DURATION_MSEC instead. */ -#ifndef PJMEDIA_DTMF_DURATION -# define PJMEDIA_DTMF_DURATION 1600 /* in timestamp */ +#ifndef PJMEDIA_DTMF_DURATION +# define PJMEDIA_DTMF_DURATION 1600 /* in timestamp */ #endif @@ -454,8 +453,8 @@ * Note that for a clockrate of 8 KHz, a dtmf duration of 1600 timestamp * units (the default value of PJMEDIA_DTMF_DURATION) is equivalent to 200 ms. */ -#ifndef PJMEDIA_DTMF_DURATION_MSEC -# define PJMEDIA_DTMF_DURATION_MSEC 0 +#ifndef PJMEDIA_DTMF_DURATION_MSEC +# define PJMEDIA_DTMF_DURATION_MSEC 0 #endif @@ -464,8 +463,8 @@ * remote address required to make the stream switch transmission * to the source address. */ -#ifndef PJMEDIA_RTP_NAT_PROBATION_CNT -# define PJMEDIA_RTP_NAT_PROBATION_CNT 10 +#ifndef PJMEDIA_RTP_NAT_PROBATION_CNT +# define PJMEDIA_RTP_NAT_PROBATION_CNT 10 #endif @@ -475,7 +474,7 @@ * to the source address. */ #ifndef PJMEDIA_RTCP_NAT_PROBATION_CNT -# define PJMEDIA_RTCP_NAT_PROBATION_CNT 3 +# define PJMEDIA_RTCP_NAT_PROBATION_CNT 3 #endif @@ -488,7 +487,7 @@ * Default: 1 (yes) */ #ifndef PJMEDIA_ADVERTISE_RTCP -# define PJMEDIA_ADVERTISE_RTCP 1 +# define PJMEDIA_ADVERTISE_RTCP 1 #endif @@ -496,7 +495,7 @@ * Interval to send regular RTCP packets, in msec. */ #ifndef PJMEDIA_RTCP_INTERVAL -# define PJMEDIA_RTCP_INTERVAL 5000 /* msec*/ +# define PJMEDIA_RTCP_INTERVAL 5000 /* msec*/ #endif @@ -505,7 +504,7 @@ * such as Picture Loss Indication, in msec. */ #ifndef PJMEDIA_RTCP_FB_INTERVAL -# define PJMEDIA_RTCP_FB_INTERVAL 50 /* msec*/ +# define PJMEDIA_RTCP_FB_INTERVAL 50 /* msec*/ #endif @@ -519,7 +518,7 @@ * Default: 25. */ #ifndef PJMEDIA_RTCP_IGNORE_FIRST_PACKETS -# define PJMEDIA_RTCP_IGNORE_FIRST_PACKETS 25 +# define PJMEDIA_RTCP_IGNORE_FIRST_PACKETS 25 #endif @@ -532,7 +531,7 @@ * Default: 0 (no). */ #ifndef PJMEDIA_RTCP_STAT_HAS_RAW_JITTER -# define PJMEDIA_RTCP_STAT_HAS_RAW_JITTER 0 +# define PJMEDIA_RTCP_STAT_HAS_RAW_JITTER 0 #endif /** @@ -545,7 +544,7 @@ * Default: 3. */ #ifndef PJMEDIA_RTCP_NORMALIZE_FACTOR -# define PJMEDIA_RTCP_NORMALIZE_FACTOR 3 +# define PJMEDIA_RTCP_NORMALIZE_FACTOR 3 #endif @@ -560,7 +559,7 @@ * Default: 0 (no). */ #ifndef PJMEDIA_RTCP_STAT_HAS_IPDV -# define PJMEDIA_RTCP_STAT_HAS_IPDV 0 +# define PJMEDIA_RTCP_STAT_HAS_IPDV 0 #endif @@ -574,7 +573,7 @@ * Default: 0 (no). */ #ifndef PJMEDIA_HAS_RTCP_XR -# define PJMEDIA_HAS_RTCP_XR 0 +# define PJMEDIA_HAS_RTCP_XR 0 #endif @@ -586,7 +585,7 @@ * Default: 0 (disabled) */ #ifndef PJMEDIA_STREAM_ENABLE_XR -# define PJMEDIA_STREAM_ENABLE_XR 0 +# define PJMEDIA_STREAM_ENABLE_XR 0 #endif @@ -598,7 +597,7 @@ * Default: 64 bytes. */ #ifndef PJMEDIA_RTCP_RX_SDES_BUF_LEN -# define PJMEDIA_RTCP_RX_SDES_BUF_LEN 64 +# define PJMEDIA_RTCP_RX_SDES_BUF_LEN 64 #endif @@ -608,7 +607,7 @@ * Default: 16 */ #ifndef PJMEDIA_RTCP_FB_MAX_CAP -# define PJMEDIA_RTCP_FB_MAX_CAP 16 +# define PJMEDIA_RTCP_FB_MAX_CAP 16 #endif @@ -627,7 +626,7 @@ * filling up the jitter buffer on the remote end). */ #ifndef PJMEDIA_STREAM_VAD_SUSPEND_MSEC -# define PJMEDIA_STREAM_VAD_SUSPEND_MSEC 600 +# define PJMEDIA_STREAM_VAD_SUSPEND_MSEC 600 #endif /** @@ -639,7 +638,7 @@ * Default: 1 */ #ifndef PJMEDIA_STREAM_CHECK_RTP_PT -# define PJMEDIA_STREAM_CHECK_RTP_PT 1 +# define PJMEDIA_STREAM_CHECK_RTP_PT 1 #endif /** @@ -647,7 +646,7 @@ * in RTP payload, so the total payload length will not exceed the MTU. */ #ifndef PJMEDIA_STREAM_RESV_PAYLOAD_LEN -# define PJMEDIA_STREAM_RESV_PAYLOAD_LEN 20 +# define PJMEDIA_STREAM_RESV_PAYLOAD_LEN 20 #endif @@ -666,7 +665,7 @@ * Default: 5000 ms */ #ifndef PJMEDIA_CODEC_MAX_SILENCE_PERIOD -# define PJMEDIA_CODEC_MAX_SILENCE_PERIOD 5000 +# define PJMEDIA_CODEC_MAX_SILENCE_PERIOD 5000 #endif @@ -676,7 +675,7 @@ * has the range from zero to 0xFFFF. */ #ifndef PJMEDIA_SILENCE_DET_THRESHOLD -# define PJMEDIA_SILENCE_DET_THRESHOLD 4 +# define PJMEDIA_SILENCE_DET_THRESHOLD 4 #endif @@ -690,7 +689,7 @@ * Default: 0x10000 (disabled) */ #ifndef PJMEDIA_SILENCE_DET_MAX_THRESHOLD -# define PJMEDIA_SILENCE_DET_MAX_THRESHOLD 0x10000 +# define PJMEDIA_SILENCE_DET_MAX_THRESHOLD 0x10000 #endif @@ -699,7 +698,7 @@ * By default is enabled. */ #ifndef PJMEDIA_HAS_SPEEX_AEC -# define PJMEDIA_HAS_SPEEX_AEC 1 +# define PJMEDIA_HAS_SPEEX_AEC 1 #endif @@ -710,7 +709,7 @@ * Default: 1 (yes) */ #ifndef PJMEDIA_SPEEX_AEC_USE_AGC -# define PJMEDIA_SPEEX_AEC_USE_AGC 1 +# define PJMEDIA_SPEEX_AEC_USE_AGC 1 #endif @@ -720,7 +719,7 @@ * Default: 1 (yes) */ #ifndef PJMEDIA_SPEEX_AEC_USE_DENOISE -# define PJMEDIA_SPEEX_AEC_USE_DENOISE 1 +# define PJMEDIA_SPEEX_AEC_USE_DENOISE 1 #endif @@ -729,7 +728,7 @@ * By default is disabled. */ #ifndef PJMEDIA_HAS_WEBRTC_AEC -# define PJMEDIA_HAS_WEBRTC_AEC 0 +# define PJMEDIA_HAS_WEBRTC_AEC 0 #endif /** @@ -738,7 +737,7 @@ * Default: 0 (no) */ #ifndef PJMEDIA_WEBRTC_AEC_USE_MOBILE -# define PJMEDIA_WEBRTC_AEC_USE_MOBILE 0 +# define PJMEDIA_WEBRTC_AEC_USE_MOBILE 0 #endif @@ -748,7 +747,7 @@ * Default: 16 */ #ifndef PJMEDIA_CODEC_MAX_FMTP_CNT -# define PJMEDIA_CODEC_MAX_FMTP_CNT 16 +# define PJMEDIA_CODEC_MAX_FMTP_CNT 16 #endif @@ -772,7 +771,7 @@ * Default is 1 (to maintain backward compatibility) */ #ifndef PJMEDIA_SDP_NEG_PREFER_REMOTE_CODEC_ORDER -# define PJMEDIA_SDP_NEG_PREFER_REMOTE_CODEC_ORDER 1 +# define PJMEDIA_SDP_NEG_PREFER_REMOTE_CODEC_ORDER 1 #endif /** @@ -785,7 +784,7 @@ * Default is 0 (to maintain backward compatibility) */ #ifndef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS -# define PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS 0 +# define PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS 0 #endif @@ -794,7 +793,7 @@ * negotiation callbacks. */ #ifndef PJMEDIA_SDP_NEG_MAX_CUSTOM_FMT_NEG_CB -# define PJMEDIA_SDP_NEG_MAX_CUSTOM_FMT_NEG_CB 8 +# define PJMEDIA_SDP_NEG_MAX_CUSTOM_FMT_NEG_CB 8 #endif @@ -806,7 +805,7 @@ * Default is 1 (yes) */ #ifndef PJMEDIA_SDP_NEG_ANSWER_SYMMETRIC_PT -# define PJMEDIA_SDP_NEG_ANSWER_SYMMETRIC_PT 1 +# define PJMEDIA_SDP_NEG_ANSWER_SYMMETRIC_PT 1 #endif @@ -820,7 +819,7 @@ * Default is 0 (No) */ #ifndef PJMEDIA_SDP_NEG_COMPARE_BEFORE_INC_VERSION -# define PJMEDIA_SDP_NEG_COMPARE_BEFORE_INC_VERSION 0 +# define PJMEDIA_SDP_NEG_COMPARE_BEFORE_INC_VERSION 0 #endif @@ -829,7 +828,7 @@ * Default is equal to PJMEDIA_ADVERTISE_RTCP setting. */ #ifndef PJMEDIA_HAS_RTCP_IN_SDP -# define PJMEDIA_HAS_RTCP_IN_SDP (PJMEDIA_ADVERTISE_RTCP) +# define PJMEDIA_HAS_RTCP_IN_SDP (PJMEDIA_ADVERTISE_RTCP) #endif @@ -851,7 +850,7 @@ * Default: 1 (yes) */ #ifndef PJMEDIA_ADD_BANDWIDTH_TIAS_IN_SDP -# define PJMEDIA_ADD_BANDWIDTH_TIAS_IN_SDP 1 +# define PJMEDIA_ADD_BANDWIDTH_TIAS_IN_SDP 1 #endif @@ -875,7 +874,7 @@ * Default: 1 (yes) */ #ifndef PJMEDIA_ADD_RTPMAP_FOR_STATIC_PT -# define PJMEDIA_ADD_RTPMAP_FOR_STATIC_PT 1 +# define PJMEDIA_ADD_RTPMAP_FOR_STATIC_PT 1 #endif @@ -886,7 +885,7 @@ * supported. */ #ifndef PJMEDIA_RTP_PT_TELEPHONE_EVENTS -# define PJMEDIA_RTP_PT_TELEPHONE_EVENTS 120 +# define PJMEDIA_RTP_PT_TELEPHONE_EVENTS 120 #endif @@ -908,7 +907,7 @@ * Maximum tones/digits that can be enqueued in the tone generator. */ #ifndef PJMEDIA_TONEGEN_MAX_DIGITS -# define PJMEDIA_TONEGEN_MAX_DIGITS 32 +# define PJMEDIA_TONEGEN_MAX_DIGITS 32 #endif @@ -921,14 +920,14 @@ * but it's the slowest and requires floating point support and * linking with the math library. */ -#define PJMEDIA_TONEGEN_SINE 1 +#define PJMEDIA_TONEGEN_SINE 1 /** * Floating point approximation of sine(). This has relatively good * precision and much faster than plain sine(), but it requires floating- * point support and linking with the math library. */ -#define PJMEDIA_TONEGEN_FLOATING_POINT 2 +#define PJMEDIA_TONEGEN_FLOATING_POINT 2 /** * Fixed point using sine signal generated by Cordic algorithm. This @@ -937,14 +936,14 @@ * setting, and may be suitable for platforms that lack floating-point * support. */ -#define PJMEDIA_TONEGEN_FIXED_POINT_CORDIC 3 +#define PJMEDIA_TONEGEN_FIXED_POINT_CORDIC 3 /** * Fast fixed point using some approximation to generate sine waves. * The tone generated by this algorithm is not very precise, however * the algorithm is very fast. */ -#define PJMEDIA_TONEGEN_FAST_FIXED_POINT 4 +#define PJMEDIA_TONEGEN_FAST_FIXED_POINT 4 /** @@ -958,9 +957,9 @@ */ #ifndef PJMEDIA_TONEGEN_ALG # if defined(PJ_HAS_FLOATING_POINT) && PJ_HAS_FLOATING_POINT -# define PJMEDIA_TONEGEN_ALG PJMEDIA_TONEGEN_FLOATING_POINT +# define PJMEDIA_TONEGEN_ALG PJMEDIA_TONEGEN_FLOATING_POINT # else -# define PJMEDIA_TONEGEN_ALG PJMEDIA_TONEGEN_FIXED_POINT_CORDIC +# define PJMEDIA_TONEGEN_ALG PJMEDIA_TONEGEN_FIXED_POINT_CORDIC # endif #endif @@ -1000,7 +999,7 @@ * Default: 1 (msec) */ #ifndef PJMEDIA_TONEGEN_FADE_IN_TIME -# define PJMEDIA_TONEGEN_FADE_IN_TIME 1 +# define PJMEDIA_TONEGEN_FADE_IN_TIME 1 #endif @@ -1011,7 +1010,7 @@ * Default: 2 (msec) */ #ifndef PJMEDIA_TONEGEN_FADE_OUT_TIME -# define PJMEDIA_TONEGEN_FADE_OUT_TIME 2 +# define PJMEDIA_TONEGEN_FADE_OUT_TIME 2 #endif @@ -1021,7 +1020,7 @@ * Default value: 12288 */ #ifndef PJMEDIA_TONEGEN_VOLUME -# define PJMEDIA_TONEGEN_VOLUME 12288 +# define PJMEDIA_TONEGEN_VOLUME 12288 #endif @@ -1032,7 +1031,7 @@ * By default it is enabled. */ #ifndef PJMEDIA_HAS_SRTP -# define PJMEDIA_HAS_SRTP 1 +# define PJMEDIA_HAS_SRTP 1 #endif @@ -1042,7 +1041,7 @@ * By default it is enabled. */ #ifndef PJMEDIA_SRTP_HAS_SDES -# define PJMEDIA_SRTP_HAS_SDES 1 +# define PJMEDIA_SRTP_HAS_SDES 1 #endif @@ -1052,7 +1051,7 @@ * Default value: 0 (disabled) */ #ifndef PJMEDIA_SRTP_HAS_DTLS -# define PJMEDIA_SRTP_HAS_DTLS 0 +# define PJMEDIA_SRTP_HAS_DTLS 0 #endif @@ -1062,7 +1061,7 @@ * Default value: "DEFAULT" */ #ifndef PJMEDIA_SRTP_DTLS_OSSL_CIPHERS -# define PJMEDIA_SRTP_DTLS_OSSL_CIPHERS "DEFAULT" +# define PJMEDIA_SRTP_DTLS_OSSL_CIPHERS "DEFAULT" #endif @@ -1072,7 +1071,7 @@ * Default: 16 */ #ifndef PJMEDIA_SRTP_MAX_CRYPTOS -# define PJMEDIA_SRTP_MAX_CRYPTOS 16 +# define PJMEDIA_SRTP_MAX_CRYPTOS 16 #endif @@ -1081,7 +1080,7 @@ * Default: enabled. */ #ifndef PJMEDIA_SRTP_HAS_AES_CM_256 -# define PJMEDIA_SRTP_HAS_AES_CM_256 1 +# define PJMEDIA_SRTP_HAS_AES_CM_256 1 #endif @@ -1096,7 +1095,7 @@ * Default: disabled. */ #ifndef PJMEDIA_SRTP_HAS_AES_CM_192 -# define PJMEDIA_SRTP_HAS_AES_CM_192 0 +# define PJMEDIA_SRTP_HAS_AES_CM_192 0 #endif @@ -1105,7 +1104,7 @@ * Default: enabled. */ #ifndef PJMEDIA_SRTP_HAS_AES_CM_128 -# define PJMEDIA_SRTP_HAS_AES_CM_128 1 +# define PJMEDIA_SRTP_HAS_AES_CM_128 1 #endif @@ -1118,7 +1117,7 @@ * Default: disabled. */ #ifndef PJMEDIA_SRTP_HAS_AES_GCM_256 -# define PJMEDIA_SRTP_HAS_AES_GCM_256 0 +# define PJMEDIA_SRTP_HAS_AES_GCM_256 0 #endif @@ -1131,7 +1130,7 @@ * Default: disabled. */ #ifndef PJMEDIA_SRTP_HAS_AES_GCM_128 -# define PJMEDIA_SRTP_HAS_AES_GCM_128 0 +# define PJMEDIA_SRTP_HAS_AES_GCM_128 0 #endif @@ -1166,7 +1165,7 @@ * By default it is enabled. */ #ifndef PJMEDIA_LIBSRTP_AUTO_INIT_DEINIT -# define PJMEDIA_LIBSRTP_AUTO_INIT_DEINIT 1 +# define PJMEDIA_LIBSRTP_AUTO_INIT_DEINIT 1 #endif @@ -1177,7 +1176,7 @@ * See: * - G.722 : RFC 3551 4.5.2 * - MPEG audio : RFC 3551 4.5.13 & RFC 3119 - * - OPUS : RFC 7587 + * - OPUS : RFC 7587 * * Also when this feature is enabled, some handling will be performed * to deal with clock rate incompatibilities of some phones. @@ -1185,7 +1184,7 @@ * By default it is enabled. */ #ifndef PJMEDIA_HANDLE_G722_MPEG_BUG -# define PJMEDIA_HANDLE_G722_MPEG_BUG 1 +# define PJMEDIA_HANDLE_G722_MPEG_BUG 1 #endif @@ -1195,7 +1194,7 @@ * By default it is enabled. */ #ifndef PJMEDIA_TRANSPORT_SWITCH_REMOTE_ADDR -# define PJMEDIA_TRANSPORT_SWITCH_REMOTE_ADDR 1 +# define PJMEDIA_TRANSPORT_SWITCH_REMOTE_ADDR 1 #endif @@ -1224,7 +1223,7 @@ * This indicates that an empty RTP packet should be used as * the keep-alive packet. */ -#define PJMEDIA_STREAM_KA_EMPTY_RTP 1 +#define PJMEDIA_STREAM_KA_EMPTY_RTP 1 /** * Value to be specified in PJMEDIA_STREAM_ENABLE_KA setting. @@ -1233,7 +1232,7 @@ * packet is specified by PJMEDIA_STREAM_KA_USER_PKT. Default * content is a CR-LF packet. */ -#define PJMEDIA_STREAM_KA_USER 2 +#define PJMEDIA_STREAM_KA_USER 2 /** * The content of the user defined keep-alive packet. The format @@ -1241,7 +1240,7 @@ * the content may contain NULL character. */ #ifndef PJMEDIA_STREAM_KA_USER_PKT -# define PJMEDIA_STREAM_KA_USER_PKT { "\r\n", 2 } +# define PJMEDIA_STREAM_KA_USER_PKT { "\r\n", 2 } #endif @@ -1268,7 +1267,7 @@ * Default: 0 (disabled) */ #ifndef PJMEDIA_STREAM_ENABLE_KA -# define PJMEDIA_STREAM_ENABLE_KA 0 +# define PJMEDIA_STREAM_ENABLE_KA 0 #endif @@ -1279,7 +1278,7 @@ * Default: 5 seconds */ #ifndef PJMEDIA_STREAM_KA_INTERVAL -# define PJMEDIA_STREAM_KA_INTERVAL 5 +# define PJMEDIA_STREAM_KA_INTERVAL 5 #endif @@ -1292,7 +1291,7 @@ * Default : 2 */ #ifndef PJMEDIA_STREAM_START_KA_CNT -# define PJMEDIA_STREAM_START_KA_CNT 2 +# define PJMEDIA_STREAM_START_KA_CNT 2 #endif @@ -1327,7 +1326,7 @@ * Default : 20 */ #ifndef PJMEDIA_IGNORE_RECV_ERR_CNT -# define PJMEDIA_IGNORE_RECV_ERR_CNT 20 +# define PJMEDIA_IGNORE_RECV_ERR_CNT 20 #endif @@ -1345,7 +1344,7 @@ * Default: 0 (disabled) */ #ifndef PJMEDIA_HAS_VIDEO -# define PJMEDIA_HAS_VIDEO 0 +# define PJMEDIA_HAS_VIDEO 0 #endif @@ -1356,7 +1355,7 @@ * Default: 0 */ #ifndef PJMEDIA_HAS_FFMPEG -# define PJMEDIA_HAS_FFMPEG 0 +# define PJMEDIA_HAS_FFMPEG 0 #endif /** @@ -1365,7 +1364,7 @@ * Default: PJMEDIA_HAS_FFMPEG (or detected by configure) */ #ifndef PJMEDIA_HAS_LIBAVFORMAT -# define PJMEDIA_HAS_LIBAVFORMAT PJMEDIA_HAS_FFMPEG +# define PJMEDIA_HAS_LIBAVFORMAT PJMEDIA_HAS_FFMPEG #endif /** @@ -1374,7 +1373,7 @@ * Default: PJMEDIA_HAS_FFMPEG (or detected by configure) */ #ifndef PJMEDIA_HAS_LIBAVCODEC -# define PJMEDIA_HAS_LIBAVCODEC PJMEDIA_HAS_FFMPEG +# define PJMEDIA_HAS_LIBAVCODEC PJMEDIA_HAS_FFMPEG #endif /** @@ -1383,7 +1382,7 @@ * Default: PJMEDIA_HAS_FFMPEG (or detected by configure) */ #ifndef PJMEDIA_HAS_LIBAVUTIL -# define PJMEDIA_HAS_LIBAVUTIL PJMEDIA_HAS_FFMPEG +# define PJMEDIA_HAS_LIBAVUTIL PJMEDIA_HAS_FFMPEG #endif /** @@ -1392,7 +1391,7 @@ * Default: PJMEDIA_HAS_FFMPEG (or detected by configure) */ #ifndef PJMEDIA_HAS_LIBSWSCALE -# define PJMEDIA_HAS_LIBSWSCALE PJMEDIA_HAS_FFMPEG +# define PJMEDIA_HAS_LIBSWSCALE PJMEDIA_HAS_FFMPEG #endif /** @@ -1401,7 +1400,7 @@ * Default: PJMEDIA_HAS_FFMPEG (or detected by configure) */ #ifndef PJMEDIA_HAS_LIBAVDEVICE -# define PJMEDIA_HAS_LIBAVDEVICE PJMEDIA_HAS_FFMPEG +# define PJMEDIA_HAS_LIBAVDEVICE PJMEDIA_HAS_FFMPEG #endif /** @@ -1410,7 +1409,7 @@ * Default: 4 */ #ifndef PJMEDIA_MAX_VIDEO_PLANES -# define PJMEDIA_MAX_VIDEO_PLANES 4 +# define PJMEDIA_MAX_VIDEO_PLANES 4 #endif /** @@ -1419,7 +1418,7 @@ * Default: 32 */ #ifndef PJMEDIA_MAX_VIDEO_FORMATS -# define PJMEDIA_MAX_VIDEO_FORMATS 32 +# define PJMEDIA_MAX_VIDEO_FORMATS 32 #endif /** @@ -1439,7 +1438,7 @@ * Default: 128kB */ #ifndef PJMEDIA_MAX_VIDEO_ENC_FRAME_SIZE -# define PJMEDIA_MAX_VIDEO_ENC_FRAME_SIZE (1<<17) +# define PJMEDIA_MAX_VIDEO_ENC_FRAME_SIZE (1<<17) #endif @@ -1465,7 +1464,7 @@ * Default: 200 ms */ #ifndef PJMEDIA_JBUF_DISC_MIN_GAP -# define PJMEDIA_JBUF_DISC_MIN_GAP 200 +# define PJMEDIA_JBUF_DISC_MIN_GAP 200 #endif @@ -1476,7 +1475,7 @@ * Default: 1 frame */ #ifndef PJMEDIA_JBUF_PRO_DISC_MIN_BURST -# define PJMEDIA_JBUF_PRO_DISC_MIN_BURST 1 +# define PJMEDIA_JBUF_PRO_DISC_MIN_BURST 1 #endif @@ -1487,7 +1486,7 @@ * Default: 200 frames */ #ifndef PJMEDIA_JBUF_PRO_DISC_MAX_BURST -# define PJMEDIA_JBUF_PRO_DISC_MAX_BURST 100 +# define PJMEDIA_JBUF_PRO_DISC_MAX_BURST 100 #endif @@ -1499,7 +1498,7 @@ * Default: 2000 ms */ #ifndef PJMEDIA_JBUF_PRO_DISC_T1 -# define PJMEDIA_JBUF_PRO_DISC_T1 2000 +# define PJMEDIA_JBUF_PRO_DISC_T1 2000 #endif @@ -1511,7 +1510,7 @@ * Default: 10000 ms */ #ifndef PJMEDIA_JBUF_PRO_DISC_T2 -# define PJMEDIA_JBUF_PRO_DISC_T2 10000 +# define PJMEDIA_JBUF_PRO_DISC_T2 10000 #endif @@ -1529,7 +1528,7 @@ * Default: 1 */ #ifndef PJMEDIA_STREAM_SOFT_START -# define PJMEDIA_STREAM_SOFT_START 1 +# define PJMEDIA_STREAM_SOFT_START 1 #endif @@ -1540,7 +1539,7 @@ * Default: 0 */ #ifndef PJMEDIA_VID_STREAM_SKIP_PACKETS_TO_REDUCE_LATENCY -# define PJMEDIA_VID_STREAM_SKIP_PACKETS_TO_REDUCE_LATENCY 0 +# define PJMEDIA_VID_STREAM_SKIP_PACKETS_TO_REDUCE_LATENCY 0 #endif @@ -1549,7 +1548,7 @@ * PJMEDIA_MAX_MTU. * * Default: (PJMEDIA_MAX_MTU - 20 - (128+16)) if SRTP is enabled, - * otherwise (PJMEDIA_MAX_MTU - 20). + * otherwise (PJMEDIA_MAX_MTU - 20). * Note that (128+16) constant value is taken from libSRTP macro * SRTP_MAX_TRAILER_LEN. */ @@ -1575,9 +1574,9 @@ */ #ifndef PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE # if PJMEDIA_HAS_VIDEO -# define PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE (64*1024) +# define PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE (64*1024) # else -# define PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE 0 +# define PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE 0 # endif #endif @@ -1595,9 +1594,9 @@ */ #ifndef PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE # if PJMEDIA_HAS_VIDEO -# define PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE (64*1024) +# define PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE (64*1024) # else -# define PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE 0 +# define PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE 0 # endif #endif @@ -1608,7 +1607,7 @@ * Default: 0 (disable) */ #ifndef PJMEDIA_HAS_LIBYUV -# define PJMEDIA_HAS_LIBYUV 0 +# define PJMEDIA_HAS_LIBYUV 0 #endif @@ -1616,7 +1615,7 @@ * Specify if dtmf flash in RFC 2833 is available. */ #ifndef PJMEDIA_HAS_DTMF_FLASH -# define PJMEDIA_HAS_DTMF_FLASH 1 +# define PJMEDIA_HAS_DTMF_FLASH 1 #endif @@ -1627,7 +1626,7 @@ * Default : 5 */ #ifndef PJMEDIA_VID_STREAM_START_KEYFRAME_CNT -# define PJMEDIA_VID_STREAM_START_KEYFRAME_CNT 5 +# define PJMEDIA_VID_STREAM_START_KEYFRAME_CNT 5 #endif @@ -1661,7 +1660,7 @@ * Default : 100 */ #ifndef PJMEDIA_VID_STREAM_DECODE_MIN_DELAY_MSEC -# define PJMEDIA_VID_STREAM_DECODE_MIN_DELAY_MSEC 100 +# define PJMEDIA_VID_STREAM_DECODE_MIN_DELAY_MSEC 100 #endif @@ -1674,7 +1673,7 @@ * Default: PJMEDIA_STREAM_CHECK_RTP_PT (follow audio stream's setting) */ #ifndef PJMEDIA_VID_STREAM_CHECK_RTP_PT -# define PJMEDIA_VID_STREAM_CHECK_RTP_PT PJMEDIA_STREAM_CHECK_RTP_PT +# define PJMEDIA_VID_STREAM_CHECK_RTP_PT PJMEDIA_STREAM_CHECK_RTP_PT #endif /** @@ -1682,6 +1681,6 @@ */ -#endif /* __PJMEDIA_CONFIG_H__ */ +#endif /* __PJMEDIA_CONFIG_H__ */ diff --git a/pjmedia/include/pjmedia/config_auto.h.in b/pjmedia/include/pjmedia/config_auto.h.in index 31a9d2b8f8..c04460d657 100644 --- a/pjmedia/include/pjmedia/config_auto.h.in +++ b/pjmedia/include/pjmedia/config_auto.h.in @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,8 +26,8 @@ /* * Note: - * The configuration in config_site.h overrides any other settings, - * including the setting as detected by autoconf. + * The configuration in config_site.h overrides any other settings, + * including the setting as detected by autoconf. */ /* G711 codec */ @@ -37,7 +36,7 @@ #endif -#endif /* __PJMEDIA_CONFIG_AUTO_H_ */ +#endif /* __PJMEDIA_CONFIG_AUTO_H_ */ diff --git a/pjmedia/include/pjmedia/converter.h b/pjmedia/include/pjmedia/converter.h index e8969bf554..ccdd93bb73 100644 --- a/pjmedia/include/pjmedia/converter.h +++ b/pjmedia/include/pjmedia/converter.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * @@ -46,8 +45,8 @@ PJ_BEGIN_DECL */ typedef struct pjmedia_conversion_param { - pjmedia_format src; /**< Source format. */ - pjmedia_format dst; /**< Destination format. */ + pjmedia_format src; /**< Source format. */ + pjmedia_format dst; /**< Destination format. */ } pjmedia_conversion_param; @@ -64,13 +63,13 @@ typedef struct pjmedia_converter_factory_op pjmedia_converter_factory_op; typedef enum pjmedia_converter_priority_guide { /** Lowest priority. */ - PJMEDIA_CONVERTER_PRIORITY_LOWEST = 0, + PJMEDIA_CONVERTER_PRIORITY_LOWEST = 0, /** Normal priority. */ - PJMEDIA_CONVERTER_PRIORITY_NORMAL = 15000, + PJMEDIA_CONVERTER_PRIORITY_NORMAL = 15000, /** Highest priority. */ - PJMEDIA_CONVERTER_PRIORITY_HIGHEST = 32000 + PJMEDIA_CONVERTER_PRIORITY_HIGHEST = 32000 } pjmedia_converter_priority_guide; /** @@ -87,7 +86,7 @@ typedef struct pjmedia_converter_factory /** * Factory name. */ - const char *name; + const char *name; /** * Converter priority determines which converter instance to be used if @@ -137,22 +136,22 @@ struct pjmedia_converter_factory_op * This function creates a converter with the specified conversion format, * if such format is supported. * - * @param cf The converter factory. - * @param pool Pool to allocate memory from. - * @param prm Conversion parameter. - * @param p_cv Pointer to hold the created converter instance. + * @param cf The converter factory. + * @param pool Pool to allocate memory from. + * @param prm Conversion parameter. + * @param p_cv Pointer to hold the created converter instance. * - * @return PJ_SUCCESS if converter has been created successfully. + * @return PJ_SUCCESS if converter has been created successfully. */ pj_status_t (*create_converter)(pjmedia_converter_factory *cf, - pj_pool_t *pool, - const pjmedia_conversion_param *prm, - pjmedia_converter **p_cv); + pj_pool_t *pool, + const pjmedia_conversion_param *prm, + pjmedia_converter **p_cv); /** * Destroy the factory. * - * @param cf The converter factory. + * @param cf The converter factory. */ void (*destroy_factory)(pjmedia_converter_factory *cf); }; @@ -170,16 +169,16 @@ struct pjmedia_converter_op * Note that application should use #pjmedia_converter_convert() instead * of calling this function directly. * - * @param cv The converter instance. - * @param src_frame The source frame. - * @param dst_frame The destination frame. + * @param cv The converter instance. + * @param src_frame The source frame. + * @param dst_frame The destination frame. * - * @return PJ_SUCCESS if conversion has been performed - * successfully. + * @return PJ_SUCCESS if conversion has been performed + * successfully. */ pj_status_t (*convert)(pjmedia_converter *cv, - pjmedia_frame *src_frame, - pjmedia_frame *dst_frame); + pjmedia_frame *src_frame, + pjmedia_frame *dst_frame); /** * Destroy the converter instance. @@ -187,7 +186,7 @@ struct pjmedia_converter_op * Note that application should use #pjmedia_converter_destroy() instead * of calling this function directly. * - * @param cv The converter. + * @param cv The converter. */ void (*destroy)(pjmedia_converter *cv); @@ -199,27 +198,27 @@ struct pjmedia_converter_op * Note that application should use #pjmedia_converter_convert2() instead * of calling this function directly. * - * @param cv The converter instance. - * @param src_frame The source frame. - * @param src_frame_size The source frame size. - * @param src_reg_pos The source region position. - * @param dst_frame The destination frame. - * @param dst_frame_size The destination frame size. - * @param dst_reg_pos The destination region position. - * @param param This is unused for now and must be NULL. + * @param cv The converter instance. + * @param src_frame The source frame. + * @param src_frame_size The source frame size. + * @param src_reg_pos The source region position. + * @param dst_frame The destination frame. + * @param dst_frame_size The destination frame size. + * @param dst_reg_pos The destination region position. + * @param param This is unused for now and must be NULL. * - * @return PJ_SUCCESS if conversion has been performed - * successfully. + * @return PJ_SUCCESS if conversion has been performed + * successfully. */ - pj_status_t (*convert2)(pjmedia_converter *cv, - pjmedia_frame *src_frame, - const pjmedia_rect_size *src_frame_size, - const pjmedia_coord *src_pos, - pjmedia_frame *dst_frame, - const pjmedia_rect_size *dst_frame_size, - const pjmedia_coord *dst_pos, - pjmedia_converter_convert_setting - *param); + pj_status_t (*convert2)(pjmedia_converter *cv, + pjmedia_frame *src_frame, + const pjmedia_rect_size *src_frame_size, + const pjmedia_coord *src_pos, + pjmedia_frame *dst_frame, + const pjmedia_rect_size *dst_frame_size, + const pjmedia_coord *dst_pos, + pjmedia_converter_convert_setting + *param); }; @@ -236,19 +235,19 @@ typedef struct pjmedia_converter_mgr pjmedia_converter_mgr; * Create a new conversion manager instance. This will also set the pointer * to the singleton instance if the value is still NULL. * - * @param pool Pool to allocate memory from. - * @param mgr Pointer to hold the created instance of the - * conversion manager. + * @param pool Pool to allocate memory from. + * @param mgr Pointer to hold the created instance of the + * conversion manager. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_converter_mgr_create(pj_pool_t *pool, - pjmedia_converter_mgr **mgr); + pjmedia_converter_mgr **mgr); /** * Get the singleton instance of the conversion manager. * - * @return The instance. + * @return The instance. */ PJ_DECL(pjmedia_converter_mgr*) pjmedia_converter_mgr_instance(void); @@ -258,9 +257,9 @@ PJ_DECL(pjmedia_converter_mgr*) pjmedia_converter_mgr_instance(void); * going to be created, as the library automatically assign the singleton * instance. * - * @param mgr The instance to be used as the singleton instance. - * Application may specify NULL to clear the singleton - * singleton instance. + * @param mgr The instance to be used as the singleton instance. + * Application may specify NULL to clear the singleton + * singleton instance. */ PJ_DECL(void) pjmedia_converter_mgr_set_instance(pjmedia_converter_mgr *mgr); @@ -268,75 +267,75 @@ PJ_DECL(void) pjmedia_converter_mgr_set_instance(pjmedia_converter_mgr *mgr); * Destroy a converter manager. If the manager happens to be the singleton * instance, the singleton instance will be set to NULL. * - * @param mgr The converter manager. Specify NULL to use - * the singleton instance. + * @param mgr The converter manager. Specify NULL to use + * the singleton instance. */ PJ_DECL(void) pjmedia_converter_mgr_destroy(pjmedia_converter_mgr *mgr); /** * Register a converter factory to the converter manager. * - * @param mgr The converter manager. Specify NULL to use - * the singleton instance. - * @param f The converter factory to be registered. + * @param mgr The converter manager. Specify NULL to use + * the singleton instance. + * @param f The converter factory to be registered. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_converter_mgr_register_factory(pjmedia_converter_mgr *mgr, - pjmedia_converter_factory *f); + pjmedia_converter_factory *f); /** * Unregister a previously registered converter factory from the converter * manager. * - * @param mgr The converter manager. Specify NULL to use - * the singleton instance. - * @param f The converter factory to be unregistered. - * @param call_destroy If this is set to non-zero, the \a destroy_factory() - * callback of the factory will be called while - * unregistering the factory from the manager. + * @param mgr The converter manager. Specify NULL to use + * the singleton instance. + * @param f The converter factory to be unregistered. + * @param call_destroy If this is set to non-zero, the \a destroy_factory() + * callback of the factory will be called while + * unregistering the factory from the manager. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_converter_mgr_unregister_factory(pjmedia_converter_mgr *mgr, - pjmedia_converter_factory *f, - pj_bool_t call_destroy); + pjmedia_converter_factory *f, + pj_bool_t call_destroy); /** * Create a converter instance to perform the specified format conversion * as specified in \a param. * - * @param mgr The converter manager. Specify NULL to use - * the singleton instance. - * @param pool Pool to allocate the memory from. - * @param param Conversion parameter. - * @param p_cv Pointer to hold the created converter. + * @param mgr The converter manager. Specify NULL to use + * the singleton instance. + * @param pool Pool to allocate the memory from. + * @param param Conversion parameter. + * @param p_cv Pointer to hold the created converter. * - * @return PJ_SUCCESS if a converter has been created successfully - * or the appropriate error code. + * @return PJ_SUCCESS if a converter has been created successfully + * or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_converter_create(pjmedia_converter_mgr *mgr, - pj_pool_t *pool, - pjmedia_conversion_param *param, - pjmedia_converter **p_cv); + pj_pool_t *pool, + pjmedia_conversion_param *param, + pjmedia_converter **p_cv); /** * Convert the buffer in the source frame and save the result in the * buffer of the destination frame, according to conversion format that * was specified when the converter was created. * - * @param cv The converter instance. - * @param src_frame The source frame. - * @param dst_frame The destination frame. + * @param cv The converter instance. + * @param src_frame The source frame. + * @param dst_frame The destination frame. * - * @return PJ_SUCCESS if conversion has been performed - * successfully. + * @return PJ_SUCCESS if conversion has been performed + * successfully. */ PJ_DECL(pj_status_t) pjmedia_converter_convert(pjmedia_converter *cv, - pjmedia_frame *src_frame, - pjmedia_frame *dst_frame); + pjmedia_frame *src_frame, + pjmedia_frame *dst_frame); /** @@ -344,33 +343,33 @@ PJ_DECL(pj_status_t) pjmedia_converter_convert(pjmedia_converter *cv, * into a region in the buffer of the destination frame, according to * conversion format that was specified when the converter was created. * - * @param cv The converter instance. - * @param src_frame The source frame. + * @param cv The converter instance. + * @param src_frame The source frame. * @param src_frame_size The source frame size. - * @param src_pos The source region position. - * @param dst_frame The destination frame. + * @param src_pos The source region position. + * @param dst_frame The destination frame. * @param dst_frame_size The destination frame size. - * @param dst_pos The destination region position. - * @param param This is unused for now and must be NULL. + * @param dst_pos The destination region position. + * @param param This is unused for now and must be NULL. * - * @return PJ_SUCCESS if conversion has been performed - * successfully. + * @return PJ_SUCCESS if conversion has been performed + * successfully. */ PJ_DECL(pj_status_t) pjmedia_converter_convert2( - pjmedia_converter *cv, - pjmedia_frame *src_frame, - const pjmedia_rect_size *src_frame_size, - const pjmedia_coord *src_pos, - pjmedia_frame *dst_frame, - const pjmedia_rect_size *dst_frame_size, - const pjmedia_coord *dst_pos, - pjmedia_converter_convert_setting - *param); + pjmedia_converter *cv, + pjmedia_frame *src_frame, + const pjmedia_rect_size *src_frame_size, + const pjmedia_coord *src_pos, + pjmedia_frame *dst_frame, + const pjmedia_rect_size *dst_frame_size, + const pjmedia_coord *dst_pos, + pjmedia_converter_convert_setting + *param); /** * Destroy the converter. * - * @param cv The converter instance. + * @param cv The converter instance. */ PJ_DECL(void) pjmedia_converter_destroy(pjmedia_converter *cv); diff --git a/pjmedia/include/pjmedia/delaybuf.h b/pjmedia/include/pjmedia/delaybuf.h index 09b01bbb51..5e98fc4564 100644 --- a/pjmedia/include/pjmedia/delaybuf.h +++ b/pjmedia/include/pjmedia/delaybuf.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -81,88 +80,88 @@ typedef enum pjmedia_delay_buf_flag * enter learning state unless the delay argument is specified, which * in this case it will directly enter the running state. * - * @param pool Pool where the delay buffer will be allocated - * from. - * @param name Optional name for the buffer for log - * identification. - * @param clock_rate Number of samples processed per second. + * @param pool Pool where the delay buffer will be allocated + * from. + * @param name Optional name for the buffer for log + * identification. + * @param clock_rate Number of samples processed per second. * @param samples_per_frame Number of samples per frame. - * @param channel_count Number of channel per frame. - * @param max_delay Maximum number of delay to be accommodated, - * in ms, if this value is negative or less than - * one frame time, default maximum delay used is - * 400 ms. - * @param options Options. If PJMEDIA_DELAY_BUF_SIMPLE_FIFO is + * @param channel_count Number of channel per frame. + * @param max_delay Maximum number of delay to be accommodated, + * in ms, if this value is negative or less than + * one frame time, default maximum delay used is + * 400 ms. + * @param options Options. If PJMEDIA_DELAY_BUF_SIMPLE_FIFO is * specified, then a simple FIFO mechanism - * will be used instead of the adaptive + * will be used instead of the adaptive * implementation (which uses WSOLA to expand * or shrink audio samples). - * See #pjmedia_delay_buf_flag for other options. - * @param p_b Pointer to receive the delay buffer instance. + * See #pjmedia_delay_buf_flag for other options. + * @param p_b Pointer to receive the delay buffer instance. * - * @return PJ_SUCCESS if the delay buffer has been - * created successfully, otherwise the appropriate - * error will be returned. + * @return PJ_SUCCESS if the delay buffer has been + * created successfully, otherwise the appropriate + * error will be returned. */ PJ_DECL(pj_status_t) pjmedia_delay_buf_create(pj_pool_t *pool, - const char *name, - unsigned clock_rate, - unsigned samples_per_frame, - unsigned channel_count, - unsigned max_delay, - unsigned options, - pjmedia_delay_buf **p_b); + const char *name, + unsigned clock_rate, + unsigned samples_per_frame, + unsigned channel_count, + unsigned max_delay, + unsigned options, + pjmedia_delay_buf **p_b); /** * Put one frame into the buffer. * - * @param b The delay buffer. - * @param frame Frame to be put into the buffer. This frame - * must have samples_per_frame length. + * @param b The delay buffer. + * @param frame Frame to be put into the buffer. This frame + * must have samples_per_frame length. * - * @return PJ_SUCCESS if frames can be put successfully. - * PJ_EPENDING if the buffer is still at learning - * state. PJ_ETOOMANY if the number of frames - * will exceed maximum delay level, which in this - * case the new frame will overwrite the oldest - * frame in the buffer. + * @return PJ_SUCCESS if frames can be put successfully. + * PJ_EPENDING if the buffer is still at learning + * state. PJ_ETOOMANY if the number of frames + * will exceed maximum delay level, which in this + * case the new frame will overwrite the oldest + * frame in the buffer. */ PJ_DECL(pj_status_t) pjmedia_delay_buf_put(pjmedia_delay_buf *b, - pj_int16_t frame[]); + pj_int16_t frame[]); /** * Get one frame from the buffer. * - * @param b The delay buffer. - * @param frame Buffer to receive the frame from the delay - * buffer. + * @param b The delay buffer. + * @param frame Buffer to receive the frame from the delay + * buffer. * - * @return PJ_SUCCESS if frame has been copied successfully. - * PJ_EPENDING if no frame is available, either - * because the buffer is still at learning state or - * no buffer is available during running state. - * On non-successful return, the frame will be - * filled with zeroes. + * @return PJ_SUCCESS if frame has been copied successfully. + * PJ_EPENDING if no frame is available, either + * because the buffer is still at learning state or + * no buffer is available during running state. + * On non-successful return, the frame will be + * filled with zeroes. */ PJ_DECL(pj_status_t) pjmedia_delay_buf_get(pjmedia_delay_buf *b, - pj_int16_t frame[]); + pj_int16_t frame[]); /** * Reset delay buffer. This will clear the buffer's content. But keep * the learning result. * - * @param b The delay buffer. + * @param b The delay buffer. * - * @return PJ_SUCCESS on success or the appropriate error. + * @return PJ_SUCCESS on success or the appropriate error. */ PJ_DECL(pj_status_t) pjmedia_delay_buf_reset(pjmedia_delay_buf *b); /** * Destroy delay buffer. * - * @param b Delay buffer session. + * @param b Delay buffer session. * - * @return PJ_SUCCESS normally. + * @return PJ_SUCCESS normally. */ PJ_DECL(pj_status_t) pjmedia_delay_buf_destroy(pjmedia_delay_buf *b); @@ -173,4 +172,4 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_DELAYBUF_H__ */ +#endif /* __PJMEDIA_DELAYBUF_H__ */ diff --git a/pjmedia/include/pjmedia/doxygen.h b/pjmedia/include/pjmedia/doxygen.h index 2aad28b445..a456a505e1 100644 --- a/pjmedia/include/pjmedia/doxygen.h +++ b/pjmedia/include/pjmedia/doxygen.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,7 +27,7 @@ /*////////////////////////////////////////////////////////////////////////// */ /* - INTRODUCTION PAGE + INTRODUCTION PAGE */ /** diff --git a/pjmedia/include/pjmedia/echo.h b/pjmedia/include/pjmedia/echo.h index 2f53d6bc39..6d05f7a0f9 100644 --- a/pjmedia/include/pjmedia/echo.h +++ b/pjmedia/include/pjmedia/echo.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -67,14 +66,14 @@ typedef enum pjmedia_echo_flag * Force to use Speex AEC as the backend echo canceller algorithm. * You can only choose one backend. */ - PJMEDIA_ECHO_SPEEX = 1, + PJMEDIA_ECHO_SPEEX = 1, /** * If PJMEDIA_ECHO_SIMPLE flag is specified during echo canceller * creation, then a simple echo suppressor will be used instead of * an accoustic echo cancellation. You can only choose one backend. */ - PJMEDIA_ECHO_SIMPLE = 2, + PJMEDIA_ECHO_SIMPLE = 2, /** * Force to use WebRTC AEC as the backend echo canceller algorithm. @@ -162,7 +161,7 @@ typedef enum pjmedia_echo_flag /** Statistic not specified. */ -#define PJMEDIA_ECHO_STAT_NOT_SPECIFIED 999999 +#define PJMEDIA_ECHO_STAT_NOT_SPECIFIED 999999 /** * Echo cancellation statistics. @@ -179,72 +178,72 @@ typedef struct pjmedia_echo_stat * Echo delay value (in ms). * PJMEDIA_ECHO_STAT_NOT_SPECIFIED if unavailable. */ - int delay; + int delay; /** * Echo return loss. * PJMEDIA_ECHO_STAT_NOT_SPECIFIED if unavailable. */ - double return_loss; + double return_loss; /** * Echo return loss enhancement. * PJMEDIA_ECHO_STAT_NOT_SPECIFIED if unavailable. */ - double return_loss_enh; + double return_loss_enh; /** * Echo delay standard deviation (in ms). * PJMEDIA_ECHO_STAT_NOT_SPECIFIED if unavailable. */ - int std; + int std; /** * Fraction of poor delay. Value between 0 to 1. The closer to 1, * the poorer the EC quality. * PJMEDIA_ECHO_STAT_NOT_SPECIFIED if unavailable. */ - float frac_delay; + float frac_delay; /** * Learning still in progress? PJ_TRUE if yes, false if done. * PJMEDIA_ECHO_STAT_NOT_SPECIFIED if unavailable. */ - unsigned learning; + unsigned learning; /** * Learning duration (in ms). * PJMEDIA_ECHO_STAT_NOT_SPECIFIED if unavailable. */ - unsigned duration; + unsigned duration; /** * Detected echo tail length (in ms). * PJMEDIA_ECHO_STAT_NOT_SPECIFIED if unavailable. */ - unsigned tail; + unsigned tail; /** * Minimum scaling factor (in ms). * PJMEDIA_ECHO_STAT_NOT_SPECIFIED if unavailable. */ - int min_factor; + int min_factor; /** * Average scaling factor (in ms). * PJMEDIA_ECHO_STAT_NOT_SPECIFIED if unavailable. */ - int avg_factor; + int avg_factor; /** * Text describing the statistic. */ - pj_str_t stat_info; + pj_str_t stat_info; /** * Internal buffer. */ - char buf_[128]; + char buf_[128]; } pjmedia_echo_stat; @@ -252,7 +251,7 @@ typedef struct pjmedia_echo_stat /** * Initialize Echo cancellation stat. * - * @param stat The statistic to be initialized. + * @param stat The statistic to be initialized. */ PJ_DECL(void) pjmedia_echo_stat_default(pjmedia_echo_stat *stat); @@ -260,65 +259,65 @@ PJ_DECL(void) pjmedia_echo_stat_default(pjmedia_echo_stat *stat); /** * Create the echo canceller. * - * @param pool Pool to allocate memory. - * @param clock_rate Media clock rate/sampling rate. + * @param pool Pool to allocate memory. + * @param clock_rate Media clock rate/sampling rate. * @param samples_per_frame Number of samples per frame. - * @param tail_ms Tail length, miliseconds. - * @param latency_ms Total lacency introduced by playback and - * recording device. Set to zero if the latency - * is not known. - * @param options Options. If PJMEDIA_ECHO_SIMPLE is specified, - * then a simple echo suppressor implementation - * will be used instead of an accoustic echo - * cancellation. - * See #pjmedia_echo_flag for other options. - * @param p_echo Pointer to receive the Echo Canceller state. + * @param tail_ms Tail length, miliseconds. + * @param latency_ms Total lacency introduced by playback and + * recording device. Set to zero if the latency + * is not known. + * @param options Options. If PJMEDIA_ECHO_SIMPLE is specified, + * then a simple echo suppressor implementation + * will be used instead of an accoustic echo + * cancellation. + * See #pjmedia_echo_flag for other options. + * @param p_echo Pointer to receive the Echo Canceller state. * - * @return PJ_SUCCESS on success, or the appropriate status. + * @return PJ_SUCCESS on success, or the appropriate status. */ PJ_DECL(pj_status_t) pjmedia_echo_create(pj_pool_t *pool, - unsigned clock_rate, - unsigned samples_per_frame, - unsigned tail_ms, - unsigned latency_ms, - unsigned options, - pjmedia_echo_state **p_echo ); + unsigned clock_rate, + unsigned samples_per_frame, + unsigned tail_ms, + unsigned latency_ms, + unsigned options, + pjmedia_echo_state **p_echo ); /** * Create multi-channel the echo canceller. * - * @param pool Pool to allocate memory. - * @param clock_rate Media clock rate/sampling rate. - * @param channel_count Number of channels. + * @param pool Pool to allocate memory. + * @param clock_rate Media clock rate/sampling rate. + * @param channel_count Number of channels. * @param samples_per_frame Number of samples per frame. - * @param tail_ms Tail length, miliseconds. - * @param latency_ms Total lacency introduced by playback and - * recording device. Set to zero if the latency - * is not known. - * @param options Options. If PJMEDIA_ECHO_SIMPLE is specified, - * then a simple echo suppressor implementation - * will be used instead of an accoustic echo - * cancellation. - * See #pjmedia_echo_flag for other options. - * @param p_echo Pointer to receive the Echo Canceller state. + * @param tail_ms Tail length, miliseconds. + * @param latency_ms Total lacency introduced by playback and + * recording device. Set to zero if the latency + * is not known. + * @param options Options. If PJMEDIA_ECHO_SIMPLE is specified, + * then a simple echo suppressor implementation + * will be used instead of an accoustic echo + * cancellation. + * See #pjmedia_echo_flag for other options. + * @param p_echo Pointer to receive the Echo Canceller state. * - * @return PJ_SUCCESS on success, or the appropriate status. + * @return PJ_SUCCESS on success, or the appropriate status. */ PJ_DECL(pj_status_t) pjmedia_echo_create2(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned tail_ms, - unsigned latency_ms, - unsigned options, - pjmedia_echo_state **p_echo ); + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned tail_ms, + unsigned latency_ms, + unsigned options, + pjmedia_echo_state **p_echo ); /** * Destroy the Echo Canceller. * - * @param echo The Echo Canceller. + * @param echo The Echo Canceller. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_echo_destroy(pjmedia_echo_state *echo ); @@ -326,9 +325,9 @@ PJ_DECL(pj_status_t) pjmedia_echo_destroy(pjmedia_echo_state *echo ); /** * Reset the echo canceller. * - * @param echo The Echo Canceller. + * @param echo The Echo Canceller. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_echo_reset(pjmedia_echo_state *echo ); @@ -336,13 +335,13 @@ PJ_DECL(pj_status_t) pjmedia_echo_reset(pjmedia_echo_state *echo ); /** * Get the echo canceller statistics. * - * @param echo The Echo Canceller. - * @param p_stat Pointer to receive the stat. + * @param echo The Echo Canceller. + * @param p_stat Pointer to receive the stat. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_echo_get_stat(pjmedia_echo_state *echo, - pjmedia_echo_stat *p_stat); + pjmedia_echo_stat *p_stat); /** @@ -350,16 +349,16 @@ PJ_DECL(pj_status_t) pjmedia_echo_get_stat(pjmedia_echo_state *echo, * The Echo Canceller will keep the frame in its internal buffer, to be used * when cancelling the echo with #pjmedia_echo_capture(). * - * @param echo The Echo Canceller. - * @param play_frm Sample buffer containing frame to be played - * (or has been played) to the playback device. - * The frame must contain exactly samples_per_frame - * number of samples. + * @param echo The Echo Canceller. + * @param play_frm Sample buffer containing frame to be played + * (or has been played) to the playback device. + * The frame must contain exactly samples_per_frame + * number of samples. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_echo_playback(pjmedia_echo_state *echo, - pj_int16_t *play_frm ); + pj_int16_t *play_frm ); /** @@ -368,46 +367,46 @@ PJ_DECL(pj_status_t) pjmedia_echo_playback(pjmedia_echo_state *echo, * signal, using the internal buffer (supplied by #pjmedia_echo_playback()) * as the FES (Far End Speech) reference. * - * @param echo The Echo Canceller. - * @param rec_frm On input, it contains the input signal (captured - * from microphone) which echo is to be removed. - * Upon returning this function, this buffer contain - * the processed signal with the echo removed. - * The frame must contain exactly samples_per_frame - * number of samples. - * @param options Echo cancellation options, reserved for future use. - * Put zero for now. + * @param echo The Echo Canceller. + * @param rec_frm On input, it contains the input signal (captured + * from microphone) which echo is to be removed. + * Upon returning this function, this buffer contain + * the processed signal with the echo removed. + * The frame must contain exactly samples_per_frame + * number of samples. + * @param options Echo cancellation options, reserved for future use. + * Put zero for now. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_echo_capture(pjmedia_echo_state *echo, - pj_int16_t *rec_frm, - unsigned options ); + pj_int16_t *rec_frm, + unsigned options ); /** * Perform echo cancellation. * - * @param echo The Echo Canceller. - * @param rec_frm On input, it contains the input signal (captured - * from microphone) which echo is to be removed. - * Upon returning this function, this buffer contain - * the processed signal with the echo removed. - * @param play_frm Sample buffer containing frame to be played - * (or has been played) to the playback device. - * The frame must contain exactly samples_per_frame - * number of samples. - * @param options Echo cancellation options, reserved for future use. - * Put zero for now. - * @param reserved Reserved for future use, put NULL for now. + * @param echo The Echo Canceller. + * @param rec_frm On input, it contains the input signal (captured + * from microphone) which echo is to be removed. + * Upon returning this function, this buffer contain + * the processed signal with the echo removed. + * @param play_frm Sample buffer containing frame to be played + * (or has been played) to the playback device. + * The frame must contain exactly samples_per_frame + * number of samples. + * @param options Echo cancellation options, reserved for future use. + * Put zero for now. + * @param reserved Reserved for future use, put NULL for now. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_echo_cancel( pjmedia_echo_state *echo, - pj_int16_t *rec_frm, - const pj_int16_t *play_frm, - unsigned options, - void *reserved ); + pj_int16_t *rec_frm, + const pj_int16_t *play_frm, + unsigned options, + void *reserved ); PJ_END_DECL @@ -417,5 +416,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_ECHO_H__ */ +#endif /* __PJMEDIA_ECHO_H__ */ diff --git a/pjmedia/include/pjmedia/echo_port.h b/pjmedia/include/pjmedia/echo_port.h index 6806a71d42..228acf16d2 100644 --- a/pjmedia/include/pjmedia/echo_port.h +++ b/pjmedia/include/pjmedia/echo_port.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,23 +43,23 @@ PJ_BEGIN_DECL /** * Create echo canceller port. * - * @param pool Pool to allocate memory. - * @param dn_port Downstream port. - * @param tail_ms Tail length in miliseconds. - * @param latency_ms Total lacency introduced by playback and - * recording device. Set to zero if the latency - * is not known. - * @param options Options, as in #pjmedia_echo_create(). - * @param p_port Pointer to receive the port instance. + * @param pool Pool to allocate memory. + * @param dn_port Downstream port. + * @param tail_ms Tail length in miliseconds. + * @param latency_ms Total lacency introduced by playback and + * recording device. Set to zero if the latency + * is not known. + * @param options Options, as in #pjmedia_echo_create(). + * @param p_port Pointer to receive the port instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_echo_port_create(pj_pool_t *pool, - pjmedia_port *dn_port, - unsigned tail_ms, - unsigned latency_ms, - unsigned options, - pjmedia_port **p_port ); + pjmedia_port *dn_port, + unsigned tail_ms, + unsigned latency_ms, + unsigned options, + pjmedia_port **p_port ); @@ -71,4 +70,4 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_AEC_PORT_H__ */ +#endif /* __PJMEDIA_AEC_PORT_H__ */ diff --git a/pjmedia/include/pjmedia/endpoint.h b/pjmedia/include/pjmedia/endpoint.h index cdf3c0053f..b00c0b1da9 100644 --- a/pjmedia/include/pjmedia/endpoint.h +++ b/pjmedia/include/pjmedia/endpoint.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -85,7 +84,7 @@ typedef void (*pjmedia_endpt_exit_callback)(pjmedia_endpt *endpt); * Call this function to initialize \a pjmedia_endpt_create_sdp_param with default * values. * - * @param param The param to be initialized. + * @param param The param to be initialized. */ PJ_DECL(void) pjmedia_endpt_create_sdp_param_default(pjmedia_endpt_create_sdp_param *param); @@ -93,42 +92,42 @@ pjmedia_endpt_create_sdp_param_default(pjmedia_endpt_create_sdp_param *param); /** * Create an instance of media endpoint. * - * @param pf Pool factory, which will be used by the media endpoint - * throughout its lifetime. - * @param ioqueue Optional ioqueue instance to be registered to the - * endpoint. The ioqueue instance is used to poll all RTP - * and RTCP sockets. If this argument is NULL, the - * endpoint will create an internal ioqueue instance. - * @param worker_cnt Specify the number of worker threads to be created - * to poll the ioqueue. - * @param p_endpt Pointer to receive the endpoint instance. - * - * @return PJ_SUCCESS on success. + * @param pf Pool factory, which will be used by the media endpoint + * throughout its lifetime. + * @param ioqueue Optional ioqueue instance to be registered to the + * endpoint. The ioqueue instance is used to poll all RTP + * and RTCP sockets. If this argument is NULL, the + * endpoint will create an internal ioqueue instance. + * @param worker_cnt Specify the number of worker threads to be created + * to poll the ioqueue. + * @param p_endpt Pointer to receive the endpoint instance. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_endpt_create2(pj_pool_factory *pf, - pj_ioqueue_t *ioqueue, - unsigned worker_cnt, - pjmedia_endpt **p_endpt); + pj_ioqueue_t *ioqueue, + unsigned worker_cnt, + pjmedia_endpt **p_endpt); /** * Create an instance of media endpoint and initialize audio subsystem. * - * @param pf Pool factory, which will be used by the media endpoint - * throughout its lifetime. - * @param ioqueue Optional ioqueue instance to be registered to the - * endpoint. The ioqueue instance is used to poll all RTP - * and RTCP sockets. If this argument is NULL, the - * endpoint will create an internal ioqueue instance. - * @param worker_cnt Specify the number of worker threads to be created - * to poll the ioqueue. - * @param p_endpt Pointer to receive the endpoint instance. - * - * @return PJ_SUCCESS on success. + * @param pf Pool factory, which will be used by the media endpoint + * throughout its lifetime. + * @param ioqueue Optional ioqueue instance to be registered to the + * endpoint. The ioqueue instance is used to poll all RTP + * and RTCP sockets. If this argument is NULL, the + * endpoint will create an internal ioqueue instance. + * @param worker_cnt Specify the number of worker threads to be created + * to poll the ioqueue. + * @param p_endpt Pointer to receive the endpoint instance. + * + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_endpt_create(pj_pool_factory *pf, - pj_ioqueue_t *ioqueue, - unsigned worker_cnt, - pjmedia_endpt **p_endpt) + pj_ioqueue_t *ioqueue, + unsigned worker_cnt, + pjmedia_endpt **p_endpt) { /* This function is inlined to avoid build problem due to circular * dependency, i.e: this function prevents pjmedia's dependency on @@ -153,18 +152,18 @@ PJ_INLINE(pj_status_t) pjmedia_endpt_create(pj_pool_factory *pf, /** * Destroy media endpoint instance. * - * @param endpt Media endpoint instance. + * @param endpt Media endpoint instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_endpt_destroy2(pjmedia_endpt *endpt); /** * Destroy media endpoint instance and shutdown audio subsystem. * - * @param endpt Media endpoint instance. + * @param endpt Media endpoint instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_endpt_destroy(pjmedia_endpt *endpt) { @@ -180,35 +179,35 @@ PJ_INLINE(pj_status_t) pjmedia_endpt_destroy(pjmedia_endpt *endpt) /** * Change the value of a flag. * - * @param endpt Media endpoint. - * @param flag The flag. - * @param value Pointer to the value to be set. + * @param endpt Media endpoint. + * @param flag The flag. + * @param value Pointer to the value to be set. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_endpt_set_flag(pjmedia_endpt *endpt, - pjmedia_endpt_flag flag, - const void *value); + pjmedia_endpt_flag flag, + const void *value); /** * Retrieve the value of a flag. * - * @param endpt Media endpoint. - * @param flag The flag. - * @param value Pointer to store the result. + * @param endpt Media endpoint. + * @param flag The flag. + * @param value Pointer to store the result. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_endpt_get_flag(pjmedia_endpt *endpt, - pjmedia_endpt_flag flag, - void *value); + pjmedia_endpt_flag flag, + void *value); /** * Get the ioqueue instance of the media endpoint. * - * @param endpt The media endpoint instance. + * @param endpt The media endpoint instance. * - * @return The ioqueue instance of the media endpoint. + * @return The ioqueue instance of the media endpoint. */ PJ_DECL(pj_ioqueue_t*) pjmedia_endpt_get_ioqueue(pjmedia_endpt *endpt); @@ -216,28 +215,28 @@ PJ_DECL(pj_ioqueue_t*) pjmedia_endpt_get_ioqueue(pjmedia_endpt *endpt); /** * Get the number of worker threads on the media endpoint * - * @param endpt The media endpoint instance. - * @return The number of worker threads on the media endpoint + * @param endpt The media endpoint instance. + * @return The number of worker threads on the media endpoint */ PJ_DECL(unsigned) pjmedia_endpt_get_thread_count(pjmedia_endpt *endpt); /** * Get a reference to one of the worker threads of the media endpoint * - * @param endpt The media endpoint instance. - * @param index The index of the thread: 0<= index < thread_cnt + * @param endpt The media endpoint instance. + * @param index The index of the thread: 0<= index < thread_cnt * - * @return pj_thread_t or NULL + * @return pj_thread_t or NULL */ PJ_DECL(pj_thread_t*) pjmedia_endpt_get_thread(pjmedia_endpt *endpt, - unsigned index); + unsigned index); /** * Stop and destroy the worker threads of the media endpoint * - * @param endpt The media endpoint instance. + * @param endpt The media endpoint instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_endpt_stop_threads(pjmedia_endpt *endpt); @@ -245,25 +244,25 @@ PJ_DECL(pj_status_t) pjmedia_endpt_stop_threads(pjmedia_endpt *endpt); /** * Request the media endpoint to create pool. * - * @param endpt The media endpoint instance. - * @param name Name to be assigned to the pool. - * @param initial Initial pool size, in bytes. - * @param increment Increment size, in bytes. + * @param endpt The media endpoint instance. + * @param name Name to be assigned to the pool. + * @param initial Initial pool size, in bytes. + * @param increment Increment size, in bytes. * - * @return Memory pool. + * @return Memory pool. */ PJ_DECL(pj_pool_t*) pjmedia_endpt_create_pool( pjmedia_endpt *endpt, - const char *name, - pj_size_t initial, - pj_size_t increment); + const char *name, + pj_size_t initial, + pj_size_t increment); /** * Get the codec manager instance of the media endpoint. * - * @param endpt The media endpoint instance. + * @param endpt The media endpoint instance. * - * @return The instance of codec manager belonging to - * this media endpoint. + * @return The instance of codec manager belonging to + * this media endpoint. */ PJ_DECL(pjmedia_codec_mgr*) pjmedia_endpt_get_codec_mgr(pjmedia_endpt *endpt); @@ -272,58 +271,58 @@ PJ_DECL(pjmedia_codec_mgr*) pjmedia_endpt_get_codec_mgr(pjmedia_endpt *endpt); * Create a SDP session description that describes the endpoint * capability. * - * @param endpt The media endpoint. - * @param pool Pool to use to create the SDP descriptor. - * @param stream_cnt Number of elements in the sock_info array. This - * also denotes the maximum number of streams (i.e. - * the "m=" lines) that will be created in the SDP. - * By convention, if this value is greater than one, - * the first media will be audio and the remaining - * media is video. - * @param sock_info Array of socket transport information. One - * transport is needed for each media stream, and - * each transport consists of an RTP and RTCP socket - * pair. - * @param p_sdp Pointer to receive SDP session descriptor. - * - * @return PJ_SUCCESS on success. + * @param endpt The media endpoint. + * @param pool Pool to use to create the SDP descriptor. + * @param stream_cnt Number of elements in the sock_info array. This + * also denotes the maximum number of streams (i.e. + * the "m=" lines) that will be created in the SDP. + * By convention, if this value is greater than one, + * the first media will be audio and the remaining + * media is video. + * @param sock_info Array of socket transport information. One + * transport is needed for each media stream, and + * each transport consists of an RTP and RTCP socket + * pair. + * @param p_sdp Pointer to receive SDP session descriptor. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_endpt_create_sdp( pjmedia_endpt *endpt, - pj_pool_t *pool, - unsigned stream_cnt, - const pjmedia_sock_info sock_info[], - pjmedia_sdp_session **p_sdp ); + pj_pool_t *pool, + unsigned stream_cnt, + const pjmedia_sock_info sock_info[], + pjmedia_sdp_session **p_sdp ); /** * Create a "blank" SDP session description. The SDP will contain basic SDP * fields such as origin, time, and name, but without any media lines. * - * @param endpt The media endpoint. - * @param pool Pool to allocate memory from. - * @param sess_name Optional SDP session name, or NULL to use default - * value. - * @param origin Address to put in the origin field. - * @param p_sdp Pointer to receive the created SDP session. + * @param endpt The media endpoint. + * @param pool Pool to allocate memory from. + * @param sess_name Optional SDP session name, or NULL to use default + * value. + * @param origin Address to put in the origin field. + * @param p_sdp Pointer to receive the created SDP session. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_endpt_create_base_sdp(pjmedia_endpt *endpt, - pj_pool_t *pool, - const pj_str_t *sess_name, - const pj_sockaddr *origin, - pjmedia_sdp_session **p_sdp); + pj_pool_t *pool, + const pj_str_t *sess_name, + const pj_sockaddr *origin, + pjmedia_sdp_session **p_sdp); /** * Create SDP media line for audio media. * - * @param endpt The media endpoint. - * @param pool Pool to allocate memory from. - * @param si Socket information. - * @param options Options parameter, can be NULL. If set to NULL, - * default values will be used. - * @param p_m Pointer to receive the created SDP media. + * @param endpt The media endpoint. + * @param pool Pool to allocate memory from. + * @param si Socket information. + * @param options Options parameter, can be NULL. If set to NULL, + * default values will be used. + * @param p_m Pointer to receive the created SDP media. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_endpt_create_audio_sdp(pjmedia_endpt *endpt, @@ -335,14 +334,14 @@ pjmedia_endpt_create_audio_sdp(pjmedia_endpt *endpt, /** * Create SDP media line for video media. * - * @param endpt The media endpoint. - * @param pool Pool to allocate memory from. - * @param si Socket information. - * @param options Options parameter, can be NULL. If set to NULL, - * default values will be used. - * @param p_m Pointer to receive the created SDP media. + * @param endpt The media endpoint. + * @param pool Pool to allocate memory from. + * @param si Socket information. + * @param options Options parameter, can be NULL. If set to NULL, + * default values will be used. + * @param p_m Pointer to receive the created SDP media. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_endpt_create_video_sdp(pjmedia_endpt *endpt, @@ -354,9 +353,9 @@ pjmedia_endpt_create_video_sdp(pjmedia_endpt *endpt, /** * Dump media endpoint capabilities. * - * @param endpt The media endpoint. + * @param endpt The media endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_endpt_dump(pjmedia_endpt *endpt); @@ -368,13 +367,13 @@ PJ_DECL(pj_status_t) pjmedia_endpt_dump(pjmedia_endpt *endpt); * the callback as such resource may have been released when the callback * function is invoked. * - * @param endpt The media endpoint. - * @param func The function to be registered. + * @param endpt The media endpoint. + * @param func The function to be registered. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_endpt_atexit(pjmedia_endpt *endpt, - pjmedia_endpt_exit_callback func); + pjmedia_endpt_exit_callback func); @@ -387,4 +386,4 @@ PJ_END_DECL -#endif /* __PJMEDIA_MEDIAMGR_H__ */ +#endif /* __PJMEDIA_MEDIAMGR_H__ */ diff --git a/pjmedia/include/pjmedia/errno.h b/pjmedia/include/pjmedia/errno.h index 5875c926f6..fab663b26a 100644 --- a/pjmedia/include/pjmedia/errno.h +++ b/pjmedia/include/pjmedia/errno.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -80,7 +79,7 @@ PJ_BEGIN_DECL * @hideinitializer * General/unknown PJMEDIA error. */ -#define PJMEDIA_ERROR (PJMEDIA_ERRNO_START+1) /* 220001 */ +#define PJMEDIA_ERROR (PJMEDIA_ERRNO_START+1) /* 220001 */ /************************************************************ @@ -90,32 +89,32 @@ PJ_BEGIN_DECL * @hideinitializer * Generic invalid SDP descriptor. */ -#define PJMEDIA_SDP_EINSDP (PJMEDIA_ERRNO_START+20) /* 220020 */ +#define PJMEDIA_SDP_EINSDP (PJMEDIA_ERRNO_START+20) /* 220020 */ /** * @hideinitializer * Invalid SDP version. */ -#define PJMEDIA_SDP_EINVER (PJMEDIA_ERRNO_START+21) /* 220021 */ +#define PJMEDIA_SDP_EINVER (PJMEDIA_ERRNO_START+21) /* 220021 */ /** * @hideinitializer * Invalid SDP origin (o=) line. */ -#define PJMEDIA_SDP_EINORIGIN (PJMEDIA_ERRNO_START+22) /* 220022 */ +#define PJMEDIA_SDP_EINORIGIN (PJMEDIA_ERRNO_START+22) /* 220022 */ /** * @hideinitializer * Invalid SDP time (t=) line. */ -#define PJMEDIA_SDP_EINTIME (PJMEDIA_ERRNO_START+23) /* 220023 */ +#define PJMEDIA_SDP_EINTIME (PJMEDIA_ERRNO_START+23) /* 220023 */ /** * @hideinitializer * Empty SDP subject/name (s=) line. */ -#define PJMEDIA_SDP_EINNAME (PJMEDIA_ERRNO_START+24) /* 220024 */ +#define PJMEDIA_SDP_EINNAME (PJMEDIA_ERRNO_START+24) /* 220024 */ /** * @hideinitializer * Invalid SDP connection info (c=) line. */ -#define PJMEDIA_SDP_EINCONN (PJMEDIA_ERRNO_START+25) /* 220025 */ +#define PJMEDIA_SDP_EINCONN (PJMEDIA_ERRNO_START+25) /* 220025 */ /** * @hideinitializer * Missing SDP connection info line. @@ -125,12 +124,12 @@ PJ_BEGIN_DECL * @hideinitializer * Invalid attribute (a=) line. */ -#define PJMEDIA_SDP_EINATTR (PJMEDIA_ERRNO_START+27) /* 220027 */ +#define PJMEDIA_SDP_EINATTR (PJMEDIA_ERRNO_START+27) /* 220027 */ /** * @hideinitializer * Invalid rtpmap attribute. */ -#define PJMEDIA_SDP_EINRTPMAP (PJMEDIA_ERRNO_START+28) /* 220028 */ +#define PJMEDIA_SDP_EINRTPMAP (PJMEDIA_ERRNO_START+28) /* 220028 */ /** * @hideinitializer * rtpmap attribute is too long. @@ -145,42 +144,42 @@ PJ_BEGIN_DECL * @hideinitializer * Invalid SDP media (m=) line. */ -#define PJMEDIA_SDP_EINMEDIA (PJMEDIA_ERRNO_START+31) /* 220031 */ +#define PJMEDIA_SDP_EINMEDIA (PJMEDIA_ERRNO_START+31) /* 220031 */ /** * @hideinitializer * No payload format in the media stream. */ -#define PJMEDIA_SDP_ENOFMT (PJMEDIA_ERRNO_START+32) /* 220032 */ +#define PJMEDIA_SDP_ENOFMT (PJMEDIA_ERRNO_START+32) /* 220032 */ /** * @hideinitializer * Invalid payload type in media. */ -#define PJMEDIA_SDP_EINPT (PJMEDIA_ERRNO_START+33) /* 220033 */ +#define PJMEDIA_SDP_EINPT (PJMEDIA_ERRNO_START+33) /* 220033 */ /** * @hideinitializer * Invalid SDP "fmtp" attribute. */ -#define PJMEDIA_SDP_EINFMTP (PJMEDIA_ERRNO_START+34) /* 220034 */ +#define PJMEDIA_SDP_EINFMTP (PJMEDIA_ERRNO_START+34) /* 220034 */ /** * @hideinitializer * Invalid SDP "rtcp" attribute. */ -#define PJMEDIA_SDP_EINRTCP (PJMEDIA_ERRNO_START+35) /* 220035 */ +#define PJMEDIA_SDP_EINRTCP (PJMEDIA_ERRNO_START+35) /* 220035 */ /** * @hideinitializer * Invalid SDP media transport protocol. */ -#define PJMEDIA_SDP_EINPROTO (PJMEDIA_ERRNO_START+36) /* 220036 */ +#define PJMEDIA_SDP_EINPROTO (PJMEDIA_ERRNO_START+36) /* 220036 */ /** * @hideinitializer * Invalid SDP bandwidth info (b=) line. */ -#define PJMEDIA_SDP_EINBANDW (PJMEDIA_ERRNO_START+37) /* 220037 */ +#define PJMEDIA_SDP_EINBANDW (PJMEDIA_ERRNO_START+37) /* 220037 */ /** * @hideinitializer * Invalid SDP "ssrc" attribute. */ -#define PJMEDIA_SDP_EINSSRC (PJMEDIA_ERRNO_START+38) /* 220038 */ +#define PJMEDIA_SDP_EINSSRC (PJMEDIA_ERRNO_START+38) /* 220038 */ /************************************************************ @@ -190,7 +189,7 @@ PJ_BEGIN_DECL * @hideinitializer * Invalid state to perform the specified operation. */ -#define PJMEDIA_SDPNEG_EINSTATE (PJMEDIA_ERRNO_START+40) /* 220040 */ +#define PJMEDIA_SDPNEG_EINSTATE (PJMEDIA_ERRNO_START+40) /* 220040 */ /** * @hideinitializer * No initial local SDP. @@ -205,7 +204,7 @@ PJ_BEGIN_DECL * @hideinitializer * No current offer or answer. */ -#define PJMEDIA_SDPNEG_ENONEG (PJMEDIA_ERRNO_START+43) /* 220043 */ +#define PJMEDIA_SDPNEG_ENONEG (PJMEDIA_ERRNO_START+43) /* 220043 */ /** * @hideinitializer * Media count mismatch in offer and answer. @@ -230,7 +229,7 @@ PJ_BEGIN_DECL * @hideinitializer * No media is active after negotiation. */ -#define PJMEDIA_SDPNEG_ENOMEDIA (PJMEDIA_ERRNO_START+48) /* 220048 */ +#define PJMEDIA_SDPNEG_ENOMEDIA (PJMEDIA_ERRNO_START+48) /* 220048 */ /** * @hideinitializer * No suitable codec for remote offer. @@ -325,12 +324,12 @@ PJ_BEGIN_DECL * @hideinitializer * Unsupported codec. */ -#define PJMEDIA_CODEC_EUNSUP (PJMEDIA_ERRNO_START+80) /* 220080 */ +#define PJMEDIA_CODEC_EUNSUP (PJMEDIA_ERRNO_START+80) /* 220080 */ /** * @hideinitializer * Codec internal creation error. */ -#define PJMEDIA_CODEC_EFAILED (PJMEDIA_ERRNO_START+81) /* 220081 */ +#define PJMEDIA_CODEC_EFAILED (PJMEDIA_ERRNO_START+81) /* 220081 */ /** * @hideinitializer * Codec frame is too short. @@ -345,7 +344,7 @@ PJ_BEGIN_DECL * @hideinitializer * Invalid codec frame length. */ -#define PJMEDIA_CODEC_EFRMINLEN (PJMEDIA_ERRNO_START+84) /* 220084 */ +#define PJMEDIA_CODEC_EFRMINLEN (PJMEDIA_ERRNO_START+84) /* 220084 */ /** * @hideinitializer * Invalid PCM frame length. @@ -355,7 +354,7 @@ PJ_BEGIN_DECL * @hideinitializer * Invalid mode. */ -#define PJMEDIA_CODEC_EINMODE (PJMEDIA_ERRNO_START+86) /* 220086 */ +#define PJMEDIA_CODEC_EINMODE (PJMEDIA_ERRNO_START+86) /* 220086 */ /** * @hideinitializer * Bad or corrupted bitstream. @@ -370,22 +369,22 @@ PJ_BEGIN_DECL * @hideinitializer * Invalid remote IP address (in SDP). */ -#define PJMEDIA_EINVALIDIP (PJMEDIA_ERRNO_START+100) /* 220100 */ +#define PJMEDIA_EINVALIDIP (PJMEDIA_ERRNO_START+100) /* 220100 */ /** * @hideinitializer * Asymetric codec is not supported. */ -#define PJMEDIA_EASYMCODEC (PJMEDIA_ERRNO_START+101) /* 220101 */ +#define PJMEDIA_EASYMCODEC (PJMEDIA_ERRNO_START+101) /* 220101 */ /** * @hideinitializer * Invalid payload type. */ -#define PJMEDIA_EINVALIDPT (PJMEDIA_ERRNO_START+102) /* 220102 */ +#define PJMEDIA_EINVALIDPT (PJMEDIA_ERRNO_START+102) /* 220102 */ /** * @hideinitializer * Missing rtpmap. */ -#define PJMEDIA_EMISSINGRTPMAP (PJMEDIA_ERRNO_START+103) /* 220103 */ +#define PJMEDIA_EMISSINGRTPMAP (PJMEDIA_ERRNO_START+103) /* 220103 */ /** * @hideinitializer * Invalid media type. @@ -395,12 +394,12 @@ PJ_BEGIN_DECL * @hideinitializer * Remote does not support DTMF. */ -#define PJMEDIA_EREMOTENODTMF (PJMEDIA_ERRNO_START+105) /* 220105 */ +#define PJMEDIA_EREMOTENODTMF (PJMEDIA_ERRNO_START+105) /* 220105 */ /** * @hideinitializer * Invalid DTMF digit. */ -#define PJMEDIA_RTP_EINDTMF (PJMEDIA_ERRNO_START+106) /* 220106 */ +#define PJMEDIA_RTP_EINDTMF (PJMEDIA_ERRNO_START+106) /* 220106 */ /** * @hideinitializer * Remote does not support RFC 2833 @@ -424,32 +423,32 @@ PJ_BEGIN_DECL * @hideinitializer * General invalid RTP packet error. */ -#define PJMEDIA_RTP_EINPKT (PJMEDIA_ERRNO_START+120) /* 220120 */ +#define PJMEDIA_RTP_EINPKT (PJMEDIA_ERRNO_START+120) /* 220120 */ /** * @hideinitializer * Invalid RTP packet packing. */ -#define PJMEDIA_RTP_EINPACK (PJMEDIA_ERRNO_START+121) /* 220121 */ +#define PJMEDIA_RTP_EINPACK (PJMEDIA_ERRNO_START+121) /* 220121 */ /** * @hideinitializer * Invalid RTP packet version. */ -#define PJMEDIA_RTP_EINVER (PJMEDIA_ERRNO_START+122) /* 220122 */ +#define PJMEDIA_RTP_EINVER (PJMEDIA_ERRNO_START+122) /* 220122 */ /** * @hideinitializer * RTP SSRC id mismatch. */ -#define PJMEDIA_RTP_EINSSRC (PJMEDIA_ERRNO_START+123) /* 220123 */ +#define PJMEDIA_RTP_EINSSRC (PJMEDIA_ERRNO_START+123) /* 220123 */ /** * @hideinitializer * RTP payload type mismatch. */ -#define PJMEDIA_RTP_EINPT (PJMEDIA_ERRNO_START+124) /* 220124 */ +#define PJMEDIA_RTP_EINPT (PJMEDIA_ERRNO_START+124) /* 220124 */ /** * @hideinitializer * Invalid RTP packet length. */ -#define PJMEDIA_RTP_EINLEN (PJMEDIA_ERRNO_START+125) /* 220125 */ +#define PJMEDIA_RTP_EINLEN (PJMEDIA_ERRNO_START+125) /* 220125 */ /** * @hideinitializer * RTP session restarted. @@ -464,17 +463,17 @@ PJ_BEGIN_DECL * @hideinitializer * Bad RTP sequence number */ -#define PJMEDIA_RTP_EBADSEQ (PJMEDIA_ERRNO_START+132) /* 220132 */ +#define PJMEDIA_RTP_EBADSEQ (PJMEDIA_ERRNO_START+132) /* 220132 */ /** * @hideinitializer * RTP media port destination is not configured */ -#define PJMEDIA_RTP_EBADDEST (PJMEDIA_ERRNO_START+133) /* 220133 */ +#define PJMEDIA_RTP_EBADDEST (PJMEDIA_ERRNO_START+133) /* 220133 */ /** * @hideinitializer * RTP is not configured. */ -#define PJMEDIA_RTP_ENOCONFIG (PJMEDIA_ERRNO_START+134) /* 220134 */ +#define PJMEDIA_RTP_ENOCONFIG (PJMEDIA_ERRNO_START+134) /* 220134 */ /************************************************************ @@ -484,12 +483,12 @@ PJ_BEGIN_DECL * @hideinitializer * Generic incompatible port error. */ -#define PJMEDIA_ENOTCOMPATIBLE (PJMEDIA_ERRNO_START+160) /* 220160 */ +#define PJMEDIA_ENOTCOMPATIBLE (PJMEDIA_ERRNO_START+160) /* 220160 */ /** * @hideinitializer * Incompatible clock rate */ -#define PJMEDIA_ENCCLOCKRATE (PJMEDIA_ERRNO_START+161) /* 220161 */ +#define PJMEDIA_ENCCLOCKRATE (PJMEDIA_ERRNO_START+161) /* 220161 */ /** * @hideinitializer * Incompatible samples per frame @@ -499,22 +498,22 @@ PJ_BEGIN_DECL * @hideinitializer * Incompatible media type */ -#define PJMEDIA_ENCTYPE (PJMEDIA_ERRNO_START+163) /* 220163 */ +#define PJMEDIA_ENCTYPE (PJMEDIA_ERRNO_START+163) /* 220163 */ /** * @hideinitializer * Incompatible bits per sample */ -#define PJMEDIA_ENCBITS (PJMEDIA_ERRNO_START+164) /* 220164 */ +#define PJMEDIA_ENCBITS (PJMEDIA_ERRNO_START+164) /* 220164 */ /** * @hideinitializer * Incompatible bytes per frame */ -#define PJMEDIA_ENCBYTES (PJMEDIA_ERRNO_START+165) /* 220165 */ +#define PJMEDIA_ENCBYTES (PJMEDIA_ERRNO_START+165) /* 220165 */ /** * @hideinitializer * Incompatible number of channels */ -#define PJMEDIA_ENCCHANNEL (PJMEDIA_ERRNO_START+166) /* 220166 */ +#define PJMEDIA_ENCCHANNEL (PJMEDIA_ERRNO_START+166) /* 220166 */ /************************************************************ @@ -524,27 +523,27 @@ PJ_BEGIN_DECL * @hideinitializer * Not a valid WAVE file. */ -#define PJMEDIA_ENOTVALIDWAVE (PJMEDIA_ERRNO_START+180) /* 220180 */ +#define PJMEDIA_ENOTVALIDWAVE (PJMEDIA_ERRNO_START+180) /* 220180 */ /** * @hideinitializer * Unsupported WAVE file. */ -#define PJMEDIA_EWAVEUNSUPP (PJMEDIA_ERRNO_START+181) /* 220181 */ +#define PJMEDIA_EWAVEUNSUPP (PJMEDIA_ERRNO_START+181) /* 220181 */ /** * @hideinitializer * Wave file too short. */ -#define PJMEDIA_EWAVETOOSHORT (PJMEDIA_ERRNO_START+182) /* 220182 */ +#define PJMEDIA_EWAVETOOSHORT (PJMEDIA_ERRNO_START+182) /* 220182 */ /** * @hideinitializer * Sound frame is too large for file buffer. */ -#define PJMEDIA_EFRMFILETOOBIG (PJMEDIA_ERRNO_START+183) /* 220183 */ +#define PJMEDIA_EFRMFILETOOBIG (PJMEDIA_ERRNO_START+183) /* 220183 */ /** * @hideinitializer * Unsupported AVI file. */ -#define PJMEDIA_EAVIUNSUPP (PJMEDIA_ERRNO_START+191) /* 220191 */ +#define PJMEDIA_EAVIUNSUPP (PJMEDIA_ERRNO_START+191) /* 220191 */ /************************************************************ @@ -554,22 +553,22 @@ PJ_BEGIN_DECL * @hideinitializer * No suitable audio capture device. */ -#define PJMEDIA_ENOSNDREC (PJMEDIA_ERRNO_START+200) /* 220200 */ +#define PJMEDIA_ENOSNDREC (PJMEDIA_ERRNO_START+200) /* 220200 */ /** * @hideinitializer * No suitable audio playback device. */ -#define PJMEDIA_ENOSNDPLAY (PJMEDIA_ERRNO_START+201) /* 220201 */ +#define PJMEDIA_ENOSNDPLAY (PJMEDIA_ERRNO_START+201) /* 220201 */ /** * @hideinitializer * Invalid sound device ID. */ -#define PJMEDIA_ESNDINDEVID (PJMEDIA_ERRNO_START+202) /* 220202 */ +#define PJMEDIA_ESNDINDEVID (PJMEDIA_ERRNO_START+202) /* 220202 */ /** * @hideinitializer * Invalid sample format for sound device. */ -#define PJMEDIA_ESNDINSAMPLEFMT (PJMEDIA_ERRNO_START+203) /* 220203 */ +#define PJMEDIA_ESNDINSAMPLEFMT (PJMEDIA_ERRNO_START+203) /* 220203 */ #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) @@ -585,7 +584,7 @@ PJ_BEGIN_DECL * @hideinitializer * Invalid SRTP key length for specific crypto. */ -#define PJMEDIA_SRTP_EINKEYLEN (PJMEDIA_ERRNO_START+221) /* 220221 */ +#define PJMEDIA_SRTP_EINKEYLEN (PJMEDIA_ERRNO_START+221) /* 220221 */ /** * @hideinitializer * Unsupported SRTP crypto-suite. @@ -630,7 +629,7 @@ PJ_BEGIN_DECL * @hideinitializer * SRTP parameters negotiation still in progress. */ -#define PJMEDIA_SRTP_EKEYNOTREADY (PJMEDIA_ERRNO_START+230) /* 220230 */ +#define PJMEDIA_SRTP_EKEYNOTREADY (PJMEDIA_ERRNO_START+230) /* 220230 */ /** * @hideinitializer @@ -654,7 +653,7 @@ PJ_BEGIN_DECL * @hideinitializer * Fingerprint not found. */ -#define PJMEDIA_SRTP_DTLS_ENOFPRINT (PJMEDIA_ERRNO_START+243) /* 220243 */ +#define PJMEDIA_SRTP_DTLS_ENOFPRINT (PJMEDIA_ERRNO_START+243) /* 220243 */ /** * @hideinitializer @@ -676,11 +675,11 @@ PJ_BEGIN_DECL * @param buffer The buffer where to put the error message. * @param bufsize Size of the buffer. * - * @return The error message as NULL terminated string, + * @return The error message as NULL terminated string, * wrapped with pj_str_t. */ PJ_DECL(pj_str_t) pjmedia_strerror( pj_status_t status, char *buffer, - pj_size_t bufsize); + pj_size_t bufsize); PJ_END_DECL @@ -690,5 +689,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_ERRNO_H__ */ +#endif /* __PJMEDIA_ERRNO_H__ */ diff --git a/pjmedia/include/pjmedia/event.h b/pjmedia/include/pjmedia/event.h index ad936847cc..74e377a580 100644 --- a/pjmedia/include/pjmedia/event.h +++ b/pjmedia/include/pjmedia/event.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011-2011 Teluu Inc. (http://www.teluu.com) * @@ -50,22 +49,22 @@ typedef enum pjmedia_event_type /** * Media format has changed event. */ - PJMEDIA_EVENT_FMT_CHANGED = PJMEDIA_FOURCC('F', 'M', 'C', 'H'), + PJMEDIA_EVENT_FMT_CHANGED = PJMEDIA_FOURCC('F', 'M', 'C', 'H'), /** * Video window is being closed. */ - PJMEDIA_EVENT_WND_CLOSING = PJMEDIA_FOURCC('W', 'N', 'C', 'L'), + PJMEDIA_EVENT_WND_CLOSING = PJMEDIA_FOURCC('W', 'N', 'C', 'L'), /** * Video window has been closed event. */ - PJMEDIA_EVENT_WND_CLOSED = PJMEDIA_FOURCC('W', 'N', 'C', 'O'), + PJMEDIA_EVENT_WND_CLOSED = PJMEDIA_FOURCC('W', 'N', 'C', 'O'), /** * Video window has been resized event. */ - PJMEDIA_EVENT_WND_RESIZED = PJMEDIA_FOURCC('W', 'N', 'R', 'Z'), + PJMEDIA_EVENT_WND_RESIZED = PJMEDIA_FOURCC('W', 'N', 'R', 'Z'), /** * Mouse button has been pressed event. @@ -121,10 +120,10 @@ typedef enum pjmedia_event_type typedef struct pjmedia_event_fmt_changed_data { /** The media flow direction */ - pjmedia_dir dir; + pjmedia_dir dir; /** The new media format. */ - pjmedia_format new_fmt; + pjmedia_format new_fmt; } pjmedia_event_fmt_changed_data; /** @@ -133,7 +132,7 @@ typedef struct pjmedia_event_fmt_changed_data typedef struct pjmedia_event_dummy_data { /** Dummy data */ - int dummy; + int dummy; } pjmedia_event_dummy_data; /** @@ -145,7 +144,7 @@ typedef struct pjmedia_event_wnd_resized_data /** * The new window size. */ - pjmedia_rect_size new_size; + pjmedia_rect_size new_size; } pjmedia_event_wnd_resized_data; /** @@ -154,7 +153,7 @@ typedef struct pjmedia_event_wnd_resized_data typedef struct pjmedia_event_wnd_closing_data { /** Consumer may set this field to PJ_TRUE to cancel the closing */ - pj_bool_t cancel; + pj_bool_t cancel; } pjmedia_event_wnd_closing_data; /** @@ -163,13 +162,13 @@ typedef struct pjmedia_event_wnd_closing_data typedef struct pjmedia_event_aud_dev_err_data { /** The media direction that fails */ - pjmedia_dir dir; + pjmedia_dir dir; /** The audio device ID */ pjmedia_aud_dev_index id; /** The error code */ - pj_status_t status; + pj_status_t status; } pjmedia_event_aud_dev_err_data; @@ -179,13 +178,13 @@ typedef struct pjmedia_event_aud_dev_err_data typedef struct pjmedia_event_vid_dev_err_data { /** The media direction that fails */ - pjmedia_dir dir; + pjmedia_dir dir; /** The video device ID */ pjmedia_vid_dev_index id; /** The error code */ - pj_status_t status; + pj_status_t status; } pjmedia_event_vid_dev_err_data; @@ -194,17 +193,17 @@ typedef struct pjmedia_event_vid_dev_err_data */ typedef struct pjmedia_event_media_tp_err_data { - /** The media type */ - pjmedia_type type; + /** The media type */ + pjmedia_type type; - /** RTP/RTCP? */ - pj_bool_t is_rtp; + /** RTP/RTCP? */ + pj_bool_t is_rtp; - /** Media direction */ - pjmedia_dir dir; + /** Media direction */ + pjmedia_dir dir; - /** The error code */ - pj_status_t status; + /** The error code */ + pj_status_t status; } pjmedia_event_media_tp_err_data; @@ -224,7 +223,7 @@ typedef pjmedia_event_dummy_data pjmedia_event_keyframe_missing_data; /** * Maximum size of additional parameters section in pjmedia_event structure */ -#define PJMEDIA_EVENT_DATA_MAX_SIZE sizeof(pjmedia_event_fmt_changed_data) +#define PJMEDIA_EVENT_DATA_MAX_SIZE sizeof(pjmedia_event_fmt_changed_data) /** Type of storage to hold user data in pjmedia_event structure */ typedef char pjmedia_event_user_data[PJMEDIA_EVENT_DATA_MAX_SIZE]; @@ -240,12 +239,12 @@ typedef struct pjmedia_event /** * The event type. */ - pjmedia_event_type type; + pjmedia_event_type type; /** * The media timestamp when the event occurs. */ - pj_timestamp timestamp; + pj_timestamp timestamp; /** * Pointer information about the source of this event. This field @@ -254,7 +253,7 @@ typedef struct pjmedia_event * pointer for other purpose may require special care such as mutex * locking or checking whether the object is already destroyed. */ - const void *src; + const void *src; /** * Pointer information about the publisher of this event. This field @@ -263,64 +262,64 @@ typedef struct pjmedia_event * pointer for other purpose may require special care such as mutex * locking or checking whether the object is already destroyed. */ - const void *epub; + const void *epub; /** * Additional data/parameters about the event. The type of data * will be specific to the event type being reported. */ union { - /** Media format changed event data. */ - pjmedia_event_fmt_changed_data fmt_changed; + /** Media format changed event data. */ + pjmedia_event_fmt_changed_data fmt_changed; - /** Window resized event data */ - pjmedia_event_wnd_resized_data wnd_resized; + /** Window resized event data */ + pjmedia_event_wnd_resized_data wnd_resized; - /** Window closing event data. */ - pjmedia_event_wnd_closing_data wnd_closing; + /** Window closing event data. */ + pjmedia_event_wnd_closing_data wnd_closing; - /** Window closed event data */ - pjmedia_event_wnd_closed_data wnd_closed; + /** Window closed event data */ + pjmedia_event_wnd_closed_data wnd_closed; - /** Mouse button down event data */ - pjmedia_event_mouse_btn_down_data mouse_btn_down; + /** Mouse button down event data */ + pjmedia_event_mouse_btn_down_data mouse_btn_down; - /** Keyframe found event data */ - pjmedia_event_keyframe_found_data keyframe_found; + /** Keyframe found event data */ + pjmedia_event_keyframe_found_data keyframe_found; - /** Keyframe missing event data */ - pjmedia_event_keyframe_missing_data keyframe_missing; + /** Keyframe missing event data */ + pjmedia_event_keyframe_missing_data keyframe_missing; - /** Audio device error event data */ - pjmedia_event_aud_dev_err_data aud_dev_err; + /** Audio device error event data */ + pjmedia_event_aud_dev_err_data aud_dev_err; - /** Video device error event data */ - pjmedia_event_vid_dev_err_data vid_dev_err; + /** Video device error event data */ + pjmedia_event_vid_dev_err_data vid_dev_err; - /** Storage for user event data */ - pjmedia_event_user_data user; + /** Storage for user event data */ + pjmedia_event_user_data user; - /** Media transport error event data */ - pjmedia_event_media_tp_err_data med_tp_err; + /** Media transport error event data */ + pjmedia_event_media_tp_err_data med_tp_err; - /** Receiving RTCP-FB event data */ - pjmedia_event_rx_rtcp_fb_data rx_rtcp_fb; + /** Receiving RTCP-FB event data */ + pjmedia_event_rx_rtcp_fb_data rx_rtcp_fb; - /** Pointer to storage to user event data, if it's outside - * this struct - */ - void *ptr; + /** Pointer to storage to user event data, if it's outside + * this struct + */ + void *ptr; } data; } pjmedia_event; /** * The callback to receive media events. * - * @param event The media event. - * @param user_data The user data associated with the callback. + * @param event The media event. + * @param user_data The user data associated with the callback. * - * @return If the callback returns non-PJ_SUCCESS, this return - * code may be propagated back to the caller. + * @return If the callback returns non-PJ_SUCCESS, this return + * code may be propagated back to the caller. */ typedef pj_status_t pjmedia_event_cb(pjmedia_event *event, void *user_data); @@ -369,21 +368,21 @@ typedef struct pjmedia_event_mgr pjmedia_event_mgr; * Create a new event manager instance. This will also set the pointer * to the singleton instance if the value is still NULL. * - * @param pool Pool to allocate memory from. + * @param pool Pool to allocate memory from. * @param options Options. Bitmask flags from #pjmedia_event_mgr_flag - * @param mgr Pointer to hold the created instance of the - * event manager. + * @param mgr Pointer to hold the created instance of the + * event manager. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_event_mgr_create(pj_pool_t *pool, unsigned options, - pjmedia_event_mgr **mgr); + pjmedia_event_mgr **mgr); /** * Get the singleton instance of the event manager. * - * @return The instance. + * @return The instance. */ PJ_DECL(pjmedia_event_mgr*) pjmedia_event_mgr_instance(void); @@ -393,9 +392,9 @@ PJ_DECL(pjmedia_event_mgr*) pjmedia_event_mgr_instance(void); * going to be created, as the library automatically assign the singleton * instance. * - * @param mgr The instance to be used as the singleton instance. - * Application may specify NULL to clear the singleton - * singleton instance. + * @param mgr The instance to be used as the singleton instance. + * Application may specify NULL to clear the singleton + * singleton instance. */ PJ_DECL(void) pjmedia_event_mgr_set_instance(pjmedia_event_mgr *mgr); @@ -403,19 +402,19 @@ PJ_DECL(void) pjmedia_event_mgr_set_instance(pjmedia_event_mgr *mgr); * Destroy an event manager. If the manager happens to be the singleton * instance, the singleton instance will be set to NULL. * - * @param mgr The eventmanager. Specify NULL to use - * the singleton instance. + * @param mgr The eventmanager. Specify NULL to use + * the singleton instance. */ PJ_DECL(void) pjmedia_event_mgr_destroy(pjmedia_event_mgr *mgr); /** * Initialize event structure with basic data about the event. * - * @param event The event to be initialized. - * @param type The event type to be set for this event. - * @param ts Event timestamp. May be set to NULL to set the event - * timestamp to zero. - * @param src Event source. + * @param event The event to be initialized. + * @param type The event type to be set for this event. + * @param ts Event timestamp. May be set to NULL to set the event + * timestamp to zero. + * @param src Event source. */ PJ_DECL(void) pjmedia_event_init(pjmedia_event *event, pjmedia_event_type type, @@ -429,13 +428,13 @@ PJ_DECL(void) pjmedia_event_init(pjmedia_event *event, * publishers contained by the publisher, if the publisher is republishing * events from other publishers. * - * @param mgr The event manager. + * @param mgr The event manager. * @param cb The callback function to receive the event. * @param user_data The user data to be associated with the callback * function. - * @param epub The event publisher. + * @param epub The event publisher. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_event_subscribe(pjmedia_event_mgr *mgr, pjmedia_event_cb *cb, @@ -448,13 +447,13 @@ PJ_DECL(pj_status_t) pjmedia_event_subscribe(pjmedia_event_mgr *mgr, * unsubscription for all user data. If the publisher, epub, is not * specified, this function will do the unsubscription from all publishers. * - * @param mgr The event manager. + * @param mgr The event manager. * @param cb The callback function. * @param user_data The user data associated with the callback * function, can be NULL. - * @param epub The event publisher, can be NULL. + * @param epub The event publisher, can be NULL. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_event_unsubscribe(pjmedia_event_mgr *mgr, @@ -470,13 +469,13 @@ pjmedia_event_unsubscribe(pjmedia_event_mgr *mgr, * to the event manager and return immediately. It is the event manager * that will later notify all the publisher's subscribers. * - * @param mgr The event manager. - * @param epub The event publisher. - * @param event The event to be published. + * @param mgr The event manager. + * @param epub The event publisher. + * @param event The event to be published. * @param flag Publication flag. * - * @return PJ_SUCCESS only if all subscription callbacks returned - * PJ_SUCCESS. + * @return PJ_SUCCESS only if all subscription callbacks returned + * PJ_SUCCESS. */ PJ_DECL(pj_status_t) pjmedia_event_publish(pjmedia_event_mgr *mgr, void *epub, @@ -491,4 +490,4 @@ PJ_DECL(pj_status_t) pjmedia_event_publish(pjmedia_event_mgr *mgr, PJ_END_DECL -#endif /* __PJMEDIA_EVENT_H__ */ +#endif /* __PJMEDIA_EVENT_H__ */ diff --git a/pjmedia/include/pjmedia/format.h b/pjmedia/include/pjmedia/format.h index a100e7e298..6c1b2d963a 100644 --- a/pjmedia/include/pjmedia/format.h +++ b/pjmedia/include/pjmedia/format.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -59,31 +58,31 @@ typedef enum pjmedia_format_id */ /** 16bit signed integer linear PCM audio */ - PJMEDIA_FORMAT_L16 = 0, + PJMEDIA_FORMAT_L16 = 0, /** Alias for PJMEDIA_FORMAT_L16 */ - PJMEDIA_FORMAT_PCM = PJMEDIA_FORMAT_L16, + PJMEDIA_FORMAT_PCM = PJMEDIA_FORMAT_L16, /** G.711 ALAW */ - PJMEDIA_FORMAT_PCMA = PJMEDIA_FORMAT_PACK('A', 'L', 'A', 'W'), + PJMEDIA_FORMAT_PCMA = PJMEDIA_FORMAT_PACK('A', 'L', 'A', 'W'), /** Alias for PJMEDIA_FORMAT_PCMA */ - PJMEDIA_FORMAT_ALAW = PJMEDIA_FORMAT_PCMA, + PJMEDIA_FORMAT_ALAW = PJMEDIA_FORMAT_PCMA, /** G.711 ULAW */ - PJMEDIA_FORMAT_PCMU = PJMEDIA_FORMAT_PACK('u', 'L', 'A', 'W'), + PJMEDIA_FORMAT_PCMU = PJMEDIA_FORMAT_PACK('u', 'L', 'A', 'W'), /** Aliaw for PJMEDIA_FORMAT_PCMU */ - PJMEDIA_FORMAT_ULAW = PJMEDIA_FORMAT_PCMU, + PJMEDIA_FORMAT_ULAW = PJMEDIA_FORMAT_PCMU, /** AMR narrowband */ - PJMEDIA_FORMAT_AMR = PJMEDIA_FORMAT_PACK(' ', 'A', 'M', 'R'), + PJMEDIA_FORMAT_AMR = PJMEDIA_FORMAT_PACK(' ', 'A', 'M', 'R'), /** ITU G.729 */ - PJMEDIA_FORMAT_G729 = PJMEDIA_FORMAT_PACK('G', '7', '2', '9'), + PJMEDIA_FORMAT_G729 = PJMEDIA_FORMAT_PACK('G', '7', '2', '9'), /** Internet Low Bit-Rate Codec (ILBC) */ - PJMEDIA_FORMAT_ILBC = PJMEDIA_FORMAT_PACK('I', 'L', 'B', 'C'), + PJMEDIA_FORMAT_ILBC = PJMEDIA_FORMAT_PACK('I', 'L', 'B', 'C'), /* @@ -124,7 +123,7 @@ typedef enum pjmedia_format_id * Y0, A0. Source: * http://msdn.microsoft.com/en-us/library/dd206750%28v=VS.85%29.aspx#ayuv */ - PJMEDIA_FORMAT_AYUV = PJMEDIA_FORMAT_PACK('A', 'Y', 'U', 'V'), + PJMEDIA_FORMAT_AYUV = PJMEDIA_FORMAT_PACK('A', 'Y', 'U', 'V'), /** * This is packed 4:2:2/16bpp YUV format, the data can be treated as @@ -134,7 +133,7 @@ typedef enum pjmedia_format_id * contains the first V (Cr) sample, and so forth. Source: * http://msdn.microsoft.com/en-us/library/dd206750%28v=VS.85%29.aspx#yuy2 */ - PJMEDIA_FORMAT_YUY2 = PJMEDIA_FORMAT_PACK('Y', 'U', 'Y', '2'), + PJMEDIA_FORMAT_YUY2 = PJMEDIA_FORMAT_PACK('Y', 'U', 'Y', '2'), /** * This format is the same as the YUY2 format except the byte order is @@ -144,7 +143,7 @@ typedef enum pjmedia_format_id * WORD contains V in the LSBs and Y1 in the MSBs. Source: * http://msdn.microsoft.com/en-us/library/dd206750%28v=VS.85%29.aspx#uyvy */ - PJMEDIA_FORMAT_UYVY = PJMEDIA_FORMAT_PACK('U', 'Y', 'V', 'Y'), + PJMEDIA_FORMAT_UYVY = PJMEDIA_FORMAT_PACK('U', 'Y', 'V', 'Y'), /** * This format is the same as the YUY2 and UYVY format except the byte @@ -153,7 +152,7 @@ typedef enum pjmedia_format_id * the first WORD contains Y0 in the LSBs and V in the MSBs, and the second * WORD contains Y1 in the LSBs and U in the MSBs. */ - PJMEDIA_FORMAT_YVYU = PJMEDIA_FORMAT_PACK('Y', 'V', 'Y', 'U'), + PJMEDIA_FORMAT_YVYU = PJMEDIA_FORMAT_PACK('Y', 'V', 'Y', 'U'), /** * This is planar 4:2:0/12bpp YUV format, the data can be treated as @@ -161,12 +160,12 @@ typedef enum pjmedia_format_id * only the Y samples, the second plane contains only the U (Cb) samples, * and the third plane contains only the V (Cr) sample. */ - PJMEDIA_FORMAT_I420 = PJMEDIA_FORMAT_PACK('I', '4', '2', '0'), + PJMEDIA_FORMAT_I420 = PJMEDIA_FORMAT_PACK('I', '4', '2', '0'), /** * IYUV is alias for I420. */ - PJMEDIA_FORMAT_IYUV = PJMEDIA_FORMAT_I420, + PJMEDIA_FORMAT_IYUV = PJMEDIA_FORMAT_I420, /** * This is planar 4:2:0/12bpp YUV format, similar to I420 or IYUV but @@ -174,7 +173,7 @@ typedef enum pjmedia_format_id * contains the V (Cb) samples and the third plane contains the V (Cr) * samples. */ - PJMEDIA_FORMAT_YV12 = PJMEDIA_FORMAT_PACK('Y', 'V', '1', '2'), + PJMEDIA_FORMAT_YV12 = PJMEDIA_FORMAT_PACK('Y', 'V', '1', '2'), /** * This is planar 4:2:0/12bpp YUV format, the data can be treated as @@ -182,7 +181,7 @@ typedef enum pjmedia_format_id * only the Y samples, the second plane contains interleaved * U (Cb) - V (Cr) samples. */ - PJMEDIA_FORMAT_NV12 = PJMEDIA_FORMAT_PACK('N', 'V', '1', '2'), + PJMEDIA_FORMAT_NV12 = PJMEDIA_FORMAT_PACK('N', 'V', '1', '2'), /** * This is planar 4:2:0/12bpp YUV format, the data can be treated as @@ -190,7 +189,7 @@ typedef enum pjmedia_format_id * only the Y samples, the second plane contains interleaved * V (Cr) - U (Cb) samples. */ - PJMEDIA_FORMAT_NV21 = PJMEDIA_FORMAT_PACK('N', 'V', '2', '1'), + PJMEDIA_FORMAT_NV21 = PJMEDIA_FORMAT_PACK('N', 'V', '2', '1'), /** * This is planar 4:2:2/16bpp YUV format, the data can be treated as @@ -198,7 +197,7 @@ typedef enum pjmedia_format_id * only the Y samples, the second plane contains only the U (Cb) samples, * and the third plane contains only the V (Cr) sample. */ - PJMEDIA_FORMAT_I422 = PJMEDIA_FORMAT_PACK('I', '4', '2', '2'), + PJMEDIA_FORMAT_I422 = PJMEDIA_FORMAT_PACK('I', '4', '2', '2'), /** * The JPEG version of planar 4:2:0/12bpp YUV format. @@ -257,12 +256,12 @@ typedef enum pjmedia_format_detail_type */ typedef struct pjmedia_audio_format_detail { - unsigned clock_rate; /**< Audio clock rate in samples or Hz. */ - unsigned channel_count; /**< Number of channels. */ - unsigned frame_time_usec;/**< Frame interval, in microseconds. */ - unsigned bits_per_sample;/**< Number of bits per sample. */ - pj_uint32_t avg_bps; /**< Average bitrate */ - pj_uint32_t max_bps; /**< Maximum bitrate */ + unsigned clock_rate; /**< Audio clock rate in samples or Hz. */ + unsigned channel_count; /**< Number of channels. */ + unsigned frame_time_usec;/**< Frame interval, in microseconds. */ + unsigned bits_per_sample;/**< Number of bits per sample. */ + pj_uint32_t avg_bps; /**< Average bitrate */ + pj_uint32_t max_bps; /**< Maximum bitrate */ } pjmedia_audio_format_detail; /** @@ -274,10 +273,10 @@ typedef struct pjmedia_audio_format_detail */ typedef struct pjmedia_video_format_detail { - pjmedia_rect_size size; /**< Video size (width, height) */ - pjmedia_ratio fps; /**< Number of frames per second. */ - pj_uint32_t avg_bps;/**< Average bitrate. */ - pj_uint32_t max_bps;/**< Maximum bitrate. */ + pjmedia_rect_size size; /**< Video size (width, height) */ + pjmedia_ratio fps; /**< Number of frames per second. */ + pj_uint32_t avg_bps;/**< Average bitrate. */ + pj_uint32_t max_bps;/**< Maximum bitrate. */ } pjmedia_video_format_detail; /** @@ -285,7 +284,7 @@ typedef struct pjmedia_video_format_detail * to be reserved for user defined detail. */ #ifndef PJMEDIA_FORMAT_DETAIL_USER_SIZE -# define PJMEDIA_FORMAT_DETAIL_USER_SIZE 1 +# define PJMEDIA_FORMAT_DETAIL_USER_SIZE 1 #endif /** @@ -301,37 +300,37 @@ typedef struct pjmedia_format * * @see pjmedia_format_id */ - pj_uint32_t id; + pj_uint32_t id; /** * The top-most type of the media, as an information. */ - pjmedia_type type; + pjmedia_type type; /** * The type of detail structure in the \a detail pointer. */ - pjmedia_format_detail_type detail_type; + pjmedia_format_detail_type detail_type; /** * Detail section to describe the media. */ union { - /** - * Detail section for audio format. - */ - pjmedia_audio_format_detail aud; - - /** - * Detail section for video format. - */ - pjmedia_video_format_detail vid; - - /** - * Reserved area for user-defined format detail. - */ - char user[PJMEDIA_FORMAT_DETAIL_USER_SIZE]; + /** + * Detail section for audio format. + */ + pjmedia_audio_format_detail aud; + + /** + * Detail section for video format. + */ + pjmedia_video_format_detail vid; + + /** + * Reserved area for user-defined format detail. + */ + char user[PJMEDIA_FORMAT_DETAIL_USER_SIZE]; } det; } pjmedia_format; @@ -367,7 +366,7 @@ typedef struct pjmedia_video_apply_fmt_param * [IN] The image size. This field is mandatory, and has to be set * correctly prior to calling \a apply_fmt() function. */ - pjmedia_rect_size size; + pjmedia_rect_size size; /** * [IN] Pointer to the buffer that holds the frame. The \a apply_fmt() @@ -377,7 +376,7 @@ typedef struct pjmedia_video_apply_fmt_param * correct pointer even though the buffer is set to NULL. This could be * useful to calculate the size (in bytes) of each plane. */ - pj_uint8_t *buffer; + pj_uint8_t *buffer; /* output fields: */ @@ -385,23 +384,23 @@ typedef struct pjmedia_video_apply_fmt_param * [OUT] The size (in bytes) required of the buffer to hold the video * frame of the particular frame size (width, height). */ - pj_size_t framebytes; + pj_size_t framebytes; /** * [OUT] Array of strides value (in bytes) for each video plane. */ - int strides[PJMEDIA_MAX_VIDEO_PLANES]; + int strides[PJMEDIA_MAX_VIDEO_PLANES]; /** * [OUT] Array of pointers to each of the video planes. The values are * calculated from the \a buffer field. */ - pj_uint8_t *planes[PJMEDIA_MAX_VIDEO_PLANES]; + pj_uint8_t *planes[PJMEDIA_MAX_VIDEO_PLANES]; /** * [OUT] Array of video plane sizes. */ - pj_size_t plane_bytes[PJMEDIA_MAX_VIDEO_PLANES]; + pj_size_t plane_bytes[PJMEDIA_MAX_VIDEO_PLANES]; } pjmedia_video_apply_fmt_param; @@ -416,29 +415,29 @@ typedef struct pjmedia_video_format_info * The unique format ID of the media. Well known format ids are declared * in pjmedia_format_id enumeration. */ - pj_uint32_t id; + pj_uint32_t id; /** * Null terminated string containing short identification about the * format. */ - char name[8]; + char name[8]; /** * Information about the color model of this video format. */ - pjmedia_color_model color_model; + pjmedia_color_model color_model; /** * Number of bits needed to store one pixel of this video format. */ - pj_uint8_t bpp; + pj_uint8_t bpp; /** * Number of video planes that this format uses. Value 1 indicates * packed format, while value greater than 1 indicates planar format. */ - pj_uint8_t plane_cnt; + pj_uint8_t plane_cnt; /** * Pointer to function to apply this format against size and buffer @@ -448,14 +447,14 @@ typedef struct pjmedia_video_format_info * location of the planes, and so on. See pjmedia_video_apply_fmt_param * for additional information. * - * @param vfi The video format info. - * @param vafp The parameters to investigate. + * @param vfi The video format info. + * @param vafp The parameters to investigate. * - * @return PJ_SUCCESS if the function has calculated the - * information in \a vafp successfully. + * @return PJ_SUCCESS if the function has calculated the + * information in \a vafp successfully. */ pj_status_t (*apply_fmt)(const struct pjmedia_video_format_info *vfi, - pjmedia_video_apply_fmt_param *vafp); + pjmedia_video_apply_fmt_param *vafp); } pjmedia_video_format_info; @@ -469,23 +468,23 @@ typedef struct pjmedia_video_format_info * rate, ptime (in usec), and channel count. Application should use this * macro whenever possible due to possible overflow in the math calculation. * - * @param clock_rate Clock rate. - * @param usec_ptime Frame interval, in microsecond. - * @param channel_count Number of channels. + * @param clock_rate Clock rate. + * @param usec_ptime Frame interval, in microsecond. + * @param channel_count Number of channels. * - * @return The samples per frame value. + * @return The samples per frame value. */ PJ_INLINE(unsigned) PJMEDIA_SPF(unsigned clock_rate, unsigned usec_ptime, - unsigned channel_count) + unsigned channel_count) { #if PJ_HAS_INT64 return ((unsigned)((pj_uint64_t)usec_ptime * \ - clock_rate * channel_count / 1000000)); + clock_rate * channel_count / 1000000)); #elif PJ_HAS_FLOATING_POINT return ((unsigned)(1.0*usec_ptime * clock_rate * channel_count / 1000000)); #else return ((unsigned)(usec_ptime / 1000L * clock_rate * \ - channel_count / 1000)); + channel_count / 1000)); #endif } @@ -493,11 +492,11 @@ PJ_INLINE(unsigned) PJMEDIA_SPF(unsigned clock_rate, unsigned usec_ptime, * Variant of #PJMEDIA_SPF() which takes frame rate instead of ptime. */ PJ_INLINE(unsigned) PJMEDIA_SPF2(unsigned clock_rate, const pjmedia_ratio *fr, - unsigned channel_count) + unsigned channel_count) { #if PJ_HAS_INT64 return ((unsigned)((pj_uint64_t)clock_rate * fr->denum \ - / fr->num / channel_count)); + / fr->num / channel_count)); #elif PJ_HAS_FLOATING_POINT return ((unsigned)(1.0* clock_rate * fr->denum / fr->num /channel_count)); #else @@ -511,10 +510,10 @@ PJ_INLINE(unsigned) PJMEDIA_SPF2(unsigned clock_rate, const pjmedia_ratio *fr, * interval values. Application should use this macro whenever possible due * to possible overflow in the math calculation. * - * @param bps The bitrate of the stream. - * @param usec_ptime Frame interval, in microsecond. + * @param bps The bitrate of the stream. + * @param usec_ptime Frame interval, in microsecond. * - * @return Frame size in bytes. + * @return Frame size in bytes. */ PJ_INLINE(unsigned) PJMEDIA_FSZ(unsigned bps, unsigned usec_ptime) { @@ -532,15 +531,15 @@ PJ_INLINE(unsigned) PJMEDIA_FSZ(unsigned bps, unsigned usec_ptime) * Application should use this macro whenever possible due to possible * overflow in the math calculation. * - * @param frame_rate Frame rate + * @param frame_rate Frame rate * - * @return The ptime value (in usec). + * @return The ptime value (in usec). */ PJ_INLINE(unsigned) PJMEDIA_PTIME(const pjmedia_ratio *frame_rate) { #if PJ_HAS_INT64 return ((unsigned)((pj_uint64_t)1000000 * \ - frame_rate->denum / frame_rate->num)); + frame_rate->denum / frame_rate->num)); #elif PJ_HAS_FLOATING_POINT return ((unsigned)(1000000.0 * frame_rate->denum / frame_rate->num)); @@ -554,13 +553,13 @@ PJ_INLINE(unsigned) PJMEDIA_PTIME(const pjmedia_ratio *frame_rate) * Utility to retrieve samples_per_frame value from * pjmedia_audio_format_detail. * - * @param pafd Pointer to pjmedia_audio_format_detail - * @return Samples per frame + * @param pafd Pointer to pjmedia_audio_format_detail + * @return Samples per frame */ PJ_INLINE(unsigned) PJMEDIA_AFD_SPF(const pjmedia_audio_format_detail *pafd) { return PJMEDIA_SPF(pafd->clock_rate, pafd->frame_time_usec, - pafd->channel_count); + pafd->channel_count); } /** @@ -568,8 +567,8 @@ PJ_INLINE(unsigned) PJMEDIA_AFD_SPF(const pjmedia_audio_format_detail *pafd) * The average frame size is derived from the average bitrate of the audio * stream. * - * @param afd Pointer to pjmedia_audio_format_detail - * @return Average frame size. + * @param afd Pointer to pjmedia_audio_format_detail + * @return Average frame size. */ PJ_INLINE(unsigned) PJMEDIA_AFD_AVG_FSZ(const pjmedia_audio_format_detail *afd) { @@ -581,8 +580,8 @@ PJ_INLINE(unsigned) PJMEDIA_AFD_AVG_FSZ(const pjmedia_audio_format_detail *afd) * The maximum frame size is derived from the maximum bitrate of the audio * stream. * - * @param afd Pointer to pjmedia_audio_format_detail - * @return Average frame size. + * @param afd Pointer to pjmedia_audio_format_detail + * @return Average frame size. */ PJ_INLINE(unsigned) PJMEDIA_AFD_MAX_FSZ(const pjmedia_audio_format_detail *afd) { @@ -593,23 +592,23 @@ PJ_INLINE(unsigned) PJMEDIA_AFD_MAX_FSZ(const pjmedia_audio_format_detail *afd) /** * Initialize the format as audio format with the specified parameters. * - * @param fmt The format to be initialized. - * @param fmt_id Format ID. See #pjmedia_format_id - * @param clock_rate Audio clock rate. - * @param channel_count Number of channels. - * @param bits_per_sample Number of bits per sample. - * @param frame_time_usec Frame interval, in microsecond. - * @param avg_bps Average bitrate. - * @param max_bps Maximum bitrate. + * @param fmt The format to be initialized. + * @param fmt_id Format ID. See #pjmedia_format_id + * @param clock_rate Audio clock rate. + * @param channel_count Number of channels. + * @param bits_per_sample Number of bits per sample. + * @param frame_time_usec Frame interval, in microsecond. + * @param avg_bps Average bitrate. + * @param max_bps Maximum bitrate. */ PJ_INLINE(void) pjmedia_format_init_audio(pjmedia_format *fmt, - pj_uint32_t fmt_id, - unsigned clock_rate, - unsigned channel_count, - unsigned bits_per_sample, - unsigned frame_time_usec, - pj_uint32_t avg_bps, - pj_uint32_t max_bps) + pj_uint32_t fmt_id, + unsigned clock_rate, + unsigned channel_count, + unsigned bits_per_sample, + unsigned frame_time_usec, + pj_uint32_t avg_bps, + pj_uint32_t max_bps) { /* This function is inlined to avoid build problem due to circular * dependency, i.e: this function is part of pjmedia and is needed @@ -635,64 +634,64 @@ PJ_INLINE(void) pjmedia_format_init_audio(pjmedia_format *fmt, * to consult to a format manager in order to fill in detailed * information about the format. * - * @param fmt The format to be initialised. - * @param fmt_id Format ID. See #pjmedia_format_id - * @param width Image width. - * @param height Image heigth. - * @param fps_num FPS numerator. - * @param fps_denum FPS denumerator. + * @param fmt The format to be initialised. + * @param fmt_id Format ID. See #pjmedia_format_id + * @param width Image width. + * @param height Image heigth. + * @param fps_num FPS numerator. + * @param fps_denum FPS denumerator. */ PJ_DECL(void) pjmedia_format_init_video(pjmedia_format *fmt, - pj_uint32_t fmt_id, - unsigned width, - unsigned height, - unsigned fps_num, - unsigned fps_denum); + pj_uint32_t fmt_id, + unsigned width, + unsigned height, + unsigned fps_num, + unsigned fps_denum); /** * Copy format to another. * - * @param dst The destination format. - * @param src The source format. + * @param dst The destination format. + * @param src The source format. * - * @return Pointer to destination format. + * @return Pointer to destination format. */ PJ_DECL(pjmedia_format*) pjmedia_format_copy(pjmedia_format *dst, - const pjmedia_format *src); + const pjmedia_format *src); /** * Check if the format contains audio format, and retrieve the audio format * detail in the format. * - * @param fmt The format structure. - * @param assert_valid If this is set to non-zero, an assertion will be - * raised if the detail type is not audio or if the - * the detail is NULL. + * @param fmt The format structure. + * @param assert_valid If this is set to non-zero, an assertion will be + * raised if the detail type is not audio or if the + * the detail is NULL. * - * @return The instance of audio format detail in the format - * structure, or NULL if the format doesn't contain - * audio detail. + * @return The instance of audio format detail in the format + * structure, or NULL if the format doesn't contain + * audio detail. */ PJ_DECL(pjmedia_audio_format_detail*) pjmedia_format_get_audio_format_detail(const pjmedia_format *fmt, - pj_bool_t assert_valid); + pj_bool_t assert_valid); /** * Check if the format contains video format, and retrieve the video format * detail in the format. * - * @param fmt The format structure. - * @param assert_valid If this is set to non-zero, an assertion will be - * raised if the detail type is not video or if the - * the detail is NULL. + * @param fmt The format structure. + * @param assert_valid If this is set to non-zero, an assertion will be + * raised if the detail type is not video or if the + * the detail is NULL. * - * @return The instance of video format detail in the format - * structure, or NULL if the format doesn't contain - * video detail. + * @return The instance of video format detail in the format + * structure, or NULL if the format doesn't contain + * video detail. */ PJ_DECL(pjmedia_video_format_detail*) pjmedia_format_get_video_format_detail(const pjmedia_format *fmt, - pj_bool_t assert_valid); + pj_bool_t assert_valid); /***************************************************************************** * FORMAT MANAGEMENT: @@ -711,23 +710,23 @@ typedef struct pjmedia_video_format_mgr pjmedia_video_format_mgr; * Create a new video format manager instance. This will also set the pointer * to the singleton instance if the value is still NULL. * - * @param pool The pool to allocate memory. - * @param max_fmt Maximum number of formats to accommodate. - * @param options Option flags. Must be zero for now. - * @param p_mgr Pointer to hold the created instance. + * @param pool The pool to allocate memory. + * @param max_fmt Maximum number of formats to accommodate. + * @param options Option flags. Must be zero for now. + * @param p_mgr Pointer to hold the created instance. * - * @return PJ_SUCCESS on success, or the appripriate error value. + * @return PJ_SUCCESS on success, or the appripriate error value. */ PJ_DECL(pj_status_t) pjmedia_video_format_mgr_create(pj_pool_t *pool, - unsigned max_fmt, - unsigned options, - pjmedia_video_format_mgr **p_mgr); + unsigned max_fmt, + unsigned options, + pjmedia_video_format_mgr **p_mgr); /** * Get the singleton instance of the video format manager. * - * @return The instance. + * @return The instance. */ PJ_DECL(pjmedia_video_format_mgr*) pjmedia_video_format_mgr_instance(void); @@ -737,9 +736,9 @@ PJ_DECL(pjmedia_video_format_mgr*) pjmedia_video_format_mgr_instance(void); * going to be created, as the library automatically assign the singleton * instance. * - * @param mgr The instance to be used as the singleton instance. - * Application may specify NULL to clear the singleton - * singleton instance. + * @param mgr The instance to be used as the singleton instance. + * Application may specify NULL to clear the singleton + * singleton instance. */ PJ_DECL(void) pjmedia_video_format_mgr_set_instance(pjmedia_video_format_mgr *mgr); @@ -747,18 +746,18 @@ pjmedia_video_format_mgr_set_instance(pjmedia_video_format_mgr *mgr); /** * Retrieve a video format info for the specified format id. * - * @param mgr The video format manager. Specify NULL to use - * the singleton instance (however, a video format - * manager still must have been created prior to - * calling this function). - * @param id The format id which format info is to be - * retrieved. + * @param mgr The video format manager. Specify NULL to use + * the singleton instance (however, a video format + * manager still must have been created prior to + * calling this function). + * @param id The format id which format info is to be + * retrieved. * - * @return The video format info. + * @return The video format info. */ PJ_DECL(const pjmedia_video_format_info*) pjmedia_get_video_format_info(pjmedia_video_format_mgr *mgr, - pj_uint32_t id); + pj_uint32_t id); /** * Register a new video format to the framework. By default, built-in @@ -768,28 +767,28 @@ pjmedia_get_video_format_info(pjmedia_video_format_mgr *mgr, * application to use user defined format id by registering that format * into the framework. * - * @param mgr The video format manager. Specify NULL to use - * the singleton instance (however, a video format - * manager still must have been created prior to - * calling this function). - * @param vfi The video format info to be registered. This - * structure must remain valid until the format - * manager is destroyed. + * @param mgr The video format manager. Specify NULL to use + * the singleton instance (however, a video format + * manager still must have been created prior to + * calling this function). + * @param vfi The video format info to be registered. This + * structure must remain valid until the format + * manager is destroyed. * - * @return PJ_SUCCESS on success, or the appripriate error value. + * @return PJ_SUCCESS on success, or the appripriate error value. */ PJ_DECL(pj_status_t) pjmedia_register_video_format_info(pjmedia_video_format_mgr *mgr, - pjmedia_video_format_info *vfi); + pjmedia_video_format_info *vfi); /** * Destroy a video format manager. If the manager happens to be the singleton * instance, the singleton instance will be set to NULL. * - * @param mgr The video format manager. Specify NULL to use - * the singleton instance (however, a video format - * manager still must have been created prior to - * calling this function). + * @param mgr The video format manager. Specify NULL to use + * the singleton instance (however, a video format + * manager still must have been created prior to + * calling this function). */ PJ_DECL(void) pjmedia_video_format_mgr_destroy(pjmedia_video_format_mgr *mgr); @@ -801,15 +800,15 @@ PJ_DECL(void) pjmedia_video_format_mgr_destroy(pjmedia_video_format_mgr *mgr); /** * Fill video frame buffer with black color. * - * @param fmt The video format. - * @param buf The frame buffer. - * @param buf_size The frame buffer size. + * @param fmt The video format. + * @param buf The frame buffer. + * @param buf_size The frame buffer size. * - * @return PJ_SUCCESS if successfull. + * @return PJ_SUCCESS if successfull. */ PJ_DECL(pj_status_t) pjmedia_video_format_fill_black(const pjmedia_format *fmt, - void *buf, - pj_size_t buf_size); + void *buf, + pj_size_t buf_size); PJ_END_DECL @@ -818,5 +817,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_FORMAT_H__ */ +#endif /* __PJMEDIA_FORMAT_H__ */ diff --git a/pjmedia/include/pjmedia/frame.h b/pjmedia/include/pjmedia/frame.h index 4c5ef67264..b354c3c797 100644 --- a/pjmedia/include/pjmedia/frame.h +++ b/pjmedia/include/pjmedia/frame.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -42,9 +41,9 @@ PJ_BEGIN_DECL */ typedef enum pjmedia_frame_type { - PJMEDIA_FRAME_TYPE_NONE, /**< No frame. */ - PJMEDIA_FRAME_TYPE_AUDIO, /**< Normal audio frame. */ - PJMEDIA_FRAME_TYPE_EXTENDED, /**< Extended audio frame. */ + PJMEDIA_FRAME_TYPE_NONE, /**< No frame. */ + PJMEDIA_FRAME_TYPE_AUDIO, /**< Normal audio frame. */ + PJMEDIA_FRAME_TYPE_EXTENDED, /**< Extended audio frame. */ PJMEDIA_FRAME_TYPE_VIDEO /**< Video frame. */ } pjmedia_frame_type; @@ -55,15 +54,15 @@ typedef enum pjmedia_frame_type */ typedef struct pjmedia_frame { - pjmedia_frame_type type; /**< Frame type. */ - void *buf; /**< Pointer to buffer. */ - pj_size_t size; /**< Frame size in bytes. */ - pj_timestamp timestamp; /**< Frame timestamp. */ - pj_uint32_t bit_info; /**< Bit info of the frame, sample case: - a frame may not exactly start and end - at the octet boundary, so this field - may be used for specifying start & - end bit offset. */ + pjmedia_frame_type type; /**< Frame type. */ + void *buf; /**< Pointer to buffer. */ + pj_size_t size; /**< Frame size in bytes. */ + pj_timestamp timestamp; /**< Frame timestamp. */ + pj_uint32_t bit_info; /**< Bit info of the frame, sample case: + a frame may not exactly start and end + at the octet boundary, so this field + may be used for specifying start & + end bit offset. */ } pjmedia_frame; @@ -83,7 +82,7 @@ typedef struct pjmedia_frame #pragma pack(1) typedef struct pjmedia_frame_ext { - pjmedia_frame base; /**< Base frame info */ + pjmedia_frame base; /**< Base frame info */ pj_uint16_t samples_cnt; /**< Number of samples in this frame */ pj_uint16_t subframe_cnt; /**< Number of (sub)frames in this frame */ @@ -99,8 +98,8 @@ typedef struct pjmedia_frame_ext { */ #pragma pack(1) typedef struct pjmedia_frame_ext_subframe { - pj_uint16_t bitlen; /**< Number of bits in the data */ - pj_uint8_t data[1]; /**< Start of encoded data */ + pj_uint16_t bitlen; /**< Number of bits in the data */ + pj_uint8_t data[1]; /**< Start of encoded data */ } pjmedia_frame_ext_subframe; #pragma pack() @@ -109,11 +108,11 @@ typedef struct pjmedia_frame_ext_subframe { * Copy one frame to another. If the destination frame's size is smaller than * the source frame's, the destination buffer will be truncated. * - * @param src Source frame. - * @param dst Destination frame. + * @param src Source frame. + * @param dst Destination frame. */ PJ_INLINE(void) pjmedia_frame_copy(pjmedia_frame *dst, - const pjmedia_frame *src) + const pjmedia_frame *src) { dst->type = src->type; dst->timestamp = src->timestamp; @@ -125,15 +124,15 @@ PJ_INLINE(void) pjmedia_frame_copy(pjmedia_frame *dst, /** * Append one subframe to #pjmedia_frame_ext. * - * @param frm The #pjmedia_frame_ext. - * @param src Subframe data. - * @param bitlen Length of subframe, in bits. - * @param samples_cnt Number of audio samples in subframe. + * @param frm The #pjmedia_frame_ext. + * @param src Subframe data. + * @param bitlen Length of subframe, in bits. + * @param samples_cnt Number of audio samples in subframe. */ PJ_INLINE(void) pjmedia_frame_ext_append_subframe(pjmedia_frame_ext *frm, - const void *src, - unsigned bitlen, - unsigned samples_cnt) + const void *src, + unsigned bitlen, + unsigned samples_cnt) { pjmedia_frame_ext_subframe *fsub; pj_uint8_t *p; @@ -141,14 +140,14 @@ PJ_INLINE(void) pjmedia_frame_ext_append_subframe(pjmedia_frame_ext *frm, p = (pj_uint8_t*)frm + sizeof(pjmedia_frame_ext); for (i = 0; i < frm->subframe_cnt; ++i) { - fsub = (pjmedia_frame_ext_subframe*) p; - p += sizeof(fsub->bitlen) + ((fsub->bitlen+7) >> 3); + fsub = (pjmedia_frame_ext_subframe*) p; + p += sizeof(fsub->bitlen) + ((fsub->bitlen+7) >> 3); } fsub = (pjmedia_frame_ext_subframe*) p; fsub->bitlen = (pj_uint16_t)bitlen; if (bitlen) - pj_memcpy(fsub->data, src, (bitlen+7) >> 3); + pj_memcpy(fsub->data, src, (bitlen+7) >> 3); frm->subframe_cnt++; frm->samples_cnt = (pj_uint16_t)(frm->samples_cnt + samples_cnt); @@ -157,10 +156,10 @@ PJ_INLINE(void) pjmedia_frame_ext_append_subframe(pjmedia_frame_ext *frm, /** * Get a subframe from #pjmedia_frame_ext. * - * @param frm The #pjmedia_frame_ext. - * @param n Subframe index, zero based. + * @param frm The #pjmedia_frame_ext. + * @param n Subframe index, zero based. * - * @return The n-th subframe, or NULL if n is out-of-range. + * @return The n-th subframe, or NULL if n is out-of-range. */ PJ_INLINE(pjmedia_frame_ext_subframe*) pjmedia_frame_ext_get_subframe(const pjmedia_frame_ext *frm, unsigned n) @@ -168,16 +167,16 @@ pjmedia_frame_ext_get_subframe(const pjmedia_frame_ext *frm, unsigned n) pjmedia_frame_ext_subframe *sf = NULL; if (n < frm->subframe_cnt) { - pj_uint8_t *p; - unsigned i; + pj_uint8_t *p; + unsigned i; - p = (pj_uint8_t*)frm + sizeof(pjmedia_frame_ext); - for (i = 0; i < n; ++i) { - sf = (pjmedia_frame_ext_subframe*) p; - p += sizeof(sf->bitlen) + ((sf->bitlen+7) >> 3); - } + p = (pj_uint8_t*)frm + sizeof(pjmedia_frame_ext); + for (i = 0; i < n; ++i) { + sf = (pjmedia_frame_ext_subframe*) p; + p += sizeof(sf->bitlen) + ((sf->bitlen+7) >> 3); + } - sf = (pjmedia_frame_ext_subframe*) p; + sf = (pjmedia_frame_ext_subframe*) p; } return sf; @@ -186,33 +185,33 @@ pjmedia_frame_ext_get_subframe(const pjmedia_frame_ext *frm, unsigned n) /** * Extract all frame payload to the specified buffer. * - * @param frm The frame. - * @param dst Destination buffer. - * @param maxlen Maximum size to copy (i.e. the size of the - * destination buffer). + * @param frm The frame. + * @param dst Destination buffer. + * @param maxlen Maximum size to copy (i.e. the size of the + * destination buffer). * - * @return Total size of payload copied. + * @return Total size of payload copied. */ PJ_INLINE(unsigned) pjmedia_frame_ext_copy_payload(const pjmedia_frame_ext *frm, - void *dst, - unsigned maxlen) + void *dst, + unsigned maxlen) { unsigned i, copied=0; for (i=0; isubframe_cnt; ++i) { - pjmedia_frame_ext_subframe *sf; - unsigned sz; + pjmedia_frame_ext_subframe *sf; + unsigned sz; - sf = pjmedia_frame_ext_get_subframe(frm, i); - if (!sf) - continue; + sf = pjmedia_frame_ext_get_subframe(frm, i); + if (!sf) + continue; - sz = ((sf->bitlen + 7) >> 3); - if (sz + copied > maxlen) - break; + sz = ((sf->bitlen + 7) >> 3); + if (sz + copied > maxlen) + break; - pj_memcpy(((pj_uint8_t*)dst) + copied, sf->data, sz); - copied += sz; + pj_memcpy(((pj_uint8_t*)dst) + copied, sf->data, sz); + copied += sz; } return copied; } @@ -221,10 +220,10 @@ pjmedia_frame_ext_copy_payload(const pjmedia_frame_ext *frm, /** * Pop out first n subframes from #pjmedia_frame_ext. * - * @param frm The #pjmedia_frame_ext. - * @param n Number of first subframes to be popped out. + * @param frm The #pjmedia_frame_ext. + * @param n Number of first subframes to be popped out. * - * @return PJ_SUCCESS when successful. + * @return PJ_SUCCESS when successful. */ PJ_INLINE(pj_status_t) pjmedia_frame_ext_pop_subframes(pjmedia_frame_ext *frm, unsigned n) @@ -234,20 +233,20 @@ pjmedia_frame_ext_pop_subframes(pjmedia_frame_ext *frm, unsigned n) pj_size_t move_len; if (frm->subframe_cnt <= n) { - frm->subframe_cnt = 0; - frm->samples_cnt = 0; - return PJ_SUCCESS; + frm->subframe_cnt = 0; + frm->samples_cnt = 0; + return PJ_SUCCESS; } move_src = (pj_uint8_t*)pjmedia_frame_ext_get_subframe(frm, n); sf = pjmedia_frame_ext_get_subframe(frm, frm->subframe_cnt-1); move_len = ((pj_uint8_t*)sf - move_src + sizeof(sf->bitlen) + - ((sf->bitlen+7) >> 3)); + ((sf->bitlen+7) >> 3)); pj_memmove((pj_uint8_t*)frm+sizeof(pjmedia_frame_ext), - move_src, move_len); + move_src, move_len); frm->samples_cnt = (pj_uint16_t) - (frm->samples_cnt - n*frm->samples_cnt/frm->subframe_cnt); + (frm->samples_cnt - n*frm->samples_cnt/frm->subframe_cnt); frm->subframe_cnt = (pj_uint16_t) (frm->subframe_cnt - n); return PJ_SUCCESS; @@ -260,8 +259,8 @@ pjmedia_frame_ext_pop_subframes(pjmedia_frame_ext *frm, unsigned n) * by putting this functionality in one place, it enables some. * clever people to optimize this function. * - * @param samples The 16bit PCM samples. - * @param count Number of samples. + * @param samples The 16bit PCM samples. + * @param count Number of samples. */ PJ_INLINE(void) pjmedia_zero_samples(pj_int16_t *samples, unsigned count) { @@ -285,7 +284,7 @@ PJ_INLINE(void) pjmedia_zero_samples(pj_int16_t *samples, unsigned count) * clever people to optimize this function. */ PJ_INLINE(void) pjmedia_copy_samples(pj_int16_t *dst, const pj_int16_t *src, - unsigned count) + unsigned count) { #if 1 pj_memcpy(dst, src, (count<<1)); @@ -296,7 +295,7 @@ PJ_INLINE(void) pjmedia_copy_samples(pj_int16_t *dst, const pj_int16_t *src, unsigned i; count >>= 1; for (i=0; i>= 1; for (i=0; i @@ -63,9 +62,9 @@ PJ_BEGIN_DECL * Initialize and register G711 codec factory to pjmedia endpoint. * This will register PCMU and PCMA codec, in that order. * - * @param endpt The pjmedia endpoint. + * @param endpt The pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_g711_init(pjmedia_endpt *endpt); @@ -74,7 +73,7 @@ PJ_DECL(pj_status_t) pjmedia_codec_g711_init(pjmedia_endpt *endpt); /** * Unregister G711 codec factory from pjmedia endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_codec_g711_deinit(void); @@ -85,5 +84,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_G711_H__ */ +#endif /* __PJMEDIA_G711_H__ */ diff --git a/pjmedia/include/pjmedia/jbuf.h b/pjmedia/include/pjmedia/jbuf.h index 9ae893aaed..25b01f48e8 100644 --- a/pjmedia/include/pjmedia/jbuf.h +++ b/pjmedia/include/pjmedia/jbuf.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -50,12 +49,12 @@ PJ_BEGIN_DECL */ typedef enum pjmedia_jb_frame_type { - PJMEDIA_JB_MISSING_FRAME = 0, /**< No frame because it's missing */ - PJMEDIA_JB_NORMAL_FRAME = 1, /**< Normal frame is being returned */ + PJMEDIA_JB_MISSING_FRAME = 0, /**< No frame because it's missing */ + PJMEDIA_JB_NORMAL_FRAME = 1, /**< Normal frame is being returned */ PJMEDIA_JB_ZERO_PREFETCH_FRAME = 2, /**< Zero frame is being returned - because JB is bufferring. */ - PJMEDIA_JB_ZERO_EMPTY_FRAME = 3 /**< Zero frame is being returned - because JB is empty. */ + because JB is bufferring. */ + PJMEDIA_JB_ZERO_EMPTY_FRAME = 3 /**< Zero frame is being returned + because JB is empty. */ } pjmedia_jb_frame_type; @@ -72,7 +71,7 @@ typedef enum pjmedia_jb_discard_algo * buffer is full and a new frame arrives, one frame will be discarded * to make space for the new frame. */ - PJMEDIA_JB_DISCARD_NONE = 0, + PJMEDIA_JB_DISCARD_NONE = 0, /** * Only discard one frame in at least 200ms when the latency is considered @@ -99,25 +98,25 @@ typedef enum pjmedia_jb_discard_algo typedef struct pjmedia_jb_state { /* Setting */ - unsigned frame_size; /**< Individual frame size, in bytes. */ - unsigned min_prefetch; /**< Minimum allowed prefetch, in frms. */ - unsigned max_prefetch; /**< Maximum allowed prefetch, in frms. */ - unsigned max_count; /**< Jitter buffer capacity, in frames. */ + unsigned frame_size; /**< Individual frame size, in bytes. */ + unsigned min_prefetch; /**< Minimum allowed prefetch, in frms. */ + unsigned max_prefetch; /**< Maximum allowed prefetch, in frms. */ + unsigned max_count; /**< Jitter buffer capacity, in frames. */ /* Status */ - unsigned burst; /**< Current burst level, in frames */ - unsigned prefetch; /**< Current prefetch value, in frames */ - unsigned size; /**< Current buffer size, in frames. */ + unsigned burst; /**< Current burst level, in frames */ + unsigned prefetch; /**< Current prefetch value, in frames */ + unsigned size; /**< Current buffer size, in frames. */ /* Statistic */ - unsigned avg_delay; /**< Average delay, in ms. */ - unsigned min_delay; /**< Minimum delay, in ms. */ - unsigned max_delay; /**< Maximum delay, in ms. */ - unsigned dev_delay; /**< Standard deviation of delay, in ms.*/ - unsigned avg_burst; /**< Average burst, in frames. */ - unsigned lost; /**< Number of lost frames. */ - unsigned discard; /**< Number of discarded frames. */ - unsigned empty; /**< Number of empty on GET events. */ + unsigned avg_delay; /**< Average delay, in ms. */ + unsigned min_delay; /**< Minimum delay, in ms. */ + unsigned max_delay; /**< Maximum delay, in ms. */ + unsigned dev_delay; /**< Standard deviation of delay, in ms.*/ + unsigned avg_burst; /**< Average burst, in frames. */ + unsigned lost; /**< Number of lost frames. */ + unsigned discard; /**< Number of discarded frames. */ + unsigned empty; /**< Number of empty on GET events. */ } pjmedia_jb_state; @@ -143,98 +142,98 @@ typedef struct pjmedia_jbuf pjmedia_jbuf; * This function may allocate large chunk of memory to keep the frames in * the buffer. * - * @param pool The pool to allocate memory. - * @param name Name to identify the jitter buffer for logging - * purpose. - * @param frame_size The size of each frame that will be kept in the - * jitter buffer, in bytes. This should correspond - * to the minimum frame size supported by the codec. - * For example, a 10ms frame (80 bytes) would be - * recommended for G.711 codec. - * @param max_count Maximum number of frames that can be kept in the - * jitter buffer. This effectively means the maximum - * delay that may be introduced by this jitter - * buffer. - * @param ptime Indication of frame duration, used to calculate - * the interval between jitter recalculation. - * @param p_jb Pointer to receive jitter buffer instance. - * - * @return PJ_SUCCESS on success. + * @param pool The pool to allocate memory. + * @param name Name to identify the jitter buffer for logging + * purpose. + * @param frame_size The size of each frame that will be kept in the + * jitter buffer, in bytes. This should correspond + * to the minimum frame size supported by the codec. + * For example, a 10ms frame (80 bytes) would be + * recommended for G.711 codec. + * @param max_count Maximum number of frames that can be kept in the + * jitter buffer. This effectively means the maximum + * delay that may be introduced by this jitter + * buffer. + * @param ptime Indication of frame duration, used to calculate + * the interval between jitter recalculation. + * @param p_jb Pointer to receive jitter buffer instance. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_jbuf_create(pj_pool_t *pool, - const pj_str_t *name, - unsigned frame_size, - unsigned ptime, - unsigned max_count, - pjmedia_jbuf **p_jb); + const pj_str_t *name, + unsigned frame_size, + unsigned ptime, + unsigned max_count, + pjmedia_jbuf **p_jb); /** * Set the jitter buffer's frame duration. * - * @param jb The jitter buffer - * @param ptime Frame duration. + * @param jb The jitter buffer + * @param ptime Frame duration. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_jbuf_set_ptime( pjmedia_jbuf *jb, - unsigned ptime); + unsigned ptime); /** * Set the jitter buffer to fixed delay mode. The default behavior * is to adapt the delay with actual packet delay. * - * @param jb The jitter buffer - * @param prefetch The fixed delay value, in number of frames. + * @param jb The jitter buffer + * @param prefetch The fixed delay value, in number of frames. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_jbuf_set_fixed( pjmedia_jbuf *jb, - unsigned prefetch); + unsigned prefetch); /** * Set the jitter buffer to adaptive mode. * - * @param jb The jitter buffer. - * @param prefetch The initial prefetch value to be applied to the - * jitter buffer. Setting this to other than 0 will - * activate prefetch buffering, a jitter buffer feature - * that each time it gets empty, it won't return a - * normal frame until its size reaches the number - * specified here. - * @param min_prefetch The minimum delay that must be applied to each - * incoming packets, in number of frames. - * @param max_prefetch The maximum allowable value for prefetch delay, - * in number of frames. - * - * @return PJ_SUCCESS on success. + * @param jb The jitter buffer. + * @param prefetch The initial prefetch value to be applied to the + * jitter buffer. Setting this to other than 0 will + * activate prefetch buffering, a jitter buffer feature + * that each time it gets empty, it won't return a + * normal frame until its size reaches the number + * specified here. + * @param min_prefetch The minimum delay that must be applied to each + * incoming packets, in number of frames. + * @param max_prefetch The maximum allowable value for prefetch delay, + * in number of frames. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_jbuf_set_adaptive( pjmedia_jbuf *jb, - unsigned prefetch, - unsigned min_prefetch, - unsigned max_prefetch); + unsigned prefetch, + unsigned min_prefetch, + unsigned max_prefetch); /** * Set the jitter buffer discard algorithm. The default discard algorithm, * set in jitter buffer creation, is PJMEDIA_JB_DISCARD_PROGRESSIVE. * - * @param jb The jitter buffer. - * @param algo The discard algorithm to be used. + * @param jb The jitter buffer. + * @param algo The discard algorithm to be used. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_jbuf_set_discard(pjmedia_jbuf *jb, - pjmedia_jb_discard_algo algo); + pjmedia_jb_discard_algo algo); /** * Destroy jitter buffer instance. * - * @param jb The jitter buffer. + * @param jb The jitter buffer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_jbuf_destroy(pjmedia_jbuf *jb); @@ -243,9 +242,9 @@ PJ_DECL(pj_status_t) pjmedia_jbuf_destroy(pjmedia_jbuf *jb); * Restart jitter. This function flushes all packets in the buffer and * reset the internal sequence number. * - * @param jb The jitter buffer. + * @param jb The jitter buffer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_jbuf_reset(pjmedia_jbuf *jb); @@ -257,16 +256,16 @@ PJ_DECL(pj_status_t) pjmedia_jbuf_reset(pjmedia_jbuf *jb); * Application MUST manage it's own synchronization when multiple threads * are accessing the jitter buffer at the same time. * - * @param jb The jitter buffer. - * @param frame Pointer to frame buffer to be stored in the jitter - * buffer. - * @param size The frame size. - * @param frame_seq The frame sequence number. + * @param jb The jitter buffer. + * @param frame Pointer to frame buffer to be stored in the jitter + * buffer. + * @param size The frame size. + * @param frame_seq The frame sequence number. */ PJ_DECL(void) pjmedia_jbuf_put_frame( pjmedia_jbuf *jb, - const void *frame, - pj_size_t size, - int frame_seq); + const void *frame, + pj_size_t size, + int frame_seq); /** * Put a frame to the jitter buffer. If the frame can be accepted (based @@ -276,23 +275,23 @@ PJ_DECL(void) pjmedia_jbuf_put_frame( pjmedia_jbuf *jb, * Application MUST manage it's own synchronization when multiple threads * are accessing the jitter buffer at the same time. * - * @param jb The jitter buffer. - * @param frame Pointer to frame buffer to be stored in the jitter - * buffer. - * @param size The frame size. - * @param bit_info Bit precise info of the frame, e.g: a frame may not - * exactly start and end at the octet boundary, so this - * field may be used for specifying start & end bit - * offset. - * @param frame_seq The frame sequence number. - * @param discarded Flag whether the frame is discarded by jitter buffer. + * @param jb The jitter buffer. + * @param frame Pointer to frame buffer to be stored in the jitter + * buffer. + * @param size The frame size. + * @param bit_info Bit precise info of the frame, e.g: a frame may not + * exactly start and end at the octet boundary, so this + * field may be used for specifying start & end bit + * offset. + * @param frame_seq The frame sequence number. + * @param discarded Flag whether the frame is discarded by jitter buffer. */ PJ_DECL(void) pjmedia_jbuf_put_frame2( pjmedia_jbuf *jb, - const void *frame, - pj_size_t size, - pj_uint32_t bit_info, - int frame_seq, - pj_bool_t *discarded); + const void *frame, + pj_size_t size, + pj_uint32_t bit_info, + int frame_seq, + pj_bool_t *discarded); /** * Put a frame to the jitter buffer. If the frame can be accepted (based @@ -302,25 +301,25 @@ PJ_DECL(void) pjmedia_jbuf_put_frame2( pjmedia_jbuf *jb, * Application MUST manage it's own synchronization when multiple threads * are accessing the jitter buffer at the same time. * - * @param jb The jitter buffer. - * @param frame Pointer to frame buffer to be stored in the jitter - * buffer. - * @param size The frame size. - * @param bit_info Bit precise info of the frame, e.g: a frame may not - * exactly start and end at the octet boundary, so this - * field may be used for specifying start & end bit - * offset. - * @param frame_seq The frame sequence number. - * @param frame_ts The frame timestamp. - * @param discarded Flag whether the frame is discarded by jitter buffer. + * @param jb The jitter buffer. + * @param frame Pointer to frame buffer to be stored in the jitter + * buffer. + * @param size The frame size. + * @param bit_info Bit precise info of the frame, e.g: a frame may not + * exactly start and end at the octet boundary, so this + * field may be used for specifying start & end bit + * offset. + * @param frame_seq The frame sequence number. + * @param frame_ts The frame timestamp. + * @param discarded Flag whether the frame is discarded by jitter buffer. */ PJ_DECL(void) pjmedia_jbuf_put_frame3( pjmedia_jbuf *jb, - const void *frame, - pj_size_t size, - pj_uint32_t bit_info, - int frame_seq, - pj_uint32_t frame_ts, - pj_bool_t *discarded); + const void *frame, + pj_size_t size, + pj_uint32_t bit_info, + int frame_seq, + pj_uint32_t frame_ts, + pj_bool_t *discarded); /** * Get a frame from the jitter buffer. The jitter buffer will return the * oldest frame from it's buffer, when it is available. @@ -328,123 +327,123 @@ PJ_DECL(void) pjmedia_jbuf_put_frame3( pjmedia_jbuf *jb, * Application MUST manage it's own synchronization when multiple threads * are accessing the jitter buffer at the same time. * - * @param jb The jitter buffer. - * @param frame Buffer to receive the payload from the jitter buffer. - * Application MUST make sure that the buffer has - * appropriate size (i.e. not less than the frame size, - * as specified when the jitter buffer was created). - * The jitter buffer only copied a frame to this - * buffer when the frame type returned by this function - * is PJMEDIA_JB_NORMAL_FRAME. - * @param p_frm_type Pointer to receive frame type. If jitter buffer is - * currently empty or bufferring, the frame type will - * be set to PJMEDIA_JB_ZERO_FRAME, and no frame will - * be copied. If the jitter buffer detects that frame is - * missing with current sequence number, the frame type - * will be set to PJMEDIA_JB_MISSING_FRAME, and no - * frame will be copied. If there is a frame, the jitter - * buffer will copy the frame to the buffer, and frame - * type will be set to PJMEDIA_JB_NORMAL_FRAME. + * @param jb The jitter buffer. + * @param frame Buffer to receive the payload from the jitter buffer. + * Application MUST make sure that the buffer has + * appropriate size (i.e. not less than the frame size, + * as specified when the jitter buffer was created). + * The jitter buffer only copied a frame to this + * buffer when the frame type returned by this function + * is PJMEDIA_JB_NORMAL_FRAME. + * @param p_frm_type Pointer to receive frame type. If jitter buffer is + * currently empty or bufferring, the frame type will + * be set to PJMEDIA_JB_ZERO_FRAME, and no frame will + * be copied. If the jitter buffer detects that frame is + * missing with current sequence number, the frame type + * will be set to PJMEDIA_JB_MISSING_FRAME, and no + * frame will be copied. If there is a frame, the jitter + * buffer will copy the frame to the buffer, and frame + * type will be set to PJMEDIA_JB_NORMAL_FRAME. */ PJ_DECL(void) pjmedia_jbuf_get_frame( pjmedia_jbuf *jb, - void *frame, - char *p_frm_type); + void *frame, + char *p_frm_type); /** * Get a frame from the jitter buffer. The jitter buffer will return the * oldest frame from it's buffer, when it is available. * - * @param jb The jitter buffer. - * @param frame Buffer to receive the payload from the jitter buffer. - * @see pjmedia_jbuf_get_frame(). - * @param size On input, it points to maximum buffer length. - * On output, it will be filled with received frame size. - * @param p_frm_type Pointer to receive frame type. - * @see pjmedia_jbuf_get_frame(). - * @param bit_info Bit precise info of the frame, e.g: a frame may not - * exactly start and end at the octet boundary, so this - * field may be used for specifying start & end bit - * offset. + * @param jb The jitter buffer. + * @param frame Buffer to receive the payload from the jitter buffer. + * @see pjmedia_jbuf_get_frame(). + * @param size On input, it points to maximum buffer length. + * On output, it will be filled with received frame size. + * @param p_frm_type Pointer to receive frame type. + * @see pjmedia_jbuf_get_frame(). + * @param bit_info Bit precise info of the frame, e.g: a frame may not + * exactly start and end at the octet boundary, so this + * field may be used for specifying start & end bit + * offset. */ PJ_DECL(void) pjmedia_jbuf_get_frame2(pjmedia_jbuf *jb, - void *frame, - pj_size_t *size, - char *p_frm_type, - pj_uint32_t *bit_info); + void *frame, + pj_size_t *size, + char *p_frm_type, + pj_uint32_t *bit_info); /** * Get a frame from the jitter buffer. The jitter buffer will return the * oldest frame from it's buffer, when it is available. * - * @param jb The jitter buffer. - * @param frame Buffer to receive the payload from the jitter buffer. - * @see pjmedia_jbuf_get_frame(). - * @param size On input, it points to maximum buffer length. - * On output, it will be filled with received frame size. - * @param p_frm_type Pointer to receive frame type. - * @see pjmedia_jbuf_get_frame(). - * @param bit_info Bit precise info of the frame, e.g: a frame may not - * exactly start and end at the octet boundary, so this - * field may be used for specifying start & end bit - * offset. - * @param ts Frame timestamp. - * @param seq Frame sequence number. + * @param jb The jitter buffer. + * @param frame Buffer to receive the payload from the jitter buffer. + * @see pjmedia_jbuf_get_frame(). + * @param size On input, it points to maximum buffer length. + * On output, it will be filled with received frame size. + * @param p_frm_type Pointer to receive frame type. + * @see pjmedia_jbuf_get_frame(). + * @param bit_info Bit precise info of the frame, e.g: a frame may not + * exactly start and end at the octet boundary, so this + * field may be used for specifying start & end bit + * offset. + * @param ts Frame timestamp. + * @param seq Frame sequence number. */ PJ_DECL(void) pjmedia_jbuf_get_frame3(pjmedia_jbuf *jb, - void *frame, - pj_size_t *size, - char *p_frm_type, - pj_uint32_t *bit_info, - pj_uint32_t *ts, - int *seq); + void *frame, + pj_size_t *size, + char *p_frm_type, + pj_uint32_t *bit_info, + pj_uint32_t *ts, + int *seq); /** * Peek a frame from the jitter buffer. The jitter buffer state will not be * modified. * - * @param jb The jitter buffer. - * @param offset Offset from the oldest frame to be peeked. - * @param frame Buffer to receive the payload from the jitter buffer. - * @see pjmedia_jbuf_get_frame(). - * @param size Pointer to receive frame size. - * @param p_frm_type Pointer to receive frame type. - * @see pjmedia_jbuf_get_frame(). - * @param bit_info Bit precise info of the frame, e.g: a frame may not - * exactly start and end at the octet boundary, so this - * field may be used for specifying start & end bit - * offset. - * @param ts Frame timestamp. - * @param seq Frame sequence number. + * @param jb The jitter buffer. + * @param offset Offset from the oldest frame to be peeked. + * @param frame Buffer to receive the payload from the jitter buffer. + * @see pjmedia_jbuf_get_frame(). + * @param size Pointer to receive frame size. + * @param p_frm_type Pointer to receive frame type. + * @see pjmedia_jbuf_get_frame(). + * @param bit_info Bit precise info of the frame, e.g: a frame may not + * exactly start and end at the octet boundary, so this + * field may be used for specifying start & end bit + * offset. + * @param ts Frame timestamp. + * @param seq Frame sequence number. */ PJ_DECL(void) pjmedia_jbuf_peek_frame(pjmedia_jbuf *jb, - unsigned offset, - const void **frame, - pj_size_t *size, - char *p_frm_type, - pj_uint32_t *bit_info, - pj_uint32_t *ts, - int *seq); + unsigned offset, + const void **frame, + pj_size_t *size, + char *p_frm_type, + pj_uint32_t *bit_info, + pj_uint32_t *ts, + int *seq); /** * Remove frames from the jitter buffer. * - * @param jb The jitter buffer. - * @param frame_cnt Number of frames to be removed. + * @param jb The jitter buffer. + * @param frame_cnt Number of frames to be removed. * - * @return The number of frame successfully removed. + * @return The number of frame successfully removed. */ PJ_DECL(unsigned) pjmedia_jbuf_remove_frame(pjmedia_jbuf *jb, - unsigned frame_cnt); + unsigned frame_cnt); /** * Check if the jitter buffer is full. * - * @param jb The jitter buffer. + * @param jb The jitter buffer. * - * @return PJ_TRUE if it is full. + * @return PJ_TRUE if it is full. */ PJ_DECL(pj_bool_t) pjmedia_jbuf_is_full(const pjmedia_jbuf *jb); @@ -452,13 +451,13 @@ PJ_DECL(pj_bool_t) pjmedia_jbuf_is_full(const pjmedia_jbuf *jb); /** * Get jitter buffer current state/settings. * - * @param jb The jitter buffer. - * @param state Buffer to receive jitter buffer state. + * @param jb The jitter buffer. + * @param state Buffer to receive jitter buffer state. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_jbuf_get_state( const pjmedia_jbuf *jb, - pjmedia_jb_state *state ); + pjmedia_jb_state *state ); @@ -468,4 +467,4 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_JBUF_H__ */ +#endif /* __PJMEDIA_JBUF_H__ */ diff --git a/pjmedia/include/pjmedia/master_port.h b/pjmedia/include/pjmedia/master_port.h index 58f21c40a9..fb0a8f9122 100644 --- a/pjmedia/include/pjmedia/master_port.h +++ b/pjmedia/include/pjmedia/master_port.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -69,28 +68,28 @@ typedef struct pjmedia_master_port pjmedia_master_port; /** * Create a master port. * - * @param pool Pool to allocate master port from. - * @param u_port Upstream port. - * @param d_port Downstream port. - * @param options Options flags, from bitmask combinations from - * pjmedia_clock_options. - * @param p_m Pointer to receive the master port instance. + * @param pool Pool to allocate master port from. + * @param u_port Upstream port. + * @param d_port Downstream port. + * @param options Options flags, from bitmask combinations from + * pjmedia_clock_options. + * @param p_m Pointer to receive the master port instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_master_port_create(pj_pool_t *pool, - pjmedia_port *u_port, - pjmedia_port *d_port, - unsigned options, - pjmedia_master_port **p_m); + pjmedia_port *u_port, + pjmedia_port *d_port, + unsigned options, + pjmedia_master_port **p_m); /** * Start the media flow. * - * @param m The master port. + * @param m The master port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_master_port_start(pjmedia_master_port *m); @@ -98,9 +97,9 @@ PJ_DECL(pj_status_t) pjmedia_master_port_start(pjmedia_master_port *m); /** * Stop the media flow. * - * @param m The master port. + * @param m The master port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_master_port_stop(pjmedia_master_port *m); @@ -110,19 +109,19 @@ PJ_DECL(pj_status_t) pjmedia_master_port_stop(pjmedia_master_port *m); * elapsed. This operation is only valid if the master port is created with * #PJMEDIA_CLOCK_NO_ASYNC flag. * - * @param m The master port. - * @param wait If non-zero, then the function will block until - * a clock tick elapsed and callback has been called. - * @param ts Optional argument to receive the current - * timestamp. + * @param m The master port. + * @param wait If non-zero, then the function will block until + * a clock tick elapsed and callback has been called. + * @param ts Optional argument to receive the current + * timestamp. * - * @return Non-zero if clock tick has elapsed, or FALSE if - * the function returns before a clock tick has - * elapsed. + * @return Non-zero if clock tick has elapsed, or FALSE if + * the function returns before a clock tick has + * elapsed. */ PJ_DECL(pj_bool_t) pjmedia_master_port_wait(pjmedia_master_port *m, - pj_bool_t wait, - pj_timestamp *ts); + pj_bool_t wait, + pj_timestamp *ts); /** @@ -130,21 +129,21 @@ PJ_DECL(pj_bool_t) pjmedia_master_port_wait(pjmedia_master_port *m, * current upstream port (the one that is going to be replaced with the * new port). * - * @param m The master port. - * @param port Port to be used for upstream port. + * @param m The master port. + * @param port Port to be used for upstream port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_master_port_set_uport(pjmedia_master_port *m, - pjmedia_port *port); + pjmedia_port *port); /** * Get the upstream port. * - * @param m The master port. + * @param m The master port. * - * @return The upstream port. + * @return The upstream port. */ PJ_DECL(pjmedia_port*) pjmedia_master_port_get_uport(pjmedia_master_port*m); @@ -154,21 +153,21 @@ PJ_DECL(pjmedia_port*) pjmedia_master_port_get_uport(pjmedia_master_port*m); * current downstream port (the one that is going to be replaced with the * new port). * - * @param m The master port. - * @param port Port to be used for downstream port. + * @param m The master port. + * @param port Port to be used for downstream port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_master_port_set_dport(pjmedia_master_port *m, - pjmedia_port *port); + pjmedia_port *port); /** * Get the downstream port. * - * @param m The master port. + * @param m The master port. * - * @return The downstream port. + * @return The downstream port. */ PJ_DECL(pjmedia_port*) pjmedia_master_port_get_dport(pjmedia_master_port*m); @@ -177,14 +176,14 @@ PJ_DECL(pjmedia_port*) pjmedia_master_port_get_dport(pjmedia_master_port*m); * Destroy the master port, and optionally destroy the upstream and * downstream ports. * - * @param m The master port. - * @param destroy_ports If non-zero, the function will destroy both - * upstream and downstream ports too. + * @param m The master port. + * @param destroy_ports If non-zero, the function will destroy both + * upstream and downstream ports too. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_master_port_destroy(pjmedia_master_port *m, - pj_bool_t destroy_ports); + pj_bool_t destroy_ports); @@ -195,5 +194,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_MASTER_PORT_H__ */ +#endif /* __PJMEDIA_MASTER_PORT_H__ */ diff --git a/pjmedia/include/pjmedia/mem_port.h b/pjmedia/include/pjmedia/mem_port.h index 0a9bd772ea..2f938e9f51 100644 --- a/pjmedia/include/pjmedia/mem_port.h +++ b/pjmedia/include/pjmedia/mem_port.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -59,31 +58,31 @@ enum pjmedia_mem_player_option * Create the buffer based playback to play the media from the specified * buffer. * - * @param pool Pool to allocate memory for the port structure. - * @param buffer The buffer to play the media from, which should - * be available throughout the life time of the port. - * The player plays the media directly from this - * buffer (i.e. no copying is done). - * @param size The size of the buffer, in bytes. - * @param clock_rate Sampling rate. - * @param channel_count Number of channels. + * @param pool Pool to allocate memory for the port structure. + * @param buffer The buffer to play the media from, which should + * be available throughout the life time of the port. + * The player plays the media directly from this + * buffer (i.e. no copying is done). + * @param size The size of the buffer, in bytes. + * @param clock_rate Sampling rate. + * @param channel_count Number of channels. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Number of bits per sample. - * @param options Option flags, see #pjmedia_mem_player_option - * @param p_port Pointer to receive the port instance. + * @param options Option flags, see #pjmedia_mem_player_option + * @param p_port Pointer to receive the port instance. * - * @return PJ_SUCCESS on success, or the appropriate - * error code. + * @return PJ_SUCCESS on success, or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_mem_player_create(pj_pool_t *pool, - const void *buffer, - pj_size_t size, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_port **p_port ); + const void *buffer, + pj_size_t size, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_port **p_port ); #if !DEPRECATED_FOR_TICKET_2251 @@ -93,20 +92,20 @@ PJ_DECL(pj_status_t) pjmedia_mem_player_create(pj_pool_t *pool, * will be called multiple times. Note that only one callback can be * registered for each player port. * - * @param port The memory player port. - * @param user_data User data to be specified in the callback - * @param cb Callback to be called. If the callback returns non- - * PJ_SUCCESS, the playback will stop. Note that if - * application destroys the player port in the callback, - * it must return non-PJ_SUCCESS here. + * @param port The memory player port. + * @param user_data User data to be specified in the callback + * @param cb Callback to be called. If the callback returns non- + * PJ_SUCCESS, the playback will stop. Note that if + * application destroys the player port in the callback, + * it must return non-PJ_SUCCESS here. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_mem_player_set_eof_cb( pjmedia_port *port, - void *user_data, - pj_status_t (*cb)(pjmedia_port *port, - void *usr_data)); + void *user_data, + pj_status_t (*cb)(pjmedia_port *port, + void *usr_data)); #endif @@ -116,21 +115,21 @@ pjmedia_mem_player_set_eof_cb( pjmedia_port *port, * will be called multiple times. Note that only one callback can be * registered for each player port. * - * @param port The memory player port. - * @param user_data User data to be specified in the callback - * @param cb Callback to be called. Note that if - * application wishes to stop the playback, it - * can disconnect the port in the callback, and - * only after all connections have been removed - * could the application safely destroy the port. + * @param port The memory player port. + * @param user_data User data to be specified in the callback + * @param cb Callback to be called. Note that if + * application wishes to stop the playback, it + * can disconnect the port in the callback, and + * only after all connections have been removed + * could the application safely destroy the port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_mem_player_set_eof_cb2(pjmedia_port *port, - void *user_data, - void (*cb)(pjmedia_port *port, - void *usr_data)); + void *user_data, + void (*cb)(pjmedia_port *port, + void *usr_data)); /** * @} @@ -150,29 +149,29 @@ pjmedia_mem_player_set_eof_cb2(pjmedia_port *port, /** * Create media port to capture/record media into a fixed size buffer. * - * @param pool Pool to allocate memory for the port structure. - * @param buffer The buffer to record the media to, which should - * be available throughout the life time of the port. - * @param size The maximum size of the buffer, in bytes. - * @param clock_rate Sampling rate. - * @param channel_count Number of channels. + * @param pool Pool to allocate memory for the port structure. + * @param buffer The buffer to record the media to, which should + * be available throughout the life time of the port. + * @param size The maximum size of the buffer, in bytes. + * @param clock_rate Sampling rate. + * @param channel_count Number of channels. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Number of bits per sample. - * @param options Option flags. - * @param p_port Pointer to receive the port instance. + * @param options Option flags. + * @param p_port Pointer to receive the port instance. * - * @return PJ_SUCCESS on success, or the appropriate - * error code. + * @return PJ_SUCCESS on success, or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_mem_capture_create(pj_pool_t *pool, - void *buffer, - pj_size_t size, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_port **p_port); + void *buffer, + pj_size_t size, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_port **p_port); #if !DEPRECATED_FOR_TICKET_2251 @@ -182,51 +181,51 @@ PJ_DECL(pj_status_t) pjmedia_mem_capture_create(pj_pool_t *pool, * called when application destroys the port and the callback has not * been called before. * - * @param port The memory recorder port. - * @param user_data User data to be specified in the callback - * @param cb Callback to be called. If the callback returns non- - * PJ_SUCCESS, the recording will stop. In other cases + * @param port The memory recorder port. + * @param user_data User data to be specified in the callback + * @param cb Callback to be called. If the callback returns non- + * PJ_SUCCESS, the recording will stop. In other cases * recording will be restarted and the rest of the frame * will be stored starting from the beginning of the - * buffer. Note that if application destroys the capture - * port in the callback, it must return non-PJ_SUCCESS - * here. + * buffer. Note that if application destroys the capture + * port in the callback, it must return non-PJ_SUCCESS + * here. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_mem_capture_set_eof_cb(pjmedia_port *port, void *user_data, pj_status_t (*cb)(pjmedia_port *port, - void *usr_data)); + void *usr_data)); #endif /** * Register a callback to be called when no space left in the buffer. * - * @param port The memory recorder port. - * @param user_data User data to be specified in the callback - * @param cb Callback to be called. Note that if - * application wishes to stop the recording, it - * can disconnect the port in the callback, and - * only after all connections have been removed - * could the application safely destroy the port. + * @param port The memory recorder port. + * @param user_data User data to be specified in the callback + * @param cb Callback to be called. Note that if + * application wishes to stop the recording, it + * can disconnect the port in the callback, and + * only after all connections have been removed + * could the application safely destroy the port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_mem_capture_set_eof_cb2(pjmedia_port *port, void *user_data, void (*cb)(pjmedia_port *port, - void *usr_data)); + void *usr_data)); /** * Return the current size of the recorded data in the buffer. * - * @param port The memory recorder port. - * @return The size of buffer data.. + * @param port The memory recorder port. + * @return The size of buffer data.. */ PJ_DECL(pj_size_t) pjmedia_mem_capture_get_size(pjmedia_port *port); @@ -239,4 +238,4 @@ pjmedia_mem_capture_get_size(pjmedia_port *port); PJ_END_DECL -#endif /* __PJMEDIA_MEM_PORT_H__ */ +#endif /* __PJMEDIA_MEM_PORT_H__ */ diff --git a/pjmedia/include/pjmedia/null_port.h b/pjmedia/include/pjmedia/null_port.h index 88e3a992c3..b54bdb8df5 100644 --- a/pjmedia/include/pjmedia/null_port.h +++ b/pjmedia/include/pjmedia/null_port.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -42,21 +41,21 @@ PJ_BEGIN_DECL /** * Create Null port. * - * @param pool Pool to allocate memory. - * @param sampling_rate Sampling rate of the port. - * @param channel_count Number of channels. - * @param samples_per_frame Number of samples per frame. - * @param bits_per_sample Number of bits per sample. - * @param p_port Pointer to receive the port instance. + * @param pool Pool to allocate memory. + * @param sampling_rate Sampling rate of the port. + * @param channel_count Number of channels. + * @param samples_per_frame Number of samples per frame. + * @param bits_per_sample Number of bits per sample. + * @param p_port Pointer to receive the port instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_null_port_create( pj_pool_t *pool, - unsigned sampling_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_port **p_port ); + unsigned sampling_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_port **p_port ); @@ -67,4 +66,4 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_NULL_PORT_H__ */ +#endif /* __PJMEDIA_NULL_PORT_H__ */ diff --git a/pjmedia/include/pjmedia/plc.h b/pjmedia/include/pjmedia/plc.h index 64f54b9aac..cea171233f 100644 --- a/pjmedia/include/pjmedia/plc.h +++ b/pjmedia/include/pjmedia/plc.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -61,46 +60,46 @@ typedef struct pjmedia_plc pjmedia_plc; * Create PLC session. This function will select the PLC algorithm to * use based on the arguments. * - * @param pool Pool to allocate memory for the PLC. - * @param clock_rate Media sampling rate. + * @param pool Pool to allocate memory for the PLC. + * @param clock_rate Media sampling rate. * @param samples_per_frame Number of samples per frame. - * @param options Must be zero for now. - * @param p_plc Pointer to receive the PLC instance. + * @param options Must be zero for now. + * @param p_plc Pointer to receive the PLC instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_plc_create( pj_pool_t *pool, - unsigned clock_rate, - unsigned samples_per_frame, - unsigned options, - pjmedia_plc **p_plc); + unsigned clock_rate, + unsigned samples_per_frame, + unsigned options, + pjmedia_plc **p_plc); /** * Save a good frame to PLC. * - * @param plc The PLC session. - * @param frame The good frame to be stored to PLC. This frame - * must have the same length as the configured - * samples per frame. + * @param plc The PLC session. + * @param frame The good frame to be stored to PLC. This frame + * must have the same length as the configured + * samples per frame. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_plc_save( pjmedia_plc *plc, - pj_int16_t *frame ); + pj_int16_t *frame ); /** * Generate a replacement for lost frame. * - * @param plc The PLC session. - * @param frame Buffer to receive the generated frame. This buffer - * must be able to store the frame. + * @param plc The PLC session. + * @param frame Buffer to receive the generated frame. This buffer + * must be able to store the frame. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_plc_generate( pjmedia_plc *plc, - pj_int16_t *frame ); + pj_int16_t *frame ); @@ -111,5 +110,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_PLC_H__ */ +#endif /* __PJMEDIA_PLC_H__ */ diff --git a/pjmedia/include/pjmedia/port.h b/pjmedia/include/pjmedia/port.h index 16f9446d9b..fa69794e6b 100644 --- a/pjmedia/include/pjmedia/port.h +++ b/pjmedia/include/pjmedia/port.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -93,33 +92,33 @@ // Create the file player port. status = pjmedia_wav_player_port_create(pool, - "Input.WAV", // file name - 20, // ptime. - PJMEDIA_FILE_NO_LOOP, // flags - 0, // buffer size - NULL, // user data. - &player ); + "Input.WAV", // file name + 20, // ptime. + PJMEDIA_FILE_NO_LOOP, // flags + 0, // buffer size + NULL, // user data. + &player ); PJ_ASSERT_RETURN(status==PJ_SUCCESS, PJ_SUCCESS); // Create the resample port with specifying the target sampling rate, // and with the file port as the source. This will effectively // connect the resample port with the player port. status = pjmedia_resample_port_create( pool, player, 8000, - 0, &resample); + 0, &resample); PJ_ASSERT_RETURN(status==PJ_SUCCESS, PJ_SUCCESS); // Create the file writer, specifying the resample port's configuration // as the WAV parameters. status pjmedia_wav_writer_port_create(pool, - "Output.WAV", // file name. - resample->info.clock_rate, - resample->info.channel_count, - resample->info.samples_per_frame, - resample->info.bits_per_sample, - 0, // flags - 0, // buffer size - NULL, // user data. - &writer); + "Output.WAV", // file name. + resample->info.clock_rate, + resample->info.channel_count, + resample->info.samples_per_frame, + resample->info.bits_per_sample, + 0, // flags + 0, // buffer size + NULL, // user data. + &writer); \endcode @@ -129,29 +128,29 @@ \code - pj_int16_t samplebuf[MAX_FRAME]; - - while (1) { - pjmedia_frame frame; - pj_status_t status; + pj_int16_t samplebuf[MAX_FRAME]; + + while (1) { + pjmedia_frame frame; + pj_status_t status; - frame.buf = samplebuf; - frame.size = sizeof(samplebuf); + frame.buf = samplebuf; + frame.size = sizeof(samplebuf); - // Get the frame from resample port. - status = pjmedia_port_get_frame(resample, &frame); - if (status != PJ_SUCCESS || frame.type == PJMEDIA_FRAME_TYPE_NONE) { - // End-of-file, end the conversion. - break; - } + // Get the frame from resample port. + status = pjmedia_port_get_frame(resample, &frame); + if (status != PJ_SUCCESS || frame.type == PJMEDIA_FRAME_TYPE_NONE) { + // End-of-file, end the conversion. + break; + } - // Put the frame to write port. - status = pjmedia_port_put_frame(writer, &frame); - if (status != PJ_SUCCESS) { - // Error in writing the file. - break; - } - } + // Put the frame to write port. + status = pjmedia_port_put_frame(writer, &frame); + if (status != PJ_SUCCESS) { + // Error in writing the file. + break; + } + } \endcode @@ -159,10 +158,10 @@ application would need to destroy the ports: \code - // Note: by default, destroying resample port will destroy the - // the downstream port too. - pjmedia_port_destroy(resample); - pjmedia_port_destroy(writer); + // Note: by default, destroying resample port will destroy the + // the downstream port too. + pjmedia_port_destroy(resample); + pjmedia_port_destroy(writer); \endcode @@ -197,14 +196,14 @@ PJ_BEGIN_DECL * See also https://github.com/pjsip/pjproject/issues/2251. */ #ifndef DEPRECATED_FOR_TICKET_2251 -# define DEPRECATED_FOR_TICKET_2251 0 +# define DEPRECATED_FOR_TICKET_2251 0 #endif /** * Create 32bit port signature from ASCII characters. */ -#define PJMEDIA_PORT_SIG(a,b,c,d) PJMEDIA_OBJ_SIG(a,b,c,d) +#define PJMEDIA_PORT_SIG(a,b,c,d) PJMEDIA_OBJ_SIG(a,b,c,d) /** @@ -242,49 +241,49 @@ typedef enum pjmedia_port_op */ typedef struct pjmedia_port_info { - pj_str_t name; /**< Port name. */ - pj_uint32_t signature; /**< Port signature. */ + pj_str_t name; /**< Port name. */ + pj_uint32_t signature; /**< Port signature. */ pjmedia_dir dir; /**< Port direction. */ - pjmedia_format fmt; /**< Format. */ + pjmedia_format fmt; /**< Format. */ } pjmedia_port_info; /** * Utility to retrieve audio clock rate/sampling rate value from * pjmedia_port_info. * - * @param pia Pointer to port info containing audio format. - * @return Audio clock rate. + * @param pia Pointer to port info containing audio format. + * @return Audio clock rate. */ PJ_INLINE(unsigned) PJMEDIA_PIA_SRATE(const pjmedia_port_info *pia) { pj_assert(pia->fmt.type==PJMEDIA_TYPE_AUDIO && - pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); + pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); return pia->fmt.det.aud.clock_rate; } /** * Utility to retrieve audio channel count value from pjmedia_port_info. * - * @param pia Pointer to port info containing audio format. - * @return Audio channel count. + * @param pia Pointer to port info containing audio format. + * @return Audio channel count. */ PJ_INLINE(unsigned) PJMEDIA_PIA_CCNT(const pjmedia_port_info *pia) { pj_assert(pia->fmt.type==PJMEDIA_TYPE_AUDIO && - pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); + pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); return pia->fmt.det.aud.channel_count; } /** * Utility to retrieve audio bits per sample value from pjmedia_port_info. * - * @param pia Pointer to port info containing audio format. - * @return Number of bits per sample. + * @param pia Pointer to port info containing audio format. + * @return Number of bits per sample. */ PJ_INLINE(unsigned) PJMEDIA_PIA_BITS(const pjmedia_port_info *pia) { pj_assert(pia->fmt.type==PJMEDIA_TYPE_AUDIO && - pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); + pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); return pia->fmt.det.aud.bits_per_sample; } @@ -292,13 +291,13 @@ PJ_INLINE(unsigned) PJMEDIA_PIA_BITS(const pjmedia_port_info *pia) * Utility to retrieve audio frame interval (ptime) value from * pjmedia_port_info. * - * @param pia Pointer to port info containing audio format. - * @return Frame interval in msec. + * @param pia Pointer to port info containing audio format. + * @return Frame interval in msec. */ PJ_INLINE(unsigned) PJMEDIA_PIA_PTIME(const pjmedia_port_info *pia) { pj_assert(pia->fmt.type==PJMEDIA_TYPE_AUDIO && - pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); + pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); return pia->fmt.det.aud.frame_time_usec / 1000; } @@ -306,13 +305,13 @@ PJ_INLINE(unsigned) PJMEDIA_PIA_PTIME(const pjmedia_port_info *pia) * This is a utility routine to retrieve the audio samples_per_frame value * from port info. * - * @param pia Pointer to port info containing audio format. - * @return Samples per frame value. + * @param pia Pointer to port info containing audio format. + * @return Samples per frame value. */ PJ_INLINE(unsigned) PJMEDIA_PIA_SPF(const pjmedia_port_info *pia) { pj_assert(pia->fmt.type==PJMEDIA_TYPE_AUDIO && - pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); + pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); return PJMEDIA_AFD_SPF(&pia->fmt.det.aud); } @@ -320,13 +319,13 @@ PJ_INLINE(unsigned) PJMEDIA_PIA_SPF(const pjmedia_port_info *pia) * This is a utility routine to retrieve the average bitrate value * from port info. * - * @param pia Pointer to port info containing audio format. - * @return Bitrate, in bits per second. + * @param pia Pointer to port info containing audio format. + * @return Bitrate, in bits per second. */ PJ_INLINE(unsigned) PJMEDIA_PIA_AVG_BPS(const pjmedia_port_info *pia) { pj_assert(pia->fmt.type==PJMEDIA_TYPE_AUDIO && - pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); + pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); return pia->fmt.det.aud.avg_bps; } @@ -334,13 +333,13 @@ PJ_INLINE(unsigned) PJMEDIA_PIA_AVG_BPS(const pjmedia_port_info *pia) * This is a utility routine to retrieve the maximum bitrate value * from port info. * - * @param pia Pointer to port info containing audio format. - * @return Bitrate, in bits per second. + * @param pia Pointer to port info containing audio format. + * @return Bitrate, in bits per second. */ PJ_INLINE(unsigned) PJMEDIA_PIA_MAX_BPS(const pjmedia_port_info *pia) { pj_assert(pia->fmt.type==PJMEDIA_TYPE_AUDIO && - pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); + pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); return pia->fmt.det.aud.max_bps; } @@ -348,13 +347,13 @@ PJ_INLINE(unsigned) PJMEDIA_PIA_MAX_BPS(const pjmedia_port_info *pia) * This is a utility routine to retrieve the average audio frame size value * from pjmedia_port_info. * - * @param pia Pointer to port info containing audio format. - * @return Frame size in bytes. + * @param pia Pointer to port info containing audio format. + * @return Frame size in bytes. */ PJ_INLINE(unsigned) PJMEDIA_PIA_AVG_FSZ(const pjmedia_port_info *pia) { pj_assert(pia->fmt.type==PJMEDIA_TYPE_AUDIO && - pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); + pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); return PJMEDIA_AFD_AVG_FSZ(&pia->fmt.det.aud); } @@ -362,13 +361,13 @@ PJ_INLINE(unsigned) PJMEDIA_PIA_AVG_FSZ(const pjmedia_port_info *pia) * Utility to retrieve audio frame size from maximum bitrate from * pjmedia_port_info. * - * @param pia Pointer to port info containing audio format. - * @return Frame size in bytes. + * @param pia Pointer to port info containing audio format. + * @return Frame size in bytes. */ PJ_INLINE(unsigned) PJMEDIA_PIA_MAX_FSZ(const pjmedia_port_info *pia) { pj_assert(pia->fmt.type==PJMEDIA_TYPE_AUDIO && - pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); + pia->fmt.detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO); return PJMEDIA_AFD_MAX_FSZ(&pia->fmt.det.aud); } @@ -377,14 +376,14 @@ PJ_INLINE(unsigned) PJMEDIA_PIA_MAX_FSZ(const pjmedia_port_info *pia) */ typedef struct pjmedia_port { - pjmedia_port_info info; /**< Port information. */ + pjmedia_port_info info; /**< Port information. */ /** Port data can be used by the port creator to attach arbitrary * value to be associated with the port. */ struct port_data { - void *pdata; /**< Pointer data. */ - long ldata; /**< Long data. */ + void *pdata; /**< Pointer data. */ + long ldata; /**< Long data. */ } port_data; /** @@ -393,7 +392,7 @@ typedef struct pjmedia_port * This is optional, but if this port is registered to the audio/video * conference bridge, the bridge will create one if the port has none. */ - pj_grp_lock_t *grp_lock; + pj_grp_lock_t *grp_lock; /** * Get clock source. @@ -407,14 +406,14 @@ typedef struct pjmedia_port * This should only be called by #pjmedia_port_put_frame(). */ pj_status_t (*put_frame)(struct pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); /** * Source interface. * This should only be called by #pjmedia_port_get_frame(). */ pj_status_t (*get_frame)(struct pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); /** * Called to destroy this port. @@ -428,50 +427,50 @@ typedef struct pjmedia_port * This is an auxiliary function to initialize port info for * ports which deal with PCM audio. * - * @param info The port info to be initialized. - * @param name Port name. - * @param signature Port signature. - * @param clock_rate Port's clock rate. - * @param channel_count Number of channels. + * @param info The port info to be initialized. + * @param name Port name. + * @param signature Port signature. + * @param clock_rate Port's clock rate. + * @param channel_count Number of channels. * @param bits_per_sample Bits per sample. * @param samples_per_frame Number of samples per frame. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_port_info_init( pjmedia_port_info *info, - const pj_str_t *name, - unsigned signature, - unsigned clock_rate, - unsigned channel_count, - unsigned bits_per_sample, - unsigned samples_per_frame); + const pj_str_t *name, + unsigned signature, + unsigned clock_rate, + unsigned channel_count, + unsigned bits_per_sample, + unsigned samples_per_frame); /** * This is an auxiliary function to initialize port info for * ports which deal with PCM audio. * - * @param info The port info to be initialized. - * @param name Port name. - * @param signature Port signature. - * @param dir Port's direction. - * @param fmt Port's media format. + * @param info The port info to be initialized. + * @param name Port name. + * @param signature Port signature. + * @param dir Port's direction. + * @param fmt Port's media format. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_port_info_init2(pjmedia_port_info *info, - const pj_str_t *name, - unsigned signature, - pjmedia_dir dir, - const pjmedia_format *fmt); + const pj_str_t *name, + unsigned signature, + pjmedia_dir dir, + const pjmedia_format *fmt); /** * Get a clock source from the port. * - * @param port The media port. + * @param port The media port. * @param dir Media port's direction. * - * @return The clock source or NULL if clock source is not present + * @return The clock source or NULL if clock source is not present * in the port. */ PJ_DECL(pjmedia_clock_src *) pjmedia_port_get_clock_src( pjmedia_port *port, @@ -481,24 +480,24 @@ PJ_DECL(pjmedia_clock_src *) pjmedia_port_get_clock_src( pjmedia_port *port, /** * Get a frame from the port (and subsequent downstream ports). * - * @param port The media port. - * @param frame Frame to store samples. + * @param port The media port. + * @param frame Frame to store samples. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_port_get_frame( pjmedia_port *port, - pjmedia_frame *frame ); + pjmedia_frame *frame ); /** * Put a frame to the port (and subsequent downstream ports). * - * @param port The media port. - * @param frame Frame to the put to the port. + * @param port The media port. + * @param frame Frame to the put to the port. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_port_put_frame( pjmedia_port *port, - pjmedia_frame *frame ); + pjmedia_frame *frame ); /** * Destroy port (and subsequent downstream ports). @@ -506,9 +505,9 @@ PJ_DECL(pj_status_t) pjmedia_port_put_frame( pjmedia_port *port, * Note that if the port has group lock, instead of destroying the port * immediately, this function will just decrease the reference counter. * - * @param port The media port. + * @param port The media port. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_port_destroy( pjmedia_port *port ); @@ -522,26 +521,26 @@ PJ_DECL(pj_status_t) pjmedia_port_destroy( pjmedia_port *port ); * This function should only be called by a media port implementation and * after port's on_destroy() function has been assigned. * - * @param port The pjmedia port to be initialized. - * @param pool The pool, this can be a temporary pool as - * group lock will create and use its internal pool. - * @param glock The group lock, or create a new one if NULL. + * @param port The pjmedia port to be initialized. + * @param pool The pool, this can be a temporary pool as + * group lock will create and use its internal pool. + * @param glock The group lock, or create a new one if NULL. * - * @return PJ_SUCCESS on success, PJ_EEXISTS if group lock - * is already initialized, or the other appropriate - * error code. + * @return PJ_SUCCESS on success, PJ_EEXISTS if group lock + * is already initialized, or the other appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_port_init_grp_lock( pjmedia_port *port, - pj_pool_t *pool, - pj_grp_lock_t *glock ); + pj_pool_t *pool, + pj_grp_lock_t *glock ); /** * This is a helper function to increase the port reference counter. * - * @param port The PJMEDIA port. + * @param port The PJMEDIA port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_port_add_ref( pjmedia_port *port ); @@ -549,9 +548,9 @@ PJ_DECL(pj_status_t) pjmedia_port_add_ref( pjmedia_port *port ); /** * This is a helper function to decrease the port reference counter. * - * @param port The PJMEDIA port. + * @param port The PJMEDIA port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_port_dec_ref( pjmedia_port *port ); @@ -562,5 +561,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_PORT_H__ */ +#endif /* __PJMEDIA_PORT_H__ */ diff --git a/pjmedia/include/pjmedia/resample.h b/pjmedia/include/pjmedia/resample.h index c573ed4960..9cea017442 100644 --- a/pjmedia/include/pjmedia/resample.h +++ b/pjmedia/include/pjmedia/resample.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -63,27 +62,27 @@ typedef struct pjmedia_resample pjmedia_resample; /** * Create a frame based resample session. * - * @param pool Pool to allocate the structure and buffers. - * @param high_quality If true, then high quality conversion will be - * used, at the expense of more CPU and memory, - * because temporary buffer needs to be created. - * @param large_filter If true, large filter size will be used. - * @param channel_count Number of channels. - * @param rate_in Clock rate of the input samples. - * @param rate_out Clock rate of the output samples. - * @param samples_per_frame Number of samples per frame in the input. - * @param p_resample Pointer to receive the resample session. + * @param pool Pool to allocate the structure and buffers. + * @param high_quality If true, then high quality conversion will be + * used, at the expense of more CPU and memory, + * because temporary buffer needs to be created. + * @param large_filter If true, large filter size will be used. + * @param channel_count Number of channels. + * @param rate_in Clock rate of the input samples. + * @param rate_out Clock rate of the output samples. + * @param samples_per_frame Number of samples per frame in the input. + * @param p_resample Pointer to receive the resample session. * * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_resample_create(pj_pool_t *pool, - pj_bool_t high_quality, - pj_bool_t large_filter, - unsigned channel_count, - unsigned rate_in, - unsigned rate_out, - unsigned samples_per_frame, - pjmedia_resample **p_resample); + pj_bool_t high_quality, + pj_bool_t large_filter, + unsigned channel_count, + unsigned rate_in, + unsigned rate_out, + unsigned samples_per_frame, + pjmedia_resample **p_resample); /** @@ -91,21 +90,21 @@ PJ_DECL(pj_status_t) pjmedia_resample_create(pj_pool_t *pool, * same size and settings as the resample session, or otherwise the * behavior is undefined. * - * @param resample The resample session. - * @param input Buffer containing the input samples. - * @param output Buffer to store the output samples. + * @param resample The resample session. + * @param input Buffer containing the input samples. + * @param output Buffer to store the output samples. */ PJ_DECL(void) pjmedia_resample_run( pjmedia_resample *resample, - const pj_int16_t *input, - pj_int16_t *output ); + const pj_int16_t *input, + pj_int16_t *output ); /** * Get the input frame size of a resample session. * - * @param resample The resample session. + * @param resample The resample session. * - * @return The frame size, in number of samples. + * @return The frame size, in number of samples. */ PJ_DECL(unsigned) pjmedia_resample_get_input_size(pjmedia_resample *resample); @@ -113,7 +112,7 @@ PJ_DECL(unsigned) pjmedia_resample_get_input_size(pjmedia_resample *resample); /** * Destroy the resample. * - * @param resample The resample session. + * @param resample The resample session. */ PJ_DECL(void) pjmedia_resample_destroy(pjmedia_resample *resample); @@ -169,24 +168,24 @@ enum pjmedia_resample_port_options * the frame to the downstream port's clock rate before giving the frame * to the downstream port. * - * @param pool Pool to allocate the structure and buffers. - * @param dn_port The downstream port, which clock rate is to - * be converted to the target clock rate. - * @param clock_rate Target clock rate. - * @param options Flags from #pjmedia_resample_port_options. - * When this flag is zero, the default behavior - * is to use high quality resampling with - * large filter, and to destroy downstream port - * when resample port is destroyed. - * @param p_port Pointer to receive the resample port instance. + * @param pool Pool to allocate the structure and buffers. + * @param dn_port The downstream port, which clock rate is to + * be converted to the target clock rate. + * @param clock_rate Target clock rate. + * @param options Flags from #pjmedia_resample_port_options. + * When this flag is zero, the default behavior + * is to use high quality resampling with + * large filter, and to destroy downstream port + * when resample port is destroyed. + * @param p_port Pointer to receive the resample port instance. * * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_resample_port_create( pj_pool_t *pool, - pjmedia_port *dn_port, - unsigned clock_rate, - unsigned options, - pjmedia_port **p_port ); + pjmedia_port *dn_port, + unsigned clock_rate, + unsigned options, + pjmedia_port **p_port ); PJ_END_DECL @@ -196,5 +195,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_RESAMPLE_H__ */ +#endif /* __PJMEDIA_RESAMPLE_H__ */ diff --git a/pjmedia/include/pjmedia/rtcp.h b/pjmedia/include/pjmedia/rtcp.h index f4bff12cda..ee13a5fae2 100644 --- a/pjmedia/include/pjmedia/rtcp.h +++ b/pjmedia/include/pjmedia/rtcp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -62,11 +61,11 @@ PJ_BEGIN_DECL */ typedef struct pjmedia_rtcp_sr { - pj_uint32_t ntp_sec; /**< NTP time, seconds part. */ - pj_uint32_t ntp_frac; /**< NTP time, fractions part. */ - pj_uint32_t rtp_ts; /**< RTP timestamp. */ - pj_uint32_t sender_pcount; /**< Sender packet cound. */ - pj_uint32_t sender_bcount; /**< Sender octet/bytes count. */ + pj_uint32_t ntp_sec; /**< NTP time, seconds part. */ + pj_uint32_t ntp_frac; /**< NTP time, fractions part. */ + pj_uint32_t rtp_ts; /**< RTP timestamp. */ + pj_uint32_t sender_pcount; /**< Sender packet cound. */ + pj_uint32_t sender_bcount; /**< Sender octet/bytes count. */ } pjmedia_rtcp_sr; @@ -75,22 +74,22 @@ typedef struct pjmedia_rtcp_sr */ typedef struct pjmedia_rtcp_rr { - pj_uint32_t ssrc; /**< SSRC identification. */ + pj_uint32_t ssrc; /**< SSRC identification. */ #if defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN!=0 - pj_uint32_t fract_lost:8; /**< Fraction lost. */ - pj_uint32_t total_lost_2:8; /**< Total lost, bit 16-23. */ - pj_uint32_t total_lost_1:8; /**< Total lost, bit 8-15. */ - pj_uint32_t total_lost_0:8; /**< Total lost, bit 0-7. */ + pj_uint32_t fract_lost:8; /**< Fraction lost. */ + pj_uint32_t total_lost_2:8; /**< Total lost, bit 16-23. */ + pj_uint32_t total_lost_1:8; /**< Total lost, bit 8-15. */ + pj_uint32_t total_lost_0:8; /**< Total lost, bit 0-7. */ #else - pj_uint32_t fract_lost:8; /**< Fraction lost. */ - pj_uint32_t total_lost_2:8; /**< Total lost, bit 0-7. */ - pj_uint32_t total_lost_1:8; /**< Total lost, bit 8-15. */ - pj_uint32_t total_lost_0:8; /**< Total lost, bit 16-23. */ -#endif - pj_uint32_t last_seq; /**< Last sequence number. */ - pj_uint32_t jitter; /**< Jitter. */ - pj_uint32_t lsr; /**< Last SR. */ - pj_uint32_t dlsr; /**< Delay since last SR. */ + pj_uint32_t fract_lost:8; /**< Fraction lost. */ + pj_uint32_t total_lost_2:8; /**< Total lost, bit 0-7. */ + pj_uint32_t total_lost_1:8; /**< Total lost, bit 8-15. */ + pj_uint32_t total_lost_0:8; /**< Total lost, bit 16-23. */ +#endif + pj_uint32_t last_seq; /**< Last sequence number. */ + pj_uint32_t jitter; /**< Jitter. */ + pj_uint32_t lsr; /**< Last SR. */ + pj_uint32_t dlsr; /**< Delay since last SR. */ } pjmedia_rtcp_rr; @@ -100,18 +99,18 @@ typedef struct pjmedia_rtcp_rr typedef struct pjmedia_rtcp_common { #if defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN!=0 - unsigned version:2; /**< packet type */ - unsigned p:1; /**< padding flag */ - unsigned count:5; /**< varies by payload type */ - unsigned pt:8; /**< payload type */ + unsigned version:2; /**< packet type */ + unsigned p:1; /**< padding flag */ + unsigned count:5; /**< varies by payload type */ + unsigned pt:8; /**< payload type */ #else - unsigned count:5; /**< varies by payload type */ - unsigned p:1; /**< padding flag */ - unsigned version:2; /**< packet type */ - unsigned pt:8; /**< payload type */ + unsigned count:5; /**< varies by payload type */ + unsigned p:1; /**< padding flag */ + unsigned version:2; /**< packet type */ + unsigned pt:8; /**< payload type */ #endif - unsigned length:16; /**< packet length */ - pj_uint32_t ssrc; /**< SSRC identification */ + unsigned length:16; /**< packet length */ + pj_uint32_t ssrc; /**< SSRC identification */ } pjmedia_rtcp_common; @@ -121,7 +120,7 @@ typedef struct pjmedia_rtcp_common typedef struct pjmedia_rtcp_fb_common { pjmedia_rtcp_common rtcp_common; - pj_uint32_t ssrc_src; /**< SSRC media source */ + pj_uint32_t ssrc_src; /**< SSRC media source */ } pjmedia_rtcp_fb_common; /** @@ -131,9 +130,9 @@ typedef struct pjmedia_rtcp_fb_common */ typedef struct pjmedia_rtcp_sr_pkt { - pjmedia_rtcp_common common; /**< Common header. */ - pjmedia_rtcp_sr sr; /**< Sender report. */ - pjmedia_rtcp_rr rr; /**< variable-length list */ + pjmedia_rtcp_common common; /**< Common header. */ + pjmedia_rtcp_sr sr; /**< Sender report. */ + pjmedia_rtcp_rr rr; /**< variable-length list */ } pjmedia_rtcp_sr_pkt; /** @@ -141,8 +140,8 @@ typedef struct pjmedia_rtcp_sr_pkt */ typedef struct pjmedia_rtcp_rr_pkt { - pjmedia_rtcp_common common; /**< Common header. */ - pjmedia_rtcp_rr rr; /**< variable-length list */ + pjmedia_rtcp_common common; /**< Common header. */ + pjmedia_rtcp_rr rr; /**< variable-length list */ } pjmedia_rtcp_rr_pkt; @@ -154,13 +153,13 @@ typedef struct pjmedia_rtcp_rr_pkt */ typedef struct pjmedia_rtcp_sdes { - pj_str_t cname; /**< RTCP SDES type CNAME. */ - pj_str_t name; /**< RTCP SDES type NAME. */ - pj_str_t email; /**< RTCP SDES type EMAIL. */ - pj_str_t phone; /**< RTCP SDES type PHONE. */ - pj_str_t loc; /**< RTCP SDES type LOC. */ - pj_str_t tool; /**< RTCP SDES type TOOL. */ - pj_str_t note; /**< RTCP SDES type NOTE. */ + pj_str_t cname; /**< RTCP SDES type CNAME. */ + pj_str_t name; /**< RTCP SDES type NAME. */ + pj_str_t email; /**< RTCP SDES type EMAIL. */ + pj_str_t phone; /**< RTCP SDES type PHONE. */ + pj_str_t loc; /**< RTCP SDES type LOC. */ + pj_str_t tool; /**< RTCP SDES type TOOL. */ + pj_str_t note; /**< RTCP SDES type NOTE. */ } pjmedia_rtcp_sdes; @@ -169,8 +168,8 @@ typedef struct pjmedia_rtcp_sdes */ typedef struct pjmedia_rtcp_ntp_rec { - pj_uint32_t hi; /**< High order 32-bit part. */ - pj_uint32_t lo; /**< Lo order 32-bit part. */ + pj_uint32_t hi; /**< High order 32-bit part. */ + pj_uint32_t lo; /**< Lo order 32-bit part. */ } pjmedia_rtcp_ntp_rec; @@ -179,23 +178,23 @@ typedef struct pjmedia_rtcp_ntp_rec */ typedef struct pjmedia_rtcp_stream_stat { - pj_time_val update; /**< Time of last update. */ - unsigned update_cnt; /**< Number of updates (to calculate avg) */ - pj_uint32_t pkt; /**< Total number of packets */ - pj_uint32_t bytes; /**< Total number of payload/bytes */ - unsigned discard; /**< Total number of discarded packets. */ - unsigned loss; /**< Total number of packets lost */ - unsigned reorder; /**< Total number of out of order packets */ - unsigned dup; /**< Total number of duplicates packets */ + pj_time_val update; /**< Time of last update. */ + unsigned update_cnt; /**< Number of updates (to calculate avg) */ + pj_uint32_t pkt; /**< Total number of packets */ + pj_uint32_t bytes; /**< Total number of payload/bytes */ + unsigned discard; /**< Total number of discarded packets. */ + unsigned loss; /**< Total number of packets lost */ + unsigned reorder; /**< Total number of out of order packets */ + unsigned dup; /**< Total number of duplicates packets */ - pj_math_stat loss_period;/**< Loss period statistics (in usec) */ + pj_math_stat loss_period;/**< Loss period statistics (in usec) */ struct { - unsigned burst:1; /**< Burst/sequential packet lost detected */ - unsigned random:1; /**< Random packet lost detected. */ - } loss_type; /**< Types of loss detected. */ + unsigned burst:1; /**< Burst/sequential packet lost detected */ + unsigned random:1; /**< Random packet lost detected. */ + } loss_type; /**< Types of loss detected. */ - pj_math_stat jitter; /**< Jitter statistics (in usec) */ + pj_math_stat jitter; /**< Jitter statistics (in usec) */ } pjmedia_rtcp_stream_stat; @@ -205,31 +204,31 @@ typedef struct pjmedia_rtcp_stream_stat */ typedef struct pjmedia_rtcp_stat { - pj_time_val start; /**< Time when session was created */ + pj_time_val start; /**< Time when session was created */ - pjmedia_rtcp_stream_stat tx; /**< Encoder stream statistics. */ - pjmedia_rtcp_stream_stat rx; /**< Decoder stream statistics. */ + pjmedia_rtcp_stream_stat tx; /**< Encoder stream statistics. */ + pjmedia_rtcp_stream_stat rx; /**< Decoder stream statistics. */ - pj_math_stat rtt; /**< Round trip delay statistic(in usec)*/ + pj_math_stat rtt; /**< Round trip delay statistic(in usec)*/ - pj_uint32_t rtp_tx_last_ts; /**< Last TX RTP timestamp. */ - pj_uint16_t rtp_tx_last_seq;/**< Last TX RTP sequence. */ + pj_uint32_t rtp_tx_last_ts; /**< Last TX RTP timestamp. */ + pj_uint16_t rtp_tx_last_seq;/**< Last TX RTP sequence. */ #if defined(PJMEDIA_RTCP_STAT_HAS_IPDV) && PJMEDIA_RTCP_STAT_HAS_IPDV!=0 - pj_math_stat rx_ipdv;/**< Statistics of IP packet delay - variation in receiving direction - (in usec). */ + pj_math_stat rx_ipdv;/**< Statistics of IP packet delay + variation in receiving direction + (in usec). */ #endif #if defined(PJMEDIA_RTCP_STAT_HAS_RAW_JITTER) && PJMEDIA_RTCP_STAT_HAS_RAW_JITTER!=0 - pj_math_stat rx_raw_jitter;/**< Statistic of raw jitter in - receiving direction - (in usec). */ + pj_math_stat rx_raw_jitter;/**< Statistic of raw jitter in + receiving direction + (in usec). */ #endif - pjmedia_rtcp_sdes peer_sdes; /**< Peer SDES. */ - char peer_sdes_buf_[PJMEDIA_RTCP_RX_SDES_BUF_LEN]; - /**< Peer SDES buffer. */ + pjmedia_rtcp_sdes peer_sdes; /**< Peer SDES. */ + char peer_sdes_buf_[PJMEDIA_RTCP_RX_SDES_BUF_LEN]; + /**< Peer SDES buffer. */ } pjmedia_rtcp_stat; @@ -240,38 +239,38 @@ typedef struct pjmedia_rtcp_stat */ typedef struct pjmedia_rtcp_session { - char *name; /**< Name identification. */ - pjmedia_rtcp_sr_pkt rtcp_sr_pkt;/**< Cached RTCP SR packet. */ - pjmedia_rtcp_rr_pkt rtcp_rr_pkt;/**< Cached RTCP RR packet. */ + char *name; /**< Name identification. */ + pjmedia_rtcp_sr_pkt rtcp_sr_pkt;/**< Cached RTCP SR packet. */ + pjmedia_rtcp_rr_pkt rtcp_rr_pkt;/**< Cached RTCP RR packet. */ pjmedia_rtcp_fb_common rtcp_fb_com;/**< Cached RTCP feedback common - header packet. */ + header packet. */ - pjmedia_rtp_seq_session seq_ctrl; /**< RTCP sequence number control. */ - unsigned rtp_last_ts;/**< Last timestamp in RX RTP pkt. */ - - unsigned clock_rate; /**< Clock rate of the stream */ - unsigned pkt_size; /**< Avg pkt size, in samples. */ - pj_uint32_t received; /**< # pkt received */ - pj_uint32_t exp_prior; /**< # pkt expected at last interval*/ - pj_uint32_t rx_prior; /**< # pkt received at last interval*/ - pj_int32_t transit; /**< Rel transit time for prev pkt */ - pj_uint32_t jitter; /**< Scaled jitter */ - pj_time_val tv_base; /**< Base time, in seconds. */ - pj_timestamp ts_base; /**< Base system timestamp. */ - pj_timestamp ts_freq; /**< System timestamp frequency. */ - pj_uint32_t rtp_ts_base;/**< Base RTP timestamp. */ - - pj_uint32_t rx_lsr; /**< NTP ts in last SR received */ - pj_timestamp rx_lsr_time;/**< Time when last SR is received */ - pj_uint32_t peer_ssrc; /**< Peer SSRC */ + pjmedia_rtp_seq_session seq_ctrl; /**< RTCP sequence number control. */ + unsigned rtp_last_ts;/**< Last timestamp in RX RTP pkt. */ + + unsigned clock_rate; /**< Clock rate of the stream */ + unsigned pkt_size; /**< Avg pkt size, in samples. */ + pj_uint32_t received; /**< # pkt received */ + pj_uint32_t exp_prior; /**< # pkt expected at last interval*/ + pj_uint32_t rx_prior; /**< # pkt received at last interval*/ + pj_int32_t transit; /**< Rel transit time for prev pkt */ + pj_uint32_t jitter; /**< Scaled jitter */ + pj_time_val tv_base; /**< Base time, in seconds. */ + pj_timestamp ts_base; /**< Base system timestamp. */ + pj_timestamp ts_freq; /**< System timestamp frequency. */ + pj_uint32_t rtp_ts_base;/**< Base RTP timestamp. */ + + pj_uint32_t rx_lsr; /**< NTP ts in last SR received */ + pj_timestamp rx_lsr_time;/**< Time when last SR is received */ + pj_uint32_t peer_ssrc; /**< Peer SSRC */ - pjmedia_rtcp_stat stat; /**< Bidirectional stream stat. */ + pjmedia_rtcp_stat stat; /**< Bidirectional stream stat. */ #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) /** * Specify whether RTCP XR processing is enabled on this session. */ - pj_bool_t xr_enabled; + pj_bool_t xr_enabled; /** * RTCP XR session, only valid if RTCP XR processing is enabled @@ -287,27 +286,27 @@ typedef struct pjmedia_rtcp_session */ typedef struct pjmedia_rtcp_session_setting { - char *name; /**< RTCP session name. */ - unsigned clock_rate; /**< Sequence. */ - unsigned samples_per_frame; /**< Timestamp. */ - pj_uint32_t ssrc; /**< Sender SSRC. */ - pj_uint32_t rtp_ts_base; /**< Base RTP timestamp. */ + char *name; /**< RTCP session name. */ + unsigned clock_rate; /**< Sequence. */ + unsigned samples_per_frame; /**< Timestamp. */ + pj_uint32_t ssrc; /**< Sender SSRC. */ + pj_uint32_t rtp_ts_base; /**< Base RTP timestamp. */ } pjmedia_rtcp_session_setting; /** * Initialize RTCP session setting. * - * @param settings The RTCP session setting to be initialized. + * @param settings The RTCP session setting to be initialized. */ PJ_DECL(void) pjmedia_rtcp_session_setting_default( - pjmedia_rtcp_session_setting *settings); + pjmedia_rtcp_session_setting *settings); /** * Initialize bidirectional RTCP statistics. * - * @param stat The bidirectional RTCP statistics. + * @param stat The bidirectional RTCP statistics. */ PJ_DECL(void) pjmedia_rtcp_init_stat(pjmedia_rtcp_stat *stat); @@ -315,40 +314,40 @@ PJ_DECL(void) pjmedia_rtcp_init_stat(pjmedia_rtcp_stat *stat); /** * Initialize RTCP session. * - * @param session The session - * @param name Optional name to identify the session (for - * logging purpose). - * @param clock_rate Codec clock rate in samples per second. + * @param session The session + * @param name Optional name to identify the session (for + * logging purpose). + * @param clock_rate Codec clock rate in samples per second. * @param samples_per_frame Average number of samples per frame. - * @param ssrc The SSRC used in to identify the session. + * @param ssrc The SSRC used in to identify the session. */ PJ_DECL(void) pjmedia_rtcp_init( pjmedia_rtcp_session *session, - char *name, - unsigned clock_rate, - unsigned samples_per_frame, - pj_uint32_t ssrc ); + char *name, + unsigned clock_rate, + unsigned samples_per_frame, + pj_uint32_t ssrc ); /** * Initialize RTCP session. * - * @param session The session - * @param settings The RTCP session settings. + * @param session The session + * @param settings The RTCP session settings. */ PJ_DECL(void) pjmedia_rtcp_init2(pjmedia_rtcp_session *session, - const pjmedia_rtcp_session_setting *settings); + const pjmedia_rtcp_session_setting *settings); /** * Utility function to retrieve current NTP timestamp. * - * @param sess RTCP session. - * @param ntp NTP record. + * @param sess RTCP session. + * @param ntp NTP record. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_rtcp_get_ntp_time(const pjmedia_rtcp_session *sess, - pjmedia_rtcp_ntp_rec *ntp); + pjmedia_rtcp_ntp_rec *ntp); /** @@ -364,14 +363,14 @@ PJ_DECL(void) pjmedia_rtcp_fini( pjmedia_rtcp_session *session); * session do its internal calculations. * * @param session The session. - * @param seq The RTP packet sequence number, in host byte order. - * @param ts The RTP packet timestamp, in host byte order. + * @param seq The RTP packet sequence number, in host byte order. + * @param ts The RTP packet timestamp, in host byte order. * @param payload Size of the payload. */ PJ_DECL(void) pjmedia_rtcp_rx_rtp( pjmedia_rtcp_session *session, - unsigned seq, - unsigned ts, - unsigned payload); + unsigned seq, + unsigned ts, + unsigned payload); /** @@ -379,16 +378,16 @@ PJ_DECL(void) pjmedia_rtcp_rx_rtp( pjmedia_rtcp_session *session, * session do its internal calculations. * * @param session The session. - * @param seq The RTP packet sequence number, in host byte order. - * @param ts The RTP packet timestamp, in host byte order. + * @param seq The RTP packet sequence number, in host byte order. + * @param ts The RTP packet timestamp, in host byte order. * @param payload Size of the payload. * @param discarded Flag to specify whether the packet is discarded. */ PJ_DECL(void) pjmedia_rtcp_rx_rtp2(pjmedia_rtcp_session *session, - unsigned seq, - unsigned ts, - unsigned payload, - pj_bool_t discarded); + unsigned seq, + unsigned ts, + unsigned payload, + pj_bool_t discarded); /** @@ -397,10 +396,10 @@ PJ_DECL(void) pjmedia_rtcp_rx_rtp2(pjmedia_rtcp_session *session, * * @param session The session. * @param ptsize The payload size of the RTP packet (ie packet minus - * RTP header) in bytes. + * RTP header) in bytes. */ PJ_DECL(void) pjmedia_rtcp_tx_rtp( pjmedia_rtcp_session *session, - unsigned ptsize ); + unsigned ptsize ); /** @@ -410,11 +409,11 @@ PJ_DECL(void) pjmedia_rtcp_tx_rtp( pjmedia_rtcp_session *session, * * @param session RTCP session. * @param rtcp_pkt The received RTCP packet. - * @param size Size of the incoming packet. + * @param size Size of the incoming packet. */ PJ_DECL(void) pjmedia_rtcp_rx_rtcp( pjmedia_rtcp_session *session, - const void *rtcp_pkt, - pj_size_t size); + const void *rtcp_pkt, + pj_size_t size); /** @@ -426,12 +425,12 @@ PJ_DECL(void) pjmedia_rtcp_rx_rtcp( pjmedia_rtcp_session *session, * * @param session The RTCP session. * @param rtcp_pkt Upon return, it will contain pointer to the - * RTCP packet, which can be RTCP SR or RR. - * @param len Upon return, it will indicate the size of - * the RTCP packet. + * RTCP packet, which can be RTCP SR or RR. + * @param len Upon return, it will indicate the size of + * the RTCP packet. */ PJ_DECL(void) pjmedia_rtcp_build_rtcp( pjmedia_rtcp_session *session, - void **rtcp_pkt, int *len); + void **rtcp_pkt, int *len); /** @@ -440,38 +439,38 @@ PJ_DECL(void) pjmedia_rtcp_build_rtcp( pjmedia_rtcp_session *session, * RTCP packet. * * @param session The RTCP session. - * @param buf The buffer to receive RTCP SDES packet. + * @param buf The buffer to receive RTCP SDES packet. * @param length On input, it will contain the buffer length. - * On output, it will contain the generated RTCP SDES - * packet length. - * @param sdes The source description, see #pjmedia_rtcp_sdes. + * On output, it will contain the generated RTCP SDES + * packet length. + * @param sdes The source description, see #pjmedia_rtcp_sdes. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_rtcp_build_rtcp_sdes( - pjmedia_rtcp_session *session, - void *buf, - pj_size_t *length, - const pjmedia_rtcp_sdes *sdes); + pjmedia_rtcp_session *session, + void *buf, + pj_size_t *length, + const pjmedia_rtcp_sdes *sdes); /** * Build an RTCP BYE packet. This packet can be appended to other RTCP * packets, e.g: RTCP RR/SR, to compose a compound RTCP packet. * * @param session The RTCP session. - * @param buf The buffer to receive RTCP BYE packet. + * @param buf The buffer to receive RTCP BYE packet. * @param length On input, it will contain the buffer length. - * On output, it will contain the generated RTCP BYE - * packet length. + * On output, it will contain the generated RTCP BYE + * packet length. * @param reason Optional, the BYE reason. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_rtcp_build_rtcp_bye( - pjmedia_rtcp_session *session, - void *buf, - pj_size_t *length, - const pj_str_t *reason); + pjmedia_rtcp_session *session, + void *buf, + pj_size_t *length, + const pj_str_t *reason); /** @@ -481,10 +480,10 @@ PJ_DECL(pj_status_t) pjmedia_rtcp_build_rtcp_bye( * @param session The RTCP session. * @param enable Enable/disable RTCP XR. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_rtcp_enable_xr( pjmedia_rtcp_session *session, - pj_bool_t enable); + pj_bool_t enable); /** @@ -494,4 +493,4 @@ PJ_DECL(pj_status_t) pjmedia_rtcp_enable_xr( pjmedia_rtcp_session *session, PJ_END_DECL -#endif /* __PJMEDIA_RTCP_H__ */ +#endif /* __PJMEDIA_RTCP_H__ */ diff --git a/pjmedia/include/pjmedia/rtcp_fb.h b/pjmedia/include/pjmedia/rtcp_fb.h index 0b27af452c..a142bfc73b 100644 --- a/pjmedia/include/pjmedia/rtcp_fb.h +++ b/pjmedia/include/pjmedia/rtcp_fb.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2018 Teluu Inc. (http://www.teluu.com) * @@ -85,7 +84,7 @@ typedef struct pjmedia_rtcp_fb_cap * pjmedia_vid_codec_mgr_find_codecs_by_id(), e.g: "L16/8000/1", "PCMU", * "H264". This can also be an asterisk ("*") to represent all codecs. */ - pj_str_t codec_id; + pj_str_t codec_id; /** * Specify the RTCP Feedback type. @@ -95,7 +94,7 @@ typedef struct pjmedia_rtcp_fb_cap /** * Specify the type name if RTCP Feedback type is PJMEDIA_RTCP_FB_OTHER. */ - pj_str_t type_name; + pj_str_t type_name; /** * Specify the RTCP Feedback parameters. Feedback subtypes should be @@ -105,7 +104,7 @@ typedef struct pjmedia_rtcp_fb_cap * - 'rpsi' for Reference Picture Selection Indication feedback, * - 'app' for specific/proprietary application layer feedback. */ - pj_str_t param; + pj_str_t param; } pjmedia_rtcp_fb_cap; @@ -118,12 +117,12 @@ typedef struct pjmedia_rtcp_fb_info /** * Number of RTCP Feedback capabilities. */ - unsigned cap_count; + unsigned cap_count; /** * The RTCP Feedback capabilities. */ - pjmedia_rtcp_fb_cap caps[PJMEDIA_RTCP_FB_MAX_CAP]; + pjmedia_rtcp_fb_cap caps[PJMEDIA_RTCP_FB_MAX_CAP]; } pjmedia_rtcp_fb_info; @@ -143,17 +142,17 @@ typedef struct pjmedia_rtcp_fb_setting * * Default: PJ_TRUE. */ - pj_bool_t dont_use_avpf; + pj_bool_t dont_use_avpf; /** * Number of RTCP Feedback capabilities. */ - unsigned cap_count; + unsigned cap_count; /** * The RTCP Feedback capabilities. */ - pjmedia_rtcp_fb_cap caps[PJMEDIA_RTCP_FB_MAX_CAP]; + pjmedia_rtcp_fb_cap caps[PJMEDIA_RTCP_FB_MAX_CAP]; } pjmedia_rtcp_fb_setting; @@ -163,9 +162,9 @@ typedef struct pjmedia_rtcp_fb_setting */ typedef struct pjmedia_rtcp_fb_nack { - pj_int32_t pid; /**< Packet ID (RTP seq) */ - pj_uint16_t blp; /**< Bitmask of following lost - packets */ + pj_int32_t pid; /**< Packet ID (RTP seq) */ + pj_uint16_t blp; /**< Bitmask of following lost + packets */ } pjmedia_rtcp_fb_nack; @@ -174,10 +173,10 @@ typedef struct pjmedia_rtcp_fb_nack */ typedef struct pjmedia_rtcp_fb_sli { - pj_uint16_t first; /**< First lost macroblock */ - pj_uint16_t number; /**< The number of lost macroblocks - packets */ - pj_uint8_t pict_id; /**< Picture ID (temporal ref) */ + pj_uint16_t first; /**< First lost macroblock */ + pj_uint16_t number; /**< The number of lost macroblocks + packets */ + pj_uint8_t pict_id; /**< Picture ID (temporal ref) */ } pjmedia_rtcp_fb_sli; @@ -187,9 +186,9 @@ typedef struct pjmedia_rtcp_fb_sli */ typedef struct pjmedia_rtcp_fb_rpsi { - pj_uint8_t pt; /**< Payload Type */ - pj_str_t rpsi; /**< Native RPSI bit string */ - pj_size_t rpsi_bit_len; /**< Length of RPSI in bit */ + pj_uint8_t pt; /**< Payload Type */ + pj_str_t rpsi; /**< Native RPSI bit string */ + pj_size_t rpsi_bit_len; /**< Length of RPSI in bit */ } pjmedia_rtcp_fb_rpsi; @@ -199,11 +198,11 @@ typedef struct pjmedia_rtcp_fb_rpsi */ typedef struct pjmedia_event_rx_rtcp_fb_data { - pjmedia_rtcp_fb_cap cap; + pjmedia_rtcp_fb_cap cap; union { - pjmedia_rtcp_fb_nack nack; - pjmedia_rtcp_fb_sli sli; - pjmedia_rtcp_fb_rpsi rpsi; + pjmedia_rtcp_fb_nack nack; + pjmedia_rtcp_fb_sli sli; + pjmedia_rtcp_fb_rpsi rpsi; } msg; } pjmedia_event_rx_rtcp_fb_data; @@ -212,38 +211,38 @@ typedef struct pjmedia_event_rx_rtcp_fb_data /** * Initialize RTCP Feedback setting with default values. * - * @param opt The RTCP Feedback setting to be initialized. + * @param opt The RTCP Feedback setting to be initialized. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_setting_default( - pjmedia_rtcp_fb_setting *opt); + pjmedia_rtcp_fb_setting *opt); /** * Duplicate RTCP Feedback setting. * - * @param pool Pool to be used for duplicating the config. - * @param dst Destination configuration. - * @param src Source configuration. + * @param pool Pool to be used for duplicating the config. + * @param dst Destination configuration. + * @param src Source configuration. * */ PJ_DECL(void) pjmedia_rtcp_fb_setting_dup(pj_pool_t *pool, - pjmedia_rtcp_fb_setting *dst, - const pjmedia_rtcp_fb_setting *src); + pjmedia_rtcp_fb_setting *dst, + const pjmedia_rtcp_fb_setting *src); /** * Duplicate RTCP Feedback info. * - * @param pool Pool to be used for duplicating the info. - * @param dst Destination info. - * @param src Source info. + * @param pool Pool to be used for duplicating the info. + * @param dst Destination info. + * @param src Source info. * */ PJ_DECL(void) pjmedia_rtcp_fb_info_dup(pj_pool_t *pool, - pjmedia_rtcp_fb_info *dst, - const pjmedia_rtcp_fb_info *src); + pjmedia_rtcp_fb_info *dst, + const pjmedia_rtcp_fb_info *src); /** @@ -252,44 +251,44 @@ PJ_DECL(void) pjmedia_rtcp_fb_info_dup(pj_pool_t *pool, * endpoint that local endpoint is capable and willing to receive RTCP * Feedback packets as described in the local SDP. * - * @param pool Pool object to allocate memory in updating local SDP. - * @param endpt The media endpoint. - * @param opt RTCP Feedback setting. - * @param sdp_local The local SDP to be filled in information from the - * media transport. - * @param med_idx The SDP media index. - * @param sdp_remote Remote SDP or NULL if local is offerer. + * @param pool Pool object to allocate memory in updating local SDP. + * @param endpt The media endpoint. + * @param opt RTCP Feedback setting. + * @param sdp_local The local SDP to be filled in information from the + * media transport. + * @param med_idx The SDP media index. + * @param sdp_remote Remote SDP or NULL if local is offerer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_encode_sdp( - pj_pool_t *pool, - pjmedia_endpt *endpt, - const pjmedia_rtcp_fb_setting *opt, - pjmedia_sdp_session *sdp_local, - unsigned med_idx, - const pjmedia_sdp_session *sdp_remote); + pj_pool_t *pool, + pjmedia_endpt *endpt, + const pjmedia_rtcp_fb_setting *opt, + pjmedia_sdp_session *sdp_local, + unsigned med_idx, + const pjmedia_sdp_session *sdp_remote); /** * Decode RTCP Feedback specific information from SDP media. * - * @param pool Pool object to allocate memory. - * @param endpt The media endpoint. - * @param opt Options, currently it must be NULL. - * @param sdp The SDP. - * @param med_idx The SDP media index. - * @param info The RTCP-FB info fetched from SDP. + * @param pool Pool object to allocate memory. + * @param endpt The media endpoint. + * @param opt Options, currently it must be NULL. + * @param sdp The SDP. + * @param med_idx The SDP media index. + * @param info The RTCP-FB info fetched from SDP. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_decode_sdp( - pj_pool_t *pool, - pjmedia_endpt *endpt, - const void *opt, - const pjmedia_sdp_session *sdp, - unsigned med_idx, - pjmedia_rtcp_fb_info *info); + pj_pool_t *pool, + pjmedia_endpt *endpt, + const void *opt, + const pjmedia_sdp_session *sdp, + unsigned med_idx, + pjmedia_rtcp_fb_info *info); /** @@ -297,24 +296,24 @@ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_decode_sdp( * payload type. If the payload type is set to negative value, it will decode * RTCP Feedback info for all payload types in the SDP media. * - * @param pool Pool object to allocate memory. - * @param endpt The media endpoint. - * @param opt Options, currently it must be NULL. - * @param sdp The SDP. - * @param med_idx The SDP media index. - * @param pt The payload type. - * @param info The RTCP-FB info fetched from SDP. + * @param pool Pool object to allocate memory. + * @param endpt The media endpoint. + * @param opt Options, currently it must be NULL. + * @param sdp The SDP. + * @param med_idx The SDP media index. + * @param pt The payload type. + * @param info The RTCP-FB info fetched from SDP. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_decode_sdp2( - pj_pool_t *pool, - pjmedia_endpt *endpt, - const void *opt, - const pjmedia_sdp_session *sdp, - unsigned med_idx, - int pt, - pjmedia_rtcp_fb_info *info); + pj_pool_t *pool, + pjmedia_endpt *endpt, + const void *opt, + const pjmedia_sdp_session *sdp, + unsigned med_idx, + int pt, + pjmedia_rtcp_fb_info *info); /** @@ -323,21 +322,21 @@ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_decode_sdp2( * See also RFC 4585 Section 6.2.1 about Generic NACK message. * * @param session The RTCP session. - * @param buf The buffer to receive RTCP Feedback packet. + * @param buf The buffer to receive RTCP Feedback packet. * @param length On input, it will contain the buffer length. - * On output, it will contain the generated RTCP Feedback - * packet length. + * On output, it will contain the generated RTCP Feedback + * packet length. * @param nack_cnt The number of RTCP Feedback Generic NACK messages. - * @param nack The array of RTCP Feedback Generic NACK messages. + * @param nack The array of RTCP Feedback Generic NACK messages. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_build_nack( - pjmedia_rtcp_session *session, - void *buf, - pj_size_t *length, - unsigned nack_cnt, - const pjmedia_rtcp_fb_nack nack[]); + pjmedia_rtcp_session *session, + void *buf, + pj_size_t *length, + unsigned nack_cnt, + const pjmedia_rtcp_fb_nack nack[]); /** @@ -346,17 +345,17 @@ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_build_nack( * compound RTCP packet. See also RFC 4585 Section 6.3.1 about PLI FB message. * * @param session The RTCP session. - * @param buf The buffer to receive RTCP Feedback packet. + * @param buf The buffer to receive RTCP Feedback packet. * @param length On input, it will contain the buffer length. - * On output, it will contain the generated RTCP Feedback - * packet length. + * On output, it will contain the generated RTCP Feedback + * packet length. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_build_pli( - pjmedia_rtcp_session *session, - void *buf, - pj_size_t *length); + pjmedia_rtcp_session *session, + void *buf, + pj_size_t *length); /** @@ -365,21 +364,21 @@ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_build_pli( * RTCP packet. See also RFC 4585 Section 6.3.2 about SLI FB message. * * @param session The RTCP session. - * @param buf The buffer to receive RTCP Feedback packet. + * @param buf The buffer to receive RTCP Feedback packet. * @param length On input, it will contain the buffer length. - * On output, it will contain the generated RTCP Feedback - * packet length. + * On output, it will contain the generated RTCP Feedback + * packet length. * @param sli_cnt The number of RTCP Feedback SLI messages. - * @param sli The array of RTCP Feedback SLI messages. + * @param sli The array of RTCP Feedback SLI messages. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_build_sli( - pjmedia_rtcp_session *session, - void *buf, - pj_size_t *length, - unsigned sli_cnt, - const pjmedia_rtcp_fb_sli sli[]); + pjmedia_rtcp_session *session, + void *buf, + pj_size_t *length, + unsigned sli_cnt, + const pjmedia_rtcp_fb_sli sli[]); /** @@ -389,75 +388,75 @@ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_build_sli( * RPSI FB message. * * @param session The RTCP session. - * @param buf The buffer to receive RTCP Feedback packet. + * @param buf The buffer to receive RTCP Feedback packet. * @param length On input, it will contain the buffer length. - * On output, it will contain the generated RTCP Feedback - * packet length. - * @param rpsi The RTCP Feedback RPSI message. + * On output, it will contain the generated RTCP Feedback + * packet length. + * @param rpsi The RTCP Feedback RPSI message. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_build_rpsi( - pjmedia_rtcp_session *session, - void *buf, - pj_size_t *length, - const pjmedia_rtcp_fb_rpsi *rpsi); + pjmedia_rtcp_session *session, + void *buf, + pj_size_t *length, + const pjmedia_rtcp_fb_rpsi *rpsi); /** * Check whether the specified payload contains RTCP feedback generic NACK * message, and parse the payload if it does. * - * @param buf The payload buffer. + * @param buf The payload buffer. * @param length The payload length. * @param nack_cnt On input, it specifies the maximum number of generic NACK - * messages. - * On output, it specifies the number of parsed generic NACK - * messages. - * @param nack The array of RTCP Feedback Generic NACK messages. + * messages. + * On output, it specifies the number of parsed generic NACK + * messages. + * @param nack The array of RTCP Feedback Generic NACK messages. * - * @return PJ_SUCCESS if the payload contains generic NACK message - * and has been parsed successfully. + * @return PJ_SUCCESS if the payload contains generic NACK message + * and has been parsed successfully. */ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_parse_nack( - const void *buf, - pj_size_t length, - unsigned *nack_cnt, - pjmedia_rtcp_fb_nack nack[]); + const void *buf, + pj_size_t length, + unsigned *nack_cnt, + pjmedia_rtcp_fb_nack nack[]); /** * Check whether the specified payload contains RTCP feedback Picture Loss * Indication (PLI) message. * - * @param buf The payload buffer. + * @param buf The payload buffer. * @param length The payload length. * - * @return PJ_SUCCESS if the payload contains PLI message. + * @return PJ_SUCCESS if the payload contains PLI message. */ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_parse_pli( - const void *buf, - pj_size_t length); + const void *buf, + pj_size_t length); /** * Check whether the specified payload contains RTCP feedback Slice Loss * Indication (SLI) message, and parse the payload if it does. * - * @param buf The payload buffer. + * @param buf The payload buffer. * @param length The payload length. * @param sli_cnt On input, it specifies the maximum number of SLI messages. - * On output, it specifies the number of parsed SLI messages. - * @param sli The array of RTCP Feedback SLI messages. + * On output, it specifies the number of parsed SLI messages. + * @param sli The array of RTCP Feedback SLI messages. * - * @return PJ_SUCCESS if the payload contains SLI messages and - * has been parsed successfully. + * @return PJ_SUCCESS if the payload contains SLI messages and + * has been parsed successfully. */ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_parse_sli( - const void *buf, - pj_size_t length, - unsigned *sli_cnt, - pjmedia_rtcp_fb_sli sli[]); + const void *buf, + pj_size_t length, + unsigned *sli_cnt, + pjmedia_rtcp_fb_sli sli[]); /** @@ -465,17 +464,17 @@ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_parse_sli( * Picture Selection Indication (RPSI) message, and parse the payload * if it does. * - * @param buf The payload buffer. + * @param buf The payload buffer. * @param length The payload length. - * @param rpsi The parsed RTCP Feedback RPSI messages. + * @param rpsi The parsed RTCP Feedback RPSI messages. * - * @return PJ_SUCCESS if the payload contains SLI messages and - * has been parsed successfully. + * @return PJ_SUCCESS if the payload contains SLI messages and + * has been parsed successfully. */ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_parse_rpsi( - const void *buf, - pj_size_t length, - pjmedia_rtcp_fb_rpsi *rpsi); + const void *buf, + pj_size_t length, + pjmedia_rtcp_fb_rpsi *rpsi); /** @@ -485,4 +484,4 @@ PJ_DECL(pj_status_t) pjmedia_rtcp_fb_parse_rpsi( PJ_END_DECL -#endif /* __PJMEDIA_RTCP_FB_H__ */ +#endif /* __PJMEDIA_RTCP_FB_H__ */ diff --git a/pjmedia/include/pjmedia/rtcp_xr.h b/pjmedia/include/pjmedia/rtcp_xr.h index fb204852ab..2d08955272 100644 --- a/pjmedia/include/pjmedia/rtcp_xr.h +++ b/pjmedia/include/pjmedia/rtcp_xr.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -47,12 +46,12 @@ PJ_BEGIN_DECL * combinations of RTCP XR report blocks. */ typedef enum { - PJMEDIA_RTCP_XR_LOSS_RLE = (1 << 0), - PJMEDIA_RTCP_XR_DUP_RLE = (1 << 1), - PJMEDIA_RTCP_XR_RCPT_TIMES = (1 << 2), - PJMEDIA_RTCP_XR_RR_TIME = (1 << 3), - PJMEDIA_RTCP_XR_DLRR = (1 << 4), - PJMEDIA_RTCP_XR_STATS = (1 << 5), + PJMEDIA_RTCP_XR_LOSS_RLE = (1 << 0), + PJMEDIA_RTCP_XR_DUP_RLE = (1 << 1), + PJMEDIA_RTCP_XR_RCPT_TIMES = (1 << 2), + PJMEDIA_RTCP_XR_RR_TIME = (1 << 3), + PJMEDIA_RTCP_XR_DLRR = (1 << 4), + PJMEDIA_RTCP_XR_STATS = (1 << 5), PJMEDIA_RTCP_XR_VOIP_METRICS = (1 << 6) } pjmedia_rtcp_xr_type; @@ -63,15 +62,15 @@ typedef enum { typedef enum { PJMEDIA_RTCP_XR_INFO_SIGNAL_LVL = 1, PJMEDIA_RTCP_XR_INFO_NOISE_LVL = 2, - PJMEDIA_RTCP_XR_INFO_RERL = 3, + PJMEDIA_RTCP_XR_INFO_RERL = 3, PJMEDIA_RTCP_XR_INFO_R_FACTOR = 4, - PJMEDIA_RTCP_XR_INFO_MOS_LQ = 5, - PJMEDIA_RTCP_XR_INFO_MOS_CQ = 6, + PJMEDIA_RTCP_XR_INFO_MOS_LQ = 5, + PJMEDIA_RTCP_XR_INFO_MOS_CQ = 6, PJMEDIA_RTCP_XR_INFO_CONF_PLC = 7, PJMEDIA_RTCP_XR_INFO_CONF_JBA = 8, PJMEDIA_RTCP_XR_INFO_CONF_JBR = 9, - PJMEDIA_RTCP_XR_INFO_JB_NOM = 10, - PJMEDIA_RTCP_XR_INFO_JB_MAX = 11, + PJMEDIA_RTCP_XR_INFO_JB_NOM = 10, + PJMEDIA_RTCP_XR_INFO_JB_MAX = 11, PJMEDIA_RTCP_XR_INFO_JB_ABS_MAX = 12 } pjmedia_rtcp_xr_info; @@ -79,10 +78,10 @@ typedef enum { * Enumeration of PLC types definitions for RTCP XR report. */ typedef enum { - PJMEDIA_RTCP_XR_PLC_UNK = 0, - PJMEDIA_RTCP_XR_PLC_DIS = 1, - PJMEDIA_RTCP_XR_PLC_ENH = 2, - PJMEDIA_RTCP_XR_PLC_STD = 3 + PJMEDIA_RTCP_XR_PLC_UNK = 0, + PJMEDIA_RTCP_XR_PLC_DIS = 1, + PJMEDIA_RTCP_XR_PLC_ENH = 2, + PJMEDIA_RTCP_XR_PLC_STD = 3 } pjmedia_rtcp_xr_plc_type; /** @@ -102,9 +101,9 @@ typedef enum { */ typedef struct pjmedia_rtcp_xr_rb_header { - pj_uint8_t bt; /**< Block type. */ - pj_uint8_t specific; /**< Block specific data. */ - pj_uint16_t length; /**< Block length. */ + pj_uint8_t bt; /**< Block type. */ + pj_uint8_t specific; /**< Block specific data. */ + pj_uint16_t length; /**< Block length. */ } pjmedia_rtcp_xr_rb_header; /** @@ -112,9 +111,9 @@ typedef struct pjmedia_rtcp_xr_rb_header */ typedef struct pjmedia_rtcp_xr_rb_rr_time { - pjmedia_rtcp_xr_rb_header header; /**< Block header. */ - pj_uint32_t ntp_sec; /**< NTP time, seconds part. */ - pj_uint32_t ntp_frac; /**< NTP time, fractions part. */ + pjmedia_rtcp_xr_rb_header header; /**< Block header. */ + pj_uint32_t ntp_sec; /**< NTP time, seconds part. */ + pj_uint32_t ntp_frac; /**< NTP time, fractions part. */ } pjmedia_rtcp_xr_rb_rr_time; @@ -123,10 +122,10 @@ typedef struct pjmedia_rtcp_xr_rb_rr_time */ typedef struct pjmedia_rtcp_xr_rb_dlrr_item { - pj_uint32_t ssrc; /**< receiver SSRC */ - pj_uint32_t lrr; /**< last receiver report */ - pj_uint32_t dlrr; /**< delay since last receiver - report */ + pj_uint32_t ssrc; /**< receiver SSRC */ + pj_uint32_t lrr; /**< last receiver report */ + pj_uint32_t dlrr; /**< delay since last receiver + report */ } pjmedia_rtcp_xr_rb_dlrr_item; /** @@ -134,9 +133,9 @@ typedef struct pjmedia_rtcp_xr_rb_dlrr_item */ typedef struct pjmedia_rtcp_xr_rb_dlrr { - pjmedia_rtcp_xr_rb_header header; /**< Block header. */ - pjmedia_rtcp_xr_rb_dlrr_item item; /**< Block contents, - variable length list */ + pjmedia_rtcp_xr_rb_header header; /**< Block header. */ + pjmedia_rtcp_xr_rb_dlrr_item item; /**< Block contents, + variable length list */ } pjmedia_rtcp_xr_rb_dlrr; /** @@ -144,23 +143,23 @@ typedef struct pjmedia_rtcp_xr_rb_dlrr */ typedef struct pjmedia_rtcp_xr_rb_stats { - pjmedia_rtcp_xr_rb_header header; /**< Block header. */ - pj_uint32_t ssrc; /**< Receiver SSRC */ - pj_uint16_t begin_seq; /**< Begin RTP sequence reported */ - pj_uint16_t end_seq; /**< End RTP sequence reported */ - pj_uint32_t lost; /**< Number of packet lost in this - interval */ - pj_uint32_t dup; /**< Number of duplicated packet in - this interval */ - pj_uint32_t jitter_min; /**< Minimum jitter in this interval */ - pj_uint32_t jitter_max; /**< Maximum jitter in this interval */ - pj_uint32_t jitter_mean; /**< Average jitter in this interval */ - pj_uint32_t jitter_dev; /**< Jitter deviation in this - interval */ - pj_uint32_t toh_min:8; /**< Minimum ToH in this interval */ - pj_uint32_t toh_max:8; /**< Maximum ToH in this interval */ - pj_uint32_t toh_mean:8; /**< Average ToH in this interval */ - pj_uint32_t toh_dev:8; /**< ToH deviation in this interval */ + pjmedia_rtcp_xr_rb_header header; /**< Block header. */ + pj_uint32_t ssrc; /**< Receiver SSRC */ + pj_uint16_t begin_seq; /**< Begin RTP sequence reported */ + pj_uint16_t end_seq; /**< End RTP sequence reported */ + pj_uint32_t lost; /**< Number of packet lost in this + interval */ + pj_uint32_t dup; /**< Number of duplicated packet in + this interval */ + pj_uint32_t jitter_min; /**< Minimum jitter in this interval */ + pj_uint32_t jitter_max; /**< Maximum jitter in this interval */ + pj_uint32_t jitter_mean; /**< Average jitter in this interval */ + pj_uint32_t jitter_dev; /**< Jitter deviation in this + interval */ + pj_uint32_t toh_min:8; /**< Minimum ToH in this interval */ + pj_uint32_t toh_max:8; /**< Maximum ToH in this interval */ + pj_uint32_t toh_mean:8; /**< Average ToH in this interval */ + pj_uint32_t toh_dev:8; /**< ToH deviation in this interval */ } pjmedia_rtcp_xr_rb_stats; /** @@ -168,36 +167,36 @@ typedef struct pjmedia_rtcp_xr_rb_stats */ typedef struct pjmedia_rtcp_xr_rb_voip_mtc { - pjmedia_rtcp_xr_rb_header header; /**< Block header. */ - pj_uint32_t ssrc; /**< Receiver SSRC */ - pj_uint8_t loss_rate; /**< Packet loss rate */ - pj_uint8_t discard_rate; /**< Packet discarded rate */ - pj_uint8_t burst_den; /**< Burst density */ - pj_uint8_t gap_den; /**< Gap density */ - pj_uint16_t burst_dur; /**< Burst duration */ - pj_uint16_t gap_dur; /**< Gap duration */ - pj_uint16_t rnd_trip_delay;/**< Round trip delay */ - pj_uint16_t end_sys_delay; /**< End system delay */ - pj_uint8_t signal_lvl; /**< Signal level */ - pj_uint8_t noise_lvl; /**< Noise level */ - pj_uint8_t rerl; /**< Residual Echo Return Loss */ - pj_uint8_t gmin; /**< The gap threshold */ - pj_uint8_t r_factor; /**< Voice quality metric carried - over this RTP session */ - pj_uint8_t ext_r_factor; /**< Voice quality metric carried - outside of this RTP session*/ - pj_uint8_t mos_lq; /**< Mean Opinion Score for - Listening Quality */ - pj_uint8_t mos_cq; /**< Mean Opinion Score for - Conversation Quality */ - pj_uint8_t rx_config; /**< Receiver configuration */ - pj_uint8_t reserved2; /**< Not used */ - pj_uint16_t jb_nom; /**< Current delay by jitter - buffer */ - pj_uint16_t jb_max; /**< Maximum delay by jitter - buffer */ - pj_uint16_t jb_abs_max; /**< Maximum possible delay by - jitter buffer */ + pjmedia_rtcp_xr_rb_header header; /**< Block header. */ + pj_uint32_t ssrc; /**< Receiver SSRC */ + pj_uint8_t loss_rate; /**< Packet loss rate */ + pj_uint8_t discard_rate; /**< Packet discarded rate */ + pj_uint8_t burst_den; /**< Burst density */ + pj_uint8_t gap_den; /**< Gap density */ + pj_uint16_t burst_dur; /**< Burst duration */ + pj_uint16_t gap_dur; /**< Gap duration */ + pj_uint16_t rnd_trip_delay;/**< Round trip delay */ + pj_uint16_t end_sys_delay; /**< End system delay */ + pj_uint8_t signal_lvl; /**< Signal level */ + pj_uint8_t noise_lvl; /**< Noise level */ + pj_uint8_t rerl; /**< Residual Echo Return Loss */ + pj_uint8_t gmin; /**< The gap threshold */ + pj_uint8_t r_factor; /**< Voice quality metric carried + over this RTP session */ + pj_uint8_t ext_r_factor; /**< Voice quality metric carried + outside of this RTP session*/ + pj_uint8_t mos_lq; /**< Mean Opinion Score for + Listening Quality */ + pj_uint8_t mos_cq; /**< Mean Opinion Score for + Conversation Quality */ + pj_uint8_t rx_config; /**< Receiver configuration */ + pj_uint8_t reserved2; /**< Not used */ + pj_uint16_t jb_nom; /**< Current delay by jitter + buffer */ + pj_uint16_t jb_max; /**< Maximum delay by jitter + buffer */ + pj_uint16_t jb_abs_max; /**< Maximum possible delay by + jitter buffer */ } pjmedia_rtcp_xr_rb_voip_mtc; @@ -218,22 +217,22 @@ typedef struct pjmedia_rtcp_xr_pkt { struct { #if defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN!=0 - unsigned version:2; /**< packet type */ - unsigned p:1; /**< padding flag */ - unsigned count:5; /**< varies by payload type */ - unsigned pt:8; /**< payload type */ + unsigned version:2; /**< packet type */ + unsigned p:1; /**< padding flag */ + unsigned count:5; /**< varies by payload type */ + unsigned pt:8; /**< payload type */ #else - unsigned count:5; /**< varies by payload type */ - unsigned p:1; /**< padding flag */ - unsigned version:2; /**< packet type */ - unsigned pt:8; /**< payload type */ + unsigned count:5; /**< varies by payload type */ + unsigned p:1; /**< padding flag */ + unsigned version:2; /**< packet type */ + unsigned pt:8; /**< payload type */ #endif - unsigned length:16; /**< packet length */ - pj_uint32_t ssrc; /**< SSRC identification */ + unsigned length:16; /**< packet length */ + pj_uint32_t ssrc; /**< SSRC identification */ } common; - pj_int8_t buf[PJMEDIA_RTCP_XR_BUF_SIZE]; - /**< Content buffer */ + pj_int8_t buf[PJMEDIA_RTCP_XR_BUF_SIZE]; + /**< Content buffer */ } pjmedia_rtcp_xr_pkt; #pragma pack() @@ -245,68 +244,68 @@ typedef struct pjmedia_rtcp_xr_pkt typedef struct pjmedia_rtcp_xr_stream_stat { struct { - pj_time_val update; /**< Time of last update. */ - - pj_uint32_t begin_seq; /**< Begin # seq of this interval. */ - pj_uint32_t end_seq; /**< End # seq of this interval. */ - unsigned count; /**< Number of packets. */ - - /** - * Flags represent whether the such report is valid/updated - */ - unsigned l:1; /**< Lost flag */ - unsigned d:1; /**< Duplicated flag */ - unsigned j:1; /**< Jitter flag */ - unsigned t:2; /**< TTL or Hop Limit, - 0=none, 1=TTL, 2=HL */ - - unsigned lost; /**< Number of packets lost */ - unsigned dup; /**< Number of duplicated packets */ - pj_math_stat jitter; /**< Jitter statistics (in usec) */ - pj_math_stat toh; /**< TTL of hop limit statistics. */ + pj_time_val update; /**< Time of last update. */ + + pj_uint32_t begin_seq; /**< Begin # seq of this interval. */ + pj_uint32_t end_seq; /**< End # seq of this interval. */ + unsigned count; /**< Number of packets. */ + + /** + * Flags represent whether the such report is valid/updated + */ + unsigned l:1; /**< Lost flag */ + unsigned d:1; /**< Duplicated flag */ + unsigned j:1; /**< Jitter flag */ + unsigned t:2; /**< TTL or Hop Limit, + 0=none, 1=TTL, 2=HL */ + + unsigned lost; /**< Number of packets lost */ + unsigned dup; /**< Number of duplicated packets */ + pj_math_stat jitter; /**< Jitter statistics (in usec) */ + pj_math_stat toh; /**< TTL of hop limit statistics. */ } stat_sum; struct { - pj_time_val update; /**< Time of last update. */ - - pj_uint8_t loss_rate; /**< Packet loss rate */ - pj_uint8_t discard_rate; /**< Packet discarded rate */ - pj_uint8_t burst_den; /**< Burst density */ - pj_uint8_t gap_den; /**< Gap density */ - pj_uint16_t burst_dur; /**< Burst duration */ - pj_uint16_t gap_dur; /**< Gap duration */ - pj_uint16_t rnd_trip_delay; /**< Round trip delay */ - pj_uint16_t end_sys_delay; /**< End system delay */ - pj_int8_t signal_lvl; /**< Signal level */ - pj_int8_t noise_lvl; /**< Noise level */ - pj_uint8_t rerl; /**< Residual Echo Return Loss */ - pj_uint8_t gmin; /**< The gap threshold */ - pj_uint8_t r_factor; /**< Voice quality metric carried - over this RTP session */ - pj_uint8_t ext_r_factor; /**< Voice quality metric carried - outside of this RTP session*/ - pj_uint8_t mos_lq; /**< Mean Opinion Score for - Listening Quality */ - pj_uint8_t mos_cq; /**< Mean Opinion Score for - Conversation Quality */ - pj_uint8_t rx_config; /**< Receiver configuration */ - pj_uint16_t jb_nom; /**< Current delay by jitter - buffer */ - pj_uint16_t jb_max; /**< Maximum delay by jitter - buffer */ - pj_uint16_t jb_abs_max; /**< Maximum possible delay by - jitter buffer */ + pj_time_val update; /**< Time of last update. */ + + pj_uint8_t loss_rate; /**< Packet loss rate */ + pj_uint8_t discard_rate; /**< Packet discarded rate */ + pj_uint8_t burst_den; /**< Burst density */ + pj_uint8_t gap_den; /**< Gap density */ + pj_uint16_t burst_dur; /**< Burst duration */ + pj_uint16_t gap_dur; /**< Gap duration */ + pj_uint16_t rnd_trip_delay; /**< Round trip delay */ + pj_uint16_t end_sys_delay; /**< End system delay */ + pj_int8_t signal_lvl; /**< Signal level */ + pj_int8_t noise_lvl; /**< Noise level */ + pj_uint8_t rerl; /**< Residual Echo Return Loss */ + pj_uint8_t gmin; /**< The gap threshold */ + pj_uint8_t r_factor; /**< Voice quality metric carried + over this RTP session */ + pj_uint8_t ext_r_factor; /**< Voice quality metric carried + outside of this RTP session*/ + pj_uint8_t mos_lq; /**< Mean Opinion Score for + Listening Quality */ + pj_uint8_t mos_cq; /**< Mean Opinion Score for + Conversation Quality */ + pj_uint8_t rx_config; /**< Receiver configuration */ + pj_uint16_t jb_nom; /**< Current delay by jitter + buffer */ + pj_uint16_t jb_max; /**< Maximum delay by jitter + buffer */ + pj_uint16_t jb_abs_max; /**< Maximum possible delay by + jitter buffer */ } voip_mtc; } pjmedia_rtcp_xr_stream_stat; typedef struct pjmedia_rtcp_xr_stat { - pjmedia_rtcp_xr_stream_stat rx; /**< Decoding direction statistics. */ - pjmedia_rtcp_xr_stream_stat tx; /**< Encoding direction statistics. */ - pj_math_stat rtt; /**< Round-trip delay stat (in usec) - the value is calculated from - receiver side. */ + pjmedia_rtcp_xr_stream_stat rx; /**< Decoding direction statistics. */ + pjmedia_rtcp_xr_stream_stat tx; /**< Encoding direction statistics. */ + pj_math_stat rtt; /**< Round-trip delay stat (in usec) + the value is calculated from + receiver side. */ } pjmedia_rtcp_xr_stat; /** @@ -320,45 +319,45 @@ struct pjmedia_rtcp_session; */ struct pjmedia_rtcp_xr_session { - char *name; /**< Name identification. */ - pjmedia_rtcp_xr_pkt pkt; /**< Cached RTCP XR packet. */ + char *name; /**< Name identification. */ + pjmedia_rtcp_xr_pkt pkt; /**< Cached RTCP XR packet. */ - pj_uint32_t rx_lrr; /**< NTP ts in last RR received. */ - pj_timestamp rx_lrr_time;/**< Time when last RR is received. */ - pj_uint32_t rx_last_rr; /**< # pkt received since last - sending RR time. */ + pj_uint32_t rx_lrr; /**< NTP ts in last RR received. */ + pj_timestamp rx_lrr_time;/**< Time when last RR is received. */ + pj_uint32_t rx_last_rr; /**< # pkt received since last + sending RR time. */ - pjmedia_rtcp_xr_stat stat; /**< RTCP XR statistics. */ + pjmedia_rtcp_xr_stat stat; /**< RTCP XR statistics. */ /* The reference sequence number is an extended sequence number * that serves as the basis for determining whether a new 16 bit * sequence number comes earlier or later in the 32 bit sequence * space. */ - pj_uint32_t src_ref_seq; - pj_bool_t uninitialized_src_ref_seq; + pj_uint32_t src_ref_seq; + pj_bool_t uninitialized_src_ref_seq; /* This structure contains variables needed for calculating * burst metrics. */ struct { - pj_uint32_t pkt; - pj_uint32_t lost; - pj_uint32_t loss_count; - pj_uint32_t discard_count; - pj_uint32_t c11; - pj_uint32_t c13; - pj_uint32_t c14; - pj_uint32_t c22; - pj_uint32_t c23; - pj_uint32_t c33; + pj_uint32_t pkt; + pj_uint32_t lost; + pj_uint32_t loss_count; + pj_uint32_t discard_count; + pj_uint32_t c11; + pj_uint32_t c13; + pj_uint32_t c14; + pj_uint32_t c22; + pj_uint32_t c23; + pj_uint32_t c33; } voip_mtc_stat; - unsigned ptime; /**< Packet time. */ - unsigned frames_per_packet; /**< # frames per packet. */ + unsigned ptime; /**< Packet time. */ + unsigned frames_per_packet; /**< # frames per packet. */ struct pjmedia_rtcp_session *rtcp_session; - /**< Parent/RTCP session. */ + /**< Parent/RTCP session. */ }; typedef struct pjmedia_rtcp_xr_session pjmedia_rtcp_xr_session; @@ -369,15 +368,15 @@ typedef struct pjmedia_rtcp_xr_session pjmedia_rtcp_xr_session; * * @param session The RTCP XR session. * @param rpt_types Report types to be included in the packet, report types - * are defined in pjmedia_rtcp_xr_type, set this to zero - * will make this function build all reports appropriately. + * are defined in pjmedia_rtcp_xr_type, set this to zero + * will make this function build all reports appropriately. * @param rtcp_pkt Upon return, it will contain pointer to the RTCP XR packet. - * @param len Upon return, it will indicate the size of the generated - * RTCP XR packet. + * @param len Upon return, it will indicate the size of the generated + * RTCP XR packet. */ PJ_DECL(void) pjmedia_rtcp_build_rtcp_xr( pjmedia_rtcp_xr_session *session, - unsigned rpt_types, - void **rtcp_pkt, int *len); + unsigned rpt_types, + void **rtcp_pkt, int *len); /** * Call this function to manually update some info needed by RTCP XR to @@ -385,13 +384,13 @@ PJ_DECL(void) pjmedia_rtcp_build_rtcp_xr( pjmedia_rtcp_xr_session *session, * RTP. * * @param session The RTCP XR session. - * @param info Info type to be updated, @see pjmedia_rtcp_xr_info. - * @param val Value. + * @param info Info type to be updated, @see pjmedia_rtcp_xr_info. + * @param val Value. */ PJ_DECL(pj_status_t) pjmedia_rtcp_xr_update_info( - pjmedia_rtcp_xr_session *session, - unsigned info, - pj_int32_t val); + pjmedia_rtcp_xr_session *session, + unsigned info, + pj_int32_t val); /* * Private APIs: @@ -405,12 +404,12 @@ PJ_DECL(pj_status_t) pjmedia_rtcp_xr_update_info( * @param r_session RTCP session. * @param gmin Gmin value (defined in RFC 3611), set to 0 for default (16). * @param frames_per_packet - Number of frames per packet. + Number of frames per packet. */ void pjmedia_rtcp_xr_init( pjmedia_rtcp_xr_session *session, - struct pjmedia_rtcp_session *r_session, - pj_uint8_t gmin, - unsigned frames_per_packet); + struct pjmedia_rtcp_session *r_session, + pj_uint8_t gmin, + unsigned frames_per_packet); /** * This function is called internally by RTCP session to destroy @@ -426,11 +425,11 @@ void pjmedia_rtcp_xr_fini( pjmedia_rtcp_xr_session *session ); * * @param session RTCP XR session. * @param rtcp_pkt The received RTCP XR packet. - * @param size Size of the incoming packet. + * @param size Size of the incoming packet. */ void pjmedia_rtcp_xr_rx_rtcp_xr( pjmedia_rtcp_xr_session *session, - const void *rtcp_pkt, - pj_size_t size); + const void *rtcp_pkt, + pj_size_t size); /** * This function is called internally by RTCP session whenever an RTP packet @@ -441,22 +440,22 @@ void pjmedia_rtcp_xr_rx_rtcp_xr( pjmedia_rtcp_xr_session *session, * should be -1 so no update will be done for this info in the RTCP XR session. * * @param session RTCP XR session. - * @param seq Sequence number of RTP packet. - * @param lost Info if this packet is lost. - * @param dup Info if this packet is a duplication. + * @param seq Sequence number of RTP packet. + * @param lost Info if this packet is lost. + * @param dup Info if this packet is a duplication. * @param discarded Info if this packet is discarded - * (not because of duplication). + * (not because of duplication). * @param jitter Info jitter of this packet. - * @param toh Info Time To Live or Hops Limit of this packet. + * @param toh Info Time To Live or Hops Limit of this packet. * @param toh_ipv4 Set PJ_TRUE if packet is transported over IPv4. */ void pjmedia_rtcp_xr_rx_rtp( pjmedia_rtcp_xr_session *session, - unsigned seq, - int lost, - int dup, - int discarded, - int jitter, - int toh, pj_bool_t toh_ipv4); + unsigned seq, + int lost, + int dup, + int discarded, + int jitter, + int toh, pj_bool_t toh_ipv4); /** * This function is called internally by RTCP session whenever an RTP @@ -466,7 +465,7 @@ void pjmedia_rtcp_xr_rx_rtp( pjmedia_rtcp_xr_session *session, * @param ptsize Size of RTP payload being sent. */ void pjmedia_rtcp_xr_tx_rtp( pjmedia_rtcp_xr_session *session, - unsigned ptsize ); + unsigned ptsize ); /** * @} @@ -475,4 +474,4 @@ void pjmedia_rtcp_xr_tx_rtp( pjmedia_rtcp_xr_session *session, PJ_END_DECL -#endif /* __PJMEDIA_RTCP_XR_H__ */ +#endif /* __PJMEDIA_RTCP_XR_H__ */ diff --git a/pjmedia/include/pjmedia/rtp.h b/pjmedia/include/pjmedia/rtp.h index 5af3724e0d..41a77ca8dd 100644 --- a/pjmedia/include/pjmedia/rtp.h +++ b/pjmedia/include/pjmedia/rtp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -86,23 +85,23 @@ PJ_BEGIN_DECL struct pjmedia_rtp_hdr { #if defined(PJ_IS_BIG_ENDIAN) && (PJ_IS_BIG_ENDIAN!=0) - pj_uint16_t v:2; /**< packet type/version */ - pj_uint16_t p:1; /**< padding flag */ - pj_uint16_t x:1; /**< extension flag */ - pj_uint16_t cc:4; /**< CSRC count */ - pj_uint16_t m:1; /**< marker bit */ - pj_uint16_t pt:7; /**< payload type */ + pj_uint16_t v:2; /**< packet type/version */ + pj_uint16_t p:1; /**< padding flag */ + pj_uint16_t x:1; /**< extension flag */ + pj_uint16_t cc:4; /**< CSRC count */ + pj_uint16_t m:1; /**< marker bit */ + pj_uint16_t pt:7; /**< payload type */ #else - pj_uint16_t cc:4; /**< CSRC count */ - pj_uint16_t x:1; /**< header extension flag */ - pj_uint16_t p:1; /**< padding flag */ - pj_uint16_t v:2; /**< packet type/version */ - pj_uint16_t pt:7; /**< payload type */ - pj_uint16_t m:1; /**< marker bit */ + pj_uint16_t cc:4; /**< CSRC count */ + pj_uint16_t x:1; /**< header extension flag */ + pj_uint16_t p:1; /**< padding flag */ + pj_uint16_t v:2; /**< packet type/version */ + pj_uint16_t pt:7; /**< payload type */ + pj_uint16_t m:1; /**< marker bit */ #endif - pj_uint16_t seq; /**< sequence number */ - pj_uint32_t ts; /**< timestamp */ - pj_uint32_t ssrc; /**< synchronization source */ + pj_uint16_t seq; /**< sequence number */ + pj_uint32_t ts; /**< timestamp */ + pj_uint32_t ssrc; /**< synchronization source */ }; #pragma pack() @@ -117,8 +116,8 @@ typedef struct pjmedia_rtp_hdr pjmedia_rtp_hdr; */ struct pjmedia_rtp_ext_hdr { - pj_uint16_t profile_data; /**< Profile data. */ - pj_uint16_t length; /**< Length. */ + pj_uint16_t profile_data; /**< Profile data. */ + pj_uint16_t length; /**< Length. */ }; /** @@ -149,9 +148,9 @@ typedef struct pjmedia_rtp_dec_hdr pjmedia_rtp_dec_hdr; */ struct pjmedia_rtp_dtmf_event { - pj_uint8_t event; /**< Event type ID. */ - pj_uint8_t e_vol; /**< Event volume. */ - pj_uint16_t duration; /**< Event duration. */ + pj_uint8_t event; /**< Event type ID. */ + pj_uint8_t e_vol; /**< Event volume. */ + pj_uint16_t duration; /**< Event duration. */ }; /** @@ -181,11 +180,11 @@ typedef struct pjmedia_rtp_dtmf_event pjmedia_rtp_dtmf_event; */ struct pjmedia_rtp_seq_session { - pj_uint16_t max_seq; /**< Highest sequence number heard */ - pj_uint32_t cycles; /**< Shifted count of seq number cycles */ - pj_uint32_t base_seq; /**< Base seq number */ - pj_uint32_t bad_seq; /**< Last 'bad' seq number + 1 */ - pj_uint32_t probation; /**< Sequ. packets till source is valid */ + pj_uint16_t max_seq; /**< Highest sequence number heard */ + pj_uint32_t cycles; /**< Shifted count of seq number cycles */ + pj_uint32_t base_seq; /**< Base seq number */ + pj_uint32_t bad_seq; /**< Last 'bad' seq number + 1 */ + pj_uint32_t probation; /**< Sequ. packets till source is valid */ }; /** @@ -199,13 +198,13 @@ typedef struct pjmedia_rtp_seq_session pjmedia_rtp_seq_session; */ struct pjmedia_rtp_session { - pjmedia_rtp_hdr out_hdr; /**< Saved hdr for outgoing pkts. */ + pjmedia_rtp_hdr out_hdr; /**< Saved hdr for outgoing pkts. */ pjmedia_rtp_seq_session seq_ctrl; /**< Sequence number management. */ - pj_uint16_t out_pt; /**< Default outgoing payload type. */ - pj_uint32_t out_extseq; /**< Outgoing extended seq #. */ - pj_bool_t has_peer_ssrc;/**< Has peer SSRC? */ - pj_uint32_t peer_ssrc; /**< Peer SSRC. */ - pj_uint32_t received; /**< Number of received packets. */ + pj_uint16_t out_pt; /**< Default outgoing payload type. */ + pj_uint32_t out_extseq; /**< Outgoing extended seq #. */ + pj_bool_t has_peer_ssrc;/**< Has peer SSRC? */ + pj_uint32_t peer_ssrc; /**< Peer SSRC. */ + pj_uint32_t received; /**< Number of received packets. */ }; /** @@ -221,34 +220,34 @@ typedef struct pjmedia_rtp_session pjmedia_rtp_session; struct pjmedia_rtp_status { union { - struct flag { - int bad:1; /**< General flag to indicate that sequence is - bad, and application should not process - this packet. More information will be given - in other flags. */ - int badpt:1; /**< Bad payload type. */ - int badssrc:1; /**< Bad SSRC */ - int dup:1; /**< Indicates duplicate packet */ - int outorder:1; /**< Indicates out of order packet */ - int probation:1;/**< Indicates that session is in probation - until more packets are received. */ - int restart:1; /**< Indicates that sequence number has made - a large jump, and internal base sequence - number has been adjusted. */ - } flag; /**< Status flags. */ - - pj_uint16_t value; /**< Status value, to conveniently address all - flags. */ - - } status; /**< Status information union. */ - - pj_uint16_t diff; /**< Sequence number difference from previous - packet. Normally the value should be 1. - Value greater than one may indicate packet - loss. If packet with lower sequence is - received, the value will be set to zero. - If base sequence has been restarted, the - value will be one. */ + struct flag { + int bad:1; /**< General flag to indicate that sequence is + bad, and application should not process + this packet. More information will be given + in other flags. */ + int badpt:1; /**< Bad payload type. */ + int badssrc:1; /**< Bad SSRC */ + int dup:1; /**< Indicates duplicate packet */ + int outorder:1; /**< Indicates out of order packet */ + int probation:1;/**< Indicates that session is in probation + until more packets are received. */ + int restart:1; /**< Indicates that sequence number has made + a large jump, and internal base sequence + number has been adjusted. */ + } flag; /**< Status flags. */ + + pj_uint16_t value; /**< Status value, to conveniently address all + flags. */ + + } status; /**< Status information union. */ + + pj_uint16_t diff; /**< Sequence number difference from previous + packet. Normally the value should be 1. + Value greater than one may indicate packet + loss. If packet with lower sequence is + received, the value will be set to zero. + If base sequence has been restarted, the + value will be one. */ }; @@ -257,19 +256,19 @@ struct pjmedia_rtp_status */ typedef struct pjmedia_rtp_session_setting { - pj_uint8_t flags; /**< Bitmask flags to specify whether such - field is set. Bitmask contents are: - (bit #0 is LSB) - bit #0: default payload type - bit #1: sender SSRC - bit #2: sequence - bit #3: timestamp - bit #4: peer SSRC */ - int default_pt; /**< Default payload type. */ - pj_uint32_t sender_ssrc; /**< Sender SSRC. */ - pj_uint32_t peer_ssrc; /**< Peer SSRC. */ - pj_uint16_t seq; /**< Sequence. */ - pj_uint32_t ts; /**< Timestamp. */ + pj_uint8_t flags; /**< Bitmask flags to specify whether such + field is set. Bitmask contents are: + (bit #0 is LSB) + bit #0: default payload type + bit #1: sender SSRC + bit #2: sequence + bit #3: timestamp + bit #4: peer SSRC */ + int default_pt; /**< Default payload type. */ + pj_uint32_t sender_ssrc; /**< Sender SSRC. */ + pj_uint32_t peer_ssrc; /**< Peer SSRC. */ + pj_uint16_t seq; /**< Sequence. */ + pj_uint32_t ts; /**< Timestamp. */ } pjmedia_rtp_session_setting; @@ -282,49 +281,49 @@ typedef struct pjmedia_rtp_status pjmedia_rtp_status; /** * This function will initialize the RTP session according to given parameters. * - * @param ses The session. - * @param default_pt Default payload type. - * @param sender_ssrc SSRC used for outgoing packets, in host byte order. + * @param ses The session. + * @param default_pt Default payload type. + * @param sender_ssrc SSRC used for outgoing packets, in host byte order. * - * @return PJ_SUCCESS if successfull. + * @return PJ_SUCCESS if successfull. */ PJ_DECL(pj_status_t) pjmedia_rtp_session_init( pjmedia_rtp_session *ses, - int default_pt, - pj_uint32_t sender_ssrc ); + int default_pt, + pj_uint32_t sender_ssrc ); /** * This function will initialize the RTP session according to given parameters * defined in RTP session settings. * - * @param ses The session. - * @param settings RTP session settings. + * @param ses The session. + * @param settings RTP session settings. * - * @return PJ_SUCCESS if successfull. + * @return PJ_SUCCESS if successfull. */ PJ_DECL(pj_status_t) pjmedia_rtp_session_init2( - pjmedia_rtp_session *ses, - pjmedia_rtp_session_setting settings); + pjmedia_rtp_session *ses, + pjmedia_rtp_session_setting settings); /** * Create the RTP header based on arguments and current state of the RTP * session. * - * @param ses The session. - * @param pt Payload type. - * @param m Marker flag. - * @param payload_len Payload length in bytes. - * @param ts_len Timestamp length. - * @param rtphdr Upon return will point to RTP packet header. - * @param hdrlen Upon return will indicate the size of RTP packet header + * @param ses The session. + * @param pt Payload type. + * @param m Marker flag. + * @param payload_len Payload length in bytes. + * @param ts_len Timestamp length. + * @param rtphdr Upon return will point to RTP packet header. + * @param hdrlen Upon return will indicate the size of RTP packet header * - * @return PJ_SUCCESS if successfull. + * @return PJ_SUCCESS if successfull. */ PJ_DECL(pj_status_t) pjmedia_rtp_encode_rtp( pjmedia_rtp_session *ses, - int pt, int m, - int payload_len, int ts_len, - const void **rtphdr, - int *hdrlen ); + int pt, int m, + int payload_len, int ts_len, + const void **rtphdr, + int *hdrlen ); /** * This function decodes incoming packet into RTP header and payload. @@ -334,24 +333,24 @@ PJ_DECL(pj_status_t) pjmedia_rtp_encode_rtp( pjmedia_rtp_session *ses, * Note that this function does not modify the returned RTP header to * host byte order. * - * @param ses The session. - * @param pkt The received RTP packet. - * @param pkt_len The length of the packet. - * @param hdr Upon return will point to the location of the RTP - * header inside the packet. Note that the RTP header - * will be given back as is, meaning that the fields - * will be in network byte order. - * @param payload Upon return will point to the location of the - * payload inside the packet. - * @param payloadlen Upon return will indicate the size of the payload. + * @param ses The session. + * @param pkt The received RTP packet. + * @param pkt_len The length of the packet. + * @param hdr Upon return will point to the location of the RTP + * header inside the packet. Note that the RTP header + * will be given back as is, meaning that the fields + * will be in network byte order. + * @param payload Upon return will point to the location of the + * payload inside the packet. + * @param payloadlen Upon return will indicate the size of the payload. * - * @return PJ_SUCCESS if successfull. + * @return PJ_SUCCESS if successfull. */ PJ_DECL(pj_status_t) pjmedia_rtp_decode_rtp( pjmedia_rtp_session *ses, - const void *pkt, int pkt_len, - const pjmedia_rtp_hdr **hdr, - const void **payload, - unsigned *payloadlen); + const void *pkt, int pkt_len, + const pjmedia_rtp_hdr **hdr, + const void **payload, + unsigned *payloadlen); /** @@ -362,43 +361,43 @@ PJ_DECL(pj_status_t) pjmedia_rtp_decode_rtp( pjmedia_rtp_session *ses, * Note that this function does not modify the returned RTP header to * host byte order. * - * @param ses The session. - * @param pkt The received RTP packet. - * @param pkt_len The length of the packet. - * @param hdr Upon return will point to the location of the RTP - * header inside the packet. Note that the RTP header - * will be given back as is, meaning that the fields - * will be in network byte order. - * @param dec_hdr Upon return will point to the location of the - * additional RTP header inside the packet, if any. - * @param payload Upon return will point to the location of the - * payload inside the packet. - * @param payloadlen Upon return will indicate the size of the payload. + * @param ses The session. + * @param pkt The received RTP packet. + * @param pkt_len The length of the packet. + * @param hdr Upon return will point to the location of the RTP + * header inside the packet. Note that the RTP header + * will be given back as is, meaning that the fields + * will be in network byte order. + * @param dec_hdr Upon return will point to the location of the + * additional RTP header inside the packet, if any. + * @param payload Upon return will point to the location of the + * payload inside the packet. + * @param payloadlen Upon return will indicate the size of the payload. * - * @return PJ_SUCCESS if successfull. + * @return PJ_SUCCESS if successfull. */ PJ_DECL(pj_status_t) pjmedia_rtp_decode_rtp2( - pjmedia_rtp_session *ses, - const void *pkt, int pkt_len, - const pjmedia_rtp_hdr **hdr, - pjmedia_rtp_dec_hdr *dec_hdr, - const void **payload, - unsigned *payloadlen); + pjmedia_rtp_session *ses, + const void *pkt, int pkt_len, + const pjmedia_rtp_hdr **hdr, + pjmedia_rtp_dec_hdr *dec_hdr, + const void **payload, + unsigned *payloadlen); /** * Call this function everytime an RTP packet is received to check whether * the packet can be received and to let the RTP session performs its internal * calculations. * - * @param ses The session. - * @param hdr The RTP header of the incoming packet. The header must - * be given with fields in network byte order. + * @param ses The session. + * @param hdr The RTP header of the incoming packet. The header must + * be given with fields in network byte order. * @param seq_st Optional structure to receive the status of the RTP packet - * processing. + * processing. */ PJ_DECL(void) pjmedia_rtp_session_update( pjmedia_rtp_session *ses, - const pjmedia_rtp_hdr *hdr, - pjmedia_rtp_status *seq_st); + const pjmedia_rtp_hdr *hdr, + pjmedia_rtp_status *seq_st); /** @@ -406,19 +405,19 @@ PJ_DECL(void) pjmedia_rtp_session_update( pjmedia_rtp_session *ses, * the packet can be received and to let the RTP session performs its internal * calculations. * - * @param ses The session. - * @param hdr The RTP header of the incoming packet. The header must - * be given with fields in network byte order. + * @param ses The session. + * @param hdr The RTP header of the incoming packet. The header must + * be given with fields in network byte order. * @param seq_st Optional structure to receive the status of the RTP packet - * processing. + * processing. * @param check_pt Flag to indicate whether payload type needs to be validate. * * @see pjmedia_rtp_session_update() */ PJ_DECL(void) pjmedia_rtp_session_update2(pjmedia_rtp_session *ses, - const pjmedia_rtp_hdr *hdr, - pjmedia_rtp_status *seq_st, - pj_bool_t check_pt); + const pjmedia_rtp_hdr *hdr, + pjmedia_rtp_status *seq_st, + pj_bool_t check_pt); /* @@ -430,23 +429,23 @@ PJ_DECL(void) pjmedia_rtp_session_update2(pjmedia_rtp_session *ses, * implementation. * * @param seq_ctrl The sequence control instance. - * @param seq Sequence number to initialize. + * @param seq Sequence number to initialize. */ void pjmedia_rtp_seq_init(pjmedia_rtp_seq_session *seq_ctrl, - pj_uint16_t seq); + pj_uint16_t seq); /** * Internal function update sequence control, shared by RTCP implementation. * - * @param seq_ctrl The sequence control instance. - * @param seq Sequence number to update. - * @param seq_status Optional structure to receive additional information - * about the packet. + * @param seq_ctrl The sequence control instance. + * @param seq Sequence number to update. + * @param seq_status Optional structure to receive additional information + * about the packet. */ void pjmedia_rtp_seq_update( pjmedia_rtp_seq_session *seq_ctrl, - pj_uint16_t seq, - pjmedia_rtp_status *seq_status); + pj_uint16_t seq, + pjmedia_rtp_status *seq_status); /** * @} @@ -455,4 +454,4 @@ void pjmedia_rtp_seq_update( pjmedia_rtp_seq_session *seq_ctrl, PJ_END_DECL -#endif /* __PJMEDIA_RTP_H__ */ +#endif /* __PJMEDIA_RTP_H__ */ diff --git a/pjmedia/include/pjmedia/sdp.h b/pjmedia/include/pjmedia/sdp.h index 4231b9fe22..46d82c3d93 100644 --- a/pjmedia/include/pjmedia/sdp.h +++ b/pjmedia/include/pjmedia/sdp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,7 +45,7 @@ PJ_BEGIN_DECL * The PJMEDIA_MAX_SDP_FMT macro defines maximum format in a media line. */ #ifndef PJMEDIA_MAX_SDP_FMT -# define PJMEDIA_MAX_SDP_FMT 32 +# define PJMEDIA_MAX_SDP_FMT 32 #endif /** @@ -54,7 +53,7 @@ PJ_BEGIN_DECL * lines in a media line. */ #ifndef PJMEDIA_MAX_SDP_BANDW -# define PJMEDIA_MAX_SDP_BANDW 4 +# define PJMEDIA_MAX_SDP_BANDW 4 #endif /** @@ -62,7 +61,7 @@ PJ_BEGIN_DECL * session descriptor. */ #ifndef PJMEDIA_MAX_SDP_ATTR -# define PJMEDIA_MAX_SDP_ATTR (PJMEDIA_MAX_SDP_FMT*2 + 4) +# define PJMEDIA_MAX_SDP_ATTR (PJMEDIA_MAX_SDP_FMT*2 + 4) #endif /** @@ -70,7 +69,7 @@ PJ_BEGIN_DECL * SDP session descriptor. */ #ifndef PJMEDIA_MAX_SDP_MEDIA -# define PJMEDIA_MAX_SDP_MEDIA 16 +# define PJMEDIA_MAX_SDP_MEDIA 16 #endif @@ -84,8 +83,8 @@ PJ_BEGIN_DECL */ struct pjmedia_sdp_attr { - pj_str_t name; /**< Attribute name. */ - pj_str_t value; /**< Attribute value. */ + pj_str_t name; /**< Attribute name. */ + pj_str_t value; /**< Attribute value. */ }; /** @@ -97,113 +96,113 @@ typedef struct pjmedia_sdp_attr pjmedia_sdp_attr; /** * Create SDP attribute. * - * @param pool Pool to create the attribute. - * @param name Attribute name. - * @param value Optional attribute value. + * @param pool Pool to create the attribute. + * @param name Attribute name. + * @param value Optional attribute value. * - * @return The new SDP attribute. + * @return The new SDP attribute. */ PJ_DECL(pjmedia_sdp_attr*) pjmedia_sdp_attr_create(pj_pool_t *pool, - const char *name, - const pj_str_t *value); + const char *name, + const pj_str_t *value); /** * Clone attribute * - * @param pool Pool to be used. - * @param attr The attribute to clone. + * @param pool Pool to be used. + * @param attr The attribute to clone. * - * @return New attribute as cloned from the attribute. + * @return New attribute as cloned from the attribute. */ PJ_DECL(pjmedia_sdp_attr*) pjmedia_sdp_attr_clone(pj_pool_t *pool, - const pjmedia_sdp_attr*attr); + const pjmedia_sdp_attr*attr); /** * Find the first attribute with the specified type. * - * @param count Number of attributes in the array. - * @param attr_array Array of attributes. - * @param name Attribute name to find. - * @param fmt Optional string to indicate which payload format - * to find for \a rtpmap and \a fmt attributes. For other - * types of attributes, the value should be NULL. + * @param count Number of attributes in the array. + * @param attr_array Array of attributes. + * @param name Attribute name to find. + * @param fmt Optional string to indicate which payload format + * to find for \a rtpmap and \a fmt attributes. For other + * types of attributes, the value should be NULL. * - * @return The specified attribute, or NULL if it can't be found. + * @return The specified attribute, or NULL if it can't be found. * * @see pjmedia_sdp_attr_find2, pjmedia_sdp_media_find_attr, - * pjmedia_sdp_media_find_attr2 + * pjmedia_sdp_media_find_attr2 */ PJ_DECL(pjmedia_sdp_attr*) pjmedia_sdp_attr_find(unsigned count, - pjmedia_sdp_attr *const attr_array[], - const pj_str_t *name, const pj_str_t *fmt); + pjmedia_sdp_attr *const attr_array[], + const pj_str_t *name, const pj_str_t *fmt); /** * Find the first attribute with the specified type. * - * @param count Number of attributes in the array. - * @param attr_array Array of attributes. - * @param name Attribute name to find. - * @param fmt Optional string to indicate which payload format - * to find for \a rtpmap and \a fmt attributes. For other - * types of attributes, the value should be NULL. + * @param count Number of attributes in the array. + * @param attr_array Array of attributes. + * @param name Attribute name to find. + * @param fmt Optional string to indicate which payload format + * to find for \a rtpmap and \a fmt attributes. For other + * types of attributes, the value should be NULL. * - * @return The specified attribute, or NULL if it can't be found. + * @return The specified attribute, or NULL if it can't be found. * * @see pjmedia_sdp_attr_find, pjmedia_sdp_media_find_attr, - * pjmedia_sdp_media_find_attr2 + * pjmedia_sdp_media_find_attr2 */ PJ_DECL(pjmedia_sdp_attr*) pjmedia_sdp_attr_find2(unsigned count, - pjmedia_sdp_attr *const attr_array[], - const char *name, const pj_str_t *fmt); + pjmedia_sdp_attr *const attr_array[], + const char *name, const pj_str_t *fmt); /** * Add a new attribute to array of attributes. * - * @param count Number of attributes in the array. - * @param attr_array Array of attributes. - * @param attr The attribute to add. + * @param count Number of attributes in the array. + * @param attr_array Array of attributes. + * @param attr The attribute to add. * - * @return PJ_SUCCESS or the error code. + * @return PJ_SUCCESS or the error code. * * @see pjmedia_sdp_media_add_attr */ PJ_DECL(pj_status_t) pjmedia_sdp_attr_add(unsigned *count, - pjmedia_sdp_attr *attr_array[], - pjmedia_sdp_attr *attr); + pjmedia_sdp_attr *attr_array[], + pjmedia_sdp_attr *attr); /** * Remove all attributes with the specified name in array of attributes. * - * @param count Number of attributes in the array. - * @param attr_array Array of attributes. - * @param name Attribute name to find. + * @param count Number of attributes in the array. + * @param attr_array Array of attributes. + * @param name Attribute name to find. * - * @return Number of attributes removed. + * @return Number of attributes removed. * * @see pjmedia_sdp_media_remove_all_attr */ PJ_DECL(unsigned) pjmedia_sdp_attr_remove_all(unsigned *count, - pjmedia_sdp_attr *attr_array[], - const char *name); + pjmedia_sdp_attr *attr_array[], + const char *name); /** * Remove the specified attribute from the attribute array. * - * @param count Number of attributes in the array. - * @param attr_array Array of attributes. - * @param attr The attribute instance to remove. + * @param count Number of attributes in the array. + * @param attr_array Array of attributes. + * @param attr The attribute instance to remove. * - * @return PJ_SUCCESS when attribute has been removed, or - * PJ_ENOTFOUND when the attribute can not be found. + * @return PJ_SUCCESS when attribute has been removed, or + * PJ_ENOTFOUND when the attribute can not be found. * * @see pjmedia_sdp_media_remove_attr */ PJ_DECL(pj_status_t) pjmedia_sdp_attr_remove(unsigned *count, - pjmedia_sdp_attr *attr_array[], - pjmedia_sdp_attr *attr); + pjmedia_sdp_attr *attr_array[], + pjmedia_sdp_attr *attr); /** @@ -211,10 +210,10 @@ PJ_DECL(pj_status_t) pjmedia_sdp_attr_remove(unsigned *count, */ struct pjmedia_sdp_rtpmap { - pj_str_t pt; /**< Payload type. */ - pj_str_t enc_name; /**< Encoding name. */ - unsigned clock_rate; /**< Clock rate. */ - pj_str_t param; /**< Parameter. */ + pj_str_t pt; /**< Payload type. */ + pj_str_t enc_name; /**< Encoding name. */ + unsigned clock_rate; /**< Clock rate. */ + pj_str_t param; /**< Parameter. */ }; /** @@ -227,51 +226,51 @@ typedef struct pjmedia_sdp_rtpmap pjmedia_sdp_rtpmap; * Convert generic attribute to SDP \a rtpmap. This function allocates * a new attribute and call #pjmedia_sdp_attr_get_rtpmap(). * - * @param pool Pool used to create the rtpmap attribute. - * @param attr Generic attribute to be converted to rtpmap, which - * name must be "rtpmap". - * @param p_rtpmap Pointer to receive SDP rtpmap attribute. + * @param pool Pool used to create the rtpmap attribute. + * @param attr Generic attribute to be converted to rtpmap, which + * name must be "rtpmap". + * @param p_rtpmap Pointer to receive SDP rtpmap attribute. * - * @return PJ_SUCCESS if the attribute can be successfully - * converted to \a rtpmap type. + * @return PJ_SUCCESS if the attribute can be successfully + * converted to \a rtpmap type. * * @see pjmedia_sdp_attr_get_rtpmap */ PJ_DECL(pj_status_t) pjmedia_sdp_attr_to_rtpmap(pj_pool_t *pool, - const pjmedia_sdp_attr *attr, - pjmedia_sdp_rtpmap **p_rtpmap); + const pjmedia_sdp_attr *attr, + pjmedia_sdp_rtpmap **p_rtpmap); /** * Get the rtpmap representation of the same SDP attribute. * - * @param attr Generic attribute to be converted to rtpmap, which - * name must be "rtpmap". Attribute value must be - * terminated with a NULL, CR, or LF character. - * @param rtpmap SDP \a rtpmap attribute to be initialized. + * @param attr Generic attribute to be converted to rtpmap, which + * name must be "rtpmap". Attribute value must be + * terminated with a NULL, CR, or LF character. + * @param rtpmap SDP \a rtpmap attribute to be initialized. * - * @return PJ_SUCCESS if the attribute can be successfully - * converted to \a rtpmap attribute. + * @return PJ_SUCCESS if the attribute can be successfully + * converted to \a rtpmap attribute. * * @see pjmedia_sdp_attr_to_rtpmap */ PJ_DECL(pj_status_t) pjmedia_sdp_attr_get_rtpmap(const pjmedia_sdp_attr *attr, - pjmedia_sdp_rtpmap *rtpmap); + pjmedia_sdp_rtpmap *rtpmap); /** * Convert \a rtpmap attribute to generic attribute. * - * @param pool Pool to be used. - * @param rtpmap The \a rtpmap attribute. - * @param p_attr Pointer to receive the generic SDP attribute. + * @param pool Pool to be used. + * @param rtpmap The \a rtpmap attribute. + * @param p_attr Pointer to receive the generic SDP attribute. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_sdp_rtpmap_to_attr( pj_pool_t *pool, - const pjmedia_sdp_rtpmap *rtpmap, - pjmedia_sdp_attr **p_attr); + const pjmedia_sdp_rtpmap *rtpmap, + pjmedia_sdp_attr **p_attr); /** @@ -279,22 +278,22 @@ pjmedia_sdp_rtpmap_to_attr( pj_pool_t *pool, */ typedef struct pjmedia_sdp_fmtp { - pj_str_t fmt; /**< Format type. */ - pj_str_t fmt_param; /**< Format specific parameter. */ + pj_str_t fmt; /**< Format type. */ + pj_str_t fmt_param; /**< Format specific parameter. */ } pjmedia_sdp_fmtp; /** * Get the fmtp representation of the same SDP attribute. * - * @param attr Generic attribute to be converted to fmtp, which - * name must be "fmtp". - * @param fmtp SDP fmtp attribute to be initialized. + * @param attr Generic attribute to be converted to fmtp, which + * name must be "fmtp". + * @param fmtp SDP fmtp attribute to be initialized. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_sdp_attr_get_fmtp(const pjmedia_sdp_attr *attr, - pjmedia_sdp_fmtp *fmtp); + pjmedia_sdp_fmtp *fmtp); /** @@ -302,36 +301,36 @@ PJ_DECL(pj_status_t) pjmedia_sdp_attr_get_fmtp(const pjmedia_sdp_attr *attr, */ typedef struct pjmedia_sdp_rtcp_attr { - unsigned port; /**< RTCP port number. */ - pj_str_t net_type; /**< Optional network type. */ - pj_str_t addr_type; /**< Optional address type. */ - pj_str_t addr; /**< Optional address. */ + unsigned port; /**< RTCP port number. */ + pj_str_t net_type; /**< Optional network type. */ + pj_str_t addr_type; /**< Optional address type. */ + pj_str_t addr; /**< Optional address. */ } pjmedia_sdp_rtcp_attr; /** * Parse a generic SDP attribute to get SDP rtcp attribute values. * - * @param attr Generic attribute to be converted to rtcp, which - * name must be "rtcp". - * @param rtcp SDP rtcp attribute to be initialized. + * @param attr Generic attribute to be converted to rtcp, which + * name must be "rtcp". + * @param rtcp SDP rtcp attribute to be initialized. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_sdp_attr_get_rtcp(const pjmedia_sdp_attr *attr, - pjmedia_sdp_rtcp_attr *rtcp); + pjmedia_sdp_rtcp_attr *rtcp); /** * Create a=rtcp attribute. * - * @param pool Pool to create the attribute. - * @param a Socket address. + * @param pool Pool to create the attribute. + * @param a Socket address. * - * @return SDP RTCP attribute. + * @return SDP RTCP attribute. */ PJ_DECL(pjmedia_sdp_attr*) pjmedia_sdp_attr_create_rtcp(pj_pool_t *pool, - const pj_sockaddr *a); + const pj_sockaddr *a); /** @@ -339,36 +338,36 @@ PJ_DECL(pjmedia_sdp_attr*) pjmedia_sdp_attr_create_rtcp(pj_pool_t *pool, */ typedef struct pjmedia_sdp_ssrc_attr { - pj_uint32_t ssrc; /**< RTP SSRC. */ - pj_str_t cname; /**< RTCP CNAME. */ + pj_uint32_t ssrc; /**< RTP SSRC. */ + pj_str_t cname; /**< RTCP CNAME. */ } pjmedia_sdp_ssrc_attr; /** * Parse a generic SDP attribute to get SDP ssrc attribute values. * - * @param attr Generic attribute to be converted to ssrc, which - * name must be "ssrc". - * @param rtcp SDP ssrc attribute to be initialized. + * @param attr Generic attribute to be converted to ssrc, which + * name must be "ssrc". + * @param rtcp SDP ssrc attribute to be initialized. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_sdp_attr_get_ssrc(const pjmedia_sdp_attr *attr, - pjmedia_sdp_ssrc_attr *rtcp); + pjmedia_sdp_ssrc_attr *rtcp); /** * Create a=ssrc attribute. * - * @param pool Pool to create the attribute. - * @param ssrc SSRC identifier. - * @param cname CNAME. + * @param pool Pool to create the attribute. + * @param ssrc SSRC identifier. + * @param cname CNAME. * - * @return SDP SSRC attribute. + * @return SDP SSRC attribute. */ PJ_DECL(pjmedia_sdp_attr*) pjmedia_sdp_attr_create_ssrc(pj_pool_t *pool, - pj_uint32_t ssrc, - const pj_str_t *cname); + pj_uint32_t ssrc, + const pj_str_t *cname); /* ************************************************************************** @@ -381,9 +380,9 @@ PJ_DECL(pjmedia_sdp_attr*) pjmedia_sdp_attr_create_ssrc(pj_pool_t *pool, */ struct pjmedia_sdp_conn { - pj_str_t net_type; /**< Network type ("IN"). */ - pj_str_t addr_type; /**< Address type ("IP4", "IP6"). */ - pj_str_t addr; /**< The address. */ + pj_str_t net_type; /**< Network type ("IN"). */ + pj_str_t addr_type; /**< Address type ("IP4", "IP6"). */ + pj_str_t addr; /**< The address. */ }; @@ -396,28 +395,28 @@ typedef struct pjmedia_sdp_conn pjmedia_sdp_conn; /** * Clone connection info. * - * @param pool Pool to allocate memory for the new connection info. - * @param rhs The connection into to clone. + * @param pool Pool to allocate memory for the new connection info. + * @param rhs The connection into to clone. * - * @return The new connection info. + * @return The new connection info. */ PJ_DECL(pjmedia_sdp_conn*) pjmedia_sdp_conn_clone(pj_pool_t *pool, - const pjmedia_sdp_conn *rhs); + const pjmedia_sdp_conn *rhs); /** * Compare connection info. * - * @param conn1 The first connection info to compare. - * @param conn2 The second connection info to compare. + * @param conn1 The first connection info to compare. + * @param conn2 The second connection info to compare. * @param option Comparison option, which should be zero for now. * - * @return PJ_SUCCESS when both connection info are equal, otherwise - * returns PJMEDIA_SDP_ECONNNOTEQUAL. + * @return PJ_SUCCESS when both connection info are equal, otherwise + * returns PJMEDIA_SDP_ECONNNOTEQUAL. */ PJ_DECL(pj_status_t) pjmedia_sdp_conn_cmp(const pjmedia_sdp_conn *conn1, - const pjmedia_sdp_conn *conn2, - unsigned option); + const pjmedia_sdp_conn *conn2, + unsigned option); /* ************************************************************************** @@ -430,18 +429,18 @@ PJ_DECL(pj_status_t) pjmedia_sdp_conn_cmp(const pjmedia_sdp_conn *conn1, */ typedef struct pjmedia_sdp_bandw { - pj_str_t modifier; /**< Bandwidth modifier. */ - pj_uint32_t value; /**< Bandwidth value. */ + pj_str_t modifier; /**< Bandwidth modifier. */ + pj_uint32_t value; /**< Bandwidth value. */ } pjmedia_sdp_bandw; /** * Clone bandwidth info. * - * @param pool Pool to allocate memory for the new bandwidth info. - * @param rhs The bandwidth into to clone. + * @param pool Pool to allocate memory for the new bandwidth info. + * @param rhs The bandwidth into to clone. * - * @return The new bandwidth info. + * @return The new bandwidth info. */ PJ_DECL(pjmedia_sdp_bandw*) pjmedia_sdp_bandw_clone(pj_pool_t *pool, const pjmedia_sdp_bandw *rhs); @@ -463,19 +462,19 @@ struct pjmedia_sdp_media /** Media descriptor line ("m=" line) */ struct { - pj_str_t media; /**< Media type ("audio", "video") */ - pj_uint16_t port; /**< Port number. */ - unsigned port_count; /**< Port count, used only when >2 */ - pj_str_t transport; /**< Transport ("RTP/AVP") */ - unsigned fmt_count; /**< Number of formats. */ - pj_str_t fmt[PJMEDIA_MAX_SDP_FMT]; /**< Media formats. */ + pj_str_t media; /**< Media type ("audio", "video") */ + pj_uint16_t port; /**< Port number. */ + unsigned port_count; /**< Port count, used only when >2 */ + pj_str_t transport; /**< Transport ("RTP/AVP") */ + unsigned fmt_count; /**< Number of formats. */ + pj_str_t fmt[PJMEDIA_MAX_SDP_FMT]; /**< Media formats. */ } desc; - pjmedia_sdp_conn *conn; /**< Optional connection info. */ - unsigned bandw_count; /**< Number of bandwidth info. */ + pjmedia_sdp_conn *conn; /**< Optional connection info. */ + unsigned bandw_count; /**< Number of bandwidth info. */ pjmedia_sdp_bandw *bandw[PJMEDIA_MAX_SDP_BANDW]; /**< Bandwidth info. */ - unsigned attr_count; /**< Number of attributes. */ - pjmedia_sdp_attr *attr[PJMEDIA_MAX_SDP_ATTR]; /**< Attributes. */ + unsigned attr_count; /**< Number of attributes. */ + pjmedia_sdp_attr *attr[PJMEDIA_MAX_SDP_ATTR]; /**< Attributes. */ }; @@ -488,139 +487,139 @@ typedef struct pjmedia_sdp_media pjmedia_sdp_media; /** * Print media description to a buffer. * - * @param media The media description. - * @param buf The buffer. - * @param size The buffer length. + * @param media The media description. + * @param buf The buffer. + * @param size The buffer length. * - * @return the length printed, or -1 if the buffer is too - * short. + * @return the length printed, or -1 if the buffer is too + * short. */ PJ_DECL(int) pjmedia_sdp_media_print(const pjmedia_sdp_media *media, char *buf, pj_size_t size); /** * Clone SDP media description. * - * @param pool Pool to allocate memory for the new media description. - * @param rhs The media descriptin to clone. + * @param pool Pool to allocate memory for the new media description. + * @param rhs The media descriptin to clone. * - * @return New media description. + * @return New media description. */ PJ_DECL(pjmedia_sdp_media*) pjmedia_sdp_media_clone( pj_pool_t *pool, - const pjmedia_sdp_media *rhs); + const pjmedia_sdp_media *rhs); /** * Find the first occurence of the specified attribute name in the media * descriptor. Optionally the format may be specified. * - * @param m The SDP media description. - * @param name Attribute name to find. - * @param fmt Optional payload type to match in the - * attribute list, when the attribute is \a rtpmap - * or \a fmtp. For other types of SDP attributes, this - * value should be NULL. + * @param m The SDP media description. + * @param name Attribute name to find. + * @param fmt Optional payload type to match in the + * attribute list, when the attribute is \a rtpmap + * or \a fmtp. For other types of SDP attributes, this + * value should be NULL. * - * @return The first instance of the specified attribute or NULL. + * @return The first instance of the specified attribute or NULL. */ PJ_DECL(pjmedia_sdp_attr*) pjmedia_sdp_media_find_attr(const pjmedia_sdp_media *m, - const pj_str_t *name, const pj_str_t *fmt); + const pj_str_t *name, const pj_str_t *fmt); /** * Find the first occurence of the specified attribute name in the SDP media * descriptor. Optionally the format may be specified. * - * @param m The SDP media description. - * @param name Attribute name to find. - * @param fmt Optional payload type to match in the - * attribute list, when the attribute is \a rtpmap - * or \a fmtp. For other types of SDP attributes, this - * value should be NULL. + * @param m The SDP media description. + * @param name Attribute name to find. + * @param fmt Optional payload type to match in the + * attribute list, when the attribute is \a rtpmap + * or \a fmtp. For other types of SDP attributes, this + * value should be NULL. * - * @return The first instance of the specified attribute or NULL. + * @return The first instance of the specified attribute or NULL. */ PJ_DECL(pjmedia_sdp_attr*) pjmedia_sdp_media_find_attr2(const pjmedia_sdp_media *m, - const char *name, const pj_str_t *fmt); + const char *name, const pj_str_t *fmt); /** * Add new attribute to the media descriptor. * - * @param m The SDP media description. - * @param attr Attribute to add. + * @param m The SDP media description. + * @param attr Attribute to add. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_sdp_media_add_attr(pjmedia_sdp_media *m, - pjmedia_sdp_attr *attr); + pjmedia_sdp_attr *attr); /** * Remove all attributes with the specified name from the SDP media * descriptor. * - * @param m The SDP media description. - * @param name Attribute name to remove. + * @param m The SDP media description. + * @param name Attribute name to remove. * - * @return The number of attributes removed. + * @return The number of attributes removed. */ PJ_DECL(unsigned) pjmedia_sdp_media_remove_all_attr(pjmedia_sdp_media *m, - const char *name); + const char *name); /** * Remove the occurence of the specified attribute from the SDP media * descriptor. * - * @param m The SDP media descriptor. - * @param attr The attribute to find and remove. + * @param m The SDP media descriptor. + * @param attr The attribute to find and remove. * - * @return PJ_SUCCESS if the attribute can be found and has - * been removed from the array. + * @return PJ_SUCCESS if the attribute can be found and has + * been removed from the array. */ PJ_DECL(pj_status_t) pjmedia_sdp_media_remove_attr(pjmedia_sdp_media *m, - pjmedia_sdp_attr *attr); + pjmedia_sdp_attr *attr); /** * Compare two SDP media for equality. * - * @param sd1 The first SDP media to compare. - * @param sd2 The second SDP media to compare. + * @param sd1 The first SDP media to compare. + * @param sd2 The second SDP media to compare. * @param option Comparison option, which should be zero for now. * - * @return PJ_SUCCESS when both SDP medias are equal, or the - * appropriate status code describing which part of - * the descriptors that are not equal. + * @return PJ_SUCCESS when both SDP medias are equal, or the + * appropriate status code describing which part of + * the descriptors that are not equal. */ PJ_DECL(pj_status_t) pjmedia_sdp_media_cmp(const pjmedia_sdp_media *sd1, - const pjmedia_sdp_media *sd2, - unsigned option); + const pjmedia_sdp_media *sd2, + unsigned option); /** * Compare two media transports for compatibility. * - * @param t1 The first media transport to compare. - * @param t2 The second media transport to compare. + * @param t1 The first media transport to compare. + * @param t2 The second media transport to compare. * - * @return PJ_SUCCESS when both media transports are compatible, - * otherwise returns PJMEDIA_SDP_ETPORTNOTEQUAL. + * @return PJ_SUCCESS when both media transports are compatible, + * otherwise returns PJMEDIA_SDP_ETPORTNOTEQUAL. */ PJ_DECL(pj_status_t) pjmedia_sdp_transport_cmp(const pj_str_t *t1, - const pj_str_t *t2); + const pj_str_t *t2); /** * Get media transport protocol info, i.e: base transport and profiles, * from the provided SDP media transport name string. * - * @param tp The SDP media transport name. + * @param tp The SDP media transport name. * - * @return Media transport info, combination of transport protocol - * and profile bit flag defined in pjmedia_tp_proto. + * @return Media transport info, combination of transport protocol + * and profile bit flag defined in pjmedia_tp_proto. */ PJ_DECL(pj_uint32_t) pjmedia_sdp_transport_get_proto(const pj_str_t *tp); @@ -628,27 +627,27 @@ PJ_DECL(pj_uint32_t) pjmedia_sdp_transport_get_proto(const pj_str_t *tp); /** * Deactivate SDP media. * - * @param pool Memory pool to allocate memory from. - * @param m The SDP media to deactivate. + * @param pool Memory pool to allocate memory from. + * @param m The SDP media to deactivate. * - * @return PJ_SUCCESS when SDP media successfully deactivated, - * otherwise appropriate status code returned. + * @return PJ_SUCCESS when SDP media successfully deactivated, + * otherwise appropriate status code returned. */ PJ_DECL(pj_status_t) pjmedia_sdp_media_deactivate(pj_pool_t *pool, - pjmedia_sdp_media *m); + pjmedia_sdp_media *m); /** * Clone SDP media description and deactivate the new SDP media. * - * @param pool Memory pool to allocate memory for the clone. - * @param rhs The SDP media to clone. + * @param pool Memory pool to allocate memory for the clone. + * @param rhs The SDP media to clone. * - * @return New media descrption with deactivated indication. + * @return New media descrption with deactivated indication. */ PJ_DECL(pjmedia_sdp_media*) pjmedia_sdp_media_clone_deactivate( - pj_pool_t *pool, - const pjmedia_sdp_media *rhs); + pj_pool_t *pool, + const pjmedia_sdp_media *rhs); /* ************************************************************************** @@ -667,32 +666,32 @@ struct pjmedia_sdp_session /** Session origin (o= line) */ struct { - pj_str_t user; /**< User */ - pj_uint32_t id; /**< Session ID */ - pj_uint32_t version; /**< Session version */ - pj_str_t net_type; /**< Network type ("IN") */ - pj_str_t addr_type; /**< Address type ("IP4", "IP6") */ - pj_str_t addr; /**< The address. */ + pj_str_t user; /**< User */ + pj_uint32_t id; /**< Session ID */ + pj_uint32_t version; /**< Session version */ + pj_str_t net_type; /**< Network type ("IN") */ + pj_str_t addr_type; /**< Address type ("IP4", "IP6") */ + pj_str_t addr; /**< The address. */ } origin; - pj_str_t name; /**< Subject line (s=) */ - pjmedia_sdp_conn *conn; /**< Connection line (c=) */ - unsigned bandw_count; /**< Number of bandwidth info (b=) */ + pj_str_t name; /**< Subject line (s=) */ + pjmedia_sdp_conn *conn; /**< Connection line (c=) */ + unsigned bandw_count; /**< Number of bandwidth info (b=) */ pjmedia_sdp_bandw *bandw[PJMEDIA_MAX_SDP_BANDW]; - /**< Bandwidth info array (b=) */ + /**< Bandwidth info array (b=) */ - /** Session time (t= line) */ + /** Session time (t= line) */ struct { - pj_uint32_t start; /**< Start time. */ - pj_uint32_t stop; /**< Stop time. */ + pj_uint32_t start; /**< Start time. */ + pj_uint32_t stop; /**< Stop time. */ } time; - unsigned attr_count; /**< Number of attributes. */ + unsigned attr_count; /**< Number of attributes. */ pjmedia_sdp_attr *attr[PJMEDIA_MAX_SDP_ATTR]; /**< Attributes array. */ - unsigned media_count; /**< Number of media. */ - pjmedia_sdp_media *media[PJMEDIA_MAX_SDP_MEDIA]; /**< Media array. */ + unsigned media_count; /**< Number of media. */ + pjmedia_sdp_media *media[PJMEDIA_MAX_SDP_MEDIA]; /**< Media array. */ }; @@ -709,30 +708,30 @@ typedef struct pjmedia_sdp_session pjmedia_sdp_session; * Note that the input message buffer MUST be NULL terminated and have * length at least len+1 (len MUST NOT include the NULL terminator). * - * @param pool The pool to allocate SDP session description. - * @param buf The message buffer, MUST be NULL terminated. - * @param len The length of the message, excluding NULL terminator. - * @param p_sdp Pointer to receive the SDP session descriptor. + * @param pool The pool to allocate SDP session description. + * @param buf The message buffer, MUST be NULL terminated. + * @param len The length of the message, excluding NULL terminator. + * @param p_sdp Pointer to receive the SDP session descriptor. * - * @return PJ_SUCCESS if message was successfully parsed into - * SDP session descriptor. + * @return PJ_SUCCESS if message was successfully parsed into + * SDP session descriptor. */ PJ_DECL(pj_status_t) pjmedia_sdp_parse( pj_pool_t *pool, - char *buf, pj_size_t len, - pjmedia_sdp_session **p_sdp ); + char *buf, pj_size_t len, + pjmedia_sdp_session **p_sdp ); /** * Print SDP description to a buffer. * - * @param sdp The SDP session description. - * @param buf The buffer. - * @param size The buffer length. + * @param sdp The SDP session description. + * @param buf The buffer. + * @param size The buffer length. * - * @return the length printed, or -1 if the buffer is too - * short. + * @return the length printed, or -1 if the buffer is too + * short. */ PJ_DECL(int) pjmedia_sdp_print( const pjmedia_sdp_session *sdp, - char *buf, pj_size_t size); + char *buf, pj_size_t size); /** @@ -742,9 +741,9 @@ PJ_DECL(int) pjmedia_sdp_print( const pjmedia_sdp_session *sdp, * the connection line, and verify that \a rtpmap attribute is present * when dynamic payload type is used. * - * @param sdp The SDP session descriptor to validate. + * @param sdp The SDP session descriptor to validate. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_sdp_validate(const pjmedia_sdp_session *sdp); @@ -756,55 +755,55 @@ PJ_DECL(pj_status_t) pjmedia_sdp_validate(const pjmedia_sdp_session *sdp); * the connection line, and verify that \a rtpmap attribute is present * when dynamic payload type is used. * - * @param sdp The SDP session descriptor to validate. + * @param sdp The SDP session descriptor to validate. * @param strict Flag whether the check should be strict, i.e: allow - * media without connection line when port is zero. + * media without connection line when port is zero. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_sdp_validate2(const pjmedia_sdp_session *sdp, - pj_bool_t strict); + pj_bool_t strict); /** * Clone SDP session descriptor. * - * @param pool The pool used to clone the session. - * @param sdp The SDP session to clone. + * @param pool The pool used to clone the session. + * @param sdp The SDP session to clone. * - * @return New SDP session. + * @return New SDP session. */ PJ_DECL(pjmedia_sdp_session*) pjmedia_sdp_session_clone( pj_pool_t *pool, - const pjmedia_sdp_session *sdp); + const pjmedia_sdp_session *sdp); /** * Compare two SDP session for equality. * - * @param sd1 The first SDP session to compare. - * @param sd2 The second SDP session to compare. + * @param sd1 The first SDP session to compare. + * @param sd2 The second SDP session to compare. * @param option Must be zero for now. * - * @return PJ_SUCCESS when both SDPs are equal, or otherwise - * the status code indicates which part of the session - * descriptors are not equal. + * @return PJ_SUCCESS when both SDPs are equal, or otherwise + * the status code indicates which part of the session + * descriptors are not equal. */ PJ_DECL(pj_status_t) pjmedia_sdp_session_cmp(const pjmedia_sdp_session *sd1, - const pjmedia_sdp_session *sd2, - unsigned option); + const pjmedia_sdp_session *sd2, + unsigned option); /** * Add new attribute to the session descriptor. * - * @param s The SDP session description. - * @param attr Attribute to add. + * @param s The SDP session description. + * @param attr Attribute to add. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_sdp_session_add_attr(pjmedia_sdp_session *s, - pjmedia_sdp_attr *attr); + pjmedia_sdp_attr *attr); PJ_END_DECL @@ -813,5 +812,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_SDP_H__ */ +#endif /* __PJMEDIA_SDP_H__ */ diff --git a/pjmedia/include/pjmedia/sdp_neg.h b/pjmedia/include/pjmedia/sdp_neg.h index 864058448f..92bb0bccbd 100644 --- a/pjmedia/include/pjmedia/sdp_neg.h +++ b/pjmedia/include/pjmedia/sdp_neg.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -331,9 +330,9 @@ typedef enum pjmedia_mod_offer_flag /** * Get the state string description of the specified state. * - * @param state Negotiator state. + * @param state Negotiator state. * - * @return String description of the state. + * @return String description of the state. */ PJ_DECL(const char*) pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_state state); @@ -348,18 +347,18 @@ PJ_DECL(const char*) pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_state state); * to remote party using signaling protocol such as SIP and wait for SDP * answer. * - * @param pool Pool to allocate memory. The pool's lifetime needs - * to be valid for the duration of the negotiator. - * @param local The initial local capability. - * @param p_neg Pointer to receive the negotiator instance. + * @param pool Pool to allocate memory. The pool's lifetime needs + * to be valid for the duration of the negotiator. + * @param local The initial local capability. + * @param p_neg Pointer to receive the negotiator instance. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_create_w_local_offer( pj_pool_t *pool, - const pjmedia_sdp_session *local, - pjmedia_sdp_neg **p_neg); + const pjmedia_sdp_session *local, + pjmedia_sdp_neg **p_neg); /** * Initialize the SDP negotiator with remote offer, and optionally @@ -378,20 +377,20 @@ pjmedia_sdp_neg_create_w_local_offer( pj_pool_t *pool, * local answer later with #pjmedia_sdp_neg_set_local_answer(), before * calling the negotiation function. * - * @param pool Pool to allocate memory. The pool's lifetime needs - * to be valid for the duration of the negotiator. - * @param initial Optional initial local capability. - * @param remote The remote offer. - * @param p_neg Pointer to receive the negotiator instance. + * @param pool Pool to allocate memory. The pool's lifetime needs + * to be valid for the duration of the negotiator. + * @param initial Optional initial local capability. + * @param remote The remote offer. + * @param p_neg Pointer to receive the negotiator instance. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_create_w_remote_offer(pj_pool_t *pool, - const pjmedia_sdp_session *initial, - const pjmedia_sdp_session *remote, - pjmedia_sdp_neg **p_neg); + const pjmedia_sdp_session *initial, + const pjmedia_sdp_session *remote, + pjmedia_sdp_neg **p_neg); /** * This specifies the behavior of the SDP negotiator when responding to an @@ -407,14 +406,14 @@ pjmedia_sdp_neg_create_w_remote_offer(pj_pool_t *pool, * By default, the value in PJMEDIA_SDP_NEG_PREFER_REMOTE_CODEC_ORDER will * be used. * - * @param neg The SDP negotiator instance. - * @param prefer_remote If non-zero, the negotiator will use the codec - * order as specified in remote offer. If zero, it - * will prefer to use the local codec order. + * @param neg The SDP negotiator instance. + * @param prefer_remote If non-zero, the negotiator will use the codec + * order as specified in remote offer. If zero, it + * will prefer to use the local codec order. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_set_prefer_remote_codec_order(pjmedia_sdp_neg *neg, - pj_bool_t prefer_remote); + pj_bool_t prefer_remote); /** * This specifies the behavior of the SDP negotiator when responding to an @@ -437,9 +436,9 @@ pjmedia_sdp_neg_set_answer_multiple_codecs(pjmedia_sdp_neg *neg, /** * Get SDP negotiator state. * - * @param neg The SDP negotiator instance. + * @param neg The SDP negotiator instance. * - * @return The negotiator state. + * @return The negotiator state. */ PJ_DECL(pjmedia_sdp_neg_state) pjmedia_sdp_neg_get_state( pjmedia_sdp_neg *neg ); @@ -450,14 +449,14 @@ pjmedia_sdp_neg_get_state( pjmedia_sdp_neg *neg ); * active SDPs. Calling this function will not change the state of the * negotiator. * - * @param neg The SDP negotiator instance. - * @param local Pointer to receive the local active SDP. + * @param neg The SDP negotiator instance. + * @param local Pointer to receive the local active SDP. * - * @return PJ_SUCCESS if local active SDP is present. + * @return PJ_SUCCESS if local active SDP is present. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_get_active_local( pjmedia_sdp_neg *neg, - const pjmedia_sdp_session **local); + const pjmedia_sdp_session **local); /** * Get the currently active remote SDP. Application can only call this @@ -465,14 +464,14 @@ pjmedia_sdp_neg_get_active_local( pjmedia_sdp_neg *neg, * active SDPs. Calling this function will not change the state of the * negotiator. * - * @param neg The SDP negotiator instance. - * @param remote Pointer to receive the remote active SDP. + * @param neg The SDP negotiator instance. + * @param remote Pointer to receive the remote active SDP. * - * @return PJ_SUCCESS if remote active SDP is present. + * @return PJ_SUCCESS if remote active SDP is present. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_get_active_remote( pjmedia_sdp_neg *neg, - const pjmedia_sdp_session **remote); + const pjmedia_sdp_session **remote); /** @@ -480,11 +479,11 @@ pjmedia_sdp_neg_get_active_remote( pjmedia_sdp_neg *neg, * last negotiation. This function can only be called in state * PJMEDIA_SDP_NEG_STATE_DONE. * - * @param neg The SDP negotiator instance. + * @param neg The SDP negotiator instance. * - * @return Non-zero if it was remote who sent answer, - * otherwise zero if it was local who supplied - * answer. + * @return Non-zero if it was remote who sent answer, + * otherwise zero if it was local who supplied + * answer. */ PJ_DECL(pj_bool_t) pjmedia_sdp_neg_was_answer_remote(pjmedia_sdp_neg *neg); @@ -497,16 +496,16 @@ pjmedia_sdp_neg_was_answer_remote(pjmedia_sdp_neg *neg); * SDP offer/answer. Calling this function will not change the state * of the negotiator. * - * @param neg The SDP negotiator instance. - * @param remote Pointer to receive the current remote offer or - * answer. + * @param neg The SDP negotiator instance. + * @param remote Pointer to receive the current remote offer or + * answer. * - * @return PJ_SUCCESS if the negotiator currently has - * remote offer or answer. + * @return PJ_SUCCESS if the negotiator currently has + * remote offer or answer. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_get_neg_remote( pjmedia_sdp_neg *neg, - const pjmedia_sdp_session **remote); + const pjmedia_sdp_session **remote); /** @@ -516,16 +515,16 @@ pjmedia_sdp_neg_get_neg_remote( pjmedia_sdp_neg *neg, * SDP offer/answer. Calling this function will not change the state * of the negotiator. * - * @param neg The SDP negotiator instance. - * @param local Pointer to receive the current local offer or - * answer. + * @param neg The SDP negotiator instance. + * @param local Pointer to receive the current local offer or + * answer. * - * @return PJ_SUCCESS if the negotiator currently has - * local offer or answer. + * @return PJ_SUCCESS if the negotiator currently has + * local offer or answer. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_get_neg_local( pjmedia_sdp_neg *neg, - const pjmedia_sdp_session **local); + const pjmedia_sdp_session **local); /** * Modify local session with a new SDP and treat this as a new offer. @@ -536,18 +535,18 @@ pjmedia_sdp_neg_get_neg_local( pjmedia_sdp_neg *neg, * where it waits for SDP answer from remote. See also * #pjmedia_sdp_neg_modify_local_offer2() * - * @param pool Pool to allocate memory. The pool's lifetime needs - * to be valid for the duration of the negotiator. - * @param neg The SDP negotiator instance. - * @param local The new local SDP. + * @param pool Pool to allocate memory. The pool's lifetime needs + * to be valid for the duration of the negotiator. + * @param neg The SDP negotiator instance. + * @param local The new local SDP. * - * @return PJ_SUCCESS on success, or the appropriate - * error code. + * @return PJ_SUCCESS on success, or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_modify_local_offer( pj_pool_t *pool, - pjmedia_sdp_neg *neg, - const pjmedia_sdp_session *local); + pjmedia_sdp_neg *neg, + const pjmedia_sdp_session *local); /** * Modify local session with a new SDP and treat this as a new offer. @@ -557,20 +556,20 @@ pjmedia_sdp_neg_modify_local_offer( pj_pool_t *pool, * The negotiator state will move to PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER, * where it waits for SDP answer from remote. * - * @param pool Pool to allocate memory. The pool's lifetime needs - * to be valid for the duration of the negotiator. - * @param neg The SDP negotiator instance. + * @param pool Pool to allocate memory. The pool's lifetime needs + * to be valid for the duration of the negotiator. + * @param neg The SDP negotiator instance. * @param flags Bitmask from pjmedia_mod_offer_flag. - * @param local The new local SDP. + * @param local The new local SDP. * - * @return PJ_SUCCESS on success, or the appropriate - * error code. + * @return PJ_SUCCESS on success, or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_modify_local_offer2( pj_pool_t *pool, - pjmedia_sdp_neg *neg, + pjmedia_sdp_neg *neg, unsigned flags, - const pjmedia_sdp_session *local); + const pjmedia_sdp_session *local); /** * This function can only be called in PJMEDIA_SDP_NEG_STATE_DONE state. @@ -582,18 +581,18 @@ pjmedia_sdp_neg_modify_local_offer2( pj_pool_t *pool, * When SDP answer has been received from remote, application must call * #pjmedia_sdp_neg_set_remote_answer(). * - * @param pool Pool to allocate memory. The pool's lifetime needs - * to be valid for the duration of the negotiator. - * @param neg The SDP negotiator instance. - * @param offer Pointer to receive active local SDP to be - * offered to remote. + * @param pool Pool to allocate memory. The pool's lifetime needs + * to be valid for the duration of the negotiator. + * @param neg The SDP negotiator instance. + * @param offer Pointer to receive active local SDP to be + * offered to remote. * - * @return PJ_SUCCESS if local offer can be created. + * @return PJ_SUCCESS if local offer can be created. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_send_local_offer( pj_pool_t *pool, - pjmedia_sdp_neg *neg, - const pjmedia_sdp_session **offer); + pjmedia_sdp_neg *neg, + const pjmedia_sdp_session **offer); /** * This function can only be called in PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER @@ -603,17 +602,17 @@ pjmedia_sdp_neg_send_local_offer( pj_pool_t *pool, * move to PJMEDIA_SDP_NEG_STATE_WAIT_NEGO, and application can call the * negotiation function #pjmedia_sdp_neg_negotiate(). * - * @param pool Pool to allocate memory. The pool's lifetime needs - * to be valid for the duration of the negotiator. - * @param neg The SDP negotiator instance. - * @param remote The remote answer. + * @param pool Pool to allocate memory. The pool's lifetime needs + * to be valid for the duration of the negotiator. + * @param neg The SDP negotiator instance. + * @param remote The remote answer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_set_remote_answer( pj_pool_t *pool, - pjmedia_sdp_neg *neg, - const pjmedia_sdp_session *remote); + pjmedia_sdp_neg *neg, + const pjmedia_sdp_session *remote); @@ -625,17 +624,17 @@ pjmedia_sdp_neg_set_remote_answer( pj_pool_t *pool, * #pjmedia_sdp_neg_set_local_answer() to set local answer before it can * call the negotiation function. * - * @param pool Pool to allocate memory. The pool's lifetime needs - * to be valid for the duration of the negotiator. - * @param neg The SDP negotiator instance. - * @param remote The remote offer. + * @param pool Pool to allocate memory. The pool's lifetime needs + * to be valid for the duration of the negotiator. + * @param neg The SDP negotiator instance. + * @param remote The remote offer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_set_remote_offer( pj_pool_t *pool, - pjmedia_sdp_neg *neg, - const pjmedia_sdp_session *remote); + pjmedia_sdp_neg *neg, + const pjmedia_sdp_session *remote); @@ -646,23 +645,23 @@ pjmedia_sdp_neg_set_remote_offer( pj_pool_t *pool, * move to PJMEDIA_SDP_NEG_STATE_WAIT_NEGO, and application can call the * negotiation function #pjmedia_sdp_neg_negotiate(). * - * @param pool Pool to allocate memory. The pool's lifetime needs - * to be valid for the duration of the negotiator. - * @param neg The SDP negotiator instance. - * @param local Optional local answer. If negotiator has initial - * local capability, application can specify NULL on - * this argument; in this case, the negotiator will - * create answer by by negotiating remote offer with - * initial local capability. If negotiator doesn't have - * initial local capability, application MUST specify - * local answer here. + * @param pool Pool to allocate memory. The pool's lifetime needs + * to be valid for the duration of the negotiator. + * @param neg The SDP negotiator instance. + * @param local Optional local answer. If negotiator has initial + * local capability, application can specify NULL on + * this argument; in this case, the negotiator will + * create answer by by negotiating remote offer with + * initial local capability. If negotiator doesn't have + * initial local capability, application MUST specify + * local answer here. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_set_local_answer( pj_pool_t *pool, - pjmedia_sdp_neg *neg, - const pjmedia_sdp_session *local); + pjmedia_sdp_neg *neg, + const pjmedia_sdp_session *local); /** @@ -670,10 +669,10 @@ pjmedia_sdp_neg_set_local_answer( pj_pool_t *pool, * state to see if it was local who is answering the offer (instead of * remote). * - * @param neg The negotiator. + * @param neg The negotiator. * - * @return PJ_TRUE if it is local is answering an offer, PJ_FALSE - * if remote has answered local offer. + * @return PJ_TRUE if it is local is answering an offer, PJ_FALSE + * if remote has answered local offer. */ PJ_DECL(pj_bool_t) pjmedia_sdp_neg_has_local_answer(pjmedia_sdp_neg *neg); @@ -685,9 +684,9 @@ PJ_DECL(pj_bool_t) pjmedia_sdp_neg_has_local_answer(pjmedia_sdp_neg *neg); * PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER or PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER * state. * - * @param neg The negotiator. + * @param neg The negotiator. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_cancel_offer(pjmedia_sdp_neg *neg); @@ -706,18 +705,18 @@ PJ_DECL(pj_status_t) pjmedia_sdp_neg_cancel_offer(pjmedia_sdp_neg *neg); * If the negotiation fails, the active local and remote SDP will not * change. * - * @param pool Pool to allocate memory. The pool's lifetime needs - * to be valid for the duration of the negotiator. - * @param neg The SDP negotiator instance. - * @param allow_asym Should be zero. + * @param pool Pool to allocate memory. The pool's lifetime needs + * to be valid for the duration of the negotiator. + * @param neg The SDP negotiator instance. + * @param allow_asym Should be zero. * - * @return PJ_SUCCESS when there is at least one media - * is actuve common in both offer and answer, or - * failure code when negotiation has failed. + * @return PJ_SUCCESS when there is at least one media + * is actuve common in both offer and answer, or + * failure code when negotiation has failed. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_negotiate( pj_pool_t *pool, - pjmedia_sdp_neg *neg, - pj_bool_t allow_asym); + pjmedia_sdp_neg *neg, + pj_bool_t allow_asym); /** @@ -742,22 +741,22 @@ typedef enum pjmedia_sdp_neg_fmt_match_flag * The declaration of customized SDP format matching callback. See * #pjmedia_sdp_neg_register_fmt_match_cb() for more info. * - * @param pool The memory pool. - * @param offer The SDP media offer. - * @param o_fmt_idx Index of the format in the SDP media offer. - * @param answer The SDP media answer. - * @param a_fmt_idx Index of the format in the SDP media answer. - * @param option The format matching option, see - * #pjmedia_sdp_neg_fmt_match_flag. + * @param pool The memory pool. + * @param offer The SDP media offer. + * @param o_fmt_idx Index of the format in the SDP media offer. + * @param answer The SDP media answer. + * @param a_fmt_idx Index of the format in the SDP media answer. + * @param option The format matching option, see + * #pjmedia_sdp_neg_fmt_match_flag. * - * @return PJ_SUCCESS when the formats in offer and answer match. + * @return PJ_SUCCESS when the formats in offer and answer match. */ typedef pj_status_t (*pjmedia_sdp_neg_fmt_match_cb)(pj_pool_t *pool, - pjmedia_sdp_media *offer, - unsigned o_fmt_idx, - pjmedia_sdp_media *answer, - unsigned a_fmt_idx, - unsigned option); + pjmedia_sdp_media *offer, + unsigned o_fmt_idx, + pjmedia_sdp_media *answer, + unsigned a_fmt_idx, + unsigned option); /** @@ -773,17 +772,17 @@ typedef pj_status_t (*pjmedia_sdp_neg_fmt_match_cb)(pj_pool_t *pool, * To unregister the callback of specific format, just call this function with * parameter cb set to NULL. * - * @param fmt_name The format name, e.g: "H.264", "AMR", "G7221". Note - * that the string buffer must remain valid until the - * callback is unregistered. - * @param cb The customized SDP format negotiation callback or - * NULL to unregister the specified format callback. + * @param fmt_name The format name, e.g: "H.264", "AMR", "G7221". Note + * that the string buffer must remain valid until the + * callback is unregistered. + * @param cb The customized SDP format negotiation callback or + * NULL to unregister the specified format callback. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_register_fmt_match_cb( - const pj_str_t *fmt_name, - pjmedia_sdp_neg_fmt_match_cb cb); + const pj_str_t *fmt_name, + pjmedia_sdp_neg_fmt_match_cb cb); /** @@ -794,22 +793,22 @@ PJ_DECL(pj_status_t) pjmedia_sdp_neg_register_fmt_match_cb( * #pjmedia_sdp_neg_register_fmt_match_cb(), it will be called for * more detail verification, e.g: format parameters specified in SDP fmtp. * - * @param pool The memory pool. - * @param offer The SDP media offer. - * @param o_fmt_idx Index of the format in the SDP media offer. - * @param answer The SDP media answer. - * @param a_fmt_idx Index of the format in the SDP media answer. - * @param option The format matching option, see - * #pjmedia_sdp_neg_fmt_match_flag. + * @param pool The memory pool. + * @param offer The SDP media offer. + * @param o_fmt_idx Index of the format in the SDP media offer. + * @param answer The SDP media answer. + * @param a_fmt_idx Index of the format in the SDP media answer. + * @param option The format matching option, see + * #pjmedia_sdp_neg_fmt_match_flag. * - * @return PJ_SUCCESS when the formats in offer and answer match. + * @return PJ_SUCCESS when the formats in offer and answer match. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_fmt_match( pj_pool_t *pool, - pjmedia_sdp_media *offer, - unsigned o_fmt_idx, - pjmedia_sdp_media *answer, - unsigned a_fmt_idx, - unsigned option); + pjmedia_sdp_media *offer, + unsigned o_fmt_idx, + pjmedia_sdp_media *answer, + unsigned a_fmt_idx, + unsigned option); PJ_END_DECL @@ -819,5 +818,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_SDP_NEG_H__ */ +#endif /* __PJMEDIA_SDP_NEG_H__ */ diff --git a/pjmedia/include/pjmedia/session.h b/pjmedia/include/pjmedia/session.h index 44238c5639..c3414ea23e 100644 --- a/pjmedia/include/pjmedia/session.h +++ b/pjmedia/include/pjmedia/session.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -60,10 +59,10 @@ PJ_BEGIN_DECL struct pjmedia_session_info { /** Number of streams. */ - unsigned stream_cnt; + unsigned stream_cnt; /** Individual stream info. */ - pjmedia_stream_info stream_info[PJMEDIA_MAX_SDP_MEDIA]; + pjmedia_stream_info stream_info[PJMEDIA_MAX_SDP_MEDIA]; }; @@ -85,22 +84,22 @@ typedef struct pjmedia_session_info pjmedia_session_info; * taken from default codec parameters. If socket info array is specified, * the socket will be copied to the session info as well. * - * @param pool Pool to allocate memory. - * @param endpt Pjmedia endpoint. - * @param max_streams Maximum number of stream infos to be created. - * @param si Session info structure to be initialized. - * @param local Local SDP session descriptor. - * @param remote Remote SDP session descriptor. + * @param pool Pool to allocate memory. + * @param endpt Pjmedia endpoint. + * @param max_streams Maximum number of stream infos to be created. + * @param si Session info structure to be initialized. + * @param local Local SDP session descriptor. + * @param remote Remote SDP session descriptor. * - * @return PJ_SUCCESS if stream info is successfully initialized. + * @return PJ_SUCCESS if stream info is successfully initialized. */ PJ_DECL(pj_status_t) pjmedia_session_info_from_sdp( pj_pool_t *pool, - pjmedia_endpt *endpt, - unsigned max_streams, - pjmedia_session_info *si, - const pjmedia_sdp_session *local, - const pjmedia_sdp_session *remote); + pjmedia_endpt *endpt, + unsigned max_streams, + pjmedia_session_info *si, + const pjmedia_sdp_session *local, + const pjmedia_sdp_session *remote); /** @@ -110,22 +109,22 @@ pjmedia_session_info_from_sdp( pj_pool_t *pool, * If socket info array is specified, the socket will be copied to the * session info as well. * - * @param si Stream info structure to be initialized. - * @param pool Pool to allocate memory. - * @param endpt PJMEDIA endpoint instance. - * @param local Local SDP session descriptor. - * @param remote Remote SDP session descriptor. - * @param stream_idx Media stream index in the session descriptor. + * @param si Stream info structure to be initialized. + * @param pool Pool to allocate memory. + * @param endpt PJMEDIA endpoint instance. + * @param local Local SDP session descriptor. + * @param remote Remote SDP session descriptor. + * @param stream_idx Media stream index in the session descriptor. * - * @return PJ_SUCCESS if stream info is successfully initialized. + * @return PJ_SUCCESS if stream info is successfully initialized. */ PJ_DECL(pj_status_t) pjmedia_stream_info_from_sdp( pjmedia_stream_info *si, - pj_pool_t *pool, - pjmedia_endpt *endpt, - const pjmedia_sdp_session *local, - const pjmedia_sdp_session *remote, - unsigned stream_idx); + pj_pool_t *pool, + pjmedia_endpt *endpt, + const pjmedia_sdp_session *local, + const pjmedia_sdp_session *remote, + unsigned stream_idx); /** * Create media session based on the local and remote SDP. After the session @@ -137,43 +136,43 @@ pjmedia_stream_info_from_sdp( pjmedia_stream_info *si, * Without application calling put_frame() and get_frame(), there will be * no media frames transmitted or received by the session. * - * @param endpt The PJMEDIA endpoint instance. - * @param si Session info containing stream count and array of - * stream info. The stream count indicates how many - * streams to be created in the session. - * @param transports Array of media stream transports, with - * sufficient number of elements (one for each stream). - * @param user_data Arbitrary user data to be kept in the session. - * @param p_session Pointer to receive the media session. - * - * @return PJ_SUCCESS if media session can be created - * successfully. + * @param endpt The PJMEDIA endpoint instance. + * @param si Session info containing stream count and array of + * stream info. The stream count indicates how many + * streams to be created in the session. + * @param transports Array of media stream transports, with + * sufficient number of elements (one for each stream). + * @param user_data Arbitrary user data to be kept in the session. + * @param p_session Pointer to receive the media session. + * + * @return PJ_SUCCESS if media session can be created + * successfully. */ PJ_DECL(pj_status_t) pjmedia_session_create( pjmedia_endpt *endpt, - const pjmedia_session_info *si, - pjmedia_transport *transports[], - void *user_data, - pjmedia_session **p_session ); + const pjmedia_session_info *si, + pjmedia_transport *transports[], + void *user_data, + pjmedia_session **p_session ); /** * Get media session info of the session. * - * @param session The session which info is being queried. - * @param info Pointer to receive session info. + * @param session The session which info is being queried. + * @param info Pointer to receive session info. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_get_info( pjmedia_session *session, - pjmedia_session_info *info ); + pjmedia_session_info *info ); /** * Get user data of the session. * - * @param session The session being queried. + * @param session The session being queried. * - * @return User data of the session. + * @return User data of the session. */ PJ_DECL(void*) pjmedia_session_get_user_data( pjmedia_session *session); @@ -183,60 +182,60 @@ PJ_DECL(void*) pjmedia_session_get_user_data( pjmedia_session *session); * Application only needs to call this function if it previously paused * the session. * - * @param session The media session. - * @param dir The direction to activate. + * @param session The media session. + * @param dir The direction to activate. * - * @return PJ_SUCCESS if success. + * @return PJ_SUCCESS if success. */ PJ_DECL(pj_status_t) pjmedia_session_resume(pjmedia_session *session, - pjmedia_dir dir); + pjmedia_dir dir); /** * Suspend receipt and transmission of all streams in media session * for the specified direction. * - * @param session The media session. - * @param dir The media direction to suspend. + * @param session The media session. + * @param dir The media direction to suspend. * - * @return PJ_SUCCESS if success. + * @return PJ_SUCCESS if success. */ PJ_DECL(pj_status_t) pjmedia_session_pause(pjmedia_session *session, - pjmedia_dir dir); + pjmedia_dir dir); /** * Suspend receipt and transmission of individual stream in media session * for the specified direction. * - * @param session The media session. - * @param index The stream index. - * @param dir The media direction to pause. + * @param session The media session. + * @param index The stream index. + * @param dir The media direction to pause. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_pause_stream( pjmedia_session *session, - unsigned index, - pjmedia_dir dir); + unsigned index, + pjmedia_dir dir); /** * Activate individual stream in media session for the specified direction. * - * @param session The media session. - * @param index The stream index. - * @param dir The media direction to activate. + * @param session The media session. + * @param index The stream index. + * @param dir The media direction to activate. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_resume_stream(pjmedia_session *session, - unsigned index, - pjmedia_dir dir); + unsigned index, + pjmedia_dir dir); /** * Send RTCP SDES for the session. * - * @param session The media session. + * @param session The media session. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_send_rtcp_sdes( const pjmedia_session *session ); @@ -244,9 +243,9 @@ pjmedia_session_send_rtcp_sdes( const pjmedia_session *session ); /** * Send RTCP BYE for the session. * - * @param session The media session. + * @param session The media session. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_send_rtcp_bye( const pjmedia_session *session ); @@ -254,18 +253,18 @@ pjmedia_session_send_rtcp_bye( const pjmedia_session *session ); /** * Enumerate media streams in the session. * - * @param session The media session. - * @param count On input, specifies the number of elements in - * the array. On output, the number will be filled - * with number of streams in the session. - * @param strm_info Array of stream info. + * @param session The media session. + * @param count On input, specifies the number of elements in + * the array. On output, the number will be filled + * with number of streams in the session. + * @param strm_info Array of stream info. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_enum_streams( const pjmedia_session *session, - unsigned *count, - pjmedia_stream_info strm_info[]); + unsigned *count, + pjmedia_stream_info strm_info[]); /** @@ -274,16 +273,16 @@ pjmedia_session_enum_streams( const pjmedia_session *session, * only way for application to transmit and receive media frames from the * stream. * - * @param session The media session. - * @param index Stream index. - * @param p_port Pointer to receive the media port interface for - * the specified stream. + * @param session The media session. + * @param index Stream index. + * @param p_port Pointer to receive the media port interface for + * the specified stream. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_get_port( pjmedia_session *session, - unsigned index, - pjmedia_port **p_port); + unsigned index, + pjmedia_port **p_port); /** @@ -291,27 +290,27 @@ PJ_DECL(pj_status_t) pjmedia_session_get_port( pjmedia_session *session, * indicators such as packet count, packet lost, jitter, delay, etc. * See also #pjmedia_session_get_stream_stat_jbuf() * - * @param session The media session. - * @param index Stream index. - * @param stat Stream statistic. + * @param session The media session. + * @param index Stream index. + * @param stat Stream statistic. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_get_stream_stat(pjmedia_session *session, - unsigned index, - pjmedia_rtcp_stat *stat); + unsigned index, + pjmedia_rtcp_stat *stat); /** * Reset session statistics. * - * @param session The media session. - * @param index Stream index. + * @param session The media session. + * @param index Stream index. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_reset_stream_stat(pjmedia_session *session, - unsigned index); + unsigned index); #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) @@ -320,16 +319,16 @@ PJ_DECL(pj_status_t) pjmedia_session_reset_stream_stat(pjmedia_session *session, * from RTCP XR, such as per interval statistics summary (packet count, * packet lost, jitter, etc), VoIP metrics (delay, quality, etc) * - * @param session The media session. - * @param index Stream index. - * @param stat_xr Stream extended statistics. + * @param session The media session. + * @param index Stream index. + * @param stat_xr Stream extended statistics. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_get_stream_stat_xr( - pjmedia_session *session, - unsigned index, - pjmedia_rtcp_xr_stat *stat_xr); + pjmedia_session *session, + unsigned index, + pjmedia_rtcp_xr_stat *stat_xr); #endif @@ -337,91 +336,91 @@ PJ_DECL(pj_status_t) pjmedia_session_get_stream_stat_xr( * Get current jitter buffer state for the specified stream. * See also #pjmedia_session_get_stream_stat() * - * @param session The media session. - * @param index Stream index. - * @param state Jitter buffer state. + * @param session The media session. + * @param index Stream index. + * @param state Jitter buffer state. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_get_stream_stat_jbuf( - pjmedia_session *session, - unsigned index, - pjmedia_jb_state *state); + pjmedia_session *session, + unsigned index, + pjmedia_jb_state *state); /** * Dial DTMF digit to the stream, using RFC 2833 mechanism. * - * @param session The media session. - * @param index The stream index. - * @param ascii_digits String of ASCII digits (i.e. 0-9*##A-B). + * @param session The media session. + * @param index The stream index. + * @param ascii_digits String of ASCII digits (i.e. 0-9*##A-B). * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_dial_dtmf( pjmedia_session *session, - unsigned index, - const pj_str_t *ascii_digits ); + unsigned index, + const pj_str_t *ascii_digits ); /** * Check if the specified stream has received DTMF digits. * - * @param session The media session. - * @param index The stream index. + * @param session The media session. + * @param index The stream index. * - * @return Non-zero (PJ_TRUE) if the stream has DTMF digits. + * @return Non-zero (PJ_TRUE) if the stream has DTMF digits. */ PJ_DECL(pj_status_t) pjmedia_session_check_dtmf( pjmedia_session *session, - unsigned index); + unsigned index); /** * Retrieve DTMF digits from the specified stream. * - * @param session The media session. - * @param index The stream index. - * @param ascii_digits Buffer to receive the digits. The length of this - * buffer is indicated in the "size" argument. - * @param size On input, contains the maximum digits to be copied - * to the buffer. - * On output, it contains the actual digits that has - * been copied to the buffer. + * @param session The media session. + * @param index The stream index. + * @param ascii_digits Buffer to receive the digits. The length of this + * buffer is indicated in the "size" argument. + * @param size On input, contains the maximum digits to be copied + * to the buffer. + * On output, it contains the actual digits that has + * been copied to the buffer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_get_dtmf( pjmedia_session *session, - unsigned index, - char *ascii_digits, - unsigned *size ); + unsigned index, + char *ascii_digits, + unsigned *size ); /** * Set callback to be called upon receiving DTMF digits. If callback is * registered, the stream will not buffer incoming DTMF but rather call * the callback as soon as DTMF digit is received completely. * - * @param session The media session. - * @param index The stream index. - * @param cb Callback to be called upon receiving DTMF digits. - * The DTMF digits will be given to the callback as - * ASCII digits. - * @param user_data User data to be returned back when the callback - * is called. + * @param session The media session. + * @param index The stream index. + * @param cb Callback to be called upon receiving DTMF digits. + * The DTMF digits will be given to the callback as + * ASCII digits. + * @param user_data User data to be returned back when the callback + * is called. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_session_set_dtmf_callback(pjmedia_session *session, - unsigned index, - void (*cb)(pjmedia_stream*, - void *user_data, - int digit), - void *user_data); + unsigned index, + void (*cb)(pjmedia_stream*, + void *user_data, + int digit), + void *user_data); /** * Destroy media session. * - * @param session The media session. + * @param session The media session. * - * @return PJ_SUCCESS if success. + * @return PJ_SUCCESS if success. */ PJ_DECL(pj_status_t) pjmedia_session_destroy(pjmedia_session *session); @@ -433,4 +432,4 @@ PJ_DECL(pj_status_t) pjmedia_session_destroy(pjmedia_session *session); PJ_END_DECL -#endif /* __PJMEDIA_SESSION_H__ */ +#endif /* __PJMEDIA_SESSION_H__ */ diff --git a/pjmedia/include/pjmedia/signatures.h b/pjmedia/include/pjmedia/signatures.h index 7d5a86660b..e9d12454c4 100644 --- a/pjmedia/include/pjmedia/signatures.h +++ b/pjmedia/include/pjmedia/signatures.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011-2011 Teluu Inc. (http://www.teluu.com) * @@ -45,7 +44,7 @@ PJ_BEGIN_DECL * macro: * * \verbatim - #define PJMEDIA_SIGNATURE(a,b,c,d) (a<<24 | b<<16 | c<<8 | d) + #define PJMEDIA_SIGNATURE(a,b,c,d) (a<<24 | b<<16 | c<<8 | d) * \endverbatim * * The following convention is used to maintain order to the signature @@ -57,32 +56,32 @@ PJ_BEGIN_DECL * \verbatim Class Signature Signature creation and test macros --------------------------------------------------------------- - Codec Cxxx PJMEDIA_SIG_CLASS_CODEC(b,c,d) - PJMEDIA_SIG_IS_CLASS_CODEC(sig) + Codec Cxxx PJMEDIA_SIG_CLASS_CODEC(b,c,d) + PJMEDIA_SIG_IS_CLASS_CODEC(sig) - Audio codec CAxx PJMEDIA_SIG_CLASS_AUD_CODEC(c,d) - PJMEDIA_SIG_IS_CLASS_AUD_CODEC(sig) + Audio codec CAxx PJMEDIA_SIG_CLASS_AUD_CODEC(c,d) + PJMEDIA_SIG_IS_CLASS_AUD_CODEC(sig) - Video codec CVxx PJMEDIA_SIG_CLASS_VID_CODEC(c,d) - PJMEDIA_SIG_IS_CLASS_VID_CODEC(sig) + Video codec CVxx PJMEDIA_SIG_CLASS_VID_CODEC(c,d) + PJMEDIA_SIG_IS_CLASS_VID_CODEC(sig) - Media port Pxxx PJMEDIA_SIG_CLASS_PORT(b,c,d) - PJMEDIA_SIG_IS_CLASS_PORT(sig) + Media port Pxxx PJMEDIA_SIG_CLASS_PORT(b,c,d) + PJMEDIA_SIG_IS_CLASS_PORT(sig) - Audio media port PAxx PJMEDIA_SIG_CLASS_PORT_AUD(c,d) - PJMEDIA_SIG_IS_CLASS_PORT_AUD(sig) + Audio media port PAxx PJMEDIA_SIG_CLASS_PORT_AUD(c,d) + PJMEDIA_SIG_IS_CLASS_PORT_AUD(sig) - Video media port PVxx PJMEDIA_SIG_CLASS_PORT_VID(c,d) - PJMEDIA_SIG_IS_CLASS_PORT_VID(sig) + Video media port PVxx PJMEDIA_SIG_CLASS_PORT_VID(c,d) + PJMEDIA_SIG_IS_CLASS_PORT_VID(sig) - Video device VDxx PJMEDIA_SIG_CLASS_VID_DEV(c,d) - PJMEDIA_SIG_IS_CLASS_VID_DEV(sig) + Video device VDxx PJMEDIA_SIG_CLASS_VID_DEV(c,d) + PJMEDIA_SIG_IS_CLASS_VID_DEV(sig) - Video other VOxx PJMEDIA_SIG_CLASS_VID_OTHER(c,d) - PJMEDIA_SIG_IS_CLASS_VID_OTHER(sig) + Video other VOxx PJMEDIA_SIG_CLASS_VID_OTHER(c,d) + PJMEDIA_SIG_IS_CLASS_VID_OTHER(sig) - Application object Axxx PJMEDIA_SIG_CLASS_APP(b,c,d) - PJMEDIA_SIG_IS_CLASS_APP(sig) + Application object Axxx PJMEDIA_SIG_CLASS_APP(b,c,d) + PJMEDIA_SIG_IS_CLASS_APP(sig) * \endverbatim * @@ -98,11 +97,11 @@ typedef pj_uint32_t pjmedia_obj_sig; /** * A utility function to convert signature to four letters string. * - * @param sig The signature value. - * @param buf Buffer to store the string, which MUST be at least - * five bytes long. + * @param sig The signature value. + * @param buf Buffer to store the string, which MUST be at least + * five bytes long. * - * @return The string. + * @return The string. */ PJ_INLINE(const char*) pjmedia_sig_name(pjmedia_obj_sig sig, char buf[]) { @@ -112,13 +111,13 @@ PJ_INLINE(const char*) pjmedia_sig_name(pjmedia_obj_sig sig, char buf[]) /** * Macro to generate signature from four ASCII letters. */ -#define PJMEDIA_SIGNATURE(a,b,c,d) PJMEDIA_FOURCC(d,c,b,a) +#define PJMEDIA_SIGNATURE(a,b,c,d) PJMEDIA_FOURCC(d,c,b,a) /************************************************************************* * Codec signature ('Cxxx'). Please keep the constant names sorted. */ -#define PJMEDIA_SIG_CLASS_CODEC(b,c,d) PJMEDIA_SIGNATURE('C',b,c,d) -#define PJMEDIA_SIG_IS_CLASS_CODEC(sig) ((sig) >> 24 == 'C') +#define PJMEDIA_SIG_CLASS_CODEC(b,c,d) PJMEDIA_SIGNATURE('C',b,c,d) +#define PJMEDIA_SIG_IS_CLASS_CODEC(sig) ((sig) >> 24 == 'C') /************************************************************************* * Audio codec signatures ('CAxx'). Please keep the constant names sorted. @@ -132,63 +131,63 @@ PJ_INLINE(const char*) pjmedia_sig_name(pjmedia_obj_sig sig, char buf[]) #define PJMEDIA_SIG_CLASS_VID_CODEC(c,d) PJMEDIA_SIG_CLASS_CODEC('V',c,d) #define PJMEDIA_SIG_IS_CLASS_VID_CODEC(sig) ((s)>>24=='C' && (((s)>>16)&0xff)=='V') -#define PJMEDIA_SIG_VID_CODEC_FFMPEG PJMEDIA_SIG_CLASS_VID_CODEC('F','F') +#define PJMEDIA_SIG_VID_CODEC_FFMPEG PJMEDIA_SIG_CLASS_VID_CODEC('F','F') /************************************************************************* * Port signatures ('Pxxx'). Please keep the constant names sorted. */ -#define PJMEDIA_SIG_CLASS_PORT(b,c,d) PJMEDIA_SIGNATURE('P',b,c,d) -#define PJMEDIA_SIG_IS_CLASS_PORT(sig) ((sig) >> 24 == 'P') +#define PJMEDIA_SIG_CLASS_PORT(b,c,d) PJMEDIA_SIGNATURE('P',b,c,d) +#define PJMEDIA_SIG_IS_CLASS_PORT(sig) ((sig) >> 24 == 'P') /************************************************************************* * Audio ports signatures ('PAxx'). Please keep the constant names sorted. */ -#define PJMEDIA_SIG_CLASS_PORT_AUD(c,d) PJMEDIA_SIG_CLASS_PORT('A',c,d) +#define PJMEDIA_SIG_CLASS_PORT_AUD(c,d) PJMEDIA_SIG_CLASS_PORT('A',c,d) #define PJMEDIA_SIG_IS_CLASS_PORT_AUD(s) ((s)>>24=='P' && (((s)>>16)&0xff)=='A') -#define PJMEDIA_SIG_PORT_BIDIR PJMEDIA_SIG_CLASS_PORT_AUD('B','D') -#define PJMEDIA_SIG_PORT_CONF PJMEDIA_SIG_CLASS_PORT_AUD('C','F') -#define PJMEDIA_SIG_PORT_CONF_PASV PJMEDIA_SIG_CLASS_PORT_AUD('C','P') -#define PJMEDIA_SIG_PORT_CONF_SWITCH PJMEDIA_SIG_CLASS_PORT_AUD('C','S') -#define PJMEDIA_SIG_PORT_ECHO PJMEDIA_SIG_CLASS_PORT_AUD('E','C') -#define PJMEDIA_SIG_PORT_MEM_CAPTURE PJMEDIA_SIG_CLASS_PORT_AUD('M','C') -#define PJMEDIA_SIG_PORT_MEM_PLAYER PJMEDIA_SIG_CLASS_PORT_AUD('M','P') -#define PJMEDIA_SIG_PORT_NULL PJMEDIA_SIG_CLASS_PORT_AUD('N','U') -#define PJMEDIA_SIG_PORT_RESAMPLE PJMEDIA_SIG_CLASS_PORT_AUD('R','E') -#define PJMEDIA_SIG_PORT_SPLIT_COMB PJMEDIA_SIG_CLASS_PORT_AUD('S','C') -#define PJMEDIA_SIG_PORT_SPLIT_COMB_P PJMEDIA_SIG_CLASS_PORT_AUD('S','P') -#define PJMEDIA_SIG_PORT_STEREO PJMEDIA_SIG_CLASS_PORT_AUD('S','R') -#define PJMEDIA_SIG_PORT_STREAM PJMEDIA_SIG_CLASS_PORT_AUD('S','T') -#define PJMEDIA_SIG_PORT_TONEGEN PJMEDIA_SIG_CLASS_PORT_AUD('T','O') -#define PJMEDIA_SIG_PORT_WAV_PLAYER PJMEDIA_SIG_CLASS_PORT_AUD('W','P') -#define PJMEDIA_SIG_PORT_WAV_PLAYLIST PJMEDIA_SIG_CLASS_PORT_AUD('W','Y') -#define PJMEDIA_SIG_PORT_WAV_WRITER PJMEDIA_SIG_CLASS_PORT_AUD('W','W') +#define PJMEDIA_SIG_PORT_BIDIR PJMEDIA_SIG_CLASS_PORT_AUD('B','D') +#define PJMEDIA_SIG_PORT_CONF PJMEDIA_SIG_CLASS_PORT_AUD('C','F') +#define PJMEDIA_SIG_PORT_CONF_PASV PJMEDIA_SIG_CLASS_PORT_AUD('C','P') +#define PJMEDIA_SIG_PORT_CONF_SWITCH PJMEDIA_SIG_CLASS_PORT_AUD('C','S') +#define PJMEDIA_SIG_PORT_ECHO PJMEDIA_SIG_CLASS_PORT_AUD('E','C') +#define PJMEDIA_SIG_PORT_MEM_CAPTURE PJMEDIA_SIG_CLASS_PORT_AUD('M','C') +#define PJMEDIA_SIG_PORT_MEM_PLAYER PJMEDIA_SIG_CLASS_PORT_AUD('M','P') +#define PJMEDIA_SIG_PORT_NULL PJMEDIA_SIG_CLASS_PORT_AUD('N','U') +#define PJMEDIA_SIG_PORT_RESAMPLE PJMEDIA_SIG_CLASS_PORT_AUD('R','E') +#define PJMEDIA_SIG_PORT_SPLIT_COMB PJMEDIA_SIG_CLASS_PORT_AUD('S','C') +#define PJMEDIA_SIG_PORT_SPLIT_COMB_P PJMEDIA_SIG_CLASS_PORT_AUD('S','P') +#define PJMEDIA_SIG_PORT_STEREO PJMEDIA_SIG_CLASS_PORT_AUD('S','R') +#define PJMEDIA_SIG_PORT_STREAM PJMEDIA_SIG_CLASS_PORT_AUD('S','T') +#define PJMEDIA_SIG_PORT_TONEGEN PJMEDIA_SIG_CLASS_PORT_AUD('T','O') +#define PJMEDIA_SIG_PORT_WAV_PLAYER PJMEDIA_SIG_CLASS_PORT_AUD('W','P') +#define PJMEDIA_SIG_PORT_WAV_PLAYLIST PJMEDIA_SIG_CLASS_PORT_AUD('W','Y') +#define PJMEDIA_SIG_PORT_WAV_WRITER PJMEDIA_SIG_CLASS_PORT_AUD('W','W') /************************************************************************* * Video ports signatures ('PVxx'). Please keep the constant names sorted. */ -#define PJMEDIA_SIG_CLASS_PORT_VID(c,d) PJMEDIA_SIG_CLASS_PORT('V',c,d) +#define PJMEDIA_SIG_CLASS_PORT_VID(c,d) PJMEDIA_SIG_CLASS_PORT('V',c,d) #define PJMEDIA_SIG_IS_CLASS_PORT_VID(s) ((s)>>24=='P' && (((s)>>16)&0xff)=='V') /** AVI player signature. */ -#define PJMEDIA_SIG_PORT_VID_AVI_PLAYER PJMEDIA_SIG_CLASS_PORT_VID('A','V') -#define PJMEDIA_SIG_PORT_VID_STREAM PJMEDIA_SIG_CLASS_PORT_VID('S','T') -#define PJMEDIA_SIG_PORT_VID_TEE PJMEDIA_SIG_CLASS_PORT_VID('T','E') +#define PJMEDIA_SIG_PORT_VID_AVI_PLAYER PJMEDIA_SIG_CLASS_PORT_VID('A','V') +#define PJMEDIA_SIG_PORT_VID_STREAM PJMEDIA_SIG_CLASS_PORT_VID('S','T') +#define PJMEDIA_SIG_PORT_VID_TEE PJMEDIA_SIG_CLASS_PORT_VID('T','E') /************************************************************************** * Video device signatures ('VDxx'). Please keep the constant names sorted. */ -#define PJMEDIA_SIG_CLASS_VID_DEV(c,d) PJMEDIA_SIGNATURE('V','D',c,d) +#define PJMEDIA_SIG_CLASS_VID_DEV(c,d) PJMEDIA_SIGNATURE('V','D',c,d) #define PJMEDIA_SIG_IS_CLASS_VID_DEV(s) ((s)>>24=='V' && (((s)>>16)&0xff)=='D') -#define PJMEDIA_SIG_VID_DEV_COLORBAR PJMEDIA_SIG_CLASS_VID_DEV('C','B') -#define PJMEDIA_SIG_VID_DEV_SDL PJMEDIA_SIG_CLASS_VID_DEV('S','D') -#define PJMEDIA_SIG_VID_DEV_V4L2 PJMEDIA_SIG_CLASS_VID_DEV('V','2') -#define PJMEDIA_SIG_VID_DEV_DSHOW PJMEDIA_SIG_CLASS_VID_DEV('D','S') -#define PJMEDIA_SIG_VID_DEV_QT PJMEDIA_SIG_CLASS_VID_DEV('Q','T') -#define PJMEDIA_SIG_VID_DEV_IOS PJMEDIA_SIG_CLASS_VID_DEV('I','P') +#define PJMEDIA_SIG_VID_DEV_COLORBAR PJMEDIA_SIG_CLASS_VID_DEV('C','B') +#define PJMEDIA_SIG_VID_DEV_SDL PJMEDIA_SIG_CLASS_VID_DEV('S','D') +#define PJMEDIA_SIG_VID_DEV_V4L2 PJMEDIA_SIG_CLASS_VID_DEV('V','2') +#define PJMEDIA_SIG_VID_DEV_DSHOW PJMEDIA_SIG_CLASS_VID_DEV('D','S') +#define PJMEDIA_SIG_VID_DEV_QT PJMEDIA_SIG_CLASS_VID_DEV('Q','T') +#define PJMEDIA_SIG_VID_DEV_IOS PJMEDIA_SIG_CLASS_VID_DEV('I','P') /********************************************************************* @@ -197,15 +196,15 @@ PJ_INLINE(const char*) pjmedia_sig_name(pjmedia_obj_sig sig, char buf[]) #define PJMEDIA_SIG_CLASS_VID_OTHER(c,d) PJMEDIA_SIGNATURE('V','O',c,d) #define PJMEDIA_SIG_IS_CLASS_VID_OTHER(s) ((s)>>24=='V' && (((s)>>16)&0xff)=='O') -#define PJMEDIA_SIG_VID_CONF PJMEDIA_SIG_CLASS_VID_OTHER('C','F') -#define PJMEDIA_SIG_VID_PORT PJMEDIA_SIG_CLASS_VID_OTHER('P','O') +#define PJMEDIA_SIG_VID_CONF PJMEDIA_SIG_CLASS_VID_OTHER('C','F') +#define PJMEDIA_SIG_VID_PORT PJMEDIA_SIG_CLASS_VID_OTHER('P','O') /********************************************************************* * Application class ('Axxx'). */ -#define PJMEDIA_SIG_CLASS_APP(b,c,d) PJMEDIA_SIGNATURE('A',b,c,d) -#define PJMEDIA_SIG_IS_CLASS_APP(s) ((s)>>24=='A') +#define PJMEDIA_SIG_CLASS_APP(b,c,d) PJMEDIA_SIGNATURE('A',b,c,d) +#define PJMEDIA_SIG_IS_CLASS_APP(s) ((s)>>24=='A') /** @@ -215,4 +214,4 @@ PJ_INLINE(const char*) pjmedia_sig_name(pjmedia_obj_sig sig, char buf[]) PJ_END_DECL -#endif /* __PJMEDIA_SIGNATURES_H__ */ +#endif /* __PJMEDIA_SIGNATURES_H__ */ diff --git a/pjmedia/include/pjmedia/silencedet.h b/pjmedia/include/pjmedia/silencedet.h index b4ff34eb2a..f7b1b5a7c1 100644 --- a/pjmedia/include/pjmedia/silencedet.h +++ b/pjmedia/include/pjmedia/silencedet.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -50,93 +49,93 @@ typedef struct pjmedia_silence_det pjmedia_silence_det; * Create voice activity detector with default settings. The default settings * are set to adaptive silence detection with the default threshold. * - * @param pool Pool for allocating the structure. - * @param clock_rate Clock rate. + * @param pool Pool for allocating the structure. + * @param clock_rate Clock rate. * @param samples_per_frame Number of samples per frame. The clock_rate and - * samples_per_frame is only used to calculate the - * frame time, from which some timing parameters - * are calculated from. - * @param p_sd Pointer to receive the silence detector instance. + * samples_per_frame is only used to calculate the + * frame time, from which some timing parameters + * are calculated from. + * @param p_sd Pointer to receive the silence detector instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_silence_det_create( pj_pool_t *pool, - unsigned clock_rate, - unsigned samples_per_frame, - pjmedia_silence_det **p_sd ); + unsigned clock_rate, + unsigned samples_per_frame, + pjmedia_silence_det **p_sd ); /** * Set silence detector name to identify the particular silence detector * instance in the log. * - * @param sd The silence detector. - * @param name Name. + * @param sd The silence detector. + * @param name Name. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_silence_det_set_name(pjmedia_silence_det *sd, - const char *name); + const char *name); /** * Set the sd to operate in fixed threshold mode. With fixed threshold mode, * the threshold will not be changed adaptively. * - * @param sd The silence detector - * @param threshold The silence threshold, or -1 to use default - * threshold. + * @param sd The silence detector + * @param threshold The silence threshold, or -1 to use default + * threshold. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_silence_det_set_fixed( pjmedia_silence_det *sd, - int threshold ); + int threshold ); /** * Set the sd to operate in adaptive mode. This is the default mode * when the silence detector is created. * - * @param sd The silence detector - * @param threshold Initial threshold to be set, or -1 to use default - * threshold. + * @param sd The silence detector + * @param threshold Initial threshold to be set, or -1 to use default + * threshold. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_silence_det_set_adaptive(pjmedia_silence_det *sd, - int threshold); + int threshold); /** * Set other silence detector parameters. * - * @param sd The silence detector + * @param sd The silence detector * @param before_silence Minimum duration of silence (in msec) before - * silence is reported. If -1 is specified, then - * the default value will be used. The default is - * 400 msec. - * @param recalc_time1 The interval (in msec) to recalculate threshold - * in non-silence condition when adaptive silence - * detection is set. If -1 is specified, then the - * default value will be used. The default is 4000 - * (msec). - * @param recalc_time2 The interval (in msec) to recalculate threshold - * in silence condition when adaptive silence detection - * is set. If -1 is specified, then the default value - * will be used. The default value is 2000 (msec). - * - * @return PJ_SUCCESS on success. + * silence is reported. If -1 is specified, then + * the default value will be used. The default is + * 400 msec. + * @param recalc_time1 The interval (in msec) to recalculate threshold + * in non-silence condition when adaptive silence + * detection is set. If -1 is specified, then the + * default value will be used. The default is 4000 + * (msec). + * @param recalc_time2 The interval (in msec) to recalculate threshold + * in silence condition when adaptive silence detection + * is set. If -1 is specified, then the default value + * will be used. The default value is 2000 (msec). + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_silence_det_set_params( pjmedia_silence_det *sd, - int before_silence, - int recalc_time1, - int recalc_time2); + int before_silence, + int recalc_time1, + int recalc_time2); /** * Disable the silence detector. * - * @param sd The silence detector + * @param sd The silence detector * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_silence_det_disable( pjmedia_silence_det *sd ); @@ -146,31 +145,31 @@ PJ_DECL(pj_status_t) pjmedia_silence_det_disable( pjmedia_silence_det *sd ); * function uses #pjmedia_calc_avg_signal() and #pjmedia_silence_det_apply() * for its calculation. * - * @param sd The silence detector instance. - * @param samples Pointer to 16-bit PCM input samples. - * @param count Number of samples in the input. - * @param p_level Optional pointer to receive average signal level - * of the input samples. + * @param sd The silence detector instance. + * @param samples Pointer to 16-bit PCM input samples. + * @param count Number of samples in the input. + * @param p_level Optional pointer to receive average signal level + * of the input samples. * - * @return Non zero if signal is silence. + * @return Non zero if signal is silence. */ PJ_DECL(pj_bool_t) pjmedia_silence_det_detect( pjmedia_silence_det *sd, - const pj_int16_t samples[], - pj_size_t count, - pj_int32_t *p_level); + const pj_int16_t samples[], + pj_size_t count, + pj_int32_t *p_level); /** * Calculate average signal level for the given samples. * - * @param samples Pointer to 16-bit PCM samples. - * @param count Number of samples in the input. + * @param samples Pointer to 16-bit PCM samples. + * @param count Number of samples in the input. * - * @return The average signal level, which simply is total level - * divided by number of samples. + * @return The average signal level, which simply is total level + * divided by number of samples. */ PJ_DECL(pj_int32_t) pjmedia_calc_avg_signal( const pj_int16_t samples[], - pj_size_t count ); + pj_size_t count ); @@ -178,13 +177,13 @@ PJ_DECL(pj_int32_t) pjmedia_calc_avg_signal( const pj_int16_t samples[], * Perform voice activity detection, given the specified average signal * level. * - * @param sd The silence detector instance. - * @param level Signal level. + * @param sd The silence detector instance. + * @param level Signal level. * - * @return Non zero if signal is silence. + * @return Non zero if signal is silence. */ PJ_DECL(pj_bool_t) pjmedia_silence_det_apply( pjmedia_silence_det *sd, - pj_uint32_t level); + pj_uint32_t level); @@ -196,5 +195,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_SILENCE_DET_H__ */ +#endif /* __PJMEDIA_SILENCE_DET_H__ */ diff --git a/pjmedia/include/pjmedia/sound.h b/pjmedia/include/pjmedia/sound.h index 00c9c4f3c5..ea8238d6de 100644 --- a/pjmedia/include/pjmedia/sound.h +++ b/pjmedia/include/pjmedia/sound.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -75,11 +74,11 @@ typedef struct pjmedia_snd_stream pjmedia_snd_stream; */ typedef struct pjmedia_snd_dev_info { - char name[PJMEDIA_AUD_DEV_INFO_NAME_LEN]; - /**< Device name. */ - unsigned input_count; /**< Max number of input channels. */ - unsigned output_count; /**< Max number of output channels. */ - unsigned default_samples_per_sec;/**< Default sampling rate. */ + char name[PJMEDIA_AUD_DEV_INFO_NAME_LEN]; + /**< Device name. */ + unsigned input_count; /**< Max number of input channels. */ + unsigned output_count; /**< Max number of output channels. */ + unsigned default_samples_per_sec;/**< Default sampling rate. */ } pjmedia_snd_dev_info; /** @@ -88,15 +87,15 @@ typedef struct pjmedia_snd_dev_info */ typedef struct pjmedia_snd_stream_info { - pjmedia_dir dir; /**< Stream direction. */ - int play_id; /**< Playback dev id, or -1 for rec only*/ - int rec_id; /**< Capture dev id, or -1 for play only*/ - unsigned clock_rate; /**< Actual clock rate. */ - unsigned channel_count; /**< Number of channels. */ - unsigned samples_per_frame; /**< Samples per frame. */ - unsigned bits_per_sample; /**< Bits per sample. */ - unsigned rec_latency; /**< Record latency, in samples. */ - unsigned play_latency; /**< Playback latency, in samples. */ + pjmedia_dir dir; /**< Stream direction. */ + int play_id; /**< Playback dev id, or -1 for rec only*/ + int rec_id; /**< Capture dev id, or -1 for play only*/ + unsigned clock_rate; /**< Actual clock rate. */ + unsigned channel_count; /**< Number of channels. */ + unsigned samples_per_frame; /**< Samples per frame. */ + unsigned bits_per_sample; /**< Bits per sample. */ + unsigned rec_latency; /**< Record latency, in samples. */ + unsigned play_latency; /**< Playback latency, in samples. */ } pjmedia_snd_stream_info; /** @@ -104,41 +103,41 @@ typedef struct pjmedia_snd_stream_info * to be played by the device. Application must fill in the whole of output * buffer with sound samples. * - * @param user_data User data associated with the stream. - * @param timestamp Timestamp, in samples. - * @param output Buffer to be filled out by application. - * @param size The size requested in bytes, which will be equal to - * the size of one whole packet. + * @param user_data User data associated with the stream. + * @param timestamp Timestamp, in samples. + * @param output Buffer to be filled out by application. + * @param size The size requested in bytes, which will be equal to + * the size of one whole packet. * - * @return Non-zero to stop the stream. + * @return Non-zero to stop the stream. */ typedef pj_status_t (*pjmedia_snd_play_cb)(/* in */ void *user_data, - /* in */ pj_uint32_t timestamp, - /* out */ void *output, - /* out */ unsigned size); + /* in */ pj_uint32_t timestamp, + /* out */ void *output, + /* out */ unsigned size); /** * This callback is called by recorder stream when it has captured the whole * packet worth of audio samples. * - * @param user_data User data associated with the stream. - * @param timestamp Timestamp, in samples. - * @param input Buffer containing the captured audio samples. - * @param size The size of the data in the buffer, in bytes. + * @param user_data User data associated with the stream. + * @param timestamp Timestamp, in samples. + * @param input Buffer containing the captured audio samples. + * @param size The size of the data in the buffer, in bytes. * - * @return Non-zero to stop the stream. + * @return Non-zero to stop the stream. */ typedef pj_status_t (*pjmedia_snd_rec_cb)(/* in */ void *user_data, - /* in */ pj_uint32_t timestamp, - /* in */ void *input, - /* in*/ unsigned size); + /* in */ pj_uint32_t timestamp, + /* in */ void *input, + /* in*/ unsigned size); /** * Init the sound library. * - * @param factory The sound factory. + * @param factory The sound factory. * - * @return Zero on success. + * @return Zero on success. */ PJ_INLINE(pj_status_t) pjmedia_snd_init(pj_pool_factory *factory) { @@ -151,7 +150,7 @@ PJ_INLINE(pj_status_t) pjmedia_snd_init(pj_pool_factory *factory) /** * Get the number of devices detected by the library. * - * @return Number of devices. + * @return Number of devices. */ PJ_INLINE(int) pjmedia_snd_get_dev_count(void) { @@ -165,8 +164,8 @@ PJ_INLINE(int) pjmedia_snd_get_dev_count(void) /** * Get device info. * - * @param index The index of the device, which should be in the range - * from zero to #pjmedia_snd_get_dev_count - 1. + * @param index The index of the device, which should be in the range + * from zero to #pjmedia_snd_get_dev_count - 1. */ PJ_DECL(const pjmedia_snd_dev_info*) pjmedia_snd_get_dev_info(unsigned index); @@ -182,15 +181,15 @@ PJ_DECL(const pjmedia_snd_dev_info*) pjmedia_snd_get_dev_info(unsigned index); * the best latency setting may vary based on many aspects, e.g: sound card, * CPU, OS, kernel, etc. * - * @param input_latency The latency of input device, in ms, set to 0 - * for default PJMEDIA_SND_DEFAULT_REC_LATENCY. + * @param input_latency The latency of input device, in ms, set to 0 + * for default PJMEDIA_SND_DEFAULT_REC_LATENCY. * @param output_latency The latency of output device, in ms, set to 0 - * for default PJMEDIA_SND_DEFAULT_PLAY_LATENCY. + * for default PJMEDIA_SND_DEFAULT_PLAY_LATENCY. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_snd_set_latency(unsigned input_latency, - unsigned output_latency); + unsigned output_latency); /** @@ -200,139 +199,139 @@ PJ_DECL(pj_status_t) pjmedia_snd_set_latency(unsigned input_latency, * streams), because it works on backends that does not allow * a device to be opened more than once. * - * @param rec_id Device index for recorder/capture stream, or - * -1 to use the first capable device. - * @param play_id Device index for playback stream, or -1 to use - * the first capable device. - * @param clock_rate Sound device's clock rate to set. - * @param channel_count Set number of channels, 1 for mono, or 2 for - * stereo. The channel count determines the format - * of the frame. + * @param rec_id Device index for recorder/capture stream, or + * -1 to use the first capable device. + * @param play_id Device index for playback stream, or -1 to use + * the first capable device. + * @param clock_rate Sound device's clock rate to set. + * @param channel_count Set number of channels, 1 for mono, or 2 for + * stereo. The channel count determines the format + * of the frame. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Set the number of bits per sample. The normal - * value for this parameter is 16 bits per sample. - * @param rec_cb Callback to handle captured audio samples. - * @param play_cb Callback to be called when the sound player needs - * more audio samples to play. - * @param user_data User data to be associated with the stream. - * @param p_snd_strm Pointer to receive the stream instance. - * - * @return PJ_SUCCESS on success. + * value for this parameter is 16 bits per sample. + * @param rec_cb Callback to handle captured audio samples. + * @param play_cb Callback to be called when the sound player needs + * more audio samples to play. + * @param user_data User data to be associated with the stream. + * @param p_snd_strm Pointer to receive the stream instance. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_snd_open(int rec_id, - int play_id, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_rec_cb rec_cb, - pjmedia_snd_play_cb play_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm); + int play_id, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_rec_cb rec_cb, + pjmedia_snd_play_cb play_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm); /** * Create a unidirectional audio stream for capturing audio samples from * the sound device. * - * @param index Device index, or -1 to let the library choose the - * first available device. - * @param clock_rate Sound device's clock rate to set. - * @param channel_count Set number of channels, 1 for mono, or 2 for - * stereo. The channel count determines the format - * of the frame. + * @param index Device index, or -1 to let the library choose the + * first available device. + * @param clock_rate Sound device's clock rate to set. + * @param channel_count Set number of channels, 1 for mono, or 2 for + * stereo. The channel count determines the format + * of the frame. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Set the number of bits per sample. The normal - * value for this parameter is 16 bits per sample. - * @param rec_cb Callback to handle captured audio samples. - * @param user_data User data to be associated with the stream. - * @param p_snd_strm Pointer to receive the stream instance. + * value for this parameter is 16 bits per sample. + * @param rec_cb Callback to handle captured audio samples. + * @param user_data User data to be associated with the stream. + * @param p_snd_strm Pointer to receive the stream instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_snd_open_rec( int index, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_rec_cb rec_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm); + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_rec_cb rec_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm); /** * Create a unidirectional audio stream for playing audio samples to the * sound device. * - * @param index Device index, or -1 to let the library choose the - * first available device. - * @param clock_rate Sound device's clock rate to set. - * @param channel_count Set number of channels, 1 for mono, or 2 for - * stereo. The channel count determines the format - * of the frame. + * @param index Device index, or -1 to let the library choose the + * first available device. + * @param clock_rate Sound device's clock rate to set. + * @param channel_count Set number of channels, 1 for mono, or 2 for + * stereo. The channel count determines the format + * of the frame. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Set the number of bits per sample. The normal - * value for this parameter is 16 bits per sample. - * @param play_cb Callback to be called when the sound player needs - * more audio samples to play. - * @param user_data User data to be associated with the stream. - * @param p_snd_strm Pointer to receive the stream instance. + * value for this parameter is 16 bits per sample. + * @param play_cb Callback to be called when the sound player needs + * more audio samples to play. + * @param user_data User data to be associated with the stream. + * @param p_snd_strm Pointer to receive the stream instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_snd_open_player( int index, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_play_cb play_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm ); + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_play_cb play_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm ); /** * Get information about live stream. * - * @param strm The stream to be queried. - * @param pi Pointer to stream information to be filled up with - * information about the stream. + * @param strm The stream to be queried. + * @param pi Pointer to stream information to be filled up with + * information about the stream. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_snd_stream_get_info(pjmedia_snd_stream *strm, - pjmedia_snd_stream_info *pi); + pjmedia_snd_stream_info *pi); /** * Start the stream. * - * @param stream The recorder or player stream. + * @param stream The recorder or player stream. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pjmedia_snd_stream_start(pjmedia_snd_stream *stream); /** * Stop the stream. * - * @param stream The recorder or player stream. + * @param stream The recorder or player stream. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pjmedia_snd_stream_stop(pjmedia_snd_stream *stream); /** * Destroy the stream. * - * @param stream The recorder of player stream. + * @param stream The recorder of player stream. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pjmedia_snd_stream_close(pjmedia_snd_stream *stream); /** * Deinitialize sound library. * - * @return Zero on success. + * @return Zero on success. */ PJ_INLINE(pj_status_t) pjmedia_snd_deinit(void) { @@ -351,4 +350,4 @@ PJ_INLINE(pj_status_t) pjmedia_snd_deinit(void) PJ_END_DECL -#endif /* __PJMEDIA_SOUND_H__ */ +#endif /* __PJMEDIA_SOUND_H__ */ diff --git a/pjmedia/include/pjmedia/sound_port.h b/pjmedia/include/pjmedia/sound_port.h index 267f5b2508..a5af4cafb3 100644 --- a/pjmedia/include/pjmedia/sound_port.h +++ b/pjmedia/include/pjmedia/sound_port.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -134,7 +133,7 @@ typedef struct pjmedia_snd_port_param /** * Initialize pjmedia_snd_port_param with default values. * - * @param prm The parameter. + * @param prm The parameter. */ PJ_DECL(void) pjmedia_snd_port_param_default(pjmedia_snd_port_param *prm); @@ -150,115 +149,115 @@ typedef struct pjmedia_snd_port pjmedia_snd_port; * Create bidirectional sound port for both capturing and playback of * audio samples. * - * @param pool Pool to allocate sound port structure. - * @param rec_id Device index for recorder/capture stream, or - * -1 to use the first capable device. - * @param play_id Device index for playback stream, or -1 to use - * the first capable device. - * @param clock_rate Sound device's clock rate to set. - * @param channel_count Set number of channels, 1 for mono, or 2 for - * stereo. The channel count determines the format - * of the frame. + * @param pool Pool to allocate sound port structure. + * @param rec_id Device index for recorder/capture stream, or + * -1 to use the first capable device. + * @param play_id Device index for playback stream, or -1 to use + * the first capable device. + * @param clock_rate Sound device's clock rate to set. + * @param channel_count Set number of channels, 1 for mono, or 2 for + * stereo. The channel count determines the format + * of the frame. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Set the number of bits per sample. The normal - * value for this parameter is 16 bits per sample. - * @param options Options flag. - * @param p_port Pointer to receive the sound device port instance. + * value for this parameter is 16 bits per sample. + * @param options Options flag. + * @param p_port Pointer to receive the sound device port instance. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_snd_port_create( pj_pool_t *pool, - int rec_id, - int play_id, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_snd_port **p_port); + int rec_id, + int play_id, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_snd_port **p_port); /** * Create unidirectional sound device port for capturing audio streams from * the sound device with the specified parameters. * - * @param pool Pool to allocate sound port structure. - * @param index Device index, or -1 to let the library choose the - * first available device. - * @param clock_rate Sound device's clock rate to set. - * @param channel_count Set number of channels, 1 for mono, or 2 for - * stereo. The channel count determines the format - * of the frame. + * @param pool Pool to allocate sound port structure. + * @param index Device index, or -1 to let the library choose the + * first available device. + * @param clock_rate Sound device's clock rate to set. + * @param channel_count Set number of channels, 1 for mono, or 2 for + * stereo. The channel count determines the format + * of the frame. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Set the number of bits per sample. The normal - * value for this parameter is 16 bits per sample. - * @param options Options flag. - * @param p_port Pointer to receive the sound device port instance. + * value for this parameter is 16 bits per sample. + * @param options Options flag. + * @param p_port Pointer to receive the sound device port instance. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_snd_port_create_rec(pj_pool_t *pool, - int index, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_snd_port **p_port); - + int index, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_snd_port **p_port); + /** * Create unidirectional sound device port for playing audio streams with the * specified parameters. * - * @param pool Pool to allocate sound port structure. - * @param index Device index, or -1 to let the library choose the - * first available device. - * @param clock_rate Sound device's clock rate to set. - * @param channel_count Set number of channels, 1 for mono, or 2 for - * stereo. The channel count determines the format - * of the frame. + * @param pool Pool to allocate sound port structure. + * @param index Device index, or -1 to let the library choose the + * first available device. + * @param clock_rate Sound device's clock rate to set. + * @param channel_count Set number of channels, 1 for mono, or 2 for + * stereo. The channel count determines the format + * of the frame. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Set the number of bits per sample. The normal - * value for this parameter is 16 bits per sample. - * @param options Options flag. - * @param p_port Pointer to receive the sound device port instance. + * value for this parameter is 16 bits per sample. + * @param options Options flag. + * @param p_port Pointer to receive the sound device port instance. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_snd_port_create_player(pj_pool_t *pool, - int index, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_snd_port **p_port); + int index, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_snd_port **p_port); /** * Create sound device port according to the specified parameters. * - * @param pool Pool to allocate sound port structure. - * @param prm Sound port parameter. - * @param p_port Pointer to receive the sound device port instance. + * @param pool Pool to allocate sound port structure. + * @param prm Sound port parameter. + * @param p_port Pointer to receive the sound device port instance. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_snd_port_create2(pj_pool_t *pool, - const pjmedia_snd_port_param *prm, - pjmedia_snd_port **p_port); + const pjmedia_snd_port_param *prm, + pjmedia_snd_port **p_port); /** * Destroy sound device port. * - * @param snd_port The sound device port. + * @param snd_port The sound device port. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_snd_port_destroy(pjmedia_snd_port *snd_port); @@ -266,12 +265,12 @@ PJ_DECL(pj_status_t) pjmedia_snd_port_destroy(pjmedia_snd_port *snd_port); /** * Retrieve the sound stream associated by this sound device port. * - * @param snd_port The sound device port. + * @param snd_port The sound device port. * - * @return The sound stream instance. + * @return The sound stream instance. */ PJ_DECL(pjmedia_aud_stream*) pjmedia_snd_port_get_snd_stream( - pjmedia_snd_port *snd_port); + pjmedia_snd_port *snd_port); /** @@ -288,46 +287,46 @@ PJ_DECL(pjmedia_aud_stream*) pjmedia_snd_port_get_snd_stream( * will be used if the device does not support AEC), this function will * change the software EC settings. * - * @param snd_port The sound device port. - * @param pool Pool to re-create the echo canceller if necessary. - * @param tail_ms Maximum echo tail length to be supported, in - * miliseconds. If zero is specified, the EC would - * be disabled. - * @param options The options to be passed to #pjmedia_echo_create(). - * This is only used if software EC is being used. + * @param snd_port The sound device port. + * @param pool Pool to re-create the echo canceller if necessary. + * @param tail_ms Maximum echo tail length to be supported, in + * miliseconds. If zero is specified, the EC would + * be disabled. + * @param options The options to be passed to #pjmedia_echo_create(). + * This is only used if software EC is being used. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_snd_port_set_ec( pjmedia_snd_port *snd_port, - pj_pool_t *pool, - unsigned tail_ms, - unsigned options); + pj_pool_t *pool, + unsigned tail_ms, + unsigned options); /** * Get current echo canceller tail length, in miliseconds. The tail length * will be zero if EC is not enabled. * - * @param snd_port The sound device port. - * @param p_length Pointer to receive the tail length. + * @param snd_port The sound device port. + * @param p_length Pointer to receive the tail length. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_snd_port_get_ec_tail(pjmedia_snd_port *snd_port, - unsigned *p_length); + unsigned *p_length); /** * Get echo canceller statistics. * - * @param snd_port The sound device port. - * @param p_stat Pointer to receive the stat. + * @param snd_port The sound device port. + * @param p_stat Pointer to receive the stat. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_snd_port_get_ec_stat(pjmedia_snd_port *snd_port, - pjmedia_echo_stat *p_stat); + pjmedia_echo_stat *p_stat); /** @@ -336,7 +335,7 @@ PJ_DECL(pj_status_t) pjmedia_snd_port_get_ec_stat(pjmedia_snd_port *snd_port, * @param snd_port The sound port. * @param dir Sound port's direction. * - * @return The clock source. + * @return The clock source. */ PJ_DECL(pjmedia_clock_src *) pjmedia_snd_port_get_clock_src( pjmedia_snd_port *snd_port, @@ -355,24 +354,24 @@ pjmedia_snd_port_get_clock_src( pjmedia_snd_port *snd_port, * fail. This means the port MUST have the same clock_rate, channel count, * samples per frame, and bits per sample as the sound device port. * - * @param snd_port The sound device port. - * @param port The media port to be connected. + * @param snd_port The sound device port. + * @param port The media port to be connected. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_snd_port_connect(pjmedia_snd_port *snd_port, - pjmedia_port *port); + pjmedia_port *port); /** * Retrieve the port instance currently attached to the sound port, if any. * - * @param snd_port The sound device port. + * @param snd_port The sound device port. * - * @return The port instance currently attached to the - * sound device port, or NULL if there is no port - * currently attached to the sound device port. + * @return The port instance currently attached to the + * sound device port, or NULL if there is no port + * currently attached to the sound device port. */ PJ_DECL(pjmedia_port*) pjmedia_snd_port_get_port(pjmedia_snd_port *snd_port); @@ -380,9 +379,9 @@ PJ_DECL(pjmedia_port*) pjmedia_snd_port_get_port(pjmedia_snd_port *snd_port); /** * Disconnect currently attached port from the sound device port. * - * @param snd_port The sound device port. + * @param snd_port The sound device port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_snd_port_disconnect(pjmedia_snd_port *snd_port); @@ -394,5 +393,5 @@ PJ_DECL(pj_status_t) pjmedia_snd_port_disconnect(pjmedia_snd_port *snd_port); PJ_END_DECL -#endif /* __PJMEDIA_SOUND_PORT_H__ */ +#endif /* __PJMEDIA_SOUND_PORT_H__ */ diff --git a/pjmedia/include/pjmedia/splitcomb.h b/pjmedia/include/pjmedia/splitcomb.h index 75ef71b86f..c9e15be22c 100644 --- a/pjmedia/include/pjmedia/splitcomb.h +++ b/pjmedia/include/pjmedia/splitcomb.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -55,25 +54,25 @@ PJ_BEGIN_DECL * of the splitter/combiner. Application needs to supply the splitter/ * combiner with a media port for each audio channels. * - * @param pool Pool to allocate memory to create the splitter/ - * combiner. - * @param clock_rate Audio clock rate/sampling rate. - * @param channel_count Number of channels. + * @param pool Pool to allocate memory to create the splitter/ + * combiner. + * @param clock_rate Audio clock rate/sampling rate. + * @param channel_count Number of channels. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Bits per sample. - * @param options Optional flags. - * @param p_splitcomb Pointer to receive the splitter/combiner. + * @param options Optional flags. + * @param p_splitcomb Pointer to receive the splitter/combiner. * - * @return PJ_SUCCESS on success, or the appropriate - * error code. + * @return PJ_SUCCESS on success, or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_splitcomb_create(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_port **p_splitcomb); + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_port **p_splitcomb); /** * Supply the splitter/combiner with media port for the specified channel @@ -82,18 +81,18 @@ PJ_DECL(pj_status_t) pjmedia_splitcomb_create(pj_pool_t *pool, * calls get_frame() of the splitter/combiner, it will call get_frame() * for all ports that have the same phase. And similarly for put_frame(). * - * @param splitcomb The splitter/combiner. - * @param ch_num Audio channel starting number (zero based). - * @param options Must be zero at the moment. - * @param port The media port. + * @param splitcomb The splitter/combiner. + * @param ch_num Audio channel starting number (zero based). + * @param options Must be zero at the moment. + * @param port The media port. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_splitcomb_set_channel(pjmedia_port *splitcomb, - unsigned ch_num, - unsigned options, - pjmedia_port *port); + unsigned ch_num, + unsigned options, + pjmedia_port *port); /** * Create a reverse phase media port for the specified channel number. @@ -106,29 +105,29 @@ PJ_DECL(pj_status_t) pjmedia_splitcomb_set_channel(pjmedia_port *splitcomb, * will be returned when application calls get_frame() to the splitter's * media port. So this effectively reverse the phase of the media port. * - * @param pool The pool to allocate memory for the port and - * buffers. - * @param splitcomb The splitter/combiner. - * @param ch_num Audio channel starting number (zero based). - * @param options Normally is zero, but the lower 8-bit of the - * options can be used to specify the number of - * buffers in the circular buffer. If zero, then - * default number will be used (default: 8). The second - * lowest 8 bits can be used to specify the options for - * the underlying delay buffer (see - * #pjmedia_delay_buf_flag for the possible options). - * @param p_chport The media port created with reverse phase for - * the specified audio channel. + * @param pool The pool to allocate memory for the port and + * buffers. + * @param splitcomb The splitter/combiner. + * @param ch_num Audio channel starting number (zero based). + * @param options Normally is zero, but the lower 8-bit of the + * options can be used to specify the number of + * buffers in the circular buffer. If zero, then + * default number will be used (default: 8). The second + * lowest 8 bits can be used to specify the options for + * the underlying delay buffer (see + * #pjmedia_delay_buf_flag for the possible options). + * @param p_chport The media port created with reverse phase for + * the specified audio channel. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_splitcomb_create_rev_channel( pj_pool_t *pool, - pjmedia_port *splitcomb, - unsigned ch_num, - unsigned options, - pjmedia_port **p_chport); + pjmedia_port *splitcomb, + unsigned ch_num, + unsigned options, + pjmedia_port **p_chport); @@ -138,6 +137,6 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_SPLITCOMB_H__ */ +#endif /* __PJMEDIA_SPLITCOMB_H__ */ diff --git a/pjmedia/include/pjmedia/stereo.h b/pjmedia/include/pjmedia/stereo.h index 8598a6287d..6c4618d27c 100644 --- a/pjmedia/include/pjmedia/stereo.h +++ b/pjmedia/include/pjmedia/stereo.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -54,49 +53,49 @@ PJ_BEGIN_DECL * Multichannel to monochannel conversion. This function can work safely * using the same buffer (in place conversion). * - * @param mono Output buffer to store the mono frame extracted - * from the multichannels frame. - * @param multi Input frame containing multichannels audio. - * @param channel_count Number of channels in the input frame. + * @param mono Output buffer to store the mono frame extracted + * from the multichannels frame. + * @param multi Input frame containing multichannels audio. + * @param channel_count Number of channels in the input frame. * @param samples_per_frame Number of samples in the input frame. - * @param mix If the value is PJ_TRUE then the input channels - * will be mixed to produce output frame, otherwise - * only frame from channel_src will be copied to the - * output frame. - * @param channel_src When mixing is disabled, the mono output frame - * will be copied from this channel number. + * @param mix If the value is PJ_TRUE then the input channels + * will be mixed to produce output frame, otherwise + * only frame from channel_src will be copied to the + * output frame. + * @param channel_src When mixing is disabled, the mono output frame + * will be copied from this channel number. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ PJ_INLINE(pj_status_t) pjmedia_convert_channel_nto1(pj_int16_t mono[], - const pj_int16_t multi[], - unsigned channel_count, - unsigned samples_per_frame, - pj_bool_t mix, - unsigned channel_src) + const pj_int16_t multi[], + unsigned channel_count, + unsigned samples_per_frame, + pj_bool_t mix, + unsigned channel_src) { unsigned i; PJ_ASSERT_RETURN(mono && multi && channel_count && samples_per_frame && - channel_src < channel_count, PJ_EINVAL); + channel_src < channel_count, PJ_EINVAL); if (mix==PJ_FALSE) { - for (i = channel_src; i < samples_per_frame; i += channel_count) { - *mono = multi[i]; - ++mono; - } + for (i = channel_src; i < samples_per_frame; i += channel_count) { + *mono = multi[i]; + ++mono; + } } else { - unsigned j; - for (i = 0; i < samples_per_frame; i += channel_count) { - int tmp = 0; - for(j = 0; j < channel_count; ++j) - tmp += multi[i+j]; - - if (tmp > 32767) tmp = 32767; - else if (tmp < -32768) tmp = -32768; - *mono = (pj_int16_t) tmp; - ++mono; - } + unsigned j; + for (i = 0; i < samples_per_frame; i += channel_count) { + int tmp = 0; + for(j = 0; j < channel_count; ++j) + tmp += multi[i+j]; + + if (tmp > 32767) tmp = 32767; + else if (tmp < -32768) tmp = -32768; + *mono = (pj_int16_t) tmp; + ++mono; + } } return PJ_SUCCESS; @@ -109,25 +108,25 @@ PJ_INLINE(pj_status_t) pjmedia_convert_channel_nto1(pj_int16_t mono[], * This function can work safely using the same buffer (in place conversion) * as long as the buffer is big enough for the multichannel samples. * - * @param multi Output buffer to store the multichannels frame - * mixed from the mono frame. - * @param mono The input monochannel audio frame. - * @param channel_count Desired number of channels in the output frame. + * @param multi Output buffer to store the multichannels frame + * mixed from the mono frame. + * @param mono The input monochannel audio frame. + * @param channel_count Desired number of channels in the output frame. * @param samples_per_frame Number of samples in the input frame. - * @param options Options for conversion, currently must be zero. + * @param options Options for conversion, currently must be zero. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ PJ_INLINE(pj_status_t) pjmedia_convert_channel_1ton(pj_int16_t multi[], - const pj_int16_t mono[], - unsigned channel_count, - unsigned samples_per_frame, - unsigned options) + const pj_int16_t mono[], + unsigned channel_count, + unsigned samples_per_frame, + unsigned options) { const pj_int16_t *src; PJ_ASSERT_RETURN(mono && multi && channel_count && samples_per_frame, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(options == 0, PJ_EINVAL); PJ_UNUSED_ARG(options); @@ -135,11 +134,11 @@ PJ_INLINE(pj_status_t) pjmedia_convert_channel_1ton(pj_int16_t multi[], src = mono + samples_per_frame - 1; samples_per_frame *= channel_count; while (samples_per_frame) { - unsigned i; - for (i=1; i<=channel_count; ++i) - multi[samples_per_frame-i] = *src; - samples_per_frame -= channel_count; - --src; + unsigned i; + for (i=1; i<=channel_count; ++i) + multi[samples_per_frame-i] = *src; + samples_per_frame -= channel_count; + --src; } return PJ_SUCCESS; @@ -172,26 +171,26 @@ typedef enum pjmedia_stereo_port_options * to the downstream port's channel count before giving the frame to the * downstream port. * - * @param pool Pool to allocate the structure and buffers. - * @param dn_port The downstream port, which channel count is to - * be converted to the target channel count. - * @param channel_count This port channel count. - * @param options Bitmask flags from #pjmedia_stereo_port_options - * and also application may add PJMEDIA_STEREO_MIX - * to mix channels. - * When this flag is zero, the default behavior - * is to use simple N-to-1 channel converter and - * to destroy downstream port when this port is - * destroyed. - * @param p_port Pointer to receive the stereo port instance. + * @param pool Pool to allocate the structure and buffers. + * @param dn_port The downstream port, which channel count is to + * be converted to the target channel count. + * @param channel_count This port channel count. + * @param options Bitmask flags from #pjmedia_stereo_port_options + * and also application may add PJMEDIA_STEREO_MIX + * to mix channels. + * When this flag is zero, the default behavior + * is to use simple N-to-1 channel converter and + * to destroy downstream port when this port is + * destroyed. + * @param p_port Pointer to receive the stereo port instance. * * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_stereo_port_create( pj_pool_t *pool, - pjmedia_port *dn_port, - unsigned channel_count, - unsigned options, - pjmedia_port **p_port ); + pjmedia_port *dn_port, + unsigned channel_count, + unsigned options, + pjmedia_port **p_port ); PJ_END_DECL @@ -200,5 +199,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_STEREO_H__ */ +#endif /* __PJMEDIA_STEREO_H__ */ diff --git a/pjmedia/include/pjmedia/stream.h b/pjmedia/include/pjmedia/stream.h index cedb6d76f3..05231f4197 100644 --- a/pjmedia/include/pjmedia/stream.h +++ b/pjmedia/include/pjmedia/stream.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -92,60 +91,60 @@ typedef struct pjmedia_channel pjmedia_channel; */ typedef struct pjmedia_stream_info { - pjmedia_type type; /**< Media type (audio, video) */ - pjmedia_tp_proto proto; /**< Transport protocol (RTP/AVP, etc.) */ - pjmedia_dir dir; /**< Media direction. */ - pj_sockaddr local_addr; /**< Local RTP address */ - pj_sockaddr rem_addr; /**< Remote RTP address */ - pj_sockaddr rem_rtcp; /**< Optional remote RTCP address. If - sin_family is zero, the RTP address - will be calculated from RTP. */ - pj_bool_t rtcp_mux; /**< Use RTP and RTCP multiplexing. */ + pjmedia_type type; /**< Media type (audio, video) */ + pjmedia_tp_proto proto; /**< Transport protocol (RTP/AVP, etc.) */ + pjmedia_dir dir; /**< Media direction. */ + pj_sockaddr local_addr; /**< Local RTP address */ + pj_sockaddr rem_addr; /**< Remote RTP address */ + pj_sockaddr rem_rtcp; /**< Optional remote RTCP address. If + sin_family is zero, the RTP address + will be calculated from RTP. */ + pj_bool_t rtcp_mux; /**< Use RTP and RTCP multiplexing. */ #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) - pj_bool_t rtcp_xr_enabled; - /**< Specify whether RTCP XR is enabled.*/ - pj_uint32_t rtcp_xr_interval; /**< RTCP XR interval. */ - pj_sockaddr rtcp_xr_dest;/** @@ -33,16 +32,16 @@ PJ_BEGIN_DECL /** * Set audio routing for APS sound device. * - * @param stream The sound device stream, the stream should be started - * before calling this function. - * @param route Audio routing to be set. + * @param stream The sound device stream, the stream should be started + * before calling this function. + * @param route Audio routing to be set. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_snd_aps_set_route( pjmedia_snd_stream *stream, - pjmedia_snd_route route); + pjmedia_snd_route route); PJ_END_DECL -#endif /* __PJMEDIA_SYMBIAN_SOUND_APS_H__ */ +#endif /* __PJMEDIA_SYMBIAN_SOUND_APS_H__ */ diff --git a/pjmedia/include/pjmedia/tonegen.h b/pjmedia/include/pjmedia/tonegen.h index a787977605..a55452ed0c 100644 --- a/pjmedia/include/pjmedia/tonegen.h +++ b/pjmedia/include/pjmedia/tonegen.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -60,13 +59,13 @@ PJ_BEGIN_DECL */ typedef struct pjmedia_tone_desc { - short freq1; /**< First frequency. */ - short freq2; /**< Optional second frequency. */ - short on_msec; /**< Playback ON duration, in miliseconds. */ - short off_msec; /**< Playback OFF duration, ini miliseconds. */ - short volume; /**< Volume (1-32767), or 0 for default, which - PJMEDIA_TONEGEN_VOLUME will be used. */ - short flags; /**< Currently internal flags, must be 0 */ + short freq1; /**< First frequency. */ + short freq2; /**< Optional second frequency. */ + short on_msec; /**< Playback ON duration, in miliseconds. */ + short off_msec; /**< Playback OFF duration, ini miliseconds. */ + short volume; /**< Volume (1-32767), or 0 for default, which + PJMEDIA_TONEGEN_VOLUME will be used. */ + short flags; /**< Currently internal flags, must be 0 */ } pjmedia_tone_desc; @@ -77,11 +76,11 @@ typedef struct pjmedia_tone_desc */ typedef struct pjmedia_tone_digit { - char digit; /**< The ASCI identification for the digit. */ - short on_msec; /**< Playback ON duration, in miliseconds. */ - short off_msec; /**< Playback OFF duration, ini miliseconds. */ - short volume; /**< Volume (1-32767), or 0 for default, which - PJMEDIA_TONEGEN_VOLUME will be used. */ + char digit; /**< The ASCI identification for the digit. */ + short on_msec; /**< Playback ON duration, in miliseconds. */ + short off_msec; /**< Playback OFF duration, ini miliseconds. */ + short volume; /**< Volume (1-32767), or 0 for default, which + PJMEDIA_TONEGEN_VOLUME will be used. */ } pjmedia_tone_digit; @@ -93,13 +92,13 @@ typedef struct pjmedia_tone_digit */ typedef struct pjmedia_tone_digit_map { - unsigned count; /**< Number of digits in the map. */ + unsigned count; /**< Number of digits in the map. */ struct { - char digit; /**< The ASCI identification for the digit. */ - short freq1; /**< First frequency. */ - short freq2; /**< Optional second frequency. */ - } digits[16]; /**< Array of digits in the digit map. */ + char digit; /**< The ASCI identification for the digit. */ + short freq1; /**< First frequency. */ + short freq2; /**< Optional second frequency. */ + } digits[16]; /**< Array of digits in the digit map. */ } pjmedia_tone_digit_map; @@ -126,27 +125,27 @@ enum * When the tone generator is first created, it will be loaded with the * default digit map. * - * @param pool Pool to allocate memory for the port structure. - * @param clock_rate Sampling rate. - * @param channel_count Number of channels. Currently only mono and stereo - * are supported. + * @param pool Pool to allocate memory for the port structure. + * @param clock_rate Sampling rate. + * @param channel_count Number of channels. Currently only mono and stereo + * are supported. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Number of bits per sample. This version of PJMEDIA - * only supports 16bit per sample. - * @param options Option flags. Application may specify - * PJMEDIA_TONEGEN_LOOP to play the tone in a loop. - * @param p_port Pointer to receive the port instance. + * only supports 16bit per sample. + * @param options Option flags. Application may specify + * PJMEDIA_TONEGEN_LOOP to play the tone in a loop. + * @param p_port Pointer to receive the port instance. * - * @return PJ_SUCCESS on success, or the appropriate - * error code. + * @return PJ_SUCCESS on success, or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_tonegen_create(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_port **p_port); + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_port **p_port); /** @@ -154,37 +153,37 @@ PJ_DECL(pj_status_t) pjmedia_tonegen_create(pj_pool_t *pool, * When the tone generator is first created, it will be loaded with the * default digit map. * - * @param pool Pool to allocate memory for the port structure. - * @param name Optional name for the tone generator. - * @param clock_rate Sampling rate. - * @param channel_count Number of channels. Currently only mono and stereo - * are supported. + * @param pool Pool to allocate memory for the port structure. + * @param name Optional name for the tone generator. + * @param clock_rate Sampling rate. + * @param channel_count Number of channels. Currently only mono and stereo + * are supported. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Number of bits per sample. This version of PJMEDIA - * only supports 16bit per sample. - * @param options Option flags. Application may specify - * PJMEDIA_TONEGEN_LOOP to play the tone in a loop. - * @param p_port Pointer to receive the port instance. + * only supports 16bit per sample. + * @param options Option flags. Application may specify + * PJMEDIA_TONEGEN_LOOP to play the tone in a loop. + * @param p_port Pointer to receive the port instance. * - * @return PJ_SUCCESS on success, or the appropriate - * error code. + * @return PJ_SUCCESS on success, or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_tonegen_create2(pj_pool_t *pool, - const pj_str_t *name, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_port **p_port); + const pj_str_t *name, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_port **p_port); /** * Check if the tone generator is still busy producing some tones. * - * @param tonegen The tone generator instance. + * @param tonegen The tone generator instance. * - * @return Non-zero if busy. + * @return Non-zero if busy. */ PJ_DECL(pj_bool_t) pjmedia_tonegen_is_busy(pjmedia_port *tonegen); @@ -192,9 +191,9 @@ PJ_DECL(pj_bool_t) pjmedia_tonegen_is_busy(pjmedia_port *tonegen); /** * Instruct the tone generator to stop current processing. * - * @param tonegen The tone generator instance. + * @param tonegen The tone generator instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_tonegen_stop(pjmedia_port *tonegen); @@ -202,9 +201,9 @@ PJ_DECL(pj_status_t) pjmedia_tonegen_stop(pjmedia_port *tonegen); /** * Instruct the tone generator to stop looping of the current tone set. * - * @param tonegen The tone generator instance. + * @param tonegen The tone generator instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_tonegen_stop_loop(pjmedia_port *tonegen); @@ -213,9 +212,9 @@ PJ_DECL(pj_status_t) pjmedia_tonegen_stop_loop(pjmedia_port *tonegen); * Rewind the playback. This will start the playback to the first * tone in the playback list. * - * @param tonegen The tone generator instance. + * @param tonegen The tone generator instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_tonegen_rewind(pjmedia_port *tonegen); @@ -227,19 +226,19 @@ PJ_DECL(pj_status_t) pjmedia_tonegen_rewind(pjmedia_port *tonegen); * this function. The playback will begin as soon as the first get_frame() * is called to the generator. * - * @param tonegen The tone generator instance. - * @param count The number of tones in the array. - * @param tones Array of tones to be played. - * @param options Option flags. Application may specify - * PJMEDIA_TONEGEN_LOOP to play the tone in a loop. + * @param tonegen The tone generator instance. + * @param count The number of tones in the array. + * @param tones Array of tones to be played. + * @param options Option flags. Application may specify + * PJMEDIA_TONEGEN_LOOP to play the tone in a loop. * - * @return PJ_SUCCESS on success, or PJ_ETOOMANY if - * there are too many digits in the queue. + * @return PJ_SUCCESS on success, or PJ_ETOOMANY if + * there are too many digits in the queue. */ PJ_DECL(pj_status_t) pjmedia_tonegen_play(pjmedia_port *tonegen, - unsigned count, - const pjmedia_tone_desc tones[], - unsigned options); + unsigned count, + const pjmedia_tone_desc tones[], + unsigned options); /** * Instruct the tone generator to play multiple MF digits with each of @@ -250,46 +249,46 @@ PJ_DECL(pj_status_t) pjmedia_tonegen_play(pjmedia_port *tonegen, * The playback will begin as soon as the first get_frame() is called * to the generator. * - * @param tonegen The tone generator instance. - * @param count Number of digits in the array. - * @param digits Array of MF digits. - * @param options Option flags. Application may specify - * PJMEDIA_TONEGEN_LOOP to play the tone in a loop. + * @param tonegen The tone generator instance. + * @param count Number of digits in the array. + * @param digits Array of MF digits. + * @param options Option flags. Application may specify + * PJMEDIA_TONEGEN_LOOP to play the tone in a loop. * - * @return PJ_SUCCESS on success, or PJ_ETOOMANY if - * there are too many digits in the queue, or - * PJMEDIA_RTP_EINDTMF if invalid digit is - * specified. + * @return PJ_SUCCESS on success, or PJ_ETOOMANY if + * there are too many digits in the queue, or + * PJMEDIA_RTP_EINDTMF if invalid digit is + * specified. */ PJ_DECL(pj_status_t) pjmedia_tonegen_play_digits(pjmedia_port *tonegen, - unsigned count, - const pjmedia_tone_digit digits[], - unsigned options); + unsigned count, + const pjmedia_tone_digit digits[], + unsigned options); /** * Get the digit-map currently used by this tone generator. * - * @param tonegen The tone generator instance. - * @param m On output, it will be filled with the pointer to - * the digitmap currently used by the tone generator. + * @param tonegen The tone generator instance. + * @param m On output, it will be filled with the pointer to + * the digitmap currently used by the tone generator. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_tonegen_get_digit_map(pjmedia_port *tonegen, - const pjmedia_tone_digit_map **m); + const pjmedia_tone_digit_map **m); /** * Set digit map to be used by the tone generator. * - * @param tonegen The tone generator instance. - * @param m Digitmap to be used by the tone generator. + * @param tonegen The tone generator instance. + * @param m Digitmap to be used by the tone generator. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_tonegen_set_digit_map(pjmedia_port *tonegen, - pjmedia_tone_digit_map *m); + pjmedia_tone_digit_map *m); PJ_END_DECL @@ -299,5 +298,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_TONEGEN_PORT_H__ */ +#endif /* __PJMEDIA_TONEGEN_PORT_H__ */ diff --git a/pjmedia/include/pjmedia/transport.h b/pjmedia/include/pjmedia/transport.h index fbd3e8b675..961f2c57b0 100644 --- a/pjmedia/include/pjmedia/transport.h +++ b/pjmedia/include/pjmedia/transport.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -276,24 +275,24 @@ typedef enum pjmedia_tranport_media_option typedef struct pjmedia_sock_info { /** The RTP socket handle */ - pj_sock_t rtp_sock; + pj_sock_t rtp_sock; /** Address to be advertised as the local address for the RTP * socket, which does not need to be equal as the bound * address (for example, this address can be the address resolved * with STUN). */ - pj_sockaddr rtp_addr_name; + pj_sockaddr rtp_addr_name; /** The RTCP socket handle. */ - pj_sock_t rtcp_sock; + pj_sock_t rtcp_sock; /** Address to be advertised as the local address for the RTCP * socket, which does not need to be equal as the bound * address (for example, this address can be the address resolved * with STUN). */ - pj_sockaddr rtcp_addr_name; + pj_sockaddr rtcp_addr_name; } pjmedia_sock_info; @@ -309,7 +308,7 @@ struct pjmedia_transport_op * Application should call #pjmedia_transport_get_info() instead */ pj_status_t (*get_info)(pjmedia_transport *tp, - pjmedia_transport_info *info); + pjmedia_transport_info *info); /** * This function is called by the stream when the transport is about @@ -322,16 +321,16 @@ struct pjmedia_transport_op * calling this function directly. */ pj_status_t (*attach)(pjmedia_transport *tp, - void *user_data, - const pj_sockaddr_t *rem_addr, - const pj_sockaddr_t *rem_rtcp, - unsigned addr_len, - void (*rtp_cb)(void *user_data, - void *pkt, - pj_ssize_t size), - void (*rtcp_cb)(void *user_data, - void *pkt, - pj_ssize_t size)); + void *user_data, + const pj_sockaddr_t *rem_addr, + const pj_sockaddr_t *rem_rtcp, + unsigned addr_len, + void (*rtp_cb)(void *user_data, + void *pkt, + pj_ssize_t size), + void (*rtcp_cb)(void *user_data, + void *pkt, + pj_ssize_t size)); /** * This function is called by the stream when the stream no longer @@ -345,7 +344,7 @@ struct pjmedia_transport_op * calling this function directly. */ void (*detach)(pjmedia_transport *tp, - void *user_data); + void *user_data); /** * This function is called by the stream to send RTP packet using the @@ -355,8 +354,8 @@ struct pjmedia_transport_op * calling this function directly. */ pj_status_t (*send_rtp)(pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); /** * This function is called by the stream to send RTCP packet using the @@ -366,8 +365,8 @@ struct pjmedia_transport_op * calling this function directly. */ pj_status_t (*send_rtcp)(pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); /** * This function is called by the stream to send RTCP packet using the @@ -378,10 +377,10 @@ struct pjmedia_transport_op * calling this function directly. */ pj_status_t (*send_rtcp2)(pjmedia_transport *tp, - const pj_sockaddr_t *addr, - unsigned addr_len, - const void *pkt, - pj_size_t size); + const pj_sockaddr_t *addr, + unsigned addr_len, + const void *pkt, + pj_size_t size); /** * Prepare the transport for a new media session. @@ -390,10 +389,10 @@ struct pjmedia_transport_op * calling this function directly. */ pj_status_t (*media_create)(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - unsigned options, - const pjmedia_sdp_session *remote_sdp, - unsigned media_index); + pj_pool_t *sdp_pool, + unsigned options, + const pjmedia_sdp_session *remote_sdp, + unsigned media_index); /** * This function is called by application to generate the SDP parts @@ -403,10 +402,10 @@ struct pjmedia_transport_op * calling this function directly. */ pj_status_t (*encode_sdp)(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index); + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index); /** * This function is called by application to start the transport @@ -416,10 +415,10 @@ struct pjmedia_transport_op * calling this function directly. */ pj_status_t (*media_start) (pjmedia_transport *tp, - pj_pool_t *tmp_pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *tmp_pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); /** * This function is called by application to stop the transport. @@ -436,8 +435,8 @@ struct pjmedia_transport_op * calling this function directly. */ pj_status_t (*simulate_lost)(pjmedia_transport *tp, - pjmedia_dir dir, - unsigned pct_lost); + pjmedia_dir dir, + unsigned pct_lost); /** * This function can be called to destroy this transport. @@ -457,7 +456,7 @@ struct pjmedia_transport_op * calling this function directly. */ pj_status_t (*attach2)(pjmedia_transport *tp, - pjmedia_transport_attach_param *att_param); + pjmedia_transport_attach_param *att_param); }; @@ -504,7 +503,7 @@ typedef enum pjmedia_transport_type struct pjmedia_transport { /** Transport name (for logging purpose). */ - char name[PJ_MAX_OBJ_NAME]; + char name[PJ_MAX_OBJ_NAME]; /** Transport type. */ pjmedia_transport_type type; @@ -513,7 +512,7 @@ struct pjmedia_transport pjmedia_transport_op *op; /** Application/user data */ - void *user_data; + void *user_data; }; /** @@ -532,17 +531,17 @@ typedef struct pjmedia_transport_specific_info /** * Specify storage buffer size of transport specific info. */ - int cbsize; + int cbsize; /** * Storage buffer of transport specific info. */ - char buffer[PJMEDIA_TRANSPORT_SPECIFIC_INFO_MAXSIZE]; + char buffer[PJMEDIA_TRANSPORT_SPECIFIC_INFO_MAXSIZE]; /** * The media transport instance. */ - pjmedia_transport *tp; + pjmedia_transport *tp; } pjmedia_transport_specific_info; @@ -563,8 +562,8 @@ struct pjmedia_transport_info * Remote address where RTP/RTCP originated from. In case this transport * hasn't ever received packet, the address can be invalid (zero). */ - pj_sockaddr src_rtp_name; - pj_sockaddr src_rtcp_name; + pj_sockaddr src_rtp_name; + pj_sockaddr src_rtcp_name; /** * Specifies number of transport specific info included. @@ -586,29 +585,29 @@ typedef struct pjmedia_tp_cb_param /** * User data. */ - void *user_data; + void *user_data; /** * Packet buffer. */ - void *pkt; + void *pkt; /** * Packet size. */ - pj_ssize_t size; + pj_ssize_t size; /** * Packet's source address. */ - pj_sockaddr *src_addr; + pj_sockaddr *src_addr; /** * Should media transport switch remote address to \a rtp_src_addr? * Media transport should initialize it to PJ_FALSE, and application * can change the value as necessary. */ - pj_bool_t rem_switch; + pj_bool_t rem_switch; } pjmedia_tp_cb_param; @@ -671,7 +670,7 @@ struct pjmedia_transport_attach_param /** * Initialize transport info. * - * @param info Transport info to be initialized. + * @param info Transport info to be initialized. */ PJ_INLINE(void) pjmedia_transport_info_init(pjmedia_transport_info *info) { @@ -686,16 +685,16 @@ PJ_INLINE(void) pjmedia_transport_info_init(pjmedia_transport_info *info) * which describes the local address of the transport, and would be needed * for example to fill in the "c=" and "m=" line of local SDP. * - * @param tp The transport. - * @param info Media transport info to be initialized. + * @param tp The transport. + * @param info Media transport info to be initialized. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_transport_get_info(pjmedia_transport *tp, - pjmedia_transport_info *info) + pjmedia_transport_info *info) { if (tp && tp->op && tp->op->get_info) - return (*tp->op->get_info)(tp, info); + return (*tp->op->get_info)(tp, info); return PJ_ENOTSUP; } @@ -705,20 +704,20 @@ PJ_INLINE(pj_status_t) pjmedia_transport_get_info(pjmedia_transport *tp, * Utility API to get transport type specific info from the specified media * transport info. * - * @param info Media transport info. - * @param type Media transport type. + * @param info Media transport info. + * @param type Media transport type. * - * @return Pointer to media transport specific info, or NULL if - * specific info for the transport type is not found. + * @return Pointer to media transport specific info, or NULL if + * specific info for the transport type is not found. */ PJ_INLINE(void*) pjmedia_transport_info_get_spc_info( - pjmedia_transport_info *info, - pjmedia_transport_type type) + pjmedia_transport_info *info, + pjmedia_transport_type type) { unsigned i; for (i = 0; i < info->specific_info_cnt; ++i) { - if (info->spc_info[i].type == type) - return (void*)info->spc_info[i].buffer; + if (info->spc_info[i].type == type) + return (void*)info->spc_info[i].buffer; } return NULL; } @@ -728,20 +727,20 @@ PJ_INLINE(void*) pjmedia_transport_info_get_spc_info( * Utility API to get the transport instance from the specified media * transport info. * - * @param info Media transport info. - * @param type Media transport type. + * @param info Media transport info. + * @param type Media transport type. * - * @return The media transport instance, or NULL if - * the transport type is not found. + * @return The media transport instance, or NULL if + * the transport type is not found. */ PJ_INLINE(pjmedia_transport*) pjmedia_transport_info_get_transport( - pjmedia_transport_info *info, - pjmedia_transport_type type) + pjmedia_transport_info *info, + pjmedia_transport_type type) { unsigned i; for (i = 0; i < info->specific_info_cnt; ++i) { - if (info->spc_info[i].type == type) - return info->spc_info[i].tp; + if (info->spc_info[i].type == type) + return info->spc_info[i].tp; } return NULL; } @@ -753,22 +752,22 @@ PJ_INLINE(pjmedia_transport*) pjmedia_transport_info_get_transport( * the transport if it is implemented, otherwise it calls attach() * member of the transport. * - * @param tp The media transport. + * @param tp The media transport. * @param att_param The transport attach param. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_INLINE(pj_status_t) pjmedia_transport_attach2(pjmedia_transport *tp, pjmedia_transport_attach_param *att_param) { if (tp->op->attach2) { - return (*tp->op->attach2)(tp, att_param); + return (*tp->op->attach2)(tp, att_param); } else { - return (*tp->op->attach)(tp, att_param->user_data, - (pj_sockaddr_t*)&att_param->rem_addr, - (pj_sockaddr_t*)&att_param->rem_rtcp, - att_param->addr_len, att_param->rtp_cb, - att_param->rtcp_cb); + return (*tp->op->attach)(tp, att_param->user_data, + (pj_sockaddr_t*)&att_param->rem_addr, + (pj_sockaddr_t*)&att_param->rem_rtcp, + att_param->addr_len, att_param->rtp_cb, + att_param->rtcp_cb); } } @@ -778,56 +777,56 @@ PJ_INLINE(pj_status_t) pjmedia_transport_attach2(pjmedia_transport *tp, * This is just a simple wrapper which calls attach() member of * the transport. * - * @param tp The media transport. + * @param tp The media transport. * @param user_data Arbitrary user data to be set when the callbacks are - * called. + * called. * @param rem_addr Remote RTP address to send RTP packet to. * @param rem_rtcp Optional remote RTCP address. If the argument is NULL - * or if the address is zero, the RTCP address will be - * calculated from the RTP address (which is RTP port - * plus one). + * or if the address is zero, the RTCP address will be + * calculated from the RTP address (which is RTP port + * plus one). * @param addr_len Length of the remote address. * @param rtp_cb Callback to be called when RTP packet is received on - * the transport. + * the transport. * @param rtcp_cb Callback to be called when RTCP packet is received on - * the transport. + * the transport. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_INLINE(pj_status_t) pjmedia_transport_attach(pjmedia_transport *tp, - void *user_data, - const pj_sockaddr_t *rem_addr, - const pj_sockaddr_t *rem_rtcp, - unsigned addr_len, - void (*rtp_cb)(void *user_data, - void *pkt, - pj_ssize_t), - void (*rtcp_cb)(void *usr_data, - void*pkt, - pj_ssize_t)) + void *user_data, + const pj_sockaddr_t *rem_addr, + const pj_sockaddr_t *rem_rtcp, + unsigned addr_len, + void (*rtp_cb)(void *user_data, + void *pkt, + pj_ssize_t), + void (*rtcp_cb)(void *usr_data, + void*pkt, + pj_ssize_t)) { if (tp->op->attach2) { - pjmedia_transport_attach_param param; - - pj_bzero(¶m, sizeof(param)); - param.user_data = user_data; - pj_sockaddr_cp(¶m.rem_addr, rem_addr); - if (rem_rtcp && pj_sockaddr_has_addr(rem_rtcp)) { - pj_sockaddr_cp(¶m.rem_rtcp, rem_rtcp); - } else { - /* Copy RTCP address from the RTP address, with port + 1 */ - pj_memcpy(¶m.rem_rtcp, rem_addr, addr_len); - pj_sockaddr_set_port(¶m.rem_rtcp, - pj_sockaddr_get_port(rem_addr) + 1); - } - param.addr_len = addr_len; - param.rtp_cb = rtp_cb; - param.rtcp_cb = rtcp_cb; - - return (*tp->op->attach2)(tp, ¶m); + pjmedia_transport_attach_param param; + + pj_bzero(¶m, sizeof(param)); + param.user_data = user_data; + pj_sockaddr_cp(¶m.rem_addr, rem_addr); + if (rem_rtcp && pj_sockaddr_has_addr(rem_rtcp)) { + pj_sockaddr_cp(¶m.rem_rtcp, rem_rtcp); + } else { + /* Copy RTCP address from the RTP address, with port + 1 */ + pj_memcpy(¶m.rem_rtcp, rem_addr, addr_len); + pj_sockaddr_set_port(¶m.rem_rtcp, + pj_sockaddr_get_port(rem_addr) + 1); + } + param.addr_len = addr_len; + param.rtp_cb = rtp_cb; + param.rtcp_cb = rtcp_cb; + + return (*tp->op->attach2)(tp, ¶m); } else { - return (*tp->op->attach)(tp, user_data, rem_addr, rem_rtcp, addr_len, - rtp_cb, rtcp_cb); + return (*tp->op->attach)(tp, user_data, rem_addr, rem_rtcp, addr_len, + rtp_cb, rtcp_cb); } } @@ -840,12 +839,12 @@ PJ_INLINE(pj_status_t) pjmedia_transport_attach(pjmedia_transport *tp, * Application may re-attach the media transport to another transport user * (e.g. stream) after the transport has been detached. * - * @param tp The media transport. + * @param tp The media transport. * @param user_data User data which must match the previously set value - * on attachment. + * on attachment. */ PJ_INLINE(void) pjmedia_transport_detach(pjmedia_transport *tp, - void *user_data) + void *user_data) { (*tp->op->detach)(tp, user_data); } @@ -857,15 +856,15 @@ PJ_INLINE(void) pjmedia_transport_detach(pjmedia_transport *tp, * RTP packet will be delivered to the destination address specified in * #pjmedia_transport_attach() function. * - * @param tp The media transport. - * @param pkt The packet to send. - * @param size Size of the packet. + * @param tp The media transport. + * @param pkt The packet to send. + * @param size Size of the packet. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_INLINE(pj_status_t) pjmedia_transport_send_rtp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { return (*tp->op->send_rtp)(tp, pkt, size); } @@ -877,15 +876,15 @@ PJ_INLINE(pj_status_t) pjmedia_transport_send_rtp(pjmedia_transport *tp, * RTCP packet will be delivered to the destination address specified in * #pjmedia_transport_attach() function. * - * @param tp The media transport. - * @param pkt The packet to send. - * @param size Size of the packet. + * @param tp The media transport. + * @param pkt The packet to send. + * @param size Size of the packet. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_INLINE(pj_status_t) pjmedia_transport_send_rtcp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { return (*tp->op->send_rtcp)(tp, pkt, size); } @@ -898,19 +897,19 @@ PJ_INLINE(pj_status_t) pjmedia_transport_send_rtcp(pjmedia_transport *tp, * param addr, if addr is NULL, RTCP packet will be delivered to destination * address specified in #pjmedia_transport_attach() function. * - * @param tp The media transport. - * @param addr The destination address. + * @param tp The media transport. + * @param addr The destination address. * @param addr_len Length of destination address. - * @param pkt The packet to send. - * @param size Size of the packet. + * @param pkt The packet to send. + * @param size Size of the packet. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_INLINE(pj_status_t) pjmedia_transport_send_rtcp2(pjmedia_transport *tp, - const pj_sockaddr_t *addr, - unsigned addr_len, - const void *pkt, - pj_size_t size) + const pj_sockaddr_t *addr, + unsigned addr_len, + const void *pkt, + pj_size_t size) { return (*tp->op->send_rtcp2)(tp, addr, addr_len, pkt, size); } @@ -924,24 +923,24 @@ PJ_INLINE(pj_status_t) pjmedia_transport_send_rtcp2(pjmedia_transport *tp, * This is just a simple wrapper which calls media_create() member * of the transport. * - * @param tp The media transport. - * @param sdp_pool Pool object to allocate memory related to SDP - * messaging components. - * @param options Option flags, from #pjmedia_tranport_media_option - * @param rem_sdp Remote SDP if local SDP is an answer, otherwise - * specify NULL if SDP is an offer. - * @param media_index Media index in SDP. + * @param tp The media transport. + * @param sdp_pool Pool object to allocate memory related to SDP + * messaging components. + * @param options Option flags, from #pjmedia_tranport_media_option + * @param rem_sdp Remote SDP if local SDP is an answer, otherwise + * specify NULL if SDP is an offer. + * @param media_index Media index in SDP. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_INLINE(pj_status_t) pjmedia_transport_media_create(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - unsigned options, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *sdp_pool, + unsigned options, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { return (*tp->op->media_create)(tp, sdp_pool, options, rem_sdp, - media_index); + media_index); } @@ -953,22 +952,22 @@ PJ_INLINE(pj_status_t) pjmedia_transport_media_create(pjmedia_transport *tp, * This is just a simple wrapper which calls encode_sdp() member * of the transport. * - * @param tp The media transport. - * @param sdp_pool Pool object to allocate memory related to SDP - * messaging components. - * @param sdp The local SDP to be filled in information from the - * media transport. - * @param rem_sdp Remote SDP if local SDP is an answer, otherwise - * specify NULL if SDP is an offer. - * @param media_index Media index in SDP. + * @param tp The media transport. + * @param sdp_pool Pool object to allocate memory related to SDP + * messaging components. + * @param sdp The local SDP to be filled in information from the + * media transport. + * @param rem_sdp Remote SDP if local SDP is an answer, otherwise + * specify NULL if SDP is an offer. + * @param media_index Media index in SDP. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_INLINE(pj_status_t) pjmedia_transport_encode_sdp(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { return (*tp->op->encode_sdp)(tp, sdp_pool, sdp, rem_sdp, media_index); } @@ -984,22 +983,22 @@ PJ_INLINE(pj_status_t) pjmedia_transport_encode_sdp(pjmedia_transport *tp, * This is just a simple wrapper which calls media_start() member * of the transport. * - * @param tp The media transport. - * @param tmp_pool The memory pool for allocating temporary objects. - * @param sdp_local Local SDP. - * @param sdp_remote Remote SDP. - * @param media_index Media index in the SDP. + * @param tp The media transport. + * @param tmp_pool The memory pool for allocating temporary objects. + * @param sdp_local Local SDP. + * @param sdp_remote Remote SDP. + * @param media_index Media index in the SDP. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_INLINE(pj_status_t) pjmedia_transport_media_start(pjmedia_transport *tp, - pj_pool_t *tmp_pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *tmp_pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { return (*tp->op->media_start)(tp, tmp_pool, sdp_local, sdp_remote, - media_index); + media_index); } @@ -1010,9 +1009,9 @@ PJ_INLINE(pj_status_t) pjmedia_transport_media_start(pjmedia_transport *tp, * This is just a simple wrapper which calls media_stop() member * of the transport. * - * @param tp The media transport. + * @param tp The media transport. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_INLINE(pj_status_t) pjmedia_transport_media_stop(pjmedia_transport *tp) { @@ -1024,16 +1023,16 @@ PJ_INLINE(pj_status_t) pjmedia_transport_media_stop(pjmedia_transport *tp) * destroy() member of the transport. This function will free * all resources created by this transport (such as sockets, memory, etc.). * - * @param tp The media transport. + * @param tp The media transport. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_INLINE(pj_status_t) pjmedia_transport_close(pjmedia_transport *tp) { if (tp->op->destroy) - return (*tp->op->destroy)(tp); + return (*tp->op->destroy)(tp); else - return PJ_SUCCESS; + return PJ_SUCCESS; } /** @@ -1041,16 +1040,16 @@ PJ_INLINE(pj_status_t) pjmedia_transport_close(pjmedia_transport *tp) * When enabled, the transport will randomly drop packets to the specified * direction. * - * @param tp The media transport. - * @param dir Media direction to which packets will be randomly dropped. + * @param tp The media transport. + * @param dir Media direction to which packets will be randomly dropped. * @param pct_lost Percent lost (0-100). Set to zero to disable packet - * lost simulation. + * lost simulation. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_transport_simulate_lost(pjmedia_transport *tp, - pjmedia_dir dir, - unsigned pct_lost) + pjmedia_dir dir, + unsigned pct_lost) { return (*tp->op->simulate_lost)(tp, dir, pct_lost); } @@ -1063,5 +1062,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_TRANSPORT_H__ */ +#endif /* __PJMEDIA_TRANSPORT_H__ */ diff --git a/pjmedia/include/pjmedia/transport_adapter_sample.h b/pjmedia/include/pjmedia/transport_adapter_sample.h index 62eb1c0f23..51d2c3037b 100644 --- a/pjmedia/include/pjmedia/transport_adapter_sample.h +++ b/pjmedia/include/pjmedia/transport_adapter_sample.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,22 +45,22 @@ PJ_BEGIN_DECL * Create the transport adapter, specifying the underlying transport to be * used to send and receive RTP/RTCP packets. * - * @param endpt The media endpoint. - * @param name Optional name to identify this media transport - * for logging purposes. - * @param base_tp The base/underlying media transport to send and - * receive RTP/RTCP packets. - * @param del_base Specify whether the base transport should also be - * destroyed when destroy() is called upon us. - * @param p_tp Pointer to receive the media transport instance. + * @param endpt The media endpoint. + * @param name Optional name to identify this media transport + * for logging purposes. + * @param base_tp The base/underlying media transport to send and + * receive RTP/RTCP packets. + * @param del_base Specify whether the base transport should also be + * destroyed when destroy() is called upon us. + * @param p_tp Pointer to receive the media transport instance. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_tp_adapter_create( pjmedia_endpt *endpt, - const char *name, - pjmedia_transport *base_tp, - pj_bool_t del_base, - pjmedia_transport **p_tp); + const char *name, + pjmedia_transport *base_tp, + pj_bool_t del_base, + pjmedia_transport **p_tp); PJ_END_DECL @@ -71,6 +70,6 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_TRANSPORT_ADAPTER_SAMPLE_H__ */ +#endif /* __PJMEDIA_TRANSPORT_ADAPTER_SAMPLE_H__ */ diff --git a/pjmedia/include/pjmedia/transport_ice.h b/pjmedia/include/pjmedia/transport_ice.h index 08476f09af..3e06b04803 100644 --- a/pjmedia/include/pjmedia/transport_ice.h +++ b/pjmedia/include/pjmedia/transport_ice.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -51,28 +50,28 @@ typedef struct pjmedia_ice_cb /** * This callback will be called when ICE negotiation completes. * - * @param tp PJMEDIA ICE transport. - * @param op The operation - * @param status Operation status. + * @param tp PJMEDIA ICE transport. + * @param op The operation + * @param status Operation status. */ void (*on_ice_complete)(pjmedia_transport *tp, - pj_ice_strans_op op, - pj_status_t status); + pj_ice_strans_op op, + pj_status_t status); /** * This callback will be called when ICE negotiation completes, with * application user data. Note that if both callbacks are implemented, * only this callback will be invoked. * - * @param tp PJMEDIA ICE transport. - * @param op The operation - * @param status Operation status. - * @param user_data User data for this callback. + * @param tp PJMEDIA ICE transport. + * @param op The operation + * @param status Operation status. + * @param user_data User data for this callback. */ void (*on_ice_complete2)(pjmedia_transport *tp, - pj_ice_strans_op op, - pj_status_t status, - void *user_data); + pj_ice_strans_op op, + pj_status_t status, + void *user_data); /** * Callback to report a new ICE local candidate, e.g: after successful @@ -84,14 +83,14 @@ typedef struct pjmedia_ice_cb * Trickle ICE can use this callback to convey the new candidate * to remote agent and monitor end-of-candidate indication. * - * @param tp PJMEDIA ICE transport. - * @param cand The new local candidate, can be NULL when the last - * local candidate initialization failed/timeout. - * @param last PJ_TRUE if this is the last of local candidate. + * @param tp PJMEDIA ICE transport. + * @param cand The new local candidate, can be NULL when the last + * local candidate initialization failed/timeout. + * @param last PJ_TRUE if this is the last of local candidate. */ void (*on_new_candidate)(pjmedia_transport *tp, - const pj_ice_sess_cand *cand, - pj_bool_t last); + const pj_ice_sess_cand *cand, + pj_bool_t last); } pjmedia_ice_cb; @@ -118,8 +117,8 @@ typedef struct pjmedia_ice_transport_info */ pj_ice_sess_role role; - pj_str_t loc_ufrag; - pj_str_t rem_ufrag; + pj_str_t loc_ufrag; + pj_str_t rem_ufrag; /** * Number of components in the component array. Before ICE negotiation @@ -136,25 +135,25 @@ typedef struct pjmedia_ice_transport_info */ struct { - /** - * Local candidate type. - */ - pj_ice_cand_type lcand_type; - - /** - * The local address. - */ - pj_sockaddr lcand_addr; - - /** - * Remote candidate type. - */ - pj_ice_cand_type rcand_type; - - /** - * Remote address. - */ - pj_sockaddr rcand_addr; + /** + * Local candidate type. + */ + pj_ice_cand_type lcand_type; + + /** + * The local address. + */ + pj_sockaddr lcand_addr; + + /** + * Remote candidate type. + */ + pj_ice_cand_type rcand_type; + + /** + * Remote address. + */ + pj_sockaddr rcand_addr; } comp[2]; @@ -205,76 +204,76 @@ enum pjmedia_transport_ice_options * Other than this, application should use the \ref PJMEDIA_TRANSPORT API * to manipulate this media transport. * - * @param endpt The media endpoint. - * @param name Optional name to identify this ICE media transport - * for logging purposes. - * @param comp_cnt Number of components to be created. - * @param cfg Pointer to configuration settings. - * @param cb Optional structure containing ICE specific callbacks. - * @param p_tp Pointer to receive the media transport instance. + * @param endpt The media endpoint. + * @param name Optional name to identify this ICE media transport + * for logging purposes. + * @param comp_cnt Number of components to be created. + * @param cfg Pointer to configuration settings. + * @param cb Optional structure containing ICE specific callbacks. + * @param p_tp Pointer to receive the media transport instance. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_ice_create(pjmedia_endpt *endpt, - const char *name, - unsigned comp_cnt, - const pj_ice_strans_cfg *cfg, - const pjmedia_ice_cb *cb, - pjmedia_transport **p_tp); + const char *name, + unsigned comp_cnt, + const pj_ice_strans_cfg *cfg, + const pjmedia_ice_cb *cb, + pjmedia_transport **p_tp); /** * The same as #pjmedia_ice_create() with additional \a options param. * - * @param endpt The media endpoint. - * @param name Optional name to identify this ICE media transport - * for logging purposes. - * @param comp_cnt Number of components to be created. - * @param cfg Pointer to configuration settings. - * @param cb Optional structure containing ICE specific callbacks. - * @param options Options, see #pjmedia_transport_ice_options. - * @param p_tp Pointer to receive the media transport instance. + * @param endpt The media endpoint. + * @param name Optional name to identify this ICE media transport + * for logging purposes. + * @param comp_cnt Number of components to be created. + * @param cfg Pointer to configuration settings. + * @param cb Optional structure containing ICE specific callbacks. + * @param options Options, see #pjmedia_transport_ice_options. + * @param p_tp Pointer to receive the media transport instance. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_ice_create2(pjmedia_endpt *endpt, - const char *name, - unsigned comp_cnt, - const pj_ice_strans_cfg *cfg, - const pjmedia_ice_cb *cb, - unsigned options, - pjmedia_transport **p_tp); + const char *name, + unsigned comp_cnt, + const pj_ice_strans_cfg *cfg, + const pjmedia_ice_cb *cb, + unsigned options, + pjmedia_transport **p_tp); /** * The same as #pjmedia_ice_create2() with additional \a user_data param. * - * @param endpt The media endpoint. - * @param name Optional name to identify this ICE media transport - * for logging purposes. - * @param comp_cnt Number of components to be created. - * @param cfg Pointer to configuration settings. - * @param cb Optional structure containing ICE specific callbacks. - * @param options Options, see #pjmedia_transport_ice_options. - * @param user_data User data to be attached to the transport. - * @param p_tp Pointer to receive the media transport instance. - * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @param endpt The media endpoint. + * @param name Optional name to identify this ICE media transport + * for logging purposes. + * @param comp_cnt Number of components to be created. + * @param cfg Pointer to configuration settings. + * @param cb Optional structure containing ICE specific callbacks. + * @param options Options, see #pjmedia_transport_ice_options. + * @param user_data User data to be attached to the transport. + * @param p_tp Pointer to receive the media transport instance. + * + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_ice_create3(pjmedia_endpt *endpt, - const char *name, - unsigned comp_cnt, - const pj_ice_strans_cfg *cfg, - const pjmedia_ice_cb *cb, - unsigned options, - void *user_data, - pjmedia_transport **p_tp); + const char *name, + unsigned comp_cnt, + const pj_ice_strans_cfg *cfg, + const pjmedia_ice_cb *cb, + unsigned options, + void *user_data, + pjmedia_transport **p_tp); /** * Get the group lock for the ICE media transport. * - * @param tp The ICE media transport. + * @param tp The ICE media transport. * - * @return The group lock. + * @return The group lock. */ PJ_DECL(pj_grp_lock_t *) pjmedia_ice_get_grp_lock(pjmedia_transport *tp); @@ -283,32 +282,32 @@ PJ_DECL(pj_grp_lock_t *) pjmedia_ice_get_grp_lock(pjmedia_transport *tp); * Add application to receive ICE notifications from the specified ICE media * transport. * - * @param tp The ICE media transport. - * @param cb The ICE specific callbacks. + * @param tp The ICE media transport. + * @param cb The ICE specific callbacks. * @param user_data Optional application user data. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_ice_add_ice_cb(pjmedia_transport *tp, - const pjmedia_ice_cb *cb, - void *user_data); + const pjmedia_ice_cb *cb, + void *user_data); /** * Remove application to stop receiving ICE notifications from the specified * ICE media transport. * - * @param tp The ICE media transport. - * @param cb The ICE specific callbacks. + * @param tp The ICE media transport. + * @param cb The ICE specific callbacks. * @param user_data Optional application user data. The same user data - * passed to pjmedia_ice_add_ice_cb(), this is for - * validation purpose. + * passed to pjmedia_ice_add_ice_cb(), this is for + * validation purpose. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_ice_remove_ice_cb(pjmedia_transport *tp, - const pjmedia_ice_cb *cb, - void *user_data); + const pjmedia_ice_cb *cb, + void *user_data); /** @@ -316,13 +315,13 @@ PJ_DECL(pj_status_t) pjmedia_ice_remove_ice_cb(pjmedia_transport *tp, * will check trickle indication in the media level first, if not found, it * will check in the session level. * - * @param sdp The SDP. - * @param med_idx The media index to be checked. + * @param sdp The SDP. + * @param med_idx The media index to be checked. * - * @return PJ_TRUE if trickle ICE indication is found. + * @return PJ_TRUE if trickle ICE indication is found. */ PJ_DECL(pj_bool_t) pjmedia_ice_sdp_has_trickle(const pjmedia_sdp_session *sdp, - unsigned med_idx); + unsigned med_idx); /** @@ -339,51 +338,51 @@ PJ_DECL(pj_bool_t) pjmedia_ice_sdp_has_trickle(const pjmedia_sdp_session *sdp, * * This function is only applicable when trickle ICE is not disabled. * - * @param tp The ICE media transport. - * @param rem_ufrag Remote ufrag, as seen in the SDP received from - * the remote agent. - * @param rem_passwd Remote password, as seen in the SDP received from - * the remote agent. - * @param rcand_cnt Number of new remote candidates in the array. - * @param rcand New remote candidates array. - * @param rcand_end Set to PJ_TRUE if remote has signalled - * end-of-candidate. - * - * @return PJ_SUCCESS, or the appropriate error code. + * @param tp The ICE media transport. + * @param rem_ufrag Remote ufrag, as seen in the SDP received from + * the remote agent. + * @param rem_passwd Remote password, as seen in the SDP received from + * the remote agent. + * @param rcand_cnt Number of new remote candidates in the array. + * @param rcand New remote candidates array. + * @param rcand_end Set to PJ_TRUE if remote has signalled + * end-of-candidate. + * + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_ice_trickle_update( - pjmedia_transport *tp, - const pj_str_t *rem_ufrag, - const pj_str_t *rem_passwd, - unsigned rcand_cnt, - const pj_ice_sess_cand rcand[], - pj_bool_t rcand_end); + pjmedia_transport *tp, + const pj_str_t *rem_ufrag, + const pj_str_t *rem_passwd, + unsigned rcand_cnt, + const pj_ice_sess_cand rcand[], + pj_bool_t rcand_end); /** * Decode trickle ICE info from the specified SDP. * - * @param sdp The SDP containing trickle ICE info. - * @param media_index The media index. - * @param mid Output, media ID. - * @param ufrag Output, ufrag. - * @param passwd Output, password. - * @param cand_cnt On input, maximum number of candidate array. - * On output, the number of candidates. - * @param cand Output, the candidates. - * @param end_of_cand Output, end of candidate indication. - * - * @return PJ_SUCCESS, or the appropriate error code. + * @param sdp The SDP containing trickle ICE info. + * @param media_index The media index. + * @param mid Output, media ID. + * @param ufrag Output, ufrag. + * @param passwd Output, password. + * @param cand_cnt On input, maximum number of candidate array. + * On output, the number of candidates. + * @param cand Output, the candidates. + * @param end_of_cand Output, end of candidate indication. + * + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_ice_trickle_decode_sdp( - const pjmedia_sdp_session *sdp, - unsigned media_index, - pj_str_t *mid, - pj_str_t *ufrag, - pj_str_t *passwd, - unsigned *cand_cnt, - pj_ice_sess_cand cand[], - pj_bool_t *end_of_cand); + const pjmedia_sdp_session *sdp, + unsigned media_index, + pj_str_t *mid, + pj_str_t *ufrag, + pj_str_t *passwd, + unsigned *cand_cnt, + pj_ice_sess_cand cand[], + pj_bool_t *end_of_cand); /** @@ -395,35 +394,35 @@ PJ_DECL(pj_status_t) pjmedia_ice_trickle_decode_sdp( * - ICE candidates, "a=candidate". * - End of candidate indication, "a=end-of-candidates". * - * @param sdp_pool The memory pool for generating SDP attributes. - * @param sdp The SDP to be updated. - * @param mid The media ID. - * @param ufrag The ufrag, optional. - * @param passwd The password, optional. - * @param cand_cnt The number of local candidates, can be zero. - * @param cand The local candidates. - * @param end_of_cand End of candidate indication. + * @param sdp_pool The memory pool for generating SDP attributes. + * @param sdp The SDP to be updated. + * @param mid The media ID. + * @param ufrag The ufrag, optional. + * @param passwd The password, optional. + * @param cand_cnt The number of local candidates, can be zero. + * @param cand The local candidates. + * @param end_of_cand End of candidate indication. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_ice_trickle_encode_sdp( - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp, - const pj_str_t *mid, - const pj_str_t *ufrag, - const pj_str_t *passwd, - unsigned cand_cnt, - const pj_ice_sess_cand cand[], - pj_bool_t end_of_cand); + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp, + const pj_str_t *mid, + const pj_str_t *ufrag, + const pj_str_t *passwd, + unsigned cand_cnt, + const pj_ice_sess_cand cand[], + pj_bool_t end_of_cand); /** * Check if trickling ICE has found any new local candidates since the last * conveyance (via pjmedia_ice_trickle_send_local_cand()). * - * @param tp The ICE media transport. + * @param tp The ICE media transport. * - * @return PJ_TRUE if new local canditates are available. + * @return PJ_TRUE if new local canditates are available. */ PJ_DECL(pj_bool_t) pjmedia_ice_trickle_has_new_cand(pjmedia_transport *tp); @@ -431,19 +430,19 @@ PJ_DECL(pj_bool_t) pjmedia_ice_trickle_has_new_cand(pjmedia_transport *tp); /** * Convey all local candidates via the specified SDP. * - * @param tp The ICE media transport. - * @param sdp_pool The memory pool for generating SDP attributes. - * @param sdp The SDP. + * @param tp The ICE media transport. + * @param sdp_pool The memory pool for generating SDP attributes. + * @param sdp The SDP. * @param p_end_of_cand Optional, pointer to receive the indication that - * candidate gathering has been completed. + * candidate gathering has been completed. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_ice_trickle_send_local_cand( - pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp, - pj_bool_t *p_end_of_cand); + pjmedia_transport *tp, + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp, + pj_bool_t *p_end_of_cand); PJ_END_DECL @@ -454,6 +453,6 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_TRANSPORT_ICE_H__ */ +#endif /* __PJMEDIA_TRANSPORT_ICE_H__ */ diff --git a/pjmedia/include/pjmedia/transport_loop.h b/pjmedia/include/pjmedia/transport_loop.h index 987dd90628..76fbe14dc0 100644 --- a/pjmedia/include/pjmedia/transport_loop.h +++ b/pjmedia/include/pjmedia/transport_loop.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -59,7 +58,7 @@ typedef struct pjmedia_loop_tp_setting /* Address family, which can be pj_AF_INET() for IPv4 or * pj_AF_INET6() for IPv6. Default is IPv4 (pj_AF_INET()). */ - int af; + int af; /* Optional local address which will be returned in the transport info. * If the string is empty, the address will be the default loopback @@ -70,7 +69,7 @@ typedef struct pjmedia_loop_tp_setting * * Default is empty string. */ - pj_str_t addr; + pj_str_t addr; /* The port number for the RTP socket. The RTCP port number will be * set to one above RTP port. If zero, it will use the default port @@ -78,7 +77,7 @@ typedef struct pjmedia_loop_tp_setting * * Note that no actual port will be allocated. Default is 4000. */ - int port; + int port; /* Setting whether attached streams will receive incoming packets. * Application can further customize the setting of a particular setting @@ -86,7 +85,7 @@ typedef struct pjmedia_loop_tp_setting * * Default: PJ_FALSE; */ - pj_bool_t disable_rx; + pj_bool_t disable_rx; } pjmedia_loop_tp_setting; @@ -94,7 +93,7 @@ typedef struct pjmedia_loop_tp_setting /** * Initialize loopback media transport setting with its default values. * - * @param opt SRTP setting to be initialized. + * @param opt SRTP setting to be initialized. */ PJ_DECL(void) pjmedia_loop_tp_setting_default(pjmedia_loop_tp_setting *opt); @@ -102,43 +101,43 @@ PJ_DECL(void) pjmedia_loop_tp_setting_default(pjmedia_loop_tp_setting *opt); /** * Create the loopback transport. * - * @param endpt The media endpoint instance. - * @param p_tp Pointer to receive the transport instance. + * @param endpt The media endpoint instance. + * @param p_tp Pointer to receive the transport instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_loop_create(pjmedia_endpt *endpt, - pjmedia_transport **p_tp); + pjmedia_transport **p_tp); /** * Create the loopback transport. * - * @param endpt The media endpoint instance. + * @param endpt The media endpoint instance. * @param opt Optional settings. If NULL is given, default - * settings will be used. - * @param p_tp Pointer to receive the transport instance. + * settings will be used. + * @param p_tp Pointer to receive the transport instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_loop_create2(pjmedia_endpt *endpt, - const pjmedia_loop_tp_setting *opt, - pjmedia_transport **p_tp); + const pjmedia_loop_tp_setting *opt, + pjmedia_transport **p_tp); /** * Set the configuration of whether a stream will become the receiver of * incoming packets. * - * @param tp The transport. - * @param user The stream. + * @param tp The transport. + * @param user The stream. * @param disabled PJ_TRUE to disable the receiving of packets, or - * PJ_FALSE to enable it. + * PJ_FALSE to enable it. */ PJ_DECL(pj_status_t) pjmedia_transport_loop_disable_rx(pjmedia_transport *tp, - void *user, - pj_bool_t disabled); + void *user, + pj_bool_t disabled); PJ_END_DECL @@ -149,6 +148,6 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_TRANSPORT_LOOP_H__ */ +#endif /* __PJMEDIA_TRANSPORT_LOOP_H__ */ diff --git a/pjmedia/include/pjmedia/transport_srtp.h b/pjmedia/include/pjmedia/transport_srtp.h index a90ba7f5aa..af702ca974 100644 --- a/pjmedia/include/pjmedia/transport_srtp.h +++ b/pjmedia/include/pjmedia/transport_srtp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -91,13 +90,13 @@ typedef enum pjmedia_srtp_crypto_option typedef struct pjmedia_srtp_crypto { /** Optional key. If empty, a random key will be autogenerated. */ - pj_str_t key; + pj_str_t key; /** Crypto name. */ - pj_str_t name; + pj_str_t name; /** Flags, bitmask from #pjmedia_srtp_crypto_option */ - unsigned flags; + unsigned flags; } pjmedia_srtp_crypto; @@ -169,11 +168,11 @@ typedef struct pjmedia_srtp_cb * callback will be invoked when the negotiation is done outside of * the SDP signalling, such as in DTLS-SRTP. * - * @param tp PJMEDIA SRTP transport. - * @param status Operation status. + * @param tp PJMEDIA SRTP transport. + * @param status Operation status. */ void (*on_srtp_nego_complete)(pjmedia_transport *tp, - pj_status_t status); + pj_status_t status); } pjmedia_srtp_cb; @@ -186,12 +185,12 @@ typedef struct pjmedia_srtp_roc /** * The synchronization source. */ - pj_uint32_t ssrc; + pj_uint32_t ssrc; /** * The rollover counter. */ - pj_uint32_t roc; + pj_uint32_t roc; } pjmedia_srtp_roc; @@ -205,19 +204,19 @@ typedef struct pjmedia_srtp_setting /** * Specify the usage policy. Default is PJMEDIA_SRTP_OPTIONAL. */ - pjmedia_srtp_use use; + pjmedia_srtp_use use; /** * Specify whether the SRTP transport should close the member transport * when it is destroyed. Default: PJ_TRUE. */ - pj_bool_t close_member_tp; + pj_bool_t close_member_tp; /** * Specify the number of crypto suite settings. If set to zero, all * available cryptos will be enabled. Default: zero. */ - unsigned crypto_count; + unsigned crypto_count; /** * Specify individual crypto suite setting and its priority order. @@ -227,7 +226,7 @@ typedef struct pjmedia_srtp_setting * AES_CM_128_HMAC_SHA1_32, AEAD_AES_256_GCM, and AEAD_AES_128_GCM. * - SRTP key is not configurable. */ - pjmedia_srtp_crypto crypto[PJMEDIA_SRTP_MAX_CRYPTOS]; + pjmedia_srtp_crypto crypto[PJMEDIA_SRTP_MAX_CRYPTOS]; /** * Specify the number of enabled keying methods. If set to zero, all @@ -236,7 +235,7 @@ typedef struct pjmedia_srtp_setting * Default is zero (all keyings are enabled with priority order: * SDES, DTLS-SRTP). */ - unsigned keying_count; + unsigned keying_count; /** * Specify enabled keying methods and its priority order. Keying method @@ -244,14 +243,14 @@ typedef struct pjmedia_srtp_setting * for example as currently only one keying is supported in the SDP offer, * keying with first priority will be likely used in the SDP offer. */ - pjmedia_srtp_keying_method keying[PJMEDIA_SRTP_KEYINGS_COUNT]; + pjmedia_srtp_keying_method keying[PJMEDIA_SRTP_KEYINGS_COUNT]; /** * RTP sequence rollover counter initialization value for incoming * direction. This is useful to maintain ROC after media transport * recreation such as in IP change scenario. */ - pjmedia_srtp_roc rx_roc; + pjmedia_srtp_roc rx_roc; /** * The previous value of RTP sequence rollover counter. This is @@ -261,24 +260,24 @@ typedef struct pjmedia_srtp_setting * unprotect with this ROC value as well. * Set prev_rx_roc.ssrc to 0 to disable this feature. */ - pjmedia_srtp_roc prev_rx_roc; + pjmedia_srtp_roc prev_rx_roc; /** * RTP sequence rollover counter initialization value for outgoing * direction. This is useful to maintain ROC after media transport * recreation such as in IP change scenario. */ - pjmedia_srtp_roc tx_roc; + pjmedia_srtp_roc tx_roc; /** * Specify SRTP callback. */ - pjmedia_srtp_cb cb; + pjmedia_srtp_cb cb; /** * Specify SRTP transport user data. */ - void *user_data; + void *user_data; } pjmedia_srtp_setting; @@ -292,37 +291,37 @@ typedef struct pjmedia_srtp_info /** * Specify whether the SRTP transport is active for SRTP session. */ - pj_bool_t active; + pj_bool_t active; /** * Specify the policy used by the SRTP session for receive direction. */ - pjmedia_srtp_crypto rx_policy; + pjmedia_srtp_crypto rx_policy; /** * Specify the policy used by the SRTP session for transmit direction. */ - pjmedia_srtp_crypto tx_policy; + pjmedia_srtp_crypto tx_policy; /** * Specify the usage policy. */ - pjmedia_srtp_use use; + pjmedia_srtp_use use; /** * Specify the peer's usage policy. */ - pjmedia_srtp_use peer_use; + pjmedia_srtp_use peer_use; /** * RTP sequence rollover counter info for incoming direction. */ - pjmedia_srtp_roc rx_roc; + pjmedia_srtp_roc rx_roc; /** * RTP sequence rollover counter info for outgoing direction. */ - pjmedia_srtp_roc tx_roc; + pjmedia_srtp_roc tx_roc; } pjmedia_srtp_info; @@ -337,24 +336,24 @@ typedef struct pjmedia_srtp_dtls_nego_param * "SHA-256/1 XX:XX:XX...". If this is not set, fingerprint verification * will not be performed. */ - pj_str_t rem_fingerprint; + pj_str_t rem_fingerprint; /** * Remote address and port. */ - pj_sockaddr rem_addr; + pj_sockaddr rem_addr; /** * Remote RTCP address and port. */ - pj_sockaddr rem_rtcp; + pj_sockaddr rem_rtcp; /** * Set to PJ_TRUE if our role is active. Active role will initiates * the DTLS negotiation. Passive role will wait for incoming DTLS * negotiation packet. */ - pj_bool_t is_role_active; + pj_bool_t is_role_active; } pjmedia_srtp_dtls_nego_param; @@ -367,9 +366,9 @@ typedef struct pjmedia_srtp_dtls_nego_param * library deinitialization to #pj_atexit(), so the deinitialization * of SRTP library will be performed automatically by PJLIB destructor. * - * @param endpt The media endpoint instance. + * @param endpt The media endpoint instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_srtp_init_lib(pjmedia_endpt *endpt); @@ -377,7 +376,7 @@ PJ_DECL(pj_status_t) pjmedia_srtp_init_lib(pjmedia_endpt *endpt); /** * Initialize SRTP setting with its default values. * - * @param opt SRTP setting to be initialized. + * @param opt SRTP setting to be initialized. */ PJ_DECL(void) pjmedia_srtp_setting_default(pjmedia_srtp_setting *opt); @@ -385,92 +384,92 @@ PJ_DECL(void) pjmedia_srtp_setting_default(pjmedia_srtp_setting *opt); /** * Enumerate available SRTP crypto name. * - * @param count On input, specifies the maximum length of crypto - * array. On output, the number of available crypto - * initialized by this function. + * @param count On input, specifies the maximum length of crypto + * array. On output, the number of available crypto + * initialized by this function. * @param crypto The SRTP crypto array output. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_srtp_enum_crypto(unsigned *count, - pjmedia_srtp_crypto crypto[]); + pjmedia_srtp_crypto crypto[]); /** * Enumerate available SRTP keying methods. * - * @param count On input, specifies the maximum length of keying method - * array. On output, the number of available keying method - * initialized by this function. + * @param count On input, specifies the maximum length of keying method + * array. On output, the number of available keying method + * initialized by this function. * @param keying The SRTP keying method array output. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_srtp_enum_keying(unsigned *count, - pjmedia_srtp_keying_method keying[]); + pjmedia_srtp_keying_method keying[]); /** * Create an SRTP media transport. * - * @param endpt The media endpoint instance. - * @param tp The actual media transport to send and receive - * RTP/RTCP packets. This media transport will be - * kept as member transport of this SRTP instance. - * @param opt Optional settings. If NULL is given, default - * settings will be used. - * @param p_tp Pointer to receive the transport SRTP instance. + * @param endpt The media endpoint instance. + * @param tp The actual media transport to send and receive + * RTP/RTCP packets. This media transport will be + * kept as member transport of this SRTP instance. + * @param opt Optional settings. If NULL is given, default + * settings will be used. + * @param p_tp Pointer to receive the transport SRTP instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_srtp_create( - pjmedia_endpt *endpt, - pjmedia_transport *tp, - const pjmedia_srtp_setting *opt, - pjmedia_transport **p_tp); + pjmedia_endpt *endpt, + pjmedia_transport *tp, + const pjmedia_srtp_setting *opt, + pjmedia_transport **p_tp); /** * Get current SRTP media transport setting. * - * @param srtp The SRTP transport. - * @param opt Structure to receive the SRTP setting + * @param srtp The SRTP transport. + * @param opt Structure to receive the SRTP setting * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_srtp_get_setting( - pjmedia_transport *srtp, - pjmedia_srtp_setting *opt); + pjmedia_transport *srtp, + pjmedia_srtp_setting *opt); /** * Modify SRTP media transport setting. * - * @param srtp The SRTP transport. - * @param opt New setting + * @param srtp The SRTP transport. + * @param opt New setting * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_srtp_modify_setting( - pjmedia_transport *srtp, - const pjmedia_srtp_setting *opt); + pjmedia_transport *srtp, + const pjmedia_srtp_setting *opt); /** * Get fingerprint of local DTLS-SRTP certificate. * - * @param srtp The SRTP transport. - * @param hash Fingerprint hash algorithm, currently valid values are - * "SHA-256" and "SHA-1". - * @param buf Buffer for fingerprint output. The output will be - * formatted as "SHA-256/1 XX:XX:XX..." and null terminated. - * @param len On input, the size of the buffer. - * On output, the length of the fingerprint. + * @param srtp The SRTP transport. + * @param hash Fingerprint hash algorithm, currently valid values are + * "SHA-256" and "SHA-1". + * @param buf Buffer for fingerprint output. The output will be + * formatted as "SHA-256/1 XX:XX:XX..." and null terminated. + * @param len On input, the size of the buffer. + * On output, the length of the fingerprint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_srtp_dtls_get_fingerprint( - pjmedia_transport *srtp, - const char *hash, - char *buf, pj_size_t *len); + pjmedia_transport *srtp, + const char *hash, + char *buf, pj_size_t *len); /** @@ -489,14 +488,14 @@ PJ_DECL(pj_status_t) pjmedia_transport_srtp_dtls_get_fingerprint( * should only call this function after ICE negotiation is completed * successfully. * - * @param srtp The SRTP transport. - * @param param DTLS-SRTP nego parameter. + * @param srtp The SRTP transport. + * @param param DTLS-SRTP nego parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_srtp_dtls_start_nego( - pjmedia_transport *srtp, - const pjmedia_srtp_dtls_nego_param *param); + pjmedia_transport *srtp, + const pjmedia_srtp_dtls_nego_param *param); /** @@ -513,23 +512,23 @@ PJ_DECL(pj_status_t) pjmedia_transport_srtp_dtls_start_nego( * If application specifies the crypto keys, the keys for transmit and receive * direction MUST be different. * - * @param srtp The SRTP transport. - * @param tx Crypto suite setting for transmit direction. - * @param rx Crypto suite setting for receive direction. + * @param srtp The SRTP transport. + * @param tx Crypto suite setting for transmit direction. + * @param rx Crypto suite setting for receive direction. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_srtp_start( - pjmedia_transport *srtp, - const pjmedia_srtp_crypto *tx, - const pjmedia_srtp_crypto *rx); + pjmedia_transport *srtp, + const pjmedia_srtp_crypto *tx, + const pjmedia_srtp_crypto *rx); /** * Stop SRTP session. * - * @param srtp The SRTP media transport. + * @param srtp The SRTP media transport. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. * * @see #pjmedia_transport_srtp_start() */ @@ -543,32 +542,32 @@ PJ_DECL(pj_status_t) pjmedia_transport_srtp_stop(pjmedia_transport *srtp); * without having to use the transport framework. See pcaputil.c in the * samples collection on how to use this function. * - * @param tp The SRTP transport. - * @param is_rtp Set to non-zero if the packet is SRTP, otherwise set - * to zero if the packet is SRTCP. - * @param pkt On input, it contains SRTP or SRTCP packet. On - * output, it contains the decrypted RTP/RTCP packet. - * @param pkt_len On input, specify the length of the buffer. On - * output, it will be filled with the actual length - * of decrypted packet. + * @param tp The SRTP transport. + * @param is_rtp Set to non-zero if the packet is SRTP, otherwise set + * to zero if the packet is SRTCP. + * @param pkt On input, it contains SRTP or SRTCP packet. On + * output, it contains the decrypted RTP/RTCP packet. + * @param pkt_len On input, specify the length of the buffer. On + * output, it will be filled with the actual length + * of decrypted packet. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_srtp_decrypt_pkt(pjmedia_transport *tp, - pj_bool_t is_rtp, - void *pkt, - int *pkt_len); + pj_bool_t is_rtp, + void *pkt, + int *pkt_len); /** * Query member transport of SRTP. * - * @param srtp The SRTP media transport. + * @param srtp The SRTP media transport. * - * @return member media transport. + * @return member media transport. */ PJ_DECL(pjmedia_transport*) pjmedia_transport_srtp_get_member( - pjmedia_transport *srtp); + pjmedia_transport *srtp); PJ_END_DECL diff --git a/pjmedia/include/pjmedia/transport_udp.h b/pjmedia/include/pjmedia/transport_udp.h index 308ef4edb6..5d37fc95dd 100644 --- a/pjmedia/include/pjmedia/transport_udp.h +++ b/pjmedia/include/pjmedia/transport_udp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -64,89 +63,89 @@ enum pjmedia_transport_udp_options * Create an RTP and RTCP sockets and bind the sockets to the specified * port to create media transport. * - * @param endpt The media endpoint instance. - * @param name Optional name to be assigned to the transport. - * @param port UDP port number for the RTP socket. The RTCP port number - * will be set to one above RTP port. + * @param endpt The media endpoint instance. + * @param name Optional name to be assigned to the transport. + * @param port UDP port number for the RTP socket. The RTCP port number + * will be set to one above RTP port. * @param options Options, bitmask of #pjmedia_transport_udp_options. - * @param p_tp Pointer to receive the transport instance. + * @param p_tp Pointer to receive the transport instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_udp_create(pjmedia_endpt *endpt, - const char *name, - int port, - unsigned options, - pjmedia_transport **p_tp); + const char *name, + int port, + unsigned options, + pjmedia_transport **p_tp); /** * Create an RTP and RTCP sockets and bind the sockets to the specified * address and port to create media transport. * - * @param endpt The media endpoint instance. - * @param name Optional name to be assigned to the transport. - * @param addr Optional local address to bind the sockets to. If this - * argument is NULL or empty, the sockets will be bound - * to all interface. - * @param port UDP port number for the RTP socket. The RTCP port number - * will be set to one above RTP port. + * @param endpt The media endpoint instance. + * @param name Optional name to be assigned to the transport. + * @param addr Optional local address to bind the sockets to. If this + * argument is NULL or empty, the sockets will be bound + * to all interface. + * @param port UDP port number for the RTP socket. The RTCP port number + * will be set to one above RTP port. * @param options Options, bitmask of #pjmedia_transport_udp_options. - * @param p_tp Pointer to receive the transport instance. + * @param p_tp Pointer to receive the transport instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_udp_create2(pjmedia_endpt *endpt, - const char *name, - const pj_str_t *addr, - int port, - unsigned options, - pjmedia_transport **p_tp); + const char *name, + const pj_str_t *addr, + int port, + unsigned options, + pjmedia_transport **p_tp); /** * Another variant of #pjmedia_transport_udp_create() which allows * the creation of IPv6 transport. * - * @param endpt The media endpoint instance. - * @param af Address family, which can be pj_AF_INET() for IPv4 or - * pj_AF_INET6() for IPv6. - * @param name Optional name to be assigned to the transport. - * @param addr Optional local address to bind the sockets to. If this - * argument is NULL or empty, the sockets will be bound - * to all interface. - * @param port UDP port number for the RTP socket. The RTCP port number - * will be set to one above RTP port. + * @param endpt The media endpoint instance. + * @param af Address family, which can be pj_AF_INET() for IPv4 or + * pj_AF_INET6() for IPv6. + * @param name Optional name to be assigned to the transport. + * @param addr Optional local address to bind the sockets to. If this + * argument is NULL or empty, the sockets will be bound + * to all interface. + * @param port UDP port number for the RTP socket. The RTCP port number + * will be set to one above RTP port. * @param options Options, bitmask of #pjmedia_transport_udp_options. - * @param p_tp Pointer to receive the transport instance. + * @param p_tp Pointer to receive the transport instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_udp_create3(pjmedia_endpt *endpt, - int af, - const char *name, - const pj_str_t *addr, - int port, - unsigned options, - pjmedia_transport **p_tp); + int af, + const char *name, + const pj_str_t *addr, + int port, + unsigned options, + pjmedia_transport **p_tp); /** * Create UDP stream transport from existing sockets. Use this function when * the sockets have previously been created. * - * @param endpt The media endpoint instance. - * @param name Optional name to be assigned to the transport. - * @param si Media socket info containing the RTP and RTCP sockets. + * @param endpt The media endpoint instance. + * @param name Optional name to be assigned to the transport. + * @param si Media socket info containing the RTP and RTCP sockets. * @param options Options, bitmask of #pjmedia_transport_udp_options. - * @param p_tp Pointer to receive the transport instance. + * @param p_tp Pointer to receive the transport instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_transport_udp_attach(pjmedia_endpt *endpt, - const char *name, - const pjmedia_sock_info *si, - unsigned options, - pjmedia_transport **p_tp); + const char *name, + const pjmedia_sock_info *si, + unsigned options, + pjmedia_transport **p_tp); PJ_END_DECL @@ -157,6 +156,6 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_TRANSPORT_UDP_H__ */ +#endif /* __PJMEDIA_TRANSPORT_UDP_H__ */ diff --git a/pjmedia/include/pjmedia/types.h b/pjmedia/include/pjmedia/types.h index 266154baac..8ff724b5f4 100644 --- a/pjmedia/include/pjmedia/types.h +++ b/pjmedia/include/pjmedia/types.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -79,58 +78,58 @@ typedef enum pjmedia_tp_proto /* Basic transports */ /** No transport type */ - PJMEDIA_TP_PROTO_NONE = 0, + PJMEDIA_TP_PROTO_NONE = 0, /** Transport unknown */ - PJMEDIA_TP_PROTO_UNKNOWN = (1 << 0), + PJMEDIA_TP_PROTO_UNKNOWN = (1 << 0), /** UDP transport */ - PJMEDIA_TP_PROTO_UDP = (1 << 1), + PJMEDIA_TP_PROTO_UDP = (1 << 1), /** RTP transport */ - PJMEDIA_TP_PROTO_RTP = (1 << 2), + PJMEDIA_TP_PROTO_RTP = (1 << 2), /** DTLS transport */ - PJMEDIA_TP_PROTO_DTLS = (1 << 3), + PJMEDIA_TP_PROTO_DTLS = (1 << 3), /* Basic profiles */ /** RTCP Feedback profile */ - PJMEDIA_TP_PROFILE_RTCP_FB = (1 << 13), + PJMEDIA_TP_PROFILE_RTCP_FB = (1 << 13), /** Secure RTP profile */ - PJMEDIA_TP_PROFILE_SRTP = (1 << 14), + PJMEDIA_TP_PROFILE_SRTP = (1 << 14), /** Audio/video profile */ - PJMEDIA_TP_PROFILE_AVP = (1 << 15), + PJMEDIA_TP_PROFILE_AVP = (1 << 15), /* Predefined transport profiles (commonly used) */ /** RTP using A/V profile */ - PJMEDIA_TP_PROTO_RTP_AVP = (PJMEDIA_TP_PROTO_RTP | - PJMEDIA_TP_PROFILE_AVP), + PJMEDIA_TP_PROTO_RTP_AVP = (PJMEDIA_TP_PROTO_RTP | + PJMEDIA_TP_PROFILE_AVP), /** Secure RTP using A/V profile */ - PJMEDIA_TP_PROTO_RTP_SAVP = (PJMEDIA_TP_PROTO_RTP_AVP | - PJMEDIA_TP_PROFILE_SRTP), + PJMEDIA_TP_PROTO_RTP_SAVP = (PJMEDIA_TP_PROTO_RTP_AVP | + PJMEDIA_TP_PROFILE_SRTP), /** Secure RTP using A/V profile and DTLS-SRTP keying */ - PJMEDIA_TP_PROTO_DTLS_SRTP = (PJMEDIA_TP_PROTO_DTLS | - PJMEDIA_TP_PROTO_RTP_SAVP), + PJMEDIA_TP_PROTO_DTLS_SRTP = (PJMEDIA_TP_PROTO_DTLS | + PJMEDIA_TP_PROTO_RTP_SAVP), /** RTP using A/V and RTCP feedback profile */ - PJMEDIA_TP_PROTO_RTP_AVPF = (PJMEDIA_TP_PROTO_RTP_AVP | - PJMEDIA_TP_PROFILE_RTCP_FB), + PJMEDIA_TP_PROTO_RTP_AVPF = (PJMEDIA_TP_PROTO_RTP_AVP | + PJMEDIA_TP_PROFILE_RTCP_FB), /** Secure RTP using A/V and RTCP feedback profile */ - PJMEDIA_TP_PROTO_RTP_SAVPF = (PJMEDIA_TP_PROTO_RTP_SAVP | - PJMEDIA_TP_PROFILE_RTCP_FB), + PJMEDIA_TP_PROTO_RTP_SAVPF = (PJMEDIA_TP_PROTO_RTP_SAVP | + PJMEDIA_TP_PROFILE_RTCP_FB), /** Secure RTP using A/V and RTCP feedback profile and DTLS-SRTP keying */ - PJMEDIA_TP_PROTO_DTLS_SRTPF = (PJMEDIA_TP_PROTO_DTLS_SRTP | - PJMEDIA_TP_PROFILE_RTCP_FB), + PJMEDIA_TP_PROTO_DTLS_SRTPF = (PJMEDIA_TP_PROTO_DTLS_SRTP | + PJMEDIA_TP_PROFILE_RTCP_FB), } pjmedia_tp_proto; @@ -139,7 +138,7 @@ typedef enum pjmedia_tp_proto * transport and profile flags. */ #define PJMEDIA_TP_PROTO_HAS_FLAG(TP_PROTO, FLAGS) \ - (((TP_PROTO) & (FLAGS)) == (FLAGS)) + (((TP_PROTO) & (FLAGS)) == (FLAGS)) /** * Macro helper for excluding specific flags in transport protocol. @@ -215,8 +214,8 @@ typedef enum pjmedia_coord_base */ typedef struct pjmedia_ratio { - int num; /** < Numerator. */ - int denum; /** < Denumerator. */ + int num; /** < Numerator. */ + int denum; /** < Denumerator. */ } pjmedia_ratio; /** @@ -224,8 +223,8 @@ typedef struct pjmedia_ratio */ typedef struct pjmedia_coord { - int x; /**< X position of the coordinate */ - int y; /**< Y position of the coordinate */ + int x; /**< X position of the coordinate */ + int y; /**< Y position of the coordinate */ } pjmedia_coord; /** @@ -233,8 +232,8 @@ typedef struct pjmedia_coord */ typedef struct pjmedia_rect_size { - unsigned w; /**< The width. */ - unsigned h; /**< The height. */ + unsigned w; /**< The width. */ + unsigned h; /**< The height. */ } pjmedia_rect_size; /** @@ -242,8 +241,8 @@ typedef struct pjmedia_rect_size */ typedef struct pjmedia_rect { - pjmedia_coord coord; /**< The position. */ - pjmedia_rect_size size; /**< The size. */ + pjmedia_coord coord; /**< The position. */ + pjmedia_rect_size size; /**< The size. */ } pjmedia_rect; /** @@ -300,9 +299,9 @@ typedef enum pjmedia_orient /** * Utility function to return the string name for a pjmedia_type. * - * @param t The media type. + * @param t The media type. * - * @return String. + * @return String. */ PJ_DECL(const char*) pjmedia_type_name(pjmedia_type t); @@ -310,9 +309,9 @@ PJ_DECL(const char*) pjmedia_type_name(pjmedia_type t); /** * Utility function to return the media type for a media name string. * - * @param name The media name string. + * @param name The media name string. * - * @return media type. + * @return media type. */ PJ_DECL(pjmedia_type) pjmedia_get_type(const pj_str_t *name); @@ -320,11 +319,11 @@ PJ_DECL(pjmedia_type) pjmedia_get_type(const pj_str_t *name); /** * A utility function to convert fourcc type of value to four letters string. * - * @param sig The fourcc value. - * @param buf Buffer to store the string, which MUST be at least - * five bytes long. + * @param sig The fourcc value. + * @param buf Buffer to store the string, which MUST be at least + * five bytes long. * - * @return The string. + * @return The string. */ PJ_INLINE(const char*) pjmedia_fourcc_name(pj_uint32_t sig, char buf[]) { @@ -342,5 +341,5 @@ PJ_INLINE(const char*) pjmedia_fourcc_name(pj_uint32_t sig, char buf[]) */ -#endif /* __PJMEDIA_TYPES_H__ */ +#endif /* __PJMEDIA_TYPES_H__ */ diff --git a/pjmedia/include/pjmedia/vid_codec.h b/pjmedia/include/pjmedia/vid_codec.h index 46f7dddf8b..340c6e1309 100644 --- a/pjmedia/include/pjmedia/vid_codec.h +++ b/pjmedia/include/pjmedia/vid_codec.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -86,7 +85,7 @@ typedef enum pjmedia_vid_frm_bit_info /** * The video frame is keyframe. */ - PJMEDIA_VID_FRM_KEYFRAME = 1 + PJMEDIA_VID_FRM_KEYFRAME = 1 } pjmedia_vid_frm_bit_info; @@ -114,23 +113,23 @@ typedef struct pjmedia_vid_encode_opt typedef struct pjmedia_vid_codec_info { pjmedia_format_id fmt_id; /**< Encoded format ID */ - unsigned pt; /**< Payload type */ - pj_str_t encoding_name; /**< Encoding name */ - pj_str_t encoding_desc; /**< Encoding desc */ - unsigned clock_rate; /**< Clock rate */ + unsigned pt; /**< Payload type */ + pj_str_t encoding_name; /**< Encoding name */ + pj_str_t encoding_desc; /**< Encoding desc */ + unsigned clock_rate; /**< Clock rate */ pjmedia_dir dir; /**< Direction */ unsigned dec_fmt_id_cnt; /**< # of supported encoding source format IDs */ pjmedia_format_id dec_fmt_id[PJMEDIA_VID_CODEC_MAX_DEC_FMT_CNT]; /**< Supported encoding source format IDs */ - unsigned packings; /**< Supported or requested packings, - strategies, bitmask from - pjmedia_vid_packing */ + unsigned packings; /**< Supported or requested packings, + strategies, bitmask from + pjmedia_vid_packing */ unsigned fps_cnt; /**< # of supported frame-rates, can be - zero (support any frame-rate) */ + zero (support any frame-rate) */ pjmedia_ratio fps[PJMEDIA_VID_CODEC_MAX_FPS_CNT]; - /**< Supported frame-rates */ + /**< Supported frame-rates */ } pjmedia_vid_codec_info; @@ -148,19 +147,19 @@ typedef struct pjmedia_vid_codec_info typedef struct pjmedia_vid_codec_param { pjmedia_dir dir; /**< Direction */ - pjmedia_vid_packing packing; /**< Packetization strategy. */ + pjmedia_vid_packing packing; /**< Packetization strategy. */ - pjmedia_format enc_fmt; /**< Encoded format */ - pjmedia_codec_fmtp enc_fmtp; /**< Encoder fmtp params */ + pjmedia_format enc_fmt; /**< Encoded format */ + pjmedia_codec_fmtp enc_fmtp; /**< Encoder fmtp params */ unsigned enc_mtu; /**< MTU or max payload size setting*/ - pjmedia_format dec_fmt; /**< Decoded format */ - pjmedia_codec_fmtp dec_fmtp; /**< Decoder fmtp params */ + pjmedia_format dec_fmt; /**< Decoded format */ + pjmedia_codec_fmtp dec_fmtp; /**< Decoder fmtp params */ - pj_bool_t ignore_fmtp; /**< Ignore fmtp params. If set to - PJ_TRUE, the codec will apply - format settings specified in - enc_fmt and dec_fmt only. */ + pj_bool_t ignore_fmtp; /**< Ignore fmtp params. If set to + PJ_TRUE, the codec will apply + format settings specified in + enc_fmt and dec_fmt only. */ } pjmedia_vid_codec_param; @@ -168,14 +167,14 @@ typedef struct pjmedia_vid_codec_param /** * Duplicate video codec parameter. * - * @param pool The pool. - * @param src The video codec parameter to be duplicated. + * @param pool The pool. + * @param src The video codec parameter to be duplicated. * - * @return Duplicated codec parameter. + * @return Duplicated codec parameter. */ PJ_DECL(pjmedia_vid_codec_param*) pjmedia_vid_codec_param_clone( - pj_pool_t *pool, - const pjmedia_vid_codec_param *src); + pj_pool_t *pool, + const pjmedia_vid_codec_param *src); /** * Forward declaration for video codec. @@ -192,14 +191,14 @@ typedef struct pjmedia_vid_codec_op /** * See #pjmedia_vid_codec_init(). */ - pj_status_t (*init)(pjmedia_vid_codec *codec, - pj_pool_t *pool ); + pj_status_t (*init)(pjmedia_vid_codec *codec, + pj_pool_t *pool ); /** * See #pjmedia_vid_codec_open(). */ - pj_status_t (*open)(pjmedia_vid_codec *codec, - pjmedia_vid_codec_param *param ); + pj_status_t (*open)(pjmedia_vid_codec *codec, + pjmedia_vid_codec_param *param ); /** * See #pjmedia_vid_codec_close(). @@ -209,49 +208,49 @@ typedef struct pjmedia_vid_codec_op /** * See #pjmedia_vid_codec_modify(). */ - pj_status_t (*modify)(pjmedia_vid_codec *codec, - const pjmedia_vid_codec_param *param); + pj_status_t (*modify)(pjmedia_vid_codec *codec, + const pjmedia_vid_codec_param *param); /** * See #pjmedia_vid_codec_get_param(). */ - pj_status_t (*get_param)(pjmedia_vid_codec *codec, - pjmedia_vid_codec_param *param); + pj_status_t (*get_param)(pjmedia_vid_codec *codec, + pjmedia_vid_codec_param *param); /** * See #pjmedia_vid_codec_encode_begin(). */ pj_status_t (*encode_begin)(pjmedia_vid_codec *codec, - const pjmedia_vid_encode_opt *opt, - const pjmedia_frame *input, - unsigned out_size, - pjmedia_frame *output, - pj_bool_t *has_more); + const pjmedia_vid_encode_opt *opt, + const pjmedia_frame *input, + unsigned out_size, + pjmedia_frame *output, + pj_bool_t *has_more); /** * See #pjmedia_vid_codec_encode_more() */ pj_status_t (*encode_more)(pjmedia_vid_codec *codec, - unsigned out_size, - pjmedia_frame *output, - pj_bool_t *has_more); + unsigned out_size, + pjmedia_frame *output, + pj_bool_t *has_more); /* * See #pjmedia_vid_codec_decode(). */ pj_status_t (*decode)(pjmedia_vid_codec *codec, - pj_size_t count, - pjmedia_frame packets[], - unsigned out_size, - pjmedia_frame *output); + pj_size_t count, + pjmedia_frame packets[], + unsigned out_size, + pjmedia_frame *output); /** * See #pjmedia_vid_codec_recover() */ pj_status_t (*recover)(pjmedia_vid_codec *codec, - unsigned out_size, - pjmedia_frame *output); + unsigned out_size, + pjmedia_frame *output); } pjmedia_vid_codec_op; @@ -274,13 +273,13 @@ struct pjmedia_vid_codec PJ_DECL_LIST_MEMBER(struct pjmedia_vid_codec); /** Codec's private data. */ - void *codec_data; + void *codec_data; /** Codec factory where this codec was allocated. */ pjmedia_vid_codec_factory *factory; /** Operations to codec. */ - pjmedia_vid_codec_op *op; + pjmedia_vid_codec_op *op; }; @@ -295,70 +294,70 @@ typedef struct pjmedia_vid_codec_factory_op * Check whether the factory can create codec with the specified * codec info. * - * @param factory The codec factory. - * @param info The codec info. + * @param factory The codec factory. + * @param info The codec info. * - * @return PJ_SUCCESS if this factory is able to create an - * instance of codec with the specified info. + * @return PJ_SUCCESS if this factory is able to create an + * instance of codec with the specified info. */ - pj_status_t (*test_alloc)(pjmedia_vid_codec_factory *factory, - const pjmedia_vid_codec_info *info ); + pj_status_t (*test_alloc)(pjmedia_vid_codec_factory *factory, + const pjmedia_vid_codec_info *info ); /** * Create default attributes for the specified codec ID. This function * can be called by application to get the capability of the codec. * - * @param factory The codec factory. - * @param info The codec info. - * @param attr The attribute to be initialized. + * @param factory The codec factory. + * @param info The codec info. + * @param attr The attribute to be initialized. * - * @return PJ_SUCCESS if success. + * @return PJ_SUCCESS if success. */ pj_status_t (*default_attr)(pjmedia_vid_codec_factory *factory, - const pjmedia_vid_codec_info *info, - pjmedia_vid_codec_param *attr ); + const pjmedia_vid_codec_info *info, + pjmedia_vid_codec_param *attr ); /** * Enumerate supported codecs that can be created using this factory. * - * @param factory The codec factory. - * @param count On input, specifies the number of elements in - * the array. On output, the value will be set to - * the number of elements that have been initialized - * by this function. - * @param info The codec info array, which contents will be - * initialized upon return. + * @param factory The codec factory. + * @param count On input, specifies the number of elements in + * the array. On output, the value will be set to + * the number of elements that have been initialized + * by this function. + * @param info The codec info array, which contents will be + * initialized upon return. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ pj_status_t (*enum_info)(pjmedia_vid_codec_factory *factory, - unsigned *count, - pjmedia_vid_codec_info codecs[]); + unsigned *count, + pjmedia_vid_codec_info codecs[]); /** * Create one instance of the codec with the specified codec info. * - * @param factory The codec factory. - * @param info The codec info. - * @param p_codec Pointer to receive the codec instance. + * @param factory The codec factory. + * @param info The codec info. + * @param p_codec Pointer to receive the codec instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ pj_status_t (*alloc_codec)(pjmedia_vid_codec_factory *factory, - const pjmedia_vid_codec_info *info, - pjmedia_vid_codec **p_codec); + const pjmedia_vid_codec_info *info, + pjmedia_vid_codec **p_codec); /** * This function is called by codec manager to return a particular * instance of codec back to the codec factory. * - * @param factory The codec factory. - * @param codec The codec instance to be returned. + * @param factory The codec factory. + * @param codec The codec instance to be returned. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ pj_status_t (*dealloc_codec)(pjmedia_vid_codec_factory *factory, - pjmedia_vid_codec *codec ); + pjmedia_vid_codec *codec ); } pjmedia_vid_codec_factory_op; @@ -375,7 +374,7 @@ struct pjmedia_vid_codec_factory PJ_DECL_LIST_MEMBER(struct pjmedia_vid_codec_factory); /** The factory's private data. */ - void *factory_data; + void *factory_data; /** Operations to the factory. */ pjmedia_vid_codec_factory_op *op; @@ -391,7 +390,7 @@ typedef struct pjmedia_vid_codec_mgr pjmedia_vid_codec_mgr; /** * Declare maximum codecs */ -#define PJMEDIA_VID_CODEC_MGR_MAX_CODECS 32 +#define PJMEDIA_VID_CODEC_MGR_MAX_CODECS 32 /** @@ -400,10 +399,10 @@ typedef struct pjmedia_vid_codec_mgr pjmedia_vid_codec_mgr; * the new codec manager instance. Normally this function is called by pjmedia * endpoint's initialization code. * - * @param pool The pool instance. - * @param mgr The pointer to the new codec manager instance. + * @param pool The pool instance. + * @param mgr The pointer to the new codec manager instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_create(pj_pool_t *pool, pjmedia_vid_codec_mgr **mgr); @@ -413,10 +412,10 @@ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_create(pj_pool_t *pool, * Destroy codec manager. Normally this function is called by pjmedia * endpoint's deinitialization code. * - * @param mgr Codec manager instance. If NULL, it is the default codec - * manager instance will be destroyed. + * @param mgr Codec manager instance. If NULL, it is the default codec + * manager instance will be destroyed. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_destroy(pjmedia_vid_codec_mgr *mgr); @@ -424,7 +423,7 @@ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_destroy(pjmedia_vid_codec_mgr *mgr); /** * Get the default codec manager instance. * - * @return The default codec manager instance or NULL if none. + * @return The default codec manager instance or NULL if none. */ PJ_DECL(pjmedia_vid_codec_mgr*) pjmedia_vid_codec_mgr_instance(void); @@ -432,7 +431,7 @@ PJ_DECL(pjmedia_vid_codec_mgr*) pjmedia_vid_codec_mgr_instance(void); /** * Set the default codec manager instance. * - * @param mgr The codec manager instance. + * @param mgr The codec manager instance. */ PJ_DECL(void) pjmedia_vid_codec_mgr_set_instance(pjmedia_vid_codec_mgr* mgr); @@ -441,85 +440,85 @@ PJ_DECL(void) pjmedia_vid_codec_mgr_set_instance(pjmedia_vid_codec_mgr* mgr); * Register codec factory to codec manager. This will also register * all supported codecs in the factory to the codec manager. * - * @param mgr The codec manager instance. If NULL, the default codec - * manager instance will be used. + * @param mgr The codec manager instance. If NULL, the default codec + * manager instance will be used. * @param factory The codec factory to be registered. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_register_factory( pjmedia_vid_codec_mgr *mgr, - pjmedia_vid_codec_factory *factory); + pjmedia_vid_codec_factory *factory); /** * Unregister codec factory from the codec manager. This will also * remove all the codecs registered by the codec factory from the * codec manager's list of supported codecs. * - * @param mgr The codec manager instance. If NULL, the default codec - * manager instance will be used. + * @param mgr The codec manager instance. If NULL, the default codec + * manager instance will be used. * @param factory The codec factory to be unregistered. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_unregister_factory( pjmedia_vid_codec_mgr *mgr, - pjmedia_vid_codec_factory *factory); + pjmedia_vid_codec_factory *factory); /** * Enumerate all supported codecs that have been registered to the * codec manager by codec factories. * - * @param mgr The codec manager instance. If NULL, the default codec - * manager instance will be used. - * @param count On input, specifies the number of elements in - * the array. On output, the value will be set to - * the number of elements that have been initialized - * by this function. - * @param info The codec info array, which contents will be - * initialized upon return. - * @param prio Optional pointer to receive array of codec priorities. + * @param mgr The codec manager instance. If NULL, the default codec + * manager instance will be used. + * @param count On input, specifies the number of elements in + * the array. On output, the value will be set to + * the number of elements that have been initialized + * by this function. + * @param info The codec info array, which contents will be + * initialized upon return. + * @param prio Optional pointer to receive array of codec priorities. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_enum_codecs(pjmedia_vid_codec_mgr *mgr, - unsigned *count, - pjmedia_vid_codec_info info[], - unsigned *prio); + unsigned *count, + pjmedia_vid_codec_info info[], + unsigned *prio); /** * Get codec info for the specified payload type. The payload type must be * static or locally defined in #pjmedia_video_pt. * - * @param mgr The codec manager instance. If NULL, the default codec - * manager instance will be used. - * @param pt The payload type/number. - * @param info Pointer to receive codec info. + * @param mgr The codec manager instance. If NULL, the default codec + * manager instance will be used. + * @param pt The payload type/number. + * @param info Pointer to receive codec info. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_get_codec_info( pjmedia_vid_codec_mgr *mgr, - unsigned pt, - const pjmedia_vid_codec_info **info); + unsigned pt, + const pjmedia_vid_codec_info **info); /** * Get codec info for the specified format ID. * - * @param mgr The codec manager instance. If NULL, the default codec - * manager instance will be used. + * @param mgr The codec manager instance. If NULL, the default codec + * manager instance will be used. * @param fmt_id Format ID. See #pjmedia_format_id - * @param info Pointer to receive codec info. + * @param info Pointer to receive codec info. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_get_codec_info2(pjmedia_vid_codec_mgr *mgr, - pjmedia_format_id fmt_id, - const pjmedia_vid_codec_info **info); + pjmedia_format_id fmt_id, + const pjmedia_vid_codec_info **info); /** @@ -527,12 +526,12 @@ pjmedia_vid_codec_mgr_get_codec_info2(pjmedia_vid_codec_mgr *mgr, * A codec identifier looks something like "H263/34", where "H263" is the * codec name and "34" is the (default) payload type. * - * @param info The codec info - * @param id Buffer to put the codec info string. + * @param info The codec info + * @param id Buffer to put the codec info string. * @param max_len The length of the buffer. * - * @return The null terminated codec info string, or NULL if - * the buffer is not long enough. + * @return The null terminated codec info string, or NULL if + * the buffer is not long enough. */ PJ_DECL(char*) pjmedia_vid_codec_info_to_id(const pjmedia_vid_codec_info *info, char *id, unsigned max_len ); @@ -544,25 +543,25 @@ PJ_DECL(char*) pjmedia_vid_codec_info_to_id(const pjmedia_vid_codec_info *info, * "H26" is specified, then it will find "H263", "H264", and so on, * up to the maximum count specified in the argument. * - * @param mgr The codec manager instance. If NULL, the default codec - * manager instance will be used. + * @param mgr The codec manager instance. If NULL, the default codec + * manager instance will be used. * @param codec_id The full codec ID or codec ID prefix. If an empty - * string is given, it will match all codecs. - * @param count Maximum number of codecs to find. On return, it - * contains the actual number of codecs found. + * string is given, it will match all codecs. + * @param count Maximum number of codecs to find. On return, it + * contains the actual number of codecs found. * @param p_info Array of pointer to codec info to be filled. This - * argument may be NULL, which in this case, only - * codec count will be returned. - * @param prio Optional array of codec priorities. + * argument may be NULL, which in this case, only + * codec count will be returned. + * @param prio Optional array of codec priorities. * - * @return PJ_SUCCESS if at least one codec info is found. + * @return PJ_SUCCESS if at least one codec info is found. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_find_codecs_by_id(pjmedia_vid_codec_mgr *mgr, - const pj_str_t *codec_id, - unsigned *count, - const pjmedia_vid_codec_info *p_info[], - unsigned prio[]); + const pj_str_t *codec_id, + unsigned *count, + const pjmedia_vid_codec_info *p_info[], + unsigned prio[]); /** @@ -571,56 +570,56 @@ pjmedia_vid_codec_mgr_find_codecs_by_id(pjmedia_vid_codec_mgr *mgr, * are found with the same codec_id prefix, then the function sets the * priorities of all those codecs. * - * @param mgr The codec manager instance. If NULL, the default codec - * manager instance will be used. + * @param mgr The codec manager instance. If NULL, the default codec + * manager instance will be used. * @param codec_id The full codec ID or codec ID prefix. If an empty - * string is given, it will match all codecs. - * @param prio Priority to be set. The priority can have any value - * between 1 to 255. When the priority is set to zero, - * the codec will be disabled. + * string is given, it will match all codecs. + * @param prio Priority to be set. The priority can have any value + * between 1 to 255. When the priority is set to zero, + * the codec will be disabled. * - * @return PJ_SUCCESS if at least one codec info is found. + * @return PJ_SUCCESS if at least one codec info is found. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_set_codec_priority(pjmedia_vid_codec_mgr *mgr, - const pj_str_t *codec_id, - pj_uint8_t prio); + const pj_str_t *codec_id, + pj_uint8_t prio); /** * Get default codec param for the specified codec info. * - * @param mgr The codec manager instance. If NULL, the default codec - * manager instance will be used. - * @param info The codec info, which default parameter's is being - * queried. - * @param param On return, will be filled with the default codec - * parameter. + * @param mgr The codec manager instance. If NULL, the default codec + * manager instance will be used. + * @param info The codec info, which default parameter's is being + * queried. + * @param param On return, will be filled with the default codec + * parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_get_default_param(pjmedia_vid_codec_mgr *mgr, - const pjmedia_vid_codec_info *info, - pjmedia_vid_codec_param *param); + const pjmedia_vid_codec_info *info, + pjmedia_vid_codec_param *param); /** * Set default codec param for the specified codec info. * - * @param mgr The codec manager instance. If NULL, the default codec - * manager instance will be used. - * @param info The codec info, which default parameter's is being - * updated. - * @param param The new default codec parameter. Set to NULL to reset - * codec parameter to library default settings. + * @param mgr The codec manager instance. If NULL, the default codec + * manager instance will be used. + * @param info The codec info, which default parameter's is being + * updated. + * @param param The new default codec parameter. Set to NULL to reset + * codec parameter to library default settings. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_set_default_param(pjmedia_vid_codec_mgr *mgr, - const pjmedia_vid_codec_info *info, - const pjmedia_vid_codec_param *param); + const pjmedia_vid_codec_info *info, + const pjmedia_vid_codec_param *param); /** @@ -628,45 +627,45 @@ pjmedia_vid_codec_mgr_set_default_param(pjmedia_vid_codec_mgr *mgr, * specified codec info. The codec will enumerate all codec factories * until it finds factory that is able to create the specified codec. * - * @param mgr The codec manager instance. If NULL, the default codec - * manager instance will be used. - * @param info The information about the codec to be created. + * @param mgr The codec manager instance. If NULL, the default codec + * manager instance will be used. + * @param info The information about the codec to be created. * @param p_codec Pointer to receive the codec instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_alloc_codec( pjmedia_vid_codec_mgr *mgr, - const pjmedia_vid_codec_info *info, - pjmedia_vid_codec **p_codec); + const pjmedia_vid_codec_info *info, + pjmedia_vid_codec **p_codec); /** * Deallocate the specified codec instance. The codec manager will return * the instance of the codec back to its factory. * - * @param mgr The codec manager instance. If NULL, the default codec - * manager instance will be used. - * @param codec The codec instance. + * @param mgr The codec manager instance. If NULL, the default codec + * manager instance will be used. + * @param codec The codec instance. * - * @return PJ_SUCESS on success. + * @return PJ_SUCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_mgr_dealloc_codec( pjmedia_vid_codec_mgr *mgr, - pjmedia_vid_codec *codec); + pjmedia_vid_codec *codec); /** * Initialize codec using the specified attribute. * - * @param codec The codec instance. - * @param pool Pool to use when the codec needs to allocate - * some memory. + * @param codec The codec instance. + * @param pool Pool to use when the codec needs to allocate + * some memory. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_vid_codec_init( pjmedia_vid_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { return (*codec->op->init)(codec, pool); } @@ -679,10 +678,10 @@ PJ_INLINE(pj_status_t) pjmedia_vid_codec_init( pjmedia_vid_codec *codec, * the encoder format, as it may need to be negotiated with remote * preferences via SDP fmtp). * - * @param codec The codec instance. - * @param param Codec initialization parameter. + * @param codec The codec instance. + * @param param Codec initialization parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_vid_codec_open(pjmedia_vid_codec *codec, pjmedia_vid_codec_param *param) @@ -695,9 +694,9 @@ PJ_INLINE(pj_status_t) pjmedia_vid_codec_open(pjmedia_vid_codec *codec, * Close and shutdown codec, releasing all resources allocated by * this codec, if any. * - * @param codec The codec instance. + * @param codec The codec instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_vid_codec_close( pjmedia_vid_codec *codec ) { @@ -711,10 +710,10 @@ PJ_INLINE(pj_status_t) pjmedia_vid_codec_close( pjmedia_vid_codec *codec ) * When the parameter cannot be changed, this function will return * non-PJ_SUCCESS, and the original parameters will not be changed. * - * @param codec The codec instance. - * @param param The new codec parameter. + * @param codec The codec instance. + * @param param The new codec parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_vid_codec_modify(pjmedia_vid_codec *codec, @@ -727,14 +726,14 @@ pjmedia_vid_codec_modify(pjmedia_vid_codec *codec, /** * Get the codec parameter after the codec is opened. * - * @param codec The codec instance. - * @param param The codec parameter. + * @param codec The codec instance. + * @param param The codec parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_INLINE(pj_status_t) pjmedia_vid_codec_get_param(pjmedia_vid_codec *codec, - pjmedia_vid_codec_param *param) + pjmedia_vid_codec_param *param) { return (*codec->op->get_param)(codec, param); } @@ -749,29 +748,29 @@ pjmedia_vid_codec_get_param(pjmedia_vid_codec *codec, * call pjmedia_vid_codec_encode_more() to get the remaining results from the * codec. * - * @param codec The codec instance. - * @param opt Optional encoding options. - * @param input The input frame. - * @param out_size The length of buffer in the output frame. This - * should be at least the same as the configured - * encoding MTU of the codec. - * @param output The output frame. - * @param has_more PJ_TRUE if more payloads are available; application - * should then call pjmedia_vid_codec_encode_more() - * to retrieve the remaining results. + * @param codec The codec instance. + * @param opt Optional encoding options. + * @param input The input frame. + * @param out_size The length of buffer in the output frame. This + * should be at least the same as the configured + * encoding MTU of the codec. + * @param output The output frame. + * @param has_more PJ_TRUE if more payloads are available; application + * should then call pjmedia_vid_codec_encode_more() + * to retrieve the remaining results. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ PJ_INLINE(pj_status_t) pjmedia_vid_codec_encode_begin( pjmedia_vid_codec *codec, - const pjmedia_vid_encode_opt *opt, - const pjmedia_frame *input, - unsigned out_size, - pjmedia_frame *output, - pj_bool_t *has_more) + const pjmedia_vid_encode_opt *opt, + const pjmedia_frame *input, + unsigned out_size, + pjmedia_frame *output, + pj_bool_t *has_more) { return (*codec->op->encode_begin)(codec, opt, input, out_size, output, - has_more); + has_more); } /** @@ -779,22 +778,22 @@ pjmedia_vid_codec_encode_begin( pjmedia_vid_codec *codec, * should call this function repeatedly until \a has_more flag is set * to PJ_FALSE. * - * @param codec The codec instance. - * @param out_size The length of buffer in the output frame. This - * should be at least the same as as the configured - * encoding MTU of the codec. - * @param output The output frame. - * @param has_more PJ_TRUE if more payloads are available, which in - * this case application should call \a encode_more() - * to retrieve them. + * @param codec The codec instance. + * @param out_size The length of buffer in the output frame. This + * should be at least the same as as the configured + * encoding MTU of the codec. + * @param output The output frame. + * @param has_more PJ_TRUE if more payloads are available, which in + * this case application should call \a encode_more() + * to retrieve them. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ PJ_INLINE(pj_status_t) pjmedia_vid_codec_encode_more( pjmedia_vid_codec *codec, - unsigned out_size, - pjmedia_frame *output, - pj_bool_t *has_more) + unsigned out_size, + pjmedia_frame *output, + pj_bool_t *has_more) { return (*codec->op->encode_more)(codec, out_size, output, has_more); } @@ -814,20 +813,20 @@ pjmedia_vid_codec_encode_more( pjmedia_vid_codec *codec, * also be updated, and application can query the format by using * pjmedia_vid_codec_get_param(). * - * @param codec The codec instance. - * @param pkt_count Number of packets in the input. - * @param packets Array of input packets, each containing an encoded - * frame. - * @param out_size The length of buffer in the output frame. - * @param output The output frame. + * @param codec The codec instance. + * @param pkt_count Number of packets in the input. + * @param packets Array of input packets, each containing an encoded + * frame. + * @param out_size The length of buffer in the output frame. + * @param output The output frame. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ PJ_INLINE(pj_status_t) pjmedia_vid_codec_decode(pjmedia_vid_codec *codec, - pj_size_t pkt_count, - pjmedia_frame packets[], - unsigned out_size, - pjmedia_frame *output) + pj_size_t pkt_count, + pjmedia_frame packets[], + unsigned out_size, + pjmedia_frame *output) { return (*codec->op->decode)(codec, pkt_count, packets, out_size, output); } @@ -835,21 +834,21 @@ PJ_INLINE(pj_status_t) pjmedia_vid_codec_decode(pjmedia_vid_codec *codec, /** * Recover a missing frame. * - * @param codec The codec instance. - * @param out_size The length of buffer in the output frame. - * @param output The output frame where generated signal - * will be placed. + * @param codec The codec instance. + * @param out_size The length of buffer in the output frame. + * @param output The output frame where generated signal + * will be placed. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ PJ_INLINE(pj_status_t) pjmedia_vid_codec_recover(pjmedia_vid_codec *codec, unsigned out_size, pjmedia_frame *output) { if (codec->op && codec->op->recover) - return (*codec->op->recover)(codec, out_size, output); + return (*codec->op->recover)(codec, out_size, output); else - return PJ_ENOTSUP; + return PJ_ENOTSUP; } @@ -868,4 +867,4 @@ PJ_INLINE(pj_status_t) pjmedia_vid_codec_recover(pjmedia_vid_codec *codec, PJ_END_DECL -#endif /* __PJMEDIA_VID_CODEC_H__ */ +#endif /* __PJMEDIA_VID_CODEC_H__ */ diff --git a/pjmedia/include/pjmedia/vid_codec_util.h b/pjmedia/include/pjmedia/vid_codec_util.h index e09475fc3c..5910ed0b4d 100644 --- a/pjmedia/include/pjmedia/vid_codec_util.h +++ b/pjmedia/include/pjmedia/vid_codec_util.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -37,11 +36,11 @@ PJ_BEGIN_DECL */ typedef struct pjmedia_vid_codec_h263_fmtp { - unsigned mpi_cnt; /**< # of parsed MPI param */ + unsigned mpi_cnt; /**< # of parsed MPI param */ struct mpi { - pjmedia_rect_size size; /**< Picture size/resolution */ - unsigned val; /**< MPI value */ - } mpi[32]; /**< Minimum Picture Interval parameter */ + pjmedia_rect_size size; /**< Picture size/resolution */ + unsigned val; /**< MPI value */ + } mpi[32]; /**< Minimum Picture Interval parameter */ } pjmedia_vid_codec_h263_fmtp; @@ -49,26 +48,26 @@ typedef struct pjmedia_vid_codec_h263_fmtp /** * Parse SDP fmtp of H.263. * - * @param fmtp The H.263 SDP fmtp to be parsed. - * @param h263_fmtp The parsing result. + * @param fmtp The H.263 SDP fmtp to be parsed. + * @param h263_fmtp The parsing result. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_h263_parse_fmtp( - const pjmedia_codec_fmtp *fmtp, - pjmedia_vid_codec_h263_fmtp *h263_fmtp); + const pjmedia_codec_fmtp *fmtp, + pjmedia_vid_codec_h263_fmtp *h263_fmtp); /** * Parse, negotiate, and apply the encoding and decoding SDP fmtp of H.263 * in the specified codec parameter. * - * @param param The codec parameter. + * @param param The codec parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_h263_apply_fmtp( - pjmedia_vid_codec_param *param); + pjmedia_vid_codec_param *param); /** @@ -77,24 +76,24 @@ PJ_DECL(pj_status_t) pjmedia_vid_codec_h263_apply_fmtp( typedef struct pjmedia_vid_codec_h264_fmtp { /* profile-level-id */ - pj_uint8_t profile_idc; /**< Profile ID */ - pj_uint8_t profile_iop; /**< Profile constraints bits */ - pj_uint8_t level; /**< Level */ + pj_uint8_t profile_idc; /**< Profile ID */ + pj_uint8_t profile_iop; /**< Profile constraints bits */ + pj_uint8_t level; /**< Level */ /* packetization-mode */ - pj_uint8_t packetization_mode; /**< Packetization mode */ + pj_uint8_t packetization_mode; /**< Packetization mode */ /* max-mbps, max-fs, max-cpb, max-dpb, and max-br */ - unsigned max_mbps; /**< Max macroblock processing rate */ - unsigned max_fs; /**< Max frame size (in macroblocks) */ - unsigned max_cpb; /**< Max coded picture buffer size */ - unsigned max_dpb; /**< Max decoded picture buffer size */ - unsigned max_br; /**< Max video bit rate */ + unsigned max_mbps; /**< Max macroblock processing rate */ + unsigned max_fs; /**< Max frame size (in macroblocks) */ + unsigned max_cpb; /**< Max coded picture buffer size */ + unsigned max_dpb; /**< Max decoded picture buffer size */ + unsigned max_br; /**< Max video bit rate */ /* sprop-parameter-sets, in NAL units */ - pj_size_t sprop_param_sets_len; /**< Parameter set length */ - pj_uint8_t sprop_param_sets[256]; /**< Parameter set (SPS & PPS), - in NAL unit bitstream */ + pj_size_t sprop_param_sets_len; /**< Parameter set length */ + pj_uint8_t sprop_param_sets[256]; /**< Parameter set (SPS & PPS), + in NAL unit bitstream */ } pjmedia_vid_codec_h264_fmtp; @@ -102,14 +101,14 @@ typedef struct pjmedia_vid_codec_h264_fmtp /** * Parse SDP fmtp of H.264. * - * @param fmtp The H.264 SDP fmtp to be parsed. - * @param h264_fmtp The parsing result. + * @param fmtp The H.264 SDP fmtp to be parsed. + * @param h264_fmtp The parsing result. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_h264_parse_fmtp( - const pjmedia_codec_fmtp *fmtp, - pjmedia_vid_codec_h264_fmtp *h264_fmtp); + const pjmedia_codec_fmtp *fmtp, + pjmedia_vid_codec_h264_fmtp *h264_fmtp); /** @@ -120,23 +119,23 @@ PJ_DECL(pj_status_t) pjmedia_vid_codec_h264_parse_fmtp( * may update the answer so the parameters in the answer match to ones * in the offer. * - * @param pool The memory pool. - * @param offer The SDP media offer. - * @param o_fmt_idx Index of the H.264 format in the SDP media offer. - * @param answer The SDP media answer. - * @param a_fmt_idx Index of the H.264 format in the SDP media answer. - * @param option The format matching option, see - * #pjmedia_sdp_neg_fmt_match_flag. + * @param pool The memory pool. + * @param offer The SDP media offer. + * @param o_fmt_idx Index of the H.264 format in the SDP media offer. + * @param answer The SDP media answer. + * @param a_fmt_idx Index of the H.264 format in the SDP media answer. + * @param option The format matching option, see + * #pjmedia_sdp_neg_fmt_match_flag. * - * @return PJ_SUCCESS when the formats in offer and answer match. + * @return PJ_SUCCESS when the formats in offer and answer match. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_h264_match_sdp( - pj_pool_t *pool, - pjmedia_sdp_media *offer, - unsigned o_fmt_idx, - pjmedia_sdp_media *answer, - unsigned a_fmt_idx, - unsigned option); + pj_pool_t *pool, + pjmedia_sdp_media *offer, + unsigned o_fmt_idx, + pjmedia_sdp_media *answer, + unsigned a_fmt_idx, + unsigned option); /** @@ -144,12 +143,12 @@ PJ_DECL(pj_status_t) pjmedia_vid_codec_h264_match_sdp( * specified codec parameter. This will validate size and fps to conform * to H.264 level specified in SDP fmtp "profile-level-id". * - * @param param The codec parameter. + * @param param The codec parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_h264_apply_fmtp( - pjmedia_vid_codec_param *param); + pjmedia_vid_codec_param *param); /** @@ -157,23 +156,23 @@ PJ_DECL(pj_status_t) pjmedia_vid_codec_h264_apply_fmtp( */ typedef struct pjmedia_vid_codec_vpx_fmtp { - unsigned max_fr; /**< Max frame rate */ - unsigned max_fs; /**< Max frame size (in macroblocks) */ - pj_uint8_t profile_id; /**< Profile ID */ + unsigned max_fr; /**< Max frame rate */ + unsigned max_fs; /**< Max frame size (in macroblocks) */ + pj_uint8_t profile_id; /**< Profile ID */ } pjmedia_vid_codec_vpx_fmtp; /** * Parse SDP fmtp of VPX. * - * @param fmtp The VPX SDP fmtp to be parsed. - * @param vpx_fmtp The parsing result. + * @param fmtp The VPX SDP fmtp to be parsed. + * @param vpx_fmtp The parsing result. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_vpx_parse_fmtp( - const pjmedia_codec_fmtp *fmtp, - pjmedia_vid_codec_vpx_fmtp *vpx_fmtp); + const pjmedia_codec_fmtp *fmtp, + pjmedia_vid_codec_vpx_fmtp *vpx_fmtp); /** @@ -181,15 +180,15 @@ PJ_DECL(pj_status_t) pjmedia_vid_codec_vpx_parse_fmtp( * specified codec parameter. This will validate size and fps to conform * to VPX level specified in SDP fmtp "max-fr" and "max-fs". * - * @param param The codec parameter. + * @param param The codec parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_codec_vpx_apply_fmtp( - pjmedia_vid_codec_param *param); + pjmedia_vid_codec_param *param); PJ_END_DECL -#endif /* __PJMEDIA_VID_CODEC_UTIL_H__ */ +#endif /* __PJMEDIA_VID_CODEC_UTIL_H__ */ diff --git a/pjmedia/include/pjmedia/vid_conf.h b/pjmedia/include/pjmedia/vid_conf.h index 09e9f0e5c5..30c6a34e97 100644 --- a/pjmedia/include/pjmedia/vid_conf.h +++ b/pjmedia/include/pjmedia/vid_conf.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2019 Teluu Inc. (http://www.teluu.com) * @@ -97,7 +96,7 @@ typedef struct pjmedia_vid_conf_setting * * Default: 32 */ - unsigned max_slot_cnt; + unsigned max_slot_cnt; /** * Frame rate the bridge will operate at. For video playback smoothness, @@ -109,14 +108,14 @@ typedef struct pjmedia_vid_conf_setting * * Default: 60 (frames per second) */ - unsigned frame_rate; + unsigned frame_rate; /** * Layout setting, see pjmedia_vid_conf_layout. * * Default: PJMEDIA_VID_CONF_LAYOUT_DEFAULT */ - unsigned layout; + unsigned layout; } pjmedia_vid_conf_setting; @@ -126,20 +125,20 @@ typedef struct pjmedia_vid_conf_setting */ typedef struct pjmedia_vid_conf_port_info { - unsigned slot; /**< Slot index. */ - pj_str_t name; /**< Port name. */ - pjmedia_format format; /**< Format. */ - unsigned listener_cnt; /**< Number of listeners. */ - unsigned *listener_slots; /**< Array of listeners. */ - unsigned transmitter_cnt; /**< Number of transmitter. */ - unsigned *transmitter_slots; /**< Array of transmitter. */ + unsigned slot; /**< Slot index. */ + pj_str_t name; /**< Port name. */ + pjmedia_format format; /**< Format. */ + unsigned listener_cnt; /**< Number of listeners. */ + unsigned *listener_slots; /**< Array of listeners. */ + unsigned transmitter_cnt; /**< Number of transmitter. */ + unsigned *transmitter_slots; /**< Array of transmitter. */ } pjmedia_vid_conf_port_info; /** * Initialize video conference settings with default values. * - * @param opt The settings to be initialized. + * @param opt The settings to be initialized. */ PJ_DECL(void) pjmedia_vid_conf_setting_default(pjmedia_vid_conf_setting *opt); @@ -147,25 +146,25 @@ PJ_DECL(void) pjmedia_vid_conf_setting_default(pjmedia_vid_conf_setting *opt); /** * Create a video conference bridge. * - * @param pool The memory pool. - * @param opt The video conference settings. - * @param p_vid_conf Pointer to receive the video conference bridge. + * @param pool The memory pool. + * @param opt The video conference settings. + * @param p_vid_conf Pointer to receive the video conference bridge. * - * @return PJ_SUCCESS on success, or the appropriate - * error code. + * @return PJ_SUCCESS on success, or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjmedia_vid_conf_create( - pj_pool_t *pool, - const pjmedia_vid_conf_setting *opt, - pjmedia_vid_conf **p_vid_conf); + pj_pool_t *pool, + const pjmedia_vid_conf_setting *opt, + pjmedia_vid_conf **p_vid_conf); /** * Destroy video conference bridge. * - * @param vid_conf The video conference bridge. + * @param vid_conf The video conference bridge. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_conf_destroy(pjmedia_vid_conf *vid_conf); @@ -173,48 +172,48 @@ PJ_DECL(pj_status_t) pjmedia_vid_conf_destroy(pjmedia_vid_conf *vid_conf); /** * Add a media port to the video conference bridge. * - * @param vid_conf The video conference bridge. - * @param pool The memory pool, the brige will create new pool - * based on this pool factory for this media port. - * @param port The media port to be added. - * @param name Name to be assigned to the slot. If not set, it will - * be set to the media port name. - * @param opt The option, for future use, currently this must - * be NULL. - * @param p_slot Pointer to receive the slot index of the port in - * the conference bridge. + * @param vid_conf The video conference bridge. + * @param pool The memory pool, the brige will create new pool + * based on this pool factory for this media port. + * @param port The media port to be added. + * @param name Name to be assigned to the slot. If not set, it will + * be set to the media port name. + * @param opt The option, for future use, currently this must + * be NULL. + * @param p_slot Pointer to receive the slot index of the port in + * the conference bridge. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_vid_conf_add_port(pjmedia_vid_conf *vid_conf, - pj_pool_t *pool, - pjmedia_port *port, - const pj_str_t *name, - void *opt, - unsigned *p_slot); + pj_pool_t *pool, + pjmedia_port *port, + const pj_str_t *name, + void *opt, + unsigned *p_slot); /** * Remove a media port from the video conference bridge. * - * @param vid_conf The video conference bridge. - * @param slot The media port's slot index to be removed. + * @param vid_conf The video conference bridge. + * @param slot The media port's slot index to be removed. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_vid_conf_remove_port(pjmedia_vid_conf *vid_conf, - unsigned slot); + unsigned slot); /** * Get number of ports currently registered in the video conference bridge. * - * @param vid_conf The video conference bridge. + * @param vid_conf The video conference bridge. * - * @return Number of ports currently registered to the video - * conference bridge. + * @return Number of ports currently registered to the video + * conference bridge. */ PJ_DECL(unsigned) pjmedia_vid_conf_get_port_count(pjmedia_vid_conf *vid_conf); @@ -222,67 +221,67 @@ PJ_DECL(unsigned) pjmedia_vid_conf_get_port_count(pjmedia_vid_conf *vid_conf); /** * Enumerate occupied slots in the video conference bridge. * - * @param vid_conf The video conference bridge. - * @param slots Array of slot to be filled in. - * @param count On input, specifies the maximum number of slot - * in the array. On return, it will be filled with - * the actual number of slot. + * @param vid_conf The video conference bridge. + * @param slots Array of slot to be filled in. + * @param count On input, specifies the maximum number of slot + * in the array. On return, it will be filled with + * the actual number of slot. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_conf_enum_ports(pjmedia_vid_conf *vid_conf, - unsigned slots[], - unsigned *count); + unsigned slots[], + unsigned *count); /** * Get port info. * - * @param vid_conf The video conference bridge. - * @param slot Slot index. - * @param info Pointer to receive the info. + * @param vid_conf The video conference bridge. + * @param slot Slot index. + * @param info Pointer to receive the info. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_conf_get_port_info( - pjmedia_vid_conf *vid_conf, - unsigned slot, - pjmedia_vid_conf_port_info *info); + pjmedia_vid_conf *vid_conf, + unsigned slot, + pjmedia_vid_conf_port_info *info); /** * Enable unidirectional video flow from the specified source slot to * the specified sink slot. * - * @param vid_conf The video conference bridge. - * @param src_slot Source slot. - * @param sink_slot Sink slot. - * @param opt The option, for future use, currently this must - * be NULL. + * @param vid_conf The video conference bridge. + * @param src_slot Source slot. + * @param sink_slot Sink slot. + * @param opt The option, for future use, currently this must + * be NULL. * - * @return PJ_SUCCES on success. + * @return PJ_SUCCES on success. */ PJ_DECL(pj_status_t) pjmedia_vid_conf_connect_port( - pjmedia_vid_conf *vid_conf, - unsigned src_slot, - unsigned sink_slot, - void *opt); + pjmedia_vid_conf *vid_conf, + unsigned src_slot, + unsigned sink_slot, + void *opt); /** * Disconnect unidirectional video flow from the specified source to * the specified sink slot. * - * @param vid_conf The video conference bridge. - * @param src_slot Source slot. - * @param sink_slot Sink slot. + * @param vid_conf The video conference bridge. + * @param src_slot Source slot. + * @param sink_slot Sink slot. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_vid_conf_disconnect_port( - pjmedia_vid_conf *vid_conf, - unsigned src_slot, - unsigned sink_slot); + pjmedia_vid_conf *vid_conf, + unsigned src_slot, + unsigned sink_slot); /** @@ -292,14 +291,14 @@ PJ_DECL(pj_status_t) pjmedia_vid_conf_disconnect_port( * has changed, video conference needs to be informed to update its * internal states. * - * @param vid_conf The video conference bridge. - * @param slot The media port's slot index to be updated. + * @param vid_conf The video conference bridge. + * @param slot The media port's slot index to be updated. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjmedia_vid_conf_update_port(pjmedia_vid_conf *vid_conf, - unsigned slot); + unsigned slot); PJ_END_DECL diff --git a/pjmedia/include/pjmedia/vid_port.h b/pjmedia/include/pjmedia/vid_port.h index 54d5675e90..32508861ef 100644 --- a/pjmedia/include/pjmedia/vid_port.h +++ b/pjmedia/include/pjmedia/vid_port.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -44,7 +43,7 @@ typedef struct pjmedia_vid_port_param /** * Video stream parameter. */ - pjmedia_vid_dev_param vidparam; + pjmedia_vid_dev_param vidparam; /** * Specify whether the video port should use active or passive interface. @@ -59,7 +58,7 @@ typedef struct pjmedia_vid_port_param * * Default: PJ_TRUE */ - pj_bool_t active; + pj_bool_t active; } pjmedia_vid_port_param; @@ -73,7 +72,7 @@ typedef struct pjmedia_vid_port pjmedia_vid_port; * would only fill the structure to zeroes unless they have different default * values. * - * @param prm The parameter. + * @param prm The parameter. */ PJ_DECL(void) pjmedia_vid_port_param_default(pjmedia_vid_port_param *prm); @@ -83,36 +82,36 @@ PJ_DECL(void) pjmedia_vid_port_param_default(pjmedia_vid_port_param *prm); * the \a prm.vidparam argument, it will automatically do the necessary * conversion. * - * @param pool Pool to allocate memory from. - * @param prm The video port parameter. - * @param p_vp Pointer to receive the result. + * @param pool Pool to allocate memory from. + * @param prm The video port parameter. + * @param p_vp Pointer to receive the result. * - * @return PJ_SUCCESS if video port has been created - * successfully, or the appropriate error code. + * @return PJ_SUCCESS if video port has been created + * successfully, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_vid_port_create(pj_pool_t *pool, - const pjmedia_vid_port_param *prm, - pjmedia_vid_port **p_vp); + const pjmedia_vid_port_param *prm, + pjmedia_vid_port **p_vp); /** * Set the callbacks of the video port's underlying video stream. * - * @param vid_port The video port. + * @param vid_port The video port. * @param cb Pointer to structure containing video stream * callbacks. * @param user_data Arbitrary user data, which will be given back in the * callbacks. */ PJ_DECL(void) pjmedia_vid_port_set_cb(pjmedia_vid_port *vid_port, - const pjmedia_vid_dev_cb *cb, + const pjmedia_vid_dev_cb *cb, void *user_data); /** * Return the underlying video stream of the video port. * - * @param vid_port The video port. + * @param vid_port The video port. * - * @return The video stream. + * @return The video stream. */ PJ_DECL(pjmedia_vid_dev_stream*) pjmedia_vid_port_get_stream(pjmedia_vid_port *vid_port); @@ -123,9 +122,9 @@ pjmedia_vid_port_get_stream(pjmedia_vid_port *vid_port); * Retrieving the media port for active video ports may raise an * assertion. * - * @param vid_port The video port. + * @param vid_port The video port. * - * @return The media port instance, or NULL. + * @return The media port instance, or NULL. */ PJ_DECL(pjmedia_port*) pjmedia_vid_port_get_passive_port(pjmedia_vid_port *vid_port); @@ -135,7 +134,7 @@ pjmedia_vid_port_get_passive_port(pjmedia_vid_port *vid_port); * * @param vid_port The video port. * - * @return The clock source. + * @return The clock source. */ PJ_DECL(pjmedia_clock_src *) pjmedia_vid_port_get_clock_src( pjmedia_vid_port *vid_port ); @@ -146,7 +145,7 @@ pjmedia_vid_port_get_clock_src( pjmedia_vid_port *vid_port ); * @param vid_port The video port. * @param clocksrc The clock source. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_vid_port_set_clock_src( pjmedia_vid_port *vid_port, @@ -158,44 +157,44 @@ pjmedia_vid_port_set_clock_src( pjmedia_vid_port *vid_port, * events so renderer can adjust its param whenever stream port detects * format change. * - * @param vid_port The video port. - * @param port The media port whose events to be monitored. + * @param vid_port The video port. + * @param port The media port whose events to be monitored. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_vid_port_subscribe_event( - pjmedia_vid_port *vid_port, - pjmedia_port *port); + pjmedia_vid_port *vid_port, + pjmedia_port *port); /** * Unsubscribe media event notifications from the specified media port. * - * @param vid_port The video port. - * @param port The media port whose events to be unsubscribed. + * @param vid_port The video port. + * @param port The media port whose events to be unsubscribed. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_vid_port_unsubscribe_event( - pjmedia_vid_port *vid_port, - pjmedia_port *port); + pjmedia_vid_port *vid_port, + pjmedia_port *port); /** * Connect the video port to a downstream (slave) media port. This operation * is only valid for video ports created with active interface selected. * Connecting a passive video port may raise an assertion. * - * @param vid_port The video port. - * @param port A downstream media port to be connected to - * this video port. - * @param destroy Specify if the downstream media port should also be - * destroyed by this video port when the video port - * is destroyed. + * @param vid_port The video port. + * @param port A downstream media port to be connected to + * this video port. + * @param destroy Specify if the downstream media port should also be + * destroyed by this video port when the video port + * is destroyed. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_vid_port_connect(pjmedia_vid_port *vid_port, - pjmedia_port *port, - pj_bool_t destroy); + pjmedia_port *port, + pj_bool_t destroy); /** * Disconnect the video port from its downstream (slave) media port, if any. @@ -203,9 +202,9 @@ PJ_DECL(pj_status_t) pjmedia_vid_port_connect(pjmedia_vid_port *vid_port, * selected, and assertion may be triggered if this is invoked on a passive * video port. * - * @param vid_port The video port. + * @param vid_port The video port. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_vid_port_disconnect(pjmedia_vid_port *vid_port); @@ -215,10 +214,10 @@ PJ_DECL(pj_status_t) pjmedia_vid_port_disconnect(pjmedia_vid_port *vid_port); * with active interface selected, and assertion may be triggered if this is * invoked on a passive video port. * - * @param vid_port The video port. + * @param vid_port The video port. * - * @return Media port currently connected to the video port, - * if any. + * @return Media port currently connected to the video port, + * if any. */ PJ_DECL(pjmedia_port*) pjmedia_vid_port_get_connected_port(pjmedia_vid_port *vid_port); @@ -226,27 +225,27 @@ pjmedia_vid_port_get_connected_port(pjmedia_vid_port *vid_port); /** * Start the video port. * - * @param vid_port The video port. + * @param vid_port The video port. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_vid_port_start(pjmedia_vid_port *vid_port); /** * Query whether the video port has been started. * - * @param vid_port The video port. + * @param vid_port The video port. * - * @return PJ_TRUE if the video port has been started. + * @return PJ_TRUE if the video port has been started. */ PJ_DECL(pj_bool_t) pjmedia_vid_port_is_running(pjmedia_vid_port *vid_port); /** * Stop the video port. * - * @param vid_port The video port. + * @param vid_port The video port. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_vid_port_stop(pjmedia_vid_port *vid_port); @@ -255,7 +254,7 @@ PJ_DECL(pj_status_t) pjmedia_vid_port_stop(pjmedia_vid_port *vid_port); * an active one, this may also destroy the downstream media port, if the * destroy flag is set when the media port is connected. * - * @param vid_port The video port. + * @param vid_port The video port. */ PJ_DECL(void) pjmedia_vid_port_destroy(pjmedia_vid_port *vid_port); diff --git a/pjmedia/include/pjmedia/vid_stream.h b/pjmedia/include/pjmedia/vid_stream.h index f1ef92c7c6..9406ca4949 100644 --- a/pjmedia/include/pjmedia/vid_stream.h +++ b/pjmedia/include/pjmedia/vid_stream.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011 Teluu Inc. (http://www.teluu.com) * @@ -84,7 +83,7 @@ typedef enum pjmedia_vid_stream_rc_method * No sending rate control. All outgoing RTP packets will be transmitted * immediately right after encoding process is done. */ - PJMEDIA_VID_STREAM_RC_NONE = 0, + PJMEDIA_VID_STREAM_RC_NONE = 0, /** * Simple blocking. Each outgoing RTP packet transmission may be delayed @@ -115,7 +114,7 @@ typedef struct pjmedia_vid_stream_rc_config * * Default: 0 (follow codec maximum bitrate). */ - unsigned bandwidth; + unsigned bandwidth; } pjmedia_vid_stream_rc_config; @@ -130,14 +129,14 @@ typedef struct pjmedia_vid_stream_sk_config * * Default: PJMEDIA_VID_STREAM_START_KEYFRAME_CNT */ - unsigned count; + unsigned count; /** * The keyframe sending interval after the stream is created. * * Default: PJMEDIA_VID_STREAM_START_KEYFRAME_INTERVAL_MSEC */ - unsigned interval; + unsigned interval; } pjmedia_vid_stream_sk_config; @@ -149,49 +148,49 @@ typedef struct pjmedia_vid_stream_sk_config */ typedef struct pjmedia_vid_stream_info { - pjmedia_type type; /**< Media type (audio, video) */ - pjmedia_tp_proto proto; /**< Transport protocol (RTP/AVP, etc.) */ - pjmedia_dir dir; /**< Media direction. */ - pj_sockaddr local_addr; /**< Local RTP address */ - pj_sockaddr rem_addr; /**< Remote RTP address */ - pj_sockaddr rem_rtcp; /**< Optional remote RTCP address. If - sin_family is zero, the RTP address - will be calculated from RTP. */ - pj_bool_t rtcp_mux; /**< Use RTP and RTCP multiplexing. */ - pjmedia_rtcp_fb_info loc_rtcp_fb; /**< Local RTCP-FB info. */ - pjmedia_rtcp_fb_info rem_rtcp_fb; /**< Remote RTCP-FB info. */ - unsigned tx_pt; /**< Outgoing codec paylaod type. */ - unsigned rx_pt; /**< Incoming codec paylaod type. */ - pj_uint32_t ssrc; /**< RTP SSRC. */ - pj_str_t cname; /**< RTCP CNAME. */ - pj_bool_t has_rem_ssrc;/** @@ -46,32 +45,32 @@ PJ_BEGIN_DECL * files must have the same clock rate, number of channels, and bits * per sample, or otherwise this function will return error. * - * @param pool Pool to create memory buffers for this port. - * @param port_label Optional label to set as the port name. - * @param file_list Array of WAV file names. - * Each filename's length must be smaller than - * PJ_MAXPATH. - * @param file_count Number of files in the array. - * @param ptime The duration (in miliseconds) of each frame read - * from this port. If the value is zero, the default - * duration (20ms) will be used. - * @param options Optional options. Application may specify - * PJMEDIA_FILE_NO_LOOP to prevent play back loop. - * @param buff_size Buffer size to be allocated. If the value is zero or - * negative, the port will use default buffer size (which - * is about 4KB). - * @param p_port Pointer to receive the file port instance. + * @param pool Pool to create memory buffers for this port. + * @param port_label Optional label to set as the port name. + * @param file_list Array of WAV file names. + * Each filename's length must be smaller than + * PJ_MAXPATH. + * @param file_count Number of files in the array. + * @param ptime The duration (in miliseconds) of each frame read + * from this port. If the value is zero, the default + * duration (20ms) will be used. + * @param options Optional options. Application may specify + * PJMEDIA_FILE_NO_LOOP to prevent play back loop. + * @param buff_size Buffer size to be allocated. If the value is zero or + * negative, the port will use default buffer size (which + * is about 4KB). + * @param p_port Pointer to receive the file port instance. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_wav_playlist_create(pj_pool_t *pool, - const pj_str_t *port_label, - const pj_str_t file_list[], - int file_count, - unsigned ptime, - unsigned options, - pj_ssize_t buff_size, - pjmedia_port **p_port); + const pj_str_t *port_label, + const pj_str_t file_list[], + int file_count, + unsigned ptime, + unsigned options, + pj_ssize_t buff_size, + pjmedia_port **p_port); #if !DEPRECATED_FOR_TICKET_2251 @@ -81,20 +80,20 @@ PJ_DECL(pj_status_t) pjmedia_wav_playlist_create(pj_pool_t *pool, * then the callback will be called multiple times. Note that only one * callback can be registered for each file port. * - * @param port The WAV play list port. - * @param user_data User data to be specified in the callback - * @param cb Callback to be called. If the callback returns non- - * PJ_SUCCESS, the playback will stop. Note that if - * application destroys the file port in the callback, - * it must return non-PJ_SUCCESS here. + * @param port The WAV play list port. + * @param user_data User data to be specified in the callback + * @param cb Callback to be called. If the callback returns non- + * PJ_SUCCESS, the playback will stop. Note that if + * application destroys the file port in the callback, + * it must return non-PJ_SUCCESS here. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_wav_playlist_set_eof_cb(pjmedia_port *port, - void *user_data, - pj_status_t (*cb)(pjmedia_port *port, - void *usr_data)); + void *user_data, + pj_status_t (*cb)(pjmedia_port *port, + void *usr_data)); #endif @@ -104,21 +103,21 @@ pjmedia_wav_playlist_set_eof_cb(pjmedia_port *port, * then the callback will be called multiple times. Note that only one * callback can be registered for each file port. * - * @param port The WAV play list port. - * @param user_data User data to be specified in the callback - * @param cb Callback to be called. Note that if - * application wishes to stop the playback, it - * can disconnect the port in the callback, and - * only after all connections have been removed - * could the application safely destroy the port. + * @param port The WAV play list port. + * @param user_data User data to be specified in the callback + * @param cb Callback to be called. Note that if + * application wishes to stop the playback, it + * can disconnect the port in the callback, and + * only after all connections have been removed + * could the application safely destroy the port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_wav_playlist_set_eof_cb2(pjmedia_port *port, - void *user_data, - void (*cb)(pjmedia_port *port, - void *usr_data)); + void *user_data, + void (*cb)(pjmedia_port *port, + void *usr_data)); /** @@ -129,4 +128,4 @@ pjmedia_wav_playlist_set_eof_cb2(pjmedia_port *port, PJ_END_DECL -#endif /* __PJMEDIA_WAV_PLAYLIST_H__ */ +#endif /* __PJMEDIA_WAV_PLAYLIST_H__ */ diff --git a/pjmedia/include/pjmedia/wav_port.h b/pjmedia/include/pjmedia/wav_port.h index b597bc5a3c..5928539c44 100644 --- a/pjmedia/include/pjmedia/wav_port.h +++ b/pjmedia/include/pjmedia/wav_port.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -59,23 +58,23 @@ typedef struct pjmedia_wav_player_info /** * Format ID of the payload. */ - pjmedia_format_id fmt_id; + pjmedia_format_id fmt_id; /** * The number of bits per sample of the file payload. For example, * the value is 16 for PCM WAV and 8 for Alaw/Ulas WAV files. */ - unsigned payload_bits_per_sample; + unsigned payload_bits_per_sample; /** * The WAV payload size in bytes. */ - pj_uint32_t size_bytes; + pj_uint32_t size_bytes; /** * The WAV payload size in samples. */ - pj_uint32_t size_samples; + pj_uint32_t size_samples; } pjmedia_wav_player_info; @@ -85,33 +84,33 @@ typedef struct pjmedia_wav_player_info * supports for reading WAV file with uncompressed 16 bit PCM format or * compressed G.711 A-law/U-law format. * - * @param pool Pool to create memory buffers for this port. - * @param filename File name to open. - * @param ptime The duration (in miliseconds) of each frame read - * from this port. If the value is zero, the default - * duration (20ms) will be used. - * @param flags Port creation flags. - * @param buff_size Buffer size to be allocated. If the value is zero or - * negative, the port will use default buffer size (which - * is about 4KB). - * @param p_port Pointer to receive the file port instance. + * @param pool Pool to create memory buffers for this port. + * @param filename File name to open. + * @param ptime The duration (in miliseconds) of each frame read + * from this port. If the value is zero, the default + * duration (20ms) will be used. + * @param flags Port creation flags. + * @param buff_size Buffer size to be allocated. If the value is zero or + * negative, the port will use default buffer size (which + * is about 4KB). + * @param p_port Pointer to receive the file port instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool, - const char *filename, - unsigned ptime, - unsigned flags, - pj_ssize_t buff_size, - pjmedia_port **p_port ); + const char *filename, + unsigned ptime, + unsigned flags, + pj_ssize_t buff_size, + pjmedia_port **p_port ); /** * Get additional info about the file player. * - * @param port The file port. - * @param i The info. + * @param port The file port. + * @param i The info. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_wav_player_get_info(pjmedia_port *port, pjmedia_wav_player_info *i); @@ -119,10 +118,10 @@ PJ_DECL(pj_status_t) pjmedia_wav_player_get_info(pjmedia_port *port, /** * Get the data length, in bytes. * - * @param port The file player port. + * @param port The file player port. * - * @return The length of the data, in bytes. On error, the - * error code is given as negative value. + * @return The length of the data, in bytes. On error, the + * error code is given as negative value. */ PJ_DECL(pj_ssize_t) pjmedia_wav_player_get_len(pjmedia_port *port); @@ -130,23 +129,23 @@ PJ_DECL(pj_ssize_t) pjmedia_wav_player_get_len(pjmedia_port *port); /** * Set the file play position of WAV player. * - * @param port The file player port. - * @param offset Playback position in bytes, relative to the start of - * the payload. + * @param port The file player port. + * @param offset Playback position in bytes, relative to the start of + * the payload. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_wav_player_port_set_pos( pjmedia_port *port, - pj_uint32_t offset ); + pj_uint32_t offset ); /** * Get the file play position of WAV player, in bytes. * - * @param port The file player port. + * @param port The file player port. * - * @return The current play position, in bytes. On error, the - * error code is given as negative value. + * @return The current play position, in bytes. On error, the + * error code is given as negative value. */ PJ_DECL(pj_ssize_t) pjmedia_wav_player_port_get_pos( pjmedia_port *port ); @@ -158,20 +157,20 @@ PJ_DECL(pj_ssize_t) pjmedia_wav_player_port_get_pos( pjmedia_port *port ); * will be called multiple times. Note that only one callback can be * registered for each file port. * - * @param port The file player port. - * @param user_data User data to be specified in the callback - * @param cb Callback to be called. If the callback returns non- - * PJ_SUCCESS, the playback will stop. Note that if - * application destroys the file port in the callback, - * it must return non-PJ_SUCCESS here. + * @param port The file player port. + * @param user_data User data to be specified in the callback + * @param cb Callback to be called. If the callback returns non- + * PJ_SUCCESS, the playback will stop. Note that if + * application destroys the file port in the callback, + * it must return non-PJ_SUCCESS here. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_wav_player_set_eof_cb( pjmedia_port *port, - void *user_data, - pj_status_t (*cb)(pjmedia_port *port, - void *usr_data)); + void *user_data, + pj_status_t (*cb)(pjmedia_port *port, + void *usr_data)); #endif @@ -181,21 +180,21 @@ pjmedia_wav_player_set_eof_cb( pjmedia_port *port, * will be called multiple times. Note that only one callback can be * registered for each file port. * - * @param port The file player port. - * @param user_data User data to be specified in the callback - * @param cb Callback to be called. Note that if - * application wishes to stop the playback, it - * can disconnect the port in the callback, and - * only after all connections have been removed - * could the application safely destroy the port. + * @param port The file player port. + * @param user_data User data to be specified in the callback + * @param cb Callback to be called. Note that if + * application wishes to stop the playback, it + * can disconnect the port in the callback, and + * only after all connections have been removed + * could the application safely destroy the port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_wav_player_set_eof_cb2(pjmedia_port *port, - void *user_data, - void (*cb)(pjmedia_port *port, - void *usr_data)); + void *user_data, + void (*cb)(pjmedia_port *port, + void *usr_data)); /** @@ -241,30 +240,30 @@ enum pjmedia_file_writer_option * or compressed G.711 U-law/A-law format, this needs to be specified in * \a flags param. * - * @param pool Pool to create memory buffers for this port. - * @param filename File name. - * @param clock_rate The sampling rate. - * @param channel_count Number of channels. + * @param pool Pool to create memory buffers for this port. + * @param filename File name. + * @param clock_rate The sampling rate. + * @param channel_count Number of channels. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Number of bits per sample (eg 16). - * @param flags Port creation flags, see - * #pjmedia_file_writer_option. - * @param buff_size Buffer size to be allocated. If the value is - * zero or negative, the port will use default buffer - * size (which is about 4KB). - * @param p_port Pointer to receive the file port instance. + * @param flags Port creation flags, see + * #pjmedia_file_writer_option. + * @param buff_size Buffer size to be allocated. If the value is + * zero or negative, the port will use default buffer + * size (which is about 4KB). + * @param p_port Pointer to receive the file port instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_wav_writer_port_create(pj_pool_t *pool, - const char *filename, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned flags, - pj_ssize_t buff_size, - pjmedia_port **p_port ); + const char *filename, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned flags, + pj_ssize_t buff_size, + pjmedia_port **p_port ); /** @@ -273,10 +272,10 @@ PJ_DECL(pj_status_t) pjmedia_wav_writer_port_create(pj_pool_t *pool, * buffering. Also the value reported here only indicates the payload size * (it does not include the size of the WAV header), * - * @param port The file writer port. + * @param port The file writer port. * - * @return Positive value to indicate the position (in bytes), - * or negative value containing the error code. + * @return Positive value to indicate the position (in bytes), + * or negative value containing the error code. */ PJ_DECL(pj_ssize_t) pjmedia_wav_writer_port_get_pos( pjmedia_port *port ); @@ -287,23 +286,23 @@ PJ_DECL(pj_ssize_t) pjmedia_wav_writer_port_get_pos( pjmedia_port *port ); * certain size. Application can use this callback, for example, to limit * the size of the output file. * - * @param port The file writer port. - * @param pos The file position on which the callback will be called. - * @param user_data User data to be specified in the callback, and will be - * given on the callback. - * @param cb Callback to be called. If the callback returns non- - * PJ_SUCCESS, the writing will stop. Note that if - * application destroys the port in the callback, it must - * return non-PJ_SUCCESS here. + * @param port The file writer port. + * @param pos The file position on which the callback will be called. + * @param user_data User data to be specified in the callback, and will be + * given on the callback. + * @param cb Callback to be called. If the callback returns non- + * PJ_SUCCESS, the writing will stop. Note that if + * application destroys the port in the callback, it must + * return non-PJ_SUCCESS here. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_wav_writer_port_set_cb( pjmedia_port *port, - pj_size_t pos, - void *user_data, - pj_status_t (*cb)(pjmedia_port *port, - void *usr_data)); + pj_size_t pos, + void *user_data, + pj_status_t (*cb)(pjmedia_port *port, + void *usr_data)); #endif @@ -312,24 +311,24 @@ pjmedia_wav_writer_port_set_cb( pjmedia_port *port, * certain size. Application can use this callback, for example, to limit * the size of the output file. * - * @param port The file writer port. - * @param pos The file position on which the callback will be called. - * @param user_data User data to be specified in the callback, and will be - * given on the callback. - * @param cb Callback to be called. Note that if - * application wishes to stop the writing, it - * can disconnect the port in the callback, and - * only after all connections have been removed - * could the application safely destroy the port. + * @param port The file writer port. + * @param pos The file position on which the callback will be called. + * @param user_data User data to be specified in the callback, and will be + * given on the callback. + * @param cb Callback to be called. Note that if + * application wishes to stop the writing, it + * can disconnect the port in the callback, and + * only after all connections have been removed + * could the application safely destroy the port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_wav_writer_port_set_cb2(pjmedia_port *port, - pj_size_t pos, - void *user_data, - void (*cb)(pjmedia_port *port, - void *usr_data)); + pj_size_t pos, + void *user_data, + void (*cb)(pjmedia_port *port, + void *usr_data)); /** @@ -340,4 +339,4 @@ pjmedia_wav_writer_port_set_cb2(pjmedia_port *port, PJ_END_DECL -#endif /* __PJMEDIA_WAV_PORT_H__ */ +#endif /* __PJMEDIA_WAV_PORT_H__ */ diff --git a/pjmedia/include/pjmedia/wave.h b/pjmedia/include/pjmedia/wave.h index 866f4fae4d..a140a5fd20 100644 --- a/pjmedia/include/pjmedia/wave.h +++ b/pjmedia/include/pjmedia/wave.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -50,36 +49,36 @@ PJ_BEGIN_DECL /** * Standard RIFF tag to identify RIFF file format in the WAVE header. */ -#define PJMEDIA_RIFF_TAG ('F'<<24|'F'<<16|'I'<<8|'R') +#define PJMEDIA_RIFF_TAG ('F'<<24|'F'<<16|'I'<<8|'R') /** * Standard WAVE tag to identify WAVE header. */ -#define PJMEDIA_WAVE_TAG ('E'<<24|'V'<<16|'A'<<8|'W') +#define PJMEDIA_WAVE_TAG ('E'<<24|'V'<<16|'A'<<8|'W') /** * Standard FMT tag to identify format chunks. */ -#define PJMEDIA_FMT_TAG (' '<<24|'t'<<16|'m'<<8|'f') +#define PJMEDIA_FMT_TAG (' '<<24|'t'<<16|'m'<<8|'f') /** * Standard DATA tag to identify data chunks. */ -#define PJMEDIA_DATA_TAG ('a'<<24|'t'<<16|'a'<<8|'d') +#define PJMEDIA_DATA_TAG ('a'<<24|'t'<<16|'a'<<8|'d') /** * Standard FACT tag to identify fact chunks. */ -#define PJMEDIA_FACT_TAG ('t'<<24|'c'<<16|'a'<<8|'f') +#define PJMEDIA_FACT_TAG ('t'<<24|'c'<<16|'a'<<8|'f') /** * Enumeration of format compression tag. */ typedef enum { - PJMEDIA_WAVE_FMT_TAG_PCM = 1, - PJMEDIA_WAVE_FMT_TAG_ALAW = 6, - PJMEDIA_WAVE_FMT_TAG_ULAW = 7 + PJMEDIA_WAVE_FMT_TAG_PCM = 1, + PJMEDIA_WAVE_FMT_TAG_ALAW = 6, + PJMEDIA_WAVE_FMT_TAG_ULAW = 7 } pjmedia_wave_fmt_tag; @@ -92,27 +91,27 @@ struct pjmedia_wave_hdr { /** This structure describes RIFF WAVE file header */ struct { - pj_uint32_t riff; /**< "RIFF" ASCII tag. */ - pj_uint32_t file_len; /**< File length minus 8 bytes */ - pj_uint32_t wave; /**< "WAVE" ASCII tag. */ + pj_uint32_t riff; /**< "RIFF" ASCII tag. */ + pj_uint32_t file_len; /**< File length minus 8 bytes */ + pj_uint32_t wave; /**< "WAVE" ASCII tag. */ } riff_hdr; /** This structure describes format chunks/header */ struct { - pj_uint32_t fmt; /**< "fmt " ASCII tag. */ - pj_uint32_t len; /**< 16 for PCM. */ - pj_uint16_t fmt_tag; /**< 1 for PCM */ - pj_uint16_t nchan; /**< Number of channels. */ - pj_uint32_t sample_rate; /**< Sampling rate. */ - pj_uint32_t bytes_per_sec; /**< Average bytes per second. */ - pj_uint16_t block_align; /**< nchannels * bits / 8 */ - pj_uint16_t bits_per_sample; /**< Bits per sample. */ + pj_uint32_t fmt; /**< "fmt " ASCII tag. */ + pj_uint32_t len; /**< 16 for PCM. */ + pj_uint16_t fmt_tag; /**< 1 for PCM */ + pj_uint16_t nchan; /**< Number of channels. */ + pj_uint32_t sample_rate; /**< Sampling rate. */ + pj_uint32_t bytes_per_sec; /**< Average bytes per second. */ + pj_uint16_t block_align; /**< nchannels * bits / 8 */ + pj_uint16_t bits_per_sample; /**< Bits per sample. */ } fmt_hdr; /** The data header preceeds the actual data in the file. */ struct { - pj_uint32_t data; /**< "data" ASCII tag. */ - pj_uint32_t len; /**< Data length. */ + pj_uint32_t data; /**< "data" ASCII tag. */ + pj_uint32_t len; /**< Data length. */ } data_hdr; }; #pragma pack() @@ -127,8 +126,8 @@ typedef struct pjmedia_wave_hdr pjmedia_wave_hdr; */ typedef struct pjmedia_wave_subchunk { - pj_uint32_t id; /**< Subchunk ASCII tag. */ - pj_uint32_t len; /**< Length following this field */ + pj_uint32_t id; /**< Subchunk ASCII tag. */ + pj_uint32_t len; /**< Length following this field */ } pjmedia_wave_subchunk; @@ -138,10 +137,10 @@ typedef struct pjmedia_wave_subchunk */ #if defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN!=0 # define PJMEDIA_WAVE_NORMALIZE_SUBCHUNK(ch) \ - do { \ - (ch)->id = pj_swap32((ch)->id); \ - (ch)->len = pj_swap32((ch)->len); \ - } while (0) + do { \ + (ch)->id = pj_swap32((ch)->id); \ + (ch)->len = pj_swap32((ch)->len); \ + } while (0) #else # define PJMEDIA_WAVE_NORMALIZE_SUBCHUNK(ch) #endif @@ -155,7 +154,7 @@ typedef struct pjmedia_wave_subchunk * Application SHOULD call this function after reading the WAVE header * chunks from a file. * - * @param hdr The WAVE header. + * @param hdr The WAVE header. */ PJ_DECL(void) pjmedia_wave_hdr_file_to_host( pjmedia_wave_hdr *hdr ); @@ -168,7 +167,7 @@ PJ_DECL(void) pjmedia_wave_hdr_file_to_host( pjmedia_wave_hdr *hdr ); * Application SHOULD call this function before writing the WAVE header * to a file. * - * @param hdr The WAVE header. + * @param hdr The WAVE header. */ PJ_DECL(void) pjmedia_wave_hdr_host_to_file( pjmedia_wave_hdr *hdr ); @@ -180,5 +179,5 @@ PJ_END_DECL */ -#endif /* __PJMEDIA_WAVE_H__ */ +#endif /* __PJMEDIA_WAVE_H__ */ diff --git a/pjmedia/include/pjmedia/wsola.h b/pjmedia/include/pjmedia/wsola.h index a679d17437..d17a9cbae0 100644 --- a/pjmedia/include/pjmedia/wsola.h +++ b/pjmedia/include/pjmedia/wsola.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -58,7 +57,7 @@ enum pjmedia_wsola_option /** * Disable Hanning window to conserve memory. */ - PJMEDIA_WSOLA_NO_HANNING = 1, + PJMEDIA_WSOLA_NO_HANNING = 1, /** * Specify that the WSOLA will not be used for PLC. @@ -87,22 +86,22 @@ enum pjmedia_wsola_option /** * Create and initialize WSOLA. * - * @param pool Pool to allocate memory for WSOLA. - * @param clock_rate Sampling rate of audio playback. + * @param pool Pool to allocate memory for WSOLA. + * @param clock_rate Sampling rate of audio playback. * @param samples_per_frame Number of samples per frame. - * @param channel_count Number of channels. - * @param options Option flags, bitmask combination of - * #pjmedia_wsola_option. - * @param p_wsola Pointer to receive WSOLA structure. + * @param channel_count Number of channels. + * @param options Option flags, bitmask combination of + * #pjmedia_wsola_option. + * @param p_wsola Pointer to receive WSOLA structure. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pjmedia_wsola_create(pj_pool_t *pool, - unsigned clock_rate, - unsigned samples_per_frame, - unsigned channel_count, - unsigned options, - pjmedia_wsola **p_wsola); + unsigned clock_rate, + unsigned samples_per_frame, + unsigned channel_count, + unsigned options, + pjmedia_wsola **p_wsola); /** @@ -113,21 +112,21 @@ PJ_DECL(pj_status_t) pjmedia_wsola_create(pj_pool_t *pool, * (see also the documentation of PJMEDIA_WSOLA_MAX_EXPAND_MSEC for * more information). * - * @param wsola The WSOLA session - * @param msec The duration. + * @param wsola The WSOLA session + * @param msec The duration. * - * @return PJ_SUCCESS normally. + * @return PJ_SUCCESS normally. */ PJ_DECL(pj_status_t) pjmedia_wsola_set_max_expand(pjmedia_wsola *wsola, - unsigned msec); + unsigned msec); /** * Destroy WSOLA. * - * @param wsola WSOLA session. + * @param wsola WSOLA session. * - * @return PJ_SUCCESS normally. + * @return PJ_SUCCESS normally. */ PJ_DECL(pj_status_t) pjmedia_wsola_destroy(pjmedia_wsola *wsola); @@ -135,13 +134,13 @@ PJ_DECL(pj_status_t) pjmedia_wsola_destroy(pjmedia_wsola *wsola); /** * Reset the buffer contents of WSOLA. * - * @param wsola WSOLA session. + * @param wsola WSOLA session. * @param options Reset options, must be zero for now. * - * @return PJ_SUCCESS normally. + * @return PJ_SUCCESS normally. */ PJ_DECL(pj_status_t) pjmedia_wsola_reset(pjmedia_wsola *wsola, - unsigned options); + unsigned options); /** @@ -150,33 +149,33 @@ PJ_DECL(pj_status_t) pjmedia_wsola_reset(pjmedia_wsola *wsola, * date with current playback. Depending on the WSOLA implementation, * this function may modify the content of the frame. * - * @param wsola WSOLA session. - * @param frm The frame, which length must match the samples per - * frame setting of the WSOLA session. + * @param wsola WSOLA session. + * @param frm The frame, which length must match the samples per + * frame setting of the WSOLA session. * @param prev_lost If application previously generated a synthetic - * frame with #pjmedia_wsola_generate() before calling - * this function, specify whether that was because of - * packet lost. If so, set this parameter to PJ_TRUE - * to make WSOLA interpolate this frame with its buffer. - * Otherwise if this value is PJ_FALSE, WSOLA will - * just append this frame to the end of its buffer. - * - * @return PJ_SUCCESS normally. + * frame with #pjmedia_wsola_generate() before calling + * this function, specify whether that was because of + * packet lost. If so, set this parameter to PJ_TRUE + * to make WSOLA interpolate this frame with its buffer. + * Otherwise if this value is PJ_FALSE, WSOLA will + * just append this frame to the end of its buffer. + * + * @return PJ_SUCCESS normally. */ PJ_DECL(pj_status_t) pjmedia_wsola_save(pjmedia_wsola *wsola, - pj_int16_t frm[], - pj_bool_t prev_lost); + pj_int16_t frm[], + pj_bool_t prev_lost); /** * Generate one synthetic frame from WSOLA. * - * @param wsola WSOLA session. - * @param frm Buffer to receive the frame. + * @param wsola WSOLA session. + * @param frm Buffer to receive the frame. * - * @return PJ_SUCCESS normally. + * @return PJ_SUCCESS normally. */ PJ_DECL(pj_status_t) pjmedia_wsola_generate(pjmedia_wsola *wsola, - pj_int16_t frm[]); + pj_int16_t frm[]); /** @@ -184,29 +183,29 @@ PJ_DECL(pj_status_t) pjmedia_wsola_generate(pjmedia_wsola *wsola, * from the buffer, without altering the pitch. For this function to work, * total length of the buffer must be more than twice \a erase_cnt. * - * @param wsola WSOLA session. - * @param buf1 Pointer to buffer. + * @param wsola WSOLA session. + * @param buf1 Pointer to buffer. * @param buf1_cnt Number of samples in the buffer. - * @param buf2 Pointer to second buffer, if the buffer is not - * contiguous. Otherwise this parameter must be NULL. + * @param buf2 Pointer to second buffer, if the buffer is not + * contiguous. Otherwise this parameter must be NULL. * @param buf2_cnt Number of samples in the second buffer, if the buffer - * is not contiguous. Otherwise this parameter should be - * zero. + * is not contiguous. Otherwise this parameter should be + * zero. * @param erase_cnt On input, specify the number of samples to be erased. - * This function may erase more or less than the requested - * number, and the actual number of samples erased will be - * given on this argument upon returning from the function. + * This function may erase more or less than the requested + * number, and the actual number of samples erased will be + * given on this argument upon returning from the function. * - * @return PJ_SUCCESS if some samples have been erased, PJ_ETOOSMALL - * if buffer is too small to be reduced, PJ_EINVAL if any - * of the parameters are not valid. + * @return PJ_SUCCESS if some samples have been erased, PJ_ETOOSMALL + * if buffer is too small to be reduced, PJ_EINVAL if any + * of the parameters are not valid. */ PJ_DECL(pj_status_t) pjmedia_wsola_discard(pjmedia_wsola *wsola, - pj_int16_t buf1[], - unsigned buf1_cnt, - pj_int16_t buf2[], - unsigned buf2_cnt, - unsigned *erase_cnt); + pj_int16_t buf1[], + unsigned buf1_cnt, + pj_int16_t buf2[], + unsigned buf2_cnt, + unsigned *erase_cnt); PJ_END_DECL @@ -215,5 +214,5 @@ PJ_END_DECL * @} */ -#endif /* __PJMEDIA_WSOLA_H__ */ +#endif /* __PJMEDIA_WSOLA_H__ */ diff --git a/pjmedia/include/pjmedia_audiodev.h b/pjmedia/include/pjmedia_audiodev.h index d35ca93b5e..87246265f3 100644 --- a/pjmedia/include/pjmedia_audiodev.h +++ b/pjmedia/include/pjmedia_audiodev.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,5 +28,5 @@ #include #include -#endif /* __PJMEDIA_AUDIODEV_H__ */ +#endif /* __PJMEDIA_AUDIODEV_H__ */ diff --git a/pjmedia/include/pjmedia_videodev.h b/pjmedia/include/pjmedia_videodev.h index 592853d664..f0adcbaf93 100644 --- a/pjmedia/include/pjmedia_videodev.h +++ b/pjmedia/include/pjmedia_videodev.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -28,4 +27,4 @@ #include #include -#endif /* __PJMEDIA_VIDEODEV_H__ */ +#endif /* __PJMEDIA_VIDEODEV_H__ */ diff --git a/pjmedia/src/pjmedia-audiodev/alsa_dev.c b/pjmedia/src/pjmedia-audiodev/alsa_dev.c index 0e5272cc35..efcffaa1fb 100755 --- a/pjmedia/src/pjmedia-audiodev/alsa_dev.c +++ b/pjmedia/src/pjmedia-audiodev/alsa_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2007-2009 Keystream AB and Konftel AB, All rights reserved. @@ -37,22 +36,22 @@ #include -#define THIS_FILE "alsa_dev.c" -#define ALSA_DEVICE_NAME "plughw:%d,%d" -#define ALSASOUND_PLAYBACK 1 -#define ALSASOUND_CAPTURE 2 -#define MAX_SOUND_CARDS 5 -#define MAX_SOUND_DEVICES_PER_CARD 5 -#define MAX_DEVICES 32 +#define THIS_FILE "alsa_dev.c" +#define ALSA_DEVICE_NAME "plughw:%d,%d" +#define ALSASOUND_PLAYBACK 1 +#define ALSASOUND_CAPTURE 2 +#define MAX_SOUND_CARDS 5 +#define MAX_SOUND_DEVICES_PER_CARD 5 +#define MAX_DEVICES 32 #define MAX_MIX_NAME_LEN 64 /* Set to 1 to enable tracing */ -#define ENABLE_TRACING 0 +#define ENABLE_TRACING 0 #if ENABLE_TRACING -# define TRACE_(expr) PJ_LOG(5,expr) +# define TRACE_(expr) PJ_LOG(5,expr) #else -# define TRACE_(expr) +# define TRACE_(expr) #endif /* @@ -63,29 +62,29 @@ static pj_status_t alsa_factory_destroy(pjmedia_aud_dev_factory *f); static pj_status_t alsa_factory_refresh(pjmedia_aud_dev_factory *f); static unsigned alsa_factory_get_dev_count(pjmedia_aud_dev_factory *f); static pj_status_t alsa_factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); + unsigned index, + pjmedia_aud_dev_info *info); static pj_status_t alsa_factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); + unsigned index, + pjmedia_aud_param *param); static pj_status_t alsa_factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_strm); + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_strm); /* * Stream prototypes */ static pj_status_t alsa_stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); + pjmedia_aud_param *param); static pj_status_t alsa_stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); + pjmedia_aud_dev_cap cap, + void *value); static pj_status_t alsa_stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); + pjmedia_aud_dev_cap cap, + const void *value); static pj_status_t alsa_stream_start(pjmedia_aud_stream *strm); static pj_status_t alsa_stream_stop(pjmedia_aud_stream *strm); static pj_status_t alsa_stream_destroy(pjmedia_aud_stream *strm); @@ -93,44 +92,44 @@ static pj_status_t alsa_stream_destroy(pjmedia_aud_stream *strm); struct alsa_factory { - pjmedia_aud_dev_factory base; - pj_pool_factory *pf; - pj_pool_t *pool; - pj_pool_t *base_pool; + pjmedia_aud_dev_factory base; + pj_pool_factory *pf; + pj_pool_t *pool; + pj_pool_t *base_pool; - unsigned dev_cnt; - pjmedia_aud_dev_info devs[MAX_DEVICES]; + unsigned dev_cnt; + pjmedia_aud_dev_info devs[MAX_DEVICES]; char pb_mixer_name[MAX_MIX_NAME_LEN]; - char cap_mixer_name[MAX_MIX_NAME_LEN]; + char cap_mixer_name[MAX_MIX_NAME_LEN]; }; struct alsa_stream { - pjmedia_aud_stream base; + pjmedia_aud_stream base; /* Common */ - pj_pool_t *pool; + pj_pool_t *pool; struct alsa_factory *af; - void *user_data; - pjmedia_aud_param param; /* Running parameter */ - int rec_id; /* Capture device id */ + void *user_data; + pjmedia_aud_param param; /* Running parameter */ + int rec_id; /* Capture device id */ int quit; /* Playback */ - snd_pcm_t *pb_pcm; - snd_pcm_uframes_t pb_frames; /* samples_per_frame */ + snd_pcm_t *pb_pcm; + snd_pcm_uframes_t pb_frames; /* samples_per_frame */ pjmedia_aud_play_cb pb_cb; unsigned pb_buf_size; - char *pb_buf; - pj_thread_t *pb_thread; + char *pb_buf; + pj_thread_t *pb_thread; /* Capture */ - snd_pcm_t *ca_pcm; - snd_pcm_uframes_t ca_frames; /* samples_per_frame */ + snd_pcm_t *ca_pcm; + snd_pcm_uframes_t ca_frames; /* samples_per_frame */ pjmedia_aud_rec_cb ca_cb; unsigned ca_buf_size; - char *ca_buf; - pj_thread_t *ca_thread; + char *ca_buf; + pj_thread_t *ca_thread; }; static pjmedia_aud_dev_factory_op alsa_factory_op = @@ -156,11 +155,11 @@ static pjmedia_aud_stream_op alsa_stream_op = #if ENABLE_TRACING==0 static void null_alsa_error_handler (const char *file, - int line, - const char *function, - int err, - const char *fmt, - ...) + int line, + const char *function, + int err, + const char *fmt, + ...) { PJ_UNUSED_ARG(file); PJ_UNUSED_ARG(line); @@ -171,11 +170,11 @@ static void null_alsa_error_handler (const char *file, #endif static void alsa_error_handler (const char *file, - int line, - const char *function, - int err, - const char *fmt, - ...) + int line, + const char *function, + int err, + const char *fmt, + ...) { char err_msg[128]; int index, len; @@ -183,32 +182,32 @@ static void alsa_error_handler (const char *file, #ifndef NDEBUG index = snprintf (err_msg, sizeof(err_msg), "ALSA lib %s:%i:(%s) ", - file, line, function); + file, line, function); #else index = snprintf (err_msg, sizeof(err_msg), "ALSA lib: "); #endif if (index < 1 || index >= (int)sizeof(err_msg)) { - index = sizeof(err_msg)-1; - err_msg[index] = '\0'; - goto print_msg; + index = sizeof(err_msg)-1; + err_msg[index] = '\0'; + goto print_msg; } va_start (arg, fmt); if (index < sizeof(err_msg)-1) { - len = vsnprintf( err_msg+index, sizeof(err_msg)-index, fmt, arg); - if (len < 1 || len >= (int)sizeof(err_msg)-index) - len = sizeof(err_msg)-index-1; - index += len; - err_msg[index] = '\0'; + len = vsnprintf( err_msg+index, sizeof(err_msg)-index, fmt, arg); + if (len < 1 || len >= (int)sizeof(err_msg)-index) + len = sizeof(err_msg)-index-1; + index += len; + err_msg[index] = '\0'; } va_end(arg); if (err && index < sizeof(err_msg)-1) { - len = snprintf( err_msg+index, sizeof(err_msg)-index, ": %s", - snd_strerror(err)); - if (len < 1 || len >= (int)sizeof(err_msg)-index) - len = sizeof(err_msg)-index-1; - index += len; - err_msg[index] = '\0'; + len = snprintf( err_msg+index, sizeof(err_msg)-index, ": %s", + snd_strerror(err)); + if (len < 1 || len >= (int)sizeof(err_msg)-index) + len = sizeof(err_msg)-index-1; + index += len; + err_msg[index] = '\0'; } print_msg: PJ_LOG (4,(THIS_FILE, "%s", err_msg)); @@ -222,7 +221,7 @@ static pj_status_t add_dev (struct alsa_factory *af, const char *dev_name) int pb_result, ca_result; if (af->dev_cnt >= PJ_ARRAY_SIZE(af->devs)) - return PJ_ETOOMANY; + return PJ_ETOOMANY; adi = &af->devs[af->dev_cnt]; @@ -231,28 +230,28 @@ static pj_status_t add_dev (struct alsa_factory *af, const char *dev_name) /* Try to open the device in playback mode */ pb_result = snd_pcm_open (&pcm, dev_name, SND_PCM_STREAM_PLAYBACK, 0); if (pb_result >= 0) { - TRACE_((THIS_FILE, "Try to open the device for playback - success")); - snd_pcm_close (pcm); + TRACE_((THIS_FILE, "Try to open the device for playback - success")); + snd_pcm_close (pcm); } else { - TRACE_((THIS_FILE, "Try to open the device for playback - failure")); + TRACE_((THIS_FILE, "Try to open the device for playback - failure")); } /* Try to open the device in capture mode */ ca_result = snd_pcm_open (&pcm, dev_name, SND_PCM_STREAM_CAPTURE, 0); if (ca_result >= 0) { - TRACE_((THIS_FILE, "Try to open the device for capture - success")); - snd_pcm_close (pcm); + TRACE_((THIS_FILE, "Try to open the device for capture - success")); + snd_pcm_close (pcm); } else { - TRACE_((THIS_FILE, "Try to open the device for capture - failure")); + TRACE_((THIS_FILE, "Try to open the device for capture - failure")); } /* Check if the device could be opened in playback or capture mode */ if (pb_result<0 && ca_result<0) { - TRACE_((THIS_FILE, "Unable to open sound device %s, setting " - "in/out channel count to 0", dev_name)); - /* Set I/O channel counts to 0 to indicate unavailable device */ - adi->output_count = 0; - adi->input_count = 0; + TRACE_((THIS_FILE, "Unable to open sound device %s, setting " + "in/out channel count to 0", dev_name)); + /* Set I/O channel counts to 0 to indicate unavailable device */ + adi->output_count = 0; + adi->input_count = 0; } /* Reset device info */ @@ -286,25 +285,25 @@ static void get_mixer_name(struct alsa_factory *af) snd_mixer_elem_t *elem; if (snd_mixer_open(&handle, 0) < 0) - return; + return; if (snd_mixer_attach(handle, "default") < 0) { - snd_mixer_close(handle); - return; + snd_mixer_close(handle); + return; } if (snd_mixer_selem_register(handle, NULL, NULL) < 0) { - snd_mixer_close(handle); - return; + snd_mixer_close(handle); + return; } if (snd_mixer_load(handle) < 0) { - snd_mixer_close(handle); - return; + snd_mixer_close(handle); + return; } for (elem = snd_mixer_first_elem(handle); elem; - elem = snd_mixer_elem_next(elem)) + elem = snd_mixer_elem_next(elem)) { const char* elemname; elemname = snd_mixer_selem_get_name(elem); @@ -313,10 +312,10 @@ static void get_mixer_name(struct alsa_factory *af) if (snd_mixer_selem_has_playback_volume(elem)) { pj_ansi_strncpy(af->pb_mixer_name, elemname, - sizeof(af->pb_mixer_name)); + sizeof(af->pb_mixer_name)); af->pb_mixer_name[sizeof(af->pb_mixer_name)-1] = 0; TRACE_((THIS_FILE, "Playback mixer name: %s", - af->pb_mixer_name)); + af->pb_mixer_name)); } if (snd_mixer_selem_has_capture_volume(elem)) { @@ -324,7 +323,7 @@ static void get_mixer_name(struct alsa_factory *af) sizeof(af->cap_mixer_name)); af->cap_mixer_name[sizeof(af->cap_mixer_name)-1] = 0; TRACE_((THIS_FILE, "Capture mixer name: %s", - af->cap_mixer_name)); + af->cap_mixer_name)); } } } @@ -353,7 +352,7 @@ static pj_status_t alsa_factory_init(pjmedia_aud_dev_factory *f) { pj_status_t status = alsa_factory_refresh(f); if (PJ_SUCCESS != status) - return status; + return status; PJ_LOG(4,(THIS_FILE, "ALSA initialized")); return PJ_SUCCESS; @@ -366,12 +365,12 @@ static pj_status_t alsa_factory_destroy(pjmedia_aud_dev_factory *f) struct alsa_factory *af = (struct alsa_factory*)f; if (af->pool) - pj_pool_release(af->pool); + pj_pool_release(af->pool); if (af->base_pool) { - pj_pool_t *pool = af->base_pool; - af->base_pool = NULL; - pj_pool_release(pool); + pj_pool_t *pool = af->base_pool; + af->base_pool = NULL; + pj_pool_release(pool); } /* Restore handler */ @@ -391,8 +390,8 @@ static pj_status_t alsa_factory_refresh(pjmedia_aud_dev_factory *f) TRACE_((THIS_FILE, "pjmedia_snd_init: Enumerate sound devices")); if (af->pool != NULL) { - pj_pool_release(af->pool); - af->pool = NULL; + pj_pool_release(af->pool); + af->pool = NULL; } af->pool = pj_pool_create(af->pf, "alsa_aud", 256, 256, NULL); @@ -401,7 +400,7 @@ static pj_status_t alsa_factory_refresh(pjmedia_aud_dev_factory *f) /* Enumerate sound devices */ err = snd_device_name_hint(-1, "pcm", (void***)&hints); if (err != 0) - return PJMEDIA_EAUD_SYSERR; + return PJMEDIA_EAUD_SYSERR; #if ENABLE_TRACING snd_lib_error_set_handler(alsa_error_handler); @@ -412,13 +411,13 @@ static pj_status_t alsa_factory_refresh(pjmedia_aud_dev_factory *f) n = hints; while (*n != NULL) { - char *name = snd_device_name_get_hint(*n, "NAME"); - if (name != NULL) { - if (0 != strcmp("null", name)) - add_dev(af, name); - free(name); - } - n++; + char *name = snd_device_name_get_hint(*n, "NAME"); + if (name != NULL) { + if (0 != strcmp("null", name)) + add_dev(af, name); + free(name); + } + n++; } /* Get the mixer name */ @@ -447,8 +446,8 @@ static unsigned alsa_factory_get_dev_count(pjmedia_aud_dev_factory *f) /* API: get device info */ static pj_status_t alsa_factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info) + unsigned index, + pjmedia_aud_dev_info *info) { struct alsa_factory *af = (struct alsa_factory*)f; @@ -456,17 +455,17 @@ static pj_status_t alsa_factory_get_dev_info(pjmedia_aud_dev_factory *f, pj_memcpy(info, &af->devs[index], sizeof(*info)); info->caps = PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING | - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; + PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY | + PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING | + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; return PJ_SUCCESS; } /* API: create default parameter */ static pj_status_t alsa_factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param) + unsigned index, + pjmedia_aud_param *param) { struct alsa_factory *af = (struct alsa_factory*)f; pjmedia_aud_dev_info *adi; @@ -477,19 +476,19 @@ static pj_status_t alsa_factory_default_param(pjmedia_aud_dev_factory *f, pj_bzero(param, sizeof(*param)); if (adi->input_count && adi->output_count) { - param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; - param->rec_id = index; - param->play_id = index; + param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; + param->rec_id = index; + param->play_id = index; } else if (adi->input_count) { - param->dir = PJMEDIA_DIR_CAPTURE; - param->rec_id = index; - param->play_id = PJMEDIA_AUD_INVALID_DEV; + param->dir = PJMEDIA_DIR_CAPTURE; + param->rec_id = index; + param->play_id = PJMEDIA_AUD_INVALID_DEV; } else if (adi->output_count) { - param->dir = PJMEDIA_DIR_PLAYBACK; - param->play_id = index; - param->rec_id = PJMEDIA_AUD_INVALID_DEV; + param->dir = PJMEDIA_DIR_PLAYBACK; + param->play_id = index; + param->rec_id = PJMEDIA_AUD_INVALID_DEV; } else { - return PJMEDIA_EAUD_INVDEV; + return PJMEDIA_EAUD_INVDEV; } param->clock_rate = adi->default_samples_per_sec; @@ -511,7 +510,7 @@ static int pb_thread_func (void *arg) int size = stream->pb_buf_size; snd_pcm_uframes_t nframes = stream->pb_frames; void* user_data = stream->user_data; - char* buf = stream->pb_buf; + char* buf = stream->pb_buf; pj_timestamp tstamp; int result; @@ -519,35 +518,35 @@ static int pb_thread_func (void *arg) tstamp.u64 = 0; TRACE_((THIS_FILE, "pb_thread_func(%u): Started", - (unsigned)syscall(SYS_gettid))); + (unsigned)syscall(SYS_gettid))); snd_pcm_prepare (pcm); while (!stream->quit) { - pjmedia_frame frame; - - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = buf; - frame.size = size; - frame.timestamp.u64 = tstamp.u64; - frame.bit_info = 0; - - result = stream->pb_cb (user_data, &frame); - if (result != PJ_SUCCESS || stream->quit) - break; - - if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) - pj_bzero (buf, size); - - result = snd_pcm_writei (pcm, buf, nframes); - if (result == -EPIPE) { - PJ_LOG (4,(THIS_FILE, "pb_thread_func: underrun!")); - snd_pcm_prepare (pcm); - } else if (result < 0) { - PJ_LOG (4,(THIS_FILE, "pb_thread_func: error writing data!")); - } - - tstamp.u64 += nframes; + pjmedia_frame frame; + + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = buf; + frame.size = size; + frame.timestamp.u64 = tstamp.u64; + frame.bit_info = 0; + + result = stream->pb_cb (user_data, &frame); + if (result != PJ_SUCCESS || stream->quit) + break; + + if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) + pj_bzero (buf, size); + + result = snd_pcm_writei (pcm, buf, nframes); + if (result == -EPIPE) { + PJ_LOG (4,(THIS_FILE, "pb_thread_func: underrun!")); + snd_pcm_prepare (pcm); + } else if (result < 0) { + PJ_LOG (4,(THIS_FILE, "pb_thread_func: error writing data!")); + } + + tstamp.u64 += nframes; } snd_pcm_drop(pcm); @@ -564,7 +563,7 @@ static int ca_thread_func (void *arg) int size = stream->ca_buf_size; snd_pcm_uframes_t nframes = stream->ca_frames; void* user_data = stream->user_data; - char* buf = stream->ca_buf; + char* buf = stream->ca_buf; pj_timestamp tstamp; int result; struct sched_param param; @@ -573,53 +572,53 @@ static int ca_thread_func (void *arg) thid = (pthread_t*) pj_thread_get_os_handle (pj_thread_this()); param.sched_priority = sched_get_priority_max (SCHED_RR); PJ_LOG (5,(THIS_FILE, "ca_thread_func(%u): Set thread priority " - "for audio capture thread.", - (unsigned)syscall(SYS_gettid))); + "for audio capture thread.", + (unsigned)syscall(SYS_gettid))); result = pthread_setschedparam (*thid, SCHED_RR, ¶m); if (result) { - if (result == EPERM) - PJ_LOG (5,(THIS_FILE, "Unable to increase thread priority, " - "root access needed.")); - else - PJ_LOG (5,(THIS_FILE, "Unable to increase thread priority, " - "error: %d", - result)); + if (result == EPERM) + PJ_LOG (5,(THIS_FILE, "Unable to increase thread priority, " + "root access needed.")); + else + PJ_LOG (5,(THIS_FILE, "Unable to increase thread priority, " + "error: %d", + result)); } pj_bzero (buf, size); tstamp.u64 = 0; TRACE_((THIS_FILE, "ca_thread_func(%u): Started", - (unsigned)syscall(SYS_gettid))); + (unsigned)syscall(SYS_gettid))); snd_pcm_prepare (pcm); while (!stream->quit) { - pjmedia_frame frame; - - pj_bzero (buf, size); - result = snd_pcm_readi (pcm, buf, nframes); - if (result == -EPIPE) { - PJ_LOG (4,(THIS_FILE, "ca_thread_func: overrun!")); - snd_pcm_prepare (pcm); - continue; - } else if (result < 0) { - PJ_LOG (4,(THIS_FILE, "ca_thread_func: error reading data!")); - } - if (stream->quit) - break; - - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = (void*) buf; - frame.size = size; - frame.timestamp.u64 = tstamp.u64; - frame.bit_info = 0; - - result = stream->ca_cb (user_data, &frame); - if (result != PJ_SUCCESS || stream->quit) - break; - - tstamp.u64 += nframes; + pjmedia_frame frame; + + pj_bzero (buf, size); + result = snd_pcm_readi (pcm, buf, nframes); + if (result == -EPIPE) { + PJ_LOG (4,(THIS_FILE, "ca_thread_func: overrun!")); + snd_pcm_prepare (pcm); + continue; + } else if (result < 0) { + PJ_LOG (4,(THIS_FILE, "ca_thread_func: error reading data!")); + } + if (stream->quit) + break; + + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = (void*) buf; + frame.size = size; + frame.timestamp.u64 = tstamp.u64; + frame.bit_info = 0; + + result = stream->ca_cb (user_data, &frame); + if (result != PJ_SUCCESS || stream->quit) + break; + + tstamp.u64 += nframes; } snd_pcm_drop(pcm); TRACE_((THIS_FILE, "ca_thread_func: Stopped")); @@ -629,7 +628,7 @@ static int ca_thread_func (void *arg) static pj_status_t open_playback (struct alsa_stream* stream, - const pjmedia_aud_param *param) + const pjmedia_aud_param *param) { snd_pcm_hw_params_t* params; snd_pcm_format_t format; @@ -639,17 +638,17 @@ static pj_status_t open_playback (struct alsa_stream* stream, snd_pcm_uframes_t tmp_period_size; if (param->play_id < 0 || param->play_id >= stream->af->dev_cnt) - return PJMEDIA_EAUD_INVDEV; + return PJMEDIA_EAUD_INVDEV; /* Open PCM for playback */ PJ_LOG (5,(THIS_FILE, "open_playback: Open playback device '%s'", - stream->af->devs[param->play_id].name)); + stream->af->devs[param->play_id].name)); result = snd_pcm_open (&stream->pb_pcm, - stream->af->devs[param->play_id].name, - SND_PCM_STREAM_PLAYBACK, - 0); + stream->af->devs[param->play_id].name, + SND_PCM_STREAM_PLAYBACK, + 0); if (result < 0) - return PJMEDIA_EAUD_SYSERR; + return PJMEDIA_EAUD_SYSERR; /* Allocate a hardware parameters object. */ snd_pcm_hw_params_alloca (¶ms); @@ -659,44 +658,44 @@ static pj_status_t open_playback (struct alsa_stream* stream, /* Set interleaved mode */ snd_pcm_hw_params_set_access (stream->pb_pcm, params, - SND_PCM_ACCESS_RW_INTERLEAVED); + SND_PCM_ACCESS_RW_INTERLEAVED); /* Set format */ switch (param->bits_per_sample) { case 8: - TRACE_((THIS_FILE, "open_playback: set format SND_PCM_FORMAT_S8")); - format = SND_PCM_FORMAT_S8; - break; + TRACE_((THIS_FILE, "open_playback: set format SND_PCM_FORMAT_S8")); + format = SND_PCM_FORMAT_S8; + break; case 16: - TRACE_((THIS_FILE, "open_playback: set format SND_PCM_FORMAT_S16_LE")); - format = SND_PCM_FORMAT_S16_LE; - break; + TRACE_((THIS_FILE, "open_playback: set format SND_PCM_FORMAT_S16_LE")); + format = SND_PCM_FORMAT_S16_LE; + break; case 24: - TRACE_((THIS_FILE, "open_playback: set format SND_PCM_FORMAT_S24_LE")); - format = SND_PCM_FORMAT_S24_LE; - break; + TRACE_((THIS_FILE, "open_playback: set format SND_PCM_FORMAT_S24_LE")); + format = SND_PCM_FORMAT_S24_LE; + break; case 32: - TRACE_((THIS_FILE, "open_playback: set format SND_PCM_FORMAT_S32_LE")); - format = SND_PCM_FORMAT_S32_LE; - break; + TRACE_((THIS_FILE, "open_playback: set format SND_PCM_FORMAT_S32_LE")); + format = SND_PCM_FORMAT_S32_LE; + break; default: - TRACE_((THIS_FILE, "open_playback: set format SND_PCM_FORMAT_S16_LE")); - format = SND_PCM_FORMAT_S16_LE; - break; + TRACE_((THIS_FILE, "open_playback: set format SND_PCM_FORMAT_S16_LE")); + format = SND_PCM_FORMAT_S16_LE; + break; } snd_pcm_hw_params_set_format (stream->pb_pcm, params, format); /* Set number of channels */ TRACE_((THIS_FILE, "open_playback: set channels: %d", - param->channel_count)); + param->channel_count)); result = snd_pcm_hw_params_set_channels (stream->pb_pcm, params, - param->channel_count); + param->channel_count); if (result < 0) { - PJ_LOG (3,(THIS_FILE, "Unable to set a channel count of %d for " - "playback device '%s'", param->channel_count, - stream->af->devs[param->play_id].name)); - snd_pcm_close (stream->pb_pcm); - return PJMEDIA_EAUD_SYSERR; + PJ_LOG (3,(THIS_FILE, "Unable to set a channel count of %d for " + "playback device '%s'", param->channel_count, + stream->af->devs[param->play_id].name)); + snd_pcm_close (stream->pb_pcm); + return PJMEDIA_EAUD_SYSERR; } /* Set clock rate */ @@ -707,67 +706,67 @@ static pj_status_t open_playback (struct alsa_stream* stream, /* Set period size to samples_per_frame frames. */ stream->pb_frames = (snd_pcm_uframes_t) param->samples_per_frame / - param->channel_count; + param->channel_count; TRACE_((THIS_FILE, "open_playback: set period size: %d", - stream->pb_frames)); + stream->pb_frames)); tmp_period_size = stream->pb_frames; snd_pcm_hw_params_set_period_size_near (stream->pb_pcm, params, - &tmp_period_size, NULL); + &tmp_period_size, NULL); /* Commenting this as it may cause the number of samples per frame * to be incorrest. */ // stream->pb_frames = tmp_period_size > stream->pb_frames ? - // tmp_period_size : stream->pb_frames; + // tmp_period_size : stream->pb_frames; TRACE_((THIS_FILE, "open_playback: period size set to: %d", - tmp_period_size)); + tmp_period_size)); /* Set the sound device buffer size and latency */ if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY) - tmp_buf_size = (rate / 1000) * param->output_latency_ms; + tmp_buf_size = (rate / 1000) * param->output_latency_ms; else - tmp_buf_size = (rate / 1000) * PJMEDIA_SND_DEFAULT_PLAY_LATENCY; + tmp_buf_size = (rate / 1000) * PJMEDIA_SND_DEFAULT_PLAY_LATENCY; if (tmp_buf_size < tmp_period_size * 2) tmp_buf_size = tmp_period_size * 2; snd_pcm_hw_params_set_buffer_size_near (stream->pb_pcm, params, - &tmp_buf_size); + &tmp_buf_size); stream->param.output_latency_ms = tmp_buf_size / (rate / 1000); /* Set our buffer */ stream->pb_buf_size = stream->pb_frames * param->channel_count * - (param->bits_per_sample/8); + (param->bits_per_sample/8); stream->pb_buf = (char*) pj_pool_alloc(stream->pool, stream->pb_buf_size); TRACE_((THIS_FILE, "open_playback: buffer size set to: %d", - (int)tmp_buf_size)); + (int)tmp_buf_size)); TRACE_((THIS_FILE, "open_playback: playback_latency set to: %d ms", - (int)stream->param.output_latency_ms)); + (int)stream->param.output_latency_ms)); /* Activate the parameters */ result = snd_pcm_hw_params (stream->pb_pcm, params); if (result < 0) { - snd_pcm_close (stream->pb_pcm); - return PJMEDIA_EAUD_SYSERR; + snd_pcm_close (stream->pb_pcm); + return PJMEDIA_EAUD_SYSERR; } if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { - alsa_stream_set_cap(&stream->base, - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - ¶m->output_vol); + alsa_stream_set_cap(&stream->base, + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + ¶m->output_vol); } PJ_LOG (5,(THIS_FILE, "Opened device alsa(%s) for playing, sample rate=%d" - ", ch=%d, bits=%d, period size=%d frames, latency=%d ms", - stream->af->devs[param->play_id].name, - rate, param->channel_count, - param->bits_per_sample, stream->pb_frames, - (int)stream->param.output_latency_ms)); + ", ch=%d, bits=%d, period size=%d frames, latency=%d ms", + stream->af->devs[param->play_id].name, + rate, param->channel_count, + param->bits_per_sample, stream->pb_frames, + (int)stream->param.output_latency_ms)); return PJ_SUCCESS; } static pj_status_t open_capture (struct alsa_stream* stream, - const pjmedia_aud_param *param) + const pjmedia_aud_param *param) { snd_pcm_hw_params_t* params; snd_pcm_format_t format; @@ -777,17 +776,17 @@ static pj_status_t open_capture (struct alsa_stream* stream, snd_pcm_uframes_t tmp_period_size; if (param->rec_id < 0 || param->rec_id >= stream->af->dev_cnt) - return PJMEDIA_EAUD_INVDEV; + return PJMEDIA_EAUD_INVDEV; /* Open PCM for capture */ PJ_LOG (5,(THIS_FILE, "open_capture: Open capture device '%s'", - stream->af->devs[param->rec_id].name)); + stream->af->devs[param->rec_id].name)); result = snd_pcm_open (&stream->ca_pcm, - stream->af->devs[param->rec_id].name, - SND_PCM_STREAM_CAPTURE, - 0); + stream->af->devs[param->rec_id].name, + SND_PCM_STREAM_CAPTURE, + 0); if (result < 0) - return PJMEDIA_EAUD_SYSERR; + return PJMEDIA_EAUD_SYSERR; /* Allocate a hardware parameters object. */ snd_pcm_hw_params_alloca (¶ms); @@ -797,44 +796,44 @@ static pj_status_t open_capture (struct alsa_stream* stream, /* Set interleaved mode */ snd_pcm_hw_params_set_access (stream->ca_pcm, params, - SND_PCM_ACCESS_RW_INTERLEAVED); + SND_PCM_ACCESS_RW_INTERLEAVED); /* Set format */ switch (param->bits_per_sample) { case 8: - TRACE_((THIS_FILE, "open_capture: set format SND_PCM_FORMAT_S8")); - format = SND_PCM_FORMAT_S8; - break; + TRACE_((THIS_FILE, "open_capture: set format SND_PCM_FORMAT_S8")); + format = SND_PCM_FORMAT_S8; + break; case 16: - TRACE_((THIS_FILE, "open_capture: set format SND_PCM_FORMAT_S16_LE")); - format = SND_PCM_FORMAT_S16_LE; - break; + TRACE_((THIS_FILE, "open_capture: set format SND_PCM_FORMAT_S16_LE")); + format = SND_PCM_FORMAT_S16_LE; + break; case 24: - TRACE_((THIS_FILE, "open_capture: set format SND_PCM_FORMAT_S24_LE")); - format = SND_PCM_FORMAT_S24_LE; - break; + TRACE_((THIS_FILE, "open_capture: set format SND_PCM_FORMAT_S24_LE")); + format = SND_PCM_FORMAT_S24_LE; + break; case 32: - TRACE_((THIS_FILE, "open_capture: set format SND_PCM_FORMAT_S32_LE")); - format = SND_PCM_FORMAT_S32_LE; - break; + TRACE_((THIS_FILE, "open_capture: set format SND_PCM_FORMAT_S32_LE")); + format = SND_PCM_FORMAT_S32_LE; + break; default: - TRACE_((THIS_FILE, "open_capture: set format SND_PCM_FORMAT_S16_LE")); - format = SND_PCM_FORMAT_S16_LE; - break; + TRACE_((THIS_FILE, "open_capture: set format SND_PCM_FORMAT_S16_LE")); + format = SND_PCM_FORMAT_S16_LE; + break; } snd_pcm_hw_params_set_format (stream->ca_pcm, params, format); /* Set number of channels */ TRACE_((THIS_FILE, "open_capture: set channels: %d", - param->channel_count)); + param->channel_count)); result = snd_pcm_hw_params_set_channels (stream->ca_pcm, params, - param->channel_count); + param->channel_count); if (result < 0) { - PJ_LOG (3,(THIS_FILE, "Unable to set a channel count of %d for " - "capture device '%s'", param->channel_count, - stream->af->devs[param->rec_id].name)); - snd_pcm_close (stream->ca_pcm); - return PJMEDIA_EAUD_SYSERR; + PJ_LOG (3,(THIS_FILE, "Unable to set a channel count of %d for " + "capture device '%s'", param->channel_count, + stream->af->devs[param->rec_id].name)); + snd_pcm_close (stream->ca_pcm); + return PJMEDIA_EAUD_SYSERR; } /* Set clock rate */ @@ -845,60 +844,60 @@ static pj_status_t open_capture (struct alsa_stream* stream, /* Set period size to samples_per_frame frames. */ stream->ca_frames = (snd_pcm_uframes_t) param->samples_per_frame / - param->channel_count; + param->channel_count; TRACE_((THIS_FILE, "open_capture: set period size: %d", - stream->ca_frames)); + stream->ca_frames)); tmp_period_size = stream->ca_frames; snd_pcm_hw_params_set_period_size_near (stream->ca_pcm, params, - &tmp_period_size, NULL); + &tmp_period_size, NULL); /* Commenting this as it may cause the number of samples per frame * to be incorrest. */ // stream->ca_frames = tmp_period_size > stream->ca_frames ? - // tmp_period_size : stream->ca_frames; + // tmp_period_size : stream->ca_frames; TRACE_((THIS_FILE, "open_capture: period size set to: %d", - tmp_period_size)); + tmp_period_size)); /* Set the sound device buffer size and latency */ if (param->flags & PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY) - tmp_buf_size = (rate / 1000) * param->input_latency_ms; + tmp_buf_size = (rate / 1000) * param->input_latency_ms; else - tmp_buf_size = (rate / 1000) * PJMEDIA_SND_DEFAULT_REC_LATENCY; + tmp_buf_size = (rate / 1000) * PJMEDIA_SND_DEFAULT_REC_LATENCY; if (tmp_buf_size < tmp_period_size * 2) tmp_buf_size = tmp_period_size * 2; snd_pcm_hw_params_set_buffer_size_near (stream->ca_pcm, params, - &tmp_buf_size); + &tmp_buf_size); stream->param.input_latency_ms = tmp_buf_size / (rate / 1000); /* Set our buffer */ stream->ca_buf_size = stream->ca_frames * param->channel_count * - (param->bits_per_sample/8); + (param->bits_per_sample/8); stream->ca_buf = (char*) pj_pool_alloc (stream->pool, stream->ca_buf_size); TRACE_((THIS_FILE, "open_capture: buffer size set to: %d", - (int)tmp_buf_size)); + (int)tmp_buf_size)); TRACE_((THIS_FILE, "open_capture: capture_latency set to: %d ms", - (int)stream->param.input_latency_ms)); + (int)stream->param.input_latency_ms)); /* Activate the parameters */ result = snd_pcm_hw_params (stream->ca_pcm, params); if (result < 0) { - snd_pcm_close (stream->ca_pcm); - return PJMEDIA_EAUD_SYSERR; + snd_pcm_close (stream->ca_pcm); + return PJMEDIA_EAUD_SYSERR; } if (param->flags & PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING) { - alsa_stream_set_cap(&stream->base, - PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING, - ¶m->input_vol); + alsa_stream_set_cap(&stream->base, + PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING, + ¶m->input_vol); } PJ_LOG (5,(THIS_FILE, "Opened device alsa(%s) for capture, sample rate=%d" - ", ch=%d, bits=%d, period size=%d frames, latency=%d ms", - stream->af->devs[param->rec_id].name, - rate, param->channel_count, - param->bits_per_sample, stream->ca_frames, - (int)stream->param.input_latency_ms)); + ", ch=%d, bits=%d, period size=%d frames, latency=%d ms", + stream->af->devs[param->rec_id].name, + rate, param->channel_count, + param->bits_per_sample, stream->ca_frames, + (int)stream->param.input_latency_ms)); return PJ_SUCCESS; } @@ -906,11 +905,11 @@ static pj_status_t open_capture (struct alsa_stream* stream, /* API: create stream */ static pj_status_t alsa_factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_strm) { struct alsa_factory *af = (struct alsa_factory*)f; pj_status_t status; @@ -919,13 +918,13 @@ static pj_status_t alsa_factory_create_stream(pjmedia_aud_dev_factory *f, pool = pj_pool_create (af->pf, "alsa%p", 1024, 1024, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Allocate and initialize comon stream data */ stream = PJ_POOL_ZALLOC_T (pool, struct alsa_stream); stream->base.op = &alsa_stream_op; stream->pool = pool; - stream->af = af; + stream->af = af; stream->user_data = user_data; stream->pb_cb = play_cb; stream->ca_cb = rec_cb; @@ -934,22 +933,22 @@ static pj_status_t alsa_factory_create_stream(pjmedia_aud_dev_factory *f, /* Init playback */ if (param->dir & PJMEDIA_DIR_PLAYBACK) { - status = open_playback (stream, param); - if (status != PJ_SUCCESS) { - pj_pool_release (pool); - return status; - } + status = open_playback (stream, param); + if (status != PJ_SUCCESS) { + pj_pool_release (pool); + return status; + } } /* Init capture */ if (param->dir & PJMEDIA_DIR_CAPTURE) { - status = open_capture (stream, param); - if (status != PJ_SUCCESS) { - if (param->dir & PJMEDIA_DIR_PLAYBACK) - snd_pcm_close (stream->pb_pcm); - pj_pool_release (pool); - return status; - } + status = open_capture (stream, param); + if (status != PJ_SUCCESS) { + if (param->dir & PJMEDIA_DIR_PLAYBACK) + snd_pcm_close (stream->pb_pcm); + pj_pool_release (pool); + return status; + } } *p_strm = &stream->base; @@ -959,7 +958,7 @@ static pj_status_t alsa_factory_create_stream(pjmedia_aud_dev_factory *f, /* API: get running parameter */ static pj_status_t alsa_stream_get_param(pjmedia_aud_stream *s, - pjmedia_aud_param *pi) + pjmedia_aud_param *pi) { struct alsa_stream *stream = (struct alsa_stream*)s; @@ -973,90 +972,90 @@ static pj_status_t alsa_stream_get_param(pjmedia_aud_stream *s, /* API: get capability */ static pj_status_t alsa_stream_get_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - void *pval) + pjmedia_aud_dev_cap cap, + void *pval) { struct alsa_stream *stream = (struct alsa_stream*)s; PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); if (cap==PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY && - (stream->param.dir & PJMEDIA_DIR_CAPTURE)) + (stream->param.dir & PJMEDIA_DIR_CAPTURE)) { - /* Recording latency */ - *(unsigned*)pval = stream->param.input_latency_ms; - return PJ_SUCCESS; + /* Recording latency */ + *(unsigned*)pval = stream->param.input_latency_ms; + return PJ_SUCCESS; } else if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY && - (stream->param.dir & PJMEDIA_DIR_PLAYBACK)) + (stream->param.dir & PJMEDIA_DIR_PLAYBACK)) { - /* Playback latency */ - *(unsigned*)pval = stream->param.output_latency_ms; - return PJ_SUCCESS; + /* Playback latency */ + *(unsigned*)pval = stream->param.output_latency_ms; + return PJ_SUCCESS; } else { - return PJMEDIA_EAUD_INVCAP; + return PJMEDIA_EAUD_INVCAP; } } /* API: set capability */ static pj_status_t alsa_stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value) + pjmedia_aud_dev_cap cap, + const void *value) { struct alsa_factory *af = ((struct alsa_stream*)strm)->af; if ((cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING && - pj_ansi_strlen(af->pb_mixer_name)) || - (cap==PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING && - pj_ansi_strlen(af->cap_mixer_name))) + pj_ansi_strlen(af->pb_mixer_name)) || + (cap==PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING && + pj_ansi_strlen(af->cap_mixer_name))) { - pj_ssize_t min, max; - snd_mixer_t *handle; - snd_mixer_selem_id_t *sid; - snd_mixer_elem_t* elem; - unsigned vol = *(unsigned*)value; - - if (snd_mixer_open(&handle, 0) < 0) - return PJMEDIA_EAUD_SYSERR; - - if (snd_mixer_attach(handle, "default") < 0) - return PJMEDIA_EAUD_SYSERR; - - if (snd_mixer_selem_register(handle, NULL, NULL) < 0) - return PJMEDIA_EAUD_SYSERR; - - if (snd_mixer_load(handle) < 0) - return PJMEDIA_EAUD_SYSERR; - - snd_mixer_selem_id_alloca(&sid); - snd_mixer_selem_id_set_index(sid, 0); - if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) - snd_mixer_selem_id_set_name(sid, af->pb_mixer_name); - else if (cap==PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING) - snd_mixer_selem_id_set_name(sid, af->cap_mixer_name); - - elem = snd_mixer_find_selem(handle, sid); - if (!elem) - return PJMEDIA_EAUD_SYSERR; - - if (cap == PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { - snd_mixer_selem_get_playback_volume_range(elem, &min, &max); - if (snd_mixer_selem_set_playback_volume_all(elem, - vol * max / 100) < 0) - { - return PJMEDIA_EAUD_SYSERR; - } - } else if (cap == PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING) { + pj_ssize_t min, max; + snd_mixer_t *handle; + snd_mixer_selem_id_t *sid; + snd_mixer_elem_t* elem; + unsigned vol = *(unsigned*)value; + + if (snd_mixer_open(&handle, 0) < 0) + return PJMEDIA_EAUD_SYSERR; + + if (snd_mixer_attach(handle, "default") < 0) + return PJMEDIA_EAUD_SYSERR; + + if (snd_mixer_selem_register(handle, NULL, NULL) < 0) + return PJMEDIA_EAUD_SYSERR; + + if (snd_mixer_load(handle) < 0) + return PJMEDIA_EAUD_SYSERR; + + snd_mixer_selem_id_alloca(&sid); + snd_mixer_selem_id_set_index(sid, 0); + if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) + snd_mixer_selem_id_set_name(sid, af->pb_mixer_name); + else if (cap==PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING) + snd_mixer_selem_id_set_name(sid, af->cap_mixer_name); + + elem = snd_mixer_find_selem(handle, sid); + if (!elem) + return PJMEDIA_EAUD_SYSERR; + + if (cap == PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { + snd_mixer_selem_get_playback_volume_range(elem, &min, &max); + if (snd_mixer_selem_set_playback_volume_all(elem, + vol * max / 100) < 0) + { + return PJMEDIA_EAUD_SYSERR; + } + } else if (cap == PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING) { snd_mixer_selem_get_capture_volume_range(elem, &min, &max); - if (snd_mixer_selem_set_capture_volume_all(elem, - vol * max / 100) < 0) - { - return PJMEDIA_EAUD_SYSERR; - } - } - - snd_mixer_close(handle); - return PJ_SUCCESS; + if (snd_mixer_selem_set_capture_volume_all(elem, + vol * max / 100) < 0) + { + return PJMEDIA_EAUD_SYSERR; + } + } + + snd_mixer_close(handle); + return PJ_SUCCESS; } return PJMEDIA_EAUD_INVCAP; @@ -1071,31 +1070,31 @@ static pj_status_t alsa_stream_start (pjmedia_aud_stream *s) stream->quit = 0; if (stream->param.dir & PJMEDIA_DIR_PLAYBACK) { - status = pj_thread_create (stream->pool, - "alsasound_playback", - pb_thread_func, - stream, - 0, //ZERO, - 0, - &stream->pb_thread); - if (status != PJ_SUCCESS) - return status; + status = pj_thread_create (stream->pool, + "alsasound_playback", + pb_thread_func, + stream, + 0, //ZERO, + 0, + &stream->pb_thread); + if (status != PJ_SUCCESS) + return status; } if (stream->param.dir & PJMEDIA_DIR_CAPTURE) { - status = pj_thread_create (stream->pool, - "alsasound_playback", - ca_thread_func, - stream, - 0, //ZERO, - 0, - &stream->ca_thread); - if (status != PJ_SUCCESS) { - stream->quit = PJ_TRUE; - pj_thread_join(stream->pb_thread); - pj_thread_destroy(stream->pb_thread); - stream->pb_thread = NULL; - } + status = pj_thread_create (stream->pool, + "alsasound_playback", + ca_thread_func, + stream, + 0, //ZERO, + 0, + &stream->ca_thread); + if (status != PJ_SUCCESS) { + stream->quit = PJ_TRUE; + pj_thread_join(stream->pb_thread); + pj_thread_destroy(stream->pb_thread); + stream->pb_thread = NULL; + } } return status; @@ -1110,27 +1109,27 @@ static pj_status_t alsa_stream_stop (pjmedia_aud_stream *s) stream->quit = 1; if (stream->pb_thread) { - TRACE_((THIS_FILE, - "alsa_stream_stop(%u): Waiting for playback to stop.", - (unsigned)syscall(SYS_gettid))); - pj_thread_join (stream->pb_thread); - TRACE_((THIS_FILE, - "alsa_stream_stop(%u): playback stopped.", - (unsigned)syscall(SYS_gettid))); - pj_thread_destroy(stream->pb_thread); - stream->pb_thread = NULL; + TRACE_((THIS_FILE, + "alsa_stream_stop(%u): Waiting for playback to stop.", + (unsigned)syscall(SYS_gettid))); + pj_thread_join (stream->pb_thread); + TRACE_((THIS_FILE, + "alsa_stream_stop(%u): playback stopped.", + (unsigned)syscall(SYS_gettid))); + pj_thread_destroy(stream->pb_thread); + stream->pb_thread = NULL; } if (stream->ca_thread) { - TRACE_((THIS_FILE, - "alsa_stream_stop(%u): Waiting for capture to stop.", - (unsigned)syscall(SYS_gettid))); - pj_thread_join (stream->ca_thread); - TRACE_((THIS_FILE, - "alsa_stream_stop(%u): capture stopped.", - (unsigned)syscall(SYS_gettid))); - pj_thread_destroy(stream->ca_thread); - stream->ca_thread = NULL; + TRACE_((THIS_FILE, + "alsa_stream_stop(%u): Waiting for capture to stop.", + (unsigned)syscall(SYS_gettid))); + pj_thread_join (stream->ca_thread); + TRACE_((THIS_FILE, + "alsa_stream_stop(%u): capture stopped.", + (unsigned)syscall(SYS_gettid))); + pj_thread_destroy(stream->ca_thread); + stream->ca_thread = NULL; } return PJ_SUCCESS; @@ -1145,12 +1144,12 @@ static pj_status_t alsa_stream_destroy (pjmedia_aud_stream *s) alsa_stream_stop (s); if (stream->param.dir & PJMEDIA_DIR_PLAYBACK) { - snd_pcm_close (stream->pb_pcm); - stream->pb_pcm = NULL; + snd_pcm_close (stream->pb_pcm); + stream->pb_pcm = NULL; } if (stream->param.dir & PJMEDIA_DIR_CAPTURE) { - snd_pcm_close (stream->ca_pcm); - stream->ca_pcm = NULL; + snd_pcm_close (stream->ca_pcm); + stream->ca_pcm = NULL; } pj_pool_release (stream->pool); @@ -1158,4 +1157,4 @@ static pj_status_t alsa_stream_destroy (pjmedia_aud_stream *s) return PJ_SUCCESS; } -#endif /* PJMEDIA_AUDIO_DEV_HAS_ALSA */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_ALSA */ diff --git a/pjmedia/src/pjmedia-audiodev/android/PjAudioDevInfo.java b/pjmedia/src/pjmedia-audiodev/android/PjAudioDevInfo.java index 387819d30f..3d89d402c5 100644 --- a/pjmedia/src/pjmedia-audiodev/android/PjAudioDevInfo.java +++ b/pjmedia/src/pjmedia-audiodev/android/PjAudioDevInfo.java @@ -37,45 +37,45 @@ public class PjAudioDevInfo { public static int GetCount() { - return devices.size(); + return devices.size(); } public static PjAudioDevInfo GetInfo(int idx) { - return devices.valueAt(idx); + return devices.valueAt(idx); } public static void RefreshDevices(Context context) { - devices = new SparseArray<>(); + devices = new SparseArray<>(); /* Default device */ - PjAudioDevInfo pj_adi = new PjAudioDevInfo(); - pj_adi.id = 0; - pj_adi.name = "Default"; - pj_adi.direction = 3; - devices.put(0, pj_adi); - - /* Enumerate devices (for API level 23 or later) */ - if (android.os.Build.VERSION.SDK_INT < 23) - return; - - AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); - AudioDeviceInfo[] devs = am.getDevices(AudioManager.GET_DEVICES_ALL); - Log.i("Oboe", "Enumerating AudioManager devices.."); - for (AudioDeviceInfo adi: devs) { - LogDevInfo(adi); - - pj_adi = new PjAudioDevInfo(); - pj_adi.id = adi.getId(); - pj_adi.name = DevTypeStr(adi.getType()) + " - " + adi.getProductName().toString(); - pj_adi.direction = 0; - if (adi.isSource()) pj_adi.direction |= 1; - if (adi.isSink()) pj_adi.direction |= 2; - pj_adi.supportedChannelCounts = adi.getChannelCounts(); - pj_adi.supportedClockRates = adi.getSampleRates(); - devices.put(adi.getId(), pj_adi); - } + PjAudioDevInfo pj_adi = new PjAudioDevInfo(); + pj_adi.id = 0; + pj_adi.name = "Default"; + pj_adi.direction = 3; + devices.put(0, pj_adi); + + /* Enumerate devices (for API level 23 or later) */ + if (android.os.Build.VERSION.SDK_INT < 23) + return; + + AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); + AudioDeviceInfo[] devs = am.getDevices(AudioManager.GET_DEVICES_ALL); + Log.i("Oboe", "Enumerating AudioManager devices.."); + for (AudioDeviceInfo adi: devs) { + LogDevInfo(adi); + + pj_adi = new PjAudioDevInfo(); + pj_adi.id = adi.getId(); + pj_adi.name = DevTypeStr(adi.getType()) + " - " + adi.getProductName().toString(); + pj_adi.direction = 0; + if (adi.isSource()) pj_adi.direction |= 1; + if (adi.isSink()) pj_adi.direction |= 2; + pj_adi.supportedChannelCounts = adi.getChannelCounts(); + pj_adi.supportedClockRates = adi.getSampleRates(); + devices.put(adi.getId(), pj_adi); + } } /* Private members */ @@ -83,85 +83,85 @@ public static void RefreshDevices(Context context) private static SparseArray devices; private static String DevTypeStr(int type) { - if (android.os.Build.VERSION.SDK_INT < 23) - return "Unknown"; - - /* - if (android.os.Build.VERSION.SDK_INT > 30) { - if (type == AudioDeviceInfo.TYPE_BLE_HEADSET) - return "BLE Headset"; - if (type == AudioDeviceInfo.TYPE_BLE_SPEAKER) - return "BLE Speaker"; - } - */ - - switch (type) { - case AudioDeviceInfo.TYPE_BUILTIN_EARPIECE: - return "Builtin Earpiece"; - case AudioDeviceInfo.TYPE_BUILTIN_SPEAKER: - return "Builtin Speaker"; - case AudioDeviceInfo.TYPE_WIRED_HEADSET: - return "Wired Headset"; - case AudioDeviceInfo.TYPE_WIRED_HEADPHONES: - return "Wired Headphones"; - case AudioDeviceInfo.TYPE_LINE_ANALOG: - return "Line Analog"; - case AudioDeviceInfo.TYPE_LINE_DIGITAL: - return "Line Digital"; - case AudioDeviceInfo.TYPE_BLUETOOTH_SCO: - return "Bluetooth SCO"; - case AudioDeviceInfo.TYPE_BLUETOOTH_A2DP: - return "Bluetooth A2DP"; - case AudioDeviceInfo.TYPE_HDMI: - return "HDMI"; - case AudioDeviceInfo.TYPE_HDMI_ARC: - return "HDMI ARC"; - case AudioDeviceInfo.TYPE_USB_DEVICE: - return "USB Device"; - case AudioDeviceInfo.TYPE_USB_ACCESSORY: - return "USB Accessory"; - case AudioDeviceInfo.TYPE_DOCK: - return "Dock"; - case AudioDeviceInfo.TYPE_FM: - return "FM"; - case AudioDeviceInfo.TYPE_BUILTIN_MIC: - return "Builtin Mic"; - case AudioDeviceInfo.TYPE_FM_TUNER: - return "FM Tuner"; - case AudioDeviceInfo.TYPE_TV_TUNER: - return "TV Tuner"; - case AudioDeviceInfo.TYPE_TELEPHONY: - return "Telephony"; - case AudioDeviceInfo.TYPE_AUX_LINE: - return "AUX Line"; - case AudioDeviceInfo.TYPE_IP: - return "IP"; - case AudioDeviceInfo.TYPE_BUS: - return "Bus"; - case AudioDeviceInfo.TYPE_USB_HEADSET: - return "USB Headset"; - default: - return "Unknown ("+ type +")"; - } + if (android.os.Build.VERSION.SDK_INT < 23) + return "Unknown"; + + /* + if (android.os.Build.VERSION.SDK_INT > 30) { + if (type == AudioDeviceInfo.TYPE_BLE_HEADSET) + return "BLE Headset"; + if (type == AudioDeviceInfo.TYPE_BLE_SPEAKER) + return "BLE Speaker"; + } + */ + + switch (type) { + case AudioDeviceInfo.TYPE_BUILTIN_EARPIECE: + return "Builtin Earpiece"; + case AudioDeviceInfo.TYPE_BUILTIN_SPEAKER: + return "Builtin Speaker"; + case AudioDeviceInfo.TYPE_WIRED_HEADSET: + return "Wired Headset"; + case AudioDeviceInfo.TYPE_WIRED_HEADPHONES: + return "Wired Headphones"; + case AudioDeviceInfo.TYPE_LINE_ANALOG: + return "Line Analog"; + case AudioDeviceInfo.TYPE_LINE_DIGITAL: + return "Line Digital"; + case AudioDeviceInfo.TYPE_BLUETOOTH_SCO: + return "Bluetooth SCO"; + case AudioDeviceInfo.TYPE_BLUETOOTH_A2DP: + return "Bluetooth A2DP"; + case AudioDeviceInfo.TYPE_HDMI: + return "HDMI"; + case AudioDeviceInfo.TYPE_HDMI_ARC: + return "HDMI ARC"; + case AudioDeviceInfo.TYPE_USB_DEVICE: + return "USB Device"; + case AudioDeviceInfo.TYPE_USB_ACCESSORY: + return "USB Accessory"; + case AudioDeviceInfo.TYPE_DOCK: + return "Dock"; + case AudioDeviceInfo.TYPE_FM: + return "FM"; + case AudioDeviceInfo.TYPE_BUILTIN_MIC: + return "Builtin Mic"; + case AudioDeviceInfo.TYPE_FM_TUNER: + return "FM Tuner"; + case AudioDeviceInfo.TYPE_TV_TUNER: + return "TV Tuner"; + case AudioDeviceInfo.TYPE_TELEPHONY: + return "Telephony"; + case AudioDeviceInfo.TYPE_AUX_LINE: + return "AUX Line"; + case AudioDeviceInfo.TYPE_IP: + return "IP"; + case AudioDeviceInfo.TYPE_BUS: + return "Bus"; + case AudioDeviceInfo.TYPE_USB_HEADSET: + return "USB Headset"; + default: + return "Unknown ("+ type +")"; + } } private static void LogDevInfo(AudioDeviceInfo adi) { - if (Build.VERSION.SDK_INT < 23) - return; - - StringBuilder info = new StringBuilder(); - info.append("id=").append(adi.getId()); - info.append(","); - if (adi.isSource()) info.append(" in"); - if (adi.isSink()) info.append(" out"); - info.append(", ").append(DevTypeStr(adi.getType())); - if (adi.getChannelCounts().length > 0) { - info.append(", channels=").append(Arrays.toString(adi.getChannelCounts())); - } - if (adi.getSampleRates().length > 0) { - info.append(", clock rates=").append(Arrays.toString(adi.getSampleRates())); - } - Log.i("Oboe", info.toString()); + if (Build.VERSION.SDK_INT < 23) + return; + + StringBuilder info = new StringBuilder(); + info.append("id=").append(adi.getId()); + info.append(","); + if (adi.isSource()) info.append(" in"); + if (adi.isSink()) info.append(" out"); + info.append(", ").append(DevTypeStr(adi.getType())); + if (adi.getChannelCounts().length > 0) { + info.append(", channels=").append(Arrays.toString(adi.getChannelCounts())); + } + if (adi.getSampleRates().length > 0) { + info.append(", clock rates=").append(Arrays.toString(adi.getSampleRates())); + } + Log.i("Oboe", info.toString()); } } diff --git a/pjmedia/src/pjmedia-audiodev/android_jni_dev.c b/pjmedia/src/pjmedia-audiodev/android_jni_dev.c index 6be317816a..80ff8a02a1 100644 --- a/pjmedia/src/pjmedia-audiodev/android_jni_dev.c +++ b/pjmedia/src/pjmedia-audiodev/android_jni_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2012-2012 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr) @@ -37,8 +36,8 @@ #include #include -#define THIS_FILE "android_jni_dev.c" -#define DRIVER_NAME "Android JNI" +#define THIS_FILE "android_jni_dev.c" +#define DRIVER_NAME "Android JNI" struct android_aud_factory { @@ -143,10 +142,10 @@ static pjmedia_aud_stream_op android_strm_op = PJ_DECL(pj_bool_t) pj_jni_attach_jvm(JNIEnv **jni_env); PJ_DECL(void) pj_jni_dettach_jvm(pj_bool_t attached); -#define attach_jvm(jni_env) pj_jni_attach_jvm(jni_env) -#define detach_jvm(attached) pj_jni_dettach_jvm(attached) -#define THREAD_PRIORITY_AUDIO -16 -#define THREAD_PRIORITY_URGENT_AUDIO -19 +#define attach_jvm(jni_env) pj_jni_attach_jvm(jni_env) +#define detach_jvm(attached) pj_jni_dettach_jvm(attached) +#define THREAD_PRIORITY_AUDIO -16 +#define THREAD_PRIORITY_URGENT_AUDIO -19 static int AndroidRecorderCallback(void *userData) @@ -221,9 +220,9 @@ static int AndroidRecorderCallback(void *userData) status = (*stream->rec_cb)(stream->user_data, &frame); (*jni_env)->ReleaseByteArrayElements(jni_env, inputBuffer, buf, - JNI_ABORT); - if (status != PJ_SUCCESS || stream->quit_flag) - break; + JNI_ABORT); + if (status != PJ_SUCCESS || stream->quit_flag) + break; stream->rec_timestamp.u64 += stream->param.samples_per_frame / stream->param.channel_count; @@ -311,7 +310,7 @@ static int AndroidTrackCallback(void *userData) pj_bzero(frame.buf, frame.size); (*jni_env)->ReleaseByteArrayElements(jni_env, outputBuffer, buf, - JNI_COMMIT); + JNI_COMMIT); /* Write to the device output. */ bytesWritten = (*jni_env)->CallIntMethod(jni_env, stream->track, @@ -408,7 +407,7 @@ static pj_status_t android_get_dev_info(pjmedia_aud_dev_factory *f, pj_ansi_strcpy(info->name, "Android JNI"); info->default_samples_per_sec = 8000; info->caps = PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING | - PJMEDIA_AUD_DEV_CAP_INPUT_SOURCE; + PJMEDIA_AUD_DEV_CAP_INPUT_SOURCE; info->input_count = 1; info->output_count = 1; info->routes = PJMEDIA_AUD_DEV_ROUTE_CUSTOM; @@ -426,7 +425,7 @@ static pj_status_t android_default_param(pjmedia_aud_dev_factory *f, status = android_get_dev_info(f, index, &adi); if (status != PJ_SUCCESS) - return status; + return status; pj_bzero(param, sizeof(*param)); if (adi.input_count && adi.output_count) { @@ -592,11 +591,11 @@ static pj_status_t android_create_stream(pjmedia_aud_dev_factory *f, jobject record_obj; int mic_source = 0; /* DEFAULT: default audio source */ - if ((param->flags & PJMEDIA_AUD_DEV_CAP_INPUT_SOURCE) && - (param->input_route & PJMEDIA_AUD_DEV_ROUTE_CUSTOM)) - { - mic_source = param->input_route & ~PJMEDIA_AUD_DEV_ROUTE_CUSTOM; - } + if ((param->flags & PJMEDIA_AUD_DEV_CAP_INPUT_SOURCE) && + (param->input_route & PJMEDIA_AUD_DEV_ROUTE_CUSTOM)) + { + mic_source = param->input_route & ~PJMEDIA_AUD_DEV_ROUTE_CUSTOM; + } /* Get pointer to the constructor */ constructor_method = (*jni_env)->GetMethodID(jni_env, @@ -611,9 +610,9 @@ static pj_status_t android_create_stream(pjmedia_aud_dev_factory *f, if (mic_source == 0) { /* Android-L (android-21) removes __system_property_get * from the NDK. - */ - /* - char sdk_version[PROP_VALUE_MAX]; + */ + /* + char sdk_version[PROP_VALUE_MAX]; pj_str_t pj_sdk_version; int sdk_v; @@ -744,7 +743,7 @@ static pj_status_t android_create_stream(pjmedia_aud_dev_factory *f, stream->track = (*jni_env)->NewGlobalRef(jni_env, track_obj); if (stream->track == 0) { jmethodID release_method=0; - + release_method = (*jni_env)->GetMethodID(jni_env, stream->track_class, "release", "()V"); @@ -786,7 +785,7 @@ static pj_status_t android_create_stream(pjmedia_aud_dev_factory *f, } if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { - strm_set_cap(&stream->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + strm_set_cap(&stream->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, ¶m->output_vol); } @@ -832,7 +831,7 @@ static pj_status_t strm_get_cap(pjmedia_aud_stream *s, PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING && - (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) + (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) { } @@ -851,7 +850,7 @@ static pj_status_t strm_set_cap(pjmedia_aud_stream *s, PJ_ASSERT_RETURN(s && value, PJ_EINVAL); if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING && - (stream->param.dir & PJMEDIA_DIR_PLAYBACK)) + (stream->param.dir & PJMEDIA_DIR_PLAYBACK)) { if (stream->track) { jmethodID vol_method = 0; @@ -951,8 +950,8 @@ static pj_status_t strm_destroy(pjmedia_aud_stream *s) PJ_LOG(4, (THIS_FILE, "Audio record released")); } if (stream->record_class) { - (*jni_env)->DeleteGlobalRef(jni_env, stream->record_class); - stream->record_class = NULL; + (*jni_env)->DeleteGlobalRef(jni_env, stream->record_class); + stream->record_class = NULL; } if (stream->track) { @@ -979,8 +978,8 @@ static pj_status_t strm_destroy(pjmedia_aud_stream *s) PJ_LOG(4, (THIS_FILE, "Audio track released")); } if (stream->track_class) { - (*jni_env)->DeleteGlobalRef(jni_env, stream->track_class); - stream->track_class = NULL; + (*jni_env)->DeleteGlobalRef(jni_env, stream->track_class); + stream->track_class = NULL; } pj_pool_release(stream->pool); @@ -990,4 +989,4 @@ static pj_status_t strm_destroy(pjmedia_aud_stream *s) return PJ_SUCCESS; } -#endif /* PJMEDIA_AUDIO_DEV_HAS_ANDROID_JNI */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_ANDROID_JNI */ diff --git a/pjmedia/src/pjmedia-audiodev/audiodev.c b/pjmedia/src/pjmedia-audiodev/audiodev.c index 2fd5568e1d..5d3a7938e5 100644 --- a/pjmedia/src/pjmedia-audiodev/audiodev.c +++ b/pjmedia/src/pjmedia-audiodev/audiodev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -92,13 +91,13 @@ PJ_DEF(pj_status_t) pjmedia_aud_subsys_init(pj_pool_factory *pf) * number of shutdown(). */ if (aud_subsys->init_count++ != 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Register error subsystem */ status = pj_register_strerror(PJMEDIA_AUDIODEV_ERRNO_START, - PJ_ERRNO_SPACE_SIZE, - &pjmedia_audiodev_strerror); + PJ_ERRNO_SPACE_SIZE, + &pjmedia_audiodev_strerror); pj_assert(status == PJ_SUCCESS); /* Init */ @@ -152,11 +151,11 @@ PJ_DEF(pj_status_t) pjmedia_aud_subsys_init(pj_pool_factory *pf) /* Initialize each factory and build the device ID list */ for (i=0; idrv_cnt; ++i) { - status = pjmedia_aud_driver_init(i, PJ_FALSE); - if (status != PJ_SUCCESS) { - pjmedia_aud_driver_deinit(i); - continue; - } + status = pjmedia_aud_driver_init(i, PJ_FALSE); + if (status != PJ_SUCCESS) { + pjmedia_aud_driver_deinit(i); + continue; + } } return aud_subsys->dev_cnt ? PJ_SUCCESS : status; @@ -170,14 +169,14 @@ pjmedia_aud_register_factory(pjmedia_aud_dev_factory_create_func_ptr adf) pjmedia_aud_subsys *aud_subsys = pjmedia_get_aud_subsys(); if (aud_subsys->init_count == 0) - return PJMEDIA_EAUD_INIT; + return PJMEDIA_EAUD_INIT; aud_subsys->drv[aud_subsys->drv_cnt].create = adf; status = pjmedia_aud_driver_init(aud_subsys->drv_cnt, PJ_FALSE); if (status == PJ_SUCCESS) { - aud_subsys->drv_cnt++; + aud_subsys->drv_cnt++; } else { - pjmedia_aud_driver_deinit(aud_subsys->drv_cnt); + pjmedia_aud_driver_deinit(aud_subsys->drv_cnt); } return status; @@ -191,20 +190,20 @@ pjmedia_aud_unregister_factory(pjmedia_aud_dev_factory_create_func_ptr adf) pjmedia_aud_subsys *aud_subsys = pjmedia_get_aud_subsys(); if (aud_subsys->init_count == 0) - return PJMEDIA_EAUD_INIT; + return PJMEDIA_EAUD_INIT; for (i=0; idrv_cnt; ++i) { - pjmedia_aud_driver *drv = &aud_subsys->drv[i]; + pjmedia_aud_driver *drv = &aud_subsys->drv[i]; - if (drv->create == adf) { - for (j = drv->start_idx; j < drv->start_idx + drv->dev_cnt; j++) - { - aud_subsys->dev_list[j] = (pj_uint32_t)PJMEDIA_AUD_INVALID_DEV; - } + if (drv->create == adf) { + for (j = drv->start_idx; j < drv->start_idx + drv->dev_cnt; j++) + { + aud_subsys->dev_list[j] = (pj_uint32_t)PJMEDIA_AUD_INVALID_DEV; + } - pjmedia_aud_driver_deinit(i); - return PJ_SUCCESS; - } + pjmedia_aud_driver_deinit(i); + return PJ_SUCCESS; + } } return PJMEDIA_EAUD_ERR; @@ -227,16 +226,16 @@ PJ_DEF(pj_status_t) pjmedia_aud_subsys_shutdown(void) * number of init(). */ if (aud_subsys->init_count == 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } --aud_subsys->init_count; if (aud_subsys->init_count == 0) { - for (i=0; idrv_cnt; ++i) { - pjmedia_aud_driver_deinit(i); - } + for (i=0; idrv_cnt; ++i) { + pjmedia_aud_driver_deinit(i); + } - aud_subsys->pf = NULL; + aud_subsys->pf = NULL; } return PJ_SUCCESS; } diff --git a/pjmedia/src/pjmedia-audiodev/audiotest.c b/pjmedia/src/pjmedia-audiodev/audiotest.c index e874d569d4..d9f84ac866 100644 --- a/pjmedia/src/pjmedia-audiodev/audiotest.c +++ b/pjmedia/src/pjmedia-audiodev/audiotest.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -22,13 +21,13 @@ #include #include -#define THIS_FILE "audiotest.c" +#define THIS_FILE "audiotest.c" /* Test duration in msec */ -#define DURATION 10000 +#define DURATION 10000 /* Skip the first msec from the calculation */ -#define SKIP_DURATION 1000 +#define SKIP_DURATION 1000 /* Division helper */ #define DIV_ROUND_UP(a,b) (((a) + ((b) - 1)) / (b)) @@ -36,23 +35,23 @@ struct stream_data { - pj_uint32_t first_timestamp; - pj_uint32_t last_timestamp; + pj_uint32_t first_timestamp; + pj_uint32_t last_timestamp; pj_timestamp last_called; pj_math_stat delay; }; struct test_data { - pj_pool_t *pool; - const pjmedia_aud_param *param; - pjmedia_aud_test_results *result; - pj_bool_t running; - pj_bool_t has_error; - pj_mutex_t *mutex; - - struct stream_data capture_data; - struct stream_data playback_data; + pj_pool_t *pool; + const pjmedia_aud_param *param; + pjmedia_aud_test_results *result; + pj_bool_t running; + pj_bool_t has_error; + pj_mutex_t *mutex; + + struct stream_data capture_data; + struct stream_data playback_data; }; static pj_status_t play_cb(void *user_data, pjmedia_frame *frame) @@ -64,30 +63,30 @@ static pj_status_t play_cb(void *user_data, pjmedia_frame *frame) /* Skip frames when test is not started or test has finished */ if (!test_data->running) { - pj_bzero(frame->buf, frame->size); - pj_mutex_unlock(test_data->mutex); - return PJ_SUCCESS; + pj_bzero(frame->buf, frame->size); + pj_mutex_unlock(test_data->mutex); + return PJ_SUCCESS; } /* Save last timestamp seen (to calculate drift) */ strm_data->last_timestamp = frame->timestamp.u32.lo; if (strm_data->last_called.u64 == 0) { - /* Init vars. */ - pj_get_timestamp(&strm_data->last_called); - pj_math_stat_init(&strm_data->delay); - strm_data->first_timestamp = frame->timestamp.u32.lo; + /* Init vars. */ + pj_get_timestamp(&strm_data->last_called); + pj_math_stat_init(&strm_data->delay); + strm_data->first_timestamp = frame->timestamp.u32.lo; } else { - pj_timestamp now; - unsigned delay; + pj_timestamp now; + unsigned delay; - /* Calculate frame interval */ - pj_get_timestamp(&now); - delay = pj_elapsed_usec(&strm_data->last_called, &now); - strm_data->last_called = now; + /* Calculate frame interval */ + pj_get_timestamp(&now); + delay = pj_elapsed_usec(&strm_data->last_called, &now); + strm_data->last_called = now; - /* Update frame interval statistic */ - pj_math_stat_update(&strm_data->delay, delay); + /* Update frame interval statistic */ + pj_math_stat_update(&strm_data->delay, delay); } pj_bzero(frame->buf, frame->size); @@ -106,29 +105,29 @@ static pj_status_t rec_cb(void *user_data, pjmedia_frame *frame) /* Skip frames when test is not started or test has finished */ if (!test_data->running) { - pj_mutex_unlock(test_data->mutex); - return PJ_SUCCESS; + pj_mutex_unlock(test_data->mutex); + return PJ_SUCCESS; } /* Save last timestamp seen (to calculate drift) */ strm_data->last_timestamp = frame->timestamp.u32.lo; if (strm_data->last_called.u64 == 0) { - /* Init vars. */ - pj_get_timestamp(&strm_data->last_called); - pj_math_stat_init(&strm_data->delay); - strm_data->first_timestamp = frame->timestamp.u32.lo; + /* Init vars. */ + pj_get_timestamp(&strm_data->last_called); + pj_math_stat_init(&strm_data->delay); + strm_data->first_timestamp = frame->timestamp.u32.lo; } else { - pj_timestamp now; - unsigned delay; + pj_timestamp now; + unsigned delay; - /* Calculate frame interval */ - pj_get_timestamp(&now); - delay = pj_elapsed_usec(&strm_data->last_called, &now); - strm_data->last_called = now; + /* Calculate frame interval */ + pj_get_timestamp(&now); + delay = pj_elapsed_usec(&strm_data->last_called, &now); + strm_data->last_called = now; - /* Update frame interval statistic */ - pj_math_stat_update(&strm_data->delay, delay); + /* Update frame interval statistic */ + pj_math_stat_update(&strm_data->delay, delay); } pj_mutex_unlock(test_data->mutex); @@ -139,14 +138,14 @@ static void app_perror(const char *title, pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); + pj_strerror(status, errmsg, sizeof(errmsg)); printf( "%s: %s (err=%d)\n", - title, errmsg, status); + title, errmsg, status); } PJ_DEF(pj_status_t) pjmedia_aud_test( const pjmedia_aud_param *param, - pjmedia_aud_test_results *result) + pjmedia_aud_test_results *result) { pj_status_t status = PJ_SUCCESS; pjmedia_aud_stream *strm; @@ -161,17 +160,17 @@ PJ_DEF(pj_status_t) pjmedia_aud_test( const pjmedia_aud_param *param, test_data.result = result; test_data.pool = pj_pool_create(pjmedia_aud_subsys_get_pool_factory(), - "audtest", 1000, 1000, NULL); + "audtest", 1000, 1000, NULL); pj_mutex_create_simple(test_data.pool, "sndtest", &test_data.mutex); /* * Open device. */ status = pjmedia_aud_stream_create(test_data.param, &rec_cb, &play_cb, - &test_data, &strm); + &test_data, &strm); if (status != PJ_SUCCESS) { app_perror("Unable to open device", status); - pj_pool_release(test_data.pool); + pj_pool_release(test_data.pool); return status; } @@ -185,14 +184,14 @@ PJ_DEF(pj_status_t) pjmedia_aud_test( const pjmedia_aud_param *param, status = pjmedia_aud_stream_start(strm); if (status != PJ_SUCCESS) { app_perror("Unable to start capture stream", status); - pjmedia_aud_stream_destroy(strm); - pj_pool_release(test_data.pool); + pjmedia_aud_stream_destroy(strm); + pj_pool_release(test_data.pool); return status; } PJ_LOG(3,(THIS_FILE, - " Please wait while test is in progress (~%d secs)..", - (DURATION+SKIP_DURATION)/1000)); + " Please wait while test is in progress (~%d secs)..", + (DURATION+SKIP_DURATION)/1000)); /* Let the stream runs for few msec/sec to get stable result. * (capture normally begins with frames available simultaneously). @@ -240,28 +239,28 @@ PJ_DEF(pj_status_t) pjmedia_aud_test( const pjmedia_aud_param *param, /* Check drifting */ if (param->dir == PJMEDIA_DIR_CAPTURE_PLAYBACK) { - int play_diff, cap_diff, drift; + int play_diff, cap_diff, drift; - play_diff = test_data.playback_data.last_timestamp - - test_data.playback_data.first_timestamp; - cap_diff = test_data.capture_data.last_timestamp - - test_data.capture_data.first_timestamp; - drift = play_diff > cap_diff? play_diff - cap_diff : - cap_diff - play_diff; + play_diff = test_data.playback_data.last_timestamp - + test_data.playback_data.first_timestamp; + cap_diff = test_data.capture_data.last_timestamp - + test_data.capture_data.first_timestamp; + drift = play_diff > cap_diff? play_diff - cap_diff : + cap_diff - play_diff; - /* Allow one frame tolerance for clock drift detection */ - if (drift < (int)param->samples_per_frame) { - result->rec_drift_per_sec = 0; - } else { - unsigned msec_dur; + /* Allow one frame tolerance for clock drift detection */ + if (drift < (int)param->samples_per_frame) { + result->rec_drift_per_sec = 0; + } else { + unsigned msec_dur; - msec_dur = (test_data.capture_data.last_timestamp - - test_data.capture_data.first_timestamp) * 1000 / - test_data.param->clock_rate; + msec_dur = (test_data.capture_data.last_timestamp - + test_data.capture_data.first_timestamp) * 1000 / + test_data.param->clock_rate; - result->rec_drift_per_sec = drift * 1000 / msec_dur; + result->rec_drift_per_sec = drift * 1000 / msec_dur; - } + } } return test_data.has_error? PJ_EUNKNOWN : PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia-audiodev/bb10_dev.c b/pjmedia/src/pjmedia-audiodev/bb10_dev.c index 5a457a26f6..da09029f2f 100644 --- a/pjmedia/src/pjmedia-audiodev/bb10_dev.c +++ b/pjmedia/src/pjmedia-audiodev/bb10_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2012 Teluu Inc. (http://www.teluu.com) * @@ -35,7 +34,7 @@ #ifndef PJ_BBSDK_VER /* Format: 0xMMNNRR: MM: major, NN: minor, RR: revision */ -# define PJ_BBSDK_VER 0x100006 +# define PJ_BBSDK_VER 0x100006 #endif #include @@ -50,13 +49,13 @@ #endif -#define THIS_FILE "bb10_dev.c" -#define BB10_DEVICE_NAME "plughw:%d,%d" +#define THIS_FILE "bb10_dev.c" +#define BB10_DEVICE_NAME "plughw:%d,%d" /* Set to 1 to enable tracing */ #if 1 -# define TRACE_(expr) PJ_LOG(4,expr) +# define TRACE_(expr) PJ_LOG(4,expr) #else # define TRACE_(expr) #endif @@ -99,44 +98,44 @@ static pj_status_t bb10_stream_destroy(pjmedia_aud_stream *strm); struct bb10_factory { - pjmedia_aud_dev_factory base; - pj_pool_factory *pf; - pj_pool_t *pool; - pj_pool_t *base_pool; - unsigned dev_cnt; - pjmedia_aud_dev_info devs[1]; + pjmedia_aud_dev_factory base; + pj_pool_factory *pf; + pj_pool_t *pool; + pj_pool_t *base_pool; + unsigned dev_cnt; + pjmedia_aud_dev_info devs[1]; }; struct bb10_stream { - pjmedia_aud_stream base; + pjmedia_aud_stream base; /* Common */ - pj_pool_t *pool; + pj_pool_t *pool; struct bb10_factory *af; - void *user_data; - pjmedia_aud_param param; /* Running parameter */ - int rec_id; /* Capture device id */ + void *user_data; + pjmedia_aud_param param; /* Running parameter */ + int rec_id; /* Capture device id */ int quit; /* Playback */ unsigned int pb_ctrl_audio_manager_handle; - snd_pcm_t *pb_pcm; + snd_pcm_t *pb_pcm; unsigned int pb_audio_manager_handle; - unsigned long pb_frames; /* samples_per_frame */ + unsigned long pb_frames; /* samples_per_frame */ pjmedia_aud_play_cb pb_cb; unsigned pb_buf_size; - char *pb_buf; - pj_thread_t *pb_thread; + char *pb_buf; + pj_thread_t *pb_thread; /* Capture */ - snd_pcm_t *ca_pcm; + snd_pcm_t *ca_pcm; unsigned int ca_audio_manager_handle; - unsigned long ca_frames; /* samples_per_frame */ + unsigned long ca_frames; /* samples_per_frame */ pjmedia_aud_rec_cb ca_cb; unsigned ca_buf_size; - char *ca_buf; - pj_thread_t *ca_thread; + char *ca_buf; + pj_thread_t *ca_thread; }; static pjmedia_aud_dev_factory_op bb10_factory_op = @@ -184,8 +183,8 @@ static pj_status_t bb10_add_dev (struct bb10_factory *af) SND_PCM_OPEN_PLAYBACK)) >= 0) { - snd_pcm_close (pcm_handle); - audio_manager_free_handle(handle); + snd_pcm_close (pcm_handle); + audio_manager_free_handle(handle); } else { TRACE_((THIS_FILE, "Try to open the device for playback - failure")); } @@ -197,8 +196,8 @@ static pj_status_t bb10_add_dev (struct bb10_factory *af) SND_PCM_OPEN_CAPTURE)) >= 0) { - snd_pcm_close (pcm_handle); - audio_manager_free_handle(handle); + snd_pcm_close (pcm_handle); + audio_manager_free_handle(handle); } else { TRACE_((THIS_FILE, "Try to open the device for capture - failure")); @@ -386,13 +385,13 @@ static void close_play_pcm(struct bb10_stream *stream) stream->pb_pcm = NULL; if (stream->pb_audio_manager_handle != 0) { - audio_manager_free_handle(stream->pb_audio_manager_handle); - stream->pb_audio_manager_handle = 0; + audio_manager_free_handle(stream->pb_audio_manager_handle); + stream->pb_audio_manager_handle = 0; } if (stream->pb_ctrl_audio_manager_handle != 0) { - audio_manager_free_handle(stream->pb_ctrl_audio_manager_handle); - stream->pb_ctrl_audio_manager_handle = 0; + audio_manager_free_handle(stream->pb_ctrl_audio_manager_handle); + stream->pb_ctrl_audio_manager_handle = 0; } } } @@ -411,8 +410,8 @@ static void close_capture_pcm(struct bb10_stream *stream) stream->ca_pcm = NULL; if (stream->ca_audio_manager_handle != 0) { - audio_manager_free_handle(stream->ca_audio_manager_handle); - stream->ca_audio_manager_handle = 0; + audio_manager_free_handle(stream->ca_audio_manager_handle); + stream->ca_audio_manager_handle = 0; } } } @@ -431,10 +430,10 @@ static void flush_capture(struct bb10_stream *stream) static int pb_thread_func (void *arg) { struct bb10_stream* stream = (struct bb10_stream *) arg; - int size = stream->pb_buf_size; - unsigned long nframes = stream->pb_frames; - void *user_data = stream->user_data; - char *buf = stream->pb_buf; + int size = stream->pb_buf_size; + unsigned long nframes = stream->pb_frames; + void *user_data = stream->user_data; + char *buf = stream->pb_buf; pj_timestamp tstamp; int result = 0; int policy; @@ -443,8 +442,8 @@ static int pb_thread_func (void *arg) TRACE_((THIS_FILE, "pb_thread_func: size = %d ", size)); if (pthread_getschedparam(pthread_self(), &policy, ¶m) == 0) { - param.sched_priority = 18; - pthread_setschedparam (pthread_self(), policy, ¶m); + param.sched_priority = 18; + pthread_setschedparam (pthread_self(), policy, ¶m); } pj_bzero (buf, size); @@ -479,39 +478,39 @@ static int pb_thread_func (void *arg) /* Write 640 to play unit */ result = snd_pcm_plugin_write(stream->pb_pcm,buf,size); if (result != size || result < 0) { - /* either the write to output device has failed or not the - * full amount of bytes have been written. This usually happens - * when audio routing is being changed by another thread - * Use a status variable for reading the error - */ - snd_pcm_channel_status_t status; + /* either the write to output device has failed or not the + * full amount of bytes have been written. This usually happens + * when audio routing is being changed by another thread + * Use a status variable for reading the error + */ + snd_pcm_channel_status_t status; status.channel = SND_PCM_CHANNEL_PLAYBACK; if (snd_pcm_plugin_status (stream->pb_pcm, &status) < 0) { /* Call has failed nothing we can do except log and * continue */ - PJ_LOG(4,(THIS_FILE, - "underrun: playback channel status error")); + PJ_LOG(4,(THIS_FILE, + "underrun: playback channel status error")); } else { - /* The status of the error has been read - * RIM say these are expected so we can "re-prepare" the stream - */ - PJ_LOG(4,(THIS_FILE,"PLAY thread ERROR status = %d", - status.status)); - if (status.status == SND_PCM_STATUS_READY || - status.status == SND_PCM_STATUS_UNDERRUN || - status.status == SND_PCM_STATUS_ERROR || - status.status == SND_PCM_STATUS_CHANGE) - { - if (snd_pcm_plugin_prepare (stream->pb_pcm, - SND_PCM_CHANNEL_PLAYBACK) < 0) - { - PJ_LOG(4,(THIS_FILE, - "underrun: playback channel prepare error")); - } - } - } + /* The status of the error has been read + * RIM say these are expected so we can "re-prepare" the stream + */ + PJ_LOG(4,(THIS_FILE,"PLAY thread ERROR status = %d", + status.status)); + if (status.status == SND_PCM_STATUS_READY || + status.status == SND_PCM_STATUS_UNDERRUN || + status.status == SND_PCM_STATUS_ERROR || + status.status == SND_PCM_STATUS_CHANGE) + { + if (snd_pcm_plugin_prepare (stream->pb_pcm, + SND_PCM_CHANNEL_PLAYBACK) < 0) + { + PJ_LOG(4,(THIS_FILE, + "underrun: playback channel prepare error")); + } + } + } } - tstamp.u64 += nframes; + tstamp.u64 += nframes; } flush_play(stream); @@ -529,7 +528,7 @@ static int ca_thread_func (void *arg) unsigned long nframes = stream->ca_frames; void *user_data = stream->user_data; /* Buffer to fill for PJMEDIA */ - char *buf = stream->ca_buf; + char *buf = stream->ca_buf; pj_timestamp tstamp; int result; int policy; @@ -538,8 +537,8 @@ static int ca_thread_func (void *arg) TRACE_((THIS_FILE, "ca_thread_func: size = %d ", size)); if (pthread_getschedparam(pthread_self(), &policy, ¶m) == 0) { - param.sched_priority = 18; - pthread_setschedparam (pthread_self(), policy, ¶m); + param.sched_priority = 18; + pthread_setschedparam (pthread_self(), policy, ¶m); } pj_bzero (buf, size); @@ -570,30 +569,30 @@ static int ca_thread_func (void *arg) * correct but saves a potential underrun in PJMEDIA */ PJ_LOG (4,(THIS_FILE, - "snd_pcm_plugin_read ERROR read = %d required = %d", - result,size)); + "snd_pcm_plugin_read ERROR read = %d required = %d", + result,size)); snd_pcm_channel_status_t status; status.channel = SND_PCM_CHANNEL_CAPTURE; if ((result = snd_pcm_plugin_status (stream->ca_pcm, &status)) < 0) { - /* Should not fail but all we can do is continue */ - PJ_LOG(4,(THIS_FILE, "capture: snd_pcm_plugin_status ret = %d", - result)); + /* Should not fail but all we can do is continue */ + PJ_LOG(4,(THIS_FILE, "capture: snd_pcm_plugin_status ret = %d", + result)); } else { - /* RIM say these are the errors that we should "prepare" - * after */ - if (status.status == SND_PCM_STATUS_READY || - status.status == SND_PCM_STATUS_OVERRUN || - status.status == SND_PCM_STATUS_ERROR || - status.status == SND_PCM_STATUS_CHANGE) - { - if (snd_pcm_plugin_prepare (stream->ca_pcm, - SND_PCM_CHANNEL_CAPTURE) < 0) - { - PJ_LOG (4,(THIS_FILE, - "overrun: capture channel prepare error")); - } - } + /* RIM say these are the errors that we should "prepare" + * after */ + if (status.status == SND_PCM_STATUS_READY || + status.status == SND_PCM_STATUS_OVERRUN || + status.status == SND_PCM_STATUS_ERROR || + status.status == SND_PCM_STATUS_CHANGE) + { + if (snd_pcm_plugin_prepare (stream->ca_pcm, + SND_PCM_CHANNEL_CAPTURE) < 0) + { + PJ_LOG (4,(THIS_FILE, + "overrun: capture channel prepare error")); + } + } } } @@ -630,37 +629,37 @@ static pj_status_t bb10_initialize_playback_ctrl(struct bb10_stream *stream, int ret = PJ_SUCCESS; if (stream->pb_ctrl_audio_manager_handle == 0) { - /* lazy init an audio manager handle */ - ret = audio_manager_get_handle(AUDIO_TYPE_VOICE, 0, false, - &stream->pb_ctrl_audio_manager_handle); - if (ret != 0) { - TRACE_((THIS_FILE, "audio_manager_get_handle ret = %d",ret)); - return PJMEDIA_EAUD_SYSERR; - } + /* lazy init an audio manager handle */ + ret = audio_manager_get_handle(AUDIO_TYPE_VOICE, 0, false, + &stream->pb_ctrl_audio_manager_handle); + if (ret != 0) { + TRACE_((THIS_FILE, "audio_manager_get_handle ret = %d",ret)); + return PJMEDIA_EAUD_SYSERR; + } } /* Set for either speaker or earpiece */ if (speaker) { - ret = audio_manager_set_handle_type( - stream->pb_ctrl_audio_manager_handle, - AUDIO_TYPE_VIDEO_CHAT, - AUDIO_DEVICE_SPEAKER, - AUDIO_DEVICE_DEFAULT); + ret = audio_manager_set_handle_type( + stream->pb_ctrl_audio_manager_handle, + AUDIO_TYPE_VIDEO_CHAT, + AUDIO_DEVICE_SPEAKER, + AUDIO_DEVICE_DEFAULT); } else { - ret = audio_manager_set_handle_type( - stream->pb_ctrl_audio_manager_handle, - AUDIO_TYPE_VOICE, - AUDIO_DEVICE_DEFAULT, - AUDIO_DEVICE_DEFAULT); + ret = audio_manager_set_handle_type( + stream->pb_ctrl_audio_manager_handle, + AUDIO_TYPE_VOICE, + AUDIO_DEVICE_DEFAULT, + AUDIO_DEVICE_DEFAULT); } /* Make the routing selection stick even when earpeace is plugged in. * But this doesn't seem to work (tested on Q10 10.2.10 */ if (ret == 0) { - ret = audio_manager_set_handle_routing_conditions( - stream->pb_ctrl_audio_manager_handle, - SETTINGS_NEVER_RESET); + ret = audio_manager_set_handle_routing_conditions( + stream->pb_ctrl_audio_manager_handle, + SETTINGS_NEVER_RESET); } if (ret != 0) { @@ -675,15 +674,15 @@ static int32_t get_alsa_pcm_fmt(const pjmedia_aud_param *param) { switch (param->bits_per_sample) { case 8: - return SND_PCM_SFMT_S8; + return SND_PCM_SFMT_S8; case 16: - return SND_PCM_SFMT_S16_LE; + return SND_PCM_SFMT_S16_LE; case 24: - return SND_PCM_SFMT_S24_LE; + return SND_PCM_SFMT_S24_LE; case 32: - return SND_PCM_SFMT_S32_LE; + return SND_PCM_SFMT_S32_LE; default: - PJ_ASSERT_RETURN(!"Unsupported bits_per_frame", SND_PCM_SFMT_S16_LE); + PJ_ASSERT_RETURN(!"Unsupported bits_per_frame", SND_PCM_SFMT_S16_LE); } } @@ -708,7 +707,7 @@ static pj_status_t bb10_open_playback (struct bb10_stream *stream, * Echo cancellation built in */ if ((ret = audio_manager_snd_pcm_open_name( - AUDIO_TYPE_VIDEO_CHAT, + AUDIO_TYPE_VIDEO_CHAT, &stream->pb_pcm, &stream->pb_audio_manager_handle, (char*)"voice", SND_PCM_OPEN_PLAYBACK)) < 0) @@ -726,8 +725,8 @@ static pj_status_t bb10_open_playback (struct bb10_stream *stream, memset (&pi, 0, sizeof (pi)); pi.channel = SND_PCM_CHANNEL_PLAYBACK; if ((ret = snd_pcm_plugin_info (stream->pb_pcm, &pi)) < 0) { - TRACE_((THIS_FILE, "snd_pcm_plugin_info ret = %d", ret)); - return PJMEDIA_EAUD_SYSERR; + TRACE_((THIS_FILE, "snd_pcm_plugin_info ret = %d", ret)); + return PJMEDIA_EAUD_SYSERR; } memset (&pp, 0, sizeof (pp)); @@ -771,7 +770,7 @@ static pj_status_t bb10_open_playback (struct bb10_stream *stream, if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY) { tmp_buf_size = rate * param->output_latency_ms / 1000; } else { - tmp_buf_size = rate * PJMEDIA_SND_DEFAULT_PLAY_LATENCY / 1000; + tmp_buf_size = rate * PJMEDIA_SND_DEFAULT_PLAY_LATENCY / 1000; } /* Set period size to samples_per_frame frames. */ stream->pb_frames = param->samples_per_frame / param->channel_count; @@ -811,8 +810,8 @@ static pj_status_t bb10_open_capture (struct bb10_stream *stream, (char*)"voice", SND_PCM_OPEN_CAPTURE)) < 0) { - TRACE_((THIS_FILE, "audio_manager_snd_pcm_open_name ret = %d", ret)); - return PJMEDIA_EAUD_SYSERR; + TRACE_((THIS_FILE, "audio_manager_snd_pcm_open_name ret = %d", ret)); + return PJMEDIA_EAUD_SYSERR; } /* Required call from January 2013 gold OS release */ snd_pcm_plugin_set_disable (stream->ca_pcm, PLUGIN_DISABLE_MMAP); @@ -875,7 +874,7 @@ static pj_status_t bb10_open_capture (struct bb10_stream *stream, /* Set clock rate */ rate = param->clock_rate; stream->ca_frames = (unsigned long) param->samples_per_frame / - param->channel_count; + param->channel_count; /* Set the sound device buffer size and latency */ if (param->flags & PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY) { @@ -888,7 +887,7 @@ static pj_status_t bb10_open_capture (struct bb10_stream *stream, /* Set our buffer */ stream->ca_buf_size = stream->ca_frames * param->channel_count * - param->bits_per_sample / 8; + param->bits_per_sample / 8; stream->ca_buf = (char *)pj_pool_alloc (stream->pool, stream->ca_buf_size); TRACE_((THIS_FILE, "bb10_open_capture: ca_frames = %d clock = %d", @@ -919,7 +918,7 @@ static pj_status_t bb10_factory_create_stream(pjmedia_aud_dev_factory *f, stream = PJ_POOL_ZALLOC_T (pool, struct bb10_stream); stream->base.op = &bb10_stream_op; stream->pool = pool; - stream->af = af; + stream->af = af; stream->user_data = user_data; stream->pb_cb = play_cb; stream->ca_cb = rec_cb; @@ -949,19 +948,19 @@ static pj_status_t bb10_factory_create_stream(pjmedia_aud_dev_factory *f, /* Set the audio routing ONLY if app explicitly asks one */ if ((param->dir & PJMEDIA_DIR_PLAYBACK) && - (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE)) + (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE)) { - status = bb10_stream_set_cap(&stream->base, - PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, + status = bb10_stream_set_cap(&stream->base, + PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, ¶m->output_route); - if (status != PJ_SUCCESS) { - TRACE_((THIS_FILE, "Error setting output route")); - bb10_stream_destroy(&stream->base); - return status; - } + if (status != PJ_SUCCESS) { + TRACE_((THIS_FILE, "Error setting output route")); + bb10_stream_destroy(&stream->base); + return status; + } } else { - /* Legacy behavior: if none specified, set to speaker */ - status = bb10_initialize_playback_ctrl(stream, false); + /* Legacy behavior: if none specified, set to speaker */ + status = bb10_initialize_playback_ctrl(stream, false); } *p_strm = &stream->base; @@ -1013,11 +1012,11 @@ static pj_status_t bb10_stream_get_cap(pjmedia_aud_stream *s, return PJ_SUCCESS; } else if (cap==PJMEDIA_AUD_DEV_CAP_EC && - (stream->param.dir & PJMEDIA_DIR_CAPTURE)) + (stream->param.dir & PJMEDIA_DIR_CAPTURE)) { - /* EC is enablied implicitly by opening "voice" device */ - *(pj_bool_t*)pval = PJ_TRUE; - return PJ_SUCCESS; + /* EC is enablied implicitly by opening "voice" device */ + *(pj_bool_t*)pval = PJ_TRUE; + return PJ_SUCCESS; } else { return PJMEDIA_EAUD_INVCAP; } @@ -1038,56 +1037,56 @@ static pj_status_t bb10_stream_set_cap(pjmedia_aud_stream *strm, if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE && (stream->param.dir & PJMEDIA_DIR_PLAYBACK)) { - pjmedia_aud_dev_route route; - pj_bool_t need_restart; - pj_status_t ret; - - PJ_ASSERT_RETURN(value, PJ_EINVAL); - - /* OS 10.2.1 requires pausing audio stream */ - /* No longer necessary! - * See https://github.com/pjsip/pjproject/issues/1743 - */ - need_restart = PJ_FALSE; - /* - need_restart = (stream->pb_thread != NULL); - if (need_restart) { - PJ_LOG(4,(THIS_FILE, "pausing audio stream..")); - ret = bb10_stream_stop(strm); - if (ret != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, ret, "Error pausing stream")); - return ret; - } - } - */ - - route = *((pjmedia_aud_dev_route*)value); - PJ_LOG(4,(THIS_FILE, "setting audio route to %d..", route)); + pjmedia_aud_dev_route route; + pj_bool_t need_restart; + pj_status_t ret; + + PJ_ASSERT_RETURN(value, PJ_EINVAL); + + /* OS 10.2.1 requires pausing audio stream */ + /* No longer necessary! + * See https://github.com/pjsip/pjproject/issues/1743 + */ + need_restart = PJ_FALSE; + /* + need_restart = (stream->pb_thread != NULL); + if (need_restart) { + PJ_LOG(4,(THIS_FILE, "pausing audio stream..")); + ret = bb10_stream_stop(strm); + if (ret != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, ret, "Error pausing stream")); + return ret; + } + } + */ + + route = *((pjmedia_aud_dev_route*)value); + PJ_LOG(4,(THIS_FILE, "setting audio route to %d..", route)); /* Use the initialization function which lazy-inits the * handle for routing */ - if (route == PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER) { + if (route == PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER) { ret = bb10_initialize_playback_ctrl(stream,true); } else { ret = bb10_initialize_playback_ctrl(stream,false); } - if (need_restart) { - PJ_LOG(4,(THIS_FILE, "resuming audio stream..")); - ret = bb10_stream_start(strm); - if (ret != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, ret, "Error resuming stream")); - } - } + if (need_restart) { + PJ_LOG(4,(THIS_FILE, "resuming audio stream..")); + ret = bb10_stream_start(strm); + if (ret != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, ret, "Error resuming stream")); + } + } - return ret; + return ret; } else if (cap==PJMEDIA_AUD_DEV_CAP_EC && - (stream->param.dir & PJMEDIA_DIR_CAPTURE)) + (stream->param.dir & PJMEDIA_DIR_CAPTURE)) { - /* EC is always enabled. Silently ignore the request */ - return PJ_SUCCESS; + /* EC is always enabled. Silently ignore the request */ + return PJ_SUCCESS; } TRACE_((THIS_FILE,"bb10_stream_set_cap() = PJMEDIA_EAUD_INVCAP")); @@ -1104,24 +1103,24 @@ static pj_status_t bb10_stream_start (pjmedia_aud_stream *s) stream->quit = 0; if (stream->param.dir & PJMEDIA_DIR_PLAYBACK) { status = pj_thread_create (stream->pool, - "bb10sound_playback", - pb_thread_func, - stream, - 0, - 0, - &stream->pb_thread); + "bb10sound_playback", + pb_thread_func, + stream, + 0, + 0, + &stream->pb_thread); if (status != PJ_SUCCESS) return status; } if (stream->param.dir & PJMEDIA_DIR_CAPTURE) { status = pj_thread_create (stream->pool, - "bb10sound_playback", - ca_thread_func, - stream, - 0, - 0, - &stream->ca_thread); + "bb10sound_playback", + ca_thread_func, + stream, + 0, + 0, + &stream->ca_thread); if (status != PJ_SUCCESS) { stream->quit = PJ_TRUE; pj_thread_join(stream->pb_thread); @@ -1173,4 +1172,4 @@ static pj_status_t bb10_stream_destroy (pjmedia_aud_stream *s) return PJ_SUCCESS; } -#endif /* PJMEDIA_AUDIO_DEV_HAS_BB10 */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_BB10 */ diff --git a/pjmedia/src/pjmedia-audiodev/bdimad_dev.c b/pjmedia/src/pjmedia-audiodev/bdimad_dev.c index 9d7c3183b9..120c35d689 100644 --- a/pjmedia/src/pjmedia-audiodev/bdimad_dev.c +++ b/pjmedia/src/pjmedia-audiodev/bdimad_dev.c @@ -81,14 +81,14 @@ struct bd_stream pjmedia_aud_param param; /** Memory pool. */ pj_pool_t *pool; - + /** Capture callback. */ pjmedia_aud_rec_cb rec_cb; /** Playback callback. */ pjmedia_aud_play_cb play_cb; /** Application data. */ void *user_data; - + /** Frame format */ pjmedia_format_id fmt_id; /** Silence pattern */ @@ -96,10 +96,10 @@ struct bd_stream /** Bytes per frame */ unsigned bytes_per_frame; /** Samples per frame */ - unsigned samples_per_frame; - /** Channel count */ - int channel_count; - + unsigned samples_per_frame; + /** Channel count */ + int channel_count; + /** Extended frame buffer */ pjmedia_frame_ext *xfrm; /** Total ext frm size */ @@ -120,32 +120,32 @@ struct bd_stream /** bdIMAD current session warnings */ bdIMADpj_Warnings_t *bdIMADpjWarningPtr; - pj_bool_t quit_flag; + pj_bool_t quit_flag; - pj_bool_t rec_thread_exited; - pj_bool_t rec_thread_initialized; - pj_thread_desc rec_thread_desc; - pj_thread_t *rec_thread; + pj_bool_t rec_thread_exited; + pj_bool_t rec_thread_initialized; + pj_thread_desc rec_thread_desc; + pj_thread_t *rec_thread; - pj_bool_t play_thread_exited; - pj_bool_t play_thread_initialized; - pj_thread_desc play_thread_desc; - pj_thread_t *play_thread; + pj_bool_t play_thread_exited; + pj_bool_t play_thread_initialized; + pj_thread_desc play_thread_desc; + pj_thread_t *play_thread; /* Sometime the record callback does not return framesize as configured * (e.g: in OSS), while this module must guarantee returning framesize * as configured in the creation settings. In this case, we need a buffer * for the recorded samples. */ - pj_int16_t *rec_buf; - unsigned rec_buf_count; + pj_int16_t *rec_buf; + unsigned rec_buf_count; /* Sometime the player callback does not request framesize as configured * (e.g: in Linux OSS) while sound device will always get samples from * the other component as many as configured samples_per_frame. */ - pj_int16_t *play_buf; - unsigned play_buf_count; + pj_int16_t *play_buf; + unsigned play_buf_count; }; /* Prototypes */ @@ -155,28 +155,28 @@ static pj_status_t factory_init(pjmedia_aud_dev_factory *f); static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f); static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f); static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); + unsigned index, + pjmedia_aud_dev_info *info); static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); + unsigned index, + pjmedia_aud_param *param); static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); static pj_status_t factory_refresh(pjmedia_aud_dev_factory *f); // pjmedia_aud_stream_op static pj_status_t stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); + pjmedia_aud_param *param); static pj_status_t stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); + pjmedia_aud_dev_cap cap, + void *value); static pj_status_t stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); + pjmedia_aud_dev_cap cap, + const void *value); static pj_status_t stream_start(pjmedia_aud_stream *strm); static pj_status_t stream_stop(pjmedia_aud_stream *strm); static pj_status_t stream_destroy(pjmedia_aud_stream *strm); @@ -222,7 +222,7 @@ char* BD_IMAD_PJ_WCHARtoCHAR(wchar_t *orig) extern "C" { #endif void manage_code(const unsigned char * pCode, unsigned char *pMsg1, - unsigned char * pMsg2); + unsigned char * pMsg2); #ifdef __cplusplus } #endif @@ -281,7 +281,7 @@ static pj_status_t factory_refresh(pjmedia_aud_dev_factory *f) // Enumerate capture sound devices while(bdIMADpj_getDeviceName(BD_IMAD_CAPTURE_DEVICES, &deviceNamep) != - BD_PJ_ERROR_IMAD_DEVICE_LIST_EMPTY) + BD_PJ_ERROR_IMAD_DEVICE_LIST_EMPTY) { wcscpy(captureDevName[captureDeviceCount], deviceNamep); captureDeviceCount++; @@ -289,7 +289,7 @@ static pj_status_t factory_refresh(pjmedia_aud_dev_factory *f) // Enumerate playback sound devices while(bdIMADpj_getDeviceName(BD_IMAD_PLAYBACK_DEVICES, &deviceNamep) != - BD_PJ_ERROR_IMAD_DEVICE_LIST_EMPTY) + BD_PJ_ERROR_IMAD_DEVICE_LIST_EMPTY) { wcscpy(playbackDevName[playbackDeviceCount], deviceNamep); playbackDeviceCount++; @@ -299,42 +299,42 @@ static pj_status_t factory_refresh(pjmedia_aud_dev_factory *f) wf->dev_count = captureDeviceCount + playbackDeviceCount; wf->pool = pj_pool_create(wf->pf, "BD_IMAD_DEVICES", 1000, 1000, NULL); wf->dev_info = (struct bddev_info*)pj_pool_calloc(wf->pool, wf->dev_count, - sizeof(struct bddev_info)); + sizeof(struct bddev_info)); // Capture device properties for(i=0;idev_info[i].deviceId = i; - bdIMADpj_getDeviceCapabilities(BD_IMAD_CAPTURE_DEVICES,&wf->dev_info[i].info.caps); + bdIMADpj_getDeviceCapabilities(BD_IMAD_CAPTURE_DEVICES,&wf->dev_info[i].info.caps); wf->dev_info[i].info.default_samples_per_sec = BD_IMAD_DEFAULT_FREQ; strcpy(wf->dev_info[i].info.driver, "BD_IMAD"); wf->dev_info[i].info.ext_fmt_cnt = 0; wf->dev_info[i].info.input_count = BD_IMAD_MAX_CHANNELS; wf->dev_info[i].info.output_count = 0; strcpy(wf->dev_info[i].info.name, - BD_IMAD_PJ_WCHARtoCHAR(captureDevName[i])); + BD_IMAD_PJ_WCHARtoCHAR(captureDevName[i])); wf->dev_info[i].info.routes = 0; } // Playback device properties for(i=0;idev_info[captureDeviceCount+i].deviceId = captureDeviceCount+i; - bdIMADpj_getDeviceCapabilities(BD_IMAD_PLAYBACK_DEVICES,&wf->dev_info[captureDeviceCount+i].info.caps); + bdIMADpj_getDeviceCapabilities(BD_IMAD_PLAYBACK_DEVICES,&wf->dev_info[captureDeviceCount+i].info.caps); wf->dev_info[captureDeviceCount+i].info.default_samples_per_sec = - BD_IMAD_DEFAULT_FREQ; + BD_IMAD_DEFAULT_FREQ; strcpy(wf->dev_info[captureDeviceCount+i].info.driver, "BD_IMAD"); wf->dev_info[captureDeviceCount+i].info.ext_fmt_cnt = 0; wf->dev_info[captureDeviceCount+i].info.input_count = 0; wf->dev_info[captureDeviceCount+i].info.output_count = - BD_IMAD_MAX_CHANNELS; + BD_IMAD_MAX_CHANNELS; strcpy(wf->dev_info[captureDeviceCount+i].info.name, - BD_IMAD_PJ_WCHARtoCHAR(playbackDevName[i])); + BD_IMAD_PJ_WCHARtoCHAR(playbackDevName[i])); wf->dev_info[captureDeviceCount+i].info.routes = 0; } PJ_LOG(4, (THIS_FILE, "BDIMAD found %d devices:", wf->dev_count)); for(i=0; idev_count; i++) { PJ_LOG(4, - (THIS_FILE, " dev_id %d: %s (in=%d, out=%d)", + (THIS_FILE, " dev_id %d: %s (in=%d, out=%d)", i, wf->dev_info[i].info.name, wf->dev_info[i].info.input_count, @@ -409,9 +409,9 @@ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, param->clock_rate = di->info.default_samples_per_sec; param->flags = di->info.caps; param->samples_per_frame = di->info.default_samples_per_sec * - param->channel_count * - BD_IMAD_MSECOND_PER_BUFFER / - 1000; + param->channel_count * + BD_IMAD_MSECOND_PER_BUFFER / + 1000; if(di->info.caps & PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING) { param->input_vol = BD_IMAD_STARTING_INPUT_VOLUME; @@ -425,8 +425,8 @@ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, param->ec_enabled = PJ_TRUE; } - if(di->info.caps & PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE) { - param->output_route = PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; + if(di->info.caps & PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE) { + param->output_route = PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; } return PJ_SUCCESS; @@ -442,7 +442,7 @@ void bdimad_CaptureCallback(void *buffer, int samples, void *user_data) struct bd_stream *strm = (struct bd_stream*)user_data; if(!strm->go) - goto on_break; + goto on_break; /* Known cases of callback's thread: * - The thread may be changed in the middle of a session, e.g: in MacOS @@ -453,15 +453,15 @@ void bdimad_CaptureCallback(void *buffer, int samples, void *user_data) */ if (strm->rec_thread_initialized == 0 || !pj_thread_is_registered()) { - pj_bzero(strm->rec_thread_desc, sizeof(pj_thread_desc)); - status = pj_thread_register("bd_CaptureCallback", - strm->rec_thread_desc, - &strm->rec_thread); - if (status != PJ_SUCCESS) - goto on_break; - - strm->rec_thread_initialized = 1; - PJ_LOG(5,(THIS_FILE, "Recorder thread started")); + pj_bzero(strm->rec_thread_desc, sizeof(pj_thread_desc)); + status = pj_thread_register("bd_CaptureCallback", + strm->rec_thread_desc, + &strm->rec_thread); + if (status != PJ_SUCCESS) + goto on_break; + + strm->rec_thread_initialized = 1; + PJ_LOG(5,(THIS_FILE, "Recorder thread started")); } /* Calculate number of samples we've got */ @@ -471,71 +471,71 @@ void bdimad_CaptureCallback(void *buffer, int samples, void *user_data) RECORD */ if (strm->fmt_id == PJMEDIA_FORMAT_L16) { - if (nsamples >= strm->samples_per_frame) { - /* If buffer is not empty, combine the buffer with the just incoming - * samples, then call put_frame. - */ - if (strm->rec_buf_count) { - unsigned chunk_count = 0; - - chunk_count = strm->samples_per_frame - strm->rec_buf_count; - pjmedia_copy_samples(strm->rec_buf + strm->rec_buf_count, - (pj_int16_t*)buffer, chunk_count); - - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = (void*) strm->rec_buf; - frame.size = strm->bytes_per_frame; - frame.timestamp.u64 = strm->timestampCapture.u64; - frame.bit_info = 0; - - status = (*strm->rec_cb)(strm->user_data, &frame); - - buffer = (pj_int16_t*) buffer + chunk_count; - nsamples -= strm->samples_per_frame; - strm->rec_buf_count = 0; - strm->timestampCapture.u64 += strm->samples_per_frame / - strm->channel_count; - } - - /* Give all frames we have */ - while (nsamples >= strm->samples_per_frame && status == 0) { - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = (void*) buffer; - frame.size = strm->bytes_per_frame; - frame.timestamp.u64 = strm->timestampCapture.u64; - frame.bit_info = 0; - - status = (*strm->rec_cb)(strm->user_data, &frame); - - buffer = (pj_int16_t*) buffer + strm->samples_per_frame; - nsamples -= strm->samples_per_frame; - strm->timestampCapture.u64 += strm->samples_per_frame / - strm->channel_count; - } - - /* Store the remaining samples into the buffer */ - if (nsamples && status == 0) { - strm->rec_buf_count = nsamples; - pjmedia_copy_samples(strm->rec_buf, (pj_int16_t*)buffer, - nsamples); - } - - } else { - /* Not enough samples, let's just store them in the buffer */ - pjmedia_copy_samples(strm->rec_buf + strm->rec_buf_count, - (pj_int16_t*)buffer, - samples * strm->channel_count); - strm->rec_buf_count += samples * strm->channel_count; - } + if (nsamples >= strm->samples_per_frame) { + /* If buffer is not empty, combine the buffer with the just incoming + * samples, then call put_frame. + */ + if (strm->rec_buf_count) { + unsigned chunk_count = 0; + + chunk_count = strm->samples_per_frame - strm->rec_buf_count; + pjmedia_copy_samples(strm->rec_buf + strm->rec_buf_count, + (pj_int16_t*)buffer, chunk_count); + + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = (void*) strm->rec_buf; + frame.size = strm->bytes_per_frame; + frame.timestamp.u64 = strm->timestampCapture.u64; + frame.bit_info = 0; + + status = (*strm->rec_cb)(strm->user_data, &frame); + + buffer = (pj_int16_t*) buffer + chunk_count; + nsamples -= strm->samples_per_frame; + strm->rec_buf_count = 0; + strm->timestampCapture.u64 += strm->samples_per_frame / + strm->channel_count; + } + + /* Give all frames we have */ + while (nsamples >= strm->samples_per_frame && status == 0) { + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = (void*) buffer; + frame.size = strm->bytes_per_frame; + frame.timestamp.u64 = strm->timestampCapture.u64; + frame.bit_info = 0; + + status = (*strm->rec_cb)(strm->user_data, &frame); + + buffer = (pj_int16_t*) buffer + strm->samples_per_frame; + nsamples -= strm->samples_per_frame; + strm->timestampCapture.u64 += strm->samples_per_frame / + strm->channel_count; + } + + /* Store the remaining samples into the buffer */ + if (nsamples && status == 0) { + strm->rec_buf_count = nsamples; + pjmedia_copy_samples(strm->rec_buf, (pj_int16_t*)buffer, + nsamples); + } + + } else { + /* Not enough samples, let's just store them in the buffer */ + pjmedia_copy_samples(strm->rec_buf + strm->rec_buf_count, + (pj_int16_t*)buffer, + samples * strm->channel_count); + strm->rec_buf_count += samples * strm->channel_count; + } } else { pj_assert(!"Frame type not supported"); } strm->timestampCapture.u64 += strm->param.samples_per_frame / - strm->param.channel_count; + strm->param.channel_count; if (status==0) - return; + return; on_break: strm->rec_thread_exited = 1; @@ -550,7 +550,7 @@ int bdimad_PlaybackCallback(void *buffer, int samples, void *user_data) unsigned nsamples_req = samples * strm->channel_count; if(!strm->go) - goto on_break; + goto on_break; /* Known cases of callback's thread: * - The thread may be changed in the middle of a session, e.g: in MacOS @@ -561,88 +561,88 @@ int bdimad_PlaybackCallback(void *buffer, int samples, void *user_data) */ if (strm->play_thread_initialized == 0 || !pj_thread_is_registered()) { - pj_bzero(strm->play_thread_desc, sizeof(pj_thread_desc)); - status = pj_thread_register("bd_PlaybackCallback", - strm->play_thread_desc, - &strm->play_thread); - if (status != PJ_SUCCESS) - goto on_break; - - strm->play_thread_initialized = 1; - PJ_LOG(5,(THIS_FILE, "Player thread started")); + pj_bzero(strm->play_thread_desc, sizeof(pj_thread_desc)); + status = pj_thread_register("bd_PlaybackCallback", + strm->play_thread_desc, + &strm->play_thread); + if (status != PJ_SUCCESS) + goto on_break; + + strm->play_thread_initialized = 1; + PJ_LOG(5,(THIS_FILE, "Player thread started")); } /* PLAY */ if(strm->fmt_id == PJMEDIA_FORMAT_L16) { - /* Check if any buffered samples */ - if (strm->play_buf_count) { - /* samples buffered >= requested by sound device */ - if (strm->play_buf_count >= nsamples_req) { - pjmedia_copy_samples((pj_int16_t*)buffer, strm->play_buf, - nsamples_req); - strm->play_buf_count -= nsamples_req; - pjmedia_move_samples(strm->play_buf, - strm->play_buf + nsamples_req, - strm->play_buf_count); - - return nsamples_req; - } - - /* samples buffered < requested by sound device */ - pjmedia_copy_samples((pj_int16_t*)buffer, strm->play_buf, - strm->play_buf_count); - nsamples_req -= strm->play_buf_count; - buffer = (pj_int16_t*)buffer + strm->play_buf_count; - strm->play_buf_count = 0; - } - - /* Fill output buffer as requested */ - while (nsamples_req && status == 0) { - if (nsamples_req >= strm->samples_per_frame) { - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = buffer; - frame.size = strm->bytes_per_frame; - frame.timestamp.u64 = strm->timestampPlayback.u64; - frame.bit_info = 0; - - status = (*strm->play_cb)(strm->user_data, &frame); - if (status != PJ_SUCCESS) - return 0; - - if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) - pj_bzero(frame.buf, frame.size); - - nsamples_req -= strm->samples_per_frame; - buffer = (pj_int16_t*)buffer + strm->samples_per_frame; - } else { - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = strm->play_buf; - frame.size = strm->bytes_per_frame; - frame.timestamp.u64 = strm->timestampPlayback.u64; - frame.bit_info = 0; - - status = (*strm->play_cb)(strm->user_data, &frame); - if (status != PJ_SUCCESS) - return 0; - - if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) - pj_bzero(frame.buf, frame.size); - - pjmedia_copy_samples((pj_int16_t*)buffer, strm->play_buf, - nsamples_req); - strm->play_buf_count = strm->samples_per_frame - - nsamples_req; - pjmedia_move_samples(strm->play_buf, - strm->play_buf+nsamples_req, - strm->play_buf_count); - nsamples_req = 0; - } - - strm->timestampPlayback.u64 += strm->samples_per_frame / - strm->channel_count; - } + /* Check if any buffered samples */ + if (strm->play_buf_count) { + /* samples buffered >= requested by sound device */ + if (strm->play_buf_count >= nsamples_req) { + pjmedia_copy_samples((pj_int16_t*)buffer, strm->play_buf, + nsamples_req); + strm->play_buf_count -= nsamples_req; + pjmedia_move_samples(strm->play_buf, + strm->play_buf + nsamples_req, + strm->play_buf_count); + + return nsamples_req; + } + + /* samples buffered < requested by sound device */ + pjmedia_copy_samples((pj_int16_t*)buffer, strm->play_buf, + strm->play_buf_count); + nsamples_req -= strm->play_buf_count; + buffer = (pj_int16_t*)buffer + strm->play_buf_count; + strm->play_buf_count = 0; + } + + /* Fill output buffer as requested */ + while (nsamples_req && status == 0) { + if (nsamples_req >= strm->samples_per_frame) { + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = buffer; + frame.size = strm->bytes_per_frame; + frame.timestamp.u64 = strm->timestampPlayback.u64; + frame.bit_info = 0; + + status = (*strm->play_cb)(strm->user_data, &frame); + if (status != PJ_SUCCESS) + return 0; + + if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) + pj_bzero(frame.buf, frame.size); + + nsamples_req -= strm->samples_per_frame; + buffer = (pj_int16_t*)buffer + strm->samples_per_frame; + } else { + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = strm->play_buf; + frame.size = strm->bytes_per_frame; + frame.timestamp.u64 = strm->timestampPlayback.u64; + frame.bit_info = 0; + + status = (*strm->play_cb)(strm->user_data, &frame); + if (status != PJ_SUCCESS) + return 0; + + if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) + pj_bzero(frame.buf, frame.size); + + pjmedia_copy_samples((pj_int16_t*)buffer, strm->play_buf, + nsamples_req); + strm->play_buf_count = strm->samples_per_frame - + nsamples_req; + pjmedia_move_samples(strm->play_buf, + strm->play_buf+nsamples_req, + strm->play_buf_count); + nsamples_req = 0; + } + + strm->timestampPlayback.u64 += strm->samples_per_frame / + strm->channel_count; + } } else { pj_assert(!"Frame type not supported"); } @@ -652,10 +652,10 @@ int bdimad_PlaybackCallback(void *buffer, int samples, void *user_data) } strm->timestampPlayback.u64 += strm->param.samples_per_frame / - strm->param.channel_count; + strm->param.channel_count; if (status == 0) - return samples; + return samples; on_break: strm->play_thread_exited = 1; @@ -691,18 +691,18 @@ static pj_status_t init_streams(struct bd_factory *wf, PJ_ASSERT_RETURN(prm->rec_id < (int)wf->dev_count, PJ_EINVAL); ptime = prm->samples_per_frame * - 1000 / - (prm->clock_rate * prm->channel_count); + 1000 / + (prm->clock_rate * prm->channel_count); strm->bytes_per_frame = (prm->clock_rate * - ((prm->channel_count * prm->bits_per_sample) / 8)) * - ptime / - 1000; + ((prm->channel_count * prm->bits_per_sample) / 8)) * + ptime / + 1000; strm->timestampCapture.u64 = 0; strm->timestampPlayback.u64 = 0; //BD_IMAD_PJ bdIMADpj_CreateStructures(&strm->bdIMADpjSettingsPtr, - &strm->bdIMADpjWarningPtr); + &strm->bdIMADpjWarningPtr); strm->bdIMADpjSettingsPtr->FrameSize_ms = ptime; strm->bdIMADpjSettingsPtr->DiagnosticEnable = BD_IMAD_DIAGNOSTIC; @@ -711,22 +711,22 @@ static pj_status_t init_streams(struct bd_factory *wf, strm->bdIMADpjSettingsPtr->validate = (void *)manage_code; if(prm->clock_rate != 8000 && prm->clock_rate != 16000 - && prm->clock_rate != 32000 && prm->clock_rate != 44100 && prm->clock_rate != 48000) { + && prm->clock_rate != 32000 && prm->clock_rate != 44100 && prm->clock_rate != 48000) { PJ_LOG(4, (THIS_FILE, - "BDIMAD support 8000 Hz, 16000 Hz, 32000 Hz, 44100 Hz and 48000 Hz " - "frequency.")); + "BDIMAD support 8000 Hz, 16000 Hz, 32000 Hz, 44100 Hz and 48000 Hz " + "frequency.")); } strm->bdIMADpjSettingsPtr->SamplingFrequency = prm->clock_rate; if(prm->channel_count > BD_IMAD_MAX_CHANNELS) { PJ_LOG(4, (THIS_FILE, - "BDIMAD doesn't support a number of channels upper than %d.", - BD_IMAD_MAX_CHANNELS)); + "BDIMAD doesn't support a number of channels upper than %d.", + BD_IMAD_MAX_CHANNELS)); } // Enumerate capture sound devices while(bdIMADpj_getDeviceName(BD_IMAD_CAPTURE_DEVICES, &deviceNamep) != - BD_PJ_ERROR_IMAD_DEVICE_LIST_EMPTY) + BD_PJ_ERROR_IMAD_DEVICE_LIST_EMPTY) { wcscpy(captureDevName[captureDeviceCount], deviceNamep); captureDeviceCount++; @@ -735,13 +735,13 @@ static pj_status_t init_streams(struct bd_factory *wf, // Enumerate playback sound devices while(bdIMADpj_getDeviceName(BD_IMAD_PLAYBACK_DEVICES, &deviceNamep) != - BD_PJ_ERROR_IMAD_DEVICE_LIST_EMPTY) + BD_PJ_ERROR_IMAD_DEVICE_LIST_EMPTY) { wcscpy(playbackDevName[playbackDeviceCount], deviceNamep); playbackDeviceCount++; } strm->bdIMADpjSettingsPtr->PlayDevice = - playbackDevName[(int)(prm->play_id-captureDeviceCount)]; + playbackDevName[(int)(prm->play_id-captureDeviceCount)]; strm->bdIMADpjSettingsPtr->cb_emptyCaptureBuffer = &bdimad_CaptureCallback; strm->bdIMADpjSettingsPtr->cb_emptyCaptureBuffer_user_data = (void*)strm; @@ -753,22 +753,22 @@ static pj_status_t init_streams(struct bd_factory *wf, strm->bdIMADpjInstance = NULL; errorInitAEC = bdIMADpj_InitAEC(&strm->bdIMADpjInstance, - &strm->bdIMADpjSettingsPtr, - &strm->bdIMADpjWarningPtr); + &strm->bdIMADpjSettingsPtr, + &strm->bdIMADpjWarningPtr); { - int auxInt = (prm->ec_enabled == PJ_TRUE ? 1 : 0); + int auxInt = (prm->ec_enabled == PJ_TRUE ? 1 : 0); bdIMADpj_setParameter(strm->bdIMADpjInstance, - BD_PARAM_IMAD_PJ_AEC_ENABLE, - &auxInt); + BD_PARAM_IMAD_PJ_AEC_ENABLE, + &auxInt); auxInt = 1; //Mic control On by default bdIMADpj_setParameter(strm->bdIMADpjInstance, - BD_PARAM_IMAD_PJ_MIC_CONTROL_ENABLE, - &auxInt); - - // Enable GUI Socket Communication [default->disabled] - bdIMADpj_enableGuiSocketCommunication(strm->bdIMADpjInstance,27000,0); + BD_PARAM_IMAD_PJ_MIC_CONTROL_ENABLE, + &auxInt); + + // Enable GUI Socket Communication [default->disabled] + bdIMADpj_enableGuiSocketCommunication(strm->bdIMADpjInstance,27000,0); } if(errorInitAEC != BD_PJ_OK && @@ -794,9 +794,9 @@ static pj_status_t stream_stopBDIMAD(pjmedia_aud_stream *s) strm->go = 0; for (i=0; !strm->rec_thread_exited && i<100; ++i) - pj_thread_sleep(10); + pj_thread_sleep(10); for (i=0; !strm->play_thread_exited && i<100; ++i) - pj_thread_sleep(10); + pj_thread_sleep(10); pj_thread_sleep(1); @@ -834,10 +834,10 @@ static pj_status_t stream_destroyBDIMAD(pjmedia_aud_stream *s) // DeInit BDIMAD bdIMADpj_FreeAEC(&strm->bdIMADpjInstance); - PJ_LOG(4, (THIS_FILE, "Free AEC")); + PJ_LOG(4, (THIS_FILE, "Free AEC")); bdIMADpj_FreeStructures(&strm->bdIMADpjSettingsPtr, - &strm->bdIMADpjWarningPtr); + &strm->bdIMADpjWarningPtr); PJ_LOG(4, (THIS_FILE, "Free AEC Structure")); strm->bdIMADpjInstance = NULL; @@ -846,10 +846,10 @@ static pj_status_t stream_destroyBDIMAD(pjmedia_aud_stream *s) strm->quit_flag = 1; for (i=0; !strm->rec_thread_exited && i<100; ++i) { - pj_thread_sleep(1); + pj_thread_sleep(1); } for (i=0; !strm->play_thread_exited && i<100; ++i) { - pj_thread_sleep(1); + pj_thread_sleep(1); } PJ_LOG(5,(THIS_FILE, "Destroying stream..")); @@ -874,8 +874,8 @@ static pj_status_t stream_destroy(pjmedia_aud_stream *s) /* API: set capability */ static pj_status_t stream_set_capBDIMAD(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - const void *pval) + pjmedia_aud_dev_cap cap, + const void *pval) { struct bd_stream *strm = (struct bd_stream*)s; bdIMADpj_Status res = BD_PJ_OK; @@ -890,7 +890,7 @@ static pj_status_t stream_set_capBDIMAD(pjmedia_aud_stream *s, vol = vol / 100.0f; res = bdIMADpj_setParameter(strm->bdIMADpjInstance, - BD_PARAM_IMAD_PJ_SPK_VOLUME, &vol); + BD_PARAM_IMAD_PJ_SPK_VOLUME, &vol); if(res == BD_PJ_OK) { @@ -910,7 +910,7 @@ static pj_status_t stream_set_capBDIMAD(pjmedia_aud_stream *s, vol = vol / 100.0f; res = bdIMADpj_setParameter(strm->bdIMADpjInstance, - BD_PARAM_IMAD_PJ_MIC_VOLUME, &vol); + BD_PARAM_IMAD_PJ_MIC_VOLUME, &vol); if(res == BD_PJ_OK) { strm->param.input_vol = *(unsigned*)pval; return PJ_SUCCESS; @@ -924,8 +924,8 @@ static pj_status_t stream_set_capBDIMAD(pjmedia_aud_stream *s, /* AEC setting */ res = bdIMADpj_setParameter(strm->bdIMADpjInstance, - BD_PARAM_IMAD_PJ_AEC_ENABLE, - &aecOnOff); + BD_PARAM_IMAD_PJ_AEC_ENABLE, + &aecOnOff); if(res == BD_PJ_OK) { strm->param.ec_enabled = (aecOnOff == 1 ? PJ_TRUE : PJ_FALSE); return PJ_SUCCESS; @@ -934,16 +934,16 @@ static pj_status_t stream_set_capBDIMAD(pjmedia_aud_stream *s, } } - if(cap == PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE) { - pjmedia_aud_dev_route outputRoute = *(pjmedia_aud_dev_route*)pval; - res = bdIMADpj_setRouteOutputDevice(strm->bdIMADpjInstance, (bdIMADpj_out_dev_route) outputRoute, &strm->bdIMADpjWarningPtr); - if(res == BD_PJ_OK) { - strm->param.output_route = outputRoute; + if(cap == PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE) { + pjmedia_aud_dev_route outputRoute = *(pjmedia_aud_dev_route*)pval; + res = bdIMADpj_setRouteOutputDevice(strm->bdIMADpjInstance, (bdIMADpj_out_dev_route) outputRoute, &strm->bdIMADpjWarningPtr); + if(res == BD_PJ_OK) { + strm->param.output_route = outputRoute; return PJ_SUCCESS; } else { return PJMEDIA_AUDIODEV_ERRNO_FROM_BDIMAD(res); } - } + } return PJMEDIA_EAUD_INVCAP; } @@ -963,10 +963,10 @@ static pj_status_t factory_create_streamBDIMAD(pjmedia_aud_dev_factory *f, switch (param->ext_fmt.id) { case PJMEDIA_FORMAT_L16: - silence_char = '\0'; - break; + silence_char = '\0'; + break; default: - return PJMEDIA_EAUD_BADFORMAT; + return PJMEDIA_EAUD_BADFORMAT; } /* Create and Initialize stream descriptor */ @@ -997,7 +997,7 @@ static pj_status_t factory_create_streamBDIMAD(pjmedia_aud_dev_factory *f, } strm->rec_buf = (pj_int16_t*)pj_pool_alloc(pool, - strm->bytes_per_frame); + strm->bytes_per_frame); if (!strm->rec_buf) { pj_pool_release(pool); return PJ_ENOMEM; @@ -1005,7 +1005,7 @@ static pj_status_t factory_create_streamBDIMAD(pjmedia_aud_dev_factory *f, strm->rec_buf_count = 0; strm->play_buf = (pj_int16_t*)pj_pool_alloc(pool, - strm->bytes_per_frame); + strm->bytes_per_frame); if (!strm->play_buf) { pj_pool_release(pool); return PJ_ENOMEM; @@ -1015,25 +1015,25 @@ static pj_status_t factory_create_streamBDIMAD(pjmedia_aud_dev_factory *f, /* Apply the remaining settings */ if(param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { stream_set_capBDIMAD(&strm->base, - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - ¶m->output_vol); + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + ¶m->output_vol); } if(param->flags & PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING) { stream_set_capBDIMAD(&strm->base, - PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING, - ¶m->input_vol); + PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING, + ¶m->input_vol); } if(param->flags & PJMEDIA_AUD_DEV_CAP_EC) { stream_set_capBDIMAD(&strm->base, - PJMEDIA_AUD_DEV_CAP_EC, - ¶m->ec_enabled); + PJMEDIA_AUD_DEV_CAP_EC, + ¶m->ec_enabled); } if(param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE) { - stream_set_capBDIMAD(&strm->base, - PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, - ¶m->output_route); - } + stream_set_capBDIMAD(&strm->base, + PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, + ¶m->output_route); + } strm->base.op = &stream_op; *p_aud_strm = &strm->base; @@ -1042,14 +1042,14 @@ static pj_status_t factory_create_streamBDIMAD(pjmedia_aud_dev_factory *f, } static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { return factory_create_streamBDIMAD(f, param, rec_cb, - play_cb, user_data, p_aud_strm); + play_cb, user_data, p_aud_strm); } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- @@ -1067,14 +1067,14 @@ static pj_status_t stream_get_param(pjmedia_aud_stream *s, // Get the output volume setting if(stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - &pi->output_vol) == PJ_SUCCESS) + &pi->output_vol) == PJ_SUCCESS) { pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; } // Get the input volume setting if(stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING, - &pi->input_vol) == PJ_SUCCESS) + &pi->input_vol) == PJ_SUCCESS) { pi->flags |= PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING; } @@ -1084,7 +1084,7 @@ static pj_status_t stream_get_param(pjmedia_aud_stream *s, { pi->flags |= PJMEDIA_AUD_DEV_CAP_EC; } - if(stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_EC, &pi->ec_enabled) == PJ_SUCCESS) + if(stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_EC, &pi->ec_enabled) == PJ_SUCCESS) { pi->flags |= PJMEDIA_AUD_DEV_CAP_EC; } @@ -1113,13 +1113,13 @@ static pj_status_t stream_get_capBDIMAD(pjmedia_aud_stream *s, /* Input volume setting */ float vol; res = bdIMADpj_getParameter(strm->bdIMADpjInstance, - BD_PARAM_IMAD_PJ_MIC_VOLUME, &vol); + BD_PARAM_IMAD_PJ_MIC_VOLUME, &vol); if(res == BD_PJ_OK) { - vol = vol * 100; - if(vol > 100.0f) vol = 100.0f; - if(vol < 0.0f) vol = 0.0f; - *(unsigned int *)pval = (unsigned int)vol; - return PJ_SUCCESS; + vol = vol * 100; + if(vol > 100.0f) vol = 100.0f; + if(vol < 0.0f) vol = 0.0f; + *(unsigned int *)pval = (unsigned int)vol; + return PJ_SUCCESS; } else{ return PJMEDIA_AUDIODEV_ERRNO_FROM_BDIMAD(res); } @@ -1127,9 +1127,9 @@ static pj_status_t stream_get_capBDIMAD(pjmedia_aud_stream *s, /* Output volume setting */ float vol; res = bdIMADpj_getParameter(strm->bdIMADpjInstance, - BD_PARAM_IMAD_PJ_SPK_VOLUME, &vol); + BD_PARAM_IMAD_PJ_SPK_VOLUME, &vol); if(res == BD_PJ_OK) { - vol = vol * 100; + vol = vol * 100; if(vol > 100.0f) vol = 100.0f; if(vol < 0.0f) vol = 0.0f; *(unsigned int *)pval = (unsigned int)vol; @@ -1141,7 +1141,7 @@ static pj_status_t stream_get_capBDIMAD(pjmedia_aud_stream *s, else if(cap == PJMEDIA_AUD_DEV_CAP_EC) { int aecIsOn; res = bdIMADpj_getParameter(strm->bdIMADpjInstance, - BD_PARAM_IMAD_PJ_AEC_ENABLE, &aecIsOn); + BD_PARAM_IMAD_PJ_AEC_ENABLE, &aecIsOn); if(res == BD_PJ_OK) { *(pj_bool_t*)pval = (aecIsOn == 1 ? PJ_TRUE : PJ_FALSE); return PJ_SUCCESS; @@ -1150,8 +1150,8 @@ static pj_status_t stream_get_capBDIMAD(pjmedia_aud_stream *s, } } else if(cap == PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE) { - pjmedia_aud_dev_route routeOutDev; - res = bdIMADpj_getRouteOutputDevice(strm->bdIMADpjInstance,(bdIMADpj_out_dev_route*)&routeOutDev); + pjmedia_aud_dev_route routeOutDev; + res = bdIMADpj_getRouteOutputDevice(strm->bdIMADpjInstance,(bdIMADpj_out_dev_route*)&routeOutDev); if(res == BD_PJ_OK) { *(pjmedia_aud_dev_route*)pval = routeOutDev; return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia-audiodev/coreaudio_dev.m b/pjmedia/src/pjmedia-audiodev/coreaudio_dev.m index 5cad0c2906..8210ad03ec 100644 --- a/pjmedia/src/pjmedia-audiodev/coreaudio_dev.m +++ b/pjmedia/src/pjmedia-audiodev/coreaudio_dev.m @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -71,81 +70,81 @@ #endif -#define THIS_FILE "coreaudio_dev.c" +#define THIS_FILE "coreaudio_dev.c" /* coreaudio device info */ struct coreaudio_dev_info { - pjmedia_aud_dev_info info; - AudioDeviceID dev_id; + pjmedia_aud_dev_info info; + AudioDeviceID dev_id; }; /* linked list of streams */ struct stream_list { PJ_DECL_LIST_MEMBER(struct stream_list); - struct coreaudio_stream *stream; + struct coreaudio_stream *stream; }; /* coreaudio factory */ struct coreaudio_factory { - pjmedia_aud_dev_factory base; - pj_pool_t *base_pool; - pj_pool_t *pool; - pj_pool_factory *pf; - pj_mutex_t *mutex; - - unsigned dev_count; - struct coreaudio_dev_info *dev_info; - - AudioComponent io_comp; - pj_bool_t has_vpio; - struct stream_list streams; + pjmedia_aud_dev_factory base; + pj_pool_t *base_pool; + pj_pool_t *pool; + pj_pool_factory *pf; + pj_mutex_t *mutex; + + unsigned dev_count; + struct coreaudio_dev_info *dev_info; + + AudioComponent io_comp; + pj_bool_t has_vpio; + struct stream_list streams; }; /* Sound stream. */ struct coreaudio_stream { - pjmedia_aud_stream base; /**< Base stream */ - pjmedia_aud_param param; /**< Settings */ - pj_pool_t *pool; /**< Memory pool. */ - struct coreaudio_factory *cf; - struct stream_list list_entry; + pjmedia_aud_stream base; /**< Base stream */ + pjmedia_aud_param param; /**< Settings */ + pj_pool_t *pool; /**< Memory pool. */ + struct coreaudio_factory *cf; + struct stream_list list_entry; - pjmedia_aud_rec_cb rec_cb; /**< Capture callback. */ - pjmedia_aud_play_cb play_cb; /**< Playback callback. */ - void *user_data; /**< Application data. */ + pjmedia_aud_rec_cb rec_cb; /**< Capture callback. */ + pjmedia_aud_play_cb play_cb; /**< Playback callback. */ + void *user_data; /**< Application data. */ - pj_timestamp play_timestamp; - pj_timestamp rec_timestamp; + pj_timestamp play_timestamp; + pj_timestamp rec_timestamp; - pj_int16_t *rec_buf; - unsigned rec_buf_count; - pj_int16_t *play_buf; - unsigned play_buf_count; + pj_int16_t *rec_buf; + unsigned rec_buf_count; + pj_int16_t *play_buf; + unsigned play_buf_count; - pj_bool_t interrupted; - pj_bool_t quit_flag; - pj_bool_t running; + pj_bool_t interrupted; + pj_bool_t quit_flag; + pj_bool_t running; - pj_bool_t rec_thread_initialized; - pj_thread_desc rec_thread_desc; - pj_thread_t *rec_thread; + pj_bool_t rec_thread_initialized; + pj_thread_desc rec_thread_desc; + pj_thread_t *rec_thread; - pj_bool_t play_thread_initialized; - pj_thread_desc play_thread_desc; - pj_thread_t *play_thread; + pj_bool_t play_thread_initialized; + pj_thread_desc play_thread_desc; + pj_thread_t *play_thread; - AudioUnit io_units[2]; + AudioUnit io_units[2]; AudioStreamBasicDescription streamFormat; - AudioBufferList *audio_buf; + AudioBufferList *audio_buf; AudioConverterRef resample; - pj_int16_t *resample_buf; - void *resample_buf_ptr; - unsigned resample_buf_count; - unsigned resample_buf_size; + pj_int16_t *resample_buf; + void *resample_buf_ptr; + unsigned resample_buf_count; + unsigned resample_buf_size; #if !COREAUDIO_MAC AVAudioSession *sess; @@ -161,34 +160,34 @@ static pj_status_t ca_factory_refresh(pjmedia_aud_dev_factory *f); static unsigned ca_factory_get_dev_count(pjmedia_aud_dev_factory *f); static pj_status_t ca_factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); + unsigned index, + pjmedia_aud_dev_info *info); static pj_status_t ca_factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); + unsigned index, + pjmedia_aud_param *param); static pj_status_t ca_factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); static pj_status_t ca_stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); + pjmedia_aud_param *param); static pj_status_t ca_stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); + pjmedia_aud_dev_cap cap, + void *value); static pj_status_t ca_stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); + pjmedia_aud_dev_cap cap, + const void *value); static pj_status_t ca_stream_start(pjmedia_aud_stream *strm); static pj_status_t ca_stream_stop(pjmedia_aud_stream *strm); static pj_status_t ca_stream_destroy(pjmedia_aud_stream *strm); static pj_status_t create_audio_unit(AudioComponent io_comp, - AudioDeviceID dev_id, - pjmedia_dir dir, - struct coreaudio_stream *strm, - AudioUnit *io_unit); + AudioDeviceID dev_id, + pjmedia_dir dir, + struct coreaudio_stream *strm, + AudioUnit *io_unit); #if !COREAUDIO_MAC && USE_AUDIO_SESSION_API != 0 static void interruptionListener(void *inClientData, UInt32 inInterruption); static void propListener(void * inClientData, @@ -253,10 +252,10 @@ static pj_status_t ca_factory_init(pjmedia_aud_dev_factory *f) pj_list_init(&cf->streams); status = pj_mutex_create_recursive(cf->base_pool, - "coreaudio", - &cf->mutex); + "coreaudio", + &cf->mutex); if (status != PJ_SUCCESS) - return status; + return status; desc.componentType = kAudioUnitType_Output; #if COREAUDIO_MAC @@ -270,53 +269,53 @@ static pj_status_t ca_factory_init(pjmedia_aud_dev_factory *f) cf->io_comp = AudioComponentFindNext(NULL, &desc); if (cf->io_comp == NULL) - return PJMEDIA_EAUD_INIT; // cannot find IO unit; + return PJMEDIA_EAUD_INIT; // cannot find IO unit; desc.componentSubType = kAudioUnitSubType_VoiceProcessingIO; if (AudioComponentFindNext(NULL, &desc) != NULL) - cf->has_vpio = PJ_TRUE; + cf->has_vpio = PJ_TRUE; status = ca_factory_refresh(f); if (status != PJ_SUCCESS) - return status; + return status; #if !COREAUDIO_MAC cf->pool = pj_pool_create(cf->pf, "core audio", 1000, 1000, NULL); cf->dev_count = 1; cf->dev_info = (struct coreaudio_dev_info*) - pj_pool_calloc(cf->pool, cf->dev_count, - sizeof(struct coreaudio_dev_info)); + pj_pool_calloc(cf->pool, cf->dev_count, + sizeof(struct coreaudio_dev_info)); for (i = 0; i < cf->dev_count; i++) { - struct coreaudio_dev_info *cdi; - - cdi = &cf->dev_info[i]; - pj_bzero(cdi, sizeof(*cdi)); - cdi->dev_id = 0; - strcpy(cdi->info.name, "iPhone IO device"); - strcpy(cdi->info.driver, "apple"); - cdi->info.input_count = 1; - cdi->info.output_count = 1; - cdi->info.default_samples_per_sec = 8000; - - /* Set the device capabilities here */ - cdi->info.caps = PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING | + struct coreaudio_dev_info *cdi; + + cdi = &cf->dev_info[i]; + pj_bzero(cdi, sizeof(*cdi)); + cdi->dev_id = 0; + strcpy(cdi->info.name, "iPhone IO device"); + strcpy(cdi->info.driver, "apple"); + cdi->info.input_count = 1; + cdi->info.output_count = 1; + cdi->info.default_samples_per_sec = 8000; + + /* Set the device capabilities here */ + cdi->info.caps = PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | + PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY | + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING | #if USE_AUDIO_SESSION_API != 0 - PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE | - PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE | + PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE | + PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE | #endif - PJMEDIA_AUD_DEV_CAP_EC; - cdi->info.routes = PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER | - PJMEDIA_AUD_DEV_ROUTE_EARPIECE | - PJMEDIA_AUD_DEV_ROUTE_BLUETOOTH; - - PJ_LOG(4, (THIS_FILE, " dev_id %d: %s (in=%d, out=%d) %dHz", - i, - cdi->info.name, - cdi->info.input_count, - cdi->info.output_count, - cdi->info.default_samples_per_sec)); + PJMEDIA_AUD_DEV_CAP_EC; + cdi->info.routes = PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER | + PJMEDIA_AUD_DEV_ROUTE_EARPIECE | + PJMEDIA_AUD_DEV_ROUTE_BLUETOOTH; + + PJ_LOG(4, (THIS_FILE, " dev_id %d: %s (in=%d, out=%d) %dHz", + i, + cdi->info.name, + cdi->info.input_count, + cdi->info.output_count, + cdi->info.default_samples_per_sec)); } #if USE_AUDIO_SESSION_API != 0 @@ -336,7 +335,7 @@ static pj_status_t ca_factory_init(pjmedia_aud_dev_factory *f) #if USE_AUDIO_ROUTE_CHANGE_PROP_LISTENER != 0 ostatus = AudioSessionAddPropertyListener( kAudioSessionProperty_AudioRouteChange, - propListener, cf); + propListener, cf); if (ostatus != kAudioSessionNoError) { PJ_LOG(4, (THIS_FILE, "Warning: cannot listen for audio route change " @@ -349,28 +348,28 @@ static pj_status_t ca_factory_init(pjmedia_aud_dev_factory *f) #if SETUP_AV_AUDIO_SESSION /* Initialize audio session category and mode */ { - AVAudioSession *sess = [AVAudioSession sharedInstance]; - pj_bool_t err; - - if ([sess respondsToSelector:@selector(setCategory:withOptions:error:)]) - { - err = [sess setCategory:AVAudioSessionCategoryPlayAndRecord - withOptions:AVAudioSessionCategoryOptionAllowBluetooth - error:nil] != YES; + AVAudioSession *sess = [AVAudioSession sharedInstance]; + pj_bool_t err; + + if ([sess respondsToSelector:@selector(setCategory:withOptions:error:)]) + { + err = [sess setCategory:AVAudioSessionCategoryPlayAndRecord + withOptions:AVAudioSessionCategoryOptionAllowBluetooth + error:nil] != YES; } else { - err = [sess setCategory:AVAudioSessionCategoryPlayAndRecord - error:nil] != YES; + err = [sess setCategory:AVAudioSessionCategoryPlayAndRecord + error:nil] != YES; } - if (err) { + if (err) { PJ_LOG(3, (THIS_FILE, - "Warning: failed settting audio session category")); - } - - if ([sess respondsToSelector:@selector(setMode:error:)] && - [sess setMode:AVAudioSessionModeVoiceChat error:nil] != YES) - { - PJ_LOG(3, (THIS_FILE, "Warning: failed settting audio mode")); - } + "Warning: failed settting audio session category")); + } + + if ([sess respondsToSelector:@selector(setMode:error:)] && + [sess setMode:AVAudioSessionModeVoiceChat error:nil] != YES) + { + PJ_LOG(3, (THIS_FILE, "Warning: failed settting audio mode")); + } } #endif @@ -400,16 +399,16 @@ static pj_status_t ca_factory_destroy(pjmedia_aud_dev_factory *f) #endif if (cf->pool) { - pj_pool_release(cf->pool); - cf->pool = NULL; + pj_pool_release(cf->pool); + cf->pool = NULL; } if (cf->mutex) { - pj_mutex_lock(cf->mutex); - cf_instance = NULL; - pj_mutex_unlock(cf->mutex); - pj_mutex_destroy(cf->mutex); - cf->mutex = NULL; + pj_mutex_lock(cf->mutex); + cf_instance = NULL; + pj_mutex_unlock(cf->mutex); + pj_mutex_destroy(cf->mutex); + cf->mutex = NULL; } pool = cf->base_pool; @@ -437,8 +436,8 @@ static pj_status_t ca_factory_refresh(pjmedia_aud_dev_factory *f) OSStatus ostatus; if (cf->pool != NULL) { - pj_pool_release(cf->pool); - cf->pool = NULL; + pj_pool_release(cf->pool); + cf->pool = NULL; } cf->dev_count = 0; @@ -451,203 +450,203 @@ static pj_status_t ca_factory_refresh(pjmedia_aud_dev_factory *f) ostatus = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &addr, 0, NULL, &dev_size); if (ostatus != noErr) { - dev_size = 0; + dev_size = 0; } /* Calculate the number of audio devices available */ dev_count = dev_size / size; if (dev_count==0) { - PJ_LOG(4,(THIS_FILE, "core audio found no sound devices")); - /* Enabling this will cause pjsua-lib initialization to fail when - * there is no sound device installed in the system, even when pjsua - * has been run with --null-audio. Moreover, it might be better to - * think that the core audio backend initialization is successful, - * regardless there is no audio device installed, as later application - * can check it using get_dev_count(). - return PJMEDIA_EAUD_NODEV; - */ - return PJ_SUCCESS; + PJ_LOG(4,(THIS_FILE, "core audio found no sound devices")); + /* Enabling this will cause pjsua-lib initialization to fail when + * there is no sound device installed in the system, even when pjsua + * has been run with --null-audio. Moreover, it might be better to + * think that the core audio backend initialization is successful, + * regardless there is no audio device installed, as later application + * can check it using get_dev_count(). + return PJMEDIA_EAUD_NODEV; + */ + return PJ_SUCCESS; } PJ_LOG(4, (THIS_FILE, "core audio detected %d devices", - dev_count)); + dev_count)); /* Get all the audio device IDs */ dev_ids = (AudioDeviceID *)pj_pool_calloc(cf->pool, dev_count, size); if (!dev_ids) - return PJ_ENOMEM; + return PJ_ENOMEM; ostatus = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, - 0, NULL, - &dev_size, (void *)dev_ids); + 0, NULL, + &dev_size, (void *)dev_ids); if (ostatus != noErr ) { - /* This should not happen since we have successfully retrieved - * the property data size before - */ - return PJMEDIA_EAUD_INIT; + /* This should not happen since we have successfully retrieved + * the property data size before + */ + return PJMEDIA_EAUD_INIT; } if (dev_size > 1) { - AudioDeviceID dev_id = kAudioObjectUnknown; - unsigned idx = 0; - - /* Find default audio input device */ - addr.mSelector = kAudioHardwarePropertyDefaultInputDevice; - addr.mScope = kAudioObjectPropertyScopeGlobal; - addr.mElement = kAudioObjectPropertyElementMaster; - size = sizeof(dev_id); - - ostatus = AudioObjectGetPropertyData(kAudioObjectSystemObject, - &addr, 0, NULL, - &size, (void *)&dev_id); - if (ostatus == noErr && dev_id != dev_ids[idx]) { - AudioDeviceID temp_id = dev_ids[idx]; - - for (i = idx + 1; i < dev_count; i++) { - if (dev_ids[i] == dev_id) { - dev_ids[idx++] = dev_id; - dev_ids[i] = temp_id; - break; - } - } - } - - /* Find default audio output device */ - addr.mSelector = kAudioHardwarePropertyDefaultOutputDevice; - ostatus = AudioObjectGetPropertyData(kAudioObjectSystemObject, - &addr, 0, NULL, - &size, (void *)&dev_id); - if (ostatus == noErr && dev_id != dev_ids[idx]) { - AudioDeviceID temp_id = dev_ids[idx]; - - for (i = idx + 1; i < dev_count; i++) { - if (dev_ids[i] == dev_id) { - dev_ids[idx] = dev_id; - dev_ids[i] = temp_id; - break; - } - } - } + AudioDeviceID dev_id = kAudioObjectUnknown; + unsigned idx = 0; + + /* Find default audio input device */ + addr.mSelector = kAudioHardwarePropertyDefaultInputDevice; + addr.mScope = kAudioObjectPropertyScopeGlobal; + addr.mElement = kAudioObjectPropertyElementMaster; + size = sizeof(dev_id); + + ostatus = AudioObjectGetPropertyData(kAudioObjectSystemObject, + &addr, 0, NULL, + &size, (void *)&dev_id); + if (ostatus == noErr && dev_id != dev_ids[idx]) { + AudioDeviceID temp_id = dev_ids[idx]; + + for (i = idx + 1; i < dev_count; i++) { + if (dev_ids[i] == dev_id) { + dev_ids[idx++] = dev_id; + dev_ids[i] = temp_id; + break; + } + } + } + + /* Find default audio output device */ + addr.mSelector = kAudioHardwarePropertyDefaultOutputDevice; + ostatus = AudioObjectGetPropertyData(kAudioObjectSystemObject, + &addr, 0, NULL, + &size, (void *)&dev_id); + if (ostatus == noErr && dev_id != dev_ids[idx]) { + AudioDeviceID temp_id = dev_ids[idx]; + + for (i = idx + 1; i < dev_count; i++) { + if (dev_ids[i] == dev_id) { + dev_ids[idx] = dev_id; + dev_ids[i] = temp_id; + break; + } + } + } } /* Build the devices' info */ cf->dev_info = (struct coreaudio_dev_info*) - pj_pool_calloc(cf->pool, dev_count, - sizeof(struct coreaudio_dev_info)); + pj_pool_calloc(cf->pool, dev_count, + sizeof(struct coreaudio_dev_info)); buf_size = 0; for (i = 0; i < dev_count; i++) { - struct coreaudio_dev_info *cdi; - Float64 sampleRate; + struct coreaudio_dev_info *cdi; + Float64 sampleRate; - cdi = &cf->dev_info[i]; - pj_bzero(cdi, sizeof(*cdi)); - cdi->dev_id = dev_ids[i]; + cdi = &cf->dev_info[i]; + pj_bzero(cdi, sizeof(*cdi)); + cdi->dev_id = dev_ids[i]; - /* Get device name */ - addr.mSelector = kAudioDevicePropertyDeviceName; - addr.mScope = kAudioObjectPropertyScopeGlobal; - addr.mElement = kAudioObjectPropertyElementMaster; - size = sizeof(cdi->info.name); - AudioObjectGetPropertyData(cdi->dev_id, &addr, - 0, NULL, - &size, (void *)cdi->info.name); + /* Get device name */ + addr.mSelector = kAudioDevicePropertyDeviceName; + addr.mScope = kAudioObjectPropertyScopeGlobal; + addr.mElement = kAudioObjectPropertyElementMaster; + size = sizeof(cdi->info.name); + AudioObjectGetPropertyData(cdi->dev_id, &addr, + 0, NULL, + &size, (void *)cdi->info.name); - strcpy(cdi->info.driver, "core audio"); + strcpy(cdi->info.driver, "core audio"); /* Get the number of input channels */ - addr.mSelector = kAudioDevicePropertyStreamConfiguration; - addr.mScope = kAudioDevicePropertyScopeInput; - size = 0; - ostatus = AudioObjectGetPropertyDataSize(cdi->dev_id, &addr, - 0, NULL, &size); - if (ostatus == noErr && size > 0) { - - if (size > buf_size) { - buf = pj_pool_alloc(cf->pool, size); - buf_size = size; - } - if (buf) { - UInt32 idx; - - /* Get the input stream configuration */ - ostatus = AudioObjectGetPropertyData(cdi->dev_id, &addr, - 0, NULL, - &size, buf); - if (ostatus == noErr) { - /* Count the total number of input channels in - * the stream - */ - for (idx = 0; idx < buf->mNumberBuffers; idx++) { - cdi->info.input_count += - buf->mBuffers[idx].mNumberChannels; - } - } - } - } + addr.mSelector = kAudioDevicePropertyStreamConfiguration; + addr.mScope = kAudioDevicePropertyScopeInput; + size = 0; + ostatus = AudioObjectGetPropertyDataSize(cdi->dev_id, &addr, + 0, NULL, &size); + if (ostatus == noErr && size > 0) { + + if (size > buf_size) { + buf = pj_pool_alloc(cf->pool, size); + buf_size = size; + } + if (buf) { + UInt32 idx; + + /* Get the input stream configuration */ + ostatus = AudioObjectGetPropertyData(cdi->dev_id, &addr, + 0, NULL, + &size, buf); + if (ostatus == noErr) { + /* Count the total number of input channels in + * the stream + */ + for (idx = 0; idx < buf->mNumberBuffers; idx++) { + cdi->info.input_count += + buf->mBuffers[idx].mNumberChannels; + } + } + } + } /* Get the number of output channels */ - addr.mScope = kAudioDevicePropertyScopeOutput; - size = 0; - ostatus = AudioObjectGetPropertyDataSize(cdi->dev_id, &addr, - 0, NULL, &size); - if (ostatus == noErr && size > 0) { - - if (size > buf_size) { - buf = pj_pool_alloc(cf->pool, size); - buf_size = size; - } - if (buf) { - UInt32 idx; - - /* Get the output stream configuration */ - ostatus = AudioObjectGetPropertyData(cdi->dev_id, &addr, - 0, NULL, - &size, buf); - if (ostatus == noErr) { - /* Count the total number of output channels in - * the stream - */ - for (idx = 0; idx < buf->mNumberBuffers; idx++) { - cdi->info.output_count += - buf->mBuffers[idx].mNumberChannels; - } - } - } - } - - /* Get default sample rate */ - addr.mSelector = kAudioDevicePropertyNominalSampleRate; - addr.mScope = kAudioObjectPropertyScopeGlobal; - size = sizeof(Float64); - ostatus = AudioObjectGetPropertyData (cdi->dev_id, &addr, - 0, NULL, - &size, &sampleRate); - cdi->info.default_samples_per_sec = (ostatus == noErr ? - sampleRate: - 16000); - - /* Set device capabilities here */ - if (cdi->info.input_count > 0) { - cdi->info.caps |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; - } - if (cdi->info.output_count > 0) { - cdi->info.caps |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; - addr.mSelector = kAudioDevicePropertyVolumeScalar; - addr.mScope = kAudioDevicePropertyScopeOutput; - if (AudioObjectHasProperty(cdi->dev_id, &addr)) { - cdi->info.caps |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; - } - } - if (cf->has_vpio) { - cdi->info.caps |= PJMEDIA_AUD_DEV_CAP_EC; - } - - cf->dev_count++; - - PJ_LOG(4, (THIS_FILE, " dev_id %d: %s (in=%d, out=%d) %dHz", - cdi->dev_id, - cdi->info.name, - cdi->info.input_count, - cdi->info.output_count, - cdi->info.default_samples_per_sec)); + addr.mScope = kAudioDevicePropertyScopeOutput; + size = 0; + ostatus = AudioObjectGetPropertyDataSize(cdi->dev_id, &addr, + 0, NULL, &size); + if (ostatus == noErr && size > 0) { + + if (size > buf_size) { + buf = pj_pool_alloc(cf->pool, size); + buf_size = size; + } + if (buf) { + UInt32 idx; + + /* Get the output stream configuration */ + ostatus = AudioObjectGetPropertyData(cdi->dev_id, &addr, + 0, NULL, + &size, buf); + if (ostatus == noErr) { + /* Count the total number of output channels in + * the stream + */ + for (idx = 0; idx < buf->mNumberBuffers; idx++) { + cdi->info.output_count += + buf->mBuffers[idx].mNumberChannels; + } + } + } + } + + /* Get default sample rate */ + addr.mSelector = kAudioDevicePropertyNominalSampleRate; + addr.mScope = kAudioObjectPropertyScopeGlobal; + size = sizeof(Float64); + ostatus = AudioObjectGetPropertyData (cdi->dev_id, &addr, + 0, NULL, + &size, &sampleRate); + cdi->info.default_samples_per_sec = (ostatus == noErr ? + sampleRate: + 16000); + + /* Set device capabilities here */ + if (cdi->info.input_count > 0) { + cdi->info.caps |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; + } + if (cdi->info.output_count > 0) { + cdi->info.caps |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; + addr.mSelector = kAudioDevicePropertyVolumeScalar; + addr.mScope = kAudioDevicePropertyScopeOutput; + if (AudioObjectHasProperty(cdi->dev_id, &addr)) { + cdi->info.caps |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; + } + } + if (cf->has_vpio) { + cdi->info.caps |= PJMEDIA_AUD_DEV_CAP_EC; + } + + cf->dev_count++; + + PJ_LOG(4, (THIS_FILE, " dev_id %d: %s (in=%d, out=%d) %dHz", + cdi->dev_id, + cdi->info.name, + cdi->info.input_count, + cdi->info.output_count, + cdi->info.default_samples_per_sec)); } return PJ_SUCCESS; @@ -663,8 +662,8 @@ static unsigned ca_factory_get_dev_count(pjmedia_aud_dev_factory *f) /* API: get device info */ static pj_status_t ca_factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info) + unsigned index, + pjmedia_aud_dev_info *info) { struct coreaudio_factory *cf = (struct coreaudio_factory*)f; @@ -677,8 +676,8 @@ static pj_status_t ca_factory_get_dev_info(pjmedia_aud_dev_factory *f, /* API: create default device parameter */ static pj_status_t ca_factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param) + unsigned index, + pjmedia_aud_param *param) { struct coreaudio_factory *cf = (struct coreaudio_factory*)f; struct coreaudio_dev_info *di = &cf->dev_info[index]; @@ -687,19 +686,19 @@ static pj_status_t ca_factory_default_param(pjmedia_aud_dev_factory *f, pj_bzero(param, sizeof(*param)); if (di->info.input_count && di->info.output_count) { - param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; - param->rec_id = index; - param->play_id = index; + param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; + param->rec_id = index; + param->play_id = index; } else if (di->info.input_count) { - param->dir = PJMEDIA_DIR_CAPTURE; - param->rec_id = index; - param->play_id = PJMEDIA_AUD_INVALID_DEV; + param->dir = PJMEDIA_DIR_CAPTURE; + param->rec_id = index; + param->play_id = PJMEDIA_AUD_INVALID_DEV; } else if (di->info.output_count) { - param->dir = PJMEDIA_DIR_PLAYBACK; - param->play_id = index; - param->rec_id = PJMEDIA_AUD_INVALID_DEV; + param->dir = PJMEDIA_DIR_PLAYBACK; + param->play_id = index; + param->rec_id = PJMEDIA_AUD_INVALID_DEV; } else { - return PJMEDIA_EAUD_INVDEV; + return PJMEDIA_EAUD_INVDEV; } /* Set the mandatory settings here */ @@ -710,7 +709,7 @@ static pj_status_t ca_factory_default_param(pjmedia_aud_dev_factory *f, /* Set the param for device capabilities here */ param->flags = PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; + PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; param->input_latency_ms = PJMEDIA_SND_DEFAULT_REC_LATENCY; param->output_latency_ms = PJMEDIA_SND_DEFAULT_PLAY_LATENCY; @@ -718,32 +717,32 @@ static pj_status_t ca_factory_default_param(pjmedia_aud_dev_factory *f, } OSStatus resampleProc(AudioConverterRef inAudioConverter, - UInt32 *ioNumberDataPackets, - AudioBufferList *ioData, - AudioStreamPacketDescription **outDataPacketDescription, - void *inUserData) + UInt32 *ioNumberDataPackets, + AudioBufferList *ioData, + AudioStreamPacketDescription **outDataPacketDescription, + void *inUserData) { struct coreaudio_stream *strm = (struct coreaudio_stream*)inUserData; if (*ioNumberDataPackets > strm->resample_buf_size) - *ioNumberDataPackets = strm->resample_buf_size; + *ioNumberDataPackets = strm->resample_buf_size; ioData->mNumberBuffers = 1; ioData->mBuffers[0].mNumberChannels = strm->streamFormat.mChannelsPerFrame; ioData->mBuffers[0].mData = strm->resample_buf_ptr; ioData->mBuffers[0].mDataByteSize = *ioNumberDataPackets * - strm->streamFormat.mChannelsPerFrame * - strm->param.bits_per_sample >> 3; + strm->streamFormat.mChannelsPerFrame * + strm->param.bits_per_sample >> 3; return noErr; } static OSStatus resample_callback(void *inRefCon, - AudioUnitRenderActionFlags *ioActionFlags, - const AudioTimeStamp *inTimeStamp, - UInt32 inBusNumber, - UInt32 inNumberFrames, - AudioBufferList *ioData) + AudioUnitRenderActionFlags *ioActionFlags, + const AudioTimeStamp *inTimeStamp, + UInt32 inBusNumber, + UInt32 inNumberFrames, + AudioBufferList *ioData) { struct coreaudio_stream *strm = (struct coreaudio_stream*)inRefCon; OSStatus ostatus; @@ -764,125 +763,125 @@ static OSStatus resample_callback(void *inRefCon, */ if (strm->rec_thread_initialized == 0 || !pj_thread_is_registered()) { - pj_bzero(strm->rec_thread_desc, sizeof(pj_thread_desc)); - status = pj_thread_register("ca_rec", strm->rec_thread_desc, - &strm->rec_thread); - strm->rec_thread_initialized = 1; - PJ_LOG(5,(THIS_FILE, "Recorder thread started, (%i frames)", - inNumberFrames)); + pj_bzero(strm->rec_thread_desc, sizeof(pj_thread_desc)); + status = pj_thread_register("ca_rec", strm->rec_thread_desc, + &strm->rec_thread); + strm->rec_thread_initialized = 1; + PJ_LOG(5,(THIS_FILE, "Recorder thread started, (%i frames)", + inNumberFrames)); } buf->mBuffers[0].mData = NULL; buf->mBuffers[0].mDataByteSize = inNumberFrames * - strm->streamFormat.mChannelsPerFrame; + strm->streamFormat.mChannelsPerFrame; /* Render the unit to get input data */ ostatus = AudioUnitRender(strm->io_units[0], - ioActionFlags, - inTimeStamp, - inBusNumber, - inNumberFrames, - buf); + ioActionFlags, + inTimeStamp, + inBusNumber, + inNumberFrames, + buf); if (ostatus != noErr) { - PJ_LOG(5, (THIS_FILE, "Core audio unit render error %i", ostatus)); - goto on_break; + PJ_LOG(5, (THIS_FILE, "Core audio unit render error %i", ostatus)); + goto on_break; } input = (pj_int16_t *)buf->mBuffers[0].mData; resampleSize = strm->resample_buf_size; nsamples = inNumberFrames * strm->param.channel_count + - strm->resample_buf_count; + strm->resample_buf_count; if (nsamples >= resampleSize) { - pjmedia_frame frame; - UInt32 resampleOutput = strm->param.samples_per_frame / - strm->streamFormat.mChannelsPerFrame; - AudioBufferList ab; - - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = (void*) strm->rec_buf; - frame.size = strm->param.samples_per_frame * - strm->param.bits_per_sample >> 3; - frame.bit_info = 0; - - ab.mNumberBuffers = 1; - ab.mBuffers[0].mNumberChannels = strm->streamFormat.mChannelsPerFrame; - ab.mBuffers[0].mData = strm->rec_buf; - ab.mBuffers[0].mDataByteSize = frame.size; - - /* If buffer is not empty, combine the buffer with the just incoming - * samples, then call put_frame. - */ - if (strm->resample_buf_count) { - unsigned chunk_count = resampleSize - strm->resample_buf_count; - pjmedia_copy_samples(strm->resample_buf + strm->resample_buf_count, - input, chunk_count); - - /* Do the resample */ - - strm->resample_buf_ptr = strm->resample_buf; - ostatus = AudioConverterFillComplexBuffer(strm->resample, - resampleProc, - strm, - &resampleOutput, - &ab, - NULL); - if (ostatus != noErr) { - goto on_break; - } - frame.timestamp.u64 = strm->rec_timestamp.u64; - - status = (*strm->rec_cb)(strm->user_data, &frame); - - input = input + chunk_count; - nsamples -= resampleSize; - strm->resample_buf_count = 0; - strm->rec_timestamp.u64 += strm->param.samples_per_frame / - strm->param.channel_count; - } - - - /* Give all frames we have */ - while (nsamples >= resampleSize && status == 0) { - frame.timestamp.u64 = strm->rec_timestamp.u64; - - /* Do the resample */ - strm->resample_buf_ptr = input; - ab.mBuffers[0].mDataByteSize = frame.size; - resampleOutput = strm->param.samples_per_frame / - strm->streamFormat.mChannelsPerFrame; - ostatus = AudioConverterFillComplexBuffer(strm->resample, - resampleProc, - strm, - &resampleOutput, - &ab, - NULL); - if (ostatus != noErr) { - goto on_break; - } - - status = (*strm->rec_cb)(strm->user_data, &frame); - - input = (pj_int16_t*) input + resampleSize; - nsamples -= resampleSize; - strm->rec_timestamp.u64 += strm->param.samples_per_frame / - strm->param.channel_count; - } - - /* Store the remaining samples into the buffer */ - if (nsamples && status == 0) { - strm->resample_buf_count = nsamples; - pjmedia_copy_samples(strm->resample_buf, input, - nsamples); - } + pjmedia_frame frame; + UInt32 resampleOutput = strm->param.samples_per_frame / + strm->streamFormat.mChannelsPerFrame; + AudioBufferList ab; + + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = (void*) strm->rec_buf; + frame.size = strm->param.samples_per_frame * + strm->param.bits_per_sample >> 3; + frame.bit_info = 0; + + ab.mNumberBuffers = 1; + ab.mBuffers[0].mNumberChannels = strm->streamFormat.mChannelsPerFrame; + ab.mBuffers[0].mData = strm->rec_buf; + ab.mBuffers[0].mDataByteSize = frame.size; + + /* If buffer is not empty, combine the buffer with the just incoming + * samples, then call put_frame. + */ + if (strm->resample_buf_count) { + unsigned chunk_count = resampleSize - strm->resample_buf_count; + pjmedia_copy_samples(strm->resample_buf + strm->resample_buf_count, + input, chunk_count); + + /* Do the resample */ + + strm->resample_buf_ptr = strm->resample_buf; + ostatus = AudioConverterFillComplexBuffer(strm->resample, + resampleProc, + strm, + &resampleOutput, + &ab, + NULL); + if (ostatus != noErr) { + goto on_break; + } + frame.timestamp.u64 = strm->rec_timestamp.u64; + + status = (*strm->rec_cb)(strm->user_data, &frame); + + input = input + chunk_count; + nsamples -= resampleSize; + strm->resample_buf_count = 0; + strm->rec_timestamp.u64 += strm->param.samples_per_frame / + strm->param.channel_count; + } + + + /* Give all frames we have */ + while (nsamples >= resampleSize && status == 0) { + frame.timestamp.u64 = strm->rec_timestamp.u64; + + /* Do the resample */ + strm->resample_buf_ptr = input; + ab.mBuffers[0].mDataByteSize = frame.size; + resampleOutput = strm->param.samples_per_frame / + strm->streamFormat.mChannelsPerFrame; + ostatus = AudioConverterFillComplexBuffer(strm->resample, + resampleProc, + strm, + &resampleOutput, + &ab, + NULL); + if (ostatus != noErr) { + goto on_break; + } + + status = (*strm->rec_cb)(strm->user_data, &frame); + + input = (pj_int16_t*) input + resampleSize; + nsamples -= resampleSize; + strm->rec_timestamp.u64 += strm->param.samples_per_frame / + strm->param.channel_count; + } + + /* Store the remaining samples into the buffer */ + if (nsamples && status == 0) { + strm->resample_buf_count = nsamples; + pjmedia_copy_samples(strm->resample_buf, input, + nsamples); + } } else { - /* Not enough samples, let's just store them in the buffer */ - pjmedia_copy_samples(strm->resample_buf + strm->resample_buf_count, - input, - inNumberFrames * strm->param.channel_count); - strm->resample_buf_count += inNumberFrames * - strm->param.channel_count; + /* Not enough samples, let's just store them in the buffer */ + pjmedia_copy_samples(strm->resample_buf + strm->resample_buf_count, + input, + inNumberFrames * strm->param.channel_count); + strm->resample_buf_count += inNumberFrames * + strm->param.channel_count; } return noErr; @@ -916,90 +915,90 @@ static OSStatus input_callback(void *inRefCon, */ if (strm->rec_thread_initialized == 0 || !pj_thread_is_registered()) { - pj_bzero(strm->rec_thread_desc, sizeof(pj_thread_desc)); - status = pj_thread_register("ca_rec", strm->rec_thread_desc, - &strm->rec_thread); - strm->rec_thread_initialized = 1; - PJ_LOG(5,(THIS_FILE, "Recorder thread started, (%i frames)", - inNumberFrames)); + pj_bzero(strm->rec_thread_desc, sizeof(pj_thread_desc)); + status = pj_thread_register("ca_rec", strm->rec_thread_desc, + &strm->rec_thread); + strm->rec_thread_initialized = 1; + PJ_LOG(5,(THIS_FILE, "Recorder thread started, (%i frames)", + inNumberFrames)); } buf->mBuffers[0].mData = NULL; buf->mBuffers[0].mDataByteSize = inNumberFrames * - strm->streamFormat.mChannelsPerFrame; + strm->streamFormat.mChannelsPerFrame; /* Render the unit to get input data */ ostatus = AudioUnitRender(strm->io_units[0], - ioActionFlags, - inTimeStamp, - inBusNumber, - inNumberFrames, - buf); + ioActionFlags, + inTimeStamp, + inBusNumber, + inNumberFrames, + buf); if (ostatus != noErr) { - PJ_LOG(5, (THIS_FILE, "Core audio unit render error %i", ostatus)); - goto on_break; + PJ_LOG(5, (THIS_FILE, "Core audio unit render error %i", ostatus)); + goto on_break; } input = (pj_int16_t *)buf->mBuffers[0].mData; /* Calculate number of samples we've got */ nsamples = inNumberFrames * strm->param.channel_count + - strm->rec_buf_count; + strm->rec_buf_count; if (nsamples >= strm->param.samples_per_frame) { - pjmedia_frame frame; - - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.size = strm->param.samples_per_frame * - strm->param.bits_per_sample >> 3; - frame.bit_info = 0; - - /* If buffer is not empty, combine the buffer with the just incoming - * samples, then call put_frame. - */ - if (strm->rec_buf_count) { - unsigned chunk_count = 0; - - chunk_count = strm->param.samples_per_frame - strm->rec_buf_count; - pjmedia_copy_samples(strm->rec_buf + strm->rec_buf_count, - input, chunk_count); - - frame.buf = (void*) strm->rec_buf; - frame.timestamp.u64 = strm->rec_timestamp.u64; - - status = (*strm->rec_cb)(strm->user_data, &frame); - - input = input + chunk_count; - nsamples -= strm->param.samples_per_frame; - strm->rec_buf_count = 0; - strm->rec_timestamp.u64 += strm->param.samples_per_frame / - strm->param.channel_count; - } - - /* Give all frames we have */ - while (nsamples >= strm->param.samples_per_frame && status == 0) { - frame.buf = (void*) input; - frame.timestamp.u64 = strm->rec_timestamp.u64; - - status = (*strm->rec_cb)(strm->user_data, &frame); - - input = (pj_int16_t*) input + strm->param.samples_per_frame; - nsamples -= strm->param.samples_per_frame; - strm->rec_timestamp.u64 += strm->param.samples_per_frame / - strm->param.channel_count; - } - - /* Store the remaining samples into the buffer */ - if (nsamples && status == 0) { - strm->rec_buf_count = nsamples; - pjmedia_copy_samples(strm->rec_buf, input, - nsamples); - } + pjmedia_frame frame; + + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.size = strm->param.samples_per_frame * + strm->param.bits_per_sample >> 3; + frame.bit_info = 0; + + /* If buffer is not empty, combine the buffer with the just incoming + * samples, then call put_frame. + */ + if (strm->rec_buf_count) { + unsigned chunk_count = 0; + + chunk_count = strm->param.samples_per_frame - strm->rec_buf_count; + pjmedia_copy_samples(strm->rec_buf + strm->rec_buf_count, + input, chunk_count); + + frame.buf = (void*) strm->rec_buf; + frame.timestamp.u64 = strm->rec_timestamp.u64; + + status = (*strm->rec_cb)(strm->user_data, &frame); + + input = input + chunk_count; + nsamples -= strm->param.samples_per_frame; + strm->rec_buf_count = 0; + strm->rec_timestamp.u64 += strm->param.samples_per_frame / + strm->param.channel_count; + } + + /* Give all frames we have */ + while (nsamples >= strm->param.samples_per_frame && status == 0) { + frame.buf = (void*) input; + frame.timestamp.u64 = strm->rec_timestamp.u64; + + status = (*strm->rec_cb)(strm->user_data, &frame); + + input = (pj_int16_t*) input + strm->param.samples_per_frame; + nsamples -= strm->param.samples_per_frame; + strm->rec_timestamp.u64 += strm->param.samples_per_frame / + strm->param.channel_count; + } + + /* Store the remaining samples into the buffer */ + if (nsamples && status == 0) { + strm->rec_buf_count = nsamples; + pjmedia_copy_samples(strm->rec_buf, input, + nsamples); + } } else { - /* Not enough samples, let's just store them in the buffer */ - pjmedia_copy_samples(strm->rec_buf + strm->rec_buf_count, - input, - inNumberFrames * strm->param.channel_count); - strm->rec_buf_count += inNumberFrames * strm->param.channel_count; + /* Not enough samples, let's just store them in the buffer */ + pjmedia_copy_samples(strm->rec_buf + strm->rec_buf_count, + input, + inNumberFrames * strm->param.channel_count); + strm->rec_buf_count += inNumberFrames * strm->param.channel_count; } return noErr; @@ -1012,22 +1011,22 @@ static OSStatus input_callback(void *inRefCon, * either 16-bit signed int, or float. */ static void copy_samples(void *dst, unsigned *dst_pos, unsigned dst_elmt_size, - pj_int16_t *src, unsigned nsamples) + pj_int16_t *src, unsigned nsamples) { if (dst_elmt_size == sizeof(pj_int16_t)) { - /* Destination is also 16-bit signed int. */ - pjmedia_copy_samples((pj_int16_t*)dst + *dst_pos, src, nsamples); + /* Destination is also 16-bit signed int. */ + pjmedia_copy_samples((pj_int16_t*)dst + *dst_pos, src, nsamples); } else { - /* Convert it first to float. */ - unsigned i; - float *fdst = (float *)dst; + /* Convert it first to float. */ + unsigned i; + float *fdst = (float *)dst; - pj_assert(dst_elmt_size == sizeof(Float32)); + pj_assert(dst_elmt_size == sizeof(Float32)); - for (i = 0; i< nsamples; i++) { - /* Value needs to be between -1.0 to 1.0 */ - fdst[*dst_pos + i] = (float)src[i] / 32768.0f; - } + for (i = 0; i< nsamples; i++) { + /* Value needs to be between -1.0 to 1.0 */ + fdst[*dst_pos + i] = (float)src[i] / 32768.0f; + } } *dst_pos += nsamples; } @@ -1044,7 +1043,7 @@ static OSStatus output_renderer(void *inRefCon, unsigned nsamples_req = inNumberFrames * stream->param.channel_count; void *output = ioData->mBuffers[0].mData; unsigned elmt_size = ioData->mBuffers[0].mDataByteSize / inNumberFrames / - stream->param.channel_count; + stream->param.channel_count; unsigned output_pos = 0; pj_assert(!stream->quit_flag); @@ -1058,91 +1057,91 @@ static OSStatus output_renderer(void *inRefCon, */ if (stream->play_thread_initialized == 0 || !pj_thread_is_registered()) { - pj_bzero(stream->play_thread_desc, sizeof(pj_thread_desc)); - status = pj_thread_register("coreaudio", stream->play_thread_desc, - &stream->play_thread); - stream->play_thread_initialized = 1; - PJ_LOG(5,(THIS_FILE, "Player thread started, (%i frames)", - inNumberFrames)); + pj_bzero(stream->play_thread_desc, sizeof(pj_thread_desc)); + status = pj_thread_register("coreaudio", stream->play_thread_desc, + &stream->play_thread); + stream->play_thread_initialized = 1; + PJ_LOG(5,(THIS_FILE, "Player thread started, (%i frames)", + inNumberFrames)); } /* Check if any buffered samples */ if (stream->play_buf_count) { - /* samples buffered >= requested by sound device */ - if (stream->play_buf_count >= nsamples_req) { - copy_samples(output, &output_pos, elmt_size, - stream->play_buf, nsamples_req); - stream->play_buf_count -= nsamples_req; - pjmedia_move_samples(stream->play_buf, - stream->play_buf + nsamples_req, - stream->play_buf_count); - nsamples_req = 0; - - return noErr; - } - - /* samples buffered < requested by sound device */ - copy_samples(output, &output_pos, elmt_size, - stream->play_buf, stream->play_buf_count); - nsamples_req -= stream->play_buf_count; - stream->play_buf_count = 0; + /* samples buffered >= requested by sound device */ + if (stream->play_buf_count >= nsamples_req) { + copy_samples(output, &output_pos, elmt_size, + stream->play_buf, nsamples_req); + stream->play_buf_count -= nsamples_req; + pjmedia_move_samples(stream->play_buf, + stream->play_buf + nsamples_req, + stream->play_buf_count); + nsamples_req = 0; + + return noErr; + } + + /* samples buffered < requested by sound device */ + copy_samples(output, &output_pos, elmt_size, + stream->play_buf, stream->play_buf_count); + nsamples_req -= stream->play_buf_count; + stream->play_buf_count = 0; } /* Fill output buffer as requested */ while (nsamples_req && status == 0) { - pjmedia_frame frame; - - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.size = stream->param.samples_per_frame * - stream->param.bits_per_sample >> 3; - frame.timestamp.u64 = stream->play_timestamp.u64; - frame.bit_info = 0; - - if (nsamples_req >= stream->param.samples_per_frame) { - /* If the output buffer is 16-bit signed int, we can - * directly use the supplied buffer. - */ - if (elmt_size == sizeof(pj_int16_t)) { - frame.buf = (pj_int16_t *)output + output_pos; - } else { - frame.buf = stream->play_buf; - } - status = (*stream->play_cb)(stream->user_data, &frame); - if (status != PJ_SUCCESS) - goto on_break; - - if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) - pj_bzero(frame.buf, frame.size); - - nsamples_req -= stream->param.samples_per_frame; - if (elmt_size == sizeof(pj_int16_t)) { - output_pos += stream->param.samples_per_frame; - } else { - copy_samples(output, &output_pos, elmt_size, stream->play_buf, - stream->param.samples_per_frame); - } - } else { - frame.buf = stream->play_buf; - status = (*stream->play_cb)(stream->user_data, &frame); - if (status != PJ_SUCCESS) - goto on_break; - - if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) - pj_bzero(frame.buf, frame.size); - - copy_samples(output, &output_pos, elmt_size, - stream->play_buf, nsamples_req); - stream->play_buf_count = stream->param.samples_per_frame - - nsamples_req; - pjmedia_move_samples(stream->play_buf, - stream->play_buf+nsamples_req, - stream->play_buf_count); - nsamples_req = 0; - } - - stream->play_timestamp.u64 += stream->param.samples_per_frame / - stream->param.channel_count; + pjmedia_frame frame; + + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.size = stream->param.samples_per_frame * + stream->param.bits_per_sample >> 3; + frame.timestamp.u64 = stream->play_timestamp.u64; + frame.bit_info = 0; + + if (nsamples_req >= stream->param.samples_per_frame) { + /* If the output buffer is 16-bit signed int, we can + * directly use the supplied buffer. + */ + if (elmt_size == sizeof(pj_int16_t)) { + frame.buf = (pj_int16_t *)output + output_pos; + } else { + frame.buf = stream->play_buf; + } + status = (*stream->play_cb)(stream->user_data, &frame); + if (status != PJ_SUCCESS) + goto on_break; + + if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) + pj_bzero(frame.buf, frame.size); + + nsamples_req -= stream->param.samples_per_frame; + if (elmt_size == sizeof(pj_int16_t)) { + output_pos += stream->param.samples_per_frame; + } else { + copy_samples(output, &output_pos, elmt_size, stream->play_buf, + stream->param.samples_per_frame); + } + } else { + frame.buf = stream->play_buf; + status = (*stream->play_cb)(stream->user_data, &frame); + if (status != PJ_SUCCESS) + goto on_break; + + if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) + pj_bzero(frame.buf, frame.size); + + copy_samples(output, &output_pos, elmt_size, + stream->play_buf, nsamples_req); + stream->play_buf_count = stream->param.samples_per_frame - + nsamples_req; + pjmedia_move_samples(stream->play_buf, + stream->play_buf+nsamples_req, + stream->play_buf_count); + nsamples_req = 0; + } + + stream->play_timestamp.u64 += stream->param.samples_per_frame / + stream->param.channel_count; } return noErr; @@ -1152,10 +1151,10 @@ static OSStatus output_renderer(void *inRefCon, } #if !COREAUDIO_MAC && USE_AUDIO_SESSION_API != 0 -static void propListener(void *inClientData, - AudioSessionPropertyID inID, - UInt32 inDataSize, - const void * inData) +static void propListener(void *inClientData, + AudioSessionPropertyID inID, + UInt32 inDataSize, + const void * inData) { struct coreaudio_factory *cf = (struct coreaudio_factory*)inClientData; struct stream_list *it, *itBegin; @@ -1165,18 +1164,18 @@ static void propListener(void *inClientData, pj_assert(cf); if (inID != kAudioSessionProperty_AudioRouteChange) - return; + return; routeDictionary = (CFDictionaryRef)inData; reason = (CFNumberRef) - CFDictionaryGetValue( - routeDictionary, - CFSTR(kAudioSession_AudioRouteChangeKey_Reason)); + CFDictionaryGetValue( + routeDictionary, + CFSTR(kAudioSession_AudioRouteChangeKey_Reason)); CFNumberGetValue(reason, kCFNumberSInt32Type, &reasonVal); if (reasonVal != kAudioSessionRouteChangeReason_OldDeviceUnavailable) { - PJ_LOG(3, (THIS_FILE, "ignoring audio route change...")); - return; + PJ_LOG(3, (THIS_FILE, "ignoring audio route change...")); + return; } PJ_LOG(3, (THIS_FILE, "audio route changed")); @@ -1184,20 +1183,20 @@ static void propListener(void *inClientData, pj_mutex_lock(cf->mutex); itBegin = &cf->streams; for (it = itBegin->next; it != itBegin; it = it->next) { - if (it->stream->interrupted) - continue; - - /* - status = ca_stream_stop((pjmedia_aud_stream *)it->stream); - status = ca_stream_start((pjmedia_aud_stream *)it->stream); - if (status != PJ_SUCCESS) { - PJ_LOG(3, (THIS_FILE, - "Error: failed to restart the audio unit (%i)", - status)); - continue; - } - PJ_LOG(3, (THIS_FILE, "core audio unit successfully restarted")); - */ + if (it->stream->interrupted) + continue; + + /* + status = ca_stream_stop((pjmedia_aud_stream *)it->stream); + status = ca_stream_start((pjmedia_aud_stream *)it->stream); + if (status != PJ_SUCCESS) { + PJ_LOG(3, (THIS_FILE, + "Error: failed to restart the audio unit (%i)", + status)); + continue; + } + PJ_LOG(3, (THIS_FILE, "core audio unit successfully restarted")); + */ } pj_mutex_unlock(cf->mutex); } @@ -1213,60 +1212,60 @@ static void interruptionListener(void *inClientData, UInt32 inInterruption) * which need to use the PJLIB framework. */ if (!pj_thread_is_registered()) { - pj_bzero(thread_desc, sizeof(pj_thread_desc)); - status = pj_thread_register("intListener", thread_desc, &thread); + pj_bzero(thread_desc, sizeof(pj_thread_desc)); + status = pj_thread_register("intListener", thread_desc, &thread); } PJ_LOG(3, (THIS_FILE, "Session interrupted! --- %s ---", - inInterruption == kAudioSessionBeginInterruption ? - "Begin Interruption" : "End Interruption")); + inInterruption == kAudioSessionBeginInterruption ? + "Begin Interruption" : "End Interruption")); if (!cf_instance) - return; + return; pj_mutex_lock(cf_instance->mutex); itBegin = &cf_instance->streams; for (it = itBegin->next; it != itBegin; it = it->next) { - if (inInterruption == kAudioSessionEndInterruption && - it->stream->interrupted == PJ_TRUE) - { - UInt32 audioCategory; - OSStatus ostatus; - - /* Make sure that your application can receive remote control - * events by adding the code: - * [[UIApplication sharedApplication] - * beginReceivingRemoteControlEvents]; - * Otherwise audio unit will fail to restart while your - * application is in the background mode. - */ - /* Make sure we set the correct audio category before restarting */ - audioCategory = kAudioSessionCategory_PlayAndRecord; - ostatus = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, - sizeof(audioCategory), - &audioCategory); - if (ostatus != kAudioSessionNoError) { - PJ_LOG(4, (THIS_FILE, - "Warning: cannot set the audio session category (%i)", - ostatus)); - } - - /* Restart the stream */ - status = ca_stream_start((pjmedia_aud_stream*)it->stream); - if (status != PJ_SUCCESS) { - PJ_LOG(3, (THIS_FILE, - "Error: failed to restart the audio unit (%i)", - status)); - continue; - } - PJ_LOG(3, (THIS_FILE, "core audio unit successfully resumed" - " after interruption")); - } else if (inInterruption == kAudioSessionBeginInterruption && - it->stream->running == PJ_TRUE) - { - status = ca_stream_stop((pjmedia_aud_stream*)it->stream); - it->stream->interrupted = PJ_TRUE; - } + if (inInterruption == kAudioSessionEndInterruption && + it->stream->interrupted == PJ_TRUE) + { + UInt32 audioCategory; + OSStatus ostatus; + + /* Make sure that your application can receive remote control + * events by adding the code: + * [[UIApplication sharedApplication] + * beginReceivingRemoteControlEvents]; + * Otherwise audio unit will fail to restart while your + * application is in the background mode. + */ + /* Make sure we set the correct audio category before restarting */ + audioCategory = kAudioSessionCategory_PlayAndRecord; + ostatus = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, + sizeof(audioCategory), + &audioCategory); + if (ostatus != kAudioSessionNoError) { + PJ_LOG(4, (THIS_FILE, + "Warning: cannot set the audio session category (%i)", + ostatus)); + } + + /* Restart the stream */ + status = ca_stream_start((pjmedia_aud_stream*)it->stream); + if (status != PJ_SUCCESS) { + PJ_LOG(3, (THIS_FILE, + "Error: failed to restart the audio unit (%i)", + status)); + continue; + } + PJ_LOG(3, (THIS_FILE, "core audio unit successfully resumed" + " after interruption")); + } else if (inInterruption == kAudioSessionBeginInterruption && + it->stream->running == PJ_TRUE) + { + status = ca_stream_stop((pjmedia_aud_stream*)it->stream); + it->stream->interrupted = PJ_TRUE; + } } pj_mutex_unlock(cf_instance->mutex); } @@ -1276,7 +1275,7 @@ static void interruptionListener(void *inClientData, UInt32 inInterruption) #if COREAUDIO_MAC /* Internal: create audio converter for resampling the recorder device */ static pj_status_t create_audio_resample(struct coreaudio_stream *strm, - AudioStreamBasicDescription *desc) + AudioStreamBasicDescription *desc) { OSStatus ostatus; @@ -1287,21 +1286,21 @@ static pj_status_t create_audio_resample(struct coreaudio_stream *strm, /* Create the audio converter */ ostatus = AudioConverterNew(desc, &strm->streamFormat, &strm->resample); if (ostatus != noErr) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); } /* * Allocate the buffer required to hold enough input data */ strm->resample_buf_size = (unsigned)(desc->mSampleRate * - strm->param.samples_per_frame / - strm->param.clock_rate); + strm->param.samples_per_frame / + strm->param.clock_rate); strm->resample_buf = (pj_int16_t*) - pj_pool_alloc(strm->pool, - strm->resample_buf_size * - strm->param.bits_per_sample >> 3); + pj_pool_alloc(strm->pool, + strm->resample_buf_size * + strm->param.bits_per_sample >> 3); if (!strm->resample_buf) - return PJ_ENOMEM; + return PJ_ENOMEM; strm->resample_buf_count = 0; return PJ_SUCCESS; @@ -1310,10 +1309,10 @@ static pj_status_t create_audio_resample(struct coreaudio_stream *strm, /* Internal: create audio unit for recorder/playback device */ static pj_status_t create_audio_unit(AudioComponent io_comp, - AudioDeviceID dev_id, - pjmedia_dir dir, - struct coreaudio_stream *strm, - AudioUnit *io_unit) + AudioDeviceID dev_id, + pjmedia_dir dir, + struct coreaudio_stream *strm, + AudioUnit *io_unit) { OSStatus ostatus; @@ -1324,326 +1323,326 @@ static pj_status_t create_audio_unit(AudioComponent io_comp, /* Create an audio unit to interface with the device */ ostatus = AudioComponentInstanceNew(io_comp, io_unit); if (ostatus != noErr) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); } /* Set audio unit's properties for capture device */ if (dir & PJMEDIA_DIR_CAPTURE) { - UInt32 enable = 1; - - /* Enable input */ - ostatus = AudioUnitSetProperty(*io_unit, - kAudioOutputUnitProperty_EnableIO, - kAudioUnitScope_Input, - 1, - &enable, - sizeof(enable)); - if (ostatus != noErr && !strm->param.ec_enabled) { - PJ_LOG(4, (THIS_FILE, - "Warning: cannot enable IO of capture device %d", - dev_id)); - } - - /* Disable output */ - if (!(dir & PJMEDIA_DIR_PLAYBACK)) { - enable = 0; - ostatus = AudioUnitSetProperty(*io_unit, - kAudioOutputUnitProperty_EnableIO, - kAudioUnitScope_Output, - 0, - &enable, - sizeof(enable)); - if (ostatus != noErr && !strm->param.ec_enabled) { - PJ_LOG(4, (THIS_FILE, - "Warning: cannot disable IO of capture device %d", - dev_id)); - } - } + UInt32 enable = 1; + + /* Enable input */ + ostatus = AudioUnitSetProperty(*io_unit, + kAudioOutputUnitProperty_EnableIO, + kAudioUnitScope_Input, + 1, + &enable, + sizeof(enable)); + if (ostatus != noErr && !strm->param.ec_enabled) { + PJ_LOG(4, (THIS_FILE, + "Warning: cannot enable IO of capture device %d", + dev_id)); + } + + /* Disable output */ + if (!(dir & PJMEDIA_DIR_PLAYBACK)) { + enable = 0; + ostatus = AudioUnitSetProperty(*io_unit, + kAudioOutputUnitProperty_EnableIO, + kAudioUnitScope_Output, + 0, + &enable, + sizeof(enable)); + if (ostatus != noErr && !strm->param.ec_enabled) { + PJ_LOG(4, (THIS_FILE, + "Warning: cannot disable IO of capture device %d", + dev_id)); + } + } } /* Set audio unit's properties for playback device */ if (dir & PJMEDIA_DIR_PLAYBACK) { - UInt32 enable = 1; - - /* Enable output */ - ostatus = AudioUnitSetProperty(*io_unit, - kAudioOutputUnitProperty_EnableIO, - kAudioUnitScope_Output, - 0, - &enable, - sizeof(enable)); - if (ostatus != noErr && !strm->param.ec_enabled) - { - PJ_LOG(4, (THIS_FILE, - "Warning: cannot enable IO of playback device %d", - dev_id)); - } + UInt32 enable = 1; + + /* Enable output */ + ostatus = AudioUnitSetProperty(*io_unit, + kAudioOutputUnitProperty_EnableIO, + kAudioUnitScope_Output, + 0, + &enable, + sizeof(enable)); + if (ostatus != noErr && !strm->param.ec_enabled) + { + PJ_LOG(4, (THIS_FILE, + "Warning: cannot enable IO of playback device %d", + dev_id)); + } } #if COREAUDIO_MAC if (!strm->param.ec_enabled) { - /* When using VPIO on Mac, we shouldn't set the current device. - * Doing so will cause getting the buffer size later to fail - * with kAudioUnitErr_InvalidProperty error (-10879). - */ - PJ_LOG(4, (THIS_FILE, "Setting current device %d", dev_id)); - ostatus = AudioUnitSetProperty(*io_unit, - kAudioOutputUnitProperty_CurrentDevice, - kAudioUnitScope_Global, - 0, - &dev_id, - sizeof(dev_id)); - if (ostatus != noErr) { - PJ_LOG(3, (THIS_FILE, "Failed setting current device %d, " - "error: %d", dev_id, ostatus)); - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } + /* When using VPIO on Mac, we shouldn't set the current device. + * Doing so will cause getting the buffer size later to fail + * with kAudioUnitErr_InvalidProperty error (-10879). + */ + PJ_LOG(4, (THIS_FILE, "Setting current device %d", dev_id)); + ostatus = AudioUnitSetProperty(*io_unit, + kAudioOutputUnitProperty_CurrentDevice, + kAudioUnitScope_Global, + 0, + &dev_id, + sizeof(dev_id)); + if (ostatus != noErr) { + PJ_LOG(3, (THIS_FILE, "Failed setting current device %d, " + "error: %d", dev_id, ostatus)); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } } #endif if (dir & PJMEDIA_DIR_CAPTURE) { #if COREAUDIO_MAC - AudioStreamBasicDescription deviceFormat; - UInt32 size; - - if (!strm->param.ec_enabled) { - /* Keep the sample rate from the device, otherwise we will confuse - * AUHAL. - */ - size = sizeof(AudioStreamBasicDescription); - ostatus = AudioUnitGetProperty(*io_unit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Input, - 1, - &deviceFormat, - &size); - if (ostatus != noErr) { - PJ_LOG(3, (THIS_FILE, "Failed getting stream format of device" - " %d, error: %d", dev_id, ostatus)); - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } - strm->streamFormat.mSampleRate = deviceFormat.mSampleRate; - } + AudioStreamBasicDescription deviceFormat; + UInt32 size; + + if (!strm->param.ec_enabled) { + /* Keep the sample rate from the device, otherwise we will confuse + * AUHAL. + */ + size = sizeof(AudioStreamBasicDescription); + ostatus = AudioUnitGetProperty(*io_unit, + kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Input, + 1, + &deviceFormat, + &size); + if (ostatus != noErr) { + PJ_LOG(3, (THIS_FILE, "Failed getting stream format of device" + " %d, error: %d", dev_id, ostatus)); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } + strm->streamFormat.mSampleRate = deviceFormat.mSampleRate; + } #endif - /* When setting the stream format, we have to make sure the sample - * rate is supported. Setting an unsupported sample rate will cause - * AudioUnitRender() to fail later. - */ - ostatus = AudioUnitSetProperty(*io_unit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Output, - 1, - &strm->streamFormat, - sizeof(strm->streamFormat)); - if (ostatus != noErr) { - PJ_LOG(3, (THIS_FILE, "Failed setting stream format of device %d" - ", error: %d", dev_id, ostatus)); - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } + /* When setting the stream format, we have to make sure the sample + * rate is supported. Setting an unsupported sample rate will cause + * AudioUnitRender() to fail later. + */ + ostatus = AudioUnitSetProperty(*io_unit, + kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Output, + 1, + &strm->streamFormat, + sizeof(strm->streamFormat)); + if (ostatus != noErr) { + PJ_LOG(3, (THIS_FILE, "Failed setting stream format of device %d" + ", error: %d", dev_id, ostatus)); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } #if COREAUDIO_MAC - strm->streamFormat.mSampleRate = strm->param.clock_rate; - size = sizeof(AudioStreamBasicDescription); - ostatus = AudioUnitGetProperty (*io_unit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Output, - 1, - &deviceFormat, - &size); - if (ostatus == noErr) { - if (strm->streamFormat.mSampleRate != deviceFormat.mSampleRate) { - PJ_LOG(4, (THIS_FILE, "Creating audio resample from %d to %d", - (int)deviceFormat.mSampleRate, - (int)strm->streamFormat.mSampleRate)); - pj_status_t rc = create_audio_resample(strm, &deviceFormat); - if (PJ_SUCCESS != rc) { - PJ_LOG(3, (THIS_FILE, "Failed creating resample %d", - rc)); - return rc; - } - } - } else { - PJ_LOG(3, (THIS_FILE, "Failed getting stream format of device %d" - " (2), error: %d", dev_id, ostatus)); - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } + strm->streamFormat.mSampleRate = strm->param.clock_rate; + size = sizeof(AudioStreamBasicDescription); + ostatus = AudioUnitGetProperty (*io_unit, + kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Output, + 1, + &deviceFormat, + &size); + if (ostatus == noErr) { + if (strm->streamFormat.mSampleRate != deviceFormat.mSampleRate) { + PJ_LOG(4, (THIS_FILE, "Creating audio resample from %d to %d", + (int)deviceFormat.mSampleRate, + (int)strm->streamFormat.mSampleRate)); + pj_status_t rc = create_audio_resample(strm, &deviceFormat); + if (PJ_SUCCESS != rc) { + PJ_LOG(3, (THIS_FILE, "Failed creating resample %d", + rc)); + return rc; + } + } + } else { + PJ_LOG(3, (THIS_FILE, "Failed getting stream format of device %d" + " (2), error: %d", dev_id, ostatus)); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } #endif } if (dir & PJMEDIA_DIR_PLAYBACK) { - AURenderCallbackStruct output_cb; - AudioStreamBasicDescription streamFormat = strm->streamFormat; + AURenderCallbackStruct output_cb; + AudioStreamBasicDescription streamFormat = strm->streamFormat; #if !COREAUDIO_MAC - BOOL isMacCatalystApp = false; + BOOL isMacCatalystApp = false; #ifdef __IPHONE_13_0 - if (@available(iOS 13.0, *)) { + if (@available(iOS 13.0, *)) { /* According to Apple's doc, the property isMacCatalystApp is true - * when the process is: + * when the process is: * - A Mac app built with Mac Catalyst, or an iOS app running on Apple silicon. * - Running on a Mac. */ isMacCatalystApp = [NSProcessInfo processInfo].isMacCatalystApp; - } + } #endif #endif - /* Set the stream format */ - if (strm->param.ec_enabled + /* Set the stream format */ + if (strm->param.ec_enabled #if !COREAUDIO_MAC - && isMacCatalystApp -#endif - ) { - /* When using VPIO on Mac, we need to use float data. Using - * signed integer will generate no errors, but strangely, - * no sound will be played. - */ - streamFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat | - kLinearPCMFormatFlagIsPacked; - streamFormat.mBitsPerChannel = sizeof(float) * 8; - streamFormat.mBytesPerFrame = streamFormat.mChannelsPerFrame * - streamFormat.mBitsPerChannel / 8; - streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * - streamFormat.mFramesPerPacket; - } - - ostatus = AudioUnitSetProperty(*io_unit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Input, - 0, - &streamFormat, - sizeof(streamFormat)); - if (ostatus != noErr) { - PJ_LOG(4, (THIS_FILE, - "Warning: cannot set playback stream format of dev %d", - dev_id)); - } - - /* Set render callback */ - output_cb.inputProc = output_renderer; - output_cb.inputProcRefCon = strm; - ostatus = AudioUnitSetProperty(*io_unit, - kAudioUnitProperty_SetRenderCallback, - kAudioUnitScope_Input, - 0, - &output_cb, - sizeof(output_cb)); - if (ostatus != noErr) { - PJ_LOG(3, (THIS_FILE, "Failed setting render callback %d", - ostatus)); - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } - - /* Allocate playback buffer */ - strm->play_buf = (pj_int16_t*)pj_pool_alloc(strm->pool, - strm->param.samples_per_frame * - (strm->param.ec_enabled? 2: 1) * - strm->param.bits_per_sample >> 3); - if (!strm->play_buf) - return PJ_ENOMEM; - strm->play_buf_count = 0; + && isMacCatalystApp +#endif + ) { + /* When using VPIO on Mac, we need to use float data. Using + * signed integer will generate no errors, but strangely, + * no sound will be played. + */ + streamFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat | + kLinearPCMFormatFlagIsPacked; + streamFormat.mBitsPerChannel = sizeof(float) * 8; + streamFormat.mBytesPerFrame = streamFormat.mChannelsPerFrame * + streamFormat.mBitsPerChannel / 8; + streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * + streamFormat.mFramesPerPacket; + } + + ostatus = AudioUnitSetProperty(*io_unit, + kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Input, + 0, + &streamFormat, + sizeof(streamFormat)); + if (ostatus != noErr) { + PJ_LOG(4, (THIS_FILE, + "Warning: cannot set playback stream format of dev %d", + dev_id)); + } + + /* Set render callback */ + output_cb.inputProc = output_renderer; + output_cb.inputProcRefCon = strm; + ostatus = AudioUnitSetProperty(*io_unit, + kAudioUnitProperty_SetRenderCallback, + kAudioUnitScope_Input, + 0, + &output_cb, + sizeof(output_cb)); + if (ostatus != noErr) { + PJ_LOG(3, (THIS_FILE, "Failed setting render callback %d", + ostatus)); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } + + /* Allocate playback buffer */ + strm->play_buf = (pj_int16_t*)pj_pool_alloc(strm->pool, + strm->param.samples_per_frame * + (strm->param.ec_enabled? 2: 1) * + strm->param.bits_per_sample >> 3); + if (!strm->play_buf) + return PJ_ENOMEM; + strm->play_buf_count = 0; } if (dir & PJMEDIA_DIR_CAPTURE) { - AURenderCallbackStruct input_cb; + AURenderCallbackStruct input_cb; #if COREAUDIO_MAC - AudioBuffer *ab; - UInt32 size, buf_size; + AudioBuffer *ab; + UInt32 size, buf_size; #endif - /* Set input callback */ - input_cb.inputProc = strm->resample ? resample_callback : - input_callback; - input_cb.inputProcRefCon = strm; - ostatus = AudioUnitSetProperty( - *io_unit, - kAudioOutputUnitProperty_SetInputCallback, - kAudioUnitScope_Global, - 1, - &input_cb, - sizeof(input_cb)); - if (ostatus != noErr) { - PJ_LOG(3, (THIS_FILE, "Failed setting input callback %d", - ostatus)); - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } + /* Set input callback */ + input_cb.inputProc = strm->resample ? resample_callback : + input_callback; + input_cb.inputProcRefCon = strm; + ostatus = AudioUnitSetProperty( + *io_unit, + kAudioOutputUnitProperty_SetInputCallback, + kAudioUnitScope_Global, + 1, + &input_cb, + sizeof(input_cb)); + if (ostatus != noErr) { + PJ_LOG(3, (THIS_FILE, "Failed setting input callback %d", + ostatus)); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } #if COREAUDIO_MAC - /* Set device's buffer frame size */ - size = sizeof(UInt32); - buf_size = (20 * strm->streamFormat.mSampleRate) / 1000; - ostatus = AudioUnitSetProperty (*io_unit, - kAudioDevicePropertyBufferFrameSize, - kAudioUnitScope_Global, - 0, - &buf_size, - size); - if (ostatus != noErr) { - PJ_LOG(3, (THIS_FILE, "Failed setting buffer size %d", - ostatus)); - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } - - /* Get device's buffer frame size */ - ostatus = AudioUnitGetProperty(*io_unit, - kAudioDevicePropertyBufferFrameSize, - kAudioUnitScope_Global, - 0, - &buf_size, - &size); - if (ostatus != noErr) { - PJ_LOG(3, (THIS_FILE, "Failed getting buffer size %d", - ostatus)); - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } - - /* Allocate audio buffer */ - strm->audio_buf = (AudioBufferList*)pj_pool_alloc(strm->pool, - sizeof(AudioBufferList) + sizeof(AudioBuffer)); - if (!strm->audio_buf) - return PJ_ENOMEM; - - strm->audio_buf->mNumberBuffers = 1; - ab = &strm->audio_buf->mBuffers[0]; - ab->mNumberChannels = strm->streamFormat.mChannelsPerFrame; - ab->mDataByteSize = buf_size * ab->mNumberChannels * - strm->streamFormat.mBitsPerChannel >> 3; - ab->mData = pj_pool_alloc(strm->pool, - ab->mDataByteSize); - if (!ab->mData) - return PJ_ENOMEM; + /* Set device's buffer frame size */ + size = sizeof(UInt32); + buf_size = (20 * strm->streamFormat.mSampleRate) / 1000; + ostatus = AudioUnitSetProperty (*io_unit, + kAudioDevicePropertyBufferFrameSize, + kAudioUnitScope_Global, + 0, + &buf_size, + size); + if (ostatus != noErr) { + PJ_LOG(3, (THIS_FILE, "Failed setting buffer size %d", + ostatus)); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } + + /* Get device's buffer frame size */ + ostatus = AudioUnitGetProperty(*io_unit, + kAudioDevicePropertyBufferFrameSize, + kAudioUnitScope_Global, + 0, + &buf_size, + &size); + if (ostatus != noErr) { + PJ_LOG(3, (THIS_FILE, "Failed getting buffer size %d", + ostatus)); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } + + /* Allocate audio buffer */ + strm->audio_buf = (AudioBufferList*)pj_pool_alloc(strm->pool, + sizeof(AudioBufferList) + sizeof(AudioBuffer)); + if (!strm->audio_buf) + return PJ_ENOMEM; + + strm->audio_buf->mNumberBuffers = 1; + ab = &strm->audio_buf->mBuffers[0]; + ab->mNumberChannels = strm->streamFormat.mChannelsPerFrame; + ab->mDataByteSize = buf_size * ab->mNumberChannels * + strm->streamFormat.mBitsPerChannel >> 3; + ab->mData = pj_pool_alloc(strm->pool, + ab->mDataByteSize); + if (!ab->mData) + return PJ_ENOMEM; #else - /* We will let AudioUnitRender() to allocate the buffer - * for us later - */ - strm->audio_buf = (AudioBufferList*)pj_pool_alloc(strm->pool, - sizeof(AudioBufferList) + sizeof(AudioBuffer)); - if (!strm->audio_buf) - return PJ_ENOMEM; - - strm->audio_buf->mNumberBuffers = 1; - strm->audio_buf->mBuffers[0].mNumberChannels = - strm->streamFormat.mChannelsPerFrame; - + /* We will let AudioUnitRender() to allocate the buffer + * for us later + */ + strm->audio_buf = (AudioBufferList*)pj_pool_alloc(strm->pool, + sizeof(AudioBufferList) + sizeof(AudioBuffer)); + if (!strm->audio_buf) + return PJ_ENOMEM; + + strm->audio_buf->mNumberBuffers = 1; + strm->audio_buf->mBuffers[0].mNumberChannels = + strm->streamFormat.mChannelsPerFrame; + #endif - /* Allocate recording buffer */ - strm->rec_buf = (pj_int16_t*)pj_pool_alloc(strm->pool, - strm->param.samples_per_frame * - strm->param.bits_per_sample >> 3); - if (!strm->rec_buf) - return PJ_ENOMEM; - strm->rec_buf_count = 0; + /* Allocate recording buffer */ + strm->rec_buf = (pj_int16_t*)pj_pool_alloc(strm->pool, + strm->param.samples_per_frame * + strm->param.bits_per_sample >> 3); + if (!strm->rec_buf) + return PJ_ENOMEM; + strm->rec_buf_count = 0; } /* Initialize the audio unit */ ostatus = AudioUnitInitialize(*io_unit); if (ostatus != noErr) { - PJ_LOG(3, (THIS_FILE, "Failed initializing audio unit %d", ostatus)); - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + PJ_LOG(3, (THIS_FILE, "Failed initializing audio unit %d", ostatus)); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); } return PJ_SUCCESS; @@ -1651,11 +1650,11 @@ static pj_status_t create_audio_unit(AudioComponent io_comp, /* API: create stream */ static pj_status_t ca_factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { struct coreaudio_factory *cf = (struct coreaudio_factory*)f; pj_pool_t *pool; @@ -1680,107 +1679,107 @@ static pj_status_t ca_factory_create_stream(pjmedia_aud_dev_factory *f, strm->streamFormat.mSampleRate = param->clock_rate; strm->streamFormat.mFormatID = kAudioFormatLinearPCM; strm->streamFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger - | kLinearPCMFormatFlagIsPacked; + | kLinearPCMFormatFlagIsPacked; strm->streamFormat.mBitsPerChannel = strm->param.bits_per_sample; strm->streamFormat.mChannelsPerFrame = param->channel_count; strm->streamFormat.mBytesPerFrame = strm->streamFormat.mChannelsPerFrame - * strm->streamFormat.mBitsPerChannel - / 8; + * strm->streamFormat.mBitsPerChannel + / 8; strm->streamFormat.mFramesPerPacket = 1; strm->streamFormat.mBytesPerPacket = strm->streamFormat.mBytesPerFrame * - strm->streamFormat.mFramesPerPacket; + strm->streamFormat.mFramesPerPacket; /* Apply input/output routes settings before we create the audio units */ if (param->flags & PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE) { - ca_stream_set_cap(&strm->base, - PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE, - ¶m->input_route); + ca_stream_set_cap(&strm->base, + PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE, + ¶m->input_route); } if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE) { - ca_stream_set_cap(&strm->base, - PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, - ¶m->output_route); + ca_stream_set_cap(&strm->base, + PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, + ¶m->output_route); } if (param->flags & PJMEDIA_AUD_DEV_CAP_EC) { #if COREAUDIO_MAC - /* Temporarily disable VPIO on Mac for stereo due to recording sound - * artefacts. - */ - if (param->channel_count > 1) { - strm->param.ec_enabled = PJ_FALSE; - } + /* Temporarily disable VPIO on Mac for stereo due to recording sound + * artefacts. + */ + if (param->channel_count > 1) { + strm->param.ec_enabled = PJ_FALSE; + } #endif - status = ca_stream_set_cap(&strm->base, - PJMEDIA_AUD_DEV_CAP_EC, - &strm->param.ec_enabled); - if (status != PJ_SUCCESS) - strm->param.ec_enabled = PJ_FALSE; + status = ca_stream_set_cap(&strm->base, + PJMEDIA_AUD_DEV_CAP_EC, + &strm->param.ec_enabled); + if (status != PJ_SUCCESS) + strm->param.ec_enabled = PJ_FALSE; } else { - pj_bool_t ec = PJ_FALSE; - ca_stream_set_cap(&strm->base, - PJMEDIA_AUD_DEV_CAP_EC, &ec); + pj_bool_t ec = PJ_FALSE; + ca_stream_set_cap(&strm->base, + PJMEDIA_AUD_DEV_CAP_EC, &ec); } #if !TARGET_OS_IPHONE if (strm->param.ec_enabled && - param->rec_id != PJMEDIA_AUD_DEFAULT_CAPTURE_DEV && - param->play_id != PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV) + param->rec_id != PJMEDIA_AUD_DEFAULT_CAPTURE_DEV && + param->play_id != PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV) { - PJ_LOG(4, (THIS_FILE, "Warning: audio device id settings are " - "ignored when using VPIO")); + PJ_LOG(4, (THIS_FILE, "Warning: audio device id settings are " + "ignored when using VPIO")); } #endif strm->io_units[0] = strm->io_units[1] = NULL; if ((param->dir == PJMEDIA_DIR_CAPTURE_PLAYBACK && - param->rec_id == param->play_id) || - (param->flags & PJMEDIA_AUD_DEV_CAP_EC && strm->param.ec_enabled)) + param->rec_id == param->play_id) || + (param->flags & PJMEDIA_AUD_DEV_CAP_EC && strm->param.ec_enabled)) { - /* If both input and output are on the same device or if EC is enabled, - * only create one audio unit to interface with the device(s). - */ - status = create_audio_unit(cf->io_comp, - cf->dev_info[param->rec_id].dev_id, - param->dir, strm, &strm->io_units[0]); - if (status != PJ_SUCCESS) - goto on_error; + /* If both input and output are on the same device or if EC is enabled, + * only create one audio unit to interface with the device(s). + */ + status = create_audio_unit(cf->io_comp, + cf->dev_info[param->rec_id].dev_id, + param->dir, strm, &strm->io_units[0]); + if (status != PJ_SUCCESS) + goto on_error; } else { - unsigned nunits = 0; - - if (param->dir & PJMEDIA_DIR_CAPTURE) { - status = create_audio_unit(cf->io_comp, - cf->dev_info[param->rec_id].dev_id, - PJMEDIA_DIR_CAPTURE, - strm, &strm->io_units[nunits++]); - if (status != PJ_SUCCESS) - goto on_error; - } - if (param->dir & PJMEDIA_DIR_PLAYBACK) { - - status = create_audio_unit(cf->io_comp, - cf->dev_info[param->play_id].dev_id, - PJMEDIA_DIR_PLAYBACK, - strm, &strm->io_units[nunits++]); - if (status != PJ_SUCCESS) - goto on_error; - } + unsigned nunits = 0; + + if (param->dir & PJMEDIA_DIR_CAPTURE) { + status = create_audio_unit(cf->io_comp, + cf->dev_info[param->rec_id].dev_id, + PJMEDIA_DIR_CAPTURE, + strm, &strm->io_units[nunits++]); + if (status != PJ_SUCCESS) + goto on_error; + } + if (param->dir & PJMEDIA_DIR_PLAYBACK) { + + status = create_audio_unit(cf->io_comp, + cf->dev_info[param->play_id].dev_id, + PJMEDIA_DIR_PLAYBACK, + strm, &strm->io_units[nunits++]); + if (status != PJ_SUCCESS) + goto on_error; + } } /* Apply the remaining settings */ if (param->flags & PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY) { - ca_stream_get_cap(&strm->base, - PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY, - &strm->param.input_latency_ms); + ca_stream_get_cap(&strm->base, + PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY, + &strm->param.input_latency_ms); } if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY) { - ca_stream_get_cap(&strm->base, - PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY, - &strm->param.output_latency_ms); + ca_stream_get_cap(&strm->base, + PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY, + &strm->param.output_latency_ms); } if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { - ca_stream_set_cap(&strm->base, - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - ¶m->output_vol); + ca_stream_set_cap(&strm->base, + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + ¶m->output_vol); } pj_mutex_lock(strm->cf->mutex); @@ -1801,7 +1800,7 @@ static pj_status_t ca_factory_create_stream(pjmedia_aud_dev_factory *f, /* API: Get stream info. */ static pj_status_t ca_stream_get_param(pjmedia_aud_stream *s, - pjmedia_aud_param *pi) + pjmedia_aud_param *pi) { struct coreaudio_stream *strm = (struct coreaudio_stream*)s; @@ -1811,32 +1810,32 @@ static pj_status_t ca_stream_get_param(pjmedia_aud_stream *s, /* Update the device capabilities' values */ if (ca_stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY, - &pi->input_latency_ms) == PJ_SUCCESS) + &pi->input_latency_ms) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; + pi->flags |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; } if (ca_stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY, - &pi->output_latency_ms) == PJ_SUCCESS) + &pi->output_latency_ms) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; + pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; } if (ca_stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - &pi->output_vol) == PJ_SUCCESS) + &pi->output_vol) == PJ_SUCCESS) { pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; } if (ca_stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE, - &pi->input_route) == PJ_SUCCESS) + &pi->input_route) == PJ_SUCCESS) { pi->flags |= PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE; } if (ca_stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, - &pi->output_route) == PJ_SUCCESS) + &pi->output_route) == PJ_SUCCESS) { pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE; } if (ca_stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_EC, - &pi->ec_enabled) == PJ_SUCCESS) + &pi->ec_enabled) == PJ_SUCCESS) { pi->flags |= PJMEDIA_AUD_DEV_CAP_EC; } @@ -1846,8 +1845,8 @@ static pj_status_t ca_stream_get_param(pjmedia_aud_stream *s, /* API: get capability */ static pj_status_t ca_stream_get_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - void *pval) + pjmedia_aud_dev_cap cap, + void *pval) { struct coreaudio_stream *strm = (struct coreaudio_stream*)s; @@ -1856,298 +1855,298 @@ static pj_status_t ca_stream_get_cap(pjmedia_aud_stream *s, PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); if (cap==PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY && - (strm->param.dir & PJMEDIA_DIR_CAPTURE)) + (strm->param.dir & PJMEDIA_DIR_CAPTURE)) { #if COREAUDIO_MAC - UInt32 latency, size = sizeof(UInt32); - - /* Recording latency */ - if (AudioUnitGetProperty (strm->io_units[0], - kAudioDevicePropertyLatency, - kAudioUnitScope_Input, - 1, - &latency, - &size) == noErr) - { - UInt32 latency2; - if (AudioUnitGetProperty (strm->io_units[0], - kAudioDevicePropertyBufferFrameSize, - kAudioUnitScope_Input, - 1, - &latency2, - &size) == noErr) - { - strm->param.input_latency_ms = (latency + latency2) * 1000 / - strm->param.clock_rate; - strm->param.input_latency_ms++; - } - } + UInt32 latency, size = sizeof(UInt32); + + /* Recording latency */ + if (AudioUnitGetProperty (strm->io_units[0], + kAudioDevicePropertyLatency, + kAudioUnitScope_Input, + 1, + &latency, + &size) == noErr) + { + UInt32 latency2; + if (AudioUnitGetProperty (strm->io_units[0], + kAudioDevicePropertyBufferFrameSize, + kAudioUnitScope_Input, + 1, + &latency2, + &size) == noErr) + { + strm->param.input_latency_ms = (latency + latency2) * 1000 / + strm->param.clock_rate; + strm->param.input_latency_ms++; + } + } #else if ([strm->sess respondsToSelector:@selector(inputLatency)]) { - strm->param.input_latency_ms = + strm->param.input_latency_ms = (unsigned)(([strm->sess inputLatency] + [strm->sess IOBufferDuration]) * 1000); - strm->param.input_latency_ms++; - } else + strm->param.input_latency_ms++; + } else return PJMEDIA_EAUD_INVCAP; #endif - *(unsigned*)pval = strm->param.input_latency_ms; - return PJ_SUCCESS; + *(unsigned*)pval = strm->param.input_latency_ms; + return PJ_SUCCESS; } else if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY && - (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) + (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) { #if COREAUDIO_MAC - UInt32 latency, size = sizeof(UInt32); - AudioUnit *io_unit = strm->io_units[1] ? &strm->io_units[1] : - &strm->io_units[0]; - - /* Playback latency */ - if (AudioUnitGetProperty (*io_unit, - kAudioDevicePropertyLatency, - kAudioUnitScope_Output, - 0, - &latency, - &size) == noErr) - { - UInt32 latency2; - if (AudioUnitGetProperty (*io_unit, - kAudioDevicePropertyBufferFrameSize, - kAudioUnitScope_Output, - 0, - &latency2, - &size) == noErr) - { - strm->param.output_latency_ms = (latency + latency2) * 1000 / - strm->param.clock_rate; - strm->param.output_latency_ms++; - } - } + UInt32 latency, size = sizeof(UInt32); + AudioUnit *io_unit = strm->io_units[1] ? &strm->io_units[1] : + &strm->io_units[0]; + + /* Playback latency */ + if (AudioUnitGetProperty (*io_unit, + kAudioDevicePropertyLatency, + kAudioUnitScope_Output, + 0, + &latency, + &size) == noErr) + { + UInt32 latency2; + if (AudioUnitGetProperty (*io_unit, + kAudioDevicePropertyBufferFrameSize, + kAudioUnitScope_Output, + 0, + &latency2, + &size) == noErr) + { + strm->param.output_latency_ms = (latency + latency2) * 1000 / + strm->param.clock_rate; + strm->param.output_latency_ms++; + } + } #else if ([strm->sess respondsToSelector:@selector(outputLatency)]) { - strm->param.output_latency_ms = + strm->param.output_latency_ms = (unsigned)(([strm->sess outputLatency] + [strm->sess IOBufferDuration]) * 1000); - strm->param.output_latency_ms++; - } else + strm->param.output_latency_ms++; + } else return PJMEDIA_EAUD_INVCAP; #endif - *(unsigned*)pval = (++strm->param.output_latency_ms * 2); - return PJ_SUCCESS; + *(unsigned*)pval = (++strm->param.output_latency_ms * 2); + return PJ_SUCCESS; } else if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING && - (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) + (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) { #if COREAUDIO_MAC - OSStatus ostatus; - Float32 volume; - UInt32 size = sizeof(Float32); - - /* Output volume setting */ - ostatus = AudioUnitGetProperty (strm->io_units[1] ? strm->io_units[1] : - strm->io_units[0], - kAudioDevicePropertyVolumeScalar, - kAudioUnitScope_Output, - 0, - &volume, - &size); - if (ostatus != noErr) - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - - *(unsigned*)pval = (unsigned)(volume * 100); - return PJ_SUCCESS; + OSStatus ostatus; + Float32 volume; + UInt32 size = sizeof(Float32); + + /* Output volume setting */ + ostatus = AudioUnitGetProperty (strm->io_units[1] ? strm->io_units[1] : + strm->io_units[0], + kAudioDevicePropertyVolumeScalar, + kAudioUnitScope_Output, + 0, + &volume, + &size); + if (ostatus != noErr) + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + + *(unsigned*)pval = (unsigned)(volume * 100); + return PJ_SUCCESS; #else if ([strm->sess respondsToSelector:@selector(outputVolume)]) { *(unsigned*)pval = (unsigned)([strm->sess outputVolume] * 100); return PJ_SUCCESS; - } else + } else return PJMEDIA_EAUD_INVCAP; #endif #if !COREAUDIO_MAC #if USE_AUDIO_SESSION_API != 0 } else if (cap==PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE && - (strm->param.dir & PJMEDIA_DIR_CAPTURE)) + (strm->param.dir & PJMEDIA_DIR_CAPTURE)) { - UInt32 btooth, size = sizeof(UInt32); - OSStatus ostatus; - - ostatus = AudioSessionGetProperty ( - kAudioSessionProperty_OverrideCategoryEnableBluetoothInput, - &size, &btooth); - if (ostatus != kAudioSessionNoError) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } - - *(pjmedia_aud_dev_route*)pval = btooth? - PJMEDIA_AUD_DEV_ROUTE_BLUETOOTH: - PJMEDIA_AUD_DEV_ROUTE_DEFAULT; - return PJ_SUCCESS; + UInt32 btooth, size = sizeof(UInt32); + OSStatus ostatus; + + ostatus = AudioSessionGetProperty ( + kAudioSessionProperty_OverrideCategoryEnableBluetoothInput, + &size, &btooth); + if (ostatus != kAudioSessionNoError) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } + + *(pjmedia_aud_dev_route*)pval = btooth? + PJMEDIA_AUD_DEV_ROUTE_BLUETOOTH: + PJMEDIA_AUD_DEV_ROUTE_DEFAULT; + return PJ_SUCCESS; } else if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE && - (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) + (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) { - CFStringRef route; - UInt32 size = sizeof(CFStringRef); - OSStatus ostatus; - - ostatus = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, - &size, &route); - if (ostatus != kAudioSessionNoError) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } - - if (!route) { - *(pjmedia_aud_dev_route*)pval = PJMEDIA_AUD_DEV_ROUTE_DEFAULT; - } else if (CFStringHasPrefix(route, CFSTR("Headset"))) { - *(pjmedia_aud_dev_route*)pval = PJMEDIA_AUD_DEV_ROUTE_EARPIECE; - } else { - *(pjmedia_aud_dev_route*)pval = PJMEDIA_AUD_DEV_ROUTE_DEFAULT; - } - - CFRelease(route); - - return PJ_SUCCESS; + CFStringRef route; + UInt32 size = sizeof(CFStringRef); + OSStatus ostatus; + + ostatus = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, + &size, &route); + if (ostatus != kAudioSessionNoError) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } + + if (!route) { + *(pjmedia_aud_dev_route*)pval = PJMEDIA_AUD_DEV_ROUTE_DEFAULT; + } else if (CFStringHasPrefix(route, CFSTR("Headset"))) { + *(pjmedia_aud_dev_route*)pval = PJMEDIA_AUD_DEV_ROUTE_EARPIECE; + } else { + *(pjmedia_aud_dev_route*)pval = PJMEDIA_AUD_DEV_ROUTE_DEFAULT; + } + + CFRelease(route); + + return PJ_SUCCESS; #endif } else if (cap==PJMEDIA_AUD_DEV_CAP_EC) { - AudioComponentDescription desc; - OSStatus ostatus; + AudioComponentDescription desc; + OSStatus ostatus; - ostatus = AudioComponentGetDescription(strm->cf->io_comp, &desc); - if (ostatus != noErr) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } + ostatus = AudioComponentGetDescription(strm->cf->io_comp, &desc); + if (ostatus != noErr) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } - *(pj_bool_t*)pval = (desc.componentSubType == - kAudioUnitSubType_VoiceProcessingIO); - return PJ_SUCCESS; + *(pj_bool_t*)pval = (desc.componentSubType == + kAudioUnitSubType_VoiceProcessingIO); + return PJ_SUCCESS; #endif } else { - return PJMEDIA_EAUD_INVCAP; + return PJMEDIA_EAUD_INVCAP; } } /* API: set capability */ static pj_status_t ca_stream_set_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - const void *pval) + pjmedia_aud_dev_cap cap, + const void *pval) { struct coreaudio_stream *strm = (struct coreaudio_stream*)s; PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); if (cap==PJMEDIA_AUD_DEV_CAP_EC) { - AudioComponentDescription desc; - AudioComponent io_comp; + AudioComponentDescription desc; + AudioComponent io_comp; - desc.componentType = kAudioUnitType_Output; - desc.componentSubType = (*(pj_bool_t*)pval)? - kAudioUnitSubType_VoiceProcessingIO : + desc.componentType = kAudioUnitType_Output; + desc.componentSubType = (*(pj_bool_t*)pval)? + kAudioUnitSubType_VoiceProcessingIO : #if COREAUDIO_MAC - kAudioUnitSubType_HALOutput; + kAudioUnitSubType_HALOutput; #else - kAudioUnitSubType_RemoteIO; + kAudioUnitSubType_RemoteIO; #endif - desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; + desc.componentManufacturer = kAudioUnitManufacturer_Apple; + desc.componentFlags = 0; + desc.componentFlagsMask = 0; - io_comp = AudioComponentFindNext(NULL, &desc); - if (io_comp == NULL) - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(-1); - strm->cf->io_comp = io_comp; - strm->param.ec_enabled = *(pj_bool_t*)pval; + io_comp = AudioComponentFindNext(NULL, &desc); + if (io_comp == NULL) + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(-1); + strm->cf->io_comp = io_comp; + strm->param.ec_enabled = *(pj_bool_t*)pval; PJ_LOG(4, (THIS_FILE, "Using %s audio unit", (desc.componentSubType == kAudioUnitSubType_VoiceProcessingIO? "VoiceProcessingIO": "default"))); - return PJ_SUCCESS; + return PJ_SUCCESS; } #if COREAUDIO_MAC else if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING && - (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) + (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) { - OSStatus ostatus; - Float32 volume = *(unsigned*)pval; - - /* Output volume setting */ - volume /= 100.0; - ostatus = AudioUnitSetProperty (strm->io_units[1] ? strm->io_units[1] : - strm->io_units[0], - kAudioDevicePropertyVolumeScalar, - kAudioUnitScope_Output, - 0, - &volume, - sizeof(Float32)); - if (ostatus != noErr) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } - strm->param.output_vol = *(unsigned*)pval; - return PJ_SUCCESS; + OSStatus ostatus; + Float32 volume = *(unsigned*)pval; + + /* Output volume setting */ + volume /= 100.0; + ostatus = AudioUnitSetProperty (strm->io_units[1] ? strm->io_units[1] : + strm->io_units[0], + kAudioDevicePropertyVolumeScalar, + kAudioUnitScope_Output, + 0, + &volume, + sizeof(Float32)); + if (ostatus != noErr) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } + strm->param.output_vol = *(unsigned*)pval; + return PJ_SUCCESS; } #else else if ((cap==PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY && - (strm->param.dir & PJMEDIA_DIR_CAPTURE)) || - (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY && - (strm->param.dir & PJMEDIA_DIR_PLAYBACK))) + (strm->param.dir & PJMEDIA_DIR_CAPTURE)) || + (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY && + (strm->param.dir & PJMEDIA_DIR_PLAYBACK))) { - NSTimeInterval duration = *(unsigned *)pval; - unsigned latency; - - /* For low-latency audio streaming, you can set this value to - * as low as 5 ms (the default is 23ms). However, lowering the - * latency may cause a decrease in audio quality. - */ - duration /= 1000; - if ([strm->sess setPreferredIOBufferDuration:duration error:nil] + NSTimeInterval duration = *(unsigned *)pval; + unsigned latency; + + /* For low-latency audio streaming, you can set this value to + * as low as 5 ms (the default is 23ms). However, lowering the + * latency may cause a decrease in audio quality. + */ + duration /= 1000; + if ([strm->sess setPreferredIOBufferDuration:duration error:nil] != YES) { - PJ_LOG(4, (THIS_FILE, - "Error: cannot set the preferred buffer duration")); - return PJMEDIA_EAUD_INVOP; - } - - ca_stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY, &latency); - ca_stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY, &latency); - - return PJ_SUCCESS; + PJ_LOG(4, (THIS_FILE, + "Error: cannot set the preferred buffer duration")); + return PJMEDIA_EAUD_INVOP; + } + + ca_stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY, &latency); + ca_stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY, &latency); + + return PJ_SUCCESS; } #if USE_AUDIO_SESSION_API != 0 else if (cap==PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE && - (strm->param.dir & PJMEDIA_DIR_CAPTURE)) + (strm->param.dir & PJMEDIA_DIR_CAPTURE)) { - UInt32 btooth = *(pjmedia_aud_dev_route*)pval == - PJMEDIA_AUD_DEV_ROUTE_BLUETOOTH ? 1 : 0; - OSStatus ostatus; - - ostatus = AudioSessionSetProperty ( - kAudioSessionProperty_OverrideCategoryEnableBluetoothInput, - sizeof(btooth), &btooth); - if (ostatus != kAudioSessionNoError) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } - strm->param.input_route = *(pjmedia_aud_dev_route*)pval; - return PJ_SUCCESS; + UInt32 btooth = *(pjmedia_aud_dev_route*)pval == + PJMEDIA_AUD_DEV_ROUTE_BLUETOOTH ? 1 : 0; + OSStatus ostatus; + + ostatus = AudioSessionSetProperty ( + kAudioSessionProperty_OverrideCategoryEnableBluetoothInput, + sizeof(btooth), &btooth); + if (ostatus != kAudioSessionNoError) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } + strm->param.input_route = *(pjmedia_aud_dev_route*)pval; + return PJ_SUCCESS; } else if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE && - (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) + (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) { - OSStatus ostatus; - UInt32 route = *(pjmedia_aud_dev_route*)pval == - PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER ? - kAudioSessionOverrideAudioRoute_Speaker : - kAudioSessionOverrideAudioRoute_None; - - ostatus = AudioSessionSetProperty ( - kAudioSessionProperty_OverrideAudioRoute, - sizeof(route), &route); - if (ostatus != kAudioSessionNoError) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } - strm->param.output_route = *(pjmedia_aud_dev_route*)pval; - return PJ_SUCCESS; + OSStatus ostatus; + UInt32 route = *(pjmedia_aud_dev_route*)pval == + PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER ? + kAudioSessionOverrideAudioRoute_Speaker : + kAudioSessionOverrideAudioRoute_None; + + ostatus = AudioSessionSetProperty ( + kAudioSessionProperty_OverrideAudioRoute, + sizeof(route), &route); + if (ostatus != kAudioSessionNoError) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } + strm->param.output_route = *(pjmedia_aud_dev_route*)pval; + return PJ_SUCCESS; } #endif #endif @@ -2163,7 +2162,7 @@ static pj_status_t ca_stream_start(pjmedia_aud_stream *strm) UInt32 i; if (stream->running) - return PJ_SUCCESS; + return PJ_SUCCESS; stream->quit_flag = 0; stream->interrupted = PJ_FALSE; @@ -2172,25 +2171,25 @@ static pj_status_t ca_stream_start(pjmedia_aud_stream *strm) stream->resample_buf_count = 0; if (stream->resample) { - ostatus = AudioConverterReset(stream->resample); - if (ostatus != noErr) - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + ostatus = AudioConverterReset(stream->resample); + if (ostatus != noErr) + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); } #if !COREAUDIO_MAC if ([stream->sess setActive:true error:nil] != YES) { - PJ_LOG(4, (THIS_FILE, "Warning: cannot activate audio session")); + PJ_LOG(4, (THIS_FILE, "Warning: cannot activate audio session")); } #endif for (i = 0; i < 2; i++) { - if (stream->io_units[i] == NULL) break; - ostatus = AudioOutputUnitStart(stream->io_units[i]); - if (ostatus != noErr) { - if (i == 1) - AudioOutputUnitStop(stream->io_units[0]); - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } + if (stream->io_units[i] == NULL) break; + ostatus = AudioOutputUnitStart(stream->io_units[i]); + if (ostatus != noErr) { + if (i == 1) + AudioOutputUnitStop(stream->io_units[0]); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } } stream->running = PJ_TRUE; @@ -2210,16 +2209,16 @@ static pj_status_t ca_stream_stop(pjmedia_aud_stream *strm) struct stream_list *it, *itBegin; if (!stream->running) - return PJ_SUCCESS; + return PJ_SUCCESS; for (i = 0; i < 2; i++) { - if (stream->io_units[i] == NULL) break; - ostatus = AudioOutputUnitStop(stream->io_units[i]); - if (ostatus != noErr) { - if (i == 0 && stream->io_units[1]) - AudioOutputUnitStop(stream->io_units[1]); - return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); - } + if (stream->io_units[i] == NULL) break; + ostatus = AudioOutputUnitStop(stream->io_units[i]); + if (ostatus != noErr) { + if (i == 0 && stream->io_units[1]) + AudioOutputUnitStop(stream->io_units[1]); + return PJMEDIA_AUDIODEV_ERRNO_FROM_COREAUDIO(ostatus); + } } /* Check whether we need to deactivate the audio session. */ @@ -2230,10 +2229,10 @@ static pj_status_t ca_stream_stop(pjmedia_aud_stream *strm) should_deactivate = PJ_TRUE; itBegin = &stream->cf->streams; for (it = itBegin->next; it != itBegin; it = it->next) { - if (it->stream->running) { - should_deactivate = PJ_FALSE; - break; - } + if (it->stream->running) { + should_deactivate = PJ_FALSE; + break; + } } pj_mutex_unlock(stream->cf->mutex); @@ -2242,13 +2241,13 @@ static pj_status_t ca_stream_stop(pjmedia_aud_stream *strm) if ([stream->sess respondsToSelector:@selector(setActive:withOptions:error:)]) { - [stream->sess setActive:NO - withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation - error:nil]; - } else { - if ([stream->sess setActive:NO error:nil] != YES) { - PJ_LOG(4, (THIS_FILE, "Warning: cannot deactivate " - "audio session")); + [stream->sess setActive:NO + withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation + error:nil]; + } else { + if ([stream->sess setActive:NO error:nil] != YES) { + PJ_LOG(4, (THIS_FILE, "Warning: cannot deactivate " + "audio session")); } } #endif @@ -2277,19 +2276,19 @@ static pj_status_t ca_stream_destroy(pjmedia_aud_stream *strm) ca_stream_stop(strm); for (i = 0; i < 2; i++) { - if (stream->io_units[i]) { - AudioUnitUninitialize(stream->io_units[i]); - AudioComponentInstanceDispose(stream->io_units[i]); - stream->io_units[i] = NULL; - } + if (stream->io_units[i]) { + AudioUnitUninitialize(stream->io_units[i]); + AudioComponentInstanceDispose(stream->io_units[i]); + stream->io_units[i] = NULL; + } } if (stream->resample) - AudioConverterDispose(stream->resample); + AudioConverterDispose(stream->resample); pj_mutex_lock(stream->cf->mutex); if (!pj_list_empty(&stream->list_entry)) - pj_list_erase(&stream->list_entry); + pj_list_erase(&stream->list_entry); pj_mutex_unlock(stream->cf->mutex); pj_pool_release(stream->pool); @@ -2297,4 +2296,4 @@ static pj_status_t ca_stream_destroy(pjmedia_aud_stream *strm) return PJ_SUCCESS; } -#endif /* PJMEDIA_AUDIO_DEV_HAS_COREAUDIO */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_COREAUDIO */ diff --git a/pjmedia/src/pjmedia-audiodev/errno.c b/pjmedia/src/pjmedia-audiodev/errno.c index 6499c21644..b177e31e59 100644 --- a/pjmedia/src/pjmedia-audiodev/errno.c +++ b/pjmedia/src/pjmedia-audiodev/errno.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -24,12 +23,12 @@ #endif #if PJMEDIA_AUDIO_DEV_HAS_WMME # ifdef _MSC_VER -# pragma warning(push, 3) +# pragma warning(push, 3) # endif # include # include # ifdef _MSC_VER -# pragma warning(pop) +# pragma warning(pop) # endif #endif @@ -46,22 +45,22 @@ static const struct const char *msg; } err_str[] = { - PJ_BUILD_ERR( PJMEDIA_EAUD_ERR, "Unspecified audio device error" ), - PJ_BUILD_ERR( PJMEDIA_EAUD_SYSERR, "Unknown error from audio driver" ), - PJ_BUILD_ERR( PJMEDIA_EAUD_INIT, "Audio subsystem not initialized" ), - PJ_BUILD_ERR( PJMEDIA_EAUD_INVDEV, "Invalid audio device" ), - PJ_BUILD_ERR( PJMEDIA_EAUD_NODEV, "Found no audio devices" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_ERR, "Unspecified audio device error" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_SYSERR, "Unknown error from audio driver" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_INIT, "Audio subsystem not initialized" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_INVDEV, "Invalid audio device" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_NODEV, "Found no audio devices" ), PJ_BUILD_ERR( PJMEDIA_EAUD_NODEFDEV, "Unable to find default audio device" ), PJ_BUILD_ERR( PJMEDIA_EAUD_NOTREADY, "Audio device not ready" ), - PJ_BUILD_ERR( PJMEDIA_EAUD_INVCAP, "Invalid or unsupported audio capability" ), - PJ_BUILD_ERR( PJMEDIA_EAUD_INVOP, "Invalid or unsupported audio device operation" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_INVCAP, "Invalid or unsupported audio capability" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_INVOP, "Invalid or unsupported audio device operation" ), PJ_BUILD_ERR( PJMEDIA_EAUD_BADFORMAT, "Bad or invalid audio device format" ), PJ_BUILD_ERR( PJMEDIA_EAUD_SAMPFORMAT, "Invalid audio device sample format"), PJ_BUILD_ERR( PJMEDIA_EAUD_BADLATENCY, "Bad audio latency setting") }; -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ @@ -69,7 +68,7 @@ static const struct * pjmedia_audiodev_strerror() */ PJ_DEF(pj_str_t) pjmedia_audiodev_strerror(pj_status_t statcode, - char *buf, pj_size_t bufsize ) + char *buf, pj_size_t bufsize ) { pj_str_t errstr; @@ -79,143 +78,143 @@ PJ_DEF(pj_str_t) pjmedia_audiodev_strerror(pj_status_t statcode, /* See if the error comes from Core Audio. */ #if PJMEDIA_AUDIO_DEV_HAS_COREAUDIO if (statcode >= PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_START && - statcode <= PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_END) + statcode <= PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_END) { - int ca_err = PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_START - statcode; + int ca_err = PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_START - statcode; - PJ_UNUSED_ARG(ca_err); - // TODO: create more helpful error messages - errstr.ptr = buf; - pj_strcpy2(&errstr, "Core audio error"); - return errstr; + PJ_UNUSED_ARG(ca_err); + // TODO: create more helpful error messages + errstr.ptr = buf; + pj_strcpy2(&errstr, "Core audio error"); + return errstr; } else #endif /* See if the error comes from PortAudio. */ #if PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO if (statcode >= PJMEDIA_AUDIODEV_PORTAUDIO_ERRNO_START && - statcode <= PJMEDIA_AUDIODEV_PORTAUDIO_ERRNO_END) + statcode <= PJMEDIA_AUDIODEV_PORTAUDIO_ERRNO_END) { - //int pa_err = statcode - PJMEDIA_ERRNO_FROM_PORTAUDIO(0); - int pa_err = PJMEDIA_AUDIODEV_PORTAUDIO_ERRNO_START - statcode; - pj_str_t msg; - - msg.ptr = (char*)Pa_GetErrorText(pa_err); - msg.slen = pj_ansi_strlen(msg.ptr); + //int pa_err = statcode - PJMEDIA_ERRNO_FROM_PORTAUDIO(0); + int pa_err = PJMEDIA_AUDIODEV_PORTAUDIO_ERRNO_START - statcode; + pj_str_t msg; + + msg.ptr = (char*)Pa_GetErrorText(pa_err); + msg.slen = pj_ansi_strlen(msg.ptr); - errstr.ptr = buf; - pj_strncpy_with_null(&errstr, &msg, bufsize); - return errstr; + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, &msg, bufsize); + return errstr; } else -#endif /* PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO */ /* See if the error comes from WMME */ #if PJMEDIA_AUDIO_DEV_HAS_WMME if ((statcode >= PJMEDIA_AUDIODEV_WMME_IN_ERROR_START && - statcode < PJMEDIA_AUDIODEV_WMME_IN_ERROR_END) || - (statcode >= PJMEDIA_AUDIODEV_WMME_OUT_ERROR_START && - statcode < PJMEDIA_AUDIODEV_WMME_OUT_ERROR_END)) + statcode < PJMEDIA_AUDIODEV_WMME_IN_ERROR_END) || + (statcode >= PJMEDIA_AUDIODEV_WMME_OUT_ERROR_START && + statcode < PJMEDIA_AUDIODEV_WMME_OUT_ERROR_END)) { - MMRESULT native_err, mr; - MMRESULT (WINAPI *waveGetErrText)(UINT mmrError, LPTSTR pszText, UINT cchText); - PJ_DECL_UNICODE_TEMP_BUF(wbuf, 80) - - if (statcode >= PJMEDIA_AUDIODEV_WMME_IN_ERROR_START && - statcode <= PJMEDIA_AUDIODEV_WMME_IN_ERROR_END) - { - native_err = statcode - PJMEDIA_AUDIODEV_WMME_IN_ERROR_START; - waveGetErrText = &waveInGetErrorText; - } else { - native_err = statcode - PJMEDIA_AUDIODEV_WMME_OUT_ERROR_START; - waveGetErrText = &waveOutGetErrorText; - } + MMRESULT native_err, mr; + MMRESULT (WINAPI *waveGetErrText)(UINT mmrError, LPTSTR pszText, UINT cchText); + PJ_DECL_UNICODE_TEMP_BUF(wbuf, 80) + + if (statcode >= PJMEDIA_AUDIODEV_WMME_IN_ERROR_START && + statcode <= PJMEDIA_AUDIODEV_WMME_IN_ERROR_END) + { + native_err = statcode - PJMEDIA_AUDIODEV_WMME_IN_ERROR_START; + waveGetErrText = &waveInGetErrorText; + } else { + native_err = statcode - PJMEDIA_AUDIODEV_WMME_OUT_ERROR_START; + waveGetErrText = &waveOutGetErrorText; + } #if PJ_NATIVE_STRING_IS_UNICODE - mr = (*waveGetErrText)(native_err, wbuf, PJ_ARRAY_SIZE(wbuf)); - if (mr == MMSYSERR_NOERROR) { - int len = wcslen(wbuf); - pj_unicode_to_ansi(wbuf, len, buf, bufsize); - } + mr = (*waveGetErrText)(native_err, wbuf, PJ_ARRAY_SIZE(wbuf)); + if (mr == MMSYSERR_NOERROR) { + int len = wcslen(wbuf); + pj_unicode_to_ansi(wbuf, len, buf, bufsize); + } #else - mr = (*waveGetErrText)(native_err, buf, (UINT)bufsize); + mr = (*waveGetErrText)(native_err, buf, (UINT)bufsize); #endif - if (mr==MMSYSERR_NOERROR) { - errstr.ptr = buf; - errstr.slen = pj_ansi_strlen(buf); - return errstr; - } else { - pj_ansi_snprintf(buf, bufsize, "MMSYSTEM native error %d", - native_err); - return pj_str(buf); - } + if (mr==MMSYSERR_NOERROR) { + errstr.ptr = buf; + errstr.slen = pj_ansi_strlen(buf); + return errstr; + } else { + pj_ansi_snprintf(buf, bufsize, "MMSYSTEM native error %d", + native_err); + return pj_str(buf); + } } else #endif /* See if the error comes from BDIMAD */ #if PJMEDIA_AUDIO_DEV_HAS_BDIMAD - - if (statcode >= PJMEDIA_AUDIODEV_BDIMAD_ERROR_START && - statcode < PJMEDIA_AUDIODEV_BDIMAD_ERROR_END) - { - pj_status_t native_err; - native_err = statcode - PJMEDIA_AUDIODEV_BDIMAD_ERROR_START; - - pj_ansi_snprintf(buf, bufsize, "BDIMAD native error %d", native_err); - return pj_str(buf); - } else + + if (statcode >= PJMEDIA_AUDIODEV_BDIMAD_ERROR_START && + statcode < PJMEDIA_AUDIODEV_BDIMAD_ERROR_END) + { + pj_status_t native_err; + native_err = statcode - PJMEDIA_AUDIODEV_BDIMAD_ERROR_START; + + pj_ansi_snprintf(buf, bufsize, "BDIMAD native error %d", native_err); + return pj_str(buf); + } else #endif /* Audiodev error */ if (statcode >= PJMEDIA_AUDIODEV_ERRNO_START && - statcode < PJMEDIA_AUDIODEV_ERRNO_END) + statcode < PJMEDIA_AUDIODEV_ERRNO_END) { - /* Find the error in the table. - * Use binary search! - */ - int first = 0; - int n = PJ_ARRAY_SIZE(err_str); - - while (n > 0) { - int half = n/2; - int mid = first + half; - - if (err_str[mid].code < statcode) { - first = mid+1; - n -= (half+1); - } else if (err_str[mid].code > statcode) { - n = half; - } else { - first = mid; - break; - } - } - - - if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { - pj_str_t msg; - - msg.ptr = (char*)err_str[first].msg; - msg.slen = pj_ansi_strlen(err_str[first].msg); - - errstr.ptr = buf; - pj_strncpy_with_null(&errstr, &msg, bufsize); - return errstr; - - } + /* Find the error in the table. + * Use binary search! + */ + int first = 0; + int n = PJ_ARRAY_SIZE(err_str); + + while (n > 0) { + int half = n/2; + int mid = first + half; + + if (err_str[mid].code < statcode) { + first = mid+1; + n -= (half+1); + } else if (err_str[mid].code > statcode) { + n = half; + } else { + first = mid; + break; + } + } + + + if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { + pj_str_t msg; + + msg.ptr = (char*)err_str[first].msg; + msg.slen = pj_ansi_strlen(err_str[first].msg); + + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, &msg, bufsize); + return errstr; + + } } -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ /* Error not found. */ errstr.ptr = buf; errstr.slen = pj_ansi_snprintf(buf, bufsize, - "Unknown pjmedia-audiodev error %d", - statcode); + "Unknown pjmedia-audiodev error %d", + statcode); if (errstr.slen < 1 || errstr.slen >= (pj_ssize_t)bufsize) - errstr.slen = bufsize - 1; + errstr.slen = bufsize - 1; return errstr; } diff --git a/pjmedia/src/pjmedia-audiodev/legacy_dev.c b/pjmedia/src/pjmedia-audiodev/legacy_dev.c index 19e383b412..2ac9c6a399 100644 --- a/pjmedia/src/pjmedia-audiodev/legacy_dev.c +++ b/pjmedia/src/pjmedia-audiodev/legacy_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -22,29 +21,29 @@ #if PJMEDIA_AUDIO_DEV_HAS_LEGACY_DEVICE -#define THIS_FILE "legacy_dev.c" +#define THIS_FILE "legacy_dev.c" /* Legacy devices factory */ struct legacy_factory { - pjmedia_aud_dev_factory base; - pj_pool_t *pool; - pj_pool_factory *pf; + pjmedia_aud_dev_factory base; + pj_pool_t *pool; + pj_pool_factory *pf; }; struct legacy_stream { - pjmedia_aud_stream base; + pjmedia_aud_stream base; - pj_pool_t *pool; + pj_pool_t *pool; pjmedia_aud_param param; - pjmedia_snd_stream *snd_strm; - pjmedia_aud_play_cb user_play_cb; + pjmedia_snd_stream *snd_strm; + pjmedia_aud_play_cb user_play_cb; pjmedia_aud_rec_cb user_rec_cb; - void *user_user_data; - unsigned input_latency; - unsigned output_latency; + void *user_user_data; + unsigned input_latency; + unsigned output_latency; }; @@ -54,26 +53,26 @@ static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f); static pj_status_t factory_refresh(pjmedia_aud_dev_factory *f); static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f); static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); + unsigned index, + pjmedia_aud_dev_info *info); static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); + unsigned index, + pjmedia_aud_param *param); static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); static pj_status_t stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); + pjmedia_aud_param *param); static pj_status_t stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); + pjmedia_aud_dev_cap cap, + void *value); static pj_status_t stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); + pjmedia_aud_dev_cap cap, + const void *value); static pj_status_t stream_start(pjmedia_aud_stream *strm); static pj_status_t stream_stop(pjmedia_aud_stream *strm); static pj_status_t stream_destroy(pjmedia_aud_stream *strm); @@ -141,7 +140,7 @@ static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f) status = pjmedia_snd_deinit(); if (status == PJ_SUCCESS) { - pj_pool_safe_release(&wf->pool); + pj_pool_safe_release(&wf->pool); } return status; @@ -163,16 +162,16 @@ static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f) /* API: get device info */ static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info) + unsigned index, + pjmedia_aud_dev_info *info) { const pjmedia_snd_dev_info *si = - pjmedia_snd_get_dev_info(index);; + pjmedia_snd_get_dev_info(index);; PJ_UNUSED_ARG(f); if (si == NULL) - return PJMEDIA_EAUD_INVDEV; + return PJMEDIA_EAUD_INVDEV; pj_bzero(info, sizeof(*info)); pj_ansi_strncpy(info->name, si->name, sizeof(info->name)); @@ -182,38 +181,38 @@ static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, info->default_samples_per_sec = si->default_samples_per_sec; pj_ansi_strcpy(info->driver, "legacy"); info->caps = PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; + PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; return PJ_SUCCESS; } /* API: create default device parameter */ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param) + unsigned index, + pjmedia_aud_param *param) { pjmedia_aud_dev_info di; pj_status_t status; status = factory_get_dev_info(f, index, &di); if (status != PJ_SUCCESS) - return status; + return status; pj_bzero(param, sizeof(*param)); if (di.input_count && di.output_count) { - param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; - param->rec_id = index; - param->play_id = index; + param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; + param->rec_id = index; + param->play_id = index; } else if (di.input_count) { - param->dir = PJMEDIA_DIR_CAPTURE; - param->rec_id = index; - param->play_id = PJMEDIA_AUD_INVALID_DEV; + param->dir = PJMEDIA_DIR_CAPTURE; + param->rec_id = index; + param->play_id = PJMEDIA_AUD_INVALID_DEV; } else if (di.output_count) { - param->dir = PJMEDIA_DIR_PLAYBACK; - param->play_id = index; - param->rec_id = PJMEDIA_AUD_INVALID_DEV; + param->dir = PJMEDIA_DIR_PLAYBACK; + param->play_id = index; + param->rec_id = PJMEDIA_AUD_INVALID_DEV; } else { - return PJMEDIA_EAUD_INVDEV; + return PJMEDIA_EAUD_INVDEV; } param->clock_rate = di.default_samples_per_sec; @@ -229,9 +228,9 @@ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, /* Callback from legacy sound device */ static pj_status_t snd_play_cb(/* in */ void *user_data, - /* in */ pj_uint32_t timestamp, - /* out */ void *output, - /* out */ unsigned size) + /* in */ pj_uint32_t timestamp, + /* out */ void *output, + /* out */ unsigned size) { struct legacy_stream *strm = (struct legacy_stream*)user_data; pjmedia_frame frame; @@ -244,10 +243,10 @@ static pj_status_t snd_play_cb(/* in */ void *user_data, status = strm->user_play_cb(strm->user_user_data, &frame); if (status != PJ_SUCCESS) - return status; + return status; if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) { - pj_bzero(output, size); + pj_bzero(output, size); } return PJ_SUCCESS; @@ -255,9 +254,9 @@ static pj_status_t snd_play_cb(/* in */ void *user_data, /* Callback from legacy sound device */ static pj_status_t snd_rec_cb( /* in */ void *user_data, - /* in */ pj_uint32_t timestamp, - /* in */ void *input, - /* in*/ unsigned size) + /* in */ pj_uint32_t timestamp, + /* in */ void *input, + /* in*/ unsigned size) { struct legacy_stream *strm = (struct legacy_stream*)user_data; pjmedia_frame frame; @@ -272,11 +271,11 @@ static pj_status_t snd_rec_cb( /* in */ void *user_data, /* API: create stream */ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { struct legacy_factory *wf = (struct legacy_factory*)f; pj_pool_t *pool; @@ -294,63 +293,63 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, /* Set the latency if wanted */ if (param->dir==PJMEDIA_DIR_CAPTURE_PLAYBACK && - param->flags & (PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY)) + param->flags & (PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | + PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY)) { - PJ_ASSERT_RETURN(param->input_latency_ms && - param->output_latency_ms, - PJMEDIA_EAUD_BADLATENCY); - - strm->input_latency = param->input_latency_ms; - strm->output_latency = param->output_latency_ms; - - status = pjmedia_snd_set_latency(param->input_latency_ms, - param->output_latency_ms); - if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; - } + PJ_ASSERT_RETURN(param->input_latency_ms && + param->output_latency_ms, + PJMEDIA_EAUD_BADLATENCY); + + strm->input_latency = param->input_latency_ms; + strm->output_latency = param->output_latency_ms; + + status = pjmedia_snd_set_latency(param->input_latency_ms, + param->output_latency_ms); + if (status != PJ_SUCCESS) { + pj_pool_release(pool); + return status; + } } /* Open the stream */ if (param->dir == PJMEDIA_DIR_CAPTURE) { - status = pjmedia_snd_open_rec(param->rec_id, - param->clock_rate, - param->channel_count, - param->samples_per_frame, - param->bits_per_sample, - &snd_rec_cb, - strm, - &strm->snd_strm); + status = pjmedia_snd_open_rec(param->rec_id, + param->clock_rate, + param->channel_count, + param->samples_per_frame, + param->bits_per_sample, + &snd_rec_cb, + strm, + &strm->snd_strm); } else if (param->dir == PJMEDIA_DIR_PLAYBACK) { - status = pjmedia_snd_open_player(param->play_id, - param->clock_rate, - param->channel_count, - param->samples_per_frame, - param->bits_per_sample, - &snd_play_cb, - strm, - &strm->snd_strm); + status = pjmedia_snd_open_player(param->play_id, + param->clock_rate, + param->channel_count, + param->samples_per_frame, + param->bits_per_sample, + &snd_play_cb, + strm, + &strm->snd_strm); } else if (param->dir == PJMEDIA_DIR_CAPTURE_PLAYBACK) { - status = pjmedia_snd_open(param->rec_id, - param->play_id, - param->clock_rate, - param->channel_count, - param->samples_per_frame, - param->bits_per_sample, - &snd_rec_cb, - &snd_play_cb, - strm, - &strm->snd_strm); + status = pjmedia_snd_open(param->rec_id, + param->play_id, + param->clock_rate, + param->channel_count, + param->samples_per_frame, + param->bits_per_sample, + &snd_rec_cb, + &snd_play_cb, + strm, + &strm->snd_strm); } else { - pj_assert(!"Invalid direction!"); - return PJ_EINVAL; + pj_assert(!"Invalid direction!"); + return PJ_EINVAL; } if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; + pj_pool_release(pool); + return status; } *p_aud_strm = &strm->base; @@ -359,7 +358,7 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, /* API: Get stream info. */ static pj_status_t stream_get_param(pjmedia_aud_stream *s, - pjmedia_aud_param *pi) + pjmedia_aud_param *pi) { struct legacy_stream *strm = (struct legacy_stream*)s; PJ_ASSERT_RETURN(strm && pi, PJ_EINVAL); @@ -367,17 +366,17 @@ static pj_status_t stream_get_param(pjmedia_aud_stream *s, pj_memcpy(pi, &strm->param, sizeof(*pi)); if (strm->input_latency) { - pi->flags |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; - pi->input_latency_ms = strm->input_latency; + pi->flags |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; + pi->input_latency_ms = strm->input_latency; } else { - pi->flags &= ~PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; + pi->flags &= ~PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; } if (strm->output_latency) { - pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; - pi->output_latency_ms = strm->output_latency; + pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; + pi->output_latency_ms = strm->output_latency; } else { - pi->flags &= ~PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; + pi->flags &= ~PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; } return PJ_SUCCESS; @@ -385,43 +384,43 @@ static pj_status_t stream_get_param(pjmedia_aud_stream *s, /* API: get capability */ static pj_status_t stream_get_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - void *pval) + pjmedia_aud_dev_cap cap, + void *pval) { struct legacy_stream *strm = (struct legacy_stream*)s; PJ_ASSERT_RETURN(strm && pval, PJ_EINVAL); if (cap==PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY && - (strm->param.dir & PJMEDIA_DIR_CAPTURE)) + (strm->param.dir & PJMEDIA_DIR_CAPTURE)) { - /* Recording latency */ - if (strm->input_latency) { - *(unsigned*)pval = strm->input_latency; - return PJ_SUCCESS; - } else { - return PJMEDIA_EAUD_INVCAP; - } + /* Recording latency */ + if (strm->input_latency) { + *(unsigned*)pval = strm->input_latency; + return PJ_SUCCESS; + } else { + return PJMEDIA_EAUD_INVCAP; + } } else if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY && - (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) + (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) { - /* Playback latency */ - if (strm->output_latency) { - *(unsigned*)pval = strm->output_latency; - return PJ_SUCCESS; - } else { - return PJMEDIA_EAUD_INVCAP; - } + /* Playback latency */ + if (strm->output_latency) { + *(unsigned*)pval = strm->output_latency; + return PJ_SUCCESS; + } else { + return PJMEDIA_EAUD_INVCAP; + } } else { - return PJMEDIA_EAUD_INVCAP; + return PJMEDIA_EAUD_INVCAP; } } /* API: set capability */ static pj_status_t stream_set_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - const void *pval) + pjmedia_aud_dev_cap cap, + const void *pval) { PJ_UNUSED_ARG(s); PJ_UNUSED_ARG(cap); @@ -453,11 +452,11 @@ static pj_status_t stream_destroy(pjmedia_aud_stream *s) status = pjmedia_snd_stream_close(strm->snd_strm); if (status == PJ_SUCCESS) { - pj_pool_safe_release(&strm->pool); + pj_pool_safe_release(&strm->pool); } return status; } -#endif /* PJMEDIA_AUDIO_DEV_HAS_LEGACY_DEVICE */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_LEGACY_DEVICE */ diff --git a/pjmedia/src/pjmedia-audiodev/null_dev.c b/pjmedia/src/pjmedia-audiodev/null_dev.c index afe5543846..9701f77d7e 100644 --- a/pjmedia/src/pjmedia-audiodev/null_dev.c +++ b/pjmedia/src/pjmedia-audiodev/null_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -23,31 +22,31 @@ #if PJMEDIA_AUDIO_DEV_HAS_NULL_AUDIO -#define THIS_FILE "null_dev.c" +#define THIS_FILE "null_dev.c" /* null_audio device info */ struct null_audio_dev_info { - pjmedia_aud_dev_info info; - unsigned dev_id; + pjmedia_aud_dev_info info; + unsigned dev_id; }; /* null_audio factory */ struct null_audio_factory { - pjmedia_aud_dev_factory base; - pj_pool_t *pool; - pj_pool_factory *pf; + pjmedia_aud_dev_factory base; + pj_pool_t *pool; + pj_pool_factory *pf; - unsigned dev_count; - struct null_audio_dev_info *dev_info; + unsigned dev_count; + struct null_audio_dev_info *dev_info; }; /* Sound stream. */ struct null_audio_stream { - pjmedia_aud_stream base; /**< Base stream */ - pjmedia_aud_param param; /**< Settings */ + pjmedia_aud_stream base; /**< Base stream */ + pjmedia_aud_param param; /**< Settings */ pj_pool_t *pool; /**< Memory pool. */ pjmedia_aud_rec_cb rec_cb; /**< Capture callback. */ @@ -62,26 +61,26 @@ static pj_status_t null_factory_destroy(pjmedia_aud_dev_factory *f); static pj_status_t null_factory_refresh(pjmedia_aud_dev_factory *f); static unsigned null_factory_get_dev_count(pjmedia_aud_dev_factory *f); static pj_status_t null_factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); + unsigned index, + pjmedia_aud_dev_info *info); static pj_status_t null_factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); + unsigned index, + pjmedia_aud_param *param); static pj_status_t null_factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); static pj_status_t null_stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); + pjmedia_aud_param *param); static pj_status_t null_stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); + pjmedia_aud_dev_cap cap, + void *value); static pj_status_t null_stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); + pjmedia_aud_dev_cap cap, + const void *value); static pj_status_t null_stream_start(pjmedia_aud_stream *strm); static pj_status_t null_stream_stop(pjmedia_aud_stream *strm); static pj_status_t null_stream_destroy(pjmedia_aud_stream *strm); @@ -139,8 +138,8 @@ static pj_status_t null_factory_init(pjmedia_aud_dev_factory *f) /* Initialize input and output devices here */ nf->dev_count = 1; nf->dev_info = (struct null_audio_dev_info*) - pj_pool_calloc(nf->pool, nf->dev_count, - sizeof(struct null_audio_dev_info)); + pj_pool_calloc(nf->pool, nf->dev_count, + sizeof(struct null_audio_dev_info)); ndi = &nf->dev_info[0]; pj_bzero(ndi, sizeof(*ndi)); strcpy(ndi->info.name, "null device"); @@ -182,8 +181,8 @@ static unsigned null_factory_get_dev_count(pjmedia_aud_dev_factory *f) /* API: get device info */ static pj_status_t null_factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info) + unsigned index, + pjmedia_aud_dev_info *info) { struct null_audio_factory *nf = (struct null_audio_factory*)f; @@ -196,8 +195,8 @@ static pj_status_t null_factory_get_dev_info(pjmedia_aud_dev_factory *f, /* API: create default device parameter */ static pj_status_t null_factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param) + unsigned index, + pjmedia_aud_param *param) { struct null_audio_factory *nf = (struct null_audio_factory*)f; struct null_audio_dev_info *di = &nf->dev_info[index]; @@ -206,19 +205,19 @@ static pj_status_t null_factory_default_param(pjmedia_aud_dev_factory *f, pj_bzero(param, sizeof(*param)); if (di->info.input_count && di->info.output_count) { - param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; - param->rec_id = index; - param->play_id = index; + param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; + param->rec_id = index; + param->play_id = index; } else if (di->info.input_count) { - param->dir = PJMEDIA_DIR_CAPTURE; - param->rec_id = index; - param->play_id = PJMEDIA_AUD_INVALID_DEV; + param->dir = PJMEDIA_DIR_CAPTURE; + param->rec_id = index; + param->play_id = PJMEDIA_AUD_INVALID_DEV; } else if (di->info.output_count) { - param->dir = PJMEDIA_DIR_PLAYBACK; - param->play_id = index; - param->rec_id = PJMEDIA_AUD_INVALID_DEV; + param->dir = PJMEDIA_DIR_PLAYBACK; + param->play_id = index; + param->rec_id = PJMEDIA_AUD_INVALID_DEV; } else { - return PJMEDIA_EAUD_INVDEV; + return PJMEDIA_EAUD_INVDEV; } /* Set the mandatory settings here */ @@ -236,11 +235,11 @@ static pj_status_t null_factory_default_param(pjmedia_aud_dev_factory *f, /* API: create stream */ static pj_status_t null_factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { struct null_audio_factory *nf = (struct null_audio_factory*)f; pj_pool_t *pool; @@ -268,9 +267,9 @@ static pj_status_t null_factory_create_stream(pjmedia_aud_dev_factory *f, /* Apply the remaining settings */ /* Below is an example if you want to set the output volume */ if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { - null_stream_set_cap(&strm->base, - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - ¶m->output_vol); + null_stream_set_cap(&strm->base, + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + ¶m->output_vol); } /* Done */ @@ -282,7 +281,7 @@ static pj_status_t null_factory_create_stream(pjmedia_aud_dev_factory *f, /* API: Get stream info. */ static pj_status_t null_stream_get_param(pjmedia_aud_stream *s, - pjmedia_aud_param *pi) + pjmedia_aud_param *pi) { struct null_audio_stream *strm = (struct null_audio_stream*)s; @@ -292,7 +291,7 @@ static pj_status_t null_stream_get_param(pjmedia_aud_stream *s, /* Example: Update the volume setting */ if (null_stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - &pi->output_vol) == PJ_SUCCESS) + &pi->output_vol) == PJ_SUCCESS) { pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; } @@ -302,8 +301,8 @@ static pj_status_t null_stream_get_param(pjmedia_aud_stream *s, /* API: get capability */ static pj_status_t null_stream_get_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - void *pval) + pjmedia_aud_dev_cap cap, + void *pval) { struct null_audio_stream *strm = (struct null_audio_stream*)s; @@ -314,18 +313,18 @@ static pj_status_t null_stream_get_cap(pjmedia_aud_stream *s, /* Example: Get the output's volume setting */ if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { - /* Output volume setting */ - *(unsigned*)pval = 0; // retrieve output device's volume here - return PJ_SUCCESS; + /* Output volume setting */ + *(unsigned*)pval = 0; // retrieve output device's volume here + return PJ_SUCCESS; } else { - return PJMEDIA_EAUD_INVCAP; + return PJMEDIA_EAUD_INVCAP; } } /* API: set capability */ static pj_status_t null_stream_set_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - const void *pval) + pjmedia_aud_dev_cap cap, + const void *pval) { struct null_audio_stream *strm = (struct null_audio_stream*)s; @@ -336,9 +335,9 @@ static pj_status_t null_stream_set_cap(pjmedia_aud_stream *s, /* Example */ if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { - /* Output volume setting */ - // set output's volume level here - return PJ_SUCCESS; + /* Output volume setting */ + // set output's volume level here + return PJ_SUCCESS; } return PJMEDIA_EAUD_INVCAP; @@ -383,4 +382,4 @@ static pj_status_t null_stream_destroy(pjmedia_aud_stream *strm) return PJ_SUCCESS; } -#endif /* PJMEDIA_AUDIO_DEV_HAS_NULL_AUDIO */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_NULL_AUDIO */ diff --git a/pjmedia/src/pjmedia-audiodev/oboe_dev.cpp b/pjmedia/src/pjmedia-audiodev/oboe_dev.cpp index 53a2a83524..f90cceec27 100644 --- a/pjmedia/src/pjmedia-audiodev/oboe_dev.cpp +++ b/pjmedia/src/pjmedia-audiodev/oboe_dev.cpp @@ -29,8 +29,8 @@ #if defined(PJMEDIA_AUDIO_DEV_HAS_OBOE) && PJMEDIA_AUDIO_DEV_HAS_OBOE != 0 -#define THIS_FILE "oboe_dev.cpp" -#define DRIVER_NAME "Oboe" +#define THIS_FILE "oboe_dev.cpp" +#define DRIVER_NAME "Oboe" #include #include @@ -43,21 +43,21 @@ /* Device info */ typedef struct aud_dev_info { - pjmedia_aud_dev_info info; /**< Base info */ - int id; /**< Original dev ID */ + pjmedia_aud_dev_info info; /**< Base info */ + int id; /**< Original dev ID */ } aud_dev_info; /* Oboe factory */ struct oboe_aud_factory { - pjmedia_aud_dev_factory base; - pj_pool_factory *pf; - pj_pool_t *pool; + pjmedia_aud_dev_factory base; + pj_pool_factory *pf; + pj_pool_t *pool; - pj_pool_t *dev_pool; /**< Device list pool */ - unsigned dev_count; /**< Device count */ - aud_dev_info *dev_info; /**< Device info list */ + pj_pool_t *dev_pool; /**< Device list pool */ + unsigned dev_count; /**< Device count */ + aud_dev_info *dev_info; /**< Device info list */ }; class MyOboeEngine; @@ -174,26 +174,26 @@ pjmedia_aud_dev_factory* pjmedia_android_oboe_factory(pj_pool_factory *pf) /* JNI stuff for enumerating audio devices. This will invoke Java code * in pjmedia/src/pjmedia-audiodev/android/PjAudioDevInfo.java. */ -#define PJ_AUDDEV_INFO_CLASS_PATH "org/pjsip/PjAudioDevInfo" +#define PJ_AUDDEV_INFO_CLASS_PATH "org/pjsip/PjAudioDevInfo" static struct jni_objs_t { struct { - jclass cls; - jmethodID m_get_cnt; - jmethodID m_get_info; - jmethodID m_refresh; - jfieldID f_id; - jfieldID f_name; - jfieldID f_direction; - jfieldID f_sup_clockrates; - jfieldID f_sup_channels; + jclass cls; + jmethodID m_get_cnt; + jmethodID m_get_info; + jmethodID m_refresh; + jfieldID f_id; + jfieldID f_name; + jfieldID f_direction; + jfieldID f_sup_clockrates; + jfieldID f_sup_channels; } dev_info; struct { - jclass cls; - jmethodID m_current; - jmethodID m_get_app; + jclass cls; + jmethodID m_current; + jmethodID m_get_app; } activity_thread; } jobjs; @@ -208,27 +208,27 @@ extern "C" { #define GET_CLASS(class_path, class_name, cls) \ cls = jni_env->FindClass(class_path); \ if (cls == NULL || jni_env->ExceptionCheck()) { \ - jni_env->ExceptionClear(); \ + jni_env->ExceptionClear(); \ PJ_LOG(3, (THIS_FILE, "[JNI] Unable to find class '" \ - class_name "'")); \ + class_name "'")); \ status = PJMEDIA_EAUD_SYSERR; \ goto on_return; \ } else { \ jclass tmp = cls; \ - cls = (jclass)jni_env->NewGlobalRef(tmp); \ - jni_env->DeleteLocalRef(tmp); \ - if (cls == NULL) { \ - PJ_LOG(3, (THIS_FILE, "[JNI] Unable to get global ref for " \ - "class '" class_name "'")); \ - status = PJMEDIA_EAUD_SYSERR; \ - goto on_return; \ - } \ + cls = (jclass)jni_env->NewGlobalRef(tmp); \ + jni_env->DeleteLocalRef(tmp); \ + if (cls == NULL) { \ + PJ_LOG(3, (THIS_FILE, "[JNI] Unable to get global ref for " \ + "class '" class_name "'")); \ + status = PJMEDIA_EAUD_SYSERR; \ + goto on_return; \ + } \ } #define GET_METHOD_ID(cls, class_name, method_name, signature, id) \ id = jni_env->GetMethodID(cls, method_name, signature); \ if (id == 0) { \ PJ_LOG(3, (THIS_FILE, "[JNI] Unable to find method '" method_name \ - "' in class '" class_name "'")); \ + "' in class '" class_name "'")); \ status = PJMEDIA_EAUD_SYSERR; \ goto on_return; \ } @@ -236,7 +236,7 @@ extern "C" { id = jni_env->GetStaticMethodID(cls, method_name, signature); \ if (id == 0) { \ PJ_LOG(3, (THIS_FILE, "[JNI] Unable to find static method '" \ - method_name "' in class '" class_name "'")); \ + method_name "' in class '" class_name "'")); \ status = PJMEDIA_EAUD_SYSERR; \ goto on_return; \ } @@ -244,7 +244,7 @@ extern "C" { id = jni_env->GetFieldID(cls, field_name, signature); \ if (id == 0) { \ PJ_LOG(3, (THIS_FILE, "[JNI] Unable to find field '" field_name \ - "' in class '" class_name "'")); \ + "' in class '" class_name "'")); \ status = PJMEDIA_EAUD_SYSERR; \ goto on_return; \ } @@ -263,33 +263,33 @@ static pj_status_t jni_init_ids() /* PjAudioDevInfo class info */ GET_CLASS(PJ_AUDDEV_INFO_CLASS_PATH, "PjAudioDevInfo", jobjs.dev_info.cls); GET_SMETHOD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "GetCount", "()I", - jobjs.dev_info.m_get_cnt); + jobjs.dev_info.m_get_cnt); GET_SMETHOD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "GetInfo", - "(I)L" PJ_AUDDEV_INFO_CLASS_PATH ";", - jobjs.dev_info.m_get_info); + "(I)L" PJ_AUDDEV_INFO_CLASS_PATH ";", + jobjs.dev_info.m_get_info); GET_SMETHOD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "RefreshDevices", - "(Landroid/content/Context;)V", - jobjs.dev_info.m_refresh); + "(Landroid/content/Context;)V", + jobjs.dev_info.m_refresh); GET_FIELD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "id", "I", - jobjs.dev_info.f_id); + jobjs.dev_info.f_id); GET_FIELD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "name", "Ljava/lang/String;", - jobjs.dev_info.f_name); + jobjs.dev_info.f_name); GET_FIELD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "direction", "I", - jobjs.dev_info.f_direction); + jobjs.dev_info.f_direction); GET_FIELD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "supportedClockRates", "[I", - jobjs.dev_info.f_sup_clockrates); + jobjs.dev_info.f_sup_clockrates); GET_FIELD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "supportedChannelCounts", "[I", - jobjs.dev_info.f_sup_channels); + jobjs.dev_info.f_sup_channels); /* ActivityThread class info */ GET_CLASS("android/app/ActivityThread", "ActivityThread", - jobjs.activity_thread.cls); + jobjs.activity_thread.cls); GET_SMETHOD_ID(jobjs.activity_thread.cls, "ActivityThread", - "currentActivityThread", "()Landroid/app/ActivityThread;", - jobjs.activity_thread.m_current); + "currentActivityThread", "()Landroid/app/ActivityThread;", + jobjs.activity_thread.m_current); GET_METHOD_ID(jobjs.activity_thread.cls, "ActivityThread", - "getApplication", "()Landroid/app/Application;", - jobjs.activity_thread.m_get_app); + "getApplication", "()Landroid/app/Application;", + jobjs.activity_thread.m_get_app); on_return: pj_jni_dettach_jvm(with_attach); @@ -307,13 +307,13 @@ static void jni_deinit_ids() pj_bool_t with_attach = pj_jni_attach_jvm(&jni_env); if (jobjs.dev_info.cls) { - jni_env->DeleteGlobalRef(jobjs.dev_info.cls); - jobjs.dev_info.cls = NULL; + jni_env->DeleteGlobalRef(jobjs.dev_info.cls); + jobjs.dev_info.cls = NULL; } if (jobjs.activity_thread.cls) { - jni_env->DeleteGlobalRef(jobjs.activity_thread.cls); - jobjs.activity_thread.cls = NULL; + jni_env->DeleteGlobalRef(jobjs.activity_thread.cls); + jobjs.activity_thread.cls = NULL; } pj_jni_dettach_jvm(with_attach); @@ -323,13 +323,13 @@ static jobject get_global_context(JNIEnv *jni_env) { jobject context = NULL; jobject cur_at = jni_env->CallStaticObjectMethod( - jobjs.activity_thread.cls, - jobjs.activity_thread.m_current); + jobjs.activity_thread.cls, + jobjs.activity_thread.m_current); if (cur_at==NULL) - return NULL; + return NULL; context = jni_env->CallObjectMethod(cur_at, - jobjs.activity_thread.m_get_app); + jobjs.activity_thread.m_get_app); return context; } @@ -341,11 +341,11 @@ static pj_status_t oboe_init(pjmedia_aud_dev_factory *f) status = jni_init_ids(); if (status != PJ_SUCCESS) - return status; + return status; status = oboe_refresh(f); if (status != PJ_SUCCESS) - return status; + return status; return PJ_SUCCESS; } @@ -368,18 +368,18 @@ static pj_status_t oboe_refresh(pjmedia_aud_dev_factory *ff) jobject context = get_global_context(jni_env); if (context == NULL) { - PJ_LOG(3, (THIS_FILE, "Failed to get context")); - status = PJMEDIA_EAUD_SYSERR; - goto on_return; + PJ_LOG(3, (THIS_FILE, "Failed to get context")); + status = PJMEDIA_EAUD_SYSERR; + goto on_return; } /* PjAudioDevInfo::RefreshDevices(Context) */ jni_env->CallStaticVoidMethod(jobjs.dev_info.cls, - jobjs.dev_info.m_refresh, context); + jobjs.dev_info.m_refresh, context); /* dev_count = PjAudioDevInfo::GetCount() */ dev_count = jni_env->CallStaticIntMethod(jobjs.dev_info.cls, - jobjs.dev_info.m_get_cnt); + jobjs.dev_info.m_get_cnt); if (dev_count < 0) { PJ_LOG(3, (THIS_FILE, "Failed to get camera count")); status = PJMEDIA_EAUD_SYSERR; @@ -388,58 +388,58 @@ static pj_status_t oboe_refresh(pjmedia_aud_dev_factory *ff) /* Start querying device info */ f->dev_info = (aud_dev_info*) - pj_pool_calloc(f->dev_pool, dev_count, - sizeof(aud_dev_info)); + pj_pool_calloc(f->dev_pool, dev_count, + sizeof(aud_dev_info)); for (i = 0; i < dev_count; i++) { - aud_dev_info *adi = &f->dev_info[f->dev_count]; - pjmedia_aud_dev_info *base_adi = &adi->info; + aud_dev_info *adi = &f->dev_info[f->dev_count]; + pjmedia_aud_dev_info *base_adi = &adi->info; jobject jdev_info; - jint jinttmp; - - /* jdev_info = PjAudioDevInfo::GetInfo(i) */ - jdev_info = jni_env->CallStaticObjectMethod( - jobjs.dev_info.cls, - jobjs.dev_info.m_get_info, - i); - if (jdev_info == NULL) - continue; - - /* Get device ID, direction, etc */ - adi->id = jni_env->GetIntField(jdev_info, jobjs.dev_info.f_id); - jinttmp = jni_env->GetIntField(jdev_info, jobjs.dev_info.f_direction); - base_adi->input_count = (jinttmp & PJMEDIA_DIR_CAPTURE); - base_adi->output_count = (jinttmp & PJMEDIA_DIR_PLAYBACK); - base_adi->caps = 0; - - /* Get name info */ - jstring jstrtmp = (jstring)jni_env->GetObjectField(jdev_info, jobjs.dev_info.f_name); - const char *strtmp = jni_env->GetStringUTFChars(jstrtmp, NULL); - pj_ansi_strncpy(base_adi->name, strtmp, sizeof(base_adi->name)); - - f->dev_count++; + jint jinttmp; + + /* jdev_info = PjAudioDevInfo::GetInfo(i) */ + jdev_info = jni_env->CallStaticObjectMethod( + jobjs.dev_info.cls, + jobjs.dev_info.m_get_info, + i); + if (jdev_info == NULL) + continue; + + /* Get device ID, direction, etc */ + adi->id = jni_env->GetIntField(jdev_info, jobjs.dev_info.f_id); + jinttmp = jni_env->GetIntField(jdev_info, jobjs.dev_info.f_direction); + base_adi->input_count = (jinttmp & PJMEDIA_DIR_CAPTURE); + base_adi->output_count = (jinttmp & PJMEDIA_DIR_PLAYBACK); + base_adi->caps = 0; + + /* Get name info */ + jstring jstrtmp = (jstring)jni_env->GetObjectField(jdev_info, jobjs.dev_info.f_name); + const char *strtmp = jni_env->GetStringUTFChars(jstrtmp, NULL); + pj_ansi_strncpy(base_adi->name, strtmp, sizeof(base_adi->name)); + + f->dev_count++; on_skip_dev: - jni_env->DeleteLocalRef(jdev_info); + jni_env->DeleteLocalRef(jdev_info); } PJ_LOG(4, (THIS_FILE, - "Oboe audio device initialized with %d device(s):", - f->dev_count)); + "Oboe audio device initialized with %d device(s):", + f->dev_count)); for (i = 0; i < f->dev_count; i++) { - aud_dev_info *adi = &f->dev_info[i]; - PJ_LOG(4, (THIS_FILE, "%2d (native id=%d): %s (%s%s%s)", - i, adi->id, adi->info.name, - adi->info.input_count?"in":"", - adi->info.input_count && adi->info.output_count?"+":"", - adi->info.output_count?"out":"" - )); + aud_dev_info *adi = &f->dev_info[i]; + PJ_LOG(4, (THIS_FILE, "%2d (native id=%d): %s (%s%s%s)", + i, adi->id, adi->info.name, + adi->info.input_count?"in":"", + adi->info.input_count && adi->info.output_count?"+":"", + adi->info.output_count?"out":"" + )); } on_return: if (context) - jni_env->DeleteLocalRef(context); + jni_env->DeleteLocalRef(context); pj_jni_dettach_jvm(with_attach); return status; @@ -497,7 +497,7 @@ static pj_status_t oboe_default_param(pjmedia_aud_dev_factory *ff, status = oboe_get_dev_info(ff, index, &adi); if (status != PJ_SUCCESS) - return status; + return status; pj_bzero(param, sizeof(*param)); if (adi.input_count && adi.output_count) { @@ -546,19 +546,19 @@ class AtomicQueue { public: AtomicQueue(unsigned max_frame_cnt, unsigned frame_size, - const char* name_= "") : - maxFrameCnt(max_frame_cnt), frameSize(frame_size), - ptrWrite(0), ptrRead(0), - buffer(NULL), name(name_) + const char* name_= "") : + maxFrameCnt(max_frame_cnt), frameSize(frame_size), + ptrWrite(0), ptrRead(0), + buffer(NULL), name(name_) { - buffer = new char[maxFrameCnt * frameSize]; + buffer = new char[maxFrameCnt * frameSize]; - /* Surpress warning when debugging log is disabled */ - PJ_UNUSED_ARG(name); + /* Surpress warning when debugging log is disabled */ + PJ_UNUSED_ARG(name); } ~AtomicQueue() { - delete [] buffer; + delete [] buffer; } /* Get a frame from the head of the queue */ @@ -566,31 +566,31 @@ class AtomicQueue { if (ptrRead == ptrWrite) return false; - unsigned cur_ptr = ptrRead; - void *p = &buffer[cur_ptr * frameSize]; - pj_memcpy(frame, p, frameSize); - inc_ptr_read_if_not_yet(cur_ptr); + unsigned cur_ptr = ptrRead; + void *p = &buffer[cur_ptr * frameSize]; + pj_memcpy(frame, p, frameSize); + inc_ptr_read_if_not_yet(cur_ptr); - //__android_log_print(ANDROID_LOG_INFO, name, - // "GET: ptrRead=%d ptrWrite=%d\n", - // ptrRead.load(), ptrWrite.load()); - return true; + //__android_log_print(ANDROID_LOG_INFO, name, + // "GET: ptrRead=%d ptrWrite=%d\n", + // ptrRead.load(), ptrWrite.load()); + return true; } /* Put a frame to the back of the queue */ void put(void* frame) { - unsigned cur_ptr = ptrWrite; - void *p = &buffer[cur_ptr * frameSize]; - pj_memcpy(p, frame, frameSize); - unsigned next_ptr = inc_ptr_write(cur_ptr); - - /* Increment read pointer if next write is overlapping (next_ptr == read ptr) */ - unsigned next_read_ptr = (next_ptr == maxFrameCnt-1)? 0 : (next_ptr+1); - ptrRead.compare_exchange_strong(next_ptr, next_read_ptr); - - //__android_log_print(ANDROID_LOG_INFO, name, - // "PUT: ptrRead=%d ptrWrite=%d\n", - // ptrRead.load(), ptrWrite.load()); + unsigned cur_ptr = ptrWrite; + void *p = &buffer[cur_ptr * frameSize]; + pj_memcpy(p, frame, frameSize); + unsigned next_ptr = inc_ptr_write(cur_ptr); + + /* Increment read pointer if next write is overlapping (next_ptr == read ptr) */ + unsigned next_read_ptr = (next_ptr == maxFrameCnt-1)? 0 : (next_ptr+1); + ptrRead.compare_exchange_strong(next_ptr, next_read_ptr); + + //__android_log_print(ANDROID_LOG_INFO, name, + // "PUT: ptrRead=%d ptrWrite=%d\n", + // ptrRead.load(), ptrWrite.load()); } private: @@ -607,19 +607,19 @@ class AtomicQueue { * right before the read pointer (buffer almost full). */ bool inc_ptr_read_if_not_yet(unsigned old_ptr) { - unsigned new_ptr = (old_ptr == maxFrameCnt-1)? 0 : (old_ptr+1); - return ptrRead.compare_exchange_strong(old_ptr, new_ptr); + unsigned new_ptr = (old_ptr == maxFrameCnt-1)? 0 : (old_ptr+1); + return ptrRead.compare_exchange_strong(old_ptr, new_ptr); } /* Increment write pointer */ unsigned inc_ptr_write(unsigned old_ptr) { - unsigned new_ptr = (old_ptr == maxFrameCnt-1)? 0 : (old_ptr+1); - if (ptrWrite.compare_exchange_strong(old_ptr, new_ptr)) - return new_ptr; + unsigned new_ptr = (old_ptr == maxFrameCnt-1)? 0 : (old_ptr+1); + if (ptrWrite.compare_exchange_strong(old_ptr, new_ptr)) + return new_ptr; /* Should never happen */ - pj_assert(!"There is more than one producer!"); - return old_ptr; + pj_assert(!"There is more than one producer!"); + return old_ptr; } AtomicQueue() {} @@ -628,7 +628,7 @@ class AtomicQueue { /* Interface to Oboe */ class MyOboeEngine : oboe::AudioStreamDataCallback, - oboe::AudioStreamErrorCallback + oboe::AudioStreamErrorCallback { public: MyOboeEngine(struct oboe_aud_stream *stream_, pjmedia_dir dir_) @@ -636,398 +636,398 @@ class MyOboeEngine : oboe::AudioStreamDataCallback, thread(NULL), thread_quit(PJ_TRUE), queue(NULL), err_thread_registered(false), mutex(NULL) { - pj_assert(dir == PJMEDIA_DIR_CAPTURE || dir == PJMEDIA_DIR_PLAYBACK); - dir_st = (dir == PJMEDIA_DIR_CAPTURE? "capture":"playback"); - pj_set_timestamp32(&ts, 0, 0); + pj_assert(dir == PJMEDIA_DIR_CAPTURE || dir == PJMEDIA_DIR_PLAYBACK); + dir_st = (dir == PJMEDIA_DIR_CAPTURE? "capture":"playback"); + pj_set_timestamp32(&ts, 0, 0); } pj_status_t Start() { - pj_status_t status; - - if (!mutex) { - status = pj_mutex_create_recursive(stream->pool, "oboe", &mutex); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, - "Oboe stream %s failed creating mutex", dir_st)); - return status; - } - } - - int dev_id = 0; - oboe::AudioStreamBuilder sb; - - pj_mutex_lock(mutex); - - if (oboe_stream) { - pj_mutex_unlock(mutex); - return PJ_SUCCESS; - } - - if (dir == PJMEDIA_DIR_CAPTURE) { - sb.setDirection(oboe::Direction::Input); - if (stream->param.rec_id >= 0 && - stream->param.rec_id < stream->f->dev_count) - { - dev_id = stream->f->dev_info[stream->param.rec_id].id; - } - } else { - sb.setDirection(oboe::Direction::Output); - if (stream->param.play_id >= 0 && - stream->param.play_id < stream->f->dev_count) - { - dev_id = stream->f->dev_info[stream->param.play_id].id; - } - } - sb.setDeviceId(dev_id); - sb.setSampleRate(stream->param.clock_rate); - sb.setChannelCount(stream->param.channel_count); - sb.setPerformanceMode(oboe::PerformanceMode::LowLatency); - sb.setFormat(oboe::AudioFormat::I16); - sb.setUsage(oboe::Usage::VoiceCommunication); - sb.setContentType(oboe::ContentType::Speech); - sb.setDataCallback(this); - sb.setErrorCallback(this); - sb.setFramesPerDataCallback(stream->param.samples_per_frame / - stream->param.channel_count); - - /* Somehow mic does not work on Samsung S10 (get no error and - * low latency, but callback is never invoked) if sample rate - * conversion is specified. If it is not specified (default is None), - * mic does not get low latency on, but it works. - */ - if (dir == PJMEDIA_DIR_PLAYBACK) { - sb.setSampleRateConversionQuality( - oboe::SampleRateConversionQuality::High); - - /* Also if mic is Exclusive, it won't reopen after - * plug/unplug headset (on Samsung S10). - */ - sb.setSharingMode(oboe::SharingMode::Exclusive); - } - - /* Create queue */ - unsigned latency = (dir == PJMEDIA_DIR_CAPTURE? - stream->param.input_latency_ms : - stream->param.output_latency_ms); - unsigned queue_size = latency * stream->param.clock_rate * - stream->param.channel_count / 1000 / - stream->param.samples_per_frame; - - /* Normalize queue size to be in range of 3-10 frames */ - if (queue_size < 3) queue_size = 3; - if (queue_size > 10) queue_size = 10; - - PJ_LOG(3,(THIS_FILE, - "Oboe stream %s queue size=%d frames (latency=%d ms)", - dir_st, queue_size, latency)); - - queue = new AtomicQueue(queue_size, stream->param.samples_per_frame*2, - dir_st); - - /* Create semaphore */ + pj_status_t status; + + if (!mutex) { + status = pj_mutex_create_recursive(stream->pool, "oboe", &mutex); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(THIS_FILE, status, + "Oboe stream %s failed creating mutex", dir_st)); + return status; + } + } + + int dev_id = 0; + oboe::AudioStreamBuilder sb; + + pj_mutex_lock(mutex); + + if (oboe_stream) { + pj_mutex_unlock(mutex); + return PJ_SUCCESS; + } + + if (dir == PJMEDIA_DIR_CAPTURE) { + sb.setDirection(oboe::Direction::Input); + if (stream->param.rec_id >= 0 && + stream->param.rec_id < stream->f->dev_count) + { + dev_id = stream->f->dev_info[stream->param.rec_id].id; + } + } else { + sb.setDirection(oboe::Direction::Output); + if (stream->param.play_id >= 0 && + stream->param.play_id < stream->f->dev_count) + { + dev_id = stream->f->dev_info[stream->param.play_id].id; + } + } + sb.setDeviceId(dev_id); + sb.setSampleRate(stream->param.clock_rate); + sb.setChannelCount(stream->param.channel_count); + sb.setPerformanceMode(oboe::PerformanceMode::LowLatency); + sb.setFormat(oboe::AudioFormat::I16); + sb.setUsage(oboe::Usage::VoiceCommunication); + sb.setContentType(oboe::ContentType::Speech); + sb.setDataCallback(this); + sb.setErrorCallback(this); + sb.setFramesPerDataCallback(stream->param.samples_per_frame / + stream->param.channel_count); + + /* Somehow mic does not work on Samsung S10 (get no error and + * low latency, but callback is never invoked) if sample rate + * conversion is specified. If it is not specified (default is None), + * mic does not get low latency on, but it works. + */ + if (dir == PJMEDIA_DIR_PLAYBACK) { + sb.setSampleRateConversionQuality( + oboe::SampleRateConversionQuality::High); + + /* Also if mic is Exclusive, it won't reopen after + * plug/unplug headset (on Samsung S10). + */ + sb.setSharingMode(oboe::SharingMode::Exclusive); + } + + /* Create queue */ + unsigned latency = (dir == PJMEDIA_DIR_CAPTURE? + stream->param.input_latency_ms : + stream->param.output_latency_ms); + unsigned queue_size = latency * stream->param.clock_rate * + stream->param.channel_count / 1000 / + stream->param.samples_per_frame; + + /* Normalize queue size to be in range of 3-10 frames */ + if (queue_size < 3) queue_size = 3; + if (queue_size > 10) queue_size = 10; + + PJ_LOG(3,(THIS_FILE, + "Oboe stream %s queue size=%d frames (latency=%d ms)", + dir_st, queue_size, latency)); + + queue = new AtomicQueue(queue_size, stream->param.samples_per_frame*2, + dir_st); + + /* Create semaphore */ if (sem_init(&sem, 0, 0) != 0) { - pj_mutex_unlock(mutex); - return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); - } + pj_mutex_unlock(mutex); + return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); + } - /* Create thread */ - thread_quit = PJ_FALSE; + /* Create thread */ + thread_quit = PJ_FALSE; status = pj_thread_create(stream->pool, "android_oboe", &AudioThread, this, 0, 0, &thread); if (status != PJ_SUCCESS) { - pj_mutex_unlock(mutex); + pj_mutex_unlock(mutex); return status; - } - - /* Open & start oboe stream */ - oboe::Result result = sb.openStream(&oboe_stream); - if (result != oboe::Result::OK) { - PJ_LOG(3,(THIS_FILE, - "Oboe stream %s open failed (err=%d/%s)", - dir_st, result, oboe::convertToText(result))); - pj_mutex_unlock(mutex); - return PJMEDIA_EAUD_SYSERR; - } - - result = oboe_stream->requestStart(); - if (result != oboe::Result::OK) { - PJ_LOG(3,(THIS_FILE, - "Oboe stream %s start failed (err=%d/%s)", - dir_st, result, oboe::convertToText(result))); - pj_mutex_unlock(mutex); - return PJMEDIA_EAUD_SYSERR; - } - - PJ_LOG(4, (THIS_FILE, - "Oboe stream %s started, " - "id=%d, clock_rate=%d, channel_count=%d, " - "samples_per_frame=%d (%dms), " - "API=%d/%s, exclusive=%s, low latency=%s, " - "size per callback=%d, buffer capacity=%d, burst size=%d", - dir_st, - stream->param.play_id, - stream->param.clock_rate, - stream->param.channel_count, - stream->param.samples_per_frame, - stream->param.samples_per_frame * 1000 / - stream->param.clock_rate, - oboe_stream->getAudioApi(), - (oboe_stream->usesAAudio()? "AAudio":"other"), - (oboe_stream->getSharingMode()== - oboe::SharingMode::Exclusive? "yes":"no"), - (oboe_stream->getPerformanceMode()== - oboe::PerformanceMode::LowLatency? "yes":"no"), - oboe_stream->getFramesPerDataCallback()* - stream->param.channel_count, - oboe_stream->getBufferCapacityInFrames(), - oboe_stream->getFramesPerBurst() - )); - - pj_mutex_unlock(mutex); - return PJ_SUCCESS; + } + + /* Open & start oboe stream */ + oboe::Result result = sb.openStream(&oboe_stream); + if (result != oboe::Result::OK) { + PJ_LOG(3,(THIS_FILE, + "Oboe stream %s open failed (err=%d/%s)", + dir_st, result, oboe::convertToText(result))); + pj_mutex_unlock(mutex); + return PJMEDIA_EAUD_SYSERR; + } + + result = oboe_stream->requestStart(); + if (result != oboe::Result::OK) { + PJ_LOG(3,(THIS_FILE, + "Oboe stream %s start failed (err=%d/%s)", + dir_st, result, oboe::convertToText(result))); + pj_mutex_unlock(mutex); + return PJMEDIA_EAUD_SYSERR; + } + + PJ_LOG(4, (THIS_FILE, + "Oboe stream %s started, " + "id=%d, clock_rate=%d, channel_count=%d, " + "samples_per_frame=%d (%dms), " + "API=%d/%s, exclusive=%s, low latency=%s, " + "size per callback=%d, buffer capacity=%d, burst size=%d", + dir_st, + stream->param.play_id, + stream->param.clock_rate, + stream->param.channel_count, + stream->param.samples_per_frame, + stream->param.samples_per_frame * 1000 / + stream->param.clock_rate, + oboe_stream->getAudioApi(), + (oboe_stream->usesAAudio()? "AAudio":"other"), + (oboe_stream->getSharingMode()== + oboe::SharingMode::Exclusive? "yes":"no"), + (oboe_stream->getPerformanceMode()== + oboe::PerformanceMode::LowLatency? "yes":"no"), + oboe_stream->getFramesPerDataCallback()* + stream->param.channel_count, + oboe_stream->getBufferCapacityInFrames(), + oboe_stream->getFramesPerBurst() + )); + + pj_mutex_unlock(mutex); + return PJ_SUCCESS; } void Stop() { - /* Just return if it has not been started */ - if (!mutex || thread_quit) { - PJ_LOG(5, (THIS_FILE, "Oboe stream %s stop request when " - "already stopped.", dir_st)); - return; - } + /* Just return if it has not been started */ + if (!mutex || thread_quit) { + PJ_LOG(5, (THIS_FILE, "Oboe stream %s stop request when " + "already stopped.", dir_st)); + return; + } - PJ_LOG(5, (THIS_FILE, "Oboe stream %s stop requested.", dir_st)); + PJ_LOG(5, (THIS_FILE, "Oboe stream %s stop requested.", dir_st)); - pj_mutex_lock(mutex); + pj_mutex_lock(mutex); - if (thread) { - PJ_LOG(5,(THIS_FILE, "Oboe %s stopping thread", dir_st)); - thread_quit = PJ_TRUE; + if (thread) { + PJ_LOG(5,(THIS_FILE, "Oboe %s stopping thread", dir_st)); + thread_quit = PJ_TRUE; sem_post(&sem); pj_thread_join(thread); pj_thread_destroy(thread); thread = NULL; - } + } - if (oboe_stream) { - PJ_LOG(5,(THIS_FILE, "Oboe %s closing stream", dir_st)); - oboe_stream->close(); - delete oboe_stream; - oboe_stream = NULL; - } + if (oboe_stream) { + PJ_LOG(5,(THIS_FILE, "Oboe %s closing stream", dir_st)); + oboe_stream->close(); + delete oboe_stream; + oboe_stream = NULL; + } - if (queue) { - PJ_LOG(5,(THIS_FILE, "Oboe %s deleting queue", dir_st)); - delete queue; - queue = NULL; - } + if (queue) { + PJ_LOG(5,(THIS_FILE, "Oboe %s deleting queue", dir_st)); + delete queue; + queue = NULL; + } - sem_destroy(&sem); + sem_destroy(&sem); - pj_mutex_unlock(mutex); + pj_mutex_unlock(mutex); - PJ_LOG(4, (THIS_FILE, "Oboe stream %s stopped.", dir_st)); + PJ_LOG(4, (THIS_FILE, "Oboe stream %s stopped.", dir_st)); } /* Oboe callback, here let's just use Android native mutex & semaphore * so we don't need to register the thread to PJLIB. */ oboe::DataCallbackResult onAudioReady(oboe::AudioStream *oboeStream, - void *audioData, - int32_t numFrames) + void *audioData, + int32_t numFrames) { - if (dir == PJMEDIA_DIR_CAPTURE) { - /* Put the audio frame to queue */ - queue->put(audioData); - } else { - /* Get audio frame from queue */ - if (!queue->get(audioData)) { - pj_bzero(audioData, stream->param.samples_per_frame*2); - __android_log_write(ANDROID_LOG_WARN, THIS_FILE, - "Oboe playback got an empty queue"); - } - } - - sem_post(&sem); - - return (thread_quit? oboe::DataCallbackResult::Stop : - oboe::DataCallbackResult::Continue); + if (dir == PJMEDIA_DIR_CAPTURE) { + /* Put the audio frame to queue */ + queue->put(audioData); + } else { + /* Get audio frame from queue */ + if (!queue->get(audioData)) { + pj_bzero(audioData, stream->param.samples_per_frame*2); + __android_log_write(ANDROID_LOG_WARN, THIS_FILE, + "Oboe playback got an empty queue"); + } + } + + sem_post(&sem); + + return (thread_quit? oboe::DataCallbackResult::Stop : + oboe::DataCallbackResult::Continue); } void onErrorAfterClose(oboe::AudioStream *oboeStream, oboe::Result result) { - __android_log_print(ANDROID_LOG_INFO, THIS_FILE, - "Oboe %s got onErrorAfterClose(%d)", - dir_st, result); - - /* Register callback thread */ - if (!err_thread_registered || !pj_thread_is_registered()) - { - pj_thread_t* tmp_thread; - pj_bzero(err_thread_desc, sizeof(pj_thread_desc)); - pj_thread_register("oboe_err_thread", err_thread_desc, - &tmp_thread); - err_thread_registered = true; - } - - /* Just try to restart */ - pj_mutex_lock(mutex); - - /* Make sure stop request has not been made */ - if (!thread_quit) { - PJ_LOG(3,(THIS_FILE, - "Oboe stream %s error (%d/%s), " - "trying to restart stream..", - dir_st, result, oboe::convertToText(result))); - - Stop(); - Start(); - } - - pj_mutex_unlock(mutex); + __android_log_print(ANDROID_LOG_INFO, THIS_FILE, + "Oboe %s got onErrorAfterClose(%d)", + dir_st, result); + + /* Register callback thread */ + if (!err_thread_registered || !pj_thread_is_registered()) + { + pj_thread_t* tmp_thread; + pj_bzero(err_thread_desc, sizeof(pj_thread_desc)); + pj_thread_register("oboe_err_thread", err_thread_desc, + &tmp_thread); + err_thread_registered = true; + } + + /* Just try to restart */ + pj_mutex_lock(mutex); + + /* Make sure stop request has not been made */ + if (!thread_quit) { + PJ_LOG(3,(THIS_FILE, + "Oboe stream %s error (%d/%s), " + "trying to restart stream..", + dir_st, result, oboe::convertToText(result))); + + Stop(); + Start(); + } + + pj_mutex_unlock(mutex); } ~MyOboeEngine() { - /* Oboe should have been stopped before destroying the engine. - * As stopping it here (below) may cause undefined behaviour when - * there is race condition against restart in onErrorAfterClose(). - */ - pj_assert(thread_quit == PJ_TRUE); - - /* Forcefully stopping Oboe anyway */ - Stop(); - - /* Try to trigger context switch in case onErrorAfterClose() is - * waiting for mutex. - */ - pj_thread_sleep(1); - - if (mutex) - pj_mutex_destroy(mutex); + /* Oboe should have been stopped before destroying the engine. + * As stopping it here (below) may cause undefined behaviour when + * there is race condition against restart in onErrorAfterClose(). + */ + pj_assert(thread_quit == PJ_TRUE); + + /* Forcefully stopping Oboe anyway */ + Stop(); + + /* Try to trigger context switch in case onErrorAfterClose() is + * waiting for mutex. + */ + pj_thread_sleep(1); + + if (mutex) + pj_mutex_destroy(mutex); } private: static int AudioThread(void *arg) { - MyOboeEngine *this_ = (MyOboeEngine*)arg; - struct oboe_aud_stream *stream = this_->stream; - pj_int16_t *tmp_buf; - unsigned ts_inc; - pj_status_t status; - - /* Try to bump up the thread priority */ - enum { - THREAD_PRIORITY_AUDIO = -16, - THREAD_PRIORITY_URGENT_AUDIO = -19 - }; - status = pj_thread_set_prio(NULL, THREAD_PRIORITY_URGENT_AUDIO); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, - "Warning: Oboe %s failed increasing thread priority", - this_->dir_st)); - } - - tmp_buf = new pj_int16_t[this_->stream->param.samples_per_frame](); - ts_inc = stream->param.samples_per_frame/stream->param.channel_count; - - /* Queue a silent frame to playback buffer */ - if (this_->dir == PJMEDIA_DIR_PLAYBACK) { - this_->queue->put(tmp_buf); - } - - while (1) { - sem_wait(&this_->sem); - if (this_->thread_quit) - break; - - if (this_->dir == PJMEDIA_DIR_CAPTURE) { - unsigned cnt = 0; - bool stop_stream = false; - - /* Read audio frames from Oboe */ - while (this_->queue->get(tmp_buf)) { - /* Send audio frame to app via callback rec_cb() */ - pjmedia_frame frame; - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.size = stream->param.samples_per_frame * 2; - frame.bit_info = 0; - frame.buf = (void *)tmp_buf; - frame.timestamp = this_->ts; - status = (*stream->rec_cb)(stream->user_data, &frame); - if (status != PJ_SUCCESS) { - /* App wants to stop audio dev stream */ - stop_stream = true; - break; - } - - /* Increment timestamp */ - pj_add_timestamp32(&this_->ts, ts_inc); - ++cnt; - } - - if (stop_stream) - break; - - /* Print log for debugging purpose */ - if (cnt == 0) { - PJ_LOG(5,(THIS_FILE, "Oboe %s got an empty queue", - this_->dir_st)); - } else if (cnt > 1) { - PJ_LOG(5,(THIS_FILE, "Oboe %s got a burst of %d frames", - this_->dir_st, cnt)); - } - } else { - /* Get audio frame from app via callback play_cb() */ - pjmedia_frame frame; - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.size = stream->param.samples_per_frame * 2; - frame.bit_info = 0; - frame.buf = (void *)tmp_buf; - frame.timestamp = this_->ts; - status = (*stream->play_cb)(stream->user_data, &frame); - - /* Send audio frame to Oboe */ - if (status == PJ_SUCCESS) { - this_->queue->put(tmp_buf); - } else { - /* App wants to stop audio dev stream */ - break; - } - - /* Increment timestamp */ - pj_add_timestamp32(&this_->ts, ts_inc); - } - } - - delete [] tmp_buf; - - PJ_LOG(5,(THIS_FILE, "Oboe %s thread stopped", this_->dir_st)); - return 0; + MyOboeEngine *this_ = (MyOboeEngine*)arg; + struct oboe_aud_stream *stream = this_->stream; + pj_int16_t *tmp_buf; + unsigned ts_inc; + pj_status_t status; + + /* Try to bump up the thread priority */ + enum { + THREAD_PRIORITY_AUDIO = -16, + THREAD_PRIORITY_URGENT_AUDIO = -19 + }; + status = pj_thread_set_prio(NULL, THREAD_PRIORITY_URGENT_AUDIO); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(THIS_FILE, status, + "Warning: Oboe %s failed increasing thread priority", + this_->dir_st)); + } + + tmp_buf = new pj_int16_t[this_->stream->param.samples_per_frame](); + ts_inc = stream->param.samples_per_frame/stream->param.channel_count; + + /* Queue a silent frame to playback buffer */ + if (this_->dir == PJMEDIA_DIR_PLAYBACK) { + this_->queue->put(tmp_buf); + } + + while (1) { + sem_wait(&this_->sem); + if (this_->thread_quit) + break; + + if (this_->dir == PJMEDIA_DIR_CAPTURE) { + unsigned cnt = 0; + bool stop_stream = false; + + /* Read audio frames from Oboe */ + while (this_->queue->get(tmp_buf)) { + /* Send audio frame to app via callback rec_cb() */ + pjmedia_frame frame; + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.size = stream->param.samples_per_frame * 2; + frame.bit_info = 0; + frame.buf = (void *)tmp_buf; + frame.timestamp = this_->ts; + status = (*stream->rec_cb)(stream->user_data, &frame); + if (status != PJ_SUCCESS) { + /* App wants to stop audio dev stream */ + stop_stream = true; + break; + } + + /* Increment timestamp */ + pj_add_timestamp32(&this_->ts, ts_inc); + ++cnt; + } + + if (stop_stream) + break; + + /* Print log for debugging purpose */ + if (cnt == 0) { + PJ_LOG(5,(THIS_FILE, "Oboe %s got an empty queue", + this_->dir_st)); + } else if (cnt > 1) { + PJ_LOG(5,(THIS_FILE, "Oboe %s got a burst of %d frames", + this_->dir_st, cnt)); + } + } else { + /* Get audio frame from app via callback play_cb() */ + pjmedia_frame frame; + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.size = stream->param.samples_per_frame * 2; + frame.bit_info = 0; + frame.buf = (void *)tmp_buf; + frame.timestamp = this_->ts; + status = (*stream->play_cb)(stream->user_data, &frame); + + /* Send audio frame to Oboe */ + if (status == PJ_SUCCESS) { + this_->queue->put(tmp_buf); + } else { + /* App wants to stop audio dev stream */ + break; + } + + /* Increment timestamp */ + pj_add_timestamp32(&this_->ts, ts_inc); + } + } + + delete [] tmp_buf; + + PJ_LOG(5,(THIS_FILE, "Oboe %s thread stopped", this_->dir_st)); + return 0; } private: - struct oboe_aud_stream *stream; - pjmedia_dir dir; - oboe::AudioStream *oboe_stream; - const char *dir_st; - pj_thread_t *thread; - volatile pj_bool_t thread_quit; - sem_t sem; - AtomicQueue *queue; - pj_timestamp ts; - bool err_thread_registered; - pj_thread_desc err_thread_desc; - pj_mutex_t *mutex; + struct oboe_aud_stream *stream; + pjmedia_dir dir; + oboe::AudioStream *oboe_stream; + const char *dir_st; + pj_thread_t *thread; + volatile pj_bool_t thread_quit; + sem_t sem; + AtomicQueue *queue; + pj_timestamp ts; + bool err_thread_registered; + pj_thread_desc err_thread_desc; + pj_mutex_t *mutex; }; /* API: create stream */ static pj_status_t oboe_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { struct oboe_aud_factory *pa = (struct oboe_aud_factory*)f; pj_pool_t *pool; @@ -1057,19 +1057,19 @@ static pj_status_t oboe_create_stream(pjmedia_aud_dev_factory *f, stream->play_cb = play_cb; if (param->dir & PJMEDIA_DIR_CAPTURE) { - stream->rec_engine = new MyOboeEngine(stream, PJMEDIA_DIR_CAPTURE); - if (!stream->rec_engine) { - status = PJ_ENOMEM; - goto on_error; - } + stream->rec_engine = new MyOboeEngine(stream, PJMEDIA_DIR_CAPTURE); + if (!stream->rec_engine) { + status = PJ_ENOMEM; + goto on_error; + } } if (stream->dir & PJMEDIA_DIR_PLAYBACK) { - stream->play_engine = new MyOboeEngine(stream, PJMEDIA_DIR_PLAYBACK); - if (!stream->play_engine) { - status = PJ_ENOMEM; - goto on_error; - } + stream->play_engine = new MyOboeEngine(stream, PJMEDIA_DIR_PLAYBACK); + if (!stream->play_engine) { + status = PJ_ENOMEM; + goto on_error; + } } /* Done */ @@ -1130,17 +1130,17 @@ static pj_status_t strm_start(pjmedia_aud_stream *s) pj_status_t status; if (stream->running) - return PJ_SUCCESS; + return PJ_SUCCESS; if (stream->rec_engine) { - status = stream->rec_engine->Start(); - if (status != PJ_SUCCESS) - goto on_error; + status = stream->rec_engine->Start(); + if (status != PJ_SUCCESS) + goto on_error; } if (stream->play_engine) { - status = stream->play_engine->Start(); - if (status != PJ_SUCCESS) - goto on_error; + status = stream->play_engine->Start(); + if (status != PJ_SUCCESS) + goto on_error; } stream->running = PJ_TRUE; @@ -1150,9 +1150,9 @@ static pj_status_t strm_start(pjmedia_aud_stream *s) on_error: if (stream->rec_engine) - stream->rec_engine->Stop(); + stream->rec_engine->Stop(); if (stream->play_engine) - stream->play_engine->Stop(); + stream->play_engine->Stop(); PJ_LOG(4, (THIS_FILE, "Failed starting Oboe stream")); @@ -1170,9 +1170,9 @@ static pj_status_t strm_stop(pjmedia_aud_stream *s) stream->running = PJ_FALSE; if (stream->rec_engine) - stream->rec_engine->Stop(); + stream->rec_engine->Stop(); if (stream->play_engine) - stream->play_engine->Stop(); + stream->play_engine->Stop(); PJ_LOG(4,(THIS_FILE, "Oboe stream stopped")); @@ -1190,12 +1190,12 @@ static pj_status_t strm_destroy(pjmedia_aud_stream *s) strm_stop(s); if (stream->rec_engine) { - delete stream->rec_engine; - stream->rec_engine = NULL; + delete stream->rec_engine; + stream->rec_engine = NULL; } if (stream->play_engine) { - delete stream->play_engine; - stream->play_engine = NULL; + delete stream->play_engine; + stream->play_engine = NULL; } pj_pool_release(stream->pool); @@ -1204,4 +1204,4 @@ static pj_status_t strm_destroy(pjmedia_aud_stream *s) return PJ_SUCCESS; } -#endif /* PJMEDIA_AUDIO_DEV_HAS_OBOE */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_OBOE */ diff --git a/pjmedia/src/pjmedia-audiodev/opensl_dev.c b/pjmedia/src/pjmedia-audiodev/opensl_dev.c index 72170afbea..16f36142ad 100644 --- a/pjmedia/src/pjmedia-audiodev/opensl_dev.c +++ b/pjmedia/src/pjmedia-audiodev/opensl_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2012-2012 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr) @@ -49,8 +48,8 @@ #define W_SL_IID_BUFFERQUEUE SL_IID_BUFFERQUEUE #endif -#define THIS_FILE "opensl_dev.c" -#define DRIVER_NAME "OpenSL" +#define THIS_FILE "opensl_dev.c" +#define DRIVER_NAME "OpenSL" #define NUM_BUFFERS 2 @@ -83,15 +82,15 @@ struct opensl_aud_stream pjmedia_aud_rec_cb rec_cb; pjmedia_aud_play_cb play_cb; - pj_timestamp play_timestamp; - pj_timestamp rec_timestamp; + pj_timestamp play_timestamp; + pj_timestamp rec_timestamp; - pj_bool_t rec_thread_initialized; - pj_thread_desc rec_thread_desc; + pj_bool_t rec_thread_initialized; + pj_thread_desc rec_thread_desc; pj_thread_t *rec_thread; - pj_bool_t play_thread_initialized; - pj_thread_desc play_thread_desc; + pj_bool_t play_thread_initialized; + pj_thread_desc play_thread_desc; pj_thread_t *play_thread; /* Player */ @@ -177,11 +176,11 @@ void bqPlayerCallback(W_SLBufferQueueItf bq, void *context) if (stream->play_thread_initialized == 0 || !pj_thread_is_registered()) { - pj_bzero(stream->play_thread_desc, sizeof(pj_thread_desc)); - status = pj_thread_register("opensl_play", stream->play_thread_desc, - &stream->play_thread); - stream->play_thread_initialized = 1; - PJ_LOG(5, (THIS_FILE, "Player thread started")); + pj_bzero(stream->play_thread_desc, sizeof(pj_thread_desc)); + status = pj_thread_register("opensl_play", stream->play_thread_desc, + &stream->play_thread); + stream->play_thread_initialized = 1; + PJ_LOG(5, (THIS_FILE, "Player thread started")); } if (!stream->quit_flag) { @@ -223,12 +222,12 @@ void bqRecorderCallback(W_SLBufferQueueItf bq, void *context) if (stream->rec_thread_initialized == 0 || !pj_thread_is_registered()) { - pj_bzero(stream->rec_thread_desc, sizeof(pj_thread_desc)); - status = pj_thread_register("opensl_rec", stream->rec_thread_desc, - &stream->rec_thread); - PJ_UNUSED_ARG(status); /* Unused for now.. */ - stream->rec_thread_initialized = 1; - PJ_LOG(5, (THIS_FILE, "Recorder thread started")); + pj_bzero(stream->rec_thread_desc, sizeof(pj_thread_desc)); + status = pj_thread_register("opensl_rec", stream->rec_thread_desc, + &stream->rec_thread); + PJ_UNUSED_ARG(status); /* Unused for now.. */ + stream->rec_thread_initialized = 1; + PJ_LOG(5, (THIS_FILE, "Recorder thread started")); } if (!stream->quit_flag) { @@ -260,23 +259,23 @@ void bqRecorderCallback(W_SLBufferQueueItf bq, void *context) pj_status_t opensl_to_pj_error(SLresult code) { switch(code) { - case SL_RESULT_SUCCESS: + case SL_RESULT_SUCCESS: return PJ_SUCCESS; - case SL_RESULT_PRECONDITIONS_VIOLATED: - case SL_RESULT_PARAMETER_INVALID: - case SL_RESULT_CONTENT_CORRUPTED: - case SL_RESULT_FEATURE_UNSUPPORTED: + case SL_RESULT_PRECONDITIONS_VIOLATED: + case SL_RESULT_PARAMETER_INVALID: + case SL_RESULT_CONTENT_CORRUPTED: + case SL_RESULT_FEATURE_UNSUPPORTED: return PJMEDIA_EAUD_INVOP; - case SL_RESULT_MEMORY_FAILURE: - case SL_RESULT_BUFFER_INSUFFICIENT: + case SL_RESULT_MEMORY_FAILURE: + case SL_RESULT_BUFFER_INSUFFICIENT: return PJ_ENOMEM; - case SL_RESULT_RESOURCE_ERROR: - case SL_RESULT_RESOURCE_LOST: - case SL_RESULT_CONTROL_LOST: + case SL_RESULT_RESOURCE_ERROR: + case SL_RESULT_RESOURCE_LOST: + case SL_RESULT_CONTROL_LOST: return PJMEDIA_EAUD_NOTREADY; - case SL_RESULT_CONTENT_UNSUPPORTED: + case SL_RESULT_CONTENT_UNSUPPORTED: return PJ_ENOTSUP; - default: + default: return PJMEDIA_EAUD_ERR; } } @@ -423,7 +422,7 @@ static pj_status_t opensl_default_param(pjmedia_aud_dev_factory *f, status = opensl_get_dev_info(f, index, &adi); if (status != PJ_SUCCESS) - return status; + return status; pj_bzero(param, sizeof(*param)); if (adi.input_count && adi.output_count) { @@ -645,12 +644,12 @@ static pj_status_t opensl_create_stream(pjmedia_aud_dev_factory *f, if (result == SL_RESULT_SUCCESS) { SLint32 streamType = SL_ANDROID_RECORDING_PRESET_GENERIC; #if __ANDROID_API__ >= 14 - streamType = SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION; + streamType = SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION; #endif #if 0 /* Android-L (android-21) removes __system_property_get * from the NDK. - */ + */ char sdk_version[PROP_VALUE_MAX]; pj_str_t pj_sdk_version; int sdk_v; @@ -718,7 +717,7 @@ static pj_status_t opensl_create_stream(pjmedia_aud_dev_factory *f, } if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { - strm_set_cap(&stream->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + strm_set_cap(&stream->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, ¶m->output_vol); } @@ -760,7 +759,7 @@ static pj_status_t strm_get_cap(pjmedia_aud_stream *s, PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING && - (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) + (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) { if (strm->playerVol) { SLresult res; @@ -793,7 +792,7 @@ static pj_status_t strm_set_cap(pjmedia_aud_stream *s, PJ_ASSERT_RETURN(s && value, PJ_EINVAL); if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING && - (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) + (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) { if (strm->playerVol) { SLresult res; @@ -952,4 +951,4 @@ static pj_status_t strm_destroy(pjmedia_aud_stream *s) return PJ_SUCCESS; } -#endif /* PJMEDIA_AUDIO_DEV_HAS_OPENSL */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_OPENSL */ diff --git a/pjmedia/src/pjmedia-audiodev/pa_dev.c b/pjmedia/src/pjmedia-audiodev/pa_dev.c index bfaa5b5d91..b8239996d6 100644 --- a/pjmedia/src/pjmedia-audiodev/pa_dev.c +++ b/pjmedia/src/pjmedia-audiodev/pa_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,8 +26,8 @@ #include -#define THIS_FILE "pa_dev.c" -#define DRIVER_NAME "PA" +#define THIS_FILE "pa_dev.c" +#define DRIVER_NAME "PA" /* Enable call to PaUtil_SetDebugPrintFunction, but this is not always * available across all PortAudio versions (?) @@ -37,9 +36,9 @@ struct pa_aud_factory { - pjmedia_aud_dev_factory base; - pj_pool_factory *pf; - pj_pool_t *pool; + pjmedia_aud_dev_factory base; + pj_pool_factory *pf; + pj_pool_t *pool; }; @@ -50,56 +49,56 @@ struct pa_aud_factory */ struct pa_aud_stream { - pjmedia_aud_stream base; - - pj_pool_t *pool; - pj_str_t name; - pjmedia_dir dir; - int play_id; - int rec_id; - int bytes_per_sample; - pj_uint32_t samples_per_sec; - unsigned samples_per_frame; - int channel_count; - - PaStream *rec_strm; - PaStream *play_strm; - - void *user_data; + pjmedia_aud_stream base; + + pj_pool_t *pool; + pj_str_t name; + pjmedia_dir dir; + int play_id; + int rec_id; + int bytes_per_sample; + pj_uint32_t samples_per_sec; + unsigned samples_per_frame; + int channel_count; + + PaStream *rec_strm; + PaStream *play_strm; + + void *user_data; pjmedia_aud_rec_cb rec_cb; pjmedia_aud_play_cb play_cb; - pj_timestamp play_timestamp; - pj_timestamp rec_timestamp; - pj_uint32_t underflow; - pj_uint32_t overflow; + pj_timestamp play_timestamp; + pj_timestamp rec_timestamp; + pj_uint32_t underflow; + pj_uint32_t overflow; - pj_bool_t quit_flag; + pj_bool_t quit_flag; - pj_bool_t rec_thread_exited; - pj_bool_t rec_thread_initialized; - pj_thread_desc rec_thread_desc; - pj_thread_t *rec_thread; + pj_bool_t rec_thread_exited; + pj_bool_t rec_thread_initialized; + pj_thread_desc rec_thread_desc; + pj_thread_t *rec_thread; - pj_bool_t play_thread_exited; - pj_bool_t play_thread_initialized; - pj_thread_desc play_thread_desc; - pj_thread_t *play_thread; + pj_bool_t play_thread_exited; + pj_bool_t play_thread_initialized; + pj_thread_desc play_thread_desc; + pj_thread_t *play_thread; /* Sometime the record callback does not return framesize as configured * (e.g: in OSS), while this module must guarantee returning framesize * as configured in the creation settings. In this case, we need a buffer * for the recorded samples. */ - pj_int16_t *rec_buf; - unsigned rec_buf_count; + pj_int16_t *rec_buf; + unsigned rec_buf_count; /* Sometime the player callback does not request framesize as configured * (e.g: in Linux OSS) while sound device will always get samples from * the other component as many as configured samples_per_frame. */ - pj_int16_t *play_buf; - unsigned play_buf_count; + pj_int16_t *play_buf; + unsigned play_buf_count; }; @@ -107,29 +106,29 @@ struct pa_aud_stream static pj_status_t pa_init(pjmedia_aud_dev_factory *f); static pj_status_t pa_destroy(pjmedia_aud_dev_factory *f); static pj_status_t pa_refresh(pjmedia_aud_dev_factory *f); -static unsigned pa_get_dev_count(pjmedia_aud_dev_factory *f); +static unsigned pa_get_dev_count(pjmedia_aud_dev_factory *f); static pj_status_t pa_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); + unsigned index, + pjmedia_aud_dev_info *info); static pj_status_t pa_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); + unsigned index, + pjmedia_aud_param *param); static pj_status_t pa_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); /* Stream prototypes */ static pj_status_t strm_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); + pjmedia_aud_param *param); static pj_status_t strm_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); + pjmedia_aud_dev_cap cap, + void *value); static pj_status_t strm_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); + pjmedia_aud_dev_cap cap, + const void *value); static pj_status_t strm_start(pjmedia_aud_stream *strm); static pj_status_t strm_stop(pjmedia_aud_stream *strm); static pj_status_t strm_destroy(pjmedia_aud_stream *strm); @@ -159,11 +158,11 @@ static pjmedia_aud_stream_op pa_strm_op = static int PaRecorderCallback(const void *input, - void *output, - unsigned long frameCount, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ) + void *output, + unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { struct pa_aud_stream *stream = (struct pa_aud_stream*) userData; pj_status_t status = 0; @@ -173,10 +172,10 @@ static int PaRecorderCallback(const void *input, PJ_UNUSED_ARG(timeInfo); if (stream->quit_flag) - goto on_break; + goto on_break; if (input == NULL) - return paContinue; + return paContinue; /* Known cases of callback's thread: * - The thread may be changed in the middle of a session, e.g: in MacOS @@ -187,84 +186,84 @@ static int PaRecorderCallback(const void *input, */ if (stream->rec_thread_initialized == 0 || !pj_thread_is_registered()) { - pj_bzero(stream->rec_thread_desc, sizeof(pj_thread_desc)); - status = pj_thread_register("pa_rec", stream->rec_thread_desc, - &stream->rec_thread); - stream->rec_thread_initialized = 1; - PJ_LOG(5,(THIS_FILE, "Recorder thread started")); + pj_bzero(stream->rec_thread_desc, sizeof(pj_thread_desc)); + status = pj_thread_register("pa_rec", stream->rec_thread_desc, + &stream->rec_thread); + stream->rec_thread_initialized = 1; + PJ_LOG(5,(THIS_FILE, "Recorder thread started")); } if (statusFlags & paInputUnderflow) - ++stream->underflow; + ++stream->underflow; if (statusFlags & paInputOverflow) - ++stream->overflow; + ++stream->overflow; /* Calculate number of samples we've got */ nsamples = frameCount * stream->channel_count + stream->rec_buf_count; if (nsamples >= stream->samples_per_frame) { - /* If buffer is not empty, combine the buffer with the just incoming - * samples, then call put_frame. - */ - if (stream->rec_buf_count) { - unsigned chunk_count = 0; - pjmedia_frame frame; - - chunk_count = stream->samples_per_frame - stream->rec_buf_count; - pjmedia_copy_samples(stream->rec_buf + stream->rec_buf_count, - (pj_int16_t*)input, chunk_count); - - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = (void*) stream->rec_buf; - frame.size = stream->samples_per_frame * stream->bytes_per_sample; - frame.timestamp.u64 = stream->rec_timestamp.u64; - frame.bit_info = 0; - - status = (*stream->rec_cb)(stream->user_data, &frame); - - input = (pj_int16_t*) input + chunk_count; - nsamples -= stream->samples_per_frame; - stream->rec_buf_count = 0; - stream->rec_timestamp.u64 += stream->samples_per_frame / - stream->channel_count; - } - - /* Give all frames we have */ - while (nsamples >= stream->samples_per_frame && status == 0) { - pjmedia_frame frame; - - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = (void*) input; - frame.size = stream->samples_per_frame * stream->bytes_per_sample; - frame.timestamp.u64 = stream->rec_timestamp.u64; - frame.bit_info = 0; - - status = (*stream->rec_cb)(stream->user_data, &frame); - - input = (pj_int16_t*) input + stream->samples_per_frame; - nsamples -= stream->samples_per_frame; - stream->rec_timestamp.u64 += stream->samples_per_frame / - stream->channel_count; - } - - /* Store the remaining samples into the buffer */ - if (nsamples && status == 0) { - stream->rec_buf_count = nsamples; - pjmedia_copy_samples(stream->rec_buf, (pj_int16_t*)input, - nsamples); - } + /* If buffer is not empty, combine the buffer with the just incoming + * samples, then call put_frame. + */ + if (stream->rec_buf_count) { + unsigned chunk_count = 0; + pjmedia_frame frame; + + chunk_count = stream->samples_per_frame - stream->rec_buf_count; + pjmedia_copy_samples(stream->rec_buf + stream->rec_buf_count, + (pj_int16_t*)input, chunk_count); + + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = (void*) stream->rec_buf; + frame.size = stream->samples_per_frame * stream->bytes_per_sample; + frame.timestamp.u64 = stream->rec_timestamp.u64; + frame.bit_info = 0; + + status = (*stream->rec_cb)(stream->user_data, &frame); + + input = (pj_int16_t*) input + chunk_count; + nsamples -= stream->samples_per_frame; + stream->rec_buf_count = 0; + stream->rec_timestamp.u64 += stream->samples_per_frame / + stream->channel_count; + } + + /* Give all frames we have */ + while (nsamples >= stream->samples_per_frame && status == 0) { + pjmedia_frame frame; + + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = (void*) input; + frame.size = stream->samples_per_frame * stream->bytes_per_sample; + frame.timestamp.u64 = stream->rec_timestamp.u64; + frame.bit_info = 0; + + status = (*stream->rec_cb)(stream->user_data, &frame); + + input = (pj_int16_t*) input + stream->samples_per_frame; + nsamples -= stream->samples_per_frame; + stream->rec_timestamp.u64 += stream->samples_per_frame / + stream->channel_count; + } + + /* Store the remaining samples into the buffer */ + if (nsamples && status == 0) { + stream->rec_buf_count = nsamples; + pjmedia_copy_samples(stream->rec_buf, (pj_int16_t*)input, + nsamples); + } } else { - /* Not enough samples, let's just store them in the buffer */ - pjmedia_copy_samples(stream->rec_buf + stream->rec_buf_count, - (pj_int16_t*)input, - frameCount * stream->channel_count); - stream->rec_buf_count += frameCount * stream->channel_count; + /* Not enough samples, let's just store them in the buffer */ + pjmedia_copy_samples(stream->rec_buf + stream->rec_buf_count, + (pj_int16_t*)input, + frameCount * stream->channel_count); + stream->rec_buf_count += frameCount * stream->channel_count; } if (status==0) - return paContinue; + return paContinue; on_break: stream->rec_thread_exited = 1; @@ -272,11 +271,11 @@ static int PaRecorderCallback(const void *input, } static int PaPlayerCallback( const void *input, - void *output, - unsigned long frameCount, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ) + void *output, + unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { struct pa_aud_stream *stream = (struct pa_aud_stream*) userData; pj_status_t status = 0; @@ -286,10 +285,10 @@ static int PaPlayerCallback( const void *input, PJ_UNUSED_ARG(timeInfo); if (stream->quit_flag) - goto on_break; + goto on_break; if (output == NULL) - return paContinue; + return paContinue; /* Known cases of callback's thread: * - The thread may be changed in the middle of a session, e.g: in MacOS @@ -300,93 +299,93 @@ static int PaPlayerCallback( const void *input, */ if (stream->play_thread_initialized == 0 || !pj_thread_is_registered()) { - pj_bzero(stream->play_thread_desc, sizeof(pj_thread_desc)); - status = pj_thread_register("portaudio", stream->play_thread_desc, - &stream->play_thread); - stream->play_thread_initialized = 1; - PJ_LOG(5,(THIS_FILE, "Player thread started")); + pj_bzero(stream->play_thread_desc, sizeof(pj_thread_desc)); + status = pj_thread_register("portaudio", stream->play_thread_desc, + &stream->play_thread); + stream->play_thread_initialized = 1; + PJ_LOG(5,(THIS_FILE, "Player thread started")); } if (statusFlags & paOutputUnderflow) - ++stream->underflow; + ++stream->underflow; if (statusFlags & paOutputOverflow) - ++stream->overflow; + ++stream->overflow; /* Check if any buffered samples */ if (stream->play_buf_count) { - /* samples buffered >= requested by sound device */ - if (stream->play_buf_count >= nsamples_req) { - pjmedia_copy_samples((pj_int16_t*)output, stream->play_buf, - nsamples_req); - stream->play_buf_count -= nsamples_req; - pjmedia_move_samples(stream->play_buf, - stream->play_buf + nsamples_req, - stream->play_buf_count); - nsamples_req = 0; - - return paContinue; - } - - /* samples buffered < requested by sound device */ - pjmedia_copy_samples((pj_int16_t*)output, stream->play_buf, - stream->play_buf_count); - nsamples_req -= stream->play_buf_count; - output = (pj_int16_t*)output + stream->play_buf_count; - stream->play_buf_count = 0; + /* samples buffered >= requested by sound device */ + if (stream->play_buf_count >= nsamples_req) { + pjmedia_copy_samples((pj_int16_t*)output, stream->play_buf, + nsamples_req); + stream->play_buf_count -= nsamples_req; + pjmedia_move_samples(stream->play_buf, + stream->play_buf + nsamples_req, + stream->play_buf_count); + nsamples_req = 0; + + return paContinue; + } + + /* samples buffered < requested by sound device */ + pjmedia_copy_samples((pj_int16_t*)output, stream->play_buf, + stream->play_buf_count); + nsamples_req -= stream->play_buf_count; + output = (pj_int16_t*)output + stream->play_buf_count; + stream->play_buf_count = 0; } /* Fill output buffer as requested */ while (nsamples_req && status == 0) { - if (nsamples_req >= stream->samples_per_frame) { - pjmedia_frame frame; - - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = output; - frame.size = stream->samples_per_frame * stream->bytes_per_sample; - frame.timestamp.u64 = stream->play_timestamp.u64; - frame.bit_info = 0; - - status = (*stream->play_cb)(stream->user_data, &frame); - if (status != PJ_SUCCESS) - goto on_break; - - if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) - pj_bzero(frame.buf, frame.size); - - nsamples_req -= stream->samples_per_frame; - output = (pj_int16_t*)output + stream->samples_per_frame; - } else { - pjmedia_frame frame; - - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = stream->play_buf; - frame.size = stream->samples_per_frame * stream->bytes_per_sample; - frame.timestamp.u64 = stream->play_timestamp.u64; - frame.bit_info = 0; - - status = (*stream->play_cb)(stream->user_data, &frame); - if (status != PJ_SUCCESS) - goto on_break; - - if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) - pj_bzero(frame.buf, frame.size); - - pjmedia_copy_samples((pj_int16_t*)output, stream->play_buf, - nsamples_req); - stream->play_buf_count = stream->samples_per_frame - nsamples_req; - pjmedia_move_samples(stream->play_buf, - stream->play_buf+nsamples_req, - stream->play_buf_count); - nsamples_req = 0; - } - - stream->play_timestamp.u64 += stream->samples_per_frame / - stream->channel_count; + if (nsamples_req >= stream->samples_per_frame) { + pjmedia_frame frame; + + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = output; + frame.size = stream->samples_per_frame * stream->bytes_per_sample; + frame.timestamp.u64 = stream->play_timestamp.u64; + frame.bit_info = 0; + + status = (*stream->play_cb)(stream->user_data, &frame); + if (status != PJ_SUCCESS) + goto on_break; + + if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) + pj_bzero(frame.buf, frame.size); + + nsamples_req -= stream->samples_per_frame; + output = (pj_int16_t*)output + stream->samples_per_frame; + } else { + pjmedia_frame frame; + + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = stream->play_buf; + frame.size = stream->samples_per_frame * stream->bytes_per_sample; + frame.timestamp.u64 = stream->play_timestamp.u64; + frame.bit_info = 0; + + status = (*stream->play_cb)(stream->user_data, &frame); + if (status != PJ_SUCCESS) + goto on_break; + + if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) + pj_bzero(frame.buf, frame.size); + + pjmedia_copy_samples((pj_int16_t*)output, stream->play_buf, + nsamples_req); + stream->play_buf_count = stream->samples_per_frame - nsamples_req; + pjmedia_move_samples(stream->play_buf, + stream->play_buf+nsamples_req, + stream->play_buf_count); + nsamples_req = 0; + } + + stream->play_timestamp.u64 += stream->samples_per_frame / + stream->channel_count; } if (status==0) - return paContinue; + return paContinue; on_break: stream->play_thread_exited = 1; @@ -395,21 +394,21 @@ static int PaPlayerCallback( const void *input, static int PaRecorderPlayerCallback( const void *input, - void *output, - unsigned long frameCount, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ) + void *output, + unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { int rc; rc = PaRecorderCallback(input, output, frameCount, timeInfo, - statusFlags, userData); + statusFlags, userData); if (rc != paContinue) - return rc; + return rc; rc = PaPlayerCallback(input, output, frameCount, timeInfo, - statusFlags, userData); + statusFlags, userData); return rc; } @@ -460,11 +459,11 @@ static pj_status_t pa_init(pjmedia_aud_dev_factory *f) err = Pa_Initialize(); PJ_LOG(4,(THIS_FILE, - "PortAudio sound library initialized, status=%d", err)); + "PortAudio sound library initialized, status=%d", err)); PJ_LOG(4,(THIS_FILE, "PortAudio host api count=%d", - Pa_GetHostApiCount())); + Pa_GetHostApiCount())); PJ_LOG(4,(THIS_FILE, "Sound device count=%d", - pa_get_dev_count(f))); + pa_get_dev_count(f))); return err ? PJMEDIA_AUDIODEV_ERRNO_FROM_PORTAUDIO(err) : PJ_SUCCESS; } @@ -498,7 +497,7 @@ static pj_status_t pa_refresh(pjmedia_aud_dev_factory *f) /* API: Get device count. */ -static unsigned pa_get_dev_count(pjmedia_aud_dev_factory *f) +static unsigned pa_get_dev_count(pjmedia_aud_dev_factory *f) { int count = Pa_GetDeviceCount(); PJ_UNUSED_ARG(f); @@ -508,8 +507,8 @@ static unsigned pa_get_dev_count(pjmedia_aud_dev_factory *f) /* API: Get device info. */ static pj_status_t pa_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info) + unsigned index, + pjmedia_aud_dev_info *info) { const PaDeviceInfo *pa_info; @@ -517,7 +516,7 @@ static pj_status_t pa_get_dev_info(pjmedia_aud_dev_factory *f, pa_info = Pa_GetDeviceInfo(index); if (!pa_info) - return PJMEDIA_EAUD_INVDEV; + return PJMEDIA_EAUD_INVDEV; pj_bzero(info, sizeof(*info)); strncpy(info->name, pa_info->name, sizeof(info->name)); @@ -528,7 +527,7 @@ static pj_status_t pa_get_dev_info(pjmedia_aud_dev_factory *f, strncpy(info->driver, DRIVER_NAME, sizeof(info->driver)); info->driver[sizeof(info->driver)-1] = '\0'; info->caps = PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; + PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; return PJ_SUCCESS; } @@ -536,8 +535,8 @@ static pj_status_t pa_get_dev_info(pjmedia_aud_dev_factory *f, /* API: fill in with default parameter. */ static pj_status_t pa_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param) + unsigned index, + pjmedia_aud_param *param) { pjmedia_aud_dev_info adi; pj_status_t status; @@ -546,23 +545,23 @@ static pj_status_t pa_default_param(pjmedia_aud_dev_factory *f, status = pa_get_dev_info(f, index, &adi); if (status != PJ_SUCCESS) - return status; + return status; pj_bzero(param, sizeof(*param)); if (adi.input_count && adi.output_count) { - param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; - param->rec_id = index; - param->play_id = index; + param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; + param->rec_id = index; + param->play_id = index; } else if (adi.input_count) { - param->dir = PJMEDIA_DIR_CAPTURE; - param->rec_id = index; - param->play_id = PJMEDIA_AUD_INVALID_DEV; + param->dir = PJMEDIA_DIR_CAPTURE; + param->rec_id = index; + param->play_id = PJMEDIA_AUD_INVALID_DEV; } else if (adi.output_count) { - param->dir = PJMEDIA_DIR_PLAYBACK; - param->play_id = index; - param->rec_id = PJMEDIA_AUD_INVALID_DEV; + param->dir = PJMEDIA_DIR_PLAYBACK; + param->play_id = index; + param->rec_id = PJMEDIA_AUD_INVALID_DEV; } else { - return PJMEDIA_EAUD_INVDEV; + return PJMEDIA_EAUD_INVDEV; } param->clock_rate = adi.default_samples_per_sec; @@ -587,15 +586,15 @@ static int pa_get_default_input_dev(int channel_count) */ #if PJMEDIA_PREFER_DIRECT_SOUND if (Pa_HostApiTypeIdToHostApiIndex(paDirectSound) >= 0) { - const PaHostApiInfo *pHI; - int index = Pa_HostApiTypeIdToHostApiIndex(paDirectSound); - pHI = Pa_GetHostApiInfo(index); - if (pHI) { - const PaDeviceInfo *paDevInfo = NULL; - paDevInfo = Pa_GetDeviceInfo(pHI->defaultInputDevice); - if (paDevInfo && paDevInfo->maxInputChannels >= channel_count) - return pHI->defaultInputDevice; - } + const PaHostApiInfo *pHI; + int index = Pa_HostApiTypeIdToHostApiIndex(paDirectSound); + pHI = Pa_GetHostApiInfo(index); + if (pHI) { + const PaDeviceInfo *paDevInfo = NULL; + paDevInfo = Pa_GetDeviceInfo(pHI->defaultInputDevice); + if (paDevInfo && paDevInfo->maxInputChannels >= channel_count) + return pHI->defaultInputDevice; + } } #endif @@ -604,30 +603,30 @@ static int pa_get_default_input_dev(int channel_count) */ count = Pa_GetHostApiCount(); for (i=0; i < count; ++i) { - const PaHostApiInfo *pHAInfo; + const PaHostApiInfo *pHAInfo; - pHAInfo = Pa_GetHostApiInfo(i); - if (!pHAInfo) - continue; + pHAInfo = Pa_GetHostApiInfo(i); + if (!pHAInfo) + continue; - if (pHAInfo->defaultInputDevice >= 0) { - const PaDeviceInfo *paDevInfo; + if (pHAInfo->defaultInputDevice >= 0) { + const PaDeviceInfo *paDevInfo; - paDevInfo = Pa_GetDeviceInfo(pHAInfo->defaultInputDevice); + paDevInfo = Pa_GetDeviceInfo(pHAInfo->defaultInputDevice); - if (paDevInfo->maxInputChannels >= channel_count) - return pHAInfo->defaultInputDevice; - } + if (paDevInfo->maxInputChannels >= channel_count) + return pHAInfo->defaultInputDevice; + } } /* If still no device is found, enumerate all devices */ count = Pa_GetDeviceCount(); for (i=0; imaxInputChannels >= channel_count) - return i; + paDevInfo = Pa_GetDeviceInfo(i); + if (paDevInfo->maxInputChannels >= channel_count) + return i; } return -1; @@ -643,15 +642,15 @@ static int pa_get_default_output_dev(int channel_count) */ #if PJMEDIA_PREFER_DIRECT_SOUND if (Pa_HostApiTypeIdToHostApiIndex(paDirectSound) >= 0) { - const PaHostApiInfo *pHI; - int index = Pa_HostApiTypeIdToHostApiIndex(paDirectSound); - pHI = Pa_GetHostApiInfo(index); - if (pHI) { - const PaDeviceInfo *paDevInfo = NULL; - paDevInfo = Pa_GetDeviceInfo(pHI->defaultOutputDevice); - if (paDevInfo && paDevInfo->maxOutputChannels >= channel_count) - return pHI->defaultOutputDevice; - } + const PaHostApiInfo *pHI; + int index = Pa_HostApiTypeIdToHostApiIndex(paDirectSound); + pHI = Pa_GetHostApiInfo(index); + if (pHI) { + const PaDeviceInfo *paDevInfo = NULL; + paDevInfo = Pa_GetDeviceInfo(pHI->defaultOutputDevice); + if (paDevInfo && paDevInfo->maxOutputChannels >= channel_count) + return pHI->defaultOutputDevice; + } } #endif @@ -660,30 +659,30 @@ static int pa_get_default_output_dev(int channel_count) */ count = Pa_GetHostApiCount(); for (i=0; i < count; ++i) { - const PaHostApiInfo *pHAInfo; + const PaHostApiInfo *pHAInfo; - pHAInfo = Pa_GetHostApiInfo(i); - if (!pHAInfo) - continue; + pHAInfo = Pa_GetHostApiInfo(i); + if (!pHAInfo) + continue; - if (pHAInfo->defaultOutputDevice >= 0) { - const PaDeviceInfo *paDevInfo; + if (pHAInfo->defaultOutputDevice >= 0) { + const PaDeviceInfo *paDevInfo; - paDevInfo = Pa_GetDeviceInfo(pHAInfo->defaultOutputDevice); + paDevInfo = Pa_GetDeviceInfo(pHAInfo->defaultOutputDevice); - if (paDevInfo->maxOutputChannels >= channel_count) - return pHAInfo->defaultOutputDevice; - } + if (paDevInfo->maxOutputChannels >= channel_count) + return pHAInfo->defaultOutputDevice; + } } /* If still no device is found, enumerate all devices */ count = Pa_GetDeviceCount(); for (i=0; imaxOutputChannels >= channel_count) - return i; + paDevInfo = Pa_GetDeviceInfo(i); + if (paDevInfo->maxOutputChannels >= channel_count) + return i; } return -1; @@ -692,10 +691,10 @@ static int pa_get_default_output_dev(int channel_count) /* Internal: create capture/recorder stream */ static pj_status_t create_rec_stream( struct pa_aud_factory *pa, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - void *user_data, - pjmedia_aud_stream **p_snd_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + void *user_data, + pjmedia_aud_stream **p_snd_strm) { pj_pool_t *pool; pjmedia_aud_dev_index rec_id; @@ -712,31 +711,31 @@ static pj_status_t create_rec_stream( struct pa_aud_factory *pa, rec_id = param->rec_id; if (rec_id < 0) { - rec_id = pa_get_default_input_dev(param->channel_count); - if (rec_id < 0) { - /* No such device. */ - return PJMEDIA_EAUD_NODEFDEV; - } + rec_id = pa_get_default_input_dev(param->channel_count); + if (rec_id < 0) { + /* No such device. */ + return PJMEDIA_EAUD_NODEFDEV; + } } paDevInfo = Pa_GetDeviceInfo(rec_id); if (!paDevInfo) { - /* Assumed it is "No such device" error. */ - return PJMEDIA_EAUD_INVDEV; + /* Assumed it is "No such device" error. */ + return PJMEDIA_EAUD_INVDEV; } if (param->bits_per_sample == 8) - sampleFormat = paUInt8; + sampleFormat = paUInt8; else if (param->bits_per_sample == 16) - sampleFormat = paInt16; + sampleFormat = paInt16; else if (param->bits_per_sample == 32) - sampleFormat = paInt32; + sampleFormat = paInt32; else - return PJMEDIA_EAUD_SAMPFORMAT; + return PJMEDIA_EAUD_SAMPFORMAT; pool = pj_pool_create(pa->pf, "recstrm", 1024, 1024, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; stream = PJ_POOL_ZALLOC_T(pool, struct pa_aud_stream); stream->pool = pool; @@ -752,7 +751,7 @@ static pj_status_t create_rec_stream( struct pa_aud_factory *pa, stream->rec_cb = rec_cb; stream->rec_buf = (pj_int16_t*)pj_pool_alloc(pool, - stream->samples_per_frame * stream->bytes_per_sample); + stream->samples_per_frame * stream->bytes_per_sample); stream->rec_buf_count = 0; pj_bzero(&inputParam, sizeof(inputParam)); @@ -761,9 +760,9 @@ static pj_status_t create_rec_stream( struct pa_aud_factory *pa, inputParam.hostApiSpecificStreamInfo = NULL; inputParam.sampleFormat = sampleFormat; if (param->flags & PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY) - inputParam.suggestedLatency = param->input_latency_ms / 1000.0; + inputParam.suggestedLatency = param->input_latency_ms / 1000.0; else - inputParam.suggestedLatency = PJMEDIA_SND_DEFAULT_REC_LATENCY / 1000.0; + inputParam.suggestedLatency = PJMEDIA_SND_DEFAULT_REC_LATENCY / 1000.0; paHostApiInfo = Pa_GetHostApiInfo(paDevInfo->hostApi); @@ -771,11 +770,11 @@ static pj_status_t create_rec_stream( struct pa_aud_factory *pa, paFrames = param->samples_per_frame / param->channel_count; err = Pa_OpenStream( &stream->rec_strm, &inputParam, NULL, - param->clock_rate, paFrames, - paClipOff, &PaRecorderCallback, stream ); + param->clock_rate, paFrames, + paClipOff, &PaRecorderCallback, stream ); if (err != paNoError) { - pj_pool_release(pool); - return PJMEDIA_AUDIODEV_ERRNO_FROM_PORTAUDIO(err); + pj_pool_release(pool); + return PJMEDIA_AUDIODEV_ERRNO_FROM_PORTAUDIO(err); } paSI = Pa_GetStreamInfo(stream->rec_strm); @@ -783,12 +782,12 @@ static pj_status_t create_rec_stream( struct pa_aud_factory *pa, paLatency = (unsigned)(paSI->inputLatency * 1000); PJ_LOG(5,(THIS_FILE, "Opened device %s (%s) for recording, sample " - "rate=%d, ch=%d, " - "bits=%d, %d samples per frame, latency=%d ms", - paDevInfo->name, paHostApiInfo->name, - paRate, param->channel_count, - param->bits_per_sample, param->samples_per_frame, - paLatency)); + "rate=%d, ch=%d, " + "bits=%d, %d samples per frame, latency=%d ms", + paDevInfo->name, paHostApiInfo->name, + paRate, param->channel_count, + param->bits_per_sample, param->samples_per_frame, + paLatency)); *p_snd_strm = &stream->base; return PJ_SUCCESS; @@ -797,10 +796,10 @@ static pj_status_t create_rec_stream( struct pa_aud_factory *pa, /* Internal: create playback stream */ static pj_status_t create_play_stream(struct pa_aud_factory *pa, - const pjmedia_aud_param *param, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_snd_strm) + const pjmedia_aud_param *param, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_snd_strm) { pj_pool_t *pool; pjmedia_aud_dev_index play_id; @@ -817,31 +816,31 @@ static pj_status_t create_play_stream(struct pa_aud_factory *pa, play_id = param->play_id; if (play_id < 0) { - play_id = pa_get_default_output_dev(param->channel_count); - if (play_id < 0) { - /* No such device. */ - return PJMEDIA_EAUD_NODEFDEV; - } + play_id = pa_get_default_output_dev(param->channel_count); + if (play_id < 0) { + /* No such device. */ + return PJMEDIA_EAUD_NODEFDEV; + } } paDevInfo = Pa_GetDeviceInfo(play_id); if (!paDevInfo) { - /* Assumed it is "No such device" error. */ - return PJMEDIA_EAUD_INVDEV; + /* Assumed it is "No such device" error. */ + return PJMEDIA_EAUD_INVDEV; } if (param->bits_per_sample == 8) - sampleFormat = paUInt8; + sampleFormat = paUInt8; else if (param->bits_per_sample == 16) - sampleFormat = paInt16; + sampleFormat = paInt16; else if (param->bits_per_sample == 32) - sampleFormat = paInt32; + sampleFormat = paInt32; else - return PJMEDIA_EAUD_SAMPFORMAT; + return PJMEDIA_EAUD_SAMPFORMAT; pool = pj_pool_create(pa->pf, "playstrm", 1024, 1024, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; stream = PJ_POOL_ZALLOC_T(pool, struct pa_aud_stream); stream->pool = pool; @@ -857,8 +856,8 @@ static pj_status_t create_play_stream(struct pa_aud_factory *pa, stream->play_cb = play_cb; stream->play_buf = (pj_int16_t*)pj_pool_alloc(pool, - stream->samples_per_frame * - stream->bytes_per_sample); + stream->samples_per_frame * + stream->bytes_per_sample); stream->play_buf_count = 0; pj_bzero(&outputParam, sizeof(outputParam)); @@ -867,9 +866,9 @@ static pj_status_t create_play_stream(struct pa_aud_factory *pa, outputParam.hostApiSpecificStreamInfo = NULL; outputParam.sampleFormat = sampleFormat; if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY) - outputParam.suggestedLatency=param->output_latency_ms / 1000.0; + outputParam.suggestedLatency=param->output_latency_ms / 1000.0; else - outputParam.suggestedLatency=PJMEDIA_SND_DEFAULT_PLAY_LATENCY/1000.0; + outputParam.suggestedLatency=PJMEDIA_SND_DEFAULT_PLAY_LATENCY/1000.0; paHostApiInfo = Pa_GetHostApiInfo(paDevInfo->hostApi); @@ -877,11 +876,11 @@ static pj_status_t create_play_stream(struct pa_aud_factory *pa, paFrames = param->samples_per_frame / param->channel_count; err = Pa_OpenStream( &stream->play_strm, NULL, &outputParam, - param->clock_rate, paFrames, - paClipOff, &PaPlayerCallback, stream ); + param->clock_rate, paFrames, + paClipOff, &PaPlayerCallback, stream ); if (err != paNoError) { - pj_pool_release(pool); - return PJMEDIA_AUDIODEV_ERRNO_FROM_PORTAUDIO(err); + pj_pool_release(pool); + return PJMEDIA_AUDIODEV_ERRNO_FROM_PORTAUDIO(err); } paSI = Pa_GetStreamInfo(stream->play_strm); @@ -889,12 +888,12 @@ static pj_status_t create_play_stream(struct pa_aud_factory *pa, paLatency = (unsigned)(paSI->outputLatency * 1000); PJ_LOG(5,(THIS_FILE, "Opened device %d: %s(%s) for playing, sample rate=%d" - ", ch=%d, " - "bits=%d, %d samples per frame, latency=%d ms", - play_id, paDevInfo->name, paHostApiInfo->name, - paRate, param->channel_count, - param->bits_per_sample, param->samples_per_frame, - paLatency)); + ", ch=%d, " + "bits=%d, %d samples per frame, latency=%d ms", + play_id, paDevInfo->name, paHostApiInfo->name, + paRate, param->channel_count, + param->bits_per_sample, param->samples_per_frame, + paLatency)); *p_snd_strm = &stream->base; @@ -904,11 +903,11 @@ static pj_status_t create_play_stream(struct pa_aud_factory *pa, /* Internal: Create both player and recorder stream */ static pj_status_t create_bidir_stream(struct pa_aud_factory *pa, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_snd_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_snd_strm) { pj_pool_t *pool; pjmedia_aud_dev_index rec_id, play_id; @@ -929,47 +928,47 @@ static pj_status_t create_bidir_stream(struct pa_aud_factory *pa, rec_id = param->rec_id; if (rec_id < 0) { - rec_id = pa_get_default_input_dev(param->channel_count); - if (rec_id < 0) { - /* No such device. */ - return PJMEDIA_EAUD_NODEFDEV; - } + rec_id = pa_get_default_input_dev(param->channel_count); + if (rec_id < 0) { + /* No such device. */ + return PJMEDIA_EAUD_NODEFDEV; + } } paRecDevInfo = Pa_GetDeviceInfo(rec_id); if (!paRecDevInfo) { - /* Assumed it is "No such device" error. */ - return PJMEDIA_EAUD_INVDEV; + /* Assumed it is "No such device" error. */ + return PJMEDIA_EAUD_INVDEV; } play_id = param->play_id; if (play_id < 0) { - play_id = pa_get_default_output_dev(param->channel_count); - if (play_id < 0) { - /* No such device. */ - return PJMEDIA_EAUD_NODEFDEV; - } + play_id = pa_get_default_output_dev(param->channel_count); + if (play_id < 0) { + /* No such device. */ + return PJMEDIA_EAUD_NODEFDEV; + } } paPlayDevInfo = Pa_GetDeviceInfo(play_id); if (!paPlayDevInfo) { - /* Assumed it is "No such device" error. */ - return PJMEDIA_EAUD_INVDEV; + /* Assumed it is "No such device" error. */ + return PJMEDIA_EAUD_INVDEV; } if (param->bits_per_sample == 8) - sampleFormat = paUInt8; + sampleFormat = paUInt8; else if (param->bits_per_sample == 16) - sampleFormat = paInt16; + sampleFormat = paInt16; else if (param->bits_per_sample == 32) - sampleFormat = paInt32; + sampleFormat = paInt32; else - return PJMEDIA_EAUD_SAMPFORMAT; + return PJMEDIA_EAUD_SAMPFORMAT; pool = pj_pool_create(pa->pf, "sndstream", 1024, 1024, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; stream = PJ_POOL_ZALLOC_T(pool, struct pa_aud_stream); stream->pool = pool; @@ -986,11 +985,11 @@ static pj_status_t create_bidir_stream(struct pa_aud_factory *pa, stream->play_cb = play_cb; stream->rec_buf = (pj_int16_t*)pj_pool_alloc(pool, - stream->samples_per_frame * stream->bytes_per_sample); + stream->samples_per_frame * stream->bytes_per_sample); stream->rec_buf_count = 0; stream->play_buf = (pj_int16_t*)pj_pool_alloc(pool, - stream->samples_per_frame * stream->bytes_per_sample); + stream->samples_per_frame * stream->bytes_per_sample); stream->play_buf_count = 0; pj_bzero(&inputParam, sizeof(inputParam)); @@ -999,9 +998,9 @@ static pj_status_t create_bidir_stream(struct pa_aud_factory *pa, inputParam.hostApiSpecificStreamInfo = NULL; inputParam.sampleFormat = sampleFormat; if (param->flags & PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY) - inputParam.suggestedLatency = param->input_latency_ms / 1000.0; + inputParam.suggestedLatency = param->input_latency_ms / 1000.0; else - inputParam.suggestedLatency = PJMEDIA_SND_DEFAULT_REC_LATENCY / 1000.0; + inputParam.suggestedLatency = PJMEDIA_SND_DEFAULT_REC_LATENCY / 1000.0; paRecHostApiInfo = Pa_GetHostApiInfo(paRecDevInfo->hostApi); @@ -1011,9 +1010,9 @@ static pj_status_t create_bidir_stream(struct pa_aud_factory *pa, outputParam.hostApiSpecificStreamInfo = NULL; outputParam.sampleFormat = sampleFormat; if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY) - outputParam.suggestedLatency=param->output_latency_ms / 1000.0; + outputParam.suggestedLatency=param->output_latency_ms / 1000.0; else - outputParam.suggestedLatency=PJMEDIA_SND_DEFAULT_PLAY_LATENCY/1000.0; + outputParam.suggestedLatency=PJMEDIA_SND_DEFAULT_PLAY_LATENCY/1000.0; paPlayHostApiInfo = Pa_GetHostApiInfo(paPlayDevInfo->hostApi); @@ -1024,15 +1023,15 @@ static pj_status_t create_bidir_stream(struct pa_aud_factory *pa, * for both input and output. */ if (rec_id == play_id) { - err = Pa_OpenStream( &paStream, &inputParam, &outputParam, - param->clock_rate, paFrames, - paClipOff, &PaRecorderPlayerCallback, stream ); - if (err == paNoError) { - /* Set play stream and record stream to the same stream */ - stream->play_strm = stream->rec_strm = paStream; - } + err = Pa_OpenStream( &paStream, &inputParam, &outputParam, + param->clock_rate, paFrames, + paClipOff, &PaRecorderPlayerCallback, stream ); + if (err == paNoError) { + /* Set play stream and record stream to the same stream */ + stream->play_strm = stream->rec_strm = paStream; + } } else { - err = -1; + err = -1; } /* .. otherwise if input and output are on the same device, OR if we're @@ -1040,23 +1039,23 @@ static pj_status_t create_bidir_stream(struct pa_aud_factory *pa, * input and output stream. */ if (paStream == NULL) { - /* Open input stream */ - err = Pa_OpenStream( &stream->rec_strm, &inputParam, NULL, - param->clock_rate, paFrames, - paClipOff, &PaRecorderCallback, stream ); - if (err == paNoError) { - /* Open output stream */ - err = Pa_OpenStream( &stream->play_strm, NULL, &outputParam, - param->clock_rate, paFrames, - paClipOff, &PaPlayerCallback, stream ); - if (err != paNoError) - Pa_CloseStream(stream->rec_strm); - } + /* Open input stream */ + err = Pa_OpenStream( &stream->rec_strm, &inputParam, NULL, + param->clock_rate, paFrames, + paClipOff, &PaRecorderCallback, stream ); + if (err == paNoError) { + /* Open output stream */ + err = Pa_OpenStream( &stream->play_strm, NULL, &outputParam, + param->clock_rate, paFrames, + paClipOff, &PaPlayerCallback, stream ); + if (err != paNoError) + Pa_CloseStream(stream->rec_strm); + } } if (err != paNoError) { - pj_pool_release(pool); - return PJMEDIA_AUDIODEV_ERRNO_FROM_PORTAUDIO(err); + pj_pool_release(pool); + return PJMEDIA_AUDIODEV_ERRNO_FROM_PORTAUDIO(err); } paSI = Pa_GetStreamInfo(stream->rec_strm); @@ -1066,14 +1065,14 @@ static pj_status_t create_bidir_stream(struct pa_aud_factory *pa, paOutputLatency = (unsigned)(paSI->outputLatency * 1000); PJ_LOG(5,(THIS_FILE, "Opened device %s(%s)/%s(%s) for recording and " - "playback, sample rate=%d, ch=%d, " - "bits=%d, %d samples per frame, input latency=%d ms, " - "output latency=%d ms", - paRecDevInfo->name, paRecHostApiInfo->name, - paPlayDevInfo->name, paPlayHostApiInfo->name, - paRate, param->channel_count, - param->bits_per_sample, param->samples_per_frame, - paInputLatency, paOutputLatency)); + "playback, sample rate=%d, ch=%d, " + "bits=%d, %d samples per frame, input latency=%d ms, " + "output latency=%d ms", + paRecDevInfo->name, paRecHostApiInfo->name, + paPlayDevInfo->name, paPlayHostApiInfo->name, + paRate, param->channel_count, + param->bits_per_sample, param->samples_per_frame, + paInputLatency, paOutputLatency)); *p_snd_strm = &stream->base; @@ -1083,28 +1082,28 @@ static pj_status_t create_bidir_stream(struct pa_aud_factory *pa, /* API: create stream */ static pj_status_t pa_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { struct pa_aud_factory *pa = (struct pa_aud_factory*)f; pj_status_t status; if (param->dir == PJMEDIA_DIR_CAPTURE) { - status = create_rec_stream(pa, param, rec_cb, user_data, p_aud_strm); + status = create_rec_stream(pa, param, rec_cb, user_data, p_aud_strm); } else if (param->dir == PJMEDIA_DIR_PLAYBACK) { - status = create_play_stream(pa, param, play_cb, user_data, p_aud_strm); + status = create_play_stream(pa, param, play_cb, user_data, p_aud_strm); } else if (param->dir == PJMEDIA_DIR_CAPTURE_PLAYBACK) { - status = create_bidir_stream(pa, param, rec_cb, play_cb, user_data, - p_aud_strm); + status = create_bidir_stream(pa, param, rec_cb, play_cb, user_data, + p_aud_strm); } else { - return PJ_EINVAL; + return PJ_EINVAL; } if (status != PJ_SUCCESS) - return status; + return status; (*p_aud_strm)->op = &pa_strm_op; @@ -1114,7 +1113,7 @@ static pj_status_t pa_create_stream(pjmedia_aud_dev_factory *f, /* API: Get stream parameters */ static pj_status_t strm_get_param(pjmedia_aud_stream *s, - pjmedia_aud_param *pi) + pjmedia_aud_param *pi) { struct pa_aud_stream *strm = (struct pa_aud_stream*)s; const PaStreamInfo *paPlaySI = NULL, *paRecSI = NULL; @@ -1123,10 +1122,10 @@ static pj_status_t strm_get_param(pjmedia_aud_stream *s, PJ_ASSERT_RETURN(strm->play_strm || strm->rec_strm, PJ_EINVALIDOP); if (strm->play_strm) { - paPlaySI = Pa_GetStreamInfo(strm->play_strm); + paPlaySI = Pa_GetStreamInfo(strm->play_strm); } if (strm->rec_strm) { - paRecSI = Pa_GetStreamInfo(strm->rec_strm); + paRecSI = Pa_GetStreamInfo(strm->rec_strm); } pj_bzero(pi, sizeof(*pi)); @@ -1134,19 +1133,19 @@ static pj_status_t strm_get_param(pjmedia_aud_stream *s, pi->play_id = strm->play_id; pi->rec_id = strm->rec_id; pi->clock_rate = (unsigned)(paPlaySI ? paPlaySI->sampleRate : - paRecSI->sampleRate); + paRecSI->sampleRate); pi->channel_count = strm->channel_count; pi->samples_per_frame = strm->samples_per_frame; pi->bits_per_sample = strm->bytes_per_sample * 8; if (paRecSI) { - pi->flags |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; - pi->input_latency_ms = (unsigned)(paRecSI ? paRecSI->inputLatency * - 1000 : 0); + pi->flags |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; + pi->input_latency_ms = (unsigned)(paRecSI ? paRecSI->inputLatency * + 1000 : 0); } if (paPlaySI) { - pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; - pi->output_latency_ms = (unsigned)(paPlaySI? paPlaySI->outputLatency * - 1000 : 0); + pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; + pi->output_latency_ms = (unsigned)(paPlaySI? paPlaySI->outputLatency * + 1000 : 0); } return PJ_SUCCESS; @@ -1155,37 +1154,37 @@ static pj_status_t strm_get_param(pjmedia_aud_stream *s, /* API: get capability */ static pj_status_t strm_get_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - void *pval) + pjmedia_aud_dev_cap cap, + void *pval) { struct pa_aud_stream *strm = (struct pa_aud_stream*)s; PJ_ASSERT_RETURN(strm && pval, PJ_EINVAL); if (cap==PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY && strm->rec_strm) { - const PaStreamInfo *si = Pa_GetStreamInfo(strm->rec_strm); - if (!si) - return PJMEDIA_EAUD_SYSERR; + const PaStreamInfo *si = Pa_GetStreamInfo(strm->rec_strm); + if (!si) + return PJMEDIA_EAUD_SYSERR; - *(unsigned*)pval = (unsigned)(si->inputLatency * 1000); - return PJ_SUCCESS; + *(unsigned*)pval = (unsigned)(si->inputLatency * 1000); + return PJ_SUCCESS; } else if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY && strm->play_strm) { - const PaStreamInfo *si = Pa_GetStreamInfo(strm->play_strm); - if (!si) - return PJMEDIA_EAUD_SYSERR; + const PaStreamInfo *si = Pa_GetStreamInfo(strm->play_strm); + if (!si) + return PJMEDIA_EAUD_SYSERR; - *(unsigned*)pval = (unsigned)(si->outputLatency * 1000); - return PJ_SUCCESS; + *(unsigned*)pval = (unsigned)(si->outputLatency * 1000); + return PJ_SUCCESS; } else { - return PJMEDIA_EAUD_INVCAP; + return PJMEDIA_EAUD_INVCAP; } } /* API: set capability */ static pj_status_t strm_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value) + pjmedia_aud_dev_cap cap, + const void *value) { PJ_UNUSED_ARG(strm); PJ_UNUSED_ARG(cap); @@ -1205,12 +1204,12 @@ static pj_status_t strm_start(pjmedia_aud_stream *s) PJ_LOG(5,(THIS_FILE, "Starting %s stream..", stream->name.ptr)); if (stream->play_strm) - err = Pa_StartStream(stream->play_strm); + err = Pa_StartStream(stream->play_strm); if (err==0 && stream->rec_strm && stream->rec_strm != stream->play_strm) { - err = Pa_StartStream(stream->rec_strm); - if (err != 0) - Pa_StopStream(stream->play_strm); + err = Pa_StartStream(stream->rec_strm); + if (err != 0) + Pa_StopStream(stream->play_strm); } PJ_LOG(5,(THIS_FILE, "Done, status=%d", err)); @@ -1227,19 +1226,19 @@ static pj_status_t strm_stop(pjmedia_aud_stream *s) stream->quit_flag = 1; for (i=0; !stream->rec_thread_exited && i<100; ++i) - pj_thread_sleep(10); + pj_thread_sleep(10); for (i=0; !stream->play_thread_exited && i<100; ++i) - pj_thread_sleep(10); + pj_thread_sleep(10); pj_thread_sleep(1); PJ_LOG(5,(THIS_FILE, "Stopping stream..")); if (stream->play_strm) - err = Pa_StopStream(stream->play_strm); + err = Pa_StopStream(stream->play_strm); if (stream->rec_strm && stream->rec_strm != stream->play_strm) - err = Pa_StopStream(stream->rec_strm); + err = Pa_StopStream(stream->rec_strm); stream->play_thread_initialized = 0; stream->rec_thread_initialized = 0; @@ -1258,27 +1257,27 @@ static pj_status_t strm_destroy(pjmedia_aud_stream *s) stream->quit_flag = 1; for (i=0; !stream->rec_thread_exited && i<100; ++i) { - pj_thread_sleep(1); + pj_thread_sleep(1); } for (i=0; !stream->play_thread_exited && i<100; ++i) { - pj_thread_sleep(1); + pj_thread_sleep(1); } PJ_LOG(5,(THIS_FILE, "Closing %.*s: %lu underflow, %lu overflow", - (int)stream->name.slen, - stream->name.ptr, - stream->underflow, stream->overflow)); + (int)stream->name.slen, + stream->name.ptr, + stream->underflow, stream->overflow)); if (stream->play_strm) - err = Pa_CloseStream(stream->play_strm); + err = Pa_CloseStream(stream->play_strm); if (stream->rec_strm && stream->rec_strm != stream->play_strm) - err = Pa_CloseStream(stream->rec_strm); + err = Pa_CloseStream(stream->rec_strm); pj_pool_release(stream->pool); return err ? PJMEDIA_AUDIODEV_ERRNO_FROM_PORTAUDIO(err) : PJ_SUCCESS; } -#endif /* PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO */ diff --git a/pjmedia/src/pjmedia-audiodev/symb_aps_dev.cpp b/pjmedia/src/pjmedia-audiodev/symb_aps_dev.cpp index 6ff0856762..389010f558 100644 --- a/pjmedia/src/pjmedia-audiodev/symb_aps_dev.cpp +++ b/pjmedia/src/pjmedia-audiodev/symb_aps_dev.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -41,8 +40,8 @@ #include "s60_g729_bitstream.h" -#define THIS_FILE "symb_aps_dev.c" -#define BITS_PER_SAMPLE 16 +#define THIS_FILE "symb_aps_dev.c" +#define BITS_PER_SAMPLE 16 #if 1 @@ -62,10 +61,10 @@ static pj_uint8_t aps_g711_frame_len; /* APS factory */ struct aps_factory { - pjmedia_aud_dev_factory base; - pj_pool_t *pool; - pj_pool_factory *pf; - pjmedia_aud_dev_info dev_info; + pjmedia_aud_dev_factory base; + pj_pool_t *pool; + pj_pool_factory *pf; + pjmedia_aud_dev_info dev_info; }; @@ -77,43 +76,43 @@ class CPjAudioEngine; struct aps_stream { // Base - pjmedia_aud_stream base; /**< Base class. */ + pjmedia_aud_stream base; /**< Base class. */ // Pool - pj_pool_t *pool; /**< Memory pool. */ + pj_pool_t *pool; /**< Memory pool. */ // Common settings. - pjmedia_aud_param param; /**< Stream param. */ - pjmedia_aud_rec_cb rec_cb; /**< Record callback. */ - pjmedia_aud_play_cb play_cb; /**< Playback callback. */ - void *user_data; /**< Application data. */ + pjmedia_aud_param param; /**< Stream param. */ + pjmedia_aud_rec_cb rec_cb; /**< Record callback. */ + pjmedia_aud_play_cb play_cb; /**< Playback callback. */ + void *user_data; /**< Application data. */ // Audio engine - CPjAudioEngine *engine; /**< Internal engine. */ + CPjAudioEngine *engine; /**< Internal engine. */ - pj_timestamp ts_play; /**< Playback timestamp.*/ - pj_timestamp ts_rec; /**< Record timestamp. */ + pj_timestamp ts_play; /**< Playback timestamp.*/ + pj_timestamp ts_rec; /**< Record timestamp. */ - pj_int16_t *play_buf; /**< Playback buffer. */ - pj_uint16_t play_buf_len; /**< Playback buffer length. */ - pj_uint16_t play_buf_start; /**< Playback buffer start index. */ - pj_int16_t *rec_buf; /**< Record buffer. */ - pj_uint16_t rec_buf_len; /**< Record buffer length. */ - void *strm_data; /**< Stream data. */ + pj_int16_t *play_buf; /**< Playback buffer. */ + pj_uint16_t play_buf_len; /**< Playback buffer length. */ + pj_uint16_t play_buf_start; /**< Playback buffer start index. */ + pj_int16_t *rec_buf; /**< Record buffer. */ + pj_uint16_t rec_buf_len; /**< Record buffer length. */ + void *strm_data; /**< Stream data. */ /* Resampling is needed, in case audio device is opened with clock rate * other than 8kHz (only for PCM format). */ - pjmedia_resample *play_resample; /**< Resampler for playback. */ - pjmedia_resample *rec_resample; /**< Resampler for recording */ - pj_uint16_t resample_factor; /**< Resample factor, requested - clock rate / 8000 */ + pjmedia_resample *play_resample; /**< Resampler for playback. */ + pjmedia_resample *rec_resample; /**< Resampler for recording */ + pj_uint16_t resample_factor; /**< Resample factor, requested + clock rate / 8000 */ /* When stream is working in PCM format, where the samples may need to be * resampled from/to different clock rate and/or channel count, PCM buffer * is needed to perform such resampling operations. */ - pj_int16_t *pcm_buf; /**< PCM buffer. */ + pj_int16_t *pcm_buf; /**< PCM buffer. */ }; @@ -123,26 +122,26 @@ static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f); static pj_status_t factory_refresh(pjmedia_aud_dev_factory *f); static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f); static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); + unsigned index, + pjmedia_aud_dev_info *info); static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); + unsigned index, + pjmedia_aud_param *param); static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); static pj_status_t stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); + pjmedia_aud_param *param); static pj_status_t stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); + pjmedia_aud_dev_cap cap, + void *value); static pj_status_t stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); + pjmedia_aud_dev_cap cap, + const void *value); static pj_status_t stream_start(pjmedia_aud_stream *strm); static pj_status_t stream_stop(pjmedia_aud_stream *strm); static pj_status_t stream_destroy(pjmedia_aud_stream *strm); @@ -192,8 +191,8 @@ static void snd_wait(unsigned ms) start.UniversalTime(); do { - pj_symbianos_poll(-1, ms); - now.UniversalTime(); + pj_symbianos_poll(-1, ms); + now.UniversalTime(); } while (now.MicroSecondsFrom(start) < ms * 1000); } @@ -206,7 +205,7 @@ class MQueueHandlerObserver { public: MQueueHandlerObserver(PjAudioCallback RecCb_, PjAudioCallback PlayCb_, - void *UserData_) + void *UserData_) : RecCb(RecCb_), PlayCb(PlayCb_), UserData(UserData_) {} @@ -236,25 +235,25 @@ class CQueueHandler : public CActive // The order corresponds to the APS Server state, do not change! enum TState { - EAPSPlayerInitialize = 1, - EAPSRecorderInitialize = 2, - EAPSPlayData = 3, - EAPSRecordData = 4, - EAPSPlayerInitComplete = 5, - EAPSRecorderInitComplete = 6 + EAPSPlayerInitialize = 1, + EAPSRecorderInitialize = 2, + EAPSPlayData = 3, + EAPSRecordData = 4, + EAPSPlayerInitComplete = 5, + EAPSRecorderInitComplete = 6 }; static CQueueHandler* NewL(MQueueHandlerObserver* aObserver, - RMsgQueue* aQ, - RMsgQueue* aWriteQ, - TQueueHandlerType aType) + RMsgQueue* aQ, + RMsgQueue* aWriteQ, + TQueueHandlerType aType) { - CQueueHandler* self = new (ELeave) CQueueHandler(aObserver, aQ, aWriteQ, - aType); - CleanupStack::PushL(self); - self->ConstructL(); - CleanupStack::Pop(self); - return self; + CQueueHandler* self = new (ELeave) CQueueHandler(aObserver, aQ, aWriteQ, + aType); + CleanupStack::PushL(self); + self->ConstructL(); + CleanupStack::Pop(self); + return self; } // Destructor @@ -262,24 +261,24 @@ class CQueueHandler : public CActive // Start listening queue event void Start() { - iQ->NotifyDataAvailable(iStatus); - SetActive(); + iQ->NotifyDataAvailable(iStatus); + SetActive(); } private: // Constructor CQueueHandler(MQueueHandlerObserver* aObserver, - RMsgQueue* aQ, - RMsgQueue* aWriteQ, - TQueueHandlerType aType) - : CActive(CActive::EPriorityHigh), - iQ(aQ), iWriteQ(aWriteQ), iObserver(aObserver), iType(aType) + RMsgQueue* aQ, + RMsgQueue* aWriteQ, + TQueueHandlerType aType) + : CActive(CActive::EPriorityHigh), + iQ(aQ), iWriteQ(aWriteQ), iObserver(aObserver), iType(aType) { - CActiveScheduler::Add(this); + CActiveScheduler::Add(this); - // use lower priority for comm queues - if ((iType == ERecordCommQueue) || (iType == EPlayCommQueue)) - SetPriority(CActive::EPriorityStandard); + // use lower priority for comm queues + if ((iType == ERecordCommQueue) || (iType == EPlayCommQueue)) + SetPriority(CActive::EPriorityStandard); } // Second phase constructor @@ -289,68 +288,68 @@ class CQueueHandler : public CActive void DoCancel() { iQ->CancelDataAvailable(); } void RunL() { - if (iStatus != KErrNone) { - iObserver->NotifyError(iStatus.Int()); - return; + if (iStatus != KErrNone) { + iObserver->NotifyError(iStatus.Int()); + return; + } + + TAPSCommBuffer buffer; + TInt ret = iQ->Receive(buffer); + + if (ret != KErrNone) { + iObserver->NotifyError(ret); + return; } - TAPSCommBuffer buffer; - TInt ret = iQ->Receive(buffer); - - if (ret != KErrNone) { - iObserver->NotifyError(ret); - return; - } - - switch (iType) { - case ERecordQueue: - if (buffer.iCommand == EAPSRecordData) { - iObserver->RecCb(buffer, iObserver->UserData); - } else { - iObserver->NotifyError(buffer.iStatus); - } - break; - - // Callbacks from the APS main thread - case EPlayCommQueue: - switch (buffer.iCommand) { - case EAPSPlayData: - if (buffer.iStatus == KErrUnderflow) { - iObserver->PlayCb(buffer, iObserver->UserData); - iWriteQ->Send(buffer); - } - break; - case EAPSPlayerInitialize: - iObserver->NotifyError(buffer.iStatus); - break; - case EAPSPlayerInitComplete: - iObserver->OutputStreamInitialized(buffer.iStatus); - break; - case EAPSRecorderInitComplete: - iObserver->InputStreamInitialized(buffer.iStatus); - break; - default: - iObserver->NotifyError(buffer.iStatus); - break; - } - break; - - // Callbacks from the APS recorder thread - case ERecordCommQueue: - switch (buffer.iCommand) { - // The APS recorder thread will only report errors - // through this handler. All other callbacks will be - // sent from the APS main thread through EPlayCommQueue - case EAPSRecorderInitialize: - case EAPSRecordData: - default: - iObserver->NotifyError(buffer.iStatus); - break; - } - break; - - default: - break; + switch (iType) { + case ERecordQueue: + if (buffer.iCommand == EAPSRecordData) { + iObserver->RecCb(buffer, iObserver->UserData); + } else { + iObserver->NotifyError(buffer.iStatus); + } + break; + + // Callbacks from the APS main thread + case EPlayCommQueue: + switch (buffer.iCommand) { + case EAPSPlayData: + if (buffer.iStatus == KErrUnderflow) { + iObserver->PlayCb(buffer, iObserver->UserData); + iWriteQ->Send(buffer); + } + break; + case EAPSPlayerInitialize: + iObserver->NotifyError(buffer.iStatus); + break; + case EAPSPlayerInitComplete: + iObserver->OutputStreamInitialized(buffer.iStatus); + break; + case EAPSRecorderInitComplete: + iObserver->InputStreamInitialized(buffer.iStatus); + break; + default: + iObserver->NotifyError(buffer.iStatus); + break; + } + break; + + // Callbacks from the APS recorder thread + case ERecordCommQueue: + switch (buffer.iCommand) { + // The APS recorder thread will only report errors + // through this handler. All other callbacks will be + // sent from the APS main thread through EPlayCommQueue + case EAPSRecorderInitialize: + case EAPSRecordData: + default: + iObserver->NotifyError(buffer.iStatus); + break; + } + break; + + default: + break; } // issue next request @@ -359,13 +358,13 @@ class CQueueHandler : public CActive } TInt RunError(TInt) { - return 0; + return 0; } // Data - RMsgQueue *iQ; // (not owned) - RMsgQueue *iWriteQ; // (not owned) - MQueueHandlerObserver *iObserver; // (not owned) + RMsgQueue *iQ; // (not owned) + RMsgQueue *iWriteQ; // (not owned) + MQueueHandlerObserver *iObserver; // (not owned) TQueueHandlerType iType; }; @@ -375,12 +374,12 @@ class CQueueHandler : public CActive class CPjAudioSetting { public: - TFourCC fourcc; - TAPSCodecMode mode; - TBool plc; - TBool vad; - TBool cng; - TBool loudspk; + TFourCC fourcc; + TAPSCodecMode mode; + TBool plc; + TBool vad; + TBool cng; + TBool loudspk; }; /* @@ -391,20 +390,20 @@ class CPjAudioEngine : public CBase, MQueueHandlerObserver public: enum State { - STATE_NULL, - STATE_INITIALIZING, - STATE_READY, - STATE_STREAMING, - STATE_PENDING_STOP + STATE_NULL, + STATE_INITIALIZING, + STATE_READY, + STATE_STREAMING, + STATE_PENDING_STOP }; ~CPjAudioEngine(); static CPjAudioEngine *NewL(struct aps_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting); + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting); TInt StartL(); void Stop(); @@ -421,10 +420,10 @@ class CPjAudioEngine : public CBase, MQueueHandlerObserver private: CPjAudioEngine(struct aps_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting); + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting); void ConstructL(); TInt InitPlayL(); @@ -437,10 +436,10 @@ class CPjAudioEngine : public CBase, MQueueHandlerObserver virtual void OutputStreamInitialized(const TInt aStatus); virtual void NotifyError(const TInt aError); - TBool session_opened; - State state_; - struct aps_stream *parentStrm_; - CPjAudioSetting setting_; + TBool session_opened; + State state_; + struct aps_stream *parentStrm_; + CPjAudioSetting setting_; RAPSSession iSession; TAPSInitSettings iPlaySettings; @@ -448,27 +447,27 @@ class CPjAudioEngine : public CBase, MQueueHandlerObserver RMsgQueue iReadQ; RMsgQueue iReadCommQ; - TBool readq_opened; + TBool readq_opened; RMsgQueue iWriteQ; RMsgQueue iWriteCommQ; - TBool writeq_opened; + TBool writeq_opened; - CQueueHandler *iPlayCommHandler; - CQueueHandler *iRecCommHandler; - CQueueHandler *iRecHandler; + CQueueHandler *iPlayCommHandler; + CQueueHandler *iRecCommHandler; + CQueueHandler *iRecHandler; }; CPjAudioEngine* CPjAudioEngine::NewL(struct aps_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting) + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting) { CPjAudioEngine* self = new (ELeave) CPjAudioEngine(parent_strm, - rec_cb, play_cb, - user_data, - setting); + rec_cb, play_cb, + user_data, + setting); CleanupStack::PushL(self); self->ConstructL(); CleanupStack::Pop(self); @@ -476,20 +475,20 @@ CPjAudioEngine* CPjAudioEngine::NewL(struct aps_stream *parent_strm, } CPjAudioEngine::CPjAudioEngine(struct aps_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting) + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting) : MQueueHandlerObserver(rec_cb, play_cb, user_data), session_opened(EFalse), - state_(STATE_NULL), - parentStrm_(parent_strm), - setting_(setting), - readq_opened(EFalse), - writeq_opened(EFalse), - iPlayCommHandler(0), - iRecCommHandler(0), - iRecHandler(0) + state_(STATE_NULL), + parentStrm_(parent_strm), + setting_(setting), + readq_opened(EFalse), + writeq_opened(EFalse), + iPlayCommHandler(0), + iRecCommHandler(0), + iRecHandler(0) { } @@ -504,9 +503,9 @@ TInt CPjAudioEngine::InitPlayL() { TInt err = iSession.InitializePlayer(iPlaySettings); if (err != KErrNone) { - Deinit(); - snd_perror("Failed to initialize player", err); - return err; + Deinit(); + snd_perror("Failed to initialize player", err); + return err; } // Open message queues for the output stream @@ -516,15 +515,15 @@ TInt CPjAudioEngine::InitPlayL() buf3.Append(_L("PlayCommQueue")); while (iWriteQ.OpenGlobal(buf2)) - User::After(10); + User::After(10); while (iWriteCommQ.OpenGlobal(buf3)) - User::After(10); + User::After(10); writeq_opened = ETrue; // Construct message queue handler iPlayCommHandler = CQueueHandler::NewL(this, &iWriteCommQ, &iWriteQ, - CQueueHandler::EPlayCommQueue); + CQueueHandler::EPlayCommQueue); // Start observing APS callbacks on output stream message queue iPlayCommHandler->Start(); @@ -537,9 +536,9 @@ TInt CPjAudioEngine::InitRecL() // Initialize input stream device TInt err = iSession.InitializeRecorder(iRecSettings); if (err != KErrNone && err != KErrAlreadyExists) { - Deinit(); - snd_perror("Failed to initialize recorder", err); - return err; + Deinit(); + snd_perror("Failed to initialize recorder", err); + return err; } TBuf<128> buf1 = iRecSettings.iGlobal; @@ -550,17 +549,17 @@ TInt CPjAudioEngine::InitRecL() // Must wait for APS thread to finish creating message queues // before we can open and use them. while (iReadQ.OpenGlobal(buf1)) - User::After(10); + User::After(10); while (iReadCommQ.OpenGlobal(buf4)) - User::After(10); + User::After(10); readq_opened = ETrue; // Construct message queue handlers iRecHandler = CQueueHandler::NewL(this, &iReadQ, NULL, - CQueueHandler::ERecordQueue); + CQueueHandler::ERecordQueue); iRecCommHandler = CQueueHandler::NewL(this, &iReadCommQ, NULL, - CQueueHandler::ERecordCommQueue); + CQueueHandler::ERecordCommQueue); // Start observing APS callbacks from on input stream message queue iRecHandler->Start(); @@ -572,15 +571,15 @@ TInt CPjAudioEngine::InitRecL() TInt CPjAudioEngine::StartL() { if (state_ == STATE_READY) - return StartStreamL(); + return StartStreamL(); PJ_ASSERT_RETURN(state_ == STATE_NULL, PJMEDIA_EAUD_INVOP); if (!session_opened) { - TInt err = iSession.Connect(); - if (err != KErrNone) - return err; - session_opened = ETrue; + TInt err = iSession.Connect(); + if (err != KErrNone) + return err; + session_opened = ETrue; } // Even if only capturer are opened, playback thread of APS Server need @@ -593,38 +592,38 @@ TInt CPjAudioEngine::StartL() void CPjAudioEngine::Stop() { if (state_ == STATE_STREAMING) { - iSession.Stop(); - state_ = STATE_READY; - TRACE_((THIS_FILE, "Sound device stopped")); + iSession.Stop(); + state_ = STATE_READY; + TRACE_((THIS_FILE, "Sound device stopped")); } else if (state_ == STATE_INITIALIZING) { - // Initialization is on progress, so let's set the state to - // STATE_PENDING_STOP to prevent it starting the stream. - state_ = STATE_PENDING_STOP; - - // Then wait until initialization done. - while (state_ != STATE_READY && state_ != STATE_NULL) - pj_symbianos_poll(-1, 100); + // Initialization is on progress, so let's set the state to + // STATE_PENDING_STOP to prevent it starting the stream. + state_ = STATE_PENDING_STOP; + + // Then wait until initialization done. + while (state_ != STATE_READY && state_ != STATE_NULL) + pj_symbianos_poll(-1, 100); } } void CPjAudioEngine::ConstructL() { // Recorder settings - iRecSettings.iFourCC = setting_.fourcc; - iRecSettings.iGlobal = APP_UID; - iRecSettings.iPriority = TMdaPriority(100); - iRecSettings.iPreference = TMdaPriorityPreference(0x05210001); - iRecSettings.iSettings.iChannels = EMMFMono; - iRecSettings.iSettings.iSampleRate = EMMFSampleRate8000Hz; + iRecSettings.iFourCC = setting_.fourcc; + iRecSettings.iGlobal = APP_UID; + iRecSettings.iPriority = TMdaPriority(100); + iRecSettings.iPreference = TMdaPriorityPreference(0x05210001); + iRecSettings.iSettings.iChannels = EMMFMono; + iRecSettings.iSettings.iSampleRate = EMMFSampleRate8000Hz; // Player settings - iPlaySettings.iFourCC = setting_.fourcc; - iPlaySettings.iGlobal = APP_UID; - iPlaySettings.iPriority = TMdaPriority(100); - iPlaySettings.iPreference = TMdaPriorityPreference(0x05220001); - iPlaySettings.iSettings.iChannels = EMMFMono; + iPlaySettings.iFourCC = setting_.fourcc; + iPlaySettings.iGlobal = APP_UID; + iPlaySettings.iPriority = TMdaPriority(100); + iPlaySettings.iPreference = TMdaPriorityPreference(0x05220001); + iPlaySettings.iSettings.iChannels = EMMFMono; iPlaySettings.iSettings.iSampleRate = EMMFSampleRate8000Hz; - iPlaySettings.iSettings.iVolume = 0; + iPlaySettings.iSettings.iVolume = 0; User::LeaveIfError(iSession.Connect()); session_opened = ETrue; @@ -643,14 +642,14 @@ TInt CPjAudioEngine::StartStreamL() // Not only capture if (parentStrm_->param.dir != PJMEDIA_DIR_CAPTURE) { - iSession.Write(); - TRACE_((THIS_FILE, "Player started")); + iSession.Write(); + TRACE_((THIS_FILE, "Player started")); } // Not only playback if (parentStrm_->param.dir != PJMEDIA_DIR_PLAYBACK) { - iSession.Read(); - TRACE_((THIS_FILE, "Recorder started")); + iSession.Read(); + TRACE_((THIS_FILE, "Recorder started")); } state_ = STATE_STREAMING; @@ -667,27 +666,27 @@ void CPjAudioEngine::Deinit() delete iRecCommHandler; if (session_opened) { - enum { APS_CLOSE_WAIT_TIME = 200 }; /* in msecs */ - - // On some devices, immediate closing after stopping may cause - // APS server panic KERN-EXEC 0, so let's wait for sometime before - // closing the client session. - snd_wait(APS_CLOSE_WAIT_TIME); - - iSession.Close(); - session_opened = EFalse; + enum { APS_CLOSE_WAIT_TIME = 200 }; /* in msecs */ + + // On some devices, immediate closing after stopping may cause + // APS server panic KERN-EXEC 0, so let's wait for sometime before + // closing the client session. + snd_wait(APS_CLOSE_WAIT_TIME); + + iSession.Close(); + session_opened = EFalse; } if (readq_opened) { - iReadQ.Close(); - iReadCommQ.Close(); - readq_opened = EFalse; + iReadQ.Close(); + iReadCommQ.Close(); + readq_opened = EFalse; } if (writeq_opened) { - iWriteQ.Close(); - iWriteCommQ.Close(); - writeq_opened = EFalse; + iWriteQ.Close(); + iWriteCommQ.Close(); + writeq_opened = EFalse; } state_ = STATE_NULL; @@ -698,14 +697,14 @@ void CPjAudioEngine::InputStreamInitialized(const TInt aStatus) TRACE_((THIS_FILE, "Recorder initialized, err=%d", aStatus)); if (aStatus == KErrNone) { - // Don't start the stream since Stop() has been requested. - if (state_ != STATE_PENDING_STOP) { - StartStreamL(); - } else { - state_ = STATE_READY; - } + // Don't start the stream since Stop() has been requested. + if (state_ != STATE_PENDING_STOP) { + StartStreamL(); + } else { + state_ = STATE_READY; + } } else { - Deinit(); + Deinit(); } } @@ -714,17 +713,17 @@ void CPjAudioEngine::OutputStreamInitialized(const TInt aStatus) TRACE_((THIS_FILE, "Player initialized, err=%d", aStatus)); if (aStatus == KErrNone) { - if (parentStrm_->param.dir == PJMEDIA_DIR_PLAYBACK) { - // Don't start the stream since Stop() has been requested. - if (state_ != STATE_PENDING_STOP) { - StartStreamL(); - } else { - state_ = STATE_READY; - } - } else - InitRecL(); + if (parentStrm_->param.dir == PJMEDIA_DIR_PLAYBACK) { + // Don't start the stream since Stop() has been requested. + if (state_ != STATE_PENDING_STOP) { + StartStreamL(); + } else { + state_ = STATE_READY; + } + } else + InitRecL(); } else { - Deinit(); + Deinit(); } } @@ -739,7 +738,7 @@ TInt CPjAudioEngine::ActivateSpeaker(TBool active) if (state_ == STATE_READY || state_ == STATE_STREAMING) { iSession.ActivateLoudspeaker(active); TRACE_((THIS_FILE, "Loudspeaker turned %s", (active? "on":"off"))); - return KErrNone; + return KErrNone; } return KErrNotReady; } @@ -759,9 +758,9 @@ static void RecCbPcm(TAPSCommBuffer &buf, void *user_data) * this recorder frame size. */ if (aps_g711_frame_len == 0) { - aps_g711_frame_len = buf.iBuffer.Length() < 160? 80 : 160; - TRACE_((THIS_FILE, "Detected APS G.711 frame size = %u samples", - aps_g711_frame_len)); + aps_g711_frame_len = buf.iBuffer.Length() < 160? 80 : 160; + TRACE_((THIS_FILE, "Detected APS G.711 frame size = %u samples", + aps_g711_frame_len)); } /* Decode APS buffer (coded in G.711) and put the PCM result into rec_buf. @@ -770,63 +769,63 @@ static void RecCbPcm(TAPSCommBuffer &buf, void *user_data) unsigned samples_processed = 0; while (samples_processed < aps_g711_frame_len) { - unsigned samples_to_process; - unsigned samples_req; - - samples_to_process = aps_g711_frame_len - samples_processed; - samples_req = (strm->param.samples_per_frame / - strm->param.channel_count / - strm->resample_factor) - - strm->rec_buf_len; - if (samples_to_process > samples_req) - samples_to_process = samples_req; - - pjmedia_ulaw_decode(&strm->rec_buf[strm->rec_buf_len], - buf.iBuffer.Ptr() + 2 + samples_processed, - samples_to_process); - - strm->rec_buf_len += samples_to_process; - samples_processed += samples_to_process; - - /* Buffer is full, time to call parent callback */ - if (strm->rec_buf_len == strm->param.samples_per_frame / - strm->param.channel_count / - strm->resample_factor) - { - pjmedia_frame f; - - /* Need to resample clock rate? */ - if (strm->rec_resample) { - unsigned resampled = 0; - - while (resampled < strm->rec_buf_len) { - pjmedia_resample_run(strm->rec_resample, - &strm->rec_buf[resampled], - strm->pcm_buf + - resampled * strm->resample_factor); - resampled += 80; - } - f.buf = strm->pcm_buf; - } else { - f.buf = strm->rec_buf; - } - - /* Need to convert channel count? */ - if (strm->param.channel_count != 1) { - pjmedia_convert_channel_1ton((pj_int16_t*)f.buf, - (pj_int16_t*)f.buf, - strm->param.channel_count, - strm->param.samples_per_frame / - strm->param.channel_count, - 0); - } - - /* Call parent callback */ - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.size = strm->param.samples_per_frame << 1; - strm->rec_cb(strm->user_data, &f); - strm->rec_buf_len = 0; - } + unsigned samples_to_process; + unsigned samples_req; + + samples_to_process = aps_g711_frame_len - samples_processed; + samples_req = (strm->param.samples_per_frame / + strm->param.channel_count / + strm->resample_factor) - + strm->rec_buf_len; + if (samples_to_process > samples_req) + samples_to_process = samples_req; + + pjmedia_ulaw_decode(&strm->rec_buf[strm->rec_buf_len], + buf.iBuffer.Ptr() + 2 + samples_processed, + samples_to_process); + + strm->rec_buf_len += samples_to_process; + samples_processed += samples_to_process; + + /* Buffer is full, time to call parent callback */ + if (strm->rec_buf_len == strm->param.samples_per_frame / + strm->param.channel_count / + strm->resample_factor) + { + pjmedia_frame f; + + /* Need to resample clock rate? */ + if (strm->rec_resample) { + unsigned resampled = 0; + + while (resampled < strm->rec_buf_len) { + pjmedia_resample_run(strm->rec_resample, + &strm->rec_buf[resampled], + strm->pcm_buf + + resampled * strm->resample_factor); + resampled += 80; + } + f.buf = strm->pcm_buf; + } else { + f.buf = strm->rec_buf; + } + + /* Need to convert channel count? */ + if (strm->param.channel_count != 1) { + pjmedia_convert_channel_1ton((pj_int16_t*)f.buf, + (pj_int16_t*)f.buf, + strm->param.channel_count, + strm->param.samples_per_frame / + strm->param.channel_count, + 0); + } + + /* Call parent callback */ + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + f.size = strm->param.samples_per_frame << 1; + strm->rec_cb(strm->user_data, &f); + strm->rec_buf_len = 0; + } } } @@ -844,7 +843,7 @@ static void PlayCbPcm(TAPSCommBuffer &buf, void *user_data) /* Assume frame size is 10ms if frame size hasn't been known. */ if (g711_frame_len == 0) - g711_frame_len = 80; + g711_frame_len = 80; /* Call parent stream callback to get PCM samples to play, * encode the PCM samples into G.711 and put it into APS buffer. @@ -852,66 +851,66 @@ static void PlayCbPcm(TAPSCommBuffer &buf, void *user_data) unsigned samples_processed = 0; while (samples_processed < g711_frame_len) { - /* Need more samples to play, time to call parent callback */ - if (strm->play_buf_len == 0) { - pjmedia_frame f; - unsigned samples_got; - - f.size = strm->param.samples_per_frame << 1; - if (strm->play_resample || strm->param.channel_count != 1) - f.buf = strm->pcm_buf; - else - f.buf = strm->play_buf; - - /* Call parent callback */ - strm->play_cb(strm->user_data, &f); - if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) { - pjmedia_zero_samples((pj_int16_t*)f.buf, - strm->param.samples_per_frame); - } - - samples_got = strm->param.samples_per_frame / - strm->param.channel_count / - strm->resample_factor; - - /* Need to convert channel count? */ - if (strm->param.channel_count != 1) { - pjmedia_convert_channel_nto1((pj_int16_t*)f.buf, - (pj_int16_t*)f.buf, - strm->param.channel_count, - strm->param.samples_per_frame, - PJ_FALSE, - 0); - } - - /* Need to resample clock rate? */ - if (strm->play_resample) { - unsigned resampled = 0; - - while (resampled < samples_got) - { - pjmedia_resample_run(strm->play_resample, - strm->pcm_buf + - resampled * strm->resample_factor, - &strm->play_buf[resampled]); - resampled += 80; - } - } - - strm->play_buf_len = samples_got; - strm->play_buf_start = 0; - } - - unsigned tmp; - - tmp = PJ_MIN(strm->play_buf_len, g711_frame_len - samples_processed); - pjmedia_ulaw_encode((pj_uint8_t*)&strm->play_buf[strm->play_buf_start], - &strm->play_buf[strm->play_buf_start], - tmp); - buf.iBuffer.Append((TUint8*)&strm->play_buf[strm->play_buf_start], tmp); - samples_processed += tmp; - strm->play_buf_len -= tmp; - strm->play_buf_start += tmp; + /* Need more samples to play, time to call parent callback */ + if (strm->play_buf_len == 0) { + pjmedia_frame f; + unsigned samples_got; + + f.size = strm->param.samples_per_frame << 1; + if (strm->play_resample || strm->param.channel_count != 1) + f.buf = strm->pcm_buf; + else + f.buf = strm->play_buf; + + /* Call parent callback */ + strm->play_cb(strm->user_data, &f); + if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) { + pjmedia_zero_samples((pj_int16_t*)f.buf, + strm->param.samples_per_frame); + } + + samples_got = strm->param.samples_per_frame / + strm->param.channel_count / + strm->resample_factor; + + /* Need to convert channel count? */ + if (strm->param.channel_count != 1) { + pjmedia_convert_channel_nto1((pj_int16_t*)f.buf, + (pj_int16_t*)f.buf, + strm->param.channel_count, + strm->param.samples_per_frame, + PJ_FALSE, + 0); + } + + /* Need to resample clock rate? */ + if (strm->play_resample) { + unsigned resampled = 0; + + while (resampled < samples_got) + { + pjmedia_resample_run(strm->play_resample, + strm->pcm_buf + + resampled * strm->resample_factor, + &strm->play_buf[resampled]); + resampled += 80; + } + } + + strm->play_buf_len = samples_got; + strm->play_buf_start = 0; + } + + unsigned tmp; + + tmp = PJ_MIN(strm->play_buf_len, g711_frame_len - samples_processed); + pjmedia_ulaw_encode((pj_uint8_t*)&strm->play_buf[strm->play_buf_start], + &strm->play_buf[strm->play_buf_start], + tmp); + buf.iBuffer.Append((TUint8*)&strm->play_buf[strm->play_buf_start], tmp); + samples_processed += tmp; + strm->play_buf_len -= tmp; + strm->play_buf_start += tmp; } } @@ -926,120 +925,120 @@ static void RecCb(TAPSCommBuffer &buf, void *user_data) switch(strm->param.ext_fmt.id) { case PJMEDIA_FORMAT_AMR: - { - const pj_uint8_t *p = (const pj_uint8_t*)buf.iBuffer.Ptr() + 1; - unsigned len = buf.iBuffer.Length() - 1; - - pjmedia_frame_ext_append_subframe(frame, p, len << 3, 160); - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - + { + const pj_uint8_t *p = (const pj_uint8_t*)buf.iBuffer.Ptr() + 1; + unsigned len = buf.iBuffer.Length() - 1; + + pjmedia_frame_ext_append_subframe(frame, p, len << 3, 160); + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + break; + case PJMEDIA_FORMAT_G729: - { - /* Check if we got a normal or SID frame. */ - if (buf.iBuffer[0] != 0 || buf.iBuffer[1] != 0) { - enum { NORMAL_LEN = 22, SID_LEN = 8 }; - TBitStream *bitstream = (TBitStream*)strm->strm_data; - unsigned src_len = buf.iBuffer.Length()- 2; - - pj_assert(src_len == NORMAL_LEN || src_len == SID_LEN); - - const TDesC8& p = bitstream->CompressG729Frame( - buf.iBuffer.Right(src_len), - src_len == SID_LEN); - - pjmedia_frame_ext_append_subframe(frame, p.Ptr(), - p.Length() << 3, 80); - } else { /* We got null frame. */ - pjmedia_frame_ext_append_subframe(frame, NULL, 0, 80); - } - - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; + { + /* Check if we got a normal or SID frame. */ + if (buf.iBuffer[0] != 0 || buf.iBuffer[1] != 0) { + enum { NORMAL_LEN = 22, SID_LEN = 8 }; + TBitStream *bitstream = (TBitStream*)strm->strm_data; + unsigned src_len = buf.iBuffer.Length()- 2; + + pj_assert(src_len == NORMAL_LEN || src_len == SID_LEN); + + const TDesC8& p = bitstream->CompressG729Frame( + buf.iBuffer.Right(src_len), + src_len == SID_LEN); + + pjmedia_frame_ext_append_subframe(frame, p.Ptr(), + p.Length() << 3, 80); + } else { /* We got null frame. */ + pjmedia_frame_ext_append_subframe(frame, NULL, 0, 80); + } + + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + break; case PJMEDIA_FORMAT_ILBC: - { - unsigned samples_got; - - samples_got = - strm->param.ext_fmt.det.aud.avg_bps == 15200? 160 : 240; - - /* Check if we got a normal frame. */ - if (buf.iBuffer[0] == 1 && buf.iBuffer[1] == 0) { - const pj_uint8_t *p = (const pj_uint8_t*)buf.iBuffer.Ptr() + 2; - unsigned len = buf.iBuffer.Length() - 2; - - pjmedia_frame_ext_append_subframe(frame, p, len << 3, - samples_got); - } else { /* We got null frame. */ - pjmedia_frame_ext_append_subframe(frame, NULL, 0, samples_got); - } - - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - + { + unsigned samples_got; + + samples_got = + strm->param.ext_fmt.det.aud.avg_bps == 15200? 160 : 240; + + /* Check if we got a normal frame. */ + if (buf.iBuffer[0] == 1 && buf.iBuffer[1] == 0) { + const pj_uint8_t *p = (const pj_uint8_t*)buf.iBuffer.Ptr() + 2; + unsigned len = buf.iBuffer.Length() - 2; + + pjmedia_frame_ext_append_subframe(frame, p, len << 3, + samples_got); + } else { /* We got null frame. */ + pjmedia_frame_ext_append_subframe(frame, NULL, 0, samples_got); + } + + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + break; + case PJMEDIA_FORMAT_PCMU: case PJMEDIA_FORMAT_PCMA: - { - unsigned samples_processed = 0; - - /* Make sure it is normal frame. */ - pj_assert(buf.iBuffer[0] == 1 && buf.iBuffer[1] == 0); - - /* Detect the recorder G.711 frame size, player frame size will - * follow this recorder frame size. - */ - if (aps_g711_frame_len == 0) { - aps_g711_frame_len = buf.iBuffer.Length() < 160? 80 : 160; - TRACE_((THIS_FILE, "Detected APS G.711 frame size = %u samples", - aps_g711_frame_len)); - } - - /* Convert APS buffer format into pjmedia_frame_ext. Whenever - * samples count in the frame is equal to stream's samples per - * frame, call parent stream callback. - */ - while (samples_processed < aps_g711_frame_len) { - unsigned tmp; - const pj_uint8_t *pb = (const pj_uint8_t*)buf.iBuffer.Ptr() + - 2 + samples_processed; + { + unsigned samples_processed = 0; + + /* Make sure it is normal frame. */ + pj_assert(buf.iBuffer[0] == 1 && buf.iBuffer[1] == 0); + + /* Detect the recorder G.711 frame size, player frame size will + * follow this recorder frame size. + */ + if (aps_g711_frame_len == 0) { + aps_g711_frame_len = buf.iBuffer.Length() < 160? 80 : 160; + TRACE_((THIS_FILE, "Detected APS G.711 frame size = %u samples", + aps_g711_frame_len)); + } + + /* Convert APS buffer format into pjmedia_frame_ext. Whenever + * samples count in the frame is equal to stream's samples per + * frame, call parent stream callback. + */ + while (samples_processed < aps_g711_frame_len) { + unsigned tmp; + const pj_uint8_t *pb = (const pj_uint8_t*)buf.iBuffer.Ptr() + + 2 + samples_processed; - tmp = PJ_MIN(strm->param.samples_per_frame - frame->samples_cnt, - aps_g711_frame_len - samples_processed); - - pjmedia_frame_ext_append_subframe(frame, pb, tmp << 3, tmp); - samples_processed += tmp; + tmp = PJ_MIN(strm->param.samples_per_frame - frame->samples_cnt, + aps_g711_frame_len - samples_processed); + + pjmedia_frame_ext_append_subframe(frame, pb, tmp << 3, tmp); + samples_processed += tmp; - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - } - break; - + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + } + break; + default: - break; + break; } } @@ -1055,206 +1054,206 @@ static void PlayCb(TAPSCommBuffer &buf, void *user_data) switch(strm->param.ext_fmt.id) { case PJMEDIA_FORMAT_AMR: - { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - - if (sf->data && sf->bitlen) { - /* AMR header for APS is one byte, the format (may be!): - * 0xxxxy00, where xxxx:frame type, y:not sure. - */ - unsigned len = (sf->bitlen+7)>>3; - enum {SID_FT = 8 }; - pj_uint8_t amr_header = 4, ft = SID_FT; - - if (len >= pjmedia_codec_amrnb_framelen[0]) - ft = pjmedia_codec_amr_get_mode2(PJ_TRUE, len); - - amr_header |= ft << 3; - buf.iBuffer.Append(amr_header); - - buf.iBuffer.Append((TUint8*)sf->data, len); - } else { - enum {NO_DATA_FT = 15 }; - pj_uint8_t amr_header = 4 | (NO_DATA_FT << 3); - - buf.iBuffer.Append(amr_header); - } - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - enum {NO_DATA_FT = 15 }; - pj_uint8_t amr_header = 4 | (NO_DATA_FT << 3); - - buf.iBuffer.Append(amr_header); - - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - + { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb(strm->user_data, (pjmedia_frame*)frame); + pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe(frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + if (sf->data && sf->bitlen) { + /* AMR header for APS is one byte, the format (may be!): + * 0xxxxy00, where xxxx:frame type, y:not sure. + */ + unsigned len = (sf->bitlen+7)>>3; + enum {SID_FT = 8 }; + pj_uint8_t amr_header = 4, ft = SID_FT; + + if (len >= pjmedia_codec_amrnb_framelen[0]) + ft = pjmedia_codec_amr_get_mode2(PJ_TRUE, len); + + amr_header |= ft << 3; + buf.iBuffer.Append(amr_header); + + buf.iBuffer.Append((TUint8*)sf->data, len); + } else { + enum {NO_DATA_FT = 15 }; + pj_uint8_t amr_header = 4 | (NO_DATA_FT << 3); + + buf.iBuffer.Append(amr_header); + } + + pjmedia_frame_ext_pop_subframes(frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + enum {NO_DATA_FT = 15 }; + pj_uint8_t amr_header = 4 | (NO_DATA_FT << 3); + + buf.iBuffer.Append(amr_header); + + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + break; + case PJMEDIA_FORMAT_G729: - { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - - if (sf->data && sf->bitlen) { - enum { NORMAL_LEN = 10, SID_LEN = 2 }; - pj_bool_t sid_frame = ((sf->bitlen >> 3) == SID_LEN); - TBitStream *bitstream = (TBitStream*)strm->strm_data; - const TPtrC8 src(sf->data, sf->bitlen>>3); - const TDesC8 &dst = bitstream->ExpandG729Frame(src, - sid_frame); - if (sid_frame) { - buf.iBuffer.Append(2); - buf.iBuffer.Append(0); - } else { - buf.iBuffer.Append(1); - buf.iBuffer.Append(0); - } - buf.iBuffer.Append(dst); - } else { - buf.iBuffer.Append(2); - buf.iBuffer.Append(0); - buf.iBuffer.AppendFill(0, 22); - } - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - buf.iBuffer.Append(2); - buf.iBuffer.Append(0); - buf.iBuffer.AppendFill(0, 22); - - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - + { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb(strm->user_data, (pjmedia_frame*)frame); + pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe(frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + if (sf->data && sf->bitlen) { + enum { NORMAL_LEN = 10, SID_LEN = 2 }; + pj_bool_t sid_frame = ((sf->bitlen >> 3) == SID_LEN); + TBitStream *bitstream = (TBitStream*)strm->strm_data; + const TPtrC8 src(sf->data, sf->bitlen>>3); + const TDesC8 &dst = bitstream->ExpandG729Frame(src, + sid_frame); + if (sid_frame) { + buf.iBuffer.Append(2); + buf.iBuffer.Append(0); + } else { + buf.iBuffer.Append(1); + buf.iBuffer.Append(0); + } + buf.iBuffer.Append(dst); + } else { + buf.iBuffer.Append(2); + buf.iBuffer.Append(0); + buf.iBuffer.AppendFill(0, 22); + } + + pjmedia_frame_ext_pop_subframes(frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + buf.iBuffer.Append(2); + buf.iBuffer.Append(0); + buf.iBuffer.AppendFill(0, 22); + + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + break; + case PJMEDIA_FORMAT_ILBC: - { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - - pj_assert((strm->param.ext_fmt.det.aud.avg_bps == 15200 && - samples_cnt == 160) || - (strm->param.ext_fmt.det.aud.avg_bps != 15200 && - samples_cnt == 240)); - - if (sf->data && sf->bitlen) { - buf.iBuffer.Append(1); - buf.iBuffer.Append(0); - buf.iBuffer.Append((TUint8*)sf->data, sf->bitlen>>3); - } else { - buf.iBuffer.Append(0); - buf.iBuffer.Append(0); - } - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - buf.iBuffer.Append(0); - buf.iBuffer.Append(0); - - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - + { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb(strm->user_data, (pjmedia_frame*)frame); + pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe(frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + pj_assert((strm->param.ext_fmt.det.aud.avg_bps == 15200 && + samples_cnt == 160) || + (strm->param.ext_fmt.det.aud.avg_bps != 15200 && + samples_cnt == 240)); + + if (sf->data && sf->bitlen) { + buf.iBuffer.Append(1); + buf.iBuffer.Append(0); + buf.iBuffer.Append((TUint8*)sf->data, sf->bitlen>>3); + } else { + buf.iBuffer.Append(0); + buf.iBuffer.Append(0); + } + + pjmedia_frame_ext_pop_subframes(frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + buf.iBuffer.Append(0); + buf.iBuffer.Append(0); + + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + break; + case PJMEDIA_FORMAT_PCMU: case PJMEDIA_FORMAT_PCMA: - { - unsigned samples_ready = 0; - unsigned samples_req = aps_g711_frame_len; - - /* Assume frame size is 10ms if frame size hasn't been known. */ - if (samples_req == 0) - samples_req = 80; - - buf.iBuffer.Append(1); - buf.iBuffer.Append(0); - - /* Call parent stream callback to get samples to play. */ - while (samples_ready < samples_req) { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } + { + unsigned samples_ready = 0; + unsigned samples_req = aps_g711_frame_len; + + /* Assume frame size is 10ms if frame size hasn't been known. */ + if (samples_req == 0) + samples_req = 80; + + buf.iBuffer.Append(1); + buf.iBuffer.Append(0); + + /* Call parent stream callback to get samples to play. */ + while (samples_ready < samples_req) { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb(strm->user_data, (pjmedia_frame*)frame); + pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - if (sf->data && sf->bitlen) { - buf.iBuffer.Append((TUint8*)sf->data, sf->bitlen>>3); - } else { - pj_uint8_t silc; - silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU)? - pjmedia_linear2ulaw(0) : pjmedia_linear2alaw(0); - buf.iBuffer.AppendFill(silc, samples_cnt); - } - samples_ready += samples_cnt; - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - pj_uint8_t silc; - - silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU)? - pjmedia_linear2ulaw(0) : pjmedia_linear2alaw(0); - buf.iBuffer.AppendFill(silc, samples_req - samples_ready); - - samples_ready = samples_req; - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - } - break; - + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe(frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + if (sf->data && sf->bitlen) { + buf.iBuffer.Append((TUint8*)sf->data, sf->bitlen>>3); + } else { + pj_uint8_t silc; + silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU)? + pjmedia_linear2ulaw(0) : pjmedia_linear2alaw(0); + buf.iBuffer.AppendFill(silc, samples_cnt); + } + samples_ready += samples_cnt; + + pjmedia_frame_ext_pop_subframes(frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + pj_uint8_t silc; + + silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU)? + pjmedia_linear2ulaw(0) : pjmedia_linear2alaw(0); + buf.iBuffer.AppendFill(silc, samples_req - samples_ready); + + samples_ready = samples_req; + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + } + break; + default: - break; + break; } } @@ -1295,13 +1294,13 @@ static pj_status_t factory_init(pjmedia_aud_dev_factory *f) pj_ansi_strcpy(af->dev_info.name, "S60 APS"); af->dev_info.default_samples_per_sec = 8000; af->dev_info.caps = PJMEDIA_AUD_DEV_CAP_EXT_FORMAT | - //PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING | - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING | - PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE | - PJMEDIA_AUD_DEV_CAP_VAD | - PJMEDIA_AUD_DEV_CAP_CNG; + //PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING | + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING | + PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE | + PJMEDIA_AUD_DEV_CAP_VAD | + PJMEDIA_AUD_DEV_CAP_CNG; af->dev_info.routes = PJMEDIA_AUD_DEV_ROUTE_EARPIECE | - PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; + PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; af->dev_info.input_count = 1; af->dev_info.output_count = 1; @@ -1318,119 +1317,119 @@ static pj_status_t factory_init(pjmedia_aud_dev_factory *f) /* Do not change the order! */ TFourCC fourcc[] = { - TFourCC(KMCPFourCCIdAMRNB), - TFourCC(KMCPFourCCIdG711), - TFourCC(KMCPFourCCIdG729), - TFourCC(KMCPFourCCIdILBC) + TFourCC(KMCPFourCCIdAMRNB), + TFourCC(KMCPFourCCIdG711), + TFourCC(KMCPFourCCIdG729), + TFourCC(KMCPFourCCIdILBC) }; for (i = 0; i < PJ_ARRAY_SIZE(fourcc); ++i) { - pj_bool_t supported = PJ_FALSE; - unsigned retry_cnt = 0; - enum { MAX_RETRY = 3 }; + pj_bool_t supported = PJ_FALSE; + unsigned retry_cnt = 0; + enum { MAX_RETRY = 3 }; #if (PJMEDIA_AUDIO_DEV_SYMB_APS_DETECTS_CODEC == 0) - /* Codec detection is disabled */ - supported = PJ_TRUE; + /* Codec detection is disabled */ + supported = PJ_TRUE; #elif (PJMEDIA_AUDIO_DEV_SYMB_APS_DETECTS_CODEC == 1) - /* Minimal codec detection, AMR-NB and G.711 only */ - if (i > 1) { - /* If G.711 has been checked, skip G.729 and iLBC checks */ - retry_cnt = MAX_RETRY; - supported = g711_supported; - } + /* Minimal codec detection, AMR-NB and G.711 only */ + if (i > 1) { + /* If G.711 has been checked, skip G.729 and iLBC checks */ + retry_cnt = MAX_RETRY; + supported = g711_supported; + } #endif - - while (!supported && ++retry_cnt <= MAX_RETRY) { - RAPSSession iSession; - TAPSInitSettings iPlaySettings; - TAPSInitSettings iRecSettings; - TInt err; - - // Recorder settings - iRecSettings.iGlobal = APP_UID; - iRecSettings.iPriority = TMdaPriority(100); - iRecSettings.iPreference = TMdaPriorityPreference(0x05210001); - iRecSettings.iSettings.iChannels = EMMFMono; - iRecSettings.iSettings.iSampleRate = EMMFSampleRate8000Hz; - - // Player settings - iPlaySettings.iGlobal = APP_UID; - iPlaySettings.iPriority = TMdaPriority(100); - iPlaySettings.iPreference = TMdaPriorityPreference(0x05220001); - iPlaySettings.iSettings.iChannels = EMMFMono; - iPlaySettings.iSettings.iSampleRate = EMMFSampleRate8000Hz; - - iRecSettings.iFourCC = iPlaySettings.iFourCC = fourcc[i]; - - err = iSession.Connect(); - if (err == KErrNone) - err = iSession.InitializePlayer(iPlaySettings); - if (err == KErrNone) - err = iSession.InitializeRecorder(iRecSettings); - - // On some devices, immediate closing causes APS Server panic, - // e.g: N95, so let's just wait for some time before closing. - enum { APS_CLOSE_WAIT_TIME = 200 }; /* in msecs */ - snd_wait(APS_CLOSE_WAIT_TIME); - - iSession.Close(); - - if (err == KErrNone) { - /* All fine, stop retyring */ - supported = PJ_TRUE; - } else if (err == KErrAlreadyExists && retry_cnt < MAX_RETRY) { - /* Seems that the previous session is still arround, - * let's wait before retrying. - */ - enum { RETRY_WAIT_TIME = 3000 }; /* in msecs */ - snd_wait(RETRY_WAIT_TIME); - } else { - /* Seems that this format is not supported */ - retry_cnt = MAX_RETRY; - } - } - - if (supported) { - pjmedia_format ext_fmt; - - switch(i) { - case 0: /* AMRNB */ - pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_AMR, - 8000, 1, 16, 20, 7400, 12200); - af->dev_info.ext_fmt[fmt_cnt] = ext_fmt; - //af->dev_info.ext_fmt[fmt_cnt].vad = PJ_TRUE; - ++fmt_cnt; - break; - case 1: /* G.711 */ - pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_PCMU, - 8000, 1, 16, 20, 64000, 64000); - af->dev_info.ext_fmt[fmt_cnt] = ext_fmt; - //af->dev_info.ext_fmt[fmt_cnt].vad = PJ_FALSE; - ++fmt_cnt; - pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_PCMA, - 8000, 1, 16, 20, 64000, 64000); - af->dev_info.ext_fmt[fmt_cnt] = ext_fmt; - //af->dev_info.ext_fmt[fmt_cnt].vad = PJ_FALSE; - ++fmt_cnt; - g711_supported = PJ_TRUE; - break; - case 2: /* G.729 */ - pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_G729, - 8000, 1, 16, 20, 8000, 8000); - af->dev_info.ext_fmt[fmt_cnt] = ext_fmt; - //af->dev_info.ext_fmt[fmt_cnt].vad = PJ_FALSE; - ++fmt_cnt; - break; - case 3: /* iLBC */ - pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_ILBC, - 8000, 1, 16, 30, 13333, 15200); - af->dev_info.ext_fmt[fmt_cnt] = ext_fmt; - //af->dev_info.ext_fmt[fmt_cnt].vad = PJ_TRUE; - ++fmt_cnt; - break; - } - } + + while (!supported && ++retry_cnt <= MAX_RETRY) { + RAPSSession iSession; + TAPSInitSettings iPlaySettings; + TAPSInitSettings iRecSettings; + TInt err; + + // Recorder settings + iRecSettings.iGlobal = APP_UID; + iRecSettings.iPriority = TMdaPriority(100); + iRecSettings.iPreference = TMdaPriorityPreference(0x05210001); + iRecSettings.iSettings.iChannels = EMMFMono; + iRecSettings.iSettings.iSampleRate = EMMFSampleRate8000Hz; + + // Player settings + iPlaySettings.iGlobal = APP_UID; + iPlaySettings.iPriority = TMdaPriority(100); + iPlaySettings.iPreference = TMdaPriorityPreference(0x05220001); + iPlaySettings.iSettings.iChannels = EMMFMono; + iPlaySettings.iSettings.iSampleRate = EMMFSampleRate8000Hz; + + iRecSettings.iFourCC = iPlaySettings.iFourCC = fourcc[i]; + + err = iSession.Connect(); + if (err == KErrNone) + err = iSession.InitializePlayer(iPlaySettings); + if (err == KErrNone) + err = iSession.InitializeRecorder(iRecSettings); + + // On some devices, immediate closing causes APS Server panic, + // e.g: N95, so let's just wait for some time before closing. + enum { APS_CLOSE_WAIT_TIME = 200 }; /* in msecs */ + snd_wait(APS_CLOSE_WAIT_TIME); + + iSession.Close(); + + if (err == KErrNone) { + /* All fine, stop retyring */ + supported = PJ_TRUE; + } else if (err == KErrAlreadyExists && retry_cnt < MAX_RETRY) { + /* Seems that the previous session is still arround, + * let's wait before retrying. + */ + enum { RETRY_WAIT_TIME = 3000 }; /* in msecs */ + snd_wait(RETRY_WAIT_TIME); + } else { + /* Seems that this format is not supported */ + retry_cnt = MAX_RETRY; + } + } + + if (supported) { + pjmedia_format ext_fmt; + + switch(i) { + case 0: /* AMRNB */ + pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_AMR, + 8000, 1, 16, 20, 7400, 12200); + af->dev_info.ext_fmt[fmt_cnt] = ext_fmt; + //af->dev_info.ext_fmt[fmt_cnt].vad = PJ_TRUE; + ++fmt_cnt; + break; + case 1: /* G.711 */ + pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_PCMU, + 8000, 1, 16, 20, 64000, 64000); + af->dev_info.ext_fmt[fmt_cnt] = ext_fmt; + //af->dev_info.ext_fmt[fmt_cnt].vad = PJ_FALSE; + ++fmt_cnt; + pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_PCMA, + 8000, 1, 16, 20, 64000, 64000); + af->dev_info.ext_fmt[fmt_cnt] = ext_fmt; + //af->dev_info.ext_fmt[fmt_cnt].vad = PJ_FALSE; + ++fmt_cnt; + g711_supported = PJ_TRUE; + break; + case 2: /* G.729 */ + pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_G729, + 8000, 1, 16, 20, 8000, 8000); + af->dev_info.ext_fmt[fmt_cnt] = ext_fmt; + //af->dev_info.ext_fmt[fmt_cnt].vad = PJ_FALSE; + ++fmt_cnt; + break; + case 3: /* iLBC */ + pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_ILBC, + 8000, 1, 16, 30, 13333, 15200); + af->dev_info.ext_fmt[fmt_cnt] = ext_fmt; + //af->dev_info.ext_fmt[fmt_cnt].vad = PJ_TRUE; + ++fmt_cnt; + break; + } + } } af->dev_info.ext_fmt_cnt = fmt_cnt; @@ -1470,8 +1469,8 @@ static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f) /* API: get device info */ static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info) + unsigned index, + pjmedia_aud_dev_info *info) { struct aps_factory *af = (struct aps_factory*)f; @@ -1484,8 +1483,8 @@ static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, /* API: create default device parameter */ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param) + unsigned index, + pjmedia_aud_param *param) { struct aps_factory *af = (struct aps_factory*)f; @@ -1508,11 +1507,11 @@ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, /* API: create stream */ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { struct aps_factory *af = (struct aps_factory*)f; pj_pool_t *pool; @@ -1530,18 +1529,18 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, * - for PCM format: 8kHz and 16kHz */ PJ_ASSERT_RETURN(param->clock_rate == 8000 || - (param->clock_rate == 16000 && - param->ext_fmt.id == PJMEDIA_FORMAT_L16), - PJ_EINVAL); + (param->clock_rate == 16000 && + param->ext_fmt.id == PJMEDIA_FORMAT_L16), + PJ_EINVAL); /* Supported channels number: * - for non-PCM format: mono * - for PCM format: mono and stereo */ PJ_ASSERT_RETURN(param->channel_count == 1 || - (param->channel_count == 2 && - param->ext_fmt.id == PJMEDIA_FORMAT_L16), - PJ_EINVAL); + (param->channel_count == 2 && + param->ext_fmt.id == PJMEDIA_FORMAT_L16), + PJ_EINVAL); /* Create and Initialize stream descriptor */ pool = pj_pool_create(af->pf, "aps-dev", 1000, 1000, NULL); @@ -1552,76 +1551,76 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, strm->param = *param; if (strm->param.flags & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT == 0) - strm->param.ext_fmt.id = PJMEDIA_FORMAT_L16; - + strm->param.ext_fmt.id = PJMEDIA_FORMAT_L16; + /* Set audio engine fourcc. */ switch(strm->param.ext_fmt.id) { case PJMEDIA_FORMAT_L16: case PJMEDIA_FORMAT_PCMU: case PJMEDIA_FORMAT_PCMA: - aps_setting.fourcc = TFourCC(KMCPFourCCIdG711); - break; + aps_setting.fourcc = TFourCC(KMCPFourCCIdG711); + break; case PJMEDIA_FORMAT_AMR: - aps_setting.fourcc = TFourCC(KMCPFourCCIdAMRNB); - break; + aps_setting.fourcc = TFourCC(KMCPFourCCIdAMRNB); + break; case PJMEDIA_FORMAT_G729: - aps_setting.fourcc = TFourCC(KMCPFourCCIdG729); - break; + aps_setting.fourcc = TFourCC(KMCPFourCCIdG729); + break; case PJMEDIA_FORMAT_ILBC: - aps_setting.fourcc = TFourCC(KMCPFourCCIdILBC); - break; + aps_setting.fourcc = TFourCC(KMCPFourCCIdILBC); + break; default: - aps_setting.fourcc = 0; - break; + aps_setting.fourcc = 0; + break; } /* Set audio engine mode. */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_AMR) { - aps_setting.mode = (TAPSCodecMode)strm->param.ext_fmt.det.aud.avg_bps; + aps_setting.mode = (TAPSCodecMode)strm->param.ext_fmt.det.aud.avg_bps; } else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMU || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 || - (strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC && - strm->param.ext_fmt.det.aud.avg_bps != 15200)) + strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 || + (strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC && + strm->param.ext_fmt.det.aud.avg_bps != 15200)) { - aps_setting.mode = EULawOr30ms; + aps_setting.mode = EULawOr30ms; } else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA || - (strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC && - strm->param.ext_fmt.det.aud.avg_bps == 15200)) + (strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC && + strm->param.ext_fmt.det.aud.avg_bps == 15200)) { - aps_setting.mode = EALawOr20ms; + aps_setting.mode = EALawOr20ms; } /* Disable VAD on L16, G711, and also G729 (G729's VAD potentially * causes noise?). */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMU || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_G729) + strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA || + strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 || + strm->param.ext_fmt.id == PJMEDIA_FORMAT_G729) { - aps_setting.vad = EFalse; + aps_setting.vad = EFalse; } else { - aps_setting.vad = (strm->param.flags & PJMEDIA_AUD_DEV_CAP_VAD) && - strm->param.vad_enabled; + aps_setting.vad = (strm->param.flags & PJMEDIA_AUD_DEV_CAP_VAD) && + strm->param.vad_enabled; } /* Set other audio engine attributes. */ aps_setting.plc = (strm->param.flags & PJMEDIA_AUD_DEV_CAP_PLC) && - strm->param.plc_enabled; + strm->param.plc_enabled; aps_setting.cng = aps_setting.vad; aps_setting.loudspk = - strm->param.output_route==PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; + strm->param.output_route==PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; /* Set audio engine callbacks. */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) { - aps_play_cb = &PlayCbPcm; - aps_rec_cb = &RecCbPcm; + aps_play_cb = &PlayCbPcm; + aps_rec_cb = &RecCbPcm; } else { - aps_play_cb = &PlayCb; - aps_rec_cb = &RecCb; + aps_play_cb = &PlayCb; + aps_rec_cb = &RecCb; } strm->rec_cb = rec_cb; @@ -1631,79 +1630,79 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, /* play_buf size is samples per frame scaled in to 8kHz mono. */ strm->play_buf = (pj_int16_t*)pj_pool_zalloc( - pool, - (strm->param.samples_per_frame / - strm->resample_factor / - strm->param.channel_count) << 1); + pool, + (strm->param.samples_per_frame / + strm->resample_factor / + strm->param.channel_count) << 1); strm->play_buf_len = 0; strm->play_buf_start = 0; /* rec_buf size is samples per frame scaled in to 8kHz mono. */ strm->rec_buf = (pj_int16_t*)pj_pool_zalloc( - pool, - (strm->param.samples_per_frame / - strm->resample_factor / - strm->param.channel_count) << 1); + pool, + (strm->param.samples_per_frame / + strm->resample_factor / + strm->param.channel_count) << 1); strm->rec_buf_len = 0; if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_G729) { - TBitStream *g729_bitstream = new TBitStream; - - PJ_ASSERT_RETURN(g729_bitstream, PJ_ENOMEM); - strm->strm_data = (void*)g729_bitstream; + TBitStream *g729_bitstream = new TBitStream; + + PJ_ASSERT_RETURN(g729_bitstream, PJ_ENOMEM); + strm->strm_data = (void*)g729_bitstream; } - + /* Init resampler when format is PCM and clock rate is not 8kHz */ if (strm->param.clock_rate != 8000 && - strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) + strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) { - pj_status_t status; - - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - /* Create resample for recorder */ - status = pjmedia_resample_create( pool, PJ_TRUE, PJ_FALSE, 1, - 8000, - strm->param.clock_rate, - 80, - &strm->rec_resample); - if (status != PJ_SUCCESS) - return status; - } + pj_status_t status; + + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + /* Create resample for recorder */ + status = pjmedia_resample_create( pool, PJ_TRUE, PJ_FALSE, 1, + 8000, + strm->param.clock_rate, + 80, + &strm->rec_resample); + if (status != PJ_SUCCESS) + return status; + } - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - /* Create resample for player */ - status = pjmedia_resample_create( pool, PJ_TRUE, PJ_FALSE, 1, - strm->param.clock_rate, - 8000, - 80 * strm->resample_factor, - &strm->play_resample); - if (status != PJ_SUCCESS) - return status; - } + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + /* Create resample for player */ + status = pjmedia_resample_create( pool, PJ_TRUE, PJ_FALSE, 1, + strm->param.clock_rate, + 8000, + 80 * strm->resample_factor, + &strm->play_resample); + if (status != PJ_SUCCESS) + return status; + } } /* Create PCM buffer, when the clock rate is not 8kHz or not mono */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 && - (strm->resample_factor > 1 || strm->param.channel_count != 1)) + (strm->resample_factor > 1 || strm->param.channel_count != 1)) { - strm->pcm_buf = (pj_int16_t*)pj_pool_zalloc(pool, - strm->param.samples_per_frame << 1); + strm->pcm_buf = (pj_int16_t*)pj_pool_zalloc(pool, + strm->param.samples_per_frame << 1); } /* Create the audio engine. */ TRAPD(err, strm->engine = CPjAudioEngine::NewL(strm, - aps_rec_cb, aps_play_cb, - strm, aps_setting)); + aps_rec_cb, aps_play_cb, + strm, aps_setting)); if (err != KErrNone) { - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err); + pj_pool_release(pool); + return PJ_RETURN_OS_ERROR(err); } /* Apply output volume setting if specified */ if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { - stream_set_cap(&strm->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - ¶m->output_vol); + stream_set_cap(&strm->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + ¶m->output_vol); } /* Done */ @@ -1715,7 +1714,7 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, /* API: Get stream info. */ static pj_status_t stream_get_param(pjmedia_aud_stream *s, - pjmedia_aud_param *pi) + pjmedia_aud_param *pi) { struct aps_stream *strm = (struct aps_stream*)s; @@ -1725,9 +1724,9 @@ static pj_status_t stream_get_param(pjmedia_aud_stream *s, /* Update the output volume setting */ if (stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - &pi->output_vol) == PJ_SUCCESS) + &pi->output_vol) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; + pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; } return PJ_SUCCESS; @@ -1735,8 +1734,8 @@ static pj_status_t stream_get_param(pjmedia_aud_stream *s, /* API: get capability */ static pj_status_t stream_get_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - void *pval) + pjmedia_aud_dev_cap cap, + void *pval) { struct aps_stream *strm = (struct aps_stream*)s; pj_status_t status = PJ_ENOTSUP; @@ -1745,48 +1744,48 @@ static pj_status_t stream_get_cap(pjmedia_aud_stream *s, switch (cap) { case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - *(pjmedia_aud_dev_route*)pval = strm->param.output_route; - status = PJ_SUCCESS; - } - break; + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + *(pjmedia_aud_dev_route*)pval = strm->param.output_route; + status = PJ_SUCCESS; + } + break; /* There is a case that GetMaxGain() stucks, e.g: in N95. */ /* case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_gain = strm->engine->GetMaxGain(); - TInt gain = strm->engine->GetGain(); - - if (max_gain > 0 && gain >= 0) { - *(unsigned*)pval = gain * 100 / max_gain; - status = PJ_SUCCESS; - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + TInt max_gain = strm->engine->GetMaxGain(); + TInt gain = strm->engine->GetGain(); + + if (max_gain > 0 && gain >= 0) { + *(unsigned*)pval = gain * 100 / max_gain; + status = PJ_SUCCESS; + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + break; */ case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_vol = strm->engine->GetMaxVolume(); - TInt vol = strm->engine->GetVolume(); - - if (max_vol > 0 && vol >= 0) { - *(unsigned*)pval = vol * 100 / max_vol; - status = PJ_SUCCESS; - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + TInt max_vol = strm->engine->GetMaxVolume(); + TInt vol = strm->engine->GetVolume(); + + if (max_vol > 0 && vol >= 0) { + *(unsigned*)pval = vol * 100 / max_vol; + status = PJ_SUCCESS; + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + break; default: - break; + break; } return status; @@ -1794,8 +1793,8 @@ static pj_status_t stream_get_cap(pjmedia_aud_stream *s, /* API: set capability */ static pj_status_t stream_set_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - const void *pval) + pjmedia_aud_dev_cap cap, + const void *pval) { struct aps_stream *strm = (struct aps_stream*)s; pj_status_t status = PJ_ENOTSUP; @@ -1804,73 +1803,73 @@ static pj_status_t stream_set_cap(pjmedia_aud_stream *s, switch (cap) { case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - pjmedia_aud_dev_route r = *(const pjmedia_aud_dev_route*)pval; - TInt err; - - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - switch (r) { - case PJMEDIA_AUD_DEV_ROUTE_DEFAULT: - case PJMEDIA_AUD_DEV_ROUTE_EARPIECE: - err = strm->engine->ActivateSpeaker(EFalse); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - break; - case PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER: - err = strm->engine->ActivateSpeaker(ETrue); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - break; - default: - status = PJ_EINVAL; - break; - } - if (status == PJ_SUCCESS) - strm->param.output_route = r; - } - break; + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + pjmedia_aud_dev_route r = *(const pjmedia_aud_dev_route*)pval; + TInt err; + + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + switch (r) { + case PJMEDIA_AUD_DEV_ROUTE_DEFAULT: + case PJMEDIA_AUD_DEV_ROUTE_EARPIECE: + err = strm->engine->ActivateSpeaker(EFalse); + status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); + break; + case PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER: + err = strm->engine->ActivateSpeaker(ETrue); + status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); + break; + default: + status = PJ_EINVAL; + break; + } + if (status == PJ_SUCCESS) + strm->param.output_route = r; + } + break; /* There is a case that GetMaxGain() stucks, e.g: in N95. */ /* case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_gain = strm->engine->GetMaxGain(); - if (max_gain > 0) { - TInt gain, err; - - gain = *(unsigned*)pval * max_gain / 100; - err = strm->engine->SetGain(gain); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - if (status == PJ_SUCCESS) - strm->param.input_vol = *(unsigned*)pval; - } - break; + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + TInt max_gain = strm->engine->GetMaxGain(); + if (max_gain > 0) { + TInt gain, err; + + gain = *(unsigned*)pval * max_gain / 100; + err = strm->engine->SetGain(gain); + status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + if (status == PJ_SUCCESS) + strm->param.input_vol = *(unsigned*)pval; + } + break; */ case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_vol = strm->engine->GetMaxVolume(); - if (max_vol > 0) { - TInt vol, err; - - vol = *(unsigned*)pval * max_vol / 100; - err = strm->engine->SetVolume(vol); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - if (status == PJ_SUCCESS) - strm->param.output_vol = *(unsigned*)pval; - } - break; + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + TInt max_vol = strm->engine->GetMaxVolume(); + if (max_vol > 0) { + TInt vol, err; + + vol = *(unsigned*)pval * max_vol / 100; + err = strm->engine->SetVolume(vol); + status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + if (status == PJ_SUCCESS) + strm->param.output_vol = *(unsigned*)pval; + } + break; default: - break; + break; } return status; @@ -1884,9 +1883,9 @@ static pj_status_t stream_start(pjmedia_aud_stream *strm) PJ_ASSERT_RETURN(stream, PJ_EINVAL); if (stream->engine) { - TInt err = stream->engine->StartL(); - if (err != KErrNone) - return PJ_RETURN_OS_ERROR(err); + TInt err = stream->engine->StartL(); + if (err != KErrNone) + return PJ_RETURN_OS_ERROR(err); } return PJ_SUCCESS; @@ -1900,7 +1899,7 @@ static pj_status_t stream_stop(pjmedia_aud_stream *strm) PJ_ASSERT_RETURN(stream, PJ_EINVAL); if (stream->engine) { - stream->engine->Stop(); + stream->engine->Stop(); } return PJ_SUCCESS; @@ -1920,16 +1919,16 @@ static pj_status_t stream_destroy(pjmedia_aud_stream *strm) stream->engine = NULL; if (stream->param.ext_fmt.id == PJMEDIA_FORMAT_G729) { - TBitStream *g729_bitstream = (TBitStream*)stream->strm_data; - stream->strm_data = NULL; - delete g729_bitstream; + TBitStream *g729_bitstream = (TBitStream*)stream->strm_data; + stream->strm_data = NULL; + delete g729_bitstream; } pj_pool_t *pool; pool = stream->pool; if (pool) { - stream->pool = NULL; - pj_pool_release(pool); + stream->pool = NULL; + pj_pool_release(pool); } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia-audiodev/symb_mda_dev.cpp b/pjmedia/src/pjmedia-audiodev/symb_mda_dev.cpp index 645ed39453..92493dbdf4 100644 --- a/pjmedia/src/pjmedia-audiodev/symb_mda_dev.cpp +++ b/pjmedia/src/pjmedia-audiodev/symb_mda_dev.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,9 +38,9 @@ #include -#define THIS_FILE "symb_mda_dev.c" -#define BITS_PER_SAMPLE 16 -#define BYTES_PER_SAMPLE (BITS_PER_SAMPLE/8) +#define THIS_FILE "symb_mda_dev.c" +#define BITS_PER_SAMPLE 16 +#define BYTES_PER_SAMPLE (BITS_PER_SAMPLE/8) #if 1 @@ -54,10 +53,10 @@ /* MDA factory */ struct mda_factory { - pjmedia_aud_dev_factory base; - pj_pool_t *pool; - pj_pool_factory *pf; - pjmedia_aud_dev_info dev_info; + pjmedia_aud_dev_factory base; + pj_pool_t *pool; + pj_pool_factory *pf; + pjmedia_aud_dev_info dev_info; }; /* Forward declaration of internal engine. */ @@ -68,17 +67,17 @@ class CPjAudioOutputEngine; struct mda_stream { // Base - pjmedia_aud_stream base; /**< Base class. */ + pjmedia_aud_stream base; /**< Base class. */ // Pool - pj_pool_t *pool; /**< Memory pool. */ + pj_pool_t *pool; /**< Memory pool. */ // Common settings. - pjmedia_aud_param param; /**< Stream param. */ + pjmedia_aud_param param; /**< Stream param. */ // Audio engine - CPjAudioInputEngine *in_engine; /**< Record engine. */ - CPjAudioOutputEngine *out_engine; /**< Playback engine. */ + CPjAudioInputEngine *in_engine; /**< Record engine. */ + CPjAudioOutputEngine *out_engine; /**< Playback engine. */ }; @@ -88,26 +87,26 @@ static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f); static pj_status_t factory_refresh(pjmedia_aud_dev_factory *f); static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f); static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); + unsigned index, + pjmedia_aud_dev_info *info); static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); + unsigned index, + pjmedia_aud_param *param); static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); static pj_status_t stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); + pjmedia_aud_param *param); static pj_status_t stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); + pjmedia_aud_dev_cap cap, + void *value); static pj_status_t stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); + pjmedia_aud_dev_cap cap, + const void *value); static pj_status_t stream_start(pjmedia_aud_stream *strm); static pj_status_t stream_stop(pjmedia_aud_stream *strm); static pj_status_t stream_destroy(pjmedia_aud_stream *strm); @@ -154,7 +153,7 @@ static TInt get_clock_rate_cap(unsigned clock_rate) case 64000: return TMdaAudioDataSettings::ESampleRate64000Hz; case 96000: return TMdaAudioDataSettings::ESampleRate96000Hz; default: - return 0; + return 0; } } @@ -167,7 +166,7 @@ static TInt get_channel_cap(unsigned channel_count) case 1: return TMdaAudioDataSettings::EChannelsMono; case 2: return TMdaAudioDataSettings::EChannelsStereo; default: - return 0; + return 0; } } @@ -190,70 +189,70 @@ class CPjAudioInputEngine : public CBase, MMdaAudioInputStreamCallback public: enum State { - STATE_INACTIVE, - STATE_ACTIVE, + STATE_INACTIVE, + STATE_ACTIVE, }; ~CPjAudioInputEngine(); static CPjAudioInputEngine *NewL(struct mda_stream *parent_strm, - pjmedia_aud_rec_cb rec_cb, - void *user_data); + pjmedia_aud_rec_cb rec_cb, + void *user_data); static CPjAudioInputEngine *NewLC(struct mda_stream *parent_strm, - pjmedia_aud_rec_cb rec_cb, - void *user_data); + pjmedia_aud_rec_cb rec_cb, + void *user_data); pj_status_t StartRecord(); void Stop(); pj_status_t SetGain(TInt gain) { - if (iInputStream_) { - iInputStream_->SetGain(gain); - return PJ_SUCCESS; - } else - return PJ_EINVALIDOP; + if (iInputStream_) { + iInputStream_->SetGain(gain); + return PJ_SUCCESS; + } else + return PJ_EINVALIDOP; } TInt GetGain() { - if (iInputStream_) { - return iInputStream_->Gain(); - } else - return PJ_EINVALIDOP; + if (iInputStream_) { + return iInputStream_->Gain(); + } else + return PJ_EINVALIDOP; } TInt GetMaxGain() { - if (iInputStream_) { - return iInputStream_->MaxGain(); - } else - return PJ_EINVALIDOP; + if (iInputStream_) { + return iInputStream_->MaxGain(); + } else + return PJ_EINVALIDOP; } private: - State state_; - struct mda_stream *parentStrm_; - pjmedia_aud_rec_cb recCb_; - void *userData_; + State state_; + struct mda_stream *parentStrm_; + pjmedia_aud_rec_cb recCb_; + void *userData_; CMdaAudioInputStream *iInputStream_; - HBufC8 *iStreamBuffer_; - TPtr8 iFramePtr_; - TInt lastError_; - pj_uint32_t timeStamp_; + HBufC8 *iStreamBuffer_; + TPtr8 iFramePtr_; + TInt lastError_; + pj_uint32_t timeStamp_; CActiveSchedulerWait startAsw_; // cache variable // to avoid calculating frame length repeatedly - TInt frameLen_; + TInt frameLen_; // sometimes recorded size != requested framesize, so let's // provide a buffer to make sure the rec callback returning // framesize as requested. - TUint8 *frameRecBuf_; - TInt frameRecBufLen_; + TUint8 *frameRecBuf_; + TInt frameRecBufLen_; CPjAudioInputEngine(struct mda_stream *parent_strm, - pjmedia_aud_rec_cb rec_cb, - void *user_data); + pjmedia_aud_rec_cb rec_cb, + void *user_data); void ConstructL(); TPtr8 & GetFrame(); @@ -266,14 +265,14 @@ class CPjAudioInputEngine : public CBase, MMdaAudioInputStreamCallback CPjAudioInputEngine::CPjAudioInputEngine(struct mda_stream *parent_strm, - pjmedia_aud_rec_cb rec_cb, - void *user_data) + pjmedia_aud_rec_cb rec_cb, + void *user_data) : state_(STATE_INACTIVE), parentStrm_(parent_strm), recCb_(rec_cb), userData_(user_data), iInputStream_(NULL), iStreamBuffer_(NULL), iFramePtr_(0, 0), lastError_(KErrNone), timeStamp_(0), frameLen_(parent_strm->param.samples_per_frame * - BYTES_PER_SAMPLE), + BYTES_PER_SAMPLE), frameRecBuf_(NULL), frameRecBufLen_(0) { } @@ -300,20 +299,20 @@ void CPjAudioInputEngine::ConstructL() } CPjAudioInputEngine *CPjAudioInputEngine::NewLC(struct mda_stream *parent, - pjmedia_aud_rec_cb rec_cb, - void *user_data) + pjmedia_aud_rec_cb rec_cb, + void *user_data) { CPjAudioInputEngine* self = new (ELeave) CPjAudioInputEngine(parent, - rec_cb, - user_data); + rec_cb, + user_data); CleanupStack::PushL(self); self->ConstructL(); return self; } CPjAudioInputEngine *CPjAudioInputEngine::NewL(struct mda_stream *parent, - pjmedia_aud_rec_cb rec_cb, - void *user_data) + pjmedia_aud_rec_cb rec_cb, + void *user_data) { CPjAudioInputEngine *self = NewLC(parent, rec_cb, user_data); CleanupStack::Pop(self->frameRecBuf_); @@ -328,7 +327,7 @@ pj_status_t CPjAudioInputEngine::StartRecord() // Ignore command if recording is in progress. if (state_ == STATE_ACTIVE) - return PJ_SUCCESS; + return PJ_SUCCESS; // According to Nokia's AudioStream example, some 2nd Edition, FP2 devices // (such as Nokia 6630) require the stream to be reconstructed each time @@ -343,22 +342,22 @@ pj_status_t CPjAudioInputEngine::StartRecord() // Create the stream. TRAPD(err, iInputStream_ = CMdaAudioInputStream::NewL(*this)); if (err != KErrNone) - return PJ_RETURN_OS_ERROR(err); + return PJ_RETURN_OS_ERROR(err); // Initialize settings. TMdaAudioDataSettings iStreamSettings; iStreamSettings.iChannels = - get_channel_cap(parentStrm_->param.channel_count); + get_channel_cap(parentStrm_->param.channel_count); iStreamSettings.iSampleRate = - get_clock_rate_cap(parentStrm_->param.clock_rate); + get_clock_rate_cap(parentStrm_->param.clock_rate); pj_assert(iStreamSettings.iChannels != 0 && - iStreamSettings.iSampleRate != 0); + iStreamSettings.iSampleRate != 0); PJ_LOG(4,(THIS_FILE, "Opening sound device for capture, " - "clock rate=%d, channel count=%d..", - parentStrm_->param.clock_rate, - parentStrm_->param.channel_count)); + "clock rate=%d, channel count=%d..", + parentStrm_->param.clock_rate, + parentStrm_->param.channel_count)); // Open stream. lastError_ = KRequestPending; @@ -381,21 +380,21 @@ void CPjAudioInputEngine::Stop() { // If capture is in progress, stop it. if (iInputStream_ && state_ == STATE_ACTIVE) { - lastError_ = KRequestPending; - iInputStream_->Stop(); + lastError_ = KRequestPending; + iInputStream_->Stop(); - // Wait until it's actually stopped - while (lastError_ == KRequestPending) - pj_symbianos_poll(-1, 100); + // Wait until it's actually stopped + while (lastError_ == KRequestPending) + pj_symbianos_poll(-1, 100); } if (iInputStream_) { - delete iInputStream_; - iInputStream_ = NULL; + delete iInputStream_; + iInputStream_ = NULL; } if (startAsw_.IsStarted()) { - startAsw_.AsyncStop(); + startAsw_.AsyncStop(); } state_ = STATE_INACTIVE; @@ -412,13 +411,13 @@ TPtr8 & CPjAudioInputEngine::GetFrame() void CPjAudioInputEngine::MaiscOpenComplete(TInt aError) { if (startAsw_.IsStarted()) { - startAsw_.AsyncStop(); + startAsw_.AsyncStop(); } lastError_ = aError; if (aError != KErrNone) { snd_perror("Error in MaiscOpenComplete()", aError); - return; + return; } /* Apply input volume setting if specified */ @@ -432,15 +431,15 @@ void CPjAudioInputEngine::MaiscOpenComplete(TInt aError) // set stream priority to normal and time sensitive iInputStream_->SetPriority(EPriorityNormal, - EMdaPriorityPreferenceTime); + EMdaPriorityPreferenceTime); // Read the first frame. TPtr8 & frm = GetFrame(); TRAPD(err2, iInputStream_->ReadL(frm)); if (err2) { - PJ_LOG(4,(THIS_FILE, "Exception in iInputStream_->ReadL()")); - lastError_ = err2; - return; + PJ_LOG(4,(THIS_FILE, "Exception in iInputStream_->ReadL()")); + lastError_ = err2; + return; } // input stream opened succesfully, set status to Active @@ -448,58 +447,58 @@ void CPjAudioInputEngine::MaiscOpenComplete(TInt aError) } void CPjAudioInputEngine::MaiscBufferCopied(TInt aError, - const TDesC8 &aBuffer) + const TDesC8 &aBuffer) { lastError_ = aError; if (aError != KErrNone) { - snd_perror("Error in MaiscBufferCopied()", aError); - return; + snd_perror("Error in MaiscBufferCopied()", aError); + return; } if (frameRecBufLen_ || aBuffer.Length() < frameLen_) { - pj_memcpy(frameRecBuf_ + frameRecBufLen_, (void*) aBuffer.Ptr(), aBuffer.Length()); - frameRecBufLen_ += aBuffer.Length(); + pj_memcpy(frameRecBuf_ + frameRecBufLen_, (void*) aBuffer.Ptr(), aBuffer.Length()); + frameRecBufLen_ += aBuffer.Length(); } if (frameRecBufLen_) { - while (frameRecBufLen_ >= frameLen_) { - pjmedia_frame f; - - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.buf = frameRecBuf_; - f.size = frameLen_; - f.timestamp.u32.lo = timeStamp_; - f.bit_info = 0; - - // Call the callback. - recCb_(userData_, &f); - // Increment timestamp. - timeStamp_ += parentStrm_->param.samples_per_frame; - - frameRecBufLen_ -= frameLen_; - pj_memmove(frameRecBuf_, frameRecBuf_+frameLen_, frameRecBufLen_); - } + while (frameRecBufLen_ >= frameLen_) { + pjmedia_frame f; + + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + f.buf = frameRecBuf_; + f.size = frameLen_; + f.timestamp.u32.lo = timeStamp_; + f.bit_info = 0; + + // Call the callback. + recCb_(userData_, &f); + // Increment timestamp. + timeStamp_ += parentStrm_->param.samples_per_frame; + + frameRecBufLen_ -= frameLen_; + pj_memmove(frameRecBuf_, frameRecBuf_+frameLen_, frameRecBufLen_); + } } else { - pjmedia_frame f; - - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.buf = (void*)aBuffer.Ptr(); - f.size = aBuffer.Length(); - f.timestamp.u32.lo = timeStamp_; - f.bit_info = 0; - - // Call the callback. - recCb_(userData_, &f); - - // Increment timestamp. - timeStamp_ += parentStrm_->param.samples_per_frame; + pjmedia_frame f; + + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + f.buf = (void*)aBuffer.Ptr(); + f.size = aBuffer.Length(); + f.timestamp.u32.lo = timeStamp_; + f.bit_info = 0; + + // Call the callback. + recCb_(userData_, &f); + + // Increment timestamp. + timeStamp_ += parentStrm_->param.samples_per_frame; } // Record next frame TPtr8 & frm = GetFrame(); TRAPD(err2, iInputStream_->ReadL(frm)); if (err2) { - PJ_LOG(4,(THIS_FILE, "Exception in iInputStream_->ReadL()")); + PJ_LOG(4,(THIS_FILE, "Exception in iInputStream_->ReadL()")); } } @@ -509,7 +508,7 @@ void CPjAudioInputEngine::MaiscRecordComplete(TInt aError) lastError_ = aError; state_ = STATE_INACTIVE; if (aError != KErrNone && aError != KErrCancel) { - snd_perror("Error in MaiscRecordComplete()", aError); + snd_perror("Error in MaiscRecordComplete()", aError); } } @@ -527,61 +526,61 @@ class CPjAudioOutputEngine : public CBase, MMdaAudioOutputStreamCallback public: enum State { - STATE_INACTIVE, - STATE_ACTIVE, + STATE_INACTIVE, + STATE_ACTIVE, }; ~CPjAudioOutputEngine(); static CPjAudioOutputEngine *NewL(struct mda_stream *parent_strm, - pjmedia_aud_play_cb play_cb, - void *user_data); + pjmedia_aud_play_cb play_cb, + void *user_data); static CPjAudioOutputEngine *NewLC(struct mda_stream *parent_strm, - pjmedia_aud_play_cb rec_cb, - void *user_data); + pjmedia_aud_play_cb rec_cb, + void *user_data); pj_status_t StartPlay(); void Stop(); pj_status_t SetVolume(TInt vol) { - if (iOutputStream_) { - iOutputStream_->SetVolume(vol); - return PJ_SUCCESS; - } else - return PJ_EINVALIDOP; + if (iOutputStream_) { + iOutputStream_->SetVolume(vol); + return PJ_SUCCESS; + } else + return PJ_EINVALIDOP; } TInt GetVolume() { - if (iOutputStream_) { - return iOutputStream_->Volume(); - } else - return PJ_EINVALIDOP; + if (iOutputStream_) { + return iOutputStream_->Volume(); + } else + return PJ_EINVALIDOP; } TInt GetMaxVolume() { - if (iOutputStream_) { - return iOutputStream_->MaxVolume(); - } else - return PJ_EINVALIDOP; + if (iOutputStream_) { + return iOutputStream_->MaxVolume(); + } else + return PJ_EINVALIDOP; } private: - State state_; - struct mda_stream *parentStrm_; - pjmedia_aud_play_cb playCb_; - void *userData_; + State state_; + struct mda_stream *parentStrm_; + pjmedia_aud_play_cb playCb_; + void *userData_; CMdaAudioOutputStream *iOutputStream_; - TUint8 *frameBuf_; - unsigned frameBufSize_; - TPtrC8 frame_; - TInt lastError_; - unsigned timestamp_; + TUint8 *frameBuf_; + unsigned frameBufSize_; + TPtrC8 frame_; + TInt lastError_; + unsigned timestamp_; CActiveSchedulerWait startAsw_; CPjAudioOutputEngine(struct mda_stream *parent_strm, - pjmedia_aud_play_cb play_cb, - void *user_data); + pjmedia_aud_play_cb play_cb, + void *user_data); void ConstructL(); virtual void MaoscOpenComplete(TInt aError); @@ -591,8 +590,8 @@ class CPjAudioOutputEngine : public CBase, MMdaAudioOutputStreamCallback CPjAudioOutputEngine::CPjAudioOutputEngine(struct mda_stream *parent_strm, - pjmedia_aud_play_cb play_cb, - void *user_data) + pjmedia_aud_play_cb play_cb, + void *user_data) : state_(STATE_INACTIVE), parentStrm_(parent_strm), playCb_(play_cb), userData_(user_data), iOutputStream_(NULL), frameBuf_(NULL), lastError_(KErrNone), timestamp_(0) @@ -603,24 +602,24 @@ CPjAudioOutputEngine::CPjAudioOutputEngine(struct mda_stream *parent_strm, void CPjAudioOutputEngine::ConstructL() { frameBufSize_ = parentStrm_->param.samples_per_frame * - BYTES_PER_SAMPLE; + BYTES_PER_SAMPLE; frameBuf_ = new TUint8[frameBufSize_]; } CPjAudioOutputEngine::~CPjAudioOutputEngine() { Stop(); - delete [] frameBuf_; + delete [] frameBuf_; } CPjAudioOutputEngine * CPjAudioOutputEngine::NewLC(struct mda_stream *parent_strm, - pjmedia_aud_play_cb play_cb, - void *user_data) + pjmedia_aud_play_cb play_cb, + void *user_data) { CPjAudioOutputEngine* self = new (ELeave) CPjAudioOutputEngine(parent_strm, - play_cb, - user_data); + play_cb, + user_data); CleanupStack::PushL(self); self->ConstructL(); return self; @@ -628,8 +627,8 @@ CPjAudioOutputEngine::NewLC(struct mda_stream *parent_strm, CPjAudioOutputEngine * CPjAudioOutputEngine::NewL(struct mda_stream *parent_strm, - pjmedia_aud_play_cb play_cb, - void *user_data) + pjmedia_aud_play_cb play_cb, + void *user_data) { CPjAudioOutputEngine *self = NewLC(parent_strm, play_cb, user_data); CleanupStack::Pop(self); @@ -640,7 +639,7 @@ pj_status_t CPjAudioOutputEngine::StartPlay() { // Ignore command if playing is in progress. if (state_ == STATE_ACTIVE) - return PJ_SUCCESS; + return PJ_SUCCESS; // Destroy existing stream. if (iOutputStream_) delete iOutputStream_; @@ -649,22 +648,22 @@ pj_status_t CPjAudioOutputEngine::StartPlay() // Create the stream TRAPD(err, iOutputStream_ = CMdaAudioOutputStream::NewL(*this)); if (err != KErrNone) - return PJ_RETURN_OS_ERROR(err); + return PJ_RETURN_OS_ERROR(err); // Initialize settings. TMdaAudioDataSettings iStreamSettings; iStreamSettings.iChannels = - get_channel_cap(parentStrm_->param.channel_count); + get_channel_cap(parentStrm_->param.channel_count); iStreamSettings.iSampleRate = - get_clock_rate_cap(parentStrm_->param.clock_rate); + get_clock_rate_cap(parentStrm_->param.clock_rate); pj_assert(iStreamSettings.iChannels != 0 && - iStreamSettings.iSampleRate != 0); + iStreamSettings.iSampleRate != 0); PJ_LOG(4,(THIS_FILE, "Opening sound device for playback, " - "clock rate=%d, channel count=%d..", - parentStrm_->param.clock_rate, - parentStrm_->param.channel_count)); + "clock rate=%d, channel count=%d..", + parentStrm_->param.clock_rate, + parentStrm_->param.channel_count)); // Open stream. lastError_ = KRequestPending; @@ -687,21 +686,21 @@ void CPjAudioOutputEngine::Stop() { // Stop stream if it's playing if (iOutputStream_ && state_ != STATE_INACTIVE) { - lastError_ = KRequestPending; - iOutputStream_->Stop(); + lastError_ = KRequestPending; + iOutputStream_->Stop(); - // Wait until it's actually stopped - while (lastError_ == KRequestPending) - pj_symbianos_poll(-1, 100); + // Wait until it's actually stopped + while (lastError_ == KRequestPending) + pj_symbianos_poll(-1, 100); } - if (iOutputStream_) { - delete iOutputStream_; - iOutputStream_ = NULL; + if (iOutputStream_) { + delete iOutputStream_; + iOutputStream_ = NULL; } if (startAsw_.IsStarted()) { - startAsw_.AsyncStop(); + startAsw_.AsyncStop(); } state_ = STATE_INACTIVE; @@ -710,21 +709,21 @@ void CPjAudioOutputEngine::Stop() void CPjAudioOutputEngine::MaoscOpenComplete(TInt aError) { if (startAsw_.IsStarted()) { - startAsw_.AsyncStop(); + startAsw_.AsyncStop(); } lastError_ = aError; if (aError==KErrNone) { - // set stream properties, 16bit 8KHz mono - TMdaAudioDataSettings iSettings; - iSettings.iChannels = - get_channel_cap(parentStrm_->param.channel_count); - iSettings.iSampleRate = - get_clock_rate_cap(parentStrm_->param.clock_rate); + // set stream properties, 16bit 8KHz mono + TMdaAudioDataSettings iSettings; + iSettings.iChannels = + get_channel_cap(parentStrm_->param.channel_count); + iSettings.iSampleRate = + get_clock_rate_cap(parentStrm_->param.clock_rate); - iOutputStream_->SetAudioPropertiesL(iSettings.iSampleRate, - iSettings.iChannels); + iOutputStream_->SetAudioPropertiesL(iSettings.iSampleRate, + iSettings.iChannels); /* Apply output volume setting if specified */ if (parentStrm_->param.flags & @@ -737,89 +736,89 @@ void CPjAudioOutputEngine::MaoscOpenComplete(TInt aError) // set volume to 1/2th of stream max volume iOutputStream_->SetVolume(iOutputStream_->MaxVolume()/2); } - - // set stream priority to normal and time sensitive - iOutputStream_->SetPriority(EPriorityNormal, - EMdaPriorityPreferenceTime); - - // Call callback to retrieve frame from upstream. - pjmedia_frame f; - pj_status_t status; - - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.buf = frameBuf_; - f.size = frameBufSize_; - f.timestamp.u32.lo = timestamp_; - f.bit_info = 0; - - status = playCb_(this->userData_, &f); - if (status != PJ_SUCCESS) { - this->Stop(); - return; - } - - if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) - pj_bzero(frameBuf_, frameBufSize_); - - // Increment timestamp. - timestamp_ += (frameBufSize_ / BYTES_PER_SAMPLE); - - // issue WriteL() to write the first audio data block, - // subsequent calls to WriteL() will be issued in - // MMdaAudioOutputStreamCallback::MaoscBufferCopied() - // until whole data buffer is written. - frame_.Set(frameBuf_, frameBufSize_); - iOutputStream_->WriteL(frame_); - - // output stream opened succesfully, set status to Active - state_ = STATE_ACTIVE; + + // set stream priority to normal and time sensitive + iOutputStream_->SetPriority(EPriorityNormal, + EMdaPriorityPreferenceTime); + + // Call callback to retrieve frame from upstream. + pjmedia_frame f; + pj_status_t status; + + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + f.buf = frameBuf_; + f.size = frameBufSize_; + f.timestamp.u32.lo = timestamp_; + f.bit_info = 0; + + status = playCb_(this->userData_, &f); + if (status != PJ_SUCCESS) { + this->Stop(); + return; + } + + if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) + pj_bzero(frameBuf_, frameBufSize_); + + // Increment timestamp. + timestamp_ += (frameBufSize_ / BYTES_PER_SAMPLE); + + // issue WriteL() to write the first audio data block, + // subsequent calls to WriteL() will be issued in + // MMdaAudioOutputStreamCallback::MaoscBufferCopied() + // until whole data buffer is written. + frame_.Set(frameBuf_, frameBufSize_); + iOutputStream_->WriteL(frame_); + + // output stream opened succesfully, set status to Active + state_ = STATE_ACTIVE; } else { - snd_perror("Error in MaoscOpenComplete()", aError); + snd_perror("Error in MaoscOpenComplete()", aError); } } void CPjAudioOutputEngine::MaoscBufferCopied(TInt aError, - const TDesC8& aBuffer) + const TDesC8& aBuffer) { PJ_UNUSED_ARG(aBuffer); if (aError==KErrNone) { - // Buffer successfully written, feed another one. - - // Call callback to retrieve frame from upstream. - pjmedia_frame f; - pj_status_t status; - - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.buf = frameBuf_; - f.size = frameBufSize_; - f.timestamp.u32.lo = timestamp_; - f.bit_info = 0; - - status = playCb_(this->userData_, &f); - if (status != PJ_SUCCESS) { - this->Stop(); - return; - } - - if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) - pj_bzero(frameBuf_, frameBufSize_); - - // Increment timestamp. - timestamp_ += (frameBufSize_ / BYTES_PER_SAMPLE); - - // Write to playback stream. - frame_.Set(frameBuf_, frameBufSize_); - iOutputStream_->WriteL(frame_); + // Buffer successfully written, feed another one. + + // Call callback to retrieve frame from upstream. + pjmedia_frame f; + pj_status_t status; + + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + f.buf = frameBuf_; + f.size = frameBufSize_; + f.timestamp.u32.lo = timestamp_; + f.bit_info = 0; + + status = playCb_(this->userData_, &f); + if (status != PJ_SUCCESS) { + this->Stop(); + return; + } + + if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) + pj_bzero(frameBuf_, frameBufSize_); + + // Increment timestamp. + timestamp_ += (frameBufSize_ / BYTES_PER_SAMPLE); + + // Write to playback stream. + frame_.Set(frameBuf_, frameBufSize_); + iOutputStream_->WriteL(frame_); } else if (aError==KErrAbort) { - // playing was aborted, due to call to CMdaAudioOutputStream::Stop() - state_ = STATE_INACTIVE; + // playing was aborted, due to call to CMdaAudioOutputStream::Stop() + state_ = STATE_INACTIVE; } else { - // error writing data to output - lastError_ = aError; - state_ = STATE_INACTIVE; - snd_perror("Error in MaoscBufferCopied()", aError); + // error writing data to output + lastError_ = aError; + state_ = STATE_INACTIVE; + snd_perror("Error in MaoscBufferCopied()", aError); } } @@ -828,7 +827,7 @@ void CPjAudioOutputEngine::MaoscPlayComplete(TInt aError) lastError_ = aError; state_ = STATE_INACTIVE; if (aError != KErrNone && aError != KErrCancel) { - snd_perror("Error in MaoscPlayComplete()", aError); + snd_perror("Error in MaoscPlayComplete()", aError); } } @@ -868,7 +867,7 @@ static pj_status_t factory_init(pjmedia_aud_dev_factory *f) pj_ansi_strcpy(af->dev_info.name, "Symbian Audio"); af->dev_info.default_samples_per_sec = 8000; af->dev_info.caps = PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING | - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; af->dev_info.input_count = 1; af->dev_info.output_count = 1; @@ -907,8 +906,8 @@ static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f) /* API: get device info */ static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info) + unsigned index, + pjmedia_aud_dev_info *info) { struct mda_factory *af = (struct mda_factory*)f; @@ -921,8 +920,8 @@ static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, /* API: create default device parameter */ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param) + unsigned index, + pjmedia_aud_param *param) { struct mda_factory *af = (struct mda_factory*)f; @@ -945,11 +944,11 @@ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, /* API: create stream */ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { struct mda_factory *mf = (struct mda_factory*)f; pj_pool_t *pool; @@ -958,8 +957,8 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, /* Can only support 16bits per sample raw PCM format. */ PJ_ASSERT_RETURN(param->bits_per_sample == BITS_PER_SAMPLE, PJ_EINVAL); PJ_ASSERT_RETURN((param->flags & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT)==0 || - param->ext_fmt.id == PJMEDIA_FORMAT_L16, - PJ_ENOTSUP); + param->ext_fmt.id == PJMEDIA_FORMAT_L16, + PJ_ENOTSUP); /* It seems that MDA recorder only supports for mono channel. */ PJ_ASSERT_RETURN(param->channel_count == 1, PJ_EINVAL); @@ -974,27 +973,27 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, // Create the output stream. if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - TRAPD(err, strm->out_engine = CPjAudioOutputEngine::NewL(strm, play_cb, - user_data)); - if (err != KErrNone) { - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err); - } + TRAPD(err, strm->out_engine = CPjAudioOutputEngine::NewL(strm, play_cb, + user_data)); + if (err != KErrNone) { + pj_pool_release(pool); + return PJ_RETURN_OS_ERROR(err); + } } // Create the input stream. if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - TRAPD(err, strm->in_engine = CPjAudioInputEngine::NewL(strm, rec_cb, - user_data)); - if (err != KErrNone) { - strm->in_engine = NULL; - delete strm->out_engine; - strm->out_engine = NULL; - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err); - } + TRAPD(err, strm->in_engine = CPjAudioInputEngine::NewL(strm, rec_cb, + user_data)); + if (err != KErrNone) { + strm->in_engine = NULL; + delete strm->out_engine; + strm->out_engine = NULL; + pj_pool_release(pool); + return PJ_RETURN_OS_ERROR(err); + } } - + /* Done */ strm->base.op = &stream_op; *p_aud_strm = &strm->base; @@ -1004,7 +1003,7 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, /* API: Get stream info. */ static pj_status_t stream_get_param(pjmedia_aud_stream *s, - pjmedia_aud_param *pi) + pjmedia_aud_param *pi) { struct mda_stream *strm = (struct mda_stream*)s; @@ -1014,16 +1013,16 @@ static pj_status_t stream_get_param(pjmedia_aud_stream *s, /* Update the output volume setting */ if (stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - &pi->output_vol) == PJ_SUCCESS) + &pi->output_vol) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; + pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; } /* Update the input volume setting */ if (stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING, - &pi->input_vol) == PJ_SUCCESS) + &pi->input_vol) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING; + pi->flags |= PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING; } return PJ_SUCCESS; @@ -1031,8 +1030,8 @@ static pj_status_t stream_get_param(pjmedia_aud_stream *s, /* API: get capability */ static pj_status_t stream_get_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - void *pval) + pjmedia_aud_dev_cap cap, + void *pval) { struct mda_stream *strm = (struct mda_stream*)s; pj_status_t status = PJ_ENOTSUP; @@ -1041,37 +1040,37 @@ static pj_status_t stream_get_cap(pjmedia_aud_stream *s, switch (cap) { case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->in_engine, PJ_EINVAL); - - TInt max_gain = strm->in_engine->GetMaxGain(); - TInt gain = strm->in_engine->GetGain(); - - if (max_gain > 0 && gain >= 0) { - *(unsigned*)pval = gain * 100 / max_gain; - status = PJ_SUCCESS; - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN(strm->in_engine, PJ_EINVAL); + + TInt max_gain = strm->in_engine->GetMaxGain(); + TInt gain = strm->in_engine->GetGain(); + + if (max_gain > 0 && gain >= 0) { + *(unsigned*)pval = gain * 100 / max_gain; + status = PJ_SUCCESS; + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + break; case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - PJ_ASSERT_RETURN(strm->out_engine, PJ_EINVAL); - - TInt max_vol = strm->out_engine->GetMaxVolume(); - TInt vol = strm->out_engine->GetVolume(); - - if (max_vol > 0 && vol >= 0) { - *(unsigned*)pval = vol * 100 / max_vol; - status = PJ_SUCCESS; - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + PJ_ASSERT_RETURN(strm->out_engine, PJ_EINVAL); + + TInt max_vol = strm->out_engine->GetMaxVolume(); + TInt vol = strm->out_engine->GetVolume(); + + if (max_vol > 0 && vol >= 0) { + *(unsigned*)pval = vol * 100 / max_vol; + status = PJ_SUCCESS; + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + break; default: - break; + break; } return status; @@ -1079,8 +1078,8 @@ static pj_status_t stream_get_cap(pjmedia_aud_stream *s, /* API: set capability */ static pj_status_t stream_set_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - const void *pval) + pjmedia_aud_dev_cap cap, + const void *pval) { struct mda_stream *strm = (struct mda_stream*)s; pj_status_t status = PJ_ENOTSUP; @@ -1089,37 +1088,37 @@ static pj_status_t stream_set_cap(pjmedia_aud_stream *s, switch (cap) { case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->in_engine, PJ_EINVAL); - - TInt max_gain = strm->in_engine->GetMaxGain(); - if (max_gain > 0) { - TInt gain; - - gain = *(unsigned*)pval * max_gain / 100; - status = strm->in_engine->SetGain(gain); - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN(strm->in_engine, PJ_EINVAL); + + TInt max_gain = strm->in_engine->GetMaxGain(); + if (max_gain > 0) { + TInt gain; + + gain = *(unsigned*)pval * max_gain / 100; + status = strm->in_engine->SetGain(gain); + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + break; case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - PJ_ASSERT_RETURN(strm->out_engine, PJ_EINVAL); - - TInt max_vol = strm->out_engine->GetMaxVolume(); - if (max_vol > 0) { - TInt vol; - - vol = *(unsigned*)pval * max_vol / 100; - status = strm->out_engine->SetVolume(vol); - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + PJ_ASSERT_RETURN(strm->out_engine, PJ_EINVAL); + + TInt max_vol = strm->out_engine->GetMaxVolume(); + if (max_vol > 0) { + TInt vol; + + vol = *(unsigned*)pval * max_vol / 100; + status = strm->out_engine->SetVolume(vol); + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + break; default: - break; + break; } return status; @@ -1133,17 +1132,17 @@ static pj_status_t stream_start(pjmedia_aud_stream *strm) PJ_ASSERT_RETURN(stream, PJ_EINVAL); if (stream->out_engine) { - pj_status_t status; - status = stream->out_engine->StartPlay(); - if (status != PJ_SUCCESS) - return status; + pj_status_t status; + status = stream->out_engine->StartPlay(); + if (status != PJ_SUCCESS) + return status; } if (stream->in_engine) { - pj_status_t status; - status = stream->in_engine->StartRecord(); - if (status != PJ_SUCCESS) - return status; + pj_status_t status; + status = stream->in_engine->StartRecord(); + if (status != PJ_SUCCESS) + return status; } return PJ_SUCCESS; @@ -1157,11 +1156,11 @@ static pj_status_t stream_stop(pjmedia_aud_stream *strm) PJ_ASSERT_RETURN(stream, PJ_EINVAL); if (stream->in_engine) { - stream->in_engine->Stop(); + stream->in_engine->Stop(); } - + if (stream->out_engine) { - stream->out_engine->Stop(); + stream->out_engine->Stop(); } return PJ_SUCCESS; @@ -1186,8 +1185,8 @@ static pj_status_t stream_destroy(pjmedia_aud_stream *strm) pj_pool_t *pool; pool = stream->pool; if (pool) { - stream->pool = NULL; - pj_pool_release(pool); + stream->pool = NULL; + pj_pool_release(pool); } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia-audiodev/symb_vas_dev.cpp b/pjmedia/src/pjmedia-audiodev/symb_vas_dev.cpp index ca421d253b..2c4ae0e9c3 100644 --- a/pjmedia/src/pjmedia-audiodev/symb_vas_dev.cpp +++ b/pjmedia/src/pjmedia-audiodev/symb_vas_dev.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * @@ -49,8 +48,8 @@ #include "s60_g729_bitstream.h" -#define THIS_FILE "symb_vas_dev.c" -#define BITS_PER_SAMPLE 16 +#define THIS_FILE "symb_vas_dev.c" +#define BITS_PER_SAMPLE 16 /* When this macro is set, VAS will use EPCM16 format for PCM input/output, @@ -72,10 +71,10 @@ static pj_uint8_t vas_g711_frame_len; /* VAS factory */ struct vas_factory { - pjmedia_aud_dev_factory base; - pj_pool_t *pool; - pj_pool_factory *pf; - pjmedia_aud_dev_info dev_info; + pjmedia_aud_dev_factory base; + pj_pool_t *pool; + pj_pool_factory *pf; + pjmedia_aud_dev_info dev_info; }; @@ -87,43 +86,43 @@ class CPjAudioEngine; struct vas_stream { // Base - pjmedia_aud_stream base; /**< Base class. */ + pjmedia_aud_stream base; /**< Base class. */ // Pool - pj_pool_t *pool; /**< Memory pool. */ + pj_pool_t *pool; /**< Memory pool. */ // Common settings. - pjmedia_aud_param param; /**< Stream param. */ - pjmedia_aud_rec_cb rec_cb; /**< Record callback. */ - pjmedia_aud_play_cb play_cb; /**< Playback callback. */ - void *user_data; /**< Application data. */ + pjmedia_aud_param param; /**< Stream param. */ + pjmedia_aud_rec_cb rec_cb; /**< Record callback. */ + pjmedia_aud_play_cb play_cb; /**< Playback callback. */ + void *user_data; /**< Application data. */ // Audio engine - CPjAudioEngine *engine; /**< Internal engine. */ + CPjAudioEngine *engine; /**< Internal engine. */ - pj_timestamp ts_play; /**< Playback timestamp.*/ - pj_timestamp ts_rec; /**< Record timestamp. */ + pj_timestamp ts_play; /**< Playback timestamp.*/ + pj_timestamp ts_rec; /**< Record timestamp. */ - pj_int16_t *play_buf; /**< Playback buffer. */ - pj_uint16_t play_buf_len; /**< Playback buffer length. */ - pj_uint16_t play_buf_start; /**< Playback buffer start index. */ - pj_int16_t *rec_buf; /**< Record buffer. */ - pj_uint16_t rec_buf_len; /**< Record buffer length. */ - void *strm_data; /**< Stream data. */ + pj_int16_t *play_buf; /**< Playback buffer. */ + pj_uint16_t play_buf_len; /**< Playback buffer length. */ + pj_uint16_t play_buf_start; /**< Playback buffer start index. */ + pj_int16_t *rec_buf; /**< Record buffer. */ + pj_uint16_t rec_buf_len; /**< Record buffer length. */ + void *strm_data; /**< Stream data. */ /* Resampling is needed, in case audio device is opened with clock rate * other than 8kHz (only for PCM format). */ - pjmedia_resample *play_resample; /**< Resampler for playback. */ - pjmedia_resample *rec_resample; /**< Resampler for recording */ - pj_uint16_t resample_factor; /**< Resample factor, requested - clock rate / 8000 */ + pjmedia_resample *play_resample; /**< Resampler for playback. */ + pjmedia_resample *rec_resample; /**< Resampler for recording */ + pj_uint16_t resample_factor; /**< Resample factor, requested + clock rate / 8000 */ /* When stream is working in PCM format, where the samples may need to be * resampled from/to different clock rate and/or channel count, PCM buffer * is needed to perform such resampling operations. */ - pj_int16_t *pcm_buf; /**< PCM buffer. */ + pj_int16_t *pcm_buf; /**< PCM buffer. */ }; @@ -133,26 +132,26 @@ static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f); static pj_status_t factory_refresh(pjmedia_aud_dev_factory *f); static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f); static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); + unsigned index, + pjmedia_aud_dev_info *info); static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); + unsigned index, + pjmedia_aud_param *param); static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); static pj_status_t stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); + pjmedia_aud_param *param); static pj_status_t stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); + pjmedia_aud_dev_cap cap, + void *value); static pj_status_t stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); + pjmedia_aud_dev_cap cap, + const void *value); static pj_status_t stream_start(pjmedia_aud_stream *strm); static pj_status_t stream_stop(pjmedia_aud_stream *strm); static pj_status_t stream_destroy(pjmedia_aud_stream *strm); @@ -201,38 +200,38 @@ typedef void(*PjAudioCallback)(CVoIPDataBuffer *buf, void *user_data); class CPjAudioSetting { public: - TVoIPCodecFormat format; - TInt mode; - TBool plc; - TBool vad; - TBool cng; - TBool loudspk; + TVoIPCodecFormat format; + TInt mode; + TBool plc; + TBool vad; + TBool cng; + TBool loudspk; }; /* * Implementation: Symbian Input & Output Stream. */ class CPjAudioEngine : public CBase, - public MVoIPDownlinkObserver, - public MVoIPUplinkObserver, - public MVoIPFormatObserver + public MVoIPDownlinkObserver, + public MVoIPUplinkObserver, + public MVoIPFormatObserver { public: enum State { - STATE_NULL, - STATE_STARTING, - STATE_READY, - STATE_STREAMING + STATE_NULL, + STATE_STARTING, + STATE_READY, + STATE_STREAMING }; ~CPjAudioEngine(); static CPjAudioEngine *NewL(struct vas_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting); + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting); TInt Start(); void Stop(); @@ -251,10 +250,10 @@ class CPjAudioEngine : public CBase, private: CPjAudioEngine(struct vas_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting); + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting); void ConstructL(); TInt InitPlay(); @@ -280,33 +279,33 @@ class CPjAudioEngine : public CBase, // From MVoIPFormatObserver void Event(const CVoIPFormatIntfc& aSrc, TInt aEventType); - State dn_state_; - State up_state_; - struct vas_stream *parentStrm_; - CPjAudioSetting setting_; - PjAudioCallback rec_cb_; - PjAudioCallback play_cb_; - void *user_data_; + State dn_state_; + State up_state_; + struct vas_stream *parentStrm_; + CPjAudioSetting setting_; + PjAudioCallback rec_cb_; + PjAudioCallback play_cb_; + void *user_data_; // VAS objects CVoIPUtilityFactory *iFactory; CVoIPAudioDownlinkStream *iVoIPDnlink; CVoIPAudioUplinkStream *iVoIPUplink; - CVoIPFormatIntfc *enc_fmt_if; - CVoIPFormatIntfc *dec_fmt_if; + CVoIPFormatIntfc *enc_fmt_if; + CVoIPFormatIntfc *dec_fmt_if; }; CPjAudioEngine* CPjAudioEngine::NewL(struct vas_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting) + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting) { CPjAudioEngine* self = new (ELeave) CPjAudioEngine(parent_strm, - rec_cb, play_cb, - user_data, - setting); + rec_cb, play_cb, + user_data, + setting); CleanupStack::PushL(self); self->ConstructL(); CleanupStack::Pop(self); @@ -322,29 +321,29 @@ void CPjAudioEngine::ConstructL() User::LeaveIfError(err); if (parentStrm_->param.dir != PJMEDIA_DIR_CAPTURE) { - err = iFactory->CreateDownlinkStream(ver, - CVoIPUtilityFactory::EVoIPCall, - iVoIPDnlink); - User::LeaveIfError(err); + err = iFactory->CreateDownlinkStream(ver, + CVoIPUtilityFactory::EVoIPCall, + iVoIPDnlink); + User::LeaveIfError(err); } if (parentStrm_->param.dir != PJMEDIA_DIR_PLAYBACK) { - err = iFactory->CreateUplinkStream(ver, - CVoIPUtilityFactory::EVoIPCall, - iVoIPUplink); - User::LeaveIfError(err); + err = iFactory->CreateUplinkStream(ver, + CVoIPUtilityFactory::EVoIPCall, + iVoIPUplink); + User::LeaveIfError(err); } } CPjAudioEngine::CPjAudioEngine(struct vas_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting) + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting) : dn_state_(STATE_NULL), up_state_(STATE_NULL), - parentStrm_(parent_strm), - setting_(setting), + parentStrm_(parent_strm), + setting_(setting), rec_cb_(rec_cb), play_cb_(play_cb), user_data_(user_data), @@ -361,10 +360,10 @@ CPjAudioEngine::~CPjAudioEngine() Stop(); if (iVoIPUplink) - iVoIPUplink->Close(); + iVoIPUplink->Close(); if (iVoIPDnlink) - iVoIPDnlink->Close(); + iVoIPDnlink->Close(); delete enc_fmt_if; delete dec_fmt_if; @@ -378,9 +377,9 @@ CPjAudioEngine::~CPjAudioEngine() TBool CPjAudioEngine::IsStarted() { return ((((parentStrm_->param.dir & PJMEDIA_DIR_CAPTURE) == 0) || - up_state_ == STATE_STREAMING) && - (((parentStrm_->param.dir & PJMEDIA_DIR_PLAYBACK) == 0) || - dn_state_ == STATE_STREAMING)); + up_state_ == STATE_STREAMING) && + (((parentStrm_->param.dir & PJMEDIA_DIR_PLAYBACK) == 0) || + dn_state_ == STATE_STREAMING)); } TInt CPjAudioEngine::InitPlay() @@ -393,11 +392,11 @@ TInt CPjAudioEngine::InitPlay() dec_fmt_if = NULL; err = iVoIPDnlink->SetFormat(setting_.format, dec_fmt_if); if (err != KErrNone) - return err; + return err; err = dec_fmt_if->SetObserver(*this); if (err != KErrNone) - return err; + return err; return iVoIPDnlink->Open(*this); } @@ -412,11 +411,11 @@ TInt CPjAudioEngine::InitRec() enc_fmt_if = NULL; err = iVoIPUplink->SetFormat(setting_.format, enc_fmt_if); if (err != KErrNone) - return err; + return err; err = enc_fmt_if->SetObserver(*this); if (err != KErrNone) - return err; + return err; return iVoIPUplink->Open(*this); } @@ -431,34 +430,34 @@ TInt CPjAudioEngine::StartPlay() /* Configure specific codec setting */ switch (setting_.format) { case EG711: - { - CVoIPG711DecoderIntfc *g711dec_if = (CVoIPG711DecoderIntfc*) - dec_fmt_if; - err = g711dec_if->SetMode((CVoIPFormatIntfc::TG711CodecMode) - setting_.mode); - } - break; - + { + CVoIPG711DecoderIntfc *g711dec_if = (CVoIPG711DecoderIntfc*) + dec_fmt_if; + err = g711dec_if->SetMode((CVoIPFormatIntfc::TG711CodecMode) + setting_.mode); + } + break; + case EILBC: - { - CVoIPILBCDecoderIntfc *ilbcdec_if = (CVoIPILBCDecoderIntfc*) - dec_fmt_if; - err = ilbcdec_if->SetMode((CVoIPFormatIntfc::TILBCCodecMode) - setting_.mode); - } - break; + { + CVoIPILBCDecoderIntfc *ilbcdec_if = (CVoIPILBCDecoderIntfc*) + dec_fmt_if; + err = ilbcdec_if->SetMode((CVoIPFormatIntfc::TILBCCodecMode) + setting_.mode); + } + break; case EAMR_NB: - /* Ticket #1008: AMR playback issue on few devices, e.g: E72, E52 */ - err = dec_fmt_if->SetFrameMode(ETrue); - break; - + /* Ticket #1008: AMR playback issue on few devices, e.g: E72, E52 */ + err = dec_fmt_if->SetFrameMode(ETrue); + break; + default: - break; + break; } if (err != KErrNone) - goto on_return; + goto on_return; /* Configure audio routing */ ActivateSpeaker(setting_.loudspk); @@ -468,10 +467,10 @@ TInt CPjAudioEngine::StartPlay() on_return: if (err == KErrNone) { - dn_state_ = STATE_STREAMING; - TRACE_((THIS_FILE, "Downlink started")); + dn_state_ = STATE_STREAMING; + TRACE_((THIS_FILE, "Downlink started")); } else { - snd_perror("Failed starting downlink", err); + snd_perror("Failed starting downlink", err); } return err; @@ -487,33 +486,33 @@ TInt CPjAudioEngine::StartRec() /* Configure specific codec setting */ switch (setting_.format) { case EG711: - { - CVoIPG711EncoderIntfc *g711enc_if = (CVoIPG711EncoderIntfc*) - enc_fmt_if; - err = g711enc_if->SetMode((CVoIPFormatIntfc::TG711CodecMode) - setting_.mode); - } - break; + { + CVoIPG711EncoderIntfc *g711enc_if = (CVoIPG711EncoderIntfc*) + enc_fmt_if; + err = g711enc_if->SetMode((CVoIPFormatIntfc::TG711CodecMode) + setting_.mode); + } + break; case EILBC: - { - CVoIPILBCEncoderIntfc *ilbcenc_if = (CVoIPILBCEncoderIntfc*) - enc_fmt_if; - err = ilbcenc_if->SetMode((CVoIPFormatIntfc::TILBCCodecMode) - setting_.mode); - } - break; - + { + CVoIPILBCEncoderIntfc *ilbcenc_if = (CVoIPILBCEncoderIntfc*) + enc_fmt_if; + err = ilbcenc_if->SetMode((CVoIPFormatIntfc::TILBCCodecMode) + setting_.mode); + } + break; + case EAMR_NB: - err = enc_fmt_if->SetBitRate(setting_.mode); - break; - + err = enc_fmt_if->SetBitRate(setting_.mode); + break; + default: - break; + break; } if (err != KErrNone) - goto on_return; + goto on_return; /* Configure general codec setting */ enc_fmt_if->SetVAD(setting_.vad); @@ -523,10 +522,10 @@ TInt CPjAudioEngine::StartRec() on_return: if (err == KErrNone) { - up_state_ = STATE_STREAMING; - TRACE_((THIS_FILE, "Uplink started")); + up_state_ = STATE_STREAMING; + TRACE_((THIS_FILE, "Uplink started")); } else { - snd_perror("Failed starting uplink", err); + snd_perror("Failed starting uplink", err); } return err; @@ -537,35 +536,35 @@ TInt CPjAudioEngine::Start() TInt err = KErrNone; if (iVoIPDnlink) { - switch(dn_state_) { - case STATE_READY: - err = StartPlay(); - break; - case STATE_NULL: - err = InitPlay(); - if (err != KErrNone) - return err; - dn_state_ = STATE_STARTING; - break; - default: - break; - } + switch(dn_state_) { + case STATE_READY: + err = StartPlay(); + break; + case STATE_NULL: + err = InitPlay(); + if (err != KErrNone) + return err; + dn_state_ = STATE_STARTING; + break; + default: + break; + } } if (iVoIPUplink) { - switch(up_state_) { - case STATE_READY: - err = StartRec(); - break; - case STATE_NULL: - err = InitRec(); - if (err != KErrNone) - return err; - up_state_ = STATE_STARTING; - break; - default: - break; - } + switch(up_state_) { + case STATE_READY: + err = StartRec(); + break; + case STATE_NULL: + err = InitRec(); + if (err != KErrNone) + return err; + up_state_ = STATE_STARTING; + break; + default: + break; + } } return err; @@ -574,31 +573,31 @@ TInt CPjAudioEngine::Start() void CPjAudioEngine::Stop() { if (iVoIPDnlink) { - switch(dn_state_) { - case STATE_STREAMING: - iVoIPDnlink->Stop(); - dn_state_ = STATE_READY; - break; - case STATE_STARTING: - dn_state_ = STATE_NULL; - break; - default: - break; - } + switch(dn_state_) { + case STATE_STREAMING: + iVoIPDnlink->Stop(); + dn_state_ = STATE_READY; + break; + case STATE_STARTING: + dn_state_ = STATE_NULL; + break; + default: + break; + } } if (iVoIPUplink) { - switch(up_state_) { - case STATE_STREAMING: - iVoIPUplink->Stop(); - up_state_ = STATE_READY; - break; - case STATE_STARTING: - up_state_ = STATE_NULL; - break; - default: - break; - } + switch(up_state_) { + case STATE_STREAMING: + iVoIPUplink->Stop(); + up_state_ = STATE_READY; + break; + case STATE_STARTING: + up_state_ = STATE_NULL; + break; + default: + break; + } } } @@ -608,10 +607,10 @@ TInt CPjAudioEngine::ActivateSpeaker(TBool active) TInt err = KErrNotSupported; if (iVoIPDnlink) { - err = iVoIPDnlink->SetAudioDevice(active? - CVoIPAudioDownlinkStream::ELoudSpeaker : - CVoIPAudioDownlinkStream::EHandset); - TRACE_((THIS_FILE, "Loudspeaker turned %s", (active? "on":"off"))); + err = iVoIPDnlink->SetAudioDevice(active? + CVoIPAudioDownlinkStream::ELoudSpeaker : + CVoIPAudioDownlinkStream::EHandset); + TRACE_((THIS_FILE, "Loudspeaker turned %s", (active? "on":"off"))); } return err; @@ -640,28 +639,28 @@ void CPjAudioEngine::Event(const CVoIPAudioDownlinkStream& /*aSrc*/, { switch (aEventType) { case MVoIPDownlinkObserver::KOpenComplete: - if (aError == KErrNone) { - State last_state = dn_state_; + if (aError == KErrNone) { + State last_state = dn_state_; - dn_state_ = STATE_READY; - TRACE_((THIS_FILE, "Downlink opened")); + dn_state_ = STATE_READY; + TRACE_((THIS_FILE, "Downlink opened")); - if (last_state == STATE_STARTING) - StartPlay(); - } - break; + if (last_state == STATE_STARTING) + StartPlay(); + } + break; case MVoIPDownlinkObserver::KDownlinkClosed: - dn_state_ = STATE_NULL; - TRACE_((THIS_FILE, "Downlink closed")); - break; + dn_state_ = STATE_NULL; + TRACE_((THIS_FILE, "Downlink closed")); + break; case MVoIPDownlinkObserver::KDownlinkError: - dn_state_ = STATE_READY; - snd_perror("Downlink problem", aError); - break; + dn_state_ = STATE_READY; + snd_perror("Downlink problem", aError); + break; default: - break; + break; } } @@ -672,34 +671,34 @@ void CPjAudioEngine::Event(const CVoIPAudioUplinkStream& /*aSrc*/, { switch (aEventType) { case MVoIPUplinkObserver::KOpenComplete: - if (aError == KErrNone) { - State last_state = up_state_; + if (aError == KErrNone) { + State last_state = up_state_; - up_state_ = STATE_READY; - TRACE_((THIS_FILE, "Uplink opened")); - - if (last_state == STATE_STARTING) - StartRec(); - } - break; + up_state_ = STATE_READY; + TRACE_((THIS_FILE, "Uplink opened")); + + if (last_state == STATE_STARTING) + StartRec(); + } + break; case MVoIPUplinkObserver::KUplinkClosed: - up_state_ = STATE_NULL; - TRACE_((THIS_FILE, "Uplink closed")); - break; + up_state_ = STATE_NULL; + TRACE_((THIS_FILE, "Uplink closed")); + break; case MVoIPUplinkObserver::KUplinkError: - up_state_ = STATE_READY; - snd_perror("Uplink problem", aError); - break; + up_state_ = STATE_READY; + snd_perror("Uplink problem", aError); + break; default: - break; + break; } } // Callback from MVoIPFormatObserver void CPjAudioEngine::Event(const CVoIPFormatIntfc& /*aSrc*/, - TInt aEventType) + TInt aEventType) { snd_perror("Format event", aEventType); } @@ -724,25 +723,25 @@ static void RecCbPcm2(CVoIPDataBuffer *buf, void *user_data) p_buf = (pj_int16_t*) buffer.Ptr(); buf_len = buffer.Length() >> 1; while (buf_len) { - unsigned req; - - req = strm->param.samples_per_frame - strm->rec_buf_len; - if (req > buf_len) - req = buf_len; - pjmedia_copy_samples(strm->rec_buf + strm->rec_buf_len, p_buf, req); - p_buf += req; - buf_len -= req; - strm->rec_buf_len += req; - - if (strm->rec_buf_len >= strm->param.samples_per_frame) { - pjmedia_frame f; - - f.buf = strm->rec_buf; - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.size = strm->param.samples_per_frame << 1; - strm->rec_cb(strm->user_data, &f); - strm->rec_buf_len = 0; - } + unsigned req; + + req = strm->param.samples_per_frame - strm->rec_buf_len; + if (req > buf_len) + req = buf_len; + pjmedia_copy_samples(strm->rec_buf + strm->rec_buf_len, p_buf, req); + p_buf += req; + buf_len -= req; + strm->rec_buf_len += req; + + if (strm->rec_buf_len >= strm->param.samples_per_frame) { + pjmedia_frame f; + + f.buf = strm->rec_buf; + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + f.size = strm->param.samples_per_frame << 1; + strm->rec_cb(strm->user_data, &f); + strm->rec_buf_len = 0; + } } } @@ -760,8 +759,8 @@ static void PlayCbPcm2(CVoIPDataBuffer *buf, void *user_data) f.size = strm->param.samples_per_frame << 1; strm->play_cb(strm->user_data, &f); if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) { - pjmedia_zero_samples((pj_int16_t*)f.buf, - strm->param.samples_per_frame); + pjmedia_zero_samples((pj_int16_t*)f.buf, + strm->param.samples_per_frame); } f.size = strm->param.samples_per_frame << 1; @@ -790,9 +789,9 @@ static void RecCbPcm(CVoIPDataBuffer *buf, void *user_data) * this recorder frame size. */ if (vas_g711_frame_len == 0) { - vas_g711_frame_len = buffer.Length() < 160? 80 : 160; - TRACE_((THIS_FILE, "Detected VAS G.711 frame size = %u samples", - vas_g711_frame_len)); + vas_g711_frame_len = buffer.Length() < 160? 80 : 160; + TRACE_((THIS_FILE, "Detected VAS G.711 frame size = %u samples", + vas_g711_frame_len)); } /* Decode VAS buffer (coded in G.711) and put the PCM result into rec_buf. @@ -801,63 +800,63 @@ static void RecCbPcm(CVoIPDataBuffer *buf, void *user_data) unsigned samples_processed = 0; while (samples_processed < vas_g711_frame_len) { - unsigned samples_to_process; - unsigned samples_req; - - samples_to_process = vas_g711_frame_len - samples_processed; - samples_req = (strm->param.samples_per_frame / - strm->param.channel_count / - strm->resample_factor) - - strm->rec_buf_len; - if (samples_to_process > samples_req) - samples_to_process = samples_req; - - pjmedia_ulaw_decode(&strm->rec_buf[strm->rec_buf_len], - buffer.Ptr() + 2 + samples_processed, - samples_to_process); - - strm->rec_buf_len += samples_to_process; - samples_processed += samples_to_process; - - /* Buffer is full, time to call parent callback */ - if (strm->rec_buf_len == strm->param.samples_per_frame / - strm->param.channel_count / - strm->resample_factor) - { - pjmedia_frame f; - - /* Need to resample clock rate? */ - if (strm->rec_resample) { - unsigned resampled = 0; - - while (resampled < strm->rec_buf_len) { - pjmedia_resample_run(strm->rec_resample, - &strm->rec_buf[resampled], - strm->pcm_buf + - resampled * strm->resample_factor); - resampled += 80; - } - f.buf = strm->pcm_buf; - } else { - f.buf = strm->rec_buf; - } - - /* Need to convert channel count? */ - if (strm->param.channel_count != 1) { - pjmedia_convert_channel_1ton((pj_int16_t*)f.buf, - (pj_int16_t*)f.buf, - strm->param.channel_count, - strm->param.samples_per_frame / - strm->param.channel_count, - 0); - } - - /* Call parent callback */ - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.size = strm->param.samples_per_frame << 1; - strm->rec_cb(strm->user_data, &f); - strm->rec_buf_len = 0; - } + unsigned samples_to_process; + unsigned samples_req; + + samples_to_process = vas_g711_frame_len - samples_processed; + samples_req = (strm->param.samples_per_frame / + strm->param.channel_count / + strm->resample_factor) - + strm->rec_buf_len; + if (samples_to_process > samples_req) + samples_to_process = samples_req; + + pjmedia_ulaw_decode(&strm->rec_buf[strm->rec_buf_len], + buffer.Ptr() + 2 + samples_processed, + samples_to_process); + + strm->rec_buf_len += samples_to_process; + samples_processed += samples_to_process; + + /* Buffer is full, time to call parent callback */ + if (strm->rec_buf_len == strm->param.samples_per_frame / + strm->param.channel_count / + strm->resample_factor) + { + pjmedia_frame f; + + /* Need to resample clock rate? */ + if (strm->rec_resample) { + unsigned resampled = 0; + + while (resampled < strm->rec_buf_len) { + pjmedia_resample_run(strm->rec_resample, + &strm->rec_buf[resampled], + strm->pcm_buf + + resampled * strm->resample_factor); + resampled += 80; + } + f.buf = strm->pcm_buf; + } else { + f.buf = strm->rec_buf; + } + + /* Need to convert channel count? */ + if (strm->param.channel_count != 1) { + pjmedia_convert_channel_1ton((pj_int16_t*)f.buf, + (pj_int16_t*)f.buf, + strm->param.channel_count, + strm->param.samples_per_frame / + strm->param.channel_count, + 0); + } + + /* Call parent callback */ + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + f.size = strm->param.samples_per_frame << 1; + strm->rec_cb(strm->user_data, &f); + strm->rec_buf_len = 0; + } } } @@ -879,7 +878,7 @@ static void PlayCbPcm(CVoIPDataBuffer *buf, void *user_data) /* Assume frame size is 10ms if frame size hasn't been known. */ if (g711_frame_len == 0) - g711_frame_len = 80; + g711_frame_len = 80; /* Call parent stream callback to get PCM samples to play, * encode the PCM samples into G.711 and put it into VAS buffer. @@ -887,66 +886,66 @@ static void PlayCbPcm(CVoIPDataBuffer *buf, void *user_data) unsigned samples_processed = 0; while (samples_processed < g711_frame_len) { - /* Need more samples to play, time to call parent callback */ - if (strm->play_buf_len == 0) { - pjmedia_frame f; - unsigned samples_got; - - f.size = strm->param.samples_per_frame << 1; - if (strm->play_resample || strm->param.channel_count != 1) - f.buf = strm->pcm_buf; - else - f.buf = strm->play_buf; - - /* Call parent callback */ - strm->play_cb(strm->user_data, &f); - if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) { - pjmedia_zero_samples((pj_int16_t*)f.buf, - strm->param.samples_per_frame); - } - - samples_got = strm->param.samples_per_frame / - strm->param.channel_count / - strm->resample_factor; - - /* Need to convert channel count? */ - if (strm->param.channel_count != 1) { - pjmedia_convert_channel_nto1((pj_int16_t*)f.buf, - (pj_int16_t*)f.buf, - strm->param.channel_count, - strm->param.samples_per_frame, - PJ_FALSE, - 0); - } - - /* Need to resample clock rate? */ - if (strm->play_resample) { - unsigned resampled = 0; - - while (resampled < samples_got) - { - pjmedia_resample_run(strm->play_resample, - strm->pcm_buf + - resampled * strm->resample_factor, - &strm->play_buf[resampled]); - resampled += 80; - } - } - - strm->play_buf_len = samples_got; - strm->play_buf_start = 0; - } - - unsigned tmp; - - tmp = PJ_MIN(strm->play_buf_len, g711_frame_len - samples_processed); - pjmedia_ulaw_encode((pj_uint8_t*)&strm->play_buf[strm->play_buf_start], - &strm->play_buf[strm->play_buf_start], - tmp); - buffer.Append((TUint8*)&strm->play_buf[strm->play_buf_start], tmp); - samples_processed += tmp; - strm->play_buf_len -= tmp; - strm->play_buf_start += tmp; + /* Need more samples to play, time to call parent callback */ + if (strm->play_buf_len == 0) { + pjmedia_frame f; + unsigned samples_got; + + f.size = strm->param.samples_per_frame << 1; + if (strm->play_resample || strm->param.channel_count != 1) + f.buf = strm->pcm_buf; + else + f.buf = strm->play_buf; + + /* Call parent callback */ + strm->play_cb(strm->user_data, &f); + if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) { + pjmedia_zero_samples((pj_int16_t*)f.buf, + strm->param.samples_per_frame); + } + + samples_got = strm->param.samples_per_frame / + strm->param.channel_count / + strm->resample_factor; + + /* Need to convert channel count? */ + if (strm->param.channel_count != 1) { + pjmedia_convert_channel_nto1((pj_int16_t*)f.buf, + (pj_int16_t*)f.buf, + strm->param.channel_count, + strm->param.samples_per_frame, + PJ_FALSE, + 0); + } + + /* Need to resample clock rate? */ + if (strm->play_resample) { + unsigned resampled = 0; + + while (resampled < samples_got) + { + pjmedia_resample_run(strm->play_resample, + strm->pcm_buf + + resampled * strm->resample_factor, + &strm->play_buf[resampled]); + resampled += 80; + } + } + + strm->play_buf_len = samples_got; + strm->play_buf_start = 0; + } + + unsigned tmp; + + tmp = PJ_MIN(strm->play_buf_len, g711_frame_len - samples_processed); + pjmedia_ulaw_encode((pj_uint8_t*)&strm->play_buf[strm->play_buf_start], + &strm->play_buf[strm->play_buf_start], + tmp); + buffer.Append((TUint8*)&strm->play_buf[strm->play_buf_start], tmp); + samples_processed += tmp; + strm->play_buf_len -= tmp; + strm->play_buf_start += tmp; } /* Set the buffer */ @@ -968,120 +967,120 @@ static void RecCb(CVoIPDataBuffer *buf, void *user_data) switch(strm->param.ext_fmt.id) { case PJMEDIA_FORMAT_AMR: - { - const pj_uint8_t *p = (const pj_uint8_t*)buffer.Ptr() + 1; - unsigned len = buffer.Length() - 1; - - pjmedia_frame_ext_append_subframe(frame, p, len << 3, 160); - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - + { + const pj_uint8_t *p = (const pj_uint8_t*)buffer.Ptr() + 1; + unsigned len = buffer.Length() - 1; + + pjmedia_frame_ext_append_subframe(frame, p, len << 3, 160); + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + break; + case PJMEDIA_FORMAT_G729: - { - /* Check if we got a normal or SID frame. */ - if (buffer[0] != 0) { - enum { NORMAL_LEN = 22, SID_LEN = 8 }; - TBitStream *bitstream = (TBitStream*)strm->strm_data; - unsigned src_len = buffer.Length()- 2; - - pj_assert(src_len == NORMAL_LEN || src_len == SID_LEN); - - const TDesC8& p = bitstream->CompressG729Frame( - buffer.Right(src_len), - src_len == SID_LEN); - - pjmedia_frame_ext_append_subframe(frame, p.Ptr(), - p.Length() << 3, 80); - } else { /* We got null frame. */ - pjmedia_frame_ext_append_subframe(frame, NULL, 0, 80); - } - - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; + { + /* Check if we got a normal or SID frame. */ + if (buffer[0] != 0) { + enum { NORMAL_LEN = 22, SID_LEN = 8 }; + TBitStream *bitstream = (TBitStream*)strm->strm_data; + unsigned src_len = buffer.Length()- 2; + + pj_assert(src_len == NORMAL_LEN || src_len == SID_LEN); + + const TDesC8& p = bitstream->CompressG729Frame( + buffer.Right(src_len), + src_len == SID_LEN); + + pjmedia_frame_ext_append_subframe(frame, p.Ptr(), + p.Length() << 3, 80); + } else { /* We got null frame. */ + pjmedia_frame_ext_append_subframe(frame, NULL, 0, 80); + } + + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + break; case PJMEDIA_FORMAT_ILBC: - { - unsigned samples_got; - - samples_got = - strm->param.ext_fmt.det.aud.avg_bps == 15200? 160 : 240; - - /* Check if we got a normal or SID frame. */ - if (buffer[0] != 0) { - const pj_uint8_t *p = (const pj_uint8_t*)buffer.Ptr() + 2; - unsigned len = buffer.Length() - 2; - - pjmedia_frame_ext_append_subframe(frame, p, len << 3, - samples_got); - } else { /* We got null frame. */ - pjmedia_frame_ext_append_subframe(frame, NULL, 0, samples_got); - } - - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - + { + unsigned samples_got; + + samples_got = + strm->param.ext_fmt.det.aud.avg_bps == 15200? 160 : 240; + + /* Check if we got a normal or SID frame. */ + if (buffer[0] != 0) { + const pj_uint8_t *p = (const pj_uint8_t*)buffer.Ptr() + 2; + unsigned len = buffer.Length() - 2; + + pjmedia_frame_ext_append_subframe(frame, p, len << 3, + samples_got); + } else { /* We got null frame. */ + pjmedia_frame_ext_append_subframe(frame, NULL, 0, samples_got); + } + + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + break; + case PJMEDIA_FORMAT_PCMU: case PJMEDIA_FORMAT_PCMA: - { - unsigned samples_processed = 0; - - /* Make sure it is normal frame. */ - pj_assert(buffer[0] == 1 && buffer[1] == 0); - - /* Detect the recorder G.711 frame size, player frame size will - * follow this recorder frame size. - */ - if (vas_g711_frame_len == 0) { - vas_g711_frame_len = buffer.Length() < 160? 80 : 160; - TRACE_((THIS_FILE, "Detected VAS G.711 frame size = %u samples", - vas_g711_frame_len)); - } - - /* Convert VAS buffer format into pjmedia_frame_ext. Whenever - * samples count in the frame is equal to stream's samples per - * frame, call parent stream callback. - */ - while (samples_processed < vas_g711_frame_len) { - unsigned tmp; - const pj_uint8_t *pb = (const pj_uint8_t*)buffer.Ptr() + - 2 + samples_processed; + { + unsigned samples_processed = 0; + + /* Make sure it is normal frame. */ + pj_assert(buffer[0] == 1 && buffer[1] == 0); + + /* Detect the recorder G.711 frame size, player frame size will + * follow this recorder frame size. + */ + if (vas_g711_frame_len == 0) { + vas_g711_frame_len = buffer.Length() < 160? 80 : 160; + TRACE_((THIS_FILE, "Detected VAS G.711 frame size = %u samples", + vas_g711_frame_len)); + } + + /* Convert VAS buffer format into pjmedia_frame_ext. Whenever + * samples count in the frame is equal to stream's samples per + * frame, call parent stream callback. + */ + while (samples_processed < vas_g711_frame_len) { + unsigned tmp; + const pj_uint8_t *pb = (const pj_uint8_t*)buffer.Ptr() + + 2 + samples_processed; - tmp = PJ_MIN(strm->param.samples_per_frame - frame->samples_cnt, - vas_g711_frame_len - samples_processed); - - pjmedia_frame_ext_append_subframe(frame, pb, tmp << 3, tmp); - samples_processed += tmp; + tmp = PJ_MIN(strm->param.samples_per_frame - frame->samples_cnt, + vas_g711_frame_len - samples_processed); + + pjmedia_frame_ext_append_subframe(frame, pb, tmp << 3, tmp); + samples_processed += tmp; - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - } - break; - + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + } + break; + default: - break; + break; } } @@ -1099,218 +1098,218 @@ static void PlayCb(CVoIPDataBuffer *buf, void *user_data) switch(strm->param.ext_fmt.id) { case PJMEDIA_FORMAT_AMR: - { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - - if (sf->data && sf->bitlen) { - /* AMR header for VAS is one byte, the format (may be!): - * 0xxxxy00, where xxxx:frame type, y:not sure. - */ - unsigned len = (sf->bitlen+7)>>3; - enum {SID_FT = 8 }; - pj_uint8_t amr_header = 4, ft = SID_FT; - - if (len >= pjmedia_codec_amrnb_framelen[0]) - ft = pjmedia_codec_amr_get_mode2(PJ_TRUE, len); - - amr_header |= ft << 3; - buffer.Append(amr_header); - - buffer.Append((TUint8*)sf->data, len); - } else { - enum {NO_DATA_FT = 15 }; - pj_uint8_t amr_header = 4 | (NO_DATA_FT << 3); - - buffer.Append(amr_header); - } - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - enum {NO_DATA_FT = 15 }; - pj_uint8_t amr_header = 4 | (NO_DATA_FT << 3); - - buffer.Append(amr_header); - - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - + { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb(strm->user_data, (pjmedia_frame*)frame); + pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe(frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + if (sf->data && sf->bitlen) { + /* AMR header for VAS is one byte, the format (may be!): + * 0xxxxy00, where xxxx:frame type, y:not sure. + */ + unsigned len = (sf->bitlen+7)>>3; + enum {SID_FT = 8 }; + pj_uint8_t amr_header = 4, ft = SID_FT; + + if (len >= pjmedia_codec_amrnb_framelen[0]) + ft = pjmedia_codec_amr_get_mode2(PJ_TRUE, len); + + amr_header |= ft << 3; + buffer.Append(amr_header); + + buffer.Append((TUint8*)sf->data, len); + } else { + enum {NO_DATA_FT = 15 }; + pj_uint8_t amr_header = 4 | (NO_DATA_FT << 3); + + buffer.Append(amr_header); + } + + pjmedia_frame_ext_pop_subframes(frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + enum {NO_DATA_FT = 15 }; + pj_uint8_t amr_header = 4 | (NO_DATA_FT << 3); + + buffer.Append(amr_header); + + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + break; + case PJMEDIA_FORMAT_G729: - { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - - if (sf->data && sf->bitlen) { - enum { NORMAL_LEN = 10, SID_LEN = 2 }; - pj_bool_t sid_frame = ((sf->bitlen >> 3) == SID_LEN); - TBitStream *bitstream = (TBitStream*)strm->strm_data; - const TPtrC8 src(sf->data, sf->bitlen>>3); - const TDesC8 &dst = bitstream->ExpandG729Frame(src, - sid_frame); - if (sid_frame) { - buffer.Append(2); - buffer.Append(0); - } else { - buffer.Append(1); - buffer.Append(0); - } - buffer.Append(dst); - } else { - buffer.Append(2); - buffer.Append(0); - - buffer.AppendFill(0, 22); - } - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - buffer.Append(2); - buffer.Append(0); - - buffer.AppendFill(0, 22); - } - } - break; - + { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb(strm->user_data, (pjmedia_frame*)frame); + pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe(frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + if (sf->data && sf->bitlen) { + enum { NORMAL_LEN = 10, SID_LEN = 2 }; + pj_bool_t sid_frame = ((sf->bitlen >> 3) == SID_LEN); + TBitStream *bitstream = (TBitStream*)strm->strm_data; + const TPtrC8 src(sf->data, sf->bitlen>>3); + const TDesC8 &dst = bitstream->ExpandG729Frame(src, + sid_frame); + if (sid_frame) { + buffer.Append(2); + buffer.Append(0); + } else { + buffer.Append(1); + buffer.Append(0); + } + buffer.Append(dst); + } else { + buffer.Append(2); + buffer.Append(0); + + buffer.AppendFill(0, 22); + } + + pjmedia_frame_ext_pop_subframes(frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + buffer.Append(2); + buffer.Append(0); + + buffer.AppendFill(0, 22); + } + } + break; + case PJMEDIA_FORMAT_ILBC: - { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - - pj_assert((strm->param.ext_fmt.det.aud.avg_bps == 15200 && - samples_cnt == 160) || - (strm->param.ext_fmt.det.aud.avg_bps != 15200 && - samples_cnt == 240)); - - if (sf->data && sf->bitlen) { - buffer.Append(1); - buffer.Append(0); - buffer.Append((TUint8*)sf->data, sf->bitlen>>3); - } else { - unsigned frame_len; - - buffer.Append(1); - buffer.Append(0); - - /* VAS iLBC frame is 20ms or 30ms */ - frame_len = - strm->param.ext_fmt.det.aud.avg_bps == 15200? 38 : 50; - buffer.AppendFill(0, frame_len); - } - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - - unsigned frame_len; - - buffer.Append(1); - buffer.Append(0); - - /* VAS iLBC frame is 20ms or 30ms */ - frame_len = - strm->param.ext_fmt.det.aud.avg_bps == 15200? 38 : 50; - buffer.AppendFill(0, frame_len); - - } - } - break; - + { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb(strm->user_data, (pjmedia_frame*)frame); + pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe(frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + pj_assert((strm->param.ext_fmt.det.aud.avg_bps == 15200 && + samples_cnt == 160) || + (strm->param.ext_fmt.det.aud.avg_bps != 15200 && + samples_cnt == 240)); + + if (sf->data && sf->bitlen) { + buffer.Append(1); + buffer.Append(0); + buffer.Append((TUint8*)sf->data, sf->bitlen>>3); + } else { + unsigned frame_len; + + buffer.Append(1); + buffer.Append(0); + + /* VAS iLBC frame is 20ms or 30ms */ + frame_len = + strm->param.ext_fmt.det.aud.avg_bps == 15200? 38 : 50; + buffer.AppendFill(0, frame_len); + } + + pjmedia_frame_ext_pop_subframes(frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + + unsigned frame_len; + + buffer.Append(1); + buffer.Append(0); + + /* VAS iLBC frame is 20ms or 30ms */ + frame_len = + strm->param.ext_fmt.det.aud.avg_bps == 15200? 38 : 50; + buffer.AppendFill(0, frame_len); + + } + } + break; + case PJMEDIA_FORMAT_PCMU: case PJMEDIA_FORMAT_PCMA: - { - unsigned samples_ready = 0; - unsigned samples_req = vas_g711_frame_len; - - /* Assume frame size is 10ms if frame size hasn't been known. */ - if (samples_req == 0) - samples_req = 80; - - buffer.Append(1); - buffer.Append(0); - - /* Call parent stream callback to get samples to play. */ - while (samples_ready < samples_req) { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } + { + unsigned samples_ready = 0; + unsigned samples_req = vas_g711_frame_len; + + /* Assume frame size is 10ms if frame size hasn't been known. */ + if (samples_req == 0) + samples_req = 80; + + buffer.Append(1); + buffer.Append(0); + + /* Call parent stream callback to get samples to play. */ + while (samples_ready < samples_req) { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb(strm->user_data, (pjmedia_frame*)frame); + pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - if (sf->data && sf->bitlen) { - buffer.Append((TUint8*)sf->data, sf->bitlen>>3); - } else { - pj_uint8_t silc; - silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU)? - pjmedia_linear2ulaw(0) : pjmedia_linear2alaw(0); - buffer.AppendFill(silc, samples_cnt); - } - samples_ready += samples_cnt; - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - pj_uint8_t silc; - - silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU)? - pjmedia_linear2ulaw(0) : pjmedia_linear2alaw(0); - buffer.AppendFill(silc, samples_req - samples_ready); - - samples_ready = samples_req; - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - } - break; - + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe(frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + if (sf->data && sf->bitlen) { + buffer.Append((TUint8*)sf->data, sf->bitlen>>3); + } else { + pj_uint8_t silc; + silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU)? + pjmedia_linear2ulaw(0) : pjmedia_linear2alaw(0); + buffer.AppendFill(silc, samples_cnt); + } + samples_ready += samples_cnt; + + pjmedia_frame_ext_pop_subframes(frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + pj_uint8_t silc; + + silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU)? + pjmedia_linear2ulaw(0) : pjmedia_linear2alaw(0); + buffer.AppendFill(silc, samples_req - samples_ready); + + samples_ready = samples_req; + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + } + break; + default: - break; + break; } /* Set the buffer */ @@ -1361,13 +1360,13 @@ static pj_status_t factory_init(pjmedia_aud_dev_factory *f) pj_ansi_strcpy(af->dev_info.name, "S60 VAS"); af->dev_info.default_samples_per_sec = 8000; af->dev_info.caps = PJMEDIA_AUD_DEV_CAP_EXT_FORMAT | - //PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING | - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING | - PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE | - PJMEDIA_AUD_DEV_CAP_VAD | - PJMEDIA_AUD_DEV_CAP_CNG; + //PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING | + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING | + PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE | + PJMEDIA_AUD_DEV_CAP_VAD | + PJMEDIA_AUD_DEV_CAP_CNG; af->dev_info.routes = PJMEDIA_AUD_DEV_ROUTE_EARPIECE | - PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; + PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; af->dev_info.input_count = 1; af->dev_info.output_count = 1; af->dev_info.ext_fmt_cnt = 0; @@ -1375,32 +1374,32 @@ static pj_status_t factory_init(pjmedia_aud_dev_factory *f) /* Enumerate supported formats */ err = CVoIPUtilityFactory::CreateFactory(vas_factory_); if (err != KErrNone) - goto on_error; + goto on_error; /* On VAS 2.0, uplink & downlink stream should be instantiated before * querying formats. */ err = vas_factory_->CreateUplinkStream(vas_version, - CVoIPUtilityFactory::EVoIPCall, - vas_uplink); + CVoIPUtilityFactory::EVoIPCall, + vas_uplink); if (err != KErrNone) - goto on_error; + goto on_error; err = vas_factory_->CreateDownlinkStream(vas_version, - CVoIPUtilityFactory::EVoIPCall, - vas_dnlink); + CVoIPUtilityFactory::EVoIPCall, + vas_dnlink); if (err != KErrNone) - goto on_error; + goto on_error; uplink_formats.Reset(); err = vas_factory_->GetSupportedUplinkFormats(uplink_formats); if (err != KErrNone) - goto on_error; + goto on_error; dnlink_formats.Reset(); err = vas_factory_->GetSupportedDownlinkFormats(dnlink_formats); if (err != KErrNone) - goto on_error; + goto on_error; /* Free the streams, they are just used for querying formats */ delete vas_uplink; @@ -1411,54 +1410,54 @@ static pj_status_t factory_init(pjmedia_aud_dev_factory *f) vas_factory_ = NULL; for (TInt i = 0; i < dnlink_formats.Count(); i++) { - pjmedia_format ext_fmt; - - /* Format must be supported by both downlink & uplink. */ - if (uplink_formats.Find(dnlink_formats[i]) == KErrNotFound) - continue; - - switch (dnlink_formats[i]) { - case EAMR_NB: - pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_AMR, - 8000, 1, 16, 20, 7400, 12200); - af->dev_info.ext_fmt[ext_fmt_cnt] = ext_fmt; - //af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_TRUE; - break; - - case EG729: - pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_G729, - 8000, 1, 16, 20, 8000, 8000); - af->dev_info.ext_fmt[ext_fmt_cnt] = ext_fmt; - //af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_FALSE; - break; - - case EILBC: - pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_ILBC, - 8000, 1, 16, 30, 13333, 15200); - af->dev_info.ext_fmt[ext_fmt_cnt] = ext_fmt; - //af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_TRUE; - break; - - case EG711: + pjmedia_format ext_fmt; + + /* Format must be supported by both downlink & uplink. */ + if (uplink_formats.Find(dnlink_formats[i]) == KErrNotFound) + continue; + + switch (dnlink_formats[i]) { + case EAMR_NB: + pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_AMR, + 8000, 1, 16, 20, 7400, 12200); + af->dev_info.ext_fmt[ext_fmt_cnt] = ext_fmt; + //af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_TRUE; + break; + + case EG729: + pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_G729, + 8000, 1, 16, 20, 8000, 8000); + af->dev_info.ext_fmt[ext_fmt_cnt] = ext_fmt; + //af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_FALSE; + break; + + case EILBC: + pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_ILBC, + 8000, 1, 16, 30, 13333, 15200); + af->dev_info.ext_fmt[ext_fmt_cnt] = ext_fmt; + //af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_TRUE; + break; + + case EG711: #if PJMEDIA_AUDIO_DEV_SYMB_VAS_VERSION==2 - case EG711_10MS: + case EG711_10MS: #endif - pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_PCMU, - 8000, 1, 16, 20, 64000, 64000); - af->dev_info.ext_fmt[ext_fmt_cnt] = ext_fmt; - //af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_FALSE; - ++ext_fmt_cnt; - pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_PCMA, - 8000, 1, 16, 20, 64000, 64000); - af->dev_info.ext_fmt[ext_fmt_cnt] = ext_fmt; - //af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_FALSE; - break; - - default: - continue; - } - - ++ext_fmt_cnt; + pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_PCMU, + 8000, 1, 16, 20, 64000, 64000); + af->dev_info.ext_fmt[ext_fmt_cnt] = ext_fmt; + //af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_FALSE; + ++ext_fmt_cnt; + pjmedia_format_init_audio(&ext_fmt, PJMEDIA_FORMAT_PCMA, + 8000, 1, 16, 20, 64000, 64000); + af->dev_info.ext_fmt[ext_fmt_cnt] = ext_fmt; + //af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_FALSE; + break; + + default: + continue; + } + + ++ext_fmt_cnt; } af->dev_info.ext_fmt_cnt = ext_fmt_cnt; @@ -1504,8 +1503,8 @@ static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f) /* API: get device info */ static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info) + unsigned index, + pjmedia_aud_dev_info *info) { struct vas_factory *af = (struct vas_factory*)f; @@ -1518,8 +1517,8 @@ static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, /* API: create default device parameter */ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param) + unsigned index, + pjmedia_aud_param *param) { struct vas_factory *af = (struct vas_factory*)f; @@ -1542,11 +1541,11 @@ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, /* API: create stream */ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { struct vas_factory *af = (struct vas_factory*)f; pj_pool_t *pool; @@ -1564,18 +1563,18 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, * - for PCM format: 8kHz and 16kHz */ PJ_ASSERT_RETURN(param->clock_rate == 8000 || - (param->clock_rate == 16000 && - param->ext_fmt.id == PJMEDIA_FORMAT_L16), - PJ_EINVAL); + (param->clock_rate == 16000 && + param->ext_fmt.id == PJMEDIA_FORMAT_L16), + PJ_EINVAL); /* Supported channels number: * - for non-PCM format: mono * - for PCM format: mono and stereo */ PJ_ASSERT_RETURN(param->channel_count == 1 || - (param->channel_count == 2 && - param->ext_fmt.id == PJMEDIA_FORMAT_L16), - PJ_EINVAL); + (param->channel_count == 2 && + param->ext_fmt.id == PJMEDIA_FORMAT_L16), + PJ_EINVAL); /* Create and Initialize stream descriptor */ pool = pj_pool_create(af->pf, "vas-dev", 1000, 1000, NULL); @@ -1586,100 +1585,100 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, strm->param = *param; if (strm->param.flags & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT == 0) - strm->param.ext_fmt.id = PJMEDIA_FORMAT_L16; - + strm->param.ext_fmt.id = PJMEDIA_FORMAT_L16; + /* Set audio engine fourcc. */ switch(strm->param.ext_fmt.id) { case PJMEDIA_FORMAT_L16: -#ifdef USE_NATIVE_PCM - vas_setting.format = EPCM16; +#ifdef USE_NATIVE_PCM + vas_setting.format = EPCM16; #else - vas_setting.format = EG711; + vas_setting.format = EG711; #endif - break; + break; case PJMEDIA_FORMAT_PCMU: case PJMEDIA_FORMAT_PCMA: - vas_setting.format = EG711; - break; + vas_setting.format = EG711; + break; case PJMEDIA_FORMAT_AMR: - vas_setting.format = EAMR_NB; - break; + vas_setting.format = EAMR_NB; + break; case PJMEDIA_FORMAT_G729: - vas_setting.format = EG729; - break; + vas_setting.format = EG729; + break; case PJMEDIA_FORMAT_ILBC: - vas_setting.format = EILBC; - break; + vas_setting.format = EILBC; + break; default: - vas_setting.format = ENULL; - break; + vas_setting.format = ENULL; + break; } /* Set audio engine mode. */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) { -#ifdef USE_NATIVE_PCM - vas_setting.mode = 0; +#ifdef USE_NATIVE_PCM + vas_setting.mode = 0; #else - vas_setting.mode = CVoIPFormatIntfc::EG711uLaw; + vas_setting.mode = CVoIPFormatIntfc::EG711uLaw; #endif } else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_AMR) { - vas_setting.mode = strm->param.ext_fmt.det.aud.avg_bps; + vas_setting.mode = strm->param.ext_fmt.det.aud.avg_bps; } else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMU) { - vas_setting.mode = CVoIPFormatIntfc::EG711uLaw; + vas_setting.mode = CVoIPFormatIntfc::EG711uLaw; } else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA) { - vas_setting.mode = CVoIPFormatIntfc::EG711ALaw; + vas_setting.mode = CVoIPFormatIntfc::EG711ALaw; } else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC) { - if (strm->param.ext_fmt.det.aud.avg_bps == 15200) - vas_setting.mode = CVoIPFormatIntfc::EiLBC20mSecFrame; - else - vas_setting.mode = CVoIPFormatIntfc::EiLBC30mSecFrame; + if (strm->param.ext_fmt.det.aud.avg_bps == 15200) + vas_setting.mode = CVoIPFormatIntfc::EiLBC20mSecFrame; + else + vas_setting.mode = CVoIPFormatIntfc::EiLBC30mSecFrame; } else { - vas_setting.mode = 0; + vas_setting.mode = 0; } /* Disable VAD on L16, G711, iLBC, and also G729 (G729's SID * potentially cause noise?). */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMU || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_G729) + strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA || + strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 || + strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC || + strm->param.ext_fmt.id == PJMEDIA_FORMAT_G729) { - vas_setting.vad = EFalse; + vas_setting.vad = EFalse; } else { - vas_setting.vad = (strm->param.flags & PJMEDIA_AUD_DEV_CAP_VAD) && - strm->param.vad_enabled; + vas_setting.vad = (strm->param.flags & PJMEDIA_AUD_DEV_CAP_VAD) && + strm->param.vad_enabled; } /* Set other audio engine attributes. */ vas_setting.plc = (strm->param.flags & PJMEDIA_AUD_DEV_CAP_PLC) && - strm->param.plc_enabled; + strm->param.plc_enabled; vas_setting.cng = vas_setting.vad; vas_setting.loudspk = - strm->param.output_route==PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; + strm->param.output_route==PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; /* Set audio engine callbacks. */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) { #ifdef USE_NATIVE_PCM - vas_play_cb = &PlayCbPcm2; - vas_rec_cb = &RecCbPcm2; + vas_play_cb = &PlayCbPcm2; + vas_rec_cb = &RecCbPcm2; #else - vas_play_cb = &PlayCbPcm; - vas_rec_cb = &RecCbPcm; + vas_play_cb = &PlayCbPcm; + vas_rec_cb = &RecCbPcm; #endif } else { - vas_play_cb = &PlayCb; - vas_rec_cb = &RecCb; + vas_play_cb = &PlayCb; + vas_rec_cb = &RecCb; } strm->rec_cb = rec_cb; @@ -1689,73 +1688,73 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, /* play_buf size is samples per frame scaled in to 8kHz mono. */ strm->play_buf = (pj_int16_t*)pj_pool_zalloc( - pool, - (strm->param.samples_per_frame / - strm->resample_factor / - strm->param.channel_count) << 1); + pool, + (strm->param.samples_per_frame / + strm->resample_factor / + strm->param.channel_count) << 1); strm->play_buf_len = 0; strm->play_buf_start = 0; /* rec_buf size is samples per frame scaled in to 8kHz mono. */ strm->rec_buf = (pj_int16_t*)pj_pool_zalloc( - pool, - (strm->param.samples_per_frame / - strm->resample_factor / - strm->param.channel_count) << 1); + pool, + (strm->param.samples_per_frame / + strm->resample_factor / + strm->param.channel_count) << 1); strm->rec_buf_len = 0; if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_G729) { - TBitStream *g729_bitstream = new TBitStream; - - PJ_ASSERT_RETURN(g729_bitstream, PJ_ENOMEM); - strm->strm_data = (void*)g729_bitstream; + TBitStream *g729_bitstream = new TBitStream; + + PJ_ASSERT_RETURN(g729_bitstream, PJ_ENOMEM); + strm->strm_data = (void*)g729_bitstream; } - + /* Init resampler when format is PCM and clock rate is not 8kHz */ if (strm->param.clock_rate != 8000 && - strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) + strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) { - pj_status_t status; - - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - /* Create resample for recorder */ - status = pjmedia_resample_create( pool, PJ_TRUE, PJ_FALSE, 1, - 8000, - strm->param.clock_rate, - 80, - &strm->rec_resample); - if (status != PJ_SUCCESS) - return status; - } + pj_status_t status; + + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + /* Create resample for recorder */ + status = pjmedia_resample_create( pool, PJ_TRUE, PJ_FALSE, 1, + 8000, + strm->param.clock_rate, + 80, + &strm->rec_resample); + if (status != PJ_SUCCESS) + return status; + } - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - /* Create resample for player */ - status = pjmedia_resample_create( pool, PJ_TRUE, PJ_FALSE, 1, - strm->param.clock_rate, - 8000, - 80 * strm->resample_factor, - &strm->play_resample); - if (status != PJ_SUCCESS) - return status; - } + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + /* Create resample for player */ + status = pjmedia_resample_create( pool, PJ_TRUE, PJ_FALSE, 1, + strm->param.clock_rate, + 8000, + 80 * strm->resample_factor, + &strm->play_resample); + if (status != PJ_SUCCESS) + return status; + } } /* Create PCM buffer, when the clock rate is not 8kHz or not mono */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 && - (strm->resample_factor > 1 || strm->param.channel_count != 1)) + (strm->resample_factor > 1 || strm->param.channel_count != 1)) { - strm->pcm_buf = (pj_int16_t*)pj_pool_zalloc(pool, - strm->param.samples_per_frame << 1); + strm->pcm_buf = (pj_int16_t*)pj_pool_zalloc(pool, + strm->param.samples_per_frame << 1); } /* Create the audio engine. */ TRAPD(err, strm->engine = CPjAudioEngine::NewL(strm, - vas_rec_cb, vas_play_cb, - strm, vas_setting)); + vas_rec_cb, vas_play_cb, + strm, vas_setting)); if (err != KErrNone) { - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err); + pj_pool_release(pool); + return PJ_RETURN_OS_ERROR(err); } /* Done */ @@ -1767,7 +1766,7 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, /* API: Get stream info. */ static pj_status_t stream_get_param(pjmedia_aud_stream *s, - pjmedia_aud_param *pi) + pjmedia_aud_param *pi) { struct vas_stream *strm = (struct vas_stream*)s; @@ -1777,9 +1776,9 @@ static pj_status_t stream_get_param(pjmedia_aud_stream *s, /* Update the output volume setting */ if (stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - &pi->output_vol) == PJ_SUCCESS) + &pi->output_vol) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; + pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; } return PJ_SUCCESS; @@ -1787,8 +1786,8 @@ static pj_status_t stream_get_param(pjmedia_aud_stream *s, /* API: get capability */ static pj_status_t stream_get_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - void *pval) + pjmedia_aud_dev_cap cap, + void *pval) { struct vas_stream *strm = (struct vas_stream*)s; pj_status_t status = PJ_ENOTSUP; @@ -1797,48 +1796,48 @@ static pj_status_t stream_get_cap(pjmedia_aud_stream *s, switch (cap) { case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - *(pjmedia_aud_dev_route*)pval = strm->param.output_route; - status = PJ_SUCCESS; - } - break; + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + *(pjmedia_aud_dev_route*)pval = strm->param.output_route; + status = PJ_SUCCESS; + } + break; /* There is a case that GetMaxGain() stucks, e.g: in N95. */ /* case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_gain = strm->engine->GetMaxGain(); - TInt gain = strm->engine->GetGain(); - - if (max_gain > 0 && gain >= 0) { - *(unsigned*)pval = gain * 100 / max_gain; - status = PJ_SUCCESS; - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + TInt max_gain = strm->engine->GetMaxGain(); + TInt gain = strm->engine->GetGain(); + + if (max_gain > 0 && gain >= 0) { + *(unsigned*)pval = gain * 100 / max_gain; + status = PJ_SUCCESS; + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + break; */ case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_vol = strm->engine->GetMaxVolume(); - TInt vol = strm->engine->GetVolume(); - - if (max_vol > 0 && vol >= 0) { - *(unsigned*)pval = vol * 100 / max_vol; - status = PJ_SUCCESS; - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + TInt max_vol = strm->engine->GetMaxVolume(); + TInt vol = strm->engine->GetVolume(); + + if (max_vol > 0 && vol >= 0) { + *(unsigned*)pval = vol * 100 / max_vol; + status = PJ_SUCCESS; + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + break; default: - break; + break; } return status; @@ -1846,8 +1845,8 @@ static pj_status_t stream_get_cap(pjmedia_aud_stream *s, /* API: set capability */ static pj_status_t stream_set_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - const void *pval) + pjmedia_aud_dev_cap cap, + const void *pval) { struct vas_stream *strm = (struct vas_stream*)s; pj_status_t status = PJ_ENOTSUP; @@ -1856,73 +1855,73 @@ static pj_status_t stream_set_cap(pjmedia_aud_stream *s, switch (cap) { case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - pjmedia_aud_dev_route r = *(const pjmedia_aud_dev_route*)pval; - TInt err; - - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - switch (r) { - case PJMEDIA_AUD_DEV_ROUTE_DEFAULT: - case PJMEDIA_AUD_DEV_ROUTE_EARPIECE: - err = strm->engine->ActivateSpeaker(EFalse); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - break; - case PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER: - err = strm->engine->ActivateSpeaker(ETrue); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - break; - default: - status = PJ_EINVAL; - break; - } - if (status == PJ_SUCCESS) - strm->param.output_route = r; - } - break; + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + pjmedia_aud_dev_route r = *(const pjmedia_aud_dev_route*)pval; + TInt err; + + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + switch (r) { + case PJMEDIA_AUD_DEV_ROUTE_DEFAULT: + case PJMEDIA_AUD_DEV_ROUTE_EARPIECE: + err = strm->engine->ActivateSpeaker(EFalse); + status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); + break; + case PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER: + err = strm->engine->ActivateSpeaker(ETrue); + status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); + break; + default: + status = PJ_EINVAL; + break; + } + if (status == PJ_SUCCESS) + strm->param.output_route = r; + } + break; /* There is a case that GetMaxGain() stucks, e.g: in N95. */ /* case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_gain = strm->engine->GetMaxGain(); - if (max_gain > 0) { - TInt gain, err; - - gain = *(unsigned*)pval * max_gain / 100; - err = strm->engine->SetGain(gain); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - if (status == PJ_SUCCESS) - strm->param.input_vol = *(unsigned*)pval; - } - break; + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + TInt max_gain = strm->engine->GetMaxGain(); + if (max_gain > 0) { + TInt gain, err; + + gain = *(unsigned*)pval * max_gain / 100; + err = strm->engine->SetGain(gain); + status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + if (status == PJ_SUCCESS) + strm->param.input_vol = *(unsigned*)pval; + } + break; */ case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_vol = strm->engine->GetMaxVolume(); - if (max_vol > 0) { - TInt vol, err; - - vol = *(unsigned*)pval * max_vol / 100; - err = strm->engine->SetVolume(vol); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - if (status == PJ_SUCCESS) - strm->param.output_vol = *(unsigned*)pval; - } - break; + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + TInt max_vol = strm->engine->GetMaxVolume(); + if (max_vol > 0) { + TInt vol, err; + + vol = *(unsigned*)pval * max_vol / 100; + err = strm->engine->SetVolume(vol); + status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + if (status == PJ_SUCCESS) + strm->param.output_vol = *(unsigned*)pval; + } + break; default: - break; + break; } return status; @@ -1936,36 +1935,36 @@ static pj_status_t stream_start(pjmedia_aud_stream *strm) PJ_ASSERT_RETURN(stream, PJ_EINVAL); if (stream->engine) { - enum { VAS_WAIT_START = 2000 }; /* in msecs */ - TTime start, now; - TInt err = stream->engine->Start(); - - if (err != KErrNone) - return PJ_RETURN_OS_ERROR(err); - - /* Perform synchronous start, timeout after VAS_WAIT_START ms */ - start.UniversalTime(); - do { - pj_symbianos_poll(-1, 100); - now.UniversalTime(); - } while (!stream->engine->IsStarted() && - (now.MicroSecondsFrom(start) < VAS_WAIT_START * 1000)); - - if (stream->engine->IsStarted()) { - - /* Apply output volume setting if specified */ - if (stream->param.flags & - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) - { - stream_set_cap(strm, - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - &stream->param.output_vol); - } - - return PJ_SUCCESS; - } else { - return PJ_ETIMEDOUT; - } + enum { VAS_WAIT_START = 2000 }; /* in msecs */ + TTime start, now; + TInt err = stream->engine->Start(); + + if (err != KErrNone) + return PJ_RETURN_OS_ERROR(err); + + /* Perform synchronous start, timeout after VAS_WAIT_START ms */ + start.UniversalTime(); + do { + pj_symbianos_poll(-1, 100); + now.UniversalTime(); + } while (!stream->engine->IsStarted() && + (now.MicroSecondsFrom(start) < VAS_WAIT_START * 1000)); + + if (stream->engine->IsStarted()) { + + /* Apply output volume setting if specified */ + if (stream->param.flags & + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) + { + stream_set_cap(strm, + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + &stream->param.output_vol); + } + + return PJ_SUCCESS; + } else { + return PJ_ETIMEDOUT; + } } return PJ_EINVALIDOP; @@ -1979,7 +1978,7 @@ static pj_status_t stream_stop(pjmedia_aud_stream *strm) PJ_ASSERT_RETURN(stream, PJ_EINVAL); if (stream->engine) { - stream->engine->Stop(); + stream->engine->Stop(); } return PJ_SUCCESS; @@ -1999,16 +1998,16 @@ static pj_status_t stream_destroy(pjmedia_aud_stream *strm) stream->engine = NULL; if (stream->param.ext_fmt.id == PJMEDIA_FORMAT_G729) { - TBitStream *g729_bitstream = (TBitStream*)stream->strm_data; - stream->strm_data = NULL; - delete g729_bitstream; + TBitStream *g729_bitstream = (TBitStream*)stream->strm_data; + stream->strm_data = NULL; + delete g729_bitstream; } pj_pool_t *pool; pool = stream->pool; if (pool) { - stream->pool = NULL; - pj_pool_release(pool); + stream->pool = NULL; + pj_pool_release(pool); } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia-audiodev/wasapi_dev.cpp b/pjmedia/src/pjmedia-audiodev/wasapi_dev.cpp index baa5e6bb0b..998353dc1e 100644 --- a/pjmedia/src/pjmedia-audiodev/wasapi_dev.cpp +++ b/pjmedia/src/pjmedia-audiodev/wasapi_dev.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -45,21 +44,21 @@ using namespace Windows::Phone::Media::Devices; #endif -#define THIS_FILE "wasapi_dev.cpp" +#define THIS_FILE "wasapi_dev.cpp" /* Set to 1 to enable tracing */ #if 1 -# define TRACE_(expr) PJ_LOG(4,expr) +# define TRACE_(expr) PJ_LOG(4,expr) #else # define TRACE_(expr) #endif #define EXIT_ON_ERROR(hr) \ - do { \ - if(FAILED(hr)) { \ - status = PJMEDIA_EAUD_WASAPI_ERROR; \ - goto on_exit; }\ - } while (0) + do { \ + if(FAILED(hr)) { \ + status = PJMEDIA_EAUD_WASAPI_ERROR; \ + goto on_exit; }\ + } while (0) struct wasapi_stream; @@ -72,7 +71,7 @@ class AudioActivator : public RuntimeClass< RuntimeClassFlags< ClassicCom >, IActivateAudioInterfaceCompletionHandler > { STDMETHODIMP ActivateCompleted(IActivateAudioInterfaceAsyncOperation - *pAsyncOp); + *pAsyncOp); public: AudioActivator() {}; task_completion_event> task_completed; @@ -83,60 +82,60 @@ class AudioActivator : public RuntimeClass< RuntimeClassFlags< ClassicCom >, /* WASAPI factory */ struct wasapi_factory { - pjmedia_aud_dev_factory base; - pj_pool_t *base_pool; - pj_pool_t *pool; - pj_pool_factory *pf; + pjmedia_aud_dev_factory base; + pj_pool_t *base_pool; + pj_pool_t *pool; + pj_pool_factory *pf; - unsigned dev_count; - pjmedia_aud_dev_info devs[1]; + unsigned dev_count; + pjmedia_aud_dev_info devs[1]; }; /* Sound stream. */ struct wasapi_stream { - pjmedia_aud_stream base; /* Base stream */ + pjmedia_aud_stream base; /* Base stream */ /* Common */ - pjmedia_aud_param param; /* Settings */ - pj_pool_t *pool; /* Memory pool */ - void *user_data; /* Application data */ + pjmedia_aud_param param; /* Settings */ + pj_pool_t *pool; /* Memory pool */ + void *user_data; /* Application data */ struct wasapi_factory *wf; - pj_thread_t *thread; /* Thread handle */ - HANDLE quit_event; - pjmedia_format_id fmt_id; /* Frame format */ - unsigned bytes_per_sample; + pj_thread_t *thread; /* Thread handle */ + HANDLE quit_event; + pjmedia_format_id fmt_id; /* Frame format */ + unsigned bytes_per_sample; /* Playback */ - pjmedia_aud_play_cb pb_cb; /* Playback callback */ - IAudioClient2 *default_pb_dev; /* Default playback dev */ - IAudioRenderClient *pb_client; /* Playback client */ - ISimpleAudioVolume *pb_volume; /* Playback volume */ - unsigned pb_max_frame_count; - HANDLE pb_event; /* Playback event */ - pj_timestamp pb_timestamp; + pjmedia_aud_play_cb pb_cb; /* Playback callback */ + IAudioClient2 *default_pb_dev; /* Default playback dev */ + IAudioRenderClient *pb_client; /* Playback client */ + ISimpleAudioVolume *pb_volume; /* Playback volume */ + unsigned pb_max_frame_count; + HANDLE pb_event; /* Playback event */ + pj_timestamp pb_timestamp; #if defined(USE_ASYNC_ACTIVATE) ComPtr pb_aud_act; - Platform::String^ pb_id; + Platform::String^ pb_id; #else - LPCWSTR pb_id; + LPCWSTR pb_id; #endif /* Capture */ - pjmedia_aud_rec_cb cap_cb; /* Capture callback */ - IAudioClient2 *default_cap_dev; /* Default capture dev */ - IAudioCaptureClient *cap_client; /* Capture client */ - unsigned bytes_per_frame; /* Bytes per frame */ - pj_int16_t *cap_buf; /* Capture audio buffer */ - unsigned cap_max_frame_count; - HANDLE cap_event; /* Capture event */ - unsigned cap_buf_count; - pj_timestamp cap_timestamp; + pjmedia_aud_rec_cb cap_cb; /* Capture callback */ + IAudioClient2 *default_cap_dev; /* Default capture dev */ + IAudioCaptureClient *cap_client; /* Capture client */ + unsigned bytes_per_frame; /* Bytes per frame */ + pj_int16_t *cap_buf; /* Capture audio buffer */ + unsigned cap_max_frame_count; + HANDLE cap_event; /* Capture event */ + unsigned cap_buf_count; + pj_timestamp cap_timestamp; #if defined(USE_ASYNC_ACTIVATE) ComPtr cap_aud_act; - Platform::String^ cap_id; + Platform::String^ cap_id; #else - LPCWSTR cap_id; + LPCWSTR cap_id; #endif }; @@ -196,43 +195,43 @@ static pjmedia_aud_stream_op stream_op = }; static pj_status_t init_waveformatex(WAVEFORMATEX *wfx, - const pjmedia_aud_param *prm, - struct wasapi_stream *strm) + const pjmedia_aud_param *prm, + struct wasapi_stream *strm) { if (prm->ext_fmt.id == PJMEDIA_FORMAT_L16) { - wfx->wFormatTag = WAVE_FORMAT_PCM; - wfx->nChannels = (pj_uint16_t)prm->channel_count; - wfx->nSamplesPerSec = prm->clock_rate; - wfx->nBlockAlign = (pj_uint16_t)(prm->channel_count * - strm->bytes_per_sample); - wfx->nAvgBytesPerSec = prm->clock_rate * prm->channel_count * - strm->bytes_per_sample; - wfx->wBitsPerSample = (WORD)prm->bits_per_sample; - wfx->cbSize = 0; - - return PJ_SUCCESS; + wfx->wFormatTag = WAVE_FORMAT_PCM; + wfx->nChannels = (pj_uint16_t)prm->channel_count; + wfx->nSamplesPerSec = prm->clock_rate; + wfx->nBlockAlign = (pj_uint16_t)(prm->channel_count * + strm->bytes_per_sample); + wfx->nAvgBytesPerSec = prm->clock_rate * prm->channel_count * + strm->bytes_per_sample; + wfx->wBitsPerSample = (WORD)prm->bits_per_sample; + wfx->cbSize = 0; + + return PJ_SUCCESS; } else if ((prm->flags & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT) && - (prm->ext_fmt.id == PJMEDIA_FORMAT_PCMA || - prm->ext_fmt.id == PJMEDIA_FORMAT_PCMU)) + (prm->ext_fmt.id == PJMEDIA_FORMAT_PCMA || + prm->ext_fmt.id == PJMEDIA_FORMAT_PCMU)) { - unsigned ptime; - ptime = prm->samples_per_frame * 1000 / - (prm->clock_rate * prm->channel_count); - wfx->wFormatTag = (pj_uint16_t) - ((prm->ext_fmt.id == PJMEDIA_FORMAT_PCMA) ? - WAVE_FORMAT_ALAW : WAVE_FORMAT_MULAW); - wfx->nChannels = (pj_uint16_t)prm->channel_count; - wfx->nSamplesPerSec = prm->clock_rate; - wfx->nAvgBytesPerSec = prm->clock_rate * prm->channel_count; - wfx->nBlockAlign = (pj_uint16_t)(wfx->nAvgBytesPerSec * ptime / - 1000); - wfx->wBitsPerSample = 8; - wfx->cbSize = 0; - - return PJ_SUCCESS; + unsigned ptime; + ptime = prm->samples_per_frame * 1000 / + (prm->clock_rate * prm->channel_count); + wfx->wFormatTag = (pj_uint16_t) + ((prm->ext_fmt.id == PJMEDIA_FORMAT_PCMA) ? + WAVE_FORMAT_ALAW : WAVE_FORMAT_MULAW); + wfx->nChannels = (pj_uint16_t)prm->channel_count; + wfx->nSamplesPerSec = prm->clock_rate; + wfx->nAvgBytesPerSec = prm->clock_rate * prm->channel_count; + wfx->nBlockAlign = (pj_uint16_t)(wfx->nAvgBytesPerSec * ptime / + 1000); + wfx->wBitsPerSample = 8; + wfx->cbSize = 0; + + return PJ_SUCCESS; } else { - return PJMEDIA_EAUD_BADFORMAT; + return PJMEDIA_EAUD_BADFORMAT; } } @@ -251,9 +250,9 @@ static int PJ_THREAD_FUNC wasapi_dev_thread(void *arg) eventCount = 0; events[eventCount++] = strm->quit_event; if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) - events[eventCount++] = strm->pb_event; + events[eventCount++] = strm->pb_event; if (strm->param.dir & PJMEDIA_DIR_CAPTURE) - events[eventCount++] = strm->cap_event; + events[eventCount++] = strm->cap_event; /* * Loop while not signalled to quit, wait for event objects to be @@ -261,222 +260,222 @@ static int PJ_THREAD_FUNC wasapi_dev_thread(void *arg) */ while (status == PJ_SUCCESS) { - DWORD rc; - pjmedia_dir signalled_dir; - HRESULT hr; + DWORD rc; + pjmedia_dir signalled_dir; + HRESULT hr; - /* Swap hWaveIn and hWaveOut to get equal opportunity for both */ - if (eventCount==3) { - HANDLE hTemp = events[2]; - events[2] = events[1]; - events[1] = hTemp; - } - - rc = WaitForMultipleObjectsEx(eventCount, events, FALSE, INFINITE, - FALSE); - - if (rc < WAIT_OBJECT_0 || rc >= WAIT_OBJECT_0 + eventCount) - continue; - - if (rc == WAIT_OBJECT_0) - break; - - if (rc == (WAIT_OBJECT_0 + 1)) { - if (events[1] == strm->pb_event) - signalled_dir = PJMEDIA_DIR_PLAYBACK; - else - signalled_dir = PJMEDIA_DIR_CAPTURE; - } else { - if (events[2] == strm->pb_event) - signalled_dir = PJMEDIA_DIR_PLAYBACK; - else - signalled_dir = PJMEDIA_DIR_CAPTURE; - } - - if (signalled_dir == PJMEDIA_DIR_PLAYBACK) { - unsigned incoming_frame = 0; - unsigned frame_to_render = 0; - unsigned padding = 0; - BYTE *cur_pb_buf = NULL; - pjmedia_frame frame; - - status = PJ_SUCCESS; - - /* Get available space on buffer to render */ - hr = strm->default_pb_dev->GetCurrentPadding(&padding); - if (FAILED(hr)) { - continue; - } - - incoming_frame = strm->bytes_per_frame / - (strm->bytes_per_sample * - strm->param.channel_count); - frame_to_render = strm->pb_max_frame_count - padding; - if (frame_to_render >= incoming_frame) { - frame_to_render = incoming_frame; - } else { - /* Don't get new frame because there's no space */ - continue; - } - - hr = strm->pb_client->GetBuffer(frame_to_render, &cur_pb_buf); - if (FAILED(hr)) { - PJ_LOG(4, (THIS_FILE, "Error getting wasapi buffer")); - continue; - } - - if (strm->fmt_id == PJMEDIA_FORMAT_L16) { - /* PCM mode */ - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.size = strm->bytes_per_frame; - frame.timestamp.u64 = strm->pb_timestamp.u64; - frame.bit_info = 0; - frame.buf = cur_pb_buf; - } - - status = (*strm->pb_cb)(strm->user_data, &frame); - - /* Write to the device. */ - hr = strm->pb_client->ReleaseBuffer(frame_to_render, 0); - if (FAILED(hr)) { - PJ_LOG(4, (THIS_FILE, "Error releasing wasapi buffer")); - continue; - } - - strm->pb_timestamp.u64 += strm->param.samples_per_frame / - strm->param.channel_count; - } else { - /* Capture */ - pj_uint32_t packet_size = 0; - - hr = strm->cap_client->GetNextPacketSize(&packet_size); - if (FAILED(hr)) { - PJ_LOG(4, (THIS_FILE, "Error getting next packet size")); - continue; - } - - while (packet_size) { - - unsigned next_frame_size = 0; - DWORD cap_flag; - pj_int16_t *cap_buf = NULL; - unsigned nsamples = 0; - - hr = strm->cap_client->GetBuffer((BYTE**)&cap_buf, - &next_frame_size, - &cap_flag, - NULL, - NULL); - - if (FAILED(hr) || (next_frame_size == 0)) { - PJ_LOG(4, (THIS_FILE, "Error getting next buffer, \ - next frame size : %d", next_frame_size)); - packet_size = 0; - continue; - } - - nsamples = (next_frame_size * strm->param.channel_count) - + strm->cap_buf_count; - - if (nsamples >= strm->param.samples_per_frame) { - /* If buffer is not empty, combine the buffer with the just - * incoming samples, then call put_frame. - */ - if (strm->cap_buf_count) { - unsigned chunk_count = 0; - pjmedia_frame frame; - - chunk_count = strm->param.samples_per_frame - - strm->cap_buf_count; - - pjmedia_copy_samples(strm->cap_buf + - strm->cap_buf_count, - (pj_int16_t*)cap_buf, - chunk_count); - - if (strm->fmt_id == PJMEDIA_FORMAT_L16) { - /* PCM mode */ - /* Prepare frame */ - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = (void *)strm->cap_buf; - frame.size = strm->bytes_per_frame; - frame.timestamp.u64 = strm->cap_timestamp.u64; - frame.bit_info = 0; - } - - status = (*strm->cap_cb)(strm->user_data, &frame); - if (status == PJ_SUCCESS) { - /* Update position */ - cap_buf = (pj_int16_t *)cap_buf + chunk_count; - nsamples -= strm->param.samples_per_frame; - strm->cap_timestamp.u64 += - strm->param.samples_per_frame / - strm->param.channel_count; - } - } - - /* Give all frame we have */ - while (nsamples >= strm->param.samples_per_frame && - status == PJ_SUCCESS) - { - pjmedia_frame frame; - - pjmedia_copy_samples(strm->cap_buf, - (pj_int16_t*)cap_buf, - strm->param.samples_per_frame); - - if (strm->fmt_id == PJMEDIA_FORMAT_L16) { - /* PCM mode */ - /* Prepare frame */ - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = (void *)strm->cap_buf; - frame.size = strm->bytes_per_frame; - frame.timestamp.u64 = strm->cap_timestamp.u64; - frame.bit_info = 0; - } - status = (*strm->cap_cb)(strm->user_data, &frame); - - if (status == PJ_SUCCESS) { - /* Update position */ - cap_buf = (pj_int16_t *)cap_buf + - strm->param.samples_per_frame; - - nsamples -= strm->param.samples_per_frame; - strm->cap_timestamp.u64 += - strm->param.samples_per_frame / - strm->param.channel_count; - } else { - nsamples = 0; - } - } - strm->cap_buf_count = nsamples; - - /* Store the remaining samples into the buffer */ - if (nsamples && (status == PJ_SUCCESS)) { - pjmedia_copy_samples(strm->cap_buf, - (pj_int16_t*)cap_buf, - nsamples); - } - } else { - /* Not enough samples, let's just store them in the - * buffer. - */ - pjmedia_copy_samples(strm->cap_buf + strm->cap_buf_count, - (pj_int16_t*)cap_buf, - next_frame_size * - strm->param.channel_count); - - strm->cap_buf_count = nsamples; - } - hr = strm->cap_client->ReleaseBuffer(next_frame_size); - - hr = strm->cap_client->GetNextPacketSize(&packet_size); - if (FAILED(hr)) { - PJ_LOG(4, (THIS_FILE, "Error getting next packet size")); - packet_size = 0; - } - } - } + /* Swap hWaveIn and hWaveOut to get equal opportunity for both */ + if (eventCount==3) { + HANDLE hTemp = events[2]; + events[2] = events[1]; + events[1] = hTemp; + } + + rc = WaitForMultipleObjectsEx(eventCount, events, FALSE, INFINITE, + FALSE); + + if (rc < WAIT_OBJECT_0 || rc >= WAIT_OBJECT_0 + eventCount) + continue; + + if (rc == WAIT_OBJECT_0) + break; + + if (rc == (WAIT_OBJECT_0 + 1)) { + if (events[1] == strm->pb_event) + signalled_dir = PJMEDIA_DIR_PLAYBACK; + else + signalled_dir = PJMEDIA_DIR_CAPTURE; + } else { + if (events[2] == strm->pb_event) + signalled_dir = PJMEDIA_DIR_PLAYBACK; + else + signalled_dir = PJMEDIA_DIR_CAPTURE; + } + + if (signalled_dir == PJMEDIA_DIR_PLAYBACK) { + unsigned incoming_frame = 0; + unsigned frame_to_render = 0; + unsigned padding = 0; + BYTE *cur_pb_buf = NULL; + pjmedia_frame frame; + + status = PJ_SUCCESS; + + /* Get available space on buffer to render */ + hr = strm->default_pb_dev->GetCurrentPadding(&padding); + if (FAILED(hr)) { + continue; + } + + incoming_frame = strm->bytes_per_frame / + (strm->bytes_per_sample * + strm->param.channel_count); + frame_to_render = strm->pb_max_frame_count - padding; + if (frame_to_render >= incoming_frame) { + frame_to_render = incoming_frame; + } else { + /* Don't get new frame because there's no space */ + continue; + } + + hr = strm->pb_client->GetBuffer(frame_to_render, &cur_pb_buf); + if (FAILED(hr)) { + PJ_LOG(4, (THIS_FILE, "Error getting wasapi buffer")); + continue; + } + + if (strm->fmt_id == PJMEDIA_FORMAT_L16) { + /* PCM mode */ + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.size = strm->bytes_per_frame; + frame.timestamp.u64 = strm->pb_timestamp.u64; + frame.bit_info = 0; + frame.buf = cur_pb_buf; + } + + status = (*strm->pb_cb)(strm->user_data, &frame); + + /* Write to the device. */ + hr = strm->pb_client->ReleaseBuffer(frame_to_render, 0); + if (FAILED(hr)) { + PJ_LOG(4, (THIS_FILE, "Error releasing wasapi buffer")); + continue; + } + + strm->pb_timestamp.u64 += strm->param.samples_per_frame / + strm->param.channel_count; + } else { + /* Capture */ + pj_uint32_t packet_size = 0; + + hr = strm->cap_client->GetNextPacketSize(&packet_size); + if (FAILED(hr)) { + PJ_LOG(4, (THIS_FILE, "Error getting next packet size")); + continue; + } + + while (packet_size) { + + unsigned next_frame_size = 0; + DWORD cap_flag; + pj_int16_t *cap_buf = NULL; + unsigned nsamples = 0; + + hr = strm->cap_client->GetBuffer((BYTE**)&cap_buf, + &next_frame_size, + &cap_flag, + NULL, + NULL); + + if (FAILED(hr) || (next_frame_size == 0)) { + PJ_LOG(4, (THIS_FILE, "Error getting next buffer, \ + next frame size : %d", next_frame_size)); + packet_size = 0; + continue; + } + + nsamples = (next_frame_size * strm->param.channel_count) + + strm->cap_buf_count; + + if (nsamples >= strm->param.samples_per_frame) { + /* If buffer is not empty, combine the buffer with the just + * incoming samples, then call put_frame. + */ + if (strm->cap_buf_count) { + unsigned chunk_count = 0; + pjmedia_frame frame; + + chunk_count = strm->param.samples_per_frame - + strm->cap_buf_count; + + pjmedia_copy_samples(strm->cap_buf + + strm->cap_buf_count, + (pj_int16_t*)cap_buf, + chunk_count); + + if (strm->fmt_id == PJMEDIA_FORMAT_L16) { + /* PCM mode */ + /* Prepare frame */ + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = (void *)strm->cap_buf; + frame.size = strm->bytes_per_frame; + frame.timestamp.u64 = strm->cap_timestamp.u64; + frame.bit_info = 0; + } + + status = (*strm->cap_cb)(strm->user_data, &frame); + if (status == PJ_SUCCESS) { + /* Update position */ + cap_buf = (pj_int16_t *)cap_buf + chunk_count; + nsamples -= strm->param.samples_per_frame; + strm->cap_timestamp.u64 += + strm->param.samples_per_frame / + strm->param.channel_count; + } + } + + /* Give all frame we have */ + while (nsamples >= strm->param.samples_per_frame && + status == PJ_SUCCESS) + { + pjmedia_frame frame; + + pjmedia_copy_samples(strm->cap_buf, + (pj_int16_t*)cap_buf, + strm->param.samples_per_frame); + + if (strm->fmt_id == PJMEDIA_FORMAT_L16) { + /* PCM mode */ + /* Prepare frame */ + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = (void *)strm->cap_buf; + frame.size = strm->bytes_per_frame; + frame.timestamp.u64 = strm->cap_timestamp.u64; + frame.bit_info = 0; + } + status = (*strm->cap_cb)(strm->user_data, &frame); + + if (status == PJ_SUCCESS) { + /* Update position */ + cap_buf = (pj_int16_t *)cap_buf + + strm->param.samples_per_frame; + + nsamples -= strm->param.samples_per_frame; + strm->cap_timestamp.u64 += + strm->param.samples_per_frame / + strm->param.channel_count; + } else { + nsamples = 0; + } + } + strm->cap_buf_count = nsamples; + + /* Store the remaining samples into the buffer */ + if (nsamples && (status == PJ_SUCCESS)) { + pjmedia_copy_samples(strm->cap_buf, + (pj_int16_t*)cap_buf, + nsamples); + } + } else { + /* Not enough samples, let's just store them in the + * buffer. + */ + pjmedia_copy_samples(strm->cap_buf + strm->cap_buf_count, + (pj_int16_t*)cap_buf, + next_frame_size * + strm->param.channel_count); + + strm->cap_buf_count = nsamples; + } + hr = strm->cap_client->ReleaseBuffer(next_frame_size); + + hr = strm->cap_client->GetNextPacketSize(&packet_size); + if (FAILED(hr)) { + PJ_LOG(4, (THIS_FILE, "Error getting next packet size")); + packet_size = 0; + } + } + } } PJ_LOG(5,(THIS_FILE, "WASAPI: thread stopping..")); @@ -490,27 +489,27 @@ static pj_status_t activate_capture_dev(struct wasapi_stream *ws) #if defined(USE_ASYNC_ACTIVATE) ComPtr async_op; ws->cap_id = MediaDevice::GetDefaultAudioCaptureId( - AudioDeviceRole::Communications); + AudioDeviceRole::Communications); #else ws->cap_id = GetDefaultAudioCaptureId(AudioDeviceRole::Communications); #endif if (!ws->cap_id) { - PJ_LOG(4, (THIS_FILE, "Error getting default capture device id")); - return PJMEDIA_EAUD_SYSERR; + PJ_LOG(4, (THIS_FILE, "Error getting default capture device id")); + return PJMEDIA_EAUD_SYSERR; } #if defined(USE_ASYNC_ACTIVATE) ws->cap_aud_act = Make(); if (ws->cap_aud_act == NULL) { - PJ_LOG(4, (THIS_FILE, "Error activating capture device")); - return PJMEDIA_EAUD_SYSERR; + PJ_LOG(4, (THIS_FILE, "Error activating capture device")); + return PJMEDIA_EAUD_SYSERR; } hr = ActivateAudioInterfaceAsync(ws->cap_id->Data(), - __uuidof(IAudioClient2), - NULL, ws->cap_aud_act.Get(), - &async_op); + __uuidof(IAudioClient2), + NULL, ws->cap_aud_act.Get(), + &async_op); //pj_thread_sleep(100); auto task_completed = create_task(ws->cap_aud_act->task_completed); @@ -518,14 +517,14 @@ static pj_status_t activate_capture_dev(struct wasapi_stream *ws) ws->default_cap_dev = task_completed.get().Get(); #else hr = ActivateAudioInterface(ws->cap_id, __uuidof(IAudioClient2), - (void**)&ws->default_cap_dev); + (void**)&ws->default_cap_dev); #endif AudioClientProperties properties = {}; if (SUCCEEDED(hr)) { - properties.cbSize = sizeof AudioClientProperties; - properties.eCategory = AudioCategory_Communications; - hr = ws->default_cap_dev->SetClientProperties(&properties); + properties.cbSize = sizeof AudioClientProperties; + properties.eCategory = AudioCategory_Communications; + hr = ws->default_cap_dev->SetClientProperties(&properties); } return FAILED(hr) ? PJMEDIA_EAUD_SYSERR : PJ_SUCCESS; @@ -535,7 +534,7 @@ static pj_status_t activate_capture_dev(struct wasapi_stream *ws) * Init capture device */ static pj_status_t init_capture_dev(struct wasapi_stream *ws, - const pjmedia_aud_param *prm) + const pjmedia_aud_param *prm) { pj_status_t status; HRESULT hr = E_FAIL; @@ -547,8 +546,8 @@ static pj_status_t init_capture_dev(struct wasapi_stream *ws, status = activate_capture_dev(ws); if (status != PJ_SUCCESS) { - PJ_LOG(4, (THIS_FILE, "Failed activating capture device")); - goto on_exit; + PJ_LOG(4, (THIS_FILE, "Failed activating capture device")); + goto on_exit; } stream_flags = 0x88140000; @@ -557,13 +556,13 @@ static pj_status_t init_capture_dev(struct wasapi_stream *ws, status = init_waveformatex(&wfx, prm, ws); if (status != PJ_SUCCESS) { - PJ_LOG(4, (THIS_FILE, "Error initiating wave format")); - goto on_exit; + PJ_LOG(4, (THIS_FILE, "Error initiating wave format")); + goto on_exit; } status = PJMEDIA_EAUD_SYSERR; ptime = prm->samples_per_frame * 1000 / - (prm->clock_rate * prm->channel_count); + (prm->clock_rate * prm->channel_count); ws->bytes_per_frame = prm->samples_per_frame * ws->bytes_per_sample; @@ -575,30 +574,30 @@ static pj_status_t init_capture_dev(struct wasapi_stream *ws, test = ws->param.input_latency_ms * 10000; hr = ws->default_cap_dev->Initialize(AUDCLNT_SHAREMODE_SHARED, - stream_flags, - //2000 * 10000, - ptime * ws->param.input_latency_ms * - 10000, - 0, - &wfx, - NULL); + stream_flags, + //2000 * 10000, + ptime * ws->param.input_latency_ms * + 10000, + 0, + &wfx, + NULL); EXIT_ON_ERROR(hr); ws->cap_buf = (pj_int16_t *)pj_pool_zalloc(ws->pool, ws->bytes_per_frame); - if (!ws->cap_buf) { - PJ_LOG(4, (THIS_FILE, "Error creating capture buffer")); - status = PJ_ENOMEM; + if (!ws->cap_buf) { + PJ_LOG(4, (THIS_FILE, "Error creating capture buffer")); + status = PJ_ENOMEM; - goto on_exit; + goto on_exit; } ws->cap_event = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS); if (!ws->cap_event) { - hr = HRESULT_FROM_WIN32(GetLastError()); + hr = HRESULT_FROM_WIN32(GetLastError()); - goto on_exit; + goto on_exit; } EXIT_ON_ERROR(hr); @@ -613,17 +612,17 @@ static pj_status_t init_capture_dev(struct wasapi_stream *ws, EXIT_ON_ERROR(hr); PJ_LOG(4, (THIS_FILE, - "Wasapi Sound recorder initialized (" - "clock_rate=%d, latency=%d, " - "channel_count=%d, samples_per_frame=%d (%dms))", - prm->clock_rate, ws->param.input_latency_ms, - prm->channel_count, prm->samples_per_frame, - ptime)); + "Wasapi Sound recorder initialized (" + "clock_rate=%d, latency=%d, " + "channel_count=%d, samples_per_frame=%d (%dms))", + prm->clock_rate, ws->param.input_latency_ms, + prm->channel_count, prm->samples_per_frame, + ptime)); status = PJ_SUCCESS; on_exit: if (status != PJ_SUCCESS) - wasapi_stream_destroy(&ws->base); + wasapi_stream_destroy(&ws->base); return status; } @@ -636,26 +635,26 @@ static pj_status_t activate_playback_dev(struct wasapi_stream *ws) ComPtr async_op; ws->pb_id = MediaDevice::GetDefaultAudioRenderId( - AudioDeviceRole::Communications); + AudioDeviceRole::Communications); #else ws->pb_id = GetDefaultAudioRenderId(AudioDeviceRole::Communications); #endif if (!ws->pb_id) { - PJ_LOG(4, (THIS_FILE, "Error getting default playback device id")); - return PJMEDIA_EAUD_SYSERR; + PJ_LOG(4, (THIS_FILE, "Error getting default playback device id")); + return PJMEDIA_EAUD_SYSERR; } #if defined(USE_ASYNC_ACTIVATE) ws->pb_aud_act = Make(); if (ws->pb_aud_act == NULL) { - PJ_LOG(4, (THIS_FILE, "Error activating playback device")); - return PJMEDIA_EAUD_SYSERR; + PJ_LOG(4, (THIS_FILE, "Error activating playback device")); + return PJMEDIA_EAUD_SYSERR; } hr = ActivateAudioInterfaceAsync(ws->pb_id->Data(), - __uuidof(IAudioClient2), - NULL, ws->pb_aud_act.Get(), - &async_op); + __uuidof(IAudioClient2), + NULL, ws->pb_aud_act.Get(), + &async_op); //pj_thread_sleep(100); auto task_completed = create_task(ws->pb_aud_act->task_completed); @@ -663,15 +662,15 @@ static pj_status_t activate_playback_dev(struct wasapi_stream *ws) ws->default_pb_dev = task_completed.get().Get(); #else hr = ActivateAudioInterface(ws->pb_id, __uuidof(IAudioClient2), - (void**)&ws->default_pb_dev); + (void**)&ws->default_pb_dev); #endif AudioClientProperties properties = {}; if (SUCCEEDED(hr)) { - properties.cbSize = sizeof AudioClientProperties; - properties.eCategory = AudioCategory_Communications; - hr = ws->default_pb_dev->SetClientProperties(&properties); + properties.cbSize = sizeof AudioClientProperties; + properties.eCategory = AudioCategory_Communications; + hr = ws->default_pb_dev->SetClientProperties(&properties); } return FAILED(hr) ? PJMEDIA_EAUD_SYSERR : PJ_SUCCESS; @@ -681,7 +680,7 @@ static pj_status_t activate_playback_dev(struct wasapi_stream *ws) * Init playback device */ static pj_status_t init_playback_dev(struct wasapi_stream *ws, - const pjmedia_aud_param *prm) + const pjmedia_aud_param *prm) { HRESULT hr = E_FAIL; pj_status_t status; @@ -691,8 +690,8 @@ static pj_status_t init_playback_dev(struct wasapi_stream *ws, status = activate_playback_dev(ws); if (status != PJ_SUCCESS) { - PJ_LOG(4, (THIS_FILE, "Failed activating playback device")); - goto on_exit; + PJ_LOG(4, (THIS_FILE, "Failed activating playback device")); + goto on_exit; } stream_flags = 0x88140000; @@ -700,24 +699,24 @@ static pj_status_t init_playback_dev(struct wasapi_stream *ws, status = init_waveformatex(&wfx, prm, ws); if (status != PJ_SUCCESS) { - PJ_LOG(4, (THIS_FILE, "Error initiating wave format")); + PJ_LOG(4, (THIS_FILE, "Error initiating wave format")); - goto on_exit; + goto on_exit; } status = PJMEDIA_EAUD_SYSERR; ptime = prm->samples_per_frame * 1000 / - (prm->clock_rate * prm->channel_count); + (prm->clock_rate * prm->channel_count); ws->bytes_per_frame = prm->samples_per_frame * ws->bytes_per_sample; hr = ws->default_pb_dev->Initialize(AUDCLNT_SHAREMODE_SHARED, - stream_flags, - ws->param.output_latency_ms * 10000, - //0, - 0, - &wfx, - NULL); + stream_flags, + ws->param.output_latency_ms * 10000, + //0, + 0, + &wfx, + NULL); EXIT_ON_ERROR(hr); @@ -728,9 +727,9 @@ static pj_status_t init_playback_dev(struct wasapi_stream *ws, ws->pb_event = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS); if (!ws->pb_event) { - hr = HRESULT_FROM_WIN32(GetLastError()); + hr = HRESULT_FROM_WIN32(GetLastError()); - goto on_exit; + goto on_exit; } EXIT_ON_ERROR(hr); @@ -740,30 +739,30 @@ static pj_status_t init_playback_dev(struct wasapi_stream *ws, EXIT_ON_ERROR(hr); hr = ws->default_pb_dev->GetService(__uuidof(IAudioRenderClient), - (void**)&ws->pb_client); + (void**)&ws->pb_client); EXIT_ON_ERROR(hr); /* Other/optional supported interfaces */ hr = ws->default_pb_dev->GetService(__uuidof(ISimpleAudioVolume), - (void**)&ws->pb_volume); + (void**)&ws->pb_volume); if (FAILED(hr)) { - PJ_LOG(4, (THIS_FILE, "Error getting vol service playback:0x%x", hr)); + PJ_LOG(4, (THIS_FILE, "Error getting vol service playback:0x%x", hr)); } PJ_LOG(4, (THIS_FILE, - " Wasapi Sound player initialized (" - "clock_rate=%d, latency=%d, " - "channel_count=%d, samples_per_frame=%d (%dms))", - prm->clock_rate, ws->param.output_latency_ms, - prm->channel_count, prm->samples_per_frame, - ptime)); + " Wasapi Sound player initialized (" + "clock_rate=%d, latency=%d, " + "channel_count=%d, samples_per_frame=%d (%dms))", + prm->clock_rate, ws->param.output_latency_ms, + prm->channel_count, prm->samples_per_frame, + ptime)); status = PJ_SUCCESS; on_exit: if (status != PJ_SUCCESS) - wasapi_stream_destroy(&ws->base); + wasapi_stream_destroy(&ws->base); return status; } @@ -778,7 +777,7 @@ static pj_status_t wasapi_add_dev(struct wasapi_factory *wf) LPCWSTR render_id = NULL; if (wf->dev_count >= PJ_ARRAY_SIZE(wf->devs)) - return PJ_ETOOMANY; + return PJ_ETOOMANY; adi = &wf->devs[wf->dev_count]; @@ -792,30 +791,30 @@ static pj_status_t wasapi_add_dev(struct wasapi_factory *wf) /* Get default capture device */ #if defined(USE_ASYNC_ACTIVATE) capture_id = MediaDevice::GetDefaultAudioCaptureId( - AudioDeviceRole::Communications)->Data(); + AudioDeviceRole::Communications)->Data(); #else capture_id = GetDefaultAudioCaptureId(AudioDeviceRole::Communications); #endif if (!capture_id) { - PJ_LOG(4, (THIS_FILE, "Failed to get default audio capture")); + PJ_LOG(4, (THIS_FILE, "Failed to get default audio capture")); } /* Get default render device */ #if defined(USE_ASYNC_ACTIVATE) render_id = MediaDevice::GetDefaultAudioRenderId( - AudioDeviceRole::Communications)->Data(); + AudioDeviceRole::Communications)->Data(); #else render_id = GetDefaultAudioRenderId(AudioDeviceRole::Communications); #endif if (!render_id) { - PJ_LOG(4, (THIS_FILE, "Failed to get default audio render")); + PJ_LOG(4, (THIS_FILE, "Failed to get default audio render")); } if (!capture_id && !render_id) { - PJ_LOG(4, (THIS_FILE, "Unable to open default sound device")); - return PJMEDIA_EAUD_NODEV; + PJ_LOG(4, (THIS_FILE, "Unable to open default sound device")); + return PJMEDIA_EAUD_NODEV; } /* Check the number of capture channels */ @@ -828,13 +827,13 @@ static pj_status_t wasapi_add_dev(struct wasapi_factory *wf) adi->default_samples_per_sec = 8000; adi->caps = PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE; + PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY | + PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE; adi->routes = PJMEDIA_AUD_DEV_ROUTE_DEFAULT | - PJMEDIA_AUD_DEV_ROUTE_EARPIECE | - PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER | - PJMEDIA_AUD_DEV_ROUTE_BLUETOOTH; + PJMEDIA_AUD_DEV_ROUTE_EARPIECE | + PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER | + PJMEDIA_AUD_DEV_ROUTE_BLUETOOTH; ++wf->dev_count; @@ -842,10 +841,10 @@ static pj_status_t wasapi_add_dev(struct wasapi_factory *wf) #if !defined(USE_ASYNC_ACTIVATE) if (capture_id) - CoTaskMemFree((LPVOID*)capture_id); + CoTaskMemFree((LPVOID*)capture_id); if (render_id) - CoTaskMemFree((LPVOID*)render_id); + CoTaskMemFree((LPVOID*)render_id); #endif return PJ_SUCCESS; @@ -897,7 +896,7 @@ static pj_status_t wasapi_factory_destroy(pjmedia_aud_dev_factory *f) if (wf->pool) { TRACE_((THIS_FILE, "wasapi_factory_destroy()")); - pj_pool_release(wf->pool); + pj_pool_release(wf->pool); } return PJ_SUCCESS; @@ -1022,29 +1021,29 @@ static pj_status_t wasapi_factory_create_stream(pjmedia_aud_dev_factory *f, /* Init capture */ if (param->dir & PJMEDIA_DIR_CAPTURE) { - status = init_capture_dev(strm, param); - if (status != PJ_SUCCESS) { - wasapi_stream_destroy(&strm->base); - return status; - } + status = init_capture_dev(strm, param); + if (status != PJ_SUCCESS) { + wasapi_stream_destroy(&strm->base); + return status; + } } /* Init playback */ if (param->dir & PJMEDIA_DIR_PLAYBACK) { - status = init_playback_dev(strm, param); + status = init_playback_dev(strm, param); if (status != PJ_SUCCESS) { - wasapi_stream_destroy(&strm->base); + wasapi_stream_destroy(&strm->base); return status; - } + } } strm->quit_event = CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, - EVENT_ALL_ACCESS); + EVENT_ALL_ACCESS); if (!strm->quit_event) { - PJ_LOG(4, (THIS_FILE, "Error creating quit event:0x%x", - HRESULT_FROM_WIN32(GetLastError()))); + PJ_LOG(4, (THIS_FILE, "Error creating quit event:0x%x", + HRESULT_FROM_WIN32(GetLastError()))); - return PJMEDIA_EAUD_SYSERR; + return PJMEDIA_EAUD_SYSERR; } /* Done */ @@ -1130,29 +1129,29 @@ static pj_status_t wasapi_stream_start(pjmedia_aud_stream *strm) TRACE_((THIS_FILE, "Starting wasapi audio stream")); if (ws->default_pb_dev) { - hr = ws->default_pb_dev->Start(); - EXIT_ON_ERROR(hr); + hr = ws->default_pb_dev->Start(); + EXIT_ON_ERROR(hr); } if (ws->default_cap_dev) { - hr = ws->default_cap_dev->Start(); - EXIT_ON_ERROR(hr); + hr = ws->default_cap_dev->Start(); + EXIT_ON_ERROR(hr); } /* Create and start the thread */ if (!ws->thread) { - status = pj_thread_create(ws->pool, "wasapi", &wasapi_dev_thread, strm, - 0, 0, &ws->thread); + status = pj_thread_create(ws->pool, "wasapi", &wasapi_dev_thread, strm, + 0, 0, &ws->thread); - if (status != PJ_SUCCESS) { - PJ_LOG(4, (THIS_FILE, "Error creating wasapi thread:%d", status)); - } + if (status != PJ_SUCCESS) { + PJ_LOG(4, (THIS_FILE, "Error creating wasapi thread:%d", status)); + } } on_exit: if (status != PJ_SUCCESS) { - PJ_LOG(4, (THIS_FILE, "Error starting wasapi:0x%x", hr)); - wasapi_stream_stop(&ws->base); + PJ_LOG(4, (THIS_FILE, "Error starting wasapi:0x%x", hr)); + wasapi_stream_stop(&ws->base); } return status; @@ -1168,28 +1167,28 @@ static pj_status_t wasapi_stream_stop(pjmedia_aud_stream *strm) PJ_ASSERT_RETURN(ws != NULL, PJ_EINVAL); if (ws->default_pb_dev) { - hr = ws->default_pb_dev->Stop(); - if (FAILED(hr)) { - PJ_LOG(4, (THIS_FILE, "Error stopping wasapi playback stream:0x%x", - hr)); - } else { - PJ_LOG(4,(THIS_FILE, "Stopped wasapi playback stream")); - } + hr = ws->default_pb_dev->Stop(); + if (FAILED(hr)) { + PJ_LOG(4, (THIS_FILE, "Error stopping wasapi playback stream:0x%x", + hr)); + } else { + PJ_LOG(4,(THIS_FILE, "Stopped wasapi playback stream")); + } } if (ws->default_cap_dev) { - hr_tmp = ws->default_cap_dev->Stop(); - if (FAILED(hr_tmp)) { - hr = hr_tmp; - PJ_LOG(4, (THIS_FILE, "Error stopping wasapi capture stream:0x%x", - hr)); - } else { - PJ_LOG(4,(THIS_FILE, "Stopped wasapi capture stream")); - } + hr_tmp = ws->default_cap_dev->Stop(); + if (FAILED(hr_tmp)) { + hr = hr_tmp; + PJ_LOG(4, (THIS_FILE, "Error stopping wasapi capture stream:0x%x", + hr)); + } else { + PJ_LOG(4,(THIS_FILE, "Stopped wasapi capture stream")); + } } if (FAILED(hr)) { - return PJMEDIA_EAUD_WASAPI_ERROR; + return PJMEDIA_EAUD_WASAPI_ERROR; } return PJ_SUCCESS; @@ -1206,73 +1205,73 @@ static pj_status_t wasapi_stream_destroy(pjmedia_aud_stream *strm) /* Stop stream thread */ if (ws->thread) { - SetEvent(ws->quit_event); - pj_thread_join(ws->thread); - pj_thread_destroy(ws->thread); - ws->thread = NULL; + SetEvent(ws->quit_event); + pj_thread_join(ws->thread); + pj_thread_destroy(ws->thread); + ws->thread = NULL; } /* Close thread quit event */ if (ws->quit_event) { - CloseHandle(ws->quit_event); - ws->quit_event = NULL; + CloseHandle(ws->quit_event); + ws->quit_event = NULL; } /* Close playback event */ if (ws->pb_event) { - CloseHandle(ws->pb_event); - ws->pb_event = NULL; + CloseHandle(ws->pb_event); + ws->pb_event = NULL; } /* Close capture event */ if (ws->cap_event) { - CloseHandle(ws->cap_event); - ws->cap_event = NULL; + CloseHandle(ws->cap_event); + ws->cap_event = NULL; } /* Release playback device */ if (ws->default_pb_dev) { - ws->default_pb_dev->Release(); - ws->default_pb_dev = NULL; + ws->default_pb_dev->Release(); + ws->default_pb_dev = NULL; } /* Release capture device */ if (ws->default_cap_dev) { - ws->default_cap_dev->Release(); - ws->default_cap_dev = NULL; + ws->default_cap_dev->Release(); + ws->default_cap_dev = NULL; } /* Release playback volume interface */ if (ws->pb_volume) { - ws->pb_volume->Release(); - ws->pb_volume = NULL; + ws->pb_volume->Release(); + ws->pb_volume = NULL; } #if defined(USE_ASYNC_ACTIVATE) /* Release audio activator */ if (ws->cap_aud_act) { - ws->cap_aud_act = nullptr; + ws->cap_aud_act = nullptr; } if (ws->pb_aud_act) { - ws->pb_aud_act = nullptr; + ws->pb_aud_act = nullptr; } if (ws->cap_id) { - ws->cap_id = nullptr; + ws->cap_id = nullptr; } if (ws->pb_id) { - ws->pb_id = nullptr; + ws->pb_id = nullptr; } #else if (ws->cap_id) { - CoTaskMemFree((LPVOID)ws->cap_id); + CoTaskMemFree((LPVOID)ws->cap_id); } if (ws->pb_id) { - CoTaskMemFree((LPVOID)ws->pb_id); + CoTaskMemFree((LPVOID)ws->pb_id); } #endif @@ -1283,7 +1282,7 @@ static pj_status_t wasapi_stream_destroy(pjmedia_aud_stream *strm) #if defined(USE_ASYNC_ACTIVATE) HRESULT AudioActivator::ActivateCompleted( - IActivateAudioInterfaceAsyncOperation *pAsyncOp) + IActivateAudioInterfaceAsyncOperation *pAsyncOp) { HRESULT hr = S_OK, hr2 = S_OK; IUnknown *aud_interface = NULL; @@ -1291,17 +1290,17 @@ HRESULT AudioActivator::ActivateCompleted( hr = pAsyncOp->GetActivateResult(&hr2, &aud_interface); if (SUCCEEDED(hr) && SUCCEEDED(hr2)) { - aud_interface->QueryInterface(IID_PPV_ARGS(&aud_client)); - if (aud_client) - { - pj_thread_desc thread_desc; - pj_thread_t *act_thread; - pj_bzero(thread_desc, sizeof(pj_thread_desc)); - - if (!pj_thread_is_registered()) { - pj_thread_register("activator", thread_desc, &act_thread); - } - } + aud_interface->QueryInterface(IID_PPV_ARGS(&aud_client)); + if (aud_client) + { + pj_thread_desc thread_desc; + pj_thread_t *act_thread; + pj_bzero(thread_desc, sizeof(pj_thread_desc)); + + if (!pj_thread_is_registered()) { + pj_thread_register("activator", thread_desc, &act_thread); + } + } } task_completed.set(aud_client); @@ -1310,4 +1309,4 @@ HRESULT AudioActivator::ActivateCompleted( #endif -#endif /* PJMEDIA_AUDIO_DEV_HAS_WASAPI */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_WASAPI */ diff --git a/pjmedia/src/pjmedia-audiodev/wmme_dev.c b/pjmedia/src/pjmedia-audiodev/wmme_dev.c index 6ca006ab38..69598176ce 100644 --- a/pjmedia/src/pjmedia-audiodev/wmme_dev.c +++ b/pjmedia/src/pjmedia-audiodev/wmme_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -67,26 +66,26 @@ #endif -#define THIS_FILE "wmme_dev.c" +#define THIS_FILE "wmme_dev.c" /* WMME device info */ struct wmme_dev_info { - pjmedia_aud_dev_info info; - unsigned deviceId; - const wchar_t *endpointId; + pjmedia_aud_dev_info info; + unsigned deviceId; + const wchar_t *endpointId; }; /* WMME factory */ struct wmme_factory { - pjmedia_aud_dev_factory base; - pj_pool_t *base_pool; - pj_pool_t *pool; - pj_pool_factory *pf; + pjmedia_aud_dev_factory base; + pj_pool_t *base_pool; + pj_pool_t *pool; + pj_pool_factory *pf; - unsigned dev_count; - struct wmme_dev_info *dev_info; + unsigned dev_count; + struct wmme_dev_info *dev_info; }; @@ -95,8 +94,8 @@ struct wmme_channel { union { - HWAVEIN In; - HWAVEOUT Out; + HWAVEIN In; + HWAVEOUT Out; } hWave; WAVEHDR *WaveHdr; @@ -110,8 +109,8 @@ struct wmme_channel /* Sound stream. */ struct wmme_stream { - pjmedia_aud_stream base; /**< Base stream */ - pjmedia_aud_param param; /**< Settings */ + pjmedia_aud_stream base; /**< Base stream */ + pjmedia_aud_param param; /**< Settings */ pj_pool_t *pool; /**< Memory pool. */ pjmedia_aud_rec_cb rec_cb; /**< Capture callback. */ @@ -121,13 +120,13 @@ struct wmme_stream struct wmme_channel play_strm; /**< Playback stream. */ struct wmme_channel rec_strm; /**< Capture stream. */ - void *buffer; /**< Temp. frame buffer. */ - pjmedia_format_id fmt_id; /**< Frame format */ - pj_uint8_t silence_char; /**< Silence pattern */ - unsigned bytes_per_frame; /**< Bytes per frame */ + void *buffer; /**< Temp. frame buffer. */ + pjmedia_format_id fmt_id; /**< Frame format */ + pj_uint8_t silence_char; /**< Silence pattern */ + unsigned bytes_per_frame; /**< Bytes per frame */ - pjmedia_frame_ext *xfrm; /**< Extended frame buffer */ - unsigned xfrm_size; /**< Total ext frm size */ + pjmedia_frame_ext *xfrm; /**< Extended frame buffer */ + unsigned xfrm_size; /**< Total ext frm size */ pj_thread_t *thread; /**< Thread handle. */ HANDLE thread_quit_event; /**< Quit signal to thread */ @@ -140,26 +139,26 @@ static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f); static pj_status_t factory_refresh(pjmedia_aud_dev_factory *f); static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f); static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); + unsigned index, + pjmedia_aud_dev_info *info); static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); + unsigned index, + pjmedia_aud_param *param); static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); static pj_status_t stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); + pjmedia_aud_param *param); static pj_status_t stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); + pjmedia_aud_dev_cap cap, + void *value); static pj_status_t stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); + pjmedia_aud_dev_cap cap, + const void *value); static pj_status_t stream_start(pjmedia_aud_stream *strm); static pj_status_t stream_stop(pjmedia_aud_stream *strm); static pj_status_t stream_destroy(pjmedia_aud_stream *strm); @@ -221,9 +220,9 @@ pjmedia_aud_dev_factory* pjmedia_wmme_factory(pj_pool_factory *pf) #include DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xBCDE0395, 0xE52F, 0x467C, - 0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E); + 0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E); DEFINE_GUID(IID_IMMDeviceEnumerator, 0xA95664D2, 0x9614, 0x4F35, - 0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6); + 0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6); static void get_dev_names(pjmedia_aud_dev_factory *f) { @@ -237,78 +236,78 @@ static void get_dev_names(pjmedia_aud_dev_factory *f) coinit = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (coinit == RPC_E_CHANGED_MODE) - coinit = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); + coinit = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); if (FAILED(coinit)) - goto on_error; + goto on_error; hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, - CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, - (void**)&pEnumerator); + CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, + (void**)&pEnumerator); if (FAILED(hr)) - goto on_error; + goto on_error; hr = IMMDeviceEnumerator_EnumAudioEndpoints(pEnumerator, eAll, - DEVICE_STATE_ACTIVE, - &pDevices); + DEVICE_STATE_ACTIVE, + &pDevices); if (FAILED(hr)) - goto on_error; + goto on_error; hr = IMMDeviceCollection_GetCount(pDevices, &cDevices); if (FAILED(hr)) - goto on_error; + goto on_error; for (nDevice = 0; nDevice < cDevices; ++nDevice) { - IMMDevice *pDevice = NULL; - IPropertyStore *pProps = NULL; - LPWSTR pwszID = NULL; - PROPVARIANT varName; - unsigned i; - - PropVariantInit(&varName); - - hr = IMMDeviceCollection_Item(pDevices, nDevice, &pDevice); - if (FAILED(hr)) - goto cleanup; - hr = IMMDevice_GetId(pDevice, &pwszID); - if (FAILED(hr)) - goto cleanup; - hr = IMMDevice_OpenPropertyStore(pDevice, STGM_READ, &pProps); - if (FAILED(hr)) - goto cleanup; - hr = IPropertyStore_GetValue(pProps, &PKEY_Device_FriendlyName, - &varName); - if (FAILED(hr)) - goto cleanup; - - for (i = 0; i < wf->dev_count; ++i) { - if (0 == wcscmp(wf->dev_info[i].endpointId, pwszID)) { - pj_unicode_to_ansi(varName.pwszVal, - wcslen(varName.pwszVal), - wf->dev_info[i].info.name, - sizeof(wf->dev_info[i].info.name)); - - break; - } - } - - PropVariantClear(&varName); + IMMDevice *pDevice = NULL; + IPropertyStore *pProps = NULL; + LPWSTR pwszID = NULL; + PROPVARIANT varName; + unsigned i; + + PropVariantInit(&varName); + + hr = IMMDeviceCollection_Item(pDevices, nDevice, &pDevice); + if (FAILED(hr)) + goto cleanup; + hr = IMMDevice_GetId(pDevice, &pwszID); + if (FAILED(hr)) + goto cleanup; + hr = IMMDevice_OpenPropertyStore(pDevice, STGM_READ, &pProps); + if (FAILED(hr)) + goto cleanup; + hr = IPropertyStore_GetValue(pProps, &PKEY_Device_FriendlyName, + &varName); + if (FAILED(hr)) + goto cleanup; + + for (i = 0; i < wf->dev_count; ++i) { + if (0 == wcscmp(wf->dev_info[i].endpointId, pwszID)) { + pj_unicode_to_ansi(varName.pwszVal, + wcslen(varName.pwszVal), + wf->dev_info[i].info.name, + sizeof(wf->dev_info[i].info.name)); + + break; + } + } + + PropVariantClear(&varName); cleanup: - if (pProps) - IPropertyStore_Release(pProps); - if (pwszID) - CoTaskMemFree(pwszID); - if (pDevice) - hr = IMMDevice_Release(pDevice); + if (pProps) + IPropertyStore_Release(pProps); + if (pwszID) + CoTaskMemFree(pwszID); + if (pDevice) + hr = IMMDevice_Release(pDevice); } on_error: if (pDevices) - hr = IMMDeviceCollection_Release(pDevices); + hr = IMMDeviceCollection_Release(pDevices); if (pEnumerator) - hr = IMMDeviceEnumerator_Release(pEnumerator); + hr = IMMDeviceEnumerator_Release(pEnumerator); if (SUCCEEDED(coinit)) - CoUninitialize(); + CoUninitialize(); } #else @@ -322,69 +321,69 @@ static void get_dev_names(pjmedia_aud_dev_factory *f) /* Internal: build device info from WAVEINCAPS/WAVEOUTCAPS */ static void build_dev_info(UINT deviceId, struct wmme_dev_info *wdi, - const WAVEINCAPS *wic, const WAVEOUTCAPS *woc) + const WAVEINCAPS *wic, const WAVEOUTCAPS *woc) { -#define WIC_WOC(wic,woc,field) (wic? wic->field : woc->field) +#define WIC_WOC(wic,woc,field) (wic? wic->field : woc->field) pj_bzero(wdi, sizeof(*wdi)); wdi->deviceId = deviceId; /* Device Name */ if (deviceId==WAVE_MAPPER) { - strncpy(wdi->info.name, "Wave mapper", sizeof(wdi->info.name)); - wdi->info.name[sizeof(wdi->info.name)-1] = '\0'; + strncpy(wdi->info.name, "Wave mapper", sizeof(wdi->info.name)); + wdi->info.name[sizeof(wdi->info.name)-1] = '\0'; } else { - const pj_char_t *szPname = WIC_WOC(wic, woc, szPname); - PJ_DECL_ANSI_TEMP_BUF(wTmp, sizeof(wdi->info.name)); - - strncpy(wdi->info.name, - PJ_NATIVE_TO_STRING(szPname, wTmp, PJ_ARRAY_SIZE(wTmp)), - sizeof(wdi->info.name)); - wdi->info.name[sizeof(wdi->info.name)-1] = '\0'; + const pj_char_t *szPname = WIC_WOC(wic, woc, szPname); + PJ_DECL_ANSI_TEMP_BUF(wTmp, sizeof(wdi->info.name)); + + strncpy(wdi->info.name, + PJ_NATIVE_TO_STRING(szPname, wTmp, PJ_ARRAY_SIZE(wTmp)), + sizeof(wdi->info.name)); + wdi->info.name[sizeof(wdi->info.name)-1] = '\0'; } wdi->info.default_samples_per_sec = 16000; strcpy(wdi->info.driver, "WMME"); if (wic) { - wdi->info.input_count = wic->wChannels; - wdi->info.caps |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; - - /* Sometimes a device can return a rediculously large number of - * channels. This happened with an SBLive card on a Windows ME box. - * It also happens on Win XP! - */ - if (wdi->info.input_count<1 || wdi->info.input_count>256) { - wdi->info.input_count = 2; - } + wdi->info.input_count = wic->wChannels; + wdi->info.caps |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; + + /* Sometimes a device can return a rediculously large number of + * channels. This happened with an SBLive card on a Windows ME box. + * It also happens on Win XP! + */ + if (wdi->info.input_count<1 || wdi->info.input_count>256) { + wdi->info.input_count = 2; + } } if (woc) { - wdi->info.output_count = woc->wChannels; - wdi->info.caps |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; - - if (woc->dwSupport & WAVECAPS_VOLUME) { - wdi->info.caps |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; - } - - /* Sometimes a device can return a rediculously large number of - * channels. This happened with an SBLive card on a Windows ME box. - * It also happens on Win XP! - */ - if (wdi->info.output_count<1 || wdi->info.output_count>256) { - wdi->info.output_count = 2; - } + wdi->info.output_count = woc->wChannels; + wdi->info.caps |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; + + if (woc->dwSupport & WAVECAPS_VOLUME) { + wdi->info.caps |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; + } + + /* Sometimes a device can return a rediculously large number of + * channels. This happened with an SBLive card on a Windows ME box. + * It also happens on Win XP! + */ + if (wdi->info.output_count<1 || wdi->info.output_count>256) { + wdi->info.output_count = 2; + } } /* Extended formats */ wdi->info.caps |= PJMEDIA_AUD_DEV_CAP_EXT_FORMAT; wdi->info.ext_fmt_cnt = 2; pjmedia_format_init_audio(&wdi->info.ext_fmt[0], - PJMEDIA_FORMAT_PCMU, 8000, 1, 8, - 20000, 64000, 64000); + PJMEDIA_FORMAT_PCMU, 8000, 1, 8, + 20000, 64000, 64000); pjmedia_format_init_audio(&wdi->info.ext_fmt[0], - PJMEDIA_FORMAT_PCMA, 8000, 1, 8, - 20000, 64000, 64000); + PJMEDIA_FORMAT_PCMA, 8000, 1, 8, + 20000, 64000, 64000); } /* API: init factory */ @@ -392,7 +391,7 @@ static pj_status_t factory_init(pjmedia_aud_dev_factory *f) { pj_status_t ret = factory_refresh(f); if (ret != PJ_SUCCESS) - return ret; + return ret; PJ_LOG(4, (THIS_FILE, "WMME initialized")); return PJ_SUCCESS; @@ -408,8 +407,8 @@ static pj_status_t factory_refresh(pjmedia_aud_dev_factory *f) pj_bool_t waveMapperAdded = PJ_FALSE; if (wf->pool != NULL) { - pj_pool_release(wf->pool); - wf->pool = NULL; + pj_pool_release(wf->pool); + wf->pool = NULL; } /* Enumerate sound devices */ @@ -423,152 +422,152 @@ static pj_status_t factory_refresh(pjmedia_aud_dev_factory *f) devCount += outputDeviceCount; if (devCount) { - /* Assume there is WAVE_MAPPER */ - devCount += 2; + /* Assume there is WAVE_MAPPER */ + devCount += 2; } if (devCount==0) { - PJ_LOG(4,(THIS_FILE, "WMME found no sound devices")); - /* Enabling this will cause pjsua-lib initialization to fail when there - * is no sound device installed in the system, even when pjsua has been - * run with --null-audio. Moreover, it might be better to think that - * the WMME backend initialization is successfull, regardless there is - * no audio device installed, as later application can check it using - * get_dev_count(). - return PJMEDIA_EAUD_NODEV; - */ - return PJ_SUCCESS; + PJ_LOG(4,(THIS_FILE, "WMME found no sound devices")); + /* Enabling this will cause pjsua-lib initialization to fail when there + * is no sound device installed in the system, even when pjsua has been + * run with --null-audio. Moreover, it might be better to think that + * the WMME backend initialization is successfull, regardless there is + * no audio device installed, as later application can check it using + * get_dev_count(). + return PJMEDIA_EAUD_NODEV; + */ + return PJ_SUCCESS; } wf->dev_info = (struct wmme_dev_info*) - pj_pool_calloc(wf->pool, devCount, - sizeof(struct wmme_dev_info)); + pj_pool_calloc(wf->pool, devCount, + sizeof(struct wmme_dev_info)); if (inputDeviceCount && outputDeviceCount) { - /* Attempt to add WAVE_MAPPER as input and output device */ - WAVEINCAPS wic; - MMRESULT mr; - - pj_bzero(&wic, sizeof(WAVEINCAPS)); - mr = waveInGetDevCaps(WAVE_MAPPER, &wic, sizeof(WAVEINCAPS)); - - if (mr == MMSYSERR_NOERROR) { - WAVEOUTCAPS woc; - - pj_bzero(&woc, sizeof(WAVEOUTCAPS)); - mr = waveOutGetDevCaps(WAVE_MAPPER, &woc, sizeof(WAVEOUTCAPS)); - if (mr == MMSYSERR_NOERROR) { - build_dev_info(WAVE_MAPPER, &wf->dev_info[wf->dev_count], - &wic, &woc); - wf->dev_info[wf->dev_count].endpointId = L""; - ++wf->dev_count; - waveMapperAdded = PJ_TRUE; - } - } + /* Attempt to add WAVE_MAPPER as input and output device */ + WAVEINCAPS wic; + MMRESULT mr; + + pj_bzero(&wic, sizeof(WAVEINCAPS)); + mr = waveInGetDevCaps(WAVE_MAPPER, &wic, sizeof(WAVEINCAPS)); + + if (mr == MMSYSERR_NOERROR) { + WAVEOUTCAPS woc; + + pj_bzero(&woc, sizeof(WAVEOUTCAPS)); + mr = waveOutGetDevCaps(WAVE_MAPPER, &woc, sizeof(WAVEOUTCAPS)); + if (mr == MMSYSERR_NOERROR) { + build_dev_info(WAVE_MAPPER, &wf->dev_info[wf->dev_count], + &wic, &woc); + wf->dev_info[wf->dev_count].endpointId = L""; + ++wf->dev_count; + waveMapperAdded = PJ_TRUE; + } + } } if (inputDeviceCount > 0) { - /* -1 is the WAVE_MAPPER */ - for (i = (waveMapperAdded? 0 : -1); i < inputDeviceCount; ++i) { - UINT uDeviceID = (UINT)((i==-1) ? WAVE_MAPPER : i); - WAVEINCAPS wic; - MMRESULT mr; - DWORD cbEndpointId; + /* -1 is the WAVE_MAPPER */ + for (i = (waveMapperAdded? 0 : -1); i < inputDeviceCount; ++i) { + UINT uDeviceID = (UINT)((i==-1) ? WAVE_MAPPER : i); + WAVEINCAPS wic; + MMRESULT mr; + DWORD cbEndpointId; - pj_bzero(&wic, sizeof(WAVEINCAPS)); + pj_bzero(&wic, sizeof(WAVEINCAPS)); - mr = waveInGetDevCaps(uDeviceID, &wic, sizeof(WAVEINCAPS)); + mr = waveInGetDevCaps(uDeviceID, &wic, sizeof(WAVEINCAPS)); - if (mr == MMSYSERR_NOMEM) - return PJ_ENOMEM; + if (mr == MMSYSERR_NOMEM) + return PJ_ENOMEM; - if (mr != MMSYSERR_NOERROR) - continue; + if (mr != MMSYSERR_NOERROR) + continue; - build_dev_info(uDeviceID, &wf->dev_info[wf->dev_count], - &wic, NULL); + build_dev_info(uDeviceID, &wf->dev_info[wf->dev_count], + &wic, NULL); #if PJMEDIA_WMME_DEV_USE_MMDEVICE_API != 0 - /* Try to get the endpoint id of the audio device */ - wf->dev_info[wf->dev_count].endpointId = L""; - - mr = waveInMessage((HWAVEIN)IntToPtr(uDeviceID), - DRV_QUERYFUNCTIONINSTANCEIDSIZE, - (DWORD_PTR)&cbEndpointId, (DWORD_PTR)NULL); - if (mr == MMSYSERR_NOERROR) { - const wchar_t **epid = &wf->dev_info[wf->dev_count].endpointId; - *epid = (const wchar_t*) pj_pool_calloc(wf->pool, - cbEndpointId, 1); - mr = waveInMessage((HWAVEIN)IntToPtr(uDeviceID), - DRV_QUERYFUNCTIONINSTANCEID, - (DWORD_PTR)*epid, - cbEndpointId); - } + /* Try to get the endpoint id of the audio device */ + wf->dev_info[wf->dev_count].endpointId = L""; + + mr = waveInMessage((HWAVEIN)IntToPtr(uDeviceID), + DRV_QUERYFUNCTIONINSTANCEIDSIZE, + (DWORD_PTR)&cbEndpointId, (DWORD_PTR)NULL); + if (mr == MMSYSERR_NOERROR) { + const wchar_t **epid = &wf->dev_info[wf->dev_count].endpointId; + *epid = (const wchar_t*) pj_pool_calloc(wf->pool, + cbEndpointId, 1); + mr = waveInMessage((HWAVEIN)IntToPtr(uDeviceID), + DRV_QUERYFUNCTIONINSTANCEID, + (DWORD_PTR)*epid, + cbEndpointId); + } #else - PJ_UNUSED_ARG(cbEndpointId); + PJ_UNUSED_ARG(cbEndpointId); #endif - ++wf->dev_count; - } + ++wf->dev_count; + } } if( outputDeviceCount > 0 ) { - /* -1 is the WAVE_MAPPER */ - for (i = (waveMapperAdded? 0 : -1); i < outputDeviceCount; ++i) { - UINT uDeviceID = (UINT)((i==-1) ? WAVE_MAPPER : i); - WAVEOUTCAPS woc; - MMRESULT mr; - DWORD cbEndpointId; + /* -1 is the WAVE_MAPPER */ + for (i = (waveMapperAdded? 0 : -1); i < outputDeviceCount; ++i) { + UINT uDeviceID = (UINT)((i==-1) ? WAVE_MAPPER : i); + WAVEOUTCAPS woc; + MMRESULT mr; + DWORD cbEndpointId; - pj_bzero(&woc, sizeof(WAVEOUTCAPS)); + pj_bzero(&woc, sizeof(WAVEOUTCAPS)); - mr = waveOutGetDevCaps(uDeviceID, &woc, sizeof(WAVEOUTCAPS)); + mr = waveOutGetDevCaps(uDeviceID, &woc, sizeof(WAVEOUTCAPS)); - if (mr == MMSYSERR_NOMEM) - return PJ_ENOMEM; + if (mr == MMSYSERR_NOMEM) + return PJ_ENOMEM; - if (mr != MMSYSERR_NOERROR) - continue; + if (mr != MMSYSERR_NOERROR) + continue; - build_dev_info(uDeviceID, &wf->dev_info[wf->dev_count], - NULL, &woc); + build_dev_info(uDeviceID, &wf->dev_info[wf->dev_count], + NULL, &woc); #if PJMEDIA_WMME_DEV_USE_MMDEVICE_API != 0 - /* Try to get the endpoint id of the audio device */ - wf->dev_info[wf->dev_count].endpointId = L""; - - mr = waveOutMessage((HWAVEOUT)IntToPtr(uDeviceID), - DRV_QUERYFUNCTIONINSTANCEIDSIZE, - (DWORD_PTR)&cbEndpointId, (DWORD_PTR)NULL); - if (mr == MMSYSERR_NOERROR) { - const wchar_t **epid = &wf->dev_info[wf->dev_count].endpointId; - *epid = (const wchar_t*)pj_pool_calloc(wf->pool, - cbEndpointId, 1); - mr = waveOutMessage((HWAVEOUT)IntToPtr(uDeviceID), - DRV_QUERYFUNCTIONINSTANCEID, - (DWORD_PTR)*epid, cbEndpointId); - } + /* Try to get the endpoint id of the audio device */ + wf->dev_info[wf->dev_count].endpointId = L""; + + mr = waveOutMessage((HWAVEOUT)IntToPtr(uDeviceID), + DRV_QUERYFUNCTIONINSTANCEIDSIZE, + (DWORD_PTR)&cbEndpointId, (DWORD_PTR)NULL); + if (mr == MMSYSERR_NOERROR) { + const wchar_t **epid = &wf->dev_info[wf->dev_count].endpointId; + *epid = (const wchar_t*)pj_pool_calloc(wf->pool, + cbEndpointId, 1); + mr = waveOutMessage((HWAVEOUT)IntToPtr(uDeviceID), + DRV_QUERYFUNCTIONINSTANCEID, + (DWORD_PTR)*epid, cbEndpointId); + } #else - PJ_UNUSED_ARG(cbEndpointId); + PJ_UNUSED_ARG(cbEndpointId); #endif - ++wf->dev_count; - } + ++wf->dev_count; + } } /* On Windows Vista and Windows 7 get the full device names */ get_dev_names(f); PJ_LOG(4, (THIS_FILE, "WMME found %d devices:", - wf->dev_count)); + wf->dev_count)); for (c = 0; c < wf->dev_count; ++c) { - PJ_LOG(4, (THIS_FILE, " dev_id %d: %s (in=%d, out=%d)", - c, - wf->dev_info[c].info.name, - wf->dev_info[c].info.input_count, - wf->dev_info[c].info.output_count)); + PJ_LOG(4, (THIS_FILE, " dev_id %d: %s (in=%d, out=%d)", + c, + wf->dev_info[c].info.name, + wf->dev_info[c].info.input_count, + wf->dev_info[c].info.output_count)); } return PJ_SUCCESS; @@ -596,8 +595,8 @@ static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f) /* API: get device info */ static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info) + unsigned index, + pjmedia_aud_dev_info *info) { struct wmme_factory *wf = (struct wmme_factory*)f; @@ -610,8 +609,8 @@ static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, /* API: create default device parameter */ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param) + unsigned index, + pjmedia_aud_param *param) { struct wmme_factory *wf = (struct wmme_factory*)f; struct wmme_dev_info *di = &wf->dev_info[index]; @@ -620,19 +619,19 @@ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, pj_bzero(param, sizeof(*param)); if (di->info.input_count && di->info.output_count) { - param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; - param->rec_id = index; - param->play_id = index; + param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; + param->rec_id = index; + param->play_id = index; } else if (di->info.input_count) { - param->dir = PJMEDIA_DIR_CAPTURE; - param->rec_id = index; - param->play_id = PJMEDIA_AUD_INVALID_DEV; + param->dir = PJMEDIA_DIR_CAPTURE; + param->rec_id = index; + param->play_id = PJMEDIA_AUD_INVALID_DEV; } else if (di->info.output_count) { - param->dir = PJMEDIA_DIR_PLAYBACK; - param->play_id = index; - param->rec_id = PJMEDIA_AUD_INVALID_DEV; + param->dir = PJMEDIA_DIR_PLAYBACK; + param->play_id = index; + param->rec_id = PJMEDIA_AUD_INVALID_DEV; } else { - return PJMEDIA_EAUD_INVDEV; + return PJMEDIA_EAUD_INVDEV; } param->clock_rate = di->info.default_samples_per_sec; @@ -640,7 +639,7 @@ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, param->samples_per_frame = di->info.default_samples_per_sec * 20 / 1000; param->bits_per_sample = 16; param->flags = PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; + PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; param->input_latency_ms = PJMEDIA_SND_DEFAULT_REC_LATENCY; param->output_latency_ms = PJMEDIA_SND_DEFAULT_PLAY_LATENCY; @@ -649,47 +648,47 @@ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, /* Internal: init WAVEFORMATEX */ static pj_status_t init_waveformatex(LPWAVEFORMATEX wfx, - const pjmedia_aud_param *prm) + const pjmedia_aud_param *prm) { pj_bzero(wfx, sizeof(WAVEFORMATEX)); if (prm->ext_fmt.id == PJMEDIA_FORMAT_L16) { - enum { BYTES_PER_SAMPLE = 2 }; - wfx->wFormatTag = WAVE_FORMAT_PCM; - wfx->nChannels = (pj_uint16_t)prm->channel_count; - wfx->nSamplesPerSec = prm->clock_rate; - wfx->nBlockAlign = (pj_uint16_t)(prm->channel_count * - BYTES_PER_SAMPLE); - wfx->nAvgBytesPerSec = prm->clock_rate * prm->channel_count * - BYTES_PER_SAMPLE; - wfx->wBitsPerSample = 16; - - return PJ_SUCCESS; + enum { BYTES_PER_SAMPLE = 2 }; + wfx->wFormatTag = WAVE_FORMAT_PCM; + wfx->nChannels = (pj_uint16_t)prm->channel_count; + wfx->nSamplesPerSec = prm->clock_rate; + wfx->nBlockAlign = (pj_uint16_t)(prm->channel_count * + BYTES_PER_SAMPLE); + wfx->nAvgBytesPerSec = prm->clock_rate * prm->channel_count * + BYTES_PER_SAMPLE; + wfx->wBitsPerSample = 16; + + return PJ_SUCCESS; } else if ((prm->flags & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT) && - (prm->ext_fmt.id == PJMEDIA_FORMAT_PCMA || - prm->ext_fmt.id == PJMEDIA_FORMAT_PCMU)) + (prm->ext_fmt.id == PJMEDIA_FORMAT_PCMA || + prm->ext_fmt.id == PJMEDIA_FORMAT_PCMU)) { - unsigned ptime; - - ptime = prm->samples_per_frame * 1000 / - (prm->clock_rate * prm->channel_count); - wfx->wFormatTag = (pj_uint16_t) - ((prm->ext_fmt.id==PJMEDIA_FORMAT_PCMA) ? - WAVE_FORMAT_ALAW : WAVE_FORMAT_MULAW); - wfx->nChannels = (pj_uint16_t)prm->channel_count; - wfx->nSamplesPerSec = prm->clock_rate; - wfx->nAvgBytesPerSec = prm->clock_rate * prm->channel_count; - wfx->nBlockAlign = (pj_uint16_t)(wfx->nAvgBytesPerSec * ptime / - 1000); - wfx->wBitsPerSample = 8; - wfx->cbSize = 0; - - return PJ_SUCCESS; + unsigned ptime; + + ptime = prm->samples_per_frame * 1000 / + (prm->clock_rate * prm->channel_count); + wfx->wFormatTag = (pj_uint16_t) + ((prm->ext_fmt.id==PJMEDIA_FORMAT_PCMA) ? + WAVE_FORMAT_ALAW : WAVE_FORMAT_MULAW); + wfx->nChannels = (pj_uint16_t)prm->channel_count; + wfx->nSamplesPerSec = prm->clock_rate; + wfx->nAvgBytesPerSec = prm->clock_rate * prm->channel_count; + wfx->nBlockAlign = (pj_uint16_t)(wfx->nAvgBytesPerSec * ptime / + 1000); + wfx->wBitsPerSample = 8; + wfx->cbSize = 0; + + return PJ_SUCCESS; } else { - return PJMEDIA_EAUD_BADFORMAT; + return PJMEDIA_EAUD_BADFORMAT; } } @@ -700,7 +699,7 @@ static const char *get_fmt_name(pj_uint32_t id) static char name[8]; if (id == PJMEDIA_FORMAT_L16) - return "PCM"; + return "PCM"; pj_memcpy(name, &id, 4); name[4] = '\0'; return name; @@ -708,11 +707,11 @@ static const char *get_fmt_name(pj_uint32_t id) /* Internal: create WMME player device. */ static pj_status_t init_player_stream( struct wmme_factory *wf, - pj_pool_t *pool, - struct wmme_stream *parent, - struct wmme_channel *wmme_strm, - const pjmedia_aud_param *prm, - unsigned buffer_count) + pj_pool_t *pool, + struct wmme_stream *parent, + struct wmme_channel *wmme_strm, + const pjmedia_aud_param *prm, + unsigned buffer_count) { MMRESULT mr; WAVEFORMATEX wfx; @@ -727,59 +726,59 @@ static pj_status_t init_player_stream( struct wmme_factory *wf, */ wmme_strm->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (NULL == wmme_strm->hEvent) - return pj_get_os_error(); + return pj_get_os_error(); /* * Set up wave format structure for opening the device. */ status = init_waveformatex(&wfx, prm); if (status != PJ_SUCCESS) - return status; + return status; ptime = prm->samples_per_frame * 1000 / - (prm->clock_rate * prm->channel_count); + (prm->clock_rate * prm->channel_count); parent->bytes_per_frame = wfx.nAvgBytesPerSec * ptime / 1000; flag = CALLBACK_EVENT; if (prm->ext_fmt.id == PJMEDIA_FORMAT_L16) - flag |= WAVE_FORMAT_DIRECT; + flag |= WAVE_FORMAT_DIRECT; /* * Open wave device. */ mr = waveOutOpen(&wmme_strm->hWave.Out, - wf->dev_info[prm->play_id].deviceId, - &wfx, (DWORD_PTR)wmme_strm->hEvent, 0, flag); + wf->dev_info[prm->play_id].deviceId, + &wfx, (DWORD_PTR)wmme_strm->hEvent, 0, flag); if (mr != MMSYSERR_NOERROR) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); + return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); } /* Pause the wave out device */ mr = waveOutPause(wmme_strm->hWave.Out); if (mr != MMSYSERR_NOERROR) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); + return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); } /* * Create the buffers. */ wmme_strm->WaveHdr = (WAVEHDR*) - pj_pool_zalloc(pool, sizeof(WAVEHDR) * buffer_count); + pj_pool_zalloc(pool, sizeof(WAVEHDR) * buffer_count); for (i = 0; i < buffer_count; ++i) { - wmme_strm->WaveHdr[i].lpData = pj_pool_zalloc(pool, - parent->bytes_per_frame); - wmme_strm->WaveHdr[i].dwBufferLength = parent->bytes_per_frame; - mr = waveOutPrepareHeader(wmme_strm->hWave.Out, - &(wmme_strm->WaveHdr[i]), - sizeof(WAVEHDR)); - if (mr != MMSYSERR_NOERROR) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); - } - mr = waveOutWrite(wmme_strm->hWave.Out, &(wmme_strm->WaveHdr[i]), - sizeof(WAVEHDR)); - if (mr != MMSYSERR_NOERROR) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); - } + wmme_strm->WaveHdr[i].lpData = pj_pool_zalloc(pool, + parent->bytes_per_frame); + wmme_strm->WaveHdr[i].dwBufferLength = parent->bytes_per_frame; + mr = waveOutPrepareHeader(wmme_strm->hWave.Out, + &(wmme_strm->WaveHdr[i]), + sizeof(WAVEHDR)); + if (mr != MMSYSERR_NOERROR) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); + } + mr = waveOutWrite(wmme_strm->hWave.Out, &(wmme_strm->WaveHdr[i]), + sizeof(WAVEHDR)); + if (mr != MMSYSERR_NOERROR) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); + } } wmme_strm->dwBufIdx = 0; @@ -788,13 +787,13 @@ static pj_status_t init_player_stream( struct wmme_factory *wf, /* Done setting up play device. */ PJ_LOG(4, (THIS_FILE, - " WaveAPI Sound player \"%s\" initialized (" - "format=%s, clock_rate=%d, " - "channel_count=%d, samples_per_frame=%d (%dms))", - wf->dev_info[prm->play_id].info.name, - get_fmt_name(prm->ext_fmt.id), - prm->clock_rate, prm->channel_count, prm->samples_per_frame, - prm->samples_per_frame * 1000 / prm->clock_rate)); + " WaveAPI Sound player \"%s\" initialized (" + "format=%s, clock_rate=%d, " + "channel_count=%d, samples_per_frame=%d (%dms))", + wf->dev_info[prm->play_id].info.name, + get_fmt_name(prm->ext_fmt.id), + prm->clock_rate, prm->channel_count, prm->samples_per_frame, + prm->samples_per_frame * 1000 / prm->clock_rate)); return PJ_SUCCESS; } @@ -802,11 +801,11 @@ static pj_status_t init_player_stream( struct wmme_factory *wf, /* Internal: create Windows Multimedia recorder device */ static pj_status_t init_capture_stream( struct wmme_factory *wf, - pj_pool_t *pool, - struct wmme_stream *parent, - struct wmme_channel *wmme_strm, - const pjmedia_aud_param *prm, - unsigned buffer_count) + pj_pool_t *pool, + struct wmme_stream *parent, + struct wmme_channel *wmme_strm, + const pjmedia_aud_param *prm, + unsigned buffer_count) { MMRESULT mr; WAVEFORMATEX wfx; @@ -820,7 +819,7 @@ static pj_status_t init_capture_stream( struct wmme_factory *wf, */ wmme_strm->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (NULL == wmme_strm->hEvent) { - return pj_get_os_error(); + return pj_get_os_error(); } /* @@ -828,43 +827,43 @@ static pj_status_t init_capture_stream( struct wmme_factory *wf, */ init_waveformatex(&wfx, prm); ptime = prm->samples_per_frame * 1000 / - (prm->clock_rate * prm->channel_count); + (prm->clock_rate * prm->channel_count); parent->bytes_per_frame = wfx.nAvgBytesPerSec * ptime / 1000; flag = CALLBACK_EVENT; if (prm->ext_fmt.id == PJMEDIA_FORMAT_L16) - flag |= WAVE_FORMAT_DIRECT; + flag |= WAVE_FORMAT_DIRECT; /* * Open wave device. */ mr = waveInOpen(&wmme_strm->hWave.In, - wf->dev_info[prm->rec_id].deviceId, - &wfx, (DWORD_PTR)wmme_strm->hEvent, 0, flag); + wf->dev_info[prm->rec_id].deviceId, + &wfx, (DWORD_PTR)wmme_strm->hEvent, 0, flag); if (mr != MMSYSERR_NOERROR) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(mr); + return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(mr); } /* * Create the buffers. */ wmme_strm->WaveHdr = (WAVEHDR*) - pj_pool_zalloc(pool, sizeof(WAVEHDR) * buffer_count); + pj_pool_zalloc(pool, sizeof(WAVEHDR) * buffer_count); for (i = 0; i < buffer_count; ++i) { - wmme_strm->WaveHdr[i].lpData = pj_pool_zalloc(pool, - parent->bytes_per_frame); - wmme_strm->WaveHdr[i].dwBufferLength = parent->bytes_per_frame; - mr = waveInPrepareHeader(wmme_strm->hWave.In, - &(wmme_strm->WaveHdr[i]), - sizeof(WAVEHDR)); - if (mr != MMSYSERR_NOERROR) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(mr); - } - mr = waveInAddBuffer(wmme_strm->hWave.In, &(wmme_strm->WaveHdr[i]), - sizeof(WAVEHDR)); - if (mr != MMSYSERR_NOERROR) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(mr); - } + wmme_strm->WaveHdr[i].lpData = pj_pool_zalloc(pool, + parent->bytes_per_frame); + wmme_strm->WaveHdr[i].dwBufferLength = parent->bytes_per_frame; + mr = waveInPrepareHeader(wmme_strm->hWave.In, + &(wmme_strm->WaveHdr[i]), + sizeof(WAVEHDR)); + if (mr != MMSYSERR_NOERROR) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(mr); + } + mr = waveInAddBuffer(wmme_strm->hWave.In, &(wmme_strm->WaveHdr[i]), + sizeof(WAVEHDR)); + if (mr != MMSYSERR_NOERROR) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(mr); + } } wmme_strm->dwBufIdx = 0; @@ -873,13 +872,13 @@ static pj_status_t init_capture_stream( struct wmme_factory *wf, /* Done setting up play device. */ PJ_LOG(4,(THIS_FILE, - " WaveAPI Sound recorder \"%s\" initialized " - "(format=%s, clock_rate=%d, " - "channel_count=%d, samples_per_frame=%d (%dms))", - wf->dev_info[prm->rec_id].info.name, - get_fmt_name(prm->ext_fmt.id), - prm->clock_rate, prm->channel_count, prm->samples_per_frame, - prm->samples_per_frame * 1000 / prm->clock_rate)); + " WaveAPI Sound recorder \"%s\" initialized " + "(format=%s, clock_rate=%d, " + "channel_count=%d, samples_per_frame=%d (%dms))", + wf->dev_info[prm->rec_id].info.name, + get_fmt_name(prm->ext_fmt.id), + prm->clock_rate, prm->channel_count, prm->samples_per_frame, + prm->samples_per_frame * 1000 / prm->clock_rate)); return PJ_SUCCESS; } @@ -904,9 +903,9 @@ static int PJ_THREAD_FUNC wmme_dev_thread(void *arg) eventCount = 0; events[eventCount++] = strm->thread_quit_event; if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) - events[eventCount++] = strm->play_strm.hEvent; + events[eventCount++] = strm->play_strm.hEvent; if (strm->param.dir & PJMEDIA_DIR_CAPTURE) - events[eventCount++] = strm->rec_strm.hEvent; + events[eventCount++] = strm->rec_strm.hEvent; /* Raise self priority. We don't want the audio to be distorted by @@ -914,9 +913,9 @@ static int PJ_THREAD_FUNC wmme_dev_thread(void *arg) */ #if defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE != 0 if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) - CeSetThreadPriority(GetCurrentThread(), 153); + CeSetThreadPriority(GetCurrentThread(), 153); else - CeSetThreadPriority(GetCurrentThread(), 247); + CeSetThreadPriority(GetCurrentThread(), 247); #else SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); #endif @@ -928,274 +927,274 @@ static int PJ_THREAD_FUNC wmme_dev_thread(void *arg) while (status == PJ_SUCCESS) { - DWORD rc; - - /* Swap hWaveIn and hWaveOut to get equal opportunity for both */ - if (eventCount==3) { - HANDLE hTemp = events[2]; - events[2] = events[1]; - events[1] = hTemp; - } - - rc = WaitForMultipleObjects(eventCount, events, FALSE, INFINITE); - if (rc < WAIT_OBJECT_0 || rc >= WAIT_OBJECT_0 + eventCount) - continue; - - if (rc == WAIT_OBJECT_0) - break; - - if (rc == (WAIT_OBJECT_0 + 1)) - { - if (events[1] == strm->play_strm.hEvent) - signalled_dir = PJMEDIA_DIR_PLAYBACK; - else - signalled_dir = PJMEDIA_DIR_CAPTURE; - } - else - { - if (events[2] == strm->play_strm.hEvent) - signalled_dir = PJMEDIA_DIR_PLAYBACK; - else - signalled_dir = PJMEDIA_DIR_CAPTURE; - } - - - if (signalled_dir == PJMEDIA_DIR_PLAYBACK) - { - struct wmme_channel *wmme_strm = &strm->play_strm; - unsigned burst; - - status = PJ_SUCCESS; - - /* - * Windows Multimedia has requested us to feed some frames to - * playback buffer. - */ - - for (burst=0; burstWaveHdr[wmme_strm->dwBufIdx].dwFlags & WHDR_DONE); - ++burst) - { - void *buffer = wmme_strm->WaveHdr[wmme_strm->dwBufIdx].lpData; - pjmedia_frame pcm_frame, *frame; - MMRESULT mr = MMSYSERR_NOERROR; - - //PJ_LOG(5,(THIS_FILE, "Finished writing buffer %d", - // wmme_strm->dwBufIdx)); - - if (strm->fmt_id == PJMEDIA_FORMAT_L16) { - /* PCM mode */ - frame = &pcm_frame; - - frame->type = PJMEDIA_FRAME_TYPE_AUDIO; - frame->size = strm->bytes_per_frame; - frame->buf = buffer; - frame->timestamp.u64 = wmme_strm->timestamp.u64; - frame->bit_info = 0; - } else { - /* Codec mode */ - frame = &strm->xfrm->base; - - strm->xfrm->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->xfrm->base.size = strm->bytes_per_frame; - strm->xfrm->base.buf = NULL; - strm->xfrm->base.timestamp.u64 = wmme_strm->timestamp.u64; - strm->xfrm->base.bit_info = 0; - } - - /* Get frame from application. */ - //PJ_LOG(5,(THIS_FILE, "xxx %u play_cb", play_cnt++)); - status = (*strm->play_cb)(strm->user_data, frame); - - if (status != PJ_SUCCESS) - break; - - if (strm->fmt_id == PJMEDIA_FORMAT_L16) { - /* PCM mode */ - if (frame->type == PJMEDIA_FRAME_TYPE_NONE) { - pj_bzero(buffer, strm->bytes_per_frame); - } else if (frame->type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pj_assert(!"Frame type not supported"); - } else if (frame->type == PJMEDIA_FRAME_TYPE_AUDIO) { - /* Nothing to do */ - } else { - pj_assert(!"Frame type not supported"); - } - } else { - /* Codec mode */ - if (frame->type == PJMEDIA_FRAME_TYPE_NONE) { - pj_memset(buffer, strm->silence_char, - strm->bytes_per_frame); - } else if (frame->type == PJMEDIA_FRAME_TYPE_EXTENDED) { - unsigned sz; - sz = pjmedia_frame_ext_copy_payload(strm->xfrm, - buffer, - strm->bytes_per_frame); - if (sz < strm->bytes_per_frame) { - pj_memset((char*)buffer+sz, - strm->silence_char, - strm->bytes_per_frame - sz); - } - } else { - pj_assert(!"Frame type not supported"); - } - } - - /* Write to the device. */ - mr = waveOutWrite(wmme_strm->hWave.Out, - &(wmme_strm->WaveHdr[wmme_strm->dwBufIdx]), - sizeof(WAVEHDR)); - if (mr != MMSYSERR_NOERROR) { - status = PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); - PJ_PERROR(3, (THIS_FILE, status, - "Failed to write audio frame for playback")); - break; - } - - /* Increment position. */ - if (++wmme_strm->dwBufIdx >= wmme_strm->dwMaxBufIdx) - wmme_strm->dwBufIdx = 0; - wmme_strm->timestamp.u64 += strm->param.samples_per_frame / - strm->param.channel_count; - } /* for */ - } - else - { - struct wmme_channel *wmme_strm = &strm->rec_strm; - unsigned burst; - MMRESULT mr = MMSYSERR_NOERROR; - status = PJ_SUCCESS; - - /* - * Windows Multimedia has indicated that it has some frames ready - * in the capture buffer. Get as much frames as possible to - * prevent overflows. - */ + DWORD rc; + + /* Swap hWaveIn and hWaveOut to get equal opportunity for both */ + if (eventCount==3) { + HANDLE hTemp = events[2]; + events[2] = events[1]; + events[1] = hTemp; + } + + rc = WaitForMultipleObjects(eventCount, events, FALSE, INFINITE); + if (rc < WAIT_OBJECT_0 || rc >= WAIT_OBJECT_0 + eventCount) + continue; + + if (rc == WAIT_OBJECT_0) + break; + + if (rc == (WAIT_OBJECT_0 + 1)) + { + if (events[1] == strm->play_strm.hEvent) + signalled_dir = PJMEDIA_DIR_PLAYBACK; + else + signalled_dir = PJMEDIA_DIR_CAPTURE; + } + else + { + if (events[2] == strm->play_strm.hEvent) + signalled_dir = PJMEDIA_DIR_PLAYBACK; + else + signalled_dir = PJMEDIA_DIR_CAPTURE; + } + + + if (signalled_dir == PJMEDIA_DIR_PLAYBACK) + { + struct wmme_channel *wmme_strm = &strm->play_strm; + unsigned burst; + + status = PJ_SUCCESS; + + /* + * Windows Multimedia has requested us to feed some frames to + * playback buffer. + */ + + for (burst=0; burstWaveHdr[wmme_strm->dwBufIdx].dwFlags & WHDR_DONE); + ++burst) + { + void *buffer = wmme_strm->WaveHdr[wmme_strm->dwBufIdx].lpData; + pjmedia_frame pcm_frame, *frame; + MMRESULT mr = MMSYSERR_NOERROR; + + //PJ_LOG(5,(THIS_FILE, "Finished writing buffer %d", + // wmme_strm->dwBufIdx)); + + if (strm->fmt_id == PJMEDIA_FORMAT_L16) { + /* PCM mode */ + frame = &pcm_frame; + + frame->type = PJMEDIA_FRAME_TYPE_AUDIO; + frame->size = strm->bytes_per_frame; + frame->buf = buffer; + frame->timestamp.u64 = wmme_strm->timestamp.u64; + frame->bit_info = 0; + } else { + /* Codec mode */ + frame = &strm->xfrm->base; + + strm->xfrm->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->xfrm->base.size = strm->bytes_per_frame; + strm->xfrm->base.buf = NULL; + strm->xfrm->base.timestamp.u64 = wmme_strm->timestamp.u64; + strm->xfrm->base.bit_info = 0; + } + + /* Get frame from application. */ + //PJ_LOG(5,(THIS_FILE, "xxx %u play_cb", play_cnt++)); + status = (*strm->play_cb)(strm->user_data, frame); + + if (status != PJ_SUCCESS) + break; + + if (strm->fmt_id == PJMEDIA_FORMAT_L16) { + /* PCM mode */ + if (frame->type == PJMEDIA_FRAME_TYPE_NONE) { + pj_bzero(buffer, strm->bytes_per_frame); + } else if (frame->type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pj_assert(!"Frame type not supported"); + } else if (frame->type == PJMEDIA_FRAME_TYPE_AUDIO) { + /* Nothing to do */ + } else { + pj_assert(!"Frame type not supported"); + } + } else { + /* Codec mode */ + if (frame->type == PJMEDIA_FRAME_TYPE_NONE) { + pj_memset(buffer, strm->silence_char, + strm->bytes_per_frame); + } else if (frame->type == PJMEDIA_FRAME_TYPE_EXTENDED) { + unsigned sz; + sz = pjmedia_frame_ext_copy_payload(strm->xfrm, + buffer, + strm->bytes_per_frame); + if (sz < strm->bytes_per_frame) { + pj_memset((char*)buffer+sz, + strm->silence_char, + strm->bytes_per_frame - sz); + } + } else { + pj_assert(!"Frame type not supported"); + } + } + + /* Write to the device. */ + mr = waveOutWrite(wmme_strm->hWave.Out, + &(wmme_strm->WaveHdr[wmme_strm->dwBufIdx]), + sizeof(WAVEHDR)); + if (mr != MMSYSERR_NOERROR) { + status = PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); + PJ_PERROR(3, (THIS_FILE, status, + "Failed to write audio frame for playback")); + break; + } + + /* Increment position. */ + if (++wmme_strm->dwBufIdx >= wmme_strm->dwMaxBufIdx) + wmme_strm->dwBufIdx = 0; + wmme_strm->timestamp.u64 += strm->param.samples_per_frame / + strm->param.channel_count; + } /* for */ + } + else + { + struct wmme_channel *wmme_strm = &strm->rec_strm; + unsigned burst; + MMRESULT mr = MMSYSERR_NOERROR; + status = PJ_SUCCESS; + + /* + * Windows Multimedia has indicated that it has some frames ready + * in the capture buffer. Get as much frames as possible to + * prevent overflows. + */ #if 0 - { - static DWORD tc = 0; - DWORD now = GetTickCount(); - DWORD i = 0; - DWORD bits = 0; - - if (tc == 0) tc = now; - - for (i = 0; i < wmme_strm->dwMaxBufIdx; ++i) - { - bits = bits << 4; - bits |= wmme_strm->WaveHdr[i].dwFlags & WHDR_DONE; - } - PJ_LOG(5,(THIS_FILE, "Record Signal> Index: %d, Delta: %4.4d, " - "Flags: %6.6x\n", - wmme_strm->dwBufIdx, - now - tc, - bits)); - tc = now; - } + { + static DWORD tc = 0; + DWORD now = GetTickCount(); + DWORD i = 0; + DWORD bits = 0; + + if (tc == 0) tc = now; + + for (i = 0; i < wmme_strm->dwMaxBufIdx; ++i) + { + bits = bits << 4; + bits |= wmme_strm->WaveHdr[i].dwFlags & WHDR_DONE; + } + PJ_LOG(5,(THIS_FILE, "Record Signal> Index: %d, Delta: %4.4d, " + "Flags: %6.6x\n", + wmme_strm->dwBufIdx, + now - tc, + bits)); + tc = now; + } #endif - for (burst=0; burstWaveHdr[wmme_strm->dwBufIdx].dwFlags & WHDR_DONE); - ++burst) - { - char* buffer = (char*) - wmme_strm->WaveHdr[wmme_strm->dwBufIdx].lpData; - unsigned cap_len = - wmme_strm->WaveHdr[wmme_strm->dwBufIdx].dwBytesRecorded; - pjmedia_frame pcm_frame, *frame; - - /* - PJ_LOG(5,(THIS_FILE, "Read %d bytes from buffer %d", cap_len, - wmme_strm->dwBufIdx)); - */ - - if (strm->fmt_id == PJMEDIA_FORMAT_L16) { - /* PCM mode */ - if (cap_len < strm->bytes_per_frame) - pj_bzero(buffer + cap_len, - strm->bytes_per_frame - cap_len); - - /* Copy the audio data out of the wave buffer. */ - pj_memcpy(strm->buffer, buffer, strm->bytes_per_frame); - - /* Prepare frame */ - frame = &pcm_frame; - frame->type = PJMEDIA_FRAME_TYPE_AUDIO; - frame->buf = strm->buffer; - frame->size = strm->bytes_per_frame; - frame->timestamp.u64 = wmme_strm->timestamp.u64; - frame->bit_info = 0; - - } else { - /* Codec mode */ - frame = &strm->xfrm->base; - - frame->type = PJMEDIA_FRAME_TYPE_EXTENDED; - frame->buf = NULL; - frame->size = strm->bytes_per_frame; - frame->timestamp.u64 = wmme_strm->timestamp.u64; - frame->bit_info = 0; - - strm->xfrm->samples_cnt = 0; - strm->xfrm->subframe_cnt = 0; - pjmedia_frame_ext_append_subframe( - strm->xfrm, buffer, - strm->bytes_per_frame *8, - strm->param.samples_per_frame - ); - } - - /* Re-add the buffer to the device. */ - mr = waveInAddBuffer(wmme_strm->hWave.In, - &(wmme_strm->WaveHdr[wmme_strm->dwBufIdx]), - sizeof(WAVEHDR)); - if (mr != MMSYSERR_NOERROR) { - status = PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(mr); - PJ_PERROR(3, (THIS_FILE, status, - "Failed to add recording buffer")); - break; - } - - - /* Call callback */ - //PJ_LOG(5,(THIS_FILE, "xxx %u rec_cb", rec_cnt++)); - status = (*strm->rec_cb)(strm->user_data, frame); - if (status != PJ_SUCCESS) - break; - - /* Increment position. */ - if (++wmme_strm->dwBufIdx >= wmme_strm->dwMaxBufIdx) - wmme_strm->dwBufIdx = 0; - wmme_strm->timestamp.u64 += strm->param.samples_per_frame / - strm->param.channel_count; - } /* for */ - } + for (burst=0; burstWaveHdr[wmme_strm->dwBufIdx].dwFlags & WHDR_DONE); + ++burst) + { + char* buffer = (char*) + wmme_strm->WaveHdr[wmme_strm->dwBufIdx].lpData; + unsigned cap_len = + wmme_strm->WaveHdr[wmme_strm->dwBufIdx].dwBytesRecorded; + pjmedia_frame pcm_frame, *frame; + + /* + PJ_LOG(5,(THIS_FILE, "Read %d bytes from buffer %d", cap_len, + wmme_strm->dwBufIdx)); + */ + + if (strm->fmt_id == PJMEDIA_FORMAT_L16) { + /* PCM mode */ + if (cap_len < strm->bytes_per_frame) + pj_bzero(buffer + cap_len, + strm->bytes_per_frame - cap_len); + + /* Copy the audio data out of the wave buffer. */ + pj_memcpy(strm->buffer, buffer, strm->bytes_per_frame); + + /* Prepare frame */ + frame = &pcm_frame; + frame->type = PJMEDIA_FRAME_TYPE_AUDIO; + frame->buf = strm->buffer; + frame->size = strm->bytes_per_frame; + frame->timestamp.u64 = wmme_strm->timestamp.u64; + frame->bit_info = 0; + + } else { + /* Codec mode */ + frame = &strm->xfrm->base; + + frame->type = PJMEDIA_FRAME_TYPE_EXTENDED; + frame->buf = NULL; + frame->size = strm->bytes_per_frame; + frame->timestamp.u64 = wmme_strm->timestamp.u64; + frame->bit_info = 0; + + strm->xfrm->samples_cnt = 0; + strm->xfrm->subframe_cnt = 0; + pjmedia_frame_ext_append_subframe( + strm->xfrm, buffer, + strm->bytes_per_frame *8, + strm->param.samples_per_frame + ); + } + + /* Re-add the buffer to the device. */ + mr = waveInAddBuffer(wmme_strm->hWave.In, + &(wmme_strm->WaveHdr[wmme_strm->dwBufIdx]), + sizeof(WAVEHDR)); + if (mr != MMSYSERR_NOERROR) { + status = PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(mr); + PJ_PERROR(3, (THIS_FILE, status, + "Failed to add recording buffer")); + break; + } + + + /* Call callback */ + //PJ_LOG(5,(THIS_FILE, "xxx %u rec_cb", rec_cnt++)); + status = (*strm->rec_cb)(strm->user_data, frame); + if (status != PJ_SUCCESS) + break; + + /* Increment position. */ + if (++wmme_strm->dwBufIdx >= wmme_strm->dwMaxBufIdx) + wmme_strm->dwBufIdx = 0; + wmme_strm->timestamp.u64 += strm->param.samples_per_frame / + strm->param.channel_count; + } /* for */ + } } PJ_LOG(5,(THIS_FILE, "WMME: thread stopping..")); if (status != PJ_SUCCESS) { - pjmedia_event e; - pj_timestamp *ts; - pjmedia_aud_param param; - - PJ_PERROR(3, (THIS_FILE, status, "WMME thread stopped due to error")); - - /* Broadcast WMME error */ - pj_assert(signalled_dir != PJMEDIA_DIR_NONE); - ts = (signalled_dir==PJMEDIA_DIR_PLAYBACK)? - &strm->play_strm.timestamp : &strm->rec_strm.timestamp; - pjmedia_event_init(&e, PJMEDIA_EVENT_AUD_DEV_ERROR, ts, &strm->base); - e.data.aud_dev_err.dir = signalled_dir; - e.data.aud_dev_err.status = status; - e.data.aud_dev_err.id = PJMEDIA_AUD_INVALID_DEV; - if (pjmedia_aud_stream_get_param(&strm->base, ¶m) == PJ_SUCCESS) { - e.data.aud_dev_err.id = (signalled_dir==PJMEDIA_DIR_PLAYBACK)? - param.play_id : param.rec_id; - } - - pjmedia_event_publish(NULL, &strm->base, &e, - PJMEDIA_EVENT_PUBLISH_DEFAULT); + pjmedia_event e; + pj_timestamp *ts; + pjmedia_aud_param param; + + PJ_PERROR(3, (THIS_FILE, status, "WMME thread stopped due to error")); + + /* Broadcast WMME error */ + pj_assert(signalled_dir != PJMEDIA_DIR_NONE); + ts = (signalled_dir==PJMEDIA_DIR_PLAYBACK)? + &strm->play_strm.timestamp : &strm->rec_strm.timestamp; + pjmedia_event_init(&e, PJMEDIA_EVENT_AUD_DEV_ERROR, ts, &strm->base); + e.data.aud_dev_err.dir = signalled_dir; + e.data.aud_dev_err.status = status; + e.data.aud_dev_err.id = PJMEDIA_AUD_INVALID_DEV; + if (pjmedia_aud_stream_get_param(&strm->base, ¶m) == PJ_SUCCESS) { + e.data.aud_dev_err.id = (signalled_dir==PJMEDIA_DIR_PLAYBACK)? + param.play_id : param.rec_id; + } + + pjmedia_event_publish(NULL, &strm->base, &e, + PJMEDIA_EVENT_PUBLISH_DEFAULT); } return 0; @@ -1204,11 +1203,11 @@ static int PJ_THREAD_FUNC wmme_dev_thread(void *arg) /* API: create stream */ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { struct wmme_factory *wf = (struct wmme_factory*)f; pj_pool_t *pool; @@ -1218,16 +1217,16 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, switch (param->ext_fmt.id) { case PJMEDIA_FORMAT_L16: - silence_char = '\0'; - break; + silence_char = '\0'; + break; case PJMEDIA_FORMAT_ALAW: - silence_char = (pj_uint8_t)'\xd5'; - break; + silence_char = (pj_uint8_t)'\xd5'; + break; case PJMEDIA_FORMAT_ULAW: - silence_char = (pj_uint8_t)'\xff'; - break; + silence_char = (pj_uint8_t)'\xff'; + break; default: - return PJMEDIA_EAUD_BADFORMAT; + return PJMEDIA_EAUD_BADFORMAT; } /* Create and Initialize stream descriptor */ @@ -1245,87 +1244,87 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, /* Create player stream */ if (param->dir & PJMEDIA_DIR_PLAYBACK) { - unsigned buf_count; - - if ((param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY)==0) { - strm->param.flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; - strm->param.output_latency_ms = PJMEDIA_SND_DEFAULT_PLAY_LATENCY; - } - - buf_count = strm->param.output_latency_ms * param->clock_rate * - param->channel_count / param->samples_per_frame / 1000; - - status = init_player_stream(wf, strm->pool, - strm, - &strm->play_strm, - param, - buf_count); - - if (status != PJ_SUCCESS) { - stream_destroy(&strm->base); - return status; - } + unsigned buf_count; + + if ((param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY)==0) { + strm->param.flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; + strm->param.output_latency_ms = PJMEDIA_SND_DEFAULT_PLAY_LATENCY; + } + + buf_count = strm->param.output_latency_ms * param->clock_rate * + param->channel_count / param->samples_per_frame / 1000; + + status = init_player_stream(wf, strm->pool, + strm, + &strm->play_strm, + param, + buf_count); + + if (status != PJ_SUCCESS) { + stream_destroy(&strm->base); + return status; + } } /* Create capture stream */ if (param->dir & PJMEDIA_DIR_CAPTURE) { - unsigned buf_count; - - if ((param->flags & PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY)==0) { - strm->param.flags |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; - strm->param.input_latency_ms = PJMEDIA_SND_DEFAULT_REC_LATENCY; - } - - buf_count = strm->param.input_latency_ms * param->clock_rate * - param->channel_count / param->samples_per_frame / 1000; - - status = init_capture_stream(wf, strm->pool, - strm, - &strm->rec_strm, - param, - buf_count); - - if (status != PJ_SUCCESS) { - stream_destroy(&strm->base); - return status; - } + unsigned buf_count; + + if ((param->flags & PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY)==0) { + strm->param.flags |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; + strm->param.input_latency_ms = PJMEDIA_SND_DEFAULT_REC_LATENCY; + } + + buf_count = strm->param.input_latency_ms * param->clock_rate * + param->channel_count / param->samples_per_frame / 1000; + + status = init_capture_stream(wf, strm->pool, + strm, + &strm->rec_strm, + param, + buf_count); + + if (status != PJ_SUCCESS) { + stream_destroy(&strm->base); + return status; + } } strm->buffer = pj_pool_alloc(pool, strm->bytes_per_frame); if (!strm->buffer) { - pj_pool_release(pool); - return PJ_ENOMEM; + pj_pool_release(pool); + return PJ_ENOMEM; } /* If format is extended, must create buffer for the extended frame. */ if (strm->fmt_id != PJMEDIA_FORMAT_L16) { - strm->xfrm_size = sizeof(pjmedia_frame_ext) + - 32 * sizeof(pjmedia_frame_ext_subframe) + - strm->bytes_per_frame + 4; - strm->xfrm = (pjmedia_frame_ext*) - pj_pool_alloc(pool, strm->xfrm_size); + strm->xfrm_size = sizeof(pjmedia_frame_ext) + + 32 * sizeof(pjmedia_frame_ext_subframe) + + strm->bytes_per_frame + 4; + strm->xfrm = (pjmedia_frame_ext*) + pj_pool_alloc(pool, strm->xfrm_size); } /* Create the stop event */ strm->thread_quit_event = CreateEvent(NULL, FALSE, FALSE, NULL); if (strm->thread_quit_event == NULL) { - status = pj_get_os_error(); - stream_destroy(&strm->base); - return status; + status = pj_get_os_error(); + stream_destroy(&strm->base); + return status; } /* Create and start the thread */ status = pj_thread_create(pool, "wmme", &wmme_dev_thread, strm, 0, 0, - &strm->thread); + &strm->thread); if (status != PJ_SUCCESS) { - stream_destroy(&strm->base); - return status; + stream_destroy(&strm->base); + return status; } /* Apply the remaining settings */ if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { - stream_set_cap(&strm->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - ¶m->output_vol); + stream_set_cap(&strm->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + ¶m->output_vol); } @@ -1338,7 +1337,7 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, /* API: Get stream info. */ static pj_status_t stream_get_param(pjmedia_aud_stream *s, - pjmedia_aud_param *pi) + pjmedia_aud_param *pi) { struct wmme_stream *strm = (struct wmme_stream*)s; @@ -1348,9 +1347,9 @@ static pj_status_t stream_get_param(pjmedia_aud_stream *s, /* Update the volume setting */ if (stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - &pi->output_vol) == PJ_SUCCESS) + &pi->output_vol) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; + pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; } return PJ_SUCCESS; @@ -1358,76 +1357,76 @@ static pj_status_t stream_get_param(pjmedia_aud_stream *s, /* API: get capability */ static pj_status_t stream_get_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - void *pval) + pjmedia_aud_dev_cap cap, + void *pval) { struct wmme_stream *strm = (struct wmme_stream*)s; PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); if (cap==PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY && - (strm->param.dir & PJMEDIA_DIR_CAPTURE)) + (strm->param.dir & PJMEDIA_DIR_CAPTURE)) { - /* Recording latency */ - *(unsigned*)pval = strm->param.input_latency_ms; - return PJ_SUCCESS; + /* Recording latency */ + *(unsigned*)pval = strm->param.input_latency_ms; + return PJ_SUCCESS; } else if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY && - (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) + (strm->param.dir & PJMEDIA_DIR_PLAYBACK)) { - /* Playback latency */ - *(unsigned*)pval = strm->param.output_latency_ms; - return PJ_SUCCESS; + /* Playback latency */ + *(unsigned*)pval = strm->param.output_latency_ms; + return PJ_SUCCESS; } else if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING && - strm->play_strm.hWave.Out) + strm->play_strm.hWave.Out) { - /* Output volume setting */ - DWORD waveVol; - MMRESULT mr; - - mr = waveOutGetVolume(strm->play_strm.hWave.Out, &waveVol); - if (mr != MMSYSERR_NOERROR) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); - } - - waveVol &= 0xFFFF; - *(unsigned*)pval = (waveVol * 100) / 0xFFFF; - return PJ_SUCCESS; + /* Output volume setting */ + DWORD waveVol; + MMRESULT mr; + + mr = waveOutGetVolume(strm->play_strm.hWave.Out, &waveVol); + if (mr != MMSYSERR_NOERROR) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); + } + + waveVol &= 0xFFFF; + *(unsigned*)pval = (waveVol * 100) / 0xFFFF; + return PJ_SUCCESS; } else { - return PJMEDIA_EAUD_INVCAP; + return PJMEDIA_EAUD_INVCAP; } } /* API: set capability */ static pj_status_t stream_set_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - const void *pval) + pjmedia_aud_dev_cap cap, + const void *pval) { struct wmme_stream *strm = (struct wmme_stream*)s; PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); if (cap==PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING && - strm->play_strm.hWave.Out) + strm->play_strm.hWave.Out) { - /* Output volume setting */ - unsigned vol = *(unsigned*)pval; - DWORD waveVol; - MMRESULT mr; - pj_status_t status; - - if (vol > 100) - vol = 100; - - waveVol = (vol * 0xFFFF) / 100; - waveVol |= (waveVol << 16); - - mr = waveOutSetVolume(strm->play_strm.hWave.Out, waveVol); - status = (mr==MMSYSERR_NOERROR)? PJ_SUCCESS : - PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); - if (status == PJ_SUCCESS) { - strm->param.output_vol = *(unsigned*)pval; - } - return status; + /* Output volume setting */ + unsigned vol = *(unsigned*)pval; + DWORD waveVol; + MMRESULT mr; + pj_status_t status; + + if (vol > 100) + vol = 100; + + waveVol = (vol * 0xFFFF) / 100; + waveVol |= (waveVol << 16); + + mr = waveOutSetVolume(strm->play_strm.hWave.Out, waveVol); + status = (mr==MMSYSERR_NOERROR)? PJ_SUCCESS : + PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); + if (status == PJ_SUCCESS) { + strm->param.output_vol = *(unsigned*)pval; + } + return status; } return PJMEDIA_EAUD_INVCAP; @@ -1441,20 +1440,20 @@ static pj_status_t stream_start(pjmedia_aud_stream *strm) if (stream->play_strm.hWave.Out != NULL) { - mr = waveOutRestart(stream->play_strm.hWave.Out); - if (mr != MMSYSERR_NOERROR) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); - } - PJ_LOG(4,(THIS_FILE, "WMME playback stream started")); + mr = waveOutRestart(stream->play_strm.hWave.Out); + if (mr != MMSYSERR_NOERROR) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); + } + PJ_LOG(4,(THIS_FILE, "WMME playback stream started")); } if (stream->rec_strm.hWave.In != NULL) { - mr = waveInStart(stream->rec_strm.hWave.In); - if (mr != MMSYSERR_NOERROR) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(mr); - } - PJ_LOG(4,(THIS_FILE, "WMME capture stream started")); + mr = waveInStart(stream->rec_strm.hWave.In); + if (mr != MMSYSERR_NOERROR) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(mr); + } + PJ_LOG(4,(THIS_FILE, "WMME capture stream started")); } return PJ_SUCCESS; @@ -1470,20 +1469,20 @@ static pj_status_t stream_stop(pjmedia_aud_stream *strm) if (stream->play_strm.hWave.Out != NULL) { - mr = waveOutPause(stream->play_strm.hWave.Out); - if (mr != MMSYSERR_NOERROR) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); - } - PJ_LOG(4,(THIS_FILE, "Stopped WMME playback stream")); + mr = waveOutPause(stream->play_strm.hWave.Out); + if (mr != MMSYSERR_NOERROR) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_OUT(mr); + } + PJ_LOG(4,(THIS_FILE, "Stopped WMME playback stream")); } if (stream->rec_strm.hWave.In != NULL) { - mr = waveInStop(stream->rec_strm.hWave.In); - if (mr != MMSYSERR_NOERROR) { - return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(mr); - } - PJ_LOG(4,(THIS_FILE, "Stopped WMME capture stream")); + mr = waveInStop(stream->rec_strm.hWave.In); + if (mr != MMSYSERR_NOERROR) { + return PJMEDIA_AUDIODEV_ERRNO_FROM_WMME_IN(mr); + } + PJ_LOG(4,(THIS_FILE, "Stopped WMME capture stream")); } return PJ_SUCCESS; @@ -1503,55 +1502,55 @@ static pj_status_t stream_destroy(pjmedia_aud_stream *strm) /* Stop the stream thread */ if (stream->thread) { - SetEvent(stream->thread_quit_event); - pj_thread_join(stream->thread); - pj_thread_destroy(stream->thread); - stream->thread = NULL; + SetEvent(stream->thread_quit_event); + pj_thread_join(stream->thread); + pj_thread_destroy(stream->thread); + stream->thread = NULL; } /* Close the thread quit event */ if (stream->thread_quit_event) { - CloseHandle(stream->thread_quit_event); - stream->thread_quit_event = NULL; + CloseHandle(stream->thread_quit_event); + stream->thread_quit_event = NULL; } /* Unprepare the headers and close the play device */ if (stream->play_strm.hWave.Out) { - waveOutReset(stream->play_strm.hWave.Out); - for (i = 0; i < stream->play_strm.dwMaxBufIdx; ++i) - waveOutUnprepareHeader(stream->play_strm.hWave.Out, - &(stream->play_strm.WaveHdr[i]), - sizeof(WAVEHDR)); - waveOutClose(stream->play_strm.hWave.Out); - stream->play_strm.hWave.Out = NULL; + waveOutReset(stream->play_strm.hWave.Out); + for (i = 0; i < stream->play_strm.dwMaxBufIdx; ++i) + waveOutUnprepareHeader(stream->play_strm.hWave.Out, + &(stream->play_strm.WaveHdr[i]), + sizeof(WAVEHDR)); + waveOutClose(stream->play_strm.hWave.Out); + stream->play_strm.hWave.Out = NULL; } /* Close the play event */ if (stream->play_strm.hEvent) { - CloseHandle(stream->play_strm.hEvent); - stream->play_strm.hEvent = NULL; + CloseHandle(stream->play_strm.hEvent); + stream->play_strm.hEvent = NULL; } /* Unprepare the headers and close the record device */ if (stream->rec_strm.hWave.In) { - waveInReset(stream->rec_strm.hWave.In); - for (i = 0; i < stream->play_strm.dwMaxBufIdx; ++i) - waveInUnprepareHeader(stream->rec_strm.hWave.In, - &(stream->rec_strm.WaveHdr[i]), - sizeof(WAVEHDR)); - waveInClose(stream->rec_strm.hWave.In); - stream->rec_strm.hWave.In = NULL; + waveInReset(stream->rec_strm.hWave.In); + for (i = 0; i < stream->play_strm.dwMaxBufIdx; ++i) + waveInUnprepareHeader(stream->rec_strm.hWave.In, + &(stream->rec_strm.WaveHdr[i]), + sizeof(WAVEHDR)); + waveInClose(stream->rec_strm.hWave.In); + stream->rec_strm.hWave.In = NULL; } /* Close the record event */ if (stream->rec_strm.hEvent) { - CloseHandle(stream->rec_strm.hEvent); - stream->rec_strm.hEvent = NULL; + CloseHandle(stream->rec_strm.hEvent); + stream->rec_strm.hEvent = NULL; } pj_pool_release(stream->pool); @@ -1559,5 +1558,5 @@ static pj_status_t stream_destroy(pjmedia_aud_stream *strm) return PJ_SUCCESS; } -#endif /* PJMEDIA_AUDIO_DEV_HAS_WMME */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_WMME */ diff --git a/pjmedia/src/pjmedia-codec/amr_sdp_match.c b/pjmedia/src/pjmedia-codec/amr_sdp_match.c index 5eb0218589..c4fa542265 100644 --- a/pjmedia/src/pjmedia-codec/amr_sdp_match.c +++ b/pjmedia/src/pjmedia-codec/amr_sdp_match.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,26 +24,26 @@ #define GET_FMTP_IVAL_BASE(ival, base, fmtp, param, default_val) \ do { \ - pj_str_t s; \ - char *p; \ - p = pj_stristr(&fmtp.fmt_param, ¶m); \ - if (!p) { \ - ival = default_val; \ - break; \ - } \ - pj_strset(&s, p + param.slen, fmtp.fmt_param.slen - \ - (p - fmtp.fmt_param.ptr) - param.slen); \ - ival = pj_strtoul2(&s, NULL, base); \ + pj_str_t s; \ + char *p; \ + p = pj_stristr(&fmtp.fmt_param, ¶m); \ + if (!p) { \ + ival = default_val; \ + break; \ + } \ + pj_strset(&s, p + param.slen, fmtp.fmt_param.slen - \ + (p - fmtp.fmt_param.ptr) - param.slen); \ + ival = pj_strtoul2(&s, NULL, base); \ } while (0) #define GET_FMTP_IVAL(ival, fmtp, param, default_val) \ - GET_FMTP_IVAL_BASE(ival, 10, fmtp, param, default_val) + GET_FMTP_IVAL_BASE(ival, 10, fmtp, param, default_val) /* Toggle AMR octet-align setting in the fmtp. */ static pj_status_t amr_toggle_octet_align(pj_pool_t *pool, - pjmedia_sdp_media *media, - unsigned fmt_idx) + pjmedia_sdp_media *media, + unsigned fmt_idx) { pjmedia_sdp_attr *attr; pjmedia_sdp_fmtp fmtp; @@ -53,48 +52,48 @@ static pj_status_t amr_toggle_octet_align(pj_pool_t *pool, enum { MAX_FMTP_STR_LEN = 160 }; attr = pjmedia_sdp_media_find_attr2(media, "fmtp", - &media->desc.fmt[fmt_idx]); + &media->desc.fmt[fmt_idx]); /* Check if the AMR media format has FMTP attribute */ if (attr) { - char *p; - pj_status_t status; - - status = pjmedia_sdp_attr_get_fmtp(attr, &fmtp); - if (status != PJ_SUCCESS) - return status; - - /* Check if the fmtp has octet-align field. */ - p = pj_stristr(&fmtp.fmt_param, &STR_OCTET_ALIGN); - if (p) { - /* It has, just toggle the value */ - unsigned octet_align; - pj_str_t s; - - pj_strset(&s, p + STR_OCTET_ALIGN.slen, fmtp.fmt_param.slen - - (p - fmtp.fmt_param.ptr) - STR_OCTET_ALIGN.slen); - octet_align = pj_strtoul(&s); - *(p + STR_OCTET_ALIGN.slen) = (char)(octet_align? '0' : '1'); - } else { - /* It doesn't, append octet-align field */ - char buf[MAX_FMTP_STR_LEN]; - - pj_ansi_snprintf(buf, MAX_FMTP_STR_LEN, "%.*s;octet-align=1", - (int)fmtp.fmt_param.slen, fmtp.fmt_param.ptr); - attr->value = pj_strdup3(pool, buf); - } + char *p; + pj_status_t status; + + status = pjmedia_sdp_attr_get_fmtp(attr, &fmtp); + if (status != PJ_SUCCESS) + return status; + + /* Check if the fmtp has octet-align field. */ + p = pj_stristr(&fmtp.fmt_param, &STR_OCTET_ALIGN); + if (p) { + /* It has, just toggle the value */ + unsigned octet_align; + pj_str_t s; + + pj_strset(&s, p + STR_OCTET_ALIGN.slen, fmtp.fmt_param.slen - + (p - fmtp.fmt_param.ptr) - STR_OCTET_ALIGN.slen); + octet_align = pj_strtoul(&s); + *(p + STR_OCTET_ALIGN.slen) = (char)(octet_align? '0' : '1'); + } else { + /* It doesn't, append octet-align field */ + char buf[MAX_FMTP_STR_LEN]; + + pj_ansi_snprintf(buf, MAX_FMTP_STR_LEN, "%.*s;octet-align=1", + (int)fmtp.fmt_param.slen, fmtp.fmt_param.ptr); + attr->value = pj_strdup3(pool, buf); + } } else { - /* Add new attribute for the AMR media format with octet-align - * field set. - */ - char buf[MAX_FMTP_STR_LEN]; - - attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); - attr->name = pj_str("fmtp"); - pj_ansi_snprintf(buf, MAX_FMTP_STR_LEN, "%.*s octet-align=1", - (int)media->desc.fmt[fmt_idx].slen, - media->desc.fmt[fmt_idx].ptr); - attr->value = pj_strdup3(pool, buf); - media->attr[media->attr_count++] = attr; + /* Add new attribute for the AMR media format with octet-align + * field set. + */ + char buf[MAX_FMTP_STR_LEN]; + + attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); + attr->name = pj_str("fmtp"); + pj_ansi_snprintf(buf, MAX_FMTP_STR_LEN, "%.*s octet-align=1", + (int)media->desc.fmt[fmt_idx].slen, + media->desc.fmt[fmt_idx].ptr); + attr->value = pj_strdup3(pool, buf); + media->attr[media->attr_count++] = attr; } return PJ_SUCCESS; @@ -102,17 +101,17 @@ static pj_status_t amr_toggle_octet_align(pj_pool_t *pool, PJ_DEF(pj_status_t) pjmedia_codec_amr_match_sdp( pj_pool_t *pool, - pjmedia_sdp_media *offer, - unsigned o_fmt_idx, - pjmedia_sdp_media *answer, - unsigned a_fmt_idx, - unsigned option) + pjmedia_sdp_media *offer, + unsigned o_fmt_idx, + pjmedia_sdp_media *answer, + unsigned a_fmt_idx, + unsigned option) { /* Negotiated format-param field-names constants. */ - const pj_str_t STR_OCTET_ALIGN = {"octet-align=", 12}; - const pj_str_t STR_CRC = {"crc=", 4}; - const pj_str_t STR_ROBUST_SORTING = {"robust-sorting=", 15}; - const pj_str_t STR_INTERLEAVING = {"interleaving=", 13}; + const pj_str_t STR_OCTET_ALIGN = {"octet-align=", 12}; + const pj_str_t STR_CRC = {"crc=", 4}; + const pj_str_t STR_ROBUST_SORTING = {"robust-sorting=", 15}; + const pj_str_t STR_INTERLEAVING = {"interleaving=", 13}; /* Negotiated params and their default values. */ unsigned a_octet_align = 0, o_octet_align = 0; @@ -127,49 +126,49 @@ PJ_DEF(pj_status_t) pjmedia_codec_amr_match_sdp( pj_pool_t *pool, /* Parse offerer FMTP */ attr_ofr = pjmedia_sdp_media_find_attr2(offer, "fmtp", - &offer->desc.fmt[o_fmt_idx]); + &offer->desc.fmt[o_fmt_idx]); if (attr_ofr) { - status = pjmedia_sdp_attr_get_fmtp(attr_ofr, &fmtp); - if (status != PJ_SUCCESS) - return status; - - GET_FMTP_IVAL(o_octet_align, fmtp, STR_OCTET_ALIGN, 0); - GET_FMTP_IVAL(o_crc, fmtp, STR_CRC, 0); - GET_FMTP_IVAL(o_robust_sorting, fmtp, STR_ROBUST_SORTING, 0); - GET_FMTP_IVAL(o_interleaving, fmtp, STR_INTERLEAVING, 0); + status = pjmedia_sdp_attr_get_fmtp(attr_ofr, &fmtp); + if (status != PJ_SUCCESS) + return status; + + GET_FMTP_IVAL(o_octet_align, fmtp, STR_OCTET_ALIGN, 0); + GET_FMTP_IVAL(o_crc, fmtp, STR_CRC, 0); + GET_FMTP_IVAL(o_robust_sorting, fmtp, STR_ROBUST_SORTING, 0); + GET_FMTP_IVAL(o_interleaving, fmtp, STR_INTERLEAVING, 0); } /* Parse answerer FMTP */ attr_ans = pjmedia_sdp_media_find_attr2(answer, "fmtp", - &answer->desc.fmt[a_fmt_idx]); + &answer->desc.fmt[a_fmt_idx]); if (attr_ans) { - status = pjmedia_sdp_attr_get_fmtp(attr_ans, &fmtp); - if (status != PJ_SUCCESS) - return status; - - GET_FMTP_IVAL(a_octet_align, fmtp, STR_OCTET_ALIGN, 0); - GET_FMTP_IVAL(a_crc, fmtp, STR_CRC, 0); - GET_FMTP_IVAL(a_robust_sorting, fmtp, STR_ROBUST_SORTING, 0); - GET_FMTP_IVAL(a_interleaving, fmtp, STR_INTERLEAVING, 0); + status = pjmedia_sdp_attr_get_fmtp(attr_ans, &fmtp); + if (status != PJ_SUCCESS) + return status; + + GET_FMTP_IVAL(a_octet_align, fmtp, STR_OCTET_ALIGN, 0); + GET_FMTP_IVAL(a_crc, fmtp, STR_CRC, 0); + GET_FMTP_IVAL(a_robust_sorting, fmtp, STR_ROBUST_SORTING, 0); + GET_FMTP_IVAL(a_interleaving, fmtp, STR_INTERLEAVING, 0); } /* First, match crc, robust-sorting, interleaving settings */ if (a_crc != o_crc || - a_robust_sorting != o_robust_sorting || - a_interleaving != o_interleaving) + a_robust_sorting != o_robust_sorting || + a_interleaving != o_interleaving) { - return PJMEDIA_SDP_EFORMATNOTEQUAL; + return PJMEDIA_SDP_EFORMATNOTEQUAL; } /* Match octet-align setting */ if (a_octet_align != o_octet_align) { - /* Check if answer can be modified to match to the offer */ - if (option & PJMEDIA_SDP_NEG_FMT_MATCH_ALLOW_MODIFY_ANSWER) { - status = amr_toggle_octet_align(pool, answer, a_fmt_idx); - return status; - } else { - return PJMEDIA_SDP_EFORMATNOTEQUAL; - } + /* Check if answer can be modified to match to the offer */ + if (option & PJMEDIA_SDP_NEG_FMT_MATCH_ALLOW_MODIFY_ANSWER) { + status = amr_toggle_octet_align(pool, answer, a_fmt_idx); + return status; + } else { + return PJMEDIA_SDP_EFORMATNOTEQUAL; + } } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia-codec/and_aud_mediacodec.cpp b/pjmedia/src/pjmedia-codec/and_aud_mediacodec.cpp index 08faf07bb7..14d33a5cad 100644 --- a/pjmedia/src/pjmedia-codec/and_aud_mediacodec.cpp +++ b/pjmedia/src/pjmedia-codec/and_aud_mediacodec.cpp @@ -47,51 +47,51 @@ #define AND_MEDIA_KEY_BITRATE "bitrate" #define AND_MEDIA_KEY_MIME "mime" -#define CODEC_WAIT_RETRY 10 -#define CODEC_THREAD_WAIT 10 +#define CODEC_WAIT_RETRY 10 +#define CODEC_THREAD_WAIT 10 /* Timeout until the buffer is ready in ms. */ -#define CODEC_DEQUEUE_TIMEOUT 10 +#define CODEC_DEQUEUE_TIMEOUT 10 /* Prototypes for Android MediaCodec codecs factory */ static pj_status_t and_media_test_alloc(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ); + const pjmedia_codec_info *id ); static pj_status_t and_media_default_attr(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ); static pj_status_t and_media_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t and_media_alloc_codec(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t and_media_dealloc_codec(pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for Android MediaCodec codecs implementation. */ static pj_status_t and_media_codec_init(pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t and_media_codec_open(pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t and_media_codec_close(pjmedia_codec *codec ); static pj_status_t and_media_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t and_media_codec_parse(pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t and_media_codec_encode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t and_media_codec_decode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t and_media_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); /* Definition for Android MediaCodec codecs operations. */ static pjmedia_codec_op and_media_op = @@ -120,9 +120,9 @@ static pjmedia_codec_factory_op and_media_factory_op = /* Android MediaCodec codecs factory */ static struct and_media_factory { pjmedia_codec_factory base; - pjmedia_endpt *endpt; - pj_pool_t *pool; - pj_mutex_t *mutex; + pjmedia_endpt *endpt; + pj_pool_t *pool; + pj_mutex_t *mutex; } and_media_factory; typedef enum and_aud_codec_id { @@ -135,22 +135,22 @@ typedef enum and_aud_codec_id { /* Android MediaCodec codecs private data. */ typedef struct and_media_private { - int codec_idx; /**< Codec index. */ - void *codec_setting; /**< Specific codec setting. */ - pj_pool_t *pool; /**< Pool for each instance. */ - AMediaCodec *enc; /**< Encoder state. */ - AMediaCodec *dec; /**< Decoder state. */ - - pj_uint16_t frame_size; /**< Bitstream frame size. */ - - pj_bool_t plc_enabled; /**< PLC enabled flag. */ - pjmedia_plc *plc; /**< PJMEDIA PLC engine, NULL if - codec has internal PLC. */ - - pj_bool_t vad_enabled; /**< VAD enabled flag. */ - pjmedia_silence_det *vad; /**< PJMEDIA VAD engine, NULL if - codec has internal VAD. */ - pj_timestamp last_tx; /**< Timestamp of last transmit.*/ + int codec_idx; /**< Codec index. */ + void *codec_setting; /**< Specific codec setting. */ + pj_pool_t *pool; /**< Pool for each instance. */ + AMediaCodec *enc; /**< Encoder state. */ + AMediaCodec *dec; /**< Decoder state. */ + + pj_uint16_t frame_size; /**< Bitstream frame size. */ + + pj_bool_t plc_enabled; /**< PLC enabled flag. */ + pjmedia_plc *plc; /**< PJMEDIA PLC engine, NULL if + codec has internal PLC. */ + + pj_bool_t vad_enabled; /**< VAD enabled flag. */ + pjmedia_silence_det *vad; /**< PJMEDIA VAD engine, NULL if + codec has internal VAD. */ + pj_timestamp last_tx; /**< Timestamp of last transmit.*/ } and_media_private_t; /* CUSTOM CALLBACKS */ @@ -161,8 +161,8 @@ typedef struct and_media_private { * unapplicable. */ typedef pj_status_t (*parse_cb)(and_media_private_t *codec_data, void *pkt, - pj_size_t pkt_size, const pj_timestamp *ts, - unsigned *frame_cnt, pjmedia_frame frames[]); + pj_size_t pkt_size, const pj_timestamp *ts, + unsigned *frame_cnt, pjmedia_frame frames[]); /* Pack frames into a packet. Default behaviour of packing frames is * just stacking the frames with octet aligned without adding any @@ -170,71 +170,71 @@ typedef pj_status_t (*parse_cb)(and_media_private_t *codec_data, void *pkt, * unapplicable. */ typedef pj_status_t (*pack_cb)(and_media_private_t *codec_data, - unsigned nframes, void *pkt, pj_size_t *pkt_size, - pj_size_t max_pkt_size); + unsigned nframes, void *pkt, pj_size_t *pkt_size, + pj_size_t max_pkt_size); /* This callback is useful for preparing a frame before pass it to decoder. */ typedef void (*predecode_cb)(and_media_private_t *codec_data, - const pjmedia_frame *rtp_frame, - pjmedia_frame *out); + const pjmedia_frame *rtp_frame, + pjmedia_frame *out); #if PJMEDIA_HAS_AND_MEDIA_AMRNB || PJMEDIA_HAS_AND_MEDIA_AMRWB /* Custom callback implementations. */ static pj_status_t parse_amr(and_media_private_t *codec_data, void *pkt, - pj_size_t pkt_size, const pj_timestamp *ts, - unsigned *frame_cnt, pjmedia_frame frames[]); + pj_size_t pkt_size, const pj_timestamp *ts, + unsigned *frame_cnt, pjmedia_frame frames[]); static pj_status_t pack_amr(and_media_private_t *codec_data, unsigned nframes, - void *pkt, pj_size_t *pkt_size, - pj_size_t max_pkt_size); + void *pkt, pj_size_t *pkt_size, + pj_size_t max_pkt_size); static void predecode_amr(and_media_private_t *codec_data, - const pjmedia_frame *input, - pjmedia_frame *out); + const pjmedia_frame *input, + pjmedia_frame *out); #endif #if PJMEDIA_HAS_AND_MEDIA_AMRNB static pj_str_t AMRNB_encoder[] = {{(char *)"OMX.google.amrnb.encoder\0", 24}, - {(char *)"c2.android.amrnb.encoder\0", 24}}; + {(char *)"c2.android.amrnb.encoder\0", 24}}; static pj_str_t AMRNB_decoder[] = {{(char *)"OMX.google.amrnb.decoder\0", 24}, - {(char *)"c2.android.amrnb.decoder\0", 24}}; + {(char *)"c2.android.amrnb.decoder\0", 24}}; #endif #if PJMEDIA_HAS_AND_MEDIA_AMRWB static pj_str_t AMRWB_encoder[] = {{(char *)"OMX.google.amrwb.encoder\0", 24}, - {(char *)"c2.android.amrwb.encoder\0", 24}}; + {(char *)"c2.android.amrwb.encoder\0", 24}}; static pj_str_t AMRWB_decoder[] = {{(char *)"OMX.google.amrwb.decoder\0", 24}, - {(char *)"c2.android.amrwb.decoder\0", 24}}; + {(char *)"c2.android.amrwb.decoder\0", 24}}; #endif /* Android MediaCodec codec implementation descriptions. */ static struct and_media_codec { - int enabled; /* Is this codec enabled? */ - const char *name; /* Codec name. */ + int enabled; /* Is this codec enabled? */ + const char *name; /* Codec name. */ const char *mime_type; /* Mime type. */ pj_str_t *encoder_name; /* Encoder name. */ pj_str_t *decoder_name; /* Decoder name. */ - pj_uint8_t pt; /* Payload type. */ - and_aud_codec_id codec_id; /* Codec id. */ - unsigned clock_rate; /* Codec's clock rate. */ - unsigned channel_count; /* Codec's channel count. */ - unsigned samples_per_frame; /* Codec's samples count. */ - unsigned def_bitrate; /* Default bitrate of this codec. */ - unsigned max_bitrate; /* Maximum bitrate of this codec. */ - pj_uint8_t frm_per_pkt; /* Default num of frames per packet.*/ - int has_native_vad; /* Codec has internal VAD? */ - int has_native_plc; /* Codec has internal PLC? */ - - parse_cb parse; /* Callback to parse bitstream. */ - pack_cb pack; /* Callback to pack bitstream. */ + pj_uint8_t pt; /* Payload type. */ + and_aud_codec_id codec_id; /* Codec id. */ + unsigned clock_rate; /* Codec's clock rate. */ + unsigned channel_count; /* Codec's channel count. */ + unsigned samples_per_frame; /* Codec's samples count. */ + unsigned def_bitrate; /* Default bitrate of this codec. */ + unsigned max_bitrate; /* Maximum bitrate of this codec. */ + pj_uint8_t frm_per_pkt; /* Default num of frames per packet.*/ + int has_native_vad; /* Codec has internal VAD? */ + int has_native_plc; /* Codec has internal PLC? */ + + parse_cb parse; /* Callback to parse bitstream. */ + pack_cb pack; /* Callback to pack bitstream. */ predecode_cb predecode; /* Callback to prepare bitstream before passing it to decoder. */ - pjmedia_codec_fmtp dec_fmtp; /* Decoder's fmtp params. */ + pjmedia_codec_fmtp dec_fmtp; /* Decoder's fmtp params. */ } and_media_codec[] = @@ -251,7 +251,7 @@ and_media_codec[] = {0, "AMR-WB", "audio/amr-wb", NULL, NULL, PJMEDIA_RTP_PT_AMRWB, AND_AUD_CODEC_AMRWB, 16000, 1, 320, 15850, 23850, 2, 0, 0, &parse_amr, &pack_amr, &predecode_amr, - {1, {{{(char *)"octet-align", 11}, {(char *)"1", 1}}}} + {1, {{{(char *)"octet-align", 11}, {(char *)"1", 1}}}} }, # endif }; @@ -268,8 +268,8 @@ typedef struct amr_settings_t { /* Pack AMR payload */ static pj_status_t pack_amr(and_media_private_t *codec_data, unsigned nframes, - void *pkt, pj_size_t *pkt_size, - pj_size_t max_pkt_size) + void *pkt, pj_size_t *pkt_size, + pj_size_t max_pkt_size) { enum {MAX_FRAMES_PER_PACKET = PJMEDIA_MAX_FRAME_DURATION_MS / 20}; @@ -287,14 +287,14 @@ static pj_status_t pack_amr(and_media_private_t *codec_data, unsigned nframes, /* Get frames */ for (i = 0; i < nframes; ++i) { - pjmedia_codec_amr_bit_info *info = (pjmedia_codec_amr_bit_info*) - &frames[i].bit_info; - pj_bzero(info, sizeof(*info)); - info->frame_type = (pj_uint8_t)((*p >> 3) & 0x0F); - info->good_quality = (pj_uint8_t)((*p >> 2) & 0x01); - info->mode = ((amr_settings_t*)codec_data->codec_setting)->enc_mode; - info->start_bit = 0; - frames[i].buf = p + 1; + pjmedia_codec_amr_bit_info *info = (pjmedia_codec_amr_bit_info*) + &frames[i].bit_info; + pj_bzero(info, sizeof(*info)); + info->frame_type = (pj_uint8_t)((*p >> 3) & 0x0F); + info->good_quality = (pj_uint8_t)((*p >> 2) & 0x01); + info->mode = ((amr_settings_t*)codec_data->codec_setting)->enc_mode; + info->start_bit = 0; + frames[i].buf = p + 1; if (setting->amr_nb) { frames[i].size = (info->frame_type <= 8)? pjmedia_codec_amrnb_framelen[info->frame_type] : 0; @@ -302,7 +302,7 @@ static pj_status_t pack_amr(and_media_private_t *codec_data, unsigned nframes, frames[i].size = (info->frame_type <= 9)? pjmedia_codec_amrwb_framelen[info->frame_type] : 0; } - p += frames[i].size + 1; + p += frames[i].size + 1; } /* Pack */ *pkt_size = max_pkt_size; @@ -313,8 +313,8 @@ static pj_status_t pack_amr(and_media_private_t *codec_data, unsigned nframes, /* Parse AMR payload into frames. */ static pj_status_t parse_amr(and_media_private_t *codec_data, void *pkt, - pj_size_t pkt_size, const pj_timestamp *ts, - unsigned *frame_cnt, pjmedia_frame frames[]) + pj_size_t pkt_size, const pj_timestamp *ts, + unsigned *frame_cnt, pjmedia_frame frames[]) { amr_settings_t* s = (amr_settings_t*)codec_data->codec_setting; pjmedia_codec_amr_pack_setting *setting; @@ -323,22 +323,22 @@ static pj_status_t parse_amr(and_media_private_t *codec_data, void *pkt, setting = &s->dec_setting; status = pjmedia_codec_amr_parse(pkt, pkt_size, ts, setting, frames, - frame_cnt, &cmr); + frame_cnt, &cmr); if (status != PJ_SUCCESS) - return status; + return status; /* Check Change Mode Request. */ if (((setting->amr_nb && cmr <= 7) || (!setting->amr_nb && cmr <= 8)) && - s->enc_mode != cmr) + s->enc_mode != cmr) { - s->enc_mode = cmr; + s->enc_mode = cmr; } return PJ_SUCCESS; } static void predecode_amr(and_media_private_t *codec_data, - const pjmedia_frame *input, - pjmedia_frame *out) + const pjmedia_frame *input, + pjmedia_frame *out) { pjmedia_codec_amr_bit_info *info; pj_uint8_t *bitstream = (pj_uint8_t *)out->buf; @@ -356,7 +356,7 @@ static void predecode_amr(and_media_private_t *codec_data, #endif /* PJMEDIA_HAS_AND_MEDIA_AMRNB || PJMEDIA_HAS_AND_MEDIA_AMRWB */ static pj_status_t configure_codec(and_media_private_t *and_media_data, - pj_bool_t is_encoder) + pj_bool_t is_encoder) { media_status_t am_status; AMediaFormat *aud_fmt; @@ -373,9 +373,9 @@ static pj_status_t configure_codec(and_media_private_t *and_media_data, AMediaFormat_setInt32(aud_fmt, AND_MEDIA_KEY_CHANNEL_COUNT, and_media_codec[idx].channel_count); AMediaFormat_setInt32(aud_fmt, AND_MEDIA_KEY_SAMPLE_RATE, - and_media_codec[idx].clock_rate); + and_media_codec[idx].clock_rate); AMediaFormat_setInt32(aud_fmt, AND_MEDIA_KEY_BITRATE, - and_media_codec[idx].def_bitrate); + and_media_codec[idx].def_bitrate); /* Configure and start encoder. */ am_status = AMediaCodec_configure(codec, aud_fmt, NULL, NULL, is_encoder); @@ -387,12 +387,12 @@ static pj_status_t configure_codec(and_media_private_t *and_media_data, } am_status = AMediaCodec_start(codec); if (am_status != AMEDIA_OK) { - PJ_LOG(4, (THIS_FILE, "%s [0x%x] start failed, status=%d", - is_encoder?"Encoder":"Decoder", codec, am_status)); - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(4, (THIS_FILE, "%s [0x%x] start failed, status=%d", + is_encoder?"Encoder":"Decoder", codec, am_status)); + return PJMEDIA_CODEC_EFAILED; } PJ_LOG(4, (THIS_FILE, "%s [0x%x] started", is_encoder?"Encoder":"Decoder", - codec)); + codec)); return PJ_SUCCESS; } @@ -406,8 +406,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_and_media_aud_init( pjmedia_endpt *endpt ) pj_status_t status; if (and_media_factory.pool != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } PJ_LOG(4, (THIS_FILE, "Initing codec")); @@ -421,20 +421,20 @@ PJ_DEF(pj_status_t) pjmedia_codec_and_media_aud_init( pjmedia_endpt *endpt ) "Android MediaCodec codecs", 4000, 4000); if (!and_media_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create mutex. */ status = pj_mutex_create_simple(and_media_factory.pool, "Android MediaCodec codecs", - &and_media_factory.mutex); + &and_media_factory.mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - status = PJ_EINVALIDOP; - goto on_error; + status = PJ_EINVALIDOP; + goto on_error; } #if PJMEDIA_HAS_AND_MEDIA_AMRNB @@ -442,10 +442,10 @@ PJ_DEF(pj_status_t) pjmedia_codec_and_media_aud_init( pjmedia_endpt *endpt ) pj_cstr(&codec_name, "AMR"); status = pjmedia_sdp_neg_register_fmt_match_cb( - &codec_name, - &pjmedia_codec_amr_match_sdp); + &codec_name, + &pjmedia_codec_amr_match_sdp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #endif #if PJMEDIA_HAS_AND_MEDIA_AMRWB @@ -453,10 +453,10 @@ PJ_DEF(pj_status_t) pjmedia_codec_and_media_aud_init( pjmedia_endpt *endpt ) pj_cstr(&codec_name, "AMR-WB"); status = pjmedia_sdp_neg_register_fmt_match_cb( - &codec_name, - &pjmedia_codec_amr_match_sdp); + &codec_name, + &pjmedia_codec_amr_match_sdp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #endif /* Suppress compile warning */ @@ -464,9 +464,9 @@ PJ_DEF(pj_status_t) pjmedia_codec_and_media_aud_init( pjmedia_endpt *endpt ) /* Register codec factory to endpoint. */ status = pjmedia_codec_mgr_register_factory(codec_mgr, - &and_media_factory.base); + &and_media_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Done. */ return PJ_SUCCESS; @@ -486,8 +486,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_and_media_aud_deinit(void) pj_status_t status; if (and_media_factory.pool == NULL) { - /* Already deinitialized */ - return PJ_SUCCESS; + /* Already deinitialized */ + return PJ_SUCCESS; } pj_mutex_lock(and_media_factory.mutex); @@ -495,15 +495,15 @@ PJ_DEF(pj_status_t) pjmedia_codec_and_media_aud_deinit(void) /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(and_media_factory.endpt); if (!codec_mgr) { - pj_pool_release(and_media_factory.pool); - and_media_factory.pool = NULL; - pj_mutex_unlock(and_media_factory.mutex); - return PJ_EINVALIDOP; + pj_pool_release(and_media_factory.pool); + and_media_factory.pool = NULL; + pj_mutex_unlock(and_media_factory.mutex); + return PJ_EINVALIDOP; } /* Unregister Android MediaCodec codecs factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &and_media_factory.base); + &and_media_factory.base); /* Destroy mutex. */ pj_mutex_unlock(and_media_factory.mutex); @@ -521,7 +521,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_and_media_aud_deinit(void) * Check if factory can allocate the specified codec. */ static pj_status_t and_media_test_alloc(pjmedia_codec_factory *factory, - const pjmedia_codec_info *info ) + const pjmedia_codec_info *info ) { unsigned i; @@ -529,17 +529,17 @@ static pj_status_t and_media_test_alloc(pjmedia_codec_factory *factory, /* Type MUST be audio. */ if (info->type != PJMEDIA_TYPE_AUDIO) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; for (i = 0; i < PJ_ARRAY_SIZE(and_media_codec); ++i) { - pj_str_t name = pj_str((char*)and_media_codec[i].name); - if ((pj_stricmp(&info->encoding_name, &name) == 0) && - (info->clock_rate == (unsigned)and_media_codec[i].clock_rate) && - (info->channel_cnt == (unsigned)and_media_codec[i].channel_count) && - (and_media_codec[i].enabled)) - { - return PJ_SUCCESS; - } + pj_str_t name = pj_str((char*)and_media_codec[i].name); + if ((pj_stricmp(&info->encoding_name, &name) == 0) && + (info->clock_rate == (unsigned)and_media_codec[i].clock_rate) && + (info->channel_cnt == (unsigned)and_media_codec[i].channel_count) && + (and_media_codec[i].enabled)) + { + return PJ_SUCCESS; + } } /* Unsupported, or mode is disabled. */ @@ -550,8 +550,8 @@ static pj_status_t and_media_test_alloc(pjmedia_codec_factory *factory, * Generate default attribute. */ static pj_status_t and_media_default_attr (pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr) { unsigned i; @@ -560,34 +560,34 @@ static pj_status_t and_media_default_attr (pjmedia_codec_factory *factory, pj_bzero(attr, sizeof(pjmedia_codec_param)); for (i = 0; i < PJ_ARRAY_SIZE(and_media_codec); ++i) { - pj_str_t name = pj_str((char*)and_media_codec[i].name); - if ((and_media_codec[i].enabled) && - (pj_stricmp(&id->encoding_name, &name) == 0) && - (id->clock_rate == (unsigned)and_media_codec[i].clock_rate) && - (id->channel_cnt == (unsigned)and_media_codec[i].channel_count) && - (id->pt == (unsigned)and_media_codec[i].pt)) - { - attr->info.pt = (pj_uint8_t)id->pt; - attr->info.channel_cnt = and_media_codec[i].channel_count; - attr->info.clock_rate = and_media_codec[i].clock_rate; - attr->info.avg_bps = and_media_codec[i].def_bitrate; - attr->info.max_bps = and_media_codec[i].max_bitrate; - attr->info.pcm_bits_per_sample = 16; - attr->info.frm_ptime = (pj_uint16_t) - (and_media_codec[i].samples_per_frame * 1000 / - and_media_codec[i].channel_count / - and_media_codec[i].clock_rate); - attr->setting.frm_per_pkt = and_media_codec[i].frm_per_pkt; - - /* Default flags. */ - attr->setting.plc = 1; - attr->setting.penh= 0; - attr->setting.vad = 1; - attr->setting.cng = attr->setting.vad; - attr->setting.dec_fmtp = and_media_codec[i].dec_fmtp; - - return PJ_SUCCESS; - } + pj_str_t name = pj_str((char*)and_media_codec[i].name); + if ((and_media_codec[i].enabled) && + (pj_stricmp(&id->encoding_name, &name) == 0) && + (id->clock_rate == (unsigned)and_media_codec[i].clock_rate) && + (id->channel_cnt == (unsigned)and_media_codec[i].channel_count) && + (id->pt == (unsigned)and_media_codec[i].pt)) + { + attr->info.pt = (pj_uint8_t)id->pt; + attr->info.channel_cnt = and_media_codec[i].channel_count; + attr->info.clock_rate = and_media_codec[i].clock_rate; + attr->info.avg_bps = and_media_codec[i].def_bitrate; + attr->info.max_bps = and_media_codec[i].max_bitrate; + attr->info.pcm_bits_per_sample = 16; + attr->info.frm_ptime = (pj_uint16_t) + (and_media_codec[i].samples_per_frame * 1000 / + and_media_codec[i].channel_count / + and_media_codec[i].clock_rate); + attr->setting.frm_per_pkt = and_media_codec[i].frm_per_pkt; + + /* Default flags. */ + attr->setting.plc = 1; + attr->setting.penh= 0; + attr->setting.vad = 1; + attr->setting.cng = attr->setting.vad; + attr->setting.dec_fmtp = and_media_codec[i].dec_fmtp; + + return PJ_SUCCESS; + } } return PJMEDIA_CODEC_EUNSUP; @@ -602,9 +602,9 @@ static pj_bool_t codec_exists(const pj_str_t *codec_name) codec = AMediaCodec_createCodecByName(codec_txt); if (!codec) { - PJ_LOG(4, (THIS_FILE, "Failed creating codec : %.*s", codec_name->slen, - codec_name->ptr)); - return PJ_FALSE; + PJ_LOG(4, (THIS_FILE, "Failed creating codec : %.*s", codec_name->slen, + codec_name->ptr)); + return PJ_FALSE; } AMediaCodec_delete(codec); @@ -615,8 +615,8 @@ static pj_bool_t codec_exists(const pj_str_t *codec_name) * Enum codecs supported by this factory. */ static pj_status_t and_media_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]) + unsigned *count, + pjmedia_codec_info codecs[]) { unsigned max; unsigned i; @@ -629,67 +629,67 @@ static pj_status_t and_media_enum_codecs(pjmedia_codec_factory *factory, for (i = 0, *count = 0; i < PJ_ARRAY_SIZE(and_media_codec) && *count < max; ++i) { - unsigned enc_idx, dec_idx; - pj_str_t *enc_name = NULL; - unsigned num_enc = 0; - pj_str_t *dec_name = NULL; - unsigned num_dec = 0; + unsigned enc_idx, dec_idx; + pj_str_t *enc_name = NULL; + unsigned num_enc = 0; + pj_str_t *dec_name = NULL; + unsigned num_dec = 0; - switch (and_media_codec[i].codec_id) { + switch (and_media_codec[i].codec_id) { - case AND_AUD_CODEC_AMRNB: + case AND_AUD_CODEC_AMRNB: #if PJMEDIA_HAS_AND_MEDIA_AMRNB - enc_name = &AMRNB_encoder[0]; - dec_name = &AMRNB_decoder[0]; - num_enc = PJ_ARRAY_SIZE(AMRNB_encoder); - num_dec = PJ_ARRAY_SIZE(AMRNB_decoder); + enc_name = &AMRNB_encoder[0]; + dec_name = &AMRNB_decoder[0]; + num_enc = PJ_ARRAY_SIZE(AMRNB_encoder); + num_dec = PJ_ARRAY_SIZE(AMRNB_decoder); #endif - break; - case AND_AUD_CODEC_AMRWB: + break; + case AND_AUD_CODEC_AMRWB: #if PJMEDIA_HAS_AND_MEDIA_AMRWB - enc_name = &AMRWB_encoder[0]; - dec_name = &AMRWB_decoder[0]; - num_enc = PJ_ARRAY_SIZE(AMRWB_encoder); - num_dec = PJ_ARRAY_SIZE(AMRWB_decoder); + enc_name = &AMRWB_encoder[0]; + dec_name = &AMRWB_decoder[0]; + num_enc = PJ_ARRAY_SIZE(AMRWB_encoder); + num_dec = PJ_ARRAY_SIZE(AMRWB_decoder); #endif - break; - default: - continue; - }; - if (!enc_name || !dec_name) { - continue; - } - - for (enc_idx = 0; enc_idx < num_enc ;++enc_idx, ++enc_name) { - if (codec_exists(enc_name)) { - break; - } - } - if (enc_idx == num_enc) - continue; - - for (dec_idx = 0; dec_idx < num_dec ;++dec_idx, ++dec_name) { - if (codec_exists(dec_name)) { - break; - } - } - if (dec_idx == num_dec) - continue; - - and_media_codec[i].encoder_name = enc_name; - and_media_codec[i].decoder_name = dec_name; - pj_bzero(&codecs[*count], sizeof(pjmedia_codec_info)); - codecs[*count].encoding_name = pj_str((char*)and_media_codec[i].name); - codecs[*count].pt = and_media_codec[i].pt; - codecs[*count].type = PJMEDIA_TYPE_AUDIO; - codecs[*count].clock_rate = and_media_codec[i].clock_rate; - codecs[*count].channel_cnt = and_media_codec[i].channel_count; - and_media_codec[i].enabled = PJ_TRUE; - PJ_LOG(4, (THIS_FILE, "Found encoder [%d]: %.*s and decoder: %.*s ", - *count, enc_name->slen, enc_name->ptr, dec_name->slen, - dec_name->ptr)); - ++*count; + break; + default: + continue; + }; + if (!enc_name || !dec_name) { + continue; + } + + for (enc_idx = 0; enc_idx < num_enc ;++enc_idx, ++enc_name) { + if (codec_exists(enc_name)) { + break; + } + } + if (enc_idx == num_enc) + continue; + + for (dec_idx = 0; dec_idx < num_dec ;++dec_idx, ++dec_name) { + if (codec_exists(dec_name)) { + break; + } + } + if (dec_idx == num_dec) + continue; + + and_media_codec[i].encoder_name = enc_name; + and_media_codec[i].decoder_name = dec_name; + pj_bzero(&codecs[*count], sizeof(pjmedia_codec_info)); + codecs[*count].encoding_name = pj_str((char*)and_media_codec[i].name); + codecs[*count].pt = and_media_codec[i].pt; + codecs[*count].type = PJMEDIA_TYPE_AUDIO; + codecs[*count].clock_rate = and_media_codec[i].clock_rate; + codecs[*count].channel_cnt = and_media_codec[i].channel_count; + and_media_codec[i].enabled = PJ_TRUE; + PJ_LOG(4, (THIS_FILE, "Found encoder [%d]: %.*s and decoder: %.*s ", + *count, enc_name->slen, enc_name->ptr, dec_name->slen, + dec_name->ptr)); + ++*count; } return PJ_SUCCESS; @@ -698,26 +698,26 @@ static pj_status_t and_media_enum_codecs(pjmedia_codec_factory *factory, static void create_codec(and_media_private_t *and_media_data) { char const *enc_name = - and_media_codec[and_media_data->codec_idx].encoder_name->ptr; + and_media_codec[and_media_data->codec_idx].encoder_name->ptr; char const *dec_name = - and_media_codec[and_media_data->codec_idx].decoder_name->ptr; + and_media_codec[and_media_data->codec_idx].decoder_name->ptr; if (!and_media_data->enc) { - and_media_data->enc = AMediaCodec_createCodecByName(enc_name); - if (!and_media_data->enc) { - PJ_LOG(4, (THIS_FILE, "Failed creating encoder: %s", enc_name)); - } - PJ_LOG(4, (THIS_FILE, "Done creating encoder: %s [0x%x]", enc_name, - and_media_data->enc)); + and_media_data->enc = AMediaCodec_createCodecByName(enc_name); + if (!and_media_data->enc) { + PJ_LOG(4, (THIS_FILE, "Failed creating encoder: %s", enc_name)); + } + PJ_LOG(4, (THIS_FILE, "Done creating encoder: %s [0x%x]", enc_name, + and_media_data->enc)); } if (!and_media_data->dec) { - and_media_data->dec = AMediaCodec_createCodecByName(dec_name); - if (!and_media_data->dec) { - PJ_LOG(4, (THIS_FILE, "Failed creating decoder: %s", dec_name)); - } - PJ_LOG(4, (THIS_FILE, "Done creating decoder: %s [0x%x]", dec_name, - and_media_data->dec)); + and_media_data->dec = AMediaCodec_createCodecByName(dec_name); + if (!and_media_data->dec) { + PJ_LOG(4, (THIS_FILE, "Failed creating decoder: %s", dec_name)); + } + PJ_LOG(4, (THIS_FILE, "Done creating decoder: %s [0x%x]", dec_name, + and_media_data->dec)); } } @@ -725,8 +725,8 @@ static void create_codec(and_media_private_t *and_media_data) * Allocate a new codec instance. */ static pj_status_t and_media_alloc_codec(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { and_media_private_t *codec_data; pjmedia_codec *codec; @@ -742,20 +742,20 @@ static pj_status_t and_media_alloc_codec(pjmedia_codec_factory *factory, /* Find codec's index */ idx = -1; for (i = 0; i < PJ_ARRAY_SIZE(and_media_codec); ++i) { - pj_str_t name = pj_str((char*)and_media_codec[i].name); - if ((pj_stricmp(&id->encoding_name, &name) == 0) && - (id->clock_rate == (unsigned)and_media_codec[i].clock_rate) && - (id->channel_cnt == (unsigned)and_media_codec[i].channel_count) && - (and_media_codec[i].enabled)) - { - idx = i; - break; - } + pj_str_t name = pj_str((char*)and_media_codec[i].name); + if ((pj_stricmp(&id->encoding_name, &name) == 0) && + (id->clock_rate == (unsigned)and_media_codec[i].clock_rate) && + (id->channel_cnt == (unsigned)and_media_codec[i].channel_count) && + (and_media_codec[i].enabled)) + { + idx = i; + break; + } } if (idx == -1) { - *p_codec = NULL; - pj_mutex_unlock(and_media_factory.mutex); - return PJMEDIA_CODEC_EFAILED; + *p_codec = NULL; + pj_mutex_unlock(and_media_factory.mutex); + return PJMEDIA_CODEC_EFAILED; } /* Create pool for codec instance */ @@ -770,25 +770,25 @@ static pj_status_t and_media_alloc_codec(pjmedia_codec_factory *factory, /* Create PLC if codec has no internal PLC */ if (!and_media_codec[idx].has_native_plc) { - pj_status_t status; - status = pjmedia_plc_create(pool, and_media_codec[idx].clock_rate, - and_media_codec[idx].samples_per_frame, 0, - &codec_data->plc); - if (status != PJ_SUCCESS) { - goto on_error; - } + pj_status_t status; + status = pjmedia_plc_create(pool, and_media_codec[idx].clock_rate, + and_media_codec[idx].samples_per_frame, 0, + &codec_data->plc); + if (status != PJ_SUCCESS) { + goto on_error; + } } /* Create silence detector if codec has no internal VAD */ if (!and_media_codec[idx].has_native_vad) { - pj_status_t status; - status = pjmedia_silence_det_create(pool, - and_media_codec[idx].clock_rate, - and_media_codec[idx].samples_per_frame, - &codec_data->vad); - if (status != PJ_SUCCESS) { - goto on_error; - } + pj_status_t status; + status = pjmedia_silence_det_create(pool, + and_media_codec[idx].clock_rate, + and_media_codec[idx].samples_per_frame, + &codec_data->vad); + if (status != PJ_SUCCESS) { + goto on_error; + } } codec_data->pool = pool; @@ -796,7 +796,7 @@ static pj_status_t and_media_alloc_codec(pjmedia_codec_factory *factory, create_codec(codec_data); if (!codec_data->enc || !codec_data->dec) { - goto on_error; + goto on_error; } pj_mutex_unlock(and_media_factory.mutex); @@ -813,7 +813,7 @@ static pj_status_t and_media_alloc_codec(pjmedia_codec_factory *factory, * Free codec. */ static pj_status_t and_media_dealloc_codec(pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { and_media_private_t *codec_data; @@ -842,7 +842,7 @@ static pj_status_t and_media_dealloc_codec(pjmedia_codec_factory *factory, * Init codec. */ static pj_status_t and_media_codec_init(pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(pool); @@ -853,11 +853,11 @@ static pj_status_t and_media_codec_init(pjmedia_codec *codec, * Open codec. */ static pj_status_t and_media_codec_open(pjmedia_codec *codec, - pjmedia_codec_param *attr) + pjmedia_codec_param *attr) { and_media_private_t *codec_data = (and_media_private_t*) codec->codec_data; struct and_media_codec *and_media_data = - &and_media_codec[codec_data->codec_idx]; + &and_media_codec[codec_data->codec_idx]; pj_status_t status; PJ_ASSERT_RETURN(codec && attr, PJ_EINVAL); @@ -871,102 +871,102 @@ static pj_status_t and_media_codec_open(pjmedia_codec *codec, #if PJMEDIA_HAS_AND_MEDIA_AMRNB if (and_media_data->codec_id == AND_AUD_CODEC_AMRNB || - and_media_data->codec_id == AND_AUD_CODEC_AMRWB) + and_media_data->codec_id == AND_AUD_CODEC_AMRWB) { - amr_settings_t *s; - pj_uint8_t octet_align = 0; - pj_int8_t enc_mode; - unsigned i; - - enc_mode = pjmedia_codec_amr_get_mode(attr->info.avg_bps); - - pj_assert(enc_mode >= 0 && enc_mode <= 8); - - /* Check AMR specific attributes */ - for (i = 0; i < attr->setting.dec_fmtp.cnt; ++i) { - /* octet-align, one of the parameters that must have same value - * in offer & answer (RFC 4867 Section 8.3.1). Just check fmtp - * in the decoder side, since it's value is guaranteed to fulfil - * above requirement (by SDP negotiator). - */ - const pj_str_t STR_FMTP_OCTET_ALIGN = {(char *)"octet-align", 11}; - - if (pj_stricmp(&attr->setting.dec_fmtp.param[i].name, - &STR_FMTP_OCTET_ALIGN) == 0) - { - octet_align=(pj_uint8_t) - pj_strtoul(&attr->setting.dec_fmtp.param[i].val); - break; - } - } - for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { - /* mode-set, encoding mode is chosen based on local default mode - * setting: - * - if local default mode is included in the mode-set, use it - * - otherwise, find the closest mode to local default mode; - * if there are two closest modes, prefer to use the higher - * one, e.g: local default mode is 4, the mode-set param - * contains '2,3,5,6', then 5 will be chosen. - */ - const pj_str_t STR_FMTP_MODE_SET = {(char *)"mode-set", 8}; - - if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name, - &STR_FMTP_MODE_SET) == 0) - { - const char *p; - pj_size_t l; - pj_int8_t diff = 99; - - p = pj_strbuf(&attr->setting.enc_fmtp.param[i].val); - l = pj_strlen(&attr->setting.enc_fmtp.param[i].val); - - while (l--) { - if ((and_media_data->codec_id == AND_AUD_CODEC_AMRNB && - *p>='0' && *p<='7') || - (and_media_data->codec_id == AND_AUD_CODEC_AMRWB && - *p>='0' && *p<='8')) - { - pj_int8_t tmp = (pj_int8_t)(*p - '0' - enc_mode); - - if (PJ_ABS(diff) > PJ_ABS(tmp) || - (PJ_ABS(diff) == PJ_ABS(tmp) && tmp > diff)) - { - diff = tmp; - if (diff == 0) break; - } - } - ++p; - } - if (diff == 99) - goto on_error; - - enc_mode = (pj_int8_t)(enc_mode + diff); - - break; - } - } - /* Initialize AMR specific settings */ - s = PJ_POOL_ZALLOC_T(codec_data->pool, amr_settings_t); - codec_data->codec_setting = s; - - s->enc_setting.amr_nb = (pj_uint8_t) - (and_media_data->codec_id == AND_AUD_CODEC_AMRNB); - s->enc_setting.octet_aligned = octet_align; - s->enc_setting.reorder = 0; - s->enc_setting.cmr = 15; - s->dec_setting.amr_nb = (pj_uint8_t) - (and_media_data->codec_id == AND_AUD_CODEC_AMRNB); - s->dec_setting.octet_aligned = octet_align; - s->dec_setting.reorder = 0; - /* Apply encoder mode/bitrate */ - s->enc_mode = enc_mode; - - PJ_LOG(4, (THIS_FILE, "Encoder setting octet_aligned=%d reorder=%d" - " cmr=%d enc_mode=%d", - s->enc_setting.octet_aligned, s->enc_setting.reorder, - s->enc_setting.cmr, enc_mode)); - PJ_LOG(4, (THIS_FILE, "Decoder setting octet_aligned=%d reorder=%d", - s->dec_setting.octet_aligned, s->dec_setting.reorder)); + amr_settings_t *s; + pj_uint8_t octet_align = 0; + pj_int8_t enc_mode; + unsigned i; + + enc_mode = pjmedia_codec_amr_get_mode(attr->info.avg_bps); + + pj_assert(enc_mode >= 0 && enc_mode <= 8); + + /* Check AMR specific attributes */ + for (i = 0; i < attr->setting.dec_fmtp.cnt; ++i) { + /* octet-align, one of the parameters that must have same value + * in offer & answer (RFC 4867 Section 8.3.1). Just check fmtp + * in the decoder side, since it's value is guaranteed to fulfil + * above requirement (by SDP negotiator). + */ + const pj_str_t STR_FMTP_OCTET_ALIGN = {(char *)"octet-align", 11}; + + if (pj_stricmp(&attr->setting.dec_fmtp.param[i].name, + &STR_FMTP_OCTET_ALIGN) == 0) + { + octet_align=(pj_uint8_t) + pj_strtoul(&attr->setting.dec_fmtp.param[i].val); + break; + } + } + for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { + /* mode-set, encoding mode is chosen based on local default mode + * setting: + * - if local default mode is included in the mode-set, use it + * - otherwise, find the closest mode to local default mode; + * if there are two closest modes, prefer to use the higher + * one, e.g: local default mode is 4, the mode-set param + * contains '2,3,5,6', then 5 will be chosen. + */ + const pj_str_t STR_FMTP_MODE_SET = {(char *)"mode-set", 8}; + + if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name, + &STR_FMTP_MODE_SET) == 0) + { + const char *p; + pj_size_t l; + pj_int8_t diff = 99; + + p = pj_strbuf(&attr->setting.enc_fmtp.param[i].val); + l = pj_strlen(&attr->setting.enc_fmtp.param[i].val); + + while (l--) { + if ((and_media_data->codec_id == AND_AUD_CODEC_AMRNB && + *p>='0' && *p<='7') || + (and_media_data->codec_id == AND_AUD_CODEC_AMRWB && + *p>='0' && *p<='8')) + { + pj_int8_t tmp = (pj_int8_t)(*p - '0' - enc_mode); + + if (PJ_ABS(diff) > PJ_ABS(tmp) || + (PJ_ABS(diff) == PJ_ABS(tmp) && tmp > diff)) + { + diff = tmp; + if (diff == 0) break; + } + } + ++p; + } + if (diff == 99) + goto on_error; + + enc_mode = (pj_int8_t)(enc_mode + diff); + + break; + } + } + /* Initialize AMR specific settings */ + s = PJ_POOL_ZALLOC_T(codec_data->pool, amr_settings_t); + codec_data->codec_setting = s; + + s->enc_setting.amr_nb = (pj_uint8_t) + (and_media_data->codec_id == AND_AUD_CODEC_AMRNB); + s->enc_setting.octet_aligned = octet_align; + s->enc_setting.reorder = 0; + s->enc_setting.cmr = 15; + s->dec_setting.amr_nb = (pj_uint8_t) + (and_media_data->codec_id == AND_AUD_CODEC_AMRNB); + s->dec_setting.octet_aligned = octet_align; + s->dec_setting.reorder = 0; + /* Apply encoder mode/bitrate */ + s->enc_mode = enc_mode; + + PJ_LOG(4, (THIS_FILE, "Encoder setting octet_aligned=%d reorder=%d" + " cmr=%d enc_mode=%d", + s->enc_setting.octet_aligned, s->enc_setting.reorder, + s->enc_setting.cmr, enc_mode)); + PJ_LOG(4, (THIS_FILE, "Decoder setting octet_aligned=%d reorder=%d", + s->dec_setting.octet_aligned, s->dec_setting.reorder)); } #endif status = configure_codec(codec_data, PJ_TRUE); @@ -975,7 +975,7 @@ static pj_status_t and_media_codec_open(pjmedia_codec *codec, } status = configure_codec(codec_data, PJ_FALSE); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } return PJ_SUCCESS; @@ -998,7 +998,7 @@ static pj_status_t and_media_codec_close(pjmedia_codec *codec) * Modify codec settings. */ static pj_status_t and_media_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr) + const pjmedia_codec_param *attr) { and_media_private_t *codec_data = (and_media_private_t*) codec->codec_data; @@ -1012,42 +1012,42 @@ static pj_status_t and_media_codec_modify(pjmedia_codec *codec, * Get frames in the packet. */ static pj_status_t and_media_codec_parse(pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { and_media_private_t *codec_data = (and_media_private_t*) codec->codec_data; struct and_media_codec *and_media_data = - &and_media_codec[codec_data->codec_idx]; + &and_media_codec[codec_data->codec_idx]; unsigned count = 0; PJ_ASSERT_RETURN(frame_cnt, PJ_EINVAL); if (and_media_data->parse != NULL) { - return and_media_data->parse(codec_data, pkt, pkt_size, ts, frame_cnt, - frames); + return and_media_data->parse(codec_data, pkt, pkt_size, ts, frame_cnt, + frames); } while (pkt_size >= codec_data->frame_size && count < *frame_cnt) { - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = pkt; - frames[count].size = codec_data->frame_size; - frames[count].timestamp.u64 = ts->u64 + - count*and_media_data->samples_per_frame; - pkt = ((char*)pkt) + codec_data->frame_size; - pkt_size -= codec_data->frame_size; - ++count; + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = pkt; + frames[count].size = codec_data->frame_size; + frames[count].timestamp.u64 = ts->u64 + + count*and_media_data->samples_per_frame; + pkt = ((char*)pkt) + codec_data->frame_size; + pkt_size -= codec_data->frame_size; + ++count; } if (pkt_size && count < *frame_cnt) { - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = pkt; - frames[count].size = pkt_size; - frames[count].timestamp.u64 = ts->u64 + - count*and_media_data->samples_per_frame; - ++count; + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = pkt; + frames[count].size = pkt_size; + frames[count].timestamp.u64 = ts->u64 + + count*and_media_data->samples_per_frame; + ++count; } *frame_cnt = count; @@ -1058,13 +1058,13 @@ static pj_status_t and_media_codec_parse(pjmedia_codec *codec, * Encode frames. */ static pj_status_t and_media_codec_encode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { and_media_private_t *codec_data = (and_media_private_t*) codec->codec_data; struct and_media_codec *and_media_data = - &and_media_codec[codec_data->codec_idx]; + &and_media_codec[codec_data->codec_idx]; unsigned samples_per_frame; unsigned nsamples; unsigned nframes; @@ -1074,36 +1074,36 @@ static pj_status_t and_media_codec_encode(pjmedia_codec *codec, /* Invoke external VAD if codec has no internal VAD */ if (codec_data->vad && codec_data->vad_enabled) { - pj_bool_t is_silence; - pj_int32_t silence_duration; - - silence_duration = pj_timestamp_diff32(&codec_data->last_tx, - &input->timestamp); - - is_silence = pjmedia_silence_det_detect(codec_data->vad, - (const pj_int16_t*) input->buf, - (input->size >> 1), - NULL); - if (is_silence && - (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || - silence_duration < (PJMEDIA_CODEC_MAX_SILENCE_PERIOD * - (int)and_media_data->clock_rate / 1000))) - { - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->buf = NULL; - output->size = 0; - output->timestamp = input->timestamp; - return PJ_SUCCESS; - } else { - codec_data->last_tx = input->timestamp; - } + pj_bool_t is_silence; + pj_int32_t silence_duration; + + silence_duration = pj_timestamp_diff32(&codec_data->last_tx, + &input->timestamp); + + is_silence = pjmedia_silence_det_detect(codec_data->vad, + (const pj_int16_t*) input->buf, + (input->size >> 1), + NULL); + if (is_silence && + (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || + silence_duration < (PJMEDIA_CODEC_MAX_SILENCE_PERIOD * + (int)and_media_data->clock_rate / 1000))) + { + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->buf = NULL; + output->size = 0; + output->timestamp = input->timestamp; + return PJ_SUCCESS; + } else { + codec_data->last_tx = input->timestamp; + } } nsamples = input->size >> 1; samples_per_frame = and_media_data->samples_per_frame; nframes = nsamples / samples_per_frame; PJ_ASSERT_RETURN(nsamples % samples_per_frame == 0, - PJMEDIA_CODEC_EPCMFRMINLEN); + PJMEDIA_CODEC_EPCMFRMINLEN); /* Encode the frames */ while (nsamples >= samples_per_frame) { @@ -1114,58 +1114,58 @@ static pj_status_t and_media_codec_encode(pjmedia_codec *codec, AMediaCodecBufferInfo buf_info; buf_idx = AMediaCodec_dequeueInputBuffer(codec_data->enc, - CODEC_DEQUEUE_TIMEOUT); + CODEC_DEQUEUE_TIMEOUT); if (buf_idx >= 0) { - media_status_t am_status; - pj_size_t output_size; + media_status_t am_status; + pj_size_t output_size; unsigned input_size = samples_per_frame << 1; - pj_uint8_t *input_buf = AMediaCodec_getInputBuffer(codec_data->enc, - buf_idx, &output_size); - - if (input_buf && output_size >= input_size) { - pj_memcpy(input_buf, pcm_in, input_size); - - am_status = AMediaCodec_queueInputBuffer(codec_data->enc, - buf_idx, 0, input_size, 0, 0); - if (am_status != AMEDIA_OK) { - PJ_LOG(4, (THIS_FILE, "Encoder queueInputBuffer return %d", - am_status)); - goto on_return; - } - } else { - if (!input_buf) { - PJ_LOG(4,(THIS_FILE, "Encoder getInputBuffer " - "returns no input buff")); - } else { - PJ_LOG(4,(THIS_FILE, "Encoder getInputBuffer " - "size: %d, expecting %d.", - input_buf, output_size, input_size)); - } - goto on_return; - } + pj_uint8_t *input_buf = AMediaCodec_getInputBuffer(codec_data->enc, + buf_idx, &output_size); + + if (input_buf && output_size >= input_size) { + pj_memcpy(input_buf, pcm_in, input_size); + + am_status = AMediaCodec_queueInputBuffer(codec_data->enc, + buf_idx, 0, input_size, 0, 0); + if (am_status != AMEDIA_OK) { + PJ_LOG(4, (THIS_FILE, "Encoder queueInputBuffer return %d", + am_status)); + goto on_return; + } + } else { + if (!input_buf) { + PJ_LOG(4,(THIS_FILE, "Encoder getInputBuffer " + "returns no input buff")); + } else { + PJ_LOG(4,(THIS_FILE, "Encoder getInputBuffer " + "size: %d, expecting %d.", + input_buf, output_size, input_size)); + } + goto on_return; + } } else { - PJ_LOG(4,(THIS_FILE, "Encoder dequeueInputBuffer failed[%d]", + PJ_LOG(4,(THIS_FILE, "Encoder dequeueInputBuffer failed[%d]", buf_idx)); - goto on_return; + goto on_return; } for (i = 0; i < CODEC_WAIT_RETRY; ++i) { - buf_idx = AMediaCodec_dequeueOutputBuffer(codec_data->enc, - &buf_info, - CODEC_DEQUEUE_TIMEOUT); - if (buf_idx == -1) { - /* Timeout, wait until output buffer is availble. */ - pj_thread_sleep(CODEC_THREAD_WAIT); - } else { - break; - } + buf_idx = AMediaCodec_dequeueOutputBuffer(codec_data->enc, + &buf_info, + CODEC_DEQUEUE_TIMEOUT); + if (buf_idx == -1) { + /* Timeout, wait until output buffer is availble. */ + pj_thread_sleep(CODEC_THREAD_WAIT); + } else { + break; + } } if (buf_idx < 0) { - PJ_LOG(4, (THIS_FILE, "Encoder dequeueOutputBuffer failed %d", - buf_idx)); + PJ_LOG(4, (THIS_FILE, "Encoder dequeueOutputBuffer failed %d", + buf_idx)); goto on_return; } @@ -1185,20 +1185,20 @@ static pj_status_t and_media_codec_encode(pjmedia_codec *codec, 0); bits_out += buf_info.size; tx += buf_info.size; - pcm_in += samples_per_frame; - nsamples -= samples_per_frame; + pcm_in += samples_per_frame; + nsamples -= samples_per_frame; } if (and_media_data->pack != NULL) { - and_media_data->pack(codec_data, nframes, output->buf, &tx, - output_buf_len); + and_media_data->pack(codec_data, nframes, output->buf, &tx, + output_buf_len); } /* Check if we don't need to transmit the frame (DTX) */ if (tx == 0) { - output->buf = NULL; - output->size = 0; - output->timestamp.u64 = input->timestamp.u64; - output->type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; + output->buf = NULL; + output->size = 0; + output->timestamp.u64 = input->timestamp.u64; + output->type = PJMEDIA_FRAME_TYPE_NONE; + return PJ_SUCCESS; } output->size = tx; output->type = PJMEDIA_FRAME_TYPE_AUDIO; @@ -1218,13 +1218,13 @@ static pj_status_t and_media_codec_encode(pjmedia_codec *codec, * Decode frame. */ static pj_status_t and_media_codec_decode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { and_media_private_t *codec_data = (and_media_private_t*) codec->codec_data; struct and_media_codec *and_media_data = - &and_media_codec[codec_data->codec_idx]; + &and_media_codec[codec_data->codec_idx]; unsigned samples_per_frame; unsigned i; @@ -1241,95 +1241,95 @@ static pj_status_t and_media_codec_decode(pjmedia_codec *codec, samples_per_frame = and_media_data->samples_per_frame; PJ_ASSERT_RETURN(output_buf_len >= samples_per_frame << 1, - PJMEDIA_CODEC_EPCMTOOSHORT); + PJMEDIA_CODEC_EPCMTOOSHORT); if (input->type != PJMEDIA_FRAME_TYPE_AUDIO) { - goto on_return; + goto on_return; } buf_idx = AMediaCodec_dequeueInputBuffer(codec_data->dec, - CODEC_DEQUEUE_TIMEOUT); + CODEC_DEQUEUE_TIMEOUT); if (buf_idx < 0) { - PJ_LOG(4,(THIS_FILE, "Decoder dequeueInputBuffer failed return %d", - buf_idx)); - goto on_return; + PJ_LOG(4,(THIS_FILE, "Decoder dequeueInputBuffer failed return %d", + buf_idx)); + goto on_return; } input_buf = AMediaCodec_getInputBuffer(codec_data->dec, - buf_idx, - &input_size); + buf_idx, + &input_size); if (input_buf == 0) { - PJ_LOG(4,(THIS_FILE, "Decoder getInputBuffer failed " - "return input_buf=%d, size=%d", input_buf, input_size)); - goto on_return; + PJ_LOG(4,(THIS_FILE, "Decoder getInputBuffer failed " + "return input_buf=%d, size=%d", input_buf, input_size)); + goto on_return; } if (and_media_data->predecode) { - input_.buf = input_buf; - and_media_data->predecode(codec_data, input, &input_); + input_.buf = input_buf; + and_media_data->predecode(codec_data, input, &input_); } else { - input_.size = input->size; - pj_memcpy(input_buf, input->buf, input->size); + input_.size = input->size; + pj_memcpy(input_buf, input->buf, input->size); } am_status = AMediaCodec_queueInputBuffer(codec_data->dec, - buf_idx, - 0, - input_.size, - input->timestamp.u32.lo, - 0); + buf_idx, + 0, + input_.size, + input->timestamp.u32.lo, + 0); if (am_status != AMEDIA_OK) { - PJ_LOG(4,(THIS_FILE, "Decoder queueInputBuffer failed return %d", - am_status)); - goto on_return; + PJ_LOG(4,(THIS_FILE, "Decoder queueInputBuffer failed return %d", + am_status)); + goto on_return; } for (i = 0; i < CODEC_WAIT_RETRY; ++i) { - buf_idx = AMediaCodec_dequeueOutputBuffer(codec_data->dec, - &buf_info, - CODEC_DEQUEUE_TIMEOUT); - if (buf_idx == -1) { - /* Timeout, wait until output buffer is availble. */ - PJ_LOG(5, (THIS_FILE, "Decoder dequeueOutputBuffer timeout[%d]", - i+1)); - pj_thread_sleep(CODEC_THREAD_WAIT); - } else { - break; - } + buf_idx = AMediaCodec_dequeueOutputBuffer(codec_data->dec, + &buf_info, + CODEC_DEQUEUE_TIMEOUT); + if (buf_idx == -1) { + /* Timeout, wait until output buffer is availble. */ + PJ_LOG(5, (THIS_FILE, "Decoder dequeueOutputBuffer timeout[%d]", + i+1)); + pj_thread_sleep(CODEC_THREAD_WAIT); + } else { + break; + } } if (buf_idx < 0) { - PJ_LOG(5, (THIS_FILE, "Decoder dequeueOutputBuffer failed [%d]", - buf_idx)); - goto on_return; + PJ_LOG(5, (THIS_FILE, "Decoder dequeueOutputBuffer failed [%d]", + buf_idx)); + goto on_return; } output_buf = AMediaCodec_getOutputBuffer(codec_data->dec, - buf_idx, - &output_size); + buf_idx, + &output_size); if (output_buf == NULL) { - am_status = AMediaCodec_releaseOutputBuffer(codec_data->dec, - buf_idx, - 0); - if (am_status != AMEDIA_OK) { - PJ_LOG(4,(THIS_FILE, "Decoder releaseOutputBuffer failed %d", - am_status)); - } - PJ_LOG(4,(THIS_FILE, "Decoder getOutputBuffer failed")); - goto on_return; + am_status = AMediaCodec_releaseOutputBuffer(codec_data->dec, + buf_idx, + 0); + if (am_status != AMEDIA_OK) { + PJ_LOG(4,(THIS_FILE, "Decoder releaseOutputBuffer failed %d", + am_status)); + } + PJ_LOG(4,(THIS_FILE, "Decoder getOutputBuffer failed")); + goto on_return; } pj_memcpy(output->buf, output_buf, buf_info.size); output->type = PJMEDIA_FRAME_TYPE_AUDIO; output->size = buf_info.size; output->timestamp.u64 = input->timestamp.u64; am_status = AMediaCodec_releaseOutputBuffer(codec_data->dec, - buf_idx, - 0); + buf_idx, + 0); /* Invoke external PLC if codec has no internal PLC */ if (codec_data->plc && codec_data->plc_enabled) - pjmedia_plc_save(codec_data->plc, (pj_int16_t*)output->buf); + pjmedia_plc_save(codec_data->plc, (pj_int16_t*)output->buf); return PJ_SUCCESS; @@ -1345,12 +1345,12 @@ static pj_status_t and_media_codec_decode(pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t and_media_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { and_media_private_t *codec_data = (and_media_private_t*) codec->codec_data; struct and_media_codec *and_media_data = - &and_media_codec[codec_data->codec_idx]; + &and_media_codec[codec_data->codec_idx]; unsigned samples_per_frame; pj_bool_t generate_plc = (codec_data->plc_enabled && codec_data->plc); @@ -1361,13 +1361,13 @@ static pj_status_t and_media_codec_recover(pjmedia_codec *codec, output->size = samples_per_frame << 1; if (generate_plc) - pjmedia_plc_generate(codec_data->plc, (pj_int16_t*)output->buf); + pjmedia_plc_generate(codec_data->plc, (pj_int16_t*)output->buf); else - pjmedia_zero_samples((pj_int16_t*)output->buf, samples_per_frame); + pjmedia_zero_samples((pj_int16_t*)output->buf, samples_per_frame); return PJ_SUCCESS; } -#endif /* PJMEDIA_HAS_ANDROID_MEDIACODEC */ +#endif /* PJMEDIA_HAS_ANDROID_MEDIACODEC */ diff --git a/pjmedia/src/pjmedia-codec/and_vid_mediacodec.cpp b/pjmedia/src/pjmedia-codec/and_vid_mediacodec.cpp index 5da5fb620c..cf1f90d50d 100644 --- a/pjmedia/src/pjmedia-codec/and_vid_mediacodec.cpp +++ b/pjmedia/src/pjmedia-codec/and_vid_mediacodec.cpp @@ -33,7 +33,7 @@ /* * Constants */ -#define THIS_FILE "and_vid_mediacodec.cpp" +#define THIS_FILE "and_vid_mediacodec.cpp" #define AND_MEDIA_KEY_COLOR_FMT "color-format" #define AND_MEDIA_KEY_WIDTH "width" #define AND_MEDIA_KEY_HEIGHT "height" @@ -43,38 +43,38 @@ #define AND_MEDIA_KEY_IFR_INTTERVAL "i-frame-interval" #define AND_MEDIA_KEY_MIME "mime" #define AND_MEDIA_KEY_REQUEST_SYNCF "request-sync" -#define AND_MEDIA_KEY_CSD0 "csd-0" -#define AND_MEDIA_KEY_CSD1 "csd-1" +#define AND_MEDIA_KEY_CSD0 "csd-0" +#define AND_MEDIA_KEY_CSD1 "csd-1" #define AND_MEDIA_KEY_MAX_INPUT_SZ "max-input-size" -#define AND_MEDIA_KEY_ENCODER "encoder" -#define AND_MEDIA_KEY_PRIORITY "priority" -#define AND_MEDIA_KEY_STRIDE "stride" +#define AND_MEDIA_KEY_ENCODER "encoder" +#define AND_MEDIA_KEY_PRIORITY "priority" +#define AND_MEDIA_KEY_STRIDE "stride" #define AND_MEDIA_I420_PLANAR_FMT 0x13 #define AND_MEDIA_QUEUE_TIMEOUT 2000*100 -#define DEFAULT_WIDTH 352 -#define DEFAULT_HEIGHT 288 +#define DEFAULT_WIDTH 352 +#define DEFAULT_HEIGHT 288 -#define DEFAULT_FPS 15 -#define DEFAULT_AVG_BITRATE 256000 -#define DEFAULT_MAX_BITRATE 256000 +#define DEFAULT_FPS 15 +#define DEFAULT_AVG_BITRATE 256000 +#define DEFAULT_MAX_BITRATE 256000 -#define SPS_PPS_BUF_SIZE 64 +#define SPS_PPS_BUF_SIZE 64 -#define MAX_RX_WIDTH 1200 -#define MAX_RX_HEIGHT 800 +#define MAX_RX_WIDTH 1200 +#define MAX_RX_HEIGHT 800 /* Maximum duration from one key frame to the next (in seconds). */ -#define KEYFRAME_INTERVAL 1 +#define KEYFRAME_INTERVAL 1 -#define CODEC_WAIT_RETRY 10 -#define CODEC_THREAD_WAIT 10 +#define CODEC_WAIT_RETRY 10 +#define CODEC_THREAD_WAIT 10 /* Timeout until the buffer is ready in ms. */ -#define CODEC_DEQUEUE_TIMEOUT 20 +#define CODEC_DEQUEUE_TIMEOUT 20 -#define AND_MED_H264_PT PJMEDIA_RTP_PT_H264_RSV2 -#define AND_MED_VP8_PT PJMEDIA_RTP_PT_VP8_RSV1 -#define AND_MED_VP9_PT PJMEDIA_RTP_PT_VP9_RSV1 +#define AND_MED_H264_PT PJMEDIA_RTP_PT_H264_RSV2 +#define AND_MED_VP8_PT PJMEDIA_RTP_PT_VP8_RSV1 +#define AND_MED_VP9_PT PJMEDIA_RTP_PT_VP9_RSV1 /* * Factory operations. @@ -149,9 +149,9 @@ static pjmedia_vid_codec_factory_op and_media_factory_op = static struct and_media_factory { pjmedia_vid_codec_factory base; - pjmedia_vid_codec_mgr *mgr; + pjmedia_vid_codec_mgr *mgr; pj_pool_factory *pf; - pj_pool_t *pool; + pj_pool_t *pool; } and_media_factory; enum and_media_frm_type { @@ -161,49 +161,49 @@ enum and_media_frm_type { }; typedef struct h264_codec_data { - pjmedia_h264_packetizer *pktz; + pjmedia_h264_packetizer *pktz; - pj_uint8_t enc_sps_pps_buf[SPS_PPS_BUF_SIZE]; - unsigned enc_sps_pps_len; - pj_bool_t enc_sps_pps_ex; + pj_uint8_t enc_sps_pps_buf[SPS_PPS_BUF_SIZE]; + unsigned enc_sps_pps_len; + pj_bool_t enc_sps_pps_ex; - pj_uint8_t *dec_sps_buf; - unsigned dec_sps_len; - pj_uint8_t *dec_pps_buf; - unsigned dec_pps_len; + pj_uint8_t *dec_sps_buf; + unsigned dec_sps_len; + pj_uint8_t *dec_pps_buf; + unsigned dec_pps_len; } h264_codec_data; typedef struct vpx_codec_data { - pjmedia_vpx_packetizer *pktz; + pjmedia_vpx_packetizer *pktz; } vpx_codec_data; typedef struct and_media_codec_data { - pj_pool_t *pool; + pj_pool_t *pool; pj_uint8_t codec_idx; - pjmedia_vid_codec_param *prm; - pj_bool_t whole; + pjmedia_vid_codec_param *prm; + pj_bool_t whole; void *ex_data; /* Encoder state */ AMediaCodec *enc; - unsigned enc_input_size; - pj_uint8_t *enc_frame_whole; - unsigned enc_frame_size; - unsigned enc_processed; + unsigned enc_input_size; + pj_uint8_t *enc_frame_whole; + unsigned enc_frame_size; + unsigned enc_processed; AMediaCodecBufferInfo enc_buf_info; - int enc_output_buf_idx; + int enc_output_buf_idx; /* Decoder state */ AMediaCodec *dec; - pj_uint8_t *dec_buf; - pj_uint8_t *dec_input_buf; - unsigned dec_input_buf_len; - pj_size_t dec_input_buf_max_size; - pj_ssize_t dec_input_buf_idx; - unsigned dec_has_output_frame; - unsigned dec_stride_len; - unsigned dec_buf_size; + pj_uint8_t *dec_buf; + pj_uint8_t *dec_input_buf; + unsigned dec_input_buf_len; + pj_size_t dec_input_buf_max_size; + pj_ssize_t dec_input_buf_idx; + unsigned dec_has_output_frame; + unsigned dec_stride_len; + unsigned dec_buf_size; AMediaCodecBufferInfo dec_buf_info; } and_media_codec_data; @@ -266,48 +266,48 @@ static pj_status_t decode_vpx(pjmedia_vid_codec *codec, #if PJMEDIA_HAS_AND_MEDIA_H264 static pj_str_t H264_sw_encoder[] = {{(char *)"OMX.google.h264.encoder\0", - 23}}; + 23}}; static pj_str_t H264_hw_encoder[] = - {{(char *)"OMX.qcom.video.encoder.avc\0", 26}, - {(char *)"OMX.Exynos.avc.Encoder\0", 22}}; + {{(char *)"OMX.qcom.video.encoder.avc\0", 26}, + {(char *)"OMX.Exynos.avc.Encoder\0", 22}}; static pj_str_t H264_sw_decoder[] = {{(char *)"OMX.google.h264.decoder\0", - 23}}; + 23}}; static pj_str_t H264_hw_decoder[] = - {{(char *)"OMX.qcom.video.decoder.avc\0", 26}, - {(char *)"OMX.Exynos.avc.dec\0", 18}}; + {{(char *)"OMX.qcom.video.decoder.avc\0", 26}, + {(char *)"OMX.Exynos.avc.dec\0", 18}}; #endif #if PJMEDIA_HAS_AND_MEDIA_VP8 static pj_str_t VP8_sw_encoder[] = {{(char *)"OMX.google.vp8.encoder\0", 23}}; static pj_str_t VP8_hw_encoder[] = - {{(char *)"OMX.qcom.video.encoder.vp8\0", 26}, - {(char *)"OMX.Exynos.vp8.Encoder\0", 22}}; + {{(char *)"OMX.qcom.video.encoder.vp8\0", 26}, + {(char *)"OMX.Exynos.vp8.Encoder\0", 22}}; static pj_str_t VP8_sw_decoder[] = {{(char *)"OMX.google.vp8.decoder\0", 23}}; static pj_str_t VP8_hw_decoder[] = - {{(char *)"OMX.qcom.video.decoder.vp8\0", 26}, - {(char *)"OMX.Exynos.vp8.dec\0", 18}}; + {{(char *)"OMX.qcom.video.decoder.vp8\0", 26}, + {(char *)"OMX.Exynos.vp8.dec\0", 18}}; #endif #if PJMEDIA_HAS_AND_MEDIA_VP9 static pj_str_t VP9_sw_encoder[] = {{(char *)"OMX.google.vp9.encoder\0", 23}}; static pj_str_t VP9_hw_encoder[] = - {{(char *)"OMX.qcom.video.encoder.vp9\0", 26}, - {(char *)"OMX.Exynos.vp9.Encoder\0", 22}}; + {{(char *)"OMX.qcom.video.encoder.vp9\0", 26}, + {(char *)"OMX.Exynos.vp9.Encoder\0", 22}}; static pj_str_t VP9_sw_decoder[] = {{(char *)"OMX.google.vp9.decoder\0", 23}}; static pj_str_t VP9_hw_decoder[] = - {{(char *)"OMX.qcom.video.decoder.vp9\0", 26}, - {(char *)"OMX.Exynos.vp9.dec\0", 18}}; + {{(char *)"OMX.qcom.video.decoder.vp9\0", 26}, + {(char *)"OMX.Exynos.vp9.dec\0", 18}}; #endif static struct and_media_codec { - int enabled; /* Is this codec enabled? */ - const char *name; /* Codec name. */ + int enabled; /* Is this codec enabled? */ + const char *name; /* Codec name. */ const char *description; /* Codec description. */ const char *mime_type; /* Mime type. */ pj_str_t *encoder_name; /* Encoder name. */ pj_str_t *decoder_name; /* Decoder name. */ - pj_uint8_t pt; /* Payload type. */ - pjmedia_format_id fmt_id; /* Format id. */ + pj_uint8_t pt; /* Payload type. */ + pjmedia_format_id fmt_id; /* Format id. */ pj_uint8_t keyframe_interval; /* Keyframe interval. */ open_cb open_codec; @@ -315,11 +315,11 @@ static struct and_media_codec { encode_more_cb encode_more; decode_cb decode; - pjmedia_codec_fmtp dec_fmtp; /* Decoder's fmtp params. */ + pjmedia_codec_fmtp dec_fmtp; /* Decoder's fmtp params. */ } and_media_codec[] = { #if PJMEDIA_HAS_AND_MEDIA_H264 - {0, "H264", "Android MediaCodec H264 codec", "video/avc", + {0, "H264", "Android MediaCodec H264 codec", "video/avc", NULL, NULL, AND_MED_H264_PT, PJMEDIA_FORMAT_H264, KEYFRAME_INTERVAL, &open_h264, &process_encode_h264, &encode_more_h264, &decode_h264, @@ -329,7 +329,7 @@ and_media_codec[] = { }, #endif #if PJMEDIA_HAS_AND_MEDIA_VP8 - {0, "VP8", "Android MediaCodec VP8 codec", "video/x-vnd.on2.vp8", + {0, "VP8", "Android MediaCodec VP8 codec", "video/x-vnd.on2.vp8", NULL, NULL, AND_MED_VP8_PT, PJMEDIA_FORMAT_VP8, KEYFRAME_INTERVAL, &open_vpx, NULL, &encode_more_vpx, &decode_vpx, @@ -339,9 +339,9 @@ and_media_codec[] = { }, #endif #if PJMEDIA_HAS_AND_MEDIA_VP9 - {0, "VP9", "Android MediaCodec VP9 codec", "video/x-vnd.on2.vp9", - NULL, NULL, - AND_MED_VP9_PT, PJMEDIA_FORMAT_VP9, KEYFRAME_INTERVAL, + {0, "VP9", "Android MediaCodec VP9 codec", "video/x-vnd.on2.vp9", + NULL, NULL, + AND_MED_VP9_PT, PJMEDIA_FORMAT_VP9, KEYFRAME_INTERVAL, &open_vpx, NULL, &encode_more_vpx, &decode_vpx, {2, {{{(char *)"max-fr", 6}, {(char *)"30", 2}}, {{(char *)" max-fs", 7}, {(char *)"580", 3}}} @@ -358,23 +358,23 @@ static pj_status_t configure_encoder(and_media_codec_data *and_media_data) vid_fmt = AMediaFormat_new(); if (!vid_fmt) { - PJ_LOG(4, (THIS_FILE, "Encoder failed creating media format")); + PJ_LOG(4, (THIS_FILE, "Encoder failed creating media format")); return PJ_ENOMEM; } AMediaFormat_setString(vid_fmt, AND_MEDIA_KEY_MIME, and_media_codec[and_media_data->codec_idx].mime_type); AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_COLOR_FMT, - AND_MEDIA_I420_PLANAR_FMT); + AND_MEDIA_I420_PLANAR_FMT); AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_HEIGHT, - param->enc_fmt.det.vid.size.h); + param->enc_fmt.det.vid.size.h); AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_WIDTH, param->enc_fmt.det.vid.size.w); AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_BIT_RATE, param->enc_fmt.det.vid.avg_bps); //AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_PROFILE, 1); AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_IFR_INTTERVAL, - KEYFRAME_INTERVAL); + KEYFRAME_INTERVAL); AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_FRAME_RATE, (param->enc_fmt.det.vid.fps.num / param->enc_fmt.det.vid.fps.denum)); @@ -386,14 +386,14 @@ static pj_status_t configure_encoder(and_media_codec_data *and_media_data) AMediaFormat_delete(vid_fmt); if (am_status != AMEDIA_OK) { PJ_LOG(4, (THIS_FILE, "Encoder configure failed, status=%d", - am_status)); + am_status)); return PJMEDIA_CODEC_EFAILED; } am_status = AMediaCodec_start(and_media_data->enc); if (am_status != AMEDIA_OK) { - PJ_LOG(4, (THIS_FILE, "Encoder start failed, status=%d", - am_status)); - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(4, (THIS_FILE, "Encoder start failed, status=%d", + am_status)); + return PJMEDIA_CODEC_EFAILED; } return PJ_SUCCESS; } @@ -404,64 +404,64 @@ static pj_status_t configure_decoder(and_media_codec_data *and_media_data) { vid_fmt = AMediaFormat_new(); if (!vid_fmt) { - PJ_LOG(4, (THIS_FILE, "Decoder failed creating media format")); + PJ_LOG(4, (THIS_FILE, "Decoder failed creating media format")); return PJ_ENOMEM; } AMediaFormat_setString(vid_fmt, AND_MEDIA_KEY_MIME, and_media_codec[and_media_data->codec_idx].mime_type); AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_COLOR_FMT, - AND_MEDIA_I420_PLANAR_FMT); + AND_MEDIA_I420_PLANAR_FMT); AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_HEIGHT, - and_media_data->prm->dec_fmt.det.vid.size.h); + and_media_data->prm->dec_fmt.det.vid.size.h); AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_WIDTH, - and_media_data->prm->dec_fmt.det.vid.size.w); + and_media_data->prm->dec_fmt.det.vid.size.w); AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_MAX_INPUT_SZ, 0); AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_ENCODER, 0); AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_PRIORITY, 0); if (and_media_data->prm->dec_fmt.id == PJMEDIA_FORMAT_H264) { - h264_codec_data *h264_data = (h264_codec_data *)and_media_data->ex_data; - - if (h264_data->dec_sps_len) { - AMediaFormat_setBuffer(vid_fmt, AND_MEDIA_KEY_CSD0, - h264_data->dec_sps_buf, - h264_data->dec_sps_len); - } - if (h264_data->dec_pps_len) { - AMediaFormat_setBuffer(vid_fmt, AND_MEDIA_KEY_CSD1, - h264_data->dec_pps_buf, - h264_data->dec_pps_len); - } + h264_codec_data *h264_data = (h264_codec_data *)and_media_data->ex_data; + + if (h264_data->dec_sps_len) { + AMediaFormat_setBuffer(vid_fmt, AND_MEDIA_KEY_CSD0, + h264_data->dec_sps_buf, + h264_data->dec_sps_len); + } + if (h264_data->dec_pps_len) { + AMediaFormat_setBuffer(vid_fmt, AND_MEDIA_KEY_CSD1, + h264_data->dec_pps_buf, + h264_data->dec_pps_len); + } } am_status = AMediaCodec_configure(and_media_data->dec, vid_fmt, NULL, - NULL, 0); + NULL, 0); AMediaFormat_delete(vid_fmt); if (am_status != AMEDIA_OK) { PJ_LOG(4, (THIS_FILE, "Decoder configure failed, status=%d, fmt_id=%d", - am_status, and_media_data->prm->dec_fmt.id)); + am_status, and_media_data->prm->dec_fmt.id)); return PJMEDIA_CODEC_EFAILED; } am_status = AMediaCodec_start(and_media_data->dec); if (am_status != AMEDIA_OK) { - PJ_LOG(4, (THIS_FILE, "Decoder start failed, status=%d", - am_status)); - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(4, (THIS_FILE, "Decoder start failed, status=%d", + am_status)); + return PJMEDIA_CODEC_EFAILED; } return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_codec_and_media_vid_init( - pjmedia_vid_codec_mgr *mgr, + pjmedia_vid_codec_mgr *mgr, pj_pool_factory *pf) { const pj_str_t h264_name = { (char*)"H264", 4}; pj_status_t status; if (and_media_factory.pool != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } if (!mgr) mgr = pjmedia_vid_codec_mgr_instance(); @@ -473,24 +473,24 @@ PJ_DEF(pj_status_t) pjmedia_codec_and_media_vid_init( and_media_factory.mgr = mgr; and_media_factory.pf = pf; and_media_factory.pool = pj_pool_create(pf, "and_media_vid_factory", - 256, 256, NULL); + 256, 256, NULL); if (!and_media_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; #if PJMEDIA_HAS_AND_MEDIA_H264 /* Registering format match for SDP negotiation */ status = pjmedia_sdp_neg_register_fmt_match_cb( - &h264_name, - &pjmedia_vid_codec_h264_match_sdp); + &h264_name, + &pjmedia_vid_codec_h264_match_sdp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #endif /* Register codec factory to codec manager. */ status = pjmedia_vid_codec_mgr_register_factory(mgr, - &and_media_factory.base); + &and_media_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; PJ_LOG(4,(THIS_FILE, "Android AMediaCodec initialized")); @@ -511,13 +511,13 @@ PJ_DEF(pj_status_t) pjmedia_codec_and_media_vid_deinit(void) pj_status_t status = PJ_SUCCESS; if (and_media_factory.pool == NULL) { - /* Already deinitialized */ - return PJ_SUCCESS; + /* Already deinitialized */ + return PJ_SUCCESS; } /* Unregister Android AMediaCodec factory. */ status = pjmedia_vid_codec_mgr_unregister_factory(and_media_factory.mgr, - &and_media_factory.base); + &and_media_factory.base); /* Destroy pool. */ pj_pool_release(and_media_factory.pool); @@ -598,9 +598,9 @@ static pj_bool_t codec_exists(const pj_str_t *codec_name) codec = AMediaCodec_createCodecByName(codec_txt); if (!codec) { - PJ_LOG(4, (THIS_FILE, "Failed creating codec : %.*s", codec_name->slen, - codec_name->ptr)); - return PJ_FALSE; + PJ_LOG(4, (THIS_FILE, "Failed creating codec : %.*s", codec_name->slen, + codec_name->ptr)); + return PJ_FALSE; } AMediaCodec_delete(codec); @@ -608,7 +608,7 @@ static pj_bool_t codec_exists(const pj_str_t *codec_name) } void add_codec(struct and_media_codec *codec, - unsigned *count, pjmedia_vid_codec_info *info) + unsigned *count, pjmedia_vid_codec_info *info) { info[*count].fmt_id = codec->fmt_id; info[*count].pt = codec->pt; @@ -631,10 +631,10 @@ void add_codec(struct and_media_codec *codec, } static void get_codec_name(pj_bool_t is_enc, - pj_bool_t prio, - pjmedia_format_id fmt_id, - pj_str_t **codec_name, - unsigned *codec_num) + pj_bool_t prio, + pjmedia_format_id fmt_id, + pj_str_t **codec_name, + unsigned *codec_num) { pj_bool_t use_sw_enc = PJMEDIA_AND_MEDIA_PRIO_SW_VID_ENC; pj_bool_t use_sw_dec = PJMEDIA_AND_MEDIA_PRIO_SW_VID_DEC; @@ -645,69 +645,69 @@ static void get_codec_name(pj_bool_t is_enc, #if PJMEDIA_HAS_AND_MEDIA_H264 case PJMEDIA_FORMAT_H264: - if (is_enc) { - if ((prio && use_sw_enc) || (!prio && !use_sw_enc)) { - *codec_name = &H264_sw_encoder[0]; - *codec_num = PJ_ARRAY_SIZE(H264_sw_encoder); - } else { - *codec_name = &H264_hw_encoder[0]; - *codec_num = PJ_ARRAY_SIZE(H264_hw_encoder); - } - } else { - if ((prio && use_sw_dec) || (!prio && !use_sw_dec)) { - *codec_name = &H264_sw_decoder[0]; - *codec_num = PJ_ARRAY_SIZE(H264_sw_decoder); - } else { - *codec_name = &H264_hw_decoder[0]; - *codec_num = PJ_ARRAY_SIZE(H264_hw_decoder); - } - } - break; + if (is_enc) { + if ((prio && use_sw_enc) || (!prio && !use_sw_enc)) { + *codec_name = &H264_sw_encoder[0]; + *codec_num = PJ_ARRAY_SIZE(H264_sw_encoder); + } else { + *codec_name = &H264_hw_encoder[0]; + *codec_num = PJ_ARRAY_SIZE(H264_hw_encoder); + } + } else { + if ((prio && use_sw_dec) || (!prio && !use_sw_dec)) { + *codec_name = &H264_sw_decoder[0]; + *codec_num = PJ_ARRAY_SIZE(H264_sw_decoder); + } else { + *codec_name = &H264_hw_decoder[0]; + *codec_num = PJ_ARRAY_SIZE(H264_hw_decoder); + } + } + break; #endif #if PJMEDIA_HAS_AND_MEDIA_VP8 case PJMEDIA_FORMAT_VP8: - if (is_enc) { - if ((prio && use_sw_enc) || (!prio && !use_sw_enc)) { - *codec_name = &VP8_sw_encoder[0]; - *codec_num = PJ_ARRAY_SIZE(VP8_sw_encoder); - } else { - *codec_name = &VP8_hw_encoder[0]; - *codec_num = PJ_ARRAY_SIZE(VP8_hw_encoder); - } - } else { - if ((prio && use_sw_dec) || (!prio && !use_sw_dec)) { - *codec_name = &VP8_sw_decoder[0]; - *codec_num = PJ_ARRAY_SIZE(VP8_sw_decoder); - } else { - *codec_name = &VP8_hw_decoder[0]; - *codec_num = PJ_ARRAY_SIZE(VP8_hw_decoder); - } - } - break; + if (is_enc) { + if ((prio && use_sw_enc) || (!prio && !use_sw_enc)) { + *codec_name = &VP8_sw_encoder[0]; + *codec_num = PJ_ARRAY_SIZE(VP8_sw_encoder); + } else { + *codec_name = &VP8_hw_encoder[0]; + *codec_num = PJ_ARRAY_SIZE(VP8_hw_encoder); + } + } else { + if ((prio && use_sw_dec) || (!prio && !use_sw_dec)) { + *codec_name = &VP8_sw_decoder[0]; + *codec_num = PJ_ARRAY_SIZE(VP8_sw_decoder); + } else { + *codec_name = &VP8_hw_decoder[0]; + *codec_num = PJ_ARRAY_SIZE(VP8_hw_decoder); + } + } + break; #endif #if PJMEDIA_HAS_AND_MEDIA_VP9 case PJMEDIA_FORMAT_VP9: - if (is_enc) { - if ((prio && use_sw_enc) || (!prio && !use_sw_enc)) { - *codec_name = &VP9_sw_encoder[0]; - *codec_num = PJ_ARRAY_SIZE(VP9_sw_encoder); - } else { - *codec_name = &VP9_hw_encoder[0]; - *codec_num = PJ_ARRAY_SIZE(VP9_hw_encoder); - } - } else { - if ((prio && use_sw_dec) || (!prio && !use_sw_dec)) { - *codec_name = &VP9_sw_decoder[0]; - *codec_num = PJ_ARRAY_SIZE(VP9_sw_decoder); - } else { - *codec_name = &VP9_hw_decoder[0]; - *codec_num = PJ_ARRAY_SIZE(VP9_hw_decoder); - } - } - break; + if (is_enc) { + if ((prio && use_sw_enc) || (!prio && !use_sw_enc)) { + *codec_name = &VP9_sw_encoder[0]; + *codec_num = PJ_ARRAY_SIZE(VP9_sw_encoder); + } else { + *codec_name = &VP9_hw_encoder[0]; + *codec_num = PJ_ARRAY_SIZE(VP9_hw_encoder); + } + } else { + if ((prio && use_sw_dec) || (!prio && !use_sw_dec)) { + *codec_name = &VP9_sw_decoder[0]; + *codec_num = PJ_ARRAY_SIZE(VP9_sw_decoder); + } else { + *codec_name = &VP9_hw_decoder[0]; + *codec_num = PJ_ARRAY_SIZE(VP9_hw_decoder); + } + } + break; #endif default: - break; + break; } } @@ -723,62 +723,62 @@ static pj_status_t and_media_enum_info(pjmedia_vid_codec_factory *factory, max = *count; for (i = 0, *count = 0; i < PJ_ARRAY_SIZE(and_media_codec) && *count < max; - ++i) + ++i) { - unsigned enc_idx = 0; - unsigned dec_idx = 0; - pj_str_t *enc_name = NULL; - unsigned num_enc; - pj_str_t *dec_name = NULL; - unsigned num_dec; - - get_codec_name(PJ_TRUE, PJ_TRUE, and_media_codec[i].fmt_id, - &enc_name, &num_enc); - - for (enc_idx = 0; enc_idx < num_enc ;++enc_idx, ++enc_name) { - if (codec_exists(enc_name)) { - break; - } - } - if (enc_idx == num_enc) { - get_codec_name(PJ_TRUE, PJ_FALSE, and_media_codec[i].fmt_id, - &enc_name, &num_enc); - - for (enc_idx = 0; enc_idx < num_enc ;++enc_idx, ++enc_name) { - if (codec_exists(enc_name)) { - break; - } - } - if (enc_idx == num_enc) - continue; - } - - get_codec_name(PJ_FALSE, PJ_TRUE, and_media_codec[i].fmt_id, - &dec_name, &num_dec); - for (dec_idx = 0; dec_idx < num_dec ;++dec_idx, ++dec_name) { - if (codec_exists(dec_name)) { - break; - } - } - if (dec_idx == num_dec) { - get_codec_name(PJ_FALSE, PJ_FALSE, and_media_codec[i].fmt_id, - &dec_name, &num_dec); - for (enc_idx = 0; enc_idx < num_enc ;++enc_idx, ++enc_name) { - if (codec_exists(enc_name)) { - break; - } - } - if (dec_idx == num_dec) - continue; - } - - and_media_codec[i].encoder_name = enc_name; - and_media_codec[i].decoder_name = dec_name; - PJ_LOG(4, (THIS_FILE, "Found encoder [%d]: %.*s and decoder: %.*s ", - *count, enc_name->slen, enc_name->ptr, dec_name->slen, - dec_name->ptr)); - add_codec(&and_media_codec[*count], count, info); - and_media_codec[i].enabled = PJ_TRUE; + unsigned enc_idx = 0; + unsigned dec_idx = 0; + pj_str_t *enc_name = NULL; + unsigned num_enc; + pj_str_t *dec_name = NULL; + unsigned num_dec; + + get_codec_name(PJ_TRUE, PJ_TRUE, and_media_codec[i].fmt_id, + &enc_name, &num_enc); + + for (enc_idx = 0; enc_idx < num_enc ;++enc_idx, ++enc_name) { + if (codec_exists(enc_name)) { + break; + } + } + if (enc_idx == num_enc) { + get_codec_name(PJ_TRUE, PJ_FALSE, and_media_codec[i].fmt_id, + &enc_name, &num_enc); + + for (enc_idx = 0; enc_idx < num_enc ;++enc_idx, ++enc_name) { + if (codec_exists(enc_name)) { + break; + } + } + if (enc_idx == num_enc) + continue; + } + + get_codec_name(PJ_FALSE, PJ_TRUE, and_media_codec[i].fmt_id, + &dec_name, &num_dec); + for (dec_idx = 0; dec_idx < num_dec ;++dec_idx, ++dec_name) { + if (codec_exists(dec_name)) { + break; + } + } + if (dec_idx == num_dec) { + get_codec_name(PJ_FALSE, PJ_FALSE, and_media_codec[i].fmt_id, + &dec_name, &num_dec); + for (enc_idx = 0; enc_idx < num_enc ;++enc_idx, ++enc_name) { + if (codec_exists(enc_name)) { + break; + } + } + if (dec_idx == num_dec) + continue; + } + + and_media_codec[i].encoder_name = enc_name; + and_media_codec[i].decoder_name = dec_name; + PJ_LOG(4, (THIS_FILE, "Found encoder [%d]: %.*s and decoder: %.*s ", + *count, enc_name->slen, enc_name->ptr, dec_name->slen, + dec_name->ptr)); + add_codec(&and_media_codec[*count], count, info); + and_media_codec[i].enabled = PJ_TRUE; } return PJ_SUCCESS; @@ -790,29 +790,29 @@ static void create_codec(struct and_media_codec_data *and_media_data) char *dec_name; if (!and_media_codec[and_media_data->codec_idx].encoder_name || - !and_media_codec[and_media_data->codec_idx].decoder_name) + !and_media_codec[and_media_data->codec_idx].decoder_name) { - return; + return; } enc_name = and_media_codec[and_media_data->codec_idx].encoder_name->ptr; dec_name = and_media_codec[and_media_data->codec_idx].decoder_name->ptr; if (!and_media_data->enc) { - and_media_data->enc = AMediaCodec_createCodecByName(enc_name); - if (!and_media_data->enc) { - PJ_LOG(4, (THIS_FILE, "Failed creating encoder: %s", enc_name)); - } + and_media_data->enc = AMediaCodec_createCodecByName(enc_name); + if (!and_media_data->enc) { + PJ_LOG(4, (THIS_FILE, "Failed creating encoder: %s", enc_name)); + } } if (!and_media_data->dec) { - and_media_data->dec = AMediaCodec_createCodecByName(dec_name); - if (!and_media_data->dec) { - PJ_LOG(4, (THIS_FILE, "Failed creating decoder: %s", dec_name)); - } + and_media_data->dec = AMediaCodec_createCodecByName(dec_name); + if (!and_media_data->dec) { + PJ_LOG(4, (THIS_FILE, "Failed creating decoder: %s", dec_name)); + } } PJ_LOG(4, (THIS_FILE, "Created encoder: %s, decoder: %s", enc_name, - dec_name)); + dec_name)); } static pj_status_t and_media_alloc_codec(pjmedia_vid_codec_factory *factory, @@ -829,22 +829,22 @@ static pj_status_t and_media_alloc_codec(pjmedia_vid_codec_factory *factory, idx = -1; for (i = 0; i < PJ_ARRAY_SIZE(and_media_codec); ++i) { - if ((info->fmt_id == and_media_codec[i].fmt_id) && + if ((info->fmt_id == and_media_codec[i].fmt_id) && (and_media_codec[i].enabled)) - { - idx = i; - break; - } + { + idx = i; + break; + } } if (idx == -1) { - *p_codec = NULL; - return PJMEDIA_CODEC_EFAILED; + *p_codec = NULL; + return PJMEDIA_CODEC_EFAILED; } *p_codec = NULL; pool = pj_pool_create(and_media_factory.pf, "anmedvid%p", 512, 512, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* codec instance */ codec = PJ_POOL_ZALLOC_T(pool, pjmedia_vid_codec); @@ -859,7 +859,7 @@ static pj_status_t and_media_alloc_codec(pjmedia_vid_codec_factory *factory, create_codec(and_media_data); if (!and_media_data->enc || !and_media_data->dec) { - goto on_error; + goto on_error; } *p_codec = codec; @@ -917,7 +917,7 @@ static pj_status_t and_media_codec_open(pjmedia_vid_codec *codec, param = and_media_data->prm; if (and_media_codec[and_media_data->codec_idx].open_codec) { status = and_media_codec[and_media_data->codec_idx].open_codec( - and_media_data); + and_media_data); if (status != PJ_SUCCESS) return status; } @@ -931,8 +931,8 @@ static pj_status_t and_media_codec_open(pjmedia_vid_codec *codec, return PJMEDIA_CODEC_EFAILED; } if (and_media_data->dec_buf_size == 0) { - and_media_data->dec_buf_size = (MAX_RX_WIDTH * MAX_RX_HEIGHT * 3 >> 1) + - (MAX_RX_WIDTH); + and_media_data->dec_buf_size = (MAX_RX_WIDTH * MAX_RX_HEIGHT * 3 >> 1) + + (MAX_RX_WIDTH); } and_media_data->dec_buf = (pj_uint8_t*)pj_pool_alloc(and_media_data->pool, and_media_data->dec_buf_size); @@ -989,83 +989,83 @@ static pj_status_t and_media_codec_encode_begin(pjmedia_vid_codec *codec, if (opt && opt->force_keyframe) { #if __ANDROID_API__ >=26 - AMediaFormat *vid_fmt = NULL; - media_status_t am_status; + AMediaFormat *vid_fmt = NULL; + media_status_t am_status; - vid_fmt = AMediaFormat_new(); - if (!vid_fmt) { - return PJMEDIA_CODEC_EFAILED; - } - AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_REQUEST_SYNCF, 0); - am_status = AMediaCodec_setParameters(and_media_data->enc, vid_fmt); + vid_fmt = AMediaFormat_new(); + if (!vid_fmt) { + return PJMEDIA_CODEC_EFAILED; + } + AMediaFormat_setInt32(vid_fmt, AND_MEDIA_KEY_REQUEST_SYNCF, 0); + am_status = AMediaCodec_setParameters(and_media_data->enc, vid_fmt); - if (am_status != AMEDIA_OK) - PJ_LOG(4,(THIS_FILE, "Encoder setParameters failed %d", am_status)); + if (am_status != AMEDIA_OK) + PJ_LOG(4,(THIS_FILE, "Encoder setParameters failed %d", am_status)); - AMediaFormat_delete(vid_fmt); + AMediaFormat_delete(vid_fmt); #else - PJ_LOG(5, (THIS_FILE, "Encoder cannot be forced to send keyframe")); + PJ_LOG(5, (THIS_FILE, "Encoder cannot be forced to send keyframe")); #endif } buf_idx = AMediaCodec_dequeueInputBuffer(and_media_data->enc, - CODEC_DEQUEUE_TIMEOUT); + CODEC_DEQUEUE_TIMEOUT); if (buf_idx >= 0) { - media_status_t am_status; - pj_size_t output_size; - pj_uint8_t *input_buf = AMediaCodec_getInputBuffer(and_media_data->enc, - buf_idx, &output_size); - if (input_buf && output_size >= input->size) { - pj_memcpy(input_buf, input->buf, input->size); - am_status = AMediaCodec_queueInputBuffer(and_media_data->enc, - buf_idx, 0, input->size, 0, 0); - if (am_status != AMEDIA_OK) { - PJ_LOG(4, (THIS_FILE, "Encoder queueInputBuffer return %d", - am_status)); - goto on_return; - } - } else { - if (!input_buf) { - PJ_LOG(4,(THIS_FILE, "Encoder getInputBuffer " - "returns no input buff")); - } else { - PJ_LOG(4,(THIS_FILE, "Encoder getInputBuffer " - "size: %d, expecting %d.", - input_buf, output_size, input->size)); - } - goto on_return; - } + media_status_t am_status; + pj_size_t output_size; + pj_uint8_t *input_buf = AMediaCodec_getInputBuffer(and_media_data->enc, + buf_idx, &output_size); + if (input_buf && output_size >= input->size) { + pj_memcpy(input_buf, input->buf, input->size); + am_status = AMediaCodec_queueInputBuffer(and_media_data->enc, + buf_idx, 0, input->size, 0, 0); + if (am_status != AMEDIA_OK) { + PJ_LOG(4, (THIS_FILE, "Encoder queueInputBuffer return %d", + am_status)); + goto on_return; + } + } else { + if (!input_buf) { + PJ_LOG(4,(THIS_FILE, "Encoder getInputBuffer " + "returns no input buff")); + } else { + PJ_LOG(4,(THIS_FILE, "Encoder getInputBuffer " + "size: %d, expecting %d.", + input_buf, output_size, input->size)); + } + goto on_return; + } } else { - PJ_LOG(4,(THIS_FILE, "Encoder dequeueInputBuffer failed[%d]", buf_idx)); - goto on_return; + PJ_LOG(4,(THIS_FILE, "Encoder dequeueInputBuffer failed[%d]", buf_idx)); + goto on_return; } for (i = 0; i < CODEC_WAIT_RETRY; ++i) { - buf_idx = AMediaCodec_dequeueOutputBuffer(and_media_data->enc, - &and_media_data->enc_buf_info, - CODEC_DEQUEUE_TIMEOUT); - if (buf_idx == -1) { - /* Timeout, wait until output buffer is availble. */ - PJ_LOG(5, (THIS_FILE, "Encoder dequeueOutputBuffer timeout[%d]", - i+1)); - pj_thread_sleep(CODEC_THREAD_WAIT); - } else { - break; - } + buf_idx = AMediaCodec_dequeueOutputBuffer(and_media_data->enc, + &and_media_data->enc_buf_info, + CODEC_DEQUEUE_TIMEOUT); + if (buf_idx == -1) { + /* Timeout, wait until output buffer is availble. */ + PJ_LOG(5, (THIS_FILE, "Encoder dequeueOutputBuffer timeout[%d]", + i+1)); + pj_thread_sleep(CODEC_THREAD_WAIT); + } else { + break; + } } if (buf_idx >= 0) { pj_size_t output_size; pj_uint8_t *output_buf = AMediaCodec_getOutputBuffer( - and_media_data->enc, + and_media_data->enc, buf_idx, &output_size); if (!output_buf) { PJ_LOG(4, (THIS_FILE, "Encoder failed getting output buffer, " - "buffer size %d, offset %d, flags %d", - and_media_data->enc_buf_info.size, - and_media_data->enc_buf_info.offset, - and_media_data->enc_buf_info.flags)); + "buffer size %d, offset %d, flags %d", + and_media_data->enc_buf_info.size, + and_media_data->enc_buf_info.offset, + and_media_data->enc_buf_info.flags)); goto on_return; } and_media_data->enc_processed = 0; @@ -1095,13 +1095,13 @@ static pj_status_t and_media_codec_encode_begin(pjmedia_vid_codec *codec, if ((and_media_data->prm->enc_fmt.id == PJMEDIA_FORMAT_H264) && (and_media_data->enc_buf_info.flags & - AND_MEDIA_FRM_TYPE_KEYFRAME)) + AND_MEDIA_FRM_TYPE_KEYFRAME)) { - h264_codec_data *h264_data = - (h264_codec_data *)and_media_data->ex_data; - start_data = h264_data->enc_sps_pps_len; + h264_codec_data *h264_data = + (h264_codec_data *)and_media_data->ex_data; + start_data = h264_data->enc_sps_pps_len; pj_memcpy(output->buf, h264_data->enc_sps_pps_buf, - h264_data->enc_sps_pps_len); + h264_data->enc_sps_pps_len); } payload_size = and_media_data->enc_buf_info.size + start_data; @@ -1113,36 +1113,36 @@ static pj_status_t and_media_codec_encode_begin(pjmedia_vid_codec *codec, output->size = payload_size; output->timestamp = input->timestamp; pj_memcpy((pj_uint8_t*)output->buf+start_data, - and_media_data->enc_frame_whole, - and_media_data->enc_buf_info.size); + and_media_data->enc_frame_whole, + and_media_data->enc_buf_info.size); - AMediaCodec_releaseOutputBuffer(and_media_data->enc, - buf_idx, - 0); + AMediaCodec_releaseOutputBuffer(and_media_data->enc, + buf_idx, + 0); return PJ_SUCCESS; } } else { if (buf_idx == -2) { - int width, height, color_fmt, stride; - - /* Format change. */ - AMediaFormat *vid_fmt = AMediaCodec_getOutputFormat( - and_media_data->enc); - - AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_WIDTH, &width); - AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_HEIGHT, &height); - AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_COLOR_FMT, &color_fmt); - AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_STRIDE, &stride); - PJ_LOG(5, (THIS_FILE, "Encoder detect new width %d, height %d, " - "color_fmt 0x%X, stride %d buf_size %d", - width, height, color_fmt, stride, - and_media_data->enc_buf_info.size)); - - AMediaFormat_delete(vid_fmt); + int width, height, color_fmt, stride; + + /* Format change. */ + AMediaFormat *vid_fmt = AMediaCodec_getOutputFormat( + and_media_data->enc); + + AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_WIDTH, &width); + AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_HEIGHT, &height); + AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_COLOR_FMT, &color_fmt); + AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_STRIDE, &stride); + PJ_LOG(5, (THIS_FILE, "Encoder detect new width %d, height %d, " + "color_fmt 0x%X, stride %d buf_size %d", + width, height, color_fmt, stride, + and_media_data->enc_buf_info.size)); + + AMediaFormat_delete(vid_fmt); } else { - PJ_LOG(4, (THIS_FILE, "Encoder dequeueOutputBuffer failed[%d]", - buf_idx)); + PJ_LOG(4, (THIS_FILE, "Encoder dequeueOutputBuffer failed[%d]", + buf_idx)); } goto on_return; } @@ -1169,13 +1169,13 @@ static pj_status_t and_media_codec_encode_more(pjmedia_vid_codec *codec, and_media_data = (and_media_codec_data*) codec->codec_data; status = and_media_codec[and_media_data->codec_idx].encode_more( - and_media_data, - out_size, output, - has_more); + and_media_data, + out_size, output, + has_more); if (!(*has_more)) { - AMediaCodec_releaseOutputBuffer(and_media_data->enc, - and_media_data->enc_output_buf_idx, - 0); + AMediaCodec_releaseOutputBuffer(and_media_data->enc, + and_media_data->enc_output_buf_idx, + 0); } return status; @@ -1195,214 +1195,214 @@ static int write_yuv(pj_uint8_t *buf, unsigned char* pPtr = NULL; req_size = (iWidth * iHeight) + (iWidth / 2 * iHeight / 2) + - (iWidth / 2 * iHeight / 2); + (iWidth / 2 * iHeight / 2); if (dst_len < req_size) - return -1; + return -1; pPtr = input; for (i = 0; i < iHeight && (dst + iWidth < max); i++) { - pj_memcpy(dst, pPtr, iWidth); - pPtr += stride_len; - dst += iWidth; + pj_memcpy(dst, pPtr, iWidth); + pPtr += stride_len; + dst += iWidth; } if (i < iHeight) - return -1; + return -1; iHeight = iHeight / 2; iWidth = iWidth / 2; for (i = 0; i < iHeight && (dst + iWidth <= max); i++) { - pj_memcpy(dst, pPtr, iWidth); - pPtr += stride_len/2; - dst += iWidth; + pj_memcpy(dst, pPtr, iWidth); + pPtr += stride_len/2; + dst += iWidth; } if (i < iHeight) - return -1; + return -1; for (i = 0; i < iHeight && (dst + iWidth <= max); i++) { - pj_memcpy(dst, pPtr, iWidth); - pPtr += stride_len/2; - dst += iWidth; + pj_memcpy(dst, pPtr, iWidth); + pPtr += stride_len/2; + dst += iWidth; } if (i < iHeight) - return -1; + return -1; return dst - buf; } static void and_media_get_input_buffer( - struct and_media_codec_data *and_media_data) + struct and_media_codec_data *and_media_data) { pj_ssize_t buf_idx = -1; buf_idx = AMediaCodec_dequeueInputBuffer(and_media_data->dec, - CODEC_DEQUEUE_TIMEOUT); + CODEC_DEQUEUE_TIMEOUT); if (buf_idx < 0) { - PJ_LOG(4,(THIS_FILE, "Decoder dequeueInputBuffer failed return %d", - buf_idx)); - - and_media_data->dec_input_buf = NULL; - - if (buf_idx == -10000) { - PJ_LOG(5, (THIS_FILE, "Resetting decoder")); - AMediaCodec_stop(and_media_data->dec); - AMediaCodec_delete(and_media_data->dec); - and_media_data->dec = NULL; - - create_codec(and_media_data); - if (and_media_data->dec) - configure_decoder(and_media_data); - } - return; + PJ_LOG(4,(THIS_FILE, "Decoder dequeueInputBuffer failed return %d", + buf_idx)); + + and_media_data->dec_input_buf = NULL; + + if (buf_idx == -10000) { + PJ_LOG(5, (THIS_FILE, "Resetting decoder")); + AMediaCodec_stop(and_media_data->dec); + AMediaCodec_delete(and_media_data->dec); + and_media_data->dec = NULL; + + create_codec(and_media_data); + if (and_media_data->dec) + configure_decoder(and_media_data); + } + return; } and_media_data->dec_input_buf_len = 0; and_media_data->dec_input_buf_idx = buf_idx; and_media_data->dec_input_buf = AMediaCodec_getInputBuffer( - and_media_data->dec, - buf_idx, - &and_media_data->dec_input_buf_max_size); + and_media_data->dec, + buf_idx, + &and_media_data->dec_input_buf_max_size); } static pj_status_t and_media_decode(pjmedia_vid_codec *codec, - struct and_media_codec_data *and_media_data, - pj_uint8_t *input_buf, unsigned buf_size, - int buf_flag, pj_timestamp *input_ts, - pj_bool_t write_output, pjmedia_frame *output) + struct and_media_codec_data *and_media_data, + pj_uint8_t *input_buf, unsigned buf_size, + int buf_flag, pj_timestamp *input_ts, + pj_bool_t write_output, pjmedia_frame *output) { pj_ssize_t buf_idx = 0; pj_status_t status = PJ_SUCCESS; media_status_t am_status; if ((and_media_data->dec_input_buf_max_size > 0) && - (and_media_data->dec_input_buf_len + buf_size > + (and_media_data->dec_input_buf_len + buf_size > and_media_data->dec_input_buf_max_size)) { - am_status = AMediaCodec_queueInputBuffer(and_media_data->dec, - and_media_data->dec_input_buf_idx, - 0, - and_media_data->dec_input_buf_len, - input_ts->u32.lo, - buf_flag); - if (am_status != AMEDIA_OK) { - PJ_LOG(4,(THIS_FILE, "Decoder queueInputBuffer idx[%d] return %d", - and_media_data->dec_input_buf_idx, am_status)); - return status; - } - and_media_data->dec_input_buf = NULL; + am_status = AMediaCodec_queueInputBuffer(and_media_data->dec, + and_media_data->dec_input_buf_idx, + 0, + and_media_data->dec_input_buf_len, + input_ts->u32.lo, + buf_flag); + if (am_status != AMEDIA_OK) { + PJ_LOG(4,(THIS_FILE, "Decoder queueInputBuffer idx[%d] return %d", + and_media_data->dec_input_buf_idx, am_status)); + return status; + } + and_media_data->dec_input_buf = NULL; } if (and_media_data->dec_input_buf == NULL) { - and_media_get_input_buffer(and_media_data); + and_media_get_input_buffer(and_media_data); - if (and_media_data->dec_input_buf == NULL) { - PJ_LOG(4,(THIS_FILE, "Decoder failed getting input buffer")); - return status; - } + if (and_media_data->dec_input_buf == NULL) { + PJ_LOG(4,(THIS_FILE, "Decoder failed getting input buffer")); + return status; + } } pj_memcpy(and_media_data->dec_input_buf + and_media_data->dec_input_buf_len, - input_buf, buf_size); + input_buf, buf_size); and_media_data->dec_input_buf_len += buf_size; if (!write_output) - return status; + return status; am_status = AMediaCodec_queueInputBuffer(and_media_data->dec, - and_media_data->dec_input_buf_idx, - 0, - and_media_data->dec_input_buf_len, - input_ts->u32.lo, - buf_flag); + and_media_data->dec_input_buf_idx, + 0, + and_media_data->dec_input_buf_len, + input_ts->u32.lo, + buf_flag); if (am_status != AMEDIA_OK) { - PJ_LOG(4,(THIS_FILE, "Decoder queueInputBuffer failed return %d", - am_status)); - and_media_data->dec_input_buf = NULL; - return status; + PJ_LOG(4,(THIS_FILE, "Decoder queueInputBuffer failed return %d", + am_status)); + and_media_data->dec_input_buf = NULL; + return status; } and_media_data->dec_input_buf_len += buf_size; buf_idx = AMediaCodec_dequeueOutputBuffer(and_media_data->dec, - &and_media_data->dec_buf_info, - CODEC_DEQUEUE_TIMEOUT); + &and_media_data->dec_buf_info, + CODEC_DEQUEUE_TIMEOUT); if (buf_idx >= 0) { - pj_size_t output_size; - int len; - - pj_uint8_t *output_buf = AMediaCodec_getOutputBuffer( - and_media_data->dec, - buf_idx, - &output_size); - if (output_buf == NULL) { - am_status = AMediaCodec_releaseOutputBuffer(and_media_data->dec, - buf_idx, - 0); - PJ_LOG(4,(THIS_FILE, "Decoder getOutputBuffer failed")); - return status; - } - len = write_yuv((pj_uint8_t *)output->buf, - and_media_data->dec_buf_info.size, - output_buf, - and_media_data->dec_stride_len, - and_media_data->prm->dec_fmt.det.vid.size.w, - and_media_data->prm->dec_fmt.det.vid.size.h); - - am_status = AMediaCodec_releaseOutputBuffer(and_media_data->dec, - buf_idx, - 0); - - if (len > 0) { - if (!and_media_data->dec_has_output_frame) { - output->type = PJMEDIA_FRAME_TYPE_VIDEO; - output->size = len; - output->timestamp = *input_ts; - - and_media_data->dec_has_output_frame = PJ_TRUE; - } - } else { - status = PJMEDIA_CODEC_EFRMTOOSHORT; - } + pj_size_t output_size; + int len; + + pj_uint8_t *output_buf = AMediaCodec_getOutputBuffer( + and_media_data->dec, + buf_idx, + &output_size); + if (output_buf == NULL) { + am_status = AMediaCodec_releaseOutputBuffer(and_media_data->dec, + buf_idx, + 0); + PJ_LOG(4,(THIS_FILE, "Decoder getOutputBuffer failed")); + return status; + } + len = write_yuv((pj_uint8_t *)output->buf, + and_media_data->dec_buf_info.size, + output_buf, + and_media_data->dec_stride_len, + and_media_data->prm->dec_fmt.det.vid.size.w, + and_media_data->prm->dec_fmt.det.vid.size.h); + + am_status = AMediaCodec_releaseOutputBuffer(and_media_data->dec, + buf_idx, + 0); + + if (len > 0) { + if (!and_media_data->dec_has_output_frame) { + output->type = PJMEDIA_FRAME_TYPE_VIDEO; + output->size = len; + output->timestamp = *input_ts; + + and_media_data->dec_has_output_frame = PJ_TRUE; + } + } else { + status = PJMEDIA_CODEC_EFRMTOOSHORT; + } } else if (buf_idx == -2) { - int width, height, stride; - AMediaFormat *vid_fmt; - /* Get output format */ - vid_fmt = AMediaCodec_getOutputFormat(and_media_data->dec); - - AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_WIDTH, &width); - AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_HEIGHT, &height); - AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_STRIDE, &stride); - - AMediaFormat_delete(vid_fmt); - and_media_data->dec_stride_len = stride; - if (width != and_media_data->prm->dec_fmt.det.vid.size.w || - height != and_media_data->prm->dec_fmt.det.vid.size.h) - { - pjmedia_event event; - - and_media_data->prm->dec_fmt.det.vid.size.w = width; - and_media_data->prm->dec_fmt.det.vid.size.h = height; - - PJ_LOG(4,(THIS_FILE, "Frame size changed to %dx%d", - and_media_data->prm->dec_fmt.det.vid.size.w, - and_media_data->prm->dec_fmt.det.vid.size.h)); - - /* Broadcast format changed event */ - pjmedia_event_init(&event, PJMEDIA_EVENT_FMT_CHANGED, - &output->timestamp, codec); - event.data.fmt_changed.dir = PJMEDIA_DIR_DECODING; - pjmedia_format_copy(&event.data.fmt_changed.new_fmt, - &and_media_data->prm->dec_fmt); - pjmedia_event_publish(NULL, codec, &event, - PJMEDIA_EVENT_PUBLISH_DEFAULT); - } + int width, height, stride; + AMediaFormat *vid_fmt; + /* Get output format */ + vid_fmt = AMediaCodec_getOutputFormat(and_media_data->dec); + + AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_WIDTH, &width); + AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_HEIGHT, &height); + AMediaFormat_getInt32(vid_fmt, AND_MEDIA_KEY_STRIDE, &stride); + + AMediaFormat_delete(vid_fmt); + and_media_data->dec_stride_len = stride; + if (width != and_media_data->prm->dec_fmt.det.vid.size.w || + height != and_media_data->prm->dec_fmt.det.vid.size.h) + { + pjmedia_event event; + + and_media_data->prm->dec_fmt.det.vid.size.w = width; + and_media_data->prm->dec_fmt.det.vid.size.h = height; + + PJ_LOG(4,(THIS_FILE, "Frame size changed to %dx%d", + and_media_data->prm->dec_fmt.det.vid.size.w, + and_media_data->prm->dec_fmt.det.vid.size.h)); + + /* Broadcast format changed event */ + pjmedia_event_init(&event, PJMEDIA_EVENT_FMT_CHANGED, + &output->timestamp, codec); + event.data.fmt_changed.dir = PJMEDIA_DIR_DECODING; + pjmedia_format_copy(&event.data.fmt_changed.new_fmt, + &and_media_data->prm->dec_fmt); + pjmedia_event_publish(NULL, codec, &event, + PJMEDIA_EVENT_PUBLISH_DEFAULT); + } } else { - PJ_LOG(4,(THIS_FILE, "Decoder dequeueOutputBuffer failed [%d]", - buf_idx)); + PJ_LOG(4,(THIS_FILE, "Decoder dequeueOutputBuffer failed [%d]", + buf_idx)); } return status; } @@ -1431,22 +1431,22 @@ static pj_status_t and_media_codec_decode(pjmedia_vid_codec *codec, output); } if (status != PJ_SUCCESS) { - return status; + return status; } if (!and_media_data->dec_has_output_frame) { - pjmedia_event event; + pjmedia_event event; - /* Broadcast missing keyframe event */ - pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, - &packets[0].timestamp, codec); - pjmedia_event_publish(NULL, codec, &event, - PJMEDIA_EVENT_PUBLISH_DEFAULT); + /* Broadcast missing keyframe event */ + pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, + &packets[0].timestamp, codec); + pjmedia_event_publish(NULL, codec, &event, + PJMEDIA_EVENT_PUBLISH_DEFAULT); - PJ_LOG(4,(THIS_FILE, "Decoder couldn't produce output frame")); + PJ_LOG(4,(THIS_FILE, "Decoder couldn't produce output frame")); - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->size = 0; - output->timestamp = packets[0].timestamp; + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->size = 0; + output->timestamp = packets[0].timestamp; } return PJ_SUCCESS; } @@ -1498,7 +1498,7 @@ static pj_status_t open_h264(and_media_codec_data *and_media_data) and_media_data->ex_data = h264_data; and_media_data->dec_buf_size = (MAX_RX_WIDTH * MAX_RX_HEIGHT * 3 >> 1) + - (MAX_RX_WIDTH); + (MAX_RX_WIDTH); /* If available, use the "sprop-parameter-sets" fmtp from remote SDP * to create the decoder. @@ -1526,9 +1526,9 @@ static pj_status_t open_h264(and_media_codec_data *and_media_data) med_code_size - code_size - i; h264_data->dec_sps_buf = (pj_uint8_t *)pj_pool_alloc( - and_media_data->pool, h264_data->dec_sps_len); + and_media_data->pool, h264_data->dec_sps_len); h264_data->dec_pps_buf = (pj_uint8_t *)pj_pool_alloc( - and_media_data->pool, h264_data->dec_pps_len); + and_media_data->pool, h264_data->dec_pps_len); pj_memcpy(h264_data->dec_sps_buf, med_start_code, med_code_size); @@ -1554,13 +1554,13 @@ static pj_status_t process_encode_h264(and_media_codec_data *and_media_data) if (and_media_data->enc_buf_info.flags & AND_MEDIA_FRM_TYPE_CONFIG) { /* - * Config data or SPS+PPS. Update the SPS and PPS buffer, - * this will be sent later when sending Keyframe. - */ - h264_data->enc_sps_pps_len = PJ_MIN(and_media_data->enc_buf_info.size, + * Config data or SPS+PPS. Update the SPS and PPS buffer, + * this will be sent later when sending Keyframe. + */ + h264_data->enc_sps_pps_len = PJ_MIN(and_media_data->enc_buf_info.size, sizeof(h264_data->enc_sps_pps_buf)); pj_memcpy(h264_data->enc_sps_pps_buf, and_media_data->enc_frame_whole, - h264_data->enc_sps_pps_len); + h264_data->enc_sps_pps_len); AMediaCodec_releaseOutputBuffer(and_media_data->enc, and_media_data->enc_output_buf_idx, @@ -1569,19 +1569,19 @@ static pj_status_t process_encode_h264(and_media_codec_data *and_media_data) return PJ_EIGNORED; } if (and_media_data->enc_buf_info.flags & AND_MEDIA_FRM_TYPE_KEYFRAME) { - h264_data->enc_sps_pps_ex = PJ_TRUE; + h264_data->enc_sps_pps_ex = PJ_TRUE; and_media_data->enc_frame_size = h264_data->enc_sps_pps_len; } else { - h264_data->enc_sps_pps_ex = PJ_FALSE; + h264_data->enc_sps_pps_ex = PJ_FALSE; } return status; } static pj_status_t encode_more_h264(and_media_codec_data *and_media_data, - unsigned out_size, - pjmedia_frame *output, - pj_bool_t *has_more) + unsigned out_size, + pjmedia_frame *output, + pj_bool_t *has_more) { const pj_uint8_t *payload; pj_size_t payload_len; @@ -1591,24 +1591,24 @@ static pj_status_t encode_more_h264(and_media_codec_data *and_media_data, h264_data = (h264_codec_data *)and_media_data->ex_data; if (h264_data->enc_sps_pps_ex) { - data_buf = h264_data->enc_sps_pps_buf; + data_buf = h264_data->enc_sps_pps_buf; } else { - data_buf = and_media_data->enc_frame_whole; + data_buf = and_media_data->enc_frame_whole; } /* We have outstanding frame in packetizer */ status = pjmedia_h264_packetize(h264_data->pktz, - data_buf, - and_media_data->enc_frame_size, - &and_media_data->enc_processed, - &payload, &payload_len); + data_buf, + and_media_data->enc_frame_size, + &and_media_data->enc_processed, + &payload, &payload_len); if (status != PJ_SUCCESS) { - /* Reset */ - and_media_data->enc_frame_size = and_media_data->enc_processed = 0; - *has_more = (and_media_data->enc_processed < - and_media_data->enc_frame_size); + /* Reset */ + and_media_data->enc_frame_size = and_media_data->enc_processed = 0; + *has_more = (and_media_data->enc_processed < + and_media_data->enc_frame_size); - PJ_PERROR(3,(THIS_FILE, status, "pjmedia_h264_packetize() error")); - return status; + PJ_PERROR(3,(THIS_FILE, status, "pjmedia_h264_packetize() error")); + return status; } PJ_ASSERT_RETURN(payload_len <= out_size, PJMEDIA_CODEC_EFRMTOOSHORT); @@ -1618,28 +1618,28 @@ static pj_status_t encode_more_h264(and_media_codec_data *and_media_data, output->size = payload_len; if (and_media_data->enc_processed >= and_media_data->enc_frame_size) { - h264_codec_data *h264_data = (h264_codec_data *)and_media_data->ex_data; - - if (h264_data->enc_sps_pps_ex) { - *has_more = PJ_TRUE; - h264_data->enc_sps_pps_ex = PJ_FALSE; - and_media_data->enc_processed = 0; - and_media_data->enc_frame_size = and_media_data->enc_buf_info.size; - } else { - *has_more = PJ_FALSE; - } + h264_codec_data *h264_data = (h264_codec_data *)and_media_data->ex_data; + + if (h264_data->enc_sps_pps_ex) { + *has_more = PJ_TRUE; + h264_data->enc_sps_pps_ex = PJ_FALSE; + and_media_data->enc_processed = 0; + and_media_data->enc_frame_size = and_media_data->enc_buf_info.size; + } else { + *has_more = PJ_FALSE; + } } else { - *has_more = PJ_TRUE; + *has_more = PJ_TRUE; } return PJ_SUCCESS; } static pj_status_t decode_h264(pjmedia_vid_codec *codec, - pj_size_t count, - pjmedia_frame packets[], - unsigned out_size, - pjmedia_frame *output) + pj_size_t count, + pjmedia_frame packets[], + unsigned out_size, + pjmedia_frame *output) { struct and_media_codec_data *and_media_data; const pj_uint8_t start_code[] = { 0, 0, 0, 1 }; @@ -1659,50 +1659,50 @@ static pj_status_t decode_h264(pjmedia_vid_codec *codec, */ whole_len = 0; if (and_media_data->whole) { - for (i=0; i and_media_data->dec_buf_size) { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]")); - return PJMEDIA_CODEC_EFRMTOOSHORT; - } - - pj_memcpy( and_media_data->dec_buf + whole_len, - (pj_uint8_t*)packets[i].buf, - packets[i].size); - whole_len += packets[i].size; - } + for (i=0; i and_media_data->dec_buf_size) { + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]")); + return PJMEDIA_CODEC_EFRMTOOSHORT; + } + + pj_memcpy( and_media_data->dec_buf + whole_len, + (pj_uint8_t*)packets[i].buf, + packets[i].size); + whole_len += packets[i].size; + } } else { - h264_codec_data *h264_data = (h264_codec_data *)and_media_data->ex_data; + h264_codec_data *h264_data = (h264_codec_data *)and_media_data->ex_data; - for (i=0; i + if (whole_len + packets[i].size + code_size > and_media_data->dec_buf_size) - { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [2]")); - return PJMEDIA_CODEC_EFRMTOOSHORT; - } - - status = pjmedia_h264_unpacketize( h264_data->pktz, - (pj_uint8_t*)packets[i].buf, - packets[i].size, - and_media_data->dec_buf, - and_media_data->dec_buf_size, - &whole_len); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, "Unpacketize error")); - continue; - } - } + { + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [2]")); + return PJMEDIA_CODEC_EFRMTOOSHORT; + } + + status = pjmedia_h264_unpacketize( h264_data->pktz, + (pj_uint8_t*)packets[i].buf, + packets[i].size, + and_media_data->dec_buf, + and_media_data->dec_buf_size, + &whole_len); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, "Unpacketize error")); + continue; + } + } } if (whole_len + code_size > and_media_data->dec_buf_size || - whole_len <= code_size + 1) + whole_len <= code_size + 1) { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow or unpacketize error " - "size: %d, buffer: %d", whole_len, - and_media_data->dec_buf_size)); - return PJMEDIA_CODEC_EFRMTOOSHORT; + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow or unpacketize error " + "size: %d, buffer: %d", whole_len, + and_media_data->dec_buf_size)); + return PJMEDIA_CODEC_EFRMTOOSHORT; } /* Dummy NAL sentinel */ @@ -1713,33 +1713,33 @@ static pj_status_t decode_h264(pjmedia_vid_codec *codec, */ buf_pos = 0; for ( frm_cnt=0; ; ++frm_cnt) { - pj_uint32_t frm_size; - pj_bool_t write_output = PJ_FALSE; - unsigned char *start; - - for (i = code_size - 1; buf_pos + i < whole_len; i++) { - if (and_media_data->dec_buf[buf_pos + i] == 0 && - and_media_data->dec_buf[buf_pos + i + 1] == 0 && - and_media_data->dec_buf[buf_pos + i + 2] == 0 && - and_media_data->dec_buf[buf_pos + i + 3] == 1) - { - break; - } - } - - frm_size = i; - start = and_media_data->dec_buf + buf_pos; - write_output = (buf_pos + frm_size >= whole_len); - - status = and_media_decode(codec, and_media_data, start, frm_size, 0, - &packets[0].timestamp, write_output, output); - if (status != PJ_SUCCESS) - return status; - - if (write_output) - break; - - buf_pos += frm_size; + pj_uint32_t frm_size; + pj_bool_t write_output = PJ_FALSE; + unsigned char *start; + + for (i = code_size - 1; buf_pos + i < whole_len; i++) { + if (and_media_data->dec_buf[buf_pos + i] == 0 && + and_media_data->dec_buf[buf_pos + i + 1] == 0 && + and_media_data->dec_buf[buf_pos + i + 2] == 0 && + and_media_data->dec_buf[buf_pos + i + 3] == 1) + { + break; + } + } + + frm_size = i; + start = and_media_data->dec_buf + buf_pos; + write_output = (buf_pos + frm_size >= whole_len); + + status = and_media_decode(codec, and_media_data, start, frm_size, 0, + &packets[0].timestamp, write_output, output); + if (status != PJ_SUCCESS) + return status; + + if (write_output) + break; + + buf_pos += frm_size; } return PJ_SUCCESS; @@ -1759,8 +1759,8 @@ static pj_status_t open_vpx(and_media_codec_data *and_media_data) if (!and_media_data->prm->ignore_fmtp) { status = pjmedia_vid_codec_vpx_apply_fmtp(and_media_data->prm); - if (status != PJ_SUCCESS) - return status; + if (status != PJ_SUCCESS) + return status; } vpx_data = PJ_POOL_ZALLOC_T(and_media_data->pool, vpx_codec_data); @@ -1769,12 +1769,12 @@ static pj_status_t open_vpx(and_media_codec_data *and_media_data) /* Parse local fmtp */ status = pjmedia_vid_codec_vpx_parse_fmtp(&and_media_data->prm->dec_fmtp, - &vpx_fmtp); + &vpx_fmtp); if (status != PJ_SUCCESS) - return status; + return status; if (vpx_fmtp.max_fs > 0) { - max_res = ((int)pj_isqrt(vpx_fmtp.max_fs * 8)) * 16; + max_res = ((int)pj_isqrt(vpx_fmtp.max_fs * 8)) * 16; } and_media_data->dec_buf_size = (max_res * max_res * 3 >> 1) + (max_res); @@ -1793,9 +1793,9 @@ static pj_status_t open_vpx(and_media_codec_data *and_media_data) } static pj_status_t encode_more_vpx(and_media_codec_data *and_media_data, - unsigned out_size, - pjmedia_frame *output, - pj_bool_t *has_more) + unsigned out_size, + pjmedia_frame *output, + pj_bool_t *has_more) { pj_status_t status = PJ_SUCCESS; struct vpx_codec_data *vpx_data = (vpx_codec_data *)and_media_data->ex_data; @@ -1804,31 +1804,31 @@ static pj_status_t encode_more_vpx(and_media_codec_data *and_media_data, PJ_EINVAL); if ((and_media_data->prm->enc_fmt.id != PJMEDIA_FORMAT_VP8) && - (and_media_data->prm->enc_fmt.id != PJMEDIA_FORMAT_VP9)) + (and_media_data->prm->enc_fmt.id != PJMEDIA_FORMAT_VP9)) { - *has_more = PJ_FALSE; - output->size = 0; - output->type = PJMEDIA_FRAME_TYPE_NONE; + *has_more = PJ_FALSE; + output->size = 0; + output->type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; + return PJ_SUCCESS; } if (and_media_data->enc_processed < and_media_data->enc_frame_size) { - unsigned payload_desc_size = 1; - pj_size_t payload_len = out_size; - pj_uint8_t *p = (pj_uint8_t *)output->buf; + unsigned payload_desc_size = 1; + pj_size_t payload_len = out_size; + pj_uint8_t *p = (pj_uint8_t *)output->buf; pj_bool_t is_keyframe = and_media_data->enc_buf_info.flags & - AND_MEDIA_FRM_TYPE_KEYFRAME; - - status = pjmedia_vpx_packetize(vpx_data->pktz, - and_media_data->enc_frame_size, - &and_media_data->enc_processed, - is_keyframe, - &p, - &payload_len); - if (status != PJ_SUCCESS) { - return status; - } + AND_MEDIA_FRM_TYPE_KEYFRAME; + + status = pjmedia_vpx_packetize(vpx_data->pktz, + and_media_data->enc_frame_size, + &and_media_data->enc_processed, + is_keyframe, + &p, + &payload_len); + if (status != PJ_SUCCESS) { + return status; + } pj_memcpy(p + payload_desc_size, (and_media_data->enc_frame_whole + and_media_data->enc_processed), payload_len); @@ -1838,22 +1838,22 @@ static pj_status_t encode_more_vpx(and_media_codec_data *and_media_data, } and_media_data->enc_processed += payload_len; *has_more = (and_media_data->enc_processed < - and_media_data->enc_frame_size); + and_media_data->enc_frame_size); } return status; } static pj_status_t decode_vpx(pjmedia_vid_codec *codec, - pj_size_t count, - pjmedia_frame packets[], - unsigned out_size, - pjmedia_frame *output) + pj_size_t count, + pjmedia_frame packets[], + unsigned out_size, + pjmedia_frame *output) { unsigned i, whole_len = 0; pj_status_t status; and_media_codec_data *and_media_data = - (and_media_codec_data*) codec->codec_data; + (and_media_codec_data*) codec->codec_data; struct vpx_codec_data *vpx_data = (vpx_codec_data *)and_media_data->ex_data; PJ_ASSERT_RETURN(codec && count && packets && out_size && output, @@ -1862,62 +1862,62 @@ static pj_status_t decode_vpx(pjmedia_vid_codec *codec, whole_len = 0; if (and_media_data->whole) { - for (i = 0; i < count; ++i) { - if (whole_len + packets[i].size > and_media_data->dec_buf_size) { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]")); - return PJMEDIA_CODEC_EFRMTOOSHORT; - } - - pj_memcpy( and_media_data->dec_buf + whole_len, - (pj_uint8_t*)packets[i].buf, - packets[i].size); - whole_len += packets[i].size; - } - status = and_media_decode(codec, and_media_data, - and_media_data->dec_buf, whole_len, 0, - &packets[0].timestamp, PJ_TRUE, output); - - if (status != PJ_SUCCESS) - return status; + for (i = 0; i < count; ++i) { + if (whole_len + packets[i].size > and_media_data->dec_buf_size) { + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]")); + return PJMEDIA_CODEC_EFRMTOOSHORT; + } + + pj_memcpy( and_media_data->dec_buf + whole_len, + (pj_uint8_t*)packets[i].buf, + packets[i].size); + whole_len += packets[i].size; + } + status = and_media_decode(codec, and_media_data, + and_media_data->dec_buf, whole_len, 0, + &packets[0].timestamp, PJ_TRUE, output); + + if (status != PJ_SUCCESS) + return status; } else { - for (i = 0; i < count; ++i) { - unsigned desc_len; - unsigned packet_size = packets[i].size; - pj_status_t status; - pj_bool_t write_output; + for (i = 0; i < count; ++i) { + unsigned desc_len; + unsigned packet_size = packets[i].size; + pj_status_t status; + pj_bool_t write_output; status = pjmedia_vpx_unpacketize(vpx_data->pktz, - (pj_uint8_t *)packets[i].buf, + (pj_uint8_t *)packets[i].buf, packet_size, &desc_len); - if (status != PJ_SUCCESS) { - PJ_LOG(4,(THIS_FILE, "Unpacketize error packet size[%d]", - packet_size)); - return status; - } - - packet_size -= desc_len; - if (whole_len + packet_size > and_media_data->dec_buf_size) { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [2]")); - return PJMEDIA_CODEC_EFRMTOOSHORT; + if (status != PJ_SUCCESS) { + PJ_LOG(4,(THIS_FILE, "Unpacketize error packet size[%d]", + packet_size)); + return status; + } + + packet_size -= desc_len; + if (whole_len + packet_size > and_media_data->dec_buf_size) { + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [2]")); + return PJMEDIA_CODEC_EFRMTOOSHORT; } - write_output = (i == count - 1); + write_output = (i == count - 1); - status = and_media_decode(codec, and_media_data, - (pj_uint8_t *)packets[i].buf + desc_len, - packet_size, 0, &packets[0].timestamp, - write_output, output); - if (status != PJ_SUCCESS) - return status; + status = and_media_decode(codec, and_media_data, + (pj_uint8_t *)packets[i].buf + desc_len, + packet_size, 0, &packets[0].timestamp, + write_output, output); + if (status != PJ_SUCCESS) + return status; - whole_len += packet_size; - } + whole_len += packet_size; + } } return PJ_SUCCESS; } #endif -#endif /* PJMEDIA_HAS_ANDROID_MEDIACODEC */ +#endif /* PJMEDIA_HAS_ANDROID_MEDIACODEC */ diff --git a/pjmedia/src/pjmedia-codec/audio_codecs.c b/pjmedia/src/pjmedia-codec/audio_codecs.c index 0a2dc952ca..0405d2994a 100644 --- a/pjmedia/src/pjmedia-codec/audio_codecs.c +++ b/pjmedia/src/pjmedia-codec/audio_codecs.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011-2011 Teluu Inc. (http://www.teluu.com) * @@ -38,8 +37,8 @@ pjmedia_codec_register_audio_codecs(pjmedia_endpt *endpt, PJ_ASSERT_RETURN(endpt, PJ_EINVAL); if (!c) { - pjmedia_audio_codec_config_default(&default_cfg); - c = &default_cfg; + pjmedia_audio_codec_config_default(&default_cfg); + c = &default_cfg; } PJ_ASSERT_RETURN(c->ilbc.mode==20 || c->ilbc.mode==30, PJ_EINVAL); @@ -48,99 +47,99 @@ pjmedia_codec_register_audio_codecs(pjmedia_endpt *endpt, /* Register Android MediaCodec */ status = pjmedia_codec_and_media_aud_init(endpt); if (status != PJ_SUCCESS) { - return status; + return status; } #endif #if PJMEDIA_HAS_PASSTHROUGH_CODECS status = pjmedia_codec_passthrough_init2(endpt, &c->passthrough.setting); if (status != PJ_SUCCESS) - return status; + return status; #endif #if PJMEDIA_HAS_SPEEX_CODEC /* Register speex. */ status = pjmedia_codec_speex_init(endpt, c->speex.option, - c->speex.quality, - c->speex.complexity); + c->speex.quality, + c->speex.complexity); if (status != PJ_SUCCESS) - return status; + return status; #endif #if PJMEDIA_HAS_ILBC_CODEC /* Register iLBC. */ status = pjmedia_codec_ilbc_init( endpt, c->ilbc.mode); if (status != PJ_SUCCESS) - return status; + return status; #endif /* PJMEDIA_HAS_ILBC_CODEC */ #if PJMEDIA_HAS_GSM_CODEC /* Register GSM */ status = pjmedia_codec_gsm_init(endpt); if (status != PJ_SUCCESS) - return status; + return status; #endif /* PJMEDIA_HAS_GSM_CODEC */ #if PJMEDIA_HAS_G711_CODEC /* Register PCMA and PCMU */ status = pjmedia_codec_g711_init(endpt); if (status != PJ_SUCCESS) - return status; -#endif /* PJMEDIA_HAS_G711_CODEC */ + return status; +#endif /* PJMEDIA_HAS_G711_CODEC */ #if PJMEDIA_HAS_G722_CODEC status = pjmedia_codec_g722_init(endpt ); if (status != PJ_SUCCESS) - return status; + return status; #endif /* PJMEDIA_HAS_G722_CODEC */ #if PJMEDIA_HAS_INTEL_IPP /* Register IPP codecs */ status = pjmedia_codec_ipp_init(endpt); if (status != PJ_SUCCESS) - return status; + return status; #endif /* PJMEDIA_HAS_INTEL_IPP */ #if PJMEDIA_HAS_G7221_CODEC /* Register G722.1 codecs */ status = pjmedia_codec_g7221_init(endpt); if (status != PJ_SUCCESS) - return status; + return status; #endif /* PJMEDIA_HAS_G7221_CODEC */ #if PJMEDIA_HAS_L16_CODEC /* Register L16 family codecs */ status = pjmedia_codec_l16_init(endpt, 0); if (status != PJ_SUCCESS) - return status; -#endif /* PJMEDIA_HAS_L16_CODEC */ + return status; +#endif /* PJMEDIA_HAS_L16_CODEC */ #if PJMEDIA_HAS_OPENCORE_AMRNB_CODEC || PJMEDIA_HAS_OPENCORE_AMRWB_CODEC /* Register OpenCORE AMR */ status = pjmedia_codec_opencore_amr_init(endpt, 0); if (status != PJ_SUCCESS) - return status; + return status; #endif #if PJMEDIA_HAS_SILK_CODEC /* Register SILK */ status = pjmedia_codec_silk_init(endpt); if (status != PJ_SUCCESS) - return status; + return status; #endif #if PJMEDIA_HAS_OPUS_CODEC /* Register OPUS */ status = pjmedia_codec_opus_init(endpt); if (status != PJ_SUCCESS) - return status; + return status; #endif #if PJMEDIA_HAS_BCG729 /* Register BCG729 */ status = pjmedia_codec_bcg729_init(endpt); if (status != PJ_SUCCESS) - return status; + return status; #endif return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia-codec/bcg729.c b/pjmedia/src/pjmedia-codec/bcg729.c index f75187ea4d..c432393adb 100644 --- a/pjmedia/src/pjmedia-codec/bcg729.c +++ b/pjmedia/src/pjmedia-codec/bcg729.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2017 Teluu Inc. (http://www.teluu.com) * @@ -32,58 +31,58 @@ #include #include -#define THIS_FILE "bcg729.c" +#define THIS_FILE "bcg729.c" /* Prototypes for BCG729 factory */ static pj_status_t bcg729_test_alloc(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id); + const pjmedia_codec_info *id); static pj_status_t bcg729_default_attr(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr); static pj_status_t bcg729_enum_codecs (pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t bcg729_alloc_codec(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t bcg729_dealloc_codec(pjmedia_codec_factory *factory, - pjmedia_codec *codec); + pjmedia_codec *codec); /* Prototypes for BCG729 implementation. */ static pj_status_t bcg729_codec_init(pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t bcg729_codec_open(pjmedia_codec *codec, - pjmedia_codec_param *attr); + pjmedia_codec_param *attr); static pj_status_t bcg729_codec_close(pjmedia_codec *codec); static pj_status_t bcg729_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr); + const pjmedia_codec_param *attr); static pj_status_t bcg729_codec_parse(pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *timestamp, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *timestamp, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t bcg729_codec_encode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t bcg729_codec_decode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t bcg729_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); /* Codec const. */ -#define G729_TAG "G729" -#define G729_CLOCK_RATE 8000 -#define G729_CHANNEL_COUNT 1 -#define G729_SAMPLES_PER_FRAME 80 -#define G729_DEFAULT_BIT_RATE 8000 -#define G729_MAX_BIT_RATE 11800 -#define G729_FRAME_PER_PACKET 2 -#define G729_FRAME_SIZE 10 +#define G729_TAG "G729" +#define G729_CLOCK_RATE 8000 +#define G729_CHANNEL_COUNT 1 +#define G729_SAMPLES_PER_FRAME 80 +#define G729_DEFAULT_BIT_RATE 8000 +#define G729_MAX_BIT_RATE 11800 +#define G729_FRAME_PER_PACKET 2 +#define G729_FRAME_SIZE 10 /* Definition for BCG729 codec operations. */ static pjmedia_codec_op bcg729_op = @@ -113,23 +112,23 @@ static pjmedia_codec_factory_op bcg729_factory_op = /* BCG729 factory private data */ static struct bcg729_factory { - pjmedia_codec_factory base; - pjmedia_endpt *endpt; - pj_pool_t *pool; - pj_mutex_t *mutex; + pjmedia_codec_factory base; + pjmedia_endpt *endpt; + pj_pool_t *pool; + pj_mutex_t *mutex; } bcg729_factory; /* BCG729 codec private data. */ typedef struct bcg729_private { - pj_pool_t *pool; /**< Pool for each instance. */ + pj_pool_t *pool; /**< Pool for each instance. */ - bcg729EncoderChannelContextStruct *encoder; - bcg729DecoderChannelContextStruct *decoder; + bcg729EncoderChannelContextStruct *encoder; + bcg729DecoderChannelContextStruct *decoder; - pj_bool_t vad_enabled; - pj_bool_t plc_enabled; + pj_bool_t vad_enabled; + pj_bool_t plc_enabled; } bcg729_private; @@ -139,8 +138,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_bcg729_init(pjmedia_endpt *endpt) pj_status_t status; if (bcg729_factory.endpt != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } /* Init factory */ @@ -151,40 +150,40 @@ PJ_DEF(pj_status_t) pjmedia_codec_bcg729_init(pjmedia_endpt *endpt) /* Create pool */ bcg729_factory.pool = pjmedia_endpt_create_pool(endpt, "bcg729", 4000, - 4000); + 4000); if (!bcg729_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create mutex. */ status = pj_mutex_create_simple(bcg729_factory.pool, "bcg729", - &bcg729_factory.mutex); + &bcg729_factory.mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - status = PJ_EINVALIDOP; - goto on_error; + status = PJ_EINVALIDOP; + goto on_error; } /* Register codec factory to endpoint. */ status = pjmedia_codec_mgr_register_factory(codec_mgr, - &bcg729_factory.base); + &bcg729_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; PJ_LOG(4,(THIS_FILE, "BCG729 codec initialized")); return PJ_SUCCESS; on_error: if (bcg729_factory.mutex) { - pj_mutex_destroy(bcg729_factory.mutex); - bcg729_factory.mutex = NULL; + pj_mutex_destroy(bcg729_factory.mutex); + bcg729_factory.mutex = NULL; } if (bcg729_factory.pool) { - pj_pool_release(bcg729_factory.pool); - bcg729_factory.pool = NULL; + pj_pool_release(bcg729_factory.pool); + bcg729_factory.pool = NULL; } return status; @@ -200,8 +199,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_bcg729_deinit(void) pj_status_t status; if (bcg729_factory.endpt == NULL) { - /* Not registered. */ - return PJ_SUCCESS; + /* Not registered. */ + return PJ_SUCCESS; } /* Lock mutex. */ @@ -210,14 +209,14 @@ PJ_DEF(pj_status_t) pjmedia_codec_bcg729_deinit(void) /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(bcg729_factory.endpt); if (!codec_mgr) { - bcg729_factory.endpt = NULL; - pj_mutex_unlock(bcg729_factory.mutex); - return PJ_EINVALIDOP; + bcg729_factory.endpt = NULL; + pj_mutex_unlock(bcg729_factory.mutex); + return PJ_EINVALIDOP; } /* Unregister bcg729 codec factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &bcg729_factory.base); + &bcg729_factory.base); bcg729_factory.endpt = NULL; /* Destroy mutex. */ @@ -237,7 +236,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_bcg729_deinit(void) * Check if factory can allocate the specified codec. */ static pj_status_t bcg729_test_alloc(pjmedia_codec_factory *factory, - const pjmedia_codec_info *info ) + const pjmedia_codec_info *info ) { pj_str_t g729_tag = pj_str(G729_TAG); PJ_UNUSED_ARG(factory); @@ -245,19 +244,19 @@ static pj_status_t bcg729_test_alloc(pjmedia_codec_factory *factory, /* Type MUST be audio. */ if (info->type != PJMEDIA_TYPE_AUDIO) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check encoding name. */ if (pj_stricmp(&info->encoding_name, &g729_tag) != 0) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Channel count must be one */ if (info->channel_cnt != G729_CHANNEL_COUNT) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check clock-rate */ if (info->clock_rate != G729_CLOCK_RATE) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; return PJ_SUCCESS; } @@ -267,13 +266,13 @@ static pj_status_t bcg729_test_alloc(pjmedia_codec_factory *factory, * Generate default attribute. */ static pj_status_t bcg729_default_attr(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ) { PJ_ASSERT_RETURN(factory==&bcg729_factory.base, PJ_EINVAL); if (id->pt != PJMEDIA_RTP_PT_G729) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; pj_bzero(attr, sizeof(pjmedia_codec_param)); attr->info.pt = PJMEDIA_RTP_PT_G729; @@ -284,9 +283,9 @@ static pj_status_t bcg729_default_attr(pjmedia_codec_factory *factory, attr->info.pcm_bits_per_sample = G729_FRAME_PER_PACKET * 8; attr->info.frm_ptime = (pj_uint16_t) - (G729_SAMPLES_PER_FRAME * 1000 / - G729_CHANNEL_COUNT / - G729_CLOCK_RATE); + (G729_SAMPLES_PER_FRAME * 1000 / + G729_CHANNEL_COUNT / + G729_CLOCK_RATE); attr->setting.frm_per_pkt = G729_FRAME_PER_PACKET; /* Default flags. */ @@ -296,9 +295,9 @@ static pj_status_t bcg729_default_attr(pjmedia_codec_factory *factory, attr->setting.cng = attr->setting.vad; if (attr->setting.vad == 0) { - attr->setting.dec_fmtp.cnt = 1; - pj_strset2(&attr->setting.dec_fmtp.param[0].name, "annexb"); - pj_strset2(&attr->setting.dec_fmtp.param[0].val, "no"); + attr->setting.dec_fmtp.cnt = 1; + pj_strset2(&attr->setting.dec_fmtp.param[0].name, "annexb"); + pj_strset2(&attr->setting.dec_fmtp.param[0].val, "no"); } return PJ_SUCCESS; } @@ -308,8 +307,8 @@ static pj_status_t bcg729_default_attr(pjmedia_codec_factory *factory, * Enum codecs supported by this factory. */ static pj_status_t bcg729_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]) + unsigned *count, + pjmedia_codec_info codecs[]) { PJ_ASSERT_RETURN(factory==&bcg729_factory.base, PJ_EINVAL); PJ_ASSERT_RETURN(codecs && *count > 0, PJ_EINVAL); @@ -331,8 +330,8 @@ static pj_status_t bcg729_enum_codecs(pjmedia_codec_factory *factory, * Allocate a new BCG729 codec instance. */ static pj_status_t bcg729_alloc_codec(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { pj_pool_t *pool; pjmedia_codec *codec; @@ -365,7 +364,7 @@ static pj_status_t bcg729_alloc_codec(pjmedia_codec_factory *factory, * Free codec. */ static pj_status_t bcg729_dealloc_codec(pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { bcg729_private *bcg729_data; @@ -376,7 +375,7 @@ static pj_status_t bcg729_dealloc_codec(pjmedia_codec_factory *factory, /* Close codec, if it's not closed. */ if (bcg729_data->encoder || bcg729_data->decoder) { - bcg729_codec_close(codec); + bcg729_codec_close(codec); } pj_pool_release(bcg729_data->pool); @@ -389,7 +388,7 @@ static pj_status_t bcg729_dealloc_codec(pjmedia_codec_factory *factory, * Init codec. */ static pj_status_t bcg729_codec_init(pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(pool); @@ -401,7 +400,7 @@ static pj_status_t bcg729_codec_init(pjmedia_codec *codec, * Open codec. */ static pj_status_t bcg729_codec_open(pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { bcg729_private *bcg729_data; unsigned i; @@ -412,26 +411,26 @@ static pj_status_t bcg729_codec_open(pjmedia_codec *codec, /* Already open? */ if (bcg729_data->encoder && bcg729_data->decoder) - return PJ_SUCCESS; + return PJ_SUCCESS; bcg729_data->vad_enabled = (attr->setting.vad != 0); bcg729_data->plc_enabled = (attr->setting.plc != 0); /* Check if G729 Annex B is signaled to be disabled */ for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { - if (pj_stricmp2(&attr->setting.enc_fmtp.param[i].name, "annexb")==0) - { - if (pj_stricmp2(&attr->setting.enc_fmtp.param[i].val, "no")==0) - { - attr->setting.vad = 0; - bcg729_data->vad_enabled = PJ_FALSE; - } - break; - } + if (pj_stricmp2(&attr->setting.enc_fmtp.param[i].name, "annexb")==0) + { + if (pj_stricmp2(&attr->setting.enc_fmtp.param[i].val, "no")==0) + { + attr->setting.vad = 0; + bcg729_data->vad_enabled = PJ_FALSE; + } + break; + } } bcg729_data->encoder = initBcg729EncoderChannel( - bcg729_data->vad_enabled?1:0); + bcg729_data->vad_enabled?1:0); if (!bcg729_data->encoder) return PJMEDIA_CODEC_EFAILED; @@ -471,11 +470,11 @@ static pj_status_t bcg729_codec_close( pjmedia_codec *codec ) * Get frames in the packet. */ static pj_status_t bcg729_codec_parse(pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { unsigned count = 0; PJ_UNUSED_ARG(codec); @@ -503,7 +502,7 @@ static pj_status_t bcg729_codec_parse(pjmedia_codec *codec, * Modify codec settings. */ static pj_status_t bcg729_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(attr); @@ -516,9 +515,9 @@ static pj_status_t bcg729_codec_modify(pjmedia_codec *codec, * Encode frame. */ static pj_status_t bcg729_codec_encode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { bcg729_private *bcg729_data; pj_int16_t *pcm_in; @@ -539,19 +538,19 @@ static pj_status_t bcg729_codec_encode(pjmedia_codec *codec, bcg729Encoder(bcg729_data->encoder, pcm_in, (unsigned char*)output->buf + output->size, &stream_len); - pcm_in += G729_SAMPLES_PER_FRAME; - nsamples -= G729_SAMPLES_PER_FRAME; - - if (stream_len == 0) { - /* Untransmitted */ - break; - } else { - output->size += stream_len; - if (stream_len == 2) { - /* SID */ - break; + pcm_in += G729_SAMPLES_PER_FRAME; + nsamples -= G729_SAMPLES_PER_FRAME; + + if (stream_len == 0) { + /* Untransmitted */ + break; + } else { + output->size += stream_len; + if (stream_len == 2) { + /* SID */ + break; } - } + } } output->type = PJMEDIA_FRAME_TYPE_AUDIO; @@ -562,9 +561,9 @@ static pj_status_t bcg729_codec_encode(pjmedia_codec *codec, static pj_status_t bcg729_codec_decode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { bcg729_private *bcg729_data; @@ -592,8 +591,8 @@ static pj_status_t bcg729_codec_decode(pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t bcg729_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { bcg729_private *bcg729_data; @@ -605,15 +604,15 @@ static pj_status_t bcg729_codec_recover(pjmedia_codec *codec, output->type = PJMEDIA_FRAME_TYPE_AUDIO; if (bcg729_data->plc_enabled) { - bcg729Decoder(bcg729_data->decoder, - NULL, - G729_FRAME_SIZE, - 1, - 0, - 0, - (short*)output->buf); + bcg729Decoder(bcg729_data->decoder, + NULL, + G729_FRAME_SIZE, + 1, + 0, + 0, + (short*)output->buf); } else { - pjmedia_zero_samples((pj_int16_t*)output->buf, G729_SAMPLES_PER_FRAME); + pjmedia_zero_samples((pj_int16_t*)output->buf, G729_SAMPLES_PER_FRAME); } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia-codec/ffmpeg_vid_codecs.c b/pjmedia/src/pjmedia-codec/ffmpeg_vid_codecs.c index 652839e900..8f0cf6d70a 100644 --- a/pjmedia/src/pjmedia-codec/ffmpeg_vid_codecs.c +++ b/pjmedia/src/pjmedia-codec/ffmpeg_vid_codecs.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * @@ -53,28 +52,28 @@ /* Various compatibility */ #if LIBAVCODEC_VER_AT_LEAST(53,20) -# define AVCODEC_OPEN(ctx,c) avcodec_open2(ctx,c,NULL) +# define AVCODEC_OPEN(ctx,c) avcodec_open2(ctx,c,NULL) #else -# define AVCODEC_OPEN(ctx,c) avcodec_open(ctx,c) +# define AVCODEC_OPEN(ctx,c) avcodec_open(ctx,c) #endif #if LIBAVCODEC_VER_AT_LEAST(53,61) # if LIBAVCODEC_VER_AT_LEAST(54,59) /* Not sure when AVCodec::encode is obsoleted/removed. */ -# define AVCODEC_HAS_ENCODE(c) (c->encode2) +# define AVCODEC_HAS_ENCODE(c) (c->encode2) # else /* Not sure when AVCodec::encode2 is introduced. It appears in * libavcodec 53.61 where some codecs actually still use AVCodec::encode * (e.g: H263, H264). */ -# define AVCODEC_HAS_ENCODE(c) (c->encode || c->encode2) +# define AVCODEC_HAS_ENCODE(c) (c->encode || c->encode2) # endif -# define AV_OPT_SET(obj,name,val,opt) (av_opt_set(obj,name,val,opt)==0) -# define AV_OPT_SET_INT(obj,name,val) (av_opt_set_int(obj,name,val,0)==0) +# define AV_OPT_SET(obj,name,val,opt) (av_opt_set(obj,name,val,opt)==0) +# define AV_OPT_SET_INT(obj,name,val) (av_opt_set_int(obj,name,val,0)==0) #else -# define AVCODEC_HAS_ENCODE(c) (c->encode) -# define AV_OPT_SET(obj,name,val,opt) (av_set_string3(obj,name,val,opt,NULL)==0) -# define AV_OPT_SET_INT(obj,name,val) (av_set_int(obj,name,val)!=NULL) +# define AVCODEC_HAS_ENCODE(c) (c->encode) +# define AV_OPT_SET(obj,name,val,opt) (av_set_string3(obj,name,val,opt,NULL)==0) +# define AV_OPT_SET_INT(obj,name,val) (av_set_int(obj,name,val)!=NULL) #endif #define AVCODEC_HAS_DECODE(c) (c->decode) @@ -83,44 +82,44 @@ /* Prototypes for FFMPEG codecs factory */ static pj_status_t ffmpeg_test_alloc( pjmedia_vid_codec_factory *factory, - const pjmedia_vid_codec_info *id ); + const pjmedia_vid_codec_info *id ); static pj_status_t ffmpeg_default_attr( pjmedia_vid_codec_factory *factory, - const pjmedia_vid_codec_info *info, - pjmedia_vid_codec_param *attr ); + const pjmedia_vid_codec_info *info, + pjmedia_vid_codec_param *attr ); static pj_status_t ffmpeg_enum_codecs( pjmedia_vid_codec_factory *factory, - unsigned *count, - pjmedia_vid_codec_info codecs[]); + unsigned *count, + pjmedia_vid_codec_info codecs[]); static pj_status_t ffmpeg_alloc_codec( pjmedia_vid_codec_factory *factory, - const pjmedia_vid_codec_info *info, - pjmedia_vid_codec **p_codec); + const pjmedia_vid_codec_info *info, + pjmedia_vid_codec **p_codec); static pj_status_t ffmpeg_dealloc_codec( pjmedia_vid_codec_factory *factory, - pjmedia_vid_codec *codec ); + pjmedia_vid_codec *codec ); /* Prototypes for FFMPEG codecs implementation. */ static pj_status_t ffmpeg_codec_init( pjmedia_vid_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t ffmpeg_codec_open( pjmedia_vid_codec *codec, - pjmedia_vid_codec_param *attr ); + pjmedia_vid_codec_param *attr ); static pj_status_t ffmpeg_codec_close( pjmedia_vid_codec *codec ); static pj_status_t ffmpeg_codec_modify(pjmedia_vid_codec *codec, - const pjmedia_vid_codec_param *attr ); + const pjmedia_vid_codec_param *attr ); static pj_status_t ffmpeg_codec_get_param(pjmedia_vid_codec *codec, - pjmedia_vid_codec_param *param); + pjmedia_vid_codec_param *param); static pj_status_t ffmpeg_codec_encode_begin(pjmedia_vid_codec *codec, - const pjmedia_vid_encode_opt *opt, + const pjmedia_vid_encode_opt *opt, const pjmedia_frame *input, - unsigned out_size, - pjmedia_frame *output, - pj_bool_t *has_more); + unsigned out_size, + pjmedia_frame *output, + pj_bool_t *has_more); static pj_status_t ffmpeg_codec_encode_more(pjmedia_vid_codec *codec, - unsigned out_size, - pjmedia_frame *output, - pj_bool_t *has_more); + unsigned out_size, + pjmedia_frame *output, + pj_bool_t *has_more); static pj_status_t ffmpeg_codec_decode( pjmedia_vid_codec *codec, - pj_size_t pkt_count, - pjmedia_frame packets[], - unsigned out_size, - pjmedia_frame *output); + pj_size_t pkt_count, + pjmedia_frame packets[], + unsigned out_size, + pjmedia_frame *output); /* Definition for FFMPEG codecs operations. */ static pjmedia_vid_codec_op ffmpeg_op = @@ -150,10 +149,10 @@ static pjmedia_vid_codec_factory_op ffmpeg_factory_op = /* FFMPEG codecs factory */ static struct ffmpeg_factory { pjmedia_vid_codec_factory base; - pjmedia_vid_codec_mgr *mgr; + pjmedia_vid_codec_mgr *mgr; pj_pool_factory *pf; - pj_pool_t *pool; - pj_mutex_t *mutex; + pj_pool_t *pool; + pj_mutex_t *mutex; } ffmpeg_factory; @@ -163,9 +162,9 @@ typedef struct ffmpeg_codec_desc ffmpeg_codec_desc; /* FFMPEG codecs private data. */ typedef struct ffmpeg_private { - const ffmpeg_codec_desc *desc; - pjmedia_vid_codec_param param; /**< Codec param */ - pj_pool_t *pool; /**< Pool for each instance */ + const ffmpeg_codec_desc *desc; + pjmedia_vid_codec_param param; /**< Codec param */ + pj_pool_t *pool; /**< Pool for each instance */ /* Format info and apply format param */ const pjmedia_video_format_info *enc_vfi; @@ -174,30 +173,30 @@ typedef struct ffmpeg_private pjmedia_video_apply_fmt_param dec_vafp; /* Buffers, only needed for multi-packets */ - pj_bool_t whole; - void *enc_buf; - unsigned enc_buf_size; - pj_bool_t enc_buf_is_keyframe; - unsigned enc_frame_len; - unsigned enc_processed; - void *dec_buf; - unsigned dec_buf_size; - pj_timestamp last_dec_keyframe_ts; + pj_bool_t whole; + void *enc_buf; + unsigned enc_buf_size; + pj_bool_t enc_buf_is_keyframe; + unsigned enc_frame_len; + unsigned enc_processed; + void *dec_buf; + unsigned dec_buf_size; + pj_timestamp last_dec_keyframe_ts; /* The ffmpeg codec states. */ - AVCodec *enc; - AVCodec *dec; - AVCodecContext *enc_ctx; - AVCodecContext *dec_ctx; + AVCodec *enc; + AVCodec *dec; + AVCodecContext *enc_ctx; + AVCodecContext *dec_ctx; /* The ffmpeg decoder cannot set the output format, so format conversion * may be needed for post-decoding. */ - enum AVPixelFormat expected_dec_fmt; - /**< Expected output format of - ffmpeg decoder */ + enum AVPixelFormat expected_dec_fmt; + /**< Expected output format of + ffmpeg decoder */ - void *data; /**< Codec specific data */ + void *data; /**< Codec specific data */ } ffmpeg_private; @@ -206,26 +205,26 @@ typedef struct ffmpeg_private */ #define FUNC_PACKETIZE(name) \ pj_status_t(name)(ffmpeg_private *ff, pj_uint8_t *bits, \ - pj_size_t bits_len, unsigned *bits_pos, \ - pj_uint8_t *payload, pj_size_t *payload_len, pj_bool_t is_keyframe) + pj_size_t bits_len, unsigned *bits_pos, \ + pj_uint8_t *payload, pj_size_t *payload_len, pj_bool_t is_keyframe) #define FUNC_UNPACKETIZE(name) \ pj_status_t(name)(ffmpeg_private *ff, const pj_uint8_t *payload, \ - pj_size_t payload_len, pj_uint8_t *bits, \ - pj_size_t bits_len, unsigned *bits_pos) + pj_size_t payload_len, pj_uint8_t *bits, \ + pj_size_t bits_len, unsigned *bits_pos) #define FUNC_FMT_MATCH(name) \ pj_status_t(name)(pj_pool_t *pool, \ - pjmedia_sdp_media *offer, unsigned o_fmt_idx, \ - pjmedia_sdp_media *answer, unsigned a_fmt_idx, \ - unsigned option) + pjmedia_sdp_media *offer, unsigned o_fmt_idx, \ + pjmedia_sdp_media *answer, unsigned a_fmt_idx, \ + unsigned option) /* Type definition of codec specific functions */ typedef FUNC_PACKETIZE(*func_packetize); typedef FUNC_UNPACKETIZE(*func_unpacketize); -typedef pj_status_t (*func_preopen) (ffmpeg_private *ff); -typedef pj_status_t (*func_postopen) (ffmpeg_private *ff); +typedef pj_status_t (*func_preopen) (ffmpeg_private *ff); +typedef pj_status_t (*func_postopen) (ffmpeg_private *ff); typedef FUNC_FMT_MATCH(*func_sdp_fmt_match); @@ -234,25 +233,25 @@ struct ffmpeg_codec_desc { /* Predefined info */ pjmedia_vid_codec_info info; - pjmedia_format_id base_fmt_id; /**< Some codecs may be exactly - same or compatible with - another codec, base format - will tell the initializer - to copy this codec desc - from its base format */ + pjmedia_format_id base_fmt_id; /**< Some codecs may be exactly + same or compatible with + another codec, base format + will tell the initializer + to copy this codec desc + from its base format */ pjmedia_rect_size size; pjmedia_ratio fps; - pj_uint32_t avg_bps; - pj_uint32_t max_bps; - func_packetize packetize; - func_unpacketize unpacketize; - func_preopen preopen; - func_preopen postopen; - func_sdp_fmt_match sdp_fmt_match; - pjmedia_codec_fmtp dec_fmtp; + pj_uint32_t avg_bps; + pj_uint32_t max_bps; + func_packetize packetize; + func_unpacketize unpacketize; + func_preopen preopen; + func_preopen postopen; + func_sdp_fmt_match sdp_fmt_match; + pjmedia_codec_fmtp dec_fmtp; /* Init time defined info */ - pj_bool_t enabled; + pj_bool_t enabled; AVCodec *enc; AVCodec *dec; }; @@ -263,8 +262,8 @@ struct ffmpeg_codec_desc #endif /* H264 constants */ -#define PROFILE_H264_BASELINE 66 -#define PROFILE_H264_MAIN 77 +#define PROFILE_H264_BASELINE 66 +#define PROFILE_H264_MAIN 77 /* Codec specific functions */ #if PJMEDIA_HAS_FFMPEG_CODEC_VP8 || PJMEDIA_HAS_FFMPEG_CODEC_VP9 @@ -291,66 +290,66 @@ static ffmpeg_codec_desc codec_desc[] = { #if PJMEDIA_HAS_FFMPEG_CODEC_H264 { - {PJMEDIA_FORMAT_H264, AVC_H264_PT, {"H264",4}, - {"Constrained Baseline (level=30, pack=1)", 39}}, - 0, - {720, 480}, {15, 1}, 256000, 256000, - &h264_packetize, &h264_unpacketize, &h264_preopen, &h264_postopen, - &pjmedia_vid_codec_h264_match_sdp, - /* Leading space for better compatibility (strange indeed!) */ - {2, { {{"profile-level-id",16}, {"42e01e",6}}, - {{" packetization-mode",19}, {"1",1}}, } }, + {PJMEDIA_FORMAT_H264, AVC_H264_PT, {"H264",4}, + {"Constrained Baseline (level=30, pack=1)", 39}}, + 0, + {720, 480}, {15, 1}, 256000, 256000, + &h264_packetize, &h264_unpacketize, &h264_preopen, &h264_postopen, + &pjmedia_vid_codec_h264_match_sdp, + /* Leading space for better compatibility (strange indeed!) */ + {2, { {{"profile-level-id",16}, {"42e01e",6}}, + {{" packetization-mode",19}, {"1",1}}, } }, }, #endif #if PJMEDIA_HAS_FFMPEG_CODEC_VP8 { - {PJMEDIA_FORMAT_VP8, PJMEDIA_RTP_PT_VP8_RSV2, {"VP8",3}, - {"FF VP8", 6}}, - 0, - {720, 480}, {15, 1}, 256000, 256000, - &vpx_packetize, &vpx_unpacketize, &vpx_preopen, &vpx_postopen, NULL, - {2, { {{"max-fr",6}, {"30",2}}, - {{" max-fs",7}, {"580",3}}, } }, + {PJMEDIA_FORMAT_VP8, PJMEDIA_RTP_PT_VP8_RSV2, {"VP8",3}, + {"FF VP8", 6}}, + 0, + {720, 480}, {15, 1}, 256000, 256000, + &vpx_packetize, &vpx_unpacketize, &vpx_preopen, &vpx_postopen, NULL, + {2, { {{"max-fr",6}, {"30",2}}, + {{" max-fs",7}, {"580",3}}, } }, }, #endif #if PJMEDIA_HAS_FFMPEG_CODEC_VP9 { - {PJMEDIA_FORMAT_VP9, PJMEDIA_RTP_PT_VP9_RSV2, {"VP9",3}, - {"FF VP9", 6}}, - 0, - {720, 480}, {15, 1}, 256000, 256000, - &vpx_packetize, &vpx_unpacketize, &vpx_preopen, &vpx_postopen, NULL, - {2, { {{"max-fr",6}, {"30",2}}, - {{" max-fs",7}, {"580",3}}, } }, + {PJMEDIA_FORMAT_VP9, PJMEDIA_RTP_PT_VP9_RSV2, {"VP9",3}, + {"FF VP9", 6}}, + 0, + {720, 480}, {15, 1}, 256000, 256000, + &vpx_packetize, &vpx_unpacketize, &vpx_preopen, &vpx_postopen, NULL, + {2, { {{"max-fr",6}, {"30",2}}, + {{" max-fs",7}, {"580",3}}, } }, }, #endif #if PJMEDIA_HAS_FFMPEG_CODEC_H263P { - {PJMEDIA_FORMAT_H263P, PJMEDIA_RTP_PT_H263P, {"H263-1998",9}}, - PJMEDIA_FORMAT_H263, - {352, 288}, {15, 1}, 256000, 256000, - &h263_packetize, &h263_unpacketize, &h263_preopen, NULL, NULL, - {2, { {{"CIF",3}, {"1",1}}, - {{"QCIF",4}, {"1",1}}, } }, + {PJMEDIA_FORMAT_H263P, PJMEDIA_RTP_PT_H263P, {"H263-1998",9}}, + PJMEDIA_FORMAT_H263, + {352, 288}, {15, 1}, 256000, 256000, + &h263_packetize, &h263_unpacketize, &h263_preopen, NULL, NULL, + {2, { {{"CIF",3}, {"1",1}}, + {{"QCIF",4}, {"1",1}}, } }, }, #endif { - {PJMEDIA_FORMAT_H263, PJMEDIA_RTP_PT_H263, {"H263",4}}, + {PJMEDIA_FORMAT_H263, PJMEDIA_RTP_PT_H263, {"H263",4}}, }, { - {PJMEDIA_FORMAT_H261, PJMEDIA_RTP_PT_H261, {"H261",4}}, + {PJMEDIA_FORMAT_H261, PJMEDIA_RTP_PT_H261, {"H261",4}}, }, { - {PJMEDIA_FORMAT_MJPEG, PJMEDIA_RTP_PT_JPEG, {"JPEG",4}}, - PJMEDIA_FORMAT_MJPEG, {640, 480}, {25, 1}, + {PJMEDIA_FORMAT_MJPEG, PJMEDIA_RTP_PT_JPEG, {"JPEG",4}}, + PJMEDIA_FORMAT_MJPEG, {640, 480}, {25, 1}, }, { - {PJMEDIA_FORMAT_MPEG4, 0, {"MP4V",4}}, - PJMEDIA_FORMAT_MPEG4, {640, 480}, {25, 1}, + {PJMEDIA_FORMAT_MPEG4, 0, {"MP4V",4}}, + PJMEDIA_FORMAT_MPEG4, {640, 480}, {25, 1}, }, }; @@ -454,8 +453,8 @@ static FUNC_UNPACKETIZE(vpx_unpacketize) typedef struct h264_data { - pjmedia_vid_codec_h264_fmtp fmtp; - pjmedia_h264_packetizer *pktz; + pjmedia_vid_codec_h264_fmtp fmtp; + pjmedia_h264_packetizer *pktz; } h264_data; @@ -470,27 +469,27 @@ static pj_status_t h264_preopen(ffmpeg_private *ff) /* Parse remote fmtp */ status = pjmedia_vid_codec_h264_parse_fmtp(&ff->param.enc_fmtp, - &data->fmtp); + &data->fmtp); if (status != PJ_SUCCESS) - return status; + return status; /* Create packetizer */ pktz_cfg.mtu = ff->param.enc_mtu; pktz_cfg.unpack_nal_start = 0; #if 0 if (data->fmtp.packetization_mode == 0) - pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL; + pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL; else if (data->fmtp.packetization_mode == 1) - pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED; + pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED; else - return PJ_ENOTSUP; + return PJ_ENOTSUP; #else if (data->fmtp.packetization_mode!= - PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL && - data->fmtp.packetization_mode!= - PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED) + PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL && + data->fmtp.packetization_mode!= + PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED) { - return PJ_ENOTSUP; + return PJ_ENOTSUP; } /* Better always send in single NAL mode for better compatibility */ pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL; @@ -498,92 +497,92 @@ static pj_status_t h264_preopen(ffmpeg_private *ff) status = pjmedia_h264_packetizer_create(ff->pool, &pktz_cfg, &data->pktz); if (status != PJ_SUCCESS) - return status; + return status; /* Apply SDP fmtp to format in codec param */ if (!ff->param.ignore_fmtp) { - status = pjmedia_vid_codec_h264_apply_fmtp(&ff->param); - if (status != PJ_SUCCESS) - return status; + status = pjmedia_vid_codec_h264_apply_fmtp(&ff->param); + if (status != PJ_SUCCESS) + return status; } if (ff->param.dir & PJMEDIA_DIR_ENCODING) { - pjmedia_video_format_detail *vfd; - AVCodecContext *ctx = ff->enc_ctx; - const char *profile = NULL; - - vfd = pjmedia_format_get_video_format_detail(&ff->param.enc_fmt, - PJ_TRUE); - - /* Override generic params after applying SDP fmtp */ - ctx->width = vfd->size.w; - ctx->height = vfd->size.h; - ctx->time_base.num = vfd->fps.denum; - ctx->time_base.den = vfd->fps.num; - - /* Apply profile. */ - ctx->profile = data->fmtp.profile_idc; - switch (ctx->profile) { - case PROFILE_H264_BASELINE: - profile = "baseline"; - break; - case PROFILE_H264_MAIN: - profile = "main"; - break; - default: - break; - } - if (profile && !AV_OPT_SET(ctx->priv_data, "profile", profile, 0)) - { - PJ_LOG(3, (THIS_FILE, "Failed to set H264 profile to '%s'", - profile)); - } - - /* Apply profile constraint bits. */ - //PJ_TODO(set_h264_constraint_bits_properly_in_ffmpeg); - if (data->fmtp.profile_iop) { + pjmedia_video_format_detail *vfd; + AVCodecContext *ctx = ff->enc_ctx; + const char *profile = NULL; + + vfd = pjmedia_format_get_video_format_detail(&ff->param.enc_fmt, + PJ_TRUE); + + /* Override generic params after applying SDP fmtp */ + ctx->width = vfd->size.w; + ctx->height = vfd->size.h; + ctx->time_base.num = vfd->fps.denum; + ctx->time_base.den = vfd->fps.num; + + /* Apply profile. */ + ctx->profile = data->fmtp.profile_idc; + switch (ctx->profile) { + case PROFILE_H264_BASELINE: + profile = "baseline"; + break; + case PROFILE_H264_MAIN: + profile = "main"; + break; + default: + break; + } + if (profile && !AV_OPT_SET(ctx->priv_data, "profile", profile, 0)) + { + PJ_LOG(3, (THIS_FILE, "Failed to set H264 profile to '%s'", + profile)); + } + + /* Apply profile constraint bits. */ + //PJ_TODO(set_h264_constraint_bits_properly_in_ffmpeg); + if (data->fmtp.profile_iop) { #if defined(FF_PROFILE_H264_CONSTRAINED) - ctx->profile |= FF_PROFILE_H264_CONSTRAINED; + ctx->profile |= FF_PROFILE_H264_CONSTRAINED; #endif - } - - /* Apply profile level. */ - ctx->level = data->fmtp.level; - - /* Limit NAL unit size as we prefer single NAL unit packetization */ - if (!AV_OPT_SET_INT(ctx->priv_data, "slice-max-size", ff->param.enc_mtu)) - { - PJ_LOG(3, (THIS_FILE, "Failed to set H264 max NAL size to %d", - ff->param.enc_mtu)); - } - - /* Apply intra-refresh */ - if (!AV_OPT_SET_INT(ctx->priv_data, "intra-refresh", 1)) - { - PJ_LOG(3, (THIS_FILE, "Failed to set x264 intra-refresh")); - } - - /* Misc x264 settings (performance, quality, latency, etc). - * Let's just use the x264 predefined preset & tune. - */ - if (!AV_OPT_SET(ctx->priv_data, "preset", "veryfast", 0)) { - PJ_LOG(3, (THIS_FILE, "Failed to set x264 preset 'veryfast'")); - } - if (!AV_OPT_SET(ctx->priv_data, "tune", "animation+zerolatency", 0)) { - PJ_LOG(3, (THIS_FILE, "Failed to set x264 tune 'zerolatency'")); - } + } + + /* Apply profile level. */ + ctx->level = data->fmtp.level; + + /* Limit NAL unit size as we prefer single NAL unit packetization */ + if (!AV_OPT_SET_INT(ctx->priv_data, "slice-max-size", ff->param.enc_mtu)) + { + PJ_LOG(3, (THIS_FILE, "Failed to set H264 max NAL size to %d", + ff->param.enc_mtu)); + } + + /* Apply intra-refresh */ + if (!AV_OPT_SET_INT(ctx->priv_data, "intra-refresh", 1)) + { + PJ_LOG(3, (THIS_FILE, "Failed to set x264 intra-refresh")); + } + + /* Misc x264 settings (performance, quality, latency, etc). + * Let's just use the x264 predefined preset & tune. + */ + if (!AV_OPT_SET(ctx->priv_data, "preset", "veryfast", 0)) { + PJ_LOG(3, (THIS_FILE, "Failed to set x264 preset 'veryfast'")); + } + if (!AV_OPT_SET(ctx->priv_data, "tune", "animation+zerolatency", 0)) { + PJ_LOG(3, (THIS_FILE, "Failed to set x264 tune 'zerolatency'")); + } } if (ff->param.dir & PJMEDIA_DIR_DECODING) { - AVCodecContext *ctx = ff->dec_ctx; - - /* Apply the "sprop-parameter-sets" fmtp from remote SDP to - * extradata of ffmpeg codec context. - */ - if (data->fmtp.sprop_param_sets_len) { - ctx->extradata_size = (int)data->fmtp.sprop_param_sets_len; - ctx->extradata = data->fmtp.sprop_param_sets; - } + AVCodecContext *ctx = ff->dec_ctx; + + /* Apply the "sprop-parameter-sets" fmtp from remote SDP to + * extradata of ffmpeg codec context. + */ + if (data->fmtp.sprop_param_sets_len) { + ctx->extradata_size = (int)data->fmtp.sprop_param_sets_len; + ctx->extradata = data->fmtp.sprop_param_sets; + } } return PJ_SUCCESS; @@ -603,7 +602,7 @@ static FUNC_PACKETIZE(h264_packetize) pj_uint8_t *outbuf = payload; pj_size_t out_size = *payload_len; status = pjmedia_h264_packetize(data->pktz, bits, bits_len, bits_pos, - &payload, payload_len); + &payload, payload_len); if (status != PJ_SUCCESS) return status; if (out_size < *payload_len) @@ -616,7 +615,7 @@ static FUNC_UNPACKETIZE(h264_unpacketize) { h264_data *data = (h264_data*)ff->data; return pjmedia_h264_unpacketize(data->pktz, payload, payload_len, - bits, bits_len, bits_pos); + bits, bits_len, bits_pos); } #endif /* PJMEDIA_HAS_FFMPEG_CODEC_H264 */ @@ -626,7 +625,7 @@ static FUNC_UNPACKETIZE(h264_unpacketize) typedef struct h263_data { - pjmedia_h263_packetizer *pktz; + pjmedia_h263_packetizer *pktz; } h263_data; /* H263 pre-open */ @@ -644,26 +643,26 @@ static pj_status_t h263_preopen(ffmpeg_private *ff) pktz_cfg.mode = PJMEDIA_H263_PACKETIZER_MODE_RFC4629; status = pjmedia_h263_packetizer_create(ff->pool, &pktz_cfg, &data->pktz); if (status != PJ_SUCCESS) - return status; + return status; /* Apply fmtp settings to codec param */ if (!ff->param.ignore_fmtp) { - status = pjmedia_vid_codec_h263_apply_fmtp(&ff->param); + status = pjmedia_vid_codec_h263_apply_fmtp(&ff->param); } /* Override generic params after applying SDP fmtp */ if (ff->param.dir & PJMEDIA_DIR_ENCODING) { - pjmedia_video_format_detail *vfd; - AVCodecContext *ctx = ff->enc_ctx; + pjmedia_video_format_detail *vfd; + AVCodecContext *ctx = ff->enc_ctx; - vfd = pjmedia_format_get_video_format_detail(&ff->param.enc_fmt, - PJ_TRUE); + vfd = pjmedia_format_get_video_format_detail(&ff->param.enc_fmt, + PJ_TRUE); - /* Override generic params after applying SDP fmtp */ - ctx->width = vfd->size.w; - ctx->height = vfd->size.h; - ctx->time_base.num = vfd->fps.denum; - ctx->time_base.den = vfd->fps.num; + /* Override generic params after applying SDP fmtp */ + ctx->width = vfd->size.w; + ctx->height = vfd->size.h; + ctx->time_base.num = vfd->fps.denum; + ctx->time_base.den = vfd->fps.num; } return status; @@ -676,7 +675,7 @@ static FUNC_PACKETIZE(h263_packetize) pj_uint8_t *outbuf = payload; pj_size_t out_size = *payload_len; status = pjmedia_h263_packetize(data->pktz, bits, bits_len, bits_pos, - &payload, payload_len); + &payload, payload_len); if (status != PJ_SUCCESS) return status; if (out_size < *payload_len) @@ -689,25 +688,25 @@ static FUNC_UNPACKETIZE(h263_unpacketize) { h263_data *data = (h263_data*)ff->data; return pjmedia_h263_unpacketize(data->pktz, payload, payload_len, - bits, bits_len, bits_pos); + bits, bits_len, bits_pos); } #endif /* PJMEDIA_HAS_FFMPEG_CODEC_H263P */ static const ffmpeg_codec_desc* find_codec_desc_by_info( - const pjmedia_vid_codec_info *info) + const pjmedia_vid_codec_info *info) { int i; for (i=0; ienabled && - (desc->info.fmt_id == info->fmt_id) && + if (desc->enabled && + (desc->info.fmt_id == info->fmt_id) && ((desc->info.dir & info->dir) == info->dir) && - (desc->info.pt == info->pt) && - (desc->info.packings & info->packings)) + (desc->info.pt == info->pt) && + (desc->info.packings & info->packings)) { return desc; } @@ -721,8 +720,8 @@ static int find_codec_idx_by_fmt_id(pjmedia_format_id fmt_id) { int i; for (i=0; iinfo.dec_fmt_id_cnt = raw_fmt_cnt; pj_memcpy(desc->info.dec_fmt_id, raw_fmt, - sizeof(raw_fmt[0])*raw_fmt_cnt); + sizeof(raw_fmt[0])*raw_fmt_cnt); } /* Get supported framerates */ @@ -876,8 +875,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_ffmpeg_vid_init(pjmedia_vid_codec_mgr *mgr, unsigned i; if (ffmpeg_factory.pool != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } if (!mgr) mgr = pjmedia_vid_codec_mgr_instance(); @@ -891,13 +890,13 @@ PJ_DEF(pj_status_t) pjmedia_codec_ffmpeg_vid_init(pjmedia_vid_codec_mgr *mgr, pool = pj_pool_create(pf, "ffmpeg codec factory", 256, 256, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create mutex. */ status = pj_mutex_create_simple(pool, "ffmpeg codec factory", - &ffmpeg_factory.mutex); + &ffmpeg_factory.mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; pjmedia_ffmpeg_add_ref(); #if !LIBAVCODEC_VER_AT_LEAST(53,20) @@ -912,15 +911,15 @@ PJ_DEF(pj_status_t) pjmedia_codec_ffmpeg_vid_init(pjmedia_vid_codec_mgr *mgr, for (i = 0; i < PJ_ARRAY_SIZE(codec_desc); ++i) { unsigned codec_id; - pjmedia_format_id_to_CodecID(codec_desc[i].info.fmt_id, &codec_id); + pjmedia_format_id_to_CodecID(codec_desc[i].info.fmt_id, &codec_id); c = avcodec_find_encoder(codec_id); if (c) - init_codec(c, PJ_TRUE, PJ_FALSE); + init_codec(c, PJ_TRUE, PJ_FALSE); c = avcodec_find_decoder(codec_id); if (c) - init_codec(c, PJ_FALSE, PJ_TRUE); + init_codec(c, PJ_FALSE, PJ_TRUE); } #else @@ -937,88 +936,88 @@ PJ_DEF(pj_status_t) pjmedia_codec_ffmpeg_vid_init(pjmedia_vid_codec_mgr *mgr, * SDP negotiation, etc. */ for (i = 0; i < PJ_ARRAY_SIZE(codec_desc); ++i) { - ffmpeg_codec_desc *desc = &codec_desc[i]; - - /* Init encoder/decoder description from base format */ - if (desc->base_fmt_id && (!desc->dec || !desc->enc)) { - ffmpeg_codec_desc *base_desc = NULL; - int base_desc_idx; - pjmedia_dir copied_dir = PJMEDIA_DIR_NONE; - - base_desc_idx = find_codec_idx_by_fmt_id(desc->base_fmt_id); - if (base_desc_idx != -1) - base_desc = &codec_desc[base_desc_idx]; - if (!base_desc || !base_desc->enabled) - continue; - - /* Copy description from base codec */ - if (!desc->info.dec_fmt_id_cnt) { - desc->info.dec_fmt_id_cnt = base_desc->info.dec_fmt_id_cnt; - pj_memcpy(desc->info.dec_fmt_id, base_desc->info.dec_fmt_id, - sizeof(pjmedia_format_id)*desc->info.dec_fmt_id_cnt); - } - if (!desc->info.fps_cnt) { - desc->info.fps_cnt = base_desc->info.fps_cnt; - pj_memcpy(desc->info.fps, base_desc->info.fps, - sizeof(desc->info.fps[0])*desc->info.fps_cnt); - } - if (!desc->info.clock_rate) { - desc->info.clock_rate = base_desc->info.clock_rate; - } - if (!desc->dec && base_desc->dec) { - copied_dir |= PJMEDIA_DIR_DECODING; - desc->dec = base_desc->dec; - } - if (!desc->enc && base_desc->enc) { - copied_dir |= PJMEDIA_DIR_ENCODING; - desc->enc = base_desc->enc; - } - - desc->info.dir |= copied_dir; - desc->enabled = (desc->info.dir != PJMEDIA_DIR_NONE); - - /* Set supported packings */ - desc->info.packings |= PJMEDIA_VID_PACKING_WHOLE; - if (desc->packetize && desc->unpacketize) - desc->info.packings |= PJMEDIA_VID_PACKING_PACKETS; - - if (copied_dir != PJMEDIA_DIR_NONE) { - const char *dir_name[] = {NULL, "encoder", "decoder", "codec"}; - PJ_LOG(5, (THIS_FILE, "The %.*s %s is using base codec (%.*s)", - desc->info.encoding_name.slen, - desc->info.encoding_name.ptr, - dir_name[copied_dir], - base_desc->info.encoding_name.slen, - base_desc->info.encoding_name.ptr)); - } + ffmpeg_codec_desc *desc = &codec_desc[i]; + + /* Init encoder/decoder description from base format */ + if (desc->base_fmt_id && (!desc->dec || !desc->enc)) { + ffmpeg_codec_desc *base_desc = NULL; + int base_desc_idx; + pjmedia_dir copied_dir = PJMEDIA_DIR_NONE; + + base_desc_idx = find_codec_idx_by_fmt_id(desc->base_fmt_id); + if (base_desc_idx != -1) + base_desc = &codec_desc[base_desc_idx]; + if (!base_desc || !base_desc->enabled) + continue; + + /* Copy description from base codec */ + if (!desc->info.dec_fmt_id_cnt) { + desc->info.dec_fmt_id_cnt = base_desc->info.dec_fmt_id_cnt; + pj_memcpy(desc->info.dec_fmt_id, base_desc->info.dec_fmt_id, + sizeof(pjmedia_format_id)*desc->info.dec_fmt_id_cnt); + } + if (!desc->info.fps_cnt) { + desc->info.fps_cnt = base_desc->info.fps_cnt; + pj_memcpy(desc->info.fps, base_desc->info.fps, + sizeof(desc->info.fps[0])*desc->info.fps_cnt); + } + if (!desc->info.clock_rate) { + desc->info.clock_rate = base_desc->info.clock_rate; + } + if (!desc->dec && base_desc->dec) { + copied_dir |= PJMEDIA_DIR_DECODING; + desc->dec = base_desc->dec; + } + if (!desc->enc && base_desc->enc) { + copied_dir |= PJMEDIA_DIR_ENCODING; + desc->enc = base_desc->enc; + } + + desc->info.dir |= copied_dir; + desc->enabled = (desc->info.dir != PJMEDIA_DIR_NONE); + + /* Set supported packings */ + desc->info.packings |= PJMEDIA_VID_PACKING_WHOLE; + if (desc->packetize && desc->unpacketize) + desc->info.packings |= PJMEDIA_VID_PACKING_PACKETS; + + if (copied_dir != PJMEDIA_DIR_NONE) { + const char *dir_name[] = {NULL, "encoder", "decoder", "codec"}; + PJ_LOG(5, (THIS_FILE, "The %.*s %s is using base codec (%.*s)", + desc->info.encoding_name.slen, + desc->info.encoding_name.ptr, + dir_name[copied_dir], + base_desc->info.encoding_name.slen, + base_desc->info.encoding_name.ptr)); + } } - /* Registering format match for SDP negotiation */ - if (desc->sdp_fmt_match) { - status = pjmedia_sdp_neg_register_fmt_match_cb( - &desc->info.encoding_name, - desc->sdp_fmt_match); - pj_assert(status == PJ_SUCCESS); - } - - /* Print warning about missing encoder/decoder */ - if (!desc->enc) { - PJ_LOG(4, (THIS_FILE, "Cannot find %.*s encoder in ffmpeg library", - desc->info.encoding_name.slen, - desc->info.encoding_name.ptr)); - } - if (!desc->dec) { - PJ_LOG(4, (THIS_FILE, "Cannot find %.*s decoder in ffmpeg library", - desc->info.encoding_name.slen, - desc->info.encoding_name.ptr)); - } + /* Registering format match for SDP negotiation */ + if (desc->sdp_fmt_match) { + status = pjmedia_sdp_neg_register_fmt_match_cb( + &desc->info.encoding_name, + desc->sdp_fmt_match); + pj_assert(status == PJ_SUCCESS); + } + + /* Print warning about missing encoder/decoder */ + if (!desc->enc) { + PJ_LOG(4, (THIS_FILE, "Cannot find %.*s encoder in ffmpeg library", + desc->info.encoding_name.slen, + desc->info.encoding_name.ptr)); + } + if (!desc->dec) { + PJ_LOG(4, (THIS_FILE, "Cannot find %.*s decoder in ffmpeg library", + desc->info.encoding_name.slen, + desc->info.encoding_name.ptr)); + } } /* Register codec factory to codec manager. */ status = pjmedia_vid_codec_mgr_register_factory(mgr, - &ffmpeg_factory.base); + &ffmpeg_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; ffmpeg_factory.pool = pool; @@ -1038,15 +1037,15 @@ PJ_DEF(pj_status_t) pjmedia_codec_ffmpeg_vid_deinit(void) pj_status_t status = PJ_SUCCESS; if (ffmpeg_factory.pool == NULL) { - /* Already deinitialized */ - return PJ_SUCCESS; + /* Already deinitialized */ + return PJ_SUCCESS; } pj_mutex_lock(ffmpeg_factory.mutex); /* Unregister FFMPEG codecs factory. */ status = pjmedia_vid_codec_mgr_unregister_factory(ffmpeg_factory.mgr, - &ffmpeg_factory.base); + &ffmpeg_factory.base); /* Destroy mutex. */ pj_mutex_unlock(ffmpeg_factory.mutex); @@ -1067,7 +1066,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_ffmpeg_vid_deinit(void) * Check if factory can allocate the specified codec. */ static pj_status_t ffmpeg_test_alloc( pjmedia_vid_codec_factory *factory, - const pjmedia_vid_codec_info *info ) + const pjmedia_vid_codec_info *info ) { const ffmpeg_codec_desc *desc; @@ -1086,8 +1085,8 @@ static pj_status_t ffmpeg_test_alloc( pjmedia_vid_codec_factory *factory, * Generate default attribute. */ static pj_status_t ffmpeg_default_attr( pjmedia_vid_codec_factory *factory, - const pjmedia_vid_codec_info *info, - pjmedia_vid_codec_param *attr ) + const pjmedia_vid_codec_info *info, + pjmedia_vid_codec_param *attr ) { const ffmpeg_codec_desc *desc; unsigned i; @@ -1105,15 +1104,15 @@ static pj_status_t ffmpeg_default_attr( pjmedia_vid_codec_factory *factory, /* Scan the requested packings and use the lowest number */ attr->packing = 0; for (i=0; i<15; ++i) { - unsigned packing = (1 << i); - if ((desc->info.packings & info->packings) & packing) { - attr->packing = (pjmedia_vid_packing)packing; - break; - } + unsigned packing = (1 << i); + if ((desc->info.packings & info->packings) & packing) { + attr->packing = (pjmedia_vid_packing)packing; + break; + } } if (attr->packing == 0) { - /* No supported packing in info */ - return PJMEDIA_CODEC_EUNSUP; + /* No supported packing in info */ + return PJMEDIA_CODEC_EUNSUP; } /* Direction */ @@ -1122,12 +1121,12 @@ static pj_status_t ffmpeg_default_attr( pjmedia_vid_codec_factory *factory, /* Encoded format */ pjmedia_format_init_video(&attr->enc_fmt, desc->info.fmt_id, desc->size.w, desc->size.h, - desc->fps.num, desc->fps.denum); + desc->fps.num, desc->fps.denum); /* Decoded format */ pjmedia_format_init_video(&attr->dec_fmt, desc->info.dec_fmt_id[0], desc->size.w, desc->size.h, - desc->fps.num, desc->fps.denum); + desc->fps.num, desc->fps.denum); /* Decoding fmtp */ attr->dec_fmtp = desc->dec_fmtp; @@ -1146,8 +1145,8 @@ static pj_status_t ffmpeg_default_attr( pjmedia_vid_codec_factory *factory, * Enum codecs supported by this factory. */ static pj_status_t ffmpeg_enum_codecs( pjmedia_vid_codec_factory *factory, - unsigned *count, - pjmedia_vid_codec_info codecs[]) + unsigned *count, + pjmedia_vid_codec_info codecs[]) { unsigned i, max_cnt; @@ -1158,11 +1157,11 @@ static pj_status_t ffmpeg_enum_codecs( pjmedia_vid_codec_factory *factory, *count = 0; for (i=0; iparam.enc_fmt, - PJ_TRUE); + PJ_TRUE); /* Allocate ffmpeg codec context */ if (ff->param.dir & PJMEDIA_DIR_ENCODING) { #if LIBAVCODEC_VER_AT_LEAST(53,20) - ff->enc_ctx = avcodec_alloc_context3(ff->enc); + ff->enc_ctx = avcodec_alloc_context3(ff->enc); #else - ff->enc_ctx = avcodec_alloc_context(); + ff->enc_ctx = avcodec_alloc_context(); #endif - if (ff->enc_ctx == NULL) - goto on_error; + if (ff->enc_ctx == NULL) + goto on_error; } if (ff->param.dir & PJMEDIA_DIR_DECODING) { #if LIBAVCODEC_VER_AT_LEAST(53,20) - ff->dec_ctx = avcodec_alloc_context3(ff->dec); + ff->dec_ctx = avcodec_alloc_context3(ff->dec); #else - ff->dec_ctx = avcodec_alloc_context(); + ff->dec_ctx = avcodec_alloc_context(); #endif - if (ff->dec_ctx == NULL) - goto on_error; + if (ff->dec_ctx == NULL) + goto on_error; } /* Init generic encoder params */ @@ -1306,35 +1305,35 @@ static pj_status_t open_ffmpeg_codec(ffmpeg_private *ff, AVCodecContext *ctx = ff->enc_ctx; ctx->pix_fmt = pix_fmt; - ctx->width = vfd->size.w; - ctx->height = vfd->size.h; - ctx->time_base.num = vfd->fps.denum; - ctx->time_base.den = vfd->fps.num; - if (vfd->avg_bps) { - ctx->bit_rate = vfd->avg_bps; - if (vfd->max_bps > vfd->avg_bps) - ctx->bit_rate_tolerance = vfd->max_bps - vfd->avg_bps; - } - ctx->strict_std_compliance = FF_COMPLIANCE_STRICT; + ctx->width = vfd->size.w; + ctx->height = vfd->size.h; + ctx->time_base.num = vfd->fps.denum; + ctx->time_base.den = vfd->fps.num; + if (vfd->avg_bps) { + ctx->bit_rate = vfd->avg_bps; + if (vfd->max_bps > vfd->avg_bps) + ctx->bit_rate_tolerance = vfd->max_bps - vfd->avg_bps; + } + ctx->strict_std_compliance = FF_COMPLIANCE_STRICT; ctx->workaround_bugs = FF_BUG_AUTODETECT; ctx->opaque = ff; - /* Set no delay, note that this may cause some codec functionals - * not working (e.g: rate control). - */ + /* Set no delay, note that this may cause some codec functionals + * not working (e.g: rate control). + */ #if LIBAVCODEC_VER_AT_LEAST(52,113) && !LIBAVCODEC_VER_AT_LEAST(53,20) - ctx->rc_lookahead = 0; + ctx->rc_lookahead = 0; #endif } /* Init generic decoder params */ if (ff->param.dir & PJMEDIA_DIR_DECODING) { - AVCodecContext *ctx = ff->dec_ctx; + AVCodecContext *ctx = ff->dec_ctx; - /* Width/height may be overriden by ffmpeg after first decoding. */ - ctx->width = ctx->coded_width = ff->param.dec_fmt.det.vid.size.w; - ctx->height = ctx->coded_height = ff->param.dec_fmt.det.vid.size.h; - ctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL; + /* Width/height may be overriden by ffmpeg after first decoding. */ + ctx->width = ctx->coded_width = ff->param.dec_fmt.det.vid.size.w; + ctx->height = ctx->coded_height = ff->param.dec_fmt.det.vid.size.h; + ctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL; ctx->workaround_bugs = FF_BUG_AUTODETECT; ctx->opaque = ff; } @@ -1343,62 +1342,62 @@ static pj_status_t open_ffmpeg_codec(ffmpeg_private *ff, * the codec. */ if (ff->desc->preopen) { - status = (*ff->desc->preopen)(ff); - if (status != PJ_SUCCESS) - goto on_error; + status = (*ff->desc->preopen)(ff); + if (status != PJ_SUCCESS) + goto on_error; } /* Open encoder */ if (ff->param.dir & PJMEDIA_DIR_ENCODING) { - int err; + int err; - pj_mutex_lock(ff_mutex); - err = AVCODEC_OPEN(ff->enc_ctx, ff->enc); + pj_mutex_lock(ff_mutex); + err = AVCODEC_OPEN(ff->enc_ctx, ff->enc); pj_mutex_unlock(ff_mutex); if (err < 0) { print_ffmpeg_err(err); status = PJMEDIA_CODEC_EFAILED; - goto on_error; + goto on_error; } - enc_opened = PJ_TRUE; + enc_opened = PJ_TRUE; } /* Open decoder */ if (ff->param.dir & PJMEDIA_DIR_DECODING) { - int err; + int err; - pj_mutex_lock(ff_mutex); - err = AVCODEC_OPEN(ff->dec_ctx, ff->dec); + pj_mutex_lock(ff_mutex); + err = AVCODEC_OPEN(ff->dec_ctx, ff->dec); pj_mutex_unlock(ff_mutex); if (err < 0) { print_ffmpeg_err(err); status = PJMEDIA_CODEC_EFAILED; - goto on_error; + goto on_error; } - dec_opened = PJ_TRUE; + dec_opened = PJ_TRUE; } /* Let the codec apply specific params after the codec opened */ if (ff->desc->postopen) { - status = (*ff->desc->postopen)(ff); - if (status != PJ_SUCCESS) - goto on_error; + status = (*ff->desc->postopen)(ff); + if (status != PJ_SUCCESS) + goto on_error; } return PJ_SUCCESS; on_error: if (ff->enc_ctx) { - if (enc_opened) - avcodec_close(ff->enc_ctx); - av_free(ff->enc_ctx); - ff->enc_ctx = NULL; + if (enc_opened) + avcodec_close(ff->enc_ctx); + av_free(ff->enc_ctx); + ff->enc_ctx = NULL; } if (ff->dec_ctx) { - if (dec_opened) - avcodec_close(ff->dec_ctx); - av_free(ff->dec_ctx); - ff->dec_ctx = NULL; + if (dec_opened) + avcodec_close(ff->dec_ctx); + av_free(ff->dec_ctx); + ff->dec_ctx = NULL; } return status; } @@ -1407,7 +1406,7 @@ static pj_status_t open_ffmpeg_codec(ffmpeg_private *ff, * Open codec. */ static pj_status_t ffmpeg_codec_open( pjmedia_vid_codec *codec, - pjmedia_vid_codec_param *attr ) + pjmedia_vid_codec_param *attr ) { ffmpeg_private *ff; pj_status_t status; @@ -1420,7 +1419,7 @@ static pj_status_t ffmpeg_codec_open( pjmedia_vid_codec *codec, /* Normalize encoding MTU in codec param */ if (attr->enc_mtu > PJMEDIA_MAX_VID_PAYLOAD_SIZE) - attr->enc_mtu = PJMEDIA_MAX_VID_PAYLOAD_SIZE; + attr->enc_mtu = PJMEDIA_MAX_VID_PAYLOAD_SIZE; /* Open the codec */ ff_mutex = ((struct ffmpeg_factory*)codec->factory)->mutex; @@ -1459,11 +1458,11 @@ static pj_status_t ffmpeg_codec_open( pjmedia_vid_codec *codec, /* Alloc buffers if needed */ ff->whole = (ff->param.packing == PJMEDIA_VID_PACKING_WHOLE); if (!ff->whole) { - ff->enc_buf_size = (unsigned)ff->enc_vafp.framebytes; - ff->enc_buf = pj_pool_alloc(ff->pool, ff->enc_buf_size); + ff->enc_buf_size = (unsigned)ff->enc_vafp.framebytes; + ff->enc_buf = pj_pool_alloc(ff->pool, ff->enc_buf_size); - ff->dec_buf_size = PJ_MAX((unsigned)ff->dec_vafp.framebytes, ff->dec_buf_size); - ff->dec_buf = pj_pool_alloc(ff->pool, ff->dec_buf_size); + ff->dec_buf_size = PJ_MAX((unsigned)ff->dec_vafp.framebytes, ff->dec_buf_size); + ff->dec_buf = pj_pool_alloc(ff->pool, ff->dec_buf_size); } /* Update codec attributes, e.g: encoding format may be changed by @@ -1511,7 +1510,7 @@ static pj_status_t ffmpeg_codec_close( pjmedia_vid_codec *codec ) * Modify codec settings. */ static pj_status_t ffmpeg_codec_modify( pjmedia_vid_codec *codec, - const pjmedia_vid_codec_param *attr) + const pjmedia_vid_codec_param *attr) { ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data; @@ -1522,7 +1521,7 @@ static pj_status_t ffmpeg_codec_modify( pjmedia_vid_codec *codec, } static pj_status_t ffmpeg_codec_get_param(pjmedia_vid_codec *codec, - pjmedia_vid_codec_param *param) + pjmedia_vid_codec_param *param) { ffmpeg_private *ff; @@ -1545,7 +1544,7 @@ static pj_status_t ffmpeg_packetize ( pjmedia_vid_codec *codec, ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data; if (ff->desc->packetize) { - return (*ff->desc->packetize)(ff, bits, bits_len, bits_pos, + return (*ff->desc->packetize)(ff, bits, bits_len, bits_pos, payload, payload_len, is_keyframe); } @@ -1557,7 +1556,7 @@ static pj_status_t ffmpeg_unpacketize(pjmedia_vid_codec *codec, pj_size_t payload_len, pj_uint8_t *bits, pj_size_t bits_len, - unsigned *bits_pos) + unsigned *bits_pos) { ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data; @@ -1574,10 +1573,10 @@ static pj_status_t ffmpeg_unpacketize(pjmedia_vid_codec *codec, * Encode frames. */ static pj_status_t ffmpeg_codec_encode_whole(pjmedia_vid_codec *codec, - const pjmedia_vid_encode_opt *opt, - const pjmedia_frame *input, - unsigned output_buf_len, - pjmedia_frame *output) + const pjmedia_vid_encode_opt *opt, + const pjmedia_frame *input, + unsigned output_buf_len, + pjmedia_frame *output) { ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data; pj_uint8_t *p = (pj_uint8_t*)input->buf; @@ -1592,7 +1591,7 @@ static pj_status_t ffmpeg_codec_encode_whole(pjmedia_vid_codec *codec, PJ_ALIGN_DATA(pj_uint32_t i[4], 16); if ((long)(pj_ssize_t)i & 0xF) { - PJ_LOG(2,(THIS_FILE, "Stack alignment fails")); + PJ_LOG(2,(THIS_FILE, "Stack alignment fails")); } /* Check if encoder has been opened */ @@ -1610,7 +1609,7 @@ static pj_status_t ffmpeg_codec_encode_whole(pjmedia_vid_codec *codec, src_timebase.num = 1; src_timebase.den = ff->desc->info.clock_rate; avframe.pts = av_rescale_q(input->timestamp.u64, src_timebase, - ff->enc_ctx->time_base); + ff->enc_ctx->time_base); */ for (i[0] = 0; i[0] < ff->enc_vfi->plane_cnt; ++i[0]) { @@ -1628,9 +1627,9 @@ static pj_status_t ffmpeg_codec_encode_whole(pjmedia_vid_codec *codec, /* Force keyframe */ if (opt && opt->force_keyframe) { #if LIBAVCODEC_VER_AT_LEAST(53,20) - avframe.pict_type = AV_PICTURE_TYPE_I; + avframe.pict_type = AV_PICTURE_TYPE_I; #else - avframe.pict_type = FF_I_TYPE; + avframe.pict_type = FF_I_TYPE; #endif } @@ -1654,11 +1653,11 @@ static pj_status_t ffmpeg_codec_encode_whole(pjmedia_vid_codec *codec, break; } if (err >= 0) { - pj_memcpy(bits_out, pkt->data, pkt->size); - bits_out += pkt->size; - out_size += pkt->size; - av_packet_unref(&avpacket); - } + pj_memcpy(bits_out, pkt->data, pkt->size); + bits_out += pkt->size; + out_size += pkt->size; + av_packet_unref(&avpacket); + } } av_packet_free(&pkt); } @@ -1668,7 +1667,7 @@ static pj_status_t ffmpeg_codec_encode_whole(pjmedia_vid_codec *codec, err = avcodec_encode_video2(ff->enc_ctx, &avpacket, &avframe, &got_packet); if (!err && got_packet) - err = avpacket.size; + err = avpacket.size; #else PJ_UNUSED_ARG(got_packet); err = avcodec_encode_video(ff->enc_ctx, avpacket.data, avpacket.size, &avframe); @@ -1680,12 +1679,12 @@ static pj_status_t ffmpeg_codec_encode_whole(pjmedia_vid_codec *codec, } else { pj_bool_t has_key_frame = PJ_FALSE; output->size = err; - output->bit_info = 0; + output->bit_info = 0; #if LIBAVCODEC_VER_AT_LEAST(54,15) has_key_frame = (avpacket.flags & AV_PKT_FLAG_KEY); #else - has_key_frame = ff->enc_ctx->coded_frame->key_frame; + has_key_frame = ff->enc_ctx->coded_frame->key_frame; #endif if (has_key_frame) output->bit_info |= PJMEDIA_VID_FRM_KEYFRAME; @@ -1695,11 +1694,11 @@ static pj_status_t ffmpeg_codec_encode_whole(pjmedia_vid_codec *codec, } static pj_status_t ffmpeg_codec_encode_begin(pjmedia_vid_codec *codec, - const pjmedia_vid_encode_opt *opt, - const pjmedia_frame *input, - unsigned out_size, - pjmedia_frame *output, - pj_bool_t *has_more) + const pjmedia_vid_encode_opt *opt, + const pjmedia_frame *input, + unsigned out_size, + pjmedia_frame *output, + pj_bool_t *has_more) { ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data; pj_status_t status; @@ -1707,33 +1706,33 @@ static pj_status_t ffmpeg_codec_encode_begin(pjmedia_vid_codec *codec, *has_more = PJ_FALSE; if (ff->whole) { - status = ffmpeg_codec_encode_whole(codec, opt, input, out_size, - output); + status = ffmpeg_codec_encode_whole(codec, opt, input, out_size, + output); } else { - pjmedia_frame whole_frm; - pj_bzero(&whole_frm, sizeof(whole_frm)); - whole_frm.buf = ff->enc_buf; - whole_frm.size = ff->enc_buf_size; - status = ffmpeg_codec_encode_whole(codec, opt, input, - (unsigned)whole_frm.size, - &whole_frm); - if (status != PJ_SUCCESS) - return status; - - ff->enc_buf_is_keyframe = (whole_frm.bit_info & - PJMEDIA_VID_FRM_KEYFRAME); - ff->enc_frame_len = (unsigned)whole_frm.size; - ff->enc_processed = 0; - status = ffmpeg_codec_encode_more(codec, out_size, output, has_more); + pjmedia_frame whole_frm; + pj_bzero(&whole_frm, sizeof(whole_frm)); + whole_frm.buf = ff->enc_buf; + whole_frm.size = ff->enc_buf_size; + status = ffmpeg_codec_encode_whole(codec, opt, input, + (unsigned)whole_frm.size, + &whole_frm); + if (status != PJ_SUCCESS) + return status; + + ff->enc_buf_is_keyframe = (whole_frm.bit_info & + PJMEDIA_VID_FRM_KEYFRAME); + ff->enc_frame_len = (unsigned)whole_frm.size; + ff->enc_processed = 0; + status = ffmpeg_codec_encode_more(codec, out_size, output, has_more); } return status; } static pj_status_t ffmpeg_codec_encode_more(pjmedia_vid_codec *codec, - unsigned out_size, - pjmedia_frame *output, - pj_bool_t *has_more) + unsigned out_size, + pjmedia_frame *output, + pj_bool_t *has_more) { ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data; pj_uint8_t *payload = (pj_uint8_t *)output->buf; @@ -1743,8 +1742,8 @@ static pj_status_t ffmpeg_codec_encode_more(pjmedia_vid_codec *codec, *has_more = PJ_FALSE; if (ff->enc_processed >= ff->enc_frame_len) { - /* No more frame */ - return PJ_EEOF; + /* No more frame */ + return PJ_EEOF; } status = ffmpeg_packetize(codec, (pj_uint8_t*)ff->enc_buf, @@ -1757,7 +1756,7 @@ static pj_status_t ffmpeg_codec_encode_more(pjmedia_vid_codec *codec, output->size = payload_len; if (ff->enc_buf_is_keyframe) - output->bit_info |= PJMEDIA_VID_FRM_KEYFRAME; + output->bit_info |= PJMEDIA_VID_FRM_KEYFRAME; *has_more = (ff->enc_processed < ff->enc_frame_len); @@ -1766,8 +1765,8 @@ static pj_status_t ffmpeg_codec_encode_more(pjmedia_vid_codec *codec, static pj_status_t check_decode_result(pjmedia_vid_codec *codec, - const pj_timestamp *ts, - pj_bool_t got_keyframe) + const pj_timestamp *ts, + pj_bool_t got_keyframe) { ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data; pjmedia_video_apply_fmt_param *vafp = &ff->dec_vafp; @@ -1778,63 +1777,63 @@ static pj_status_t check_decode_result(pjmedia_vid_codec *codec, * to the configured param. */ if (ff->dec_ctx->pix_fmt != ff->expected_dec_fmt || - ff->dec_ctx->width != (int)vafp->size.w || - ff->dec_ctx->height != (int)vafp->size.h) + ff->dec_ctx->width != (int)vafp->size.w || + ff->dec_ctx->height != (int)vafp->size.h) { - pjmedia_format_id new_fmt_id; - pj_status_t status; - - /* Get current raw format id from ffmpeg decoder context */ - status = PixelFormat_to_pjmedia_format_id(ff->dec_ctx->pix_fmt, - &new_fmt_id); - if (status != PJ_SUCCESS) - return status; - - /* Update decoder format in param */ - ff->param.dec_fmt.id = new_fmt_id; - ff->param.dec_fmt.det.vid.size.w = ff->dec_ctx->width; - ff->param.dec_fmt.det.vid.size.h = ff->dec_ctx->height; - ff->expected_dec_fmt = ff->dec_ctx->pix_fmt; - - /* Re-init format info and apply-param of decoder */ - ff->dec_vfi = pjmedia_get_video_format_info(NULL, ff->param.dec_fmt.id); - if (!ff->dec_vfi) - return PJ_ENOTSUP; - pj_bzero(&ff->dec_vafp, sizeof(ff->dec_vafp)); - ff->dec_vafp.size = ff->param.dec_fmt.det.vid.size; - ff->dec_vafp.buffer = NULL; - status = (*ff->dec_vfi->apply_fmt)(ff->dec_vfi, &ff->dec_vafp); - if (status != PJ_SUCCESS) - return status; - - /* Realloc buffer if necessary */ - if (ff->dec_vafp.framebytes > ff->dec_buf_size) { - PJ_LOG(5,(THIS_FILE, "Reallocating decoding buffer %u --> %u", - (unsigned)ff->dec_buf_size, - (unsigned)ff->dec_vafp.framebytes)); - ff->dec_buf_size = (unsigned)ff->dec_vafp.framebytes; - ff->dec_buf = pj_pool_alloc(ff->pool, ff->dec_buf_size); - } - - /* Broadcast format changed event */ - pjmedia_event_init(&event, PJMEDIA_EVENT_FMT_CHANGED, ts, codec); - event.data.fmt_changed.dir = PJMEDIA_DIR_DECODING; - pj_memcpy(&event.data.fmt_changed.new_fmt, &ff->param.dec_fmt, - sizeof(ff->param.dec_fmt)); - pjmedia_event_publish(NULL, codec, &event, 0); + pjmedia_format_id new_fmt_id; + pj_status_t status; + + /* Get current raw format id from ffmpeg decoder context */ + status = PixelFormat_to_pjmedia_format_id(ff->dec_ctx->pix_fmt, + &new_fmt_id); + if (status != PJ_SUCCESS) + return status; + + /* Update decoder format in param */ + ff->param.dec_fmt.id = new_fmt_id; + ff->param.dec_fmt.det.vid.size.w = ff->dec_ctx->width; + ff->param.dec_fmt.det.vid.size.h = ff->dec_ctx->height; + ff->expected_dec_fmt = ff->dec_ctx->pix_fmt; + + /* Re-init format info and apply-param of decoder */ + ff->dec_vfi = pjmedia_get_video_format_info(NULL, ff->param.dec_fmt.id); + if (!ff->dec_vfi) + return PJ_ENOTSUP; + pj_bzero(&ff->dec_vafp, sizeof(ff->dec_vafp)); + ff->dec_vafp.size = ff->param.dec_fmt.det.vid.size; + ff->dec_vafp.buffer = NULL; + status = (*ff->dec_vfi->apply_fmt)(ff->dec_vfi, &ff->dec_vafp); + if (status != PJ_SUCCESS) + return status; + + /* Realloc buffer if necessary */ + if (ff->dec_vafp.framebytes > ff->dec_buf_size) { + PJ_LOG(5,(THIS_FILE, "Reallocating decoding buffer %u --> %u", + (unsigned)ff->dec_buf_size, + (unsigned)ff->dec_vafp.framebytes)); + ff->dec_buf_size = (unsigned)ff->dec_vafp.framebytes; + ff->dec_buf = pj_pool_alloc(ff->pool, ff->dec_buf_size); + } + + /* Broadcast format changed event */ + pjmedia_event_init(&event, PJMEDIA_EVENT_FMT_CHANGED, ts, codec); + event.data.fmt_changed.dir = PJMEDIA_DIR_DECODING; + pj_memcpy(&event.data.fmt_changed.new_fmt, &ff->param.dec_fmt, + sizeof(ff->param.dec_fmt)); + pjmedia_event_publish(NULL, codec, &event, 0); } /* Check for missing/found keyframe */ if (got_keyframe) { - pj_get_timestamp(&ff->last_dec_keyframe_ts); + pj_get_timestamp(&ff->last_dec_keyframe_ts); - /* Broadcast keyframe event */ + /* Broadcast keyframe event */ pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_FOUND, ts, codec); pjmedia_event_publish(NULL, codec, &event, 0); } else if (ff->last_dec_keyframe_ts.u64 == 0) { - /* Broadcast missing keyframe event */ - pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, ts, codec); - pjmedia_event_publish(NULL, codec, &event, 0); + /* Broadcast missing keyframe event */ + pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, ts, codec); + pjmedia_event_publish(NULL, codec, &event, 0); } return PJ_SUCCESS; @@ -1844,9 +1843,9 @@ static pj_status_t check_decode_result(pjmedia_vid_codec *codec, * Decode frame. */ static pj_status_t ffmpeg_codec_decode_whole(pjmedia_vid_codec *codec, - const pjmedia_frame *input, - unsigned output_buf_len, - pjmedia_frame *output) + const pjmedia_frame *input, + unsigned output_buf_len, + pjmedia_frame *output) { ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data; AVFrame avframe; @@ -1863,7 +1862,7 @@ static pj_status_t ffmpeg_codec_decode_whole(pjmedia_vid_codec *codec, // Do this validation later after getting decoding result, where the real // decoded size will be assured. //if (ff->dec_vafp.framebytes > output_buf_len) - //return PJ_ETOOSMALL; + //return PJ_ETOOSMALL; /* Init frame to receive the decoded data, the ffmpeg codec context will * automatically provide the decoded buffer (single buffer used for the @@ -1927,73 +1926,73 @@ static pj_status_t ffmpeg_codec_decode_whole(pjmedia_vid_codec *codec, &got_picture, avpacket.data, avpacket.size); #endif if (err < 0) { - pjmedia_event event; + pjmedia_event event; - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->size = 0; + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->size = 0; print_ffmpeg_err(err); - /* Broadcast missing keyframe event */ - pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, - &input->timestamp, codec); - pjmedia_event_publish(NULL, codec, &event, 0); + /* Broadcast missing keyframe event */ + pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, + &input->timestamp, codec); + pjmedia_event_publish(NULL, codec, &event, 0); - return PJMEDIA_CODEC_EBADBITSTREAM; + return PJMEDIA_CODEC_EBADBITSTREAM; } else if (got_picture) { pjmedia_video_apply_fmt_param *vafp = &ff->dec_vafp; pj_uint8_t *q = (pj_uint8_t*)output->buf; - unsigned i; - pj_status_t status; - - /* Check decoding result, e.g: see if the format got changed, - * keyframe found/missing. - */ - status = check_decode_result(codec, &input->timestamp, - avframe.key_frame); - if (status != PJ_SUCCESS) - return status; - - /* Check provided buffer size */ - if (vafp->framebytes > output_buf_len) - return PJ_ETOOSMALL; - - /* Get the decoded data */ - for (i = 0; i < ff->dec_vfi->plane_cnt; ++i) { - pj_uint8_t *p = avframe.data[i]; - - /* The decoded data may contain padding */ - if (avframe.linesize[i]!=vafp->strides[i]) { - /* Padding exists, copy line by line */ - pj_uint8_t *q_end; + unsigned i; + pj_status_t status; + + /* Check decoding result, e.g: see if the format got changed, + * keyframe found/missing. + */ + status = check_decode_result(codec, &input->timestamp, + avframe.key_frame); + if (status != PJ_SUCCESS) + return status; + + /* Check provided buffer size */ + if (vafp->framebytes > output_buf_len) + return PJ_ETOOSMALL; + + /* Get the decoded data */ + for (i = 0; i < ff->dec_vfi->plane_cnt; ++i) { + pj_uint8_t *p = avframe.data[i]; + + /* The decoded data may contain padding */ + if (avframe.linesize[i]!=vafp->strides[i]) { + /* Padding exists, copy line by line */ + pj_uint8_t *q_end; - q_end = q+vafp->plane_bytes[i]; - while(q < q_end) { - pj_memcpy(q, p, vafp->strides[i]); - q += vafp->strides[i]; - p += avframe.linesize[i]; - } - } else { - /* No padding, copy the whole plane */ - pj_memcpy(q, p, vafp->plane_bytes[i]); - q += vafp->plane_bytes[i]; - } - } - - output->type = PJMEDIA_FRAME_TYPE_VIDEO; + q_end = q+vafp->plane_bytes[i]; + while(q < q_end) { + pj_memcpy(q, p, vafp->strides[i]); + q += vafp->strides[i]; + p += avframe.linesize[i]; + } + } else { + /* No padding, copy the whole plane */ + pj_memcpy(q, p, vafp->plane_bytes[i]); + q += vafp->plane_bytes[i]; + } + } + + output->type = PJMEDIA_FRAME_TYPE_VIDEO; output->size = vafp->framebytes; } else { - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->size = 0; + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->size = 0; } return PJ_SUCCESS; } static pj_status_t ffmpeg_codec_decode( pjmedia_vid_codec *codec, - pj_size_t pkt_count, - pjmedia_frame packets[], - unsigned out_size, - pjmedia_frame *output) + pj_size_t pkt_count, + pjmedia_frame packets[], + unsigned out_size, + pjmedia_frame *output) { ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data; pj_status_t status; @@ -2002,34 +2001,34 @@ static pj_status_t ffmpeg_codec_decode( pjmedia_vid_codec *codec, PJ_EINVAL); if (ff->whole) { - pj_assert(pkt_count==1); - return ffmpeg_codec_decode_whole(codec, &packets[0], out_size, output); + pj_assert(pkt_count==1); + return ffmpeg_codec_decode_whole(codec, &packets[0], out_size, output); } else { - pjmedia_frame whole_frm; - unsigned whole_len = 0; - unsigned i; - - for (i=0; i ff->dec_buf_size) { - PJ_LOG(5,(THIS_FILE, "Decoding buffer overflow")); - break; - } - - status = ffmpeg_unpacketize(codec, packets[i].buf, packets[i].size, - ff->dec_buf, ff->dec_buf_size, - &whole_len); - if (status != PJ_SUCCESS) { - PJ_PERROR(5,(THIS_FILE, status, "Unpacketize error")); - continue; - } - } - - whole_frm.buf = ff->dec_buf; - whole_frm.size = whole_len; - whole_frm.timestamp = output->timestamp = packets[i].timestamp; - whole_frm.bit_info = 0; - - return ffmpeg_codec_decode_whole(codec, &whole_frm, out_size, output); + pjmedia_frame whole_frm; + unsigned whole_len = 0; + unsigned i; + + for (i=0; i ff->dec_buf_size) { + PJ_LOG(5,(THIS_FILE, "Decoding buffer overflow")); + break; + } + + status = ffmpeg_unpacketize(codec, packets[i].buf, packets[i].size, + ff->dec_buf, ff->dec_buf_size, + &whole_len); + if (status != PJ_SUCCESS) { + PJ_PERROR(5,(THIS_FILE, status, "Unpacketize error")); + continue; + } + } + + whole_frm.buf = ff->dec_buf; + whole_frm.size = whole_len; + whole_frm.timestamp = output->timestamp = packets[i].timestamp; + whole_frm.bit_info = 0; + + return ffmpeg_codec_decode_whole(codec, &whole_frm, out_size, output); } } @@ -2038,5 +2037,5 @@ static pj_status_t ffmpeg_codec_decode( pjmedia_vid_codec *codec, # pragma comment( lib, "avcodec.lib") #endif -#endif /* PJMEDIA_HAS_FFMPEG_VID_CODEC */ +#endif /* PJMEDIA_HAS_FFMPEG_VID_CODEC */ diff --git a/pjmedia/src/pjmedia-codec/g722.c b/pjmedia/src/pjmedia-codec/g722.c index ccc03ec763..8c34ea0040 100644 --- a/pjmedia/src/pjmedia-codec/g722.c +++ b/pjmedia/src/pjmedia-codec/g722.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,63 +37,63 @@ #define THIS_FILE "g722.c" /* Defines */ -#define PTIME (10) -#define SAMPLES_PER_FRAME (16000 * PTIME /1000) -#define FRAME_LEN (80) -#define PLC_DISABLED 0 +#define PTIME (10) +#define SAMPLES_PER_FRAME (16000 * PTIME /1000) +#define FRAME_LEN (80) +#define PLC_DISABLED 0 /* Tracing */ #ifndef PJ_TRACE -# define PJ_TRACE 0 +# define PJ_TRACE 0 #endif #if PJ_TRACE -# define TRACE_(expr) PJ_LOG(4,expr) +# define TRACE_(expr) PJ_LOG(4,expr) #else # define TRACE_(expr) #endif /* Prototypes for G722 factory */ static pj_status_t g722_test_alloc(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ); + const pjmedia_codec_info *id ); static pj_status_t g722_default_attr(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ); static pj_status_t g722_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t g722_alloc_codec(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t g722_dealloc_codec(pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for G722 implementation. */ static pj_status_t g722_codec_init(pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t g722_codec_open(pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t g722_codec_close(pjmedia_codec *codec ); static pj_status_t g722_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t g722_codec_parse(pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t g722_codec_encode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t g722_codec_decode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); #if !PLC_DISABLED static pj_status_t g722_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); #endif /* Definition for G722 codec operations. */ @@ -129,28 +128,28 @@ static pjmedia_codec_factory_op g722_factory_op = static struct g722_codec_factory { pjmedia_codec_factory base; - pjmedia_endpt *endpt; - pj_pool_t *pool; - pj_mutex_t *mutex; - pjmedia_codec codec_list; - unsigned pcm_shift; + pjmedia_endpt *endpt; + pj_pool_t *pool; + pj_mutex_t *mutex; + pjmedia_codec codec_list; + unsigned pcm_shift; } g722_codec_factory; /* G722 codec private data. */ struct g722_data { - g722_enc_t encoder; - g722_dec_t decoder; - pj_int16_t pcm_shift_val; - pj_int16_t pcm_min; - pj_int16_t pcm_max; - pj_bool_t plc_enabled; - pj_bool_t vad_enabled; - pjmedia_silence_det *vad; - pj_timestamp last_tx; + g722_enc_t encoder; + g722_dec_t decoder; + pj_int16_t pcm_shift_val; + pj_int16_t pcm_min; + pj_int16_t pcm_max; + pj_bool_t plc_enabled; + pj_bool_t vad_enabled; + pjmedia_silence_det *vad; + pj_timestamp last_tx; #if !PLC_DISABLED - pjmedia_plc *plc; + pjmedia_plc *plc; #endif }; @@ -165,7 +164,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_g722_init( pjmedia_endpt *endpt ) pj_status_t status; if (g722_codec_factory.pool != NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Create G722 codec factory. */ g722_codec_factory.base.op = &g722_factory_op; @@ -174,31 +173,31 @@ PJ_DEF(pj_status_t) pjmedia_codec_g722_init( pjmedia_endpt *endpt ) g722_codec_factory.pcm_shift = PJMEDIA_G722_DEFAULT_PCM_SHIFT; g722_codec_factory.pool = pjmedia_endpt_create_pool(endpt, "g722", - PJMEDIA_POOL_LEN_G722_CODEC, - PJMEDIA_POOL_INC_G722_CODEC); + PJMEDIA_POOL_LEN_G722_CODEC, + PJMEDIA_POOL_INC_G722_CODEC); if (!g722_codec_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; pj_list_init(&g722_codec_factory.codec_list); /* Create mutex. */ status = pj_mutex_create_simple(g722_codec_factory.pool, "g722", - &g722_codec_factory.mutex); + &g722_codec_factory.mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - status = PJ_EINVALIDOP; - goto on_error; + status = PJ_EINVALIDOP; + goto on_error; } /* Register codec factory to endpoint. */ status = pjmedia_codec_mgr_register_factory(codec_mgr, - &g722_codec_factory.base); + &g722_codec_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; TRACE_((THIS_FILE, "G722 codec factory initialized")); @@ -221,19 +220,19 @@ PJ_DEF(pj_status_t) pjmedia_codec_g722_deinit(void) pj_status_t status; if (g722_codec_factory.pool == NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(g722_codec_factory.endpt); if (!codec_mgr) { - pj_pool_release(g722_codec_factory.pool); - g722_codec_factory.pool = NULL; - return PJ_EINVALIDOP; + pj_pool_release(g722_codec_factory.pool); + g722_codec_factory.pool = NULL; + return PJ_EINVALIDOP; } /* Unregister G722 codec factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &g722_codec_factory.base); + &g722_codec_factory.base); /* Destroy mutex. */ pj_mutex_destroy(g722_codec_factory.mutex); @@ -261,13 +260,13 @@ PJ_DEF(pj_status_t) pjmedia_codec_g722_set_pcm_shift(unsigned val) * Check if factory can allocate the specified codec. */ static pj_status_t g722_test_alloc(pjmedia_codec_factory *factory, - const pjmedia_codec_info *info ) + const pjmedia_codec_info *info ) { PJ_UNUSED_ARG(factory); /* Check payload type. */ if (info->pt != PJMEDIA_RTP_PT_G722) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Ignore the rest, since it's static payload type. */ @@ -278,8 +277,8 @@ static pj_status_t g722_test_alloc(pjmedia_codec_factory *factory, * Generate default attribute. */ static pj_status_t g722_default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ) { PJ_UNUSED_ARG(factory); PJ_UNUSED_ARG(id); @@ -306,8 +305,8 @@ static pj_status_t g722_default_attr( pjmedia_codec_factory *factory, * Enum codecs supported by this factory (i.e. only G722!). */ static pj_status_t g722_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]) + unsigned *count, + pjmedia_codec_info codecs[]) { PJ_UNUSED_ARG(factory); PJ_ASSERT_RETURN(codecs && *count > 0, PJ_EINVAL); @@ -328,8 +327,8 @@ static pj_status_t g722_enum_codecs(pjmedia_codec_factory *factory, * Allocate a new G722 codec instance. */ static pj_status_t g722_alloc_codec(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { pjmedia_codec *codec; struct g722_data *g722_data; @@ -341,39 +340,39 @@ static pj_status_t g722_alloc_codec(pjmedia_codec_factory *factory, /* Get free nodes, if any. */ if (!pj_list_empty(&g722_codec_factory.codec_list)) { - codec = g722_codec_factory.codec_list.next; - pj_list_erase(codec); + codec = g722_codec_factory.codec_list.next; + pj_list_erase(codec); } else { - pj_status_t status; + pj_status_t status; - codec = PJ_POOL_ZALLOC_T(g722_codec_factory.pool, pjmedia_codec); - PJ_ASSERT_RETURN(codec != NULL, PJ_ENOMEM); - codec->op = &g722_op; - codec->factory = factory; + codec = PJ_POOL_ZALLOC_T(g722_codec_factory.pool, pjmedia_codec); + PJ_ASSERT_RETURN(codec != NULL, PJ_ENOMEM); + codec->op = &g722_op; + codec->factory = factory; - g722_data = PJ_POOL_ZALLOC_T(g722_codec_factory.pool, struct g722_data); - codec->codec_data = g722_data; + g722_data = PJ_POOL_ZALLOC_T(g722_codec_factory.pool, struct g722_data); + codec->codec_data = g722_data; #if !PLC_DISABLED - /* Create PLC */ - status = pjmedia_plc_create(g722_codec_factory.pool, 16000, - SAMPLES_PER_FRAME, 0, &g722_data->plc); - if (status != PJ_SUCCESS) { - pj_mutex_unlock(g722_codec_factory.mutex); - return status; - } + /* Create PLC */ + status = pjmedia_plc_create(g722_codec_factory.pool, 16000, + SAMPLES_PER_FRAME, 0, &g722_data->plc); + if (status != PJ_SUCCESS) { + pj_mutex_unlock(g722_codec_factory.mutex); + return status; + } #endif - /* Create silence detector */ - status = pjmedia_silence_det_create(g722_codec_factory.pool, - 16000, SAMPLES_PER_FRAME, - &g722_data->vad); - if (status != PJ_SUCCESS) { - pj_mutex_unlock(g722_codec_factory.mutex); - TRACE_((THIS_FILE, "Create silence detector failed (status = %d)", + /* Create silence detector */ + status = pjmedia_silence_det_create(g722_codec_factory.pool, + 16000, SAMPLES_PER_FRAME, + &g722_data->vad); + if (status != PJ_SUCCESS) { + pj_mutex_unlock(g722_codec_factory.mutex); + TRACE_((THIS_FILE, "Create silence detector failed (status = %d)", status)); - return status; - } + return status; + } } @@ -387,7 +386,7 @@ static pj_status_t g722_alloc_codec(pjmedia_codec_factory *factory, * Free codec. */ static pj_status_t g722_dealloc_codec(pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { struct g722_data *g722_data; int i; @@ -405,9 +404,9 @@ static pj_status_t g722_dealloc_codec(pjmedia_codec_factory *factory, * next time. */ for (i=0; i<2; ++i) { - pj_int16_t frame[SAMPLES_PER_FRAME]; - pjmedia_zero_samples(frame, PJ_ARRAY_SIZE(frame)); - pjmedia_plc_save(g722_data->plc, frame); + pj_int16_t frame[SAMPLES_PER_FRAME]; + pjmedia_zero_samples(frame, PJ_ARRAY_SIZE(frame)); + pjmedia_plc_save(g722_data->plc, frame); } #else PJ_UNUSED_ARG(i); @@ -428,7 +427,7 @@ static pj_status_t g722_dealloc_codec(pjmedia_codec_factory *factory, * Init codec. */ static pj_status_t g722_codec_init(pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(pool); @@ -439,7 +438,7 @@ static pj_status_t g722_codec_init(pjmedia_codec *codec, * Open codec. */ static pj_status_t g722_codec_open(pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { struct g722_data *g722_data = (struct g722_data*) codec->codec_data; pj_status_t status; @@ -449,16 +448,16 @@ static pj_status_t g722_codec_open(pjmedia_codec *codec, status = g722_enc_init(&g722_data->encoder); if (status != PJ_SUCCESS) { - TRACE_((THIS_FILE, "g722_enc_init() failed, status=%d", status)); - pj_mutex_unlock(g722_codec_factory.mutex); - return PJMEDIA_CODEC_EFAILED; + TRACE_((THIS_FILE, "g722_enc_init() failed, status=%d", status)); + pj_mutex_unlock(g722_codec_factory.mutex); + return PJMEDIA_CODEC_EFAILED; } status = g722_dec_init(&g722_data->decoder); if (status != PJ_SUCCESS) { - TRACE_((THIS_FILE, "g722_dec_init() failed, status=%d", status)); - pj_mutex_unlock(g722_codec_factory.mutex); - return PJMEDIA_CODEC_EFAILED; + TRACE_((THIS_FILE, "g722_dec_init() failed, status=%d", status)); + pj_mutex_unlock(g722_codec_factory.mutex); + return PJMEDIA_CODEC_EFAILED; } g722_data->vad_enabled = (attr->setting.vad != 0); @@ -468,7 +467,7 @@ static pj_status_t g722_codec_open(pjmedia_codec *codec, g722_data->pcm_min = -0x7FFF / g722_data->pcm_shift_val - 1; TRACE_((THIS_FILE, "G722 codec opened: vad=%d, plc=%d", - g722_data->vad_enabled, g722_data->plc_enabled)); + g722_data->vad_enabled, g722_data->plc_enabled)); return PJ_SUCCESS; } @@ -492,7 +491,7 @@ static pj_status_t g722_codec_close( pjmedia_codec *codec ) * Modify codec settings. */ static pj_status_t g722_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { struct g722_data *g722_data = (struct g722_data*) codec->codec_data; @@ -502,7 +501,7 @@ static pj_status_t g722_codec_modify(pjmedia_codec *codec, g722_data->plc_enabled = (attr->setting.plc != 0); TRACE_((THIS_FILE, "G722 codec modified: vad=%d, plc=%d", - g722_data->vad_enabled, g722_data->plc_enabled)); + g722_data->vad_enabled, g722_data->plc_enabled)); return PJ_SUCCESS; } @@ -511,11 +510,11 @@ static pj_status_t g722_codec_modify(pjmedia_codec *codec, * Get frames in the packet. */ static pj_status_t g722_codec_parse(pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { unsigned count = 0; @@ -526,15 +525,15 @@ static pj_status_t g722_codec_parse(pjmedia_codec *codec, TRACE_((THIS_FILE, "G722 parse(): input len=%d", pkt_size)); while (pkt_size >= FRAME_LEN && count < *frame_cnt) { - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = pkt; - frames[count].size = FRAME_LEN; - frames[count].timestamp.u64 = ts->u64 + count * SAMPLES_PER_FRAME; + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = pkt; + frames[count].size = FRAME_LEN; + frames[count].timestamp.u64 = ts->u64 + count * SAMPLES_PER_FRAME; - pkt = ((char*)pkt) + FRAME_LEN; - pkt_size -= FRAME_LEN; + pkt = ((char*)pkt) + FRAME_LEN; + pkt_size -= FRAME_LEN; - ++count; + ++count; } TRACE_((THIS_FILE, "G722 parse(): got %d frames", count)); @@ -547,9 +546,9 @@ static pj_status_t g722_codec_parse(pjmedia_codec *codec, * Encode frame. */ static pj_status_t g722_codec_encode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct g722_data *g722_data = (struct g722_data*) codec->codec_data; pj_status_t status; @@ -561,52 +560,52 @@ static pj_status_t g722_codec_encode(pjmedia_codec *codec, /* Detect silence */ if (g722_data->vad_enabled) { - pj_bool_t is_silence; - pj_int32_t silence_duration; - - silence_duration = pj_timestamp_diff32(&g722_data->last_tx, - &input->timestamp); - - is_silence = pjmedia_silence_det_detect(g722_data->vad, - (const pj_int16_t*) input->buf, - (input->size >> 1), - NULL); - if (is_silence && - (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || - silence_duration < PJMEDIA_CODEC_MAX_SILENCE_PERIOD*16000/1000)) - { - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->buf = NULL; - output->size = 0; - output->timestamp = input->timestamp; - return PJ_SUCCESS; - } else { - g722_data->last_tx = input->timestamp; - } + pj_bool_t is_silence; + pj_int32_t silence_duration; + + silence_duration = pj_timestamp_diff32(&g722_data->last_tx, + &input->timestamp); + + is_silence = pjmedia_silence_det_detect(g722_data->vad, + (const pj_int16_t*) input->buf, + (input->size >> 1), + NULL); + if (is_silence && + (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || + silence_duration < PJMEDIA_CODEC_MAX_SILENCE_PERIOD*16000/1000)) + { + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->buf = NULL; + output->size = 0; + output->timestamp = input->timestamp; + return PJ_SUCCESS; + } else { + g722_data->last_tx = input->timestamp; + } } /* Adjust input signal level from 16-bit to 14-bit */ if (g722_data->pcm_shift_val > 1) { - pj_int16_t *p, *end; - - p = (pj_int16_t*)input->buf; - end = p + input->size/2; - while (p < end) { - *p = *p / g722_data->pcm_shift_val; - ++p; - } + pj_int16_t *p, *end; + + p = (pj_int16_t*)input->buf; + end = p + input->size/2; + while (p < end) { + *p = *p / g722_data->pcm_shift_val; + ++p; + } } /* Encode to temporary buffer */ output->size = output_buf_len; status = g722_enc_encode(&g722_data->encoder, (pj_int16_t*)input->buf, - (input->size >> 1), output->buf, &output->size); + (input->size >> 1), output->buf, &output->size); if (status != PJ_SUCCESS) { - output->size = 0; - output->buf = NULL; - output->type = PJMEDIA_FRAME_TYPE_NONE; - TRACE_((THIS_FILE, "G722 encode() status: %d", status)); - return PJMEDIA_CODEC_EFAILED; + output->size = 0; + output->buf = NULL; + output->type = PJMEDIA_FRAME_TYPE_NONE; + TRACE_((THIS_FILE, "G722 encode() status: %d", status)); + return PJMEDIA_CODEC_EFAILED; } output->type = PJMEDIA_FRAME_TYPE_AUDIO; @@ -620,9 +619,9 @@ static pj_status_t g722_codec_encode(pjmedia_codec *codec, * Decode frame. */ static pj_status_t g722_codec_decode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct g722_data *g722_data = (struct g722_data*) codec->codec_data; pj_status_t status; @@ -631,57 +630,57 @@ static pj_status_t g722_codec_decode(pjmedia_codec *codec, PJ_ASSERT_RETURN(input && output, PJ_EINVAL); TRACE_((THIS_FILE, "G722 decode(): inbuf=%p, insize=%d, outbuf=%p," - "outsize=%d", - input->buf, input->size, output->buf, output_buf_len)); + "outsize=%d", + input->buf, input->size, output->buf, output_buf_len)); if (output_buf_len < SAMPLES_PER_FRAME * 2) { TRACE_((THIS_FILE, "G722 decode() ERROR: PJMEDIA_CODEC_EPCMTOOSHORT")); - return PJMEDIA_CODEC_EPCMTOOSHORT; + return PJMEDIA_CODEC_EPCMTOOSHORT; } if (input->size != FRAME_LEN) { TRACE_((THIS_FILE, "G722 decode() ERROR: PJMEDIA_CODEC_EFRMTOOSHORT")); - return PJMEDIA_CODEC_EFRMTOOSHORT; + return PJMEDIA_CODEC_EFRMTOOSHORT; } /* Decode */ output->size = SAMPLES_PER_FRAME; status = g722_dec_decode(&g722_data->decoder, input->buf, input->size, - (pj_int16_t*)output->buf, &output->size); + (pj_int16_t*)output->buf, &output->size); if (status != PJ_SUCCESS) { - TRACE_((THIS_FILE, "G722 decode() status: %d", status)); - return PJMEDIA_CODEC_EFAILED; + TRACE_((THIS_FILE, "G722 decode() status: %d", status)); + return PJMEDIA_CODEC_EFAILED; } pj_assert(output->size == SAMPLES_PER_FRAME); /* Adjust input signal level from 14-bit to 16-bit */ if (g722_data->pcm_shift_val > 1) { - pj_int16_t *p, *end; + pj_int16_t *p, *end; - p = (pj_int16_t*)output->buf; - end = p + output->size; - while (p < end) { + p = (pj_int16_t*)output->buf; + end = p + output->size; + while (p < end) { #if PJMEDIA_G722_STOP_PCM_SHIFT_ON_CLIPPING - /* If there is clipping, reduce/stop the PCM shifting */ - if (*p < g722_data->pcm_min || *p > g722_data->pcm_max) { - g722_data->pcm_shift_val /= 2; - g722_data->pcm_max = 0x7FFF/g722_data->pcm_shift_val; - g722_data->pcm_min = -0x7FFF/g722_data->pcm_shift_val-1; - break; - } + /* If there is clipping, reduce/stop the PCM shifting */ + if (*p < g722_data->pcm_min || *p > g722_data->pcm_max) { + g722_data->pcm_shift_val /= 2; + g722_data->pcm_max = 0x7FFF/g722_data->pcm_shift_val; + g722_data->pcm_min = -0x7FFF/g722_data->pcm_shift_val-1; + break; + } #else - /* Avoid PCM shift overflow if we don't stop on clipping */ - if (*p < g722_data->pcm_min) - *p = g722_data->pcm_min; - else if (*p > g722_data->pcm_max) - *p = g722_data->pcm_max; - + /* Avoid PCM shift overflow if we don't stop on clipping */ + if (*p < g722_data->pcm_min) + *p = g722_data->pcm_min; + else if (*p > g722_data->pcm_max) + *p = g722_data->pcm_max; + #endif - *p = *p * g722_data->pcm_shift_val; - ++p; - } + *p = *p * g722_data->pcm_shift_val; + ++p; + } } output->size = SAMPLES_PER_FRAME * 2; @@ -690,7 +689,7 @@ static pj_status_t g722_codec_decode(pjmedia_codec *codec, #if !PLC_DISABLED if (g722_data->plc_enabled) - pjmedia_plc_save(g722_data->plc, (pj_int16_t*)output->buf); + pjmedia_plc_save(g722_data->plc, (pj_int16_t*)output->buf); #endif TRACE_((THIS_FILE, "G722 decode done")); @@ -703,8 +702,8 @@ static pj_status_t g722_codec_decode(pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t g722_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { struct g722_data *g722_data = (struct g722_data*)codec->codec_data; diff --git a/pjmedia/src/pjmedia-codec/g722/g722_dec.c b/pjmedia/src/pjmedia-codec/g722/g722_dec.c index d04ee3aa47..c5c3f1c141 100644 --- a/pjmedia/src/pjmedia-codec/g722/g722_dec.c +++ b/pjmedia/src/pjmedia-codec/g722/g722_dec.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -40,7 +39,7 @@ extern const int g722_qmf_coeff[24]; static const int qm4[16] = { - 0, -20456, -12896, -8968, + 0, -20456, -12896, -8968, -6288, -4240, -2584, -1200, 20456, 12896, 8968, 6288, 4240, 2584, 1200, 0 @@ -73,10 +72,10 @@ static int block3l (g722_dec_t *dec, int il) int detl ; int ril, il4, wd, wd1, wd2, wd3, nbpl, depl ; static const int wl[8] = { - -60, -30, 58, 172, 334, 538, 1198, 3042 + -60, -30, 58, 172, 334, 538, 1198, 3042 }; static const int rl42[16] = { - 0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0 + 0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0 }; /* LOGSCL */ @@ -166,24 +165,24 @@ static int block4l (g722_dec_t *dec, int dl) dec->sgl[0] = dec->dlt[0] >> 15 ; for ( i = 1; i < 7; i++ ) { - dec->sgl[i] = dec->dlt[i] >> 15 ; - if ( dec->sgl[i] == dec->sgl[0] ) wd2 = wd1 ; - else wd2 = - wd1 ; - wd3 = (dec->bl[i] * 32640) >> 15 ; - dec->bpl[i] = wd2 + wd3 ; - SATURATE(dec->bpl[i], 32767, -32768); + dec->sgl[i] = dec->dlt[i] >> 15 ; + if ( dec->sgl[i] == dec->sgl[0] ) wd2 = wd1 ; + else wd2 = - wd1 ; + wd3 = (dec->bl[i] * 32640) >> 15 ; + dec->bpl[i] = wd2 + wd3 ; + SATURATE(dec->bpl[i], 32767, -32768); } /* DELAYA */ for ( i = 6; i > 0; i-- ) { - dec->dlt[i] = dec->dlt[i-1] ; - dec->bl[i] = dec->bpl[i] ; + dec->dlt[i] = dec->dlt[i-1] ; + dec->bl[i] = dec->bpl[i] ; } for ( i = 2; i > 0; i-- ) { - dec->rlt[i] = dec->rlt[i-1] ; - dec->plt[i] = dec->plt[i-1] ; - dec->al[i] = dec->apl[i] ; + dec->rlt[i] = dec->rlt[i-1] ; + dec->plt[i] = dec->plt[i-1] ; + dec->al[i] = dec->apl[i] ; } /* FILTEP */ @@ -201,10 +200,10 @@ static int block4l (g722_dec_t *dec, int dl) /* FILTEZ */ dec->szl = 0 ; for (i=6; i>0; i--) { - wd = dec->dlt[i] << 1; - SATURATE(wd, 32767, -32768); - dec->szl += (dec->bl[i] * wd) >> 15 ; - SATURATE(dec->szl, 32767, -32768); + wd = dec->dlt[i] << 1; + SATURATE(wd, 32767, -32768); + dec->szl += (dec->bl[i] * wd) >> 15 ; + SATURATE(dec->szl, 32767, -32768); } /* PREDIC */ @@ -219,48 +218,48 @@ static int block5l (int ilr, int sl, int detl, int mode) int yl ; int ril, dl, wd2 = 0; static const int qm5[32] = { - -280, -280, -23352, -17560, - -14120, -11664, -9752, -8184, - -6864, -5712, -4696, -3784, - -2960, -2208, -1520, -880, - 23352, 17560, 14120, 11664, - 9752, 8184, 6864, 5712, - 4696, 3784, 2960, 2208, - 1520, 880, 280, -280 + -280, -280, -23352, -17560, + -14120, -11664, -9752, -8184, + -6864, -5712, -4696, -3784, + -2960, -2208, -1520, -880, + 23352, 17560, 14120, 11664, + 9752, 8184, 6864, 5712, + 4696, 3784, 2960, 2208, + 1520, 880, 280, -280 }; static const int qm6[64] = { - -136, -136, -136, -136, - -24808, -21904, -19008, -16704, - -14984, -13512, -12280, -11192, - -10232, -9360, -8576, -7856, - -7192, -6576, -6000, -5456, - -4944, -4464, -4008, -3576, - -3168, -2776, -2400, -2032, - -1688, -1360, -1040, -728, - 24808, 21904, 19008, 16704, - 14984, 13512, 12280, 11192, - 10232, 9360, 8576, 7856, - 7192, 6576, 6000, 5456, - 4944, 4464, 4008, 3576, - 3168, 2776, 2400, 2032, - 1688, 1360, 1040, 728, - 432, 136, -432, -136 + -136, -136, -136, -136, + -24808, -21904, -19008, -16704, + -14984, -13512, -12280, -11192, + -10232, -9360, -8576, -7856, + -7192, -6576, -6000, -5456, + -4944, -4464, -4008, -3576, + -3168, -2776, -2400, -2032, + -1688, -1360, -1040, -728, + 24808, 21904, 19008, 16704, + 14984, 13512, 12280, 11192, + 10232, 9360, 8576, 7856, + 7192, 6576, 6000, 5456, + 4944, 4464, 4008, 3576, + 3168, 2776, 2400, 2032, + 1688, 1360, 1040, 728, + 432, 136, -432, -136 }; /* INVQBL */ if (mode == 1) { - ril = ilr ; - wd2 = qm6[ril] ; + ril = ilr ; + wd2 = qm6[ril] ; } if (mode == 2) { - ril = ilr >> 1 ; - wd2 = qm5[ril] ; + ril = ilr >> 1 ; + wd2 = qm5[ril] ; } if (mode == 3) { - ril = ilr >> 2 ; - wd2 = qm4[ril] ; + ril = ilr >> 2 ; + wd2 = qm4[ril] ; } dl = (detl * wd2 ) >> 15 ; @@ -393,23 +392,23 @@ static int block4h (g722_dec_t *dec, int d) dec->sgh[0] = dec->dh[0] >> 15 ; for ( i = 1; i < 7; i++ ) { - dec->sgh[i] = dec->dh[i] >> 15 ; - if ( dec->sgh[i] == dec->sgh[0] ) wd2 = wd1 ; - else wd2 = - wd1 ; - wd3 = (dec->bh[i] * 32640) >> 15 ; - dec->bph[i] = wd2 + wd3 ; + dec->sgh[i] = dec->dh[i] >> 15 ; + if ( dec->sgh[i] == dec->sgh[0] ) wd2 = wd1 ; + else wd2 = - wd1 ; + wd3 = (dec->bh[i] * 32640) >> 15 ; + dec->bph[i] = wd2 + wd3 ; } /* DELAYA */ for ( i = 6; i > 0; i-- ) { - dec->dh[i] = dec->dh[i-1] ; - dec->bh[i] = dec->bph[i] ; + dec->dh[i] = dec->dh[i-1] ; + dec->bh[i] = dec->bph[i] ; } for ( i = 2; i > 0; i-- ) { - dec->rh[i] = dec->rh[i-1] ; - dec->ph[i] = dec->ph[i-1] ; - dec->ah[i] = dec->aph[i] ; + dec->rh[i] = dec->rh[i-1] ; + dec->ph[i] = dec->ph[i-1] ; + dec->ah[i] = dec->aph[i] ; } /* FILTEP */ @@ -427,10 +426,10 @@ static int block4h (g722_dec_t *dec, int d) /* FILTEZ */ dec->szh = 0 ; for (i=6; i>0; i--) { - wd = dec->dh[i] << 1; - SATURATE(wd, 32767, -32768); - dec->szh += (dec->bh[i] * wd) >> 15 ; - SATURATE(dec->szh, 32767, -32768); + wd = dec->dh[i] << 1; + SATURATE(wd, 32767, -32768); + dec->szh += (dec->bh[i] * wd) >> 15 ; + SATURATE(dec->szh, 32767, -32768); } /* PREDIC */ @@ -496,10 +495,10 @@ PJ_DEF(pj_status_t) g722_dec_init(g722_dec_t *dec) } PJ_DEF(pj_status_t) g722_dec_decode( g722_dec_t *dec, - void *in, - pj_size_t in_size, - pj_int16_t out[], - pj_size_t *nsamples) + void *in, + pj_size_t in_size, + pj_int16_t out[], + pj_size_t *nsamples) { unsigned i; int ilowr, ylow, rlow, dlowt; @@ -511,27 +510,27 @@ PJ_DEF(pj_status_t) g722_dec_decode( g722_dec_t *dec, PJ_ASSERT_RETURN(*nsamples >= (in_size << 1), PJ_ETOOSMALL); for(i = 0; i < in_size; ++i) { - ilowr = in_[i] & 63; - ihigh = (in_[i] >> 6) & 3; - - /* low band decoder */ - ylow = block5l (ilowr, dec->slow, dec->detlow, MODE) ; - rlow = block6l (ylow) ; - dlowt = block2l (ilowr, dec->detlow) ; - dec->detlow = block3l (dec, ilowr) ; - dec->slow = block4l (dec, dlowt) ; - /* rlow <= output low band pcm */ - - /* high band decoder */ - dhigh = block2h (ihigh, dec->dethigh) ; - rhigh = block5h (dhigh, dec->shigh) ; - dec->dethigh = block3h (dec, ihigh) ; - dec->shigh = block4h (dec, dhigh) ; - /* rhigh <= output high band pcm */ - - rx_qmf(dec, rlow, rhigh, &pcm1, &pcm2); - out[i*2] = (pj_int16_t)pcm1; - out[i*2+1] = (pj_int16_t)pcm2; + ilowr = in_[i] & 63; + ihigh = (in_[i] >> 6) & 3; + + /* low band decoder */ + ylow = block5l (ilowr, dec->slow, dec->detlow, MODE) ; + rlow = block6l (ylow) ; + dlowt = block2l (ilowr, dec->detlow) ; + dec->detlow = block3l (dec, ilowr) ; + dec->slow = block4l (dec, dlowt) ; + /* rlow <= output low band pcm */ + + /* high band decoder */ + dhigh = block2h (ihigh, dec->dethigh) ; + rhigh = block5h (dhigh, dec->shigh) ; + dec->dethigh = block3h (dec, ihigh) ; + dec->shigh = block4h (dec, dhigh) ; + /* rhigh <= output high band pcm */ + + rx_qmf(dec, rlow, rhigh, &pcm1, &pcm2); + out[i*2] = (pj_int16_t)pcm1; + out[i*2+1] = (pj_int16_t)pcm2; } *nsamples = in_size << 1; diff --git a/pjmedia/src/pjmedia-codec/g722/g722_dec.h b/pjmedia/src/pjmedia-codec/g722/g722_dec.h index a29a82b87a..54de4b5f2b 100644 --- a/pjmedia/src/pjmedia-codec/g722/g722_dec.h +++ b/pjmedia/src/pjmedia-codec/g722/g722_dec.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -68,10 +67,10 @@ typedef struct g722_dec_t { PJ_DECL(pj_status_t) g722_dec_init(g722_dec_t *dec); PJ_DECL(pj_status_t) g722_dec_decode(g722_dec_t *dec, - void *in, - pj_size_t in_size, - pj_int16_t out[], - pj_size_t *nsamples); + void *in, + pj_size_t in_size, + pj_int16_t out[], + pj_size_t *nsamples); PJ_DECL(pj_status_t) g722_dec_deinit(g722_dec_t *dec); diff --git a/pjmedia/src/pjmedia-codec/g722/g722_enc.c b/pjmedia/src/pjmedia-codec/g722/g722_enc.c index bd5644d902..ee4ce8e53b 100644 --- a/pjmedia/src/pjmedia-codec/g722/g722_enc.c +++ b/pjmedia/src/pjmedia-codec/g722/g722_enc.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,10 +35,10 @@ /* QMF tap coefficients */ const int g722_qmf_coeff[24] = { - 3, -11, -11, 53, 12, -156, - 32, 362, -210, -805, 951, 3876, + 3, -11, -11, 53, 12, -156, + 32, 362, -210, -805, 951, 3876, 3876, 951, -805, -210, 362, 32, - -156, 12, 53, -11, -11, 3 + -156, 12, 53, -11, -11, 3 }; @@ -50,22 +49,22 @@ static int block1l (int xl, int sl, int detl) int i, el, sil, mil, wd, wd1, hdu ; static const int q6[32] = { - 0, 35, 72, 110, 150, 190, 233, 276, 323, - 370, 422, 473, 530, 587, 650, 714, 786, - 858, 940, 1023, 1121, 1219, 1339, 1458, - 1612, 1765, 1980, 2195, 2557, 2919, 0, 0 + 0, 35, 72, 110, 150, 190, 233, 276, 323, + 370, 422, 473, 530, 587, 650, 714, 786, + 858, 940, 1023, 1121, 1219, 1339, 1458, + 1612, 1765, 1980, 2195, 2557, 2919, 0, 0 }; static const int iln[32] = { - 0, 63, 62, 31, 30, 29, 28, 27, 26, 25, - 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, - 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 0 + 0, 63, 62, 31, 30, 29, 28, 27, 26, 25, + 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, + 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 0 }; static const int ilp[32] = { - 0, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, - 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, - 40, 39, 38, 37, 36, 35, 34, 33, 32, 0 + 0, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, + 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, + 40, 39, 38, 37, 36, 35, 34, 33, 32, 0 }; /* SUBTRA */ @@ -82,10 +81,10 @@ static int block1l (int xl, int sl, int detl) mil = 1 ; for (i = 1; i < 30; i++) { - hdu = (q6[i] << 3) * detl; - wd1 = (hdu >> 15) ; - if (wd >= wd1) mil = (i + 1) ; - else break ; + hdu = (q6[i] << 3) * detl; + wd1 = (hdu >> 15) ; + if (wd >= wd1) mil = (i + 1) ; + else break ; } if (sil == -1 ) il = iln[mil] ; @@ -99,10 +98,10 @@ static int block2l (int il, int detl) int dlt; int ril, wd2 ; static const int qm4[16] = { - 0, -20456, -12896, -8968, - -6288, -4240, -2584, -1200, - 20456, 12896, 8968, 6288, - 4240, 2584, 1200, 0 + 0, -20456, -12896, -8968, + -6288, -4240, -2584, -1200, + 20456, 12896, 8968, 6288, + 4240, 2584, 1200, 0 }; /* INVQAL */ @@ -118,17 +117,17 @@ static int block3l (g722_enc_t *enc, int il) int detl; int ril, il4, wd, wd1, wd2, wd3, nbpl, depl ; static int const wl[8] = { - -60, -30, 58, 172, 334, 538, 1198, 3042 + -60, -30, 58, 172, 334, 538, 1198, 3042 } ; static int const rl42[16] = { - 0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0 + 0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0 }; static const int ilb[32] = { - 2048, 2093, 2139, 2186, 2233, 2282, 2332, - 2383, 2435, 2489, 2543, 2599, 2656, 2714, - 2774, 2834, 2896, 2960, 3025, 3091, 3158, - 3228, 3298, 3371, 3444, 3520, 3597, 3676, - 3756, 3838, 3922, 4008 + 2048, 2093, 2139, 2186, 2233, 2282, 2332, + 2383, 2435, 2489, 2543, 2599, 2656, 2714, + 2774, 2834, 2896, 2960, 3025, 3091, 3158, + 3228, 3298, 3371, 3444, 3520, 3597, 3676, + 3756, 3838, 3922, 4008 }; /* LOGSCL */ @@ -157,10 +156,10 @@ static int block3l (g722_enc_t *enc, int il) detl = depl ; #ifdef DEBUG_VERBOSE - printf ("BLOCK3L il=%4d, ril=%4d, il4=%4d, nbl=%4d, wd=%4d, nbpl=%4d\n", - il, ril, il4, enc->nbl, wd, nbpl) ; - printf ("wd1=%4d, wd2=%4d, wd3=%4d, depl=%4d, detl=%4d\n", - wd1, wd2, wd3, depl, detl) ; + printf ("BLOCK3L il=%4d, ril=%4d, il4=%4d, nbl=%4d, wd=%4d, nbpl=%4d\n", + il, ril, il4, enc->nbl, wd, nbpl) ; + printf ("wd1=%4d, wd2=%4d, wd3=%4d, depl=%4d, detl=%4d\n", + wd1, wd2, wd3, depl, detl) ; #endif return (detl) ; @@ -235,25 +234,25 @@ static int block4l (g722_enc_t *enc, int dl) enc->sgl[0] = enc->dlt[0] >> 15 ; for ( i = 1; i < 7; i++ ) { - enc->sgl[i] = enc->dlt[i] >> 15 ; - if ( enc->sgl[i] == enc->sgl[0] ) wd2 = wd1 ; - else wd2 = - wd1 ; - wd3 = (enc->bl[i] * 32640) >> 15 ; - enc->bpl[i] = wd2 + wd3 ; - SATURATE(enc->bpl[i], 32767, -32768); + enc->sgl[i] = enc->dlt[i] >> 15 ; + if ( enc->sgl[i] == enc->sgl[0] ) wd2 = wd1 ; + else wd2 = - wd1 ; + wd3 = (enc->bl[i] * 32640) >> 15 ; + enc->bpl[i] = wd2 + wd3 ; + SATURATE(enc->bpl[i], 32767, -32768); } /* DELAYA */ for ( i = 6; i > 0; i-- ) { - enc->dlt[i] = enc->dlt[i-1] ; - enc->bl[i] = enc->bpl[i] ; + enc->dlt[i] = enc->dlt[i-1] ; + enc->bl[i] = enc->bpl[i] ; } for ( i = 2; i > 0; i-- ) { - enc->rlt[i] = enc->rlt[i-1] ; - enc->plt[i] = enc->plt[i-1] ; - enc->al[i] = enc->apl[i] ; + enc->rlt[i] = enc->rlt[i-1] ; + enc->plt[i] = enc->plt[i-1] ; + enc->al[i] = enc->apl[i] ; } /* FILTEP */ @@ -273,10 +272,10 @@ static int block4l (g722_enc_t *enc, int dl) enc->szl = 0 ; for (i=6; i>0; i--) { - wd = enc->dlt[i] + enc->dlt[i]; - SATURATE(wd, 32767, -32768); - enc->szl += (enc->bl[i] * wd) >> 15 ; - SATURATE(enc->szl, 32767, -32768); + wd = enc->dlt[i] + enc->dlt[i]; + SATURATE(wd, 32767, -32768); + enc->szl += (enc->bl[i] * wd) >> 15 ; + SATURATE(enc->szl, 32767, -32768); } /* PREDIC */ @@ -339,11 +338,11 @@ static int block3h (g722_enc_t *enc, int ih) static const int wh[3] = {0, -214, 798} ; static const int rh2[4] = {2, 1, 2, 1} ; static const int ilb[32] = { - 2048, 2093, 2139, 2186, 2233, 2282, 2332, - 2383, 2435, 2489, 2543, 2599, 2656, 2714, - 2774, 2834, 2896, 2960, 3025, 3091, 3158, - 3228, 3298, 3371, 3444, 3520, 3597, 3676, - 3756, 3838, 3922, 4008 + 2048, 2093, 2139, 2186, 2233, 2282, 2332, + 2383, 2435, 2489, 2543, 2599, 2656, 2714, + 2774, 2834, 2896, 2960, 3025, 3091, 3158, + 3228, 3298, 3371, 3444, 3520, 3597, 3676, + 3756, 3838, 3922, 4008 }; /* LOGSCH */ @@ -440,24 +439,24 @@ static int block4h (g722_enc_t *enc, int d) enc->sgh[0] = enc->dh[0] >> 15 ; for ( i = 1; i < 7; i++ ) { - enc->sgh[i] = enc->dh[i] >> 15 ; - if ( enc->sgh[i] == enc->sgh[0] ) wd2 = wd1 ; - else wd2 = - wd1 ; - wd3 = (enc->bh[i] * 32640) >> 15 ; - enc->bph[i] = wd2 + wd3 ; - SATURATE(enc->bph[i], 32767, -32768); + enc->sgh[i] = enc->dh[i] >> 15 ; + if ( enc->sgh[i] == enc->sgh[0] ) wd2 = wd1 ; + else wd2 = - wd1 ; + wd3 = (enc->bh[i] * 32640) >> 15 ; + enc->bph[i] = wd2 + wd3 ; + SATURATE(enc->bph[i], 32767, -32768); } /* DELAYA */ for ( i = 6; i > 0; i-- ) { - enc->dh[i] = enc->dh[i-1] ; - enc->bh[i] = enc->bph[i] ; + enc->dh[i] = enc->dh[i-1] ; + enc->bh[i] = enc->bph[i] ; } for ( i = 2; i > 0; i-- ) { - enc->rh[i] = enc->rh[i-1] ; - enc->ph[i] = enc->ph[i-1] ; - enc->ah[i] = enc->aph[i] ; + enc->rh[i] = enc->rh[i-1] ; + enc->ph[i] = enc->ph[i-1] ; + enc->ah[i] = enc->aph[i] ; } /* FILTEP */ @@ -477,10 +476,10 @@ static int block4h (g722_enc_t *enc, int d) enc->szh = 0 ; for (i=6; i>0; i--) { - wd = enc->dh[i] + enc->dh[i]; - SATURATE(wd, 32767, -32768); - enc->szh += (enc->bh[i] * wd) >> 15 ; - SATURATE(enc->szh, 32767, -32768); + wd = enc->dh[i] + enc->dh[i]; + SATURATE(wd, 32767, -32768); + enc->szh += (enc->bh[i] * wd) >> 15 ; + SATURATE(enc->szh, 32767, -32768); } /* PREDIC */ @@ -528,10 +527,10 @@ PJ_DEF(pj_status_t) g722_enc_init(g722_enc_t *enc) } PJ_DEF(pj_status_t) g722_enc_encode( g722_enc_t *enc, - pj_int16_t in[], - pj_size_t nsamples, - void *out, - pj_size_t *out_size) + pj_int16_t in[], + pj_size_t nsamples, + void *out, + pj_size_t *out_size) { unsigned i; int xlow, ilow, dlowt; @@ -543,22 +542,22 @@ PJ_DEF(pj_status_t) g722_enc_encode( g722_enc_t *enc, PJ_ASSERT_RETURN(*out_size >= (nsamples >> 1), PJ_ETOOSMALL); for(i = 0; i < nsamples; i += 2) { - tx_qmf(enc, in[i], in[i+1], &xlow, &xhigh); - - /* low band encoder */ - ilow = block1l (xlow, enc->slow, enc->detlow) ; - dlowt = block2l (ilow, enc->detlow) ; - enc->detlow = block3l (enc, ilow) ; - enc->slow = block4l (enc, dlowt) ; - - /* high band encoder */ - ihigh = block1h (xhigh, enc->shigh, enc->dethigh) ; - dhigh = block2h (ihigh, enc->dethigh) ; - enc->dethigh = block3h (enc, ihigh) ; - enc->shigh = block4h (enc, dhigh) ; - - /* bits mix low & high adpcm */ - out_[i/2] = (pj_uint8_t)((ihigh << 6) | ilow); + tx_qmf(enc, in[i], in[i+1], &xlow, &xhigh); + + /* low band encoder */ + ilow = block1l (xlow, enc->slow, enc->detlow) ; + dlowt = block2l (ilow, enc->detlow) ; + enc->detlow = block3l (enc, ilow) ; + enc->slow = block4l (enc, dlowt) ; + + /* high band encoder */ + ihigh = block1h (xhigh, enc->shigh, enc->dethigh) ; + dhigh = block2h (ihigh, enc->dethigh) ; + enc->dethigh = block3h (enc, ihigh) ; + enc->shigh = block4h (enc, dhigh) ; + + /* bits mix low & high adpcm */ + out_[i/2] = (pj_uint8_t)((ihigh << 6) | ilow); } *out_size = nsamples >> 1; diff --git a/pjmedia/src/pjmedia-codec/g722/g722_enc.h b/pjmedia/src/pjmedia-codec/g722/g722_enc.h index eb0e3904f5..59da85f19c 100644 --- a/pjmedia/src/pjmedia-codec/g722/g722_enc.h +++ b/pjmedia/src/pjmedia-codec/g722/g722_enc.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -67,10 +66,10 @@ typedef struct g722_enc_t { PJ_DECL(pj_status_t) g722_enc_init(g722_enc_t *enc); PJ_DECL(pj_status_t) g722_enc_encode(g722_enc_t *enc, - pj_int16_t in[], - pj_size_t nsamples, - void *out, - pj_size_t *out_size); + pj_int16_t in[], + pj_size_t nsamples, + void *out, + pj_size_t *out_size); PJ_DECL(pj_status_t) g722_enc_deinit(g722_enc_t *enc); diff --git a/pjmedia/src/pjmedia-codec/g7221.c b/pjmedia/src/pjmedia-codec/g7221.c index c860557361..8616043f48 100644 --- a/pjmedia/src/pjmedia-codec/g7221.c +++ b/pjmedia/src/pjmedia-codec/g7221.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,63 +37,63 @@ #include "../../../third_party/g7221/common/defs.h" -#define THIS_FILE "g7221.c" +#define THIS_FILE "g7221.c" /* Codec tag, it is the SDP encoding name and also MIME subtype name */ -#define CODEC_TAG "G7221" +#define CODEC_TAG "G7221" /* Sampling rates definition */ -#define WB_SAMPLE_RATE 16000 -#define UWB_SAMPLE_RATE 32000 +#define WB_SAMPLE_RATE 16000 +#define UWB_SAMPLE_RATE 32000 /* Maximum number of samples per frame. */ #define MAX_SAMPLES_PER_FRAME (UWB_SAMPLE_RATE * 20 / 1000) /* Maximum number of codec params. */ -#define MAX_CODEC_MODES 8 +#define MAX_CODEC_MODES 8 #define START_RSV_MODES_IDX 6 /* Prototypes for G722.1 codec factory */ static pj_status_t test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ); + const pjmedia_codec_info *id ); static pj_status_t default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ); static pj_status_t enum_codecs( pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for G722.1 codec implementation. */ static pj_status_t codec_init( pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t codec_close( pjmedia_codec *codec ); static pj_status_t codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t codec_recover( pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); /* Definition for G722.1 codec operations. */ static pjmedia_codec_op codec_op = @@ -124,60 +123,60 @@ static pjmedia_codec_factory_op codec_factory_op = /* Structure of G722.1 mode */ typedef struct codec_mode { - pj_bool_t enabled; /* Is this mode enabled? */ - pj_uint8_t pt; /* Payload type. */ - unsigned sample_rate; /* Default sampling rate to be used.*/ - unsigned bitrate; /* Bitrate. */ - char bitrate_str[8]; /* Bitrate in string. */ + pj_bool_t enabled; /* Is this mode enabled? */ + pj_uint8_t pt; /* Payload type. */ + unsigned sample_rate; /* Default sampling rate to be used.*/ + unsigned bitrate; /* Bitrate. */ + char bitrate_str[8]; /* Bitrate in string. */ } codec_mode; /* G722.1 codec factory */ static struct codec_factory { - pjmedia_codec_factory base; /**< Base class. */ - pjmedia_endpt *endpt; /**< PJMEDIA endpoint instance. */ - pj_pool_t *pool; /**< Codec factory pool. */ - pj_mutex_t *mutex; /**< Codec factory mutex. */ - - int pcm_shift; /**< Level adjustment */ - unsigned mode_count; /**< Number of G722.1 modes. */ - codec_mode modes[MAX_CODEC_MODES]; /**< The G722.1 modes. */ - unsigned mode_rsv_start;/**< Start index of G722.1 non- - standard modes, currently - there can only be up to two - non-standard modes enabled - at the same time. */ + pjmedia_codec_factory base; /**< Base class. */ + pjmedia_endpt *endpt; /**< PJMEDIA endpoint instance. */ + pj_pool_t *pool; /**< Codec factory pool. */ + pj_mutex_t *mutex; /**< Codec factory mutex. */ + + int pcm_shift; /**< Level adjustment */ + unsigned mode_count; /**< Number of G722.1 modes. */ + codec_mode modes[MAX_CODEC_MODES]; /**< The G722.1 modes. */ + unsigned mode_rsv_start;/**< Start index of G722.1 non- + standard modes, currently + there can only be up to two + non-standard modes enabled + at the same time. */ } codec_factory; /* G722.1 codec private data. */ typedef struct codec_private { - pj_pool_t *pool; /**< Pool for each instance. */ - pj_bool_t plc_enabled; /**< PLC enabled? */ - pj_bool_t vad_enabled; /**< VAD enabled? */ - pjmedia_silence_det *vad; /**< PJMEDIA VAD instance. */ - pj_timestamp last_tx; /**< Timestamp of last transmit.*/ + pj_pool_t *pool; /**< Pool for each instance. */ + pj_bool_t plc_enabled; /**< PLC enabled? */ + pj_bool_t vad_enabled; /**< VAD enabled? */ + pjmedia_silence_det *vad; /**< PJMEDIA VAD instance. */ + pj_timestamp last_tx; /**< Timestamp of last transmit.*/ /* ITU ref implementation seems to leave the codec engine states to be * managed by the application, so here we go. */ /* Common engine state */ - pj_uint16_t samples_per_frame; /**< Samples per frame. */ - pj_uint16_t bitrate; /**< Coded stream bitrate. */ - pj_uint16_t frame_size; /**< Coded frame size. */ - pj_uint16_t frame_size_bits; /**< Coded frame size in bits. */ - pj_uint16_t number_of_regions; /**< Number of regions. */ - pj_int16_t pcm_shift_val; /**< Adjustment for PCM in/out */ + pj_uint16_t samples_per_frame; /**< Samples per frame. */ + pj_uint16_t bitrate; /**< Coded stream bitrate. */ + pj_uint16_t frame_size; /**< Coded frame size. */ + pj_uint16_t frame_size_bits; /**< Coded frame size in bits. */ + pj_uint16_t number_of_regions; /**< Number of regions. */ + pj_int16_t pcm_shift_val; /**< Adjustment for PCM in/out */ /* Encoder specific state */ - Word16 *enc_frame; /**< 16bit to 14bit buffer */ - Word16 *enc_old_frame; + Word16 *enc_frame; /**< 16bit to 14bit buffer */ + Word16 *enc_old_frame; /* Decoder specific state */ - Word16 *dec_old_frame; - Rand_Obj dec_randobj; - Word16 dec_old_mag_shift; - Word16 *dec_old_mlt_coefs; + Word16 *dec_old_frame; + Rand_Obj dec_randobj; + Word16 dec_old_mag_shift; + Word16 *dec_old_mlt_coefs; } codec_private_t; /* @@ -189,9 +188,9 @@ static codec_mode* lookup_mode(unsigned pt) unsigned i; for (i = 0; i < codec_factory.mode_count; ++i) { - mode = &codec_factory.modes[i]; - if (mode->pt == pt) - break; + mode = &codec_factory.modes[i]; + if (mode->pt == pt) + break; } return mode; @@ -209,19 +208,19 @@ static codec_mode* lookup_mode(unsigned pt) static pj_bool_t validate_mode(unsigned sample_rate, unsigned bitrate) { if (sample_rate == WB_SAMPLE_RATE) { - if (bitrate < 16000 || bitrate > 32000 || - ((bitrate-16000) % 400 != 0)) - { - return PJ_FALSE; - } + if (bitrate < 16000 || bitrate > 32000 || + ((bitrate-16000) % 400 != 0)) + { + return PJ_FALSE; + } } else if (sample_rate == UWB_SAMPLE_RATE) { - if (bitrate < 24000 || bitrate > 48000 || - ((bitrate-24000) % 400 != 0)) - { - return PJ_FALSE; - } + if (bitrate < 24000 || bitrate > 48000 || + ((bitrate-24000) % 400 != 0)) + { + return PJ_FALSE; + } } else { - return PJ_FALSE; + return PJ_FALSE; } return PJ_TRUE; @@ -232,8 +231,8 @@ PJ_INLINE(void) swap_bytes(pj_uint16_t *buf, unsigned count) { pj_uint16_t *end = buf + count; while (buf != end) { - *buf = (pj_uint16_t)((*buf << 8) | (*buf >> 8)); - ++buf; + *buf = (pj_uint16_t)((*buf << 8) | (*buf >> 8)); + ++buf; } } #else @@ -251,8 +250,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_g7221_init( pjmedia_endpt *endpt ) pj_status_t status; if (codec_factory.pool != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } /* Initialize codec modes, by default all standard bitrates are enabled */ @@ -322,44 +321,44 @@ PJ_DEF(pj_status_t) pjmedia_codec_g7221_init( pjmedia_endpt *endpt ) codec_factory.endpt = endpt; codec_factory.pool = pjmedia_endpt_create_pool(endpt, "G722.1 codec", - 4000, 4000); + 4000, 4000); if (!codec_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create mutex. */ status = pj_mutex_create_simple(codec_factory.pool, "G722.1 codec", - &codec_factory.mutex); + &codec_factory.mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - status = PJ_EINVALIDOP; - goto on_error; + status = PJ_EINVALIDOP; + goto on_error; } /* Register format match callback. */ pj_cstr(&codec_name, CODEC_TAG); status = pjmedia_sdp_neg_register_fmt_match_cb( - &codec_name, - &pjmedia_codec_g7221_match_sdp); + &codec_name, + &pjmedia_codec_g7221_match_sdp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Register codec factory to endpoint. */ status = pjmedia_codec_mgr_register_factory(codec_mgr, - &codec_factory.base); + &codec_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Done. */ return PJ_SUCCESS; on_error: if (codec_factory.mutex) { - pj_mutex_destroy(codec_factory.mutex); - codec_factory.mutex = NULL; + pj_mutex_destroy(codec_factory.mutex); + codec_factory.mutex = NULL; } pj_pool_release(codec_factory.pool); @@ -372,35 +371,35 @@ PJ_DEF(pj_status_t) pjmedia_codec_g7221_init( pjmedia_endpt *endpt ) * Enable and disable G722.1 modes, including non-standard modes. */ PJ_DEF(pj_status_t) pjmedia_codec_g7221_set_mode(unsigned sample_rate, - unsigned bitrate, - pj_bool_t enabled) + unsigned bitrate, + pj_bool_t enabled) { pjmedia_codec_mgr *codec_mgr; unsigned i; /* Validate mode */ if (!validate_mode(sample_rate, bitrate)) - return PJMEDIA_CODEC_EINMODE; + return PJMEDIA_CODEC_EINMODE; /* Get codec manager */ codec_mgr = pjmedia_endpt_get_codec_mgr(codec_factory.endpt); if (!codec_mgr) - return PJMEDIA_CODEC_EFAILED; + return PJMEDIA_CODEC_EFAILED; /* Look up in factory modes table */ for (i = 0; i < codec_factory.mode_count; ++i) { - if (codec_factory.modes[i].sample_rate == sample_rate && - codec_factory.modes[i].bitrate == bitrate) - { - codec_factory.modes[i].enabled = enabled; - - /* Re-register G722.1 codec factory to update codec list */ - pjmedia_codec_mgr_unregister_factory(codec_mgr, - &codec_factory.base); - pjmedia_codec_mgr_register_factory(codec_mgr, - &codec_factory.base); - return PJ_SUCCESS; - } + if (codec_factory.modes[i].sample_rate == sample_rate && + codec_factory.modes[i].bitrate == bitrate) + { + codec_factory.modes[i].enabled = enabled; + + /* Re-register G722.1 codec factory to update codec list */ + pjmedia_codec_mgr_unregister_factory(codec_mgr, + &codec_factory.base); + pjmedia_codec_mgr_register_factory(codec_mgr, + &codec_factory.base); + return PJ_SUCCESS; + } } /* Mode not found in modes table, this may be a request to enable @@ -411,28 +410,28 @@ PJ_DEF(pj_status_t) pjmedia_codec_g7221_set_mode(unsigned sample_rate, * can disable it. */ if (!enabled) - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; /* Initialize a non-standard mode, look for available space. */ for (i = codec_factory.mode_rsv_start; - i < codec_factory.mode_count; ++i) + i < codec_factory.mode_count; ++i) { - if (!codec_factory.modes[i].enabled) - { - codec_mode *mode = &codec_factory.modes[i]; - mode->enabled = PJ_TRUE; - mode->sample_rate = sample_rate; - mode->bitrate = bitrate; - pj_utoa(mode->bitrate, mode->bitrate_str); - - /* Re-register G722.1 codec factory to update codec list */ - pjmedia_codec_mgr_unregister_factory(codec_mgr, - &codec_factory.base); - pjmedia_codec_mgr_register_factory(codec_mgr, - &codec_factory.base); - - return PJ_SUCCESS; - } + if (!codec_factory.modes[i].enabled) + { + codec_mode *mode = &codec_factory.modes[i]; + mode->enabled = PJ_TRUE; + mode->sample_rate = sample_rate; + mode->bitrate = bitrate; + pj_utoa(mode->bitrate, mode->bitrate_str); + + /* Re-register G722.1 codec factory to update codec list */ + pjmedia_codec_mgr_unregister_factory(codec_mgr, + &codec_factory.base); + pjmedia_codec_mgr_register_factory(codec_mgr, + &codec_factory.base); + + return PJ_SUCCESS; + } } /* No space for non-standard mode. */ @@ -458,8 +457,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_g7221_deinit(void) pj_status_t status; if (codec_factory.pool == NULL) { - /* Already deinitialized */ - return PJ_SUCCESS; + /* Already deinitialized */ + return PJ_SUCCESS; } pj_mutex_lock(codec_factory.mutex); @@ -467,15 +466,15 @@ PJ_DEF(pj_status_t) pjmedia_codec_g7221_deinit(void) /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(codec_factory.endpt); if (!codec_mgr) { - pj_pool_release(codec_factory.pool); - codec_factory.pool = NULL; - pj_mutex_unlock(codec_factory.mutex); - return PJ_EINVALIDOP; + pj_pool_release(codec_factory.pool); + codec_factory.pool = NULL; + pj_mutex_unlock(codec_factory.mutex); + return PJ_EINVALIDOP; } /* Unregister G722.1 codec factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &codec_factory.base); + &codec_factory.base); /* Destroy mutex. */ pj_mutex_unlock(codec_factory.mutex); @@ -493,23 +492,23 @@ PJ_DEF(pj_status_t) pjmedia_codec_g7221_deinit(void) * Check if factory can allocate the specified codec. */ static pj_status_t test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *info ) + const pjmedia_codec_info *info ) { PJ_UNUSED_ARG(factory); /* Type MUST be audio. */ if (info->type != PJMEDIA_TYPE_AUDIO) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check encoding name. */ if (pj_stricmp2(&info->encoding_name, CODEC_TAG) != 0) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check clock-rate */ if (info->clock_rate != WB_SAMPLE_RATE && - info->clock_rate != UWB_SAMPLE_RATE) + info->clock_rate != UWB_SAMPLE_RATE) { - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; } return PJ_SUCCESS; @@ -519,8 +518,8 @@ static pj_status_t test_alloc( pjmedia_codec_factory *factory, * Generate default attribute. */ static pj_status_t default_attr ( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ) { codec_mode *mode; @@ -530,7 +529,7 @@ static pj_status_t default_attr ( pjmedia_codec_factory *factory, mode = lookup_mode(id->pt); if (mode == NULL || !mode->enabled) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; attr->info.pt = (pj_uint8_t)id->pt; attr->info.channel_cnt = 1; @@ -557,8 +556,8 @@ static pj_status_t default_attr ( pjmedia_codec_factory *factory, * Enum codecs supported by this factory. */ static pj_status_t enum_codecs( pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]) + unsigned *count, + pjmedia_codec_info codecs[]) { unsigned i, max_cnt; @@ -570,17 +569,17 @@ static pj_status_t enum_codecs( pjmedia_codec_factory *factory, for (i=0; (i < codec_factory.mode_count) && (*count < max_cnt); ++i) { - if (!codec_factory.modes[i].enabled) - continue; + if (!codec_factory.modes[i].enabled) + continue; - pj_bzero(&codecs[*count], sizeof(pjmedia_codec_info)); - codecs[*count].encoding_name = pj_str((char*)CODEC_TAG); - codecs[*count].pt = codec_factory.modes[i].pt; - codecs[*count].type = PJMEDIA_TYPE_AUDIO; - codecs[*count].clock_rate = codec_factory.modes[i].sample_rate; - codecs[*count].channel_cnt = 1; + pj_bzero(&codecs[*count], sizeof(pjmedia_codec_info)); + codecs[*count].encoding_name = pj_str((char*)CODEC_TAG); + codecs[*count].pt = codec_factory.modes[i].pt; + codecs[*count].type = PJMEDIA_TYPE_AUDIO; + codecs[*count].clock_rate = codec_factory.modes[i].sample_rate; + codecs[*count].channel_cnt = 1; - ++ *count; + ++ *count; } return PJ_SUCCESS; @@ -590,8 +589,8 @@ static pj_status_t enum_codecs( pjmedia_codec_factory *factory, * Allocate a new codec instance. */ static pj_status_t alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { codec_private_t *codec_data; pjmedia_codec *codec; @@ -614,11 +613,11 @@ static pj_status_t alloc_codec( pjmedia_codec_factory *factory, /* Create silence detector */ status = pjmedia_silence_det_create(pool, id->clock_rate, - id->clock_rate * 20 / 1000, - &codec_data->vad); + id->clock_rate * 20 / 1000, + &codec_data->vad); if (status != PJ_SUCCESS) { - pj_mutex_unlock(codec_factory.mutex); - return status; + pj_mutex_unlock(codec_factory.mutex); + return status; } pj_mutex_unlock(codec_factory.mutex); @@ -631,7 +630,7 @@ static pj_status_t alloc_codec( pjmedia_codec_factory *factory, * Free codec. */ static pj_status_t dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { codec_private_t *codec_data; pj_pool_t *pool; @@ -654,7 +653,7 @@ static pj_status_t dealloc_codec( pjmedia_codec_factory *factory, * Init codec. */ static pj_status_t codec_init( pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(pool); @@ -665,7 +664,7 @@ static pj_status_t codec_init( pjmedia_codec *codec, * Open codec. */ static pj_status_t codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { codec_private_t *codec_data = (codec_private_t*) codec->codec_data; pj_pool_t *pool; @@ -674,16 +673,16 @@ static pj_status_t codec_open( pjmedia_codec *codec, unsigned tmp; for (tmp = 0; tmp < fmtp->cnt && !fmtp_bitrate; ++tmp) { - if (!pj_strcmp2(&fmtp->param[tmp].name, "bitrate")) - fmtp_bitrate = (pj_uint16_t)pj_strtoul(&fmtp->param[tmp].val); + if (!pj_strcmp2(&fmtp->param[tmp].name, "bitrate")) + fmtp_bitrate = (pj_uint16_t)pj_strtoul(&fmtp->param[tmp].val); } if (fmtp_bitrate == 0) - fmtp_bitrate = (pj_uint16_t)attr->info.avg_bps; + fmtp_bitrate = (pj_uint16_t)attr->info.avg_bps; /* Validate bitrate */ if (!fmtp_bitrate || !validate_mode(attr->info.clock_rate, fmtp_bitrate)) - return PJMEDIA_CODEC_EINMODE; + return PJMEDIA_CODEC_EINMODE; pool = codec_data->pool; @@ -695,10 +694,10 @@ static pj_status_t codec_open( pjmedia_codec *codec, codec_data->frame_size_bits = fmtp_bitrate*20/1000; codec_data->frame_size = (pj_uint16_t)(codec_data->frame_size_bits>>3); codec_data->samples_per_frame = (pj_uint16_t) - (attr->info.clock_rate*20/1000); + (attr->info.clock_rate*20/1000); codec_data->number_of_regions = (pj_uint16_t) - (attr->info.clock_rate <= WB_SAMPLE_RATE? - NUMBER_OF_REGIONS:MAX_NUMBER_OF_REGIONS); + (attr->info.clock_rate <= WB_SAMPLE_RATE? + NUMBER_OF_REGIONS:MAX_NUMBER_OF_REGIONS); codec_data->pcm_shift_val = 1 << (pj_int16_t)codec_factory.pcm_shift; /* Initialize encoder state */ @@ -739,7 +738,7 @@ static pj_status_t codec_close( pjmedia_codec *codec ) * Modify codec settings. */ static pj_status_t codec_modify( pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { codec_private_t *codec_data = (codec_private_t*) codec->codec_data; @@ -753,11 +752,11 @@ static pj_status_t codec_modify( pjmedia_codec *codec, * Get frames in the packet. */ static pj_status_t codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { codec_private_t *codec_data = (codec_private_t*) codec->codec_data; unsigned count = 0; @@ -766,16 +765,16 @@ static pj_status_t codec_parse( pjmedia_codec *codec, /* Parse based on fixed frame size. */ while (pkt_size >= codec_data->frame_size && count < *frame_cnt) { - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = pkt; - frames[count].size = codec_data->frame_size; - frames[count].timestamp.u64 = ts->u64 + - count * codec_data->samples_per_frame; + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = pkt; + frames[count].size = codec_data->frame_size; + frames[count].timestamp.u64 = ts->u64 + + count * codec_data->samples_per_frame; - pkt = (pj_uint8_t*)pkt + codec_data->frame_size; - pkt_size -= codec_data->frame_size; + pkt = (pj_uint8_t*)pkt + codec_data->frame_size; + pkt_size -= codec_data->frame_size; - ++count; + ++count; } pj_assert(pkt_size == 0); @@ -788,9 +787,9 @@ static pj_status_t codec_parse( pjmedia_codec *codec, * Encode frames. */ static pj_status_t codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { codec_private_t *codec_data = (codec_private_t*) codec->codec_data; unsigned nsamples, processed; @@ -798,83 +797,83 @@ static pj_status_t codec_encode( pjmedia_codec *codec, /* Check frame in & out size */ nsamples = input->size >> 1; PJ_ASSERT_RETURN(nsamples % codec_data->samples_per_frame == 0, - PJMEDIA_CODEC_EPCMFRMINLEN); + PJMEDIA_CODEC_EPCMFRMINLEN); PJ_ASSERT_RETURN(output_buf_len >= codec_data->frame_size * nsamples / - codec_data->samples_per_frame, - PJMEDIA_CODEC_EFRMTOOSHORT); + codec_data->samples_per_frame, + PJMEDIA_CODEC_EFRMTOOSHORT); /* Apply silence detection if VAD is enabled */ if (codec_data->vad_enabled) { - pj_bool_t is_silence; - pj_int32_t silence_duration; - - pj_assert(codec_data->vad); - - silence_duration = pj_timestamp_diff32(&codec_data->last_tx, - &input->timestamp); - - is_silence = pjmedia_silence_det_detect(codec_data->vad, - (const pj_int16_t*) input->buf, - (input->size >> 1), - NULL); - if (is_silence && - (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || - silence_duration < (PJMEDIA_CODEC_MAX_SILENCE_PERIOD * - (int)codec_data->samples_per_frame / 20))) - { - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->buf = NULL; - output->size = 0; - output->timestamp = input->timestamp; - return PJ_SUCCESS; - } else { - codec_data->last_tx = input->timestamp; - } + pj_bool_t is_silence; + pj_int32_t silence_duration; + + pj_assert(codec_data->vad); + + silence_duration = pj_timestamp_diff32(&codec_data->last_tx, + &input->timestamp); + + is_silence = pjmedia_silence_det_detect(codec_data->vad, + (const pj_int16_t*) input->buf, + (input->size >> 1), + NULL); + if (is_silence && + (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || + silence_duration < (PJMEDIA_CODEC_MAX_SILENCE_PERIOD * + (int)codec_data->samples_per_frame / 20))) + { + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->buf = NULL; + output->size = 0; + output->timestamp = input->timestamp; + return PJ_SUCCESS; + } else { + codec_data->last_tx = input->timestamp; + } } processed = 0; output->size = 0; while (processed < nsamples) { - Word16 mlt_coefs[MAX_SAMPLES_PER_FRAME]; - Word16 mag_shift; - const Word16 *pcm_input; - pj_int8_t *out_bits; - - pcm_input = (const Word16*)input->buf + processed; - out_bits = (pj_int8_t*)output->buf + output->size; - - /* Encoder adjust the input signal level */ - if (codec_data->pcm_shift_val > 1) { - unsigned i; - for (i=0; isamples_per_frame; ++i) { - codec_data->enc_frame[i] = - (Word16)(pcm_input[i] / codec_data->pcm_shift_val); - } - pcm_input = codec_data->enc_frame; - } - - /* Convert input samples to rmlt coefs */ - mag_shift = samples_to_rmlt_coefs(pcm_input, - codec_data->enc_old_frame, - mlt_coefs, - codec_data->samples_per_frame); - - /* Encode the mlt coefs. Note that encoder output stream is - * 16 bit array, so we need to take care about endianness. - */ - encoder(codec_data->frame_size_bits, - codec_data->number_of_regions, - mlt_coefs, - mag_shift, - (Word16*)out_bits); - - /* Encoder output are in native host byte order, while ITU says - * it must be in network byte order (MSB first). - */ - swap_bytes((pj_uint16_t*)out_bits, codec_data->frame_size/2); - - processed += codec_data->samples_per_frame; - output->size += codec_data->frame_size; + Word16 mlt_coefs[MAX_SAMPLES_PER_FRAME]; + Word16 mag_shift; + const Word16 *pcm_input; + pj_int8_t *out_bits; + + pcm_input = (const Word16*)input->buf + processed; + out_bits = (pj_int8_t*)output->buf + output->size; + + /* Encoder adjust the input signal level */ + if (codec_data->pcm_shift_val > 1) { + unsigned i; + for (i=0; isamples_per_frame; ++i) { + codec_data->enc_frame[i] = + (Word16)(pcm_input[i] / codec_data->pcm_shift_val); + } + pcm_input = codec_data->enc_frame; + } + + /* Convert input samples to rmlt coefs */ + mag_shift = samples_to_rmlt_coefs(pcm_input, + codec_data->enc_old_frame, + mlt_coefs, + codec_data->samples_per_frame); + + /* Encode the mlt coefs. Note that encoder output stream is + * 16 bit array, so we need to take care about endianness. + */ + encoder(codec_data->frame_size_bits, + codec_data->number_of_regions, + mlt_coefs, + mag_shift, + (Word16*)out_bits); + + /* Encoder output are in native host byte order, while ITU says + * it must be in network byte order (MSB first). + */ + swap_bytes((pj_uint16_t*)out_bits, codec_data->frame_size/2); + + processed += codec_data->samples_per_frame; + output->size += codec_data->frame_size; } output->type = PJMEDIA_FRAME_TYPE_AUDIO; @@ -887,9 +886,9 @@ static pj_status_t codec_encode( pjmedia_codec *codec, * Decode frame. */ static pj_status_t codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { codec_private_t *codec_data = (codec_private_t*) codec->codec_data; Word16 mlt_coefs[MAX_SAMPLES_PER_FRAME]; @@ -899,57 +898,57 @@ static pj_status_t codec_decode( pjmedia_codec *codec, /* Check frame out length size */ PJ_ASSERT_RETURN(output_buf_len >= - (unsigned)(codec_data->samples_per_frame<<1), - PJMEDIA_CODEC_EPCMTOOSHORT); + (unsigned)(codec_data->samples_per_frame<<1), + PJMEDIA_CODEC_EPCMTOOSHORT); /* If input is NULL, perform PLC by settting frame_error_flag to 1 */ if (input) { - /* Check frame in length size */ - PJ_ASSERT_RETURN((pj_uint16_t)input->size == codec_data->frame_size, - PJMEDIA_CODEC_EFRMINLEN); - - /* Decoder requires input of 16-bits array in native host byte - * order, while the frame received from the network are in - * network byte order (MSB first). - */ - swap_bytes((pj_uint16_t*)input->buf, codec_data->frame_size/2); - - bitobj.code_word_ptr = (Word16*)input->buf; - bitobj.current_word = *bitobj.code_word_ptr; - bitobj.code_bit_count = 0; - bitobj.number_of_bits_left = codec_data->frame_size_bits; - - output->timestamp = input->timestamp; + /* Check frame in length size */ + PJ_ASSERT_RETURN((pj_uint16_t)input->size == codec_data->frame_size, + PJMEDIA_CODEC_EFRMINLEN); + + /* Decoder requires input of 16-bits array in native host byte + * order, while the frame received from the network are in + * network byte order (MSB first). + */ + swap_bytes((pj_uint16_t*)input->buf, codec_data->frame_size/2); + + bitobj.code_word_ptr = (Word16*)input->buf; + bitobj.current_word = *bitobj.code_word_ptr; + bitobj.code_bit_count = 0; + bitobj.number_of_bits_left = codec_data->frame_size_bits; + + output->timestamp = input->timestamp; } else { - pj_bzero(&bitobj, sizeof(bitobj)); - frame_error_flag = 1; + pj_bzero(&bitobj, sizeof(bitobj)); + frame_error_flag = 1; } /* Process the input frame to get mlt coefs */ decoder(&bitobj, - &codec_data->dec_randobj, + &codec_data->dec_randobj, codec_data->number_of_regions, - mlt_coefs, + mlt_coefs, &mag_shift, - &codec_data->dec_old_mag_shift, + &codec_data->dec_old_mag_shift, codec_data->dec_old_mlt_coefs, frame_error_flag); /* Convert the mlt_coefs to PCM samples */ rmlt_coefs_to_samples(mlt_coefs, - codec_data->dec_old_frame, - (Word16*)output->buf, - codec_data->samples_per_frame, - mag_shift); + codec_data->dec_old_frame, + (Word16*)output->buf, + codec_data->samples_per_frame, + mag_shift); /* Decoder adjust PCM signal */ if (codec_data->pcm_shift_val > 1) { - unsigned i; - pj_int16_t *buf = (Word16*)output->buf; + unsigned i; + pj_int16_t *buf = (Word16*)output->buf; - for (i=0; isamples_per_frame; ++i) { - buf[i] = buf[i] * codec_data->pcm_shift_val; - } + for (i=0; isamples_per_frame; ++i) { + buf[i] = buf[i] * codec_data->pcm_shift_val; + } } output->type = PJMEDIA_FRAME_TYPE_AUDIO; @@ -962,23 +961,23 @@ static pj_status_t codec_decode( pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t codec_recover( pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { codec_private_t *codec_data = (codec_private_t*) codec->codec_data; /* Use native PLC when PLC is enabled. */ if (codec_data->plc_enabled) - return codec_decode(codec, NULL, output_buf_len, output); + return codec_decode(codec, NULL, output_buf_len, output); /* Otherwise just return zero-fill frame. */ output->type = PJMEDIA_FRAME_TYPE_AUDIO; output->size = codec_data->samples_per_frame << 1; pjmedia_zero_samples((pj_int16_t*)output->buf, - codec_data->samples_per_frame); + codec_data->samples_per_frame); return PJ_SUCCESS; } -#endif /* PJMEDIA_HAS_G7221_CODEC */ +#endif /* PJMEDIA_HAS_G7221_CODEC */ diff --git a/pjmedia/src/pjmedia-codec/g7221_sdp_match.c b/pjmedia/src/pjmedia-codec/g7221_sdp_match.c index a9cc17dcbf..f0cf792e07 100644 --- a/pjmedia/src/pjmedia-codec/g7221_sdp_match.c +++ b/pjmedia/src/pjmedia-codec/g7221_sdp_match.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,29 +24,29 @@ #define GET_FMTP_IVAL_BASE(ival, base, fmtp, param, default_val) \ do { \ - pj_str_t s; \ - char *p; \ - p = pj_stristr(&fmtp.fmt_param, ¶m); \ - if (!p) { \ - ival = default_val; \ - break; \ - } \ - pj_strset(&s, p + param.slen, fmtp.fmt_param.slen - \ - (p - fmtp.fmt_param.ptr) - param.slen); \ - ival = pj_strtoul2(&s, NULL, base); \ + pj_str_t s; \ + char *p; \ + p = pj_stristr(&fmtp.fmt_param, ¶m); \ + if (!p) { \ + ival = default_val; \ + break; \ + } \ + pj_strset(&s, p + param.slen, fmtp.fmt_param.slen - \ + (p - fmtp.fmt_param.ptr) - param.slen); \ + ival = pj_strtoul2(&s, NULL, base); \ } while (0) #define GET_FMTP_IVAL(ival, fmtp, param, default_val) \ - GET_FMTP_IVAL_BASE(ival, 10, fmtp, param, default_val) + GET_FMTP_IVAL_BASE(ival, 10, fmtp, param, default_val) PJ_DEF(pj_status_t) pjmedia_codec_g7221_match_sdp(pj_pool_t *pool, - pjmedia_sdp_media *offer, - unsigned o_fmt_idx, - pjmedia_sdp_media *answer, - unsigned a_fmt_idx, - unsigned option) + pjmedia_sdp_media *offer, + unsigned o_fmt_idx, + pjmedia_sdp_media *answer, + unsigned a_fmt_idx, + unsigned option) { const pjmedia_sdp_attr *attr_ans; const pjmedia_sdp_attr *attr_ofr; @@ -61,31 +60,31 @@ PJ_DEF(pj_status_t) pjmedia_codec_g7221_match_sdp(pj_pool_t *pool, /* Parse offer */ attr_ofr = pjmedia_sdp_media_find_attr2(offer, "fmtp", - &offer->desc.fmt[o_fmt_idx]); + &offer->desc.fmt[o_fmt_idx]); if (!attr_ofr) - return PJMEDIA_SDP_EINFMTP; + return PJMEDIA_SDP_EINFMTP; status = pjmedia_sdp_attr_get_fmtp(attr_ofr, &fmtp); if (status != PJ_SUCCESS) - return status; + return status; GET_FMTP_IVAL(o_bitrate, fmtp, bitrate, 0); /* Parse answer */ attr_ans = pjmedia_sdp_media_find_attr2(answer, "fmtp", - &answer->desc.fmt[a_fmt_idx]); + &answer->desc.fmt[a_fmt_idx]); if (!attr_ans) - return PJMEDIA_SDP_EINFMTP; + return PJMEDIA_SDP_EINFMTP; status = pjmedia_sdp_attr_get_fmtp(attr_ans, &fmtp); if (status != PJ_SUCCESS) - return status; + return status; GET_FMTP_IVAL(a_bitrate, fmtp, bitrate, 0); /* Compare bitrate in answer and offer. */ if (a_bitrate != o_bitrate) - return PJMEDIA_SDP_EFORMATNOTEQUAL; + return PJMEDIA_SDP_EFORMATNOTEQUAL; return PJ_SUCCESS; } diff --git a/pjmedia/src/pjmedia-codec/gsm.c b/pjmedia/src/pjmedia-codec/gsm.c index 86c3d57c65..8685d11121 100644 --- a/pjmedia/src/pjmedia-codec/gsm.c +++ b/pjmedia/src/pjmedia-codec/gsm.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -47,50 +46,50 @@ #endif /* We removed PLC in 0.6 (and re-enabled it again in 0.9!) */ -#define PLC_DISABLED 0 +#define PLC_DISABLED 0 /* Prototypes for GSM factory */ static pj_status_t gsm_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ); + const pjmedia_codec_info *id ); static pj_status_t gsm_default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ); static pj_status_t gsm_enum_codecs( pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t gsm_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t gsm_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for GSM implementation. */ static pj_status_t gsm_codec_init( pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t gsm_codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t gsm_codec_close( pjmedia_codec *codec ); static pj_status_t gsm_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t gsm_codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t gsm_codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t gsm_codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); #if !PLC_DISABLED static pj_status_t gsm_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); #endif /* Definition for GSM codec operations. */ @@ -125,25 +124,25 @@ static pjmedia_codec_factory_op gsm_factory_op = static struct gsm_codec_factory { pjmedia_codec_factory base; - pjmedia_endpt *endpt; - pj_pool_t *pool; - pj_mutex_t *mutex; - pjmedia_codec codec_list; + pjmedia_endpt *endpt; + pj_pool_t *pool; + pj_mutex_t *mutex; + pjmedia_codec codec_list; } gsm_codec_factory; /* GSM codec private data. */ struct gsm_data { - struct gsm_state *encoder; - struct gsm_state *decoder; - pj_bool_t plc_enabled; + struct gsm_state *encoder; + struct gsm_state *decoder; + pj_bool_t plc_enabled; #if !PLC_DISABLED - pjmedia_plc *plc; + pjmedia_plc *plc; #endif - pj_bool_t vad_enabled; - pjmedia_silence_det *vad; - pj_timestamp last_tx; + pj_bool_t vad_enabled; + pjmedia_silence_det *vad; + pj_timestamp last_tx; }; @@ -157,7 +156,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_gsm_init( pjmedia_endpt *endpt ) pj_status_t status; if (gsm_codec_factory.pool != NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Create GSM codec factory. */ gsm_codec_factory.base.op = &gsm_factory_op; @@ -165,30 +164,30 @@ PJ_DEF(pj_status_t) pjmedia_codec_gsm_init( pjmedia_endpt *endpt ) gsm_codec_factory.endpt = endpt; gsm_codec_factory.pool = pjmedia_endpt_create_pool(endpt, "gsm", 4000, - 4000); + 4000); if (!gsm_codec_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; pj_list_init(&gsm_codec_factory.codec_list); /* Create mutex. */ status = pj_mutex_create_simple(gsm_codec_factory.pool, "gsm", - &gsm_codec_factory.mutex); + &gsm_codec_factory.mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - status = PJ_EINVALIDOP; - goto on_error; + status = PJ_EINVALIDOP; + goto on_error; } /* Register codec factory to endpoint. */ status = pjmedia_codec_mgr_register_factory(codec_mgr, - &gsm_codec_factory.base); + &gsm_codec_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Done. */ return PJ_SUCCESS; @@ -211,7 +210,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_gsm_deinit(void) pj_status_t status; if (gsm_codec_factory.pool == NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* We don't want to deinit if there's outstanding codec. */ /* This is silly, as we'll always have codec in the list if @@ -219,22 +218,22 @@ PJ_DEF(pj_status_t) pjmedia_codec_gsm_deinit(void) deallocate all codecs in the list. pj_mutex_lock(gsm_codec_factory.mutex); if (!pj_list_empty(&gsm_codec_factory.codec_list)) { - pj_mutex_unlock(gsm_codec_factory.mutex); - return PJ_EBUSY; + pj_mutex_unlock(gsm_codec_factory.mutex); + return PJ_EBUSY; } */ /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(gsm_codec_factory.endpt); if (!codec_mgr) { - pj_pool_release(gsm_codec_factory.pool); - gsm_codec_factory.pool = NULL; - return PJ_EINVALIDOP; + pj_pool_release(gsm_codec_factory.pool); + gsm_codec_factory.pool = NULL; + return PJ_EINVALIDOP; } /* Unregister GSM codec factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &gsm_codec_factory.base); + &gsm_codec_factory.base); /* Destroy mutex. */ pj_mutex_destroy(gsm_codec_factory.mutex); @@ -250,13 +249,13 @@ PJ_DEF(pj_status_t) pjmedia_codec_gsm_deinit(void) * Check if factory can allocate the specified codec. */ static pj_status_t gsm_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *info ) + const pjmedia_codec_info *info ) { PJ_UNUSED_ARG(factory); /* Check payload type. */ if (info->pt != PJMEDIA_RTP_PT_GSM) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Ignore the rest, since it's static payload type. */ @@ -267,8 +266,8 @@ static pj_status_t gsm_test_alloc( pjmedia_codec_factory *factory, * Generate default attribute. */ static pj_status_t gsm_default_attr (pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ) { PJ_UNUSED_ARG(factory); PJ_UNUSED_ARG(id); @@ -297,8 +296,8 @@ static pj_status_t gsm_default_attr (pjmedia_codec_factory *factory, * Enum codecs supported by this factory (i.e. only GSM!). */ static pj_status_t gsm_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]) + unsigned *count, + pjmedia_codec_info codecs[]) { PJ_UNUSED_ARG(factory); PJ_ASSERT_RETURN(codecs && *count > 0, PJ_EINVAL); @@ -319,8 +318,8 @@ static pj_status_t gsm_enum_codecs(pjmedia_codec_factory *factory, * Allocate a new GSM codec instance. */ static pj_status_t gsm_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { pjmedia_codec *codec; struct gsm_data *gsm_data; @@ -334,35 +333,35 @@ static pj_status_t gsm_alloc_codec( pjmedia_codec_factory *factory, /* Get free nodes, if any. */ if (!pj_list_empty(&gsm_codec_factory.codec_list)) { - codec = gsm_codec_factory.codec_list.next; - pj_list_erase(codec); + codec = gsm_codec_factory.codec_list.next; + pj_list_erase(codec); } else { - codec = PJ_POOL_ZALLOC_T(gsm_codec_factory.pool, pjmedia_codec); - PJ_ASSERT_RETURN(codec != NULL, PJ_ENOMEM); - codec->op = &gsm_op; - codec->factory = factory; + codec = PJ_POOL_ZALLOC_T(gsm_codec_factory.pool, pjmedia_codec); + PJ_ASSERT_RETURN(codec != NULL, PJ_ENOMEM); + codec->op = &gsm_op; + codec->factory = factory; - gsm_data = PJ_POOL_ZALLOC_T(gsm_codec_factory.pool, struct gsm_data); - codec->codec_data = gsm_data; + gsm_data = PJ_POOL_ZALLOC_T(gsm_codec_factory.pool, struct gsm_data); + codec->codec_data = gsm_data; #if !PLC_DISABLED - /* Create PLC */ - status = pjmedia_plc_create(gsm_codec_factory.pool, 8000, - 160, 0, &gsm_data->plc); - if (status != PJ_SUCCESS) { - pj_mutex_unlock(gsm_codec_factory.mutex); - return status; - } + /* Create PLC */ + status = pjmedia_plc_create(gsm_codec_factory.pool, 8000, + 160, 0, &gsm_data->plc); + if (status != PJ_SUCCESS) { + pj_mutex_unlock(gsm_codec_factory.mutex); + return status; + } #endif - /* Create silence detector */ - status = pjmedia_silence_det_create(gsm_codec_factory.pool, - 8000, 160, - &gsm_data->vad); - if (status != PJ_SUCCESS) { - pj_mutex_unlock(gsm_codec_factory.mutex); - return status; - } + /* Create silence detector */ + status = pjmedia_silence_det_create(gsm_codec_factory.pool, + 8000, 160, + &gsm_data->vad); + if (status != PJ_SUCCESS) { + pj_mutex_unlock(gsm_codec_factory.mutex); + return status; + } } pj_mutex_unlock(gsm_codec_factory.mutex); @@ -375,7 +374,7 @@ static pj_status_t gsm_alloc_codec( pjmedia_codec_factory *factory, * Free codec. */ static pj_status_t gsm_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { struct gsm_data *gsm_data; int i; @@ -393,9 +392,9 @@ static pj_status_t gsm_dealloc_codec( pjmedia_codec_factory *factory, * next time. */ for (i=0; i<2; ++i) { - pj_int16_t frame[160]; - pjmedia_zero_samples(frame, PJ_ARRAY_SIZE(frame)); - pjmedia_plc_save(gsm_data->plc, frame); + pj_int16_t frame[160]; + pjmedia_zero_samples(frame, PJ_ARRAY_SIZE(frame)); + pjmedia_plc_save(gsm_data->plc, frame); } #else PJ_UNUSED_ARG(i); @@ -416,7 +415,7 @@ static pj_status_t gsm_dealloc_codec( pjmedia_codec_factory *factory, * Init codec. */ static pj_status_t gsm_codec_init( pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(pool); @@ -427,7 +426,7 @@ static pj_status_t gsm_codec_init( pjmedia_codec *codec, * Open codec. */ static pj_status_t gsm_codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { struct gsm_data *gsm_data = (struct gsm_data*) codec->codec_data; @@ -436,11 +435,11 @@ static pj_status_t gsm_codec_open( pjmedia_codec *codec, gsm_data->encoder = gsm_create(); if (!gsm_data->encoder) - return PJMEDIA_CODEC_EFAILED; + return PJMEDIA_CODEC_EFAILED; gsm_data->decoder = gsm_create(); if (!gsm_data->decoder) - return PJMEDIA_CODEC_EFAILED; + return PJMEDIA_CODEC_EFAILED; gsm_data->vad_enabled = (attr->setting.vad != 0); gsm_data->plc_enabled = (attr->setting.plc != 0); @@ -458,12 +457,12 @@ static pj_status_t gsm_codec_close( pjmedia_codec *codec ) pj_assert(gsm_data != NULL); if (gsm_data->encoder) { - gsm_destroy(gsm_data->encoder); - gsm_data->encoder = NULL; + gsm_destroy(gsm_data->encoder); + gsm_data->encoder = NULL; } if (gsm_data->decoder) { - gsm_destroy(gsm_data->decoder); - gsm_data->decoder = NULL; + gsm_destroy(gsm_data->decoder); + gsm_data->decoder = NULL; } return PJ_SUCCESS; @@ -474,7 +473,7 @@ static pj_status_t gsm_codec_close( pjmedia_codec *codec ) * Modify codec settings. */ static pj_status_t gsm_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { struct gsm_data *gsm_data = (struct gsm_data*) codec->codec_data; @@ -492,11 +491,11 @@ static pj_status_t gsm_codec_modify(pjmedia_codec *codec, * Get frames in the packet. */ static pj_status_t gsm_codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { unsigned count = 0; @@ -505,15 +504,15 @@ static pj_status_t gsm_codec_parse( pjmedia_codec *codec, PJ_ASSERT_RETURN(frame_cnt, PJ_EINVAL); while (pkt_size >= 33 && count < *frame_cnt) { - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = pkt; - frames[count].size = 33; - frames[count].timestamp.u64 = ts->u64 + count * 160; + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = pkt; + frames[count].size = 33; + frames[count].timestamp.u64 = ts->u64 + count * 160; - pkt = ((char*)pkt) + 33; - pkt_size -= 33; + pkt = ((char*)pkt) + 33; + pkt_size -= 33; - ++count; + ++count; } *frame_cnt = count; @@ -524,9 +523,9 @@ static pj_status_t gsm_codec_parse( pjmedia_codec *codec, * Encode frame. */ static pj_status_t gsm_codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct gsm_data *gsm_data = (struct gsm_data*) codec->codec_data; pj_int16_t *pcm_in; @@ -539,42 +538,42 @@ static pj_status_t gsm_codec_encode( pjmedia_codec *codec, PJ_ASSERT_RETURN(in_size % 320 == 0, PJMEDIA_CODEC_EPCMFRMINLEN); PJ_ASSERT_RETURN(output_buf_len >= 33 * in_size/320, - PJMEDIA_CODEC_EFRMTOOSHORT); + PJMEDIA_CODEC_EFRMTOOSHORT); /* Detect silence */ if (gsm_data->vad_enabled) { - pj_bool_t is_silence; - pj_int32_t silence_duration; - - silence_duration = pj_timestamp_diff32(&gsm_data->last_tx, - &input->timestamp); - - is_silence = pjmedia_silence_det_detect(gsm_data->vad, - (const pj_int16_t*) input->buf, - (input->size >> 1), - NULL); - if (is_silence && - (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || - silence_duration < PJMEDIA_CODEC_MAX_SILENCE_PERIOD*8000/1000)) - { - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->buf = NULL; - output->size = 0; - output->timestamp = input->timestamp; - return PJ_SUCCESS; - } else { - gsm_data->last_tx = input->timestamp; - } + pj_bool_t is_silence; + pj_int32_t silence_duration; + + silence_duration = pj_timestamp_diff32(&gsm_data->last_tx, + &input->timestamp); + + is_silence = pjmedia_silence_det_detect(gsm_data->vad, + (const pj_int16_t*) input->buf, + (input->size >> 1), + NULL); + if (is_silence && + (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || + silence_duration < PJMEDIA_CODEC_MAX_SILENCE_PERIOD*8000/1000)) + { + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->buf = NULL; + output->size = 0; + output->timestamp = input->timestamp; + return PJ_SUCCESS; + } else { + gsm_data->last_tx = input->timestamp; + } } /* Encode */ output->size = 0; while (in_size >= 320) { - gsm_encode(gsm_data->encoder, pcm_in, - (unsigned char*)output->buf + output->size); - pcm_in += 160; - output->size += 33; - in_size -= 320; + gsm_encode(gsm_data->encoder, pcm_in, + (unsigned char*)output->buf + output->size); + pcm_in += 160; + output->size += 33; + in_size -= 320; } output->type = PJMEDIA_FRAME_TYPE_AUDIO; @@ -587,9 +586,9 @@ static pj_status_t gsm_codec_encode( pjmedia_codec *codec, * Decode frame. */ static pj_status_t gsm_codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct gsm_data *gsm_data = (struct gsm_data*) codec->codec_data; @@ -597,14 +596,14 @@ static pj_status_t gsm_codec_decode( pjmedia_codec *codec, PJ_ASSERT_RETURN(input && output, PJ_EINVAL); if (output_buf_len < 320) - return PJMEDIA_CODEC_EPCMTOOSHORT; + return PJMEDIA_CODEC_EPCMTOOSHORT; if (input->size < 33) - return PJMEDIA_CODEC_EFRMTOOSHORT; + return PJMEDIA_CODEC_EFRMTOOSHORT; gsm_decode(gsm_data->decoder, - (unsigned char*)input->buf, - (short*)output->buf); + (unsigned char*)input->buf, + (short*)output->buf); output->size = 320; output->type = PJMEDIA_FRAME_TYPE_AUDIO; @@ -612,7 +611,7 @@ static pj_status_t gsm_codec_decode( pjmedia_codec *codec, #if !PLC_DISABLED if (gsm_data->plc_enabled) - pjmedia_plc_save( gsm_data->plc, (pj_int16_t*)output->buf); + pjmedia_plc_save( gsm_data->plc, (pj_int16_t*)output->buf); #endif return PJ_SUCCESS; @@ -624,8 +623,8 @@ static pj_status_t gsm_codec_decode( pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t gsm_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { struct gsm_data *gsm_data = (struct gsm_data*) codec->codec_data; @@ -641,5 +640,5 @@ static pj_status_t gsm_codec_recover(pjmedia_codec *codec, #endif -#endif /* PJMEDIA_HAS_GSM_CODEC */ +#endif /* PJMEDIA_HAS_GSM_CODEC */ diff --git a/pjmedia/src/pjmedia-codec/h263_packetizer.c b/pjmedia/src/pjmedia-codec/h263_packetizer.c index 3bfafe18b6..07b7ccbd2b 100644 --- a/pjmedia/src/pjmedia-codec/h263_packetizer.c +++ b/pjmedia/src/pjmedia-codec/h263_packetizer.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -26,7 +25,7 @@ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -#define THIS_FILE "h263_packetizer.c" +#define THIS_FILE "h263_packetizer.c" /* H.263 packetizer definition */ @@ -35,8 +34,8 @@ struct pjmedia_h263_packetizer { pjmedia_h263_packetizer_cfg cfg; /* Unpacketizer state */ - unsigned unpack_last_sync_pos; - pj_bool_t unpack_prev_lost; + unsigned unpack_last_sync_pos; + pj_bool_t unpack_prev_lost; }; @@ -45,7 +44,7 @@ struct pjmedia_h263_packetizer { * bitstream. */ static pj_uint8_t* find_sync_point(pj_uint8_t *data, - pj_size_t data_len) + pj_size_t data_len) { pj_uint8_t *p = data, *end = data+data_len-1; @@ -82,23 +81,23 @@ static pj_uint8_t* find_sync_point_rev(pj_uint8_t *data, * Create H263 packetizer. */ PJ_DEF(pj_status_t) pjmedia_h263_packetizer_create( - pj_pool_t *pool, - const pjmedia_h263_packetizer_cfg *cfg, - pjmedia_h263_packetizer **p) + pj_pool_t *pool, + const pjmedia_h263_packetizer_cfg *cfg, + pjmedia_h263_packetizer **p) { pjmedia_h263_packetizer *p_; PJ_ASSERT_RETURN(pool && p, PJ_EINVAL); if (cfg && cfg->mode != PJMEDIA_H263_PACKETIZER_MODE_RFC4629) - return PJ_ENOTSUP; + return PJ_ENOTSUP; p_ = PJ_POOL_ZALLOC_T(pool, pjmedia_h263_packetizer); if (cfg) { - pj_memcpy(&p_->cfg, cfg, sizeof(*cfg)); + pj_memcpy(&p_->cfg, cfg, sizeof(*cfg)); } else { - p_->cfg.mode = PJMEDIA_H263_PACKETIZER_MODE_RFC4629; - p_->cfg.mtu = PJMEDIA_MAX_VID_PAYLOAD_SIZE; + p_->cfg.mode = PJMEDIA_H263_PACKETIZER_MODE_RFC4629; + p_->cfg.mtu = PJMEDIA_MAX_VID_PAYLOAD_SIZE; } *p = p_; @@ -111,7 +110,7 @@ PJ_DEF(pj_status_t) pjmedia_h263_packetizer_create( * Generate an RTP payload from H.263 frame bitstream, in-place processing. */ PJ_DEF(pj_status_t) pjmedia_h263_packetize(pjmedia_h263_packetizer *pktz, - pj_uint8_t *bits, + pj_uint8_t *bits, pj_size_t bits_len, unsigned *pos, const pj_uint8_t **payload, @@ -136,12 +135,12 @@ PJ_DEF(pj_status_t) pjmedia_h263_packetize(pjmedia_h263_packetizer *pktz, * preceeding the bitstream for payload header! */ - if (*pos < 2) { - /* Invalid H263 bitstream, it's not started with PSC */ - return PJ_EINVAL; - } + if (*pos < 2) { + /* Invalid H263 bitstream, it's not started with PSC */ + return PJ_EINVAL; + } - p -= 2; + p -= 2; *p = 0; } *(p+1) = 0; @@ -150,7 +149,7 @@ PJ_DEF(pj_status_t) pjmedia_h263_packetize(pjmedia_h263_packetizer *pktz, * limitation, try to use sync point for the payload boundary. */ if (end-p > pktz->cfg.mtu) { - end = find_sync_point_rev(p+2, pktz->cfg.mtu-2); + end = find_sync_point_rev(p+2, pktz->cfg.mtu-2); } *payload = p; @@ -165,11 +164,11 @@ PJ_DEF(pj_status_t) pjmedia_h263_packetize(pjmedia_h263_packetizer *pktz, * Append an RTP payload to a H.263 picture bitstream. */ PJ_DEF(pj_status_t) pjmedia_h263_unpacketize (pjmedia_h263_packetizer *pktz, - const pj_uint8_t *payload, + const pj_uint8_t *payload, pj_size_t payload_len, pj_uint8_t *bits, pj_size_t bits_size, - unsigned *pos) + unsigned *pos) { pj_uint8_t P, V, PLEN; const pj_uint8_t *p = payload; @@ -179,20 +178,20 @@ PJ_DEF(pj_status_t) pjmedia_h263_unpacketize (pjmedia_h263_packetizer *pktz, /* Check if this is a missing/lost packet */ if (payload == NULL) { - pktz->unpack_prev_lost = PJ_TRUE; - return PJ_SUCCESS; + pktz->unpack_prev_lost = PJ_TRUE; + return PJ_SUCCESS; } /* H263 payload header size is two octets */ if (payload_len < 2) { - /* Invalid bitstream, discard this payload */ - pktz->unpack_prev_lost = PJ_TRUE; - return PJ_EINVAL; + /* Invalid bitstream, discard this payload */ + pktz->unpack_prev_lost = PJ_TRUE; + return PJ_EINVAL; } /* Reset last sync point for every new picture bitstream */ if (*pos == 0) - pktz->unpack_last_sync_pos = 0; + pktz->unpack_last_sync_pos = 0; /* Get payload header info */ P = *p & 0x04; @@ -200,80 +199,80 @@ PJ_DEF(pj_status_t) pjmedia_h263_unpacketize (pjmedia_h263_packetizer *pktz, PLEN = ((*p & 0x01) << 5) + ((*(p+1) & 0xF8)>>3); /* Get start bitstream pointer */ - p += 2; /* Skip payload header */ + p += 2; /* Skip payload header */ if (V) - p += 1; /* Skip VRC data */ + p += 1; /* Skip VRC data */ if (PLEN) p += PLEN; /* Skip extra picture header data */ /* Get bitstream length */ if (payload_len > (pj_size_t)(p - payload)) { - payload_len -= (p - payload); + payload_len -= (p - payload); } else { - /* Invalid bitstream, discard this payload */ - pktz->unpack_prev_lost = PJ_TRUE; - return PJ_EINVAL; + /* Invalid bitstream, discard this payload */ + pktz->unpack_prev_lost = PJ_TRUE; + return PJ_EINVAL; } /* Validate bitstream length */ if (bits_size < *pos + payload_len + 2) { - /* Insufficient bistream buffer, discard this payload */ - pj_assert(!"Insufficient H.263 bitstream buffer"); - pktz->unpack_prev_lost = PJ_TRUE; - return PJ_ETOOSMALL; + /* Insufficient bistream buffer, discard this payload */ + pj_assert(!"Insufficient H.263 bitstream buffer"); + pktz->unpack_prev_lost = PJ_TRUE; + return PJ_ETOOSMALL; } /* Start writing bitstream */ /* No sync point flag */ if (!P) { - if (*pos == 0) { - /* Previous packet must be lost */ - pktz->unpack_prev_lost = PJ_TRUE; - - /* If there is extra picture header, let's use it. */ - if (PLEN) { - /* Write two zero octets for PSC */ - *q++ = 0; - *q++ = 0; - /* Copy the picture header */ - p -= PLEN; - pj_memcpy(q, p, PLEN); - p += PLEN; - q += PLEN; - } - } else if (pktz->unpack_prev_lost) { - /* If prev packet was lost, revert the bitstream pointer to - * the last sync point. - */ - pj_assert(pktz->unpack_last_sync_pos <= *pos); - q = bits + pktz->unpack_last_sync_pos; - } - - /* There was packet lost, see if this payload contain sync point - * (usable data). - */ - if (pktz->unpack_prev_lost) { - pj_uint8_t *sync; - sync = find_sync_point((pj_uint8_t*)p, payload_len); - if (sync) { - /* Got sync point, update P/sync-point flag */ - P = 1; - /* Skip the two zero octets */ - sync += 2; - /* Update payload length and start bitstream pointer */ - payload_len -= (sync - p); - p = sync; - } else { - /* No sync point in it, just discard this payload */ - return PJ_EIGNORED; - } - } + if (*pos == 0) { + /* Previous packet must be lost */ + pktz->unpack_prev_lost = PJ_TRUE; + + /* If there is extra picture header, let's use it. */ + if (PLEN) { + /* Write two zero octets for PSC */ + *q++ = 0; + *q++ = 0; + /* Copy the picture header */ + p -= PLEN; + pj_memcpy(q, p, PLEN); + p += PLEN; + q += PLEN; + } + } else if (pktz->unpack_prev_lost) { + /* If prev packet was lost, revert the bitstream pointer to + * the last sync point. + */ + pj_assert(pktz->unpack_last_sync_pos <= *pos); + q = bits + pktz->unpack_last_sync_pos; + } + + /* There was packet lost, see if this payload contain sync point + * (usable data). + */ + if (pktz->unpack_prev_lost) { + pj_uint8_t *sync; + sync = find_sync_point((pj_uint8_t*)p, payload_len); + if (sync) { + /* Got sync point, update P/sync-point flag */ + P = 1; + /* Skip the two zero octets */ + sync += 2; + /* Update payload length and start bitstream pointer */ + payload_len -= (sync - p); + p = sync; + } else { + /* No sync point in it, just discard this payload */ + return PJ_EIGNORED; + } + } } /* Write two zero octets when payload flagged with sync point */ if (P) { - pktz->unpack_last_sync_pos = (unsigned)(q - bits); + pktz->unpack_last_sync_pos = (unsigned)(q - bits); *q++ = 0; *q++ = 0; } diff --git a/pjmedia/src/pjmedia-codec/h264_packetizer.c b/pjmedia/src/pjmedia-codec/h264_packetizer.c index d03de6b6ad..83fb7a67d6 100644 --- a/pjmedia/src/pjmedia-codec/h264_packetizer.c +++ b/pjmedia/src/pjmedia-codec/h264_packetizer.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011 Teluu Inc. (http://www.teluu.com) * @@ -28,10 +27,10 @@ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -#define THIS_FILE "h264_packetizer.c" +#define THIS_FILE "h264_packetizer.c" -#define DBG_PACKETIZE 0 -#define DBG_UNPACKETIZE 0 +#define DBG_PACKETIZE 0 +#define DBG_UNPACKETIZE 0 /* H.264 packetizer definition */ @@ -41,18 +40,18 @@ struct pjmedia_h264_packetizer pjmedia_h264_packetizer_cfg cfg; /* Unpacketizer state */ - unsigned unpack_last_sync_pos; - pj_bool_t unpack_prev_lost; + unsigned unpack_last_sync_pos; + pj_bool_t unpack_prev_lost; }; /* Enumeration of H.264 NAL unit types */ enum { - NAL_TYPE_SINGLE_NAL_MIN = 1, - NAL_TYPE_SINGLE_NAL_MAX = 23, - NAL_TYPE_STAP_A = 24, - NAL_TYPE_FU_A = 28, + NAL_TYPE_SINGLE_NAL_MIN = 1, + NAL_TYPE_SINGLE_NAL_MAX = 23, + NAL_TYPE_STAP_A = 24, + NAL_TYPE_FU_A = 28, }; @@ -69,12 +68,12 @@ static pj_uint8_t* find_next_nal_unit(pj_uint8_t *start, ++p; if (p > end-3) - /* No more NAL unit in this bitstream */ + /* No more NAL unit in this bitstream */ return NULL; /* Include 8 bits leading zero */ if (p>start && *(p-1)==0) - return (p-1); + return (p-1); return p; } @@ -84,32 +83,32 @@ static pj_uint8_t* find_next_nal_unit(pj_uint8_t *start, * Create H264 packetizer. */ PJ_DEF(pj_status_t) pjmedia_h264_packetizer_create( - pj_pool_t *pool, - const pjmedia_h264_packetizer_cfg *cfg, - pjmedia_h264_packetizer **p) + pj_pool_t *pool, + const pjmedia_h264_packetizer_cfg *cfg, + pjmedia_h264_packetizer **p) { pjmedia_h264_packetizer *p_; PJ_ASSERT_RETURN(pool && p, PJ_EINVAL); if (cfg && - cfg->mode != PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED && - cfg->mode != PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL && - cfg->unpack_nal_start != 0 && cfg->unpack_nal_start != 3 && - cfg->unpack_nal_start != 4) + cfg->mode != PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED && + cfg->mode != PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL && + cfg->unpack_nal_start != 0 && cfg->unpack_nal_start != 3 && + cfg->unpack_nal_start != 4) { - return PJ_ENOTSUP; + return PJ_ENOTSUP; } p_ = PJ_POOL_ZALLOC_T(pool, pjmedia_h264_packetizer); if (cfg) { - pj_memcpy(&p_->cfg, cfg, sizeof(*cfg)); - if (p_->cfg.unpack_nal_start == 0) - p_->cfg.unpack_nal_start = 3; + pj_memcpy(&p_->cfg, cfg, sizeof(*cfg)); + if (p_->cfg.unpack_nal_start == 0) + p_->cfg.unpack_nal_start = 3; } else { - p_->cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED; - p_->cfg.mtu = PJMEDIA_MAX_VID_PAYLOAD_SIZE; - p_->cfg.unpack_nal_start = 3; + p_->cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED; + p_->cfg.mtu = PJMEDIA_MAX_VID_PAYLOAD_SIZE; + p_->cfg.unpack_nal_start = 3; } *p = p_; @@ -123,7 +122,7 @@ PJ_DEF(pj_status_t) pjmedia_h264_packetizer_create( * Generate an RTP payload from H.264 frame bitstream, in-place processing. */ PJ_DEF(pj_status_t) pjmedia_h264_packetize(pjmedia_h264_packetizer *pktz, - pj_uint8_t *buf, + pj_uint8_t *buf, pj_size_t buf_len, unsigned *pos, const pj_uint8_t **payload, @@ -132,14 +131,14 @@ PJ_DEF(pj_status_t) pjmedia_h264_packetize(pjmedia_h264_packetizer *pktz, pj_uint8_t *nal_start = NULL, *nal_end = NULL, *nal_octet = NULL; pj_uint8_t *p, *end; enum { - HEADER_SIZE_FU_A = 2, - HEADER_SIZE_STAP_A = 3, + HEADER_SIZE_FU_A = 2, + HEADER_SIZE_STAP_A = 3, }; enum { MAX_NALS_IN_AGGR = 32 }; #if DBG_PACKETIZE if (*pos == 0 && buf_len) { - PJ_LOG(3, ("h264pack", "<< Start packing new frame >>")); + PJ_LOG(3, ("h264pack", "<< Start packing new frame >>")); } #endif @@ -148,179 +147,179 @@ PJ_DEF(pj_status_t) pjmedia_h264_packetize(pjmedia_h264_packetizer *pktz, /* Find NAL unit startcode */ if (end-p >= 4) - nal_start = find_next_nal_unit(p, p+4); + nal_start = find_next_nal_unit(p, p+4); if (nal_start) { - /* Get NAL unit octet pointer */ - while (*nal_start++ == 0); - nal_octet = nal_start; + /* Get NAL unit octet pointer */ + while (*nal_start++ == 0); + nal_octet = nal_start; } else { - /* This NAL unit is being fragmented */ - nal_start = p; + /* This NAL unit is being fragmented */ + nal_start = p; } /* Get end of NAL unit */ p = nal_start+pktz->cfg.mtu+1; if (p > end || pktz->cfg.mode==PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL) - p = end; + p = end; nal_end = find_next_nal_unit(nal_start, p); if (!nal_end) - nal_end = p; + nal_end = p; /* Validate MTU vs NAL length on single NAL unit packetization */ if ((pktz->cfg.mode==PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL) && - nal_end - nal_start > pktz->cfg.mtu) + nal_end - nal_start > pktz->cfg.mtu) { - //pj_assert(!"MTU too small for H.264 single NAL packetization mode"); - PJ_LOG(2,(THIS_FILE, - "MTU too small for H.264 (required=%u, MTU=%u)", - nal_end - nal_start, pktz->cfg.mtu)); - return PJ_ETOOSMALL; + //pj_assert(!"MTU too small for H.264 single NAL packetization mode"); + PJ_LOG(2,(THIS_FILE, + "MTU too small for H.264 (required=%u, MTU=%u)", + nal_end - nal_start, pktz->cfg.mtu)); + return PJ_ETOOSMALL; } /* Evaluate the proper payload format structure */ /* Fragmentation (FU-A) packet */ if ((pktz->cfg.mode != PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL) && - (!nal_octet || nal_end-nal_start > pktz->cfg.mtu)) + (!nal_octet || nal_end-nal_start > pktz->cfg.mtu)) { - pj_uint8_t NRI, TYPE; - - if (nal_octet) { - /* We have NAL unit octet, so this is the first fragment */ - NRI = (*nal_octet & 0x60) >> 5; - TYPE = *nal_octet & 0x1F; - - /* Skip nal_octet in nal_start to be overriden by FU header */ - ++nal_start; - } else { - /* Not the first fragment, get NRI and NAL unit type - * from the previous fragment. - */ - p = nal_start - pktz->cfg.mtu; - NRI = (*p & 0x60) >> 5; - TYPE = *(p+1) & 0x1F; - } - - /* Init FU indicator (one octet: F+NRI+TYPE) */ - p = nal_start - HEADER_SIZE_FU_A; - *p = (NRI << 5) | NAL_TYPE_FU_A; - ++p; - - /* Init FU header (one octed: S+E+R+TYPE) */ - *p = TYPE; - if (nal_octet) - *p |= (1 << 7); /* S bit flag = start of fragmentation */ - if (nal_end-nal_start+HEADER_SIZE_FU_A <= pktz->cfg.mtu) - *p |= (1 << 6); /* E bit flag = end of fragmentation */ - - /* Set payload, payload length */ - *payload = nal_start - HEADER_SIZE_FU_A; - if (nal_end-nal_start+HEADER_SIZE_FU_A > pktz->cfg.mtu) - *payload_len = pktz->cfg.mtu; - else - *payload_len = nal_end - nal_start + HEADER_SIZE_FU_A; - *pos = (unsigned)(*payload + *payload_len - buf); + pj_uint8_t NRI, TYPE; + + if (nal_octet) { + /* We have NAL unit octet, so this is the first fragment */ + NRI = (*nal_octet & 0x60) >> 5; + TYPE = *nal_octet & 0x1F; + + /* Skip nal_octet in nal_start to be overriden by FU header */ + ++nal_start; + } else { + /* Not the first fragment, get NRI and NAL unit type + * from the previous fragment. + */ + p = nal_start - pktz->cfg.mtu; + NRI = (*p & 0x60) >> 5; + TYPE = *(p+1) & 0x1F; + } + + /* Init FU indicator (one octet: F+NRI+TYPE) */ + p = nal_start - HEADER_SIZE_FU_A; + *p = (NRI << 5) | NAL_TYPE_FU_A; + ++p; + + /* Init FU header (one octed: S+E+R+TYPE) */ + *p = TYPE; + if (nal_octet) + *p |= (1 << 7); /* S bit flag = start of fragmentation */ + if (nal_end-nal_start+HEADER_SIZE_FU_A <= pktz->cfg.mtu) + *p |= (1 << 6); /* E bit flag = end of fragmentation */ + + /* Set payload, payload length */ + *payload = nal_start - HEADER_SIZE_FU_A; + if (nal_end-nal_start+HEADER_SIZE_FU_A > pktz->cfg.mtu) + *payload_len = pktz->cfg.mtu; + else + *payload_len = nal_end - nal_start + HEADER_SIZE_FU_A; + *pos = (unsigned)(*payload + *payload_len - buf); #if DBG_PACKETIZE - PJ_LOG(3, ("h264pack", "Packetized fragmented H264 NAL unit " - "(pos=%d, type=%d, NRI=%d, S=%d, E=%d, len=%d/%d)", - *payload-buf, TYPE, NRI, *p>>7, (*p>>6)&1, *payload_len, - buf_len)); + PJ_LOG(3, ("h264pack", "Packetized fragmented H264 NAL unit " + "(pos=%d, type=%d, NRI=%d, S=%d, E=%d, len=%d/%d)", + *payload-buf, TYPE, NRI, *p>>7, (*p>>6)&1, *payload_len, + buf_len)); #endif - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Aggregation (STAP-A) packet */ if ((pktz->cfg.mode != PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL) && - (nal_end != end) && - (nal_end - nal_start + HEADER_SIZE_STAP_A) < pktz->cfg.mtu) + (nal_end != end) && + (nal_end - nal_start + HEADER_SIZE_STAP_A) < pktz->cfg.mtu) { - int total_size; - unsigned nal_cnt = 1; - pj_uint8_t *nal[MAX_NALS_IN_AGGR]; - pj_size_t nal_size[MAX_NALS_IN_AGGR]; - pj_uint8_t NRI; - - pj_assert(nal_octet); - - /* Init the first NAL unit in the packet */ - nal[0] = nal_start; - nal_size[0] = nal_end - nal_start; - total_size = (int)nal_size[0] + HEADER_SIZE_STAP_A; - NRI = (*nal_octet & 0x60) >> 5; - - /* Populate next NAL units */ - while (nal_cnt < MAX_NALS_IN_AGGR) { - pj_uint8_t *tmp_end; - - /* Find start address of the next NAL unit */ - p = nal[nal_cnt-1] + nal_size[nal_cnt-1]; - while (*p++ == 0); - nal[nal_cnt] = p; - - /* Find end address of the next NAL unit */ - tmp_end = p + (pktz->cfg.mtu - total_size); - if (tmp_end > end) - tmp_end = end; - p = find_next_nal_unit(p+1, tmp_end); - if (p) { - nal_size[nal_cnt] = p - nal[nal_cnt]; - } else { - break; - } - - /* Update total payload size (2 octet NAL size + NAL) */ - total_size += (2 + (int)nal_size[nal_cnt]); - if (total_size <= pktz->cfg.mtu) { - pj_uint8_t tmp_nri; - - /* Get maximum NRI of the aggregated NAL units */ - tmp_nri = (*(nal[nal_cnt]-1) & 0x60) >> 5; - if (tmp_nri > NRI) - NRI = tmp_nri; - } else { - break; - } - - ++nal_cnt; - } - - /* Only use STAP-A when we found more than one NAL units */ - if (nal_cnt > 1) { - unsigned i; - - /* Init STAP-A NAL header (F+NRI+TYPE) */ - p = nal[0] - HEADER_SIZE_STAP_A; - *p++ = (NRI << 5) | NAL_TYPE_STAP_A; - - /* Append all populated NAL units into payload (SIZE+NAL) */ - for (i = 0; i < nal_cnt; ++i) { - /* Put size (2 octets in network order) */ - pj_assert(nal_size[i] <= 0xFFFF); - *p++ = (pj_uint8_t)(nal_size[i] >> 8); - *p++ = (pj_uint8_t)(nal_size[i] & 0xFF); - - /* Append NAL unit, watchout memmove()-ing bitstream! */ - if (p != nal[i]) - pj_memmove(p, nal[i], nal_size[i]); - p += nal_size[i]; - } - - /* Set payload, payload length, and pos */ - *payload = nal[0] - HEADER_SIZE_STAP_A; - pj_assert(*payload >= buf+*pos); - *payload_len = p - *payload; - *pos = (unsigned)(nal[nal_cnt-1] + nal_size[nal_cnt-1] - buf); + int total_size; + unsigned nal_cnt = 1; + pj_uint8_t *nal[MAX_NALS_IN_AGGR]; + pj_size_t nal_size[MAX_NALS_IN_AGGR]; + pj_uint8_t NRI; + + pj_assert(nal_octet); + + /* Init the first NAL unit in the packet */ + nal[0] = nal_start; + nal_size[0] = nal_end - nal_start; + total_size = (int)nal_size[0] + HEADER_SIZE_STAP_A; + NRI = (*nal_octet & 0x60) >> 5; + + /* Populate next NAL units */ + while (nal_cnt < MAX_NALS_IN_AGGR) { + pj_uint8_t *tmp_end; + + /* Find start address of the next NAL unit */ + p = nal[nal_cnt-1] + nal_size[nal_cnt-1]; + while (*p++ == 0); + nal[nal_cnt] = p; + + /* Find end address of the next NAL unit */ + tmp_end = p + (pktz->cfg.mtu - total_size); + if (tmp_end > end) + tmp_end = end; + p = find_next_nal_unit(p+1, tmp_end); + if (p) { + nal_size[nal_cnt] = p - nal[nal_cnt]; + } else { + break; + } + + /* Update total payload size (2 octet NAL size + NAL) */ + total_size += (2 + (int)nal_size[nal_cnt]); + if (total_size <= pktz->cfg.mtu) { + pj_uint8_t tmp_nri; + + /* Get maximum NRI of the aggregated NAL units */ + tmp_nri = (*(nal[nal_cnt]-1) & 0x60) >> 5; + if (tmp_nri > NRI) + NRI = tmp_nri; + } else { + break; + } + + ++nal_cnt; + } + + /* Only use STAP-A when we found more than one NAL units */ + if (nal_cnt > 1) { + unsigned i; + + /* Init STAP-A NAL header (F+NRI+TYPE) */ + p = nal[0] - HEADER_SIZE_STAP_A; + *p++ = (NRI << 5) | NAL_TYPE_STAP_A; + + /* Append all populated NAL units into payload (SIZE+NAL) */ + for (i = 0; i < nal_cnt; ++i) { + /* Put size (2 octets in network order) */ + pj_assert(nal_size[i] <= 0xFFFF); + *p++ = (pj_uint8_t)(nal_size[i] >> 8); + *p++ = (pj_uint8_t)(nal_size[i] & 0xFF); + + /* Append NAL unit, watchout memmove()-ing bitstream! */ + if (p != nal[i]) + pj_memmove(p, nal[i], nal_size[i]); + p += nal_size[i]; + } + + /* Set payload, payload length, and pos */ + *payload = nal[0] - HEADER_SIZE_STAP_A; + pj_assert(*payload >= buf+*pos); + *payload_len = p - *payload; + *pos = (unsigned)(nal[nal_cnt-1] + nal_size[nal_cnt-1] - buf); #if DBG_PACKETIZE - PJ_LOG(3, ("h264pack", "Packetized aggregation of " - "%d H264 NAL units (pos=%d, NRI=%d len=%d/%d)", - nal_cnt, *payload-buf, NRI, *payload_len, buf_len)); + PJ_LOG(3, ("h264pack", "Packetized aggregation of " + "%d H264 NAL units (pos=%d, NRI=%d len=%d/%d)", + nal_cnt, *payload-buf, NRI, *payload_len, buf_len)); #endif - return PJ_SUCCESS; - } + return PJ_SUCCESS; + } } /* Single NAL unit packet */ @@ -330,9 +329,9 @@ PJ_DEF(pj_status_t) pjmedia_h264_packetize(pjmedia_h264_packetizer *pktz, #if DBG_PACKETIZE PJ_LOG(3, ("h264pack", "Packetized single H264 NAL unit " - "(pos=%d, type=%d, NRI=%d, len=%d/%d)", - nal_start-buf, *nal_octet&0x1F, (*nal_octet&0x60)>>5, - *payload_len, buf_len)); + "(pos=%d, type=%d, NRI=%d, len=%d/%d)", + nal_start-buf, *nal_octet&0x1F, (*nal_octet&0x60)>>5, + *payload_len, buf_len)); #endif return PJ_SUCCESS; @@ -346,11 +345,11 @@ PJ_DEF(pj_status_t) pjmedia_h264_packetize(pjmedia_h264_packetizer *pktz, * state for the FU-A/B packets. */ PJ_DEF(pj_status_t) pjmedia_h264_unpacketize(pjmedia_h264_packetizer *pktz, - const pj_uint8_t *payload, + const pj_uint8_t *payload, pj_size_t payload_len, pj_uint8_t *bits, pj_size_t bits_len, - unsigned *bits_pos) + unsigned *bits_pos) { const pj_uint8_t nal_start[4] = {0, 0, 0, 1}; const pj_uint8_t *nal_start_code; @@ -358,179 +357,179 @@ PJ_DEF(pj_status_t) pjmedia_h264_unpacketize(pjmedia_h264_packetizer *pktz, pj_uint8_t nal_type; nal_start_code = nal_start + PJ_ARRAY_SIZE(nal_start) - - pktz->cfg.unpack_nal_start; + pktz->cfg.unpack_nal_start; #if DBG_UNPACKETIZE if (*bits_pos == 0 && payload_len) { - PJ_LOG(3, ("h264unpack", ">> Start unpacking new frame <<")); + PJ_LOG(3, ("h264unpack", ">> Start unpacking new frame <<")); } #endif /* Check if this is a missing/lost packet */ if (payload == NULL) { - pktz->unpack_prev_lost = PJ_TRUE; - return PJ_SUCCESS; + pktz->unpack_prev_lost = PJ_TRUE; + return PJ_SUCCESS; } /* H264 payload size */ if (payload_len < MIN_PAYLOAD_SIZE) { - /* Invalid bitstream, discard this payload */ - pktz->unpack_prev_lost = PJ_TRUE; - return PJ_EINVAL; + /* Invalid bitstream, discard this payload */ + pktz->unpack_prev_lost = PJ_TRUE; + return PJ_EINVAL; } /* Reset last sync point for every new picture bitstream */ if (*bits_pos == 0) - pktz->unpack_last_sync_pos = 0; + pktz->unpack_last_sync_pos = 0; nal_type = *payload & 0x1F; if (nal_type >= NAL_TYPE_SINGLE_NAL_MIN && - nal_type <= NAL_TYPE_SINGLE_NAL_MAX) + nal_type <= NAL_TYPE_SINGLE_NAL_MAX) { - /* Single NAL unit packet */ - pj_uint8_t *p = bits + *bits_pos; + /* Single NAL unit packet */ + pj_uint8_t *p = bits + *bits_pos; - /* Validate bitstream length */ - if (bits_len-*bits_pos < payload_len+pktz->cfg.unpack_nal_start) { - /* Insufficient bistream buffer, discard this payload */ - pj_assert(!"Insufficient H.264 bitstream buffer"); - return PJ_ETOOSMALL; - } + /* Validate bitstream length */ + if (bits_len-*bits_pos < payload_len+pktz->cfg.unpack_nal_start) { + /* Insufficient bistream buffer, discard this payload */ + pj_assert(!"Insufficient H.264 bitstream buffer"); + return PJ_ETOOSMALL; + } - /* Write NAL unit start code */ - pj_memcpy(p, nal_start_code, pktz->cfg.unpack_nal_start); - p += pktz->cfg.unpack_nal_start; + /* Write NAL unit start code */ + pj_memcpy(p, nal_start_code, pktz->cfg.unpack_nal_start); + p += pktz->cfg.unpack_nal_start; - /* Write NAL unit */ - pj_memcpy(p, payload, payload_len); - p += payload_len; + /* Write NAL unit */ + pj_memcpy(p, payload, payload_len); + p += payload_len; - /* Update the bitstream writing offset */ - *bits_pos = (unsigned)(p - bits); - pktz->unpack_last_sync_pos = *bits_pos; + /* Update the bitstream writing offset */ + *bits_pos = (unsigned)(p - bits); + pktz->unpack_last_sync_pos = *bits_pos; #if DBG_UNPACKETIZE - PJ_LOG(3, ("h264unpack", "Unpacked single H264 NAL unit " - "(type=%d, NRI=%d, len=%d)", - nal_type, (*payload&0x60)>>5, payload_len)); + PJ_LOG(3, ("h264unpack", "Unpacked single H264 NAL unit " + "(type=%d, NRI=%d, len=%d)", + nal_type, (*payload&0x60)>>5, payload_len)); #endif } else if (nal_type == NAL_TYPE_STAP_A) { - /* Aggregation packet */ - pj_uint8_t *p, *p_end; - const pj_uint8_t *q, *q_end; - unsigned cnt = 0; - - /* Validate bitstream length */ - if (bits_len - *bits_pos < payload_len + 32) { - /* Insufficient bistream buffer, discard this payload */ - pj_assert(!"Insufficient H.264 bitstream buffer"); - return PJ_ETOOSMALL; - } - - /* Fill bitstream */ - p = bits + *bits_pos; - p_end = bits + bits_len; - q = payload + 1; - q_end = payload + payload_len; - while (q < q_end && p < p_end) { - pj_uint16_t tmp_nal_size; - - /* Write NAL unit start code */ - pj_memcpy(p, nal_start_code, pktz->cfg.unpack_nal_start); - p += pktz->cfg.unpack_nal_start; - - /* Get NAL unit size */ - tmp_nal_size = (*q << 8) | *(q+1); - q += 2; - if (q + tmp_nal_size > q_end) { - /* Invalid bitstream, discard the rest of the payload */ - return PJ_EINVAL; - } - - /* Write NAL unit */ - pj_memcpy(p, q, tmp_nal_size); - p += tmp_nal_size; - q += tmp_nal_size; - ++cnt; - - /* Update the bitstream writing offset */ - *bits_pos = (unsigned)(p - bits); - pktz->unpack_last_sync_pos = *bits_pos; - } + /* Aggregation packet */ + pj_uint8_t *p, *p_end; + const pj_uint8_t *q, *q_end; + unsigned cnt = 0; + + /* Validate bitstream length */ + if (bits_len - *bits_pos < payload_len + 32) { + /* Insufficient bistream buffer, discard this payload */ + pj_assert(!"Insufficient H.264 bitstream buffer"); + return PJ_ETOOSMALL; + } + + /* Fill bitstream */ + p = bits + *bits_pos; + p_end = bits + bits_len; + q = payload + 1; + q_end = payload + payload_len; + while (q < q_end && p < p_end) { + pj_uint16_t tmp_nal_size; + + /* Write NAL unit start code */ + pj_memcpy(p, nal_start_code, pktz->cfg.unpack_nal_start); + p += pktz->cfg.unpack_nal_start; + + /* Get NAL unit size */ + tmp_nal_size = (*q << 8) | *(q+1); + q += 2; + if (q + tmp_nal_size > q_end) { + /* Invalid bitstream, discard the rest of the payload */ + return PJ_EINVAL; + } + + /* Write NAL unit */ + pj_memcpy(p, q, tmp_nal_size); + p += tmp_nal_size; + q += tmp_nal_size; + ++cnt; + + /* Update the bitstream writing offset */ + *bits_pos = (unsigned)(p - bits); + pktz->unpack_last_sync_pos = *bits_pos; + } #if DBG_UNPACKETIZE - PJ_LOG(3, ("h264unpack", "Unpacked %d H264 NAL units (len=%d)", - cnt, payload_len)); + PJ_LOG(3, ("h264unpack", "Unpacked %d H264 NAL units (len=%d)", + cnt, payload_len)); #endif } else if (nal_type == NAL_TYPE_FU_A) { - /* Fragmentation packet */ - pj_uint8_t *p; - const pj_uint8_t *q = payload; - pj_uint8_t NRI, TYPE, S, E; - - p = bits + *bits_pos; - - /* Validate bitstream length */ - if (bits_len-*bits_pos < payload_len+pktz->cfg.unpack_nal_start) { - /* Insufficient bistream buffer, drop this packet */ - pj_assert(!"Insufficient H.264 bitstream buffer"); - pktz->unpack_prev_lost = PJ_TRUE; - return PJ_ETOOSMALL; - } - - /* Get info */ - S = *(q+1) & 0x80; /* Start bit flag */ - E = *(q+1) & 0x40; /* End bit flag */ - TYPE = *(q+1) & 0x1f; - NRI = (*q & 0x60) >> 5; - - /* Fill bitstream */ - if (S) { - /* This is the first part, write NAL unit start code */ - pj_memcpy(p, nal_start_code, pktz->cfg.unpack_nal_start); - p += pktz->cfg.unpack_nal_start; - - /* Write NAL unit octet */ - *p++ = (NRI << 5) | TYPE; - } else if (pktz->unpack_prev_lost) { - /* If prev packet was lost, revert the bitstream pointer to - * the last sync point. - */ - pj_assert(pktz->unpack_last_sync_pos <= *bits_pos); - *bits_pos = pktz->unpack_last_sync_pos; - /* And discard this payload (and the following fragmentation - * payloads carrying this same NAL unit. - */ - return PJ_EIGNORED; - } - q += 2; - - /* Write NAL unit */ - pj_memcpy(p, q, payload_len - 2); - p += (payload_len - 2); - - /* Update the bitstream writing offset */ - *bits_pos = (unsigned)(p - bits); - if (E) { - /* Update the sync pos only if the end bit flag is set */ - pktz->unpack_last_sync_pos = *bits_pos; - } + /* Fragmentation packet */ + pj_uint8_t *p; + const pj_uint8_t *q = payload; + pj_uint8_t NRI, TYPE, S, E; + + p = bits + *bits_pos; + + /* Validate bitstream length */ + if (bits_len-*bits_pos < payload_len+pktz->cfg.unpack_nal_start) { + /* Insufficient bistream buffer, drop this packet */ + pj_assert(!"Insufficient H.264 bitstream buffer"); + pktz->unpack_prev_lost = PJ_TRUE; + return PJ_ETOOSMALL; + } + + /* Get info */ + S = *(q+1) & 0x80; /* Start bit flag */ + E = *(q+1) & 0x40; /* End bit flag */ + TYPE = *(q+1) & 0x1f; + NRI = (*q & 0x60) >> 5; + + /* Fill bitstream */ + if (S) { + /* This is the first part, write NAL unit start code */ + pj_memcpy(p, nal_start_code, pktz->cfg.unpack_nal_start); + p += pktz->cfg.unpack_nal_start; + + /* Write NAL unit octet */ + *p++ = (NRI << 5) | TYPE; + } else if (pktz->unpack_prev_lost) { + /* If prev packet was lost, revert the bitstream pointer to + * the last sync point. + */ + pj_assert(pktz->unpack_last_sync_pos <= *bits_pos); + *bits_pos = pktz->unpack_last_sync_pos; + /* And discard this payload (and the following fragmentation + * payloads carrying this same NAL unit. + */ + return PJ_EIGNORED; + } + q += 2; + + /* Write NAL unit */ + pj_memcpy(p, q, payload_len - 2); + p += (payload_len - 2); + + /* Update the bitstream writing offset */ + *bits_pos = (unsigned)(p - bits); + if (E) { + /* Update the sync pos only if the end bit flag is set */ + pktz->unpack_last_sync_pos = *bits_pos; + } #if DBG_UNPACKETIZE - PJ_LOG(3, ("h264unpack", "Unpacked fragmented H264 NAL unit " - "(type=%d, NRI=%d, len=%d)", - TYPE, NRI, payload_len)); + PJ_LOG(3, ("h264unpack", "Unpacked fragmented H264 NAL unit " + "(type=%d, NRI=%d, len=%d)", + TYPE, NRI, payload_len)); #endif } else { - *bits_pos = 0; - return PJ_ENOTSUP; + *bits_pos = 0; + return PJ_ENOTSUP; } pktz->unpack_prev_lost = PJ_FALSE; diff --git a/pjmedia/src/pjmedia-codec/ilbc.c b/pjmedia/src/pjmedia-codec/ilbc.c index e5481b92b5..9e42212eac 100644 --- a/pjmedia/src/pjmedia-codec/ilbc.c +++ b/pjmedia/src/pjmedia-codec/ilbc.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,7 +34,7 @@ #include #define iLBC_Enc_Inst_t AudioConverterRef #define iLBC_Dec_Inst_t AudioConverterRef - #define BLOCKL_MAX 1 + #define BLOCKL_MAX 1 #else #include "../../third_party/ilbc/iLBC_encode.h" #include "../../third_party/ilbc/iLBC_decode.h" @@ -47,51 +46,51 @@ #if defined(PJMEDIA_HAS_ILBC_CODEC) && PJMEDIA_HAS_ILBC_CODEC != 0 -#define THIS_FILE "ilbc.c" -#define CLOCK_RATE 8000 -#define DEFAULT_MODE 30 +#define THIS_FILE "ilbc.c" +#define CLOCK_RATE 8000 +#define DEFAULT_MODE 30 /* Prototypes for iLBC factory */ static pj_status_t ilbc_test_alloc(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ); + const pjmedia_codec_info *id ); static pj_status_t ilbc_default_attr(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ); static pj_status_t ilbc_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t ilbc_alloc_codec(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t ilbc_dealloc_codec(pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for iLBC implementation. */ static pj_status_t ilbc_codec_init(pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t ilbc_codec_open(pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t ilbc_codec_close(pjmedia_codec *codec ); static pj_status_t ilbc_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t ilbc_codec_parse(pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t ilbc_codec_encode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t ilbc_codec_decode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t ilbc_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); /* Definition for iLBC codec operations. */ static pjmedia_codec_op ilbc_op = @@ -121,45 +120,45 @@ static pjmedia_codec_factory_op ilbc_factory_op = static struct ilbc_factory { pjmedia_codec_factory base; - pjmedia_endpt *endpt; + pjmedia_endpt *endpt; - int mode; - int bps; + int mode; + int bps; } ilbc_factory; /* iLBC codec private data. */ struct ilbc_codec { - pjmedia_codec base; - pj_pool_t *pool; - char obj_name[PJ_MAX_OBJ_NAME]; - pjmedia_silence_det *vad; - pj_bool_t vad_enabled; - pj_bool_t plc_enabled; - pj_timestamp last_tx; - - - pj_bool_t enc_ready; - iLBC_Enc_Inst_t enc; - unsigned enc_frame_size; - unsigned enc_samples_per_frame; - float enc_block[BLOCKL_MAX]; - - pj_bool_t dec_ready; - iLBC_Dec_Inst_t dec; - unsigned dec_frame_size; - unsigned dec_samples_per_frame; - float dec_block[BLOCKL_MAX]; + pjmedia_codec base; + pj_pool_t *pool; + char obj_name[PJ_MAX_OBJ_NAME]; + pjmedia_silence_det *vad; + pj_bool_t vad_enabled; + pj_bool_t plc_enabled; + pj_timestamp last_tx; + + + pj_bool_t enc_ready; + iLBC_Enc_Inst_t enc; + unsigned enc_frame_size; + unsigned enc_samples_per_frame; + float enc_block[BLOCKL_MAX]; + + pj_bool_t dec_ready; + iLBC_Dec_Inst_t dec; + unsigned dec_frame_size; + unsigned dec_samples_per_frame; + float dec_block[BLOCKL_MAX]; #if defined(PJMEDIA_ILBC_CODEC_USE_COREAUDIO)&& PJMEDIA_ILBC_CODEC_USE_COREAUDIO - unsigned enc_total_packets; - char *enc_buffer; - unsigned enc_buffer_offset; + unsigned enc_total_packets; + char *enc_buffer; + unsigned enc_buffer_offset; - unsigned dec_total_packets; - char *dec_buffer; - unsigned dec_buffer_offset; + unsigned dec_total_packets; + char *dec_buffer; + unsigned dec_buffer_offset; #endif }; @@ -169,7 +168,7 @@ static pj_str_t STR_MODE = {"mode", 4}; * Initialize and register iLBC codec factory to pjmedia endpoint. */ PJ_DEF(pj_status_t) pjmedia_codec_ilbc_init( pjmedia_endpt *endpt, - int mode ) + int mode ) { pjmedia_codec_mgr *codec_mgr; pj_status_t status; @@ -178,8 +177,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_ilbc_init( pjmedia_endpt *endpt, PJ_ASSERT_RETURN(mode==0 || mode==20 || mode==30, PJ_EINVAL); if (ilbc_factory.endpt != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } /* Create iLBC codec factory. */ @@ -188,29 +187,29 @@ PJ_DEF(pj_status_t) pjmedia_codec_ilbc_init( pjmedia_endpt *endpt, ilbc_factory.endpt = endpt; if (mode == 0) - mode = DEFAULT_MODE; + mode = DEFAULT_MODE; ilbc_factory.mode = mode; if (mode == 20) { - ilbc_factory.bps = 15200; + ilbc_factory.bps = 15200; } else { - ilbc_factory.bps = 13333; + ilbc_factory.bps = 13333; } /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - ilbc_factory.endpt = NULL; - return PJ_EINVALIDOP; + ilbc_factory.endpt = NULL; + return PJ_EINVALIDOP; } /* Register codec factory to endpoint. */ status = pjmedia_codec_mgr_register_factory(codec_mgr, - &ilbc_factory.base); + &ilbc_factory.base); if (status != PJ_SUCCESS) { - ilbc_factory.endpt = NULL; - return status; + ilbc_factory.endpt = NULL; + return status; } /* Done. */ @@ -229,18 +228,18 @@ PJ_DEF(pj_status_t) pjmedia_codec_ilbc_deinit(void) pj_status_t status; if (ilbc_factory.endpt == NULL) { - /* Not registered. */ - return PJ_SUCCESS; + /* Not registered. */ + return PJ_SUCCESS; } /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(ilbc_factory.endpt); if (!codec_mgr) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; /* Unregister iLBC codec factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &ilbc_factory.base); + &ilbc_factory.base); ilbc_factory.endpt = NULL; return status; @@ -250,7 +249,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_ilbc_deinit(void) * Check if factory can allocate the specified codec. */ static pj_status_t ilbc_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *info ) + const pjmedia_codec_info *info ) { const pj_str_t ilbc_tag = { "iLBC", 4}; @@ -260,19 +259,19 @@ static pj_status_t ilbc_test_alloc( pjmedia_codec_factory *factory, /* Type MUST be audio. */ if (info->type != PJMEDIA_TYPE_AUDIO) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check encoding name. */ if (pj_stricmp(&info->encoding_name, &ilbc_tag) != 0) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check clock-rate */ if (info->clock_rate != CLOCK_RATE) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Channel count must be one */ if (info->channel_cnt != 1) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Yes, this should be iLBC! */ return PJ_SUCCESS; @@ -283,8 +282,8 @@ static pj_status_t ilbc_test_alloc( pjmedia_codec_factory *factory, * Generate default attribute. */ static pj_status_t ilbc_default_attr (pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ) { PJ_UNUSED_ARG(factory); PJ_ASSERT_RETURN(factory==&ilbc_factory.base, PJ_EINVAL); @@ -309,9 +308,9 @@ static pj_status_t ilbc_default_attr (pjmedia_codec_factory *factory, attr->setting.dec_fmtp.cnt = 1; attr->setting.dec_fmtp.param[0].name = STR_MODE; if (ilbc_factory.mode == 30) - attr->setting.dec_fmtp.param[0].val = pj_str("30"); + attr->setting.dec_fmtp.param[0].val = pj_str("30"); else - attr->setting.dec_fmtp.param[0].val = pj_str("20"); + attr->setting.dec_fmtp.param[0].val = pj_str("20"); return PJ_SUCCESS; } @@ -320,8 +319,8 @@ static pj_status_t ilbc_default_attr (pjmedia_codec_factory *factory, * Enum codecs supported by this factory (i.e. only iLBC!). */ static pj_status_t ilbc_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]) + unsigned *count, + pjmedia_codec_info codecs[]) { PJ_UNUSED_ARG(factory); PJ_ASSERT_RETURN(factory==&ilbc_factory.base, PJ_EINVAL); @@ -345,8 +344,8 @@ static pj_status_t ilbc_enum_codecs(pjmedia_codec_factory *factory, * Allocate a new iLBC codec instance. */ static pj_status_t ilbc_alloc_codec(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { pj_pool_t *pool; struct ilbc_codec *codec; @@ -355,7 +354,7 @@ static pj_status_t ilbc_alloc_codec(pjmedia_codec_factory *factory, PJ_ASSERT_RETURN(factory == &ilbc_factory.base, PJ_EINVAL); pool = pjmedia_endpt_create_pool(ilbc_factory.endpt, "iLBC%p", - 2000, 2000); + 2000, 2000); PJ_ASSERT_RETURN(pool != NULL, PJ_ENOMEM); codec = PJ_POOL_ZALLOC_T(pool, struct ilbc_codec); @@ -364,7 +363,7 @@ static pj_status_t ilbc_alloc_codec(pjmedia_codec_factory *factory, codec->pool = pool; pj_ansi_snprintf(codec->obj_name, sizeof(codec->obj_name), - "ilbc%p", codec); + "ilbc%p", codec); *p_codec = &codec->base; return PJ_SUCCESS; @@ -375,7 +374,7 @@ static pj_status_t ilbc_alloc_codec(pjmedia_codec_factory *factory, * Free codec. */ static pj_status_t ilbc_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { struct ilbc_codec *ilbc_codec; @@ -387,12 +386,12 @@ static pj_status_t ilbc_dealloc_codec( pjmedia_codec_factory *factory, #if defined(PJMEDIA_ILBC_CODEC_USE_COREAUDIO)&& PJMEDIA_ILBC_CODEC_USE_COREAUDIO if (ilbc_codec->enc) { - AudioConverterDispose(ilbc_codec->enc); - ilbc_codec->enc = NULL; + AudioConverterDispose(ilbc_codec->enc); + ilbc_codec->enc = NULL; } if (ilbc_codec->dec) { - AudioConverterDispose(ilbc_codec->dec); - ilbc_codec->dec = NULL; + AudioConverterDispose(ilbc_codec->dec); + ilbc_codec->dec = NULL; } #endif @@ -405,7 +404,7 @@ static pj_status_t ilbc_dealloc_codec( pjmedia_codec_factory *factory, * Init codec. */ static pj_status_t ilbc_codec_init(pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(pool); @@ -416,13 +415,13 @@ static pj_status_t ilbc_codec_init(pjmedia_codec *codec, * Open codec. */ static pj_status_t ilbc_codec_open(pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { struct ilbc_codec *ilbc_codec = (struct ilbc_codec*)codec; pj_status_t status; unsigned i; pj_uint16_t dec_fmtp_mode = DEFAULT_MODE, - enc_fmtp_mode = DEFAULT_MODE; + enc_fmtp_mode = DEFAULT_MODE; #if defined(PJMEDIA_ILBC_CODEC_USE_COREAUDIO)&& PJMEDIA_ILBC_CODEC_USE_COREAUDIO AudioStreamBasicDescription srcFormat, dstFormat; @@ -431,61 +430,61 @@ static pj_status_t ilbc_codec_open(pjmedia_codec *codec, srcFormat.mSampleRate = attr->info.clock_rate; srcFormat.mFormatID = kAudioFormatLinearPCM; srcFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger - | kLinearPCMFormatFlagIsPacked; + | kLinearPCMFormatFlagIsPacked; srcFormat.mBitsPerChannel = attr->info.pcm_bits_per_sample; srcFormat.mChannelsPerFrame = attr->info.channel_cnt; srcFormat.mBytesPerFrame = srcFormat.mChannelsPerFrame - * srcFormat.mBitsPerChannel >> 3; + * srcFormat.mBitsPerChannel >> 3; srcFormat.mFramesPerPacket = 1; srcFormat.mBytesPerPacket = srcFormat.mBytesPerFrame * - srcFormat.mFramesPerPacket; + srcFormat.mFramesPerPacket; memset(&dstFormat, 0, sizeof(dstFormat)); - dstFormat.mSampleRate = attr->info.clock_rate; - dstFormat.mFormatID = kAudioFormatiLBC; + dstFormat.mSampleRate = attr->info.clock_rate; + dstFormat.mFormatID = kAudioFormatiLBC; dstFormat.mChannelsPerFrame = attr->info.channel_cnt; #endif pj_assert(ilbc_codec != NULL); pj_assert(ilbc_codec->enc_ready == PJ_FALSE && - ilbc_codec->dec_ready == PJ_FALSE); + ilbc_codec->dec_ready == PJ_FALSE); /* Get decoder mode */ for (i = 0; i < attr->setting.dec_fmtp.cnt; ++i) { - if (pj_stricmp(&attr->setting.dec_fmtp.param[i].name, &STR_MODE) == 0) - { - dec_fmtp_mode = (pj_uint16_t) - pj_strtoul(&attr->setting.dec_fmtp.param[i].val); - break; - } + if (pj_stricmp(&attr->setting.dec_fmtp.param[i].name, &STR_MODE) == 0) + { + dec_fmtp_mode = (pj_uint16_t) + pj_strtoul(&attr->setting.dec_fmtp.param[i].val); + break; + } } /* Decoder mode must be set */ PJ_ASSERT_RETURN(dec_fmtp_mode == 20 || dec_fmtp_mode == 30, - PJMEDIA_CODEC_EINMODE); + PJMEDIA_CODEC_EINMODE); /* Get encoder mode */ for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { - if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name, &STR_MODE) == 0) - { - enc_fmtp_mode = (pj_uint16_t) - pj_strtoul(&attr->setting.enc_fmtp.param[i].val); - break; - } + if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name, &STR_MODE) == 0) + { + enc_fmtp_mode = (pj_uint16_t) + pj_strtoul(&attr->setting.enc_fmtp.param[i].val); + break; + } } PJ_ASSERT_RETURN(enc_fmtp_mode==20 || enc_fmtp_mode==30, - PJMEDIA_CODEC_EINMODE); + PJMEDIA_CODEC_EINMODE); /* Both sides of a bi-directional session MUST use the same "mode" value. * In this point, possible values are only 20 or 30, so when encoder and * decoder modes are not same, just use the default mode, it is 30. */ if (enc_fmtp_mode != dec_fmtp_mode) { - enc_fmtp_mode = dec_fmtp_mode = DEFAULT_MODE; - PJ_LOG(4,(ilbc_codec->obj_name, - "Normalized iLBC encoder and decoder modes to %d", - DEFAULT_MODE)); + enc_fmtp_mode = dec_fmtp_mode = DEFAULT_MODE; + PJ_LOG(4,(ilbc_codec->obj_name, + "Normalized iLBC encoder and decoder modes to %d", + DEFAULT_MODE)); } /* Update some attributes based on negotiated mode. */ @@ -500,10 +499,10 @@ static pj_status_t ilbc_codec_open(pjmedia_codec *codec, /* Use AudioFormat API to fill out the rest of the description */ size = sizeof(dstFormat); AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, - 0, NULL, &size, &dstFormat); + 0, NULL, &size, &dstFormat); if (AudioConverterNew(&srcFormat, &dstFormat, &ilbc_codec->enc) != noErr) - return PJMEDIA_CODEC_EFAILED; + return PJMEDIA_CODEC_EFAILED; ilbc_codec->enc_frame_size = (enc_fmtp_mode == 20? 38 : 50); #else ilbc_codec->enc_frame_size = initEncode(&ilbc_codec->enc, enc_fmtp_mode); @@ -514,12 +513,12 @@ static pj_status_t ilbc_codec_open(pjmedia_codec *codec, /* Create decoder */ #if defined(PJMEDIA_ILBC_CODEC_USE_COREAUDIO)&& PJMEDIA_ILBC_CODEC_USE_COREAUDIO if (AudioConverterNew(&dstFormat, &srcFormat, &ilbc_codec->dec) != noErr) - return PJMEDIA_CODEC_EFAILED; + return PJMEDIA_CODEC_EFAILED; ilbc_codec->dec_samples_per_frame = CLOCK_RATE * dec_fmtp_mode / 1000; #else ilbc_codec->dec_samples_per_frame = initDecode(&ilbc_codec->dec, - dec_fmtp_mode, - attr->setting.penh); + dec_fmtp_mode, + attr->setting.penh); #endif ilbc_codec->dec_frame_size = (dec_fmtp_mode == 20? 38 : 50); ilbc_codec->dec_ready = PJ_TRUE; @@ -530,10 +529,10 @@ static pj_status_t ilbc_codec_open(pjmedia_codec *codec, /* Create silence detector. */ ilbc_codec->vad_enabled = (attr->setting.vad != 0); status = pjmedia_silence_det_create(ilbc_codec->pool, CLOCK_RATE, - ilbc_codec->enc_samples_per_frame, - &ilbc_codec->vad); + ilbc_codec->enc_samples_per_frame, + &ilbc_codec->vad); if (status != PJ_SUCCESS) - return status; + return status; /* Init last_tx (not necessary because of zalloc, but better * be safe in case someone remove zalloc later. @@ -541,7 +540,7 @@ static pj_status_t ilbc_codec_open(pjmedia_codec *codec, pj_set_timestamp32(&ilbc_codec->last_tx, 0, 0); PJ_LOG(4,(ilbc_codec->obj_name, - "iLBC codec opened, mode=%d", dec_fmtp_mode)); + "iLBC codec opened, mode=%d", dec_fmtp_mode)); return PJ_SUCCESS; } @@ -565,7 +564,7 @@ static pj_status_t ilbc_codec_close( pjmedia_codec *codec ) * Modify codec settings. */ static pj_status_t ilbc_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { struct ilbc_codec *ilbc_codec = (struct ilbc_codec*)codec; @@ -579,11 +578,11 @@ static pj_status_t ilbc_codec_modify(pjmedia_codec *codec, * Get frames in the packet. */ static pj_status_t ilbc_codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { struct ilbc_codec *ilbc_codec = (struct ilbc_codec*)codec; unsigned count; @@ -592,16 +591,16 @@ static pj_status_t ilbc_codec_parse( pjmedia_codec *codec, count = 0; while (pkt_size >= ilbc_codec->dec_frame_size && count < *frame_cnt) { - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = pkt; - frames[count].size = ilbc_codec->dec_frame_size; - frames[count].timestamp.u64 = ts->u64 + (pj_uint64_t)count * - ilbc_codec->dec_samples_per_frame; + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = pkt; + frames[count].size = ilbc_codec->dec_frame_size; + frames[count].timestamp.u64 = ts->u64 + (pj_uint64_t)count * + ilbc_codec->dec_samples_per_frame; - pkt = ((char*)pkt) + ilbc_codec->dec_frame_size; - pkt_size -= ilbc_codec->dec_frame_size; + pkt = ((char*)pkt) + ilbc_codec->dec_frame_size; + pkt_size -= ilbc_codec->dec_frame_size; - ++count; + ++count; } *frame_cnt = count; @@ -624,16 +623,16 @@ static OSStatus encodeDataProc ( ioData->mBuffers[0].mDataByteSize = 0; if (ilbc_codec->enc_total_packets < *ioNumberDataPackets) { - *ioNumberDataPackets = ilbc_codec->enc_total_packets; + *ioNumberDataPackets = ilbc_codec->enc_total_packets; } if (*ioNumberDataPackets) { - ioData->mBuffers[0].mData = ilbc_codec->enc_buffer + - ilbc_codec->enc_buffer_offset; - ioData->mBuffers[0].mDataByteSize = *ioNumberDataPackets * - ilbc_codec->enc_samples_per_frame - << 1; - ilbc_codec->enc_buffer_offset += ioData->mBuffers[0].mDataByteSize; + ioData->mBuffers[0].mData = ilbc_codec->enc_buffer + + ilbc_codec->enc_buffer_offset; + ioData->mBuffers[0].mDataByteSize = *ioNumberDataPackets * + ilbc_codec->enc_samples_per_frame + << 1; + ilbc_codec->enc_buffer_offset += ioData->mBuffers[0].mDataByteSize; } ilbc_codec->enc_total_packets -= *ioNumberDataPackets; @@ -655,15 +654,15 @@ static OSStatus decodeDataProc ( ioData->mBuffers[0].mDataByteSize = 0; if (ilbc_codec->dec_total_packets < *ioNumberDataPackets) { - *ioNumberDataPackets = ilbc_codec->dec_total_packets; + *ioNumberDataPackets = ilbc_codec->dec_total_packets; } if (*ioNumberDataPackets) { - ioData->mBuffers[0].mData = ilbc_codec->dec_buffer + - ilbc_codec->dec_buffer_offset; - ioData->mBuffers[0].mDataByteSize = *ioNumberDataPackets * - ilbc_codec->dec_frame_size; - ilbc_codec->dec_buffer_offset += ioData->mBuffers[0].mDataByteSize; + ioData->mBuffers[0].mData = ilbc_codec->dec_buffer + + ilbc_codec->dec_buffer_offset; + ioData->mBuffers[0].mDataByteSize = *ioNumberDataPackets * + ilbc_codec->dec_frame_size; + ilbc_codec->dec_buffer_offset += ioData->mBuffers[0].mDataByteSize; } ilbc_codec->dec_total_packets -= *ioNumberDataPackets; @@ -675,9 +674,9 @@ static OSStatus decodeDataProc ( * Encode frame. */ static pj_status_t ilbc_codec_encode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct ilbc_codec *ilbc_codec = (struct ilbc_codec*)codec; pj_int16_t *pcm_in; @@ -689,35 +688,35 @@ static pj_status_t ilbc_codec_encode(pjmedia_codec *codec, nsamples = input->size >> 1; PJ_ASSERT_RETURN(nsamples % ilbc_codec->enc_samples_per_frame == 0, - PJMEDIA_CODEC_EPCMFRMINLEN); + PJMEDIA_CODEC_EPCMFRMINLEN); PJ_ASSERT_RETURN(output_buf_len >= ilbc_codec->enc_frame_size * nsamples / - ilbc_codec->enc_samples_per_frame, - PJMEDIA_CODEC_EFRMTOOSHORT); + ilbc_codec->enc_samples_per_frame, + PJMEDIA_CODEC_EFRMTOOSHORT); /* Detect silence */ if (ilbc_codec->vad_enabled) { - pj_bool_t is_silence; - pj_int32_t silence_period; - - silence_period = pj_timestamp_diff32(&ilbc_codec->last_tx, - &input->timestamp); - - is_silence = pjmedia_silence_det_detect(ilbc_codec->vad, - (const pj_int16_t*)input->buf, - (input->size >> 1), - NULL); - if (is_silence && - (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || - silence_period < PJMEDIA_CODEC_MAX_SILENCE_PERIOD*8000/1000)) - { - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->buf = NULL; - output->size = 0; - output->timestamp = input->timestamp; - return PJ_SUCCESS; - } else { - ilbc_codec->last_tx = input->timestamp; - } + pj_bool_t is_silence; + pj_int32_t silence_period; + + silence_period = pj_timestamp_diff32(&ilbc_codec->last_tx, + &input->timestamp); + + is_silence = pjmedia_silence_det_detect(ilbc_codec->vad, + (const pj_int16_t*)input->buf, + (input->size >> 1), + NULL); + if (is_silence && + (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || + silence_period < PJMEDIA_CODEC_MAX_SILENCE_PERIOD*8000/1000)) + { + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->buf = NULL; + output->size = 0; + output->timestamp = input->timestamp; + return PJ_SUCCESS; + } else { + ilbc_codec->last_tx = input->timestamp; + } } /* Encode */ @@ -758,7 +757,7 @@ static pj_status_t ilbc_codec_encode(pjmedia_codec *codec, output->size += ilbc_codec->enc.no_of_bytes; #endif - nsamples -= ilbc_codec->enc_samples_per_frame; + nsamples -= ilbc_codec->enc_samples_per_frame; } output->type = PJMEDIA_FRAME_TYPE_AUDIO; @@ -771,9 +770,9 @@ static pj_status_t ilbc_codec_encode(pjmedia_codec *codec, * Decode frame. */ static pj_status_t ilbc_codec_decode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct ilbc_codec *ilbc_codec = (struct ilbc_codec*)codec; #if defined(PJMEDIA_ILBC_CODEC_USE_COREAUDIO)&& PJMEDIA_ILBC_CODEC_USE_COREAUDIO @@ -788,15 +787,15 @@ static pj_status_t ilbc_codec_decode(pjmedia_codec *codec, PJ_ASSERT_RETURN(input && output, PJ_EINVAL); if (output_buf_len < (ilbc_codec->dec_samples_per_frame << 1)) - return PJMEDIA_CODEC_EPCMTOOSHORT; + return PJMEDIA_CODEC_EPCMTOOSHORT; if (input->size != ilbc_codec->dec_frame_size) - return PJMEDIA_CODEC_EFRMINLEN; + return PJMEDIA_CODEC_EFRMINLEN; /* Decode to temporary buffer */ #if defined(PJMEDIA_ILBC_CODEC_USE_COREAUDIO)&& PJMEDIA_ILBC_CODEC_USE_COREAUDIO npackets = input->size / ilbc_codec->dec_frame_size * - ilbc_codec->dec_samples_per_frame; + ilbc_codec->dec_samples_per_frame; theABL.mNumberBuffers = 1; theABL.mBuffers[0].mNumberChannels = 1; @@ -808,18 +807,18 @@ static pj_status_t ilbc_codec_decode(pjmedia_codec *codec, ilbc_codec->dec_buffer_offset = 0; err = AudioConverterFillComplexBuffer(ilbc_codec->dec, decodeDataProc, - ilbc_codec, &npackets, - &theABL, NULL); + ilbc_codec, &npackets, + &theABL, NULL); if (err == noErr) { - output->size = npackets * (ilbc_codec->dec_samples_per_frame << 1); + output->size = npackets * (ilbc_codec->dec_samples_per_frame << 1); } #else iLBC_decode(ilbc_codec->dec_block, (unsigned char*) input->buf, - &ilbc_codec->dec, 1); + &ilbc_codec->dec, 1); /* Convert decodec samples from float to short */ for (i=0; idec_samples_per_frame; ++i) { - ((short*)output->buf)[i] = (short)ilbc_codec->dec_block[i]; + ((short*)output->buf)[i] = (short)ilbc_codec->dec_block[i]; } output->size = (ilbc_codec->dec_samples_per_frame << 1); #endif @@ -835,8 +834,8 @@ static pj_status_t ilbc_codec_decode(pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t ilbc_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { struct ilbc_codec *ilbc_codec = (struct ilbc_codec*)codec; #if defined(PJMEDIA_ILBC_CODEC_USE_COREAUDIO)&& PJMEDIA_ILBC_CODEC_USE_COREAUDIO @@ -851,7 +850,7 @@ static pj_status_t ilbc_codec_recover(pjmedia_codec *codec, PJ_ASSERT_RETURN(output, PJ_EINVAL); if (output_buf_len < (ilbc_codec->dec_samples_per_frame << 1)) - return PJMEDIA_CODEC_EPCMTOOSHORT; + return PJMEDIA_CODEC_EPCMTOOSHORT; /* Decode to temporary buffer */ #if defined(PJMEDIA_ILBC_CODEC_USE_COREAUDIO)&& PJMEDIA_ILBC_CODEC_USE_COREAUDIO @@ -865,23 +864,23 @@ static pj_status_t ilbc_codec_recover(pjmedia_codec *codec, ilbc_codec->dec_total_packets = npackets; ilbc_codec->dec_buffer_offset = 0; if (ilbc_codec->dec_buffer) { - err = AudioConverterFillComplexBuffer(ilbc_codec->dec, decodeDataProc, - ilbc_codec, &npackets, - &theABL, NULL); - if (err == noErr) { - output->size = npackets * - (ilbc_codec->dec_samples_per_frame << 1); - } + err = AudioConverterFillComplexBuffer(ilbc_codec->dec, decodeDataProc, + ilbc_codec, &npackets, + &theABL, NULL); + if (err == noErr) { + output->size = npackets * + (ilbc_codec->dec_samples_per_frame << 1); + } } else { - output->size = npackets * (ilbc_codec->dec_samples_per_frame << 1); - pj_bzero(output->buf, output->size); + output->size = npackets * (ilbc_codec->dec_samples_per_frame << 1); + pj_bzero(output->buf, output->size); } #else iLBC_decode(ilbc_codec->dec_block, NULL, &ilbc_codec->dec, 0); /* Convert decodec samples from float to short */ for (i=0; idec_samples_per_frame; ++i) { - ((short*)output->buf)[i] = (short)ilbc_codec->dec_block[i]; + ((short*)output->buf)[i] = (short)ilbc_codec->dec_block[i]; } output->size = (ilbc_codec->dec_samples_per_frame << 1); #endif @@ -891,4 +890,4 @@ static pj_status_t ilbc_codec_recover(pjmedia_codec *codec, } -#endif /* PJMEDIA_HAS_ILBC_CODEC */ +#endif /* PJMEDIA_HAS_ILBC_CODEC */ diff --git a/pjmedia/src/pjmedia-codec/ipp_codecs.c b/pjmedia/src/pjmedia-codec/ipp_codecs.c index ccedc9249c..e5c484b12c 100644 --- a/pjmedia/src/pjmedia-codec/ipp_codecs.c +++ b/pjmedia/src/pjmedia-codec/ipp_codecs.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -47,44 +46,44 @@ /* Prototypes for IPP codecs factory */ static pj_status_t ipp_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ); + const pjmedia_codec_info *id ); static pj_status_t ipp_default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ); static pj_status_t ipp_enum_codecs( pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t ipp_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t ipp_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for IPP codecs implementation. */ static pj_status_t ipp_codec_init( pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t ipp_codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t ipp_codec_close( pjmedia_codec *codec ); static pj_status_t ipp_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t ipp_codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t ipp_codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t ipp_codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t ipp_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); /* Definition for IPP codecs operations. */ static pjmedia_codec_op ipp_op = @@ -113,33 +112,33 @@ static pjmedia_codec_factory_op ipp_factory_op = /* IPP codecs factory */ static struct ipp_factory { pjmedia_codec_factory base; - pjmedia_endpt *endpt; - pj_pool_t *pool; - pj_mutex_t *mutex; - unsigned g7221_pcm_shift; + pjmedia_endpt *endpt; + pj_pool_t *pool; + pj_mutex_t *mutex; + unsigned g7221_pcm_shift; } ipp_factory; /* IPP codecs private data. */ typedef struct ipp_private { - int codec_idx; /**< Codec index. */ - void *codec_setting; /**< Specific codec setting. */ - pj_pool_t *pool; /**< Pool for each instance. */ + int codec_idx; /**< Codec index. */ + void *codec_setting; /**< Specific codec setting. */ + pj_pool_t *pool; /**< Pool for each instance. */ - USC_Handle enc; /**< Encoder state. */ - USC_Handle dec; /**< Decoder state. */ - USC_CodecInfo *info; /**< Native codec info. */ - pj_uint16_t frame_size; /**< Bitstream frame size. */ + USC_Handle enc; /**< Encoder state. */ + USC_Handle dec; /**< Decoder state. */ + USC_CodecInfo *info; /**< Native codec info. */ + pj_uint16_t frame_size; /**< Bitstream frame size. */ - pj_bool_t plc_enabled; /**< PLC enabled flag. */ - pjmedia_plc *plc; /**< PJMEDIA PLC engine, NULL if - codec has internal PLC. */ + pj_bool_t plc_enabled; /**< PLC enabled flag. */ + pjmedia_plc *plc; /**< PJMEDIA PLC engine, NULL if + codec has internal PLC. */ - pj_bool_t vad_enabled; /**< VAD enabled flag. */ - pjmedia_silence_det *vad; /**< PJMEDIA VAD engine, NULL if - codec has internal VAD. */ - pj_timestamp last_tx; /**< Timestamp of last transmit.*/ + pj_bool_t vad_enabled; /**< VAD enabled flag. */ + pjmedia_silence_det *vad; /**< PJMEDIA VAD engine, NULL if + codec has internal VAD. */ + pj_timestamp last_tx; /**< Timestamp of last transmit.*/ - unsigned g7221_pcm_shift; /**< G722.1 PCM level adjustment*/ + unsigned g7221_pcm_shift; /**< G722.1 PCM level adjustment*/ } ipp_private_t; @@ -165,8 +164,8 @@ extern USC_Fxns USC_AMRWBE_Fxns; * the default behaviour is unapplicable. */ typedef void (*predecode_cb)(ipp_private_t *codec_data, - const pjmedia_frame *rtp_frame, - USC_Bitstream *usc_frame); + const pjmedia_frame *rtp_frame, + USC_Bitstream *usc_frame); /* Parse frames from a packet. Default behaviour of frame parsing is * just separating frames based on calculating frame length derived @@ -174,8 +173,8 @@ typedef void (*predecode_cb)(ipp_private_t *codec_data, * unapplicable. */ typedef pj_status_t (*parse_cb)(ipp_private_t *codec_data, void *pkt, - pj_size_t pkt_size, const pj_timestamp *ts, - unsigned *frame_cnt, pjmedia_frame frames[]); + pj_size_t pkt_size, const pj_timestamp *ts, + unsigned *frame_cnt, pjmedia_frame frames[]); /* Pack frames into a packet. Default behaviour of packing frames is * just stacking the frames with octet aligned without adding any @@ -183,147 +182,147 @@ typedef pj_status_t (*parse_cb)(ipp_private_t *codec_data, void *pkt, * unapplicable. */ typedef pj_status_t (*pack_cb)(ipp_private_t *codec_data, void *pkt, - pj_size_t *pkt_size, pj_size_t max_pkt_size); + pj_size_t *pkt_size, pj_size_t max_pkt_size); /* Custom callback implementations. */ static void predecode_g723( ipp_private_t *codec_data, - const pjmedia_frame *rtp_frame, - USC_Bitstream *usc_frame); + const pjmedia_frame *rtp_frame, + USC_Bitstream *usc_frame); static pj_status_t parse_g723( ipp_private_t *codec_data, void *pkt, - pj_size_t pkt_size, const pj_timestamp *ts, - unsigned *frame_cnt, pjmedia_frame frames[]); + pj_size_t pkt_size, const pj_timestamp *ts, + unsigned *frame_cnt, pjmedia_frame frames[]); static void predecode_g729( ipp_private_t *codec_data, - const pjmedia_frame *rtp_frame, - USC_Bitstream *usc_frame); + const pjmedia_frame *rtp_frame, + USC_Bitstream *usc_frame); static void predecode_amr( ipp_private_t *codec_data, - const pjmedia_frame *rtp_frame, - USC_Bitstream *usc_frame); + const pjmedia_frame *rtp_frame, + USC_Bitstream *usc_frame); static pj_status_t parse_amr( ipp_private_t *codec_data, void *pkt, - pj_size_t pkt_size, const pj_timestamp *ts, - unsigned *frame_cnt, pjmedia_frame frames[]); + pj_size_t pkt_size, const pj_timestamp *ts, + unsigned *frame_cnt, pjmedia_frame frames[]); static pj_status_t pack_amr( ipp_private_t *codec_data, void *pkt, - pj_size_t *pkt_size, pj_size_t max_pkt_size); + pj_size_t *pkt_size, pj_size_t max_pkt_size); static void predecode_g7221( ipp_private_t *codec_data, - const pjmedia_frame *rtp_frame, - USC_Bitstream *usc_frame); + const pjmedia_frame *rtp_frame, + USC_Bitstream *usc_frame); static pj_status_t pack_g7221( ipp_private_t *codec_data, void *pkt, - pj_size_t *pkt_size, pj_size_t max_pkt_size); + pj_size_t *pkt_size, pj_size_t max_pkt_size); /* IPP codec implementation descriptions. */ static struct ipp_codec { - int enabled; /* Is this codec enabled? */ - const char *name; /* Codec name. */ - pj_uint8_t pt; /* Payload type. */ - USC_Fxns *fxns; /* USC callback functions. */ - unsigned clock_rate; /* Codec's clock rate. */ - unsigned channel_count; /* Codec's channel count. */ - unsigned samples_per_frame; /* Codec's samples count. */ - - unsigned def_bitrate; /* Default bitrate of this codec. */ - unsigned max_bitrate; /* Maximum bitrate of this codec. */ - pj_uint8_t frm_per_pkt; /* Default num of frames per packet.*/ - int has_native_vad; /* Codec has internal VAD? */ - int has_native_plc; /* Codec has internal PLC? */ - - predecode_cb predecode; /* Callback to translate RTP frame - into USC frame. */ - parse_cb parse; /* Callback to parse bitstream. */ - pack_cb pack; /* Callback to pack bitstream. */ - - pjmedia_codec_fmtp dec_fmtp; /* Decoder's fmtp params. */ + int enabled; /* Is this codec enabled? */ + const char *name; /* Codec name. */ + pj_uint8_t pt; /* Payload type. */ + USC_Fxns *fxns; /* USC callback functions. */ + unsigned clock_rate; /* Codec's clock rate. */ + unsigned channel_count; /* Codec's channel count. */ + unsigned samples_per_frame; /* Codec's samples count. */ + + unsigned def_bitrate; /* Default bitrate of this codec. */ + unsigned max_bitrate; /* Maximum bitrate of this codec. */ + pj_uint8_t frm_per_pkt; /* Default num of frames per packet.*/ + int has_native_vad; /* Codec has internal VAD? */ + int has_native_plc; /* Codec has internal PLC? */ + + predecode_cb predecode; /* Callback to translate RTP frame + into USC frame. */ + parse_cb parse; /* Callback to parse bitstream. */ + pack_cb pack; /* Callback to pack bitstream. */ + + pjmedia_codec_fmtp dec_fmtp; /* Decoder's fmtp params. */ } ipp_codec[] = { # if PJMEDIA_HAS_INTEL_IPP_CODEC_AMR - {1, "AMR", PJMEDIA_RTP_PT_AMR, &USC_GSMAMR_Fxns, 8000, 1, 160, - 7400, 12200, 2, 1, 1, - &predecode_amr, &parse_amr, &pack_amr, - {1, {{{"octet-align", 11}, {"1", 1}}} } + {1, "AMR", PJMEDIA_RTP_PT_AMR, &USC_GSMAMR_Fxns, 8000, 1, 160, + 7400, 12200, 2, 1, 1, + &predecode_amr, &parse_amr, &pack_amr, + {1, {{{"octet-align", 11}, {"1", 1}}} } }, # endif # if PJMEDIA_HAS_INTEL_IPP_CODEC_AMRWB {1, "AMR-WB", PJMEDIA_RTP_PT_AMRWB, &USC_AMRWB_Fxns, 16000, 1, 320, - 15850, 23850, 2, 1, 1, - &predecode_amr, &parse_amr, &pack_amr, - {1, {{{"octet-align", 11}, {"1", 1}}} } + 15850, 23850, 2, 1, 1, + &predecode_amr, &parse_amr, &pack_amr, + {1, {{{"octet-align", 11}, {"1", 1}}} } }, # endif # if PJMEDIA_HAS_INTEL_IPP_CODEC_G729 -# if defined(PJ_HAS_FLOATING_POINT) && (PJ_HAS_FLOATING_POINT != 0) - {1, "G729", PJMEDIA_RTP_PT_G729, &USC_G729AFP_Fxns, 8000, 1, 80, - 8000, 11800, 2, 1, 1, - &predecode_g729, NULL, NULL +# if defined(PJ_HAS_FLOATING_POINT) && (PJ_HAS_FLOATING_POINT != 0) + {1, "G729", PJMEDIA_RTP_PT_G729, &USC_G729AFP_Fxns, 8000, 1, 80, + 8000, 11800, 2, 1, 1, + &predecode_g729, NULL, NULL }, -# else - {1, "G729", PJMEDIA_RTP_PT_G729, &USC_G729I_Fxns, 8000, 1, 80, - 8000, 11800, 2, 1, 1, - &predecode_g729, NULL, NULL +# else + {1, "G729", PJMEDIA_RTP_PT_G729, &USC_G729I_Fxns, 8000, 1, 80, + 8000, 11800, 2, 1, 1, + &predecode_g729, NULL, NULL }, -# endif +# endif # endif # if PJMEDIA_HAS_INTEL_IPP_CODEC_G723_1 /* This is actually G.723.1 */ - {1, "G723", PJMEDIA_RTP_PT_G723, &USC_G723_Fxns, 8000, 1, 240, - 6300, 6300, 1, 1, 1, - &predecode_g723, &parse_g723, NULL + {1, "G723", PJMEDIA_RTP_PT_G723, &USC_G723_Fxns, 8000, 1, 240, + 6300, 6300, 1, 1, 1, + &predecode_g723, &parse_g723, NULL }, # endif # if PJMEDIA_HAS_INTEL_IPP_CODEC_G726 - {0, "G726-16", PJMEDIA_RTP_PT_G726_16, &USC_G726_Fxns, 8000, 1, 80, - 16000, 16000, 2, 0, 0, - NULL, NULL, NULL + {0, "G726-16", PJMEDIA_RTP_PT_G726_16, &USC_G726_Fxns, 8000, 1, 80, + 16000, 16000, 2, 0, 0, + NULL, NULL, NULL }, - {0, "G726-24", PJMEDIA_RTP_PT_G726_24, &USC_G726_Fxns, 8000, 1, 80, - 24000, 24000, 2, 0, 0, - NULL, NULL, NULL + {0, "G726-24", PJMEDIA_RTP_PT_G726_24, &USC_G726_Fxns, 8000, 1, 80, + 24000, 24000, 2, 0, 0, + NULL, NULL, NULL }, - {1, "G726-32", PJMEDIA_RTP_PT_G726_32, &USC_G726_Fxns, 8000, 1, 80, - 32000, 32000, 2, 0, 0, - NULL, NULL, NULL + {1, "G726-32", PJMEDIA_RTP_PT_G726_32, &USC_G726_Fxns, 8000, 1, 80, + 32000, 32000, 2, 0, 0, + NULL, NULL, NULL }, - {0, "G726-40", PJMEDIA_RTP_PT_G726_40, &USC_G726_Fxns, 8000, 1, 80, - 40000, 40000, 2, 0, 0, - NULL, NULL, NULL + {0, "G726-40", PJMEDIA_RTP_PT_G726_40, &USC_G726_Fxns, 8000, 1, 80, + 40000, 40000, 2, 0, 0, + NULL, NULL, NULL }, /* Old definition of G726-32 */ - {1, "G721", PJMEDIA_RTP_PT_G721, &USC_G726_Fxns, 8000, 1, 80, - 32000, 32000, 2, 0, 0, - NULL, NULL, NULL + {1, "G721", PJMEDIA_RTP_PT_G721, &USC_G726_Fxns, 8000, 1, 80, + 32000, 32000, 2, 0, 0, + NULL, NULL, NULL }, # endif # if PJMEDIA_HAS_INTEL_IPP_CODEC_G728 - {1, "G728", PJMEDIA_RTP_PT_G728, &USC_G728_Fxns, 8000, 1, 80, - 16000, 16000, 2, 0, 1, - NULL, NULL, NULL + {1, "G728", PJMEDIA_RTP_PT_G728, &USC_G728_Fxns, 8000, 1, 80, + 16000, 16000, 2, 0, 1, + NULL, NULL, NULL }, # endif # if PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1 - {0, "G7221", PJMEDIA_RTP_PT_G722_1_16, &USC_G722_Fxns, 16000, 1, 320, - 16000, 16000, 1, 0, 1, - predecode_g7221, NULL, pack_g7221, - {1, {{{"bitrate", 7}, {"16000", 5}}} } + {0, "G7221", PJMEDIA_RTP_PT_G722_1_16, &USC_G722_Fxns, 16000, 1, 320, + 16000, 16000, 1, 0, 1, + predecode_g7221, NULL, pack_g7221, + {1, {{{"bitrate", 7}, {"16000", 5}}} } }, - {1, "G7221", PJMEDIA_RTP_PT_G722_1_24, &USC_G722_Fxns, 16000, 1, 320, - 24000, 24000, 1, 0, 1, - predecode_g7221, NULL, pack_g7221, - {1, {{{"bitrate", 7}, {"24000", 5}}} } + {1, "G7221", PJMEDIA_RTP_PT_G722_1_24, &USC_G722_Fxns, 16000, 1, 320, + 24000, 24000, 1, 0, 1, + predecode_g7221, NULL, pack_g7221, + {1, {{{"bitrate", 7}, {"24000", 5}}} } }, - {1, "G7221", PJMEDIA_RTP_PT_G722_1_32, &USC_G722_Fxns, 16000, 1, 320, - 32000, 32000, 1, 0, 1, - predecode_g7221, NULL, pack_g7221, - {1, {{{"bitrate", 7}, {"32000", 5}}} } + {1, "G7221", PJMEDIA_RTP_PT_G722_1_32, &USC_G722_Fxns, 16000, 1, 320, + 32000, 32000, 1, 0, 1, + predecode_g7221, NULL, pack_g7221, + {1, {{{"bitrate", 7}, {"32000", 5}}} } }, # endif }; @@ -332,34 +331,34 @@ ipp_codec[] = #if PJMEDIA_HAS_INTEL_IPP_CODEC_G729 static void predecode_g729( ipp_private_t *codec_data, - const pjmedia_frame *rtp_frame, - USC_Bitstream *usc_frame) + const pjmedia_frame *rtp_frame, + USC_Bitstream *usc_frame) { switch (rtp_frame->size) { case 2: - /* SID */ - usc_frame->frametype = 1; - usc_frame->bitrate = codec_data->info->params.modes.bitrate; - break; + /* SID */ + usc_frame->frametype = 1; + usc_frame->bitrate = codec_data->info->params.modes.bitrate; + break; case 8: - /* G729D */ - usc_frame->frametype = 2; - usc_frame->bitrate = 6400; - break; + /* G729D */ + usc_frame->frametype = 2; + usc_frame->bitrate = 6400; + break; case 10: - /* G729 */ - usc_frame->frametype = 3; - usc_frame->bitrate = 8000; - break; + /* G729 */ + usc_frame->frametype = 3; + usc_frame->bitrate = 8000; + break; case 15: - /* G729E */ - usc_frame->frametype = 4; - usc_frame->bitrate = 11800; - break; + /* G729E */ + usc_frame->frametype = 4; + usc_frame->bitrate = 11800; + break; default: - usc_frame->frametype = 0; - usc_frame->bitrate = 0; - break; + usc_frame->frametype = 0; + usc_frame->bitrate = 0; + break; } usc_frame->pBuffer = rtp_frame->buf; @@ -372,8 +371,8 @@ static void predecode_g729( ipp_private_t *codec_data, #if PJMEDIA_HAS_INTEL_IPP_CODEC_G723_1 static void predecode_g723( ipp_private_t *codec_data, - const pjmedia_frame *rtp_frame, - USC_Bitstream *usc_frame) + const pjmedia_frame *rtp_frame, + USC_Bitstream *usc_frame) { int i, HDR = 0; pj_uint8_t *f = (pj_uint8_t*)rtp_frame->buf; @@ -381,9 +380,9 @@ static void predecode_g723( ipp_private_t *codec_data, PJ_UNUSED_ARG(codec_data); for (i = 0; i < 2; ++i){ - int tmp; - tmp = (f[0] >> (i & 0x7)) & 1; - HDR += tmp << i ; + int tmp; + tmp = (f[0] >> (i & 0x7)) & 1; + HDR += tmp << i ; } usc_frame->pBuffer = rtp_frame->buf; @@ -393,44 +392,44 @@ static void predecode_g723( ipp_private_t *codec_data, } static pj_status_t parse_g723(ipp_private_t *codec_data, void *pkt, - pj_size_t pkt_size, const pj_timestamp *ts, - unsigned *frame_cnt, pjmedia_frame frames[]) + pj_size_t pkt_size, const pj_timestamp *ts, + unsigned *frame_cnt, pjmedia_frame frames[]) { unsigned count = 0; pj_uint8_t *f = (pj_uint8_t*)pkt; while (pkt_size && count < *frame_cnt) { - int framesize, i, j; - int HDR = 0; - - for (i = 0; i < 2; ++i){ - j = (f[0] >> (i & 0x7)) & 1; - HDR += j << i ; - } - - if (HDR == 0) - framesize = 24; - else if (HDR == 1) - framesize = 20; - else if (HDR == 2) - framesize = 4; - else if (HDR == 3) - framesize = 1; - else { - pj_assert(!"Unknown G723.1 frametype, packet may be corrupted!"); - return PJMEDIA_CODEC_EINMODE; - } - - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = f; - frames[count].size = framesize; - frames[count].timestamp.u64 = ts->u64 + count * - ipp_codec[codec_data->codec_idx].samples_per_frame; - - f += framesize; - pkt_size -= framesize; - - ++count; + int framesize, i, j; + int HDR = 0; + + for (i = 0; i < 2; ++i){ + j = (f[0] >> (i & 0x7)) & 1; + HDR += j << i ; + } + + if (HDR == 0) + framesize = 24; + else if (HDR == 1) + framesize = 20; + else if (HDR == 2) + framesize = 4; + else if (HDR == 3) + framesize = 1; + else { + pj_assert(!"Unknown G723.1 frametype, packet may be corrupted!"); + return PJMEDIA_CODEC_EINMODE; + } + + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = f; + frames[count].size = framesize; + frames[count].timestamp.u64 = ts->u64 + count * + ipp_codec[codec_data->codec_idx].samples_per_frame; + + f += framesize; + pkt_size -= framesize; + + ++count; } *frame_cnt = count; @@ -458,8 +457,8 @@ typedef struct amr_settings_t { * - set the appropriate value of usc_frame. */ static void predecode_amr( ipp_private_t *codec_data, - const pjmedia_frame *rtp_frame, - USC_Bitstream *usc_frame) + const pjmedia_frame *rtp_frame, + USC_Bitstream *usc_frame) { pjmedia_frame frame; pjmedia_codec_amr_bit_info *info; @@ -474,35 +473,35 @@ static void predecode_amr( ipp_private_t *codec_data, usc_frame->pBuffer = frame.buf; usc_frame->nbytes = frame.size; if (info->mode != -1) { - usc_frame->bitrate = setting->amr_nb? - pjmedia_codec_amrnb_bitrates[info->mode]: - pjmedia_codec_amrwb_bitrates[info->mode]; + usc_frame->bitrate = setting->amr_nb? + pjmedia_codec_amrnb_bitrates[info->mode]: + pjmedia_codec_amrwb_bitrates[info->mode]; } else { - usc_frame->bitrate = 0; + usc_frame->bitrate = 0; } if (frame.size > 5) { - /* Speech */ - if (info->good_quality) - usc_frame->frametype = 0; - else - usc_frame->frametype = setting->amr_nb ? 5 : 6; + /* Speech */ + if (info->good_quality) + usc_frame->frametype = 0; + else + usc_frame->frametype = setting->amr_nb ? 5 : 6; } else if (frame.size == 5) { - /* SID */ - if (info->good_quality) { - usc_frame->frametype = info->STI? 2 : 1; - } else { - usc_frame->frametype = setting->amr_nb ? 6 : 7; - } + /* SID */ + if (info->good_quality) { + usc_frame->frametype = info->STI? 2 : 1; + } else { + usc_frame->frametype = setting->amr_nb ? 6 : 7; + } } else { - /* no data */ - usc_frame->frametype = 3; + /* no data */ + usc_frame->frametype = 3; } } /* Pack AMR payload */ static pj_status_t pack_amr(ipp_private_t *codec_data, void *pkt, - pj_size_t *pkt_size, pj_size_t max_pkt_size) + pj_size_t *pkt_size, pj_size_t max_pkt_size) { enum {MAX_FRAMES_PER_PACKET = PJMEDIA_MAX_FRAME_DURATION_MS / 20}; @@ -516,7 +515,7 @@ static pj_status_t pack_amr(ipp_private_t *codec_data, void *pkt, setting = &((amr_settings_t*)codec_data->codec_setting)->enc_setting; framelen_tbl = setting->amr_nb? pjmedia_codec_amrnb_framelen: - pjmedia_codec_amrwb_framelen; + pjmedia_codec_amrwb_framelen; SID_FT = (pj_uint8_t)(setting->amr_nb? 8 : 9); @@ -526,28 +525,28 @@ static pj_status_t pack_amr(ipp_private_t *codec_data, void *pkt, /* Get frames */ for (;;) { - pj_bool_t eof; - pj_uint16_t info_; + pj_bool_t eof; + pj_uint16_t info_; - info_ = *((pj_uint16_t*)r); - eof = ((info_ & 0x40) != 0); + info_ = *((pj_uint16_t*)r); + eof = ((info_ & 0x40) != 0); - info = (pjmedia_codec_amr_bit_info*) &frames[nframes].bit_info; - pj_bzero(info, sizeof(*info)); - info->frame_type = (pj_uint8_t)(info_ & 0x0F); - info->good_quality = (pj_uint8_t)((info_ & 0x80) == 0); - info->mode = (pj_int8_t) ((info_ >> 8) & 0x0F); - info->STI = (pj_uint8_t)((info_ >> 5) & 1); + info = (pjmedia_codec_amr_bit_info*) &frames[nframes].bit_info; + pj_bzero(info, sizeof(*info)); + info->frame_type = (pj_uint8_t)(info_ & 0x0F); + info->good_quality = (pj_uint8_t)((info_ & 0x80) == 0); + info->mode = (pj_int8_t) ((info_ >> 8) & 0x0F); + info->STI = (pj_uint8_t)((info_ >> 5) & 1); - frames[nframes].buf = r + 2; - frames[nframes].size = info->frame_type <= SID_FT ? - framelen_tbl[info->frame_type] : 0; + frames[nframes].buf = r + 2; + frames[nframes].size = info->frame_type <= SID_FT ? + framelen_tbl[info->frame_type] : 0; - r += frames[nframes].size + 2; + r += frames[nframes].size + 2; - /* Last frame */ - if (++nframes >= MAX_FRAMES_PER_PACKET || eof) - break; + /* Last frame */ + if (++nframes >= MAX_FRAMES_PER_PACKET || eof) + break; } /* Pack */ @@ -558,8 +557,8 @@ static pj_status_t pack_amr(ipp_private_t *codec_data, void *pkt, /* Parse AMR payload into frames. */ static pj_status_t parse_amr(ipp_private_t *codec_data, void *pkt, - pj_size_t pkt_size, const pj_timestamp *ts, - unsigned *frame_cnt, pjmedia_frame frames[]) + pj_size_t pkt_size, const pj_timestamp *ts, + unsigned *frame_cnt, pjmedia_frame frames[]) { amr_settings_t* s = (amr_settings_t*)codec_data->codec_setting; pjmedia_codec_amr_pack_setting *setting; @@ -569,27 +568,27 @@ static pj_status_t parse_amr(ipp_private_t *codec_data, void *pkt, setting = &s->dec_setting; status = pjmedia_codec_amr_parse(pkt, pkt_size, ts, setting, frames, - frame_cnt, &cmr); + frame_cnt, &cmr); if (status != PJ_SUCCESS) - return status; + return status; /* Check Change Mode Request. */ if (((setting->amr_nb && cmr <= 7) || (!setting->amr_nb && cmr <= 8)) && - s->enc_mode != cmr) + s->enc_mode != cmr) { - struct ipp_codec *ippc = &ipp_codec[codec_data->codec_idx]; - - s->enc_mode = cmr; - codec_data->info->params.modes.bitrate = s->enc_setting.amr_nb? - pjmedia_codec_amrnb_bitrates[s->enc_mode] : - pjmedia_codec_amrwb_bitrates[s->enc_mode]; - ippc->fxns->std.Control(&codec_data->info->params.modes, - codec_data->enc); - - PJ_LOG(4,(THIS_FILE, "AMR%s switched encoding mode to: %d (%dbps)", - (s->enc_setting.amr_nb?"":"-WB"), - s->enc_mode, - codec_data->info->params.modes.bitrate)); + struct ipp_codec *ippc = &ipp_codec[codec_data->codec_idx]; + + s->enc_mode = cmr; + codec_data->info->params.modes.bitrate = s->enc_setting.amr_nb? + pjmedia_codec_amrnb_bitrates[s->enc_mode] : + pjmedia_codec_amrwb_bitrates[s->enc_mode]; + ippc->fxns->std.Control(&codec_data->info->params.modes, + codec_data->enc); + + PJ_LOG(4,(THIS_FILE, "AMR%s switched encoding mode to: %d (%dbps)", + (s->enc_setting.amr_nb?"":"-WB"), + s->enc_mode, + codec_data->info->params.modes.bitrate)); } return PJ_SUCCESS; @@ -601,8 +600,8 @@ static pj_status_t parse_amr(ipp_private_t *codec_data, void *pkt, #if PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1 static void predecode_g7221( ipp_private_t *codec_data, - const pjmedia_frame *rtp_frame, - USC_Bitstream *usc_frame) + const pjmedia_frame *rtp_frame, + USC_Bitstream *usc_frame) { usc_frame->pBuffer = (char*)rtp_frame->buf; usc_frame->nbytes = rtp_frame->size; @@ -611,34 +610,34 @@ static void predecode_g7221( ipp_private_t *codec_data, #if defined(PJ_IS_LITTLE_ENDIAN) && PJ_IS_LITTLE_ENDIAN!=0 { - pj_uint16_t *p, *p_end; - - p = (pj_uint16_t*)rtp_frame->buf; - p_end = p + rtp_frame->size/2; - while (p < p_end) { - *p = pj_ntohs(*p); - ++p; - } + pj_uint16_t *p, *p_end; + + p = (pj_uint16_t*)rtp_frame->buf; + p_end = p + rtp_frame->size/2; + while (p < p_end) { + *p = pj_ntohs(*p); + ++p; + } } #endif } static pj_status_t pack_g7221( ipp_private_t *codec_data, void *pkt, - pj_size_t *pkt_size, pj_size_t max_pkt_size) + pj_size_t *pkt_size, pj_size_t max_pkt_size) { PJ_UNUSED_ARG(codec_data); PJ_UNUSED_ARG(max_pkt_size); #if defined(PJ_IS_LITTLE_ENDIAN) && PJ_IS_LITTLE_ENDIAN!=0 { - pj_uint16_t *p, *p_end; - - p = (pj_uint16_t*)pkt; - p_end = p + *pkt_size/2; - while (p < p_end) { - *p = pj_htons(*p); - ++p; - } + pj_uint16_t *p, *p_end; + + p = (pj_uint16_t*)pkt; + p_end = p + *pkt_size/2; + while (p < p_end) { + *p = pj_htons(*p); + ++p; + } } #else PJ_UNUSED_ARG(pkt); @@ -673,8 +672,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_ipp_init( pjmedia_endpt *endpt ) pj_status_t status; if (ipp_factory.pool != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } /* Create IPP codec factory. */ @@ -685,47 +684,47 @@ PJ_DEF(pj_status_t) pjmedia_codec_ipp_init( pjmedia_endpt *endpt ) ipp_factory.pool = pjmedia_endpt_create_pool(endpt, "IPP codecs", 4000, 4000); if (!ipp_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create mutex. */ status = pj_mutex_create_simple(ipp_factory.pool, "IPP codecs", - &ipp_factory.mutex); + &ipp_factory.mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - status = PJ_EINVALIDOP; - goto on_error; + status = PJ_EINVALIDOP; + goto on_error; } /* Register format match callback. */ #if PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1 pj_cstr(&codec_name, "G7221"); status = pjmedia_sdp_neg_register_fmt_match_cb( - &codec_name, - &pjmedia_codec_g7221_match_sdp); + &codec_name, + &pjmedia_codec_g7221_match_sdp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #endif #if PJMEDIA_HAS_INTEL_IPP_CODEC_AMR pj_cstr(&codec_name, "AMR"); status = pjmedia_sdp_neg_register_fmt_match_cb( - &codec_name, - &pjmedia_codec_amr_match_sdp); + &codec_name, + &pjmedia_codec_amr_match_sdp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #endif #if PJMEDIA_HAS_INTEL_IPP_CODEC_AMRWB pj_cstr(&codec_name, "AMR-WB"); status = pjmedia_sdp_neg_register_fmt_match_cb( - &codec_name, - &pjmedia_codec_amr_match_sdp); + &codec_name, + &pjmedia_codec_amr_match_sdp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #endif /* Suppress compile warning */ @@ -733,9 +732,9 @@ PJ_DEF(pj_status_t) pjmedia_codec_ipp_init( pjmedia_endpt *endpt ) /* Register codec factory to endpoint. */ status = pjmedia_codec_mgr_register_factory(codec_mgr, - &ipp_factory.base); + &ipp_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Done. */ return PJ_SUCCESS; @@ -755,8 +754,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_ipp_deinit(void) pj_status_t status; if (ipp_factory.pool == NULL) { - /* Already deinitialized */ - return PJ_SUCCESS; + /* Already deinitialized */ + return PJ_SUCCESS; } pj_mutex_lock(ipp_factory.mutex); @@ -764,15 +763,15 @@ PJ_DEF(pj_status_t) pjmedia_codec_ipp_deinit(void) /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(ipp_factory.endpt); if (!codec_mgr) { - pj_pool_release(ipp_factory.pool); - ipp_factory.pool = NULL; - pj_mutex_unlock(ipp_factory.mutex); - return PJ_EINVALIDOP; + pj_pool_release(ipp_factory.pool); + ipp_factory.pool = NULL; + pj_mutex_unlock(ipp_factory.mutex); + return PJ_EINVALIDOP; } /* Unregister IPP codecs factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &ipp_factory.base); + &ipp_factory.base); /* Destroy mutex. */ pj_mutex_unlock(ipp_factory.mutex); @@ -791,7 +790,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_ipp_deinit(void) * Check if factory can allocate the specified codec. */ static pj_status_t ipp_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *info ) + const pjmedia_codec_info *info ) { unsigned i; @@ -799,17 +798,17 @@ static pj_status_t ipp_test_alloc( pjmedia_codec_factory *factory, /* Type MUST be audio. */ if (info->type != PJMEDIA_TYPE_AUDIO) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; for (i = 0; i < PJ_ARRAY_SIZE(ipp_codec); ++i) { - pj_str_t name = pj_str((char*)ipp_codec[i].name); - if ((pj_stricmp(&info->encoding_name, &name) == 0) && - (info->clock_rate == (unsigned)ipp_codec[i].clock_rate) && - (info->channel_cnt == (unsigned)ipp_codec[i].channel_count) && - (ipp_codec[i].enabled)) - { - return PJ_SUCCESS; - } + pj_str_t name = pj_str((char*)ipp_codec[i].name); + if ((pj_stricmp(&info->encoding_name, &name) == 0) && + (info->clock_rate == (unsigned)ipp_codec[i].clock_rate) && + (info->channel_cnt == (unsigned)ipp_codec[i].channel_count) && + (ipp_codec[i].enabled)) + { + return PJ_SUCCESS; + } } /* Unsupported, or mode is disabled. */ @@ -820,8 +819,8 @@ static pj_status_t ipp_test_alloc( pjmedia_codec_factory *factory, * Generate default attribute. */ static pj_status_t ipp_default_attr (pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ) { unsigned i; @@ -830,44 +829,44 @@ static pj_status_t ipp_default_attr (pjmedia_codec_factory *factory, pj_bzero(attr, sizeof(pjmedia_codec_param)); for (i = 0; i < PJ_ARRAY_SIZE(ipp_codec); ++i) { - pj_str_t name = pj_str((char*)ipp_codec[i].name); - if ((pj_stricmp(&id->encoding_name, &name) == 0) && - (id->clock_rate == (unsigned)ipp_codec[i].clock_rate) && - (id->channel_cnt == (unsigned)ipp_codec[i].channel_count) && - (id->pt == (unsigned)ipp_codec[i].pt)) - { - attr->info.pt = (pj_uint8_t)id->pt; - attr->info.channel_cnt = ipp_codec[i].channel_count; - attr->info.clock_rate = ipp_codec[i].clock_rate; - attr->info.avg_bps = ipp_codec[i].def_bitrate; - attr->info.max_bps = ipp_codec[i].max_bitrate; - attr->info.pcm_bits_per_sample = 16; - attr->info.frm_ptime = (pj_uint16_t) - (ipp_codec[i].samples_per_frame * 1000 / - ipp_codec[i].channel_count / - ipp_codec[i].clock_rate); - attr->setting.frm_per_pkt = ipp_codec[i].frm_per_pkt; - - /* Default flags. */ - attr->setting.plc = 1; - attr->setting.penh= 0; - attr->setting.vad = 1; - attr->setting.cng = attr->setting.vad; - attr->setting.dec_fmtp = ipp_codec[i].dec_fmtp; - - if (attr->setting.vad == 0) { + pj_str_t name = pj_str((char*)ipp_codec[i].name); + if ((pj_stricmp(&id->encoding_name, &name) == 0) && + (id->clock_rate == (unsigned)ipp_codec[i].clock_rate) && + (id->channel_cnt == (unsigned)ipp_codec[i].channel_count) && + (id->pt == (unsigned)ipp_codec[i].pt)) + { + attr->info.pt = (pj_uint8_t)id->pt; + attr->info.channel_cnt = ipp_codec[i].channel_count; + attr->info.clock_rate = ipp_codec[i].clock_rate; + attr->info.avg_bps = ipp_codec[i].def_bitrate; + attr->info.max_bps = ipp_codec[i].max_bitrate; + attr->info.pcm_bits_per_sample = 16; + attr->info.frm_ptime = (pj_uint16_t) + (ipp_codec[i].samples_per_frame * 1000 / + ipp_codec[i].channel_count / + ipp_codec[i].clock_rate); + attr->setting.frm_per_pkt = ipp_codec[i].frm_per_pkt; + + /* Default flags. */ + attr->setting.plc = 1; + attr->setting.penh= 0; + attr->setting.vad = 1; + attr->setting.cng = attr->setting.vad; + attr->setting.dec_fmtp = ipp_codec[i].dec_fmtp; + + if (attr->setting.vad == 0) { #if PJMEDIA_HAS_INTEL_IPP_CODEC_G729 - if (id->pt == PJMEDIA_RTP_PT_G729) { - /* Signal G729 Annex B is being disabled */ - attr->setting.dec_fmtp.cnt = 1; - pj_strset2(&attr->setting.dec_fmtp.param[0].name, "annexb"); - pj_strset2(&attr->setting.dec_fmtp.param[0].val, "no"); - } + if (id->pt == PJMEDIA_RTP_PT_G729) { + /* Signal G729 Annex B is being disabled */ + attr->setting.dec_fmtp.cnt = 1; + pj_strset2(&attr->setting.dec_fmtp.param[0].name, "annexb"); + pj_strset2(&attr->setting.dec_fmtp.param[0].val, "no"); + } #endif - } + } - return PJ_SUCCESS; - } + return PJ_SUCCESS; + } } return PJMEDIA_CODEC_EUNSUP; @@ -877,8 +876,8 @@ static pj_status_t ipp_default_attr (pjmedia_codec_factory *factory, * Enum codecs supported by this factory. */ static pj_status_t ipp_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]) + unsigned *count, + pjmedia_codec_info codecs[]) { unsigned max; unsigned i; @@ -890,17 +889,17 @@ static pj_status_t ipp_enum_codecs(pjmedia_codec_factory *factory, for (i = 0, *count = 0; i < PJ_ARRAY_SIZE(ipp_codec) && *count < max; ++i) { - if (!ipp_codec[i].enabled) - continue; + if (!ipp_codec[i].enabled) + continue; - pj_bzero(&codecs[*count], sizeof(pjmedia_codec_info)); - codecs[*count].encoding_name = pj_str((char*)ipp_codec[i].name); - codecs[*count].pt = ipp_codec[i].pt; - codecs[*count].type = PJMEDIA_TYPE_AUDIO; - codecs[*count].clock_rate = ipp_codec[i].clock_rate; - codecs[*count].channel_cnt = ipp_codec[i].channel_count; + pj_bzero(&codecs[*count], sizeof(pjmedia_codec_info)); + codecs[*count].encoding_name = pj_str((char*)ipp_codec[i].name); + codecs[*count].pt = ipp_codec[i].pt; + codecs[*count].type = PJMEDIA_TYPE_AUDIO; + codecs[*count].clock_rate = ipp_codec[i].clock_rate; + codecs[*count].channel_cnt = ipp_codec[i].channel_count; - ++*count; + ++*count; } return PJ_SUCCESS; @@ -910,8 +909,8 @@ static pj_status_t ipp_enum_codecs(pjmedia_codec_factory *factory, * Allocate a new codec instance. */ static pj_status_t ipp_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { ipp_private_t *codec_data; pjmedia_codec *codec; @@ -927,20 +926,20 @@ static pj_status_t ipp_alloc_codec( pjmedia_codec_factory *factory, /* Find codec's index */ idx = -1; for (i = 0; i < PJ_ARRAY_SIZE(ipp_codec); ++i) { - pj_str_t name = pj_str((char*)ipp_codec[i].name); - if ((pj_stricmp(&id->encoding_name, &name) == 0) && - (id->clock_rate == (unsigned)ipp_codec[i].clock_rate) && - (id->channel_cnt == (unsigned)ipp_codec[i].channel_count) && - (ipp_codec[i].enabled)) - { - idx = i; - break; - } + pj_str_t name = pj_str((char*)ipp_codec[i].name); + if ((pj_stricmp(&id->encoding_name, &name) == 0) && + (id->clock_rate == (unsigned)ipp_codec[i].clock_rate) && + (id->channel_cnt == (unsigned)ipp_codec[i].channel_count) && + (ipp_codec[i].enabled)) + { + idx = i; + break; + } } if (idx == -1) { - *p_codec = NULL; - pj_mutex_unlock(ipp_factory.mutex); - return PJMEDIA_CODEC_EFAILED; + *p_codec = NULL; + pj_mutex_unlock(ipp_factory.mutex); + return PJMEDIA_CODEC_EFAILED; } /* Create pool for codec instance */ @@ -954,29 +953,29 @@ static pj_status_t ipp_alloc_codec( pjmedia_codec_factory *factory, /* Create PLC if codec has no internal PLC */ if (!ipp_codec[idx].has_native_plc) { - pj_status_t status; - status = pjmedia_plc_create(pool, ipp_codec[idx].clock_rate, - ipp_codec[idx].samples_per_frame, 0, - &codec_data->plc); - if (status != PJ_SUCCESS) { - pj_pool_release(pool); - pj_mutex_unlock(ipp_factory.mutex); - return status; - } + pj_status_t status; + status = pjmedia_plc_create(pool, ipp_codec[idx].clock_rate, + ipp_codec[idx].samples_per_frame, 0, + &codec_data->plc); + if (status != PJ_SUCCESS) { + pj_pool_release(pool); + pj_mutex_unlock(ipp_factory.mutex); + return status; + } } /* Create silence detector if codec has no internal VAD */ if (!ipp_codec[idx].has_native_vad) { - pj_status_t status; - status = pjmedia_silence_det_create(pool, - ipp_codec[idx].clock_rate, - ipp_codec[idx].samples_per_frame, - &codec_data->vad); - if (status != PJ_SUCCESS) { - pj_pool_release(pool); - pj_mutex_unlock(ipp_factory.mutex); - return status; - } + pj_status_t status; + status = pjmedia_silence_det_create(pool, + ipp_codec[idx].clock_rate, + ipp_codec[idx].samples_per_frame, + &codec_data->vad); + if (status != PJ_SUCCESS) { + pj_pool_release(pool); + pj_mutex_unlock(ipp_factory.mutex); + return status; + } } codec_data->pool = pool; @@ -992,7 +991,7 @@ static pj_status_t ipp_alloc_codec( pjmedia_codec_factory *factory, * Free codec. */ static pj_status_t ipp_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { ipp_private_t *codec_data; @@ -1002,7 +1001,7 @@ static pj_status_t ipp_dealloc_codec( pjmedia_codec_factory *factory, /* Close codec, if it's not closed. */ codec_data = (ipp_private_t*) codec->codec_data; if (codec_data->enc != NULL || codec_data->dec != NULL) { - ipp_codec_close(codec); + ipp_codec_close(codec); } pj_pool_release(codec_data->pool); @@ -1014,7 +1013,7 @@ static pj_status_t ipp_dealloc_codec( pjmedia_codec_factory *factory, * Init codec. */ static pj_status_t ipp_codec_init( pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(pool); @@ -1025,7 +1024,7 @@ static pj_status_t ipp_codec_init( pjmedia_codec *codec, * Open codec. */ static pj_status_t ipp_codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { ipp_private_t *codec_data = (ipp_private_t*) codec->codec_data; struct ipp_codec *ippc = &ipp_codec[codec_data->codec_idx]; @@ -1039,16 +1038,16 @@ static pj_status_t ipp_codec_open( pjmedia_codec *codec, /* Get the codec info size */ if (USC_NoError != ippc->fxns->std.GetInfoSize(&info_size)) { - PJ_LOG(1,(THIS_FILE, "Error getting codec info size")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Error getting codec info size")); + goto on_error; } /* Get the codec info */ codec_data->info = pj_pool_zalloc(pool, info_size); if (USC_NoError != ippc->fxns->std.GetInfo((USC_Handle)NULL, - codec_data->info)) + codec_data->info)) { - PJ_LOG(1,(THIS_FILE, "Error getting codec info")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Error getting codec info")); + goto on_error; } /* PREPARING THE ENCODER */ @@ -1056,58 +1055,58 @@ static pj_status_t ipp_codec_open( pjmedia_codec *codec, /* Setting the encoder params */ codec_data->info->params.direction = USC_ENCODE; codec_data->info->params.modes.vad = attr->setting.vad && - ippc->has_native_vad; + ippc->has_native_vad; codec_data->info->params.modes.bitrate = attr->info.avg_bps; codec_data->info->params.law = 0; /* Linear PCM input */ #if PJMEDIA_HAS_INTEL_IPP_CODEC_G729 if (ippc->pt == PJMEDIA_RTP_PT_G729) { - /* Check if G729 Annex B is signaled to be disabled */ - for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { - if (pj_stricmp2(&attr->setting.enc_fmtp.param[i].name, "annexb")==0) - { - if (pj_stricmp2(&attr->setting.enc_fmtp.param[i].val, "no")==0) - { - attr->setting.vad = 0; - codec_data->info->params.modes.vad = 0; - } - break; - } - } + /* Check if G729 Annex B is signaled to be disabled */ + for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { + if (pj_stricmp2(&attr->setting.enc_fmtp.param[i].name, "annexb")==0) + { + if (pj_stricmp2(&attr->setting.enc_fmtp.param[i].val, "no")==0) + { + attr->setting.vad = 0; + codec_data->info->params.modes.vad = 0; + } + break; + } + } } #endif /* Get number of memory blocks needed by the encoder */ if (USC_NoError != ippc->fxns->std.NumAlloc(&codec_data->info->params, - &nb_membanks)) + &nb_membanks)) { - PJ_LOG(1,(THIS_FILE, "Error getting no of memory blocks of encoder")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Error getting no of memory blocks of encoder")); + goto on_error; } /* Allocate memory blocks table */ membanks = (USC_MemBank*) pj_pool_zalloc(pool, - sizeof(USC_MemBank) * nb_membanks); + sizeof(USC_MemBank) * nb_membanks); /* Get size of each memory block */ if (USC_NoError != ippc->fxns->std.MemAlloc(&codec_data->info->params, - membanks)) + membanks)) { - PJ_LOG(1,(THIS_FILE, "Error getting memory blocks size of encoder")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Error getting memory blocks size of encoder")); + goto on_error; } /* Allocate memory for each block */ for (i = 0; i < nb_membanks; i++) { - membanks[i].pMem = (char*) pj_pool_zalloc(pool, membanks[i].nbytes); + membanks[i].pMem = (char*) pj_pool_zalloc(pool, membanks[i].nbytes); } /* Create encoder instance */ if (USC_NoError != ippc->fxns->std.Init(&codec_data->info->params, - membanks, - &codec_data->enc)) + membanks, + &codec_data->enc)) { - PJ_LOG(1,(THIS_FILE, "Error initializing encoder")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Error initializing encoder")); + goto on_error; } /* PREPARING THE DECODER */ @@ -1120,34 +1119,34 @@ static pj_status_t ipp_codec_open( pjmedia_codec *codec, /* Get number of memory blocks needed by the decoder */ if (USC_NoError != ippc->fxns->std.NumAlloc(&codec_data->info->params, - &nb_membanks)) + &nb_membanks)) { - PJ_LOG(1,(THIS_FILE, "Error getting no of memory blocks of decoder")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Error getting no of memory blocks of decoder")); + goto on_error; } /* Allocate memory blocks table */ membanks = (USC_MemBank*) pj_pool_zalloc(pool, - sizeof(USC_MemBank) * nb_membanks); + sizeof(USC_MemBank) * nb_membanks); /* Get size of each memory block */ if (USC_NoError != ippc->fxns->std.MemAlloc(&codec_data->info->params, - membanks)) + membanks)) { - PJ_LOG(1,(THIS_FILE, "Error getting memory blocks size of decoder")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Error getting memory blocks size of decoder")); + goto on_error; } /* Allocate memory for each block */ for (i = 0; i < nb_membanks; i++) { - membanks[i].pMem = (char*) pj_pool_zalloc(pool, membanks[i].nbytes); + membanks[i].pMem = (char*) pj_pool_zalloc(pool, membanks[i].nbytes); } /* Create decoder instance */ if (USC_NoError != ippc->fxns->std.Init(&codec_data->info->params, - membanks, &codec_data->dec)) + membanks, &codec_data->dec)) { - PJ_LOG(1,(THIS_FILE, "Error initializing decoder")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Error initializing decoder")); + goto on_error; } /* Update codec info */ @@ -1165,115 +1164,115 @@ static pj_status_t ipp_codec_open( pjmedia_codec *codec, #if PJMEDIA_HAS_INTEL_IPP_CODEC_AMR /* Init AMR settings */ if (ippc->pt == PJMEDIA_RTP_PT_AMR || ippc->pt == PJMEDIA_RTP_PT_AMRWB) { - amr_settings_t *s; - pj_uint8_t octet_align = 0; - pj_int8_t enc_mode; - - enc_mode = pjmedia_codec_amr_get_mode( - codec_data->info->params.modes.bitrate); - pj_assert(enc_mode >= 0 && enc_mode <= 8); - - /* Check AMR specific attributes */ - - for (i = 0; i < attr->setting.dec_fmtp.cnt; ++i) { - /* octet-align, one of the parameters that must have same value - * in offer & answer (RFC 4867 Section 8.3.1). Just check fmtp - * in the decoder side, since it's value is guaranteed to fulfil - * above requirement (by SDP negotiator). - */ - const pj_str_t STR_FMTP_OCTET_ALIGN = {"octet-align", 11}; - - if (pj_stricmp(&attr->setting.dec_fmtp.param[i].name, - &STR_FMTP_OCTET_ALIGN) == 0) - { - octet_align=(pj_uint8_t) - pj_strtoul(&attr->setting.dec_fmtp.param[i].val); - break; - } - } - - for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { - /* mode-set, encoding mode is chosen based on local default mode - * setting: - * - if local default mode is included in the mode-set, use it - * - otherwise, find the closest mode to local default mode; - * if there are two closest modes, prefer to use the higher - * one, e.g: local default mode is 4, the mode-set param - * contains '2,3,5,6', then 5 will be chosen. - */ - const pj_str_t STR_FMTP_MODE_SET = {"mode-set", 8}; - - if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name, - &STR_FMTP_MODE_SET) == 0) - { - const char *p; - pj_size_t l; - pj_int8_t diff = 99; - - p = pj_strbuf(&attr->setting.enc_fmtp.param[i].val); - l = pj_strlen(&attr->setting.enc_fmtp.param[i].val); - - while (l--) { - if ((ippc->pt==PJMEDIA_RTP_PT_AMR && *p>='0' && *p<='7') || - (ippc->pt==PJMEDIA_RTP_PT_AMRWB && *p>='0' && *p<='8')) - { - pj_int8_t tmp = (pj_int8_t)(*p - '0' - enc_mode); - - if (PJ_ABS(diff) > PJ_ABS(tmp) || - (PJ_ABS(diff) == PJ_ABS(tmp) && tmp > diff)) - { - diff = tmp; - if (diff == 0) break; - } - } - ++p; - } - - if (diff == 99) - goto on_error; - - enc_mode = (pj_int8_t)(enc_mode + diff); - - break; - } - } - - /* Initialize AMR specific settings */ - s = PJ_POOL_ZALLOC_T(pool, amr_settings_t); - codec_data->codec_setting = s; - - s->enc_setting.amr_nb = (pj_uint8_t)(ippc->pt == PJMEDIA_RTP_PT_AMR); - s->enc_setting.octet_aligned = octet_align; - s->enc_setting.reorder = PJ_TRUE; - s->enc_setting.cmr = 15; - - s->dec_setting.amr_nb = (pj_uint8_t)(ippc->pt == PJMEDIA_RTP_PT_AMR); - s->dec_setting.octet_aligned = octet_align; - s->dec_setting.reorder = PJ_TRUE; - - /* Apply encoder mode/bitrate */ - s->enc_mode = enc_mode; - codec_data->info->params.modes.bitrate = s->enc_setting.amr_nb? - pjmedia_codec_amrnb_bitrates[s->enc_mode]: - pjmedia_codec_amrwb_bitrates[s->enc_mode]; - ippc->fxns->std.Control(&codec_data->info->params.modes, - codec_data->enc); - - PJ_LOG(4,(THIS_FILE, "AMR%s encoding mode: %d (%dbps)", - (s->enc_setting.amr_nb?"":"-WB"), - s->enc_mode, - codec_data->info->params.modes.bitrate)); - - /* Return back bitrate info to application */ - attr->info.avg_bps = codec_data->info->params.modes.bitrate; + amr_settings_t *s; + pj_uint8_t octet_align = 0; + pj_int8_t enc_mode; + + enc_mode = pjmedia_codec_amr_get_mode( + codec_data->info->params.modes.bitrate); + pj_assert(enc_mode >= 0 && enc_mode <= 8); + + /* Check AMR specific attributes */ + + for (i = 0; i < attr->setting.dec_fmtp.cnt; ++i) { + /* octet-align, one of the parameters that must have same value + * in offer & answer (RFC 4867 Section 8.3.1). Just check fmtp + * in the decoder side, since it's value is guaranteed to fulfil + * above requirement (by SDP negotiator). + */ + const pj_str_t STR_FMTP_OCTET_ALIGN = {"octet-align", 11}; + + if (pj_stricmp(&attr->setting.dec_fmtp.param[i].name, + &STR_FMTP_OCTET_ALIGN) == 0) + { + octet_align=(pj_uint8_t) + pj_strtoul(&attr->setting.dec_fmtp.param[i].val); + break; + } + } + + for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { + /* mode-set, encoding mode is chosen based on local default mode + * setting: + * - if local default mode is included in the mode-set, use it + * - otherwise, find the closest mode to local default mode; + * if there are two closest modes, prefer to use the higher + * one, e.g: local default mode is 4, the mode-set param + * contains '2,3,5,6', then 5 will be chosen. + */ + const pj_str_t STR_FMTP_MODE_SET = {"mode-set", 8}; + + if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name, + &STR_FMTP_MODE_SET) == 0) + { + const char *p; + pj_size_t l; + pj_int8_t diff = 99; + + p = pj_strbuf(&attr->setting.enc_fmtp.param[i].val); + l = pj_strlen(&attr->setting.enc_fmtp.param[i].val); + + while (l--) { + if ((ippc->pt==PJMEDIA_RTP_PT_AMR && *p>='0' && *p<='7') || + (ippc->pt==PJMEDIA_RTP_PT_AMRWB && *p>='0' && *p<='8')) + { + pj_int8_t tmp = (pj_int8_t)(*p - '0' - enc_mode); + + if (PJ_ABS(diff) > PJ_ABS(tmp) || + (PJ_ABS(diff) == PJ_ABS(tmp) && tmp > diff)) + { + diff = tmp; + if (diff == 0) break; + } + } + ++p; + } + + if (diff == 99) + goto on_error; + + enc_mode = (pj_int8_t)(enc_mode + diff); + + break; + } + } + + /* Initialize AMR specific settings */ + s = PJ_POOL_ZALLOC_T(pool, amr_settings_t); + codec_data->codec_setting = s; + + s->enc_setting.amr_nb = (pj_uint8_t)(ippc->pt == PJMEDIA_RTP_PT_AMR); + s->enc_setting.octet_aligned = octet_align; + s->enc_setting.reorder = PJ_TRUE; + s->enc_setting.cmr = 15; + + s->dec_setting.amr_nb = (pj_uint8_t)(ippc->pt == PJMEDIA_RTP_PT_AMR); + s->dec_setting.octet_aligned = octet_align; + s->dec_setting.reorder = PJ_TRUE; + + /* Apply encoder mode/bitrate */ + s->enc_mode = enc_mode; + codec_data->info->params.modes.bitrate = s->enc_setting.amr_nb? + pjmedia_codec_amrnb_bitrates[s->enc_mode]: + pjmedia_codec_amrwb_bitrates[s->enc_mode]; + ippc->fxns->std.Control(&codec_data->info->params.modes, + codec_data->enc); + + PJ_LOG(4,(THIS_FILE, "AMR%s encoding mode: %d (%dbps)", + (s->enc_setting.amr_nb?"":"-WB"), + s->enc_mode, + codec_data->info->params.modes.bitrate)); + + /* Return back bitrate info to application */ + attr->info.avg_bps = codec_data->info->params.modes.bitrate; } #endif #if PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1 if (ippc->pt >= PJMEDIA_RTP_PT_G722_1_16 && - ippc->pt <= PJMEDIA_RTP_PT_G7221_RSV2) + ippc->pt <= PJMEDIA_RTP_PT_G7221_RSV2) { - codec_data->g7221_pcm_shift = ipp_factory.g7221_pcm_shift; + codec_data->g7221_pcm_shift = ipp_factory.g7221_pcm_shift; } #endif @@ -1298,7 +1297,7 @@ static pj_status_t ipp_codec_close( pjmedia_codec *codec ) * Modify codec settings. */ static pj_status_t ipp_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { ipp_private_t *codec_data = (ipp_private_t*) codec->codec_data; struct ipp_codec *ippc = &ipp_codec[codec_data->codec_idx]; @@ -1307,11 +1306,11 @@ static pj_status_t ipp_codec_modify(pjmedia_codec *codec, codec_data->plc_enabled = (attr->setting.plc != 0); if (ippc->has_native_vad) { - USC_Modes modes; + USC_Modes modes; - modes = codec_data->info->params.modes; - modes.vad = codec_data->vad_enabled; - ippc->fxns->std.Control(&modes, codec_data->enc); + modes = codec_data->info->params.modes; + modes.vad = codec_data->vad_enabled; + ippc->fxns->std.Control(&modes, codec_data->enc); } return PJ_SUCCESS; @@ -1321,11 +1320,11 @@ static pj_status_t ipp_codec_modify(pjmedia_codec *codec, * Get frames in the packet. */ static pj_status_t ipp_codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { ipp_private_t *codec_data = (ipp_private_t*) codec->codec_data; struct ipp_codec *ippc = &ipp_codec[codec_data->codec_idx]; @@ -1334,27 +1333,27 @@ static pj_status_t ipp_codec_parse( pjmedia_codec *codec, PJ_ASSERT_RETURN(frame_cnt, PJ_EINVAL); if (ippc->parse != NULL) { - return ippc->parse(codec_data, pkt, pkt_size, ts, frame_cnt, frames); + return ippc->parse(codec_data, pkt, pkt_size, ts, frame_cnt, frames); } while (pkt_size >= codec_data->frame_size && count < *frame_cnt) { - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = pkt; - frames[count].size = codec_data->frame_size; - frames[count].timestamp.u64 = ts->u64 + count*ippc->samples_per_frame; + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = pkt; + frames[count].size = codec_data->frame_size; + frames[count].timestamp.u64 = ts->u64 + count*ippc->samples_per_frame; - pkt = ((char*)pkt) + codec_data->frame_size; - pkt_size -= codec_data->frame_size; + pkt = ((char*)pkt) + codec_data->frame_size; + pkt_size -= codec_data->frame_size; - ++count; + ++count; } if (pkt_size && count < *frame_cnt) { - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = pkt; - frames[count].size = pkt_size; - frames[count].timestamp.u64 = ts->u64 + count*ippc->samples_per_frame; - ++count; + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = pkt; + frames[count].size = pkt_size; + frames[count].timestamp.u64 = ts->u64 + count*ippc->samples_per_frame; + ++count; } *frame_cnt = count; @@ -1365,9 +1364,9 @@ static pj_status_t ipp_codec_parse( pjmedia_codec *codec, * Encode frames. */ static pj_status_t ipp_codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { ipp_private_t *codec_data = (ipp_private_t*) codec->codec_data; struct ipp_codec *ippc = &ipp_codec[codec_data->codec_idx]; @@ -1380,29 +1379,29 @@ static pj_status_t ipp_codec_encode( pjmedia_codec *codec, /* Invoke external VAD if codec has no internal VAD */ if (codec_data->vad && codec_data->vad_enabled) { - pj_bool_t is_silence; - pj_int32_t silence_duration; - - silence_duration = pj_timestamp_diff32(&codec_data->last_tx, - &input->timestamp); - - is_silence = pjmedia_silence_det_detect(codec_data->vad, - (const pj_int16_t*) input->buf, - (input->size >> 1), - NULL); - if (is_silence && - (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || - silence_duration < (PJMEDIA_CODEC_MAX_SILENCE_PERIOD * - (int)ippc->clock_rate / 1000))) - { - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->buf = NULL; - output->size = 0; - output->timestamp = input->timestamp; - return PJ_SUCCESS; - } else { - codec_data->last_tx = input->timestamp; - } + pj_bool_t is_silence; + pj_int32_t silence_duration; + + silence_duration = pj_timestamp_diff32(&codec_data->last_tx, + &input->timestamp); + + is_silence = pjmedia_silence_det_detect(codec_data->vad, + (const pj_int16_t*) input->buf, + (input->size >> 1), + NULL); + if (is_silence && + (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || + silence_duration < (PJMEDIA_CODEC_MAX_SILENCE_PERIOD * + (int)ippc->clock_rate / 1000))) + { + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->buf = NULL; + output->size = 0; + output->timestamp = input->timestamp; + return PJ_SUCCESS; + } else { + codec_data->last_tx = input->timestamp; + } } nsamples = input->size >> 1; @@ -1410,127 +1409,127 @@ static pj_status_t ipp_codec_encode( pjmedia_codec *codec, pt = ippc->pt; PJ_ASSERT_RETURN(nsamples % samples_per_frame == 0, - PJMEDIA_CODEC_EPCMFRMINLEN); + PJMEDIA_CODEC_EPCMFRMINLEN); /* Encode the frames */ while (nsamples >= samples_per_frame) { - USC_PCMStream in; - USC_Bitstream out; + USC_PCMStream in; + USC_Bitstream out; - in.bitrate = codec_data->info->params.modes.bitrate; - in.nbytes = samples_per_frame << 1; - in.pBuffer = (char*)pcm_in; - in.pcmType.bitPerSample = codec_data->info->params.pcmType.bitPerSample; - in.pcmType.nChannels = codec_data->info->params.pcmType.nChannels; - in.pcmType.sample_frequency = codec_data->info->params.pcmType.sample_frequency; + in.bitrate = codec_data->info->params.modes.bitrate; + in.nbytes = samples_per_frame << 1; + in.pBuffer = (char*)pcm_in; + in.pcmType.bitPerSample = codec_data->info->params.pcmType.bitPerSample; + in.pcmType.nChannels = codec_data->info->params.pcmType.nChannels; + in.pcmType.sample_frequency = codec_data->info->params.pcmType.sample_frequency; - out.pBuffer = (char*)bits_out; + out.pBuffer = (char*)bits_out; #if PJMEDIA_HAS_INTEL_IPP_CODEC_AMR - /* For AMR: reserve two octets for AMR frame info */ - if (pt == PJMEDIA_RTP_PT_AMR || pt == PJMEDIA_RTP_PT_AMRWB) { - out.pBuffer += 2; - } + /* For AMR: reserve two octets for AMR frame info */ + if (pt == PJMEDIA_RTP_PT_AMR || pt == PJMEDIA_RTP_PT_AMRWB) { + out.pBuffer += 2; + } #endif #if PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1 - /* For G722.1: adjust the encoder input signal level */ - if (pt >= PJMEDIA_RTP_PT_G722_1_16 && - pt <= PJMEDIA_RTP_PT_G7221_RSV2 && - codec_data->g7221_pcm_shift) - { - unsigned i; - for (i = 0; i < samples_per_frame; ++i) - pcm_in[i] >>= codec_data->g7221_pcm_shift; - } + /* For G722.1: adjust the encoder input signal level */ + if (pt >= PJMEDIA_RTP_PT_G722_1_16 && + pt <= PJMEDIA_RTP_PT_G7221_RSV2 && + codec_data->g7221_pcm_shift) + { + unsigned i; + for (i = 0; i < samples_per_frame; ++i) + pcm_in[i] >>= codec_data->g7221_pcm_shift; + } #endif - if (USC_NoError != ippc->fxns->Encode(codec_data->enc, &in, &out)) { - break; - } + if (USC_NoError != ippc->fxns->Encode(codec_data->enc, &in, &out)) { + break; + } #if PJMEDIA_HAS_INTEL_IPP_CODEC_AMR - /* For AMR: put info (frametype, degraded, last frame, mode) in the - * first two octets for payload packing. - */ - if (pt == PJMEDIA_RTP_PT_AMR || pt == PJMEDIA_RTP_PT_AMRWB) { - pj_uint16_t *info = (pj_uint16_t*)bits_out; - - /* Two octets for AMR frame info, 0=LSB: - * bit 0-3 : frame type - * bit 5 : STI flag - * bit 6 : last frame flag - * bit 7 : quality flag - * bit 8-11 : mode - */ - out.nbytes += 2; - if (out.frametype == 0 || out.frametype == 4 || - (pt == PJMEDIA_RTP_PT_AMR && out.frametype == 5) || - (pt == PJMEDIA_RTP_PT_AMRWB && out.frametype == 6)) - { - /* Speech frame type */ - *info = (char)pjmedia_codec_amr_get_mode(out.bitrate); - /* Quality */ - if (out.frametype == 5 || out.frametype == 6) - *info |= 0x80; - } else if (out.frametype == 1 || out.frametype == 2 || - (pt == PJMEDIA_RTP_PT_AMR && out.frametype == 6) || - (pt == PJMEDIA_RTP_PT_AMRWB && out.frametype == 7)) - { - /* SID frame type */ - *info = (pj_uint8_t)(pt == PJMEDIA_RTP_PT_AMRWB? 9 : 8); - /* Quality */ - if (out.frametype == 6 || out.frametype == 7) - *info |= 0x80; - /* STI */ - if (out.frametype != 1) - *info |= 0x20; - } else { - /* Untransmited */ - *info = 15; - out.nbytes = 2; - } - - /* Mode */ - *info |= (char)pjmedia_codec_amr_get_mode(out.bitrate) << 8; - - /* Last frame flag */ - if (nsamples == samples_per_frame) - *info |= 0x40; - } + /* For AMR: put info (frametype, degraded, last frame, mode) in the + * first two octets for payload packing. + */ + if (pt == PJMEDIA_RTP_PT_AMR || pt == PJMEDIA_RTP_PT_AMRWB) { + pj_uint16_t *info = (pj_uint16_t*)bits_out; + + /* Two octets for AMR frame info, 0=LSB: + * bit 0-3 : frame type + * bit 5 : STI flag + * bit 6 : last frame flag + * bit 7 : quality flag + * bit 8-11 : mode + */ + out.nbytes += 2; + if (out.frametype == 0 || out.frametype == 4 || + (pt == PJMEDIA_RTP_PT_AMR && out.frametype == 5) || + (pt == PJMEDIA_RTP_PT_AMRWB && out.frametype == 6)) + { + /* Speech frame type */ + *info = (char)pjmedia_codec_amr_get_mode(out.bitrate); + /* Quality */ + if (out.frametype == 5 || out.frametype == 6) + *info |= 0x80; + } else if (out.frametype == 1 || out.frametype == 2 || + (pt == PJMEDIA_RTP_PT_AMR && out.frametype == 6) || + (pt == PJMEDIA_RTP_PT_AMRWB && out.frametype == 7)) + { + /* SID frame type */ + *info = (pj_uint8_t)(pt == PJMEDIA_RTP_PT_AMRWB? 9 : 8); + /* Quality */ + if (out.frametype == 6 || out.frametype == 7) + *info |= 0x80; + /* STI */ + if (out.frametype != 1) + *info |= 0x20; + } else { + /* Untransmited */ + *info = 15; + out.nbytes = 2; + } + + /* Mode */ + *info |= (char)pjmedia_codec_amr_get_mode(out.bitrate) << 8; + + /* Last frame flag */ + if (nsamples == samples_per_frame) + *info |= 0x40; + } #endif - pcm_in += samples_per_frame; - nsamples -= samples_per_frame; - tx += out.nbytes; - bits_out += out.nbytes; + pcm_in += samples_per_frame; + nsamples -= samples_per_frame; + tx += out.nbytes; + bits_out += out.nbytes; #if PJMEDIA_HAS_INTEL_IPP_CODEC_G729 - if (pt == PJMEDIA_RTP_PT_G729) { - if (out.frametype == 1) { - /* SID */ - break; - } else if (out.frametype == 0) { - /* Untransmitted */ - tx -= out.nbytes; - break; - } - } + if (pt == PJMEDIA_RTP_PT_G729) { + if (out.frametype == 1) { + /* SID */ + break; + } else if (out.frametype == 0) { + /* Untransmitted */ + tx -= out.nbytes; + break; + } + } #endif } if (ippc->pack != NULL) { - ippc->pack(codec_data, output->buf, &tx, output_buf_len); + ippc->pack(codec_data, output->buf, &tx, output_buf_len); } /* Check if we don't need to transmit the frame (DTX) */ if (tx == 0) { - output->buf = NULL; - output->size = 0; - output->timestamp.u64 = input->timestamp.u64; - output->type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; + output->buf = NULL; + output->size = 0; + output->timestamp.u64 = input->timestamp.u64; + output->type = PJMEDIA_FRAME_TYPE_NONE; + return PJ_SUCCESS; } output->size = tx; @@ -1544,9 +1543,9 @@ static pj_status_t ipp_codec_encode( pjmedia_codec *codec, * Decode frame. */ static pj_status_t ipp_codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { ipp_private_t *codec_data = (ipp_private_t*) codec->codec_data; struct ipp_codec *ippc = &ipp_codec[codec_data->codec_idx]; @@ -1559,57 +1558,57 @@ static pj_status_t ipp_codec_decode( pjmedia_codec *codec, samples_per_frame = ippc->samples_per_frame; PJ_ASSERT_RETURN(output_buf_len >= samples_per_frame << 1, - PJMEDIA_CODEC_EPCMTOOSHORT); + PJMEDIA_CODEC_EPCMTOOSHORT); if (input->type == PJMEDIA_FRAME_TYPE_AUDIO) { - if (ippc->predecode) { - ippc->predecode(codec_data, input, &in); - } else { - /* Most IPP codecs have frametype==0 for speech frame */ - in.pBuffer = (char*)input->buf; - in.nbytes = input->size; - in.frametype = 0; - in.bitrate = codec_data->info->params.modes.bitrate; - } - - out.pBuffer = output->buf; + if (ippc->predecode) { + ippc->predecode(codec_data, input, &in); + } else { + /* Most IPP codecs have frametype==0 for speech frame */ + in.pBuffer = (char*)input->buf; + in.nbytes = input->size; + in.frametype = 0; + in.bitrate = codec_data->info->params.modes.bitrate; + } + + out.pBuffer = output->buf; } if (input->type != PJMEDIA_FRAME_TYPE_AUDIO || - USC_NoError != ippc->fxns->Decode(codec_data->dec, &in, &out)) + USC_NoError != ippc->fxns->Decode(codec_data->dec, &in, &out)) { - pjmedia_zero_samples((pj_int16_t*)output->buf, samples_per_frame); - output->size = samples_per_frame << 1; - output->timestamp.u64 = input->timestamp.u64; - output->type = PJMEDIA_FRAME_TYPE_AUDIO; - return PJ_SUCCESS; + pjmedia_zero_samples((pj_int16_t*)output->buf, samples_per_frame); + output->size = samples_per_frame << 1; + output->timestamp.u64 = input->timestamp.u64; + output->type = PJMEDIA_FRAME_TYPE_AUDIO; + return PJ_SUCCESS; } #if PJMEDIA_HAS_INTEL_IPP_CODEC_G726 /* For G.726: amplify decoding result (USC G.726 encoder deamplified it) */ if (pt == PJMEDIA_RTP_PT_G726_16 || pt == PJMEDIA_RTP_PT_G726_24 || - pt == PJMEDIA_RTP_PT_G726_32 || pt == PJMEDIA_RTP_PT_G726_40 || - pt == PJMEDIA_RTP_PT_G721) + pt == PJMEDIA_RTP_PT_G726_32 || pt == PJMEDIA_RTP_PT_G726_40 || + pt == PJMEDIA_RTP_PT_G721) { - unsigned i; - pj_int16_t *s = (pj_int16_t*)output->buf; + unsigned i; + pj_int16_t *s = (pj_int16_t*)output->buf; - for (i = 0; i < samples_per_frame; ++i) - s[i] <<= 2; + for (i = 0; i < samples_per_frame; ++i) + s[i] <<= 2; } #endif #if PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1 /* For G722.1: adjust the decoder output signal level */ if (pt >= PJMEDIA_RTP_PT_G722_1_16 && - pt <= PJMEDIA_RTP_PT_G7221_RSV2 && - codec_data->g7221_pcm_shift) + pt <= PJMEDIA_RTP_PT_G7221_RSV2 && + codec_data->g7221_pcm_shift) { - unsigned i; - pj_int16_t *s = (pj_int16_t*)output->buf; + unsigned i; + pj_int16_t *s = (pj_int16_t*)output->buf; - for (i = 0; i < samples_per_frame; ++i) - s[i] <<= codec_data->g7221_pcm_shift; + for (i = 0; i < samples_per_frame; ++i) + s[i] <<= codec_data->g7221_pcm_shift; } #endif @@ -1619,7 +1618,7 @@ static pj_status_t ipp_codec_decode( pjmedia_codec *codec, /* Invoke external PLC if codec has no internal PLC */ if (codec_data->plc && codec_data->plc_enabled) - pjmedia_plc_save(codec_data->plc, (pj_int16_t*)output->buf); + pjmedia_plc_save(codec_data->plc, (pj_int16_t*)output->buf); return PJ_SUCCESS; } @@ -1628,8 +1627,8 @@ static pj_status_t ipp_codec_decode( pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t ipp_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { ipp_private_t *codec_data = (ipp_private_t*) codec->codec_data; struct ipp_codec *ippc = &ipp_codec[codec_data->codec_idx]; @@ -1643,15 +1642,15 @@ static pj_status_t ipp_codec_recover(pjmedia_codec *codec, output->size = samples_per_frame << 1; if (codec_data->plc_enabled) { - if (codec_data->plc) { - pjmedia_plc_generate(codec_data->plc, (pj_int16_t*)output->buf); - } else { - USC_PCMStream out; - out.pBuffer = output->buf; - ippc->fxns->Decode(codec_data->dec, NULL, &out); - } + if (codec_data->plc) { + pjmedia_plc_generate(codec_data->plc, (pj_int16_t*)output->buf); + } else { + USC_PCMStream out; + out.pBuffer = output->buf; + ippc->fxns->Decode(codec_data->dec, NULL, &out); + } } else { - pjmedia_zero_samples((pj_int16_t*)output->buf, samples_per_frame); + pjmedia_zero_samples((pj_int16_t*)output->buf, samples_per_frame); } return PJ_SUCCESS; @@ -1663,7 +1662,7 @@ static pj_status_t ipp_codec_recover(pjmedia_codec *codec, # pragma comment( lib, "ipps.lib") # pragma comment( lib, "ippsc.lib") # if defined(IPP_VERSION_MAJOR) && IPP_VERSION_MAJOR<=6 -# pragma comment( lib, "ippsr.lib") +# pragma comment( lib, "ippsr.lib") # endif //# pragma comment( lib, "ippcorel.lib") //# pragma comment( lib, "ippsemerged.lib") @@ -1673,12 +1672,12 @@ static pj_status_t ipp_codec_recover(pjmedia_codec *codec, //# pragma comment( lib, "ippsremerged.lib") //# pragma comment( lib, "ippsrmerged.lib") # if defined(IPP_VERSION_MAJOR) && IPP_VERSION_MAJOR>=6 -# pragma comment( lib, "speech.lib") +# pragma comment( lib, "speech.lib") # else -# pragma comment( lib, "usc.lib") +# pragma comment( lib, "usc.lib") # endif #endif -#endif /* PJMEDIA_HAS_INTEL_IPP */ +#endif /* PJMEDIA_HAS_INTEL_IPP */ diff --git a/pjmedia/src/pjmedia-codec/l16.c b/pjmedia/src/pjmedia-codec/l16.c index a3d2219bff..10f8bd1738 100644 --- a/pjmedia/src/pjmedia-codec/l16.c +++ b/pjmedia/src/pjmedia-codec/l16.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,7 +33,7 @@ */ #if defined(PJMEDIA_HAS_L16_CODEC) && PJMEDIA_HAS_L16_CODEC != 0 -#define PLC_DISABLED 0 +#define PLC_DISABLED 0 static const pj_str_t STR_L16 = { "L16", 3 }; @@ -42,50 +41,50 @@ static const pj_str_t STR_L16 = { "L16", 3 }; /* To keep frame size below 1400 MTU, set ptime to 10ms for * sampling rate > 35 KHz */ -#define GET_PTIME(clock_rate) ((pj_uint16_t)(clock_rate > 35000 ? 10 : 20)) +#define GET_PTIME(clock_rate) ((pj_uint16_t)(clock_rate > 35000 ? 10 : 20)) /* Prototypes for L16 factory */ static pj_status_t l16_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ); + const pjmedia_codec_info *id ); static pj_status_t l16_default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ); static pj_status_t l16_enum_codecs (pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t l16_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t l16_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for L16 implementation. */ static pj_status_t l16_init( pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t l16_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t l16_close( pjmedia_codec *codec ); static pj_status_t l16_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t l16_parse(pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t l16_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t l16_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); #if !PLC_DISABLED static pj_status_t l16_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); #endif /* Definition for L16 codec operations. */ @@ -119,33 +118,33 @@ static pjmedia_codec_factory_op l16_factory_op = /* L16 factory private data */ static struct l16_factory { - pjmedia_codec_factory base; - pjmedia_endpt *endpt; - pj_pool_t *pool; - pj_mutex_t *mutex; + pjmedia_codec_factory base; + pjmedia_endpt *endpt; + pj_pool_t *pool; + pj_mutex_t *mutex; } l16_factory; /* L16 codec private data. */ struct l16_data { - pj_pool_t *pool; - unsigned frame_size; /* Frame size, in bytes */ - unsigned clock_rate; /* Clock rate */ + pj_pool_t *pool; + unsigned frame_size; /* Frame size, in bytes */ + unsigned clock_rate; /* Clock rate */ #if !PLC_DISABLED - pj_bool_t plc_enabled; - pjmedia_plc *plc; + pj_bool_t plc_enabled; + pjmedia_plc *plc; #endif - pj_bool_t vad_enabled; - pjmedia_silence_det *vad; - pj_timestamp last_tx; + pj_bool_t vad_enabled; + pjmedia_silence_det *vad; + pj_timestamp last_tx; }; PJ_DEF(pj_status_t) pjmedia_codec_l16_init(pjmedia_endpt *endpt, - unsigned options) + unsigned options) { pjmedia_codec_mgr *codec_mgr; pj_status_t status; @@ -155,8 +154,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_l16_init(pjmedia_endpt *endpt, if (l16_factory.endpt != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } /* Init factory */ @@ -167,37 +166,37 @@ PJ_DEF(pj_status_t) pjmedia_codec_l16_init(pjmedia_endpt *endpt, /* Create pool */ l16_factory.pool = pjmedia_endpt_create_pool(endpt, "l16", 4000, 4000); if (!l16_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create mutex. */ status = pj_mutex_create_simple(l16_factory.pool, "l16", - &l16_factory.mutex); + &l16_factory.mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; } /* Register codec factory to endpoint. */ status = pjmedia_codec_mgr_register_factory(codec_mgr, - &l16_factory.base); + &l16_factory.base); if (status != PJ_SUCCESS) - return status; + return status; return PJ_SUCCESS; on_error: if (l16_factory.mutex) { - pj_mutex_destroy(l16_factory.mutex); - l16_factory.mutex = NULL; + pj_mutex_destroy(l16_factory.mutex); + l16_factory.mutex = NULL; } if (l16_factory.pool) { - pj_pool_release(l16_factory.pool); - l16_factory.pool = NULL; + pj_pool_release(l16_factory.pool); + l16_factory.pool = NULL; } return status; } @@ -208,8 +207,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_l16_deinit(void) pj_status_t status; if (l16_factory.endpt == NULL) { - /* Not registered. */ - return PJ_SUCCESS; + /* Not registered. */ + return PJ_SUCCESS; } /* Lock mutex. */ @@ -218,14 +217,14 @@ PJ_DEF(pj_status_t) pjmedia_codec_l16_deinit(void) /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(l16_factory.endpt); if (!codec_mgr) { - l16_factory.endpt = NULL; - pj_mutex_unlock(l16_factory.mutex); - return PJ_EINVALIDOP; + l16_factory.endpt = NULL; + pj_mutex_unlock(l16_factory.mutex); + return PJ_EINVALIDOP; } /* Unregister L16 codec factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &l16_factory.base); + &l16_factory.base); l16_factory.endpt = NULL; /* Destroy mutex. */ @@ -243,21 +242,21 @@ PJ_DEF(pj_status_t) pjmedia_codec_l16_deinit(void) } static pj_status_t l16_test_alloc(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ) + const pjmedia_codec_info *id ) { PJ_UNUSED_ARG(factory); if (pj_stricmp(&id->encoding_name, &STR_L16)==0) { - /* Match! */ - return PJ_SUCCESS; + /* Match! */ + return PJ_SUCCESS; } return -1; } static pj_status_t l16_default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ) { PJ_UNUSED_ARG(factory); @@ -285,169 +284,169 @@ static pj_status_t l16_default_attr( pjmedia_codec_factory *factory, } static pj_status_t l16_enum_codecs( pjmedia_codec_factory *factory, - unsigned *max_count, - pjmedia_codec_info codecs[]) + unsigned *max_count, + pjmedia_codec_info codecs[]) { unsigned count = 0; PJ_UNUSED_ARG(factory); if (count < *max_count) { - /* Register 44100Hz 1 channel L16 codec */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_1; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 44100; - codecs[count].channel_cnt = 1; - ++count; + /* Register 44100Hz 1 channel L16 codec */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_1; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 44100; + codecs[count].channel_cnt = 1; + ++count; } if (count < *max_count) { - /* Register 44100Hz 2 channels L16 codec */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_2; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 44100; - codecs[count].channel_cnt = 2; - ++count; + /* Register 44100Hz 2 channels L16 codec */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_2; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 44100; + codecs[count].channel_cnt = 2; + ++count; } #if PJMEDIA_CODEC_L16_HAS_8KHZ_MONO if (count < *max_count) { - /* 8KHz mono */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_8KHZ_MONO; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 8000; - codecs[count].channel_cnt = 1; - ++count; + /* 8KHz mono */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_8KHZ_MONO; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 8000; + codecs[count].channel_cnt = 1; + ++count; } #endif #if PJMEDIA_CODEC_L16_HAS_8KHZ_STEREO if (count < *max_count) { - /* 8KHz stereo */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_8KHZ_STEREO; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 8000; - codecs[count].channel_cnt = 2; - ++count; + /* 8KHz stereo */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_8KHZ_STEREO; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 8000; + codecs[count].channel_cnt = 2; + ++count; } #endif // disable some L16 modes #if 0 if (count < *max_count) { - /* 11025 Hz mono */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_11KHZ_MONO; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 11025; - codecs[count].channel_cnt = 1; - ++count; + /* 11025 Hz mono */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_11KHZ_MONO; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 11025; + codecs[count].channel_cnt = 1; + ++count; } if (count < *max_count) { - /* 11025 Hz stereo */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_11KHZ_STEREO; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 11025; - codecs[count].channel_cnt = 2; - ++count; + /* 11025 Hz stereo */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_11KHZ_STEREO; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 11025; + codecs[count].channel_cnt = 2; + ++count; } #endif #if PJMEDIA_CODEC_L16_HAS_16KHZ_MONO if (count < *max_count) { - /* 16000 Hz mono */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_16KHZ_MONO; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 16000; - codecs[count].channel_cnt = 1; - ++count; + /* 16000 Hz mono */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_16KHZ_MONO; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 16000; + codecs[count].channel_cnt = 1; + ++count; } #endif #if PJMEDIA_CODEC_L16_HAS_16KHZ_STEREO if (count < *max_count) { - /* 16000 Hz stereo */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_16KHZ_STEREO; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 16000; - codecs[count].channel_cnt = 2; - ++count; + /* 16000 Hz stereo */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_16KHZ_STEREO; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 16000; + codecs[count].channel_cnt = 2; + ++count; } #endif // disable some L16 modes #if 0 if (count < *max_count) { - /* 22050 Hz mono */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_22KHZ_MONO; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 22050; - codecs[count].channel_cnt = 1; - ++count; + /* 22050 Hz mono */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_22KHZ_MONO; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 22050; + codecs[count].channel_cnt = 1; + ++count; } if (count < *max_count) { - /* 22050 Hz stereo */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_22KHZ_STEREO; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 22050; - codecs[count].channel_cnt = 2; - ++count; + /* 22050 Hz stereo */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_22KHZ_STEREO; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 22050; + codecs[count].channel_cnt = 2; + ++count; } if (count < *max_count) { - /* 32000 Hz mono */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_32KHZ_MONO; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 32000; - codecs[count].channel_cnt = 1; - ++count; + /* 32000 Hz mono */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_32KHZ_MONO; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 32000; + codecs[count].channel_cnt = 1; + ++count; } if (count < *max_count) { - /* 32000 Hz stereo */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_32KHZ_STEREO; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 32000; - codecs[count].channel_cnt = 2; - ++count; + /* 32000 Hz stereo */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_32KHZ_STEREO; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 32000; + codecs[count].channel_cnt = 2; + ++count; } #endif #if PJMEDIA_CODEC_L16_HAS_48KHZ_MONO if (count < *max_count) { - /* 48KHz mono */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_48KHZ_MONO; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 48000; - codecs[count].channel_cnt = 1; - ++count; + /* 48KHz mono */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_48KHZ_MONO; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 48000; + codecs[count].channel_cnt = 1; + ++count; } #endif #if PJMEDIA_CODEC_L16_HAS_48KHZ_STEREO if (count < *max_count) { - /* 48KHz stereo */ - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_L16_48KHZ_STEREO; - codecs[count].encoding_name = STR_L16; - codecs[count].clock_rate = 48000; - codecs[count].channel_cnt = 2; - ++count; + /* 48KHz stereo */ + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_L16_48KHZ_STEREO; + codecs[count].encoding_name = STR_L16; + codecs[count].clock_rate = 48000; + codecs[count].channel_cnt = 2; + ++count; } #endif @@ -458,8 +457,8 @@ static pj_status_t l16_enum_codecs( pjmedia_codec_factory *factory, } static pj_status_t l16_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { pjmedia_codec *codec = NULL; struct l16_data *data; @@ -490,21 +489,21 @@ static pj_status_t l16_alloc_codec( pjmedia_codec_factory *factory, #if !PLC_DISABLED /* Create PLC */ status = pjmedia_plc_create(pool, id->clock_rate, - data->frame_size >> 1, 0, - &data->plc); + data->frame_size >> 1, 0, + &data->plc); if (status != PJ_SUCCESS) { - pj_mutex_unlock(l16_factory.mutex); - return status; + pj_mutex_unlock(l16_factory.mutex); + return status; } #endif /* Create silence detector */ status = pjmedia_silence_det_create(pool, id->clock_rate, - data->frame_size >> 1, - &data->vad); + data->frame_size >> 1, + &data->vad); if (status != PJ_SUCCESS) { - pj_mutex_unlock(l16_factory.mutex); - return status; + pj_mutex_unlock(l16_factory.mutex); + return status; } *p_codec = codec; @@ -516,7 +515,7 @@ static pj_status_t l16_alloc_codec( pjmedia_codec_factory *factory, } static pj_status_t l16_dealloc_codec(pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { struct l16_data *data; @@ -547,7 +546,7 @@ static pj_status_t l16_init( pjmedia_codec *codec, pj_pool_t *pool ) } static pj_status_t l16_open(pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { struct l16_data *data = NULL; @@ -571,7 +570,7 @@ static pj_status_t l16_close( pjmedia_codec *codec ) } static pj_status_t l16_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { struct l16_data *data = (struct l16_data*) codec->codec_data; @@ -586,11 +585,11 @@ static pj_status_t l16_modify(pjmedia_codec *codec, } static pj_status_t l16_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { unsigned count = 0; struct l16_data *data = (struct l16_data*) codec->codec_data; @@ -599,15 +598,15 @@ static pj_status_t l16_parse( pjmedia_codec *codec, PJ_ASSERT_RETURN(frame_cnt, PJ_EINVAL); while (pkt_size >= data->frame_size && count < *frame_cnt) { - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = pkt; - frames[count].size = data->frame_size; - frames[count].timestamp.u64 = ts->u64 + (count * data->frame_size >> 1); + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = pkt; + frames[count].size = data->frame_size; + frames[count].timestamp.u64 = ts->u64 + (count * data->frame_size >> 1); - pkt = ((char*)pkt) + data->frame_size; - pkt_size -= data->frame_size; + pkt = ((char*)pkt) + data->frame_size; + pkt_size -= data->frame_size; - ++count; + ++count; } *frame_cnt = count; @@ -615,9 +614,9 @@ static pj_status_t l16_parse( pjmedia_codec *codec, } static pj_status_t l16_encode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct l16_data *data = (struct l16_data*) codec->codec_data; const pj_int16_t *samp = (const pj_int16_t*) input->buf; @@ -628,39 +627,39 @@ static pj_status_t l16_encode(pjmedia_codec *codec, /* Check output buffer length */ if (output_buf_len < input->size) - return PJMEDIA_CODEC_EFRMTOOSHORT; + return PJMEDIA_CODEC_EFRMTOOSHORT; /* Detect silence */ if (data->vad_enabled) { - pj_bool_t is_silence; - pj_int32_t silence_duration; - - silence_duration = pj_timestamp_diff32(&data->last_tx, - &input->timestamp); - - is_silence = pjmedia_silence_det_detect(data->vad, - (const pj_int16_t*) input->buf, - (input->size >> 1), - NULL); - if (is_silence && - (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || - silence_duration < PJMEDIA_CODEC_MAX_SILENCE_PERIOD* - (int)data->clock_rate/1000)) - { - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->buf = NULL; - output->size = 0; - output->timestamp = input->timestamp; - return PJ_SUCCESS; - } else { - data->last_tx = input->timestamp; - } + pj_bool_t is_silence; + pj_int32_t silence_duration; + + silence_duration = pj_timestamp_diff32(&data->last_tx, + &input->timestamp); + + is_silence = pjmedia_silence_det_detect(data->vad, + (const pj_int16_t*) input->buf, + (input->size >> 1), + NULL); + if (is_silence && + (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || + silence_duration < PJMEDIA_CODEC_MAX_SILENCE_PERIOD* + (int)data->clock_rate/1000)) + { + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->buf = NULL; + output->size = 0; + output->timestamp = input->timestamp; + return PJ_SUCCESS; + } else { + data->last_tx = input->timestamp; + } } /* Encode */ #if defined(PJ_IS_LITTLE_ENDIAN) && PJ_IS_LITTLE_ENDIAN!=0 while (samp!=samp_end) - *samp_out++ = pj_htons(*samp++); + *samp_out++ = pj_htons(*samp++); #else pjmedia_copy_samples(samp_out, samp, input->size >> 1); #endif @@ -675,9 +674,9 @@ static pj_status_t l16_encode(pjmedia_codec *codec, } static pj_status_t l16_decode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct l16_data *l16_data = (struct l16_data*) codec->codec_data; const pj_int16_t *samp = (const pj_int16_t*) input->buf; @@ -690,13 +689,13 @@ static pj_status_t l16_decode(pjmedia_codec *codec, /* Check output buffer length */ if (output_buf_len < input->size) - return PJMEDIA_CODEC_EPCMTOOSHORT; + return PJMEDIA_CODEC_EPCMTOOSHORT; /* Decode */ #if defined(PJ_IS_LITTLE_ENDIAN) && PJ_IS_LITTLE_ENDIAN!=0 while (samp!=samp_end) - *samp_out++ = pj_ntohs(*samp++); + *samp_out++ = pj_ntohs(*samp++); #else pjmedia_copy_samples(samp_out, samp, input->size >> 1); #endif @@ -708,7 +707,7 @@ static pj_status_t l16_decode(pjmedia_codec *codec, #if !PLC_DISABLED if (l16_data->plc_enabled) - pjmedia_plc_save( l16_data->plc, (pj_int16_t*)output->buf); + pjmedia_plc_save( l16_data->plc, (pj_int16_t*)output->buf); #endif return PJ_SUCCESS; @@ -719,15 +718,15 @@ static pj_status_t l16_decode(pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t l16_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { struct l16_data *data = (struct l16_data*) codec->codec_data; PJ_ASSERT_RETURN(data->plc_enabled, PJ_EINVALIDOP); PJ_ASSERT_RETURN(output_buf_len >= data->frame_size, - PJMEDIA_CODEC_EPCMTOOSHORT); + PJMEDIA_CODEC_EPCMTOOSHORT); pjmedia_plc_generate(data->plc, (pj_int16_t*)output->buf); output->size = data->frame_size; @@ -736,6 +735,6 @@ static pj_status_t l16_recover(pjmedia_codec *codec, } #endif -#endif /* PJMEDIA_HAS_L16_CODEC */ +#endif /* PJMEDIA_HAS_L16_CODEC */ diff --git a/pjmedia/src/pjmedia-codec/opencore_amr.c b/pjmedia/src/pjmedia-codec/opencore_amr.c index 7193bb82c4..b39e12f222 100644 --- a/pjmedia/src/pjmedia-codec/opencore_amr.c +++ b/pjmedia/src/pjmedia-codec/opencore_amr.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011-2013 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2011 Dan Arrhenius @@ -67,57 +66,57 @@ #define PJ_TRACE 0 #if PJ_TRACE -# define TRACE_(expr) PJ_LOG(4,expr) +# define TRACE_(expr) PJ_LOG(4,expr) #else # define TRACE_(expr) #endif /* Use PJMEDIA PLC */ -#define USE_PJMEDIA_PLC 1 +#define USE_PJMEDIA_PLC 1 #define FRAME_LENGTH_MS 20 /* Prototypes for AMR factory */ static pj_status_t amr_test_alloc(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ); + const pjmedia_codec_info *id ); static pj_status_t amr_default_attr(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ); static pj_status_t amr_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t amr_alloc_codec(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t amr_dealloc_codec(pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for AMR implementation. */ static pj_status_t amr_codec_init(pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t amr_codec_open(pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t amr_codec_close(pjmedia_codec *codec ); static pj_status_t amr_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t amr_codec_parse(pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t amr_codec_encode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t amr_codec_decode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t amr_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); @@ -150,8 +149,8 @@ static pjmedia_codec_factory_op amr_factory_op = static struct amr_codec_factory { pjmedia_codec_factory base; - pjmedia_endpt *endpt; - pj_pool_t *pool; + pjmedia_endpt *endpt; + pj_pool_t *pool; pj_bool_t init[2]; } amr_codec_factory; @@ -159,36 +158,36 @@ static struct amr_codec_factory /* AMR codec private data. */ struct amr_data { - pj_pool_t *pool; + pj_pool_t *pool; unsigned clock_rate; - void *encoder; - void *decoder; - pj_bool_t plc_enabled; - pj_bool_t vad_enabled; - int enc_mode; + void *encoder; + void *decoder; + pj_bool_t plc_enabled; + pj_bool_t vad_enabled; + int enc_mode; pjmedia_codec_amr_pack_setting enc_setting; pjmedia_codec_amr_pack_setting dec_setting; #if USE_PJMEDIA_PLC - pjmedia_plc *plc; + pjmedia_plc *plc; #endif - pj_timestamp last_tx; + pj_timestamp last_tx; }; /* Index for AMR tables. */ enum { - IDX_AMR_NB, /* Index for narrowband. */ - IDX_AMR_WB /* Index for wideband. */ + IDX_AMR_NB, /* Index for narrowband. */ + IDX_AMR_WB /* Index for wideband. */ }; static pjmedia_codec_amr_config def_config[2] = {{ /* AMR-NB */ - PJ_FALSE, /* octet align */ - 5900 /* bitrate */ + PJ_FALSE, /* octet align */ + 5900 /* bitrate */ }, { /* AMR-WB */ - PJ_FALSE, /* octet align */ - 12650 /* bitrate */ + PJ_FALSE, /* octet align */ + 12650 /* bitrate */ }}; static const pj_uint16_t* amr_bitrates[2] = @@ -212,7 +211,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_opencore_amr_init( pjmedia_endpt *endpt, pj_status_t status; if (amr_codec_factory.pool != NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Create AMR codec factory. */ amr_codec_factory.base.op = &amr_factory_op; @@ -230,44 +229,44 @@ PJ_DEF(pj_status_t) pjmedia_codec_opencore_amr_init( pjmedia_endpt *endpt, #endif amr_codec_factory.pool = pjmedia_endpt_create_pool(endpt, "amr", 1000, - 1000); + 1000); if (!amr_codec_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - status = PJ_EINVALIDOP; - goto on_error; + status = PJ_EINVALIDOP; + goto on_error; } /* Register format match callback. */ #ifdef USE_AMRNB if ((options & PJMEDIA_AMR_NO_NB) == 0) { - pj_cstr(&codec_name, "AMR"); - status = pjmedia_sdp_neg_register_fmt_match_cb( - &codec_name, - &pjmedia_codec_amr_match_sdp); - if (status != PJ_SUCCESS) - goto on_error; + pj_cstr(&codec_name, "AMR"); + status = pjmedia_sdp_neg_register_fmt_match_cb( + &codec_name, + &pjmedia_codec_amr_match_sdp); + if (status != PJ_SUCCESS) + goto on_error; } #endif #ifdef USE_AMRWB if ((options & PJMEDIA_AMR_NO_WB) == 0) { - pj_cstr(&codec_name, "AMR-WB"); - status = pjmedia_sdp_neg_register_fmt_match_cb( - &codec_name, - &pjmedia_codec_amr_match_sdp); - if (status != PJ_SUCCESS) - goto on_error; + pj_cstr(&codec_name, "AMR-WB"); + status = pjmedia_sdp_neg_register_fmt_match_cb( + &codec_name, + &pjmedia_codec_amr_match_sdp); + if (status != PJ_SUCCESS) + goto on_error; } #endif /* Register codec factory to endpoint. */ status = pjmedia_codec_mgr_register_factory(codec_mgr, - &amr_codec_factory.base); + &amr_codec_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Done. */ return PJ_SUCCESS; @@ -303,19 +302,19 @@ PJ_DEF(pj_status_t) pjmedia_codec_opencore_amr_deinit(void) amr_codec_factory.init[IDX_AMR_WB] = PJ_FALSE; if (amr_codec_factory.pool == NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(amr_codec_factory.endpt); if (!codec_mgr) { - pj_pool_release(amr_codec_factory.pool); - amr_codec_factory.pool = NULL; - return PJ_EINVALIDOP; + pj_pool_release(amr_codec_factory.pool); + amr_codec_factory.pool = NULL; + return PJ_EINVALIDOP; } /* Unregister AMR codec factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &amr_codec_factory.base); + &amr_codec_factory.base); /* Destroy pool. */ pj_pool_release(amr_codec_factory.pool); @@ -348,18 +347,18 @@ amr_set_config(unsigned idx, const pjmedia_codec_amr_config *config) /* Normalize bitrate. */ nbitrates = amr_bitrates_size[idx]; if (def_config[idx].bitrate < amr_bitrates[idx][0]) { - def_config[idx].bitrate = amr_bitrates[idx][0]; + def_config[idx].bitrate = amr_bitrates[idx][0]; } else if (def_config[idx].bitrate > amr_bitrates[idx][nbitrates-1]) { - def_config[idx].bitrate = amr_bitrates[idx][nbitrates-1]; + def_config[idx].bitrate = amr_bitrates[idx][nbitrates-1]; } else { - unsigned i; - - for (i = 0; i < nbitrates; ++i) { - if (def_config[idx].bitrate <= amr_bitrates[idx][i]) - break; - } - def_config[idx].bitrate = amr_bitrates[idx][i]; + unsigned i; + + for (i = 0; i < nbitrates; ++i) { + if (def_config[idx].bitrate <= amr_bitrates[idx][i]) + break; + } + def_config[idx].bitrate = amr_bitrates[idx][i]; } return PJ_SUCCESS; @@ -381,7 +380,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_opencore_amrwb_set_config( * Check if factory can allocate the specified codec. */ static pj_status_t amr_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *info ) + const pjmedia_codec_info *info ) { const pj_str_t amr_tag = { "AMR", 3}; const pj_str_t amrwb_tag = { "AMR-WB", 6}; @@ -389,17 +388,17 @@ static pj_status_t amr_test_alloc( pjmedia_codec_factory *factory, /* Type MUST be audio. */ if (info->type != PJMEDIA_TYPE_AUDIO) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check payload type. */ if (info->pt != PJMEDIA_RTP_PT_AMR && info->pt != PJMEDIA_RTP_PT_AMRWB) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check encoding name. */ if (pj_stricmp(&info->encoding_name, &amr_tag) != 0 && pj_stricmp(&info->encoding_name, &amrwb_tag) != 0) { - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; } /* Check clock-rate */ @@ -417,8 +416,8 @@ static pj_status_t amr_test_alloc( pjmedia_codec_factory *factory, * Generate default attribute. */ static pj_status_t amr_default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ) { unsigned idx; @@ -439,9 +438,9 @@ static pj_status_t amr_default_attr( pjmedia_codec_factory *factory, attr->setting.plc = 1; if (def_config[idx].octet_align) { - attr->setting.dec_fmtp.cnt = 1; - attr->setting.dec_fmtp.param[0].name = pj_str("octet-align"); - attr->setting.dec_fmtp.param[0].val = pj_str("1"); + attr->setting.dec_fmtp.cnt = 1; + attr->setting.dec_fmtp.param[0].name = pj_str("octet-align"); + attr->setting.dec_fmtp.param[0].val = pj_str("1"); } /* Default all other flag bits disabled. */ @@ -454,8 +453,8 @@ static pj_status_t amr_default_attr( pjmedia_codec_factory *factory, * Enum codecs supported by this factory (i.e. AMR-NB and AMR-WB). */ static pj_status_t amr_enum_codecs( pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]) + unsigned *count, + pjmedia_codec_info codecs[]) { PJ_UNUSED_ARG(factory); PJ_ASSERT_RETURN(codecs && *count > 0, PJ_EINVAL); @@ -490,8 +489,8 @@ static pj_status_t amr_enum_codecs( pjmedia_codec_factory *factory, * Allocate a new AMR codec instance. */ static pj_status_t amr_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { pj_pool_t *pool; pjmedia_codec *codec; @@ -502,7 +501,7 @@ static pj_status_t amr_alloc_codec( pjmedia_codec_factory *factory, PJ_ASSERT_RETURN(factory == &amr_codec_factory.base, PJ_EINVAL); pool = pjmedia_endpt_create_pool(amr_codec_factory.endpt, "amr-inst", - 512, 512); + 512, 512); codec = PJ_POOL_ZALLOC_T(pool, pjmedia_codec); PJ_ASSERT_RETURN(codec != NULL, PJ_ENOMEM); @@ -519,7 +518,7 @@ static pj_status_t amr_alloc_codec( pjmedia_codec_factory *factory, id->clock_rate * FRAME_LENGTH_MS / 1000, 0, &amr_data->plc); if (status != PJ_SUCCESS) { - return status; + return status; } #else PJ_UNUSED_ARG(status); @@ -533,7 +532,7 @@ static pj_status_t amr_alloc_codec( pjmedia_codec_factory *factory, * Free codec. */ static pj_status_t amr_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { struct amr_data *amr_data; @@ -555,7 +554,7 @@ static pj_status_t amr_dealloc_codec( pjmedia_codec_factory *factory, * Init codec. */ static pj_status_t amr_codec_init( pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(pool); @@ -567,7 +566,7 @@ static pj_status_t amr_codec_init( pjmedia_codec *codec, * Open codec. */ static pj_status_t amr_codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { struct amr_data *amr_data = (struct amr_data*) codec->codec_data; pjmedia_codec_amr_pack_setting *setting; @@ -586,54 +585,54 @@ static pj_status_t amr_codec_open( pjmedia_codec *codec, /* Check octet-align */ for (i = 0; i < attr->setting.dec_fmtp.cnt; ++i) { - if (pj_stricmp(&attr->setting.dec_fmtp.param[i].name, - &STR_FMTP_OCTET_ALIGN) == 0) - { - octet_align = (pj_uint8_t) - (pj_strtoul(&attr->setting.dec_fmtp.param[i].val)); - break; - } + if (pj_stricmp(&attr->setting.dec_fmtp.param[i].name, + &STR_FMTP_OCTET_ALIGN) == 0) + { + octet_align = (pj_uint8_t) + (pj_strtoul(&attr->setting.dec_fmtp.param[i].val)); + break; + } } /* Check mode-set */ for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { - const pj_str_t STR_FMTP_MODE_SET = {"mode-set", 8}; + const pj_str_t STR_FMTP_MODE_SET = {"mode-set", 8}; - if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name, - &STR_FMTP_MODE_SET) == 0) - { - const char *p; - pj_size_t l; - pj_int8_t diff = 99; - - /* Encoding mode is chosen based on local default mode setting: - * - if local default mode is included in the mode-set, use it - * - otherwise, find the closest mode to local default mode; - * if there are two closest modes, prefer to use the higher - * one, e.g: local default mode is 4, the mode-set param - * contains '2,3,5,6', then 5 will be chosen. - */ - p = pj_strbuf(&attr->setting.enc_fmtp.param[i].val); - l = pj_strlen(&attr->setting.enc_fmtp.param[i].val); - while (l--) { - if (*p>='0' && (unsigned)*p<=('0'+amr_bitrates_size[idx]-1)) { - pj_int8_t tmp = *p - '0' - enc_mode; - - if (PJ_ABS(diff) > PJ_ABS(tmp) || - (PJ_ABS(diff) == PJ_ABS(tmp) && tmp > diff)) - { - diff = tmp; - if (diff == 0) break; - } - } - ++p; - } - PJ_ASSERT_RETURN(diff != 99, PJMEDIA_CODEC_EFAILED); - - enc_mode = enc_mode + diff; - - break; - } + if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name, + &STR_FMTP_MODE_SET) == 0) + { + const char *p; + pj_size_t l; + pj_int8_t diff = 99; + + /* Encoding mode is chosen based on local default mode setting: + * - if local default mode is included in the mode-set, use it + * - otherwise, find the closest mode to local default mode; + * if there are two closest modes, prefer to use the higher + * one, e.g: local default mode is 4, the mode-set param + * contains '2,3,5,6', then 5 will be chosen. + */ + p = pj_strbuf(&attr->setting.enc_fmtp.param[i].val); + l = pj_strlen(&attr->setting.enc_fmtp.param[i].val); + while (l--) { + if (*p>='0' && (unsigned)*p<=('0'+amr_bitrates_size[idx]-1)) { + pj_int8_t tmp = *p - '0' - enc_mode; + + if (PJ_ABS(diff) > PJ_ABS(tmp) || + (PJ_ABS(diff) == PJ_ABS(tmp) && tmp > diff)) + { + diff = tmp; + if (diff == 0) break; + } + } + ++p; + } + PJ_ASSERT_RETURN(diff != 99, PJMEDIA_CODEC_EFAILED); + + enc_mode = enc_mode + diff; + + break; + } } amr_data->clock_rate = attr->info.clock_rate; @@ -651,9 +650,9 @@ static pj_status_t amr_codec_open( pjmedia_codec *codec, #endif } if (amr_data->encoder == NULL) { - TRACE_((THIS_FILE, "Encoder initialization failed")); - amr_codec_close(codec); - return PJMEDIA_CODEC_EFAILED; + TRACE_((THIS_FILE, "Encoder initialization failed")); + amr_codec_close(codec); + return PJMEDIA_CODEC_EFAILED; } setting = &amr_data->enc_setting; pj_bzero(setting, sizeof(pjmedia_codec_amr_pack_setting)); @@ -672,9 +671,9 @@ static pj_status_t amr_codec_open( pjmedia_codec *codec, #endif } if (amr_data->decoder == NULL) { - TRACE_((THIS_FILE, "Decoder initialization failed")); - amr_codec_close(codec); - return PJMEDIA_CODEC_EFAILED; + TRACE_((THIS_FILE, "Decoder initialization failed")); + amr_codec_close(codec); + return PJMEDIA_CODEC_EFAILED; } setting = &amr_data->dec_setting; pj_bzero(setting, sizeof(pjmedia_codec_amr_pack_setting)); @@ -684,8 +683,8 @@ static pj_status_t amr_codec_open( pjmedia_codec *codec, TRACE_((THIS_FILE, "AMR codec allocated: clockrate=%d vad=%d, plc=%d," " bitrate=%d", amr_data->clock_rate, - amr_data->vad_enabled, amr_data->plc_enabled, - amr_bitrates[idx][amr_data->enc_mode])); + amr_data->vad_enabled, amr_data->plc_enabled, + amr_bitrates[idx][amr_data->enc_mode])); return PJ_SUCCESS; } @@ -737,7 +736,7 @@ static pj_status_t amr_codec_close( pjmedia_codec *codec ) * Modify codec settings. */ static pj_status_t amr_codec_modify( pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { struct amr_data *amr_data = (struct amr_data*) codec->codec_data; pj_bool_t prev_vad_state; @@ -752,21 +751,21 @@ static pj_status_t amr_codec_modify( pjmedia_codec *codec, if (amr_data->enc_setting.amr_nb && prev_vad_state != amr_data->vad_enabled) { - /* Reinit AMR encoder to update VAD setting */ - TRACE_((THIS_FILE, "Reiniting AMR encoder to update VAD setting.")); + /* Reinit AMR encoder to update VAD setting */ + TRACE_((THIS_FILE, "Reiniting AMR encoder to update VAD setting.")); #ifdef USE_AMRNB Encoder_Interface_exit(amr_data->encoder); amr_data->encoder = Encoder_Interface_init(amr_data->vad_enabled); #endif if (amr_data->encoder == NULL) { - TRACE_((THIS_FILE, "Encoder_Interface_init() failed")); - amr_codec_close(codec); - return PJMEDIA_CODEC_EFAILED; - } + TRACE_((THIS_FILE, "Encoder_Interface_init() failed")); + amr_codec_close(codec); + return PJMEDIA_CODEC_EFAILED; + } } TRACE_((THIS_FILE, "AMR codec modified: vad=%d, plc=%d", - amr_data->vad_enabled, amr_data->plc_enabled)); + amr_data->vad_enabled, amr_data->plc_enabled)); return PJ_SUCCESS; } @@ -775,11 +774,11 @@ static pj_status_t amr_codec_modify( pjmedia_codec *codec, * Get frames in the packet. */ static pj_status_t amr_codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { struct amr_data *amr_data = (struct amr_data*) codec->codec_data; pj_uint8_t cmr; @@ -787,14 +786,14 @@ static pj_status_t amr_codec_parse( pjmedia_codec *codec, unsigned idx = (amr_data->enc_setting.amr_nb? 0: 1); status = pjmedia_codec_amr_parse(pkt, pkt_size, ts, &amr_data->dec_setting, - frames, frame_cnt, &cmr); + frames, frame_cnt, &cmr); if (status != PJ_SUCCESS) - return status; + return status; /* Check for Change Mode Request. */ if (cmr < amr_bitrates_size[idx] && amr_data->enc_mode != cmr) { - amr_data->enc_mode = cmr; - TRACE_((THIS_FILE, "AMR encoder switched mode to %d (%dbps)", + amr_data->enc_mode = cmr; + TRACE_((THIS_FILE, "AMR encoder switched mode to %d (%dbps)", amr_data->enc_mode, amr_bitrates[idx][amr_data->enc_mode])); } @@ -807,9 +806,9 @@ static pj_status_t amr_codec_parse( pjmedia_codec *codec, * Encode frame. */ static pj_status_t amr_codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct amr_data *amr_data = (struct amr_data*) codec->codec_data; unsigned char *bitstream; @@ -829,17 +828,17 @@ static pj_status_t amr_codec_encode( pjmedia_codec *codec, nsamples = input->size >> 1; samples_per_frame = amr_data->clock_rate * FRAME_LENGTH_MS / 1000; PJ_ASSERT_RETURN(nsamples % samples_per_frame == 0, - PJMEDIA_CODEC_EPCMFRMINLEN); + PJMEDIA_CODEC_EPCMFRMINLEN); nframes = nsamples / samples_per_frame; PJ_ASSERT_RETURN(nframes <= MAX_FRAMES_PER_PACKET, - PJMEDIA_CODEC_EFRMTOOSHORT); + PJMEDIA_CODEC_EFRMTOOSHORT); /* Encode the frames */ speech = (pj_int16_t*)input->buf; bitstream = (unsigned char*)output->buf; while (nsamples >= samples_per_frame) { - int size; + int size; if (amr_data->enc_setting.amr_nb) { #ifdef USE_AMRNB size = Encoder_Interface_Encode (amr_data->encoder, @@ -856,19 +855,19 @@ static pj_status_t amr_codec_encode( pjmedia_codec *codec, size = 0; #endif } - if (size == 0) { - output->size = 0; - output->buf = NULL; - output->type = PJMEDIA_FRAME_TYPE_NONE; - TRACE_((THIS_FILE, "AMR encode() failed")); - return PJMEDIA_CODEC_EFAILED; - } - nsamples -= samples_per_frame; - speech += samples_per_frame; - bitstream += size; - out_size += size; - TRACE_((THIS_FILE, "AMR encode(): mode=%d, size=%d", - amr_data->enc_mode, out_size)); + if (size == 0) { + output->size = 0; + output->buf = NULL; + output->type = PJMEDIA_FRAME_TYPE_NONE; + TRACE_((THIS_FILE, "AMR encode() failed")); + return PJMEDIA_CODEC_EFAILED; + } + nsamples -= samples_per_frame; + speech += samples_per_frame; + bitstream += size; + out_size += size; + TRACE_((THIS_FILE, "AMR encode(): mode=%d, size=%d", + amr_data->enc_mode, out_size)); } /* Pack payload */ @@ -876,13 +875,13 @@ static pj_status_t amr_codec_encode( pjmedia_codec *codec, pj_memmove(p, output->buf, out_size); dtx_cnt = sid_cnt = 0; for (i = 0; i < nframes; ++i) { - pjmedia_codec_amr_bit_info *info = (pjmedia_codec_amr_bit_info*) - &frames[i].bit_info; - info->frame_type = (pj_uint8_t)((*p >> 3) & 0x0F); - info->good_quality = (pj_uint8_t)((*p >> 2) & 0x01); - info->mode = (pj_int8_t)amr_data->enc_mode; - info->start_bit = 0; - frames[i].buf = p + 1; + pjmedia_codec_amr_bit_info *info = (pjmedia_codec_amr_bit_info*) + &frames[i].bit_info; + info->frame_type = (pj_uint8_t)((*p >> 3) & 0x0F); + info->good_quality = (pj_uint8_t)((*p >> 2) & 0x01); + info->mode = (pj_int8_t)amr_data->enc_mode; + info->start_bit = 0; + frames[i].buf = p + 1; if (amr_data->enc_setting.amr_nb) { frames[i].size = (info->frame_type <= 8)? pjmedia_codec_amrnb_framelen[info->frame_type] : 0; @@ -890,15 +889,15 @@ static pj_status_t amr_codec_encode( pjmedia_codec *codec, frames[i].size = (info->frame_type <= 9)? pjmedia_codec_amrwb_framelen[info->frame_type] : 0; } - p += frames[i].size + 1; - - /* Count the number of SID and DTX frames */ - if (info->frame_type == 15) /* DTX*/ - ++dtx_cnt; - else if (info->frame_type == 8 && amr_data->enc_setting.amr_nb) /* SID */ - ++sid_cnt; - else if (info->frame_type == 9 && !amr_data->enc_setting.amr_nb) /* SID */ - ++sid_cnt; + p += frames[i].size + 1; + + /* Count the number of SID and DTX frames */ + if (info->frame_type == 15) /* DTX*/ + ++dtx_cnt; + else if (info->frame_type == 8 && amr_data->enc_setting.amr_nb) /* SID */ + ++sid_cnt; + else if (info->frame_type == 9 && !amr_data->enc_setting.amr_nb) /* SID */ + ++sid_cnt; } /* VA generates DTX frames as DTX+SID frames switching quickly and it @@ -908,31 +907,31 @@ static pj_status_t amr_codec_encode( pjmedia_codec *codec, * milliseconds. */ if (sid_cnt + dtx_cnt == nframes) { - pj_int32_t dtx_duration; + pj_int32_t dtx_duration; - dtx_duration = pj_timestamp_diff32(&amr_data->last_tx, - &input->timestamp); - if (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || - dtx_duration < (int)(PJMEDIA_CODEC_MAX_SILENCE_PERIOD* + dtx_duration = pj_timestamp_diff32(&amr_data->last_tx, + &input->timestamp); + if (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || + dtx_duration < (int)(PJMEDIA_CODEC_MAX_SILENCE_PERIOD* amr_data->clock_rate/1000)) - { - output->size = 0; - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->timestamp = input->timestamp; - return PJ_SUCCESS; - } + { + output->size = 0; + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->timestamp = input->timestamp; + return PJ_SUCCESS; + } } payload_len = output_buf_len; status = pjmedia_codec_amr_pack(frames, nframes, &amr_data->enc_setting, - output->buf, &payload_len); + output->buf, &payload_len); if (status != PJ_SUCCESS) { - output->size = 0; - output->buf = NULL; - output->type = PJMEDIA_FRAME_TYPE_NONE; - TRACE_((THIS_FILE, "Failed to pack AMR payload, status=%d", status)); - return status; + output->size = 0; + output->buf = NULL; + output->type = PJMEDIA_FRAME_TYPE_NONE; + TRACE_((THIS_FILE, "Failed to pack AMR payload, status=%d", status)); + return status; } output->size = payload_len; @@ -949,9 +948,9 @@ static pj_status_t amr_codec_encode( pjmedia_codec *codec, * Decode frame. */ static pj_status_t amr_codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct amr_data *amr_data = (struct amr_data*) codec->codec_data; pjmedia_frame input_; @@ -965,7 +964,7 @@ static pj_status_t amr_codec_decode( pjmedia_codec *codec, out_size = amr_data->clock_rate * FRAME_LENGTH_MS / 1000 * 2; if (output_buf_len < out_size) - return PJMEDIA_CODEC_EPCMTOOSHORT; + return PJMEDIA_CODEC_EPCMTOOSHORT; input_.buf = &bitstream[1]; /* AMR max frame size */ @@ -977,7 +976,7 @@ static pj_status_t amr_codec_decode( pjmedia_codec *codec, bitstream[0] = (info->frame_type << 3) | (info->good_quality << 2); TRACE_((THIS_FILE, "AMR decode(): mode=%d, ft=%d, size=%d", - info->mode, info->frame_type, input_.size)); + info->mode, info->frame_type, input_.size)); /* Decode */ if (amr_data->dec_setting.amr_nb) { @@ -998,7 +997,7 @@ static pj_status_t amr_codec_decode( pjmedia_codec *codec, #if USE_PJMEDIA_PLC if (amr_data->plc_enabled) - pjmedia_plc_save(amr_data->plc, (pj_int16_t*)output->buf); + pjmedia_plc_save(amr_data->plc, (pj_int16_t*)output->buf); #endif return PJ_SUCCESS; @@ -1013,8 +1012,8 @@ static pj_status_t amr_codec_decode( pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t amr_codec_recover( pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { struct amr_data *amr_data = codec->codec_data; unsigned out_size = amr_data->clock_rate * FRAME_LENGTH_MS / 1000 * 2; diff --git a/pjmedia/src/pjmedia-codec/openh264.cpp b/pjmedia/src/pjmedia-codec/openh264.cpp index 8ce675b493..cf6ccaf62d 100644 --- a/pjmedia/src/pjmedia-codec/openh264.cpp +++ b/pjmedia/src/pjmedia-codec/openh264.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C)2014 Teluu Inc. (http://www.teluu.com) * @@ -38,23 +37,23 @@ /* * Constants */ -#define THIS_FILE "openh264.cpp" +#define THIS_FILE "openh264.cpp" #if (defined(PJ_DARWINOS) && PJ_DARWINOS != 0 && TARGET_OS_IPHONE) || \ defined(__ANDROID__) -# define DEFAULT_WIDTH 352 -# define DEFAULT_HEIGHT 288 +# define DEFAULT_WIDTH 352 +# define DEFAULT_HEIGHT 288 #else -# define DEFAULT_WIDTH 720 -# define DEFAULT_HEIGHT 480 +# define DEFAULT_WIDTH 720 +# define DEFAULT_HEIGHT 480 #endif -#define DEFAULT_FPS 15 -#define DEFAULT_AVG_BITRATE 256000 -#define DEFAULT_MAX_BITRATE 256000 +#define DEFAULT_FPS 15 +#define DEFAULT_AVG_BITRATE 256000 +#define DEFAULT_MAX_BITRATE 256000 -#define MAX_RX_WIDTH 1200 -#define MAX_RX_HEIGHT 800 +#define MAX_RX_WIDTH 1200 +#define MAX_RX_HEIGHT 800 /* OpenH264 default PT */ #define OH264_PT PJMEDIA_RTP_PT_H264 @@ -63,7 +62,7 @@ * This is to avoid sending too many events during consecutive decode * failures. */ -#define MISSING_KEYFRAME_EV_MIN_INTERVAL 1000 +#define MISSING_KEYFRAME_EV_MIN_INTERVAL 1000 /* * Factory operations. @@ -139,42 +138,42 @@ static pjmedia_vid_codec_factory_op oh264_factory_op = static struct oh264_factory { pjmedia_vid_codec_factory base; - pjmedia_vid_codec_mgr *mgr; + pjmedia_vid_codec_mgr *mgr; pj_pool_factory *pf; - pj_pool_t *pool; + pj_pool_t *pool; } oh264_factory; typedef struct oh264_codec_data { - pj_pool_t *pool; - pjmedia_vid_codec_param *prm; - pj_bool_t whole; - pjmedia_h264_packetizer *pktz; + pj_pool_t *pool; + pjmedia_vid_codec_param *prm; + pj_bool_t whole; + pjmedia_h264_packetizer *pktz; /* Encoder state */ - ISVCEncoder *enc; - SSourcePicture *esrc_pic; - unsigned enc_input_size; - pj_uint8_t *enc_frame_whole; - unsigned enc_frame_size; - unsigned enc_processed; - pj_timestamp ets; - SFrameBSInfo bsi; - int ilayer; + ISVCEncoder *enc; + SSourcePicture *esrc_pic; + unsigned enc_input_size; + pj_uint8_t *enc_frame_whole; + unsigned enc_frame_size; + unsigned enc_processed; + pj_timestamp ets; + SFrameBSInfo bsi; + int ilayer; /* Decoder state */ - ISVCDecoder *dec; - pj_uint8_t *dec_buf; - unsigned dec_buf_size; - unsigned missing_kf_interval; - unsigned last_missing_kf_event; + ISVCDecoder *dec; + pj_uint8_t *dec_buf; + unsigned dec_buf_size; + unsigned missing_kf_interval; + unsigned last_missing_kf_event; } oh264_codec_data; struct SLayerPEncCtx { - pj_int32_t iDLayerQp; - SSliceArgument sSliceArgument; + pj_int32_t iDLayerQp; + SSliceArgument sSliceArgument; }; static void log_print(void* ctx, int level, const char* string) { @@ -189,8 +188,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_openh264_vid_init(pjmedia_vid_codec_mgr *mgr, pj_status_t status; if (oh264_factory.pool != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } if (!mgr) mgr = pjmedia_vid_codec_mgr_instance(); @@ -203,20 +202,20 @@ PJ_DEF(pj_status_t) pjmedia_codec_openh264_vid_init(pjmedia_vid_codec_mgr *mgr, oh264_factory.pf = pf; oh264_factory.pool = pj_pool_create(pf, "oh264factory", 256, 256, NULL); if (!oh264_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Registering format match for SDP negotiation */ status = pjmedia_sdp_neg_register_fmt_match_cb( - &h264_name, - &pjmedia_vid_codec_h264_match_sdp); + &h264_name, + &pjmedia_vid_codec_h264_match_sdp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Register codec factory to codec manager. */ status = pjmedia_vid_codec_mgr_register_factory(mgr, - &oh264_factory.base); + &oh264_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; PJ_LOG(4,(THIS_FILE, "OpenH264 codec initialized")); @@ -237,13 +236,13 @@ PJ_DEF(pj_status_t) pjmedia_codec_openh264_vid_deinit(void) pj_status_t status = PJ_SUCCESS; if (oh264_factory.pool == NULL) { - /* Already deinitialized */ - return PJ_SUCCESS; + /* Already deinitialized */ + return PJ_SUCCESS; } /* Unregister OpenH264 codecs factory. */ status = pjmedia_vid_codec_mgr_unregister_factory(oh264_factory.mgr, - &oh264_factory.base); + &oh264_factory.base); /* Destroy pool. */ pj_pool_release(oh264_factory.pool); @@ -258,9 +257,9 @@ static pj_status_t oh264_test_alloc(pjmedia_vid_codec_factory *factory, PJ_ASSERT_RETURN(factory == &oh264_factory.base, PJ_EINVAL); if (info->fmt_id == PJMEDIA_FORMAT_H264 && - info->pt == OH264_PT) + info->pt == OH264_PT) { - return PJ_SUCCESS; + return PJ_SUCCESS; } return PJMEDIA_CODEC_EUNSUP; @@ -281,12 +280,12 @@ static pj_status_t oh264_default_attr(pjmedia_vid_codec_factory *factory, /* Encoded format */ pjmedia_format_init_video(&attr->enc_fmt, PJMEDIA_FORMAT_H264, DEFAULT_WIDTH, DEFAULT_HEIGHT, - DEFAULT_FPS, 1); + DEFAULT_FPS, 1); /* Decoded format */ pjmedia_format_init_video(&attr->dec_fmt, PJMEDIA_FORMAT_I420, DEFAULT_WIDTH, DEFAULT_HEIGHT, - DEFAULT_FPS, 1); + DEFAULT_FPS, 1); /* Decoding fmtp */ attr->dec_fmtp.cnt = 2; @@ -322,7 +321,7 @@ static pj_status_t oh264_enum_info(pjmedia_vid_codec_factory *factory, info->dec_fmt_id_cnt = 1; info->dec_fmt_id[0] = PJMEDIA_FORMAT_I420; info->packings = PJMEDIA_VID_PACKING_PACKETS | - PJMEDIA_VID_PACKING_WHOLE; + PJMEDIA_VID_PACKING_WHOLE; info->fps_cnt = 3; info->fps[0].num = 15; info->fps[0].denum = 1; @@ -353,7 +352,7 @@ static pj_status_t oh264_alloc_codec(pjmedia_vid_codec_factory *factory, pool = pj_pool_create(oh264_factory.pf, "oh264%p", 512, 512, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* codec instance */ codec = PJ_POOL_ZALLOC_T(pool, pjmedia_vid_codec); @@ -368,14 +367,14 @@ static pj_status_t oh264_alloc_codec(pjmedia_vid_codec_factory *factory, /* encoder allocation */ rc = WelsCreateSVCEncoder(&oh264_data->enc); if (rc != 0) - goto on_error; + goto on_error; oh264_data->esrc_pic = PJ_POOL_ZALLOC_T(pool, SSourcePicture); /* decoder allocation */ rc = WelsCreateDecoder(&oh264_data->dec); if (rc != 0) - goto on_error; + goto on_error; oh264_data->enc->SetOption(ENCODER_OPTION_TRACE_LEVEL, &log_level); oh264_data->enc->SetOption(ENCODER_OPTION_TRACE_CALLBACK, &log_cb); @@ -401,13 +400,13 @@ static pj_status_t oh264_dealloc_codec(pjmedia_vid_codec_factory *factory, oh264_data = (oh264_codec_data*) codec->codec_data; if (oh264_data->enc) { - WelsDestroySVCEncoder(oh264_data->enc); - oh264_data->enc = NULL; + WelsDestroySVCEncoder(oh264_data->enc); + oh264_data->enc = NULL; } if (oh264_data->dec) { - oh264_data->dec->Uninitialize(); - WelsDestroyDecoder(oh264_data->dec); - oh264_data->dec = NULL; + oh264_data->dec->Uninitialize(); + WelsDestroyDecoder(oh264_data->dec); + oh264_data->dec = NULL; } pj_pool_release(oh264_data->pool); return PJ_SUCCESS; @@ -425,16 +424,16 @@ static pj_status_t oh264_codec_init(pjmedia_vid_codec *codec, static pj_status_t oh264_codec_open(pjmedia_vid_codec *codec, pjmedia_vid_codec_param *codec_param ) { - oh264_codec_data *oh264_data; - pjmedia_vid_codec_param *param; + oh264_codec_data *oh264_data; + pjmedia_vid_codec_param *param; pjmedia_h264_packetizer_cfg pktz_cfg; pjmedia_vid_codec_h264_fmtp h264_fmtp; - SEncParamExt eprm; + SEncParamExt eprm; SSpatialLayerConfig *elayer = &eprm.sSpatialLayers[0]; - SLayerPEncCtx elayer_ctx; - SDecodingParam sDecParam = {0}; - int rc; - pj_status_t status; + SLayerPEncCtx elayer_ctx; + SDecodingParam sDecParam = {0}; + int rc; + pj_status_t status; PJ_ASSERT_RETURN(codec && codec_param, PJ_EINVAL); @@ -449,13 +448,13 @@ static pj_status_t oh264_codec_open(pjmedia_vid_codec *codec, pj_bzero(&h264_fmtp, sizeof(h264_fmtp)); status = pjmedia_vid_codec_h264_parse_fmtp(¶m->enc_fmtp, &h264_fmtp); if (status != PJ_SUCCESS) - return status; + return status; /* Apply SDP fmtp to format in codec param */ if (!param->ignore_fmtp) { - status = pjmedia_vid_codec_h264_apply_fmtp(param); - if (status != PJ_SUCCESS) - return status; + status = pjmedia_vid_codec_h264_apply_fmtp(param); + if (status != PJ_SUCCESS) + return status; } pj_bzero(&pktz_cfg, sizeof(pktz_cfg)); @@ -463,18 +462,18 @@ static pj_status_t oh264_codec_open(pjmedia_vid_codec *codec, /* Packetization mode */ #if 0 if (h264_fmtp.packetization_mode == 0) - pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL; + pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL; else if (h264_fmtp.packetization_mode == 1) - pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED; + pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED; else - return PJ_ENOTSUP; + return PJ_ENOTSUP; #else if (h264_fmtp.packetization_mode!= - PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL && - h264_fmtp.packetization_mode!= - PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED) + PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL && + h264_fmtp.packetization_mode!= + PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED) { - return PJ_ENOTSUP; + return PJ_ENOTSUP; } /* Better always send in single NAL mode for better compatibility */ pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL; @@ -483,7 +482,7 @@ static pj_status_t oh264_codec_open(pjmedia_vid_codec *codec, status = pjmedia_h264_packetizer_create(oh264_data->pool, &pktz_cfg, &oh264_data->pktz); if (status != PJ_SUCCESS) - return status; + return status; oh264_data->whole = (param->packing == PJMEDIA_VID_PACKING_WHOLE); @@ -493,40 +492,40 @@ static pj_status_t oh264_codec_open(pjmedia_vid_codec *codec, /* Init encoder parameters */ oh264_data->enc->GetDefaultParams (&eprm); - eprm.iComplexityMode = MEDIUM_COMPLEXITY; - eprm.sSpatialLayers[0].uiProfileIdc = PRO_BASELINE; - eprm.iPicWidth = param->enc_fmt.det.vid.size.w; - eprm.iUsageType = CAMERA_VIDEO_REAL_TIME; - eprm.iPicHeight = param->enc_fmt.det.vid.size.h; - eprm.fMaxFrameRate = (param->enc_fmt.det.vid.fps.num * - 1.0f / - param->enc_fmt.det.vid.fps.denum); - eprm.iTemporalLayerNum = 1; - eprm.uiIntraPeriod = 0; /* I-Frame interval in frames */ - eprm.eSpsPpsIdStrategy = (oh264_data->whole ? CONSTANT_ID : - INCREASING_ID); - eprm.bEnableFrameCroppingFlag = true; - eprm.iLoopFilterDisableIdc = 0; - eprm.iLoopFilterAlphaC0Offset = 0; - eprm.iLoopFilterBetaOffset = 0; - eprm.iMultipleThreadIdc = 1; - //eprm.bEnableRc = 1; - eprm.iTargetBitrate = param->enc_fmt.det.vid.avg_bps; - eprm.bEnableFrameSkip = 1; - eprm.bEnableDenoise = 0; - eprm.bEnableSceneChangeDetect = 1; - eprm.bEnableBackgroundDetection = 1; - eprm.bEnableAdaptiveQuant = 1; - eprm.bEnableLongTermReference = 0; - eprm.iLtrMarkPeriod = 30; - eprm.bPrefixNalAddingCtrl = false; - eprm.iSpatialLayerNum = 1; + eprm.iComplexityMode = MEDIUM_COMPLEXITY; + eprm.sSpatialLayers[0].uiProfileIdc = PRO_BASELINE; + eprm.iPicWidth = param->enc_fmt.det.vid.size.w; + eprm.iUsageType = CAMERA_VIDEO_REAL_TIME; + eprm.iPicHeight = param->enc_fmt.det.vid.size.h; + eprm.fMaxFrameRate = (param->enc_fmt.det.vid.fps.num * + 1.0f / + param->enc_fmt.det.vid.fps.denum); + eprm.iTemporalLayerNum = 1; + eprm.uiIntraPeriod = 0; /* I-Frame interval in frames */ + eprm.eSpsPpsIdStrategy = (oh264_data->whole ? CONSTANT_ID : + INCREASING_ID); + eprm.bEnableFrameCroppingFlag = true; + eprm.iLoopFilterDisableIdc = 0; + eprm.iLoopFilterAlphaC0Offset = 0; + eprm.iLoopFilterBetaOffset = 0; + eprm.iMultipleThreadIdc = 1; + //eprm.bEnableRc = 1; + eprm.iTargetBitrate = param->enc_fmt.det.vid.avg_bps; + eprm.bEnableFrameSkip = 1; + eprm.bEnableDenoise = 0; + eprm.bEnableSceneChangeDetect = 1; + eprm.bEnableBackgroundDetection = 1; + eprm.bEnableAdaptiveQuant = 1; + eprm.bEnableLongTermReference = 0; + eprm.iLtrMarkPeriod = 30; + eprm.bPrefixNalAddingCtrl = false; + eprm.iSpatialLayerNum = 1; if (!oh264_data->whole) { - eprm.uiMaxNalSize = param->enc_mtu; + eprm.uiMaxNalSize = param->enc_mtu; } pj_bzero(&elayer_ctx, sizeof (SLayerPEncCtx)); - elayer_ctx.iDLayerQp = 24; + elayer_ctx.iDLayerQp = 24; elayer_ctx.sSliceArgument.uiSliceMode = (oh264_data->whole ? SM_SINGLE_SLICE : SM_SIZELIMITED_SLICE); @@ -543,12 +542,12 @@ static pj_status_t oh264_codec_open(pjmedia_vid_codec *codec, elayer_ctx.sSliceArgument.uiSliceMbNum[6] = 0; elayer_ctx.sSliceArgument.uiSliceMbNum[7] = 0; - elayer->iVideoWidth = eprm.iPicWidth; - elayer->iVideoHeight = eprm.iPicHeight; - elayer->fFrameRate = eprm.fMaxFrameRate; - elayer->uiProfileIdc = eprm.sSpatialLayers[0].uiProfileIdc; - elayer->iSpatialBitrate = eprm.iTargetBitrate; - elayer->iDLayerQp = elayer_ctx.iDLayerQp; + elayer->iVideoWidth = eprm.iPicWidth; + elayer->iVideoHeight = eprm.iPicHeight; + elayer->fFrameRate = eprm.fMaxFrameRate; + elayer->uiProfileIdc = eprm.sSpatialLayers[0].uiProfileIdc; + elayer->iSpatialBitrate = eprm.iTargetBitrate; + elayer->iDLayerQp = elayer_ctx.iDLayerQp; elayer->sSliceArgument.uiSliceMode = elayer_ctx.sSliceArgument.uiSliceMode; memcpy ( &elayer->sSliceArgument, @@ -559,46 +558,46 @@ static pj_status_t oh264_codec_open(pjmedia_vid_codec *codec, sizeof (elayer_ctx.sSliceArgument.uiSliceMbNum)); /* Init input picture */ - oh264_data->esrc_pic->iColorFormat = videoFormatI420; - oh264_data->esrc_pic->uiTimeStamp = 0; - oh264_data->esrc_pic->iPicWidth = eprm.iPicWidth; - oh264_data->esrc_pic->iPicHeight = eprm.iPicHeight; - oh264_data->esrc_pic->iStride[0] = oh264_data->esrc_pic->iPicWidth; - oh264_data->esrc_pic->iStride[1] = - oh264_data->esrc_pic->iStride[2] = - oh264_data->esrc_pic->iStride[0]>>1; + oh264_data->esrc_pic->iColorFormat = videoFormatI420; + oh264_data->esrc_pic->uiTimeStamp = 0; + oh264_data->esrc_pic->iPicWidth = eprm.iPicWidth; + oh264_data->esrc_pic->iPicHeight = eprm.iPicHeight; + oh264_data->esrc_pic->iStride[0] = oh264_data->esrc_pic->iPicWidth; + oh264_data->esrc_pic->iStride[1] = + oh264_data->esrc_pic->iStride[2] = + oh264_data->esrc_pic->iStride[0]>>1; oh264_data->enc_input_size = oh264_data->esrc_pic->iPicWidth * - oh264_data->esrc_pic->iPicHeight * 3 >> 1; + oh264_data->esrc_pic->iPicHeight * 3 >> 1; /* Initialize encoder */ rc = oh264_data->enc->InitializeExt (&eprm); if (rc != cmResultSuccess) { - PJ_LOG(4,(THIS_FILE, "SVC encoder Initialize failed, rc=%d", rc)); - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(4,(THIS_FILE, "SVC encoder Initialize failed, rc=%d", rc)); + return PJMEDIA_CODEC_EFAILED; } int videoFormat = videoFormatI420; rc = oh264_data->enc->SetOption (ENCODER_OPTION_DATAFORMAT, &videoFormat); if (rc != cmResultSuccess) { PJ_LOG(4,(THIS_FILE, "SVC encoder SetOption videoFormatI420 failed, " - "rc=%d", rc)); + "rc=%d", rc)); return PJMEDIA_CODEC_EFAILED; } /* * Decoder */ - sDecParam.sVideoProperty.size = sizeof (sDecParam.sVideoProperty); - sDecParam.uiTargetDqLayer = (pj_uint8_t) - 1; - sDecParam.eEcActiveIdc = ERROR_CON_SLICE_COPY; + sDecParam.sVideoProperty.size = sizeof (sDecParam.sVideoProperty); + sDecParam.uiTargetDqLayer = (pj_uint8_t) - 1; + sDecParam.eEcActiveIdc = ERROR_CON_SLICE_COPY; sDecParam.sVideoProperty.eVideoBsType = VIDEO_BITSTREAM_DEFAULT; /* Calculate minimum missing keyframe event interval in frames. */ oh264_data->missing_kf_interval = - (unsigned)((1.0f * param->dec_fmt.det.vid.fps.num / - param->dec_fmt.det.vid.fps.denum) * - MISSING_KEYFRAME_EV_MIN_INTERVAL/1000); + (unsigned)((1.0f * param->dec_fmt.det.vid.fps.num / + param->dec_fmt.det.vid.fps.denum) * + MISSING_KEYFRAME_EV_MIN_INTERVAL/1000); oh264_data->last_missing_kf_event = oh264_data->missing_kf_interval; //TODO: @@ -607,12 +606,12 @@ static pj_status_t oh264_codec_open(pjmedia_vid_codec *codec, /* Initialize decoder */ rc = oh264_data->dec->Initialize (&sDecParam); if (rc) { - PJ_LOG(4,(THIS_FILE, "Decoder initialization failed, rc=%d", rc)); - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(4,(THIS_FILE, "Decoder initialization failed, rc=%d", rc)); + return PJMEDIA_CODEC_EFAILED; } oh264_data->dec_buf_size = (MAX_RX_WIDTH * MAX_RX_HEIGHT * 3 >> 1) + - (MAX_RX_WIDTH); + (MAX_RX_WIDTH); oh264_data->dec_buf = (pj_uint8_t*)pj_pool_alloc(oh264_data->pool, oh264_data->dec_buf_size); @@ -670,29 +669,29 @@ static pj_status_t oh264_codec_encode_begin(pjmedia_vid_codec *codec, PJMEDIA_CODEC_EFRMINLEN); if (opt && opt->force_keyframe) { - oh264_data->enc->ForceIntraFrame(true); + oh264_data->enc->ForceIntraFrame(true); } oh264_data->esrc_pic->pData[0] = (pj_uint8_t*)input->buf; oh264_data->esrc_pic->pData[1] = oh264_data->esrc_pic->pData[0] + - (oh264_data->esrc_pic->iPicWidth * - oh264_data->esrc_pic->iPicHeight); + (oh264_data->esrc_pic->iPicWidth * + oh264_data->esrc_pic->iPicHeight); oh264_data->esrc_pic->pData[2] = oh264_data->esrc_pic->pData[1] + - (oh264_data->esrc_pic->iPicWidth * - oh264_data->esrc_pic->iPicHeight >>2); + (oh264_data->esrc_pic->iPicWidth * + oh264_data->esrc_pic->iPicHeight >>2); pj_memset (&oh264_data->bsi, 0, sizeof (SFrameBSInfo)); rc = oh264_data->enc->EncodeFrame( oh264_data->esrc_pic, &oh264_data->bsi); if (rc != cmResultSuccess) { - PJ_LOG(5,(THIS_FILE, "EncodeFrame() error, ret: %d", rc)); - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(5,(THIS_FILE, "EncodeFrame() error, ret: %d", rc)); + return PJMEDIA_CODEC_EFAILED; } if (oh264_data->bsi.eFrameType == videoFrameTypeSkip) { - output->size = 0; - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->timestamp = input->timestamp; - return PJ_SUCCESS; + output->size = 0; + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->timestamp = input->timestamp; + return PJ_SUCCESS; } oh264_data->ets = input->timestamp; @@ -700,48 +699,48 @@ static pj_status_t oh264_codec_encode_begin(pjmedia_vid_codec *codec, oh264_data->enc_frame_size = oh264_data->enc_processed = 0; if (oh264_data->whole) { - SLayerBSInfo* pLayerBsInfo; - pj_uint8_t *payload; - unsigned i, payload_size = 0; + SLayerBSInfo* pLayerBsInfo; + pj_uint8_t *payload; + unsigned i, payload_size = 0; - *has_more = PJ_FALSE; + *has_more = PJ_FALSE; - /* Find which layer with biggest payload */ - oh264_data->ilayer = 0; + /* Find which layer with biggest payload */ + oh264_data->ilayer = 0; payload_size = oh264_data->bsi.sLayerInfo[0].pNalLengthInByte[0]; - for (i=0; i < (unsigned)oh264_data->bsi.iLayerNum; ++i) { - unsigned j; - pLayerBsInfo = &oh264_data->bsi.sLayerInfo[i]; - for (j=0; j < (unsigned)pLayerBsInfo->iNalCount; ++j) { - if (pLayerBsInfo->pNalLengthInByte[j] > (int)payload_size) { + for (i=0; i < (unsigned)oh264_data->bsi.iLayerNum; ++i) { + unsigned j; + pLayerBsInfo = &oh264_data->bsi.sLayerInfo[i]; + for (j=0; j < (unsigned)pLayerBsInfo->iNalCount; ++j) { + if (pLayerBsInfo->pNalLengthInByte[j] > (int)payload_size) { payload_size = pLayerBsInfo->pNalLengthInByte[j]; - oh264_data->ilayer = i; - } - } - } - - pLayerBsInfo = &oh264_data->bsi.sLayerInfo[oh264_data->ilayer]; - if (pLayerBsInfo == NULL) { - output->size = 0; - output->type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; - } - - payload = pLayerBsInfo->pBsBuf; - payload_size = 0; - for (int inal = pLayerBsInfo->iNalCount - 1; inal >= 0; --inal) { - payload_size += pLayerBsInfo->pNalLengthInByte[inal]; - } - - if (payload_size > out_size) - return PJMEDIA_CODEC_EFRMTOOSHORT; - - output->type = PJMEDIA_FRAME_TYPE_VIDEO; - output->size = payload_size; - output->timestamp = input->timestamp; - pj_memcpy(output->buf, payload, payload_size); - - return PJ_SUCCESS; + oh264_data->ilayer = i; + } + } + } + + pLayerBsInfo = &oh264_data->bsi.sLayerInfo[oh264_data->ilayer]; + if (pLayerBsInfo == NULL) { + output->size = 0; + output->type = PJMEDIA_FRAME_TYPE_NONE; + return PJ_SUCCESS; + } + + payload = pLayerBsInfo->pBsBuf; + payload_size = 0; + for (int inal = pLayerBsInfo->iNalCount - 1; inal >= 0; --inal) { + payload_size += pLayerBsInfo->pNalLengthInByte[inal]; + } + + if (payload_size > out_size) + return PJMEDIA_CODEC_EFRMTOOSHORT; + + output->type = PJMEDIA_FRAME_TYPE_VIDEO; + output->size = payload_size; + output->timestamp = input->timestamp; + pj_memcpy(output->buf, payload, payload_size); + + return PJ_SUCCESS; } return oh264_codec_encode_more(codec, out_size, output, has_more); @@ -764,52 +763,52 @@ static pj_status_t oh264_codec_encode_more(pjmedia_vid_codec *codec, oh264_data = (oh264_codec_data*) codec->codec_data; if (oh264_data->enc_processed < oh264_data->enc_frame_size) { - /* We have outstanding frame in packetizer */ - status = pjmedia_h264_packetize(oh264_data->pktz, - oh264_data->enc_frame_whole, - oh264_data->enc_frame_size, - &oh264_data->enc_processed, - &payload, &payload_len); - if (status != PJ_SUCCESS) { - /* Reset */ - oh264_data->enc_frame_size = oh264_data->enc_processed = 0; - *has_more = (oh264_data->enc_processed < - oh264_data->enc_frame_size) || - (oh264_data->ilayer < oh264_data->bsi.iLayerNum); - - PJ_PERROR(3,(THIS_FILE, status, "pjmedia_h264_packetize() error")); - return status; - } - - PJ_ASSERT_RETURN(payload_len <= out_size, PJMEDIA_CODEC_EFRMTOOSHORT); + /* We have outstanding frame in packetizer */ + status = pjmedia_h264_packetize(oh264_data->pktz, + oh264_data->enc_frame_whole, + oh264_data->enc_frame_size, + &oh264_data->enc_processed, + &payload, &payload_len); + if (status != PJ_SUCCESS) { + /* Reset */ + oh264_data->enc_frame_size = oh264_data->enc_processed = 0; + *has_more = (oh264_data->enc_processed < + oh264_data->enc_frame_size) || + (oh264_data->ilayer < oh264_data->bsi.iLayerNum); + + PJ_PERROR(3,(THIS_FILE, status, "pjmedia_h264_packetize() error")); + return status; + } + + PJ_ASSERT_RETURN(payload_len <= out_size, PJMEDIA_CODEC_EFRMTOOSHORT); output->type = PJMEDIA_FRAME_TYPE_VIDEO; pj_memcpy(output->buf, payload, payload_len); output->size = payload_len; if (oh264_data->bsi.eFrameType == videoFrameTypeIDR) { - output->bit_info |= PJMEDIA_VID_FRM_KEYFRAME; + output->bit_info |= PJMEDIA_VID_FRM_KEYFRAME; } *has_more = (oh264_data->enc_processed < oh264_data->enc_frame_size) || - (oh264_data->ilayer < oh264_data->bsi.iLayerNum); + (oh264_data->ilayer < oh264_data->bsi.iLayerNum); return PJ_SUCCESS; } if (oh264_data->ilayer >= oh264_data->bsi.iLayerNum) { - /* No more unretrieved frame */ - goto no_frame; + /* No more unretrieved frame */ + goto no_frame; } SLayerBSInfo* pLayerBsInfo; pLayerBsInfo = &oh264_data->bsi.sLayerInfo[oh264_data->ilayer++]; if (pLayerBsInfo == NULL) { - goto no_frame; + goto no_frame; } oh264_data->enc_frame_size = 0; for (int inal = pLayerBsInfo->iNalCount - 1; inal >= 0; --inal) { - oh264_data->enc_frame_size += pLayerBsInfo->pNalLengthInByte[inal]; + oh264_data->enc_frame_size += pLayerBsInfo->pNalLengthInByte[inal]; } oh264_data->enc_frame_whole = pLayerBsInfo->pBsBuf; @@ -817,17 +816,17 @@ static pj_status_t oh264_codec_encode_more(pjmedia_vid_codec *codec, status = pjmedia_h264_packetize(oh264_data->pktz, - oh264_data->enc_frame_whole, - oh264_data->enc_frame_size, - &oh264_data->enc_processed, - &payload, &payload_len); + oh264_data->enc_frame_whole, + oh264_data->enc_frame_size, + &oh264_data->enc_processed, + &payload, &payload_len); if (status != PJ_SUCCESS) { - /* Reset */ - oh264_data->enc_frame_size = oh264_data->enc_processed = 0; - *has_more = (oh264_data->ilayer < oh264_data->bsi.iLayerNum); + /* Reset */ + oh264_data->enc_frame_size = oh264_data->enc_processed = 0; + *has_more = (oh264_data->ilayer < oh264_data->bsi.iLayerNum); - PJ_PERROR(3,(THIS_FILE, status, "pjmedia_h264_packetize() error [2]")); - return status; + PJ_PERROR(3,(THIS_FILE, status, "pjmedia_h264_packetize() error [2]")); + return status; } PJ_ASSERT_RETURN(payload_len <= out_size, PJMEDIA_CODEC_EFRMTOOSHORT); @@ -837,11 +836,11 @@ static pj_status_t oh264_codec_encode_more(pjmedia_vid_codec *codec, output->size = payload_len; if (oh264_data->bsi.eFrameType == videoFrameTypeIDR) { - output->bit_info |= PJMEDIA_VID_FRM_KEYFRAME; + output->bit_info |= PJMEDIA_VID_FRM_KEYFRAME; } *has_more = (oh264_data->enc_processed < oh264_data->enc_frame_size) || - (oh264_data->ilayer < oh264_data->bsi.iLayerNum); + (oh264_data->ilayer < oh264_data->bsi.iLayerNum); return PJ_SUCCESS; @@ -866,52 +865,52 @@ static int write_yuv(pj_uint8_t *buf, unsigned char* pPtr = NULL; req_size = (iWidth * iHeight) + (iWidth / 2 * iHeight / 2) + - (iWidth / 2 * iHeight / 2); + (iWidth / 2 * iHeight / 2); if (dst_len < req_size) - return -1; + return -1; pPtr = pData[0]; for (i = 0; i < iHeight && (dst + iWidth < max); i++) { - pj_memcpy(dst, pPtr, iWidth); - pPtr += iStride[0]; - dst += iWidth; + pj_memcpy(dst, pPtr, iWidth); + pPtr += iStride[0]; + dst += iWidth; } if (i < iHeight) - return -1; + return -1; iHeight = iHeight / 2; iWidth = iWidth / 2; pPtr = pData[1]; for (i = 0; i < iHeight && (dst + iWidth <= max); i++) { - pj_memcpy(dst, pPtr, iWidth); - pPtr += iStride[1]; - dst += iWidth; + pj_memcpy(dst, pPtr, iWidth); + pPtr += iStride[1]; + dst += iWidth; } if (i < iHeight) - return -1; + return -1; pPtr = pData[2]; for (i = 0; i < iHeight && (dst + iWidth <= max); i++) { - pj_memcpy(dst, pPtr, iWidth); - pPtr += iStride[1]; - dst += iWidth; + pj_memcpy(dst, pPtr, iWidth); + pPtr += iStride[1]; + dst += iWidth; } if (i < iHeight) - return -1; + return -1; return (int)(dst - buf); } static pj_status_t oh264_got_decoded_frame(pjmedia_vid_codec *codec, - struct oh264_codec_data *oh264_data, - unsigned char *pData[3], - SBufferInfo *sDstBufInfo, - pj_timestamp *timestamp, - unsigned out_size, - pjmedia_frame *output) + struct oh264_codec_data *oh264_data, + unsigned char *pData[3], + SBufferInfo *sDstBufInfo, + pj_timestamp *timestamp, + unsigned out_size, + pjmedia_frame *output) { pj_uint8_t* pDst[3] = {NULL}; @@ -924,7 +923,7 @@ static pj_status_t oh264_got_decoded_frame(pjmedia_vid_codec *codec, */ if (!pDst[0] || !pDst[1] || !pDst[2]) { - return PJ_SUCCESS; + return PJ_SUCCESS; } int iStride[2]; @@ -935,39 +934,39 @@ static pj_status_t oh264_got_decoded_frame(pjmedia_vid_codec *codec, iStride[1] = sDstBufInfo->UsrData.sSystemBuffer.iStride[1]; int len = write_yuv((pj_uint8_t *)output->buf, out_size, - pDst, iStride, iWidth, iHeight); + pDst, iStride, iWidth, iHeight); if (len > 0) { - output->timestamp = *timestamp; - output->size = len; - output->type = PJMEDIA_FRAME_TYPE_VIDEO; + output->timestamp = *timestamp; + output->size = len; + output->type = PJMEDIA_FRAME_TYPE_VIDEO; } else { - /* buffer is damaged, reset size */ - output->size = 0; - return PJMEDIA_CODEC_EFRMTOOSHORT; + /* buffer is damaged, reset size */ + output->size = 0; + return PJMEDIA_CODEC_EFRMTOOSHORT; } /* Detect format change */ if (iWidth != (int)oh264_data->prm->dec_fmt.det.vid.size.w || - iHeight != (int)oh264_data->prm->dec_fmt.det.vid.size.h) + iHeight != (int)oh264_data->prm->dec_fmt.det.vid.size.h) { - pjmedia_event event; - - PJ_LOG(4,(THIS_FILE, "Frame size changed: %dx%d --> %dx%d", - oh264_data->prm->dec_fmt.det.vid.size.w, - oh264_data->prm->dec_fmt.det.vid.size.h, - iWidth, iHeight)); - - oh264_data->prm->dec_fmt.det.vid.size.w = iWidth; - oh264_data->prm->dec_fmt.det.vid.size.h = iHeight; - - /* Broadcast format changed event */ - pjmedia_event_init(&event, PJMEDIA_EVENT_FMT_CHANGED, - timestamp, codec); - event.data.fmt_changed.dir = PJMEDIA_DIR_DECODING; - pjmedia_format_copy(&event.data.fmt_changed.new_fmt, - &oh264_data->prm->dec_fmt); - pjmedia_event_publish(NULL, codec, &event, - PJMEDIA_EVENT_PUBLISH_DEFAULT); + pjmedia_event event; + + PJ_LOG(4,(THIS_FILE, "Frame size changed: %dx%d --> %dx%d", + oh264_data->prm->dec_fmt.det.vid.size.w, + oh264_data->prm->dec_fmt.det.vid.size.h, + iWidth, iHeight)); + + oh264_data->prm->dec_fmt.det.vid.size.w = iWidth; + oh264_data->prm->dec_fmt.det.vid.size.h = iHeight; + + /* Broadcast format changed event */ + pjmedia_event_init(&event, PJMEDIA_EVENT_FMT_CHANGED, + timestamp, codec); + event.data.fmt_changed.dir = PJMEDIA_DIR_DECODING; + pjmedia_format_copy(&event.data.fmt_changed.new_fmt, + &oh264_data->prm->dec_fmt); + pjmedia_event_publish(NULL, codec, &event, + PJMEDIA_EVENT_PUBLISH_DEFAULT); } return PJ_SUCCESS; @@ -998,51 +997,51 @@ static pj_status_t oh264_codec_decode(pjmedia_vid_codec *codec, oh264_data->last_missing_kf_event++; /* Check if we have recently generated missing keyframe event. */ if (oh264_data->last_missing_kf_event < oh264_data->missing_kf_interval) - kf_requested = PJ_TRUE; + kf_requested = PJ_TRUE; /* * Step 1: unpacketize the packets/frames */ whole_len = 0; if (oh264_data->whole) { - for (i=0; i oh264_data->dec_buf_size) { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]")); - return PJMEDIA_CODEC_EFRMTOOSHORT; - } - - pj_memcpy( oh264_data->dec_buf + whole_len, - (pj_uint8_t*)packets[i].buf, - packets[i].size); - whole_len += (unsigned)packets[i].size; - } + for (i=0; i oh264_data->dec_buf_size) { + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]")); + return PJMEDIA_CODEC_EFRMTOOSHORT; + } + + pj_memcpy( oh264_data->dec_buf + whole_len, + (pj_uint8_t*)packets[i].buf, + packets[i].size); + whole_len += (unsigned)packets[i].size; + } } else { - for (i=0; i - oh264_data->dec_buf_size) - { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]")); - return PJMEDIA_CODEC_EFRMTOOSHORT; - } - - status = pjmedia_h264_unpacketize( oh264_data->pktz, - (pj_uint8_t*)packets[i].buf, - packets[i].size, - oh264_data->dec_buf, - oh264_data->dec_buf_size, - &whole_len); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, "Unpacketize error")); - continue; - } - } + for (i=0; i + oh264_data->dec_buf_size) + { + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]")); + return PJMEDIA_CODEC_EFRMTOOSHORT; + } + + status = pjmedia_h264_unpacketize( oh264_data->pktz, + (pj_uint8_t*)packets[i].buf, + packets[i].size, + oh264_data->dec_buf, + oh264_data->dec_buf_size, + &whole_len); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, "Unpacketize error")); + continue; + } + } } if (whole_len + sizeof(nal_start) > oh264_data->dec_buf_size) { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [2]")); - return PJMEDIA_CODEC_EFRMTOOSHORT; + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [2]")); + return PJMEDIA_CODEC_EFRMTOOSHORT; } /* Dummy NAL sentinel */ @@ -1053,56 +1052,56 @@ static pj_status_t oh264_codec_decode(pjmedia_vid_codec *codec, */ buf_pos = 0; for ( frm_cnt=0; ; ++frm_cnt) { - unsigned frm_size; - unsigned char *start; - - for (i = 0; buf_pos + i < whole_len; i++) { - if (oh264_data->dec_buf[buf_pos + i] == 0 && - oh264_data->dec_buf[buf_pos + i + 1] == 0 && - oh264_data->dec_buf[buf_pos + i + 2] == 1 && - i > 1) - { - break; - } - } - frm_size = i; - - pj_bzero( pData, sizeof(pData)); - pj_bzero( &sDstBufInfo, sizeof (SBufferInfo)); - - start = oh264_data->dec_buf + buf_pos; - - /* Decode */ - ret = oh264_data->dec->DecodeFrame2( start, frm_size, pData, - &sDstBufInfo); - - if (ret != dsErrorFree && !kf_requested) { - /* Broadcast missing keyframe event */ - pjmedia_event event; - pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, - &packets[0].timestamp, codec); - pjmedia_event_publish(NULL, codec, &event, - PJMEDIA_EVENT_PUBLISH_DEFAULT); - kf_requested = PJ_TRUE; - oh264_data->last_missing_kf_event = 0; - } - - if (0 && sDstBufInfo.iBufferStatus == 1) { - // Better to just get the frame later after all NALs are consumed - // by the decoder, it should have the best quality and save some - // CPU load. - /* May overwrite existing frame but that's ok. */ - status = oh264_got_decoded_frame(codec, oh264_data, pData, - &sDstBufInfo, - &packets[0].timestamp, out_size, - output); - has_frame = (status==PJ_SUCCESS && output->size != 0); - } - - if (buf_pos + frm_size >= whole_len) - break; - - buf_pos += frm_size; + unsigned frm_size; + unsigned char *start; + + for (i = 0; buf_pos + i < whole_len; i++) { + if (oh264_data->dec_buf[buf_pos + i] == 0 && + oh264_data->dec_buf[buf_pos + i + 1] == 0 && + oh264_data->dec_buf[buf_pos + i + 2] == 1 && + i > 1) + { + break; + } + } + frm_size = i; + + pj_bzero( pData, sizeof(pData)); + pj_bzero( &sDstBufInfo, sizeof (SBufferInfo)); + + start = oh264_data->dec_buf + buf_pos; + + /* Decode */ + ret = oh264_data->dec->DecodeFrame2( start, frm_size, pData, + &sDstBufInfo); + + if (ret != dsErrorFree && !kf_requested) { + /* Broadcast missing keyframe event */ + pjmedia_event event; + pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, + &packets[0].timestamp, codec); + pjmedia_event_publish(NULL, codec, &event, + PJMEDIA_EVENT_PUBLISH_DEFAULT); + kf_requested = PJ_TRUE; + oh264_data->last_missing_kf_event = 0; + } + + if (0 && sDstBufInfo.iBufferStatus == 1) { + // Better to just get the frame later after all NALs are consumed + // by the decoder, it should have the best quality and save some + // CPU load. + /* May overwrite existing frame but that's ok. */ + status = oh264_got_decoded_frame(codec, oh264_data, pData, + &sDstBufInfo, + &packets[0].timestamp, out_size, + output); + has_frame = (status==PJ_SUCCESS && output->size != 0); + } + + if (buf_pos + frm_size >= whole_len) + break; + + buf_pos += frm_size; } /* Signal that we have no more frames */ @@ -1116,46 +1115,46 @@ static pj_status_t oh264_codec_decode(pjmedia_vid_codec *codec, ret = oh264_data->dec->DecodeFrame2 (NULL, 0, pData, &sDstBufInfo); if (sDstBufInfo.iBufferStatus == 1 && - !(ret & dsRefLost) && !(ret & dsNoParamSets) && - !(ret & dsDepLayerLost)) + !(ret & dsRefLost) && !(ret & dsNoParamSets) && + !(ret & dsDepLayerLost)) { - /* Overwrite existing output frame and that's ok, because we assume - * newer frame have better quality because it has more NALs - */ - status = oh264_got_decoded_frame(codec, oh264_data, pData, - &sDstBufInfo, &packets[0].timestamp, - out_size, output); - has_frame = (status==PJ_SUCCESS && output->size != 0); + /* Overwrite existing output frame and that's ok, because we assume + * newer frame have better quality because it has more NALs + */ + status = oh264_got_decoded_frame(codec, oh264_data, pData, + &sDstBufInfo, &packets[0].timestamp, + out_size, output); + has_frame = (status==PJ_SUCCESS && output->size != 0); } if (ret != dsErrorFree) { - if (!kf_requested) { - /* Broadcast missing keyframe event */ - pjmedia_event event; - pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, - &packets[0].timestamp, codec); - pjmedia_event_publish(NULL, codec, &event, - PJMEDIA_EVENT_PUBLISH_DEFAULT); - oh264_data->last_missing_kf_event = 0; - } - - if (has_frame) { - PJ_LOG(5,(oh264_data->pool->obj_name, - "Decoder returned non error free frame, ret=%d", ret)); - } + if (!kf_requested) { + /* Broadcast missing keyframe event */ + pjmedia_event event; + pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, + &packets[0].timestamp, codec); + pjmedia_event_publish(NULL, codec, &event, + PJMEDIA_EVENT_PUBLISH_DEFAULT); + oh264_data->last_missing_kf_event = 0; + } + + if (has_frame) { + PJ_LOG(5,(oh264_data->pool->obj_name, + "Decoder returned non error free frame, ret=%d", ret)); + } } - + if (!has_frame) { - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->size = 0; - output->timestamp = packets[0].timestamp; + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->size = 0; + output->timestamp = packets[0].timestamp; - PJ_LOG(5,(THIS_FILE, "Decode couldn't produce picture, " - "input nframes=%d, concatenated size=%d bytes, ret=%d", - count, whole_len, ret)); + PJ_LOG(5,(THIS_FILE, "Decode couldn't produce picture, " + "input nframes=%d, concatenated size=%d bytes, ret=%d", + count, whole_len, ret)); } return status; } -#endif /* PJMEDIA_HAS_OPENH264_CODEC */ +#endif /* PJMEDIA_HAS_OPENH264_CODEC */ diff --git a/pjmedia/src/pjmedia-codec/opus.c b/pjmedia/src/pjmedia-codec/opus.c index 7d9fd28343..bec4c6dd8a 100644 --- a/pjmedia/src/pjmedia-codec/opus.c +++ b/pjmedia/src/pjmedia-codec/opus.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2015-2016 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2012-2015 Zaark Technology AB @@ -34,21 +33,21 @@ #define THIS_FILE "opus.c" /* Default packet loss concealment setting. */ -#define OPUS_DEFAULT_PLC 1 +#define OPUS_DEFAULT_PLC 1 /* Default Voice Activity Detector setting. */ -#define OPUS_DEFAULT_VAD 0 +#define OPUS_DEFAULT_VAD 0 /* Maximum size of an encoded packet. * If the the actual size is bigger, the encode/parse will fail. */ -#define MAX_ENCODED_PACKET_SIZE 1280 +#define MAX_ENCODED_PACKET_SIZE 1280 /* Default frame time (msec) */ -#define PTIME 20 +#define PTIME 20 /* Tracing */ #if 0 -# define TRACE_(expr) PJ_LOG(4,expr) +# define TRACE_(expr) PJ_LOG(4,expr) #else # define TRACE_(expr) #endif @@ -56,45 +55,45 @@ /* Prototypes for Opus factory */ static pj_status_t factory_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *ci ); + const pjmedia_codec_info *ci ); static pj_status_t factory_default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *ci, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *ci, + pjmedia_codec_param *attr ); static pj_status_t factory_enum_codecs( pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t factory_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *ci, - pjmedia_codec **p_codec); + const pjmedia_codec_info *ci, + pjmedia_codec **p_codec); static pj_status_t factory_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for Opus implementation. */ static pj_status_t codec_init( pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t codec_close( pjmedia_codec *codec ); static pj_status_t codec_modify( pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t codec_recover( pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); /* Definition for Opus operations. */ static pjmedia_codec_op opus_op = @@ -125,24 +124,24 @@ static pjmedia_codec_factory_op opus_factory_op = struct opus_codec_factory { pjmedia_codec_factory base; - pjmedia_endpt *endpt; - pj_pool_t *pool; + pjmedia_endpt *endpt; + pj_pool_t *pool; }; /* Opus codec private data. */ struct opus_data { - pj_pool_t *pool; - pj_mutex_t *mutex; - OpusEncoder *enc; - OpusDecoder *dec; - OpusRepacketizer *enc_packer; - OpusRepacketizer *dec_packer; - pjmedia_codec_opus_config cfg; - unsigned enc_ptime; - unsigned dec_ptime; - pjmedia_frame dec_frame[2]; - int dec_frame_index; + pj_pool_t *pool; + pj_mutex_t *mutex; + OpusEncoder *enc; + OpusDecoder *dec; + OpusRepacketizer *enc_packer; + OpusRepacketizer *dec_packer; + pjmedia_codec_opus_config cfg; + unsigned enc_ptime; + unsigned dec_ptime; + pjmedia_frame dec_frame[2]; + int dec_frame_index; }; /* Codec factory instance */ @@ -151,28 +150,28 @@ static struct opus_codec_factory opus_codec_factory; /* Opus default configuration */ static pjmedia_codec_opus_config opus_cfg = { - PJMEDIA_CODEC_OPUS_DEFAULT_SAMPLE_RATE, /* Sample rate */ - 1, /* Channel count */ - PTIME, /* Frame time */ - PJMEDIA_CODEC_OPUS_DEFAULT_BIT_RATE, /* Bit rate */ - 5, /* Expected packet loss */ - PJMEDIA_CODEC_OPUS_DEFAULT_COMPLEXITY, /* Complexity */ - PJMEDIA_CODEC_OPUS_DEFAULT_CBR, /* Constant bit rate */ + PJMEDIA_CODEC_OPUS_DEFAULT_SAMPLE_RATE, /* Sample rate */ + 1, /* Channel count */ + PTIME, /* Frame time */ + PJMEDIA_CODEC_OPUS_DEFAULT_BIT_RATE, /* Bit rate */ + 5, /* Expected packet loss */ + PJMEDIA_CODEC_OPUS_DEFAULT_COMPLEXITY, /* Complexity */ + PJMEDIA_CODEC_OPUS_DEFAULT_CBR, /* Constant bit rate */ }; static int get_opus_bw_constant (unsigned sample_rate) { if (sample_rate <= 8000) - return OPUS_BANDWIDTH_NARROWBAND; + return OPUS_BANDWIDTH_NARROWBAND; else if (sample_rate <= 12000) - return OPUS_BANDWIDTH_MEDIUMBAND; + return OPUS_BANDWIDTH_MEDIUMBAND; else if (sample_rate <= 16000) - return OPUS_BANDWIDTH_WIDEBAND; + return OPUS_BANDWIDTH_WIDEBAND; else if (sample_rate <= 24000) - return OPUS_BANDWIDTH_SUPERWIDEBAND; + return OPUS_BANDWIDTH_SUPERWIDEBAND; else - return OPUS_BANDWIDTH_FULLBAND; + return OPUS_BANDWIDTH_FULLBAND; } @@ -187,7 +186,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_opus_init( pjmedia_endpt *endpt ) PJ_ASSERT_RETURN(endpt, PJ_EINVAL); if (opus_codec_factory.pool != NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Create the Opus codec factory */ opus_codec_factory.base.op = &opus_factory_op; @@ -195,26 +194,26 @@ PJ_DEF(pj_status_t) pjmedia_codec_opus_init( pjmedia_endpt *endpt ) opus_codec_factory.endpt = endpt; opus_codec_factory.pool = pjmedia_endpt_create_pool(endpt, "opus-factory", - 1024, 1024); + 1024, 1024); if (!opus_codec_factory.pool) { - PJ_LOG(2, (THIS_FILE, "Unable to create memory pool for Opus codec")); - return PJ_ENOMEM; + PJ_LOG(2, (THIS_FILE, "Unable to create memory pool for Opus codec")); + return PJ_ENOMEM; } /* Get the codec manager */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - PJ_LOG(2, (THIS_FILE, "Unable to get the codec manager")); - status = PJ_EINVALIDOP; - goto on_codec_factory_error; + PJ_LOG(2, (THIS_FILE, "Unable to get the codec manager")); + status = PJ_EINVALIDOP; + goto on_codec_factory_error; } /* Register the codec factory */ status = pjmedia_codec_mgr_register_factory (codec_mgr, - &opus_codec_factory.base); + &opus_codec_factory.base); if (status != PJ_SUCCESS) { - PJ_LOG(2, (THIS_FILE, "Unable to register the codec factory")); - goto on_codec_factory_error; + PJ_LOG(2, (THIS_FILE, "Unable to register the codec factory")); + goto on_codec_factory_error; } return PJ_SUCCESS; @@ -236,22 +235,22 @@ PJ_DEF(pj_status_t) pjmedia_codec_opus_deinit( void ) pjmedia_codec_mgr *codec_mgr; if (opus_codec_factory.pool == NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Get the codec manager */ codec_mgr = pjmedia_endpt_get_codec_mgr(opus_codec_factory.endpt); if (!codec_mgr) { - PJ_LOG(2, (THIS_FILE, "Unable to get the codec manager")); - pj_pool_release(opus_codec_factory.pool); - opus_codec_factory.pool = NULL; - return PJ_EINVALIDOP; + PJ_LOG(2, (THIS_FILE, "Unable to get the codec manager")); + pj_pool_release(opus_codec_factory.pool); + opus_codec_factory.pool = NULL; + return PJ_EINVALIDOP; } /* Unregister the codec factory */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &opus_codec_factory.base); + &opus_codec_factory.base); if (status != PJ_SUCCESS) - PJ_LOG(2, (THIS_FILE, "Unable to unregister the codec factory")); + PJ_LOG(2, (THIS_FILE, "Unable to unregister the codec factory")); /* Release the memory pool */ pj_pool_release(opus_codec_factory.pool); @@ -276,7 +275,7 @@ pjmedia_codec_opus_get_config( pjmedia_codec_opus_config *cfg ) static pj_str_t STR_MAX_PLAYBACK = {"maxplaybackrate", 15}; static pj_str_t STR_MAX_CAPTURE = {"sprop-maxcapturerate", 20}; -static pj_str_t STR_STEREO = {"stereo", 6}; +static pj_str_t STR_STEREO = {"stereo", 6}; static pj_str_t STR_SPROP_STEREO = {"sprop-stereo", 12}; static pj_str_t STR_MAX_BIT_RATE = {"maxaveragebitrate", 17}; static pj_str_t STR_INBAND_FEC = {"useinbandfec", 12}; @@ -287,8 +286,8 @@ static int find_fmtp(pjmedia_codec_fmtp *fmtp, pj_str_t *name, pj_bool_t add) { int i; for (i = 0; i < fmtp->cnt; i++) { - if (pj_stricmp(&fmtp->param[i].name, name) == 0) - return i; + if (pj_stricmp(&fmtp->param[i].name, name) == 0) + return i; } if (add && (i < PJMEDIA_CODEC_MAX_FMTP_CNT)) { @@ -303,13 +302,13 @@ static void remove_fmtp(pjmedia_codec_fmtp *fmtp, pj_str_t *name) { int i, j; for (i = 0; i < fmtp->cnt; i++) { - if (pj_stricmp(&fmtp->param[i].name, name) == 0) { - fmtp->cnt--; - for (j = i; j < fmtp->cnt; j++) { - fmtp->param[i].name = fmtp->param[i+1].name; - fmtp->param[i].val = fmtp->param[i+1].val; - } - } + if (pj_stricmp(&fmtp->param[i].name, name) == 0) { + fmtp->cnt--; + for (j = i; j < fmtp->cnt; j++) { + fmtp->param[i].name = fmtp->param[i+1].name; + fmtp->param[i].val = fmtp->param[i+1].val; + } + } } } @@ -320,29 +319,29 @@ static pj_status_t generate_fmtp(pjmedia_codec_param *attr) static char clockrate_str[12]; if (attr->info.clock_rate != 48000) { - pj_ansi_snprintf(clockrate_str, sizeof(clockrate_str), "%u", - attr->info.clock_rate); + pj_ansi_snprintf(clockrate_str, sizeof(clockrate_str), "%u", + attr->info.clock_rate); idx = find_fmtp(&attr->setting.dec_fmtp, &STR_MAX_PLAYBACK, PJ_TRUE); if (idx >= 0) - attr->setting.dec_fmtp.param[idx].val = pj_str(clockrate_str); + attr->setting.dec_fmtp.param[idx].val = pj_str(clockrate_str); - idx = find_fmtp(&attr->setting.dec_fmtp, &STR_MAX_CAPTURE, PJ_TRUE); - if (idx >= 0) - attr->setting.dec_fmtp.param[idx].val = pj_str(clockrate_str); + idx = find_fmtp(&attr->setting.dec_fmtp, &STR_MAX_CAPTURE, PJ_TRUE); + if (idx >= 0) + attr->setting.dec_fmtp.param[idx].val = pj_str(clockrate_str); } else { - remove_fmtp(&attr->setting.dec_fmtp, &STR_MAX_PLAYBACK); - remove_fmtp(&attr->setting.dec_fmtp, &STR_MAX_CAPTURE); + remove_fmtp(&attr->setting.dec_fmtp, &STR_MAX_PLAYBACK); + remove_fmtp(&attr->setting.dec_fmtp, &STR_MAX_CAPTURE); } /* Check if we need to set parameter 'maxaveragebitrate' */ if (opus_cfg.bit_rate > 0) { idx = find_fmtp(&attr->setting.dec_fmtp, &STR_MAX_BIT_RATE, PJ_TRUE); if (idx >= 0) { - pj_ansi_snprintf(bitrate_str, sizeof(bitrate_str), "%u", - attr->info.avg_bps); - attr->setting.dec_fmtp.param[idx].val = pj_str(bitrate_str); - } + pj_ansi_snprintf(bitrate_str, sizeof(bitrate_str), "%u", + attr->info.avg_bps); + attr->setting.dec_fmtp.param[idx].val = pj_str(bitrate_str); + } } else { remove_fmtp(&attr->setting.dec_fmtp, &STR_MAX_BIT_RATE); } @@ -350,38 +349,38 @@ static pj_status_t generate_fmtp(pjmedia_codec_param *attr) if (attr->info.channel_cnt > 1) { idx = find_fmtp(&attr->setting.dec_fmtp, &STR_STEREO, PJ_TRUE); if (idx >= 0) - attr->setting.dec_fmtp.param[idx].val = pj_str("1"); + attr->setting.dec_fmtp.param[idx].val = pj_str("1"); idx = find_fmtp(&attr->setting.dec_fmtp, &STR_SPROP_STEREO, PJ_TRUE); if (idx >= 0) - attr->setting.dec_fmtp.param[idx].val = pj_str("1"); + attr->setting.dec_fmtp.param[idx].val = pj_str("1"); } else { - remove_fmtp(&attr->setting.dec_fmtp, &STR_STEREO); - remove_fmtp(&attr->setting.dec_fmtp, &STR_SPROP_STEREO); + remove_fmtp(&attr->setting.dec_fmtp, &STR_STEREO); + remove_fmtp(&attr->setting.dec_fmtp, &STR_SPROP_STEREO); } if (opus_cfg.cbr) { idx = find_fmtp(&attr->setting.dec_fmtp, &STR_CBR, PJ_TRUE); if (idx >= 0) - attr->setting.dec_fmtp.param[idx].val = pj_str("1"); + attr->setting.dec_fmtp.param[idx].val = pj_str("1"); } else { - remove_fmtp(&attr->setting.dec_fmtp, &STR_CBR); + remove_fmtp(&attr->setting.dec_fmtp, &STR_CBR); } if (attr->setting.plc) { idx = find_fmtp(&attr->setting.dec_fmtp, &STR_INBAND_FEC, PJ_TRUE); if (idx >= 0) - attr->setting.dec_fmtp.param[idx].val = pj_str("1"); + attr->setting.dec_fmtp.param[idx].val = pj_str("1"); } else { - remove_fmtp(&attr->setting.dec_fmtp, &STR_INBAND_FEC); + remove_fmtp(&attr->setting.dec_fmtp, &STR_INBAND_FEC); } if (attr->setting.vad) { idx = find_fmtp(&attr->setting.dec_fmtp, &STR_DTX, PJ_TRUE); if (idx >= 0) - attr->setting.dec_fmtp.param[idx].val = pj_str("1"); + attr->setting.dec_fmtp.param[idx].val = pj_str("1"); } else { - remove_fmtp(&attr->setting.dec_fmtp, &STR_DTX); + remove_fmtp(&attr->setting.dec_fmtp, &STR_DTX); } return PJ_SUCCESS; @@ -392,7 +391,7 @@ static pj_status_t generate_fmtp(pjmedia_codec_param *attr) */ PJ_DEF(pj_status_t) pjmedia_codec_opus_set_default_param(const pjmedia_codec_opus_config *cfg, - pjmedia_codec_param *param ) + pjmedia_codec_param *param ) { const pj_str_t opus_str = {"opus", 4}; const pjmedia_codec_info *info[1]; @@ -406,16 +405,16 @@ pjmedia_codec_opus_set_default_param(const pjmedia_codec_opus_config *cfg, codec_mgr = pjmedia_endpt_get_codec_mgr(opus_codec_factory.endpt); status = pjmedia_codec_mgr_find_codecs_by_id(codec_mgr, &opus_str, - &count, info, NULL); + &count, info, NULL); if (status != PJ_SUCCESS) - return status; + return status; /* Set sample rate */ if (cfg->sample_rate != 8000 && cfg->sample_rate != 12000 && - cfg->sample_rate != 16000 && cfg->sample_rate != 24000 && - cfg->sample_rate != 48000) + cfg->sample_rate != 16000 && cfg->sample_rate != 24000 && + cfg->sample_rate != 48000) { - return PJ_EINVAL; + return PJ_EINVAL; } param->info.clock_rate = opus_cfg.sample_rate = cfg->sample_rate; @@ -432,19 +431,19 @@ pjmedia_codec_opus_set_default_param(const pjmedia_codec_opus_config *cfg, if ((cfg->bit_rate != PJMEDIA_CODEC_OPUS_DEFAULT_BIT_RATE) && (cfg->bit_rate < 6000 || cfg->bit_rate > 510000)) { - return PJ_EINVAL; + return PJ_EINVAL; } opus_cfg.bit_rate = cfg->bit_rate; param->info.avg_bps = opus_cfg.bit_rate; /* Set expected packet loss */ if (cfg->packet_loss >= 100) - return PJ_EINVAL; + return PJ_EINVAL; opus_cfg.packet_loss = cfg->packet_loss; /* Set complexity */ if (cfg->complexity > 10) - return PJ_EINVAL; + return PJ_EINVAL; opus_cfg.complexity = cfg->complexity; opus_cfg.cbr = cfg->cbr; @@ -460,7 +459,7 @@ pjmedia_codec_opus_set_default_param(const pjmedia_codec_opus_config *cfg, * Check if factory can allocate the specified codec. */ static pj_status_t factory_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *ci ) + const pjmedia_codec_info *ci ) { const pj_str_t opus_tag = {"OPUS", 4}; @@ -469,18 +468,18 @@ static pj_status_t factory_test_alloc( pjmedia_codec_factory *factory, /* Type MUST be audio. */ if (ci->type != PJMEDIA_TYPE_AUDIO) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check encoding name. */ if (pj_stricmp(&ci->encoding_name, &opus_tag) != 0) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check clock rate */ if (ci->clock_rate != 8000 && ci->clock_rate != 12000 && - ci->clock_rate != 16000 && ci->clock_rate != 24000 && - ci->clock_rate != 48000) + ci->clock_rate != 16000 && ci->clock_rate != 24000 && + ci->clock_rate != 48000) { - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; } return PJ_SUCCESS; @@ -491,26 +490,26 @@ static pj_status_t factory_test_alloc( pjmedia_codec_factory *factory, * Generate default attribute. */ static pj_status_t factory_default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *ci, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *ci, + pjmedia_codec_param *attr ) { PJ_UNUSED_ARG(factory); TRACE_((THIS_FILE, "%s:%d: - TRACE", __FUNCTION__, __LINE__)); pj_bzero(attr, sizeof(pjmedia_codec_param)); - attr->info.pt = (pj_uint8_t)ci->pt; - attr->info.clock_rate = opus_cfg.sample_rate; - attr->info.channel_cnt = opus_cfg.channel_cnt; - attr->info.avg_bps = opus_cfg.bit_rate; - attr->info.max_bps = opus_cfg.sample_rate * 2; - attr->info.frm_ptime = (pj_uint16_t)opus_cfg.frm_ptime; - attr->setting.frm_per_pkt = 1; + attr->info.pt = (pj_uint8_t)ci->pt; + attr->info.clock_rate = opus_cfg.sample_rate; + attr->info.channel_cnt = opus_cfg.channel_cnt; + attr->info.avg_bps = opus_cfg.bit_rate; + attr->info.max_bps = opus_cfg.sample_rate * 2; + attr->info.frm_ptime = (pj_uint16_t)opus_cfg.frm_ptime; + attr->setting.frm_per_pkt = 1; attr->info.pcm_bits_per_sample = 16; - attr->setting.vad = OPUS_DEFAULT_VAD; - attr->setting.plc = OPUS_DEFAULT_PLC; - attr->setting.packet_loss = opus_cfg.packet_loss; - attr->setting.complexity = opus_cfg.complexity; - attr->setting.cbr = opus_cfg.cbr; + attr->setting.vad = OPUS_DEFAULT_VAD; + attr->setting.plc = OPUS_DEFAULT_PLC; + attr->setting.packet_loss = opus_cfg.packet_loss; + attr->setting.complexity = opus_cfg.complexity; + attr->setting.cbr = opus_cfg.cbr; /* Set max RX frame size to 1275 (max Opus frame size) to anticipate * possible ptime change on the fly. @@ -527,26 +526,26 @@ static pj_status_t factory_default_attr( pjmedia_codec_factory *factory, * Enum codecs supported by this factory. */ static pj_status_t factory_enum_codecs( pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[] ) + unsigned *count, + pjmedia_codec_info codecs[] ) { PJ_UNUSED_ARG(factory); PJ_ASSERT_RETURN(codecs, PJ_EINVAL); if (*count > 0) { - pj_bzero(&codecs[0], sizeof(pjmedia_codec_info)); - codecs[0].type = PJMEDIA_TYPE_AUDIO; - codecs[0].pt = PJMEDIA_RTP_PT_OPUS; + pj_bzero(&codecs[0], sizeof(pjmedia_codec_info)); + codecs[0].type = PJMEDIA_TYPE_AUDIO; + codecs[0].pt = PJMEDIA_RTP_PT_OPUS; /* * RFC 7587, Section 7: * The media subtype ("opus") goes in SDP "a=rtpmap" as the encoding * name. The RTP clock rate in "a=rtpmap" MUST be 48000 and the * number of channels MUST be 2. - */ - codecs[0].encoding_name = pj_str("opus"); - codecs[0].clock_rate = 48000; - codecs[0].channel_cnt = 2; - *count = 1; + */ + codecs[0].encoding_name = pj_str("opus"); + codecs[0].clock_rate = 48000; + codecs[0].channel_cnt = 2; + *count = 1; } return PJ_SUCCESS; @@ -557,8 +556,8 @@ static pj_status_t factory_enum_codecs( pjmedia_codec_factory *factory, * Allocate a new Opus codec instance. */ static pj_status_t factory_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *ci, - pjmedia_codec **p_codec ) + const pjmedia_codec_info *ci, + pjmedia_codec **p_codec ) { pjmedia_codec *codec; pj_pool_t *pool; @@ -577,8 +576,8 @@ static pj_status_t factory_alloc_codec( pjmedia_codec_factory *factory, status = pj_mutex_create_simple (pool, "opus_mutex", &opus_data->mutex); if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; + pj_pool_release(pool); + return status; } pj_memcpy(&opus_data->cfg, &opus_cfg, sizeof(pjmedia_codec_opus_config)); @@ -596,7 +595,7 @@ static pj_status_t factory_alloc_codec( pjmedia_codec_factory *factory, * Free codec. */ static pj_status_t factory_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { struct opus_data *opus_data; @@ -607,7 +606,7 @@ static pj_status_t factory_dealloc_codec( pjmedia_codec_factory *factory, if (opus_data) { pj_mutex_destroy(opus_data->mutex); opus_data->mutex = NULL; - pj_pool_release(opus_data->pool); + pj_pool_release(opus_data->pool); } return PJ_SUCCESS; @@ -618,7 +617,7 @@ static pj_status_t factory_dealloc_codec( pjmedia_codec_factory *factory, * Init codec. */ static pj_status_t codec_init( pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(pool); @@ -630,7 +629,7 @@ static pj_status_t codec_init( pjmedia_codec *codec, * Open codec. */ static pj_status_t codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { struct opus_data *opus_data = (struct opus_data *)codec->codec_data; int idx, err; @@ -648,143 +647,143 @@ static pj_status_t codec_open( pjmedia_codec *codec, /* Allocate memory used by the codec */ if (!opus_data->enc) { - /* Allocate memory for max 2 channels */ - opus_data->enc = pj_pool_zalloc(opus_data->pool, - opus_encoder_get_size(2)); + /* Allocate memory for max 2 channels */ + opus_data->enc = pj_pool_zalloc(opus_data->pool, + opus_encoder_get_size(2)); } if (!opus_data->dec) { - /* Allocate memory for max 2 channels */ - opus_data->dec = pj_pool_zalloc(opus_data->pool, - opus_decoder_get_size(2)); + /* Allocate memory for max 2 channels */ + opus_data->dec = pj_pool_zalloc(opus_data->pool, + opus_decoder_get_size(2)); } if (!opus_data->enc_packer) { - opus_data->enc_packer = pj_pool_zalloc(opus_data->pool, - opus_repacketizer_get_size()); + opus_data->enc_packer = pj_pool_zalloc(opus_data->pool, + opus_repacketizer_get_size()); } if (!opus_data->dec_packer) { - opus_data->dec_packer = pj_pool_zalloc(opus_data->pool, - opus_repacketizer_get_size()); + opus_data->dec_packer = pj_pool_zalloc(opus_data->pool, + opus_repacketizer_get_size()); } if (!opus_data->enc || !opus_data->dec || - !opus_data->enc_packer || !opus_data->dec_packer) + !opus_data->enc_packer || !opus_data->dec_packer) { - PJ_LOG(2, (THIS_FILE, "Unable to allocate memory for the codec")); + PJ_LOG(2, (THIS_FILE, "Unable to allocate memory for the codec")); pj_mutex_unlock (opus_data->mutex); - return PJ_ENOMEM; + return PJ_ENOMEM; } /* Check max average bit rate */ idx = find_fmtp(&attr->setting.enc_fmtp, &STR_MAX_BIT_RATE, PJ_FALSE); if (idx >= 0) { - unsigned rate; - auto_bit_rate = PJ_FALSE; - rate = (unsigned)pj_strtoul(&attr->setting.enc_fmtp.param[idx].val); - if (rate < attr->info.avg_bps) - attr->info.avg_bps = rate; + unsigned rate; + auto_bit_rate = PJ_FALSE; + rate = (unsigned)pj_strtoul(&attr->setting.enc_fmtp.param[idx].val); + if (rate < attr->info.avg_bps) + attr->info.avg_bps = rate; } /* Check plc */ idx = find_fmtp(&attr->setting.enc_fmtp, &STR_INBAND_FEC, PJ_FALSE); if (idx >= 0) { - unsigned plc; - plc = (unsigned) pj_strtoul(&attr->setting.enc_fmtp.param[idx].val); - attr->setting.plc = plc > 0? PJ_TRUE: PJ_FALSE; + unsigned plc; + plc = (unsigned) pj_strtoul(&attr->setting.enc_fmtp.param[idx].val); + attr->setting.plc = plc > 0? PJ_TRUE: PJ_FALSE; } /* Check vad */ idx = find_fmtp(&attr->setting.enc_fmtp, &STR_DTX, PJ_FALSE); if (idx >= 0) { - unsigned vad; - vad = (unsigned) pj_strtoul(&attr->setting.enc_fmtp.param[idx].val); - attr->setting.vad = vad > 0? PJ_TRUE: PJ_FALSE; + unsigned vad; + vad = (unsigned) pj_strtoul(&attr->setting.enc_fmtp.param[idx].val); + attr->setting.vad = vad > 0? PJ_TRUE: PJ_FALSE; } /* Check cbr */ idx = find_fmtp(&attr->setting.enc_fmtp, &STR_CBR, PJ_FALSE); if (idx >= 0) { - unsigned cbr; - cbr = (unsigned) pj_strtoul(&attr->setting.enc_fmtp.param[idx].val); - opus_data->cfg.cbr = cbr > 0? PJ_TRUE: PJ_FALSE; + unsigned cbr; + cbr = (unsigned) pj_strtoul(&attr->setting.enc_fmtp.param[idx].val); + opus_data->cfg.cbr = cbr > 0? PJ_TRUE: PJ_FALSE; } /* Check max average bit rate */ idx = find_fmtp(&attr->setting.dec_fmtp, &STR_MAX_BIT_RATE, PJ_FALSE); if (idx >= 0) { - unsigned rate; - rate = (unsigned) pj_strtoul(&attr->setting.dec_fmtp.param[idx].val); - if (rate < attr->info.avg_bps) - attr->info.avg_bps = rate; + unsigned rate; + rate = (unsigned) pj_strtoul(&attr->setting.dec_fmtp.param[idx].val); + if (rate < attr->info.avg_bps) + attr->info.avg_bps = rate; } TRACE_((THIS_FILE, "%s:%d: sample_rate: %u", - __FUNCTION__, __LINE__, opus_data->cfg.sample_rate)); + __FUNCTION__, __LINE__, opus_data->cfg.sample_rate)); /* Initialize encoder */ err = opus_encoder_init(opus_data->enc, - opus_data->cfg.sample_rate, - attr->info.channel_cnt, - OPUS_APPLICATION_VOIP); + opus_data->cfg.sample_rate, + attr->info.channel_cnt, + OPUS_APPLICATION_VOIP); if (err != OPUS_OK) { - PJ_LOG(2, (THIS_FILE, "Unable to create encoder")); - pj_mutex_unlock (opus_data->mutex); - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(2, (THIS_FILE, "Unable to create encoder")); + pj_mutex_unlock (opus_data->mutex); + return PJMEDIA_CODEC_EFAILED; } /* Set signal type */ opus_encoder_ctl(opus_data->enc, OPUS_SET_SIGNAL(OPUS_SIGNAL_VOICE)); /* Set bitrate */ opus_encoder_ctl(opus_data->enc, OPUS_SET_BITRATE(auto_bit_rate? - OPUS_AUTO: - attr->info.avg_bps)); + OPUS_AUTO: + attr->info.avg_bps)); /* Set VAD */ opus_encoder_ctl(opus_data->enc, OPUS_SET_DTX(attr->setting.vad ? 1 : 0)); /* Set PLC */ opus_encoder_ctl(opus_data->enc, - OPUS_SET_INBAND_FEC(attr->setting.plc ? 1 : 0)); + OPUS_SET_INBAND_FEC(attr->setting.plc ? 1 : 0)); /* Set bandwidth */ opus_encoder_ctl(opus_data->enc, - OPUS_SET_MAX_BANDWIDTH(get_opus_bw_constant( - opus_data->cfg.sample_rate))); + OPUS_SET_MAX_BANDWIDTH(get_opus_bw_constant( + opus_data->cfg.sample_rate))); /* Set expected packet loss */ opus_encoder_ctl(opus_data->enc, - OPUS_SET_PACKET_LOSS_PERC(opus_data->cfg.packet_loss)); + OPUS_SET_PACKET_LOSS_PERC(opus_data->cfg.packet_loss)); /* Set complexity */ opus_encoder_ctl(opus_data->enc, - OPUS_SET_COMPLEXITY(opus_data->cfg.complexity)); + OPUS_SET_COMPLEXITY(opus_data->cfg.complexity)); /* Set constant bit rate */ opus_encoder_ctl(opus_data->enc, - OPUS_SET_VBR(opus_data->cfg.cbr ? 0 : 1)); + OPUS_SET_VBR(opus_data->cfg.cbr ? 0 : 1)); PJ_LOG(4, (THIS_FILE, "Initialize Opus encoder, sample rate: %d, " - "avg bitrate: %d%s, vad: %d, plc: %d, pkt loss: %d, " - "complexity: %d, constant bit rate: %d", - opus_data->cfg.sample_rate, - (auto_bit_rate? 0: attr->info.avg_bps), - (auto_bit_rate? "(auto)": ""), - attr->setting.vad?1:0, - attr->setting.plc?1:0, - opus_data->cfg.packet_loss, - opus_data->cfg.complexity, - opus_data->cfg.cbr?1:0)); + "avg bitrate: %d%s, vad: %d, plc: %d, pkt loss: %d, " + "complexity: %d, constant bit rate: %d", + opus_data->cfg.sample_rate, + (auto_bit_rate? 0: attr->info.avg_bps), + (auto_bit_rate? "(auto)": ""), + attr->setting.vad?1:0, + attr->setting.plc?1:0, + opus_data->cfg.packet_loss, + opus_data->cfg.complexity, + opus_data->cfg.cbr?1:0)); /* Initialize decoder */ err = opus_decoder_init (opus_data->dec, - opus_data->cfg.sample_rate, - attr->info.channel_cnt); + opus_data->cfg.sample_rate, + attr->info.channel_cnt); if (err != OPUS_OK) { - PJ_LOG(2, (THIS_FILE, "Unable to initialize decoder")); - pj_mutex_unlock (opus_data->mutex); - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(2, (THIS_FILE, "Unable to initialize decoder")); + pj_mutex_unlock (opus_data->mutex); + return PJMEDIA_CODEC_EFAILED; } /* Initialize temporary decode frames used for FEC */ opus_data->dec_frame[0].type = PJMEDIA_FRAME_TYPE_NONE; opus_data->dec_frame[0].buf = pj_pool_zalloc(opus_data->pool, - (opus_data->cfg.sample_rate / 1000) + (opus_data->cfg.sample_rate / 1000) * 60 * attr->info.channel_cnt * 2 /* bytes per sample */); opus_data->dec_frame[1].type = PJMEDIA_FRAME_TYPE_NONE; opus_data->dec_frame[1].buf = pj_pool_zalloc(opus_data->pool, - (opus_data->cfg.sample_rate / 1000) + (opus_data->cfg.sample_rate / 1000) * 60 * attr->info.channel_cnt * 2 /* bytes per sample */); opus_data->dec_frame_index = -1; @@ -811,7 +810,7 @@ static pj_status_t codec_close( pjmedia_codec *codec ) * Modify codec settings. */ static pj_status_t codec_modify( pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { struct opus_data *opus_data = (struct opus_data *)codec->codec_data; @@ -822,39 +821,39 @@ static pj_status_t codec_modify( pjmedia_codec *codec, /* Set bitrate */ opus_data->cfg.bit_rate = attr->info.avg_bps; opus_encoder_ctl(opus_data->enc, OPUS_SET_BITRATE(attr->info.avg_bps? - attr->info.avg_bps: - OPUS_AUTO)); + attr->info.avg_bps: + OPUS_AUTO)); /* Set VAD */ opus_encoder_ctl(opus_data->enc, OPUS_SET_DTX(attr->setting.vad ? 1 : 0)); /* Set PLC */ opus_encoder_ctl(opus_data->enc, - OPUS_SET_INBAND_FEC(attr->setting.plc ? 1 : 0)); + OPUS_SET_INBAND_FEC(attr->setting.plc ? 1 : 0)); /* Set bandwidth */ opus_encoder_ctl(opus_data->enc, - OPUS_SET_MAX_BANDWIDTH(get_opus_bw_constant( - attr->info.clock_rate))); + OPUS_SET_MAX_BANDWIDTH(get_opus_bw_constant( + attr->info.clock_rate))); /* Set expected packet loss */ opus_encoder_ctl(opus_data->enc, - OPUS_SET_PACKET_LOSS_PERC(attr->setting.packet_loss)); + OPUS_SET_PACKET_LOSS_PERC(attr->setting.packet_loss)); /* Set complexity */ opus_encoder_ctl(opus_data->enc, - OPUS_SET_COMPLEXITY(attr->setting.complexity)); + OPUS_SET_COMPLEXITY(attr->setting.complexity)); /* Set constant bit rate */ opus_encoder_ctl(opus_data->enc, - OPUS_SET_VBR(attr->setting.cbr ? 0 : 1)); + OPUS_SET_VBR(attr->setting.cbr ? 0 : 1)); PJ_LOG(4, (THIS_FILE, "Modifying Opus encoder, sample rate: %d, " - "avg bitrate: %d%s, vad: %d, plc: %d, pkt loss: %d, " - "complexity: %d, constant bit rate: %d", - attr->info.clock_rate, - (attr->info.avg_bps? attr->info.avg_bps: 0), - (attr->info.avg_bps? "": "(auto)"), - attr->setting.vad?1:0, - attr->setting.plc?1:0, - attr->setting.packet_loss, - attr->setting.complexity, - attr->setting.cbr?1:0)); + "avg bitrate: %d%s, vad: %d, plc: %d, pkt loss: %d, " + "complexity: %d, constant bit rate: %d", + attr->info.clock_rate, + (attr->info.avg_bps? attr->info.avg_bps: 0), + (attr->info.avg_bps? "": "(auto)"), + attr->setting.vad?1:0, + attr->setting.plc?1:0, + attr->setting.packet_loss, + attr->setting.complexity, + attr->setting.cbr?1:0)); pj_mutex_unlock (opus_data->mutex); return PJ_SUCCESS; @@ -865,11 +864,11 @@ static pj_status_t codec_modify( pjmedia_codec *codec, * Get frames in the packet. */ static pj_status_t codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[] ) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[] ) { struct opus_data *opus_data = (struct opus_data *)codec->codec_data; unsigned char tmp_buf[MAX_ENCODED_PACKET_SIZE]; @@ -883,9 +882,9 @@ static pj_status_t codec_parse( pjmedia_codec *codec, pj_mutex_lock (opus_data->mutex); if (pkt_size > sizeof(tmp_buf)) { - PJ_LOG(5, (THIS_FILE, "Encoded size bigger than buffer")); + PJ_LOG(5, (THIS_FILE, "Encoded size bigger than buffer")); pj_mutex_unlock (opus_data->mutex); - return PJMEDIA_CODEC_EFRMTOOSHORT; + return PJMEDIA_CODEC_EFRMTOOSHORT; } pj_memcpy(tmp_buf, pkt, pkt_size); @@ -902,50 +901,50 @@ static pj_status_t codec_parse( pjmedia_codec *codec, out_pos = 0; for (i = 0; i < num_frames; ++i) { - size = opus_repacketizer_out_range(opus_data->dec_packer, i, i+1, - ((unsigned char*)pkt) + out_pos, - sizeof(tmp_buf)); - if (size < 0) { - PJ_LOG(5, (THIS_FILE, "Parse failed! (pkt_size=%d, err=%d)", - pkt_size, size)); + size = opus_repacketizer_out_range(opus_data->dec_packer, i, i+1, + ((unsigned char*)pkt) + out_pos, + sizeof(tmp_buf)); + if (size < 0) { + PJ_LOG(5, (THIS_FILE, "Parse failed! (pkt_size=%d, err=%d)", + pkt_size, size)); pj_mutex_unlock (opus_data->mutex); - return PJMEDIA_CODEC_EFAILED; - } - frames[i].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[i].buf = ((char*)pkt) + out_pos; - frames[i].size = size; - frames[i].bit_info = 0; - - if (i == 0) { - int nsamples; - unsigned ptime; - - nsamples = opus_packet_get_nb_samples(frames[i].buf, - frames[i].size, - opus_data->cfg.sample_rate); - if (nsamples <= 0) { - PJ_LOG(5, (THIS_FILE, "Parse failed to get samples number! " - "(err=%d)", nsamples)); - pj_mutex_unlock (opus_data->mutex); - return PJMEDIA_CODEC_EFAILED; - } - - ptime = nsamples * 1000 / opus_data->cfg.sample_rate; - if (ptime != opus_data->dec_ptime) { - PJ_LOG(4, (THIS_FILE, "Opus ptime change detected: %d ms " - "--> %d ms", - opus_data->dec_ptime, ptime)); - opus_data->dec_ptime = ptime; - opus_data->dec_frame_index = -1; - - /* Signal to the stream about ptime change. */ - frames[i].bit_info = 0x10000 | nsamples; - } - samples_per_frame = nsamples; - } - - frames[i].timestamp.u64 = ts->u64 + i * samples_per_frame; - out_pos += size; + return PJMEDIA_CODEC_EFAILED; + } + frames[i].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[i].buf = ((char*)pkt) + out_pos; + frames[i].size = size; + frames[i].bit_info = 0; + + if (i == 0) { + int nsamples; + unsigned ptime; + + nsamples = opus_packet_get_nb_samples(frames[i].buf, + frames[i].size, + opus_data->cfg.sample_rate); + if (nsamples <= 0) { + PJ_LOG(5, (THIS_FILE, "Parse failed to get samples number! " + "(err=%d)", nsamples)); + pj_mutex_unlock (opus_data->mutex); + return PJMEDIA_CODEC_EFAILED; + } + + ptime = nsamples * 1000 / opus_data->cfg.sample_rate; + if (ptime != opus_data->dec_ptime) { + PJ_LOG(4, (THIS_FILE, "Opus ptime change detected: %d ms " + "--> %d ms", + opus_data->dec_ptime, ptime)); + opus_data->dec_ptime = ptime; + opus_data->dec_frame_index = -1; + + /* Signal to the stream about ptime change. */ + frames[i].bit_info = 0x10000 | nsamples; + } + samples_per_frame = nsamples; + } + + frames[i].timestamp.u64 = ts->u64 + i * samples_per_frame; + out_pos += size; } *frame_cnt = num_frames; @@ -958,9 +957,9 @@ static pj_status_t codec_parse( pjmedia_codec *codec, * Encode frame. */ static pj_status_t codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output ) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output ) { struct opus_data *opus_data = (struct opus_data *)codec->codec_data; opus_int32 size = 0; @@ -974,50 +973,50 @@ static pj_status_t codec_encode( pjmedia_codec *codec, pj_mutex_lock (opus_data->mutex); samples_per_frame = (opus_data->cfg.sample_rate * - opus_data->enc_ptime) / 1000; + opus_data->enc_ptime) / 1000; frame_size = samples_per_frame * opus_data->cfg.channel_cnt * - sizeof(opus_int16); + sizeof(opus_int16); opus_repacketizer_init(opus_data->enc_packer); while (input->size - in_pos >= frame_size) { - size = opus_encode(opus_data->enc, - (const opus_int16*)(((char*)input->buf) + in_pos), - samples_per_frame, - tmp_buf + out_pos, - (tmp_bytes_left < frame_size ? - tmp_bytes_left : frame_size)); - if (size < 0) { - PJ_LOG(4, (THIS_FILE, "Encode failed! (%d)", size)); + size = opus_encode(opus_data->enc, + (const opus_int16*)(((char*)input->buf) + in_pos), + samples_per_frame, + tmp_buf + out_pos, + (tmp_bytes_left < frame_size ? + tmp_bytes_left : frame_size)); + if (size < 0) { + PJ_LOG(4, (THIS_FILE, "Encode failed! (%d)", size)); pj_mutex_unlock (opus_data->mutex); - return PJMEDIA_CODEC_EFAILED; - } else if (size > 0) { - /* Only add packets containing more than the TOC */ - opus_repacketizer_cat(opus_data->enc_packer, - tmp_buf + out_pos, - size); - out_pos += size; - tmp_bytes_left -= size; - } - in_pos += frame_size; + return PJMEDIA_CODEC_EFAILED; + } else if (size > 0) { + /* Only add packets containing more than the TOC */ + opus_repacketizer_cat(opus_data->enc_packer, + tmp_buf + out_pos, + size); + out_pos += size; + tmp_bytes_left -= size; + } + in_pos += frame_size; } if (!opus_repacketizer_get_nb_frames(opus_data->enc_packer)) { - /* Empty packet */ - output->size = 0; - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->timestamp = input->timestamp; + /* Empty packet */ + output->size = 0; + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->timestamp = input->timestamp; } if (size) { - size = opus_repacketizer_out(opus_data->enc_packer, - output->buf, - output_buf_len); - if (size < 0) { - PJ_LOG(4, (THIS_FILE, "Encode failed! (%d), out_size: %u", - size, output_buf_len)); - pj_mutex_unlock (opus_data->mutex); - return PJMEDIA_CODEC_EFAILED; - } + size = opus_repacketizer_out(opus_data->enc_packer, + output->buf, + output_buf_len); + if (size < 0) { + PJ_LOG(4, (THIS_FILE, "Encode failed! (%d), out_size: %u", + size, output_buf_len)); + pj_mutex_unlock (opus_data->mutex); + return PJMEDIA_CODEC_EFAILED; + } } output->size = (unsigned)size; @@ -1033,9 +1032,9 @@ static pj_status_t codec_encode( pjmedia_codec *codec, * Decode frame. */ static pj_status_t codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output ) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output ) { struct opus_data *opus_data = (struct opus_data *)codec->codec_data; int decoded_samples; @@ -1087,9 +1086,9 @@ static pj_status_t codec_decode( pjmedia_codec *codec, frm_size = output->size / (sizeof(opus_int16) * opus_data->cfg.channel_cnt); if (inframe->type != PJMEDIA_FRAME_TYPE_AUDIO || fec) { - frm_size = PJ_MIN((unsigned)frm_size, - opus_data->cfg.sample_rate * - opus_data->dec_ptime / 1000); + frm_size = PJ_MIN((unsigned)frm_size, + opus_data->cfg.sample_rate * + opus_data->dec_ptime / 1000); } decoded_samples = opus_decode( opus_data->dec, inframe->type==PJMEDIA_FRAME_TYPE_AUDIO ? @@ -1123,7 +1122,7 @@ static pj_status_t codec_decode( pjmedia_codec *codec, } output->size = decoded_samples * sizeof(opus_int16) * - opus_data->cfg.channel_cnt; + opus_data->cfg.channel_cnt; output->type = PJMEDIA_FRAME_TYPE_AUDIO; pj_mutex_unlock (opus_data->mutex); @@ -1135,8 +1134,8 @@ static pj_status_t codec_decode( pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t codec_recover( pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output ) + unsigned output_buf_len, + struct pjmedia_frame *output ) { struct opus_data *opus_data = (struct opus_data *)codec->codec_data; int decoded_samples; @@ -1148,12 +1147,12 @@ static pj_status_t codec_recover( pjmedia_codec *codec, if (opus_data->dec_frame_index == -1) { /* Recover the first packet? Don't think so, fill it with zeroes. */ - unsigned samples_per_frame; - samples_per_frame = opus_data->cfg.sample_rate * opus_data->dec_ptime/ - 1000; - output->type = PJMEDIA_FRAME_TYPE_AUDIO; - output->size = samples_per_frame << 1; - pjmedia_zero_samples((pj_int16_t*)output->buf, samples_per_frame); + unsigned samples_per_frame; + samples_per_frame = opus_data->cfg.sample_rate * opus_data->dec_ptime/ + 1000; + output->type = PJMEDIA_FRAME_TYPE_AUDIO; + output->size = samples_per_frame << 1; + pjmedia_zero_samples((pj_int16_t*)output->buf, samples_per_frame); pj_mutex_unlock (opus_data->mutex); return PJ_SUCCESS; @@ -1163,17 +1162,17 @@ static pj_status_t codec_recover( pjmedia_codec *codec, frm_size = output->size / (sizeof(opus_int16) * opus_data->cfg.channel_cnt); if (inframe->type != PJMEDIA_FRAME_TYPE_AUDIO) { - frm_size = PJ_MIN((unsigned)frm_size, opus_data->cfg.sample_rate * - opus_data->dec_ptime/1000); + frm_size = PJ_MIN((unsigned)frm_size, opus_data->cfg.sample_rate * + opus_data->dec_ptime/1000); } decoded_samples = opus_decode(opus_data->dec, - inframe->type==PJMEDIA_FRAME_TYPE_AUDIO ? - inframe->buf : NULL, - inframe->type==PJMEDIA_FRAME_TYPE_AUDIO ? - inframe->size : 0, - (opus_int16*)output->buf, - frm_size, - 0); + inframe->type==PJMEDIA_FRAME_TYPE_AUDIO ? + inframe->buf : NULL, + inframe->type==PJMEDIA_FRAME_TYPE_AUDIO ? + inframe->size : 0, + (opus_int16*)output->buf, + frm_size, + 0); /* Mark current indexed frame as invalid */ inframe->type = PJMEDIA_FRAME_TYPE_NONE; @@ -1193,7 +1192,7 @@ static pj_status_t codec_recover( pjmedia_codec *codec, } output->size = decoded_samples * sizeof(opus_int16) * - opus_data->cfg.channel_cnt; + opus_data->cfg.channel_cnt; output->type = PJMEDIA_FRAME_TYPE_AUDIO; output->timestamp = inframe->timestamp; diff --git a/pjmedia/src/pjmedia-codec/passthrough.c b/pjmedia/src/pjmedia-codec/passthrough.c index 4eeb35177b..79db3bce8c 100644 --- a/pjmedia/src/pjmedia-codec/passthrough.c +++ b/pjmedia/src/pjmedia-codec/passthrough.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -40,44 +39,44 @@ /* Prototypes for passthrough codecs factory */ static pj_status_t test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ); + const pjmedia_codec_info *id ); static pj_status_t default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ); static pj_status_t enum_codecs( pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for passthrough codecs implementation. */ static pj_status_t codec_init( pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t codec_close( pjmedia_codec *codec ); static pj_status_t codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t codec_recover( pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); /* Definition for passthrough codecs operations. */ static pjmedia_codec_op codec_op = @@ -106,21 +105,21 @@ static pjmedia_codec_factory_op codec_factory_op = /* Passthrough codecs factory */ static struct codec_factory { pjmedia_codec_factory base; - pjmedia_endpt *endpt; - pj_pool_t *pool; - pj_mutex_t *mutex; + pjmedia_endpt *endpt; + pj_pool_t *pool; + pj_mutex_t *mutex; } codec_factory; /* Passthrough codecs private data. */ typedef struct codec_private { - pj_pool_t *pool; /**< Pool for each instance. */ - int codec_idx; /**< Codec index. */ - void *codec_setting; /**< Specific codec setting. */ - pj_uint16_t avg_frame_size; /**< Average of frame size. */ - unsigned samples_per_frame; /**< Samples per frame, for iLBC - this can be 240 or 160, can - only be known after codec is - opened. */ + pj_pool_t *pool; /**< Pool for each instance. */ + int codec_idx; /**< Codec index. */ + void *codec_setting; /**< Specific codec setting. */ + pj_uint16_t avg_frame_size; /**< Average of frame size. */ + unsigned samples_per_frame; /**< Samples per frame, for iLBC + this can be 240 or 160, can + only be known after codec is + opened. */ } codec_private_t; @@ -133,8 +132,8 @@ typedef struct codec_private { * unapplicable. */ typedef pj_status_t (*parse_cb)(codec_private_t *codec_data, void *pkt, - pj_size_t pkt_size, const pj_timestamp *ts, - unsigned *frame_cnt, pjmedia_frame frames[]); + pj_size_t pkt_size, const pj_timestamp *ts, + unsigned *frame_cnt, pjmedia_frame frames[]); /* Pack frames into a packet. Default behaviour of packing frames is * just stacking the frames with octet aligned without adding any @@ -142,78 +141,78 @@ typedef pj_status_t (*parse_cb)(codec_private_t *codec_data, void *pkt, * unapplicable. */ typedef pj_status_t (*pack_cb)(codec_private_t *codec_data, - const struct pjmedia_frame_ext *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame_ext *input, + unsigned output_buf_len, + struct pjmedia_frame *output); /* Custom callback implementations. */ static pj_status_t parse_amr( codec_private_t *codec_data, void *pkt, - pj_size_t pkt_size, const pj_timestamp *ts, - unsigned *frame_cnt, pjmedia_frame frames[]); + pj_size_t pkt_size, const pj_timestamp *ts, + unsigned *frame_cnt, pjmedia_frame frames[]); static pj_status_t pack_amr ( codec_private_t *codec_data, - const struct pjmedia_frame_ext *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame_ext *input, + unsigned output_buf_len, + struct pjmedia_frame *output); /* Passthrough codec implementation descriptions. */ static struct codec_desc { - int enabled; /* Is this codec enabled? */ - const char *name; /* Codec name. */ - pj_uint8_t pt; /* Payload type. */ - pjmedia_format_id fmt_id; /* Source format. */ - unsigned clock_rate; /* Codec's clock rate. */ - unsigned channel_count; /* Codec's channel count. */ - unsigned samples_per_frame; /* Codec's samples count. */ - unsigned def_bitrate; /* Default bitrate of this codec. */ - unsigned max_bitrate; /* Maximum bitrate of this codec. */ - pj_uint8_t frm_per_pkt; /* Default num of frames per packet.*/ - pj_uint8_t vad; /* VAD enabled/disabled. */ - pj_uint8_t plc; /* PLC enabled/disabled. */ - parse_cb parse; /* Callback to parse bitstream. */ - pack_cb pack; /* Callback to pack bitstream. */ - pjmedia_codec_fmtp dec_fmtp; /* Decoder's fmtp params. */ + int enabled; /* Is this codec enabled? */ + const char *name; /* Codec name. */ + pj_uint8_t pt; /* Payload type. */ + pjmedia_format_id fmt_id; /* Source format. */ + unsigned clock_rate; /* Codec's clock rate. */ + unsigned channel_count; /* Codec's channel count. */ + unsigned samples_per_frame; /* Codec's samples count. */ + unsigned def_bitrate; /* Default bitrate of this codec. */ + unsigned max_bitrate; /* Maximum bitrate of this codec. */ + pj_uint8_t frm_per_pkt; /* Default num of frames per packet.*/ + pj_uint8_t vad; /* VAD enabled/disabled. */ + pj_uint8_t plc; /* PLC enabled/disabled. */ + parse_cb parse; /* Callback to parse bitstream. */ + pack_cb pack; /* Callback to pack bitstream. */ + pjmedia_codec_fmtp dec_fmtp; /* Decoder's fmtp params. */ } codec_desc[] = { # if PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR - {1, "AMR", PJMEDIA_RTP_PT_AMR, PJMEDIA_FORMAT_AMR, - 8000, 1, 160, - 7400, 12200, 2, 1, 1, - &parse_amr, &pack_amr - /*, {1, {{{"octet-align", 11}, {"1", 1}}} } */ + {1, "AMR", PJMEDIA_RTP_PT_AMR, PJMEDIA_FORMAT_AMR, + 8000, 1, 160, + 7400, 12200, 2, 1, 1, + &parse_amr, &pack_amr + /*, {1, {{{"octet-align", 11}, {"1", 1}}} } */ }, # endif # if PJMEDIA_HAS_PASSTHROUGH_CODEC_G729 - {1, "G729", PJMEDIA_RTP_PT_G729, PJMEDIA_FORMAT_G729, - 8000, 1, 80, - 8000, 8000, 2, 1, 1 + {1, "G729", PJMEDIA_RTP_PT_G729, PJMEDIA_FORMAT_G729, + 8000, 1, 80, + 8000, 8000, 2, 1, 1 }, # endif # if PJMEDIA_HAS_PASSTHROUGH_CODEC_ILBC - {1, "iLBC", PJMEDIA_RTP_PT_ILBC, PJMEDIA_FORMAT_ILBC, - 8000, 1, 240, - 13333, 15200, 1, 1, 1, - NULL, NULL, - {1, {{{"mode", 4}, {"30", 2}}} } + {1, "iLBC", PJMEDIA_RTP_PT_ILBC, PJMEDIA_FORMAT_ILBC, + 8000, 1, 240, + 13333, 15200, 1, 1, 1, + NULL, NULL, + {1, {{{"mode", 4}, {"30", 2}}} } }, # endif # if PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMU - {1, "PCMU", PJMEDIA_RTP_PT_PCMU, PJMEDIA_FORMAT_PCMU, - 8000, 1, 80, - 64000, 64000, 2, 1, 1 + {1, "PCMU", PJMEDIA_RTP_PT_PCMU, PJMEDIA_FORMAT_PCMU, + 8000, 1, 80, + 64000, 64000, 2, 1, 1 }, # endif # if PJMEDIA_HAS_PASSTHROUGH_CODEC_PCMA - {1, "PCMA", PJMEDIA_RTP_PT_PCMA, PJMEDIA_FORMAT_PCMA, - 8000, 1, 80, - 64000, 64000, 2, 1, 1 + {1, "PCMA", PJMEDIA_RTP_PT_PCMA, PJMEDIA_FORMAT_PCMA, + 8000, 1, 80, + 64000, 64000, 2, 1, 1 }, # endif }; @@ -232,9 +231,9 @@ typedef struct amr_settings_t { /* Pack AMR payload */ static pj_status_t pack_amr ( codec_private_t *codec_data, - const struct pjmedia_frame_ext *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame_ext *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { enum {MAX_FRAMES_PER_PACKET = PJMEDIA_MAX_FRAME_DURATION_MS / 20}; @@ -250,43 +249,43 @@ static pj_status_t pack_amr ( codec_private_t *codec_data, /* Get frames */ for (i = 0; i < input->subframe_cnt; ++i) { - pjmedia_frame_ext_subframe *sf; - pjmedia_codec_amr_bit_info *info; - unsigned len; - - sf = pjmedia_frame_ext_get_subframe(input, i); - len = (sf->bitlen + 7) >> 3; - - info = (pjmedia_codec_amr_bit_info*) &frames[i].bit_info; - pj_bzero(info, sizeof(*info)); - - if (len == 0) { - /* DTX */ - info->frame_type = 15; - } else { - info->frame_type = pjmedia_codec_amr_get_mode2(enc_setting->amr_nb, - len); - } - info->good_quality = 1; - info->mode = setting->enc_mode; - if (info->frame_type == SID_FT) - info->STI = (sf->data[4] >> 4) & 1; - - frames[i].buf = sf->data; - frames[i].size = len; + pjmedia_frame_ext_subframe *sf; + pjmedia_codec_amr_bit_info *info; + unsigned len; + + sf = pjmedia_frame_ext_get_subframe(input, i); + len = (sf->bitlen + 7) >> 3; + + info = (pjmedia_codec_amr_bit_info*) &frames[i].bit_info; + pj_bzero(info, sizeof(*info)); + + if (len == 0) { + /* DTX */ + info->frame_type = 15; + } else { + info->frame_type = pjmedia_codec_amr_get_mode2(enc_setting->amr_nb, + len); + } + info->good_quality = 1; + info->mode = setting->enc_mode; + if (info->frame_type == SID_FT) + info->STI = (sf->data[4] >> 4) & 1; + + frames[i].buf = sf->data; + frames[i].size = len; } output->size = output_buf_len; return pjmedia_codec_amr_pack(frames, input->subframe_cnt, enc_setting, - output->buf, &output->size); + output->buf, &output->size); } /* Parse AMR payload into frames. */ static pj_status_t parse_amr(codec_private_t *codec_data, void *pkt, - pj_size_t pkt_size, const pj_timestamp *ts, - unsigned *frame_cnt, pjmedia_frame frames[]) + pj_size_t pkt_size, const pj_timestamp *ts, + unsigned *frame_cnt, pjmedia_frame frames[]) { amr_settings_t* s = (amr_settings_t*)codec_data->codec_setting; pjmedia_codec_amr_pack_setting *setting; @@ -296,14 +295,14 @@ static pj_status_t parse_amr(codec_private_t *codec_data, void *pkt, setting = &s->dec_setting; status = pjmedia_codec_amr_parse(pkt, pkt_size, ts, setting, frames, - frame_cnt, &cmr); + frame_cnt, &cmr); if (status != PJ_SUCCESS) - return status; + return status; // CMR is not supported for now. /* Check Change Mode Request. */ //if ((setting->amr_nb && cmr <= 7) || (!setting->amr_nb && cmr <= 8)) { - // s->enc_mode = cmr; + // s->enc_mode = cmr; //} return PJ_SUCCESS; @@ -322,8 +321,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_passthrough_init( pjmedia_endpt *endpt ) pj_status_t status; if (codec_factory.pool != NULL) { - /* Already initialized. */ - return PJ_EEXISTS; + /* Already initialized. */ + return PJ_EEXISTS; } /* Create passthrough codec factory. */ @@ -332,31 +331,31 @@ PJ_DEF(pj_status_t) pjmedia_codec_passthrough_init( pjmedia_endpt *endpt ) codec_factory.endpt = endpt; codec_factory.pool = pjmedia_endpt_create_pool(endpt, "Passthrough codecs", - 4000, 4000); + 4000, 4000); if (!codec_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create mutex. */ status = pj_mutex_create_simple(codec_factory.pool, "Passthrough codecs", - &codec_factory.mutex); + &codec_factory.mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - status = PJ_EINVALIDOP; - goto on_error; + status = PJ_EINVALIDOP; + goto on_error; } /* Register format match callback. */ #if PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR pj_cstr(&codec_name, "AMR"); status = pjmedia_sdp_neg_register_fmt_match_cb( - &codec_name, - &pjmedia_codec_amr_match_sdp); + &codec_name, + &pjmedia_codec_amr_match_sdp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #endif /* Suppress compile warning */ @@ -364,9 +363,9 @@ PJ_DEF(pj_status_t) pjmedia_codec_passthrough_init( pjmedia_endpt *endpt ) /* Register codec factory to endpoint. */ status = pjmedia_codec_mgr_register_factory(codec_mgr, - &codec_factory.base); + &codec_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Done. */ return PJ_SUCCESS; @@ -381,45 +380,45 @@ PJ_DEF(pj_status_t) pjmedia_codec_passthrough_init( pjmedia_endpt *endpt ) * Initialize and register passthrough codec factory to pjmedia endpoint. */ PJ_DEF(pj_status_t) pjmedia_codec_passthrough_init2( - pjmedia_endpt *endpt, - const pjmedia_codec_passthrough_setting *setting) + pjmedia_endpt *endpt, + const pjmedia_codec_passthrough_setting *setting) { if (codec_factory.pool != NULL) { - /* Already initialized. */ - return PJ_EEXISTS; + /* Already initialized. */ + return PJ_EEXISTS; } if (setting != NULL) { - unsigned i; + unsigned i; - /* Enable/disable codecs based on the specified encoding formats */ - for (i = 0; i < PJ_ARRAY_SIZE(codec_desc); ++i) { - pj_bool_t enabled = PJ_FALSE; - unsigned j; + /* Enable/disable codecs based on the specified encoding formats */ + for (i = 0; i < PJ_ARRAY_SIZE(codec_desc); ++i) { + pj_bool_t enabled = PJ_FALSE; + unsigned j; - for (j = 0; j < setting->fmt_cnt && !enabled; ++j) { - if ((pj_uint32_t)codec_desc[i].fmt_id == setting->fmts[j].id) - enabled = PJ_TRUE; - } + for (j = 0; j < setting->fmt_cnt && !enabled; ++j) { + if ((pj_uint32_t)codec_desc[i].fmt_id == setting->fmts[j].id) + enabled = PJ_TRUE; + } - codec_desc[i].enabled = enabled; - } + codec_desc[i].enabled = enabled; + } #if PJMEDIA_HAS_PASSTHROUGH_CODEC_ILBC - /* Update iLBC codec description based on default mode setting. */ - for (i = 0; i < PJ_ARRAY_SIZE(codec_desc); ++i) { - if (codec_desc[i].enabled && - codec_desc[i].fmt_id == PJMEDIA_FORMAT_ILBC) - { - codec_desc[i].samples_per_frame = - (setting->ilbc_mode == 20? 160 : 240); - codec_desc[i].def_bitrate = - (setting->ilbc_mode == 20? 15200 : 13333); - pj_strset2(&codec_desc[i].dec_fmtp.param[0].val, - (setting->ilbc_mode == 20? "20" : "30")); - break; - } - } + /* Update iLBC codec description based on default mode setting. */ + for (i = 0; i < PJ_ARRAY_SIZE(codec_desc); ++i) { + if (codec_desc[i].enabled && + codec_desc[i].fmt_id == PJMEDIA_FORMAT_ILBC) + { + codec_desc[i].samples_per_frame = + (setting->ilbc_mode == 20? 160 : 240); + codec_desc[i].def_bitrate = + (setting->ilbc_mode == 20? 15200 : 13333); + pj_strset2(&codec_desc[i].dec_fmtp.param[0].val, + (setting->ilbc_mode == 20? "20" : "30")); + break; + } + } #endif } @@ -436,8 +435,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_passthrough_deinit(void) pj_status_t status; if (codec_factory.pool == NULL) { - /* Already deinitialized */ - return PJ_SUCCESS; + /* Already deinitialized */ + return PJ_SUCCESS; } pj_mutex_lock(codec_factory.mutex); @@ -445,15 +444,15 @@ PJ_DEF(pj_status_t) pjmedia_codec_passthrough_deinit(void) /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(codec_factory.endpt); if (!codec_mgr) { - pj_pool_release(codec_factory.pool); - codec_factory.pool = NULL; - pj_mutex_unlock(codec_factory.mutex); - return PJ_EINVALIDOP; + pj_pool_release(codec_factory.pool); + codec_factory.pool = NULL; + pj_mutex_unlock(codec_factory.mutex); + return PJ_EINVALIDOP; } /* Unregister passthrough codecs factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &codec_factory.base); + &codec_factory.base); /* Destroy mutex. */ pj_mutex_unlock(codec_factory.mutex); @@ -466,7 +465,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_passthrough_deinit(void) /* Re-enable all codecs in the codec_desc. */ for (i = 0; i < PJ_ARRAY_SIZE(codec_desc); ++i) { - codec_desc[i].enabled = PJ_TRUE; + codec_desc[i].enabled = PJ_TRUE; } return status; @@ -476,7 +475,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_passthrough_deinit(void) * Check if factory can allocate the specified codec. */ static pj_status_t test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *info ) + const pjmedia_codec_info *info ) { unsigned i; @@ -484,17 +483,17 @@ static pj_status_t test_alloc( pjmedia_codec_factory *factory, /* Type MUST be audio. */ if (info->type != PJMEDIA_TYPE_AUDIO) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; for (i = 0; i < PJ_ARRAY_SIZE(codec_desc); ++i) { - pj_str_t name = pj_str((char*)codec_desc[i].name); - if ((pj_stricmp(&info->encoding_name, &name) == 0) && - (info->clock_rate == (unsigned)codec_desc[i].clock_rate) && - (info->channel_cnt == (unsigned)codec_desc[i].channel_count) && - (codec_desc[i].enabled)) - { - return PJ_SUCCESS; - } + pj_str_t name = pj_str((char*)codec_desc[i].name); + if ((pj_stricmp(&info->encoding_name, &name) == 0) && + (info->clock_rate == (unsigned)codec_desc[i].clock_rate) && + (info->channel_cnt == (unsigned)codec_desc[i].channel_count) && + (codec_desc[i].enabled)) + { + return PJ_SUCCESS; + } } /* Unsupported, or mode is disabled. */ @@ -505,8 +504,8 @@ static pj_status_t test_alloc( pjmedia_codec_factory *factory, * Generate default attribute. */ static pj_status_t default_attr ( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ) { unsigned i; @@ -515,45 +514,45 @@ static pj_status_t default_attr ( pjmedia_codec_factory *factory, pj_bzero(attr, sizeof(pjmedia_codec_param)); for (i = 0; i < PJ_ARRAY_SIZE(codec_desc); ++i) { - pj_str_t name = pj_str((char*)codec_desc[i].name); - if ((pj_stricmp(&id->encoding_name, &name) == 0) && - (id->clock_rate == (unsigned)codec_desc[i].clock_rate) && - (id->channel_cnt == (unsigned)codec_desc[i].channel_count) && - (id->pt == (unsigned)codec_desc[i].pt)) - { - attr->info.pt = (pj_uint8_t)id->pt; - attr->info.channel_cnt = codec_desc[i].channel_count; - attr->info.clock_rate = codec_desc[i].clock_rate; - attr->info.avg_bps = codec_desc[i].def_bitrate; - attr->info.max_bps = codec_desc[i].max_bitrate; - attr->info.pcm_bits_per_sample = 16; - attr->info.frm_ptime = (pj_uint16_t) - (codec_desc[i].samples_per_frame * 1000 / - codec_desc[i].channel_count / - codec_desc[i].clock_rate); - attr->info.fmt_id = codec_desc[i].fmt_id; - - /* Default flags. */ - attr->setting.frm_per_pkt = codec_desc[i].frm_per_pkt; - attr->setting.plc = codec_desc[i].plc; - attr->setting.penh= 0; - attr->setting.vad = codec_desc[i].vad; - attr->setting.cng = attr->setting.vad; - attr->setting.dec_fmtp = codec_desc[i].dec_fmtp; - - if (attr->setting.vad == 0) { + pj_str_t name = pj_str((char*)codec_desc[i].name); + if ((pj_stricmp(&id->encoding_name, &name) == 0) && + (id->clock_rate == (unsigned)codec_desc[i].clock_rate) && + (id->channel_cnt == (unsigned)codec_desc[i].channel_count) && + (id->pt == (unsigned)codec_desc[i].pt)) + { + attr->info.pt = (pj_uint8_t)id->pt; + attr->info.channel_cnt = codec_desc[i].channel_count; + attr->info.clock_rate = codec_desc[i].clock_rate; + attr->info.avg_bps = codec_desc[i].def_bitrate; + attr->info.max_bps = codec_desc[i].max_bitrate; + attr->info.pcm_bits_per_sample = 16; + attr->info.frm_ptime = (pj_uint16_t) + (codec_desc[i].samples_per_frame * 1000 / + codec_desc[i].channel_count / + codec_desc[i].clock_rate); + attr->info.fmt_id = codec_desc[i].fmt_id; + + /* Default flags. */ + attr->setting.frm_per_pkt = codec_desc[i].frm_per_pkt; + attr->setting.plc = codec_desc[i].plc; + attr->setting.penh= 0; + attr->setting.vad = codec_desc[i].vad; + attr->setting.cng = attr->setting.vad; + attr->setting.dec_fmtp = codec_desc[i].dec_fmtp; + + if (attr->setting.vad == 0) { #if PJMEDIA_HAS_PASSTHROUGH_CODEC_G729 - if (id->pt == PJMEDIA_RTP_PT_G729) { - /* Signal G729 Annex B is being disabled */ - attr->setting.dec_fmtp.cnt = 1; - pj_strset2(&attr->setting.dec_fmtp.param[0].name, "annexb"); - pj_strset2(&attr->setting.dec_fmtp.param[0].val, "no"); - } + if (id->pt == PJMEDIA_RTP_PT_G729) { + /* Signal G729 Annex B is being disabled */ + attr->setting.dec_fmtp.cnt = 1; + pj_strset2(&attr->setting.dec_fmtp.param[0].name, "annexb"); + pj_strset2(&attr->setting.dec_fmtp.param[0].val, "no"); + } #endif - } + } - return PJ_SUCCESS; - } + return PJ_SUCCESS; + } } return PJMEDIA_CODEC_EUNSUP; @@ -563,8 +562,8 @@ static pj_status_t default_attr ( pjmedia_codec_factory *factory, * Enum codecs supported by this factory. */ static pj_status_t enum_codecs( pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]) + unsigned *count, + pjmedia_codec_info codecs[]) { unsigned max; unsigned i; @@ -576,17 +575,17 @@ static pj_status_t enum_codecs( pjmedia_codec_factory *factory, for (i = 0, *count = 0; i < PJ_ARRAY_SIZE(codec_desc) && *count < max; ++i) { - if (!codec_desc[i].enabled) - continue; + if (!codec_desc[i].enabled) + continue; - pj_bzero(&codecs[*count], sizeof(pjmedia_codec_info)); - codecs[*count].encoding_name = pj_str((char*)codec_desc[i].name); - codecs[*count].pt = codec_desc[i].pt; - codecs[*count].type = PJMEDIA_TYPE_AUDIO; - codecs[*count].clock_rate = codec_desc[i].clock_rate; - codecs[*count].channel_cnt = codec_desc[i].channel_count; + pj_bzero(&codecs[*count], sizeof(pjmedia_codec_info)); + codecs[*count].encoding_name = pj_str((char*)codec_desc[i].name); + codecs[*count].pt = codec_desc[i].pt; + codecs[*count].type = PJMEDIA_TYPE_AUDIO; + codecs[*count].clock_rate = codec_desc[i].clock_rate; + codecs[*count].channel_cnt = codec_desc[i].channel_count; - ++*count; + ++*count; } return PJ_SUCCESS; @@ -596,8 +595,8 @@ static pj_status_t enum_codecs( pjmedia_codec_factory *factory, * Allocate a new codec instance. */ static pj_status_t alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { codec_private_t *codec_data; pjmedia_codec *codec; @@ -613,25 +612,25 @@ static pj_status_t alloc_codec( pjmedia_codec_factory *factory, /* Find codec's index */ idx = -1; for (i = 0; i < PJ_ARRAY_SIZE(codec_desc); ++i) { - pj_str_t name = pj_str((char*)codec_desc[i].name); - if ((pj_stricmp(&id->encoding_name, &name) == 0) && - (id->clock_rate == (unsigned)codec_desc[i].clock_rate) && - (id->channel_cnt == (unsigned)codec_desc[i].channel_count) && - (codec_desc[i].enabled)) - { - idx = i; - break; - } + pj_str_t name = pj_str((char*)codec_desc[i].name); + if ((pj_stricmp(&id->encoding_name, &name) == 0) && + (id->clock_rate == (unsigned)codec_desc[i].clock_rate) && + (id->channel_cnt == (unsigned)codec_desc[i].channel_count) && + (codec_desc[i].enabled)) + { + idx = i; + break; + } } if (idx == -1) { - *p_codec = NULL; - pj_mutex_unlock(codec_factory.mutex); - return PJMEDIA_CODEC_EUNSUP; + *p_codec = NULL; + pj_mutex_unlock(codec_factory.mutex); + return PJMEDIA_CODEC_EUNSUP; } /* Create pool for codec instance */ pool = pjmedia_endpt_create_pool(codec_factory.endpt, "passthroughcodec", - 512, 512); + 512, 512); codec = PJ_POOL_ZALLOC_T(pool, pjmedia_codec); codec->op = &codec_op; codec->factory = factory; @@ -650,7 +649,7 @@ static pj_status_t alloc_codec( pjmedia_codec_factory *factory, * Free codec. */ static pj_status_t dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { codec_private_t *codec_data; @@ -670,7 +669,7 @@ static pj_status_t dealloc_codec( pjmedia_codec_factory *factory, * Init codec. */ static pj_status_t codec_init( pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(pool); @@ -681,7 +680,7 @@ static pj_status_t codec_init( pjmedia_codec *codec, * Open codec. */ static pj_status_t codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { codec_private_t *codec_data = (codec_private_t*) codec->codec_data; struct codec_desc *desc = &codec_desc[codec_data->codec_idx]; @@ -702,99 +701,99 @@ static pj_status_t codec_open( pjmedia_codec *codec, #if PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR /* Init AMR settings */ if (desc->pt == PJMEDIA_RTP_PT_AMR || desc->pt == PJMEDIA_RTP_PT_AMRWB) { - amr_settings_t *s; - pj_uint8_t octet_align = 0; - pj_int8_t enc_mode; - - enc_mode = pjmedia_codec_amr_get_mode(attr->info.avg_bps); - pj_assert(enc_mode >= 0 && enc_mode <= 8); - - for (i = 0; i < attr->setting.dec_fmtp.cnt; ++i) { - const pj_str_t STR_FMTP_OCTET_ALIGN = {"octet-align", 11}; - - /* Fetch octet-align setting. It should be fine to fetch only - * the decoder, since encoder & decoder must use the same setting - * (RFC 4867 section 8.3.1). - */ - if (pj_stricmp(&attr->setting.dec_fmtp.param[i].name, - &STR_FMTP_OCTET_ALIGN) == 0) - { - octet_align=(pj_uint8_t) - (pj_strtoul(&attr->setting.dec_fmtp.param[i].val)); - break; - } - } - - for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { - const pj_str_t STR_FMTP_MODE_SET = {"mode-set", 8}; - - /* mode-set, encoding mode is chosen based on local default mode - * setting: - * - if local default mode is included in the mode-set, use it - * - otherwise, find the closest mode to local default mode; - * if there are two closest modes, prefer to use the higher - * one, e.g: local default mode is 4, the mode-set param - * contains '2,3,5,6', then 5 will be chosen. - */ - if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name, - &STR_FMTP_MODE_SET) == 0) - { - const char *p; - pj_size_t l; - pj_int8_t diff = 99; - - p = pj_strbuf(&attr->setting.enc_fmtp.param[i].val); - l = pj_strlen(&attr->setting.enc_fmtp.param[i].val); - - while (l--) { - if ((desc->pt==PJMEDIA_RTP_PT_AMR && *p>='0' && *p<='7') || - (desc->pt==PJMEDIA_RTP_PT_AMRWB && *p>='0' && *p<='8')) - { - pj_int8_t tmp = (pj_int8_t)(*p - '0' - enc_mode); - - if (PJ_ABS(diff) > PJ_ABS(tmp) || - (PJ_ABS(diff) == PJ_ABS(tmp) && tmp > diff)) - { - diff = tmp; - if (diff == 0) break; - } - } - ++p; - } - - if (diff == 99) - return PJMEDIA_CODEC_EFAILED; - - enc_mode = (pj_int8_t)(enc_mode + diff); - - break; - } - } - - s = PJ_POOL_ZALLOC_T(pool, amr_settings_t); - codec_data->codec_setting = s; - - s->enc_mode = enc_mode; - if (s->enc_mode < 0) - return PJMEDIA_CODEC_EINMODE; - - s->enc_setting.amr_nb = (pj_uint8_t)(desc->pt == PJMEDIA_RTP_PT_AMR); - s->enc_setting.octet_aligned = octet_align; - s->enc_setting.reorder = PJ_FALSE; /* Note this! passthrough codec - doesn't do sensitivity bits - reordering */ - s->enc_setting.cmr = 15; - - s->dec_setting.amr_nb = (pj_uint8_t)(desc->pt == PJMEDIA_RTP_PT_AMR); - s->dec_setting.octet_aligned = octet_align; - s->dec_setting.reorder = PJ_FALSE; /* Note this! passthrough codec - doesn't do sensitivity bits - reordering */ - - /* Return back bitrate info to application */ - attr->info.avg_bps = s->enc_setting.amr_nb? - pjmedia_codec_amrnb_bitrates[s->enc_mode]: - pjmedia_codec_amrwb_bitrates[s->enc_mode]; + amr_settings_t *s; + pj_uint8_t octet_align = 0; + pj_int8_t enc_mode; + + enc_mode = pjmedia_codec_amr_get_mode(attr->info.avg_bps); + pj_assert(enc_mode >= 0 && enc_mode <= 8); + + for (i = 0; i < attr->setting.dec_fmtp.cnt; ++i) { + const pj_str_t STR_FMTP_OCTET_ALIGN = {"octet-align", 11}; + + /* Fetch octet-align setting. It should be fine to fetch only + * the decoder, since encoder & decoder must use the same setting + * (RFC 4867 section 8.3.1). + */ + if (pj_stricmp(&attr->setting.dec_fmtp.param[i].name, + &STR_FMTP_OCTET_ALIGN) == 0) + { + octet_align=(pj_uint8_t) + (pj_strtoul(&attr->setting.dec_fmtp.param[i].val)); + break; + } + } + + for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { + const pj_str_t STR_FMTP_MODE_SET = {"mode-set", 8}; + + /* mode-set, encoding mode is chosen based on local default mode + * setting: + * - if local default mode is included in the mode-set, use it + * - otherwise, find the closest mode to local default mode; + * if there are two closest modes, prefer to use the higher + * one, e.g: local default mode is 4, the mode-set param + * contains '2,3,5,6', then 5 will be chosen. + */ + if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name, + &STR_FMTP_MODE_SET) == 0) + { + const char *p; + pj_size_t l; + pj_int8_t diff = 99; + + p = pj_strbuf(&attr->setting.enc_fmtp.param[i].val); + l = pj_strlen(&attr->setting.enc_fmtp.param[i].val); + + while (l--) { + if ((desc->pt==PJMEDIA_RTP_PT_AMR && *p>='0' && *p<='7') || + (desc->pt==PJMEDIA_RTP_PT_AMRWB && *p>='0' && *p<='8')) + { + pj_int8_t tmp = (pj_int8_t)(*p - '0' - enc_mode); + + if (PJ_ABS(diff) > PJ_ABS(tmp) || + (PJ_ABS(diff) == PJ_ABS(tmp) && tmp > diff)) + { + diff = tmp; + if (diff == 0) break; + } + } + ++p; + } + + if (diff == 99) + return PJMEDIA_CODEC_EFAILED; + + enc_mode = (pj_int8_t)(enc_mode + diff); + + break; + } + } + + s = PJ_POOL_ZALLOC_T(pool, amr_settings_t); + codec_data->codec_setting = s; + + s->enc_mode = enc_mode; + if (s->enc_mode < 0) + return PJMEDIA_CODEC_EINMODE; + + s->enc_setting.amr_nb = (pj_uint8_t)(desc->pt == PJMEDIA_RTP_PT_AMR); + s->enc_setting.octet_aligned = octet_align; + s->enc_setting.reorder = PJ_FALSE; /* Note this! passthrough codec + doesn't do sensitivity bits + reordering */ + s->enc_setting.cmr = 15; + + s->dec_setting.amr_nb = (pj_uint8_t)(desc->pt == PJMEDIA_RTP_PT_AMR); + s->dec_setting.octet_aligned = octet_align; + s->dec_setting.reorder = PJ_FALSE; /* Note this! passthrough codec + doesn't do sensitivity bits + reordering */ + + /* Return back bitrate info to application */ + attr->info.avg_bps = s->enc_setting.amr_nb? + pjmedia_codec_amrnb_bitrates[s->enc_mode]: + pjmedia_codec_amrwb_bitrates[s->enc_mode]; } #endif @@ -802,58 +801,58 @@ static pj_status_t codec_open( pjmedia_codec *codec, /* Init iLBC settings */ if (desc->pt == PJMEDIA_RTP_PT_ILBC) { - enum { DEFAULT_MODE = 30 }; - static pj_str_t STR_MODE = {"mode", 4}; - pj_uint16_t dec_fmtp_mode = DEFAULT_MODE, - enc_fmtp_mode = DEFAULT_MODE; - - /* Get decoder mode */ - for (i = 0; i < attr->setting.dec_fmtp.cnt; ++i) { - if (pj_stricmp(&attr->setting.dec_fmtp.param[i].name, &STR_MODE) == 0) - { - dec_fmtp_mode = (pj_uint16_t) - pj_strtoul(&attr->setting.dec_fmtp.param[i].val); - break; - } - } - - /* Decoder mode must be set */ - PJ_ASSERT_RETURN(dec_fmtp_mode == 20 || dec_fmtp_mode == 30, - PJMEDIA_CODEC_EINMODE); - - /* Get encoder mode */ - for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { - if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name, &STR_MODE) == 0) - { - enc_fmtp_mode = (pj_uint16_t) - pj_strtoul(&attr->setting.enc_fmtp.param[i].val); - break; - } - } - - PJ_ASSERT_RETURN(enc_fmtp_mode==20 || enc_fmtp_mode==30, - PJMEDIA_CODEC_EINMODE); - - /* Both sides of a bi-directional session MUST use the same "mode" value. - * In this point, possible values are only 20 or 30, so when encoder and - * decoder modes are not same, just use the default mode, it is 30. - */ - if (enc_fmtp_mode != dec_fmtp_mode) { - enc_fmtp_mode = dec_fmtp_mode = DEFAULT_MODE; - PJ_LOG(4,(pool->obj_name, - "Normalized iLBC encoder and decoder modes to %d", - DEFAULT_MODE)); - } - - /* Update some attributes based on negotiated mode. */ - attr->info.avg_bps = (dec_fmtp_mode == 30? 13333 : 15200); - attr->info.frm_ptime = dec_fmtp_mode; - - /* Override average frame size */ - codec_data->avg_frame_size = (dec_fmtp_mode == 30? 50 : 38); - - /* Override samples per frame */ - codec_data->samples_per_frame = (dec_fmtp_mode == 30? 240 : 160); + enum { DEFAULT_MODE = 30 }; + static pj_str_t STR_MODE = {"mode", 4}; + pj_uint16_t dec_fmtp_mode = DEFAULT_MODE, + enc_fmtp_mode = DEFAULT_MODE; + + /* Get decoder mode */ + for (i = 0; i < attr->setting.dec_fmtp.cnt; ++i) { + if (pj_stricmp(&attr->setting.dec_fmtp.param[i].name, &STR_MODE) == 0) + { + dec_fmtp_mode = (pj_uint16_t) + pj_strtoul(&attr->setting.dec_fmtp.param[i].val); + break; + } + } + + /* Decoder mode must be set */ + PJ_ASSERT_RETURN(dec_fmtp_mode == 20 || dec_fmtp_mode == 30, + PJMEDIA_CODEC_EINMODE); + + /* Get encoder mode */ + for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { + if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name, &STR_MODE) == 0) + { + enc_fmtp_mode = (pj_uint16_t) + pj_strtoul(&attr->setting.enc_fmtp.param[i].val); + break; + } + } + + PJ_ASSERT_RETURN(enc_fmtp_mode==20 || enc_fmtp_mode==30, + PJMEDIA_CODEC_EINMODE); + + /* Both sides of a bi-directional session MUST use the same "mode" value. + * In this point, possible values are only 20 or 30, so when encoder and + * decoder modes are not same, just use the default mode, it is 30. + */ + if (enc_fmtp_mode != dec_fmtp_mode) { + enc_fmtp_mode = dec_fmtp_mode = DEFAULT_MODE; + PJ_LOG(4,(pool->obj_name, + "Normalized iLBC encoder and decoder modes to %d", + DEFAULT_MODE)); + } + + /* Update some attributes based on negotiated mode. */ + attr->info.avg_bps = (dec_fmtp_mode == 30? 13333 : 15200); + attr->info.frm_ptime = dec_fmtp_mode; + + /* Override average frame size */ + codec_data->avg_frame_size = (dec_fmtp_mode == 30? 50 : 38); + + /* Override samples per frame */ + codec_data->samples_per_frame = (dec_fmtp_mode == 30? 240 : 160); } #endif @@ -875,7 +874,7 @@ static pj_status_t codec_close( pjmedia_codec *codec ) * Modify codec settings. */ static pj_status_t codec_modify( pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { /* Not supported yet. */ PJ_UNUSED_ARG(codec); @@ -888,11 +887,11 @@ static pj_status_t codec_modify( pjmedia_codec *codec, * Get frames in the packet. */ static pj_status_t codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { codec_private_t *codec_data = (codec_private_t*) codec->codec_data; struct codec_desc *desc = &codec_desc[codec_data->codec_idx]; @@ -901,29 +900,29 @@ static pj_status_t codec_parse( pjmedia_codec *codec, PJ_ASSERT_RETURN(frame_cnt, PJ_EINVAL); if (desc->parse != NULL) { - return desc->parse(codec_data, pkt, pkt_size, ts, frame_cnt, frames); + return desc->parse(codec_data, pkt, pkt_size, ts, frame_cnt, frames); } while (pkt_size >= codec_data->avg_frame_size && count < *frame_cnt) { - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = pkt; - frames[count].size = codec_data->avg_frame_size; - frames[count].timestamp.u64 = ts->u64 + - count * codec_data->samples_per_frame; + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = pkt; + frames[count].size = codec_data->avg_frame_size; + frames[count].timestamp.u64 = ts->u64 + + count * codec_data->samples_per_frame; - pkt = (pj_uint8_t*)pkt + codec_data->avg_frame_size; - pkt_size -= codec_data->avg_frame_size; + pkt = (pj_uint8_t*)pkt + codec_data->avg_frame_size; + pkt_size -= codec_data->avg_frame_size; - ++count; + ++count; } if (pkt_size && count < *frame_cnt) { - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = pkt; - frames[count].size = pkt_size; - frames[count].timestamp.u64 = ts->u64 + - count * codec_data->samples_per_frame; - ++count; + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = pkt; + frames[count].size = pkt_size; + frames[count].timestamp.u64 = ts->u64 + + count * codec_data->samples_per_frame; + ++count; } *frame_cnt = count; @@ -934,9 +933,9 @@ static pj_status_t codec_parse( pjmedia_codec *codec, * Encode frames. */ static pj_status_t codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { codec_private_t *codec_data = (codec_private_t*) codec->codec_data; struct codec_desc *desc = &codec_desc[codec_data->codec_idx]; @@ -945,42 +944,42 @@ static pj_status_t codec_encode( pjmedia_codec *codec, pj_assert(input && input->type == PJMEDIA_FRAME_TYPE_EXTENDED); if (desc->pack != NULL) { - desc->pack(codec_data, input_, output_buf_len, output); + desc->pack(codec_data, input_, output_buf_len, output); } else { - if (input_->subframe_cnt == 0) { - /* DTX */ - output->buf = NULL; - output->size = 0; - output->type = PJMEDIA_FRAME_TYPE_NONE; - } else { - unsigned i; - pj_uint8_t *p = output->buf; - - output->type = PJMEDIA_FRAME_TYPE_AUDIO; - output->size = 0; - - for (i = 0; i < input_->subframe_cnt; ++i) { - pjmedia_frame_ext_subframe *sf; - unsigned sf_len; - - sf = pjmedia_frame_ext_get_subframe(input_, i); - pj_assert(sf); - - sf_len = (sf->bitlen + 7) >> 3; - - pj_memcpy(p, sf->data, sf_len); - p += sf_len; - output->size += sf_len; - - /* If there is SID or DTX frame, break the loop. */ - if (desc->pt == PJMEDIA_RTP_PT_G729 && - sf_len < codec_data->avg_frame_size) - { - break; - } - - } - } + if (input_->subframe_cnt == 0) { + /* DTX */ + output->buf = NULL; + output->size = 0; + output->type = PJMEDIA_FRAME_TYPE_NONE; + } else { + unsigned i; + pj_uint8_t *p = output->buf; + + output->type = PJMEDIA_FRAME_TYPE_AUDIO; + output->size = 0; + + for (i = 0; i < input_->subframe_cnt; ++i) { + pjmedia_frame_ext_subframe *sf; + unsigned sf_len; + + sf = pjmedia_frame_ext_get_subframe(input_, i); + pj_assert(sf); + + sf_len = (sf->bitlen + 7) >> 3; + + pj_memcpy(p, sf->data, sf_len); + p += sf_len; + output->size += sf_len; + + /* If there is SID or DTX frame, break the loop. */ + if (desc->pt == PJMEDIA_RTP_PT_G729 && + sf_len < codec_data->avg_frame_size) + { + break; + } + + } + } } output->timestamp = input->timestamp; @@ -992,9 +991,9 @@ static pj_status_t codec_encode( pjmedia_codec *codec, * Decode frame. */ static pj_status_t codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { codec_private_t *codec_data = (codec_private_t*) codec->codec_data; #if PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR @@ -1011,26 +1010,26 @@ static pj_status_t codec_decode( pjmedia_codec *codec, * into encoder bits order. */ if (desc->pt == PJMEDIA_RTP_PT_AMR || desc->pt == PJMEDIA_RTP_PT_AMRWB) { - pjmedia_frame input_; - pjmedia_codec_amr_pack_setting *setting; - - setting = &((amr_settings_t*)codec_data->codec_setting)->dec_setting; - - input_ = *input; - pjmedia_codec_amr_predecode(input, setting, &input_); - - pjmedia_frame_ext_append_subframe(output_, input_.buf, - (pj_uint16_t)(input_.size << 3), - (pj_uint16_t)codec_data->samples_per_frame); - output->timestamp = input->timestamp; - - return PJ_SUCCESS; + pjmedia_frame input_; + pjmedia_codec_amr_pack_setting *setting; + + setting = &((amr_settings_t*)codec_data->codec_setting)->dec_setting; + + input_ = *input; + pjmedia_codec_amr_predecode(input, setting, &input_); + + pjmedia_frame_ext_append_subframe(output_, input_.buf, + (pj_uint16_t)(input_.size << 3), + (pj_uint16_t)codec_data->samples_per_frame); + output->timestamp = input->timestamp; + + return PJ_SUCCESS; } #endif pjmedia_frame_ext_append_subframe(output_, input->buf, - (pj_uint16_t)(input->size << 3), - (pj_uint16_t)codec_data->samples_per_frame); + (pj_uint16_t)(input->size << 3), + (pj_uint16_t)codec_data->samples_per_frame); output->timestamp = input->timestamp; return PJ_SUCCESS; @@ -1040,8 +1039,8 @@ static pj_status_t codec_decode( pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t codec_recover( pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { codec_private_t *codec_data = (codec_private_t*) codec->codec_data; pjmedia_frame_ext *output_ = (pjmedia_frame_ext*) output; @@ -1049,10 +1048,10 @@ static pj_status_t codec_recover( pjmedia_codec *codec, PJ_UNUSED_ARG(output_buf_len); pjmedia_frame_ext_append_subframe(output_, NULL, 0, - (pj_uint16_t)codec_data->samples_per_frame); + (pj_uint16_t)codec_data->samples_per_frame); return PJ_SUCCESS; } -#endif /* PJMEDIA_HAS_PASSTHROUGH_CODECS */ +#endif /* PJMEDIA_HAS_PASSTHROUGH_CODECS */ diff --git a/pjmedia/src/pjmedia-codec/silk.c b/pjmedia/src/pjmedia-codec/silk.c index 67a4a4ca9d..8412ec1bdc 100644 --- a/pjmedia/src/pjmedia-codec/silk.c +++ b/pjmedia/src/pjmedia-codec/silk.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2012-2012 Teluu Inc. (http://www.teluu.com) * Contributed by Regis Montoya (aka r3gis - www.r3gis.fr) @@ -33,7 +32,7 @@ #include "SKP_Silk_SDK_API.h" -#define THIS_FILE "silk.c" +#define THIS_FILE "silk.c" #ifndef PJMEDIA_SILK_DELAY_BUF_OPTIONS #define PJMEDIA_SILK_DELAY_BUF_OPTIONS PJMEDIA_DELAY_BUF_SIMPLE_FIFO @@ -51,65 +50,65 @@ /* Prototypes for SILK factory */ static pj_status_t silk_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ); + const pjmedia_codec_info *id ); static pj_status_t silk_default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ); static pj_status_t silk_enum_codecs ( pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t silk_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t silk_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for SILK implementation. */ static pj_status_t silk_codec_init( pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t silk_codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t silk_codec_close( pjmedia_codec *codec ); static pj_status_t silk_codec_modify( pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t silk_codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *timestamp, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *timestamp, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t silk_codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t silk_codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t silk_codec_recover( pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); typedef enum { - PARAM_NB, /* Index for narrowband parameter. */ - PARAM_MB, /* Index for medium parameter. */ - PARAM_WB, /* Index for wideband parameter. */ - PARAM_SWB, /* Index for super-wideband parameter */ + PARAM_NB, /* Index for narrowband parameter. */ + PARAM_MB, /* Index for medium parameter. */ + PARAM_WB, /* Index for wideband parameter. */ + PARAM_SWB, /* Index for super-wideband parameter */ } silk_mode; /* Silk default parameter */ typedef struct silk_param { - int enabled; /* Is this mode enabled? */ - int pt; /* Payload type. */ - unsigned clock_rate; /* Default sampling rate to be used. */ - pj_uint16_t ptime; /* packet length (in ms). */ - pj_uint32_t bitrate; /* Bit rate for current mode. */ - pj_uint32_t max_bitrate; /* Max bit rate for current mode. */ - int complexity; /* Complexity mode: 0/lowest to 2. */ + int enabled; /* Is this mode enabled? */ + int pt; /* Payload type. */ + unsigned clock_rate; /* Default sampling rate to be used. */ + pj_uint16_t ptime; /* packet length (in ms). */ + pj_uint32_t bitrate; /* Bit rate for current mode. */ + pj_uint32_t max_bitrate; /* Max bit rate for current mode. */ + int complexity; /* Complexity mode: 0/lowest to 2. */ } silk_param; @@ -141,29 +140,29 @@ static pjmedia_codec_factory_op silk_factory_op = /* SILK factory private data */ static struct silk_factory { - pjmedia_codec_factory base; - pjmedia_endpt *endpt; - pj_pool_t *pool; - pj_mutex_t *mutex; - struct silk_param silk_param[4]; + pjmedia_codec_factory base; + pjmedia_endpt *endpt; + pj_pool_t *pool; + pj_mutex_t *mutex; + struct silk_param silk_param[4]; } silk_factory; /* SILK codec private data. */ typedef struct silk_private { - silk_mode mode; /**< Silk mode. */ - pj_pool_t *pool; /**< Pool for each instance. */ - unsigned samples_per_frame; + silk_mode mode; /**< Silk mode. */ + pj_pool_t *pool; /**< Pool for each instance. */ + unsigned samples_per_frame; pj_uint8_t pcm_bytes_per_sample; - pj_bool_t enc_ready; + pj_bool_t enc_ready; SKP_SILK_SDK_EncControlStruct enc_ctl; - void *enc_st; + void *enc_st; - pj_bool_t dec_ready; + pj_bool_t dec_ready; SKP_SILK_SDK_DecControlStruct dec_ctl; - void *dec_st; + void *dec_st; /* Buffer to hold decoded frames. */ void *dec_buf[SILK_MAX_FRAMES_PER_PACKET-1]; @@ -176,11 +175,11 @@ typedef struct silk_private silk_mode silk_get_mode_from_clock_rate(unsigned clock_rate) { if (clock_rate <= silk_factory.silk_param[PARAM_NB].clock_rate) { - return PARAM_NB; + return PARAM_NB; } else if (clock_rate <= silk_factory.silk_param[PARAM_MB].clock_rate) { - return PARAM_MB; + return PARAM_MB; } else if (clock_rate <= silk_factory.silk_param[PARAM_WB].clock_rate) { - return PARAM_WB; + return PARAM_WB; } return PARAM_SWB; } @@ -193,8 +192,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_silk_init(pjmedia_endpt *endpt) pj_status_t status; if (silk_factory.endpt != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } /* Init factory */ @@ -206,13 +205,13 @@ PJ_DEF(pj_status_t) pjmedia_codec_silk_init(pjmedia_endpt *endpt) /* Create pool */ silk_factory.pool = pjmedia_endpt_create_pool(endpt, "silk", 4000, 4000); if (!silk_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create mutex. */ status = pj_mutex_create_simple(silk_factory.pool, "silk", - &silk_factory.mutex); + &silk_factory.mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Initialize default codec params */ @@ -270,27 +269,27 @@ PJ_DEF(pj_status_t) pjmedia_codec_silk_init(pjmedia_endpt *endpt) /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; } /* Register codec factory to endpoint. */ status = pjmedia_codec_mgr_register_factory(codec_mgr, - &silk_factory.base); + &silk_factory.base); if (status != PJ_SUCCESS) - return status; + return status; PJ_LOG(4,(THIS_FILE, "SILK codec version %s initialized", - SKP_Silk_SDK_get_version())); + SKP_Silk_SDK_get_version())); return PJ_SUCCESS; on_error: if (silk_factory.mutex) { - pj_mutex_destroy(silk_factory.mutex); - silk_factory.mutex = NULL; + pj_mutex_destroy(silk_factory.mutex); + silk_factory.mutex = NULL; } if (silk_factory.pool) { - pj_pool_release(silk_factory.pool); - silk_factory.pool = NULL; + pj_pool_release(silk_factory.pool); + silk_factory.pool = NULL; } return status; @@ -302,8 +301,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_silk_init(pjmedia_endpt *endpt) * clock rate. */ PJ_DEF(pj_status_t) pjmedia_codec_silk_set_config( - unsigned clock_rate, - const pjmedia_codec_silk_setting *opt) + unsigned clock_rate, + const pjmedia_codec_silk_setting *opt) { unsigned i; @@ -315,7 +314,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_silk_set_config( int quality = PJMEDIA_CODEC_SILK_DEFAULT_QUALITY; int complexity = PJMEDIA_CODEC_SILK_DEFAULT_COMPLEXITY; - silk_factory.silk_param[i].enabled = opt->enabled; + silk_factory.silk_param[i].enabled = opt->enabled; if (opt->complexity >= 0) complexity = opt->complexity; silk_factory.silk_param[i].complexity = complexity; @@ -327,8 +326,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_silk_set_config( if (silk_factory.silk_param[i].bitrate < SILK_MIN_BITRATE) silk_factory.silk_param[i].bitrate = SILK_MIN_BITRATE; - return PJ_SUCCESS; - } + return PJ_SUCCESS; + } } return PJ_ENOTFOUND; @@ -345,8 +344,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_silk_deinit(void) pj_status_t status; if (silk_factory.endpt == NULL) { - /* Not registered. */ - return PJ_SUCCESS; + /* Not registered. */ + return PJ_SUCCESS; } /* Lock mutex. */ @@ -355,14 +354,14 @@ PJ_DEF(pj_status_t) pjmedia_codec_silk_deinit(void) /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(silk_factory.endpt); if (!codec_mgr) { - silk_factory.endpt = NULL; - pj_mutex_unlock(silk_factory.mutex); - return PJ_EINVALIDOP; + silk_factory.endpt = NULL; + pj_mutex_unlock(silk_factory.mutex); + return PJ_EINVALIDOP; } /* Unregister silk codec factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &silk_factory.base); + &silk_factory.base); silk_factory.endpt = NULL; /* Destroy mutex. */ @@ -383,7 +382,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_silk_deinit(void) * Check if factory can allocate the specified codec. */ static pj_status_t silk_test_alloc(pjmedia_codec_factory *factory, - const pjmedia_codec_info *info ) + const pjmedia_codec_info *info ) { const pj_str_t silk_tag = {"SILK", 4}; unsigned i; @@ -393,23 +392,23 @@ static pj_status_t silk_test_alloc(pjmedia_codec_factory *factory, /* Type MUST be audio. */ if (info->type != PJMEDIA_TYPE_AUDIO) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check encoding name. */ if (pj_stricmp(&info->encoding_name, &silk_tag) != 0) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Channel count must be one */ if (info->channel_cnt != 1) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check clock-rate */ for (i=0; ienabled && info->clock_rate == sp->clock_rate) - { - return PJ_SUCCESS; - } + silk_param *sp = &silk_factory.silk_param[i]; + if (sp->enabled && info->clock_rate == sp->clock_rate) + { + return PJ_SUCCESS; + } } /* Clock rate not supported */ return PJMEDIA_CODEC_EUNSUP; @@ -420,8 +419,8 @@ static pj_status_t silk_test_alloc(pjmedia_codec_factory *factory, * Generate default attribute. */ static pj_status_t silk_default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ) { silk_param *sp; int i; @@ -462,8 +461,8 @@ static pj_status_t silk_default_attr( pjmedia_codec_factory *factory, * Enum codecs supported by this factory. */ static pj_status_t silk_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]) + unsigned *count, + pjmedia_codec_info codecs[]) { unsigned max; int i; @@ -476,19 +475,19 @@ static pj_status_t silk_enum_codecs(pjmedia_codec_factory *factory, for (i = 0; ienabled) - continue; + if (!sp->enabled) + continue; - pj_bzero(&codecs[*count], sizeof(pjmedia_codec_info)); - codecs[*count].encoding_name = pj_str("SILK"); - codecs[*count].pt = sp->pt; - codecs[*count].type = PJMEDIA_TYPE_AUDIO; - codecs[*count].clock_rate = sp->clock_rate; - codecs[*count].channel_cnt = 1; + pj_bzero(&codecs[*count], sizeof(pjmedia_codec_info)); + codecs[*count].encoding_name = pj_str("SILK"); + codecs[*count].pt = sp->pt; + codecs[*count].type = PJMEDIA_TYPE_AUDIO; + codecs[*count].clock_rate = sp->clock_rate; + codecs[*count].channel_cnt = 1; - ++*count; + ++*count; } return PJ_SUCCESS; @@ -499,8 +498,8 @@ static pj_status_t silk_enum_codecs(pjmedia_codec_factory *factory, * Allocate a new SILK codec instance. */ static pj_status_t silk_alloc_codec(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { pj_pool_t *pool; pjmedia_codec *codec; @@ -532,7 +531,7 @@ static pj_status_t silk_alloc_codec(pjmedia_codec_factory *factory, * Free codec. */ static pj_status_t silk_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { silk_private *silk; @@ -543,7 +542,7 @@ static pj_status_t silk_dealloc_codec( pjmedia_codec_factory *factory, /* Close codec, if it's not closed. */ if (silk->enc_ready == PJ_TRUE || silk->dec_ready == PJ_TRUE) { - silk_codec_close(codec); + silk_codec_close(codec); } pj_pool_release(silk->pool); @@ -556,7 +555,7 @@ static pj_status_t silk_dealloc_codec( pjmedia_codec_factory *factory, * Init codec. */ static pj_status_t silk_codec_init(pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(pool); @@ -568,7 +567,7 @@ static pj_status_t silk_codec_init(pjmedia_codec *codec, * Open codec. */ static pj_status_t silk_codec_open(pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { silk_private *silk; @@ -584,44 +583,44 @@ static pj_status_t silk_codec_open(pjmedia_codec *codec, /* Already opened? */ if (silk->enc_ready || silk->dec_ready) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Allocate and initialize encoder */ err = SKP_Silk_SDK_Get_Encoder_Size(&st_size); if (err) { PJ_LOG(3,(THIS_FILE, "Failed to get encoder state size (err=%d)", - err)); - return PJMEDIA_CODEC_EFAILED; + err)); + return PJMEDIA_CODEC_EFAILED; } silk->enc_st = pj_pool_zalloc(silk->pool, st_size); err = SKP_Silk_SDK_InitEncoder(silk->enc_st, &silk->enc_ctl); if (err) { PJ_LOG(3,(THIS_FILE, "Failed to init encoder (err=%d)", err)); - return PJMEDIA_CODEC_EFAILED; + return PJMEDIA_CODEC_EFAILED; } /* Check fmtp params */ enc_use_fec = PJ_TRUE; enc_bitrate = sp->bitrate; for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) { - pjmedia_codec_fmtp *fmtp = &attr->setting.enc_fmtp; - const pj_str_t STR_USEINBANDFEC = {"useinbandfec", 12}; - const pj_str_t STR_MAXAVERAGEBITRATE = {"maxaveragebitrate", 17}; - - if (!pj_stricmp(&fmtp->param[i].name, &STR_USEINBANDFEC)) { - enc_use_fec = pj_strtoul(&fmtp->param[i].val) != 0; - } else if (!pj_stricmp(&fmtp->param[i].name, &STR_MAXAVERAGEBITRATE)) { - enc_bitrate = pj_strtoul(&fmtp->param[i].val); - if (enc_bitrate > sp->max_bitrate) { - enc_bitrate = sp->max_bitrate; - } - } + pjmedia_codec_fmtp *fmtp = &attr->setting.enc_fmtp; + const pj_str_t STR_USEINBANDFEC = {"useinbandfec", 12}; + const pj_str_t STR_MAXAVERAGEBITRATE = {"maxaveragebitrate", 17}; + + if (!pj_stricmp(&fmtp->param[i].name, &STR_USEINBANDFEC)) { + enc_use_fec = pj_strtoul(&fmtp->param[i].val) != 0; + } else if (!pj_stricmp(&fmtp->param[i].name, &STR_MAXAVERAGEBITRATE)) { + enc_bitrate = pj_strtoul(&fmtp->param[i].val); + if (enc_bitrate > sp->max_bitrate) { + enc_bitrate = sp->max_bitrate; + } + } } /* Setup encoder control for encoding process */ silk->enc_ready = PJ_TRUE; silk->samples_per_frame = FRAME_LENGTH_MS * - attr->info.clock_rate / 1000; + attr->info.clock_rate / 1000; silk->pcm_bytes_per_sample = attr->info.pcm_bits_per_sample / 8; silk->enc_ctl.API_sampleRate = attr->info.clock_rate; @@ -642,19 +641,19 @@ static pj_status_t silk_codec_open(pjmedia_codec *codec, err = SKP_Silk_SDK_Get_Decoder_Size(&st_size); if (err) { PJ_LOG(3,(THIS_FILE, "Failed to get decoder state size (err=%d)", - err)); - return PJMEDIA_CODEC_EFAILED; + err)); + return PJMEDIA_CODEC_EFAILED; } silk->dec_st = pj_pool_zalloc(silk->pool, st_size); err = SKP_Silk_SDK_InitDecoder(silk->dec_st); if (err) { PJ_LOG(3,(THIS_FILE, "Failed to init decoder (err=%d)", err)); - return PJMEDIA_CODEC_EFAILED; + return PJMEDIA_CODEC_EFAILED; } /* Setup decoder control for decoding process */ silk->dec_ctl.API_sampleRate = attr->info.clock_rate; - silk->dec_ctl.framesPerPacket = 1; /* for proper PLC at start */ + silk->dec_ctl.framesPerPacket = 1; /* for proper PLC at start */ silk->dec_ready = PJ_TRUE; silk->dec_buf_sz = attr->info.clock_rate * attr->info.channel_cnt * attr->info.frm_ptime / 1000 * @@ -664,10 +663,10 @@ static pj_status_t silk_codec_open(pjmedia_codec *codec, * SILK packets and split it into individual frames. */ attr->info.max_rx_frame_size = attr->info.max_bps * - attr->info.frm_ptime / 8 / 1000; + attr->info.frm_ptime / 8 / 1000; if ((attr->info.max_bps * attr->info.frm_ptime) % 8000 != 0) { - ++attr->info.max_rx_frame_size; + ++attr->info.max_rx_frame_size; } attr->info.max_rx_frame_size *= SILK_MAX_FRAMES_PER_PACKET; @@ -694,7 +693,7 @@ static pj_status_t silk_codec_close( pjmedia_codec *codec ) * Modify codec settings. */ static pj_status_t silk_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { PJ_TODO(implement_silk_codec_modify); @@ -709,9 +708,9 @@ static pj_status_t silk_codec_modify(pjmedia_codec *codec, * Encode frame. */ static pj_status_t silk_codec_encode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { silk_private *silk; SKP_int err; @@ -724,20 +723,20 @@ static pj_status_t silk_codec_encode(pjmedia_codec *codec, /* Check frame in size */ nsamples = input->size >> 1; PJ_ASSERT_RETURN(nsamples % silk->samples_per_frame == 0, - PJMEDIA_CODEC_EPCMFRMINLEN); + PJMEDIA_CODEC_EPCMFRMINLEN); /* Encode */ output->size = 0; out_size = (SKP_int16)output_buf_len; err = SKP_Silk_SDK_Encode(silk->enc_st, &silk->enc_ctl, - (SKP_int16*)input->buf, nsamples, - (SKP_uint8*)output->buf, &out_size); + (SKP_int16*)input->buf, nsamples, + (SKP_uint8*)output->buf, &out_size); if (err) { - PJ_LOG(3, (THIS_FILE, "Failed to encode frame (err=%d)", err)); - output->type = PJMEDIA_FRAME_TYPE_NONE; - if (err == SKP_SILK_ENC_PAYLOAD_BUF_TOO_SHORT) - return PJMEDIA_CODEC_EFRMTOOSHORT; - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(3, (THIS_FILE, "Failed to encode frame (err=%d)", err)); + output->type = PJMEDIA_FRAME_TYPE_NONE; + if (err == SKP_SILK_ENC_PAYLOAD_BUF_TOO_SHORT) + return PJMEDIA_CODEC_EFRMTOOSHORT; + return PJMEDIA_CODEC_EFAILED; } output->size = out_size; @@ -752,11 +751,11 @@ static pj_status_t silk_codec_encode(pjmedia_codec *codec, * Get frames in the packet. */ static pj_status_t silk_codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { silk_private *silk; SKP_Silk_TOC_struct toc; @@ -784,9 +783,9 @@ static pj_status_t silk_codec_parse( pjmedia_codec *codec, } static pj_status_t silk_codec_decode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { silk_private *silk; SKP_int16 out_size; @@ -846,11 +845,11 @@ static pj_status_t silk_codec_decode(pjmedia_codec *codec, *size = nsamples; err = SKP_Silk_SDK_Decode(silk->dec_st, &silk->dec_ctl, - 0, /* Normal frame flag */ - input->buf, input->size, - buf, size); + 0, /* Normal frame flag */ + input->buf, input->size, + buf, size); if (err) { - PJ_LOG(3, (THIS_FILE, "Failed to decode frame (err=%d)", + PJ_LOG(3, (THIS_FILE, "Failed to decode frame (err=%d)", err)); *size = 0; } else { @@ -911,8 +910,8 @@ static pj_status_t silk_codec_decode(pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t silk_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { silk_private *silk; SKP_int16 out_size; @@ -923,17 +922,17 @@ static pj_status_t silk_codec_recover(pjmedia_codec *codec, out_size = (SKP_int16)output_buf_len / silk->pcm_bytes_per_sample; err = SKP_Silk_SDK_Decode(silk->dec_st, &silk->dec_ctl, - 1, /* Lost frame flag */ - NULL, - 0, - output->buf, - &out_size); + 1, /* Lost frame flag */ + NULL, + 0, + output->buf, + &out_size); if (err) { - PJ_LOG(3, (THIS_FILE, "Failed to conceal lost frame (err=%d)", err)); - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->buf = NULL; - output->size = 0; - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(3, (THIS_FILE, "Failed to conceal lost frame (err=%d)", err)); + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->buf = NULL; + output->size = 0; + return PJMEDIA_CODEC_EFAILED; } output->size = out_size * silk->pcm_bytes_per_sample; diff --git a/pjmedia/src/pjmedia-codec/speex_codec.c b/pjmedia/src/pjmedia-codec/speex_codec.c index 113e84f9cd..f5339f31a9 100644 --- a/pjmedia/src/pjmedia-codec/speex_codec.c +++ b/pjmedia/src/pjmedia-codec/speex_codec.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -40,44 +39,44 @@ /* Prototypes for Speex factory */ static pj_status_t spx_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ); + const pjmedia_codec_info *id ); static pj_status_t spx_default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ); static pj_status_t spx_enum_codecs( pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t spx_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t spx_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for Speex implementation. */ static pj_status_t spx_codec_init( pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t spx_codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t spx_codec_close( pjmedia_codec *codec ); static pj_status_t spx_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t spx_codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t spx_codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t spx_codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t spx_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); /* Definition for Speex codec operations. */ static pjmedia_codec_op spx_op = @@ -106,47 +105,47 @@ static pjmedia_codec_factory_op spx_factory_op = /* Index to Speex parameter. */ enum { - PARAM_NB, /* Index for narrowband parameter. */ - PARAM_WB, /* Index for wideband parameter. */ - PARAM_UWB, /* Index for ultra-wideband parameter */ + PARAM_NB, /* Index for narrowband parameter. */ + PARAM_WB, /* Index for wideband parameter. */ + PARAM_UWB, /* Index for ultra-wideband parameter */ }; /* Speex default parameter */ struct speex_param { - int enabled; /* Is this mode enabled? */ - const SpeexMode *mode; /* Speex mode. */ - int pt; /* Payload type. */ - unsigned clock_rate; /* Default sampling rate to be used.*/ - int quality; /* Default encoder quality. */ - int complexity; /* Default encoder complexity. */ - int samples_per_frame; /* Samples per frame. */ - int framesize; /* Frame size for current mode. */ - int bitrate; /* Bit rate for current mode. */ - int max_bitrate; /* Max bit rate for current mode. */ + int enabled; /* Is this mode enabled? */ + const SpeexMode *mode; /* Speex mode. */ + int pt; /* Payload type. */ + unsigned clock_rate; /* Default sampling rate to be used.*/ + int quality; /* Default encoder quality. */ + int complexity; /* Default encoder complexity. */ + int samples_per_frame; /* Samples per frame. */ + int framesize; /* Frame size for current mode. */ + int bitrate; /* Bit rate for current mode. */ + int max_bitrate; /* Max bit rate for current mode. */ }; /* Speex factory */ static struct spx_factory { pjmedia_codec_factory base; - pjmedia_endpt *endpt; - pj_pool_t *pool; - pj_mutex_t *mutex; - pjmedia_codec codec_list; - struct speex_param speex_param[3]; + pjmedia_endpt *endpt; + pj_pool_t *pool; + pj_mutex_t *mutex; + pjmedia_codec codec_list; + struct speex_param speex_param[3]; } spx_factory; /* Speex codec private data. */ struct spx_private { - int param_id; /**< Index to speex param. */ + int param_id; /**< Index to speex param. */ - void *enc; /**< Encoder state. */ - SpeexBits enc_bits; /**< Encoder bits. */ - void *dec; /**< Decoder state. */ - SpeexBits dec_bits; /**< Decoder bits. */ + void *enc; /**< Encoder state. */ + SpeexBits enc_bits; /**< Encoder bits. */ + void *dec; /**< Decoder state. */ + SpeexBits dec_bits; /**< Decoder bits. */ }; @@ -161,11 +160,11 @@ static pj_status_t get_speex_info( struct speex_param *p ) /* Create temporary encoder */ state = speex_encoder_init(p->mode); if (!state) - return PJMEDIA_CODEC_EFAILED; + return PJMEDIA_CODEC_EFAILED; /* Set the quality */ if (p->quality != -1) - speex_encoder_ctl(state, SPEEX_SET_QUALITY, &p->quality); + speex_encoder_ctl(state, SPEEX_SET_QUALITY, &p->quality); /* Sampling rate. */ speex_encoder_ctl(state, SPEEX_SET_SAMPLING_RATE, &p->clock_rate); @@ -176,7 +175,7 @@ static pj_status_t get_speex_info( struct speex_param *p ) /* Complexity. */ if (p->complexity != -1) - speex_encoder_ctl(state, SPEEX_SET_COMPLEXITY, &p->complexity); + speex_encoder_ctl(state, SPEEX_SET_COMPLEXITY, &p->complexity); /* Now get the frame size */ speex_encoder_ctl(state, SPEEX_GET_FRAME_SIZE, &p->samples_per_frame); @@ -202,17 +201,17 @@ static pj_status_t get_speex_info( struct speex_param *p ) * Initialize and register Speex codec factory to pjmedia endpoint. */ PJ_DEF(pj_status_t) pjmedia_codec_speex_init( pjmedia_endpt *endpt, - unsigned options, - int quality, - int complexity ) + unsigned options, + int quality, + int complexity ) { pjmedia_codec_mgr *codec_mgr; unsigned i; pj_status_t status; if (spx_factory.pool != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } /* Get defaults */ @@ -229,21 +228,21 @@ PJ_DEF(pj_status_t) pjmedia_codec_speex_init( pjmedia_endpt *endpt, spx_factory.endpt = endpt; spx_factory.pool = pjmedia_endpt_create_pool(endpt, "speex", - 4000, 4000); + 4000, 4000); if (!spx_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; pj_list_init(&spx_factory.codec_list); /* Create mutex. */ status = pj_mutex_create_simple(spx_factory.pool, "speex", - &spx_factory.mutex); + &spx_factory.mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Initialize default Speex parameter. */ spx_factory.speex_param[PARAM_NB].enabled = - ((options & PJMEDIA_SPEEX_NO_NB) == 0); + ((options & PJMEDIA_SPEEX_NO_NB) == 0); spx_factory.speex_param[PARAM_NB].pt = PJMEDIA_RTP_PT_SPEEX_NB; spx_factory.speex_param[PARAM_NB].mode = speex_lib_get_mode(SPEEX_MODEID_NB); spx_factory.speex_param[PARAM_NB].clock_rate = 8000; @@ -251,7 +250,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_speex_init( pjmedia_endpt *endpt, spx_factory.speex_param[PARAM_NB].complexity = complexity; spx_factory.speex_param[PARAM_WB].enabled = - ((options & PJMEDIA_SPEEX_NO_WB) == 0); + ((options & PJMEDIA_SPEEX_NO_WB) == 0); spx_factory.speex_param[PARAM_WB].pt = PJMEDIA_RTP_PT_SPEEX_WB; spx_factory.speex_param[PARAM_WB].mode = speex_lib_get_mode(SPEEX_MODEID_WB); spx_factory.speex_param[PARAM_WB].clock_rate = 16000; @@ -259,7 +258,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_speex_init( pjmedia_endpt *endpt, spx_factory.speex_param[PARAM_WB].complexity = complexity; spx_factory.speex_param[PARAM_UWB].enabled = - ((options & PJMEDIA_SPEEX_NO_UWB) == 0); + ((options & PJMEDIA_SPEEX_NO_UWB) == 0); spx_factory.speex_param[PARAM_UWB].pt = PJMEDIA_RTP_PT_SPEEX_UWB; spx_factory.speex_param[PARAM_UWB].mode = speex_lib_get_mode(SPEEX_MODEID_UWB); spx_factory.speex_param[PARAM_UWB].clock_rate = 32000; @@ -268,27 +267,27 @@ PJ_DEF(pj_status_t) pjmedia_codec_speex_init( pjmedia_endpt *endpt, /* Somehow quality <=4 is broken in linux. */ if (quality <= 4 && quality >= 0) { - PJ_LOG(5,(THIS_FILE, "Adjusting quality to 5 for uwb")); - spx_factory.speex_param[PARAM_UWB].quality = 5; + PJ_LOG(5,(THIS_FILE, "Adjusting quality to 5 for uwb")); + spx_factory.speex_param[PARAM_UWB].quality = 5; } /* Get codec framesize and avg bitrate for each mode. */ for (i=0; i= 0) { - PJ_LOG(5,(THIS_FILE, "Adjusting quality to 5 for uwb")); - spx_factory.speex_param[PARAM_UWB].quality = 5; - } + /* Somehow quality<=4 is broken in linux. */ + if (i == PARAM_UWB && quality <= 4 && quality >= 0) { + PJ_LOG(5,(THIS_FILE, "Adjusting quality to 5 for uwb")); + spx_factory.speex_param[PARAM_UWB].quality = 5; + } - status = get_speex_info(&spx_factory.speex_param[i]); + status = get_speex_info(&spx_factory.speex_param[i]); - return status; - } + return status; + } } return PJ_EINVAL; @@ -358,8 +357,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_speex_deinit(void) pj_status_t status; if (spx_factory.pool == NULL) { - /* Already deinitialized */ - return PJ_SUCCESS; + /* Already deinitialized */ + return PJ_SUCCESS; } pj_mutex_lock(spx_factory.mutex); @@ -369,23 +368,23 @@ PJ_DEF(pj_status_t) pjmedia_codec_speex_deinit(void) we ever allocate a codec! A better behavior maybe is to deallocate all codecs in the list. if (!pj_list_empty(&spx_factory.codec_list)) { - pj_mutex_unlock(spx_factory.mutex); - return PJ_EBUSY; + pj_mutex_unlock(spx_factory.mutex); + return PJ_EBUSY; } */ /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(spx_factory.endpt); if (!codec_mgr) { - pj_pool_release(spx_factory.pool); - spx_factory.pool = NULL; - pj_mutex_unlock(spx_factory.mutex); - return PJ_EINVALIDOP; + pj_pool_release(spx_factory.pool); + spx_factory.pool = NULL; + pj_mutex_unlock(spx_factory.mutex); + return PJ_EINVALIDOP; } /* Unregister Speex codec factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &spx_factory.base); + &spx_factory.base); /* Destroy mutex. */ pj_mutex_unlock(spx_factory.mutex); @@ -403,7 +402,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_speex_deinit(void) * Check if factory can allocate the specified codec. */ static pj_status_t spx_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *info ) + const pjmedia_codec_info *info ) { const pj_str_t speex_tag = { "speex", 5}; unsigned i; @@ -412,18 +411,18 @@ static pj_status_t spx_test_alloc( pjmedia_codec_factory *factory, /* Type MUST be audio. */ if (info->type != PJMEDIA_TYPE_AUDIO) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check encoding name. */ if (pj_stricmp(&info->encoding_name, &speex_tag) != 0) - return PJMEDIA_CODEC_EUNSUP; + return PJMEDIA_CODEC_EUNSUP; /* Check clock-rate */ for (i=0; iclock_rate == spx_factory.speex_param[i].clock_rate) { - /* Okay, let's Speex! */ - return PJ_SUCCESS; - } + if (info->clock_rate == spx_factory.speex_param[i].clock_rate) { + /* Okay, let's Speex! */ + return PJ_SUCCESS; + } } @@ -435,8 +434,8 @@ static pj_status_t spx_test_alloc( pjmedia_codec_factory *factory, * Generate default attribute. */ static pj_status_t spx_default_attr (pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ) { PJ_ASSERT_RETURN(factory==&spx_factory.base, PJ_EINVAL); @@ -446,20 +445,20 @@ static pj_status_t spx_default_attr (pjmedia_codec_factory *factory, attr->info.channel_cnt = 1; if (id->clock_rate <= 8000) { - attr->info.clock_rate = spx_factory.speex_param[PARAM_NB].clock_rate; - attr->info.avg_bps = spx_factory.speex_param[PARAM_NB].bitrate; - attr->info.max_bps = spx_factory.speex_param[PARAM_NB].max_bitrate; + attr->info.clock_rate = spx_factory.speex_param[PARAM_NB].clock_rate; + attr->info.avg_bps = spx_factory.speex_param[PARAM_NB].bitrate; + attr->info.max_bps = spx_factory.speex_param[PARAM_NB].max_bitrate; } else if (id->clock_rate <= 16000) { - attr->info.clock_rate = spx_factory.speex_param[PARAM_WB].clock_rate; - attr->info.avg_bps = spx_factory.speex_param[PARAM_WB].bitrate; - attr->info.max_bps = spx_factory.speex_param[PARAM_WB].max_bitrate; + attr->info.clock_rate = spx_factory.speex_param[PARAM_WB].clock_rate; + attr->info.avg_bps = spx_factory.speex_param[PARAM_WB].bitrate; + attr->info.max_bps = spx_factory.speex_param[PARAM_WB].max_bitrate; } else { - /* Wow.. somebody is doing ultra-wideband. Cool...! */ - attr->info.clock_rate = spx_factory.speex_param[PARAM_UWB].clock_rate; - attr->info.avg_bps = spx_factory.speex_param[PARAM_UWB].bitrate; - attr->info.max_bps = spx_factory.speex_param[PARAM_UWB].max_bitrate; + /* Wow.. somebody is doing ultra-wideband. Cool...! */ + attr->info.clock_rate = spx_factory.speex_param[PARAM_UWB].clock_rate; + attr->info.avg_bps = spx_factory.speex_param[PARAM_UWB].bitrate; + attr->info.max_bps = spx_factory.speex_param[PARAM_UWB].max_bitrate; } attr->info.pcm_bits_per_sample = 16; @@ -481,8 +480,8 @@ static pj_status_t spx_default_attr (pjmedia_codec_factory *factory, * Enum codecs supported by this factory (i.e. only Speex!). */ static pj_status_t spx_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]) + unsigned *count, + pjmedia_codec_info codecs[]) { unsigned max; int i; /* Must be signed */ @@ -495,21 +494,21 @@ static pj_status_t spx_enum_codecs(pjmedia_codec_factory *factory, /* * We return three codecs here, and in this order: - * - ultra-wideband, wideband, and narrowband. + * - ultra-wideband, wideband, and narrowband. */ for (i=PJ_ARRAY_SIZE(spx_factory.speex_param)-1; i>=0 && *countop = &spx_op; - codec->factory = factory; - codec->codec_data = pj_pool_alloc(spx_factory.pool, - sizeof(struct spx_private)); + codec = PJ_POOL_ZALLOC_T(spx_factory.pool, pjmedia_codec); + PJ_ASSERT_RETURN(codec != NULL, PJ_ENOMEM); + codec->op = &spx_op; + codec->factory = factory; + codec->codec_data = pj_pool_alloc(spx_factory.pool, + sizeof(struct spx_private)); } pj_mutex_unlock(spx_factory.mutex); @@ -551,11 +550,11 @@ static pj_status_t spx_alloc_codec( pjmedia_codec_factory *factory, spx->dec = NULL; if (id->clock_rate <= 8000) - spx->param_id = PARAM_NB; + spx->param_id = PARAM_NB; else if (id->clock_rate <= 16000) - spx->param_id = PARAM_WB; + spx->param_id = PARAM_WB; else - spx->param_id = PARAM_UWB; + spx->param_id = PARAM_UWB; *p_codec = codec; return PJ_SUCCESS; @@ -565,7 +564,7 @@ static pj_status_t spx_alloc_codec( pjmedia_codec_factory *factory, * Free codec. */ static pj_status_t spx_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { struct spx_private *spx; @@ -575,7 +574,7 @@ static pj_status_t spx_dealloc_codec( pjmedia_codec_factory *factory, /* Close codec, if it's not closed. */ spx = (struct spx_private*) codec->codec_data; if (spx->enc != NULL || spx->dec != NULL) { - spx_codec_close(codec); + spx_codec_close(codec); } /* Put in the free list. */ @@ -590,7 +589,7 @@ static pj_status_t spx_dealloc_codec( pjmedia_codec_factory *factory, * Init codec. */ static pj_status_t spx_codec_init( pjmedia_codec *codec, - pj_pool_t *pool ) + pj_pool_t *pool ) { PJ_UNUSED_ARG(codec); PJ_UNUSED_ARG(pool); @@ -601,7 +600,7 @@ static pj_status_t spx_codec_init( pjmedia_codec *codec, * Open codec. */ static pj_status_t spx_codec_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { struct spx_private *spx; int id, tmp; @@ -614,19 +613,19 @@ static pj_status_t spx_codec_open( pjmedia_codec *codec, */ spx->enc = speex_encoder_init(spx_factory.speex_param[id].mode); if (!spx->enc) - return PJMEDIA_CODEC_EFAILED; + return PJMEDIA_CODEC_EFAILED; speex_bits_init(&spx->enc_bits); /* Set the quality*/ if (spx_factory.speex_param[id].quality != -1) { - speex_encoder_ctl(spx->enc, SPEEX_SET_QUALITY, - &spx_factory.speex_param[id].quality); + speex_encoder_ctl(spx->enc, SPEEX_SET_QUALITY, + &spx_factory.speex_param[id].quality); } /* Sampling rate. */ tmp = attr->info.clock_rate; speex_encoder_ctl(spx->enc, SPEEX_SET_SAMPLING_RATE, - &spx_factory.speex_param[id].clock_rate); + &spx_factory.speex_param[id].clock_rate); /* VAD */ tmp = (attr->setting.vad != 0); @@ -635,8 +634,8 @@ static pj_status_t spx_codec_open( pjmedia_codec *codec, /* Complexity */ if (spx_factory.speex_param[id].complexity != -1) { - speex_encoder_ctl(spx->enc, SPEEX_SET_COMPLEXITY, - &spx_factory.speex_param[id].complexity); + speex_encoder_ctl(spx->enc, SPEEX_SET_COMPLEXITY, + &spx_factory.speex_param[id].complexity); } /* @@ -644,14 +643,14 @@ static pj_status_t spx_codec_open( pjmedia_codec *codec, */ spx->dec = speex_decoder_init(spx_factory.speex_param[id].mode); if (!spx->dec) { - spx_codec_close(codec); - return PJMEDIA_CODEC_EFAILED; + spx_codec_close(codec); + return PJMEDIA_CODEC_EFAILED; } speex_bits_init(&spx->dec_bits); /* Sampling rate. */ speex_decoder_ctl(spx->dec, SPEEX_SET_SAMPLING_RATE, - &spx_factory.speex_param[id].clock_rate); + &spx_factory.speex_param[id].clock_rate); /* PENH */ tmp = attr->setting.penh; @@ -671,16 +670,16 @@ static pj_status_t spx_codec_close( pjmedia_codec *codec ) /* Destroy encoder*/ if (spx->enc) { - speex_encoder_destroy( spx->enc ); - spx->enc = NULL; - speex_bits_destroy( &spx->enc_bits ); + speex_encoder_destroy( spx->enc ); + spx->enc = NULL; + speex_bits_destroy( &spx->enc_bits ); } /* Destroy decoder */ if (spx->dec) { - speex_decoder_destroy( spx->dec); - spx->dec = NULL; - speex_bits_destroy( &spx->dec_bits ); + speex_decoder_destroy( spx->dec); + spx->dec = NULL; + speex_bits_destroy( &spx->dec_bits ); } return PJ_SUCCESS; @@ -691,7 +690,7 @@ static pj_status_t spx_codec_close( pjmedia_codec *codec ) * Modify codec settings. */ static pj_status_t spx_codec_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { struct spx_private *spx; int tmp; @@ -711,7 +710,7 @@ static pj_status_t spx_codec_modify(pjmedia_codec *codec, } #if 0 -# define TRACE__(args) PJ_LOG(5,args) +# define TRACE__(args) PJ_LOG(5,args) #else # define TRACE__(args) #endif @@ -739,85 +738,85 @@ static int speex_get_next_frame(SpeexBits *bits) unsigned nb_count = 0; while (speex_bits_remaining(bits) >= 5) { - unsigned wb_count = 0; - unsigned bit_ptr = bits->bitPtr; - unsigned char_ptr = bits->charPtr; - - /* WB frame */ - while ((speex_bits_remaining(bits) >= 4) - && speex_bits_unpack_unsigned(bits, 1)) - { - int advance; - - submode = speex_bits_unpack_unsigned(bits, 3); - advance = wb_skip_table[submode]; - if (advance < 0) { - TRACE__((THIS_FUNC, "Invalid mode encountered. " - "The stream is corrupted.")); - return -1; - } - TRACE__((THIS_FUNC, "WB layer skipped: %d bits", advance)); - advance -= (SB_SUBMODE_BITS+1); - speex_bits_advance(bits, advance); - - bit_ptr = bits->bitPtr; - char_ptr = bits->charPtr; - - /* Consecutive subband frames may not exceed 2 frames */ - if (++wb_count > 2) - return -1; - } - - /* End of bits, return the frame */ - if (speex_bits_remaining(bits) < 4) { - TRACE__((THIS_FUNC, "End of stream")); - return 0; - } - - /* Stop iteration, return the frame */ - if (nb_count > 0) { - bits->bitPtr = bit_ptr; - bits->charPtr = char_ptr; - return 0; - } - - /* Get control bits */ - submode = speex_bits_unpack_unsigned(bits, 4); - TRACE__((THIS_FUNC, "Control bits: %d at %d", - submode, bits->charPtr*8+bits->bitPtr)); - - if (submode == 15) { - TRACE__((THIS_FUNC, "Found submode: terminator")); - return -1; - } else if (submode == 14) { - /* in-band signal; next 4 bits contain signal id */ - submode = speex_bits_unpack_unsigned(bits, 4); - TRACE__((THIS_FUNC, "Found submode: in-band %d bits", - inband_skip_table[submode])); - speex_bits_advance(bits, inband_skip_table[submode]); - } else if (submode == 13) { - /* user in-band; next 5 bits contain msg len */ - submode = speex_bits_unpack_unsigned(bits, 5); - TRACE__((THIS_FUNC, "Found submode: user-band %d bytes", submode)); - speex_bits_advance(bits, submode * 8); - } else if (submode > 8) { - TRACE__((THIS_FUNC, "Unknown sub-mode %d", submode)); - return -1; - } else { - /* NB frame */ - int advance = submode; - speex_mode_query(&speex_nb_mode, SPEEX_SUBMODE_BITS_PER_FRAME, &advance); - if (advance < 0) { - TRACE__((THIS_FUNC, "Invalid mode encountered. " - "The stream is corrupted.")); - return -1; - } - TRACE__((THIS_FUNC, "Submode %d: %d bits", submode, advance)); - advance -= (NB_SUBMODE_BITS+1); - speex_bits_advance(bits, advance); - - ++nb_count; - } + unsigned wb_count = 0; + unsigned bit_ptr = bits->bitPtr; + unsigned char_ptr = bits->charPtr; + + /* WB frame */ + while ((speex_bits_remaining(bits) >= 4) + && speex_bits_unpack_unsigned(bits, 1)) + { + int advance; + + submode = speex_bits_unpack_unsigned(bits, 3); + advance = wb_skip_table[submode]; + if (advance < 0) { + TRACE__((THIS_FUNC, "Invalid mode encountered. " + "The stream is corrupted.")); + return -1; + } + TRACE__((THIS_FUNC, "WB layer skipped: %d bits", advance)); + advance -= (SB_SUBMODE_BITS+1); + speex_bits_advance(bits, advance); + + bit_ptr = bits->bitPtr; + char_ptr = bits->charPtr; + + /* Consecutive subband frames may not exceed 2 frames */ + if (++wb_count > 2) + return -1; + } + + /* End of bits, return the frame */ + if (speex_bits_remaining(bits) < 4) { + TRACE__((THIS_FUNC, "End of stream")); + return 0; + } + + /* Stop iteration, return the frame */ + if (nb_count > 0) { + bits->bitPtr = bit_ptr; + bits->charPtr = char_ptr; + return 0; + } + + /* Get control bits */ + submode = speex_bits_unpack_unsigned(bits, 4); + TRACE__((THIS_FUNC, "Control bits: %d at %d", + submode, bits->charPtr*8+bits->bitPtr)); + + if (submode == 15) { + TRACE__((THIS_FUNC, "Found submode: terminator")); + return -1; + } else if (submode == 14) { + /* in-band signal; next 4 bits contain signal id */ + submode = speex_bits_unpack_unsigned(bits, 4); + TRACE__((THIS_FUNC, "Found submode: in-band %d bits", + inband_skip_table[submode])); + speex_bits_advance(bits, inband_skip_table[submode]); + } else if (submode == 13) { + /* user in-band; next 5 bits contain msg len */ + submode = speex_bits_unpack_unsigned(bits, 5); + TRACE__((THIS_FUNC, "Found submode: user-band %d bytes", submode)); + speex_bits_advance(bits, submode * 8); + } else if (submode > 8) { + TRACE__((THIS_FUNC, "Unknown sub-mode %d", submode)); + return -1; + } else { + /* NB frame */ + int advance = submode; + speex_mode_query(&speex_nb_mode, SPEEX_SUBMODE_BITS_PER_FRAME, &advance); + if (advance < 0) { + TRACE__((THIS_FUNC, "Invalid mode encountered. " + "The stream is corrupted.")); + return -1; + } + TRACE__((THIS_FUNC, "Submode %d: %d bits", submode, advance)); + advance -= (NB_SUBMODE_BITS+1); + speex_bits_advance(bits, advance); + + ++nb_count; + } } return 0; @@ -828,11 +827,11 @@ static int speex_get_next_frame(SpeexBits *bits) * Get frames in the packet. */ static pj_status_t spx_codec_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { struct spx_private *spx = (struct spx_private*) codec->codec_data; unsigned samples_per_frame; @@ -846,22 +845,22 @@ static pj_status_t spx_codec_parse( pjmedia_codec *codec, speex_bits_read_from(&spx->dec_bits, (char*)pkt, (int)pkt_size); while (speex_get_next_frame(&spx->dec_bits) == 0 && - spx->dec_bits.charPtr != char_ptr) + spx->dec_bits.charPtr != char_ptr) { - frames[count].buf = (char*)pkt + char_ptr; - /* Bit info contains start bit offset of the frame */ - frames[count].bit_info = bit_ptr; - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].timestamp.u64 = ts->u64 + - (pj_uint64_t)count * samples_per_frame; - frames[count].size = spx->dec_bits.charPtr - char_ptr; - if (spx->dec_bits.bitPtr) - ++frames[count].size; - - bit_ptr = spx->dec_bits.bitPtr; - char_ptr = spx->dec_bits.charPtr; - - ++count; + frames[count].buf = (char*)pkt + char_ptr; + /* Bit info contains start bit offset of the frame */ + frames[count].bit_info = bit_ptr; + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].timestamp.u64 = ts->u64 + + (pj_uint64_t)count * samples_per_frame; + frames[count].size = spx->dec_bits.charPtr - char_ptr; + if (spx->dec_bits.bitPtr) + ++frames[count].size; + + bit_ptr = spx->dec_bits.bitPtr; + char_ptr = spx->dec_bits.charPtr; + + ++count; } *frame_cnt = count; @@ -873,9 +872,9 @@ static pj_status_t spx_codec_parse( pjmedia_codec *codec, * Encode frames. */ static pj_status_t spx_codec_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct spx_private *spx; unsigned samples_per_frame; @@ -886,36 +885,36 @@ static pj_status_t spx_codec_encode( pjmedia_codec *codec, spx = (struct spx_private*) codec->codec_data; if (input->type != PJMEDIA_FRAME_TYPE_AUDIO) { - output->size = 0; - output->buf = NULL; - output->timestamp = input->timestamp; - output->type = input->type; - return PJ_SUCCESS; + output->size = 0; + output->buf = NULL; + output->timestamp = input->timestamp; + output->type = input->type; + return PJ_SUCCESS; } nsamples = input->size >> 1; samples_per_frame=spx_factory.speex_param[spx->param_id].samples_per_frame; PJ_ASSERT_RETURN(nsamples % samples_per_frame == 0, - PJMEDIA_CODEC_EPCMFRMINLEN); + PJMEDIA_CODEC_EPCMFRMINLEN); /* Flush all the bits in the struct so we can encode a new frame */ speex_bits_reset(&spx->enc_bits); /* Encode the frames */ while (nsamples >= samples_per_frame) { - tx += speex_encode_int(spx->enc, pcm_in, &spx->enc_bits); - pcm_in += samples_per_frame; - nsamples -= samples_per_frame; + tx += speex_encode_int(spx->enc, pcm_in, &spx->enc_bits); + pcm_in += samples_per_frame; + nsamples -= samples_per_frame; } /* Check if we need not to transmit the frame (DTX) */ if (tx == 0) { - output->buf = NULL; - output->size = 0; - output->timestamp.u64 = input->timestamp.u64; - output->type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; + output->buf = NULL; + output->size = 0; + output->timestamp.u64 = input->timestamp.u64; + output->type = PJMEDIA_FRAME_TYPE_NONE; + return PJ_SUCCESS; } /* Check size. */ @@ -923,7 +922,7 @@ static pj_status_t spx_codec_encode( pjmedia_codec *codec, /* Copy the bits to an array of char that can be written */ output->size = speex_bits_write(&spx->enc_bits, - (char*)output->buf, output_buf_len); + (char*)output->buf, output_buf_len); output->type = PJMEDIA_FRAME_TYPE_AUDIO; output->timestamp = input->timestamp; @@ -934,9 +933,9 @@ static pj_status_t spx_codec_encode( pjmedia_codec *codec, * Decode frame. */ static pj_status_t spx_codec_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct spx_private *spx; unsigned samples_per_frame; @@ -945,14 +944,14 @@ static pj_status_t spx_codec_decode( pjmedia_codec *codec, samples_per_frame=spx_factory.speex_param[spx->param_id].samples_per_frame; PJ_ASSERT_RETURN(output_buf_len >= samples_per_frame << 1, - PJMEDIA_CODEC_EPCMTOOSHORT); + PJMEDIA_CODEC_EPCMTOOSHORT); if (input->type != PJMEDIA_FRAME_TYPE_AUDIO) { - pjmedia_zero_samples((pj_int16_t*)output->buf, samples_per_frame); - output->size = samples_per_frame << 1; - output->timestamp.u64 = input->timestamp.u64; - output->type = PJMEDIA_FRAME_TYPE_AUDIO; - return PJ_SUCCESS; + pjmedia_zero_samples((pj_int16_t*)output->buf, samples_per_frame); + output->size = samples_per_frame << 1; + output->timestamp.u64 = input->timestamp.u64; + output->type = PJMEDIA_FRAME_TYPE_AUDIO; + return PJ_SUCCESS; } /* Copy the data into the bit-stream struct */ @@ -975,8 +974,8 @@ static pj_status_t spx_codec_decode( pjmedia_codec *codec, * Recover lost frame. */ static pj_status_t spx_codec_recover(pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { struct spx_private *spx; unsigned count; @@ -998,4 +997,4 @@ static pj_status_t spx_codec_recover(pjmedia_codec *codec, } -#endif /* PJMEDIA_HAS_SPEEX_CODEC */ +#endif /* PJMEDIA_HAS_SPEEX_CODEC */ diff --git a/pjmedia/src/pjmedia-codec/vid_toolbox.m b/pjmedia/src/pjmedia-codec/vid_toolbox.m index 59ee75ff7b..8d1c710cb9 100644 --- a/pjmedia/src/pjmedia-codec/vid_toolbox.m +++ b/pjmedia/src/pjmedia-codec/vid_toolbox.m @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C)2017 Teluu Inc. (http://www.teluu.com) * @@ -32,37 +31,37 @@ #include "TargetConditionals.h" -#define THIS_FILE "vid_toolbox.m" +#define THIS_FILE "vid_toolbox.m" #if (defined(PJ_DARWINOS) && PJ_DARWINOS != 0 && TARGET_OS_IPHONE) #import -# define DEFAULT_WIDTH 352 -# define DEFAULT_HEIGHT 288 +# define DEFAULT_WIDTH 352 +# define DEFAULT_HEIGHT 288 #else -# define DEFAULT_WIDTH 720 -# define DEFAULT_HEIGHT 480 +# define DEFAULT_WIDTH 720 +# define DEFAULT_HEIGHT 480 #endif -#define DEFAULT_FPS 15 -#define DEFAULT_AVG_BITRATE 256000 -#define DEFAULT_MAX_BITRATE 256000 +#define DEFAULT_FPS 15 +#define DEFAULT_AVG_BITRATE 256000 +#define DEFAULT_MAX_BITRATE 256000 -#define MAX_RX_WIDTH 1200 -#define MAX_RX_HEIGHT 800 +#define MAX_RX_WIDTH 1200 +#define MAX_RX_HEIGHT 800 -#define SPS_PPS_BUF_SIZE 32 +#define SPS_PPS_BUF_SIZE 32 /* For better compatibility with other codecs (OpenH264 and x264), * we decode the whole packets at once. */ -#define DECODE_WHOLE PJ_TRUE +#define DECODE_WHOLE PJ_TRUE /* Maximum duration from one key frame to the next (in seconds). */ -#define KEYFRAME_INTERVAL PJMEDIA_CODEC_VID_TOOLBOX_MAX_KEYFRAME_INTERVAL +#define KEYFRAME_INTERVAL PJMEDIA_CODEC_VID_TOOLBOX_MAX_KEYFRAME_INTERVAL /* vidtoolbox H264 default PT */ -#define VT_H264_PT PJMEDIA_RTP_PT_H264_RSV1 +#define VT_H264_PT PJMEDIA_RTP_PT_H264_RSV1 /* * Factory operations. */ @@ -137,47 +136,47 @@ static pj_status_t vtool_codec_decode(pjmedia_vid_codec *codec, static struct vtool_factory { pjmedia_vid_codec_factory base; - pjmedia_vid_codec_mgr *mgr; + pjmedia_vid_codec_mgr *mgr; pj_pool_factory *pf; - pj_pool_t *pool; + pj_pool_t *pool; } vtool_factory; typedef struct vtool_codec_data { - pjmedia_vid_codec *codec; - pj_pool_t *pool; - pjmedia_vid_codec_param *prm; - pj_bool_t whole; - pjmedia_h264_packetizer *pktz; + pjmedia_vid_codec *codec; + pj_pool_t *pool; + pjmedia_vid_codec_param *prm; + pj_bool_t whole; + pjmedia_h264_packetizer *pktz; /* Encoder */ - VTCompressionSessionRef enc; - void *enc_buf; - unsigned enc_buf_size; - - unsigned enc_input_size; - unsigned enc_wxh; - unsigned enc_fps; - unsigned enc_frm_cnt; - unsigned enc_frame_size; - unsigned enc_processed; - pj_bool_t enc_is_keyframe; + VTCompressionSessionRef enc; + void *enc_buf; + unsigned enc_buf_size; + + unsigned enc_input_size; + unsigned enc_wxh; + unsigned enc_fps; + unsigned enc_frm_cnt; + unsigned enc_frame_size; + unsigned enc_processed; + pj_bool_t enc_is_keyframe; /* Decoder */ - VTDecompressionSessionRef dec; - pj_uint8_t *dec_buf; - unsigned dec_buf_size; - CMFormatDescriptionRef dec_format; + VTDecompressionSessionRef dec; + pj_uint8_t *dec_buf; + unsigned dec_buf_size; + CMFormatDescriptionRef dec_format; OSStatus dec_status; - unsigned dec_sps_size; - unsigned dec_pps_size; - unsigned char dec_sps[SPS_PPS_BUF_SIZE]; - unsigned char dec_pps[SPS_PPS_BUF_SIZE]; + unsigned dec_sps_size; + unsigned dec_pps_size; + unsigned char dec_sps[SPS_PPS_BUF_SIZE]; + unsigned char dec_pps[SPS_PPS_BUF_SIZE]; - pjmedia_frame *dec_frame; - pj_bool_t dec_fmt_change; + pjmedia_frame *dec_frame; + pj_bool_t dec_fmt_change; } vtool_codec_data; /* Prototypes */ @@ -201,8 +200,8 @@ static void dispatch_sync_on_main_queue(void (^block)(void)) pj_status_t status; if (vtool_factory.pool != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } if (!mgr) mgr = pjmedia_vid_codec_mgr_instance(); @@ -215,20 +214,20 @@ static void dispatch_sync_on_main_queue(void (^block)(void)) vtool_factory.pf = pf; vtool_factory.pool = pj_pool_create(pf, "vtoolfactory", 256, 256, NULL); if (!vtool_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Registering format match for SDP negotiation */ status = pjmedia_sdp_neg_register_fmt_match_cb( - &h264_name, - &pjmedia_vid_codec_h264_match_sdp); + &h264_name, + &pjmedia_vid_codec_h264_match_sdp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Register codec factory to codec manager. */ status = pjmedia_vid_codec_mgr_register_factory(mgr, - &vtool_factory.base); + &vtool_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; PJ_LOG(4,(THIS_FILE, "Video Toolbox codec initialized")); @@ -249,13 +248,13 @@ static void dispatch_sync_on_main_queue(void (^block)(void)) pj_status_t status = PJ_SUCCESS; if (vtool_factory.pool == NULL) { - /* Already deinitialized */ - return PJ_SUCCESS; + /* Already deinitialized */ + return PJ_SUCCESS; } /* Unregister Video Toolbox codecs factory. */ status = pjmedia_vid_codec_mgr_unregister_factory(vtool_factory.mgr, - &vtool_factory.base); + &vtool_factory.base); /* Destroy pool. */ pj_pool_release(vtool_factory.pool); @@ -270,9 +269,9 @@ static pj_status_t vtool_test_alloc(pjmedia_vid_codec_factory *factory, PJ_ASSERT_RETURN(factory == &vtool_factory.base, PJ_EINVAL); if (info->fmt_id == PJMEDIA_FORMAT_H264 && - info->pt == VT_H264_PT) + info->pt == VT_H264_PT) { - return PJ_SUCCESS; + return PJ_SUCCESS; } return PJMEDIA_CODEC_EUNSUP; @@ -293,12 +292,12 @@ static pj_status_t vtool_default_attr(pjmedia_vid_codec_factory *factory, /* Encoded format */ pjmedia_format_init_video(&attr->enc_fmt, PJMEDIA_FORMAT_H264, DEFAULT_WIDTH, DEFAULT_HEIGHT, - DEFAULT_FPS, 1); + DEFAULT_FPS, 1); /* Decoded format */ pjmedia_format_init_video(&attr->dec_fmt, PJMEDIA_FORMAT_I420, DEFAULT_WIDTH, DEFAULT_HEIGHT, - DEFAULT_FPS, 1); + DEFAULT_FPS, 1); /* Decoding fmtp */ attr->dec_fmtp.cnt = 2; @@ -334,7 +333,7 @@ static pj_status_t vtool_enum_info(pjmedia_vid_codec_factory *factory, info->dec_fmt_id_cnt = 1; info->dec_fmt_id[0] = PJMEDIA_FORMAT_I420; info->packings = PJMEDIA_VID_PACKING_PACKETS | - PJMEDIA_VID_PACKING_WHOLE; + PJMEDIA_VID_PACKING_WHOLE; info->fps_cnt = 3; info->fps[0].num = 15; info->fps[0].denum = 1; @@ -361,7 +360,7 @@ static pj_status_t vtool_alloc_codec(pjmedia_vid_codec_factory *factory, pool = pj_pool_create(vtool_factory.pf, "vtool%p", 512, 512, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* codec instance */ codec = PJ_POOL_ZALLOC_T(pool, pjmedia_vid_codec); @@ -432,38 +431,38 @@ static void encode_cb(void *outputCallbackRefCon, array = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, true); if (array) dict = (CFDictionaryRef)CFArrayGetValueAtIndex(array, 0); if (dict && !CFDictionaryContainsKey(dict,kCMSampleAttachmentKey_NotSync)) - vtool_data->enc_is_keyframe = PJ_TRUE; + vtool_data->enc_is_keyframe = PJ_TRUE; if (vtool_data->enc_is_keyframe) { - CMFormatDescriptionRef format; - size_t enc_sps_size, enc_sps_cnt; - size_t enc_pps_size, enc_pps_cnt; - const uint8_t *enc_sps, *enc_pps; - OSStatus status; - - format = CMSampleBufferGetFormatDescription(sampleBuffer); + CMFormatDescriptionRef format; + size_t enc_sps_size, enc_sps_cnt; + size_t enc_pps_size, enc_pps_cnt; + const uint8_t *enc_sps, *enc_pps; + OSStatus status; + + format = CMSampleBufferGetFormatDescription(sampleBuffer); /* Get SPS */ status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( - format, 0, &enc_sps, &enc_sps_size, &enc_sps_cnt, 0 ); + format, 0, &enc_sps, &enc_sps_size, &enc_sps_cnt, 0 ); if (status != noErr) return; - /* Get PPS */ + /* Get PPS */ status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( - format, 1, &enc_pps, &enc_pps_size, &enc_pps_cnt, 0 ); + format, 1, &enc_pps, &enc_pps_size, &enc_pps_cnt, 0 ); if (status != noErr) return; - /* Append SPS and PPS to output frame */ - pj_assert (enc_sps_size + enc_pps_size + 2 * code_size <= - vtool_data->enc_buf_size); - pj_memcpy(buf + offset, start_code, code_size); - offset += code_size; - pj_memcpy(buf + offset, enc_sps, enc_sps_size); - offset += enc_sps_size; - pj_memcpy(buf + offset, start_code, code_size); - offset += code_size; - pj_memcpy(buf + offset, enc_pps, enc_pps_size); - offset += enc_pps_size; + /* Append SPS and PPS to output frame */ + pj_assert (enc_sps_size + enc_pps_size + 2 * code_size <= + vtool_data->enc_buf_size); + pj_memcpy(buf + offset, start_code, code_size); + offset += code_size; + pj_memcpy(buf + offset, enc_sps, enc_sps_size); + offset += enc_sps_size; + pj_memcpy(buf + offset, start_code, code_size); + offset += code_size; + pj_memcpy(buf + offset, enc_pps, enc_pps_size); + offset += enc_pps_size; } pj_assert(CMSampleBufferGetNumSamples(sampleBuffer) == 1); @@ -472,8 +471,8 @@ static void encode_cb(void *outputCallbackRefCon, block_buf = CMSampleBufferGetDataBuffer(sampleBuffer); status = CMBlockBufferGetDataPointer(block_buf, 0, &length, NULL, &data); if (status != noErr || (offset + length) > vtool_data->enc_buf_size) - return; - + return; + pj_assert(CMBlockBufferIsRangeContiguous(block_buf, 0, length)); pj_assert(length == CMBlockBufferGetDataLength(block_buf)); @@ -481,7 +480,7 @@ static void encode_cb(void *outputCallbackRefCon, while (buf_pos < length - avcc_size) { uint32_t data_length; - /* Get data length and copy the data to the output buffer */ + /* Get data length and copy the data to the output buffer */ pj_memcpy(&data_length, data + buf_pos, avcc_size); data_length = pj_ntohl(data_length); pj_assert(buf_pos + data_length + avcc_size <= length); @@ -499,76 +498,76 @@ static void encode_cb(void *outputCallbackRefCon, static OSStatus create_encoder(vtool_codec_data *vtool_data) { - pjmedia_vid_codec_param *param = vtool_data->prm; - CFDictionaryRef supported_prop; - OSStatus ret; + pjmedia_vid_codec_param *param = vtool_data->prm; + CFDictionaryRef supported_prop; + OSStatus ret; /* Destroy if initialized before */ if (vtool_data->enc) { - VTCompressionSessionInvalidate(vtool_data->enc); - CFRelease(vtool_data->enc); - vtool_data->enc = NULL; + VTCompressionSessionInvalidate(vtool_data->enc); + CFRelease(vtool_data->enc); + vtool_data->enc = NULL; } /* Create encoder session */ ret = VTCompressionSessionCreate(NULL, (int)param->enc_fmt.det.vid.size.w, - (int)param->enc_fmt.det.vid.size.h, - kCMVideoCodecType_H264, NULL, NULL, - NULL, encode_cb, vtool_data, - &vtool_data->enc); + (int)param->enc_fmt.det.vid.size.h, + kCMVideoCodecType_H264, NULL, NULL, + NULL, encode_cb, vtool_data, + &vtool_data->enc); if (ret != noErr) { - PJ_LOG(4,(THIS_FILE, "VTCompressionCreate failed, ret=%d", ret)); - return ret; + PJ_LOG(4,(THIS_FILE, "VTCompressionCreate failed, ret=%d", ret)); + return ret; } #define SET_PROPERTY(sess, prop, val) \ { \ ret = VTSessionSetProperty(sess, prop, val); \ if (ret != noErr) \ - PJ_LOG(5,(THIS_FILE, "Failed to set session property %s", #prop)); \ + PJ_LOG(5,(THIS_FILE, "Failed to set session property %s", #prop)); \ } SET_PROPERTY(vtool_data->enc, - kVTCompressionPropertyKey_ProfileLevel, - kVTProfileLevel_H264_Baseline_AutoLevel); + kVTCompressionPropertyKey_ProfileLevel, + kVTProfileLevel_H264_Baseline_AutoLevel); SET_PROPERTY(vtool_data->enc, kVTCompressionPropertyKey_RealTime, - kCFBooleanTrue); + kCFBooleanTrue); SET_PROPERTY(vtool_data->enc, - kVTCompressionPropertyKey_AllowFrameReordering, - kCFBooleanFalse); + kVTCompressionPropertyKey_AllowFrameReordering, + kCFBooleanFalse); SET_PROPERTY(vtool_data->enc, - kVTCompressionPropertyKey_AverageBitRate, - (__bridge CFTypeRef)@(param->enc_fmt.det.vid.avg_bps)); + kVTCompressionPropertyKey_AverageBitRate, + (__bridge CFTypeRef)@(param->enc_fmt.det.vid.avg_bps)); vtool_data->enc_fps = param->enc_fmt.det.vid.fps.num / - param->enc_fmt.det.vid.fps.denum; + param->enc_fmt.det.vid.fps.denum; SET_PROPERTY(vtool_data->enc, - kVTCompressionPropertyKey_ExpectedFrameRate, - (__bridge CFTypeRef)@(vtool_data->enc_fps)); + kVTCompressionPropertyKey_ExpectedFrameRate, + (__bridge CFTypeRef)@(vtool_data->enc_fps)); SET_PROPERTY(vtool_data->enc, - kVTCompressionPropertyKey_DataRateLimits, - ((__bridge CFArrayRef) // [Bytes, second] - @[@(param->enc_fmt.det.vid.max_bps >> 3), @(1)])); + kVTCompressionPropertyKey_DataRateLimits, + ((__bridge CFArrayRef) // [Bytes, second] + @[@(param->enc_fmt.det.vid.max_bps >> 3), @(1)])); SET_PROPERTY(vtool_data->enc, - kVTCompressionPropertyKey_MaxKeyFrameInterval, - (__bridge CFTypeRef)@(KEYFRAME_INTERVAL * - param->enc_fmt.det.vid.fps.num / - param->enc_fmt.det.vid.fps.denum)); + kVTCompressionPropertyKey_MaxKeyFrameInterval, + (__bridge CFTypeRef)@(KEYFRAME_INTERVAL * + param->enc_fmt.det.vid.fps.num / + param->enc_fmt.det.vid.fps.denum)); SET_PROPERTY(vtool_data->enc, - kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, - (__bridge CFTypeRef)@(KEYFRAME_INTERVAL)); + kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, + (__bridge CFTypeRef)@(KEYFRAME_INTERVAL)); ret = VTSessionCopySupportedPropertyDictionary(vtool_data->enc, - &supported_prop); + &supported_prop); if (ret == noErr && CFDictionaryContainsKey(supported_prop, - kVTCompressionPropertyKey_MaxH264SliceBytes)) + kVTCompressionPropertyKey_MaxH264SliceBytes)) { - /* kVTCompressionPropertyKey_MaxH264SliceBytes is not yet supported - * by Apple. We leave it here for possible future enhancements. - SET_PROPERTY(vtool_data->enc, - kVTCompressionPropertyKey_MaxH264SliceBytes, - // param->enc_mtu - NAL_HEADER_ADD_0X30BYTES - (__bridge CFTypeRef)@(param->enc_mtu - 50)); + /* kVTCompressionPropertyKey_MaxH264SliceBytes is not yet supported + * by Apple. We leave it here for possible future enhancements. + SET_PROPERTY(vtool_data->enc, + kVTCompressionPropertyKey_MaxH264SliceBytes, + // param->enc_mtu - NAL_HEADER_ADD_0X30BYTES + (__bridge CFTypeRef)@(param->enc_mtu - 50)); */ } @@ -581,12 +580,12 @@ static OSStatus create_encoder(vtool_codec_data *vtool_data) static pj_status_t vtool_codec_open(pjmedia_vid_codec *codec, pjmedia_vid_codec_param *codec_param ) { - vtool_codec_data *vtool_data; - pjmedia_vid_codec_param *param; + vtool_codec_data *vtool_data; + pjmedia_vid_codec_param *param; pjmedia_h264_packetizer_cfg pktz_cfg; pjmedia_vid_codec_h264_fmtp h264_fmtp; - pj_status_t status; - OSStatus ret; + pj_status_t status; + OSStatus ret; PJ_ASSERT_RETURN(codec && codec_param, PJ_EINVAL); @@ -601,13 +600,13 @@ static pj_status_t vtool_codec_open(pjmedia_vid_codec *codec, pj_bzero(&h264_fmtp, sizeof(h264_fmtp)); status = pjmedia_vid_codec_h264_parse_fmtp(¶m->enc_fmtp, &h264_fmtp); if (status != PJ_SUCCESS) - return status; + return status; /* Apply SDP fmtp to format in codec param */ if (!param->ignore_fmtp) { - status = pjmedia_vid_codec_h264_apply_fmtp(param); - if (status != PJ_SUCCESS) - return status; + status = pjmedia_vid_codec_h264_apply_fmtp(param); + if (status != PJ_SUCCESS) + return status; } pj_bzero(&pktz_cfg, sizeof(pktz_cfg)); @@ -615,11 +614,11 @@ static pj_status_t vtool_codec_open(pjmedia_vid_codec *codec, pktz_cfg.unpack_nal_start = 4; /* Packetization mode */ if (h264_fmtp.packetization_mode == 0) - pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL; + pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL; else if (h264_fmtp.packetization_mode == 1) - pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED; + pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED; else - return PJ_ENOTSUP; + return PJ_ENOTSUP; /* Video Toolbox encoder doesn't support setting maximum slice size, * so we cannot use single NAL mode since the NAL size likely * exceeds the MTU. @@ -629,77 +628,77 @@ static pj_status_t vtool_codec_open(pjmedia_vid_codec *codec, status = pjmedia_h264_packetizer_create(vtool_data->pool, &pktz_cfg, &vtool_data->pktz); if (status != PJ_SUCCESS) - return status; + return status; vtool_data->whole = (param->packing == PJMEDIA_VID_PACKING_WHOLE); if (1) { /* Init format info and apply-param of encoder */ const pjmedia_video_format_info *enc_vfi; - pjmedia_video_apply_fmt_param enc_vafp; + pjmedia_video_apply_fmt_param enc_vafp; - enc_vfi = pjmedia_get_video_format_info(NULL,codec_param->dec_fmt.id); - if (!enc_vfi) + enc_vfi = pjmedia_get_video_format_info(NULL,codec_param->dec_fmt.id); + if (!enc_vfi) return PJ_EINVAL; - pj_bzero(&enc_vafp, sizeof(enc_vafp)); - enc_vafp.size = codec_param->enc_fmt.det.vid.size; - enc_vafp.buffer = NULL; - status = (*enc_vfi->apply_fmt)(enc_vfi, &enc_vafp); - if (status != PJ_SUCCESS) + pj_bzero(&enc_vafp, sizeof(enc_vafp)); + enc_vafp.size = codec_param->enc_fmt.det.vid.size; + enc_vafp.buffer = NULL; + status = (*enc_vfi->apply_fmt)(enc_vfi, &enc_vafp); + if (status != PJ_SUCCESS) return status; - vtool_data->enc_wxh = codec_param->enc_fmt.det.vid.size.w * - codec_param->enc_fmt.det.vid.size.h; - vtool_data->enc_input_size = enc_vafp.framebytes; - if (!vtool_data->whole) { - vtool_data->enc_buf_size = (unsigned)enc_vafp.framebytes; - vtool_data->enc_buf = pj_pool_alloc(vtool_data->pool, - vtool_data->enc_buf_size); - } + vtool_data->enc_wxh = codec_param->enc_fmt.det.vid.size.w * + codec_param->enc_fmt.det.vid.size.h; + vtool_data->enc_input_size = enc_vafp.framebytes; + if (!vtool_data->whole) { + vtool_data->enc_buf_size = (unsigned)enc_vafp.framebytes; + vtool_data->enc_buf = pj_pool_alloc(vtool_data->pool, + vtool_data->enc_buf_size); + } } /* Create encoder */ ret = create_encoder(vtool_data); if (ret != noErr) - return PJMEDIA_CODEC_EFAILED; + return PJMEDIA_CODEC_EFAILED; /* If available, use the "sprop-parameter-sets" fmtp from remote SDP * to create the decoder. */ if (h264_fmtp.sprop_param_sets_len) { - const pj_uint8_t start_code[3] = {0, 0, 1}; - const int code_size = PJ_ARRAY_SIZE(start_code); - unsigned i, j; - - for (i = h264_fmtp.sprop_param_sets_len-code_size; i >= code_size; - i--) - { - for (j = 0; j < code_size; j++) { - if (h264_fmtp.sprop_param_sets[i+j] != start_code[j]) { - break; - } - } - } - - if (i >= code_size) { - vtool_data->dec_sps_size = i - code_size; - pj_memcpy(vtool_data->dec_sps, - &h264_fmtp.sprop_param_sets[code_size], - vtool_data->dec_sps_size); - - vtool_data->dec_pps_size = h264_fmtp.sprop_param_sets_len - - code_size-i; - pj_memcpy(vtool_data->dec_pps, - &h264_fmtp.sprop_param_sets[i + code_size], - vtool_data->dec_pps_size); - - create_decoder(vtool_data); - } + const pj_uint8_t start_code[3] = {0, 0, 1}; + const int code_size = PJ_ARRAY_SIZE(start_code); + unsigned i, j; + + for (i = h264_fmtp.sprop_param_sets_len-code_size; i >= code_size; + i--) + { + for (j = 0; j < code_size; j++) { + if (h264_fmtp.sprop_param_sets[i+j] != start_code[j]) { + break; + } + } + } + + if (i >= code_size) { + vtool_data->dec_sps_size = i - code_size; + pj_memcpy(vtool_data->dec_sps, + &h264_fmtp.sprop_param_sets[code_size], + vtool_data->dec_sps_size); + + vtool_data->dec_pps_size = h264_fmtp.sprop_param_sets_len - + code_size-i; + pj_memcpy(vtool_data->dec_pps, + &h264_fmtp.sprop_param_sets[i + code_size], + vtool_data->dec_pps_size); + + create_decoder(vtool_data); + } } /* Create decoder buffer */ vtool_data->dec_buf_size = (MAX_RX_WIDTH * MAX_RX_HEIGHT * 3 >> 1) + - (MAX_RX_WIDTH); + (MAX_RX_WIDTH); vtool_data->dec_buf = (pj_uint8_t*)pj_pool_alloc(vtool_data->pool, vtool_data->dec_buf_size); @@ -718,19 +717,19 @@ static pj_status_t vtool_codec_close(pjmedia_vid_codec *codec) vtool_data = (vtool_codec_data*) codec->codec_data; if (vtool_data->enc) { - VTCompressionSessionInvalidate(vtool_data->enc); - CFRelease(vtool_data->enc); - vtool_data->enc = NULL; + VTCompressionSessionInvalidate(vtool_data->enc); + CFRelease(vtool_data->enc); + vtool_data->enc = NULL; } if (vtool_data->dec) { - VTDecompressionSessionInvalidate(vtool_data->dec); - CFRelease(vtool_data->dec); - vtool_data->dec = NULL; + VTDecompressionSessionInvalidate(vtool_data->dec); + CFRelease(vtool_data->dec); + vtool_data->dec = NULL; } if (vtool_data->dec_format) - CFRelease(vtool_data->dec_format); + CFRelease(vtool_data->dec_format); return PJ_SUCCESS; } @@ -789,42 +788,42 @@ static pj_status_t vtool_codec_encode_begin(pjmedia_vid_codec *codec, #if TARGET_OS_IPHONE ret = CVPixelBufferCreate(NULL, - vtool_data->prm->enc_fmt.det.vid.size.w, - vtool_data->prm->enc_fmt.det.vid.size.h, - kCVPixelFormatType_420YpCbCr8Planar, /* I420 */ - NULL, &image_buf); + vtool_data->prm->enc_fmt.det.vid.size.w, + vtool_data->prm->enc_fmt.det.vid.size.h, + kCVPixelFormatType_420YpCbCr8Planar, /* I420 */ + NULL, &image_buf); if (ret == noErr) { size_t i, count; - CVPixelBufferLockBaseAddress(image_buf, 0); + CVPixelBufferLockBaseAddress(image_buf, 0); - count = CVPixelBufferGetPlaneCount(image_buf); - for (i = 0; i < count; i++) { - char *ptr = (char*)CVPixelBufferGetBaseAddressOfPlane(image_buf, i); - char *src = (char*)base_addr[i]; - size_t bpr = CVPixelBufferGetBytesPerRowOfPlane(image_buf, i); - int j; + count = CVPixelBufferGetPlaneCount(image_buf); + for (i = 0; i < count; i++) { + char *ptr = (char*)CVPixelBufferGetBaseAddressOfPlane(image_buf, i); + char *src = (char*)base_addr[i]; + size_t bpr = CVPixelBufferGetBytesPerRowOfPlane(image_buf, i); + int j; - pj_assert(bpr >= plane_bpr[i]); - for (j = 0; j < plane_h[i]; ++j) { - pj_memcpy(ptr, src, plane_bpr[i]); - src += plane_bpr[i]; - ptr += bpr; - } - } + pj_assert(bpr >= plane_bpr[i]); + for (j = 0; j < plane_h[i]; ++j) { + pj_memcpy(ptr, src, plane_bpr[i]); + src += plane_bpr[i]; + ptr += bpr; + } + } - CVPixelBufferUnlockBaseAddress(image_buf, 0); + CVPixelBufferUnlockBaseAddress(image_buf, 0); } #else ret = CVPixelBufferCreateWithPlanarBytes(NULL, - vtool_data->prm->enc_fmt.det.vid.size.w, - vtool_data->prm->enc_fmt.det.vid.size.h, - kCVPixelFormatType_420YpCbCr8Planar, /* I420 */ - NULL, vtool_data->enc_input_size, - 3, /* number of planes of I420 */ - base_addr, - (size_t *)plane_w, (size_t *)plane_h, (size_t *)plane_bpr, - NULL, NULL, NULL, &image_buf); + vtool_data->prm->enc_fmt.det.vid.size.w, + vtool_data->prm->enc_fmt.det.vid.size.h, + kCVPixelFormatType_420YpCbCr8Planar, /* I420 */ + NULL, vtool_data->enc_input_size, + 3, /* number of planes of I420 */ + base_addr, + (size_t *)plane_w, (size_t *)plane_h, (size_t *)plane_bpr, + NULL, NULL, NULL, &image_buf); #endif if (ret != noErr) { @@ -837,49 +836,49 @@ static pj_status_t vtool_codec_encode_begin(pjmedia_vid_codec *codec, vtool_data->enc_frame_size = vtool_data->enc_processed = 0; if (vtool_data->whole) { - vtool_data->enc_buf = output->buf; - vtool_data->enc_buf_size = out_size; + vtool_data->enc_buf = output->buf; + vtool_data->enc_buf_size = out_size; } if (opt && opt->force_keyframe) { - frm_prop = @{ (__bridge NSString *) - kVTEncodeFrameOptionKey_ForceKeyFrame: @YES }; + frm_prop = @{ (__bridge NSString *) + kVTEncodeFrameOptionKey_ForceKeyFrame: @YES }; } ret = VTCompressionSessionEncodeFrame(vtool_data->enc, image_buf, - ts, dur, - (__bridge CFDictionaryRef)frm_prop, - NULL, NULL); + ts, dur, + (__bridge CFDictionaryRef)frm_prop, + NULL, NULL); if (ret == kVTInvalidSessionErr) { #if TARGET_OS_IPHONE - /* Just return if app is not active, i.e. in the bg. */ - __block UIApplicationState state; - - dispatch_sync_on_main_queue(^{ - state = [UIApplication sharedApplication].applicationState; - }); - if (state != UIApplicationStateActive) { - *has_more = PJ_FALSE; - output->size = 0; - output->type = PJMEDIA_FRAME_TYPE_NONE; - - CVPixelBufferRelease(image_buf); - return PJ_SUCCESS; - } + /* Just return if app is not active, i.e. in the bg. */ + __block UIApplicationState state; + + dispatch_sync_on_main_queue(^{ + state = [UIApplication sharedApplication].applicationState; + }); + if (state != UIApplicationStateActive) { + *has_more = PJ_FALSE; + output->size = 0; + output->type = PJMEDIA_FRAME_TYPE_NONE; + + CVPixelBufferRelease(image_buf); + return PJ_SUCCESS; + } #endif - /* Reset compression session */ + /* Reset compression session */ ret = create_encoder(vtool_data); - PJ_LOG(3,(THIS_FILE, "Encoder needs to be reset [1]: %s (%d)", - (ret == noErr? "success": "fail"), ret)); + PJ_LOG(3,(THIS_FILE, "Encoder needs to be reset [1]: %s (%d)", + (ret == noErr? "success": "fail"), ret)); if (ret == noErr) { - /* Retry encoding the frame after successful encoder reset. */ - ret = VTCompressionSessionEncodeFrame(vtool_data->enc, image_buf, - ts, dur, - (__bridge CFDictionaryRef) - frm_prop, - NULL, NULL); - } + /* Retry encoding the frame after successful encoder reset. */ + ret = VTCompressionSessionEncodeFrame(vtool_data->enc, image_buf, + ts, dur, + (__bridge CFDictionaryRef) + frm_prop, + NULL, NULL); + } } if (ret != noErr) { @@ -892,14 +891,14 @@ static pj_status_t vtool_codec_encode_begin(pjmedia_vid_codec *codec, ts.flags = kCMTimeFlags_Indefinite; ret = VTCompressionSessionCompleteFrames(vtool_data->enc, ts); if (ret == kVTInvalidSessionErr) { - /* Reset compression session */ + /* Reset compression session */ ret = create_encoder(vtool_data); - PJ_LOG(3,(THIS_FILE, "Encoder needs to be reset [2]: %s (%d)", - (ret == noErr? "success": "fail"), ret)); + PJ_LOG(3,(THIS_FILE, "Encoder needs to be reset [2]: %s (%d)", + (ret == noErr? "success": "fail"), ret)); if (ret == PJ_SUCCESS) { - /* Retry finishing the encoding after successful encoder reset. */ - ret = VTCompressionSessionCompleteFrames(vtool_data->enc, ts); - } + /* Retry finishing the encoding after successful encoder reset. */ + ret = VTCompressionSessionCompleteFrames(vtool_data->enc, ts); + } } if (ret != noErr) { @@ -911,9 +910,9 @@ static pj_status_t vtool_codec_encode_begin(pjmedia_vid_codec *codec, CVPixelBufferRelease(image_buf); if (vtool_data->whole) { - *has_more = PJ_FALSE; - output->size = vtool_data->enc_frame_size; - return PJ_SUCCESS; + *has_more = PJ_FALSE; + output->size = vtool_data->enc_frame_size; + return PJ_SUCCESS; } return vtool_codec_encode_more(codec, out_size, output, has_more); @@ -936,20 +935,20 @@ static pj_status_t vtool_codec_encode_more(pjmedia_vid_codec *codec, vtool_data = (vtool_codec_data*) codec->codec_data; if (vtool_data->enc_processed >= vtool_data->enc_frame_size) { - /* No more frame */ - *has_more = PJ_FALSE; - output->size = 0; - output->type = PJMEDIA_FRAME_TYPE_NONE; + /* No more frame */ + *has_more = PJ_FALSE; + output->size = 0; + output->type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; + return PJ_SUCCESS; } /* We have outstanding frame in packetizer */ status = pjmedia_h264_packetize(vtool_data->pktz, - (pj_uint8_t*)vtool_data->enc_buf, - vtool_data->enc_frame_size, - &vtool_data->enc_processed, - &payload, &payload_len); + (pj_uint8_t*)vtool_data->enc_buf, + vtool_data->enc_frame_size, + &vtool_data->enc_processed, + &payload, &payload_len); if (status != PJ_SUCCESS) { /* Reset */ vtool_data->enc_frame_size = vtool_data->enc_processed = 0; @@ -980,27 +979,27 @@ static int process_i420(CVImageBufferRef src_buf, pj_uint8_t *dst) count = CVPixelBufferGetPlaneCount(src_buf); for (i = 0; i < count; i++) { - pj_uint8_t *psrc; - pj_size_t src_w, dst_w, h; - - psrc = CVPixelBufferGetBaseAddressOfPlane(src_buf, i); - src_w = CVPixelBufferGetBytesPerRowOfPlane(src_buf, i); - dst_w = CVPixelBufferGetWidthOfPlane(src_buf, i); - h = CVPixelBufferGetHeightOfPlane(src_buf, i); - - /* Check if clipping is required */ - if (src_w == dst_w) { - pj_size_t plane_size = dst_w * h; - pj_memcpy(pdst, psrc, plane_size); - pdst += plane_size; - } else { - pj_size_t j = 0; - for (; j < h; ++j) { - pj_memcpy(pdst, psrc, dst_w); - pdst += dst_w; - psrc += src_w; - } - } + pj_uint8_t *psrc; + pj_size_t src_w, dst_w, h; + + psrc = CVPixelBufferGetBaseAddressOfPlane(src_buf, i); + src_w = CVPixelBufferGetBytesPerRowOfPlane(src_buf, i); + dst_w = CVPixelBufferGetWidthOfPlane(src_buf, i); + h = CVPixelBufferGetHeightOfPlane(src_buf, i); + + /* Check if clipping is required */ + if (src_w == dst_w) { + pj_size_t plane_size = dst_w * h; + pj_memcpy(pdst, psrc, plane_size); + pdst += plane_size; + } else { + pj_size_t j = 0; + for (; j < h; ++j) { + pj_memcpy(pdst, psrc, dst_w); + pdst += dst_w; + psrc += src_w; + } + } } return (pdst - dst); @@ -1008,12 +1007,12 @@ static int process_i420(CVImageBufferRef src_buf, pj_uint8_t *dst) static void decode_cb(void *decompressionOutputRefCon, - void *sourceFrameRefCon, - OSStatus status, - VTDecodeInfoFlags infoFlags, - CVImageBufferRef imageBuffer, - CMTime presentationTimeStamp, - CMTime presentationDuration) + void *sourceFrameRefCon, + OSStatus status, + VTDecodeInfoFlags infoFlags, + CVImageBufferRef imageBuffer, + CMTime presentationTimeStamp, + CMTime presentationDuration) { struct vtool_codec_data *vtool_data; pj_size_t width, height, len; @@ -1033,11 +1032,11 @@ static void decode_cb(void *decompressionOutputRefCon, /* Detect format change */ if (width != vtool_data->prm->dec_fmt.det.vid.size.w || - height != vtool_data->prm->dec_fmt.det.vid.size.h) + height != vtool_data->prm->dec_fmt.det.vid.size.h) { - vtool_data->dec_fmt_change = PJ_TRUE; - vtool_data->prm->dec_fmt.det.vid.size.w = width; - vtool_data->prm->dec_fmt.det.vid.size.h = height; + vtool_data->dec_fmt_change = PJ_TRUE; + vtool_data->prm->dec_fmt.det.vid.size.w = width; + vtool_data->prm->dec_fmt.det.vid.size.h = height; } else { vtool_data->dec_fmt_change = PJ_FALSE; } @@ -1051,9 +1050,9 @@ static void decode_cb(void *decompressionOutputRefCon, static OSStatus create_decoder(struct vtool_codec_data *vtool_data) { uint8_t *param_ptrs[2] = {vtool_data->dec_sps, - vtool_data->dec_pps}; + vtool_data->dec_pps}; const size_t param_sizes[2] = {vtool_data->dec_sps_size, - vtool_data->dec_pps_size}; + vtool_data->dec_pps_size}; const int code_size = 4; // PJ_ARRAY_SIZE(start_code); CMFormatDescriptionRef dec_format; VTDecompressionOutputCallbackRecord cbr; @@ -1069,15 +1068,15 @@ static OSStatus create_decoder(struct vtool_codec_data *vtool_data) param_sizes, code_size, &dec_format); if (ret != noErr) { PJ_LOG(4,(THIS_FILE, "Failed to create video format " - "description %d", ret)); - return ret; + "description %d", ret)); + return ret; } if (!vtool_data->dec || !vtool_data->dec_format || - !CMFormatDescriptionEqual(dec_format, vtool_data->dec_format)) + !CMFormatDescriptionEqual(dec_format, vtool_data->dec_format)) { - if (vtool_data->dec_format) - CFRelease(vtool_data->dec_format); + if (vtool_data->dec_format) + CFRelease(vtool_data->dec_format); vtool_data->dec_format = dec_format; } else { CFRelease(dec_format); @@ -1088,30 +1087,30 @@ static OSStatus create_decoder(struct vtool_codec_data *vtool_data) cbr.decompressionOutputRefCon = vtool_data; if (vtool_data->dec) { - VTDecompressionSessionInvalidate(vtool_data->dec); - CFRelease(vtool_data->dec); - vtool_data->dec = NULL; + VTDecompressionSessionInvalidate(vtool_data->dec); + CFRelease(vtool_data->dec); + vtool_data->dec = NULL; } dst_attr = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt: /* I420 */ - kCVPixelFormatType_420YpCbCr8Planar], - kCVPixelBufferPixelFormatTypeKey, + kCVPixelFormatType_420YpCbCr8Planar], + kCVPixelBufferPixelFormatTypeKey, nil]; ret = VTDecompressionSessionCreate(NULL, vtool_data->dec_format, NULL, (__bridge CFDictionaryRef)dst_attr, &cbr, &vtool_data->dec); if (ret != noErr) { PJ_LOG(3,(THIS_FILE, "Failed to create decompression session %d", - ret)); + ret)); } SET_PROPERTY(vtool_data->dec, kVTCompressionPropertyKey_RealTime, - kCFBooleanTrue); + kCFBooleanTrue); #if !TARGET_OS_IPHONE SET_PROPERTY(vtool_data->dec, - kVTVideoDecoderSpecification_EnableHardwareAcceleratedVideoDecoder, - kCFBooleanTrue); + kVTVideoDecoderSpecification_EnableHardwareAcceleratedVideoDecoder, + kCFBooleanTrue); #endif return ret; @@ -1144,49 +1143,49 @@ static pj_status_t vtool_codec_decode(pjmedia_vid_codec *codec, */ whole_len = 0; if (vtool_data->whole) { - for (i=0; i vtool_data->dec_buf_size) { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow")); - status = PJMEDIA_CODEC_EFRMTOOSHORT; - break; - } - - pj_memcpy( vtool_data->dec_buf + whole_len, - (pj_uint8_t*)packets[i].buf, - packets[i].size); - whole_len += packets[i].size; - } + for (i=0; i vtool_data->dec_buf_size) { + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow")); + status = PJMEDIA_CODEC_EFRMTOOSHORT; + break; + } + + pj_memcpy( vtool_data->dec_buf + whole_len, + (pj_uint8_t*)packets[i].buf, + packets[i].size); + whole_len += packets[i].size; + } } else { - for (i=0; i - vtool_data->dec_buf_size) - { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]")); - status = PJMEDIA_CODEC_EFRMTOOSHORT; - break; - } - - status = pjmedia_h264_unpacketize( vtool_data->pktz, - (pj_uint8_t*)packets[i].buf, - packets[i].size, - vtool_data->dec_buf, - vtool_data->dec_buf_size, - &whole_len); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, "Unpacketize error")); - continue; - } - } + for (i=0; i + vtool_data->dec_buf_size) + { + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]")); + status = PJMEDIA_CODEC_EFRMTOOSHORT; + break; + } + + status = pjmedia_h264_unpacketize( vtool_data->pktz, + (pj_uint8_t*)packets[i].buf, + packets[i].size, + vtool_data->dec_buf, + vtool_data->dec_buf_size, + &whole_len); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, "Unpacketize error")); + continue; + } + } } if (whole_len + code_size > vtool_data->dec_buf_size || - whole_len <= code_size + 1) + whole_len <= code_size + 1) { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow or unpacketize error " - "size: %d, buffer: %d", whole_len, - vtool_data->dec_buf_size)); - status = PJMEDIA_CODEC_EFRMTOOSHORT; + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow or unpacketize error " + "size: %d, buffer: %d", whole_len, + vtool_data->dec_buf_size)); + status = PJMEDIA_CODEC_EFRMTOOSHORT; } if (status != PJ_SUCCESS) @@ -1200,186 +1199,186 @@ static pj_status_t vtool_codec_decode(pjmedia_vid_codec *codec, */ buf_pos = 0; for ( frm_cnt=0; ; ++frm_cnt) { - uint32_t frm_size, nalu_type, data_length; - unsigned char *start; - - for (i = code_size - 1; buf_pos + i < whole_len; i++) { - if (vtool_data->dec_buf[buf_pos + i] == 0 && - vtool_data->dec_buf[buf_pos + i + 1] == 0 && - vtool_data->dec_buf[buf_pos + i + 2] == 0 && - vtool_data->dec_buf[buf_pos + i + 3] == 1) - { - break; - } - } - - frm_size = i; - start = vtool_data->dec_buf + buf_pos; - nalu_type = (start[code_size] & 0x1F); - + uint32_t frm_size, nalu_type, data_length; + unsigned char *start; + + for (i = code_size - 1; buf_pos + i < whole_len; i++) { + if (vtool_data->dec_buf[buf_pos + i] == 0 && + vtool_data->dec_buf[buf_pos + i + 1] == 0 && + vtool_data->dec_buf[buf_pos + i + 2] == 0 && + vtool_data->dec_buf[buf_pos + i + 3] == 1) + { + break; + } + } + + frm_size = i; + start = vtool_data->dec_buf + buf_pos; + nalu_type = (start[code_size] & 0x1F); + #if TARGET_OS_IPHONE - /* On iOS, packets preceded by SEI frame (type 6), such as the ones - * sent by Mac VideoToolbox encoder will cause DecodeFrame to fail - * with -12911 (kVTVideoDecoderMalfunctionErr). The workaround - * is to decode the whole packets at once. - */ - if (nalu_type == 6) - decode_whole = PJ_TRUE; + /* On iOS, packets preceded by SEI frame (type 6), such as the ones + * sent by Mac VideoToolbox encoder will cause DecodeFrame to fail + * with -12911 (kVTVideoDecoderMalfunctionErr). The workaround + * is to decode the whole packets at once. + */ + if (nalu_type == 6) + decode_whole = PJ_TRUE; #endif - /* AVCC format requires us to replace the start code header - * on this NAL with its frame size. + /* AVCC format requires us to replace the start code header + * on this NAL with its frame size. */ data_length = pj_htonl(frm_size - code_size); pj_memcpy(start, &data_length, sizeof (data_length)); - if (nalu_type == 7) { - /* NALU type 7 is the SPS parameter NALU */ - vtool_data->dec_sps_size = PJ_MIN(frm_size - code_size, - sizeof(vtool_data->dec_sps)); - pj_memcpy(vtool_data->dec_sps, &start[code_size], - vtool_data->dec_sps_size); - } else if (nalu_type == 8) { - /* NALU type 8 is the PPS parameter NALU */ - vtool_data->dec_pps_size = PJ_MIN(frm_size - code_size, - sizeof(vtool_data->dec_pps)); - pj_memcpy(vtool_data->dec_pps, &start[code_size], - vtool_data->dec_pps_size); - - ret = create_decoder(vtool_data); - } else if (vtool_data->dec && - (!decode_whole || (buf_pos + frm_size >= whole_len))) - { - CMBlockBufferRef block_buf = NULL; - CMSampleBufferRef sample_buf = NULL; - - if (decode_whole) { - /* We decode all the packets at once. */ - frm_size = whole_len; - start = vtool_data->dec_buf; - } + if (nalu_type == 7) { + /* NALU type 7 is the SPS parameter NALU */ + vtool_data->dec_sps_size = PJ_MIN(frm_size - code_size, + sizeof(vtool_data->dec_sps)); + pj_memcpy(vtool_data->dec_sps, &start[code_size], + vtool_data->dec_sps_size); + } else if (nalu_type == 8) { + /* NALU type 8 is the PPS parameter NALU */ + vtool_data->dec_pps_size = PJ_MIN(frm_size - code_size, + sizeof(vtool_data->dec_pps)); + pj_memcpy(vtool_data->dec_pps, &start[code_size], + vtool_data->dec_pps_size); + + ret = create_decoder(vtool_data); + } else if (vtool_data->dec && + (!decode_whole || (buf_pos + frm_size >= whole_len))) + { + CMBlockBufferRef block_buf = NULL; + CMSampleBufferRef sample_buf = NULL; + + if (decode_whole) { + /* We decode all the packets at once. */ + frm_size = whole_len; + start = vtool_data->dec_buf; + } /* Create a block buffer from the NALU */ ret = CMBlockBufferCreateWithMemoryBlock(NULL, - start, frm_size, + start, frm_size, kCFAllocatorNull, NULL, 0, frm_size, 0, &block_buf); - if (ret == noErr) { - const size_t sample_size = frm_size; - ret = CMSampleBufferCreate(kCFAllocatorDefault, - block_buf, true, NULL, NULL, - vtool_data->dec_format, - 1, 0, NULL, 1, - &sample_size, &sample_buf); + if (ret == noErr) { + const size_t sample_size = frm_size; + ret = CMSampleBufferCreate(kCFAllocatorDefault, + block_buf, true, NULL, NULL, + vtool_data->dec_format, + 1, 0, NULL, 1, + &sample_size, &sample_buf); if (ret != noErr) { PJ_LOG(4,(THIS_FILE, "Failed to create sample buffer")); CFRelease(block_buf); - } - } else { - PJ_LOG(4,(THIS_FILE, "Failed to create block buffer")); - } - - if (ret == noErr) { - vtool_data->dec_frame = output; - ret = VTDecompressionSessionDecodeFrame( - vtool_data->dec, sample_buf, 0, - NULL, NULL); - if (ret == kVTInvalidSessionErr) { + } + } else { + PJ_LOG(4,(THIS_FILE, "Failed to create block buffer")); + } + + if (ret == noErr) { + vtool_data->dec_frame = output; + ret = VTDecompressionSessionDecodeFrame( + vtool_data->dec, sample_buf, 0, + NULL, NULL); + if (ret == kVTInvalidSessionErr) { #if TARGET_OS_IPHONE - /* Just return if app is not active, i.e. in the bg. */ - __block UIApplicationState state; - - dispatch_sync_on_main_queue(^{ - state = [UIApplication sharedApplication].applicationState; - }); - if (state != UIApplicationStateActive) { - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->size = 0; - output->timestamp = packets[0].timestamp; - - CFRelease(block_buf); - CFRelease(sample_buf); - return PJ_SUCCESS; - } + /* Just return if app is not active, i.e. in the bg. */ + __block UIApplicationState state; + + dispatch_sync_on_main_queue(^{ + state = [UIApplication sharedApplication].applicationState; + }); + if (state != UIApplicationStateActive) { + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->size = 0; + output->timestamp = packets[0].timestamp; + + CFRelease(block_buf); + CFRelease(sample_buf); + return PJ_SUCCESS; + } #endif - if (vtool_data->dec_format) - CFRelease(vtool_data->dec_format); - vtool_data->dec_format = NULL; - ret = create_decoder(vtool_data); - PJ_LOG(3,(THIS_FILE, "Decoder needs to be reset: %s (%d)", - (ret == noErr? "success": "fail"), ret)); - - if (ret == noErr) { - /* Retry decoding the frame after successful reset */ - ret = VTDecompressionSessionDecodeFrame( - vtool_data->dec, sample_buf, 0, - NULL, NULL); - } - } - - if ((ret != noErr) || (vtool_data->dec_status != noErr)) { + if (vtool_data->dec_format) + CFRelease(vtool_data->dec_format); + vtool_data->dec_format = NULL; + ret = create_decoder(vtool_data); + PJ_LOG(3,(THIS_FILE, "Decoder needs to be reset: %s (%d)", + (ret == noErr? "success": "fail"), ret)); + + if (ret == noErr) { + /* Retry decoding the frame after successful reset */ + ret = VTDecompressionSessionDecodeFrame( + vtool_data->dec, sample_buf, 0, + NULL, NULL); + } + } + + if ((ret != noErr) || (vtool_data->dec_status != noErr)) { char *ret_err = (ret != noErr)?"decode err":"cb err"; OSStatus err_code = (ret != noErr)?ret:vtool_data->dec_status; - PJ_LOG(5,(THIS_FILE, "Failed to decode frame %d of size " + PJ_LOG(5,(THIS_FILE, "Failed to decode frame %d of size " "%d %s:%d", nalu_type, frm_size, ret_err, err_code)); - } else { - has_frame = PJ_TRUE; - output->type = PJMEDIA_FRAME_TYPE_VIDEO; - output->timestamp = packets[0].timestamp; - - /* Broadcast format changed event */ - if (vtool_data->dec_fmt_change) { - pjmedia_event event; - - PJ_LOG(4,(THIS_FILE, "Frame size changed to %dx%d", - vtool_data->prm->dec_fmt.det.vid.size.w, - vtool_data->prm->dec_fmt.det.vid.size.h)); - - /* Broadcast format changed event */ - pjmedia_event_init(&event, PJMEDIA_EVENT_FMT_CHANGED, - &output->timestamp, codec); - event.data.fmt_changed.dir = PJMEDIA_DIR_DECODING; - pjmedia_format_copy(&event.data.fmt_changed.new_fmt, - &vtool_data->prm->dec_fmt); - pjmedia_event_publish(NULL, codec, &event, - PJMEDIA_EVENT_PUBLISH_DEFAULT); - } - } - - CFRelease(block_buf); - CFRelease(sample_buf); - } - } - - if (buf_pos + frm_size >= whole_len) - break; - - buf_pos += frm_size; + } else { + has_frame = PJ_TRUE; + output->type = PJMEDIA_FRAME_TYPE_VIDEO; + output->timestamp = packets[0].timestamp; + + /* Broadcast format changed event */ + if (vtool_data->dec_fmt_change) { + pjmedia_event event; + + PJ_LOG(4,(THIS_FILE, "Frame size changed to %dx%d", + vtool_data->prm->dec_fmt.det.vid.size.w, + vtool_data->prm->dec_fmt.det.vid.size.h)); + + /* Broadcast format changed event */ + pjmedia_event_init(&event, PJMEDIA_EVENT_FMT_CHANGED, + &output->timestamp, codec); + event.data.fmt_changed.dir = PJMEDIA_DIR_DECODING; + pjmedia_format_copy(&event.data.fmt_changed.new_fmt, + &vtool_data->prm->dec_fmt); + pjmedia_event_publish(NULL, codec, &event, + PJMEDIA_EVENT_PUBLISH_DEFAULT); + } + } + + CFRelease(block_buf); + CFRelease(sample_buf); + } + } + + if (buf_pos + frm_size >= whole_len) + break; + + buf_pos += frm_size; } on_return: if (!has_frame) { - pjmedia_event event; + pjmedia_event event; - /* Broadcast missing keyframe event */ - pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, - &packets[0].timestamp, codec); - pjmedia_event_publish(NULL, codec, &event, - PJMEDIA_EVENT_PUBLISH_DEFAULT); + /* Broadcast missing keyframe event */ + pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, + &packets[0].timestamp, codec); + pjmedia_event_publish(NULL, codec, &event, + PJMEDIA_EVENT_PUBLISH_DEFAULT); - PJ_LOG(5,(THIS_FILE, "Decode couldn't produce picture, " - "input nframes=%d, concatenated size=%d bytes", - count, whole_len)); + PJ_LOG(5,(THIS_FILE, "Decode couldn't produce picture, " + "input nframes=%d, concatenated size=%d bytes", + count, whole_len)); - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->size = 0; - output->timestamp = packets[0].timestamp; + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->size = 0; + output->timestamp = packets[0].timestamp; } return PJ_SUCCESS; } -#endif /* PJMEDIA_HAS_VID_TOOLBOX_CODEC */ +#endif /* PJMEDIA_HAS_VID_TOOLBOX_CODEC */ diff --git a/pjmedia/src/pjmedia-codec/vpx.c b/pjmedia/src/pjmedia-codec/vpx.c index 4e3d3fd0bb..c4b934982d 100644 --- a/pjmedia/src/pjmedia-codec/vpx.c +++ b/pjmedia/src/pjmedia-codec/vpx.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C)2019 Teluu Inc. (http://www.teluu.com) * @@ -41,27 +40,27 @@ /* * Constants */ -#define THIS_FILE "vpx.c" +#define THIS_FILE "vpx.c" #if (defined(PJ_DARWINOS) && PJ_DARWINOS != 0 && TARGET_OS_IPHONE) || \ defined(__ANDROID__) -# define DEFAULT_WIDTH 352 -# define DEFAULT_HEIGHT 288 +# define DEFAULT_WIDTH 352 +# define DEFAULT_HEIGHT 288 #else -# define DEFAULT_WIDTH 720 -# define DEFAULT_HEIGHT 480 +# define DEFAULT_WIDTH 720 +# define DEFAULT_HEIGHT 480 #endif -#define DEFAULT_FPS 15 -#define DEFAULT_AVG_BITRATE 200000 -#define DEFAULT_MAX_BITRATE 200000 +#define DEFAULT_FPS 15 +#define DEFAULT_AVG_BITRATE 200000 +#define DEFAULT_MAX_BITRATE 200000 -#define MAX_RX_RES 1200 +#define MAX_RX_RES 1200 /* VPX VP8 default PT */ -#define VPX_VP8_PT PJMEDIA_RTP_PT_VP8 +#define VPX_VP8_PT PJMEDIA_RTP_PT_VP8 /* VPX VP9 default PT */ -#define VPX_VP9_PT PJMEDIA_RTP_PT_VP9 +#define VPX_VP9_PT PJMEDIA_RTP_PT_VP9 /* * Factory operations. @@ -137,35 +136,35 @@ static pjmedia_vid_codec_factory_op vpx_factory_op = static struct vpx_factory { pjmedia_vid_codec_factory base; - pjmedia_vid_codec_mgr *mgr; + pjmedia_vid_codec_mgr *mgr; pj_pool_factory *pf; - pj_pool_t *pool; + pj_pool_t *pool; } vpx_factory; typedef struct vpx_codec_data { - pj_pool_t *pool; - pjmedia_vid_codec_param *prm; - pj_bool_t whole; - pjmedia_vpx_packetizer *pktz; + pj_pool_t *pool; + pjmedia_vid_codec_param *prm; + pj_bool_t whole; + pjmedia_vpx_packetizer *pktz; /* Encoder */ - vpx_codec_iface_t *(*enc_if)(); - vpx_codec_ctx_t enc; - vpx_codec_iter_t enc_iter; - unsigned enc_input_size; - pj_uint8_t *enc_frame_whole; - unsigned enc_frame_size; - unsigned enc_processed; - pj_bool_t enc_frame_is_keyframe; - pj_timestamp ets; + vpx_codec_iface_t *(*enc_if)(); + vpx_codec_ctx_t enc; + vpx_codec_iter_t enc_iter; + unsigned enc_input_size; + pj_uint8_t *enc_frame_whole; + unsigned enc_frame_size; + unsigned enc_processed; + pj_bool_t enc_frame_is_keyframe; + pj_timestamp ets; /* Decoder */ - vpx_codec_iface_t *(*dec_if)(); - vpx_codec_ctx_t dec; - pj_uint8_t *dec_buf; - unsigned dec_buf_size; + vpx_codec_iface_t *(*dec_if)(); + vpx_codec_ctx_t dec; + pj_uint8_t *dec_buf; + unsigned dec_buf_size; } vpx_codec_data; @@ -175,8 +174,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_vpx_vid_init(pjmedia_vid_codec_mgr *mgr, pj_status_t status; if (vpx_factory.pool != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } if (!mgr) mgr = pjmedia_vid_codec_mgr_instance(); @@ -189,13 +188,13 @@ PJ_DEF(pj_status_t) pjmedia_codec_vpx_vid_init(pjmedia_vid_codec_mgr *mgr, vpx_factory.pf = pf; vpx_factory.pool = pj_pool_create(pf, "vpxfactory", 256, 256, NULL); if (!vpx_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Register codec factory to codec manager. */ status = pjmedia_vid_codec_mgr_register_factory(mgr, - &vpx_factory.base); + &vpx_factory.base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; PJ_LOG(4,(THIS_FILE, "VPX codec initialized")); @@ -216,13 +215,13 @@ PJ_DEF(pj_status_t) pjmedia_codec_vpx_vid_deinit(void) pj_status_t status = PJ_SUCCESS; if (vpx_factory.pool == NULL) { - /* Already deinitialized */ - return PJ_SUCCESS; + /* Already deinitialized */ + return PJ_SUCCESS; } /* Unregister VPX codecs factory. */ status = pjmedia_vid_codec_mgr_unregister_factory(vpx_factory.mgr, - &vpx_factory.base); + &vpx_factory.base); /* Destroy pool. */ pj_pool_release(vpx_factory.pool); @@ -239,7 +238,7 @@ static pj_status_t vpx_test_alloc(pjmedia_vid_codec_factory *factory, if (((info->fmt_id == PJMEDIA_FORMAT_VP8) && (info->pt == VPX_VP8_PT)) || ((info->fmt_id == PJMEDIA_FORMAT_VP9) && (info->pt == VPX_VP9_PT))) { - return PJ_SUCCESS; + return PJ_SUCCESS; } return PJMEDIA_CODEC_EUNSUP; @@ -260,12 +259,12 @@ static pj_status_t vpx_default_attr(pjmedia_vid_codec_factory *factory, /* Encoded format */ pjmedia_format_init_video(&attr->enc_fmt, info->fmt_id, DEFAULT_WIDTH, DEFAULT_HEIGHT, - DEFAULT_FPS, 1); + DEFAULT_FPS, 1); /* Decoded format */ pjmedia_format_init_video(&attr->dec_fmt, PJMEDIA_FORMAT_I420, DEFAULT_WIDTH, DEFAULT_HEIGHT, - DEFAULT_FPS, 1); + DEFAULT_FPS, 1); /* Decoding fmtp */ /* If the implementation is willing to receive media, both parameters @@ -306,28 +305,28 @@ static pj_status_t vpx_enum_info(pjmedia_vid_codec_factory *factory, #if PJMEDIA_HAS_VPX_CODEC_VP9 if (i + 1 < *count) { - info[i].fmt_id = PJMEDIA_FORMAT_VP9; + info[i].fmt_id = PJMEDIA_FORMAT_VP9; info[i].pt = VPX_VP9_PT; - info[i].encoding_name = pj_str((char*)"VP9"); - info[i].encoding_desc = pj_str((char*)"VPX VP9 codec"); - i++; + info[i].encoding_name = pj_str((char*)"VP9"); + info[i].encoding_desc = pj_str((char*)"VPX VP9 codec"); + i++; } #endif *count = i; for (i = 0; i < *count; i++) { - info[i].clock_rate = 90000; - info[i].dir = PJMEDIA_DIR_ENCODING_DECODING; - info[i].dec_fmt_id_cnt = 1; - info[i].dec_fmt_id[0] = PJMEDIA_FORMAT_I420; - info[i].packings = PJMEDIA_VID_PACKING_PACKETS; - info[i].fps_cnt = 3; - info[i].fps[0].num = 15; - info[i].fps[0].denum = 1; - info[i].fps[1].num = 25; - info[i].fps[1].denum = 1; - info[i].fps[2].num = 30; - info[i].fps[2].denum = 1; + info[i].clock_rate = 90000; + info[i].dir = PJMEDIA_DIR_ENCODING_DECODING; + info[i].dec_fmt_id_cnt = 1; + info[i].dec_fmt_id[0] = PJMEDIA_FORMAT_I420; + info[i].packings = PJMEDIA_VID_PACKING_PACKETS; + info[i].fps_cnt = 3; + info[i].fps[0].num = 15; + info[i].fps[0].denum = 1; + info[i].fps[1].num = 25; + info[i].fps[1].denum = 1; + info[i].fps[2].num = 30; + info[i].fps[2].denum = 1; } return PJ_SUCCESS; @@ -349,7 +348,7 @@ static pj_status_t vpx_alloc_codec(pjmedia_vid_codec_factory *factory, pool = pj_pool_create(vpx_factory.pf, "vpx%p", 512, 512, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* codec instance */ codec = PJ_POOL_ZALLOC_T(pool, pjmedia_vid_codec); @@ -363,11 +362,11 @@ static pj_status_t vpx_alloc_codec(pjmedia_vid_codec_factory *factory, /* encoder and decoder interfaces */ if (info->fmt_id == PJMEDIA_FORMAT_VP8) { - vpx_data->enc_if = &vpx_codec_vp8_cx; - vpx_data->dec_if = &vpx_codec_vp8_dx; + vpx_data->enc_if = &vpx_codec_vp8_cx; + vpx_data->dec_if = &vpx_codec_vp8_dx; } else if (info->fmt_id == PJMEDIA_FORMAT_VP9) { - vpx_data->enc_if = &vpx_codec_vp9_cx; - vpx_data->dec_if = &vpx_codec_vp9_dx; + vpx_data->enc_if = &vpx_codec_vp9_cx; + vpx_data->dec_if = &vpx_codec_vp9_dx; } *p_codec = codec; @@ -403,14 +402,14 @@ static pj_status_t vpx_codec_init(pjmedia_vid_codec *codec, static pj_status_t vpx_codec_open(pjmedia_vid_codec *codec, pjmedia_vid_codec_param *codec_param ) { - vpx_codec_data *vpx_data; - pjmedia_vid_codec_param *param; + vpx_codec_data *vpx_data; + pjmedia_vid_codec_param *param; pjmedia_vid_codec_vpx_fmtp vpx_fmtp; vpx_codec_enc_cfg_t cfg; vpx_codec_err_t res; pjmedia_vpx_packetizer_cfg pktz_cfg; unsigned max_res = MAX_RX_RES; - pj_status_t status; + pj_status_t status; PJ_ASSERT_RETURN(codec && codec_param, PJ_EINVAL); @@ -424,9 +423,9 @@ static pj_status_t vpx_codec_open(pjmedia_vid_codec *codec, /* Apply SDP fmtp to format in codec param */ if (!param->ignore_fmtp) { - status = pjmedia_vid_codec_vpx_apply_fmtp(param); - if (status != PJ_SUCCESS) - return status; + status = pjmedia_vid_codec_vpx_apply_fmtp(param); + if (status != PJ_SUCCESS) + return status; } /* @@ -436,8 +435,8 @@ static pj_status_t vpx_codec_open(pjmedia_vid_codec *codec, /* Init encoder parameters */ res = vpx_codec_enc_config_default(vpx_data->enc_if(), &cfg, 0); if (res) { - PJ_LOG(3, (THIS_FILE, "Failed to get encoder default config")); - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(3, (THIS_FILE, "Failed to get encoder default config")); + return PJMEDIA_CODEC_EFAILED; } cfg.g_w = vpx_data->prm->enc_fmt.det.vid.size.w; @@ -461,7 +460,7 @@ static pj_status_t vpx_codec_open(pjmedia_vid_codec *codec, cfg.rc_buf_sz = 600; /* kf max distance is 60s. */ cfg.kf_max_dist = 60 * vpx_data->prm->enc_fmt.det.vid.fps.num/ - vpx_data->prm->enc_fmt.det.vid.fps.denum; + vpx_data->prm->enc_fmt.det.vid.fps.denum; cfg.rc_resize_allowed = 0; cfg.rc_dropframe_thresh = 25; @@ -470,8 +469,8 @@ static pj_status_t vpx_codec_open(pjmedia_vid_codec *codec, /* Initialize encoder */ res = vpx_codec_enc_init(&vpx_data->enc, vpx_data->enc_if(), &cfg, 0); if (res) { - PJ_LOG(3, (THIS_FILE, "Failed to initialize encoder")); - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(3, (THIS_FILE, "Failed to initialize encoder")); + return PJMEDIA_CODEC_EFAILED; } /* Values greater than 0 will increase encoder speed at the expense of @@ -486,17 +485,17 @@ static pj_status_t vpx_codec_open(pjmedia_vid_codec *codec, */ res = vpx_codec_dec_init(&vpx_data->dec, vpx_data->dec_if(), NULL, 0); if (res) { - PJ_LOG(3, (THIS_FILE, "Failed to initialize decoder")); - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(3, (THIS_FILE, "Failed to initialize decoder")); + return PJMEDIA_CODEC_EFAILED; } /* Parse local fmtp */ status = pjmedia_vid_codec_vpx_parse_fmtp(¶m->dec_fmtp, &vpx_fmtp); if (status != PJ_SUCCESS) - return status; + return status; if (vpx_fmtp.max_fs > 0) { - max_res = ((int)pj_isqrt(vpx_fmtp.max_fs * 8)) * 16; + max_res = ((int)pj_isqrt(vpx_fmtp.max_fs * 8)) * 16; } vpx_data->dec_buf_size = (max_res * max_res * 3 >> 1) + (max_res); vpx_data->dec_buf = (pj_uint8_t*)pj_pool_alloc(vpx_data->pool, @@ -573,12 +572,12 @@ static pj_status_t vpx_codec_encode_begin(pjmedia_vid_codec *codec, PJMEDIA_CODEC_EFRMINLEN); vpx_img_wrap(&img, VPX_IMG_FMT_I420, - vpx_data->prm->enc_fmt.det.vid.size.w, - vpx_data->prm->enc_fmt.det.vid.size.h, - 1, (unsigned char *)input->buf); + vpx_data->prm->enc_fmt.det.vid.size.w, + vpx_data->prm->enc_fmt.det.vid.size.h, + 1, (unsigned char *)input->buf); if (opt && opt->force_keyframe) { - flags |= VPX_EFLAG_FORCE_KF; + flags |= VPX_EFLAG_FORCE_KF; } vpx_data->ets = input->timestamp; @@ -586,49 +585,49 @@ static pj_status_t vpx_codec_encode_begin(pjmedia_vid_codec *codec, vpx_data->enc_iter = NULL; res = vpx_codec_encode(&vpx_data->enc, &img, vpx_data->ets.u64, 1, - flags, VPX_DL_REALTIME); + flags, VPX_DL_REALTIME); if (res) { - PJ_LOG(4, (THIS_FILE, "Failed to encode frame %s", - vpx_codec_error(&vpx_data->enc))); - return PJMEDIA_CODEC_EFAILED; + PJ_LOG(4, (THIS_FILE, "Failed to encode frame %s", + vpx_codec_error(&vpx_data->enc))); + return PJMEDIA_CODEC_EFAILED; } do { - const vpx_codec_cx_pkt_t *pkt; + const vpx_codec_cx_pkt_t *pkt; - pkt = vpx_codec_get_cx_data(&vpx_data->enc, &vpx_data->enc_iter); - if (!pkt) break; - if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { - /* We have a valid frame packet */ - vpx_data->enc_frame_whole = pkt->data.frame.buf; + pkt = vpx_codec_get_cx_data(&vpx_data->enc, &vpx_data->enc_iter); + if (!pkt) break; + if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { + /* We have a valid frame packet */ + vpx_data->enc_frame_whole = pkt->data.frame.buf; vpx_data->enc_frame_size = pkt->data.frame.sz; vpx_data->enc_processed = 0; if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) - vpx_data->enc_frame_is_keyframe = PJ_TRUE; + vpx_data->enc_frame_is_keyframe = PJ_TRUE; else - vpx_data->enc_frame_is_keyframe = PJ_FALSE; - + vpx_data->enc_frame_is_keyframe = PJ_FALSE; + break; - } + } } while (1); if (vpx_data->enc_frame_size == 0) { - *has_more = PJ_FALSE; - output->size = 0; - output->type = PJMEDIA_FRAME_TYPE_NONE; - - if (vpx_data->enc.err) { - PJ_LOG(4, (THIS_FILE, "Failed to get encoded frame %s", - vpx_codec_error(&vpx_data->enc))); - } else { - return PJ_SUCCESS; - } + *has_more = PJ_FALSE; + output->size = 0; + output->type = PJMEDIA_FRAME_TYPE_NONE; + + if (vpx_data->enc.err) { + PJ_LOG(4, (THIS_FILE, "Failed to get encoded frame %s", + vpx_codec_error(&vpx_data->enc))); + } else { + return PJ_SUCCESS; + } } if (vpx_data->whole) { - *has_more = PJ_FALSE; - if (vpx_data->enc_frame_size > out_size) - return PJMEDIA_CODEC_EFRMTOOSHORT; + *has_more = PJ_FALSE; + if (vpx_data->enc_frame_size > out_size) + return PJMEDIA_CODEC_EFRMTOOSHORT; output->timestamp = vpx_data->ets; output->type = PJMEDIA_FRAME_TYPE_VIDEO; @@ -661,23 +660,23 @@ static pj_status_t vpx_codec_encode_more(pjmedia_vid_codec *codec, vpx_data = (vpx_codec_data*) codec->codec_data; if (vpx_data->enc_processed < vpx_data->enc_frame_size) { - unsigned payload_desc_size = 1; - pj_size_t payload_len = out_size; - pj_uint8_t *p = (pj_uint8_t *)output->buf; - - status = pjmedia_vpx_packetize(vpx_data->pktz, - vpx_data->enc_frame_size, - &vpx_data->enc_processed, - vpx_data->enc_frame_is_keyframe, - &p, - &payload_len); - - if (status != PJ_SUCCESS) { - return status; - } + unsigned payload_desc_size = 1; + pj_size_t payload_len = out_size; + pj_uint8_t *p = (pj_uint8_t *)output->buf; + + status = pjmedia_vpx_packetize(vpx_data->pktz, + vpx_data->enc_frame_size, + &vpx_data->enc_processed, + vpx_data->enc_frame_is_keyframe, + &p, + &payload_len); + + if (status != PJ_SUCCESS) { + return status; + } pj_memcpy(p + payload_desc_size, - (vpx_data->enc_frame_whole + vpx_data->enc_processed), - payload_len); + (vpx_data->enc_frame_whole + vpx_data->enc_processed), + payload_len); output->size = payload_len + payload_desc_size; output->timestamp = vpx_data->ets; output->type = PJMEDIA_FRAME_TYPE_VIDEO; @@ -718,127 +717,127 @@ static pj_status_t vpx_codec_decode_(pjmedia_vid_codec *codec, */ whole_len = 0; if (vpx_data->whole) { - for (i = 0; i < count; ++i) { - if (whole_len + packets[i].size > vpx_data->dec_buf_size) { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]")); - return PJMEDIA_CODEC_EFRMTOOSHORT; - } - - pj_memcpy( vpx_data->dec_buf + whole_len, - (pj_uint8_t*)packets[i].buf, - packets[i].size); - whole_len += packets[i].size; - } + for (i = 0; i < count; ++i) { + if (whole_len + packets[i].size > vpx_data->dec_buf_size) { + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]")); + return PJMEDIA_CODEC_EFRMTOOSHORT; + } + + pj_memcpy( vpx_data->dec_buf + whole_len, + (pj_uint8_t*)packets[i].buf, + packets[i].size); + whole_len += packets[i].size; + } } else { - for (i = 0; i < count; ++i) { - unsigned desc_len; - unsigned packet_size = packets[i].size; - pj_status_t status; + for (i = 0; i < count; ++i) { + unsigned desc_len; + unsigned packet_size = packets[i].size; + pj_status_t status; status = pjmedia_vpx_unpacketize(vpx_data->pktz, packets[i].buf, packet_size, &desc_len); - if (status != PJ_SUCCESS) { - PJ_LOG(4,(THIS_FILE, "Unpacketize error")); - return status; - } - - packet_size -= desc_len; - if (whole_len + packet_size > vpx_data->dec_buf_size) { - PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [2]")); - return PJMEDIA_CODEC_EFRMTOOSHORT; + if (status != PJ_SUCCESS) { + PJ_LOG(4,(THIS_FILE, "Unpacketize error")); + return status; + } + + packet_size -= desc_len; + if (whole_len + packet_size > vpx_data->dec_buf_size) { + PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [2]")); + return PJMEDIA_CODEC_EFRMTOOSHORT; } - pj_memcpy(vpx_data->dec_buf + whole_len, - (char *)packets[i].buf + desc_len, packet_size); - whole_len += packet_size; - } + pj_memcpy(vpx_data->dec_buf + whole_len, + (char *)packets[i].buf + desc_len, packet_size); + whole_len += packet_size; + } } /* Decode */ res = vpx_codec_decode(&vpx_data->dec, vpx_data->dec_buf, whole_len, - 0, VPX_DL_REALTIME); + 0, VPX_DL_REALTIME); if (res) { - PJ_LOG(4, (THIS_FILE, "Failed to decode frame %s", - vpx_codec_error(&vpx_data->dec))); - goto on_return; + PJ_LOG(4, (THIS_FILE, "Failed to decode frame %s", + vpx_codec_error(&vpx_data->dec))); + goto on_return; } img = vpx_codec_get_frame(&vpx_data->dec, &iter); if (!img) { - PJ_LOG(4, (THIS_FILE, "Failed to get decoded frame %s", - vpx_codec_error(&vpx_data->dec))); - goto on_return; + PJ_LOG(4, (THIS_FILE, "Failed to get decoded frame %s", + vpx_codec_error(&vpx_data->dec))); + goto on_return; } has_frame = PJ_TRUE; /* Detect format change */ if (img->d_w != vpx_data->prm->dec_fmt.det.vid.size.w || - img->d_h != vpx_data->prm->dec_fmt.det.vid.size.h) + img->d_h != vpx_data->prm->dec_fmt.det.vid.size.h) { - pjmedia_event event; - - PJ_LOG(4,(THIS_FILE, "Frame size changed: %dx%d --> %dx%d", - vpx_data->prm->dec_fmt.det.vid.size.w, - vpx_data->prm->dec_fmt.det.vid.size.h, - img->d_w, img->d_h)); - - vpx_data->prm->dec_fmt.det.vid.size.w = img->d_w; - vpx_data->prm->dec_fmt.det.vid.size.h = img->d_h; - - /* Broadcast format changed event */ - pjmedia_event_init(&event, PJMEDIA_EVENT_FMT_CHANGED, - &packets[0].timestamp, codec); - event.data.fmt_changed.dir = PJMEDIA_DIR_DECODING; - pjmedia_format_copy(&event.data.fmt_changed.new_fmt, - &vpx_data->prm->dec_fmt); - pjmedia_event_publish(NULL, codec, &event, - PJMEDIA_EVENT_PUBLISH_DEFAULT); + pjmedia_event event; + + PJ_LOG(4,(THIS_FILE, "Frame size changed: %dx%d --> %dx%d", + vpx_data->prm->dec_fmt.det.vid.size.w, + vpx_data->prm->dec_fmt.det.vid.size.h, + img->d_w, img->d_h)); + + vpx_data->prm->dec_fmt.det.vid.size.w = img->d_w; + vpx_data->prm->dec_fmt.det.vid.size.h = img->d_h; + + /* Broadcast format changed event */ + pjmedia_event_init(&event, PJMEDIA_EVENT_FMT_CHANGED, + &packets[0].timestamp, codec); + event.data.fmt_changed.dir = PJMEDIA_DIR_DECODING; + pjmedia_format_copy(&event.data.fmt_changed.new_fmt, + &vpx_data->prm->dec_fmt); + pjmedia_event_publish(NULL, codec, &event, + PJMEDIA_EVENT_PUBLISH_DEFAULT); } if (img->d_w * img->d_h * 3/2 > output->size) - return PJMEDIA_CODEC_EFRMTOOSHORT; + return PJMEDIA_CODEC_EFRMTOOSHORT; output->type = PJMEDIA_FRAME_TYPE_VIDEO; output->timestamp = packets[0].timestamp; for (plane = 0; plane < 3; ++plane) { const unsigned char *buf = img->planes[plane]; - const int stride = img->stride[plane]; - const int w = (plane? img->d_w / 2: img->d_w); - const int h = (plane? img->d_h / 2: img->d_h); - int y; - - for (y = 0; y < h; ++y) { - pj_memcpy((char *)output->buf + pos, buf, w); - pos += w; - buf += stride; - } + const int stride = img->stride[plane]; + const int w = (plane? img->d_w / 2: img->d_w); + const int h = (plane? img->d_h / 2: img->d_h); + int y; + + for (y = 0; y < h; ++y) { + pj_memcpy((char *)output->buf + pos, buf, w); + pos += w; + buf += stride; + } } output->size = pos; - + on_return: if (!has_frame) { - pjmedia_event event; + pjmedia_event event; - /* Broadcast missing keyframe event */ - pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, - &packets[0].timestamp, codec); - pjmedia_event_publish(NULL, codec, &event, - PJMEDIA_EVENT_PUBLISH_DEFAULT); + /* Broadcast missing keyframe event */ + pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, + &packets[0].timestamp, codec); + pjmedia_event_publish(NULL, codec, &event, + PJMEDIA_EVENT_PUBLISH_DEFAULT); - PJ_LOG(4,(THIS_FILE, "Decode couldn't produce picture, " - "input nframes=%d, concatenated size=%d bytes", - count, whole_len)); + PJ_LOG(4,(THIS_FILE, "Decode couldn't produce picture, " + "input nframes=%d, concatenated size=%d bytes", + count, whole_len)); - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->size = 0; - output->timestamp = packets[0].timestamp; + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->size = 0; + output->timestamp = packets[0].timestamp; } return PJ_SUCCESS; } -#endif /* PJMEDIA_HAS_VPX_CODEC */ +#endif /* PJMEDIA_HAS_VPX_CODEC */ diff --git a/pjmedia/src/pjmedia-codec/vpx_packetizer.c b/pjmedia/src/pjmedia-codec/vpx_packetizer.c index a1adbc778c..d743996a56 100644 --- a/pjmedia/src/pjmedia-codec/vpx_packetizer.c +++ b/pjmedia/src/pjmedia-codec/vpx_packetizer.c @@ -28,7 +28,7 @@ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -#define THIS_FILE "vpx_packetizer.c" +#define THIS_FILE "vpx_packetizer.c" /* VPX packetizer definition */ struct pjmedia_vpx_packetizer @@ -52,25 +52,25 @@ PJ_DEF(void) pjmedia_vpx_packetizer_cfg_default(pjmedia_vpx_packetizer_cfg *cfg) * Create vpx packetizer. */ PJ_DEF(pj_status_t) pjmedia_vpx_packetizer_create( - pj_pool_t *pool, - const pjmedia_vpx_packetizer_cfg *cfg, - pjmedia_vpx_packetizer **p) + pj_pool_t *pool, + const pjmedia_vpx_packetizer_cfg *cfg, + pjmedia_vpx_packetizer **p) { pjmedia_vpx_packetizer *p_; PJ_ASSERT_RETURN(pool && p, PJ_EINVAL); if (cfg && cfg->fmt_id != PJMEDIA_FORMAT_VP8 && - cfg->fmt_id != PJMEDIA_FORMAT_VP9) + cfg->fmt_id != PJMEDIA_FORMAT_VP9) { - return PJ_ENOTSUP; + return PJ_ENOTSUP; } p_ = PJ_POOL_ZALLOC_T(pool, pjmedia_vpx_packetizer); if (cfg) { - pj_memcpy(&p_->cfg, cfg, sizeof(*cfg)); + pj_memcpy(&p_->cfg, cfg, sizeof(*cfg)); } else { - pjmedia_vpx_packetizer_cfg_default(&p_->cfg); + pjmedia_vpx_packetizer_cfg_default(&p_->cfg); } *p = p_; @@ -81,7 +81,7 @@ PJ_DEF(pj_status_t) pjmedia_vpx_packetizer_create( * Generate an RTP payload from H.264 frame bitstream, in-place processing. */ PJ_DEF(pj_status_t) pjmedia_vpx_packetize(const pjmedia_vpx_packetizer *pktz, - pj_size_t bits_len, + pj_size_t bits_len, unsigned *bits_pos, pj_bool_t is_keyframe, pj_uint8_t **payload, @@ -95,24 +95,24 @@ PJ_DEF(pj_status_t) pjmedia_vpx_packetize(const pjmedia_vpx_packetizer *pktz, *payload_len = PJ_MIN(remaining_size, max_size); if (*payload_len + payload_desc_size > out_size) - return PJMEDIA_CODEC_EFRMTOOSHORT; + return PJMEDIA_CODEC_EFRMTOOSHORT; /* Set payload header */ bits[0] = 0; if (pktz->cfg.fmt_id == PJMEDIA_FORMAT_VP8) { - /* Set N: Non-reference frame */ + /* Set N: Non-reference frame */ if (!is_keyframe) bits[0] |= 0x20; /* Set S: Start of VP8 partition. */ if (*bits_pos == 0) bits[0] |= 0x10; } else if (pktz->cfg.fmt_id == PJMEDIA_FORMAT_VP9) { - /* Set P: Inter-picture predicted frame */ + /* Set P: Inter-picture predicted frame */ if (!is_keyframe) bits[0] |= 0x40; /* Set B: Start of a frame */ if (*bits_pos == 0) bits[0] |= 0x8; /* Set E: End of a frame */ if (*bits_pos + *payload_len == bits_len) { bits[0] |= 0x4; - } + } } return PJ_SUCCESS; } @@ -122,9 +122,9 @@ PJ_DEF(pj_status_t) pjmedia_vpx_packetize(const pjmedia_vpx_packetizer *pktz, * Append RTP payload to a VPX picture bitstream */ PJ_DEF(pj_status_t) pjmedia_vpx_unpacketize(pjmedia_vpx_packetizer *pktz, - const pj_uint8_t *payload, + const pj_uint8_t *payload, pj_size_t payload_len, - unsigned *payload_desc_len) + unsigned *payload_desc_len) { unsigned desc_len = 1; pj_uint8_t *p = (pj_uint8_t *)payload; @@ -138,21 +138,21 @@ PJ_DEF(pj_status_t) pjmedia_vpx_unpacketize(pjmedia_vpx_packetizer *pktz, * +-+-+-+-+-+-+-+-+ * |X|R|N|S|R| PID | (REQUIRED) */ - /* X: Extended control bits present. */ - if (p[0] & 0x80) { - INC_DESC_LEN(); - /* |I|L|T|K| RSV | */ - /* I: PictureID present. */ - if (p[1] & 0x80) { - INC_DESC_LEN(); - /* If M bit is set, the PID field MUST contain 15 bits. */ - if (p[2] & 0x80) INC_DESC_LEN(); - } - /* L: TL0PICIDX present. */ - if (p[1] & 0x40) INC_DESC_LEN(); - /* T: TID present or K: KEYIDX present. */ - if ((p[1] & 0x20) || (p[1] & 0x10)) INC_DESC_LEN(); - } + /* X: Extended control bits present. */ + if (p[0] & 0x80) { + INC_DESC_LEN(); + /* |I|L|T|K| RSV | */ + /* I: PictureID present. */ + if (p[1] & 0x80) { + INC_DESC_LEN(); + /* If M bit is set, the PID field MUST contain 15 bits. */ + if (p[2] & 0x80) INC_DESC_LEN(); + } + /* L: TL0PICIDX present. */ + if (p[1] & 0x40) INC_DESC_LEN(); + /* T: TID present or K: KEYIDX present. */ + if ((p[1] & 0x20) || (p[1] & 0x10)) INC_DESC_LEN(); + } } else if (pktz->cfg.fmt_id == PJMEDIA_FORMAT_VP9) { /* 0 1 2 3 4 5 6 7 @@ -160,60 +160,60 @@ PJ_DEF(pj_status_t) pjmedia_vpx_unpacketize(pjmedia_vpx_packetizer *pktz, * |I|P|L|F|B|E|V|-| (REQUIRED) */ /* I: Picture ID (PID) present. */ - if (p[0] & 0x80) { - INC_DESC_LEN(); - /* If M bit is set, the PID field MUST contain 15 bits. */ - if (p[1] & 0x80) INC_DESC_LEN(); - } - /* L: Layer indices present. */ - if (p[0] & 0x20) { - INC_DESC_LEN(); - if (!(p[0] & 0x10)) INC_DESC_LEN(); - } - /* F: Flexible mode. - * I must also be set to 1, and if P is set, there's up to 3 - * reference index. - */ - if ((p[0] & 0x10) && (p[0] & 0x80) && (p[0] & 0x40)) { - unsigned char *q = p + desc_len; - - INC_DESC_LEN(); - if (*q & 0x1) { - q++; - INC_DESC_LEN(); - if (*q & 0x1) { - q++; - INC_DESC_LEN(); - } - } - } - /* V: Scalability structure (SS) data present. */ - if (p[0] & 0x2) { - unsigned char *q = p + desc_len; - unsigned N_S = (*q >> 5) + 1; - - INC_DESC_LEN(); - /* Y: Each spatial layer's frame resolution present. */ - if (*q & 0x10) desc_len += N_S * 4; - - /* G: PG description present flag. */ - if (*q & 0x8) { - unsigned j; - unsigned N_G = *(p + desc_len); - - INC_DESC_LEN(); - for (j = 0; j< N_G; j++) { - unsigned R; - - q = p + desc_len; - INC_DESC_LEN(); - R = (*q & 0x0F) >> 2; - desc_len += R; - if (desc_len >= payload_len) - return PJ_ETOOSMALL; - } - } - } + if (p[0] & 0x80) { + INC_DESC_LEN(); + /* If M bit is set, the PID field MUST contain 15 bits. */ + if (p[1] & 0x80) INC_DESC_LEN(); + } + /* L: Layer indices present. */ + if (p[0] & 0x20) { + INC_DESC_LEN(); + if (!(p[0] & 0x10)) INC_DESC_LEN(); + } + /* F: Flexible mode. + * I must also be set to 1, and if P is set, there's up to 3 + * reference index. + */ + if ((p[0] & 0x10) && (p[0] & 0x80) && (p[0] & 0x40)) { + unsigned char *q = p + desc_len; + + INC_DESC_LEN(); + if (*q & 0x1) { + q++; + INC_DESC_LEN(); + if (*q & 0x1) { + q++; + INC_DESC_LEN(); + } + } + } + /* V: Scalability structure (SS) data present. */ + if (p[0] & 0x2) { + unsigned char *q = p + desc_len; + unsigned N_S = (*q >> 5) + 1; + + INC_DESC_LEN(); + /* Y: Each spatial layer's frame resolution present. */ + if (*q & 0x10) desc_len += N_S * 4; + + /* G: PG description present flag. */ + if (*q & 0x8) { + unsigned j; + unsigned N_G = *(p + desc_len); + + INC_DESC_LEN(); + for (j = 0; j< N_G; j++) { + unsigned R; + + q = p + desc_len; + INC_DESC_LEN(); + R = (*q & 0x0F) >> 2; + desc_len += R; + if (desc_len >= payload_len) + return PJ_ETOOSMALL; + } + } + } } #undef INC_DESC_LEN diff --git a/pjmedia/src/pjmedia-videodev/android/PjCamera.java b/pjmedia/src/pjmedia-videodev/android/PjCamera.java index bd5198666d..b1e1858286 100644 --- a/pjmedia/src/pjmedia-videodev/android/PjCamera.java +++ b/pjmedia/src/pjmedia-videodev/android/PjCamera.java @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2015 Teluu Inc. (http://www.teluu.com) * @@ -31,10 +30,10 @@ public class PjCamera implements Camera.PreviewCallback, SurfaceHolder.Callback private final String TAG = "PjCamera"; public class Param { - public int width; - public int height; - public int format; - public int fps1000; + public int width; + public int height; + public int format; + public int fps1000; } private Camera camera = null; @@ -49,162 +48,162 @@ public class Param { private SurfaceTexture surfaceTexture = null; public PjCamera(int idx, int w, int h, int fmt, int fps, - long userData_, SurfaceView surface) + long userData_, SurfaceView surface) { - camIdx = idx; - userData = userData_; + camIdx = idx; + userData = userData_; - param = new Param(); - param.width = w; - param.height = h; - param.format = fmt; - param.fps1000 = fps; + param = new Param(); + param.width = w; + param.height = h; + param.format = fmt; + param.fps1000 = fps; - SetSurfaceView(surface); + SetSurfaceView(surface); } public void SetSurfaceView(SurfaceView surface) { - boolean isCaptureRunning = isRunning; - - if (isCaptureRunning) - Stop(); - - if (surface != null) { - surfaceView = surface; - surfaceHolder = surfaceView.getHolder(); - } else { - // Create dummy texture - surfaceHolder = null; - surfaceView = null; - if (surfaceTexture == null) { - surfaceTexture = new SurfaceTexture(10); - } - } - - if (isCaptureRunning) - Start(); + boolean isCaptureRunning = isRunning; + + if (isCaptureRunning) + Stop(); + + if (surface != null) { + surfaceView = surface; + surfaceHolder = surfaceView.getHolder(); + } else { + // Create dummy texture + surfaceHolder = null; + surfaceView = null; + if (surfaceTexture == null) { + surfaceTexture = new SurfaceTexture(10); + } + } + + if (isCaptureRunning) + Start(); } public int SwitchDevice(int idx) { - boolean isCaptureRunning = isRunning; - int oldIdx = camIdx; + boolean isCaptureRunning = isRunning; + int oldIdx = camIdx; - if (isCaptureRunning) - Stop(); + if (isCaptureRunning) + Stop(); - camIdx = idx; + camIdx = idx; - if (isCaptureRunning) { - int ret = Start(); - if (ret != 0) { - /* Try to revert back */ - camIdx = oldIdx; - Start(); - return ret; - } - } + if (isCaptureRunning) { + int ret = Start(); + if (ret != 0) { + /* Try to revert back */ + camIdx = oldIdx; + Start(); + return ret; + } + } - return 0; + return 0; } public int Start() { - try { - camera = Camera.open(camIdx); - } catch (Exception e) { - Log.d("IOException", e.getMessage()); - return -10; - } - - try { - if (surfaceHolder != null) { - camera.setPreviewDisplay(surfaceHolder); - surfaceHolder.addCallback(this); - } else { - camera.setPreviewTexture(surfaceTexture); - } - } catch (IOException e) { - Log.d("IOException", e.getMessage()); - return -20; - } - - Camera.Parameters cp = camera.getParameters(); - cp.setPreviewSize(param.width, param.height); - cp.setPreviewFormat(param.format); - // Some devices such as Nexus require an exact FPS range from the - // supported FPS ranges, specifying a subset range will raise - // exception. - //cp.setPreviewFpsRange(param.fps1000, param.fps1000); - try { - camera.setParameters(cp); - } catch (RuntimeException e) { - Log.d("RuntimeException", e.getMessage()); - return -30; - } - - camera.setPreviewCallback(this); - camera.startPreview(); - isRunning = true; - - return 0; + try { + camera = Camera.open(camIdx); + } catch (Exception e) { + Log.d("IOException", e.getMessage()); + return -10; + } + + try { + if (surfaceHolder != null) { + camera.setPreviewDisplay(surfaceHolder); + surfaceHolder.addCallback(this); + } else { + camera.setPreviewTexture(surfaceTexture); + } + } catch (IOException e) { + Log.d("IOException", e.getMessage()); + return -20; + } + + Camera.Parameters cp = camera.getParameters(); + cp.setPreviewSize(param.width, param.height); + cp.setPreviewFormat(param.format); + // Some devices such as Nexus require an exact FPS range from the + // supported FPS ranges, specifying a subset range will raise + // exception. + //cp.setPreviewFpsRange(param.fps1000, param.fps1000); + try { + camera.setParameters(cp); + } catch (RuntimeException e) { + Log.d("RuntimeException", e.getMessage()); + return -30; + } + + camera.setPreviewCallback(this); + camera.startPreview(); + isRunning = true; + + return 0; } public void Stop() { - isRunning = false; - if (camera == null) - return; + isRunning = false; + if (camera == null) + return; - if (surfaceHolder != null) - surfaceHolder.removeCallback(this); + if (surfaceHolder != null) + surfaceHolder.removeCallback(this); - camera.setPreviewCallback(null); - camera.stopPreview(); - camera.release(); - camera = null; + camera.setPreviewCallback(null); + camera.stopPreview(); + camera.release(); + camera = null; } native void PushFrame(byte[] data, int length, long userData_); public void onPreviewFrame(byte[] data, Camera camera) { - if (isRunning) { - PushFrame(data, data.length, userData); - } + if (isRunning) { + PushFrame(data, data.length, userData); + } } public void surfaceChanged(SurfaceHolder holder, - int format, int width, int height) + int format, int width, int height) { - Log.d(TAG, "VideoCaptureAndroid::surfaceChanged"); + Log.d(TAG, "VideoCaptureAndroid::surfaceChanged"); } public void surfaceCreated(SurfaceHolder holder) { - Log.d(TAG, "VideoCaptureAndroid::surfaceCreated"); - try { - if(camera != null) { - camera.setPreviewDisplay(holder); - } - } catch (IOException e) { - Log.e(TAG, "Failed to set preview surface!", e); - } + Log.d(TAG, "VideoCaptureAndroid::surfaceCreated"); + try { + if(camera != null) { + camera.setPreviewDisplay(holder); + } + } catch (IOException e) { + Log.e(TAG, "Failed to set preview surface!", e); + } } public void surfaceDestroyed(SurfaceHolder holder) { - Log.d(TAG, "VideoCaptureAndroid::surfaceDestroyed"); - try { - if(camera != null) { - camera.setPreviewDisplay(null); - } - } catch (IOException e) { - Log.e(TAG, "Failed to clear preview surface!", e); - } catch (RuntimeException e) { - Log.w(TAG, "Clear preview surface useless", e); - } + Log.d(TAG, "VideoCaptureAndroid::surfaceDestroyed"); + try { + if(camera != null) { + camera.setPreviewDisplay(null); + } + } catch (IOException e) { + Log.e(TAG, "Failed to clear preview surface!", e); + } catch (RuntimeException e) { + Log.w(TAG, "Clear preview surface useless", e); + } } } diff --git a/pjmedia/src/pjmedia-videodev/android/PjCamera2.java b/pjmedia/src/pjmedia-videodev/android/PjCamera2.java index 69b6152141..bb6ed50916 100644 --- a/pjmedia/src/pjmedia-videodev/android/PjCamera2.java +++ b/pjmedia/src/pjmedia-videodev/android/PjCamera2.java @@ -62,208 +62,208 @@ public class PjCamera2 private final SurfaceView surfaceView; native void PushFrame2(long userData_, - ByteBuffer plane0, int rowStride0, int pixStride0, - ByteBuffer plane1, int rowStride1, int pixStride1, - ByteBuffer plane2, int rowStride2, int pixStride2); + ByteBuffer plane0, int rowStride0, int pixStride0, + ByteBuffer plane1, int rowStride1, int pixStride1, + ByteBuffer plane2, int rowStride2, int pixStride2); ImageReader.OnImageAvailableListener imageAvailListener = new ImageReader.OnImageAvailableListener() { - @Override - public void onImageAvailable(ImageReader reader) { - if (!isRunning) - return; - - Image image = reader.acquireLatestImage(); - if (image == null) - return; - - /* Get planes buffers. According to the docs, the buffers are always direct buffers */ - Image.Plane[] planes = image.getPlanes(); - ByteBuffer plane0 = planes[0].getBuffer(); - ByteBuffer plane1 = planes.length > 1 ? planes[1].getBuffer() : null; - ByteBuffer plane2 = planes.length > 2 ? planes[2].getBuffer() : null; - assert plane0.isDirect(); - - //for (Image.Plane p: planes) { - // Log.d(TAG, String.format("size=%d bytes, getRowStride()=%d getPixelStride()=%d", p.getBuffer().remaining(), p.getRowStride(), p.getPixelStride())); - //} - - PushFrame2( userData, - plane0, planes[0].getRowStride(), planes[0].getPixelStride(), - plane1, plane1!=null? planes[1].getRowStride():0, plane1!=null? planes[1].getPixelStride():0, - plane2, plane2!=null? planes[2].getRowStride():0, plane2!=null? planes[2].getPixelStride():0); - - image.close(); - } + @Override + public void onImageAvailable(ImageReader reader) { + if (!isRunning) + return; + + Image image = reader.acquireLatestImage(); + if (image == null) + return; + + /* Get planes buffers. According to the docs, the buffers are always direct buffers */ + Image.Plane[] planes = image.getPlanes(); + ByteBuffer plane0 = planes[0].getBuffer(); + ByteBuffer plane1 = planes.length > 1 ? planes[1].getBuffer() : null; + ByteBuffer plane2 = planes.length > 2 ? planes[2].getBuffer() : null; + assert plane0.isDirect(); + + //for (Image.Plane p: planes) { + // Log.d(TAG, String.format("size=%d bytes, getRowStride()=%d getPixelStride()=%d", p.getBuffer().remaining(), p.getRowStride(), p.getPixelStride())); + //} + + PushFrame2( userData, + plane0, planes[0].getRowStride(), planes[0].getPixelStride(), + plane1, plane1!=null? planes[1].getRowStride():0, plane1!=null? planes[1].getPixelStride():0, + plane2, plane2!=null? planes[2].getRowStride():0, plane2!=null? planes[2].getPixelStride():0); + + image.close(); + } }; private final CameraDevice.StateCallback camStateCallback = new CameraDevice.StateCallback() { - @Override - public void onOpened(CameraDevice c) { - Log.i(TAG, "CameraDevice.StateCallback.onOpened"); - camera = c; - StartPreview(); - } - @Override - public void onClosed(CameraDevice c) { - Log.i(TAG, "CameraDevice.StateCallback.onClosed"); - } - @Override - public void onDisconnected(CameraDevice c) { - Log.i(TAG, "CameraDevice.StateCallback.onDisconnected"); - Stop(); - } - @Override - public void onError(CameraDevice c, int error) { - Log.e(TAG, "CameraDevice.StateCallback.onError: " + error); - - boolean was_with_fps = start_with_fps; - Stop(); - - /* First retry */ - if ((error == CameraDevice.StateCallback.ERROR_CAMERA_DEVICE || - error == CameraDevice.StateCallback.ERROR_CAMERA_SERVICE) && - was_with_fps) - { - Log.i(TAG, "Retrying without enforcing frame rate.."); - start_with_fps = false; - Start(); - } - } + @Override + public void onOpened(CameraDevice c) { + Log.i(TAG, "CameraDevice.StateCallback.onOpened"); + camera = c; + StartPreview(); + } + @Override + public void onClosed(CameraDevice c) { + Log.i(TAG, "CameraDevice.StateCallback.onClosed"); + } + @Override + public void onDisconnected(CameraDevice c) { + Log.i(TAG, "CameraDevice.StateCallback.onDisconnected"); + Stop(); + } + @Override + public void onError(CameraDevice c, int error) { + Log.e(TAG, "CameraDevice.StateCallback.onError: " + error); + + boolean was_with_fps = start_with_fps; + Stop(); + + /* First retry */ + if ((error == CameraDevice.StateCallback.ERROR_CAMERA_DEVICE || + error == CameraDevice.StateCallback.ERROR_CAMERA_SERVICE) && + was_with_fps) + { + Log.i(TAG, "Retrying without enforcing frame rate.."); + start_with_fps = false; + Start(); + } + } }; private final SurfaceHolder.Callback surfaceHolderCallback = new SurfaceHolder.Callback() { - @Override - public void surfaceCreated(SurfaceHolder holder) { - Log.d(TAG, "SurfaceHolder.Callback.surfaceCreated"); - if (camera != null) { - StartPreview(); - } - } - - @Override - public void surfaceChanged(SurfaceHolder holder, - int format, int width, int height) - { - Log.d(TAG, "SurfaceHolder.Callback.surfaceChanged"); - } - - @Override - public void surfaceDestroyed(SurfaceHolder holder) - { - Log.d(TAG, "SurfaceHolder.Callback.surfaceDestroyed"); - } + @Override + public void surfaceCreated(SurfaceHolder holder) { + Log.d(TAG, "SurfaceHolder.Callback.surfaceCreated"); + if (camera != null) { + StartPreview(); + } + } + + @Override + public void surfaceChanged(SurfaceHolder holder, + int format, int width, int height) + { + Log.d(TAG, "SurfaceHolder.Callback.surfaceChanged"); + } + + @Override + public void surfaceDestroyed(SurfaceHolder holder) + { + Log.d(TAG, "SurfaceHolder.Callback.surfaceDestroyed"); + } }; public PjCamera2(int idx, int w_, int h_, int fmt_, int fps_, - long userData_, SurfaceView surface) + long userData_, SurfaceView surface) { - camIdx = idx; - w = w_; - h = h_; - fmt = fmt_; - userData = userData_; - fps = fps_; - surfaceView = surface; + camIdx = idx; + w = w_; + h = h_; + fmt = fmt_; + userData = userData_; + fps = fps_; + surfaceView = surface; } public int SwitchDevice(int idx) { - boolean isCaptureRunning = isRunning; - int oldIdx = camIdx; + boolean isCaptureRunning = isRunning; + int oldIdx = camIdx; - if (isCaptureRunning) - Stop(); + if (isCaptureRunning) + Stop(); - camIdx = idx; + camIdx = idx; - if (isCaptureRunning) { - int ret = Start(); - if (ret != 0) { - /* Try to revert back */ - camIdx = oldIdx; - Start(); - return ret; - } - } + if (isCaptureRunning) { + int ret = Start(); + if (ret != 0) { + /* Try to revert back */ + camIdx = oldIdx; + Start(); + return ret; + } + } - return 0; + return 0; } private void StartPreview() { - try { - List surfaceList = new ArrayList<>(); - surfaceList.add(imageReader.getSurface()); - if (surfaceView != null) - surfaceList.add(surfaceView.getHolder().getSurface()); - - camera.createCaptureSession(surfaceList, - new CameraCaptureSession.StateCallback() { - @Override - public void onConfigured(CameraCaptureSession session) { - Log.d(TAG, "CameraCaptureSession.StateCallback.onConfigured"); - - try { - CaptureRequest.Builder previewBuilder = camera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD); - previewBuilder.addTarget(imageReader.getSurface()); - if (surfaceView != null) - previewBuilder.addTarget(surfaceView.getHolder().getSurface()); - previewBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO); - if (start_with_fps) { - Range fpsRange = new Range<>(fps, fps); - previewBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, fpsRange); - } - session.setRepeatingRequest(previewBuilder.build(), null, handler); - previewSession = session; - } catch (Exception e) { - Log.d(TAG, e.getMessage()); - Stop(); - } - if (surfaceView!=null) - surfaceView.getHolder().addCallback(surfaceHolderCallback); - } - @Override - public void onConfigureFailed(CameraCaptureSession session) { - Log.e(TAG, "CameraCaptureSession.StateCallback.onConfigureFailed"); - Stop(); - } - }, handler); - } catch (Exception e) { - Log.d(TAG, e.getMessage()); - Stop(); - } + try { + List surfaceList = new ArrayList<>(); + surfaceList.add(imageReader.getSurface()); + if (surfaceView != null) + surfaceList.add(surfaceView.getHolder().getSurface()); + + camera.createCaptureSession(surfaceList, + new CameraCaptureSession.StateCallback() { + @Override + public void onConfigured(CameraCaptureSession session) { + Log.d(TAG, "CameraCaptureSession.StateCallback.onConfigured"); + + try { + CaptureRequest.Builder previewBuilder = camera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD); + previewBuilder.addTarget(imageReader.getSurface()); + if (surfaceView != null) + previewBuilder.addTarget(surfaceView.getHolder().getSurface()); + previewBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO); + if (start_with_fps) { + Range fpsRange = new Range<>(fps, fps); + previewBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, fpsRange); + } + session.setRepeatingRequest(previewBuilder.build(), null, handler); + previewSession = session; + } catch (Exception e) { + Log.d(TAG, e.getMessage()); + Stop(); + } + if (surfaceView!=null) + surfaceView.getHolder().addCallback(surfaceHolderCallback); + } + @Override + public void onConfigureFailed(CameraCaptureSession session) { + Log.e(TAG, "CameraCaptureSession.StateCallback.onConfigureFailed"); + Stop(); + } + }, handler); + } catch (Exception e) { + Log.d(TAG, e.getMessage()); + Stop(); + } } public int Start() { - PjCameraInfo2 ci = PjCameraInfo2.GetCameraInfo(camIdx); - if (ci == null) { - Log.e(TAG, "Invalid device index: " + camIdx); - return -1; - } - - CameraManager cm = PjCameraInfo2.GetCameraManager(); - if (cm == null) - return -2; - - handlerThread = new HandlerThread("Cam2HandlerThread"); - handlerThread.start(); - handler = new Handler(handlerThread.getLooper()); - - /* Some say to put a larger maxImages to improve FPS */ - imageReader = ImageReader.newInstance(w, h, fmt, 3); - imageReader.setOnImageAvailableListener(imageAvailListener, handler); - isRunning = true; - - try { - cm.openCamera(ci.id, camStateCallback, handler); - } catch (Exception e) { - Log.d(TAG, e.getMessage()); - Stop(); - return -10; - } - - return 0; + PjCameraInfo2 ci = PjCameraInfo2.GetCameraInfo(camIdx); + if (ci == null) { + Log.e(TAG, "Invalid device index: " + camIdx); + return -1; + } + + CameraManager cm = PjCameraInfo2.GetCameraManager(); + if (cm == null) + return -2; + + handlerThread = new HandlerThread("Cam2HandlerThread"); + handlerThread.start(); + handler = new Handler(handlerThread.getLooper()); + + /* Some say to put a larger maxImages to improve FPS */ + imageReader = ImageReader.newInstance(w, h, fmt, 3); + imageReader.setOnImageAvailableListener(imageAvailListener, handler); + isRunning = true; + + try { + cm.openCamera(ci.id, camStateCallback, handler); + } catch (Exception e) { + Log.d(TAG, e.getMessage()); + Stop(); + return -10; + } + + return 0; } public void Stop() @@ -271,46 +271,46 @@ public void Stop() if (!isRunning) return; - isRunning = false; - Log.d(TAG, "Stopping.."); - - if (previewSession != null) { - previewSession.close(); - previewSession = null; - } - - if (camera != null) { - camera.close(); - camera = null; - } - - if (surfaceView != null) - surfaceView.getHolder().removeCallback(surfaceHolderCallback); - - if (handlerThread != null) { - handlerThread.quitSafely(); - try { - if (handlerThread.getId() != Thread.currentThread().getId()) { - Log.d(TAG, "Wait thread.."); - handlerThread.join(); - Log.d(TAG, "Wait thread done"); - } - handlerThread = null; - handler = null; - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - if (imageReader != null) { - imageReader.close(); - imageReader = null; - } - - /* Reset setting */ - start_with_fps = true; - - Log.d(TAG, "Stopped."); + isRunning = false; + Log.d(TAG, "Stopping.."); + + if (previewSession != null) { + previewSession.close(); + previewSession = null; + } + + if (camera != null) { + camera.close(); + camera = null; + } + + if (surfaceView != null) + surfaceView.getHolder().removeCallback(surfaceHolderCallback); + + if (handlerThread != null) { + handlerThread.quitSafely(); + try { + if (handlerThread.getId() != Thread.currentThread().getId()) { + Log.d(TAG, "Wait thread.."); + handlerThread.join(); + Log.d(TAG, "Wait thread done"); + } + handlerThread = null; + handler = null; + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + if (imageReader != null) { + imageReader.close(); + imageReader = null; + } + + /* Reset setting */ + start_with_fps = true; + + Log.d(TAG, "Stopped."); } } diff --git a/pjmedia/src/pjmedia-videodev/android/PjCameraInfo.java b/pjmedia/src/pjmedia-videodev/android/PjCameraInfo.java index b974518e92..0cf04e0a5a 100644 --- a/pjmedia/src/pjmedia-videodev/android/PjCameraInfo.java +++ b/pjmedia/src/pjmedia-videodev/android/PjCameraInfo.java @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2015 Teluu Inc. (http://www.teluu.com) * @@ -26,85 +25,85 @@ public class PjCameraInfo { public int facing; public int orient; - public int[] supportedSize; // [w1, h1, w2, h2, ...] - public int[] supportedFps1000; // [min1, max1, min2, max2, ...] - public int[] supportedFormat; // [fmt1, fmt2, ...] + public int[] supportedSize; // [w1, h1, w2, h2, ...] + public int[] supportedFps1000; // [min1, max1, min2, max2, ...] + public int[] supportedFormat; // [fmt1, fmt2, ...] // convert Format list {fmt1, fmt2, ...} to [fmt1, fmt2, ...] private static int[] IntegerListToIntArray(List list) { - int[] li = new int[list.size()]; - int i = 0; - for (Integer e : list) { - li[i++] = e.intValue(); - } - return li; + int[] li = new int[list.size()]; + int i = 0; + for (Integer e : list) { + li[i++] = e.intValue(); + } + return li; } // convert Fps list {[min1, max1], [min2, max2], ...} to // [min1, max1, min2, max2, ...] private static int[] IntArrayListToIntArray(List list) { - int[] li = new int[list.size() * 2]; - int i = 0; - for (int[] e : list) { - li[i++] = e[0]; - li[i++] = e[1]; - } - return li; + int[] li = new int[list.size() * 2]; + int i = 0; + for (int[] e : list) { + li[i++] = e[0]; + li[i++] = e[1]; + } + return li; } // convert Size list {{w1, h1}, {w2, h2}, ...} to [w1, h1, w2, h2, ...] private static int[] CameraSizeListToIntArray(List list) { - int[] li = new int[list.size() * 2]; - int i = 0; - for (Camera.Size e : list) { - li[i++] = e.width; - li[i++] = e.height; - } - return li; + int[] li = new int[list.size() * 2]; + int i = 0; + for (Camera.Size e : list) { + li[i++] = e.width; + li[i++] = e.height; + } + return li; } public static int GetCameraCount() { - return Camera.getNumberOfCameras(); + return Camera.getNumberOfCameras(); } // Get camera info: facing, orientation, supported size/fps/format. // Camera must not be opened. public static PjCameraInfo GetCameraInfo(int idx) { - if (idx < 0 || idx >= GetCameraCount()) - return null; + if (idx < 0 || idx >= GetCameraCount()) + return null; - Camera cam; - try { - cam = Camera.open(idx); - } catch (Exception e) { - Log.d("IOException", e.getMessage()); - return null; - } + Camera cam; + try { + cam = Camera.open(idx); + } catch (Exception e) { + Log.d("IOException", e.getMessage()); + return null; + } - PjCameraInfo pjci = new PjCameraInfo(); + PjCameraInfo pjci = new PjCameraInfo(); - Camera.CameraInfo ci = new Camera.CameraInfo(); - Camera.getCameraInfo(idx, ci); + Camera.CameraInfo ci = new Camera.CameraInfo(); + Camera.getCameraInfo(idx, ci); - pjci.facing = ci.facing; - pjci.orient = ci.orientation; + pjci.facing = ci.facing; + pjci.orient = ci.orientation; - Camera.Parameters param = cam.getParameters(); - cam.release(); - cam = null; + Camera.Parameters param = cam.getParameters(); + cam.release(); + cam = null; - pjci.supportedFormat = IntegerListToIntArray( - param.getSupportedPreviewFormats()); - pjci.supportedFps1000 = IntArrayListToIntArray( - param.getSupportedPreviewFpsRange()); - pjci.supportedSize = CameraSizeListToIntArray( - param.getSupportedPreviewSizes()); + pjci.supportedFormat = IntegerListToIntArray( + param.getSupportedPreviewFormats()); + pjci.supportedFps1000 = IntArrayListToIntArray( + param.getSupportedPreviewFpsRange()); + pjci.supportedSize = CameraSizeListToIntArray( + param.getSupportedPreviewSizes()); - return pjci; + return pjci; } } diff --git a/pjmedia/src/pjmedia-videodev/android/PjCameraInfo2.java b/pjmedia/src/pjmedia-videodev/android/PjCameraInfo2.java index 215d5dce23..1f5d7d779a 100644 --- a/pjmedia/src/pjmedia-videodev/android/PjCameraInfo2.java +++ b/pjmedia/src/pjmedia-videodev/android/PjCameraInfo2.java @@ -28,11 +28,11 @@ public class PjCameraInfo2 { public String id; - public int facing; // 0: back, 1: front, 2: external + public int facing; // 0: back, 1: front, 2: external public int orient; - public int[] supportedSize; // [w1, h1, w2, h2, ...] - public int[] supportedFps1000; // [min1, max1, min2, max2, ...] - public int[] supportedFormat; // [fmt1, fmt2, ...] + public int[] supportedSize; // [w1, h1, w2, h2, ...] + public int[] supportedFps1000; // [min1, max1, min2, max2, ...] + public int[] supportedFormat; // [fmt1, fmt2, ...] private static final String TAG = "PjCameraInfo2"; @@ -43,7 +43,7 @@ public class PjCameraInfo2 { * For now, we only support I420. */ private static final int[] PJ_SUPPORTED_FORMAT = { - ImageFormat.YUV_420_888, // PJMEDIA_FORMAT_I420 + ImageFormat.YUV_420_888, // PJMEDIA_FORMAT_I420 }; private static boolean is_inited = false; @@ -56,147 +56,147 @@ public static void SetCameraManager(CameraManager cm) { } public static CameraManager GetCameraManager() { - return cameraManager; + return cameraManager; } private static int Refresh() { - CameraManager cm = GetCameraManager(); - if (cm==null) { - Log.e(TAG, "Need camera manager instance for enumerating camera"); - return -1; - } - - is_inited = false; - - String[] camIds; - try { - camIds = cm.getCameraIdList(); - } catch (CameraAccessException e) { - Log.d(TAG, e.getMessage()); - e.printStackTrace(); - return -1; - } - - camInfo = new PjCameraInfo2[camIds.length]; - camInfoCnt = 0; - - Log.i(TAG, "Found " + camIds.length + " cameras:"); - for (int i = 0; i < camIds.length; ++i) { - Integer facing; - CameraCharacteristics cc; - StreamConfigurationMap scm; - int[] outFmts; - - /* Query basic info */ - try { - cc = cm.getCameraCharacteristics(camIds[i]); - facing = cc.get(CameraCharacteristics.LENS_FACING); - scm = cc.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); - outFmts = scm.getOutputFormats(); - } catch (Exception e) { - Log.d(TAG, e.getMessage()); - Log.w(TAG, String.format("%3d: id=%s skipped due to failure in querying info", - i, camIds[i])); - continue; - } - - PjCameraInfo2 pjci = new PjCameraInfo2(); - pjci.id = camIds[i]; - switch(facing) { - case CameraCharacteristics.LENS_FACING_BACK: - pjci.facing = 0; - break; - case CameraCharacteristics.LENS_FACING_FRONT: - pjci.facing = 1; - break; - default: - pjci.facing = 2; - break; - } - - int[] fmts = new int[outFmts.length]; - int fmtCnt = 0; - for (int pjFmt : PJ_SUPPORTED_FORMAT) { - for (int outFmt : outFmts) { - if (outFmt == pjFmt) { - fmts[fmtCnt++] = pjFmt; - break; - } - } - } - Log.i(TAG, String.format("%3d: id=%s formats=%s", - i, pjci.id, Arrays.toString(outFmts))); - if (fmtCnt == 0) { - Log.w(TAG, String.format("%3d: id=%s skipped due to no PJSIP compatible format", - i, pjci.id)); - continue; - } - - pjci.supportedFormat = new int[fmtCnt]; - System.arraycopy(fmts, 0, pjci.supportedFormat, 0, fmtCnt); - - /* Query additional info */ - try { - pjci.orient = cc.get(CameraCharacteristics.SENSOR_ORIENTATION); - } catch (Exception e) { - Log.d(TAG, e.getMessage()); - Log.w(TAG, String.format("%3d: id=%s failed in getting orient", - i, camIds[i])); - } - - try { - Size[] suppSize = scm.getOutputSizes(pjci.supportedFormat[0]); - pjci.supportedSize = new int[suppSize.length * 2]; - for (int j = 0; j < suppSize.length; ++j) { - pjci.supportedSize[j*2] = suppSize[j].getWidth(); - pjci.supportedSize[j*2 + 1] = suppSize[j].getHeight(); - } - } catch (Exception e) { - Log.d(TAG, e.getMessage()); - Log.w(TAG, String.format("%3d: id=%s failed in getting sizes", - i, camIds[i])); - - /* Query failed, let's just hardcode the supported sizes */ - pjci.supportedSize = new int[] {176, 144, 320, 240, 352, 288, 640, 480, 1280, 720, 1920, 1080}; - } - - /* FPS info is not really used for now, let's just hardcode it */ - pjci.supportedFps1000 = new int[] { 1000, 30000 }; - - camInfo[camInfoCnt++] = pjci; - - Log.i(TAG, String.format("%3d: id=%s facing=%d orient=%d formats=%s sizes=%s", - i, pjci.id, pjci.facing, pjci.orient, - Arrays.toString(pjci.supportedFormat), - Arrays.toString(pjci.supportedSize))); - } - - is_inited = true; - return 0; + CameraManager cm = GetCameraManager(); + if (cm==null) { + Log.e(TAG, "Need camera manager instance for enumerating camera"); + return -1; + } + + is_inited = false; + + String[] camIds; + try { + camIds = cm.getCameraIdList(); + } catch (CameraAccessException e) { + Log.d(TAG, e.getMessage()); + e.printStackTrace(); + return -1; + } + + camInfo = new PjCameraInfo2[camIds.length]; + camInfoCnt = 0; + + Log.i(TAG, "Found " + camIds.length + " cameras:"); + for (int i = 0; i < camIds.length; ++i) { + Integer facing; + CameraCharacteristics cc; + StreamConfigurationMap scm; + int[] outFmts; + + /* Query basic info */ + try { + cc = cm.getCameraCharacteristics(camIds[i]); + facing = cc.get(CameraCharacteristics.LENS_FACING); + scm = cc.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); + outFmts = scm.getOutputFormats(); + } catch (Exception e) { + Log.d(TAG, e.getMessage()); + Log.w(TAG, String.format("%3d: id=%s skipped due to failure in querying info", + i, camIds[i])); + continue; + } + + PjCameraInfo2 pjci = new PjCameraInfo2(); + pjci.id = camIds[i]; + switch(facing) { + case CameraCharacteristics.LENS_FACING_BACK: + pjci.facing = 0; + break; + case CameraCharacteristics.LENS_FACING_FRONT: + pjci.facing = 1; + break; + default: + pjci.facing = 2; + break; + } + + int[] fmts = new int[outFmts.length]; + int fmtCnt = 0; + for (int pjFmt : PJ_SUPPORTED_FORMAT) { + for (int outFmt : outFmts) { + if (outFmt == pjFmt) { + fmts[fmtCnt++] = pjFmt; + break; + } + } + } + Log.i(TAG, String.format("%3d: id=%s formats=%s", + i, pjci.id, Arrays.toString(outFmts))); + if (fmtCnt == 0) { + Log.w(TAG, String.format("%3d: id=%s skipped due to no PJSIP compatible format", + i, pjci.id)); + continue; + } + + pjci.supportedFormat = new int[fmtCnt]; + System.arraycopy(fmts, 0, pjci.supportedFormat, 0, fmtCnt); + + /* Query additional info */ + try { + pjci.orient = cc.get(CameraCharacteristics.SENSOR_ORIENTATION); + } catch (Exception e) { + Log.d(TAG, e.getMessage()); + Log.w(TAG, String.format("%3d: id=%s failed in getting orient", + i, camIds[i])); + } + + try { + Size[] suppSize = scm.getOutputSizes(pjci.supportedFormat[0]); + pjci.supportedSize = new int[suppSize.length * 2]; + for (int j = 0; j < suppSize.length; ++j) { + pjci.supportedSize[j*2] = suppSize[j].getWidth(); + pjci.supportedSize[j*2 + 1] = suppSize[j].getHeight(); + } + } catch (Exception e) { + Log.d(TAG, e.getMessage()); + Log.w(TAG, String.format("%3d: id=%s failed in getting sizes", + i, camIds[i])); + + /* Query failed, let's just hardcode the supported sizes */ + pjci.supportedSize = new int[] {176, 144, 320, 240, 352, 288, 640, 480, 1280, 720, 1920, 1080}; + } + + /* FPS info is not really used for now, let's just hardcode it */ + pjci.supportedFps1000 = new int[] { 1000, 30000 }; + + camInfo[camInfoCnt++] = pjci; + + Log.i(TAG, String.format("%3d: id=%s facing=%d orient=%d formats=%s sizes=%s", + i, pjci.id, pjci.facing, pjci.orient, + Arrays.toString(pjci.supportedFormat), + Arrays.toString(pjci.supportedSize))); + } + + is_inited = true; + return 0; } public static int GetCameraCount() { /* Always refresh */ - if (Refresh() != 0) { - return -1; - } - return camInfoCnt; + if (Refresh() != 0) { + return -1; + } + return camInfoCnt; } /* Get camera info: facing, orientation, supported size/fps/format. */ public static PjCameraInfo2 GetCameraInfo(int idx) { - if (!is_inited) { - Log.e(TAG, "Not initalized"); - return null; - } + if (!is_inited) { + Log.e(TAG, "Not initalized"); + return null; + } - if (idx < 0 || idx >= camInfoCnt) { - Log.e(TAG, "Invalid camera ID"); - return null; - } + if (idx < 0 || idx >= camInfoCnt) { + Log.e(TAG, "Invalid camera ID"); + return null; + } - return camInfo[idx]; + return camInfo[idx]; } } diff --git a/pjmedia/src/pjmedia-videodev/android_dev.c b/pjmedia/src/pjmedia-videodev/android_dev.c index efc6bf5863..0650fca5ef 100644 --- a/pjmedia/src/pjmedia-videodev/android_dev.c +++ b/pjmedia/src/pjmedia-videodev/android_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2015 Teluu Inc. (http://www.teluu.com) * @@ -30,25 +29,25 @@ #include -#define THIS_FILE "android_dev.c" +#define THIS_FILE "android_dev.c" /* Default video params */ -#define DEFAULT_CLOCK_RATE 90000 -#define DEFAULT_WIDTH 352 -#define DEFAULT_HEIGHT 288 -#define DEFAULT_FPS 15 -#define ALIGN16(x) ((((x)+15) >> 4) << 4) +#define DEFAULT_CLOCK_RATE 90000 +#define DEFAULT_WIDTH 352 +#define DEFAULT_HEIGHT 288 +#define DEFAULT_FPS 15 +#define ALIGN16(x) ((((x)+15) >> 4) << 4) /* Define whether we should maintain the aspect ratio when rotating the image. * For more details, please refer to util.h. */ -#define MAINTAIN_ASPECT_RATIO PJ_TRUE +#define MAINTAIN_ASPECT_RATIO PJ_TRUE /* Format map info */ typedef struct and_fmt_map { pjmedia_format_id fmt_id; - pj_uint32_t and_fmt_id; + pj_uint32_t and_fmt_id; } and_fmt_map; @@ -69,62 +68,62 @@ static and_fmt_map fmt_map[] = /* Device info */ typedef struct and_dev_info { - pjmedia_vid_dev_info info; /**< Base info */ - unsigned dev_idx; /**< Original dev ID */ - pj_bool_t facing; /**< Front/back camera?*/ - unsigned sup_size_cnt; /**< # of supp'd size */ - pjmedia_rect_size *sup_size; /**< Supported size */ - unsigned sup_fps_cnt; /**< # of supp'd FPS */ - pjmedia_rect_size *sup_fps; /**< Supported FPS */ - pj_bool_t has_yv12; /**< Support YV12? */ - pj_bool_t has_nv21; /**< Support NV21? */ - pj_bool_t forced_i420; /**< Support I420 with - conversion */ + pjmedia_vid_dev_info info; /**< Base info */ + unsigned dev_idx; /**< Original dev ID */ + pj_bool_t facing; /**< Front/back camera?*/ + unsigned sup_size_cnt; /**< # of supp'd size */ + pjmedia_rect_size *sup_size; /**< Supported size */ + unsigned sup_fps_cnt; /**< # of supp'd FPS */ + pjmedia_rect_size *sup_fps; /**< Supported FPS */ + pj_bool_t has_yv12; /**< Support YV12? */ + pj_bool_t has_nv21; /**< Support NV21? */ + pj_bool_t forced_i420; /**< Support I420 with + conversion */ } and_dev_info; /* Video factory */ typedef struct and_factory { - pjmedia_vid_dev_factory base; /**< Base factory */ - pj_pool_t *pool; /**< Memory pool */ - pj_pool_factory *pf; /**< Pool factory */ + pjmedia_vid_dev_factory base; /**< Base factory */ + pj_pool_t *pool; /**< Memory pool */ + pj_pool_factory *pf; /**< Pool factory */ - pj_pool_t *dev_pool; /**< Device list pool */ - unsigned dev_count; /**< Device count */ - and_dev_info *dev_info; /**< Device info list */ + pj_pool_t *dev_pool; /**< Device list pool */ + unsigned dev_count; /**< Device count */ + and_dev_info *dev_info; /**< Device info list */ } and_factory; /* Video stream. */ typedef struct and_stream { - pjmedia_vid_dev_stream base; /**< Base stream */ - pjmedia_vid_dev_param param; /**< Settings */ - pj_pool_t *pool; /**< Memory pool */ - and_factory *factory; /**< Factory */ + pjmedia_vid_dev_stream base; /**< Base stream */ + pjmedia_vid_dev_param param; /**< Settings */ + pj_pool_t *pool; /**< Memory pool */ + and_factory *factory; /**< Factory */ - pjmedia_vid_dev_cb vid_cb; /**< Stream callback */ - void *user_data; /**< Application data */ - pj_bool_t is_running; /**< Stream running? */ + pjmedia_vid_dev_cb vid_cb; /**< Stream callback */ + void *user_data; /**< Application data */ + pj_bool_t is_running; /**< Stream running? */ - jobject jcam; /**< PjCamera instance */ - - pj_timestamp frame_ts; /**< Current timestamp */ - unsigned ts_inc; /**< Timestamp interval*/ - unsigned convert_to_i420; /**< Need to convert to I420? - 0: no - 1: from NV21 - 2: from YV12 */ + jobject jcam; /**< PjCamera instance */ + + pj_timestamp frame_ts; /**< Current timestamp */ + unsigned ts_inc; /**< Timestamp interval*/ + unsigned convert_to_i420; /**< Need to convert to I420? + 0: no + 1: from NV21 + 2: from YV12 */ /** Capture thread info */ - pj_bool_t thread_initialized; - pj_thread_desc thread_desc; - pj_thread_t *thread; + pj_bool_t thread_initialized; + pj_thread_desc thread_desc; + pj_thread_t *thread; /** NV21/YV12 -> I420 Conversion buffer */ - pj_uint8_t *convert_buf; - pjmedia_rect_size cam_size; + pj_uint8_t *convert_buf; + pjmedia_rect_size cam_size; /** Converter to rotate frame */ pjmedia_vid_dev_conv conv; @@ -140,18 +139,18 @@ static pj_status_t and_factory_destroy(pjmedia_vid_dev_factory *f); static pj_status_t and_factory_refresh(pjmedia_vid_dev_factory *f); static unsigned and_factory_get_dev_count(pjmedia_vid_dev_factory *f); static pj_status_t and_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info); + unsigned index, + pjmedia_vid_dev_info *info); static pj_status_t and_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param); + unsigned index, + pjmedia_vid_dev_param *param); static pj_status_t and_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm); + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm); static pj_status_t and_stream_get_param(pjmedia_vid_dev_stream *strm, @@ -198,40 +197,40 @@ static pjmedia_vid_dev_stream_op stream_op = extern JavaVM *pj_jni_jvm; /* Use camera2 (since Android API level 21) */ -#define USE_CAMERA2 1 +#define USE_CAMERA2 1 #if USE_CAMERA2 -#define PJ_CAMERA "PjCamera2" -#define PJ_CAMERA_INFO "PjCameraInfo2" +#define PJ_CAMERA "PjCamera2" +#define PJ_CAMERA_INFO "PjCameraInfo2" #else -#define PJ_CAMERA "PjCamera" -#define PJ_CAMERA_INFO "PjCameraInfo" +#define PJ_CAMERA "PjCamera" +#define PJ_CAMERA_INFO "PjCameraInfo" #endif -#define PJ_CLASS_PATH "org/pjsip/" -#define PJ_CAMERA_CLASS_PATH PJ_CLASS_PATH PJ_CAMERA -#define PJ_CAMERA_INFO_CLASS_PATH PJ_CLASS_PATH PJ_CAMERA_INFO +#define PJ_CLASS_PATH "org/pjsip/" +#define PJ_CAMERA_CLASS_PATH PJ_CLASS_PATH PJ_CAMERA +#define PJ_CAMERA_INFO_CLASS_PATH PJ_CLASS_PATH PJ_CAMERA_INFO static struct jni_objs_t { struct { - jclass cls; - jmethodID m_init; - jmethodID m_start; - jmethodID m_stop; - jmethodID m_switch; + jclass cls; + jmethodID m_init; + jmethodID m_start; + jmethodID m_stop; + jmethodID m_switch; } cam; struct { - jclass cls; - jmethodID m_get_cnt; - jmethodID m_get_info; - jfieldID f_facing; - jfieldID f_orient; - jfieldID f_sup_size; - jfieldID f_sup_fmt; - jfieldID f_sup_fps; + jclass cls; + jmethodID m_get_cnt; + jmethodID m_get_info; + jfieldID f_facing; + jfieldID f_orient; + jfieldID f_sup_size; + jfieldID f_sup_fmt; + jfieldID f_sup_fps; } cam_info; } jobjs; @@ -239,14 +238,14 @@ static struct jni_objs_t #if USE_CAMERA2 static void JNICALL OnGetFrame2(JNIEnv *env, jobject obj, - jlong user_data, - jobject plane0, jint rowStride0, jint pixStride0, - jobject plane1, jint rowStride1, jint pixStride1, - jobject plane2, jint rowStride2, jint pixStride2); + jlong user_data, + jobject plane0, jint rowStride0, jint pixStride0, + jobject plane1, jint rowStride1, jint pixStride1, + jobject plane2, jint rowStride2, jint pixStride2); #else static void JNICALL OnGetFrame(JNIEnv *env, jobject obj, jbyteArray data, jint length, - jlong user_data); + jlong user_data); #endif @@ -260,8 +259,8 @@ static pj_bool_t jni_get_env(JNIEnv **jni_env) { *jni_env = NULL; } else { - with_attach = PJ_TRUE; - } + with_attach = PJ_TRUE; + } } return with_attach; @@ -289,27 +288,27 @@ static pj_status_t jni_init_ids() #define GET_CLASS(class_path, class_name, cls) \ cls = (*jni_env)->FindClass(jni_env, class_path); \ if (cls == NULL || (*jni_env)->ExceptionCheck(jni_env)) { \ - (*jni_env)->ExceptionClear(jni_env); \ + (*jni_env)->ExceptionClear(jni_env); \ PJ_LOG(3, (THIS_FILE, "[JNI] Unable to find class '" \ - class_name "'")); \ + class_name "'")); \ status = PJMEDIA_EVID_SYSERR; \ goto on_return; \ } else { \ jclass tmp = cls; \ - cls = (jclass)(*jni_env)->NewGlobalRef(jni_env, tmp); \ - (*jni_env)->DeleteLocalRef(jni_env, tmp); \ - if (cls == NULL) { \ - PJ_LOG(3, (THIS_FILE, "[JNI] Unable to get global ref for " \ - "class '" class_name "'")); \ - status = PJMEDIA_EVID_SYSERR; \ - goto on_return; \ - } \ + cls = (jclass)(*jni_env)->NewGlobalRef(jni_env, tmp); \ + (*jni_env)->DeleteLocalRef(jni_env, tmp); \ + if (cls == NULL) { \ + PJ_LOG(3, (THIS_FILE, "[JNI] Unable to get global ref for " \ + "class '" class_name "'")); \ + status = PJMEDIA_EVID_SYSERR; \ + goto on_return; \ + } \ } #define GET_METHOD_ID(cls, class_name, method_name, signature, id) \ id = (*jni_env)->GetMethodID(jni_env, cls, method_name, signature); \ if (id == 0) { \ PJ_LOG(3, (THIS_FILE, "[JNI] Unable to find method '" method_name \ - "' in class '" class_name "'")); \ + "' in class '" class_name "'")); \ status = PJMEDIA_EVID_SYSERR; \ goto on_return; \ } @@ -317,7 +316,7 @@ static pj_status_t jni_init_ids() id = (*jni_env)->GetStaticMethodID(jni_env, cls, method_name, signature); \ if (id == 0) { \ PJ_LOG(3, (THIS_FILE, "[JNI] Unable to find static method '" \ - method_name "' in class '" class_name "'")); \ + method_name "' in class '" class_name "'")); \ status = PJMEDIA_EVID_SYSERR; \ goto on_return; \ } @@ -325,7 +324,7 @@ static pj_status_t jni_init_ids() id = (*jni_env)->GetFieldID(jni_env, cls, field_name, signature); \ if (id == 0) { \ PJ_LOG(3, (THIS_FILE, "[JNI] Unable to find field '" field_name \ - "' in class '" class_name "'")); \ + "' in class '" class_name "'")); \ status = PJMEDIA_EVID_SYSERR; \ goto on_return; \ } @@ -333,32 +332,32 @@ static pj_status_t jni_init_ids() /* PjCamera class info */ GET_CLASS(PJ_CAMERA_CLASS_PATH, PJ_CAMERA, jobjs.cam.cls); GET_METHOD_ID(jobjs.cam.cls, PJ_CAMERA, "", - "(IIIIIJLandroid/view/SurfaceView;)V", - jobjs.cam.m_init); + "(IIIIIJLandroid/view/SurfaceView;)V", + jobjs.cam.m_init); GET_METHOD_ID(jobjs.cam.cls, PJ_CAMERA, "Start", "()I", - jobjs.cam.m_start); + jobjs.cam.m_start); GET_METHOD_ID(jobjs.cam.cls, PJ_CAMERA, "Stop", "()V", - jobjs.cam.m_stop); + jobjs.cam.m_stop); GET_METHOD_ID(jobjs.cam.cls, PJ_CAMERA, "SwitchDevice", "(I)I", - jobjs.cam.m_switch); + jobjs.cam.m_switch); /* PjCameraInfo class info */ GET_CLASS(PJ_CAMERA_INFO_CLASS_PATH, PJ_CAMERA_INFO, jobjs.cam_info.cls); GET_SMETHOD_ID(jobjs.cam_info.cls, PJ_CAMERA_INFO, "GetCameraCount", "()I", - jobjs.cam_info.m_get_cnt); + jobjs.cam_info.m_get_cnt); GET_SMETHOD_ID(jobjs.cam_info.cls, PJ_CAMERA_INFO, "GetCameraInfo", - "(I)L" PJ_CAMERA_INFO_CLASS_PATH ";", - jobjs.cam_info.m_get_info); + "(I)L" PJ_CAMERA_INFO_CLASS_PATH ";", + jobjs.cam_info.m_get_info); GET_FIELD_ID(jobjs.cam_info.cls, PJ_CAMERA_INFO, "facing", "I", - jobjs.cam_info.f_facing); + jobjs.cam_info.f_facing); GET_FIELD_ID(jobjs.cam_info.cls, PJ_CAMERA_INFO, "orient", "I", - jobjs.cam_info.f_orient); + jobjs.cam_info.f_orient); GET_FIELD_ID(jobjs.cam_info.cls, PJ_CAMERA_INFO, "supportedSize", "[I", - jobjs.cam_info.f_sup_size); + jobjs.cam_info.f_sup_size); GET_FIELD_ID(jobjs.cam_info.cls, PJ_CAMERA_INFO, "supportedFormat", "[I", - jobjs.cam_info.f_sup_fmt); + jobjs.cam_info.f_sup_fmt); GET_FIELD_ID(jobjs.cam_info.cls, PJ_CAMERA_INFO, "supportedFps1000", "[I", - jobjs.cam_info.f_sup_fps); + jobjs.cam_info.f_sup_fps); #undef GET_CLASS_ID #undef GET_METHOD_ID @@ -368,15 +367,15 @@ static pj_status_t jni_init_ids() /* Register native function */ { #if USE_CAMERA2 - JNINativeMethod m = { "PushFrame2", "(JLjava/nio/ByteBuffer;IILjava/nio/ByteBuffer;IILjava/nio/ByteBuffer;II)V", (void*)&OnGetFrame2 }; + JNINativeMethod m = { "PushFrame2", "(JLjava/nio/ByteBuffer;IILjava/nio/ByteBuffer;IILjava/nio/ByteBuffer;II)V", (void*)&OnGetFrame2 }; #else - JNINativeMethod m = { "PushFrame", "([BIJ)V", (void*)&OnGetFrame }; + JNINativeMethod m = { "PushFrame", "([BIJ)V", (void*)&OnGetFrame }; #endif - if ((*jni_env)->RegisterNatives(jni_env, jobjs.cam.cls, &m, 1)) { - PJ_LOG(3, (THIS_FILE, "[JNI] Failed in registering native " - "function 'OnGetFrame()'")); - status = PJMEDIA_EVID_SYSERR; - } + if ((*jni_env)->RegisterNatives(jni_env, jobjs.cam.cls, &m, 1)) { + PJ_LOG(3, (THIS_FILE, "[JNI] Failed in registering native " + "function 'OnGetFrame()'")); + status = PJMEDIA_EVID_SYSERR; + } } on_return: @@ -391,13 +390,13 @@ static void jni_deinit_ids() pj_bool_t with_attach = jni_get_env(&jni_env); if (jobjs.cam.cls) { - (*jni_env)->DeleteGlobalRef(jni_env, jobjs.cam.cls); - jobjs.cam.cls = NULL; + (*jni_env)->DeleteGlobalRef(jni_env, jobjs.cam.cls); + jobjs.cam.cls = NULL; } if (jobjs.cam_info.cls) { - (*jni_env)->DeleteGlobalRef(jni_env, jobjs.cam_info.cls); - jobjs.cam_info.cls = NULL; + (*jni_env)->DeleteGlobalRef(jni_env, jobjs.cam_info.cls); + jobjs.cam_info.cls = NULL; } jni_detach_env(with_attach); @@ -457,11 +456,11 @@ static pj_status_t and_factory_init(pjmedia_vid_dev_factory *ff) status = jni_init_ids(); if (status != PJ_SUCCESS) - return status; + return status; status = and_factory_refresh(ff); if (status != PJ_SUCCESS) - return status; + return status; return PJ_SUCCESS; } @@ -498,7 +497,7 @@ static pj_status_t and_factory_refresh(pjmedia_vid_dev_factory *ff) /* dev_count = PjCameraInfo::GetCameraCount() */ dev_count = (*jni_env)->CallStaticIntMethod(jni_env, jobjs.cam_info.cls, - jobjs.cam_info.m_get_cnt); + jobjs.cam_info.m_get_cnt); if (dev_count < 0) { PJ_LOG(3, (THIS_FILE, "Failed to get camera count")); status = PJMEDIA_EVID_SYSERR; @@ -507,212 +506,212 @@ static pj_status_t and_factory_refresh(pjmedia_vid_dev_factory *ff) /* Start querying device info */ f->dev_info = (and_dev_info*) - pj_pool_calloc(f->dev_pool, dev_count, - sizeof(and_dev_info)); + pj_pool_calloc(f->dev_pool, dev_count, + sizeof(and_dev_info)); for (i = 0; i < dev_count; i++) { - and_dev_info *adi = &f->dev_info[f->dev_count]; - pjmedia_vid_dev_info *vdi = &adi->info; + and_dev_info *adi = &f->dev_info[f->dev_count]; + pjmedia_vid_dev_info *vdi = &adi->info; jobject jdev_info; - jobject jtmp; - int facing, max_fmt_cnt = PJMEDIA_VID_DEV_INFO_FMT_CNT; - - /* jdev_info = PjCameraInfo::GetCameraInfo(i) */ - jdev_info = (*jni_env)->CallStaticObjectMethod( - jni_env, - jobjs.cam_info.cls, - jobjs.cam_info.m_get_info, - i); - if (jdev_info == NULL) - continue; - - /* Get camera facing: 0=back 1=front */ - facing = (*jni_env)->GetIntField(jni_env, jdev_info, - jobjs.cam_info.f_facing); - if (facing < 0) - goto on_skip_dev; - - /* Set device ID, direction, and has_callback info */ - adi->dev_idx = i; - vdi->id = f->dev_count; - vdi->dir = PJMEDIA_DIR_CAPTURE; - vdi->has_callback = PJ_TRUE; - vdi->caps = PJMEDIA_VID_DEV_CAP_SWITCH | - PJMEDIA_VID_DEV_CAP_ORIENTATION; - - /* Set driver & name info */ - pj_ansi_strncpy(vdi->driver, "Android", sizeof(vdi->driver)); - adi->facing = facing; - if (facing == 0) { - pj_ansi_strncpy(vdi->name, "Back camera", sizeof(vdi->name)); - } else { - pj_ansi_strncpy(vdi->name, "Front camera", sizeof(vdi->name)); - } - - /* Get supported sizes */ - jtmp = (*jni_env)->GetObjectField(jni_env, jdev_info, - jobjs.cam_info.f_sup_size); - if (jtmp) { - jintArray jiarray = (jintArray*)jtmp; - jint *sizes; - jsize cnt, j; - - cnt = (*jni_env)->GetArrayLength(jni_env, jiarray); - sizes = (*jni_env)->GetIntArrayElements(jni_env, jiarray, 0); - - adi->sup_size_cnt = cnt/2; - adi->sup_size = pj_pool_calloc(f->dev_pool, adi->sup_size_cnt, - sizeof(adi->sup_size[0])); - for (j = 0; j < adi->sup_size_cnt; j++) { - adi->sup_size[j].w = sizes[j*2]; - adi->sup_size[j].h = sizes[j*2+1]; - } - (*jni_env)->ReleaseIntArrayElements(jni_env, jiarray, sizes, 0); - (*jni_env)->DeleteLocalRef(jni_env, jtmp); - } else { - goto on_skip_dev; - } - - /* Get supported formats */ - jtmp = (*jni_env)->GetObjectField(jni_env, jdev_info, - jobjs.cam_info.f_sup_fmt); - if (jtmp) { - jintArray jiarray = (jintArray*)jtmp; - jint *fmts; - jsize cnt, j; - pj_bool_t has_i420 = PJ_FALSE; - int k; - - cnt = (*jni_env)->GetArrayLength(jni_env, jiarray); - fmts = (*jni_env)->GetIntArrayElements(jni_env, jiarray, 0); - for (j = 0; j < cnt; j++) { - pjmedia_format_id fmt = and_fmt_to_pj((pj_uint32_t)fmts[j]); - - /* Make sure we recognize this format */ - if (fmt == 0) - continue; - - /* Check formats for I420 conversion */ - if (fmt == PJMEDIA_FORMAT_I420) has_i420 = PJ_TRUE; - else if (fmt == PJMEDIA_FORMAT_YV12) adi->has_yv12 = PJ_TRUE; - else if (fmt == PJMEDIA_FORMAT_NV21) adi->has_nv21 = PJ_TRUE; - } - (*jni_env)->ReleaseIntArrayElements(jni_env, jiarray, fmts, - JNI_ABORT); - (*jni_env)->DeleteLocalRef(jni_env, jtmp); - - /* Always put I420/IYUV and in the first place, for better - * compatibility. - */ - adi->forced_i420 = !has_i420; - for (k = 0; k < adi->sup_size_cnt && - vdi->fmt_cnt < max_fmt_cnt-1; k++) - { - /* Landscape video */ - pjmedia_format_init_video(&vdi->fmt[vdi->fmt_cnt++], - PJMEDIA_FORMAT_I420, - adi->sup_size[k].w, - adi->sup_size[k].h, - DEFAULT_FPS, 1); - /* Portrait video */ - pjmedia_format_init_video(&vdi->fmt[vdi->fmt_cnt++], - PJMEDIA_FORMAT_I420, - adi->sup_size[k].h, - adi->sup_size[k].w, - DEFAULT_FPS, 1); - } + jobject jtmp; + int facing, max_fmt_cnt = PJMEDIA_VID_DEV_INFO_FMT_CNT; + + /* jdev_info = PjCameraInfo::GetCameraInfo(i) */ + jdev_info = (*jni_env)->CallStaticObjectMethod( + jni_env, + jobjs.cam_info.cls, + jobjs.cam_info.m_get_info, + i); + if (jdev_info == NULL) + continue; + + /* Get camera facing: 0=back 1=front */ + facing = (*jni_env)->GetIntField(jni_env, jdev_info, + jobjs.cam_info.f_facing); + if (facing < 0) + goto on_skip_dev; + + /* Set device ID, direction, and has_callback info */ + adi->dev_idx = i; + vdi->id = f->dev_count; + vdi->dir = PJMEDIA_DIR_CAPTURE; + vdi->has_callback = PJ_TRUE; + vdi->caps = PJMEDIA_VID_DEV_CAP_SWITCH | + PJMEDIA_VID_DEV_CAP_ORIENTATION; + + /* Set driver & name info */ + pj_ansi_strncpy(vdi->driver, "Android", sizeof(vdi->driver)); + adi->facing = facing; + if (facing == 0) { + pj_ansi_strncpy(vdi->name, "Back camera", sizeof(vdi->name)); + } else { + pj_ansi_strncpy(vdi->name, "Front camera", sizeof(vdi->name)); + } + + /* Get supported sizes */ + jtmp = (*jni_env)->GetObjectField(jni_env, jdev_info, + jobjs.cam_info.f_sup_size); + if (jtmp) { + jintArray jiarray = (jintArray*)jtmp; + jint *sizes; + jsize cnt, j; + + cnt = (*jni_env)->GetArrayLength(jni_env, jiarray); + sizes = (*jni_env)->GetIntArrayElements(jni_env, jiarray, 0); + + adi->sup_size_cnt = cnt/2; + adi->sup_size = pj_pool_calloc(f->dev_pool, adi->sup_size_cnt, + sizeof(adi->sup_size[0])); + for (j = 0; j < adi->sup_size_cnt; j++) { + adi->sup_size[j].w = sizes[j*2]; + adi->sup_size[j].h = sizes[j*2+1]; + } + (*jni_env)->ReleaseIntArrayElements(jni_env, jiarray, sizes, 0); + (*jni_env)->DeleteLocalRef(jni_env, jtmp); + } else { + goto on_skip_dev; + } + + /* Get supported formats */ + jtmp = (*jni_env)->GetObjectField(jni_env, jdev_info, + jobjs.cam_info.f_sup_fmt); + if (jtmp) { + jintArray jiarray = (jintArray*)jtmp; + jint *fmts; + jsize cnt, j; + pj_bool_t has_i420 = PJ_FALSE; + int k; + + cnt = (*jni_env)->GetArrayLength(jni_env, jiarray); + fmts = (*jni_env)->GetIntArrayElements(jni_env, jiarray, 0); + for (j = 0; j < cnt; j++) { + pjmedia_format_id fmt = and_fmt_to_pj((pj_uint32_t)fmts[j]); + + /* Make sure we recognize this format */ + if (fmt == 0) + continue; + + /* Check formats for I420 conversion */ + if (fmt == PJMEDIA_FORMAT_I420) has_i420 = PJ_TRUE; + else if (fmt == PJMEDIA_FORMAT_YV12) adi->has_yv12 = PJ_TRUE; + else if (fmt == PJMEDIA_FORMAT_NV21) adi->has_nv21 = PJ_TRUE; + } + (*jni_env)->ReleaseIntArrayElements(jni_env, jiarray, fmts, + JNI_ABORT); + (*jni_env)->DeleteLocalRef(jni_env, jtmp); + + /* Always put I420/IYUV and in the first place, for better + * compatibility. + */ + adi->forced_i420 = !has_i420; + for (k = 0; k < adi->sup_size_cnt && + vdi->fmt_cnt < max_fmt_cnt-1; k++) + { + /* Landscape video */ + pjmedia_format_init_video(&vdi->fmt[vdi->fmt_cnt++], + PJMEDIA_FORMAT_I420, + adi->sup_size[k].w, + adi->sup_size[k].h, + DEFAULT_FPS, 1); + /* Portrait video */ + pjmedia_format_init_video(&vdi->fmt[vdi->fmt_cnt++], + PJMEDIA_FORMAT_I420, + adi->sup_size[k].h, + adi->sup_size[k].w, + DEFAULT_FPS, 1); + } /* Camera2 supports only I420 for now */ #if !USE_CAMERA2 - /* YV12 */ - if (adi->has_yv12) { - for (k = 0; k < adi->sup_size_cnt && - vdi->fmt_cnt < max_fmt_cnt-1; k++) - { - /* Landscape video */ - pjmedia_format_init_video(&vdi->fmt[vdi->fmt_cnt++], - PJMEDIA_FORMAT_YV12, - adi->sup_size[k].w, - adi->sup_size[k].h, - DEFAULT_FPS, 1); - /* Portrait video */ - pjmedia_format_init_video(&vdi->fmt[vdi->fmt_cnt++], - PJMEDIA_FORMAT_YV12, - adi->sup_size[k].h, - adi->sup_size[k].w, - DEFAULT_FPS, 1); - } - } - - /* NV21 */ - if (adi->has_nv21) { - for (k = 0; k < adi->sup_size_cnt && - vdi->fmt_cnt < max_fmt_cnt-1; k++) - { - /* Landscape video */ - pjmedia_format_init_video(&vdi->fmt[vdi->fmt_cnt++], - PJMEDIA_FORMAT_NV21, - adi->sup_size[k].w, - adi->sup_size[k].h, - DEFAULT_FPS, 1); - /* Portrait video */ - pjmedia_format_init_video(&vdi->fmt[vdi->fmt_cnt++], - PJMEDIA_FORMAT_NV21, - adi->sup_size[k].h, - adi->sup_size[k].w, - DEFAULT_FPS, 1); - } - } + /* YV12 */ + if (adi->has_yv12) { + for (k = 0; k < adi->sup_size_cnt && + vdi->fmt_cnt < max_fmt_cnt-1; k++) + { + /* Landscape video */ + pjmedia_format_init_video(&vdi->fmt[vdi->fmt_cnt++], + PJMEDIA_FORMAT_YV12, + adi->sup_size[k].w, + adi->sup_size[k].h, + DEFAULT_FPS, 1); + /* Portrait video */ + pjmedia_format_init_video(&vdi->fmt[vdi->fmt_cnt++], + PJMEDIA_FORMAT_YV12, + adi->sup_size[k].h, + adi->sup_size[k].w, + DEFAULT_FPS, 1); + } + } + + /* NV21 */ + if (adi->has_nv21) { + for (k = 0; k < adi->sup_size_cnt && + vdi->fmt_cnt < max_fmt_cnt-1; k++) + { + /* Landscape video */ + pjmedia_format_init_video(&vdi->fmt[vdi->fmt_cnt++], + PJMEDIA_FORMAT_NV21, + adi->sup_size[k].w, + adi->sup_size[k].h, + DEFAULT_FPS, 1); + /* Portrait video */ + pjmedia_format_init_video(&vdi->fmt[vdi->fmt_cnt++], + PJMEDIA_FORMAT_NV21, + adi->sup_size[k].h, + adi->sup_size[k].w, + DEFAULT_FPS, 1); + } + } #endif - - } else { - goto on_skip_dev; - } - - /* If this is front camera, set it as first/default (if not yet) */ - if (facing == 1) { - if (!found_front && f->dev_count > 0) { - /* Swap this front cam info with one whose idx==0 */ - and_dev_info tmp_adi; - pj_memcpy(&tmp_adi, &f->dev_info[0], sizeof(tmp_adi)); - pj_memcpy(&f->dev_info[0], adi, sizeof(tmp_adi)); - pj_memcpy(adi, &tmp_adi, sizeof(tmp_adi)); - f->dev_info[0].info.id = 0; - f->dev_info[f->dev_count].info.id = f->dev_count; - } - found_front = PJ_TRUE; - } - - f->dev_count++; + + } else { + goto on_skip_dev; + } + + /* If this is front camera, set it as first/default (if not yet) */ + if (facing == 1) { + if (!found_front && f->dev_count > 0) { + /* Swap this front cam info with one whose idx==0 */ + and_dev_info tmp_adi; + pj_memcpy(&tmp_adi, &f->dev_info[0], sizeof(tmp_adi)); + pj_memcpy(&f->dev_info[0], adi, sizeof(tmp_adi)); + pj_memcpy(adi, &tmp_adi, sizeof(tmp_adi)); + f->dev_info[0].info.id = 0; + f->dev_info[f->dev_count].info.id = f->dev_count; + } + found_front = PJ_TRUE; + } + + f->dev_count++; on_skip_dev: - (*jni_env)->DeleteLocalRef(jni_env, jdev_info); + (*jni_env)->DeleteLocalRef(jni_env, jdev_info); } PJ_LOG(4, (THIS_FILE, - "Android video capture initialized with %d device(s):", - f->dev_count)); + "Android video capture initialized with %d device(s):", + f->dev_count)); for (i = 0; i < f->dev_count; i++) { - and_dev_info *adi = &f->dev_info[i]; - char tmp_str[2048], *p; - int j, plen, slen; - PJ_LOG(4, (THIS_FILE, "%2d: %s", i, f->dev_info[i].info.name)); - - /* Print supported formats */ - p = tmp_str; - plen = sizeof(tmp_str); - for (j = 0; j < adi->info.fmt_cnt; j++) { - char tmp_str2[5]; - const pjmedia_video_format_detail *vfd = - pjmedia_format_get_video_format_detail(&adi->info.fmt[j], 0); - pjmedia_fourcc_name(adi->info.fmt[j].id, tmp_str2); - slen = pj_ansi_snprintf(p, plen, "%s/%dx%d ", - tmp_str2, vfd->size.w, vfd->size.h); - if (slen < 0 || slen >= plen) break; - plen -= slen; - p += slen; - } - PJ_LOG(4, (THIS_FILE, " supported format = %s", tmp_str)); + and_dev_info *adi = &f->dev_info[i]; + char tmp_str[2048], *p; + int j, plen, slen; + PJ_LOG(4, (THIS_FILE, "%2d: %s", i, f->dev_info[i].info.name)); + + /* Print supported formats */ + p = tmp_str; + plen = sizeof(tmp_str); + for (j = 0; j < adi->info.fmt_cnt; j++) { + char tmp_str2[5]; + const pjmedia_video_format_detail *vfd = + pjmedia_format_get_video_format_detail(&adi->info.fmt[j], 0); + pjmedia_fourcc_name(adi->info.fmt[j].id, tmp_str2); + slen = pj_ansi_snprintf(p, plen, "%s/%dx%d ", + tmp_str2, vfd->size.w, vfd->size.h); + if (slen < 0 || slen >= plen) break; + plen -= slen; + p += slen; + } + PJ_LOG(4, (THIS_FILE, " supported format = %s", tmp_str)); } on_return: @@ -731,8 +730,8 @@ static unsigned and_factory_get_dev_count(pjmedia_vid_dev_factory *ff) /* API: get device info */ static pj_status_t and_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info) + unsigned index, + pjmedia_vid_dev_info *info) { and_factory *cf = (and_factory*)f; @@ -747,8 +746,8 @@ static pj_status_t and_factory_get_dev_info(pjmedia_vid_dev_factory *f, /* API: create default device parameter */ static pj_status_t and_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param) + unsigned index, + pjmedia_vid_dev_param *param) { and_factory *cf = (and_factory*)f; and_dev_info *di = &cf->dev_info[index]; @@ -771,11 +770,11 @@ static pj_status_t and_factory_default_param(pj_pool_t *pool, /* API: create stream */ static pj_status_t and_factory_create_stream( - pjmedia_vid_dev_factory *ff, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm) + pjmedia_vid_dev_factory *ff, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm) { and_factory *f = (and_factory*)ff; pj_pool_t *pool; @@ -794,9 +793,9 @@ static pj_status_t and_factory_create_stream( PJ_ASSERT_RETURN(f && param && p_vid_strm, PJ_EINVAL); PJ_ASSERT_RETURN(param->fmt.type == PJMEDIA_TYPE_VIDEO && - param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && + param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && param->dir == PJMEDIA_DIR_CAPTURE, - PJ_EINVAL); + PJ_EINVAL); /* Camera2 supports only I420 for now */ #if USE_CAMERA2 @@ -810,17 +809,17 @@ static pj_status_t and_factory_create_stream( vfi = pjmedia_get_video_format_info(NULL, param->fmt.id); if (param->fmt.id == PJMEDIA_FORMAT_I420 && adi->forced_i420) { - /* Not really support I420, need to convert it from YV12/NV21 */ - if (adi->has_nv21) { - and_fmt = pj_fmt_to_and(PJMEDIA_FORMAT_NV21); - convert_to_i420 = 1; - } else if (adi->has_yv12) { - and_fmt = pj_fmt_to_and(PJMEDIA_FORMAT_YV12); - convert_to_i420 = 2; - } else - pj_assert(!"Bug!"); + /* Not really support I420, need to convert it from YV12/NV21 */ + if (adi->has_nv21) { + and_fmt = pj_fmt_to_and(PJMEDIA_FORMAT_NV21); + convert_to_i420 = 1; + } else if (adi->has_yv12) { + and_fmt = pj_fmt_to_and(PJMEDIA_FORMAT_YV12); + convert_to_i420 = 2; + } else + pj_assert(!"Bug!"); } else { - and_fmt = pj_fmt_to_and(param->fmt.id); + and_fmt = pj_fmt_to_and(param->fmt.id); } if (!vfi || !and_fmt) return PJMEDIA_EVID_BADFORMAT; @@ -849,9 +848,9 @@ static pj_status_t and_factory_create_stream( * we should always check and conversion buffer may be needed. */ if (USE_CAMERA2 || convert_to_i420) { - pj_assert(vfi->plane_cnt > 1); - strm->convert_to_i420 = convert_to_i420; - strm->convert_buf = pj_pool_alloc(pool, vafp.plane_bytes[1]); + pj_assert(vfi->plane_cnt > 1); + strm->convert_to_i420 = convert_to_i420; + strm->convert_buf = pj_pool_alloc(pool, vafp.plane_bytes[1]); } /* Native preview */ @@ -864,30 +863,30 @@ static pj_status_t and_factory_create_stream( strm->cam_size.w = (vfd->size.w > vfd->size.h? vfd->size.w: vfd->size.h); strm->cam_size.h = (vfd->size.w > vfd->size.h? vfd->size.h: vfd->size.w); jcam = (*jni_env)->NewObject(jni_env, jobjs.cam.cls, jobjs.cam.m_init, - adi->dev_idx, /* idx */ - strm->cam_size.w, /* w */ - strm->cam_size.h, /* h */ - and_fmt, /* fmt */ + adi->dev_idx, /* idx */ + strm->cam_size.w, /* w */ + strm->cam_size.h, /* h */ + and_fmt, /* fmt */ #if USE_CAMERA2 - vfd->fps.num/ + vfd->fps.num/ #else - vfd->fps.num*1000/ + vfd->fps.num*1000/ #endif - vfd->fps.denum, /* fps */ - (jlong)(intptr_t)strm, /* user data */ - NULL /* SurfaceView */ - ); + vfd->fps.denum, /* fps */ + (jlong)(intptr_t)strm, /* user data */ + NULL /* SurfaceView */ + ); if (jcam == NULL) { PJ_LOG(3, (THIS_FILE, "Unable to create PjCamera instance")); status = PJMEDIA_EVID_SYSERR; - goto on_return; + goto on_return; } strm->jcam = (jobject)(*jni_env)->NewGlobalRef(jni_env, jcam); (*jni_env)->DeleteLocalRef(jni_env, jcam); if (strm->jcam == NULL) { PJ_LOG(3, (THIS_FILE, "Unable to create global ref to PjCamera")); status = PJMEDIA_EVID_SYSERR; - goto on_return; + goto on_return; } /* Video orientation. @@ -898,9 +897,9 @@ static pj_status_t and_factory_create_stream( (vfd->size.h > vfd->size.w)) { if (param->orient == PJMEDIA_ORIENT_UNKNOWN) - param->orient = PJMEDIA_ORIENT_NATURAL; + param->orient = PJMEDIA_ORIENT_NATURAL; and_stream_set_cap(&strm->base, PJMEDIA_VID_DEV_CAP_ORIENTATION, - ¶m->orient); + ¶m->orient); } on_return: @@ -908,8 +907,8 @@ static pj_status_t and_factory_create_stream( /* Success */ if (status == PJ_SUCCESS) { - strm->base.op = &stream_op; - *p_vid_strm = &strm->base; + strm->base.op = &stream_op; + *p_vid_strm = &strm->base; } return status; @@ -975,43 +974,43 @@ static pj_status_t and_stream_set_cap(pjmedia_vid_dev_stream *s, PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); switch (cap) { - case PJMEDIA_VID_DEV_CAP_SWITCH: - { - pjmedia_vid_dev_switch_param *p = (pjmedia_vid_dev_switch_param*) - pval; - and_dev_info *adi; - int res; + case PJMEDIA_VID_DEV_CAP_SWITCH: + { + pjmedia_vid_dev_switch_param *p = (pjmedia_vid_dev_switch_param*) + pval; + and_dev_info *adi; + int res; - /* Just return if current and target device are the same */ + /* Just return if current and target device are the same */ if (strm->param.cap_id == p->target_id) return PJ_SUCCESS; - /* Verify target capture ID */ - if (p->target_id < 0 || p->target_id >= strm->factory->dev_count) - return PJ_EINVAL; - - /* Ok, let's do the switch */ - adi = &strm->factory->dev_info[p->target_id]; - PJ_LOG(4, (THIS_FILE, "Switching camera to %s..", adi->info.name)); - - /* Call PjCamera::Start() method */ - with_attach = jni_get_env(&jni_env); - res = (*jni_env)->CallIntMethod(jni_env, strm->jcam, - jobjs.cam.m_switch, adi->dev_idx); - if (res < 0) { - PJ_LOG(3, (THIS_FILE, "Failed to switch camera (err=%d)", - res)); - status = PJMEDIA_EVID_SYSERR; - } else { - strm->param.cap_id = p->target_id; - - /* If successful, set the orientation as well */ - and_stream_set_cap(s, PJMEDIA_VID_DEV_CAP_ORIENTATION, - &strm->param.orient); - } - jni_detach_env(with_attach); - break; - } + /* Verify target capture ID */ + if (p->target_id < 0 || p->target_id >= strm->factory->dev_count) + return PJ_EINVAL; + + /* Ok, let's do the switch */ + adi = &strm->factory->dev_info[p->target_id]; + PJ_LOG(4, (THIS_FILE, "Switching camera to %s..", adi->info.name)); + + /* Call PjCamera::Start() method */ + with_attach = jni_get_env(&jni_env); + res = (*jni_env)->CallIntMethod(jni_env, strm->jcam, + jobjs.cam.m_switch, adi->dev_idx); + if (res < 0) { + PJ_LOG(3, (THIS_FILE, "Failed to switch camera (err=%d)", + res)); + status = PJMEDIA_EVID_SYSERR; + } else { + strm->param.cap_id = p->target_id; + + /* If successful, set the orientation as well */ + and_stream_set_cap(s, PJMEDIA_VID_DEV_CAP_ORIENTATION, + &strm->param.orient); + } + jni_detach_env(with_attach); + break; + } case PJMEDIA_VID_DEV_CAP_ORIENTATION: { @@ -1019,8 +1018,8 @@ static pj_status_t and_stream_set_cap(pjmedia_vid_dev_stream *s, pjmedia_orient eff_ori; and_dev_info *adi; - pj_assert(orient >= PJMEDIA_ORIENT_UNKNOWN && - orient <= PJMEDIA_ORIENT_ROTATE_270DEG); + pj_assert(orient >= PJMEDIA_ORIENT_UNKNOWN && + orient <= PJMEDIA_ORIENT_ROTATE_270DEG); if (orient == PJMEDIA_ORIENT_UNKNOWN) return PJ_EINVAL; @@ -1028,39 +1027,39 @@ static pj_status_t and_stream_set_cap(pjmedia_vid_dev_stream *s, pj_memcpy(&strm->param.orient, pval, sizeof(strm->param.orient)); - if (!strm->conv.conv) { - status = pjmedia_vid_dev_conv_create_converter( - &strm->conv, strm->pool, - &strm->param.fmt, - strm->cam_size, - strm->param.fmt.det.vid.size, - PJ_TRUE, - MAINTAIN_ASPECT_RATIO); - - if (status != PJ_SUCCESS) - return status; - } - - eff_ori = strm->param.orient; - adi = &strm->factory->dev_info[strm->param.cap_id]; - /* Normalize the orientation for back-facing camera */ - if (!adi->facing) { - if (eff_ori == PJMEDIA_ORIENT_ROTATE_90DEG) - eff_ori = PJMEDIA_ORIENT_ROTATE_270DEG; - else if (eff_ori == PJMEDIA_ORIENT_ROTATE_270DEG) - eff_ori = PJMEDIA_ORIENT_ROTATE_90DEG; - } - pjmedia_vid_dev_conv_set_rotation(&strm->conv, eff_ori); - - PJ_LOG(4, (THIS_FILE, "Video capture orientation set to %d", - strm->param.orient)); + if (!strm->conv.conv) { + status = pjmedia_vid_dev_conv_create_converter( + &strm->conv, strm->pool, + &strm->param.fmt, + strm->cam_size, + strm->param.fmt.det.vid.size, + PJ_TRUE, + MAINTAIN_ASPECT_RATIO); + + if (status != PJ_SUCCESS) + return status; + } + + eff_ori = strm->param.orient; + adi = &strm->factory->dev_info[strm->param.cap_id]; + /* Normalize the orientation for back-facing camera */ + if (!adi->facing) { + if (eff_ori == PJMEDIA_ORIENT_ROTATE_90DEG) + eff_ori = PJMEDIA_ORIENT_ROTATE_270DEG; + else if (eff_ori == PJMEDIA_ORIENT_ROTATE_270DEG) + eff_ori = PJMEDIA_ORIENT_ROTATE_90DEG; + } + pjmedia_vid_dev_conv_set_rotation(&strm->conv, eff_ori); + + PJ_LOG(4, (THIS_FILE, "Video capture orientation set to %d", + strm->param.orient)); break; } - default: - status = PJMEDIA_EVID_INVCAP; - break; + default: + status = PJMEDIA_EVID_INVCAP; + break; } return status; @@ -1133,11 +1132,11 @@ static pj_status_t and_stream_destroy(pjmedia_vid_dev_stream *s) with_attach = jni_get_env(&jni_env); if (strm->is_running) - and_stream_stop(s); + and_stream_stop(s); if (strm->jcam) { - (*jni_env)->DeleteGlobalRef(jni_env, strm->jcam); - strm->jcam = NULL; + (*jni_env)->DeleteGlobalRef(jni_env, strm->jcam); + strm->jcam = NULL; } jni_detach_env(with_attach); @@ -1145,7 +1144,7 @@ static pj_status_t and_stream_destroy(pjmedia_vid_dev_stream *s) pjmedia_vid_dev_conv_destroy_converter(&strm->conv); if (strm->pool) - pj_pool_release(strm->pool); + pj_pool_release(strm->pool); PJ_LOG(4, (THIS_FILE, "Android camera stream destroyed")); @@ -1158,17 +1157,17 @@ PJ_INLINE(void) strip_padding(void *dst, void *src, int w, int h, int stride) { int i; for (i = 0; i < h; ++i) { - pj_memmove(dst, src, w); - src += stride; - dst += w; + pj_memmove(dst, src, w); + src += stride; + dst += w; } } static void JNICALL OnGetFrame2(JNIEnv *env, jobject obj, - jlong user_data, - jobject plane0, jint rowStride0, jint pixStride0, - jobject plane1, jint rowStride1, jint pixStride1, - jobject plane2, jint rowStride2, jint pixStride2) + jlong user_data, + jobject plane0, jint rowStride0, jint pixStride0, + jobject plane1, jint rowStride1, jint pixStride1, + jobject plane2, jint rowStride2, jint pixStride2) { and_stream *strm = (and_stream*)(intptr_t)user_data; pjmedia_frame f; @@ -1179,17 +1178,17 @@ static void JNICALL OnGetFrame2(JNIEnv *env, jobject obj, strm->frame_ts.u64 += strm->ts_inc; if (!strm->vid_cb.capture_cb) - return; + return; if (strm->thread_initialized == 0 || !pj_thread_is_registered()) { - pj_status_t status; - pj_bzero(strm->thread_desc, sizeof(pj_thread_desc)); - status = pj_thread_register("and_cam", strm->thread_desc, - &strm->thread); - if (status != PJ_SUCCESS) - return; - strm->thread_initialized = 1; - PJ_LOG(5,(THIS_FILE, "Android camera thread registered")); + pj_status_t status; + pj_bzero(strm->thread_desc, sizeof(pj_thread_desc)); + status = pj_thread_register("and_cam", strm->thread_desc, + &strm->thread); + if (status != PJ_SUCCESS) + return; + strm->thread_initialized = 1; + PJ_LOG(5,(THIS_FILE, "Android camera thread registered")); } p0 = (pj_uint8_t*)(*env)->GetDirectBufferAddress(env, plane0); @@ -1231,53 +1230,53 @@ static void JNICALL OnGetFrame2(JNIEnv *env, jobject obj, /* I420 with padding, remove padding */ else if (pixStride1==1 && pixStride2==1 && p2 > p1 && p1 > p0) { - /* Strip out Y padding */ - if (rowStride0 > strm->cam_size.w) { - strip_padding(Y, p0, strm->cam_size.w, strm->cam_size.h, - rowStride0); - } - - /* Get U & V planes */ - - if (rowStride1 == strm->cam_size.w/2) { - /* No padding, simply bulk memmove U & V */ - pj_memmove(U, p1, strm->vafp.plane_bytes[1]); - pj_memmove(V, p2, strm->vafp.plane_bytes[2]); - } else if (rowStride1 > strm->cam_size.w/2) { - /* Strip padding */ - strip_padding(U, p1, strm->cam_size.w/2, strm->cam_size.h/2, - rowStride1); - strip_padding(V, p2, strm->cam_size.w/2, strm->cam_size.h/2, - rowStride2); - } + /* Strip out Y padding */ + if (rowStride0 > strm->cam_size.w) { + strip_padding(Y, p0, strm->cam_size.w, strm->cam_size.h, + rowStride0); + } + + /* Get U & V planes */ + + if (rowStride1 == strm->cam_size.w/2) { + /* No padding, simply bulk memmove U & V */ + pj_memmove(U, p1, strm->vafp.plane_bytes[1]); + pj_memmove(V, p2, strm->vafp.plane_bytes[2]); + } else if (rowStride1 > strm->cam_size.w/2) { + /* Strip padding */ + strip_padding(U, p1, strm->cam_size.w/2, strm->cam_size.h/2, + rowStride1); + strip_padding(V, p2, strm->cam_size.w/2, strm->cam_size.h/2, + rowStride2); + } } /* The buffer may be originally NV21, i.e: V/U is interleaved */ else if (p1-p2==1 && pixStride0==1 && pixStride1==2 && pixStride2==2) { - /* Strip out Y padding */ - if (rowStride0 > strm->cam_size.w) { - strip_padding(Y, p0, strm->cam_size.w, strm->cam_size.h, - rowStride0); - } - - /* Get U & V, and strip if needed */ - { - pj_uint8_t *src = p2; - pj_uint8_t *dst_u = U; - pj_uint8_t *dst_v = strm->convert_buf; - int diff = rowStride1 - strm->cam_size.w; - int i; - for (i = 0; i < strm->cam_size.h/2; ++i) { - int j; - for (j = 0; j < strm->cam_size.w/2; ++j) { - *dst_v++ = *src++; - *dst_u++ = *src++; - } - src += diff; /* stripping any padding */ - } - pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[2]); - } + /* Strip out Y padding */ + if (rowStride0 > strm->cam_size.w) { + strip_padding(Y, p0, strm->cam_size.w, strm->cam_size.h, + rowStride0); + } + + /* Get U & V, and strip if needed */ + { + pj_uint8_t *src = p2; + pj_uint8_t *dst_u = U; + pj_uint8_t *dst_v = strm->convert_buf; + int diff = rowStride1 - strm->cam_size.w; + int i; + for (i = 0; i < strm->cam_size.h/2; ++i) { + int j; + for (j = 0; j < strm->cam_size.w/2; ++j) { + *dst_v++ = *src++; + *dst_u++ = *src++; + } + src += diff; /* stripping any padding */ + } + pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[2]); + } } /* The buffer may be originally YV12, i.e: U & V planes are swapped. @@ -1285,89 +1284,89 @@ static void JNICALL OnGetFrame2(JNIEnv *env, jobject obj, */ else if (pixStride1==1 && pixStride2==1 && p1 > p2 && p2 > p0) { - /* Strip out Y padding */ - if (rowStride0 > strm->cam_size.w) { - strip_padding(Y, p0, strm->cam_size.w, strm->cam_size.h, - rowStride0); - } + /* Strip out Y padding */ + if (rowStride0 > strm->cam_size.w) { + strip_padding(Y, p0, strm->cam_size.w, strm->cam_size.h, + rowStride0); + } - /* Swap U & V planes */ - if (rowStride1 == strm->cam_size.w/2) { + /* Swap U & V planes */ + if (rowStride1 == strm->cam_size.w/2) { - /* No padding, note Y plane should be no padding too! */ - pj_assert(rowStride0 == strm->cam_size.w); - pj_memcpy(strm->convert_buf, p1, strm->vafp.plane_bytes[1]); - pj_memmove(U, p1, strm->vafp.plane_bytes[1]); - pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[1]); + /* No padding, note Y plane should be no padding too! */ + pj_assert(rowStride0 == strm->cam_size.w); + pj_memcpy(strm->convert_buf, p1, strm->vafp.plane_bytes[1]); + pj_memmove(U, p1, strm->vafp.plane_bytes[1]); + pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[1]); - } else if (rowStride1 > strm->cam_size.w/2) { + } else if (rowStride1 > strm->cam_size.w/2) { - /* Strip padding */ - strip_padding(strm->convert_buf, p1, strm->cam_size.w/2, - strm->cam_size.h/2, rowStride1); - strip_padding(V, p2, strm->cam_size.w/2, strm->cam_size.h/2, - rowStride2); + /* Strip padding */ + strip_padding(strm->convert_buf, p1, strm->cam_size.w/2, + strm->cam_size.h/2, rowStride1); + strip_padding(V, p2, strm->cam_size.w/2, strm->cam_size.h/2, + rowStride2); - /* Get V plane data from conversion buffer */ - pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[2]); + /* Get V plane data from conversion buffer */ + pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[2]); - } + } } /* Else, let's just print log for now */ else { - jlong p0_len, p1_len, p2_len; + jlong p0_len, p1_len, p2_len; - p0_len = (*env)->GetDirectBufferCapacity(env, plane0); - p1_len = (*env)->GetDirectBufferCapacity(env, plane1); - p2_len = (*env)->GetDirectBufferCapacity(env, plane2); + p0_len = (*env)->GetDirectBufferCapacity(env, plane0); + p1_len = (*env)->GetDirectBufferCapacity(env, plane1); + p2_len = (*env)->GetDirectBufferCapacity(env, plane2); - PJ_LOG(1,(THIS_FILE, "Unrecognized image format from Android camera2, " - "please report the following plane format:")); - PJ_LOG(1,(THIS_FILE, " Planes (buf/len/row_stride/pix_stride):" - " p0=%p/%d/%d/%d p1=%p/%d/%d/%d p2=%p/%d/%d/%d", - p0, p0_len, rowStride0, pixStride0, - p1, p1_len, rowStride1, pixStride1, - p2, p2_len, rowStride2, pixStride2)); + PJ_LOG(1,(THIS_FILE, "Unrecognized image format from Android camera2, " + "please report the following plane format:")); + PJ_LOG(1,(THIS_FILE, " Planes (buf/len/row_stride/pix_stride):" + " p0=%p/%d/%d/%d p1=%p/%d/%d/%d p2=%p/%d/%d/%d", + p0, p0_len, rowStride0, pixStride0, + p1, p1_len, rowStride1, pixStride1, + p2, p2_len, rowStride2, pixStride2)); #if 1 - /* Generic converter to I420, based on row stride & pixel stride */ - - /* Strip out Y padding */ - if (rowStride0 > strm->cam_size.w) { - strip_padding(Y, p0, strm->cam_size.w, strm->cam_size.h, - rowStride0); - } - - /* Get U & V, and strip if needed */ - { - pj_uint8_t *src_u = p1; - pj_uint8_t *src_v = p2; - pj_uint8_t *dst_u = U; - pj_uint8_t *dst_v = strm->convert_buf; - int i; - - /* Note, we use convert buffer for V, just in case U & V are - * swapped. - */ - for (i = 0; i < strm->cam_size.h/2; ++i) { - int j; - for (j = 0; j < strm->cam_size.w/2; ++j) { - *dst_v++ = *(src_v + j*pixStride2); - *dst_u++ = *(src_u + j*pixStride1); - } - src_u += rowStride1; - src_v += rowStride2; - } - pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[2]); - } + /* Generic converter to I420, based on row stride & pixel stride */ + + /* Strip out Y padding */ + if (rowStride0 > strm->cam_size.w) { + strip_padding(Y, p0, strm->cam_size.w, strm->cam_size.h, + rowStride0); + } + + /* Get U & V, and strip if needed */ + { + pj_uint8_t *src_u = p1; + pj_uint8_t *src_v = p2; + pj_uint8_t *dst_u = U; + pj_uint8_t *dst_v = strm->convert_buf; + int i; + + /* Note, we use convert buffer for V, just in case U & V are + * swapped. + */ + for (i = 0; i < strm->cam_size.h/2; ++i) { + int j; + for (j = 0; j < strm->cam_size.w/2; ++j) { + *dst_v++ = *(src_v + j*pixStride2); + *dst_u++ = *(src_u + j*pixStride1); + } + src_u += rowStride1; + src_v += rowStride2; + } + pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[2]); + } #endif } status = pjmedia_vid_dev_conv_resize_and_rotate(&strm->conv, - f.buf, - &frame_buf); + f.buf, + &frame_buf); if (status == PJ_SUCCESS) { f.buf = frame_buf; } @@ -1379,7 +1378,7 @@ static void JNICALL OnGetFrame2(JNIEnv *env, jobject obj, static void JNICALL OnGetFrame(JNIEnv *env, jobject obj, jbyteArray data, jint length, - jlong user_data) + jlong user_data) { and_stream *strm = (and_stream*)(intptr_t)user_data; pjmedia_frame f; @@ -1389,17 +1388,17 @@ static void JNICALL OnGetFrame(JNIEnv *env, jobject obj, strm->frame_ts.u64 += strm->ts_inc; if (!strm->vid_cb.capture_cb) - return; + return; if (strm->thread_initialized == 0 || !pj_thread_is_registered()) { - pj_status_t status; - pj_bzero(strm->thread_desc, sizeof(pj_thread_desc)); - status = pj_thread_register("and_cam", strm->thread_desc, - &strm->thread); - if (status != PJ_SUCCESS) - return; - strm->thread_initialized = 1; - PJ_LOG(5,(THIS_FILE, "Android camera thread registered")); + pj_status_t status; + pj_bzero(strm->thread_desc, sizeof(pj_thread_desc)); + status = pj_thread_register("and_cam", strm->thread_desc, + &strm->thread); + if (status != PJ_SUCCESS) + return; + strm->thread_initialized = 1; + PJ_LOG(5,(THIS_FILE, "Android camera thread registered")); } f.type = PJMEDIA_FRAME_TYPE_VIDEO; @@ -1415,76 +1414,76 @@ static void JNICALL OnGetFrame(JNIEnv *env, jobject obj, * into U & V planes. */ if (strm->convert_to_i420 == 1) { - pj_uint8_t *src = U; - pj_uint8_t *dst_u = U; - pj_uint8_t *end_u = U + strm->vafp.plane_bytes[1]; - pj_uint8_t *dst_v = strm->convert_buf; - while (dst_u < end_u) { - *dst_v++ = *src++; - *dst_u++ = *src++; - } - pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[2]); + pj_uint8_t *src = U; + pj_uint8_t *dst_u = U; + pj_uint8_t *end_u = U + strm->vafp.plane_bytes[1]; + pj_uint8_t *dst_v = strm->convert_buf; + while (dst_u < end_u) { + *dst_v++ = *src++; + *dst_u++ = *src++; + } + pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[2]); } /* Convert YV12 -> I420, i.e: swap U & V planes. We also need to * strip out padding, if any. */ else if (strm->convert_to_i420 == 2) { - int y_stride = ALIGN16(strm->vafp.size.w); - int uv_stride = ALIGN16(strm->vafp.size.w/2); - - /* Strip out Y padding */ - if (y_stride > strm->vafp.size.w) { - int i; - pj_uint8_t *src = Y + y_stride; - pj_uint8_t *dst = Y + strm->vafp.size.w; - - for (i = 1; i < strm->vafp.size.h; ++i) { - memmove(dst, src, strm->vafp.size.w); - src += y_stride; - dst += strm->vafp.size.w; - } - } - - /* Swap U & V planes */ - if (uv_stride == strm->vafp.size.w/2) { - - /* No padding, note Y plane should be no padding too! */ - pj_assert(y_stride == strm->vafp.size.w); - pj_memcpy(strm->convert_buf, U, strm->vafp.plane_bytes[1]); - pj_memmove(U, V, strm->vafp.plane_bytes[1]); - pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[1]); - - } else if (uv_stride > strm->vafp.size.w/2) { - - /* Strip & copy V plane into conversion buffer */ - pj_uint8_t *src = Y + y_stride*strm->vafp.size.h; - pj_uint8_t *dst = strm->convert_buf; - unsigned dst_stride = strm->vafp.size.w/2; - int i; - for (i = 0; i < strm->vafp.size.h/2; ++i) { - memmove(dst, src, dst_stride); - src += uv_stride; - dst += dst_stride; - } - - /* Strip U plane */ - dst = U; - for (i = 0; i < strm->vafp.size.h/2; ++i) { - memmove(dst, src, dst_stride); - src += uv_stride; - dst += dst_stride; - } - - /* Get V plane data from conversion buffer */ - pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[2]); - - } + int y_stride = ALIGN16(strm->vafp.size.w); + int uv_stride = ALIGN16(strm->vafp.size.w/2); + + /* Strip out Y padding */ + if (y_stride > strm->vafp.size.w) { + int i; + pj_uint8_t *src = Y + y_stride; + pj_uint8_t *dst = Y + strm->vafp.size.w; + + for (i = 1; i < strm->vafp.size.h; ++i) { + memmove(dst, src, strm->vafp.size.w); + src += y_stride; + dst += strm->vafp.size.w; + } + } + + /* Swap U & V planes */ + if (uv_stride == strm->vafp.size.w/2) { + + /* No padding, note Y plane should be no padding too! */ + pj_assert(y_stride == strm->vafp.size.w); + pj_memcpy(strm->convert_buf, U, strm->vafp.plane_bytes[1]); + pj_memmove(U, V, strm->vafp.plane_bytes[1]); + pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[1]); + + } else if (uv_stride > strm->vafp.size.w/2) { + + /* Strip & copy V plane into conversion buffer */ + pj_uint8_t *src = Y + y_stride*strm->vafp.size.h; + pj_uint8_t *dst = strm->convert_buf; + unsigned dst_stride = strm->vafp.size.w/2; + int i; + for (i = 0; i < strm->vafp.size.h/2; ++i) { + memmove(dst, src, dst_stride); + src += uv_stride; + dst += dst_stride; + } + + /* Strip U plane */ + dst = U; + for (i = 0; i < strm->vafp.size.h/2; ++i) { + memmove(dst, src, dst_stride); + src += uv_stride; + dst += dst_stride; + } + + /* Get V plane data from conversion buffer */ + pj_memcpy(V, strm->convert_buf, strm->vafp.plane_bytes[2]); + + } } status = pjmedia_vid_dev_conv_resize_and_rotate(&strm->conv, - f.buf, - &frame_buf); + f.buf, + &frame_buf); if (status == PJ_SUCCESS) { f.buf = frame_buf; } @@ -1495,4 +1494,4 @@ static void JNICALL OnGetFrame(JNIEnv *env, jobject obj, #endif /* USE_CAMERA2 */ -#endif /* PJMEDIA_VIDEO_DEV_HAS_ANDROID */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_ANDROID */ diff --git a/pjmedia/src/pjmedia-videodev/android_opengl.c b/pjmedia/src/pjmedia-videodev/android_opengl.c index a13c9ab46a..53075627cc 100644 --- a/pjmedia/src/pjmedia-videodev/android_opengl.c +++ b/pjmedia/src/pjmedia-videodev/android_opengl.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013-2014 Teluu Inc. (http://www.teluu.com) * @@ -32,7 +31,7 @@ #include #include -#define THIS_FILE "android_opengl.cpp" +#define THIS_FILE "android_opengl.cpp" #define MAX_JOBS 1 /* Define the number of errors before the stream stops trying to do rendering. @@ -75,12 +74,12 @@ typedef struct job_queue { /* Video stream. */ struct andgl_stream { - pjmedia_vid_dev_stream base; /**< Base stream */ - pjmedia_vid_dev_param param; /**< Settings */ - pj_pool_t *pool; /**< Memory pool */ + pjmedia_vid_dev_stream base; /**< Base stream */ + pjmedia_vid_dev_param param; /**< Settings */ + pj_pool_t *pool; /**< Memory pool */ - pjmedia_vid_dev_cb vid_cb; /**< Stream callback */ - void *user_data; /**< Application data */ + pjmedia_vid_dev_cb vid_cb; /**< Stream callback */ + void *user_data; /**< Application data */ pj_timestamp frame_ts; unsigned ts_inc; @@ -88,14 +87,14 @@ struct andgl_stream job_queue *jq; pj_bool_t is_running; - pj_int32_t err_rend; + pj_int32_t err_rend; const pjmedia_frame *frame; gl_buffers *gl_buf; - EGLDisplay display; - EGLSurface surface; - EGLContext context; - ANativeWindow *window; + EGLDisplay display; + EGLSurface surface; + EGLContext context; + ANativeWindow *window; }; @@ -120,8 +119,8 @@ static pj_status_t deinit_opengl(void * data); /* Job queue prototypes */ static pj_status_t job_queue_create(pj_pool_t *pool, job_queue **pjq); static pj_status_t job_queue_post_job(job_queue *jq, job_func_ptr func, - void *data, unsigned flags, - pj_status_t *retval); + void *data, unsigned flags, + pj_status_t *retval); static pj_status_t job_queue_destroy(job_queue *jq); /* Operations */ @@ -158,7 +157,7 @@ static andgl_fmt_info* get_andgl_format_info(pjmedia_format_id id) { \ PJ_LOG(3, (THIS_FILE, "Unable to %s %d", str, eglGetError())); \ status = PJMEDIA_EVID_SYSERR; \ - goto on_return; \ + goto on_return; \ } static pj_status_t init_opengl(void * data) @@ -168,7 +167,7 @@ static pj_status_t init_opengl(void * data) { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, - EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 8, EGL_NONE + EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 8, EGL_NONE }; EGLint context_attr[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; EGLConfig config; @@ -180,13 +179,13 @@ static pj_status_t init_opengl(void * data) strm->display = eglGetDisplay(EGL_DEFAULT_DISPLAY); if (strm->display == EGL_NO_DISPLAY || - !eglInitialize(strm->display, NULL, NULL)) + !eglInitialize(strm->display, NULL, NULL)) { EGL_ERR("initialize OpenGL display"); } if (!eglChooseConfig(strm->display, attr, &config, 1, &numConfigs) || - (!eglGetConfigAttrib(strm->display, config, EGL_NATIVE_VISUAL_ID, + (!eglGetConfigAttrib(strm->display, config, EGL_NATIVE_VISUAL_ID, &format))) { EGL_ERR("configure OpenGL display"); @@ -228,7 +227,7 @@ static pj_status_t init_opengl(void * data) on_return: if (status != PJ_SUCCESS) - deinit_opengl(strm); + deinit_opengl(strm); return status; } @@ -240,7 +239,7 @@ static pj_status_t render(void * data) struct andgl_stream *stream = (struct andgl_stream *)data; if (stream->display == EGL_NO_DISPLAY || stream->err_rend == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; pjmedia_vid_dev_opengl_draw(stream->gl_buf, stream->vid_size.w, stream->vid_size.h, stream->frame->buf); @@ -250,8 +249,8 @@ static pj_status_t render(void * data) stream->err_rend--; if (stream->err_rend == 0) { PJ_LOG(3, (THIS_FILE, "Stopping OpenGL rendering due to " - "consecutive errors. If app is in bg," - "it's advisable to stop the stream.")); + "consecutive errors. If app is in bg," + "it's advisable to stop the stream.")); } } return eglGetError(); @@ -320,13 +319,13 @@ pjmedia_vid_dev_opengl_imp_create_stream(pj_pool_t *pool, if (param->flags & PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW) { status = andgl_stream_set_cap(&strm->base, - PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW, - ¶m->window); + PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW, + ¶m->window); } if (status != PJ_SUCCESS) { PJ_LOG(3, (THIS_FILE, "Failed to initialize OpenGL with the specified" - " output window")); + " output window")); goto on_error; } @@ -379,7 +378,7 @@ static pj_status_t andgl_stream_get_cap(pjmedia_vid_dev_stream *s, wnd->info.android.window = strm->window; return PJ_SUCCESS; } else { - return PJMEDIA_EVID_INVCAP; + return PJMEDIA_EVID_INVCAP; } } @@ -419,13 +418,13 @@ static pj_status_t andgl_stream_set_cap(pjmedia_vid_dev_stream *s, pj_memcpy(&strm->vid_size, &vfd->size, sizeof(vfd->size)); pj_memcpy(&strm->param.disp_size, &vfd->size, sizeof(vfd->size)); - if (strm->window) - job_queue_post_job(strm->jq, init_opengl, strm, 0, &status); - - PJ_PERROR(4,(THIS_FILE, status, - "Re-initializing OpenGL due to format change")); - return status; - + if (strm->window) + job_queue_post_job(strm->jq, init_opengl, strm, 0, &status); + + PJ_PERROR(4,(THIS_FILE, status, + "Re-initializing OpenGL due to format change")); + return status; + } else if (cap == PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW) { pj_status_t status = PJ_SUCCESS; pjmedia_vid_dev_hwnd *wnd = (pjmedia_vid_dev_hwnd *)pval; @@ -445,8 +444,8 @@ static pj_status_t andgl_stream_set_cap(pjmedia_vid_dev_stream *s, } PJ_PERROR(4,(THIS_FILE, status, - "Re-initializing OpenGL with native window %p", - strm->window)); + "Re-initializing OpenGL with native window %p", + strm->window)); return status; } @@ -477,10 +476,10 @@ static pj_status_t andgl_stream_put_frame(pjmedia_vid_dev_stream *strm, * or keep-alive, this port doesn't need any, just ignore. */ if (frame->size==0 || frame->buf==NULL) - return PJ_SUCCESS; - + return PJ_SUCCESS; + if (!stream->is_running || stream->display == EGL_NO_DISPLAY) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; stream->frame = frame; job_queue_post_job(stream->jq, render, strm, 0, &status); @@ -533,7 +532,7 @@ static int job_thread(void * data) while (1) { job *jb; - /* Wait until there is a job. */ + /* Wait until there is a job. */ pj_sem_wait(jq->sem); /* Make sure there is no pending jobs before we quit. */ @@ -584,8 +583,8 @@ static pj_status_t job_queue_create(pj_pool_t *pool, job_queue **pjq) } static pj_status_t job_queue_post_job(job_queue *jq, job_func_ptr func, - void *data, unsigned flags, - pj_status_t *retval) + void *data, unsigned flags, + pj_status_t *retval) { job jb; int tail; @@ -643,4 +642,4 @@ static pj_status_t job_queue_destroy(job_queue *jq) return PJ_SUCCESS; } -#endif /* PJMEDIA_VIDEO_DEV_HAS_ANDROID_OPENGL */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_ANDROID_OPENGL */ diff --git a/pjmedia/src/pjmedia-videodev/avi_dev.c b/pjmedia/src/pjmedia-videodev/avi_dev.c index df2eea3d88..9ddd52803f 100644 --- a/pjmedia/src/pjmedia-videodev/avi_dev.c +++ b/pjmedia/src/pjmedia-videodev/avi_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -27,26 +26,26 @@ #if defined(PJMEDIA_VIDEO_DEV_HAS_AVI) && PJMEDIA_VIDEO_DEV_HAS_AVI != 0 && \ defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -#define THIS_FILE "avi_dev.c" -#define DRIVER_NAME "AVIDev" -#define DEFAULT_CLOCK_RATE 90000 -#define DEFAULT_WIDTH 640 -#define DEFAULT_HEIGHT 480 -#define DEFAULT_FPS 25 +#define THIS_FILE "avi_dev.c" +#define DRIVER_NAME "AVIDev" +#define DEFAULT_CLOCK_RATE 90000 +#define DEFAULT_WIDTH 640 +#define DEFAULT_HEIGHT 480 +#define DEFAULT_FPS 25 typedef struct avi_dev_strm avi_dev_strm; /* avi_ device info */ struct avi_dev_info { - pjmedia_vid_dev_info info; + pjmedia_vid_dev_info info; - pj_pool_t *pool; - pj_str_t fpath; - pj_str_t title; - pjmedia_avi_streams *avi; + pj_pool_t *pool; + pj_str_t fpath; + pj_str_t title; + pjmedia_avi_streams *avi; pjmedia_port *vid; - avi_dev_strm *strm; + avi_dev_strm *strm; pjmedia_vid_codec *codec; pj_uint8_t *enc_buf; pj_size_t enc_buf_size; @@ -55,24 +54,24 @@ struct avi_dev_info /* avi_ factory */ struct avi_factory { - pjmedia_vid_dev_factory base; - pj_pool_t *pool; - pj_pool_factory *pf; + pjmedia_vid_dev_factory base; + pj_pool_t *pool; + pj_pool_factory *pf; - unsigned dev_count; - struct avi_dev_info *dev_info; + unsigned dev_count; + struct avi_dev_info *dev_info; }; /* Video stream. */ struct avi_dev_strm { - pjmedia_vid_dev_stream base; /**< Base stream */ - pjmedia_vid_dev_param param; /**< Settings */ - pj_pool_t *pool; /**< Memory pool. */ - struct avi_dev_info *adi; + pjmedia_vid_dev_stream base; /**< Base stream */ + pjmedia_vid_dev_param param; /**< Settings */ + pj_pool_t *pool; /**< Memory pool. */ + struct avi_dev_info *adi; - pjmedia_vid_dev_cb vid_cb; /**< Stream callback. */ - void *user_data; /**< Application data. */ + pjmedia_vid_dev_cb vid_cb; /**< Stream callback. */ + void *user_data; /**< Application data. */ }; @@ -82,27 +81,27 @@ static pj_status_t avi_factory_destroy(pjmedia_vid_dev_factory *f); static pj_status_t avi_factory_refresh(pjmedia_vid_dev_factory *f); static unsigned avi_factory_get_dev_count(pjmedia_vid_dev_factory *f); static pj_status_t avi_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info); + unsigned index, + pjmedia_vid_dev_info *info); static pj_status_t avi_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param); + unsigned index, + pjmedia_vid_dev_param *param); static pj_status_t avi_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm); + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm); static pj_status_t avi_dev_strm_get_param(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_param *param); + pjmedia_vid_dev_param *param); static pj_status_t avi_dev_strm_get_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - void *value); + pjmedia_vid_dev_cap cap, + void *value); static pj_status_t avi_dev_strm_set_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - const void *value); + pjmedia_vid_dev_cap cap, + const void *value); static pj_status_t avi_dev_strm_get_frame(pjmedia_vid_dev_stream *strm, pjmedia_frame *frame); static pj_status_t avi_dev_strm_start(pjmedia_vid_dev_stream *strm); @@ -142,9 +141,9 @@ static pjmedia_vid_dev_stream_op stream_op = /* API */ PJ_DEF(pj_status_t) pjmedia_avi_dev_create_factory( - pj_pool_factory *pf, - unsigned max_dev, - pjmedia_vid_dev_factory **p_ret) + pj_pool_factory *pf, + unsigned max_dev, + pjmedia_vid_dev_factory **p_ret) { struct avi_factory *cf; pj_pool_t *pool; @@ -158,19 +157,19 @@ PJ_DEF(pj_status_t) pjmedia_avi_dev_create_factory( cf->base.op = &factory_op; cf->dev_info = (struct avi_dev_info*) - pj_pool_calloc(cf->pool, cf->dev_count, - sizeof(struct avi_dev_info)); + pj_pool_calloc(cf->pool, cf->dev_count, + sizeof(struct avi_dev_info)); if (p_ret) { - *p_ret = &cf->base; + *p_ret = &cf->base; } status = pjmedia_vid_register_factory(NULL, &cf->base); if (status != PJ_SUCCESS) - return status; + return status; PJ_LOG(4, (THIS_FILE, "AVI dev factory created with %d virtual device(s)", - cf->dev_count)); + cf->dev_count)); return PJ_SUCCESS; } @@ -182,7 +181,7 @@ static pj_status_t avi_factory_init(pjmedia_vid_dev_factory *f) unsigned i; for (i=0; idev_count; ++i) { - reset_dev_info(&cf->dev_info[i]); + reset_dev_info(&cf->dev_info[i]); } return PJ_SUCCESS; @@ -214,8 +213,8 @@ static unsigned avi_factory_get_dev_count(pjmedia_vid_dev_factory *f) /* API: get device info */ static pj_status_t avi_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info) + unsigned index, + pjmedia_vid_dev_info *info) { struct avi_factory *cf = (struct avi_factory*)f; @@ -229,8 +228,8 @@ static pj_status_t avi_factory_get_dev_info(pjmedia_vid_dev_factory *f, /* API: create default device parameter */ static pj_status_t avi_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param) + unsigned index, + pjmedia_vid_dev_param *param) { struct avi_factory *cf = (struct avi_factory*)f; struct avi_dev_info *di = &cf->dev_info[index]; @@ -255,20 +254,20 @@ static void reset_dev_info(struct avi_dev_info *adi) { /* Close avi streams */ if (adi->avi) { - unsigned i, cnt; - - cnt = pjmedia_avi_streams_get_num_streams(adi->avi); - for (i=0; iavi, i); - if (as) { - pjmedia_port *port; - port = pjmedia_avi_stream_get_port(as); - pjmedia_port_destroy(port); - } - } - adi->avi = NULL; + unsigned i, cnt; + + cnt = pjmedia_avi_streams_get_num_streams(adi->avi); + for (i=0; iavi, i); + if (as) { + pjmedia_port *port; + port = pjmedia_avi_stream_get_port(as); + pjmedia_port_destroy(port); + } + } + adi->avi = NULL; } if (adi->codec) { @@ -277,7 +276,7 @@ static void reset_dev_info(struct avi_dev_info *adi) } if (adi->pool) - pj_pool_release(adi->pool); + pj_pool_release(adi->pool); pj_bzero(adi, sizeof(*adi)); @@ -300,7 +299,7 @@ PJ_DEF(pj_status_t) pjmedia_avi_dev_free(pjmedia_vid_dev_index id) /* Lookup the factory and local device index */ status = pjmedia_vid_dev_get_local_index(id, &f, &local_idx); if (status != PJ_SUCCESS) - return status; + return status; /* The factory must be AVI factory */ PJ_ASSERT_RETURN(f->op->init == &avi_factory_init, PJMEDIA_EVID_INVDEV); @@ -312,7 +311,7 @@ PJ_DEF(pj_status_t) pjmedia_avi_dev_free(pjmedia_vid_dev_index id) /* Cannot configure if stream is running */ if (adi->strm) - return PJ_EBUSY; + return PJ_EBUSY; /* Reset */ reset_dev_info(adi); @@ -332,7 +331,7 @@ PJ_DEF(pj_status_t) pjmedia_avi_dev_get_param(pjmedia_vid_dev_index id, /* Lookup the factory and local device index */ status = pjmedia_vid_dev_get_local_index(id, &f, &local_idx); if (status != PJ_SUCCESS) - return status; + return status; /* The factory must be factory */ PJ_ASSERT_RETURN(f->op->init == &avi_factory_init, PJMEDIA_EVID_INVDEV); @@ -371,27 +370,27 @@ PJ_DEF(pj_status_t) pjmedia_avi_dev_alloc( pjmedia_vid_dev_factory *f, PJ_ASSERT_RETURN(f && p && p_id, PJ_EINVAL); if (p_id) - *p_id = PJMEDIA_VID_INVALID_DEV; + *p_id = PJMEDIA_VID_INVALID_DEV; /* Get a free dev */ for (local_idx=0; local_idxdev_count; ++local_idx) { - if (cf->dev_info[local_idx].avi == NULL) { - adi = &cf->dev_info[local_idx]; - break; - } + if (cf->dev_info[local_idx].avi == NULL) { + adi = &cf->dev_info[local_idx]; + break; + } } if (!adi) - return PJ_ETOOMANY; + return PJ_ETOOMANY; /* Convert local ID to global id */ status = pjmedia_vid_dev_get_global_index(&cf->base, local_idx, &id); if (status != PJ_SUCCESS) - return status; + return status; /* Reset */ if (adi->pool) { - pj_pool_release(adi->pool); + pj_pool_release(adi->pool); } pj_bzero(adi, sizeof(*adi)); @@ -405,16 +404,16 @@ PJ_DEF(pj_status_t) pjmedia_avi_dev_alloc( pjmedia_vid_dev_factory *f, status = pjmedia_avi_player_create_streams(adi->pool, adi->fpath.ptr, 0, &adi->avi); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } adi->vid = pjmedia_avi_streams_get_stream_by_media(adi->avi, 0, PJMEDIA_TYPE_VIDEO); if (!adi->vid) { - status = PJMEDIA_EVID_BADFORMAT; - PJ_LOG(4,(THIS_FILE, "Error: cannot find video in AVI %s", - adi->fpath.ptr)); - goto on_error; + status = PJMEDIA_EVID_BADFORMAT; + PJ_LOG(4,(THIS_FILE, "Error: cannot find video in AVI %s", + adi->fpath.ptr)); + goto on_error; } pjmedia_format_copy(&avi_fmt, &adi->vid->info.fmt); @@ -424,7 +423,7 @@ PJ_DEF(pj_status_t) pjmedia_avi_dev_alloc( pjmedia_vid_dev_factory *f, /* Yes, prepare codec */ const pjmedia_vid_codec_info *codec_info; pjmedia_vid_codec_param codec_param; - pjmedia_video_apply_fmt_param vafp; + pjmedia_video_apply_fmt_param vafp; /* Lookup codec */ status = pjmedia_vid_codec_mgr_get_codec_info2(NULL, @@ -454,34 +453,34 @@ PJ_DEF(pj_status_t) pjmedia_avi_dev_alloc( pjmedia_vid_dev_factory *f, if (status != PJ_SUCCESS) goto on_error; - /* Allocate buffer */ + /* Allocate buffer */ avi_fmt.id = codec_info->dec_fmt_id[0]; vfi = pjmedia_get_video_format_info(NULL, avi_fmt.id); - pj_bzero(&vafp, sizeof(vafp)); - vafp.size = avi_fmt.det.vid.size; - status = vfi->apply_fmt(vfi, &vafp); - if (status != PJ_SUCCESS) - goto on_error; - - adi->enc_buf = pj_pool_alloc(adi->pool, vafp.framebytes); - adi->enc_buf_size = vafp.framebytes; + pj_bzero(&vafp, sizeof(vafp)); + vafp.size = avi_fmt.det.vid.size; + status = vfi->apply_fmt(vfi, &vafp); + if (status != PJ_SUCCESS) + goto on_error; + + adi->enc_buf = pj_pool_alloc(adi->pool, vafp.framebytes); + adi->enc_buf_size = vafp.framebytes; } /* Calculate title */ if (p->title.slen) { - pj_strdup_with_null(adi->pool, &adi->title, &p->title); + pj_strdup_with_null(adi->pool, &adi->title, &p->title); } else { - char *start = p->path.ptr + p->path.slen; - pj_str_t tmp; - - while (start >= p->path.ptr) { - if (*start == '/' || *start == '\\') - break; - --start; - } - tmp.ptr = start + 1; - tmp.slen = p->path.ptr + p->path.slen - tmp.ptr; - pj_strdup_with_null(adi->pool, &adi->title, &tmp); + char *start = p->path.ptr + p->path.slen; + pj_str_t tmp; + + while (start >= p->path.ptr) { + if (*start == '/' || *start == '\\') + break; + --start; + } + tmp.ptr = start + 1; + tmp.slen = p->path.ptr + p->path.slen - tmp.ptr; + pj_strdup_with_null(adi->pool, &adi->title, &tmp); } /* Init device info */ @@ -496,10 +495,10 @@ PJ_DEF(pj_status_t) pjmedia_avi_dev_alloc( pjmedia_vid_dev_factory *f, /* Set out vars */ if (p_id) - *p_id = id; + *p_id = id; p->avi_streams = adi->avi; if (p->title.slen == 0) - p->title = adi->title; + p->title = adi->title; return PJ_SUCCESS; @@ -509,8 +508,8 @@ PJ_DEF(pj_status_t) pjmedia_avi_dev_alloc( pjmedia_vid_dev_factory *f, adi->codec = NULL; } if (adi->pool) { - pj_pool_release(adi->pool); - adi->pool = NULL; + pj_pool_release(adi->pool); + adi->pool = NULL; } pjmedia_avi_dev_free(id); return status; @@ -519,11 +518,11 @@ PJ_DEF(pj_status_t) pjmedia_avi_dev_alloc( pjmedia_vid_dev_factory *f, /* API: create stream */ static pj_status_t avi_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm) + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm) { struct avi_factory *cf = (struct avi_factory*)f; pj_pool_t *pool = NULL; @@ -532,9 +531,9 @@ static pj_status_t avi_factory_create_stream( PJ_ASSERT_RETURN(f && param && p_vid_strm, PJ_EINVAL); PJ_ASSERT_RETURN(param->fmt.type == PJMEDIA_TYPE_VIDEO && - param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && + param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && param->dir == PJMEDIA_DIR_CAPTURE, - PJ_EINVAL); + PJ_EINVAL); /* Device must have been configured with pjmedia_avi_dev_set_param() */ adi = &cf->dev_info[param->cap_id]; @@ -566,7 +565,7 @@ static pj_status_t avi_factory_create_stream( /* API: Get stream info. */ static pj_status_t avi_dev_strm_get_param(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_param *pi) + pjmedia_vid_dev_param *pi) { struct avi_dev_strm *strm = (struct avi_dev_strm*)s; @@ -579,8 +578,8 @@ static pj_status_t avi_dev_strm_get_param(pjmedia_vid_dev_stream *s, /* API: get capability */ static pj_status_t avi_dev_strm_get_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - void *pval) + pjmedia_vid_dev_cap cap, + void *pval) { struct avi_dev_strm *strm = (struct avi_dev_strm*)s; @@ -595,8 +594,8 @@ static pj_status_t avi_dev_strm_get_cap(pjmedia_vid_dev_stream *s, /* API: set capability */ static pj_status_t avi_dev_strm_set_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - const void *pval) + pjmedia_vid_dev_cap cap, + const void *pval) { struct avi_dev_strm *strm = (struct avi_dev_strm*)s; @@ -673,4 +672,4 @@ static pj_status_t avi_dev_strm_destroy(pjmedia_vid_dev_stream *strm) return PJ_SUCCESS; } -#endif /* PJMEDIA_VIDEO_DEV_HAS_AVI */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_AVI */ diff --git a/pjmedia/src/pjmedia-videodev/colorbar_dev.c b/pjmedia/src/pjmedia-videodev/colorbar_dev.c index e1245898a8..16753a4c7f 100644 --- a/pjmedia/src/pjmedia-videodev/colorbar_dev.c +++ b/pjmedia/src/pjmedia-videodev/colorbar_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -29,28 +28,28 @@ PJMEDIA_VIDEO_DEV_HAS_CBAR_SRC != 0 -#define THIS_FILE "colorbar_dev.c" -#define DEFAULT_CLOCK_RATE 90000 -#define DEFAULT_WIDTH 352 //640 -#define DEFAULT_HEIGHT 288 //480 -#define DEFAULT_FPS 25 +#define THIS_FILE "colorbar_dev.c" +#define DEFAULT_CLOCK_RATE 90000 +#define DEFAULT_WIDTH 352 //640 +#define DEFAULT_HEIGHT 288 //480 +#define DEFAULT_FPS 25 /* cbar_ device info */ struct cbar_dev_info { - pjmedia_vid_dev_info info; + pjmedia_vid_dev_info info; }; /* cbar_ factory */ struct cbar_factory { - pjmedia_vid_dev_factory base; - pj_pool_t *pool; - pj_pool_factory *pf; + pjmedia_vid_dev_factory base; + pj_pool_t *pool; + pj_pool_factory *pf; - unsigned dev_count; - struct cbar_dev_info *dev_info; + unsigned dev_count; + struct cbar_dev_info *dev_info; }; struct cbar_fmt_info { @@ -87,23 +86,23 @@ static struct cbar_fmt_info cbar_fmts[] = /* Video stream. */ struct cbar_stream { - pjmedia_vid_dev_stream base; /**< Base stream */ - pjmedia_vid_dev_param param; /**< Settings */ - pj_pool_t *pool; /**< Memory pool. */ + pjmedia_vid_dev_stream base; /**< Base stream */ + pjmedia_vid_dev_param param; /**< Settings */ + pj_pool_t *pool; /**< Memory pool. */ - pjmedia_vid_dev_cb vid_cb; /**< Stream callback. */ - void *user_data; /**< Application data. */ + pjmedia_vid_dev_cb vid_cb; /**< Stream callback. */ + void *user_data; /**< Application data. */ const struct cbar_fmt_info *cbfi; const pjmedia_video_format_info *vfi; pjmedia_video_apply_fmt_param vafp; pj_uint8_t *first_line[PJMEDIA_MAX_VIDEO_PLANES]; - pj_timestamp ts; - unsigned ts_inc; + pj_timestamp ts; + unsigned ts_inc; /* For active capturer only */ - pjmedia_clock *clock; - pj_uint8_t *clock_buf; + pjmedia_clock *clock; + pj_uint8_t *clock_buf; }; @@ -113,27 +112,27 @@ static pj_status_t cbar_factory_destroy(pjmedia_vid_dev_factory *f); static pj_status_t cbar_factory_refresh(pjmedia_vid_dev_factory *f); static unsigned cbar_factory_get_dev_count(pjmedia_vid_dev_factory *f); static pj_status_t cbar_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info); + unsigned index, + pjmedia_vid_dev_info *info); static pj_status_t cbar_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param); + unsigned index, + pjmedia_vid_dev_param *param); static pj_status_t cbar_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm); + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm); static pj_status_t cbar_stream_get_param(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_param *param); + pjmedia_vid_dev_param *param); static pj_status_t cbar_stream_get_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - void *value); + pjmedia_vid_dev_cap cap, + void *value); static pj_status_t cbar_stream_set_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - const void *value); + pjmedia_vid_dev_cap cap, + const void *value); static pj_status_t cbar_stream_get_frame(pjmedia_vid_dev_stream *strm, pjmedia_frame *frame); static pj_status_t cbar_stream_start(pjmedia_vid_dev_stream *strm); @@ -196,14 +195,14 @@ static pj_status_t cbar_factory_init(pjmedia_vid_dev_factory *f) cf->dev_count = 2; cf->dev_info = (struct cbar_dev_info*) - pj_pool_calloc(cf->pool, cf->dev_count, - sizeof(struct cbar_dev_info)); + pj_pool_calloc(cf->pool, cf->dev_count, + sizeof(struct cbar_dev_info)); /* Passive capturer */ ddi = &cf->dev_info[0]; pj_bzero(ddi, sizeof(*ddi)); pj_ansi_strncpy(ddi->info.name, "Colorbar generator", - sizeof(ddi->info.name)); + sizeof(ddi->info.name)); ddi->info.driver[sizeof(ddi->info.driver)-1] = '\0'; pj_ansi_strncpy(ddi->info.driver, "Colorbar", sizeof(ddi->info.driver)); ddi->info.driver[sizeof(ddi->info.driver)-1] = '\0'; @@ -215,15 +214,15 @@ static pj_status_t cbar_factory_init(pjmedia_vid_dev_factory *f) for (i = 0; i < ddi->info.fmt_cnt; i++) { pjmedia_format *fmt = &ddi->info.fmt[i]; pjmedia_format_init_video(fmt, cbar_fmts[i].fmt_id, - DEFAULT_WIDTH, DEFAULT_HEIGHT, - DEFAULT_FPS, 1); + DEFAULT_WIDTH, DEFAULT_HEIGHT, + DEFAULT_FPS, 1); } /* Active capturer */ ddi = &cf->dev_info[1]; pj_bzero(ddi, sizeof(*ddi)); pj_ansi_strncpy(ddi->info.name, "Colorbar-active", - sizeof(ddi->info.name)); + sizeof(ddi->info.name)); ddi->info.driver[sizeof(ddi->info.driver)-1] = '\0'; pj_ansi_strncpy(ddi->info.driver, "Colorbar", sizeof(ddi->info.driver)); ddi->info.driver[sizeof(ddi->info.driver)-1] = '\0'; @@ -235,14 +234,14 @@ static pj_status_t cbar_factory_init(pjmedia_vid_dev_factory *f) for (i = 0; i < ddi->info.fmt_cnt; i++) { pjmedia_format *fmt = &ddi->info.fmt[i]; pjmedia_format_init_video(fmt, cbar_fmts[i].fmt_id, - DEFAULT_WIDTH, DEFAULT_HEIGHT, - DEFAULT_FPS, 1); + DEFAULT_WIDTH, DEFAULT_HEIGHT, + DEFAULT_FPS, 1); } PJ_LOG(4, (THIS_FILE, "Colorbar video src initialized with %d device(s):", - cf->dev_count)); + cf->dev_count)); for (i = 0; i < cf->dev_count; i++) { - PJ_LOG(4, (THIS_FILE, "%2d: %s", i, cf->dev_info[i].info.name)); + PJ_LOG(4, (THIS_FILE, "%2d: %s", i, cf->dev_info[i].info.name)); } return PJ_SUCCESS; @@ -274,8 +273,8 @@ static unsigned cbar_factory_get_dev_count(pjmedia_vid_dev_factory *f) /* API: get device info */ static pj_status_t cbar_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info) + unsigned index, + pjmedia_vid_dev_info *info) { struct cbar_factory *cf = (struct cbar_factory*)f; @@ -289,8 +288,8 @@ static pj_status_t cbar_factory_get_dev_info(pjmedia_vid_dev_factory *f, /* API: create default device parameter */ static pj_status_t cbar_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param) + unsigned index, + pjmedia_vid_dev_param *param) { struct cbar_factory *cf = (struct cbar_factory*)f; struct cbar_dev_info *di = &cf->dev_info[index]; @@ -382,12 +381,12 @@ static void fill_first_line(pj_uint8_t *first_lines[], if (vfi->color_model == PJMEDIA_COLOR_MODEL_RGB) c = rgb_colors[i][j]; - else { - if (vfi->id == PJMEDIA_FORMAT_YV12 && j > 0) - c = yuv_colors[i][3-j]; - else - c = yuv_colors[i][j]; - } + else { + if (vfi->id == PJMEDIA_FORMAT_YV12 && j > 0) + c = yuv_colors[i][3-j]; + else + c = yuv_colors[i][j]; + } bar_width = vafp->strides[j]/8; p = first_lines[j] + bar_width*i; @@ -414,18 +413,18 @@ static void clock_cb(const pj_timestamp *ts, void *user_data) f.size = stream->vafp.framebytes; status = cbar_stream_get_frame(&stream->base, &f); if (status == PJ_SUCCESS) { - (*stream->vid_cb.capture_cb)(&stream->base, stream->user_data, &f); + (*stream->vid_cb.capture_cb)(&stream->base, stream->user_data, &f); } } /* API: create stream */ static pj_status_t cbar_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm) + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm) { struct cbar_factory *cf = (struct cbar_factory*)f; pj_pool_t *pool; @@ -438,9 +437,9 @@ static pj_status_t cbar_factory_create_stream( PJ_ASSERT_RETURN(f && param && p_vid_strm, PJ_EINVAL); PJ_ASSERT_RETURN(param->fmt.type == PJMEDIA_TYPE_VIDEO && - param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && + param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && param->dir == PJMEDIA_DIR_CAPTURE, - PJ_EINVAL); + PJ_EINVAL); pj_bzero(&vafp, sizeof(vafp)); @@ -477,8 +476,8 @@ static pj_status_t cbar_factory_create_stream( /* Apply the remaining settings */ /* if (param->flags & PJMEDIA_VID_DEV_CAP_INPUT_SCALE) { - cbar_stream_set_cap(&strm->base, - PJMEDIA_VID_DEV_CAP_INPUT_SCALE, + cbar_stream_set_cap(&strm->base, + PJMEDIA_VID_DEV_CAP_INPUT_SCALE, ¶m->fmt); } */ @@ -486,23 +485,23 @@ static pj_status_t cbar_factory_create_stream( /* Active role? */ if (param->cap_id == 1 && cb && cb->capture_cb) { pjmedia_clock_param clock_param; - pj_status_t status; + pj_status_t status; - /* Allocate buffer */ - strm->clock_buf = pj_pool_alloc(pool, strm->vafp.framebytes); + /* Allocate buffer */ + strm->clock_buf = pj_pool_alloc(pool, strm->vafp.framebytes); - /* Create clock */ - pj_bzero(&clock_param, sizeof(clock_param)); + /* Create clock */ + pj_bzero(&clock_param, sizeof(clock_param)); clock_param.usec_interval = PJMEDIA_PTIME(&vfd->fps); clock_param.clock_rate = param->clock_rate; status = pjmedia_clock_create2(pool, &clock_param, PJMEDIA_CLOCK_NO_HIGHEST_PRIO, &clock_cb, strm, &strm->clock); - if (status != PJ_SUCCESS) { - pj_pool_release(pool); + if (status != PJ_SUCCESS) { + pj_pool_release(pool); return status; - } + } } /* Done */ @@ -514,7 +513,7 @@ static pj_status_t cbar_factory_create_stream( /* API: Get stream info. */ static pj_status_t cbar_stream_get_param(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_param *pi) + pjmedia_vid_dev_param *pi) { struct cbar_stream *strm = (struct cbar_stream*)s; @@ -533,8 +532,8 @@ static pj_status_t cbar_stream_get_param(pjmedia_vid_dev_stream *s, /* API: get capability */ static pj_status_t cbar_stream_get_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - void *pval) + pjmedia_vid_dev_cap cap, + void *pval) { struct cbar_stream *strm = (struct cbar_stream*)s; @@ -545,16 +544,16 @@ static pj_status_t cbar_stream_get_cap(pjmedia_vid_dev_stream *s, if (cap==PJMEDIA_VID_DEV_CAP_INPUT_SCALE) { return PJMEDIA_EVID_INVCAP; -// return PJ_SUCCESS; +// return PJ_SUCCESS; } else { - return PJMEDIA_EVID_INVCAP; + return PJMEDIA_EVID_INVCAP; } } /* API: set capability */ static pj_status_t cbar_stream_set_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - const void *pval) + pjmedia_vid_dev_cap cap, + const void *pval) { struct cbar_stream *strm = (struct cbar_stream*)s; @@ -564,7 +563,7 @@ static pj_status_t cbar_stream_set_cap(pjmedia_vid_dev_stream *s, if (cap==PJMEDIA_VID_DEV_CAP_INPUT_SCALE) { - return PJ_SUCCESS; + return PJ_SUCCESS; } return PJMEDIA_EVID_INVCAP; @@ -593,7 +592,7 @@ static pj_status_t spectrum_run(struct cbar_stream *d, pj_uint8_t *p, /* blinking dot */ pj_gettimeofday(&tv); if (tv.msec < 660) { - enum { DOT_SIZE = 8 }; + enum { DOT_SIZE = 8 }; pj_uint8_t dot_clr_rgb[3] = {255, 255, 255}; pj_uint8_t dot_clr_yuv[3] = {235, 128, 128}; @@ -665,7 +664,7 @@ static pj_status_t cbar_stream_start(pjmedia_vid_dev_stream *strm) PJ_LOG(4, (THIS_FILE, "Starting cbar video stream")); if (stream->clock) - return pjmedia_clock_start(stream->clock); + return pjmedia_clock_start(stream->clock); return PJ_SUCCESS; } @@ -678,7 +677,7 @@ static pj_status_t cbar_stream_stop(pjmedia_vid_dev_stream *strm) PJ_LOG(4, (THIS_FILE, "Stopping cbar video stream")); if (stream->clock) - return pjmedia_clock_stop(stream->clock); + return pjmedia_clock_stop(stream->clock); return PJ_SUCCESS; } @@ -694,7 +693,7 @@ static pj_status_t cbar_stream_destroy(pjmedia_vid_dev_stream *strm) cbar_stream_stop(strm); if (stream->clock) - pjmedia_clock_destroy(stream->clock); + pjmedia_clock_destroy(stream->clock); stream->clock = NULL; pj_pool_release(stream->pool); @@ -702,4 +701,4 @@ static pj_status_t cbar_stream_destroy(pjmedia_vid_dev_stream *strm) return PJ_SUCCESS; } -#endif /* PJMEDIA_VIDEO_DEV_HAS_CBAR_SRC */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_CBAR_SRC */ diff --git a/pjmedia/src/pjmedia-videodev/darwin_dev.m b/pjmedia/src/pjmedia-videodev/darwin_dev.m index 2cd649d5d5..896a05eaae 100644 --- a/pjmedia/src/pjmedia-videodev/darwin_dev.m +++ b/pjmedia/src/pjmedia-videodev/darwin_dev.m @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -35,26 +34,26 @@ #import #import -#define THIS_FILE "darwin_dev.m" -#define DEFAULT_CLOCK_RATE 90000 +#define THIS_FILE "darwin_dev.m" +#define DEFAULT_CLOCK_RATE 90000 #if TARGET_OS_IPHONE - #define DEFAULT_WIDTH 352 - #define DEFAULT_HEIGHT 288 + #define DEFAULT_WIDTH 352 + #define DEFAULT_HEIGHT 288 #else - #define DEFAULT_WIDTH 1280 - #define DEFAULT_HEIGHT 720 + #define DEFAULT_WIDTH 1280 + #define DEFAULT_HEIGHT 720 #endif -#define DEFAULT_FPS 15 +#define DEFAULT_FPS 15 /* Define whether we should maintain the aspect ratio when rotating the image. * For more details, please refer to util.h. */ -#define MAINTAIN_ASPECT_RATIO PJ_TRUE +#define MAINTAIN_ASPECT_RATIO PJ_TRUE typedef struct darwin_fmt_info { pjmedia_format_id pjmedia_format; - UInt32 darwin_format; + UInt32 darwin_format; } darwin_fmt_info; static darwin_fmt_info darwin_fmts[] = @@ -94,23 +93,23 @@ /* darwin device info */ struct darwin_dev_info { - pjmedia_vid_dev_info info; + pjmedia_vid_dev_info info; AVCaptureDevice *dev; }; /* darwin factory */ struct darwin_factory { - pjmedia_vid_dev_factory base; - pj_pool_t *pool; - pj_pool_factory *pf; + pjmedia_vid_dev_factory base; + pj_pool_t *pool; + pj_pool_factory *pf; - unsigned dev_count; - struct darwin_dev_info *dev_info; + unsigned dev_count; + struct darwin_dev_info *dev_info; }; @interface VOutDelegate: NSObject - + { @public struct darwin_stream *stream; @@ -120,44 +119,44 @@ @interface VOutDelegate: NSObject /* Video stream. */ struct darwin_stream { - pjmedia_vid_dev_stream base; /**< Base stream */ - pjmedia_vid_dev_param param; /**< Settings */ - pj_pool_t *pool; /**< Memory pool */ + pjmedia_vid_dev_stream base; /**< Base stream */ + pjmedia_vid_dev_param param; /**< Settings */ + pj_pool_t *pool; /**< Memory pool */ struct darwin_factory *factory; /**< Factory */ - pjmedia_vid_dev_cb vid_cb; /**< Stream callback */ - void *user_data; /**< Application data */ + pjmedia_vid_dev_cb vid_cb; /**< Stream callback */ + void *user_data; /**< Application data */ - pjmedia_rect_size size; - unsigned bytes_per_row; - unsigned frame_size; /**< Frame size (bytes)*/ + pjmedia_rect_size size; + unsigned bytes_per_row; + unsigned frame_size; /**< Frame size (bytes)*/ pj_bool_t is_planar; - NSLock *frame_lock; + NSLock *frame_lock; void *capture_buf; - void *frame_buf; + void *frame_buf; pjmedia_vid_dev_conv conv; - pjmedia_rect_size vid_size; + pjmedia_rect_size vid_size; - AVCaptureSession *cap_session; - AVCaptureDeviceInput *dev_input; - pj_bool_t has_image; - AVCaptureVideoDataOutput *video_output; - VOutDelegate *vout_delegate; - dispatch_queue_t queue; + AVCaptureSession *cap_session; + AVCaptureDeviceInput *dev_input; + pj_bool_t has_image; + AVCaptureVideoDataOutput *video_output; + VOutDelegate *vout_delegate; + dispatch_queue_t queue; AVCaptureVideoPreviewLayer *prev_layer; - pj_bool_t is_running; + pj_bool_t is_running; #if TARGET_OS_IPHONE - pj_bool_t is_rendering; - void *render_buf; - pj_size_t render_buf_size; + pj_bool_t is_rendering; + void *render_buf; + pj_size_t render_buf_size; CGDataProviderRef render_data_provider; UIView *render_view; #endif - pj_timestamp frame_ts; - unsigned ts_inc; + pj_timestamp frame_ts; + unsigned ts_inc; }; @@ -167,32 +166,32 @@ @interface VOutDelegate: NSObject static pj_status_t darwin_factory_refresh(pjmedia_vid_dev_factory *f); static unsigned darwin_factory_get_dev_count(pjmedia_vid_dev_factory *f); static pj_status_t darwin_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info); + unsigned index, + pjmedia_vid_dev_info *info); static pj_status_t darwin_factory_default_param(pj_pool_t *pool, - pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param); + pjmedia_vid_dev_factory *f, + unsigned index, + pjmedia_vid_dev_param *param); static pj_status_t darwin_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm); + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm); static pj_status_t darwin_stream_get_param(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_param *param); + pjmedia_vid_dev_param *param); static pj_status_t darwin_stream_get_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - void *value); + pjmedia_vid_dev_cap cap, + void *value); static pj_status_t darwin_stream_set_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - const void *value); + pjmedia_vid_dev_cap cap, + const void *value); static pj_status_t darwin_stream_start(pjmedia_vid_dev_stream *strm); static pj_status_t darwin_stream_get_frame(pjmedia_vid_dev_stream *strm, pjmedia_frame *frame); static pj_status_t darwin_stream_put_frame(pjmedia_vid_dev_stream *strm, - const pjmedia_frame *frame); + const pjmedia_frame *frame); static pj_status_t darwin_stream_stop(pjmedia_vid_dev_stream *strm); static pj_status_t darwin_stream_destroy(pjmedia_vid_dev_stream *strm); @@ -297,8 +296,8 @@ static pj_status_t darwin_factory_refresh(pjmedia_vid_dev_factory *f) /* Initialize input and output devices here */ qf->dev_info = (struct darwin_dev_info*) - pj_pool_calloc(qf->pool, MAX_DEV_COUNT, - sizeof(struct darwin_dev_info)); + pj_pool_calloc(qf->pool, MAX_DEV_COUNT, + sizeof(struct darwin_dev_info)); qf->dev_count = 0; #if TARGET_OS_IPHONE @@ -314,39 +313,39 @@ static pj_status_t darwin_factory_refresh(pjmedia_vid_dev_factory *f) /* Init input device */ first_idx = qf->dev_count; if (NSClassFromString(@"AVCaptureSession")) { - NSArray *dev_list = NULL; + NSArray *dev_list = NULL; #if (TARGET_OS_IPHONE && defined(__IPHONE_10_0)) || \ (TARGET_OS_OSX && defined(__MAC_10_15)) - if (__builtin_available(macOS 10.15, iOS 10.0, *)) { - /* Starting in iOS 10 and macOS 10.15, [AVCaptureDevice devices] - * is deprecated and replaced by AVCaptureDeviceDiscoverySession. - */ - AVCaptureDeviceDiscoverySession *dds; - NSArray *dev_types = - @[AVCaptureDeviceTypeBuiltInWideAngleCamera + if (__builtin_available(macOS 10.15, iOS 10.0, *)) { + /* Starting in iOS 10 and macOS 10.15, [AVCaptureDevice devices] + * is deprecated and replaced by AVCaptureDeviceDiscoverySession. + */ + AVCaptureDeviceDiscoverySession *dds; + NSArray *dev_types = + @[AVCaptureDeviceTypeBuiltInWideAngleCamera #if TARGET_OS_OSX && defined(__MAC_10_15) - , AVCaptureDeviceTypeExternalUnknown + , AVCaptureDeviceTypeExternalUnknown #endif #if TARGET_OS_IPHONE && defined(__IPHONE_10_0) - , AVCaptureDeviceTypeBuiltInDuoCamera - , AVCaptureDeviceTypeBuiltInTelephotoCamera + , AVCaptureDeviceTypeBuiltInDuoCamera + , AVCaptureDeviceTypeBuiltInTelephotoCamera #endif - ]; + ]; - dds = [AVCaptureDeviceDiscoverySession - discoverySessionWithDeviceTypes:dev_types - mediaType:AVMediaTypeVideo - position:AVCaptureDevicePositionUnspecified]; + dds = [AVCaptureDeviceDiscoverySession + discoverySessionWithDeviceTypes:dev_types + mediaType:AVMediaTypeVideo + position:AVCaptureDevicePositionUnspecified]; - dev_list = [dds devices]; - } else { + dev_list = [dds devices]; + } else { #if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_15 - dev_list = [AVCaptureDevice devices]; + dev_list = [AVCaptureDevice devices]; #endif - } + } #else - dev_list = [AVCaptureDevice devices]; + dev_list = [AVCaptureDevice devices]; #endif for (AVCaptureDevice *device in dev_list) { @@ -371,7 +370,7 @@ static pj_status_t darwin_factory_refresh(pjmedia_vid_dev_factory *f) qdi->info.has_callback = PJ_FALSE; #if TARGET_OS_IPHONE qdi->info.caps = PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW | - PJMEDIA_VID_DEV_CAP_SWITCH; + PJMEDIA_VID_DEV_CAP_SWITCH; #endif qdi->dev = device; } @@ -386,15 +385,15 @@ static pj_status_t darwin_factory_refresh(pjmedia_vid_dev_factory *f) /* Set supported formats */ for (i = 0; i < qf->dev_count; i++) { - qdi = &qf->dev_info[i]; - qdi->info.caps |= PJMEDIA_VID_DEV_CAP_FORMAT | + qdi = &qf->dev_info[i]; + qdi->info.caps |= PJMEDIA_VID_DEV_CAP_FORMAT | PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW | PJMEDIA_VID_DEV_CAP_OUTPUT_RESIZE | PJMEDIA_VID_DEV_CAP_OUTPUT_POSITION | PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE | PJMEDIA_VID_DEV_CAP_ORIENTATION; - - for (l = 0; l < PJ_ARRAY_SIZE(darwin_fmts); l++) { + + for (l = 0; l < PJ_ARRAY_SIZE(darwin_fmts); l++) { pjmedia_format *fmt; /* Simple renderer UIView only supports BGRA */ @@ -427,25 +426,25 @@ static pj_status_t darwin_factory_refresh(pjmedia_vid_dev_factory *f) /* Landscape video */ fmt = &qdi->info.fmt[qdi->info.fmt_cnt++]; pjmedia_format_init_video(fmt, - darwin_fmts[l].pjmedia_format, + darwin_fmts[l].pjmedia_format, darwin_sizes[m].supported_size_w, darwin_sizes[m].supported_size_h, DEFAULT_FPS, 1); /* Portrait video */ fmt = &qdi->info.fmt[qdi->info.fmt_cnt++]; pjmedia_format_init_video(fmt, - darwin_fmts[l].pjmedia_format, - darwin_sizes[m].supported_size_h, - darwin_sizes[m].supported_size_w, + darwin_fmts[l].pjmedia_format, + darwin_sizes[m].supported_size_h, + darwin_sizes[m].supported_size_w, DEFAULT_FPS, 1); } } } - } + } } PJ_LOG(4, (THIS_FILE, "Darwin video initialized with %d devices:", - qf->dev_count)); + qf->dev_count)); for (i = 0; i < qf->dev_count; i++) { qdi = &qf->dev_info[i]; PJ_LOG(4, (THIS_FILE, "%2d: [%s] %s - %s", i, @@ -465,8 +464,8 @@ static unsigned darwin_factory_get_dev_count(pjmedia_vid_dev_factory *f) /* API: get device info */ static pj_status_t darwin_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info) + unsigned index, + pjmedia_vid_dev_info *info) { struct darwin_factory *qf = (struct darwin_factory*)f; @@ -479,9 +478,9 @@ static pj_status_t darwin_factory_get_dev_info(pjmedia_vid_dev_factory *f, /* API: create default device parameter */ static pj_status_t darwin_factory_default_param(pj_pool_t *pool, - pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param) + pjmedia_vid_dev_factory *f, + unsigned index, + pjmedia_vid_dev_param *param) { struct darwin_factory *qf = (struct darwin_factory*)f; struct darwin_dev_info *di; @@ -493,15 +492,15 @@ static pj_status_t darwin_factory_default_param(pj_pool_t *pool, pj_bzero(param, sizeof(*param)); if (di->info.dir & PJMEDIA_DIR_CAPTURE) { - param->dir = PJMEDIA_DIR_CAPTURE; - param->cap_id = index; - param->rend_id = PJMEDIA_VID_INVALID_DEV; + param->dir = PJMEDIA_DIR_CAPTURE; + param->cap_id = index; + param->rend_id = PJMEDIA_VID_INVALID_DEV; } else if (di->info.dir & PJMEDIA_DIR_RENDER) { - param->dir = PJMEDIA_DIR_RENDER; - param->rend_id = index; - param->cap_id = PJMEDIA_VID_INVALID_DEV; + param->dir = PJMEDIA_DIR_RENDER; + param->rend_id = index; + param->cap_id = PJMEDIA_VID_INVALID_DEV; } else { - return PJMEDIA_EVID_INVDEV; + return PJMEDIA_EVID_INVDEV; } param->flags = PJMEDIA_VID_DEV_CAP_FORMAT; @@ -555,13 +554,13 @@ - (void)session_runtime_error:(NSNotification *)notification NSError *error = notification.userInfo[AVCaptureSessionErrorKey]; PJ_LOG(3, (THIS_FILE, "Capture session runtime error: %s, %s", - [error.localizedDescription UTF8String], - [error.localizedFailureReason UTF8String])); + [error.localizedDescription UTF8String], + [error.localizedFailureReason UTF8String])); } - (void)captureOutput:(AVCaptureOutput *)captureOutput - didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer - fromConnection:(AVCaptureConnection *)connection + didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer + fromConnection:(AVCaptureConnection *)connection { CVImageBufferRef img; pj_status_t status; @@ -575,7 +574,7 @@ - (void)captureOutput:(AVCaptureOutput *)captureOutput */ if (!sampleBuffer) - return; + return; /* Get a CMSampleBuffer's Core Video image buffer for the media data */ img = CMSampleBufferGetImageBuffer(sampleBuffer); @@ -606,7 +605,7 @@ - (void)captureOutput:(AVCaptureOutput *)captureOutput if ((stream->vid_size.w > stream->vid_size.h && stride < height) || (stream->vid_size.h > stream->vid_size.w && stride > height)) { - pj_size_t w = stream->vid_size.w; + pj_size_t w = stream->vid_size.w; stream->vid_size.w = stream->vid_size.h; stream->vid_size.h = w; } @@ -634,7 +633,7 @@ - (void)captureOutput:(AVCaptureOutput *)captureOutput if (stream->vid_size.h > height) { pj_memset(Y, 16, (stream->vid_size.h - height) * - stream->vid_size.w); + stream->vid_size.w); } p = (pj_uint8_t*)CVPixelBufferGetBaseAddressOfPlane(img, 1); @@ -659,8 +658,8 @@ - (void)captureOutput:(AVCaptureOutput *)captureOutput } if (stream->vid_size.h > height) { - pj_size_t UV_size = (stream->vid_size.h - height) * - stream->vid_size.w / 4; + pj_size_t UV_size = (stream->vid_size.h - height) * + stream->vid_size.w / 4; pj_memset(U, 0x80, UV_size); pj_memset(V, 0x80, UV_size); } @@ -671,8 +670,8 @@ - (void)captureOutput:(AVCaptureOutput *)captureOutput } status = pjmedia_vid_dev_conv_resize_and_rotate(&stream->conv, - stream->capture_buf, - &frame_buf); + stream->capture_buf, + &frame_buf); if (status == PJ_SUCCESS) { stream->frame_buf = frame_buf; } @@ -691,10 +690,10 @@ static pj_status_t darwin_stream_get_frame(pjmedia_vid_dev_stream *strm, struct darwin_stream *stream = (struct darwin_stream *)strm; if (!stream->has_image) { - frame->size = 0; - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->timestamp.u64 = stream->frame_ts.u64; - return PJMEDIA_EVID_NOTREADY; + frame->size = 0; + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->timestamp.u64 = stream->frame_ts.u64; + return PJMEDIA_EVID_NOTREADY; } frame->type = PJMEDIA_FRAME_TYPE_VIDEO; @@ -732,7 +731,7 @@ static pj_status_t darwin_init_view(struct darwin_stream *strm) param->fmt.det.vid.size.h); if (param->flags & PJMEDIA_VID_DEV_CAP_OUTPUT_RESIZE) { - view_rect.size.width = param->disp_size.w; + view_rect.size.width = param->disp_size.w; view_rect.size.height = param->disp_size.h; } @@ -765,11 +764,11 @@ static pj_status_t darwin_init_view(struct darwin_stream *strm) /* API: create stream */ static pj_status_t darwin_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm) + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm) { struct darwin_factory *qf = (struct darwin_factory*)f; pj_pool_t *pool; @@ -781,10 +780,10 @@ static pj_status_t darwin_factory_create_stream( PJ_ASSERT_RETURN(f && param && p_vid_strm, PJ_EINVAL); PJ_ASSERT_RETURN(param->fmt.type == PJMEDIA_TYPE_VIDEO && - param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && + param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && (param->dir == PJMEDIA_DIR_CAPTURE || param->dir == PJMEDIA_DIR_RENDER), - PJ_EINVAL); + PJ_EINVAL); if (!(ifi = get_darwin_format_info(param->fmt.id))) return PJMEDIA_EVID_BADFORMAT; @@ -813,14 +812,14 @@ static pj_status_t darwin_factory_create_stream( if (param->dir & PJMEDIA_DIR_CAPTURE) { int i; - + /* Create capture stream here */ - strm->cap_session = [[AVCaptureSession alloc] init]; - if (!strm->cap_session) { - PJ_LOG(2, (THIS_FILE, "Unable to create AV capture session")); - status = PJ_ENOMEM; - goto on_error; - } + strm->cap_session = [[AVCaptureSession alloc] init]; + if (!strm->cap_session) { + PJ_LOG(2, (THIS_FILE, "Unable to create AV capture session")); + status = PJ_ENOMEM; + goto on_error; + } AVCaptureDevice *dev = qf->dev_info[param->cap_id].dev; for (i = PJ_ARRAY_SIZE(darwin_sizes)-1; i > 0; --i) { @@ -871,77 +870,77 @@ static pj_status_t darwin_factory_create_stream( } #endif - /* Add the video device to the session as a device input */ + /* Add the video device to the session as a device input */ NSError *error; - strm->dev_input = [AVCaptureDeviceInput - deviceInputWithDevice:dev - error: &error]; - if (error || !strm->dev_input) { - PJ_LOG(2, (THIS_FILE, "Unable to get input capture device")); - status = PJMEDIA_EVID_SYSERR; - goto on_error; - } - - if ([strm->cap_session canAddInput:strm->dev_input]) { - [strm->cap_session addInput:strm->dev_input]; - } else { - PJ_LOG(2, (THIS_FILE, "Unable to add input capture device")); - status = PJMEDIA_EVID_SYSERR; - goto on_error; - } - - strm->video_output = [[AVCaptureVideoDataOutput alloc] init]; - if (!strm->video_output) { - PJ_LOG(2, (THIS_FILE, "Unable to create AV video output")); - status = PJ_ENOMEM; - goto on_error; - } + strm->dev_input = [AVCaptureDeviceInput + deviceInputWithDevice:dev + error: &error]; + if (error || !strm->dev_input) { + PJ_LOG(2, (THIS_FILE, "Unable to get input capture device")); + status = PJMEDIA_EVID_SYSERR; + goto on_error; + } + + if ([strm->cap_session canAddInput:strm->dev_input]) { + [strm->cap_session addInput:strm->dev_input]; + } else { + PJ_LOG(2, (THIS_FILE, "Unable to add input capture device")); + status = PJMEDIA_EVID_SYSERR; + goto on_error; + } + + strm->video_output = [[AVCaptureVideoDataOutput alloc] init]; + if (!strm->video_output) { + PJ_LOG(2, (THIS_FILE, "Unable to create AV video output")); + status = PJ_ENOMEM; + goto on_error; + } - /* Configure the video output */ + /* Configure the video output */ strm->video_output.alwaysDiscardsLateVideoFrames = YES; - strm->video_output.videoSettings = - [NSDictionary dictionaryWithObjectsAndKeys: + strm->video_output.videoSettings = + [NSDictionary dictionaryWithObjectsAndKeys: #if !TARGET_OS_IPHONE - /* On Mac, we need to set the buffer's dimension - * to avoid extra padding. - */ + /* On Mac, we need to set the buffer's dimension + * to avoid extra padding. + */ [NSNumber numberWithDouble: - darwin_sizes[i].supported_size_w], + darwin_sizes[i].supported_size_w], (id)kCVPixelBufferWidthKey, [NSNumber numberWithDouble: - darwin_sizes[i].supported_size_h], + darwin_sizes[i].supported_size_h], (id)kCVPixelBufferHeightKey, #endif - [NSNumber numberWithInt:ifi->darwin_format], - kCVPixelBufferPixelFormatTypeKey, nil]; - - strm->vout_delegate = [VOutDelegate alloc]; - strm->vout_delegate->stream = strm; - strm->queue = dispatch_queue_create("vout_queue", - DISPATCH_QUEUE_SERIAL); - [strm->video_output setSampleBufferDelegate:strm->vout_delegate + [NSNumber numberWithInt:ifi->darwin_format], + kCVPixelBufferPixelFormatTypeKey, nil]; + + strm->vout_delegate = [VOutDelegate alloc]; + strm->vout_delegate->stream = strm; + strm->queue = dispatch_queue_create("vout_queue", + DISPATCH_QUEUE_SERIAL); + [strm->video_output setSampleBufferDelegate:strm->vout_delegate queue:strm->queue]; - /* Add observer to catch notification when the capture session - * fails to start running or encounters an error during runtime. - */ - [[NSNotificationCenter defaultCenter] addObserver:strm->vout_delegate - selector:@selector(session_runtime_error:) - name:AVCaptureSessionRuntimeErrorNotification - object:strm->cap_session]; + /* Add observer to catch notification when the capture session + * fails to start running or encounters an error during runtime. + */ + [[NSNotificationCenter defaultCenter] addObserver:strm->vout_delegate + selector:@selector(session_runtime_error:) + name:AVCaptureSessionRuntimeErrorNotification + object:strm->cap_session]; if ([strm->cap_session canAddOutput:strm->video_output]) { - [strm->cap_session addOutput:strm->video_output]; - } else { - PJ_LOG(2, (THIS_FILE, "Unable to add video data output")); - status = PJMEDIA_EVID_SYSERR; - goto on_error; - } - - strm->capture_buf = pj_pool_alloc(strm->pool, strm->frame_size); - strm->frame_buf = strm->capture_buf; - strm->frame_lock = [[NSLock alloc]init]; - + [strm->cap_session addOutput:strm->video_output]; + } else { + PJ_LOG(2, (THIS_FILE, "Unable to add video data output")); + status = PJMEDIA_EVID_SYSERR; + goto on_error; + } + + strm->capture_buf = pj_pool_alloc(strm->pool, strm->frame_size); + strm->frame_buf = strm->capture_buf; + strm->frame_lock = [[NSLock alloc]init]; + /* Native preview */ if (param->flags & PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW) { darwin_stream_set_cap(&strm->base, PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW, @@ -969,13 +968,13 @@ static pj_status_t darwin_factory_create_stream( darwin_init_view(strm); }); - if (!strm->vout_delegate) { - strm->vout_delegate = [VOutDelegate alloc]; - strm->vout_delegate->stream = strm; - } + if (!strm->vout_delegate) { + strm->vout_delegate = [VOutDelegate alloc]; + strm->vout_delegate->stream = strm; + } - strm->render_buf = pj_pool_alloc(pool, strm->frame_size); - strm->render_buf_size = strm->frame_size; + strm->render_buf = pj_pool_alloc(pool, strm->frame_size); + strm->render_buf_size = strm->frame_size; strm->render_data_provider = CGDataProviderCreateWithData(NULL, strm->render_buf, strm->frame_size, NULL); @@ -996,7 +995,7 @@ static pj_status_t darwin_factory_create_stream( /* API: Get stream info. */ static pj_status_t darwin_stream_get_param(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_param *pi) + pjmedia_vid_dev_param *pi) { struct darwin_stream *strm = (struct darwin_stream*)s; @@ -1009,8 +1008,8 @@ static pj_status_t darwin_stream_get_param(pjmedia_vid_dev_stream *s, /* API: get capability */ static pj_status_t darwin_stream_get_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - void *pval) + pjmedia_vid_dev_cap cap, + void *pval) { struct darwin_stream *strm = (struct darwin_stream*)s; @@ -1036,8 +1035,8 @@ static pj_status_t darwin_stream_get_cap(pjmedia_vid_dev_stream *s, /* API: set capability */ static pj_status_t darwin_stream_set_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - const void *pval) + pjmedia_vid_dev_cap cap, + const void *pval) { struct darwin_stream *strm = (struct darwin_stream*)s; @@ -1049,36 +1048,36 @@ static pj_status_t darwin_stream_set_cap(pjmedia_vid_dev_stream *s, { pj_bool_t native_preview = *((pj_bool_t *)pval); - /* Disable native preview */ + /* Disable native preview */ if (!native_preview) { - if (strm->prev_layer) { - CALayer *prev_layer = strm->prev_layer; + if (strm->prev_layer) { + CALayer *prev_layer = strm->prev_layer; dispatch_sync_on_main_queue(^{ - [prev_layer removeFromSuperlayer]; - [prev_layer release]; - }); - strm->prev_layer = nil; - PJ_LOG(4, (THIS_FILE, "Native preview deinitialized")); - } + [prev_layer removeFromSuperlayer]; + [prev_layer release]; + }); + strm->prev_layer = nil; + PJ_LOG(4, (THIS_FILE, "Native preview deinitialized")); + } return PJ_SUCCESS; } - /* Enable native preview */ + /* Enable native preview */ - /* Verify if it is already enabled */ - if (strm->prev_layer) - return PJ_SUCCESS; - - /* Verify capture session instance availability */ + /* Verify if it is already enabled */ + if (strm->prev_layer) + return PJ_SUCCESS; + + /* Verify capture session instance availability */ if (!strm->cap_session) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; #if TARGET_OS_IPHONE /* Preview layer instantiation should be in main thread! */ dispatch_sync_on_main_queue(^{ - /* Create view, if none */ - if (!strm->render_view) - darwin_init_view(strm); + /* Create view, if none */ + if (!strm->render_view) + darwin_init_view(strm); /* Create preview layer */ AVCaptureVideoPreviewLayer *prev_layer = @@ -1138,14 +1137,14 @@ static pj_status_t darwin_stream_set_cap(pjmedia_vid_dev_stream *s, /* Set the orientation as well */ darwin_stream_set_cap(s, PJMEDIA_VID_DEV_CAP_ORIENTATION, - &strm->param.orient); + &strm->param.orient); return PJ_SUCCESS; } #if TARGET_OS_IPHONE case PJMEDIA_VID_DEV_CAP_FORMAT: - { + { const pjmedia_video_format_info *vfi; pjmedia_video_format_detail *vfd; pjmedia_format *fmt = (pjmedia_format *)pval; @@ -1163,23 +1162,23 @@ static pj_status_t darwin_stream_set_cap(pjmedia_vid_dev_stream *s, pjmedia_format_copy(&strm->param.fmt, fmt); vfd = pjmedia_format_get_video_format_detail(fmt, PJ_TRUE); - pj_memcpy(&strm->size, &vfd->size, sizeof(vfd->size)); - strm->bytes_per_row = strm->size.w * vfi->bpp / 8; - strm->frame_size = strm->bytes_per_row * strm->size.h; - if (strm->render_buf_size < strm->frame_size) { + pj_memcpy(&strm->size, &vfd->size, sizeof(vfd->size)); + strm->bytes_per_row = strm->size.w * vfi->bpp / 8; + strm->frame_size = strm->bytes_per_row * strm->size.h; + if (strm->render_buf_size < strm->frame_size) { /* Realloc only when needed */ - strm->render_buf = pj_pool_alloc(strm->pool, strm->frame_size); - strm->render_buf_size = strm->frame_size; - CGDataProviderRelease(strm->render_data_provider); - strm->render_data_provider = CGDataProviderCreateWithData(NULL, - strm->render_buf, - strm->frame_size, - NULL); - } - - return PJ_SUCCESS; - } - + strm->render_buf = pj_pool_alloc(strm->pool, strm->frame_size); + strm->render_buf_size = strm->frame_size; + CGDataProviderRelease(strm->render_data_provider); + strm->render_data_provider = CGDataProviderCreateWithData(NULL, + strm->render_buf, + strm->frame_size, + NULL); + } + + return PJ_SUCCESS; + } + case PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW: { UIView *view = (UIView *)pval; @@ -1195,10 +1194,10 @@ static pj_status_t darwin_stream_set_cap(pjmedia_vid_dev_stream *s, pj_memcpy(&strm->param.disp_size, pval, sizeof(strm->param.disp_size)); dispatch_sync_on_main_queue(^{ - CGRect r = strm->render_view.bounds; - r.size = CGSizeMake(strm->param.disp_size.w, + CGRect r = strm->render_view.bounds; + r.size = CGSizeMake(strm->param.disp_size.w, strm->param.disp_size.h); - strm->render_view.bounds = r; + strm->render_view.bounds = r; if (strm->prev_layer) strm->prev_layer.frame = r; }); @@ -1232,8 +1231,8 @@ static pj_status_t darwin_stream_set_cap(pjmedia_vid_dev_stream *s, { pjmedia_orient orient = *(pjmedia_orient *)pval; - pj_assert(orient >= PJMEDIA_ORIENT_UNKNOWN && - orient <= PJMEDIA_ORIENT_ROTATE_270DEG); + pj_assert(orient >= PJMEDIA_ORIENT_UNKNOWN && + orient <= PJMEDIA_ORIENT_ROTATE_270DEG); if (orient == PJMEDIA_ORIENT_UNKNOWN) return PJ_EINVAL; @@ -1250,63 +1249,63 @@ static pj_status_t darwin_stream_set_cap(pjmedia_vid_dev_stream *s, }); #endif - return PJ_SUCCESS; + return PJ_SUCCESS; } const AVCaptureVideoOrientation cap_ori[4] = { - AVCaptureVideoOrientationLandscapeLeft, /* NATURAL */ - AVCaptureVideoOrientationPortrait, /* 90DEG */ - AVCaptureVideoOrientationLandscapeRight, /* 180DEG */ - AVCaptureVideoOrientationPortraitUpsideDown, /* 270DEG */ + AVCaptureVideoOrientationLandscapeLeft, /* NATURAL */ + AVCaptureVideoOrientationPortrait, /* 90DEG */ + AVCaptureVideoOrientationLandscapeRight, /* 180DEG */ + AVCaptureVideoOrientationPortraitUpsideDown, /* 270DEG */ }; - AVCaptureConnection *vidcon; - pj_bool_t support_ori = PJ_TRUE; - - pj_assert(strm->param.dir == PJMEDIA_DIR_CAPTURE); - - if (!strm->video_output) - return PJMEDIA_EVID_NOTREADY; - - vidcon = [strm->video_output - connectionWithMediaType:AVMediaTypeVideo]; - if ([vidcon isVideoOrientationSupported]) { - vidcon.videoOrientation = cap_ori[strm->param.orient-1]; - } else { - support_ori = PJ_FALSE; - } - - if (!strm->conv.conv) { - pj_status_t status; - pjmedia_rect_size orig_size; - - /* Original native size of device is landscape */ - orig_size.w = (strm->size.w > strm->size.h? strm->size.w : - strm->size.h); - orig_size.h = (strm->size.w > strm->size.h? strm->size.h : - strm->size.w); - - if (!support_ori) { - PJ_LOG(4, (THIS_FILE, "Native video capture orientation " - "unsupported, will use converter's " - "rotation.")); - } - - status = pjmedia_vid_dev_conv_create_converter( - &strm->conv, strm->pool, - &strm->param.fmt, - orig_size, strm->size, - (support_ori?PJ_FALSE:PJ_TRUE), - MAINTAIN_ASPECT_RATIO); - - if (status != PJ_SUCCESS) - return status; - } - - pjmedia_vid_dev_conv_set_rotation(&strm->conv, strm->param.orient); - - PJ_LOG(5, (THIS_FILE, "Video capture orientation set to %d", - strm->param.orient)); + AVCaptureConnection *vidcon; + pj_bool_t support_ori = PJ_TRUE; + + pj_assert(strm->param.dir == PJMEDIA_DIR_CAPTURE); + + if (!strm->video_output) + return PJMEDIA_EVID_NOTREADY; + + vidcon = [strm->video_output + connectionWithMediaType:AVMediaTypeVideo]; + if ([vidcon isVideoOrientationSupported]) { + vidcon.videoOrientation = cap_ori[strm->param.orient-1]; + } else { + support_ori = PJ_FALSE; + } + + if (!strm->conv.conv) { + pj_status_t status; + pjmedia_rect_size orig_size; + + /* Original native size of device is landscape */ + orig_size.w = (strm->size.w > strm->size.h? strm->size.w : + strm->size.h); + orig_size.h = (strm->size.w > strm->size.h? strm->size.h : + strm->size.w); + + if (!support_ori) { + PJ_LOG(4, (THIS_FILE, "Native video capture orientation " + "unsupported, will use converter's " + "rotation.")); + } + + status = pjmedia_vid_dev_conv_create_converter( + &strm->conv, strm->pool, + &strm->param.fmt, + orig_size, strm->size, + (support_ori?PJ_FALSE:PJ_TRUE), + MAINTAIN_ASPECT_RATIO); + + if (status != PJ_SUCCESS) + return status; + } + + pjmedia_vid_dev_conv_set_rotation(&strm->conv, strm->param.orient); + + PJ_LOG(5, (THIS_FILE, "Video capture orientation set to %d", + strm->param.orient)); return PJ_SUCCESS; } @@ -1332,14 +1331,14 @@ static pj_status_t darwin_stream_start(pjmedia_vid_dev_stream *strm) performSelectorOnMainThread:@selector(startRunning) withObject:nil waitUntilDone:YES]; - if (![stream->cap_session isRunning]) { - /* More info about the error should be reported in - * VOutDelegate::session_runtime_error() - */ - PJ_LOG(3, (THIS_FILE, "Unable to start AVFoundation capture " - "session")); - return PJ_EUNKNOWN; - } + if (![stream->cap_session isRunning]) { + /* More info about the error should be reported in + * VOutDelegate::session_runtime_error() + */ + PJ_LOG(3, (THIS_FILE, "Unable to start AVFoundation capture " + "session")); + return PJ_EUNKNOWN; + } } return PJ_SUCCESS; @@ -1348,7 +1347,7 @@ static pj_status_t darwin_stream_start(pjmedia_vid_dev_stream *strm) /* API: Put frame from stream */ static pj_status_t darwin_stream_put_frame(pjmedia_vid_dev_stream *strm, - const pjmedia_frame *frame) + const pjmedia_frame *frame) { #if TARGET_OS_IPHONE struct darwin_stream *stream = (struct darwin_stream*)strm; @@ -1357,14 +1356,14 @@ static pj_status_t darwin_stream_put_frame(pjmedia_vid_dev_stream *strm, * or keep-alive, this port doesn't need any, just ignore. */ if (frame->size==0 || frame->buf==NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; if (!stream->is_running) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; /* Prevent more than one async rendering task. */ if (stream->is_rendering) - return PJ_EIGNORED; + return PJ_EIGNORED; if (stream->frame_size >= frame->size) pj_memcpy(stream->render_buf, frame->buf, frame->size); @@ -1420,8 +1419,8 @@ static pj_status_t darwin_stream_destroy(pjmedia_vid_dev_stream *strm) stream->dev_input = nil; } [stream->cap_session removeOutput:stream->video_output]; - [stream->cap_session release]; - stream->cap_session = nil; + [stream->cap_session release]; + stream->cap_session = nil; } if (stream->video_output) { @@ -1430,22 +1429,22 @@ static pj_status_t darwin_stream_destroy(pjmedia_vid_dev_stream *strm) } if (stream->vout_delegate) { - [stream->vout_delegate release]; - stream->vout_delegate = nil; + [stream->vout_delegate release]; + stream->vout_delegate = nil; } #if TARGET_OS_IPHONE if (stream->prev_layer) { - [stream->prev_layer - performSelectorOnMainThread:@selector(removeFromSuperlayer) + [stream->prev_layer + performSelectorOnMainThread:@selector(removeFromSuperlayer) withObject:nil waitUntilDone:YES]; [stream->prev_layer release]; stream->prev_layer = nil; } if (stream->render_view) { - [stream->render_view - performSelectorOnMainThread:@selector(removeFromSuperview) + [stream->render_view + performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:YES]; [stream->render_view release]; @@ -1475,4 +1474,4 @@ static pj_status_t darwin_stream_destroy(pjmedia_vid_dev_stream *strm) return PJ_SUCCESS; } -#endif /* PJMEDIA_VIDEO_DEV_HAS_DARWIN */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_DARWIN */ diff --git a/pjmedia/src/pjmedia-videodev/dshow_dev.c b/pjmedia/src/pjmedia-videodev/dshow_dev.c index c963014da8..1b0298c17a 100644 --- a/pjmedia/src/pjmedia-videodev/dshow_dev.c +++ b/pjmedia/src/pjmedia-videodev/dshow_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -46,14 +45,14 @@ #pragma comment(lib, "Rpcrt4.lib") #pragma comment(lib, "Quartz.lib") -#define THIS_FILE "dshow_dev.c" -#define DEFAULT_CLOCK_RATE 90000 -#define DEFAULT_WIDTH 640 -#define DEFAULT_HEIGHT 480 -#define DEFAULT_FPS 25 +#define THIS_FILE "dshow_dev.c" +#define DEFAULT_CLOCK_RATE 90000 +#define DEFAULT_WIDTH 640 +#define DEFAULT_HEIGHT 480 +#define DEFAULT_FPS 25 /* Temporarily disable DirectShow renderer (VMR) */ -#define HAS_VMR 0 +#define HAS_VMR 0 typedef void (*input_callback)(void *user_data, IMediaSample *pMediaSample); typedef struct NullRenderer NullRenderer; @@ -83,39 +82,39 @@ static dshow_fmt_info dshow_fmts[] = /* dshow_ device info */ struct dshow_dev_info { - pjmedia_vid_dev_info info; - unsigned dev_id; + pjmedia_vid_dev_info info; + unsigned dev_id; WCHAR display_name[192]; }; /* dshow_ factory */ struct dshow_factory { - pjmedia_vid_dev_factory base; - pj_pool_t *pool; - pj_pool_t *dev_pool; - pj_pool_factory *pf; + pjmedia_vid_dev_factory base; + pj_pool_t *pool; + pj_pool_t *dev_pool; + pj_pool_factory *pf; - unsigned dev_count; - struct dshow_dev_info *dev_info; + unsigned dev_count; + struct dshow_dev_info *dev_info; }; /* Video stream. */ struct dshow_stream { - pjmedia_vid_dev_stream base; /**< Base stream */ - pjmedia_vid_dev_param param; /**< Settings */ - pj_pool_t *pool; /**< Memory pool. */ - - pjmedia_vid_dev_cb vid_cb; /**< Stream callback. */ - void *user_data; /**< Application data. */ - - pj_bool_t quit_flag; - pj_bool_t rend_thread_exited; - pj_bool_t cap_thread_exited; - pj_bool_t cap_thread_initialized; - pj_thread_desc cap_thread_desc; - pj_thread_t *cap_thread; + pjmedia_vid_dev_stream base; /**< Base stream */ + pjmedia_vid_dev_param param; /**< Settings */ + pj_pool_t *pool; /**< Memory pool. */ + + pjmedia_vid_dev_cb vid_cb; /**< Stream callback. */ + void *user_data; /**< Application data. */ + + pj_bool_t quit_flag; + pj_bool_t rend_thread_exited; + pj_bool_t cap_thread_exited; + pj_bool_t cap_thread_initialized; + pj_thread_desc cap_thread_desc; + pj_thread_t *cap_thread; void *frm_buf; unsigned frm_buf_size; @@ -129,8 +128,8 @@ struct dshow_stream AM_MEDIA_TYPE *mediatype; } dgraph; - pj_timestamp cap_ts; - unsigned cap_ts_inc; + pj_timestamp cap_ts; + unsigned cap_ts_inc; }; @@ -140,27 +139,27 @@ static pj_status_t dshow_factory_destroy(pjmedia_vid_dev_factory *f); static pj_status_t dshow_factory_refresh(pjmedia_vid_dev_factory *f); static unsigned dshow_factory_get_dev_count(pjmedia_vid_dev_factory *f); static pj_status_t dshow_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info); + unsigned index, + pjmedia_vid_dev_info *info); static pj_status_t dshow_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param); + unsigned index, + pjmedia_vid_dev_param *param); static pj_status_t dshow_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm); + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm); static pj_status_t dshow_stream_get_param(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_param *param); + pjmedia_vid_dev_param *param); static pj_status_t dshow_stream_get_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - void *value); + pjmedia_vid_dev_cap cap, + void *value); static pj_status_t dshow_stream_set_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - const void *value); + pjmedia_vid_dev_cap cap, + const void *value); static pj_status_t dshow_stream_start(pjmedia_vid_dev_stream *strm); static pj_status_t dshow_stream_put_frame(pjmedia_vid_dev_stream *strm, const pjmedia_frame *frame); @@ -216,18 +215,18 @@ pjmedia_vid_dev_factory* pjmedia_dshow_factory(pj_pool_factory *pf) static pj_status_t dshow_factory_init(pjmedia_vid_dev_factory *f) { HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); - if (hr == RPC_E_CHANGED_MODE) { - /* When using apartment mode, Dshow object would not be accessible from - * other thread. Take this into consideration when implementing native - * renderer using Dshow. - */ - hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); - if (FAILED(hr)) { - PJ_LOG(4,(THIS_FILE, "Failed initializing DShow: " - "COM library already initialized with " - "incompatible concurrency model")); - return PJMEDIA_EVID_INIT; - } + if (hr == RPC_E_CHANGED_MODE) { + /* When using apartment mode, Dshow object would not be accessible from + * other thread. Take this into consideration when implementing native + * renderer using Dshow. + */ + hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); + if (FAILED(hr)) { + PJ_LOG(4,(THIS_FILE, "Failed initializing DShow: " + "COM library already initialized with " + "incompatible concurrency model")); + return PJMEDIA_EVID_INIT; + } } return dshow_factory_refresh(f); @@ -251,39 +250,39 @@ static pj_status_t dshow_factory_destroy(pjmedia_vid_dev_factory *f) } static HRESULT get_cap_device(struct dshow_factory *df, - unsigned id, - IBaseFilter **filter) + unsigned id, + IBaseFilter **filter) { IBindCtx *pbc; HRESULT hr; hr = CreateBindCtx(0, &pbc); if (SUCCEEDED (hr)) { - IMoniker *moniker; - DWORD pchEaten; - - hr = MkParseDisplayName(pbc, df->dev_info[id].display_name, - &pchEaten, &moniker); - if (SUCCEEDED(hr)) { - hr = IMoniker_BindToObject(moniker, pbc, NULL, - &IID_IBaseFilter, - (LPVOID *)filter); - IMoniker_Release(moniker); - } - IBindCtx_Release(pbc); + IMoniker *moniker; + DWORD pchEaten; + + hr = MkParseDisplayName(pbc, df->dev_info[id].display_name, + &pchEaten, &moniker); + if (SUCCEEDED(hr)) { + hr = IMoniker_BindToObject(moniker, pbc, NULL, + &IID_IBaseFilter, + (LPVOID *)filter); + IMoniker_Release(moniker); + } + IBindCtx_Release(pbc); } return hr; } static void enum_dev_cap(IBaseFilter *filter, - pjmedia_dir dir, - const GUID *dshow_fmt, - AM_MEDIA_TYPE **pMediatype, + pjmedia_dir dir, + const GUID *dshow_fmt, + AM_MEDIA_TYPE **pMediatype, int width, int height, - IPin **pSrcpin, - pjmedia_vid_dev_info *vdi) + IPin **pSrcpin, + pjmedia_vid_dev_info *vdi) { IEnumPins *pEnum; AM_MEDIA_TYPE *mediatype = NULL; @@ -291,11 +290,11 @@ static void enum_dev_cap(IBaseFilter *filter, HRESULT hr; if (pSrcpin) - *pSrcpin = NULL; + *pSrcpin = NULL; hr = IBaseFilter_EnumPins(filter, &pEnum); if (SUCCEEDED(hr)) { /* Loop through all the pins. */ - IPin *pPin = NULL; + IPin *pPin = NULL; while (IEnumPins_Next(pEnum, 1, &pPin, NULL) == S_OK) { PIN_DIRECTION pindirtmp; @@ -320,7 +319,7 @@ static void enum_dev_cap(IBaseFilter *filter, &icount, &isize); for (i = 0; i < icount; i++) { - unsigned j, nformat; + unsigned j, nformat; RPC_STATUS rpcstatus, rpcstatus2; hr = IAMStreamConfig_GetStreamCaps(streamcaps, i, @@ -329,29 +328,29 @@ static void enum_dev_cap(IBaseFilter *filter, if (FAILED (hr)) continue; - nformat = (dshow_fmt? 1: - sizeof(dshow_fmts)/sizeof(dshow_fmts[0])); - for (j = 0; j < nformat; j++) { - const GUID *dshow_format = dshow_fmt; + nformat = (dshow_fmt? 1: + sizeof(dshow_fmts)/sizeof(dshow_fmts[0])); + for (j = 0; j < nformat; j++) { + const GUID *dshow_format = dshow_fmt; - if (!dshow_format) - dshow_format = dshow_fmts[j].dshow_format; - if (UuidCompare(&mediatype->subtype, - (UUID*)dshow_format, - &rpcstatus) == 0 && - rpcstatus == RPC_S_OK && - UuidCompare(&mediatype->formattype, - (UUID*)&FORMAT_VideoInfo, - &rpcstatus2) == 0 && - rpcstatus2 == RPC_S_OK) - { + if (!dshow_format) + dshow_format = dshow_fmts[j].dshow_format; + if (UuidCompare(&mediatype->subtype, + (UUID*)dshow_format, + &rpcstatus) == 0 && + rpcstatus == RPC_S_OK && + UuidCompare(&mediatype->formattype, + (UUID*)&FORMAT_VideoInfo, + &rpcstatus2) == 0 && + rpcstatus2 == RPC_S_OK) + { VIDEOINFOHEADER *vi; vi = (VIDEOINFOHEADER *)mediatype->pbFormat; if (!dshow_fmt) dshow_fmts[j].enabled = PJ_TRUE; - if (vdi && vdi->fmt_cnt < + if (vdi && vdi->fmt_cnt < PJMEDIA_VID_DEV_INFO_FMT_CNT) { unsigned fps_num=DEFAULT_FPS, fps_denum=1; @@ -368,7 +367,7 @@ static void enum_dev_cap(IBaseFilter *filter, vi->bmiHeader.biHeight, fps_num, fps_denum); } - + if (pSrcpin) { if ((width == 0 && height == 0 ) || (vi->bmiHeader.biWidth == width && @@ -376,13 +375,13 @@ static void enum_dev_cap(IBaseFilter *filter, { match_wh = PJ_TRUE; } - *pSrcpin = pPin; - *pMediatype = mediatype; - } - } - } - if (pSrcpin && *pSrcpin && match_wh) - break; + *pSrcpin = pPin; + *pMediatype = mediatype; + } + } + } + if (pSrcpin && *pSrcpin && match_wh) + break; } IAMStreamConfig_Release(streamcaps); } @@ -392,7 +391,7 @@ static void enum_dev_cap(IBaseFilter *filter, if (pSrcpin && *pSrcpin) break; IPin_Release(pPin); - } + } IEnumPins_Release(pEnum); } } @@ -429,10 +428,10 @@ static pj_status_t dshow_factory_refresh(pjmedia_vid_dev_factory *f) ICreateDevEnum_CreateClassEnumerator(dev_enum, &CLSID_VideoInputDeviceCategory, &enum_cat, 0) != S_OK) { - PJ_LOG(4,(THIS_FILE, "Windows found no video input devices")); + PJ_LOG(4,(THIS_FILE, "Windows found no video input devices")); if (dev_enum) ICreateDevEnum_Release(dev_enum); - dev_count = 0; + dev_count = 0; } else { while (IEnumMoniker_Next(enum_cat, 1, &moniker, &fetched) == S_OK) { dev_count++; @@ -442,8 +441,8 @@ static pj_status_t dshow_factory_refresh(pjmedia_vid_dev_factory *f) /* Add renderer device */ dev_count += 1; df->dev_info = (struct dshow_dev_info*) - pj_pool_calloc(df->dev_pool, dev_count, - sizeof(struct dshow_dev_info)); + pj_pool_calloc(df->dev_pool, dev_count, + sizeof(struct dshow_dev_info)); if (dev_count > 1) { IEnumMoniker_Reset(enum_cat); @@ -460,7 +459,7 @@ static pj_status_t dshow_factory_refresh(pjmedia_vid_dev_factory *f) &var_name, NULL); if (SUCCEEDED(hr) && var_name.bstrVal) { WCHAR *wszDisplayName = NULL; - IBaseFilter *filter; + IBaseFilter *filter; ddi = &df->dev_info[df->dev_count++]; pj_bzero(ddi, sizeof(*ddi)); @@ -486,12 +485,12 @@ static pj_status_t dshow_factory_refresh(pjmedia_vid_dev_factory *f) /* Set the device capabilities here */ ddi->info.caps = PJMEDIA_VID_DEV_CAP_FORMAT; - hr = get_cap_device(df, df->dev_count-1, &filter); - if (SUCCEEDED(hr)) { - ddi->info.fmt_cnt = 0; - enum_dev_cap(filter, ddi->info.dir, NULL, NULL, + hr = get_cap_device(df, df->dev_count-1, &filter); + if (SUCCEEDED(hr)) { + ddi->info.fmt_cnt = 0; + enum_dev_cap(filter, ddi->info.dir, NULL, NULL, 0, 0, NULL, &ddi->info); - } + } } VariantClear(&var_name); @@ -520,17 +519,17 @@ static pj_status_t dshow_factory_refresh(pjmedia_vid_dev_factory *f) ddi->info.fmt_cnt = 1; pjmedia_format_init_video(&ddi->info.fmt[0], dshow_fmts[0].pjmedia_format, - DEFAULT_WIDTH, DEFAULT_HEIGHT, - DEFAULT_FPS, 1); + DEFAULT_WIDTH, DEFAULT_HEIGHT, + DEFAULT_FPS, 1); #endif PJ_LOG(4, (THIS_FILE, "DShow has %d devices:", - df->dev_count)); + df->dev_count)); for (c = 0; c < df->dev_count; ++c) { - PJ_LOG(4, (THIS_FILE, " dev_id %d: %s (%s)", - c, - df->dev_info[c].info.name, - df->dev_info[c].info.dir & PJMEDIA_DIR_CAPTURE ? + PJ_LOG(4, (THIS_FILE, " dev_id %d: %s (%s)", + c, + df->dev_info[c].info.name, + df->dev_info[c].info.dir & PJMEDIA_DIR_CAPTURE ? "capture" : "render")); } @@ -546,8 +545,8 @@ static unsigned dshow_factory_get_dev_count(pjmedia_vid_dev_factory *f) /* API: get device info */ static pj_status_t dshow_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info) + unsigned index, + pjmedia_vid_dev_info *info) { struct dshow_factory *df = (struct dshow_factory*)f; @@ -561,8 +560,8 @@ static pj_status_t dshow_factory_get_dev_info(pjmedia_vid_dev_factory *f, /* API: create default device parameter */ static pj_status_t dshow_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param) + unsigned index, + pjmedia_vid_dev_param *param) { struct dshow_factory *df = (struct dshow_factory*)f; struct dshow_dev_info *di = &df->dev_info[index]; @@ -573,15 +572,15 @@ static pj_status_t dshow_factory_default_param(pj_pool_t *pool, pj_bzero(param, sizeof(*param)); if (di->info.dir & PJMEDIA_DIR_CAPTURE) { - param->dir = PJMEDIA_DIR_CAPTURE; - param->cap_id = index; - param->rend_id = PJMEDIA_VID_INVALID_DEV; + param->dir = PJMEDIA_DIR_CAPTURE; + param->cap_id = index; + param->rend_id = PJMEDIA_VID_INVALID_DEV; } else if (di->info.dir & PJMEDIA_DIR_RENDER) { - param->dir = PJMEDIA_DIR_RENDER; - param->rend_id = index; - param->cap_id = PJMEDIA_VID_INVALID_DEV; + param->dir = PJMEDIA_DIR_RENDER; + param->rend_id = index; + param->cap_id = PJMEDIA_VID_INVALID_DEV; } else { - return PJMEDIA_EVID_INVDEV; + return PJMEDIA_EVID_INVDEV; } /* Set the device capabilities here */ @@ -607,12 +606,12 @@ static void input_cb(void *user_data, IMediaSample *pMediaSample) { pj_status_t status; - status = pj_thread_register("ds_cap", strm->cap_thread_desc, - &strm->cap_thread); + status = pj_thread_register("ds_cap", strm->cap_thread_desc, + &strm->cap_thread); if (status != PJ_SUCCESS) return; - strm->cap_thread_initialized = 1; - PJ_LOG(5,(THIS_FILE, "Capture thread started")); + strm->cap_thread_initialized = 1; + PJ_LOG(5,(THIS_FILE, "Capture thread started")); } frame.type = PJMEDIA_FRAME_TYPE_VIDEO; @@ -714,8 +713,8 @@ static pj_status_t create_filter_graph(pjmedia_dir dir, } if (dir == PJMEDIA_DIR_CAPTURE) { - hr = get_cap_device(df, id, &graph->source_filter); - if (FAILED(hr)) { + hr = get_cap_device(df, id, &graph->source_filter); + if (FAILED(hr)) { goto on_error; } } else { @@ -742,7 +741,7 @@ static pj_status_t create_filter_graph(pjmedia_dir dir, IBaseFilter_EnumPins(graph->rend_filter, &pEnum); if (SUCCEEDED(hr)) { // Loop through all the pins - IPin *pPin = NULL; + IPin *pPin = NULL; while (IEnumPins_Next(pEnum, 1, &pPin, NULL) == S_OK) { PIN_DIRECTION pindirtmp; @@ -752,7 +751,7 @@ static pj_status_t create_filter_graph(pjmedia_dir dir, sinkpin = pPin; break; } - IPin_Release(pPin); + IPin_Release(pPin); } IEnumPins_Release(pEnum); } @@ -760,37 +759,37 @@ static pj_status_t create_filter_graph(pjmedia_dir dir, vfd = pjmedia_format_get_video_format_detail(&strm->param.fmt, PJ_TRUE); enum_dev_cap(graph->source_filter, dir, - get_dshow_format_info(strm->param.fmt.id)->dshow_format, - &mediatype, (use_def_size? 0: vfd->size.w), + get_dshow_format_info(strm->param.fmt.id)->dshow_format, + &mediatype, (use_def_size? 0: vfd->size.w), (use_def_size? 0: vfd->size.h), &srcpin, NULL); graph->mediatype = mediatype; if (srcpin && dir == PJMEDIA_DIR_RENDER) { - mediatype = graph->mediatype = &mtype; - - memset (mediatype, 0, sizeof(AM_MEDIA_TYPE)); - mediatype->majortype = MEDIATYPE_Video; - mediatype->subtype = *(get_dshow_format_info(strm->param.fmt.id)-> - dshow_format); - mediatype->bFixedSizeSamples = TRUE; - mediatype->bTemporalCompression = FALSE; - - vi = (VIDEOINFOHEADER *) - CoTaskMemAlloc(sizeof(VIDEOINFOHEADER)); - memset (vi, 0, sizeof(VIDEOINFOHEADER)); - mediatype->formattype = FORMAT_VideoInfo; - mediatype->cbFormat = sizeof(VIDEOINFOHEADER); - mediatype->pbFormat = (BYTE *)vi; - - vi->rcSource.bottom = vfd->size.h; - vi->rcSource.right = vfd->size.w; - vi->rcTarget.bottom = vfd->size.h; - vi->rcTarget.right = vfd->size.w; - - vi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); - vi->bmiHeader.biPlanes = 1; - vi->bmiHeader.biBitCount = vfi->bpp; - vi->bmiHeader.biCompression = strm->param.fmt.id; + mediatype = graph->mediatype = &mtype; + + memset (mediatype, 0, sizeof(AM_MEDIA_TYPE)); + mediatype->majortype = MEDIATYPE_Video; + mediatype->subtype = *(get_dshow_format_info(strm->param.fmt.id)-> + dshow_format); + mediatype->bFixedSizeSamples = TRUE; + mediatype->bTemporalCompression = FALSE; + + vi = (VIDEOINFOHEADER *) + CoTaskMemAlloc(sizeof(VIDEOINFOHEADER)); + memset (vi, 0, sizeof(VIDEOINFOHEADER)); + mediatype->formattype = FORMAT_VideoInfo; + mediatype->cbFormat = sizeof(VIDEOINFOHEADER); + mediatype->pbFormat = (BYTE *)vi; + + vi->rcSource.bottom = vfd->size.h; + vi->rcSource.right = vfd->size.w; + vi->rcTarget.bottom = vfd->size.h; + vi->rcTarget.right = vfd->size.w; + + vi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + vi->bmiHeader.biPlanes = 1; + vi->bmiHeader.biBitCount = vfi->bpp; + vi->bmiHeader.biCompression = strm->param.fmt.id; } if (!srcpin || !sinkpin || !mediatype) { @@ -806,8 +805,8 @@ static pj_status_t create_filter_graph(pjmedia_dir dir, (!use_def_fps && vfd->fps.num != 0)) { video_info->AvgTimePerFrame = (LONGLONG) (10000000 * - (double)vfd->fps.denum / - vfd->fps.num); + (double)vfd->fps.denum / + vfd->fps.num); } video_info->bmiHeader.biSizeImage = DIBSIZE(video_info->bmiHeader); mediatype->lSampleSize = DIBSIZE(video_info->bmiHeader); @@ -852,11 +851,11 @@ static pj_status_t create_filter_graph(pjmedia_dir dir, if (vi) CoTaskMemFree(vi); if (FAILED(hr)) { - char msg[80]; - if (AMGetErrorText(hr, msg, sizeof(msg))) { - PJ_LOG(4,(THIS_FILE, "Error creating filter graph: %s (hr=0x%x)", - msg, hr)); - } + char msg[80]; + if (AMGetErrorText(hr, msg, sizeof(msg))) { + PJ_LOG(4,(THIS_FILE, "Error creating filter graph: %s (hr=0x%x)", + msg, hr)); + } return PJ_EUNKNOWN; } @@ -885,11 +884,11 @@ static void destroy_filter_graph(struct dshow_stream * stream) /* API: create stream */ static pj_status_t dshow_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm) + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm) { struct dshow_factory *df = (struct dshow_factory*)f; pj_pool_t *pool; @@ -913,7 +912,7 @@ static pj_status_t dshow_factory_create_stream( strm->user_data = user_data; if (param->dir & PJMEDIA_DIR_CAPTURE) { - const pjmedia_video_format_detail *vfd; + const pjmedia_video_format_detail *vfd; /* Create capture stream here */ status = create_filter_graph(PJMEDIA_DIR_CAPTURE, param->cap_id, @@ -943,9 +942,9 @@ static pj_status_t dshow_factory_create_stream( goto on_error; pj_memcpy(param, &strm->param, sizeof(*param)); } - - vfd = pjmedia_format_get_video_format_detail(¶m->fmt, PJ_TRUE); - strm->cap_ts_inc = PJMEDIA_SPF2(param->clock_rate, &vfd->fps, 1); + + vfd = pjmedia_format_get_video_format_detail(¶m->fmt, PJ_TRUE); + strm->cap_ts_inc = PJMEDIA_SPF2(param->clock_rate, &vfd->fps, 1); } else if (param->dir & PJMEDIA_DIR_RENDER) { /* Create render stream here */ status = create_filter_graph(PJMEDIA_DIR_RENDER, param->rend_id, @@ -957,9 +956,9 @@ static pj_status_t dshow_factory_create_stream( /* Apply the remaining settings */ if (param->flags & PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW) { - dshow_stream_set_cap(&strm->base, - PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW, - ¶m->window); + dshow_stream_set_cap(&strm->base, + PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW, + ¶m->window); } /* Done */ @@ -975,7 +974,7 @@ static pj_status_t dshow_factory_create_stream( /* API: Get stream info. */ static pj_status_t dshow_stream_get_param(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_param *pi) + pjmedia_vid_dev_param *pi) { struct dshow_stream *strm = (struct dshow_stream*)s; @@ -984,7 +983,7 @@ static pj_status_t dshow_stream_get_param(pjmedia_vid_dev_stream *s, pj_memcpy(pi, &strm->param, sizeof(*pi)); if (dshow_stream_get_cap(s, PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW, - &pi->window) == PJ_SUCCESS) + &pi->window) == PJ_SUCCESS) { pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW; } @@ -994,8 +993,8 @@ static pj_status_t dshow_stream_get_param(pjmedia_vid_dev_stream *s, /* API: get capability */ static pj_status_t dshow_stream_get_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - void *pval) + pjmedia_vid_dev_cap cap, + void *pval) { struct dshow_stream *strm = (struct dshow_stream*)s; @@ -1005,17 +1004,17 @@ static pj_status_t dshow_stream_get_cap(pjmedia_vid_dev_stream *s, if (cap==PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW) { - *(unsigned*)pval = 0; - return PJ_SUCCESS; + *(unsigned*)pval = 0; + return PJ_SUCCESS; } else { - return PJMEDIA_EVID_INVCAP; + return PJMEDIA_EVID_INVCAP; } } /* API: set capability */ static pj_status_t dshow_stream_set_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - const void *pval) + pjmedia_vid_dev_cap cap, + const void *pval) { struct dshow_stream *strm = (struct dshow_stream*)s; @@ -1025,8 +1024,8 @@ static pj_status_t dshow_stream_set_cap(pjmedia_vid_dev_stream *s, if (cap==PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW) { - // set renderer's window here - return PJ_SUCCESS; + // set renderer's window here + return PJ_SUCCESS; } return PJMEDIA_EVID_INVCAP; @@ -1065,15 +1064,15 @@ static pj_status_t dshow_stream_stop(pjmedia_vid_dev_stream *strm) stream->quit_flag = PJ_TRUE; if (stream->cap_thread) { for (i=0; !stream->cap_thread_exited && i<100; ++i) - pj_thread_sleep(10); + pj_thread_sleep(10); } if (stream->param.dir & PJMEDIA_DIR_RENDER) { - for (i=0; !stream->rend_thread_exited && i<100; ++i) - pj_thread_sleep(10); + for (i=0; !stream->rend_thread_exited && i<100; ++i) + pj_thread_sleep(10); } if (stream->dgraph.media_filter) - IMediaFilter_Stop(stream->dgraph.media_filter); + IMediaFilter_Stop(stream->dgraph.media_filter); PJ_LOG(4, (THIS_FILE, "Stopping dshow video stream")); @@ -1095,4 +1094,4 @@ static pj_status_t dshow_stream_destroy(pjmedia_vid_dev_stream *strm) return PJ_SUCCESS; } -#endif /* PJMEDIA_VIDEO_DEV_HAS_DSHOW */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_DSHOW */ diff --git a/pjmedia/src/pjmedia-videodev/dshowclasses.cpp b/pjmedia/src/pjmedia-videodev/dshowclasses.cpp index 830259d84a..f1de2d349b 100644 --- a/pjmedia/src/pjmedia-videodev/dshowclasses.cpp +++ b/pjmedia/src/pjmedia-videodev/dshowclasses.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -239,4 +238,4 @@ extern "C" void SourceFilter_SetMediaType(SourceFilter *src, } -#endif /* PJMEDIA_VIDEO_DEV_HAS_DSHOW */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_DSHOW */ diff --git a/pjmedia/src/pjmedia-videodev/errno.c b/pjmedia/src/pjmedia-videodev/errno.c index ee5197a413..33a4c40bc0 100644 --- a/pjmedia/src/pjmedia-videodev/errno.c +++ b/pjmedia/src/pjmedia-videodev/errno.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -37,22 +36,22 @@ static const struct const char *msg; } err_str[] = { - PJ_BUILD_ERR( PJMEDIA_EVID_ERR, "Unspecified video device error" ), - PJ_BUILD_ERR( PJMEDIA_EVID_SYSERR, "Unknown error from video driver" ), - PJ_BUILD_ERR( PJMEDIA_EVID_INIT, "video subsystem not initialized" ), - PJ_BUILD_ERR( PJMEDIA_EVID_INVDEV, "Invalid video device" ), - PJ_BUILD_ERR( PJMEDIA_EVID_NODEV, "Found no video devices" ), + PJ_BUILD_ERR( PJMEDIA_EVID_ERR, "Unspecified video device error" ), + PJ_BUILD_ERR( PJMEDIA_EVID_SYSERR, "Unknown error from video driver" ), + PJ_BUILD_ERR( PJMEDIA_EVID_INIT, "video subsystem not initialized" ), + PJ_BUILD_ERR( PJMEDIA_EVID_INVDEV, "Invalid video device" ), + PJ_BUILD_ERR( PJMEDIA_EVID_NODEV, "Found no video devices" ), PJ_BUILD_ERR( PJMEDIA_EVID_NODEFDEV, "Unable to find default video device" ), PJ_BUILD_ERR( PJMEDIA_EVID_NOTREADY, "video device not ready" ), - PJ_BUILD_ERR( PJMEDIA_EVID_INVCAP, "Invalid or unsupported video capability" ), - PJ_BUILD_ERR( PJMEDIA_EVID_INVOP, "Invalid or unsupported video device operation" ), + PJ_BUILD_ERR( PJMEDIA_EVID_INVCAP, "Invalid or unsupported video capability" ), + PJ_BUILD_ERR( PJMEDIA_EVID_INVOP, "Invalid or unsupported video device operation" ), PJ_BUILD_ERR( PJMEDIA_EVID_BADFORMAT, "Bad or invalid video device format" ), PJ_BUILD_ERR( PJMEDIA_EVID_SAMPFORMAT, "Invalid video device sample format"), PJ_BUILD_ERR( PJMEDIA_EVID_BADLATENCY, "Bad video latency setting") }; -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ @@ -60,7 +59,7 @@ static const struct * pjmedia_videodev_strerror() */ PJ_DEF(pj_str_t) pjmedia_videodev_strerror(pj_status_t statcode, - char *buf, pj_size_t bufsize ) + char *buf, pj_size_t bufsize ) { pj_str_t errstr; @@ -68,51 +67,51 @@ PJ_DEF(pj_str_t) pjmedia_videodev_strerror(pj_status_t statcode, /* videodev error */ if (statcode >= PJMEDIA_VIDEODEV_ERRNO_START && - statcode < PJMEDIA_VIDEODEV_ERRNO_END) + statcode < PJMEDIA_VIDEODEV_ERRNO_END) { - /* Find the error in the table. - * Use binary search! - */ - int first = 0; - int n = PJ_ARRAY_SIZE(err_str); - - while (n > 0) { - int half = n/2; - int mid = first + half; - - if (err_str[mid].code < statcode) { - first = mid+1; - n -= (half+1); - } else if (err_str[mid].code > statcode) { - n = half; - } else { - first = mid; - break; - } - } - - - if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { - pj_str_t msg; - - msg.ptr = (char*)err_str[first].msg; - msg.slen = pj_ansi_strlen(err_str[first].msg); - - errstr.ptr = buf; - pj_strncpy_with_null(&errstr, &msg, bufsize); - return errstr; - - } + /* Find the error in the table. + * Use binary search! + */ + int first = 0; + int n = PJ_ARRAY_SIZE(err_str); + + while (n > 0) { + int half = n/2; + int mid = first + half; + + if (err_str[mid].code < statcode) { + first = mid+1; + n -= (half+1); + } else if (err_str[mid].code > statcode) { + n = half; + } else { + first = mid; + break; + } + } + + + if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { + pj_str_t msg; + + msg.ptr = (char*)err_str[first].msg; + msg.slen = pj_ansi_strlen(err_str[first].msg); + + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, &msg, bufsize); + return errstr; + + } } -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ /* Error not found. */ errstr.ptr = buf; errstr.slen = pj_ansi_snprintf(buf, bufsize, - "Unknown pjmedia-videodev error %d", - statcode); + "Unknown pjmedia-videodev error %d", + statcode); if (errstr.slen < 1 || errstr.slen >= (pj_ssize_t)bufsize) - errstr.slen = bufsize - 1; + errstr.slen = bufsize - 1; return errstr; } diff --git a/pjmedia/src/pjmedia-videodev/ffmpeg_dev.c b/pjmedia/src/pjmedia-videodev/ffmpeg_dev.c index 30c267d4b3..a86845ed77 100644 --- a/pjmedia/src/pjmedia-videodev/ffmpeg_dev.c +++ b/pjmedia/src/pjmedia-videodev/ffmpeg_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -43,11 +42,11 @@ defined(PJMEDIA_VIDEO_DEV_HAS_FFMPEG) && PJMEDIA_VIDEO_DEV_HAS_FFMPEG != 0 -#define THIS_FILE "ffmpeg.c" +#define THIS_FILE "ffmpeg.c" #define LIBAVFORMAT_VER_AT_LEAST(major,minor) (LIBAVFORMAT_VERSION_MAJOR > major || \ - (LIBAVFORMAT_VERSION_MAJOR == major && \ - LIBAVFORMAT_VERSION_MINOR >= minor)) + (LIBAVFORMAT_VERSION_MAJOR == major && \ + LIBAVFORMAT_VERSION_MINOR >= minor)) #include "../pjmedia/ffmpeg_util.h" #include @@ -73,8 +72,8 @@ typedef struct ffmpeg_dev_info typedef struct ffmpeg_factory { - pjmedia_vid_dev_factory base; - pj_pool_factory *pf; + pjmedia_vid_dev_factory base; + pj_pool_factory *pf; pj_pool_t *pool; pj_pool_t *dev_pool; unsigned dev_count; @@ -89,7 +88,7 @@ typedef struct ffmpeg_stream pj_pool_t *pool; pjmedia_vid_dev_param param; AVFormatContext *ff_fmt_ctx; - void *frame_buf; + void *frame_buf; } ffmpeg_stream; @@ -99,27 +98,27 @@ static pj_status_t ffmpeg_factory_destroy(pjmedia_vid_dev_factory *f); static pj_status_t ffmpeg_factory_refresh(pjmedia_vid_dev_factory *f); static unsigned ffmpeg_factory_get_dev_count(pjmedia_vid_dev_factory *f); static pj_status_t ffmpeg_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info); + unsigned index, + pjmedia_vid_dev_info *info); static pj_status_t ffmpeg_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param); + unsigned index, + pjmedia_vid_dev_param *param); static pj_status_t ffmpeg_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm); + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm); static pj_status_t ffmpeg_stream_get_param(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_param *param); + pjmedia_vid_dev_param *param); static pj_status_t ffmpeg_stream_get_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - void *value); + pjmedia_vid_dev_cap cap, + void *value); static pj_status_t ffmpeg_stream_set_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - const void *value); + pjmedia_vid_dev_cap cap, + const void *value); static pj_status_t ffmpeg_stream_start(pjmedia_vid_dev_stream *strm); static pj_status_t ffmpeg_stream_get_frame(pjmedia_vid_dev_stream *s, pjmedia_frame *frame); @@ -165,7 +164,7 @@ static void print_ffmpeg_log(void* ptr, int level, const char* fmt, va_list vl) /* Custom callback needs to filter log level by itself */ if (level > av_log_get_level()) - return; + return; vfprintf(stdout, fmt, vl); } @@ -193,8 +192,8 @@ static pj_status_t ffmpeg_capture_open(AVFormatContext **ctx, status = pjmedia_format_id_to_PixelFormat(param->fmt.id, &av_fmt); if (status != PJ_SUCCESS) { - avformat_free_context(*ctx); - return status; + avformat_free_context(*ctx); + return status; } vfd = pjmedia_format_get_video_format_detail(¶m->fmt, PJ_TRUE); @@ -307,7 +306,7 @@ static pj_status_t ffmpeg_factory_destroy(pjmedia_vid_dev_factory *f) #define MAX_DEV_NAME_LEN 80 static pj_status_t dshow_enum_devices(unsigned *dev_cnt, - char dev_names[][MAX_DEV_NAME_LEN]) + char dev_names[][MAX_DEV_NAME_LEN]) { unsigned max_cnt = *dev_cnt; ICreateDevEnum *dev_enum = NULL; @@ -327,28 +326,28 @@ static pj_status_t dshow_enum_devices(unsigned *dev_cnt, ICreateDevEnum_CreateClassEnumerator(dev_enum, &CLSID_VideoInputDeviceCategory, &enum_cat, 0) != S_OK) { - PJ_LOG(4,(THIS_FILE, "Windows found no video input devices")); + PJ_LOG(4,(THIS_FILE, "Windows found no video input devices")); if (dev_enum) ICreateDevEnum_Release(dev_enum); - return PJ_SUCCESS; + return PJ_SUCCESS; } while (IEnumMoniker_Next(enum_cat, 1, &moniker, &fetched) == S_OK && - *dev_cnt < max_cnt) + *dev_cnt < max_cnt) { - (*dev_cnt)++; + (*dev_cnt)++; } if (*dev_cnt == 0) { IEnumMoniker_Release(enum_cat); ICreateDevEnum_Release(dev_enum); - return PJ_SUCCESS; + return PJ_SUCCESS; } IEnumMoniker_Reset(enum_cat); while (i < max_cnt && - IEnumMoniker_Next(enum_cat, 1, &moniker, &fetched) == S_OK) + IEnumMoniker_Next(enum_cat, 1, &moniker, &fetched) == S_OK) { IPropertyBag *prop_bag; @@ -359,14 +358,14 @@ static pj_status_t dshow_enum_devices(unsigned *dev_cnt, VariantInit(&var_name); hr = IPropertyBag_Read(prop_bag, L"FriendlyName", &var_name, - NULL); + NULL); if (SUCCEEDED(hr) && var_name.bstrVal) { - char tmp[MAX_DEV_NAME_LEN] = {0}; + char tmp[MAX_DEV_NAME_LEN] = {0}; WideCharToMultiByte(CP_ACP, 0, var_name.bstrVal, (int)wcslen(var_name.bstrVal), tmp, MAX_DEV_NAME_LEN, NULL, NULL); - pj_ansi_snprintf(dev_names[i++], MAX_DEV_NAME_LEN, - "video=%s", tmp); + pj_ansi_snprintf(dev_names[i++], MAX_DEV_NAME_LEN, + "video=%s", tmp); } VariantClear(&var_name); IPropertyBag_Release(prop_bag); @@ -379,7 +378,7 @@ static pj_status_t dshow_enum_devices(unsigned *dev_cnt, PJ_LOG(4, (THIS_FILE, "DShow has %d devices:", *dev_cnt)); for (i = 0; i < *dev_cnt; ++i) { - PJ_LOG(4, (THIS_FILE, " %d: %s", (i+1), dev_names[i])); + PJ_LOG(4, (THIS_FILE, " %d: %s", (i+1), dev_names[i])); } return PJ_SUCCESS; @@ -408,92 +407,92 @@ static pj_status_t ffmpeg_factory_refresh(pjmedia_vid_dev_factory *f) /* Iterate host APIs */ p = av_input_video_device_next(NULL); while (p && ff->dev_count < MAX_DEV_CNT) { - char dev_names[MAX_DEV_CNT][MAX_DEV_NAME_LEN]; - unsigned dev_cnt = MAX_DEV_CNT; - unsigned dev_idx; + char dev_names[MAX_DEV_CNT][MAX_DEV_NAME_LEN]; + unsigned dev_cnt = MAX_DEV_CNT; + unsigned dev_idx; - if ((p->flags & AVFMT_NOFILE)==0 || p->read_probe) { - goto next_format; - } + if ((p->flags & AVFMT_NOFILE)==0 || p->read_probe) { + goto next_format; + } #if (defined(PJ_WIN32) && PJ_WIN32!=0) || \ (defined(PJ_WIN64) && PJ_WIN64!=0) - if (pj_ansi_strcmp(p->name, "dshow") == 0) { - dshow_enum_devices(&dev_cnt, dev_names); - } else if (pj_ansi_strcmp(p->name, "vfwcap") == 0) { - dev_cnt = 1; - pj_ansi_snprintf(dev_names[0], MAX_DEV_NAME_LEN, "0"); - } else { - dev_cnt = 0; - } + if (pj_ansi_strcmp(p->name, "dshow") == 0) { + dshow_enum_devices(&dev_cnt, dev_names); + } else if (pj_ansi_strcmp(p->name, "vfwcap") == 0) { + dev_cnt = 1; + pj_ansi_snprintf(dev_names[0], MAX_DEV_NAME_LEN, "0"); + } else { + dev_cnt = 0; + } #elif defined(PJ_LINUX) && PJ_LINUX!=0 - dev_cnt = 1; - pj_ansi_snprintf(dev_names[0], MAX_DEV_NAME_LEN, "/dev/video0"); + dev_cnt = 1; + pj_ansi_snprintf(dev_names[0], MAX_DEV_NAME_LEN, "/dev/video0"); #else - dev_cnt = 0; + dev_cnt = 0; #endif - /* Iterate devices (only DirectShow devices for now) */ - for (dev_idx = 0; dev_idx < dev_cnt && ff->dev_count < MAX_DEV_CNT; - ++dev_idx) - { - ffmpeg_dev_info *info; - AVFormatContext *ctx; - AVCodecContext *codec = NULL; - pjmedia_format_id fmt_id; - pj_str_t dev_name; - pj_status_t status; - unsigned i; + /* Iterate devices (only DirectShow devices for now) */ + for (dev_idx = 0; dev_idx < dev_cnt && ff->dev_count < MAX_DEV_CNT; + ++dev_idx) + { + ffmpeg_dev_info *info; + AVFormatContext *ctx; + AVCodecContext *codec = NULL; + pjmedia_format_id fmt_id; + pj_str_t dev_name; + pj_status_t status; + unsigned i; + + ctx = avformat_alloc_context(); + if (!ctx || avformat_open_input(&ctx, dev_names[dev_idx], p, NULL)!=0) + continue; + + for(i = 0; i < ctx->nb_streams; i++) { + if (ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { + codec = ctx->streams[i]->codec; + break; + } + } + if (!codec) { + av_close_input_stream(ctx); + continue; + } + + status = PixelFormat_to_pjmedia_format_id(codec->pix_fmt, &fmt_id); + if (status != PJ_SUCCESS) { + av_close_input_stream(ctx); + continue; + } + + info = &ff->dev_info[ff->dev_count++]; + pj_bzero(info, sizeof(*info)); + pj_ansi_strncpy(info->base.name, "default", + sizeof(info->base.name)); + pj_ansi_snprintf(info->base.driver, sizeof(info->base.driver), + "ffmpeg %s", p->name); - ctx = avformat_alloc_context(); - if (!ctx || avformat_open_input(&ctx, dev_names[dev_idx], p, NULL)!=0) - continue; - - for(i = 0; i < ctx->nb_streams; i++) { - if (ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { - codec = ctx->streams[i]->codec; - break; - } - } - if (!codec) { - av_close_input_stream(ctx); - continue; - } - - status = PixelFormat_to_pjmedia_format_id(codec->pix_fmt, &fmt_id); - if (status != PJ_SUCCESS) { - av_close_input_stream(ctx); - continue; - } - - info = &ff->dev_info[ff->dev_count++]; - pj_bzero(info, sizeof(*info)); - pj_ansi_strncpy(info->base.name, "default", - sizeof(info->base.name)); - pj_ansi_snprintf(info->base.driver, sizeof(info->base.driver), - "ffmpeg %s", p->name); - - pj_strdup2_with_null(ff->pool, &dev_name, dev_names[dev_idx]); - info->def_devname = dev_name.ptr; - info->base.dir = PJMEDIA_DIR_CAPTURE; - info->base.has_callback = PJ_FALSE; - - info->host_api = p; - - /* Set supported formats */ - info->base.caps = PJMEDIA_VID_DEV_CAP_FORMAT; - info->base.fmt_cnt = 1; - for (i = 0; i < info->base.fmt_cnt; ++i) { - pjmedia_format *fmt = &info->base.fmt[i]; - pjmedia_format_init_video(fmt, fmt_id, - codec->width, codec->height, 15, 1); - } - - av_close_input_stream(ctx); - } + pj_strdup2_with_null(ff->pool, &dev_name, dev_names[dev_idx]); + info->def_devname = dev_name.ptr; + info->base.dir = PJMEDIA_DIR_CAPTURE; + info->base.has_callback = PJ_FALSE; + + info->host_api = p; + + /* Set supported formats */ + info->base.caps = PJMEDIA_VID_DEV_CAP_FORMAT; + info->base.fmt_cnt = 1; + for (i = 0; i < info->base.fmt_cnt; ++i) { + pjmedia_format *fmt = &info->base.fmt[i]; + pjmedia_format_init_video(fmt, fmt_id, + codec->width, codec->height, 15, 1); + } + + av_close_input_stream(ctx); + } next_format: - p = av_input_video_device_next(p); + p = av_input_video_device_next(p); } return PJ_SUCCESS; @@ -508,8 +507,8 @@ static unsigned ffmpeg_factory_get_dev_count(pjmedia_vid_dev_factory *f) /* API: get device info */ static pj_status_t ffmpeg_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info) + unsigned index, + pjmedia_vid_dev_info *info) { ffmpeg_factory *ff = (ffmpeg_factory*)f; @@ -523,8 +522,8 @@ static pj_status_t ffmpeg_factory_get_dev_info(pjmedia_vid_dev_factory *f, /* API: create default device parameter */ static pj_status_t ffmpeg_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param) + unsigned index, + pjmedia_vid_dev_param *param) { ffmpeg_factory *ff = (ffmpeg_factory*)f; ffmpeg_dev_info *info; @@ -554,11 +553,11 @@ static pj_status_t ffmpeg_factory_default_param(pj_pool_t *pool, /* API: create stream */ static pj_status_t ffmpeg_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm) + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm) { ffmpeg_factory *ff = (ffmpeg_factory*)f; pj_pool_t *pool; @@ -568,7 +567,7 @@ static pj_status_t ffmpeg_factory_create_stream( PJ_ASSERT_RETURN(param->dir == PJMEDIA_DIR_CAPTURE, PJ_EINVAL); PJ_ASSERT_RETURN((unsigned)param->cap_id < ff->dev_count, PJ_EINVAL); PJ_ASSERT_RETURN(param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO, - PJ_EINVAL); + PJ_EINVAL); PJ_UNUSED_ARG(cb); PJ_UNUSED_ARG(user_data); @@ -584,17 +583,17 @@ static pj_status_t ffmpeg_factory_create_stream( /* Allocate frame buffer */ { - const pjmedia_video_format_info *vfi; - pjmedia_video_apply_fmt_param vafp; + const pjmedia_video_format_info *vfi; + pjmedia_video_apply_fmt_param vafp; - vfi = pjmedia_get_video_format_info(NULL, param->fmt.id); - if (!vfi) goto on_error; + vfi = pjmedia_get_video_format_info(NULL, param->fmt.id); + if (!vfi) goto on_error; - pj_bzero(&vafp, sizeof(vafp)); - vafp.size = param->fmt.det.vid.size; - vfi->apply_fmt(vfi, &vafp); + pj_bzero(&vafp, sizeof(vafp)); + vafp.size = param->fmt.det.vid.size; + vfi->apply_fmt(vfi, &vafp); - strm->frame_buf = pj_pool_alloc(pool, vafp.framebytes); + strm->frame_buf = pj_pool_alloc(pool, vafp.framebytes); } /* Done */ @@ -610,7 +609,7 @@ static pj_status_t ffmpeg_factory_create_stream( /* API: Get stream info. */ static pj_status_t ffmpeg_stream_get_param(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_param *pi) + pjmedia_vid_dev_param *pi) { ffmpeg_stream *strm = (ffmpeg_stream*)s; @@ -623,8 +622,8 @@ static pj_status_t ffmpeg_stream_get_param(pjmedia_vid_dev_stream *s, /* API: get capability */ static pj_status_t ffmpeg_stream_get_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - void *pval) + pjmedia_vid_dev_cap cap, + void *pval) { ffmpeg_stream *strm = (ffmpeg_stream*)s; @@ -637,8 +636,8 @@ static pj_status_t ffmpeg_stream_get_cap(pjmedia_vid_dev_stream *s, /* API: set capability */ static pj_status_t ffmpeg_stream_set_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - const void *pval) + pjmedia_vid_dev_cap cap, + const void *pval) { ffmpeg_stream *strm = (ffmpeg_stream*)s; @@ -732,4 +731,4 @@ static pj_status_t ffmpeg_stream_destroy(pjmedia_vid_dev_stream *s) #endif -#endif /* PJMEDIA_VIDEO_DEV_HAS_FFMPEG */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_FFMPEG */ diff --git a/pjmedia/src/pjmedia-videodev/ios_opengl_dev.m b/pjmedia/src/pjmedia-videodev/ios_opengl_dev.m index 51f6e67ce5..f087e2bbf9 100644 --- a/pjmedia/src/pjmedia-videodev/ios_opengl_dev.m +++ b/pjmedia/src/pjmedia-videodev/ios_opengl_dev.m @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013-2014 Teluu Inc. (http://www.teluu.com) * @@ -30,13 +29,13 @@ #include #import -#define THIS_FILE "ios_opengl_dev.c" +#define THIS_FILE "ios_opengl_dev.c" /* If this is enabled, iOS OpenGL will not return error during creation when * in the background. Instead, it will perform the initialization later * during rendering. */ -#define ALLOW_DELAYED_INITIALIZATION 0 +#define ALLOW_DELAYED_INITIALIZATION 0 typedef struct iosgl_fmt_info { @@ -60,23 +59,23 @@ @interface GLView : UIView /* Video stream. */ struct iosgl_stream { - pjmedia_vid_dev_stream base; /**< Base stream */ - pjmedia_vid_dev_param param; /**< Settings */ - pj_pool_t *pool; /**< Memory pool */ + pjmedia_vid_dev_stream base; /**< Base stream */ + pjmedia_vid_dev_param param; /**< Settings */ + pj_pool_t *pool; /**< Memory pool */ - pjmedia_vid_dev_cb vid_cb; /**< Stream callback */ - void *user_data; /**< Application data */ + pjmedia_vid_dev_cb vid_cb; /**< Stream callback */ + void *user_data; /**< Application data */ - pj_bool_t is_running; + pj_bool_t is_running; pj_status_t status; pj_timestamp frame_ts; unsigned ts_inc; pjmedia_rect_size vid_size; - unsigned frame_size; + unsigned frame_size; - pj_bool_t is_rendering; - void *render_buf; - unsigned render_buf_size; + pj_bool_t is_rendering; + void *render_buf; + unsigned render_buf_size; gl_buffers *gl_buf; GLView *gl_view; @@ -220,7 +219,7 @@ - (void)render if (stream->status == PJMEDIA_EVID_INIT) { [self init_gl]; NSLog(@"Initializing OpenGL now %s", stream->status == PJ_SUCCESS? - "success": "failed"); + "success": "failed"); } return; @@ -285,7 +284,7 @@ - (void)change_format rect = CGRectMake(0, 0, strm->param.disp_size.w, strm->param.disp_size.h); dispatch_sync_on_main_queue(^{ - strm->gl_view = [[GLView alloc] initWithFrame:rect]; + strm->gl_view = [[GLView alloc] initWithFrame:rect]; }); if (!strm->gl_view) return PJ_ENOMEM; @@ -310,11 +309,11 @@ - (void)change_format { if (status == PJMEDIA_EVID_INIT) { PJ_LOG(3, (THIS_FILE, "Failed to initialize iOS OpenGL because " - "we are in background")); + "we are in background")); #if !ALLOW_DELAYED_INITIALIZATION goto on_error; #endif - } else { + } else { PJ_LOG(3, (THIS_FILE, "Unable to create and init OpenGL buffers")); goto on_error; } @@ -398,7 +397,7 @@ static pj_status_t iosgl_stream_get_cap(pjmedia_vid_dev_stream *s, wnd->info.ios.window = strm->gl_view; return PJ_SUCCESS; } else { - return PJMEDIA_EVID_INVCAP; + return PJMEDIA_EVID_INVCAP; } } @@ -415,7 +414,7 @@ static pj_status_t iosgl_stream_set_cap(pjmedia_vid_dev_stream *s, if (cap==PJMEDIA_VID_DEV_CAP_FORMAT) { const pjmedia_video_format_info *vfi; - pjmedia_video_apply_fmt_param vafp; + pjmedia_video_apply_fmt_param vafp; pjmedia_format *fmt = (pjmedia_format *)pval; iosgl_fmt_info *ifi; @@ -427,24 +426,24 @@ static pj_status_t iosgl_stream_set_cap(pjmedia_vid_dev_stream *s, if (!vfi) return PJMEDIA_EVID_BADFORMAT; - vafp.size = fmt->det.vid.size; - vafp.buffer = NULL; - if (vfi->apply_fmt(vfi, &vafp) != PJ_SUCCESS) + vafp.size = fmt->det.vid.size; + vafp.buffer = NULL; + if (vfi->apply_fmt(vfi, &vafp) != PJ_SUCCESS) return PJMEDIA_EVID_BADFORMAT; pjmedia_format_copy(&strm->param.fmt, fmt); strm->frame_size = vafp.framebytes; - if (strm->render_buf_size < strm->frame_size) { + if (strm->render_buf_size < strm->frame_size) { /* Realloc only when needed */ - strm->render_buf_size = strm->frame_size; + strm->render_buf_size = strm->frame_size; strm->render_buf=pj_pool_alloc(strm->pool, strm->render_buf_size); } [strm->gl_view performSelectorOnMainThread:@selector(change_format) withObject:nil waitUntilDone:YES]; - return PJ_SUCCESS; + return PJ_SUCCESS; } else if (cap == PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW) { UIView *view = (UIView *)pval; strm->param.window.info.ios.window = (void *)pval; @@ -507,14 +506,14 @@ static pj_status_t iosgl_stream_put_frame(pjmedia_vid_dev_stream *strm, * or keep-alive, this port doesn't need any, just ignore. */ if (frame->size==0 || frame->buf==NULL) - return PJ_SUCCESS; - + return PJ_SUCCESS; + if (!stream->is_running) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; /* Prevent more than one async rendering task. */ if (stream->is_rendering) - return PJ_EIGNORED; + return PJ_EIGNORED; if (stream->frame_size >= frame->size) pj_memcpy(stream->render_buf, frame->buf, frame->size); @@ -557,7 +556,7 @@ static pj_status_t iosgl_stream_destroy(pjmedia_vid_dev_stream *strm) if (stream->gl_view) { [stream->gl_view performSelectorOnMainThread:@selector(deinit_gl) - withObject:nil waitUntilDone:YES]; + withObject:nil waitUntilDone:YES]; [stream->gl_view release]; stream->gl_view = NULL; @@ -568,4 +567,4 @@ static pj_status_t iosgl_stream_destroy(pjmedia_vid_dev_stream *strm) return PJ_SUCCESS; } -#endif /* PJMEDIA_VIDEO_DEV_HAS_IOS_OPENGL */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_IOS_OPENGL */ diff --git a/pjmedia/src/pjmedia-videodev/opengl_dev.c b/pjmedia/src/pjmedia-videodev/opengl_dev.c index 740828a325..056e1c1772 100644 --- a/pjmedia/src/pjmedia-videodev/opengl_dev.c +++ b/pjmedia/src/pjmedia-videodev/opengl_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013-2014 Teluu Inc. (http://www.teluu.com) * @@ -29,9 +28,9 @@ # if PJ_ANDROID # include # include -# undef GL_RGBA -# define GL_RGBA GL_BGRA_EXT -# define GL_BGRA GL_BGRA_EXT +# undef GL_RGBA +# define GL_RGBA GL_BGRA_EXT +# define GL_BGRA GL_BGRA_EXT # else # include # include @@ -41,11 +40,11 @@ # include #endif -#define THIS_FILE "opengl_dev.c" -#define DEFAULT_CLOCK_RATE 90000 -#define DEFAULT_WIDTH 480 -#define DEFAULT_HEIGHT 360 -#define DEFAULT_FPS 15 +#define THIS_FILE "opengl_dev.c" +#define DEFAULT_CLOCK_RATE 90000 +#define DEFAULT_WIDTH 480 +#define DEFAULT_HEIGHT 360 +#define DEFAULT_FPS 15 #if PJ_ANDROID # define LOG(a) PJ_LOG(3, (THIS_FILE, a)) @@ -81,14 +80,14 @@ void main() \ /* OpenGL buffers structure. */ struct gl_buffers { - GLuint frameBuf; - GLuint rendBuf; - GLuint rendTex; - GLuint directProg; - - int rendBufW; - int rendBufH; - pj_bool_t direct; + GLuint frameBuf; + GLuint rendBuf; + GLuint rendTex; + GLuint directProg; + + int rendBufW; + int rendBufH; + pj_bool_t direct; }; /* Supported formats */ @@ -97,18 +96,18 @@ static pjmedia_format_id opengl_fmts[] = {PJMEDIA_FORMAT_BGRA}; /* opengl device info */ struct opengl_dev_info { - pjmedia_vid_dev_info info; + pjmedia_vid_dev_info info; }; /* opengl factory */ struct opengl_factory { - pjmedia_vid_dev_factory base; - pj_pool_t *pool; - pj_pool_factory *pf; + pjmedia_vid_dev_factory base; + pj_pool_t *pool; + pj_pool_factory *pf; - unsigned dev_count; - struct opengl_dev_info *dev_info; + unsigned dev_count; + struct opengl_dev_info *dev_info; }; /* Prototypes */ @@ -215,7 +214,7 @@ GLint create_program(const GLchar *vertSource, const GLchar *fragSource, } void pjmedia_vid_dev_opengl_create_buffers(pj_pool_t *pool, pj_bool_t direct, - gl_buffers **glb) + gl_buffers **glb) { gl_buffers *glbuf = PJ_POOL_ZALLOC_T(pool, gl_buffers); @@ -223,11 +222,11 @@ void pjmedia_vid_dev_opengl_create_buffers(pj_pool_t *pool, pj_bool_t direct, glDisable(GL_DEPTH_TEST); if (!(glbuf->direct = direct)) { - glGenFramebuffers(1, &glbuf->frameBuf); - glBindFramebuffer(GL_FRAMEBUFFER, glbuf->frameBuf); + glGenFramebuffers(1, &glbuf->frameBuf); + glBindFramebuffer(GL_FRAMEBUFFER, glbuf->frameBuf); - glGenRenderbuffers(1, &glbuf->rendBuf); - glBindRenderbuffer(GL_RENDERBUFFER, glbuf->rendBuf); + glGenRenderbuffers(1, &glbuf->rendBuf); + glBindRenderbuffer(GL_RENDERBUFFER, glbuf->rendBuf); } glGenTextures(1, &glbuf->rendTex); @@ -241,14 +240,14 @@ pj_status_t pjmedia_vid_dev_opengl_init_buffers(gl_buffers *glb) GLchar *attribName[NUM_ATTRIBUTES] = { "position", "texCoord" }; if (!glb->direct ) { - glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, + glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &glb->rendBufW); - glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, + glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &glb->rendBufH); - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, glb->rendBuf); - if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { LOG("Unable to create frame buffer"); return -1; } @@ -288,7 +287,7 @@ pj_status_t pjmedia_vid_dev_opengl_draw(gl_buffers *glb, unsigned int width, glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)width, (GLsizei)height, - 0, GL_BGRA, GL_UNSIGNED_BYTE, (GLvoid *)pixels); + 0, GL_BGRA, GL_UNSIGNED_BYTE, (GLvoid *)pixels); glFlush(); @@ -384,7 +383,7 @@ static pj_status_t opengl_factory_init(pjmedia_vid_dev_factory *f) qdi->info.caps = PJMEDIA_VID_DEV_CAP_FORMAT; qdi->info.fmt_cnt = PJ_ARRAY_SIZE(opengl_fmts); qdi->info.caps |= pjmedia_vid_dev_opengl_imp_get_cap(); - + for (l = 0; l < PJ_ARRAY_SIZE(opengl_fmts); l++) { pjmedia_format *fmt = &qdi->info.fmt[l]; pjmedia_format_init_video(fmt, opengl_fmts[l], DEFAULT_WIDTH, @@ -451,11 +450,11 @@ static pj_status_t opengl_factory_default_param(pj_pool_t *pool, pj_bzero(param, sizeof(*param)); if (di->info.dir & PJMEDIA_DIR_RENDER) { - param->dir = PJMEDIA_DIR_RENDER; - param->rend_id = index; - param->cap_id = PJMEDIA_VID_INVALID_DEV; + param->dir = PJMEDIA_DIR_RENDER; + param->rend_id = index; + param->cap_id = PJMEDIA_VID_INVALID_DEV; } else { - return PJMEDIA_EVID_INVDEV; + return PJMEDIA_EVID_INVDEV; } param->flags = PJMEDIA_VID_DEV_CAP_FORMAT; @@ -479,10 +478,10 @@ opengl_factory_create_stream(pjmedia_vid_dev_factory *f, PJ_ASSERT_RETURN(f && param && p_vid_strm, PJ_EINVAL); PJ_ASSERT_RETURN(param->fmt.type == PJMEDIA_TYPE_VIDEO && - param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && + param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && (param->dir == PJMEDIA_DIR_CAPTURE || param->dir == PJMEDIA_DIR_RENDER), - PJ_EINVAL); + PJ_EINVAL); vfi = pjmedia_get_video_format_info(NULL, param->fmt.id); if (!vfi) @@ -496,4 +495,4 @@ opengl_factory_create_stream(pjmedia_vid_dev_factory *f, user_data, p_vid_strm); } -#endif /* PJMEDIA_VIDEO_DEV_HAS_OPENGL */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_OPENGL */ diff --git a/pjmedia/src/pjmedia-videodev/qt_dev.m b/pjmedia/src/pjmedia-videodev/qt_dev.m index e5d512d8f7..636407e633 100644 --- a/pjmedia/src/pjmedia-videodev/qt_dev.m +++ b/pjmedia/src/pjmedia-videodev/qt_dev.m @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -27,18 +26,18 @@ #include #include -#define THIS_FILE "qt_dev.c" -#define DEFAULT_CLOCK_RATE 90000 -#define DEFAULT_WIDTH 640 -#define DEFAULT_HEIGHT 480 -#define DEFAULT_FPS 15 +#define THIS_FILE "qt_dev.c" +#define DEFAULT_CLOCK_RATE 90000 +#define DEFAULT_WIDTH 640 +#define DEFAULT_HEIGHT 480 +#define DEFAULT_FPS 15 #define kCVPixelFormatType_422YpCbCr8_yuvs 'yuvs' typedef struct qt_fmt_info { pjmedia_format_id pjmedia_format; - unsigned qt_format; + unsigned qt_format; } qt_fmt_info; static qt_fmt_info qt_fmts[] = @@ -50,20 +49,20 @@ /* qt device info */ struct qt_dev_info { - pjmedia_vid_dev_info info; - char dev_id[192]; + pjmedia_vid_dev_info info; + char dev_id[192]; }; /* qt factory */ struct qt_factory { - pjmedia_vid_dev_factory base; - pj_pool_t *pool; - pj_pool_t *dev_pool; - pj_pool_factory *pf; + pjmedia_vid_dev_factory base; + pj_pool_t *pool; + pj_pool_t *dev_pool; + pj_pool_factory *pf; - unsigned dev_count; - struct qt_dev_info *dev_info; + unsigned dev_count; + struct qt_dev_info *dev_info; }; struct qt_stream; @@ -82,29 +81,29 @@ - (void)run_func; /* Video stream. */ struct qt_stream { - pjmedia_vid_dev_stream base; /**< Base stream */ - pjmedia_vid_dev_param param; /**< Settings */ - pj_pool_t *pool; /**< Memory pool. */ + pjmedia_vid_dev_stream base; /**< Base stream */ + pjmedia_vid_dev_param param; /**< Settings */ + pj_pool_t *pool; /**< Memory pool. */ - pj_timestamp cap_frame_ts; /**< Captured frame tstamp */ - unsigned cap_ts_inc; /**< Increment */ + pj_timestamp cap_frame_ts; /**< Captured frame tstamp */ + unsigned cap_ts_inc; /**< Increment */ - pjmedia_vid_dev_cb vid_cb; /**< Stream callback. */ - void *user_data; /**< Application data. */ + pjmedia_vid_dev_cb vid_cb; /**< Stream callback. */ + void *user_data; /**< Application data. */ - pj_bool_t cap_thread_exited; - pj_bool_t cap_thread_initialized; - pj_thread_desc cap_thread_desc; - pj_thread_t *cap_thread; + pj_bool_t cap_thread_exited; + pj_bool_t cap_thread_initialized; + pj_thread_desc cap_thread_desc; + pj_thread_t *cap_thread; struct qt_factory *qf; pj_status_t status; pj_bool_t is_running; pj_bool_t cap_exited; - QTCaptureSession *cap_session; - QTCaptureDeviceInput *dev_input; - QTCaptureDecompressedVideoOutput *video_output; + QTCaptureSession *cap_session; + QTCaptureDeviceInput *dev_input; + QTCaptureDecompressedVideoOutput *video_output; QTDelegate *qt_delegate; }; @@ -115,27 +114,27 @@ - (void)run_func; static pj_status_t qt_factory_refresh(pjmedia_vid_dev_factory *f); static unsigned qt_factory_get_dev_count(pjmedia_vid_dev_factory *f); static pj_status_t qt_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info); + unsigned index, + pjmedia_vid_dev_info *info); static pj_status_t qt_factory_default_param(pj_pool_t *pool, - pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param); + pjmedia_vid_dev_factory *f, + unsigned index, + pjmedia_vid_dev_param *param); static pj_status_t qt_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm); + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm); static pj_status_t qt_stream_get_param(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_param *param); + pjmedia_vid_dev_param *param); static pj_status_t qt_stream_get_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - void *value); + pjmedia_vid_dev_cap cap, + void *value); static pj_status_t qt_stream_set_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - const void *value); + pjmedia_vid_dev_cap cap, + const void *value); static pj_status_t qt_stream_start(pjmedia_vid_dev_stream *strm); static pj_status_t qt_stream_stop(pjmedia_vid_dev_stream *strm); static pj_status_t qt_stream_destroy(pjmedia_vid_dev_stream *strm); @@ -223,12 +222,12 @@ static pj_status_t qt_factory_refresh(pjmedia_vid_dev_factory *f) dev_array = [QTCaptureDevice inputDevices]; for (i = 0; i < [dev_array count]; i++) { - QTCaptureDevice *dev = [dev_array objectAtIndex:i]; - if ([dev hasMediaType:QTMediaTypeVideo] || - [dev hasMediaType:QTMediaTypeMuxed]) - { - dev_count++; - } + QTCaptureDevice *dev = [dev_array objectAtIndex:i]; + if ([dev hasMediaType:QTMediaTypeVideo] || + [dev hasMediaType:QTMediaTypeMuxed]) + { + dev_count++; + } } /* Initialize input and output devices here */ @@ -239,53 +238,53 @@ static pj_status_t qt_factory_refresh(pjmedia_vid_dev_factory *f) pj_pool_calloc(qf->dev_pool, dev_count, sizeof(struct qt_dev_info)); for (i = 0; i < [dev_array count]; i++) { - QTCaptureDevice *dev = [dev_array objectAtIndex:i]; - if ([dev hasMediaType:QTMediaTypeVideo] || - [dev hasMediaType:QTMediaTypeMuxed]) - { - unsigned k; - - qdi = &qf->dev_info[qf->dev_count++]; - pj_bzero(qdi, sizeof(*qdi)); - [[dev localizedDisplayName] getCString:qdi->info.name + QTCaptureDevice *dev = [dev_array objectAtIndex:i]; + if ([dev hasMediaType:QTMediaTypeVideo] || + [dev hasMediaType:QTMediaTypeMuxed]) + { + unsigned k; + + qdi = &qf->dev_info[qf->dev_count++]; + pj_bzero(qdi, sizeof(*qdi)); + [[dev localizedDisplayName] getCString:qdi->info.name maxLength:sizeof(qdi->info.name) encoding: [NSString defaultCStringEncoding]]; - [[dev uniqueID] getCString:qdi->dev_id + [[dev uniqueID] getCString:qdi->dev_id maxLength:sizeof(qdi->dev_id) encoding:[NSString defaultCStringEncoding]]; - strcpy(qdi->info.driver, "QT"); - qdi->info.dir = PJMEDIA_DIR_CAPTURE; - qdi->info.has_callback = PJ_TRUE; + strcpy(qdi->info.driver, "QT"); + qdi->info.dir = PJMEDIA_DIR_CAPTURE; + qdi->info.has_callback = PJ_TRUE; - qdi->info.fmt_cnt = 0; - qdi->info.caps = PJMEDIA_VID_DEV_CAP_FORMAT; - for (k = 0; k < [[dev formatDescriptions] count]; k++) { - unsigned l; - QTFormatDescription *desc = [[dev formatDescriptions] - objectAtIndex:k]; - for (l = 0; l < PJ_ARRAY_SIZE(qt_fmts); l++) { - if ([desc formatType] == qt_fmts[l].qt_format) { - pjmedia_format *fmt = + qdi->info.fmt_cnt = 0; + qdi->info.caps = PJMEDIA_VID_DEV_CAP_FORMAT; + for (k = 0; k < [[dev formatDescriptions] count]; k++) { + unsigned l; + QTFormatDescription *desc = [[dev formatDescriptions] + objectAtIndex:k]; + for (l = 0; l < PJ_ARRAY_SIZE(qt_fmts); l++) { + if ([desc formatType] == qt_fmts[l].qt_format) { + pjmedia_format *fmt = &qdi->info.fmt[qdi->info.fmt_cnt++]; - pjmedia_format_init_video(fmt, - qt_fmts[l].pjmedia_format, - DEFAULT_WIDTH, - DEFAULT_HEIGHT, - DEFAULT_FPS, 1); - break; - } - } - } + pjmedia_format_init_video(fmt, + qt_fmts[l].pjmedia_format, + DEFAULT_WIDTH, + DEFAULT_HEIGHT, + DEFAULT_FPS, 1); + break; + } + } + } - PJ_LOG(4, (THIS_FILE, " dev_id %d: %s", i, qdi->info.name)); - } + PJ_LOG(4, (THIS_FILE, " dev_id %d: %s", i, qdi->info.name)); + } } [apool release]; PJ_LOG(4, (THIS_FILE, "qt video has %d devices", - qf->dev_count)); + qf->dev_count)); return PJ_SUCCESS; } @@ -299,8 +298,8 @@ static unsigned qt_factory_get_dev_count(pjmedia_vid_dev_factory *f) /* API: get device info */ static pj_status_t qt_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info) + unsigned index, + pjmedia_vid_dev_info *info) { struct qt_factory *qf = (struct qt_factory*)f; @@ -313,9 +312,9 @@ static pj_status_t qt_factory_get_dev_info(pjmedia_vid_dev_factory *f, /* API: create default device parameter */ static pj_status_t qt_factory_default_param(pj_pool_t *pool, - pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param) + pjmedia_vid_dev_factory *f, + unsigned index, + pjmedia_vid_dev_param *param) { struct qt_factory *qf = (struct qt_factory*)f; struct qt_dev_info *di = &qf->dev_info[index]; @@ -349,9 +348,9 @@ static pj_status_t qt_factory_default_param(pj_pool_t *pool, @implementation QTDelegate - (void)captureOutput:(QTCaptureOutput *)captureOutput - didOutputVideoFrame:(CVImageBufferRef)videoFrame - withSampleBuffer:(QTSampleBuffer *)sampleBuffer - fromConnection:(QTCaptureConnection *)connection + didOutputVideoFrame:(CVImageBufferRef)videoFrame + withSampleBuffer:(QTSampleBuffer *)sampleBuffer + fromConnection:(QTCaptureConnection *)connection { unsigned size = [sampleBuffer lengthForAllSamples]; pjmedia_frame frame; @@ -363,14 +362,14 @@ - (void)captureOutput:(QTCaptureOutput *)captureOutput if (strm->cap_thread_initialized == 0 || !pj_thread_is_registered()) { - pj_thread_register("qt_cap", strm->cap_thread_desc, - &strm->cap_thread); - strm->cap_thread_initialized = 1; - PJ_LOG(5,(THIS_FILE, "Capture thread started")); + pj_thread_register("qt_cap", strm->cap_thread_desc, + &strm->cap_thread); + strm->cap_thread_initialized = 1; + PJ_LOG(5,(THIS_FILE, "Capture thread started")); } if (!videoFrame) - return; + return; frame.type = PJMEDIA_FRAME_TYPE_VIDEO; frame.buf = [sampleBuffer bytesForAllSamples]; @@ -421,7 +420,7 @@ static void init_qt(struct qt_stream *strm) return; } - /* Add the video device to the session as a device input */ + /* Add the video device to the session as a device input */ strm->dev_input = [[QTCaptureDeviceInput alloc] initWithDevice:videoDevice]; success = [strm->cap_session addInput:strm->dev_input error:&error]; @@ -482,11 +481,11 @@ static void run_func_on_main_thread(struct qt_stream *strm, func_ptr func) /* API: create stream */ static pj_status_t qt_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm) + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm) { struct qt_factory *qf = (struct qt_factory*)f; pj_pool_t *pool; @@ -496,9 +495,9 @@ static pj_status_t qt_factory_create_stream( PJ_ASSERT_RETURN(f && param && p_vid_strm, PJ_EINVAL); PJ_ASSERT_RETURN(param->fmt.type == PJMEDIA_TYPE_VIDEO && - param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && + param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && param->dir == PJMEDIA_DIR_CAPTURE, - PJ_EINVAL); + PJ_EINVAL); vfi = pjmedia_get_video_format_info(NULL, param->fmt.id); if (!vfi) @@ -526,9 +525,9 @@ static pj_status_t qt_factory_create_stream( /* Apply the remaining settings */ /* if (param->flags & PJMEDIA_VID_DEV_CAP_INPUT_SCALE) { - qt_stream_set_cap(&strm->base, - PJMEDIA_VID_DEV_CAP_INPUT_SCALE, - ¶m->fmt); + qt_stream_set_cap(&strm->base, + PJMEDIA_VID_DEV_CAP_INPUT_SCALE, + ¶m->fmt); } */ /* Done */ @@ -545,7 +544,7 @@ static pj_status_t qt_factory_create_stream( /* API: Get stream info. */ static pj_status_t qt_stream_get_param(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_param *pi) + pjmedia_vid_dev_param *pi) { struct qt_stream *strm = (struct qt_stream*)s; @@ -564,8 +563,8 @@ static pj_status_t qt_stream_get_param(pjmedia_vid_dev_stream *s, /* API: get capability */ static pj_status_t qt_stream_get_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - void *pval) + pjmedia_vid_dev_cap cap, + void *pval) { struct qt_stream *strm = (struct qt_stream*)s; @@ -576,16 +575,16 @@ static pj_status_t qt_stream_get_cap(pjmedia_vid_dev_stream *s, if (cap==PJMEDIA_VID_DEV_CAP_INPUT_SCALE) { return PJMEDIA_EVID_INVCAP; -// return PJ_SUCCESS; +// return PJ_SUCCESS; } else { - return PJMEDIA_EVID_INVCAP; + return PJMEDIA_EVID_INVCAP; } } /* API: set capability */ static pj_status_t qt_stream_set_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - const void *pval) + pjmedia_vid_dev_cap cap, + const void *pval) { struct qt_stream *strm = (struct qt_stream*)s; @@ -595,7 +594,7 @@ static pj_status_t qt_stream_set_cap(pjmedia_vid_dev_stream *s, if (cap==PJMEDIA_VID_DEV_CAP_INPUT_SCALE) { - return PJ_SUCCESS; + return PJ_SUCCESS; } return PJMEDIA_EVID_INVCAP; @@ -623,8 +622,8 @@ static pj_status_t qt_stream_start(pjmedia_vid_dev_stream *strm) if (stream->cap_session) { run_func_on_main_thread(stream, start_qt); - if (![stream->cap_session isRunning]) - return PJMEDIA_EVID_NOTREADY; + if (![stream->cap_session isRunning]) + return PJMEDIA_EVID_NOTREADY; stream->is_running = PJ_TRUE; } @@ -659,23 +658,23 @@ static pj_status_t qt_stream_stop(pjmedia_vid_dev_stream *strm) static void destroy_qt(struct qt_stream *strm) { if (strm->dev_input && [[strm->dev_input device] isOpen]) - [[strm->dev_input device] close]; + [[strm->dev_input device] close]; if (strm->cap_session) { - [strm->cap_session release]; - strm->cap_session = NULL; + [strm->cap_session release]; + strm->cap_session = NULL; } if (strm->dev_input) { - [strm->dev_input release]; - strm->dev_input = NULL; + [strm->dev_input release]; + strm->dev_input = NULL; } if (strm->qt_delegate) { - [strm->qt_delegate release]; - strm->qt_delegate = NULL; + [strm->qt_delegate release]; + strm->qt_delegate = NULL; } if (strm->video_output) { - [strm->video_output release]; - strm->video_output = NULL; + [strm->video_output release]; + strm->video_output = NULL; } } @@ -695,4 +694,4 @@ static pj_status_t qt_stream_destroy(pjmedia_vid_dev_stream *strm) return PJ_SUCCESS; } -#endif /* PJMEDIA_VIDEO_DEV_HAS_QT */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_QT */ diff --git a/pjmedia/src/pjmedia-videodev/sdl_dev.c b/pjmedia/src/pjmedia-videodev/sdl_dev.c index 44f3451d4b..79c70b9533 100644 --- a/pjmedia/src/pjmedia-videodev/sdl_dev.c +++ b/pjmedia/src/pjmedia-videodev/sdl_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -41,11 +40,11 @@ # include #endif -#define THIS_FILE "sdl_dev.c" -#define DEFAULT_CLOCK_RATE 90000 -#define DEFAULT_WIDTH 640 -#define DEFAULT_HEIGHT 480 -#define DEFAULT_FPS 25 +#define THIS_FILE "sdl_dev.c" +#define DEFAULT_CLOCK_RATE 90000 +#define DEFAULT_WIDTH 640 +#define DEFAULT_HEIGHT 480 +#define DEFAULT_FPS 25 typedef struct sdl_fmt_info { @@ -90,14 +89,14 @@ static sdl_fmt_info sdl_fmts[] = /* sdl_ device info */ struct sdl_dev_info { - pjmedia_vid_dev_info info; + pjmedia_vid_dev_info info; }; /* Linked list of streams */ struct stream_list { PJ_DECL_LIST_MEMBER(struct stream_list); - struct sdl_stream *stream; + struct sdl_stream *stream; }; #define INITIAL_MAX_JOBS 64 @@ -141,55 +140,55 @@ typedef struct job_queue { unsigned size; unsigned head, tail; - pj_bool_t is_full; + pj_bool_t is_full; pj_bool_t is_quitting; } job_queue; /* sdl_ factory */ struct sdl_factory { - pjmedia_vid_dev_factory base; - pj_pool_t *pool; - pj_pool_factory *pf; + pjmedia_vid_dev_factory base; + pj_pool_t *pool; + pj_pool_factory *pf; - unsigned dev_count; - struct sdl_dev_info *dev_info; + unsigned dev_count; + struct sdl_dev_info *dev_info; job_queue *jq; - pj_thread_t *sdl_thread; /**< SDL thread. */ + pj_thread_t *sdl_thread; /**< SDL thread. */ pj_sem_t *sem; - pj_mutex_t *mutex; - struct stream_list streams; + pj_mutex_t *mutex; + struct stream_list streams; pj_bool_t is_quitting; - pj_thread_desc thread_desc; - pj_thread_t *ev_thread; + pj_thread_desc thread_desc; + pj_thread_t *ev_thread; }; /* Video stream. */ struct sdl_stream { - pjmedia_vid_dev_stream base; /**< Base stream */ - pjmedia_vid_dev_param param; /**< Settings */ - pj_pool_t *pool; /**< Memory pool. */ + pjmedia_vid_dev_stream base; /**< Base stream */ + pjmedia_vid_dev_param param; /**< Settings */ + pj_pool_t *pool; /**< Memory pool. */ - pjmedia_vid_dev_cb vid_cb; /**< Stream callback. */ - void *user_data; /**< Application data. */ + pjmedia_vid_dev_cb vid_cb; /**< Stream callback. */ + void *user_data; /**< Application data. */ struct sdl_factory *sf; const pjmedia_frame *frame; - pj_bool_t is_running; - pj_timestamp last_ts; - struct stream_list list_entry; + pj_bool_t is_running; + pj_timestamp last_ts; + struct stream_list list_entry; SDL_Window *window; /**< Display window. */ SDL_Renderer *renderer; /**< Display renderer. */ SDL_Texture *scr_tex; /**< Screen texture. */ int pitch; /**< Pitch value. */ - SDL_Rect rect; /**< Frame rectangle. */ - SDL_Rect dstrect; /**< Display rectangle. */ + SDL_Rect rect; /**< Frame rectangle. */ + SDL_Rect dstrect; /**< Display rectangle. */ #if PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL SDL_GLContext *gl_context; - GLuint texture; + GLuint texture; #endif /* PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL */ pjmedia_video_apply_fmt_param vafp; @@ -201,27 +200,27 @@ static pj_status_t sdl_factory_destroy(pjmedia_vid_dev_factory *f); static pj_status_t sdl_factory_refresh(pjmedia_vid_dev_factory *f); static unsigned sdl_factory_get_dev_count(pjmedia_vid_dev_factory *f); static pj_status_t sdl_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info); + unsigned index, + pjmedia_vid_dev_info *info); static pj_status_t sdl_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param); + unsigned index, + pjmedia_vid_dev_param *param); static pj_status_t sdl_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm); + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm); static pj_status_t sdl_stream_get_param(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_param *param); + pjmedia_vid_dev_param *param); static pj_status_t sdl_stream_get_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - void *value); + pjmedia_vid_dev_cap cap, + void *value); static pj_status_t sdl_stream_set_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - const void *value); + pjmedia_vid_dev_cap cap, + const void *value); static pj_status_t sdl_stream_put_frame(pjmedia_vid_dev_stream *strm, const pjmedia_frame *frame); static pj_status_t sdl_stream_start(pjmedia_vid_dev_stream *strm); @@ -235,8 +234,8 @@ static pj_status_t sdl_destroy_all(void *data); /* Job queue prototypes */ static pj_status_t job_queue_create(pj_pool_t *pool, job_queue **pjq); static pj_status_t job_queue_post_job(job_queue *jq, job_func_ptr func, - void *data, unsigned flags, - pj_status_t *retval); + void *data, unsigned flags, + pj_status_t *retval); static pj_status_t job_queue_destroy(job_queue *jq); /* Operations */ @@ -328,7 +327,7 @@ static struct sdl_stream* find_stream(struct sdl_factory *sf, if (strm) pjmedia_event_init(pevent, PJMEDIA_EVENT_NONE, &strm->last_ts, - strm); + strm); return strm; } @@ -339,7 +338,7 @@ static pj_status_t handle_event(void *data) SDL_Event sevent; if (!pj_thread_is_registered()) - pj_thread_register("sdl_ev", sf->thread_desc, &sf->ev_thread); + pj_thread_register("sdl_ev", sf->thread_desc, &sf->ev_thread); while (SDL_PollEvent(&sevent)) { struct sdl_stream *strm = NULL; @@ -347,7 +346,7 @@ static pj_status_t handle_event(void *data) pj_mutex_lock(sf->mutex); pevent.type = PJMEDIA_EVENT_NONE; - switch(sevent.type) { + switch(sevent.type) { case SDL_MOUSEBUTTONDOWN: strm = find_stream(sf, sevent.button.windowID, &pevent); pevent.type = PJMEDIA_EVENT_MOUSE_BTN_DOWN; @@ -369,32 +368,32 @@ static pj_status_t handle_event(void *data) break; default: break; - } + } if (strm && pevent.type != PJMEDIA_EVENT_NONE) { pj_status_t status; - pjmedia_event_publish(NULL, strm, &pevent, 0); + pjmedia_event_publish(NULL, strm, &pevent, 0); - switch (pevent.type) { - case PJMEDIA_EVENT_WND_RESIZED: + switch (pevent.type) { + case PJMEDIA_EVENT_WND_RESIZED: status = resize_disp(strm, &pevent.data.wnd_resized.new_size); - if (status != PJ_SUCCESS) { + if (status != PJ_SUCCESS) { PJ_PERROR(3, (THIS_FILE, status, - "Failed resizing the display.")); - } - break; - case PJMEDIA_EVENT_WND_CLOSING: - if (pevent.data.wnd_closing.cancel) { - /* Cancel the closing operation */ - break; - } - - /* Proceed to cleanup SDL. App must still call - * pjmedia_dev_stream_destroy() when getting WND_CLOSED - * event - */ - sdl_stream_stop(&strm->base); + "Failed resizing the display.")); + } + break; + case PJMEDIA_EVENT_WND_CLOSING: + if (pevent.data.wnd_closing.cancel) { + /* Cancel the closing operation */ + break; + } + + /* Proceed to cleanup SDL. App must still call + * pjmedia_dev_stream_destroy() when getting WND_CLOSED + * event + */ + sdl_stream_stop(&strm->base); sdl_destroy_all(strm); pjmedia_event_init(&pevent, PJMEDIA_EVENT_WND_CLOSED, &strm->last_ts, strm); @@ -405,10 +404,10 @@ static pj_status_t handle_event(void *data) * might have been destroyed */ break; - default: - /* Just to prevent gcc warning about unused enums */ - break; - } + default: + /* Just to prevent gcc warning about unused enums */ + break; + } } pj_mutex_unlock(sf->mutex); @@ -470,17 +469,17 @@ static pj_status_t sdl_factory_init(pjmedia_vid_dev_factory *f) return status; status = pj_mutex_create_recursive(sf->pool, "sdl_factory", - &sf->mutex); + &sf->mutex); if (status != PJ_SUCCESS) - return status; + return status; status = pj_sem_create(sf->pool, NULL, 0, 1, &sf->sem); if (status != PJ_SUCCESS) - return status; + return status; /* Create event handler thread. */ status = pj_thread_create(sf->pool, "sdl_thread", sdl_ev_thread, - sf, 0, 0, &sf->sdl_thread); + sf, 0, 0, &sf->sdl_thread); if (status != PJ_SUCCESS) return status; @@ -489,8 +488,8 @@ static pj_status_t sdl_factory_init(pjmedia_vid_dev_factory *f) sf->dev_count++; #endif /* PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL */ sf->dev_info = (struct sdl_dev_info*) - pj_pool_calloc(sf->pool, sf->dev_count, - sizeof(struct sdl_dev_info)); + pj_pool_calloc(sf->pool, sf->dev_count, + sizeof(struct sdl_dev_info)); ddi = &sf->dev_info[0]; pj_bzero(ddi, sizeof(*ddi)); @@ -527,7 +526,7 @@ static pj_status_t sdl_factory_init(pjmedia_vid_dev_factory *f) SDL_VERSION(&version); PJ_LOG(4, (THIS_FILE, "SDL %d.%d initialized", - version.major, version.minor)); + version.major, version.minor)); return PJ_SUCCESS; } @@ -556,8 +555,8 @@ static pj_status_t sdl_factory_destroy(pjmedia_vid_dev_factory *f) } if (sf->mutex) { - pj_mutex_destroy(sf->mutex); - sf->mutex = NULL; + pj_mutex_destroy(sf->mutex); + sf->mutex = NULL; } if (sf->sem) { @@ -590,8 +589,8 @@ static unsigned sdl_factory_get_dev_count(pjmedia_vid_dev_factory *f) /* API: get device info */ static pj_status_t sdl_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info) + unsigned index, + pjmedia_vid_dev_info *info) { struct sdl_factory *sf = (struct sdl_factory*)f; @@ -605,8 +604,8 @@ static pj_status_t sdl_factory_get_dev_info(pjmedia_vid_dev_factory *f, /* API: create default device parameter */ static pj_status_t sdl_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param) + unsigned index, + pjmedia_vid_dev_param *param) { struct sdl_factory *sf = (struct sdl_factory*)f; struct sdl_dev_info *di = &sf->dev_info[index]; @@ -647,8 +646,8 @@ static pj_status_t sdl_destroy(void *data) #if PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL if (strm->texture) { - glDeleteTextures(1, &strm->texture); - strm->texture = 0; + glDeleteTextures(1, &strm->texture); + strm->texture = 0; } if (strm->gl_context) { SDL_GL_DeleteContext(strm->gl_context); @@ -683,9 +682,9 @@ static pj_status_t sdl_destroy_all(void *data) } static pj_status_t sdl_create_window(struct sdl_stream *strm, - pj_bool_t use_app_win, - Uint32 sdl_format, - pjmedia_vid_dev_hwnd *hwnd) + pj_bool_t use_app_win, + Uint32 sdl_format, + pjmedia_vid_dev_hwnd *hwnd) { if (!strm->window) { Uint32 flags = 0; @@ -711,23 +710,23 @@ static pj_status_t sdl_create_window(struct sdl_stream *strm, if ((strm->param.flags & PJMEDIA_VID_DEV_CAP_OUTPUT_FULLSCREEN) && strm->param.window_fullscreen) { - if (strm->param.window_fullscreen == PJMEDIA_VID_DEV_FULLSCREEN) - flags |= SDL_WINDOW_FULLSCREEN; - else - flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; + if (strm->param.window_fullscreen == PJMEDIA_VID_DEV_FULLSCREEN) + flags |= SDL_WINDOW_FULLSCREEN; + else + flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; } #if PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL if (strm->param.rend_id == OPENGL_DEV_IDX) flags |= SDL_WINDOW_OPENGL; -#endif /* PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL */ - if (use_app_win) { - /* Use the window supplied by the application. */ - strm->window = SDL_CreateWindowFrom(hwnd->info.window); - if (!strm->window) { - sdl_log_err("SDL_CreateWindowFrom()"); - return PJMEDIA_EVID_SYSERR; - } +#endif /* PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL */ + if (use_app_win) { + /* Use the window supplied by the application. */ + strm->window = SDL_CreateWindowFrom(hwnd->info.window); + if (!strm->window) { + sdl_log_err("SDL_CreateWindowFrom()"); + return PJMEDIA_EVID_SYSERR; + } } else { int x, y; @@ -743,10 +742,10 @@ static pj_status_t sdl_create_window(struct sdl_stream *strm, strm->param.disp_size.w, strm->param.disp_size.h, flags); - if (!strm->window) { - sdl_log_err("SDL_CreateWindow()"); - return PJMEDIA_EVID_SYSERR; - } + if (!strm->window) { + sdl_log_err("SDL_CreateWindow()"); + return PJMEDIA_EVID_SYSERR; + } } } @@ -756,7 +755,7 @@ static pj_status_t sdl_create_window(struct sdl_stream *strm, */ strm->renderer = SDL_CreateRenderer(strm->window, -1, 0); if (!strm->renderer) { - sdl_log_err("SDL_CreateRenderer()"); + sdl_log_err("SDL_CreateRenderer()"); return PJMEDIA_EVID_SYSERR; } @@ -770,24 +769,24 @@ static pj_status_t sdl_create_window(struct sdl_stream *strm, SDL_GL_MakeCurrent(strm->window, strm->gl_context); /* Init some OpenGL settings */ - glDisable(GL_DEPTH_TEST); - glDisable(GL_CULL_FACE); - glEnable(GL_TEXTURE_2D); - - /* Init the viewport */ - glViewport(0, 0, strm->param.disp_size.w, strm->param.disp_size.h); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - - glOrtho(0.0, (GLdouble)strm->param.disp_size.w, + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glEnable(GL_TEXTURE_2D); + + /* Init the viewport */ + glViewport(0, 0, strm->param.disp_size.w, strm->param.disp_size.h); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + + glOrtho(0.0, (GLdouble)strm->param.disp_size.w, (GLdouble)strm->param.disp_size.h, 0.0, 0.0, 1.0); - - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - - /* Create a texture */ - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); - glGenTextures(1, &strm->texture); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + /* Create a texture */ + glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); + glGenTextures(1, &strm->texture); if (!strm->texture) return PJMEDIA_EVID_SYSERR; @@ -842,13 +841,13 @@ static pj_status_t sdl_create_rend(struct sdl_stream * strm, #if PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL if (strm->param.rend_id == OPENGL_DEV_IDX) { - SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1); + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1); } #endif /* PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL */ return sdl_create_window(strm, - (strm->param.flags & PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW), - sdl_info->sdl_format, - &strm->param.window); + (strm->param.flags & PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW), + sdl_info->sdl_format, + &strm->param.window); } static pj_status_t sdl_create(void *data) @@ -866,12 +865,12 @@ static pj_status_t resize_disp(struct sdl_stream *strm, if (strm->scr_tex) { strm->dstrect.x = strm->dstrect.y = 0; strm->dstrect.w = (Uint16)strm->param.disp_size.w; - strm->dstrect.h = (Uint16)strm->param.disp_size.h; - SDL_RenderSetViewport(strm->renderer, &strm->dstrect); + strm->dstrect.h = (Uint16)strm->param.disp_size.h; + SDL_RenderSetViewport(strm->renderer, &strm->dstrect); } #if PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL else if (strm->param.rend_id == OPENGL_DEV_IDX) { - sdl_create_rend(strm, &strm->param.fmt); + sdl_create_rend(strm, &strm->param.fmt); } #endif /* PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL */ @@ -885,7 +884,7 @@ static pj_status_t change_format(struct sdl_stream *strm, /* Recreate SDL renderer */ status = sdl_create_rend(strm, (new_fmt? new_fmt : - &strm->param.fmt)); + &strm->param.fmt)); if (status == PJ_SUCCESS && new_fmt) pjmedia_format_copy(&strm->param.fmt, new_fmt); @@ -901,24 +900,24 @@ static pj_status_t put_frame(void *data) SDL_UpdateTexture(stream->scr_tex, NULL, frame->buf, stream->pitch); SDL_RenderClear(stream->renderer); SDL_RenderCopy(stream->renderer, stream->scr_tex, - &stream->rect, &stream->dstrect); + &stream->rect, &stream->dstrect); SDL_RenderPresent(stream->renderer); } #if PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL else if (stream->param.rend_id == OPENGL_DEV_IDX && stream->texture) { - glBindTexture(GL_TEXTURE_2D, stream->texture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, - stream->rect.w, stream->rect.h, 0, - GL_RGBA, GL_UNSIGNED_BYTE, frame->buf); - glBegin(GL_TRIANGLE_STRIP); - glTexCoord2f(0, 0); glVertex2i(0, 0); - glTexCoord2f(1, 0); glVertex2i(stream->param.disp_size.w, 0); - glTexCoord2f(0, 1); glVertex2i(0, stream->param.disp_size.h); - glTexCoord2f(1, 1); + glBindTexture(GL_TEXTURE_2D, stream->texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, + stream->rect.w, stream->rect.h, 0, + GL_RGBA, GL_UNSIGNED_BYTE, frame->buf); + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(0, 0); glVertex2i(0, 0); + glTexCoord2f(1, 0); glVertex2i(stream->param.disp_size.w, 0); + glTexCoord2f(0, 1); glVertex2i(0, stream->param.disp_size.h); + glTexCoord2f(1, 1); glVertex2i(stream->param.disp_size.w, stream->param.disp_size.h); - glEnd(); + glEnd(); SDL_GL_SwapWindow(stream->window); } #endif /* PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL */ @@ -928,7 +927,7 @@ static pj_status_t put_frame(void *data) /* API: Put frame from stream */ static pj_status_t sdl_stream_put_frame(pjmedia_vid_dev_stream *strm, - const pjmedia_frame *frame) + const pjmedia_frame *frame) { struct sdl_stream *stream = (struct sdl_stream*)strm; pj_status_t status; @@ -939,13 +938,13 @@ static pj_status_t sdl_stream_put_frame(pjmedia_vid_dev_stream *strm, * or keep-alive, this port doesn't need any, just ignore. */ if (frame->size==0 || frame->buf==NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; if (frame->size < stream->vafp.framebytes) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; if (!stream->is_running) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; stream->frame = frame; job_queue_post_job(stream->sf->jq, put_frame, strm, 0, &status); @@ -955,11 +954,11 @@ static pj_status_t sdl_stream_put_frame(pjmedia_vid_dev_stream *strm, /* API: create stream */ static pj_status_t sdl_factory_create_stream( - pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm) + pjmedia_vid_dev_factory *f, + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm) { struct sdl_factory *sf = (struct sdl_factory*)f; pj_pool_t *pool; @@ -1005,7 +1004,7 @@ static pj_status_t sdl_factory_create_stream( /* API: Get stream info. */ static pj_status_t sdl_stream_get_param(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_param *pi) + pjmedia_vid_dev_param *pi) { struct sdl_stream *strm = (struct sdl_stream*)s; @@ -1014,34 +1013,34 @@ static pj_status_t sdl_stream_get_param(pjmedia_vid_dev_stream *s, pj_memcpy(pi, &strm->param, sizeof(*pi)); if (sdl_stream_get_cap(s, PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW, - &pi->window) == PJ_SUCCESS) + &pi->window) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW; + pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW; } if (sdl_stream_get_cap(s, PJMEDIA_VID_DEV_CAP_OUTPUT_POSITION, - &pi->window_pos) == PJ_SUCCESS) + &pi->window_pos) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_POSITION; + pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_POSITION; } if (sdl_stream_get_cap(s, PJMEDIA_VID_DEV_CAP_OUTPUT_RESIZE, - &pi->disp_size) == PJ_SUCCESS) + &pi->disp_size) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_RESIZE; + pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_RESIZE; } if (sdl_stream_get_cap(s, PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE, - &pi->window_hide) == PJ_SUCCESS) + &pi->window_hide) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE; + pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE; } if (sdl_stream_get_cap(s, PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS, - &pi->window_flags) == PJ_SUCCESS) + &pi->window_flags) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS; + pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS; } if (sdl_stream_get_cap(s, PJMEDIA_VID_DEV_CAP_OUTPUT_FULLSCREEN, - &pi->window_fullscreen) == PJ_SUCCESS) + &pi->window_fullscreen) == PJ_SUCCESS) { - pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_FULLSCREEN; + pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_FULLSCREEN; } return PJ_SUCCESS; @@ -1065,72 +1064,72 @@ static pj_status_t get_cap(void *data) if (cap == PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW) { - SDL_SysWMinfo info; - SDL_VERSION(&info.version); + SDL_SysWMinfo info; + SDL_VERSION(&info.version); - if (SDL_GetWindowWMInfo(strm->window, &info)) { - pjmedia_vid_dev_hwnd *wnd = (pjmedia_vid_dev_hwnd *)pval; - if (0) { } + if (SDL_GetWindowWMInfo(strm->window, &info)) { + pjmedia_vid_dev_hwnd *wnd = (pjmedia_vid_dev_hwnd *)pval; + if (0) { } #if defined(SDL_VIDEO_DRIVER_WINDOWS) - else if (info.subsystem == SDL_SYSWM_WINDOWS) { - wnd->type = PJMEDIA_VID_DEV_HWND_TYPE_WINDOWS; - wnd->info.win.hwnd = (void *)info.info.win.window; - } + else if (info.subsystem == SDL_SYSWM_WINDOWS) { + wnd->type = PJMEDIA_VID_DEV_HWND_TYPE_WINDOWS; + wnd->info.win.hwnd = (void *)info.info.win.window; + } #endif #if defined(SDL_VIDEO_DRIVER_X11) - else if (info.subsystem == SDL_SYSWM_X11) { - wnd->info.x11.window = (void *)info.info.x11.window; - wnd->info.x11.display = (void *)info.info.x11.display; - } + else if (info.subsystem == SDL_SYSWM_X11) { + wnd->info.x11.window = (void *)info.info.x11.window; + wnd->info.x11.display = (void *)info.info.x11.display; + } #endif #if defined(SDL_VIDEO_DRIVER_COCOA) - else if (info.subsystem == SDL_SYSWM_COCOA) { - wnd->info.cocoa.window = (void *)info.info.cocoa.window; - } + else if (info.subsystem == SDL_SYSWM_COCOA) { + wnd->info.cocoa.window = (void *)info.info.cocoa.window; + } #endif #if defined(SDL_VIDEO_DRIVER_UIKIT) - else if (info.subsystem == SDL_SYSWM_UIKIT) { - wnd->info.ios.window = (void *)info.info.uikit.window; - } + else if (info.subsystem == SDL_SYSWM_UIKIT) { + wnd->info.ios.window = (void *)info.info.uikit.window; + } #endif - else { - return PJMEDIA_EVID_INVCAP; - } - return PJ_SUCCESS; - } else - return PJMEDIA_EVID_INVCAP; + else { + return PJMEDIA_EVID_INVCAP; + } + return PJ_SUCCESS; + } else + return PJMEDIA_EVID_INVCAP; } else if (cap == PJMEDIA_VID_DEV_CAP_OUTPUT_POSITION) { SDL_GetWindowPosition(strm->window, &((pjmedia_coord *)pval)->x, &((pjmedia_coord *)pval)->y); - return PJ_SUCCESS; + return PJ_SUCCESS; } else if (cap == PJMEDIA_VID_DEV_CAP_OUTPUT_RESIZE) { SDL_GetWindowSize(strm->window, (int *)&((pjmedia_rect_size *)pval)->w, (int *)&((pjmedia_rect_size *)pval)->h); - return PJ_SUCCESS; + return PJ_SUCCESS; } else if (cap == PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE) { - Uint32 flag = SDL_GetWindowFlags(strm->window); - *((pj_bool_t *)pval) = (flag & SDL_WINDOW_HIDDEN)? PJ_TRUE: PJ_FALSE; - return PJ_SUCCESS; + Uint32 flag = SDL_GetWindowFlags(strm->window); + *((pj_bool_t *)pval) = (flag & SDL_WINDOW_HIDDEN)? PJ_TRUE: PJ_FALSE; + return PJ_SUCCESS; } else if (cap == PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS) { - Uint32 flag = SDL_GetWindowFlags(strm->window); + Uint32 flag = SDL_GetWindowFlags(strm->window); unsigned *wnd_flags = (unsigned *)pval; if (!(flag & SDL_WINDOW_BORDERLESS)) *wnd_flags |= PJMEDIA_VID_DEV_WND_BORDER; if (flag & SDL_WINDOW_RESIZABLE) *wnd_flags |= PJMEDIA_VID_DEV_WND_RESIZABLE; - return PJ_SUCCESS; + return PJ_SUCCESS; } else if (cap == PJMEDIA_VID_DEV_CAP_OUTPUT_FULLSCREEN) { - Uint32 flag = SDL_GetWindowFlags(strm->window); - pjmedia_vid_dev_fullscreen_flag val = PJMEDIA_VID_DEV_WINDOWED; - if ((flag & SDL_WINDOW_FULLSCREEN_DESKTOP) == - SDL_WINDOW_FULLSCREEN_DESKTOP) - { - val = PJMEDIA_VID_DEV_FULLSCREEN_DESKTOP; - } else if ((flag & SDL_WINDOW_FULLSCREEN) == SDL_WINDOW_FULLSCREEN) { - val = PJMEDIA_VID_DEV_FULLSCREEN; - } - *((pjmedia_vid_dev_fullscreen_flag*)pval) = val; - return PJ_SUCCESS; + Uint32 flag = SDL_GetWindowFlags(strm->window); + pjmedia_vid_dev_fullscreen_flag val = PJMEDIA_VID_DEV_WINDOWED; + if ((flag & SDL_WINDOW_FULLSCREEN_DESKTOP) == + SDL_WINDOW_FULLSCREEN_DESKTOP) + { + val = PJMEDIA_VID_DEV_FULLSCREEN_DESKTOP; + } else if ((flag & SDL_WINDOW_FULLSCREEN) == SDL_WINDOW_FULLSCREEN) { + val = PJMEDIA_VID_DEV_FULLSCREEN; + } + *((pjmedia_vid_dev_fullscreen_flag*)pval) = val; + return PJ_SUCCESS; } return PJMEDIA_EVID_INVCAP; @@ -1138,8 +1137,8 @@ static pj_status_t get_cap(void *data) /* API: get capability */ static pj_status_t sdl_stream_get_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - void *pval) + pjmedia_vid_dev_cap cap, + void *pval) { struct sdl_stream *strm = (struct sdl_stream*)s; struct strm_cap scap; @@ -1171,102 +1170,102 @@ static pj_status_t set_cap(void *data) * the window's visibility. * See ticket #1429 (https://github.com/pjsip/pjproject/issues/1429) */ - Uint32 flag = SDL_GetWindowFlags(strm->window); - if (flag & SDL_WINDOW_HIDDEN) + Uint32 flag = SDL_GetWindowFlags(strm->window); + if (flag & SDL_WINDOW_HIDDEN) SDL_ShowWindow(strm->window); SDL_SetWindowPosition(strm->window, ((pjmedia_coord *)pval)->x, ((pjmedia_coord *)pval)->y); - if (flag & SDL_WINDOW_HIDDEN) + if (flag & SDL_WINDOW_HIDDEN) SDL_HideWindow(strm->window); - return PJ_SUCCESS; + return PJ_SUCCESS; } else if (cap == PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE) { if (*(pj_bool_t *)pval) SDL_HideWindow(strm->window); else SDL_ShowWindow(strm->window); - return PJ_SUCCESS; + return PJ_SUCCESS; } else if (cap == PJMEDIA_VID_DEV_CAP_FORMAT) { pj_status_t status; status = change_format(strm, (pjmedia_format *)pval); - if (status != PJ_SUCCESS) { - pj_status_t status_; - - /** - * Failed to change the output format. Try to revert - * to its original format. - */ + if (status != PJ_SUCCESS) { + pj_status_t status_; + + /** + * Failed to change the output format. Try to revert + * to its original format. + */ status_ = change_format(strm, &strm->param.fmt); - if (status_ != PJ_SUCCESS) { - /** - * This means that we failed to revert to our - * original state! - */ - status = PJMEDIA_EVID_ERR; - } - } - - return status; + if (status_ != PJ_SUCCESS) { + /** + * This means that we failed to revert to our + * original state! + */ + status = PJMEDIA_EVID_ERR; + } + } + + return status; } else if (cap == PJMEDIA_VID_DEV_CAP_OUTPUT_RESIZE) { - pjmedia_rect_size *new_size = (pjmedia_rect_size *)pval; - Uint32 flag = SDL_GetWindowFlags(strm->window); - pj_status_t status; + pjmedia_rect_size *new_size = (pjmedia_rect_size *)pval; + Uint32 flag = SDL_GetWindowFlags(strm->window); + pj_status_t status; - /** - * Exit full-screen if engaged, since resizing while in full-screen is + /** + * Exit full-screen if engaged, since resizing while in full-screen is * not supported. - */ - if (flag & SDL_WINDOW_FULLSCREEN_DESKTOP) - SDL_SetWindowFullscreen(strm->window, 0); + */ + if (flag & SDL_WINDOW_FULLSCREEN_DESKTOP) + SDL_SetWindowFullscreen(strm->window, 0); - SDL_SetWindowSize(strm->window, new_size->w, new_size->h); - status = resize_disp(strm, new_size); + SDL_SetWindowSize(strm->window, new_size->w, new_size->h); + status = resize_disp(strm, new_size); - /* Restore full-screen if it was engaged. */ - if (flag & SDL_WINDOW_FULLSCREEN_DESKTOP) - SDL_SetWindowFullscreen(strm->window, SDL_WINDOW_FULLSCREEN_DESKTOP); + /* Restore full-screen if it was engaged. */ + if (flag & SDL_WINDOW_FULLSCREEN_DESKTOP) + SDL_SetWindowFullscreen(strm->window, SDL_WINDOW_FULLSCREEN_DESKTOP); - return status; + return status; } else if (cap == PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW) { - pjmedia_vid_dev_hwnd *hwnd = (pjmedia_vid_dev_hwnd*)pval; - pj_status_t status = PJ_SUCCESS; - sdl_fmt_info *sdl_info = get_sdl_format_info(strm->param.fmt.id); - /* Re-init SDL */ - status = sdl_destroy_all(strm); - if (status != PJ_SUCCESS) - return status; - - status = sdl_create_window(strm, PJ_TRUE, sdl_info->sdl_format, hwnd); + pjmedia_vid_dev_hwnd *hwnd = (pjmedia_vid_dev_hwnd*)pval; + pj_status_t status = PJ_SUCCESS; + sdl_fmt_info *sdl_info = get_sdl_format_info(strm->param.fmt.id); + /* Re-init SDL */ + status = sdl_destroy_all(strm); + if (status != PJ_SUCCESS) + return status; + + status = sdl_create_window(strm, PJ_TRUE, sdl_info->sdl_format, hwnd); PJ_PERROR(4, (THIS_FILE, status, - "Re-initializing SDL with native window %d", - hwnd->info.window)); - return status; + "Re-initializing SDL with native window %d", + hwnd->info.window)); + return status; } else if (cap == PJMEDIA_VID_DEV_CAP_OUTPUT_FULLSCREEN) { Uint32 flag; - pjmedia_vid_dev_fullscreen_flag val = - *(pjmedia_vid_dev_fullscreen_flag*)pval; + pjmedia_vid_dev_fullscreen_flag val = + *(pjmedia_vid_dev_fullscreen_flag*)pval; - flag = SDL_GetWindowFlags(strm->window); - if (val == PJMEDIA_VID_DEV_FULLSCREEN_DESKTOP) - flag |= SDL_WINDOW_FULLSCREEN_DESKTOP; - else if (val == PJMEDIA_VID_DEV_FULLSCREEN) + flag = SDL_GetWindowFlags(strm->window); + if (val == PJMEDIA_VID_DEV_FULLSCREEN_DESKTOP) + flag |= SDL_WINDOW_FULLSCREEN_DESKTOP; + else if (val == PJMEDIA_VID_DEV_FULLSCREEN) flag |= SDL_WINDOW_FULLSCREEN; else flag &= (~SDL_WINDOW_FULLSCREEN_DESKTOP); SDL_SetWindowFullscreen(strm->window, flag); - /* Trying to restore the border after returning from fullscreen, - * unfortunately not sure how to put back the resizable flag. - */ - if ((flag & SDL_WINDOW_FULLSCREEN)==0 && - (flag & SDL_WINDOW_BORDERLESS)==0) - { - SDL_SetWindowBordered(strm->window, SDL_FALSE); - SDL_SetWindowBordered(strm->window, SDL_TRUE); - } - - return PJ_SUCCESS; + /* Trying to restore the border after returning from fullscreen, + * unfortunately not sure how to put back the resizable flag. + */ + if ((flag & SDL_WINDOW_FULLSCREEN)==0 && + (flag & SDL_WINDOW_BORDERLESS)==0) + { + SDL_SetWindowBordered(strm->window, SDL_FALSE); + SDL_SetWindowBordered(strm->window, SDL_TRUE); + } + + return PJ_SUCCESS; } return PJMEDIA_EVID_INVCAP; @@ -1274,8 +1273,8 @@ static pj_status_t set_cap(void *data) /* API: set capability */ static pj_status_t sdl_stream_set_cap(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_cap cap, - const void *pval) + pjmedia_vid_dev_cap cap, + const void *pval) { struct sdl_stream *strm = (struct sdl_stream*)s; struct strm_cap scap; @@ -1334,7 +1333,7 @@ static pj_status_t sdl_stream_destroy(pjmedia_vid_dev_stream *strm) pj_mutex_lock(stream->sf->mutex); if (!pj_list_empty(&stream->list_entry)) - pj_list_erase(&stream->list_entry); + pj_list_erase(&stream->list_entry); pj_mutex_unlock(stream->sf->mutex); pj_pool_release(stream->pool); @@ -1353,7 +1352,7 @@ static int job_thread(void * data) while (1) { job *jb; - /* Wait until there is a job. */ + /* Wait until there is a job. */ pj_sem_wait(jq->sem); /* Make sure there is no pending jobs before we quit. */ @@ -1383,7 +1382,7 @@ static int job_thread(void * data) &jq->sem); if (status != PJ_SUCCESS) { PJ_PERROR(3, (THIS_FILE, status, - "Failed growing SDL job queue size.")); + "Failed growing SDL job queue size.")); return 0; } jq->jobs = (job **)pj_pool_calloc(jq->pool, jq->size, @@ -1395,7 +1394,7 @@ static int job_thread(void * data) &jq->job_sem[i]); if (status != PJ_SUCCESS) { PJ_PERROR(3, (THIS_FILE, status, - "Failed growing SDL job queue size.")); + "Failed growing SDL job queue size.")); return 0; } } @@ -1455,8 +1454,8 @@ static pj_status_t job_queue_create(pj_pool_t *pool, job_queue **pjq) } static pj_status_t job_queue_post_job(job_queue *jq, job_func_ptr func, - void *data, unsigned flags, - pj_status_t *retval) + void *data, unsigned flags, + pj_status_t *retval) { job jb; int tail; @@ -1474,7 +1473,7 @@ static pj_status_t job_queue_post_job(job_queue *jq, job_func_ptr func, JQDelegate *jqd = [[JQDelegate alloc]init]; jqd->pjob = &jb; [jqd performSelectorOnMainThread:@selector(run_job) - withObject:nil waitUntilDone:YES]; + withObject:nil waitUntilDone:YES]; [jqd release]; [apool release]; #else /* PJ_DARWINOS */ @@ -1483,7 +1482,7 @@ static pj_status_t job_queue_post_job(job_queue *jq, job_func_ptr func, tail = jq->tail; jq->tail = (jq->tail + 1) % jq->size; if (jq->tail == jq->head) { - jq->is_full = PJ_TRUE; + jq->is_full = PJ_TRUE; PJ_LOG(4, (THIS_FILE, "SDL job queue is full, increasing " "the queue size.")); pj_sem_post(jq->sem); @@ -1543,16 +1542,16 @@ static pj_status_t job_queue_destroy(job_queue *jq) #ifdef _MSC_VER # if defined(PJMEDIA_SDL_LIB) -# pragma comment( lib, PJMEDIA_SDL_LIB) +# pragma comment( lib, PJMEDIA_SDL_LIB) # elif SDL_VERSION_ATLEAST(2,0,0) -# pragma comment( lib, "sdl2.lib") +# pragma comment( lib, "sdl2.lib") # elif SDL_VERSION_ATLEAST(1,3,0) -# pragma comment( lib, "sdl.lib") +# pragma comment( lib, "sdl.lib") # endif # if PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL -# pragma comment(lib, "OpenGL32.lib") +# pragma comment(lib, "OpenGL32.lib") # endif /* PJMEDIA_VIDEO_DEV_SDL_HAS_OPENGL */ #endif /* _MSC_VER */ -#endif /* PJMEDIA_VIDEO_DEV_HAS_SDL */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_SDL */ diff --git a/pjmedia/src/pjmedia-videodev/sdl_dev_m.m b/pjmedia/src/pjmedia-videodev/sdl_dev_m.m index 566bf31e70..d61b095586 100644 --- a/pjmedia/src/pjmedia-videodev/sdl_dev_m.m +++ b/pjmedia/src/pjmedia-videodev/sdl_dev_m.m @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjmedia/src/pjmedia-videodev/util.c b/pjmedia/src/pjmedia-videodev/util.c index 334f65f893..5c36af1b7c 100644 --- a/pjmedia/src/pjmedia-videodev/util.c +++ b/pjmedia/src/pjmedia-videodev/util.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2014-2015 Teluu Inc. (http://www.teluu.com) * @@ -32,20 +31,20 @@ #define HAS_ROTATION 0 #endif -#define THIS_FILE "vid_util.c" +#define THIS_FILE "vid_util.c" pj_status_t pjmedia_vid_dev_conv_create_converter(pjmedia_vid_dev_conv *conv, - pj_pool_t *pool, - pjmedia_format *fmt, - pjmedia_rect_size src_size, - pjmedia_rect_size dst_size, - pj_bool_t handle_rotation, - pj_bool_t maintain_aspect_ratio) + pj_pool_t *pool, + pjmedia_format *fmt, + pjmedia_rect_size src_size, + pjmedia_rect_size dst_size, + pj_bool_t handle_rotation, + pj_bool_t maintain_aspect_ratio) { pj_status_t status; pjmedia_conversion_param conv_param; - const pjmedia_video_format_info *vfi; + const pjmedia_video_format_info *vfi; pj_assert((src_size.w == dst_size.w || src_size.h == dst_size.h) || (src_size.w == dst_size.h || src_size.h == dst_size.w)); @@ -62,7 +61,7 @@ pjmedia_vid_dev_conv_create_converter(pjmedia_vid_dev_conv *conv, if (handle_rotation) { #if !HAS_ROTATION - return PJ_ENOTSUP; + return PJ_ENOTSUP; #endif } @@ -101,20 +100,20 @@ pjmedia_vid_dev_conv_create_converter(pjmedia_vid_dev_conv *conv, conv->maintain_aspect_ratio = maintain_aspect_ratio; if (maintain_aspect_ratio) { conv->fit_to_h = (dst_size.w >= dst_size.h? PJ_TRUE: PJ_FALSE); - if (conv->fit_to_h) { /* Fit to height */ - conv->rot_size.h = dst_size.h; - conv->rot_size.w = dst_size.h * dst_size.h / dst_size.w; - /* Make sure the width difference is divisible by four - * so we can have equal padding left and right. - */ - conv->rot_size.w += (dst_size.w - conv->rot_size.w) % 4; - conv->pad = (conv->dst_size.w - conv->rot_size.w) / 2; - } else { /* Fit to width */ - conv->rot_size.w = dst_size.w; - conv->rot_size.h = dst_size.w * dst_size.w / dst_size.h; - conv->rot_size.h += (dst_size.h - conv->rot_size.h) % 4; - conv->pad = (conv->dst_size.h - conv->rot_size.h) / 2; - } + if (conv->fit_to_h) { /* Fit to height */ + conv->rot_size.h = dst_size.h; + conv->rot_size.w = dst_size.h * dst_size.h / dst_size.w; + /* Make sure the width difference is divisible by four + * so we can have equal padding left and right. + */ + conv->rot_size.w += (dst_size.w - conv->rot_size.w) % 4; + conv->pad = (conv->dst_size.w - conv->rot_size.w) / 2; + } else { /* Fit to width */ + conv->rot_size.w = dst_size.w; + conv->rot_size.h = dst_size.w * dst_size.w / dst_size.h; + conv->rot_size.h += (dst_size.h - conv->rot_size.h) % 4; + conv->pad = (conv->dst_size.h - conv->rot_size.h) / 2; + } } else { conv->rot_size = dst_size; } @@ -128,9 +127,9 @@ pjmedia_vid_dev_conv_create_converter(pjmedia_vid_dev_conv *conv, * For example: 352x288 will be converted to 288x236 */ pj_size_t long_s = (conv->rot_size.h > conv->rot_size.w? - conv->rot_size.h: conv->rot_size.w); + conv->rot_size.h: conv->rot_size.w); pj_size_t short_s = (conv->rot_size.h > conv->rot_size.w? - conv->rot_size.w: conv->rot_size.h); + conv->rot_size.w: conv->rot_size.h); if (src_size.w > src_size.h) { conv->res_size.w = long_s; conv->res_size.h = short_s; @@ -149,14 +148,14 @@ pjmedia_vid_dev_conv_create_converter(pjmedia_vid_dev_conv *conv, conv_param.dst.det.vid.size = conv->res_size; } else { conv->res_size = conv->rot_size; - conv_param.dst.det.vid.size = conv->rot_size; + conv_param.dst.det.vid.size = conv->rot_size; } status = pjmedia_converter_create(NULL, pool, &conv_param, - &conv->conv); + &conv->conv); if (status != PJ_SUCCESS) { - PJ_LOG(3, (THIS_FILE, "Error creating converter")); - return status; + PJ_LOG(3, (THIS_FILE, "Error creating converter")); + return status; } vfi = pjmedia_get_video_format_info(NULL, fmt->id); @@ -165,31 +164,31 @@ pjmedia_vid_dev_conv_create_converter(pjmedia_vid_dev_conv *conv, conv->wxh = conv->dst_size.w * conv->dst_size.h; conv->src_frame_size = dst_size.w * dst_size.h * vfi->bpp / 8; conv->conv_frame_size = conv->rot_size.w * conv->rot_size.h * - vfi->bpp / 8; + vfi->bpp / 8; conv->conv_buf = pj_pool_alloc(pool, conv->src_frame_size); pjmedia_vid_dev_conv_set_rotation(conv, PJMEDIA_ORIENT_NATURAL); PJ_LOG(4, (THIS_FILE, "Orientation converter created: %dx%d to %dx%d, " - "maintain aspect ratio=%s", - conv_param.src.det.vid.size.w, - conv_param.src.det.vid.size.h, - conv_param.dst.det.vid.size.w, - conv_param.dst.det.vid.size.h, - maintain_aspect_ratio? "yes": "no")); - + "maintain aspect ratio=%s", + conv_param.src.det.vid.size.w, + conv_param.src.det.vid.size.h, + conv_param.dst.det.vid.size.w, + conv_param.dst.det.vid.size.h, + maintain_aspect_ratio? "yes": "no")); + return PJ_SUCCESS; } void pjmedia_vid_dev_conv_set_rotation(pjmedia_vid_dev_conv *conv, - pjmedia_orient rotation) + pjmedia_orient rotation) { pjmedia_rect_size new_size = conv->src_size; conv->rotation = rotation; if (rotation == PJMEDIA_ORIENT_ROTATE_90DEG || - rotation == PJMEDIA_ORIENT_ROTATE_270DEG) + rotation == PJMEDIA_ORIENT_ROTATE_270DEG) { new_size.w = conv->src_size.h; new_size.h = conv->src_size.w; @@ -211,8 +210,8 @@ void pjmedia_vid_dev_conv_set_rotation(pjmedia_vid_dev_conv *conv, } pj_status_t pjmedia_vid_dev_conv_resize_and_rotate(pjmedia_vid_dev_conv *conv, - void *src_buf, - void **result) + void *src_buf, + void **result) { #define swap(a, b) {pj_uint8_t *c = a; a = b; b = c;} @@ -228,13 +227,13 @@ pj_status_t pjmedia_vid_dev_conv_resize_and_rotate(pjmedia_vid_dev_conv *conv, if (!conv->match_src_dst) { /* We need to resize. */ - src_frame.buf = src; - dst_frame.buf = dst; - src_frame.size = conv->src_frame_size; - dst_frame.size = conv->conv_frame_size; + src_frame.buf = src; + dst_frame.buf = dst; + src_frame.size = conv->src_frame_size; + dst_frame.size = conv->conv_frame_size; - status = pjmedia_converter_convert(conv->conv, &src_frame, &dst_frame); - if (status != PJ_SUCCESS) { + status = pjmedia_converter_convert(conv->conv, &src_frame, &dst_frame); + if (status != PJ_SUCCESS) { PJ_LOG(3, (THIS_FILE, "Failed to convert frame")); return status; } @@ -246,58 +245,58 @@ pj_status_t pjmedia_vid_dev_conv_resize_and_rotate(pjmedia_vid_dev_conv *conv, if (conv->handle_rotation && conv->rotation != PJMEDIA_ORIENT_NATURAL) { /* We need to do rotation. */ - if (conv->fmt.id == PJMEDIA_FORMAT_I420) { - pjmedia_rect_size dst_size = src_size; - pj_size_t p_len = src_size.w * src_size.h; - - if (conv->rotation == PJMEDIA_ORIENT_ROTATE_90DEG || - conv->rotation == PJMEDIA_ORIENT_ROTATE_270DEG) - { - dst_size.w = src_size.h; - dst_size.h = src_size.w; - } - + if (conv->fmt.id == PJMEDIA_FORMAT_I420) { + pjmedia_rect_size dst_size = src_size; + pj_size_t p_len = src_size.w * src_size.h; + + if (conv->rotation == PJMEDIA_ORIENT_ROTATE_90DEG || + conv->rotation == PJMEDIA_ORIENT_ROTATE_270DEG) + { + dst_size.w = src_size.h; + dst_size.h = src_size.w; + } + #if defined(PJMEDIA_HAS_LIBYUV) && PJMEDIA_HAS_LIBYUV != 0 - enum RotationMode mode; - - switch (conv->rotation) { - case PJMEDIA_ORIENT_ROTATE_90DEG: - mode = kRotate90; - break; - case PJMEDIA_ORIENT_ROTATE_180DEG: - mode = kRotate180; - break; - case PJMEDIA_ORIENT_ROTATE_270DEG: - mode = kRotate270; - break; - default: - mode = kRotate0; - } + enum RotationMode mode; + + switch (conv->rotation) { + case PJMEDIA_ORIENT_ROTATE_90DEG: + mode = kRotate90; + break; + case PJMEDIA_ORIENT_ROTATE_180DEG: + mode = kRotate180; + break; + case PJMEDIA_ORIENT_ROTATE_270DEG: + mode = kRotate270; + break; + default: + mode = kRotate0; + } - I420Rotate(src, src_size.w, - src+p_len, src_size.w/2, - src+p_len+p_len/4, src_size.w/2, - dst, dst_size.w, - dst+p_len, dst_size.w/2, - dst+p_len+p_len/4, dst_size.w/2, - src_size.w, src_size.h, mode); - - swap(src, dst); + I420Rotate(src, src_size.w, + src+p_len, src_size.w/2, + src+p_len+p_len/4, src_size.w/2, + dst, dst_size.w, + dst+p_len, dst_size.w/2, + dst+p_len+p_len/4, dst_size.w/2, + src_size.w, src_size.h, mode); + + swap(src, dst); #else - PJ_UNUSED_ARG(p_len); - PJ_UNUSED_ARG(dst_size); + PJ_UNUSED_ARG(p_len); + PJ_UNUSED_ARG(dst_size); #endif - } + } } if (!conv->match_src_dst && conv->maintain_aspect_ratio) { - /* Center the frame and fill the area with black color */ + /* Center the frame and fill the area with black color */ if (conv->fmt.id == PJMEDIA_FORMAT_I420) { - unsigned i = 0; - pj_uint8_t *pdst = dst; - pj_uint8_t *psrc = src; + unsigned i = 0; + pj_uint8_t *pdst = dst; + pj_uint8_t *psrc = src; pj_size_t p_len_src = 0, p_len_dst = conv->wxh; - int pad = conv->pad; + int pad = conv->pad; pj_bzero(pdst, p_len_dst); @@ -318,13 +317,13 @@ pj_status_t pjmedia_vid_dev_conv_resize_and_rotate(pjmedia_vid_dev_conv *conv, pdst += p_len_dst; } - /* Fill the U&V components with 0x80 to make it black. - * Bzero-ing will make the area look green instead. - */ - pj_memset(pdst, 0x80, p_len_dst/2); - pad /= 2; + /* Fill the U&V components with 0x80 to make it black. + * Bzero-ing will make the area look green instead. + */ + pj_memset(pdst, 0x80, p_len_dst/2); + pad /= 2; if (conv->fit_to_h) { - p_len_src = conv->rot_size.w / 2; + p_len_src = conv->rot_size.w / 2; for (i = conv->dst_size.h; i > 0; --i) { pdst += pad; pj_memcpy(pdst, psrc, p_len_src); @@ -336,7 +335,7 @@ pj_status_t pjmedia_vid_dev_conv_resize_and_rotate(pjmedia_vid_dev_conv *conv, pj_uint8_t *U, *V; pj_size_t gap = conv->rot_size.w * pad / 2; - p_len_src /= 4; + p_len_src /= 4; U = pdst; V = U + p_len_dst/4; @@ -346,7 +345,7 @@ pj_status_t pjmedia_vid_dev_conv_resize_and_rotate(pjmedia_vid_dev_conv *conv, } swap(src, dst); - } + } } *result = src; diff --git a/pjmedia/src/pjmedia-videodev/util.h b/pjmedia/src/pjmedia-videodev/util.h index e0b8b21a14..f34344dbbd 100644 --- a/pjmedia/src/pjmedia-videodev/util.h +++ b/pjmedia/src/pjmedia-videodev/util.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2014-2015 Teluu Inc. (http://www.teluu.com) * @@ -29,24 +28,24 @@ typedef struct pjmedia_vid_dev_conv { - pjmedia_converter *conv; - pjmedia_format fmt; - pjmedia_rect_size src_size; - pjmedia_rect_size dst_size; - pjmedia_rect_size res_size; /* Size after resizing */ - pjmedia_orient rotation; - pjmedia_rect_size rot_size; /* Size after rotation */ + pjmedia_converter *conv; + pjmedia_format fmt; + pjmedia_rect_size src_size; + pjmedia_rect_size dst_size; + pjmedia_rect_size res_size; /* Size after resizing */ + pjmedia_orient rotation; + pjmedia_rect_size rot_size; /* Size after rotation */ - void *conv_buf; - pj_size_t src_frame_size; - pj_size_t conv_frame_size; + void *conv_buf; + pj_size_t src_frame_size; + pj_size_t conv_frame_size; - pj_bool_t fit_to_h; - pj_bool_t handle_rotation; - pj_bool_t maintain_aspect_ratio; - pj_bool_t match_src_dst; - pj_int32_t pad; - pj_size_t wxh; + pj_bool_t fit_to_h; + pj_bool_t handle_rotation; + pj_bool_t maintain_aspect_ratio; + pj_bool_t match_src_dst; + pj_int32_t pad; + pj_size_t wxh; } pjmedia_vid_dev_conv; /** @@ -74,21 +73,21 @@ typedef struct pjmedia_vid_dev_conv */ pj_status_t pjmedia_vid_dev_conv_create_converter(pjmedia_vid_dev_conv *conv, - pj_pool_t *pool, - pjmedia_format *fmt, - pjmedia_rect_size src_size, - pjmedia_rect_size dst_size, - pj_bool_t handle_rotation, - pj_bool_t maintain_aspect_ratio); + pj_pool_t *pool, + pjmedia_format *fmt, + pjmedia_rect_size src_size, + pjmedia_rect_size dst_size, + pj_bool_t handle_rotation, + pj_bool_t maintain_aspect_ratio); /* Set rotation */ void pjmedia_vid_dev_conv_set_rotation(pjmedia_vid_dev_conv *conv, - pjmedia_orient rotation); + pjmedia_orient rotation); /* Resize the buffer and rotate it, if necessary */ pj_status_t pjmedia_vid_dev_conv_resize_and_rotate(pjmedia_vid_dev_conv *conv, - void *src_buf, - void **result); + void *src_buf, + void **result); /* Destroy converter */ void pjmedia_vid_dev_conv_destroy_converter(pjmedia_vid_dev_conv *conv); diff --git a/pjmedia/src/pjmedia-videodev/v4l2_dev.c b/pjmedia/src/pjmedia-videodev/v4l2_dev.c index 24f3d2452d..d1ac856236 100644 --- a/pjmedia/src/pjmedia-videodev/v4l2_dev.c +++ b/pjmedia/src/pjmedia-videodev/v4l2_dev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -34,23 +33,23 @@ #include #include -#define THIS_FILE "v4l2_dev.c" -#define DRIVER_NAME "v4l2" -#define V4L2_MAX_DEVS 4 -#define DEFAULT_WIDTH 640 -#define DEFAULT_HEIGHT 480 -#define DEFAULT_FPS 25 -#define DEFAULT_CLOCK_RATE 90000 -#define INVALID_FD -1 -#define BUFFER_CNT 2 -#define MAX_IOCTL_RETRY 20 +#define THIS_FILE "v4l2_dev.c" +#define DRIVER_NAME "v4l2" +#define V4L2_MAX_DEVS 4 +#define DEFAULT_WIDTH 640 +#define DEFAULT_HEIGHT 480 +#define DEFAULT_FPS 25 +#define DEFAULT_CLOCK_RATE 90000 +#define INVALID_FD -1 +#define BUFFER_CNT 2 +#define MAX_IOCTL_RETRY 20 /* mapping between pjmedia_fmt_id and v4l2 pixel format */ typedef struct vid4lin_fmt_map { pj_uint32_t pjmedia_fmt_id; - pj_uint32_t v4l2_fmt_id; + pj_uint32_t v4l2_fmt_id; } vid4lin_fmt_map; /* I/O type being used */ @@ -72,51 +71,51 @@ typedef struct vid4lin_buffer /* v4l2 device info */ typedef struct vid4lin_dev_info { - pjmedia_vid_dev_info info; - char dev_name[32]; - struct v4l2_capability v4l2_cap; + pjmedia_vid_dev_info info; + char dev_name[32]; + struct v4l2_capability v4l2_cap; } vid4lin_dev_info; /* v4l2 factory */ typedef struct vid4lin_factory { - pjmedia_vid_dev_factory base; - pj_pool_t *pool; - pj_pool_t *dev_pool; - pj_pool_factory *pf; + pjmedia_vid_dev_factory base; + pj_pool_t *pool; + pj_pool_t *dev_pool; + pj_pool_factory *pf; - unsigned dev_count; - vid4lin_dev_info *dev_info; + unsigned dev_count; + vid4lin_dev_info *dev_info; } vid4lin_factory; /* Video stream. */ typedef struct vid4lin_stream { - pjmedia_vid_dev_stream base; /**< Base stream */ - pjmedia_vid_dev_param param; /**< Settings */ - pj_pool_t *pool; /**< Memory pool. */ + pjmedia_vid_dev_stream base; /**< Base stream */ + pjmedia_vid_dev_param param; /**< Settings */ + pj_pool_t *pool; /**< Memory pool. */ - int fd; /**< Video fd. */ - char name[64]; /**< Name for log */ - enum vid4lin_io_type io_type; /**< I/O method. */ - unsigned buf_cnt; /**< MMap buf cnt. */ - vid4lin_buffer *buffers; /**< MMap buffers. */ - pj_time_val start_time; /**< Time when started */ + int fd; /**< Video fd. */ + char name[64]; /**< Name for log */ + enum vid4lin_io_type io_type; /**< I/O method. */ + unsigned buf_cnt; /**< MMap buf cnt. */ + vid4lin_buffer *buffers; /**< MMap buffers. */ + pj_time_val start_time; /**< Time when started */ - pjmedia_vid_dev_cb vid_cb; /**< Stream callback */ - void *user_data; /**< Application data */ + pjmedia_vid_dev_cb vid_cb; /**< Stream callback */ + void *user_data; /**< Application data */ } vid4lin_stream; /* Use this to convert between pjmedia_format_id and V4L2 fourcc */ static vid4lin_fmt_map v4l2_fmt_maps[] = { - { PJMEDIA_FORMAT_RGB24, V4L2_PIX_FMT_BGR24 }, - { PJMEDIA_FORMAT_RGBA, V4L2_PIX_FMT_BGR32 }, - { PJMEDIA_FORMAT_RGB32, V4L2_PIX_FMT_BGR32 }, - { PJMEDIA_FORMAT_AYUV, V4L2_PIX_FMT_YUV32 }, - { PJMEDIA_FORMAT_YUY2, V4L2_PIX_FMT_YUYV }, - { PJMEDIA_FORMAT_UYVY, V4L2_PIX_FMT_UYVY }, - { PJMEDIA_FORMAT_I420, V4L2_PIX_FMT_YUV420 } + { PJMEDIA_FORMAT_RGB24, V4L2_PIX_FMT_BGR24 }, + { PJMEDIA_FORMAT_RGBA, V4L2_PIX_FMT_BGR32 }, + { PJMEDIA_FORMAT_RGB32, V4L2_PIX_FMT_BGR32 }, + { PJMEDIA_FORMAT_AYUV, V4L2_PIX_FMT_YUV32 }, + { PJMEDIA_FORMAT_YUY2, V4L2_PIX_FMT_YUYV }, + { PJMEDIA_FORMAT_UYVY, V4L2_PIX_FMT_UYVY }, + { PJMEDIA_FORMAT_I420, V4L2_PIX_FMT_YUV420 } }; /* Prototypes */ @@ -125,26 +124,26 @@ static pj_status_t vid4lin_factory_destroy(pjmedia_vid_dev_factory *f); static pj_status_t vid4lin_factory_refresh(pjmedia_vid_dev_factory *f); static unsigned vid4lin_factory_get_dev_count(pjmedia_vid_dev_factory *f); static pj_status_t vid4lin_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info); + unsigned index, + pjmedia_vid_dev_info *info); static pj_status_t vid4lin_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_param *param); + unsigned index, + pjmedia_vid_dev_param *param); static pj_status_t vid4lin_factory_create_stream(pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *prm, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p); + pjmedia_vid_dev_param *prm, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p); static pj_status_t vid4lin_stream_get_param(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_param *param); + pjmedia_vid_dev_param *param); static pj_status_t vid4lin_stream_get_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - void *value); + pjmedia_vid_dev_cap cap, + void *value); static pj_status_t vid4lin_stream_set_cap(pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - const void *value); + pjmedia_vid_dev_cap cap, + const void *value); static pj_status_t vid4lin_stream_get_frame(pjmedia_vid_dev_stream *strm, pjmedia_frame *frame); static pj_status_t vid4lin_stream_start(pjmedia_vid_dev_stream *strm); @@ -203,7 +202,7 @@ static pj_status_t xioctl(int fh, int request, void *arg) int r, c=0; do { - r = v4l2_ioctl(fh, request, arg); + r = v4l2_ioctl(fh, request, arg); } while (r==-1 && c++fmt_cntv4l2_fmt_id; - v4l2_fmt.fmt.pix.field = V4L2_FIELD_INTERLACED; - status = xioctl(fd, VIDIOC_TRY_FMT, &v4l2_fmt); - if (status != PJ_SUCCESS || - v4l2_fmt.fmt.pix.pixelformat != fmt_map->v4l2_fmt_id || - v4l2_fmt.fmt.pix.width != v4l_sizes[i].w || - v4l2_fmt.fmt.pix.height != v4l_sizes[i].h) - { - continue; - } - - pjmedia_format_init_video(&info->fmt[info->fmt_cnt++], - fmt_id, - v4l_sizes[i].w, - v4l_sizes[i].h, - DEFAULT_FPS, 1); + struct v4l2_format v4l2_fmt; + pj_status_t status; + + pj_bzero(&v4l2_fmt, sizeof(v4l2_fmt)); + v4l2_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + v4l2_fmt.fmt.pix.width = v4l_sizes[i].w; + v4l2_fmt.fmt.pix.height = v4l_sizes[i].h; + v4l2_fmt.fmt.pix.pixelformat = fmt_map->v4l2_fmt_id; + v4l2_fmt.fmt.pix.field = V4L2_FIELD_INTERLACED; + status = xioctl(fd, VIDIOC_TRY_FMT, &v4l2_fmt); + if (status != PJ_SUCCESS || + v4l2_fmt.fmt.pix.pixelformat != fmt_map->v4l2_fmt_id || + v4l2_fmt.fmt.pix.width != v4l_sizes[i].w || + v4l2_fmt.fmt.pix.height != v4l_sizes[i].h) + { + continue; + } + + pjmedia_format_init_video(&info->fmt[info->fmt_cnt++], + fmt_id, + v4l_sizes[i].w, + v4l_sizes[i].h, + DEFAULT_FPS, 1); } } @@ -294,97 +293,97 @@ static pj_status_t v4l2_scan_devs(vid4lin_factory *f) f->dev_pool = pj_pool_create(f->pf, DRIVER_NAME, 500, 500, NULL); for (i=0; idev_count < V4L2_MAX_DEVS; ++i) { - int fd; - vid4lin_dev_info *pdi; - pj_uint32_t fmt_cap[8]; - int j, fmt_cnt=0; - - pdi = &vdi[f->dev_count]; - - snprintf(dev_name, sizeof(dev_name), "/dev/video%d", i); - if (!pj_file_exists(dev_name)) - continue; - - fd = v4l2_open(dev_name, O_RDWR, 0); - if (fd == -1) - continue; - - status = xioctl(fd, VIDIOC_QUERYCAP, &pdi->v4l2_cap); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, "Error querying %s", dev_name)); - v4l2_close(fd); - continue; - } - - if ((pdi->v4l2_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) { - v4l2_close(fd); - continue; - } - - PJ_LOG(5,(THIS_FILE, "Found capture device %s", pdi->v4l2_cap.card)); - PJ_LOG(5,(THIS_FILE, " Enumerating formats:")); - for (j=0; fmt_cntdev_name, dev_name, sizeof(pdi->dev_name)); - pdi->dev_name[sizeof(pdi->dev_name)-1] = '\0'; - strncpy(pdi->info.name, (char*)pdi->v4l2_cap.card, - sizeof(pdi->info.name)); - pdi->info.name[sizeof(pdi->info.name)-1] = '\0'; - strncpy(pdi->info.driver, DRIVER_NAME, sizeof(pdi->info.driver)); - pdi->info.driver[sizeof(pdi->info.driver)-1] = '\0'; - pdi->info.dir = PJMEDIA_DIR_CAPTURE; - pdi->info.has_callback = PJ_FALSE; - pdi->info.caps = PJMEDIA_VID_DEV_CAP_FORMAT; - - for (j=0; jinfo); - } - - v4l2_close(fd); - - if (j < fmt_cnt) - continue; - - f->dev_count++; + int fd; + vid4lin_dev_info *pdi; + pj_uint32_t fmt_cap[8]; + int j, fmt_cnt=0; + + pdi = &vdi[f->dev_count]; + + snprintf(dev_name, sizeof(dev_name), "/dev/video%d", i); + if (!pj_file_exists(dev_name)) + continue; + + fd = v4l2_open(dev_name, O_RDWR, 0); + if (fd == -1) + continue; + + status = xioctl(fd, VIDIOC_QUERYCAP, &pdi->v4l2_cap); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, "Error querying %s", dev_name)); + v4l2_close(fd); + continue; + } + + if ((pdi->v4l2_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) { + v4l2_close(fd); + continue; + } + + PJ_LOG(5,(THIS_FILE, "Found capture device %s", pdi->v4l2_cap.card)); + PJ_LOG(5,(THIS_FILE, " Enumerating formats:")); + for (j=0; fmt_cntdev_name, dev_name, sizeof(pdi->dev_name)); + pdi->dev_name[sizeof(pdi->dev_name)-1] = '\0'; + strncpy(pdi->info.name, (char*)pdi->v4l2_cap.card, + sizeof(pdi->info.name)); + pdi->info.name[sizeof(pdi->info.name)-1] = '\0'; + strncpy(pdi->info.driver, DRIVER_NAME, sizeof(pdi->info.driver)); + pdi->info.driver[sizeof(pdi->info.driver)-1] = '\0'; + pdi->info.dir = PJMEDIA_DIR_CAPTURE; + pdi->info.has_callback = PJ_FALSE; + pdi->info.caps = PJMEDIA_VID_DEV_CAP_FORMAT; + + for (j=0; jinfo); + } + + v4l2_close(fd); + + if (j < fmt_cnt) + continue; + + f->dev_count++; } if (f->dev_count == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; if (f->dev_count > old_count || f->dev_info == NULL) { - f->dev_info = (vid4lin_dev_info*) - pj_pool_calloc(f->dev_pool, - f->dev_count, - sizeof(vid4lin_dev_info)); + f->dev_info = (vid4lin_dev_info*) + pj_pool_calloc(f->dev_pool, + f->dev_count, + sizeof(vid4lin_dev_info)); } pj_memcpy(f->dev_info, vdi, f->dev_count * sizeof(vid4lin_dev_info)); @@ -407,8 +406,8 @@ static pj_status_t vid4lin_factory_destroy(pjmedia_vid_dev_factory *f) if (cf->dev_pool) pj_pool_release(cf->dev_pool); if (cf->pool) { - cf->pool = NULL; - pj_pool_release(pool); + cf->pool = NULL; + pj_pool_release(pool); } return PJ_SUCCESS; @@ -422,10 +421,10 @@ static pj_status_t vid4lin_factory_refresh(pjmedia_vid_dev_factory *f) status = v4l2_scan_devs(cf); if (status != PJ_SUCCESS) - return status; + return status; PJ_LOG(4, (THIS_FILE, "Video4Linux2 has %d devices", - cf->dev_count)); + cf->dev_count)); return PJ_SUCCESS; } @@ -439,8 +438,8 @@ static unsigned vid4lin_factory_get_dev_count(pjmedia_vid_dev_factory *f) /* API: get device info */ static pj_status_t vid4lin_factory_get_dev_info(pjmedia_vid_dev_factory *f, - unsigned index, - pjmedia_vid_dev_info *info) + unsigned index, + pjmedia_vid_dev_info *info) { vid4lin_factory *cf = (vid4lin_factory*)f; @@ -474,8 +473,8 @@ static pj_status_t vid4lin_factory_default_param(pj_pool_t *pool, /* util: setup format */ static pj_status_t vid4lin_stream_init_fmt(vid4lin_stream *stream, - const pjmedia_vid_dev_param *param, - pj_uint32_t pix_fmt) + const pjmedia_vid_dev_param *param, + pj_uint32_t pix_fmt) { pjmedia_video_format_detail *vfd; struct v4l2_format v4l2_fmt; @@ -483,7 +482,7 @@ static pj_status_t vid4lin_stream_init_fmt(vid4lin_stream *stream, vfd = pjmedia_format_get_video_format_detail(¶m->fmt, PJ_TRUE); if (vfd == NULL) - return PJMEDIA_EVID_BADFORMAT; + return PJMEDIA_EVID_BADFORMAT; pj_bzero(&v4l2_fmt, sizeof(v4l2_fmt)); v4l2_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; @@ -493,19 +492,19 @@ static pj_status_t vid4lin_stream_init_fmt(vid4lin_stream *stream, v4l2_fmt.fmt.pix.field = V4L2_FIELD_INTERLACED; status = xioctl(stream->fd, VIDIOC_S_FMT, &v4l2_fmt); if (status != PJ_SUCCESS) - return status; + return status; if (v4l2_fmt.fmt.pix.pixelformat != pix_fmt) { - status = PJMEDIA_EVID_BADFORMAT; - return status; + status = PJMEDIA_EVID_BADFORMAT; + return status; } if ((v4l2_fmt.fmt.pix.width != vfd->size.w) || - (v4l2_fmt.fmt.pix.height != vfd->size.h)) + (v4l2_fmt.fmt.pix.height != vfd->size.h)) { - /* Size has changed */ - vfd->size.w = v4l2_fmt.fmt.pix.width; - vfd->size.h = v4l2_fmt.fmt.pix.height; + /* Size has changed */ + vfd->size.w = v4l2_fmt.fmt.pix.width; + vfd->size.h = v4l2_fmt.fmt.pix.height; } return PJ_SUCCESS; @@ -524,37 +523,37 @@ static pj_status_t vid4lin_stream_init_streaming(vid4lin_stream *stream) req.memory = V4L2_MEMORY_MMAP; status = xioctl(stream->fd, VIDIOC_REQBUFS, &req); if (status != PJ_SUCCESS) - return status; + return status; stream->buffers = pj_pool_calloc(stream->pool, req.count, - sizeof(*stream->buffers)); + sizeof(*stream->buffers)); stream->buf_cnt = 0; for (i = 0; i < req.count; ++i) { - struct v4l2_buffer buf; + struct v4l2_buffer buf; - pj_bzero(&buf, sizeof(buf)); + pj_bzero(&buf, sizeof(buf)); - buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - buf.memory = V4L2_MEMORY_MMAP; - buf.index = i; + buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + buf.memory = V4L2_MEMORY_MMAP; + buf.index = i; - status = xioctl(stream->fd, VIDIOC_QUERYBUF, &buf); - if (status != PJ_SUCCESS) - goto on_error; + status = xioctl(stream->fd, VIDIOC_QUERYBUF, &buf); + if (status != PJ_SUCCESS) + goto on_error; - stream->buffers[i].length = buf.length; - stream->buffers[i].start = v4l2_mmap(NULL, buf.length, - PROT_READ | PROT_WRITE, - MAP_SHARED, stream->fd, - buf.m.offset); + stream->buffers[i].length = buf.length; + stream->buffers[i].start = v4l2_mmap(NULL, buf.length, + PROT_READ | PROT_WRITE, + MAP_SHARED, stream->fd, + buf.m.offset); - if (MAP_FAILED == stream->buffers[i].start) { - status = pj_get_os_error(); - goto on_error; - } + if (MAP_FAILED == stream->buffers[i].start) { + status = pj_get_os_error(); + goto on_error; + } - stream->buf_cnt++; + stream->buf_cnt++; } PJ_LOG(5,(THIS_FILE, " mmap streaming initialized")); @@ -580,10 +579,10 @@ static pj_status_t vid4lin_stream_init_read_write(vid4lin_stream *stream) /* API: create stream */ static pj_status_t vid4lin_factory_create_stream(pjmedia_vid_dev_factory *f, - pjmedia_vid_dev_param *param, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm) + pjmedia_vid_dev_param *param, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm) { vid4lin_factory *cf = (vid4lin_factory*)f; pj_pool_t *pool; @@ -597,11 +596,11 @@ static pj_status_t vid4lin_factory_create_stream(pjmedia_vid_dev_factory *f, PJ_ASSERT_RETURN(f && param && p_vid_strm, PJ_EINVAL); PJ_ASSERT_RETURN(param->fmt.type == PJMEDIA_TYPE_VIDEO && - param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && + param->fmt.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO && param->dir == PJMEDIA_DIR_CAPTURE, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(param->cap_id >= 0 && param->cap_id < cf->dev_count, - PJMEDIA_EVID_INVDEV); + PJMEDIA_EVID_INVDEV); fmt_info = pjmedia_get_video_format_info(NULL, param->fmt.id); if (!fmt_info || (fmt_map=get_v4l2_format_info(param->fmt.id))==NULL) @@ -626,25 +625,25 @@ static pj_status_t vid4lin_factory_create_stream(pjmedia_vid_dev_factory *f, stream->fd = v4l2_open(vdi->dev_name, O_RDWR, 0); if (stream->fd < 0) - goto on_error; + goto on_error; status = vid4lin_stream_init_fmt(stream, param, fmt_map->v4l2_fmt_id); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; if (vdi->v4l2_cap.capabilities & V4L2_CAP_STREAMING) - status = vid4lin_stream_init_streaming(stream); + status = vid4lin_stream_init_streaming(stream); if (status!=PJ_SUCCESS && vdi->v4l2_cap.capabilities & V4L2_CAP_STREAMING) - status = vid4lin_stream_init_streaming_user(stream); + status = vid4lin_stream_init_streaming_user(stream); if (status!=PJ_SUCCESS && vdi->v4l2_cap.capabilities & V4L2_CAP_READWRITE) - status = vid4lin_stream_init_read_write(stream); + status = vid4lin_stream_init_read_write(stream); if (status != PJ_SUCCESS) { - PJ_LOG(1,(THIS_FILE, "Error: unable to initiate I/O on %s", - stream->name)); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Error: unable to initiate I/O on %s", + stream->name)); + goto on_error; } /* Done */ @@ -655,7 +654,7 @@ static pj_status_t vid4lin_factory_create_stream(pjmedia_vid_dev_factory *f, on_error: if (status == PJ_SUCCESS) - status = PJ_RETURN_OS_ERROR(errno); + status = PJ_RETURN_OS_ERROR(errno); vid4lin_stream_destroy(&stream->base); return status; @@ -663,7 +662,7 @@ static pj_status_t vid4lin_factory_create_stream(pjmedia_vid_dev_factory *f, /* API: Get stream info. */ static pj_status_t vid4lin_stream_get_param(pjmedia_vid_dev_stream *s, - pjmedia_vid_dev_param *pi) + pjmedia_vid_dev_param *pi) { vid4lin_stream *strm = (vid4lin_stream*)s; @@ -688,9 +687,9 @@ static pj_status_t vid4lin_stream_get_cap(pjmedia_vid_dev_stream *s, if (cap==PJMEDIA_VID_DEV_CAP_INPUT_SCALE) { return PJMEDIA_EVID_INVCAP; -// return PJ_SUCCESS; +// return PJ_SUCCESS; } else { - return PJMEDIA_EVID_INVCAP; + return PJMEDIA_EVID_INVCAP; } } @@ -707,7 +706,7 @@ static pj_status_t vid4lin_stream_set_cap(pjmedia_vid_dev_stream *s, /* if (cap==PJMEDIA_VID_DEV_CAP_INPUT_SCALE) { - return PJ_SUCCESS; + return PJ_SUCCESS; } */ PJ_UNUSED_ARG(strm); @@ -731,13 +730,13 @@ static pj_status_t vid4lin_stream_get_frame_mmap(vid4lin_stream *stream, buf.memory = V4L2_MEMORY_MMAP; status = xioctl(stream->fd, VIDIOC_DQBUF, &buf); if (status != PJ_SUCCESS) - return status; + return status; if (frame->size < buf.bytesused) { - /* supplied buffer is too small */ - pj_assert(!"frame buffer is too small for v4l2"); - status = PJ_ETOOSMALL; - goto on_return; + /* supplied buffer is too small */ + pj_assert(!"frame buffer is too small for v4l2"); + status = PJ_ETOOSMALL; + goto on_return; } time.sec = buf.timestamp.tv_sec; @@ -748,7 +747,7 @@ static pj_status_t vid4lin_stream_get_frame_mmap(vid4lin_stream *stream, frame->bit_info = 0; frame->size = buf.bytesused; frame->timestamp.u64 = PJ_UINT64(1) * PJ_TIME_VAL_MSEC(time) * - stream->param.clock_rate / PJ_UINT64(1000); + stream->param.clock_rate / PJ_UINT64(1000); pj_memcpy(frame->buf, stream->buffers[buf.index].start, buf.bytesused); on_return: @@ -769,10 +768,10 @@ static pj_status_t vid4lin_stream_get_frame(pjmedia_vid_dev_stream *strm, vid4lin_stream *stream = (vid4lin_stream*)strm; if (stream->io_type == IO_TYPE_MMAP) - return vid4lin_stream_get_frame_mmap(stream, frame); + return vid4lin_stream_get_frame_mmap(stream, frame); else { - pj_assert(!"Unsupported i/o type"); - return PJ_EINVALIDOP; + pj_assert(!"Unsupported i/o type"); + return PJ_EINVALIDOP; } } @@ -792,34 +791,34 @@ static pj_status_t vid4lin_stream_start(pjmedia_vid_dev_stream *strm) pj_gettimeofday(&stream->start_time); for (i = 0; i < stream->buf_cnt; ++i) { - pj_bzero(&buf, sizeof(buf)); - buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - buf.memory = V4L2_MEMORY_MMAP; - buf.index = i; - status = xioctl(stream->fd, VIDIOC_QBUF, &buf); - if (status != PJ_SUCCESS) - goto on_error; + pj_bzero(&buf, sizeof(buf)); + buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + buf.memory = V4L2_MEMORY_MMAP; + buf.index = i; + status = xioctl(stream->fd, VIDIOC_QBUF, &buf); + if (status != PJ_SUCCESS) + goto on_error; } type = V4L2_BUF_TYPE_VIDEO_CAPTURE; status = xioctl(stream->fd, VIDIOC_STREAMON, &type); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; return PJ_SUCCESS; on_error: if (i > 0) { - /* Dequeue already enqueued buffers. Can we do this while streaming - * is not started? - */ - unsigned n = i; - for (i=0; ifd, VIDIOC_DQBUF, &buf); - } + /* Dequeue already enqueued buffers. Can we do this while streaming + * is not started? + */ + unsigned n = i; + for (i=0; ifd, VIDIOC_DQBUF, &buf); + } } return status; } @@ -832,14 +831,14 @@ static pj_status_t vid4lin_stream_stop(pjmedia_vid_dev_stream *strm) pj_status_t status; if (stream->fd < 0) - return PJ_SUCCESS; + return PJ_SUCCESS; PJ_LOG(4, (THIS_FILE, "Stopping v4l2 video stream %s", stream->name)); type = V4L2_BUF_TYPE_VIDEO_CAPTURE; status = xioctl(stream->fd, VIDIOC_STREAMOFF, &type); if (status != PJ_SUCCESS) - return status; + return status; return PJ_SUCCESS; } @@ -858,19 +857,19 @@ static pj_status_t vid4lin_stream_destroy(pjmedia_vid_dev_stream *strm) PJ_LOG(4, (THIS_FILE, "Destroying v4l2 video stream %s", stream->name)); for (i=0; ibuf_cnt; ++i) { - if (stream->buffers[i].start != MAP_FAILED) { - v4l2_munmap(stream->buffers[i].start, stream->buffers[i].length); - stream->buffers[i].start = MAP_FAILED; - } + if (stream->buffers[i].start != MAP_FAILED) { + v4l2_munmap(stream->buffers[i].start, stream->buffers[i].length); + stream->buffers[i].start = MAP_FAILED; + } } if (stream->fd >= 0) { - v4l2_close(stream->fd); - stream->fd = -1; + v4l2_close(stream->fd); + stream->fd = -1; } pj_pool_release(stream->pool); return PJ_SUCCESS; } -#endif /* PJMEDIA_VIDEO_DEV_HAS_V4L2 */ +#endif /* PJMEDIA_VIDEO_DEV_HAS_V4L2 */ diff --git a/pjmedia/src/pjmedia-videodev/videodev.c b/pjmedia/src/pjmedia-videodev/videodev.c index 6f3ee1d5d0..811b841e27 100644 --- a/pjmedia/src/pjmedia-videodev/videodev.c +++ b/pjmedia/src/pjmedia-videodev/videodev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -63,8 +62,8 @@ pjmedia_vid_dev_factory* pjmedia_opengl_factory(pj_pool_factory *pf); pjmedia_vid_dev_factory* pjmedia_and_factory(pj_pool_factory *pf); #endif -#define MAX_DRIVERS PJMEDIA_VID_DEV_MAX_DRIVERS -#define MAX_DEVS PJMEDIA_VID_DEV_MAX_DEVS +#define MAX_DRIVERS PJMEDIA_VID_DEV_MAX_DRIVERS +#define MAX_DEVS PJMEDIA_VID_DEV_MAX_DEVS /* API: Initialize the video device subsystem. */ @@ -78,13 +77,13 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_subsys_init(pj_pool_factory *pf) * number of shutdown(). */ if (vid_subsys->init_count++ != 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Register error subsystem */ pj_register_strerror(PJMEDIA_VIDEODEV_ERRNO_START, - PJ_ERRNO_SPACE_SIZE, - &pjmedia_videodev_strerror); + PJ_ERRNO_SPACE_SIZE, + &pjmedia_videodev_strerror); /* Init */ vid_subsys->pf = pf; @@ -125,11 +124,11 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_subsys_init(pj_pool_factory *pf) /* Initialize each factory and build the device ID list */ for (i=0; idrv_cnt; ++i) { - status = pjmedia_vid_driver_init(i, PJ_FALSE); - if (status != PJ_SUCCESS) { - pjmedia_vid_driver_deinit(i); - continue; - } + status = pjmedia_vid_driver_init(i, PJ_FALSE); + if (status != PJ_SUCCESS) { + pjmedia_vid_driver_deinit(i); + continue; + } } return vid_subsys->dev_cnt ? PJ_SUCCESS : status; @@ -145,7 +144,7 @@ pjmedia_vid_register_factory(pjmedia_vid_dev_factory_create_func_ptr adf, pjmedia_vid_subsys *vid_subsys = pjmedia_get_vid_subsys(); if (vid_subsys->init_count == 0) - return PJMEDIA_EVID_INIT; + return PJMEDIA_EVID_INIT; vid_subsys->drv[vid_subsys->drv_cnt].create = adf; vid_subsys->drv[vid_subsys->drv_cnt].f = factory; @@ -162,9 +161,9 @@ pjmedia_vid_register_factory(pjmedia_vid_dev_factory_create_func_ptr adf, status = pjmedia_vid_driver_init(vid_subsys->drv_cnt, refresh); if (status == PJ_SUCCESS) { - vid_subsys->drv_cnt++; + vid_subsys->drv_cnt++; } else { - pjmedia_vid_driver_deinit(vid_subsys->drv_cnt); + pjmedia_vid_driver_deinit(vid_subsys->drv_cnt); } return status; @@ -179,21 +178,21 @@ pjmedia_vid_unregister_factory(pjmedia_vid_dev_factory_create_func_ptr adf, pjmedia_vid_subsys *vid_subsys = pjmedia_get_vid_subsys(); if (vid_subsys->init_count == 0) - return PJMEDIA_EVID_INIT; + return PJMEDIA_EVID_INIT; for (i=0; idrv_cnt; ++i) { - pjmedia_vid_driver *drv = &vid_subsys->drv[i]; - - if ((factory && drv->f==factory) || (adf && drv->create == adf)) { - for (j = drv->start_idx; j < drv->start_idx + drv->dev_cnt; j++) - { - vid_subsys->dev_list[j] = (pj_uint32_t)PJMEDIA_VID_INVALID_DEV; - } - - pjmedia_vid_driver_deinit(i); - pj_bzero(drv, sizeof(*drv)); - return PJ_SUCCESS; - } + pjmedia_vid_driver *drv = &vid_subsys->drv[i]; + + if ((factory && drv->f==factory) || (adf && drv->create == adf)) { + for (j = drv->start_idx; j < drv->start_idx + drv->dev_cnt; j++) + { + vid_subsys->dev_list[j] = (pj_uint32_t)PJMEDIA_VID_INVALID_DEV; + } + + pjmedia_vid_driver_deinit(i); + pj_bzero(drv, sizeof(*drv)); + return PJ_SUCCESS; + } } return PJMEDIA_EVID_ERR; @@ -216,13 +215,13 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_subsys_shutdown(void) * matching number of init(). */ if (vid_subsys->init_count == 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } --vid_subsys->init_count; if (vid_subsys->init_count == 0) { for (i=0; idrv_cnt; ++i) { - pjmedia_vid_driver_deinit(i); + pjmedia_vid_driver_deinit(i); } pj_bzero(vid_subsys, sizeof(pjmedia_vid_subsys)); diff --git a/pjmedia/src/pjmedia/alaw_ulaw.c b/pjmedia/src/pjmedia/alaw_ulaw.c index 3436890f06..87fc867a38 100644 --- a/pjmedia/src/pjmedia/alaw_ulaw.c +++ b/pjmedia/src/pjmedia/alaw_ulaw.c @@ -36,65 +36,65 @@ * * u-law, A-law and linear PCM conversions. */ -#define SIGN_BIT (0x80) /* Sign bit for a A-law byte. */ -#define QUANT_MASK (0xf) /* Quantization field mask. */ -#define NSEGS (8) /* Number of A-law segments. */ -#define SEG_SHIFT (4) /* Left shift for segment number. */ -#define SEG_MASK (0x70) /* Segment field mask. */ +#define SIGN_BIT (0x80) /* Sign bit for a A-law byte. */ +#define QUANT_MASK (0xf) /* Quantization field mask. */ +#define NSEGS (8) /* Number of A-law segments. */ +#define SEG_SHIFT (4) /* Left shift for segment number. */ +#define SEG_MASK (0x70) /* Segment field mask. */ static short seg_end[8] = {0xFF, 0x1FF, 0x3FF, 0x7FF, - 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF}; + 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF}; /* copy from CCITT G.711 specifications */ -static unsigned char _u2a[128] = { /* u- to A-law conversions */ - 1, 1, 2, 2, 3, 3, 4, 4, - 5, 5, 6, 6, 7, 7, 8, 8, - 9, 10, 11, 12, 13, 14, 15, 16, - 17, 18, 19, 20, 21, 22, 23, 24, - 25, 27, 29, 31, 33, 34, 35, 36, - 37, 38, 39, 40, 41, 42, 43, 44, - 46, 48, 49, 50, 51, 52, 53, 54, - 55, 56, 57, 58, 59, 60, 61, 62, - 64, 65, 66, 67, 68, 69, 70, 71, - 72, 73, 74, 75, 76, 77, 78, 79, - 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}; - -static unsigned char _a2u[128] = { /* A- to u-law conversions */ - 1, 3, 5, 7, 9, 11, 13, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 32, 33, 33, 34, 34, 35, 35, - 36, 37, 38, 39, 40, 41, 42, 43, - 44, 45, 46, 47, 48, 48, 49, 49, - 50, 51, 52, 53, 54, 55, 56, 57, - 58, 59, 60, 61, 62, 63, 64, 64, - 65, 66, 67, 68, 69, 70, 71, 72, - 73, 74, 75, 76, 77, 78, 79, 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}; +static unsigned char _u2a[128] = { /* u- to A-law conversions */ + 1, 1, 2, 2, 3, 3, 4, 4, + 5, 5, 6, 6, 7, 7, 8, 8, + 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, + 25, 27, 29, 31, 33, 34, 35, 36, + 37, 38, 39, 40, 41, 42, 43, 44, + 46, 48, 49, 50, 51, 52, 53, 54, + 55, 56, 57, 58, 59, 60, 61, 62, + 64, 65, 66, 67, 68, 69, 70, 71, + 72, 73, 74, 75, 76, 77, 78, 79, + 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}; + +static unsigned char _a2u[128] = { /* A- to u-law conversions */ + 1, 3, 5, 7, 9, 11, 13, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 32, 33, 33, 34, 34, 35, 35, + 36, 37, 38, 39, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 48, 49, 49, + 50, 51, 52, 53, 54, 55, 56, 57, + 58, 59, 60, 61, 62, 63, 64, 64, + 65, 66, 67, 68, 69, 70, 71, 72, + 73, 74, 75, 76, 77, 78, 79, 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}; static int search( - int val, - short *table, - int size) + int val, + short *table, + int size) { - int i; + int i; - for (i = 0; i < size; i++) { - if (val <= *table++) - return (i); - } - return (size); + for (i = 0; i < size; i++) { + if (val <= *table++) + return (i); + } + return (size); } /* @@ -102,55 +102,55 @@ search( * * linear2alaw() accepts an 16-bit integer and encodes it as A-law data. * - * Linear Input Code Compressed Code - * ------------------------ --------------- - * 0000000wxyza 000wxyz - * 0000001wxyza 001wxyz - * 000001wxyzab 010wxyz - * 00001wxyzabc 011wxyz - * 0001wxyzabcd 100wxyz - * 001wxyzabcde 101wxyz - * 01wxyzabcdef 110wxyz - * 1wxyzabcdefg 111wxyz + * Linear Input Code Compressed Code + * ------------------------ --------------- + * 0000000wxyza 000wxyz + * 0000001wxyza 001wxyz + * 000001wxyzab 010wxyz + * 00001wxyzabc 011wxyz + * 0001wxyzabcd 100wxyz + * 001wxyzabcde 101wxyz + * 01wxyzabcdef 110wxyz + * 1wxyzabcdefg 111wxyz * * For further information see John C. Bellamy's Digital Telephony, 1982, * John Wiley & Sons, pps 98-111 and 472-476. */ PJ_DEF(pj_uint8_t) pjmedia_linear2alaw( - int pcm_val) /* 2's complement (16-bit range) */ + int pcm_val) /* 2's complement (16-bit range) */ { - int mask; - int seg; - unsigned char aval; - - if (pcm_val >= 0) { - mask = 0xD5; /* sign (7th) bit = 1 */ - } else { - mask = 0x55; /* sign bit = 0 */ - pcm_val = -pcm_val - 8; - - /* https://github.com/pjsip/pjproject/issues/1301 - * Thank you K Johnson - Zetron - 27 May 2011 - */ - if (pcm_val < 0) - pcm_val = 0; - } - - /* Convert the scaled magnitude to segment number. */ - seg = search(pcm_val, seg_end, 8); - - /* Combine the sign, segment, and quantization bits. */ - - if (seg >= 8) /* out of range, return maximum value. */ - return (0x7F ^ mask); - else { - aval = seg << SEG_SHIFT; - if (seg < 2) - aval |= (pcm_val >> 4) & QUANT_MASK; - else - aval |= (pcm_val >> (seg + 3)) & QUANT_MASK; - return (aval ^ mask); - } + int mask; + int seg; + unsigned char aval; + + if (pcm_val >= 0) { + mask = 0xD5; /* sign (7th) bit = 1 */ + } else { + mask = 0x55; /* sign bit = 0 */ + pcm_val = -pcm_val - 8; + + /* https://github.com/pjsip/pjproject/issues/1301 + * Thank you K Johnson - Zetron - 27 May 2011 + */ + if (pcm_val < 0) + pcm_val = 0; + } + + /* Convert the scaled magnitude to segment number. */ + seg = search(pcm_val, seg_end, 8); + + /* Combine the sign, segment, and quantization bits. */ + + if (seg >= 8) /* out of range, return maximum value. */ + return (0x7F ^ mask); + else { + aval = seg << SEG_SHIFT; + if (seg < 2) + aval |= (pcm_val >> 4) & QUANT_MASK; + else + aval |= (pcm_val >> (seg + 3)) & QUANT_MASK; + return (aval ^ mask); + } } /* @@ -158,30 +158,30 @@ PJ_DEF(pj_uint8_t) pjmedia_linear2alaw( * */ PJ_DEF(int) pjmedia_alaw2linear( - unsigned a_val) + unsigned a_val) { - int t; - int seg; - - a_val ^= 0x55; - - t = (a_val & QUANT_MASK) << 4; - seg = ((unsigned)a_val & SEG_MASK) >> SEG_SHIFT; - switch (seg) { - case 0: - t += 8; - break; - case 1: - t += 0x108; - break; - default: - t += 0x108; - t <<= seg - 1; - } - return ((a_val & SIGN_BIT) ? t : -t); + int t; + int seg; + + a_val ^= 0x55; + + t = (a_val & QUANT_MASK) << 4; + seg = ((unsigned)a_val & SEG_MASK) >> SEG_SHIFT; + switch (seg) { + case 0: + t += 8; + break; + case 1: + t += 0x108; + break; + default: + t += 0x108; + t <<= seg - 1; + } + return ((a_val & SIGN_BIT) ? t : -t); } -#define BIAS (0x84) /* Bias for linear code. */ +#define BIAS (0x84) /* Bias for linear code. */ /* * linear2ulaw() - Convert a linear PCM value to u-law @@ -190,16 +190,16 @@ PJ_DEF(int) pjmedia_alaw2linear( * is biased by adding 33 which shifts the encoding range from (0 - 8158) to * (33 - 8191). The result can be seen in the following encoding table: * - * Biased Linear Input Code Compressed Code - * ------------------------ --------------- - * 00000001wxyza 000wxyz - * 0000001wxyzab 001wxyz - * 000001wxyzabc 010wxyz - * 00001wxyzabcd 011wxyz - * 0001wxyzabcde 100wxyz - * 001wxyzabcdef 101wxyz - * 01wxyzabcdefg 110wxyz - * 1wxyzabcdefgh 111wxyz + * Biased Linear Input Code Compressed Code + * ------------------------ --------------- + * 00000001wxyza 000wxyz + * 0000001wxyzab 001wxyz + * 000001wxyzabc 010wxyz + * 00001wxyzabcd 011wxyz + * 0001wxyzabcde 100wxyz + * 001wxyzabcdef 101wxyz + * 01wxyzabcdefg 110wxyz + * 1wxyzabcdefgh 111wxyz * * Each biased linear code has a leading 1 which identifies the segment * number. The value of the segment number is equal to 7 minus the number @@ -213,34 +213,34 @@ PJ_DEF(int) pjmedia_alaw2linear( * John Wiley & Sons, pps 98-111 and 472-476. */ PJ_DEF(unsigned char) pjmedia_linear2ulaw( - int pcm_val) /* 2's complement (16-bit range) */ + int pcm_val) /* 2's complement (16-bit range) */ { - int mask; - int seg; - unsigned char uval; - - /* Get the sign and the magnitude of the value. */ - if (pcm_val < 0) { - pcm_val = BIAS - pcm_val; - mask = 0x7F; - } else { - pcm_val += BIAS; - mask = 0xFF; - } - - /* Convert the scaled magnitude to segment number. */ - seg = search(pcm_val, seg_end, 8); - - /* - * Combine the sign, segment, quantization bits; - * and complement the code word. - */ - if (seg >= 8) /* out of range, return maximum value. */ - return (0x7F ^ mask); - else { - uval = (seg << 4) | ((pcm_val >> (seg + 3)) & 0xF); - return (uval ^ mask); - } + int mask; + int seg; + unsigned char uval; + + /* Get the sign and the magnitude of the value. */ + if (pcm_val < 0) { + pcm_val = BIAS - pcm_val; + mask = 0x7F; + } else { + pcm_val += BIAS; + mask = 0xFF; + } + + /* Convert the scaled magnitude to segment number. */ + seg = search(pcm_val, seg_end, 8); + + /* + * Combine the sign, segment, quantization bits; + * and complement the code word. + */ + if (seg >= 8) /* out of range, return maximum value. */ + return (0x7F ^ mask); + else { + uval = (seg << 4) | ((pcm_val >> (seg + 3)) & 0xF); + return (uval ^ mask); + } } @@ -254,47 +254,47 @@ PJ_DEF(unsigned char) pjmedia_linear2ulaw( * original code word. This is in keeping with ISDN conventions. */ PJ_DEF(int) pjmedia_ulaw2linear( - unsigned char u_val) + unsigned char u_val) { - int t; + int t; - /* Shortcut: when input is zero, output is zero - * This will also make the VAD works harder. - * -bennylp - */ - if (u_val == 0) return 0; + /* Shortcut: when input is zero, output is zero + * This will also make the VAD works harder. + * -bennylp + */ + if (u_val == 0) return 0; - /* Complement to obtain normal u-law value. */ - u_val = ~u_val; + /* Complement to obtain normal u-law value. */ + u_val = ~u_val; - /* - * Extract and bias the quantization bits. Then - * shift up by the segment number and subtract out the bias. - */ - t = ((u_val & QUANT_MASK) << 3) + BIAS; - t <<= ((unsigned)u_val & SEG_MASK) >> SEG_SHIFT; + /* + * Extract and bias the quantization bits. Then + * shift up by the segment number and subtract out the bias. + */ + t = ((u_val & QUANT_MASK) << 3) + BIAS; + t <<= ((unsigned)u_val & SEG_MASK) >> SEG_SHIFT; - return ((u_val & SIGN_BIT) ? (BIAS - t) : (t - BIAS)); + return ((u_val & SIGN_BIT) ? (BIAS - t) : (t - BIAS)); } /* A-law to u-law conversion */ PJ_DEF(unsigned char) pjmedia_alaw2ulaw( - unsigned char aval) + unsigned char aval) { - aval &= 0xff; - return ((aval & 0x80) ? (0xFF ^ _a2u[aval ^ 0xD5]) : - (0x7F ^ _a2u[aval ^ 0x55])); + aval &= 0xff; + return ((aval & 0x80) ? (0xFF ^ _a2u[aval ^ 0xD5]) : + (0x7F ^ _a2u[aval ^ 0x55])); } /* u-law to A-law conversion */ PJ_DEF(unsigned char) pjmedia_ulaw2alaw( - unsigned char uval) + unsigned char uval) { - uval &= 0xff; - return ((uval & 0x80) ? (0xD5 ^ (_u2a[0xFF ^ uval] - 1)) : - (0x55 ^ (_u2a[0x7F ^ uval] - 1))); + uval &= 0xff; + return ((uval & 0x80) ? (0xD5 ^ (_u2a[0xFF ^ uval] - 1)) : + (0x55 ^ (_u2a[0x7F ^ uval] - 1))); } -#endif /* PJMEDIA_HAS_ALAW_ULAW_TABLE */ +#endif /* PJMEDIA_HAS_ALAW_ULAW_TABLE */ diff --git a/pjmedia/src/pjmedia/alaw_ulaw_table.c b/pjmedia/src/pjmedia/alaw_ulaw_table.c index 14306edba7..7771a30b40 100644 --- a/pjmedia/src/pjmedia/alaw_ulaw_table.c +++ b/pjmedia/src/pjmedia/alaw_ulaw_table.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -4179,7 +4178,7 @@ const pj_int16_t pjmedia_alaw2linear_tab[256] = -15104,-14592,-16128,-15616,-13056,-12544,-14080,-13568, -344, -328, -376, -360, -280, -264, -312, -296, -472, -456, -504, -488, -408, -392, -440, -424, - -88, -72, -120, -104, -24, -8, -56, -40, + -88, -72, -120, -104, -24, -8, -56, -40, -216, -200, -248, -232, -152, -136, -184, -168, -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184, -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696, @@ -4193,14 +4192,14 @@ const pj_int16_t pjmedia_alaw2linear_tab[256] = 30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136, 11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472, 15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568, - 344, 328, 376, 360, 280, 264, 312, 296, - 472, 456, 504, 488, 408, 392, 440, 424, - 88, 72, 120, 104, 24, 8, 56, 40, - 216, 200, 248, 232, 152, 136, 184, 168, + 344, 328, 376, 360, 280, 264, 312, 296, + 472, 456, 504, 488, 408, 392, 440, 424, + 88, 72, 120, 104, 24, 8, 56, 40, + 216, 200, 248, 232, 152, 136, 184, 168, 1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184, 1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696, - 688, 656, 752, 720, 560, 528, 624, 592, - 944, 912, 1008, 976, 816, 784, 880, 848 + 688, 656, 752, 720, 560, 528, 624, 592, + 944, 912, 1008, 976, 816, 784, 880, 848 }; #endif diff --git a/pjmedia/src/pjmedia/audiodev.c b/pjmedia/src/pjmedia/audiodev.c index 398a40424f..8439c0492d 100644 --- a/pjmedia/src/pjmedia/audiodev.c +++ b/pjmedia/src/pjmedia/audiodev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -26,7 +25,7 @@ #define THIS_FILE "audiodev.c" -#define DEFINE_CAP(name, info) {name, info} +#define DEFINE_CAP(name, info) {name, info} /* Capability names */ static struct cap_info @@ -44,11 +43,11 @@ static struct cap_info DEFINE_CAP("meter-out", "Output meter"), DEFINE_CAP("route-in", "Input routing"), DEFINE_CAP("route-out", "Output routing"), - DEFINE_CAP("aec", "Accoustic echo cancellation"), + DEFINE_CAP("aec", "Accoustic echo cancellation"), DEFINE_CAP("aec-tail", "Tail length setting for AEC"), - DEFINE_CAP("vad", "Voice activity detection"), - DEFINE_CAP("cng", "Comfort noise generation"), - DEFINE_CAP("plg", "Packet loss concealment") + DEFINE_CAP("vad", "Voice activity detection"), + DEFINE_CAP("cng", "Comfort noise generation"), + DEFINE_CAP("plg", "Packet loss concealment") }; @@ -60,9 +59,9 @@ static struct cap_info * factory only. */ #define MAKE_DEV_ID(f_id, index) (((f_id & 0xFFFF) << 16) | (index & 0xFFFF)) -#define GET_INDEX(dev_id) ((dev_id) & 0xFFFF) -#define GET_FID(dev_id) ((dev_id) >> 16) -#define DEFAULT_DEV_ID 0 +#define GET_INDEX(dev_id) ((dev_id) & 0xFFFF) +#define GET_FID(dev_id) ((dev_id) >> 16) +#define DEFAULT_DEV_ID 0 /* The audio subsystem */ @@ -76,7 +75,7 @@ PJ_DEF(pjmedia_aud_subsys*) pjmedia_get_aud_subsys(void) /* API: init driver */ PJ_DEF(pj_status_t) pjmedia_aud_driver_init(unsigned drv_idx, - pj_bool_t refresh) + pj_bool_t refresh) { pjmedia_aud_driver *drv = &aud_subsys.drv[drv_idx]; pjmedia_aud_dev_factory *f; @@ -84,32 +83,32 @@ PJ_DEF(pj_status_t) pjmedia_aud_driver_init(unsigned drv_idx, pj_status_t status; if (!refresh && drv->create) { - /* Create the factory */ - f = (*drv->create)(aud_subsys.pf); - if (!f) - return PJ_EUNKNOWN; - - /* Call factory->init() */ - status = f->op->init(f); - if (status != PJ_SUCCESS) { - f->op->destroy(f); - return status; - } + /* Create the factory */ + f = (*drv->create)(aud_subsys.pf); + if (!f) + return PJ_EUNKNOWN; + + /* Call factory->init() */ + status = f->op->init(f); + if (status != PJ_SUCCESS) { + f->op->destroy(f); + return status; + } } else { - f = drv->f; + f = drv->f; } if (!f) - return PJ_EUNKNOWN; + return PJ_EUNKNOWN; /* Get number of devices */ dev_cnt = f->op->get_dev_count(f); if (dev_cnt + aud_subsys.dev_cnt > PJMEDIA_AUD_MAX_DEVS) { - PJ_LOG(4,(THIS_FILE, "%d device(s) cannot be registered because" - " there are too many devices", - aud_subsys.dev_cnt + dev_cnt - - PJMEDIA_AUD_MAX_DEVS)); - dev_cnt = PJMEDIA_AUD_MAX_DEVS - aud_subsys.dev_cnt; + PJ_LOG(4,(THIS_FILE, "%d device(s) cannot be registered because" + " there are too many devices", + aud_subsys.dev_cnt + dev_cnt - + PJMEDIA_AUD_MAX_DEVS)); + dev_cnt = PJMEDIA_AUD_MAX_DEVS - aud_subsys.dev_cnt; } /* enabling this will cause pjsua-lib initialization to fail when there @@ -117,50 +116,50 @@ PJ_DEF(pj_status_t) pjmedia_aud_driver_init(unsigned drv_idx, * run with --null-audio * if (dev_cnt == 0) { - f->op->destroy(f); - return PJMEDIA_EAUD_NODEV; + f->op->destroy(f); + return PJMEDIA_EAUD_NODEV; } */ /* Fill in default devices */ drv->play_dev_idx = drv->rec_dev_idx = - drv->dev_idx = PJMEDIA_AUD_INVALID_DEV; + drv->dev_idx = PJMEDIA_AUD_INVALID_DEV; for (i=0; iop->get_dev_info(f, i, &info); - if (status != PJ_SUCCESS) { - f->op->destroy(f); - return status; - } - - if (drv->name[0]=='\0') { - /* Set driver name */ - pj_ansi_strncpy(drv->name, info.driver, sizeof(drv->name)); - drv->name[sizeof(drv->name)-1] = '\0'; - } - - if (drv->play_dev_idx < 0 && info.output_count) { - /* Set default playback device */ - drv->play_dev_idx = i; - } - if (drv->rec_dev_idx < 0 && info.input_count) { - /* Set default capture device */ - drv->rec_dev_idx = i; - } - if (drv->dev_idx < 0 && info.input_count && - info.output_count) - { - /* Set default capture and playback device */ - drv->dev_idx = i; - } - - if (drv->play_dev_idx >= 0 && drv->rec_dev_idx >= 0 && - drv->dev_idx >= 0) - { - /* Done. */ - break; - } + pjmedia_aud_dev_info info; + + status = f->op->get_dev_info(f, i, &info); + if (status != PJ_SUCCESS) { + f->op->destroy(f); + return status; + } + + if (drv->name[0]=='\0') { + /* Set driver name */ + pj_ansi_strncpy(drv->name, info.driver, sizeof(drv->name)); + drv->name[sizeof(drv->name)-1] = '\0'; + } + + if (drv->play_dev_idx < 0 && info.output_count) { + /* Set default playback device */ + drv->play_dev_idx = i; + } + if (drv->rec_dev_idx < 0 && info.input_count) { + /* Set default capture device */ + drv->rec_dev_idx = i; + } + if (drv->dev_idx < 0 && info.input_count && + info.output_count) + { + /* Set default capture and playback device */ + drv->dev_idx = i; + } + + if (drv->play_dev_idx >= 0 && drv->rec_dev_idx >= 0 && + drv->dev_idx >= 0) + { + /* Done. */ + break; + } } /* Register the factory */ @@ -171,7 +170,7 @@ PJ_DEF(pj_status_t) pjmedia_aud_driver_init(unsigned drv_idx, /* Register devices to global list */ for (i=0; if) { - drv->f->op->destroy(drv->f); - drv->f = NULL; + drv->f->op->destroy(drv->f); + drv->f = NULL; } pj_bzero(drv, sizeof(*drv)); drv->play_dev_idx = drv->rec_dev_idx = - drv->dev_idx = PJMEDIA_AUD_INVALID_DEV; + drv->dev_idx = PJMEDIA_AUD_INVALID_DEV; } /* API: get capability name/info */ PJ_DEF(const char*) pjmedia_aud_dev_cap_name(pjmedia_aud_dev_cap cap, - const char **p_desc) + const char **p_desc) { const char *desc; unsigned i; @@ -202,13 +201,13 @@ PJ_DEF(const char*) pjmedia_aud_dev_cap_name(pjmedia_aud_dev_cap cap, if (p_desc==NULL) p_desc = &desc; for (i=0; iname; \ - *size = sizeof(param->name) + *size = sizeof(param->name) switch (cap) { case PJMEDIA_AUD_DEV_CAP_EXT_FORMAT: - FIELD_INFO(ext_fmt); - break; + FIELD_INFO(ext_fmt); + break; case PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY: - FIELD_INFO(input_latency_ms); - break; + FIELD_INFO(input_latency_ms); + break; case PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY: - FIELD_INFO(output_latency_ms); - break; + FIELD_INFO(output_latency_ms); + break; case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - FIELD_INFO(input_vol); - break; + FIELD_INFO(input_vol); + break; case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - FIELD_INFO(output_vol); - break; + FIELD_INFO(output_vol); + break; case PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE: - FIELD_INFO(input_route); - break; + FIELD_INFO(input_route); + break; case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: - FIELD_INFO(output_route); - break; + FIELD_INFO(output_route); + break; case PJMEDIA_AUD_DEV_CAP_EC: - FIELD_INFO(ec_enabled); - break; + FIELD_INFO(ec_enabled); + break; case PJMEDIA_AUD_DEV_CAP_EC_TAIL: - FIELD_INFO(ec_tail_ms); - break; + FIELD_INFO(ec_tail_ms); + break; /* vad is no longer in "fmt" in 2.0. case PJMEDIA_AUD_DEV_CAP_VAD: - FIELD_INFO(ext_fmt.vad); - break; + FIELD_INFO(ext_fmt.vad); + break; */ case PJMEDIA_AUD_DEV_CAP_CNG: - FIELD_INFO(cng_enabled); - break; + FIELD_INFO(cng_enabled); + break; case PJMEDIA_AUD_DEV_CAP_PLC: - FIELD_INFO(plc_enabled); - break; + FIELD_INFO(plc_enabled); + break; default: - return PJMEDIA_EAUD_INVCAP; + return PJMEDIA_EAUD_INVCAP; } #undef FIELD_INFO @@ -273,8 +272,8 @@ static pj_status_t get_cap_pointer(const pjmedia_aud_param *param, /* API: set cap value to param */ PJ_DEF(pj_status_t) pjmedia_aud_param_set_cap( pjmedia_aud_param *param, - pjmedia_aud_dev_cap cap, - const void *pval) + pjmedia_aud_dev_cap cap, + const void *pval) { void *cap_ptr; unsigned cap_size; @@ -282,7 +281,7 @@ PJ_DEF(pj_status_t) pjmedia_aud_param_set_cap( pjmedia_aud_param *param, status = get_cap_pointer(param, cap, &cap_ptr, &cap_size); if (status != PJ_SUCCESS) - return status; + return status; pj_memcpy(cap_ptr, pval, cap_size); param->flags |= cap; @@ -292,8 +291,8 @@ PJ_DEF(pj_status_t) pjmedia_aud_param_set_cap( pjmedia_aud_param *param, /* API: get cap value from param */ PJ_DEF(pj_status_t) pjmedia_aud_param_get_cap( const pjmedia_aud_param *param, - pjmedia_aud_dev_cap cap, - void *pval) + pjmedia_aud_dev_cap cap, + void *pval) { void *cap_ptr; unsigned cap_size; @@ -301,11 +300,11 @@ PJ_DEF(pj_status_t) pjmedia_aud_param_get_cap( const pjmedia_aud_param *param, status = get_cap_pointer(param, cap, &cap_ptr, &cap_size); if (status != PJ_SUCCESS) - return status; + return status; if ((param->flags & cap) == 0) { - pj_bzero(cap_ptr, cap_size); - return PJMEDIA_EAUD_INVCAP; + pj_bzero(cap_ptr, cap_size); + return PJMEDIA_EAUD_INVCAP; } pj_memcpy(pval, cap_ptr, cap_size); @@ -320,16 +319,16 @@ PJ_DEF(pj_status_t) pjmedia_aud_dev_refresh(void) aud_subsys.dev_cnt = 0; for (i=0; if && drv->f->op->refresh) { - pj_status_t status = drv->f->op->refresh(drv->f); - if (status != PJ_SUCCESS) { - PJ_PERROR(4, (THIS_FILE, status, "Unable to refresh device " - "list for %s", drv->name)); - } - } - pjmedia_aud_driver_init(i, PJ_TRUE); + pjmedia_aud_driver *drv = &aud_subsys.drv[i]; + + if (drv->f && drv->f->op->refresh) { + pj_status_t status = drv->f->op->refresh(drv->f); + if (status != PJ_SUCCESS) { + PJ_PERROR(4, (THIS_FILE, status, "Unable to refresh device " + "list for %s", drv->name)); + } + } + pjmedia_aud_driver_init(i, PJ_TRUE); } return PJ_SUCCESS; } @@ -342,10 +341,10 @@ PJ_DEF(unsigned) pjmedia_aud_dev_count(void) /* Internal: convert local index to global device index */ static pj_status_t make_global_index(unsigned drv_idx, - pjmedia_aud_dev_index *id) + pjmedia_aud_dev_index *id) { if (*id < 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Check that factory still exists */ @@ -353,7 +352,7 @@ static pj_status_t make_global_index(unsigned drv_idx, /* Check that device index is valid */ PJ_ASSERT_RETURN(*id>=0 && *id<(int)aud_subsys.drv[drv_idx].dev_cnt, - PJ_EBUG); + PJ_EBUG); *id += aud_subsys.drv[drv_idx].start_idx; return PJ_SUCCESS; @@ -361,51 +360,51 @@ static pj_status_t make_global_index(unsigned drv_idx, /* Internal: lookup device id */ static pj_status_t lookup_dev(pjmedia_aud_dev_index id, - pjmedia_aud_dev_factory **p_f, - unsigned *p_local_index) + pjmedia_aud_dev_factory **p_f, + unsigned *p_local_index) { int f_id, index; if (id < 0) { - unsigned i; - - if (id == PJMEDIA_AUD_INVALID_DEV) - return PJMEDIA_EAUD_INVDEV; - - for (i=0; idev_idx >= 0) { - id = drv->dev_idx; - make_global_index(i, &id); - break; - } else if (id==PJMEDIA_AUD_DEFAULT_CAPTURE_DEV && - drv->rec_dev_idx >= 0) - { - id = drv->rec_dev_idx; - make_global_index(i, &id); - break; - } else if (id==PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV && - drv->play_dev_idx >= 0) - { - id = drv->play_dev_idx; - make_global_index(i, &id); - break; - } - } - - if (id < 0) { - return PJMEDIA_EAUD_NODEFDEV; - } + unsigned i; + + if (id == PJMEDIA_AUD_INVALID_DEV) + return PJMEDIA_EAUD_INVDEV; + + for (i=0; idev_idx >= 0) { + id = drv->dev_idx; + make_global_index(i, &id); + break; + } else if (id==PJMEDIA_AUD_DEFAULT_CAPTURE_DEV && + drv->rec_dev_idx >= 0) + { + id = drv->rec_dev_idx; + make_global_index(i, &id); + break; + } else if (id==PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV && + drv->play_dev_idx >= 0) + { + id = drv->play_dev_idx; + make_global_index(i, &id); + break; + } + } + + if (id < 0) { + return PJMEDIA_EAUD_NODEFDEV; + } } f_id = GET_FID(aud_subsys.dev_list[id]); index = GET_INDEX(aud_subsys.dev_list[id]); if (f_id < 0 || f_id >= (int)aud_subsys.drv_cnt) - return PJMEDIA_EAUD_INVDEV; + return PJMEDIA_EAUD_INVDEV; if (index < 0 || index >= (int)aud_subsys.drv[f_id].dev_cnt) - return PJMEDIA_EAUD_INVDEV; + return PJMEDIA_EAUD_INVDEV; *p_f = aud_subsys.drv[f_id].f; *p_local_index = (unsigned)index; @@ -416,7 +415,7 @@ static pj_status_t lookup_dev(pjmedia_aud_dev_index id, /* API: Get device information. */ PJ_DEF(pj_status_t) pjmedia_aud_dev_get_info(pjmedia_aud_dev_index id, - pjmedia_aud_dev_info *info) + pjmedia_aud_dev_info *info) { pjmedia_aud_dev_factory *f; unsigned index; @@ -427,15 +426,15 @@ PJ_DEF(pj_status_t) pjmedia_aud_dev_get_info(pjmedia_aud_dev_index id, status = lookup_dev(id, &f, &index); if (status != PJ_SUCCESS) - return status; + return status; return f->op->get_dev_info(f, index, info); } /* API: find device */ PJ_DEF(pj_status_t) pjmedia_aud_dev_lookup( const char *drv_name, - const char *dev_name, - pjmedia_aud_dev_index *id) + const char *dev_name, + pjmedia_aud_dev_index *id) { pjmedia_aud_dev_factory *f = NULL; unsigned drv_idx, dev_idx; @@ -444,29 +443,29 @@ PJ_DEF(pj_status_t) pjmedia_aud_dev_lookup( const char *drv_name, PJ_ASSERT_RETURN(aud_subsys.pf, PJMEDIA_EAUD_INIT); for (drv_idx=0; drv_idxop->get_dev_info(f, dev_idx, &info); - if (status != PJ_SUCCESS) - return status; + status = f->op->get_dev_info(f, dev_idx, &info); + if (status != PJ_SUCCESS) + return status; - if (!pj_ansi_stricmp(dev_name, info.name)) - break; + if (!pj_ansi_stricmp(dev_name, info.name)) + break; } if (dev_idx==aud_subsys.drv[drv_idx].dev_cnt) - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; *id = dev_idx; make_global_index(drv_idx, id); @@ -478,7 +477,7 @@ PJ_DEF(pj_status_t) pjmedia_aud_dev_lookup( const char *drv_name, * specified device. */ PJ_DEF(pj_status_t) pjmedia_aud_dev_default_param(pjmedia_aud_dev_index id, - pjmedia_aud_param *param) + pjmedia_aud_param *param) { pjmedia_aud_dev_factory *f; unsigned index; @@ -489,11 +488,11 @@ PJ_DEF(pj_status_t) pjmedia_aud_dev_default_param(pjmedia_aud_dev_index id, status = lookup_dev(id, &f, &index); if (status != PJ_SUCCESS) - return status; + return status; status = f->op->default_param(f, index, param); if (status != PJ_SUCCESS) - return status; + return status; /* Normalize device IDs */ make_global_index(f->sys.drv_idx, ¶m->rec_id); @@ -504,10 +503,10 @@ PJ_DEF(pj_status_t) pjmedia_aud_dev_default_param(pjmedia_aud_dev_index id, /* API: Open audio stream object using the specified parameters. */ PJ_DEF(pj_status_t) pjmedia_aud_stream_create(const pjmedia_aud_param *prm, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { pjmedia_aud_dev_factory *rec_f=NULL, *play_f=NULL, *f=NULL; pjmedia_aud_param param; @@ -516,55 +515,55 @@ PJ_DEF(pj_status_t) pjmedia_aud_stream_create(const pjmedia_aud_param *prm, PJ_ASSERT_RETURN(prm && prm->dir && p_aud_strm, PJ_EINVAL); PJ_ASSERT_RETURN(aud_subsys.pf, PJMEDIA_EAUD_INIT); PJ_ASSERT_RETURN(prm->dir==PJMEDIA_DIR_CAPTURE || - prm->dir==PJMEDIA_DIR_PLAYBACK || - prm->dir==PJMEDIA_DIR_CAPTURE_PLAYBACK, - PJ_EINVAL); + prm->dir==PJMEDIA_DIR_PLAYBACK || + prm->dir==PJMEDIA_DIR_CAPTURE_PLAYBACK, + PJ_EINVAL); /* Must make copy of param because we're changing device ID */ pj_memcpy(¶m, prm, sizeof(param)); /* Normalize rec_id */ if (param.dir & PJMEDIA_DIR_CAPTURE) { - unsigned index; + unsigned index; - if (param.rec_id < 0) - param.rec_id = PJMEDIA_AUD_DEFAULT_CAPTURE_DEV; + if (param.rec_id < 0) + param.rec_id = PJMEDIA_AUD_DEFAULT_CAPTURE_DEV; - status = lookup_dev(param.rec_id, &rec_f, &index); - if (status != PJ_SUCCESS) - return status; + status = lookup_dev(param.rec_id, &rec_f, &index); + if (status != PJ_SUCCESS) + return status; - param.rec_id = index; - f = rec_f; + param.rec_id = index; + f = rec_f; } /* Normalize play_id */ if (param.dir & PJMEDIA_DIR_PLAYBACK) { - unsigned index; + unsigned index; - if (param.play_id < 0) - param.play_id = PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV; + if (param.play_id < 0) + param.play_id = PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV; - status = lookup_dev(param.play_id, &play_f, &index); - if (status != PJ_SUCCESS) - return status; + status = lookup_dev(param.play_id, &play_f, &index); + if (status != PJ_SUCCESS) + return status; - param.play_id = index; - f = play_f; + param.play_id = index; + f = play_f; } PJ_ASSERT_RETURN(f != NULL, PJ_EBUG); /* For now, rec_id and play_id must belong to the same factory */ PJ_ASSERT_RETURN((param.dir != PJMEDIA_DIR_CAPTURE_PLAYBACK) || - (rec_f == play_f), - PJMEDIA_EAUD_INVDEV); + (rec_f == play_f), + PJMEDIA_EAUD_INVDEV); /* Create the stream */ status = f->op->create_stream(f, ¶m, rec_cb, play_cb, - user_data, p_aud_strm); + user_data, p_aud_strm); if (status != PJ_SUCCESS) - return status; + return status; /* Assign factory id to the stream */ (*p_aud_strm)->sys.drv_idx = f->sys.drv_idx; @@ -573,7 +572,7 @@ PJ_DEF(pj_status_t) pjmedia_aud_stream_create(const pjmedia_aud_param *prm, /* API: Get the running parameters for the specified audio stream. */ PJ_DEF(pj_status_t) pjmedia_aud_stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param) + pjmedia_aud_param *param) { pj_status_t status; @@ -582,7 +581,7 @@ PJ_DEF(pj_status_t) pjmedia_aud_stream_get_param(pjmedia_aud_stream *strm, status = strm->op->get_param(strm, param); if (status != PJ_SUCCESS) - return status; + return status; /* Normalize device id's */ make_global_index(strm->sys.drv_idx, ¶m->rec_id); @@ -593,16 +592,16 @@ PJ_DEF(pj_status_t) pjmedia_aud_stream_get_param(pjmedia_aud_stream *strm, /* API: Get the value of a specific capability of the audio stream. */ PJ_DEF(pj_status_t) pjmedia_aud_stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value) + pjmedia_aud_dev_cap cap, + void *value) { return strm->op->get_cap(strm, cap, value); } /* API: Set the value of a specific capability of the audio stream. */ PJ_DEF(pj_status_t) pjmedia_aud_stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value) + pjmedia_aud_dev_cap cap, + const void *value) { return strm->op->set_cap(strm, cap, value); } diff --git a/pjmedia/src/pjmedia/avi_player.c b/pjmedia/src/pjmedia/avi_player.c index c9bd9bf850..cecd02422a 100644 --- a/pjmedia/src/pjmedia/avi_player.c +++ b/pjmedia/src/pjmedia/avi_player.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -47,14 +46,14 @@ //#define COMPARE_TAG(doc_tag, tag) (doc_tag==*((pj_uint32_t*)avi_tags[tag])) #define COMPARE_TAG(doc_tag, tag) \ - (pj_memcmp(&(doc_tag), &avi_tags[tag], 4)==0) + (pj_memcmp(&(doc_tag), &avi_tags[tag], 4)==0) -#define SIGNATURE PJMEDIA_SIG_PORT_VID_AVI_PLAYER +#define SIGNATURE PJMEDIA_SIG_PORT_VID_AVI_PLAYER -#define VIDEO_CLOCK_RATE 90000 +#define VIDEO_CLOCK_RATE 90000 #if 0 -# define TRACE_(x) PJ_LOG(4,x) +# define TRACE_(x) PJ_LOG(4,x) #else # define TRACE_(x) #endif @@ -62,25 +61,25 @@ #if defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN!=0 static void data_to_host(void *data, pj_uint8_t bits, unsigned count) { - unsigned i; + unsigned i; count /= (bits == 32? 4 : 2); - if (bits == 32) { - pj_int32_t *data32 = (pj_int32_t *)data; - for (i=0; ibase.info, &name, SIGNATURE, - 8000, 1, 16, 80); + 8000, 1, 16, 80); port->fd = (pj_oshandle_t)(pj_ssize_t)-1; port->base.get_frame = &avi_get_frame; @@ -202,8 +201,8 @@ static pj_status_t file_read3(pj_oshandle_t fd, void *data, pj_ssize_t size, PJ_DEF(pj_status_t) pjmedia_avi_player_create_streams(pj_pool_t *pool, const char *filename, - unsigned options, - pjmedia_avi_streams **p_streams) + unsigned options, + pjmedia_avi_streams **p_streams) { pjmedia_avi_hdr avi_hdr; struct avi_reader_port *fport[PJMEDIA_AVI_MAX_NUM_STREAMS]; @@ -216,13 +215,13 @@ pjmedia_avi_player_create_streams(pj_pool_t *pool, /* Check the file really exists. */ if (!pj_file_exists(filename)) { - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; } /* Create fport instance. */ fport[0] = create_avi_port(pool); if (!fport[0]) { - return PJ_ENOMEM; + return PJ_ENOMEM; } /* Get the file size. */ @@ -232,13 +231,13 @@ pjmedia_avi_player_create_streams(pj_pool_t *pool, if (fport[0]->fsize <= sizeof(riff_hdr_t) + sizeof(avih_hdr_t) + sizeof(strl_hdr_t)) { - return PJMEDIA_EINVALIMEDIATYPE; + return PJMEDIA_EINVALIMEDIATYPE; } /* Open file. */ status = pj_file_open(pool, filename, PJ_O_RDONLY, &fport[0]->fd); if (status != PJ_SUCCESS) - return status; + return status; /* Read the RIFF + AVIH header. */ status = file_read(fport[0]->fd, &avi_hdr, @@ -248,12 +247,12 @@ pjmedia_avi_player_create_streams(pj_pool_t *pool, /* Validate AVI file. */ if (!COMPARE_TAG(avi_hdr.riff_hdr.riff, PJMEDIA_AVI_RIFF_TAG) || - !COMPARE_TAG(avi_hdr.riff_hdr.avi, PJMEDIA_AVI_AVI_TAG) || + !COMPARE_TAG(avi_hdr.riff_hdr.avi, PJMEDIA_AVI_AVI_TAG) || !COMPARE_TAG(avi_hdr.avih_hdr.list_tag, PJMEDIA_AVI_LIST_TAG) || !COMPARE_TAG(avi_hdr.avih_hdr.hdrl_tag, PJMEDIA_AVI_HDRL_TAG) || !COMPARE_TAG(avi_hdr.avih_hdr.avih, PJMEDIA_AVI_AVIH_TAG)) { - status = PJMEDIA_EINVALIMEDIATYPE; + status = PJMEDIA_EINVALIMEDIATYPE; goto on_error; } @@ -318,10 +317,10 @@ pjmedia_avi_player_create_streams(pj_pool_t *pool, /* Skip the remainder of the header */ size_to_read = avi_hdr.strl_hdr[i].list_sz - (sizeof(strl_hdr_t) - 8) - elem; - status = pj_file_setpos(fport[0]->fd, size_to_read, PJ_SEEK_CUR); - if (status != PJ_SUCCESS) { + status = pj_file_setpos(fport[0]->fd, size_to_read, PJ_SEEK_CUR); + if (status != PJ_SUCCESS) { goto on_error; - } + } } /* Finish reading the AVIH header */ @@ -346,9 +345,9 @@ pjmedia_avi_player_create_streams(pj_pool_t *pool, { read = 4; status = file_read(fport[0]->fd, &ch, read); - if (status != PJ_SUCCESS) { - goto on_error; - } + if (status != PJ_SUCCESS) { + goto on_error; + } if (COMPARE_TAG(ch.id, PJMEDIA_AVI_MOVI_TAG)) break; @@ -373,7 +372,7 @@ pjmedia_avi_player_create_streams(pj_pool_t *pool, goto on_error; for (i = 0, nstr = 0; i < avi_hdr.avih_hdr.num_streams; i++) { - pjmedia_format_id fmt_id; + pjmedia_format_id fmt_id; /* Skip non-audio, non-video, or disabled streams) */ if ((!COMPARE_TAG(avi_hdr.strl_hdr[i].data_type, @@ -411,22 +410,22 @@ pjmedia_avi_player_create_streams(pj_pool_t *pool, } } else { /* Check supported audio formats here */ - strf_audio_hdr_t *hdr = (strf_audio_hdr_t*) - &avi_hdr.strf_hdr[i].strf_audio_hdr; + strf_audio_hdr_t *hdr = (strf_audio_hdr_t*) + &avi_hdr.strf_hdr[i].strf_audio_hdr; if (hdr->fmt_tag == PJMEDIA_WAVE_FMT_TAG_PCM && - hdr->bits_per_sample == 16) - { - fmt_id = PJMEDIA_FORMAT_PCM; - } - else if (hdr->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ALAW) - { - fmt_id = PJMEDIA_FORMAT_PCMA; - } - else if (hdr->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ULAW) - { - fmt_id = PJMEDIA_FORMAT_PCMU; - } - else + hdr->bits_per_sample == 16) + { + fmt_id = PJMEDIA_FORMAT_PCM; + } + else if (hdr->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ALAW) + { + fmt_id = PJMEDIA_FORMAT_PCMA; + } + else if (hdr->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ULAW) + { + fmt_id = PJMEDIA_FORMAT_PCMU; + } + else { PJ_LOG(4, (THIS_FILE, "Unsupported audio stream")); continue; @@ -437,7 +436,7 @@ pjmedia_avi_player_create_streams(pj_pool_t *pool, /* Create fport instance. */ fport[nstr] = create_avi_port(pool); if (!fport[nstr]) { - status = PJ_ENOMEM; + status = PJ_ENOMEM; goto on_error; } @@ -499,10 +498,10 @@ pjmedia_avi_player_create_streams(pj_pool_t *pool, */ bps = strf_hdr->biSizeImage * 8 * strl_hdr->rate / strl_hdr->scale; if (bps==0) { - /* strf_hdr->biSizeImage may be zero for uncompressed RGB */ - bps = strf_hdr->biWidth * strf_hdr->biHeight * - strf_hdr->biBitCount * - strl_hdr->rate / strl_hdr->scale; + /* strf_hdr->biSizeImage may be zero for uncompressed RGB */ + bps = strf_hdr->biWidth * strf_hdr->biHeight * + strf_hdr->biBitCount * + strl_hdr->rate / strl_hdr->scale; } fport[i]->base.info.fmt.det.vid.avg_bps = bps; fport[i]->base.info.fmt.det.vid.max_bps = bps; @@ -522,14 +521,14 @@ pjmedia_avi_player_create_streams(pj_pool_t *pool, strf_hdr->bytes_per_sec * 8, strf_hdr->bytes_per_sec * 8); - /* Set format to PCM (we will decode PCMA/U) */ - if (fport[i]->fmt_id == PJMEDIA_FORMAT_PCMA || - fport[i]->fmt_id == PJMEDIA_FORMAT_PCMU) - { - fport[i]->base.info.fmt.id = PJMEDIA_FORMAT_PCM; - fport[i]->base.info.fmt.det.aud.bits_per_sample = 16; - } - } + /* Set format to PCM (we will decode PCMA/U) */ + if (fport[i]->fmt_id == PJMEDIA_FORMAT_PCMA || + fport[i]->fmt_id == PJMEDIA_FORMAT_PCMU) + { + fport[i]->base.info.fmt.id = PJMEDIA_FORMAT_PCM; + fport[i]->base.info.fmt.det.aud.bits_per_sample = 16; + } + } pj_strdup2(pool, &fport[i]->base.info.name, filename); } @@ -543,10 +542,10 @@ pjmedia_avi_player_create_streams(pj_pool_t *pool, (*p_streams)->streams[i] = &fport[i]->base; PJ_LOG(4,(THIS_FILE, - "AVI file player '%.*s' created with " - "%d media ports", - (int)fport[0]->base.info.name.slen, - fport[0]->base.info.name.ptr, + "AVI file player '%.*s' created with " + "%d media ports", + (int)fport[0]->base.info.name.slen, + fport[0]->base.info.name.ptr, (*p_streams)->num_streams)); return PJ_SUCCESS; @@ -616,9 +615,9 @@ PJ_DEF(pj_ssize_t) pjmedia_avi_stream_get_len(pjmedia_avi_stream *stream) */ PJ_DEF(pj_status_t) pjmedia_avi_stream_set_eof_cb( pjmedia_avi_stream *stream, - void *user_data, - pj_status_t (*cb)(pjmedia_avi_stream *stream, - void *usr_data)) + void *user_data, + pj_status_t (*cb)(pjmedia_avi_stream *stream, + void *usr_data)) { struct avi_reader_port *fport; @@ -629,7 +628,7 @@ pjmedia_avi_stream_set_eof_cb( pjmedia_avi_stream *stream, PJ_ASSERT_RETURN(stream->info.signature == SIGNATURE, -PJ_EINVALIDOP); PJ_LOG(1, (THIS_FILE, "pjmedia_avi_stream_set_eof_cb() is deprecated. " - "Use pjmedia_avi_stream_set_eof_cb2() instead.")); + "Use pjmedia_avi_stream_set_eof_cb2() instead.")); fport = (struct avi_reader_port*) stream; @@ -647,9 +646,9 @@ pjmedia_avi_stream_set_eof_cb( pjmedia_avi_stream *stream, */ PJ_DEF(pj_status_t) pjmedia_avi_stream_set_eof_cb2(pjmedia_avi_stream *stream, - void *user_data, - void (*cb)(pjmedia_avi_stream *stream, - void *usr_data)) + void *user_data, + void (*cb)(pjmedia_avi_stream *stream, + void *usr_data)) { struct avi_reader_port *fport; @@ -674,8 +673,8 @@ static pj_status_t file_on_event(pjmedia_event *event, struct avi_reader_port *fport = (struct avi_reader_port*)user_data; if (event->type == PJMEDIA_EVENT_CALLBACK) { - if (fport->cb2) - (*fport->cb2)(&fport->base, fport->base.port_data.pdata); + if (fport->cb2) + (*fport->cb2)(&fport->base, fport->base.port_data.pdata); } return PJ_SUCCESS; @@ -686,7 +685,7 @@ static pj_status_t file_on_event(pjmedia_event *event, * Get frame from file. */ static pj_status_t avi_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct avi_reader_port *fport = (struct avi_reader_port*)this_port; pj_status_t status = PJ_SUCCESS; @@ -696,76 +695,76 @@ static pj_status_t avi_get_frame(pjmedia_port *this_port, /* We encountered end of file */ if (fport->eof) { - PJ_LOG(5,(THIS_FILE, "File port %.*s EOF", - (int)fport->base.info.name.slen, - fport->base.info.name.ptr)); - - /* Call callback, if any */ - if (fport->cb2) { - pj_bool_t no_loop = (fport->options & PJMEDIA_AVI_FILE_NO_LOOP); - - if (!fport->subscribed) { - status = pjmedia_event_subscribe(NULL, &file_on_event, - fport, fport); - fport->subscribed = (status == PJ_SUCCESS)? PJ_TRUE: - PJ_FALSE; - } - - if (fport->subscribed && fport->eof != 2) { - pjmedia_event event; - - if (no_loop) { - /* To prevent the callback from being called repeatedly */ - fport->eof = 2; - } else { - fport->eof = PJ_FALSE; - pj_file_setpos(fport->fd, fport->start_data, PJ_SEEK_SET); - } - - pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, - NULL, fport); - pjmedia_event_publish(NULL, fport, &event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); - } - - /* Should not access player port after this since - * it might have been destroyed by the callback. - */ - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - - return (no_loop? PJ_EEOF: PJ_SUCCESS); - - } else if (fport->cb) { - status = (*fport->cb)(this_port, fport->base.port_data.pdata); - } - - /* If callback returns non PJ_SUCCESS or 'no loop' is specified, - * return immediately (and don't try to access player port since - * it might have been destroyed by the callback). - */ - if ((status != PJ_SUCCESS) || + PJ_LOG(5,(THIS_FILE, "File port %.*s EOF", + (int)fport->base.info.name.slen, + fport->base.info.name.ptr)); + + /* Call callback, if any */ + if (fport->cb2) { + pj_bool_t no_loop = (fport->options & PJMEDIA_AVI_FILE_NO_LOOP); + + if (!fport->subscribed) { + status = pjmedia_event_subscribe(NULL, &file_on_event, + fport, fport); + fport->subscribed = (status == PJ_SUCCESS)? PJ_TRUE: + PJ_FALSE; + } + + if (fport->subscribed && fport->eof != 2) { + pjmedia_event event; + + if (no_loop) { + /* To prevent the callback from being called repeatedly */ + fport->eof = 2; + } else { + fport->eof = PJ_FALSE; + pj_file_setpos(fport->fd, fport->start_data, PJ_SEEK_SET); + } + + pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, + NULL, fport); + pjmedia_event_publish(NULL, fport, &event, + PJMEDIA_EVENT_PUBLISH_POST_EVENT); + } + + /* Should not access player port after this since + * it might have been destroyed by the callback. + */ + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + + return (no_loop? PJ_EEOF: PJ_SUCCESS); + + } else if (fport->cb) { + status = (*fport->cb)(this_port, fport->base.port_data.pdata); + } + + /* If callback returns non PJ_SUCCESS or 'no loop' is specified, + * return immediately (and don't try to access player port since + * it might have been destroyed by the callback). + */ + if ((status != PJ_SUCCESS) || (fport->options & PJMEDIA_AVI_FILE_NO_LOOP)) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - return PJ_EEOF; - } + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + return PJ_EEOF; + } /* Rewind file */ - PJ_LOG(5,(THIS_FILE, "File port %.*s rewinding..", - (int)fport->base.info.name.slen, - fport->base.info.name.ptr)); - fport->eof = PJ_FALSE; + PJ_LOG(5,(THIS_FILE, "File port %.*s rewinding..", + (int)fport->base.info.name.slen, + fport->base.info.name.ptr)); + fport->eof = PJ_FALSE; pj_file_setpos(fport->fd, fport->start_data, PJ_SEEK_SET); } /* For PCMU/A audio stream, reduce frame size to half (temporarily). */ if (fport->base.info.fmt.type == PJMEDIA_TYPE_AUDIO && - (fport->fmt_id == PJMEDIA_FORMAT_PCMA || - fport->fmt_id == PJMEDIA_FORMAT_PCMU)) + (fport->fmt_id == PJMEDIA_FORMAT_PCMA || + fport->fmt_id == PJMEDIA_FORMAT_PCMU)) { - frame->size >>= 1; + frame->size >>= 1; } /* Fill frame buffer. */ @@ -867,48 +866,48 @@ static pj_status_t avi_get_frame(pjmedia_port *this_port, frame->timestamp.u64 = fport->next_ts.u64; if (frame->type == PJMEDIA_FRAME_TYPE_AUDIO) { - /* Decode PCMU/A frame */ - if (fport->fmt_id == PJMEDIA_FORMAT_PCMA || - fport->fmt_id == PJMEDIA_FORMAT_PCMU) - { - unsigned i; - pj_uint16_t *dst; - pj_uint8_t *src; - - dst = (pj_uint16_t*)frame->buf + frame->size - 1; - src = (pj_uint8_t*)frame->buf + frame->size - 1; - - if (fport->fmt_id == PJMEDIA_FORMAT_PCMU) { - for (i = 0; i < frame->size; ++i) { - *dst-- = (pj_uint16_t) pjmedia_ulaw2linear(*src--); - } - } else { - for (i = 0; i < frame->size; ++i) { - *dst-- = (pj_uint16_t) pjmedia_alaw2linear(*src--); - } - } - - /* Return back the frame size */ - frame->size <<= 1; - } - - if (fport->usec_per_frame) { - fport->next_ts.u64 += (fport->usec_per_frame * - fport->base.info.fmt.det.aud.clock_rate / - 1000000); - } else { - fport->next_ts.u64 += (frame->size * - fport->base.info.fmt.det.aud.clock_rate / - (fport->base.info.fmt.det.aud.avg_bps / 8)); - } + /* Decode PCMU/A frame */ + if (fport->fmt_id == PJMEDIA_FORMAT_PCMA || + fport->fmt_id == PJMEDIA_FORMAT_PCMU) + { + unsigned i; + pj_uint16_t *dst; + pj_uint8_t *src; + + dst = (pj_uint16_t*)frame->buf + frame->size - 1; + src = (pj_uint8_t*)frame->buf + frame->size - 1; + + if (fport->fmt_id == PJMEDIA_FORMAT_PCMU) { + for (i = 0; i < frame->size; ++i) { + *dst-- = (pj_uint16_t) pjmedia_ulaw2linear(*src--); + } + } else { + for (i = 0; i < frame->size; ++i) { + *dst-- = (pj_uint16_t) pjmedia_alaw2linear(*src--); + } + } + + /* Return back the frame size */ + frame->size <<= 1; + } + + if (fport->usec_per_frame) { + fport->next_ts.u64 += (fport->usec_per_frame * + fport->base.info.fmt.det.aud.clock_rate / + 1000000); + } else { + fport->next_ts.u64 += (frame->size * + fport->base.info.fmt.det.aud.clock_rate / + (fport->base.info.fmt.det.aud.avg_bps / 8)); + } } else { - if (fport->usec_per_frame) { - fport->next_ts.u64 += (fport->usec_per_frame * VIDEO_CLOCK_RATE / - 1000000); - } else { - fport->next_ts.u64 += (frame->size * VIDEO_CLOCK_RATE / - (fport->base.info.fmt.det.vid.avg_bps / 8)); - } + if (fport->usec_per_frame) { + fport->next_ts.u64 += (fport->usec_per_frame * VIDEO_CLOCK_RATE / + 1000000); + } else { + fport->next_ts.u64 += (frame->size * VIDEO_CLOCK_RATE / + (fport->base.info.fmt.det.vid.avg_bps / 8)); + } } return PJ_SUCCESS; @@ -920,9 +919,9 @@ static pj_status_t avi_get_frame(pjmedia_port *this_port, size_to_read -= size_read; if (size_to_read == (pj_ssize_t)frame->size) { /* Frame is empty */ - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - return PJ_EEOF; + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + return PJ_EEOF; } pj_bzero((char *)frame->buf + frame->size - size_to_read, size_to_read); @@ -943,8 +942,8 @@ static pj_status_t avi_on_destroy(pjmedia_port *this_port) pj_assert(this_port->info.signature == SIGNATURE); if (fport->subscribed) { - pjmedia_event_unsubscribe(NULL, &file_on_event, fport, fport); - fport->subscribed = PJ_FALSE; + pjmedia_event_unsubscribe(NULL, &file_on_event, fport, fport); + fport->subscribed = PJ_FALSE; } if (fport->fd != (pj_oshandle_t) (pj_ssize_t)-1) diff --git a/pjmedia/src/pjmedia/bidirectional.c b/pjmedia/src/pjmedia/bidirectional.c index a106d2ddc0..53211f7150 100644 --- a/pjmedia/src/pjmedia/bidirectional.c +++ b/pjmedia/src/pjmedia/bidirectional.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -33,7 +32,7 @@ struct bidir_port static pj_status_t put_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct bidir_port *p = (struct bidir_port*)this_port; return pjmedia_port_put_frame(p->put_port, frame); @@ -41,7 +40,7 @@ static pj_status_t put_frame(pjmedia_port *this_port, static pj_status_t get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct bidir_port *p = (struct bidir_port*)this_port; return pjmedia_port_get_frame(p->get_port, frame); @@ -49,9 +48,9 @@ static pj_status_t get_frame(pjmedia_port *this_port, PJ_DEF(pj_status_t) pjmedia_bidirectional_port_create( pj_pool_t *pool, - pjmedia_port *get_port, - pjmedia_port *put_port, - pjmedia_port **p_port ) + pjmedia_port *get_port, + pjmedia_port *put_port, + pjmedia_port **p_port ) { struct bidir_port *port; const pjmedia_audio_format_detail *gafd; @@ -60,10 +59,10 @@ PJ_DEF(pj_status_t) pjmedia_bidirectional_port_create( pj_pool_t *pool, gafd = pjmedia_format_get_audio_format_detail(&get_port->info.fmt, 1); pjmedia_port_info_init(&port->base.info, &get_port->info.name, SIGNATURE, - gafd->clock_rate, - gafd->channel_count, - gafd->bits_per_sample, - PJMEDIA_AFD_SPF(gafd)); + gafd->clock_rate, + gafd->channel_count, + gafd->bits_per_sample, + PJMEDIA_AFD_SPF(gafd)); port->get_port = get_port; port->put_port = put_port; diff --git a/pjmedia/src/pjmedia/clock_thread.c b/pjmedia/src/pjmedia/clock_thread.c index 70b1165f4d..b3166ac781 100644 --- a/pjmedia/src/pjmedia/clock_thread.c +++ b/pjmedia/src/pjmedia/clock_thread.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -109,44 +108,44 @@ pjmedia_clock_src_get_time_msec( const pjmedia_clock_src *clocksrc ) struct pjmedia_clock { - pj_pool_t *pool; - pj_timestamp freq; - pj_timestamp interval; - pj_timestamp next_tick; - pj_timestamp timestamp; - unsigned timestamp_inc; - unsigned options; - pj_uint64_t max_jump; + pj_pool_t *pool; + pj_timestamp freq; + pj_timestamp interval; + pj_timestamp next_tick; + pj_timestamp timestamp; + unsigned timestamp_inc; + unsigned options; + pj_uint64_t max_jump; pjmedia_clock_callback *cb; - void *user_data; - pj_thread_t *thread; - pj_bool_t running; - pj_bool_t quitting; - pj_lock_t *lock; + void *user_data; + pj_thread_t *thread; + pj_bool_t running; + pj_bool_t quitting; + pj_lock_t *lock; }; static int clock_thread(void *arg); -#define MAX_JUMP_MSEC 500 -#define USEC_IN_SEC (pj_uint64_t)1000000 +#define MAX_JUMP_MSEC 500 +#define USEC_IN_SEC (pj_uint64_t)1000000 /* * Create media clock. */ PJ_DEF(pj_status_t) pjmedia_clock_create( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned options, - pjmedia_clock_callback *cb, - void *user_data, - pjmedia_clock **p_clock) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned options, + pjmedia_clock_callback *cb, + void *user_data, + pjmedia_clock **p_clock) { pjmedia_clock_param param; param.usec_interval = (unsigned)(samples_per_frame * USEC_IN_SEC / - channel_count / clock_rate); + channel_count / clock_rate); param.clock_rate = clock_rate; return pjmedia_clock_create2(pool, ¶m, options, cb, user_data, p_clock); @@ -154,10 +153,10 @@ PJ_DEF(pj_status_t) pjmedia_clock_create( pj_pool_t *pool, PJ_DEF(pj_status_t) pjmedia_clock_create2(pj_pool_t *pool, const pjmedia_clock_param *param, - unsigned options, - pjmedia_clock_callback *cb, - void *user_data, - pjmedia_clock **p_clock) + unsigned options, + pjmedia_clock_callback *cb, + void *user_data, + pjmedia_clock **p_clock) { pjmedia_clock *clock; pj_status_t status; @@ -170,7 +169,7 @@ PJ_DEF(pj_status_t) pjmedia_clock_create2(pj_pool_t *pool, status = pj_get_timestamp_freq(&clock->freq); if (status != PJ_SUCCESS) - return status; + return status; clock->interval.u64 = param->usec_interval * clock->freq.u64 / USEC_IN_SEC; @@ -179,7 +178,7 @@ PJ_DEF(pj_status_t) pjmedia_clock_create2(pj_pool_t *pool, clock->max_jump = MAX_JUMP_MSEC * clock->freq.u64 / 1000; clock->timestamp_inc = (unsigned)(param->usec_interval * param->clock_rate / - (unsigned)USEC_IN_SEC); + (unsigned)USEC_IN_SEC); clock->options = options; clock->cb = cb; clock->user_data = user_data; @@ -190,7 +189,7 @@ PJ_DEF(pj_status_t) pjmedia_clock_create2(pj_pool_t *pool, /* I don't think we need a mutex, so we'll use null. */ status = pj_lock_create_null_mutex(pool, "clock", &clock->lock); if (status != PJ_SUCCESS) - return status; + return status; *p_clock = clock; @@ -209,23 +208,23 @@ PJ_DEF(pj_status_t) pjmedia_clock_start(pjmedia_clock *clock) PJ_ASSERT_RETURN(clock != NULL, PJ_EINVAL); if (clock->running) - return PJ_SUCCESS; + return PJ_SUCCESS; status = pj_get_timestamp(&now); if (status != PJ_SUCCESS) - return status; + return status; clock->next_tick.u64 = now.u64 + clock->interval.u64; clock->running = PJ_TRUE; clock->quitting = PJ_FALSE; if ((clock->options & PJMEDIA_CLOCK_NO_ASYNC) == 0 && !clock->thread) { - status = pj_thread_create(clock->pool, "clock", &clock_thread, clock, - 0, 0, &clock->thread); - if (status != PJ_SUCCESS) { - clock->running = PJ_FALSE; - return status; - } + status = pj_thread_create(clock->pool, "clock", &clock_thread, clock, + 0, 0, &clock->thread); + if (status != PJ_SUCCESS) { + clock->running = PJ_FALSE; + return status; + } } return PJ_SUCCESS; @@ -243,13 +242,13 @@ PJ_DEF(pj_status_t) pjmedia_clock_stop(pjmedia_clock *clock) clock->quitting = PJ_TRUE; if (clock->thread) { - if (pj_thread_join(clock->thread) == PJ_SUCCESS) { - pj_thread_destroy(clock->thread); - clock->thread = NULL; - pj_pool_reset(clock->pool); - } else { - clock->quitting = PJ_FALSE; - } + if (pj_thread_join(clock->thread) == PJ_SUCCESS) { + pj_thread_destroy(clock->thread); + clock->thread = NULL; + pj_pool_reset(clock->pool); + } else { + clock->quitting = PJ_FALSE; + } } return PJ_SUCCESS; @@ -266,7 +265,7 @@ PJ_DEF(pj_status_t) pjmedia_clock_modify(pjmedia_clock *clock, USEC_IN_SEC; clock->timestamp_inc = (unsigned)(param->usec_interval * param->clock_rate / - (unsigned)USEC_IN_SEC); + (unsigned)USEC_IN_SEC); return PJ_SUCCESS; } @@ -274,11 +273,11 @@ PJ_DEF(pj_status_t) pjmedia_clock_modify(pjmedia_clock *clock, /* Calculate next tick */ PJ_INLINE(void) clock_calc_next_tick(pjmedia_clock *clock, - pj_timestamp *now) + pj_timestamp *now) { if (clock->next_tick.u64+clock->max_jump < now->u64) { - /* Timestamp has made large jump, adjust next_tick */ - clock->next_tick.u64 = now->u64; + /* Timestamp has made large jump, adjust next_tick */ + clock->next_tick.u64 = now->u64; } clock->next_tick.u64 += clock->interval.u64; @@ -288,39 +287,39 @@ PJ_INLINE(void) clock_calc_next_tick(pjmedia_clock *clock, * Poll the clock. */ PJ_DEF(pj_bool_t) pjmedia_clock_wait( pjmedia_clock *clock, - pj_bool_t wait, - pj_timestamp *ts) + pj_bool_t wait, + pj_timestamp *ts) { pj_timestamp now; pj_status_t status; PJ_ASSERT_RETURN(clock != NULL, PJ_FALSE); PJ_ASSERT_RETURN((clock->options & PJMEDIA_CLOCK_NO_ASYNC) != 0, - PJ_FALSE); + PJ_FALSE); PJ_ASSERT_RETURN(clock->running, PJ_FALSE); status = pj_get_timestamp(&now); if (status != PJ_SUCCESS) - return PJ_FALSE; + return PJ_FALSE; /* Wait for the next tick to happen */ if (now.u64 < clock->next_tick.u64) { - unsigned msec; + unsigned msec; - if (!wait) - return PJ_FALSE; + if (!wait) + return PJ_FALSE; - msec = pj_elapsed_msec(&now, &clock->next_tick); - pj_thread_sleep(msec); + msec = pj_elapsed_msec(&now, &clock->next_tick); + pj_thread_sleep(msec); } /* Call callback, if any */ if (clock->cb) - (*clock->cb)(&clock->timestamp, clock->user_data); + (*clock->cb)(&clock->timestamp, clock->user_data); /* Report timestamp to caller */ if (ts) - ts->u64 = clock->timestamp.u64; + ts->u64 = clock->timestamp.u64; /* Increment timestamp */ clock->timestamp.u64 += clock->timestamp_inc; @@ -343,9 +342,9 @@ static int clock_thread(void *arg) /* Set thread priority to maximum unless not wanted. */ if ((clock->options & PJMEDIA_CLOCK_NO_HIGHEST_PRIO) == 0) { - int max = pj_thread_get_prio_max(pj_thread_this()); - if (max > 0) - pj_thread_set_prio(pj_thread_this(), max); + int max = pj_thread_get_prio_max(pj_thread_this()); + if (max > 0) + pj_thread_set_prio(pj_thread_this(), max); } /* Get the first tick */ @@ -355,41 +354,41 @@ static int clock_thread(void *arg) while (!clock->quitting) { - pj_get_timestamp(&now); + pj_get_timestamp(&now); - /* Wait for the next tick to happen */ - if (now.u64 < clock->next_tick.u64) { - unsigned msec; - msec = pj_elapsed_msec(&now, &clock->next_tick); - pj_thread_sleep(msec); - } + /* Wait for the next tick to happen */ + if (now.u64 < clock->next_tick.u64) { + unsigned msec; + msec = pj_elapsed_msec(&now, &clock->next_tick); + pj_thread_sleep(msec); + } - /* Skip if not running */ - if (!clock->running) { - /* Calculate next tick */ - clock_calc_next_tick(clock, &now); - continue; - } + /* Skip if not running */ + if (!clock->running) { + /* Calculate next tick */ + clock_calc_next_tick(clock, &now); + continue; + } - pj_lock_acquire(clock->lock); + pj_lock_acquire(clock->lock); - /* Call callback, if any */ - if (clock->cb) - (*clock->cb)(&clock->timestamp, clock->user_data); + /* Call callback, if any */ + if (clock->cb) + (*clock->cb)(&clock->timestamp, clock->user_data); - /* Best effort way to detect if we've been destroyed in the callback */ - if (clock->quitting) { - pj_lock_release(clock->lock); - break; - } + /* Best effort way to detect if we've been destroyed in the callback */ + if (clock->quitting) { + pj_lock_release(clock->lock); + break; + } - /* Increment timestamp */ - clock->timestamp.u64 += clock->timestamp_inc; + /* Increment timestamp */ + clock->timestamp.u64 += clock->timestamp_inc; - /* Calculate next tick */ - clock_calc_next_tick(clock, &now); + /* Calculate next tick */ + clock_calc_next_tick(clock, &now); - pj_lock_release(clock->lock); + pj_lock_release(clock->lock); } return 0; @@ -407,14 +406,14 @@ PJ_DEF(pj_status_t) pjmedia_clock_destroy(pjmedia_clock *clock) clock->quitting = PJ_TRUE; if (clock->thread) { - pj_thread_join(clock->thread); - pj_thread_destroy(clock->thread); - clock->thread = NULL; + pj_thread_join(clock->thread); + pj_thread_destroy(clock->thread); + clock->thread = NULL; } if (clock->lock) { - pj_lock_destroy(clock->lock); - clock->lock = NULL; + pj_lock_destroy(clock->lock); + clock->lock = NULL; } pj_pool_safe_release(&clock->pool); diff --git a/pjmedia/src/pjmedia/codec.c b/pjmedia/src/pjmedia/codec.c index 5d40418907..5ccf09720a 100644 --- a/pjmedia/src/pjmedia/codec.c +++ b/pjmedia/src/pjmedia/codec.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,8 +30,8 @@ /* Definition of default codecs parameters */ struct pjmedia_codec_default_param { - pj_pool_t *pool; - pjmedia_codec_param *param; + pj_pool_t *pool; + pjmedia_codec_param *param; }; @@ -44,8 +43,8 @@ static void sort_codecs(pjmedia_codec_mgr *mgr); * Duplicate codec parameter. */ PJ_DEF(pjmedia_codec_param*) pjmedia_codec_param_clone( - pj_pool_t *pool, - const pjmedia_codec_param *src) + pj_pool_t *pool, + const pjmedia_codec_param *src) { pjmedia_codec_param *p; unsigned i; @@ -57,16 +56,16 @@ PJ_DEF(pjmedia_codec_param*) pjmedia_codec_param_clone( /* Update codec param */ pj_memcpy(p, src, sizeof(pjmedia_codec_param)); for (i = 0; i < src->setting.dec_fmtp.cnt; ++i) { - pj_strdup(pool, &p->setting.dec_fmtp.param[i].name, - &src->setting.dec_fmtp.param[i].name); - pj_strdup(pool, &p->setting.dec_fmtp.param[i].val, - &src->setting.dec_fmtp.param[i].val); + pj_strdup(pool, &p->setting.dec_fmtp.param[i].name, + &src->setting.dec_fmtp.param[i].name); + pj_strdup(pool, &p->setting.dec_fmtp.param[i].val, + &src->setting.dec_fmtp.param[i].val); } for (i = 0; i < src->setting.enc_fmtp.cnt; ++i) { - pj_strdup(pool, &p->setting.enc_fmtp.param[i].name, - &src->setting.enc_fmtp.param[i].name); - pj_strdup(pool, &p->setting.enc_fmtp.param[i].val, - &src->setting.enc_fmtp.param[i].val); + pj_strdup(pool, &p->setting.enc_fmtp.param[i].name, + &src->setting.enc_fmtp.param[i].name); + pj_strdup(pool, &p->setting.enc_fmtp.param[i].val, + &src->setting.enc_fmtp.param[i].val); } return p; @@ -77,7 +76,7 @@ PJ_DEF(pjmedia_codec_param*) pjmedia_codec_param_clone( * Initialize codec manager. */ PJ_DEF(pj_status_t) pjmedia_codec_mgr_init (pjmedia_codec_mgr *mgr, - pj_pool_factory *pf) + pj_pool_factory *pf) { pj_status_t status; @@ -95,7 +94,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_init (pjmedia_codec_mgr *mgr, /* Create mutex */ status = pj_mutex_create_recursive(mgr->pool, "codec-mgr", &mgr->mutex); if (status != PJ_SUCCESS) - return status; + return status; return PJ_SUCCESS; } @@ -113,26 +112,26 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_destroy (pjmedia_codec_mgr *mgr) /* Destroy all factories in the list */ factory = mgr->factory_list.next; while (factory != &mgr->factory_list) { - pjmedia_codec_factory *next = factory->next; - (*factory->op->destroy)(); - factory = next; + pjmedia_codec_factory *next = factory->next; + (*factory->op->destroy)(); + factory = next; } /* Cleanup all pools of all codec default params */ for (i=0; icodec_cnt; ++i) { - if (mgr->codec_desc[i].param) { - pj_assert(mgr->codec_desc[i].param->pool); - pj_pool_release(mgr->codec_desc[i].param->pool); - } + if (mgr->codec_desc[i].param) { + pj_assert(mgr->codec_desc[i].param->pool); + pj_pool_release(mgr->codec_desc[i].param->pool); + } } /* Destroy mutex */ if (mgr->mutex) - pj_mutex_destroy(mgr->mutex); + pj_mutex_destroy(mgr->mutex); /* Release pool */ if (mgr->pool) - pj_pool_release(mgr->pool); + pj_pool_release(mgr->pool); /* Just for safety, set codec manager states to zero */ pj_bzero(mgr, sizeof(pjmedia_codec_mgr)); @@ -145,7 +144,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_destroy (pjmedia_codec_mgr *mgr) * Register a codec factory. */ PJ_DEF(pj_status_t) pjmedia_codec_mgr_register_factory( pjmedia_codec_mgr *mgr, - pjmedia_codec_factory *factory) + pjmedia_codec_factory *factory) { pjmedia_codec_info info[PJMEDIA_CODEC_MGR_MAX_CODECS]; unsigned i, count; @@ -164,26 +163,26 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_register_factory( pjmedia_codec_mgr *mgr, count = PJ_ARRAY_SIZE(info); status = factory->op->enum_info(factory, &count, info); if (status != PJ_SUCCESS) - return status; + return status; pj_mutex_lock(mgr->mutex); /* Check codec count */ if (count + mgr->codec_cnt > PJ_ARRAY_SIZE(mgr->codec_desc)) { - pj_mutex_unlock(mgr->mutex); - return PJ_ETOOMANY; + pj_mutex_unlock(mgr->mutex); + return PJ_ETOOMANY; } /* Save the codecs */ for (i=0; icodec_desc[mgr->codec_cnt+i], - &info[i], sizeof(pjmedia_codec_info)); - mgr->codec_desc[mgr->codec_cnt+i].prio = PJMEDIA_CODEC_PRIO_NORMAL; - mgr->codec_desc[mgr->codec_cnt+i].factory = factory; - pjmedia_codec_info_to_id( &info[i], - mgr->codec_desc[mgr->codec_cnt+i].id, - sizeof(pjmedia_codec_id)); + pj_memcpy( &mgr->codec_desc[mgr->codec_cnt+i], + &info[i], sizeof(pjmedia_codec_info)); + mgr->codec_desc[mgr->codec_cnt+i].prio = PJMEDIA_CODEC_PRIO_NORMAL; + mgr->codec_desc[mgr->codec_cnt+i].factory = factory; + pjmedia_codec_info_to_id( &info[i], + mgr->codec_desc[mgr->codec_cnt+i].id, + sizeof(pjmedia_codec_id)); } /* Update count */ @@ -205,8 +204,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_register_factory( pjmedia_codec_mgr *mgr, * Unregister a codec factory. */ PJ_DEF(pj_status_t) pjmedia_codec_mgr_unregister_factory( - pjmedia_codec_mgr *mgr, - pjmedia_codec_factory *factory) + pjmedia_codec_mgr *mgr, + pjmedia_codec_factory *factory) { unsigned i; PJ_ASSERT_RETURN(mgr && factory, PJ_EINVAL); @@ -215,8 +214,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_unregister_factory( /* Factory must be registered. */ if (pj_list_find_node(&mgr->factory_list, factory) != factory) { - pj_mutex_unlock(mgr->mutex); - return PJ_ENOTFOUND; + pj_mutex_unlock(mgr->mutex); + return PJ_ENOTFOUND; } /* Erase factory from the factory list */ @@ -228,21 +227,21 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_unregister_factory( */ for (i=0; icodec_cnt; ) { - if (mgr->codec_desc[i].factory == factory) { - /* Release pool of codec default param */ - if (mgr->codec_desc[i].param) { - pj_assert(mgr->codec_desc[i].param->pool); - pj_pool_release(mgr->codec_desc[i].param->pool); - } - - /* Remove the codec from array of codec descriptions */ - pj_array_erase(mgr->codec_desc, sizeof(mgr->codec_desc[0]), - mgr->codec_cnt, i); - --mgr->codec_cnt; - - } else { - ++i; - } + if (mgr->codec_desc[i].factory == factory) { + /* Release pool of codec default param */ + if (mgr->codec_desc[i].param) { + pj_assert(mgr->codec_desc[i].param->pool); + pj_pool_release(mgr->codec_desc[i].param->pool); + } + + /* Remove the codec from array of codec descriptions */ + pj_array_erase(mgr->codec_desc, sizeof(mgr->codec_desc[0]), + mgr->codec_cnt, i); + --mgr->codec_cnt; + + } else { + ++i; + } } pj_mutex_unlock(mgr->mutex); @@ -255,9 +254,9 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_unregister_factory( * Enum all codecs. */ PJ_DEF(pj_status_t) pjmedia_codec_mgr_enum_codecs(pjmedia_codec_mgr *mgr, - unsigned *count, - pjmedia_codec_info codecs[], - unsigned *prio) + unsigned *count, + pjmedia_codec_info codecs[], + unsigned *prio) { unsigned i; @@ -266,17 +265,17 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_enum_codecs(pjmedia_codec_mgr *mgr, pj_mutex_lock(mgr->mutex); if (*count > mgr->codec_cnt) - *count = mgr->codec_cnt; + *count = mgr->codec_cnt; for (i=0; i<*count; ++i) { - pj_memcpy(&codecs[i], - &mgr->codec_desc[i].info, - sizeof(pjmedia_codec_info)); + pj_memcpy(&codecs[i], + &mgr->codec_desc[i].info, + sizeof(pjmedia_codec_info)); } if (prio) { - for (i=0; i < *count; ++i) - prio[i] = mgr->codec_desc[i].prio; + for (i=0; i < *count; ++i) + prio[i] = mgr->codec_desc[i].prio; } pj_mutex_unlock(mgr->mutex); @@ -289,8 +288,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_enum_codecs(pjmedia_codec_mgr *mgr, * Get codec info for static payload type. */ PJ_DEF(pj_status_t) pjmedia_codec_mgr_get_codec_info( pjmedia_codec_mgr *mgr, - unsigned pt, - const pjmedia_codec_info **p_info) + unsigned pt, + const pjmedia_codec_info **p_info) { unsigned i; @@ -299,12 +298,12 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_get_codec_info( pjmedia_codec_mgr *mgr, pj_mutex_lock(mgr->mutex); for (i=0; icodec_cnt; ++i) { - if (mgr->codec_desc[i].info.pt == pt) { - *p_info = &mgr->codec_desc[i].info; + if (mgr->codec_desc[i].info.pt == pt) { + *p_info = &mgr->codec_desc[i].info; - pj_mutex_unlock(mgr->mutex); - return PJ_SUCCESS; - } + pj_mutex_unlock(mgr->mutex); + return PJ_SUCCESS; + } } pj_mutex_unlock(mgr->mutex); @@ -318,21 +317,21 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_get_codec_info( pjmedia_codec_mgr *mgr, * A codec identifier looks something like "L16/44100/2". */ PJ_DEF(char*) pjmedia_codec_info_to_id( const pjmedia_codec_info *info, - char *id, unsigned max_len ) + char *id, unsigned max_len ) { int len; PJ_ASSERT_RETURN(info && id && max_len, NULL); len = pj_ansi_snprintf(id, max_len, "%.*s/%u/%u", - (int)info->encoding_name.slen, - info->encoding_name.ptr, - info->clock_rate, - info->channel_cnt); + (int)info->encoding_name.slen, + info->encoding_name.ptr, + info->clock_rate, + info->channel_cnt); if (len < 1 || len >= (int)max_len) { - id[0] = '\0'; - return NULL; + id[0] = '\0'; + return NULL; } return id; @@ -346,10 +345,10 @@ PJ_DEF(char*) pjmedia_codec_info_to_id( const pjmedia_codec_info *info, * and so on, up to the maximum count specified in the argument. */ PJ_DEF(pj_status_t) pjmedia_codec_mgr_find_codecs_by_id( pjmedia_codec_mgr *mgr, - const pj_str_t *codec_id, - unsigned *count, - const pjmedia_codec_info *p_info[], - unsigned prio[]) + const pj_str_t *codec_id, + unsigned *count, + const pjmedia_codec_info *p_info[], + unsigned prio[]) { unsigned i, found = 0; @@ -359,21 +358,21 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_find_codecs_by_id( pjmedia_codec_mgr *mgr, for (i=0; icodec_cnt; ++i) { - if (codec_id->slen == 0 || - pj_strnicmp2(codec_id, mgr->codec_desc[i].id, - codec_id->slen) == 0) - { + if (codec_id->slen == 0 || + pj_strnicmp2(codec_id, mgr->codec_desc[i].id, + codec_id->slen) == 0) + { - if (p_info) - p_info[found] = &mgr->codec_desc[i].info; - if (prio) - prio[found] = mgr->codec_desc[i].prio; + if (p_info) + p_info[found] = &mgr->codec_desc[i].info; + if (prio) + prio[found] = mgr->codec_desc[i].prio; - ++found; + ++found; - if (found >= *count) - break; - } + if (found >= *count) + break; + } } @@ -393,7 +392,7 @@ static void swap_codec(pjmedia_codec_mgr *mgr, unsigned i, unsigned j) pj_memcpy(&tmp, &mgr->codec_desc[i], sizeof(struct pjmedia_codec_desc)); pj_memcpy(&mgr->codec_desc[i], &mgr->codec_desc[j], - sizeof(struct pjmedia_codec_desc)); + sizeof(struct pjmedia_codec_desc)); pj_memcpy(&mgr->codec_desc[j], &tmp, sizeof(struct pjmedia_codec_desc)); } @@ -406,23 +405,23 @@ static void sort_codecs(pjmedia_codec_mgr *mgr) /* Re-sort */ for (i=0; icodec_cnt; ++i) { - unsigned j, max; + unsigned j, max; - for (max=i, j=i+1; jcodec_cnt; ++j) { - if (mgr->codec_desc[j].prio > mgr->codec_desc[max].prio) - max = j; - } + for (max=i, j=i+1; jcodec_cnt; ++j) { + if (mgr->codec_desc[j].prio > mgr->codec_desc[max].prio) + max = j; + } - if (max != i) - swap_codec(mgr, i, max); + if (max != i) + swap_codec(mgr, i, max); } /* Change PJMEDIA_CODEC_PRIO_HIGHEST codecs to NEXT_HIGHER */ for (i=0; icodec_cnt; ++i) { - if (mgr->codec_desc[i].prio == PJMEDIA_CODEC_PRIO_HIGHEST) - mgr->codec_desc[i].prio = PJMEDIA_CODEC_PRIO_NEXT_HIGHER; - else - break; + if (mgr->codec_desc[i].prio == PJMEDIA_CODEC_PRIO_HIGHEST) + mgr->codec_desc[i].prio = PJMEDIA_CODEC_PRIO_NEXT_HIGHER; + else + break; } } @@ -434,9 +433,9 @@ static void sort_codecs(pjmedia_codec_mgr *mgr) * priorities of all those codecs. */ PJ_DEF(pj_status_t) pjmedia_codec_mgr_set_codec_priority( - pjmedia_codec_mgr *mgr, - const pj_str_t *codec_id, - pj_uint8_t prio) + pjmedia_codec_mgr *mgr, + const pj_str_t *codec_id, + pj_uint8_t prio) { unsigned i, found = 0; @@ -447,18 +446,18 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_set_codec_priority( /* Update the priorities of affected codecs */ for (i=0; icodec_cnt; ++i) { - if (codec_id->slen == 0 || - pj_strnicmp2(codec_id, mgr->codec_desc[i].id, - codec_id->slen) == 0) - { - mgr->codec_desc[i].prio = (pjmedia_codec_priority) prio; - ++found; - } + if (codec_id->slen == 0 || + pj_strnicmp2(codec_id, mgr->codec_desc[i].id, + codec_id->slen) == 0) + { + mgr->codec_desc[i].prio = (pjmedia_codec_priority) prio; + ++found; + } } if (!found) { - pj_mutex_unlock(mgr->mutex); - return PJ_ENOTFOUND; + pj_mutex_unlock(mgr->mutex); + return PJ_ENOTFOUND; } /* Re-sort codecs */ @@ -474,8 +473,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_set_codec_priority( * Allocate one codec. */ PJ_DEF(pj_status_t) pjmedia_codec_mgr_alloc_codec(pjmedia_codec_mgr *mgr, - const pjmedia_codec_info *info, - pjmedia_codec **p_codec) + const pjmedia_codec_info *info, + pjmedia_codec **p_codec) { pjmedia_codec_factory *factory; pj_status_t status; @@ -489,17 +488,17 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_alloc_codec(pjmedia_codec_mgr *mgr, factory = mgr->factory_list.next; while (factory != &mgr->factory_list) { - if ( (*factory->op->test_alloc)(factory, info) == PJ_SUCCESS ) { + if ( (*factory->op->test_alloc)(factory, info) == PJ_SUCCESS ) { - status = (*factory->op->alloc_codec)(factory, info, p_codec); - if (status == PJ_SUCCESS) { - pj_mutex_unlock(mgr->mutex); - return PJ_SUCCESS; - } + status = (*factory->op->alloc_codec)(factory, info, p_codec); + if (status == PJ_SUCCESS) { + pj_mutex_unlock(mgr->mutex); + return PJ_SUCCESS; + } - } + } - factory = factory->next; + factory = factory->next; } pj_mutex_unlock(mgr->mutex); @@ -512,8 +511,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_alloc_codec(pjmedia_codec_mgr *mgr, * Get default codec parameter. */ PJ_DEF(pj_status_t) pjmedia_codec_mgr_get_default_param( pjmedia_codec_mgr *mgr, - const pjmedia_codec_info *info, - pjmedia_codec_param *param ) + const pjmedia_codec_info *info, + pjmedia_codec_param *param ) { pjmedia_codec_factory *factory; pj_status_t status; @@ -524,47 +523,47 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_get_default_param( pjmedia_codec_mgr *mgr, PJ_ASSERT_RETURN(mgr && info && param, PJ_EINVAL); if (!pjmedia_codec_info_to_id(info, (char*)&codec_id, sizeof(codec_id))) - return PJ_EINVAL; + return PJ_EINVAL; pj_mutex_lock(mgr->mutex); /* First, lookup default param in codec desc */ for (i=0; i < mgr->codec_cnt; ++i) { - if (pj_ansi_stricmp(codec_id, mgr->codec_desc[i].id) == 0) { - codec_desc = &mgr->codec_desc[i]; - break; - } + if (pj_ansi_stricmp(codec_id, mgr->codec_desc[i].id) == 0) { + codec_desc = &mgr->codec_desc[i]; + break; + } } /* If we found the codec and its default param is set, return it */ if (codec_desc && codec_desc->param) { - pj_assert(codec_desc->param->param); - pj_memcpy(param, codec_desc->param->param, - sizeof(pjmedia_codec_param)); + pj_assert(codec_desc->param->param); + pj_memcpy(param, codec_desc->param->param, + sizeof(pjmedia_codec_param)); - pj_mutex_unlock(mgr->mutex); - return PJ_SUCCESS; + pj_mutex_unlock(mgr->mutex); + return PJ_SUCCESS; } /* Otherwise query the default param from codec factory */ factory = mgr->factory_list.next; while (factory != &mgr->factory_list) { - if ( (*factory->op->test_alloc)(factory, info) == PJ_SUCCESS ) { + if ( (*factory->op->test_alloc)(factory, info) == PJ_SUCCESS ) { - status = (*factory->op->default_attr)(factory, info, param); - if (status == PJ_SUCCESS) { - /* Check for invalid max_bps. */ - if (param->info.max_bps < param->info.avg_bps) - param->info.max_bps = param->info.avg_bps; + status = (*factory->op->default_attr)(factory, info, param); + if (status == PJ_SUCCESS) { + /* Check for invalid max_bps. */ + if (param->info.max_bps < param->info.avg_bps) + param->info.max_bps = param->info.avg_bps; - pj_mutex_unlock(mgr->mutex); - return PJ_SUCCESS; - } + pj_mutex_unlock(mgr->mutex); + return PJ_SUCCESS; + } - } + } - factory = factory->next; + factory = factory->next; } pj_mutex_unlock(mgr->mutex); @@ -578,9 +577,9 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_get_default_param( pjmedia_codec_mgr *mgr, * Set default codec parameter. */ PJ_DEF(pj_status_t) pjmedia_codec_mgr_set_default_param( - pjmedia_codec_mgr *mgr, - const pjmedia_codec_info *info, - const pjmedia_codec_param *param ) + pjmedia_codec_mgr *mgr, + const pjmedia_codec_info *info, + const pjmedia_codec_param *param ) { unsigned i; pjmedia_codec_id codec_id; @@ -591,41 +590,41 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_set_default_param( PJ_ASSERT_RETURN(mgr && info, PJ_EINVAL); if (!pjmedia_codec_info_to_id(info, (char*)&codec_id, sizeof(codec_id))) - return PJ_EINVAL; + return PJ_EINVAL; pj_mutex_lock(mgr->mutex); /* Lookup codec desc */ for (i=0; i < mgr->codec_cnt; ++i) { - if (pj_ansi_stricmp(codec_id, mgr->codec_desc[i].id) == 0) { - codec_desc = &mgr->codec_desc[i]; - break; - } + if (pj_ansi_stricmp(codec_id, mgr->codec_desc[i].id) == 0) { + codec_desc = &mgr->codec_desc[i]; + break; + } } /* Codec not found */ if (!codec_desc) { - pj_mutex_unlock(mgr->mutex); - return PJMEDIA_CODEC_EUNSUP; + pj_mutex_unlock(mgr->mutex); + return PJMEDIA_CODEC_EUNSUP; } /* If codec param is previously set, reset the codec param but release * the codec param pool later after the new param is set (ticket #1171). */ if (codec_desc->param) { - pj_assert(codec_desc->param->pool); + pj_assert(codec_desc->param->pool); old_pool = codec_desc->param->pool; - codec_desc->param = NULL; + codec_desc->param = NULL; } /* When param is set to NULL, i.e: setting default codec param to library * default setting, just return PJ_SUCCESS. */ if (NULL == param) { - pj_mutex_unlock(mgr->mutex); + pj_mutex_unlock(mgr->mutex); if (old_pool) - pj_pool_release(old_pool); - return PJ_SUCCESS; + pj_pool_release(old_pool); + return PJ_SUCCESS; } /* Instantiate and initialize codec param */ @@ -637,14 +636,14 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_set_default_param( /* Update codec param */ p->param = pjmedia_codec_param_clone(pool, param); if (!p->param) { - pj_mutex_unlock(mgr->mutex); - return PJ_EINVAL; + pj_mutex_unlock(mgr->mutex); + return PJ_EINVAL; } pj_mutex_unlock(mgr->mutex); if (old_pool) - pj_pool_release(old_pool); + pj_pool_release(old_pool); return PJ_SUCCESS; } @@ -654,7 +653,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_mgr_set_default_param( * Dealloc codec. */ PJ_DEF(pj_status_t) pjmedia_codec_mgr_dealloc_codec(pjmedia_codec_mgr *mgr, - pjmedia_codec *codec) + pjmedia_codec *codec) { PJ_ASSERT_RETURN(mgr && codec, PJ_EINVAL); diff --git a/pjmedia/src/pjmedia/conf_switch.c b/pjmedia/src/pjmedia/conf_switch.c index 114b48a04f..74a3ffd7c1 100644 --- a/pjmedia/src/pjmedia/conf_switch.c +++ b/pjmedia/src/pjmedia/conf_switch.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -43,16 +42,16 @@ # define TRACE_(x) #endif -#define THIS_FILE "conf_switch.c" +#define THIS_FILE "conf_switch.c" -#define SIGNATURE PJMEDIA_CONF_SWITCH_SIGNATURE -#define SIGNATURE_PORT PJMEDIA_PORT_SIGNATURE('S', 'W', 'T', 'P') -#define NORMAL_LEVEL 128 -#define SLOT_TYPE unsigned -#define INVALID_SLOT ((SLOT_TYPE)-1) -#define BUFFER_SIZE PJMEDIA_CONF_SWITCH_BOARD_BUF_SIZE -#define MAX_LEVEL (32767) -#define MIN_LEVEL (-32768) +#define SIGNATURE PJMEDIA_CONF_SWITCH_SIGNATURE +#define SIGNATURE_PORT PJMEDIA_PORT_SIGNATURE('S', 'W', 'T', 'P') +#define NORMAL_LEVEL 128 +#define SLOT_TYPE unsigned +#define INVALID_SLOT ((SLOT_TYPE)-1) +#define BUFFER_SIZE PJMEDIA_CONF_SWITCH_BOARD_BUF_SIZE +#define MAX_LEVEL (32767) +#define MIN_LEVEL (-32768) /* * DON'T GET CONFUSED WITH TX/RX!! @@ -69,39 +68,39 @@ */ struct conf_port { - SLOT_TYPE slot; /**< Array of listeners. */ - pj_str_t name; /**< Port name. */ - pjmedia_port *port; /**< get_frame() and put_frame() */ - pjmedia_port_op rx_setting; /**< Can we receive from this port */ - pjmedia_port_op tx_setting; /**< Can we transmit to this port */ - unsigned listener_cnt; /**< Number of listeners. */ - SLOT_TYPE *listener_slots;/**< Array of listeners. */ - unsigned transmitter_cnt;/**info.fmt.id == PJMEDIA_FORMAT_PCM && - PJMEDIA_PIA_SPF(&port->info)*2 > BUFFER_SIZE - sizeof(pjmedia_frame)) + PJMEDIA_PIA_SPF(&port->info)*2 > BUFFER_SIZE - sizeof(pjmedia_frame)) { - pj_assert(!"Too small buffer size for audio switchboard. " - "Try increase PJMEDIA_CONF_SWITCH_BOARD_BUF_SIZE"); - return PJ_ETOOSMALL; + pj_assert(!"Too small buffer size for audio switchboard. " + "Try increase PJMEDIA_CONF_SWITCH_BOARD_BUF_SIZE"); + return PJ_ETOOSMALL; } /* Create port. */ @@ -169,8 +168,8 @@ static pj_status_t create_conf_port( pj_pool_t *pool, /* Create transmit flag array */ conf_port->listener_slots = (SLOT_TYPE*) - pj_pool_zalloc(pool, - conf->max_ports * sizeof(SLOT_TYPE)); + pj_pool_zalloc(pool, + conf->max_ports * sizeof(SLOT_TYPE)); PJ_ASSERT_RETURN(conf_port->listener_slots, PJ_ENOMEM); /* Save some port's infos, for convenience. */ @@ -191,7 +190,7 @@ static pj_status_t create_conf_port( pj_pool_t *pool, * Create port zero for the sound device. */ static pj_status_t create_sound_port( pj_pool_t *pool, - pjmedia_conf *conf ) + pjmedia_conf *conf ) { struct conf_port *conf_port; pj_str_t name = { "Master/sound", 12 }; @@ -199,7 +198,7 @@ static pj_status_t create_sound_port( pj_pool_t *pool, status = create_conf_port(pool, conf, conf->master_port, &name, &conf_port); if (status != PJ_SUCCESS) - return status; + return status; /* Add the port to the bridge */ conf_port->slot = 0; @@ -214,13 +213,13 @@ static pj_status_t create_sound_port( pj_pool_t *pool, * Create conference bridge. */ PJ_DEF(pj_status_t) pjmedia_conf_create( pj_pool_t *pool, - unsigned max_ports, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_conf **p_conf ) + unsigned max_ports, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_conf **p_conf ) { pjmedia_conf *conf; const pj_str_t name = { "Conf", 4 }; @@ -230,14 +229,14 @@ PJ_DEF(pj_status_t) pjmedia_conf_create( pj_pool_t *pool, PJ_ASSERT_RETURN(bits_per_sample == 16, PJ_EINVAL); PJ_LOG(5,(THIS_FILE, "Creating conference bridge with %d ports", - max_ports)); + max_ports)); /* Create and init conf structure. */ conf = PJ_POOL_ZALLOC_T(pool, pjmedia_conf); PJ_ASSERT_RETURN(conf, PJ_ENOMEM); conf->ports = (struct conf_port**) - pj_pool_zalloc(pool, max_ports*sizeof(void*)); + pj_pool_zalloc(pool, max_ports*sizeof(void*)); PJ_ASSERT_RETURN(conf->ports, PJ_ENOMEM); conf->options = options; @@ -248,8 +247,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_create( pj_pool_t *pool, PJ_ASSERT_RETURN(conf->master_port, PJ_ENOMEM); pjmedia_port_info_init(&conf->master_port->info, &name, SIGNATURE, - clock_rate, channel_count, bits_per_sample, - samples_per_frame); + clock_rate, channel_count, bits_per_sample, + samples_per_frame); conf->master_port->port_data.pdata = conf; conf->master_port->port_data.ldata = 0; @@ -262,12 +261,12 @@ PJ_DEF(pj_status_t) pjmedia_conf_create( pj_pool_t *pool, /* Create port zero for sound device. */ status = create_sound_port(pool, conf); if (status != PJ_SUCCESS) - return status; + return status; /* Create mutex. */ status = pj_mutex_create_recursive(pool, "conf", &conf->mutex); if (status != PJ_SUCCESS) - return status; + return status; /* Done */ @@ -342,7 +341,7 @@ PJ_DEF(pjmedia_port*) pjmedia_conf_get_master_port(pjmedia_conf *conf) * Set master port name. */ PJ_DEF(pj_status_t) pjmedia_conf_set_port0_name(pjmedia_conf *conf, - const pj_str_t *name) + const pj_str_t *name) { unsigned len; @@ -351,7 +350,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_set_port0_name(pjmedia_conf *conf, len = name->slen; if (len > sizeof(conf->master_name_buf)) - len = sizeof(conf->master_name_buf); + len = sizeof(conf->master_name_buf); if (len > 0) pj_memcpy(conf->master_name_buf, name->ptr, len); @@ -367,10 +366,10 @@ PJ_DEF(pj_status_t) pjmedia_conf_set_port0_name(pjmedia_conf *conf, * Add stream port to the conference bridge. */ PJ_DEF(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, - pj_pool_t *pool, - pjmedia_port *strm_port, - const pj_str_t *port_name, - unsigned *p_port ) + pj_pool_t *pool, + pjmedia_port *strm_port, + const pj_str_t *port_name, + unsigned *p_port ) { struct conf_port *conf_port; unsigned index; @@ -379,11 +378,11 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, PJ_ASSERT_RETURN(conf && pool && strm_port, PJ_EINVAL); /* PJ_ASSERT_RETURN(conf->clock_rate == strm_port->info.clock_rate, - PJMEDIA_ENCCLOCKRATE); + PJMEDIA_ENCCLOCKRATE); PJ_ASSERT_RETURN(conf->channel_count == strm_port->info.channel_count, - PJMEDIA_ENCCHANNEL); + PJMEDIA_ENCCHANNEL); PJ_ASSERT_RETURN(conf->bits_per_sample == strm_port->info.bits_per_sample, - PJMEDIA_ENCBITS); + PJMEDIA_ENCBITS); */ /* Port's samples per frame should be equal to or multiplication of @@ -392,28 +391,28 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, /* Not sure if this is needed! PJ_ASSERT_RETURN((conf->samples_per_frame % - strm_port->info.samples_per_frame==0) || - (strm_port->info.samples_per_frame % - conf->samples_per_frame==0), - PJMEDIA_ENCSAMPLESPFRAME); + strm_port->info.samples_per_frame==0) || + (strm_port->info.samples_per_frame % + conf->samples_per_frame==0), + PJMEDIA_ENCSAMPLESPFRAME); */ /* If port_name is not specified, use the port's name */ if (!port_name) - port_name = &strm_port->info.name; + port_name = &strm_port->info.name; pj_mutex_lock(conf->mutex); if (conf->port_cnt >= conf->max_ports) { - pj_assert(!"Too many ports"); - pj_mutex_unlock(conf->mutex); - return PJ_ETOOMANY; + pj_assert(!"Too many ports"); + pj_mutex_unlock(conf->mutex); + return PJ_ETOOMANY; } /* Find empty port in the conference bridge. */ for (index=0; index < conf->max_ports; ++index) { - if (conf->ports[index] == NULL) - break; + if (conf->ports[index] == NULL) + break; } pj_assert(index != conf->max_ports); @@ -421,8 +420,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, /* Create conf port structure. */ status = create_conf_port(pool, conf, strm_port, port_name, &conf_port); if (status != PJ_SUCCESS) { - pj_mutex_unlock(conf->mutex); - return status; + pj_mutex_unlock(conf->mutex); + return status; } /* Put the port. */ @@ -432,7 +431,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, /* Done. */ if (p_port) { - *p_port = index; + *p_port = index; } pj_mutex_unlock(conf->mutex); @@ -445,15 +444,15 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, * Add passive port. */ PJ_DEF(pj_status_t) pjmedia_conf_add_passive_port( pjmedia_conf *conf, - pj_pool_t *pool, - const pj_str_t *name, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - unsigned *p_slot, - pjmedia_port **p_port ) + pj_pool_t *pool, + const pj_str_t *name, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + unsigned *p_slot, + pjmedia_port **p_port ) { PJ_UNUSED_ARG(conf); PJ_UNUSED_ARG(pool); @@ -475,9 +474,9 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_passive_port( pjmedia_conf *conf, * Change TX and RX settings for the port. */ PJ_DEF(pj_status_t) pjmedia_conf_configure_port( pjmedia_conf *conf, - unsigned slot, - pjmedia_port_op tx, - pjmedia_port_op rx) + unsigned slot, + pjmedia_port_op tx, + pjmedia_port_op rx) { struct conf_port *conf_port; @@ -489,15 +488,15 @@ PJ_DEF(pj_status_t) pjmedia_conf_configure_port( pjmedia_conf *conf, /* Port must be valid. */ conf_port = conf->ports[slot]; if (conf_port == NULL) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } if (tx != PJMEDIA_PORT_NO_CHANGE) - conf_port->tx_setting = tx; + conf_port->tx_setting = tx; if (rx != PJMEDIA_PORT_NO_CHANGE) - conf_port->rx_setting = rx; + conf_port->rx_setting = rx; pj_mutex_unlock(conf->mutex); @@ -509,9 +508,9 @@ PJ_DEF(pj_status_t) pjmedia_conf_configure_port( pjmedia_conf *conf, * Connect port. */ PJ_DEF(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, - unsigned src_slot, - unsigned sink_slot, - int level ) + unsigned src_slot, + unsigned sink_slot, + int level ) { struct conf_port *src_port, *dst_port; pj_bool_t start_sound = PJ_FALSE; @@ -520,7 +519,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, /* Check arguments */ PJ_ASSERT_RETURN(conf && src_slotmax_ports && - sink_slotmax_ports, PJ_EINVAL); + sink_slotmax_ports, PJ_EINVAL); /* For now, level MUST be zero. */ PJ_ASSERT_RETURN(level == 0, PJ_EINVAL); @@ -531,8 +530,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, src_port = conf->ports[src_slot]; dst_port = conf->ports[sink_slot]; if (!src_port || !dst_port) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } src_afd = pjmedia_format_get_audio_format_detail(&src_port->info->fmt, 1); @@ -540,63 +539,63 @@ PJ_DEF(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, /* Format must match. */ if (src_port->info->fmt.id != dst_port->info->fmt.id || - src_afd->avg_bps != dst_afd->avg_bps) + src_afd->avg_bps != dst_afd->avg_bps) { - pj_mutex_unlock(conf->mutex); - return PJMEDIA_ENOTCOMPATIBLE; + pj_mutex_unlock(conf->mutex); + return PJMEDIA_ENOTCOMPATIBLE; } /* Clock rate must match. */ if (src_afd->clock_rate != dst_afd->clock_rate) { - pj_mutex_unlock(conf->mutex); - return PJMEDIA_ENCCLOCKRATE; + pj_mutex_unlock(conf->mutex); + return PJMEDIA_ENCCLOCKRATE; } /* Channel count must match. */ if (src_afd->channel_count != dst_afd->channel_count) { - pj_mutex_unlock(conf->mutex); - return PJMEDIA_ENCCHANNEL; + pj_mutex_unlock(conf->mutex); + return PJMEDIA_ENCCHANNEL; } /* Source and sink ptime must be equal or a multiplication factor. */ if ((src_afd->frame_time_usec % dst_afd->frame_time_usec != 0) && (dst_afd->frame_time_usec % src_afd->frame_time_usec != 0)) { - pj_mutex_unlock(conf->mutex); - return PJMEDIA_ENCSAMPLESPFRAME; + pj_mutex_unlock(conf->mutex); + return PJMEDIA_ENCSAMPLESPFRAME; } /* If sink is currently listening to other ports, it needs to be released * first before the new connection made. */ if (dst_port->transmitter_cnt > 0) { - unsigned j; - pj_bool_t transmitter_found = PJ_FALSE; - - pj_assert(dst_port->transmitter_cnt == 1); - for (j=0; jmax_ports && !transmitter_found; ++j) { - if (conf->ports[j]) { - unsigned k; - - for (k=0; k < conf->ports[j]->listener_cnt; ++k) { - if (conf->ports[j]->listener_slots[k] == sink_slot) { - PJ_LOG(2,(THIS_FILE, "Connection [%d->%d] is " - "disconnected for new connection [%d->%d]", - j, sink_slot, src_slot, sink_slot)); - pjmedia_conf_disconnect_port(conf, j, sink_slot); - transmitter_found = PJ_TRUE; - break; - } - } - } - } - pj_assert(dst_port->transmitter_cnt == 0); + unsigned j; + pj_bool_t transmitter_found = PJ_FALSE; + + pj_assert(dst_port->transmitter_cnt == 1); + for (j=0; jmax_ports && !transmitter_found; ++j) { + if (conf->ports[j]) { + unsigned k; + + for (k=0; k < conf->ports[j]->listener_cnt; ++k) { + if (conf->ports[j]->listener_slots[k] == sink_slot) { + PJ_LOG(2,(THIS_FILE, "Connection [%d->%d] is " + "disconnected for new connection [%d->%d]", + j, sink_slot, src_slot, sink_slot)); + pjmedia_conf_disconnect_port(conf, j, sink_slot); + transmitter_found = PJ_TRUE; + break; + } + } + } + } + pj_assert(dst_port->transmitter_cnt == 0); } /* Check if connection has been made */ for (i=0; ilistener_cnt; ++i) { - if (src_port->listener_slots[i] == sink_slot) - break; + if (src_port->listener_slots[i] == sink_slot) + break; } /* Update master port info shortcut, note that application may update @@ -606,21 +605,21 @@ PJ_DEF(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, conf->ports[0]->samples_per_frame = PJMEDIA_PIA_SPF(conf->ports[0]->info); if (i == src_port->listener_cnt) { - src_port->listener_slots[src_port->listener_cnt] = sink_slot; - ++conf->connect_cnt; - ++src_port->listener_cnt; - ++dst_port->transmitter_cnt; - - if (conf->connect_cnt == 1) - start_sound = 1; - - PJ_LOG(4,(THIS_FILE,"Port %d (%.*s) transmitting to port %d (%.*s)", - src_slot, - (int)src_port->name.slen, - src_port->name.ptr, - sink_slot, - (int)dst_port->name.slen, - dst_port->name.ptr)); + src_port->listener_slots[src_port->listener_cnt] = sink_slot; + ++conf->connect_cnt; + ++src_port->listener_cnt; + ++dst_port->transmitter_cnt; + + if (conf->connect_cnt == 1) + start_sound = 1; + + PJ_LOG(4,(THIS_FILE,"Port %d (%.*s) transmitting to port %d (%.*s)", + src_slot, + (int)src_port->name.slen, + src_port->name.ptr, + sink_slot, + (int)dst_port->name.slen, + dst_port->name.ptr)); } pj_mutex_unlock(conf->mutex); @@ -629,7 +628,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, * sound thread will deadlock (?) */ if (start_sound) - resume_sound(conf); + resume_sound(conf); return PJ_SUCCESS; } @@ -639,15 +638,15 @@ PJ_DEF(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, * Disconnect port */ PJ_DEF(pj_status_t) pjmedia_conf_disconnect_port( pjmedia_conf *conf, - unsigned src_slot, - unsigned sink_slot ) + unsigned src_slot, + unsigned sink_slot ) { struct conf_port *src_port, *dst_port; unsigned i; /* Check arguments */ PJ_ASSERT_RETURN(conf && src_slotmax_ports && - sink_slotmax_ports, PJ_EINVAL); + sink_slotmax_ports, PJ_EINVAL); pj_mutex_lock(conf->mutex); @@ -655,50 +654,50 @@ PJ_DEF(pj_status_t) pjmedia_conf_disconnect_port( pjmedia_conf *conf, src_port = conf->ports[src_slot]; dst_port = conf->ports[sink_slot]; if (!src_port || !dst_port) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } /* Check if connection has been made */ for (i=0; ilistener_cnt; ++i) { - if (src_port->listener_slots[i] == sink_slot) - break; + if (src_port->listener_slots[i] == sink_slot) + break; } if (i != src_port->listener_cnt) { - pjmedia_frame_ext *f; - - pj_assert(src_port->listener_cnt > 0 && - src_port->listener_cnt < conf->max_ports); - pj_assert(dst_port->transmitter_cnt > 0 && - dst_port->transmitter_cnt < conf->max_ports); - pj_array_erase(src_port->listener_slots, sizeof(SLOT_TYPE), - src_port->listener_cnt, i); - --conf->connect_cnt; - --src_port->listener_cnt; - --dst_port->transmitter_cnt; - - /* Cleanup listener TX buffer. */ - f = (pjmedia_frame_ext*)dst_port->tx_buf; - f->base.type = PJMEDIA_FRAME_TYPE_NONE; - f->base.size = 0; - f->samples_cnt = 0; - f->subframe_cnt = 0; - - PJ_LOG(4,(THIS_FILE, - "Port %d (%.*s) stop transmitting to port %d (%.*s)", - src_slot, - (int)src_port->name.slen, - src_port->name.ptr, - sink_slot, - (int)dst_port->name.slen, - dst_port->name.ptr)); + pjmedia_frame_ext *f; + + pj_assert(src_port->listener_cnt > 0 && + src_port->listener_cnt < conf->max_ports); + pj_assert(dst_port->transmitter_cnt > 0 && + dst_port->transmitter_cnt < conf->max_ports); + pj_array_erase(src_port->listener_slots, sizeof(SLOT_TYPE), + src_port->listener_cnt, i); + --conf->connect_cnt; + --src_port->listener_cnt; + --dst_port->transmitter_cnt; + + /* Cleanup listener TX buffer. */ + f = (pjmedia_frame_ext*)dst_port->tx_buf; + f->base.type = PJMEDIA_FRAME_TYPE_NONE; + f->base.size = 0; + f->samples_cnt = 0; + f->subframe_cnt = 0; + + PJ_LOG(4,(THIS_FILE, + "Port %d (%.*s) stop transmitting to port %d (%.*s)", + src_slot, + (int)src_port->name.slen, + src_port->name.ptr, + sink_slot, + (int)dst_port->name.slen, + dst_port->name.ptr)); } pj_mutex_unlock(conf->mutex); if (conf->connect_cnt == 0) { - pause_sound(conf); + pause_sound(conf); } return PJ_SUCCESS; @@ -725,7 +724,7 @@ PJ_DEF(unsigned) pjmedia_conf_get_connect_count(pjmedia_conf *conf) * Remove the specified port. */ PJ_DEF(pj_status_t) pjmedia_conf_remove_port( pjmedia_conf *conf, - unsigned port ) + unsigned port ) { struct conf_port *conf_port; unsigned i; @@ -743,8 +742,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_remove_port( pjmedia_conf *conf, /* Port must be valid. */ conf_port = conf->ports[port]; if (conf_port == NULL) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } conf_port->tx_setting = PJMEDIA_PORT_DISABLE; @@ -752,48 +751,48 @@ PJ_DEF(pj_status_t) pjmedia_conf_remove_port( pjmedia_conf *conf, /* Remove this port from transmit array of other ports. */ for (i=0; imax_ports; ++i) { - unsigned j; - struct conf_port *src_port; - - src_port = conf->ports[i]; - - if (!src_port) - continue; - - if (src_port->listener_cnt == 0) - continue; - - for (j=0; jlistener_cnt; ++j) { - if (src_port->listener_slots[j] == port) { - pj_array_erase(src_port->listener_slots, sizeof(SLOT_TYPE), - src_port->listener_cnt, j); - pj_assert(conf->connect_cnt > 0); - --conf->connect_cnt; - --src_port->listener_cnt; - break; - } - } + unsigned j; + struct conf_port *src_port; + + src_port = conf->ports[i]; + + if (!src_port) + continue; + + if (src_port->listener_cnt == 0) + continue; + + for (j=0; jlistener_cnt; ++j) { + if (src_port->listener_slots[j] == port) { + pj_array_erase(src_port->listener_slots, sizeof(SLOT_TYPE), + src_port->listener_cnt, j); + pj_assert(conf->connect_cnt > 0); + --conf->connect_cnt; + --src_port->listener_cnt; + break; + } + } } /* Update transmitter_cnt of ports we're transmitting to */ while (conf_port->listener_cnt) { - unsigned dst_slot; - struct conf_port *dst_port; - pjmedia_frame_ext *f; - - dst_slot = conf_port->listener_slots[conf_port->listener_cnt-1]; - dst_port = conf->ports[dst_slot]; - --dst_port->transmitter_cnt; - --conf_port->listener_cnt; - pj_assert(conf->connect_cnt > 0); - --conf->connect_cnt; - - /* Cleanup & reinit listener TX buffer. */ - f = (pjmedia_frame_ext*)dst_port->tx_buf; - f->base.type = PJMEDIA_FRAME_TYPE_NONE; - f->base.size = 0; - f->samples_cnt = 0; - f->subframe_cnt = 0; + unsigned dst_slot; + struct conf_port *dst_port; + pjmedia_frame_ext *f; + + dst_slot = conf_port->listener_slots[conf_port->listener_cnt-1]; + dst_port = conf->ports[dst_slot]; + --dst_port->transmitter_cnt; + --conf_port->listener_cnt; + pj_assert(conf->connect_cnt > 0); + --conf->connect_cnt; + + /* Cleanup & reinit listener TX buffer. */ + f = (pjmedia_frame_ext*)dst_port->tx_buf; + f->base.type = PJMEDIA_FRAME_TYPE_NONE; + f->base.size = 0; + f->samples_cnt = 0; + f->subframe_cnt = 0; } /* Remove the port. */ @@ -805,7 +804,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_remove_port( pjmedia_conf *conf, /* Stop sound if there's no connection. */ if (conf->connect_cnt == 0) { - pause_sound(conf); + pause_sound(conf); } return PJ_SUCCESS; @@ -816,8 +815,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_remove_port( pjmedia_conf *conf, * Enum ports. */ PJ_DEF(pj_status_t) pjmedia_conf_enum_ports( pjmedia_conf *conf, - unsigned ports[], - unsigned *p_count ) + unsigned ports[], + unsigned *p_count ) { unsigned i, count=0; @@ -827,10 +826,10 @@ PJ_DEF(pj_status_t) pjmedia_conf_enum_ports( pjmedia_conf *conf, pj_mutex_lock(conf->mutex); for (i=0; imax_ports && count<*p_count; ++i) { - if (!conf->ports[i]) - continue; + if (!conf->ports[i]) + continue; - ports[count++] = i; + ports[count++] = i; } /* Unlock mutex */ @@ -844,8 +843,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_enum_ports( pjmedia_conf *conf, * Get port info */ PJ_DEF(pj_status_t) pjmedia_conf_get_port_info( pjmedia_conf *conf, - unsigned slot, - pjmedia_conf_port_info *info) + unsigned slot, + pjmedia_conf_port_info *info) { struct conf_port *conf_port; const pjmedia_audio_format_detail *afd; @@ -859,8 +858,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_get_port_info( pjmedia_conf *conf, /* Port must be valid. */ conf_port = conf->ports[slot]; if (conf_port == NULL) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } afd = pjmedia_format_get_audio_format_detail(&conf_port->info->fmt, 1); @@ -890,8 +889,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_get_port_info( pjmedia_conf *conf, PJ_DEF(pj_status_t) pjmedia_conf_get_ports_info(pjmedia_conf *conf, - unsigned *size, - pjmedia_conf_port_info info[]) + unsigned *size, + pjmedia_conf_port_info info[]) { unsigned i, count=0; @@ -901,11 +900,11 @@ PJ_DEF(pj_status_t) pjmedia_conf_get_ports_info(pjmedia_conf *conf, pj_mutex_lock(conf->mutex); for (i=0; imax_ports && count<*size; ++i) { - if (!conf->ports[i]) - continue; + if (!conf->ports[i]) + continue; - pjmedia_conf_get_port_info(conf, i, &info[count]); - ++count; + pjmedia_conf_get_port_info(conf, i, &info[count]); + ++count; } /* Unlock mutex */ @@ -920,9 +919,9 @@ PJ_DEF(pj_status_t) pjmedia_conf_get_ports_info(pjmedia_conf *conf, * Get signal level. */ PJ_DEF(pj_status_t) pjmedia_conf_get_signal_level( pjmedia_conf *conf, - unsigned slot, - unsigned *tx_level, - unsigned *rx_level) + unsigned slot, + unsigned *tx_level, + unsigned *rx_level) { struct conf_port *conf_port; @@ -935,16 +934,16 @@ PJ_DEF(pj_status_t) pjmedia_conf_get_signal_level( pjmedia_conf *conf, /* Port must be valid. */ conf_port = conf->ports[slot]; if (conf_port == NULL) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } if (tx_level != NULL) { - *tx_level = conf_port->tx_level; + *tx_level = conf_port->tx_level; } if (rx_level != NULL) - *rx_level = conf_port->rx_level; + *rx_level = conf_port->rx_level; /* Unlock mutex */ pj_mutex_unlock(conf->mutex); @@ -957,8 +956,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_get_signal_level( pjmedia_conf *conf, * Adjust RX level of individual port. */ PJ_DEF(pj_status_t) pjmedia_conf_adjust_rx_level( pjmedia_conf *conf, - unsigned slot, - int adj_level ) + unsigned slot, + int adj_level ) { struct conf_port *conf_port; @@ -977,13 +976,13 @@ PJ_DEF(pj_status_t) pjmedia_conf_adjust_rx_level( pjmedia_conf *conf, /* Port must be valid. */ conf_port = conf->ports[slot]; if (conf_port == NULL) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } /* Level adjustment is applicable only for ports that work with raw PCM. */ PJ_ASSERT_RETURN(conf_port->info->fmt.id == PJMEDIA_FORMAT_L16, - PJ_EIGNORED); + PJ_EIGNORED); /* Set normalized adjustment level. */ conf_port->rx_adj_level = adj_level + NORMAL_LEVEL; @@ -999,8 +998,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_adjust_rx_level( pjmedia_conf *conf, * Adjust TX level of individual port. */ PJ_DEF(pj_status_t) pjmedia_conf_adjust_tx_level( pjmedia_conf *conf, - unsigned slot, - int adj_level ) + unsigned slot, + int adj_level ) { struct conf_port *conf_port; @@ -1019,13 +1018,13 @@ PJ_DEF(pj_status_t) pjmedia_conf_adjust_tx_level( pjmedia_conf *conf, /* Port must be valid. */ conf_port = conf->ports[slot]; if (conf_port == NULL) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } /* Level adjustment is applicable only for ports that work with raw PCM. */ PJ_ASSERT_RETURN(conf_port->info->fmt.id == PJMEDIA_FORMAT_L16, - PJ_EIGNORED); + PJ_EIGNORED); /* Set normalized adjustment level. */ conf_port->tx_adj_level = adj_level + NORMAL_LEVEL; @@ -1040,7 +1039,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_adjust_tx_level( pjmedia_conf *conf, * when samples count in the frm_dst are equal to port's samples_per_frame. */ static pj_status_t write_frame(struct conf_port *cport_dst, - const pjmedia_frame *frm_src) + const pjmedia_frame *frm_src) { pjmedia_frame *frm_dst = (pjmedia_frame*)cport_dst->tx_buf; @@ -1051,170 +1050,170 @@ static pj_status_t write_frame(struct conf_port *cport_dst, if (frm_src->type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext *f_src = (pjmedia_frame_ext*)frm_src; - pjmedia_frame_ext *f_dst = (pjmedia_frame_ext*)frm_dst; - unsigned i; - - for (i = 0; i < f_src->subframe_cnt; ++i) { - pjmedia_frame_ext_subframe *sf; - - /* Copy frame to listener's TX buffer. */ - sf = pjmedia_frame_ext_get_subframe(f_src, i); - pjmedia_frame_ext_append_subframe(f_dst, sf->data, sf->bitlen, - f_src->samples_cnt / - f_src->subframe_cnt); - - /* Check if it's time to deliver the TX buffer to listener, - * i.e: samples count in TX buffer equal to listener's - * samples per frame. - */ - if (f_dst->samples_cnt >= cport_dst->samples_per_frame) - { - if (cport_dst->slot) { - pjmedia_port_put_frame(cport_dst->port, - (pjmedia_frame*)f_dst); - - /* Reset TX buffer. */ - f_dst->subframe_cnt = 0; - f_dst->samples_cnt = 0; - } - - /* Update TX timestamp. */ - pj_add_timestamp32(&cport_dst->ts_tx, - cport_dst->samples_per_frame); - } - } + pjmedia_frame_ext *f_src = (pjmedia_frame_ext*)frm_src; + pjmedia_frame_ext *f_dst = (pjmedia_frame_ext*)frm_dst; + unsigned i; + + for (i = 0; i < f_src->subframe_cnt; ++i) { + pjmedia_frame_ext_subframe *sf; + + /* Copy frame to listener's TX buffer. */ + sf = pjmedia_frame_ext_get_subframe(f_src, i); + pjmedia_frame_ext_append_subframe(f_dst, sf->data, sf->bitlen, + f_src->samples_cnt / + f_src->subframe_cnt); + + /* Check if it's time to deliver the TX buffer to listener, + * i.e: samples count in TX buffer equal to listener's + * samples per frame. + */ + if (f_dst->samples_cnt >= cport_dst->samples_per_frame) + { + if (cport_dst->slot) { + pjmedia_port_put_frame(cport_dst->port, + (pjmedia_frame*)f_dst); + + /* Reset TX buffer. */ + f_dst->subframe_cnt = 0; + f_dst->samples_cnt = 0; + } + + /* Update TX timestamp. */ + pj_add_timestamp32(&cport_dst->ts_tx, + cport_dst->samples_per_frame); + } + } } else if (frm_src->type == PJMEDIA_FRAME_TYPE_AUDIO) { - pj_int16_t *f_start, *f_end; - - f_start = (pj_int16_t*)frm_src->buf; - f_end = f_start + (frm_src->size >> 1); - - while (f_start < f_end) { - unsigned nsamples_to_copy, nsamples_req; - - /* Copy frame to listener's TX buffer. - * Note that if the destination is port 0, just copy the whole - * available samples. - */ - nsamples_to_copy = f_end - f_start; - nsamples_req = cport_dst->samples_per_frame - - (frm_dst->size>>1); - if (cport_dst->slot && nsamples_to_copy > nsamples_req) - nsamples_to_copy = nsamples_req; - - /* Adjust TX level. */ - if (cport_dst->tx_adj_level != NORMAL_LEVEL) { - pj_int16_t *p, *p_end; - - p = f_start; - p_end = p + nsamples_to_copy; - while (p < p_end) { - pj_int32_t itemp = *p; - - /* Adjust the level */ - itemp = (itemp * cport_dst->tx_adj_level) >> 7; - - /* Clip the signal if it's too loud */ - if (itemp > MAX_LEVEL) itemp = MAX_LEVEL; - else if (itemp < MIN_LEVEL) itemp = MIN_LEVEL; - - /* Put back in the buffer. */ - *p = (pj_int16_t)itemp; - ++p; - } - } - - pjmedia_copy_samples((pj_int16_t*)frm_dst->buf + (frm_dst->size>>1), - f_start, - nsamples_to_copy); - frm_dst->size += nsamples_to_copy << 1; - f_start += nsamples_to_copy; - - /* Check if it's time to deliver the TX buffer to listener, - * i.e: samples count in TX buffer equal to listener's - * samples per frame. Note that for destination port 0 this - * function will just populate all samples in the TX buffer. - */ - if (cport_dst->slot == 0) { - /* Update TX timestamp. */ - pj_add_timestamp32(&cport_dst->ts_tx, nsamples_to_copy); - } else if ((frm_dst->size >> 1) == - cport_dst->samples_per_frame) - { - pjmedia_port_put_frame(cport_dst->port, frm_dst); - - /* Reset TX buffer. */ - frm_dst->size = 0; - - /* Update TX timestamp. */ - pj_add_timestamp32(&cport_dst->ts_tx, - cport_dst->samples_per_frame); - } - } + pj_int16_t *f_start, *f_end; + + f_start = (pj_int16_t*)frm_src->buf; + f_end = f_start + (frm_src->size >> 1); + + while (f_start < f_end) { + unsigned nsamples_to_copy, nsamples_req; + + /* Copy frame to listener's TX buffer. + * Note that if the destination is port 0, just copy the whole + * available samples. + */ + nsamples_to_copy = f_end - f_start; + nsamples_req = cport_dst->samples_per_frame - + (frm_dst->size>>1); + if (cport_dst->slot && nsamples_to_copy > nsamples_req) + nsamples_to_copy = nsamples_req; + + /* Adjust TX level. */ + if (cport_dst->tx_adj_level != NORMAL_LEVEL) { + pj_int16_t *p, *p_end; + + p = f_start; + p_end = p + nsamples_to_copy; + while (p < p_end) { + pj_int32_t itemp = *p; + + /* Adjust the level */ + itemp = (itemp * cport_dst->tx_adj_level) >> 7; + + /* Clip the signal if it's too loud */ + if (itemp > MAX_LEVEL) itemp = MAX_LEVEL; + else if (itemp < MIN_LEVEL) itemp = MIN_LEVEL; + + /* Put back in the buffer. */ + *p = (pj_int16_t)itemp; + ++p; + } + } + + pjmedia_copy_samples((pj_int16_t*)frm_dst->buf + (frm_dst->size>>1), + f_start, + nsamples_to_copy); + frm_dst->size += nsamples_to_copy << 1; + f_start += nsamples_to_copy; + + /* Check if it's time to deliver the TX buffer to listener, + * i.e: samples count in TX buffer equal to listener's + * samples per frame. Note that for destination port 0 this + * function will just populate all samples in the TX buffer. + */ + if (cport_dst->slot == 0) { + /* Update TX timestamp. */ + pj_add_timestamp32(&cport_dst->ts_tx, nsamples_to_copy); + } else if ((frm_dst->size >> 1) == + cport_dst->samples_per_frame) + { + pjmedia_port_put_frame(cport_dst->port, frm_dst); + + /* Reset TX buffer. */ + frm_dst->size = 0; + + /* Update TX timestamp. */ + pj_add_timestamp32(&cport_dst->ts_tx, + cport_dst->samples_per_frame); + } + } } else if (frm_src->type == PJMEDIA_FRAME_TYPE_NONE) { - /* Check port format. */ - if (cport_dst->port && - cport_dst->port->info.fmt.id == PJMEDIA_FORMAT_L16) - { - /* When there is already some samples in listener's TX buffer, - * pad the buffer with "zero samples". - */ - if (frm_dst->size != 0) { - pjmedia_zero_samples((pj_int16_t*)frm_dst->buf, - cport_dst->samples_per_frame - - (frm_dst->size>>1)); - - frm_dst->type = PJMEDIA_FRAME_TYPE_AUDIO; - frm_dst->size = cport_dst->samples_per_frame << 1; - if (cport_dst->slot) { - pjmedia_port_put_frame(cport_dst->port, frm_dst); - - /* Reset TX buffer. */ - frm_dst->size = 0; - } - - /* Update TX timestamp. */ - pj_add_timestamp32(&cport_dst->ts_tx, - cport_dst->samples_per_frame); - } - } else { - pjmedia_frame_ext *f_dst = (pjmedia_frame_ext*)frm_dst; - - if (f_dst->samples_cnt != 0) { - frm_dst->type = PJMEDIA_FRAME_TYPE_EXTENDED; - pjmedia_frame_ext_append_subframe(f_dst, NULL, 0, (pj_uint16_t) - (cport_dst->samples_per_frame - f_dst->samples_cnt)); - if (cport_dst->slot) { - pjmedia_port_put_frame(cport_dst->port, frm_dst); - - /* Reset TX buffer. */ - f_dst->subframe_cnt = 0; - f_dst->samples_cnt = 0; - } - - /* Update TX timestamp. */ - pj_add_timestamp32(&cport_dst->ts_tx, - cport_dst->samples_per_frame); - } - } - - /* Synchronize clock. */ - while (pj_cmp_timestamp(&cport_dst->ts_clock, - &cport_dst->ts_tx) > 0) - { - frm_dst->type = PJMEDIA_FRAME_TYPE_NONE; - frm_dst->timestamp = cport_dst->ts_tx; - if (cport_dst->slot) - pjmedia_port_put_frame(cport_dst->port, frm_dst); - - /* Update TX timestamp. */ - pj_add_timestamp32(&cport_dst->ts_tx, cport_dst->samples_per_frame); - } + /* Check port format. */ + if (cport_dst->port && + cport_dst->port->info.fmt.id == PJMEDIA_FORMAT_L16) + { + /* When there is already some samples in listener's TX buffer, + * pad the buffer with "zero samples". + */ + if (frm_dst->size != 0) { + pjmedia_zero_samples((pj_int16_t*)frm_dst->buf, + cport_dst->samples_per_frame - + (frm_dst->size>>1)); + + frm_dst->type = PJMEDIA_FRAME_TYPE_AUDIO; + frm_dst->size = cport_dst->samples_per_frame << 1; + if (cport_dst->slot) { + pjmedia_port_put_frame(cport_dst->port, frm_dst); + + /* Reset TX buffer. */ + frm_dst->size = 0; + } + + /* Update TX timestamp. */ + pj_add_timestamp32(&cport_dst->ts_tx, + cport_dst->samples_per_frame); + } + } else { + pjmedia_frame_ext *f_dst = (pjmedia_frame_ext*)frm_dst; + + if (f_dst->samples_cnt != 0) { + frm_dst->type = PJMEDIA_FRAME_TYPE_EXTENDED; + pjmedia_frame_ext_append_subframe(f_dst, NULL, 0, (pj_uint16_t) + (cport_dst->samples_per_frame - f_dst->samples_cnt)); + if (cport_dst->slot) { + pjmedia_port_put_frame(cport_dst->port, frm_dst); + + /* Reset TX buffer. */ + f_dst->subframe_cnt = 0; + f_dst->samples_cnt = 0; + } + + /* Update TX timestamp. */ + pj_add_timestamp32(&cport_dst->ts_tx, + cport_dst->samples_per_frame); + } + } + + /* Synchronize clock. */ + while (pj_cmp_timestamp(&cport_dst->ts_clock, + &cport_dst->ts_tx) > 0) + { + frm_dst->type = PJMEDIA_FRAME_TYPE_NONE; + frm_dst->timestamp = cport_dst->ts_tx; + if (cport_dst->slot) + pjmedia_port_put_frame(cport_dst->port, frm_dst); + + /* Update TX timestamp. */ + pj_add_timestamp32(&cport_dst->ts_tx, cport_dst->samples_per_frame); + } } return PJ_SUCCESS; @@ -1224,7 +1223,7 @@ static pj_status_t write_frame(struct conf_port *cport_dst, * Player callback. */ static pj_status_t get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { pjmedia_conf *conf = (pjmedia_conf*) this_port->port_data.pdata; unsigned ci, i; @@ -1238,227 +1237,227 @@ static pj_status_t get_frame(pjmedia_port *this_port, * put_frame() of that port) to ports that are receiving from this port. */ for (i=1, ci=1; imax_ports && ciport_cnt; ++i) { - struct conf_port *cport = conf->ports[i]; - unsigned master_samples_per_frame; - - /* Skip empty port. */ - if (!cport) - continue; - - /* Var "ci" is to count how many ports have been visited so far. */ - ++ci; - - master_samples_per_frame = PJMEDIA_PIA_SPF(&conf->master_port->info); - - /* Update clock of the port. */ - pj_add_timestamp32(&cport->ts_clock, master_samples_per_frame); - - /* Skip if we're not allowed to receive from this port or - * the port doesn't have listeners. - */ - if (cport->rx_setting == PJMEDIA_PORT_DISABLE || - cport->listener_cnt == 0) - { - cport->rx_level = 0; - pj_add_timestamp32(&cport->ts_rx, master_samples_per_frame); - continue; - } - - /* Get frame from each port, put it to the listener TX buffer, - * and eventually call put_frame() of the listener. This loop - * will also make sure the ptime between conf & port synchronized. - */ - while (pj_cmp_timestamp(&cport->ts_clock, &cport->ts_rx) > 0) { - pjmedia_frame *f = (pjmedia_frame*)conf->buf; - pj_status_t status; - unsigned j; - pj_int32_t level = 0; - - pj_add_timestamp32(&cport->ts_rx, cport->samples_per_frame); - - f->buf = &conf->buf[sizeof(pjmedia_frame)]; - f->size = cport->samples_per_frame<<1; - - /* Get frame from port. */ - status = pjmedia_port_get_frame(cport->port, f); - if (status != PJ_SUCCESS) - continue; - - /* Calculate & adjust RX level. */ - if (f->type == PJMEDIA_FRAME_TYPE_AUDIO) { - if (cport->rx_adj_level != NORMAL_LEVEL) { - pj_int16_t *p = (pj_int16_t*)f->buf; - pj_int16_t *end; - - end = p + (f->size >> 1); - while (p < end) { - pj_int32_t itemp = *p; - - /* Adjust the level */ - itemp = (itemp * cport->rx_adj_level) >> 7; - - /* Clip the signal if it's too loud */ - if (itemp > MAX_LEVEL) itemp = MAX_LEVEL; - else if (itemp < MIN_LEVEL) itemp = MIN_LEVEL; - - level += PJ_ABS(itemp); - - /* Put back in the buffer. */ - *p = (pj_int16_t)itemp; - ++p; - } - level /= (f->size >> 1); - } else { - level = pjmedia_calc_avg_signal((const pj_int16_t*)f->buf, - f->size >> 1); - } - } else if (f->type == PJMEDIA_FRAME_TYPE_EXTENDED) { - /* For extended frame, level is unknown, so we just set - * it to NORMAL_LEVEL. - */ - level = NORMAL_LEVEL; - } - - cport->rx_level = pjmedia_linear2ulaw(level) ^ 0xff; - - /* Put the frame to all listeners. */ - for (j=0; j < cport->listener_cnt; ++j) - { - struct conf_port *listener; - - listener = conf->ports[cport->listener_slots[j]]; - - /* Skip if this listener doesn't want to receive audio */ - if (listener->tx_setting == PJMEDIA_PORT_DISABLE) { - pj_add_timestamp32(&listener->ts_tx, - listener->samples_per_frame); - listener->tx_level = 0; - continue; - } - - status = write_frame(listener, f); - if (status != PJ_SUCCESS) { - listener->tx_level = 0; - continue; - } - - /* Set listener TX level based on transmitter RX level & - * listener TX level. - */ - listener->tx_level = (cport->rx_level * listener->tx_adj_level) - >> 8; - } - } + struct conf_port *cport = conf->ports[i]; + unsigned master_samples_per_frame; + + /* Skip empty port. */ + if (!cport) + continue; + + /* Var "ci" is to count how many ports have been visited so far. */ + ++ci; + + master_samples_per_frame = PJMEDIA_PIA_SPF(&conf->master_port->info); + + /* Update clock of the port. */ + pj_add_timestamp32(&cport->ts_clock, master_samples_per_frame); + + /* Skip if we're not allowed to receive from this port or + * the port doesn't have listeners. + */ + if (cport->rx_setting == PJMEDIA_PORT_DISABLE || + cport->listener_cnt == 0) + { + cport->rx_level = 0; + pj_add_timestamp32(&cport->ts_rx, master_samples_per_frame); + continue; + } + + /* Get frame from each port, put it to the listener TX buffer, + * and eventually call put_frame() of the listener. This loop + * will also make sure the ptime between conf & port synchronized. + */ + while (pj_cmp_timestamp(&cport->ts_clock, &cport->ts_rx) > 0) { + pjmedia_frame *f = (pjmedia_frame*)conf->buf; + pj_status_t status; + unsigned j; + pj_int32_t level = 0; + + pj_add_timestamp32(&cport->ts_rx, cport->samples_per_frame); + + f->buf = &conf->buf[sizeof(pjmedia_frame)]; + f->size = cport->samples_per_frame<<1; + + /* Get frame from port. */ + status = pjmedia_port_get_frame(cport->port, f); + if (status != PJ_SUCCESS) + continue; + + /* Calculate & adjust RX level. */ + if (f->type == PJMEDIA_FRAME_TYPE_AUDIO) { + if (cport->rx_adj_level != NORMAL_LEVEL) { + pj_int16_t *p = (pj_int16_t*)f->buf; + pj_int16_t *end; + + end = p + (f->size >> 1); + while (p < end) { + pj_int32_t itemp = *p; + + /* Adjust the level */ + itemp = (itemp * cport->rx_adj_level) >> 7; + + /* Clip the signal if it's too loud */ + if (itemp > MAX_LEVEL) itemp = MAX_LEVEL; + else if (itemp < MIN_LEVEL) itemp = MIN_LEVEL; + + level += PJ_ABS(itemp); + + /* Put back in the buffer. */ + *p = (pj_int16_t)itemp; + ++p; + } + level /= (f->size >> 1); + } else { + level = pjmedia_calc_avg_signal((const pj_int16_t*)f->buf, + f->size >> 1); + } + } else if (f->type == PJMEDIA_FRAME_TYPE_EXTENDED) { + /* For extended frame, level is unknown, so we just set + * it to NORMAL_LEVEL. + */ + level = NORMAL_LEVEL; + } + + cport->rx_level = pjmedia_linear2ulaw(level) ^ 0xff; + + /* Put the frame to all listeners. */ + for (j=0; j < cport->listener_cnt; ++j) + { + struct conf_port *listener; + + listener = conf->ports[cport->listener_slots[j]]; + + /* Skip if this listener doesn't want to receive audio */ + if (listener->tx_setting == PJMEDIA_PORT_DISABLE) { + pj_add_timestamp32(&listener->ts_tx, + listener->samples_per_frame); + listener->tx_level = 0; + continue; + } + + status = write_frame(listener, f); + if (status != PJ_SUCCESS) { + listener->tx_level = 0; + continue; + } + + /* Set listener TX level based on transmitter RX level & + * listener TX level. + */ + listener->tx_level = (cport->rx_level * listener->tx_adj_level) + >> 8; + } + } } /* Keep alive. Update TX timestamp and send frame type NONE to all * underflow ports at their own clock. */ for (i=1, ci=1; imax_ports && ciport_cnt; ++i) { - struct conf_port *cport = conf->ports[i]; - - /* Skip empty port. */ - if (!cport) - continue; - - /* Var "ci" is to count how many ports have been visited so far. */ - ++ci; - - if (cport->tx_setting==PJMEDIA_PORT_MUTE || cport->transmitter_cnt==0) - { - pjmedia_frame_ext *f; - - /* Clear left-over samples in tx_buffer, if any, so that it won't - * be transmitted next time we have audio signal. - */ - f = (pjmedia_frame_ext*)cport->tx_buf; - f->base.type = PJMEDIA_FRAME_TYPE_NONE; - f->base.size = 0; - f->samples_cnt = 0; - f->subframe_cnt = 0; - - cport->tx_level = 0; - - while (pj_cmp_timestamp(&cport->ts_clock, &cport->ts_tx) > 0) - { - if (cport->tx_setting == PJMEDIA_PORT_ENABLE) { - pjmedia_frame tmp_f; - - tmp_f.timestamp = cport->ts_tx; - tmp_f.type = PJMEDIA_FRAME_TYPE_NONE; - tmp_f.buf = NULL; - tmp_f.size = 0; - - pjmedia_port_put_frame(cport->port, &tmp_f); - pj_add_timestamp32(&cport->ts_tx, cport->samples_per_frame); - } - } - } + struct conf_port *cport = conf->ports[i]; + + /* Skip empty port. */ + if (!cport) + continue; + + /* Var "ci" is to count how many ports have been visited so far. */ + ++ci; + + if (cport->tx_setting==PJMEDIA_PORT_MUTE || cport->transmitter_cnt==0) + { + pjmedia_frame_ext *f; + + /* Clear left-over samples in tx_buffer, if any, so that it won't + * be transmitted next time we have audio signal. + */ + f = (pjmedia_frame_ext*)cport->tx_buf; + f->base.type = PJMEDIA_FRAME_TYPE_NONE; + f->base.size = 0; + f->samples_cnt = 0; + f->subframe_cnt = 0; + + cport->tx_level = 0; + + while (pj_cmp_timestamp(&cport->ts_clock, &cport->ts_tx) > 0) + { + if (cport->tx_setting == PJMEDIA_PORT_ENABLE) { + pjmedia_frame tmp_f; + + tmp_f.timestamp = cport->ts_tx; + tmp_f.type = PJMEDIA_FRAME_TYPE_NONE; + tmp_f.buf = NULL; + tmp_f.size = 0; + + pjmedia_port_put_frame(cport->port, &tmp_f); + pj_add_timestamp32(&cport->ts_tx, cport->samples_per_frame); + } + } + } } /* Return sound playback frame. */ do { - struct conf_port *this_cport = conf->ports[this_port->port_data.ldata]; - pjmedia_frame *f_src = (pjmedia_frame*) this_cport->tx_buf; - - frame->type = f_src->type; - - if (f_src->type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext *f_src_ = (pjmedia_frame_ext*)f_src; - pjmedia_frame_ext *f_dst = (pjmedia_frame_ext*)frame; - pjmedia_frame_ext_subframe *sf; - unsigned samples_per_subframe; - - if (f_src_->samples_cnt < this_cport->samples_per_frame) { - f_dst->base.type = PJMEDIA_FRAME_TYPE_NONE; - f_dst->samples_cnt = 0; - f_dst->subframe_cnt = 0; - break; - } - - f_dst->samples_cnt = 0; - f_dst->subframe_cnt = 0; - i = 0; - samples_per_subframe = f_src_->samples_cnt / f_src_->subframe_cnt; - - - while (f_dst->samples_cnt < this_cport->samples_per_frame) { - sf = pjmedia_frame_ext_get_subframe(f_src_, i++); - pj_assert(sf); - pjmedia_frame_ext_append_subframe(f_dst, sf->data, sf->bitlen, - samples_per_subframe); - } - - /* Shift left TX buffer. */ - pjmedia_frame_ext_pop_subframes(f_src_, i); - - } else if (f_src->type == PJMEDIA_FRAME_TYPE_AUDIO) { - if ((f_src->size>>1) < this_cport->samples_per_frame) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - break; - } - - pjmedia_copy_samples((pj_int16_t*)frame->buf, - (pj_int16_t*)f_src->buf, - this_cport->samples_per_frame); - frame->size = this_cport->samples_per_frame << 1; - - /* Shift left TX buffer. */ - f_src->size -= frame->size; - if (f_src->size) - pjmedia_move_samples((pj_int16_t*)f_src->buf, - (pj_int16_t*)f_src->buf + - this_cport->samples_per_frame, - f_src->size >> 1); - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - pjmedia_frame_ext *f_src_ = (pjmedia_frame_ext*)f_src; - - /* Reset source/TX buffer */ - f_src_->base.size = 0; - f_src_->samples_cnt = 0; - f_src_->subframe_cnt = 0; - } + struct conf_port *this_cport = conf->ports[this_port->port_data.ldata]; + pjmedia_frame *f_src = (pjmedia_frame*) this_cport->tx_buf; + + frame->type = f_src->type; + + if (f_src->type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext *f_src_ = (pjmedia_frame_ext*)f_src; + pjmedia_frame_ext *f_dst = (pjmedia_frame_ext*)frame; + pjmedia_frame_ext_subframe *sf; + unsigned samples_per_subframe; + + if (f_src_->samples_cnt < this_cport->samples_per_frame) { + f_dst->base.type = PJMEDIA_FRAME_TYPE_NONE; + f_dst->samples_cnt = 0; + f_dst->subframe_cnt = 0; + break; + } + + f_dst->samples_cnt = 0; + f_dst->subframe_cnt = 0; + i = 0; + samples_per_subframe = f_src_->samples_cnt / f_src_->subframe_cnt; + + + while (f_dst->samples_cnt < this_cport->samples_per_frame) { + sf = pjmedia_frame_ext_get_subframe(f_src_, i++); + pj_assert(sf); + pjmedia_frame_ext_append_subframe(f_dst, sf->data, sf->bitlen, + samples_per_subframe); + } + + /* Shift left TX buffer. */ + pjmedia_frame_ext_pop_subframes(f_src_, i); + + } else if (f_src->type == PJMEDIA_FRAME_TYPE_AUDIO) { + if ((f_src->size>>1) < this_cport->samples_per_frame) { + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + break; + } + + pjmedia_copy_samples((pj_int16_t*)frame->buf, + (pj_int16_t*)f_src->buf, + this_cport->samples_per_frame); + frame->size = this_cport->samples_per_frame << 1; + + /* Shift left TX buffer. */ + f_src->size -= frame->size; + if (f_src->size) + pjmedia_move_samples((pj_int16_t*)f_src->buf, + (pj_int16_t*)f_src->buf + + this_cport->samples_per_frame, + f_src->size >> 1); + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + pjmedia_frame_ext *f_src_ = (pjmedia_frame_ext*)f_src; + + /* Reset source/TX buffer */ + f_src_->base.size = 0; + f_src_->samples_cnt = 0; + f_src_->subframe_cnt = 0; + } } while (0); /* Unlock mutex */ @@ -1471,7 +1470,7 @@ static pj_status_t get_frame(pjmedia_port *this_port, * Recorder callback. */ static pj_status_t put_frame(pjmedia_port *this_port, - pjmedia_frame *f) + pjmedia_frame *f) { pjmedia_conf *conf = (pjmedia_conf*) this_port->port_data.pdata; struct conf_port *cport; @@ -1484,62 +1483,62 @@ static pj_status_t put_frame(pjmedia_port *this_port, /* Get conf port of this port */ cport = conf->ports[this_port->port_data.ldata]; if (cport == NULL) { - /* Unlock mutex */ - pj_mutex_unlock(conf->mutex); - return PJ_SUCCESS; + /* Unlock mutex */ + pj_mutex_unlock(conf->mutex); + return PJ_SUCCESS; } pj_add_timestamp32(&cport->ts_rx, cport->samples_per_frame); /* Skip if this port is muted/disabled. */ if (cport->rx_setting == PJMEDIA_PORT_DISABLE) { - cport->rx_level = 0; - /* Unlock mutex */ - pj_mutex_unlock(conf->mutex); - return PJ_SUCCESS; + cport->rx_level = 0; + /* Unlock mutex */ + pj_mutex_unlock(conf->mutex); + return PJ_SUCCESS; } /* Skip if no port is listening to the microphone */ if (cport->listener_cnt == 0) { - cport->rx_level = 0; - /* Unlock mutex */ - pj_mutex_unlock(conf->mutex); - return PJ_SUCCESS; + cport->rx_level = 0; + /* Unlock mutex */ + pj_mutex_unlock(conf->mutex); + return PJ_SUCCESS; } /* Calculate & adjust RX level. */ if (f->type == PJMEDIA_FRAME_TYPE_AUDIO) { - if (cport->rx_adj_level != NORMAL_LEVEL) { - pj_int16_t *p = (pj_int16_t*)f->buf; - pj_int16_t *end; - - end = p + (f->size >> 1); - while (p < end) { - pj_int32_t itemp = *p; - - /* Adjust the level */ - itemp = (itemp * cport->rx_adj_level) >> 7; - - /* Clip the signal if it's too loud */ - if (itemp > MAX_LEVEL) itemp = MAX_LEVEL; - else if (itemp < MIN_LEVEL) itemp = MIN_LEVEL; - - level += PJ_ABS(itemp); - - /* Put back in the buffer. */ - *p = (pj_int16_t)itemp; - ++p; - } - level /= (f->size >> 1); - } else { - level = pjmedia_calc_avg_signal((const pj_int16_t*)f->buf, - f->size >> 1); - } + if (cport->rx_adj_level != NORMAL_LEVEL) { + pj_int16_t *p = (pj_int16_t*)f->buf; + pj_int16_t *end; + + end = p + (f->size >> 1); + while (p < end) { + pj_int32_t itemp = *p; + + /* Adjust the level */ + itemp = (itemp * cport->rx_adj_level) >> 7; + + /* Clip the signal if it's too loud */ + if (itemp > MAX_LEVEL) itemp = MAX_LEVEL; + else if (itemp < MIN_LEVEL) itemp = MIN_LEVEL; + + level += PJ_ABS(itemp); + + /* Put back in the buffer. */ + *p = (pj_int16_t)itemp; + ++p; + } + level /= (f->size >> 1); + } else { + level = pjmedia_calc_avg_signal((const pj_int16_t*)f->buf, + f->size >> 1); + } } else if (f->type == PJMEDIA_FRAME_TYPE_EXTENDED) { - /* For extended frame, level is unknown, so we just set - * it to NORMAL_LEVEL. - */ - level = NORMAL_LEVEL; + /* For extended frame, level is unknown, so we just set + * it to NORMAL_LEVEL. + */ + level = NORMAL_LEVEL; } cport->rx_level = pjmedia_linear2ulaw(level) ^ 0xff; @@ -1547,37 +1546,37 @@ static pj_status_t put_frame(pjmedia_port *this_port, /* Put the frame to all listeners. */ for (j=0; j < cport->listener_cnt; ++j) { - struct conf_port *listener; - pj_status_t status; - - listener = conf->ports[cport->listener_slots[j]]; - - /* Skip if this listener doesn't want to receive audio */ - if (listener->tx_setting == PJMEDIA_PORT_DISABLE) { - pj_add_timestamp32(&listener->ts_tx, - listener->samples_per_frame); - listener->tx_level = 0; - continue; - } - - /* Skip loopback for now. */ - if (listener == cport) { - pj_add_timestamp32(&listener->ts_tx, - listener->samples_per_frame); - listener->tx_level = 0; - continue; - } - - status = write_frame(listener, f); - if (status != PJ_SUCCESS) { - listener->tx_level = 0; - continue; - } - - /* Set listener TX level based on transmitter RX level & listener - * TX level. - */ - listener->tx_level = (cport->rx_level * listener->tx_adj_level) >> 8; + struct conf_port *listener; + pj_status_t status; + + listener = conf->ports[cport->listener_slots[j]]; + + /* Skip if this listener doesn't want to receive audio */ + if (listener->tx_setting == PJMEDIA_PORT_DISABLE) { + pj_add_timestamp32(&listener->ts_tx, + listener->samples_per_frame); + listener->tx_level = 0; + continue; + } + + /* Skip loopback for now. */ + if (listener == cport) { + pj_add_timestamp32(&listener->ts_tx, + listener->samples_per_frame); + listener->tx_level = 0; + continue; + } + + status = write_frame(listener, f); + if (status != PJ_SUCCESS) { + listener->tx_level = 0; + continue; + } + + /* Set listener TX level based on transmitter RX level & listener + * TX level. + */ + listener->tx_level = (cport->rx_level * listener->tx_adj_level) >> 8; } /* Unlock mutex */ diff --git a/pjmedia/src/pjmedia/conference.c b/pjmedia/src/pjmedia/conference.c index 139a81a776..8b85da5049 100644 --- a/pjmedia/src/pjmedia/conference.c +++ b/pjmedia/src/pjmedia/conference.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -57,18 +56,18 @@ static FILE *fhnd_rec; #endif -#define THIS_FILE "conference.c" +#define THIS_FILE "conference.c" -#define RX_BUF_COUNT PJMEDIA_SOUND_BUFFER_COUNT +#define RX_BUF_COUNT PJMEDIA_SOUND_BUFFER_COUNT #define BYTES_PER_SAMPLE 2 -#define SIGNATURE PJMEDIA_CONF_BRIDGE_SIGNATURE -#define SIGNATURE_PORT PJMEDIA_SIG_PORT_CONF_PASV +#define SIGNATURE PJMEDIA_CONF_BRIDGE_SIGNATURE +#define SIGNATURE_PORT PJMEDIA_SIG_PORT_CONF_PASV /* Normal level is hardcodec to 128 in all over places */ -#define NORMAL_LEVEL 128 -#define SLOT_TYPE unsigned -#define INVALID_SLOT ((SLOT_TYPE)-1) +#define NORMAL_LEVEL 128 +#define SLOT_TYPE unsigned +#define INVALID_SLOT ((SLOT_TYPE)-1) /* These are settings to control the adaptivity of changes in the @@ -77,15 +76,15 @@ static FILE *fhnd_rec; */ #if defined(PJMEDIA_CONF_USE_AGC) && PJMEDIA_CONF_USE_AGC != 0 # define ATTACK_A ((conf->clock_rate / conf->samples_per_frame) >> 4) -# define ATTACK_B 1 -# define DECAY_A 0 -# define DECAY_B 1 +# define ATTACK_B 1 +# define DECAY_A 0 +# define DECAY_B 1 # define SIMPLE_AGC(last, target) \ if (target >= last) \ - target = (ATTACK_A*(last+1)+ATTACK_B*target)/(ATTACK_A+ATTACK_B); \ + target = (ATTACK_A*(last+1)+ATTACK_B*target)/(ATTACK_A+ATTACK_B); \ else \ - target = (DECAY_A*last+DECAY_B*target)/(DECAY_A+DECAY_B) + target = (DECAY_A*last+DECAY_B*target)/(DECAY_A+DECAY_B) #else # define SIMPLE_AGC(last, target) #endif @@ -111,36 +110,36 @@ static FILE *fhnd_rec; */ struct conf_port { - pj_str_t name; /**< Port name. */ - pjmedia_port *port; /**< get_frame() and put_frame() */ - pjmedia_port_op rx_setting; /**< Can we receive from this port */ - pjmedia_port_op tx_setting; /**< Can we transmit to this port */ - unsigned listener_cnt; /**< Number of listeners. */ - SLOT_TYPE *listener_slots;/**< Array of listeners. */ - unsigned *listener_adj_level; - /**< Array of listeners' level - adjustment. */ - unsigned transmitter_cnt;/**listener_slots = (SLOT_TYPE*) pj_pool_zalloc(pool, - conf->max_ports * sizeof(SLOT_TYPE)); + conf->max_ports * sizeof(SLOT_TYPE)); PJ_ASSERT_RETURN(conf_port->listener_slots, PJ_ENOMEM); /* Create adjustment level array */ conf_port->listener_adj_level = (unsigned *) pj_pool_zalloc(pool, - conf->max_ports * sizeof(unsigned)); + conf->max_ports * sizeof(unsigned)); PJ_ASSERT_RETURN(conf_port->listener_adj_level, PJ_ENOMEM); /* Save some port's infos, for convenience. */ if (port) { - pjmedia_audio_format_detail *afd; + pjmedia_audio_format_detail *afd; - afd = pjmedia_format_get_audio_format_detail(&port->info.fmt, 1); - conf_port->port = port; - conf_port->clock_rate = afd->clock_rate; - conf_port->samples_per_frame = PJMEDIA_AFD_SPF(afd); - conf_port->channel_count = afd->channel_count; + afd = pjmedia_format_get_audio_format_detail(&port->info.fmt, 1); + conf_port->port = port; + conf_port->clock_rate = afd->clock_rate; + conf_port->samples_per_frame = PJMEDIA_AFD_SPF(afd); + conf_port->channel_count = afd->channel_count; } else { - conf_port->port = NULL; - conf_port->clock_rate = conf->clock_rate; - conf_port->samples_per_frame = conf->samples_per_frame; - conf_port->channel_count = conf->channel_count; + conf_port->port = NULL; + conf_port->clock_rate = conf->clock_rate; + conf_port->samples_per_frame = conf->samples_per_frame; + conf_port->channel_count = conf->channel_count; } /* Create adjustment level buffer. */ conf_port->adj_level_buf = (pj_int16_t*) pj_pool_zalloc(pool, - conf->samples_per_frame * sizeof(pj_int16_t)); + conf->samples_per_frame * sizeof(pj_int16_t)); /* If port's clock rate is different than conference's clock rate, * create a resample sessions. */ if (conf_port->clock_rate != conf->clock_rate) { - pj_bool_t high_quality; - pj_bool_t large_filter; - - high_quality = ((conf->options & PJMEDIA_CONF_USE_LINEAR)==0); - large_filter = ((conf->options & PJMEDIA_CONF_SMALL_FILTER)==0); - - /* Create resample for rx buffer. */ - status = pjmedia_resample_create( pool, - high_quality, - large_filter, - conf->channel_count, - conf_port->clock_rate,/* Rate in */ - conf->clock_rate, /* Rate out */ - conf->samples_per_frame * - conf_port->clock_rate / - conf->clock_rate, - &conf_port->rx_resample); - if (status != PJ_SUCCESS) - return status; - - - /* Create resample for tx buffer. */ - status = pjmedia_resample_create(pool, - high_quality, - large_filter, - conf->channel_count, - conf->clock_rate, /* Rate in */ - conf_port->clock_rate, /* Rate out */ - conf->samples_per_frame, - &conf_port->tx_resample); - if (status != PJ_SUCCESS) - return status; + pj_bool_t high_quality; + pj_bool_t large_filter; + + high_quality = ((conf->options & PJMEDIA_CONF_USE_LINEAR)==0); + large_filter = ((conf->options & PJMEDIA_CONF_SMALL_FILTER)==0); + + /* Create resample for rx buffer. */ + status = pjmedia_resample_create( pool, + high_quality, + large_filter, + conf->channel_count, + conf_port->clock_rate,/* Rate in */ + conf->clock_rate, /* Rate out */ + conf->samples_per_frame * + conf_port->clock_rate / + conf->clock_rate, + &conf_port->rx_resample); + if (status != PJ_SUCCESS) + return status; + + + /* Create resample for tx buffer. */ + status = pjmedia_resample_create(pool, + high_quality, + large_filter, + conf->channel_count, + conf->clock_rate, /* Rate in */ + conf_port->clock_rate, /* Rate out */ + conf->samples_per_frame, + &conf_port->tx_resample); + if (status != PJ_SUCCESS) + return status; } /* @@ -362,64 +361,64 @@ static pj_status_t create_conf_port( pj_pool_t *pool, * bridge settings. */ if (conf_port->clock_rate != conf->clock_rate || - conf_port->channel_count != conf->channel_count || - conf_port->samples_per_frame != conf->samples_per_frame) + conf_port->channel_count != conf->channel_count || + conf_port->samples_per_frame != conf->samples_per_frame) { - unsigned port_ptime, conf_ptime, buff_ptime; - - port_ptime = conf_port->samples_per_frame / conf_port->channel_count * - 1000 / conf_port->clock_rate; - conf_ptime = conf->samples_per_frame / conf->channel_count * - 1000 / conf->clock_rate; - - /* Calculate the size (in ptime) for the port buffer according to - * this formula: - * - if either ptime is an exact multiple of the other, then use - * the larger ptime (e.g. 20ms and 40ms, use 40ms). - * - if not, then the ptime is sum of both ptimes (e.g. 20ms - * and 30ms, use 50ms) - */ - if (port_ptime > conf_ptime) { - buff_ptime = port_ptime; - if (port_ptime % conf_ptime) - buff_ptime += conf_ptime; - } else { - buff_ptime = conf_ptime; - if (conf_ptime % port_ptime) - buff_ptime += port_ptime; - } - - /* Create RX buffer. */ - //conf_port->rx_buf_cap = (unsigned)(conf_port->samples_per_frame + - // conf->samples_per_frame * - // conf_port->clock_rate * 1.0 / - // conf->clock_rate + 0.5); - conf_port->rx_buf_cap = conf_port->clock_rate * buff_ptime / 1000; - if (conf_port->channel_count > conf->channel_count) - conf_port->rx_buf_cap *= conf_port->channel_count; - else - conf_port->rx_buf_cap *= conf->channel_count; - - conf_port->rx_buf_count = 0; - conf_port->rx_buf = (pj_int16_t*) - pj_pool_alloc(pool, conf_port->rx_buf_cap * - sizeof(conf_port->rx_buf[0])); - PJ_ASSERT_RETURN(conf_port->rx_buf, PJ_ENOMEM); - - /* Create TX buffer. */ - conf_port->tx_buf_cap = conf_port->rx_buf_cap; - conf_port->tx_buf_count = 0; - conf_port->tx_buf = (pj_int16_t*) - pj_pool_alloc(pool, conf_port->tx_buf_cap * - sizeof(conf_port->tx_buf[0])); - PJ_ASSERT_RETURN(conf_port->tx_buf, PJ_ENOMEM); + unsigned port_ptime, conf_ptime, buff_ptime; + + port_ptime = conf_port->samples_per_frame / conf_port->channel_count * + 1000 / conf_port->clock_rate; + conf_ptime = conf->samples_per_frame / conf->channel_count * + 1000 / conf->clock_rate; + + /* Calculate the size (in ptime) for the port buffer according to + * this formula: + * - if either ptime is an exact multiple of the other, then use + * the larger ptime (e.g. 20ms and 40ms, use 40ms). + * - if not, then the ptime is sum of both ptimes (e.g. 20ms + * and 30ms, use 50ms) + */ + if (port_ptime > conf_ptime) { + buff_ptime = port_ptime; + if (port_ptime % conf_ptime) + buff_ptime += conf_ptime; + } else { + buff_ptime = conf_ptime; + if (conf_ptime % port_ptime) + buff_ptime += port_ptime; + } + + /* Create RX buffer. */ + //conf_port->rx_buf_cap = (unsigned)(conf_port->samples_per_frame + + // conf->samples_per_frame * + // conf_port->clock_rate * 1.0 / + // conf->clock_rate + 0.5); + conf_port->rx_buf_cap = conf_port->clock_rate * buff_ptime / 1000; + if (conf_port->channel_count > conf->channel_count) + conf_port->rx_buf_cap *= conf_port->channel_count; + else + conf_port->rx_buf_cap *= conf->channel_count; + + conf_port->rx_buf_count = 0; + conf_port->rx_buf = (pj_int16_t*) + pj_pool_alloc(pool, conf_port->rx_buf_cap * + sizeof(conf_port->rx_buf[0])); + PJ_ASSERT_RETURN(conf_port->rx_buf, PJ_ENOMEM); + + /* Create TX buffer. */ + conf_port->tx_buf_cap = conf_port->rx_buf_cap; + conf_port->tx_buf_count = 0; + conf_port->tx_buf = (pj_int16_t*) + pj_pool_alloc(pool, conf_port->tx_buf_cap * + sizeof(conf_port->tx_buf[0])); + PJ_ASSERT_RETURN(conf_port->tx_buf, PJ_ENOMEM); } /* Create mix buffer. */ conf_port->mix_buf = (pj_int32_t*) - pj_pool_zalloc(pool, conf->samples_per_frame * - sizeof(conf_port->mix_buf[0])); + pj_pool_zalloc(pool, conf->samples_per_frame * + sizeof(conf_port->mix_buf[0])); PJ_ASSERT_RETURN(conf_port->mix_buf, PJ_ENOMEM); conf_port->last_mix_adj = NORMAL_LEVEL; @@ -434,10 +433,10 @@ static pj_status_t create_conf_port( pj_pool_t *pool, * Add passive port. */ static pj_status_t create_pasv_port( pjmedia_conf *conf, - pj_pool_t *pool, - const pj_str_t *name, - pjmedia_port *port, - struct conf_port **p_conf_port) + pj_pool_t *pool, + const pj_str_t *name, + pjmedia_port *port, + struct conf_port **p_conf_port) { struct conf_port *conf_port; pj_status_t status; @@ -446,20 +445,20 @@ static pj_status_t create_pasv_port( pjmedia_conf *conf, /* Create port */ status = create_conf_port(pool, conf, port, name, &conf_port); if (status != PJ_SUCCESS) - return status; + return status; /* Passive port has delay buf. */ ptime = conf->samples_per_frame * 1000 / conf->clock_rate / - conf->channel_count; + conf->channel_count; status = pjmedia_delay_buf_create(pool, name->ptr, - conf->clock_rate, - conf->samples_per_frame, - conf->channel_count, - RX_BUF_COUNT * ptime, /* max delay */ - 0, /* options */ - &conf_port->delay_buf); + conf->clock_rate, + conf->samples_per_frame, + conf->channel_count, + RX_BUF_COUNT * ptime, /* max delay */ + 0, /* options */ + &conf_port->delay_buf); if (status != PJ_SUCCESS) - return status; + return status; *p_conf_port = conf_port; @@ -471,7 +470,7 @@ static pj_status_t create_pasv_port( pjmedia_conf *conf, * Create port zero for the sound device. */ static pj_status_t create_sound_port( pj_pool_t *pool, - pjmedia_conf *conf ) + pjmedia_conf *conf ) { struct conf_port *conf_port; pj_str_t name = { "Master/sound", 12 }; @@ -480,52 +479,52 @@ static pj_status_t create_sound_port( pj_pool_t *pool, status = create_pasv_port(conf, pool, &name, NULL, &conf_port); if (status != PJ_SUCCESS) - return status; + return status; /* Create sound device port: */ if ((conf->options & PJMEDIA_CONF_NO_DEVICE) == 0) { - pjmedia_aud_stream *strm; - pjmedia_aud_param param; - - /* - * If capture is disabled then create player only port. - * Otherwise create bidirectional sound device port. - */ - if (conf->options & PJMEDIA_CONF_NO_MIC) { - status = pjmedia_snd_port_create_player(pool, -1, conf->clock_rate, - conf->channel_count, - conf->samples_per_frame, - conf->bits_per_sample, - 0, /* options */ - &conf->snd_dev_port); - - } else { - status = pjmedia_snd_port_create( pool, -1, -1, conf->clock_rate, - conf->channel_count, - conf->samples_per_frame, - conf->bits_per_sample, - 0, /* Options */ - &conf->snd_dev_port); - - } - - if (status != PJ_SUCCESS) - return status; - - strm = pjmedia_snd_port_get_snd_stream(conf->snd_dev_port); - status = pjmedia_aud_stream_get_param(strm, ¶m); - if (status == PJ_SUCCESS) { - pjmedia_aud_dev_info snd_dev_info; - if (conf->options & PJMEDIA_CONF_NO_MIC) - pjmedia_aud_dev_get_info(param.play_id, &snd_dev_info); - else - pjmedia_aud_dev_get_info(param.rec_id, &snd_dev_info); - pj_strdup2_with_null(pool, &conf_port->name, snd_dev_info.name); - } - - PJ_LOG(5,(THIS_FILE, "Sound device successfully created for port 0")); + pjmedia_aud_stream *strm; + pjmedia_aud_param param; + + /* + * If capture is disabled then create player only port. + * Otherwise create bidirectional sound device port. + */ + if (conf->options & PJMEDIA_CONF_NO_MIC) { + status = pjmedia_snd_port_create_player(pool, -1, conf->clock_rate, + conf->channel_count, + conf->samples_per_frame, + conf->bits_per_sample, + 0, /* options */ + &conf->snd_dev_port); + + } else { + status = pjmedia_snd_port_create( pool, -1, -1, conf->clock_rate, + conf->channel_count, + conf->samples_per_frame, + conf->bits_per_sample, + 0, /* Options */ + &conf->snd_dev_port); + + } + + if (status != PJ_SUCCESS) + return status; + + strm = pjmedia_snd_port_get_snd_stream(conf->snd_dev_port); + status = pjmedia_aud_stream_get_param(strm, ¶m); + if (status == PJ_SUCCESS) { + pjmedia_aud_dev_info snd_dev_info; + if (conf->options & PJMEDIA_CONF_NO_MIC) + pjmedia_aud_dev_get_info(param.play_id, &snd_dev_info); + else + pjmedia_aud_dev_get_info(param.rec_id, &snd_dev_info); + pj_strdup2_with_null(pool, &conf_port->name, snd_dev_info.name); + } + + PJ_LOG(5,(THIS_FILE, "Sound device successfully created for port 0")); } @@ -540,13 +539,13 @@ static pj_status_t create_sound_port( pj_pool_t *pool, * Create conference bridge. */ PJ_DEF(pj_status_t) pjmedia_conf_create( pj_pool_t *pool, - unsigned max_ports, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_conf **p_conf ) + unsigned max_ports, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_conf **p_conf ) { pjmedia_conf *conf; const pj_str_t name = { "Conf", 4 }; @@ -556,14 +555,14 @@ PJ_DEF(pj_status_t) pjmedia_conf_create( pj_pool_t *pool, PJ_ASSERT_RETURN(bits_per_sample == 16, PJ_EINVAL); PJ_LOG(5,(THIS_FILE, "Creating conference bridge with %d ports", - max_ports)); + max_ports)); /* Create and init conf structure. */ conf = PJ_POOL_ZALLOC_T(pool, pjmedia_conf); PJ_ASSERT_RETURN(conf, PJ_ENOMEM); conf->ports = (struct conf_port**) - pj_pool_zalloc(pool, max_ports*sizeof(void*)); + pj_pool_zalloc(pool, max_ports*sizeof(void*)); PJ_ASSERT_RETURN(conf->ports, PJ_ENOMEM); conf->options = options; @@ -579,8 +578,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_create( pj_pool_t *pool, PJ_ASSERT_RETURN(conf->master_port, PJ_ENOMEM); pjmedia_port_info_init(&conf->master_port->info, &name, SIGNATURE, - clock_rate, channel_count, bits_per_sample, - samples_per_frame); + clock_rate, channel_count, bits_per_sample, + samples_per_frame); conf->master_port->port_data.pdata = conf; conf->master_port->port_data.ldata = 0; @@ -593,27 +592,27 @@ PJ_DEF(pj_status_t) pjmedia_conf_create( pj_pool_t *pool, /* Create port zero for sound device. */ status = create_sound_port(pool, conf); if (status != PJ_SUCCESS) { - pjmedia_conf_destroy(conf); - return status; + pjmedia_conf_destroy(conf); + return status; } /* Create mutex. */ status = pj_mutex_create_recursive(pool, "conf", &conf->mutex); if (status != PJ_SUCCESS) { - pjmedia_conf_destroy(conf); - return status; + pjmedia_conf_destroy(conf); + return status; } /* If sound device was created, connect sound device to the * master port. */ if (conf->snd_dev_port) { - status = pjmedia_snd_port_connect( conf->snd_dev_port, - conf->master_port ); - if (status != PJ_SUCCESS) { - pjmedia_conf_destroy(conf); - return status; - } + status = pjmedia_snd_port_connect( conf->snd_dev_port, + conf->master_port ); + if (status != PJ_SUCCESS) { + pjmedia_conf_destroy(conf); + return status; + } } @@ -657,37 +656,37 @@ PJ_DEF(pj_status_t) pjmedia_conf_destroy( pjmedia_conf *conf ) /* Destroy sound device port. */ if (conf->snd_dev_port) { - pjmedia_snd_port_destroy(conf->snd_dev_port); - conf->snd_dev_port = NULL; + pjmedia_snd_port_destroy(conf->snd_dev_port); + conf->snd_dev_port = NULL; } /* Destroy delay buf of all (passive) ports. */ for (i=0, ci=0; imax_ports && ciport_cnt; ++i) { - struct conf_port *cport; - - cport = conf->ports[i]; - if (!cport) - continue; - - ++ci; - - if (cport->rx_resample) { - pjmedia_resample_destroy(cport->rx_resample); - cport->rx_resample = NULL; - } - if (cport->tx_resample) { - pjmedia_resample_destroy(cport->tx_resample); - cport->tx_resample = NULL; - } - if (cport->delay_buf) { - pjmedia_delay_buf_destroy(cport->delay_buf); - cport->delay_buf = NULL; - } + struct conf_port *cport; + + cport = conf->ports[i]; + if (!cport) + continue; + + ++ci; + + if (cport->rx_resample) { + pjmedia_resample_destroy(cport->rx_resample); + cport->rx_resample = NULL; + } + if (cport->tx_resample) { + pjmedia_resample_destroy(cport->tx_resample); + cport->tx_resample = NULL; + } + if (cport->delay_buf) { + pjmedia_delay_buf_destroy(cport->delay_buf); + cport->delay_buf = NULL; + } } /* Destroy mutex */ if (conf->mutex) - pj_mutex_destroy(conf->mutex); + pj_mutex_destroy(conf->mutex); return PJ_SUCCESS; } @@ -710,7 +709,7 @@ static pj_status_t destroy_port_pasv(pjmedia_port *this_port) { status = pjmedia_delay_buf_destroy(port->delay_buf); if (status == PJ_SUCCESS) - port->delay_buf = NULL; + port->delay_buf = NULL; return status; } @@ -737,7 +736,7 @@ PJ_DEF(pjmedia_port*) pjmedia_conf_get_master_port(pjmedia_conf *conf) * Set master port name. */ PJ_DEF(pj_status_t) pjmedia_conf_set_port0_name(pjmedia_conf *conf, - const pj_str_t *name) + const pj_str_t *name) { pj_size_t len; @@ -746,7 +745,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_set_port0_name(pjmedia_conf *conf, len = name->slen; if (len > sizeof(conf->master_name_buf)) - len = sizeof(conf->master_name_buf); + len = sizeof(conf->master_name_buf); if (len > 0) pj_memcpy(conf->master_name_buf, name->ptr, len); @@ -754,7 +753,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_set_port0_name(pjmedia_conf *conf, conf->ports[0]->name.slen = len; if (conf->master_port) - conf->master_port->info.name = conf->ports[0]->name; + conf->master_port->info.name = conf->ports[0]->name; return PJ_SUCCESS; } @@ -763,10 +762,10 @@ PJ_DEF(pj_status_t) pjmedia_conf_set_port0_name(pjmedia_conf *conf, * Add stream port to the conference bridge. */ PJ_DEF(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, - pj_pool_t *pool, - pjmedia_port *strm_port, - const pj_str_t *port_name, - unsigned *p_port ) + pj_pool_t *pool, + pjmedia_port *strm_port, + const pj_str_t *port_name, + unsigned *p_port ) { struct conf_port *conf_port; unsigned index; @@ -776,32 +775,32 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, /* If port_name is not specified, use the port's name */ if (!port_name) - port_name = &strm_port->info.name; + port_name = &strm_port->info.name; /* For this version of PJMEDIA, channel(s) number MUST be: * - same between port & conference bridge. * - monochannel on port or conference bridge. */ if (PJMEDIA_PIA_CCNT(&strm_port->info) != conf->channel_count && - (PJMEDIA_PIA_CCNT(&strm_port->info) != 1 && - conf->channel_count != 1)) + (PJMEDIA_PIA_CCNT(&strm_port->info) != 1 && + conf->channel_count != 1)) { - pj_assert(!"Number of channels mismatch"); - return PJMEDIA_ENCCHANNEL; + pj_assert(!"Number of channels mismatch"); + return PJMEDIA_ENCCHANNEL; } pj_mutex_lock(conf->mutex); if (conf->port_cnt >= conf->max_ports) { - pj_assert(!"Too many ports"); - pj_mutex_unlock(conf->mutex); - return PJ_ETOOMANY; + pj_assert(!"Too many ports"); + pj_mutex_unlock(conf->mutex); + return PJ_ETOOMANY; } /* Find empty port in the conference bridge. */ for (index=0; index < conf->max_ports; ++index) { - if (conf->ports[index] == NULL) - break; + if (conf->ports[index] == NULL) + break; } pj_assert(index != conf->max_ports); @@ -809,8 +808,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, /* Create conf port structure. */ status = create_conf_port(pool, conf, strm_port, port_name, &conf_port); if (status != PJ_SUCCESS) { - pj_mutex_unlock(conf->mutex); - return status; + pj_mutex_unlock(conf->mutex); + return status; } /* Put the port. */ @@ -819,7 +818,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, /* Done. */ if (p_port) { - *p_port = index; + *p_port = index; } pj_mutex_unlock(conf->mutex); @@ -833,15 +832,15 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_port( pjmedia_conf *conf, * Add passive port. */ PJ_DEF(pj_status_t) pjmedia_conf_add_passive_port( pjmedia_conf *conf, - pj_pool_t *pool, - const pj_str_t *name, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - unsigned *p_slot, - pjmedia_port **p_port ) + pj_pool_t *pool, + const pj_str_t *name, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + unsigned *p_slot, + pjmedia_port **p_port ) { struct conf_port *conf_port; pjmedia_port *port; @@ -850,7 +849,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_passive_port( pjmedia_conf *conf, pj_status_t status; PJ_LOG(1, (THIS_FILE, "This API has been deprecated since 1.3 and will " - "be removed in the future release!")); + "be removed in the future release!")); PJ_ASSERT_RETURN(conf && pool, PJ_EINVAL); @@ -859,10 +858,10 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_passive_port( pjmedia_conf *conf, * - monochannel on port or conference bridge. */ if (channel_count != conf->channel_count && - (channel_count != 1 && conf->channel_count != 1)) + (channel_count != 1 && conf->channel_count != 1)) { - pj_assert(!"Number of channels mismatch"); - return PJMEDIA_ENCCHANNEL; + pj_assert(!"Number of channels mismatch"); + return PJMEDIA_ENCCHANNEL; } /* For this version, options must be zero */ @@ -872,24 +871,24 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_passive_port( pjmedia_conf *conf, pj_mutex_lock(conf->mutex); if (conf->port_cnt >= conf->max_ports) { - pj_assert(!"Too many ports"); - pj_mutex_unlock(conf->mutex); - return PJ_ETOOMANY; + pj_assert(!"Too many ports"); + pj_mutex_unlock(conf->mutex); + return PJ_ETOOMANY; } /* Find empty port in the conference bridge. */ for (index=0; index < conf->max_ports; ++index) { - if (conf->ports[index] == NULL) - break; + if (conf->ports[index] == NULL) + break; } pj_assert(index != conf->max_ports); if (name == NULL) { - name = &tmp; + name = &tmp; - tmp.ptr = (char*) pj_pool_alloc(pool, 32); - tmp.slen = pj_ansi_snprintf(tmp.ptr, 32, "ConfPort#%d", index); + tmp.ptr = (char*) pj_pool_alloc(pool, 32); + tmp.slen = pj_ansi_snprintf(tmp.ptr, 32, "ConfPort#%d", index); } /* Create and initialize the media port structure. */ @@ -897,8 +896,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_passive_port( pjmedia_conf *conf, PJ_ASSERT_RETURN(port, PJ_ENOMEM); pjmedia_port_info_init(&port->info, name, SIGNATURE_PORT, - clock_rate, channel_count, bits_per_sample, - samples_per_frame); + clock_rate, channel_count, bits_per_sample, + samples_per_frame); port->port_data.pdata = conf; port->port_data.ldata = index; @@ -911,8 +910,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_passive_port( pjmedia_conf *conf, /* Create conf port structure. */ status = create_pasv_port(conf, pool, name, port, &conf_port); if (status != PJ_SUCCESS) { - pj_mutex_unlock(conf->mutex); - return status; + pj_mutex_unlock(conf->mutex); + return status; } @@ -922,9 +921,9 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_passive_port( pjmedia_conf *conf, /* Done. */ if (p_slot) - *p_slot = index; + *p_slot = index; if (p_port) - *p_port = port; + *p_port = port; pj_mutex_unlock(conf->mutex); @@ -938,9 +937,9 @@ PJ_DEF(pj_status_t) pjmedia_conf_add_passive_port( pjmedia_conf *conf, * Change TX and RX settings for the port. */ PJ_DEF(pj_status_t) pjmedia_conf_configure_port( pjmedia_conf *conf, - unsigned slot, - pjmedia_port_op tx, - pjmedia_port_op rx) + unsigned slot, + pjmedia_port_op tx, + pjmedia_port_op rx) { struct conf_port *conf_port; @@ -952,17 +951,17 @@ PJ_DEF(pj_status_t) pjmedia_conf_configure_port( pjmedia_conf *conf, /* Port must be valid. */ conf_port = conf->ports[slot]; if (conf_port == NULL) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } conf_port = conf->ports[slot]; if (tx != PJMEDIA_PORT_NO_CHANGE) - conf_port->tx_setting = tx; + conf_port->tx_setting = tx; if (rx != PJMEDIA_PORT_NO_CHANGE) - conf_port->rx_setting = rx; + conf_port->rx_setting = rx; pj_mutex_unlock(conf->mutex); @@ -974,9 +973,9 @@ PJ_DEF(pj_status_t) pjmedia_conf_configure_port( pjmedia_conf *conf, * Connect port. */ PJ_DEF(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, - unsigned src_slot, - unsigned sink_slot, - int adj_level ) + unsigned src_slot, + unsigned sink_slot, + int adj_level ) { struct conf_port *src_port, *dst_port; pj_bool_t start_sound = PJ_FALSE; @@ -984,7 +983,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, /* Check arguments */ PJ_ASSERT_RETURN(conf && src_slotmax_ports && - sink_slotmax_ports, PJ_EINVAL); + sink_slotmax_ports, PJ_EINVAL); /* Value must be from -128 to +127 */ /* Disabled, you can put more than +127, at your own risk: @@ -998,35 +997,35 @@ PJ_DEF(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, src_port = conf->ports[src_slot]; dst_port = conf->ports[sink_slot]; if (!src_port || !dst_port) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } /* Check if connection has been made */ for (i=0; ilistener_cnt; ++i) { - if (src_port->listener_slots[i] == sink_slot) - break; + if (src_port->listener_slots[i] == sink_slot) + break; } if (i == src_port->listener_cnt) { - src_port->listener_slots[src_port->listener_cnt] = sink_slot; - /* Set normalized adjustment level. */ - src_port->listener_adj_level[src_port->listener_cnt] = adj_level + - NORMAL_LEVEL; - ++conf->connect_cnt; - ++src_port->listener_cnt; - ++dst_port->transmitter_cnt; - - if (conf->connect_cnt == 1) - start_sound = 1; - - PJ_LOG(4,(THIS_FILE,"Port %d (%.*s) transmitting to port %d (%.*s)", - src_slot, - (int)src_port->name.slen, - src_port->name.ptr, - sink_slot, - (int)dst_port->name.slen, - dst_port->name.ptr)); + src_port->listener_slots[src_port->listener_cnt] = sink_slot; + /* Set normalized adjustment level. */ + src_port->listener_adj_level[src_port->listener_cnt] = adj_level + + NORMAL_LEVEL; + ++conf->connect_cnt; + ++src_port->listener_cnt; + ++dst_port->transmitter_cnt; + + if (conf->connect_cnt == 1) + start_sound = 1; + + PJ_LOG(4,(THIS_FILE,"Port %d (%.*s) transmitting to port %d (%.*s)", + src_slot, + (int)src_port->name.slen, + src_port->name.ptr, + sink_slot, + (int)dst_port->name.slen, + dst_port->name.ptr)); } pj_mutex_unlock(conf->mutex); @@ -1035,7 +1034,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, * sound thread will deadlock (?) */ if (start_sound) - resume_sound(conf); + resume_sound(conf); return PJ_SUCCESS; } @@ -1045,15 +1044,15 @@ PJ_DEF(pj_status_t) pjmedia_conf_connect_port( pjmedia_conf *conf, * Disconnect port */ PJ_DEF(pj_status_t) pjmedia_conf_disconnect_port( pjmedia_conf *conf, - unsigned src_slot, - unsigned sink_slot ) + unsigned src_slot, + unsigned sink_slot ) { struct conf_port *src_port, *dst_port; unsigned i; /* Check arguments */ PJ_ASSERT_RETURN(conf && src_slotmax_ports && - sink_slotmax_ports, PJ_EINVAL); + sink_slotmax_ports, PJ_EINVAL); pj_mutex_lock(conf->mutex); @@ -1061,47 +1060,47 @@ PJ_DEF(pj_status_t) pjmedia_conf_disconnect_port( pjmedia_conf *conf, src_port = conf->ports[src_slot]; dst_port = conf->ports[sink_slot]; if (!src_port || !dst_port) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } /* Check if connection has been made */ for (i=0; ilistener_cnt; ++i) { - if (src_port->listener_slots[i] == sink_slot) - break; + if (src_port->listener_slots[i] == sink_slot) + break; } if (i != src_port->listener_cnt) { - pj_assert(src_port->listener_cnt > 0 && - src_port->listener_cnt < conf->max_ports); - pj_assert(dst_port->transmitter_cnt > 0 && - dst_port->transmitter_cnt < conf->max_ports); - pj_array_erase(src_port->listener_slots, sizeof(SLOT_TYPE), - src_port->listener_cnt, i); + pj_assert(src_port->listener_cnt > 0 && + src_port->listener_cnt < conf->max_ports); + pj_assert(dst_port->transmitter_cnt > 0 && + dst_port->transmitter_cnt < conf->max_ports); + pj_array_erase(src_port->listener_slots, sizeof(SLOT_TYPE), + src_port->listener_cnt, i); pj_array_erase(src_port->listener_adj_level, sizeof(unsigned), src_port->listener_cnt, i); - --conf->connect_cnt; - --src_port->listener_cnt; - --dst_port->transmitter_cnt; - - PJ_LOG(4,(THIS_FILE, - "Port %d (%.*s) stop transmitting to port %d (%.*s)", - src_slot, - (int)src_port->name.slen, - src_port->name.ptr, - sink_slot, - (int)dst_port->name.slen, - dst_port->name.ptr)); - - /* if source port is passive port and has no listener, reset delaybuf */ - if (src_port->delay_buf && src_port->listener_cnt == 0) - pjmedia_delay_buf_reset(src_port->delay_buf); + --conf->connect_cnt; + --src_port->listener_cnt; + --dst_port->transmitter_cnt; + + PJ_LOG(4,(THIS_FILE, + "Port %d (%.*s) stop transmitting to port %d (%.*s)", + src_slot, + (int)src_port->name.slen, + src_port->name.ptr, + sink_slot, + (int)dst_port->name.slen, + dst_port->name.ptr)); + + /* if source port is passive port and has no listener, reset delaybuf */ + if (src_port->delay_buf && src_port->listener_cnt == 0) + pjmedia_delay_buf_reset(src_port->delay_buf); } pj_mutex_unlock(conf->mutex); if (conf->connect_cnt == 0) { - pause_sound(conf); + pause_sound(conf); } return PJ_SUCCESS; @@ -1113,7 +1112,7 @@ PJ_DEF(pj_status_t) pjmedia_conf_disconnect_port( pjmedia_conf *conf, */ PJ_DEF(pj_status_t) pjmedia_conf_disconnect_port_from_sources( pjmedia_conf *conf, - unsigned sink_slot) + unsigned sink_slot) { unsigned i; @@ -1124,33 +1123,33 @@ pjmedia_conf_disconnect_port_from_sources( pjmedia_conf *conf, /* Remove this port from transmit array of other ports. */ for (i=0; imax_ports; ++i) { - unsigned j; - struct conf_port *src_port; - - src_port = conf->ports[i]; - - if (!src_port) - continue; - - if (src_port->listener_cnt == 0) - continue; - - for (j=0; jlistener_cnt; ++j) { - if (src_port->listener_slots[j] == sink_slot) { - pj_array_erase(src_port->listener_slots, sizeof(SLOT_TYPE), - src_port->listener_cnt, j); - pj_array_erase(src_port->listener_adj_level, sizeof(unsigned), - src_port->listener_cnt, j); - pj_assert(conf->connect_cnt > 0); - --conf->connect_cnt; - --src_port->listener_cnt; - break; - } - } + unsigned j; + struct conf_port *src_port; + + src_port = conf->ports[i]; + + if (!src_port) + continue; + + if (src_port->listener_cnt == 0) + continue; + + for (j=0; jlistener_cnt; ++j) { + if (src_port->listener_slots[j] == sink_slot) { + pj_array_erase(src_port->listener_slots, sizeof(SLOT_TYPE), + src_port->listener_cnt, j); + pj_array_erase(src_port->listener_adj_level, sizeof(unsigned), + src_port->listener_cnt, j); + pj_assert(conf->connect_cnt > 0); + --conf->connect_cnt; + --src_port->listener_cnt; + break; + } + } } if (conf->connect_cnt == 0) { - pause_sound(conf); + pause_sound(conf); } pj_mutex_unlock(conf->mutex); @@ -1164,7 +1163,7 @@ pjmedia_conf_disconnect_port_from_sources( pjmedia_conf *conf, */ PJ_DEF(pj_status_t) pjmedia_conf_disconnect_port_from_sinks( pjmedia_conf *conf, - unsigned src_slot) + unsigned src_slot) { struct conf_port *src_port; @@ -1176,25 +1175,25 @@ pjmedia_conf_disconnect_port_from_sinks( pjmedia_conf *conf, /* Port must be valid. */ src_port = conf->ports[src_slot]; if (!src_port) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } /* Update transmitter_cnt of ports we're transmitting to */ while (src_port->listener_cnt) { - unsigned dst_slot; - struct conf_port *dst_port; - - dst_slot = src_port->listener_slots[src_port->listener_cnt-1]; - dst_port = conf->ports[dst_slot]; - --dst_port->transmitter_cnt; - --src_port->listener_cnt; - pj_assert(conf->connect_cnt > 0); - --conf->connect_cnt; + unsigned dst_slot; + struct conf_port *dst_port; + + dst_slot = src_port->listener_slots[src_port->listener_cnt-1]; + dst_port = conf->ports[dst_slot]; + --dst_port->transmitter_cnt; + --src_port->listener_cnt; + pj_assert(conf->connect_cnt > 0); + --conf->connect_cnt; } if (conf->connect_cnt == 0) { - pause_sound(conf); + pause_sound(conf); } pj_mutex_unlock(conf->mutex); @@ -1224,7 +1223,7 @@ PJ_DEF(unsigned) pjmedia_conf_get_connect_count(pjmedia_conf *conf) * Remove the specified port. */ PJ_DEF(pj_status_t) pjmedia_conf_remove_port( pjmedia_conf *conf, - unsigned port ) + unsigned port ) { struct conf_port *conf_port; @@ -1241,8 +1240,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_remove_port( pjmedia_conf *conf, /* Port must be valid. */ conf_port = conf->ports[port]; if (conf_port == NULL) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } conf_port->tx_setting = PJMEDIA_PORT_DISABLE; @@ -1256,23 +1255,23 @@ PJ_DEF(pj_status_t) pjmedia_conf_remove_port( pjmedia_conf *conf, /* Destroy resample if this conf port has it. */ if (conf_port->rx_resample) { - pjmedia_resample_destroy(conf_port->rx_resample); - conf_port->rx_resample = NULL; + pjmedia_resample_destroy(conf_port->rx_resample); + conf_port->rx_resample = NULL; } if (conf_port->tx_resample) { - pjmedia_resample_destroy(conf_port->tx_resample); - conf_port->tx_resample = NULL; + pjmedia_resample_destroy(conf_port->tx_resample); + conf_port->tx_resample = NULL; } /* Destroy pjmedia port if this conf port is passive port, * i.e: has delay buf. */ if (conf_port->delay_buf) { - pjmedia_delay_buf_destroy(conf_port->delay_buf); - conf_port->delay_buf = NULL; + pjmedia_delay_buf_destroy(conf_port->delay_buf); + conf_port->delay_buf = NULL; - pjmedia_port_destroy(conf_port->port); - conf_port->port = NULL; + pjmedia_port_destroy(conf_port->port); + conf_port->port = NULL; } /* Remove the port. */ @@ -1289,8 +1288,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_remove_port( pjmedia_conf *conf, * Enum ports. */ PJ_DEF(pj_status_t) pjmedia_conf_enum_ports( pjmedia_conf *conf, - unsigned ports[], - unsigned *p_count ) + unsigned ports[], + unsigned *p_count ) { unsigned i, count=0; @@ -1300,10 +1299,10 @@ PJ_DEF(pj_status_t) pjmedia_conf_enum_ports( pjmedia_conf *conf, pj_mutex_lock(conf->mutex); for (i=0; imax_ports && count<*p_count; ++i) { - if (!conf->ports[i]) - continue; + if (!conf->ports[i]) + continue; - ports[count++] = i; + ports[count++] = i; } /* Unlock mutex */ @@ -1317,8 +1316,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_enum_ports( pjmedia_conf *conf, * Get port info */ PJ_DEF(pj_status_t) pjmedia_conf_get_port_info( pjmedia_conf *conf, - unsigned slot, - pjmedia_conf_port_info *info) + unsigned slot, + pjmedia_conf_port_info *info) { struct conf_port *conf_port; @@ -1331,8 +1330,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_get_port_info( pjmedia_conf *conf, /* Port must be valid. */ conf_port = conf->ports[slot]; if (conf_port == NULL) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } info->slot = slot; @@ -1363,8 +1362,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_get_port_info( pjmedia_conf *conf, PJ_DEF(pj_status_t) pjmedia_conf_get_ports_info(pjmedia_conf *conf, - unsigned *size, - pjmedia_conf_port_info info[]) + unsigned *size, + pjmedia_conf_port_info info[]) { unsigned i, count=0; @@ -1374,11 +1373,11 @@ PJ_DEF(pj_status_t) pjmedia_conf_get_ports_info(pjmedia_conf *conf, pj_mutex_lock(conf->mutex); for (i=0; imax_ports && count<*size; ++i) { - if (!conf->ports[i]) - continue; + if (!conf->ports[i]) + continue; - pjmedia_conf_get_port_info(conf, i, &info[count]); - ++count; + pjmedia_conf_get_port_info(conf, i, &info[count]); + ++count; } /* Unlock mutex */ @@ -1393,9 +1392,9 @@ PJ_DEF(pj_status_t) pjmedia_conf_get_ports_info(pjmedia_conf *conf, * Get signal level. */ PJ_DEF(pj_status_t) pjmedia_conf_get_signal_level( pjmedia_conf *conf, - unsigned slot, - unsigned *tx_level, - unsigned *rx_level) + unsigned slot, + unsigned *tx_level, + unsigned *rx_level) { struct conf_port *conf_port; @@ -1408,16 +1407,16 @@ PJ_DEF(pj_status_t) pjmedia_conf_get_signal_level( pjmedia_conf *conf, /* Port must be valid. */ conf_port = conf->ports[slot]; if (conf_port == NULL) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } if (tx_level != NULL) { - *tx_level = conf_port->tx_level; + *tx_level = conf_port->tx_level; } if (rx_level != NULL) - *rx_level = conf_port->rx_level; + *rx_level = conf_port->rx_level; /* Unlock mutex */ pj_mutex_unlock(conf->mutex); @@ -1430,8 +1429,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_get_signal_level( pjmedia_conf *conf, * Adjust RX level of individual port. */ PJ_DEF(pj_status_t) pjmedia_conf_adjust_rx_level( pjmedia_conf *conf, - unsigned slot, - int adj_level ) + unsigned slot, + int adj_level ) { struct conf_port *conf_port; @@ -1450,8 +1449,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_adjust_rx_level( pjmedia_conf *conf, /* Port must be valid. */ conf_port = conf->ports[slot]; if (conf_port == NULL) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } /* Set normalized adjustment level. */ @@ -1468,8 +1467,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_adjust_rx_level( pjmedia_conf *conf, * Adjust TX level of individual port. */ PJ_DEF(pj_status_t) pjmedia_conf_adjust_tx_level( pjmedia_conf *conf, - unsigned slot, - int adj_level ) + unsigned slot, + int adj_level ) { struct conf_port *conf_port; @@ -1488,8 +1487,8 @@ PJ_DEF(pj_status_t) pjmedia_conf_adjust_tx_level( pjmedia_conf *conf, /* Port must be valid. */ conf_port = conf->ports[slot]; if (conf_port == NULL) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } /* Set normalized adjustment level. */ @@ -1505,16 +1504,16 @@ PJ_DEF(pj_status_t) pjmedia_conf_adjust_tx_level( pjmedia_conf *conf, * Adjust level of individual connection. */ PJ_DEF(pj_status_t) pjmedia_conf_adjust_conn_level( pjmedia_conf *conf, - unsigned src_slot, - unsigned sink_slot, - int adj_level ) + unsigned src_slot, + unsigned sink_slot, + int adj_level ) { struct conf_port *src_port, *dst_port; unsigned i; /* Check arguments */ PJ_ASSERT_RETURN(conf && src_slotmax_ports && - sink_slotmax_ports, PJ_EINVAL); + sink_slotmax_ports, PJ_EINVAL); /* Value must be from -128 to +127 */ /* Disabled, you can put more than +127, at your own risk: @@ -1528,20 +1527,20 @@ PJ_DEF(pj_status_t) pjmedia_conf_adjust_conn_level( pjmedia_conf *conf, src_port = conf->ports[src_slot]; dst_port = conf->ports[sink_slot]; if (!src_port || !dst_port) { - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } /* Check if connection has been made */ for (i=0; ilistener_cnt; ++i) { - if (src_port->listener_slots[i] == sink_slot) - break; + if (src_port->listener_slots[i] == sink_slot) + break; } if (i == src_port->listener_cnt) { - /* connection hasn't been made */ - pj_mutex_unlock(conf->mutex); - return PJ_EINVAL; + /* connection hasn't been made */ + pj_mutex_unlock(conf->mutex); + return PJ_EINVAL; } /* Set normalized adjustment level. */ src_port->listener_adj_level[i] = adj_level + NORMAL_LEVEL; @@ -1555,15 +1554,15 @@ PJ_DEF(pj_status_t) pjmedia_conf_adjust_conn_level( pjmedia_conf *conf, * Read from port. */ static pj_status_t read_port( pjmedia_conf *conf, - struct conf_port *cport, pj_int16_t *frame, - pj_size_t count, pjmedia_frame_type *type ) + struct conf_port *cport, pj_int16_t *frame, + pj_size_t count, pjmedia_frame_type *type ) { pj_assert(count == conf->samples_per_frame); TRACE_((THIS_FILE, "read_port %.*s: count=%d", - (int)cport->name.slen, cport->name.ptr, - count)); + (int)cport->name.slen, cport->name.ptr, + count)); /* * If port's samples per frame and sampling rate and channel count @@ -1571,131 +1570,131 @@ static pj_status_t read_port( pjmedia_conf *conf, * the port. */ if (cport->rx_buf_cap == 0) { - pjmedia_frame f; - pj_status_t status; + pjmedia_frame f; + pj_status_t status; - f.buf = frame; - f.size = count * BYTES_PER_SAMPLE; + f.buf = frame; + f.size = count * BYTES_PER_SAMPLE; - TRACE_((THIS_FILE, " get_frame %.*s: count=%d", - (int)cport->name.slen, cport->name.ptr, - count)); + TRACE_((THIS_FILE, " get_frame %.*s: count=%d", + (int)cport->name.slen, cport->name.ptr, + count)); - status = pjmedia_port_get_frame(cport->port, &f); + status = pjmedia_port_get_frame(cport->port, &f); - *type = f.type; + *type = f.type; - return status; + return status; } else { - unsigned samples_req; - - /* Initialize frame type */ - if (cport->rx_buf_count == 0) { - *type = PJMEDIA_FRAME_TYPE_NONE; - } else { - /* we got some samples in the buffer */ - *type = PJMEDIA_FRAME_TYPE_AUDIO; - } - - /* - * If we don't have enough samples in rx_buf, read from the port - * first. Remember that rx_buf may be in different clock rate and - * channel count! - */ - - samples_req = (unsigned) (count * 1.0 * - cport->clock_rate / conf->clock_rate + 0.5); - - while (cport->rx_buf_count < samples_req) { - - pjmedia_frame f; - pj_status_t status; - - f.buf = cport->rx_buf + cport->rx_buf_count; - f.size = cport->samples_per_frame * BYTES_PER_SAMPLE; - - TRACE_((THIS_FILE, " get_frame, count=%d", - cport->samples_per_frame)); - - status = pjmedia_port_get_frame(cport->port, &f); - - if (status != PJ_SUCCESS) { - /* Fatal error! */ - return status; - } - - if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) { - TRACE_((THIS_FILE, " get_frame returned non-audio")); - pjmedia_zero_samples( cport->rx_buf + cport->rx_buf_count, - cport->samples_per_frame); - } else { - /* We've got at least one frame */ - *type = PJMEDIA_FRAME_TYPE_AUDIO; - } - - /* Adjust channels */ - if (cport->channel_count != conf->channel_count) { - if (cport->channel_count == 1) { - pjmedia_convert_channel_1ton((pj_int16_t*)f.buf, - (const pj_int16_t*)f.buf, - conf->channel_count, - cport->samples_per_frame, - 0); - cport->rx_buf_count += (cport->samples_per_frame * - conf->channel_count); - } else { /* conf->channel_count == 1 */ - pjmedia_convert_channel_nto1((pj_int16_t*)f.buf, - (const pj_int16_t*)f.buf, - cport->channel_count, - cport->samples_per_frame, - PJMEDIA_STEREO_MIX, 0); - cport->rx_buf_count += (cport->samples_per_frame / - cport->channel_count); - } - } else { - cport->rx_buf_count += cport->samples_per_frame; - } - - TRACE_((THIS_FILE, " rx buffer size is now %d", - cport->rx_buf_count)); - - pj_assert(cport->rx_buf_count <= cport->rx_buf_cap); - } - - /* - * If port's clock_rate is different, resample. - * Otherwise just copy. - */ - if (cport->clock_rate != conf->clock_rate) { - - unsigned src_count; - - TRACE_((THIS_FILE, " resample, input count=%d", - pjmedia_resample_get_input_size(cport->rx_resample))); - - pjmedia_resample_run( cport->rx_resample,cport->rx_buf, frame); - - src_count = (unsigned)(count * 1.0 * cport->clock_rate / - conf->clock_rate + 0.5); - cport->rx_buf_count -= src_count; - if (cport->rx_buf_count) { - pjmedia_move_samples(cport->rx_buf, cport->rx_buf+src_count, - cport->rx_buf_count); - } - - TRACE_((THIS_FILE, " rx buffer size is now %d", - cport->rx_buf_count)); - - } else { - - pjmedia_copy_samples(frame, cport->rx_buf, (unsigned)count); - cport->rx_buf_count -= (unsigned)count; - if (cport->rx_buf_count) { - pjmedia_move_samples(cport->rx_buf, cport->rx_buf+count, - cport->rx_buf_count); - } - } + unsigned samples_req; + + /* Initialize frame type */ + if (cport->rx_buf_count == 0) { + *type = PJMEDIA_FRAME_TYPE_NONE; + } else { + /* we got some samples in the buffer */ + *type = PJMEDIA_FRAME_TYPE_AUDIO; + } + + /* + * If we don't have enough samples in rx_buf, read from the port + * first. Remember that rx_buf may be in different clock rate and + * channel count! + */ + + samples_req = (unsigned) (count * 1.0 * + cport->clock_rate / conf->clock_rate + 0.5); + + while (cport->rx_buf_count < samples_req) { + + pjmedia_frame f; + pj_status_t status; + + f.buf = cport->rx_buf + cport->rx_buf_count; + f.size = cport->samples_per_frame * BYTES_PER_SAMPLE; + + TRACE_((THIS_FILE, " get_frame, count=%d", + cport->samples_per_frame)); + + status = pjmedia_port_get_frame(cport->port, &f); + + if (status != PJ_SUCCESS) { + /* Fatal error! */ + return status; + } + + if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) { + TRACE_((THIS_FILE, " get_frame returned non-audio")); + pjmedia_zero_samples( cport->rx_buf + cport->rx_buf_count, + cport->samples_per_frame); + } else { + /* We've got at least one frame */ + *type = PJMEDIA_FRAME_TYPE_AUDIO; + } + + /* Adjust channels */ + if (cport->channel_count != conf->channel_count) { + if (cport->channel_count == 1) { + pjmedia_convert_channel_1ton((pj_int16_t*)f.buf, + (const pj_int16_t*)f.buf, + conf->channel_count, + cport->samples_per_frame, + 0); + cport->rx_buf_count += (cport->samples_per_frame * + conf->channel_count); + } else { /* conf->channel_count == 1 */ + pjmedia_convert_channel_nto1((pj_int16_t*)f.buf, + (const pj_int16_t*)f.buf, + cport->channel_count, + cport->samples_per_frame, + PJMEDIA_STEREO_MIX, 0); + cport->rx_buf_count += (cport->samples_per_frame / + cport->channel_count); + } + } else { + cport->rx_buf_count += cport->samples_per_frame; + } + + TRACE_((THIS_FILE, " rx buffer size is now %d", + cport->rx_buf_count)); + + pj_assert(cport->rx_buf_count <= cport->rx_buf_cap); + } + + /* + * If port's clock_rate is different, resample. + * Otherwise just copy. + */ + if (cport->clock_rate != conf->clock_rate) { + + unsigned src_count; + + TRACE_((THIS_FILE, " resample, input count=%d", + pjmedia_resample_get_input_size(cport->rx_resample))); + + pjmedia_resample_run( cport->rx_resample,cport->rx_buf, frame); + + src_count = (unsigned)(count * 1.0 * cport->clock_rate / + conf->clock_rate + 0.5); + cport->rx_buf_count -= src_count; + if (cport->rx_buf_count) { + pjmedia_move_samples(cport->rx_buf, cport->rx_buf+src_count, + cport->rx_buf_count); + } + + TRACE_((THIS_FILE, " rx buffer size is now %d", + cport->rx_buf_count)); + + } else { + + pjmedia_copy_samples(frame, cport->rx_buf, (unsigned)count); + cport->rx_buf_count -= (unsigned)count; + if (cport->rx_buf_count) { + pjmedia_move_samples(cport->rx_buf, cport->rx_buf+count, + cport->rx_buf_count); + } + } } return PJ_SUCCESS; @@ -1706,8 +1705,8 @@ static pj_status_t read_port( pjmedia_conf *conf, * Write the mixed signal to the port. */ static pj_status_t write_port(pjmedia_conf *conf, struct conf_port *cport, - const pj_timestamp *timestamp, - pjmedia_frame_type *frm_type) + const pj_timestamp *timestamp, + pjmedia_frame_type *frm_type) { pj_int16_t *buf; unsigned j, ts; @@ -1720,50 +1719,50 @@ static pj_status_t write_port(pjmedia_conf *conf, struct conf_port *cport, /* Skip port if it is disabled */ if (cport->tx_setting != PJMEDIA_PORT_ENABLE) { - cport->tx_level = 0; - *frm_type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; + cport->tx_level = 0; + *frm_type = PJMEDIA_FRAME_TYPE_NONE; + return PJ_SUCCESS; } /* If port is muted or nobody is transmitting to this port, * transmit NULL frame. */ else if ((cport->tx_setting == PJMEDIA_PORT_MUTE) || - (cport->transmitter_cnt == 0)) { - pjmedia_frame frame; - - /* Clear left-over samples in tx_buffer, if any, so that it won't - * be transmitted next time we have audio signal. - */ - cport->tx_buf_count = 0; - - /* Add sample counts to heart-beat samples */ - cport->tx_heart_beat += conf->samples_per_frame * cport->clock_rate / - conf->clock_rate * - cport->channel_count / conf->channel_count; - - /* Set frame timestamp */ - frame.timestamp.u64 = timestamp->u64 * cport->clock_rate / - conf->clock_rate; - frame.type = PJMEDIA_FRAME_TYPE_NONE; - frame.buf = NULL; - frame.size = 0; - - /* Transmit heart-beat frames (may transmit more than one NULL frame - * if port's ptime is less than bridge's ptime. - */ - if (cport->port && cport->port->put_frame) { - while (cport->tx_heart_beat >= cport->samples_per_frame) { - - pjmedia_port_put_frame(cport->port, &frame); - - cport->tx_heart_beat -= cport->samples_per_frame; - frame.timestamp.u64 += cport->samples_per_frame; - } - } - - cport->tx_level = 0; - *frm_type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; + (cport->transmitter_cnt == 0)) { + pjmedia_frame frame; + + /* Clear left-over samples in tx_buffer, if any, so that it won't + * be transmitted next time we have audio signal. + */ + cport->tx_buf_count = 0; + + /* Add sample counts to heart-beat samples */ + cport->tx_heart_beat += conf->samples_per_frame * cport->clock_rate / + conf->clock_rate * + cport->channel_count / conf->channel_count; + + /* Set frame timestamp */ + frame.timestamp.u64 = timestamp->u64 * cport->clock_rate / + conf->clock_rate; + frame.type = PJMEDIA_FRAME_TYPE_NONE; + frame.buf = NULL; + frame.size = 0; + + /* Transmit heart-beat frames (may transmit more than one NULL frame + * if port's ptime is less than bridge's ptime. + */ + if (cport->port && cport->port->put_frame) { + while (cport->tx_heart_beat >= cport->samples_per_frame) { + + pjmedia_port_put_frame(cport->port, &frame); + + cport->tx_heart_beat -= cport->samples_per_frame; + frame.timestamp.u64 += cport->samples_per_frame; + } + } + + cport->tx_level = 0; + *frm_type = PJMEDIA_FRAME_TYPE_NONE; + return PJ_SUCCESS; } /* Reset heart-beat sample count */ @@ -1799,27 +1798,27 @@ static pj_status_t write_port(pjmedia_conf *conf, struct conf_port *cport, tx_level = 0; if (adj_level != NORMAL_LEVEL) { - for (j=0; jsamples_per_frame; ++j) { - pj_int32_t itemp = cport->mix_buf[j]; + for (j=0; jsamples_per_frame; ++j) { + pj_int32_t itemp = cport->mix_buf[j]; - /* Adjust the level */ - /*itemp = itemp * adj_level / NORMAL_LEVEL;*/ - itemp = (itemp * adj_level) >> 7; + /* Adjust the level */ + /*itemp = itemp * adj_level / NORMAL_LEVEL;*/ + itemp = (itemp * adj_level) >> 7; - /* Clip the signal if it's too loud */ - if (itemp > MAX_LEVEL) itemp = MAX_LEVEL; - else if (itemp < MIN_LEVEL) itemp = MIN_LEVEL; + /* Clip the signal if it's too loud */ + if (itemp > MAX_LEVEL) itemp = MAX_LEVEL; + else if (itemp < MIN_LEVEL) itemp = MIN_LEVEL; - /* Put back in the buffer. */ - buf[j] = (pj_int16_t) itemp; + /* Put back in the buffer. */ + buf[j] = (pj_int16_t) itemp; - tx_level += (buf[j]>=0? buf[j] : -buf[j]); - } + tx_level += (buf[j]>=0? buf[j] : -buf[j]); + } } else { - for (j=0; jsamples_per_frame; ++j) { - buf[j] = (pj_int16_t) cport->mix_buf[j]; - tx_level += (buf[j]>=0? buf[j] : -buf[j]); - } + for (j=0; jsamples_per_frame; ++j) { + buf[j] = (pj_int16_t) cport->mix_buf[j]; + tx_level += (buf[j]>=0? buf[j] : -buf[j]); + } } tx_level /= conf->samples_per_frame; @@ -1834,58 +1833,58 @@ static pj_status_t write_port(pjmedia_conf *conf, struct conf_port *cport, * frame as is. */ if (cport->clock_rate == conf->clock_rate && - cport->samples_per_frame == conf->samples_per_frame && - cport->channel_count == conf->channel_count) + cport->samples_per_frame == conf->samples_per_frame && + cport->channel_count == conf->channel_count) { - if (cport->port != NULL) { - pjmedia_frame frame; - - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = buf; - frame.size = conf->samples_per_frame * BYTES_PER_SAMPLE; - /* No need to adjust timestamp, port has the same - * clock rate as conference bridge - */ - frame.timestamp = *timestamp; - - TRACE_((THIS_FILE, "put_frame %.*s, count=%d", - (int)cport->name.slen, cport->name.ptr, - frame.size / BYTES_PER_SAMPLE)); - - return pjmedia_port_put_frame(cport->port, &frame); - } else - return PJ_SUCCESS; + if (cport->port != NULL) { + pjmedia_frame frame; + + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = buf; + frame.size = conf->samples_per_frame * BYTES_PER_SAMPLE; + /* No need to adjust timestamp, port has the same + * clock rate as conference bridge + */ + frame.timestamp = *timestamp; + + TRACE_((THIS_FILE, "put_frame %.*s, count=%d", + (int)cport->name.slen, cport->name.ptr, + frame.size / BYTES_PER_SAMPLE)); + + return pjmedia_port_put_frame(cport->port, &frame); + } else + return PJ_SUCCESS; } /* If it has different clock_rate, must resample. */ if (cport->clock_rate != conf->clock_rate) { - pjmedia_resample_run( cport->tx_resample, buf, - cport->tx_buf + cport->tx_buf_count ); - dst_count = (unsigned)(conf->samples_per_frame * 1.0 * - cport->clock_rate / conf->clock_rate + 0.5); + pjmedia_resample_run( cport->tx_resample, buf, + cport->tx_buf + cport->tx_buf_count ); + dst_count = (unsigned)(conf->samples_per_frame * 1.0 * + cport->clock_rate / conf->clock_rate + 0.5); } else { - /* Same clock rate. - * Just copy the samples to tx_buffer. - */ - pjmedia_copy_samples( cport->tx_buf + cport->tx_buf_count, - buf, conf->samples_per_frame ); - dst_count = conf->samples_per_frame; + /* Same clock rate. + * Just copy the samples to tx_buffer. + */ + pjmedia_copy_samples( cport->tx_buf + cport->tx_buf_count, + buf, conf->samples_per_frame ); + dst_count = conf->samples_per_frame; } /* Adjust channels */ if (cport->channel_count != conf->channel_count) { - pj_int16_t *tx_buf = cport->tx_buf + cport->tx_buf_count; - if (conf->channel_count == 1) { - pjmedia_convert_channel_1ton(tx_buf, tx_buf, - cport->channel_count, - dst_count, 0); - dst_count *= cport->channel_count; - } else { /* cport->channel_count == 1 */ - pjmedia_convert_channel_nto1(tx_buf, tx_buf, - conf->channel_count, - dst_count, PJMEDIA_STEREO_MIX, 0); - dst_count /= conf->channel_count; - } + pj_int16_t *tx_buf = cport->tx_buf + cport->tx_buf_count; + if (conf->channel_count == 1) { + pjmedia_convert_channel_1ton(tx_buf, tx_buf, + cport->channel_count, + dst_count, 0); + dst_count *= cport->channel_count; + } else { /* cport->channel_count == 1 */ + pjmedia_convert_channel_nto1(tx_buf, tx_buf, + conf->channel_count, + dst_count, PJMEDIA_STEREO_MIX, 0); + dst_count /= conf->channel_count; + } } cport->tx_buf_count += dst_count; @@ -1896,47 +1895,47 @@ static pj_status_t write_port(pjmedia_conf *conf, struct conf_port *cport, status = PJ_SUCCESS; ts = 0; while (cport->tx_buf_count >= cport->samples_per_frame && - status == PJ_SUCCESS) + status == PJ_SUCCESS) { - - TRACE_((THIS_FILE, "write_port %.*s: count=%d", - (int)cport->name.slen, cport->name.ptr, - cport->samples_per_frame)); - - if (cport->port) { - pjmedia_frame frame; - - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - frame.buf = cport->tx_buf; - frame.size = cport->samples_per_frame * BYTES_PER_SAMPLE; - /* Adjust timestamp as port may have different clock rate - * than the bridge. - */ - frame.timestamp.u64 = timestamp->u64 * cport->clock_rate / - conf->clock_rate; - - /* Add timestamp for individual frame */ - frame.timestamp.u64 += ts; - ts += cport->samples_per_frame; - - TRACE_((THIS_FILE, "put_frame %.*s, count=%d", - (int)cport->name.slen, cport->name.ptr, - frame.size / BYTES_PER_SAMPLE)); - - status = pjmedia_port_put_frame(cport->port, &frame); - - } else - status = PJ_SUCCESS; - - cport->tx_buf_count -= cport->samples_per_frame; - if (cport->tx_buf_count) { - pjmedia_move_samples(cport->tx_buf, - cport->tx_buf + cport->samples_per_frame, - cport->tx_buf_count); - } - - TRACE_((THIS_FILE, " tx_buf count now is %d", - cport->tx_buf_count)); + + TRACE_((THIS_FILE, "write_port %.*s: count=%d", + (int)cport->name.slen, cport->name.ptr, + cport->samples_per_frame)); + + if (cport->port) { + pjmedia_frame frame; + + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + frame.buf = cport->tx_buf; + frame.size = cport->samples_per_frame * BYTES_PER_SAMPLE; + /* Adjust timestamp as port may have different clock rate + * than the bridge. + */ + frame.timestamp.u64 = timestamp->u64 * cport->clock_rate / + conf->clock_rate; + + /* Add timestamp for individual frame */ + frame.timestamp.u64 += ts; + ts += cport->samples_per_frame; + + TRACE_((THIS_FILE, "put_frame %.*s, count=%d", + (int)cport->name.slen, cport->name.ptr, + frame.size / BYTES_PER_SAMPLE)); + + status = pjmedia_port_put_frame(cport->port, &frame); + + } else + status = PJ_SUCCESS; + + cport->tx_buf_count -= cport->samples_per_frame; + if (cport->tx_buf_count) { + pjmedia_move_samples(cport->tx_buf, + cport->tx_buf + cport->samples_per_frame, + cport->tx_buf_count); + } + + TRACE_((THIS_FILE, " tx_buf count now is %d", + cport->tx_buf_count)); } return status; @@ -1947,7 +1946,7 @@ static pj_status_t write_port(pjmedia_conf *conf, struct conf_port *cport, * Player callback. */ static pj_status_t get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { pjmedia_conf *conf = (pjmedia_conf*) this_port->port_data.pdata; pjmedia_frame_type speaker_frame_type = PJMEDIA_FRAME_TYPE_NONE; @@ -1958,7 +1957,7 @@ static pj_status_t get_frame(pjmedia_port *this_port, /* Check that correct size is specified. */ pj_assert(frame->size == conf->samples_per_frame * - conf->bits_per_sample / 8); + conf->bits_per_sample / 8); /* Must lock mutex */ pj_mutex_lock(conf->mutex); @@ -1967,289 +1966,289 @@ static pj_status_t get_frame(pjmedia_port *this_port, * buffer when we have someone transmitting to it. */ for (i=0, ci=0; imax_ports && ci < conf->port_cnt; ++i) { - struct conf_port *conf_port = conf->ports[i]; - - /* Skip empty port. */ - if (!conf_port) - continue; - - /* Var "ci" is to count how many ports have been visited so far. */ - ++ci; - - /* Reset buffer (only necessary if the port has transmitter) and - * reset auto adjustment level for mixed signal. - */ - conf_port->mix_adj = NORMAL_LEVEL; - if (conf_port->transmitter_cnt) { - pj_bzero(conf_port->mix_buf, - conf->samples_per_frame*sizeof(conf_port->mix_buf[0])); - } + struct conf_port *conf_port = conf->ports[i]; + + /* Skip empty port. */ + if (!conf_port) + continue; + + /* Var "ci" is to count how many ports have been visited so far. */ + ++ci; + + /* Reset buffer (only necessary if the port has transmitter) and + * reset auto adjustment level for mixed signal. + */ + conf_port->mix_adj = NORMAL_LEVEL; + if (conf_port->transmitter_cnt) { + pj_bzero(conf_port->mix_buf, + conf->samples_per_frame*sizeof(conf_port->mix_buf[0])); + } } /* Get frames from all ports, and "mix" the signal * to mix_buf of all listeners of the port. */ for (i=0, ci=0; i < conf->max_ports && ci < conf->port_cnt; ++i) { - struct conf_port *conf_port = conf->ports[i]; - pj_int32_t level = 0; - - /* Skip empty port. */ - if (!conf_port) - continue; - - /* Var "ci" is to count how many ports have been visited so far. */ - ++ci; - - /* Skip if we're not allowed to receive from this port. */ - if (conf_port->rx_setting == PJMEDIA_PORT_DISABLE) { - conf_port->rx_level = 0; - continue; - } - - /* Also skip if this port doesn't have listeners. */ - if (conf_port->listener_cnt == 0) { - conf_port->rx_level = 0; - continue; - } - - /* Get frame from this port. - * For passive ports, get the frame from the delay_buf. - * For other ports, get the frame from the port. - */ - if (conf_port->delay_buf != NULL) { - pj_status_t status; - - status = pjmedia_delay_buf_get(conf_port->delay_buf, - (pj_int16_t*)frame->buf); - if (status != PJ_SUCCESS) { - conf_port->rx_level = 0; - continue; - } - - } else { - - pj_status_t status; - pjmedia_frame_type frame_type; - - status = read_port(conf, conf_port, (pj_int16_t*)frame->buf, - conf->samples_per_frame, &frame_type); - - if (status != PJ_SUCCESS) { - /* bennylp: why do we need this???? - * Also see comments on similar issue with write_port(). - PJ_LOG(4,(THIS_FILE, "Port %.*s get_frame() returned %d. " - "Port is now disabled", - (int)conf_port->name.slen, - conf_port->name.ptr, - status)); - conf_port->rx_setting = PJMEDIA_PORT_DISABLE; - */ - conf_port->rx_level = 0; - continue; - } - - /* Check that the port is not removed when we call get_frame() */ - if (conf->ports[i] == NULL) { - conf_port->rx_level = 0; - continue; - } - - - /* Ignore if we didn't get any frame */ - if (frame_type != PJMEDIA_FRAME_TYPE_AUDIO) { - conf_port->rx_level = 0; - continue; - } - } - - p_in = (pj_int16_t*) frame->buf; - - /* Adjust the RX level from this port - * and calculate the average level at the same time. - */ - if (conf_port->rx_adj_level != NORMAL_LEVEL) { - for (j=0; jsamples_per_frame; ++j) { - /* For the level adjustment, we need to store the sample to - * a temporary 32bit integer value to avoid overflowing the - * 16bit sample storage. - */ - pj_int32_t itemp; - - itemp = p_in[j]; - /*itemp = itemp * adj / NORMAL_LEVEL;*/ - /* bad code (signed/unsigned badness): - * itemp = (itemp * conf_port->rx_adj_level) >> 7; - */ - itemp *= conf_port->rx_adj_level; - itemp >>= 7; - - /* Clip the signal if it's too loud */ - if (itemp > MAX_LEVEL) itemp = MAX_LEVEL; - else if (itemp < MIN_LEVEL) itemp = MIN_LEVEL; - - p_in[j] = (pj_int16_t) itemp; - level += (p_in[j]>=0? p_in[j] : -p_in[j]); - } - } else { - for (j=0; jsamples_per_frame; ++j) { - level += (p_in[j]>=0? p_in[j] : -p_in[j]); - } - } - - level /= conf->samples_per_frame; - - /* Convert level to 8bit complement ulaw */ - level = pjmedia_linear2ulaw(level) ^ 0xff; - - /* Put this level to port's last RX level. */ - conf_port->rx_level = level; - - // Ticket #671: Skipping very low audio signal may cause noise - // to be generated in the remote end by some hardphones. - /* Skip processing frame if level is zero */ - //if (level == 0) - // continue; - - /* Add the signal to all listeners. */ - for (cj=0; cj < conf_port->listener_cnt; ++cj) - { - struct conf_port *listener; - pj_int32_t *mix_buf; - pj_int16_t *p_in_conn_leveled; - - listener = conf->ports[conf_port->listener_slots[cj]]; - - /* Skip if this listener doesn't want to receive audio */ - if (listener->tx_setting != PJMEDIA_PORT_ENABLE) - continue; - - mix_buf = listener->mix_buf; - - /* apply connection level, if not normal */ - if (conf_port->listener_adj_level[cj] != NORMAL_LEVEL) { - unsigned k = 0; - for (; k < conf->samples_per_frame; ++k) { - /* For the level adjustment, we need to store the sample to - * a temporary 32bit integer value to avoid overflowing the - * 16bit sample storage. - */ - pj_int32_t itemp; - - itemp = p_in[k]; - /*itemp = itemp * adj / NORMAL_LEVEL;*/ - /* bad code (signed/unsigned badness): - * itemp = (itemp * conf_port->listsener_adj_level) >> 7; - */ - itemp *= conf_port->listener_adj_level[cj]; - itemp >>= 7; - - /* Clip the signal if it's too loud */ - if (itemp > MAX_LEVEL) itemp = MAX_LEVEL; - else if (itemp < MIN_LEVEL) itemp = MIN_LEVEL; - - conf_port->adj_level_buf[k] = (pj_int16_t)itemp; - } - - /* take the leveled frame */ - p_in_conn_leveled = conf_port->adj_level_buf; - } else { - /* take the frame as-is */ - p_in_conn_leveled = p_in; - } - - if (listener->transmitter_cnt > 1) { - /* Mixing signals, - * and calculate appropriate level adjustment if there is - * any overflowed level in the mixed signal. - */ - unsigned k, samples_per_frame = conf->samples_per_frame; - pj_int32_t mix_buf_min = 0; - pj_int32_t mix_buf_max = 0; - - for (k = 0; k < samples_per_frame; ++k) { - mix_buf[k] += p_in_conn_leveled[k]; - if (mix_buf[k] < mix_buf_min) - mix_buf_min = mix_buf[k]; - if (mix_buf[k] > mix_buf_max) - mix_buf_max = mix_buf[k]; - } - - /* Check if normalization adjustment needed. */ - if (mix_buf_min < MIN_LEVEL || mix_buf_max > MAX_LEVEL) { - int tmp_adj; - - if (-mix_buf_min > mix_buf_max) - mix_buf_max = -mix_buf_min; - - /* NORMAL_LEVEL * MAX_LEVEL / mix_buf_max; */ - tmp_adj = (MAX_LEVEL<<7) / mix_buf_max; - if (tmp_adj < listener->mix_adj) - listener->mix_adj = tmp_adj; - } - } else { - /* Only 1 transmitter: - * just copy the samples to the mix buffer - * no mixing and level adjustment needed - */ - unsigned k, samples_per_frame = conf->samples_per_frame; - - for (k = 0; k < samples_per_frame; ++k) { - mix_buf[k] = p_in_conn_leveled[k]; - } - } - } /* loop the listeners of conf port */ + struct conf_port *conf_port = conf->ports[i]; + pj_int32_t level = 0; + + /* Skip empty port. */ + if (!conf_port) + continue; + + /* Var "ci" is to count how many ports have been visited so far. */ + ++ci; + + /* Skip if we're not allowed to receive from this port. */ + if (conf_port->rx_setting == PJMEDIA_PORT_DISABLE) { + conf_port->rx_level = 0; + continue; + } + + /* Also skip if this port doesn't have listeners. */ + if (conf_port->listener_cnt == 0) { + conf_port->rx_level = 0; + continue; + } + + /* Get frame from this port. + * For passive ports, get the frame from the delay_buf. + * For other ports, get the frame from the port. + */ + if (conf_port->delay_buf != NULL) { + pj_status_t status; + + status = pjmedia_delay_buf_get(conf_port->delay_buf, + (pj_int16_t*)frame->buf); + if (status != PJ_SUCCESS) { + conf_port->rx_level = 0; + continue; + } + + } else { + + pj_status_t status; + pjmedia_frame_type frame_type; + + status = read_port(conf, conf_port, (pj_int16_t*)frame->buf, + conf->samples_per_frame, &frame_type); + + if (status != PJ_SUCCESS) { + /* bennylp: why do we need this???? + * Also see comments on similar issue with write_port(). + PJ_LOG(4,(THIS_FILE, "Port %.*s get_frame() returned %d. " + "Port is now disabled", + (int)conf_port->name.slen, + conf_port->name.ptr, + status)); + conf_port->rx_setting = PJMEDIA_PORT_DISABLE; + */ + conf_port->rx_level = 0; + continue; + } + + /* Check that the port is not removed when we call get_frame() */ + if (conf->ports[i] == NULL) { + conf_port->rx_level = 0; + continue; + } + + + /* Ignore if we didn't get any frame */ + if (frame_type != PJMEDIA_FRAME_TYPE_AUDIO) { + conf_port->rx_level = 0; + continue; + } + } + + p_in = (pj_int16_t*) frame->buf; + + /* Adjust the RX level from this port + * and calculate the average level at the same time. + */ + if (conf_port->rx_adj_level != NORMAL_LEVEL) { + for (j=0; jsamples_per_frame; ++j) { + /* For the level adjustment, we need to store the sample to + * a temporary 32bit integer value to avoid overflowing the + * 16bit sample storage. + */ + pj_int32_t itemp; + + itemp = p_in[j]; + /*itemp = itemp * adj / NORMAL_LEVEL;*/ + /* bad code (signed/unsigned badness): + * itemp = (itemp * conf_port->rx_adj_level) >> 7; + */ + itemp *= conf_port->rx_adj_level; + itemp >>= 7; + + /* Clip the signal if it's too loud */ + if (itemp > MAX_LEVEL) itemp = MAX_LEVEL; + else if (itemp < MIN_LEVEL) itemp = MIN_LEVEL; + + p_in[j] = (pj_int16_t) itemp; + level += (p_in[j]>=0? p_in[j] : -p_in[j]); + } + } else { + for (j=0; jsamples_per_frame; ++j) { + level += (p_in[j]>=0? p_in[j] : -p_in[j]); + } + } + + level /= conf->samples_per_frame; + + /* Convert level to 8bit complement ulaw */ + level = pjmedia_linear2ulaw(level) ^ 0xff; + + /* Put this level to port's last RX level. */ + conf_port->rx_level = level; + + // Ticket #671: Skipping very low audio signal may cause noise + // to be generated in the remote end by some hardphones. + /* Skip processing frame if level is zero */ + //if (level == 0) + // continue; + + /* Add the signal to all listeners. */ + for (cj=0; cj < conf_port->listener_cnt; ++cj) + { + struct conf_port *listener; + pj_int32_t *mix_buf; + pj_int16_t *p_in_conn_leveled; + + listener = conf->ports[conf_port->listener_slots[cj]]; + + /* Skip if this listener doesn't want to receive audio */ + if (listener->tx_setting != PJMEDIA_PORT_ENABLE) + continue; + + mix_buf = listener->mix_buf; + + /* apply connection level, if not normal */ + if (conf_port->listener_adj_level[cj] != NORMAL_LEVEL) { + unsigned k = 0; + for (; k < conf->samples_per_frame; ++k) { + /* For the level adjustment, we need to store the sample to + * a temporary 32bit integer value to avoid overflowing the + * 16bit sample storage. + */ + pj_int32_t itemp; + + itemp = p_in[k]; + /*itemp = itemp * adj / NORMAL_LEVEL;*/ + /* bad code (signed/unsigned badness): + * itemp = (itemp * conf_port->listsener_adj_level) >> 7; + */ + itemp *= conf_port->listener_adj_level[cj]; + itemp >>= 7; + + /* Clip the signal if it's too loud */ + if (itemp > MAX_LEVEL) itemp = MAX_LEVEL; + else if (itemp < MIN_LEVEL) itemp = MIN_LEVEL; + + conf_port->adj_level_buf[k] = (pj_int16_t)itemp; + } + + /* take the leveled frame */ + p_in_conn_leveled = conf_port->adj_level_buf; + } else { + /* take the frame as-is */ + p_in_conn_leveled = p_in; + } + + if (listener->transmitter_cnt > 1) { + /* Mixing signals, + * and calculate appropriate level adjustment if there is + * any overflowed level in the mixed signal. + */ + unsigned k, samples_per_frame = conf->samples_per_frame; + pj_int32_t mix_buf_min = 0; + pj_int32_t mix_buf_max = 0; + + for (k = 0; k < samples_per_frame; ++k) { + mix_buf[k] += p_in_conn_leveled[k]; + if (mix_buf[k] < mix_buf_min) + mix_buf_min = mix_buf[k]; + if (mix_buf[k] > mix_buf_max) + mix_buf_max = mix_buf[k]; + } + + /* Check if normalization adjustment needed. */ + if (mix_buf_min < MIN_LEVEL || mix_buf_max > MAX_LEVEL) { + int tmp_adj; + + if (-mix_buf_min > mix_buf_max) + mix_buf_max = -mix_buf_min; + + /* NORMAL_LEVEL * MAX_LEVEL / mix_buf_max; */ + tmp_adj = (MAX_LEVEL<<7) / mix_buf_max; + if (tmp_adj < listener->mix_adj) + listener->mix_adj = tmp_adj; + } + } else { + /* Only 1 transmitter: + * just copy the samples to the mix buffer + * no mixing and level adjustment needed + */ + unsigned k, samples_per_frame = conf->samples_per_frame; + + for (k = 0; k < samples_per_frame; ++k) { + mix_buf[k] = p_in_conn_leveled[k]; + } + } + } /* loop the listeners of conf port */ } /* loop of all conf ports */ /* Time for all ports to transmit whetever they have in their * buffer. */ for (i=0, ci=0; imax_ports && ciport_cnt; ++i) { - struct conf_port *conf_port = conf->ports[i]; - pjmedia_frame_type frm_type; - pj_status_t status; - - if (!conf_port) - continue; - - /* Var "ci" is to count how many ports have been visited. */ - ++ci; - - status = write_port( conf, conf_port, &frame->timestamp, - &frm_type); - if (status != PJ_SUCCESS) { - /* bennylp: why do we need this???? - One thing for sure, put_frame()/write_port() may return - non-successfull status on Win32 if there's temporary glitch - on network interface, so disabling the port here does not - sound like a good idea. - - PJ_LOG(4,(THIS_FILE, "Port %.*s put_frame() returned %d. " - "Port is now disabled", - (int)conf_port->name.slen, - conf_port->name.ptr, - status)); - conf_port->tx_setting = PJMEDIA_PORT_DISABLE; - */ - continue; - } - - /* Set the type of frame to be returned to sound playback - * device. - */ - if (i == 0) - speaker_frame_type = frm_type; + struct conf_port *conf_port = conf->ports[i]; + pjmedia_frame_type frm_type; + pj_status_t status; + + if (!conf_port) + continue; + + /* Var "ci" is to count how many ports have been visited. */ + ++ci; + + status = write_port( conf, conf_port, &frame->timestamp, + &frm_type); + if (status != PJ_SUCCESS) { + /* bennylp: why do we need this???? + One thing for sure, put_frame()/write_port() may return + non-successfull status on Win32 if there's temporary glitch + on network interface, so disabling the port here does not + sound like a good idea. + + PJ_LOG(4,(THIS_FILE, "Port %.*s put_frame() returned %d. " + "Port is now disabled", + (int)conf_port->name.slen, + conf_port->name.ptr, + status)); + conf_port->tx_setting = PJMEDIA_PORT_DISABLE; + */ + continue; + } + + /* Set the type of frame to be returned to sound playback + * device. + */ + if (i == 0) + speaker_frame_type = frm_type; } /* Return sound playback frame. */ if (conf->ports[0]->tx_level) { - TRACE_((THIS_FILE, "write to audio, count=%d", - conf->samples_per_frame)); - pjmedia_copy_samples( (pj_int16_t*)frame->buf, - (const pj_int16_t*)conf->ports[0]->mix_buf, - conf->samples_per_frame); + TRACE_((THIS_FILE, "write to audio, count=%d", + conf->samples_per_frame)); + pjmedia_copy_samples( (pj_int16_t*)frame->buf, + (const pj_int16_t*)conf->ports[0]->mix_buf, + conf->samples_per_frame); } else { - /* Force frame type NONE */ - speaker_frame_type = PJMEDIA_FRAME_TYPE_NONE; + /* Force frame type NONE */ + speaker_frame_type = PJMEDIA_FRAME_TYPE_NONE; } /* MUST set frame type */ @@ -2259,9 +2258,9 @@ static pj_status_t get_frame(pjmedia_port *this_port, #ifdef REC_FILE if (fhnd_rec == NULL) - fhnd_rec = fopen(REC_FILE, "wb"); + fhnd_rec = fopen(REC_FILE, "wb"); if (fhnd_rec) - fwrite(frame->buf, frame->size, 1, fhnd_rec); + fwrite(frame->buf, frame->size, 1, fhnd_rec); #endif return PJ_SUCCESS; @@ -2273,7 +2272,7 @@ static pj_status_t get_frame(pjmedia_port *this_port, * get_frame() for passive port */ static pj_status_t get_frame_pasv(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { pj_assert(0); PJ_UNUSED_ARG(this_port); @@ -2287,7 +2286,7 @@ static pj_status_t get_frame_pasv(pjmedia_port *this_port, * Recorder (or passive port) callback. */ static pj_status_t put_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { pjmedia_conf *conf = (pjmedia_conf*) this_port->port_data.pdata; struct conf_port *port = conf->ports[this_port->port_data.ldata]; @@ -2295,20 +2294,20 @@ static pj_status_t put_frame(pjmedia_port *this_port, /* Check for correct size. */ PJ_ASSERT_RETURN( frame->size == conf->samples_per_frame * - conf->bits_per_sample / 8, - PJMEDIA_ENCSAMPLESPFRAME); + conf->bits_per_sample / 8, + PJMEDIA_ENCSAMPLESPFRAME); /* Check existance of delay_buf instance */ PJ_ASSERT_RETURN( port->delay_buf, PJ_EBUG ); /* Skip if this port is muted/disabled. */ if (port->rx_setting != PJMEDIA_PORT_ENABLE) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Skip if no port is listening to the microphone */ if (port->listener_cnt == 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } status = pjmedia_delay_buf_put(port->delay_buf, (pj_int16_t*)frame->buf); diff --git a/pjmedia/src/pjmedia/converter.c b/pjmedia/src/pjmedia/converter.c index bff5d9ed1e..cb20300e2b 100644 --- a/pjmedia/src/pjmedia/converter.c +++ b/pjmedia/src/pjmedia/converter.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * @@ -20,7 +19,7 @@ #include #include -#define THIS_FILE "converter.c" +#define THIS_FILE "converter.c" struct pjmedia_converter_mgr { @@ -42,7 +41,7 @@ pjmedia_libyuv_converter_init(pjmedia_converter_mgr *mgr); #endif PJ_DEF(pj_status_t) pjmedia_converter_mgr_create(pj_pool_t *pool, - pjmedia_converter_mgr **p_mgr) + pjmedia_converter_mgr **p_mgr) { pjmedia_converter_mgr *mgr; pj_status_t status = PJ_SUCCESS; @@ -51,14 +50,14 @@ PJ_DEF(pj_status_t) pjmedia_converter_mgr_create(pj_pool_t *pool, pj_list_init(&mgr->factory_list); if (!converter_manager_instance) - converter_manager_instance = mgr; + converter_manager_instance = mgr; #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) && \ defined(PJMEDIA_HAS_LIBSWSCALE) && (PJMEDIA_HAS_LIBSWSCALE != 0) status = pjmedia_libswscale_converter_init(mgr); if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Error initializing libswscale converter")); + PJ_PERROR(4,(THIS_FILE, status, + "Error initializing libswscale converter")); } #endif @@ -66,13 +65,13 @@ PJ_DEF(pj_status_t) pjmedia_converter_mgr_create(pj_pool_t *pool, defined(PJMEDIA_HAS_LIBYUV) && (PJMEDIA_HAS_LIBYUV != 0) status = pjmedia_libyuv_converter_init(mgr); if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Error initializing libyuv converter")); + PJ_PERROR(4,(THIS_FILE, status, + "Error initializing libyuv converter")); } #endif if (p_mgr) - *p_mgr = mgr; + *p_mgr = mgr; return status; } @@ -98,19 +97,19 @@ PJ_DEF(void) pjmedia_converter_mgr_destroy(pjmedia_converter_mgr *mgr) f = mgr->factory_list.next; while (f != &mgr->factory_list) { - pjmedia_converter_factory *next = f->next; - pj_list_erase(f); - (*f->op->destroy_factory)(f); - f = next; + pjmedia_converter_factory *next = f->next; + pj_list_erase(f); + (*f->op->destroy_factory)(f); + f = next; } if (converter_manager_instance == mgr) - converter_manager_instance = NULL; + converter_manager_instance = NULL; } PJ_DEF(pj_status_t) pjmedia_converter_mgr_register_factory(pjmedia_converter_mgr *mgr, - pjmedia_converter_factory *factory) + pjmedia_converter_factory *factory) { pjmedia_converter_factory *pf; @@ -119,13 +118,13 @@ pjmedia_converter_mgr_register_factory(pjmedia_converter_mgr *mgr, PJ_ASSERT_RETURN(mgr != NULL, PJ_EINVAL); PJ_ASSERT_RETURN(!pj_list_find_node(&mgr->factory_list, factory), - PJ_EEXISTS); + PJ_EEXISTS); pf = mgr->factory_list.next; while (pf != &mgr->factory_list) { - if (pf->priority > factory->priority) - break; - pf = pf->next; + if (pf->priority > factory->priority) + break; + pf = pf->next; } pj_list_insert_before(pf, factory); return PJ_SUCCESS; @@ -134,8 +133,8 @@ pjmedia_converter_mgr_register_factory(pjmedia_converter_mgr *mgr, PJ_DEF(pj_status_t) pjmedia_converter_mgr_unregister_factory(pjmedia_converter_mgr *mgr, - pjmedia_converter_factory *f, - pj_bool_t destroy) + pjmedia_converter_factory *f, + pj_bool_t destroy) { if (!mgr) mgr = pjmedia_converter_mgr_instance(); @@ -144,14 +143,14 @@ pjmedia_converter_mgr_unregister_factory(pjmedia_converter_mgr *mgr, PJ_ASSERT_RETURN(pj_list_find_node(&mgr->factory_list, f), PJ_ENOTFOUND); pj_list_erase(f); if (destroy) - (*f->op->destroy_factory)(f); + (*f->op->destroy_factory)(f); return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_converter_create(pjmedia_converter_mgr *mgr, - pj_pool_t *pool, - pjmedia_conversion_param *param, - pjmedia_converter **p_cv) + pj_pool_t *pool, + pjmedia_conversion_param *param, + pjmedia_converter **p_cv) { pjmedia_converter_factory *f; pjmedia_converter *cv = NULL; @@ -165,14 +164,14 @@ PJ_DEF(pj_status_t) pjmedia_converter_create(pjmedia_converter_mgr *mgr, f = mgr->factory_list.next; while (f != &mgr->factory_list) { - status = (*f->op->create_converter)(f, pool, param, &cv); - if (status == PJ_SUCCESS) - break; - f = f->next; + status = (*f->op->create_converter)(f, pool, param, &cv); + if (status == PJ_SUCCESS) + break; + f = f->next; } if (status != PJ_SUCCESS) - return status; + return status; *p_cv = cv; @@ -180,8 +179,8 @@ PJ_DEF(pj_status_t) pjmedia_converter_create(pjmedia_converter_mgr *mgr, } PJ_DEF(pj_status_t) pjmedia_converter_convert(pjmedia_converter *cv, - pjmedia_frame *src_frame, - pjmedia_frame *dst_frame) + pjmedia_frame *src_frame, + pjmedia_frame *dst_frame) { return (*cv->op->convert)(cv, src_frame, dst_frame); } @@ -192,19 +191,19 @@ PJ_DEF(void) pjmedia_converter_destroy(pjmedia_converter *cv) } PJ_DEF(pj_status_t) pjmedia_converter_convert2( - pjmedia_converter *cv, - pjmedia_frame *src_frame, - const pjmedia_rect_size *src_frame_size, - const pjmedia_coord *src_pos, - pjmedia_frame *dst_frame, - const pjmedia_rect_size *dst_frame_size, - const pjmedia_coord *dst_pos, - void *param) + pjmedia_converter *cv, + pjmedia_frame *src_frame, + const pjmedia_rect_size *src_frame_size, + const pjmedia_coord *src_pos, + pjmedia_frame *dst_frame, + const pjmedia_rect_size *dst_frame_size, + const pjmedia_coord *dst_pos, + void *param) { if (!cv->op->convert2) - return PJ_ENOTSUP; + return PJ_ENOTSUP; return (*cv->op->convert2)(cv, src_frame, src_frame_size, src_pos, - dst_frame, dst_frame_size, dst_pos, param); + dst_frame, dst_frame_size, dst_pos, param); } diff --git a/pjmedia/src/pjmedia/converter_libswscale.c b/pjmedia/src/pjmedia/converter_libswscale.c index dc61b966ec..3f053adae8 100644 --- a/pjmedia/src/pjmedia/converter_libswscale.c +++ b/pjmedia/src/pjmedia/converter_libswscale.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * @@ -26,38 +25,38 @@ #include static pj_status_t factory_create_converter(pjmedia_converter_factory *cf, - pj_pool_t *pool, - const pjmedia_conversion_param*prm, - pjmedia_converter **p_cv); + pj_pool_t *pool, + const pjmedia_conversion_param*prm, + pjmedia_converter **p_cv); static void factory_destroy_factory(pjmedia_converter_factory *cf); static pj_status_t libswscale_conv_convert(pjmedia_converter *converter, - pjmedia_frame *src_frame, - pjmedia_frame *dst_frame); + pjmedia_frame *src_frame, + pjmedia_frame *dst_frame); static pj_status_t libswscale_conv_convert2( - pjmedia_converter *converter, - pjmedia_frame *src_frame, - const pjmedia_rect_size *src_frame_size, - const pjmedia_coord *src_pos, - pjmedia_frame *dst_frame, - const pjmedia_rect_size *dst_frame_size, - const pjmedia_coord *dst_pos, - pjmedia_converter_convert_setting - *param); + pjmedia_converter *converter, + pjmedia_frame *src_frame, + const pjmedia_rect_size *src_frame_size, + const pjmedia_coord *src_pos, + pjmedia_frame *dst_frame, + const pjmedia_rect_size *dst_frame_size, + const pjmedia_coord *dst_pos, + pjmedia_converter_convert_setting + *param); static void libswscale_conv_destroy(pjmedia_converter *converter); struct fmt_info { - const pjmedia_video_format_info *fmt_info; - pjmedia_video_apply_fmt_param apply_param; + const pjmedia_video_format_info *fmt_info; + pjmedia_video_apply_fmt_param apply_param; }; struct ffmpeg_converter { - pjmedia_converter base; - struct SwsContext *sws_ctx; - struct fmt_info src, - dst; + pjmedia_converter base; + struct SwsContext *sws_ctx; + struct fmt_info src, + dst; }; static pjmedia_converter_factory_op libswscale_factory_op = @@ -74,9 +73,9 @@ static pjmedia_converter_op liswscale_converter_op = }; static pj_status_t factory_create_converter(pjmedia_converter_factory *cf, - pj_pool_t *pool, - const pjmedia_conversion_param *prm, - pjmedia_converter **p_cv) + pj_pool_t *pool, + const pjmedia_conversion_param *prm, + pjmedia_converter **p_cv) { enum AVPixelFormat srcFormat, dstFormat; const pjmedia_video_format_detail *src_detail, *dst_detail; @@ -89,44 +88,44 @@ static pj_status_t factory_create_converter(pjmedia_converter_factory *cf, /* Only supports video */ if (prm->src.type != PJMEDIA_TYPE_VIDEO || - prm->dst.type != prm->src.type || - prm->src.detail_type != PJMEDIA_FORMAT_DETAIL_VIDEO || - prm->dst.detail_type != prm->src.detail_type) + prm->dst.type != prm->src.type || + prm->src.detail_type != PJMEDIA_FORMAT_DETAIL_VIDEO || + prm->dst.detail_type != prm->src.detail_type) { - return PJ_ENOTSUP; + return PJ_ENOTSUP; } /* lookup source format info */ src_fmt_info = pjmedia_get_video_format_info( - pjmedia_video_format_mgr_instance(), - prm->src.id); + pjmedia_video_format_mgr_instance(), + prm->src.id); if (!src_fmt_info) - return PJ_ENOTSUP; + return PJ_ENOTSUP; /* lookup destination format info */ dst_fmt_info = pjmedia_get_video_format_info( - pjmedia_video_format_mgr_instance(), - prm->dst.id); + pjmedia_video_format_mgr_instance(), + prm->dst.id); if (!dst_fmt_info) - return PJ_ENOTSUP; + return PJ_ENOTSUP; src_detail = pjmedia_format_get_video_format_detail(&prm->src, PJ_TRUE); dst_detail = pjmedia_format_get_video_format_detail(&prm->dst, PJ_TRUE); status = pjmedia_format_id_to_PixelFormat(prm->src.id, &srcFormat); if (status != PJ_SUCCESS) - return PJ_ENOTSUP; + return PJ_ENOTSUP; status = pjmedia_format_id_to_PixelFormat(prm->dst.id, &dstFormat); if (status != PJ_SUCCESS) - return PJ_ENOTSUP; + return PJ_ENOTSUP; sws_ctx = sws_getContext(src_detail->size.w, src_detail->size.h, srcFormat, - dst_detail->size.w, dst_detail->size.h, dstFormat, - SWS_BICUBIC, - NULL, NULL, NULL); + dst_detail->size.w, dst_detail->size.h, dstFormat, + SWS_BICUBIC, + NULL, NULL, NULL); if (sws_ctx == NULL) - return PJ_ENOTSUP; + return PJ_ENOTSUP; fcv = PJ_POOL_ZALLOC_T(pool, struct ffmpeg_converter); fcv->base.op = &liswscale_converter_op; @@ -147,12 +146,12 @@ static void factory_destroy_factory(pjmedia_converter_factory *cf) } static pj_status_t libswscale_conv_convert(pjmedia_converter *converter, - pjmedia_frame *src_frame, - pjmedia_frame *dst_frame) + pjmedia_frame *src_frame, + pjmedia_frame *dst_frame) { struct ffmpeg_converter *fcv = (struct ffmpeg_converter*)converter; struct fmt_info *src = &fcv->src, - *dst = &fcv->dst; + *dst = &fcv->dst; int h; src->apply_param.buffer = src_frame->buf; @@ -162,10 +161,10 @@ static pj_status_t libswscale_conv_convert(pjmedia_converter *converter, (*dst->fmt_info->apply_fmt)(dst->fmt_info, &dst->apply_param); h = sws_scale(fcv->sws_ctx, - (const uint8_t* const *)src->apply_param.planes, - src->apply_param.strides, - 0, src->apply_param.size.h, - dst->apply_param.planes, dst->apply_param.strides); + (const uint8_t* const *)src->apply_param.planes, + src->apply_param.strides, + 0, src->apply_param.size.h, + dst->apply_param.planes, dst->apply_param.strides); //sws_scale() return value can't be trusted? There are cases when //sws_scale() returns zero but conversion seems to work okay. @@ -176,19 +175,19 @@ static pj_status_t libswscale_conv_convert(pjmedia_converter *converter, } static pj_status_t libswscale_conv_convert2( - pjmedia_converter *converter, - pjmedia_frame *src_frame, - const pjmedia_rect_size *src_frame_size, - const pjmedia_coord *src_pos, - pjmedia_frame *dst_frame, - const pjmedia_rect_size *dst_frame_size, - const pjmedia_coord *dst_pos, - pjmedia_converter_convert_setting - *param) + pjmedia_converter *converter, + pjmedia_frame *src_frame, + const pjmedia_rect_size *src_frame_size, + const pjmedia_coord *src_pos, + pjmedia_frame *dst_frame, + const pjmedia_rect_size *dst_frame_size, + const pjmedia_coord *dst_pos, + pjmedia_converter_convert_setting + *param) { struct ffmpeg_converter *fcv = (struct ffmpeg_converter*)converter; struct fmt_info *src = &fcv->src, - *dst = &fcv->dst; + *dst = &fcv->dst; int h; unsigned j; pjmedia_rect_size orig_src_size; @@ -211,19 +210,19 @@ static pj_status_t libswscale_conv_convert2( (*dst->fmt_info->apply_fmt)(dst->fmt_info, &dst->apply_param); for (j = 0; j < src->fmt_info->plane_cnt; ++j) { - pjmedia_video_apply_fmt_param *ap = &src->apply_param; - int y = src_pos->y * ap->plane_bytes[j] / ap->strides[j] / - ap->size.h; - ap->planes[j] += y * ap->strides[j] + - src_pos->x * ap->strides[j] / ap->size.w; + pjmedia_video_apply_fmt_param *ap = &src->apply_param; + int y = src_pos->y * ap->plane_bytes[j] / ap->strides[j] / + ap->size.h; + ap->planes[j] += y * ap->strides[j] + + src_pos->x * ap->strides[j] / ap->size.w; } for (j = 0; j < dst->fmt_info->plane_cnt; ++j) { - pjmedia_video_apply_fmt_param *ap = &dst->apply_param; - int y = dst_pos->y * ap->plane_bytes[j] / ap->strides[j] / - ap->size.h; - ap->planes[j] += y * ap->strides[j] + - dst_pos->x * ap->strides[j] / ap->size.w; + pjmedia_video_apply_fmt_param *ap = &dst->apply_param; + int y = dst_pos->y * ap->plane_bytes[j] / ap->strides[j] / + ap->size.h; + ap->planes[j] += y * ap->strides[j] + + dst_pos->x * ap->strides[j] / ap->size.w; } /* Return back the original conversion size */ @@ -231,10 +230,10 @@ static pj_status_t libswscale_conv_convert2( dst->apply_param.size = orig_dst_size; h = sws_scale(fcv->sws_ctx, - (const uint8_t* const *)src->apply_param.planes, - src->apply_param.strides, - 0, src->apply_param.size.h, - dst->apply_param.planes, dst->apply_param.strides); + (const uint8_t* const *)src->apply_param.planes, + src->apply_param.strides, + 0, src->apply_param.size.h, + dst->apply_param.planes, dst->apply_param.strides); //sws_scale() return value can't be trusted? There are cases when //sws_scale() returns zero but conversion seems to work okay. @@ -248,18 +247,18 @@ static void libswscale_conv_destroy(pjmedia_converter *converter) { struct ffmpeg_converter *fcv = (struct ffmpeg_converter*)converter; if (fcv->sws_ctx) { - struct SwsContext *tmp = fcv->sws_ctx; - fcv->sws_ctx = NULL; - sws_freeContext(tmp); + struct SwsContext *tmp = fcv->sws_ctx; + fcv->sws_ctx = NULL; + sws_freeContext(tmp); } } static pjmedia_converter_factory libswscale_factory = { - NULL, NULL, /* list */ - "libswscale", /* name */ - PJMEDIA_CONVERTER_PRIORITY_NORMAL+1, /* priority */ - NULL /* op will be init-ed later */ + NULL, NULL, /* list */ + "libswscale", /* name */ + PJMEDIA_CONVERTER_PRIORITY_NORMAL+1, /* priority */ + NULL /* op will be init-ed later */ }; PJ_DEF(pj_status_t) @@ -273,12 +272,12 @@ pjmedia_libswscale_converter_init(pjmedia_converter_mgr *mgr) PJ_DEF(pj_status_t) pjmedia_libswscale_converter_shutdown(pjmedia_converter_mgr *mgr, - pj_pool_t *pool) + pj_pool_t *pool) { PJ_UNUSED_ARG(pool); pjmedia_ffmpeg_dec_ref(); return pjmedia_converter_mgr_unregister_factory(mgr, &libswscale_factory, - PJ_TRUE); + PJ_TRUE); } #ifdef _MSC_VER diff --git a/pjmedia/src/pjmedia/converter_libyuv.c b/pjmedia/src/pjmedia/converter_libyuv.c index 8155f26742..e3587cf4d2 100644 --- a/pjmedia/src/pjmedia/converter_libyuv.c +++ b/pjmedia/src/pjmedia/converter_libyuv.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * @@ -26,25 +25,25 @@ #include static pj_status_t factory_create_converter(pjmedia_converter_factory *cf, - pj_pool_t *pool, - const pjmedia_conversion_param*prm, - pjmedia_converter **p_cv); + pj_pool_t *pool, + const pjmedia_conversion_param*prm, + pjmedia_converter **p_cv); static void factory_destroy_factory(pjmedia_converter_factory *cf); static pj_status_t libyuv_conv_convert(pjmedia_converter *converter, - pjmedia_frame *src_frame, - pjmedia_frame *dst_frame); + pjmedia_frame *src_frame, + pjmedia_frame *dst_frame); static pj_status_t libyuv_conv_convert2( - pjmedia_converter *converter, - pjmedia_frame *src_frame, - const pjmedia_rect_size *src_frame_size, - const pjmedia_coord *src_pos, - pjmedia_frame *dst_frame, - const pjmedia_rect_size *dst_frame_size, - const pjmedia_coord *dst_pos, - void *param); + pjmedia_converter *converter, + pjmedia_frame *src_frame, + const pjmedia_rect_size *src_frame_size, + const pjmedia_coord *src_pos, + pjmedia_frame *dst_frame, + const pjmedia_rect_size *dst_frame_size, + const pjmedia_coord *dst_pos, + void *param); static void libyuv_conv_destroy(pjmedia_converter *converter); @@ -63,8 +62,8 @@ static pjmedia_converter_op libyuv_converter_op = typedef struct fmt_info { - const pjmedia_video_format_info *vid_fmt_info; - pjmedia_video_apply_fmt_param apply_param; + const pjmedia_video_format_info *vid_fmt_info; + pjmedia_video_apply_fmt_param apply_param; } fmt_info; typedef enum conv_func_type @@ -80,38 +79,38 @@ typedef enum conv_func_type typedef void (*gen_conv_func)(); typedef int (*conv_pack_to_pack_method)(const uint8* src, int src_stride, - uint8* dst, int dst_stride, - int width, int height); + uint8* dst, int dst_stride, + int width, int height); typedef int (*conv_pack_to_planar_method)(const uint8* src, int src_stride, - uint8* dst1, int dst_stride1, - uint8* dst2, int dst_stride2, - uint8* dst3, int dst_stride3, - int width, int height); + uint8* dst1, int dst_stride1, + uint8* dst2, int dst_stride2, + uint8* dst3, int dst_stride3, + int width, int height); typedef int (*conv_planar_to_pack_method)(const uint8* src1, int src_stride1, - const uint8* src2, int src_stride2, - const uint8* src3, int src_stride3, - uint8* dst, int dst_stride, - int width, int height); + const uint8* src2, int src_stride2, + const uint8* src3, int src_stride3, + uint8* dst, int dst_stride, + int width, int height); typedef int (*conv_planar_to_planar_method)(const uint8* src1, int src_stride1, - const uint8* src2, int src_stride2, - const uint8* src3, int src_stride3, - uint8* dst1, int dst_stride1, - uint8* dst2, int dst_stride2, - uint8* dst3, int dst_stride3, - int width, int height); + const uint8* src2, int src_stride2, + const uint8* src3, int src_stride3, + uint8* dst1, int dst_stride1, + uint8* dst2, int dst_stride2, + uint8* dst3, int dst_stride3, + int width, int height); typedef int (*scale_pack_method) - (const uint8* src_argb, int src_stride_argb, + (const uint8* src_argb, int src_stride_argb, int src_width, int src_height, uint8* dst_argb, int dst_stride_argb, int dst_width, int dst_height, enum FilterMode filtering); -typedef int (*scale_planar_method) - (const uint8* src_y, int src_stride_y, +typedef int (*scale_planar_method) + (const uint8* src_y, int src_stride_y, const uint8* src_u, int src_stride_u, const uint8* src_v, int src_stride_v, int src_width, int src_height, @@ -123,19 +122,19 @@ typedef int (*scale_planar_method) typedef union act_method { - conv_pack_to_pack_method conv_pack_to_pack; - conv_pack_to_planar_method conv_pack_to_planar; - conv_planar_to_pack_method conv_planar_to_pack; + conv_pack_to_pack_method conv_pack_to_pack; + conv_pack_to_planar_method conv_pack_to_planar; + conv_planar_to_pack_method conv_planar_to_pack; conv_planar_to_planar_method conv_planar_to_planar; - scale_pack_method scale_pack; - scale_planar_method scale_planar; + scale_pack_method scale_pack; + scale_planar_method scale_planar; } act_method; typedef struct fmt_convert_map { - pj_uint32_t src_id; - pj_uint32_t dst_id; - conv_func_type func_type; - gen_conv_func conv_func; + pj_uint32_t src_id; + pj_uint32_t dst_id; + conv_func_type func_type; + gen_conv_func conv_func; } fmt_convert_map; /* Maximum number of steps/act needed for the conversion/scale process. */ @@ -213,26 +212,26 @@ static fmt_convert_map conv_from_bgra[] = typedef struct converter_act { - conv_func_type act_type; - struct fmt_info src_fmt_info; - struct fmt_info dst_fmt_info; - act_method method; + conv_func_type act_type; + struct fmt_info src_fmt_info; + struct fmt_info dst_fmt_info; + act_method method; } converter_act; struct libyuv_converter { - pjmedia_converter base; - int act_num; - converter_act act[MAXIMUM_ACT]; + pjmedia_converter base; + int act_num; + converter_act act[MAXIMUM_ACT]; }; /* Find the matched format conversion map. */ static pj_status_t get_converter_map(pj_uint32_t src_id, - pj_uint32_t dst_id, - const pjmedia_rect_size *src_size, - const pjmedia_rect_size *dst_size, - int act_num, - converter_act *act) + pj_uint32_t dst_id, + const pjmedia_rect_size *src_size, + const pjmedia_rect_size *dst_size, + int act_num, + converter_act *act) { fmt_convert_map *map = NULL; unsigned cnt = 0, i = 0; @@ -240,82 +239,82 @@ static pj_status_t get_converter_map(pj_uint32_t src_id, # define GET_MAP(src) \ do { \ - map=src; \ - cnt=PJ_ARRAY_SIZE(src); \ + map=src; \ + cnt=PJ_ARRAY_SIZE(src); \ }while(0) if (src_id == PJMEDIA_FORMAT_I420) { - GET_MAP(conv_from_i420); + GET_MAP(conv_from_i420); } else if (src_id == PJMEDIA_FORMAT_BGRA) { - GET_MAP(conv_from_bgra); + GET_MAP(conv_from_bgra); } if (!map) { - if (dst_id == PJMEDIA_FORMAT_I420) { - GET_MAP(conv_to_i420); - } else if (dst_id == PJMEDIA_FORMAT_BGRA) { - GET_MAP(conv_to_bgra); - } + if (dst_id == PJMEDIA_FORMAT_I420) { + GET_MAP(conv_to_i420); + } else if (dst_id == PJMEDIA_FORMAT_BGRA) { + GET_MAP(conv_to_bgra); + } } if (!map) - return PJ_ENOTSUP; + return PJ_ENOTSUP; for (;icolor_model == PJMEDIA_COLOR_MODEL_YUV) { - return PJMEDIA_FORMAT_I420; + return PJMEDIA_FORMAT_I420; } else { - return PJMEDIA_FORMAT_BGRA; + return PJMEDIA_FORMAT_BGRA; } } @@ -342,15 +341,15 @@ static pjmedia_format_id get_next_conv_fmt(pj_uint32_t src_id) { * More than one step might be needed, since not all format is provided with * a direct conversion/scale method. * e.g : Scale YUY2 (240*320) to YUY2 (320*720) - * - Step 1: Convert YUY2(240*320) to I420 (240*320) - * - Step 2: Scale I420 (320*760) - * - Step 3: Convert I420 (320*760) to YUY2 (320*760) + * - Step 1: Convert YUY2(240*320) to I420 (240*320) + * - Step 2: Scale I420 (320*760) + * - Step 3: Convert I420 (320*760) to YUY2 (320*760) */ static int set_converter_act(pj_uint32_t src_id, - pj_uint32_t dst_id, - const pjmedia_rect_size *src_size, - const pjmedia_rect_size *dst_size, - converter_act *act) + pj_uint32_t dst_id, + const pjmedia_rect_size *src_size, + const pjmedia_rect_size *dst_size, + converter_act *act) { unsigned act_num = 0; pj_uint32_t current_id = src_id; @@ -358,27 +357,27 @@ static int set_converter_act(pj_uint32_t src_id, /* Convert to I420 or BGRA if needed. */ if ((src_id != PJMEDIA_FORMAT_I420) && (src_id != PJMEDIA_FORMAT_BGRA)) { - pj_uint32_t next_id = get_next_conv_fmt(src_id); + pj_uint32_t next_id = get_next_conv_fmt(src_id); if (get_converter_map(src_id, next_id, src_size, dst_size, ++act_num, act) != PJ_SUCCESS) { - return 0; - } - - current_id = next_id; + return 0; + } + + current_id = next_id; } /* Scale if needed */ //need_scale = ((src_size->w != dst_size->w) || - //(src_size->h != dst_size->h)); + //(src_size->h != dst_size->h)); // Always enable scale, as this can be used for rendering a region of // a frame to another region of similar/another frame. need_scale = PJ_TRUE; if (need_scale) { - if (get_converter_map(current_id, current_id, src_size, dst_size, - ++act_num, act) != PJ_SUCCESS) + if (get_converter_map(current_id, current_id, src_size, dst_size, + ++act_num, act) != PJ_SUCCESS) { return 0; } @@ -386,7 +385,7 @@ static int set_converter_act(pj_uint32_t src_id, /* Convert if needed */ if (current_id != dst_id) { - if (get_converter_map(current_id, dst_id, src_size, dst_size, ++act_num, + if (get_converter_map(current_id, dst_id, src_size, dst_size, ++act_num, act) != PJ_SUCCESS) { return 0; @@ -401,59 +400,59 @@ static int set_converter_act(pj_uint32_t src_id, * the conversion/scaling process. */ static pj_status_t set_destination_buffer(pj_pool_t *pool, - struct libyuv_converter *lconv) + struct libyuv_converter *lconv) { int i = 0; for (;iact_num-1;++i) { - pj_size_t buffer_size = 0; - fmt_info *info = &lconv->act[i].dst_fmt_info; + pj_size_t buffer_size = 0; + fmt_info *info = &lconv->act[i].dst_fmt_info; - /* Get destination buffer size. */ - (*info->vid_fmt_info->apply_fmt)(info->vid_fmt_info, - &info->apply_param); + /* Get destination buffer size. */ + (*info->vid_fmt_info->apply_fmt)(info->vid_fmt_info, + &info->apply_param); - buffer_size = info->apply_param.framebytes; + buffer_size = info->apply_param.framebytes; - /* Allocate buffer. */ - lconv->act[i].dst_fmt_info.apply_param.buffer = - (pj_uint8_t*)pj_pool_alloc(pool, buffer_size); + /* Allocate buffer. */ + lconv->act[i].dst_fmt_info.apply_param.buffer = + (pj_uint8_t*)pj_pool_alloc(pool, buffer_size); - if (!lconv->act[i].dst_fmt_info.apply_param.buffer) - return PJ_ENOMEM; + if (!lconv->act[i].dst_fmt_info.apply_param.buffer) + return PJ_ENOMEM; } return PJ_SUCCESS; } /* Check the act input/output format matched the conversion/scale format. */ static pj_bool_t check_converter_act(const converter_act *act, - int act_num, - pj_uint32_t src_id, - const pjmedia_rect_size *src_size, - pj_uint32_t dst_id, - const pjmedia_rect_size *dst_size) + int act_num, + pj_uint32_t src_id, + const pjmedia_rect_size *src_size, + pj_uint32_t dst_id, + const pjmedia_rect_size *dst_size) { if (act_num) { - const struct fmt_info *first_fmt = &act[0].src_fmt_info; - const struct fmt_info *last_fmt = &act[act_num-1].dst_fmt_info; - - if ((first_fmt->vid_fmt_info->id == src_id) && - (first_fmt->apply_param.size.h == src_size->h) && - (first_fmt->apply_param.size.w == src_size->w) && - (last_fmt->vid_fmt_info->id == dst_id) && - (last_fmt->apply_param.size.h == dst_size->h) && - (last_fmt->apply_param.size.w == dst_size->w)) - { - return PJ_TRUE; - } + const struct fmt_info *first_fmt = &act[0].src_fmt_info; + const struct fmt_info *last_fmt = &act[act_num-1].dst_fmt_info; + + if ((first_fmt->vid_fmt_info->id == src_id) && + (first_fmt->apply_param.size.h == src_size->h) && + (first_fmt->apply_param.size.w == src_size->w) && + (last_fmt->vid_fmt_info->id == dst_id) && + (last_fmt->apply_param.size.h == dst_size->h) && + (last_fmt->apply_param.size.w == dst_size->w)) + { + return PJ_TRUE; + } } return PJ_FALSE; } static pj_status_t factory_create_converter(pjmedia_converter_factory *cf, - pj_pool_t *pool, - const pjmedia_conversion_param *prm, - pjmedia_converter **p_cv) + pj_pool_t *pool, + const pjmedia_conversion_param *prm, + pjmedia_converter **p_cv) { const pjmedia_video_format_detail *src_detail, *dst_detail; const pjmedia_video_format_info *src_fmt_info, *dst_fmt_info; @@ -464,28 +463,28 @@ static pj_status_t factory_create_converter(pjmedia_converter_factory *cf, /* Only supports video */ if (prm->src.type != PJMEDIA_TYPE_VIDEO || - prm->dst.type != prm->src.type || - prm->src.detail_type != PJMEDIA_FORMAT_DETAIL_VIDEO || - prm->dst.detail_type != prm->src.detail_type) + prm->dst.type != prm->src.type || + prm->src.detail_type != PJMEDIA_FORMAT_DETAIL_VIDEO || + prm->dst.detail_type != prm->src.detail_type) { - return status; + return status; } /* lookup source format info */ src_fmt_info = pjmedia_get_video_format_info( - pjmedia_video_format_mgr_instance(), - prm->src.id); + pjmedia_video_format_mgr_instance(), + prm->src.id); if (!src_fmt_info) - return status; + return status; /* lookup destination format info */ dst_fmt_info = pjmedia_get_video_format_info( - pjmedia_video_format_mgr_instance(), - prm->dst.id); + pjmedia_video_format_mgr_instance(), + prm->dst.id); if (!dst_fmt_info) - return status; + return status; src_detail = pjmedia_format_get_video_format_detail(&prm->src, PJ_TRUE); dst_detail = pjmedia_format_get_video_format_detail(&prm->dst, PJ_TRUE); @@ -494,18 +493,18 @@ static pj_status_t factory_create_converter(pjmedia_converter_factory *cf, lconv->base.op = &libyuv_converter_op; lconv->act_num = set_converter_act(src_fmt_info->id, dst_fmt_info->id, - &src_detail->size, &dst_detail->size, - lconv->act); + &src_detail->size, &dst_detail->size, + lconv->act); if (!lconv->act_num) { - return status; + return status; } if (!check_converter_act(lconv->act, lconv->act_num, - src_fmt_info->id, &src_detail->size, - dst_fmt_info->id, &dst_detail->size)) + src_fmt_info->id, &src_detail->size, + dst_fmt_info->id, &dst_detail->size)) { - return status; + return status; } status = set_destination_buffer(pool, lconv); @@ -521,8 +520,8 @@ static void factory_destroy_factory(pjmedia_converter_factory *cf) } static pj_status_t libyuv_conv_convert(pjmedia_converter *converter, - pjmedia_frame *src_frame, - pjmedia_frame *dst_frame) + pjmedia_frame *src_frame, + pjmedia_frame *dst_frame) { struct libyuv_converter *lconv = (struct libyuv_converter*)converter; int i = 0; @@ -532,121 +531,121 @@ static pj_status_t libyuv_conv_convert(pjmedia_converter *converter, /* Set the last act buffer from dst frame. */ lconv->act[lconv->act_num-1].dst_fmt_info.apply_param.buffer = - dst_frame->buf; - - for (;iact_num;++i) { - /* Use destination info as the source info for the next act. */ - struct fmt_info *src_fmt_info = (i==0)?&lconv->act[i].src_fmt_info: - &lconv->act[i-1].dst_fmt_info; - - struct fmt_info *dst_fmt_info = &lconv->act[i].dst_fmt_info; - - (*src_fmt_info->vid_fmt_info->apply_fmt)(src_fmt_info->vid_fmt_info, - &src_fmt_info->apply_param); - - (*dst_fmt_info->vid_fmt_info->apply_fmt)(dst_fmt_info->vid_fmt_info, - &dst_fmt_info->apply_param); - - switch (lconv->act[i].act_type) { - case CONV_PACK_TO_PACK: - (*lconv->act[i].method.conv_pack_to_pack)( - (const uint8*)src_fmt_info->apply_param.planes[0], - src_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.planes[0], - dst_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.size.w, - dst_fmt_info->apply_param.size.h); - break; - case CONV_PACK_TO_PLANAR: - (*lconv->act[i].method.conv_pack_to_planar)( - (const uint8*)src_fmt_info->apply_param.planes[0], - src_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.planes[0], - dst_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.planes[1], - dst_fmt_info->apply_param.strides[1], - dst_fmt_info->apply_param.planes[2], - dst_fmt_info->apply_param.strides[2], - dst_fmt_info->apply_param.size.w, - dst_fmt_info->apply_param.size.h); - break; - case CONV_PLANAR_TO_PACK: - (*lconv->act[i].method.conv_planar_to_pack)( - (const uint8*)src_fmt_info->apply_param.planes[0], - src_fmt_info->apply_param.strides[0], - (const uint8*)src_fmt_info->apply_param.planes[1], - src_fmt_info->apply_param.strides[1], - (const uint8*)src_fmt_info->apply_param.planes[2], - src_fmt_info->apply_param.strides[2], - dst_fmt_info->apply_param.planes[0], - dst_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.size.w, - dst_fmt_info->apply_param.size.h); - break; - case CONV_PLANAR_TO_PLANAR: - (*lconv->act[i].method.conv_planar_to_planar)( - (const uint8*)src_fmt_info->apply_param.planes[0], - src_fmt_info->apply_param.strides[0], - (const uint8*)src_fmt_info->apply_param.planes[1], - src_fmt_info->apply_param.strides[1], - (const uint8*)src_fmt_info->apply_param.planes[2], - src_fmt_info->apply_param.strides[2], - dst_fmt_info->apply_param.planes[0], - dst_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.planes[1], - dst_fmt_info->apply_param.strides[1], - dst_fmt_info->apply_param.planes[2], - dst_fmt_info->apply_param.strides[2], - dst_fmt_info->apply_param.size.w, - dst_fmt_info->apply_param.size.h); - break; - case SCALE_PACK: - (*lconv->act[i].method.scale_pack)( - (const uint8*)src_fmt_info->apply_param.planes[0], - src_fmt_info->apply_param.strides[0], - src_fmt_info->apply_param.size.w, - src_fmt_info->apply_param.size.h, - (uint8*)dst_fmt_info->apply_param.planes[0], - dst_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.size.w, - dst_fmt_info->apply_param.size.h, - LIBYUV_FILTER_MODE); - break; - case SCALE_PLANAR: - (*lconv->act[i].method.scale_planar)( - (const uint8*)src_fmt_info->apply_param.planes[0], - src_fmt_info->apply_param.strides[0], - (const uint8*)src_fmt_info->apply_param.planes[1], - src_fmt_info->apply_param.strides[1], - (const uint8*)src_fmt_info->apply_param.planes[2], - src_fmt_info->apply_param.strides[2], - src_fmt_info->apply_param.size.w, - src_fmt_info->apply_param.size.h, - (uint8*)dst_fmt_info->apply_param.planes[0], - dst_fmt_info->apply_param.strides[0], - (uint8*)dst_fmt_info->apply_param.planes[1], - dst_fmt_info->apply_param.strides[1], - (uint8*)dst_fmt_info->apply_param.planes[2], - dst_fmt_info->apply_param.strides[2], - dst_fmt_info->apply_param.size.w, - dst_fmt_info->apply_param.size.h, - LIBYUV_FILTER_MODE); - break; - }; + dst_frame->buf; + + for (;iact_num;++i) { + /* Use destination info as the source info for the next act. */ + struct fmt_info *src_fmt_info = (i==0)?&lconv->act[i].src_fmt_info: + &lconv->act[i-1].dst_fmt_info; + + struct fmt_info *dst_fmt_info = &lconv->act[i].dst_fmt_info; + + (*src_fmt_info->vid_fmt_info->apply_fmt)(src_fmt_info->vid_fmt_info, + &src_fmt_info->apply_param); + + (*dst_fmt_info->vid_fmt_info->apply_fmt)(dst_fmt_info->vid_fmt_info, + &dst_fmt_info->apply_param); + + switch (lconv->act[i].act_type) { + case CONV_PACK_TO_PACK: + (*lconv->act[i].method.conv_pack_to_pack)( + (const uint8*)src_fmt_info->apply_param.planes[0], + src_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.planes[0], + dst_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.size.w, + dst_fmt_info->apply_param.size.h); + break; + case CONV_PACK_TO_PLANAR: + (*lconv->act[i].method.conv_pack_to_planar)( + (const uint8*)src_fmt_info->apply_param.planes[0], + src_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.planes[0], + dst_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.planes[1], + dst_fmt_info->apply_param.strides[1], + dst_fmt_info->apply_param.planes[2], + dst_fmt_info->apply_param.strides[2], + dst_fmt_info->apply_param.size.w, + dst_fmt_info->apply_param.size.h); + break; + case CONV_PLANAR_TO_PACK: + (*lconv->act[i].method.conv_planar_to_pack)( + (const uint8*)src_fmt_info->apply_param.planes[0], + src_fmt_info->apply_param.strides[0], + (const uint8*)src_fmt_info->apply_param.planes[1], + src_fmt_info->apply_param.strides[1], + (const uint8*)src_fmt_info->apply_param.planes[2], + src_fmt_info->apply_param.strides[2], + dst_fmt_info->apply_param.planes[0], + dst_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.size.w, + dst_fmt_info->apply_param.size.h); + break; + case CONV_PLANAR_TO_PLANAR: + (*lconv->act[i].method.conv_planar_to_planar)( + (const uint8*)src_fmt_info->apply_param.planes[0], + src_fmt_info->apply_param.strides[0], + (const uint8*)src_fmt_info->apply_param.planes[1], + src_fmt_info->apply_param.strides[1], + (const uint8*)src_fmt_info->apply_param.planes[2], + src_fmt_info->apply_param.strides[2], + dst_fmt_info->apply_param.planes[0], + dst_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.planes[1], + dst_fmt_info->apply_param.strides[1], + dst_fmt_info->apply_param.planes[2], + dst_fmt_info->apply_param.strides[2], + dst_fmt_info->apply_param.size.w, + dst_fmt_info->apply_param.size.h); + break; + case SCALE_PACK: + (*lconv->act[i].method.scale_pack)( + (const uint8*)src_fmt_info->apply_param.planes[0], + src_fmt_info->apply_param.strides[0], + src_fmt_info->apply_param.size.w, + src_fmt_info->apply_param.size.h, + (uint8*)dst_fmt_info->apply_param.planes[0], + dst_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.size.w, + dst_fmt_info->apply_param.size.h, + LIBYUV_FILTER_MODE); + break; + case SCALE_PLANAR: + (*lconv->act[i].method.scale_planar)( + (const uint8*)src_fmt_info->apply_param.planes[0], + src_fmt_info->apply_param.strides[0], + (const uint8*)src_fmt_info->apply_param.planes[1], + src_fmt_info->apply_param.strides[1], + (const uint8*)src_fmt_info->apply_param.planes[2], + src_fmt_info->apply_param.strides[2], + src_fmt_info->apply_param.size.w, + src_fmt_info->apply_param.size.h, + (uint8*)dst_fmt_info->apply_param.planes[0], + dst_fmt_info->apply_param.strides[0], + (uint8*)dst_fmt_info->apply_param.planes[1], + dst_fmt_info->apply_param.strides[1], + (uint8*)dst_fmt_info->apply_param.planes[2], + dst_fmt_info->apply_param.strides[2], + dst_fmt_info->apply_param.size.w, + dst_fmt_info->apply_param.size.h, + LIBYUV_FILTER_MODE); + break; + }; } return PJ_SUCCESS; } static pj_status_t libyuv_conv_convert2( - pjmedia_converter *converter, - pjmedia_frame *src_frame, - const pjmedia_rect_size *src_frame_size, - const pjmedia_coord *src_pos, - pjmedia_frame *dst_frame, - const pjmedia_rect_size *dst_frame_size, - const pjmedia_coord *dst_pos, - pjmedia_converter_convert_setting - *param) + pjmedia_converter *converter, + pjmedia_frame *src_frame, + const pjmedia_rect_size *src_frame_size, + const pjmedia_coord *src_pos, + pjmedia_frame *dst_frame, + const pjmedia_rect_size *dst_frame_size, + const pjmedia_coord *dst_pos, + pjmedia_converter_convert_setting + *param) { struct libyuv_converter *lconv = (struct libyuv_converter*)converter; int i = 0; @@ -670,131 +669,131 @@ static pj_status_t libyuv_conv_convert2( dst_info->apply_param.size = *dst_frame_size; for (i=0;iact_num;++i) { - /* Use destination info as the source info for the next act. */ - struct fmt_info *src_fmt_info = (i==0)? src_info : - &lconv->act[i-1].dst_fmt_info; - - struct fmt_info *dst_fmt_info = &lconv->act[i].dst_fmt_info; - - (*src_fmt_info->vid_fmt_info->apply_fmt)(src_fmt_info->vid_fmt_info, - &src_fmt_info->apply_param); - - (*dst_fmt_info->vid_fmt_info->apply_fmt)(dst_fmt_info->vid_fmt_info, - &dst_fmt_info->apply_param); - - /* For first and last acts, apply plane buffer offset and return back - * the original sizes. - */ - if (i == 0) { - pjmedia_video_apply_fmt_param *ap = &src_fmt_info->apply_param; - unsigned j; - for (j = 0; j < src_fmt_info->vid_fmt_info->plane_cnt; ++j) { - int y = src_pos->y * (int)ap->plane_bytes[j] / ap->strides[j] / - ap->size.h; - ap->planes[j] += y * ap->strides[j] + src_pos->x * - ap->strides[j] / ap->size.w; - } - ap->size = orig_src_size; - } - if (i == lconv->act_num-1) { - pjmedia_video_apply_fmt_param *ap = &dst_fmt_info->apply_param; - unsigned j; - for (j = 0; j < dst_fmt_info->vid_fmt_info->plane_cnt; ++j) - { - int y = dst_pos->y * (int)ap->plane_bytes[j] / ap->strides[j] / - ap->size.h; - ap->planes[j] += y * ap->strides[j] + dst_pos->x * - ap->strides[j] / ap->size.w; - } - ap->size = orig_dst_size; - } - - switch (lconv->act[i].act_type) { - case CONV_PACK_TO_PACK: - (*lconv->act[i].method.conv_pack_to_pack)( - (const uint8*)src_fmt_info->apply_param.planes[0], - src_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.planes[0], - dst_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.size.w, - dst_fmt_info->apply_param.size.h); - break; - case CONV_PACK_TO_PLANAR: - (*lconv->act[i].method.conv_pack_to_planar)( - (const uint8*)src_fmt_info->apply_param.planes[0], - src_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.planes[0], - dst_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.planes[1], - dst_fmt_info->apply_param.strides[1], - dst_fmt_info->apply_param.planes[2], - dst_fmt_info->apply_param.strides[2], - dst_fmt_info->apply_param.size.w, - dst_fmt_info->apply_param.size.h); - break; - case CONV_PLANAR_TO_PACK: - (*lconv->act[i].method.conv_planar_to_pack)( - (const uint8*)src_fmt_info->apply_param.planes[0], - src_fmt_info->apply_param.strides[0], - (const uint8*)src_fmt_info->apply_param.planes[1], - src_fmt_info->apply_param.strides[1], - (const uint8*)src_fmt_info->apply_param.planes[2], - src_fmt_info->apply_param.strides[2], - dst_fmt_info->apply_param.planes[0], - dst_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.size.w, - dst_fmt_info->apply_param.size.h); - break; - case CONV_PLANAR_TO_PLANAR: - (*lconv->act[i].method.conv_planar_to_planar)( - (const uint8*)src_fmt_info->apply_param.planes[0], - src_fmt_info->apply_param.strides[0], - (const uint8*)src_fmt_info->apply_param.planes[1], - src_fmt_info->apply_param.strides[1], - (const uint8*)src_fmt_info->apply_param.planes[2], - src_fmt_info->apply_param.strides[2], - dst_fmt_info->apply_param.planes[0], - dst_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.planes[1], - dst_fmt_info->apply_param.strides[1], - dst_fmt_info->apply_param.planes[2], - dst_fmt_info->apply_param.strides[2], - dst_fmt_info->apply_param.size.w, - dst_fmt_info->apply_param.size.h); - break; - case SCALE_PACK: - (*lconv->act[i].method.scale_pack)( - (const uint8*)src_fmt_info->apply_param.planes[0], - src_fmt_info->apply_param.strides[0], - src_fmt_info->apply_param.size.w, - src_fmt_info->apply_param.size.h, - (uint8*)dst_fmt_info->apply_param.planes[0], - dst_fmt_info->apply_param.strides[0], - dst_fmt_info->apply_param.size.w, - dst_fmt_info->apply_param.size.h, - LIBYUV_FILTER_MODE); - break; - case SCALE_PLANAR: - (*lconv->act[i].method.scale_planar)( - (const uint8*)src_fmt_info->apply_param.planes[0], - src_fmt_info->apply_param.strides[0], - (const uint8*)src_fmt_info->apply_param.planes[1], - src_fmt_info->apply_param.strides[1], - (const uint8*)src_fmt_info->apply_param.planes[2], - src_fmt_info->apply_param.strides[2], - src_fmt_info->apply_param.size.w, - src_fmt_info->apply_param.size.h, - (uint8*)dst_fmt_info->apply_param.planes[0], - dst_fmt_info->apply_param.strides[0], - (uint8*)dst_fmt_info->apply_param.planes[1], - dst_fmt_info->apply_param.strides[1], - (uint8*)dst_fmt_info->apply_param.planes[2], - dst_fmt_info->apply_param.strides[2], - dst_fmt_info->apply_param.size.w, - dst_fmt_info->apply_param.size.h, - LIBYUV_FILTER_MODE); - break; - }; + /* Use destination info as the source info for the next act. */ + struct fmt_info *src_fmt_info = (i==0)? src_info : + &lconv->act[i-1].dst_fmt_info; + + struct fmt_info *dst_fmt_info = &lconv->act[i].dst_fmt_info; + + (*src_fmt_info->vid_fmt_info->apply_fmt)(src_fmt_info->vid_fmt_info, + &src_fmt_info->apply_param); + + (*dst_fmt_info->vid_fmt_info->apply_fmt)(dst_fmt_info->vid_fmt_info, + &dst_fmt_info->apply_param); + + /* For first and last acts, apply plane buffer offset and return back + * the original sizes. + */ + if (i == 0) { + pjmedia_video_apply_fmt_param *ap = &src_fmt_info->apply_param; + unsigned j; + for (j = 0; j < src_fmt_info->vid_fmt_info->plane_cnt; ++j) { + int y = src_pos->y * (int)ap->plane_bytes[j] / ap->strides[j] / + ap->size.h; + ap->planes[j] += y * ap->strides[j] + src_pos->x * + ap->strides[j] / ap->size.w; + } + ap->size = orig_src_size; + } + if (i == lconv->act_num-1) { + pjmedia_video_apply_fmt_param *ap = &dst_fmt_info->apply_param; + unsigned j; + for (j = 0; j < dst_fmt_info->vid_fmt_info->plane_cnt; ++j) + { + int y = dst_pos->y * (int)ap->plane_bytes[j] / ap->strides[j] / + ap->size.h; + ap->planes[j] += y * ap->strides[j] + dst_pos->x * + ap->strides[j] / ap->size.w; + } + ap->size = orig_dst_size; + } + + switch (lconv->act[i].act_type) { + case CONV_PACK_TO_PACK: + (*lconv->act[i].method.conv_pack_to_pack)( + (const uint8*)src_fmt_info->apply_param.planes[0], + src_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.planes[0], + dst_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.size.w, + dst_fmt_info->apply_param.size.h); + break; + case CONV_PACK_TO_PLANAR: + (*lconv->act[i].method.conv_pack_to_planar)( + (const uint8*)src_fmt_info->apply_param.planes[0], + src_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.planes[0], + dst_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.planes[1], + dst_fmt_info->apply_param.strides[1], + dst_fmt_info->apply_param.planes[2], + dst_fmt_info->apply_param.strides[2], + dst_fmt_info->apply_param.size.w, + dst_fmt_info->apply_param.size.h); + break; + case CONV_PLANAR_TO_PACK: + (*lconv->act[i].method.conv_planar_to_pack)( + (const uint8*)src_fmt_info->apply_param.planes[0], + src_fmt_info->apply_param.strides[0], + (const uint8*)src_fmt_info->apply_param.planes[1], + src_fmt_info->apply_param.strides[1], + (const uint8*)src_fmt_info->apply_param.planes[2], + src_fmt_info->apply_param.strides[2], + dst_fmt_info->apply_param.planes[0], + dst_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.size.w, + dst_fmt_info->apply_param.size.h); + break; + case CONV_PLANAR_TO_PLANAR: + (*lconv->act[i].method.conv_planar_to_planar)( + (const uint8*)src_fmt_info->apply_param.planes[0], + src_fmt_info->apply_param.strides[0], + (const uint8*)src_fmt_info->apply_param.planes[1], + src_fmt_info->apply_param.strides[1], + (const uint8*)src_fmt_info->apply_param.planes[2], + src_fmt_info->apply_param.strides[2], + dst_fmt_info->apply_param.planes[0], + dst_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.planes[1], + dst_fmt_info->apply_param.strides[1], + dst_fmt_info->apply_param.planes[2], + dst_fmt_info->apply_param.strides[2], + dst_fmt_info->apply_param.size.w, + dst_fmt_info->apply_param.size.h); + break; + case SCALE_PACK: + (*lconv->act[i].method.scale_pack)( + (const uint8*)src_fmt_info->apply_param.planes[0], + src_fmt_info->apply_param.strides[0], + src_fmt_info->apply_param.size.w, + src_fmt_info->apply_param.size.h, + (uint8*)dst_fmt_info->apply_param.planes[0], + dst_fmt_info->apply_param.strides[0], + dst_fmt_info->apply_param.size.w, + dst_fmt_info->apply_param.size.h, + LIBYUV_FILTER_MODE); + break; + case SCALE_PLANAR: + (*lconv->act[i].method.scale_planar)( + (const uint8*)src_fmt_info->apply_param.planes[0], + src_fmt_info->apply_param.strides[0], + (const uint8*)src_fmt_info->apply_param.planes[1], + src_fmt_info->apply_param.strides[1], + (const uint8*)src_fmt_info->apply_param.planes[2], + src_fmt_info->apply_param.strides[2], + src_fmt_info->apply_param.size.w, + src_fmt_info->apply_param.size.h, + (uint8*)dst_fmt_info->apply_param.planes[0], + dst_fmt_info->apply_param.strides[0], + (uint8*)dst_fmt_info->apply_param.planes[1], + dst_fmt_info->apply_param.strides[1], + (uint8*)dst_fmt_info->apply_param.planes[2], + dst_fmt_info->apply_param.strides[2], + dst_fmt_info->apply_param.size.w, + dst_fmt_info->apply_param.size.h, + LIBYUV_FILTER_MODE); + break; + }; } return PJ_SUCCESS; } @@ -806,10 +805,10 @@ static void libyuv_conv_destroy(pjmedia_converter *converter) static pjmedia_converter_factory libyuv_factory = { - NULL, NULL, /* list */ - "libyuv", /* name */ - PJMEDIA_CONVERTER_PRIORITY_NORMAL, /* priority */ - NULL /* op will be init-ed later */ + NULL, NULL, /* list */ + "libyuv", /* name */ + PJMEDIA_CONVERTER_PRIORITY_NORMAL, /* priority */ + NULL /* op will be init-ed later */ }; PJ_DEF(pj_status_t) @@ -822,11 +821,11 @@ pjmedia_libyuv_converter_init(pjmedia_converter_mgr *mgr) PJ_DEF(pj_status_t) pjmedia_libyuv_converter_shutdown(pjmedia_converter_mgr *mgr, - pj_pool_t *pool) + pj_pool_t *pool) { PJ_UNUSED_ARG(pool); return pjmedia_converter_mgr_unregister_factory(mgr, &libyuv_factory, - PJ_TRUE); + PJ_TRUE); } #endif //#if defined(PJMEDIA_HAS_LIBYUV) && PJMEDIA_HAS_LIBYUV != 0 diff --git a/pjmedia/src/pjmedia/delaybuf.c b/pjmedia/src/pjmedia/delaybuf.c index 5a119d15c0..49fb5c56ad 100644 --- a/pjmedia/src/pjmedia/delaybuf.c +++ b/pjmedia/src/pjmedia/delaybuf.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -45,7 +44,7 @@ enum OP /* Specify time for delaybuf to recalculate effective delay, in ms. */ -#define RECALC_TIME 2000 +#define RECALC_TIME 2000 /* Default value of maximum delay, in ms, this value is used when * maximum delay requested is less than ptime (one frame length). @@ -54,55 +53,55 @@ enum OP /* Number of frames to add to learnt level for additional stability. */ -#define SAFE_MARGIN 0 +#define SAFE_MARGIN 0 /* This structure describes internal delaybuf settings and states. */ struct pjmedia_delay_buf { /* Properties and configuration */ - char obj_name[PJ_MAX_OBJ_NAME]; - pj_lock_t *lock; /**< Lock object. */ - unsigned samples_per_frame; /**< Number of samples in one frame */ - unsigned ptime; /**< Frame time, in ms */ - unsigned channel_count; /**< Channel count, in ms */ - pjmedia_circ_buf *circ_buf; /**< Circular buffer to store audio - samples */ - unsigned max_cnt; /**< Maximum samples to be buffered */ - unsigned eff_cnt; /**< Effective count of buffered - samples to keep the optimum - balance between delay and - stability. This is calculated - based on burst level. */ + char obj_name[PJ_MAX_OBJ_NAME]; + pj_lock_t *lock; /**< Lock object. */ + unsigned samples_per_frame; /**< Number of samples in one frame */ + unsigned ptime; /**< Frame time, in ms */ + unsigned channel_count; /**< Channel count, in ms */ + pjmedia_circ_buf *circ_buf; /**< Circular buffer to store audio + samples */ + unsigned max_cnt; /**< Maximum samples to be buffered */ + unsigned eff_cnt; /**< Effective count of buffered + samples to keep the optimum + balance between delay and + stability. This is calculated + based on burst level. */ /* Learning vars */ - unsigned level; /**< Burst level counter */ - enum OP last_op; /**< Last op (GET or PUT) of learning*/ - int recalc_timer; /**< Timer for recalculating max_level*/ - unsigned max_level; /**< Current max burst level */ + unsigned level; /**< Burst level counter */ + enum OP last_op; /**< Last op (GET or PUT) of learning*/ + int recalc_timer; /**< Timer for recalculating max_level*/ + unsigned max_level; /**< Current max burst level */ /* Drift handler */ - pjmedia_wsola *wsola; /**< Drift handler */ + pjmedia_wsola *wsola; /**< Drift handler */ }; PJ_DEF(pj_status_t) pjmedia_delay_buf_create( pj_pool_t *pool, - const char *name, - unsigned clock_rate, - unsigned samples_per_frame, - unsigned channel_count, - unsigned max_delay, - unsigned options, - pjmedia_delay_buf **p_b) + const char *name, + unsigned clock_rate, + unsigned samples_per_frame, + unsigned channel_count, + unsigned max_delay, + unsigned options, + pjmedia_delay_buf **p_b) { pjmedia_delay_buf *b; pj_status_t status; PJ_ASSERT_RETURN(pool && samples_per_frame && clock_rate && channel_count && - p_b, PJ_EINVAL); + p_b, PJ_EINVAL); if (!name) { - name = "delaybuf"; + name = "delaybuf"; } b = PJ_POOL_ZALLOC_T(pool, pjmedia_delay_buf); @@ -113,7 +112,7 @@ PJ_DEF(pj_status_t) pjmedia_delay_buf_create( pj_pool_t *pool, b->channel_count = channel_count; b->ptime = samples_per_frame * 1000 / clock_rate / channel_count; if (max_delay < b->ptime) - max_delay = PJ_MAX(DEFAULT_MAX_DELAY, b->ptime); + max_delay = PJ_MAX(DEFAULT_MAX_DELAY, b->ptime); b->max_cnt = samples_per_frame * max_delay / b->ptime; b->eff_cnt = b->max_cnt >> 1; @@ -122,14 +121,14 @@ PJ_DEF(pj_status_t) pjmedia_delay_buf_create( pj_pool_t *pool, /* Create circular buffer */ status = pjmedia_circ_buf_create(pool, b->max_cnt, &b->circ_buf); if (status != PJ_SUCCESS) - return status; + return status; if (!(options & PJMEDIA_DELAY_BUF_SIMPLE_FIFO)) { /* Create WSOLA */ status = pjmedia_wsola_create(pool, clock_rate, samples_per_frame, 1, - PJMEDIA_WSOLA_NO_FADING, &b->wsola); + PJMEDIA_WSOLA_NO_FADING, &b->wsola); if (status != PJ_SUCCESS) - return status; + return status; PJ_LOG(5, (b->obj_name, "Using delay buffer with WSOLA.")); } else { PJ_LOG(5, (b->obj_name, "Using simple FIFO delay buffer.")); @@ -137,9 +136,9 @@ PJ_DEF(pj_status_t) pjmedia_delay_buf_create( pj_pool_t *pool, /* Finally, create mutex */ status = pj_lock_create_recursive_mutex(pool, b->obj_name, - &b->lock); + &b->lock); if (status != PJ_SUCCESS) - return status; + return status; *p_b = b; @@ -159,7 +158,7 @@ PJ_DEF(pj_status_t) pjmedia_delay_buf_destroy(pjmedia_delay_buf *b) if (b->wsola) { status = pjmedia_wsola_destroy(b->wsola); if (status == PJ_SUCCESS) - b->wsola = NULL; + b->wsola = NULL; } pj_lock_release(b->lock); @@ -183,22 +182,22 @@ static void shrink_buffer(pjmedia_delay_buf *b, unsigned erase_cnt) pj_assert(b && erase_cnt && pjmedia_circ_buf_get_len(b->circ_buf)); pjmedia_circ_buf_get_read_regions(b->circ_buf, &buf1, &buf1len, - &buf2, &buf2len); + &buf2, &buf2len); status = pjmedia_wsola_discard(b->wsola, buf1, buf1len, buf2, buf2len, - &erase_cnt); + &erase_cnt); if ((status == PJ_SUCCESS) && (erase_cnt > 0)) { - /* WSOLA discard will manage the first buffer to be full, unless - * erase_cnt is greater than second buffer length. So it is safe - * to just set the circular buffer length. - */ + /* WSOLA discard will manage the first buffer to be full, unless + * erase_cnt is greater than second buffer length. So it is safe + * to just set the circular buffer length. + */ - pjmedia_circ_buf_set_len(b->circ_buf, - pjmedia_circ_buf_get_len(b->circ_buf) - - erase_cnt); + pjmedia_circ_buf_set_len(b->circ_buf, + pjmedia_circ_buf_get_len(b->circ_buf) - + erase_cnt); - PJ_LOG(5,(b->obj_name,"%d samples reduced, buf_cnt=%d", - erase_cnt, pjmedia_circ_buf_get_len(b->circ_buf))); + PJ_LOG(5,(b->obj_name,"%d samples reduced, buf_cnt=%d", + erase_cnt, pjmedia_circ_buf_get_len(b->circ_buf))); } } @@ -213,13 +212,13 @@ static void update(pjmedia_delay_buf *b, enum OP op) { /* Sequential operation */ if (op == b->last_op) { - ++b->level; - return; + ++b->level; + return; } /* Switching operation */ if (b->level > b->max_level) - b->max_level = b->level; + b->max_level = b->level; b->recalc_timer -= (b->level * b->ptime) >> 1; @@ -228,40 +227,40 @@ static void update(pjmedia_delay_buf *b, enum OP op) /* Recalculate effective count based on max_level */ if (b->recalc_timer <= 0) { - unsigned new_eff_cnt = (b->max_level+SAFE_MARGIN)*b->samples_per_frame; - - /* Smoothening effective count transition */ - AGC(b->eff_cnt, new_eff_cnt); - - /* Make sure the new effective count is multiplication of - * channel_count, so let's round it up. - */ - if (b->eff_cnt % b->channel_count) - b->eff_cnt += b->channel_count - (b->eff_cnt % b->channel_count); - - TRACE__((b->obj_name,"Cur eff_cnt=%d", b->eff_cnt)); - - b->max_level = 0; - b->recalc_timer = RECALC_TIME; + unsigned new_eff_cnt = (b->max_level+SAFE_MARGIN)*b->samples_per_frame; + + /* Smoothening effective count transition */ + AGC(b->eff_cnt, new_eff_cnt); + + /* Make sure the new effective count is multiplication of + * channel_count, so let's round it up. + */ + if (b->eff_cnt % b->channel_count) + b->eff_cnt += b->channel_count - (b->eff_cnt % b->channel_count); + + TRACE__((b->obj_name,"Cur eff_cnt=%d", b->eff_cnt)); + + b->max_level = 0; + b->recalc_timer = RECALC_TIME; } /* See if we need to shrink the buffer to reduce delay */ if (op == OP_PUT && pjmedia_circ_buf_get_len(b->circ_buf) > - b->samples_per_frame + b->eff_cnt) + b->samples_per_frame + b->eff_cnt) { - unsigned erase_cnt = b->samples_per_frame >> 1; - unsigned old_buf_cnt = pjmedia_circ_buf_get_len(b->circ_buf); - - shrink_buffer(b, erase_cnt); - PJ_LOG(4,(b->obj_name,"Buffer size adjusted from %d to %d (eff_cnt=%d)", - old_buf_cnt, - pjmedia_circ_buf_get_len(b->circ_buf), - b->eff_cnt)); + unsigned erase_cnt = b->samples_per_frame >> 1; + unsigned old_buf_cnt = pjmedia_circ_buf_get_len(b->circ_buf); + + shrink_buffer(b, erase_cnt); + PJ_LOG(4,(b->obj_name,"Buffer size adjusted from %d to %d (eff_cnt=%d)", + old_buf_cnt, + pjmedia_circ_buf_get_len(b->circ_buf), + b->eff_cnt)); } } PJ_DEF(pj_status_t) pjmedia_delay_buf_put(pjmedia_delay_buf *b, - pj_int16_t frame[]) + pj_int16_t frame[]) { pj_status_t status; @@ -274,42 +273,42 @@ PJ_DEF(pj_status_t) pjmedia_delay_buf_put(pjmedia_delay_buf *b, status = pjmedia_wsola_save(b->wsola, frame, PJ_FALSE); if (status != PJ_SUCCESS) { - pj_lock_release(b->lock); - return status; + pj_lock_release(b->lock); + return status; } } /* Overflow checking */ if (pjmedia_circ_buf_get_len(b->circ_buf) + b->samples_per_frame > - b->max_cnt) + b->max_cnt) { - unsigned erase_cnt; + unsigned erase_cnt; if (b->wsola) { - /* shrink one frame or just the diff? */ - //erase_cnt = b->samples_per_frame; - erase_cnt = pjmedia_circ_buf_get_len(b->circ_buf) + - b->samples_per_frame - b->max_cnt; + /* shrink one frame or just the diff? */ + //erase_cnt = b->samples_per_frame; + erase_cnt = pjmedia_circ_buf_get_len(b->circ_buf) + + b->samples_per_frame - b->max_cnt; - shrink_buffer(b, erase_cnt); + shrink_buffer(b, erase_cnt); } - /* Check if shrinking failed or erased count is less than requested, - * delaybuf needs to drop eldest samples, this is bad since the voice - * samples get rough transition which may produce tick noise. - */ - if (pjmedia_circ_buf_get_len(b->circ_buf) + b->samples_per_frame > - b->max_cnt) - { - erase_cnt = pjmedia_circ_buf_get_len(b->circ_buf) + - b->samples_per_frame - b->max_cnt; + /* Check if shrinking failed or erased count is less than requested, + * delaybuf needs to drop eldest samples, this is bad since the voice + * samples get rough transition which may produce tick noise. + */ + if (pjmedia_circ_buf_get_len(b->circ_buf) + b->samples_per_frame > + b->max_cnt) + { + erase_cnt = pjmedia_circ_buf_get_len(b->circ_buf) + + b->samples_per_frame - b->max_cnt; - pjmedia_circ_buf_adv_read_ptr(b->circ_buf, erase_cnt); + pjmedia_circ_buf_adv_read_ptr(b->circ_buf, erase_cnt); - PJ_LOG(4,(b->obj_name,"%sDropping %d eldest samples, buf_cnt=%d", + PJ_LOG(4,(b->obj_name,"%sDropping %d eldest samples, buf_cnt=%d", (b->wsola? "Shrinking failed or insufficient. ": ""), erase_cnt, pjmedia_circ_buf_get_len(b->circ_buf))); - } + } } pjmedia_circ_buf_write(b->circ_buf, frame, b->samples_per_frame); @@ -319,7 +318,7 @@ PJ_DEF(pj_status_t) pjmedia_delay_buf_put(pjmedia_delay_buf *b, } PJ_DEF(pj_status_t) pjmedia_delay_buf_get( pjmedia_delay_buf *b, - pj_int16_t frame[]) + pj_int16_t frame[]) { pj_status_t status = PJ_SUCCESS; @@ -333,43 +332,43 @@ PJ_DEF(pj_status_t) pjmedia_delay_buf_get( pjmedia_delay_buf *b, /* Starvation checking */ if (pjmedia_circ_buf_get_len(b->circ_buf) < b->samples_per_frame) { - PJ_LOG(4,(b->obj_name,"Underflow, buf_cnt=%d, will generate 1 frame", - pjmedia_circ_buf_get_len(b->circ_buf))); + PJ_LOG(4,(b->obj_name,"Underflow, buf_cnt=%d, will generate 1 frame", + pjmedia_circ_buf_get_len(b->circ_buf))); if (b->wsola) { status = pjmedia_wsola_generate(b->wsola, frame); - if (status == PJ_SUCCESS) { - TRACE__((b->obj_name,"Successfully generate 1 frame")); - if (pjmedia_circ_buf_get_len(b->circ_buf) == 0) { - pj_lock_release(b->lock); - return PJ_SUCCESS; - } + if (status == PJ_SUCCESS) { + TRACE__((b->obj_name,"Successfully generate 1 frame")); + if (pjmedia_circ_buf_get_len(b->circ_buf) == 0) { + pj_lock_release(b->lock); + return PJ_SUCCESS; + } - /* Put generated frame into buffer */ - pjmedia_circ_buf_write(b->circ_buf, frame, + /* Put generated frame into buffer */ + pjmedia_circ_buf_write(b->circ_buf, frame, b->samples_per_frame); } } - if (!b->wsola || status != PJ_SUCCESS) { - unsigned buf_len = pjmedia_circ_buf_get_len(b->circ_buf); - - /* Give all what delay buffer has, then pad with zeroes */ + if (!b->wsola || status != PJ_SUCCESS) { + unsigned buf_len = pjmedia_circ_buf_get_len(b->circ_buf); + + /* Give all what delay buffer has, then pad with zeroes */ if (b->wsola) - PJ_PERROR(4,(b->obj_name, status, "Error generating frame")); + PJ_PERROR(4,(b->obj_name, status, "Error generating frame")); - pjmedia_circ_buf_read(b->circ_buf, frame, buf_len); - pjmedia_zero_samples(&frame[buf_len], - b->samples_per_frame - buf_len); + pjmedia_circ_buf_read(b->circ_buf, frame, buf_len); + pjmedia_zero_samples(&frame[buf_len], + b->samples_per_frame - buf_len); - /* The buffer is empty now, reset it */ - pjmedia_circ_buf_reset(b->circ_buf); + /* The buffer is empty now, reset it */ + pjmedia_circ_buf_reset(b->circ_buf); - pj_lock_release(b->lock); + pj_lock_release(b->lock); - return PJ_SUCCESS; - } + return PJ_SUCCESS; + } } pjmedia_circ_buf_read(b->circ_buf, frame, b->samples_per_frame); diff --git a/pjmedia/src/pjmedia/dummy.c b/pjmedia/src/pjmedia/dummy.c index 54f0ed6679..0b3ec16213 100644 --- a/pjmedia/src/pjmedia/dummy.c +++ b/pjmedia/src/pjmedia/dummy.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjmedia/src/pjmedia/echo_common.c b/pjmedia/src/pjmedia/echo_common.c index f16a02d85c..d5b84ea466 100644 --- a/pjmedia/src/pjmedia/echo_common.c +++ b/pjmedia/src/pjmedia/echo_common.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -41,18 +40,18 @@ struct frame struct pjmedia_echo_state { - pj_pool_t *pool; - char *obj_name; - unsigned samples_per_frame; - void *state; + pj_pool_t *pool; + char *obj_name; + unsigned samples_per_frame; + void *state; ec_operations *op; - pj_bool_t lat_ready; /* lat_buf has been filled in. */ - struct frame lat_buf; /* Frame queue for delayed playback */ - struct frame lat_free; /* Free frame list. */ + pj_bool_t lat_ready; /* lat_buf has been filled in. */ + struct frame lat_buf; /* Frame queue for delayed playback */ + struct frame lat_free; /* Free frame list. */ - pjmedia_delay_buf *delay_buf; - pj_int16_t *frm_buf; + pjmedia_delay_buf *delay_buf; + pj_int16_t *frm_buf; }; @@ -61,26 +60,26 @@ struct ec_operations const char *name; pj_status_t (*ec_create)(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned tail_ms, - unsigned options, - void **p_state ); + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned tail_ms, + unsigned options, + void **p_state ); pj_status_t (*ec_destroy)(void *state ); void (*ec_reset)(void *state ); pj_status_t (*ec_cancel)(void *state, - pj_int16_t *rec_frm, - const pj_int16_t *play_frm, - unsigned options, - void *reserved ); + pj_int16_t *rec_frm, + const pj_int16_t *play_frm, + unsigned options, + void *reserved ); pj_status_t (*ec_playback)(void *state, - pj_int16_t *play_frm ); + pj_int16_t *play_frm ); pj_status_t (*ec_capture)(void *state, - pj_int16_t *rec_frm, - unsigned options ); - pj_status_t (*ec_get_stat)(void *state, - pjmedia_echo_stat *stat); + pj_int16_t *rec_frm, + unsigned options ); + pj_status_t (*ec_get_stat)(void *state, + pjmedia_echo_stat *stat); }; @@ -181,28 +180,28 @@ PJ_DEF(void) pjmedia_echo_stat_default(pjmedia_echo_stat *stat) * Create the echo canceller. */ PJ_DEF(pj_status_t) pjmedia_echo_create( pj_pool_t *pool, - unsigned clock_rate, - unsigned samples_per_frame, - unsigned tail_ms, - unsigned latency_ms, - unsigned options, - pjmedia_echo_state **p_echo ) + unsigned clock_rate, + unsigned samples_per_frame, + unsigned tail_ms, + unsigned latency_ms, + unsigned options, + pjmedia_echo_state **p_echo ) { return pjmedia_echo_create2(pool, clock_rate, 1, samples_per_frame, - tail_ms, latency_ms, options, p_echo); + tail_ms, latency_ms, options, p_echo); } /* * Create the echo canceller. */ PJ_DEF(pj_status_t) pjmedia_echo_create2(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned tail_ms, - unsigned latency_ms, - unsigned options, - pjmedia_echo_state **p_echo ) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned tail_ms, + unsigned latency_ms, + unsigned options, + pjmedia_echo_state **p_echo ) { unsigned ptime, lat_cnt; unsigned delay_buf_opt = 0; @@ -221,20 +220,20 @@ PJ_DEF(pj_status_t) pjmedia_echo_create2(pj_pool_t *pool, /* Select the backend algorithm */ if (0) { - /* Dummy */ - ; + /* Dummy */ + ; #if defined(PJMEDIA_HAS_SPEEX_AEC) && PJMEDIA_HAS_SPEEX_AEC!=0 } else if ((options & PJMEDIA_ECHO_ALGO_MASK) == PJMEDIA_ECHO_SPEEX || - (options & PJMEDIA_ECHO_ALGO_MASK) == PJMEDIA_ECHO_DEFAULT) + (options & PJMEDIA_ECHO_ALGO_MASK) == PJMEDIA_ECHO_DEFAULT) { - ec->op = &speex_aec_op; + ec->op = &speex_aec_op; #endif #if defined(PJMEDIA_HAS_INTEL_IPP_AEC) && PJMEDIA_HAS_INTEL_IPP_AEC!=0 } else if ((options & PJMEDIA_ECHO_ALGO_MASK) == PJMEDIA_ECHO_IPP || - (options & PJMEDIA_ECHO_ALGO_MASK) == PJMEDIA_ECHO_DEFAULT) + (options & PJMEDIA_ECHO_ALGO_MASK) == PJMEDIA_ECHO_DEFAULT) { - ec->op = &ipp_aec_op; + ec->op = &ipp_aec_op; #endif @@ -253,7 +252,7 @@ PJ_DEF(pj_status_t) pjmedia_echo_create2(pj_pool_t *pool, #endif } else { - ec->op = &echo_supp_op; + ec->op = &echo_supp_op; } /* Completeness check for EC operation playback and capture, they must @@ -265,57 +264,57 @@ PJ_DEF(pj_status_t) pjmedia_echo_create2(pj_pool_t *pool, /* Instantiate EC object */ status = (*ec->op->ec_create)(pool, clock_rate, channel_count, - samples_per_frame, tail_ms, - options, &ec->state); + samples_per_frame, tail_ms, + options, &ec->state); if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; + pj_pool_release(pool); + return status; } /* If EC algo does not have playback and capture callbakcs, * create latency buffer and delay buffer to handle drift. */ if (ec->op->ec_playback && ec->op->ec_capture) { - latency_ms = 0; + latency_ms = 0; } else { - /* Create latency buffers */ - ptime = samples_per_frame * 1000 / clock_rate; - if (latency_ms > ptime) { - /* Normalize latency with delaybuf/WSOLA latency */ - latency_ms -= PJ_MIN(ptime, PJMEDIA_WSOLA_DELAY_MSEC); - } - if (latency_ms < ptime) { - /* Give at least one frame delay to simplify programming */ - latency_ms = ptime; - } - lat_cnt = latency_ms / ptime; - while (lat_cnt--) { - struct frame *frm; - - frm = (struct frame*) pj_pool_alloc(pool, (samples_per_frame<<1) + - sizeof(struct frame)); - pj_list_push_back(&ec->lat_free, frm); - } - - /* Create delay buffer to compensate drifts */ - if (options & PJMEDIA_ECHO_USE_SIMPLE_FIFO) - delay_buf_opt |= PJMEDIA_DELAY_BUF_SIMPLE_FIFO; - status = pjmedia_delay_buf_create(ec->pool, ec->obj_name, clock_rate, - samples_per_frame, channel_count, - (PJMEDIA_SOUND_BUFFER_COUNT+1) * ptime, - delay_buf_opt, &ec->delay_buf); - if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; - } + /* Create latency buffers */ + ptime = samples_per_frame * 1000 / clock_rate; + if (latency_ms > ptime) { + /* Normalize latency with delaybuf/WSOLA latency */ + latency_ms -= PJ_MIN(ptime, PJMEDIA_WSOLA_DELAY_MSEC); + } + if (latency_ms < ptime) { + /* Give at least one frame delay to simplify programming */ + latency_ms = ptime; + } + lat_cnt = latency_ms / ptime; + while (lat_cnt--) { + struct frame *frm; + + frm = (struct frame*) pj_pool_alloc(pool, (samples_per_frame<<1) + + sizeof(struct frame)); + pj_list_push_back(&ec->lat_free, frm); + } + + /* Create delay buffer to compensate drifts */ + if (options & PJMEDIA_ECHO_USE_SIMPLE_FIFO) + delay_buf_opt |= PJMEDIA_DELAY_BUF_SIMPLE_FIFO; + status = pjmedia_delay_buf_create(ec->pool, ec->obj_name, clock_rate, + samples_per_frame, channel_count, + (PJMEDIA_SOUND_BUFFER_COUNT+1) * ptime, + delay_buf_opt, &ec->delay_buf); + if (status != PJ_SUCCESS) { + pj_pool_release(pool); + return status; + } } PJ_LOG(4,(ec->obj_name, - "%s created, clock_rate=%d, channel=%d, " - "samples per frame=%d, tail length=%d ms, " - "latency=%d ms", - ec->op->name, clock_rate, channel_count, samples_per_frame, - tail_ms, latency_ms)); + "%s created, clock_rate=%d, channel=%d, " + "samples per frame=%d, tail length=%d ms, " + "latency=%d ms", + ec->op->name, clock_rate, channel_count, samples_per_frame, + tail_ms, latency_ms)); /* Done */ *p_echo = ec; @@ -332,8 +331,8 @@ PJ_DEF(pj_status_t) pjmedia_echo_destroy(pjmedia_echo_state *echo ) (*echo->op->ec_destroy)(echo->state); if (echo->delay_buf) { - pjmedia_delay_buf_destroy(echo->delay_buf); - echo->delay_buf = NULL; + pjmedia_delay_buf_destroy(echo->delay_buf); + echo->delay_buf = NULL; } pj_pool_release(echo->pool); @@ -347,14 +346,14 @@ PJ_DEF(pj_status_t) pjmedia_echo_destroy(pjmedia_echo_state *echo ) PJ_DEF(pj_status_t) pjmedia_echo_reset(pjmedia_echo_state *echo ) { while (!pj_list_empty(&echo->lat_buf)) { - struct frame *frm; - frm = echo->lat_buf.next; - pj_list_erase(frm); - pj_list_push_back(&echo->lat_free, frm); + struct frame *frm; + frm = echo->lat_buf.next; + pj_list_erase(frm); + pj_list_push_back(&echo->lat_free, frm); } echo->lat_ready = PJ_FALSE; if (echo->delay_buf) - pjmedia_delay_buf_reset(echo->delay_buf); + pjmedia_delay_buf_reset(echo->delay_buf); echo->op->ec_reset(echo->state); return PJ_SUCCESS; } @@ -364,11 +363,11 @@ PJ_DEF(pj_status_t) pjmedia_echo_reset(pjmedia_echo_state *echo ) * Let the Echo Canceller know that a frame has been played to the speaker. */ PJ_DEF(pj_status_t) pjmedia_echo_playback( pjmedia_echo_state *echo, - pj_int16_t *play_frm ) + pj_int16_t *play_frm ) { /* If EC algo has playback handler, just pass the frame. */ if (echo->op->ec_playback) { - return (*echo->op->ec_playback)(echo->state, play_frm); + return (*echo->op->ec_playback)(echo->state, play_frm); } /* Playing frame should be stored, as it will be used by echo_capture() @@ -385,28 +384,28 @@ PJ_DEF(pj_status_t) pjmedia_echo_playback( pjmedia_echo_state *echo, * by the speaker. */ pjmedia_copy_samples(echo->frm_buf, play_frm, - echo->samples_per_frame); + echo->samples_per_frame); pjmedia_delay_buf_put(echo->delay_buf, echo->frm_buf); if (!echo->lat_ready) { - /* We've not built enough latency in the buffer, so put this frame - * in the latency buffer list. - */ - struct frame *frm; - - if (pj_list_empty(&echo->lat_free)) { - echo->lat_ready = PJ_TRUE; - PJ_LOG(5,(echo->obj_name, "Latency bufferring complete")); - return PJ_SUCCESS; - } - - frm = echo->lat_free.prev; - pj_list_erase(frm); - - /* Move one frame from delay buffer to the latency buffer. */ - pjmedia_delay_buf_get(echo->delay_buf, echo->frm_buf); - pjmedia_copy_samples(frm->buf, echo->frm_buf, echo->samples_per_frame); - pj_list_push_back(&echo->lat_buf, frm); + /* We've not built enough latency in the buffer, so put this frame + * in the latency buffer list. + */ + struct frame *frm; + + if (pj_list_empty(&echo->lat_free)) { + echo->lat_ready = PJ_TRUE; + PJ_LOG(5,(echo->obj_name, "Latency bufferring complete")); + return PJ_SUCCESS; + } + + frm = echo->lat_free.prev; + pj_list_erase(frm); + + /* Move one frame from delay buffer to the latency buffer. */ + pjmedia_delay_buf_get(echo->delay_buf, echo->frm_buf); + pjmedia_copy_samples(frm->buf, echo->frm_buf, echo->samples_per_frame); + pj_list_push_back(&echo->lat_buf, frm); } return PJ_SUCCESS; @@ -418,21 +417,21 @@ PJ_DEF(pj_status_t) pjmedia_echo_playback( pjmedia_echo_state *echo, * the microphone. */ PJ_DEF(pj_status_t) pjmedia_echo_capture( pjmedia_echo_state *echo, - pj_int16_t *rec_frm, - unsigned options ) + pj_int16_t *rec_frm, + unsigned options ) { struct frame *oldest_frm; pj_status_t status, rc; /* If EC algo has capture handler, just pass the frame. */ if (echo->op->ec_capture) { - return (*echo->op->ec_capture)(echo->state, rec_frm, options); + return (*echo->op->ec_capture)(echo->state, rec_frm, options); } if (!echo->lat_ready) { - /* Prefetching to fill in the desired latency */ - PJ_LOG(5,(echo->obj_name, "Prefetching..")); - return PJ_SUCCESS; + /* Prefetching to fill in the desired latency */ + PJ_LOG(5,(echo->obj_name, "Prefetching..")); + return PJ_SUCCESS; } /* Retrieve oldest frame from the latency buffer */ @@ -441,15 +440,15 @@ PJ_DEF(pj_status_t) pjmedia_echo_capture( pjmedia_echo_state *echo, /* Cancel echo using this reference frame */ status = pjmedia_echo_cancel(echo, rec_frm, oldest_frm->buf, - options, NULL); + options, NULL); /* Move one frame from delay buffer to the latency buffer. */ rc = pjmedia_delay_buf_get(echo->delay_buf, oldest_frm->buf); if (rc != PJ_SUCCESS) { - /* Ooops.. no frame! */ - PJ_PERROR(5,(echo->obj_name, rc, - "No frame from delay buffer (this will upset EC later)")); - pjmedia_zero_samples(oldest_frm->buf, echo->samples_per_frame); + /* Ooops.. no frame! */ + PJ_PERROR(5,(echo->obj_name, rc, + "No frame from delay buffer (this will upset EC later)")); + pjmedia_zero_samples(oldest_frm->buf, echo->samples_per_frame); } pj_list_push_back(&echo->lat_buf, oldest_frm); @@ -461,13 +460,13 @@ PJ_DEF(pj_status_t) pjmedia_echo_capture( pjmedia_echo_state *echo, * Perform echo cancellation. */ PJ_DEF(pj_status_t) pjmedia_echo_cancel( pjmedia_echo_state *echo, - pj_int16_t *rec_frm, - const pj_int16_t *play_frm, - unsigned options, - void *reserved ) + pj_int16_t *rec_frm, + const pj_int16_t *play_frm, + unsigned options, + void *reserved ) { return (*echo->op->ec_cancel)( echo->state, rec_frm, play_frm, options, - reserved); + reserved); } @@ -475,12 +474,12 @@ PJ_DEF(pj_status_t) pjmedia_echo_cancel( pjmedia_echo_state *echo, * Get the Echo Canceller stats. */ PJ_DEF(pj_status_t) pjmedia_echo_get_stat(pjmedia_echo_state *echo, - pjmedia_echo_stat *p_stat) + pjmedia_echo_stat *p_stat) { PJ_ASSERT_RETURN(p_stat, PJ_EINVAL); if (echo->op->ec_get_stat) - return (*echo->op->ec_get_stat)(echo->state, p_stat); + return (*echo->op->ec_get_stat)(echo->state, p_stat); return PJ_ENOTSUP; } diff --git a/pjmedia/src/pjmedia/echo_internal.h b/pjmedia/src/pjmedia/echo_internal.h index 58d6976c4a..e7834859bd 100644 --- a/pjmedia/src/pjmedia/echo_internal.h +++ b/pjmedia/src/pjmedia/echo_internal.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,56 +28,56 @@ PJ_BEGIN_DECL * Simple echo suppressor */ PJ_DECL(pj_status_t) echo_supp_create(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned tail_ms, - unsigned options, - void **p_state ); + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned tail_ms, + unsigned options, + void **p_state ); PJ_DECL(pj_status_t) echo_supp_destroy(void *state); PJ_DECL(pj_status_t) echo_supp_get_stat(void *state, - pjmedia_echo_stat *p_stat); + pjmedia_echo_stat *p_stat); PJ_DECL(void) echo_supp_reset(void *state); PJ_DECL(pj_status_t) echo_supp_cancel_echo(void *state, - pj_int16_t *rec_frm, - const pj_int16_t *play_frm, - unsigned options, - void *reserved ); + pj_int16_t *rec_frm, + const pj_int16_t *play_frm, + unsigned options, + void *reserved ); PJ_DECL(pj_status_t) speex_aec_create(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned tail_ms, - unsigned options, - void **p_state ); + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned tail_ms, + unsigned options, + void **p_state ); PJ_DECL(pj_status_t) speex_aec_destroy(void *state ); PJ_DECL(void) speex_aec_reset(void *state ); PJ_DECL(pj_status_t) speex_aec_cancel_echo(void *state, - pj_int16_t *rec_frm, - const pj_int16_t *play_frm, - unsigned options, - void *reserved ); + pj_int16_t *rec_frm, + const pj_int16_t *play_frm, + unsigned options, + void *reserved ); PJ_DECL(pj_status_t) speex_aec_playback(void *state, - pj_int16_t *play_frm ); + pj_int16_t *play_frm ); PJ_DECL(pj_status_t) speex_aec_capture(void *state, - pj_int16_t *rec_frm, - unsigned options ); + pj_int16_t *rec_frm, + unsigned options ); PJ_DECL(pj_status_t) ipp_aec_create(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned tail_ms, - unsigned options, - void **p_echo ); + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned tail_ms, + unsigned options, + void **p_echo ); PJ_DECL(pj_status_t) ipp_aec_destroy(void *state ); PJ_DECL(void) ipp_aec_reset(void *state ); PJ_DECL(pj_status_t) ipp_aec_cancel_echo(void *state, - pj_int16_t *rec_frm, - const pj_int16_t *play_frm, - unsigned options, - void *reserved ); + pj_int16_t *rec_frm, + const pj_int16_t *play_frm, + unsigned options, + void *reserved ); PJ_DECL(pj_status_t) webrtc_aec_create(pj_pool_t *pool, unsigned clock_rate, @@ -89,7 +88,7 @@ PJ_DECL(pj_status_t) webrtc_aec_create(pj_pool_t *pool, void **p_echo ); PJ_DECL(pj_status_t) webrtc_aec_destroy(void *state ); PJ_DECL(pj_status_t) webrtc_aec_get_stat(void *state, - pjmedia_echo_stat *p_stat); + pjmedia_echo_stat *p_stat); PJ_DECL(void) webrtc_aec_reset(void *state ); PJ_DECL(pj_status_t) webrtc_aec_cancel_echo(void *state, pj_int16_t *rec_frm, @@ -106,7 +105,7 @@ PJ_DECL(pj_status_t) webrtc_aec3_create(pj_pool_t *pool, void **p_echo ); PJ_DECL(pj_status_t) webrtc_aec3_destroy(void *state ); PJ_DECL(pj_status_t) webrtc_aec3_get_stat(void *state, - pjmedia_echo_stat *p_stat); + pjmedia_echo_stat *p_stat); PJ_DECL(void) webrtc_aec3_reset(void *state ); PJ_DECL(pj_status_t) webrtc_aec3_cancel_echo(void *state, pj_int16_t *rec_frm, diff --git a/pjmedia/src/pjmedia/echo_port.c b/pjmedia/src/pjmedia/echo_port.c index 4c098cc401..5fc24bf556 100644 --- a/pjmedia/src/pjmedia/echo_port.c +++ b/pjmedia/src/pjmedia/echo_port.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,25 +30,25 @@ struct ec { - pjmedia_port base; - pjmedia_port *dn_port; - pjmedia_echo_state *ec; + pjmedia_port base; + pjmedia_port *dn_port; + pjmedia_echo_state *ec; }; static pj_status_t ec_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t ec_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t ec_on_destroy(pjmedia_port *this_port); PJ_DEF(pj_status_t) pjmedia_echo_port_create(pj_pool_t *pool, - pjmedia_port *dn_port, - unsigned tail_ms, - unsigned latency_ms, - unsigned options, - pjmedia_port **p_port ) + pjmedia_port *dn_port, + unsigned tail_ms, + unsigned latency_ms, + unsigned options, + pjmedia_port **p_port ) { const pj_str_t AEC = { "EC", 2 }; pjmedia_audio_format_detail *afd; @@ -61,23 +60,23 @@ PJ_DEF(pj_status_t) pjmedia_echo_port_create(pj_pool_t *pool, afd = pjmedia_format_get_audio_format_detail(&dn_port->info.fmt, PJ_TRUE); PJ_ASSERT_RETURN(afd->bits_per_sample==16 && tail_ms, - PJ_EINVAL); + PJ_EINVAL); /* Create the port and the AEC itself */ ec = PJ_POOL_ZALLOC_T(pool, struct ec); pjmedia_port_info_init(&ec->base.info, &AEC, SIGNATURE, - afd->clock_rate, - afd->channel_count, - afd->bits_per_sample, - PJMEDIA_AFD_SPF(afd)); + afd->clock_rate, + afd->channel_count, + afd->bits_per_sample, + PJMEDIA_AFD_SPF(afd)); status = pjmedia_echo_create2(pool, afd->clock_rate, - afd->channel_count, - PJMEDIA_AFD_SPF(afd), - tail_ms, latency_ms, options, &ec->ec); + afd->channel_count, + PJMEDIA_AFD_SPF(afd), + tail_ms, latency_ms, options, &ec->ec); if (status != PJ_SUCCESS) - return status; + return status; /* More init */ ec->dn_port = dn_port; @@ -93,18 +92,18 @@ PJ_DEF(pj_status_t) pjmedia_echo_port_create(pj_pool_t *pool, static pj_status_t ec_put_frame( pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct ec *ec = (struct ec*)this_port; PJ_ASSERT_RETURN(this_port->info.signature == SIGNATURE, PJ_EINVAL); if (frame->type == PJMEDIA_FRAME_TYPE_NONE ) { - return pjmedia_port_put_frame(ec->dn_port, frame); + return pjmedia_port_put_frame(ec->dn_port, frame); } PJ_ASSERT_RETURN(frame->size == PJMEDIA_PIA_AVG_FSZ(&this_port->info), - PJ_EINVAL); + PJ_EINVAL); pjmedia_echo_capture(ec->ec, (pj_int16_t*)frame->buf, 0); @@ -113,7 +112,7 @@ static pj_status_t ec_put_frame( pjmedia_port *this_port, static pj_status_t ec_get_frame( pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct ec *ec = (struct ec*)this_port; pj_status_t status; @@ -122,8 +121,8 @@ static pj_status_t ec_get_frame( pjmedia_port *this_port, status = pjmedia_port_get_frame(ec->dn_port, frame); if (status!=PJ_SUCCESS || frame->type!=PJMEDIA_FRAME_TYPE_AUDIO) { - pjmedia_zero_samples((pj_int16_t*)frame->buf, - PJMEDIA_PIA_SPF(&this_port->info)); + pjmedia_zero_samples((pj_int16_t*)frame->buf, + PJMEDIA_PIA_SPF(&this_port->info)); } pjmedia_echo_playback(ec->ec, (pj_int16_t*)frame->buf); diff --git a/pjmedia/src/pjmedia/echo_speex.c b/pjmedia/src/pjmedia/echo_speex.c index f2d4fe62a9..e0a61636ad 100644 --- a/pjmedia/src/pjmedia/echo_speex.c +++ b/pjmedia/src/pjmedia/echo_speex.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,15 +33,15 @@ typedef struct speex_ec { - SpeexEchoState *state; - SpeexDecorrState *decorr; + SpeexEchoState *state; + SpeexDecorrState *decorr; SpeexPreprocessState **preprocess; - unsigned samples_per_frame; - unsigned channel_count; - unsigned spf_per_channel; - unsigned options; - pj_int16_t *tmp_frame; + unsigned samples_per_frame; + unsigned channel_count; + unsigned spf_per_channel; + unsigned options; + pj_int16_t *tmp_frame; } speex_ec; @@ -51,12 +50,12 @@ typedef struct speex_ec * Create the AEC. */ PJ_DEF(pj_status_t) speex_aec_create(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned tail_ms, - unsigned options, - void **p_echo ) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned tail_ms, + unsigned options, + void **p_echo ) { speex_ec *echo; int sampling_rate; @@ -74,72 +73,72 @@ PJ_DEF(pj_status_t) speex_aec_create(pj_pool_t *pool, #if 1 echo->state = speex_echo_state_init_mc(echo->spf_per_channel, - clock_rate * tail_ms / 1000, - channel_count, channel_count); + clock_rate * tail_ms / 1000, + channel_count, channel_count); #else if (channel_count != 1) { - PJ_LOG(2,("echo_speex.c", "Multichannel EC is not supported by this " - "echo canceller. It may not work.")); + PJ_LOG(2,("echo_speex.c", "Multichannel EC is not supported by this " + "echo canceller. It may not work.")); } echo->state = speex_echo_state_init(echo->samples_per_frame, - clock_rate * tail_ms / 1000); + clock_rate * tail_ms / 1000); #endif if (echo->state == NULL) - return PJ_ENOMEM; + return PJ_ENOMEM; echo->decorr = speex_decorrelate_new(clock_rate, channel_count, - echo->spf_per_channel); + echo->spf_per_channel); if (echo->decorr == NULL) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Set sampling rate */ sampling_rate = clock_rate; speex_echo_ctl(echo->state, SPEEX_ECHO_SET_SAMPLING_RATE, - &sampling_rate); + &sampling_rate); /* We need to create one state per channel processed. */ echo->preprocess = PJ_POOL_ZALLOC_T(pool, SpeexPreprocessState *); for (i = 0; i < channel_count; i++) { - spx_int32_t enabled; - - echo->preprocess[i] = speex_preprocess_state_init( - echo->spf_per_channel, clock_rate); - if (echo->preprocess[i] == NULL) { - speex_aec_destroy(echo); - return PJ_ENOMEM; - } - - /* Enable/disable AGC & denoise */ - enabled = PJMEDIA_SPEEX_AEC_USE_AGC; - speex_preprocess_ctl(echo->preprocess[i], SPEEX_PREPROCESS_SET_AGC, - &enabled); - - enabled = PJMEDIA_SPEEX_AEC_USE_DENOISE; - speex_preprocess_ctl(echo->preprocess[i], - SPEEX_PREPROCESS_SET_DENOISE, &enabled); - - /* Currently, VAD and dereverb are set at default setting. */ - /* - enabled = 1; - speex_preprocess_ctl(echo->preprocess[i], SPEEX_PREPROCESS_SET_VAD, - &enabled); - speex_preprocess_ctl(echo->preprocess[i], - SPEEX_PREPROCESS_SET_DEREVERB, - &enabled); - */ - - /* Control echo cancellation in the preprocessor */ - speex_preprocess_ctl(echo->preprocess[i], - SPEEX_PREPROCESS_SET_ECHO_STATE, echo->state); + spx_int32_t enabled; + + echo->preprocess[i] = speex_preprocess_state_init( + echo->spf_per_channel, clock_rate); + if (echo->preprocess[i] == NULL) { + speex_aec_destroy(echo); + return PJ_ENOMEM; + } + + /* Enable/disable AGC & denoise */ + enabled = PJMEDIA_SPEEX_AEC_USE_AGC; + speex_preprocess_ctl(echo->preprocess[i], SPEEX_PREPROCESS_SET_AGC, + &enabled); + + enabled = PJMEDIA_SPEEX_AEC_USE_DENOISE; + speex_preprocess_ctl(echo->preprocess[i], + SPEEX_PREPROCESS_SET_DENOISE, &enabled); + + /* Currently, VAD and dereverb are set at default setting. */ + /* + enabled = 1; + speex_preprocess_ctl(echo->preprocess[i], SPEEX_PREPROCESS_SET_VAD, + &enabled); + speex_preprocess_ctl(echo->preprocess[i], + SPEEX_PREPROCESS_SET_DEREVERB, + &enabled); + */ + + /* Control echo cancellation in the preprocessor */ + speex_preprocess_ctl(echo->preprocess[i], + SPEEX_PREPROCESS_SET_ECHO_STATE, echo->state); } /* Create temporary frame for echo cancellation */ echo->tmp_frame = (pj_int16_t*) pj_pool_zalloc(pool, sizeof(pj_int16_t) * - channel_count * - samples_per_frame); + channel_count * + samples_per_frame); if (!echo->tmp_frame) { - speex_aec_destroy(echo); - return PJ_ENOMEM; + speex_aec_destroy(echo); + return PJ_ENOMEM; } /* Done */ @@ -160,23 +159,23 @@ PJ_DEF(pj_status_t) speex_aec_destroy(void *state ) PJ_ASSERT_RETURN(echo && echo->state, PJ_EINVAL); if (echo->state) { - speex_echo_state_destroy(echo->state); - echo->state = NULL; + speex_echo_state_destroy(echo->state); + echo->state = NULL; } if (echo->decorr) { - speex_decorrelate_destroy(echo->decorr); - echo->decorr = NULL; + speex_decorrelate_destroy(echo->decorr); + echo->decorr = NULL; } if (echo->preprocess) { for (i = 0; i < echo->channel_count; i++) { - if (echo->preprocess[i]) { - speex_preprocess_state_destroy(echo->preprocess[i]); - echo->preprocess[i] = NULL; - } - } - echo->preprocess = NULL; + if (echo->preprocess[i]) { + speex_preprocess_state_destroy(echo->preprocess[i]); + echo->preprocess[i] = NULL; + } + } + echo->preprocess = NULL; } return PJ_SUCCESS; @@ -197,44 +196,44 @@ PJ_DEF(void) speex_aec_reset(void *state ) * Perform echo cancellation. */ PJ_DEF(pj_status_t) speex_aec_cancel_echo( void *state, - pj_int16_t *rec_frm, - const pj_int16_t *play_frm, - unsigned options, - void *reserved ) + pj_int16_t *rec_frm, + const pj_int16_t *play_frm, + unsigned options, + void *reserved ) { speex_ec *echo = (speex_ec*) state; unsigned i; /* Sanity checks */ PJ_ASSERT_RETURN(echo && rec_frm && play_frm && options==0 && - reserved==NULL, PJ_EINVAL); + reserved==NULL, PJ_EINVAL); /* Cancel echo, put output in temporary buffer */ speex_echo_cancellation(echo->state, (const spx_int16_t*)rec_frm, - (const spx_int16_t*)play_frm, - (spx_int16_t*)echo->tmp_frame); + (const spx_int16_t*)play_frm, + (spx_int16_t*)echo->tmp_frame); /* Preprocess output per channel */ for (i = 0; i < echo->channel_count; i++) { - spx_int16_t *buf = (spx_int16_t*)echo->tmp_frame; - unsigned j; + spx_int16_t *buf = (spx_int16_t*)echo->tmp_frame; + unsigned j; /* De-interleave each channel. */ if (echo->channel_count > 1) { - for (j = 0; j < echo->spf_per_channel; j++) { - rec_frm[j] = echo->tmp_frame[j * echo->channel_count + i]; - } - buf = (spx_int16_t*)rec_frm; - } + for (j = 0; j < echo->spf_per_channel; j++) { + rec_frm[j] = echo->tmp_frame[j * echo->channel_count + i]; + } + buf = (spx_int16_t*)rec_frm; + } - speex_preprocess_run(echo->preprocess[i], buf); + speex_preprocess_run(echo->preprocess[i], buf); if (echo->channel_count > 1) { - for (j = 0; j < echo->spf_per_channel; j++) { - echo->tmp_frame[j * echo->channel_count + i] = rec_frm[j]; - } - } + for (j = 0; j < echo->spf_per_channel; j++) { + echo->tmp_frame[j * echo->channel_count + i] = rec_frm[j]; + } + } } /* Copy temporary buffer back to original rec_frm */ @@ -248,7 +247,7 @@ PJ_DEF(pj_status_t) speex_aec_cancel_echo( void *state, * Let AEC know that a frame was queued to be played. */ PJ_DEF(pj_status_t) speex_aec_playback( void *state, - pj_int16_t *play_frm ) + pj_int16_t *play_frm ) { speex_ec *echo = (speex_ec*) state; @@ -259,9 +258,9 @@ PJ_DEF(pj_status_t) speex_aec_playback( void *state, * cancellation only . */ if (echo->channel_count > 1) { - pjmedia_copy_samples(echo->tmp_frame, play_frm, echo->samples_per_frame); - speex_decorrelate(echo->decorr, (spx_int16_t*)echo->tmp_frame, - (spx_int16_t*)play_frm, 100); + pjmedia_copy_samples(echo->tmp_frame, play_frm, echo->samples_per_frame); + speex_decorrelate(echo->decorr, (spx_int16_t*)echo->tmp_frame, + (spx_int16_t*)play_frm, 100); } speex_echo_playback(echo->state, (spx_int16_t*)play_frm); @@ -274,8 +273,8 @@ PJ_DEF(pj_status_t) speex_aec_playback( void *state, * Perform echo cancellation to captured frame. */ PJ_DEF(pj_status_t) speex_aec_capture( void *state, - pj_int16_t *rec_frm, - unsigned options ) + pj_int16_t *rec_frm, + unsigned options ) { speex_ec *echo = (speex_ec*) state; unsigned i; @@ -287,29 +286,29 @@ PJ_DEF(pj_status_t) speex_aec_capture( void *state, /* Cancel echo */ speex_echo_capture(echo->state, - (spx_int16_t*)rec_frm, - (spx_int16_t*)echo->tmp_frame); + (spx_int16_t*)rec_frm, + (spx_int16_t*)echo->tmp_frame); /* Apply preprocessing per channel. */ for (i = 0; i < echo->channel_count; i++) { - spx_int16_t *buf = (spx_int16_t*)echo->tmp_frame; - unsigned j; + spx_int16_t *buf = (spx_int16_t*)echo->tmp_frame; + unsigned j; /* De-interleave each channel. */ if (echo->channel_count > 1) { - for (j = 0; j < echo->spf_per_channel; j++) { - rec_frm[j] = echo->tmp_frame[j * echo->channel_count + i]; - } - buf = (spx_int16_t*)rec_frm; - } + for (j = 0; j < echo->spf_per_channel; j++) { + rec_frm[j] = echo->tmp_frame[j * echo->channel_count + i]; + } + buf = (spx_int16_t*)rec_frm; + } - speex_preprocess_run(echo->preprocess[i], buf); + speex_preprocess_run(echo->preprocess[i], buf); if (echo->channel_count > 1) { - for (j = 0; j < echo->spf_per_channel; j++) { - echo->tmp_frame[j * echo->channel_count + i] = rec_frm[j]; - } - } + for (j = 0; j < echo->spf_per_channel; j++) { + echo->tmp_frame[j * echo->channel_count + i] = rec_frm[j]; + } + } } pjmedia_copy_samples(rec_frm, echo->tmp_frame, echo->samples_per_frame); diff --git a/pjmedia/src/pjmedia/echo_suppress.c b/pjmedia/src/pjmedia/echo_suppress.c index c9ebfdb3d5..6b4606a4ce 100644 --- a/pjmedia/src/pjmedia/echo_suppress.c +++ b/pjmedia/src/pjmedia/echo_suppress.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,52 +30,52 @@ #include "echo_internal.h" -#define THIS_FILE "echo_suppress.c" +#define THIS_FILE "echo_suppress.c" /* Maximum float constant */ -#define MAX_FLOAT (float)1.701411e38 +#define MAX_FLOAT (float)1.701411e38 /* The effective learn duration (in seconds) before we declare that learning * is complete. The actual learning duration itself may be longer depending * on the conversation pattern (e.g. we can't detect echo if speaker is only * playing silence). */ -#define MAX_CALC_DURATION_SEC 3 +#define MAX_CALC_DURATION_SEC 3 /* The internal audio segment length, in milliseconds. 10ms shold be good * and no need to change it. */ -#define SEGMENT_PTIME 10 +#define SEGMENT_PTIME 10 /* The length of the template signal in milliseconds. The longer the template, * the better correlation will be found, at the expense of more processing * and longer learning time. */ -#define TEMPLATE_PTIME 200 +#define TEMPLATE_PTIME 200 /* How long to look back in the past to see if either mic or speaker is * active. */ -#define SIGNAL_LOOKUP_MSEC 200 +#define SIGNAL_LOOKUP_MSEC 200 /* The minimum level value to be considered as talking, in uLaw complement * (0-255). */ -#define MIN_SIGNAL_ULAW 35 +#define MIN_SIGNAL_ULAW 35 /* The period (in seconds) on which the ES will analize it's effectiveness, * and it may trigger soft-reset to force recalculation. */ -#define CHECK_PERIOD 30 +#define CHECK_PERIOD 30 /* Maximum signal level of average echo residue (in uLaw complement). When * the residue value exceeds this value, we force the ES to re-learn. */ -#define MAX_RESIDUE 2.5 +#define MAX_RESIDUE 2.5 #if 0 -# define TRACE_(expr) PJ_LOG(5,expr) +# define TRACE_(expr) PJ_LOG(5,expr) static const char *state_names[] = { @@ -94,33 +93,33 @@ static const char *state_names[] = PJ_INLINE(float) FABS(float val) { if (val < 0) - return -val; + return -val; else - return val; + return val; } #if defined(PJ_HAS_FLOATING_POINT) && PJ_HAS_FLOATING_POINT!=0 typedef float pj_ufloat_t; -# define pj_ufloat_from_float(f) (f) -# define pj_ufloat_mul_u(val1, f) ((val1) * (f)) -# define pj_ufloat_mul_i(val1, f) ((val1) * (f)) +# define pj_ufloat_from_float(f) (f) +# define pj_ufloat_mul_u(val1, f) ((val1) * (f)) +# define pj_ufloat_mul_i(val1, f) ((val1) * (f)) #else typedef pj_uint32_t pj_ufloat_t; pj_ufloat_t pj_ufloat_from_float(float f) { - return (pj_ufloat_t)(f * 65536); + return (pj_ufloat_t)(f * 65536); } unsigned pj_ufloat_mul_u(unsigned val1, pj_ufloat_t val2) { - return (val1 * val2) >> 16; + return (val1 * val2) >> 16; } int pj_ufloat_mul_i(int val1, pj_ufloat_t val2) { - return (val1 * (pj_int32_t)val2) >> 16; + return (val1 * (pj_int32_t)val2) >> 16; } #endif @@ -221,44 +220,44 @@ typedef enum talk_state */ typedef struct echo_supp { - unsigned clock_rate; /* Clock rate. */ - pj_uint16_t samples_per_frame; /* Frame length in samples */ - pj_uint16_t samples_per_segment;/* Segment length in samples */ - pj_uint16_t tail_ms; /* Tail length in milliseconds */ - pj_uint16_t tail_samples; /* Tail length in samples. */ - - pj_bool_t learning; /* Are we still learning yet? */ - talk_state_t talk_state; /* Current talking state */ - int tail_index; /* Echo location, -1 if not found */ - - unsigned max_calc; /* # of calc before learning complete. - (see MAX_CALC_DURATION_SEC) */ - unsigned calc_cnt; /* Number of calculations so far */ - - unsigned update_cnt; /* # of updates */ - unsigned templ_cnt; /* Template length, in # of segments */ - unsigned tail_cnt; /* Tail length, in # of segments */ - unsigned play_hist_cnt; /* # of segments in play_hist */ - pj_uint16_t *play_hist; /* Array of playback levels */ - pj_uint16_t *rec_hist; /* Array of rec levels */ - - float *corr_sum; /* Array of corr for each tail pos. */ - float *tmp_corr; /* Temporary corr array calculation */ - float best_corr; /* Best correlation so far. */ - - unsigned sum_rec_level; /* Running sum of level in rec_hist */ - float rec_corr; /* Running corr in rec_hist. */ - - unsigned sum_play_level0; /* Running sum of level for first pos */ - float play_corr0; /* Running corr for first pos . */ - - float *min_factor; /* Array of minimum scaling factor */ - float *avg_factor; /* Array of average scaling factor */ - float *tmp_factor; /* Array to store provisional result */ - - unsigned running_cnt; /* Running duration in # of frames */ - float residue; /* Accummulated echo residue. */ - float last_factor; /* Last factor applied to mic signal */ + unsigned clock_rate; /* Clock rate. */ + pj_uint16_t samples_per_frame; /* Frame length in samples */ + pj_uint16_t samples_per_segment;/* Segment length in samples */ + pj_uint16_t tail_ms; /* Tail length in milliseconds */ + pj_uint16_t tail_samples; /* Tail length in samples. */ + + pj_bool_t learning; /* Are we still learning yet? */ + talk_state_t talk_state; /* Current talking state */ + int tail_index; /* Echo location, -1 if not found */ + + unsigned max_calc; /* # of calc before learning complete. + (see MAX_CALC_DURATION_SEC) */ + unsigned calc_cnt; /* Number of calculations so far */ + + unsigned update_cnt; /* # of updates */ + unsigned templ_cnt; /* Template length, in # of segments */ + unsigned tail_cnt; /* Tail length, in # of segments */ + unsigned play_hist_cnt; /* # of segments in play_hist */ + pj_uint16_t *play_hist; /* Array of playback levels */ + pj_uint16_t *rec_hist; /* Array of rec levels */ + + float *corr_sum; /* Array of corr for each tail pos. */ + float *tmp_corr; /* Temporary corr array calculation */ + float best_corr; /* Best correlation so far. */ + + unsigned sum_rec_level; /* Running sum of level in rec_hist */ + float rec_corr; /* Running corr in rec_hist. */ + + unsigned sum_play_level0; /* Running sum of level for first pos */ + float play_corr0; /* Running corr for first pos . */ + + float *min_factor; /* Array of minimum scaling factor */ + float *avg_factor; /* Array of average scaling factor */ + float *tmp_factor; /* Array to store provisional result */ + + unsigned running_cnt; /* Running duration in # of frames */ + float residue; /* Accummulated echo residue. */ + float last_factor; /* Last factor applied to mic signal */ } echo_supp; @@ -267,12 +266,12 @@ typedef struct echo_supp * Create. */ PJ_DEF(pj_status_t) echo_supp_create( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned tail_ms, - unsigned options, - void **p_state ) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned tail_ms, + unsigned options, + void **p_state ) { echo_supp *ec; @@ -280,7 +279,7 @@ PJ_DEF(pj_status_t) echo_supp_create( pj_pool_t *pool, PJ_UNUSED_ARG(options); PJ_ASSERT_RETURN(samples_per_frame >= SEGMENT_PTIME * clock_rate / 1000, - PJ_ENOTSUP); + PJ_ENOTSUP); ec = PJ_POOL_ZALLOC_T(pool, struct echo_supp); ec->clock_rate = clock_rate; @@ -294,32 +293,32 @@ PJ_DEF(pj_status_t) echo_supp_create( pj_pool_t *pool, ec->play_hist_cnt = (pj_uint16_t)(ec->tail_cnt+ec->templ_cnt); ec->max_calc = (pj_uint16_t)(MAX_CALC_DURATION_SEC * clock_rate / - ec->samples_per_segment); + ec->samples_per_segment); ec->rec_hist = (pj_uint16_t*) - pj_pool_alloc(pool, ec->templ_cnt * - sizeof(ec->rec_hist[0])); + pj_pool_alloc(pool, ec->templ_cnt * + sizeof(ec->rec_hist[0])); /* Note: play history has twice number of elements */ ec->play_hist = (pj_uint16_t*) - pj_pool_alloc(pool, ec->play_hist_cnt * - sizeof(ec->play_hist[0])); + pj_pool_alloc(pool, ec->play_hist_cnt * + sizeof(ec->play_hist[0])); ec->corr_sum = (float*) - pj_pool_alloc(pool, ec->tail_cnt * - sizeof(ec->corr_sum[0])); + pj_pool_alloc(pool, ec->tail_cnt * + sizeof(ec->corr_sum[0])); ec->tmp_corr = (float*) - pj_pool_alloc(pool, ec->tail_cnt * - sizeof(ec->tmp_corr[0])); + pj_pool_alloc(pool, ec->tail_cnt * + sizeof(ec->tmp_corr[0])); ec->min_factor = (float*) - pj_pool_alloc(pool, ec->tail_cnt * - sizeof(ec->min_factor[0])); + pj_pool_alloc(pool, ec->tail_cnt * + sizeof(ec->min_factor[0])); ec->avg_factor = (float*) - pj_pool_alloc(pool, ec->tail_cnt * - sizeof(ec->avg_factor[0])); + pj_pool_alloc(pool, ec->tail_cnt * + sizeof(ec->avg_factor[0])); ec->tmp_factor = (float*) - pj_pool_alloc(pool, ec->tail_cnt * - sizeof(ec->tmp_factor[0])); + pj_pool_alloc(pool, ec->tail_cnt * + sizeof(ec->tmp_factor[0])); echo_supp_reset(ec); *p_state = ec; @@ -349,8 +348,8 @@ PJ_DEF(void) echo_supp_reset(void *state) pj_bzero(ec->play_hist, ec->play_hist_cnt * sizeof(ec->play_hist[0])); for (i=0; itail_cnt; ++i) { - ec->corr_sum[i] = ec->avg_factor[i] = 0; - ec->min_factor[i] = MAX_FLOAT; + ec->corr_sum[i] = ec->avg_factor[i] = 0; + ec->min_factor[i] = MAX_FLOAT; } ec->update_cnt = 0; @@ -377,7 +376,7 @@ PJ_DEF(void) echo_supp_soft_reset(void *state) echo_supp *ec = (echo_supp*) state; for (i=0; itail_cnt; ++i) { - ec->corr_sum[i] = 0; + ec->corr_sum[i] = 0; } ec->update_cnt = 0; @@ -395,17 +394,17 @@ PJ_DEF(void) echo_supp_soft_reset(void *state) /* Set state */ static void echo_supp_set_state(echo_supp *ec, talk_state_t state, - unsigned level) + unsigned level) { PJ_UNUSED_ARG(level); if (state != ec->talk_state) { - TRACE_((THIS_FILE, "[%03d.%03d] %s --> %s, level=%u", - (ec->update_cnt * SEGMENT_PTIME / 1000), - ((ec->update_cnt * SEGMENT_PTIME) % 1000), - state_names[ec->talk_state], - state_names[state], level)); - ec->talk_state = state; + TRACE_((THIS_FILE, "[%03d.%03d] %s --> %s, level=%u", + (ec->update_cnt * SEGMENT_PTIME / 1000), + ((ec->update_cnt * SEGMENT_PTIME) % 1000), + state_names[ec->talk_state], + state_names[state], level)); + ec->talk_state = state; } } @@ -413,7 +412,7 @@ static void echo_supp_set_state(echo_supp *ec, talk_state_t state, * Update EC state */ static void echo_supp_update(echo_supp *ec, pj_int16_t *rec_frm, - const pj_int16_t *play_frm) + const pj_int16_t *play_frm) { int prev_index; unsigned i, j, frm_level, sum_play_level, ulaw; @@ -422,7 +421,7 @@ static void echo_supp_update(echo_supp *ec, pj_int16_t *rec_frm, ++ec->update_cnt; if (ec->update_cnt > 0x7FFFFFFF) - ec->update_cnt = 0x7FFFFFFF; /* Detect overflow */ + ec->update_cnt = 0x7FFFFFFF; /* Detect overflow */ /* Calculate current play frame level */ frm_level = pjmedia_calc_avg_signal(play_frm, ec->samples_per_segment); @@ -449,33 +448,33 @@ static void echo_supp_update(echo_supp *ec, pj_int16_t *rec_frm, /* Can't do the calc until the play history is full. */ if (ec->update_cnt < ec->play_hist_cnt) - return; + return; /* Skip if learning is done */ if (!ec->learning) - return; + return; /* Calculate rec signal pattern */ if (ec->sum_rec_level == 0) { - /* Buffer has just been filled up, do full calculation */ - ec->rec_corr = 0; - ec->sum_rec_level = 0; - for (i=0; i < ec->templ_cnt-1; ++i) { - float corr; - corr = (float)ec->rec_hist[i+1] / ec->rec_hist[i]; - ec->rec_corr += corr; - ec->sum_rec_level += ec->rec_hist[i]; - } - ec->sum_rec_level += ec->rec_hist[i]; + /* Buffer has just been filled up, do full calculation */ + ec->rec_corr = 0; + ec->sum_rec_level = 0; + for (i=0; i < ec->templ_cnt-1; ++i) { + float corr; + corr = (float)ec->rec_hist[i+1] / ec->rec_hist[i]; + ec->rec_corr += corr; + ec->sum_rec_level += ec->rec_hist[i]; + } + ec->sum_rec_level += ec->rec_hist[i]; } else { - /* Update from previous calculation */ - ec->sum_rec_level = ec->sum_rec_level - old_rec_frm_level + - ec->rec_hist[ec->templ_cnt-1]; - ec->rec_corr = ec->rec_corr - ((float)ec->rec_hist[0] / - old_rec_frm_level) + - ((float)ec->rec_hist[ec->templ_cnt-1] / - ec->rec_hist[ec->templ_cnt-2]); + /* Update from previous calculation */ + ec->sum_rec_level = ec->sum_rec_level - old_rec_frm_level + + ec->rec_hist[ec->templ_cnt-1]; + ec->rec_corr = ec->rec_corr - ((float)ec->rec_hist[0] / + old_rec_frm_level) + + ((float)ec->rec_hist[ec->templ_cnt-1] / + ec->rec_hist[ec->templ_cnt-2]); } /* Iterate through the play history and calculate the signal correlation @@ -487,28 +486,28 @@ static void echo_supp_update(echo_supp *ec, pj_int16_t *rec_frm, * First phase: do full calculation for the first position */ if (ec->sum_play_level0 == 0) { - /* Buffer has just been filled up, do full calculation */ - sum_play_level = 0; - play_corr = 0; - for (j=0; jtempl_cnt-1; ++j) { - float corr; - corr = (float)ec->play_hist[j+1] / ec->play_hist[j]; - play_corr += corr; - sum_play_level += ec->play_hist[j]; - } - sum_play_level += ec->play_hist[j]; - ec->sum_play_level0 = sum_play_level; - ec->play_corr0 = play_corr; + /* Buffer has just been filled up, do full calculation */ + sum_play_level = 0; + play_corr = 0; + for (j=0; jtempl_cnt-1; ++j) { + float corr; + corr = (float)ec->play_hist[j+1] / ec->play_hist[j]; + play_corr += corr; + sum_play_level += ec->play_hist[j]; + } + sum_play_level += ec->play_hist[j]; + ec->sum_play_level0 = sum_play_level; + ec->play_corr0 = play_corr; } else { - /* Update from previous calculation */ - ec->sum_play_level0 = ec->sum_play_level0 - old_play_frm_level + - ec->play_hist[ec->templ_cnt-1]; - ec->play_corr0 = ec->play_corr0 - ((float)ec->play_hist[0] / - old_play_frm_level) + - ((float)ec->play_hist[ec->templ_cnt-1] / - ec->play_hist[ec->templ_cnt-2]); - sum_play_level = ec->sum_play_level0; - play_corr = ec->play_corr0; + /* Update from previous calculation */ + ec->sum_play_level0 = ec->sum_play_level0 - old_play_frm_level + + ec->play_hist[ec->templ_cnt-1]; + ec->play_corr0 = ec->play_corr0 - ((float)ec->play_hist[0] / + old_play_frm_level) + + ((float)ec->play_hist[ec->templ_cnt-1] / + ec->play_hist[ec->templ_cnt-2]); + sum_play_level = ec->sum_play_level0; + play_corr = ec->play_corr0; } ec->tmp_corr[0] = FABS(play_corr - ec->rec_corr); ec->tmp_factor[0] = (float)ec->sum_rec_level / sum_play_level; @@ -516,57 +515,57 @@ static void echo_supp_update(echo_supp *ec, pj_int16_t *rec_frm, /* Bail out if remote isn't talking */ ulaw = pjmedia_linear2ulaw(sum_play_level/ec->templ_cnt) ^ 0xFF; if (ulaw < MIN_SIGNAL_ULAW) { - echo_supp_set_state(ec, ST_REM_SILENT, ulaw); - return; + echo_supp_set_state(ec, ST_REM_SILENT, ulaw); + return; } /* Bail out if local user is talking */ if (ec->sum_rec_level >= sum_play_level) { - echo_supp_set_state(ec, ST_LOCAL_TALK, ulaw); - return; + echo_supp_set_state(ec, ST_LOCAL_TALK, ulaw); + return; } /* * Second phase: do incremental calculation for the rest of positions */ for (i=1; i < ec->tail_cnt; ++i) { - unsigned end; + unsigned end; - end = i + ec->templ_cnt; + end = i + ec->templ_cnt; - sum_play_level = sum_play_level - ec->play_hist[i-1] + - ec->play_hist[end-1]; - play_corr = play_corr - ((float)ec->play_hist[i]/ec->play_hist[i-1]) + - ((float)ec->play_hist[end-1]/ec->play_hist[end-2]); + sum_play_level = sum_play_level - ec->play_hist[i-1] + + ec->play_hist[end-1]; + play_corr = play_corr - ((float)ec->play_hist[i]/ec->play_hist[i-1]) + + ((float)ec->play_hist[end-1]/ec->play_hist[end-2]); - /* Bail out if remote isn't talking */ - ulaw = pjmedia_linear2ulaw(sum_play_level/ec->templ_cnt) ^ 0xFF; - if (ulaw < MIN_SIGNAL_ULAW) { - echo_supp_set_state(ec, ST_REM_SILENT, ulaw); - return; - } + /* Bail out if remote isn't talking */ + ulaw = pjmedia_linear2ulaw(sum_play_level/ec->templ_cnt) ^ 0xFF; + if (ulaw < MIN_SIGNAL_ULAW) { + echo_supp_set_state(ec, ST_REM_SILENT, ulaw); + return; + } - /* Bail out if local user is talking */ - if (ec->sum_rec_level >= sum_play_level) { - echo_supp_set_state(ec, ST_LOCAL_TALK, ulaw); - return; - } + /* Bail out if local user is talking */ + if (ec->sum_rec_level >= sum_play_level) { + echo_supp_set_state(ec, ST_LOCAL_TALK, ulaw); + return; + } #if 0 - // disabled: not a good idea if mic throws out loud echo - /* Also bail out if we suspect there's a doubletalk */ - ulaw = pjmedia_linear2ulaw(ec->sum_rec_level/ec->templ_cnt) ^ 0xFF; - if (ulaw > MIN_SIGNAL_ULAW) { - echo_supp_set_state(ec, ST_DOUBLETALK, ulaw); - return; - } + // disabled: not a good idea if mic throws out loud echo + /* Also bail out if we suspect there's a doubletalk */ + ulaw = pjmedia_linear2ulaw(ec->sum_rec_level/ec->templ_cnt) ^ 0xFF; + if (ulaw > MIN_SIGNAL_ULAW) { + echo_supp_set_state(ec, ST_DOUBLETALK, ulaw); + return; + } #endif - /* Calculate correlation and save to temporary array */ - ec->tmp_corr[i] = FABS(play_corr - ec->rec_corr); + /* Calculate correlation and save to temporary array */ + ec->tmp_corr[i] = FABS(play_corr - ec->rec_corr); - /* Also calculate the gain factor between mic and speaker level */ - ec->tmp_factor[i] = (float)ec->sum_rec_level / sum_play_level; - pj_assert(ec->tmp_factor[i] < 1); + /* Also calculate the gain factor between mic and speaker level */ + ec->tmp_factor[i] = (float)ec->sum_rec_level / sum_play_level; + pj_assert(ec->tmp_factor[i] < 1); } /* We seem to have good signal, we can update the EC state */ @@ -577,70 +576,70 @@ static void echo_supp_update(echo_supp *ec, pj_int16_t *rec_frm, */ prev_index = ec->tail_index; for (i=1; itail_cnt-1; ++i) { - float *p = &ec->corr_sum[i], sum; - - /* Accummulate correlation value for this tail position */ - ec->corr_sum[i] += ec->tmp_corr[i]; - - /* Update the min and avg gain factor for this tail position */ - if (ec->tmp_factor[i] < ec->min_factor[i]) - ec->min_factor[i] = ec->tmp_factor[i]; - ec->avg_factor[i] = ((ec->avg_factor[i] * ec->tail_cnt) + - ec->tmp_factor[i]) / - (ec->tail_cnt + 1); - - /* To get the best correlation, also include the correlation - * value of the neighbouring tail locations. - */ - sum = *(p-1) + (*p)*2 + *(p+1); - //sum = *p; - - /* See if we have better correlation value */ - if (sum < ec->best_corr) { - ec->tail_index = i; - ec->best_corr = sum; - } + float *p = &ec->corr_sum[i], sum; + + /* Accummulate correlation value for this tail position */ + ec->corr_sum[i] += ec->tmp_corr[i]; + + /* Update the min and avg gain factor for this tail position */ + if (ec->tmp_factor[i] < ec->min_factor[i]) + ec->min_factor[i] = ec->tmp_factor[i]; + ec->avg_factor[i] = ((ec->avg_factor[i] * ec->tail_cnt) + + ec->tmp_factor[i]) / + (ec->tail_cnt + 1); + + /* To get the best correlation, also include the correlation + * value of the neighbouring tail locations. + */ + sum = *(p-1) + (*p)*2 + *(p+1); + //sum = *p; + + /* See if we have better correlation value */ + if (sum < ec->best_corr) { + ec->tail_index = i; + ec->best_corr = sum; + } } if (ec->tail_index != prev_index) { - unsigned duration; - int imin, iavg; + unsigned duration; + int imin, iavg; - duration = ec->update_cnt * SEGMENT_PTIME; - imin = (int)(ec->min_factor[ec->tail_index] * 1000); - iavg = (int)(ec->avg_factor[ec->tail_index] * 1000); + duration = ec->update_cnt * SEGMENT_PTIME; + imin = (int)(ec->min_factor[ec->tail_index] * 1000); + iavg = (int)(ec->avg_factor[ec->tail_index] * 1000); - PJ_LOG(4,(THIS_FILE, - "Echo suppressor updated at t=%03d.%03ds, echo tail=%d msec" - ", factor min/avg=%d.%03d/%d.%03d", - (duration/1000), (duration%1000), - (ec->tail_cnt-ec->tail_index) * SEGMENT_PTIME, - imin/1000, imin%1000, - iavg/1000, iavg%1000)); + PJ_LOG(4,(THIS_FILE, + "Echo suppressor updated at t=%03d.%03ds, echo tail=%d msec" + ", factor min/avg=%d.%03d/%d.%03d", + (duration/1000), (duration%1000), + (ec->tail_cnt-ec->tail_index) * SEGMENT_PTIME, + imin/1000, imin%1000, + iavg/1000, iavg%1000)); } ++ec->calc_cnt; if (ec->calc_cnt > ec->max_calc) { - unsigned duration; - int imin, iavg; + unsigned duration; + int imin, iavg; - ec->learning = PJ_FALSE; - ec->running_cnt = 0; + ec->learning = PJ_FALSE; + ec->running_cnt = 0; - duration = ec->update_cnt * SEGMENT_PTIME; - imin = (int)(ec->min_factor[ec->tail_index] * 1000); - iavg = (int)(ec->avg_factor[ec->tail_index] * 1000); + duration = ec->update_cnt * SEGMENT_PTIME; + imin = (int)(ec->min_factor[ec->tail_index] * 1000); + iavg = (int)(ec->avg_factor[ec->tail_index] * 1000); - PJ_LOG(4,(THIS_FILE, - "Echo suppressor learning done at t=%03d.%03ds, tail=%d ms" - ", factor min/avg=%d.%03d/%d.%03d", - (duration/1000), (duration%1000), - (ec->tail_cnt-ec->tail_index) * SEGMENT_PTIME, - imin/1000, imin%1000, - iavg/1000, iavg%1000)); + PJ_LOG(4,(THIS_FILE, + "Echo suppressor learning done at t=%03d.%03ds, tail=%d ms" + ", factor min/avg=%d.%03d/%d.%03d", + (duration/1000), (duration%1000), + (ec->tail_cnt-ec->tail_index) * SEGMENT_PTIME, + imin/1000, imin%1000, + iavg/1000, iavg%1000)); } } @@ -648,12 +647,12 @@ static void echo_supp_update(echo_supp *ec, pj_int16_t *rec_frm, /* Amplify frame */ static void amplify_frame(pj_int16_t *frm, unsigned length, - pj_ufloat_t factor) + pj_ufloat_t factor) { unsigned i; for (i=0; isamples_per_frame / ec->samples_per_segment; pj_assert(N>0); for (i=0; isamples_per_segment; - echo_supp_update(ec, rec_frm+pos, play_frm+pos); + unsigned pos = i * ec->samples_per_segment; + echo_supp_update(ec, rec_frm+pos, play_frm+pos); } if (ec->tail_index < 0) { - /* Not ready */ + /* Not ready */ } else { - unsigned lookup_cnt, rec_level=0, play_level=0; - unsigned tail_cnt; - float factor; - - /* How many previous segments to lookup */ - lookup_cnt = SIGNAL_LOOKUP_MSEC / SEGMENT_PTIME; - if (lookup_cnt > ec->templ_cnt) - lookup_cnt = ec->templ_cnt; - - /* Lookup in recording history to get maximum mic level, to see - * if local user is currently talking - */ - for (i=ec->templ_cnt - lookup_cnt; i < ec->templ_cnt; ++i) { - if (ec->rec_hist[i] > rec_level) - rec_level = ec->rec_hist[i]; - } - rec_level = pjmedia_linear2ulaw(rec_level) ^ 0xFF; - - /* Calculate the detected tail length, in # of segments */ - tail_cnt = (ec->tail_cnt - ec->tail_index); - - /* Lookup in playback history to get max speaker level, to see - * if remote user is currently talking - */ - for (i=ec->play_hist_cnt -lookup_cnt -tail_cnt; - iplay_hist_cnt-tail_cnt; ++i) - { - if (ec->play_hist[i] > play_level) - play_level = ec->play_hist[i]; - } - play_level = pjmedia_linear2ulaw(play_level) ^ 0xFF; - - if (rec_level >= MIN_SIGNAL_ULAW) { - if (play_level < MIN_SIGNAL_ULAW) { - /* Mic is talking, speaker is idle. Let mic signal pass as is. - */ - factor = 1.0; - echo_supp_set_state(ec, ST_LOCAL_TALK, rec_level); - } else if (rec_level > play_level) { - /* Seems that both are talking. Scale the mic signal - * down a little bit to reduce echo, while allowing both - * parties to talk at the same time. - */ - factor = (float)(ec->avg_factor[ec->tail_index] * 2); - echo_supp_set_state(ec, ST_DOUBLETALK, rec_level); - } else { - /* Speaker is active, but we've picked up large signal in - * the microphone. Assume that this is an echo, so bring - * the level down to minimum too. - */ - factor = ec->min_factor[ec->tail_index] / 2; - echo_supp_set_state(ec, ST_REM_TALK, play_level); - } - } else { - if (play_level < MIN_SIGNAL_ULAW) { - /* Both mic and speaker seems to be idle. Also scale the - * mic signal down with average factor to reduce low power - * echo. - */ - factor = ec->avg_factor[ec->tail_index] * 3 / 2; - echo_supp_set_state(ec, ST_REM_SILENT, rec_level); - } else { - /* Mic is idle, but there's something playing in speaker. - * Scale the mic down to minimum - */ - factor = ec->min_factor[ec->tail_index] / 2; - echo_supp_set_state(ec, ST_REM_TALK, play_level); - } - } - - /* Smoothen the transition */ - if (factor >= ec->last_factor) - factor = (factor + ec->last_factor) / 2; - else - factor = (factor + ec->last_factor*19) / 20; - - /* Amplify frame */ - amplify_frame(rec_frm, ec->samples_per_frame, - pj_ufloat_from_float(factor)); - ec->last_factor = factor; - - if (ec->talk_state == ST_REM_TALK) { - unsigned level, recalc_cnt; - - /* Get the adjusted frame signal level */ - level = pjmedia_calc_avg_signal(rec_frm, ec->samples_per_frame); - level = pjmedia_linear2ulaw(level) ^ 0xFF; - - /* Accumulate average echo residue to see the ES effectiveness */ - ec->residue = ((ec->residue * ec->running_cnt) + level) / - (ec->running_cnt + 1); - - ++ec->running_cnt; - - /* Check if we need to re-learn */ - recalc_cnt = CHECK_PERIOD * ec->clock_rate / ec->samples_per_frame; - if (ec->running_cnt > recalc_cnt) { - int iresidue; - - iresidue = (int)(ec->residue*1000); - - PJ_LOG(5,(THIS_FILE, "Echo suppressor residue = %d.%03d", - iresidue/1000, iresidue%1000)); - - if (ec->residue > MAX_RESIDUE && !ec->learning) { - echo_supp_soft_reset(ec); - ec->residue = 0; - } else { - ec->running_cnt = 0; - ec->residue = 0; - } - } - } + unsigned lookup_cnt, rec_level=0, play_level=0; + unsigned tail_cnt; + float factor; + + /* How many previous segments to lookup */ + lookup_cnt = SIGNAL_LOOKUP_MSEC / SEGMENT_PTIME; + if (lookup_cnt > ec->templ_cnt) + lookup_cnt = ec->templ_cnt; + + /* Lookup in recording history to get maximum mic level, to see + * if local user is currently talking + */ + for (i=ec->templ_cnt - lookup_cnt; i < ec->templ_cnt; ++i) { + if (ec->rec_hist[i] > rec_level) + rec_level = ec->rec_hist[i]; + } + rec_level = pjmedia_linear2ulaw(rec_level) ^ 0xFF; + + /* Calculate the detected tail length, in # of segments */ + tail_cnt = (ec->tail_cnt - ec->tail_index); + + /* Lookup in playback history to get max speaker level, to see + * if remote user is currently talking + */ + for (i=ec->play_hist_cnt -lookup_cnt -tail_cnt; + iplay_hist_cnt-tail_cnt; ++i) + { + if (ec->play_hist[i] > play_level) + play_level = ec->play_hist[i]; + } + play_level = pjmedia_linear2ulaw(play_level) ^ 0xFF; + + if (rec_level >= MIN_SIGNAL_ULAW) { + if (play_level < MIN_SIGNAL_ULAW) { + /* Mic is talking, speaker is idle. Let mic signal pass as is. + */ + factor = 1.0; + echo_supp_set_state(ec, ST_LOCAL_TALK, rec_level); + } else if (rec_level > play_level) { + /* Seems that both are talking. Scale the mic signal + * down a little bit to reduce echo, while allowing both + * parties to talk at the same time. + */ + factor = (float)(ec->avg_factor[ec->tail_index] * 2); + echo_supp_set_state(ec, ST_DOUBLETALK, rec_level); + } else { + /* Speaker is active, but we've picked up large signal in + * the microphone. Assume that this is an echo, so bring + * the level down to minimum too. + */ + factor = ec->min_factor[ec->tail_index] / 2; + echo_supp_set_state(ec, ST_REM_TALK, play_level); + } + } else { + if (play_level < MIN_SIGNAL_ULAW) { + /* Both mic and speaker seems to be idle. Also scale the + * mic signal down with average factor to reduce low power + * echo. + */ + factor = ec->avg_factor[ec->tail_index] * 3 / 2; + echo_supp_set_state(ec, ST_REM_SILENT, rec_level); + } else { + /* Mic is idle, but there's something playing in speaker. + * Scale the mic down to minimum + */ + factor = ec->min_factor[ec->tail_index] / 2; + echo_supp_set_state(ec, ST_REM_TALK, play_level); + } + } + + /* Smoothen the transition */ + if (factor >= ec->last_factor) + factor = (factor + ec->last_factor) / 2; + else + factor = (factor + ec->last_factor*19) / 20; + + /* Amplify frame */ + amplify_frame(rec_frm, ec->samples_per_frame, + pj_ufloat_from_float(factor)); + ec->last_factor = factor; + + if (ec->talk_state == ST_REM_TALK) { + unsigned level, recalc_cnt; + + /* Get the adjusted frame signal level */ + level = pjmedia_calc_avg_signal(rec_frm, ec->samples_per_frame); + level = pjmedia_linear2ulaw(level) ^ 0xFF; + + /* Accumulate average echo residue to see the ES effectiveness */ + ec->residue = ((ec->residue * ec->running_cnt) + level) / + (ec->running_cnt + 1); + + ++ec->running_cnt; + + /* Check if we need to re-learn */ + recalc_cnt = CHECK_PERIOD * ec->clock_rate / ec->samples_per_frame; + if (ec->running_cnt > recalc_cnt) { + int iresidue; + + iresidue = (int)(ec->residue*1000); + + PJ_LOG(5,(THIS_FILE, "Echo suppressor residue = %d.%03d", + iresidue/1000, iresidue%1000)); + + if (ec->residue > MAX_RESIDUE && !ec->learning) { + echo_supp_soft_reset(ec); + ec->residue = 0; + } else { + ec->running_cnt = 0; + ec->residue = 0; + } + } + } } return PJ_SUCCESS; @@ -806,7 +805,7 @@ PJ_DEF(pj_status_t) echo_supp_cancel_echo( void *state, PJ_DEF(pj_status_t) echo_supp_get_stat( void *state, - pjmedia_echo_stat *p_stat) + pjmedia_echo_stat *p_stat) { echo_supp *ec = (echo_supp*) state; @@ -820,14 +819,14 @@ PJ_DEF(pj_status_t) echo_supp_get_stat( void *state, p_stat->stat_info.ptr = p_stat->buf_; p_stat->stat_info.slen = - pj_ansi_snprintf(p_stat->buf_, sizeof(p_stat->buf_), - "Echo suppressor learning %s at t=%03d.%03ds, tail=%d ms,\n" - " factor min/avg=%d.%03d/%d.%03d", - (ec->learning? "in progress": "done"), - (p_stat->duration/1000), (p_stat->duration%1000), - p_stat->tail, - p_stat->min_factor/1000, p_stat->min_factor%1000, - p_stat->avg_factor/1000, p_stat->avg_factor%1000); + pj_ansi_snprintf(p_stat->buf_, sizeof(p_stat->buf_), + "Echo suppressor learning %s at t=%03d.%03ds, tail=%d ms,\n" + " factor min/avg=%d.%03d/%d.%03d", + (ec->learning? "in progress": "done"), + (p_stat->duration/1000), (p_stat->duration%1000), + p_stat->tail, + p_stat->min_factor/1000, p_stat->min_factor%1000, + p_stat->avg_factor/1000, p_stat->avg_factor%1000); return PJ_SUCCESS; } diff --git a/pjmedia/src/pjmedia/echo_webrtc.c b/pjmedia/src/pjmedia/echo_webrtc.c index 7718fbce91..47e211eb1f 100644 --- a/pjmedia/src/pjmedia/echo_webrtc.c +++ b/pjmedia/src/pjmedia/echo_webrtc.c @@ -31,7 +31,7 @@ #include "echo_internal.h" -#define THIS_FILE "echo_webrtc.c" +#define THIS_FILE "echo_webrtc.c" #if PJMEDIA_WEBRTC_AEC_USE_MOBILE == 1 #include @@ -57,20 +57,20 @@ #endif -#define BUF_LEN 160 +#define BUF_LEN 160 /* Set this to 0 to disable metrics calculation. */ -#define SHOW_DELAY_METRICS 1 +#define SHOW_DELAY_METRICS 1 typedef struct webrtc_ec { void *AEC_inst; NsHandle *NS_inst; unsigned options; - unsigned samples_per_frame; - unsigned tail; + unsigned samples_per_frame; + unsigned tail; unsigned clock_rate; - unsigned channel_count; + unsigned channel_count; unsigned subframe_len; sample tmp_buf[BUF_LEN]; sample tmp_buf2[BUF_LEN]; @@ -94,13 +94,13 @@ static void set_config(void *AEC_inst, unsigned options) if (aggr_opt == PJMEDIA_ECHO_AGGRESSIVENESS_CONSERVATIVE) aec_config.echoMode = 0; else if (aggr_opt == PJMEDIA_ECHO_AGGRESSIVENESS_AGGRESSIVE) - aec_config.echoMode = 4; + aec_config.echoMode = 4; aec_config.cngMode = AecmTrue; #else aec_config.nlpMode = kAecNlpModerate; if (aggr_opt == PJMEDIA_ECHO_AGGRESSIVENESS_CONSERVATIVE) - aec_config.nlpMode = kAecNlpConservative; + aec_config.nlpMode = kAecNlpConservative; else if (aggr_opt == PJMEDIA_ECHO_AGGRESSIVENESS_AGGRESSIVE) aec_config.nlpMode = kAecNlpAggressive; else @@ -144,8 +144,8 @@ PJ_DEF(pj_status_t) webrtc_aec_create(pj_pool_t *pool, /* Currently we only support mono. */ if (channel_count != 1) { - PJ_LOG(3, (THIS_FILE, "WebRTC AEC doesn't support stereo")); - return PJ_ENOTSUP; + PJ_LOG(3, (THIS_FILE, "WebRTC AEC doesn't support stereo")); + return PJ_ENOTSUP; } echo->channel_count = channel_count; @@ -156,13 +156,13 @@ PJ_DEF(pj_status_t) webrtc_aec_create(pj_pool_t *pool, if (clock_rate > 8000) echo->subframe_len = 160; else - echo->subframe_len = 80; + echo->subframe_len = 80; echo->options = options; /* Create WebRTC AEC */ echo->AEC_inst = WebRtcAec_Create(); if (!echo->AEC_inst) { - return PJ_ENOMEM; + return PJ_ENOMEM; } /* Init WebRTC AEC */ @@ -170,7 +170,7 @@ PJ_DEF(pj_status_t) webrtc_aec_create(pj_pool_t *pool, if (status != 0) { print_webrtc_aec_error("Init", echo->AEC_inst); WebRtcAec_Free(echo->AEC_inst); - return PJ_ENOTSUP; + return PJ_ENOTSUP; } /* WebRtc is very dependent on delay calculation, which will be passed @@ -205,10 +205,10 @@ PJ_DEF(pj_status_t) webrtc_aec_create(pj_pool_t *pool, #if PJMEDIA_WEBRTC_AEC_USE_MOBILE PJ_LOG(3, (THIS_FILE, "WebRTC AEC mobile successfully created with " - "options %d", options)); + "options %d", options)); #else PJ_LOG(3, (THIS_FILE, "WebRTC AEC successfully created with " - "options %d", options)); + "options %d", options)); #endif /* Done */ @@ -227,8 +227,8 @@ PJ_DEF(pj_status_t) webrtc_aec_destroy(void *state ) PJ_ASSERT_RETURN(echo, PJ_EINVAL); if (echo->AEC_inst) { - WebRtcAec_Free(echo->AEC_inst); - echo->AEC_inst = NULL; + WebRtcAec_Free(echo->AEC_inst); + echo->AEC_inst = NULL; } if (echo->NS_inst) { WebRtcNs_Free(echo->NS_inst); @@ -266,10 +266,10 @@ PJ_DEF(void) webrtc_aec_reset(void *state ) * Perform echo cancellation. */ PJ_DEF(pj_status_t) webrtc_aec_cancel_echo( void *state, - pj_int16_t *rec_frm, - const pj_int16_t *play_frm, - unsigned options, - void *reserved ) + pj_int16_t *rec_frm, + const pj_int16_t *play_frm, + unsigned options, + void *reserved ) { webrtc_ec *echo = (webrtc_ec*) state; int status; @@ -285,7 +285,7 @@ PJ_DEF(pj_status_t) webrtc_aec_cancel_echo( void *state, for(i = echo->samples_per_frame / echo->subframe_len; i > 0; i--) { #if PJMEDIA_WEBRTC_AEC_USE_MOBILE - buf_ptr = &play_frm[frm_idx]; + buf_ptr = &play_frm[frm_idx]; #else for (j = 0; j < echo->subframe_len; j++) { echo->tmp_buf[j] = rec_frm[frm_idx+j]; @@ -302,13 +302,13 @@ PJ_DEF(pj_status_t) webrtc_aec_cancel_echo( void *state, return PJ_EUNKNOWN; } - buf_ptr = echo->tmp_buf; - out_buf_ptr = echo->tmp_buf2; + buf_ptr = echo->tmp_buf; + out_buf_ptr = echo->tmp_buf2; if (echo->NS_inst) { #if PJMEDIA_WEBRTC_AEC_USE_MOBILE - buf_ptr = &rec_frm[frm_idx]; + buf_ptr = &rec_frm[frm_idx]; WebRtcNsx_Process(echo->NS_inst, &buf_ptr, echo->channel_count, - &out_buf_ptr); + &out_buf_ptr); buf_ptr = out_buf_ptr; out_buf_ptr = echo->tmp_buf; #else @@ -319,9 +319,9 @@ PJ_DEF(pj_status_t) webrtc_aec_cancel_echo( void *state, /* Process echo cancellation */ #if PJMEDIA_WEBRTC_AEC_USE_MOBILE status = WebRtcAecm_Process(echo->AEC_inst, &rec_frm[frm_idx], - (echo->NS_inst? buf_ptr: NULL), - out_buf_ptr, echo->subframe_len, - echo->tail); + (echo->NS_inst? buf_ptr: NULL), + out_buf_ptr, echo->subframe_len, + echo->tail); #else status = WebRtcAec_Process(echo->AEC_inst, &buf_ptr, echo->channel_count, &out_buf_ptr, @@ -333,18 +333,18 @@ PJ_DEF(pj_status_t) webrtc_aec_cancel_echo( void *state, } #if !PJMEDIA_WEBRTC_AEC_USE_MOBILE - if (echo->NS_inst) { + if (echo->NS_inst) { /* Noise suppression */ - buf_ptr = echo->tmp_buf2; - out_buf_ptr = echo->tmp_buf; + buf_ptr = echo->tmp_buf2; + out_buf_ptr = echo->tmp_buf; WebRtcNs_Process(echo->NS_inst, &buf_ptr, echo->channel_count, &out_buf_ptr); - } + } #endif - for (j = 0; j < echo->subframe_len; j++) { - rec_frm[frm_idx++] = (pj_int16_t)out_buf_ptr[j]; - } + for (j = 0; j < echo->subframe_len; j++) { + rec_frm[frm_idx++] = (pj_int16_t)out_buf_ptr[j]; + } } return PJ_SUCCESS; @@ -352,12 +352,12 @@ PJ_DEF(pj_status_t) webrtc_aec_cancel_echo( void *state, PJ_DEF(pj_status_t) webrtc_aec_get_stat(void *state, - pjmedia_echo_stat *p_stat) + pjmedia_echo_stat *p_stat) { webrtc_ec *echo = (webrtc_ec*) state; if (WebRtcAec_GetDelayMetrics(echo->AEC_inst, &p_stat->delay, - &p_stat->std, &p_stat->frac_delay) != 0) + &p_stat->std, &p_stat->frac_delay) != 0) { return PJ_EUNKNOWN; } @@ -366,9 +366,9 @@ PJ_DEF(pj_status_t) webrtc_aec_get_stat(void *state, p_stat->stat_info.ptr = p_stat->buf_; p_stat->stat_info.slen = pj_ansi_snprintf(p_stat->buf_, sizeof(p_stat->buf_), - "WebRTC delay metric: median=%d, std=%d, " - "frac of poor delay=%.02f", - p_stat->delay, p_stat->std, p_stat->frac_delay); + "WebRTC delay metric: median=%d, std=%d, " + "frac of poor delay=%.02f", + p_stat->delay, p_stat->std, p_stat->frac_delay); return PJ_SUCCESS; } diff --git a/pjmedia/src/pjmedia/echo_webrtc_aec3.cpp b/pjmedia/src/pjmedia/echo_webrtc_aec3.cpp index c1315ccc48..72d4262226 100644 --- a/pjmedia/src/pjmedia/echo_webrtc_aec3.cpp +++ b/pjmedia/src/pjmedia/echo_webrtc_aec3.cpp @@ -39,18 +39,18 @@ using namespace webrtc; #include "echo_internal.h" -#define THIS_FILE "echo_webrtc_aec3.cpp" +#define THIS_FILE "echo_webrtc_aec3.cpp" typedef struct webrtc_ec { unsigned options; - unsigned samples_per_frame; + unsigned samples_per_frame; unsigned clock_rate; - unsigned channel_count; - unsigned frame_length; - unsigned num_bands; + unsigned channel_count; + unsigned frame_length; + unsigned num_bands; - pj_bool_t get_metrics; + pj_bool_t get_metrics; EchoControl::Metrics metrics; EchoControl *aec; @@ -80,8 +80,8 @@ PJ_DEF(pj_status_t) webrtc_aec3_create(pj_pool_t *pool, PJ_ASSERT_RETURN(echo != NULL, PJ_ENOMEM); if (clock_rate != 16000 && clock_rate != 32000 && clock_rate != 48000) { - PJ_LOG(3, (THIS_FILE, "Unsupported clock rate for WebRTC AEC3")); - return PJ_ENOTSUP; + PJ_LOG(3, (THIS_FILE, "Unsupported clock rate for WebRTC AEC3")); + return PJ_ENOTSUP; } echo->options = options; @@ -92,28 +92,28 @@ PJ_DEF(pj_status_t) webrtc_aec3_create(pj_pool_t *pool, echo->num_bands = clock_rate/16000; echo->aec = new EchoCanceller3(EchoCanceller3Config(), clock_rate, - channel_count, channel_count); + channel_count, channel_count); echo->cap_buf = new AudioBuffer(clock_rate, channel_count, clock_rate, - channel_count, clock_rate, channel_count); + channel_count, clock_rate, channel_count); echo->rend_buf = new AudioBuffer(clock_rate, channel_count, clock_rate, - channel_count, clock_rate, channel_count); + channel_count, clock_rate, channel_count); if (options & PJMEDIA_ECHO_USE_NOISE_SUPPRESSOR) { - NsConfig cfg; - /* Valid values are 6, 12, 18, 21 dB */ - cfg.target_level = NsConfig::SuppressionLevel::k12dB; - echo->ns = new NoiseSuppressor(cfg, clock_rate, channel_count); + NsConfig cfg; + /* Valid values are 6, 12, 18, 21 dB */ + cfg.target_level = NsConfig::SuppressionLevel::k12dB; + echo->ns = new NoiseSuppressor(cfg, clock_rate, channel_count); } if (options & PJMEDIA_ECHO_USE_GAIN_CONTROLLER) { - echo->agc = new GainController2(); - echo->agc->Initialize(clock_rate); - - AudioProcessing::Config::GainController2 cfg; - cfg.adaptive_digital.enabled = true; - if (GainController2::Validate(cfg)) - echo->agc->ApplyConfig(cfg); + echo->agc = new GainController2(); + echo->agc->Initialize(clock_rate); + + AudioProcessing::Config::GainController2 cfg; + cfg.adaptive_digital.enabled = true; + if (GainController2::Validate(cfg)) + echo->agc->ApplyConfig(cfg); } /* Done */ @@ -131,25 +131,25 @@ PJ_DEF(pj_status_t) webrtc_aec3_destroy(void *state ) PJ_ASSERT_RETURN(echo, PJ_EINVAL); if (echo->aec) { - delete echo->aec; - echo->aec = NULL; + delete echo->aec; + echo->aec = NULL; } if (echo->ns) { - delete echo->ns; - echo->ns = NULL; + delete echo->ns; + echo->ns = NULL; } if (echo->agc) { - delete echo->agc; - echo->agc = NULL; + delete echo->agc; + echo->agc = NULL; } if (echo->cap_buf) { - delete echo->cap_buf; - echo->cap_buf = NULL; + delete echo->cap_buf; + echo->cap_buf = NULL; } if (echo->rend_buf) { - delete echo->rend_buf; - echo->rend_buf = NULL; + delete echo->rend_buf; + echo->rend_buf = NULL; } return PJ_SUCCESS; @@ -173,10 +173,10 @@ PJ_DEF(void) webrtc_aec3_reset(void *state ) * Perform echo cancellation. */ PJ_DEF(pj_status_t) webrtc_aec3_cancel_echo(void *state, - pj_int16_t *rec_frm, - const pj_int16_t *play_frm, - unsigned options, - void *reserved ) + pj_int16_t *rec_frm, + const pj_int16_t *play_frm, + unsigned options, + void *reserved ) { webrtc_ec *echo = (webrtc_ec*) state; unsigned i; @@ -188,42 +188,42 @@ PJ_DEF(pj_status_t) webrtc_aec3_cancel_echo(void *state, PJ_ASSERT_RETURN(echo && rec_frm && play_frm, PJ_EINVAL); for (i = 0; i < echo->samples_per_frame; - i += echo->frame_length) + i += echo->frame_length) { - StreamConfig scfg(echo->clock_rate, echo->channel_count); - - echo->cap_buf->CopyFrom(rec_frm + i, scfg); - echo->rend_buf->CopyFrom(play_frm + i, scfg); - - if (echo->clock_rate > 16000) { - echo->cap_buf->SplitIntoFrequencyBands(); - echo->rend_buf->SplitIntoFrequencyBands(); - } - - echo->aec->AnalyzeCapture(echo->cap_buf); - echo->aec->AnalyzeRender(echo->rend_buf); - - if (echo->ns) { - echo->ns->Analyze(*echo->cap_buf); - echo->ns->Process(echo->cap_buf); - } - - echo->aec->ProcessCapture(echo->cap_buf, false); - - if (echo->agc) { - echo->agc->Process(echo->cap_buf); - } - - if (echo->clock_rate > 16000) { - echo->cap_buf->MergeFrequencyBands(); - } - - echo->cap_buf->CopyTo(scfg, rec_frm + i); + StreamConfig scfg(echo->clock_rate, echo->channel_count); + + echo->cap_buf->CopyFrom(rec_frm + i, scfg); + echo->rend_buf->CopyFrom(play_frm + i, scfg); + + if (echo->clock_rate > 16000) { + echo->cap_buf->SplitIntoFrequencyBands(); + echo->rend_buf->SplitIntoFrequencyBands(); + } + + echo->aec->AnalyzeCapture(echo->cap_buf); + echo->aec->AnalyzeRender(echo->rend_buf); + + if (echo->ns) { + echo->ns->Analyze(*echo->cap_buf); + echo->ns->Process(echo->cap_buf); + } + + echo->aec->ProcessCapture(echo->cap_buf, false); + + if (echo->agc) { + echo->agc->Process(echo->cap_buf); + } + + if (echo->clock_rate > 16000) { + echo->cap_buf->MergeFrequencyBands(); + } + + echo->cap_buf->CopyTo(scfg, rec_frm + i); } if (echo->get_metrics) { - echo->metrics = echo->aec->GetMetrics(); - echo->get_metrics = PJ_FALSE; + echo->metrics = echo->aec->GetMetrics(); + echo->get_metrics = PJ_FALSE; } return PJ_SUCCESS; @@ -231,13 +231,13 @@ PJ_DEF(pj_status_t) webrtc_aec3_cancel_echo(void *state, PJ_DEF(pj_status_t) webrtc_aec3_get_stat(void *state, - pjmedia_echo_stat *p_stat) + pjmedia_echo_stat *p_stat) { webrtc_ec *echo = (webrtc_ec*) state; unsigned i = 0; if (!echo || !echo->aec) - return PJ_EINVAL; + return PJ_EINVAL; /* We cannot perform get metrics here since it may cause a race * condition with echo cancellation process and crash with: @@ -260,10 +260,10 @@ PJ_DEF(pj_status_t) webrtc_aec3_get_stat(void *state, p_stat->stat_info.ptr = p_stat->buf_; p_stat->stat_info.slen = pj_ansi_snprintf(p_stat->buf_, sizeof(p_stat->buf_), - "WebRTC AEC3 metrics: delay=%d ms, " - "return loss=%.02f, return loss enh=%.02f", - p_stat->delay, p_stat->return_loss, - p_stat->return_loss_enh); + "WebRTC AEC3 metrics: delay=%d ms, " + "return loss=%.02f, return loss enh=%.02f", + p_stat->delay, p_stat->return_loss, + p_stat->return_loss_enh); return PJ_SUCCESS; } diff --git a/pjmedia/src/pjmedia/endpoint.c b/pjmedia/src/pjmedia/endpoint.c index 3d549f396c..2afe46c405 100644 --- a/pjmedia/src/pjmedia/endpoint.c +++ b/pjmedia/src/pjmedia/endpoint.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -47,7 +46,7 @@ static const pj_str_t STR_INACTIVE = { "inactive", 8 }; /* Config to control rtpmap inclusion for static payload types */ pj_bool_t pjmedia_add_rtpmap_for_static_pt = - PJMEDIA_ADD_RTPMAP_FOR_STATIC_PT; + PJMEDIA_ADD_RTPMAP_FOR_STATIC_PT; /* Config to control use of RFC3890 TIAS */ pj_bool_t pjmedia_add_bandwidth_tias_in_sdp = @@ -59,14 +58,14 @@ pj_bool_t pjmedia_add_bandwidth_tias_in_sdp = static int PJ_THREAD_FUNC worker_proc(void*); -#define MAX_THREADS 16 +#define MAX_THREADS 16 /* List of media endpoint exit callback. */ typedef struct exit_cb { - PJ_DECL_LIST_MEMBER (struct exit_cb); - pjmedia_endpt_exit_callback func; + PJ_DECL_LIST_MEMBER (struct exit_cb); + pjmedia_endpt_exit_callback func; } exit_cb; @@ -74,34 +73,34 @@ typedef struct exit_cb struct pjmedia_endpt { /** Pool. */ - pj_pool_t *pool; + pj_pool_t *pool; /** Pool factory. */ - pj_pool_factory *pf; + pj_pool_factory *pf; /** Codec manager. */ - pjmedia_codec_mgr codec_mgr; + pjmedia_codec_mgr codec_mgr; /** IOqueue instance. */ - pj_ioqueue_t *ioqueue; + pj_ioqueue_t *ioqueue; /** Do we own the ioqueue? */ - pj_bool_t own_ioqueue; + pj_bool_t own_ioqueue; /** Number of threads. */ - unsigned thread_cnt; + unsigned thread_cnt; /** IOqueue polling thread, if any. */ - pj_thread_t *thread[MAX_THREADS]; + pj_thread_t *thread[MAX_THREADS]; /** To signal polling thread to quit. */ - pj_bool_t quit_flag; + pj_bool_t quit_flag; /** Is telephone-event enable */ - pj_bool_t has_telephone_event; + pj_bool_t has_telephone_event; /** List of exit callback. */ - exit_cb exit_cb_list; + exit_cb exit_cb_list; }; @@ -115,9 +114,9 @@ pjmedia_endpt_create_sdp_param_default(pjmedia_endpt_create_sdp_param *param) * Initialize and get the instance of media endpoint. */ PJ_DEF(pj_status_t) pjmedia_endpt_create2(pj_pool_factory *pf, - pj_ioqueue_t *ioqueue, - unsigned worker_cnt, - pjmedia_endpt **p_endpt) + pj_ioqueue_t *ioqueue, + unsigned worker_cnt, + pjmedia_endpt **p_endpt) { pj_pool_t *pool; pjmedia_endpt *endpt; @@ -125,16 +124,16 @@ PJ_DEF(pj_status_t) pjmedia_endpt_create2(pj_pool_factory *pf, pj_status_t status; status = pj_register_strerror(PJMEDIA_ERRNO_START, PJ_ERRNO_SPACE_SIZE, - &pjmedia_strerror); + &pjmedia_strerror); pj_assert(status == PJ_SUCCESS); PJ_ASSERT_RETURN(pf && p_endpt, PJ_EINVAL); PJ_ASSERT_RETURN(worker_cnt <= MAX_THREADS, PJ_EINVAL); pool = pj_pool_create(pf, "med-ept", PJMEDIA_POOL_LEN_ENDPT, - PJMEDIA_POOL_INC_ENDPT, NULL); + PJMEDIA_POOL_INC_ENDPT, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; endpt = PJ_POOL_ZALLOC_T(pool, struct pjmedia_endpt); endpt->pool = pool; @@ -151,38 +150,38 @@ PJ_DEF(pj_status_t) pjmedia_endpt_create2(pj_pool_factory *pf, */ //status = pjmedia_aud_subsys_init(pf); //if (status != PJ_SUCCESS) - // goto on_error; + // goto on_error; /* Init codec manager. */ status = pjmedia_codec_mgr_init(&endpt->codec_mgr, endpt->pf); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Initialize exit callback list. */ pj_list_init(&endpt->exit_cb_list); /* Create ioqueue if none is specified. */ if (endpt->ioqueue == NULL) { - - endpt->own_ioqueue = PJ_TRUE; - - status = pj_ioqueue_create( endpt->pool, PJ_IOQUEUE_MAX_HANDLES, - &endpt->ioqueue); - if (status != PJ_SUCCESS) - goto on_error; - - if (worker_cnt == 0) { - PJ_LOG(4,(THIS_FILE, "Warning: no worker thread is created in" - "media endpoint for internal ioqueue")); - } + + endpt->own_ioqueue = PJ_TRUE; + + status = pj_ioqueue_create( endpt->pool, PJ_IOQUEUE_MAX_HANDLES, + &endpt->ioqueue); + if (status != PJ_SUCCESS) + goto on_error; + + if (worker_cnt == 0) { + PJ_LOG(4,(THIS_FILE, "Warning: no worker thread is created in" + "media endpoint for internal ioqueue")); + } } /* Create worker threads if asked. */ for (i=0; ipool, "media", &worker_proc, - endpt, 0, 0, &endpt->thread[i]); - if (status != PJ_SUCCESS) - goto on_error; + status = pj_thread_create( endpt->pool, "media", &worker_proc, + endpt, 0, 0, &endpt->thread[i]); + if (status != PJ_SUCCESS) + goto on_error; } @@ -193,14 +192,14 @@ PJ_DEF(pj_status_t) pjmedia_endpt_create2(pj_pool_factory *pf, /* Destroy threads */ for (i=0; ithread_cnt; ++i) { - if (endpt->thread[i]) { - pj_thread_destroy(endpt->thread[i]); - } + if (endpt->thread[i]) { + pj_thread_destroy(endpt->thread[i]); + } } /* Destroy internal ioqueue */ if (endpt->ioqueue && endpt->own_ioqueue) - pj_ioqueue_destroy(endpt->ioqueue); + pj_ioqueue_destroy(endpt->ioqueue); pjmedia_codec_mgr_destroy(&endpt->codec_mgr); //pjmedia_aud_subsys_shutdown(); @@ -227,8 +226,8 @@ PJ_DEF(pj_status_t) pjmedia_endpt_destroy2 (pjmedia_endpt *endpt) /* Destroy internal ioqueue */ if (endpt->ioqueue && endpt->own_ioqueue) { - pj_ioqueue_destroy(endpt->ioqueue); - endpt->ioqueue = NULL; + pj_ioqueue_destroy(endpt->ioqueue); + endpt->ioqueue = NULL; } endpt->pf = NULL; @@ -239,8 +238,8 @@ PJ_DEF(pj_status_t) pjmedia_endpt_destroy2 (pjmedia_endpt *endpt) /* Call all registered exit callbacks */ ecb = endpt->exit_cb_list.next; while (ecb != &endpt->exit_cb_list) { - (*ecb->func)(endpt); - ecb = ecb->next; + (*ecb->func)(endpt); + ecb = ecb->next; } pj_pool_release (endpt->pool); @@ -249,34 +248,34 @@ PJ_DEF(pj_status_t) pjmedia_endpt_destroy2 (pjmedia_endpt *endpt) } PJ_DEF(pj_status_t) pjmedia_endpt_set_flag( pjmedia_endpt *endpt, - pjmedia_endpt_flag flag, - const void *value) + pjmedia_endpt_flag flag, + const void *value) { PJ_ASSERT_RETURN(endpt, PJ_EINVAL); switch (flag) { case PJMEDIA_ENDPT_HAS_TELEPHONE_EVENT_FLAG: - endpt->has_telephone_event = *(pj_bool_t*)value; - break; + endpt->has_telephone_event = *(pj_bool_t*)value; + break; default: - return PJ_EINVAL; + return PJ_EINVAL; } return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_endpt_get_flag( pjmedia_endpt *endpt, - pjmedia_endpt_flag flag, - void *value) + pjmedia_endpt_flag flag, + void *value) { PJ_ASSERT_RETURN(endpt, PJ_EINVAL); switch (flag) { case PJMEDIA_ENDPT_HAS_TELEPHONE_EVENT_FLAG: - *(pj_bool_t*)value = endpt->has_telephone_event; - break; + *(pj_bool_t*)value = endpt->has_telephone_event; + break; default: - return PJ_EINVAL; + return PJ_EINVAL; } return PJ_SUCCESS; @@ -304,7 +303,7 @@ PJ_DEF(unsigned) pjmedia_endpt_get_thread_count(pjmedia_endpt *endpt) * Get a reference to one of the worker threads of the media endpoint */ PJ_DEF(pj_thread_t*) pjmedia_endpt_get_thread(pjmedia_endpt *endpt, - unsigned index) + unsigned index) { PJ_ASSERT_RETURN(endpt, NULL); PJ_ASSERT_RETURN(index < endpt->thread_cnt, NULL); @@ -327,11 +326,11 @@ PJ_DEF(pj_status_t) pjmedia_endpt_stop_threads(pjmedia_endpt *endpt) /* Destroy threads */ for (i=0; ithread_cnt; ++i) { - if (endpt->thread[i]) { - pj_thread_join(endpt->thread[i]); - pj_thread_destroy(endpt->thread[i]); - endpt->thread[i] = NULL; - } + if (endpt->thread[i]) { + pj_thread_join(endpt->thread[i]); + pj_thread_destroy(endpt->thread[i]); + endpt->thread[i] = NULL; + } } return PJ_SUCCESS; @@ -345,8 +344,8 @@ static int PJ_THREAD_FUNC worker_proc(void *arg) pjmedia_endpt *endpt = (pjmedia_endpt*) arg; while (!endpt->quit_flag) { - pj_time_val timeout = { 0, 10 }; - pj_ioqueue_poll(endpt->ioqueue, &timeout); + pj_time_val timeout = { 0, 10 }; + pj_ioqueue_poll(endpt->ioqueue, &timeout); } return 0; @@ -356,9 +355,9 @@ static int PJ_THREAD_FUNC worker_proc(void *arg) * Create pool. */ PJ_DEF(pj_pool_t*) pjmedia_endpt_create_pool( pjmedia_endpt *endpt, - const char *name, - pj_size_t initial, - pj_size_t increment) + const char *name, + pj_size_t initial, + pj_size_t increment) { pj_assert(endpt != NULL); @@ -369,8 +368,8 @@ PJ_DEF(pj_pool_t*) pjmedia_endpt_create_pool( pjmedia_endpt *endpt, static pj_status_t init_sdp_media(pjmedia_sdp_media *m, pj_pool_t *pool, const pj_str_t *media_type, - const pjmedia_sock_info *sock_info, - pjmedia_dir dir) + const pjmedia_sock_info *sock_info, + pjmedia_dir dir) { char tmp_addr[PJ_INET6_ADDRSTRLEN]; pjmedia_sdp_attr *attr; @@ -400,25 +399,25 @@ static pj_status_t init_sdp_media(pjmedia_sdp_media *m, /* Add "rtcp" attribute */ #if defined(PJMEDIA_HAS_RTCP_IN_SDP) && PJMEDIA_HAS_RTCP_IN_SDP!=0 if (sock_info->rtcp_addr_name.addr.sa_family != 0) { - attr = pjmedia_sdp_attr_create_rtcp(pool, &sock_info->rtcp_addr_name); - if (attr) - pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); + attr = pjmedia_sdp_attr_create_rtcp(pool, &sock_info->rtcp_addr_name); + if (attr) + pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); } #endif /* Add direction attribute. */ if (m->desc.port != 0) { - attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); - if (dir == PJMEDIA_DIR_ENCODING) { - attr->name = STR_SENDONLY; - } else if (dir == PJMEDIA_DIR_DECODING) { - attr->name = STR_RECVONLY; - } else if (dir == PJMEDIA_DIR_NONE) { - attr->name = STR_INACTIVE; - } else { - attr->name = STR_SENDRECV; - } - m->attr[m->attr_count++] = attr; + attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); + if (dir == PJMEDIA_DIR_ENCODING) { + attr->name = STR_SENDONLY; + } else if (dir == PJMEDIA_DIR_DECODING) { + attr->name = STR_RECVONLY; + } else if (dir == PJMEDIA_DIR_NONE) { + attr->name = STR_INACTIVE; + } else { + attr->name = STR_SENDRECV; + } + m->attr[m->attr_count++] = attr; } return PJ_SUCCESS; @@ -439,7 +438,7 @@ pjmedia_endpt_create_audio_sdp(pjmedia_endpt *endpt, unsigned max_bitrate = 0; pj_status_t status; #if defined(PJMEDIA_RTP_PT_TELEPHONE_EVENTS) && \ - PJMEDIA_RTP_PT_TELEPHONE_EVENTS != 0 + PJMEDIA_RTP_PT_TELEPHONE_EVENTS != 0 unsigned televent_num = 0; unsigned televent_clockrates[8]; #endif @@ -449,17 +448,17 @@ pjmedia_endpt_create_audio_sdp(pjmedia_endpt *endpt, /* Check that there are not too many codecs */ PJ_ASSERT_RETURN(endpt->codec_mgr.codec_cnt <= PJMEDIA_MAX_SDP_FMT, - PJ_ETOOMANY); + PJ_ETOOMANY); /* Insert PJMEDIA_RTP_PT_TELEPHONE_EVENTS as used PT */ #if defined(PJMEDIA_RTP_PT_TELEPHONE_EVENTS) && \ - PJMEDIA_RTP_PT_TELEPHONE_EVENTS != 0 + PJMEDIA_RTP_PT_TELEPHONE_EVENTS != 0 if (endpt->has_telephone_event) { - used_pt[used_pt_num++] = PJMEDIA_RTP_PT_TELEPHONE_EVENTS; + used_pt[used_pt_num++] = PJMEDIA_RTP_PT_TELEPHONE_EVENTS; # if PJMEDIA_TELEPHONE_EVENT_ALL_CLOCKRATES==0 - televent_num = 1; - televent_clockrates[0] = 8000; + televent_num = 1; + televent_clockrates[0] = 8000; # endif } @@ -469,251 +468,251 @@ pjmedia_endpt_create_audio_sdp(pjmedia_endpt *endpt, m = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_media); pjmedia_endpt_create_sdp_param_default(¶m); status = init_sdp_media(m, pool, &STR_AUDIO, si, options? options->dir: - param.dir); + param.dir); if (status != PJ_SUCCESS) - return status; + return status; /* Add format, rtpmap, and fmtp (when applicable) for each codec */ for (i=0; icodec_mgr.codec_cnt; ++i) { - pjmedia_codec_info *codec_info; - pjmedia_sdp_rtpmap rtpmap; - char tmp_param[3]; - pjmedia_codec_param codec_param; - pj_str_t *fmt; - unsigned pt; - - if (endpt->codec_mgr.codec_desc[i].prio == PJMEDIA_CODEC_PRIO_DISABLED) - break; - - codec_info = &endpt->codec_mgr.codec_desc[i].info; - pjmedia_codec_mgr_get_default_param(&endpt->codec_mgr, codec_info, - &codec_param); - fmt = &m->desc.fmt[m->desc.fmt_count++]; - pt = codec_info->pt; - - /* Rearrange dynamic payload type to make sure it is inside 96-127 - * range and not being used by other codec/tel-event. - */ - if (pt >= 96) { - unsigned pt_check = 96; - unsigned j = 0; - while (j < used_pt_num && pt_check <= 127) { - if (pt_check==used_pt[j]) { - pt_check++; - j = 0; - } else { - j++; - } - } - if (pt_check > 127) { - /* No more available PT */ - PJ_LOG(4,(THIS_FILE, "Warning: no available dynamic " - "payload type for audio codec")); - break; - } - pt = pt_check; - } - - /* Take a note of used dynamic PT */ - if (pt >= 96) - used_pt[used_pt_num++] = pt; - - fmt->ptr = (char*) pj_pool_alloc(pool, 8); - fmt->slen = pj_utoa(pt, fmt->ptr); - - rtpmap.pt = *fmt; - rtpmap.enc_name = codec_info->encoding_name; + pjmedia_codec_info *codec_info; + pjmedia_sdp_rtpmap rtpmap; + char tmp_param[3]; + pjmedia_codec_param codec_param; + pj_str_t *fmt; + unsigned pt; + + if (endpt->codec_mgr.codec_desc[i].prio == PJMEDIA_CODEC_PRIO_DISABLED) + break; + + codec_info = &endpt->codec_mgr.codec_desc[i].info; + pjmedia_codec_mgr_get_default_param(&endpt->codec_mgr, codec_info, + &codec_param); + fmt = &m->desc.fmt[m->desc.fmt_count++]; + pt = codec_info->pt; + + /* Rearrange dynamic payload type to make sure it is inside 96-127 + * range and not being used by other codec/tel-event. + */ + if (pt >= 96) { + unsigned pt_check = 96; + unsigned j = 0; + while (j < used_pt_num && pt_check <= 127) { + if (pt_check==used_pt[j]) { + pt_check++; + j = 0; + } else { + j++; + } + } + if (pt_check > 127) { + /* No more available PT */ + PJ_LOG(4,(THIS_FILE, "Warning: no available dynamic " + "payload type for audio codec")); + break; + } + pt = pt_check; + } + + /* Take a note of used dynamic PT */ + if (pt >= 96) + used_pt[used_pt_num++] = pt; + + fmt->ptr = (char*) pj_pool_alloc(pool, 8); + fmt->slen = pj_utoa(pt, fmt->ptr); + + rtpmap.pt = *fmt; + rtpmap.enc_name = codec_info->encoding_name; #if defined(PJMEDIA_HANDLE_G722_MPEG_BUG) && (PJMEDIA_HANDLE_G722_MPEG_BUG != 0) - if (pt == PJMEDIA_RTP_PT_G722) - rtpmap.clock_rate = 8000; - else - rtpmap.clock_rate = codec_info->clock_rate; + if (pt == PJMEDIA_RTP_PT_G722) + rtpmap.clock_rate = 8000; + else + rtpmap.clock_rate = codec_info->clock_rate; #else - rtpmap.clock_rate = codec_info->clock_rate; + rtpmap.clock_rate = codec_info->clock_rate; #endif - /* For audio codecs, rtpmap parameters denotes the number - * of channels, which can be omited if the value is 1. - */ - if (codec_info->type == PJMEDIA_TYPE_AUDIO && - codec_info->channel_cnt > 1) - { - /* Can only support one digit channel count */ - pj_assert(codec_info->channel_cnt < 10); - - tmp_param[0] = (char)('0' + codec_info->channel_cnt); - - rtpmap.param.ptr = tmp_param; - rtpmap.param.slen = 1; - - } else { - rtpmap.param.ptr = ""; - rtpmap.param.slen = 0; - } - - if (pt >= 96 || pjmedia_add_rtpmap_for_static_pt) { - pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr); - m->attr[m->attr_count++] = attr; - } - - /* Add fmtp params */ - if (codec_param.setting.dec_fmtp.cnt > 0) { - enum { MAX_FMTP_STR_LEN = 160 }; - char buf[MAX_FMTP_STR_LEN]; - unsigned buf_len = 0, n, ii; - pjmedia_codec_fmtp *dec_fmtp = &codec_param.setting.dec_fmtp; - - /* Print codec PT */ - n = pj_ansi_snprintf(buf, MAX_FMTP_STR_LEN - buf_len, - "%d", pt); - buf_len = PJ_MIN(buf_len + n, MAX_FMTP_STR_LEN); - - for (ii = 0; ii < dec_fmtp->cnt; ++ii) { - pj_size_t test_len = 2; - - /* Check if buf still available */ - test_len = dec_fmtp->param[ii].val.slen + - dec_fmtp->param[ii].name.slen + 2; - if (test_len + buf_len >= MAX_FMTP_STR_LEN) - return PJ_ETOOBIG; - - /* Print delimiter */ - n = pj_ansi_snprintf(&buf[buf_len], - MAX_FMTP_STR_LEN - buf_len, - (ii == 0?" ":";")); - buf_len = PJ_MIN(buf_len + n, MAX_FMTP_STR_LEN); - - /* Print an fmtp param */ - if (dec_fmtp->param[ii].name.slen) - n = pj_ansi_snprintf(&buf[buf_len], - MAX_FMTP_STR_LEN - buf_len, - "%.*s=%.*s", - (int)dec_fmtp->param[ii].name.slen, - dec_fmtp->param[ii].name.ptr, - (int)dec_fmtp->param[ii].val.slen, - dec_fmtp->param[ii].val.ptr); - else - n = pj_ansi_snprintf(&buf[buf_len], - MAX_FMTP_STR_LEN - buf_len, - "%.*s", - (int)dec_fmtp->param[ii].val.slen, - dec_fmtp->param[ii].val.ptr); - - buf_len = PJ_MIN(buf_len + n, MAX_FMTP_STR_LEN); - } - - attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); - - attr->name = pj_str("fmtp"); - attr->value = pj_strdup3(pool, buf); - m->attr[m->attr_count++] = attr; - } - - /* Find maximum bitrate in this media */ - if (max_bitrate < codec_param.info.max_bps) - max_bitrate = codec_param.info.max_bps; - - /* List clock rate of audio codecs for generating telephone-event */ + /* For audio codecs, rtpmap parameters denotes the number + * of channels, which can be omited if the value is 1. + */ + if (codec_info->type == PJMEDIA_TYPE_AUDIO && + codec_info->channel_cnt > 1) + { + /* Can only support one digit channel count */ + pj_assert(codec_info->channel_cnt < 10); + + tmp_param[0] = (char)('0' + codec_info->channel_cnt); + + rtpmap.param.ptr = tmp_param; + rtpmap.param.slen = 1; + + } else { + rtpmap.param.ptr = ""; + rtpmap.param.slen = 0; + } + + if (pt >= 96 || pjmedia_add_rtpmap_for_static_pt) { + pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr); + m->attr[m->attr_count++] = attr; + } + + /* Add fmtp params */ + if (codec_param.setting.dec_fmtp.cnt > 0) { + enum { MAX_FMTP_STR_LEN = 160 }; + char buf[MAX_FMTP_STR_LEN]; + unsigned buf_len = 0, n, ii; + pjmedia_codec_fmtp *dec_fmtp = &codec_param.setting.dec_fmtp; + + /* Print codec PT */ + n = pj_ansi_snprintf(buf, MAX_FMTP_STR_LEN - buf_len, + "%d", pt); + buf_len = PJ_MIN(buf_len + n, MAX_FMTP_STR_LEN); + + for (ii = 0; ii < dec_fmtp->cnt; ++ii) { + pj_size_t test_len = 2; + + /* Check if buf still available */ + test_len = dec_fmtp->param[ii].val.slen + + dec_fmtp->param[ii].name.slen + 2; + if (test_len + buf_len >= MAX_FMTP_STR_LEN) + return PJ_ETOOBIG; + + /* Print delimiter */ + n = pj_ansi_snprintf(&buf[buf_len], + MAX_FMTP_STR_LEN - buf_len, + (ii == 0?" ":";")); + buf_len = PJ_MIN(buf_len + n, MAX_FMTP_STR_LEN); + + /* Print an fmtp param */ + if (dec_fmtp->param[ii].name.slen) + n = pj_ansi_snprintf(&buf[buf_len], + MAX_FMTP_STR_LEN - buf_len, + "%.*s=%.*s", + (int)dec_fmtp->param[ii].name.slen, + dec_fmtp->param[ii].name.ptr, + (int)dec_fmtp->param[ii].val.slen, + dec_fmtp->param[ii].val.ptr); + else + n = pj_ansi_snprintf(&buf[buf_len], + MAX_FMTP_STR_LEN - buf_len, + "%.*s", + (int)dec_fmtp->param[ii].val.slen, + dec_fmtp->param[ii].val.ptr); + + buf_len = PJ_MIN(buf_len + n, MAX_FMTP_STR_LEN); + } + + attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); + + attr->name = pj_str("fmtp"); + attr->value = pj_strdup3(pool, buf); + m->attr[m->attr_count++] = attr; + } + + /* Find maximum bitrate in this media */ + if (max_bitrate < codec_param.info.max_bps) + max_bitrate = codec_param.info.max_bps; + + /* List clock rate of audio codecs for generating telephone-event */ #if defined(PJMEDIA_RTP_PT_TELEPHONE_EVENTS) && \ - PJMEDIA_RTP_PT_TELEPHONE_EVENTS != 0 && \ - PJMEDIA_TELEPHONE_EVENT_ALL_CLOCKRATES != 0 - if (endpt->has_telephone_event) { - unsigned j; - - for (j=0; jhas_telephone_event) { + unsigned j; + + for (j=0; jhas_telephone_event) { - for (i=0; i 127) { - /* Not found? Find more, but now starting from 96 */ - pt = 96; - j = 0; - while (j < used_pt_num && - pt < PJMEDIA_RTP_PT_TELEPHONE_EVENTS) - { - if (pt == used_pt[j]) { - pt++; - j = 0; - } else { - j++; - } - } - if (pt >= PJMEDIA_RTP_PT_TELEPHONE_EVENTS) { - /* No more available PT */ - PJ_LOG(4,(THIS_FILE, "Warning: no available dynamic " - "payload type for telephone-event")); - break; - } - } - } - used_pt[used_pt_num++] = pt; - - /* Print tel-event PT */ - pj_ansi_snprintf(buf, sizeof(buf), "%d", pt); - m->desc.fmt[m->desc.fmt_count++] = pj_strdup3(pool, buf); - - /* Add rtpmap. */ - attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); - attr->name = pj_str("rtpmap"); - pj_ansi_snprintf(buf, sizeof(buf), "%d telephone-event/%d", - pt, televent_clockrates[i]); - /* Must be NULL terminated for pjmedia_sdp_attr_get_rtpmap() */ - pj_strdup2_with_null(pool, &attr->value, buf); - m->attr[m->attr_count++] = attr; - - /* Add fmtp */ - attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); - attr->name = pj_str("fmtp"); + for (i=0; i 127) { + /* Not found? Find more, but now starting from 96 */ + pt = 96; + j = 0; + while (j < used_pt_num && + pt < PJMEDIA_RTP_PT_TELEPHONE_EVENTS) + { + if (pt == used_pt[j]) { + pt++; + j = 0; + } else { + j++; + } + } + if (pt >= PJMEDIA_RTP_PT_TELEPHONE_EVENTS) { + /* No more available PT */ + PJ_LOG(4,(THIS_FILE, "Warning: no available dynamic " + "payload type for telephone-event")); + break; + } + } + } + used_pt[used_pt_num++] = pt; + + /* Print tel-event PT */ + pj_ansi_snprintf(buf, sizeof(buf), "%d", pt); + m->desc.fmt[m->desc.fmt_count++] = pj_strdup3(pool, buf); + + /* Add rtpmap. */ + attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); + attr->name = pj_str("rtpmap"); + pj_ansi_snprintf(buf, sizeof(buf), "%d telephone-event/%d", + pt, televent_clockrates[i]); + /* Must be NULL terminated for pjmedia_sdp_attr_get_rtpmap() */ + pj_strdup2_with_null(pool, &attr->value, buf); + m->attr[m->attr_count++] = attr; + + /* Add fmtp */ + attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); + attr->name = pj_str("fmtp"); #if defined(PJMEDIA_HAS_DTMF_FLASH) && PJMEDIA_HAS_DTMF_FLASH!= 0 - pj_ansi_snprintf(buf, sizeof(buf), "%d 0-16", pt); + pj_ansi_snprintf(buf, sizeof(buf), "%d 0-16", pt); #else - pj_ansi_snprintf(buf, sizeof(buf), "%d 0-15", pt); + pj_ansi_snprintf(buf, sizeof(buf), "%d 0-15", pt); #endif - attr->value = pj_strdup3(pool, buf); - m->attr[m->attr_count++] = attr; - } + attr->value = pj_strdup3(pool, buf); + m->attr[m->attr_count++] = attr; + } } #endif @@ -721,13 +720,13 @@ pjmedia_endpt_create_audio_sdp(pjmedia_endpt *endpt, * (RFC3890). */ if (max_bitrate && pjmedia_add_bandwidth_tias_in_sdp) { - const pj_str_t STR_BANDW_MODIFIER = { "TIAS", 4 }; - pjmedia_sdp_bandw *b; - - b = PJ_POOL_ALLOC_T(pool, pjmedia_sdp_bandw); - b->modifier = STR_BANDW_MODIFIER; - b->value = max_bitrate; - m->bandw[m->bandw_count++] = b; + const pj_str_t STR_BANDW_MODIFIER = { "TIAS", 4 }; + pjmedia_sdp_bandw *b; + + b = PJ_POOL_ALLOC_T(pool, pjmedia_sdp_bandw); + b->modifier = STR_BANDW_MODIFIER; + b->value = max_bitrate; + m->bandw[m->bandw_count++] = b; } *p_m = m; @@ -759,142 +758,142 @@ pjmedia_endpt_create_video_sdp(pjmedia_endpt *endpt, /* Make sure video codec manager is instantiated */ if (!pjmedia_vid_codec_mgr_instance()) - pjmedia_vid_codec_mgr_create(endpt->pool, NULL); + pjmedia_vid_codec_mgr_create(endpt->pool, NULL); /* Create and init basic SDP media */ pjmedia_endpt_create_sdp_param_default(¶m); m = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_media); status = init_sdp_media(m, pool, &STR_VIDEO, si, options? options->dir: - param.dir); + param.dir); if (status != PJ_SUCCESS) - return status; + return status; cnt = PJ_ARRAY_SIZE(codec_info); status = pjmedia_vid_codec_mgr_enum_codecs(NULL, &cnt, - codec_info, codec_prio); + codec_info, codec_prio); /* Check that there are not too many codecs */ PJ_ASSERT_RETURN(0 <= PJMEDIA_MAX_SDP_FMT, - PJ_ETOOMANY); + PJ_ETOOMANY); /* Add format, rtpmap, and fmtp (when applicable) for each codec */ for (i=0; i PJMEDIA_MAX_SDP_FMT) { - /* Too many codecs, perhaps it is better to tell application by - * returning appropriate status code. - */ - PJ_PERROR(3,(THIS_FILE, PJ_ETOOMANY, - "Skipping some video codecs")); - break; - } + if (i > PJMEDIA_MAX_SDP_FMT) { + /* Too many codecs, perhaps it is better to tell application by + * returning appropriate status code. + */ + PJ_PERROR(3,(THIS_FILE, PJ_ETOOMANY, + "Skipping some video codecs")); + break; + } /* Must support RTP packetization */ if ((codec_info[i].packings & PJMEDIA_VID_PACKING_PACKETS) == 0) - { - continue; - } - - pjmedia_vid_codec_mgr_get_default_param(NULL, &codec_info[i], - &codec_param); - - fmt = &m->desc.fmt[m->desc.fmt_count++]; - fmt->ptr = (char*) pj_pool_alloc(pool, 8); - fmt->slen = pj_utoa(codec_info[i].pt, fmt->ptr); - rtpmap.pt = *fmt; - - /* Encoding name */ - rtpmap.enc_name = codec_info[i].encoding_name; - - /* Clock rate */ - rtpmap.clock_rate = codec_info[i].clock_rate; - - if (codec_info[i].pt >= 96 || pjmedia_add_rtpmap_for_static_pt) { - pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr); - m->attr[m->attr_count++] = attr; - } - - /* Add fmtp params */ - if (codec_param.dec_fmtp.cnt > 0) { - enum { MAX_FMTP_STR_LEN = 160 }; - char buf[MAX_FMTP_STR_LEN]; - unsigned buf_len = 0, n, j; - pjmedia_codec_fmtp *dec_fmtp = &codec_param.dec_fmtp; - - /* Print codec PT */ - n = pj_ansi_snprintf(buf, MAX_FMTP_STR_LEN - buf_len, - "%d", - codec_info[i].pt); - buf_len = PJ_MIN(buf_len + n, MAX_FMTP_STR_LEN); - - for (j = 0; j < dec_fmtp->cnt; ++j) { - pj_size_t test_len = 2; - - /* Check if buf still available */ - test_len = dec_fmtp->param[j].val.slen + - dec_fmtp->param[j].name.slen + 2; - if (test_len + buf_len >= MAX_FMTP_STR_LEN) - return PJ_ETOOBIG; - - /* Print delimiter */ - n = pj_ansi_snprintf(&buf[buf_len], - MAX_FMTP_STR_LEN - buf_len, - (j == 0?" ":";")); - buf_len = PJ_MIN(buf_len + n, MAX_FMTP_STR_LEN); - - /* Print an fmtp param */ - if (dec_fmtp->param[j].name.slen) - n = pj_ansi_snprintf(&buf[buf_len], - MAX_FMTP_STR_LEN - buf_len, - "%.*s=%.*s", - (int)dec_fmtp->param[j].name.slen, - dec_fmtp->param[j].name.ptr, - (int)dec_fmtp->param[j].val.slen, - dec_fmtp->param[j].val.ptr); - else - n = pj_ansi_snprintf(&buf[buf_len], - MAX_FMTP_STR_LEN - buf_len, - "%.*s", - (int)dec_fmtp->param[j].val.slen, - dec_fmtp->param[j].val.ptr); - - buf_len = PJ_MIN(buf_len + n, MAX_FMTP_STR_LEN); - } - - attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); - - attr->name = pj_str("fmtp"); - attr->value = pj_strdup3(pool, buf); - m->attr[m->attr_count++] = attr; - } + { + continue; + } + + pjmedia_vid_codec_mgr_get_default_param(NULL, &codec_info[i], + &codec_param); + + fmt = &m->desc.fmt[m->desc.fmt_count++]; + fmt->ptr = (char*) pj_pool_alloc(pool, 8); + fmt->slen = pj_utoa(codec_info[i].pt, fmt->ptr); + rtpmap.pt = *fmt; + + /* Encoding name */ + rtpmap.enc_name = codec_info[i].encoding_name; + + /* Clock rate */ + rtpmap.clock_rate = codec_info[i].clock_rate; + + if (codec_info[i].pt >= 96 || pjmedia_add_rtpmap_for_static_pt) { + pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr); + m->attr[m->attr_count++] = attr; + } + + /* Add fmtp params */ + if (codec_param.dec_fmtp.cnt > 0) { + enum { MAX_FMTP_STR_LEN = 160 }; + char buf[MAX_FMTP_STR_LEN]; + unsigned buf_len = 0, n, j; + pjmedia_codec_fmtp *dec_fmtp = &codec_param.dec_fmtp; + + /* Print codec PT */ + n = pj_ansi_snprintf(buf, MAX_FMTP_STR_LEN - buf_len, + "%d", + codec_info[i].pt); + buf_len = PJ_MIN(buf_len + n, MAX_FMTP_STR_LEN); + + for (j = 0; j < dec_fmtp->cnt; ++j) { + pj_size_t test_len = 2; + + /* Check if buf still available */ + test_len = dec_fmtp->param[j].val.slen + + dec_fmtp->param[j].name.slen + 2; + if (test_len + buf_len >= MAX_FMTP_STR_LEN) + return PJ_ETOOBIG; + + /* Print delimiter */ + n = pj_ansi_snprintf(&buf[buf_len], + MAX_FMTP_STR_LEN - buf_len, + (j == 0?" ":";")); + buf_len = PJ_MIN(buf_len + n, MAX_FMTP_STR_LEN); + + /* Print an fmtp param */ + if (dec_fmtp->param[j].name.slen) + n = pj_ansi_snprintf(&buf[buf_len], + MAX_FMTP_STR_LEN - buf_len, + "%.*s=%.*s", + (int)dec_fmtp->param[j].name.slen, + dec_fmtp->param[j].name.ptr, + (int)dec_fmtp->param[j].val.slen, + dec_fmtp->param[j].val.ptr); + else + n = pj_ansi_snprintf(&buf[buf_len], + MAX_FMTP_STR_LEN - buf_len, + "%.*s", + (int)dec_fmtp->param[j].val.slen, + dec_fmtp->param[j].val.ptr); + + buf_len = PJ_MIN(buf_len + n, MAX_FMTP_STR_LEN); + } + + attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); + + attr->name = pj_str("fmtp"); + attr->value = pj_strdup3(pool, buf); + m->attr[m->attr_count++] = attr; + } - /* Find maximum bitrate in this media */ - vfd = pjmedia_format_get_video_format_detail(&codec_param.enc_fmt, - PJ_TRUE); - if (vfd && max_bitrate < vfd->max_bps) - max_bitrate = vfd->max_bps; + /* Find maximum bitrate in this media */ + vfd = pjmedia_format_get_video_format_detail(&codec_param.enc_fmt, + PJ_TRUE); + if (vfd && max_bitrate < vfd->max_bps) + max_bitrate = vfd->max_bps; } /* Put bandwidth info in media level using bandwidth modifier "TIAS" * (RFC3890). */ if (max_bitrate && pjmedia_add_bandwidth_tias_in_sdp) { - const pj_str_t STR_BANDW_MODIFIER = { "TIAS", 4 }; - pjmedia_sdp_bandw *b; - - b = PJ_POOL_ALLOC_T(pool, pjmedia_sdp_bandw); - b->modifier = STR_BANDW_MODIFIER; - b->value = max_bitrate; - m->bandw[m->bandw_count++] = b; + const pj_str_t STR_BANDW_MODIFIER = { "TIAS", 4 }; + pjmedia_sdp_bandw *b; + + b = PJ_POOL_ALLOC_T(pool, pjmedia_sdp_bandw); + b->modifier = STR_BANDW_MODIFIER; + b->value = max_bitrate; + m->bandw[m->bandw_count++] = b; } *p_m = m; @@ -909,10 +908,10 @@ pjmedia_endpt_create_video_sdp(pjmedia_endpt *endpt, * fields such as origin, time, and name, but without any media lines. */ PJ_DEF(pj_status_t) pjmedia_endpt_create_base_sdp( pjmedia_endpt *endpt, - pj_pool_t *pool, - const pj_str_t *sess_name, - const pj_sockaddr *origin, - pjmedia_sdp_session **p_sdp) + pj_pool_t *pool, + const pj_str_t *sess_name, + const pj_sockaddr *origin, + pjmedia_sdp_session **p_sdp) { char tmp_addr[PJ_INET6_ADDRSTRLEN]; pj_time_val tv; @@ -929,21 +928,21 @@ PJ_DEF(pj_status_t) pjmedia_endpt_create_base_sdp( pjmedia_endpt *endpt, sdp->origin.net_type = STR_IN; if (origin->addr.sa_family == pj_AF_INET()) { - sdp->origin.addr_type = STR_IP4; + sdp->origin.addr_type = STR_IP4; } else if (origin->addr.sa_family == pj_AF_INET6()) { - sdp->origin.addr_type = STR_IP6; + sdp->origin.addr_type = STR_IP6; } else { - pj_assert(!"Invalid address family"); - return PJ_EAFNOTSUP; + pj_assert(!"Invalid address family"); + return PJ_EAFNOTSUP; } pj_strdup2(pool, &sdp->origin.addr, - pj_sockaddr_print(origin, tmp_addr, sizeof(tmp_addr), 0)); + pj_sockaddr_print(origin, tmp_addr, sizeof(tmp_addr), 0)); if (sess_name) - pj_strdup(pool, &sdp->name, sess_name); + pj_strdup(pool, &sdp->name, sess_name); else - sdp->name = STR_SDP_NAME; + sdp->name = STR_SDP_NAME; /* SDP time and attributes. */ sdp->time.start = sdp->time.stop = 0; @@ -960,10 +959,10 @@ PJ_DEF(pj_status_t) pjmedia_endpt_create_base_sdp( pjmedia_endpt *endpt, * capability. */ PJ_DEF(pj_status_t) pjmedia_endpt_create_sdp( pjmedia_endpt *endpt, - pj_pool_t *pool, - unsigned stream_cnt, - const pjmedia_sock_info sock_info[], - pjmedia_sdp_session **p_sdp ) + pj_pool_t *pool, + unsigned stream_cnt, + const pjmedia_sock_info sock_info[], + pjmedia_sdp_session **p_sdp ) { const pj_sockaddr *addr0; pjmedia_sdp_session *sdp; @@ -979,27 +978,27 @@ PJ_DEF(pj_status_t) pjmedia_endpt_create_sdp( pjmedia_endpt *endpt, /* Create and initialize basic SDP session */ status = pjmedia_endpt_create_base_sdp(endpt, pool, NULL, addr0, &sdp); if (status != PJ_SUCCESS) - return status; + return status; /* Audio is first, by convention */ status = pjmedia_endpt_create_audio_sdp(endpt, pool, &sock_info[0], 0, &m); if (status != PJ_SUCCESS) - return status; + return status; sdp->media[sdp->media_count++] = m; #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) { - unsigned i; - - /* The remaining stream, if any, are videos (by convention as well) */ - for (i=1; imedia[sdp->media_count++] = m; - } + unsigned i; + + /* The remaining stream, if any, are videos (by convention as well) */ + for (i=1; imedia[sdp->media_count++] = m; + } } #endif @@ -1015,15 +1014,15 @@ PJ_DEF(pj_status_t) pjmedia_endpt_create_sdp( pjmedia_endpt *endpt, static const char *good_number(char *buf, pj_int32_t val) { if (val < 1000) { - pj_ansi_sprintf(buf, "%d", val); + pj_ansi_sprintf(buf, "%d", val); } else if (val < 1000000) { - pj_ansi_sprintf(buf, "%d.%dK", - val / 1000, - (val % 1000) / 100); + pj_ansi_sprintf(buf, "%d.%dK", + val / 1000, + (val % 1000) / 100); } else { - pj_ansi_sprintf(buf, "%d.%02dM", - val / 1000000, - (val % 1000000) / 10000); + pj_ansi_sprintf(buf, "%d.%02dM", + val / 1000000, + (val % 1000000) / 10000); } return buf; @@ -1042,48 +1041,48 @@ PJ_DEF(pj_status_t) pjmedia_endpt_dump(pjmedia_endpt *endpt) count = PJ_ARRAY_SIZE(codec_info); if (pjmedia_codec_mgr_enum_codecs(&endpt->codec_mgr, - &count, codec_info, prio) != PJ_SUCCESS) + &count, codec_info, prio) != PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, " -error: failed to enum codecs")); - return PJ_SUCCESS; + PJ_LOG(3,(THIS_FILE, " -error: failed to enum codecs")); + return PJ_SUCCESS; } PJ_LOG(3,(THIS_FILE, " Total number of installed codecs: %d", count)); for (i=0; icodec_mgr, - &codec_info[i], - ¶m) != PJ_SUCCESS) - { - pj_bzero(¶m, sizeof(pjmedia_codec_param)); - } - - PJ_LOG(3,(THIS_FILE, - " %s codec #%2d: pt=%d (%.*s @%dKHz/%d, %sbps, %dms%s%s%s%s%s)", - type, i, codec_info[i].pt, - (int)codec_info[i].encoding_name.slen, - codec_info[i].encoding_name.ptr, - codec_info[i].clock_rate/1000, - codec_info[i].channel_cnt, - good_number(bps, param.info.avg_bps), - param.info.frm_ptime * param.setting.frm_per_pkt, - (param.setting.vad ? " vad" : ""), - (param.setting.cng ? " cng" : ""), - (param.setting.plc ? " plc" : ""), - (param.setting.penh ? " penh" : ""), - (prio[i]==PJMEDIA_CODEC_PRIO_DISABLED?" disabled":""))); + const char *type; + pjmedia_codec_param param; + char bps[32]; + + switch (codec_info[i].type) { + case PJMEDIA_TYPE_AUDIO: + type = "Audio"; break; + case PJMEDIA_TYPE_VIDEO: + type = "Video"; break; + default: + type = "Unknown type"; break; + } + + if (pjmedia_codec_mgr_get_default_param(&endpt->codec_mgr, + &codec_info[i], + ¶m) != PJ_SUCCESS) + { + pj_bzero(¶m, sizeof(pjmedia_codec_param)); + } + + PJ_LOG(3,(THIS_FILE, + " %s codec #%2d: pt=%d (%.*s @%dKHz/%d, %sbps, %dms%s%s%s%s%s)", + type, i, codec_info[i].pt, + (int)codec_info[i].encoding_name.slen, + codec_info[i].encoding_name.ptr, + codec_info[i].clock_rate/1000, + codec_info[i].channel_cnt, + good_number(bps, param.info.avg_bps), + param.info.frm_ptime * param.setting.frm_per_pkt, + (param.setting.vad ? " vad" : ""), + (param.setting.cng ? " cng" : ""), + (param.setting.plc ? " plc" : ""), + (param.setting.penh ? " penh" : ""), + (prio[i]==PJMEDIA_CODEC_PRIO_DISABLED?" disabled":""))); } #endif @@ -1091,14 +1090,14 @@ PJ_DEF(pj_status_t) pjmedia_endpt_dump(pjmedia_endpt *endpt) } PJ_DEF(pj_status_t) pjmedia_endpt_atexit( pjmedia_endpt *endpt, - pjmedia_endpt_exit_callback func) + pjmedia_endpt_exit_callback func) { exit_cb *new_cb; PJ_ASSERT_RETURN(endpt && func, PJ_EINVAL); if (endpt->quit_flag) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; new_cb = PJ_POOL_ZALLOC_T(endpt->pool, exit_cb); new_cb->func = func; diff --git a/pjmedia/src/pjmedia/errno.c b/pjmedia/src/pjmedia/errno.c index f5fdfdbe8b..b7790be136 100644 --- a/pjmedia/src/pjmedia/errno.c +++ b/pjmedia/src/pjmedia/errno.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -45,42 +44,42 @@ static const struct } err_str[] = { /* Generic PJMEDIA errors, shouldn't be used! */ - PJ_BUILD_ERR( PJMEDIA_ERROR, "Unspecified PJMEDIA error" ), + PJ_BUILD_ERR( PJMEDIA_ERROR, "Unspecified PJMEDIA error" ), /* SDP error. */ - PJ_BUILD_ERR( PJMEDIA_SDP_EINSDP, "Invalid SDP descriptor" ), - PJ_BUILD_ERR( PJMEDIA_SDP_EINVER, "Invalid SDP version line" ), + PJ_BUILD_ERR( PJMEDIA_SDP_EINSDP, "Invalid SDP descriptor" ), + PJ_BUILD_ERR( PJMEDIA_SDP_EINVER, "Invalid SDP version line" ), PJ_BUILD_ERR( PJMEDIA_SDP_EINORIGIN, "Invalid SDP origin line" ), - PJ_BUILD_ERR( PJMEDIA_SDP_EINTIME, "Invalid SDP time line"), - PJ_BUILD_ERR( PJMEDIA_SDP_EINNAME, "SDP name/subject line is empty"), - PJ_BUILD_ERR( PJMEDIA_SDP_EINCONN, "Invalid SDP connection line"), + PJ_BUILD_ERR( PJMEDIA_SDP_EINTIME, "Invalid SDP time line"), + PJ_BUILD_ERR( PJMEDIA_SDP_EINNAME, "SDP name/subject line is empty"), + PJ_BUILD_ERR( PJMEDIA_SDP_EINCONN, "Invalid SDP connection line"), PJ_BUILD_ERR( PJMEDIA_SDP_EMISSINGCONN, "Missing SDP connection info line"), - PJ_BUILD_ERR( PJMEDIA_SDP_EINATTR, "Invalid SDP attributes"), + PJ_BUILD_ERR( PJMEDIA_SDP_EINATTR, "Invalid SDP attributes"), PJ_BUILD_ERR( PJMEDIA_SDP_EINRTPMAP, "Invalid SDP rtpmap attribute"), PJ_BUILD_ERR( PJMEDIA_SDP_ERTPMAPTOOLONG,"SDP rtpmap attribute too long"), PJ_BUILD_ERR( PJMEDIA_SDP_EMISSINGRTPMAP,"Missing SDP rtpmap for dynamic payload type"), - PJ_BUILD_ERR( PJMEDIA_SDP_EINMEDIA, "Invalid SDP media line" ), - PJ_BUILD_ERR( PJMEDIA_SDP_ENOFMT, "No SDP payload format in the media line" ), - PJ_BUILD_ERR( PJMEDIA_SDP_EINPT, "Invalid SDP payload type in media line" ), - PJ_BUILD_ERR( PJMEDIA_SDP_EINFMTP, "Invalid SDP fmtp attribute" ), - PJ_BUILD_ERR( PJMEDIA_SDP_EINRTCP, "Invalid SDP rtcp attribute" ), - PJ_BUILD_ERR( PJMEDIA_SDP_EINPROTO, "Invalid SDP media transport protocol" ), - PJ_BUILD_ERR( PJMEDIA_SDP_EINBANDW, "Invalid SDP bandwidth info line" ), - PJ_BUILD_ERR( PJMEDIA_SDP_EINSSRC, "Invalid SDP ssrc attribute" ), + PJ_BUILD_ERR( PJMEDIA_SDP_EINMEDIA, "Invalid SDP media line" ), + PJ_BUILD_ERR( PJMEDIA_SDP_ENOFMT, "No SDP payload format in the media line" ), + PJ_BUILD_ERR( PJMEDIA_SDP_EINPT, "Invalid SDP payload type in media line" ), + PJ_BUILD_ERR( PJMEDIA_SDP_EINFMTP, "Invalid SDP fmtp attribute" ), + PJ_BUILD_ERR( PJMEDIA_SDP_EINRTCP, "Invalid SDP rtcp attribute" ), + PJ_BUILD_ERR( PJMEDIA_SDP_EINPROTO, "Invalid SDP media transport protocol" ), + PJ_BUILD_ERR( PJMEDIA_SDP_EINBANDW, "Invalid SDP bandwidth info line" ), + PJ_BUILD_ERR( PJMEDIA_SDP_EINSSRC, "Invalid SDP ssrc attribute" ), /* SDP negotiator errors. */ - PJ_BUILD_ERR( PJMEDIA_SDPNEG_EINSTATE, "Invalid SDP negotiator state for operation" ), - PJ_BUILD_ERR( PJMEDIA_SDPNEG_ENOINITIAL, "No initial local SDP in SDP negotiator" ), - PJ_BUILD_ERR( PJMEDIA_SDPNEG_ENOACTIVE, "No active SDP in SDP negotiator" ), - PJ_BUILD_ERR( PJMEDIA_SDPNEG_ENONEG, "No current local/remote offer/answer" ), - PJ_BUILD_ERR( PJMEDIA_SDPNEG_EMISMEDIA, "SDP media count mismatch in offer/answer" ), - PJ_BUILD_ERR( PJMEDIA_SDPNEG_EINVANSMEDIA, "SDP media type mismatch in offer/answer" ), - PJ_BUILD_ERR( PJMEDIA_SDPNEG_EINVANSTP, "SDP media transport type mismatch in offer/answer" ), - PJ_BUILD_ERR( PJMEDIA_SDPNEG_EANSNOMEDIA, "No common SDP media payload in answer" ), - PJ_BUILD_ERR( PJMEDIA_SDPNEG_ENOMEDIA, "No active media stream after negotiation" ), - PJ_BUILD_ERR( PJMEDIA_SDPNEG_NOANSCODEC, "No suitable codec for remote offer"), - PJ_BUILD_ERR( PJMEDIA_SDPNEG_NOANSTELEVENT, "No suitable telephone-event for remote offer"), - PJ_BUILD_ERR( PJMEDIA_SDPNEG_NOANSUNKNOWN, "No suitable answer for unknown remote offer"), + PJ_BUILD_ERR( PJMEDIA_SDPNEG_EINSTATE, "Invalid SDP negotiator state for operation" ), + PJ_BUILD_ERR( PJMEDIA_SDPNEG_ENOINITIAL, "No initial local SDP in SDP negotiator" ), + PJ_BUILD_ERR( PJMEDIA_SDPNEG_ENOACTIVE, "No active SDP in SDP negotiator" ), + PJ_BUILD_ERR( PJMEDIA_SDPNEG_ENONEG, "No current local/remote offer/answer" ), + PJ_BUILD_ERR( PJMEDIA_SDPNEG_EMISMEDIA, "SDP media count mismatch in offer/answer" ), + PJ_BUILD_ERR( PJMEDIA_SDPNEG_EINVANSMEDIA, "SDP media type mismatch in offer/answer" ), + PJ_BUILD_ERR( PJMEDIA_SDPNEG_EINVANSTP, "SDP media transport type mismatch in offer/answer" ), + PJ_BUILD_ERR( PJMEDIA_SDPNEG_EANSNOMEDIA, "No common SDP media payload in answer" ), + PJ_BUILD_ERR( PJMEDIA_SDPNEG_ENOMEDIA, "No active media stream after negotiation" ), + PJ_BUILD_ERR( PJMEDIA_SDPNEG_NOANSCODEC, "No suitable codec for remote offer"), + PJ_BUILD_ERR( PJMEDIA_SDPNEG_NOANSTELEVENT, "No suitable telephone-event for remote offer"), + PJ_BUILD_ERR( PJMEDIA_SDPNEG_NOANSUNKNOWN, "No suitable answer for unknown remote offer"), /* SDP comparison results */ PJ_BUILD_ERR( PJMEDIA_SDP_EMEDIANOTEQUAL, "SDP media descriptor not equal" ), @@ -98,66 +97,66 @@ static const struct PJ_BUILD_ERR( PJMEDIA_SDP_ETIMENOTEQUAL, "SDP time line not equal" ), /* Codec errors. */ - PJ_BUILD_ERR( PJMEDIA_CODEC_EUNSUP, "Unsupported media codec" ), - PJ_BUILD_ERR( PJMEDIA_CODEC_EFAILED, "Codec internal creation error" ), + PJ_BUILD_ERR( PJMEDIA_CODEC_EUNSUP, "Unsupported media codec" ), + PJ_BUILD_ERR( PJMEDIA_CODEC_EFAILED, "Codec internal creation error" ), PJ_BUILD_ERR( PJMEDIA_CODEC_EFRMTOOSHORT, "Codec frame is too short" ), PJ_BUILD_ERR( PJMEDIA_CODEC_EPCMTOOSHORT, "PCM frame is too short" ), PJ_BUILD_ERR( PJMEDIA_CODEC_EFRMINLEN, "Invalid codec frame length" ), PJ_BUILD_ERR( PJMEDIA_CODEC_EPCMFRMINLEN, "Invalid PCM frame length" ), - PJ_BUILD_ERR( PJMEDIA_CODEC_EINMODE, "Invalid codec mode (no fmtp?)" ), - PJ_BUILD_ERR( PJMEDIA_CODEC_EBADBITSTREAM, "Bad or corrupted bitstream" ), + PJ_BUILD_ERR( PJMEDIA_CODEC_EINMODE, "Invalid codec mode (no fmtp?)" ), + PJ_BUILD_ERR( PJMEDIA_CODEC_EBADBITSTREAM, "Bad or corrupted bitstream" ), /* Media errors. */ - PJ_BUILD_ERR( PJMEDIA_EINVALIDIP, "Invalid remote media (IP) address" ), - PJ_BUILD_ERR( PJMEDIA_EASYMCODEC, "Asymetric media codec is not supported" ), - PJ_BUILD_ERR( PJMEDIA_EINVALIDPT, "Invalid media payload type" ), + PJ_BUILD_ERR( PJMEDIA_EINVALIDIP, "Invalid remote media (IP) address" ), + PJ_BUILD_ERR( PJMEDIA_EASYMCODEC, "Asymetric media codec is not supported" ), + PJ_BUILD_ERR( PJMEDIA_EINVALIDPT, "Invalid media payload type" ), PJ_BUILD_ERR( PJMEDIA_EMISSINGRTPMAP, "Missing rtpmap in media description" ), PJ_BUILD_ERR( PJMEDIA_EINVALIMEDIATYPE, "Invalid media type" ), PJ_BUILD_ERR( PJMEDIA_EREMOTENODTMF, "Remote does not support DTMF" ), - PJ_BUILD_ERR( PJMEDIA_RTP_EINDTMF, "Invalid DTMF digit" ), + PJ_BUILD_ERR( PJMEDIA_RTP_EINDTMF, "Invalid DTMF digit" ), PJ_BUILD_ERR( PJMEDIA_RTP_EREMNORFC2833,"Remote does not support RFC 2833" ), - PJ_BUILD_ERR( PJMEDIA_EBADFMT, "Bad format"), + PJ_BUILD_ERR( PJMEDIA_EBADFMT, "Bad format"), PJ_BUILD_ERR( PJMEDIA_EUNSUPMEDIATYPE, "Unsupported media type"), /* RTP session errors. */ - PJ_BUILD_ERR( PJMEDIA_RTP_EINPKT, "Invalid RTP packet" ), - PJ_BUILD_ERR( PJMEDIA_RTP_EINPACK, "Invalid RTP packing (internal error)" ), - PJ_BUILD_ERR( PJMEDIA_RTP_EINVER, "Invalid RTP version" ), - PJ_BUILD_ERR( PJMEDIA_RTP_EINSSRC, "RTP packet SSRC id mismatch" ), - PJ_BUILD_ERR( PJMEDIA_RTP_EINPT, "RTP packet payload type mismatch" ), - PJ_BUILD_ERR( PJMEDIA_RTP_EINLEN, "Invalid RTP packet length" ), + PJ_BUILD_ERR( PJMEDIA_RTP_EINPKT, "Invalid RTP packet" ), + PJ_BUILD_ERR( PJMEDIA_RTP_EINPACK, "Invalid RTP packing (internal error)" ), + PJ_BUILD_ERR( PJMEDIA_RTP_EINVER, "Invalid RTP version" ), + PJ_BUILD_ERR( PJMEDIA_RTP_EINSSRC, "RTP packet SSRC id mismatch" ), + PJ_BUILD_ERR( PJMEDIA_RTP_EINPT, "RTP packet payload type mismatch" ), + PJ_BUILD_ERR( PJMEDIA_RTP_EINLEN, "Invalid RTP packet length" ), PJ_BUILD_ERR( PJMEDIA_RTP_ESESSRESTART, "RTP session restarted" ), PJ_BUILD_ERR( PJMEDIA_RTP_ESESSPROBATION, "RTP session in probation" ), - PJ_BUILD_ERR( PJMEDIA_RTP_EBADSEQ, "Bad sequence number in RTP packet" ), - PJ_BUILD_ERR( PJMEDIA_RTP_EBADDEST, "RTP media port destination is not configured" ), + PJ_BUILD_ERR( PJMEDIA_RTP_EBADSEQ, "Bad sequence number in RTP packet" ), + PJ_BUILD_ERR( PJMEDIA_RTP_EBADDEST, "RTP media port destination is not configured" ), PJ_BUILD_ERR( PJMEDIA_RTP_ENOCONFIG, "RTP is not configured" ), /* Media port errors: */ PJ_BUILD_ERR( PJMEDIA_ENOTCOMPATIBLE, "Media ports are not compatible" ), - PJ_BUILD_ERR( PJMEDIA_ENCCLOCKRATE, "Media ports have incompatible clock rate" ), + PJ_BUILD_ERR( PJMEDIA_ENCCLOCKRATE, "Media ports have incompatible clock rate" ), PJ_BUILD_ERR( PJMEDIA_ENCSAMPLESPFRAME, "Media ports have incompatible samples per frame" ), - PJ_BUILD_ERR( PJMEDIA_ENCTYPE, "Media ports have incompatible media type" ), - PJ_BUILD_ERR( PJMEDIA_ENCBITS, "Media ports have incompatible bits per sample" ), - PJ_BUILD_ERR( PJMEDIA_ENCBYTES, "Media ports have incompatible bytes per frame" ), - PJ_BUILD_ERR( PJMEDIA_ENCCHANNEL, "Media ports have incompatible number of channels" ), + PJ_BUILD_ERR( PJMEDIA_ENCTYPE, "Media ports have incompatible media type" ), + PJ_BUILD_ERR( PJMEDIA_ENCBITS, "Media ports have incompatible bits per sample" ), + PJ_BUILD_ERR( PJMEDIA_ENCBYTES, "Media ports have incompatible bytes per frame" ), + PJ_BUILD_ERR( PJMEDIA_ENCCHANNEL, "Media ports have incompatible number of channels" ), /* Media file errors: */ PJ_BUILD_ERR( PJMEDIA_ENOTVALIDWAVE, "Not a valid WAVE file" ), - PJ_BUILD_ERR( PJMEDIA_EWAVEUNSUPP, "Unsupported WAVE file format" ), + PJ_BUILD_ERR( PJMEDIA_EWAVEUNSUPP, "Unsupported WAVE file format" ), PJ_BUILD_ERR( PJMEDIA_EWAVETOOSHORT, "WAVE file too short" ), PJ_BUILD_ERR( PJMEDIA_EFRMFILETOOBIG, "Sound frame too large for file buffer"), - PJ_BUILD_ERR( PJMEDIA_EAVIUNSUPP, "Unsupported AVI file"), + PJ_BUILD_ERR( PJMEDIA_EAVIUNSUPP, "Unsupported AVI file"), /* Sound device errors: */ - PJ_BUILD_ERR( PJMEDIA_ENOSNDREC, "No suitable sound capture device" ), - PJ_BUILD_ERR( PJMEDIA_ENOSNDPLAY, "No suitable sound playback device" ), - PJ_BUILD_ERR( PJMEDIA_ESNDINDEVID, "Invalid sound device ID" ), + PJ_BUILD_ERR( PJMEDIA_ENOSNDREC, "No suitable sound capture device" ), + PJ_BUILD_ERR( PJMEDIA_ENOSNDPLAY, "No suitable sound playback device" ), + PJ_BUILD_ERR( PJMEDIA_ESNDINDEVID, "Invalid sound device ID" ), PJ_BUILD_ERR( PJMEDIA_ESNDINSAMPLEFMT, "Invalid sample format for sound device" ), #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) /* SRTP transport errors: */ PJ_BUILD_ERR( PJMEDIA_SRTP_ECRYPTONOTMATCH, "SRTP crypto-suite name not match the offerer tag" ), - PJ_BUILD_ERR( PJMEDIA_SRTP_EINKEYLEN, "Invalid SRTP key length for specific crypto" ), + PJ_BUILD_ERR( PJMEDIA_SRTP_EINKEYLEN, "Invalid SRTP key length for specific crypto" ), PJ_BUILD_ERR( PJMEDIA_SRTP_ENOTSUPCRYPTO, "Unsupported SRTP crypto-suite" ), PJ_BUILD_ERR( PJMEDIA_SRTP_ESDPAMBIGUEANS, "SRTP SDP contains ambigue answer" ), PJ_BUILD_ERR( PJMEDIA_SRTP_ESDPDUPCRYPTOTAG,"Duplicated SRTP crypto tag" ), @@ -170,13 +169,13 @@ static const struct PJ_BUILD_ERR( PJMEDIA_SRTP_DTLS_ENOCRYPTO, "No matching SRTP crypto-suite after DTLS nego" ), PJ_BUILD_ERR( PJMEDIA_SRTP_DTLS_EPEERNOCERT,"No certificate supplied by peer in DTLS nego" ), PJ_BUILD_ERR( PJMEDIA_SRTP_DTLS_EFPNOTMATCH,"Fingerprint from signalling not match to actual fingerprint" ), - PJ_BUILD_ERR( PJMEDIA_SRTP_DTLS_ENOFPRINT, "Fingerprint not found" ), - PJ_BUILD_ERR( PJMEDIA_SRTP_DTLS_ENOPROFILE, "No valid SRTP protection profile found" ) + PJ_BUILD_ERR( PJMEDIA_SRTP_DTLS_ENOFPRINT, "Fingerprint not found" ), + PJ_BUILD_ERR( PJMEDIA_SRTP_DTLS_ENOPROFILE, "No valid SRTP protection profile found" ) #endif }; -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ @@ -184,7 +183,7 @@ static const struct * pjmedia_strerror() */ PJ_DEF(pj_str_t) pjmedia_strerror( pj_status_t statcode, - char *buf, pj_size_t bufsize ) + char *buf, pj_size_t bufsize ) { pj_str_t errstr; @@ -193,87 +192,87 @@ PJ_DEF(pj_str_t) pjmedia_strerror( pj_status_t statcode, /* See if the error comes from PortAudio. */ #if PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO if (statcode >= PJMEDIA_PORTAUDIO_ERRNO_START && - statcode <= PJMEDIA_PORTAUDIO_ERRNO_END) + statcode <= PJMEDIA_PORTAUDIO_ERRNO_END) { - //int pa_err = statcode - PJMEDIA_ERRNO_FROM_PORTAUDIO(0); - int pa_err = PJMEDIA_PORTAUDIO_ERRNO_START - statcode; - pj_str_t msg; - - msg.ptr = (char*)Pa_GetErrorText(pa_err); - msg.slen = pj_ansi_strlen(msg.ptr); + //int pa_err = statcode - PJMEDIA_ERRNO_FROM_PORTAUDIO(0); + int pa_err = PJMEDIA_PORTAUDIO_ERRNO_START - statcode; + pj_str_t msg; + + msg.ptr = (char*)Pa_GetErrorText(pa_err); + msg.slen = pj_ansi_strlen(msg.ptr); - errstr.ptr = buf; - pj_strncpy_with_null(&errstr, &msg, bufsize); - return errstr; + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, &msg, bufsize); + return errstr; } else -#endif /* PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO */ +#endif /* PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO */ #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) /* LIBSRTP error */ if (statcode >= PJMEDIA_LIBSRTP_ERRNO_START && - statcode < PJMEDIA_LIBSRTP_ERRNO_END) + statcode < PJMEDIA_LIBSRTP_ERRNO_END) { - int err = statcode - PJMEDIA_LIBSRTP_ERRNO_START; - pj_str_t msg; - - msg = pj_str((char*)get_libsrtp_errstr(err)); - - errstr.ptr = buf; - pj_strncpy_with_null(&errstr, &msg, bufsize); - return errstr; + int err = statcode - PJMEDIA_LIBSRTP_ERRNO_START; + pj_str_t msg; + + msg = pj_str((char*)get_libsrtp_errstr(err)); + + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, &msg, bufsize); + return errstr; } else #endif /* PJMEDIA error */ if (statcode >= PJMEDIA_ERRNO_START && - statcode < PJMEDIA_ERRNO_END) + statcode < PJMEDIA_ERRNO_END) { - /* Find the error in the table. - * Use binary search! - */ - int first = 0; - int n = PJ_ARRAY_SIZE(err_str); - - while (n > 0) { - int half = n/2; - int mid = first + half; - - if (err_str[mid].code < statcode) { - first = mid+1; - n -= (half+1); - } else if (err_str[mid].code > statcode) { - n = half; - } else { - first = mid; - break; - } - } - - - if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { - pj_str_t msg; - - msg.ptr = (char*)err_str[first].msg; - msg.slen = pj_ansi_strlen(err_str[first].msg); - - errstr.ptr = buf; - pj_strncpy_with_null(&errstr, &msg, bufsize); - return errstr; - - } + /* Find the error in the table. + * Use binary search! + */ + int first = 0; + int n = PJ_ARRAY_SIZE(err_str); + + while (n > 0) { + int half = n/2; + int mid = first + half; + + if (err_str[mid].code < statcode) { + first = mid+1; + n -= (half+1); + } else if (err_str[mid].code > statcode) { + n = half; + } else { + first = mid; + break; + } + } + + + if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { + pj_str_t msg; + + msg.ptr = (char*)err_str[first].msg; + msg.slen = pj_ansi_strlen(err_str[first].msg); + + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, &msg, bufsize); + return errstr; + + } } -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ /* Error not found. */ errstr.ptr = buf; errstr.slen = pj_ansi_snprintf(buf, bufsize, - "Unknown pjmedia error %d", - statcode); + "Unknown pjmedia error %d", + statcode); if (errstr.slen < 1 || errstr.slen >= (pj_ssize_t)bufsize) - errstr.slen = bufsize - 1; + errstr.slen = bufsize - 1; return errstr; } diff --git a/pjmedia/src/pjmedia/event.c b/pjmedia/src/pjmedia/event.c index f27bf44919..bf6ffb2c15 100644 --- a/pjmedia/src/pjmedia/event.c +++ b/pjmedia/src/pjmedia/event.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011-2011 Teluu Inc. (http://www.teluu.com) * @@ -25,7 +24,7 @@ #include #include -#define THIS_FILE "event.c" +#define THIS_FILE "event.c" #define MAX_EVENTS 16 @@ -33,7 +32,7 @@ // #define EVENT_TRACE #ifdef EVENT_TRACE - #define TRACE_(arg) PJ_LOG(4, arg) + #define TRACE_(arg) PJ_LOG(4, arg) #else #define TRACE_(arg) #endif @@ -126,20 +125,20 @@ static pj_status_t event_mgr_distribute_events(pjmedia_event_mgr *mgr, pj_mutex_unlock(mgr->mutex); } - TRACE_((THIS_FILE, "Distributing event %d sub->epub %p ev->epub %p " - "user data %p", i, sub->epub, ev->epub, sub->user_data)); + TRACE_((THIS_FILE, "Distributing event %d sub->epub %p ev->epub %p " + "user data %p", i, sub->epub, ev->epub, sub->user_data)); status = (*cb)(ev, user_data); if (status != PJ_SUCCESS && err == PJ_SUCCESS) - err = status; + err = status; if (rls_lock) { pj_mutex_unlock(mgr->cb_mutex); pj_mutex_lock(mgr->mutex); } } - sub = *next_sub; - i++; + sub = *next_sub; + i++; } *next_sub = NULL; @@ -155,7 +154,7 @@ static int event_worker_thread(void *arg) pjmedia_event_mgr *mgr = (pjmedia_event_mgr *)arg; while (1) { - /* Wait until there is an event. */ + /* Wait until there is an event. */ pj_sem_wait(mgr->sem); if (mgr->is_quitting) @@ -172,7 +171,7 @@ static int event_worker_thread(void *arg) PJ_DEF(pj_status_t) pjmedia_event_mgr_create(pj_pool_t *pool, unsigned options, - pjmedia_event_mgr **p_mgr) + pjmedia_event_mgr **p_mgr) { pjmedia_event_mgr *mgr; pj_status_t status; @@ -206,17 +205,17 @@ PJ_DEF(pj_status_t) pjmedia_event_mgr_create(pj_pool_t *pool, } status = pj_mutex_create_recursive(mgr->pool, "ev_cb_mutex", - &mgr->cb_mutex); + &mgr->cb_mutex); if (status != PJ_SUCCESS) { pjmedia_event_mgr_destroy(mgr); return status; } if (!event_manager_instance) - event_manager_instance = mgr; + event_manager_instance = mgr; if (p_mgr) - *p_mgr = mgr; + *p_mgr = mgr; return PJ_SUCCESS; } @@ -261,7 +260,7 @@ PJ_DEF(void) pjmedia_event_mgr_destroy(pjmedia_event_mgr *mgr) pj_pool_release(mgr->pool); if (event_manager_instance == mgr) - event_manager_instance = NULL; + event_manager_instance = NULL; } PJ_DEF(void) pjmedia_event_init( pjmedia_event *event, @@ -272,7 +271,7 @@ PJ_DEF(void) pjmedia_event_init( pjmedia_event *event, pj_bzero(event, sizeof(*event)); event->type = type; if (ts) - event->timestamp.u64 = ts->u64; + event->timestamp.u64 = ts->u64; event->epub = event->src = src; } @@ -296,15 +295,15 @@ PJ_DEF(pj_status_t) pjmedia_event_subscribe( pjmedia_event_mgr *mgr, */ sub = mgr->esub_list.next; while (sub != &mgr->esub_list) { - esub *next = sub->next; + esub *next = sub->next; if (sub->cb == cb && sub->user_data == user_data && sub->epub == epub) { pj_mutex_unlock(mgr->mutex); return PJ_SUCCESS; } - sub = next; - i++; + sub = next; + i++; } if (mgr->free_esub_list.next != &mgr->free_esub_list) { @@ -318,7 +317,7 @@ PJ_DEF(pj_status_t) pjmedia_event_subscribe( pjmedia_event_mgr *mgr, pj_list_push_back(&mgr->esub_list, sub); TRACE_((THIS_FILE, "Media event: subscribing event %d epub %p " - "user data %p", i, epub, user_data)); + "user data %p", i, epub, user_data)); pj_mutex_unlock(mgr->mutex); @@ -341,18 +340,18 @@ pjmedia_event_unsubscribe(pjmedia_event_mgr *mgr, PJ_ASSERT_RETURN(mgr, PJ_EINVAL); while(1) { - pj_mutex_lock(mgr->mutex); - if (pj_mutex_trylock(mgr->cb_mutex) == PJ_SUCCESS) - break; - - /* The callback is currently being called, wait for a while. */ - pj_mutex_unlock(mgr->mutex); - pj_thread_sleep(10); + pj_mutex_lock(mgr->mutex); + if (pj_mutex_trylock(mgr->cb_mutex) == PJ_SUCCESS) + break; + + /* The callback is currently being called, wait for a while. */ + pj_mutex_unlock(mgr->mutex); + pj_thread_sleep(10); } sub = mgr->esub_list.next; while (sub != &mgr->esub_list) { - esub *next = sub->next; + esub *next = sub->next; if (sub->cb == cb && (sub->user_data == user_data || !user_data) && (sub->epub == epub || !epub)) { @@ -370,12 +369,12 @@ pjmedia_event_unsubscribe(pjmedia_event_mgr *mgr, if (user_data && epub) break; } - sub = next; - i++; + sub = next; + i++; } TRACE_((THIS_FILE, "Media event: unsubscribing event %d/%d epub %p " - "user data %p", j, i, epub, user_data)); + "user data %p", j, i, epub, user_data)); pj_mutex_unlock(mgr->cb_mutex); pj_mutex_unlock(mgr->mutex); @@ -425,7 +424,7 @@ PJ_DEF(pj_status_t) pjmedia_event_publish( pjmedia_event_mgr *mgr, &mgr->pub_next_sub, PJ_FALSE); if (status != PJ_SUCCESS && err == PJ_SUCCESS) - err = status; + err = status; } while(ev_queue.head != ev_queue.tail || ev_queue.is_full); mgr->pub_ev_queue = NULL; diff --git a/pjmedia/src/pjmedia/ffmpeg_util.c b/pjmedia/src/pjmedia/ffmpeg_util.c index 9de668519d..c5b871f195 100644 --- a/pjmedia/src/pjmedia/ffmpeg_util.c +++ b/pjmedia/src/pjmedia/ffmpeg_util.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * @@ -30,8 +29,8 @@ /* Conversion table between pjmedia_format_id and AVPixelFormat */ static const struct ffmpeg_fmt_table_t { - pjmedia_format_id id; - enum AVPixelFormat pf; + pjmedia_format_id id; + enum AVPixelFormat pf; } ffmpeg_fmt_table[] = { { PJMEDIA_FORMAT_RGBA, AV(PIX_FMT_RGBA)}, @@ -54,20 +53,20 @@ static const struct ffmpeg_fmt_table_t /* Conversion table between pjmedia_format_id and CodecID */ static const struct ffmpeg_codec_table_t { - pjmedia_format_id id; - unsigned codec_id; + pjmedia_format_id id; + unsigned codec_id; } ffmpeg_codec_table[] = { - {PJMEDIA_FORMAT_H261, AV(CODEC_ID_H261)}, - {PJMEDIA_FORMAT_H263, AV(CODEC_ID_H263)}, - {PJMEDIA_FORMAT_H263P, AV(CODEC_ID_H263P)}, - {PJMEDIA_FORMAT_H264, AV(CODEC_ID_H264)}, - {PJMEDIA_FORMAT_VP8, AV(CODEC_ID_VP8)}, - {PJMEDIA_FORMAT_VP9, AV(CODEC_ID_VP9)}, - {PJMEDIA_FORMAT_MPEG1VIDEO, AV(CODEC_ID_MPEG1VIDEO)}, + {PJMEDIA_FORMAT_H261, AV(CODEC_ID_H261)}, + {PJMEDIA_FORMAT_H263, AV(CODEC_ID_H263)}, + {PJMEDIA_FORMAT_H263P, AV(CODEC_ID_H263P)}, + {PJMEDIA_FORMAT_H264, AV(CODEC_ID_H264)}, + {PJMEDIA_FORMAT_VP8, AV(CODEC_ID_VP8)}, + {PJMEDIA_FORMAT_VP9, AV(CODEC_ID_VP9)}, + {PJMEDIA_FORMAT_MPEG1VIDEO, AV(CODEC_ID_MPEG1VIDEO)}, {PJMEDIA_FORMAT_MPEG2VIDEO, AV(CODEC_ID_MPEG2VIDEO)}, - {PJMEDIA_FORMAT_MPEG4, AV(CODEC_ID_MPEG4)}, - {PJMEDIA_FORMAT_MJPEG, AV(CODEC_ID_MJPEG)} + {PJMEDIA_FORMAT_MPEG4, AV(CODEC_ID_MPEG4)}, + {PJMEDIA_FORMAT_MJPEG, AV(CODEC_ID_MJPEG)} }; static int pjmedia_ffmpeg_ref_cnt; @@ -77,10 +76,10 @@ static void ffmpeg_log_cb(void* ptr, int level, const char* fmt, va_list vl); void pjmedia_ffmpeg_add_ref() { if (pjmedia_ffmpeg_ref_cnt++ == 0) { - av_log_set_level(AV_LOG_ERROR); - av_log_set_callback(&ffmpeg_log_cb); + av_log_set_level(AV_LOG_ERROR); + av_log_set_callback(&ffmpeg_log_cb); #if !LIBAVCODEC_VER_AT_LEAST(58,137) - av_register_all(); + av_register_all(); #endif } } @@ -88,7 +87,7 @@ void pjmedia_ffmpeg_add_ref() void pjmedia_ffmpeg_dec_ref() { if (pjmedia_ffmpeg_ref_cnt-- == 1) { - /* How to shutdown ffmpeg? */ + /* How to shutdown ffmpeg? */ } if (pjmedia_ffmpeg_ref_cnt < 0) pjmedia_ffmpeg_ref_cnt = 0; @@ -105,21 +104,21 @@ static void ffmpeg_log_cb(void* ptr, int level, const char* fmt, va_list vl) /* Custom callback needs to filter log level by itself */ if (level > av_log_get_level()) - return; + return; /* Add original ffmpeg sender to log format */ if (ptr) { - AVClass* avc = *(AVClass**)ptr; - len = pj_ansi_snprintf(buf, bufsize, "%s: ", avc->item_name(ptr)); - if (len < 1 || len >= bufsize) - len = bufsize - 1; - bufsize -= len; + AVClass* avc = *(AVClass**)ptr; + len = pj_ansi_snprintf(buf, bufsize, "%s: ", avc->item_name(ptr)); + if (len < 1 || len >= bufsize) + len = bufsize - 1; + bufsize -= len; } /* Copy original log format */ len = pj_ansi_strlen(fmt); if (len > bufsize-1) - len = bufsize-1; + len = bufsize-1; pj_memcpy(buf+sizeof(buf)-bufsize, fmt, len); bufsize -= len; @@ -133,15 +132,15 @@ static void ffmpeg_log_cb(void* ptr, int level, const char* fmt, va_list vl) pj_status_t pjmedia_format_id_to_PixelFormat(pjmedia_format_id fmt_id, - enum AVPixelFormat *pixel_format) + enum AVPixelFormat *pixel_format) { unsigned i; for (i=0; iid==fmt_id && t->pf != AV(PIX_FMT_NONE)) { - *pixel_format = t->pf; - return PJ_SUCCESS; - } + const struct ffmpeg_fmt_table_t *t = &ffmpeg_fmt_table[i]; + if (t->id==fmt_id && t->pf != AV(PIX_FMT_NONE)) { + *pixel_format = t->pf; + return PJ_SUCCESS; + } } *pixel_format = AV(PIX_FMT_NONE); @@ -149,30 +148,30 @@ pj_status_t pjmedia_format_id_to_PixelFormat(pjmedia_format_id fmt_id, } pj_status_t PixelFormat_to_pjmedia_format_id(enum AVPixelFormat pf, - pjmedia_format_id *fmt_id) + pjmedia_format_id *fmt_id) { unsigned i; for (i=0; ipf == pf) { - if (fmt_id) *fmt_id = t->id; - return PJ_SUCCESS; - } + const struct ffmpeg_fmt_table_t *t = &ffmpeg_fmt_table[i]; + if (t->pf == pf) { + if (fmt_id) *fmt_id = t->id; + return PJ_SUCCESS; + } } return PJ_ENOTFOUND; } pj_status_t pjmedia_format_id_to_CodecID(pjmedia_format_id fmt_id, - unsigned *codec_id) + unsigned *codec_id) { unsigned i; for (i=0; iid==fmt_id && t->codec_id != AV(PIX_FMT_NONE)) { - *codec_id = t->codec_id; - return PJ_SUCCESS; - } + const struct ffmpeg_codec_table_t *t = &ffmpeg_codec_table[i]; + if (t->id==fmt_id && t->codec_id != AV(PIX_FMT_NONE)) { + *codec_id = t->codec_id; + return PJ_SUCCESS; + } } *codec_id = (unsigned)AV(PIX_FMT_NONE); @@ -180,15 +179,15 @@ pj_status_t pjmedia_format_id_to_CodecID(pjmedia_format_id fmt_id, } pj_status_t CodecID_to_pjmedia_format_id(unsigned codec_id, - pjmedia_format_id *fmt_id) + pjmedia_format_id *fmt_id) { unsigned i; for (i=0; icodec_id == codec_id) { - if (fmt_id) *fmt_id = t->id; - return PJ_SUCCESS; - } + const struct ffmpeg_codec_table_t *t = &ffmpeg_codec_table[i]; + if ((unsigned)t->codec_id == codec_id) { + if (fmt_id) *fmt_id = t->id; + return PJ_SUCCESS; + } } return PJ_ENOTFOUND; @@ -200,4 +199,4 @@ pj_status_t CodecID_to_pjmedia_format_id(unsigned codec_id, # pragma comment( lib, "avutil.lib") #endif -#endif /* PJMEDIA_HAS_LIBAVFORMAT */ +#endif /* PJMEDIA_HAS_LIBAVFORMAT */ diff --git a/pjmedia/src/pjmedia/ffmpeg_util.h b/pjmedia/src/pjmedia/ffmpeg_util.h index dc9bedbd5d..6711f4847d 100644 --- a/pjmedia/src/pjmedia/ffmpeg_util.h +++ b/pjmedia/src/pjmedia/ffmpeg_util.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * @@ -29,7 +28,7 @@ #ifdef _MSC_VER # ifndef __cplusplus -# define inline _inline +# define inline _inline # endif # pragma warning(disable:4244) /* possible loss of data */ #endif @@ -39,30 +38,30 @@ #ifdef PJMEDIA_USE_OLD_FFMPEG -# define AVPixelFormat PixelFormat -# define AV(str) str -# define PIX_FMT_GBRP PIX_FMT_GBR24P +# define AVPixelFormat PixelFormat +# define AV(str) str +# define PIX_FMT_GBRP PIX_FMT_GBR24P #else -# define AV(str) AV_ ## str +# define AV(str) AV_ ## str #endif #define LIBAVCODEC_VER_AT_LEAST(major,minor) (LIBAVCODEC_VERSION_MAJOR > major || \ - (LIBAVCODEC_VERSION_MAJOR == major && \ - LIBAVCODEC_VERSION_MINOR >= minor)) + (LIBAVCODEC_VERSION_MAJOR == major && \ + LIBAVCODEC_VERSION_MINOR >= minor)) void pjmedia_ffmpeg_add_ref(); void pjmedia_ffmpeg_dec_ref(); pj_status_t pjmedia_format_id_to_PixelFormat(pjmedia_format_id fmt_id, - enum AVPixelFormat *pixel_format); + enum AVPixelFormat *pixel_format); pj_status_t PixelFormat_to_pjmedia_format_id(enum AVPixelFormat pf, - pjmedia_format_id *fmt_id); + pjmedia_format_id *fmt_id); pj_status_t pjmedia_format_id_to_CodecID(pjmedia_format_id fmt_id, - unsigned *codec_id); + unsigned *codec_id); pj_status_t CodecID_to_pjmedia_format_id(unsigned codec_id, - pjmedia_format_id *fmt_id); + pjmedia_format_id *fmt_id); #endif /* __PJMEDIA_FFMPEG_UTIL_H__ */ diff --git a/pjmedia/src/pjmedia/format.c b/pjmedia/src/pjmedia/format.c index 89573f640d..8121e91328 100644 --- a/pjmedia/src/pjmedia/format.c +++ b/pjmedia/src/pjmedia/format.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -26,23 +25,23 @@ PJ_DEF(pjmedia_audio_format_detail*) pjmedia_format_get_audio_format_detail(const pjmedia_format *fmt, - pj_bool_t assert_valid) + pj_bool_t assert_valid) { if (fmt->detail_type==PJMEDIA_FORMAT_DETAIL_AUDIO) { - return (pjmedia_audio_format_detail*) &fmt->det.aud; + return (pjmedia_audio_format_detail*) &fmt->det.aud; } else { /* Get rid of unused var compiler warning if pj_assert() * macro does not do anything */ PJ_UNUSED_ARG(assert_valid); - pj_assert(!assert_valid || !"Invalid audio format detail"); - return NULL; + pj_assert(!assert_valid || !"Invalid audio format detail"); + return NULL; } } PJ_DEF(pjmedia_format*) pjmedia_format_copy(pjmedia_format *dst, - const pjmedia_format *src) + const pjmedia_format *src) { return (pjmedia_format*)pj_memcpy(dst, src, sizeof(*src)); } @@ -52,24 +51,24 @@ PJ_DEF(pjmedia_format*) pjmedia_format_copy(pjmedia_format *dst, static pj_status_t apply_packed_fmt(const pjmedia_video_format_info *fi, - pjmedia_video_apply_fmt_param *aparam); + pjmedia_video_apply_fmt_param *aparam); static pj_status_t apply_planar_420(const pjmedia_video_format_info *fi, - pjmedia_video_apply_fmt_param *aparam); + pjmedia_video_apply_fmt_param *aparam); static pj_status_t apply_planar_422(const pjmedia_video_format_info *fi, - pjmedia_video_apply_fmt_param *aparam); + pjmedia_video_apply_fmt_param *aparam); static pj_status_t apply_planar_444(const pjmedia_video_format_info *fi, - pjmedia_video_apply_fmt_param *aparam); + pjmedia_video_apply_fmt_param *aparam); static pj_status_t apply_biplanar_420(const pjmedia_video_format_info *fi, - pjmedia_video_apply_fmt_param *aparam); + pjmedia_video_apply_fmt_param *aparam); struct pjmedia_video_format_mgr { - unsigned max_info; - unsigned info_cnt; + unsigned max_info; + unsigned info_cnt; pjmedia_video_format_info **infos; }; @@ -95,11 +94,11 @@ static pjmedia_video_format_info built_in_vid_fmt_info[] = }; PJ_DEF(void) pjmedia_format_init_video( pjmedia_format *fmt, - pj_uint32_t fmt_id, - unsigned width, - unsigned height, - unsigned fps_num, - unsigned fps_denum) + pj_uint32_t fmt_id, + unsigned width, + unsigned height, + unsigned fps_num, + unsigned fps_denum) { pj_assert(fps_denum); fmt->id = fmt_id; @@ -113,37 +112,37 @@ PJ_DEF(void) pjmedia_format_init_video( pjmedia_format *fmt, fmt->det.vid.avg_bps = fmt->det.vid.max_bps = 0; if (pjmedia_video_format_mgr_instance()) { - const pjmedia_video_format_info *vfi; - pjmedia_video_apply_fmt_param vafp; - pj_uint32_t bps; + const pjmedia_video_format_info *vfi; + pjmedia_video_apply_fmt_param vafp; + pj_uint32_t bps; - vfi = pjmedia_get_video_format_info(NULL, fmt->id); + vfi = pjmedia_get_video_format_info(NULL, fmt->id); if (vfi) { - pj_bzero(&vafp, sizeof(vafp)); - vafp.size = fmt->det.vid.size; - vfi->apply_fmt(vfi, &vafp); + pj_bzero(&vafp, sizeof(vafp)); + vafp.size = fmt->det.vid.size; + vfi->apply_fmt(vfi, &vafp); - bps = (pj_uint32_t)((pj_uint64_t)vafp.framebytes * fps_num * 8 / fps_denum); - fmt->det.vid.avg_bps = fmt->det.vid.max_bps = bps; + bps = (pj_uint32_t)((pj_uint64_t)vafp.framebytes * fps_num * 8 / fps_denum); + fmt->det.vid.avg_bps = fmt->det.vid.max_bps = bps; } } } PJ_DEF(pjmedia_video_format_detail*) pjmedia_format_get_video_format_detail(const pjmedia_format *fmt, - pj_bool_t assert_valid) + pj_bool_t assert_valid) { if (fmt->detail_type==PJMEDIA_FORMAT_DETAIL_VIDEO) { - return (pjmedia_video_format_detail*)&fmt->det.vid; + return (pjmedia_video_format_detail*)&fmt->det.vid; } else { - pj_assert(!assert_valid || !"Invalid video format detail"); - return NULL; + pj_assert(!assert_valid || !"Invalid video format detail"); + return NULL; } } static pj_status_t apply_packed_fmt(const pjmedia_video_format_info *fi, - pjmedia_video_apply_fmt_param *aparam) + pjmedia_video_apply_fmt_param *aparam) { unsigned i; pj_size_t stride; @@ -160,15 +159,15 @@ static pj_status_t apply_packed_fmt(const pjmedia_video_format_info *fi, /* Zero unused planes */ for (i=1; istrides[i] = 0; - aparam->planes[i] = NULL; + aparam->strides[i] = 0; + aparam->planes[i] = NULL; } return PJ_SUCCESS; } static pj_status_t apply_planar_420(const pjmedia_video_format_info *fi, - pjmedia_video_apply_fmt_param *aparam) + pjmedia_video_apply_fmt_param *aparam) { unsigned i; pj_size_t Y_bytes; @@ -192,8 +191,8 @@ static pj_status_t apply_planar_420(const pjmedia_video_format_info *fi, /* Zero unused planes */ for (i=3; istrides[i] = 0; - aparam->planes[i] = NULL; + aparam->strides[i] = 0; + aparam->planes[i] = NULL; aparam->plane_bytes[i] = 0; } @@ -201,7 +200,7 @@ static pj_status_t apply_planar_420(const pjmedia_video_format_info *fi, } static pj_status_t apply_planar_422(const pjmedia_video_format_info *fi, - pjmedia_video_apply_fmt_param *aparam) + pjmedia_video_apply_fmt_param *aparam) { unsigned i; pj_size_t Y_bytes; @@ -225,8 +224,8 @@ static pj_status_t apply_planar_422(const pjmedia_video_format_info *fi, /* Zero unused planes */ for (i=3; istrides[i] = 0; - aparam->planes[i] = NULL; + aparam->strides[i] = 0; + aparam->planes[i] = NULL; aparam->plane_bytes[i] = 0; } @@ -234,7 +233,7 @@ static pj_status_t apply_planar_422(const pjmedia_video_format_info *fi, } static pj_status_t apply_planar_444(const pjmedia_video_format_info *fi, - pjmedia_video_apply_fmt_param *aparam) + pjmedia_video_apply_fmt_param *aparam) { unsigned i; pj_size_t Y_bytes; @@ -247,19 +246,19 @@ static pj_status_t apply_planar_444(const pjmedia_video_format_info *fi, /* Planar formats use 3 plane */ aparam->strides[0] = aparam->strides[1] = - aparam->strides[2] = aparam->size.w; + aparam->strides[2] = aparam->size.w; aparam->planes[0] = aparam->buffer; aparam->planes[1] = aparam->planes[0] + Y_bytes; aparam->planes[2] = aparam->planes[1] + Y_bytes; aparam->plane_bytes[0] = aparam->plane_bytes[1] = - aparam->plane_bytes[2] = Y_bytes; + aparam->plane_bytes[2] = Y_bytes; /* Zero unused planes */ for (i=3; istrides[i] = 0; - aparam->planes[i] = NULL; + aparam->strides[i] = 0; + aparam->planes[i] = NULL; aparam->plane_bytes[i] = 0; } @@ -267,7 +266,7 @@ static pj_status_t apply_planar_444(const pjmedia_video_format_info *fi, } static pj_status_t apply_biplanar_420(const pjmedia_video_format_info *fi, - pjmedia_video_apply_fmt_param *aparam) + pjmedia_video_apply_fmt_param *aparam) { unsigned i; pj_size_t Y_bytes; @@ -290,8 +289,8 @@ static pj_status_t apply_biplanar_420(const pjmedia_video_format_info *fi, /* Zero unused planes */ for (i=2; istrides[i] = 0; - aparam->planes[i] = NULL; + aparam->strides[i] = 0; + aparam->planes[i] = NULL; aparam->plane_bytes[i] = 0; } @@ -301,9 +300,9 @@ static pj_status_t apply_biplanar_420(const pjmedia_video_format_info *fi, PJ_DEF(pj_status_t) pjmedia_video_format_mgr_create(pj_pool_t *pool, - unsigned max_fmt, - unsigned options, - pjmedia_video_format_mgr **p_mgr) + unsigned max_fmt, + unsigned options, + pjmedia_video_format_mgr **p_mgr) { pjmedia_video_format_mgr *mgr; unsigned i; @@ -318,15 +317,15 @@ pjmedia_video_format_mgr_create(pj_pool_t *pool, mgr->infos = pj_pool_calloc(pool, max_fmt, sizeof(pjmedia_video_format_info *)); if (video_format_mgr_instance == NULL) - video_format_mgr_instance = mgr; + video_format_mgr_instance = mgr; for (i=0; iinfos[0]; n = mgr->info_cnt; for (; n > 0; ) { - unsigned half = n / 2; - pjmedia_video_format_info **mid = first + half; - - if ((*mid)->id < id) { - first = ++mid; - n -= half + 1; - } else if ((*mid)->id==id) { - return *mid; - } else { - n = half; - } + unsigned half = n / 2; + pjmedia_video_format_info **mid = first + half; + + if ((*mid)->id < id) { + first = ++mid; + n -= half + 1; + } else if ((*mid)->id==id) { + return *mid; + } else { + n = half; + } } return NULL; @@ -367,33 +366,33 @@ pjmedia_get_video_format_info(pjmedia_video_format_mgr *mgr, PJ_DEF(pj_status_t) pjmedia_register_video_format_info(pjmedia_video_format_mgr *mgr, - pjmedia_video_format_info *info) + pjmedia_video_format_info *info) { unsigned i; if (!mgr) - mgr = pjmedia_video_format_mgr_instance(); + mgr = pjmedia_video_format_mgr_instance(); PJ_ASSERT_RETURN(mgr != NULL, PJ_EINVALIDOP); if (mgr->info_cnt >= mgr->max_info) - return PJ_ETOOMANY; + return PJ_ETOOMANY; /* Insert to the array, sorted */ for (i=0; iinfo_cnt; ++i) { - if (mgr->infos[i]->id >= info->id) - break; + if (mgr->infos[i]->id >= info->id) + break; } if (i < mgr->info_cnt) { - if (mgr->infos[i]->id == info->id) { - /* just overwrite */ - mgr->infos[i] = info; - return PJ_SUCCESS; - } - - pj_memmove(&mgr->infos[i+1], &mgr->infos[i], - (mgr->info_cnt - i) * sizeof(pjmedia_video_format_info*)); + if (mgr->infos[i]->id == info->id) { + /* just overwrite */ + mgr->infos[i] = info; + return PJ_SUCCESS; + } + + pj_memmove(&mgr->infos[i+1], &mgr->infos[i], + (mgr->info_cnt - i) * sizeof(pjmedia_video_format_info*)); } mgr->infos[i] = info; @@ -418,13 +417,13 @@ pjmedia_video_format_mgr_set_instance(pjmedia_video_format_mgr *mgr) PJ_DEF(void) pjmedia_video_format_mgr_destroy(pjmedia_video_format_mgr *mgr) { if (!mgr) - mgr = pjmedia_video_format_mgr_instance(); + mgr = pjmedia_video_format_mgr_instance(); PJ_ASSERT_ON_FAIL(mgr != NULL, return); mgr->info_cnt = 0; if (video_format_mgr_instance == mgr) - video_format_mgr_instance = NULL; + video_format_mgr_instance = NULL; } @@ -436,8 +435,8 @@ PJ_DEF(void) pjmedia_video_format_mgr_destroy(pjmedia_video_format_mgr *mgr) * Fill video frame buffer with black color. */ PJ_DEF(pj_status_t) pjmedia_video_format_fill_black(const pjmedia_format *fmt, - void *buf, - pj_size_t buf_size) + void *buf, + pj_size_t buf_size) { const pjmedia_video_format_info *vfi; pjmedia_video_apply_fmt_param vafp; @@ -452,36 +451,36 @@ PJ_DEF(pj_status_t) pjmedia_video_format_fill_black(const pjmedia_format *fmt, vafp.size = fmt->det.vid.size; status = (*vfi->apply_fmt)(vfi, &vafp); if (status != PJ_SUCCESS) - return status; + return status; if (buf_size < vafp.framebytes) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; if (vfi->color_model == PJMEDIA_COLOR_MODEL_RGB) { - pj_memset(buf, 0, vafp.framebytes); + pj_memset(buf, 0, vafp.framebytes); } else if (fmt_id == PJMEDIA_FORMAT_I420 || - fmt_id == PJMEDIA_FORMAT_YV12 || - fmt_id == PJMEDIA_FORMAT_I422) + fmt_id == PJMEDIA_FORMAT_YV12 || + fmt_id == PJMEDIA_FORMAT_I422) { - pj_memset(buf, 16, vafp.plane_bytes[0]); - pj_memset((pj_uint8_t*)buf + vafp.plane_bytes[0], 0x80, - vafp.plane_bytes[1] * 2); + pj_memset(buf, 16, vafp.plane_bytes[0]); + pj_memset((pj_uint8_t*)buf + vafp.plane_bytes[0], 0x80, + vafp.plane_bytes[1] * 2); } else if (fmt_id == PJMEDIA_FORMAT_NV12 || - fmt_id == PJMEDIA_FORMAT_NV21) + fmt_id == PJMEDIA_FORMAT_NV21) { - pj_memset(buf, 16, vafp.plane_bytes[0]); - pj_memset((pj_uint8_t*)buf + vafp.plane_bytes[0], 0x80, - vafp.plane_bytes[1]); + pj_memset(buf, 16, vafp.plane_bytes[0]); + pj_memset((pj_uint8_t*)buf + vafp.plane_bytes[0], 0x80, + vafp.plane_bytes[1]); } else if (fmt_id == PJMEDIA_FORMAT_YUY2) { - pj_uint8_t *ptr = (pj_uint8_t *)buf; - pj_size_t i; + pj_uint8_t *ptr = (pj_uint8_t *)buf; + pj_size_t i; - for (i = vafp.framebytes / 2; i > 0; i--) { - *(ptr++) = 0x10; *(ptr++) = 0x80; - } + for (i = vafp.framebytes / 2; i > 0; i--) { + *(ptr++) = 0x10; *(ptr++) = 0x80; + } } else { - /* Don't know how to fill it black (for now) */ - return PJ_ENOTSUP; + /* Don't know how to fill it black (for now) */ + return PJ_ENOTSUP; } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia/g711.c b/pjmedia/src/pjmedia/g711.c index 5ec2eaf240..fe4f4389bc 100644 --- a/pjmedia/src/pjmedia/g711.c +++ b/pjmedia/src/pjmedia/g711.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,56 +34,56 @@ #if defined(PJMEDIA_HAS_G711_CODEC) && PJMEDIA_HAS_G711_CODEC!=0 /* We removed PLC in 0.6 (and re-enabled it again in 0.9!) */ -#define PLC_DISABLED 0 +#define PLC_DISABLED 0 -#define G711_BPS 64000 -#define G711_CODEC_CNT 0 /* number of codec to preallocate in memory */ -#define PTIME 10 /* basic frame size is 10 msec */ -#define FRAME_SIZE (8000 * PTIME / 1000) /* 80 bytes */ +#define G711_BPS 64000 +#define G711_CODEC_CNT 0 /* number of codec to preallocate in memory */ +#define PTIME 10 /* basic frame size is 10 msec */ +#define FRAME_SIZE (8000 * PTIME / 1000) /* 80 bytes */ #define SAMPLES_PER_FRAME (8000 * PTIME / 1000) /* 80 samples */ /* Prototypes for G711 factory */ static pj_status_t g711_test_alloc( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ); + const pjmedia_codec_info *id ); static pj_status_t g711_default_attr( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ); + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ); static pj_status_t g711_enum_codecs (pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]); + unsigned *count, + pjmedia_codec_info codecs[]); static pj_status_t g711_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec); + const pjmedia_codec_info *id, + pjmedia_codec **p_codec); static pj_status_t g711_dealloc_codec( pjmedia_codec_factory *factory, - pjmedia_codec *codec ); + pjmedia_codec *codec ); /* Prototypes for G711 implementation. */ static pj_status_t g711_init( pjmedia_codec *codec, - pj_pool_t *pool ); + pj_pool_t *pool ); static pj_status_t g711_open( pjmedia_codec *codec, - pjmedia_codec_param *attr ); + pjmedia_codec_param *attr ); static pj_status_t g711_close( pjmedia_codec *codec ); static pj_status_t g711_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ); + const pjmedia_codec_param *attr ); static pj_status_t g711_parse(pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *timestamp, - unsigned *frame_cnt, - pjmedia_frame frames[]); + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *timestamp, + unsigned *frame_cnt, + pjmedia_frame frames[]); static pj_status_t g711_encode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); static pj_status_t g711_decode( pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output); + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output); #if !PLC_DISABLED static pj_status_t g711_recover( pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output); + unsigned output_buf_len, + struct pjmedia_frame *output); #endif /* Definition for G711 codec operations. */ @@ -118,24 +117,24 @@ static pjmedia_codec_factory_op g711_factory_op = /* G711 factory private data */ static struct g711_factory { - pjmedia_codec_factory base; - pjmedia_endpt *endpt; - pj_pool_t *pool; - pj_mutex_t *mutex; - pjmedia_codec codec_list; + pjmedia_codec_factory base; + pjmedia_endpt *endpt; + pj_pool_t *pool; + pj_mutex_t *mutex; + pjmedia_codec codec_list; } g711_factory; /* G711 codec private data. */ struct g711_private { - unsigned pt; + unsigned pt; #if !PLC_DISABLED - pj_bool_t plc_enabled; - pjmedia_plc *plc; + pj_bool_t plc_enabled; + pjmedia_plc *plc; #endif - pj_bool_t vad_enabled; + pj_bool_t vad_enabled; pjmedia_silence_det *vad; - pj_timestamp last_tx; + pj_timestamp last_tx; }; @@ -145,8 +144,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_g711_init(pjmedia_endpt *endpt) pj_status_t status; if (g711_factory.endpt != NULL) { - /* Already initialized. */ - return PJ_SUCCESS; + /* Already initialized. */ + return PJ_SUCCESS; } /* Init factory */ @@ -159,37 +158,37 @@ PJ_DEF(pj_status_t) pjmedia_codec_g711_init(pjmedia_endpt *endpt) /* Create pool */ g711_factory.pool = pjmedia_endpt_create_pool(endpt, "g711", 4000, 4000); if (!g711_factory.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create mutex. */ status = pj_mutex_create_simple(g711_factory.pool, "g611", - &g711_factory.mutex); + &g711_factory.mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); if (!codec_mgr) { - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; } /* Register codec factory to endpoint. */ status = pjmedia_codec_mgr_register_factory(codec_mgr, - &g711_factory.base); + &g711_factory.base); if (status != PJ_SUCCESS) - return status; + return status; return PJ_SUCCESS; on_error: if (g711_factory.mutex) { - pj_mutex_destroy(g711_factory.mutex); - g711_factory.mutex = NULL; + pj_mutex_destroy(g711_factory.mutex); + g711_factory.mutex = NULL; } if (g711_factory.pool) { - pj_pool_release(g711_factory.pool); - g711_factory.pool = NULL; + pj_pool_release(g711_factory.pool); + g711_factory.pool = NULL; } return status; } @@ -200,8 +199,8 @@ PJ_DEF(pj_status_t) pjmedia_codec_g711_deinit(void) pj_status_t status; if (g711_factory.endpt == NULL) { - /* Not registered. */ - return PJ_SUCCESS; + /* Not registered. */ + return PJ_SUCCESS; } /* Lock mutex. */ @@ -210,14 +209,14 @@ PJ_DEF(pj_status_t) pjmedia_codec_g711_deinit(void) /* Get the codec manager. */ codec_mgr = pjmedia_endpt_get_codec_mgr(g711_factory.endpt); if (!codec_mgr) { - g711_factory.endpt = NULL; - pj_mutex_unlock(g711_factory.mutex); - return PJ_EINVALIDOP; + g711_factory.endpt = NULL; + pj_mutex_unlock(g711_factory.mutex); + return PJ_EINVALIDOP; } /* Unregister G711 codec factory. */ status = pjmedia_codec_mgr_unregister_factory(codec_mgr, - &g711_factory.base); + &g711_factory.base); g711_factory.endpt = NULL; /* Destroy mutex. */ @@ -235,7 +234,7 @@ PJ_DEF(pj_status_t) pjmedia_codec_g711_deinit(void) } static pj_status_t g711_test_alloc(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id ) + const pjmedia_codec_info *id ) { PJ_UNUSED_ARG(factory); @@ -244,8 +243,8 @@ static pj_status_t g711_test_alloc(pjmedia_codec_factory *factory, } static pj_status_t g711_default_attr (pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec_param *attr ) + const pjmedia_codec_info *id, + pjmedia_codec_param *attr ) { PJ_UNUSED_ARG(factory); @@ -275,28 +274,28 @@ static pj_status_t g711_default_attr (pjmedia_codec_factory *factory, } static pj_status_t g711_enum_codecs(pjmedia_codec_factory *factory, - unsigned *max_count, - pjmedia_codec_info codecs[]) + unsigned *max_count, + pjmedia_codec_info codecs[]) { unsigned count = 0; PJ_UNUSED_ARG(factory); if (count < *max_count) { - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_PCMU; - codecs[count].encoding_name = pj_str("PCMU"); - codecs[count].clock_rate = 8000; - codecs[count].channel_cnt = 1; - ++count; + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_PCMU; + codecs[count].encoding_name = pj_str("PCMU"); + codecs[count].clock_rate = 8000; + codecs[count].channel_cnt = 1; + ++count; } if (count < *max_count) { - codecs[count].type = PJMEDIA_TYPE_AUDIO; - codecs[count].pt = PJMEDIA_RTP_PT_PCMA; - codecs[count].encoding_name = pj_str("PCMA"); - codecs[count].clock_rate = 8000; - codecs[count].channel_cnt = 1; - ++count; + codecs[count].type = PJMEDIA_TYPE_AUDIO; + codecs[count].pt = PJMEDIA_RTP_PT_PCMA; + codecs[count].encoding_name = pj_str("PCMA"); + codecs[count].clock_rate = 8000; + codecs[count].channel_cnt = 1; + ++count; } *max_count = count; @@ -305,8 +304,8 @@ static pj_status_t g711_enum_codecs(pjmedia_codec_factory *factory, } static pj_status_t g711_alloc_codec( pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { pjmedia_codec *codec = NULL; pj_status_t status; @@ -318,44 +317,44 @@ static pj_status_t g711_alloc_codec( pjmedia_codec_factory *factory, /* Allocate new codec if no more is available */ if (pj_list_empty(&g711_factory.codec_list)) { - struct g711_private *codec_priv; + struct g711_private *codec_priv; - codec = PJ_POOL_ALLOC_T(g711_factory.pool, pjmedia_codec); - codec_priv = PJ_POOL_ZALLOC_T(g711_factory.pool, struct g711_private); - if (!codec || !codec_priv) { - pj_mutex_unlock(g711_factory.mutex); - return PJ_ENOMEM; - } + codec = PJ_POOL_ALLOC_T(g711_factory.pool, pjmedia_codec); + codec_priv = PJ_POOL_ZALLOC_T(g711_factory.pool, struct g711_private); + if (!codec || !codec_priv) { + pj_mutex_unlock(g711_factory.mutex); + return PJ_ENOMEM; + } - /* Set the payload type */ - codec_priv->pt = id->pt; + /* Set the payload type */ + codec_priv->pt = id->pt; #if !PLC_DISABLED - /* Create PLC, always with 10ms ptime */ - status = pjmedia_plc_create(g711_factory.pool, 8000, - SAMPLES_PER_FRAME, - 0, &codec_priv->plc); - if (status != PJ_SUCCESS) { - pj_mutex_unlock(g711_factory.mutex); - return status; - } + /* Create PLC, always with 10ms ptime */ + status = pjmedia_plc_create(g711_factory.pool, 8000, + SAMPLES_PER_FRAME, + 0, &codec_priv->plc); + if (status != PJ_SUCCESS) { + pj_mutex_unlock(g711_factory.mutex); + return status; + } #endif - /* Create VAD */ - status = pjmedia_silence_det_create(g711_factory.pool, - 8000, SAMPLES_PER_FRAME, - &codec_priv->vad); - if (status != PJ_SUCCESS) { - pj_mutex_unlock(g711_factory.mutex); - return status; - } - - codec->factory = factory; - codec->op = &g711_op; - codec->codec_data = codec_priv; + /* Create VAD */ + status = pjmedia_silence_det_create(g711_factory.pool, + 8000, SAMPLES_PER_FRAME, + &codec_priv->vad); + if (status != PJ_SUCCESS) { + pj_mutex_unlock(g711_factory.mutex); + return status; + } + + codec->factory = factory; + codec->op = &g711_op; + codec->codec_data = codec_priv; } else { - codec = g711_factory.codec_list.next; - pj_list_erase(codec); + codec = g711_factory.codec_list.next; + pj_list_erase(codec); } /* Zero the list, for error detection in g711_dealloc_codec */ @@ -370,7 +369,7 @@ static pj_status_t g711_alloc_codec( pjmedia_codec_factory *factory, } static pj_status_t g711_dealloc_codec(pjmedia_codec_factory *factory, - pjmedia_codec *codec ) + pjmedia_codec *codec ) { struct g711_private *priv = (struct g711_private*) codec->codec_data; int i = 0; @@ -380,7 +379,7 @@ static pj_status_t g711_dealloc_codec(pjmedia_codec_factory *factory, /* Check that this node has not been deallocated before */ pj_assert (codec->next==NULL && codec->prev==NULL); if (codec->next!=NULL || codec->prev!=NULL) { - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; } #if !PLC_DISABLED @@ -388,9 +387,9 @@ static pj_status_t g711_dealloc_codec(pjmedia_codec_factory *factory, * next time. */ for (i=0; i<2; ++i) { - pj_int16_t frame[SAMPLES_PER_FRAME]; - pjmedia_zero_samples(frame, PJ_ARRAY_SIZE(frame)); - pjmedia_plc_save(priv->plc, frame); + pj_int16_t frame[SAMPLES_PER_FRAME]; + pjmedia_zero_samples(frame, PJ_ARRAY_SIZE(frame)); + pjmedia_plc_save(priv->plc, frame); } #else PJ_UNUSED_ARG(i); @@ -419,7 +418,7 @@ static pj_status_t g711_init( pjmedia_codec *codec, pj_pool_t *pool ) } static pj_status_t g711_open(pjmedia_codec *codec, - pjmedia_codec_param *attr ) + pjmedia_codec_param *attr ) { struct g711_private *priv = (struct g711_private*) codec->codec_data; priv->pt = attr->info.pt; @@ -438,12 +437,12 @@ static pj_status_t g711_close( pjmedia_codec *codec ) } static pj_status_t g711_modify(pjmedia_codec *codec, - const pjmedia_codec_param *attr ) + const pjmedia_codec_param *attr ) { struct g711_private *priv = (struct g711_private*) codec->codec_data; if (attr->info.pt != priv->pt) - return PJMEDIA_EINVALIDPT; + return PJMEDIA_EINVALIDPT; #if !PLC_DISABLED priv->plc_enabled = (attr->setting.plc != 0); @@ -454,11 +453,11 @@ static pj_status_t g711_modify(pjmedia_codec *codec, } static pj_status_t g711_parse( pjmedia_codec *codec, - void *pkt, - pj_size_t pkt_size, - const pj_timestamp *ts, - unsigned *frame_cnt, - pjmedia_frame frames[]) + void *pkt, + pj_size_t pkt_size, + const pj_timestamp *ts, + unsigned *frame_cnt, + pjmedia_frame frames[]) { unsigned count = 0; @@ -467,15 +466,15 @@ static pj_status_t g711_parse( pjmedia_codec *codec, PJ_ASSERT_RETURN(ts && frame_cnt && frames, PJ_EINVAL); while (pkt_size >= FRAME_SIZE && count < *frame_cnt) { - frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; - frames[count].buf = pkt; - frames[count].size = FRAME_SIZE; - frames[count].timestamp.u64 = ts->u64 + SAMPLES_PER_FRAME * count; + frames[count].type = PJMEDIA_FRAME_TYPE_AUDIO; + frames[count].buf = pkt; + frames[count].size = FRAME_SIZE; + frames[count].timestamp.u64 = ts->u64 + SAMPLES_PER_FRAME * count; - pkt = ((char*)pkt) + FRAME_SIZE; - pkt_size -= FRAME_SIZE; + pkt = ((char*)pkt) + FRAME_SIZE; + pkt_size -= FRAME_SIZE; - ++count; + ++count; } *frame_cnt = count; @@ -483,62 +482,62 @@ static pj_status_t g711_parse( pjmedia_codec *codec, } static pj_status_t g711_encode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { pj_int16_t *samples = (pj_int16_t*) input->buf; struct g711_private *priv = (struct g711_private*) codec->codec_data; /* Check output buffer length */ if (output_buf_len < (input->size >> 1)) - return PJMEDIA_CODEC_EFRMTOOSHORT; + return PJMEDIA_CODEC_EFRMTOOSHORT; /* Detect silence if VAD is enabled */ if (priv->vad_enabled) { - pj_bool_t is_silence; - pj_int32_t silence_period; - - silence_period = pj_timestamp_diff32(&priv->last_tx, - &input->timestamp); - - is_silence = pjmedia_silence_det_detect(priv->vad, - (const pj_int16_t*) input->buf, - (input->size >> 1), NULL); - if (is_silence && - (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || - silence_period < PJMEDIA_CODEC_MAX_SILENCE_PERIOD*8000/1000)) - { - output->type = PJMEDIA_FRAME_TYPE_NONE; - output->buf = NULL; - output->size = 0; - output->timestamp = input->timestamp; - return PJ_SUCCESS; - } else { - priv->last_tx = input->timestamp; - } + pj_bool_t is_silence; + pj_int32_t silence_period; + + silence_period = pj_timestamp_diff32(&priv->last_tx, + &input->timestamp); + + is_silence = pjmedia_silence_det_detect(priv->vad, + (const pj_int16_t*) input->buf, + (input->size >> 1), NULL); + if (is_silence && + (PJMEDIA_CODEC_MAX_SILENCE_PERIOD == -1 || + silence_period < PJMEDIA_CODEC_MAX_SILENCE_PERIOD*8000/1000)) + { + output->type = PJMEDIA_FRAME_TYPE_NONE; + output->buf = NULL; + output->size = 0; + output->timestamp = input->timestamp; + return PJ_SUCCESS; + } else { + priv->last_tx = input->timestamp; + } } /* Encode */ if (priv->pt == PJMEDIA_RTP_PT_PCMA) { - unsigned i, n; - pj_uint8_t *dst = (pj_uint8_t*) output->buf; + unsigned i, n; + pj_uint8_t *dst = (pj_uint8_t*) output->buf; - n = ((unsigned)input->size >> 1); - for (i=0; i!=n; ++i, ++dst) { - *dst = pjmedia_linear2alaw(samples[i]); - } + n = ((unsigned)input->size >> 1); + for (i=0; i!=n; ++i, ++dst) { + *dst = pjmedia_linear2alaw(samples[i]); + } } else if (priv->pt == PJMEDIA_RTP_PT_PCMU) { - unsigned i, n; - pj_uint8_t *dst = (pj_uint8_t*) output->buf; + unsigned i, n; + pj_uint8_t *dst = (pj_uint8_t*) output->buf; - n = ((unsigned)input->size >> 1); - for (i=0; i!=n; ++i, ++dst) { - *dst = pjmedia_linear2ulaw(samples[i]); - } + n = ((unsigned)input->size >> 1); + for (i=0; i!=n; ++i, ++dst) { + *dst = pjmedia_linear2ulaw(samples[i]); + } } else { - return PJMEDIA_EINVALIDPT; + return PJMEDIA_EINVALIDPT; } output->type = PJMEDIA_FRAME_TYPE_AUDIO; @@ -549,40 +548,40 @@ static pj_status_t g711_encode(pjmedia_codec *codec, } static pj_status_t g711_decode(pjmedia_codec *codec, - const struct pjmedia_frame *input, - unsigned output_buf_len, - struct pjmedia_frame *output) + const struct pjmedia_frame *input, + unsigned output_buf_len, + struct pjmedia_frame *output) { struct g711_private *priv = (struct g711_private*) codec->codec_data; /* Check output buffer length */ PJ_ASSERT_RETURN(output_buf_len >= (input->size << 1), - PJMEDIA_CODEC_EPCMTOOSHORT); + PJMEDIA_CODEC_EPCMTOOSHORT); /* Input buffer MUST have exactly 80 bytes long */ PJ_ASSERT_RETURN(input->size == FRAME_SIZE, - PJMEDIA_CODEC_EFRMINLEN); + PJMEDIA_CODEC_EFRMINLEN); /* Decode */ if (priv->pt == PJMEDIA_RTP_PT_PCMA) { - unsigned i; - pj_uint8_t *src = (pj_uint8_t*) input->buf; - pj_uint16_t *dst = (pj_uint16_t*) output->buf; + unsigned i; + pj_uint8_t *src = (pj_uint8_t*) input->buf; + pj_uint16_t *dst = (pj_uint16_t*) output->buf; - for (i=0; i!=input->size; ++i) { - *dst++ = (pj_uint16_t) pjmedia_alaw2linear(*src++); - } + for (i=0; i!=input->size; ++i) { + *dst++ = (pj_uint16_t) pjmedia_alaw2linear(*src++); + } } else if (priv->pt == PJMEDIA_RTP_PT_PCMU) { - unsigned i; - pj_uint8_t *src = (pj_uint8_t*) input->buf; - pj_uint16_t *dst = (pj_uint16_t*) output->buf; + unsigned i; + pj_uint8_t *src = (pj_uint8_t*) input->buf; + pj_uint16_t *dst = (pj_uint16_t*) output->buf; - for (i=0; i!=input->size; ++i) { - *dst++ = (pj_uint16_t) pjmedia_ulaw2linear(*src++); - } + for (i=0; i!=input->size; ++i) { + *dst++ = (pj_uint16_t) pjmedia_ulaw2linear(*src++); + } } else { - return PJMEDIA_EINVALIDPT; + return PJMEDIA_EINVALIDPT; } output->type = PJMEDIA_FRAME_TYPE_AUDIO; @@ -591,7 +590,7 @@ static pj_status_t g711_decode(pjmedia_codec *codec, #if !PLC_DISABLED if (priv->plc_enabled) - pjmedia_plc_save( priv->plc, (pj_int16_t*)output->buf); + pjmedia_plc_save( priv->plc, (pj_int16_t*)output->buf); #endif return PJ_SUCCESS; @@ -599,16 +598,16 @@ static pj_status_t g711_decode(pjmedia_codec *codec, #if !PLC_DISABLED static pj_status_t g711_recover( pjmedia_codec *codec, - unsigned output_buf_len, - struct pjmedia_frame *output) + unsigned output_buf_len, + struct pjmedia_frame *output) { struct g711_private *priv = (struct g711_private*) codec->codec_data; if (!priv->plc_enabled) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; PJ_ASSERT_RETURN(output_buf_len >= SAMPLES_PER_FRAME * 2, - PJMEDIA_CODEC_EPCMTOOSHORT); + PJMEDIA_CODEC_EPCMTOOSHORT); pjmedia_plc_generate(priv->plc, (pj_int16_t*)output->buf); output->size = SAMPLES_PER_FRAME * 2; @@ -617,7 +616,7 @@ static pj_status_t g711_recover( pjmedia_codec *codec, } #endif -#endif /* PJMEDIA_HAS_G711_CODEC */ +#endif /* PJMEDIA_HAS_G711_CODEC */ diff --git a/pjmedia/src/pjmedia/jbuf.c b/pjmedia/src/pjmedia/jbuf.c index 42e7160432..ed718b841a 100644 --- a/pjmedia/src/pjmedia/jbuf.c +++ b/pjmedia/src/pjmedia/jbuf.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -33,17 +32,17 @@ /* Invalid sequence number, used as the initial value. */ -#define INVALID_OFFSET -9999 +#define INVALID_OFFSET -9999 /* Maximum burst length, whenever an operation is bursting longer than * this value, JB will assume that the opposite operation was idle. */ -#define MAX_BURST_MSEC 1000 +#define MAX_BURST_MSEC 1000 /* Number of OP switches to be performed in JB_STATUS_INITIALIZING, before * JB can switch its states to JB_STATUS_PROCESSING. */ -#define INIT_CYCLE 10 +#define INIT_CYCLE 10 /* Maximum frame index in JB framelist (estimated). @@ -51,13 +50,13 @@ * usually ranging from MAXUINT32/9000 (10 fps video at 90kHz) to MAXUINT32/80 * (10 ms audio at 8000Hz), lets take the 'lowest'. */ -#define MAX_FRAME_INDEX (0xFFFFFFFF/9000) +#define MAX_FRAME_INDEX (0xFFFFFFFF/9000) /* Minimal difference between JB size and 2*burst-level to perform * JB shrinking in static discard algorithm. */ -#define STA_DISC_SAFE_SHRINKING_DIFF 1 +#define STA_DISC_SAFE_SHRINKING_DIFF 1 /* Struct of JB internal buffer, represented in a circular buffer containing @@ -66,24 +65,24 @@ typedef struct jb_framelist_t { /* Settings */ - unsigned frame_size; /**< maximum size of frame */ - unsigned max_count; /**< maximum number of frames */ + unsigned frame_size; /**< maximum size of frame */ + unsigned max_count; /**< maximum number of frames */ /* Buffers */ - char *content; /**< frame content array */ - int *frame_type; /**< frame type array */ - pj_size_t *content_len; /**< frame length array */ - pj_uint32_t *bit_info; /**< frame bit info array */ - pj_uint32_t *ts; /**< timestamp array */ + char *content; /**< frame content array */ + int *frame_type; /**< frame type array */ + pj_size_t *content_len; /**< frame length array */ + pj_uint32_t *bit_info; /**< frame bit info array */ + pj_uint32_t *ts; /**< timestamp array */ /* States */ - unsigned head; /**< index of head, pointed frame - will be returned by next GET */ - unsigned size; /**< current size of framelist, - including discarded frames. */ - unsigned discarded_num; /**< current number of discarded - frames. */ - int origin; /**< original index of flist_head */ + unsigned head; /**< index of head, pointed frame + will be returned by next GET */ + unsigned size; /**< current size of framelist, + including discarded frames. */ + unsigned discarded_num; /**< current number of discarded + frames. */ + int origin; /**< original index of flist_head */ } jb_framelist_t; @@ -96,66 +95,66 @@ static void jbuf_discard_progressive(pjmedia_jbuf *jb); struct pjmedia_jbuf { /* Settings (consts) */ - pj_str_t jb_name; /**< jitter buffer name */ - pj_size_t jb_frame_size; /**< frame size */ - unsigned jb_frame_ptime; /**< frame duration. */ - pj_size_t jb_max_count; /**< capacity of jitter buffer, - in frames */ - int jb_init_prefetch; /**< Initial prefetch */ - int jb_min_prefetch; /**< Minimum allowable prefetch */ - int jb_max_prefetch; /**< Maximum allowable prefetch */ - int jb_max_burst; /**< maximum possible burst, whenever - burst exceeds this value, it - won't be included in level - calculation */ - int jb_min_shrink_gap; /**< How often can we shrink */ - discard_algo jb_discard_algo; /**< Discard algorithm */ + pj_str_t jb_name; /**< jitter buffer name */ + pj_size_t jb_frame_size; /**< frame size */ + unsigned jb_frame_ptime; /**< frame duration. */ + pj_size_t jb_max_count; /**< capacity of jitter buffer, + in frames */ + int jb_init_prefetch; /**< Initial prefetch */ + int jb_min_prefetch; /**< Minimum allowable prefetch */ + int jb_max_prefetch; /**< Maximum allowable prefetch */ + int jb_max_burst; /**< maximum possible burst, whenever + burst exceeds this value, it + won't be included in level + calculation */ + int jb_min_shrink_gap; /**< How often can we shrink */ + discard_algo jb_discard_algo; /**< Discard algorithm */ /* Buffer */ - jb_framelist_t jb_framelist; /**< the buffer */ + jb_framelist_t jb_framelist; /**< the buffer */ /* States */ - int jb_level; /**< delay between source & - destination (calculated according - of the number of burst get/put - operations) */ - int jb_max_hist_level; /**< max level during the last level - calculations */ - int jb_stable_hist; /**< num of times the delay has been - lower then the prefetch num */ - int jb_last_op; /**< last operation executed - (put/get) */ - int jb_eff_level; /**< effective burst level */ - int jb_prefetch; /**< no. of frame to insert before - removing some (at the beginning - of the framelist->content - operation), the value may be - continuously updated based on - current frame burst level. */ - pj_bool_t jb_prefetching; /**< flag if jbuf is prefetching. */ - int jb_status; /**< status is 'init' until the first - 'put' operation */ - int jb_init_cycle_cnt; /**< status is 'init' until the first - 'put' operation */ - - int jb_discard_ref; /**< Seq # of last frame deleted or - discarded */ - unsigned jb_discard_dist; /**< Distance from jb_discard_ref - to perform discard (in frm) */ + int jb_level; /**< delay between source & + destination (calculated according + of the number of burst get/put + operations) */ + int jb_max_hist_level; /**< max level during the last level + calculations */ + int jb_stable_hist; /**< num of times the delay has been + lower then the prefetch num */ + int jb_last_op; /**< last operation executed + (put/get) */ + int jb_eff_level; /**< effective burst level */ + int jb_prefetch; /**< no. of frame to insert before + removing some (at the beginning + of the framelist->content + operation), the value may be + continuously updated based on + current frame burst level. */ + pj_bool_t jb_prefetching; /**< flag if jbuf is prefetching. */ + int jb_status; /**< status is 'init' until the first + 'put' operation */ + int jb_init_cycle_cnt; /**< status is 'init' until the first + 'put' operation */ + + int jb_discard_ref; /**< Seq # of last frame deleted or + discarded */ + unsigned jb_discard_dist; /**< Distance from jb_discard_ref + to perform discard (in frm) */ /* Statistics */ - pj_math_stat jb_delay; /**< Delay statistics of jitter buffer - (in ms) */ - pj_math_stat jb_burst; /**< Burst statistics (in frames) */ - unsigned jb_lost; /**< Number of lost frames. */ - unsigned jb_discard; /**< Number of discarded frames. */ - unsigned jb_empty; /**< Number of empty/prefetching frame - returned by GET. */ + pj_math_stat jb_delay; /**< Delay statistics of jitter buffer + (in ms) */ + pj_math_stat jb_burst; /**< Burst statistics (in frames) */ + unsigned jb_lost; /**< Number of lost frames. */ + unsigned jb_discard; /**< Number of discarded frames. */ + unsigned jb_empty; /**< Number of empty/prefetching frame + returned by GET. */ }; -#define JB_STATUS_INITIALIZING 0 -#define JB_STATUS_PROCESSING 1 +#define JB_STATUS_INITIALIZING 0 +#define JB_STATUS_PROCESSING 1 @@ -176,19 +175,19 @@ struct pjmedia_jbuf * second. */ #if 0 -# define TRACE__(args) PJ_LOG(5,args) +# define TRACE__(args) PJ_LOG(5,args) #else # define TRACE__(args) #endif static pj_status_t jb_framelist_reset(jb_framelist_t *framelist); static unsigned jb_framelist_remove_head(jb_framelist_t *framelist, - unsigned count); + unsigned count); static pj_status_t jb_framelist_init( pj_pool_t *pool, - jb_framelist_t *framelist, - unsigned frame_size, - unsigned max_count) + jb_framelist_t *framelist, + unsigned frame_size, + unsigned max_count) { PJ_ASSERT_RETURN(pool && framelist, PJ_EINVAL); @@ -196,26 +195,26 @@ static pj_status_t jb_framelist_init( pj_pool_t *pool, framelist->frame_size = frame_size; framelist->max_count = max_count; - framelist->content = (char*) - pj_pool_alloc(pool, - (pj_size_t)framelist->frame_size* - framelist->max_count); + framelist->content = (char*) + pj_pool_alloc(pool, + (pj_size_t)framelist->frame_size* + framelist->max_count); framelist->frame_type = (int*) - pj_pool_alloc(pool, - sizeof(framelist->frame_type[0])* - framelist->max_count); + pj_pool_alloc(pool, + sizeof(framelist->frame_type[0])* + framelist->max_count); framelist->content_len = (pj_size_t*) - pj_pool_alloc(pool, - sizeof(framelist->content_len[0])* - framelist->max_count); - framelist->bit_info = (pj_uint32_t*) - pj_pool_alloc(pool, - sizeof(framelist->bit_info[0])* - framelist->max_count); - framelist->ts = (pj_uint32_t*) - pj_pool_alloc(pool, - sizeof(framelist->ts[0])* - framelist->max_count); + pj_pool_alloc(pool, + sizeof(framelist->content_len[0])* + framelist->max_count); + framelist->bit_info = (pj_uint32_t*) + pj_pool_alloc(pool, + sizeof(framelist->bit_info[0])* + framelist->max_count); + framelist->ts = (pj_uint32_t*) + pj_pool_alloc(pool, + sizeof(framelist->ts[0])* + framelist->max_count); return jb_framelist_reset(framelist); @@ -236,21 +235,21 @@ static pj_status_t jb_framelist_reset(jb_framelist_t *framelist) //pj_bzero(framelist->content, - // framelist->frame_size * - // framelist->max_count); + // framelist->frame_size * + // framelist->max_count); pj_memset(framelist->frame_type, - PJMEDIA_JB_MISSING_FRAME, - sizeof(framelist->frame_type[0]) * - framelist->max_count); + PJMEDIA_JB_MISSING_FRAME, + sizeof(framelist->frame_type[0]) * + framelist->max_count); pj_bzero(framelist->content_len, - sizeof(framelist->content_len[0]) * - framelist->max_count); + sizeof(framelist->content_len[0]) * + framelist->max_count); //pj_bzero(framelist->bit_info, - // sizeof(framelist->bit_info[0]) * - // framelist->max_count); + // sizeof(framelist->bit_info[0]) * + // framelist->max_count); return PJ_SUCCESS; } @@ -274,76 +273,76 @@ static int jb_framelist_origin(const jb_framelist_t *framelist) static pj_bool_t jb_framelist_get(jb_framelist_t *framelist, - void *frame, pj_size_t *size, - pjmedia_jb_frame_type *p_type, - pj_uint32_t *bit_info, - pj_uint32_t *ts, - int *seq) + void *frame, pj_size_t *size, + pjmedia_jb_frame_type *p_type, + pj_uint32_t *bit_info, + pj_uint32_t *ts, + int *seq) { if (framelist->size) { - pj_bool_t prev_discarded = PJ_FALSE; - - /* Skip discarded frames */ - while (framelist->frame_type[framelist->head] == - PJMEDIA_JB_DISCARDED_FRAME) - { - jb_framelist_remove_head(framelist, 1); - prev_discarded = PJ_TRUE; - } - - /* Return the head frame if any */ - if (framelist->size) { - if (prev_discarded) { - /* Ticket #1188: when previous frame(s) was discarded, return - * 'missing' frame to trigger PLC to get smoother signal. - */ - *p_type = PJMEDIA_JB_MISSING_FRAME; - if (size) - *size = 0; - if (bit_info) - *bit_info = 0; - } else { - pj_size_t frm_size = framelist->content_len[framelist->head]; - pj_size_t max_size = size? *size : frm_size; - pj_size_t copy_size = PJ_MIN(max_size, frm_size); - - /* Buffer size should not be smaller than frame size. */ - if (max_size < frm_size) { - pj_assert(!"Buffer too small"); - PJ_LOG(4, (THIS_FILE, "Warning: buffer too small for the " - "retrieved frame!")); - } - - pj_memcpy(frame, - framelist->content + - framelist->head * framelist->frame_size, - copy_size); - *p_type = (pjmedia_jb_frame_type) - framelist->frame_type[framelist->head]; - if (size) - *size = copy_size; - if (bit_info) - *bit_info = framelist->bit_info[framelist->head]; - } - if (ts) - *ts = framelist->ts[framelist->head]; - if (seq) - *seq = framelist->origin; - - //pj_bzero(framelist->content + - // framelist->head * framelist->frame_size, - // framelist->frame_size); - framelist->frame_type[framelist->head] = PJMEDIA_JB_MISSING_FRAME; - framelist->content_len[framelist->head] = 0; - framelist->bit_info[framelist->head] = 0; - framelist->ts[framelist->head] = 0; - - framelist->origin++; - framelist->head = (framelist->head + 1) % framelist->max_count; - framelist->size--; - - return PJ_TRUE; - } + pj_bool_t prev_discarded = PJ_FALSE; + + /* Skip discarded frames */ + while (framelist->frame_type[framelist->head] == + PJMEDIA_JB_DISCARDED_FRAME) + { + jb_framelist_remove_head(framelist, 1); + prev_discarded = PJ_TRUE; + } + + /* Return the head frame if any */ + if (framelist->size) { + if (prev_discarded) { + /* Ticket #1188: when previous frame(s) was discarded, return + * 'missing' frame to trigger PLC to get smoother signal. + */ + *p_type = PJMEDIA_JB_MISSING_FRAME; + if (size) + *size = 0; + if (bit_info) + *bit_info = 0; + } else { + pj_size_t frm_size = framelist->content_len[framelist->head]; + pj_size_t max_size = size? *size : frm_size; + pj_size_t copy_size = PJ_MIN(max_size, frm_size); + + /* Buffer size should not be smaller than frame size. */ + if (max_size < frm_size) { + pj_assert(!"Buffer too small"); + PJ_LOG(4, (THIS_FILE, "Warning: buffer too small for the " + "retrieved frame!")); + } + + pj_memcpy(frame, + framelist->content + + framelist->head * framelist->frame_size, + copy_size); + *p_type = (pjmedia_jb_frame_type) + framelist->frame_type[framelist->head]; + if (size) + *size = copy_size; + if (bit_info) + *bit_info = framelist->bit_info[framelist->head]; + } + if (ts) + *ts = framelist->ts[framelist->head]; + if (seq) + *seq = framelist->origin; + + //pj_bzero(framelist->content + + // framelist->head * framelist->frame_size, + // framelist->frame_size); + framelist->frame_type[framelist->head] = PJMEDIA_JB_MISSING_FRAME; + framelist->content_len[framelist->head] = 0; + framelist->bit_info[framelist->head] = 0; + framelist->ts[framelist->head] = 0; + + framelist->origin++; + framelist->head = (framelist->head + 1) % framelist->max_count; + framelist->size--; + + return PJ_TRUE; + } } /* No frame available */ @@ -354,47 +353,47 @@ static pj_bool_t jb_framelist_get(jb_framelist_t *framelist, static pj_bool_t jb_framelist_peek(jb_framelist_t *framelist, - unsigned offset, - const void **frame, - pj_size_t *size, - pjmedia_jb_frame_type *type, - pj_uint32_t *bit_info, - pj_uint32_t *ts, - int *seq) + unsigned offset, + const void **frame, + pj_size_t *size, + pjmedia_jb_frame_type *type, + pj_uint32_t *bit_info, + pj_uint32_t *ts, + int *seq) { unsigned pos, idx; if (offset >= jb_framelist_eff_size(framelist)) - return PJ_FALSE; + return PJ_FALSE; pos = framelist->head; idx = offset; /* Find actual peek position, note there may be discarded frames */ while (1) { - if (framelist->frame_type[pos] != PJMEDIA_JB_DISCARDED_FRAME) { - if (idx == 0) - break; - else - --idx; - } - pos = (pos + 1) % framelist->max_count; + if (framelist->frame_type[pos] != PJMEDIA_JB_DISCARDED_FRAME) { + if (idx == 0) + break; + else + --idx; + } + pos = (pos + 1) % framelist->max_count; } /* Return the frame pointer */ if (frame) - *frame = framelist->content + pos*framelist->frame_size; + *frame = framelist->content + pos*framelist->frame_size; if (type) - *type = (pjmedia_jb_frame_type) - framelist->frame_type[pos]; + *type = (pjmedia_jb_frame_type) + framelist->frame_type[pos]; if (size) - *size = framelist->content_len[pos]; + *size = framelist->content_len[pos]; if (bit_info) - *bit_info = framelist->bit_info[pos]; + *bit_info = framelist->bit_info[pos]; if (ts) - *ts = framelist->ts[pos]; + *ts = framelist->ts[pos]; if (seq) - *seq = framelist->origin + offset; + *seq = framelist->origin + offset; return PJ_TRUE; } @@ -402,61 +401,61 @@ static pj_bool_t jb_framelist_peek(jb_framelist_t *framelist, /* Remove oldest frames as many as param 'count' */ static unsigned jb_framelist_remove_head(jb_framelist_t *framelist, - unsigned count) + unsigned count) { if (count > framelist->size) - count = framelist->size; + count = framelist->size; if (count) { - /* may be done in two steps if overlapping */ - unsigned step1,step2; - unsigned tmp = framelist->head+count; - unsigned i; - - if (tmp > framelist->max_count) { - step1 = framelist->max_count - framelist->head; - step2 = count-step1; - } else { - step1 = count; - step2 = 0; - } - - for (i = framelist->head; i < (framelist->head + step1); ++i) { - if (framelist->frame_type[i] == PJMEDIA_JB_DISCARDED_FRAME) { - pj_assert(framelist->discarded_num > 0); - framelist->discarded_num--; - } - } - - //pj_bzero(framelist->content + - // framelist->head * framelist->frame_size, - // step1*framelist->frame_size); - pj_memset(framelist->frame_type+framelist->head, - PJMEDIA_JB_MISSING_FRAME, - step1*sizeof(framelist->frame_type[0])); - pj_bzero(framelist->content_len+framelist->head, - step1*sizeof(framelist->content_len[0])); - - if (step2) { - for (i = 0; i < step2; ++i) { - if (framelist->frame_type[i] == PJMEDIA_JB_DISCARDED_FRAME) { - pj_assert(framelist->discarded_num > 0); - framelist->discarded_num--; - } - } - //pj_bzero( framelist->content, - // step2*framelist->frame_size); - pj_memset(framelist->frame_type, - PJMEDIA_JB_MISSING_FRAME, - step2*sizeof(framelist->frame_type[0])); - pj_bzero (framelist->content_len, - step2*sizeof(framelist->content_len[0])); - } - - /* update states */ - framelist->origin += count; - framelist->head = (framelist->head + count) % framelist->max_count; - framelist->size -= count; + /* may be done in two steps if overlapping */ + unsigned step1,step2; + unsigned tmp = framelist->head+count; + unsigned i; + + if (tmp > framelist->max_count) { + step1 = framelist->max_count - framelist->head; + step2 = count-step1; + } else { + step1 = count; + step2 = 0; + } + + for (i = framelist->head; i < (framelist->head + step1); ++i) { + if (framelist->frame_type[i] == PJMEDIA_JB_DISCARDED_FRAME) { + pj_assert(framelist->discarded_num > 0); + framelist->discarded_num--; + } + } + + //pj_bzero(framelist->content + + // framelist->head * framelist->frame_size, + // step1*framelist->frame_size); + pj_memset(framelist->frame_type+framelist->head, + PJMEDIA_JB_MISSING_FRAME, + step1*sizeof(framelist->frame_type[0])); + pj_bzero(framelist->content_len+framelist->head, + step1*sizeof(framelist->content_len[0])); + + if (step2) { + for (i = 0; i < step2; ++i) { + if (framelist->frame_type[i] == PJMEDIA_JB_DISCARDED_FRAME) { + pj_assert(framelist->discarded_num > 0); + framelist->discarded_num--; + } + } + //pj_bzero( framelist->content, + // step2*framelist->frame_size); + pj_memset(framelist->frame_type, + PJMEDIA_JB_MISSING_FRAME, + step2*sizeof(framelist->frame_type[0])); + pj_bzero (framelist->content_len, + step2*sizeof(framelist->content_len[0])); + } + + /* update states */ + framelist->origin += count; + framelist->head = (framelist->head + count) % framelist->max_count; + framelist->size -= count; } return count; @@ -464,12 +463,12 @@ static unsigned jb_framelist_remove_head(jb_framelist_t *framelist, static pj_status_t jb_framelist_put_at(jb_framelist_t *framelist, - int index, - const void *frame, - unsigned frame_size, - pj_uint32_t bit_info, - pj_uint32_t ts, - unsigned frame_type) + int index, + const void *frame, + unsigned frame_size, + pj_uint32_t bit_info, + pj_uint32_t ts, + unsigned frame_type) { int distance; unsigned pos; @@ -483,53 +482,53 @@ static pj_status_t jb_framelist_put_at(jb_framelist_t *framelist, /* too late or sequence restart or far jump */ if (distance < 0) { - if (framelist->origin - index < MAX_MISORDER) { - /* too late */ - TRACE__((THIS_FILE,"Put frame #%d: too late (distance=%d)", - index, distance)); - return PJ_ETOOSMALL; - } else if (framelist->origin + framelist->size >= MAX_FRAME_INDEX) { - /* sequence restart */ - TRACE__((THIS_FILE,"Put frame #%d: sequence restart (distance=%d, " - "orig=%d, size=%d)", - index, distance, framelist->origin, - framelist->size)); - framelist->origin = index - framelist->size; - distance = framelist->size; - } else { - /* jump too far, reset the buffer */ - TRACE__((THIS_FILE,"Put frame #%d: far jump (distance=%d)", - index, distance)); - jb_framelist_reset(framelist); - framelist->origin = index; - distance = 0; - } + if (framelist->origin - index < MAX_MISORDER) { + /* too late */ + TRACE__((THIS_FILE,"Put frame #%d: too late (distance=%d)", + index, distance)); + return PJ_ETOOSMALL; + } else if (framelist->origin + framelist->size >= MAX_FRAME_INDEX) { + /* sequence restart */ + TRACE__((THIS_FILE,"Put frame #%d: sequence restart (distance=%d, " + "orig=%d, size=%d)", + index, distance, framelist->origin, + framelist->size)); + framelist->origin = index - framelist->size; + distance = framelist->size; + } else { + /* jump too far, reset the buffer */ + TRACE__((THIS_FILE,"Put frame #%d: far jump (distance=%d)", + index, distance)); + jb_framelist_reset(framelist); + framelist->origin = index; + distance = 0; + } } /* if jbuf is empty, just reset the origin */ if (framelist->size == 0) { - pj_assert(framelist->discarded_num == 0); - TRACE__((THIS_FILE,"Put frame #%d: origin reset (from %d) as JB empty", - index, framelist->origin)); - framelist->origin = index; - distance = 0; + pj_assert(framelist->discarded_num == 0); + TRACE__((THIS_FILE,"Put frame #%d: origin reset (from %d) as JB empty", + index, framelist->origin)); + framelist->origin = index; + distance = 0; } /* far jump, the distance is greater than buffer capacity */ if (distance >= (int)framelist->max_count) { - if (distance > MAX_DROPOUT) { - /* jump too far, reset the buffer */ - TRACE__((THIS_FILE,"Put frame #%d: far jump (distance=%d)", - index, distance)); - jb_framelist_reset(framelist); - framelist->origin = index; - distance = 0; - } else { - /* otherwise, reject the frame */ - TRACE__((THIS_FILE,"Put frame #%d: rejected due to JB full", - index)); - return PJ_ETOOMANY; - } + if (distance > MAX_DROPOUT) { + /* jump too far, reset the buffer */ + TRACE__((THIS_FILE,"Put frame #%d: far jump (distance=%d)", + index, distance)); + jb_framelist_reset(framelist); + framelist->origin = index; + distance = 0; + } else { + /* otherwise, reject the frame */ + TRACE__((THIS_FILE,"Put frame #%d: rejected due to JB full", + index)); + return PJ_ETOOMANY; + } } /* get the slot position */ @@ -537,8 +536,8 @@ static pj_status_t jb_framelist_put_at(jb_framelist_t *framelist, /* if the slot is occupied, it must be duplicated frame, ignore it. */ if (framelist->frame_type[pos] != PJMEDIA_JB_MISSING_FRAME) { - TRACE__((THIS_FILE,"Put frame #%d maybe a duplicate, ignored", index)); - return PJ_EEXISTS; + TRACE__((THIS_FILE,"Put frame #%d maybe a duplicate, ignored", index)); + return PJ_EEXISTS; } /* put the frame into the slot */ @@ -549,12 +548,12 @@ static pj_status_t jb_framelist_put_at(jb_framelist_t *framelist, /* update framelist size */ if (framelist->origin + (int)framelist->size <= index) - framelist->size = distance + 1; + framelist->size = distance + 1; if(PJMEDIA_JB_NORMAL_FRAME == frame_type) { - /* copy frame content */ - pj_memcpy(framelist->content + pos * framelist->frame_size, - frame, frame_size); + /* copy frame content */ + pj_memcpy(framelist->content + pos * framelist->frame_size, + frame, frame_size); } return PJ_SUCCESS; @@ -562,17 +561,17 @@ static pj_status_t jb_framelist_put_at(jb_framelist_t *framelist, static pj_status_t jb_framelist_discard(jb_framelist_t *framelist, - int index) + int index) { unsigned pos; PJ_ASSERT_RETURN(index >= framelist->origin && - index < framelist->origin + (int)framelist->size, - PJ_EINVAL); + index < framelist->origin + (int)framelist->size, + PJ_EINVAL); /* Get the slot position */ pos = (framelist->head + (index - framelist->origin)) % - framelist->max_count; + framelist->max_count; /* Discard the frame */ framelist->frame_type[pos] = PJMEDIA_JB_DISCARDED_FRAME; @@ -591,11 +590,11 @@ enum pjmedia_jb_op PJ_DEF(pj_status_t) pjmedia_jbuf_create(pj_pool_t *pool, - const pj_str_t *name, - unsigned frame_size, - unsigned ptime, - unsigned max_count, - pjmedia_jbuf **p_jb) + const pj_str_t *name, + unsigned frame_size, + unsigned ptime, + unsigned max_count, + pjmedia_jbuf **p_jb) { pjmedia_jbuf *jb; pj_status_t status; @@ -604,17 +603,17 @@ PJ_DEF(pj_status_t) pjmedia_jbuf_create(pj_pool_t *pool, status = jb_framelist_init(pool, &jb->jb_framelist, frame_size, max_count); if (status != PJ_SUCCESS) - return status; + return status; pj_strdup_with_null(pool, &jb->jb_name, name); - jb->jb_frame_size = frame_size; + jb->jb_frame_size = frame_size; jb->jb_frame_ptime = ptime; - jb->jb_prefetch = PJ_MIN(PJMEDIA_JB_DEFAULT_INIT_DELAY,max_count*4/5); + jb->jb_prefetch = PJ_MIN(PJMEDIA_JB_DEFAULT_INIT_DELAY,max_count*4/5); jb->jb_min_prefetch = 0; jb->jb_max_prefetch = max_count*4/5; - jb->jb_max_count = max_count; + jb->jb_max_count = max_count; jb->jb_min_shrink_gap= PJMEDIA_JBUF_DISC_MIN_GAP / ptime; - jb->jb_max_burst = PJ_MAX(MAX_BURST_MSEC / ptime, max_count*3/4); + jb->jb_max_burst = PJ_MAX(MAX_BURST_MSEC / ptime, max_count*3/4); pj_math_stat_init(&jb->jb_delay); pj_math_stat_init(&jb->jb_burst); @@ -628,14 +627,14 @@ PJ_DEF(pj_status_t) pjmedia_jbuf_create(pj_pool_t *pool, PJ_DEF(pj_status_t) pjmedia_jbuf_set_ptime( pjmedia_jbuf *jb, - unsigned ptime) + unsigned ptime) { PJ_ASSERT_RETURN(jb, PJ_EINVAL); jb->jb_frame_ptime = ptime; jb->jb_min_shrink_gap = PJMEDIA_JBUF_DISC_MIN_GAP / ptime; - jb->jb_max_burst = (int)PJ_MAX(MAX_BURST_MSEC / ptime, - jb->jb_max_count*3/4); + jb->jb_max_burst = (int)PJ_MAX(MAX_BURST_MSEC / ptime, + jb->jb_max_count*3/4); return PJ_SUCCESS; } @@ -647,13 +646,13 @@ PJ_DEF(pj_status_t) pjmedia_jbuf_set_ptime( pjmedia_jbuf *jb, * */ PJ_DEF(pj_status_t) pjmedia_jbuf_set_fixed( pjmedia_jbuf *jb, - unsigned prefetch) + unsigned prefetch) { PJ_ASSERT_RETURN(jb, PJ_EINVAL); PJ_ASSERT_RETURN(prefetch <= jb->jb_max_count, PJ_EINVAL); jb->jb_min_prefetch = jb->jb_max_prefetch = - jb->jb_prefetch = jb->jb_init_prefetch = prefetch; + jb->jb_prefetch = jb->jb_init_prefetch = prefetch; pjmedia_jbuf_set_discard(jb, PJMEDIA_JB_DISCARD_NONE); return PJ_SUCCESS; @@ -664,15 +663,15 @@ PJ_DEF(pj_status_t) pjmedia_jbuf_set_fixed( pjmedia_jbuf *jb, * Set the jitter buffer to adaptive mode. */ PJ_DEF(pj_status_t) pjmedia_jbuf_set_adaptive( pjmedia_jbuf *jb, - unsigned prefetch, - unsigned min_prefetch, - unsigned max_prefetch) + unsigned prefetch, + unsigned min_prefetch, + unsigned max_prefetch) { PJ_ASSERT_RETURN(jb, PJ_EINVAL); PJ_ASSERT_RETURN(min_prefetch <= max_prefetch && - prefetch <= max_prefetch && - max_prefetch <= jb->jb_max_count, - PJ_EINVAL); + prefetch <= max_prefetch && + max_prefetch <= jb->jb_max_count, + PJ_EINVAL); jb->jb_prefetch = jb->jb_init_prefetch = prefetch; jb->jb_min_prefetch = min_prefetch; @@ -683,23 +682,23 @@ PJ_DEF(pj_status_t) pjmedia_jbuf_set_adaptive( pjmedia_jbuf *jb, PJ_DEF(pj_status_t) pjmedia_jbuf_set_discard( pjmedia_jbuf *jb, - pjmedia_jb_discard_algo algo) + pjmedia_jb_discard_algo algo) { PJ_ASSERT_RETURN(jb, PJ_EINVAL); PJ_ASSERT_RETURN(algo >= PJMEDIA_JB_DISCARD_NONE && - algo <= PJMEDIA_JB_DISCARD_PROGRESSIVE, - PJ_EINVAL); + algo <= PJMEDIA_JB_DISCARD_PROGRESSIVE, + PJ_EINVAL); switch(algo) { case PJMEDIA_JB_DISCARD_PROGRESSIVE: - jb->jb_discard_algo = &jbuf_discard_progressive; - break; + jb->jb_discard_algo = &jbuf_discard_progressive; + break; case PJMEDIA_JB_DISCARD_STATIC: - jb->jb_discard_algo = &jbuf_discard_static; - break; + jb->jb_discard_algo = &jbuf_discard_static; + break; default: - jb->jb_discard_algo = NULL; - break; + jb->jb_discard_algo = NULL; + break; } return PJ_SUCCESS; @@ -708,10 +707,10 @@ PJ_DEF(pj_status_t) pjmedia_jbuf_set_discard( pjmedia_jbuf *jb, PJ_DEF(pj_status_t) pjmedia_jbuf_reset(pjmedia_jbuf *jb) { - jb->jb_level = 0; - jb->jb_last_op = JB_OP_INIT; - jb->jb_stable_hist = 0; - jb->jb_status = JB_STATUS_INITIALIZING; + jb->jb_level = 0; + jb->jb_last_op = JB_OP_INIT; + jb->jb_stable_hist = 0; + jb->jb_status = JB_STATUS_INITIALIZING; jb->jb_init_cycle_cnt= 0; jb->jb_max_hist_level= 0; jb->jb_prefetching = (jb->jb_prefetch != 0); @@ -728,19 +727,19 @@ PJ_DEF(pj_status_t) pjmedia_jbuf_reset(pjmedia_jbuf *jb) PJ_DEF(pj_status_t) pjmedia_jbuf_destroy(pjmedia_jbuf *jb) { PJ_LOG(5, (jb->jb_name.ptr, "" - "JB summary:\n" - " size=%d/eff=%d prefetch=%d level=%d\n" - " delay (min/max/avg/dev)=%d/%d/%d/%d ms\n" - " burst (min/max/avg/dev)=%d/%d/%d/%d frames\n" - " lost=%d discard=%d empty=%d", - jb_framelist_size(&jb->jb_framelist), - jb_framelist_eff_size(&jb->jb_framelist), - jb->jb_prefetch, jb->jb_eff_level, - jb->jb_delay.min, jb->jb_delay.max, jb->jb_delay.mean, - pj_math_stat_get_stddev(&jb->jb_delay), - jb->jb_burst.min, jb->jb_burst.max, jb->jb_burst.mean, - pj_math_stat_get_stddev(&jb->jb_burst), - jb->jb_lost, jb->jb_discard, jb->jb_empty)); + "JB summary:\n" + " size=%d/eff=%d prefetch=%d level=%d\n" + " delay (min/max/avg/dev)=%d/%d/%d/%d ms\n" + " burst (min/max/avg/dev)=%d/%d/%d/%d frames\n" + " lost=%d discard=%d empty=%d", + jb_framelist_size(&jb->jb_framelist), + jb_framelist_eff_size(&jb->jb_framelist), + jb->jb_prefetch, jb->jb_eff_level, + jb->jb_delay.min, jb->jb_delay.max, jb->jb_delay.mean, + pj_math_stat_get_stddev(&jb->jb_delay), + jb->jb_burst.min, jb->jb_burst.max, jb->jb_burst.mean, + pj_math_stat_get_stddev(&jb->jb_burst), + jb->jb_lost, jb->jb_discard, jb->jb_empty)); return jb_framelist_destroy(&jb->jb_framelist); } @@ -761,69 +760,69 @@ static void jbuf_calculate_jitter(pjmedia_jbuf *jb) /* Burst level is decreasing */ if (jb->jb_level < jb->jb_eff_level) { - enum { STABLE_HISTORY_LIMIT = 20 }; + enum { STABLE_HISTORY_LIMIT = 20 }; - jb->jb_stable_hist++; + jb->jb_stable_hist++; - /* Only update the effective level (and prefetch) if 'stable' - * condition is reached (not just short time impulse) - */ - if (jb->jb_stable_hist > STABLE_HISTORY_LIMIT) { + /* Only update the effective level (and prefetch) if 'stable' + * condition is reached (not just short time impulse) + */ + if (jb->jb_stable_hist > STABLE_HISTORY_LIMIT) { - diff = (jb->jb_eff_level - jb->jb_max_hist_level) / 3; + diff = (jb->jb_eff_level - jb->jb_max_hist_level) / 3; - if (diff < 1) - diff = 1; + if (diff < 1) + diff = 1; - /* Update effective burst level */ - jb->jb_eff_level -= diff; + /* Update effective burst level */ + jb->jb_eff_level -= diff; - /* Update prefetch based on level */ - if (jb->jb_init_prefetch) { - jb->jb_prefetch = jb->jb_eff_level; - if (jb->jb_prefetch < jb->jb_min_prefetch) - jb->jb_prefetch = jb->jb_min_prefetch; - if (jb->jb_prefetch > jb->jb_max_prefetch) - jb->jb_prefetch = jb->jb_max_prefetch; - } + /* Update prefetch based on level */ + if (jb->jb_init_prefetch) { + jb->jb_prefetch = jb->jb_eff_level; + if (jb->jb_prefetch < jb->jb_min_prefetch) + jb->jb_prefetch = jb->jb_min_prefetch; + if (jb->jb_prefetch > jb->jb_max_prefetch) + jb->jb_prefetch = jb->jb_max_prefetch; + } - /* Reset history */ - jb->jb_max_hist_level = 0; - jb->jb_stable_hist = 0; + /* Reset history */ + jb->jb_max_hist_level = 0; + jb->jb_stable_hist = 0; - TRACE__((jb->jb_name.ptr,"jb updated(1), lvl=%d pre=%d, size=%d", - jb->jb_eff_level, jb->jb_prefetch, cur_size)); - PJ_UNUSED_ARG(cur_size); /* Warning about unused var */ - } + TRACE__((jb->jb_name.ptr,"jb updated(1), lvl=%d pre=%d, size=%d", + jb->jb_eff_level, jb->jb_prefetch, cur_size)); + PJ_UNUSED_ARG(cur_size); /* Warning about unused var */ + } } /* Burst level is increasing */ else if (jb->jb_level > jb->jb_eff_level) { - /* Instaneous set effective burst level to recent maximum level */ - jb->jb_eff_level = PJ_MIN(jb->jb_max_hist_level, - (int)(jb->jb_max_count*4/5)); - - /* Update prefetch based on level */ - if (jb->jb_init_prefetch) { - jb->jb_prefetch = jb->jb_eff_level; - if (jb->jb_prefetch > jb->jb_max_prefetch) - jb->jb_prefetch = jb->jb_max_prefetch; - if (jb->jb_prefetch < jb->jb_min_prefetch) - jb->jb_prefetch = jb->jb_min_prefetch; - } - - jb->jb_stable_hist = 0; - /* Do not reset max_hist_level. */ - //jb->jb_max_hist_level = 0; - - TRACE__((jb->jb_name.ptr,"jb updated(2), lvl=%d pre=%d, size=%d", - jb->jb_eff_level, jb->jb_prefetch, cur_size)); + /* Instaneous set effective burst level to recent maximum level */ + jb->jb_eff_level = PJ_MIN(jb->jb_max_hist_level, + (int)(jb->jb_max_count*4/5)); + + /* Update prefetch based on level */ + if (jb->jb_init_prefetch) { + jb->jb_prefetch = jb->jb_eff_level; + if (jb->jb_prefetch > jb->jb_max_prefetch) + jb->jb_prefetch = jb->jb_max_prefetch; + if (jb->jb_prefetch < jb->jb_min_prefetch) + jb->jb_prefetch = jb->jb_min_prefetch; + } + + jb->jb_stable_hist = 0; + /* Do not reset max_hist_level. */ + //jb->jb_max_hist_level = 0; + + TRACE__((jb->jb_name.ptr,"jb updated(2), lvl=%d pre=%d, size=%d", + jb->jb_eff_level, jb->jb_prefetch, cur_size)); } /* Level is unchanged */ else { - jb->jb_stable_hist = 0; + jb->jb_stable_hist = 0; } } @@ -853,29 +852,29 @@ static void jbuf_discard_static(pjmedia_jbuf *jb) diff = jb_framelist_eff_size(&jb->jb_framelist) - burst_level*2; if (diff >= STA_DISC_SAFE_SHRINKING_DIFF) { - int seq_origin; - - /* Check and adjust jb_discard_ref, in case there was - * seq restart - */ - seq_origin = jb_framelist_origin(&jb->jb_framelist); - if (seq_origin < jb->jb_discard_ref) - jb->jb_discard_ref = seq_origin; - - if (seq_origin - jb->jb_discard_ref >= jb->jb_min_shrink_gap) - { - /* Shrink slowly, one frame per cycle */ - diff = 1; - - /* Drop frame(s)! */ - diff = jb_framelist_remove_head(&jb->jb_framelist, diff); - jb->jb_discard_ref = jb_framelist_origin(&jb->jb_framelist); - jb->jb_discard += diff; - - TRACE__((jb->jb_name.ptr, - "JB shrinking %d frame(s), cur size=%d", diff, - jb_framelist_eff_size(&jb->jb_framelist))); - } + int seq_origin; + + /* Check and adjust jb_discard_ref, in case there was + * seq restart + */ + seq_origin = jb_framelist_origin(&jb->jb_framelist); + if (seq_origin < jb->jb_discard_ref) + jb->jb_discard_ref = seq_origin; + + if (seq_origin - jb->jb_discard_ref >= jb->jb_min_shrink_gap) + { + /* Shrink slowly, one frame per cycle */ + diff = 1; + + /* Drop frame(s)! */ + diff = jb_framelist_remove_head(&jb->jb_framelist, diff); + jb->jb_discard_ref = jb_framelist_origin(&jb->jb_framelist); + jb->jb_discard += diff; + + TRACE__((jb->jb_name.ptr, + "JB shrinking %d frame(s), cur size=%d", diff, + jb_framelist_eff_size(&jb->jb_framelist))); + } } } @@ -887,27 +886,27 @@ static void jbuf_discard_progressive(pjmedia_jbuf *jb) /* Should be done in PUT operation */ if (jb->jb_last_op != JB_OP_PUT) - return; + return; /* Check if latency is longer than burst */ cur_size = jb_framelist_eff_size(&jb->jb_framelist); burst_level = PJ_MAX(jb->jb_eff_level, jb->jb_level); if (cur_size <= burst_level) { - /* Reset any scheduled discard */ - jb->jb_discard_dist = 0; - return; + /* Reset any scheduled discard */ + jb->jb_discard_dist = 0; + return; } /* Estimate discard duration needed for adjusting latency */ if (burst_level <= PJMEDIA_JBUF_PRO_DISC_MIN_BURST) - T = PJMEDIA_JBUF_PRO_DISC_T1; + T = PJMEDIA_JBUF_PRO_DISC_T1; else if (burst_level >= PJMEDIA_JBUF_PRO_DISC_MAX_BURST) - T = PJMEDIA_JBUF_PRO_DISC_T2; + T = PJMEDIA_JBUF_PRO_DISC_T2; else - T = PJMEDIA_JBUF_PRO_DISC_T1 + - (PJMEDIA_JBUF_PRO_DISC_T2 - PJMEDIA_JBUF_PRO_DISC_T1) * - (burst_level - PJMEDIA_JBUF_PRO_DISC_MIN_BURST) / - (PJMEDIA_JBUF_PRO_DISC_MAX_BURST-PJMEDIA_JBUF_PRO_DISC_MIN_BURST); + T = PJMEDIA_JBUF_PRO_DISC_T1 + + (PJMEDIA_JBUF_PRO_DISC_T2 - PJMEDIA_JBUF_PRO_DISC_T1) * + (burst_level - PJMEDIA_JBUF_PRO_DISC_MIN_BURST) / + (PJMEDIA_JBUF_PRO_DISC_MAX_BURST-PJMEDIA_JBUF_PRO_DISC_MIN_BURST); /* Calculate current discard distance */ overflow = cur_size - burst_level; @@ -915,44 +914,44 @@ static void jbuf_discard_progressive(pjmedia_jbuf *jb) /* Get last seq number in the JB */ last_seq = jb_framelist_origin(&jb->jb_framelist) + - jb_framelist_size(&jb->jb_framelist) - 1; + jb_framelist_size(&jb->jb_framelist) - 1; /* Setup new discard schedule if none, otherwise, update the existing * discard schedule (can be delayed or accelerated). */ if (jb->jb_discard_dist == 0) { - /* Setup new discard schedule */ - jb->jb_discard_ref = last_seq; + /* Setup new discard schedule */ + jb->jb_discard_ref = last_seq; } else if (last_seq < jb->jb_discard_ref) { - /* Seq restarted, update discard reference */ - jb->jb_discard_ref = last_seq; + /* Seq restarted, update discard reference */ + jb->jb_discard_ref = last_seq; } jb->jb_discard_dist = PJ_MAX(jb->jb_min_shrink_gap, (int)discard_dist); /* Check if we need to discard now */ if (last_seq >= (jb->jb_discard_ref + (int)jb->jb_discard_dist)) { - int discard_seq; - - discard_seq = jb->jb_discard_ref + jb->jb_discard_dist; - if (discard_seq < jb_framelist_origin(&jb->jb_framelist)) - discard_seq = jb_framelist_origin(&jb->jb_framelist); - - jb_framelist_discard(&jb->jb_framelist, discard_seq); - - TRACE__((jb->jb_name.ptr, - "Discard #%d: ref=#%d dist=%d orig=%d size=%d/%d " - "burst=%d/%d", - discard_seq, - jb->jb_discard_ref, - jb->jb_discard_dist, - jb_framelist_origin(&jb->jb_framelist), - cur_size, - jb_framelist_size(&jb->jb_framelist), - jb->jb_eff_level, - burst_level)); - - /* Update discard reference */ - jb->jb_discard_ref = discard_seq; + int discard_seq; + + discard_seq = jb->jb_discard_ref + jb->jb_discard_dist; + if (discard_seq < jb_framelist_origin(&jb->jb_framelist)) + discard_seq = jb_framelist_origin(&jb->jb_framelist); + + jb_framelist_discard(&jb->jb_framelist, discard_seq); + + TRACE__((jb->jb_name.ptr, + "Discard #%d: ref=#%d dist=%d orig=%d size=%d/%d " + "burst=%d/%d", + discard_seq, + jb->jb_discard_ref, + jb->jb_discard_dist, + jb_framelist_origin(&jb->jb_framelist), + cur_size, + jb_framelist_size(&jb->jb_framelist), + jb->jb_eff_level, + burst_level)); + + /* Update discard reference */ + jb->jb_discard_ref = discard_seq; } } @@ -960,70 +959,70 @@ static void jbuf_discard_progressive(pjmedia_jbuf *jb) PJ_INLINE(void) jbuf_update(pjmedia_jbuf *jb, int oper) { if(jb->jb_last_op != oper) { - jb->jb_last_op = oper; - - if (jb->jb_status == JB_STATUS_INITIALIZING) { - /* Switch status 'initializing' -> 'processing' after some OP - * switch cycles and current OP is GET (burst level is calculated - * based on PUT burst), so burst calculation is guaranted to be - * performed right after the status switching. - */ - if (++jb->jb_init_cycle_cnt >= INIT_CYCLE && oper == JB_OP_GET) { - jb->jb_status = JB_STATUS_PROCESSING; - /* To make sure the burst calculation will be done right after - * this, adjust burst level if it exceeds max burst level. - */ - jb->jb_level = PJ_MIN(jb->jb_level, jb->jb_max_burst); - } else { - jb->jb_level = 0; - return; - } - } - - /* Perform jitter calculation based on PUT burst-level only, since - * GET burst-level may not be accurate, e.g: when VAD is active. - * Note that when burst-level is too big, i.e: exceeds jb_max_burst, - * the GET op may be idle, in this case, we better skip the jitter - * calculation. - */ - if (oper == JB_OP_GET && jb->jb_level <= jb->jb_max_burst) - jbuf_calculate_jitter(jb); - - jb->jb_level = 0; + jb->jb_last_op = oper; + + if (jb->jb_status == JB_STATUS_INITIALIZING) { + /* Switch status 'initializing' -> 'processing' after some OP + * switch cycles and current OP is GET (burst level is calculated + * based on PUT burst), so burst calculation is guaranted to be + * performed right after the status switching. + */ + if (++jb->jb_init_cycle_cnt >= INIT_CYCLE && oper == JB_OP_GET) { + jb->jb_status = JB_STATUS_PROCESSING; + /* To make sure the burst calculation will be done right after + * this, adjust burst level if it exceeds max burst level. + */ + jb->jb_level = PJ_MIN(jb->jb_level, jb->jb_max_burst); + } else { + jb->jb_level = 0; + return; + } + } + + /* Perform jitter calculation based on PUT burst-level only, since + * GET burst-level may not be accurate, e.g: when VAD is active. + * Note that when burst-level is too big, i.e: exceeds jb_max_burst, + * the GET op may be idle, in this case, we better skip the jitter + * calculation. + */ + if (oper == JB_OP_GET && jb->jb_level <= jb->jb_max_burst) + jbuf_calculate_jitter(jb); + + jb->jb_level = 0; } /* Call discard algorithm */ if (jb->jb_status == JB_STATUS_PROCESSING && jb->jb_discard_algo) { - (*jb->jb_discard_algo)(jb); + (*jb->jb_discard_algo)(jb); } } PJ_DEF(void) pjmedia_jbuf_put_frame( pjmedia_jbuf *jb, - const void *frame, - pj_size_t frame_size, - int frame_seq) + const void *frame, + pj_size_t frame_size, + int frame_seq) { pjmedia_jbuf_put_frame3(jb, frame, frame_size, 0, frame_seq, 0, NULL); } PJ_DEF(void) pjmedia_jbuf_put_frame2(pjmedia_jbuf *jb, - const void *frame, - pj_size_t frame_size, - pj_uint32_t bit_info, - int frame_seq, - pj_bool_t *discarded) + const void *frame, + pj_size_t frame_size, + pj_uint32_t bit_info, + int frame_seq, + pj_bool_t *discarded) { pjmedia_jbuf_put_frame3(jb, frame, frame_size, bit_info, frame_seq, 0, - discarded); + discarded); } PJ_DEF(void) pjmedia_jbuf_put_frame3(pjmedia_jbuf *jb, - const void *frame, - pj_size_t frame_size, - pj_uint32_t bit_info, - int frame_seq, - pj_uint32_t ts, - pj_bool_t *discarded) + const void *frame, + pj_size_t frame_size, + pj_uint32_t bit_info, + int frame_seq, + pj_uint32_t ts, + pj_bool_t *discarded) { pj_size_t min_frame_size; int new_size, cur_size; @@ -1033,36 +1032,36 @@ PJ_DEF(void) pjmedia_jbuf_put_frame3(pjmedia_jbuf *jb, /* Check if frame size is larger than JB frame size */ if (frame_size > jb->jb_frame_size) { - PJ_LOG(4, (THIS_FILE, "Warning: frame too large for jitter buffer, " - "it will be truncated!")); + PJ_LOG(4, (THIS_FILE, "Warning: frame too large for jitter buffer, " + "it will be truncated!")); } /* Attempt to store the frame */ min_frame_size = PJ_MIN(frame_size, jb->jb_frame_size); status = jb_framelist_put_at(&jb->jb_framelist, frame_seq, frame, - (unsigned)min_frame_size, bit_info, ts, - PJMEDIA_JB_NORMAL_FRAME); + (unsigned)min_frame_size, bit_info, ts, + PJMEDIA_JB_NORMAL_FRAME); /* Jitter buffer is full, remove some older frames */ while (status == PJ_ETOOMANY) { - int distance; - unsigned removed; - - /* Remove as few as possible just to make this frame in. Note that - * the cases of seq-jump, out-of-order, and seq restart should have - * been handled/normalized by previous call of jb_framelist_put_at(). - * So we're confident about 'distance' value here. - */ - distance = (frame_seq - jb_framelist_origin(&jb->jb_framelist)) - - (int)jb->jb_max_count + 1; - pj_assert(distance > 0); - - removed = jb_framelist_remove_head(&jb->jb_framelist, distance); - status = jb_framelist_put_at(&jb->jb_framelist, frame_seq, frame, - (unsigned)min_frame_size, bit_info, ts, - PJMEDIA_JB_NORMAL_FRAME); - - jb->jb_discard += removed; + int distance; + unsigned removed; + + /* Remove as few as possible just to make this frame in. Note that + * the cases of seq-jump, out-of-order, and seq restart should have + * been handled/normalized by previous call of jb_framelist_put_at(). + * So we're confident about 'distance' value here. + */ + distance = (frame_seq - jb_framelist_origin(&jb->jb_framelist)) - + (int)jb->jb_max_count + 1; + pj_assert(distance > 0); + + removed = jb_framelist_remove_head(&jb->jb_framelist, distance); + status = jb_framelist_put_at(&jb->jb_framelist, frame_seq, frame, + (unsigned)min_frame_size, bit_info, ts, + PJMEDIA_JB_NORMAL_FRAME); + + jb->jb_discard += removed; } /* Get new JB size after PUT */ @@ -1070,112 +1069,112 @@ PJ_DEF(void) pjmedia_jbuf_put_frame3(pjmedia_jbuf *jb, /* Return the flag if this frame is discarded */ if (discarded) - *discarded = (status != PJ_SUCCESS); + *discarded = (status != PJ_SUCCESS); if (status == PJ_SUCCESS) { - if (jb->jb_prefetching) { - TRACE__((jb->jb_name.ptr, "PUT prefetch_cnt=%d/%d", - new_size, jb->jb_prefetch)); - if (new_size >= jb->jb_prefetch) - jb->jb_prefetching = PJ_FALSE; - } - jb->jb_level += (new_size > cur_size ? new_size-cur_size : 1); - jbuf_update(jb, JB_OP_PUT); + if (jb->jb_prefetching) { + TRACE__((jb->jb_name.ptr, "PUT prefetch_cnt=%d/%d", + new_size, jb->jb_prefetch)); + if (new_size >= jb->jb_prefetch) + jb->jb_prefetching = PJ_FALSE; + } + jb->jb_level += (new_size > cur_size ? new_size-cur_size : 1); + jbuf_update(jb, JB_OP_PUT); } else - jb->jb_discard++; + jb->jb_discard++; } /* * Get frame from jitter buffer. */ PJ_DEF(void) pjmedia_jbuf_get_frame( pjmedia_jbuf *jb, - void *frame, - char *p_frame_type) + void *frame, + char *p_frame_type) { pjmedia_jbuf_get_frame3(jb, frame, NULL, p_frame_type, NULL, - NULL, NULL); + NULL, NULL); } /* * Get frame from jitter buffer. */ PJ_DEF(void) pjmedia_jbuf_get_frame2(pjmedia_jbuf *jb, - void *frame, - pj_size_t *size, - char *p_frame_type, - pj_uint32_t *bit_info) + void *frame, + pj_size_t *size, + char *p_frame_type, + pj_uint32_t *bit_info) { pjmedia_jbuf_get_frame3(jb, frame, size, p_frame_type, bit_info, - NULL, NULL); + NULL, NULL); } /* * Get frame from jitter buffer. */ PJ_DEF(void) pjmedia_jbuf_get_frame3(pjmedia_jbuf *jb, - void *frame, - pj_size_t *size, - char *p_frame_type, - pj_uint32_t *bit_info, - pj_uint32_t *ts, - int *seq) + void *frame, + pj_size_t *size, + char *p_frame_type, + pj_uint32_t *bit_info, + pj_uint32_t *ts, + int *seq) { if (jb->jb_prefetching) { - /* Can't return frame because jitter buffer is filling up - * minimum prefetch. - */ + /* Can't return frame because jitter buffer is filling up + * minimum prefetch. + */ - //pj_bzero(frame, jb->jb_frame_size); - *p_frame_type = PJMEDIA_JB_ZERO_PREFETCH_FRAME; - if (size) - *size = 0; + //pj_bzero(frame, jb->jb_frame_size); + *p_frame_type = PJMEDIA_JB_ZERO_PREFETCH_FRAME; + if (size) + *size = 0; - TRACE__((jb->jb_name.ptr, "GET prefetch_cnt=%d/%d", - jb_framelist_eff_size(&jb->jb_framelist), jb->jb_prefetch)); + TRACE__((jb->jb_name.ptr, "GET prefetch_cnt=%d/%d", + jb_framelist_eff_size(&jb->jb_framelist), jb->jb_prefetch)); - jb->jb_empty++; + jb->jb_empty++; } else { - pjmedia_jb_frame_type ftype = PJMEDIA_JB_NORMAL_FRAME; - pj_bool_t res; - - /* Try to retrieve a frame from frame list */ - res = jb_framelist_get(&jb->jb_framelist, frame, size, &ftype, - bit_info, ts, seq); - if (res) { - /* We've successfully retrieved a frame from the frame list, but - * the frame could be a blank frame! - */ - if (ftype == PJMEDIA_JB_NORMAL_FRAME) { - *p_frame_type = PJMEDIA_JB_NORMAL_FRAME; - } else { - *p_frame_type = PJMEDIA_JB_MISSING_FRAME; - jb->jb_lost++; - } - - /* Store delay history at the first GET */ - if (jb->jb_last_op == JB_OP_PUT) { - unsigned cur_size; - - /* We've just retrieved one frame, so add one to cur_size */ - cur_size = jb_framelist_eff_size(&jb->jb_framelist) + 1; - pj_math_stat_update(&jb->jb_delay, - cur_size*jb->jb_frame_ptime); - } - } else { - /* Jitter buffer is empty */ - if (jb->jb_prefetch) - jb->jb_prefetching = PJ_TRUE; - - //pj_bzero(frame, jb->jb_frame_size); - *p_frame_type = PJMEDIA_JB_ZERO_EMPTY_FRAME; - if (size) - *size = 0; - - jb->jb_empty++; - } + pjmedia_jb_frame_type ftype = PJMEDIA_JB_NORMAL_FRAME; + pj_bool_t res; + + /* Try to retrieve a frame from frame list */ + res = jb_framelist_get(&jb->jb_framelist, frame, size, &ftype, + bit_info, ts, seq); + if (res) { + /* We've successfully retrieved a frame from the frame list, but + * the frame could be a blank frame! + */ + if (ftype == PJMEDIA_JB_NORMAL_FRAME) { + *p_frame_type = PJMEDIA_JB_NORMAL_FRAME; + } else { + *p_frame_type = PJMEDIA_JB_MISSING_FRAME; + jb->jb_lost++; + } + + /* Store delay history at the first GET */ + if (jb->jb_last_op == JB_OP_PUT) { + unsigned cur_size; + + /* We've just retrieved one frame, so add one to cur_size */ + cur_size = jb_framelist_eff_size(&jb->jb_framelist) + 1; + pj_math_stat_update(&jb->jb_delay, + cur_size*jb->jb_frame_ptime); + } + } else { + /* Jitter buffer is empty */ + if (jb->jb_prefetch) + jb->jb_prefetching = PJ_TRUE; + + //pj_bzero(frame, jb->jb_frame_size); + *p_frame_type = PJMEDIA_JB_ZERO_EMPTY_FRAME; + if (size) + *size = 0; + + jb->jb_empty++; + } } jb->jb_level++; @@ -1186,7 +1185,7 @@ PJ_DEF(void) pjmedia_jbuf_get_frame3(pjmedia_jbuf *jb, * Get jitter buffer state. */ PJ_DEF(pj_status_t) pjmedia_jbuf_get_state( const pjmedia_jbuf *jb, - pjmedia_jb_state *state ) + pjmedia_jb_state *state ) { PJ_ASSERT_RETURN(jb && state, PJ_EINVAL); @@ -1214,30 +1213,30 @@ PJ_DEF(pj_status_t) pjmedia_jbuf_get_state( const pjmedia_jbuf *jb, PJ_DEF(void) pjmedia_jbuf_peek_frame( pjmedia_jbuf *jb, - unsigned offset, - const void **frame, - pj_size_t *size, - char *p_frm_type, - pj_uint32_t *bit_info, - pj_uint32_t *ts, - int *seq) + unsigned offset, + const void **frame, + pj_size_t *size, + char *p_frm_type, + pj_uint32_t *bit_info, + pj_uint32_t *ts, + int *seq) { pjmedia_jb_frame_type ftype; pj_bool_t res; res = jb_framelist_peek(&jb->jb_framelist, offset, frame, size, &ftype, - bit_info, ts, seq); + bit_info, ts, seq); if (!res) - *p_frm_type = PJMEDIA_JB_ZERO_EMPTY_FRAME; + *p_frm_type = PJMEDIA_JB_ZERO_EMPTY_FRAME; else if (ftype == PJMEDIA_JB_NORMAL_FRAME) - *p_frm_type = PJMEDIA_JB_NORMAL_FRAME; + *p_frm_type = PJMEDIA_JB_NORMAL_FRAME; else - *p_frm_type = PJMEDIA_JB_MISSING_FRAME; + *p_frm_type = PJMEDIA_JB_MISSING_FRAME; } PJ_DEF(unsigned) pjmedia_jbuf_remove_frame(pjmedia_jbuf *jb, - unsigned frame_cnt) + unsigned frame_cnt) { unsigned count, last_discard_num; @@ -1246,15 +1245,15 @@ PJ_DEF(unsigned) pjmedia_jbuf_remove_frame(pjmedia_jbuf *jb, /* Remove some more when there were discarded frames included */ while (jb->jb_framelist.discarded_num < last_discard_num) { - /* Calculate frames count to be removed next */ - frame_cnt = last_discard_num - jb->jb_framelist.discarded_num; + /* Calculate frames count to be removed next */ + frame_cnt = last_discard_num - jb->jb_framelist.discarded_num; - /* Normalize non-discarded frames count just been removed */ - count -= frame_cnt; + /* Normalize non-discarded frames count just been removed */ + count -= frame_cnt; - /* Remove more frames */ - last_discard_num = jb->jb_framelist.discarded_num; - count += jb_framelist_remove_head(&jb->jb_framelist, frame_cnt); + /* Remove more frames */ + last_discard_num = jb->jb_framelist.discarded_num; + count += jb_framelist_remove_head(&jb->jb_framelist, frame_cnt); } return count; diff --git a/pjmedia/src/pjmedia/master_port.c b/pjmedia/src/pjmedia/master_port.c index 25a9e995f3..54bcce202a 100644 --- a/pjmedia/src/pjmedia/master_port.c +++ b/pjmedia/src/pjmedia/master_port.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,13 +27,13 @@ struct pjmedia_master_port { - unsigned options; + unsigned options; pjmedia_clock *clock; pjmedia_port *u_port; pjmedia_port *d_port; - unsigned buff_size; - void *buff; - pj_lock_t *lock; + unsigned buff_size; + void *buff; + pj_lock_t *lock; }; @@ -46,10 +45,10 @@ static void clock_callback(const pj_timestamp *ts, void *user_data); * */ PJ_DEF(pj_status_t) pjmedia_master_port_create( pj_pool_t *pool, - pjmedia_port *u_port, - pjmedia_port *d_port, - unsigned options, - pjmedia_master_port **p_m) + pjmedia_port *u_port, + pjmedia_port *d_port, + unsigned options, + pjmedia_master_port **p_m) { pjmedia_master_port *m; unsigned clock_rate; @@ -67,16 +66,16 @@ PJ_DEF(pj_status_t) pjmedia_master_port_create( pj_pool_t *pool, /* Both ports MUST have equal clock rate */ PJ_ASSERT_RETURN(u_afd->clock_rate == d_afd->clock_rate, - PJMEDIA_ENCCLOCKRATE); + PJMEDIA_ENCCLOCKRATE); /* Both ports MUST have equal samples per frame */ PJ_ASSERT_RETURN(PJMEDIA_PIA_SPF(&u_port->info)== - PJMEDIA_PIA_SPF(&d_port->info), - PJMEDIA_ENCSAMPLESPFRAME); + PJMEDIA_PIA_SPF(&d_port->info), + PJMEDIA_ENCSAMPLESPFRAME); /* Both ports MUST have equal channel count */ PJ_ASSERT_RETURN(u_afd->channel_count == d_afd->channel_count, - PJMEDIA_ENCCHANNEL); + PJMEDIA_ENCCHANNEL); /* Get clock_rate and samples_per_frame from one of the port. */ @@ -90,7 +89,7 @@ PJ_DEF(pj_status_t) pjmedia_master_port_create( pj_pool_t *pool, */ bytes_per_frame = PJMEDIA_AFD_AVG_FSZ(u_afd); if (PJMEDIA_AFD_AVG_FSZ(d_afd) > bytes_per_frame) - bytes_per_frame = PJMEDIA_AFD_AVG_FSZ(d_afd); + bytes_per_frame = PJMEDIA_AFD_AVG_FSZ(d_afd); /* Create the master port instance */ @@ -104,20 +103,20 @@ PJ_DEF(pj_status_t) pjmedia_master_port_create( pj_pool_t *pool, m->buff_size = bytes_per_frame; m->buff = pj_pool_alloc(pool, m->buff_size); if (!m->buff) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create lock object */ status = pj_lock_create_simple_mutex(pool, "mport", &m->lock); if (status != PJ_SUCCESS) - return status; + return status; /* Create media clock */ status = pjmedia_clock_create(pool, clock_rate, channel_count, - samples_per_frame, options, &clock_callback, - m, &m->clock); + samples_per_frame, options, &clock_callback, + m, &m->clock); if (status != PJ_SUCCESS) { - pj_lock_destroy(m->lock); - return status; + pj_lock_destroy(m->lock); + return status; } /* Done */ @@ -152,8 +151,8 @@ PJ_DEF(pj_status_t) pjmedia_master_port_stop(pjmedia_master_port *m) /* Poll the master port clock */ PJ_DEF(pj_bool_t) pjmedia_master_port_wait( pjmedia_master_port *m, - pj_bool_t wait, - pj_timestamp *ts) + pj_bool_t wait, + pj_timestamp *ts) { PJ_ASSERT_RETURN(m && m->clock, PJ_FALSE); @@ -181,7 +180,7 @@ static void clock_callback(const pj_timestamp *ts, void *user_data) status = pjmedia_port_get_frame(m->u_port, &frame); if (status != PJ_SUCCESS) - frame.type = PJMEDIA_FRAME_TYPE_NONE; + frame.type = PJMEDIA_FRAME_TYPE_NONE; status = pjmedia_port_put_frame(m->d_port, &frame); @@ -193,7 +192,7 @@ static void clock_callback(const pj_timestamp *ts, void *user_data) status = pjmedia_port_get_frame(m->d_port, &frame); if (status != PJ_SUCCESS) - frame.type = PJMEDIA_FRAME_TYPE_NONE; + frame.type = PJMEDIA_FRAME_TYPE_NONE; status = pjmedia_port_put_frame(m->u_port, &frame); @@ -206,7 +205,7 @@ static void clock_callback(const pj_timestamp *ts, void *user_data) * Change the upstream port. */ PJ_DEF(pj_status_t) pjmedia_master_port_set_uport(pjmedia_master_port *m, - pjmedia_port *port) + pjmedia_port *port) { PJ_ASSERT_RETURN(m && port, PJ_EINVAL); @@ -217,11 +216,11 @@ PJ_DEF(pj_status_t) pjmedia_master_port_set_uport(pjmedia_master_port *m, * frame. */ if (m->d_port) { - PJ_ASSERT_RETURN( - PJMEDIA_PIA_PTIME(&port->info) == - PJMEDIA_PIA_PTIME(&m->d_port->info), - PJMEDIA_ENCSAMPLESPFRAME - ); + PJ_ASSERT_RETURN( + PJMEDIA_PIA_PTIME(&port->info) == + PJMEDIA_PIA_PTIME(&m->d_port->info), + PJMEDIA_ENCSAMPLESPFRAME + ); } pj_lock_acquire(m->lock); @@ -248,7 +247,7 @@ PJ_DEF(pjmedia_port*) pjmedia_master_port_get_uport(pjmedia_master_port*m) * Change the downstream port. */ PJ_DEF(pj_status_t) pjmedia_master_port_set_dport(pjmedia_master_port *m, - pjmedia_port *port) + pjmedia_port *port) { PJ_ASSERT_RETURN(m && port, PJ_EINVAL); @@ -259,11 +258,11 @@ PJ_DEF(pj_status_t) pjmedia_master_port_set_dport(pjmedia_master_port *m, * frame. */ if (m->u_port) { - PJ_ASSERT_RETURN( - PJMEDIA_PIA_PTIME(&port->info) == - PJMEDIA_PIA_PTIME(&m->u_port->info), - PJMEDIA_ENCSAMPLESPFRAME - ); + PJ_ASSERT_RETURN( + PJMEDIA_PIA_PTIME(&port->info) == + PJMEDIA_PIA_PTIME(&m->u_port->info), + PJMEDIA_ENCSAMPLESPFRAME + ); } pj_lock_acquire(m->lock); @@ -291,28 +290,28 @@ PJ_DEF(pjmedia_port*) pjmedia_master_port_get_dport(pjmedia_master_port*m) * d_port ports. */ PJ_DEF(pj_status_t) pjmedia_master_port_destroy(pjmedia_master_port *m, - pj_bool_t destroy_ports) + pj_bool_t destroy_ports) { PJ_ASSERT_RETURN(m, PJ_EINVAL); if (m->clock) { - pjmedia_clock_destroy(m->clock); - m->clock = NULL; + pjmedia_clock_destroy(m->clock); + m->clock = NULL; } if (m->u_port && destroy_ports) { - pjmedia_port_destroy(m->u_port); - m->u_port = NULL; + pjmedia_port_destroy(m->u_port); + m->u_port = NULL; } if (m->d_port && destroy_ports) { - pjmedia_port_destroy(m->d_port); - m->d_port = NULL; + pjmedia_port_destroy(m->d_port); + m->d_port = NULL; } if (m->lock) { - pj_lock_destroy(m->lock); - m->lock = NULL; + pj_lock_destroy(m->lock); + m->lock = NULL; } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia/mem_capture.c b/pjmedia/src/pjmedia/mem_capture.c index 7bbffdb49d..d03771c0ad 100644 --- a/pjmedia/src/pjmedia/mem_capture.c +++ b/pjmedia/src/pjmedia/mem_capture.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,54 +23,54 @@ #include -#define THIS_FILE "mem_capture.c" +#define THIS_FILE "mem_capture.c" -#define SIGNATURE PJMEDIA_SIG_PORT_MEM_CAPTURE +#define SIGNATURE PJMEDIA_SIG_PORT_MEM_CAPTURE #define BYTES_PER_SAMPLE 2 struct mem_rec { pjmedia_port base; - unsigned options; + unsigned options; - char *buffer; - pj_size_t buf_size; - char *write_pos; + char *buffer; + pj_size_t buf_size; + char *write_pos; pj_bool_t eof; - void *user_data; + void *user_data; pj_status_t (*cb)(pjmedia_port *port, - void *user_data); - pj_bool_t subscribed; - void (*cb2)(pjmedia_port*, void*); + void *user_data); + pj_bool_t subscribed; + void (*cb2)(pjmedia_port*, void*); }; static pj_status_t rec_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t rec_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t rec_on_destroy(pjmedia_port *this_port); PJ_DEF(pj_status_t) pjmedia_mem_capture_create( pj_pool_t *pool, - void *buffer, - pj_size_t size, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_port **p_port) + void *buffer, + pj_size_t size, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_port **p_port) { struct mem_rec *rec; const pj_str_t name = { "memrec", 6 }; /* Sanity check */ PJ_ASSERT_RETURN(pool && buffer && size && clock_rate && channel_count && - samples_per_frame && bits_per_sample && p_port, - PJ_EINVAL); + samples_per_frame && bits_per_sample && p_port, + PJ_EINVAL); /* Can only support 16bit PCM */ PJ_ASSERT_RETURN(bits_per_sample == 16, PJ_EINVAL); @@ -82,8 +81,8 @@ PJ_DEF(pj_status_t) pjmedia_mem_capture_create( pj_pool_t *pool, /* Create the rec */ pjmedia_port_info_init(&rec->base.info, &name, SIGNATURE, - clock_rate, channel_count, bits_per_sample, - samples_per_frame); + clock_rate, channel_count, bits_per_sample, + samples_per_frame); rec->base.put_frame = &rec_put_frame; @@ -110,17 +109,17 @@ PJ_DEF(pj_status_t) pjmedia_mem_capture_create( pj_pool_t *pool, * end of buffer. */ PJ_DEF(pj_status_t) pjmedia_mem_capture_set_eof_cb( pjmedia_port *port, - void *user_data, - pj_status_t (*cb)(pjmedia_port *port, - void *usr_data)) + void *user_data, + pj_status_t (*cb)(pjmedia_port *port, + void *usr_data)) { struct mem_rec *rec; PJ_ASSERT_RETURN(port->info.signature == SIGNATURE, - PJ_EINVALIDOP); + PJ_EINVALIDOP); PJ_LOG(1, (THIS_FILE, "pjmedia_mem_capture_set_eof_cb() is deprecated. " - "Use pjmedia_mem_capture_set_eof_cb2() instead.")); + "Use pjmedia_mem_capture_set_eof_cb2() instead.")); rec = (struct mem_rec*) port; rec->user_data = user_data; @@ -136,14 +135,14 @@ PJ_DEF(pj_status_t) pjmedia_mem_capture_set_eof_cb( pjmedia_port *port, * end of buffer. */ PJ_DEF(pj_status_t) pjmedia_mem_capture_set_eof_cb2( pjmedia_port *port, - void *user_data, - void (*cb)(pjmedia_port *port, - void *usr_data)) + void *user_data, + void (*cb)(pjmedia_port *port, + void *usr_data)) { struct mem_rec *rec; PJ_ASSERT_RETURN(port->info.signature == SIGNATURE, - PJ_EINVALIDOP); + PJ_EINVALIDOP); rec = (struct mem_rec*) port; rec->user_data = user_data; @@ -175,8 +174,8 @@ static pj_status_t rec_on_event(pjmedia_event *event, struct mem_rec *rec = (struct mem_rec *)user_data; if (event->type == PJMEDIA_EVENT_CALLBACK) { - if (rec->cb2) - (*rec->cb2)(&rec->base, rec->user_data); + if (rec->cb2) + (*rec->cb2)(&rec->base, rec->user_data); } return PJ_SUCCESS; @@ -184,77 +183,77 @@ static pj_status_t rec_on_event(pjmedia_event *event, static pj_status_t rec_put_frame( pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct mem_rec *rec; char *endpos; pj_size_t size_written; PJ_ASSERT_RETURN(this_port->info.signature == SIGNATURE, - PJ_EINVALIDOP); + PJ_EINVALIDOP); rec = (struct mem_rec*) this_port; if (rec->eof) { - return PJ_EEOF; + return PJ_EEOF; } size_written = 0; endpos = rec->buffer + rec->buf_size; while (size_written < frame->size) { - pj_size_t max; - - max = frame->size - size_written; - if ((endpos - rec->write_pos) < (int)max) - max = endpos - rec->write_pos; - - pj_memcpy(rec->write_pos, ((char*)frame->buf)+size_written, max); - size_written += max; - rec->write_pos += max; - - pj_assert(rec->write_pos <= endpos); - + pj_size_t max; + + max = frame->size - size_written; + if ((endpos - rec->write_pos) < (int)max) + max = endpos - rec->write_pos; + + pj_memcpy(rec->write_pos, ((char*)frame->buf)+size_written, max); + size_written += max; + rec->write_pos += max; + + pj_assert(rec->write_pos <= endpos); + if (rec->write_pos == endpos) { - - /* Rewind */ - rec->write_pos = rec->buffer; - - /* Call callback, if any */ - if (rec->cb2) { - if (!rec->subscribed) { - pj_status_t status; - - status = pjmedia_event_subscribe(NULL, rec_on_event, - rec, rec); - rec->subscribed = (status == PJ_SUCCESS)? PJ_TRUE: - PJ_FALSE; - } - - if (rec->subscribed) { - pjmedia_event event; - - pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, - NULL, rec); - pjmedia_event_publish(NULL, rec, &event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); - } - - return PJ_SUCCESS; - - } else if (rec->cb) { - pj_status_t status; - - rec->eof = PJ_TRUE; - status = (*rec->cb)(this_port, rec->user_data); - if (status != PJ_SUCCESS) { - /* Must not access recorder from here on. It may be - * destroyed by application. - */ + + /* Rewind */ + rec->write_pos = rec->buffer; + + /* Call callback, if any */ + if (rec->cb2) { + if (!rec->subscribed) { + pj_status_t status; + + status = pjmedia_event_subscribe(NULL, rec_on_event, + rec, rec); + rec->subscribed = (status == PJ_SUCCESS)? PJ_TRUE: + PJ_FALSE; + } + + if (rec->subscribed) { + pjmedia_event event; + + pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, + NULL, rec); + pjmedia_event_publish(NULL, rec, &event, + PJMEDIA_EVENT_PUBLISH_POST_EVENT); + } + + return PJ_SUCCESS; + + } else if (rec->cb) { + pj_status_t status; + + rec->eof = PJ_TRUE; + status = (*rec->cb)(this_port, rec->user_data); + if (status != PJ_SUCCESS) { + /* Must not access recorder from here on. It may be + * destroyed by application. + */ return status; - } - rec->eof = PJ_FALSE; - } + } + rec->eof = PJ_FALSE; + } } } @@ -263,10 +262,10 @@ static pj_status_t rec_put_frame( pjmedia_port *this_port, static pj_status_t rec_get_frame( pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { PJ_ASSERT_RETURN(this_port->info.signature == SIGNATURE, - PJ_EINVALIDOP); + PJ_EINVALIDOP); PJ_UNUSED_ARG(this_port); @@ -290,12 +289,12 @@ static pj_status_t rec_on_destroy(pjmedia_port *this_port) rec = (struct mem_rec*) this_port; if (rec->subscribed) { - pjmedia_event_unsubscribe(NULL, &rec_on_event, rec, rec); - rec->subscribed = PJ_FALSE; + pjmedia_event_unsubscribe(NULL, &rec_on_event, rec, rec); + rec->subscribed = PJ_FALSE; } if(rec->cb && PJ_FALSE == rec->eof) { - rec->eof = PJ_TRUE; + rec->eof = PJ_TRUE; (*rec->cb)(this_port, rec->user_data); } diff --git a/pjmedia/src/pjmedia/mem_player.c b/pjmedia/src/pjmedia/mem_player.c index 3ebf5a1288..ff38065df6 100644 --- a/pjmedia/src/pjmedia/mem_player.c +++ b/pjmedia/src/pjmedia/mem_player.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,55 +23,55 @@ #include -#define THIS_FILE "mem_player.c" +#define THIS_FILE "mem_player.c" -#define SIGNATURE PJMEDIA_SIG_PORT_MEM_PLAYER +#define SIGNATURE PJMEDIA_SIG_PORT_MEM_PLAYER #define BYTES_PER_SAMPLE 2 struct mem_player { pjmedia_port base; - unsigned options; + unsigned options; pj_timestamp timestamp; - char *buffer; - pj_size_t buf_size; - char *read_pos; + char *buffer; + pj_size_t buf_size; + char *read_pos; - pj_bool_t eof; - void *user_data; + pj_bool_t eof; + void *user_data; pj_status_t (*cb)(pjmedia_port *port, - void *user_data); - pj_bool_t subscribed; - void (*cb2)(pjmedia_port*, void*); + void *user_data); + pj_bool_t subscribed; + void (*cb2)(pjmedia_port*, void*); }; static pj_status_t mem_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t mem_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t mem_on_destroy(pjmedia_port *this_port); PJ_DEF(pj_status_t) pjmedia_mem_player_create( pj_pool_t *pool, - const void *buffer, - pj_size_t size, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_port **p_port ) + const void *buffer, + pj_size_t size, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_port **p_port ) { struct mem_player *port; pj_str_t name = pj_str("memplayer"); /* Sanity check */ PJ_ASSERT_RETURN(pool && buffer && size && clock_rate && channel_count && - samples_per_frame && bits_per_sample && p_port, - PJ_EINVAL); + samples_per_frame && bits_per_sample && p_port, + PJ_EINVAL); /* Can only support 16bit PCM */ PJ_ASSERT_RETURN(bits_per_sample == 16, PJ_EINVAL); @@ -83,7 +82,7 @@ PJ_DEF(pj_status_t) pjmedia_mem_player_create( pj_pool_t *pool, /* Create the port */ pjmedia_port_info_init(&port->base.info, &name, SIGNATURE, clock_rate, - channel_count, bits_per_sample, samples_per_frame); + channel_count, bits_per_sample, samples_per_frame); port->base.put_frame = &mem_put_frame; port->base.get_frame = &mem_get_frame; @@ -109,17 +108,17 @@ PJ_DEF(pj_status_t) pjmedia_mem_player_create( pj_pool_t *pool, * end of buffer. */ PJ_DEF(pj_status_t) pjmedia_mem_player_set_eof_cb( pjmedia_port *port, - void *user_data, - pj_status_t (*cb)(pjmedia_port *port, - void *usr_data)) + void *user_data, + pj_status_t (*cb)(pjmedia_port *port, + void *usr_data)) { struct mem_player *player; PJ_ASSERT_RETURN(port->info.signature == SIGNATURE, - PJ_EINVALIDOP); + PJ_EINVALIDOP); PJ_LOG(1, (THIS_FILE, "pjmedia_mem_player_set_eof_cb() is deprecated. " - "Use pjmedia_mem_player_set_eof_cb2() instead.")); + "Use pjmedia_mem_player_set_eof_cb2() instead.")); player = (struct mem_player*) port; player->user_data = user_data; @@ -135,14 +134,14 @@ PJ_DEF(pj_status_t) pjmedia_mem_player_set_eof_cb( pjmedia_port *port, * end of buffer. */ PJ_DEF(pj_status_t) pjmedia_mem_player_set_eof_cb2( pjmedia_port *port, - void *user_data, - void (*cb)(pjmedia_port *port, - void *usr_data)) + void *user_data, + void (*cb)(pjmedia_port *port, + void *usr_data)) { struct mem_player *player; PJ_ASSERT_RETURN(port->info.signature == SIGNATURE, - PJ_EINVALIDOP); + PJ_EINVALIDOP); player = (struct mem_player*) port; player->user_data = user_data; @@ -153,7 +152,7 @@ PJ_DEF(pj_status_t) pjmedia_mem_player_set_eof_cb2( pjmedia_port *port, static pj_status_t mem_put_frame( pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { PJ_UNUSED_ARG(this_port); PJ_UNUSED_ARG(frame); @@ -168,8 +167,8 @@ static pj_status_t player_on_event(pjmedia_event *event, struct mem_player *player = (struct mem_player *)user_data; if (event->type == PJMEDIA_EVENT_CALLBACK) { - if (player->cb2) - (*player->cb2)(&player->base, player->user_data); + if (player->cb2) + (*player->cb2)(&player->base, player->user_data); } return PJ_SUCCESS; @@ -177,7 +176,7 @@ static pj_status_t player_on_event(pjmedia_event *event, static pj_status_t mem_get_frame( pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct mem_player *player; char *endpos; @@ -185,65 +184,65 @@ static pj_status_t mem_get_frame( pjmedia_port *this_port, pj_bool_t delayed_cb = PJ_FALSE; PJ_ASSERT_RETURN(this_port->info.signature == SIGNATURE, - PJ_EINVALIDOP); + PJ_EINVALIDOP); player = (struct mem_player*) this_port; if (player->eof) { - pj_status_t status = PJ_SUCCESS; - pj_bool_t no_loop = (player->options & PJMEDIA_MEM_NO_LOOP); - - /* Call callback, if any */ - if (player->cb2) { - if (!player->subscribed) { - pj_status_t status2; - status2 = pjmedia_event_subscribe(NULL, &player_on_event, - player, player); - player->subscribed = (status2 == PJ_SUCCESS)? PJ_TRUE: - PJ_FALSE; - } - - if (player->subscribed && player->eof != 2) { - if (no_loop) { - pjmedia_event event; - - /* To prevent the callback from being called repeatedly */ - player->eof = 2; - - pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, - NULL, player); - pjmedia_event_publish(NULL, player, &event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); - /* Should not access player port after this since - * it might have been destroyed by the callback. - */ - } else { - delayed_cb = PJ_TRUE; - } - } - - if (no_loop) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - return PJ_EEOF; - } - - } else if (player->cb) { - status = (*player->cb)(this_port, player->user_data); - } - - /* If callback returns non PJ_SUCCESS or 'no loop' is specified - * return immediately (and don't try to access player port since - * it might have been destroyed by the callback). - */ - if ((status != PJ_SUCCESS) || no_loop) - { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - return PJ_EEOF; - } - - player->eof = PJ_FALSE; + pj_status_t status = PJ_SUCCESS; + pj_bool_t no_loop = (player->options & PJMEDIA_MEM_NO_LOOP); + + /* Call callback, if any */ + if (player->cb2) { + if (!player->subscribed) { + pj_status_t status2; + status2 = pjmedia_event_subscribe(NULL, &player_on_event, + player, player); + player->subscribed = (status2 == PJ_SUCCESS)? PJ_TRUE: + PJ_FALSE; + } + + if (player->subscribed && player->eof != 2) { + if (no_loop) { + pjmedia_event event; + + /* To prevent the callback from being called repeatedly */ + player->eof = 2; + + pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, + NULL, player); + pjmedia_event_publish(NULL, player, &event, + PJMEDIA_EVENT_PUBLISH_POST_EVENT); + /* Should not access player port after this since + * it might have been destroyed by the callback. + */ + } else { + delayed_cb = PJ_TRUE; + } + } + + if (no_loop) { + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + return PJ_EEOF; + } + + } else if (player->cb) { + status = (*player->cb)(this_port, player->user_data); + } + + /* If callback returns non PJ_SUCCESS or 'no loop' is specified + * return immediately (and don't try to access player port since + * it might have been destroyed by the callback). + */ + if ((status != PJ_SUCCESS) || no_loop) + { + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + return PJ_EEOF; + } + + player->eof = PJ_FALSE; } size_needed = PJMEDIA_PIA_AVG_FSZ(&this_port->info); @@ -251,34 +250,34 @@ static pj_status_t mem_get_frame( pjmedia_port *this_port, endpos = player->buffer + player->buf_size; while (size_written < size_needed) { - char *dst = ((char*)frame->buf) + size_written; - pj_size_t max; - - max = size_needed - size_written; - if (endpos - player->read_pos < (int)max) - max = endpos - player->read_pos; - - pj_memcpy(dst, player->read_pos, max); - size_written += max; - player->read_pos += max; - - pj_assert(player->read_pos <= endpos); - - if (player->read_pos == endpos) { - /* Set EOF flag */ - player->eof = PJ_TRUE; - /* Reset read pointer */ - player->read_pos = player->buffer; - - /* Pad with zeroes then return for no looped play */ - if (player->options & PJMEDIA_MEM_NO_LOOP) { - pj_size_t null_len; - - null_len = size_needed - size_written; - pj_bzero(dst + max, null_len); - break; - } - } + char *dst = ((char*)frame->buf) + size_written; + pj_size_t max; + + max = size_needed - size_written; + if (endpos - player->read_pos < (int)max) + max = endpos - player->read_pos; + + pj_memcpy(dst, player->read_pos, max); + size_written += max; + player->read_pos += max; + + pj_assert(player->read_pos <= endpos); + + if (player->read_pos == endpos) { + /* Set EOF flag */ + player->eof = PJ_TRUE; + /* Reset read pointer */ + player->read_pos = player->buffer; + + /* Pad with zeroes then return for no looped play */ + if (player->options & PJMEDIA_MEM_NO_LOOP) { + pj_size_t null_len; + + null_len = size_needed - size_written; + pj_bzero(dst + max, null_len); + break; + } + } } frame->size = PJMEDIA_PIA_AVG_FSZ(&this_port->info); @@ -288,14 +287,14 @@ static pj_status_t mem_get_frame( pjmedia_port *this_port, player->timestamp.u64 += PJMEDIA_PIA_SPF(&this_port->info); if (delayed_cb) { - pjmedia_event event; - pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, - NULL, player); - pjmedia_event_publish(NULL, player, &event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); - /* Should not access player port after this since - * it might have been destroyed by the callback. - */ + pjmedia_event event; + pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, + NULL, player); + pjmedia_event_publish(NULL, player, &event, + PJMEDIA_EVENT_PUBLISH_POST_EVENT); + /* Should not access player port after this since + * it might have been destroyed by the callback. + */ } return PJ_SUCCESS; @@ -312,8 +311,8 @@ static pj_status_t mem_on_destroy(pjmedia_port *this_port) player = (struct mem_player*) this_port; if (player->subscribed) { - pjmedia_event_unsubscribe(NULL, &player_on_event, player, player); - player->subscribed = PJ_FALSE; + pjmedia_event_unsubscribe(NULL, &player_on_event, player, player); + player->subscribed = PJ_FALSE; } /* Destroy signature */ diff --git a/pjmedia/src/pjmedia/null_port.c b/pjmedia/src/pjmedia/null_port.c index ca50c533fc..fb5dfccf4d 100644 --- a/pjmedia/src/pjmedia/null_port.c +++ b/pjmedia/src/pjmedia/null_port.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,18 +26,18 @@ #define SIGNATURE PJMEDIA_SIG_PORT_NULL static pj_status_t null_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t null_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t null_on_destroy(pjmedia_port *this_port); PJ_DEF(pj_status_t) pjmedia_null_port_create( pj_pool_t *pool, - unsigned sampling_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_port **p_port ) + unsigned sampling_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_port **p_port ) { pjmedia_port *port; const pj_str_t name = pj_str("null-port"); @@ -49,7 +48,7 @@ PJ_DEF(pj_status_t) pjmedia_null_port_create( pj_pool_t *pool, PJ_ASSERT_RETURN(port != NULL, PJ_ENOMEM); pjmedia_port_info_init(&port->info, &name, SIGNATURE, sampling_rate, - channel_count, bits_per_sample, samples_per_frame); + channel_count, bits_per_sample, samples_per_frame); port->get_frame = &null_get_frame; port->put_frame = &null_put_frame; @@ -67,7 +66,7 @@ PJ_DEF(pj_status_t) pjmedia_null_port_create( pj_pool_t *pool, * Put frame to file. */ static pj_status_t null_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { PJ_UNUSED_ARG(this_port); PJ_UNUSED_ARG(frame); @@ -79,13 +78,13 @@ static pj_status_t null_put_frame(pjmedia_port *this_port, * Get frame from file. */ static pj_status_t null_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { frame->type = PJMEDIA_FRAME_TYPE_AUDIO; frame->size = PJMEDIA_PIA_AVG_FSZ(&this_port->info); frame->timestamp.u32.lo += PJMEDIA_PIA_SPF(&this_port->info); pjmedia_zero_samples((pj_int16_t*)frame->buf, - PJMEDIA_PIA_SPF(&this_port->info)); + PJMEDIA_PIA_SPF(&this_port->info)); return PJ_SUCCESS; } diff --git a/pjmedia/src/pjmedia/plc_common.c b/pjmedia/src/pjmedia/plc_common.c index 18ffd3c596..a1dc683140 100644 --- a/pjmedia/src/pjmedia/plc_common.c +++ b/pjmedia/src/pjmedia/plc_common.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -50,7 +49,7 @@ static struct plc_alg plc_wsola = struct pjmedia_plc { - void *obj; + void *obj; struct plc_alg *op; }; @@ -60,15 +59,15 @@ struct pjmedia_plc * use based on the arguments. */ PJ_DEF(pj_status_t) pjmedia_plc_create( pj_pool_t *pool, - unsigned clock_rate, - unsigned samples_per_frame, - unsigned options, - pjmedia_plc **p_plc) + unsigned clock_rate, + unsigned samples_per_frame, + unsigned options, + pjmedia_plc **p_plc) { pjmedia_plc *plc; PJ_ASSERT_RETURN(pool && clock_rate && samples_per_frame && p_plc, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(options == 0, PJ_EINVAL); PJ_UNUSED_ARG(options); @@ -88,7 +87,7 @@ PJ_DEF(pj_status_t) pjmedia_plc_create( pj_pool_t *pool, * Save a good frame to PLC. */ PJ_DEF(pj_status_t) pjmedia_plc_save( pjmedia_plc *plc, - pj_int16_t *frame ) + pj_int16_t *frame ) { PJ_ASSERT_RETURN(plc && frame, PJ_EINVAL); @@ -101,7 +100,7 @@ PJ_DEF(pj_status_t) pjmedia_plc_save( pjmedia_plc *plc, * Generate a replacement for lost frame. */ PJ_DEF(pj_status_t) pjmedia_plc_generate( pjmedia_plc *plc, - pj_int16_t *frame ) + pj_int16_t *frame ) { PJ_ASSERT_RETURN(plc && frame, PJ_EINVAL); @@ -117,12 +116,12 @@ PJ_DEF(pj_status_t) pjmedia_plc_generate( pjmedia_plc *plc, struct wsola_plc { pjmedia_wsola *wsola; - pj_bool_t prev_lost; + pj_bool_t prev_lost; }; static void* plc_wsola_create(pj_pool_t *pool, unsigned clock_rate, - unsigned samples_per_frame) + unsigned samples_per_frame) { struct wsola_plc *o; unsigned flag; @@ -135,12 +134,12 @@ static void* plc_wsola_create(pj_pool_t *pool, unsigned clock_rate, flag = PJMEDIA_WSOLA_NO_DISCARD; if (PJMEDIA_WSOLA_PLC_NO_FADING) - flag |= PJMEDIA_WSOLA_NO_FADING; + flag |= PJMEDIA_WSOLA_NO_FADING; status = pjmedia_wsola_create(pool, clock_rate, samples_per_frame, 1, - flag, &o->wsola); + flag, &o->wsola); if (status != PJ_SUCCESS) - return NULL; + return NULL; return o; } diff --git a/pjmedia/src/pjmedia/port.c b/pjmedia/src/pjmedia/port.c index 0ed1d2986f..605e060bbc 100644 --- a/pjmedia/src/pjmedia/port.c +++ b/pjmedia/src/pjmedia/port.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -23,7 +22,7 @@ #include #include -#define THIS_FILE "port.c" +#define THIS_FILE "port.c" /** @@ -31,12 +30,12 @@ * ports which deal with PCM audio. */ PJ_DEF(pj_status_t) pjmedia_port_info_init( pjmedia_port_info *info, - const pj_str_t *name, - unsigned signature, - unsigned clock_rate, - unsigned channel_count, - unsigned bits_per_sample, - unsigned samples_per_frame) + const pj_str_t *name, + unsigned signature, + unsigned clock_rate, + unsigned channel_count, + unsigned bits_per_sample, + unsigned samples_per_frame) { #define USEC_IN_SEC (pj_uint64_t)1000000 unsigned frame_time_usec, avg_bps; @@ -50,21 +49,21 @@ PJ_DEF(pj_status_t) pjmedia_port_info_init( pjmedia_port_info *info, info->name = *name; frame_time_usec = (unsigned)(samples_per_frame * USEC_IN_SEC / - channel_count / clock_rate); + channel_count / clock_rate); avg_bps = clock_rate * channel_count * bits_per_sample; pjmedia_format_init_audio(&info->fmt, PJMEDIA_FORMAT_L16, clock_rate, - channel_count, bits_per_sample, frame_time_usec, - avg_bps, avg_bps); + channel_count, bits_per_sample, frame_time_usec, + avg_bps, avg_bps); return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_port_info_init2( pjmedia_port_info *info, - const pj_str_t *name, - unsigned signature, - pjmedia_dir dir, - const pjmedia_format *fmt) + const pj_str_t *name, + unsigned signature, + pjmedia_dir dir, + const pjmedia_format *fmt) { pj_bzero(info, sizeof(*info)); info->signature = signature; @@ -83,24 +82,24 @@ PJ_DEF(pjmedia_clock_src *) pjmedia_port_get_clock_src( pjmedia_port *port, pjmedia_dir dir ) { if (port && port->get_clock_src) - return port->get_clock_src(port, dir); + return port->get_clock_src(port, dir); else - return NULL; + return NULL; } /** * Get a frame from the port (and subsequent downstream ports). */ PJ_DEF(pj_status_t) pjmedia_port_get_frame( pjmedia_port *port, - pjmedia_frame *frame ) + pjmedia_frame *frame ) { PJ_ASSERT_RETURN(port && frame, PJ_EINVAL); if (port->get_frame) - return port->get_frame(port, frame); + return port->get_frame(port, frame); else { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_EINVALIDOP; + frame->type = PJMEDIA_FRAME_TYPE_NONE; + return PJ_EINVALIDOP; } } @@ -109,14 +108,14 @@ PJ_DEF(pj_status_t) pjmedia_port_get_frame( pjmedia_port *port, * Put a frame to the port (and subsequent downstream ports). */ PJ_DEF(pj_status_t) pjmedia_port_put_frame( pjmedia_port *port, - pjmedia_frame *frame ) + pjmedia_frame *frame ) { PJ_ASSERT_RETURN(port && frame, PJ_EINVAL); if (port->put_frame) - return port->put_frame(port, frame); + return port->put_frame(port, frame); else - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; } /** @@ -127,12 +126,12 @@ PJ_DEF(pj_status_t) pjmedia_port_destroy( pjmedia_port *port ) PJ_ASSERT_RETURN(port, PJ_EINVAL); if (port->grp_lock) { - pjmedia_port_dec_ref(port); - return PJ_SUCCESS; + pjmedia_port_dec_ref(port); + return PJ_SUCCESS; } if (port->on_destroy) { - return port->on_destroy(port); + return port->on_destroy(port); } return PJ_SUCCESS; @@ -144,7 +143,7 @@ static void port_on_destroy(void *arg) { pjmedia_port *port = (pjmedia_port*)arg; if (port->on_destroy) - port->on_destroy(port); + port->on_destroy(port); } @@ -152,8 +151,8 @@ static void port_on_destroy(void *arg) * Create and init group lock. */ PJ_DEF(pj_status_t) pjmedia_port_init_grp_lock( pjmedia_port *port, - pj_pool_t *pool, - pj_grp_lock_t *glock ) + pj_pool_t *pool, + pj_grp_lock_t *glock ) { pj_grp_lock_t *grp_lock = glock; pj_status_t status; @@ -166,33 +165,33 @@ PJ_DEF(pj_status_t) pjmedia_port_init_grp_lock( pjmedia_port *port, * If the port doesn't have one, we'd expect a possible premature destroy! */ if (port->on_destroy == NULL) { - PJ_LOG(3,(THIS_FILE, "Media port %s is using group lock but does not " - "implement on_destroy()!", - port->info.name.ptr)); - pj_assert(!"Port using group lock should implement on_destroy()!"); - return PJ_EINVALIDOP; + PJ_LOG(3,(THIS_FILE, "Media port %s is using group lock but does not " + "implement on_destroy()!", + port->info.name.ptr)); + pj_assert(!"Port using group lock should implement on_destroy()!"); + return PJ_EINVALIDOP; } if (!grp_lock) { - /* Create if not supplied */ - status = pj_grp_lock_create_w_handler(pool, NULL, port, - &port_on_destroy, - &grp_lock); + /* Create if not supplied */ + status = pj_grp_lock_create_w_handler(pool, NULL, port, + &port_on_destroy, + &grp_lock); } else { - /* Just add handler, and use internal group lock pool */ - status = pj_grp_lock_add_handler(grp_lock, NULL, port, - &port_on_destroy); + /* Just add handler, and use internal group lock pool */ + status = pj_grp_lock_add_handler(grp_lock, NULL, port, + &port_on_destroy); } if (status == PJ_SUCCESS) { - status = pj_grp_lock_add_ref(grp_lock); + status = pj_grp_lock_add_ref(grp_lock); } if (status == PJ_SUCCESS) { - port->grp_lock = grp_lock; + port->grp_lock = grp_lock; } else if (grp_lock && !glock) { - /* Something wrong, destroy group lock if it is created here */ - pj_grp_lock_destroy(grp_lock); + /* Something wrong, destroy group lock if it is created here */ + pj_grp_lock_destroy(grp_lock); } return status; diff --git a/pjmedia/src/pjmedia/resample_libsamplerate.c b/pjmedia/src/pjmedia/resample_libsamplerate.c index fdcb603941..a2abf32ffd 100644 --- a/pjmedia/src/pjmedia/resample_libsamplerate.c +++ b/pjmedia/src/pjmedia/resample_libsamplerate.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,56 +38,56 @@ #if defined(_MSC_VER) # ifdef _DEBUG -# pragma comment( lib, "../../third_party/lib/libsamplerate-i386-win32-vc-debug.lib") +# pragma comment( lib, "../../third_party/lib/libsamplerate-i386-win32-vc-debug.lib") # else -# pragma comment( lib, "../../third_party/lib/libsamplerate-i386-win32-vc-release.lib") +# pragma comment( lib, "../../third_party/lib/libsamplerate-i386-win32-vc-release.lib") # endif #endif struct pjmedia_resample { - SRC_STATE *state; - unsigned in_samples; - unsigned out_samples; - float *frame_in, *frame_out; - unsigned in_extra, out_extra; - double ratio; + SRC_STATE *state; + unsigned in_samples; + unsigned out_samples; + float *frame_in, *frame_out; + unsigned in_extra, out_extra; + double ratio; }; PJ_DEF(pj_status_t) pjmedia_resample_create( pj_pool_t *pool, - pj_bool_t high_quality, - pj_bool_t large_filter, - unsigned channel_count, - unsigned rate_in, - unsigned rate_out, - unsigned samples_per_frame, - pjmedia_resample **p_resample) + pj_bool_t high_quality, + pj_bool_t large_filter, + unsigned channel_count, + unsigned rate_in, + unsigned rate_out, + unsigned samples_per_frame, + pjmedia_resample **p_resample) { pjmedia_resample *resample; int type, err, i=0; enum { MAX_KICKOFF = 10 }; PJ_ASSERT_RETURN(pool && p_resample && rate_in && - rate_out && samples_per_frame, PJ_EINVAL); + rate_out && samples_per_frame, PJ_EINVAL); resample = PJ_POOL_ZALLOC_T(pool, pjmedia_resample); PJ_ASSERT_RETURN(resample, PJ_ENOMEM); /* Select conversion type */ if (high_quality) { - type = large_filter ? SRC_SINC_BEST_QUALITY : SRC_SINC_MEDIUM_QUALITY; + type = large_filter ? SRC_SINC_BEST_QUALITY : SRC_SINC_MEDIUM_QUALITY; } else { - type = large_filter ? SRC_SINC_FASTEST : SRC_LINEAR; + type = large_filter ? SRC_SINC_FASTEST : SRC_LINEAR; } /* Create converter */ resample->state = src_new(type, channel_count, &err); if (resample->state == NULL) { - PJ_LOG(4,(THIS_FILE, "Error creating resample: %s", - src_strerror(err))); - return PJMEDIA_ERROR; + PJ_LOG(4,(THIS_FILE, "Error creating resample: %s", + src_strerror(err))); + return PJMEDIA_ERROR; } /* Calculate ratio */ @@ -99,21 +98,21 @@ PJ_DEF(pj_status_t) pjmedia_resample_create( pj_pool_t *pool, resample->out_samples = rate_out / (rate_in / samples_per_frame); resample->frame_in = (float*) - pj_pool_calloc(pool, - resample->in_samples + 8, - sizeof(float)); + pj_pool_calloc(pool, + resample->in_samples + 8, + sizeof(float)); resample->frame_out = (float*) - pj_pool_calloc(pool, - resample->out_samples + 8, - sizeof(float)); + pj_pool_calloc(pool, + resample->out_samples + 8, + sizeof(float)); /* Set the converter ratio */ err = src_set_ratio(resample->state, resample->ratio); if (err != 0) { - PJ_LOG(4,(THIS_FILE, "Error creating resample: %s", - src_strerror(err))); - return PJMEDIA_ERROR; + PJ_LOG(4,(THIS_FILE, "Error creating resample: %s", + src_strerror(err))); + return PJMEDIA_ERROR; } /* Kick off. Some initial processes may return samples less than @@ -123,31 +122,31 @@ PJ_DEF(pj_status_t) pjmedia_resample_create( pj_pool_t *pool, * audio frames, until full frame is returned, to avoid that. */ while (++i <= MAX_KICKOFF) { - SRC_DATA src_data; - pj_bzero(&src_data, sizeof(src_data)); - src_data.data_in = resample->frame_in; - src_data.data_out = resample->frame_out; - src_data.input_frames = resample->in_samples; - src_data.output_frames = resample->out_samples; - src_data.src_ratio = resample->ratio; - src_process(resample->state, &src_data); - if (src_data.output_frames_gen == (int)resample->out_samples) - break; - - PJ_LOG(5,(THIS_FILE, - "Resample kickoff #%d: output_frames_gen=%d (expected=%d)%s", - i, src_data.output_frames_gen, resample->out_samples, - (i==MAX_KICKOFF?", warning: kickoff failed!":""))); + SRC_DATA src_data; + pj_bzero(&src_data, sizeof(src_data)); + src_data.data_in = resample->frame_in; + src_data.data_out = resample->frame_out; + src_data.input_frames = resample->in_samples; + src_data.output_frames = resample->out_samples; + src_data.src_ratio = resample->ratio; + src_process(resample->state, &src_data); + if (src_data.output_frames_gen == (int)resample->out_samples) + break; + + PJ_LOG(5,(THIS_FILE, + "Resample kickoff #%d: output_frames_gen=%d (expected=%d)%s", + i, src_data.output_frames_gen, resample->out_samples, + (i==MAX_KICKOFF?", warning: kickoff failed!":""))); } /* Done */ PJ_LOG(5,(THIS_FILE, - "Resample using libsamplerate %s, type=%s (%s), " - "ch=%d, in/out rate=%d/%d", - src_get_version(), - src_get_name(type), src_get_description(type), - channel_count, rate_in, rate_out)); + "Resample using libsamplerate %s, type=%s (%s), " + "ch=%d, in/out rate=%d/%d", + src_get_version(), + src_get_name(type), src_get_description(type), + channel_count, rate_in, rate_out)); *p_resample = resample; @@ -156,21 +155,21 @@ PJ_DEF(pj_status_t) pjmedia_resample_create( pj_pool_t *pool, PJ_DEF(void) pjmedia_resample_run( pjmedia_resample *resample, - const pj_int16_t *input, - pj_int16_t *output ) + const pj_int16_t *input, + pj_int16_t *output ) { SRC_DATA src_data; /* Convert samples to float */ src_short_to_float_array(input, resample->frame_in, - resample->in_samples); + resample->in_samples); if (resample->in_extra) { - unsigned i; + unsigned i; - for (i=0; iin_extra; ++i) - resample->frame_in[resample->in_samples+i] = - resample->frame_in[resample->in_samples-1]; + for (i=0; iin_extra; ++i) + resample->frame_in[resample->in_samples+i] = + resample->frame_in[resample->in_samples-1]; } /* Prepare SRC_DATA */ @@ -186,22 +185,22 @@ PJ_DEF(void) pjmedia_resample_run( pjmedia_resample *resample, /* Convert output back to short */ src_float_to_short_array(resample->frame_out, output, - src_data.output_frames_gen); + src_data.output_frames_gen); /* Replay last sample if conversion couldn't fill up the whole * frame. This could happen for example with 22050 to 16000 conversion. */ if (src_data.output_frames_gen < (int)resample->out_samples) { - unsigned i; + unsigned i; - if (resample->in_extra < 4) - resample->in_extra++; + if (resample->in_extra < 4) + resample->in_extra++; - for (i=src_data.output_frames_gen; - iout_samples; ++i) - { - output[i] = output[src_data.output_frames_gen-1]; - } + for (i=src_data.output_frames_gen; + iout_samples; ++i) + { + output[i] = output[src_data.output_frames_gen-1]; + } } } @@ -217,10 +216,10 @@ PJ_DEF(void) pjmedia_resample_destroy(pjmedia_resample *resample) { PJ_ASSERT_ON_FAIL(resample, return); if (resample->state) { - src_delete(resample->state); - resample->state = NULL; + src_delete(resample->state); + resample->state = NULL; - PJ_LOG(5,(THIS_FILE, "Resample destroyed")); + PJ_LOG(5,(THIS_FILE, "Resample destroyed")); } } @@ -228,5 +227,5 @@ PJ_DEF(void) pjmedia_resample_destroy(pjmedia_resample *resample) int pjmedia_libsamplerate_excluded; -#endif /* PJMEDIA_RESAMPLE_IMP==PJMEDIA_RESAMPLE_LIBSAMPLERATE */ +#endif /* PJMEDIA_RESAMPLE_IMP==PJMEDIA_RESAMPLE_LIBSAMPLERATE */ diff --git a/pjmedia/src/pjmedia/resample_port.c b/pjmedia/src/pjmedia/resample_port.c index 82211758b8..5de27b208a 100644 --- a/pjmedia/src/pjmedia/resample_port.c +++ b/pjmedia/src/pjmedia/resample_port.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,36 +23,36 @@ #include -#define BYTES_PER_SAMPLE 2 -#define SIGNATURE PJMEDIA_SIG_PORT_RESAMPLE +#define BYTES_PER_SAMPLE 2 +#define SIGNATURE PJMEDIA_SIG_PORT_RESAMPLE struct resample_port { - pjmedia_port base; - pjmedia_port *dn_port; - unsigned options; - pjmedia_resample *resample_get; - pjmedia_resample *resample_put; - pj_int16_t *get_buf; - pj_int16_t *put_buf; + pjmedia_port base; + pjmedia_port *dn_port; + unsigned options; + pjmedia_resample *resample_get; + pjmedia_resample *resample_put; + pj_int16_t *get_buf; + pj_int16_t *put_buf; }; static pj_status_t resample_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t resample_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t resample_destroy(pjmedia_port *this_port); PJ_DEF(pj_status_t) pjmedia_resample_port_create( pj_pool_t *pool, - pjmedia_port *dn_port, - unsigned clock_rate, - unsigned opt, - pjmedia_port **p_port ) + pjmedia_port *dn_port, + unsigned clock_rate, + unsigned opt, + pjmedia_port **p_port ) { const pj_str_t name = pj_str("resample"); struct resample_port *rport; @@ -73,8 +72,8 @@ PJ_DEF(pj_status_t) pjmedia_resample_port_create( pj_pool_t *pool, PJ_ASSERT_RETURN(rport != NULL, PJ_ENOMEM); pjmedia_port_info_init(&rport->base.info, &name, SIGNATURE, clock_rate, - d_afd->channel_count, BYTES_PER_SAMPLE * 8, - clock_rate * d_afd->frame_time_usec / 1000000); + d_afd->channel_count, BYTES_PER_SAMPLE * 8, + clock_rate * d_afd->frame_time_usec / 1000000); rport->dn_port = dn_port; rport->options = opt; @@ -86,35 +85,35 @@ PJ_DEF(pj_status_t) pjmedia_resample_port_create( pj_pool_t *pool, * both functions may run simultaneously. */ rport->get_buf = (pj_int16_t*) - pj_pool_alloc(pool, PJMEDIA_PIA_AVG_FSZ(&dn_port->info)); + pj_pool_alloc(pool, PJMEDIA_PIA_AVG_FSZ(&dn_port->info)); PJ_ASSERT_RETURN(rport->get_buf != NULL, PJ_ENOMEM); rport->put_buf = (pj_int16_t*) - pj_pool_alloc(pool, PJMEDIA_PIA_AVG_FSZ(&dn_port->info)); + pj_pool_alloc(pool, PJMEDIA_PIA_AVG_FSZ(&dn_port->info)); PJ_ASSERT_RETURN(rport->put_buf != NULL, PJ_ENOMEM); /* Create "get_frame" resample */ status = pjmedia_resample_create(pool, - (opt&PJMEDIA_RESAMPLE_USE_LINEAR)==0, - (opt&PJMEDIA_RESAMPLE_USE_SMALL_FILTER)==0, - d_afd->channel_count, - d_afd->clock_rate, - r_afd->clock_rate, - PJMEDIA_PIA_SPF(&dn_port->info), - &rport->resample_get); + (opt&PJMEDIA_RESAMPLE_USE_LINEAR)==0, + (opt&PJMEDIA_RESAMPLE_USE_SMALL_FILTER)==0, + d_afd->channel_count, + d_afd->clock_rate, + r_afd->clock_rate, + PJMEDIA_PIA_SPF(&dn_port->info), + &rport->resample_get); if (status != PJ_SUCCESS) - return status; + return status; /* Create "put_frame" resample */ status = pjmedia_resample_create(pool, - (opt&PJMEDIA_RESAMPLE_USE_LINEAR)==0, - (opt&PJMEDIA_RESAMPLE_USE_SMALL_FILTER)==0, - d_afd->channel_count, - r_afd->clock_rate, - d_afd->clock_rate, - PJMEDIA_PIA_SPF(&rport->base.info), - &rport->resample_put); + (opt&PJMEDIA_RESAMPLE_USE_LINEAR)==0, + (opt&PJMEDIA_RESAMPLE_USE_SMALL_FILTER)==0, + d_afd->channel_count, + r_afd->clock_rate, + d_afd->clock_rate, + PJMEDIA_PIA_SPF(&rport->base.info), + &rport->resample_put); /* Media port interface */ rport->base.get_frame = &resample_get_frame; @@ -131,26 +130,26 @@ PJ_DEF(pj_status_t) pjmedia_resample_port_create( pj_pool_t *pool, static pj_status_t resample_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct resample_port *rport = (struct resample_port*) this_port; pjmedia_frame downstream_frame; /* Return if we don't have downstream port. */ if (rport->dn_port == NULL) { - return PJ_SUCCESS; + return PJ_SUCCESS; } if (frame->type == PJMEDIA_FRAME_TYPE_AUDIO) { - pjmedia_resample_run( rport->resample_put, - (const pj_int16_t*) frame->buf, - rport->put_buf); + pjmedia_resample_run( rport->resample_put, + (const pj_int16_t*) frame->buf, + rport->put_buf); - downstream_frame.buf = rport->put_buf; - downstream_frame.size = PJMEDIA_PIA_AVG_FSZ(&rport->dn_port->info); + downstream_frame.buf = rport->put_buf; + downstream_frame.size = PJMEDIA_PIA_AVG_FSZ(&rport->dn_port->info); } else { - downstream_frame.buf = frame->buf; - downstream_frame.size = frame->size; + downstream_frame.buf = frame->buf; + downstream_frame.size = frame->size; } downstream_frame.type = frame->type; @@ -162,7 +161,7 @@ static pj_status_t resample_put_frame(pjmedia_port *this_port, static pj_status_t resample_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct resample_port *rport = (struct resample_port*) this_port; pjmedia_frame tmp_frame; @@ -170,8 +169,8 @@ static pj_status_t resample_get_frame(pjmedia_port *this_port, /* Return silence if we don't have downstream port */ if (rport->dn_port == NULL) { - pj_bzero(frame->buf, frame->size); - return PJ_SUCCESS; + pj_bzero(frame->buf, frame->size); + return PJ_SUCCESS; } tmp_frame.buf = rport->get_buf; @@ -181,25 +180,25 @@ static pj_status_t resample_get_frame(pjmedia_port *this_port, status = pjmedia_port_get_frame( rport->dn_port, &tmp_frame); if (status != PJ_SUCCESS) - return status; + return status; if (tmp_frame.type != PJMEDIA_FRAME_TYPE_AUDIO) { - frame->type = tmp_frame.type; - frame->timestamp = tmp_frame.timestamp; - /* Copy whatever returned as long as the buffer size is enough */ - frame->size = tmp_frame.size < PJMEDIA_PIA_AVG_FSZ(&rport->base.info) ? - tmp_frame.size : PJMEDIA_PIA_AVG_FSZ(&rport->base.info); - if (tmp_frame.size) { - pjmedia_copy_samples((pj_int16_t*)frame->buf, - (const pj_int16_t*)tmp_frame.buf, - (unsigned)frame->size >> 1); - } - return PJ_SUCCESS; + frame->type = tmp_frame.type; + frame->timestamp = tmp_frame.timestamp; + /* Copy whatever returned as long as the buffer size is enough */ + frame->size = tmp_frame.size < PJMEDIA_PIA_AVG_FSZ(&rport->base.info) ? + tmp_frame.size : PJMEDIA_PIA_AVG_FSZ(&rport->base.info); + if (tmp_frame.size) { + pjmedia_copy_samples((pj_int16_t*)frame->buf, + (const pj_int16_t*)tmp_frame.buf, + (unsigned)frame->size >> 1); + } + return PJ_SUCCESS; } pjmedia_resample_run( rport->resample_get, - (const pj_int16_t*) tmp_frame.buf, - (pj_int16_t*) frame->buf); + (const pj_int16_t*) tmp_frame.buf, + (pj_int16_t*) frame->buf); frame->size = PJMEDIA_PIA_AVG_FSZ(&rport->base.info); frame->type = PJMEDIA_FRAME_TYPE_AUDIO; @@ -213,18 +212,18 @@ static pj_status_t resample_destroy(pjmedia_port *this_port) struct resample_port *rport = (struct resample_port*) this_port; if ((rport->options & PJMEDIA_RESAMPLE_DONT_DESTROY_DN)==0) { - pjmedia_port_destroy(rport->dn_port); - rport->dn_port = NULL; + pjmedia_port_destroy(rport->dn_port); + rport->dn_port = NULL; } if (rport->resample_get) { - pjmedia_resample_destroy(rport->resample_get); - rport->resample_get = NULL; + pjmedia_resample_destroy(rport->resample_get); + rport->resample_get = NULL; } if (rport->resample_put) { - pjmedia_resample_destroy(rport->resample_put); - rport->resample_put = NULL; + pjmedia_resample_destroy(rport->resample_put); + rport->resample_put = NULL; } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia/resample_resample.c b/pjmedia/src/pjmedia/resample_resample.c index 7f1066fd2d..3ed3ed9603 100644 --- a/pjmedia/src/pjmedia/resample_resample.c +++ b/pjmedia/src/pjmedia/resample_resample.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,35 +35,35 @@ struct pjmedia_resample { - double factor; /* Conversion factor = rate_out / rate_in. */ - pj_bool_t large_filter; /* Large filter? */ - pj_bool_t high_quality; /* Not fast? */ - unsigned xoff; /* History and lookahead size, in samples */ - unsigned frame_size; /* Samples per frame. */ - unsigned channel_cnt; /* Channel count. */ + double factor; /* Conversion factor = rate_out / rate_in. */ + pj_bool_t large_filter; /* Large filter? */ + pj_bool_t high_quality; /* Not fast? */ + unsigned xoff; /* History and lookahead size, in samples */ + unsigned frame_size; /* Samples per frame. */ + unsigned channel_cnt; /* Channel count. */ /* Buffer for monochannel */ - pj_int16_t *buffer; /* Input buffer. */ + pj_int16_t *buffer; /* Input buffer. */ /* Buffer for multichannel */ - pj_int16_t **in_buffer; /* Array of input buffer for each channel. */ - pj_int16_t *tmp_buffer; /* Temporary output buffer for processing. */ + pj_int16_t **in_buffer; /* Array of input buffer for each channel. */ + pj_int16_t *tmp_buffer; /* Temporary output buffer for processing. */ }; PJ_DEF(pj_status_t) pjmedia_resample_create( pj_pool_t *pool, - pj_bool_t high_quality, - pj_bool_t large_filter, - unsigned channel_count, - unsigned rate_in, - unsigned rate_out, - unsigned samples_per_frame, - pjmedia_resample **p_resample) + pj_bool_t high_quality, + pj_bool_t large_filter, + unsigned channel_count, + unsigned rate_in, + unsigned rate_out, + unsigned samples_per_frame, + pjmedia_resample **p_resample) { pjmedia_resample *resample; PJ_ASSERT_RETURN(pool && p_resample && rate_in && - rate_out && samples_per_frame, PJ_EINVAL); + rate_out && samples_per_frame, PJ_EINVAL); resample = PJ_POOL_ZALLOC_T(pool, pjmedia_resample); PJ_ASSERT_RETURN(resample, PJ_ENOMEM); @@ -74,9 +73,9 @@ PJ_DEF(pj_status_t) pjmedia_resample_create( pj_pool_t *pool, * to yield the same quality. */ if (rate_out < rate_in) { - //no this is not a good idea. It sounds pretty good with speech, - //but very poor with background noise etc. - //high_quality = 0; + //no this is not a good idea. It sounds pretty good with speech, + //but very poor with background noise etc. + //high_quality = 0; } resample->factor = rate_out * 1.0 / rate_in; @@ -86,63 +85,63 @@ PJ_DEF(pj_status_t) pjmedia_resample_create( pj_pool_t *pool, resample->frame_size = samples_per_frame; if (high_quality) { - /* This is a bug in xoff calculation, thanks Stephane Lussier - * of Macadamian dot com. - * resample->xoff = large_filter ? 32 : 6; - */ - resample->xoff = res_GetXOFF(resample->factor, (char)large_filter); + /* This is a bug in xoff calculation, thanks Stephane Lussier + * of Macadamian dot com. + * resample->xoff = large_filter ? 32 : 6; + */ + resample->xoff = res_GetXOFF(resample->factor, (char)large_filter); } else { - resample->xoff = 1; + resample->xoff = 1; } if (channel_count == 1) { - unsigned size; + unsigned size; - /* Allocate input buffer */ - size = (samples_per_frame + 2*resample->xoff) * sizeof(pj_int16_t); - resample->buffer = (pj_int16_t*) pj_pool_alloc(pool, size); - PJ_ASSERT_RETURN(resample->buffer, PJ_ENOMEM); + /* Allocate input buffer */ + size = (samples_per_frame + 2*resample->xoff) * sizeof(pj_int16_t); + resample->buffer = (pj_int16_t*) pj_pool_alloc(pool, size); + PJ_ASSERT_RETURN(resample->buffer, PJ_ENOMEM); - pjmedia_zero_samples(resample->buffer, resample->xoff*2); + pjmedia_zero_samples(resample->buffer, resample->xoff*2); } else if (channel_count > 1) { - unsigned i, size; - - /* Allocate input buffer table */ - size = channel_count * sizeof(pj_int16_t*); - resample->in_buffer = (pj_int16_t**)pj_pool_alloc(pool, size); - - /* Allocate input buffer */ - size = (samples_per_frame/channel_count + 2*resample->xoff) * - sizeof(pj_int16_t); - for (i = 0; i < channel_count; ++i) { - resample->in_buffer[i] = (pj_int16_t*)pj_pool_alloc(pool, size); - PJ_ASSERT_RETURN(resample->in_buffer, PJ_ENOMEM); - pjmedia_zero_samples(resample->in_buffer[i], resample->xoff*2); - } - - /* Allocate temporary output buffer */ - size = (unsigned) (resample->frame_size * sizeof(pj_int16_t) * - resample->factor / channel_count + 0.5); - resample->tmp_buffer = (pj_int16_t*) pj_pool_alloc(pool, size); - PJ_ASSERT_RETURN(resample->tmp_buffer, PJ_ENOMEM); + unsigned i, size; + + /* Allocate input buffer table */ + size = channel_count * sizeof(pj_int16_t*); + resample->in_buffer = (pj_int16_t**)pj_pool_alloc(pool, size); + + /* Allocate input buffer */ + size = (samples_per_frame/channel_count + 2*resample->xoff) * + sizeof(pj_int16_t); + for (i = 0; i < channel_count; ++i) { + resample->in_buffer[i] = (pj_int16_t*)pj_pool_alloc(pool, size); + PJ_ASSERT_RETURN(resample->in_buffer, PJ_ENOMEM); + pjmedia_zero_samples(resample->in_buffer[i], resample->xoff*2); + } + + /* Allocate temporary output buffer */ + size = (unsigned) (resample->frame_size * sizeof(pj_int16_t) * + resample->factor / channel_count + 0.5); + resample->tmp_buffer = (pj_int16_t*) pj_pool_alloc(pool, size); + PJ_ASSERT_RETURN(resample->tmp_buffer, PJ_ENOMEM); } *p_resample = resample; PJ_LOG(5,(THIS_FILE, "resample created: %s qualiy, %s filter, in/out " - "rate=%d/%d", - (high_quality?"high":"low"), - (large_filter?"large":"small"), - rate_in, rate_out)); + "rate=%d/%d", + (high_quality?"high":"low"), + (large_filter?"large":"small"), + rate_in, rate_out)); return PJ_SUCCESS; } PJ_DEF(void) pjmedia_resample_run( pjmedia_resample *resample, - const pj_int16_t *input, - pj_int16_t *output ) + const pj_int16_t *input, + pj_int16_t *output ) { PJ_ASSERT_ON_FAIL(resample, return); @@ -175,8 +174,8 @@ PJ_DEF(void) pjmedia_resample_run( pjmedia_resample *resample, * | 0000 | 0000 | frame0... | * +------+------+--------------+ * ^ ^ ^ ^ - * 0 xoff 2*xoff size+2*xoff - * + * 0 xoff 2*xoff size+2*xoff + * * (Note again: resample algorithm is called at resample->buffer+xoff) * * At the end of the run, 2*xoff samples from the end of @@ -203,7 +202,7 @@ PJ_DEF(void) pjmedia_resample_run( pjmedia_resample *resample, * | frm0 | frm0 | frame1... | * +------+------+--------------+ * ^ ^ ^ ^ - * 0 xoff 2*xoff size+2*xoff + * 0 xoff 2*xoff size+2*xoff * * As you can see from above diagram, the resampling algorithm is * actually called from the last xoff part of previous frame (frm0). @@ -213,74 +212,74 @@ PJ_DEF(void) pjmedia_resample_run( pjmedia_resample *resample, * */ if (resample->channel_cnt == 1) { - pj_int16_t *dst_buf; - const pj_int16_t *src_buf; - - /* Prepare input frame */ - dst_buf = resample->buffer + resample->xoff*2; - pjmedia_copy_samples(dst_buf, input, resample->frame_size); - - /* Resample */ - if (resample->high_quality) { - res_Resample(resample->buffer + resample->xoff, output, - resample->factor, (pj_uint16_t)resample->frame_size, - (char)resample->large_filter, (char)PJ_TRUE); - } else { - res_SrcLinear(resample->buffer + resample->xoff, output, - resample->factor, (pj_uint16_t)resample->frame_size); - } - - /* Update history */ - dst_buf = resample->buffer; - src_buf = input + resample->frame_size - resample->xoff*2; - pjmedia_copy_samples(dst_buf, src_buf, resample->xoff * 2); + pj_int16_t *dst_buf; + const pj_int16_t *src_buf; + + /* Prepare input frame */ + dst_buf = resample->buffer + resample->xoff*2; + pjmedia_copy_samples(dst_buf, input, resample->frame_size); + + /* Resample */ + if (resample->high_quality) { + res_Resample(resample->buffer + resample->xoff, output, + resample->factor, (pj_uint16_t)resample->frame_size, + (char)resample->large_filter, (char)PJ_TRUE); + } else { + res_SrcLinear(resample->buffer + resample->xoff, output, + resample->factor, (pj_uint16_t)resample->frame_size); + } + + /* Update history */ + dst_buf = resample->buffer; + src_buf = input + resample->frame_size - resample->xoff*2; + pjmedia_copy_samples(dst_buf, src_buf, resample->xoff * 2); } else { /* Multichannel */ - unsigned i, j; - - for (i = 0; i < resample->channel_cnt; ++i) { - pj_int16_t *dst_buf; - const pj_int16_t *src_buf; - unsigned mono_frm_sz_in; - unsigned mono_frm_sz_out; - - mono_frm_sz_in = resample->frame_size / resample->channel_cnt; - mono_frm_sz_out = (unsigned)(mono_frm_sz_in * resample->factor + 0.5); - - /* Deinterleave input */ - dst_buf = resample->in_buffer[i] + resample->xoff*2; - src_buf = input + i; - for (j = 0; j < mono_frm_sz_in; ++j) { - *dst_buf++ = *src_buf; - src_buf += resample->channel_cnt; - } - - /* Resample this channel */ - if (resample->high_quality) { - res_Resample(resample->in_buffer[i] + resample->xoff, - resample->tmp_buffer, resample->factor, - (pj_uint16_t)mono_frm_sz_in, - (char)resample->large_filter, (char)PJ_TRUE); - } else { - res_SrcLinear( resample->in_buffer[i], - resample->tmp_buffer, - resample->factor, - (pj_uint16_t)mono_frm_sz_in); - } - - /* Update history */ - dst_buf = resample->in_buffer[i]; - src_buf = resample->in_buffer[i] + mono_frm_sz_in; - pjmedia_copy_samples(dst_buf, src_buf, resample->xoff * 2); - - /* Reinterleave output */ - dst_buf = output + i; - src_buf = resample->tmp_buffer; - for (j = 0; j < mono_frm_sz_out; ++j) { - *dst_buf = *src_buf++; - dst_buf += resample->channel_cnt; - } - } + unsigned i, j; + + for (i = 0; i < resample->channel_cnt; ++i) { + pj_int16_t *dst_buf; + const pj_int16_t *src_buf; + unsigned mono_frm_sz_in; + unsigned mono_frm_sz_out; + + mono_frm_sz_in = resample->frame_size / resample->channel_cnt; + mono_frm_sz_out = (unsigned)(mono_frm_sz_in * resample->factor + 0.5); + + /* Deinterleave input */ + dst_buf = resample->in_buffer[i] + resample->xoff*2; + src_buf = input + i; + for (j = 0; j < mono_frm_sz_in; ++j) { + *dst_buf++ = *src_buf; + src_buf += resample->channel_cnt; + } + + /* Resample this channel */ + if (resample->high_quality) { + res_Resample(resample->in_buffer[i] + resample->xoff, + resample->tmp_buffer, resample->factor, + (pj_uint16_t)mono_frm_sz_in, + (char)resample->large_filter, (char)PJ_TRUE); + } else { + res_SrcLinear( resample->in_buffer[i], + resample->tmp_buffer, + resample->factor, + (pj_uint16_t)mono_frm_sz_in); + } + + /* Update history */ + dst_buf = resample->in_buffer[i]; + src_buf = resample->in_buffer[i] + mono_frm_sz_in; + pjmedia_copy_samples(dst_buf, src_buf, resample->xoff * 2); + + /* Reinterleave output */ + dst_buf = output + i; + src_buf = resample->tmp_buffer; + for (j = 0; j < mono_frm_sz_out; ++j) { + *dst_buf = *src_buf++; + dst_buf += resample->channel_cnt; + } + } } } @@ -302,13 +301,13 @@ PJ_DEF(void) pjmedia_resample_destroy(pjmedia_resample *resample) * This is the configuration when sample rate conversion is disabled. */ PJ_DEF(pj_status_t) pjmedia_resample_create( pj_pool_t *pool, - pj_bool_t high_quality, - pj_bool_t large_filter, - unsigned channel_count, - unsigned rate_in, - unsigned rate_out, - unsigned samples_per_frame, - pjmedia_resample **p_resample) + pj_bool_t high_quality, + pj_bool_t large_filter, + unsigned channel_count, + unsigned rate_in, + unsigned rate_out, + unsigned samples_per_frame, + pjmedia_resample **p_resample) { PJ_UNUSED_ARG(pool); PJ_UNUSED_ARG(high_quality); @@ -323,8 +322,8 @@ PJ_DEF(pj_status_t) pjmedia_resample_create( pj_pool_t *pool, } PJ_DEF(void) pjmedia_resample_run( pjmedia_resample *resample, - const pj_int16_t *input, - pj_int16_t *output ) + const pj_int16_t *input, + pj_int16_t *output ) { PJ_UNUSED_ARG(resample); PJ_UNUSED_ARG(input); @@ -342,5 +341,5 @@ PJ_DEF(void) pjmedia_resample_destroy(pjmedia_resample *resample) PJ_UNUSED_ARG(resample); } -#endif /* PJMEDIA_RESAMPLE_IMP */ +#endif /* PJMEDIA_RESAMPLE_IMP */ diff --git a/pjmedia/src/pjmedia/resample_speex.c b/pjmedia/src/pjmedia/resample_speex.c index 0721c8f19a..cac57ba27c 100644 --- a/pjmedia/src/pjmedia/resample_speex.c +++ b/pjmedia/src/pjmedia/resample_speex.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -33,37 +32,37 @@ struct pjmedia_resample { SpeexResamplerState *state; - unsigned in_samples_per_frame; - unsigned out_samples_per_frame; + unsigned in_samples_per_frame; + unsigned out_samples_per_frame; }; PJ_DEF(pj_status_t) pjmedia_resample_create( pj_pool_t *pool, - pj_bool_t high_quality, - pj_bool_t large_filter, - unsigned channel_count, - unsigned rate_in, - unsigned rate_out, - unsigned samples_per_frame, - pjmedia_resample **p_resample) + pj_bool_t high_quality, + pj_bool_t large_filter, + unsigned channel_count, + unsigned rate_in, + unsigned rate_out, + unsigned samples_per_frame, + pjmedia_resample **p_resample) { pjmedia_resample *resample; int quality; int err; PJ_ASSERT_RETURN(pool && p_resample && rate_in && - rate_out && samples_per_frame, PJ_EINVAL); + rate_out && samples_per_frame, PJ_EINVAL); resample = PJ_POOL_ZALLOC_T(pool, pjmedia_resample); PJ_ASSERT_RETURN(resample, PJ_ENOMEM); if (high_quality) { - if (large_filter) - quality = 10; - else - quality = 7; + if (large_filter) + quality = 10; + else + quality = 7; } else { - quality = 3; + quality = 3; } resample->in_samples_per_frame = samples_per_frame; @@ -71,21 +70,21 @@ PJ_DEF(pj_status_t) pjmedia_resample_create( pj_pool_t *pool, resample->state = speex_resampler_init(channel_count, rate_in, rate_out, quality, &err); if (resample->state == NULL || err != RESAMPLER_ERR_SUCCESS) - return PJ_ENOMEM; + return PJ_ENOMEM; *p_resample = resample; PJ_LOG(5,(THIS_FILE, - "resample created: quality=%d, ch=%d, in/out rate=%d/%d", - quality, channel_count, rate_in, rate_out)); + "resample created: quality=%d, ch=%d, in/out rate=%d/%d", + quality, channel_count, rate_in, rate_out)); return PJ_SUCCESS; } PJ_DEF(void) pjmedia_resample_run( pjmedia_resample *resample, - const pj_int16_t *input, - pj_int16_t *output ) + const pj_int16_t *input, + pj_int16_t *output ) { spx_uint32_t in_length, out_length; @@ -95,9 +94,9 @@ PJ_DEF(void) pjmedia_resample_run( pjmedia_resample *resample, out_length = resample->out_samples_per_frame; speex_resampler_process_interleaved_int(resample->state, - (const spx_int16_t *)input, - &in_length, (spx_int16_t *)output, - &out_length); + (const spx_int16_t *)input, + &in_length, (spx_int16_t *)output, + &out_length); pj_assert(in_length == resample->in_samples_per_frame); pj_assert(out_length == resample->out_samples_per_frame); @@ -115,8 +114,8 @@ PJ_DEF(void) pjmedia_resample_destroy(pjmedia_resample *resample) { PJ_ASSERT_ON_FAIL(resample, return); if (resample->state) { - speex_resampler_destroy(resample->state); - resample->state = NULL; + speex_resampler_destroy(resample->state); + resample->state = NULL; } } @@ -124,5 +123,5 @@ PJ_DEF(void) pjmedia_resample_destroy(pjmedia_resample *resample) int pjmedia_resample_speex_excluded; -#endif /* PJMEDIA_RESAMPLE_IMP==PJMEDIA_RESAMPLE_SPEEX */ +#endif /* PJMEDIA_RESAMPLE_IMP==PJMEDIA_RESAMPLE_SPEEX */ diff --git a/pjmedia/src/pjmedia/rtcp.c b/pjmedia/src/pjmedia/rtcp.c index cc949a127b..449d7dd842 100644 --- a/pjmedia/src/pjmedia/rtcp.c +++ b/pjmedia/src/pjmedia/rtcp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,8 +35,8 @@ #define RTCP_XR 207 /* RTCP Feedbacks */ -#define RTCP_RTPFB 205 -#define RTCP_PSFB 206 +#define RTCP_RTPFB 205 +#define RTCP_PSFB 206 enum { RTCP_SDES_NULL = 0, @@ -57,9 +56,9 @@ enum { #if 0 -# define TRACE_(x) PJ_LOG(3,x) +# define TRACE_(x) PJ_LOG(3,x) #else -# define TRACE_(x) ; +# define TRACE_(x) ; #endif @@ -67,7 +66,7 @@ enum { * Get NTP time. */ PJ_DEF(pj_status_t) pjmedia_rtcp_get_ntp_time(const pjmedia_rtcp_session *sess, - pjmedia_rtcp_ntp_rec *ntp) + pjmedia_rtcp_ntp_rec *ntp) { /* Seconds between 1900-01-01 to 1970-01-01 */ #define JAN_1970 (2208988800UL) @@ -78,7 +77,7 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_get_ntp_time(const pjmedia_rtcp_session *sess, /* Fill up the high 32bit part */ ntp->hi = (pj_uint32_t)((ts.u64 - sess->ts_base.u64) / sess->ts_freq.u64) - + sess->tv_base.sec + JAN_1970; + + sess->tv_base.sec + JAN_1970; /* Calculate seconds fractions */ ts.u64 = (ts.u64 - sess->ts_base.u64) % sess->ts_freq.u64; @@ -99,44 +98,44 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_get_ntp_time(const pjmedia_rtcp_session *sess, * http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q274323 */ { - /* - * Compare elapsed time reported by timestamp with actual elapsed - * time. If the difference is too excessive, then we use system - * time instead. - */ + /* + * Compare elapsed time reported by timestamp with actual elapsed + * time. If the difference is too excessive, then we use system + * time instead. + */ - /* MIN_DIFF needs to be large enough so that "normal" diff caused - * by system activity or context switch doesn't trigger the time - * correction. - */ - enum { MIN_DIFF = 400 }; + /* MIN_DIFF needs to be large enough so that "normal" diff caused + * by system activity or context switch doesn't trigger the time + * correction. + */ + enum { MIN_DIFF = 400 }; - pj_time_val ts_time, elapsed, diff; + pj_time_val ts_time, elapsed, diff; - pj_gettimeofday(&elapsed); + pj_gettimeofday(&elapsed); - ts_time.sec = ntp->hi - sess->tv_base.sec - JAN_1970; - ts_time.msec = (long)(ntp->lo * 1000.0 / 0xFFFFFFFF); + ts_time.sec = ntp->hi - sess->tv_base.sec - JAN_1970; + ts_time.msec = (long)(ntp->lo * 1000.0 / 0xFFFFFFFF); - PJ_TIME_VAL_SUB(elapsed, sess->tv_base); + PJ_TIME_VAL_SUB(elapsed, sess->tv_base); - if (PJ_TIME_VAL_LT(ts_time, elapsed)) { - diff = elapsed; - PJ_TIME_VAL_SUB(diff, ts_time); - } else { - diff = ts_time; - PJ_TIME_VAL_SUB(diff, elapsed); - } + if (PJ_TIME_VAL_LT(ts_time, elapsed)) { + diff = elapsed; + PJ_TIME_VAL_SUB(diff, ts_time); + } else { + diff = ts_time; + PJ_TIME_VAL_SUB(diff, elapsed); + } - if (PJ_TIME_VAL_MSEC(diff) >= MIN_DIFF) { + if (PJ_TIME_VAL_MSEC(diff) >= MIN_DIFF) { - TRACE_((sess->name, "RTCP NTP timestamp corrected by %d ms", - PJ_TIME_VAL_MSEC(diff))); + TRACE_((sess->name, "RTCP NTP timestamp corrected by %d ms", + PJ_TIME_VAL_MSEC(diff))); - ntp->hi = elapsed.sec + sess->tv_base.sec + JAN_1970; - ntp->lo = (elapsed.msec * 65536 / 1000) << 16; - } + ntp->hi = elapsed.sec + sess->tv_base.sec + JAN_1970; + ntp->lo = (elapsed.msec * 65536 / 1000) << 16; + } } #endif @@ -149,7 +148,7 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_get_ntp_time(const pjmedia_rtcp_session *sess, * Initialize RTCP session setting. */ PJ_DEF(void) pjmedia_rtcp_session_setting_default( - pjmedia_rtcp_session_setting *settings) + pjmedia_rtcp_session_setting *settings) { pj_bzero(settings, sizeof(*settings)); } @@ -190,10 +189,10 @@ PJ_DEF(void) pjmedia_rtcp_init_stat(pjmedia_rtcp_stat *stat) * Initialize RTCP session. */ PJ_DEF(void) pjmedia_rtcp_init(pjmedia_rtcp_session *sess, - char *name, - unsigned clock_rate, - unsigned samples_per_frame, - pj_uint32_t ssrc) + char *name, + unsigned clock_rate, + unsigned samples_per_frame, + pj_uint32_t ssrc) { pjmedia_rtcp_session_setting settings; @@ -211,7 +210,7 @@ PJ_DEF(void) pjmedia_rtcp_init(pjmedia_rtcp_session *sess, * Initialize RTCP session. */ PJ_DEF(void) pjmedia_rtcp_init2( pjmedia_rtcp_session *sess, - const pjmedia_rtcp_session_setting *settings) + const pjmedia_rtcp_session_setting *settings) { pjmedia_rtcp_sr_pkt *sr_pkt = &sess->rtcp_sr_pkt; pj_time_val now; @@ -238,13 +237,13 @@ PJ_DEF(void) pjmedia_rtcp_init2( pjmedia_rtcp_session *sess, /* Copy to RTCP RR header */ pj_memcpy(&sess->rtcp_rr_pkt.common, &sr_pkt->common, - sizeof(pjmedia_rtcp_common)); + sizeof(pjmedia_rtcp_common)); sess->rtcp_rr_pkt.common.pt = RTCP_RR; sess->rtcp_rr_pkt.common.length = pj_htons(7); /* Copy to RTCP FB common header */ pj_memcpy(&sess->rtcp_fb_com, &sr_pkt->common, - sizeof(pjmedia_rtcp_common)); + sizeof(pjmedia_rtcp_common)); sess->rtcp_fb_com.ssrc_src = 0; /* Get time and timestamp base and frequency */ @@ -281,18 +280,18 @@ static void rtcp_init_seq(pjmedia_rtcp_session *sess) } PJ_DEF(void) pjmedia_rtcp_rx_rtp( pjmedia_rtcp_session *sess, - unsigned seq, - unsigned rtp_ts, - unsigned payload) + unsigned seq, + unsigned rtp_ts, + unsigned payload) { pjmedia_rtcp_rx_rtp2(sess, seq, rtp_ts, payload, PJ_FALSE); } PJ_DEF(void) pjmedia_rtcp_rx_rtp2(pjmedia_rtcp_session *sess, - unsigned seq, - unsigned rtp_ts, - unsigned payload, - pj_bool_t discarded) + unsigned seq, + unsigned rtp_ts, + unsigned payload, + pj_bool_t discarded) { pj_timestamp ts; pj_uint32_t arrival; @@ -304,8 +303,8 @@ PJ_DEF(void) pjmedia_rtcp_rx_rtp2(pjmedia_rtcp_session *sess, #endif if (sess->stat.rx.pkt == 0) { - /* Init sequence for the first time. */ - pjmedia_rtp_seq_init(&sess->seq_ctrl, (pj_uint16_t)seq); + /* Init sequence for the first time. */ + pjmedia_rtp_seq_init(&sess->seq_ctrl, (pj_uint16_t)seq); } sess->stat.rx.pkt++; @@ -315,33 +314,33 @@ PJ_DEF(void) pjmedia_rtcp_rx_rtp2(pjmedia_rtcp_session *sess, pjmedia_rtp_seq_update(&sess->seq_ctrl, (pj_uint16_t)seq, &seq_st); if (seq_st.status.flag.restart) { - rtcp_init_seq(sess); + rtcp_init_seq(sess); } if (seq_st.status.flag.dup) { - sess->stat.rx.dup++; - TRACE_((sess->name, "Duplicate packet detected")); + sess->stat.rx.dup++; + TRACE_((sess->name, "Duplicate packet detected")); } if (seq_st.status.flag.outorder && !seq_st.status.flag.probation) { - sess->stat.rx.reorder++; - TRACE_((sess->name, "Out-of-order packet detected")); + sess->stat.rx.reorder++; + TRACE_((sess->name, "Out-of-order packet detected")); } if (seq_st.status.flag.bad) { - sess->stat.rx.discard++; + sess->stat.rx.discard++; #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) - pjmedia_rtcp_xr_rx_rtp(&sess->xr_session, seq, - -1, /* lost */ - (seq_st.status.flag.dup? 1:0), /* dup */ - (!seq_st.status.flag.dup? 1:-1), /* discard */ - -1, /* jitter */ - -1, 0); /* toh */ + pjmedia_rtcp_xr_rx_rtp(&sess->xr_session, seq, + -1, /* lost */ + (seq_st.status.flag.dup? 1:0), /* dup */ + (!seq_st.status.flag.dup? 1:-1), /* discard */ + -1, /* jitter */ + -1, 0); /* toh */ #endif - TRACE_((sess->name, "Bad packet discarded")); - return; + TRACE_((sess->name, "Bad packet discarded")); + return; } /* Only mark "good" packets */ @@ -349,21 +348,21 @@ PJ_DEF(void) pjmedia_rtcp_rx_rtp2(pjmedia_rtcp_session *sess, /* Calculate loss periods. */ if (seq_st.diff > 1) { - unsigned count = seq_st.diff - 1; - unsigned period; + unsigned count = seq_st.diff - 1; + unsigned period; - period = count * sess->pkt_size * 1000 / sess->clock_rate; - period *= 1000; + period = count * sess->pkt_size * 1000 / sess->clock_rate; + period *= 1000; - /* Update packet lost. - * The packet lost number will also be updated when we're sending - * outbound RTCP RR. - */ - sess->stat.rx.loss += (seq_st.diff - 1); - TRACE_((sess->name, "%d packet(s) lost", seq_st.diff - 1)); + /* Update packet lost. + * The packet lost number will also be updated when we're sending + * outbound RTCP RR. + */ + sess->stat.rx.loss += (seq_st.diff - 1); + TRACE_((sess->name, "%d packet(s) lost", seq_st.diff - 1)); - /* Update loss period stat */ - pj_math_stat_update(&sess->stat.rx.loss_period, period); + /* Update loss period stat */ + pj_math_stat_update(&sess->stat.rx.loss_period, period); } @@ -373,113 +372,113 @@ PJ_DEF(void) pjmedia_rtcp_rx_rtp2(pjmedia_rtcp_session *sess, * (see RTP FAQ). */ if (seq_st.diff == 1 && rtp_ts != sess->rtp_last_ts) { - /* Get arrival time and convert timestamp to samples */ - pj_get_timestamp(&ts); - ts.u64 = ts.u64 * sess->clock_rate / sess->ts_freq.u64; - arrival = ts.u32.lo; + /* Get arrival time and convert timestamp to samples */ + pj_get_timestamp(&ts); + ts.u64 = ts.u64 * sess->clock_rate / sess->ts_freq.u64; + arrival = ts.u32.lo; - transit = arrival - rtp_ts; + transit = arrival - rtp_ts; - /* Ignore the first N packets as they normally have bad jitter - * due to other threads working to establish the call - */ - if (sess->transit == 0 || - sess->received < PJMEDIA_RTCP_IGNORE_FIRST_PACKETS) - { - sess->transit = transit; - sess->stat.rx.jitter.min = (unsigned)-1; - } else { - pj_int32_t d; - pj_uint32_t jitter; - - d = transit - sess->transit; - if (d < 0) - d = -d; - - sess->jitter += d - ((sess->jitter + 8) >> 4); - - /* Update jitter stat */ - jitter = sess->jitter >> 4; - - /* Convert jitter unit from samples to usec */ - if (jitter < 4294) - jitter = jitter * 1000000 / sess->clock_rate; - else { - jitter = jitter * 1000 / sess->clock_rate; - jitter *= 1000; - } - pj_math_stat_update(&sess->stat.rx.jitter, jitter); + /* Ignore the first N packets as they normally have bad jitter + * due to other threads working to establish the call + */ + if (sess->transit == 0 || + sess->received < PJMEDIA_RTCP_IGNORE_FIRST_PACKETS) + { + sess->transit = transit; + sess->stat.rx.jitter.min = (unsigned)-1; + } else { + pj_int32_t d; + pj_uint32_t jitter; + + d = transit - sess->transit; + if (d < 0) + d = -d; + + sess->jitter += d - ((sess->jitter + 8) >> 4); + + /* Update jitter stat */ + jitter = sess->jitter >> 4; + + /* Convert jitter unit from samples to usec */ + if (jitter < 4294) + jitter = jitter * 1000000 / sess->clock_rate; + else { + jitter = jitter * 1000 / sess->clock_rate; + jitter *= 1000; + } + pj_math_stat_update(&sess->stat.rx.jitter, jitter); #if defined(PJMEDIA_RTCP_STAT_HAS_RAW_JITTER) && PJMEDIA_RTCP_STAT_HAS_RAW_JITTER!=0 - { - pj_uint32_t raw_jitter; - - /* Convert raw jitter unit from samples to usec */ - if (d < 4294) - raw_jitter = d * 1000000 / sess->clock_rate; - else { - raw_jitter = d * 1000 / sess->clock_rate; - raw_jitter *= 1000; - } - - /* Update jitter stat */ - pj_math_stat_update(&sess->stat.rx_raw_jitter, raw_jitter); - } + { + pj_uint32_t raw_jitter; + + /* Convert raw jitter unit from samples to usec */ + if (d < 4294) + raw_jitter = d * 1000000 / sess->clock_rate; + else { + raw_jitter = d * 1000 / sess->clock_rate; + raw_jitter *= 1000; + } + + /* Update jitter stat */ + pj_math_stat_update(&sess->stat.rx_raw_jitter, raw_jitter); + } #endif #if defined(PJMEDIA_RTCP_STAT_HAS_IPDV) && PJMEDIA_RTCP_STAT_HAS_IPDV!=0 - { - pj_int32_t ipdv; - - ipdv = transit - sess->transit; - /* Convert IPDV unit from samples to usec */ - if (ipdv > -2147 && ipdv < 2147) - ipdv = ipdv * 1000000 / (int)sess->clock_rate; - else { - ipdv = ipdv * 1000 / (int)sess->clock_rate; - ipdv *= 1000; - } - - /* Update jitter stat */ - pj_math_stat_update(&sess->stat.rx_ipdv, ipdv); - } + { + pj_int32_t ipdv; + + ipdv = transit - sess->transit; + /* Convert IPDV unit from samples to usec */ + if (ipdv > -2147 && ipdv < 2147) + ipdv = ipdv * 1000000 / (int)sess->clock_rate; + else { + ipdv = ipdv * 1000 / (int)sess->clock_rate; + ipdv *= 1000; + } + + /* Update jitter stat */ + pj_math_stat_update(&sess->stat.rx_ipdv, ipdv); + } #endif #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) - pjmedia_rtcp_xr_rx_rtp(&sess->xr_session, seq, - 0, /* lost */ - 0, /* dup */ - discarded, /* discard */ - (sess->jitter >> 4), /* jitter */ - -1, 0); /* toh */ + pjmedia_rtcp_xr_rx_rtp(&sess->xr_session, seq, + 0, /* lost */ + 0, /* dup */ + discarded, /* discard */ + (sess->jitter >> 4), /* jitter */ + -1, 0); /* toh */ #endif - /* Update session transit */ - sess->transit = transit; - } + /* Update session transit */ + sess->transit = transit; + } #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) } else if (seq_st.diff > 1) { - int i; - - /* Report RTCP XR about packet losses */ - for (i=seq_st.diff-1; i>0; --i) { - pjmedia_rtcp_xr_rx_rtp(&sess->xr_session, seq - i, - 1, /* lost */ - 0, /* dup */ - 0, /* discard */ - -1, /* jitter */ - -1, 0); /* toh */ - } - - /* Report RTCP XR this packet */ - pjmedia_rtcp_xr_rx_rtp(&sess->xr_session, seq, - 0, /* lost */ - 0, /* dup */ - discarded, /* discard */ - -1, /* jitter */ - -1, 0); /* toh */ + int i; + + /* Report RTCP XR about packet losses */ + for (i=seq_st.diff-1; i>0; --i) { + pjmedia_rtcp_xr_rx_rtp(&sess->xr_session, seq - i, + 1, /* lost */ + 0, /* dup */ + 0, /* discard */ + -1, /* jitter */ + -1, 0); /* toh */ + } + + /* Report RTCP XR this packet */ + pjmedia_rtcp_xr_rx_rtp(&sess->xr_session, seq, + 0, /* lost */ + 0, /* dup */ + discarded, /* discard */ + -1, /* jitter */ + -1, 0); /* toh */ #endif } @@ -488,7 +487,7 @@ PJ_DEF(void) pjmedia_rtcp_rx_rtp2(pjmedia_rtcp_session *sess, } PJ_DEF(void) pjmedia_rtcp_tx_rtp(pjmedia_rtcp_session *sess, - unsigned bytes_payload_size) + unsigned bytes_payload_size) { /* Update statistics */ sess->stat.tx.pkt++; @@ -497,8 +496,8 @@ PJ_DEF(void) pjmedia_rtcp_tx_rtp(pjmedia_rtcp_session *sess, static void parse_rtcp_report( pjmedia_rtcp_session *sess, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { pjmedia_rtcp_common *common = (pjmedia_rtcp_common*) pkt; const pjmedia_rtcp_rr *rr = NULL; @@ -508,89 +507,89 @@ static void parse_rtcp_report( pjmedia_rtcp_session *sess, /* Parse RTCP */ if (common->pt == RTCP_SR) { if (sizeof (pjmedia_rtcp_common) + sizeof (pjmedia_rtcp_sr) > size) { - TRACE_((sess->name, "Discarding RTCP SR due to truncated size " - "%d bytes", size)); + TRACE_((sess->name, "Discarding RTCP SR due to truncated size " + "%d bytes", size)); return; } - sr = (pjmedia_rtcp_sr*) (((char*)pkt) + sizeof(pjmedia_rtcp_common)); - if (common->count > 0 && size >= (sizeof(pjmedia_rtcp_sr_pkt))) { - rr = (pjmedia_rtcp_rr*)(((char*)pkt) + (sizeof(pjmedia_rtcp_common) - + sizeof(pjmedia_rtcp_sr))); - } + sr = (pjmedia_rtcp_sr*) (((char*)pkt) + sizeof(pjmedia_rtcp_common)); + if (common->count > 0 && size >= (sizeof(pjmedia_rtcp_sr_pkt))) { + rr = (pjmedia_rtcp_rr*)(((char*)pkt) + (sizeof(pjmedia_rtcp_common) + + sizeof(pjmedia_rtcp_sr))); + } } else if (common->pt == RTCP_RR && common->count > 0) { - if (sizeof (pjmedia_rtcp_common) + sizeof (pjmedia_rtcp_rr) > size) { - TRACE_((sess->name, "Discarding RTCP RR due to truncated size " - "%d bytes", size)); - return; - } - rr = (pjmedia_rtcp_rr*)(((char*)pkt) + sizeof(pjmedia_rtcp_common)); + if (sizeof (pjmedia_rtcp_common) + sizeof (pjmedia_rtcp_rr) > size) { + TRACE_((sess->name, "Discarding RTCP RR due to truncated size " + "%d bytes", size)); + return; + } + rr = (pjmedia_rtcp_rr*)(((char*)pkt) + sizeof(pjmedia_rtcp_common)); #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) } else if (common->pt == RTCP_XR) { - if (sess->xr_enabled) - pjmedia_rtcp_xr_rx_rtcp_xr(&sess->xr_session, pkt, size); + if (sess->xr_enabled) + pjmedia_rtcp_xr_rx_rtcp_xr(&sess->xr_session, pkt, size); - return; + return; #endif } if (sr) { - /* Save LSR from NTP timestamp of RTCP packet */ - sess->rx_lsr = ((pj_ntohl(sr->ntp_sec) & 0x0000FFFF) << 16) | - ((pj_ntohl(sr->ntp_frac) >> 16) & 0xFFFF); + /* Save LSR from NTP timestamp of RTCP packet */ + sess->rx_lsr = ((pj_ntohl(sr->ntp_sec) & 0x0000FFFF) << 16) | + ((pj_ntohl(sr->ntp_frac) >> 16) & 0xFFFF); - /* Calculate SR arrival time for DLSR */ - pj_get_timestamp(&sess->rx_lsr_time); + /* Calculate SR arrival time for DLSR */ + pj_get_timestamp(&sess->rx_lsr_time); - TRACE_((sess->name, "Rx RTCP SR: ntp_ts=%p", - sess->rx_lsr, - (pj_uint32_t)(sess->rx_lsr_time.u64*65536/sess->ts_freq.u64))); + TRACE_((sess->name, "Rx RTCP SR: ntp_ts=%p", + sess->rx_lsr, + (pj_uint32_t)(sess->rx_lsr_time.u64*65536/sess->ts_freq.u64))); } /* Nothing more to do if there's no RR packet */ if (rr == NULL) - return; + return; last_loss = sess->stat.tx.loss; /* Get packet loss */ sess->stat.tx.loss = (rr->total_lost_2 << 16) + - (rr->total_lost_1 << 8) + - rr->total_lost_0; + (rr->total_lost_1 << 8) + + rr->total_lost_0; TRACE_((sess->name, "Rx RTCP RR: total_lost_2=%x, 1=%x, 0=%x, lost=%d", - (int)rr->total_lost_2, - (int)rr->total_lost_1, - (int)rr->total_lost_0, - sess->stat.tx.loss)); + (int)rr->total_lost_2, + (int)rr->total_lost_1, + (int)rr->total_lost_0, + sess->stat.tx.loss)); /* We can't calculate the exact loss period for TX, so just give the * best estimation. */ if (sess->stat.tx.loss > last_loss) { - unsigned period; + unsigned period; - /* Loss period in msec */ - period = (sess->stat.tx.loss - last_loss) * sess->pkt_size * - 1000 / sess->clock_rate; + /* Loss period in msec */ + period = (sess->stat.tx.loss - last_loss) * sess->pkt_size * + 1000 / sess->clock_rate; - /* Loss period in usec */ - period *= 1000; + /* Loss period in usec */ + period *= 1000; - /* Update loss period stat */ - pj_math_stat_update(&sess->stat.tx.loss_period, period); + /* Update loss period stat */ + pj_math_stat_update(&sess->stat.tx.loss_period, period); } /* Get jitter value in usec */ jitter_samp = pj_ntohl(rr->jitter); /* Calculate jitter in usec, avoiding overflows */ if (jitter_samp <= 4294) - jitter = jitter_samp * 1000000 / sess->clock_rate; + jitter = jitter_samp * 1000000 / sess->clock_rate; else { - jitter = jitter_samp * 1000 / sess->clock_rate; - jitter *= 1000; + jitter = jitter_samp * 1000 / sess->clock_rate; + jitter *= 1000; } /* Update jitter statistics */ @@ -598,84 +597,84 @@ static void parse_rtcp_report( pjmedia_rtcp_session *sess, /* Can only calculate if LSR and DLSR is present in RR */ if (rr->lsr && rr->dlsr) { - pj_uint32_t lsr, now, dlsr; - pj_uint64_t eedelay; - pjmedia_rtcp_ntp_rec ntp; + pj_uint32_t lsr, now, dlsr; + pj_uint64_t eedelay; + pjmedia_rtcp_ntp_rec ntp; - /* LSR is the middle 32bit of NTP. It has 1/65536 second - * resolution - */ - lsr = pj_ntohl(rr->lsr); + /* LSR is the middle 32bit of NTP. It has 1/65536 second + * resolution + */ + lsr = pj_ntohl(rr->lsr); - /* DLSR is delay since LSR, also in 1/65536 resolution */ - dlsr = pj_ntohl(rr->dlsr); + /* DLSR is delay since LSR, also in 1/65536 resolution */ + dlsr = pj_ntohl(rr->dlsr); - /* Get current time, and convert to 1/65536 resolution */ - pjmedia_rtcp_get_ntp_time(sess, &ntp); - now = ((ntp.hi & 0xFFFF) << 16) + (ntp.lo >> 16); + /* Get current time, and convert to 1/65536 resolution */ + pjmedia_rtcp_get_ntp_time(sess, &ntp); + now = ((ntp.hi & 0xFFFF) << 16) + (ntp.lo >> 16); - /* End-to-end delay is (now-lsr-dlsr) */ - eedelay = now - lsr - dlsr; + /* End-to-end delay is (now-lsr-dlsr) */ + eedelay = now - lsr - dlsr; - /* Convert end to end delay to usec (keeping the calculation in + /* Convert end to end delay to usec (keeping the calculation in * 64bit space):: - * sess->ee_delay = (eedelay * 1000) / 65536; - */ - if (eedelay < 4294) { - eedelay = (eedelay * 1000000) >> 16; - } else { - eedelay = (eedelay * 1000) >> 16; - eedelay *= 1000; - } - - TRACE_((sess->name, "Rx RTCP RR: lsr=%p, dlsr=%p (%d:%03dms), " - "now=%p, rtt=%p", - lsr, dlsr, dlsr/65536, (dlsr%65536)*1000/65536, - now, (pj_uint32_t)eedelay)); - - /* Only save calculation if "now" is greater than lsr, or - * otherwise rtt will be invalid - */ - if (now-dlsr >= lsr) { - unsigned rtt = (pj_uint32_t)eedelay; - - /* Check that eedelay value really makes sense. - * We allow up to 30 seconds RTT! - */ - if (eedelay > 30 * 1000 * 1000UL) { - - TRACE_((sess->name, "RTT not making any sense, ignored..")); - goto end_rtt_calc; - } + * sess->ee_delay = (eedelay * 1000) / 65536; + */ + if (eedelay < 4294) { + eedelay = (eedelay * 1000000) >> 16; + } else { + eedelay = (eedelay * 1000) >> 16; + eedelay *= 1000; + } + + TRACE_((sess->name, "Rx RTCP RR: lsr=%p, dlsr=%p (%d:%03dms), " + "now=%p, rtt=%p", + lsr, dlsr, dlsr/65536, (dlsr%65536)*1000/65536, + now, (pj_uint32_t)eedelay)); + + /* Only save calculation if "now" is greater than lsr, or + * otherwise rtt will be invalid + */ + if (now-dlsr >= lsr) { + unsigned rtt = (pj_uint32_t)eedelay; + + /* Check that eedelay value really makes sense. + * We allow up to 30 seconds RTT! + */ + if (eedelay > 30 * 1000 * 1000UL) { + + TRACE_((sess->name, "RTT not making any sense, ignored..")); + goto end_rtt_calc; + } #if defined(PJMEDIA_RTCP_NORMALIZE_FACTOR) && PJMEDIA_RTCP_NORMALIZE_FACTOR!=0 - /* "Normalize" rtt value that is exceptionally high. For such - * values, "normalize" the rtt to be PJMEDIA_RTCP_NORMALIZE_FACTOR - * times the average value. - */ - if (rtt > ((unsigned)sess->stat.rtt.mean * - PJMEDIA_RTCP_NORMALIZE_FACTOR) && sess->stat.rtt.n!=0) - { - unsigned orig_rtt = rtt; - rtt = sess->stat.rtt.mean * PJMEDIA_RTCP_NORMALIZE_FACTOR; - PJ_LOG(5,(sess->name, - "RTT value %d usec is normalized to %d usec", - orig_rtt, rtt)); - } + /* "Normalize" rtt value that is exceptionally high. For such + * values, "normalize" the rtt to be PJMEDIA_RTCP_NORMALIZE_FACTOR + * times the average value. + */ + if (rtt > ((unsigned)sess->stat.rtt.mean * + PJMEDIA_RTCP_NORMALIZE_FACTOR) && sess->stat.rtt.n!=0) + { + unsigned orig_rtt = rtt; + rtt = sess->stat.rtt.mean * PJMEDIA_RTCP_NORMALIZE_FACTOR; + PJ_LOG(5,(sess->name, + "RTT value %d usec is normalized to %d usec", + orig_rtt, rtt)); + } #endif - TRACE_((sess->name, "RTCP RTT is set to %d usec", rtt)); - - /* Update RTT stat */ - pj_math_stat_update(&sess->stat.rtt, rtt); - - } else { - PJ_LOG(5, (sess->name, "Internal RTCP NTP clock skew detected: " - "lsr=%p, now=%p, dlsr=%p (%d:%03dms), " - "diff=%d", - lsr, now, dlsr, dlsr/65536, - (dlsr%65536)*1000/65536, - dlsr-(now-lsr))); - } + TRACE_((sess->name, "RTCP RTT is set to %d usec", rtt)); + + /* Update RTT stat */ + pj_math_stat_update(&sess->stat.rtt, rtt); + + } else { + PJ_LOG(5, (sess->name, "Internal RTCP NTP clock skew detected: " + "lsr=%p, now=%p, dlsr=%p (%d:%03dms), " + "diff=%d", + lsr, now, dlsr, dlsr/65536, + (dlsr%65536)*1000/65536, + dlsr-(now-lsr))); + } } end_rtt_calc: @@ -686,8 +685,8 @@ static void parse_rtcp_report( pjmedia_rtcp_session *sess, static void parse_rtcp_sdes(pjmedia_rtcp_session *sess, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { pjmedia_rtcp_sdes *sdes = &sess->stat.peer_sdes; char *p, *p_end; @@ -701,100 +700,100 @@ static void parse_rtcp_sdes(pjmedia_rtcp_session *sess, b_end = b + sizeof(sess->stat.peer_sdes_buf_); while (p < p_end) { - pj_uint8_t sdes_type, sdes_len; - pj_str_t sdes_value = {NULL, 0}; - - sdes_type = *p++; - - /* Check for end of SDES item list */ - if (sdes_type == RTCP_SDES_NULL || p == p_end) - break; - - sdes_len = *p++; - - /* Check for corrupted SDES packet */ - if (p + sdes_len > p_end) - break; - - /* Get SDES item */ - if (b + sdes_len < b_end) { - pj_memcpy(b, p, sdes_len); - sdes_value.ptr = b; - sdes_value.slen = sdes_len; - b += sdes_len; - } else { - /* Insufficient SDES buffer */ - PJ_LOG(5, (sess->name, - "Unsufficient buffer to save RTCP SDES type %d:%.*s", - sdes_type, sdes_len, p)); - p += sdes_len; - continue; - } - - switch (sdes_type) { - case RTCP_SDES_CNAME: - sdes->cname = sdes_value; - break; - case RTCP_SDES_NAME: - sdes->name = sdes_value; - break; - case RTCP_SDES_EMAIL: - sdes->email = sdes_value; - break; - case RTCP_SDES_PHONE: - sdes->phone = sdes_value; - break; - case RTCP_SDES_LOC: - sdes->loc = sdes_value; - break; - case RTCP_SDES_TOOL: - sdes->tool = sdes_value; - break; - case RTCP_SDES_NOTE: - sdes->note = sdes_value; - break; - default: - TRACE_((sess->name, "Received unknown RTCP SDES type %d:%.*s", - sdes_type, sdes_value.slen, sdes_value.ptr)); - break; - } - - p += sdes_len; + pj_uint8_t sdes_type, sdes_len; + pj_str_t sdes_value = {NULL, 0}; + + sdes_type = *p++; + + /* Check for end of SDES item list */ + if (sdes_type == RTCP_SDES_NULL || p == p_end) + break; + + sdes_len = *p++; + + /* Check for corrupted SDES packet */ + if (p + sdes_len > p_end) + break; + + /* Get SDES item */ + if (b + sdes_len < b_end) { + pj_memcpy(b, p, sdes_len); + sdes_value.ptr = b; + sdes_value.slen = sdes_len; + b += sdes_len; + } else { + /* Insufficient SDES buffer */ + PJ_LOG(5, (sess->name, + "Unsufficient buffer to save RTCP SDES type %d:%.*s", + sdes_type, sdes_len, p)); + p += sdes_len; + continue; + } + + switch (sdes_type) { + case RTCP_SDES_CNAME: + sdes->cname = sdes_value; + break; + case RTCP_SDES_NAME: + sdes->name = sdes_value; + break; + case RTCP_SDES_EMAIL: + sdes->email = sdes_value; + break; + case RTCP_SDES_PHONE: + sdes->phone = sdes_value; + break; + case RTCP_SDES_LOC: + sdes->loc = sdes_value; + break; + case RTCP_SDES_TOOL: + sdes->tool = sdes_value; + break; + case RTCP_SDES_NOTE: + sdes->note = sdes_value; + break; + default: + TRACE_((sess->name, "Received unknown RTCP SDES type %d:%.*s", + sdes_type, sdes_value.slen, sdes_value.ptr)); + break; + } + + p += sdes_len; } } static void parse_rtcp_bye(pjmedia_rtcp_session *sess, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { pj_str_t reason = {"-", 1}; /* Check and get BYE reason */ if (size > 8) { - /* Make sure the BYE reason does not exceed: - * - the size of the available buffer - * - the declared reason's length - * - the actual packet size - */ - reason.slen = PJ_MIN(sizeof(sess->stat.peer_sdes_buf_), + /* Make sure the BYE reason does not exceed: + * - the size of the available buffer + * - the declared reason's length + * - the actual packet size + */ + reason.slen = PJ_MIN(sizeof(sess->stat.peer_sdes_buf_), *((pj_uint8_t*)pkt+8)); reason.slen = PJ_MIN(reason.slen, (pj_ssize_t)(size-9)); - pj_memcpy(sess->stat.peer_sdes_buf_, ((pj_uint8_t*)pkt+9), - reason.slen); - reason.ptr = sess->stat.peer_sdes_buf_; + pj_memcpy(sess->stat.peer_sdes_buf_, ((pj_uint8_t*)pkt+9), + reason.slen); + reason.ptr = sess->stat.peer_sdes_buf_; } /* Just print RTCP BYE log */ PJ_LOG(5, (sess->name, "Received RTCP BYE, reason: %.*s", - reason.slen, reason.ptr)); + reason.slen, reason.ptr)); } static void parse_rtcp_fb(pjmedia_rtcp_session *sess, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { unsigned cnt = 1; pjmedia_rtcp_fb_nack nack[1]; @@ -806,92 +805,92 @@ static void parse_rtcp_fb(pjmedia_rtcp_session *sess, if (size < sizeof(pjmedia_rtcp_fb_common)) { PJ_PERROR(3, (THIS_FILE, PJ_ETOOSMALL, "Failed parsing RTCP FB, invalid packet length")); - return; + return; } pj_get_timestamp(&ts_now); if (pjmedia_rtcp_fb_parse_nack(pkt, size, &cnt, nack)==PJ_SUCCESS) { - pjmedia_event_init(&ev, PJMEDIA_EVENT_RX_RTCP_FB, &ts_now, sess); - ev.data.rx_rtcp_fb.cap.type = PJMEDIA_RTCP_FB_NACK; - ev.data.rx_rtcp_fb.msg.nack = nack[0]; - pjmedia_event_publish(NULL, sess, &ev, 0); + pjmedia_event_init(&ev, PJMEDIA_EVENT_RX_RTCP_FB, &ts_now, sess); + ev.data.rx_rtcp_fb.cap.type = PJMEDIA_RTCP_FB_NACK; + ev.data.rx_rtcp_fb.msg.nack = nack[0]; + pjmedia_event_publish(NULL, sess, &ev, 0); } else if (pjmedia_rtcp_fb_parse_pli(pkt, size)==PJ_SUCCESS) { - pjmedia_event_init(&ev, PJMEDIA_EVENT_RX_RTCP_FB, &ts_now, sess); - ev.data.rx_rtcp_fb.cap.type = PJMEDIA_RTCP_FB_NACK; - pj_strset2(&ev.data.rx_rtcp_fb.cap.param, (char*)"pli"); - pjmedia_event_publish(NULL, sess, &ev, 0); + pjmedia_event_init(&ev, PJMEDIA_EVENT_RX_RTCP_FB, &ts_now, sess); + ev.data.rx_rtcp_fb.cap.type = PJMEDIA_RTCP_FB_NACK; + pj_strset2(&ev.data.rx_rtcp_fb.cap.param, (char*)"pli"); + pjmedia_event_publish(NULL, sess, &ev, 0); - /* For other FB type implementations later + /* For other FB type implementations later } else if (pjmedia_rtcp_fb_parse_sli(pkt, size, &cnt, sli)==PJ_SUCCESS) { } else if (pjmedia_rtcp_fb_parse_rpsi(pkt, size, &rpsi)==PJ_SUCCESS) { - */ + */ } else { - /* Ignore unknown RTCP Feedback */ - TRACE_((sess->name, "Received unknown RTCP feedback")); + /* Ignore unknown RTCP Feedback */ + TRACE_((sess->name, "Received unknown RTCP feedback")); } } PJ_DEF(void) pjmedia_rtcp_rx_rtcp( pjmedia_rtcp_session *sess, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { pj_uint8_t *p, *p_end; p = (pj_uint8_t*)pkt; p_end = p + size; while (p < p_end) { - pjmedia_rtcp_common *common; - unsigned len; - - if (p + sizeof(pjmedia_rtcp_common) > p_end) { - TRACE_((sess->name, "Receiving truncated RTCP packet (1)")); - break; - } - common = (pjmedia_rtcp_common*)p; - - len = (pj_ntohs((pj_uint16_t)common->length)+1) * 4; - if (p + len > p_end) { - TRACE_((sess->name, "Receiving truncated RTCP packet (2)")); - break; - } - - switch(common->pt) { - case RTCP_SR: - case RTCP_RR: - case RTCP_XR: - parse_rtcp_report(sess, p, len); - break; - case RTCP_SDES: - parse_rtcp_sdes(sess, p, len); - break; - case RTCP_BYE: - parse_rtcp_bye(sess, p, len); - break; - case RTCP_RTPFB: - case RTCP_PSFB: - parse_rtcp_fb(sess, p, len); - break; - default: - /* Ignore unknown RTCP */ - TRACE_((sess->name, "Received unknown RTCP packet type=%d", - common->pt)); - break; - } - - p += len; + pjmedia_rtcp_common *common; + unsigned len; + + if (p + sizeof(pjmedia_rtcp_common) > p_end) { + TRACE_((sess->name, "Receiving truncated RTCP packet (1)")); + break; + } + common = (pjmedia_rtcp_common*)p; + + len = (pj_ntohs((pj_uint16_t)common->length)+1) * 4; + if (p + len > p_end) { + TRACE_((sess->name, "Receiving truncated RTCP packet (2)")); + break; + } + + switch(common->pt) { + case RTCP_SR: + case RTCP_RR: + case RTCP_XR: + parse_rtcp_report(sess, p, len); + break; + case RTCP_SDES: + parse_rtcp_sdes(sess, p, len); + break; + case RTCP_BYE: + parse_rtcp_bye(sess, p, len); + break; + case RTCP_RTPFB: + case RTCP_PSFB: + parse_rtcp_fb(sess, p, len); + break; + default: + /* Ignore unknown RTCP */ + TRACE_((sess->name, "Received unknown RTCP packet type=%d", + common->pt)); + break; + } + + p += len; } } PJ_DEF(void) pjmedia_rtcp_build_rtcp(pjmedia_rtcp_session *sess, - void **ret_p_pkt, int *len) + void **ret_p_pkt, int *len) { pj_uint32_t expected, expected_interval, received_interval, lost_interval; pjmedia_rtcp_sr *sr; @@ -908,44 +907,44 @@ PJ_DEF(void) pjmedia_rtcp_build_rtcp(pjmedia_rtcp_session *sess, * sent RTCP SR. */ if (sess->stat.tx.pkt != pj_ntohl(sess->rtcp_sr_pkt.sr.sender_pcount)) { - pj_time_val ts_time; - pj_uint32_t rtp_ts; + pj_time_val ts_time; + pj_uint32_t rtp_ts; - /* So we should send RTCP SR */ - *ret_p_pkt = (void*) &sess->rtcp_sr_pkt; - *len = sizeof(pjmedia_rtcp_sr_pkt); - rr = &sess->rtcp_sr_pkt.rr; - sr = &sess->rtcp_sr_pkt.sr; + /* So we should send RTCP SR */ + *ret_p_pkt = (void*) &sess->rtcp_sr_pkt; + *len = sizeof(pjmedia_rtcp_sr_pkt); + rr = &sess->rtcp_sr_pkt.rr; + sr = &sess->rtcp_sr_pkt.sr; - /* Update packet count */ - sr->sender_pcount = pj_htonl(sess->stat.tx.pkt); + /* Update packet count */ + sr->sender_pcount = pj_htonl(sess->stat.tx.pkt); - /* Update octets count */ - sr->sender_bcount = pj_htonl(sess->stat.tx.bytes); + /* Update octets count */ + sr->sender_bcount = pj_htonl(sess->stat.tx.bytes); - /* Fill in NTP timestamp in SR. */ - sr->ntp_sec = pj_htonl(ntp.hi); - sr->ntp_frac = pj_htonl(ntp.lo); + /* Fill in NTP timestamp in SR. */ + sr->ntp_sec = pj_htonl(ntp.hi); + sr->ntp_frac = pj_htonl(ntp.lo); - /* Fill in RTP timestamp (corresponds to NTP timestamp) in SR. */ - ts_time.sec = ntp.hi - sess->tv_base.sec - JAN_1970; - ts_time.msec = (long)(ntp.lo * 1000.0 / 0xFFFFFFFF); - rtp_ts = sess->rtp_ts_base + - (pj_uint32_t)(sess->clock_rate*ts_time.sec) + - (pj_uint32_t)(sess->clock_rate*ts_time.msec/1000); - sr->rtp_ts = pj_htonl(rtp_ts); + /* Fill in RTP timestamp (corresponds to NTP timestamp) in SR. */ + ts_time.sec = ntp.hi - sess->tv_base.sec - JAN_1970; + ts_time.msec = (long)(ntp.lo * 1000.0 / 0xFFFFFFFF); + rtp_ts = sess->rtp_ts_base + + (pj_uint32_t)(sess->clock_rate*ts_time.sec) + + (pj_uint32_t)(sess->clock_rate*ts_time.msec/1000); + sr->rtp_ts = pj_htonl(rtp_ts); - TRACE_((sess->name, "TX RTCP SR: ntp_ts=%p", - ((ntp.hi & 0xFFFF) << 16) + ((ntp.lo & 0xFFFF0000) - >> 16))); + TRACE_((sess->name, "TX RTCP SR: ntp_ts=%p", + ((ntp.hi & 0xFFFF) << 16) + ((ntp.lo & 0xFFFF0000) + >> 16))); } else { - /* We should send RTCP RR then */ - *ret_p_pkt = (void*) &sess->rtcp_rr_pkt; - *len = sizeof(pjmedia_rtcp_rr_pkt); - rr = &sess->rtcp_rr_pkt.rr; - sr = NULL; + /* We should send RTCP RR then */ + *ret_p_pkt = (void*) &sess->rtcp_rr_pkt; + *len = sizeof(pjmedia_rtcp_rr_pkt); + rr = &sess->rtcp_rr_pkt.rr; + sr = NULL; } /* SSRC and last_seq */ @@ -968,9 +967,9 @@ PJ_DEF(void) pjmedia_rtcp_build_rtcp(pjmedia_rtcp_session *sess, /* This is bug: total lost already calculated on each incoming RTP! if (expected >= sess->received) - sess->stat.rx.loss = expected - sess->received; + sess->stat.rx.loss = expected - sess->received; else - sess->stat.rx.loss = 0; + sess->stat.rx.loss = 0; */ rr->total_lost_2 = (sess->stat.rx.loss >> 16) & 0xFF; @@ -985,53 +984,53 @@ PJ_DEF(void) pjmedia_rtcp_build_rtcp(pjmedia_rtcp_session *sess, sess->rx_prior = sess->received; if (expected_interval >= received_interval) - lost_interval = expected_interval - received_interval; + lost_interval = expected_interval - received_interval; else - lost_interval = 0; + lost_interval = 0; if (expected_interval==0 || lost_interval == 0) { - rr->fract_lost = 0; + rr->fract_lost = 0; } else { - rr->fract_lost = (lost_interval << 8) / expected_interval; + rr->fract_lost = (lost_interval << 8) / expected_interval; } if (sess->rx_lsr_time.u64 == 0 || sess->rx_lsr == 0) { - rr->lsr = 0; - rr->dlsr = 0; + rr->lsr = 0; + rr->dlsr = 0; } else { - pj_timestamp ts; - pj_uint32_t lsr = sess->rx_lsr; - pj_uint64_t lsr_time = sess->rx_lsr_time.u64; - pj_uint32_t dlsr; - - /* Convert LSR time to 1/65536 seconds resolution */ - lsr_time = (lsr_time << 16) / sess->ts_freq.u64; - - /* Fill in LSR. - LSR is the middle 32bit of the last SR NTP time received. - */ - rr->lsr = pj_htonl(lsr); - - /* Fill in DLSR. - DLSR is Delay since Last SR, in 1/65536 seconds. - */ - ts.u64 = ts_now.u64; - - /* Convert interval to 1/65536 seconds value */ - ts.u64 = (ts.u64 << 16) / sess->ts_freq.u64; - - /* Get DLSR */ - dlsr = (pj_uint32_t)(ts.u64 - lsr_time); - rr->dlsr = pj_htonl(dlsr); - - TRACE_((sess->name,"Tx RTCP RR: lsr=%p, lsr_time=%p, now=%p, dlsr=%p" - "(%ds:%03dms)", - lsr, - (pj_uint32_t)lsr_time, - (pj_uint32_t)ts.u64, - dlsr, - dlsr/65536, - (dlsr%65536)*1000/65536 )); + pj_timestamp ts; + pj_uint32_t lsr = sess->rx_lsr; + pj_uint64_t lsr_time = sess->rx_lsr_time.u64; + pj_uint32_t dlsr; + + /* Convert LSR time to 1/65536 seconds resolution */ + lsr_time = (lsr_time << 16) / sess->ts_freq.u64; + + /* Fill in LSR. + LSR is the middle 32bit of the last SR NTP time received. + */ + rr->lsr = pj_htonl(lsr); + + /* Fill in DLSR. + DLSR is Delay since Last SR, in 1/65536 seconds. + */ + ts.u64 = ts_now.u64; + + /* Convert interval to 1/65536 seconds value */ + ts.u64 = (ts.u64 << 16) / sess->ts_freq.u64; + + /* Get DLSR */ + dlsr = (pj_uint32_t)(ts.u64 - lsr_time); + rr->dlsr = pj_htonl(dlsr); + + TRACE_((sess->name,"Tx RTCP RR: lsr=%p, lsr_time=%p, now=%p, dlsr=%p" + "(%ds:%03dms)", + lsr, + (pj_uint32_t)lsr_time, + (pj_uint32_t)ts.u64, + dlsr, + dlsr/65536, + (dlsr%65536)*1000/65536 )); } /* Update counter */ @@ -1041,10 +1040,10 @@ PJ_DEF(void) pjmedia_rtcp_build_rtcp(pjmedia_rtcp_session *sess, PJ_DEF(pj_status_t) pjmedia_rtcp_build_rtcp_sdes( - pjmedia_rtcp_session *session, - void *buf, - pj_size_t *length, - const pjmedia_rtcp_sdes *sdes) + pjmedia_rtcp_session *session, + void *buf, + pj_size_t *length, + const pjmedia_rtcp_sdes *sdes) { pjmedia_rtcp_common *hdr; pj_uint8_t *p; @@ -1054,11 +1053,11 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_build_rtcp_sdes( /* Verify SDES item length */ if (sdes->cname.slen > 255 || sdes->name.slen > 255 || - sdes->email.slen > 255 || sdes->phone.slen > 255 || - sdes->loc.slen > 255 || sdes->tool.slen > 255 || - sdes->note.slen > 255) + sdes->email.slen > 255 || sdes->phone.slen > 255 || + sdes->loc.slen > 255 || sdes->tool.slen > 255 || + sdes->note.slen > 255) { - return PJ_EINVAL; + return PJ_EINVAL; } /* Verify buffer length */ @@ -1073,7 +1072,7 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_build_rtcp_sdes( len++; /* null termination */ len = ((len+3)/4) * 4; if (len > *length) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; /* Build RTCP SDES header */ hdr = (pjmedia_rtcp_common*)buf; @@ -1085,10 +1084,10 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_build_rtcp_sdes( p = (pj_uint8_t*)hdr + sizeof(*hdr); #define BUILD_SDES_ITEM(SDES_NAME, SDES_TYPE) \ if (sdes->SDES_NAME.slen) { \ - *p++ = SDES_TYPE; \ - *p++ = (pj_uint8_t)sdes->SDES_NAME.slen; \ - pj_memcpy(p, sdes->SDES_NAME.ptr, sdes->SDES_NAME.slen); \ - p += sdes->SDES_NAME.slen; \ + *p++ = SDES_TYPE; \ + *p++ = (pj_uint8_t)sdes->SDES_NAME.slen; \ + pj_memcpy(p, sdes->SDES_NAME.ptr, sdes->SDES_NAME.slen); \ + p += sdes->SDES_NAME.slen; \ } BUILD_SDES_ITEM(cname, RTCP_SDES_CNAME); BUILD_SDES_ITEM(name, RTCP_SDES_NAME); @@ -1104,7 +1103,7 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_build_rtcp_sdes( /* Pad to 32bit */ while ((p-(pj_uint8_t*)buf) % 4) - *p++ = 0; + *p++ = 0; /* Finally */ pj_assert((int)len == p-(pj_uint8_t*)buf); @@ -1115,9 +1114,9 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_build_rtcp_sdes( PJ_DEF(pj_status_t) pjmedia_rtcp_build_rtcp_bye(pjmedia_rtcp_session *session, - void *buf, - pj_size_t *length, - const pj_str_t *reason) + void *buf, + pj_size_t *length, + const pj_str_t *reason) { pjmedia_rtcp_common *hdr; pj_uint8_t *p; @@ -1127,14 +1126,14 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_build_rtcp_bye(pjmedia_rtcp_session *session, /* Verify BYE reason length */ if (reason && reason->slen > 255) - return PJ_EINVAL; + return PJ_EINVAL; /* Verify buffer length */ len = sizeof(*hdr); if (reason && reason->slen) len += reason->slen + 1; len = ((len+3)/4) * 4; if (len > *length) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; /* Build RTCP BYE header */ hdr = (pjmedia_rtcp_common*)buf; @@ -1145,14 +1144,14 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_build_rtcp_bye(pjmedia_rtcp_session *session, /* Write RTCP BYE reason */ p = (pj_uint8_t*)hdr + sizeof(*hdr); if (reason && reason->slen) { - *p++ = (pj_uint8_t)reason->slen; - pj_memcpy(p, reason->ptr, reason->slen); - p += reason->slen; + *p++ = (pj_uint8_t)reason->slen; + pj_memcpy(p, reason->ptr, reason->slen); + p += reason->slen; } /* Pad to 32bit */ while ((p-(pj_uint8_t*)buf) % 4) - *p++ = 0; + *p++ = 0; pj_assert((int)len == p-(pj_uint8_t*)buf); *length = len; @@ -1162,17 +1161,17 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_build_rtcp_bye(pjmedia_rtcp_session *session, PJ_DEF(pj_status_t) pjmedia_rtcp_enable_xr( pjmedia_rtcp_session *sess, - pj_bool_t enable) + pj_bool_t enable) { #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) /* Check if request won't change anything */ if (!(enable ^ sess->xr_enabled)) - return PJ_SUCCESS; + return PJ_SUCCESS; if (!enable) { - sess->xr_enabled = PJ_FALSE; - return PJ_SUCCESS; + sess->xr_enabled = PJ_FALSE; + return PJ_SUCCESS; } pjmedia_rtcp_xr_init(&sess->xr_session, sess, 0, 1); diff --git a/pjmedia/src/pjmedia/rtcp_fb.c b/pjmedia/src/pjmedia/rtcp_fb.c index ea7887d311..a11a385f7f 100644 --- a/pjmedia/src/pjmedia/rtcp_fb.c +++ b/pjmedia/src/pjmedia/rtcp_fb.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2018 Teluu Inc. (http://www.teluu.com) * @@ -30,18 +29,18 @@ #define THIS_FILE "rtcp_fb.c" -#define RTCP_RTPFB 205 -#define RTCP_PSFB 206 +#define RTCP_RTPFB 205 +#define RTCP_PSFB 206 /* * Build an RTCP-FB Generic NACK packet. */ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_nack( - pjmedia_rtcp_session *session, - void *buf, - pj_size_t *length, - unsigned nack_cnt, - const pjmedia_rtcp_fb_nack nack[]) + pjmedia_rtcp_session *session, + void *buf, + pj_size_t *length, + unsigned nack_cnt, + const pjmedia_rtcp_fb_nack nack[]) { pjmedia_rtcp_fb_common *hdr; pj_uint8_t *p; @@ -51,7 +50,7 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_nack( len = (3 + nack_cnt) * 4; if (len > *length) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; /* Build RTCP-FB NACK header */ hdr = (pjmedia_rtcp_fb_common*)buf; @@ -63,12 +62,12 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_nack( /* Build RTCP-FB NACK FCI */ p = (pj_uint8_t*)hdr + sizeof(*hdr); for (i = 0; i < nack_cnt; ++i) { - pj_uint16_t val; - val = pj_htons((pj_uint16_t)nack[i].pid); - pj_memcpy(p, &val, 2); - val = pj_htons(nack[i].blp); - pj_memcpy(p+2, &val, 2); - p += 4; + pj_uint16_t val; + val = pj_htons((pj_uint16_t)nack[i].pid); + pj_memcpy(p, &val, 2); + val = pj_htons(nack[i].blp); + pj_memcpy(p+2, &val, 2); + p += 4; } /* Finally */ @@ -82,9 +81,9 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_nack( * Build an RTCP-FB Picture Loss Indication (PLI) packet. */ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_pli( - pjmedia_rtcp_session *session, - void *buf, - pj_size_t *length) + pjmedia_rtcp_session *session, + void *buf, + pj_size_t *length) { pjmedia_rtcp_fb_common *hdr; unsigned len; @@ -93,7 +92,7 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_pli( len = 12; if (len > *length) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; /* Build RTCP-FB PLI header */ hdr = (pjmedia_rtcp_fb_common*)buf; @@ -113,11 +112,11 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_pli( * Build an RTCP-FB Slice Loss Indication (SLI) packet. */ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_sli( - pjmedia_rtcp_session *session, - void *buf, - pj_size_t *length, - unsigned sli_cnt, - const pjmedia_rtcp_fb_sli sli[]) + pjmedia_rtcp_session *session, + void *buf, + pj_size_t *length, + unsigned sli_cnt, + const pjmedia_rtcp_fb_sli sli[]) { pjmedia_rtcp_fb_common *hdr; pj_uint8_t *p; @@ -127,7 +126,7 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_sli( len = (3 + sli_cnt) * 4; if (len > *length) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; /* Build RTCP-FB SLI header */ hdr = (pjmedia_rtcp_fb_common*)buf; @@ -139,15 +138,15 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_sli( /* Build RTCP-FB SLI FCI */ p = (pj_uint8_t*)hdr + sizeof(*hdr); for (i = 0; i < sli_cnt; ++i) { - /* 'first' takes 13 bit */ - *p++ = (pj_uint8_t)((sli[i].first >> 5) & 0xFF); /* 8 MSB bits */ - *p = (pj_uint8_t)((sli[i].first & 31) << 3); /* 5 LSB bits */ - /* 'number' takes 13 bit */ - *p++ |= (pj_uint8_t)((sli[i].number >> 10) & 7); /* 3 MSB bits */ - *p++ = (pj_uint8_t)((sli[i].number >> 2) & 0xFF); /* 8 mid bits */ - *p = (pj_uint8_t)((sli[i].number & 3) << 6); /* 2 LSB bits */ - /* 'pict_id' takes 6 bit */ - *p++ |= (sli[i].pict_id & 63); + /* 'first' takes 13 bit */ + *p++ = (pj_uint8_t)((sli[i].first >> 5) & 0xFF); /* 8 MSB bits */ + *p = (pj_uint8_t)((sli[i].first & 31) << 3); /* 5 LSB bits */ + /* 'number' takes 13 bit */ + *p++ |= (pj_uint8_t)((sli[i].number >> 10) & 7); /* 3 MSB bits */ + *p++ = (pj_uint8_t)((sli[i].number >> 2) & 0xFF); /* 8 mid bits */ + *p = (pj_uint8_t)((sli[i].number & 3) << 6); /* 2 LSB bits */ + /* 'pict_id' takes 6 bit */ + *p++ |= (sli[i].pict_id & 63); } /* Finally */ @@ -161,10 +160,10 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_sli( * Build an RTCP-FB Slice Loss Indication (SLI) packet. */ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_rpsi( - pjmedia_rtcp_session *session, - void *buf, - pj_size_t *length, - const pjmedia_rtcp_fb_rpsi *rpsi) + pjmedia_rtcp_session *session, + void *buf, + pj_size_t *length, + const pjmedia_rtcp_fb_rpsi *rpsi) { pjmedia_rtcp_fb_common *hdr; pj_uint8_t *p; @@ -176,7 +175,7 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_rpsi( padlen = (32 - (bitlen % 32)) % 32; len = (3 + (bitlen+padlen)/32) * 4; if (len > *length) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; /* Build RTCP-FB RPSI header */ hdr = (pjmedia_rtcp_fb_common*)buf; @@ -195,11 +194,11 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_rpsi( pj_memcpy(p, rpsi->rpsi.ptr, rpsi->rpsi_bit_len/8); p += rpsi->rpsi_bit_len/8; if (rpsi->rpsi_bit_len % 8) { - *p++ = *(rpsi->rpsi.ptr + rpsi->rpsi_bit_len/8); + *p++ = *(rpsi->rpsi.ptr + rpsi->rpsi_bit_len/8); } /* Zero padding */ if (padlen >= 8) - pj_bzero(p, padlen/8); + pj_bzero(p, padlen/8); /* Finally */ *length = len; @@ -212,7 +211,7 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_rpsi( * Initialize RTCP Feedback setting with default values. */ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_setting_default( - pjmedia_rtcp_fb_setting *opt) + pjmedia_rtcp_fb_setting *opt) { pj_bzero(opt, sizeof(*opt)); opt->dont_use_avpf = PJ_TRUE; @@ -222,8 +221,8 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_setting_default( static void pjmedia_rtcp_fb_cap_dup(pj_pool_t *pool, - pjmedia_rtcp_fb_cap *dst, - const pjmedia_rtcp_fb_cap *src) + pjmedia_rtcp_fb_cap *dst, + const pjmedia_rtcp_fb_cap *src) { pj_strdup(pool, &dst->codec_id, &src->codec_id); dst->type = src->type; @@ -236,8 +235,8 @@ static void pjmedia_rtcp_fb_cap_dup(pj_pool_t *pool, * Duplicate RTCP Feedback setting. */ PJ_DEF(void) pjmedia_rtcp_fb_setting_dup( pj_pool_t *pool, - pjmedia_rtcp_fb_setting *dst, - const pjmedia_rtcp_fb_setting *src) + pjmedia_rtcp_fb_setting *dst, + const pjmedia_rtcp_fb_setting *src) { unsigned i; @@ -245,7 +244,7 @@ PJ_DEF(void) pjmedia_rtcp_fb_setting_dup( pj_pool_t *pool, pj_memcpy(dst, src, sizeof(pjmedia_rtcp_fb_setting)); for (i = 0; i < src->cap_count; ++i) { - pjmedia_rtcp_fb_cap_dup(pool, &dst->caps[i], &src->caps[i]); + pjmedia_rtcp_fb_cap_dup(pool, &dst->caps[i], &src->caps[i]); } } @@ -254,8 +253,8 @@ PJ_DEF(void) pjmedia_rtcp_fb_setting_dup( pj_pool_t *pool, * Duplicate RTCP Feedback info. */ PJ_DEF(void) pjmedia_rtcp_fb_info_dup( pj_pool_t *pool, - pjmedia_rtcp_fb_info *dst, - const pjmedia_rtcp_fb_info *src) + pjmedia_rtcp_fb_info *dst, + const pjmedia_rtcp_fb_info *src) { unsigned i; @@ -263,7 +262,7 @@ PJ_DEF(void) pjmedia_rtcp_fb_info_dup( pj_pool_t *pool, pj_memcpy(dst, src, sizeof(pjmedia_rtcp_fb_info)); for (i = 0; i < src->cap_count; ++i) { - pjmedia_rtcp_fb_cap_dup(pool, &dst->caps[i], &src->caps[i]); + pjmedia_rtcp_fb_cap_dup(pool, &dst->caps[i], &src->caps[i]); } } @@ -272,19 +271,19 @@ PJ_DEF(void) pjmedia_rtcp_fb_info_dup( pj_pool_t *pool, struct rtcp_fb_type_name_t { pjmedia_rtcp_fb_type type; - const char *name; + const char *name; } rtcp_fb_type_name[] = { - {PJMEDIA_RTCP_FB_ACK, "ack"}, - {PJMEDIA_RTCP_FB_NACK, "nack"}, - {PJMEDIA_RTCP_FB_TRR_INT, "trr-int"} + {PJMEDIA_RTCP_FB_ACK, "ack"}, + {PJMEDIA_RTCP_FB_NACK, "nack"}, + {PJMEDIA_RTCP_FB_TRR_INT, "trr-int"} }; /* Generate a=rtcp-fb based on the specified PT & RTCP-FB capability */ static pj_status_t add_sdp_attr_rtcp_fb( pj_pool_t *pool, - const char *pt, - const pjmedia_rtcp_fb_cap *cap, - pjmedia_sdp_media *m) + const char *pt, + const pjmedia_rtcp_fb_cap *cap, + pjmedia_sdp_media *m) { pjmedia_sdp_attr *a; char tmp[128]; @@ -292,21 +291,21 @@ static pj_status_t add_sdp_attr_rtcp_fb( pj_pool_t *pool, pj_str_t type_name = {0}; if (cap->type < PJMEDIA_RTCP_FB_OTHER) - pj_cstr(&type_name, rtcp_fb_type_name[cap->type].name); + pj_cstr(&type_name, rtcp_fb_type_name[cap->type].name); else if (cap->type == PJMEDIA_RTCP_FB_OTHER) - type_name = cap->type_name; + type_name = cap->type_name; if (type_name.slen == 0) - return PJ_EINVAL; + return PJ_EINVAL; /* Generate RTCP FB param */ if (cap->param.slen) { - pj_ansi_snprintf(tmp, sizeof(tmp), "%s %.*s %.*s", pt, - (int)type_name.slen, type_name.ptr, - (int)cap->param.slen, cap->param.ptr); + pj_ansi_snprintf(tmp, sizeof(tmp), "%s %.*s %.*s", pt, + (int)type_name.slen, type_name.ptr, + (int)cap->param.slen, cap->param.ptr); } else { - pj_ansi_snprintf(tmp, sizeof(tmp), "%s %.*s", pt, - (int)type_name.slen, type_name.ptr); + pj_ansi_snprintf(tmp, sizeof(tmp), "%s %.*s", pt, + (int)type_name.slen, type_name.ptr); } pj_strset2(&val, tmp); @@ -320,16 +319,16 @@ static pj_status_t add_sdp_attr_rtcp_fb( pj_pool_t *pool, /* SDP codec info (ID and PT) */ typedef struct sdp_codec_info_t { - char id[32]; - unsigned pt; + char id[32]; + unsigned pt; } sdp_codec_info_t; /* Populate codec ID/name and PT in SDP */ static pj_status_t get_codec_info_from_sdp(pjmedia_endpt *endpt, - const pjmedia_sdp_media *m, - unsigned *sci_cnt, - sdp_codec_info_t sci[]) + const pjmedia_sdp_media *m, + unsigned *sci_cnt, + sdp_codec_info_t sci[]) { pjmedia_codec_mgr *codec_mgr; unsigned j, cnt = 0; @@ -338,66 +337,66 @@ static pj_status_t get_codec_info_from_sdp(pjmedia_endpt *endpt, type = pjmedia_get_type(&m->desc.media); if (type != PJMEDIA_TYPE_AUDIO && type != PJMEDIA_TYPE_VIDEO) - return PJMEDIA_EUNSUPMEDIATYPE; + return PJMEDIA_EUNSUPMEDIATYPE; codec_mgr = pjmedia_endpt_get_codec_mgr(endpt); for (j = 0; j < m->desc.fmt_count && cnt < *sci_cnt; ++j) { - unsigned pt = 0; - pt = pj_strtoul(&m->desc.fmt[j]); - if (pt < 96) { - if (type == PJMEDIA_TYPE_AUDIO) { - const pjmedia_codec_info *ci; - status = pjmedia_codec_mgr_get_codec_info(codec_mgr, pt, &ci); - if (status != PJ_SUCCESS) - continue; - - pjmedia_codec_info_to_id(ci, sci[cnt].id, sizeof(sci[0].id)); - } else { + unsigned pt = 0; + pt = pj_strtoul(&m->desc.fmt[j]); + if (pt < 96) { + if (type == PJMEDIA_TYPE_AUDIO) { + const pjmedia_codec_info *ci; + status = pjmedia_codec_mgr_get_codec_info(codec_mgr, pt, &ci); + if (status != PJ_SUCCESS) + continue; + + pjmedia_codec_info_to_id(ci, sci[cnt].id, sizeof(sci[0].id)); + } else { #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) - const pjmedia_vid_codec_info *ci; - status = pjmedia_vid_codec_mgr_get_codec_info(NULL, pt, &ci); - if (status != PJ_SUCCESS) - continue; + const pjmedia_vid_codec_info *ci; + status = pjmedia_vid_codec_mgr_get_codec_info(NULL, pt, &ci); + if (status != PJ_SUCCESS) + continue; - pjmedia_vid_codec_info_to_id(ci, sci[cnt].id, - sizeof(sci[0].id)); + pjmedia_vid_codec_info_to_id(ci, sci[cnt].id, + sizeof(sci[0].id)); #else - continue; + continue; #endif - } - } else { - pjmedia_sdp_attr *a; - pjmedia_sdp_rtpmap r; - a = pjmedia_sdp_media_find_attr2(m, "rtpmap", - &m->desc.fmt[j]); - if (a == NULL) - continue; - status = pjmedia_sdp_attr_get_rtpmap(a, &r); - if (status != PJ_SUCCESS) - continue; - - if (type == PJMEDIA_TYPE_AUDIO) { - /* Audio codec id format: "name/clock-rate/channel-count" */ - if (r.param.slen) { - pj_ansi_snprintf(sci[cnt].id, sizeof(sci[0].id), - "%.*s/%d/%.*s", - (int)r.enc_name.slen, r.enc_name.ptr, - r.clock_rate, - (int)r.param.slen, r.param.ptr); - } else { - pj_ansi_snprintf(sci[cnt].id, sizeof(sci[0].id), - "%.*s/%d/1", - (int)r.enc_name.slen, r.enc_name.ptr, - r.clock_rate); - } - } else { - /* Video codec id format: "name/payload-type" */ - pj_ansi_snprintf(sci[cnt].id, sizeof(sci[0].id), - "%.*s/%d", - (int)r.enc_name.slen, r.enc_name.ptr, pt); - } - } - sci[cnt++].pt = pt; + } + } else { + pjmedia_sdp_attr *a; + pjmedia_sdp_rtpmap r; + a = pjmedia_sdp_media_find_attr2(m, "rtpmap", + &m->desc.fmt[j]); + if (a == NULL) + continue; + status = pjmedia_sdp_attr_get_rtpmap(a, &r); + if (status != PJ_SUCCESS) + continue; + + if (type == PJMEDIA_TYPE_AUDIO) { + /* Audio codec id format: "name/clock-rate/channel-count" */ + if (r.param.slen) { + pj_ansi_snprintf(sci[cnt].id, sizeof(sci[0].id), + "%.*s/%d/%.*s", + (int)r.enc_name.slen, r.enc_name.ptr, + r.clock_rate, + (int)r.param.slen, r.param.ptr); + } else { + pj_ansi_snprintf(sci[cnt].id, sizeof(sci[0].id), + "%.*s/%d/1", + (int)r.enc_name.slen, r.enc_name.ptr, + r.clock_rate); + } + } else { + /* Video codec id format: "name/payload-type" */ + pj_ansi_snprintf(sci[cnt].id, sizeof(sci[0].id), + "%.*s/%d", + (int)r.enc_name.slen, r.enc_name.ptr, pt); + } + } + sci[cnt++].pt = pt; } *sci_cnt = cnt; @@ -409,12 +408,12 @@ static pj_status_t get_codec_info_from_sdp(pjmedia_endpt *endpt, * the provided RTCP Feedback setting. */ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_encode_sdp( - pj_pool_t *pool, - pjmedia_endpt *endpt, - const pjmedia_rtcp_fb_setting *opt, - pjmedia_sdp_session *sdp_local, - unsigned med_idx, - const pjmedia_sdp_session *sdp_remote) + pj_pool_t *pool, + pjmedia_endpt *endpt, + const pjmedia_rtcp_fb_setting *opt, + pjmedia_sdp_session *sdp_local, + unsigned med_idx, + const pjmedia_sdp_session *sdp_remote) { pjmedia_sdp_media *m = sdp_local->media[med_idx]; unsigned i; @@ -429,63 +428,63 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_encode_sdp( /* Add RTCP Feedback profile (AVPF), if configured to */ if (!opt->dont_use_avpf) { - unsigned proto = pjmedia_sdp_transport_get_proto(&m->desc.transport); - if (!PJMEDIA_TP_PROTO_HAS_FLAG(proto, PJMEDIA_TP_PROFILE_RTCP_FB)) { - pj_str_t new_tp; - pj_strdup_with_null(pool, &new_tp, &m->desc.transport); - new_tp.ptr[new_tp.slen++] = 'F'; - m->desc.transport = new_tp; - } + unsigned proto = pjmedia_sdp_transport_get_proto(&m->desc.transport); + if (!PJMEDIA_TP_PROTO_HAS_FLAG(proto, PJMEDIA_TP_PROFILE_RTCP_FB)) { + pj_str_t new_tp; + pj_strdup_with_null(pool, &new_tp, &m->desc.transport); + new_tp.ptr[new_tp.slen++] = 'F'; + m->desc.transport = new_tp; + } } /* Add RTCP Feedback capability to SDP */ for (i = 0; i < opt->cap_count; ++i) { - unsigned j; - - /* All codecs */ - if (pj_strcmp2(&opt->caps[i].codec_id, "*") == 0) { - status = add_sdp_attr_rtcp_fb(pool, "*", &opt->caps[i], m); - if (status != PJ_SUCCESS) { - PJ_PERROR(3, (THIS_FILE, status, - "Failed generating SDP a=rtcp-fb:*")); - } - continue; - } - - /* Specific codec */ - if (sci_cnt == 0) { - sci_cnt = PJ_ARRAY_SIZE(sci); - status = get_codec_info_from_sdp(endpt, m, &sci_cnt, sci); - if (status != PJ_SUCCESS) { - PJ_PERROR(3, (THIS_FILE, status, - "Failed populating codec info from SDP")); - return status; - } - } - - for (j = 0; j < sci_cnt; ++j) { - if (pj_strnicmp2(&opt->caps[i].codec_id, sci[j].id, - opt->caps[i].codec_id.slen) == 0) - { - char tmp[4]; - snprintf(tmp, sizeof(tmp), "%d", sci[j].pt); - status = add_sdp_attr_rtcp_fb(pool, tmp, &opt->caps[i], m); - if (status != PJ_SUCCESS) { - PJ_PERROR(3, (THIS_FILE, status, - "Failed generating SDP a=rtcp-fb:%d (%s)", - sci[j].pt, opt->caps[i].codec_id.ptr)); - } - break; - } - } - if (j == sci_cnt) { - /* Codec ID not found in SDP (perhaps better ignore this error - * as app may configure audio and video in single setting). - */ - PJ_PERROR(6, (THIS_FILE, PJ_ENOTFOUND, - "Failed generating SDP a=rtcp-fb for %s", - opt->caps[i].codec_id.ptr)); - } + unsigned j; + + /* All codecs */ + if (pj_strcmp2(&opt->caps[i].codec_id, "*") == 0) { + status = add_sdp_attr_rtcp_fb(pool, "*", &opt->caps[i], m); + if (status != PJ_SUCCESS) { + PJ_PERROR(3, (THIS_FILE, status, + "Failed generating SDP a=rtcp-fb:*")); + } + continue; + } + + /* Specific codec */ + if (sci_cnt == 0) { + sci_cnt = PJ_ARRAY_SIZE(sci); + status = get_codec_info_from_sdp(endpt, m, &sci_cnt, sci); + if (status != PJ_SUCCESS) { + PJ_PERROR(3, (THIS_FILE, status, + "Failed populating codec info from SDP")); + return status; + } + } + + for (j = 0; j < sci_cnt; ++j) { + if (pj_strnicmp2(&opt->caps[i].codec_id, sci[j].id, + opt->caps[i].codec_id.slen) == 0) + { + char tmp[4]; + snprintf(tmp, sizeof(tmp), "%d", sci[j].pt); + status = add_sdp_attr_rtcp_fb(pool, tmp, &opt->caps[i], m); + if (status != PJ_SUCCESS) { + PJ_PERROR(3, (THIS_FILE, status, + "Failed generating SDP a=rtcp-fb:%d (%s)", + sci[j].pt, opt->caps[i].codec_id.ptr)); + } + break; + } + } + if (j == sci_cnt) { + /* Codec ID not found in SDP (perhaps better ignore this error + * as app may configure audio and video in single setting). + */ + PJ_PERROR(6, (THIS_FILE, PJ_ENOTFOUND, + "Failed generating SDP a=rtcp-fb for %s", + opt->caps[i].codec_id.ptr)); + } } return PJ_SUCCESS; @@ -496,28 +495,28 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_encode_sdp( * Decode RTCP Feedback specific information from SDP media. */ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_decode_sdp( - pj_pool_t *pool, - pjmedia_endpt *endpt, - const void *opt, - const pjmedia_sdp_session *sdp, - unsigned med_idx, - pjmedia_rtcp_fb_info *info) + pj_pool_t *pool, + pjmedia_endpt *endpt, + const void *opt, + const pjmedia_sdp_session *sdp, + unsigned med_idx, + pjmedia_rtcp_fb_info *info) { return pjmedia_rtcp_fb_decode_sdp2(pool, endpt, opt, sdp, med_idx, -1, - info); + info); } /* * Decode RTCP Feedback specific information from SDP media. */ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_decode_sdp2( - pj_pool_t *pool, - pjmedia_endpt *endpt, - const void *opt, - const pjmedia_sdp_session *sdp, - unsigned med_idx, - int pt, - pjmedia_rtcp_fb_info *info) + pj_pool_t *pool, + pjmedia_endpt *endpt, + const void *opt, + const pjmedia_sdp_session *sdp, + unsigned med_idx, + int pt, + pjmedia_rtcp_fb_info *info) { unsigned sci_cnt = PJMEDIA_MAX_SDP_FMT; sdp_codec_info_t sci[PJMEDIA_MAX_SDP_FMT]; @@ -534,76 +533,76 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_decode_sdp2( m = sdp->media[med_idx]; status = get_codec_info_from_sdp(endpt, m, &sci_cnt, sci); if (status != PJ_SUCCESS) - return status; + return status; pj_bzero(info, sizeof(*info)); /* Iterate all SDP attribute a=rtcp-fb in the SDP media */ for (i = 0; i < m->attr_count; ++i) { - const pjmedia_sdp_attr *a = m->attr[i]; - pj_str_t token; - pj_ssize_t tok_idx; - unsigned j; - const char *codec_id = NULL; - pj_str_t type_name = {0}; - pjmedia_rtcp_fb_type type = PJMEDIA_RTCP_FB_OTHER; - - /* Skip non a=rtcp-fb */ - if (pj_strcmp2(&a->name, "rtcp-fb") != 0) - continue; - - /* Get PT */ - tok_idx = pj_strtok2(&a->value, " \t", &token, 0); - if (tok_idx == a->value.slen) - continue; - - if (pj_strcmp2(&token, "*") == 0) { - /* All codecs */ - codec_id = "*"; - } else { - /* Specific PT/codec */ - unsigned pt_ = (unsigned) pj_strtoul2(&token, NULL, 10); - for (j = 0; j < sci_cnt; ++j) { - /* Check if payload type is valid and requested */ - if (pt_ == sci[j].pt && (pt < 0 || pt == (int)pt_)) { - codec_id = sci[j].id; - break; - } - } - } - - /* Skip this a=rtcp-fb if PT is not recognized or not requested */ - if (!codec_id) - continue; - - /* Get RTCP-FB type */ - tok_idx = pj_strtok2(&a->value, " \t", &token, tok_idx + token.slen); - if (tok_idx == a->value.slen) - continue; - - for (j = 0; j < PJ_ARRAY_SIZE(rtcp_fb_type_name); ++j) { - if (pj_strcmp2(&token, rtcp_fb_type_name[j].name) == 0) { - type = rtcp_fb_type_name[j].type; - break; - } - } - if (type == PJMEDIA_RTCP_FB_OTHER) - type_name = token; - - /* Got all the mandatory fields, let's initialize RTCP-FB cap */ - pj_strdup2(pool, &info->caps[info->cap_count].codec_id, codec_id); - info->caps[info->cap_count].type = type; - if (type == PJMEDIA_RTCP_FB_OTHER) - pj_strdup(pool, &info->caps[info->cap_count].type_name, &type_name); - - /* Get RTCP-FB param */ - tok_idx = pj_strtok2(&a->value, " \t", &token, tok_idx + token.slen); - if (tok_idx != a->value.slen) - pj_strdup(pool, &info->caps[info->cap_count].param, &token); - - /* Next */ - if (++info->cap_count == PJMEDIA_RTCP_FB_MAX_CAP) - break; + const pjmedia_sdp_attr *a = m->attr[i]; + pj_str_t token; + pj_ssize_t tok_idx; + unsigned j; + const char *codec_id = NULL; + pj_str_t type_name = {0}; + pjmedia_rtcp_fb_type type = PJMEDIA_RTCP_FB_OTHER; + + /* Skip non a=rtcp-fb */ + if (pj_strcmp2(&a->name, "rtcp-fb") != 0) + continue; + + /* Get PT */ + tok_idx = pj_strtok2(&a->value, " \t", &token, 0); + if (tok_idx == a->value.slen) + continue; + + if (pj_strcmp2(&token, "*") == 0) { + /* All codecs */ + codec_id = "*"; + } else { + /* Specific PT/codec */ + unsigned pt_ = (unsigned) pj_strtoul2(&token, NULL, 10); + for (j = 0; j < sci_cnt; ++j) { + /* Check if payload type is valid and requested */ + if (pt_ == sci[j].pt && (pt < 0 || pt == (int)pt_)) { + codec_id = sci[j].id; + break; + } + } + } + + /* Skip this a=rtcp-fb if PT is not recognized or not requested */ + if (!codec_id) + continue; + + /* Get RTCP-FB type */ + tok_idx = pj_strtok2(&a->value, " \t", &token, tok_idx + token.slen); + if (tok_idx == a->value.slen) + continue; + + for (j = 0; j < PJ_ARRAY_SIZE(rtcp_fb_type_name); ++j) { + if (pj_strcmp2(&token, rtcp_fb_type_name[j].name) == 0) { + type = rtcp_fb_type_name[j].type; + break; + } + } + if (type == PJMEDIA_RTCP_FB_OTHER) + type_name = token; + + /* Got all the mandatory fields, let's initialize RTCP-FB cap */ + pj_strdup2(pool, &info->caps[info->cap_count].codec_id, codec_id); + info->caps[info->cap_count].type = type; + if (type == PJMEDIA_RTCP_FB_OTHER) + pj_strdup(pool, &info->caps[info->cap_count].type_name, &type_name); + + /* Get RTCP-FB param */ + tok_idx = pj_strtok2(&a->value, " \t", &token, tok_idx + token.slen); + if (tok_idx != a->value.slen) + pj_strdup(pool, &info->caps[info->cap_count].param, &token); + + /* Next */ + if (++info->cap_count == PJMEDIA_RTCP_FB_MAX_CAP) + break; } return PJ_SUCCESS; @@ -615,10 +614,10 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_decode_sdp2( * message, and parse the payload if it does. */ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_nack( - const void *buf, - pj_size_t length, - unsigned *nack_cnt, - pjmedia_rtcp_fb_nack nack[]) + const void *buf, + pj_size_t length, + unsigned *nack_cnt, + pjmedia_rtcp_fb_nack nack[]) { pjmedia_rtcp_fb_common *hdr = (pjmedia_rtcp_fb_common*) buf; pj_uint8_t *p; @@ -629,24 +628,24 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_nack( /* Generic NACK uses pt==RTCP_RTPFB and FMT==1 */ if (hdr->rtcp_common.pt != RTCP_RTPFB || hdr->rtcp_common.count != 1) - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; cnt = pj_ntohs((pj_uint16_t)hdr->rtcp_common.length); if (cnt > 2) cnt -= 2; else cnt = 0; if (length < (cnt+3)*4) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; *nack_cnt = PJ_MIN(*nack_cnt, cnt); p = (pj_uint8_t*)hdr + sizeof(*hdr); for (i = 0; i < *nack_cnt; ++i) { - pj_uint16_t val; + pj_uint16_t val; - pj_memcpy(&val, p, 2); - nack[i].pid = pj_ntohs(val); - pj_memcpy(&val, p+2, 2); - nack[i].blp = pj_ntohs(val); - p += 4; + pj_memcpy(&val, p, 2); + nack[i].pid = pj_ntohs(val); + pj_memcpy(&val, p+2, 2); + nack[i].blp = pj_ntohs(val); + p += 4; } return PJ_SUCCESS; @@ -658,8 +657,8 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_nack( * Indication (PLI) message. */ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_pli( - const void *buf, - pj_size_t length) + const void *buf, + pj_size_t length) { pjmedia_rtcp_fb_common *hdr = (pjmedia_rtcp_fb_common*) buf; @@ -668,7 +667,7 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_pli( /* PLI uses pt==RTCP_PSFB and FMT==1 */ if (hdr->rtcp_common.pt != RTCP_PSFB || hdr->rtcp_common.count != 1) - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; return PJ_SUCCESS; } @@ -679,10 +678,10 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_pli( * Indication (SLI) message, and parse the payload if it does. */ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_sli( - const void *buf, - pj_size_t length, - unsigned *sli_cnt, - pjmedia_rtcp_fb_sli sli[]) + const void *buf, + pj_size_t length, + unsigned *sli_cnt, + pjmedia_rtcp_fb_sli sli[]) { pjmedia_rtcp_fb_common *hdr = (pjmedia_rtcp_fb_common*) buf; pj_uint8_t *p; @@ -693,31 +692,31 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_sli( /* PLI uses pt==RTCP_PSFB and FMT==2 */ if (hdr->rtcp_common.pt != RTCP_PSFB || hdr->rtcp_common.count != 2) - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; if (hdr->rtcp_common.length < 3) { PJ_PERROR(3, (THIS_FILE, PJ_ETOOSMALL, "Failed parsing FB SLI, invalid header length")); - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; } cnt = pj_ntohs((pj_uint16_t)hdr->rtcp_common.length) - 2; if (length < (cnt+3)*4) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; *sli_cnt = PJ_MIN(*sli_cnt, cnt); p = (pj_uint8_t*)hdr + sizeof(*hdr); for (i = 0; i < *sli_cnt; ++i) { - /* 'first' takes 13 bit */ - sli[i].first = (p[0] << 5) + ((p[1] & 0xF8) >> 3); - /* 'number' takes 13 bit */ - sli[i].number = ((p[1] & 0x07) << 10) + - (p[2] << 2) + - ((p[3] & 0xC0) >> 6); - /* 'pict_id' takes 6 bit */ - sli[i].pict_id = (p[3] & 0x3F); - p += 4; + /* 'first' takes 13 bit */ + sli[i].first = (p[0] << 5) + ((p[1] & 0xF8) >> 3); + /* 'number' takes 13 bit */ + sli[i].number = ((p[1] & 0x07) << 10) + + (p[2] << 2) + + ((p[3] & 0xC0) >> 6); + /* 'pict_id' takes 6 bit */ + sli[i].pict_id = (p[3] & 0x3F); + p += 4; } return PJ_SUCCESS; @@ -730,9 +729,9 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_sli( * if it does. */ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_rpsi( - const void *buf, - pj_size_t length, - pjmedia_rtcp_fb_rpsi *rpsi) + const void *buf, + pj_size_t length, + pjmedia_rtcp_fb_rpsi *rpsi) { pjmedia_rtcp_fb_common *hdr = (pjmedia_rtcp_fb_common*) buf; pj_uint8_t *p; @@ -744,17 +743,17 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_rpsi( /* RPSI uses pt==RTCP_PSFB and FMT==3 */ if (hdr->rtcp_common.pt != RTCP_PSFB || hdr->rtcp_common.count != 3) - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; if (hdr->rtcp_common.length < 3) { PJ_PERROR(3, (THIS_FILE, PJ_ETOOSMALL, "Failed parsing FB RPSI, invalid header length")); - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; } rpsi_len = (pj_ntohs((pj_uint16_t)hdr->rtcp_common.length)-2) * 4; if (length < rpsi_len + 12) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; p = (pj_uint8_t*)hdr + sizeof(*hdr); padlen = *p++; @@ -762,13 +761,13 @@ PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_rpsi( if (padlen >= 32) { PJ_PERROR(3, (THIS_FILE, PJ_ETOOBIG, "Failed parsing FB RPSI, invalid RPSI padding len")); - return PJ_ETOOBIG; + return PJ_ETOOBIG; } if ((rpsi_len * 8) < (unsigned)(16 + padlen)) { PJ_PERROR(3, (THIS_FILE, PJ_ETOOSMALL, "Failed parsing FB RPSI, invalid RPSI bit len")); - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; } rpsi->pt = (*p++ & 0x7F); diff --git a/pjmedia/src/pjmedia/rtcp_xr.c b/pjmedia/src/pjmedia/rtcp_xr.c index f554698a20..e5a8b22e4b 100644 --- a/pjmedia/src/pjmedia/rtcp_xr.c +++ b/pjmedia/src/pjmedia/rtcp_xr.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,44 +37,44 @@ /* RTCP XR payload type */ -#define RTCP_XR 207 +#define RTCP_XR 207 /* RTCP XR block types */ -#define BT_LOSS_RLE 1 -#define BT_DUP_RLE 2 -#define BT_RCPT_TIMES 3 -#define BT_RR_TIME 4 -#define BT_DLRR 5 -#define BT_STATS 6 -#define BT_VOIP_METRICS 7 +#define BT_LOSS_RLE 1 +#define BT_DUP_RLE 2 +#define BT_RCPT_TIMES 3 +#define BT_RR_TIME 4 +#define BT_DLRR 5 +#define BT_STATS 6 +#define BT_VOIP_METRICS 7 -#define DEFAULT_GMIN 16 +#define DEFAULT_GMIN 16 #if 0 -# define TRACE_(x) PJ_LOG(3,x) +# define TRACE_(x) PJ_LOG(3,x) #else -# define TRACE_(x) ; +# define TRACE_(x) ; #endif void pjmedia_rtcp_xr_init( pjmedia_rtcp_xr_session *session, - struct pjmedia_rtcp_session *parent_session, - pj_uint8_t gmin, - unsigned frames_per_packet) + struct pjmedia_rtcp_session *parent_session, + pj_uint8_t gmin, + unsigned frames_per_packet) { pj_bzero(session, sizeof(pjmedia_rtcp_xr_session)); session->name = parent_session->name; session->rtcp_session = parent_session; pj_memcpy(&session->pkt.common, &session->rtcp_session->rtcp_sr_pkt.common, - sizeof(pjmedia_rtcp_common)); + sizeof(pjmedia_rtcp_common)); session->pkt.common.pt = RTCP_XR; /* Init config */ session->stat.rx.voip_mtc.gmin = (pj_uint8_t)(gmin? gmin : DEFAULT_GMIN); session->ptime = session->rtcp_session->pkt_size * 1000 / - session->rtcp_session->clock_rate; + session->rtcp_session->clock_rate; session->frames_per_packet = frames_per_packet; /* Init Statistics Summary fields which have non-zero default */ @@ -106,292 +105,292 @@ void pjmedia_rtcp_xr_fini(pjmedia_rtcp_xr_session *session) } PJ_DEF(void) pjmedia_rtcp_build_rtcp_xr( pjmedia_rtcp_xr_session *sess, - unsigned rpt_types, - void **rtcp_pkt, int *len) + unsigned rpt_types, + void **rtcp_pkt, int *len) { pj_uint16_t size = 0; /* Receiver Reference Time Report Block */ /* Build this block if we have received packets since last build */ if ((rpt_types == 0 || (rpt_types & PJMEDIA_RTCP_XR_RR_TIME)) && - sess->rx_last_rr != sess->rtcp_session->stat.rx.pkt) + sess->rx_last_rr != sess->rtcp_session->stat.rx.pkt) { - pjmedia_rtcp_xr_rb_rr_time *r; - pjmedia_rtcp_ntp_rec ntp; + pjmedia_rtcp_xr_rb_rr_time *r; + pjmedia_rtcp_ntp_rec ntp; - r = (pjmedia_rtcp_xr_rb_rr_time*) &sess->pkt.buf[size]; - pj_bzero(r, sizeof(pjmedia_rtcp_xr_rb_rr_time)); + r = (pjmedia_rtcp_xr_rb_rr_time*) &sess->pkt.buf[size]; + pj_bzero(r, sizeof(pjmedia_rtcp_xr_rb_rr_time)); - /* Init block header */ - r->header.bt = BT_RR_TIME; - r->header.specific = 0; - r->header.length = pj_htons(2); + /* Init block header */ + r->header.bt = BT_RR_TIME; + r->header.specific = 0; + r->header.length = pj_htons(2); - /* Generate block contents */ - pjmedia_rtcp_get_ntp_time(sess->rtcp_session, &ntp); - r->ntp_sec = pj_htonl(ntp.hi); - r->ntp_frac = pj_htonl(ntp.lo); + /* Generate block contents */ + pjmedia_rtcp_get_ntp_time(sess->rtcp_session, &ntp); + r->ntp_sec = pj_htonl(ntp.hi); + r->ntp_frac = pj_htonl(ntp.lo); - /* Finally */ - size += sizeof(pjmedia_rtcp_xr_rb_rr_time); - sess->rx_last_rr = sess->rtcp_session->stat.rx.pkt; + /* Finally */ + size += sizeof(pjmedia_rtcp_xr_rb_rr_time); + sess->rx_last_rr = sess->rtcp_session->stat.rx.pkt; } /* DLRR Report Block */ /* Build this block if we have received RR NTP (rx_lrr) before */ if ((rpt_types == 0 || (rpt_types & PJMEDIA_RTCP_XR_DLRR)) && - sess->rx_lrr) + sess->rx_lrr) { - pjmedia_rtcp_xr_rb_dlrr *r; - pjmedia_rtcp_xr_rb_dlrr_item *dlrr_item; - pj_timestamp ts; - - r = (pjmedia_rtcp_xr_rb_dlrr*) &sess->pkt.buf[size]; - pj_bzero(r, sizeof(pjmedia_rtcp_xr_rb_dlrr)); - - /* Init block header */ - r->header.bt = BT_DLRR; - r->header.specific = 0; - r->header.length = pj_htons(sizeof(pjmedia_rtcp_xr_rb_dlrr)/4 - 1); - - /* Generate block contents */ - dlrr_item = &r->item; - dlrr_item->ssrc = pj_htonl(sess->rtcp_session->peer_ssrc); - dlrr_item->lrr = pj_htonl(sess->rx_lrr); - - /* Calculate DLRR */ - if (sess->rx_lrr != 0) { - pj_get_timestamp(&ts); - ts.u64 -= sess->rx_lrr_time.u64; - - /* Convert DLRR time to 1/65536 seconds resolution */ - ts.u64 = (ts.u64 << 16) / sess->rtcp_session->ts_freq.u64; - dlrr_item->dlrr = pj_htonl(ts.u32.lo); - } else { - dlrr_item->dlrr = 0; - } - - /* Finally */ - size += sizeof(pjmedia_rtcp_xr_rb_dlrr); + pjmedia_rtcp_xr_rb_dlrr *r; + pjmedia_rtcp_xr_rb_dlrr_item *dlrr_item; + pj_timestamp ts; + + r = (pjmedia_rtcp_xr_rb_dlrr*) &sess->pkt.buf[size]; + pj_bzero(r, sizeof(pjmedia_rtcp_xr_rb_dlrr)); + + /* Init block header */ + r->header.bt = BT_DLRR; + r->header.specific = 0; + r->header.length = pj_htons(sizeof(pjmedia_rtcp_xr_rb_dlrr)/4 - 1); + + /* Generate block contents */ + dlrr_item = &r->item; + dlrr_item->ssrc = pj_htonl(sess->rtcp_session->peer_ssrc); + dlrr_item->lrr = pj_htonl(sess->rx_lrr); + + /* Calculate DLRR */ + if (sess->rx_lrr != 0) { + pj_get_timestamp(&ts); + ts.u64 -= sess->rx_lrr_time.u64; + + /* Convert DLRR time to 1/65536 seconds resolution */ + ts.u64 = (ts.u64 << 16) / sess->rtcp_session->ts_freq.u64; + dlrr_item->dlrr = pj_htonl(ts.u32.lo); + } else { + dlrr_item->dlrr = 0; + } + + /* Finally */ + size += sizeof(pjmedia_rtcp_xr_rb_dlrr); } /* Statistics Summary Block */ /* Build this block if we have received packets since last build */ if ((rpt_types == 0 || (rpt_types & PJMEDIA_RTCP_XR_STATS)) && - sess->stat.rx.stat_sum.count > 0) + sess->stat.rx.stat_sum.count > 0) { - pjmedia_rtcp_xr_rb_stats *r; - pj_uint8_t specific = 0; - - r = (pjmedia_rtcp_xr_rb_stats*) &sess->pkt.buf[size]; - pj_bzero(r, sizeof(pjmedia_rtcp_xr_rb_stats)); - - /* Init block header */ - specific |= sess->stat.rx.stat_sum.l ? (1 << 7) : 0; - specific |= sess->stat.rx.stat_sum.d ? (1 << 6) : 0; - specific |= sess->stat.rx.stat_sum.j ? (1 << 5) : 0; - specific |= (sess->stat.rx.stat_sum.t & 3) << 3; - r->header.bt = BT_STATS; - r->header.specific = specific; - r->header.length = pj_htons(9); - - /* Generate block contents */ - r->ssrc = pj_htonl(sess->rtcp_session->peer_ssrc); - r->begin_seq = pj_htons((pj_uint16_t) - (sess->stat.rx.stat_sum.begin_seq & 0xFFFF)); - r->end_seq = pj_htons((pj_uint16_t) - (sess->stat.rx.stat_sum.end_seq & 0xFFFF)); - if (sess->stat.rx.stat_sum.l) { - r->lost = pj_htonl(sess->stat.rx.stat_sum.lost); - } - if (sess->stat.rx.stat_sum.d) { - r->dup = pj_htonl(sess->stat.rx.stat_sum.dup); - } - if (sess->stat.rx.stat_sum.j) { - r->jitter_min = pj_htonl(sess->stat.rx.stat_sum.jitter.min); - r->jitter_max = pj_htonl(sess->stat.rx.stat_sum.jitter.max); - r->jitter_mean = - pj_htonl((unsigned)sess->stat.rx.stat_sum.jitter.mean); - r->jitter_dev = - pj_htonl(pj_math_stat_get_stddev(&sess->stat.rx.stat_sum.jitter)); - } - if (sess->stat.rx.stat_sum.t) { - r->toh_min = sess->stat.rx.stat_sum.toh.min; - r->toh_max = sess->stat.rx.stat_sum.toh.max; - r->toh_mean = (unsigned) sess->stat.rx.stat_sum.toh.mean; - r->toh_dev = pj_math_stat_get_stddev(&sess->stat.rx.stat_sum.toh); - } - - /* Reset TX statistics summary each time built */ - pj_bzero(&sess->stat.rx.stat_sum, sizeof(sess->stat.rx.stat_sum)); - sess->stat.rx.stat_sum.jitter.min = (unsigned) -1; - sess->stat.rx.stat_sum.toh.min = (unsigned) -1; - - /* Finally */ - size += sizeof(pjmedia_rtcp_xr_rb_stats); - pj_gettimeofday(&sess->stat.rx.stat_sum.update); + pjmedia_rtcp_xr_rb_stats *r; + pj_uint8_t specific = 0; + + r = (pjmedia_rtcp_xr_rb_stats*) &sess->pkt.buf[size]; + pj_bzero(r, sizeof(pjmedia_rtcp_xr_rb_stats)); + + /* Init block header */ + specific |= sess->stat.rx.stat_sum.l ? (1 << 7) : 0; + specific |= sess->stat.rx.stat_sum.d ? (1 << 6) : 0; + specific |= sess->stat.rx.stat_sum.j ? (1 << 5) : 0; + specific |= (sess->stat.rx.stat_sum.t & 3) << 3; + r->header.bt = BT_STATS; + r->header.specific = specific; + r->header.length = pj_htons(9); + + /* Generate block contents */ + r->ssrc = pj_htonl(sess->rtcp_session->peer_ssrc); + r->begin_seq = pj_htons((pj_uint16_t) + (sess->stat.rx.stat_sum.begin_seq & 0xFFFF)); + r->end_seq = pj_htons((pj_uint16_t) + (sess->stat.rx.stat_sum.end_seq & 0xFFFF)); + if (sess->stat.rx.stat_sum.l) { + r->lost = pj_htonl(sess->stat.rx.stat_sum.lost); + } + if (sess->stat.rx.stat_sum.d) { + r->dup = pj_htonl(sess->stat.rx.stat_sum.dup); + } + if (sess->stat.rx.stat_sum.j) { + r->jitter_min = pj_htonl(sess->stat.rx.stat_sum.jitter.min); + r->jitter_max = pj_htonl(sess->stat.rx.stat_sum.jitter.max); + r->jitter_mean = + pj_htonl((unsigned)sess->stat.rx.stat_sum.jitter.mean); + r->jitter_dev = + pj_htonl(pj_math_stat_get_stddev(&sess->stat.rx.stat_sum.jitter)); + } + if (sess->stat.rx.stat_sum.t) { + r->toh_min = sess->stat.rx.stat_sum.toh.min; + r->toh_max = sess->stat.rx.stat_sum.toh.max; + r->toh_mean = (unsigned) sess->stat.rx.stat_sum.toh.mean; + r->toh_dev = pj_math_stat_get_stddev(&sess->stat.rx.stat_sum.toh); + } + + /* Reset TX statistics summary each time built */ + pj_bzero(&sess->stat.rx.stat_sum, sizeof(sess->stat.rx.stat_sum)); + sess->stat.rx.stat_sum.jitter.min = (unsigned) -1; + sess->stat.rx.stat_sum.toh.min = (unsigned) -1; + + /* Finally */ + size += sizeof(pjmedia_rtcp_xr_rb_stats); + pj_gettimeofday(&sess->stat.rx.stat_sum.update); } /* Voip Metrics Block */ /* Build this block if we have received packets */ if ((rpt_types == 0 || (rpt_types & PJMEDIA_RTCP_XR_VOIP_METRICS)) && - sess->rtcp_session->stat.rx.pkt) + sess->rtcp_session->stat.rx.pkt) { - pjmedia_rtcp_xr_rb_voip_mtc *r; - pj_uint32_t c11; - pj_uint32_t c13; - pj_uint32_t c14; - pj_uint32_t c22; - pj_uint32_t c23; - pj_uint32_t c31; - pj_uint32_t c32; - pj_uint32_t c33; - pj_uint32_t ctotal, m; - unsigned est_extra_delay; - - r = (pjmedia_rtcp_xr_rb_voip_mtc*) &sess->pkt.buf[size]; - pj_bzero(r, sizeof(pjmedia_rtcp_xr_rb_voip_mtc)); - - /* Init block header */ - r->header.bt = BT_VOIP_METRICS; - r->header.specific = 0; - r->header.length = pj_htons(8); - - /* Use temp vars for easiness. */ - c11 = sess->voip_mtc_stat.c11; - c13 = sess->voip_mtc_stat.c13; - c14 = sess->voip_mtc_stat.c14; - c22 = sess->voip_mtc_stat.c22; - c23 = sess->voip_mtc_stat.c23; - c33 = sess->voip_mtc_stat.c33; - m = sess->ptime * sess->frames_per_packet; - - /* Calculate additional transition counts. */ - c31 = c13; - c32 = c23; - ctotal = c11 + c14 + c13 + c22 + c23 + c31 + c32 + c33; - - if (ctotal) { - pj_uint32_t p32, p23; - - //original version: - //p32 = c32 / (c31 + c32 + c33); - if (c31 + c32 + c33 == 0) - p32 = 0; - else - p32 = (c32 << 16) / (c31 + c32 + c33); - - //original version: - //if ((c22 + c23) < 1) { - // p23 = 1; - //} else { - // p23 = 1 - c22 / (c22 + c23); - //} - if (c23 == 0) { - p23 = 0; - } else { - p23 = (c23 << 16) / (c22 + c23); - } - - /* Calculate loss/discard densities, scaled of 0-256 */ - if (c11 == 0) - sess->stat.rx.voip_mtc.gap_den = 0; - else - sess->stat.rx.voip_mtc.gap_den = (pj_uint8_t) - ((c14 << 8) / (c11 + c14)); - if (p23 == 0) - sess->stat.rx.voip_mtc.burst_den = 0; - else - sess->stat.rx.voip_mtc.burst_den = (pj_uint8_t) - ((p23 << 8) / (p23 + p32)); - - /* Calculate (average) durations, in ms */ - if (c13 == 0) { - c13 = 1; - ctotal += 1; - } - sess->stat.rx.voip_mtc.gap_dur = (pj_uint16_t) - ((c11+c14+c13) * m / c13); - sess->stat.rx.voip_mtc.burst_dur = (pj_uint16_t) - ((ctotal - (c11+c14+c13)) * m / c13); - - /* Callculate loss/discard rates, scaled 0-256 */ - sess->stat.rx.voip_mtc.loss_rate = (pj_uint8_t) - ((sess->voip_mtc_stat.loss_count << 8) / ctotal); - sess->stat.rx.voip_mtc.discard_rate = (pj_uint8_t) - ((sess->voip_mtc_stat.discard_count << 8) / ctotal); - } else { - /* No lost/discarded packet yet. */ - sess->stat.rx.voip_mtc.gap_den = 0; - sess->stat.rx.voip_mtc.burst_den = 0; - sess->stat.rx.voip_mtc.gap_dur = 0; - sess->stat.rx.voip_mtc.burst_dur = 0; - sess->stat.rx.voip_mtc.loss_rate = 0; - sess->stat.rx.voip_mtc.discard_rate = 0; - } - - /* Set round trip delay (in ms) to RTT calculated after receiving - * DLRR or DLSR. - */ - if (sess->stat.rtt.last) - sess->stat.rx.voip_mtc.rnd_trip_delay = (pj_uint16_t) - (sess->stat.rtt.last / 1000); - else if (sess->rtcp_session->stat.rtt.last) - sess->stat.rx.voip_mtc.rnd_trip_delay = (pj_uint16_t) - (sess->rtcp_session->stat.rtt.last / 1000); - - /* End system delay = RTT/2 + current jitter buffer size + - * EXTRA (estimated extra delay) - * EXTRA will cover additional delay introduced by other components of - * audio engine, e.g: sound device, codec, AEC, PLC, WSOLA. - * Since it is difficult to get the exact value of EXTRA, estimation - * is taken to be totally around 30ms + sound device latency. - */ - est_extra_delay = 30; + pjmedia_rtcp_xr_rb_voip_mtc *r; + pj_uint32_t c11; + pj_uint32_t c13; + pj_uint32_t c14; + pj_uint32_t c22; + pj_uint32_t c23; + pj_uint32_t c31; + pj_uint32_t c32; + pj_uint32_t c33; + pj_uint32_t ctotal, m; + unsigned est_extra_delay; + + r = (pjmedia_rtcp_xr_rb_voip_mtc*) &sess->pkt.buf[size]; + pj_bzero(r, sizeof(pjmedia_rtcp_xr_rb_voip_mtc)); + + /* Init block header */ + r->header.bt = BT_VOIP_METRICS; + r->header.specific = 0; + r->header.length = pj_htons(8); + + /* Use temp vars for easiness. */ + c11 = sess->voip_mtc_stat.c11; + c13 = sess->voip_mtc_stat.c13; + c14 = sess->voip_mtc_stat.c14; + c22 = sess->voip_mtc_stat.c22; + c23 = sess->voip_mtc_stat.c23; + c33 = sess->voip_mtc_stat.c33; + m = sess->ptime * sess->frames_per_packet; + + /* Calculate additional transition counts. */ + c31 = c13; + c32 = c23; + ctotal = c11 + c14 + c13 + c22 + c23 + c31 + c32 + c33; + + if (ctotal) { + pj_uint32_t p32, p23; + + //original version: + //p32 = c32 / (c31 + c32 + c33); + if (c31 + c32 + c33 == 0) + p32 = 0; + else + p32 = (c32 << 16) / (c31 + c32 + c33); + + //original version: + //if ((c22 + c23) < 1) { + // p23 = 1; + //} else { + // p23 = 1 - c22 / (c22 + c23); + //} + if (c23 == 0) { + p23 = 0; + } else { + p23 = (c23 << 16) / (c22 + c23); + } + + /* Calculate loss/discard densities, scaled of 0-256 */ + if (c11 == 0) + sess->stat.rx.voip_mtc.gap_den = 0; + else + sess->stat.rx.voip_mtc.gap_den = (pj_uint8_t) + ((c14 << 8) / (c11 + c14)); + if (p23 == 0) + sess->stat.rx.voip_mtc.burst_den = 0; + else + sess->stat.rx.voip_mtc.burst_den = (pj_uint8_t) + ((p23 << 8) / (p23 + p32)); + + /* Calculate (average) durations, in ms */ + if (c13 == 0) { + c13 = 1; + ctotal += 1; + } + sess->stat.rx.voip_mtc.gap_dur = (pj_uint16_t) + ((c11+c14+c13) * m / c13); + sess->stat.rx.voip_mtc.burst_dur = (pj_uint16_t) + ((ctotal - (c11+c14+c13)) * m / c13); + + /* Callculate loss/discard rates, scaled 0-256 */ + sess->stat.rx.voip_mtc.loss_rate = (pj_uint8_t) + ((sess->voip_mtc_stat.loss_count << 8) / ctotal); + sess->stat.rx.voip_mtc.discard_rate = (pj_uint8_t) + ((sess->voip_mtc_stat.discard_count << 8) / ctotal); + } else { + /* No lost/discarded packet yet. */ + sess->stat.rx.voip_mtc.gap_den = 0; + sess->stat.rx.voip_mtc.burst_den = 0; + sess->stat.rx.voip_mtc.gap_dur = 0; + sess->stat.rx.voip_mtc.burst_dur = 0; + sess->stat.rx.voip_mtc.loss_rate = 0; + sess->stat.rx.voip_mtc.discard_rate = 0; + } + + /* Set round trip delay (in ms) to RTT calculated after receiving + * DLRR or DLSR. + */ + if (sess->stat.rtt.last) + sess->stat.rx.voip_mtc.rnd_trip_delay = (pj_uint16_t) + (sess->stat.rtt.last / 1000); + else if (sess->rtcp_session->stat.rtt.last) + sess->stat.rx.voip_mtc.rnd_trip_delay = (pj_uint16_t) + (sess->rtcp_session->stat.rtt.last / 1000); + + /* End system delay = RTT/2 + current jitter buffer size + + * EXTRA (estimated extra delay) + * EXTRA will cover additional delay introduced by other components of + * audio engine, e.g: sound device, codec, AEC, PLC, WSOLA. + * Since it is difficult to get the exact value of EXTRA, estimation + * is taken to be totally around 30ms + sound device latency. + */ + est_extra_delay = 30; #if !PJMEDIA_AUDIO_DEV_HAS_NULL_AUDIO - est_extra_delay += PJMEDIA_SND_DEFAULT_REC_LATENCY + - PJMEDIA_SND_DEFAULT_PLAY_LATENCY; + est_extra_delay += PJMEDIA_SND_DEFAULT_REC_LATENCY + + PJMEDIA_SND_DEFAULT_PLAY_LATENCY; #endif - sess->stat.rx.voip_mtc.end_sys_delay = (pj_uint16_t) - (sess->stat.rx.voip_mtc.rnd_trip_delay / 2 + - sess->stat.rx.voip_mtc.jb_nom + - est_extra_delay); - - /* Generate block contents */ - r->ssrc = pj_htonl(sess->rtcp_session->peer_ssrc); - r->loss_rate = sess->stat.rx.voip_mtc.loss_rate; - r->discard_rate = sess->stat.rx.voip_mtc.discard_rate; - r->burst_den = sess->stat.rx.voip_mtc.burst_den; - r->gap_den = sess->stat.rx.voip_mtc.gap_den; - r->burst_dur = pj_htons(sess->stat.rx.voip_mtc.burst_dur); - r->gap_dur = pj_htons(sess->stat.rx.voip_mtc.gap_dur); - r->rnd_trip_delay = pj_htons(sess->stat.rx.voip_mtc.rnd_trip_delay); - r->end_sys_delay = pj_htons(sess->stat.rx.voip_mtc.end_sys_delay); - /* signal & noise level encoded in two's complement form */ - r->signal_lvl = (pj_uint8_t) - ((sess->stat.rx.voip_mtc.signal_lvl >= 0)? - sess->stat.rx.voip_mtc.signal_lvl : - (sess->stat.rx.voip_mtc.signal_lvl + 256)); - r->noise_lvl = (pj_uint8_t) - ((sess->stat.rx.voip_mtc.noise_lvl >= 0)? - sess->stat.rx.voip_mtc.noise_lvl : - (sess->stat.rx.voip_mtc.noise_lvl + 256)); - r->rerl = sess->stat.rx.voip_mtc.rerl; - r->gmin = sess->stat.rx.voip_mtc.gmin; - r->r_factor = sess->stat.rx.voip_mtc.r_factor; - r->ext_r_factor = sess->stat.rx.voip_mtc.ext_r_factor; - r->mos_lq = sess->stat.rx.voip_mtc.mos_lq; - r->mos_cq = sess->stat.rx.voip_mtc.mos_cq; - r->rx_config = sess->stat.rx.voip_mtc.rx_config; - r->jb_nom = pj_htons(sess->stat.rx.voip_mtc.jb_nom); - r->jb_max = pj_htons(sess->stat.rx.voip_mtc.jb_max); - r->jb_abs_max = pj_htons(sess->stat.rx.voip_mtc.jb_abs_max); - - /* Finally */ - size += sizeof(pjmedia_rtcp_xr_rb_voip_mtc); - pj_gettimeofday(&sess->stat.rx.voip_mtc.update); + sess->stat.rx.voip_mtc.end_sys_delay = (pj_uint16_t) + (sess->stat.rx.voip_mtc.rnd_trip_delay / 2 + + sess->stat.rx.voip_mtc.jb_nom + + est_extra_delay); + + /* Generate block contents */ + r->ssrc = pj_htonl(sess->rtcp_session->peer_ssrc); + r->loss_rate = sess->stat.rx.voip_mtc.loss_rate; + r->discard_rate = sess->stat.rx.voip_mtc.discard_rate; + r->burst_den = sess->stat.rx.voip_mtc.burst_den; + r->gap_den = sess->stat.rx.voip_mtc.gap_den; + r->burst_dur = pj_htons(sess->stat.rx.voip_mtc.burst_dur); + r->gap_dur = pj_htons(sess->stat.rx.voip_mtc.gap_dur); + r->rnd_trip_delay = pj_htons(sess->stat.rx.voip_mtc.rnd_trip_delay); + r->end_sys_delay = pj_htons(sess->stat.rx.voip_mtc.end_sys_delay); + /* signal & noise level encoded in two's complement form */ + r->signal_lvl = (pj_uint8_t) + ((sess->stat.rx.voip_mtc.signal_lvl >= 0)? + sess->stat.rx.voip_mtc.signal_lvl : + (sess->stat.rx.voip_mtc.signal_lvl + 256)); + r->noise_lvl = (pj_uint8_t) + ((sess->stat.rx.voip_mtc.noise_lvl >= 0)? + sess->stat.rx.voip_mtc.noise_lvl : + (sess->stat.rx.voip_mtc.noise_lvl + 256)); + r->rerl = sess->stat.rx.voip_mtc.rerl; + r->gmin = sess->stat.rx.voip_mtc.gmin; + r->r_factor = sess->stat.rx.voip_mtc.r_factor; + r->ext_r_factor = sess->stat.rx.voip_mtc.ext_r_factor; + r->mos_lq = sess->stat.rx.voip_mtc.mos_lq; + r->mos_cq = sess->stat.rx.voip_mtc.mos_cq; + r->rx_config = sess->stat.rx.voip_mtc.rx_config; + r->jb_nom = pj_htons(sess->stat.rx.voip_mtc.jb_nom); + r->jb_max = pj_htons(sess->stat.rx.voip_mtc.jb_max); + r->jb_abs_max = pj_htons(sess->stat.rx.voip_mtc.jb_abs_max); + + /* Finally */ + size += sizeof(pjmedia_rtcp_xr_rb_voip_mtc); + pj_gettimeofday(&sess->stat.rx.voip_mtc.update); } /* Add RTCP XR header size */ @@ -407,234 +406,234 @@ PJ_DEF(void) pjmedia_rtcp_build_rtcp_xr( pjmedia_rtcp_xr_session *sess, void pjmedia_rtcp_xr_rx_rtcp_xr( pjmedia_rtcp_xr_session *sess, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { - const pjmedia_rtcp_xr_pkt *rtcp_xr = (pjmedia_rtcp_xr_pkt*) pkt; + const pjmedia_rtcp_xr_pkt *rtcp_xr = (pjmedia_rtcp_xr_pkt*) pkt; const pjmedia_rtcp_xr_rb_rr_time *rb_rr_time = NULL; const pjmedia_rtcp_xr_rb_dlrr *rb_dlrr = NULL; const pjmedia_rtcp_xr_rb_stats *rb_stats = NULL; const pjmedia_rtcp_xr_rb_voip_mtc *rb_voip_mtc = NULL; const pjmedia_rtcp_xr_rb_header *rb_hdr = (pjmedia_rtcp_xr_rb_header*) - rtcp_xr->buf; + rtcp_xr->buf; unsigned pkt_len, rb_len; if (rtcp_xr->common.pt != RTCP_XR) - return; + return; pkt_len = pj_ntohs((pj_uint16_t)rtcp_xr->common.length); if ((pkt_len + 1) > (size / 4)) - return; + return; /* Parse report rpt_types */ while ((pj_int32_t*)rb_hdr < (pj_int32_t*)pkt + pkt_len) - { - rb_len = pj_ntohs((pj_uint16_t)rb_hdr->length); - - /* Just skip any block with length == 0 (no report content) */ - if (rb_len) { - switch (rb_hdr->bt) { - case BT_RR_TIME: - if ((char*)rb_hdr + sizeof(*rb_rr_time) <= - (char*)pkt + size) - { - rb_rr_time = (pjmedia_rtcp_xr_rb_rr_time*)rb_hdr; - } - break; - case BT_DLRR: - if ((char*)rb_hdr + sizeof(*rb_dlrr) <= - (char*)pkt + size) - { - rb_dlrr = (pjmedia_rtcp_xr_rb_dlrr*)rb_hdr; - } - break; - case BT_STATS: - if ((char*)rb_hdr + sizeof(*rb_stats) <= - (char*)pkt + size) - { - rb_stats = (pjmedia_rtcp_xr_rb_stats*)rb_hdr; - } - break; - case BT_VOIP_METRICS: - if ((char*)rb_hdr + sizeof(*rb_voip_mtc) <= - (char*)pkt + size) - { - rb_voip_mtc = (pjmedia_rtcp_xr_rb_voip_mtc*)rb_hdr; - } - break; - default: - break; - } - } - rb_hdr = (pjmedia_rtcp_xr_rb_header*) - ((pj_int32_t*)rb_hdr + rb_len + 1); + { + rb_len = pj_ntohs((pj_uint16_t)rb_hdr->length); + + /* Just skip any block with length == 0 (no report content) */ + if (rb_len) { + switch (rb_hdr->bt) { + case BT_RR_TIME: + if ((char*)rb_hdr + sizeof(*rb_rr_time) <= + (char*)pkt + size) + { + rb_rr_time = (pjmedia_rtcp_xr_rb_rr_time*)rb_hdr; + } + break; + case BT_DLRR: + if ((char*)rb_hdr + sizeof(*rb_dlrr) <= + (char*)pkt + size) + { + rb_dlrr = (pjmedia_rtcp_xr_rb_dlrr*)rb_hdr; + } + break; + case BT_STATS: + if ((char*)rb_hdr + sizeof(*rb_stats) <= + (char*)pkt + size) + { + rb_stats = (pjmedia_rtcp_xr_rb_stats*)rb_hdr; + } + break; + case BT_VOIP_METRICS: + if ((char*)rb_hdr + sizeof(*rb_voip_mtc) <= + (char*)pkt + size) + { + rb_voip_mtc = (pjmedia_rtcp_xr_rb_voip_mtc*)rb_hdr; + } + break; + default: + break; + } + } + rb_hdr = (pjmedia_rtcp_xr_rb_header*) + ((pj_int32_t*)rb_hdr + rb_len + 1); } /* Receiving RR Time */ if (rb_rr_time) { - /* Save LRR from NTP timestamp of the RR time block report */ - sess->rx_lrr = ((pj_ntohl(rb_rr_time->ntp_sec) & 0x0000FFFF) << 16) | - ((pj_ntohl(rb_rr_time->ntp_frac) >> 16) & 0xFFFF); + /* Save LRR from NTP timestamp of the RR time block report */ + sess->rx_lrr = ((pj_ntohl(rb_rr_time->ntp_sec) & 0x0000FFFF) << 16) | + ((pj_ntohl(rb_rr_time->ntp_frac) >> 16) & 0xFFFF); - /* Calculate RR arrival time for DLRR */ - pj_get_timestamp(&sess->rx_lrr_time); + /* Calculate RR arrival time for DLRR */ + pj_get_timestamp(&sess->rx_lrr_time); - TRACE_((sess->name, "Rx RTCP SR: ntp_ts=%p", sess->rx_lrr, - (pj_uint32_t)(sess->rx_lrr_time.u64*65536/ - sess->rtcp_session->ts_freq.u64))); + TRACE_((sess->name, "Rx RTCP SR: ntp_ts=%p", sess->rx_lrr, + (pj_uint32_t)(sess->rx_lrr_time.u64*65536/ + sess->rtcp_session->ts_freq.u64))); } /* Receiving DLRR */ if (rb_dlrr) { - pj_uint32_t lrr, now, dlrr; - pj_uint64_t eedelay; - pjmedia_rtcp_ntp_rec ntp; + pj_uint32_t lrr, now, dlrr; + pj_uint64_t eedelay; + pjmedia_rtcp_ntp_rec ntp; - /* LRR is the middle 32bit of NTP. It has 1/65536 second - * resolution - */ - lrr = pj_ntohl(rb_dlrr->item.lrr); + /* LRR is the middle 32bit of NTP. It has 1/65536 second + * resolution + */ + lrr = pj_ntohl(rb_dlrr->item.lrr); - /* DLRR is delay since LRR, also in 1/65536 resolution */ - dlrr = pj_ntohl(rb_dlrr->item.dlrr); + /* DLRR is delay since LRR, also in 1/65536 resolution */ + dlrr = pj_ntohl(rb_dlrr->item.dlrr); - /* Get current time, and convert to 1/65536 resolution */ - pjmedia_rtcp_get_ntp_time(sess->rtcp_session, &ntp); - now = ((ntp.hi & 0xFFFF) << 16) + (ntp.lo >> 16); + /* Get current time, and convert to 1/65536 resolution */ + pjmedia_rtcp_get_ntp_time(sess->rtcp_session, &ntp); + now = ((ntp.hi & 0xFFFF) << 16) + (ntp.lo >> 16); - /* End-to-end delay is (now-lrr-dlrr) */ - eedelay = now - lrr - dlrr; + /* End-to-end delay is (now-lrr-dlrr) */ + eedelay = now - lrr - dlrr; - /* Convert end to end delay to usec (keeping the calculation in + /* Convert end to end delay to usec (keeping the calculation in * 64bit space):: - * sess->ee_delay = (eedelay * 1000) / 65536; - */ - if (eedelay < 4294) { - eedelay = (eedelay * 1000000) >> 16; - } else { - eedelay = (eedelay * 1000) >> 16; - eedelay *= 1000; - } - - TRACE_((sess->name, "Rx RTCP XR DLRR: lrr=%p, dlrr=%p (%d:%03dms), " - "now=%p, rtt=%p", - lrr, dlrr, dlrr/65536, (dlrr%65536)*1000/65536, - now, (pj_uint32_t)eedelay)); - - /* Only save calculation if "now" is greater than lrr, or - * otherwise rtt will be invalid - */ - if (now-dlrr >= lrr) { - unsigned rtt = (pj_uint32_t)eedelay; - - /* Check that eedelay value really makes sense. - * We allow up to 30 seconds RTT! - */ - if (eedelay <= 30 * 1000 * 1000UL) { - /* "Normalize" rtt value that is exceptionally high. - * For such values, "normalize" the rtt to be three times - * the average value. - */ - if (rtt>((unsigned)sess->stat.rtt.mean*3) && sess->stat.rtt.n!=0) - { - unsigned orig_rtt = rtt; - rtt = (unsigned)sess->stat.rtt.mean*3; - PJ_LOG(5,(sess->name, - "RTT value %d usec is normalized to %d usec", - orig_rtt, rtt)); - } - - TRACE_((sess->name, "RTCP RTT is set to %d usec", rtt)); - pj_math_stat_update(&sess->stat.rtt, rtt); - } - } else { - PJ_LOG(5, (sess->name, "Internal RTCP NTP clock skew detected: " - "lrr=%p, now=%p, dlrr=%p (%d:%03dms), " - "diff=%d", - lrr, now, dlrr, dlrr/65536, - (dlrr%65536)*1000/65536, - dlrr-(now-lrr))); - } + * sess->ee_delay = (eedelay * 1000) / 65536; + */ + if (eedelay < 4294) { + eedelay = (eedelay * 1000000) >> 16; + } else { + eedelay = (eedelay * 1000) >> 16; + eedelay *= 1000; + } + + TRACE_((sess->name, "Rx RTCP XR DLRR: lrr=%p, dlrr=%p (%d:%03dms), " + "now=%p, rtt=%p", + lrr, dlrr, dlrr/65536, (dlrr%65536)*1000/65536, + now, (pj_uint32_t)eedelay)); + + /* Only save calculation if "now" is greater than lrr, or + * otherwise rtt will be invalid + */ + if (now-dlrr >= lrr) { + unsigned rtt = (pj_uint32_t)eedelay; + + /* Check that eedelay value really makes sense. + * We allow up to 30 seconds RTT! + */ + if (eedelay <= 30 * 1000 * 1000UL) { + /* "Normalize" rtt value that is exceptionally high. + * For such values, "normalize" the rtt to be three times + * the average value. + */ + if (rtt>((unsigned)sess->stat.rtt.mean*3) && sess->stat.rtt.n!=0) + { + unsigned orig_rtt = rtt; + rtt = (unsigned)sess->stat.rtt.mean*3; + PJ_LOG(5,(sess->name, + "RTT value %d usec is normalized to %d usec", + orig_rtt, rtt)); + } + + TRACE_((sess->name, "RTCP RTT is set to %d usec", rtt)); + pj_math_stat_update(&sess->stat.rtt, rtt); + } + } else { + PJ_LOG(5, (sess->name, "Internal RTCP NTP clock skew detected: " + "lrr=%p, now=%p, dlrr=%p (%d:%03dms), " + "diff=%d", + lrr, now, dlrr, dlrr/65536, + (dlrr%65536)*1000/65536, + dlrr-(now-lrr))); + } } /* Receiving Statistics Summary */ if (rb_stats) { - pj_uint8_t flags = rb_stats->header.specific; - - pj_bzero(&sess->stat.tx.stat_sum, sizeof(sess->stat.tx.stat_sum)); - - /* Range of packets sequence reported in this blocks */ - sess->stat.tx.stat_sum.begin_seq = pj_ntohs(rb_stats->begin_seq); - sess->stat.tx.stat_sum.end_seq = pj_ntohs(rb_stats->end_seq); - - /* Get flags of valid fields */ - sess->stat.tx.stat_sum.l = (flags & (1 << 7)) != 0; - sess->stat.tx.stat_sum.d = (flags & (1 << 6)) != 0; - sess->stat.tx.stat_sum.j = (flags & (1 << 5)) != 0; - sess->stat.tx.stat_sum.t = (flags & (3 << 3)) != 0; - - /* Fetch the reports info */ - if (sess->stat.tx.stat_sum.l) { - sess->stat.tx.stat_sum.lost = pj_ntohl(rb_stats->lost); - } - - if (sess->stat.tx.stat_sum.d) { - sess->stat.tx.stat_sum.dup = pj_ntohl(rb_stats->dup); - } - - if (sess->stat.tx.stat_sum.j) { - sess->stat.tx.stat_sum.jitter.min = pj_ntohl(rb_stats->jitter_min); - sess->stat.tx.stat_sum.jitter.max = pj_ntohl(rb_stats->jitter_max); - sess->stat.tx.stat_sum.jitter.mean= pj_ntohl(rb_stats->jitter_mean); - pj_math_stat_set_stddev(&sess->stat.tx.stat_sum.jitter, - pj_ntohl(rb_stats->jitter_dev)); - } - - if (sess->stat.tx.stat_sum.t) { - sess->stat.tx.stat_sum.toh.min = rb_stats->toh_min; - sess->stat.tx.stat_sum.toh.max = rb_stats->toh_max; - sess->stat.tx.stat_sum.toh.mean= rb_stats->toh_mean; - pj_math_stat_set_stddev(&sess->stat.tx.stat_sum.toh, - pj_ntohl(rb_stats->toh_dev)); - } - - pj_gettimeofday(&sess->stat.tx.stat_sum.update); + pj_uint8_t flags = rb_stats->header.specific; + + pj_bzero(&sess->stat.tx.stat_sum, sizeof(sess->stat.tx.stat_sum)); + + /* Range of packets sequence reported in this blocks */ + sess->stat.tx.stat_sum.begin_seq = pj_ntohs(rb_stats->begin_seq); + sess->stat.tx.stat_sum.end_seq = pj_ntohs(rb_stats->end_seq); + + /* Get flags of valid fields */ + sess->stat.tx.stat_sum.l = (flags & (1 << 7)) != 0; + sess->stat.tx.stat_sum.d = (flags & (1 << 6)) != 0; + sess->stat.tx.stat_sum.j = (flags & (1 << 5)) != 0; + sess->stat.tx.stat_sum.t = (flags & (3 << 3)) != 0; + + /* Fetch the reports info */ + if (sess->stat.tx.stat_sum.l) { + sess->stat.tx.stat_sum.lost = pj_ntohl(rb_stats->lost); + } + + if (sess->stat.tx.stat_sum.d) { + sess->stat.tx.stat_sum.dup = pj_ntohl(rb_stats->dup); + } + + if (sess->stat.tx.stat_sum.j) { + sess->stat.tx.stat_sum.jitter.min = pj_ntohl(rb_stats->jitter_min); + sess->stat.tx.stat_sum.jitter.max = pj_ntohl(rb_stats->jitter_max); + sess->stat.tx.stat_sum.jitter.mean= pj_ntohl(rb_stats->jitter_mean); + pj_math_stat_set_stddev(&sess->stat.tx.stat_sum.jitter, + pj_ntohl(rb_stats->jitter_dev)); + } + + if (sess->stat.tx.stat_sum.t) { + sess->stat.tx.stat_sum.toh.min = rb_stats->toh_min; + sess->stat.tx.stat_sum.toh.max = rb_stats->toh_max; + sess->stat.tx.stat_sum.toh.mean= rb_stats->toh_mean; + pj_math_stat_set_stddev(&sess->stat.tx.stat_sum.toh, + pj_ntohl(rb_stats->toh_dev)); + } + + pj_gettimeofday(&sess->stat.tx.stat_sum.update); } /* Receiving VoIP Metrics */ if (rb_voip_mtc) { - sess->stat.tx.voip_mtc.loss_rate = rb_voip_mtc->loss_rate; - sess->stat.tx.voip_mtc.discard_rate = rb_voip_mtc->discard_rate; - sess->stat.tx.voip_mtc.burst_den = rb_voip_mtc->burst_den; - sess->stat.tx.voip_mtc.gap_den = rb_voip_mtc->gap_den; - sess->stat.tx.voip_mtc.burst_dur = pj_ntohs(rb_voip_mtc->burst_dur); - sess->stat.tx.voip_mtc.gap_dur = pj_ntohs(rb_voip_mtc->gap_dur); - sess->stat.tx.voip_mtc.rnd_trip_delay = - pj_ntohs(rb_voip_mtc->rnd_trip_delay); - sess->stat.tx.voip_mtc.end_sys_delay = - pj_ntohs(rb_voip_mtc->end_sys_delay); - /* signal & noise level encoded in two's complement form */ - sess->stat.tx.voip_mtc.signal_lvl = (pj_int8_t) - ((rb_voip_mtc->signal_lvl > 127)? - ((int)rb_voip_mtc->signal_lvl - 256) : - rb_voip_mtc->signal_lvl); - sess->stat.tx.voip_mtc.noise_lvl = (pj_int8_t) - ((rb_voip_mtc->noise_lvl > 127)? - ((int)rb_voip_mtc->noise_lvl - 256) : - rb_voip_mtc->noise_lvl); - sess->stat.tx.voip_mtc.rerl = rb_voip_mtc->rerl; - sess->stat.tx.voip_mtc.gmin = rb_voip_mtc->gmin; - sess->stat.tx.voip_mtc.r_factor = rb_voip_mtc->r_factor; - sess->stat.tx.voip_mtc.ext_r_factor = rb_voip_mtc->ext_r_factor; - sess->stat.tx.voip_mtc.mos_lq = rb_voip_mtc->mos_lq; - sess->stat.tx.voip_mtc.mos_cq = rb_voip_mtc->mos_cq; - sess->stat.tx.voip_mtc.rx_config = rb_voip_mtc->rx_config; - sess->stat.tx.voip_mtc.jb_nom = pj_ntohs(rb_voip_mtc->jb_nom); - sess->stat.tx.voip_mtc.jb_max = pj_ntohs(rb_voip_mtc->jb_max); - sess->stat.tx.voip_mtc.jb_abs_max = pj_ntohs(rb_voip_mtc->jb_abs_max); - - pj_gettimeofday(&sess->stat.tx.voip_mtc.update); + sess->stat.tx.voip_mtc.loss_rate = rb_voip_mtc->loss_rate; + sess->stat.tx.voip_mtc.discard_rate = rb_voip_mtc->discard_rate; + sess->stat.tx.voip_mtc.burst_den = rb_voip_mtc->burst_den; + sess->stat.tx.voip_mtc.gap_den = rb_voip_mtc->gap_den; + sess->stat.tx.voip_mtc.burst_dur = pj_ntohs(rb_voip_mtc->burst_dur); + sess->stat.tx.voip_mtc.gap_dur = pj_ntohs(rb_voip_mtc->gap_dur); + sess->stat.tx.voip_mtc.rnd_trip_delay = + pj_ntohs(rb_voip_mtc->rnd_trip_delay); + sess->stat.tx.voip_mtc.end_sys_delay = + pj_ntohs(rb_voip_mtc->end_sys_delay); + /* signal & noise level encoded in two's complement form */ + sess->stat.tx.voip_mtc.signal_lvl = (pj_int8_t) + ((rb_voip_mtc->signal_lvl > 127)? + ((int)rb_voip_mtc->signal_lvl - 256) : + rb_voip_mtc->signal_lvl); + sess->stat.tx.voip_mtc.noise_lvl = (pj_int8_t) + ((rb_voip_mtc->noise_lvl > 127)? + ((int)rb_voip_mtc->noise_lvl - 256) : + rb_voip_mtc->noise_lvl); + sess->stat.tx.voip_mtc.rerl = rb_voip_mtc->rerl; + sess->stat.tx.voip_mtc.gmin = rb_voip_mtc->gmin; + sess->stat.tx.voip_mtc.r_factor = rb_voip_mtc->r_factor; + sess->stat.tx.voip_mtc.ext_r_factor = rb_voip_mtc->ext_r_factor; + sess->stat.tx.voip_mtc.mos_lq = rb_voip_mtc->mos_lq; + sess->stat.tx.voip_mtc.mos_cq = rb_voip_mtc->mos_cq; + sess->stat.tx.voip_mtc.rx_config = rb_voip_mtc->rx_config; + sess->stat.tx.voip_mtc.jb_nom = pj_ntohs(rb_voip_mtc->jb_nom); + sess->stat.tx.voip_mtc.jb_max = pj_ntohs(rb_voip_mtc->jb_max); + sess->stat.tx.voip_mtc.jb_abs_max = pj_ntohs(rb_voip_mtc->jb_abs_max); + + pj_gettimeofday(&sess->stat.tx.voip_mtc.update); } } @@ -642,49 +641,49 @@ void pjmedia_rtcp_xr_rx_rtcp_xr( pjmedia_rtcp_xr_session *sess, * heuristic for its most likely location. */ static pj_uint32_t extend_seq(pjmedia_rtcp_xr_session *sess, - const pj_uint16_t seq) + const pj_uint16_t seq) { pj_uint32_t extended_seq, seq_a, seq_b, diff_a, diff_b; if(sess->uninitialized_src_ref_seq) { - /* This is the first sequence number received. Place - * it in the middle of the extended sequence number - * space. - */ - sess->src_ref_seq = seq | 0x80000000u; - sess->uninitialized_src_ref_seq = PJ_FALSE; - extended_seq = sess->src_ref_seq; + /* This is the first sequence number received. Place + * it in the middle of the extended sequence number + * space. + */ + sess->src_ref_seq = seq | 0x80000000u; + sess->uninitialized_src_ref_seq = PJ_FALSE; + extended_seq = sess->src_ref_seq; } else { - /* Prior sequence numbers have been received. - * Propose two candidates for the extended sequence - * number: seq_a is without wraparound, seq_b with - * wraparound. - */ - seq_a = seq | (sess->src_ref_seq & 0xFFFF0000u); - if(sess->src_ref_seq < seq_a) { - seq_b = seq_a - 0x00010000u; - diff_a = seq_a - sess->src_ref_seq; - diff_b = sess->src_ref_seq - seq_b; - } else { - seq_b = seq_a + 0x00010000u; - diff_a = sess->src_ref_seq - seq_a; - diff_b = seq_b - sess->src_ref_seq; - } - - /* Choose the closer candidate. If they are equally - * close, the choice is somewhat arbitrary: we choose - * the candidate for which no rollover is necessary. - */ - if(diff_a < diff_b) { - extended_seq = seq_a; - } else { - extended_seq = seq_b; - } - - /* Set the reference sequence number to be this most - * recently-received sequence number. - */ - sess->src_ref_seq = extended_seq; + /* Prior sequence numbers have been received. + * Propose two candidates for the extended sequence + * number: seq_a is without wraparound, seq_b with + * wraparound. + */ + seq_a = seq | (sess->src_ref_seq & 0xFFFF0000u); + if(sess->src_ref_seq < seq_a) { + seq_b = seq_a - 0x00010000u; + diff_a = seq_a - sess->src_ref_seq; + diff_b = sess->src_ref_seq - seq_b; + } else { + seq_b = seq_a + 0x00010000u; + diff_a = sess->src_ref_seq - seq_a; + diff_b = seq_b - sess->src_ref_seq; + } + + /* Choose the closer candidate. If they are equally + * close, the choice is somewhat arbitrary: we choose + * the candidate for which no rollover is necessary. + */ + if(diff_a < diff_b) { + extended_seq = seq_a; + } else { + extended_seq = seq_b; + } + + /* Set the reference sequence number to be this most + * recently-received sequence number. + */ + sess->src_ref_seq = extended_seq; } /* Return our best guess for a 32-bit sequence number that @@ -694,12 +693,12 @@ static pj_uint32_t extend_seq(pjmedia_rtcp_xr_session *sess, } void pjmedia_rtcp_xr_rx_rtp( pjmedia_rtcp_xr_session *sess, - unsigned seq, - int lost, - int dup, - int discarded, - int jitter, - int toh, pj_bool_t toh_ipv4) + unsigned seq, + int lost, + int dup, + int discarded, + int jitter, + int toh, pj_bool_t toh_ipv4) { pj_uint32_t ext_seq; @@ -710,37 +709,37 @@ void pjmedia_rtcp_xr_rx_rtp( pjmedia_rtcp_xr_session *sess, sess->stat.rx.stat_sum.count++; if (sess->stat.rx.stat_sum.begin_seq == 0 || - sess->stat.rx.stat_sum.begin_seq > ext_seq) + sess->stat.rx.stat_sum.begin_seq > ext_seq) { - sess->stat.rx.stat_sum.begin_seq = ext_seq; + sess->stat.rx.stat_sum.begin_seq = ext_seq; } if (sess->stat.rx.stat_sum.end_seq == 0 || - sess->stat.rx.stat_sum.end_seq < ext_seq) + sess->stat.rx.stat_sum.end_seq < ext_seq) { - sess->stat.rx.stat_sum.end_seq = ext_seq; + sess->stat.rx.stat_sum.end_seq = ext_seq; } if (lost >= 0) { - sess->stat.rx.stat_sum.l = PJ_TRUE; - if (lost > 0) - sess->stat.rx.stat_sum.lost++; + sess->stat.rx.stat_sum.l = PJ_TRUE; + if (lost > 0) + sess->stat.rx.stat_sum.lost++; } if (dup >= 0) { - sess->stat.rx.stat_sum.d = PJ_TRUE; - if (dup > 0) - sess->stat.rx.stat_sum.dup++; + sess->stat.rx.stat_sum.d = PJ_TRUE; + if (dup > 0) + sess->stat.rx.stat_sum.dup++; } if (jitter >= 0) { - sess->stat.rx.stat_sum.j = PJ_TRUE; - pj_math_stat_update(&sess->stat.rx.stat_sum.jitter, jitter); + sess->stat.rx.stat_sum.j = PJ_TRUE; + pj_math_stat_update(&sess->stat.rx.stat_sum.jitter, jitter); } if (toh >= 0) { - sess->stat.rx.stat_sum.t = toh_ipv4? 1 : 2; - pj_math_stat_update(&sess->stat.rx.stat_sum.toh, toh); + sess->stat.rx.stat_sum.t = toh_ipv4? 1 : 2; + pj_math_stat_update(&sess->stat.rx.stat_sum.toh, toh); } /* Update burst metrics. @@ -749,123 +748,123 @@ void pjmedia_rtcp_xr_rx_rtp( pjmedia_rtcp_xr_session *sess, * Burst represents the opposite, lost+discard rate > 1/Gmin. */ if (lost >= 0 && discarded >= 0) { - if(lost > 0) { - sess->voip_mtc_stat.loss_count++; - } - if(discarded > 0) { - sess->voip_mtc_stat.discard_count++; - } - if(!lost && !discarded) { - /* Number of good packets since last lost/discarded */ - sess->voip_mtc_stat.pkt++; - } - else { - if(sess->voip_mtc_stat.pkt >= sess->stat.rx.voip_mtc.gmin) { - /* Gap condition */ - if(sess->voip_mtc_stat.lost == 1) { - /* Gap -> Gap */ - sess->voip_mtc_stat.c14++; - } - else { - /* Burst -> Gap */ - sess->voip_mtc_stat.c13++; - } - sess->voip_mtc_stat.lost = 1; - sess->voip_mtc_stat.c11 += sess->voip_mtc_stat.pkt; - } - else { - /* Burst condition */ - sess->voip_mtc_stat.lost++; - if(sess->voip_mtc_stat.pkt == 0) { - /* Consecutive losts */ - sess->voip_mtc_stat.c33++; - } - else { - /* Any good packets, but still bursting */ - sess->voip_mtc_stat.c23++; - sess->voip_mtc_stat.c22 += (sess->voip_mtc_stat.pkt - 1); - } - } - - sess->voip_mtc_stat.pkt = 0; - } + if(lost > 0) { + sess->voip_mtc_stat.loss_count++; + } + if(discarded > 0) { + sess->voip_mtc_stat.discard_count++; + } + if(!lost && !discarded) { + /* Number of good packets since last lost/discarded */ + sess->voip_mtc_stat.pkt++; + } + else { + if(sess->voip_mtc_stat.pkt >= sess->stat.rx.voip_mtc.gmin) { + /* Gap condition */ + if(sess->voip_mtc_stat.lost == 1) { + /* Gap -> Gap */ + sess->voip_mtc_stat.c14++; + } + else { + /* Burst -> Gap */ + sess->voip_mtc_stat.c13++; + } + sess->voip_mtc_stat.lost = 1; + sess->voip_mtc_stat.c11 += sess->voip_mtc_stat.pkt; + } + else { + /* Burst condition */ + sess->voip_mtc_stat.lost++; + if(sess->voip_mtc_stat.pkt == 0) { + /* Consecutive losts */ + sess->voip_mtc_stat.c33++; + } + else { + /* Any good packets, but still bursting */ + sess->voip_mtc_stat.c23++; + sess->voip_mtc_stat.c22 += (sess->voip_mtc_stat.pkt - 1); + } + } + + sess->voip_mtc_stat.pkt = 0; + } } } void pjmedia_rtcp_xr_tx_rtp( pjmedia_rtcp_xr_session *session, - unsigned ptsize ) + unsigned ptsize ) { PJ_UNUSED_ARG(session); PJ_UNUSED_ARG(ptsize); } PJ_DEF(pj_status_t) pjmedia_rtcp_xr_update_info( - pjmedia_rtcp_xr_session *sess, - unsigned info, - pj_int32_t val) + pjmedia_rtcp_xr_session *sess, + unsigned info, + pj_int32_t val) { int v = val; switch(info) { - case PJMEDIA_RTCP_XR_INFO_SIGNAL_LVL: - sess->stat.rx.voip_mtc.signal_lvl = (pj_int8_t) v; - break; - - case PJMEDIA_RTCP_XR_INFO_NOISE_LVL: - sess->stat.rx.voip_mtc.noise_lvl = (pj_int8_t) v; - break; - - case PJMEDIA_RTCP_XR_INFO_RERL: - sess->stat.rx.voip_mtc.rerl = (pj_uint8_t) v; - break; - - case PJMEDIA_RTCP_XR_INFO_R_FACTOR: - sess->stat.rx.voip_mtc.ext_r_factor = (pj_uint8_t) v; - break; - - case PJMEDIA_RTCP_XR_INFO_MOS_LQ: - sess->stat.rx.voip_mtc.mos_lq = (pj_uint8_t) v; - break; - - case PJMEDIA_RTCP_XR_INFO_MOS_CQ: - sess->stat.rx.voip_mtc.mos_cq = (pj_uint8_t) v; - break; - - case PJMEDIA_RTCP_XR_INFO_CONF_PLC: - if (v >= 0 && v <= 3) { - sess->stat.rx.voip_mtc.rx_config &= 0x3F; - sess->stat.rx.voip_mtc.rx_config |= (pj_uint8_t) (v << 6); - } - break; - - case PJMEDIA_RTCP_XR_INFO_CONF_JBA: - if (v >= 0 && v <= 3) { - sess->stat.rx.voip_mtc.rx_config &= 0xCF; - sess->stat.rx.voip_mtc.rx_config |= (pj_uint8_t) (v << 4); - } - break; - - case PJMEDIA_RTCP_XR_INFO_CONF_JBR: - if (v >= 0 && v <= 15) { - sess->stat.rx.voip_mtc.rx_config &= 0xF0; - sess->stat.rx.voip_mtc.rx_config |= (pj_uint8_t) v; - } - break; - - case PJMEDIA_RTCP_XR_INFO_JB_NOM: - sess->stat.rx.voip_mtc.jb_nom = (pj_uint16_t) v; - break; - - case PJMEDIA_RTCP_XR_INFO_JB_MAX: - sess->stat.rx.voip_mtc.jb_max = (pj_uint16_t) v; - break; - - case PJMEDIA_RTCP_XR_INFO_JB_ABS_MAX: - sess->stat.rx.voip_mtc.jb_abs_max = (pj_uint16_t) v; - break; - - default: - return PJ_EINVAL; + case PJMEDIA_RTCP_XR_INFO_SIGNAL_LVL: + sess->stat.rx.voip_mtc.signal_lvl = (pj_int8_t) v; + break; + + case PJMEDIA_RTCP_XR_INFO_NOISE_LVL: + sess->stat.rx.voip_mtc.noise_lvl = (pj_int8_t) v; + break; + + case PJMEDIA_RTCP_XR_INFO_RERL: + sess->stat.rx.voip_mtc.rerl = (pj_uint8_t) v; + break; + + case PJMEDIA_RTCP_XR_INFO_R_FACTOR: + sess->stat.rx.voip_mtc.ext_r_factor = (pj_uint8_t) v; + break; + + case PJMEDIA_RTCP_XR_INFO_MOS_LQ: + sess->stat.rx.voip_mtc.mos_lq = (pj_uint8_t) v; + break; + + case PJMEDIA_RTCP_XR_INFO_MOS_CQ: + sess->stat.rx.voip_mtc.mos_cq = (pj_uint8_t) v; + break; + + case PJMEDIA_RTCP_XR_INFO_CONF_PLC: + if (v >= 0 && v <= 3) { + sess->stat.rx.voip_mtc.rx_config &= 0x3F; + sess->stat.rx.voip_mtc.rx_config |= (pj_uint8_t) (v << 6); + } + break; + + case PJMEDIA_RTCP_XR_INFO_CONF_JBA: + if (v >= 0 && v <= 3) { + sess->stat.rx.voip_mtc.rx_config &= 0xCF; + sess->stat.rx.voip_mtc.rx_config |= (pj_uint8_t) (v << 4); + } + break; + + case PJMEDIA_RTCP_XR_INFO_CONF_JBR: + if (v >= 0 && v <= 15) { + sess->stat.rx.voip_mtc.rx_config &= 0xF0; + sess->stat.rx.voip_mtc.rx_config |= (pj_uint8_t) v; + } + break; + + case PJMEDIA_RTCP_XR_INFO_JB_NOM: + sess->stat.rx.voip_mtc.jb_nom = (pj_uint16_t) v; + break; + + case PJMEDIA_RTCP_XR_INFO_JB_MAX: + sess->stat.rx.voip_mtc.jb_max = (pj_uint16_t) v; + break; + + case PJMEDIA_RTCP_XR_INFO_JB_ABS_MAX: + sess->stat.rx.voip_mtc.jb_abs_max = (pj_uint16_t) v; + break; + + default: + return PJ_EINVAL; } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia/rtp.c b/pjmedia/src/pjmedia/rtp.c index 2c02aff6ae..2aa3a37412 100644 --- a/pjmedia/src/pjmedia/rtp.c +++ b/pjmedia/src/pjmedia/rtp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -20,7 +19,7 @@ #include #include #include -#include /* pj_htonx, pj_htonx */ +#include /* pj_htonx, pj_htonx */ #include #include #include @@ -28,36 +27,36 @@ #define THIS_FILE "rtp.c" -#define RTP_VERSION 2 +#define RTP_VERSION 2 -#define RTP_SEQ_MOD (1 << 16) -#define MAX_DROPOUT ((pj_int16_t)3000) -#define MAX_MISORDER ((pj_int16_t)100) +#define RTP_SEQ_MOD (1 << 16) +#define MAX_DROPOUT ((pj_int16_t)3000) +#define MAX_MISORDER ((pj_int16_t)100) #define MIN_SEQUENTIAL ((pj_int16_t)2) static void pjmedia_rtp_seq_restart(pjmedia_rtp_seq_session *seq_ctrl, - pj_uint16_t seq); + pj_uint16_t seq); PJ_DEF(pj_status_t) pjmedia_rtp_session_init( pjmedia_rtp_session *ses, - int default_pt, - pj_uint32_t sender_ssrc ) + int default_pt, + pj_uint32_t sender_ssrc ) { PJ_LOG(5, (THIS_FILE, - "pjmedia_rtp_session_init: ses=%p, default_pt=%d, ssrc=0x%x", - ses, default_pt, sender_ssrc)); + "pjmedia_rtp_session_init: ses=%p, default_pt=%d, ssrc=0x%x", + ses, default_pt, sender_ssrc)); /* Check RTP header packing. */ if (sizeof(struct pjmedia_rtp_hdr) != 12) { - pj_assert(!"Wrong RTP header packing!"); - return PJMEDIA_RTP_EINPACK; + pj_assert(!"Wrong RTP header packing!"); + return PJMEDIA_RTP_EINPACK; } /* If sender_ssrc is not specified, create from random value. */ if (sender_ssrc == 0 || sender_ssrc == (pj_uint32_t)-1) { - sender_ssrc = pj_htonl(pj_rand()); + sender_ssrc = pj_htonl(pj_rand()); } else { - sender_ssrc = pj_htonl(sender_ssrc); + sender_ssrc = pj_htonl(sender_ssrc); } /* Initialize session. */ @@ -86,46 +85,46 @@ PJ_DEF(pj_status_t) pjmedia_rtp_session_init( pjmedia_rtp_session *ses, } PJ_DEF(pj_status_t) pjmedia_rtp_session_init2( - pjmedia_rtp_session *ses, - pjmedia_rtp_session_setting settings) + pjmedia_rtp_session *ses, + pjmedia_rtp_session_setting settings) { pj_status_t status; - int pt = 0; - pj_uint32_t sender_ssrc = 0; + int pt = 0; + pj_uint32_t sender_ssrc = 0; if (settings.flags & 1) - pt = settings.default_pt; + pt = settings.default_pt; if (settings.flags & 2) - sender_ssrc = settings.sender_ssrc; + sender_ssrc = settings.sender_ssrc; status = pjmedia_rtp_session_init(ses, pt, sender_ssrc); if (status != PJ_SUCCESS) - return status; + return status; if (settings.flags & 4) { - ses->out_extseq = settings.seq; - ses->out_hdr.seq = pj_htons((pj_uint16_t)ses->out_extseq); + ses->out_extseq = settings.seq; + ses->out_hdr.seq = pj_htons((pj_uint16_t)ses->out_extseq); } if (settings.flags & 8) - ses->out_hdr.ts = pj_htonl(settings.ts); + ses->out_hdr.ts = pj_htonl(settings.ts); if (settings.flags & 16) { ses->has_peer_ssrc = PJ_TRUE; - ses->peer_ssrc = settings.peer_ssrc; + ses->peer_ssrc = settings.peer_ssrc; } PJ_LOG(5, (THIS_FILE, - "pjmedia_rtp_session_init2: ses=%p, seq=%d, ts=%d, peer_ssrc=%d", - ses, pj_ntohs(ses->out_hdr.seq), pj_ntohl(ses->out_hdr.ts), - ses->has_peer_ssrc? ses->peer_ssrc : 0)); + "pjmedia_rtp_session_init2: ses=%p, seq=%d, ts=%d, peer_ssrc=%d", + ses, pj_ntohs(ses->out_hdr.seq), pj_ntohl(ses->out_hdr.ts), + ses->has_peer_ssrc? ses->peer_ssrc : 0)); return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_rtp_encode_rtp( pjmedia_rtp_session *ses, - int pt, int m, - int payload_len, int ts_len, - const void **rtphdr, int *hdrlen ) + int pt, int m, + int payload_len, int ts_len, + const void **rtphdr, int *hdrlen ) { /* Update timestamp */ ses->out_hdr.ts = pj_htonl(pj_ntohl(ses->out_hdr.ts)+ts_len); @@ -134,7 +133,7 @@ PJ_DEF(pj_status_t) pjmedia_rtp_encode_rtp( pjmedia_rtp_session *ses, * This is a clock frame; we're not really transmitting anything. */ if (payload_len == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Update session. */ ses->out_extseq++; @@ -153,25 +152,25 @@ PJ_DEF(pj_status_t) pjmedia_rtp_encode_rtp( pjmedia_rtp_session *ses, PJ_DEF(pj_status_t) pjmedia_rtp_decode_rtp( pjmedia_rtp_session *ses, - const void *pkt, int pkt_len, - const pjmedia_rtp_hdr **hdr, - const void **payload, - unsigned *payloadlen) + const void *pkt, int pkt_len, + const pjmedia_rtp_hdr **hdr, + const void **payload, + unsigned *payloadlen) { pjmedia_rtp_dec_hdr dec_hdr; return pjmedia_rtp_decode_rtp2(ses, pkt, pkt_len, hdr, &dec_hdr, - payload, payloadlen); + payload, payloadlen); } PJ_DEF(pj_status_t) pjmedia_rtp_decode_rtp2( - pjmedia_rtp_session *ses, - const void *pkt, int pkt_len, - const pjmedia_rtp_hdr **hdr, - pjmedia_rtp_dec_hdr *dec_hdr, - const void **payload, - unsigned *payloadlen) + pjmedia_rtp_session *ses, + const void *pkt, int pkt_len, + const pjmedia_rtp_hdr **hdr, + pjmedia_rtp_dec_hdr *dec_hdr, + const void **payload, + unsigned *payloadlen) { int offset; @@ -182,7 +181,7 @@ PJ_DEF(pj_status_t) pjmedia_rtp_decode_rtp2( /* Check RTP header sanity. */ if ((*hdr)->v != RTP_VERSION) { - return PJMEDIA_RTP_EINVER; + return PJMEDIA_RTP_EINVER; } /* Payload is located right after header plus CSRC */ @@ -197,9 +196,9 @@ PJ_DEF(pj_status_t) pjmedia_rtp_decode_rtp2( dec_hdr->ext_len = pj_ntohs((dec_hdr->ext_hdr)->length); offset += ((dec_hdr->ext_len + 1) * sizeof(pj_uint32_t)); } else { - dec_hdr->ext_hdr = NULL; - dec_hdr->ext = NULL; - dec_hdr->ext_len = 0; + dec_hdr->ext_hdr = NULL; + dec_hdr->ext = NULL; + dec_hdr->ext_len = 0; } /* Check that offset is not greater than packet size */ @@ -213,11 +212,11 @@ PJ_DEF(pj_status_t) pjmedia_rtp_decode_rtp2( /* Remove payload padding if any */ if ((*hdr)->p && *payloadlen > 0) { - pj_uint8_t pad_len; + pj_uint8_t pad_len; - pad_len = ((pj_uint8_t*)(*payload))[*payloadlen - 1]; - if (pad_len <= *payloadlen) - *payloadlen -= pad_len; + pad_len = ((pj_uint8_t*)(*payload))[*payloadlen - 1]; + if (pad_len <= *payloadlen) + *payloadlen -= pad_len; } return PJ_SUCCESS; @@ -225,16 +224,16 @@ PJ_DEF(pj_status_t) pjmedia_rtp_decode_rtp2( PJ_DEF(void) pjmedia_rtp_session_update( pjmedia_rtp_session *ses, - const pjmedia_rtp_hdr *hdr, - pjmedia_rtp_status *p_seq_st) + const pjmedia_rtp_hdr *hdr, + pjmedia_rtp_status *p_seq_st) { pjmedia_rtp_session_update2(ses, hdr, p_seq_st, PJ_TRUE); } PJ_DEF(void) pjmedia_rtp_session_update2( pjmedia_rtp_session *ses, - const pjmedia_rtp_hdr *hdr, - pjmedia_rtp_status *p_seq_st, - pj_bool_t check_pt) + const pjmedia_rtp_hdr *hdr, + pjmedia_rtp_status *p_seq_st, + pj_bool_t check_pt) { pjmedia_rtp_status seq_st; @@ -253,37 +252,37 @@ PJ_DEF(void) pjmedia_rtp_session_update2( pjmedia_rtp_session *ses, ses->peer_ssrc = pj_ntohl(hdr->ssrc); if (pj_ntohl(hdr->ssrc) != ses->peer_ssrc) { - seq_st.status.flag.badssrc = 1; - if (!ses->has_peer_ssrc) - ses->peer_ssrc = pj_ntohl(hdr->ssrc); + seq_st.status.flag.badssrc = 1; + if (!ses->has_peer_ssrc) + ses->peer_ssrc = pj_ntohl(hdr->ssrc); } /* Check payload type. */ if (check_pt && hdr->pt != ses->out_pt) { - if (p_seq_st) { - p_seq_st->status.value = seq_st.status.value; - p_seq_st->status.flag.bad = 1; - p_seq_st->status.flag.badpt = 1; - } - return; + if (p_seq_st) { + p_seq_st->status.value = seq_st.status.value; + p_seq_st->status.flag.bad = 1; + p_seq_st->status.flag.badpt = 1; + } + return; } /* Initialize sequence number on first packet received. */ if (ses->received == 0) - pjmedia_rtp_seq_init( &ses->seq_ctrl, pj_ntohs(hdr->seq) ); + pjmedia_rtp_seq_init( &ses->seq_ctrl, pj_ntohs(hdr->seq) ); /* Check sequence number to see if remote session has been restarted. */ pjmedia_rtp_seq_update( &ses->seq_ctrl, pj_ntohs(hdr->seq), &seq_st); if (seq_st.status.flag.restart) { - ++ses->received; + ++ses->received; } else if (!seq_st.status.flag.bad) { - ++ses->received; + ++ses->received; } if (p_seq_st) { - p_seq_st->status.value = seq_st.status.value; - p_seq_st->diff = seq_st.diff; + p_seq_st->status.value = seq_st.status.value; + p_seq_st->diff = seq_st.diff; } } @@ -308,8 +307,8 @@ void pjmedia_rtp_seq_init(pjmedia_rtp_seq_session *sess, pj_uint16_t seq) void pjmedia_rtp_seq_update( pjmedia_rtp_seq_session *sess, - pj_uint16_t seq, - pjmedia_rtp_status *seq_status) + pj_uint16_t seq, + pjmedia_rtp_status *seq_status) { pj_uint16_t udelta = (pj_uint16_t) (seq - sess->max_seq); pjmedia_rtp_status st; @@ -324,73 +323,73 @@ void pjmedia_rtp_seq_update( pjmedia_rtp_seq_session *sess, */ if (sess->probation) { - st.status.flag.probation = 1; - + st.status.flag.probation = 1; + if (seq == sess->max_seq+ 1) { - /* packet is in sequence */ - st.diff = 1; - sess->probation--; + /* packet is in sequence */ + st.diff = 1; + sess->probation--; sess->max_seq = seq; if (sess->probation == 0) { - st.status.flag.probation = 0; + st.status.flag.probation = 0; } - } else { + } else { - st.diff = 0; + st.diff = 0; - st.status.flag.bad = 1; - if (seq == sess->max_seq) - st.status.flag.dup = 1; - else - st.status.flag.outorder = 1; + st.status.flag.bad = 1; + if (seq == sess->max_seq) + st.status.flag.dup = 1; + else + st.status.flag.outorder = 1; - sess->probation = MIN_SEQUENTIAL - 1; - sess->max_seq = seq; + sess->probation = MIN_SEQUENTIAL - 1; + sess->max_seq = seq; } } else if (udelta == 0) { - st.status.flag.dup = 1; + st.status.flag.dup = 1; } else if (udelta < MAX_DROPOUT) { - /* in order, with permissible gap */ - if (seq < sess->max_seq) { - /* Sequence number wrapped - count another 64K cycle. */ - sess->cycles += RTP_SEQ_MOD; + /* in order, with permissible gap */ + if (seq < sess->max_seq) { + /* Sequence number wrapped - count another 64K cycle. */ + sess->cycles += RTP_SEQ_MOD; } sess->max_seq = seq; - st.diff = udelta; + st.diff = udelta; } else if (udelta <= (RTP_SEQ_MOD - MAX_MISORDER)) { - /* the sequence number made a very large jump */ + /* the sequence number made a very large jump */ if (seq == sess->bad_seq) { - /* - * Two sequential packets -- assume that the other side - * restarted without telling us so just re-sync - * (i.e., pretend this was the first packet). - */ - pjmedia_rtp_seq_restart(sess, seq); - st.status.flag.restart = 1; - st.status.flag.probation = 1; - st.diff = 1; - } + /* + * Two sequential packets -- assume that the other side + * restarted without telling us so just re-sync + * (i.e., pretend this was the first packet). + */ + pjmedia_rtp_seq_restart(sess, seq); + st.status.flag.restart = 1; + st.status.flag.probation = 1; + st.diff = 1; + } else { - sess->bad_seq = (seq + 1) & (RTP_SEQ_MOD-1); + sess->bad_seq = (seq + 1) & (RTP_SEQ_MOD-1); st.status.flag.bad = 1; - st.status.flag.outorder = 1; + st.status.flag.outorder = 1; } } else { - /* old duplicate or reordered packet. - * Not necessarily bad packet (?) - */ - st.status.flag.outorder = 1; + /* old duplicate or reordered packet. + * Not necessarily bad packet (?) + */ + st.status.flag.outorder = 1; } if (seq_status) { - seq_status->diff = st.diff; - seq_status->status.value = st.status.value; + seq_status->diff = st.diff; + seq_status->status.value = st.status.value; } } diff --git a/pjmedia/src/pjmedia/sdp.c b/pjmedia/src/pjmedia/sdp.c index 647f49e138..b28aa31837 100644 --- a/pjmedia/src/pjmedia/sdp.c +++ b/pjmedia/src/pjmedia/sdp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,11 +34,11 @@ enum { SYNTAX_ERROR = 1, }; // New token definition from RFC 4566 (SDP) -#define TOKEN "!#$%&'*+-.^_`{|}~" -//#define TOKEN "-.!%*_=`'~" -//#define TOKEN "'`-./:?\"#$&*;=@[]^_`{|}+~!" -#define NTP_OFFSET ((pj_uint32_t)2208988800) -#define THIS_FILE "sdp.c" +#define TOKEN "!#$%&'*+-.^_`{|}~" +//#define TOKEN "-.!%*_=`'~" +//#define TOKEN "'`-./:?\"#$&*;=@[]^_`{|}+~!" +#define NTP_OFFSET ((pj_uint32_t)2208988800) +#define THIS_FILE "sdp.c" typedef struct parse_context { @@ -52,19 +51,19 @@ typedef struct parse_context */ static void parse_version(pj_scanner *scanner, volatile parse_context *ctx); static void parse_origin(pj_scanner *scanner, pjmedia_sdp_session *ses, - volatile parse_context *ctx); + volatile parse_context *ctx); static void parse_time(pj_scanner *scanner, pjmedia_sdp_session *ses, - volatile parse_context *ctx); + volatile parse_context *ctx); static void parse_generic_line(pj_scanner *scanner, pj_str_t *str, - volatile parse_context *ctx); + volatile parse_context *ctx); static void parse_connection_info(pj_scanner *scanner, pjmedia_sdp_conn *conn, - volatile parse_context *ctx); + volatile parse_context *ctx); static void parse_bandwidth_info(pj_scanner *scanner, pjmedia_sdp_bandw *bandw, - volatile parse_context *ctx); + volatile parse_context *ctx); static pjmedia_sdp_attr *parse_attr(pj_pool_t *pool, pj_scanner *scanner, - volatile parse_context *ctx); + volatile parse_context *ctx); static void parse_media(pj_scanner *scanner, pjmedia_sdp_media *med, - volatile parse_context *ctx); + volatile parse_context *ctx); static void on_scanner_error(pj_scanner *scanner); /* @@ -77,13 +76,13 @@ static pj_cis_t cs_digit, cs_token; static void init_sdp_parser(void) { if (is_initialized != 0) - return; + return; pj_enter_critical_section(); if (is_initialized != 0) { - pj_leave_critical_section(); - return; + pj_leave_critical_section(); + return; } pj_cis_buf_init(&cis_buf); @@ -101,8 +100,8 @@ static void init_sdp_parser(void) } PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_create( pj_pool_t *pool, - const char *name, - const pj_str_t *value) + const char *name, + const pj_str_t *value) { pjmedia_sdp_attr *attr; @@ -112,17 +111,17 @@ PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_create( pj_pool_t *pool, pj_strdup2(pool, &attr->name, name); if (value) - pj_strdup_with_null(pool, &attr->value, value); + pj_strdup_with_null(pool, &attr->value, value); else { - attr->value.ptr = NULL; - attr->value.slen = 0; + attr->value.ptr = NULL; + attr->value.slen = 0; } return attr; } PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_clone(pj_pool_t *pool, - const pjmedia_sdp_attr *rhs) + const pjmedia_sdp_attr *rhs) { pjmedia_sdp_attr *attr; @@ -137,9 +136,9 @@ PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_clone(pj_pool_t *pool, } PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_find (unsigned count, - pjmedia_sdp_attr *const attr_array[], - const pj_str_t *name, - const pj_str_t *c_fmt) + pjmedia_sdp_attr *const attr_array[], + const pj_str_t *name, + const pj_str_t *c_fmt) { unsigned i; unsigned c_pt = 0xFFFF; @@ -147,27 +146,27 @@ PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_find (unsigned count, PJ_ASSERT_RETURN(count <= PJMEDIA_MAX_SDP_ATTR, NULL); if (c_fmt) - c_pt = pj_strtoul(c_fmt); + c_pt = pj_strtoul(c_fmt); for (i=0; iname, name) == 0) { - const pjmedia_sdp_attr *a = attr_array[i]; - if (c_fmt) { - unsigned pt = (unsigned) pj_strtoul2(&a->value, NULL, 10); - if (pt == c_pt) { - return (pjmedia_sdp_attr*)a; - } - } else - return (pjmedia_sdp_attr*)a; - } + if (pj_strcmp(&attr_array[i]->name, name) == 0) { + const pjmedia_sdp_attr *a = attr_array[i]; + if (c_fmt) { + unsigned pt = (unsigned) pj_strtoul2(&a->value, NULL, 10); + if (pt == c_pt) { + return (pjmedia_sdp_attr*)a; + } + } else + return (pjmedia_sdp_attr*)a; + } } return NULL; } PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_find2(unsigned count, - pjmedia_sdp_attr *const attr_array[], - const char *c_name, - const pj_str_t *c_fmt) + pjmedia_sdp_attr *const attr_array[], + const char *c_name, + const pj_str_t *c_fmt) { pj_str_t name; @@ -180,8 +179,8 @@ PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_find2(unsigned count, PJ_DEF(pj_status_t) pjmedia_sdp_attr_add(unsigned *count, - pjmedia_sdp_attr *attr_array[], - pjmedia_sdp_attr *attr) + pjmedia_sdp_attr *attr_array[], + pjmedia_sdp_attr *attr) { PJ_ASSERT_RETURN(count && attr_array && attr, PJ_EINVAL); PJ_ASSERT_RETURN(*count < PJMEDIA_MAX_SDP_ATTR, PJ_ETOOMANY); @@ -194,8 +193,8 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_add(unsigned *count, PJ_DEF(unsigned) pjmedia_sdp_attr_remove_all(unsigned *count, - pjmedia_sdp_attr *attr_array[], - const char *name) + pjmedia_sdp_attr *attr_array[], + const char *name) { unsigned i, removed = 0; pj_str_t attr_name; @@ -207,14 +206,14 @@ PJ_DEF(unsigned) pjmedia_sdp_attr_remove_all(unsigned *count, attr_name.slen = pj_ansi_strlen(name); for (i=0; i<*count; ) { - if (pj_strcmp(&attr_array[i]->name, &attr_name)==0) { - pj_array_erase(attr_array, sizeof(pjmedia_sdp_attr*), - *count, i); - --(*count); - ++removed; - } else { - ++i; - } + if (pj_strcmp(&attr_array[i]->name, &attr_name)==0) { + pj_array_erase(attr_array, sizeof(pjmedia_sdp_attr*), + *count, i); + --(*count); + ++removed; + } else { + ++i; + } } return removed; @@ -222,8 +221,8 @@ PJ_DEF(unsigned) pjmedia_sdp_attr_remove_all(unsigned *count, PJ_DEF(pj_status_t) pjmedia_sdp_attr_remove( unsigned *count, - pjmedia_sdp_attr *attr_array[], - pjmedia_sdp_attr *attr ) + pjmedia_sdp_attr *attr_array[], + pjmedia_sdp_attr *attr ) { unsigned i, removed=0; @@ -231,14 +230,14 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_remove( unsigned *count, PJ_ASSERT_RETURN(*count <= PJMEDIA_MAX_SDP_ATTR, PJ_ETOOMANY); for (i=0; i<*count; ) { - if (attr_array[i] == attr) { - pj_array_erase(attr_array, sizeof(pjmedia_sdp_attr*), - *count, i); - --(*count); - ++removed; - } else { - ++i; - } + if (attr_array[i] == attr) { + pj_array_erase(attr_array, sizeof(pjmedia_sdp_attr*), + *count, i); + --(*count); + ++removed; + } else { + ++i; + } } return removed ? PJ_SUCCESS : PJ_ENOTFOUND; @@ -246,7 +245,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_remove( unsigned *count, PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_rtpmap( const pjmedia_sdp_attr *attr, - pjmedia_sdp_rtpmap *rtpmap) + pjmedia_sdp_rtpmap *rtpmap) { pj_scanner scanner; pj_str_t token; @@ -268,22 +267,22 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_rtpmap( const pjmedia_sdp_attr *attr, * null terminated. */ if (attr->value.ptr[attr->value.slen] != 0 && - attr->value.ptr[attr->value.slen] != '\r' && - attr->value.ptr[attr->value.slen] != '\n') + attr->value.ptr[attr->value.slen] != '\r' && + attr->value.ptr[attr->value.slen] != '\n') { - pj_assert(!"Shouldn't happen"); - term = attr->value.ptr[attr->value.slen]; - attr->value.ptr[attr->value.slen] = '\0'; + pj_assert(!"Shouldn't happen"); + term = attr->value.ptr[attr->value.slen]; + attr->value.ptr[attr->value.slen] = '\0'; } /* The buffer passed to the scanner is not guaranteed to be NULL * terminated, but should be safe. See ticket #2063. */ pj_scan_init(&scanner, (char*)attr->value.ptr, attr->value.slen, - PJ_SCAN_AUTOSKIP_WS, &on_scanner_error); + PJ_SCAN_AUTOSKIP_WS, &on_scanner_error); /* rtpmap sample: - * a=rtpmap:98 L16/16000/2. + * a=rtpmap:98 L16/16000/2. */ /* Init */ @@ -293,37 +292,37 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_rtpmap( const pjmedia_sdp_attr *attr, /* Parse */ PJ_TRY { - /* Get payload type. */ - pj_scan_get(&scanner, &cs_token, &rtpmap->pt); + /* Get payload type. */ + pj_scan_get(&scanner, &cs_token, &rtpmap->pt); - /* Get encoding name. */ - pj_scan_get(&scanner, &cs_token, &rtpmap->enc_name); + /* Get encoding name. */ + pj_scan_get(&scanner, &cs_token, &rtpmap->enc_name); - /* Expecting '/' after encoding name. */ - if (pj_scan_get_char(&scanner) != '/') { - status = PJMEDIA_SDP_EINRTPMAP; - goto on_return; - } + /* Expecting '/' after encoding name. */ + if (pj_scan_get_char(&scanner) != '/') { + status = PJMEDIA_SDP_EINRTPMAP; + goto on_return; + } - /* Get the clock rate. */ - pj_scan_get(&scanner, &cs_digit, &token); - rtpmap->clock_rate = pj_strtoul(&token); + /* Get the clock rate. */ + pj_scan_get(&scanner, &cs_digit, &token); + rtpmap->clock_rate = pj_strtoul(&token); - /* Expecting either '/' or EOF */ - if (*scanner.curptr == '/') { - /* Skip the '/' */ - pj_scan_get_char(&scanner); - pj_scan_get(&scanner, &cs_token, &rtpmap->param); - } else { - rtpmap->param.slen = 0; - } + /* Expecting either '/' or EOF */ + if (*scanner.curptr == '/') { + /* Skip the '/' */ + pj_scan_get_char(&scanner); + pj_scan_get(&scanner, &cs_token, &rtpmap->param); + } else { + rtpmap->param.slen = 0; + } - status = PJ_SUCCESS; + status = PJ_SUCCESS; } PJ_CATCH_ANY { - status = PJMEDIA_SDP_EINRTPMAP; + status = PJMEDIA_SDP_EINRTPMAP; } PJ_END; @@ -331,13 +330,13 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_rtpmap( const pjmedia_sdp_attr *attr, on_return: pj_scan_fini(&scanner); if (term) { - attr->value.ptr[attr->value.slen] = term; + attr->value.ptr[attr->value.slen] = term; } return status; } PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_fmtp( const pjmedia_sdp_attr *attr, - pjmedia_sdp_fmtp *fmtp) + pjmedia_sdp_fmtp *fmtp) { const char *p = attr->value.ptr; const char *end = attr->value.ptr + attr->value.slen; @@ -349,16 +348,16 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_fmtp( const pjmedia_sdp_attr *attr, return PJMEDIA_SDP_EINATTR; /* fmtp BNF: - * a=fmtp: + * a=fmtp: */ /* Get format. */ token.ptr = (char*)p; while (pj_isdigit(*p) && p!=end) - ++p; + ++p; token.slen = p - token.ptr; if (token.slen == 0) - return PJMEDIA_SDP_EINFMTP; + return PJMEDIA_SDP_EINFMTP; fmtp->fmt = token; @@ -377,7 +376,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_fmtp( const pjmedia_sdp_attr *attr, PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_rtcp(const pjmedia_sdp_attr *attr, - pjmedia_sdp_rtcp_attr *rtcp) + pjmedia_sdp_rtcp_attr *rtcp) { pj_scanner scanner; pj_str_t token; @@ -392,14 +391,14 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_rtcp(const pjmedia_sdp_attr *attr, init_sdp_parser(); /* fmtp BNF: - * a=rtcp: [nettype addrtype address] + * a=rtcp: [nettype addrtype address] */ /* The buffer passed to the scanner is not guaranteed to be NULL * terminated, but should be safe. See ticket #2063. */ pj_scan_init(&scanner, (char*)attr->value.ptr, attr->value.slen, - PJ_SCAN_AUTOSKIP_WS, &on_scanner_error); + PJ_SCAN_AUTOSKIP_WS, &on_scanner_error); /* Init */ rtcp->net_type.slen = rtcp->addr_type.slen = rtcp->addr.slen = 0; @@ -407,30 +406,30 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_rtcp(const pjmedia_sdp_attr *attr, /* Parse */ PJ_TRY { - /* Get the port */ - pj_scan_get(&scanner, &cs_token, &token); - rtcp->port = pj_strtoul(&token); + /* Get the port */ + pj_scan_get(&scanner, &cs_token, &token); + rtcp->port = pj_strtoul(&token); - /* Have address? */ - if (!pj_scan_is_eof(&scanner)) { + /* Have address? */ + if (!pj_scan_is_eof(&scanner)) { - /* Get network type */ - pj_scan_get(&scanner, &cs_token, &rtcp->net_type); + /* Get network type */ + pj_scan_get(&scanner, &cs_token, &rtcp->net_type); - /* Get address type */ - pj_scan_get(&scanner, &cs_token, &rtcp->addr_type); + /* Get address type */ + pj_scan_get(&scanner, &cs_token, &rtcp->addr_type); - /* Get the address */ - //pj_scan_get(&scanner, &cs_token, &rtcp->addr); - pj_scan_get_until_chr(&scanner, "/ \t\r\n", &rtcp->addr); + /* Get the address */ + //pj_scan_get(&scanner, &cs_token, &rtcp->addr); + pj_scan_get_until_chr(&scanner, "/ \t\r\n", &rtcp->addr); - } + } - status = PJ_SUCCESS; + status = PJ_SUCCESS; } PJ_CATCH_ANY { - status = PJMEDIA_SDP_EINRTCP; + status = PJMEDIA_SDP_EINRTCP; } PJ_END; @@ -440,10 +439,10 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_rtcp(const pjmedia_sdp_attr *attr, PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_create_rtcp(pj_pool_t *pool, - const pj_sockaddr *a) + const pj_sockaddr *a) { enum { - ATTR_LEN = PJ_INET6_ADDRSTRLEN+16 + ATTR_LEN = PJ_INET6_ADDRSTRLEN+16 }; char tmp_addr[PJ_INET6_ADDRSTRLEN]; pjmedia_sdp_attr *attr; @@ -452,23 +451,23 @@ PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_create_rtcp(pj_pool_t *pool, attr->name = pj_str("rtcp"); attr->value.ptr = (char*) pj_pool_alloc(pool, ATTR_LEN); if (a->addr.sa_family == pj_AF_INET()) { - attr->value.slen = - pj_ansi_snprintf(attr->value.ptr, ATTR_LEN, - "%u IN IP4 %s", - pj_sockaddr_get_port(a), - pj_sockaddr_print(a, tmp_addr, - sizeof(tmp_addr), 0)); + attr->value.slen = + pj_ansi_snprintf(attr->value.ptr, ATTR_LEN, + "%u IN IP4 %s", + pj_sockaddr_get_port(a), + pj_sockaddr_print(a, tmp_addr, + sizeof(tmp_addr), 0)); } else if (a->addr.sa_family == pj_AF_INET6()) { - attr->value.slen = - pj_ansi_snprintf(attr->value.ptr, ATTR_LEN, - "%u IN IP6 %s", - pj_sockaddr_get_port(a), - pj_sockaddr_print(a, tmp_addr, - sizeof(tmp_addr), 0)); + attr->value.slen = + pj_ansi_snprintf(attr->value.ptr, ATTR_LEN, + "%u IN IP6 %s", + pj_sockaddr_get_port(a), + pj_sockaddr_print(a, tmp_addr, + sizeof(tmp_addr), 0)); } else { - pj_assert(!"Unsupported address family"); - return NULL; + pj_assert(!"Unsupported address family"); + return NULL; } return attr; @@ -476,7 +475,7 @@ PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_create_rtcp(pj_pool_t *pool, PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_ssrc(const pjmedia_sdp_attr *attr, - pjmedia_sdp_ssrc_attr *ssrc) + pjmedia_sdp_ssrc_attr *ssrc) { pj_scanner scanner; pj_str_t token; @@ -492,14 +491,14 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_ssrc(const pjmedia_sdp_attr *attr, /* ssrc BNF: * a=ssrc: - * a=ssrc: : + * a=ssrc: : */ /* The buffer passed to the scanner is not guaranteed to be NULL * terminated, but should be safe. See ticket #2063. */ pj_scan_init(&scanner, (char*)attr->value.ptr, attr->value.slen, - PJ_SCAN_AUTOSKIP_WS, &on_scanner_error); + PJ_SCAN_AUTOSKIP_WS, &on_scanner_error); /* Init */ pj_bzero(ssrc, sizeof(*ssrc)); @@ -508,26 +507,26 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_ssrc(const pjmedia_sdp_attr *attr, PJ_TRY { pj_str_t scan_attr; - /* Get the ssrc */ - pj_scan_get(&scanner, &cs_digit, &token); - ssrc->ssrc = pj_strtoul(&token); + /* Get the ssrc */ + pj_scan_get(&scanner, &cs_digit, &token); + ssrc->ssrc = pj_strtoul(&token); - pj_scan_get_char(&scanner); - pj_scan_get(&scanner, &cs_token, &scan_attr); - - /* Get cname attribute, if any */ - if (!pj_scan_is_eof(&scanner) && - pj_scan_get_char(&scanner) == ':' && - pj_strcmp2(&scan_attr, "cname")) - { - pj_scan_get(&scanner, &cs_token, &ssrc->cname); - } + pj_scan_get_char(&scanner); + pj_scan_get(&scanner, &cs_token, &scan_attr); + + /* Get cname attribute, if any */ + if (!pj_scan_is_eof(&scanner) && + pj_scan_get_char(&scanner) == ':' && + pj_strcmp2(&scan_attr, "cname")) + { + pj_scan_get(&scanner, &cs_token, &ssrc->cname); + } - status = PJ_SUCCESS; + status = PJ_SUCCESS; } PJ_CATCH_ANY { - status = PJMEDIA_SDP_EINSSRC; + status = PJMEDIA_SDP_EINSSRC; } PJ_END; @@ -537,8 +536,8 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_get_ssrc(const pjmedia_sdp_attr *attr, PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_create_ssrc( pj_pool_t *pool, - pj_uint32_t ssrc, - const pj_str_t *cname) + pj_uint32_t ssrc, + const pj_str_t *cname) { pjmedia_sdp_attr *attr; @@ -548,19 +547,19 @@ PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_attr_create_ssrc( pj_pool_t *pool, attr = PJ_POOL_ALLOC_T(pool, pjmedia_sdp_attr); attr->name = pj_str("ssrc"); attr->value.ptr = (char*) pj_pool_alloc(pool, cname->slen+7 /* " cname:"*/ - + 10 /* 32-bit integer */ - + 1 /* NULL */); + + 10 /* 32-bit integer */ + + 1 /* NULL */); attr->value.slen = pj_ansi_snprintf(attr->value.ptr, cname->slen+18, - "%u cname:%.*s", ssrc, - (int)cname->slen, cname->ptr); + "%u cname:%.*s", ssrc, + (int)cname->slen, cname->ptr); return attr; } PJ_DEF(pj_status_t) pjmedia_sdp_attr_to_rtpmap(pj_pool_t *pool, - const pjmedia_sdp_attr *attr, - pjmedia_sdp_rtpmap **p_rtpmap) + const pjmedia_sdp_attr *attr, + pjmedia_sdp_rtpmap **p_rtpmap) { PJ_ASSERT_RETURN(pool && attr && p_rtpmap, PJ_EINVAL); @@ -572,8 +571,8 @@ PJ_DEF(pj_status_t) pjmedia_sdp_attr_to_rtpmap(pj_pool_t *pool, PJ_DEF(pj_status_t) pjmedia_sdp_rtpmap_to_attr(pj_pool_t *pool, - const pjmedia_sdp_rtpmap *rtpmap, - pjmedia_sdp_attr **p_attr) + const pjmedia_sdp_rtpmap *rtpmap, + pjmedia_sdp_attr **p_attr) { pjmedia_sdp_attr *attr; char tempbuf[128]; @@ -584,7 +583,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_rtpmap_to_attr(pj_pool_t *pool, /* Check that mandatory attributes are specified. */ PJ_ASSERT_RETURN(rtpmap->enc_name.slen && rtpmap->clock_rate, - PJMEDIA_SDP_EINRTPMAP); + PJMEDIA_SDP_EINRTPMAP); attr = PJ_POOL_ALLOC_T(pool, pjmedia_sdp_attr); @@ -595,18 +594,18 @@ PJ_DEF(pj_status_t) pjmedia_sdp_rtpmap_to_attr(pj_pool_t *pool, /* Format: ":pt enc_name/clock_rate[/param]" */ len = pj_ansi_snprintf(tempbuf, sizeof(tempbuf), - "%.*s %.*s/%u%s%.*s", - (int)rtpmap->pt.slen, - rtpmap->pt.ptr, - (int)rtpmap->enc_name.slen, - rtpmap->enc_name.ptr, - rtpmap->clock_rate, - (rtpmap->param.slen ? "/" : ""), - (int)rtpmap->param.slen, - rtpmap->param.ptr); + "%.*s %.*s/%u%s%.*s", + (int)rtpmap->pt.slen, + rtpmap->pt.ptr, + (int)rtpmap->enc_name.slen, + rtpmap->enc_name.ptr, + rtpmap->clock_rate, + (rtpmap->param.slen ? "/" : ""), + (int)rtpmap->param.slen, + rtpmap->param.ptr); if (len < 1 || len >= (int)sizeof(tempbuf)) - return PJMEDIA_SDP_ERTPMAPTOOLONG; + return PJMEDIA_SDP_ERTPMAPTOOLONG; attr->value.slen = len; attr->value.ptr = (char*) pj_pool_alloc(pool, attr->value.slen+1); @@ -622,21 +621,21 @@ static int print_connection_info( pjmedia_sdp_conn *c, char *buf, int len) int printed; printed = pj_ansi_snprintf(buf, len, "c=%.*s %.*s %.*s\r\n", - (int)c->net_type.slen, - c->net_type.ptr, - (int)c->addr_type.slen, - c->addr_type.ptr, - (int)c->addr.slen, - c->addr.ptr); + (int)c->net_type.slen, + c->net_type.ptr, + (int)c->addr_type.slen, + c->addr_type.ptr, + (int)c->addr.slen, + c->addr.ptr); if (printed < 1 || printed >= len) - return -1; + return -1; return printed; } PJ_DEF(pjmedia_sdp_conn*) pjmedia_sdp_conn_clone (pj_pool_t *pool, - const pjmedia_sdp_conn *rhs) + const pjmedia_sdp_conn *rhs) { pjmedia_sdp_conn *c = PJ_POOL_ALLOC_T(pool, pjmedia_sdp_conn); if (!c) return NULL; @@ -650,7 +649,7 @@ PJ_DEF(pjmedia_sdp_conn*) pjmedia_sdp_conn_clone (pj_pool_t *pool, PJ_DEF(pjmedia_sdp_bandw*) pjmedia_sdp_bandw_clone (pj_pool_t *pool, - const pjmedia_sdp_bandw *rhs) + const pjmedia_sdp_bandw *rhs) { pjmedia_sdp_bandw *b = PJ_POOL_ALLOC_T(pool, pjmedia_sdp_bandw); if (!b) return NULL; @@ -662,12 +661,12 @@ pjmedia_sdp_bandw_clone (pj_pool_t *pool, } static pj_ssize_t print_bandw(const pjmedia_sdp_bandw *bandw, - char *buf, pj_size_t len) + char *buf, pj_size_t len) { char *p = buf; if ((int)len < bandw->modifier.slen + 10 + 5) - return -1; + return -1; *p++ = 'b'; *p++ = '='; @@ -682,12 +681,12 @@ static pj_ssize_t print_bandw(const pjmedia_sdp_bandw *bandw, } static pj_ssize_t print_attr(const pjmedia_sdp_attr *attr, - char *buf, pj_size_t len) + char *buf, pj_size_t len) { char *p = buf; if ((int)len < attr->name.slen + attr->value.slen + 10) - return -1; + return -1; *p++ = 'a'; *p++ = '='; @@ -696,9 +695,9 @@ static pj_ssize_t print_attr(const pjmedia_sdp_attr *attr, if (attr->value.slen) { - *p++ = ':'; - pj_memcpy(p, attr->value.ptr, attr->value.slen); - p += attr->value.slen; + *p++ = ':'; + pj_memcpy(p, attr->value.ptr, attr->value.slen); + p += attr->value.slen; } *p++ = '\r'; @@ -715,9 +714,9 @@ static int print_media_desc(const pjmedia_sdp_media *m, char *buf, pj_size_t len /* check length for the "m=" line. */ if (len < (pj_size_t)m->desc.media.slen+m->desc.transport.slen+12+24) { - return -1; + return -1; } - *p++ = 'm'; /* m= */ + *p++ = 'm'; /* m= */ *p++ = '='; pj_memcpy(p, m->desc.media.ptr, m->desc.media.slen); p += m->desc.media.slen; @@ -725,69 +724,69 @@ static int print_media_desc(const pjmedia_sdp_media *m, char *buf, pj_size_t len printed = pj_utoa(m->desc.port, p); p += printed; if (m->desc.port_count > 1) { - *p++ = '/'; - printed = pj_utoa(m->desc.port_count, p); - p += printed; + *p++ = '/'; + printed = pj_utoa(m->desc.port_count, p); + p += printed; } *p++ = ' '; pj_memcpy(p, m->desc.transport.ptr, m->desc.transport.slen); p += m->desc.transport.slen; for (i=0; idesc.fmt_count; ++i) { - if (end-p > m->desc.fmt[i].slen) { - *p++ = ' '; - pj_memcpy(p, m->desc.fmt[i].ptr, m->desc.fmt[i].slen); - p += m->desc.fmt[i].slen; - } else { - return -1; - } + if (end-p > m->desc.fmt[i].slen) { + *p++ = ' '; + pj_memcpy(p, m->desc.fmt[i].ptr, m->desc.fmt[i].slen); + p += m->desc.fmt[i].slen; + } else { + return -1; + } } if (end-p >= 2) { - *p++ = '\r'; - *p++ = '\n'; + *p++ = '\r'; + *p++ = '\n'; } else { - return -1; + return -1; } /* print connection info, if present. */ if (m->conn) { - printed = print_connection_info(m->conn, p, (int)(end-p)); - if (printed < 0) { - return -1; - } - p += printed; + printed = print_connection_info(m->conn, p, (int)(end-p)); + if (printed < 0) { + return -1; + } + p += printed; } /* print optional bandwidth info. */ for (i=0; ibandw_count; ++i) { - printed = (int)print_bandw(m->bandw[i], p, end-p); - if (printed < 0) { - return -1; - } - p += printed; + printed = (int)print_bandw(m->bandw[i], p, end-p); + if (printed < 0) { + return -1; + } + p += printed; } /* print attributes. */ for (i=0; iattr_count; ++i) { - printed = (int)print_attr(m->attr[i], p, end-p); - if (printed < 0) { - return -1; - } - p += printed; + printed = (int)print_attr(m->attr[i], p, end-p); + if (printed < 0) { + return -1; + } + p += printed; } return (int)(p-buf); } PJ_DEF(int) pjmedia_sdp_media_print(const pjmedia_sdp_media *media, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { - return print_media_desc(media, buf, size); + return print_media_desc(media, buf, size); } PJ_DEF(pjmedia_sdp_media*) pjmedia_sdp_media_clone( - pj_pool_t *pool, - const pjmedia_sdp_media *rhs) + pj_pool_t *pool, + const pjmedia_sdp_media *rhs) { unsigned int i; pjmedia_sdp_media *m = PJ_POOL_ALLOC_T(pool, pjmedia_sdp_media); @@ -799,33 +798,33 @@ PJ_DEF(pjmedia_sdp_media*) pjmedia_sdp_media_clone( pj_strdup (pool, &m->desc.transport, &rhs->desc.transport); m->desc.fmt_count = rhs->desc.fmt_count; for (i=0; idesc.fmt_count; ++i) - pj_strdup(pool, &m->desc.fmt[i], &rhs->desc.fmt[i]); + pj_strdup(pool, &m->desc.fmt[i], &rhs->desc.fmt[i]); if (rhs->conn) { - m->conn = pjmedia_sdp_conn_clone (pool, rhs->conn); - PJ_ASSERT_RETURN(m->conn != NULL, NULL); + m->conn = pjmedia_sdp_conn_clone (pool, rhs->conn); + PJ_ASSERT_RETURN(m->conn != NULL, NULL); } else { - m->conn = NULL; + m->conn = NULL; } m->bandw_count = rhs->bandw_count; for (i=0; i < rhs->bandw_count; ++i) { - m->bandw[i] = pjmedia_sdp_bandw_clone (pool, rhs->bandw[i]); - PJ_ASSERT_RETURN(m->bandw[i] != NULL, NULL); + m->bandw[i] = pjmedia_sdp_bandw_clone (pool, rhs->bandw[i]); + PJ_ASSERT_RETURN(m->bandw[i] != NULL, NULL); } m->attr_count = rhs->attr_count; for (i=0; i < rhs->attr_count; ++i) { - m->attr[i] = pjmedia_sdp_attr_clone (pool, rhs->attr[i]); - PJ_ASSERT_RETURN(m->attr[i] != NULL, NULL); + m->attr[i] = pjmedia_sdp_attr_clone (pool, rhs->attr[i]); + PJ_ASSERT_RETURN(m->attr[i] != NULL, NULL); } return m; } PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_media_find_attr( - const pjmedia_sdp_media *m, - const pj_str_t *name, const pj_str_t *fmt) + const pjmedia_sdp_media *m, + const pj_str_t *name, const pj_str_t *fmt) { PJ_ASSERT_RETURN(m && name, NULL); return pjmedia_sdp_attr_find(m->attr_count, m->attr, name, fmt); @@ -834,8 +833,8 @@ PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_media_find_attr( PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_media_find_attr2( - const pjmedia_sdp_media *m, - const char *name, const pj_str_t *fmt) + const pjmedia_sdp_media *m, + const char *name, const pj_str_t *fmt) { PJ_ASSERT_RETURN(m && name, NULL); return pjmedia_sdp_attr_find2(m->attr_count, m->attr, name, fmt); @@ -843,31 +842,31 @@ PJ_DEF(pjmedia_sdp_attr*) pjmedia_sdp_media_find_attr2( PJ_DEF(pj_status_t) pjmedia_sdp_media_add_attr( pjmedia_sdp_media *m, - pjmedia_sdp_attr *attr) + pjmedia_sdp_attr *attr) { return pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); } PJ_DEF(pj_status_t) pjmedia_sdp_session_add_attr(pjmedia_sdp_session *s, - pjmedia_sdp_attr *attr) + pjmedia_sdp_attr *attr) { return pjmedia_sdp_attr_add(&s->attr_count, s->attr, attr); } PJ_DEF(unsigned) pjmedia_sdp_media_remove_all_attr(pjmedia_sdp_media *m, - const char *name) + const char *name) { return pjmedia_sdp_attr_remove_all(&m->attr_count, m->attr, name); } PJ_DEF(pj_status_t) pjmedia_sdp_media_remove_attr(pjmedia_sdp_media *m, - pjmedia_sdp_attr *attr) + pjmedia_sdp_attr *attr) { return pjmedia_sdp_attr_remove(&m->attr_count, m->attr, attr); } static int print_session(const pjmedia_sdp_session *ses, - char *buf, pj_ssize_t len) + char *buf, pj_ssize_t len) { char *p = buf; char *end = buf+len; @@ -876,10 +875,10 @@ static int print_session(const pjmedia_sdp_session *ses, /* Check length for v= and o= lines. */ if (len < 5+ - 2+ses->origin.user.slen+18+ - ses->origin.net_type.slen+ses->origin.addr.slen + 2) + 2+ses->origin.user.slen+18+ + ses->origin.net_type.slen+ses->origin.addr.slen + 2) { - return -1; + return -1; } /* SDP version (v= line) */ @@ -911,7 +910,7 @@ static int print_session(const pjmedia_sdp_session *ses, /* Session name (s=) line. */ if ((end-p) < 8+ses->name.slen) { - return -1; + return -1; } *p++ = 's'; *p++ = '='; @@ -922,25 +921,25 @@ static int print_session(const pjmedia_sdp_session *ses, /* Connection line (c=) if exist. */ if (ses->conn) { - printed = print_connection_info(ses->conn, p, (int)(end-p)); - if (printed < 1) { - return -1; - } - p += printed; + printed = print_connection_info(ses->conn, p, (int)(end-p)); + if (printed < 1) { + return -1; + } + p += printed; } /* print optional bandwidth info. */ for (i=0; ibandw_count; ++i) { - printed = (int)print_bandw(ses->bandw[i], p, end-p); - if (printed < 1) { - return -1; - } - p += printed; + printed = (int)print_bandw(ses->bandw[i], p, end-p); + if (printed < 1) { + return -1; + } + p += printed; } /* Time */ if ((end-p) < 24) { - return -1; + return -1; } *p++ = 't'; *p++ = '='; @@ -954,20 +953,20 @@ static int print_session(const pjmedia_sdp_session *ses, /* Print all attribute (a=) lines. */ for (i=0; iattr_count; ++i) { - printed = (int)print_attr(ses->attr[i], p, end-p); - if (printed < 0) { - return -1; - } - p += printed; + printed = (int)print_attr(ses->attr[i], p, end-p); + if (printed < 0) { + return -1; + } + p += printed; } /* Print media (m=) lines. */ for (i=0; imedia_count; ++i) { - printed = print_media_desc(ses->media[i], p, (int)(end-p)); - if (printed < 0) { - return -1; - } - p += printed; + printed = print_media_desc(ses->media[i], p, (int)(end-p)); + if (printed < 0) { + return -1; + } + p += printed; } return (int)(p-buf); @@ -984,14 +983,14 @@ static void parse_version(pj_scanner *scanner, /* check equal sign */ if (scanner->curptr+1 >= scanner->end || *(scanner->curptr+1) != '=') { - on_scanner_error(scanner); - return; + on_scanner_error(scanner); + return; } /* check version is 0 */ if (scanner->curptr+2 >= scanner->end || *(scanner->curptr+2) != '0') { - on_scanner_error(scanner); - return; + on_scanner_error(scanner); + return; } /* We've got what we're looking for, skip anything until newline */ @@ -999,7 +998,7 @@ static void parse_version(pj_scanner *scanner, } static void parse_origin(pj_scanner *scanner, pjmedia_sdp_session *ses, - volatile parse_context *ctx) + volatile parse_context *ctx) { pj_str_t str; @@ -1007,8 +1006,8 @@ static void parse_origin(pj_scanner *scanner, pjmedia_sdp_session *ses, /* check equal sign */ if (scanner->curptr+1 >= scanner->end || *(scanner->curptr+1) != '=') { - on_scanner_error(scanner); - return; + on_scanner_error(scanner); + return; } /* o= */ @@ -1045,7 +1044,7 @@ static void parse_origin(pj_scanner *scanner, pjmedia_sdp_session *ses, } static void parse_time(pj_scanner *scanner, pjmedia_sdp_session *ses, - volatile parse_context *ctx) + volatile parse_context *ctx) { pj_str_t str; @@ -1053,8 +1052,8 @@ static void parse_time(pj_scanner *scanner, pjmedia_sdp_session *ses, /* check equal sign */ if (scanner->curptr+1 >= scanner->end || *(scanner->curptr+1) != '=') { - on_scanner_error(scanner); - return; + on_scanner_error(scanner); + return; } /* t= */ @@ -1075,14 +1074,14 @@ static void parse_time(pj_scanner *scanner, pjmedia_sdp_session *ses, } static void parse_generic_line(pj_scanner *scanner, pj_str_t *str, - volatile parse_context *ctx) + volatile parse_context *ctx) { ctx->last_error = PJMEDIA_SDP_EINSDP; /* check equal sign */ if ((scanner->curptr+1 >= scanner->end) || *(scanner->curptr+1) != '=') { - on_scanner_error(scanner); - return; + on_scanner_error(scanner); + return; } /* x= */ @@ -1096,7 +1095,7 @@ static void parse_generic_line(pj_scanner *scanner, pj_str_t *str, } static void parse_connection_info(pj_scanner *scanner, pjmedia_sdp_conn *conn, - volatile parse_context *ctx) + volatile parse_context *ctx) { ctx->last_error = PJMEDIA_SDP_EINCONN; @@ -1120,7 +1119,7 @@ static void parse_connection_info(pj_scanner *scanner, pjmedia_sdp_conn *conn, } static void parse_bandwidth_info(pj_scanner *scanner, pjmedia_sdp_bandw *bandw, - volatile parse_context *ctx) + volatile parse_context *ctx) { pj_str_t str; @@ -1142,7 +1141,7 @@ static void parse_bandwidth_info(pj_scanner *scanner, pjmedia_sdp_bandw *bandw, } static void parse_media(pj_scanner *scanner, pjmedia_sdp_media *med, - volatile parse_context *ctx) + volatile parse_context *ctx) { pj_str_t str; @@ -1150,8 +1149,8 @@ static void parse_media(pj_scanner *scanner, pjmedia_sdp_media *med, /* check the equal sign */ if (scanner->curptr+1 >= scanner->end || *(scanner->curptr+1) != '=') { - on_scanner_error(scanner); - return; + on_scanner_error(scanner); + return; } /* m= */ @@ -1169,17 +1168,17 @@ static void parse_media(pj_scanner *scanner, pjmedia_sdp_media *med, return; } if (*scanner->curptr == '/') { - /* port count */ - pj_scan_get_char(scanner); - pj_scan_get(scanner, &cs_token, &str); - med->desc.port_count = pj_strtoul(&str); + /* port count */ + pj_scan_get_char(scanner); + pj_scan_get(scanner, &cs_token, &str); + med->desc.port_count = pj_strtoul(&str); } else { - med->desc.port_count = 0; + med->desc.port_count = 0; } if (pj_scan_get_char(scanner) != ' ') { - on_scanner_error(scanner); + on_scanner_error(scanner); } /* transport */ @@ -1188,22 +1187,22 @@ static void parse_media(pj_scanner *scanner, pjmedia_sdp_media *med, /* format list */ med->desc.fmt_count = 0; while (scanner->curptr < scanner->end && *scanner->curptr == ' ') { - pj_str_t fmt; - - pj_scan_get_char(scanner); - - /* Check again for the end of the line */ - if ((*scanner->curptr == '\r') || (*scanner->curptr == '\n')) - break; - - pj_scan_get(scanner, &cs_token, &fmt); - if (med->desc.fmt_count < PJMEDIA_MAX_SDP_FMT) - med->desc.fmt[med->desc.fmt_count++] = fmt; - else - PJ_PERROR(2,(THIS_FILE, PJ_ETOOMANY, - "Error adding SDP media format %.*s, " - "format is ignored", - (int)fmt.slen, fmt.ptr)); + pj_str_t fmt; + + pj_scan_get_char(scanner); + + /* Check again for the end of the line */ + if ((*scanner->curptr == '\r') || (*scanner->curptr == '\n')) + break; + + pj_scan_get(scanner, &cs_token, &fmt); + if (med->desc.fmt_count < PJMEDIA_MAX_SDP_FMT) + med->desc.fmt[med->desc.fmt_count++] = fmt; + else + PJ_PERROR(2,(THIS_FILE, PJ_ETOOMANY, + "Error adding SDP media format %.*s, " + "format is ignored", + (int)fmt.slen, fmt.ptr)); } /* We've got what we're looking for, skip anything until newline */ @@ -1218,7 +1217,7 @@ static void on_scanner_error(pj_scanner *scanner) } static pjmedia_sdp_attr *parse_attr( pj_pool_t *pool, pj_scanner *scanner, - volatile parse_context *ctx) + volatile parse_context *ctx) { pjmedia_sdp_attr *attr; @@ -1228,8 +1227,8 @@ static pjmedia_sdp_attr *parse_attr( pj_pool_t *pool, pj_scanner *scanner, /* check equal sign */ if (scanner->curptr+1 >= scanner->end || *(scanner->curptr+1) != '=') { - on_scanner_error(scanner); - return NULL; + on_scanner_error(scanner); + return NULL; } /* skip a= */ @@ -1239,23 +1238,23 @@ static pjmedia_sdp_attr *parse_attr( pj_pool_t *pool, pj_scanner *scanner, pj_scan_get(scanner, &cs_token, &attr->name); if (*scanner->curptr && *scanner->curptr != '\r' && - *scanner->curptr != '\n') + *scanner->curptr != '\n') { - /* skip ':' if present. */ - if (*scanner->curptr == ':') - pj_scan_get_char(scanner); - - /* get value */ - if (!pj_scan_is_eof(scanner) && *scanner->curptr != '\r' && *scanner->curptr != '\n') { - pj_scan_get_until_chr(scanner, "\r\n", &attr->value); - } else { - attr->value.ptr = NULL; - attr->value.slen = 0; - } + /* skip ':' if present. */ + if (*scanner->curptr == ':') + pj_scan_get_char(scanner); + + /* get value */ + if (!pj_scan_is_eof(scanner) && *scanner->curptr != '\r' && *scanner->curptr != '\n') { + pj_scan_get_until_chr(scanner, "\r\n", &attr->value); + } else { + attr->value.ptr = NULL; + attr->value.slen = 0; + } } else { - attr->value.ptr = NULL; - attr->value.slen = 0; + attr->value.ptr = NULL; + attr->value.slen = 0; } /* We've got what we're looking for, skip anything until newline */ @@ -1282,42 +1281,42 @@ static void apply_media_direction(pjmedia_sdp_session *sdp) * direction "sendrecv". */ for (i = 0; i < sdp->attr_count && !dir_attr; ++i) { - if (!pj_strcmp(&sdp->attr[i]->name, &sendonly) || - !pj_strcmp(&sdp->attr[i]->name, &recvonly) || - !pj_strcmp(&sdp->attr[i]->name, &inactive)) - { - dir_attr = sdp->attr[i]; - } + if (!pj_strcmp(&sdp->attr[i]->name, &sendonly) || + !pj_strcmp(&sdp->attr[i]->name, &recvonly) || + !pj_strcmp(&sdp->attr[i]->name, &inactive)) + { + dir_attr = sdp->attr[i]; + } } /* Found the direction attribute */ if (dir_attr) { - /* Remove the direction attribute in session */ - pjmedia_sdp_attr_remove(&sdp->attr_count, sdp->attr, dir_attr); - - /* Apply the direction attribute to all media, but not overriding it - * if media already has direction attribute. - */ - for (i = 0; i < sdp->media_count; ++i) { - pjmedia_sdp_media *m; - unsigned j; - - /* Find direction attribute in this media */ - m = sdp->media[i]; - for (j = 0; j < m->attr_count; ++j) { - if (!pj_strcmp(&m->attr[j]->name, &sendrecv) || - !pj_strcmp(&m->attr[j]->name, &sendonly) || - !pj_strcmp(&m->attr[j]->name, &recvonly) || - !pj_strcmp(&m->attr[j]->name, &inactive)) - { - break; - } - } - - /* Not found, apply direction attribute from session */ - if (j == m->attr_count) - pjmedia_sdp_media_add_attr(m, dir_attr); - } + /* Remove the direction attribute in session */ + pjmedia_sdp_attr_remove(&sdp->attr_count, sdp->attr, dir_attr); + + /* Apply the direction attribute to all media, but not overriding it + * if media already has direction attribute. + */ + for (i = 0; i < sdp->media_count; ++i) { + pjmedia_sdp_media *m; + unsigned j; + + /* Find direction attribute in this media */ + m = sdp->media[i]; + for (j = 0; j < m->attr_count; ++j) { + if (!pj_strcmp(&m->attr[j]->name, &sendrecv) || + !pj_strcmp(&m->attr[j]->name, &sendonly) || + !pj_strcmp(&m->attr[j]->name, &recvonly) || + !pj_strcmp(&m->attr[j]->name, &inactive)) + { + break; + } + } + + /* Not found, apply direction attribute from session */ + if (j == m->attr_count) + pjmedia_sdp_media_add_attr(m, dir_attr); + } } } @@ -1326,8 +1325,8 @@ static void apply_media_direction(pjmedia_sdp_session *sdp) * Parse SDP message. */ PJ_DEF(pj_status_t) pjmedia_sdp_parse( pj_pool_t *pool, - char *buf, pj_size_t len, - pjmedia_sdp_session **p_sdp) + char *buf, pj_size_t len, + pjmedia_sdp_session **p_sdp) { pj_scanner scanner; pjmedia_sdp_session *session; @@ -1350,122 +1349,122 @@ PJ_DEF(pj_status_t) pjmedia_sdp_parse( pj_pool_t *pool, /* Ignore leading newlines */ while (*scanner.curptr=='\r' || *scanner.curptr=='\n') - pj_scan_get_char(&scanner); + pj_scan_get_char(&scanner); PJ_TRY { - while (!pj_scan_is_eof(&scanner)) { - cur_name = *scanner.curptr; - switch (cur_name) { - case 'a': - attr = parse_attr(pool, &scanner, &ctx); - if (attr) { - if (media) { - if (media->attr_count < PJMEDIA_MAX_SDP_ATTR) - pjmedia_sdp_media_add_attr(media, attr); - else - PJ_PERROR(2, (THIS_FILE, PJ_ETOOMANY, - "Error adding media attribute, " - "attribute is ignored")); - } else { - if (session->attr_count < PJMEDIA_MAX_SDP_ATTR) - pjmedia_sdp_session_add_attr(session, attr); - else - PJ_PERROR(2, (THIS_FILE, PJ_ETOOMANY, - "Error adding session attribute" - ", attribute is ignored")); - } - } - break; - case 'o': - parse_origin(&scanner, session, &ctx); - break; - case 's': - parse_generic_line(&scanner, &session->name, &ctx); - break; - case 'c': - conn = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_conn); - parse_connection_info(&scanner, conn, &ctx); - if (media) { - media->conn = conn; - } else { - session->conn = conn; - } - break; - case 't': - parse_time(&scanner, session, &ctx); - break; - case 'm': - media = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_media); - parse_media(&scanner, media, &ctx); - if (session->media_count < PJMEDIA_MAX_SDP_MEDIA) - session->media[ session->media_count++ ] = media; - else - PJ_PERROR(2,(THIS_FILE, PJ_ETOOMANY, - "Error adding media, media is ignored")); - break; - case 'v': - parse_version(&scanner, &ctx); - break; - case 13: - case 10: - pj_scan_get_char(&scanner); - /* Allow empty newlines at the end of the message */ - while (!pj_scan_is_eof(&scanner)) { - if (*scanner.curptr != 13 && *scanner.curptr != 10) { - ctx.last_error = PJMEDIA_SDP_EINSDP; - on_scanner_error(&scanner); - } - pj_scan_get_char(&scanner); - } - break; - case 'b': - bandw = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_bandw); - parse_bandwidth_info(&scanner, bandw, &ctx); - if (media) { - if (media->bandw_count < PJMEDIA_MAX_SDP_BANDW) - media->bandw[media->bandw_count++] = bandw; - else - PJ_PERROR(2, (THIS_FILE, PJ_ETOOMANY, - "Error adding media bandwidth " - "info, info is ignored")); - } else { - if (session->bandw_count < PJMEDIA_MAX_SDP_BANDW) - session->bandw[session->bandw_count++] = bandw; - else - PJ_PERROR(2, (THIS_FILE, PJ_ETOOMANY, - "Error adding session bandwidth " - "info, info is ignored")); - } - break; - default: - if (cur_name >= 'a' && cur_name <= 'z') - parse_generic_line(&scanner, &dummy, &ctx); - else { - ctx.last_error = PJMEDIA_SDP_EINSDP; - on_scanner_error(&scanner); - } - break; - } - } - - ctx.last_error = PJ_SUCCESS; + while (!pj_scan_is_eof(&scanner)) { + cur_name = *scanner.curptr; + switch (cur_name) { + case 'a': + attr = parse_attr(pool, &scanner, &ctx); + if (attr) { + if (media) { + if (media->attr_count < PJMEDIA_MAX_SDP_ATTR) + pjmedia_sdp_media_add_attr(media, attr); + else + PJ_PERROR(2, (THIS_FILE, PJ_ETOOMANY, + "Error adding media attribute, " + "attribute is ignored")); + } else { + if (session->attr_count < PJMEDIA_MAX_SDP_ATTR) + pjmedia_sdp_session_add_attr(session, attr); + else + PJ_PERROR(2, (THIS_FILE, PJ_ETOOMANY, + "Error adding session attribute" + ", attribute is ignored")); + } + } + break; + case 'o': + parse_origin(&scanner, session, &ctx); + break; + case 's': + parse_generic_line(&scanner, &session->name, &ctx); + break; + case 'c': + conn = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_conn); + parse_connection_info(&scanner, conn, &ctx); + if (media) { + media->conn = conn; + } else { + session->conn = conn; + } + break; + case 't': + parse_time(&scanner, session, &ctx); + break; + case 'm': + media = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_media); + parse_media(&scanner, media, &ctx); + if (session->media_count < PJMEDIA_MAX_SDP_MEDIA) + session->media[ session->media_count++ ] = media; + else + PJ_PERROR(2,(THIS_FILE, PJ_ETOOMANY, + "Error adding media, media is ignored")); + break; + case 'v': + parse_version(&scanner, &ctx); + break; + case 13: + case 10: + pj_scan_get_char(&scanner); + /* Allow empty newlines at the end of the message */ + while (!pj_scan_is_eof(&scanner)) { + if (*scanner.curptr != 13 && *scanner.curptr != 10) { + ctx.last_error = PJMEDIA_SDP_EINSDP; + on_scanner_error(&scanner); + } + pj_scan_get_char(&scanner); + } + break; + case 'b': + bandw = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_bandw); + parse_bandwidth_info(&scanner, bandw, &ctx); + if (media) { + if (media->bandw_count < PJMEDIA_MAX_SDP_BANDW) + media->bandw[media->bandw_count++] = bandw; + else + PJ_PERROR(2, (THIS_FILE, PJ_ETOOMANY, + "Error adding media bandwidth " + "info, info is ignored")); + } else { + if (session->bandw_count < PJMEDIA_MAX_SDP_BANDW) + session->bandw[session->bandw_count++] = bandw; + else + PJ_PERROR(2, (THIS_FILE, PJ_ETOOMANY, + "Error adding session bandwidth " + "info, info is ignored")); + } + break; + default: + if (cur_name >= 'a' && cur_name <= 'z') + parse_generic_line(&scanner, &dummy, &ctx); + else { + ctx.last_error = PJMEDIA_SDP_EINSDP; + on_scanner_error(&scanner); + } + break; + } + } + + ctx.last_error = PJ_SUCCESS; } - PJ_CATCH_ANY { - PJ_PERROR(4, (THIS_FILE, ctx.last_error, - "Error parsing SDP in line %d col %d", - scanner.line, pj_scan_get_col(&scanner))); + PJ_CATCH_ANY { + PJ_PERROR(4, (THIS_FILE, ctx.last_error, + "Error parsing SDP in line %d col %d", + scanner.line, pj_scan_get_col(&scanner))); - session = NULL; + session = NULL; - pj_assert(ctx.last_error != PJ_SUCCESS); + pj_assert(ctx.last_error != PJ_SUCCESS); } PJ_END; pj_scan_fini(&scanner); if (session) - apply_media_direction(session); + apply_media_direction(session); *p_sdp = session; return ctx.last_error; @@ -1475,7 +1474,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_parse( pj_pool_t *pool, * Print SDP description. */ PJ_DEF(int) pjmedia_sdp_print( const pjmedia_sdp_session *desc, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { return print_session(desc, buf, size); } @@ -1485,7 +1484,7 @@ PJ_DEF(int) pjmedia_sdp_print( const pjmedia_sdp_session *desc, * Clone session */ PJ_DEF(pjmedia_sdp_session*) pjmedia_sdp_session_clone( pj_pool_t *pool, - const pjmedia_sdp_session *rhs) + const pjmedia_sdp_session *rhs) { pjmedia_sdp_session *sess; unsigned i; @@ -1508,14 +1507,14 @@ PJ_DEF(pjmedia_sdp_session*) pjmedia_sdp_session_clone( pj_pool_t *pool, /* Clone connection line */ if (rhs->conn) { - sess->conn = pjmedia_sdp_conn_clone(pool, rhs->conn); - PJ_ASSERT_RETURN(sess->conn != NULL, NULL); + sess->conn = pjmedia_sdp_conn_clone(pool, rhs->conn); + PJ_ASSERT_RETURN(sess->conn != NULL, NULL); } /* Duplicate bandwidth info */ sess->bandw_count = rhs->bandw_count; for (i=0; ibandw_count; ++i) { - sess->bandw[i] = pjmedia_sdp_bandw_clone(pool, rhs->bandw[i]); + sess->bandw[i] = pjmedia_sdp_bandw_clone(pool, rhs->bandw[i]); } /* Clone time line. */ @@ -1525,24 +1524,24 @@ PJ_DEF(pjmedia_sdp_session*) pjmedia_sdp_session_clone( pj_pool_t *pool, /* Duplicate session attributes. */ sess->attr_count = rhs->attr_count; for (i=0; iattr_count; ++i) { - sess->attr[i] = pjmedia_sdp_attr_clone(pool, rhs->attr[i]); + sess->attr[i] = pjmedia_sdp_attr_clone(pool, rhs->attr[i]); } /* Duplicate media descriptors. */ sess->media_count = rhs->media_count; for (i=0; imedia_count; ++i) { - sess->media[i] = pjmedia_sdp_media_clone(pool, rhs->media[i]); + sess->media[i] = pjmedia_sdp_media_clone(pool, rhs->media[i]); } return sess; } -#define CHECK(exp,ret) do { \ - /*pj_assert(exp);*/ \ - if (!(exp)) \ - return ret; \ - } while (0) +#define CHECK(exp,ret) do { \ + /*pj_assert(exp);*/ \ + if (!(exp)) \ + return ret; \ + } while (0) /* Validate SDP connetion info. */ static pj_status_t validate_sdp_conn(const pjmedia_sdp_conn *c) @@ -1550,8 +1549,8 @@ static pj_status_t validate_sdp_conn(const pjmedia_sdp_conn *c) CHECK( c, PJ_EINVAL); CHECK( pj_strcmp2(&c->net_type, "IN")==0, PJMEDIA_SDP_EINCONN); CHECK( pj_strcmp2(&c->addr_type, "IP4")==0 || - pj_strcmp2(&c->addr_type, "IP6")==0, - PJMEDIA_SDP_EINCONN); + pj_strcmp2(&c->addr_type, "IP6")==0, + PJMEDIA_SDP_EINCONN); CHECK( c->addr.slen != 0, PJMEDIA_SDP_EINCONN); return PJ_SUCCESS; @@ -1567,7 +1566,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_validate(const pjmedia_sdp_session *sdp) /* Validate SDP session descriptor. */ PJ_DEF(pj_status_t) pjmedia_sdp_validate2(const pjmedia_sdp_session *sdp, - pj_bool_t strict) + pj_bool_t strict) { unsigned i; const pj_str_t STR_RTPMAP = { "rtpmap", 6 }; @@ -1577,10 +1576,10 @@ PJ_DEF(pj_status_t) pjmedia_sdp_validate2(const pjmedia_sdp_session *sdp, /* Validate origin line. */ CHECK( sdp->origin.user.slen != 0, PJMEDIA_SDP_EINORIGIN); CHECK( pj_strcmp2(&sdp->origin.net_type, "IN")==0, - PJMEDIA_SDP_EINORIGIN); + PJMEDIA_SDP_EINORIGIN); CHECK( pj_strcmp2(&sdp->origin.addr_type, "IP4")==0 || - pj_strcmp2(&sdp->origin.addr_type, "IP6")==0, - PJMEDIA_SDP_EINORIGIN); + pj_strcmp2(&sdp->origin.addr_type, "IP6")==0, + PJMEDIA_SDP_EINORIGIN); CHECK( sdp->origin.addr.slen != 0, PJMEDIA_SDP_EINORIGIN); /* Validate subject line. */ @@ -1590,63 +1589,63 @@ PJ_DEF(pj_status_t) pjmedia_sdp_validate2(const pjmedia_sdp_session *sdp, /* If session level connection info is present, validate it. */ if (sdp->conn) { - pj_status_t status = validate_sdp_conn(sdp->conn); - if (status != PJ_SUCCESS) - return status; + pj_status_t status = validate_sdp_conn(sdp->conn); + if (status != PJ_SUCCESS) + return status; } /* Validate each media. */ for (i=0; imedia_count; ++i) { - const pjmedia_sdp_media *m = sdp->media[i]; - unsigned j; - - /* Validate the m= line. */ - CHECK( m->desc.media.slen != 0, PJMEDIA_SDP_EINMEDIA); - CHECK( m->desc.transport.slen != 0, PJMEDIA_SDP_EINMEDIA); - CHECK( m->desc.fmt_count != 0 || m->desc.port==0, PJMEDIA_SDP_ENOFMT); - - /* If media level connection info is present, validate it. */ - if (m->conn) { - pj_status_t status = validate_sdp_conn(m->conn); - if (status != PJ_SUCCESS) - return status; - } - - /* If media doesn't have connection info, then connection info - * must be present in the session. - */ - if (m->conn == NULL) { - if (sdp->conn == NULL) - if (strict || m->desc.port != 0) - return PJMEDIA_SDP_EMISSINGCONN; - } - - /* Verify payload type. */ - for (j=0; jdesc.fmt_count; ++j) { - - /* Arrgh noo!! Payload type can be non-numeric!! - * RTC based programs sends "null" for instant messaging! - */ - if (pj_isdigit(*m->desc.fmt[j].ptr)) { - unsigned long pt; - pj_status_t status = pj_strtoul3(&m->desc.fmt[j], &pt, 10); - - /* Payload type is between 0 and 127. - */ - CHECK( status == PJ_SUCCESS && pt <= 127, PJMEDIA_SDP_EINPT); - - /* If port is not zero, then for each dynamic payload type, an - * rtpmap attribute must be specified. - */ - if (m->desc.port != 0 && pt >= 96) { - const pjmedia_sdp_attr *a; - - a = pjmedia_sdp_media_find_attr(m, &STR_RTPMAP, - &m->desc.fmt[j]); - CHECK( a != NULL, PJMEDIA_SDP_EMISSINGRTPMAP); - } - } - } + const pjmedia_sdp_media *m = sdp->media[i]; + unsigned j; + + /* Validate the m= line. */ + CHECK( m->desc.media.slen != 0, PJMEDIA_SDP_EINMEDIA); + CHECK( m->desc.transport.slen != 0, PJMEDIA_SDP_EINMEDIA); + CHECK( m->desc.fmt_count != 0 || m->desc.port==0, PJMEDIA_SDP_ENOFMT); + + /* If media level connection info is present, validate it. */ + if (m->conn) { + pj_status_t status = validate_sdp_conn(m->conn); + if (status != PJ_SUCCESS) + return status; + } + + /* If media doesn't have connection info, then connection info + * must be present in the session. + */ + if (m->conn == NULL) { + if (sdp->conn == NULL) + if (strict || m->desc.port != 0) + return PJMEDIA_SDP_EMISSINGCONN; + } + + /* Verify payload type. */ + for (j=0; jdesc.fmt_count; ++j) { + + /* Arrgh noo!! Payload type can be non-numeric!! + * RTC based programs sends "null" for instant messaging! + */ + if (pj_isdigit(*m->desc.fmt[j].ptr)) { + unsigned long pt; + pj_status_t status = pj_strtoul3(&m->desc.fmt[j], &pt, 10); + + /* Payload type is between 0 and 127. + */ + CHECK( status == PJ_SUCCESS && pt <= 127, PJMEDIA_SDP_EINPT); + + /* If port is not zero, then for each dynamic payload type, an + * rtpmap attribute must be specified. + */ + if (m->desc.port != 0 && pt >= 96) { + const pjmedia_sdp_attr *a; + + a = pjmedia_sdp_media_find_attr(m, &STR_RTPMAP, + &m->desc.fmt[j]); + CHECK( a != NULL, PJMEDIA_SDP_EMISSINGRTPMAP); + } + } + } } /* Looks good. */ @@ -1655,30 +1654,30 @@ PJ_DEF(pj_status_t) pjmedia_sdp_validate2(const pjmedia_sdp_session *sdp, PJ_DEF(pj_status_t) pjmedia_sdp_transport_cmp( const pj_str_t *t1, - const pj_str_t *t2) + const pj_str_t *t2) { pj_uint32_t t1_proto, t2_proto; /* Exactly equal? */ if (pj_stricmp(t1, t2) == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Check if boths are RTP/AVP based */ t1_proto = pjmedia_sdp_transport_get_proto(t1); t2_proto = pjmedia_sdp_transport_get_proto(t2); if (PJMEDIA_TP_PROTO_HAS_FLAG(t1_proto, PJMEDIA_TP_PROTO_RTP_AVP) && - PJMEDIA_TP_PROTO_HAS_FLAG(t2_proto, PJMEDIA_TP_PROTO_RTP_AVP)) + PJMEDIA_TP_PROTO_HAS_FLAG(t2_proto, PJMEDIA_TP_PROTO_RTP_AVP)) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Compatible? */ //{ - // static const pj_str_t ID_RTP_AVP = { "RTP/AVP", 7 }; - // static const pj_str_t ID_RTP_SAVP = { "RTP/SAVP", 8 }; - // if ((!pj_stricmp(t1, &ID_RTP_AVP) || !pj_stricmp(t1, &ID_RTP_SAVP)) && + // static const pj_str_t ID_RTP_AVP = { "RTP/AVP", 7 }; + // static const pj_str_t ID_RTP_SAVP = { "RTP/SAVP", 8 }; + // if ((!pj_stricmp(t1, &ID_RTP_AVP) || !pj_stricmp(t1, &ID_RTP_SAVP)) && // (!pj_stricmp(t2, &ID_RTP_AVP) || !pj_stricmp(t2, &ID_RTP_SAVP))) - // return PJ_SUCCESS; + // return PJ_SUCCESS; //} return PJMEDIA_SDP_ETPORTNOTEQUAL; @@ -1697,41 +1696,41 @@ PJ_DEF(pj_uint32_t) pjmedia_sdp_transport_get_proto(const pj_str_t *tp) idx = pj_strtok2(tp, "/", &token, 0); if (idx != tp->slen) - pj_strset(&rest, tp->ptr + token.slen + 1, tp->slen - token.slen - 1); + pj_strset(&rest, tp->ptr + token.slen + 1, tp->slen - token.slen - 1); if (pj_stricmp2(&token, "RTP") == 0) { - /* Starts with "RTP" */ + /* Starts with "RTP" */ - /* RTP/AVP */ - if (pj_stricmp2(&rest, "AVP") == 0) - return PJMEDIA_TP_PROTO_RTP_AVP; + /* RTP/AVP */ + if (pj_stricmp2(&rest, "AVP") == 0) + return PJMEDIA_TP_PROTO_RTP_AVP; - /* RTP/SAVP */ - if (pj_stricmp2(&rest, "SAVP") == 0) - return PJMEDIA_TP_PROTO_RTP_SAVP; + /* RTP/SAVP */ + if (pj_stricmp2(&rest, "SAVP") == 0) + return PJMEDIA_TP_PROTO_RTP_SAVP; - /* RTP/AVPF */ - if (pj_stricmp2(&rest, "AVPF") == 0) - return PJMEDIA_TP_PROTO_RTP_AVPF; + /* RTP/AVPF */ + if (pj_stricmp2(&rest, "AVPF") == 0) + return PJMEDIA_TP_PROTO_RTP_AVPF; - /* RTP/SAVPF */ - if (pj_stricmp2(&rest, "SAVPF") == 0) - return PJMEDIA_TP_PROTO_RTP_SAVPF; + /* RTP/SAVPF */ + if (pj_stricmp2(&rest, "SAVPF") == 0) + return PJMEDIA_TP_PROTO_RTP_SAVPF; } else if (pj_stricmp2(&token, "UDP") == 0) { - /* Starts with "UDP" */ + /* Starts with "UDP" */ - /* Plain UDP */ - if (rest.slen == 0) - return PJMEDIA_TP_PROTO_UDP; + /* Plain UDP */ + if (rest.slen == 0) + return PJMEDIA_TP_PROTO_UDP; - /* DTLS-SRTP */ - if (pj_stricmp2(&rest, "TLS/RTP/SAVP") == 0) - return PJMEDIA_TP_PROTO_DTLS_SRTP; + /* DTLS-SRTP */ + if (pj_stricmp2(&rest, "TLS/RTP/SAVP") == 0) + return PJMEDIA_TP_PROTO_DTLS_SRTP; - /* DTLS-SRTP with RTCP-FB */ - if (pj_stricmp2(&rest, "TLS/RTP/SAVPF") == 0) - return PJMEDIA_TP_PROTO_DTLS_SRTPF; + /* DTLS-SRTP with RTCP-FB */ + if (pj_stricmp2(&rest, "TLS/RTP/SAVPF") == 0) + return PJMEDIA_TP_PROTO_DTLS_SRTPF; } /* Unknown transport */ @@ -1740,7 +1739,7 @@ PJ_DEF(pj_uint32_t) pjmedia_sdp_transport_get_proto(const pj_str_t *tp) PJ_DEF(pj_status_t) pjmedia_sdp_media_deactivate(pj_pool_t *pool, - pjmedia_sdp_media *m) + pjmedia_sdp_media *m) { PJ_ASSERT_RETURN(m, PJ_EINVAL); PJ_UNUSED_ARG(pool); @@ -1756,8 +1755,8 @@ PJ_DEF(pj_status_t) pjmedia_sdp_media_deactivate(pj_pool_t *pool, PJ_DEF(pjmedia_sdp_media*) pjmedia_sdp_media_clone_deactivate( - pj_pool_t *pool, - const pjmedia_sdp_media *rhs) + pj_pool_t *pool, + const pjmedia_sdp_media *rhs) { unsigned int i; pjmedia_sdp_media *m; @@ -1771,17 +1770,17 @@ PJ_DEF(pjmedia_sdp_media*) pjmedia_sdp_media_clone_deactivate( pj_strdup (pool, &m->desc.media, &rhs->desc.media); pj_strdup (pool, &m->desc.transport, &rhs->desc.transport); for (i=0; idesc.fmt_count; ++i) - pj_strdup(pool, &m->desc.fmt[i], &rhs->desc.fmt[i]); + pj_strdup(pool, &m->desc.fmt[i], &rhs->desc.fmt[i]); if (rhs->conn) { - m->conn = pjmedia_sdp_conn_clone (pool, rhs->conn); - PJ_ASSERT_RETURN(m->conn != NULL, NULL); + m->conn = pjmedia_sdp_conn_clone (pool, rhs->conn); + PJ_ASSERT_RETURN(m->conn != NULL, NULL); } m->bandw_count = rhs->bandw_count; for (i=0; i < rhs->bandw_count; ++i) { - m->bandw[i] = pjmedia_sdp_bandw_clone (pool, rhs->bandw[i]); - PJ_ASSERT_RETURN(m->bandw[i] != NULL, NULL); + m->bandw[i] = pjmedia_sdp_bandw_clone (pool, rhs->bandw[i]); + PJ_ASSERT_RETURN(m->bandw[i] != NULL, NULL); } /* And deactivate it */ diff --git a/pjmedia/src/pjmedia/sdp_cmp.c b/pjmedia/src/pjmedia/sdp_cmp.c index b4a23c74a8..5a57b2a642 100644 --- a/pjmedia/src/pjmedia/sdp_cmp.c +++ b/pjmedia/src/pjmedia/sdp_cmp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,28 +24,28 @@ /* Compare connection line. */ static pj_status_t compare_conn(const pjmedia_sdp_conn *c1, - const pjmedia_sdp_conn *c2) + const pjmedia_sdp_conn *c2) { /* Compare network type. */ if (pj_strcmp(&c1->net_type, &c2->net_type) != 0) - return PJMEDIA_SDP_ECONNNOTEQUAL; + return PJMEDIA_SDP_ECONNNOTEQUAL; /* Compare address type. */ if (pj_strcmp(&c1->addr_type, &c2->addr_type) != 0) - return PJMEDIA_SDP_ECONNNOTEQUAL; + return PJMEDIA_SDP_ECONNNOTEQUAL; /* Compare address. */ if (pj_strcmp(&c1->addr, &c2->addr) != 0) - return PJMEDIA_SDP_ECONNNOTEQUAL; + return PJMEDIA_SDP_ECONNNOTEQUAL; return PJ_SUCCESS; } /* Compare attributes array. */ static pj_status_t compare_attr_imp(unsigned count1, - pjmedia_sdp_attr *const attr1[], - unsigned count2, - pjmedia_sdp_attr *const attr2[]) + pjmedia_sdp_attr *const attr1[], + unsigned count2, + pjmedia_sdp_attr *const attr2[]) { pj_status_t status; unsigned i; @@ -59,77 +58,77 @@ static pj_status_t compare_attr_imp(unsigned count1, /* For simplicity, we only compare the following attributes, and ignore * the others: - * - direction, eg. inactive, sendonly, recvonly, sendrecv - * - fmtp for each payload. - * - rtpmap for each payload. + * - direction, eg. inactive, sendonly, recvonly, sendrecv + * - fmtp for each payload. + * - rtpmap for each payload. */ for (i=0; iname, &inactive) == 0 || - pj_strcmp(&a1->name, &sendrecv) == 0 || - pj_strcmp(&a1->name, &sendonly) == 0 || - pj_strcmp(&a1->name, &recvonly) == 0) - { - /* For inactive, sendrecv, sendonly, and recvonly attributes, - * the same attribute must be present on the other SDP. - */ - const pjmedia_sdp_attr *a2; - a2 = pjmedia_sdp_attr_find(count2, attr2, &a1->name, NULL); - if (!a2) - return PJMEDIA_SDP_EDIRNOTEQUAL; - - } else if (pj_strcmp(&a1->name, &fmtp) == 0) { - /* For fmtp attribute, find the fmtp attribute in the other SDP - * for the same payload type, and compare the fmtp param/value. - */ - pjmedia_sdp_fmtp fmtp1, fmtp2; - const pjmedia_sdp_attr *a2; - - status = pjmedia_sdp_attr_get_fmtp(a1, &fmtp1); - if (status != PJ_SUCCESS) - return PJMEDIA_SDP_EFMTPNOTEQUAL; - - a2 = pjmedia_sdp_attr_find(count2, attr2, &a1->name, &fmtp1.fmt); - if (!a2) - return PJMEDIA_SDP_EFMTPNOTEQUAL; - - status = pjmedia_sdp_attr_get_fmtp(a2, &fmtp2); - if (status != PJ_SUCCESS) - return PJMEDIA_SDP_EFMTPNOTEQUAL; - - if (pj_strcmp(&fmtp1.fmt_param, &fmtp2.fmt_param) != 0) - return PJMEDIA_SDP_EFMTPNOTEQUAL; - - } else if (pj_strcmp(&a1->name, &rtpmap) == 0) { - /* For rtpmap attribute, find rtpmap attribute on the other SDP - * for the same payload type, and compare both rtpmap atribute - * values. - */ - pjmedia_sdp_rtpmap r1, r2; - const pjmedia_sdp_attr *a2; - - status = pjmedia_sdp_attr_get_rtpmap(a1, &r1); - if (status != PJ_SUCCESS) - return PJMEDIA_SDP_ERTPMAPNOTEQUAL; - - a2 = pjmedia_sdp_attr_find(count2, attr2, &a1->name, &r1.pt); - if (!a2) - return PJMEDIA_SDP_ERTPMAPNOTEQUAL; - - status = pjmedia_sdp_attr_get_rtpmap(a2, &r2); - if (status != PJ_SUCCESS) - return PJMEDIA_SDP_ERTPMAPNOTEQUAL; - - if (pj_strcmp(&r1.pt, &r2.pt) != 0) - return PJMEDIA_SDP_ERTPMAPNOTEQUAL; - if (pj_strcmp(&r1.enc_name, &r2.enc_name) != 0) - return PJMEDIA_SDP_ERTPMAPNOTEQUAL; - if (r1.clock_rate != r2.clock_rate) - return PJMEDIA_SDP_ERTPMAPNOTEQUAL; - if (pj_strcmp(&r1.param, &r2.param) != 0) - return PJMEDIA_SDP_ERTPMAPNOTEQUAL; - } + const pjmedia_sdp_attr *a1 = attr1[i]; + + if (pj_strcmp(&a1->name, &inactive) == 0 || + pj_strcmp(&a1->name, &sendrecv) == 0 || + pj_strcmp(&a1->name, &sendonly) == 0 || + pj_strcmp(&a1->name, &recvonly) == 0) + { + /* For inactive, sendrecv, sendonly, and recvonly attributes, + * the same attribute must be present on the other SDP. + */ + const pjmedia_sdp_attr *a2; + a2 = pjmedia_sdp_attr_find(count2, attr2, &a1->name, NULL); + if (!a2) + return PJMEDIA_SDP_EDIRNOTEQUAL; + + } else if (pj_strcmp(&a1->name, &fmtp) == 0) { + /* For fmtp attribute, find the fmtp attribute in the other SDP + * for the same payload type, and compare the fmtp param/value. + */ + pjmedia_sdp_fmtp fmtp1, fmtp2; + const pjmedia_sdp_attr *a2; + + status = pjmedia_sdp_attr_get_fmtp(a1, &fmtp1); + if (status != PJ_SUCCESS) + return PJMEDIA_SDP_EFMTPNOTEQUAL; + + a2 = pjmedia_sdp_attr_find(count2, attr2, &a1->name, &fmtp1.fmt); + if (!a2) + return PJMEDIA_SDP_EFMTPNOTEQUAL; + + status = pjmedia_sdp_attr_get_fmtp(a2, &fmtp2); + if (status != PJ_SUCCESS) + return PJMEDIA_SDP_EFMTPNOTEQUAL; + + if (pj_strcmp(&fmtp1.fmt_param, &fmtp2.fmt_param) != 0) + return PJMEDIA_SDP_EFMTPNOTEQUAL; + + } else if (pj_strcmp(&a1->name, &rtpmap) == 0) { + /* For rtpmap attribute, find rtpmap attribute on the other SDP + * for the same payload type, and compare both rtpmap atribute + * values. + */ + pjmedia_sdp_rtpmap r1, r2; + const pjmedia_sdp_attr *a2; + + status = pjmedia_sdp_attr_get_rtpmap(a1, &r1); + if (status != PJ_SUCCESS) + return PJMEDIA_SDP_ERTPMAPNOTEQUAL; + + a2 = pjmedia_sdp_attr_find(count2, attr2, &a1->name, &r1.pt); + if (!a2) + return PJMEDIA_SDP_ERTPMAPNOTEQUAL; + + status = pjmedia_sdp_attr_get_rtpmap(a2, &r2); + if (status != PJ_SUCCESS) + return PJMEDIA_SDP_ERTPMAPNOTEQUAL; + + if (pj_strcmp(&r1.pt, &r2.pt) != 0) + return PJMEDIA_SDP_ERTPMAPNOTEQUAL; + if (pj_strcmp(&r1.enc_name, &r2.enc_name) != 0) + return PJMEDIA_SDP_ERTPMAPNOTEQUAL; + if (r1.clock_rate != r2.clock_rate) + return PJMEDIA_SDP_ERTPMAPNOTEQUAL; + if (pj_strcmp(&r1.param, &r2.param) != 0) + return PJMEDIA_SDP_ERTPMAPNOTEQUAL; + } } return PJ_SUCCESS; @@ -138,27 +137,27 @@ static pj_status_t compare_attr_imp(unsigned count1, /* Compare attributes array. */ static pj_status_t compare_attr(unsigned count1, - pjmedia_sdp_attr *const attr1[], - unsigned count2, - pjmedia_sdp_attr *const attr2[]) + pjmedia_sdp_attr *const attr1[], + unsigned count2, + pjmedia_sdp_attr *const attr2[]) { pj_status_t status; status = compare_attr_imp(count1, attr1, count2, attr2); if (status != PJ_SUCCESS) - return status; + return status; status = compare_attr_imp(count2, attr2, count1, attr1); if (status != PJ_SUCCESS) - return status; + return status; return PJ_SUCCESS; } /* Compare media descriptor */ PJ_DEF(pj_status_t) pjmedia_sdp_media_cmp( const pjmedia_sdp_media *sd1, - const pjmedia_sdp_media *sd2, - unsigned option) + const pjmedia_sdp_media *sd2, + unsigned option) { unsigned i; pj_status_t status; @@ -169,49 +168,49 @@ PJ_DEF(pj_status_t) pjmedia_sdp_media_cmp( const pjmedia_sdp_media *sd1, /* Compare media type. */ if (pj_strcmp(&sd1->desc.media, &sd2->desc.media) != 0) - return PJMEDIA_SDP_EMEDIANOTEQUAL; + return PJMEDIA_SDP_EMEDIANOTEQUAL; /* Compare port number. */ if (sd1->desc.port != sd2->desc.port) - return PJMEDIA_SDP_EPORTNOTEQUAL; + return PJMEDIA_SDP_EPORTNOTEQUAL; /* Compare port count. */ if (sd1->desc.port_count != sd2->desc.port_count) - return PJMEDIA_SDP_EPORTNOTEQUAL; + return PJMEDIA_SDP_EPORTNOTEQUAL; /* Compare transports. */ if (pj_strcmp(&sd1->desc.transport, &sd2->desc.transport) != 0) - return PJMEDIA_SDP_ETPORTNOTEQUAL; + return PJMEDIA_SDP_ETPORTNOTEQUAL; /* For zeroed port media, stop comparing here */ if (sd1->desc.port == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Compare number of formats. */ if (sd1->desc.fmt_count != sd2->desc.fmt_count) - return PJMEDIA_SDP_EFORMATNOTEQUAL; + return PJMEDIA_SDP_EFORMATNOTEQUAL; /* Compare formats, in order. */ for (i=0; idesc.fmt_count; ++i) { - if (pj_strcmp(&sd1->desc.fmt[i], &sd2->desc.fmt[i]) != 0) - return PJMEDIA_SDP_EFORMATNOTEQUAL; + if (pj_strcmp(&sd1->desc.fmt[i], &sd2->desc.fmt[i]) != 0) + return PJMEDIA_SDP_EFORMATNOTEQUAL; } /* Compare connection line, if they exist. */ if (sd1->conn) { - if (!sd2->conn) - return PJMEDIA_SDP_EMEDIANOTEQUAL; - status = compare_conn(sd1->conn, sd2->conn); + if (!sd2->conn) + return PJMEDIA_SDP_EMEDIANOTEQUAL; + status = compare_conn(sd1->conn, sd2->conn); } else { - if (sd2->conn) - return PJMEDIA_SDP_EMEDIANOTEQUAL; + if (sd2->conn) + return PJMEDIA_SDP_EMEDIANOTEQUAL; } /* Compare attributes. */ status = compare_attr(sd1->attr_count, sd1->attr, - sd2->attr_count, sd2->attr); + sd2->attr_count, sd2->attr); if (status != PJ_SUCCESS) - return status; + return status; /* Looks equal */ return PJ_SUCCESS; @@ -221,8 +220,8 @@ PJ_DEF(pj_status_t) pjmedia_sdp_media_cmp( const pjmedia_sdp_media *sd1, * Compare two SDP session for equality. */ PJ_DEF(pj_status_t) pjmedia_sdp_session_cmp( const pjmedia_sdp_session *sd1, - const pjmedia_sdp_session *sd2, - unsigned option) + const pjmedia_sdp_session *sd2, + unsigned option) { unsigned i; pj_status_t status; @@ -233,61 +232,61 @@ PJ_DEF(pj_status_t) pjmedia_sdp_session_cmp( const pjmedia_sdp_session *sd1, /* Compare the origin line. */ if (pj_strcmp(&sd1->origin.user, &sd2->origin.user) != 0) - return PJMEDIA_SDP_EORIGINNOTEQUAL; + return PJMEDIA_SDP_EORIGINNOTEQUAL; if (sd1->origin.id != sd2->origin.id) - return PJMEDIA_SDP_EORIGINNOTEQUAL; + return PJMEDIA_SDP_EORIGINNOTEQUAL; if (sd1->origin.version != sd2->origin.version) - return PJMEDIA_SDP_EORIGINNOTEQUAL; + return PJMEDIA_SDP_EORIGINNOTEQUAL; if (pj_strcmp(&sd1->origin.net_type, &sd2->origin.net_type) != 0) - return PJMEDIA_SDP_EORIGINNOTEQUAL; + return PJMEDIA_SDP_EORIGINNOTEQUAL; if (pj_strcmp(&sd1->origin.addr_type, &sd2->origin.addr_type) != 0) - return PJMEDIA_SDP_EORIGINNOTEQUAL; + return PJMEDIA_SDP_EORIGINNOTEQUAL; if (pj_strcmp(&sd1->origin.addr, &sd2->origin.addr) != 0) - return PJMEDIA_SDP_EORIGINNOTEQUAL; + return PJMEDIA_SDP_EORIGINNOTEQUAL; /* Compare the subject line. */ if (pj_strcmp(&sd1->name, &sd2->name) != 0) - return PJMEDIA_SDP_ENAMENOTEQUAL; + return PJMEDIA_SDP_ENAMENOTEQUAL; /* Compare connection line, when they exist */ if (sd1->conn) { - if (!sd2->conn) - return PJMEDIA_SDP_ECONNNOTEQUAL; - status = compare_conn(sd1->conn, sd2->conn); - if (status != PJ_SUCCESS) - return status; + if (!sd2->conn) + return PJMEDIA_SDP_ECONNNOTEQUAL; + status = compare_conn(sd1->conn, sd2->conn); + if (status != PJ_SUCCESS) + return status; } else { - if (sd2->conn) - return PJMEDIA_SDP_ECONNNOTEQUAL; + if (sd2->conn) + return PJMEDIA_SDP_ECONNNOTEQUAL; } /* Compare time line. */ if (sd1->time.start != sd2->time.start) - return PJMEDIA_SDP_ETIMENOTEQUAL; + return PJMEDIA_SDP_ETIMENOTEQUAL; if (sd1->time.stop != sd2->time.stop) - return PJMEDIA_SDP_ETIMENOTEQUAL; + return PJMEDIA_SDP_ETIMENOTEQUAL; /* Compare attributes. */ status = compare_attr(sd1->attr_count, sd1->attr, - sd2->attr_count, sd2->attr); + sd2->attr_count, sd2->attr); if (status != PJ_SUCCESS) - return status; + return status; /* Compare media lines. */ if (sd1->media_count != sd2->media_count) - return PJMEDIA_SDP_EMEDIANOTEQUAL; + return PJMEDIA_SDP_EMEDIANOTEQUAL; for (i=0; imedia_count; ++i) { - status = pjmedia_sdp_media_cmp(sd1->media[i], sd2->media[i], 0); - if (status != PJ_SUCCESS) - return status; + status = pjmedia_sdp_media_cmp(sd1->media[i], sd2->media[i], 0); + if (status != PJ_SUCCESS) + return status; } /* Looks equal. */ @@ -296,8 +295,8 @@ PJ_DEF(pj_status_t) pjmedia_sdp_session_cmp( const pjmedia_sdp_session *sd1, PJ_DEF(pj_status_t) pjmedia_sdp_conn_cmp(const pjmedia_sdp_conn *conn1, - const pjmedia_sdp_conn *conn2, - unsigned option) + const pjmedia_sdp_conn *conn2, + unsigned option) { PJ_UNUSED_ARG(option); return compare_conn(conn1, conn2); diff --git a/pjmedia/src/pjmedia/sdp_neg.c b/pjmedia/src/pjmedia/sdp_neg.c index b22d14dfb9..35dad24918 100644 --- a/pjmedia/src/pjmedia/sdp_neg.c +++ b/pjmedia/src/pjmedia/sdp_neg.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,18 +30,18 @@ */ struct pjmedia_sdp_neg { - pjmedia_sdp_neg_state state; /**< Negotiator state. */ - pj_bool_t prefer_remote_codec_order; + pjmedia_sdp_neg_state state; /**< Negotiator state. */ + pj_bool_t prefer_remote_codec_order; pj_bool_t answer_with_multiple_codecs; - pj_bool_t has_remote_answer; - pj_bool_t answer_was_remote; - - pjmedia_sdp_session *initial_sdp, /**< Initial local SDP */ - *initial_sdp_tmp, /**< Temporary initial local SDP */ - *active_local_sdp, /**< Currently active local SDP. */ - *active_remote_sdp, /**< Currently active remote's. */ - *neg_local_sdp, /**< Temporary local SDP. */ - *neg_remote_sdp; /**< Temporary remote SDP. */ + pj_bool_t has_remote_answer; + pj_bool_t answer_was_remote; + + pjmedia_sdp_session *initial_sdp, /**< Initial local SDP */ + *initial_sdp_tmp, /**< Temporary initial local SDP */ + *active_local_sdp, /**< Currently active local SDP. */ + *active_remote_sdp, /**< Currently active remote's. */ + *neg_local_sdp, /**< Temporary local SDP. */ + *neg_remote_sdp; /**< Temporary remote SDP. */ }; static const char *state_str[] = @@ -57,7 +56,7 @@ static const char *state_str[] = /* Definition of customized SDP format negotiation callback */ struct fmt_match_cb_t { - pj_str_t fmt_name; + pj_str_t fmt_name; pjmedia_sdp_neg_fmt_match_cb cb; }; @@ -66,18 +65,18 @@ static unsigned fmt_match_cb_cnt; /* The registered customized SDP format negotiation callbacks */ static struct fmt_match_cb_t - fmt_match_cb[PJMEDIA_SDP_NEG_MAX_CUSTOM_FMT_NEG_CB]; + fmt_match_cb[PJMEDIA_SDP_NEG_MAX_CUSTOM_FMT_NEG_CB]; /* Redefining a very long identifier name, just for convenience */ #define ALLOW_MODIFY_ANSWER PJMEDIA_SDP_NEG_FMT_MATCH_ALLOW_MODIFY_ANSWER static pj_status_t custom_fmt_match( pj_pool_t *pool, - const pj_str_t *fmt_name, - pjmedia_sdp_media *offer, - unsigned o_fmt_idx, - pjmedia_sdp_media *answer, - unsigned a_fmt_idx, - unsigned option); + const pj_str_t *fmt_name, + pjmedia_sdp_media *offer, + unsigned o_fmt_idx, + pjmedia_sdp_media *answer, + unsigned a_fmt_idx, + unsigned option); /* @@ -86,7 +85,7 @@ static pj_status_t custom_fmt_match( pj_pool_t *pool, PJ_DEF(const char*) pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_state state) { if ((int)state >=0 && state < (pjmedia_sdp_neg_state)PJ_ARRAY_SIZE(state_str)) - return state_str[state]; + return state_str[state]; return ""; } @@ -96,8 +95,8 @@ PJ_DEF(const char*) pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_state state) * Create with local offer. */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_create_w_local_offer( pj_pool_t *pool, - const pjmedia_sdp_session *local, - pjmedia_sdp_neg **p_neg) + const pjmedia_sdp_session *local, + pjmedia_sdp_neg **p_neg) { pjmedia_sdp_neg *neg; pj_status_t status; @@ -128,9 +127,9 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_create_w_local_offer( pj_pool_t *pool, * Create with remote offer and initial local offer/answer. */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_create_w_remote_offer(pj_pool_t *pool, - const pjmedia_sdp_session *initial, - const pjmedia_sdp_session *remote, - pjmedia_sdp_neg **p_neg) + const pjmedia_sdp_session *initial, + const pjmedia_sdp_session *remote, + pjmedia_sdp_neg **p_neg) { pjmedia_sdp_neg *neg; pj_status_t status; @@ -143,7 +142,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_create_w_remote_offer(pj_pool_t *pool, /* Validate remote offer and initial answer */ status = pjmedia_sdp_validate2(remote, PJ_FALSE); if (status != PJ_SUCCESS) - return status; + return status; /* Create and initialize negotiator. */ neg = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_neg); @@ -154,17 +153,17 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_create_w_remote_offer(pj_pool_t *pool, neg->neg_remote_sdp = pjmedia_sdp_session_clone(pool, remote); if (initial) { - PJ_ASSERT_RETURN((status=pjmedia_sdp_validate(initial))==PJ_SUCCESS, - status); + PJ_ASSERT_RETURN((status=pjmedia_sdp_validate(initial))==PJ_SUCCESS, + status); - neg->initial_sdp = pjmedia_sdp_session_clone(pool, initial); - neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, initial); + neg->initial_sdp = pjmedia_sdp_session_clone(pool, initial); + neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, initial); - neg->state = PJMEDIA_SDP_NEG_STATE_WAIT_NEGO; + neg->state = PJMEDIA_SDP_NEG_STATE_WAIT_NEGO; } else { - - neg->state = PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER; + + neg->state = PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER; } @@ -177,8 +176,8 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_create_w_remote_offer(pj_pool_t *pool, * Set codec order preference. */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_prefer_remote_codec_order( - pjmedia_sdp_neg *neg, - pj_bool_t prefer_remote) + pjmedia_sdp_neg *neg, + pj_bool_t prefer_remote) { PJ_ASSERT_RETURN(neg, PJ_EINVAL); neg->prefer_remote_codec_order = prefer_remote; @@ -211,7 +210,7 @@ PJ_DEF(pjmedia_sdp_neg_state) pjmedia_sdp_neg_get_state( pjmedia_sdp_neg *neg ) PJ_DEF(pj_status_t) pjmedia_sdp_neg_get_active_local( pjmedia_sdp_neg *neg, - const pjmedia_sdp_session **local) + const pjmedia_sdp_session **local) { PJ_ASSERT_RETURN(neg && local, PJ_EINVAL); PJ_ASSERT_RETURN(neg->active_local_sdp, PJMEDIA_SDPNEG_ENOACTIVE); @@ -222,7 +221,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_get_active_local( pjmedia_sdp_neg *neg, PJ_DEF(pj_status_t) pjmedia_sdp_neg_get_active_remote( pjmedia_sdp_neg *neg, - const pjmedia_sdp_session **remote) + const pjmedia_sdp_session **remote) { PJ_ASSERT_RETURN(neg && remote, PJ_EINVAL); PJ_ASSERT_RETURN(neg->active_remote_sdp, PJMEDIA_SDPNEG_ENOACTIVE); @@ -241,7 +240,7 @@ PJ_DEF(pj_bool_t) pjmedia_sdp_neg_was_answer_remote(pjmedia_sdp_neg *neg) PJ_DEF(pj_status_t) pjmedia_sdp_neg_get_neg_remote( pjmedia_sdp_neg *neg, - const pjmedia_sdp_session **remote) + const pjmedia_sdp_session **remote) { PJ_ASSERT_RETURN(neg && remote, PJ_EINVAL); PJ_ASSERT_RETURN(neg->neg_remote_sdp, PJMEDIA_SDPNEG_ENONEG); @@ -251,7 +250,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_get_neg_remote( pjmedia_sdp_neg *neg, } PJ_DEF(pj_status_t) pjmedia_sdp_neg_get_neg_local( pjmedia_sdp_neg *neg, - const pjmedia_sdp_session **local) + const pjmedia_sdp_session **local) { PJ_ASSERT_RETURN(neg && local, PJ_EINVAL); PJ_ASSERT_RETURN(neg->neg_local_sdp, PJMEDIA_SDPNEG_ENONEG); @@ -261,7 +260,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_get_neg_local( pjmedia_sdp_neg *neg, } static pjmedia_sdp_media *sdp_media_clone_deactivate( - pj_pool_t *pool, + pj_pool_t *pool, const pjmedia_sdp_media *rem_med, const pjmedia_sdp_media *local_med, const pjmedia_sdp_session *local_sess) @@ -270,17 +269,17 @@ static pjmedia_sdp_media *sdp_media_clone_deactivate( res = pjmedia_sdp_media_clone_deactivate(pool, rem_med); if (!res) - return NULL; + return NULL; if (!res->conn && (!local_sess || !local_sess->conn)) { - if (local_med && local_med->conn) - res->conn = pjmedia_sdp_conn_clone(pool, local_med->conn); - else { - res->conn = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_conn); - res->conn->net_type = pj_str("IN"); - res->conn->addr_type = pj_str("IP4"); - res->conn->addr = pj_str("127.0.0.1"); - } + if (local_med && local_med->conn) + res->conn = pjmedia_sdp_conn_clone(pool, local_med->conn); + else { + res->conn = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_conn); + res->conn->net_type = pj_str("IN"); + res->conn->addr_type = pj_str("IP4"); + res->conn->addr = pj_str("127.0.0.1"); + } } return res; @@ -290,17 +289,17 @@ static pjmedia_sdp_media *sdp_media_clone_deactivate( * Modify local SDP and wait for remote answer. */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer( pj_pool_t *pool, - pjmedia_sdp_neg *neg, - const pjmedia_sdp_session *local) + pjmedia_sdp_neg *neg, + const pjmedia_sdp_session *local) { return pjmedia_sdp_neg_modify_local_offer2(pool, neg, 0, local); } PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer2( pj_pool_t *pool, - pjmedia_sdp_neg *neg, + pjmedia_sdp_neg *neg, unsigned flags, - const pjmedia_sdp_session *local) + const pjmedia_sdp_session *local) { pjmedia_sdp_session *new_offer; pjmedia_sdp_session *old_offer; @@ -312,12 +311,12 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer2( /* Can only do this in STATE_DONE. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_DONE, - PJMEDIA_SDPNEG_EINSTATE); + PJMEDIA_SDPNEG_EINSTATE); /* Validate the new offer */ status = pjmedia_sdp_validate(local); if (status != PJ_SUCCESS) - return status; + return status; /* Change state to STATE_LOCAL_OFFER */ neg->state = PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER; @@ -327,11 +326,11 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer2( * so we'll just set the local SDP offer here. */ if (!neg->active_local_sdp) { - neg->initial_sdp_tmp = NULL; - neg->initial_sdp = pjmedia_sdp_session_clone(pool, local); - neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, local); + neg->initial_sdp_tmp = NULL; + neg->initial_sdp = pjmedia_sdp_session_clone(pool, local); + neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, local); - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Init vars */ @@ -358,39 +357,39 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer2( * port number set to zero. */ for (oi = 0; oi < old_offer->media_count; ++oi) { - pjmedia_sdp_media *om; - pjmedia_sdp_media *nm; - unsigned ni; /* new offer media index */ - pj_bool_t found = PJ_FALSE; - - om = old_offer->media[oi]; - for (ni = oi; ni < new_offer->media_count; ++ni) { - nm = new_offer->media[ni]; - if (pj_strcmp(&nm->desc.media, &om->desc.media) == 0) { - if (ni != oi) { - /* The same media found but the position unmatched to + pjmedia_sdp_media *om; + pjmedia_sdp_media *nm; + unsigned ni; /* new offer media index */ + pj_bool_t found = PJ_FALSE; + + om = old_offer->media[oi]; + for (ni = oi; ni < new_offer->media_count; ++ni) { + nm = new_offer->media[ni]; + if (pj_strcmp(&nm->desc.media, &om->desc.media) == 0) { + if (ni != oi) { + /* The same media found but the position unmatched to * the old offer, so let's put this media in the right * place, and keep the order of the rest. - */ - pj_array_insert( - new_offer->media, /* array */ - sizeof(new_offer->media[0]), /* elmt size*/ - ni, /* count */ - oi, /* pos */ - &nm); /* new elmt */ - } - found = PJ_TRUE; - break; - } - } - if (!found) { - pjmedia_sdp_media *m; - - m = sdp_media_clone_deactivate(pool, om, om, local); - - pj_array_insert(new_offer->media, sizeof(new_offer->media[0]), - new_offer->media_count++, oi, &m); - } + */ + pj_array_insert( + new_offer->media, /* array */ + sizeof(new_offer->media[0]), /* elmt size*/ + ni, /* count */ + oi, /* pos */ + &nm); /* new elmt */ + } + found = PJ_TRUE; + break; + } + } + if (!found) { + pjmedia_sdp_media *m; + + m = sdp_media_clone_deactivate(pool, om, om, local); + + pj_array_insert(new_offer->media, sizeof(new_offer->media[0]), + new_offer->media_count++, oi, &m); + } } } else { /* If media type change is allowed, the negotiator only needs to fix @@ -400,11 +399,11 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer2( for (oi = new_offer->media_count; oi < old_offer->media_count; ++oi) { pjmedia_sdp_media *m; - m = sdp_media_clone_deactivate(pool, old_offer->media[oi], + m = sdp_media_clone_deactivate(pool, old_offer->media[oi], old_offer->media[oi], local); - pj_array_insert(new_offer->media, sizeof(new_offer->media[0]), - new_offer->media_count++, oi, &m); + pj_array_insert(new_offer->media, sizeof(new_offer->media[0]), + new_offer->media_count++, oi, &m); } } @@ -415,7 +414,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer2( if (pjmedia_sdp_session_cmp(new_offer, neg->initial_sdp, 0) != PJ_SUCCESS) { - ++new_offer->origin.version; + ++new_offer->origin.version; } #else new_offer->origin.version = old_offer->origin.version + 1; @@ -430,8 +429,8 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer2( PJ_DEF(pj_status_t) pjmedia_sdp_neg_send_local_offer( pj_pool_t *pool, - pjmedia_sdp_neg *neg, - const pjmedia_sdp_session **offer) + pjmedia_sdp_neg *neg, + const pjmedia_sdp_session **offer) { /* Check arguments are valid. */ PJ_ASSERT_RETURN(neg && offer, PJ_EINVAL); @@ -440,41 +439,41 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_send_local_offer( pj_pool_t *pool, /* Can only do this in STATE_DONE or STATE_LOCAL_OFFER. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_DONE || - neg->state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER, - PJMEDIA_SDPNEG_EINSTATE); + neg->state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER, + PJMEDIA_SDPNEG_EINSTATE); if (neg->state == PJMEDIA_SDP_NEG_STATE_DONE) { - /* If in STATE_DONE, set the active SDP as the offer. */ - PJ_ASSERT_RETURN(neg->active_local_sdp, PJMEDIA_SDPNEG_ENOACTIVE); - - /* Retain initial SDP */ - if (neg->initial_sdp) { - neg->initial_sdp_tmp = neg->initial_sdp; - neg->initial_sdp = pjmedia_sdp_session_clone(pool, - neg->initial_sdp); - } + /* If in STATE_DONE, set the active SDP as the offer. */ + PJ_ASSERT_RETURN(neg->active_local_sdp, PJMEDIA_SDPNEG_ENOACTIVE); + + /* Retain initial SDP */ + if (neg->initial_sdp) { + neg->initial_sdp_tmp = neg->initial_sdp; + neg->initial_sdp = pjmedia_sdp_session_clone(pool, + neg->initial_sdp); + } - neg->state = PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER; - neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, - neg->active_local_sdp); + neg->state = PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER; + neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, + neg->active_local_sdp); #if PJMEDIA_SDP_NEG_COMPARE_BEFORE_INC_VERSION - if (pjmedia_sdp_session_cmp(neg->neg_local_sdp, - neg->initial_sdp, 0) != PJ_SUCCESS) - { - neg->neg_local_sdp->origin.version++; - } + if (pjmedia_sdp_session_cmp(neg->neg_local_sdp, + neg->initial_sdp, 0) != PJ_SUCCESS) + { + neg->neg_local_sdp->origin.version++; + } #else - neg->neg_local_sdp->origin.version++; + neg->neg_local_sdp->origin.version++; #endif - *offer = neg->neg_local_sdp; + *offer = neg->neg_local_sdp; } else { - /* We assume that we're in STATE_LOCAL_OFFER. - * In this case set the neg_local_sdp as the offer. - */ - *offer = neg->neg_local_sdp; + /* We assume that we're in STATE_LOCAL_OFFER. + * In this case set the neg_local_sdp as the offer. + */ + *offer = neg->neg_local_sdp; } return PJ_SUCCESS; @@ -482,8 +481,8 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_send_local_offer( pj_pool_t *pool, PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_remote_answer( pj_pool_t *pool, - pjmedia_sdp_neg *neg, - const pjmedia_sdp_session *remote) + pjmedia_sdp_neg *neg, + const pjmedia_sdp_session *remote) { /* Check arguments are valid. */ PJ_ASSERT_RETURN(pool && neg && remote, PJ_EINVAL); @@ -493,7 +492,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_remote_answer( pj_pool_t *pool, * be called instead of this function. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER, - PJMEDIA_SDPNEG_EINSTATE); + PJMEDIA_SDPNEG_EINSTATE); /* We're ready to negotiate. */ neg->state = PJMEDIA_SDP_NEG_STATE_WAIT_NEGO; @@ -504,8 +503,8 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_remote_answer( pj_pool_t *pool, } PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_remote_offer( pj_pool_t *pool, - pjmedia_sdp_neg *neg, - const pjmedia_sdp_session *remote) + pjmedia_sdp_neg *neg, + const pjmedia_sdp_session *remote) { /* Check arguments are valid. */ PJ_ASSERT_RETURN(pool && neg && remote, PJ_EINVAL); @@ -515,7 +514,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_remote_offer( pj_pool_t *pool, * be called instead of this function. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_DONE, - PJMEDIA_SDPNEG_EINSTATE); + PJMEDIA_SDPNEG_EINSTATE); /* State now is STATE_REMOTE_OFFER. */ neg->state = PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER; @@ -525,8 +524,8 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_remote_offer( pj_pool_t *pool, } PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_local_answer( pj_pool_t *pool, - pjmedia_sdp_neg *neg, - const pjmedia_sdp_session *local) + pjmedia_sdp_neg *neg, + const pjmedia_sdp_session *local) { /* Check arguments are valid. */ PJ_ASSERT_RETURN(pool && neg && local, PJ_EINVAL); @@ -536,34 +535,34 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_local_answer( pj_pool_t *pool, * be called instead of this function. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER || - neg->state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO, - PJMEDIA_SDPNEG_EINSTATE); + neg->state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO, + PJMEDIA_SDPNEG_EINSTATE); /* State now is STATE_WAIT_NEGO. */ neg->state = PJMEDIA_SDP_NEG_STATE_WAIT_NEGO; if (local) { - neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, local); - if (neg->initial_sdp) { - /* Retain initial_sdp value. */ - neg->initial_sdp_tmp = neg->initial_sdp; - neg->initial_sdp = pjmedia_sdp_session_clone(pool, - neg->initial_sdp); + neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, local); + if (neg->initial_sdp) { + /* Retain initial_sdp value. */ + neg->initial_sdp_tmp = neg->initial_sdp; + neg->initial_sdp = pjmedia_sdp_session_clone(pool, + neg->initial_sdp); - /* I don't think there is anything in RFC 3264 that mandates - * answerer to place the same origin (and increment version) - * in the answer, but probably it won't hurt either. - * Note that the version will be incremented in - * pjmedia_sdp_neg_negotiate() - */ - neg->neg_local_sdp->origin.id = neg->initial_sdp->origin.id; - } else { - neg->initial_sdp = pjmedia_sdp_session_clone(pool, local); - } + /* I don't think there is anything in RFC 3264 that mandates + * answerer to place the same origin (and increment version) + * in the answer, but probably it won't hurt either. + * Note that the version will be incremented in + * pjmedia_sdp_neg_negotiate() + */ + neg->neg_local_sdp->origin.id = neg->initial_sdp->origin.id; + } else { + neg->initial_sdp = pjmedia_sdp_session_clone(pool, local); + } } else { - PJ_ASSERT_RETURN(neg->initial_sdp, PJMEDIA_SDPNEG_ENOINITIAL); - neg->initial_sdp_tmp = neg->initial_sdp; - neg->initial_sdp = pjmedia_sdp_session_clone(pool, neg->initial_sdp); - neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, neg->initial_sdp); + PJ_ASSERT_RETURN(neg->initial_sdp, PJMEDIA_SDPNEG_ENOINITIAL); + neg->initial_sdp_tmp = neg->initial_sdp; + neg->initial_sdp = pjmedia_sdp_session_clone(pool, neg->initial_sdp); + neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, neg->initial_sdp); } return PJ_SUCCESS; @@ -594,92 +593,92 @@ static void remove_all_media_directions(pjmedia_sdp_media *m) /* Update media direction based on peer's media direction */ static void update_media_direction(pj_pool_t *pool, - const pjmedia_sdp_media *remote, - pjmedia_sdp_media *local) + const pjmedia_sdp_media *remote, + pjmedia_sdp_media *local) { pjmedia_dir old_dir = PJMEDIA_DIR_ENCODING_DECODING, - new_dir; + new_dir; /* Get the media direction of local SDP */ if (pjmedia_sdp_media_find_attr2(local, "sendonly", NULL)) - old_dir = PJMEDIA_DIR_ENCODING; + old_dir = PJMEDIA_DIR_ENCODING; else if (pjmedia_sdp_media_find_attr2(local, "recvonly", NULL)) - old_dir = PJMEDIA_DIR_DECODING; + old_dir = PJMEDIA_DIR_DECODING; else if (pjmedia_sdp_media_find_attr2(local, "inactive", NULL)) - old_dir = PJMEDIA_DIR_NONE; + old_dir = PJMEDIA_DIR_NONE; new_dir = old_dir; /* Adjust local media direction based on remote media direction */ if (pjmedia_sdp_media_find_attr2(remote, "inactive", NULL) != NULL) { - /* If remote has "a=inactive", then local is inactive too */ + /* If remote has "a=inactive", then local is inactive too */ - new_dir = PJMEDIA_DIR_NONE; + new_dir = PJMEDIA_DIR_NONE; } else if(pjmedia_sdp_media_find_attr2(remote, "sendonly", NULL) != NULL) { - /* If remote has "a=sendonly", then set local to "recvonly" if - * it is currently "sendrecv". Otherwise if local is NOT "recvonly", - * then set local direction to "inactive". - */ - switch (old_dir) { - case PJMEDIA_DIR_ENCODING_DECODING: - new_dir = PJMEDIA_DIR_DECODING; - break; - case PJMEDIA_DIR_DECODING: - /* No change */ - break; - default: - new_dir = PJMEDIA_DIR_NONE; - break; - } + /* If remote has "a=sendonly", then set local to "recvonly" if + * it is currently "sendrecv". Otherwise if local is NOT "recvonly", + * then set local direction to "inactive". + */ + switch (old_dir) { + case PJMEDIA_DIR_ENCODING_DECODING: + new_dir = PJMEDIA_DIR_DECODING; + break; + case PJMEDIA_DIR_DECODING: + /* No change */ + break; + default: + new_dir = PJMEDIA_DIR_NONE; + break; + } } else if(pjmedia_sdp_media_find_attr2(remote, "recvonly", NULL) != NULL) { - /* If remote has "a=recvonly", then set local to "sendonly" if - * it is currently "sendrecv". Otherwise if local is NOT "sendonly", - * then set local direction to "inactive" - */ + /* If remote has "a=recvonly", then set local to "sendonly" if + * it is currently "sendrecv". Otherwise if local is NOT "sendonly", + * then set local direction to "inactive" + */ - switch (old_dir) { - case PJMEDIA_DIR_ENCODING_DECODING: - new_dir = PJMEDIA_DIR_ENCODING; - break; - case PJMEDIA_DIR_ENCODING: - /* No change */ - break; - default: - new_dir = PJMEDIA_DIR_NONE; - break; - } + switch (old_dir) { + case PJMEDIA_DIR_ENCODING_DECODING: + new_dir = PJMEDIA_DIR_ENCODING; + break; + case PJMEDIA_DIR_ENCODING: + /* No change */ + break; + default: + new_dir = PJMEDIA_DIR_NONE; + break; + } } else { - /* Remote indicates "sendrecv" capability. No change to local - * direction - */ + /* Remote indicates "sendrecv" capability. No change to local + * direction + */ } if (new_dir != old_dir) { - pjmedia_sdp_attr *a = NULL; - - remove_all_media_directions(local); - - switch (new_dir) { - case PJMEDIA_DIR_NONE: - a = pjmedia_sdp_attr_create(pool, "inactive", NULL); - break; - case PJMEDIA_DIR_ENCODING: - a = pjmedia_sdp_attr_create(pool, "sendonly", NULL); - break; - case PJMEDIA_DIR_DECODING: - a = pjmedia_sdp_attr_create(pool, "recvonly", NULL); - break; - default: - /* sendrecv */ - break; - } - - if (a) { - pjmedia_sdp_media_add_attr(local, a); - } + pjmedia_sdp_attr *a = NULL; + + remove_all_media_directions(local); + + switch (new_dir) { + case PJMEDIA_DIR_NONE: + a = pjmedia_sdp_attr_create(pool, "inactive", NULL); + break; + case PJMEDIA_DIR_ENCODING: + a = pjmedia_sdp_attr_create(pool, "sendonly", NULL); + break; + case PJMEDIA_DIR_DECODING: + a = pjmedia_sdp_attr_create(pool, "recvonly", NULL); + break; + default: + /* sendrecv */ + break; + } + + if (a) { + pjmedia_sdp_media_add_attr(local, a); + } } } @@ -688,29 +687,29 @@ static void update_media_direction(pj_pool_t *pool, * from remote. */ static pj_status_t process_m_answer( pj_pool_t *pool, - pjmedia_sdp_media *offer, - pjmedia_sdp_media *answer, - pj_bool_t allow_asym) + pjmedia_sdp_media *offer, + pjmedia_sdp_media *answer, + pj_bool_t allow_asym) { unsigned i; /* Check that the media type match our offer. */ if (pj_strcmp(&answer->desc.media, &offer->desc.media)!=0) { - /* The media type in the answer is different than the offer! */ - return PJMEDIA_SDPNEG_EINVANSMEDIA; + /* The media type in the answer is different than the offer! */ + return PJMEDIA_SDPNEG_EINVANSMEDIA; } /* Check if remote has rejected our offer */ if (answer->desc.port == 0) { - - /* Remote has rejected our offer. - * Deactivate our media too. - */ - pjmedia_sdp_media_deactivate(pool, offer); - - /* Don't need to proceed */ - return PJ_SUCCESS; + + /* Remote has rejected our offer. + * Deactivate our media too. + */ + pjmedia_sdp_media_deactivate(pool, offer); + + /* Don't need to proceed */ + return PJ_SUCCESS; } /* Check that transport in the answer match our offer. */ @@ -719,10 +718,10 @@ static pj_status_t process_m_answer( pj_pool_t *pool, * the transport instance will do more validation later. */ if (pjmedia_sdp_transport_cmp(&answer->desc.transport, - &offer->desc.transport) - != PJ_SUCCESS) + &offer->desc.transport) + != PJ_SUCCESS) { - return PJMEDIA_SDPNEG_EINVANSTP; + return PJMEDIA_SDPNEG_EINVANSTP; } @@ -730,8 +729,8 @@ static pj_status_t process_m_answer( pj_pool_t *pool, * offered with port zero. Let's just tolerate it. */ if (offer->desc.port == 0) { - /* Don't need to proceed */ - return PJ_SUCCESS; + /* Don't need to proceed */ + return PJ_SUCCESS; } /* Process direction attributes */ @@ -744,177 +743,177 @@ static pj_status_t process_m_answer( pj_pool_t *pool, * one codec in our initial offer to match the answer. */ if (allow_asym) { - for (i=0; idesc.fmt_count; ++i) { - unsigned j; - pj_str_t *rem_fmt = &answer->desc.fmt[i]; + for (i=0; idesc.fmt_count; ++i) { + unsigned j; + pj_str_t *rem_fmt = &answer->desc.fmt[i]; + + for (j=0; jdesc.fmt_count; ++j) { + if (pj_strcmp(rem_fmt, &answer->desc.fmt[j])==0) + break; + } + + if (j != offer->desc.fmt_count) { + /* Found at least one common codec. */ + break; + } + } - for (j=0; jdesc.fmt_count; ++j) { - if (pj_strcmp(rem_fmt, &answer->desc.fmt[j])==0) - break; - } + if (i == answer->desc.fmt_count) { + /* No common codec in the answer! */ + return PJMEDIA_SDPNEG_EANSNOMEDIA; + } - if (j != offer->desc.fmt_count) { - /* Found at least one common codec. */ - break; - } - } + PJ_TODO(CHECK_SDP_NEGOTIATION_WHEN_ASYMETRIC_MEDIA_IS_ALLOWED); - if (i == answer->desc.fmt_count) { - /* No common codec in the answer! */ - return PJMEDIA_SDPNEG_EANSNOMEDIA; - } + } else { + /* Offer format priority based on answer format index/priority */ + unsigned offer_fmt_prior[PJMEDIA_MAX_SDP_FMT]; + + /* Remove all format in the offer that has no matching answer */ + for (i=0; idesc.fmt_count;) { + unsigned pt; + pj_uint32_t j; + pj_str_t *fmt = &offer->desc.fmt[i]; + + + /* Find matching answer */ + pt = pj_strtoul(fmt); + + if (pt < 96) { + for (j=0; jdesc.fmt_count; ++j) { + if (pj_strcmp(fmt, &answer->desc.fmt[j])==0) + break; + } + } else { + /* This is dynamic payload type. + * For dynamic payload type, we must look the rtpmap and + * compare the encoding name. + */ + const pjmedia_sdp_attr *a; + pjmedia_sdp_rtpmap or_; + + /* Get the rtpmap for the payload type in the offer. */ + a = pjmedia_sdp_media_find_attr2(offer, "rtpmap", fmt); + if (!a) { + pj_assert(!"Bug! Offer should have been validated"); + return PJ_EBUG; + } + pjmedia_sdp_attr_get_rtpmap(a, &or_); + + /* Find paylaod in answer SDP with matching + * encoding name and clock rate. + */ + for (j=0; jdesc.fmt_count; ++j) { + a = pjmedia_sdp_media_find_attr2(answer, "rtpmap", + &answer->desc.fmt[j]); + if (a) { + pjmedia_sdp_rtpmap ar; + pjmedia_sdp_attr_get_rtpmap(a, &ar); + + /* See if encoding name, clock rate, and channel + * count match + */ + if (!pj_stricmp(&or_.enc_name, &ar.enc_name) && + or_.clock_rate == ar.clock_rate && + (pj_stricmp(&or_.param, &ar.param)==0 || + (ar.param.slen==1 && *ar.param.ptr=='1'))) + { + /* Call custom format matching callbacks */ + if (custom_fmt_match(pool, &or_.enc_name, + offer, i, answer, j, 0) == + PJ_SUCCESS) + { + /* Match! */ + break; + } + } + } + } + } + + if (j == answer->desc.fmt_count) { + /* This format has no matching answer. + * Remove it from our offer. + */ + pjmedia_sdp_attr *a; + + /* Remove rtpmap associated with this format */ + a = pjmedia_sdp_media_find_attr2(offer, "rtpmap", fmt); + if (a) + pjmedia_sdp_media_remove_attr(offer, a); + + /* Remove fmtp associated with this format */ + a = pjmedia_sdp_media_find_attr2(offer, "fmtp", fmt); + if (a) + pjmedia_sdp_media_remove_attr(offer, a); + + /* Remove this format from offer's array */ + pj_array_erase(offer->desc.fmt, sizeof(offer->desc.fmt[0]), + offer->desc.fmt_count, i); + --offer->desc.fmt_count; + + } else { + offer_fmt_prior[i] = j; + ++i; + } + } - PJ_TODO(CHECK_SDP_NEGOTIATION_WHEN_ASYMETRIC_MEDIA_IS_ALLOWED); + if (0 == offer->desc.fmt_count) { + /* No common codec in the answer! */ + return PJMEDIA_SDPNEG_EANSNOMEDIA; + } - } else { - /* Offer format priority based on answer format index/priority */ - unsigned offer_fmt_prior[PJMEDIA_MAX_SDP_FMT]; - - /* Remove all format in the offer that has no matching answer */ - for (i=0; idesc.fmt_count;) { - unsigned pt; - pj_uint32_t j; - pj_str_t *fmt = &offer->desc.fmt[i]; - - - /* Find matching answer */ - pt = pj_strtoul(fmt); - - if (pt < 96) { - for (j=0; jdesc.fmt_count; ++j) { - if (pj_strcmp(fmt, &answer->desc.fmt[j])==0) - break; - } - } else { - /* This is dynamic payload type. - * For dynamic payload type, we must look the rtpmap and - * compare the encoding name. - */ - const pjmedia_sdp_attr *a; - pjmedia_sdp_rtpmap or_; - - /* Get the rtpmap for the payload type in the offer. */ - a = pjmedia_sdp_media_find_attr2(offer, "rtpmap", fmt); - if (!a) { - pj_assert(!"Bug! Offer should have been validated"); - return PJ_EBUG; - } - pjmedia_sdp_attr_get_rtpmap(a, &or_); - - /* Find paylaod in answer SDP with matching - * encoding name and clock rate. - */ - for (j=0; jdesc.fmt_count; ++j) { - a = pjmedia_sdp_media_find_attr2(answer, "rtpmap", - &answer->desc.fmt[j]); - if (a) { - pjmedia_sdp_rtpmap ar; - pjmedia_sdp_attr_get_rtpmap(a, &ar); - - /* See if encoding name, clock rate, and channel - * count match - */ - if (!pj_stricmp(&or_.enc_name, &ar.enc_name) && - or_.clock_rate == ar.clock_rate && - (pj_stricmp(&or_.param, &ar.param)==0 || - (ar.param.slen==1 && *ar.param.ptr=='1'))) - { - /* Call custom format matching callbacks */ - if (custom_fmt_match(pool, &or_.enc_name, - offer, i, answer, j, 0) == - PJ_SUCCESS) - { - /* Match! */ - break; - } - } - } - } - } - - if (j == answer->desc.fmt_count) { - /* This format has no matching answer. - * Remove it from our offer. - */ - pjmedia_sdp_attr *a; - - /* Remove rtpmap associated with this format */ - a = pjmedia_sdp_media_find_attr2(offer, "rtpmap", fmt); - if (a) - pjmedia_sdp_media_remove_attr(offer, a); - - /* Remove fmtp associated with this format */ - a = pjmedia_sdp_media_find_attr2(offer, "fmtp", fmt); - if (a) - pjmedia_sdp_media_remove_attr(offer, a); - - /* Remove this format from offer's array */ - pj_array_erase(offer->desc.fmt, sizeof(offer->desc.fmt[0]), - offer->desc.fmt_count, i); - --offer->desc.fmt_count; - - } else { - offer_fmt_prior[i] = j; - ++i; - } - } - - if (0 == offer->desc.fmt_count) { - /* No common codec in the answer! */ - return PJMEDIA_SDPNEG_EANSNOMEDIA; - } - - /* Post process: - * - Resort offer formats so the order match to the answer. - * - Remove answer formats that unmatches to the offer. - */ - - /* Resort offer formats */ - for (i=0; idesc.fmt_count; ++i) { - unsigned j; - for (j=i+1; jdesc.fmt_count; ++j) { - if (offer_fmt_prior[i] > offer_fmt_prior[j]) { - unsigned tmp = offer_fmt_prior[i]; - offer_fmt_prior[i] = offer_fmt_prior[j]; - offer_fmt_prior[j] = tmp; - str_swap(&offer->desc.fmt[i], &offer->desc.fmt[j]); - } - } - } - - /* Remove unmatched answer formats */ - { - unsigned del_cnt = 0; - for (i=0; idesc.fmt_count;) { - /* The offer is ordered now, also the offer_fmt_prior */ - if (i >= offer->desc.fmt_count || - offer_fmt_prior[i]-del_cnt != i) - { - pj_str_t *fmt = &answer->desc.fmt[i]; - pjmedia_sdp_attr *a; - - /* Remove rtpmap associated with this format */ - a = pjmedia_sdp_media_find_attr2(answer, "rtpmap", fmt); - if (a) - pjmedia_sdp_media_remove_attr(answer, a); - - /* Remove fmtp associated with this format */ - a = pjmedia_sdp_media_find_attr2(answer, "fmtp", fmt); - if (a) - pjmedia_sdp_media_remove_attr(answer, a); - - /* Remove this format from answer's array */ - pj_array_erase(answer->desc.fmt, - sizeof(answer->desc.fmt[0]), - answer->desc.fmt_count, i); - --answer->desc.fmt_count; - - ++del_cnt; - } else { - ++i; - } - } - } + /* Post process: + * - Resort offer formats so the order match to the answer. + * - Remove answer formats that unmatches to the offer. + */ + + /* Resort offer formats */ + for (i=0; idesc.fmt_count; ++i) { + unsigned j; + for (j=i+1; jdesc.fmt_count; ++j) { + if (offer_fmt_prior[i] > offer_fmt_prior[j]) { + unsigned tmp = offer_fmt_prior[i]; + offer_fmt_prior[i] = offer_fmt_prior[j]; + offer_fmt_prior[j] = tmp; + str_swap(&offer->desc.fmt[i], &offer->desc.fmt[j]); + } + } + } + + /* Remove unmatched answer formats */ + { + unsigned del_cnt = 0; + for (i=0; idesc.fmt_count;) { + /* The offer is ordered now, also the offer_fmt_prior */ + if (i >= offer->desc.fmt_count || + offer_fmt_prior[i]-del_cnt != i) + { + pj_str_t *fmt = &answer->desc.fmt[i]; + pjmedia_sdp_attr *a; + + /* Remove rtpmap associated with this format */ + a = pjmedia_sdp_media_find_attr2(answer, "rtpmap", fmt); + if (a) + pjmedia_sdp_media_remove_attr(answer, a); + + /* Remove fmtp associated with this format */ + a = pjmedia_sdp_media_find_attr2(answer, "fmtp", fmt); + if (a) + pjmedia_sdp_media_remove_attr(answer, a); + + /* Remove this format from answer's array */ + pj_array_erase(answer->desc.fmt, + sizeof(answer->desc.fmt[0]), + answer->desc.fmt_count, i); + --answer->desc.fmt_count; + + ++del_cnt; + } else { + ++i; + } + } + } } /* Looks okay */ @@ -926,10 +925,10 @@ static pj_status_t process_m_answer( pj_pool_t *pool, * after receiving remote answer. */ static pj_status_t process_answer(pj_pool_t *pool, - pjmedia_sdp_session *local_offer, - pjmedia_sdp_session *answer, - pj_bool_t allow_asym, - pjmedia_sdp_session **p_active) + pjmedia_sdp_session *local_offer, + pjmedia_sdp_session *answer, + pj_bool_t allow_asym, + pjmedia_sdp_session **p_active) { unsigned omi = 0; /* Offer media index */ unsigned ami = 0; /* Answer media index */ @@ -947,49 +946,49 @@ static pj_status_t process_answer(pj_pool_t *pool, // Ticket #527, different media count is allowed for more interoperability, // however, the media order must be same between offer and answer. // if (offer->media_count != answer->media_count) - // return PJMEDIA_SDPNEG_EMISMEDIA; + // return PJMEDIA_SDPNEG_EMISMEDIA; /* Now update each media line in the offer with the answer. */ for (; omimedia_count; ++omi) { - if (ami == answer->media_count) { - /* The answer has less media than the offer */ - pjmedia_sdp_media *am; - - /* Generate matching-but-disabled-media for the answer */ - am = sdp_media_clone_deactivate(pool, offer->media[omi], - offer->media[omi], offer); - answer->media[answer->media_count++] = am; - ++ami; - - /* Deactivate our media offer too */ - pjmedia_sdp_media_deactivate(pool, offer->media[omi]); - - /* No answer media to be negotiated */ - continue; - } - - status = process_m_answer(pool, offer->media[omi], answer->media[ami], - allow_asym); - - /* If media type is mismatched, just disable the media. */ - if (status == PJMEDIA_SDPNEG_EINVANSMEDIA) { - pjmedia_sdp_media_deactivate(pool, offer->media[omi]); - continue; - } - /* No common format in the answer media. */ - else if (status == PJMEDIA_SDPNEG_EANSNOMEDIA) { - pjmedia_sdp_media_deactivate(pool, offer->media[omi]); - pjmedia_sdp_media_deactivate(pool, answer->media[ami]); - } - /* Return the error code, for other errors. */ - else if (status != PJ_SUCCESS) { - return status; - } - - if (offer->media[omi]->desc.port != 0) - has_active = PJ_TRUE; - - ++ami; + if (ami == answer->media_count) { + /* The answer has less media than the offer */ + pjmedia_sdp_media *am; + + /* Generate matching-but-disabled-media for the answer */ + am = sdp_media_clone_deactivate(pool, offer->media[omi], + offer->media[omi], offer); + answer->media[answer->media_count++] = am; + ++ami; + + /* Deactivate our media offer too */ + pjmedia_sdp_media_deactivate(pool, offer->media[omi]); + + /* No answer media to be negotiated */ + continue; + } + + status = process_m_answer(pool, offer->media[omi], answer->media[ami], + allow_asym); + + /* If media type is mismatched, just disable the media. */ + if (status == PJMEDIA_SDPNEG_EINVANSMEDIA) { + pjmedia_sdp_media_deactivate(pool, offer->media[omi]); + continue; + } + /* No common format in the answer media. */ + else if (status == PJMEDIA_SDPNEG_EANSNOMEDIA) { + pjmedia_sdp_media_deactivate(pool, offer->media[omi]); + pjmedia_sdp_media_deactivate(pool, answer->media[ami]); + } + /* Return the error code, for other errors. */ + else if (status != PJ_SUCCESS) { + return status; + } + + if (offer->media[omi]->desc.port != 0) + has_active = PJ_TRUE; + + ++ami; } *p_active = offer; @@ -1002,21 +1001,21 @@ static pj_status_t process_answer(pj_pool_t *pool, * and fmtp. */ PJ_INLINE(void) rewrite_pt(pj_pool_t *pool, pj_str_t *attr_val, - const pj_str_t *old_pt, const pj_str_t *new_pt) + const pj_str_t *old_pt, const pj_str_t *new_pt) { int len_diff = (int)(new_pt->slen - old_pt->slen); /* Note that attribute value should be null-terminated. */ if (len_diff > 0) { - pj_str_t new_val; - new_val.ptr = (char*)pj_pool_alloc(pool, attr_val->slen+len_diff+1); - new_val.slen = attr_val->slen + len_diff; - pj_memcpy(new_val.ptr + len_diff, attr_val->ptr, attr_val->slen + 1); - *attr_val = new_val; + pj_str_t new_val; + new_val.ptr = (char*)pj_pool_alloc(pool, attr_val->slen+len_diff+1); + new_val.slen = attr_val->slen + len_diff; + pj_memcpy(new_val.ptr + len_diff, attr_val->ptr, attr_val->slen + 1); + *attr_val = new_val; } else if (len_diff < 0) { - attr_val->slen += len_diff; - pj_memmove(attr_val->ptr, attr_val->ptr - len_diff, - attr_val->slen + 1); + attr_val->slen += len_diff; + pj_memmove(attr_val->ptr, attr_val->ptr - len_diff, + attr_val->slen + 1); } pj_memcpy(attr_val->ptr, new_pt->ptr, new_pt->slen); } @@ -1024,10 +1023,10 @@ PJ_INLINE(void) rewrite_pt(pj_pool_t *pool, pj_str_t *attr_val, /* Internal function to apply symmetric PT for the local answer. */ static void apply_answer_symmetric_pt(pj_pool_t *pool, - pjmedia_sdp_media *answer, - unsigned pt_cnt, - const pj_str_t pt_offer[], - const pj_str_t pt_answer[]) + pjmedia_sdp_media *answer, + unsigned pt_cnt, + const pj_str_t pt_offer[], + const pj_str_t pt_answer[]) { pjmedia_sdp_attr *a_tmp[PJMEDIA_MAX_SDP_ATTR]; unsigned i, a_tmp_cnt = 0; @@ -1036,59 +1035,59 @@ static void apply_answer_symmetric_pt(pj_pool_t *pool, * the ones in the offer. */ for (i = 0; i < pt_cnt; ++i) { - pjmedia_sdp_attr *a; - - /* Skip if the PTs are the same already, e.g: static PT. */ - if (pj_strcmp(&pt_answer[i], &pt_offer[i]) == 0) - continue; - - /* Rewrite payload type in the answer to match to the offer */ - pj_strdup(pool, &answer->desc.fmt[i], &pt_offer[i]); - - /* Also update payload type in rtpmap */ - a = pjmedia_sdp_media_find_attr2(answer, "rtpmap", &pt_answer[i]); - if (a) { - rewrite_pt(pool, &a->value, &pt_answer[i], &pt_offer[i]); - /* Temporarily remove the attribute in case the new payload - * type is being used by another format in the media. - */ - pjmedia_sdp_media_remove_attr(answer, a); - a_tmp[a_tmp_cnt++] = a; - } - - /* Also update payload type in fmtp */ - a = pjmedia_sdp_media_find_attr2(answer, "fmtp", &pt_answer[i]); - if (a) { - rewrite_pt(pool, &a->value, &pt_answer[i], &pt_offer[i]); - /* Temporarily remove the attribute in case the new payload - * type is being used by another format in the media. - */ - pjmedia_sdp_media_remove_attr(answer, a); - a_tmp[a_tmp_cnt++] = a; - } + pjmedia_sdp_attr *a; + + /* Skip if the PTs are the same already, e.g: static PT. */ + if (pj_strcmp(&pt_answer[i], &pt_offer[i]) == 0) + continue; + + /* Rewrite payload type in the answer to match to the offer */ + pj_strdup(pool, &answer->desc.fmt[i], &pt_offer[i]); + + /* Also update payload type in rtpmap */ + a = pjmedia_sdp_media_find_attr2(answer, "rtpmap", &pt_answer[i]); + if (a) { + rewrite_pt(pool, &a->value, &pt_answer[i], &pt_offer[i]); + /* Temporarily remove the attribute in case the new payload + * type is being used by another format in the media. + */ + pjmedia_sdp_media_remove_attr(answer, a); + a_tmp[a_tmp_cnt++] = a; + } + + /* Also update payload type in fmtp */ + a = pjmedia_sdp_media_find_attr2(answer, "fmtp", &pt_answer[i]); + if (a) { + rewrite_pt(pool, &a->value, &pt_answer[i], &pt_offer[i]); + /* Temporarily remove the attribute in case the new payload + * type is being used by another format in the media. + */ + pjmedia_sdp_media_remove_attr(answer, a); + a_tmp[a_tmp_cnt++] = a; + } } /* Return back 'rtpmap' and 'fmtp' attributes */ for (i = 0; i < a_tmp_cnt; ++i) - pjmedia_sdp_media_add_attr(answer, a_tmp[i]); + pjmedia_sdp_media_add_attr(answer, a_tmp[i]); } /* Try to match offer with answer. */ static pj_status_t match_offer(pj_pool_t *pool, - pj_bool_t prefer_remote_codec_order, + pj_bool_t prefer_remote_codec_order, pj_bool_t answer_with_multiple_codecs, - const pjmedia_sdp_media *offer, - const pjmedia_sdp_media *preanswer, - const pjmedia_sdp_session *preanswer_sdp, - pjmedia_sdp_media **p_answer) + const pjmedia_sdp_media *offer, + const pjmedia_sdp_media *preanswer, + const pjmedia_sdp_session *preanswer_sdp, + pjmedia_sdp_media **p_answer) { unsigned i; pj_bool_t master_has_codec = 0, - master_has_other = 0, - found_matching_codec = 0, - found_matching_telephone_event = 0, - found_matching_other = 0; + master_has_other = 0, + found_matching_codec = 0, + found_matching_telephone_event = 0, + found_matching_other = 0; unsigned pt_answer_count = 0; pj_str_t pt_answer[PJMEDIA_MAX_SDP_FMT]; pj_str_t pt_offer[PJMEDIA_MAX_SDP_FMT]; @@ -1099,291 +1098,291 @@ static pj_status_t match_offer(pj_pool_t *pool, /* If offer has zero port, just clone the offer */ if (offer->desc.port == 0) { - answer = sdp_media_clone_deactivate(pool, offer, preanswer, - preanswer_sdp); - *p_answer = answer; - return PJ_SUCCESS; + answer = sdp_media_clone_deactivate(pool, offer, preanswer, + preanswer_sdp); + *p_answer = answer; + return PJ_SUCCESS; } /* If the preanswer define zero port, this media is being rejected, * just clone the preanswer. */ if (preanswer->desc.port == 0) { - answer = pjmedia_sdp_media_clone(pool, preanswer); - *p_answer = answer; - return PJ_SUCCESS; + answer = pjmedia_sdp_media_clone(pool, preanswer); + *p_answer = answer; + return PJ_SUCCESS; } /* Set master/slave negotiator based on prefer_remote_codec_order. */ if (prefer_remote_codec_order) { - master = offer; - slave = preanswer; + master = offer; + slave = preanswer; } else { - master = preanswer; - slave = offer; + master = preanswer; + slave = offer; } /* With the addition of telephone-event and dodgy MS RTC SDP, * the answer generation algorithm looks really shitty... */ for (i=0; idesc.fmt_count; ++i) { - unsigned j; - - if (pj_isdigit(*master->desc.fmt[i].ptr)) { - /* This is normal/standard payload type, where it's identified - * by payload number. - */ - unsigned pt; - - pt = pj_strtoul(&master->desc.fmt[i]); - - if (pt < 96) { - /* For static payload type, it's enough to compare just - * the payload number. - */ - - master_has_codec = 1; - - /* We just need to select one codec if not allowing multiple. - * Continue if we have selected matching codec for previous - * payload. - */ - if (!answer_with_multiple_codecs && found_matching_codec) - continue; - - /* Find matching codec in local descriptor. */ - for (j=0; jdesc.fmt_count; ++j) { - unsigned p; - p = pj_strtoul(&slave->desc.fmt[j]); - if (p == pt && pj_isdigit(*slave->desc.fmt[j].ptr)) { - unsigned k; - - found_matching_codec = 1; - pt_offer[pt_answer_count] = slave->desc.fmt[j]; - pt_answer[pt_answer_count++] = slave->desc.fmt[j]; - - /* Take note of clock rate for tel-event. Note: for - * static PT, we assume the clock rate is 8000. - */ - for (k=0; kdesc.fmt[i]); - if (!a) { - pj_assert(!"Bug! Offer should have been validated"); - return PJMEDIA_SDP_EMISSINGRTPMAP; - } - pjmedia_sdp_attr_get_rtpmap(a, &or_); - - if (pj_stricmp2(&or_.enc_name, "telephone-event")) { - master_has_codec = 1; - if (!answer_with_multiple_codecs && found_matching_codec) - continue; - is_codec = 1; - } - - /* Find paylaod in our initial SDP with matching - * encoding name and clock rate. - */ - for (j=0; jdesc.fmt_count; ++j) { - a = pjmedia_sdp_media_find_attr2(slave, "rtpmap", - &slave->desc.fmt[j]); - if (a) { - pjmedia_sdp_rtpmap lr; - pjmedia_sdp_attr_get_rtpmap(a, &lr); - - /* See if encoding name, clock rate, and - * channel count match - */ - if (!pj_stricmp(&or_.enc_name, &lr.enc_name) && - or_.clock_rate == lr.clock_rate && - (pj_stricmp(&or_.param, &lr.param)==0 || - (lr.param.slen==0 && or_.param.slen==1 && - *or_.param.ptr=='1') || - (or_.param.slen==0 && lr.param.slen==1 && - *lr.param.ptr=='1'))) - { - /* Match! */ - if (is_codec) { - pjmedia_sdp_media *o_med, *a_med; - unsigned o_fmt_idx, a_fmt_idx; - unsigned k; - - o_med = (pjmedia_sdp_media*)offer; - a_med = (pjmedia_sdp_media*)preanswer; - o_fmt_idx = prefer_remote_codec_order? i:j; - a_fmt_idx = prefer_remote_codec_order? j:i; - - /* Call custom format matching callbacks */ - if (custom_fmt_match(pool, &or_.enc_name, - o_med, o_fmt_idx, - a_med, a_fmt_idx, - ALLOW_MODIFY_ANSWER) != - PJ_SUCCESS) - { - continue; - } - found_matching_codec = 1; - - /* Take note of clock rate for tel-event */ - for (k=0; kdesc.fmt[i]: - offer->desc.fmt[j]; - pt_answer[pt_answer_count++] = - prefer_remote_codec_order? - preanswer->desc.fmt[j]: - preanswer->desc.fmt[i]; - break; - } - } - } - } - - } else { - /* This is a non-standard, brain damaged SDP where the payload - * type is non-numeric. It exists e.g. in Microsoft RTC based - * UA, to indicate instant messaging capability. - * Example: - * - m=x-ms-message 5060 sip null - */ - master_has_other = 1; - if (found_matching_other) - continue; - - for (j=0; jdesc.fmt_count; ++j) { - if (!pj_strcmp(&master->desc.fmt[i], &slave->desc.fmt[j])) { - /* Match */ - found_matching_other = 1; - pt_offer[pt_answer_count] = prefer_remote_codec_order? - offer->desc.fmt[i]: - offer->desc.fmt[j]; - pt_answer[pt_answer_count++] = prefer_remote_codec_order? - preanswer->desc.fmt[j]: - preanswer->desc.fmt[i]; - break; - } - } - } + unsigned j; + + if (pj_isdigit(*master->desc.fmt[i].ptr)) { + /* This is normal/standard payload type, where it's identified + * by payload number. + */ + unsigned pt; + + pt = pj_strtoul(&master->desc.fmt[i]); + + if (pt < 96) { + /* For static payload type, it's enough to compare just + * the payload number. + */ + + master_has_codec = 1; + + /* We just need to select one codec if not allowing multiple. + * Continue if we have selected matching codec for previous + * payload. + */ + if (!answer_with_multiple_codecs && found_matching_codec) + continue; + + /* Find matching codec in local descriptor. */ + for (j=0; jdesc.fmt_count; ++j) { + unsigned p; + p = pj_strtoul(&slave->desc.fmt[j]); + if (p == pt && pj_isdigit(*slave->desc.fmt[j].ptr)) { + unsigned k; + + found_matching_codec = 1; + pt_offer[pt_answer_count] = slave->desc.fmt[j]; + pt_answer[pt_answer_count++] = slave->desc.fmt[j]; + + /* Take note of clock rate for tel-event. Note: for + * static PT, we assume the clock rate is 8000. + */ + for (k=0; kdesc.fmt[i]); + if (!a) { + pj_assert(!"Bug! Offer should have been validated"); + return PJMEDIA_SDP_EMISSINGRTPMAP; + } + pjmedia_sdp_attr_get_rtpmap(a, &or_); + + if (pj_stricmp2(&or_.enc_name, "telephone-event")) { + master_has_codec = 1; + if (!answer_with_multiple_codecs && found_matching_codec) + continue; + is_codec = 1; + } + + /* Find paylaod in our initial SDP with matching + * encoding name and clock rate. + */ + for (j=0; jdesc.fmt_count; ++j) { + a = pjmedia_sdp_media_find_attr2(slave, "rtpmap", + &slave->desc.fmt[j]); + if (a) { + pjmedia_sdp_rtpmap lr; + pjmedia_sdp_attr_get_rtpmap(a, &lr); + + /* See if encoding name, clock rate, and + * channel count match + */ + if (!pj_stricmp(&or_.enc_name, &lr.enc_name) && + or_.clock_rate == lr.clock_rate && + (pj_stricmp(&or_.param, &lr.param)==0 || + (lr.param.slen==0 && or_.param.slen==1 && + *or_.param.ptr=='1') || + (or_.param.slen==0 && lr.param.slen==1 && + *lr.param.ptr=='1'))) + { + /* Match! */ + if (is_codec) { + pjmedia_sdp_media *o_med, *a_med; + unsigned o_fmt_idx, a_fmt_idx; + unsigned k; + + o_med = (pjmedia_sdp_media*)offer; + a_med = (pjmedia_sdp_media*)preanswer; + o_fmt_idx = prefer_remote_codec_order? i:j; + a_fmt_idx = prefer_remote_codec_order? j:i; + + /* Call custom format matching callbacks */ + if (custom_fmt_match(pool, &or_.enc_name, + o_med, o_fmt_idx, + a_med, a_fmt_idx, + ALLOW_MODIFY_ANSWER) != + PJ_SUCCESS) + { + continue; + } + found_matching_codec = 1; + + /* Take note of clock rate for tel-event */ + for (k=0; kdesc.fmt[i]: + offer->desc.fmt[j]; + pt_answer[pt_answer_count++] = + prefer_remote_codec_order? + preanswer->desc.fmt[j]: + preanswer->desc.fmt[i]; + break; + } + } + } + } + + } else { + /* This is a non-standard, brain damaged SDP where the payload + * type is non-numeric. It exists e.g. in Microsoft RTC based + * UA, to indicate instant messaging capability. + * Example: + * - m=x-ms-message 5060 sip null + */ + master_has_other = 1; + if (found_matching_other) + continue; + + for (j=0; jdesc.fmt_count; ++j) { + if (!pj_strcmp(&master->desc.fmt[i], &slave->desc.fmt[j])) { + /* Match */ + found_matching_other = 1; + pt_offer[pt_answer_count] = prefer_remote_codec_order? + offer->desc.fmt[i]: + offer->desc.fmt[j]; + pt_answer[pt_answer_count++] = prefer_remote_codec_order? + preanswer->desc.fmt[j]: + preanswer->desc.fmt[i]; + break; + } + } + } } /* See if all types of master can be matched. */ if (master_has_codec && !found_matching_codec) { - return PJMEDIA_SDPNEG_NOANSCODEC; + return PJMEDIA_SDPNEG_NOANSCODEC; } /* If this comment is removed, negotiation will fail if remote has offered telephone-event and local is not configured with telephone-event if (offer_has_telephone_event && !found_matching_telephone_event) { - return PJMEDIA_SDPNEG_NOANSTELEVENT; + return PJMEDIA_SDPNEG_NOANSTELEVENT; } */ if (master_has_other && !found_matching_other) { - return PJMEDIA_SDPNEG_NOANSUNKNOWN; + return PJMEDIA_SDPNEG_NOANSUNKNOWN; } /* Seems like everything is in order. */ /* Remove unwanted telephone-event formats. */ if (found_matching_telephone_event) { - pj_str_t first_televent_offer = {0}; - pj_str_t first_televent_answer = {0}; - unsigned matched_cnt = 0; - - for (i=0; idesc.fmt_count; ++j) { - if (!pj_strcmp(&answer->desc.fmt[j], &pt_answer[i])) - break; - } - pj_assert(j != answer->desc.fmt_count); - str_swap(&answer->desc.fmt[i], &answer->desc.fmt[j]); + unsigned j; + for (j=i; jdesc.fmt_count; ++j) { + if (!pj_strcmp(&answer->desc.fmt[j], &pt_answer[i])) + break; + } + pj_assert(j != answer->desc.fmt_count); + str_swap(&answer->desc.fmt[i], &answer->desc.fmt[j]); } /* Remove unwanted local formats. */ for (i=pt_answer_count; idesc.fmt_count; ++i) { - pjmedia_sdp_attr *a; - - /* Remove rtpmap for this format */ - a = pjmedia_sdp_media_find_attr2(answer, "rtpmap", - &answer->desc.fmt[i]); - if (a) { - pjmedia_sdp_media_remove_attr(answer, a); - } - - /* Remove fmtp for this format */ - a = pjmedia_sdp_media_find_attr2(answer, "fmtp", - &answer->desc.fmt[i]); - if (a) { - pjmedia_sdp_media_remove_attr(answer, a); - } + pjmedia_sdp_attr *a; + + /* Remove rtpmap for this format */ + a = pjmedia_sdp_media_find_attr2(answer, "rtpmap", + &answer->desc.fmt[i]); + if (a) { + pjmedia_sdp_media_remove_attr(answer, a); + } + + /* Remove fmtp for this format */ + a = pjmedia_sdp_media_find_attr2(answer, "fmtp", + &answer->desc.fmt[i]); + if (a) { + pjmedia_sdp_media_remove_attr(answer, a); + } } answer->desc.fmt_count = pt_answer_count; #if PJMEDIA_SDP_NEG_ANSWER_SYMMETRIC_PT apply_answer_symmetric_pt(pool, answer, pt_answer_count, - pt_offer, pt_answer); + pt_offer, pt_answer); #endif /* Update media direction. */ @@ -1434,11 +1433,11 @@ static pj_status_t match_offer(pj_pool_t *pool, /* Create complete answer for remote's offer. */ static pj_status_t create_answer( pj_pool_t *pool, - pj_bool_t prefer_remote_codec_order, + pj_bool_t prefer_remote_codec_order, pj_bool_t answer_with_multiple_codecs, - const pjmedia_sdp_session *initial, - const pjmedia_sdp_session *offer, - pjmedia_sdp_session **p_answer) + const pjmedia_sdp_session *initial, + const pjmedia_sdp_session *offer, + pjmedia_sdp_session **p_answer) { pj_status_t status = PJMEDIA_SDPNEG_ENOMEDIA; pj_bool_t has_active = PJ_FALSE; @@ -1465,60 +1464,60 @@ static pj_status_t create_answer( pj_pool_t *pool, * capability. */ for (i=0; imedia_count; ++i) { - const pjmedia_sdp_media *om; /* offer */ - const pjmedia_sdp_media *im; /* initial media */ - pjmedia_sdp_media *am = NULL; /* answer/result */ - unsigned j; - - om = offer->media[i]; - - /* Find media description in our initial capability that matches - * the media type and transport type of offer's media, has - * matching codec, and has not been used to answer other offer. - */ - for (im=NULL, j=0; jmedia_count; ++j) { - im = initial->media[j]; - if (pj_strcmp(&om->desc.media, &im->desc.media)==0 && - pj_strcmp(&om->desc.transport, &im->desc.transport)==0 && - media_used[j] == 0) - { + const pjmedia_sdp_media *om; /* offer */ + const pjmedia_sdp_media *im; /* initial media */ + pjmedia_sdp_media *am = NULL; /* answer/result */ + unsigned j; + + om = offer->media[i]; + + /* Find media description in our initial capability that matches + * the media type and transport type of offer's media, has + * matching codec, and has not been used to answer other offer. + */ + for (im=NULL, j=0; jmedia_count; ++j) { + im = initial->media[j]; + if (pj_strcmp(&om->desc.media, &im->desc.media)==0 && + pj_strcmp(&om->desc.transport, &im->desc.transport)==0 && + media_used[j] == 0) + { pj_status_t status2; - /* See if it has matching codec. */ - status2 = match_offer(pool, prefer_remote_codec_order, + /* See if it has matching codec. */ + status2 = match_offer(pool, prefer_remote_codec_order, answer_with_multiple_codecs, - om, im, initial, &am); - if (status2 == PJ_SUCCESS) { - /* Mark media as used. */ - media_used[j] = 1; - break; + om, im, initial, &am); + if (status2 == PJ_SUCCESS) { + /* Mark media as used. */ + media_used[j] = 1; + break; } else { status = status2; } - } - } - - if (j==initial->media_count) { - /* No matching media. - * Reject the offer by setting the port to zero in the answer. - */ - /* For simplicity in the construction of the answer, we'll - * just clone the media from the offer. Anyway receiver will - * ignore anything in the media once it sees that the port - * number is zero. - */ - am = sdp_media_clone_deactivate(pool, om, om, answer); - } else { - /* The answer is in am */ - pj_assert(am != NULL); - } - - /* Add the media answer */ - answer->media[answer->media_count++] = am; - - /* Check if this media is active.*/ - if (am->desc.port != 0) - has_active = PJ_TRUE; + } + } + + if (j==initial->media_count) { + /* No matching media. + * Reject the offer by setting the port to zero in the answer. + */ + /* For simplicity in the construction of the answer, we'll + * just clone the media from the offer. Anyway receiver will + * ignore anything in the media once it sees that the port + * number is zero. + */ + am = sdp_media_clone_deactivate(pool, om, om, answer); + } else { + /* The answer is in am */ + pj_assert(am != NULL); + } + + /* Add the media answer */ + answer->media[answer->media_count++] = am; + + /* Check if this media is active.*/ + if (am->desc.port != 0) + has_active = PJ_TRUE; } *p_answer = answer; @@ -1533,22 +1532,22 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_cancel_offer(pjmedia_sdp_neg *neg) /* Must be in LOCAL_OFFER state. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER || - neg->state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER, - PJMEDIA_SDPNEG_EINSTATE); + neg->state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER, + PJMEDIA_SDPNEG_EINSTATE); if (neg->state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER && - neg->active_local_sdp) + neg->active_local_sdp) { - /* Increment next version number. This happens if for example - * the reinvite offer is rejected by 488. If we don't increment - * the version here, the next offer will have the same version. - */ - neg->active_local_sdp->origin.version++; + /* Increment next version number. This happens if for example + * the reinvite offer is rejected by 488. If we don't increment + * the version here, the next offer will have the same version. + */ + neg->active_local_sdp->origin.version++; } /* Revert back initial SDP */ if (neg->state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) - neg->initial_sdp = neg->initial_sdp_tmp; + neg->initial_sdp = neg->initial_sdp_tmp; /* Clear temporary SDP */ neg->initial_sdp_tmp = NULL; @@ -1564,8 +1563,8 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_cancel_offer(pjmedia_sdp_neg *neg) /* The best bit: SDP negotiation function! */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_negotiate( pj_pool_t *pool, - pjmedia_sdp_neg *neg, - pj_bool_t allow_asym) + pjmedia_sdp_neg *neg, + pj_bool_t allow_asym) { pj_status_t status; @@ -1574,51 +1573,51 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_negotiate( pj_pool_t *pool, /* Must be in STATE_WAIT_NEGO state. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO, - PJMEDIA_SDPNEG_EINSTATE); + PJMEDIA_SDPNEG_EINSTATE); /* Must have remote offer. */ PJ_ASSERT_RETURN(neg->neg_remote_sdp, PJ_EBUG); if (neg->has_remote_answer) { - pjmedia_sdp_session *active; - status = process_answer(pool, neg->neg_local_sdp, neg->neg_remote_sdp, - allow_asym, &active); - if (status == PJ_SUCCESS) { - /* Only update active SDPs when negotiation is successfull */ - neg->active_local_sdp = active; - neg->active_remote_sdp = neg->neg_remote_sdp; - } + pjmedia_sdp_session *active; + status = process_answer(pool, neg->neg_local_sdp, neg->neg_remote_sdp, + allow_asym, &active); + if (status == PJ_SUCCESS) { + /* Only update active SDPs when negotiation is successfull */ + neg->active_local_sdp = active; + neg->active_remote_sdp = neg->neg_remote_sdp; + } } else { - pjmedia_sdp_session *answer = NULL; + pjmedia_sdp_session *answer = NULL; - status = create_answer(pool, neg->prefer_remote_codec_order, + status = create_answer(pool, neg->prefer_remote_codec_order, neg->answer_with_multiple_codecs, - neg->neg_local_sdp, neg->neg_remote_sdp, - &answer); - if (status == PJ_SUCCESS) { - pj_uint32_t active_ver; + neg->neg_local_sdp, neg->neg_remote_sdp, + &answer); + if (status == PJ_SUCCESS) { + pj_uint32_t active_ver; - if (neg->active_local_sdp) - active_ver = neg->active_local_sdp->origin.version; - else - active_ver = neg->initial_sdp->origin.version; + if (neg->active_local_sdp) + active_ver = neg->active_local_sdp->origin.version; + else + active_ver = neg->initial_sdp->origin.version; #if PJMEDIA_SDP_NEG_COMPARE_BEFORE_INC_VERSION - answer->origin.version = active_ver; - - if ((neg->active_local_sdp == NULL) || - (pjmedia_sdp_session_cmp(answer, neg->active_local_sdp, 0) - != PJ_SUCCESS)) - { - ++answer->origin.version; - } + answer->origin.version = active_ver; + + if ((neg->active_local_sdp == NULL) || + (pjmedia_sdp_session_cmp(answer, neg->active_local_sdp, 0) + != PJ_SUCCESS)) + { + ++answer->origin.version; + } #else - answer->origin.version = active_ver + 1; -#endif - /* Only update active SDPs when negotiation is successfull */ - neg->active_local_sdp = answer; - neg->active_remote_sdp = neg->neg_remote_sdp; - } + answer->origin.version = active_ver + 1; +#endif + /* Only update active SDPs when negotiation is successfull */ + neg->active_local_sdp = answer; + neg->active_remote_sdp = neg->neg_remote_sdp; + } } /* State is DONE regardless */ @@ -1629,7 +1628,7 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_negotiate( pj_pool_t *pool, /* Revert back initial SDP if nego fails */ if (status != PJ_SUCCESS) - neg->initial_sdp = neg->initial_sdp_tmp; + neg->initial_sdp = neg->initial_sdp_tmp; /* Clear temporary SDP */ neg->initial_sdp_tmp = NULL; @@ -1641,22 +1640,22 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_negotiate( pj_pool_t *pool, static pj_status_t custom_fmt_match(pj_pool_t *pool, - const pj_str_t *fmt_name, - pjmedia_sdp_media *offer, - unsigned o_fmt_idx, - pjmedia_sdp_media *answer, - unsigned a_fmt_idx, - unsigned option) + const pj_str_t *fmt_name, + pjmedia_sdp_media *offer, + unsigned o_fmt_idx, + pjmedia_sdp_media *answer, + unsigned a_fmt_idx, + unsigned option) { unsigned i; for (i = 0; i < fmt_match_cb_cnt; ++i) { - if (pj_stricmp(fmt_name, &fmt_match_cb[i].fmt_name) == 0) { - pj_assert(fmt_match_cb[i].cb); - return (*fmt_match_cb[i].cb)(pool, offer, o_fmt_idx, - answer, a_fmt_idx, - option); - } + if (pj_stricmp(fmt_name, &fmt_match_cb[i].fmt_name) == 0) { + pj_assert(fmt_match_cb[i].cb); + return (*fmt_match_cb[i].cb)(pool, offer, o_fmt_idx, + answer, a_fmt_idx, + option); + } } /* Not customized format matching found, should be matched */ @@ -1665,8 +1664,8 @@ static pj_status_t custom_fmt_match(pj_pool_t *pool, /* Register customized SDP format negotiation callback function. */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_register_fmt_match_cb( - const pj_str_t *fmt_name, - pjmedia_sdp_neg_fmt_match_cb cb) + const pj_str_t *fmt_name, + pjmedia_sdp_neg_fmt_match_cb cb) { struct fmt_match_cb_t *f = NULL; unsigned i; @@ -1675,35 +1674,35 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_register_fmt_match_cb( /* Check if the callback for the format name has been registered */ for (i = 0; i < fmt_match_cb_cnt; ++i) { - if (pj_stricmp(fmt_name, &fmt_match_cb[i].fmt_name) == 0) - break; + if (pj_stricmp(fmt_name, &fmt_match_cb[i].fmt_name) == 0) + break; } /* Unregistration */ if (cb == NULL) { - if (i == fmt_match_cb_cnt) - return PJ_ENOTFOUND; + if (i == fmt_match_cb_cnt) + return PJ_ENOTFOUND; - pj_array_erase(fmt_match_cb, sizeof(fmt_match_cb[0]), - fmt_match_cb_cnt, i); - fmt_match_cb_cnt--; + pj_array_erase(fmt_match_cb, sizeof(fmt_match_cb[0]), + fmt_match_cb_cnt, i); + fmt_match_cb_cnt--; - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Registration */ if (i < fmt_match_cb_cnt) { - /* The same format name has been registered before */ - if (cb != fmt_match_cb[i].cb) - return PJ_EEXISTS; - else - return PJ_SUCCESS; + /* The same format name has been registered before */ + if (cb != fmt_match_cb[i].cb) + return PJ_EEXISTS; + else + return PJ_SUCCESS; } if (fmt_match_cb_cnt >= PJ_ARRAY_SIZE(fmt_match_cb)) - return PJ_ETOOMANY; + return PJ_ETOOMANY; f = &fmt_match_cb[fmt_match_cb_cnt++]; f->fmt_name = *fmt_name; @@ -1715,11 +1714,11 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_register_fmt_match_cb( /* Match format in the SDP media offer and answer. */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_fmt_match(pj_pool_t *pool, - pjmedia_sdp_media *offer, - unsigned o_fmt_idx, - pjmedia_sdp_media *answer, - unsigned a_fmt_idx, - unsigned option) + pjmedia_sdp_media *offer, + unsigned o_fmt_idx, + pjmedia_sdp_media *answer, + unsigned a_fmt_idx, + unsigned option) { const pjmedia_sdp_attr *attr; pjmedia_sdp_rtpmap o_rtpmap, a_rtpmap; @@ -1730,42 +1729,42 @@ PJ_DEF(pj_status_t) pjmedia_sdp_neg_fmt_match(pj_pool_t *pool, a_pt = pj_strtoul(&answer->desc.fmt[a_fmt_idx]); if (o_pt < 96 || a_pt < 96) { - if (o_pt == a_pt) - return PJ_SUCCESS; - else - return PJMEDIA_SDP_EFORMATNOTEQUAL; + if (o_pt == a_pt) + return PJ_SUCCESS; + else + return PJMEDIA_SDP_EFORMATNOTEQUAL; } /* Get the format rtpmap from the offer. */ attr = pjmedia_sdp_media_find_attr2(offer, "rtpmap", - &offer->desc.fmt[o_fmt_idx]); + &offer->desc.fmt[o_fmt_idx]); if (!attr) { - pj_assert(!"Bug! Offer haven't been validated"); - return PJ_EBUG; + pj_assert(!"Bug! Offer haven't been validated"); + return PJ_EBUG; } pjmedia_sdp_attr_get_rtpmap(attr, &o_rtpmap); /* Get the format rtpmap from the answer. */ attr = pjmedia_sdp_media_find_attr2(answer, "rtpmap", - &answer->desc.fmt[a_fmt_idx]); + &answer->desc.fmt[a_fmt_idx]); if (!attr) { - pj_assert(!"Bug! Answer haven't been validated"); - return PJ_EBUG; + pj_assert(!"Bug! Answer haven't been validated"); + return PJ_EBUG; } pjmedia_sdp_attr_get_rtpmap(attr, &a_rtpmap); if (pj_stricmp(&o_rtpmap.enc_name, &a_rtpmap.enc_name) != 0 || - (o_rtpmap.clock_rate != a_rtpmap.clock_rate) || - (!(pj_stricmp(&o_rtpmap.param, &a_rtpmap.param) == 0 || - (a_rtpmap.param.slen == 0 && o_rtpmap.param.slen == 1 && - *o_rtpmap.param.ptr == '1') || - (o_rtpmap.param.slen == 0 && a_rtpmap.param.slen == 1 && - *a_rtpmap.param.ptr=='1')))) + (o_rtpmap.clock_rate != a_rtpmap.clock_rate) || + (!(pj_stricmp(&o_rtpmap.param, &a_rtpmap.param) == 0 || + (a_rtpmap.param.slen == 0 && o_rtpmap.param.slen == 1 && + *o_rtpmap.param.ptr == '1') || + (o_rtpmap.param.slen == 0 && a_rtpmap.param.slen == 1 && + *a_rtpmap.param.ptr=='1')))) { - return PJMEDIA_SDP_EFORMATNOTEQUAL; + return PJMEDIA_SDP_EFORMATNOTEQUAL; } return custom_fmt_match(pool, &o_rtpmap.enc_name, - offer, o_fmt_idx, answer, a_fmt_idx, option); + offer, o_fmt_idx, answer, a_fmt_idx, option); } diff --git a/pjmedia/src/pjmedia/sdp_wrap.cpp b/pjmedia/src/pjmedia/sdp_wrap.cpp index 24bae56ed8..93e421007f 100644 --- a/pjmedia/src/pjmedia/sdp_wrap.cpp +++ b/pjmedia/src/pjmedia/sdp_wrap.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjmedia/src/pjmedia/session.c b/pjmedia/src/pjmedia/session.c index 96c6e42032..291e0ce092 100644 --- a/pjmedia/src/pjmedia/session.c +++ b/pjmedia/src/pjmedia/session.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,33 +29,33 @@ struct pjmedia_session { - pj_pool_t *pool; - pjmedia_endpt *endpt; - unsigned stream_cnt; - pjmedia_stream_info stream_info[PJMEDIA_MAX_SDP_MEDIA]; - pjmedia_stream *stream[PJMEDIA_MAX_SDP_MEDIA]; - void *user_data; + pj_pool_t *pool; + pjmedia_endpt *endpt; + unsigned stream_cnt; + pjmedia_stream_info stream_info[PJMEDIA_MAX_SDP_MEDIA]; + pjmedia_stream *stream[PJMEDIA_MAX_SDP_MEDIA]; + void *user_data; }; -#define THIS_FILE "session.c" +#define THIS_FILE "session.c" #ifndef PJMEDIA_SESSION_SIZE -# define PJMEDIA_SESSION_SIZE (10*1024) +# define PJMEDIA_SESSION_SIZE (10*1024) #endif #ifndef PJMEDIA_SESSION_INC -# define PJMEDIA_SESSION_INC 1024 +# define PJMEDIA_SESSION_INC 1024 #endif /* * Initialize session info from SDP session descriptors. */ PJ_DEF(pj_status_t) pjmedia_session_info_from_sdp( pj_pool_t *pool, - pjmedia_endpt *endpt, - unsigned max_streams, - pjmedia_session_info *si, - const pjmedia_sdp_session *local, - const pjmedia_sdp_session *remote) + pjmedia_endpt *endpt, + unsigned max_streams, + pjmedia_session_info *si, + const pjmedia_sdp_session *local, + const pjmedia_sdp_session *remote) { unsigned i; @@ -64,16 +63,16 @@ PJ_DEF(pj_status_t) pjmedia_session_info_from_sdp( pj_pool_t *pool, si->stream_cnt = max_streams; if (si->stream_cnt > local->media_count) - si->stream_cnt = local->media_count; + si->stream_cnt = local->media_count; for (i=0; istream_cnt; ++i) { - pj_status_t status; + pj_status_t status; - status = pjmedia_stream_info_from_sdp( &si->stream_info[i], pool, - endpt, - local, remote, i); - if (status != PJ_SUCCESS) - return status; + status = pjmedia_stream_info_from_sdp( &si->stream_info[i], pool, + endpt, + local, remote, i); + if (status != PJ_SUCCESS) + return status; } return PJ_SUCCESS; @@ -84,10 +83,10 @@ PJ_DEF(pj_status_t) pjmedia_session_info_from_sdp( pj_pool_t *pool, * Create new session. */ PJ_DEF(pj_status_t) pjmedia_session_create( pjmedia_endpt *endpt, - const pjmedia_session_info *si, - pjmedia_transport *transports[], - void *user_data, - pjmedia_session **p_session ) + const pjmedia_session_info *si, + pjmedia_transport *transports[], + void *user_data, + pjmedia_session **p_session ) { pj_pool_t *pool; pjmedia_session *session; @@ -99,8 +98,8 @@ PJ_DEF(pj_status_t) pjmedia_session_create( pjmedia_endpt *endpt, /* Create pool for the session. */ pool = pjmedia_endpt_create_pool( endpt, "session", - PJMEDIA_SESSION_SIZE, - PJMEDIA_SESSION_INC); + PJMEDIA_SESSION_SIZE, + PJMEDIA_SESSION_INC); PJ_ASSERT_RETURN(pool != NULL, PJ_ENOMEM); session = PJ_POOL_ZALLOC_T(pool, pjmedia_session); @@ -111,31 +110,31 @@ PJ_DEF(pj_status_t) pjmedia_session_create( pjmedia_endpt *endpt, /* Copy stream info (this simple memcpy may break sometime) */ pj_memcpy(session->stream_info, si->stream_info, - si->stream_cnt * sizeof(pjmedia_stream_info)); + si->stream_cnt * sizeof(pjmedia_stream_info)); /* * Now create and start the stream! */ for (i=0; i<(int)si->stream_cnt; ++i) { - /* Create the stream */ - status = pjmedia_stream_create(endpt, session->pool, - &session->stream_info[i], - (transports?transports[i]:NULL), - session, - &session->stream[i]); - if (status == PJ_SUCCESS) - status = pjmedia_stream_start(session->stream[i]); + /* Create the stream */ + status = pjmedia_stream_create(endpt, session->pool, + &session->stream_info[i], + (transports?transports[i]:NULL), + session, + &session->stream[i]); + if (status == PJ_SUCCESS) + status = pjmedia_stream_start(session->stream[i]); - if (status != PJ_SUCCESS) { + if (status != PJ_SUCCESS) { - for ( --i; i>=0; --i) { - pjmedia_stream_destroy(session->stream[i]); - } + for ( --i; i>=0; --i) { + pjmedia_stream_destroy(session->stream[i]); + } - pj_pool_release(session->pool); - return status; - } + pj_pool_release(session->pool); + return status; + } } @@ -150,13 +149,13 @@ PJ_DEF(pj_status_t) pjmedia_session_create( pjmedia_endpt *endpt, * Get session info. */ PJ_DEF(pj_status_t) pjmedia_session_get_info( pjmedia_session *session, - pjmedia_session_info *info ) + pjmedia_session_info *info ) { PJ_ASSERT_RETURN(session && info, PJ_EINVAL); info->stream_cnt = session->stream_cnt; pj_memcpy(info->stream_info, session->stream_info, - session->stream_cnt * sizeof(pjmedia_stream_info)); + session->stream_cnt * sizeof(pjmedia_stream_info)); return PJ_SUCCESS; } @@ -179,8 +178,8 @@ PJ_DEF(pj_status_t) pjmedia_session_destroy (pjmedia_session *session) PJ_ASSERT_RETURN(session, PJ_EINVAL); for (i=0; istream_cnt; ++i) { - - pjmedia_stream_destroy(session->stream[i]); + + pjmedia_stream_destroy(session->stream[i]); } @@ -195,14 +194,14 @@ PJ_DEF(pj_status_t) pjmedia_session_destroy (pjmedia_session *session) * */ PJ_DEF(pj_status_t) pjmedia_session_resume(pjmedia_session *session, - pjmedia_dir dir) + pjmedia_dir dir) { unsigned i; PJ_ASSERT_RETURN(session, PJ_EINVAL); for (i=0; istream_cnt; ++i) { - pjmedia_session_resume_stream(session, i, dir); + pjmedia_session_resume_stream(session, i, dir); } return PJ_SUCCESS; @@ -214,14 +213,14 @@ PJ_DEF(pj_status_t) pjmedia_session_resume(pjmedia_session *session, * */ PJ_DEF(pj_status_t) pjmedia_session_pause(pjmedia_session *session, - pjmedia_dir dir) + pjmedia_dir dir) { unsigned i; PJ_ASSERT_RETURN(session, PJ_EINVAL); for (i=0; istream_cnt; ++i) { - pjmedia_session_pause_stream(session, i, dir); + pjmedia_session_pause_stream(session, i, dir); } return PJ_SUCCESS; @@ -232,8 +231,8 @@ PJ_DEF(pj_status_t) pjmedia_session_pause(pjmedia_session *session, * Suspend receipt and transmission of individual stream in media session. */ PJ_DEF(pj_status_t) pjmedia_session_pause_stream( pjmedia_session *session, - unsigned index, - pjmedia_dir dir) + unsigned index, + pjmedia_dir dir) { PJ_ASSERT_RETURN(session && index < session->stream_cnt, PJ_EINVAL); @@ -246,8 +245,8 @@ PJ_DEF(pj_status_t) pjmedia_session_pause_stream( pjmedia_session *session, * */ PJ_DEF(pj_status_t) pjmedia_session_resume_stream( pjmedia_session *session, - unsigned index, - pjmedia_dir dir) + unsigned index, + pjmedia_dir dir) { PJ_ASSERT_RETURN(session && index < session->stream_cnt, PJ_EINVAL); @@ -265,7 +264,7 @@ pjmedia_session_send_rtcp_sdes( const pjmedia_session *session ) PJ_ASSERT_RETURN(session, PJ_EINVAL); for (i=0; istream_cnt; ++i) { - pjmedia_stream_send_rtcp_sdes(session->stream[i]); + pjmedia_stream_send_rtcp_sdes(session->stream[i]); } return PJ_SUCCESS; @@ -282,7 +281,7 @@ pjmedia_session_send_rtcp_bye( const pjmedia_session *session ) PJ_ASSERT_RETURN(session, PJ_EINVAL); for (i=0; istream_cnt; ++i) { - pjmedia_stream_send_rtcp_bye(session->stream[i]); + pjmedia_stream_send_rtcp_bye(session->stream[i]); } return PJ_SUCCESS; @@ -292,18 +291,18 @@ pjmedia_session_send_rtcp_bye( const pjmedia_session *session ) * Enumerate media stream in the session. */ PJ_DEF(pj_status_t) pjmedia_session_enum_streams(const pjmedia_session *session, - unsigned *count, - pjmedia_stream_info info[]) + unsigned *count, + pjmedia_stream_info info[]) { unsigned i; PJ_ASSERT_RETURN(session && count && *count && info, PJ_EINVAL); if (*count > session->stream_cnt) - *count = session->stream_cnt; + *count = session->stream_cnt; for (i=0; i<*count; ++i) { - pj_memcpy(&info[i], &session->stream_info[i], + pj_memcpy(&info[i], &session->stream_info[i], sizeof(pjmedia_stream_info)); } @@ -315,8 +314,8 @@ PJ_DEF(pj_status_t) pjmedia_session_enum_streams(const pjmedia_session *session, * Get the port interface. */ PJ_DEF(pj_status_t) pjmedia_session_get_port( pjmedia_session *session, - unsigned index, - pjmedia_port **p_port) + unsigned index, + pjmedia_port **p_port) { return pjmedia_stream_get_port( session->stream[index], p_port); } @@ -325,11 +324,11 @@ PJ_DEF(pj_status_t) pjmedia_session_get_port( pjmedia_session *session, * Get statistics */ PJ_DEF(pj_status_t) pjmedia_session_get_stream_stat( pjmedia_session *session, - unsigned index, - pjmedia_rtcp_stat *stat) + unsigned index, + pjmedia_rtcp_stat *stat) { PJ_ASSERT_RETURN(session && stat && index < session->stream_cnt, - PJ_EINVAL); + PJ_EINVAL); return pjmedia_stream_get_stat(session->stream[index], stat); } @@ -339,7 +338,7 @@ PJ_DEF(pj_status_t) pjmedia_session_get_stream_stat( pjmedia_session *session, * Reset session statistics. */ PJ_DEF(pj_status_t) pjmedia_session_reset_stream_stat( pjmedia_session *session, - unsigned index) + unsigned index) { PJ_ASSERT_RETURN(session && index < session->stream_cnt, PJ_EINVAL); @@ -352,24 +351,24 @@ PJ_DEF(pj_status_t) pjmedia_session_reset_stream_stat( pjmedia_session *session, * Get extended statistics */ PJ_DEF(pj_status_t) pjmedia_session_get_stream_stat_xr( - pjmedia_session *session, - unsigned index, - pjmedia_rtcp_xr_stat *stat_xr) + pjmedia_session *session, + unsigned index, + pjmedia_rtcp_xr_stat *stat_xr) { PJ_ASSERT_RETURN(session && stat_xr && index < session->stream_cnt, - PJ_EINVAL); + PJ_EINVAL); return pjmedia_stream_get_stat_xr(session->stream[index], stat_xr); } #endif PJ_DEF(pj_status_t) pjmedia_session_get_stream_stat_jbuf( - pjmedia_session *session, - unsigned index, - pjmedia_jb_state *state) + pjmedia_session *session, + unsigned index, + pjmedia_jb_state *state) { PJ_ASSERT_RETURN(session && state && index < session->stream_cnt, - PJ_EINVAL); + PJ_EINVAL); return pjmedia_stream_get_stat_jbuf(session->stream[index], state); } @@ -378,8 +377,8 @@ PJ_DEF(pj_status_t) pjmedia_session_get_stream_stat_jbuf( * Dial DTMF digit to the stream, using RFC 2833 mechanism. */ PJ_DEF(pj_status_t) pjmedia_session_dial_dtmf( pjmedia_session *session, - unsigned index, - const pj_str_t *ascii_digits ) + unsigned index, + const pj_str_t *ascii_digits ) { PJ_ASSERT_RETURN(session && ascii_digits, PJ_EINVAL); return pjmedia_stream_dial_dtmf(session->stream[index], ascii_digits); @@ -389,7 +388,7 @@ PJ_DEF(pj_status_t) pjmedia_session_dial_dtmf( pjmedia_session *session, * Check if the specified stream has received DTMF digits. */ PJ_DEF(pj_status_t) pjmedia_session_check_dtmf( pjmedia_session *session, - unsigned index ) + unsigned index ) { PJ_ASSERT_RETURN(session, PJ_EINVAL); return pjmedia_stream_check_dtmf(session->stream[index]); @@ -400,27 +399,27 @@ PJ_DEF(pj_status_t) pjmedia_session_check_dtmf( pjmedia_session *session, * Retrieve DTMF digits from the specified stream. */ PJ_DEF(pj_status_t) pjmedia_session_get_dtmf( pjmedia_session *session, - unsigned index, - char *ascii_digits, - unsigned *size ) + unsigned index, + char *ascii_digits, + unsigned *size ) { PJ_ASSERT_RETURN(session && ascii_digits && size, PJ_EINVAL); return pjmedia_stream_get_dtmf(session->stream[index], ascii_digits, - size); + size); } /* * Install DTMF callback. */ PJ_DEF(pj_status_t) pjmedia_session_set_dtmf_callback(pjmedia_session *session, - unsigned index, - void (*cb)(pjmedia_stream*, - void *user_data, - int digit), - void *user_data) + unsigned index, + void (*cb)(pjmedia_stream*, + void *user_data, + int digit), + void *user_data) { PJ_ASSERT_RETURN(session && index < session->stream_cnt, PJ_EINVAL); return pjmedia_stream_set_dtmf_callback(session->stream[index], cb, - user_data); + user_data); } diff --git a/pjmedia/src/pjmedia/silencedet.c b/pjmedia/src/pjmedia/silencedet.c index e0342241d6..a2f8964c46 100644 --- a/pjmedia/src/pjmedia/silencedet.c +++ b/pjmedia/src/pjmedia/silencedet.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,7 +27,7 @@ #define THIS_FILE "silencedet.c" #if 1 -# define TRACE_(x) PJ_LOG(5,x) +# define TRACE_(x) PJ_LOG(5,x) #else # define TRACE_(x) #endif @@ -45,13 +44,13 @@ typedef enum pjmedia_silence_det_mode { /** * Default settings */ -#define DEF_RECALC_ON_VOICED 4000 /* Time to recalculate threshold - in voiced condition, in ms */ -#define DEF_RECALC_ON_SILENCE 2000 /* Time to recalculate threshold - in silence condition, in ms. */ -#define DEF_BEFORE_SILENCE 400 /* Silence time before really changing - state into SILENCE, in ms. */ -#define DEF_THRESHOLD 1000 /* Default threshold. */ +#define DEF_RECALC_ON_VOICED 4000 /* Time to recalculate threshold + in voiced condition, in ms */ +#define DEF_RECALC_ON_SILENCE 2000 /* Time to recalculate threshold + in silence condition, in ms. */ +#define DEF_BEFORE_SILENCE 400 /* Silence time before really changing + state into SILENCE, in ms. */ +#define DEF_THRESHOLD 1000 /* Default threshold. */ /** * This enumeration specifies the states of the silence detector. @@ -67,33 +66,33 @@ enum pjmedia_silence_det_state { */ struct pjmedia_silence_det { - char objname[PJ_MAX_OBJ_NAME]; /**< VAD name. */ + char objname[PJ_MAX_OBJ_NAME]; /**< VAD name. */ - int mode; /**< VAD mode. */ - unsigned ptime; /**< Frame time, in msec. */ + int mode; /**< VAD mode. */ + unsigned ptime; /**< Frame time, in msec. */ - unsigned threshold; /**< Current threshold level. */ - unsigned sum_level; /**< Total sum of recent level. */ - unsigned sum_cnt; /**< Number of level summed. */ - unsigned silence_timer; /**< Silence condition timer. */ - unsigned voiced_timer; /**< Voiced condition timer. */ + unsigned threshold; /**< Current threshold level. */ + unsigned sum_level; /**< Total sum of recent level. */ + unsigned sum_cnt; /**< Number of level summed. */ + unsigned silence_timer; /**< Silence condition timer. */ + unsigned voiced_timer; /**< Voiced condition timer. */ - enum pjmedia_silence_det_state state;/**< Silence detector state. */ - unsigned recalc_on_voiced; /**< Setting of time to recalc - threshold in voiced condition. */ - unsigned recalc_on_silence; /**< Setting of time to recalc - threshold in silence condition.*/ - unsigned before_silence; /**< Setting of silence time before - really changing state into SILENCE, - in ms. */ + enum pjmedia_silence_det_state state;/**< Silence detector state. */ + unsigned recalc_on_voiced; /**< Setting of time to recalc + threshold in voiced condition. */ + unsigned recalc_on_silence; /**< Setting of time to recalc + threshold in silence condition.*/ + unsigned before_silence; /**< Setting of silence time before + really changing state into SILENCE, + in ms. */ }; PJ_DEF(pj_status_t) pjmedia_silence_det_create( pj_pool_t *pool, - unsigned clock_rate, - unsigned samples_per_frame, - pjmedia_silence_det **p_sd) + unsigned clock_rate, + unsigned samples_per_frame, + pjmedia_silence_det **p_sd) { pjmedia_silence_det *sd; @@ -118,7 +117,7 @@ PJ_DEF(pj_status_t) pjmedia_silence_det_create( pj_pool_t *pool, PJ_DEF(pj_status_t) pjmedia_silence_det_set_name( pjmedia_silence_det *sd, - const char *name) + const char *name) { PJ_ASSERT_RETURN(sd && name, PJ_EINVAL); @@ -128,12 +127,12 @@ PJ_DEF(pj_status_t) pjmedia_silence_det_set_name( pjmedia_silence_det *sd, } PJ_DEF(pj_status_t) pjmedia_silence_det_set_adaptive(pjmedia_silence_det *sd, - int threshold) + int threshold) { PJ_ASSERT_RETURN(sd, PJ_EINVAL); if (threshold < 0) - threshold = DEF_THRESHOLD; + threshold = DEF_THRESHOLD; sd->mode = VAD_MODE_ADAPTIVE; sd->threshold = threshold; @@ -142,12 +141,12 @@ PJ_DEF(pj_status_t) pjmedia_silence_det_set_adaptive(pjmedia_silence_det *sd, } PJ_DEF(pj_status_t) pjmedia_silence_det_set_fixed( pjmedia_silence_det *sd, - int threshold ) + int threshold ) { PJ_ASSERT_RETURN(sd, PJ_EINVAL); if (threshold < 0) - threshold = DEF_THRESHOLD; + threshold = DEF_THRESHOLD; sd->mode = VAD_MODE_FIXED; sd->threshold = threshold; @@ -156,18 +155,18 @@ PJ_DEF(pj_status_t) pjmedia_silence_det_set_fixed( pjmedia_silence_det *sd, } PJ_DEF(pj_status_t) pjmedia_silence_det_set_params( pjmedia_silence_det *sd, - int before_silence, - int recalc_time1, - int recalc_time2) + int before_silence, + int recalc_time1, + int recalc_time2) { PJ_ASSERT_RETURN(sd, PJ_EINVAL); if (recalc_time1 < 0) - recalc_time1 = DEF_RECALC_ON_VOICED; + recalc_time1 = DEF_RECALC_ON_VOICED; if (recalc_time2 < 0) - recalc_time2 = DEF_RECALC_ON_SILENCE; + recalc_time2 = DEF_RECALC_ON_SILENCE; if (before_silence < 0) - before_silence = DEF_BEFORE_SILENCE; + before_silence = DEF_BEFORE_SILENCE; sd->recalc_on_voiced = recalc_time1; sd->recalc_on_silence = recalc_time2; @@ -188,7 +187,7 @@ PJ_DEF(pj_status_t) pjmedia_silence_det_disable( pjmedia_silence_det *sd ) PJ_DEF(pj_int32_t) pjmedia_calc_avg_signal( const pj_int16_t samples[], - pj_size_t count) + pj_size_t count) { pj_uint32_t sum = 0; @@ -196,28 +195,28 @@ PJ_DEF(pj_int32_t) pjmedia_calc_avg_signal( const pj_int16_t samples[], const pj_int16_t * end = samples + count; if (count==0) - return 0; + return 0; while (pcm != end) { - if (*pcm < 0) - sum -= *pcm++; - else - sum += *pcm++; + if (*pcm < 0) + sum -= *pcm++; + else + sum += *pcm++; } return (pj_int32_t)(sum / count); } PJ_DEF(pj_bool_t) pjmedia_silence_det_apply( pjmedia_silence_det *sd, - pj_uint32_t level) + pj_uint32_t level) { int avg_recent_level; if (sd->mode == VAD_MODE_NONE) - return PJ_FALSE; + return PJ_FALSE; if (sd->mode == VAD_MODE_FIXED) - return (level < sd->threshold); + return (level < sd->threshold); /* Calculating recent level */ sd->sum_level += level; @@ -225,89 +224,89 @@ PJ_DEF(pj_bool_t) pjmedia_silence_det_apply( pjmedia_silence_det *sd, avg_recent_level = (sd->sum_level / sd->sum_cnt); if (level > sd->threshold || - level >= PJMEDIA_SILENCE_DET_MAX_THRESHOLD) + level >= PJMEDIA_SILENCE_DET_MAX_THRESHOLD) { - sd->silence_timer = 0; - sd->voiced_timer += sd->ptime; - - switch(sd->state) { - case STATE_VOICED: - if (sd->voiced_timer > sd->recalc_on_voiced) { - /* Voiced for long time (>recalc_on_voiced), current - * threshold seems to be too low. - */ - sd->threshold = (avg_recent_level + sd->threshold) >> 1; - TRACE_((THIS_FILE,"Re-adjust threshold (in talk burst)" - "to %d", sd->threshold)); - - sd->voiced_timer = 0; - - /* Reset sig_level */ - sd->sum_level = avg_recent_level; - sd->sum_cnt = 1; - } - break; - - case STATE_SILENCE: - TRACE_((THIS_FILE,"Starting talk burst (level=%d threshold=%d)", - level, sd->threshold)); - - case STATE_START_SILENCE: - sd->state = STATE_VOICED; - - /* Reset sig_level */ - sd->sum_level = level; - sd->sum_cnt = 1; - - break; - - default: - pj_assert(0); - break; - } + sd->silence_timer = 0; + sd->voiced_timer += sd->ptime; + + switch(sd->state) { + case STATE_VOICED: + if (sd->voiced_timer > sd->recalc_on_voiced) { + /* Voiced for long time (>recalc_on_voiced), current + * threshold seems to be too low. + */ + sd->threshold = (avg_recent_level + sd->threshold) >> 1; + TRACE_((THIS_FILE,"Re-adjust threshold (in talk burst)" + "to %d", sd->threshold)); + + sd->voiced_timer = 0; + + /* Reset sig_level */ + sd->sum_level = avg_recent_level; + sd->sum_cnt = 1; + } + break; + + case STATE_SILENCE: + TRACE_((THIS_FILE,"Starting talk burst (level=%d threshold=%d)", + level, sd->threshold)); + + case STATE_START_SILENCE: + sd->state = STATE_VOICED; + + /* Reset sig_level */ + sd->sum_level = level; + sd->sum_cnt = 1; + + break; + + default: + pj_assert(0); + break; + } } else { - sd->voiced_timer = 0; - sd->silence_timer += sd->ptime; - - switch(sd->state) { - case STATE_SILENCE: - if (sd->silence_timer >= sd->recalc_on_silence) { - sd->threshold = avg_recent_level << 1; - TRACE_((THIS_FILE,"Re-adjust threshold (in silence)" - "to %d", sd->threshold)); - - sd->silence_timer = 0; - - /* Reset sig_level */ - sd->sum_level = avg_recent_level; - sd->sum_cnt = 1; - } - break; - - case STATE_VOICED: - sd->state = STATE_START_SILENCE; - - /* Reset sig_level */ - sd->sum_level = level; - sd->sum_cnt = 1; - - case STATE_START_SILENCE: - if (sd->silence_timer >= sd->before_silence) { - sd->state = STATE_SILENCE; - sd->threshold = avg_recent_level << 1; - TRACE_((THIS_FILE,"Starting silence (level=%d " - "threshold=%d)", level, sd->threshold)); - - /* Reset sig_level */ - sd->sum_level = avg_recent_level; - sd->sum_cnt = 1; - } - break; - - default: - pj_assert(0); - break; - } + sd->voiced_timer = 0; + sd->silence_timer += sd->ptime; + + switch(sd->state) { + case STATE_SILENCE: + if (sd->silence_timer >= sd->recalc_on_silence) { + sd->threshold = avg_recent_level << 1; + TRACE_((THIS_FILE,"Re-adjust threshold (in silence)" + "to %d", sd->threshold)); + + sd->silence_timer = 0; + + /* Reset sig_level */ + sd->sum_level = avg_recent_level; + sd->sum_cnt = 1; + } + break; + + case STATE_VOICED: + sd->state = STATE_START_SILENCE; + + /* Reset sig_level */ + sd->sum_level = level; + sd->sum_cnt = 1; + + case STATE_START_SILENCE: + if (sd->silence_timer >= sd->before_silence) { + sd->state = STATE_SILENCE; + sd->threshold = avg_recent_level << 1; + TRACE_((THIS_FILE,"Starting silence (level=%d " + "threshold=%d)", level, sd->threshold)); + + /* Reset sig_level */ + sd->sum_level = avg_recent_level; + sd->sum_cnt = 1; + } + break; + + default: + pj_assert(0); + break; + } } return (sd->state == STATE_SILENCE); @@ -315,9 +314,9 @@ PJ_DEF(pj_bool_t) pjmedia_silence_det_apply( pjmedia_silence_det *sd, PJ_DEF(pj_bool_t) pjmedia_silence_det_detect( pjmedia_silence_det *sd, - const pj_int16_t samples[], - pj_size_t count, - pj_int32_t *p_level) + const pj_int16_t samples[], + pj_size_t count, + pj_int32_t *p_level) { pj_uint32_t level; @@ -326,7 +325,7 @@ PJ_DEF(pj_bool_t) pjmedia_silence_det_detect( pjmedia_silence_det *sd, /* Report to caller, if required. */ if (p_level) - *p_level = level; + *p_level = level; return pjmedia_silence_det_apply(sd, level); } diff --git a/pjmedia/src/pjmedia/sound_legacy.c b/pjmedia/src/pjmedia/sound_legacy.c index ee9dd027b6..381cd13ea1 100644 --- a/pjmedia/src/pjmedia/sound_legacy.c +++ b/pjmedia/src/pjmedia/sound_legacy.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -34,18 +33,18 @@ static struct legacy_subsys { pjmedia_snd_dev_info info[4]; - unsigned info_counter; - unsigned user_rec_latency; - unsigned user_play_latency; + unsigned info_counter; + unsigned user_rec_latency; + unsigned user_play_latency; } g_sys; struct pjmedia_snd_stream { - pj_pool_t *pool; - pjmedia_aud_stream *aud_strm; - pjmedia_snd_rec_cb user_rec_cb; + pj_pool_t *pool; + pjmedia_aud_stream *aud_strm; + pjmedia_snd_rec_cb user_rec_cb; pjmedia_snd_play_cb user_play_cb; - void *user_user_data; + void *user_user_data; }; @@ -57,7 +56,7 @@ PJ_DEF(const pjmedia_snd_dev_info*) pjmedia_snd_get_dev_info(unsigned index) g_sys.info_counter = (g_sys.info_counter+1) % PJ_ARRAY_SIZE(g_sys.info); if (pjmedia_aud_dev_get_info(index, &di) != PJ_SUCCESS) - return NULL; + return NULL; pj_bzero(oi, sizeof(*oi)); pj_ansi_strncpy(oi->name, di.name, sizeof(oi->name)); @@ -71,38 +70,38 @@ PJ_DEF(const pjmedia_snd_dev_info*) pjmedia_snd_get_dev_info(unsigned index) static pj_status_t snd_play_cb(void *user_data, - pjmedia_frame *frame) + pjmedia_frame *frame) { pjmedia_snd_stream *strm = (pjmedia_snd_stream*)user_data; frame->type = PJMEDIA_FRAME_TYPE_AUDIO; return strm->user_play_cb(strm->user_user_data, - frame->timestamp.u32.lo, - frame->buf, - (unsigned)frame->size); + frame->timestamp.u32.lo, + frame->buf, + (unsigned)frame->size); } static pj_status_t snd_rec_cb(void *user_data, - pjmedia_frame *frame) + pjmedia_frame *frame) { pjmedia_snd_stream *strm = (pjmedia_snd_stream*)user_data; return strm->user_rec_cb(strm->user_user_data, - frame->timestamp.u32.lo, - frame->buf, - (unsigned)frame->size); + frame->timestamp.u32.lo, + frame->buf, + (unsigned)frame->size); } static pj_status_t open_stream( pjmedia_dir dir, - int rec_id, - int play_id, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_rec_cb rec_cb, - pjmedia_snd_play_cb play_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm) + int rec_id, + int play_id, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_rec_cb rec_cb, + pjmedia_snd_play_cb play_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm) { pj_pool_t *pool; pjmedia_snd_stream *snd_strm; @@ -111,18 +110,18 @@ static pj_status_t open_stream( pjmedia_dir dir, /* Normalize rec_id & play_id */ if (dir & PJMEDIA_DIR_CAPTURE && rec_id < 0) - rec_id = PJMEDIA_AUD_DEFAULT_CAPTURE_DEV; + rec_id = PJMEDIA_AUD_DEFAULT_CAPTURE_DEV; if (dir & PJMEDIA_DIR_PLAYBACK && play_id < 0) - play_id = PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV; + play_id = PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV; /* Initialize parameters */ if (dir & PJMEDIA_DIR_CAPTURE) { - status = pjmedia_aud_dev_default_param(rec_id, ¶m); + status = pjmedia_aud_dev_default_param(rec_id, ¶m); } else { - status = pjmedia_aud_dev_default_param(play_id, ¶m); + status = pjmedia_aud_dev_default_param(play_id, ¶m); } if (status != PJ_SUCCESS) - return status; + return status; param.dir = dir; param.rec_id = rec_id; @@ -134,17 +133,17 @@ static pj_status_t open_stream( pjmedia_dir dir, /* Latencies setting */ if ((dir & PJMEDIA_DIR_CAPTURE) && g_sys.user_rec_latency) { - param.flags |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; - param.input_latency_ms = g_sys.user_rec_latency; + param.flags |= PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY; + param.input_latency_ms = g_sys.user_rec_latency; } if ((dir & PJMEDIA_DIR_PLAYBACK) && g_sys.user_play_latency) { - param.flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; - param.output_latency_ms = g_sys.user_play_latency; + param.flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY; + param.output_latency_ms = g_sys.user_play_latency; } /* Create sound wrapper */ pool = pj_pool_create(pjmedia_get_aud_subsys()->pf, - "legacy-snd", 512, 512, NULL); + "legacy-snd", 512, 512, NULL); snd_strm = PJ_POOL_ZALLOC_T(pool, pjmedia_snd_stream); snd_strm->pool = pool; snd_strm->user_rec_cb = rec_cb; @@ -153,11 +152,11 @@ static pj_status_t open_stream( pjmedia_dir dir, /* Create the stream */ status = pjmedia_aud_stream_create(¶m, &snd_rec_cb, - &snd_play_cb, snd_strm, - &snd_strm->aud_strm); + &snd_play_cb, snd_strm, + &snd_strm->aud_strm); if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; + pj_pool_release(pool); + return status; } *p_snd_strm = snd_strm; @@ -165,50 +164,50 @@ static pj_status_t open_stream( pjmedia_dir dir, } PJ_DEF(pj_status_t) pjmedia_snd_open_rec( int index, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_rec_cb rec_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_rec_cb rec_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm) { return open_stream(PJMEDIA_DIR_CAPTURE, index, PJMEDIA_AUD_INVALID_DEV, - clock_rate, channel_count, samples_per_frame, - bits_per_sample, rec_cb, NULL, - user_data, p_snd_strm); + clock_rate, channel_count, samples_per_frame, + bits_per_sample, rec_cb, NULL, + user_data, p_snd_strm); } PJ_DEF(pj_status_t) pjmedia_snd_open_player( int index, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_play_cb play_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm ) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_play_cb play_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm ) { return open_stream(PJMEDIA_DIR_PLAYBACK, PJMEDIA_AUD_INVALID_DEV, index, - clock_rate, channel_count, samples_per_frame, - bits_per_sample, NULL, play_cb, - user_data, p_snd_strm); + clock_rate, channel_count, samples_per_frame, + bits_per_sample, NULL, play_cb, + user_data, p_snd_strm); } PJ_DEF(pj_status_t) pjmedia_snd_open( int rec_id, - int play_id, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_rec_cb rec_cb, - pjmedia_snd_play_cb play_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm) + int play_id, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_rec_cb rec_cb, + pjmedia_snd_play_cb play_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm) { return open_stream(PJMEDIA_DIR_CAPTURE_PLAYBACK, rec_id, play_id, - clock_rate, channel_count, samples_per_frame, - bits_per_sample, rec_cb, play_cb, - user_data, p_snd_strm); + clock_rate, channel_count, samples_per_frame, + bits_per_sample, rec_cb, play_cb, + user_data, p_snd_strm); } PJ_DEF(pj_status_t) pjmedia_snd_stream_start(pjmedia_snd_stream *stream) @@ -222,14 +221,14 @@ PJ_DEF(pj_status_t) pjmedia_snd_stream_stop(pjmedia_snd_stream *stream) } PJ_DEF(pj_status_t) pjmedia_snd_stream_get_info(pjmedia_snd_stream *strm, - pjmedia_snd_stream_info *pi) + pjmedia_snd_stream_info *pi) { pjmedia_aud_param param; pj_status_t status; status = pjmedia_aud_stream_get_param(strm->aud_strm, ¶m); if (status != PJ_SUCCESS) - return status; + return status; pj_bzero(pi, sizeof(*pi)); pi->dir = param.dir; @@ -241,10 +240,10 @@ PJ_DEF(pj_status_t) pjmedia_snd_stream_get_info(pjmedia_snd_stream *strm, pi->bits_per_sample = param.bits_per_sample; if (param.flags & PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY) { - pi->rec_latency = param.input_latency_ms; + pi->rec_latency = param.input_latency_ms; } if (param.flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY) { - pi->play_latency = param.output_latency_ms; + pi->play_latency = param.output_latency_ms; } return PJ_SUCCESS; @@ -257,19 +256,19 @@ PJ_DEF(pj_status_t) pjmedia_snd_stream_close(pjmedia_snd_stream *stream) status = pjmedia_aud_stream_destroy(stream->aud_strm); if (status != PJ_SUCCESS) - return status; + return status; pj_pool_release(stream->pool); return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_snd_set_latency(unsigned input_latency, - unsigned output_latency) + unsigned output_latency) { g_sys.user_rec_latency = input_latency; g_sys.user_play_latency = output_latency; return PJ_SUCCESS; } -#endif /* PJMEDIA_HAS_LEGACY_SOUND_API */ +#endif /* PJMEDIA_HAS_LEGACY_SOUND_API */ diff --git a/pjmedia/src/pjmedia/sound_port.c b/pjmedia/src/pjmedia/sound_port.c index ad5a199ae5..74c9c7d0bc 100644 --- a/pjmedia/src/pjmedia/sound_port.c +++ b/pjmedia/src/pjmedia/sound_port.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,45 +24,45 @@ #include #include #include -#include /* pj_memset() */ +#include /* pj_memset() */ -#define AEC_TAIL 128 /* default AEC length in ms */ -#define AEC_SUSPEND_LIMIT 5 /* seconds of no activity */ +#define AEC_TAIL 128 /* default AEC length in ms */ +#define AEC_SUSPEND_LIMIT 5 /* seconds of no activity */ -#define THIS_FILE "sound_port.c" +#define THIS_FILE "sound_port.c" //#define TEST_OVERFLOW_UNDERFLOW struct pjmedia_snd_port { - int rec_id; - int play_id; - pj_uint32_t aud_caps; - pjmedia_aud_param aud_param; - pjmedia_aud_stream *aud_stream; - pjmedia_dir dir; - pjmedia_port *port; + int rec_id; + int play_id; + pj_uint32_t aud_caps; + pjmedia_aud_param aud_param; + pjmedia_aud_stream *aud_stream; + pjmedia_dir dir; + pjmedia_port *port; pjmedia_clock_src cap_clocksrc, play_clocksrc; - unsigned clock_rate; - unsigned channel_count; - unsigned samples_per_frame; - unsigned bits_per_sample; - unsigned options; - unsigned prm_ec_options; + unsigned clock_rate; + unsigned channel_count; + unsigned samples_per_frame; + unsigned bits_per_sample; + unsigned options; + unsigned prm_ec_options; /* software ec */ - pjmedia_echo_state *ec_state; - unsigned ec_options; - unsigned ec_tail_len; - pj_bool_t ec_suspended; - unsigned ec_suspend_count; - unsigned ec_suspend_limit; + pjmedia_echo_state *ec_state; + unsigned ec_options; + unsigned ec_tail_len; + pj_bool_t ec_suspended; + unsigned ec_suspend_count; + unsigned ec_suspend_limit; /* audio frame preview callbacks */ - void *user_data; + void *user_data; pjmedia_aud_play_cb on_play_frame; pjmedia_aud_rec_cb on_rec_frame; }; @@ -83,31 +82,31 @@ static pj_status_t play_cb(void *user_data, pjmedia_frame *frame) port = snd_port->port; if (port == NULL) - goto no_frame; + goto no_frame; status = pjmedia_port_get_frame(port, frame); if (status != PJ_SUCCESS) - goto no_frame; + goto no_frame; if (frame->type != PJMEDIA_FRAME_TYPE_AUDIO) - goto no_frame; + goto no_frame; /* Must supply the required samples */ pj_assert(frame->size == required_size); if (snd_port->ec_state) { - if (snd_port->ec_suspended) { - snd_port->ec_suspended = PJ_FALSE; - //pjmedia_echo_state_reset(snd_port->ec_state); - PJ_LOG(4,(THIS_FILE, "EC activated")); - } - snd_port->ec_suspend_count = 0; - pjmedia_echo_playback(snd_port->ec_state, (pj_int16_t*)frame->buf); + if (snd_port->ec_suspended) { + snd_port->ec_suspended = PJ_FALSE; + //pjmedia_echo_state_reset(snd_port->ec_state); + PJ_LOG(4,(THIS_FILE, "EC activated")); + } + snd_port->ec_suspend_count = 0; + pjmedia_echo_playback(snd_port->ec_state, (pj_int16_t*)frame->buf); } /* Invoke preview callback */ if (snd_port->on_play_frame) - (*snd_port->on_play_frame)(snd_port->user_data, frame); + (*snd_port->on_play_frame)(snd_port->user_data, frame); return PJ_SUCCESS; @@ -117,20 +116,20 @@ static pj_status_t play_cb(void *user_data, pjmedia_frame *frame) pj_bzero(frame->buf, frame->size); if (snd_port->ec_state && !snd_port->ec_suspended) { - ++snd_port->ec_suspend_count; - if (snd_port->ec_suspend_count > snd_port->ec_suspend_limit) { - snd_port->ec_suspended = PJ_TRUE; - PJ_LOG(4,(THIS_FILE, "EC suspended because of inactivity")); - } - if (snd_port->ec_state) { - /* To maintain correct delay in EC */ - pjmedia_echo_playback(snd_port->ec_state, (pj_int16_t*)frame->buf); - } + ++snd_port->ec_suspend_count; + if (snd_port->ec_suspend_count > snd_port->ec_suspend_limit) { + snd_port->ec_suspended = PJ_TRUE; + PJ_LOG(4,(THIS_FILE, "EC suspended because of inactivity")); + } + if (snd_port->ec_state) { + /* To maintain correct delay in EC */ + pjmedia_echo_playback(snd_port->ec_state, (pj_int16_t*)frame->buf); + } } /* Invoke preview callback */ if (snd_port->on_play_frame) - (*snd_port->on_play_frame)(snd_port->user_data, frame); + (*snd_port->on_play_frame)(snd_port->user_data, frame); return PJ_SUCCESS; } @@ -149,15 +148,15 @@ static pj_status_t rec_cb(void *user_data, pjmedia_frame *frame) /* Invoke preview callback */ if (snd_port->on_rec_frame) - (*snd_port->on_rec_frame)(snd_port->user_data, frame); + (*snd_port->on_rec_frame)(snd_port->user_data, frame); port = snd_port->port; if (port == NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Cancel echo */ if (snd_port->ec_state && !snd_port->ec_suspended) { - pjmedia_echo_capture(snd_port->ec_state, (pj_int16_t*) frame->buf, 0); + pjmedia_echo_capture(snd_port->ec_state, (pj_int16_t*) frame->buf, 0); } pjmedia_port_put_frame(port, frame); @@ -176,15 +175,15 @@ static pj_status_t play_cb_ext(void *user_data, pjmedia_frame *frame) pjmedia_port *port = snd_port->port; if (port == NULL) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; + frame->type = PJMEDIA_FRAME_TYPE_NONE; + return PJ_SUCCESS; } pjmedia_port_get_frame(port, frame); /* Invoke preview callback */ if (snd_port->on_play_frame) - (*snd_port->on_play_frame)(snd_port->user_data, frame); + (*snd_port->on_play_frame)(snd_port->user_data, frame); return PJ_SUCCESS; } @@ -201,11 +200,11 @@ static pj_status_t rec_cb_ext(void *user_data, pjmedia_frame *frame) /* Invoke preview callback */ if (snd_port->on_rec_frame) - (*snd_port->on_rec_frame)(snd_port->user_data, frame); + (*snd_port->on_rec_frame)(snd_port->user_data, frame); port = snd_port->port; if (port == NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; pjmedia_port_put_frame(port, frame); @@ -223,7 +222,7 @@ PJ_DEF(void) pjmedia_snd_port_param_default(pjmedia_snd_port_param *prm) * This may be called even when the sound stream has already been started. */ static pj_status_t start_sound_device( pj_pool_t *pool, - pjmedia_snd_port *snd_port ) + pjmedia_snd_port *snd_port ) { pjmedia_aud_rec_cb snd_rec_cb; pjmedia_aud_play_cb snd_play_cb; @@ -232,107 +231,107 @@ static pj_status_t start_sound_device( pj_pool_t *pool, /* Check if sound has been started. */ if (snd_port->aud_stream != NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; PJ_ASSERT_RETURN(snd_port->dir == PJMEDIA_DIR_CAPTURE || - snd_port->dir == PJMEDIA_DIR_PLAYBACK || - snd_port->dir == PJMEDIA_DIR_CAPTURE_PLAYBACK, - PJ_EBUG); + snd_port->dir == PJMEDIA_DIR_PLAYBACK || + snd_port->dir == PJMEDIA_DIR_CAPTURE_PLAYBACK, + PJ_EBUG); /* Get device caps */ if ((snd_port->aud_param.dir & PJMEDIA_DIR_CAPTURE) || (snd_port->aud_param.dir & PJMEDIA_DIR_PLAYBACK)) { - pjmedia_aud_dev_info dev_info; + pjmedia_aud_dev_info dev_info; pjmedia_aud_dev_index dev_id = (snd_port->aud_param.dir & PJMEDIA_DIR_CAPTURE) ? snd_port->aud_param.rec_id : snd_port->aud_param.play_id; - status = pjmedia_aud_dev_get_info(dev_id, &dev_info); - if (status != PJ_SUCCESS) - return status; + status = pjmedia_aud_dev_get_info(dev_id, &dev_info); + if (status != PJ_SUCCESS) + return status; - snd_port->aud_caps = dev_info.caps; + snd_port->aud_caps = dev_info.caps; } /* Process EC settings */ pj_memcpy(¶m_copy, &snd_port->aud_param, sizeof(param_copy)); if (param_copy.flags & PJMEDIA_AUD_DEV_CAP_EC) { - /* EC is wanted */ - if ((snd_port->prm_ec_options & PJMEDIA_ECHO_USE_SW_ECHO) == 0 && + /* EC is wanted */ + if ((snd_port->prm_ec_options & PJMEDIA_ECHO_USE_SW_ECHO) == 0 && (snd_port->aud_caps & PJMEDIA_AUD_DEV_CAP_EC)) { - /* Device supports EC */ - /* Nothing to do */ - } else { - /* Application wants to use software EC or device + /* Device supports EC */ + /* Nothing to do */ + } else { + /* Application wants to use software EC or device * doesn't support EC, remove EC settings from - * device parameters - */ - param_copy.flags &= ~(PJMEDIA_AUD_DEV_CAP_EC | - PJMEDIA_AUD_DEV_CAP_EC_TAIL); - } + * device parameters + */ + param_copy.flags &= ~(PJMEDIA_AUD_DEV_CAP_EC | + PJMEDIA_AUD_DEV_CAP_EC_TAIL); + } } /* Use different callback if format is not PCM */ if (snd_port->aud_param.ext_fmt.id == PJMEDIA_FORMAT_L16) { - snd_rec_cb = &rec_cb; - snd_play_cb = &play_cb; + snd_rec_cb = &rec_cb; + snd_play_cb = &play_cb; } else { - snd_rec_cb = &rec_cb_ext; - snd_play_cb = &play_cb_ext; + snd_rec_cb = &rec_cb_ext; + snd_play_cb = &play_cb_ext; } /* Open the device */ status = pjmedia_aud_stream_create(¶m_copy, - snd_rec_cb, - snd_play_cb, - snd_port, - &snd_port->aud_stream); + snd_rec_cb, + snd_play_cb, + snd_port, + &snd_port->aud_stream); if (status != PJ_SUCCESS) - return status; + return status; /* Inactivity limit before EC is suspended. */ snd_port->ec_suspend_limit = AEC_SUSPEND_LIMIT * - (snd_port->clock_rate / - snd_port->samples_per_frame); + (snd_port->clock_rate / + snd_port->samples_per_frame); /* Create software EC if parameter specifies EC and * (app specifically requests software EC or device * doesn't support EC). Only do this if the format is PCM! */ if ((snd_port->aud_param.flags & PJMEDIA_AUD_DEV_CAP_EC) && - ((snd_port->aud_caps & PJMEDIA_AUD_DEV_CAP_EC)==0 || + ((snd_port->aud_caps & PJMEDIA_AUD_DEV_CAP_EC)==0 || (snd_port->prm_ec_options & PJMEDIA_ECHO_USE_SW_ECHO) != 0) && - param_copy.ext_fmt.id == PJMEDIA_FORMAT_PCM) + param_copy.ext_fmt.id == PJMEDIA_FORMAT_PCM) { - if ((snd_port->aud_param.flags & PJMEDIA_AUD_DEV_CAP_EC_TAIL)==0) { - snd_port->aud_param.flags |= PJMEDIA_AUD_DEV_CAP_EC_TAIL; - snd_port->aud_param.ec_tail_ms = AEC_TAIL; - PJ_LOG(4,(THIS_FILE, "AEC tail is set to default %u ms", - snd_port->aud_param.ec_tail_ms)); - } - - status = pjmedia_snd_port_set_ec(snd_port, pool, - snd_port->aud_param.ec_tail_ms, - snd_port->prm_ec_options); - if (status != PJ_SUCCESS) { - pjmedia_aud_stream_destroy(snd_port->aud_stream); - snd_port->aud_stream = NULL; - return status; - } + if ((snd_port->aud_param.flags & PJMEDIA_AUD_DEV_CAP_EC_TAIL)==0) { + snd_port->aud_param.flags |= PJMEDIA_AUD_DEV_CAP_EC_TAIL; + snd_port->aud_param.ec_tail_ms = AEC_TAIL; + PJ_LOG(4,(THIS_FILE, "AEC tail is set to default %u ms", + snd_port->aud_param.ec_tail_ms)); + } + + status = pjmedia_snd_port_set_ec(snd_port, pool, + snd_port->aud_param.ec_tail_ms, + snd_port->prm_ec_options); + if (status != PJ_SUCCESS) { + pjmedia_aud_stream_destroy(snd_port->aud_stream); + snd_port->aud_stream = NULL; + return status; + } } /* Start sound stream. */ if (!(snd_port->options & PJMEDIA_SND_PORT_NO_AUTO_START)) { - status = pjmedia_aud_stream_start(snd_port->aud_stream); + status = pjmedia_aud_stream_start(snd_port->aud_stream); } if (status != PJ_SUCCESS) { - pjmedia_aud_stream_destroy(snd_port->aud_stream); - snd_port->aud_stream = NULL; - return status; + pjmedia_aud_stream_destroy(snd_port->aud_stream); + snd_port->aud_stream = NULL; + return status; } return PJ_SUCCESS; @@ -347,15 +346,15 @@ static pj_status_t stop_sound_device( pjmedia_snd_port *snd_port ) { /* Check if we have sound stream device. */ if (snd_port->aud_stream) { - pjmedia_aud_stream_stop(snd_port->aud_stream); - pjmedia_aud_stream_destroy(snd_port->aud_stream); - snd_port->aud_stream = NULL; + pjmedia_aud_stream_stop(snd_port->aud_stream); + pjmedia_aud_stream_destroy(snd_port->aud_stream); + snd_port->aud_stream = NULL; } /* Destroy AEC */ if (snd_port->ec_state) { - pjmedia_echo_destroy(snd_port->ec_state); - snd_port->ec_state = NULL; + pjmedia_echo_destroy(snd_port->ec_state); + snd_port->ec_state = NULL; } return PJ_SUCCESS; @@ -366,14 +365,14 @@ static pj_status_t stop_sound_device( pjmedia_snd_port *snd_port ) * Create bidirectional port. */ PJ_DEF(pj_status_t) pjmedia_snd_port_create( pj_pool_t *pool, - int rec_id, - int play_id, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_snd_port **p_port) + int rec_id, + int play_id, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_snd_port **p_port) { pjmedia_snd_port_param param; pj_status_t status; @@ -382,13 +381,13 @@ PJ_DEF(pj_status_t) pjmedia_snd_port_create( pj_pool_t *pool, /* Normalize rec_id & play_id */ if (rec_id < 0) - rec_id = PJMEDIA_AUD_DEFAULT_CAPTURE_DEV; + rec_id = PJMEDIA_AUD_DEFAULT_CAPTURE_DEV; if (play_id < 0) - play_id = PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV; + play_id = PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV; status = pjmedia_aud_dev_default_param(rec_id, ¶m.base); if (status != PJ_SUCCESS) - return status; + return status; param.base.dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; param.base.rec_id = rec_id; @@ -407,13 +406,13 @@ PJ_DEF(pj_status_t) pjmedia_snd_port_create( pj_pool_t *pool, * Create sound recorder AEC. */ PJ_DEF(pj_status_t) pjmedia_snd_port_create_rec( pj_pool_t *pool, - int dev_id, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_snd_port **p_port) + int dev_id, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_snd_port **p_port) { pjmedia_snd_port_param param; pj_status_t status; @@ -422,11 +421,11 @@ PJ_DEF(pj_status_t) pjmedia_snd_port_create_rec( pj_pool_t *pool, /* Normalize dev_id */ if (dev_id < 0) - dev_id = PJMEDIA_AUD_DEFAULT_CAPTURE_DEV; + dev_id = PJMEDIA_AUD_DEFAULT_CAPTURE_DEV; status = pjmedia_aud_dev_default_param(dev_id, ¶m.base); if (status != PJ_SUCCESS) - return status; + return status; param.base.dir = PJMEDIA_DIR_CAPTURE; param.base.rec_id = dev_id; @@ -445,13 +444,13 @@ PJ_DEF(pj_status_t) pjmedia_snd_port_create_rec( pj_pool_t *pool, * Create sound player port. */ PJ_DEF(pj_status_t) pjmedia_snd_port_create_player( pj_pool_t *pool, - int dev_id, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_snd_port **p_port) + int dev_id, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_snd_port **p_port) { pjmedia_snd_port_param param; pj_status_t status; @@ -460,11 +459,11 @@ PJ_DEF(pj_status_t) pjmedia_snd_port_create_player( pj_pool_t *pool, /* Normalize dev_id */ if (dev_id < 0) - dev_id = PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV; + dev_id = PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV; status = pjmedia_aud_dev_default_param(dev_id, ¶m.base); if (status != PJ_SUCCESS) - return status; + return status; param.base.dir = PJMEDIA_DIR_PLAYBACK; param.base.play_id = dev_id; @@ -483,8 +482,8 @@ PJ_DEF(pj_status_t) pjmedia_snd_port_create_player( pj_pool_t *pool, * Create sound port. */ PJ_DEF(pj_status_t) pjmedia_snd_port_create2(pj_pool_t *pool, - const pjmedia_snd_port_param *prm, - pjmedia_snd_port **p_port) + const pjmedia_snd_port_param *prm, + pjmedia_snd_port **p_port) { pjmedia_snd_port *snd_port; pj_status_t status; @@ -522,8 +521,8 @@ PJ_DEF(pj_status_t) pjmedia_snd_port_create2(pj_pool_t *pool, */ status = start_sound_device( pool, snd_port ); if (status != PJ_SUCCESS) { - pjmedia_snd_port_destroy(snd_port); - return status; + pjmedia_snd_port_destroy(snd_port); + return status; } *p_port = snd_port; @@ -546,7 +545,7 @@ PJ_DEF(pj_status_t) pjmedia_snd_port_destroy(pjmedia_snd_port *snd_port) * Retrieve the sound stream associated by this sound device port. */ PJ_DEF(pjmedia_aud_stream*) pjmedia_snd_port_get_snd_stream( - pjmedia_snd_port *snd_port) + pjmedia_snd_port *snd_port) { PJ_ASSERT_RETURN(snd_port, NULL); return snd_port->aud_stream; @@ -557,9 +556,9 @@ PJ_DEF(pjmedia_aud_stream*) pjmedia_snd_port_get_snd_stream( * Change EC settings. */ PJ_DEF(pj_status_t) pjmedia_snd_port_set_ec( pjmedia_snd_port *snd_port, - pj_pool_t *pool, - unsigned tail_ms, - unsigned options) + pj_pool_t *pool, + unsigned tail_ms, + unsigned options) { pjmedia_aud_param prm; pj_status_t status; @@ -572,102 +571,102 @@ PJ_DEF(pj_status_t) pjmedia_snd_port_set_ec( pjmedia_snd_port *snd_port, if ((snd_port->prm_ec_options & PJMEDIA_ECHO_USE_SW_ECHO) == 0 && (snd_port->aud_caps & PJMEDIA_AUD_DEV_CAP_EC)) { - /* We use device EC */ - pj_bool_t ec_enabled; - - /* Query EC status */ - status = pjmedia_aud_stream_get_cap(snd_port->aud_stream, - PJMEDIA_AUD_DEV_CAP_EC, - &ec_enabled); - if (status != PJ_SUCCESS) - return status; - - if (tail_ms != 0) { - /* Change EC setting */ - - if (!ec_enabled) { - /* Enable EC first */ - pj_bool_t value = PJ_TRUE; - status = pjmedia_aud_stream_set_cap(snd_port->aud_stream, - PJMEDIA_AUD_DEV_CAP_EC, - &value); - if (status != PJ_SUCCESS) - return status; - } - - if ((snd_port->aud_caps & PJMEDIA_AUD_DEV_CAP_EC_TAIL)==0) { - /* Device does not support setting EC tail */ - return PJMEDIA_EAUD_INVCAP; - } - - return pjmedia_aud_stream_set_cap(snd_port->aud_stream, - PJMEDIA_AUD_DEV_CAP_EC_TAIL, - &tail_ms); - - } else if (ec_enabled) { - /* Disable EC */ - pj_bool_t value = PJ_FALSE; - return pjmedia_aud_stream_set_cap(snd_port->aud_stream, - PJMEDIA_AUD_DEV_CAP_EC, - &value); - } else { - /* Request to disable EC but EC has been disabled */ - /* Do nothing */ - return PJ_SUCCESS; - } + /* We use device EC */ + pj_bool_t ec_enabled; + + /* Query EC status */ + status = pjmedia_aud_stream_get_cap(snd_port->aud_stream, + PJMEDIA_AUD_DEV_CAP_EC, + &ec_enabled); + if (status != PJ_SUCCESS) + return status; + + if (tail_ms != 0) { + /* Change EC setting */ + + if (!ec_enabled) { + /* Enable EC first */ + pj_bool_t value = PJ_TRUE; + status = pjmedia_aud_stream_set_cap(snd_port->aud_stream, + PJMEDIA_AUD_DEV_CAP_EC, + &value); + if (status != PJ_SUCCESS) + return status; + } + + if ((snd_port->aud_caps & PJMEDIA_AUD_DEV_CAP_EC_TAIL)==0) { + /* Device does not support setting EC tail */ + return PJMEDIA_EAUD_INVCAP; + } + + return pjmedia_aud_stream_set_cap(snd_port->aud_stream, + PJMEDIA_AUD_DEV_CAP_EC_TAIL, + &tail_ms); + + } else if (ec_enabled) { + /* Disable EC */ + pj_bool_t value = PJ_FALSE; + return pjmedia_aud_stream_set_cap(snd_port->aud_stream, + PJMEDIA_AUD_DEV_CAP_EC, + &value); + } else { + /* Request to disable EC but EC has been disabled */ + /* Do nothing */ + return PJ_SUCCESS; + } } else { - /* We use software EC */ - - /* Check if there is change in parameters */ - if (tail_ms==snd_port->ec_tail_len && options==snd_port->ec_options) { - PJ_LOG(5,(THIS_FILE, "pjmedia_snd_port_set_ec() ignored, no " - "change in settings")); - return PJ_SUCCESS; - } - - status = pjmedia_aud_stream_get_param(snd_port->aud_stream, &prm); - if (status != PJ_SUCCESS) - return status; - - /* Audio stream must be in PCM format */ - PJ_ASSERT_RETURN(prm.ext_fmt.id == PJMEDIA_FORMAT_PCM, - PJ_EINVALIDOP); - - /* Destroy AEC */ - if (snd_port->ec_state) { - pjmedia_echo_destroy(snd_port->ec_state); - snd_port->ec_state = NULL; - } - - if (tail_ms != 0) { - unsigned delay_ms; - - //No need to add input latency in the latency calculation, - //since actual input latency should be zero. - //delay_ms = (si.rec_latency + si.play_latency) * 1000 / - // snd_port->clock_rate; - /* Set EC latency to 3/4 of output latency to reduce the - * possibility of missing/late reference frame. - */ - delay_ms = prm.output_latency_ms * 3/4; - status = pjmedia_echo_create2(pool, snd_port->clock_rate, - snd_port->channel_count, - snd_port->samples_per_frame, - tail_ms, delay_ms, - options, &snd_port->ec_state); - if (status != PJ_SUCCESS) - snd_port->ec_state = NULL; - else - snd_port->ec_suspended = PJ_FALSE; - } else { - PJ_LOG(4,(THIS_FILE, "Echo canceller is now disabled in the " - "sound port")); - status = PJ_SUCCESS; - } - - snd_port->ec_options = options; - snd_port->ec_tail_len = tail_ms; + /* We use software EC */ + + /* Check if there is change in parameters */ + if (tail_ms==snd_port->ec_tail_len && options==snd_port->ec_options) { + PJ_LOG(5,(THIS_FILE, "pjmedia_snd_port_set_ec() ignored, no " + "change in settings")); + return PJ_SUCCESS; + } + + status = pjmedia_aud_stream_get_param(snd_port->aud_stream, &prm); + if (status != PJ_SUCCESS) + return status; + + /* Audio stream must be in PCM format */ + PJ_ASSERT_RETURN(prm.ext_fmt.id == PJMEDIA_FORMAT_PCM, + PJ_EINVALIDOP); + + /* Destroy AEC */ + if (snd_port->ec_state) { + pjmedia_echo_destroy(snd_port->ec_state); + snd_port->ec_state = NULL; + } + + if (tail_ms != 0) { + unsigned delay_ms; + + //No need to add input latency in the latency calculation, + //since actual input latency should be zero. + //delay_ms = (si.rec_latency + si.play_latency) * 1000 / + // snd_port->clock_rate; + /* Set EC latency to 3/4 of output latency to reduce the + * possibility of missing/late reference frame. + */ + delay_ms = prm.output_latency_ms * 3/4; + status = pjmedia_echo_create2(pool, snd_port->clock_rate, + snd_port->channel_count, + snd_port->samples_per_frame, + tail_ms, delay_ms, + options, &snd_port->ec_state); + if (status != PJ_SUCCESS) + snd_port->ec_state = NULL; + else + snd_port->ec_suspended = PJ_FALSE; + } else { + PJ_LOG(4,(THIS_FILE, "Echo canceller is now disabled in the " + "sound port")); + status = PJ_SUCCESS; + } + + snd_port->ec_options = options; + snd_port->ec_tail_len = tail_ms; } return status; @@ -676,40 +675,40 @@ PJ_DEF(pj_status_t) pjmedia_snd_port_set_ec( pjmedia_snd_port *snd_port, /* Get AEC tail length */ PJ_DEF(pj_status_t) pjmedia_snd_port_get_ec_tail( pjmedia_snd_port *snd_port, - unsigned *p_length) + unsigned *p_length) { PJ_ASSERT_RETURN(snd_port && p_length, PJ_EINVAL); /* Determine whether we use device or software EC */ if (snd_port->aud_caps & PJMEDIA_AUD_DEV_CAP_EC) { - /* We use device EC */ - pj_bool_t ec_enabled; - pj_status_t status; - - /* Query EC status */ - status = pjmedia_aud_stream_get_cap(snd_port->aud_stream, - PJMEDIA_AUD_DEV_CAP_EC, - &ec_enabled); - if (status != PJ_SUCCESS) - return status; - - if (!ec_enabled) { - *p_length = 0; - } else if (snd_port->aud_caps & PJMEDIA_AUD_DEV_CAP_EC_TAIL) { - /* Get device EC tail */ - status = pjmedia_aud_stream_get_cap(snd_port->aud_stream, - PJMEDIA_AUD_DEV_CAP_EC_TAIL, - p_length); - if (status != PJ_SUCCESS) - return status; - } else { - /* Just use default */ - *p_length = AEC_TAIL; - } + /* We use device EC */ + pj_bool_t ec_enabled; + pj_status_t status; + + /* Query EC status */ + status = pjmedia_aud_stream_get_cap(snd_port->aud_stream, + PJMEDIA_AUD_DEV_CAP_EC, + &ec_enabled); + if (status != PJ_SUCCESS) + return status; + + if (!ec_enabled) { + *p_length = 0; + } else if (snd_port->aud_caps & PJMEDIA_AUD_DEV_CAP_EC_TAIL) { + /* Get device EC tail */ + status = pjmedia_aud_stream_get_cap(snd_port->aud_stream, + PJMEDIA_AUD_DEV_CAP_EC_TAIL, + p_length); + if (status != PJ_SUCCESS) + return status; + } else { + /* Just use default */ + *p_length = AEC_TAIL; + } } else { - /* We use software EC */ - *p_length = snd_port->ec_state ? snd_port->ec_tail_len : 0; + /* We use software EC */ + *p_length = snd_port->ec_state ? snd_port->ec_tail_len : 0; } return PJ_SUCCESS; } @@ -719,18 +718,18 @@ PJ_DEF(pj_status_t) pjmedia_snd_port_get_ec_tail( pjmedia_snd_port *snd_port, * Get echo canceller statistics. */ PJ_DEF(pj_status_t) pjmedia_snd_port_get_ec_stat( pjmedia_snd_port *snd_port, - pjmedia_echo_stat *p_stat) + pjmedia_echo_stat *p_stat) { PJ_ASSERT_RETURN(snd_port && p_stat, PJ_EINVAL); if (snd_port->ec_state) { - return pjmedia_echo_get_stat(snd_port->ec_state, p_stat); + return pjmedia_echo_get_stat(snd_port->ec_state, p_stat); } else { - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; } } - + /* * Get clock source. */ @@ -747,7 +746,7 @@ pjmedia_snd_port_get_clock_src( pjmedia_snd_port *snd_port, * Connect a port. */ PJ_DEF(pj_status_t) pjmedia_snd_port_connect( pjmedia_snd_port *snd_port, - pjmedia_port *port) + pjmedia_port *port) { pjmedia_audio_format_detail *afd; @@ -759,16 +758,16 @@ PJ_DEF(pj_status_t) pjmedia_snd_port_connect( pjmedia_snd_port *snd_port, * port. */ if (afd->clock_rate != snd_port->clock_rate) - return PJMEDIA_ENCCLOCKRATE; + return PJMEDIA_ENCCLOCKRATE; if (PJMEDIA_AFD_SPF(afd) != snd_port->samples_per_frame) - return PJMEDIA_ENCSAMPLESPFRAME; + return PJMEDIA_ENCSAMPLESPFRAME; if (afd->channel_count != snd_port->channel_count) - return PJMEDIA_ENCCHANNEL; + return PJMEDIA_ENCCHANNEL; if (afd->bits_per_sample != snd_port->bits_per_sample) - return PJMEDIA_ENCBITS; + return PJMEDIA_ENCBITS; /* Port is okay. */ snd_port->port = port; diff --git a/pjmedia/src/pjmedia/splitcomb.c b/pjmedia/src/pjmedia/splitcomb.c index ef9a07e8c8..fd03ec94d5 100644 --- a/pjmedia/src/pjmedia/splitcomb.c +++ b/pjmedia/src/pjmedia/splitcomb.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,29 +24,29 @@ #include -#define SIGNATURE PJMEDIA_SIG_PORT_SPLIT_COMB -#define SIGNATURE_PORT PJMEDIA_SIG_PORT_SPLIT_COMB_P -#define THIS_FILE "splitcomb.c" -#define TMP_SAMP_TYPE pj_int16_t +#define SIGNATURE PJMEDIA_SIG_PORT_SPLIT_COMB +#define SIGNATURE_PORT PJMEDIA_SIG_PORT_SPLIT_COMB_P +#define THIS_FILE "splitcomb.c" +#define TMP_SAMP_TYPE pj_int16_t /* Maximum number of channels. */ -#define MAX_CHANNELS 16 +#define MAX_CHANNELS 16 /* Maximum number of buffers to be accommodated by delaybuf */ -#define MAX_BUF_CNT PJMEDIA_SOUND_BUFFER_COUNT +#define MAX_BUF_CNT PJMEDIA_SOUND_BUFFER_COUNT /* Maximum number of burst before we pause the media flow */ -#define MAX_BURST (buf_cnt + 6) +#define MAX_BURST (buf_cnt + 6) /* Maximum number of NULL frames received before we pause the * media flow. */ -#define MAX_NULL_FRAMES (rport->max_burst) +#define MAX_NULL_FRAMES (rport->max_burst) /* Operations */ -#define OP_PUT (1) -#define OP_GET (-1) +#define OP_PUT (1) +#define OP_GET (-1) /* @@ -85,12 +84,12 @@ struct splitcomb { pjmedia_port base; - unsigned options; + unsigned options; /* Array of ports, one for each channel */ struct { - pjmedia_port *port; - pj_bool_t reversed; + pjmedia_port *port; + pj_bool_t reversed; } port_desc[MAX_CHANNELS]; /* Temporary buffers needed to extract mono frame from @@ -109,7 +108,7 @@ struct reverse_port { pjmedia_port base; struct splitcomb*parent; - unsigned ch_num; + unsigned ch_num; /* Maximum burst before media flow is suspended. * With reverse port, it's possible that either end of the @@ -123,7 +122,7 @@ struct reverse_port * be suspended once underflow/overflow goes over this max_burst * limit. */ - int max_burst; + int max_burst; /* When the media interface port of the splitcomb or the reverse * channel port is registered to conference bridge, the bridge @@ -139,7 +138,7 @@ struct reverse_port * This value controls how many NULL frames can be received * before we suspend media flow for a particular direction. */ - unsigned max_null_frames; + unsigned max_null_frames; /* A reverse port need a temporary buffer to store frames * (because of the different phase, see splitcomb.h for details). @@ -152,36 +151,36 @@ struct reverse_port */ struct { - /* The delay buffer where frames will be stored */ - pjmedia_delay_buf *dbuf; + /* The delay buffer where frames will be stored */ + pjmedia_delay_buf *dbuf; - /* Flag to indicate that audio flow on this direction - * is currently being suspended (perhaps because nothing - * is processing the frame on the other end). - */ - pj_bool_t paused; + /* Flag to indicate that audio flow on this direction + * is currently being suspended (perhaps because nothing + * is processing the frame on the other end). + */ + pj_bool_t paused; - /* Operation level. When the level exceeds a maximum value, - * the media flow on this direction will be paused. - */ - int level; + /* Operation level. When the level exceeds a maximum value, + * the media flow on this direction will be paused. + */ + int level; - /* Timestamp. */ - pj_timestamp ts; + /* Timestamp. */ + pj_timestamp ts; - /* Number of NULL frames transmitted to this port so far. - * NULL frame indicate that nothing is transmitted, and - * once we get too many of this, we should pause the media - * flow to reduce processing. - */ - unsigned null_cnt; + /* Number of NULL frames transmitted to this port so far. + * NULL frame indicate that nothing is transmitted, and + * once we get too many of this, we should pause the media + * flow to reduce processing. + */ + unsigned null_cnt; } buf[2]; /* Must have temporary put buffer for the delay buf, * unfortunately. */ - pj_int16_t *tmp_up_buf; + pj_int16_t *tmp_up_buf; }; @@ -189,15 +188,15 @@ struct reverse_port * Prototypes. */ static pj_status_t put_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t get_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t on_destroy(pjmedia_port *this_port); static pj_status_t rport_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t rport_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t rport_on_destroy(pjmedia_port *this_port); @@ -205,20 +204,20 @@ static pj_status_t rport_on_destroy(pjmedia_port *this_port); * Create the splitter/combiner. */ PJ_DEF(pj_status_t) pjmedia_splitcomb_create( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_port **p_splitcomb) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_port **p_splitcomb) { const pj_str_t name = pj_str("splitcomb"); struct splitcomb *sc; /* Sanity check */ PJ_ASSERT_RETURN(pool && clock_rate && channel_count && - samples_per_frame && bits_per_sample && - p_splitcomb, PJ_EINVAL); + samples_per_frame && bits_per_sample && + p_splitcomb, PJ_EINVAL); /* Only supports 16 bits per sample */ PJ_ASSERT_RETURN(bits_per_sample == 16, PJ_EINVAL); @@ -231,15 +230,15 @@ PJ_DEF(pj_status_t) pjmedia_splitcomb_create( pj_pool_t *pool, /* Create temporary buffers */ sc->get_buf = (TMP_SAMP_TYPE*) - pj_pool_alloc(pool, samples_per_frame * - sizeof(TMP_SAMP_TYPE) / - channel_count); + pj_pool_alloc(pool, samples_per_frame * + sizeof(TMP_SAMP_TYPE) / + channel_count); PJ_ASSERT_RETURN(sc->get_buf, PJ_ENOMEM); sc->put_buf = (TMP_SAMP_TYPE*) - pj_pool_alloc(pool, samples_per_frame * - sizeof(TMP_SAMP_TYPE) / - channel_count); + pj_pool_alloc(pool, samples_per_frame * + sizeof(TMP_SAMP_TYPE) / + channel_count); PJ_ASSERT_RETURN(sc->put_buf, PJ_ENOMEM); @@ -248,7 +247,7 @@ PJ_DEF(pj_status_t) pjmedia_splitcomb_create( pj_pool_t *pool, /* Initialize port */ pjmedia_port_info_init(&sc->base.info, &name, SIGNATURE, clock_rate, - channel_count, bits_per_sample, samples_per_frame); + channel_count, bits_per_sample, samples_per_frame); sc->base.put_frame = &put_frame; sc->base.get_frame = &get_frame; @@ -271,9 +270,9 @@ PJ_DEF(pj_status_t) pjmedia_splitcomb_create( pj_pool_t *pool, * Attach media port with the same phase as the splitter/combiner. */ PJ_DEF(pj_status_t) pjmedia_splitcomb_set_channel( pjmedia_port *splitcomb, - unsigned ch_num, - unsigned options, - pjmedia_port *port) + unsigned ch_num, + unsigned options, + pjmedia_port *port) { struct splitcomb *sc = (struct splitcomb*) splitcomb; @@ -300,10 +299,10 @@ PJ_DEF(pj_status_t) pjmedia_splitcomb_set_channel( pjmedia_port *splitcomb, * Create reverse phase port for the specified channel. */ PJ_DEF(pj_status_t) pjmedia_splitcomb_create_rev_channel( pj_pool_t *pool, - pjmedia_port *splitcomb, - unsigned ch_num, - unsigned options, - pjmedia_port **p_chport) + pjmedia_port *splitcomb, + unsigned ch_num, + unsigned options, + pjmedia_port **p_chport) { const pj_str_t name = pj_str("scomb-rev"); struct splitcomb *sc = (struct splitcomb*) splitcomb; @@ -336,10 +335,10 @@ PJ_DEF(pj_status_t) pjmedia_splitcomb_create_rev_channel( pj_pool_t *pool, /* Initialize port info... */ port = &rport->base; pjmedia_port_info_init(&port->info, &name, SIGNATURE_PORT, - sc_afd->clock_rate, 1, - sc_afd->bits_per_sample, - PJMEDIA_PIA_SPF(&splitcomb->info) / - sc_afd->channel_count); + sc_afd->clock_rate, 1, + sc_afd->bits_per_sample, + PJMEDIA_PIA_SPF(&splitcomb->info) / + sc_afd->channel_count); p_afd = pjmedia_format_get_audio_format_detail(&port->info.fmt, 1); @@ -351,7 +350,7 @@ PJ_DEF(pj_status_t) pjmedia_splitcomb_create_rev_channel( pj_pool_t *pool, /* Buffer settings */ buf_cnt = options & 0xFF; if (buf_cnt == 0) - buf_cnt = MAX_BUF_CNT; + buf_cnt = MAX_BUF_CNT; /* Buffer options */ buf_options = (options >> 8U) & 0xFF; @@ -361,33 +360,33 @@ PJ_DEF(pj_status_t) pjmedia_splitcomb_create_rev_channel( pj_pool_t *pool, /* Create downstream/put buffers */ status = pjmedia_delay_buf_create(pool, "scombdb-dn", - p_afd->clock_rate, - PJMEDIA_PIA_SPF(&port->info), - p_afd->channel_count, - buf_cnt * p_afd->frame_time_usec / 1000, - buf_options, - &rport->buf[DIR_DOWNSTREAM].dbuf); + p_afd->clock_rate, + PJMEDIA_PIA_SPF(&port->info), + p_afd->channel_count, + buf_cnt * p_afd->frame_time_usec / 1000, + buf_options, + &rport->buf[DIR_DOWNSTREAM].dbuf); if (status != PJ_SUCCESS) { - return status; + return status; } /* Create upstream/get buffers */ status = pjmedia_delay_buf_create(pool, "scombdb-up", - p_afd->clock_rate, - PJMEDIA_PIA_SPF(&port->info), - p_afd->channel_count, - buf_cnt * p_afd->frame_time_usec / 1000, - buf_options, - &rport->buf[DIR_UPSTREAM].dbuf); + p_afd->clock_rate, + PJMEDIA_PIA_SPF(&port->info), + p_afd->channel_count, + buf_cnt * p_afd->frame_time_usec / 1000, + buf_options, + &rport->buf[DIR_UPSTREAM].dbuf); if (status != PJ_SUCCESS) { - pjmedia_delay_buf_destroy(rport->buf[DIR_DOWNSTREAM].dbuf); - return status; + pjmedia_delay_buf_destroy(rport->buf[DIR_DOWNSTREAM].dbuf); + return status; } /* And temporary upstream/get buffer */ rport->tmp_up_buf = (pj_int16_t*) - pj_pool_alloc(pool, - PJMEDIA_PIA_AVG_FSZ(&port->info)); + pj_pool_alloc(pool, + PJMEDIA_PIA_AVG_FSZ(&port->info)); /* Save port in the splitcomb */ sc->port_desc[ch_num].port = &rport->base; @@ -404,17 +403,17 @@ PJ_DEF(pj_status_t) pjmedia_splitcomb_create_rev_channel( pj_pool_t *pool, * Extract one mono frame from a multichannel frame. */ static void extract_mono_frame( const pj_int16_t *in, - pj_int16_t *out, - unsigned ch, - unsigned ch_cnt, - unsigned samples_count) + pj_int16_t *out, + unsigned ch, + unsigned ch_cnt, + unsigned samples_count) { unsigned i; in += ch; for (i=0; ibuf[dir].level += op; if (op == OP_PUT) { - rport->buf[dir].ts.u64 += PJMEDIA_PIA_SPF(&rport->base.info); + rport->buf[dir].ts.u64 += PJMEDIA_PIA_SPF(&rport->base.info); } if (rport->buf[dir].paused) { - if (rport->buf[dir].level < -rport->max_burst) { - /* Prevent the level from overflowing and resets back to zero */ - rport->buf[dir].level = -rport->max_burst; - } else if (rport->buf[dir].level > rport->max_burst) { - /* Prevent the level from overflowing and resets back to zero */ - rport->buf[dir].level = rport->max_burst; - } else { - /* Level has fallen below max level, we can resume - * media flow. - */ - PJ_LOG(5,(rport->base.info.name.ptr, - "Resuming media flow on %s direction (level=%d)", - dir_name[dir], rport->buf[dir].level)); - rport->buf[dir].level = 0; - rport->buf[dir].paused = PJ_FALSE; - - //This will cause disruption in audio, and it seems to be - //working fine without this anyway, so we disable it for now. - //pjmedia_delay_buf_learn(rport->buf[dir].dbuf); - - } + if (rport->buf[dir].level < -rport->max_burst) { + /* Prevent the level from overflowing and resets back to zero */ + rport->buf[dir].level = -rport->max_burst; + } else if (rport->buf[dir].level > rport->max_burst) { + /* Prevent the level from overflowing and resets back to zero */ + rport->buf[dir].level = rport->max_burst; + } else { + /* Level has fallen below max level, we can resume + * media flow. + */ + PJ_LOG(5,(rport->base.info.name.ptr, + "Resuming media flow on %s direction (level=%d)", + dir_name[dir], rport->buf[dir].level)); + rport->buf[dir].level = 0; + rport->buf[dir].paused = PJ_FALSE; + + //This will cause disruption in audio, and it seems to be + //working fine without this anyway, so we disable it for now. + //pjmedia_delay_buf_learn(rport->buf[dir].dbuf); + + } } else { - if (rport->buf[dir].level >= rport->max_burst || - rport->buf[dir].level <= -rport->max_burst) - { - /* Level has reached maximum level, the other side of - * rport is not sending/retrieving frames. Pause the - * rport on this direction. - */ - PJ_LOG(5,(rport->base.info.name.ptr, - "Pausing media flow on %s direction (level=%d)", - dir_name[dir], rport->buf[dir].level)); - rport->buf[dir].paused = PJ_TRUE; - } + if (rport->buf[dir].level >= rport->max_burst || + rport->buf[dir].level <= -rport->max_burst) + { + /* Level has reached maximum level, the other side of + * rport is not sending/retrieving frames. Pause the + * rport on this direction. + */ + PJ_LOG(5,(rport->base.info.name.ptr, + "Pausing media flow on %s direction (level=%d)", + dir_name[dir], rport->buf[dir].level)); + rport->buf[dir].paused = PJ_TRUE; + } } } @@ -493,115 +492,115 @@ static void op_update(struct reverse_port *rport, int dir, int op) * it to the appropriate port. */ static pj_status_t put_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct splitcomb *sc = (struct splitcomb*) this_port; unsigned ch; /* Handle null frame */ if (frame->type == PJMEDIA_FRAME_TYPE_NONE) { - for (ch=0; ch < PJMEDIA_PIA_CCNT(&this_port->info); ++ch) { - pjmedia_port *port = sc->port_desc[ch].port; - - if (!port) continue; - - if (!sc->port_desc[ch].reversed) { - pjmedia_port_put_frame(port, frame); - } else { - struct reverse_port *rport = (struct reverse_port*)port; - - /* Update the number of NULL frames received. Once we have too - * many of this, we'll stop calling op_update() to let the - * media be suspended. - */ - - if (++rport->buf[DIR_DOWNSTREAM].null_cnt > - rport->max_null_frames) - { - /* Prevent the counter from overflowing and resetting - * back to zero - */ - rport->buf[DIR_DOWNSTREAM].null_cnt = - rport->max_null_frames + 1; - continue; - } - - /* Write zero port to delaybuf so that it doesn't underflow. - * If we don't do this, get_frame() on this direction will - * cause delaybuf to generate missing frame and the last - * frame transmitted to delaybuf will be replayed multiple - * times, which doesn't sound good. - */ - - /* Update rport state. */ - op_update(rport, DIR_DOWNSTREAM, OP_PUT); - - /* Discard frame if rport is paused on this direction */ - if (rport->buf[DIR_DOWNSTREAM].paused) - continue; - - /* Generate zero frame. */ - pjmedia_zero_samples(sc->put_buf, - PJMEDIA_PIA_SPF(&port->info)); - - /* Put frame to delay buffer */ - pjmedia_delay_buf_put(rport->buf[DIR_DOWNSTREAM].dbuf, - sc->put_buf); - - } - } - return PJ_SUCCESS; + for (ch=0; ch < PJMEDIA_PIA_CCNT(&this_port->info); ++ch) { + pjmedia_port *port = sc->port_desc[ch].port; + + if (!port) continue; + + if (!sc->port_desc[ch].reversed) { + pjmedia_port_put_frame(port, frame); + } else { + struct reverse_port *rport = (struct reverse_port*)port; + + /* Update the number of NULL frames received. Once we have too + * many of this, we'll stop calling op_update() to let the + * media be suspended. + */ + + if (++rport->buf[DIR_DOWNSTREAM].null_cnt > + rport->max_null_frames) + { + /* Prevent the counter from overflowing and resetting + * back to zero + */ + rport->buf[DIR_DOWNSTREAM].null_cnt = + rport->max_null_frames + 1; + continue; + } + + /* Write zero port to delaybuf so that it doesn't underflow. + * If we don't do this, get_frame() on this direction will + * cause delaybuf to generate missing frame and the last + * frame transmitted to delaybuf will be replayed multiple + * times, which doesn't sound good. + */ + + /* Update rport state. */ + op_update(rport, DIR_DOWNSTREAM, OP_PUT); + + /* Discard frame if rport is paused on this direction */ + if (rport->buf[DIR_DOWNSTREAM].paused) + continue; + + /* Generate zero frame. */ + pjmedia_zero_samples(sc->put_buf, + PJMEDIA_PIA_SPF(&port->info)); + + /* Put frame to delay buffer */ + pjmedia_delay_buf_put(rport->buf[DIR_DOWNSTREAM].dbuf, + sc->put_buf); + + } + } + return PJ_SUCCESS; } /* Not sure how we would handle partial frame, so better reject * it for now. */ PJ_ASSERT_RETURN(frame->size == PJMEDIA_PIA_AVG_FSZ(&this_port->info), - PJ_EINVAL); + PJ_EINVAL); /* * Write mono frame into each channels */ for (ch=0; ch < PJMEDIA_PIA_CCNT(&this_port->info); ++ch) { - pjmedia_port *port = sc->port_desc[ch].port; + pjmedia_port *port = sc->port_desc[ch].port; - if (!port) - continue; + if (!port) + continue; - /* Extract the mono frame to temporary buffer */ - extract_mono_frame((const pj_int16_t*)frame->buf, sc->put_buf, ch, - PJMEDIA_PIA_CCNT(&this_port->info), - (unsigned)frame->size * 8 / - PJMEDIA_PIA_BITS(&this_port->info) / - PJMEDIA_PIA_CCNT(&this_port->info)); + /* Extract the mono frame to temporary buffer */ + extract_mono_frame((const pj_int16_t*)frame->buf, sc->put_buf, ch, + PJMEDIA_PIA_CCNT(&this_port->info), + (unsigned)frame->size * 8 / + PJMEDIA_PIA_BITS(&this_port->info) / + PJMEDIA_PIA_CCNT(&this_port->info)); - if (!sc->port_desc[ch].reversed) { - /* Write to normal port */ - pjmedia_frame mono_frame; + if (!sc->port_desc[ch].reversed) { + /* Write to normal port */ + pjmedia_frame mono_frame; - mono_frame.buf = sc->put_buf; - mono_frame.size = frame->size / PJMEDIA_PIA_CCNT(&this_port->info); - mono_frame.type = frame->type; - mono_frame.timestamp.u64 = frame->timestamp.u64; + mono_frame.buf = sc->put_buf; + mono_frame.size = frame->size / PJMEDIA_PIA_CCNT(&this_port->info); + mono_frame.type = frame->type; + mono_frame.timestamp.u64 = frame->timestamp.u64; - /* Write */ - pjmedia_port_put_frame(port, &mono_frame); + /* Write */ + pjmedia_port_put_frame(port, &mono_frame); - } else { - /* Write to reversed phase port */ - struct reverse_port *rport = (struct reverse_port*)port; + } else { + /* Write to reversed phase port */ + struct reverse_port *rport = (struct reverse_port*)port; - /* Reset NULL frame counter */ - rport->buf[DIR_DOWNSTREAM].null_cnt = 0; + /* Reset NULL frame counter */ + rport->buf[DIR_DOWNSTREAM].null_cnt = 0; - /* Update rport state. */ - op_update(rport, DIR_DOWNSTREAM, OP_PUT); + /* Update rport state. */ + op_update(rport, DIR_DOWNSTREAM, OP_PUT); - if (!rport->buf[DIR_DOWNSTREAM].paused) { - pjmedia_delay_buf_put(rport->buf[DIR_DOWNSTREAM].dbuf, - sc->put_buf); - } - } + if (!rport->buf[DIR_DOWNSTREAM].paused) { + pjmedia_delay_buf_put(rport->buf[DIR_DOWNSTREAM].dbuf, + sc->put_buf); + } + } } return PJ_SUCCESS; @@ -614,7 +613,7 @@ static pj_status_t put_frame(pjmedia_port *this_port, * mono frame into the multichannel frame. */ static pj_status_t get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct splitcomb *sc = (struct splitcomb*) this_port; unsigned ch; @@ -622,66 +621,66 @@ static pj_status_t get_frame(pjmedia_port *this_port, /* Read frame from each port */ for (ch=0; ch < PJMEDIA_PIA_CCNT(&this_port->info); ++ch) { - pjmedia_port *port = sc->port_desc[ch].port; - pjmedia_frame mono_frame; - pj_status_t status; - - if (!port) { - pjmedia_zero_samples(sc->get_buf, - PJMEDIA_PIA_SPF(&this_port->info) / - PJMEDIA_PIA_CCNT(&this_port->info)); - - } else if (sc->port_desc[ch].reversed == PJ_FALSE) { - /* Read from normal port */ - mono_frame.buf = sc->get_buf; - mono_frame.size = PJMEDIA_PIA_AVG_FSZ(&port->info); - mono_frame.timestamp.u64 = frame->timestamp.u64; - - status = pjmedia_port_get_frame(port, &mono_frame); - if (status != PJ_SUCCESS || - mono_frame.type != PJMEDIA_FRAME_TYPE_AUDIO) - { - pjmedia_zero_samples(sc->get_buf, - PJMEDIA_PIA_SPF(&port->info)); - } - - frame->timestamp.u64 = mono_frame.timestamp.u64; - - } else { - /* Read from temporary buffer for reverse port */ - struct reverse_port *rport = (struct reverse_port*)port; - - /* Update rport state. */ - op_update(rport, DIR_UPSTREAM, OP_GET); - - if (!rport->buf[DIR_UPSTREAM].paused) { - pjmedia_delay_buf_get(rport->buf[DIR_UPSTREAM].dbuf, - sc->get_buf); - - } else { - pjmedia_zero_samples(sc->get_buf, - PJMEDIA_PIA_SPF(&port->info)); - } - - frame->timestamp.u64 = rport->buf[DIR_UPSTREAM].ts.u64; - } - - /* Combine the mono frame into multichannel frame */ - store_mono_frame(sc->get_buf, - (pj_int16_t*)frame->buf, ch, - PJMEDIA_PIA_CCNT(&this_port->info), - PJMEDIA_PIA_SPF(&this_port->info) / - PJMEDIA_PIA_CCNT(&this_port->info)); - - has_frame = PJ_TRUE; + pjmedia_port *port = sc->port_desc[ch].port; + pjmedia_frame mono_frame; + pj_status_t status; + + if (!port) { + pjmedia_zero_samples(sc->get_buf, + PJMEDIA_PIA_SPF(&this_port->info) / + PJMEDIA_PIA_CCNT(&this_port->info)); + + } else if (sc->port_desc[ch].reversed == PJ_FALSE) { + /* Read from normal port */ + mono_frame.buf = sc->get_buf; + mono_frame.size = PJMEDIA_PIA_AVG_FSZ(&port->info); + mono_frame.timestamp.u64 = frame->timestamp.u64; + + status = pjmedia_port_get_frame(port, &mono_frame); + if (status != PJ_SUCCESS || + mono_frame.type != PJMEDIA_FRAME_TYPE_AUDIO) + { + pjmedia_zero_samples(sc->get_buf, + PJMEDIA_PIA_SPF(&port->info)); + } + + frame->timestamp.u64 = mono_frame.timestamp.u64; + + } else { + /* Read from temporary buffer for reverse port */ + struct reverse_port *rport = (struct reverse_port*)port; + + /* Update rport state. */ + op_update(rport, DIR_UPSTREAM, OP_GET); + + if (!rport->buf[DIR_UPSTREAM].paused) { + pjmedia_delay_buf_get(rport->buf[DIR_UPSTREAM].dbuf, + sc->get_buf); + + } else { + pjmedia_zero_samples(sc->get_buf, + PJMEDIA_PIA_SPF(&port->info)); + } + + frame->timestamp.u64 = rport->buf[DIR_UPSTREAM].ts.u64; + } + + /* Combine the mono frame into multichannel frame */ + store_mono_frame(sc->get_buf, + (pj_int16_t*)frame->buf, ch, + PJMEDIA_PIA_CCNT(&this_port->info), + PJMEDIA_PIA_SPF(&this_port->info) / + PJMEDIA_PIA_CCNT(&this_port->info)); + + has_frame = PJ_TRUE; } /* Return NO_FRAME is we don't get any frames from downstream ports */ if (has_frame) { - frame->type = PJMEDIA_FRAME_TYPE_AUDIO; - frame->size = PJMEDIA_PIA_AVG_FSZ(&this_port->info); + frame->type = PJMEDIA_FRAME_TYPE_AUDIO; + frame->size = PJMEDIA_PIA_AVG_FSZ(&this_port->info); } else - frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->type = PJMEDIA_FRAME_TYPE_NONE; return PJ_SUCCESS; } @@ -703,7 +702,7 @@ static pj_status_t on_destroy(pjmedia_port *this_port) * will be picked up by get_frame() above. */ static pj_status_t rport_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct reverse_port *rport = (struct reverse_port*) this_port; @@ -711,44 +710,44 @@ static pj_status_t rport_put_frame(pjmedia_port *this_port, /* Handle NULL frame */ if (frame->type != PJMEDIA_FRAME_TYPE_AUDIO) { - /* Update the number of NULL frames received. Once we have too - * many of this, we'll stop calling op_update() to let the - * media be suspended. - */ - if (++rport->buf[DIR_UPSTREAM].null_cnt > rport->max_null_frames) { - /* Prevent the counter from overflowing and resetting back - * to zero - */ - rport->buf[DIR_UPSTREAM].null_cnt = rport->max_null_frames + 1; - return PJ_SUCCESS; - } - - /* Write zero port to delaybuf so that it doesn't underflow. - * If we don't do this, get_frame() on this direction will - * cause delaybuf to generate missing frame and the last - * frame transmitted to delaybuf will be replayed multiple - * times, which doesn't sound good. - */ - - /* Update rport state. */ - op_update(rport, DIR_UPSTREAM, OP_PUT); - - /* Discard frame if rport is paused on this direction */ - if (rport->buf[DIR_UPSTREAM].paused) - return PJ_SUCCESS; - - /* Generate zero frame. */ - pjmedia_zero_samples(rport->tmp_up_buf, - PJMEDIA_PIA_SPF(&this_port->info)); - - /* Put frame to delay buffer */ - return pjmedia_delay_buf_put(rport->buf[DIR_UPSTREAM].dbuf, - rport->tmp_up_buf); + /* Update the number of NULL frames received. Once we have too + * many of this, we'll stop calling op_update() to let the + * media be suspended. + */ + if (++rport->buf[DIR_UPSTREAM].null_cnt > rport->max_null_frames) { + /* Prevent the counter from overflowing and resetting back + * to zero + */ + rport->buf[DIR_UPSTREAM].null_cnt = rport->max_null_frames + 1; + return PJ_SUCCESS; + } + + /* Write zero port to delaybuf so that it doesn't underflow. + * If we don't do this, get_frame() on this direction will + * cause delaybuf to generate missing frame and the last + * frame transmitted to delaybuf will be replayed multiple + * times, which doesn't sound good. + */ + + /* Update rport state. */ + op_update(rport, DIR_UPSTREAM, OP_PUT); + + /* Discard frame if rport is paused on this direction */ + if (rport->buf[DIR_UPSTREAM].paused) + return PJ_SUCCESS; + + /* Generate zero frame. */ + pjmedia_zero_samples(rport->tmp_up_buf, + PJMEDIA_PIA_SPF(&this_port->info)); + + /* Put frame to delay buffer */ + return pjmedia_delay_buf_put(rport->buf[DIR_UPSTREAM].dbuf, + rport->tmp_up_buf); } /* Not sure how to handle partial frame, so better reject for now */ PJ_ASSERT_RETURN(frame->size == PJMEDIA_PIA_AVG_FSZ(&this_port->info), - PJ_EINVAL); + PJ_EINVAL); /* Reset NULL frame counter */ rport->buf[DIR_UPSTREAM].null_cnt = 0; @@ -758,17 +757,17 @@ static pj_status_t rport_put_frame(pjmedia_port *this_port, /* Discard frame if rport is paused on this direction */ if (rport->buf[DIR_UPSTREAM].paused) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Unfortunately must copy to temporary buffer since delay buf * modifies the frame content. */ pjmedia_copy_samples(rport->tmp_up_buf, (const pj_int16_t*)frame->buf, - PJMEDIA_PIA_SPF(&this_port->info)); + PJMEDIA_PIA_SPF(&this_port->info)); /* Put frame to delay buffer */ return pjmedia_delay_buf_put(rport->buf[DIR_UPSTREAM].dbuf, - rport->tmp_up_buf); + rport->tmp_up_buf); } @@ -776,7 +775,7 @@ static pj_status_t rport_put_frame(pjmedia_port *this_port, * The frame is put by put_frame() call to the splitcomb. */ static pj_status_t rport_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct reverse_port *rport = (struct reverse_port*) this_port; @@ -787,8 +786,8 @@ static pj_status_t rport_get_frame(pjmedia_port *this_port, * paused. */ if (rport->buf[DIR_DOWNSTREAM].paused) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; + frame->type = PJMEDIA_FRAME_TYPE_NONE; + return PJ_SUCCESS; } /* Get frame from delay buffer */ @@ -797,7 +796,7 @@ static pj_status_t rport_get_frame(pjmedia_port *this_port, frame->timestamp.u64 = rport->buf[DIR_DOWNSTREAM].ts.u64; return pjmedia_delay_buf_get(rport->buf[DIR_DOWNSTREAM].dbuf, - (short*)frame->buf); + (short*)frame->buf); } diff --git a/pjmedia/src/pjmedia/stereo_port.c b/pjmedia/src/pjmedia/stereo_port.c index 1b4a49dfc5..5144386d72 100644 --- a/pjmedia/src/pjmedia/stereo_port.c +++ b/pjmedia/src/pjmedia/stereo_port.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,33 +23,33 @@ #include -#define SIGNATURE PJMEDIA_SIG_PORT_STEREO +#define SIGNATURE PJMEDIA_SIG_PORT_STEREO struct stereo_port { - pjmedia_port base; - pjmedia_port *dn_port; - unsigned options; - pj_int16_t *put_buf; - pj_int16_t *get_buf; + pjmedia_port base; + pjmedia_port *dn_port; + unsigned options; + pj_int16_t *put_buf; + pj_int16_t *get_buf; }; static pj_status_t stereo_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t stereo_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t stereo_destroy(pjmedia_port *this_port); PJ_DEF(pj_status_t) pjmedia_stereo_port_create( pj_pool_t *pool, - pjmedia_port *dn_port, - unsigned channel_count, - unsigned options, - pjmedia_port **p_port ) + pjmedia_port *dn_port, + unsigned channel_count, + unsigned options, + pjmedia_port **p_port ) { const pj_str_t name = pj_str("stereo"); struct stereo_port *sport; @@ -61,41 +60,41 @@ PJ_DEF(pj_status_t) pjmedia_stereo_port_create( pj_pool_t *pool, /* Only supports 16bit samples per frame */ PJ_ASSERT_RETURN(PJMEDIA_PIA_BITS(&dn_port->info) == 16, - PJMEDIA_ENCBITS); + PJMEDIA_ENCBITS); /* Validate channel counts */ PJ_ASSERT_RETURN(((PJMEDIA_PIA_CCNT(&dn_port->info)>1 && - channel_count==1) || - (PJMEDIA_PIA_CCNT(&dn_port->info)==1 && - channel_count>1)), - PJ_EINVAL); + channel_count==1) || + (PJMEDIA_PIA_CCNT(&dn_port->info)==1 && + channel_count>1)), + PJ_EINVAL); /* Create and initialize port. */ sport = PJ_POOL_ZALLOC_T(pool, struct stereo_port); PJ_ASSERT_RETURN(sport != NULL, PJ_ENOMEM); samples_per_frame = PJMEDIA_PIA_SPF(&dn_port->info) * channel_count / - PJMEDIA_PIA_CCNT(&dn_port->info); + PJMEDIA_PIA_CCNT(&dn_port->info); pjmedia_port_info_init(&sport->base.info, &name, SIGNATURE, - PJMEDIA_PIA_SRATE(&dn_port->info), - channel_count, - PJMEDIA_PIA_BITS(&dn_port->info), - samples_per_frame); + PJMEDIA_PIA_SRATE(&dn_port->info), + channel_count, + PJMEDIA_PIA_BITS(&dn_port->info), + samples_per_frame); sport->dn_port = dn_port; sport->options = options; /* We always need buffer for put_frame */ sport->put_buf = (pj_int16_t*) - pj_pool_alloc(pool, - PJMEDIA_PIA_AVG_FSZ(&dn_port->info)); + pj_pool_alloc(pool, + PJMEDIA_PIA_AVG_FSZ(&dn_port->info)); /* See if we need buffer for get_frame */ if (PJMEDIA_PIA_CCNT(&dn_port->info) > channel_count) { - sport->get_buf = (pj_int16_t*) - pj_pool_alloc(pool, - PJMEDIA_PIA_AVG_FSZ(&dn_port->info)); + sport->get_buf = (pj_int16_t*) + pj_pool_alloc(pool, + PJMEDIA_PIA_AVG_FSZ(&dn_port->info)); } /* Media port interface */ @@ -111,7 +110,7 @@ PJ_DEF(pj_status_t) pjmedia_stereo_port_create( pj_pool_t *pool, } static pj_status_t stereo_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct stereo_port *sport = (struct stereo_port*) this_port; const pjmedia_audio_format_detail *s_afd, *dn_afd; @@ -119,33 +118,33 @@ static pj_status_t stereo_put_frame(pjmedia_port *this_port, /* Return if we don't have downstream port. */ if (sport->dn_port == NULL) { - return PJ_SUCCESS; + return PJ_SUCCESS; } s_afd = pjmedia_format_get_audio_format_detail(&this_port->info.fmt, 1); dn_afd = pjmedia_format_get_audio_format_detail(&sport->dn_port->info.fmt, - 1); + 1); if (frame->type == PJMEDIA_FRAME_TYPE_AUDIO) { - tmp_frame.buf = sport->put_buf; - if (dn_afd->channel_count == 1) { - pjmedia_convert_channel_nto1((pj_int16_t*)tmp_frame.buf, - (const pj_int16_t*)frame->buf, - s_afd->channel_count, - PJMEDIA_AFD_SPF(s_afd), - (sport->options & PJMEDIA_STEREO_MIX), - 0); - } else { - pjmedia_convert_channel_1ton((pj_int16_t*)tmp_frame.buf, - (const pj_int16_t*)frame->buf, - dn_afd->channel_count, - PJMEDIA_AFD_SPF(s_afd), - sport->options); - } - tmp_frame.size = PJMEDIA_AFD_AVG_FSZ(dn_afd); + tmp_frame.buf = sport->put_buf; + if (dn_afd->channel_count == 1) { + pjmedia_convert_channel_nto1((pj_int16_t*)tmp_frame.buf, + (const pj_int16_t*)frame->buf, + s_afd->channel_count, + PJMEDIA_AFD_SPF(s_afd), + (sport->options & PJMEDIA_STEREO_MIX), + 0); + } else { + pjmedia_convert_channel_1ton((pj_int16_t*)tmp_frame.buf, + (const pj_int16_t*)frame->buf, + dn_afd->channel_count, + PJMEDIA_AFD_SPF(s_afd), + sport->options); + } + tmp_frame.size = PJMEDIA_AFD_AVG_FSZ(dn_afd); } else { - tmp_frame.buf = frame->buf; - tmp_frame.size = frame->size; + tmp_frame.buf = frame->buf; + tmp_frame.size = frame->size; } tmp_frame.type = frame->type; @@ -157,7 +156,7 @@ static pj_status_t stereo_put_frame(pjmedia_port *this_port, static pj_status_t stereo_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct stereo_port *sport = (struct stereo_port*) this_port; const pjmedia_audio_format_detail *s_afd, *dn_afd; @@ -166,13 +165,13 @@ static pj_status_t stereo_get_frame(pjmedia_port *this_port, /* Return silence if we don't have downstream port */ if (sport->dn_port == NULL) { - pj_bzero(frame->buf, frame->size); - return PJ_SUCCESS; + pj_bzero(frame->buf, frame->size); + return PJ_SUCCESS; } s_afd = pjmedia_format_get_audio_format_detail(&this_port->info.fmt, 1); dn_afd = pjmedia_format_get_audio_format_detail(&sport->dn_port->info.fmt, - 1); + 1); tmp_frame.buf = sport->get_buf? sport->get_buf : frame->buf; tmp_frame.size = PJMEDIA_PIA_AVG_FSZ(&sport->dn_port->info); @@ -181,29 +180,29 @@ static pj_status_t stereo_get_frame(pjmedia_port *this_port, status = pjmedia_port_get_frame( sport->dn_port, &tmp_frame); if (status != PJ_SUCCESS) - return status; + return status; if (tmp_frame.type != PJMEDIA_FRAME_TYPE_AUDIO) { - frame->type = tmp_frame.type; - frame->timestamp = tmp_frame.timestamp; - frame->size = tmp_frame.size; - if (tmp_frame.size && tmp_frame.buf == sport->get_buf) - pj_memcpy(frame->buf, tmp_frame.buf, tmp_frame.size); - return PJ_SUCCESS; + frame->type = tmp_frame.type; + frame->timestamp = tmp_frame.timestamp; + frame->size = tmp_frame.size; + if (tmp_frame.size && tmp_frame.buf == sport->get_buf) + pj_memcpy(frame->buf, tmp_frame.buf, tmp_frame.size); + return PJ_SUCCESS; } if (s_afd->channel_count == 1) { - pjmedia_convert_channel_nto1((pj_int16_t*)frame->buf, - (const pj_int16_t*)tmp_frame.buf, - dn_afd->channel_count, - PJMEDIA_AFD_SPF(s_afd), - (sport->options & PJMEDIA_STEREO_MIX), 0); + pjmedia_convert_channel_nto1((pj_int16_t*)frame->buf, + (const pj_int16_t*)tmp_frame.buf, + dn_afd->channel_count, + PJMEDIA_AFD_SPF(s_afd), + (sport->options & PJMEDIA_STEREO_MIX), 0); } else { - pjmedia_convert_channel_1ton((pj_int16_t*)frame->buf, - (const pj_int16_t*)tmp_frame.buf, - s_afd->channel_count, - PJMEDIA_AFD_SPF(dn_afd), - sport->options); + pjmedia_convert_channel_1ton((pj_int16_t*)frame->buf, + (const pj_int16_t*)tmp_frame.buf, + s_afd->channel_count, + PJMEDIA_AFD_SPF(dn_afd), + sport->options); } frame->size = PJMEDIA_AFD_AVG_FSZ(s_afd); @@ -218,8 +217,8 @@ static pj_status_t stereo_destroy(pjmedia_port *this_port) struct stereo_port *sport = (struct stereo_port*) this_port; if ((sport->options & PJMEDIA_STEREO_DONT_DESTROY_DN)==0) { - pjmedia_port_destroy(sport->dn_port); - sport->dn_port = NULL; + pjmedia_port_destroy(sport->dn_port); + sport->dn_port = NULL; } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia/stream.c b/pjmedia/src/pjmedia/stream.c index 53daf7ed0b..acdb052170 100644 --- a/pjmedia/src/pjmedia/stream.c +++ b/pjmedia/src/pjmedia/stream.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -33,71 +32,71 @@ #include #include #include -#include /* memcpy() */ +#include /* memcpy() */ -#define THIS_FILE "stream.c" -#define ERRLEVEL 1 -#define LOGERR_(expr) PJ_PERROR(4,expr); -#define TRC_(expr) PJ_LOG(5,expr) +#define THIS_FILE "stream.c" +#define ERRLEVEL 1 +#define LOGERR_(expr) PJ_PERROR(4,expr); +#define TRC_(expr) PJ_LOG(5,expr) -#define BYTES_PER_SAMPLE 2 +#define BYTES_PER_SAMPLE 2 /* Limit the number of synthetic audio samples that are generated by PLC. * Normally PLC should have it's own means to limit the number of * synthetic frames, so we need to set this to a reasonably large value * just as precaution */ -#define MAX_PLC_MSEC PJMEDIA_MAX_PLC_DURATION_MSEC +#define MAX_PLC_MSEC PJMEDIA_MAX_PLC_DURATION_MSEC /* Tracing jitter buffer operations in a stream session to a CSV file. * The trace will contain JB operation timestamp, frame info, RTP info, and * the JB state right after the operation. */ -#define TRACE_JB 0 /* Enable/disable trace. */ -#define TRACE_JB_PATH_PREFIX "" /* Optional path/prefix - for the CSV filename. */ +#define TRACE_JB 0 /* Enable/disable trace. */ +#define TRACE_JB_PATH_PREFIX "" /* Optional path/prefix + for the CSV filename. */ #if TRACE_JB # include -# define TRACE_JB_INVALID_FD ((pj_oshandle_t)-1) -# define TRACE_JB_OPENED(s) (s->trace_jb_fd != TRACE_JB_INVALID_FD) +# define TRACE_JB_INVALID_FD ((pj_oshandle_t)-1) +# define TRACE_JB_OPENED(s) (s->trace_jb_fd != TRACE_JB_INVALID_FD) #endif #ifndef PJMEDIA_STREAM_SIZE -# define PJMEDIA_STREAM_SIZE 1000 +# define PJMEDIA_STREAM_SIZE 1000 #endif #ifndef PJMEDIA_STREAM_INC -# define PJMEDIA_STREAM_INC 1000 +# define PJMEDIA_STREAM_INC 1000 #endif /* Number of DTMF E bit transmissions */ -#define DTMF_EBIT_RETRANSMIT_CNT 3 +#define DTMF_EBIT_RETRANSMIT_CNT 3 /* Number of send error before repeat the report. */ -#define SEND_ERR_COUNT_TO_REPORT 50 +#define SEND_ERR_COUNT_TO_REPORT 50 /** * Media channel. */ struct pjmedia_channel { - pjmedia_stream *stream; /**< Parent stream. */ - pjmedia_dir dir; /**< Channel direction. */ - unsigned pt; /**< Payload type. */ - pj_bool_t paused; /**< Paused?. */ - unsigned out_pkt_size; /**< Size of output buffer. */ - void *out_pkt; /**< Output buffer. */ - pjmedia_rtp_session rtp; /**< RTP session. */ + pjmedia_stream *stream; /**< Parent stream. */ + pjmedia_dir dir; /**< Channel direction. */ + unsigned pt; /**< Payload type. */ + pj_bool_t paused; /**< Paused?. */ + unsigned out_pkt_size; /**< Size of output buffer. */ + void *out_pkt; /**< Output buffer. */ + pjmedia_rtp_session rtp; /**< RTP session. */ }; struct dtmf { - int event; - pj_uint32_t duration; - int ebit_cnt; /**< # of E bit transmissions */ + int event; + pj_uint32_t duration; + int ebit_cnt; /**< # of E bit transmissions */ }; @@ -110,90 +109,90 @@ struct dtmf */ struct pjmedia_stream { - pjmedia_endpt *endpt; /**< Media endpoint. */ - pjmedia_codec_mgr *codec_mgr; /**< Codec manager instance. */ - pjmedia_stream_info si; /**< Creation parameter. */ - pjmedia_port port; /**< Port interface. */ - pjmedia_channel *enc; /**< Encoding channel. */ - pjmedia_channel *dec; /**< Decoding channel. */ - - pj_pool_t *own_pool; /**< Only created if not given */ - - pjmedia_dir dir; /**< Stream direction. */ - void *user_data; /**< User data. */ - pj_str_t cname; /**< SDES CNAME */ - - pjmedia_transport *transport; /**< Stream transport. */ - - pjmedia_codec *codec; /**< Codec instance being used. */ - pjmedia_codec_param codec_param; /**< Codec param. */ - pj_int16_t *enc_buf; /**< Encoding buffer, when enc's - ptime is different than dec. - Otherwise it's NULL. */ - - unsigned enc_samples_per_pkt; - unsigned enc_buf_size; /**< Encoding buffer size, in - samples. */ - unsigned enc_buf_pos; /**< First position in buf. */ - unsigned enc_buf_count; /**< Number of samples in the - encoding buffer. */ - - pj_int16_t *dec_buf; /**< Decoding buffer. */ - unsigned dec_buf_size; /**< Decoding buffer size, in - samples. */ - unsigned dec_buf_pos; /**< First position in buf. */ - unsigned dec_buf_count; /**< Number of samples in the - decoding buffer. */ - - pj_uint16_t dec_ptime; /**< Decoder frame ptime in ms. */ - pj_bool_t detect_ptime_change; - /**< Detect decode ptime change */ - - unsigned plc_cnt; /**< # of consecutive PLC frames*/ - unsigned max_plc_cnt; /**< Max # of PLC frames */ - - unsigned vad_enabled; /**< VAD enabled in param. */ - unsigned frame_size; /**< Size of encoded base frame.*/ - pj_bool_t is_streaming; /**< Currently streaming?. This - is used to put RTP marker - bit. */ - pj_uint32_t ts_vad_disabled;/**< TS when VAD was disabled. */ - pj_uint32_t tx_duration; /**< TX duration in timestamp. */ - - pj_mutex_t *jb_mutex; - pjmedia_jbuf *jb; /**< Jitter buffer. */ - char jb_last_frm; /**< Last frame type from jb */ - unsigned jb_last_frm_cnt;/**< Last JB frame type counter*/ - unsigned soft_start_cnt;/**< Stream soft start counter */ - - pjmedia_rtcp_session rtcp; /**< RTCP for incoming RTP. */ - - pj_uint32_t rtcp_last_tx; /**< RTCP tx time in timestamp */ - pj_uint32_t rtcp_interval; /**< Interval, in timestamp. */ - pj_bool_t initial_rr; /**< Initial RTCP RR sent */ + pjmedia_endpt *endpt; /**< Media endpoint. */ + pjmedia_codec_mgr *codec_mgr; /**< Codec manager instance. */ + pjmedia_stream_info si; /**< Creation parameter. */ + pjmedia_port port; /**< Port interface. */ + pjmedia_channel *enc; /**< Encoding channel. */ + pjmedia_channel *dec; /**< Decoding channel. */ + + pj_pool_t *own_pool; /**< Only created if not given */ + + pjmedia_dir dir; /**< Stream direction. */ + void *user_data; /**< User data. */ + pj_str_t cname; /**< SDES CNAME */ + + pjmedia_transport *transport; /**< Stream transport. */ + + pjmedia_codec *codec; /**< Codec instance being used. */ + pjmedia_codec_param codec_param; /**< Codec param. */ + pj_int16_t *enc_buf; /**< Encoding buffer, when enc's + ptime is different than dec. + Otherwise it's NULL. */ + + unsigned enc_samples_per_pkt; + unsigned enc_buf_size; /**< Encoding buffer size, in + samples. */ + unsigned enc_buf_pos; /**< First position in buf. */ + unsigned enc_buf_count; /**< Number of samples in the + encoding buffer. */ + + pj_int16_t *dec_buf; /**< Decoding buffer. */ + unsigned dec_buf_size; /**< Decoding buffer size, in + samples. */ + unsigned dec_buf_pos; /**< First position in buf. */ + unsigned dec_buf_count; /**< Number of samples in the + decoding buffer. */ + + pj_uint16_t dec_ptime; /**< Decoder frame ptime in ms. */ + pj_bool_t detect_ptime_change; + /**< Detect decode ptime change */ + + unsigned plc_cnt; /**< # of consecutive PLC frames*/ + unsigned max_plc_cnt; /**< Max # of PLC frames */ + + unsigned vad_enabled; /**< VAD enabled in param. */ + unsigned frame_size; /**< Size of encoded base frame.*/ + pj_bool_t is_streaming; /**< Currently streaming?. This + is used to put RTP marker + bit. */ + pj_uint32_t ts_vad_disabled;/**< TS when VAD was disabled. */ + pj_uint32_t tx_duration; /**< TX duration in timestamp. */ + + pj_mutex_t *jb_mutex; + pjmedia_jbuf *jb; /**< Jitter buffer. */ + char jb_last_frm; /**< Last frame type from jb */ + unsigned jb_last_frm_cnt;/**< Last JB frame type counter*/ + unsigned soft_start_cnt;/**< Stream soft start counter */ + + pjmedia_rtcp_session rtcp; /**< RTCP for incoming RTP. */ + + pj_uint32_t rtcp_last_tx; /**< RTCP tx time in timestamp */ + pj_uint32_t rtcp_interval; /**< Interval, in timestamp. */ + pj_bool_t initial_rr; /**< Initial RTCP RR sent */ pj_bool_t rtcp_sdes_bye_disabled;/**< Send RTCP SDES/BYE?*/ - void *out_rtcp_pkt; /**< Outgoing RTCP packet. */ - unsigned out_rtcp_pkt_size; - /**< Outgoing RTCP packet size. */ - pj_int16_t *zero_frame; /**< Zero frame buffer. */ + void *out_rtcp_pkt; /**< Outgoing RTCP packet. */ + unsigned out_rtcp_pkt_size; + /**< Outgoing RTCP packet size. */ + pj_int16_t *zero_frame; /**< Zero frame buffer. */ /* RFC 2833 DTMF transmission queue: */ - unsigned dtmf_duration; /**< DTMF duration(in timestamp)*/ - int tx_event_pt; /**< Outgoing pt for dtmf. */ - int tx_dtmf_count; /**< # of digits in tx dtmf buf.*/ - struct dtmf tx_dtmf_buf[32];/**< Outgoing dtmf queue. */ + unsigned dtmf_duration; /**< DTMF duration(in timestamp)*/ + int tx_event_pt; /**< Outgoing pt for dtmf. */ + int tx_dtmf_count; /**< # of digits in tx dtmf buf.*/ + struct dtmf tx_dtmf_buf[32];/**< Outgoing dtmf queue. */ /* Incoming DTMF: */ - int rx_event_pt; /**< Incoming pt for dtmf. */ - int last_dtmf; /**< Current digit, or -1. */ - pj_uint32_t last_dtmf_dur; /**< Start ts for cur digit. */ + int rx_event_pt; /**< Incoming pt for dtmf. */ + int last_dtmf; /**< Current digit, or -1. */ + pj_uint32_t last_dtmf_dur; /**< Start ts for cur digit. */ pj_bool_t last_dtmf_ended; - unsigned rx_dtmf_count; /**< # of digits in dtmf rx buf.*/ - char rx_dtmf_buf[32];/**< Incoming DTMF buffer. */ + unsigned rx_dtmf_count; /**< # of digits in dtmf rx buf.*/ + char rx_dtmf_buf[32];/**< Incoming DTMF buffer. */ /* DTMF callback */ - void (*dtmf_cb)(pjmedia_stream*, void*, int); - void *dtmf_cb_user_data; + void (*dtmf_cb)(pjmedia_stream*, void*, int); + void *dtmf_cb_user_data; void (*dtmf_event_cb)(pjmedia_stream*, void*, const pjmedia_stream_dtmf_event*); @@ -204,75 +203,75 @@ struct pjmedia_stream * between clock rate in SDP/RTP & the clock rate that is actually used. * This happens for example with G.722 and MPEG audio codecs. */ - pj_bool_t has_g722_mpeg_bug; - /**< Flag to specify whether - normalization process - is needed */ - unsigned rtp_tx_ts_len_per_pkt; - /**< Normalized ts length per packet - transmitted according to - 'erroneous' definition */ - unsigned rtp_rx_ts_len_per_frame; - /**< Normalized ts length per frame - received according to - 'erroneous' definition */ - unsigned rtp_rx_last_cnt;/**< Nb of frames in last pkt */ - unsigned rtp_rx_check_cnt; - /**< Counter of remote timestamp - checking */ + pj_bool_t has_g722_mpeg_bug; + /**< Flag to specify whether + normalization process + is needed */ + unsigned rtp_tx_ts_len_per_pkt; + /**< Normalized ts length per packet + transmitted according to + 'erroneous' definition */ + unsigned rtp_rx_ts_len_per_frame; + /**< Normalized ts length per frame + received according to + 'erroneous' definition */ + unsigned rtp_rx_last_cnt;/**< Nb of frames in last pkt */ + unsigned rtp_rx_check_cnt; + /**< Counter of remote timestamp + checking */ #endif #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) - pj_uint32_t rtcp_xr_last_tx; /**< RTCP XR tx time - in timestamp. */ - pj_uint32_t rtcp_xr_interval; /**< Interval, in timestamp. */ - pj_sockaddr rtcp_xr_dest; /**< Additional remote RTCP XR - dest. If sin_family is - zero, it will be ignored*/ - unsigned rtcp_xr_dest_len; /**< Length of RTCP XR dest - address */ + pj_uint32_t rtcp_xr_last_tx; /**< RTCP XR tx time + in timestamp. */ + pj_uint32_t rtcp_xr_interval; /**< Interval, in timestamp. */ + pj_sockaddr rtcp_xr_dest; /**< Additional remote RTCP XR + dest. If sin_family is + zero, it will be ignored*/ + unsigned rtcp_xr_dest_len; /**< Length of RTCP XR dest + address */ #endif #if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0 - pj_bool_t use_ka; /**< Stream keep-alive with non- - codec-VAD mechanism is - enabled? */ - unsigned ka_interval; /**< The keepalive sending - interval */ - pj_time_val last_frm_ts_sent; /**< Time of last sending - packet */ - unsigned start_ka_count; /**< The number of keep-alive + pj_bool_t use_ka; /**< Stream keep-alive with non- + codec-VAD mechanism is + enabled? */ + unsigned ka_interval; /**< The keepalive sending + interval */ + pj_time_val last_frm_ts_sent; /**< Time of last sending + packet */ + unsigned start_ka_count; /**< The number of keep-alive to be sent after it is created */ - unsigned start_ka_interval;/**< The keepalive sending + unsigned start_ka_interval;/**< The keepalive sending interval after the stream is created */ #endif - pj_sockaddr rem_rtp_addr; /**< Remote RTP address */ - unsigned rem_rtp_flag; /**< Indicator flag about - packet from this addr. - 0=no pkt, 1=good ssrc, - 2=bad ssrc pkts */ - unsigned rtp_src_cnt; /**< How many pkt from - this addr. */ + pj_sockaddr rem_rtp_addr; /**< Remote RTP address */ + unsigned rem_rtp_flag; /**< Indicator flag about + packet from this addr. + 0=no pkt, 1=good ssrc, + 2=bad ssrc pkts */ + unsigned rtp_src_cnt; /**< How many pkt from + this addr. */ #if TRACE_JB - pj_oshandle_t trace_jb_fd; /**< Jitter tracing file handle.*/ - char *trace_jb_buf; /**< Jitter tracing buffer. */ + pj_oshandle_t trace_jb_fd; /**< Jitter tracing file handle.*/ + char *trace_jb_buf; /**< Jitter tracing buffer. */ #endif - pj_uint32_t rtp_rx_last_ts; /**< Last received RTP - timestamp */ - pj_uint32_t rtp_tx_err_cnt; /**< The number of RTP - send() error */ - pj_uint32_t rtcp_tx_err_cnt; /**< The number of RTCP - send() error */ + pj_uint32_t rtp_rx_last_ts; /**< Last received RTP + timestamp */ + pj_uint32_t rtp_tx_err_cnt; /**< The number of RTP + send() error */ + pj_uint32_t rtcp_tx_err_cnt; /**< The number of RTCP + send() error */ /* RTCP Feedback */ - pj_bool_t send_rtcp_fb_nack; /**< Send NACK? */ - pjmedia_rtcp_fb_nack rtcp_fb_nack; /**< TX NACK state. */ - int rtcp_fb_nack_cap_idx; /**< RX NACK cap idx. */ + pj_bool_t send_rtcp_fb_nack; /**< Send NACK? */ + pjmedia_rtcp_fb_nack rtcp_fb_nack; /**< TX NACK state. */ + int rtcp_fb_nack_cap_idx; /**< RX NACK cap idx. */ }; @@ -280,10 +279,10 @@ struct pjmedia_stream /* RFC 2833 digit */ static const char digitmap[17] = { '0', '1', '2', '3', - '4', '5', '6', '7', - '8', '9', '*', '#', - 'A', 'B', 'C', 'D', - 'R'}; + '4', '5', '6', '7', + '8', '9', '*', '#', + 'A', 'B', 'C', 'D', + 'R'}; /* Zero audio frame samples */ static pj_int16_t zero_frame[2 * 30 * 16000 / 1000]; @@ -294,10 +293,10 @@ static void on_rx_rtcp( void *data, pj_ssize_t bytes_read); static pj_status_t send_rtcp(pjmedia_stream *stream, - pj_bool_t with_sdes, - pj_bool_t with_bye, - pj_bool_t with_xr, - pj_bool_t with_fb); + pj_bool_t with_sdes, + pj_bool_t with_bye, + pj_bool_t with_xr, + pj_bool_t with_fb); #if TRACE_JB @@ -309,7 +308,7 @@ PJ_INLINE(int) trace_jb_print_timestamp(char **buf, pj_ssize_t len) char *p = *buf; if (len < 14) - return -1; + return -1; pj_gettimeofday(&now); pj_time_decode(&now, &ptime); @@ -328,7 +327,7 @@ PJ_INLINE(int) trace_jb_print_timestamp(char **buf, pj_ssize_t len) } PJ_INLINE(int) trace_jb_print_state(pjmedia_stream *stream, - char **buf, pj_ssize_t len) + char **buf, pj_ssize_t len) { char *p = *buf; char *endp = *buf + len; @@ -337,9 +336,9 @@ PJ_INLINE(int) trace_jb_print_state(pjmedia_stream *stream, pjmedia_jbuf_get_state(stream->jb, &state); len = pj_ansi_snprintf(p, endp-p, "%d, %d, %d", - state.size, state.burst, state.prefetch); + state.size, state.burst, state.prefetch); if ((len < 0) || (len >= endp-p)) - return -1; + return -1; p += len; *buf = p; @@ -347,7 +346,7 @@ PJ_INLINE(int) trace_jb_print_state(pjmedia_stream *stream, } static void trace_jb_get(pjmedia_stream *stream, pjmedia_jb_frame_type ft, - pj_size_t fsize) + pj_size_t fsize) { char *p = stream->trace_jb_buf; char *endp = stream->trace_jb_buf + PJ_LOG_MAX_SIZE; @@ -355,44 +354,44 @@ static void trace_jb_get(pjmedia_stream *stream, pjmedia_jb_frame_type ft, const char* ft_st; if (!TRACE_JB_OPENED(stream)) - return; + return; /* Print timestamp. */ if (trace_jb_print_timestamp(&p, endp-p)) - goto on_insuff_buffer; + goto on_insuff_buffer; /* Print frame type and size */ switch(ft) { - case PJMEDIA_JB_MISSING_FRAME: - ft_st = "missing"; - break; - case PJMEDIA_JB_NORMAL_FRAME: - ft_st = "normal"; - break; - case PJMEDIA_JB_ZERO_PREFETCH_FRAME: - ft_st = "prefetch"; - break; - case PJMEDIA_JB_ZERO_EMPTY_FRAME: - ft_st = "empty"; - break; - default: - ft_st = "unknown"; - break; + case PJMEDIA_JB_MISSING_FRAME: + ft_st = "missing"; + break; + case PJMEDIA_JB_NORMAL_FRAME: + ft_st = "normal"; + break; + case PJMEDIA_JB_ZERO_PREFETCH_FRAME: + ft_st = "prefetch"; + break; + case PJMEDIA_JB_ZERO_EMPTY_FRAME: + ft_st = "empty"; + break; + default: + ft_st = "unknown"; + break; } /* Print operation, size, frame count, frame type */ len = pj_ansi_snprintf(p, endp-p, "GET,%d,1,%s,,,,", fsize, ft_st); if ((len < 0) || (len >= endp-p)) - goto on_insuff_buffer; + goto on_insuff_buffer; p += len; /* Print JB state */ if (trace_jb_print_state(stream, &p, endp-p)) - goto on_insuff_buffer; + goto on_insuff_buffer; /* Print end of line */ if (endp-p < 2) - goto on_insuff_buffer; + goto on_insuff_buffer; *p++ = '\n'; /* Write and flush */ @@ -406,35 +405,35 @@ static void trace_jb_get(pjmedia_stream *stream, pjmedia_jb_frame_type ft, } static void trace_jb_put(pjmedia_stream *stream, const pjmedia_rtp_hdr *hdr, - unsigned payloadlen, unsigned frame_cnt) + unsigned payloadlen, unsigned frame_cnt) { char *p = stream->trace_jb_buf; char *endp = stream->trace_jb_buf + PJ_LOG_MAX_SIZE; pj_ssize_t len = 0; if (!TRACE_JB_OPENED(stream)) - return; + return; /* Print timestamp. */ if (trace_jb_print_timestamp(&p, endp-p)) - goto on_insuff_buffer; + goto on_insuff_buffer; /* Print operation, size, frame count, RTP info */ len = pj_ansi_snprintf(p, endp-p, - "PUT,%d,%d,,%d,%d,%d,", - payloadlen, frame_cnt, - pj_ntohs(hdr->seq), pj_ntohl(hdr->ts), hdr->m); + "PUT,%d,%d,,%d,%d,%d,", + payloadlen, frame_cnt, + pj_ntohs(hdr->seq), pj_ntohl(hdr->ts), hdr->m); if ((len < 0) || (len >= endp-p)) - goto on_insuff_buffer; + goto on_insuff_buffer; p += len; /* Print JB state */ if (trace_jb_print_state(stream, &p, endp-p)) - goto on_insuff_buffer; + goto on_insuff_buffer; /* Print end of line */ if (endp-p < 2) - goto on_insuff_buffer; + goto on_insuff_buffer; *p++ = '\n'; /* Write and flush */ @@ -464,20 +463,20 @@ static void send_keep_alive_packet(pjmedia_stream *stream) int pkt_len; TRC_((stream->port.info.name.ptr, - "Sending keep-alive (RTCP and empty RTP)")); + "Sending keep-alive (RTCP and empty RTP)")); /* Send RTP */ status = pjmedia_rtp_encode_rtp( &stream->enc->rtp, - stream->enc->pt, 0, - 1, - 0, - (const void**)&pkt, - &pkt_len); + stream->enc->pt, 0, + 1, + 0, + (const void**)&pkt, + &pkt_len); pj_assert(status == PJ_SUCCESS); pj_memcpy(stream->enc->out_pkt, pkt, pkt_len); pjmedia_transport_send_rtp(stream->transport, stream->enc->out_pkt, - pkt_len); + pkt_len); /* Send RTCP */ send_rtcp(stream, PJ_TRUE, PJ_FALSE, PJ_FALSE, PJ_FALSE); @@ -492,17 +491,17 @@ static void send_keep_alive_packet(pjmedia_stream *stream) const pj_str_t str_ka = PJMEDIA_STREAM_KA_USER_PKT; TRC_((stream->port.info.name.ptr, - "Sending keep-alive (custom RTP/RTCP packets)")); + "Sending keep-alive (custom RTP/RTCP packets)")); /* Send to RTP port */ pj_memcpy(stream->enc->out_pkt, str_ka.ptr, str_ka.slen); pkt_len = str_ka.slen; pjmedia_transport_send_rtp(stream->transport, stream->enc->out_pkt, - pkt_len); + pkt_len); /* Send to RTCP port */ pjmedia_transport_send_rtcp(stream->transport, stream->enc->out_pkt, - pkt_len); + pkt_len); #else @@ -510,7 +509,7 @@ static void send_keep_alive_packet(pjmedia_stream *stream) #endif } -#endif /* defined(PJMEDIA_STREAM_ENABLE_KA) */ +#endif /* defined(PJMEDIA_STREAM_ENABLE_KA) */ /* * play_callback() @@ -529,21 +528,21 @@ static pj_status_t get_frame( pjmedia_port *port, pjmedia_frame *frame) /* Return no frame is channel is paused */ if (channel->paused) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; + frame->type = PJMEDIA_FRAME_TYPE_NONE; + return PJ_SUCCESS; } if (stream->soft_start_cnt) { - if (stream->soft_start_cnt == PJMEDIA_STREAM_SOFT_START) { - PJ_LOG(4,(stream->port.info.name.ptr, - "Resetting jitter buffer in stream playback start")); - pj_mutex_lock( stream->jb_mutex ); - pjmedia_jbuf_reset(stream->jb); - pj_mutex_unlock( stream->jb_mutex ); - } - --stream->soft_start_cnt; - frame->type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; + if (stream->soft_start_cnt == PJMEDIA_STREAM_SOFT_START) { + PJ_LOG(4,(stream->port.info.name.ptr, + "Resetting jitter buffer in stream playback start")); + pj_mutex_lock( stream->jb_mutex ); + pjmedia_jbuf_reset(stream->jb); + pj_mutex_unlock( stream->jb_mutex ); + } + --stream->soft_start_cnt; + frame->type = PJMEDIA_FRAME_TYPE_NONE; + return PJ_SUCCESS; } /* Repeat get frame from the jitter buffer and decode the frame @@ -555,251 +554,251 @@ static pj_status_t get_frame( pjmedia_port *port, pjmedia_frame *frame) samples_required = PJMEDIA_PIA_SPF(&stream->port.info); samples_per_frame = stream->dec_ptime * - stream->codec_param.info.clock_rate * - stream->codec_param.info.channel_cnt / - 1000; + stream->codec_param.info.clock_rate * + stream->codec_param.info.channel_cnt / + 1000; p_out_samp = (pj_int16_t*) frame->buf; for (samples_count=0; samples_count < samples_required;) { - char frame_type; - pj_size_t frame_size = channel->out_pkt_size; - pj_uint32_t bit_info; - - if (stream->dec_buf && stream->dec_buf_pos < stream->dec_buf_count) { - unsigned nsamples_req = samples_required - samples_count; - unsigned nsamples_avail = stream->dec_buf_count - - stream->dec_buf_pos; - unsigned nsamples_copy = PJ_MIN(nsamples_req, nsamples_avail); - - pjmedia_copy_samples(p_out_samp + samples_count, - stream->dec_buf + stream->dec_buf_pos, - nsamples_copy); - samples_count += nsamples_copy; - stream->dec_buf_pos += nsamples_copy; - continue; - } - - /* Get frame from jitter buffer. */ - pjmedia_jbuf_get_frame2(stream->jb, channel->out_pkt, &frame_size, - &frame_type, &bit_info); + char frame_type; + pj_size_t frame_size = channel->out_pkt_size; + pj_uint32_t bit_info; + + if (stream->dec_buf && stream->dec_buf_pos < stream->dec_buf_count) { + unsigned nsamples_req = samples_required - samples_count; + unsigned nsamples_avail = stream->dec_buf_count - + stream->dec_buf_pos; + unsigned nsamples_copy = PJ_MIN(nsamples_req, nsamples_avail); + + pjmedia_copy_samples(p_out_samp + samples_count, + stream->dec_buf + stream->dec_buf_pos, + nsamples_copy); + samples_count += nsamples_copy; + stream->dec_buf_pos += nsamples_copy; + continue; + } + + /* Get frame from jitter buffer. */ + pjmedia_jbuf_get_frame2(stream->jb, channel->out_pkt, &frame_size, + &frame_type, &bit_info); #if TRACE_JB - trace_jb_get(stream, frame_type, frame_size); + trace_jb_get(stream, frame_type, frame_size); #endif - if (frame_type == PJMEDIA_JB_MISSING_FRAME) { - - /* Activate PLC */ - if (stream->codec->op->recover && - stream->codec_param.setting.plc && - stream->plc_cnt < stream->max_plc_cnt) - { - pjmedia_frame frame_out; - - frame_out.buf = p_out_samp + samples_count; - frame_out.size = frame->size - samples_count*2; - status = pjmedia_codec_recover(stream->codec, - (unsigned)frame_out.size, - &frame_out); - - ++stream->plc_cnt; - - } else { - status = -1; - } - - if (status != PJ_SUCCESS) { - /* Either PLC failed or PLC not supported/enabled */ - pjmedia_zero_samples(p_out_samp + samples_count, - samples_required - samples_count); - } - - if (frame_type != stream->jb_last_frm) { - /* Report changing frame type event */ - PJ_LOG(5,(stream->port.info.name.ptr, "Frame lost%s!", - (status == PJ_SUCCESS? ", recovered":""))); - - stream->jb_last_frm = frame_type; - stream->jb_last_frm_cnt = 1; - } else { - stream->jb_last_frm_cnt++; - } - - samples_count += samples_per_frame; - } else if (frame_type == PJMEDIA_JB_ZERO_EMPTY_FRAME) { - - const char *with_plc = ""; - - /* Jitter buffer is empty. If this is the first "empty" state, - * activate PLC to smoothen the fade-out, otherwise zero - * the frame. - */ - //Using this "if" will only invoke PLC for the first packet - //lost and not the subsequent ones. - //if (frame_type != stream->jb_last_frm) { - if (1) { - /* Activate PLC to smoothen the missing frame */ - if (stream->codec->op->recover && - stream->codec_param.setting.plc && - stream->plc_cnt < stream->max_plc_cnt) - { - pjmedia_frame frame_out; - - do { - frame_out.buf = p_out_samp + samples_count; - frame_out.size = frame->size - samples_count*2; - status = pjmedia_codec_recover(stream->codec, - (unsigned)frame_out.size, - &frame_out); - if (status != PJ_SUCCESS) - break; - - samples_count += samples_per_frame; - ++stream->plc_cnt; - - } while (samples_count < samples_required && - stream->plc_cnt < stream->max_plc_cnt); - - with_plc = ", plc invoked"; - } - } - - if (samples_count < samples_required) { - pjmedia_zero_samples(p_out_samp + samples_count, - samples_required - samples_count); - samples_count = samples_required; - } - - if (stream->jb_last_frm != frame_type) { - pjmedia_jb_state jb_state; - - /* Report changing frame type event */ - pjmedia_jbuf_get_state(stream->jb, &jb_state); - PJ_LOG(5,(stream->port.info.name.ptr, - "Jitter buffer empty (prefetch=%d)%s", - jb_state.prefetch, with_plc)); - - stream->jb_last_frm = frame_type; - stream->jb_last_frm_cnt = 1; - } else { - stream->jb_last_frm_cnt++; - } - break; - - } else if (frame_type != PJMEDIA_JB_NORMAL_FRAME) { - - const char *with_plc = ""; - - /* It can only be PJMEDIA_JB_ZERO_PREFETCH frame */ - pj_assert(frame_type == PJMEDIA_JB_ZERO_PREFETCH_FRAME); - - /* Always activate PLC when it's available.. */ - if (stream->codec->op->recover && - stream->codec_param.setting.plc && - stream->plc_cnt < stream->max_plc_cnt) - { - pjmedia_frame frame_out; - - do { - frame_out.buf = p_out_samp + samples_count; - frame_out.size = frame->size - samples_count*2; - status = pjmedia_codec_recover(stream->codec, - (unsigned)frame_out.size, - &frame_out); - if (status != PJ_SUCCESS) - break; - samples_count += samples_per_frame; - - ++stream->plc_cnt; - - } while (samples_count < samples_required && - stream->plc_cnt < stream->max_plc_cnt); - - with_plc = ", plc invoked"; - } - - if (samples_count < samples_required) { - pjmedia_zero_samples(p_out_samp + samples_count, - samples_required - samples_count); - samples_count = samples_required; - } - - if (stream->jb_last_frm != frame_type) { - pjmedia_jb_state jb_state; - - /* Report changing frame type event */ - pjmedia_jbuf_get_state(stream->jb, &jb_state); - PJ_LOG(5,(stream->port.info.name.ptr, - "Jitter buffer is bufferring (prefetch=%d)%s", - jb_state.prefetch, with_plc)); - - stream->jb_last_frm = frame_type; - stream->jb_last_frm_cnt = 1; - } else { - stream->jb_last_frm_cnt++; - } - break; - - } else { - /* Got "NORMAL" frame from jitter buffer */ - pjmedia_frame frame_in, frame_out; - pj_bool_t use_dec_buf = PJ_FALSE; - - stream->plc_cnt = 0; - - /* Decode */ - frame_in.buf = channel->out_pkt; - frame_in.size = frame_size; - frame_in.bit_info = bit_info; - frame_in.type = PJMEDIA_FRAME_TYPE_AUDIO; /* ignored */ - - frame_out.buf = p_out_samp + samples_count; - frame_out.size = frame->size - samples_count*BYTES_PER_SAMPLE; - if (stream->dec_buf && - bit_info * sizeof(pj_int16_t) > frame_out.size) - { - stream->dec_buf_pos = 0; - stream->dec_buf_count = bit_info; - - use_dec_buf = PJ_TRUE; - frame_out.buf = stream->dec_buf; - frame_out.size = stream->dec_buf_size; - } - - status = pjmedia_codec_decode( stream->codec, &frame_in, - (unsigned)frame_out.size, - &frame_out); - if (status != 0) { - LOGERR_((port->info.name.ptr, status, - "codec decode() error")); - - if (use_dec_buf) { - pjmedia_zero_samples(p_out_samp + samples_count, - samples_per_frame); - } else { - pjmedia_zero_samples(stream->dec_buf, - stream->dec_buf_count); - } - } else if (use_dec_buf) { - stream->dec_buf_count = (unsigned)frame_out.size / - sizeof(pj_int16_t); - } - - if (stream->jb_last_frm != frame_type) { - /* Report changing frame type event */ - PJ_LOG(5,(stream->port.info.name.ptr, - "Jitter buffer starts returning normal frames " - "(after %d empty/lost)", - stream->jb_last_frm_cnt, stream->jb_last_frm)); - - stream->jb_last_frm = frame_type; - stream->jb_last_frm_cnt = 1; - } else { - stream->jb_last_frm_cnt++; - } - if (!use_dec_buf) - samples_count += samples_per_frame; - } + if (frame_type == PJMEDIA_JB_MISSING_FRAME) { + + /* Activate PLC */ + if (stream->codec->op->recover && + stream->codec_param.setting.plc && + stream->plc_cnt < stream->max_plc_cnt) + { + pjmedia_frame frame_out; + + frame_out.buf = p_out_samp + samples_count; + frame_out.size = frame->size - samples_count*2; + status = pjmedia_codec_recover(stream->codec, + (unsigned)frame_out.size, + &frame_out); + + ++stream->plc_cnt; + + } else { + status = -1; + } + + if (status != PJ_SUCCESS) { + /* Either PLC failed or PLC not supported/enabled */ + pjmedia_zero_samples(p_out_samp + samples_count, + samples_required - samples_count); + } + + if (frame_type != stream->jb_last_frm) { + /* Report changing frame type event */ + PJ_LOG(5,(stream->port.info.name.ptr, "Frame lost%s!", + (status == PJ_SUCCESS? ", recovered":""))); + + stream->jb_last_frm = frame_type; + stream->jb_last_frm_cnt = 1; + } else { + stream->jb_last_frm_cnt++; + } + + samples_count += samples_per_frame; + } else if (frame_type == PJMEDIA_JB_ZERO_EMPTY_FRAME) { + + const char *with_plc = ""; + + /* Jitter buffer is empty. If this is the first "empty" state, + * activate PLC to smoothen the fade-out, otherwise zero + * the frame. + */ + //Using this "if" will only invoke PLC for the first packet + //lost and not the subsequent ones. + //if (frame_type != stream->jb_last_frm) { + if (1) { + /* Activate PLC to smoothen the missing frame */ + if (stream->codec->op->recover && + stream->codec_param.setting.plc && + stream->plc_cnt < stream->max_plc_cnt) + { + pjmedia_frame frame_out; + + do { + frame_out.buf = p_out_samp + samples_count; + frame_out.size = frame->size - samples_count*2; + status = pjmedia_codec_recover(stream->codec, + (unsigned)frame_out.size, + &frame_out); + if (status != PJ_SUCCESS) + break; + + samples_count += samples_per_frame; + ++stream->plc_cnt; + + } while (samples_count < samples_required && + stream->plc_cnt < stream->max_plc_cnt); + + with_plc = ", plc invoked"; + } + } + + if (samples_count < samples_required) { + pjmedia_zero_samples(p_out_samp + samples_count, + samples_required - samples_count); + samples_count = samples_required; + } + + if (stream->jb_last_frm != frame_type) { + pjmedia_jb_state jb_state; + + /* Report changing frame type event */ + pjmedia_jbuf_get_state(stream->jb, &jb_state); + PJ_LOG(5,(stream->port.info.name.ptr, + "Jitter buffer empty (prefetch=%d)%s", + jb_state.prefetch, with_plc)); + + stream->jb_last_frm = frame_type; + stream->jb_last_frm_cnt = 1; + } else { + stream->jb_last_frm_cnt++; + } + break; + + } else if (frame_type != PJMEDIA_JB_NORMAL_FRAME) { + + const char *with_plc = ""; + + /* It can only be PJMEDIA_JB_ZERO_PREFETCH frame */ + pj_assert(frame_type == PJMEDIA_JB_ZERO_PREFETCH_FRAME); + + /* Always activate PLC when it's available.. */ + if (stream->codec->op->recover && + stream->codec_param.setting.plc && + stream->plc_cnt < stream->max_plc_cnt) + { + pjmedia_frame frame_out; + + do { + frame_out.buf = p_out_samp + samples_count; + frame_out.size = frame->size - samples_count*2; + status = pjmedia_codec_recover(stream->codec, + (unsigned)frame_out.size, + &frame_out); + if (status != PJ_SUCCESS) + break; + samples_count += samples_per_frame; + + ++stream->plc_cnt; + + } while (samples_count < samples_required && + stream->plc_cnt < stream->max_plc_cnt); + + with_plc = ", plc invoked"; + } + + if (samples_count < samples_required) { + pjmedia_zero_samples(p_out_samp + samples_count, + samples_required - samples_count); + samples_count = samples_required; + } + + if (stream->jb_last_frm != frame_type) { + pjmedia_jb_state jb_state; + + /* Report changing frame type event */ + pjmedia_jbuf_get_state(stream->jb, &jb_state); + PJ_LOG(5,(stream->port.info.name.ptr, + "Jitter buffer is bufferring (prefetch=%d)%s", + jb_state.prefetch, with_plc)); + + stream->jb_last_frm = frame_type; + stream->jb_last_frm_cnt = 1; + } else { + stream->jb_last_frm_cnt++; + } + break; + + } else { + /* Got "NORMAL" frame from jitter buffer */ + pjmedia_frame frame_in, frame_out; + pj_bool_t use_dec_buf = PJ_FALSE; + + stream->plc_cnt = 0; + + /* Decode */ + frame_in.buf = channel->out_pkt; + frame_in.size = frame_size; + frame_in.bit_info = bit_info; + frame_in.type = PJMEDIA_FRAME_TYPE_AUDIO; /* ignored */ + + frame_out.buf = p_out_samp + samples_count; + frame_out.size = frame->size - samples_count*BYTES_PER_SAMPLE; + if (stream->dec_buf && + bit_info * sizeof(pj_int16_t) > frame_out.size) + { + stream->dec_buf_pos = 0; + stream->dec_buf_count = bit_info; + + use_dec_buf = PJ_TRUE; + frame_out.buf = stream->dec_buf; + frame_out.size = stream->dec_buf_size; + } + + status = pjmedia_codec_decode( stream->codec, &frame_in, + (unsigned)frame_out.size, + &frame_out); + if (status != 0) { + LOGERR_((port->info.name.ptr, status, + "codec decode() error")); + + if (use_dec_buf) { + pjmedia_zero_samples(p_out_samp + samples_count, + samples_per_frame); + } else { + pjmedia_zero_samples(stream->dec_buf, + stream->dec_buf_count); + } + } else if (use_dec_buf) { + stream->dec_buf_count = (unsigned)frame_out.size / + sizeof(pj_int16_t); + } + + if (stream->jb_last_frm != frame_type) { + /* Report changing frame type event */ + PJ_LOG(5,(stream->port.info.name.ptr, + "Jitter buffer starts returning normal frames " + "(after %d empty/lost)", + stream->jb_last_frm_cnt, stream->jb_last_frm)); + + stream->jb_last_frm = frame_type; + stream->jb_last_frm_cnt = 1; + } else { + stream->jb_last_frm_cnt++; + } + if (!use_dec_buf) + samples_count += samples_per_frame; + } } @@ -810,12 +809,12 @@ static pj_status_t get_frame( pjmedia_port *port, pjmedia_frame *frame) * (it can happen when jitter buffer returns PJMEDIA_JB_ZERO_EMPTY_FRAME). */ if (samples_count == 0) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; } else { - frame->type = PJMEDIA_FRAME_TYPE_AUDIO; - frame->size = samples_count * BYTES_PER_SAMPLE; - frame->timestamp.u64 = 0; + frame->type = PJMEDIA_FRAME_TYPE_AUDIO; + frame->size = samples_count * BYTES_PER_SAMPLE; + frame->timestamp.u64 = 0; } return PJ_SUCCESS; @@ -835,8 +834,8 @@ static pj_status_t get_frame_ext( pjmedia_port *port, pjmedia_frame *frame) /* Return no frame if channel is paused */ if (channel->paused) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - return PJ_SUCCESS; + frame->type = PJMEDIA_FRAME_TYPE_NONE; + return PJ_SUCCESS; } /* Repeat get frame from the jitter buffer and decode the frame @@ -845,124 +844,124 @@ static pj_status_t get_frame_ext( pjmedia_port *port, pjmedia_frame *frame) samples_required = PJMEDIA_PIA_SPF(&stream->port.info); samples_per_frame = stream->codec_param.info.frm_ptime * - stream->codec_param.info.clock_rate * - stream->codec_param.info.channel_cnt / - 1000; + stream->codec_param.info.clock_rate * + stream->codec_param.info.channel_cnt / + 1000; pj_bzero(f, sizeof(pjmedia_frame_ext)); f->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; while (f->samples_cnt < samples_required) { - char frame_type; - pj_size_t frame_size = channel->out_pkt_size; - pj_uint32_t bit_info; + char frame_type; + pj_size_t frame_size = channel->out_pkt_size; + pj_uint32_t bit_info; - /* Lock jitter buffer mutex first */ - pj_mutex_lock( stream->jb_mutex ); + /* Lock jitter buffer mutex first */ + pj_mutex_lock( stream->jb_mutex ); - /* Get frame from jitter buffer. */ - pjmedia_jbuf_get_frame2(stream->jb, channel->out_pkt, &frame_size, - &frame_type, &bit_info); + /* Get frame from jitter buffer. */ + pjmedia_jbuf_get_frame2(stream->jb, channel->out_pkt, &frame_size, + &frame_type, &bit_info); #if TRACE_JB - trace_jb_get(stream, frame_type, frame_size); + trace_jb_get(stream, frame_type, frame_size); #endif - /* Unlock jitter buffer mutex. */ - pj_mutex_unlock( stream->jb_mutex ); - - if (frame_type == PJMEDIA_JB_NORMAL_FRAME) { - /* Got "NORMAL" frame from jitter buffer */ - pjmedia_frame frame_in; - - /* Decode */ - frame_in.buf = channel->out_pkt; - frame_in.size = frame_size; - frame_in.bit_info = bit_info; - frame_in.type = PJMEDIA_FRAME_TYPE_AUDIO; - - status = pjmedia_codec_decode( stream->codec, &frame_in, - 0, frame); - if (status != PJ_SUCCESS) { - LOGERR_((port->info.name.ptr, status, - "codec decode() error")); - pjmedia_frame_ext_append_subframe(f, NULL, 0, - (pj_uint16_t)samples_per_frame); - } - - if (stream->jb_last_frm != frame_type) { - /* Report changing frame type event */ - PJ_LOG(5,(stream->port.info.name.ptr, - "Jitter buffer starts returning normal frames " - "(after %d empty/lost)", - stream->jb_last_frm_cnt, stream->jb_last_frm)); - - stream->jb_last_frm = frame_type; - stream->jb_last_frm_cnt = 1; - } else { - stream->jb_last_frm_cnt++; - } - - } else { - - /* Try to generate frame by invoking PLC (when any) */ - status = PJ_SUCCESS; - if (stream->codec->op->recover) { - status = pjmedia_codec_recover(stream->codec, 0, frame); - } - - /* No PLC or PLC failed */ - if (!stream->codec->op->recover || status != PJ_SUCCESS) { - pjmedia_frame_ext_append_subframe(f, NULL, 0, - (pj_uint16_t)samples_per_frame); - } - - if (frame_type == PJMEDIA_JB_MISSING_FRAME) { - if (frame_type != stream->jb_last_frm) { - /* Report changing frame type event */ - PJ_LOG(5,(stream->port.info.name.ptr, "Frame lost!")); - - stream->jb_last_frm = frame_type; - stream->jb_last_frm_cnt = 1; - } else { - stream->jb_last_frm_cnt++; - } - } else if (frame_type == PJMEDIA_JB_ZERO_EMPTY_FRAME) { - if (frame_type != stream->jb_last_frm) { - pjmedia_jb_state jb_state; - - /* Report changing frame type event */ - pjmedia_jbuf_get_state(stream->jb, &jb_state); - PJ_LOG(5,(stream->port.info.name.ptr, - "Jitter buffer empty (prefetch=%d)", - jb_state.prefetch)); - - stream->jb_last_frm = frame_type; - stream->jb_last_frm_cnt = 1; - } else { - stream->jb_last_frm_cnt++; - } - } else { - - /* It can only be PJMEDIA_JB_ZERO_PREFETCH frame */ - pj_assert(frame_type == PJMEDIA_JB_ZERO_PREFETCH_FRAME); - - if (stream->jb_last_frm != frame_type) { - pjmedia_jb_state jb_state; - - /* Report changing frame type event */ - pjmedia_jbuf_get_state(stream->jb, &jb_state); - PJ_LOG(5,(stream->port.info.name.ptr, - "Jitter buffer is bufferring (prefetch=%d)", - jb_state.prefetch)); - - stream->jb_last_frm = frame_type; - stream->jb_last_frm_cnt = 1; - } else { - stream->jb_last_frm_cnt++; - } - } - } + /* Unlock jitter buffer mutex. */ + pj_mutex_unlock( stream->jb_mutex ); + + if (frame_type == PJMEDIA_JB_NORMAL_FRAME) { + /* Got "NORMAL" frame from jitter buffer */ + pjmedia_frame frame_in; + + /* Decode */ + frame_in.buf = channel->out_pkt; + frame_in.size = frame_size; + frame_in.bit_info = bit_info; + frame_in.type = PJMEDIA_FRAME_TYPE_AUDIO; + + status = pjmedia_codec_decode( stream->codec, &frame_in, + 0, frame); + if (status != PJ_SUCCESS) { + LOGERR_((port->info.name.ptr, status, + "codec decode() error")); + pjmedia_frame_ext_append_subframe(f, NULL, 0, + (pj_uint16_t)samples_per_frame); + } + + if (stream->jb_last_frm != frame_type) { + /* Report changing frame type event */ + PJ_LOG(5,(stream->port.info.name.ptr, + "Jitter buffer starts returning normal frames " + "(after %d empty/lost)", + stream->jb_last_frm_cnt, stream->jb_last_frm)); + + stream->jb_last_frm = frame_type; + stream->jb_last_frm_cnt = 1; + } else { + stream->jb_last_frm_cnt++; + } + + } else { + + /* Try to generate frame by invoking PLC (when any) */ + status = PJ_SUCCESS; + if (stream->codec->op->recover) { + status = pjmedia_codec_recover(stream->codec, 0, frame); + } + + /* No PLC or PLC failed */ + if (!stream->codec->op->recover || status != PJ_SUCCESS) { + pjmedia_frame_ext_append_subframe(f, NULL, 0, + (pj_uint16_t)samples_per_frame); + } + + if (frame_type == PJMEDIA_JB_MISSING_FRAME) { + if (frame_type != stream->jb_last_frm) { + /* Report changing frame type event */ + PJ_LOG(5,(stream->port.info.name.ptr, "Frame lost!")); + + stream->jb_last_frm = frame_type; + stream->jb_last_frm_cnt = 1; + } else { + stream->jb_last_frm_cnt++; + } + } else if (frame_type == PJMEDIA_JB_ZERO_EMPTY_FRAME) { + if (frame_type != stream->jb_last_frm) { + pjmedia_jb_state jb_state; + + /* Report changing frame type event */ + pjmedia_jbuf_get_state(stream->jb, &jb_state); + PJ_LOG(5,(stream->port.info.name.ptr, + "Jitter buffer empty (prefetch=%d)", + jb_state.prefetch)); + + stream->jb_last_frm = frame_type; + stream->jb_last_frm_cnt = 1; + } else { + stream->jb_last_frm_cnt++; + } + } else { + + /* It can only be PJMEDIA_JB_ZERO_PREFETCH frame */ + pj_assert(frame_type == PJMEDIA_JB_ZERO_PREFETCH_FRAME); + + if (stream->jb_last_frm != frame_type) { + pjmedia_jb_state jb_state; + + /* Report changing frame type event */ + pjmedia_jbuf_get_state(stream->jb, &jb_state); + PJ_LOG(5,(stream->port.info.name.ptr, + "Jitter buffer is bufferring (prefetch=%d)", + jb_state.prefetch)); + + stream->jb_last_frm = frame_type; + stream->jb_last_frm_cnt = 1; + } else { + stream->jb_last_frm_cnt++; + } + } + } } return PJ_SUCCESS; @@ -973,8 +972,8 @@ static pj_status_t get_frame_ext( pjmedia_port *port, pjmedia_frame *frame) * Transmit DTMF */ static void create_dtmf_payload(pjmedia_stream *stream, - struct pjmedia_frame *frame_out, - int forced_last, int *first, int *last) + struct pjmedia_frame *frame_out, + int forced_last, int *first, int *last) { pjmedia_rtp_dtmf_event *event; struct dtmf *digit = &stream->tx_dtmf_buf[0]; @@ -986,39 +985,39 @@ static void create_dtmf_payload(pjmedia_stream *stream, event = (pjmedia_rtp_dtmf_event*) frame_out->buf; if (digit->duration == 0) { - PJ_LOG(5,(stream->port.info.name.ptr, "Sending DTMF digit id %c", - digitmap[digit->event])); - *first = 1; + PJ_LOG(5,(stream->port.info.name.ptr, "Sending DTMF digit id %c", + digitmap[digit->event])); + *first = 1; } digit->duration += stream->rtp_tx_ts_len_per_pkt; if (digit->duration >= stream->dtmf_duration) - digit->duration = stream->dtmf_duration; + digit->duration = stream->dtmf_duration; event->event = (pj_uint8_t)digit->event; event->e_vol = 10; event->duration = pj_htons((pj_uint16_t)digit->duration); if (forced_last) { - digit->duration = stream->dtmf_duration; + digit->duration = stream->dtmf_duration; } if (digit->duration >= stream->dtmf_duration) { - event->e_vol |= 0x80; + event->e_vol |= 0x80; - if (++digit->ebit_cnt >= DTMF_EBIT_RETRANSMIT_CNT) { - *last = 1; + if (++digit->ebit_cnt >= DTMF_EBIT_RETRANSMIT_CNT) { + *last = 1; - /* Prepare next digit. */ - pj_mutex_lock(stream->jb_mutex); + /* Prepare next digit. */ + pj_mutex_lock(stream->jb_mutex); - pj_array_erase(stream->tx_dtmf_buf, sizeof(stream->tx_dtmf_buf[0]), - stream->tx_dtmf_count, 0); - --stream->tx_dtmf_count; + pj_array_erase(stream->tx_dtmf_buf, sizeof(stream->tx_dtmf_buf[0]), + stream->tx_dtmf_count, 0); + --stream->tx_dtmf_count; - pj_mutex_unlock(stream->jb_mutex); - } + pj_mutex_unlock(stream->jb_mutex); + } } frame_out->size = 4; @@ -1026,20 +1025,20 @@ static void create_dtmf_payload(pjmedia_stream *stream, static pj_status_t build_rtcp_fb(pjmedia_stream *stream, void *buf, - pj_size_t *length) + pj_size_t *length) { pj_status_t status; /* Generic NACK */ if (stream->send_rtcp_fb_nack && stream->rtcp_fb_nack.pid >= 0) { - status = pjmedia_rtcp_fb_build_nack(&stream->rtcp, buf, length, 1, - &stream->rtcp_fb_nack); - if (status != PJ_SUCCESS) - return status; + status = pjmedia_rtcp_fb_build_nack(&stream->rtcp, buf, length, 1, + &stream->rtcp_fb_nack); + if (status != PJ_SUCCESS) + return status; - /* Reset Packet ID */ - stream->rtcp_fb_nack.pid = -1; + /* Reset Packet ID */ + stream->rtcp_fb_nack.pid = -1; } return PJ_SUCCESS; @@ -1050,10 +1049,10 @@ static pj_status_t build_rtcp_fb(pjmedia_stream *stream, void *buf, * Publish transport error event. */ static void publish_tp_event(pjmedia_event_type event_type, - pj_status_t status, - pj_bool_t is_rtp, - pjmedia_dir dir, - pjmedia_stream *stream) + pj_status_t status, + pj_bool_t is_rtp, + pjmedia_dir dir, + pjmedia_stream *stream) { pjmedia_event ev; pj_timestamp ts_now; @@ -1063,7 +1062,7 @@ static void publish_tp_event(pjmedia_event_type event_type, /* Publish event. */ pjmedia_event_init(&ev, event_type, - &ts_now, stream); + &ts_now, stream); ev.data.med_tp_err.type = PJMEDIA_TYPE_AUDIO; ev.data.med_tp_err.is_rtp = is_rtp; ev.data.med_tp_err.dir = dir; @@ -1074,10 +1073,10 @@ static void publish_tp_event(pjmedia_event_type event_type, static pj_status_t send_rtcp(pjmedia_stream *stream, - pj_bool_t with_sdes, - pj_bool_t with_bye, - pj_bool_t with_xr, - pj_bool_t with_fb) + pj_bool_t with_sdes, + pj_bool_t with_bye, + pj_bool_t with_xr, + pj_bool_t with_fb) { void *sr_rr_pkt; pj_uint8_t *pkt; @@ -1092,115 +1091,115 @@ static pj_status_t send_rtcp(pjmedia_stream *stream, #endif if (with_sdes || with_bye || with_xr || with_fb) { - pkt = (pj_uint8_t*) stream->out_rtcp_pkt; - pj_memcpy(pkt, sr_rr_pkt, len); - max_len = stream->out_rtcp_pkt_size; + pkt = (pj_uint8_t*) stream->out_rtcp_pkt; + pj_memcpy(pkt, sr_rr_pkt, len); + max_len = stream->out_rtcp_pkt_size; } else { - pkt = (pj_uint8_t*)sr_rr_pkt; - max_len = len; + pkt = (pj_uint8_t*)sr_rr_pkt; + max_len = len; } /* RTCP FB must be sent in compound (i.e: with RR/SR and SDES) */ if (with_fb) - with_sdes = PJ_TRUE; + with_sdes = PJ_TRUE; /* Build RTCP SDES packet */ if (with_sdes) { - pjmedia_rtcp_sdes sdes; - pj_size_t sdes_len; - - pj_bzero(&sdes, sizeof(sdes)); - sdes.cname = stream->cname; - sdes_len = max_len - len; - status = pjmedia_rtcp_build_rtcp_sdes(&stream->rtcp, pkt+len, - &sdes_len, &sdes); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stream->port.info.name.ptr, status, - "Error generating RTCP SDES")); - } else { - len += (int)sdes_len; - } + pjmedia_rtcp_sdes sdes; + pj_size_t sdes_len; + + pj_bzero(&sdes, sizeof(sdes)); + sdes.cname = stream->cname; + sdes_len = max_len - len; + status = pjmedia_rtcp_build_rtcp_sdes(&stream->rtcp, pkt+len, + &sdes_len, &sdes); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stream->port.info.name.ptr, status, + "Error generating RTCP SDES")); + } else { + len += (int)sdes_len; + } } if (with_fb) { - pj_size_t fb_len = max_len - len; - status = build_rtcp_fb(stream, pkt+len, &fb_len); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stream->port.info.name.ptr, status, - "Error generating RTCP FB")); - } else { - len += (int)fb_len; - } + pj_size_t fb_len = max_len - len; + status = build_rtcp_fb(stream, pkt+len, &fb_len); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stream->port.info.name.ptr, status, + "Error generating RTCP FB")); + } else { + len += (int)fb_len; + } } /* Build RTCP XR packet */ #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) if (with_xr) { - int i; - pjmedia_jb_state jb_state; - void *xr_pkt; - int xr_len; - - /* Update RTCP XR with current JB states */ - pjmedia_jbuf_get_state(stream->jb, &jb_state); - - i = jb_state.avg_delay; - status = pjmedia_rtcp_xr_update_info(&stream->rtcp.xr_session, - PJMEDIA_RTCP_XR_INFO_JB_NOM, i); - pj_assert(status == PJ_SUCCESS); - - i = jb_state.max_delay; - status = pjmedia_rtcp_xr_update_info(&stream->rtcp.xr_session, - PJMEDIA_RTCP_XR_INFO_JB_MAX, i); - pj_assert(status == PJ_SUCCESS); - - pjmedia_rtcp_build_rtcp_xr(&stream->rtcp.xr_session, 0, - &xr_pkt, &xr_len); - - if (xr_len + len <= max_len) { - pj_memcpy(pkt+len, xr_pkt, xr_len); - len += xr_len; - - /* Send the RTCP XR to third-party destination if specified */ - if (stream->rtcp_xr_dest_len) { - pjmedia_transport_send_rtcp2(stream->transport, - &stream->rtcp_xr_dest, - stream->rtcp_xr_dest_len, - xr_pkt, xr_len); - } - - } else { - PJ_PERROR(4,(stream->port.info.name.ptr, PJ_ETOOBIG, - "Error generating RTCP-XR")); - } + int i; + pjmedia_jb_state jb_state; + void *xr_pkt; + int xr_len; + + /* Update RTCP XR with current JB states */ + pjmedia_jbuf_get_state(stream->jb, &jb_state); + + i = jb_state.avg_delay; + status = pjmedia_rtcp_xr_update_info(&stream->rtcp.xr_session, + PJMEDIA_RTCP_XR_INFO_JB_NOM, i); + pj_assert(status == PJ_SUCCESS); + + i = jb_state.max_delay; + status = pjmedia_rtcp_xr_update_info(&stream->rtcp.xr_session, + PJMEDIA_RTCP_XR_INFO_JB_MAX, i); + pj_assert(status == PJ_SUCCESS); + + pjmedia_rtcp_build_rtcp_xr(&stream->rtcp.xr_session, 0, + &xr_pkt, &xr_len); + + if (xr_len + len <= max_len) { + pj_memcpy(pkt+len, xr_pkt, xr_len); + len += xr_len; + + /* Send the RTCP XR to third-party destination if specified */ + if (stream->rtcp_xr_dest_len) { + pjmedia_transport_send_rtcp2(stream->transport, + &stream->rtcp_xr_dest, + stream->rtcp_xr_dest_len, + xr_pkt, xr_len); + } + + } else { + PJ_PERROR(4,(stream->port.info.name.ptr, PJ_ETOOBIG, + "Error generating RTCP-XR")); + } } #endif /* Build RTCP BYE packet */ if (with_bye) { - pj_size_t bye_len; + pj_size_t bye_len; - bye_len = max_len - len; - status = pjmedia_rtcp_build_rtcp_bye(&stream->rtcp, pkt+len, - &bye_len, NULL); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stream->port.info.name.ptr, status, - "Error generating RTCP BYE")); - } else { - len += (int)bye_len; - } + bye_len = max_len - len; + status = pjmedia_rtcp_build_rtcp_bye(&stream->rtcp, pkt+len, + &bye_len, NULL); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stream->port.info.name.ptr, status, + "Error generating RTCP BYE")); + } else { + len += (int)bye_len; + } } /* Send! */ status = pjmedia_transport_send_rtcp(stream->transport, pkt, len); if (status != PJ_SUCCESS) { - if (stream->rtcp_tx_err_cnt++ == 0) { - LOGERR_((stream->port.info.name.ptr, status, - "Error sending RTCP")); - } - if (stream->rtcp_tx_err_cnt > SEND_ERR_COUNT_TO_REPORT) { - stream->rtcp_tx_err_cnt = 0; - } + if (stream->rtcp_tx_err_cnt++ == 0) { + LOGERR_((stream->port.info.name.ptr, status, + "Error sending RTCP")); + } + if (stream->rtcp_tx_err_cnt > SEND_ERR_COUNT_TO_REPORT) { + stream->rtcp_tx_err_cnt = 0; + } } return status; @@ -1221,32 +1220,32 @@ static void check_tx_rtcp(pjmedia_stream *stream, pj_uint32_t timestamp) if (stream->rtcp_last_tx == 0) { - stream->rtcp_last_tx = timestamp; + stream->rtcp_last_tx = timestamp; } else if (timestamp - stream->rtcp_last_tx >= stream->rtcp_interval) { - pj_bool_t with_xr = PJ_FALSE; - pj_status_t status; + pj_bool_t with_xr = PJ_FALSE; + pj_status_t status; #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) - if (stream->rtcp.xr_enabled) { - if (stream->rtcp_xr_last_tx == 0) { - stream->rtcp_xr_last_tx = timestamp; - } else if (timestamp - stream->rtcp_xr_last_tx >= - stream->rtcp_xr_interval) - { - with_xr = PJ_TRUE; - - /* Update last tx RTCP XR */ - stream->rtcp_xr_last_tx = timestamp; - } - } + if (stream->rtcp.xr_enabled) { + if (stream->rtcp_xr_last_tx == 0) { + stream->rtcp_xr_last_tx = timestamp; + } else if (timestamp - stream->rtcp_xr_last_tx >= + stream->rtcp_xr_interval) + { + with_xr = PJ_TRUE; + + /* Update last tx RTCP XR */ + stream->rtcp_xr_last_tx = timestamp; + } + } #endif - status = send_rtcp(stream, !stream->rtcp_sdes_bye_disabled, PJ_FALSE, - with_xr, PJ_FALSE); - if (status == PJ_SUCCESS) { - stream->rtcp_last_tx = timestamp; - } + status = send_rtcp(stream, !stream->rtcp_sdes_bye_disabled, PJ_FALSE, + with_xr, PJ_FALSE); + if (status == PJ_SUCCESS) { + stream->rtcp_last_tx = timestamp; + } } } @@ -1256,58 +1255,58 @@ static void check_tx_rtcp(pjmedia_stream *stream, pj_uint32_t timestamp) * (such as when different iLBC modes are used by local and remote) */ static void rebuffer(pjmedia_stream *stream, - pjmedia_frame *frame) + pjmedia_frame *frame) { /* How many samples are needed */ unsigned count; /* Normalize frame */ if (frame->type != PJMEDIA_FRAME_TYPE_AUDIO) - frame->size = 0; + frame->size = 0; /* Remove used frame from the buffer. */ if (stream->enc_buf_pos) { - if (stream->enc_buf_count) { - pj_memmove(stream->enc_buf, - stream->enc_buf + stream->enc_buf_pos, - (stream->enc_buf_count << 1)); - } - stream->enc_buf_pos = 0; + if (stream->enc_buf_count) { + pj_memmove(stream->enc_buf, + stream->enc_buf + stream->enc_buf_pos, + (stream->enc_buf_count << 1)); + } + stream->enc_buf_pos = 0; } /* Make sure we have space to store the new frame */ pj_assert(stream->enc_buf_count + (frame->size >> 1) < - stream->enc_buf_size); + stream->enc_buf_size); /* Append new frame to the buffer */ if (frame->size) { - /* Handle case when there is no port transmitting to this port */ - if (frame->buf) { - pj_memcpy(stream->enc_buf + stream->enc_buf_count, - frame->buf, frame->size); - } else { - pj_bzero(stream->enc_buf + stream->enc_buf_count, frame->size); - } - stream->enc_buf_count += ((unsigned)frame->size >> 1); + /* Handle case when there is no port transmitting to this port */ + if (frame->buf) { + pj_memcpy(stream->enc_buf + stream->enc_buf_count, + frame->buf, frame->size); + } else { + pj_bzero(stream->enc_buf + stream->enc_buf_count, frame->size); + } + stream->enc_buf_count += ((unsigned)frame->size >> 1); } /* How many samples are needed */ count = stream->codec_param.info.enc_ptime * - PJMEDIA_PIA_SRATE(&stream->port.info) / 1000; + PJMEDIA_PIA_SRATE(&stream->port.info) / 1000; /* See if we have enough samples */ if (stream->enc_buf_count >= count) { - frame->type = PJMEDIA_FRAME_TYPE_AUDIO; - frame->buf = stream->enc_buf; - frame->size = (count << 1); + frame->type = PJMEDIA_FRAME_TYPE_AUDIO; + frame->buf = stream->enc_buf; + frame->size = (count << 1); - stream->enc_buf_pos = count; - stream->enc_buf_count -= count; + stream->enc_buf_pos = count; + stream->enc_buf_count -= count; } else { - /* We don't have enough samples */ - frame->type = PJMEDIA_FRAME_TYPE_NONE; + /* We don't have enough samples */ + frame->type = PJMEDIA_FRAME_TYPE_NONE; } } @@ -1316,7 +1315,7 @@ static void rebuffer(pjmedia_stream *stream, * put_frame_imp() */ static pj_status_t put_frame_imp( pjmedia_port *port, - pjmedia_frame *frame ) + pjmedia_frame *frame ) { pjmedia_stream *stream = (pjmedia_stream*) port->port_data.pdata; pjmedia_channel *channel = stream->enc; @@ -1335,12 +1334,12 @@ static pj_status_t put_frame_imp( pjmedia_port *port, if (stream->use_ka) { pj_uint32_t dtx_duration, ka_interval; - pj_time_val now, tmp; + pj_time_val now, tmp; - pj_gettimeofday(&now); - tmp = now; - PJ_TIME_VAL_SUB(tmp, stream->last_frm_ts_sent); - dtx_duration = PJ_TIME_VAL_MSEC(tmp); + pj_gettimeofday(&now); + tmp = now; + PJ_TIME_VAL_SUB(tmp, stream->last_frm_ts_sent); + dtx_duration = PJ_TIME_VAL_MSEC(tmp); if (stream->start_ka_count) { ka_interval = stream->start_ka_interval; } else { @@ -1358,38 +1357,38 @@ static pj_status_t put_frame_imp( pjmedia_port *port, /* Number of samples in the frame */ if (frame->type == PJMEDIA_FRAME_TYPE_AUDIO) - ts_len = ((unsigned)frame->size >> 1) / - stream->codec_param.info.channel_cnt; + ts_len = ((unsigned)frame->size >> 1) / + stream->codec_param.info.channel_cnt; else if (frame->type == PJMEDIA_FRAME_TYPE_EXTENDED) - ts_len = PJMEDIA_PIA_SPF(&stream->port.info) / - PJMEDIA_PIA_CCNT(&stream->port.info); + ts_len = PJMEDIA_PIA_SPF(&stream->port.info) / + PJMEDIA_PIA_CCNT(&stream->port.info); else - ts_len = 0; + ts_len = 0; #if defined(PJMEDIA_HANDLE_G722_MPEG_BUG) && (PJMEDIA_HANDLE_G722_MPEG_BUG!=0) /* Handle special case for audio codec with RTP timestamp inconsistence * e.g: G722, MPEG audio. */ if (stream->has_g722_mpeg_bug) - rtp_ts_len = stream->rtp_tx_ts_len_per_pkt; + rtp_ts_len = stream->rtp_tx_ts_len_per_pkt; else - rtp_ts_len = ts_len; + rtp_ts_len = ts_len; #else rtp_ts_len = ts_len; #endif /* Don't do anything if stream is paused, except updating RTP timestamp */ if (channel->paused) { - stream->enc_buf_pos = stream->enc_buf_count = 0; + stream->enc_buf_pos = stream->enc_buf_count = 0; - /* Update RTP session's timestamp. */ - status = pjmedia_rtp_encode_rtp( &channel->rtp, 0, 0, 0, rtp_ts_len, - NULL, NULL); + /* Update RTP session's timestamp. */ + status = pjmedia_rtp_encode_rtp( &channel->rtp, 0, 0, 0, rtp_ts_len, + NULL, NULL); - /* Update RTCP stats with last RTP timestamp. */ - stream->rtcp.stat.rtp_tx_last_ts = pj_ntohl(channel->rtp.out_hdr.ts); + /* Update RTCP stats with last RTP timestamp. */ + stream->rtcp.stat.rtp_tx_last_ts = pj_ntohl(channel->rtp.out_hdr.ts); - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Increment transmit duration */ @@ -1403,31 +1402,31 @@ static pj_status_t put_frame_imp( pjmedia_port *port, * Otherwise encode the PCM buffer. */ if (stream->tx_dtmf_count) { - int first=0, last=0; + int first=0, last=0; - create_dtmf_payload(stream, &frame_out, 0, &first, &last); + create_dtmf_payload(stream, &frame_out, 0, &first, &last); - /* Encapsulate into RTP packet. Note that: + /* Encapsulate into RTP packet. Note that: * - RTP marker should be set on the beginning of a new event - * - RTP timestamp is constant for the same packet. + * - RTP timestamp is constant for the same packet. */ - status = pjmedia_rtp_encode_rtp( &channel->rtp, - stream->tx_event_pt, first, - (int)frame_out.size, - (first ? rtp_ts_len : 0), - (const void**)&rtphdr, - &rtphdrlen); - - if (last) { - /* This is the last packet for the event. - * Increment the RTP timestamp of the RTP session, for next - * RTP packets. - */ - inc_timestamp = stream->dtmf_duration + - ((DTMF_EBIT_RETRANSMIT_CNT-1) * - stream->rtp_tx_ts_len_per_pkt) - - rtp_ts_len; - } + status = pjmedia_rtp_encode_rtp( &channel->rtp, + stream->tx_event_pt, first, + (int)frame_out.size, + (first ? rtp_ts_len : 0), + (const void**)&rtphdr, + &rtphdrlen); + + if (last) { + /* This is the last packet for the event. + * Increment the RTP timestamp of the RTP session, for next + * RTP packets. + */ + inc_timestamp = stream->dtmf_duration + + ((DTMF_EBIT_RETRANSMIT_CNT-1) * + stream->rtp_tx_ts_len_per_pkt) + - rtp_ts_len; + } /* @@ -1441,74 +1440,74 @@ static pj_status_t put_frame_imp( pjmedia_port *port, * now it's enabled again. */ } else if (frame->type == PJMEDIA_FRAME_TYPE_AUDIO && - frame->buf == NULL && - stream->port.info.fmt.id == PJMEDIA_FORMAT_L16 && - (stream->dir & PJMEDIA_DIR_ENCODING)) + frame->buf == NULL && + stream->port.info.fmt.id == PJMEDIA_FORMAT_L16 && + (stream->dir & PJMEDIA_DIR_ENCODING)) { - pjmedia_frame silence_frame; - - pj_bzero(&silence_frame, sizeof(silence_frame)); - silence_frame.buf = stream->zero_frame; - silence_frame.size = stream->enc_samples_per_pkt * 2; - silence_frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - silence_frame.timestamp.u32.lo = pj_ntohl(stream->enc->rtp.out_hdr.ts); - - /* Encode! */ - status = pjmedia_codec_encode( stream->codec, &silence_frame, - channel->out_pkt_size - - sizeof(pjmedia_rtp_hdr), - &frame_out); - if (status != PJ_SUCCESS) { - LOGERR_((stream->port.info.name.ptr, status, - "Codec encode() error")); - return status; - } - - /* Encapsulate. */ - status = pjmedia_rtp_encode_rtp( &channel->rtp, - channel->pt, 0, - (int)frame_out.size, rtp_ts_len, - (const void**)&rtphdr, - &rtphdrlen); + pjmedia_frame silence_frame; + + pj_bzero(&silence_frame, sizeof(silence_frame)); + silence_frame.buf = stream->zero_frame; + silence_frame.size = stream->enc_samples_per_pkt * 2; + silence_frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + silence_frame.timestamp.u32.lo = pj_ntohl(stream->enc->rtp.out_hdr.ts); + + /* Encode! */ + status = pjmedia_codec_encode( stream->codec, &silence_frame, + channel->out_pkt_size - + sizeof(pjmedia_rtp_hdr), + &frame_out); + if (status != PJ_SUCCESS) { + LOGERR_((stream->port.info.name.ptr, status, + "Codec encode() error")); + return status; + } + + /* Encapsulate. */ + status = pjmedia_rtp_encode_rtp( &channel->rtp, + channel->pt, 0, + (int)frame_out.size, rtp_ts_len, + (const void**)&rtphdr, + &rtphdrlen); /* Encode audio frame */ } else if ((frame->type == PJMEDIA_FRAME_TYPE_AUDIO && - frame->buf != NULL) || - (frame->type == PJMEDIA_FRAME_TYPE_EXTENDED)) + frame->buf != NULL) || + (frame->type == PJMEDIA_FRAME_TYPE_EXTENDED)) { - /* Encode! */ - status = pjmedia_codec_encode( stream->codec, frame, - channel->out_pkt_size - - sizeof(pjmedia_rtp_hdr), - &frame_out); - if (status != PJ_SUCCESS) { - LOGERR_((stream->port.info.name.ptr, status, - "Codec encode() error")); - return status; - } - - /* Encapsulate. */ - status = pjmedia_rtp_encode_rtp( &channel->rtp, - channel->pt, 0, - (int)frame_out.size, rtp_ts_len, - (const void**)&rtphdr, - &rtphdrlen); + /* Encode! */ + status = pjmedia_codec_encode( stream->codec, frame, + channel->out_pkt_size - + sizeof(pjmedia_rtp_hdr), + &frame_out); + if (status != PJ_SUCCESS) { + LOGERR_((stream->port.info.name.ptr, status, + "Codec encode() error")); + return status; + } + + /* Encapsulate. */ + status = pjmedia_rtp_encode_rtp( &channel->rtp, + channel->pt, 0, + (int)frame_out.size, rtp_ts_len, + (const void**)&rtphdr, + &rtphdrlen); } else { - /* Just update RTP session's timestamp. */ - status = pjmedia_rtp_encode_rtp( &channel->rtp, - 0, 0, - 0, rtp_ts_len, - (const void**)&rtphdr, - &rtphdrlen); + /* Just update RTP session's timestamp. */ + status = pjmedia_rtp_encode_rtp( &channel->rtp, + 0, 0, + 0, rtp_ts_len, + (const void**)&rtphdr, + &rtphdrlen); } if (status != PJ_SUCCESS) { - LOGERR_((stream->port.info.name.ptr, status, - "RTP encode_rtp() error")); - return status; + LOGERR_((stream->port.info.name.ptr, status, + "RTP encode_rtp() error")); + return status; } /* Check if now is the time to transmit RTCP SR/RR report. @@ -1516,17 +1515,17 @@ static pj_status_t put_frame_imp( pjmedia_port *port, * when it is, check_tx_rtcp() will be handled by get_frame(). */ if (stream->dir != PJMEDIA_DIR_DECODING) { - check_tx_rtcp(stream, pj_ntohl(channel->rtp.out_hdr.ts)); + check_tx_rtcp(stream, pj_ntohl(channel->rtp.out_hdr.ts)); } /* Do nothing if we have nothing to transmit */ if (frame_out.size == 0) { - if (stream->is_streaming) { - PJ_LOG(5,(stream->port.info.name.ptr,"Starting silence")); - stream->is_streaming = PJ_FALSE; - } + if (stream->is_streaming) { + PJ_LOG(5,(stream->port.info.name.ptr,"Starting silence")); + stream->is_streaming = PJ_FALSE; + } - return PJ_SUCCESS; + return PJ_SUCCESS; } @@ -1538,16 +1537,16 @@ static pj_status_t put_frame_imp( pjmedia_port *port, * has been transmitted. */ if (inc_timestamp) { - pjmedia_rtp_encode_rtp( &channel->rtp, stream->tx_event_pt, 0, - 0, inc_timestamp, NULL, NULL); + pjmedia_rtp_encode_rtp( &channel->rtp, stream->tx_event_pt, 0, + 0, inc_timestamp, NULL, NULL); } /* Set RTP marker bit if currently not streaming */ if (stream->is_streaming == PJ_FALSE) { - pjmedia_rtp_hdr *rtp = (pjmedia_rtp_hdr*) channel->out_pkt; + pjmedia_rtp_hdr *rtp = (pjmedia_rtp_hdr*) channel->out_pkt; - rtp->m = 1; - PJ_LOG(5,(stream->port.info.name.ptr,"Start talksprut..")); + rtp->m = 1; + PJ_LOG(5,(stream->port.info.name.ptr,"Start talksprut..")); } stream->is_streaming = PJ_TRUE; @@ -1555,16 +1554,16 @@ static pj_status_t put_frame_imp( pjmedia_port *port, /* Send the RTP packet to the transport. */ status = pjmedia_transport_send_rtp(stream->transport, channel->out_pkt, frame_out.size + - sizeof(pjmedia_rtp_hdr)); + sizeof(pjmedia_rtp_hdr)); if (status != PJ_SUCCESS) { - if (stream->rtp_tx_err_cnt++ == 0) { - LOGERR_((stream->port.info.name.ptr, status, "Error sending RTP")); - } - if (stream->rtp_tx_err_cnt > SEND_ERR_COUNT_TO_REPORT) { - stream->rtp_tx_err_cnt = 0; - } - return PJ_SUCCESS; + if (stream->rtp_tx_err_cnt++ == 0) { + LOGERR_((stream->port.info.name.ptr, status, "Error sending RTP")); + } + if (stream->rtp_tx_err_cnt > SEND_ERR_COUNT_TO_REPORT) { + stream->rtp_tx_err_cnt = 0; + } + return PJ_SUCCESS; } /* Update stat */ @@ -1589,7 +1588,7 @@ static pj_status_t put_frame_imp( pjmedia_port *port, * RTP packet, and transmit to peer. */ static pj_status_t put_frame( pjmedia_port *port, - pjmedia_frame *frame ) + pjmedia_frame *frame ) { pjmedia_stream *stream = (pjmedia_stream*) port->port_data.pdata; pjmedia_frame tmp_zero_frame; @@ -1603,12 +1602,12 @@ static pj_status_t put_frame( pjmedia_port *port, * silence frame. */ if (frame->type == PJMEDIA_FRAME_TYPE_NONE) { - pj_memcpy(&tmp_zero_frame, frame, sizeof(pjmedia_frame)); - frame = &tmp_zero_frame; + pj_memcpy(&tmp_zero_frame, frame, sizeof(pjmedia_frame)); + frame = &tmp_zero_frame; - tmp_zero_frame.buf = NULL; - tmp_zero_frame.size = samples_per_frame * 2; - tmp_zero_frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + tmp_zero_frame.buf = NULL; + tmp_zero_frame.size = samples_per_frame * 2; + tmp_zero_frame.type = PJMEDIA_FRAME_TYPE_AUDIO; } #if 0 @@ -1619,16 +1618,16 @@ static pj_status_t put_frame( pjmedia_port *port, * to the codec. */ if (stream->vad_enabled != stream->codec_param.setting.vad && - stream->vad_enabled != 0 && - frame->type == PJMEDIA_FRAME_TYPE_NONE && - samples_per_frame <= ZERO_PCM_MAX_SIZE) + stream->vad_enabled != 0 && + frame->type == PJMEDIA_FRAME_TYPE_NONE && + samples_per_frame <= ZERO_PCM_MAX_SIZE) { - pj_memcpy(&tmp_in_frame, frame, sizeof(pjmedia_frame)); - frame = &tmp_in_frame; + pj_memcpy(&tmp_in_frame, frame, sizeof(pjmedia_frame)); + frame = &tmp_in_frame; - tmp_in_frame.buf = NULL; - tmp_in_frame.size = samples_per_frame * 2; - tmp_in_frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + tmp_in_frame.buf = NULL; + tmp_in_frame.size = samples_per_frame * 2; + tmp_in_frame.type = PJMEDIA_FRAME_TYPE_AUDIO; } #endif @@ -1636,13 +1635,13 @@ static pj_status_t put_frame( pjmedia_port *port, * after transmitting for VAD_SUSPEND_SEC seconds. */ if (stream->vad_enabled != stream->codec_param.setting.vad && - (stream->tx_duration - stream->ts_vad_disabled) > + (stream->tx_duration - stream->ts_vad_disabled) > PJMEDIA_PIA_SRATE(&stream->port.info) * - PJMEDIA_STREAM_VAD_SUSPEND_MSEC / 1000) + PJMEDIA_STREAM_VAD_SUSPEND_MSEC / 1000) { - stream->codec_param.setting.vad = stream->vad_enabled; - pjmedia_codec_modify(stream->codec, &stream->codec_param); - PJ_LOG(4,(stream->port.info.name.ptr,"VAD re-enabled")); + stream->codec_param.setting.vad = stream->vad_enabled; + pjmedia_codec_modify(stream->codec, &stream->codec_param); + PJ_LOG(4,(stream->port.info.name.ptr,"VAD re-enabled")); } @@ -1650,44 +1649,44 @@ static pj_status_t put_frame( pjmedia_port *port, * be passed through the encoding buffer via rebuffer() function. */ if (stream->enc_buf != NULL) { - pjmedia_frame tmp_rebuffer_frame; - pj_status_t status = PJ_SUCCESS; + pjmedia_frame tmp_rebuffer_frame; + pj_status_t status = PJ_SUCCESS; - /* Copy original frame to temporary frame since we need - * to modify it. - */ - pj_memcpy(&tmp_rebuffer_frame, frame, sizeof(pjmedia_frame)); + /* Copy original frame to temporary frame since we need + * to modify it. + */ + pj_memcpy(&tmp_rebuffer_frame, frame, sizeof(pjmedia_frame)); - /* Loop while we have full frame in enc_buffer */ - for (;;) { - pj_status_t st; + /* Loop while we have full frame in enc_buffer */ + for (;;) { + pj_status_t st; - /* Run rebuffer() */ - rebuffer(stream, &tmp_rebuffer_frame); + /* Run rebuffer() */ + rebuffer(stream, &tmp_rebuffer_frame); - /* Process this frame */ - st = put_frame_imp(port, &tmp_rebuffer_frame); - if (st != PJ_SUCCESS) - status = st; + /* Process this frame */ + st = put_frame_imp(port, &tmp_rebuffer_frame); + if (st != PJ_SUCCESS) + status = st; - /* If we still have full frame in the buffer, re-run - * rebuffer() with NULL frame. - */ - if (stream->enc_buf_count >= stream->enc_samples_per_pkt) { + /* If we still have full frame in the buffer, re-run + * rebuffer() with NULL frame. + */ + if (stream->enc_buf_count >= stream->enc_samples_per_pkt) { - tmp_rebuffer_frame.type = PJMEDIA_FRAME_TYPE_NONE; + tmp_rebuffer_frame.type = PJMEDIA_FRAME_TYPE_NONE; - } else { + } else { - /* Otherwise break */ - break; - } - } + /* Otherwise break */ + break; + } + } - return status; + return status; } else { - return put_frame_imp(port, frame); + return put_frame_imp(port, frame); } } @@ -1699,19 +1698,19 @@ static void dump_bin(const char *buf, unsigned len) PJ_LOG(3,(THIS_FILE, "begin dump")); for (i=0; ievent > 15) { #endif - PJ_LOG(5,(stream->port.info.name.ptr, - "Ignored RTP pkt with bad DTMF event %d", - event->event)); - return; + PJ_LOG(5,(stream->port.info.name.ptr, + "Ignored RTP pkt with bad DTMF event %d", + event->event)); + return; } /* Extract event data. */ @@ -1757,14 +1756,14 @@ static void handle_incoming_dtmf( pjmedia_stream *stream, /* Check if this is the same/current digit of the last packet. */ if (stream->last_dtmf != -1 && - event->event == stream->last_dtmf && - event_duration >= stream->last_dtmf_dur) + event->event == stream->last_dtmf && + event_duration >= stream->last_dtmf_dur) { /* Emit all updates but hide duplicate end frames. */ emit_event = !is_event_end || stream->last_dtmf_ended != is_event_end; - /* Yes, this is the same event. */ - stream->last_dtmf_dur = event_duration; + /* Yes, this is the same event. */ + stream->last_dtmf_dur = event_duration; stream->last_dtmf_ended = is_event_end; /* If DTMF callback is installed and end of event hasn't been reported @@ -1783,13 +1782,13 @@ static void handle_incoming_dtmf( pjmedia_stream *stream, stream->dtmf_event_cb(stream, stream->dtmf_event_cb_user_data, &dtmf_event); } - return; + return; } /* New event! */ PJ_LOG(5,(stream->port.info.name.ptr, "Received DTMF digit %c, vol=%d", - digitmap[event->event], - (event->e_vol & PJMEDIA_RTP_DTMF_EVENT_VOLUME_MASK))); + digitmap[event->event], + (event->e_vol & PJMEDIA_RTP_DTMF_EVENT_VOLUME_MASK))); stream->last_dtmf = event->event; stream->last_dtmf_dur = event_duration; @@ -1811,22 +1810,22 @@ static void handle_incoming_dtmf( pjmedia_stream *stream, stream->dtmf_event_cb(stream, stream->dtmf_event_cb_user_data, &dtmf_event); } else if (stream->dtmf_cb) { - stream->dtmf_cb(stream, stream->dtmf_cb_user_data, - digitmap[event->event]); + stream->dtmf_cb(stream, stream->dtmf_cb_user_data, + digitmap[event->event]); } else { - /* By convention, we use jitter buffer's mutex to access shared - * DTMF variables. - */ - pj_mutex_lock(stream->jb_mutex); - if (stream->rx_dtmf_count >= PJ_ARRAY_SIZE(stream->rx_dtmf_buf)) { - /* DTMF digits overflow. Discard the oldest digit. */ - pj_array_erase(stream->rx_dtmf_buf, - sizeof(stream->rx_dtmf_buf[0]), - stream->rx_dtmf_count, 0); - --stream->rx_dtmf_count; - } - stream->rx_dtmf_buf[stream->rx_dtmf_count++] = digitmap[event->event]; - pj_mutex_unlock(stream->jb_mutex); + /* By convention, we use jitter buffer's mutex to access shared + * DTMF variables. + */ + pj_mutex_lock(stream->jb_mutex); + if (stream->rx_dtmf_count >= PJ_ARRAY_SIZE(stream->rx_dtmf_buf)) { + /* DTMF digits overflow. Discard the oldest digit. */ + pj_array_erase(stream->rx_dtmf_buf, + sizeof(stream->rx_dtmf_buf[0]), + stream->rx_dtmf_count, 0); + --stream->rx_dtmf_count; + } + stream->rx_dtmf_buf[stream->rx_dtmf_count++] = digitmap[event->event]; + pj_mutex_unlock(stream->jb_mutex); } } @@ -1851,39 +1850,39 @@ static void on_rx_rtp( pjmedia_tp_cb_param *param) /* Check for errors */ if (bytes_read < 0) { - status = (pj_status_t)-bytes_read; - if (status == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK)) { - return; - } + status = (pj_status_t)-bytes_read; + if (status == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK)) { + return; + } - LOGERR_((stream->port.info.name.ptr, status, - "Unable to receive RTP packet")); + LOGERR_((stream->port.info.name.ptr, status, + "Unable to receive RTP packet")); - if (status == PJ_ESOCKETSTOP) { - /* Publish receive error event. */ - publish_tp_event(PJMEDIA_EVENT_MEDIA_TP_ERR, status, PJ_TRUE, - PJMEDIA_DIR_DECODING, stream); - } - return; + if (status == PJ_ESOCKETSTOP) { + /* Publish receive error event. */ + publish_tp_event(PJMEDIA_EVENT_MEDIA_TP_ERR, status, PJ_TRUE, + PJMEDIA_DIR_DECODING, stream); + } + return; } /* Ignore non-RTP keep-alive packets */ if (bytes_read < (pj_ssize_t) sizeof(pjmedia_rtp_hdr)) - return; + return; /* Update RTP and RTCP session. */ status = pjmedia_rtp_decode_rtp(&channel->rtp, pkt, (int)bytes_read, - &hdr, &payload, &payloadlen); + &hdr, &payload, &payloadlen); if (status != PJ_SUCCESS) { - LOGERR_((stream->port.info.name.ptr, status, "RTP decode error")); - stream->rtcp.stat.rx.discard++; - return; + LOGERR_((stream->port.info.name.ptr, status, "RTP decode error")); + stream->rtcp.stat.rx.discard++; + return; } /* Check if multiplexing is allowed and the payload indicates RTCP. */ if (stream->si.rtcp_mux && hdr->pt >= 64 && hdr->pt <= 95) { - on_rx_rtcp(stream, pkt, bytes_read); - return; + on_rx_rtcp(stream, pkt, bytes_read); + return; } /* See if source address of RTP packet is different than the @@ -1891,67 +1890,67 @@ static void on_rx_rtp( pjmedia_tp_cb_param *param) * media transport to switch RTP remote address. */ if (param->src_addr) { - pj_uint32_t peer_ssrc = channel->rtp.peer_ssrc; - pj_bool_t badssrc = PJ_FALSE; - - /* Check SSRC. */ - if (!channel->rtp.has_peer_ssrc && peer_ssrc == 0) - peer_ssrc = pj_ntohl(hdr->ssrc); - - if ((stream->si.has_rem_ssrc) && (pj_ntohl(hdr->ssrc) != peer_ssrc)) { - badssrc = PJ_TRUE; - } - - if (pj_sockaddr_cmp(&stream->rem_rtp_addr, param->src_addr) == 0) { - /* We're still receiving from rem_rtp_addr. */ - stream->rtp_src_cnt = 0; - stream->rem_rtp_flag = badssrc? 2: 1; - } else { - stream->rtp_src_cnt++; - - if (stream->rtp_src_cnt < PJMEDIA_RTP_NAT_PROBATION_CNT) { - if (stream->rem_rtp_flag == 1 || - (stream->rem_rtp_flag == 2 && badssrc)) - { - /* Only discard if: - * - we have ever received packet with good ssrc from - * remote address (rem_rtp_addr), or - * - we have ever received packet with bad ssrc from - * remote address and this packet also has bad ssrc. - */ - return; - } - if (!badssrc && stream->rem_rtp_flag != 1) - { - /* Immediately switch if we receive packet with the - * correct ssrc AND we never receive packets with - * good ssrc from rem_rtp_addr. - */ - param->rem_switch = PJ_TRUE; - } - } else { - /* Switch. We no longer receive packets from rem_rtp_addr. */ - param->rem_switch = PJ_TRUE; - } - - if (param->rem_switch) { - /* Set remote RTP address to source address */ - pj_sockaddr_cp(&stream->rem_rtp_addr, param->src_addr); - - /* Reset counter and flag */ - stream->rtp_src_cnt = 0; - stream->rem_rtp_flag = badssrc? 2: 1; - - /* Update RTCP peer ssrc */ - stream->rtcp.peer_ssrc = pj_ntohl(hdr->ssrc); - } - } + pj_uint32_t peer_ssrc = channel->rtp.peer_ssrc; + pj_bool_t badssrc = PJ_FALSE; + + /* Check SSRC. */ + if (!channel->rtp.has_peer_ssrc && peer_ssrc == 0) + peer_ssrc = pj_ntohl(hdr->ssrc); + + if ((stream->si.has_rem_ssrc) && (pj_ntohl(hdr->ssrc) != peer_ssrc)) { + badssrc = PJ_TRUE; + } + + if (pj_sockaddr_cmp(&stream->rem_rtp_addr, param->src_addr) == 0) { + /* We're still receiving from rem_rtp_addr. */ + stream->rtp_src_cnt = 0; + stream->rem_rtp_flag = badssrc? 2: 1; + } else { + stream->rtp_src_cnt++; + + if (stream->rtp_src_cnt < PJMEDIA_RTP_NAT_PROBATION_CNT) { + if (stream->rem_rtp_flag == 1 || + (stream->rem_rtp_flag == 2 && badssrc)) + { + /* Only discard if: + * - we have ever received packet with good ssrc from + * remote address (rem_rtp_addr), or + * - we have ever received packet with bad ssrc from + * remote address and this packet also has bad ssrc. + */ + return; + } + if (!badssrc && stream->rem_rtp_flag != 1) + { + /* Immediately switch if we receive packet with the + * correct ssrc AND we never receive packets with + * good ssrc from rem_rtp_addr. + */ + param->rem_switch = PJ_TRUE; + } + } else { + /* Switch. We no longer receive packets from rem_rtp_addr. */ + param->rem_switch = PJ_TRUE; + } + + if (param->rem_switch) { + /* Set remote RTP address to source address */ + pj_sockaddr_cp(&stream->rem_rtp_addr, param->src_addr); + + /* Reset counter and flag */ + stream->rtp_src_cnt = 0; + stream->rem_rtp_flag = badssrc? 2: 1; + + /* Update RTCP peer ssrc */ + stream->rtcp.peer_ssrc = pj_ntohl(hdr->ssrc); + } + } } pj_bzero(&seq_st, sizeof(seq_st)); /* Ignore the packet if decoder is paused */ if (channel->paused) { - goto on_return; + goto on_return; } /* Update RTP session (also checks if RTP session can accept @@ -1961,66 +1960,66 @@ static void on_rx_rtp( pjmedia_tp_cb_param *param) pjmedia_rtp_session_update2(&channel->rtp, hdr, &seq_st, check_pt); #if !PJMEDIA_STREAM_CHECK_RTP_PT if (!check_pt && hdr->pt != channel->rtp.out_pt && - hdr->pt != stream->rx_event_pt) + hdr->pt != stream->rx_event_pt) { - seq_st.status.flag.badpt = 1; + seq_st.status.flag.badpt = 1; } #endif if (seq_st.status.value) { - TRC_ ((stream->port.info.name.ptr, - "RTP status: badpt=%d, badssrc=%d, dup=%d, " - "outorder=%d, probation=%d, restart=%d", - seq_st.status.flag.badpt, - seq_st.status.flag.badssrc, - seq_st.status.flag.dup, - seq_st.status.flag.outorder, - seq_st.status.flag.probation, - seq_st.status.flag.restart)); - - if (seq_st.status.flag.badpt) { - PJ_LOG(4,(stream->port.info.name.ptr, - "Bad RTP pt %d (expecting %d)", - hdr->pt, channel->rtp.out_pt)); - } + TRC_ ((stream->port.info.name.ptr, + "RTP status: badpt=%d, badssrc=%d, dup=%d, " + "outorder=%d, probation=%d, restart=%d", + seq_st.status.flag.badpt, + seq_st.status.flag.badssrc, + seq_st.status.flag.dup, + seq_st.status.flag.outorder, + seq_st.status.flag.probation, + seq_st.status.flag.restart)); + + if (seq_st.status.flag.badpt) { + PJ_LOG(4,(stream->port.info.name.ptr, + "Bad RTP pt %d (expecting %d)", + hdr->pt, channel->rtp.out_pt)); + } - if (!stream->si.has_rem_ssrc && seq_st.status.flag.badssrc) { - PJ_LOG(4,(stream->port.info.name.ptr, - "Changed RTP peer SSRC %d (previously %d)", - channel->rtp.peer_ssrc, stream->rtcp.peer_ssrc)); - stream->rtcp.peer_ssrc = channel->rtp.peer_ssrc; - } + if (!stream->si.has_rem_ssrc && seq_st.status.flag.badssrc) { + PJ_LOG(4,(stream->port.info.name.ptr, + "Changed RTP peer SSRC %d (previously %d)", + channel->rtp.peer_ssrc, stream->rtcp.peer_ssrc)); + stream->rtcp.peer_ssrc = channel->rtp.peer_ssrc; + } } /* Skip bad RTP packet */ if (seq_st.status.flag.bad) { - pkt_discarded = PJ_TRUE; - goto on_return; + pkt_discarded = PJ_TRUE; + goto on_return; } /* Ignore if payloadlen is zero */ if (payloadlen == 0) { - pkt_discarded = PJ_TRUE; - goto on_return; + pkt_discarded = PJ_TRUE; + goto on_return; } /* Handle incoming DTMF. */ if (hdr->pt == stream->rx_event_pt) { pj_timestamp ts; - /* Ignore out-of-order packet as it will be detected as new - * digit. Also ignore duplicate packet as it serves no use. - */ - if (seq_st.status.flag.outorder || seq_st.status.flag.dup) { - goto on_return; - } + /* Ignore out-of-order packet as it will be detected as new + * digit. Also ignore duplicate packet as it serves no use. + */ + if (seq_st.status.flag.outorder || seq_st.status.flag.dup) { + goto on_return; + } /* Get the timestamp of the event */ - ts.u64 = pj_ntohl(hdr->ts); + ts.u64 = pj_ntohl(hdr->ts); - handle_incoming_dtmf(stream, &ts, payload, payloadlen); - goto on_return; + handle_incoming_dtmf(stream, &ts, payload, payloadlen); + goto on_return; } /* Put "good" packet to jitter buffer, or reset the jitter buffer @@ -2028,148 +2027,148 @@ static void on_rx_rtp( pjmedia_tp_cb_param *param) */ pj_mutex_lock( stream->jb_mutex ); if (seq_st.status.flag.restart) { - status = pjmedia_jbuf_reset(stream->jb); - PJ_LOG(4,(stream->port.info.name.ptr, "Jitter buffer reset")); + status = pjmedia_jbuf_reset(stream->jb); + PJ_LOG(4,(stream->port.info.name.ptr, "Jitter buffer reset")); } else { - /* - * Packets may contain more than one frames, while the jitter - * buffer can only take one frame per "put" operation. So we need - * to ask the codec to "parse" the payload into multiple frames. - */ - enum { MAX = 16 }; - pj_timestamp ts; - unsigned i, count = MAX; - unsigned ts_span; - pjmedia_frame frames[MAX]; - pj_bzero(frames, sizeof(frames[0]) * MAX); - - /* Get the timestamp of the first sample */ - ts.u64 = pj_ntohl(hdr->ts); - - /* Parse the payload. */ - status = pjmedia_codec_parse(stream->codec, (void*)payload, - payloadlen, &ts, &count, frames); - if (status != PJ_SUCCESS) { - LOGERR_((stream->port.info.name.ptr, status, - "Codec parse() error")); - count = 0; - } else if (count == 0) { - PJ_LOG(2, (stream->port.info.name.ptr, "codec parsed 0 frames")); - } else if (stream->detect_ptime_change && - frames[0].bit_info > 0xFFFF) - { - unsigned dec_ptime, old_ptime; - - old_ptime = stream->dec_ptime; - - frames[0].bit_info &= 0xFFFF; - dec_ptime = frames[0].bit_info * 1000 / - stream->codec_param.info.clock_rate; - stream->rtp_rx_ts_len_per_frame= stream->rtp_rx_ts_len_per_frame * - dec_ptime / stream->dec_ptime; - stream->dec_ptime = (pj_uint16_t)dec_ptime; - pjmedia_jbuf_set_ptime(stream->jb, stream->dec_ptime); - - PJ_LOG(4, (stream->port.info.name.ptr, "codec decode " - "ptime change detected: %d -> %d", - old_ptime, dec_ptime)); - - /* Reset jitter buffer after ptime changed */ - pjmedia_jbuf_reset(stream->jb); - } + /* + * Packets may contain more than one frames, while the jitter + * buffer can only take one frame per "put" operation. So we need + * to ask the codec to "parse" the payload into multiple frames. + */ + enum { MAX = 16 }; + pj_timestamp ts; + unsigned i, count = MAX; + unsigned ts_span; + pjmedia_frame frames[MAX]; + pj_bzero(frames, sizeof(frames[0]) * MAX); + + /* Get the timestamp of the first sample */ + ts.u64 = pj_ntohl(hdr->ts); + + /* Parse the payload. */ + status = pjmedia_codec_parse(stream->codec, (void*)payload, + payloadlen, &ts, &count, frames); + if (status != PJ_SUCCESS) { + LOGERR_((stream->port.info.name.ptr, status, + "Codec parse() error")); + count = 0; + } else if (count == 0) { + PJ_LOG(2, (stream->port.info.name.ptr, "codec parsed 0 frames")); + } else if (stream->detect_ptime_change && + frames[0].bit_info > 0xFFFF) + { + unsigned dec_ptime, old_ptime; + + old_ptime = stream->dec_ptime; + + frames[0].bit_info &= 0xFFFF; + dec_ptime = frames[0].bit_info * 1000 / + stream->codec_param.info.clock_rate; + stream->rtp_rx_ts_len_per_frame= stream->rtp_rx_ts_len_per_frame * + dec_ptime / stream->dec_ptime; + stream->dec_ptime = (pj_uint16_t)dec_ptime; + pjmedia_jbuf_set_ptime(stream->jb, stream->dec_ptime); + + PJ_LOG(4, (stream->port.info.name.ptr, "codec decode " + "ptime change detected: %d -> %d", + old_ptime, dec_ptime)); + + /* Reset jitter buffer after ptime changed */ + pjmedia_jbuf_reset(stream->jb); + } #if defined(PJMEDIA_HANDLE_G722_MPEG_BUG) && (PJMEDIA_HANDLE_G722_MPEG_BUG!=0) - /* This code is used to learn the samples per frame value that is put - * by remote endpoint, for codecs with inconsistent clock rate such - * as G.722 or MPEG audio. We need to learn the samples per frame - * value as it is used as divider when inserting frames into the - * jitter buffer. - */ - if (stream->has_g722_mpeg_bug) { - if (stream->rtp_rx_check_cnt) { - /* Make sure the detection performed only on two consecutive - * packets with valid RTP sequence and no wrapped timestamp. - */ - if (seq_st.diff == 1 && stream->rtp_rx_last_ts && - ts.u64 > stream->rtp_rx_last_ts && - stream->rtp_rx_last_cnt > 0) - { - unsigned peer_frm_ts_diff; - unsigned frm_ts_span; - - /* Calculate actual frame timestamp span */ - frm_ts_span = PJMEDIA_PIA_SPF(&stream->port.info) / - stream->codec_param.setting.frm_per_pkt/ - PJMEDIA_PIA_CCNT(&stream->port.info); - - /* Get remote frame timestamp span */ - peer_frm_ts_diff = - ((pj_uint32_t)ts.u64-stream->rtp_rx_last_ts) / - stream->rtp_rx_last_cnt; - - /* Possibilities remote's samples per frame for G.722 - * are only (frm_ts_span) and (frm_ts_span/2), this - * validation is needed to avoid wrong decision because - * of silence frames. - */ - if (stream->codec_param.info.pt == PJMEDIA_RTP_PT_G722 && - (peer_frm_ts_diff == frm_ts_span || - peer_frm_ts_diff == (frm_ts_span>>1))) - { - if (peer_frm_ts_diff < stream->rtp_rx_ts_len_per_frame) - { - stream->rtp_rx_ts_len_per_frame = peer_frm_ts_diff; - /* Done, stop the check immediately */ - stream->rtp_rx_check_cnt = 1; - } - - if (--stream->rtp_rx_check_cnt == 0) { - PJ_LOG(4, (THIS_FILE, "G722 codec used, remote" - " samples per frame detected = %d", - stream->rtp_rx_ts_len_per_frame)); - - /* Reset jitter buffer once detection done */ - pjmedia_jbuf_reset(stream->jb); - } - } - } - - stream->rtp_rx_last_ts = (pj_uint32_t)ts.u64; - stream->rtp_rx_last_cnt = count; - } - - ts_span = stream->rtp_rx_ts_len_per_frame; - - /* Adjust the timestamp of the parsed frames */ - for (i=0; idec_ptime * - stream->codec_param.info.clock_rate / - 1000; - } + /* This code is used to learn the samples per frame value that is put + * by remote endpoint, for codecs with inconsistent clock rate such + * as G.722 or MPEG audio. We need to learn the samples per frame + * value as it is used as divider when inserting frames into the + * jitter buffer. + */ + if (stream->has_g722_mpeg_bug) { + if (stream->rtp_rx_check_cnt) { + /* Make sure the detection performed only on two consecutive + * packets with valid RTP sequence and no wrapped timestamp. + */ + if (seq_st.diff == 1 && stream->rtp_rx_last_ts && + ts.u64 > stream->rtp_rx_last_ts && + stream->rtp_rx_last_cnt > 0) + { + unsigned peer_frm_ts_diff; + unsigned frm_ts_span; + + /* Calculate actual frame timestamp span */ + frm_ts_span = PJMEDIA_PIA_SPF(&stream->port.info) / + stream->codec_param.setting.frm_per_pkt/ + PJMEDIA_PIA_CCNT(&stream->port.info); + + /* Get remote frame timestamp span */ + peer_frm_ts_diff = + ((pj_uint32_t)ts.u64-stream->rtp_rx_last_ts) / + stream->rtp_rx_last_cnt; + + /* Possibilities remote's samples per frame for G.722 + * are only (frm_ts_span) and (frm_ts_span/2), this + * validation is needed to avoid wrong decision because + * of silence frames. + */ + if (stream->codec_param.info.pt == PJMEDIA_RTP_PT_G722 && + (peer_frm_ts_diff == frm_ts_span || + peer_frm_ts_diff == (frm_ts_span>>1))) + { + if (peer_frm_ts_diff < stream->rtp_rx_ts_len_per_frame) + { + stream->rtp_rx_ts_len_per_frame = peer_frm_ts_diff; + /* Done, stop the check immediately */ + stream->rtp_rx_check_cnt = 1; + } + + if (--stream->rtp_rx_check_cnt == 0) { + PJ_LOG(4, (THIS_FILE, "G722 codec used, remote" + " samples per frame detected = %d", + stream->rtp_rx_ts_len_per_frame)); + + /* Reset jitter buffer once detection done */ + pjmedia_jbuf_reset(stream->jb); + } + } + } + + stream->rtp_rx_last_ts = (pj_uint32_t)ts.u64; + stream->rtp_rx_last_cnt = count; + } + + ts_span = stream->rtp_rx_ts_len_per_frame; + + /* Adjust the timestamp of the parsed frames */ + for (i=0; idec_ptime * + stream->codec_param.info.clock_rate / + 1000; + } #else - ts_span = stream->dec_ptime * - stream->codec_param.info.clock_rate / - 1000; + ts_span = stream->dec_ptime * + stream->codec_param.info.clock_rate / + 1000; #endif - /* Put each frame to jitter buffer. */ - for (i=0; ijb, frames[i].buf, frames[i].size, - frames[i].bit_info, ext_seq, &discarded); - if (discarded) - pkt_discarded = PJ_TRUE; - } + ext_seq = (unsigned)(frames[i].timestamp.u64 / ts_span); + pjmedia_jbuf_put_frame2(stream->jb, frames[i].buf, frames[i].size, + frames[i].bit_info, ext_seq, &discarded); + if (discarded) + pkt_discarded = PJ_TRUE; + } #if TRACE_JB - trace_jb_put(stream, hdr, payloadlen, count); + trace_jb_put(stream, hdr, payloadlen, count); #endif } @@ -2182,56 +2181,56 @@ static void on_rx_rtp( pjmedia_tp_cb_param *param) * because otherwise check_tx_rtcp() will be handled by put_frame() */ if (stream->dir == PJMEDIA_DIR_DECODING || stream->enc->paused) { - check_tx_rtcp(stream, pj_ntohl(hdr->ts)); + check_tx_rtcp(stream, pj_ntohl(hdr->ts)); } if (status != 0) { - LOGERR_((stream->port.info.name.ptr, status, - "Jitter buffer put() error")); - pkt_discarded = PJ_TRUE; - goto on_return; + LOGERR_((stream->port.info.name.ptr, status, + "Jitter buffer put() error")); + pkt_discarded = PJ_TRUE; + goto on_return; } on_return: /* Update RTCP session */ if (stream->rtcp.peer_ssrc == 0) - stream->rtcp.peer_ssrc = channel->rtp.peer_ssrc; + stream->rtcp.peer_ssrc = channel->rtp.peer_ssrc; pjmedia_rtcp_rx_rtp2(&stream->rtcp, pj_ntohs(hdr->seq), - pj_ntohl(hdr->ts), payloadlen, pkt_discarded); + pj_ntohl(hdr->ts), payloadlen, pkt_discarded); /* RTCP-FB generic NACK */ if (stream->rtcp.received >= 10 && seq_st.diff > 1 && - stream->send_rtcp_fb_nack && pj_ntohs(hdr->seq) >= seq_st.diff) + stream->send_rtcp_fb_nack && pj_ntohs(hdr->seq) >= seq_st.diff) { - int i; - pj_bzero(&stream->rtcp_fb_nack, sizeof(stream->rtcp_fb_nack)); - stream->rtcp_fb_nack.pid = pj_ntohs(hdr->seq) - seq_st.diff + 1; - for (i = 0; i < (seq_st.diff - 1); ++i) { - stream->rtcp_fb_nack.blp <<= 1; - stream->rtcp_fb_nack.blp |= 1; - } - - /* Send it immediately */ - status = send_rtcp(stream, PJ_TRUE, PJ_FALSE, PJ_FALSE, PJ_TRUE); + int i; + pj_bzero(&stream->rtcp_fb_nack, sizeof(stream->rtcp_fb_nack)); + stream->rtcp_fb_nack.pid = pj_ntohs(hdr->seq) - seq_st.diff + 1; + for (i = 0; i < (seq_st.diff - 1); ++i) { + stream->rtcp_fb_nack.blp <<= 1; + stream->rtcp_fb_nack.blp |= 1; + } + + /* Send it immediately */ + status = send_rtcp(stream, PJ_TRUE, PJ_FALSE, PJ_FALSE, PJ_TRUE); if (status != PJ_SUCCESS) { PJ_PERROR(4,(stream->port.info.name.ptr, status, - "Error sending RTCP FB generic NACK")); - } else { - stream->initial_rr = PJ_TRUE; - } + "Error sending RTCP FB generic NACK")); + } else { + stream->initial_rr = PJ_TRUE; + } } /* Send RTCP RR and SDES after we receive some RTP packets */ if (stream->rtcp.received >= 10 && !stream->initial_rr) { - status = send_rtcp(stream, !stream->rtcp_sdes_bye_disabled, - PJ_FALSE, PJ_FALSE, PJ_FALSE); + status = send_rtcp(stream, !stream->rtcp_sdes_bye_disabled, + PJ_FALSE, PJ_FALSE, PJ_FALSE); if (status != PJ_SUCCESS) { PJ_PERROR(4,(stream->port.info.name.ptr, status, - "Error sending initial RTCP RR")); - } else { - stream->initial_rr = PJ_TRUE; - } + "Error sending initial RTCP RR")); + } else { + stream->initial_rr = PJ_TRUE; + } } } @@ -2249,19 +2248,19 @@ static void on_rx_rtcp( void *data, /* Check for errors */ if (bytes_read < 0) { - status = (pj_status_t)-bytes_read; - if (status == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK)) { - return; - } - LOGERR_((stream->port.info.name.ptr, status, - "Unable to receive RTCP packet")); + status = (pj_status_t)-bytes_read; + if (status == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK)) { + return; + } + LOGERR_((stream->port.info.name.ptr, status, + "Unable to receive RTCP packet")); - if (status == PJ_ESOCKETSTOP) { - /* Publish receive error event. */ - publish_tp_event(PJMEDIA_EVENT_MEDIA_TP_ERR, status, PJ_FALSE, - PJMEDIA_DIR_DECODING, stream); - } - return; + if (status == PJ_ESOCKETSTOP) { + /* Publish receive error event. */ + publish_tp_event(PJMEDIA_EVENT_MEDIA_TP_ERR, status, PJ_FALSE, + PJMEDIA_DIR_DECODING, stream); + } + return; } pjmedia_rtcp_rx_rtcp(&stream->rtcp, pkt, bytes_read); @@ -2272,11 +2271,11 @@ static void on_rx_rtcp( void *data, * Create media channel. */ static pj_status_t create_channel( pj_pool_t *pool, - pjmedia_stream *stream, - pjmedia_dir dir, - unsigned pt, - const pjmedia_stream_info *param, - pjmedia_channel **p_channel) + pjmedia_stream *stream, + pjmedia_dir dir, + unsigned pt, + const pjmedia_stream_info *param, + pjmedia_channel **p_channel) { pjmedia_channel *channel; pj_status_t status; @@ -2297,28 +2296,28 @@ static pj_status_t create_channel( pj_pool_t *pool, /* Allocate buffer for outgoing packet. */ if (param->type == PJMEDIA_TYPE_AUDIO) { - unsigned max_rx_based_size; - unsigned max_bps_based_size; - - /* out_pkt buffer is used for sending and receiving, so lets calculate - * its size based on both. For receiving, we have stream->frame_size, - * which is used in configuring jitter buffer frame length. - * For sending, it is based on codec max_bps info. - */ - max_rx_based_size = stream->frame_size; - max_bps_based_size = stream->codec_param.info.max_bps * - PJMEDIA_MAX_FRAME_DURATION_MS / 8 / 1000; - channel->out_pkt_size = PJ_MAX(max_rx_based_size, max_bps_based_size); - - /* Also include RTP header size (for sending) */ + unsigned max_rx_based_size; + unsigned max_bps_based_size; + + /* out_pkt buffer is used for sending and receiving, so lets calculate + * its size based on both. For receiving, we have stream->frame_size, + * which is used in configuring jitter buffer frame length. + * For sending, it is based on codec max_bps info. + */ + max_rx_based_size = stream->frame_size; + max_bps_based_size = stream->codec_param.info.max_bps * + PJMEDIA_MAX_FRAME_DURATION_MS / 8 / 1000; + channel->out_pkt_size = PJ_MAX(max_rx_based_size, max_bps_based_size); + + /* Also include RTP header size (for sending) */ channel->out_pkt_size += sizeof(pjmedia_rtp_hdr); if (channel->out_pkt_size > PJMEDIA_MAX_MTU - - PJMEDIA_STREAM_RESV_PAYLOAD_LEN) - { - channel->out_pkt_size = PJMEDIA_MAX_MTU - - PJMEDIA_STREAM_RESV_PAYLOAD_LEN; - } + PJMEDIA_STREAM_RESV_PAYLOAD_LEN) + { + channel->out_pkt_size = PJMEDIA_MAX_MTU - + PJMEDIA_STREAM_RESV_PAYLOAD_LEN; + } } else { return PJ_ENOTSUP; } @@ -2330,19 +2329,19 @@ static pj_status_t create_channel( pj_pool_t *pool, /* Create RTP and RTCP sessions: */ { - pjmedia_rtp_session_setting settings; + pjmedia_rtp_session_setting settings; - settings.flags = (pj_uint8_t)((param->rtp_seq_ts_set << 2) | - (param->has_rem_ssrc << 4) | 3); - settings.default_pt = pt; - settings.sender_ssrc = param->ssrc; - settings.peer_ssrc = param->rem_ssrc; - settings.seq = param->rtp_seq; - settings.ts = param->rtp_ts; - status = pjmedia_rtp_session_init2(&channel->rtp, settings); + settings.flags = (pj_uint8_t)((param->rtp_seq_ts_set << 2) | + (param->has_rem_ssrc << 4) | 3); + settings.default_pt = pt; + settings.sender_ssrc = param->ssrc; + settings.peer_ssrc = param->rem_ssrc; + settings.seq = param->rtp_seq; + settings.ts = param->rtp_ts; + status = pjmedia_rtp_session_init2(&channel->rtp, settings); } if (status != PJ_SUCCESS) - return status; + return status; /* Done. */ *p_channel = channel; @@ -2360,21 +2359,21 @@ static pj_status_t stream_event_cb(pjmedia_event *event, /* Set RTCP FB capability in the event */ if (event->type==PJMEDIA_EVENT_RX_RTCP_FB && - event->epub==&stream->rtcp) + event->epub==&stream->rtcp) { - pjmedia_event_rx_rtcp_fb_data *data = (pjmedia_event_rx_rtcp_fb_data*) - &event->data.rx_rtcp_fb; + pjmedia_event_rx_rtcp_fb_data *data = (pjmedia_event_rx_rtcp_fb_data*) + &event->data.rx_rtcp_fb; - /* Application not configured to listen to NACK, discard this event */ - if (stream->rtcp_fb_nack_cap_idx < 0) - return PJ_SUCCESS; + /* Application not configured to listen to NACK, discard this event */ + if (stream->rtcp_fb_nack_cap_idx < 0) + return PJ_SUCCESS; - data->cap = stream->si.loc_rtcp_fb.caps[stream->rtcp_fb_nack_cap_idx]; + data->cap = stream->si.loc_rtcp_fb.caps[stream->rtcp_fb_nack_cap_idx]; } /* Republish events */ return pjmedia_event_publish(NULL, stream, event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); + PJMEDIA_EVENT_PUBLISH_POST_EVENT); } @@ -2382,11 +2381,11 @@ static pj_status_t stream_event_cb(pjmedia_event *event, * Create media stream. */ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, - pj_pool_t *pool, - const pjmedia_stream_info *info, - pjmedia_transport *tp, - void *user_data, - pjmedia_stream **p_stream) + pj_pool_t *pool, + const pjmedia_stream_info *info, + pjmedia_transport *tp, + void *user_data, + pjmedia_stream **p_stream) { enum { M = 32 }; @@ -2402,11 +2401,11 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, PJ_ASSERT_RETURN(endpt && info && p_stream, PJ_EINVAL); if (pool == NULL) { - own_pool = pjmedia_endpt_create_pool( endpt, "strm%p", - PJMEDIA_STREAM_SIZE, - PJMEDIA_STREAM_INC); - PJ_ASSERT_RETURN(own_pool != NULL, PJ_ENOMEM); - pool = own_pool; + own_pool = pjmedia_endpt_create_pool( endpt, "strm%p", + PJMEDIA_STREAM_SIZE, + PJMEDIA_STREAM_INC); + PJ_ASSERT_RETURN(own_pool != NULL, PJ_ENOMEM); + pool = own_pool; } /* Allocate the media stream: */ @@ -2419,11 +2418,11 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, pj_memcpy(&stream->si, info, sizeof(*info)); pj_strdup(pool, &stream->si.fmt.encoding_name, &info->fmt.encoding_name); if (info->param) - stream->si.param = pjmedia_codec_param_clone(pool, info->param); + stream->si.param = pjmedia_codec_param_clone(pool, info->param); pjmedia_rtcp_fb_info_dup(pool, &stream->si.loc_rtcp_fb, - &info->loc_rtcp_fb); + &info->loc_rtcp_fb); pjmedia_rtcp_fb_info_dup(pool, &stream->si.rem_rtcp_fb, - &info->rem_rtcp_fb); + &info->rem_rtcp_fb); /* Init stream/port name */ name.ptr = (char*) pj_pool_alloc(pool, M); @@ -2434,8 +2433,8 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, */ pjmedia_port_info_init(&stream->port.info, &name, PJMEDIA_SIG_PORT_STREAM, - info->fmt.clock_rate, info->fmt.channel_cnt, - 16, 80); + info->fmt.clock_rate, info->fmt.channel_cnt, + 16, 80); afd = pjmedia_format_get_audio_format_detail(&stream->port.info.fmt, 1); /* Init port. */ @@ -2452,7 +2451,7 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, stream->dir = info->dir; stream->user_data = user_data; stream->rtcp_interval = (PJMEDIA_RTCP_INTERVAL-500 + (pj_rand()%1000)) * - info->fmt.clock_rate / 1000; + info->fmt.clock_rate / 1000; stream->rtcp_sdes_bye_disabled = info->rtcp_sdes_bye_disabled; stream->tx_event_pt = info->tx_event_pt ? info->tx_event_pt : -1; @@ -2471,55 +2470,55 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, stream->cname = info->cname; if (stream->cname.slen == 0) { - /* Build random RTCP CNAME. CNAME has user@host format */ - stream->cname.ptr = p = (char*) pj_pool_alloc(pool, 20); - pj_create_random_string(p, 5); - p += 5; - *p++ = '@'; *p++ = 'p'; *p++ = 'j'; - pj_create_random_string(p, 6); - p += 6; - *p++ = '.'; *p++ = 'o'; *p++ = 'r'; *p++ = 'g'; - stream->cname.slen = p - stream->cname.ptr; + /* Build random RTCP CNAME. CNAME has user@host format */ + stream->cname.ptr = p = (char*) pj_pool_alloc(pool, 20); + pj_create_random_string(p, 5); + p += 5; + *p++ = '@'; *p++ = 'p'; *p++ = 'j'; + pj_create_random_string(p, 6); + p += 6; + *p++ = '.'; *p++ = 'o'; *p++ = 'r'; *p++ = 'g'; + stream->cname.slen = p - stream->cname.ptr; } /* Create mutex to protect jitter buffer: */ status = pj_mutex_create_simple(pool, NULL, &stream->jb_mutex); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Create and initialize codec: */ status = pjmedia_codec_mgr_alloc_codec( stream->codec_mgr, - &info->fmt, &stream->codec); + &info->fmt, &stream->codec); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Get codec param: */ if (info->param) - stream->codec_param = *stream->si.param; + stream->codec_param = *stream->si.param; else { - status = pjmedia_codec_mgr_get_default_param(stream->codec_mgr, - &info->fmt, - &stream->codec_param); - if (status != PJ_SUCCESS) - goto err_cleanup; + status = pjmedia_codec_mgr_get_default_param(stream->codec_mgr, + &info->fmt, + &stream->codec_param); + if (status != PJ_SUCCESS) + goto err_cleanup; } /* Check for invalid max_bps. */ if (stream->codec_param.info.max_bps < stream->codec_param.info.avg_bps) - stream->codec_param.info.max_bps = stream->codec_param.info.avg_bps; + stream->codec_param.info.max_bps = stream->codec_param.info.avg_bps; /* Check for invalid frame per packet. */ if (stream->codec_param.setting.frm_per_pkt < 1) - stream->codec_param.setting.frm_per_pkt = 1; + stream->codec_param.setting.frm_per_pkt = 1; /* Init the codec. */ status = pjmedia_codec_init(stream->codec, pool); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Open the codec. */ @@ -2527,54 +2526,54 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, * it's negotiated in the SDP. */ if (!pj_stricmp2(&info->fmt.encoding_name, "opus")) { - stream->codec_param.info.clock_rate = info->fmt.clock_rate; - stream->codec_param.info.channel_cnt = info->fmt.channel_cnt; + stream->codec_param.info.clock_rate = info->fmt.clock_rate; + stream->codec_param.info.channel_cnt = info->fmt.channel_cnt; - /* Allocate decoding buffer as Opus can send a packet duration of - * up to 120 ms. - */ - stream->dec_buf_size = stream->codec_param.info.clock_rate * 120 / - 1000; - stream->dec_buf = (pj_int16_t*)pj_pool_alloc(pool, - stream->dec_buf_size * - sizeof(pj_int16_t)); + /* Allocate decoding buffer as Opus can send a packet duration of + * up to 120 ms. + */ + stream->dec_buf_size = stream->codec_param.info.clock_rate * 120 / + 1000; + stream->dec_buf = (pj_int16_t*)pj_pool_alloc(pool, + stream->dec_buf_size * + sizeof(pj_int16_t)); } status = pjmedia_codec_open(stream->codec, &stream->codec_param); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Set additional info and callbacks. */ stream->dec_ptime = stream->codec_param.info.frm_ptime; afd->bits_per_sample = 16; afd->frame_time_usec = stream->codec_param.info.frm_ptime * - stream->codec_param.setting.frm_per_pkt * 1000; + stream->codec_param.setting.frm_per_pkt * 1000; stream->port.info.fmt.id = stream->codec_param.info.fmt_id; if (stream->codec_param.info.fmt_id == PJMEDIA_FORMAT_L16) { - /* Raw format */ - afd->avg_bps = afd->max_bps = afd->clock_rate * afd->channel_count * - afd->bits_per_sample; + /* Raw format */ + afd->avg_bps = afd->max_bps = afd->clock_rate * afd->channel_count * + afd->bits_per_sample; - stream->port.put_frame = &put_frame; - stream->port.get_frame = &get_frame; + stream->port.put_frame = &put_frame; + stream->port.get_frame = &get_frame; } else { - /* Encoded format */ - afd->avg_bps = stream->codec_param.info.avg_bps; - afd->max_bps = stream->codec_param.info.max_bps; + /* Encoded format */ + afd->avg_bps = stream->codec_param.info.avg_bps; + afd->max_bps = stream->codec_param.info.max_bps; - /* Not applicable for 2.0 - if ((stream->codec_param.info.max_bps * - stream->codec_param.info.frm_ptime * - stream->codec_param.setting.frm_per_pkt) % 8000 != 0) - { - ++stream->port.info.bytes_per_frame; - } - stream->port.info.format.bitrate = stream->codec_param.info.avg_bps; - stream->port.info.format.vad = (stream->codec_param.setting.vad != 0); - */ + /* Not applicable for 2.0 + if ((stream->codec_param.info.max_bps * + stream->codec_param.info.frm_ptime * + stream->codec_param.setting.frm_per_pkt) % 8000 != 0) + { + ++stream->port.info.bytes_per_frame; + } + stream->port.info.format.bitrate = stream->codec_param.info.avg_bps; + stream->port.info.format.vad = (stream->codec_param.setting.vad != 0); + */ - stream->port.put_frame = &put_frame; - stream->port.get_frame = &get_frame_ext; + stream->port.put_frame = &put_frame; + stream->port.get_frame = &get_frame_ext; } /* If encoder and decoder's ptime are asymmetric, then we need to @@ -2582,45 +2581,45 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, * with iLBC */ if (stream->codec_param.info.enc_ptime!=0 && - stream->codec_param.info.enc_ptime!=stream->codec_param.info.frm_ptime) + stream->codec_param.info.enc_ptime!=stream->codec_param.info.frm_ptime) { - unsigned ptime; + unsigned ptime; - stream->enc_samples_per_pkt = stream->codec_param.info.enc_ptime * - stream->codec_param.info.channel_cnt * - afd->clock_rate / 1000; + stream->enc_samples_per_pkt = stream->codec_param.info.enc_ptime * + stream->codec_param.info.channel_cnt * + afd->clock_rate / 1000; - /* Set buffer size as twice the largest ptime value between - * stream's ptime, encoder ptime, or decoder ptime. - */ + /* Set buffer size as twice the largest ptime value between + * stream's ptime, encoder ptime, or decoder ptime. + */ - ptime = afd->frame_time_usec / 1000; + ptime = afd->frame_time_usec / 1000; - if (stream->codec_param.info.enc_ptime > ptime) - ptime = stream->codec_param.info.enc_ptime; + if (stream->codec_param.info.enc_ptime > ptime) + ptime = stream->codec_param.info.enc_ptime; - if (stream->codec_param.info.frm_ptime > ptime) - ptime = stream->codec_param.info.frm_ptime; + if (stream->codec_param.info.frm_ptime > ptime) + ptime = stream->codec_param.info.frm_ptime; - ptime <<= 1; + ptime <<= 1; - /* Allocate buffer */ - stream->enc_buf_size = afd->clock_rate * ptime / 1000; - stream->enc_buf = (pj_int16_t*) - pj_pool_alloc(pool, stream->enc_buf_size * 2); + /* Allocate buffer */ + stream->enc_buf_size = afd->clock_rate * ptime / 1000; + stream->enc_buf = (pj_int16_t*) + pj_pool_alloc(pool, stream->enc_buf_size * 2); } else { - stream->enc_samples_per_pkt = PJMEDIA_AFD_SPF(afd); + stream->enc_samples_per_pkt = PJMEDIA_AFD_SPF(afd); } /* Initially disable the VAD in the stream, to help traverse NAT better */ stream->vad_enabled = stream->codec_param.setting.vad; if (PJMEDIA_STREAM_VAD_SUSPEND_MSEC > 0 && stream->vad_enabled) { - stream->codec_param.setting.vad = 0; - stream->ts_vad_disabled = 0; - pjmedia_codec_modify(stream->codec, &stream->codec_param); - PJ_LOG(4,(stream->port.info.name.ptr,"VAD temporarily disabled")); + stream->codec_param.setting.vad = 0; + stream->ts_vad_disabled = 0; + pjmedia_codec_modify(stream->codec, &stream->codec_param); + PJ_LOG(4,(stream->port.info.name.ptr,"VAD temporarily disabled")); } /* Get the frame size */ @@ -2628,23 +2627,23 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, stream->frame_size = stream->codec_param.info.max_rx_frame_size; } else { stream->frame_size = stream->codec_param.info.max_bps * - stream->codec_param.info.frm_ptime / 8 / 1000; + stream->codec_param.info.frm_ptime / 8 / 1000; if ((stream->codec_param.info.max_bps * stream->codec_param.info.frm_ptime) % 8000 != 0) { - ++stream->frame_size; + ++stream->frame_size; } } /* How many consecutive PLC frames can be generated */ stream->max_plc_cnt = (MAX_PLC_MSEC+stream->codec_param.info.frm_ptime-1)/ - stream->codec_param.info.frm_ptime; + stream->codec_param.info.frm_ptime; /* Disable PLC until a "NORMAL" frame is gotten from the jitter buffer. */ stream->plc_cnt = stream->max_plc_cnt; #if defined(PJMEDIA_DTMF_DURATION_MSEC) && (PJMEDIA_DTMF_DURATION_MSEC > 0) stream->dtmf_duration = PJMEDIA_DTMF_DURATION_MSEC * - afd->clock_rate / 1000; + afd->clock_rate / 1000; #else stream->dtmf_duration = PJMEDIA_DTMF_DURATION; #endif @@ -2655,63 +2654,63 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, stream->rtp_rx_last_ts = 0; stream->rtp_rx_last_cnt = 0; stream->rtp_tx_ts_len_per_pkt = stream->enc_samples_per_pkt / - stream->codec_param.info.channel_cnt; + stream->codec_param.info.channel_cnt; stream->rtp_rx_ts_len_per_frame = PJMEDIA_AFD_SPF(afd) / - stream->codec_param.setting.frm_per_pkt / - stream->codec_param.info.channel_cnt; + stream->codec_param.setting.frm_per_pkt / + stream->codec_param.info.channel_cnt; if (info->fmt.pt == PJMEDIA_RTP_PT_G722) { - stream->has_g722_mpeg_bug = PJ_TRUE; - /* RTP clock rate = 1/2 real clock rate */ - stream->rtp_tx_ts_len_per_pkt >>= 1; + stream->has_g722_mpeg_bug = PJ_TRUE; + /* RTP clock rate = 1/2 real clock rate */ + stream->rtp_tx_ts_len_per_pkt >>= 1; #if defined(PJMEDIA_DTMF_DURATION_MSEC) && (PJMEDIA_DTMF_DURATION_MSEC > 0) - stream->dtmf_duration >>= 1; + stream->dtmf_duration >>= 1; #endif } else if (!pj_stricmp2(&info->fmt.encoding_name, "opus")) { - unsigned opus_ts_modifier = 48000 / afd->clock_rate; - stream->rtp_rx_check_cnt = 0; - stream->has_g722_mpeg_bug = PJ_TRUE; - stream->rtp_tx_ts_len_per_pkt *= opus_ts_modifier; - stream->rtp_rx_ts_len_per_frame *= opus_ts_modifier; - stream->detect_ptime_change = PJ_TRUE; + unsigned opus_ts_modifier = 48000 / afd->clock_rate; + stream->rtp_rx_check_cnt = 0; + stream->has_g722_mpeg_bug = PJ_TRUE; + stream->rtp_tx_ts_len_per_pkt *= opus_ts_modifier; + stream->rtp_rx_ts_len_per_frame *= opus_ts_modifier; + stream->detect_ptime_change = PJ_TRUE; #if defined(PJMEDIA_DTMF_DURATION_MSEC) && (PJMEDIA_DTMF_DURATION_MSEC > 0) - stream->dtmf_duration *= opus_ts_modifier; + stream->dtmf_duration *= opus_ts_modifier; #endif } #endif /* Init jitter buffer parameters: */ if (info->jb_max >= stream->codec_param.info.frm_ptime) - jb_max = (info->jb_max + stream->codec_param.info.frm_ptime - 1) / - stream->codec_param.info.frm_ptime; + jb_max = (info->jb_max + stream->codec_param.info.frm_ptime - 1) / + stream->codec_param.info.frm_ptime; else - jb_max = 500 / stream->codec_param.info.frm_ptime; + jb_max = 500 / stream->codec_param.info.frm_ptime; if (info->jb_min_pre >= stream->codec_param.info.frm_ptime) - jb_min_pre = info->jb_min_pre / stream->codec_param.info.frm_ptime; + jb_min_pre = info->jb_min_pre / stream->codec_param.info.frm_ptime; else - //jb_min_pre = 60 / stream->codec_param.info.frm_ptime; - jb_min_pre = 1; + //jb_min_pre = 60 / stream->codec_param.info.frm_ptime; + jb_min_pre = 1; if (info->jb_max_pre >= stream->codec_param.info.frm_ptime) - jb_max_pre = info->jb_max_pre / stream->codec_param.info.frm_ptime; + jb_max_pre = info->jb_max_pre / stream->codec_param.info.frm_ptime; else - //jb_max_pre = 240 / stream->codec_param.info.frm_ptime; - jb_max_pre = jb_max * 4 / 5; + //jb_max_pre = 240 / stream->codec_param.info.frm_ptime; + jb_max_pre = jb_max * 4 / 5; if (info->jb_init >= stream->codec_param.info.frm_ptime) - jb_init = info->jb_init / stream->codec_param.info.frm_ptime; + jb_init = info->jb_init / stream->codec_param.info.frm_ptime; else - //jb_init = (jb_min_pre + jb_max_pre) / 2; - jb_init = 0; + //jb_init = (jb_min_pre + jb_max_pre) / 2; + jb_init = 0; /* Create jitter buffer */ status = pjmedia_jbuf_create(pool, &stream->port.info.name, - stream->frame_size, - stream->codec_param.info.frm_ptime, - jb_max, &stream->jb); + stream->frame_size, + stream->codec_param.info.frm_ptime, + jb_max, &stream->jb); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Set up jitter buffer */ @@ -2721,66 +2720,66 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, /* Create decoder channel: */ status = create_channel( pool, stream, PJMEDIA_DIR_DECODING, - info->rx_pt, info, &stream->dec); + info->rx_pt, info, &stream->dec); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Create encoder channel: */ status = create_channel( pool, stream, PJMEDIA_DIR_ENCODING, - info->tx_pt, info, &stream->enc); + info->tx_pt, info, &stream->enc); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Init RTCP session: */ { - pjmedia_rtcp_session_setting rtcp_setting; + pjmedia_rtcp_session_setting rtcp_setting; - pjmedia_rtcp_session_setting_default(&rtcp_setting); - rtcp_setting.name = stream->port.info.name.ptr; - rtcp_setting.ssrc = info->ssrc; - rtcp_setting.rtp_ts_base = pj_ntohl(stream->enc->rtp.out_hdr.ts); - rtcp_setting.clock_rate = info->fmt.clock_rate; - rtcp_setting.samples_per_frame = PJMEDIA_AFD_SPF(afd); + pjmedia_rtcp_session_setting_default(&rtcp_setting); + rtcp_setting.name = stream->port.info.name.ptr; + rtcp_setting.ssrc = info->ssrc; + rtcp_setting.rtp_ts_base = pj_ntohl(stream->enc->rtp.out_hdr.ts); + rtcp_setting.clock_rate = info->fmt.clock_rate; + rtcp_setting.samples_per_frame = PJMEDIA_AFD_SPF(afd); #if defined(PJMEDIA_HANDLE_G722_MPEG_BUG) && (PJMEDIA_HANDLE_G722_MPEG_BUG!=0) - /* Special case for G.722 */ - if (info->fmt.pt == PJMEDIA_RTP_PT_G722) { - rtcp_setting.clock_rate = 8000; - rtcp_setting.samples_per_frame = 160; - } + /* Special case for G.722 */ + if (info->fmt.pt == PJMEDIA_RTP_PT_G722) { + rtcp_setting.clock_rate = 8000; + rtcp_setting.samples_per_frame = 160; + } #endif - pjmedia_rtcp_init2(&stream->rtcp, &rtcp_setting); + pjmedia_rtcp_init2(&stream->rtcp, &rtcp_setting); - if (info->rtp_seq_ts_set) { - stream->rtcp.stat.rtp_tx_last_seq = info->rtp_seq; - stream->rtcp.stat.rtp_tx_last_ts = info->rtp_ts; - } + if (info->rtp_seq_ts_set) { + stream->rtcp.stat.rtp_tx_last_seq = info->rtp_seq; + stream->rtcp.stat.rtp_tx_last_ts = info->rtp_ts; + } - /* Subscribe to RTCP events */ - pjmedia_event_subscribe(NULL, &stream_event_cb, stream, - &stream->rtcp); + /* Subscribe to RTCP events */ + pjmedia_event_subscribe(NULL, &stream_event_cb, stream, + &stream->rtcp); } /* Allocate outgoing RTCP buffer, should be enough to hold SR/RR, SDES, * BYE, and XR. */ stream->out_rtcp_pkt_size = sizeof(pjmedia_rtcp_sr_pkt) + - sizeof(pjmedia_rtcp_common) + - (4 + (unsigned)stream->cname.slen) + - 32; + sizeof(pjmedia_rtcp_common) + + (4 + (unsigned)stream->cname.slen) + + 32; #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) if (info->rtcp_xr_enabled) { - stream->out_rtcp_pkt_size += sizeof(pjmedia_rtcp_xr_pkt); + stream->out_rtcp_pkt_size += sizeof(pjmedia_rtcp_xr_pkt); } #endif if (stream->out_rtcp_pkt_size > PJMEDIA_MAX_MTU) - stream->out_rtcp_pkt_size = PJMEDIA_MAX_MTU; + stream->out_rtcp_pkt_size = PJMEDIA_MAX_MTU; stream->out_rtcp_pkt = pj_pool_alloc(pool, stream->out_rtcp_pkt_size); pj_bzero(&att_param, sizeof(att_param)); @@ -2790,9 +2789,9 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, pj_sockaddr_cp(&att_param.rem_addr, &info->rem_addr); pj_sockaddr_cp(&stream->rem_rtp_addr, &info->rem_addr); if (stream->si.rtcp_mux) { - pj_sockaddr_cp(&att_param.rem_rtcp, &info->rem_addr); + pj_sockaddr_cp(&att_param.rem_rtcp, &info->rem_addr); } else if (pj_sockaddr_has_addr(&info->rem_rtcp.addr)) { - pj_sockaddr_cp(&att_param.rem_rtcp, &info->rem_rtcp); + pj_sockaddr_cp(&att_param.rem_rtcp, &info->rem_rtcp); } att_param.addr_len = pj_sockaddr_get_len(&info->rem_addr); att_param.rtp_cb2 = &on_rx_rtp; @@ -2802,96 +2801,96 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, stream->transport = tp; status = pjmedia_transport_attach2(tp, &att_param); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) /* Enable RTCP XR and update stream info/config to RTCP XR */ if (info->rtcp_xr_enabled) { - int i; - - pjmedia_rtcp_enable_xr(&stream->rtcp, PJ_TRUE); - - /* Set RTCP XR TX interval */ - if (info->rtcp_xr_interval != 0) - stream->rtcp_xr_interval = info->rtcp_xr_interval; - else - stream->rtcp_xr_interval = (PJMEDIA_RTCP_INTERVAL + - (pj_rand() % 8000)) * - info->fmt.clock_rate / 1000; - - /* Additional third-party RTCP XR destination */ - if (info->rtcp_xr_dest.addr.sa_family != 0) { - stream->rtcp_xr_dest_len = pj_sockaddr_get_len(&info->rtcp_xr_dest); - pj_memcpy(&stream->rtcp_xr_dest, &info->rtcp_xr_dest, - stream->rtcp_xr_dest_len); - } - - /* jitter buffer adaptive info */ - i = PJMEDIA_RTCP_XR_JB_ADAPTIVE; - pjmedia_rtcp_xr_update_info(&stream->rtcp.xr_session, - PJMEDIA_RTCP_XR_INFO_CONF_JBA, - i); - - /* Jitter buffer aggressiveness info (estimated) */ - i = 7; - pjmedia_rtcp_xr_update_info(&stream->rtcp.xr_session, - PJMEDIA_RTCP_XR_INFO_CONF_JBR, - i); - - /* Jitter buffer absolute maximum delay */ - i = jb_max * stream->codec_param.info.frm_ptime; - pjmedia_rtcp_xr_update_info(&stream->rtcp.xr_session, - PJMEDIA_RTCP_XR_INFO_JB_ABS_MAX, - i); - - /* PLC info */ - if (stream->codec_param.setting.plc == 0) - i = PJMEDIA_RTCP_XR_PLC_DIS; - else + int i; + + pjmedia_rtcp_enable_xr(&stream->rtcp, PJ_TRUE); + + /* Set RTCP XR TX interval */ + if (info->rtcp_xr_interval != 0) + stream->rtcp_xr_interval = info->rtcp_xr_interval; + else + stream->rtcp_xr_interval = (PJMEDIA_RTCP_INTERVAL + + (pj_rand() % 8000)) * + info->fmt.clock_rate / 1000; + + /* Additional third-party RTCP XR destination */ + if (info->rtcp_xr_dest.addr.sa_family != 0) { + stream->rtcp_xr_dest_len = pj_sockaddr_get_len(&info->rtcp_xr_dest); + pj_memcpy(&stream->rtcp_xr_dest, &info->rtcp_xr_dest, + stream->rtcp_xr_dest_len); + } + + /* jitter buffer adaptive info */ + i = PJMEDIA_RTCP_XR_JB_ADAPTIVE; + pjmedia_rtcp_xr_update_info(&stream->rtcp.xr_session, + PJMEDIA_RTCP_XR_INFO_CONF_JBA, + i); + + /* Jitter buffer aggressiveness info (estimated) */ + i = 7; + pjmedia_rtcp_xr_update_info(&stream->rtcp.xr_session, + PJMEDIA_RTCP_XR_INFO_CONF_JBR, + i); + + /* Jitter buffer absolute maximum delay */ + i = jb_max * stream->codec_param.info.frm_ptime; + pjmedia_rtcp_xr_update_info(&stream->rtcp.xr_session, + PJMEDIA_RTCP_XR_INFO_JB_ABS_MAX, + i); + + /* PLC info */ + if (stream->codec_param.setting.plc == 0) + i = PJMEDIA_RTCP_XR_PLC_DIS; + else #if PJMEDIA_WSOLA_IMP==PJMEDIA_WSOLA_IMP_WSOLA - i = PJMEDIA_RTCP_XR_PLC_ENH; + i = PJMEDIA_RTCP_XR_PLC_ENH; #else - i = PJMEDIA_RTCP_XR_PLC_DIS; + i = PJMEDIA_RTCP_XR_PLC_DIS; #endif - pjmedia_rtcp_xr_update_info(&stream->rtcp.xr_session, - PJMEDIA_RTCP_XR_INFO_CONF_PLC, - i); + pjmedia_rtcp_xr_update_info(&stream->rtcp.xr_session, + PJMEDIA_RTCP_XR_INFO_CONF_PLC, + i); } #endif /* Check if we should send RTCP-FB */ if (stream->si.rem_rtcp_fb.cap_count) { - pjmedia_rtcp_fb_info *rfi = &stream->si.rem_rtcp_fb; - unsigned i; - - for (i = 0; i < rfi->cap_count; ++i) { - if (rfi->caps[i].type == PJMEDIA_RTCP_FB_NACK && - rfi->caps[i].param.slen == 0) - { - stream->send_rtcp_fb_nack = PJ_TRUE; - PJ_LOG(4,(stream->port.info.name.ptr, - "Send RTCP-FB generic NACK")); - break; - } - } + pjmedia_rtcp_fb_info *rfi = &stream->si.rem_rtcp_fb; + unsigned i; + + for (i = 0; i < rfi->cap_count; ++i) { + if (rfi->caps[i].type == PJMEDIA_RTCP_FB_NACK && + rfi->caps[i].param.slen == 0) + { + stream->send_rtcp_fb_nack = PJ_TRUE; + PJ_LOG(4,(stream->port.info.name.ptr, + "Send RTCP-FB generic NACK")); + break; + } + } } /* Check if we should process incoming RTCP-FB */ stream->rtcp_fb_nack_cap_idx = -1; if (stream->si.loc_rtcp_fb.cap_count) { - pjmedia_rtcp_fb_info *lfi = &stream->si.loc_rtcp_fb; - unsigned i; - - for (i = 0; i < lfi->cap_count; ++i) { - if (lfi->caps[i].type == PJMEDIA_RTCP_FB_NACK && - lfi->caps[i].param.slen == 0) - { - stream->rtcp_fb_nack_cap_idx = i; - PJ_LOG(4,(stream->port.info.name.ptr, - "Receive RTCP-FB generic NACK")); - break; - } - } + pjmedia_rtcp_fb_info *lfi = &stream->si.loc_rtcp_fb; + unsigned i; + + for (i = 0; i < lfi->cap_count; ++i) { + if (lfi->caps[i].type == PJMEDIA_RTCP_FB_NACK && + lfi->caps[i].param.slen == 0) + { + stream->rtcp_fb_nack_cap_idx = i; + PJ_LOG(4,(stream->port.info.name.ptr, + "Receive RTCP-FB generic NACK")); + break; + } + } } /* Update the stream info's codec param */ @@ -2899,10 +2898,10 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, /* Check the zero frame buffer. */ if (stream->enc_samples_per_pkt > PJ_ARRAY_SIZE(zero_frame)) { - stream->zero_frame = (pj_int16_t*)pj_pool_zalloc(pool, - sizeof(pj_int16_t)*stream->enc_samples_per_pkt); + stream->zero_frame = (pj_int16_t*)pj_pool_zalloc(pool, + sizeof(pj_int16_t)*stream->enc_samples_per_pkt); } else { - stream->zero_frame = zero_frame; + stream->zero_frame = zero_frame; } /* Send RTCP SDES */ @@ -2913,36 +2912,36 @@ PJ_DEF(pj_status_t) pjmedia_stream_create( pjmedia_endpt *endpt, #if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0 /* NAT hole punching by sending KA packet via RTP transport. */ if (stream->use_ka) - send_keep_alive_packet(stream); + send_keep_alive_packet(stream); #endif #if TRACE_JB { - char trace_name[PJ_MAXPATH]; - pj_ssize_t len; - - pj_ansi_snprintf(trace_name, sizeof(trace_name), - TRACE_JB_PATH_PREFIX "%s.csv", - stream->port.info.name.ptr); - status = pj_file_open(pool, trace_name, PJ_O_WRONLY, - &stream->trace_jb_fd); - if (status != PJ_SUCCESS) { - stream->trace_jb_fd = TRACE_JB_INVALID_FD; - PJ_PERROR(3,(THIS_FILE, status, - "Failed creating RTP trace file '%s'", trace_name)); - } else { - stream->trace_jb_buf = (char*)pj_pool_alloc(pool, PJ_LOG_MAX_SIZE); - - /* Print column header */ - len = pj_ansi_snprintf(stream->trace_jb_buf, PJ_LOG_MAX_SIZE, - "Time, Operation, Size, Frame Count, " - "Frame type, RTP Seq, RTP TS, RTP M, " - "JB size, JB burst level, JB prefetch\n"); - if (len < 1 || len >= PJ_LOG_MAX_SIZE) - len = PJ_LOG_MAX_SIZE-1; - pj_file_write(stream->trace_jb_fd, stream->trace_jb_buf, &len); - pj_file_flush(stream->trace_jb_fd); - } + char trace_name[PJ_MAXPATH]; + pj_ssize_t len; + + pj_ansi_snprintf(trace_name, sizeof(trace_name), + TRACE_JB_PATH_PREFIX "%s.csv", + stream->port.info.name.ptr); + status = pj_file_open(pool, trace_name, PJ_O_WRONLY, + &stream->trace_jb_fd); + if (status != PJ_SUCCESS) { + stream->trace_jb_fd = TRACE_JB_INVALID_FD; + PJ_PERROR(3,(THIS_FILE, status, + "Failed creating RTP trace file '%s'", trace_name)); + } else { + stream->trace_jb_buf = (char*)pj_pool_alloc(pool, PJ_LOG_MAX_SIZE); + + /* Print column header */ + len = pj_ansi_snprintf(stream->trace_jb_buf, PJ_LOG_MAX_SIZE, + "Time, Operation, Size, Frame Count, " + "Frame type, RTP Seq, RTP TS, RTP M, " + "JB size, JB burst level, JB prefetch\n"); + if (len < 1 || len >= PJ_LOG_MAX_SIZE) + len = PJ_LOG_MAX_SIZE-1; + pj_file_write(stream->trace_jb_fd, stream->trace_jb_buf, &len); + pj_file_flush(stream->trace_jb_fd); + } } #endif @@ -2972,9 +2971,9 @@ PJ_DEF(pj_status_t) pjmedia_stream_destroy( pjmedia_stream *stream ) /* Send RTCP BYE (also SDES & XR) */ if (stream->transport && !stream->rtcp_sdes_bye_disabled) { #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) - send_rtcp(stream, PJ_TRUE, PJ_TRUE, stream->rtcp.xr_enabled, PJ_FALSE); + send_rtcp(stream, PJ_TRUE, PJ_TRUE, stream->rtcp.xr_enabled, PJ_FALSE); #else - send_rtcp(stream, PJ_TRUE, PJ_TRUE, PJ_FALSE, PJ_FALSE); + send_rtcp(stream, PJ_TRUE, PJ_TRUE, PJ_FALSE, PJ_FALSE); #endif } @@ -2982,86 +2981,86 @@ PJ_DEF(pj_status_t) pjmedia_stream_destroy( pjmedia_stream *stream ) * RFC 2833 RTP packet with 'End' flag set. */ if (stream->tx_dtmf_count && stream->tx_dtmf_buf[0].duration != 0) { - pjmedia_frame frame_out; - pjmedia_channel *channel = stream->enc; - int first=0, last=0; - void *rtphdr; - int rtphdrlen; + pjmedia_frame frame_out; + pjmedia_channel *channel = stream->enc; + int first=0, last=0; + void *rtphdr; + int rtphdrlen; - pj_bzero(&frame_out, sizeof(frame_out)); - frame_out.buf = ((char*)channel->out_pkt) + sizeof(pjmedia_rtp_hdr); - frame_out.size = 0; + pj_bzero(&frame_out, sizeof(frame_out)); + frame_out.buf = ((char*)channel->out_pkt) + sizeof(pjmedia_rtp_hdr); + frame_out.size = 0; - create_dtmf_payload(stream, &frame_out, 1, &first, &last); + create_dtmf_payload(stream, &frame_out, 1, &first, &last); - /* Encapsulate into RTP packet. Note that: + /* Encapsulate into RTP packet. Note that: * - RTP marker should be set on the beginning of a new event - * - RTP timestamp is constant for the same packet. + * - RTP timestamp is constant for the same packet. */ - status = pjmedia_rtp_encode_rtp( &channel->rtp, - stream->tx_event_pt, first, - (int)frame_out.size, 0, - (const void**)&rtphdr, - &rtphdrlen); - if (status == PJ_SUCCESS) { - /* Copy RTP header to the beginning of packet */ - pj_memcpy(channel->out_pkt, rtphdr, sizeof(pjmedia_rtp_hdr)); - - /* Send the RTP packet to the transport. */ - status = pjmedia_transport_send_rtp(stream->transport, - channel->out_pkt, - frame_out.size + - sizeof(pjmedia_rtp_hdr)); - } - - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stream->port.info.name.ptr, status, - "Error sending RTP/DTMF end packet")); - } + status = pjmedia_rtp_encode_rtp( &channel->rtp, + stream->tx_event_pt, first, + (int)frame_out.size, 0, + (const void**)&rtphdr, + &rtphdrlen); + if (status == PJ_SUCCESS) { + /* Copy RTP header to the beginning of packet */ + pj_memcpy(channel->out_pkt, rtphdr, sizeof(pjmedia_rtp_hdr)); + + /* Send the RTP packet to the transport. */ + status = pjmedia_transport_send_rtp(stream->transport, + channel->out_pkt, + frame_out.size + + sizeof(pjmedia_rtp_hdr)); + } + + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stream->port.info.name.ptr, status, + "Error sending RTP/DTMF end packet")); + } } /* Unsubscribe from RTCP session events */ pjmedia_event_unsubscribe(NULL, &stream_event_cb, stream, - &stream->rtcp); + &stream->rtcp); /* Detach from transport * MUST NOT hold stream mutex while detaching from transport, as * it may cause deadlock. See ticket #460 for the details. */ if (stream->transport) { - pjmedia_transport_detach(stream->transport, stream); - stream->transport = NULL; + pjmedia_transport_detach(stream->transport, stream); + stream->transport = NULL; } /* This function may be called when stream is partly initialized. */ if (stream->jb_mutex) - pj_mutex_lock(stream->jb_mutex); + pj_mutex_lock(stream->jb_mutex); /* Free codec. */ if (stream->codec) { - pjmedia_codec_close(stream->codec); - pjmedia_codec_mgr_dealloc_codec(stream->codec_mgr, stream->codec); - stream->codec = NULL; + pjmedia_codec_close(stream->codec); + pjmedia_codec_mgr_dealloc_codec(stream->codec_mgr, stream->codec); + stream->codec = NULL; } /* Free mutex */ if (stream->jb_mutex) { pj_mutex_unlock(stream->jb_mutex); - pj_mutex_destroy(stream->jb_mutex); - stream->jb_mutex = NULL; + pj_mutex_destroy(stream->jb_mutex); + stream->jb_mutex = NULL; } /* Destroy jitter buffer */ if (stream->jb) - pjmedia_jbuf_destroy(stream->jb); + pjmedia_jbuf_destroy(stream->jb); #if TRACE_JB if (TRACE_JB_OPENED(stream)) { - pj_file_close(stream->trace_jb_fd); - stream->trace_jb_fd = TRACE_JB_INVALID_FD; + pj_file_close(stream->trace_jb_fd); + stream->trace_jb_fd = TRACE_JB_INVALID_FD; } #endif @@ -3084,7 +3083,7 @@ PJ_DEF(char) pjmedia_stream_get_last_jb_frame_type(pjmedia_stream *stream) * Get the port interface. */ PJ_DEF(pj_status_t) pjmedia_stream_get_port( pjmedia_stream *stream, - pjmedia_port **p_port ) + pjmedia_port **p_port ) { *p_port = &stream->port; return PJ_SUCCESS; @@ -3109,19 +3108,19 @@ PJ_DEF(pj_status_t) pjmedia_stream_start(pjmedia_stream *stream) PJ_ASSERT_RETURN(stream && stream->enc && stream->dec, PJ_EINVALIDOP); if (stream->enc && (stream->dir & PJMEDIA_DIR_ENCODING)) { - stream->enc->paused = 0; - //pjmedia_snd_stream_start(stream->enc->snd_stream); - PJ_LOG(4,(stream->port.info.name.ptr, "Encoder stream started")); + stream->enc->paused = 0; + //pjmedia_snd_stream_start(stream->enc->snd_stream); + PJ_LOG(4,(stream->port.info.name.ptr, "Encoder stream started")); } else { - PJ_LOG(4,(stream->port.info.name.ptr, "Encoder stream paused")); + PJ_LOG(4,(stream->port.info.name.ptr, "Encoder stream paused")); } if (stream->dec && (stream->dir & PJMEDIA_DIR_DECODING)) { - stream->dec->paused = 0; - //pjmedia_snd_stream_start(stream->dec->snd_stream); - PJ_LOG(4,(stream->port.info.name.ptr, "Decoder stream started")); + stream->dec->paused = 0; + //pjmedia_snd_stream_start(stream->dec->snd_stream); + PJ_LOG(4,(stream->port.info.name.ptr, "Decoder stream started")); } else { - PJ_LOG(4,(stream->port.info.name.ptr, "Decoder stream paused")); + PJ_LOG(4,(stream->port.info.name.ptr, "Decoder stream paused")); } return PJ_SUCCESS; @@ -3132,7 +3131,7 @@ PJ_DEF(pj_status_t) pjmedia_stream_start(pjmedia_stream *stream) */ PJ_DEF(pj_status_t) pjmedia_stream_modify_codec_param(pjmedia_stream *stream, - const pjmedia_codec_param *param) + const pjmedia_codec_param *param) { PJ_ASSERT_RETURN(stream && param, PJ_EINVAL); @@ -3141,7 +3140,7 @@ pjmedia_stream_modify_codec_param(pjmedia_stream *stream, PJ_DEF(pj_status_t) pjmedia_stream_get_info( const pjmedia_stream *stream, - pjmedia_stream_info *info) + pjmedia_stream_info *info) { PJ_ASSERT_RETURN(stream && info, PJ_EINVAL); @@ -3153,7 +3152,7 @@ PJ_DEF(pj_status_t) pjmedia_stream_get_info( const pjmedia_stream *stream, * Get stream statistics. */ PJ_DEF(pj_status_t) pjmedia_stream_get_stat( const pjmedia_stream *stream, - pjmedia_rtcp_stat *stat) + pjmedia_rtcp_stat *stat) { PJ_ASSERT_RETURN(stream && stat, PJ_EINVAL); @@ -3180,13 +3179,13 @@ PJ_DEF(pj_status_t) pjmedia_stream_reset_stat(pjmedia_stream *stream) * Get stream extended statistics. */ PJ_DEF(pj_status_t) pjmedia_stream_get_stat_xr( const pjmedia_stream *stream, - pjmedia_rtcp_xr_stat *stat) + pjmedia_rtcp_xr_stat *stat) { PJ_ASSERT_RETURN(stream && stat, PJ_EINVAL); if (stream->rtcp.xr_enabled) { - pj_memcpy(stat, &stream->rtcp.xr_session.stat, sizeof(pjmedia_rtcp_xr_stat)); - return PJ_SUCCESS; + pj_memcpy(stat, &stream->rtcp.xr_session.stat, sizeof(pjmedia_rtcp_xr_stat)); + return PJ_SUCCESS; } return PJ_ENOTFOUND; } @@ -3196,7 +3195,7 @@ PJ_DEF(pj_status_t) pjmedia_stream_get_stat_xr( const pjmedia_stream *stream, * Get jitter buffer state. */ PJ_DEF(pj_status_t) pjmedia_stream_get_stat_jbuf(const pjmedia_stream *stream, - pjmedia_jb_state *state) + pjmedia_jb_state *state) { PJ_ASSERT_RETURN(stream && state, PJ_EINVAL); return pjmedia_jbuf_get_state(stream->jb, state); @@ -3206,24 +3205,24 @@ PJ_DEF(pj_status_t) pjmedia_stream_get_stat_jbuf(const pjmedia_stream *stream, * Pause stream. */ PJ_DEF(pj_status_t) pjmedia_stream_pause( pjmedia_stream *stream, - pjmedia_dir dir) + pjmedia_dir dir) { PJ_ASSERT_RETURN(stream, PJ_EINVAL); if ((dir & PJMEDIA_DIR_ENCODING) && stream->enc) { - stream->enc->paused = 1; - PJ_LOG(4,(stream->port.info.name.ptr, "Encoder stream paused")); + stream->enc->paused = 1; + PJ_LOG(4,(stream->port.info.name.ptr, "Encoder stream paused")); } if ((dir & PJMEDIA_DIR_DECODING) && stream->dec) { - stream->dec->paused = 1; + stream->dec->paused = 1; - /* Also reset jitter buffer */ - pj_mutex_lock( stream->jb_mutex ); - pjmedia_jbuf_reset(stream->jb); - pj_mutex_unlock( stream->jb_mutex ); + /* Also reset jitter buffer */ + pj_mutex_lock( stream->jb_mutex ); + pjmedia_jbuf_reset(stream->jb); + pj_mutex_unlock( stream->jb_mutex ); - PJ_LOG(4,(stream->port.info.name.ptr, "Decoder stream paused")); + PJ_LOG(4,(stream->port.info.name.ptr, "Decoder stream paused")); } return PJ_SUCCESS; @@ -3234,19 +3233,19 @@ PJ_DEF(pj_status_t) pjmedia_stream_pause( pjmedia_stream *stream, * Resume stream */ PJ_DEF(pj_status_t) pjmedia_stream_resume( pjmedia_stream *stream, - pjmedia_dir dir) + pjmedia_dir dir) { PJ_ASSERT_RETURN(stream, PJ_EINVAL); if ((dir & PJMEDIA_DIR_ENCODING) && stream->enc) { - stream->enc->paused = 0; - PJ_LOG(4,(stream->port.info.name.ptr, "Encoder stream resumed")); + stream->enc->paused = 0; + PJ_LOG(4,(stream->port.info.name.ptr, "Encoder stream resumed")); } if ((dir & PJMEDIA_DIR_DECODING) && stream->dec) { - stream->dec->paused = 0; - stream->soft_start_cnt = PJMEDIA_STREAM_SOFT_START; - PJ_LOG(4,(stream->port.info.name.ptr, "Decoder stream resumed")); + stream->dec->paused = 0; + stream->soft_start_cnt = PJMEDIA_STREAM_SOFT_START; + PJ_LOG(4,(stream->port.info.name.ptr, "Decoder stream resumed")); } return PJ_SUCCESS; @@ -3256,7 +3255,7 @@ PJ_DEF(pj_status_t) pjmedia_stream_resume( pjmedia_stream *stream, * Dial DTMF */ PJ_DEF(pj_status_t) pjmedia_stream_dial_dtmf( pjmedia_stream *stream, - const pj_str_t *digit_char) + const pj_str_t *digit_char) { pj_status_t status = PJ_SUCCESS; @@ -3267,63 +3266,63 @@ PJ_DEF(pj_status_t) pjmedia_stream_dial_dtmf( pjmedia_stream *stream, /* Check that remote can receive DTMF events. */ if (stream->tx_event_pt < 0) { - return PJMEDIA_RTP_EREMNORFC2833; + return PJMEDIA_RTP_EREMNORFC2833; } pj_mutex_lock(stream->jb_mutex); if (stream->tx_dtmf_count+digit_char->slen >= - (long)PJ_ARRAY_SIZE(stream->tx_dtmf_buf)) + (long)PJ_ARRAY_SIZE(stream->tx_dtmf_buf)) { - status = PJ_ETOOMANY; + status = PJ_ETOOMANY; } else { - int i; - - /* convert ASCII digits into payload type first, to make sure - * that all digits are valid. - */ - for (i=0; islen; ++i) { - unsigned pt; - int dig = pj_tolower(digit_char->ptr[i]); - - if (dig >= '0' && dig <= '9') - { - pt = dig - '0'; - } - else if (dig >= 'a' && dig <= 'd') - { - pt = dig - 'a' + 12; - } - else if (dig == '*') - { - pt = 10; - } - else if (dig == '#') - { - pt = 11; - } + int i; + + /* convert ASCII digits into payload type first, to make sure + * that all digits are valid. + */ + for (i=0; islen; ++i) { + unsigned pt; + int dig = pj_tolower(digit_char->ptr[i]); + + if (dig >= '0' && dig <= '9') + { + pt = dig - '0'; + } + else if (dig >= 'a' && dig <= 'd') + { + pt = dig - 'a' + 12; + } + else if (dig == '*') + { + pt = 10; + } + else if (dig == '#') + { + pt = 11; + } #if defined(PJMEDIA_HAS_DTMF_FLASH) && PJMEDIA_HAS_DTMF_FLASH!= 0 - else if (dig == 'r') - { - pt = 16; - } + else if (dig == 'r') + { + pt = 16; + } #endif - else - { - status = PJMEDIA_RTP_EINDTMF; - break; - } + else + { + status = PJMEDIA_RTP_EINDTMF; + break; + } - stream->tx_dtmf_buf[stream->tx_dtmf_count+i].event = pt; - stream->tx_dtmf_buf[stream->tx_dtmf_count+i].duration = 0; - stream->tx_dtmf_buf[stream->tx_dtmf_count+i].ebit_cnt = 0; - } + stream->tx_dtmf_buf[stream->tx_dtmf_count+i].event = pt; + stream->tx_dtmf_buf[stream->tx_dtmf_count+i].duration = 0; + stream->tx_dtmf_buf[stream->tx_dtmf_count+i].ebit_cnt = 0; + } - if (status != PJ_SUCCESS) - goto on_return; + if (status != PJ_SUCCESS) + goto on_return; - /* Increment digit count only if all digits are valid. */ - stream->tx_dtmf_count += (int)digit_char->slen; + /* Increment digit count only if all digits are valid. */ + stream->tx_dtmf_count += (int)digit_char->slen; } on_return: @@ -3346,8 +3345,8 @@ PJ_DEF(pj_bool_t) pjmedia_stream_check_dtmf(pjmedia_stream *stream) * Retrieve incoming DTMF digits from the stream's DTMF buffer. */ PJ_DEF(pj_status_t) pjmedia_stream_get_dtmf( pjmedia_stream *stream, - char *digits, - unsigned *size) + char *digits, + unsigned *size) { PJ_ASSERT_RETURN(stream && digits && size, PJ_EINVAL); @@ -3357,16 +3356,16 @@ PJ_DEF(pj_status_t) pjmedia_stream_get_dtmf( pjmedia_stream *stream, pj_mutex_lock(stream->jb_mutex); if (stream->rx_dtmf_count < *size) - *size = stream->rx_dtmf_count; + *size = stream->rx_dtmf_count; if (*size) { - pj_memcpy(digits, stream->rx_dtmf_buf, *size); - stream->rx_dtmf_count -= *size; - if (stream->rx_dtmf_count) { - pj_memmove(stream->rx_dtmf_buf, - &stream->rx_dtmf_buf[*size], - stream->rx_dtmf_count); - } + pj_memcpy(digits, stream->rx_dtmf_buf, *size); + stream->rx_dtmf_count -= *size; + if (stream->rx_dtmf_count) { + pj_memmove(stream->rx_dtmf_buf, + &stream->rx_dtmf_buf[*size], + stream->rx_dtmf_count); + } } pj_mutex_unlock(stream->jb_mutex); @@ -3379,10 +3378,10 @@ PJ_DEF(pj_status_t) pjmedia_stream_get_dtmf( pjmedia_stream *stream, * Set callback to be called upon receiving DTMF digits. */ PJ_DEF(pj_status_t) pjmedia_stream_set_dtmf_callback(pjmedia_stream *stream, - void (*cb)(pjmedia_stream*, - void *user_data, - int digit), - void *user_data) + void (*cb)(pjmedia_stream*, + void *user_data, + int digit), + void *user_data) { PJ_ASSERT_RETURN(stream, PJ_EINVAL); @@ -3440,7 +3439,7 @@ pjmedia_stream_send_rtcp_bye( pjmedia_stream *stream ) PJ_ASSERT_RETURN(stream, PJ_EINVAL); if (stream->enc && stream->transport) { - return send_rtcp(stream, PJ_TRUE, PJ_TRUE, PJ_FALSE, PJ_FALSE); + return send_rtcp(stream, PJ_TRUE, PJ_TRUE, PJ_FALSE, PJ_FALSE); } return PJ_SUCCESS; @@ -3452,7 +3451,7 @@ pjmedia_stream_send_rtcp_bye( pjmedia_stream *stream ) */ PJ_DEF(pj_status_t) pjmedia_stream_get_rtp_session_info(pjmedia_stream *stream, - pjmedia_stream_rtp_sess_info *session_info) + pjmedia_stream_rtp_sess_info *session_info) { session_info->rx_rtp = &stream->dec->rtp; session_info->tx_rtp = &stream->enc->rtp; diff --git a/pjmedia/src/pjmedia/stream_common.c b/pjmedia/src/pjmedia/stream_common.c index 3d68e9ad37..ac5d236f36 100644 --- a/pjmedia/src/pjmedia/stream_common.c +++ b/pjmedia/src/pjmedia/stream_common.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011 Teluu Inc. (http://www.teluu.com) * @@ -19,7 +18,7 @@ #include #include -#define THIS_FILE "stream_common.c" +#define THIS_FILE "stream_common.c" #if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0 @@ -38,9 +37,9 @@ pjmedia_stream_ka_config_default(pjmedia_stream_ka_config *cfg) * Parse fmtp for specified format/payload type. */ PJ_DEF(pj_status_t) pjmedia_stream_info_parse_fmtp( pj_pool_t *pool, - const pjmedia_sdp_media *m, - unsigned pt, - pjmedia_codec_fmtp *fmtp) + const pjmedia_sdp_media *m, + unsigned pt, + pjmedia_codec_fmtp *fmtp) { const pjmedia_sdp_attr *attr; pjmedia_sdp_fmtp sdp_fmtp; @@ -57,12 +56,12 @@ PJ_DEF(pj_status_t) pjmedia_stream_info_parse_fmtp( pj_pool_t *pool, fmt = pj_str(fmt_buf); attr = pjmedia_sdp_media_find_attr2(m, "fmtp", &fmt); if (attr == NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Parse "fmtp" attribute */ status = pjmedia_sdp_attr_get_fmtp(attr, &sdp_fmtp); if (status != PJ_SUCCESS) - return status; + return status; /* Prepare parsing */ p = sdp_fmtp.fmt_param.ptr; @@ -70,53 +69,53 @@ PJ_DEF(pj_status_t) pjmedia_stream_info_parse_fmtp( pj_pool_t *pool, /* Parse */ while (p < p_end) { - char *token, *start, *end; - - if (fmtp->cnt >= PJMEDIA_CODEC_MAX_FMTP_CNT) { - PJ_LOG(4,(THIS_FILE, - "Warning: fmtp parameter count exceeds " - "PJMEDIA_CODEC_MAX_FMTP_CNT")); - return PJ_SUCCESS; - } - - /* Skip whitespaces */ - while (p < p_end && (*p == ' ' || *p == '\t')) ++p; - if (p == p_end) - break; - - /* Get token */ - start = p; - while (p < p_end && *p != ';' && *p != '=') ++p; - end = p - 1; - - /* Right trim */ - while (end >= start && (*end == ' ' || *end == '\t' || - *end == '\r' || *end == '\n' )) - --end; - - /* Forward a char after trimming */ - ++end; - - /* Store token */ - if (end > start) { - if (pool) { - token = (char*)pj_pool_alloc(pool, end - start); - pj_ansi_strncpy(token, start, end - start); - } else { - token = start; - } - if (*p == '=') - /* Got param name */ - pj_strset(&fmtp->param[fmtp->cnt].name, token, end - start); - else - /* Got param value */ - pj_strset(&fmtp->param[fmtp->cnt++].val, token, end - start); - } else if (*p != '=') { - ++fmtp->cnt; - } - - /* Next */ - ++p; + char *token, *start, *end; + + if (fmtp->cnt >= PJMEDIA_CODEC_MAX_FMTP_CNT) { + PJ_LOG(4,(THIS_FILE, + "Warning: fmtp parameter count exceeds " + "PJMEDIA_CODEC_MAX_FMTP_CNT")); + return PJ_SUCCESS; + } + + /* Skip whitespaces */ + while (p < p_end && (*p == ' ' || *p == '\t')) ++p; + if (p == p_end) + break; + + /* Get token */ + start = p; + while (p < p_end && *p != ';' && *p != '=') ++p; + end = p - 1; + + /* Right trim */ + while (end >= start && (*end == ' ' || *end == '\t' || + *end == '\r' || *end == '\n' )) + --end; + + /* Forward a char after trimming */ + ++end; + + /* Store token */ + if (end > start) { + if (pool) { + token = (char*)pj_pool_alloc(pool, end - start); + pj_ansi_strncpy(token, start, end - start); + } else { + token = start; + } + if (*p == '=') + /* Got param name */ + pj_strset(&fmtp->param[fmtp->cnt].name, token, end - start); + else + /* Got param value */ + pj_strset(&fmtp->param[fmtp->cnt++].val, token, end - start); + } else if (*p != '=') { + ++fmtp->cnt; + } + + /* Next */ + ++p; } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia/stream_info.c b/pjmedia/src/pjmedia/stream_info.c index c066e6d3eb..f07895b7fa 100644 --- a/pjmedia/src/pjmedia/stream_info.c +++ b/pjmedia/src/pjmedia/stream_info.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,32 +30,32 @@ static const pj_str_t ID_RTPMAP = { "rtpmap", 6 }; static const pj_str_t ID_TELEPHONE_EVENT = { "telephone-event", 15 }; static void get_opus_channels_and_clock_rate(const pjmedia_codec_fmtp *enc_fmtp, - const pjmedia_codec_fmtp *dec_fmtp, - unsigned *channel_cnt, - unsigned *clock_rate) + const pjmedia_codec_fmtp *dec_fmtp, + unsigned *channel_cnt, + unsigned *clock_rate) { unsigned i; unsigned enc_channel_cnt = 0, local_channel_cnt = 0; unsigned enc_clock_rate = 0, local_clock_rate = 0; for (i = 0; i < dec_fmtp->cnt; ++i) { - if (!pj_stricmp2(&dec_fmtp->param[i].name, "sprop-maxcapturerate")) { - local_clock_rate = (unsigned)pj_strtoul(&dec_fmtp->param[i].val); - } else if (!pj_stricmp2(&dec_fmtp->param[i].name, "sprop-stereo")) { - local_channel_cnt = (unsigned)pj_strtoul(&dec_fmtp->param[i].val); - local_channel_cnt = (local_channel_cnt > 0) ? 2 : 1; - } + if (!pj_stricmp2(&dec_fmtp->param[i].name, "sprop-maxcapturerate")) { + local_clock_rate = (unsigned)pj_strtoul(&dec_fmtp->param[i].val); + } else if (!pj_stricmp2(&dec_fmtp->param[i].name, "sprop-stereo")) { + local_channel_cnt = (unsigned)pj_strtoul(&dec_fmtp->param[i].val); + local_channel_cnt = (local_channel_cnt > 0) ? 2 : 1; + } } if (!local_clock_rate) local_clock_rate = *clock_rate; if (!local_channel_cnt) local_channel_cnt = *channel_cnt; for (i = 0; i < enc_fmtp->cnt; ++i) { - if (!pj_stricmp2(&enc_fmtp->param[i].name, "maxplaybackrate")) { - enc_clock_rate = (unsigned)pj_strtoul(&enc_fmtp->param[i].val); - } else if (!pj_stricmp2(&enc_fmtp->param[i].name, "stereo")) { - enc_channel_cnt = (unsigned)pj_strtoul(&enc_fmtp->param[i].val); - enc_channel_cnt = (enc_channel_cnt > 0) ? 2 : 1; - } + if (!pj_stricmp2(&enc_fmtp->param[i].name, "maxplaybackrate")) { + enc_clock_rate = (unsigned)pj_strtoul(&enc_fmtp->param[i].val); + } else if (!pj_stricmp2(&enc_fmtp->param[i].name, "stereo")) { + enc_channel_cnt = (unsigned)pj_strtoul(&enc_fmtp->param[i].val); + enc_channel_cnt = (enc_channel_cnt > 0) ? 2 : 1; + } } /* The default is a standard mono session with 48000 Hz clock rate * (RFC 7587, section 7) @@ -65,20 +64,20 @@ static void get_opus_channels_and_clock_rate(const pjmedia_codec_fmtp *enc_fmtp, if (!enc_channel_cnt) enc_channel_cnt = 1; *clock_rate = (enc_clock_rate < local_clock_rate) ? enc_clock_rate : - local_clock_rate; + local_clock_rate; *channel_cnt = (enc_channel_cnt < local_channel_cnt) ? enc_channel_cnt : - local_channel_cnt; + local_channel_cnt; } /* * Internal function for collecting codec info and param from the SDP media. */ static pj_status_t get_audio_codec_info_param(pjmedia_stream_info *si, - pj_pool_t *pool, - pjmedia_codec_mgr *mgr, - const pjmedia_sdp_media *local_m, - const pjmedia_sdp_media *rem_m) + pj_pool_t *pool, + pjmedia_codec_mgr *mgr, + const pjmedia_sdp_media *local_m, + const pjmedia_sdp_media *rem_m) { const pjmedia_sdp_attr *attr; pjmedia_sdp_rtpmap *rtpmap; @@ -88,32 +87,32 @@ static pj_status_t get_audio_codec_info_param(pjmedia_stream_info *si, /* Find the first codec which is not telephone-event */ for ( fmti = 0; fmti < local_m->desc.fmt_count; ++fmti ) { - pjmedia_sdp_rtpmap r; + pjmedia_sdp_rtpmap r; - if ( !pj_isdigit(*local_m->desc.fmt[fmti].ptr) ) - return PJMEDIA_EINVALIDPT; - pt = pj_strtoul(&local_m->desc.fmt[fmti]); + if ( !pj_isdigit(*local_m->desc.fmt[fmti].ptr) ) + return PJMEDIA_EINVALIDPT; + pt = pj_strtoul(&local_m->desc.fmt[fmti]); - if (pt < 96) { - /* This is known static PT. Skip rtpmap checking because it is - * optional. */ - break; - } + if (pt < 96) { + /* This is known static PT. Skip rtpmap checking because it is + * optional. */ + break; + } - attr = pjmedia_sdp_media_find_attr(local_m, &ID_RTPMAP, - &local_m->desc.fmt[fmti]); - if (attr == NULL) - continue; + attr = pjmedia_sdp_media_find_attr(local_m, &ID_RTPMAP, + &local_m->desc.fmt[fmti]); + if (attr == NULL) + continue; - status = pjmedia_sdp_attr_get_rtpmap(attr, &r); - if (status != PJ_SUCCESS) - continue; + status = pjmedia_sdp_attr_get_rtpmap(attr, &r); + if (status != PJ_SUCCESS) + continue; - if (pj_strcmp(&r.enc_name, &ID_TELEPHONE_EVENT) != 0) - break; + if (pj_strcmp(&r.enc_name, &ID_TELEPHONE_EVENT) != 0) + break; } if ( fmti >= local_m->desc.fmt_count ) - return PJMEDIA_EINVALIDPT; + return PJMEDIA_EINVALIDPT; /* Get payload type for receiving direction */ si->rx_pt = pt; @@ -123,223 +122,223 @@ static pj_status_t get_audio_codec_info_param(pjmedia_stream_info *si, * For dynamic payload types, MUST get the rtpmap. */ if (pt < 96) { - pj_bool_t has_rtpmap; - - rtpmap = NULL; - has_rtpmap = PJ_TRUE; - - attr = pjmedia_sdp_media_find_attr(local_m, &ID_RTPMAP, - &local_m->desc.fmt[fmti]); - if (attr == NULL) { - has_rtpmap = PJ_FALSE; - } - if (attr != NULL) { - status = pjmedia_sdp_attr_to_rtpmap(pool, attr, &rtpmap); - if (status != PJ_SUCCESS) - has_rtpmap = PJ_FALSE; - } - - /* Build codec format info: */ - if (has_rtpmap) { - si->fmt.type = si->type; - si->fmt.pt = pj_strtoul(&local_m->desc.fmt[fmti]); - pj_strdup(pool, &si->fmt.encoding_name, &rtpmap->enc_name); - si->fmt.clock_rate = rtpmap->clock_rate; + pj_bool_t has_rtpmap; + + rtpmap = NULL; + has_rtpmap = PJ_TRUE; + + attr = pjmedia_sdp_media_find_attr(local_m, &ID_RTPMAP, + &local_m->desc.fmt[fmti]); + if (attr == NULL) { + has_rtpmap = PJ_FALSE; + } + if (attr != NULL) { + status = pjmedia_sdp_attr_to_rtpmap(pool, attr, &rtpmap); + if (status != PJ_SUCCESS) + has_rtpmap = PJ_FALSE; + } + + /* Build codec format info: */ + if (has_rtpmap) { + si->fmt.type = si->type; + si->fmt.pt = pj_strtoul(&local_m->desc.fmt[fmti]); + pj_strdup(pool, &si->fmt.encoding_name, &rtpmap->enc_name); + si->fmt.clock_rate = rtpmap->clock_rate; #if defined(PJMEDIA_HANDLE_G722_MPEG_BUG) && (PJMEDIA_HANDLE_G722_MPEG_BUG != 0) - /* The session info should have the actual clock rate, because - * this info is used for calculationg buffer size, etc in stream - */ - if (si->fmt.pt == PJMEDIA_RTP_PT_G722) - si->fmt.clock_rate = 16000; + /* The session info should have the actual clock rate, because + * this info is used for calculationg buffer size, etc in stream + */ + if (si->fmt.pt == PJMEDIA_RTP_PT_G722) + si->fmt.clock_rate = 16000; #endif - /* For audio codecs, rtpmap parameters denotes the number of - * channels. - */ - if (si->type == PJMEDIA_TYPE_AUDIO && rtpmap->param.slen) { - si->fmt.channel_cnt = (unsigned) pj_strtoul(&rtpmap->param); - } else { - si->fmt.channel_cnt = 1; - } + /* For audio codecs, rtpmap parameters denotes the number of + * channels. + */ + if (si->type == PJMEDIA_TYPE_AUDIO && rtpmap->param.slen) { + si->fmt.channel_cnt = (unsigned) pj_strtoul(&rtpmap->param); + } else { + si->fmt.channel_cnt = 1; + } - } else { - const pjmedia_codec_info *p_info; + } else { + const pjmedia_codec_info *p_info; - status = pjmedia_codec_mgr_get_codec_info( mgr, pt, &p_info); - if (status != PJ_SUCCESS) - return status; + status = pjmedia_codec_mgr_get_codec_info( mgr, pt, &p_info); + if (status != PJ_SUCCESS) + return status; - pj_memcpy(&si->fmt, p_info, sizeof(pjmedia_codec_info)); - } + pj_memcpy(&si->fmt, p_info, sizeof(pjmedia_codec_info)); + } - /* For static payload type, pt's are symetric */ - si->tx_pt = pt; + /* For static payload type, pt's are symetric */ + si->tx_pt = pt; } else { - pjmedia_codec_id codec_id; - pj_str_t codec_id_st; - const pjmedia_codec_info *p_info; - - attr = pjmedia_sdp_media_find_attr(local_m, &ID_RTPMAP, - &local_m->desc.fmt[fmti]); - if (attr == NULL) - return PJMEDIA_EMISSINGRTPMAP; - - status = pjmedia_sdp_attr_to_rtpmap(pool, attr, &rtpmap); - if (status != PJ_SUCCESS) - return status; - - /* Build codec format info: */ - - si->fmt.type = si->type; - si->fmt.pt = pj_strtoul(&local_m->desc.fmt[fmti]); - si->fmt.encoding_name = rtpmap->enc_name; - si->fmt.clock_rate = rtpmap->clock_rate; - - /* For audio codecs, rtpmap parameters denotes the number of - * channels. - */ - if (si->type == PJMEDIA_TYPE_AUDIO && rtpmap->param.slen) { - si->fmt.channel_cnt = (unsigned) pj_strtoul(&rtpmap->param); - } else { - si->fmt.channel_cnt = 1; - } - - /* Normalize the codec info from codec manager. Note that the - * payload type will be resetted to its default (it might have - * been rewritten by the SDP negotiator to match to the remote - * offer), this is intentional as currently some components may - * prefer (or even require) the default PT in codec info. - */ - pjmedia_codec_info_to_id(&si->fmt, codec_id, sizeof(codec_id)); - - i = 1; - codec_id_st = pj_str(codec_id); - status = pjmedia_codec_mgr_find_codecs_by_id(mgr, &codec_id_st, - &i, &p_info, NULL); - if (status != PJ_SUCCESS) - return status; - - pj_memcpy(&si->fmt, p_info, sizeof(pjmedia_codec_info)); - - /* Determine payload type for outgoing channel, by finding - * dynamic payload type in remote SDP that matches the answer. - */ - si->tx_pt = 0xFFFF; - for (i=0; idesc.fmt_count; ++i) { - if (pjmedia_sdp_neg_fmt_match(pool, - (pjmedia_sdp_media*)local_m, fmti, - (pjmedia_sdp_media*)rem_m, i, 0) == - PJ_SUCCESS) - { - /* Found matched codec. */ - si->tx_pt = pj_strtoul(&rem_m->desc.fmt[i]); - break; - } - } - - if (si->tx_pt == 0xFFFF) - return PJMEDIA_EMISSINGRTPMAP; + pjmedia_codec_id codec_id; + pj_str_t codec_id_st; + const pjmedia_codec_info *p_info; + + attr = pjmedia_sdp_media_find_attr(local_m, &ID_RTPMAP, + &local_m->desc.fmt[fmti]); + if (attr == NULL) + return PJMEDIA_EMISSINGRTPMAP; + + status = pjmedia_sdp_attr_to_rtpmap(pool, attr, &rtpmap); + if (status != PJ_SUCCESS) + return status; + + /* Build codec format info: */ + + si->fmt.type = si->type; + si->fmt.pt = pj_strtoul(&local_m->desc.fmt[fmti]); + si->fmt.encoding_name = rtpmap->enc_name; + si->fmt.clock_rate = rtpmap->clock_rate; + + /* For audio codecs, rtpmap parameters denotes the number of + * channels. + */ + if (si->type == PJMEDIA_TYPE_AUDIO && rtpmap->param.slen) { + si->fmt.channel_cnt = (unsigned) pj_strtoul(&rtpmap->param); + } else { + si->fmt.channel_cnt = 1; + } + + /* Normalize the codec info from codec manager. Note that the + * payload type will be resetted to its default (it might have + * been rewritten by the SDP negotiator to match to the remote + * offer), this is intentional as currently some components may + * prefer (or even require) the default PT in codec info. + */ + pjmedia_codec_info_to_id(&si->fmt, codec_id, sizeof(codec_id)); + + i = 1; + codec_id_st = pj_str(codec_id); + status = pjmedia_codec_mgr_find_codecs_by_id(mgr, &codec_id_st, + &i, &p_info, NULL); + if (status != PJ_SUCCESS) + return status; + + pj_memcpy(&si->fmt, p_info, sizeof(pjmedia_codec_info)); + + /* Determine payload type for outgoing channel, by finding + * dynamic payload type in remote SDP that matches the answer. + */ + si->tx_pt = 0xFFFF; + for (i=0; idesc.fmt_count; ++i) { + if (pjmedia_sdp_neg_fmt_match(pool, + (pjmedia_sdp_media*)local_m, fmti, + (pjmedia_sdp_media*)rem_m, i, 0) == + PJ_SUCCESS) + { + /* Found matched codec. */ + si->tx_pt = pj_strtoul(&rem_m->desc.fmt[i]); + break; + } + } + + if (si->tx_pt == 0xFFFF) + return PJMEDIA_EMISSINGRTPMAP; } /* Now that we have codec info, get the codec param. */ si->param = PJ_POOL_ALLOC_T(pool, pjmedia_codec_param); status = pjmedia_codec_mgr_get_default_param(mgr, &si->fmt, - si->param); + si->param); /* Get remote fmtp for our encoder. */ pjmedia_stream_info_parse_fmtp(pool, rem_m, si->tx_pt, - &si->param->setting.enc_fmtp); + &si->param->setting.enc_fmtp); /* Get local fmtp for our decoder. */ pjmedia_stream_info_parse_fmtp(pool, local_m, si->rx_pt, - &si->param->setting.dec_fmtp); + &si->param->setting.dec_fmtp); if (!pj_stricmp2(&si->fmt.encoding_name, "opus")) { - get_opus_channels_and_clock_rate(&si->param->setting.enc_fmtp, - &si->param->setting.dec_fmtp, - &si->fmt.channel_cnt, - &si->fmt.clock_rate); + get_opus_channels_and_clock_rate(&si->param->setting.enc_fmtp, + &si->param->setting.dec_fmtp, + &si->fmt.channel_cnt, + &si->fmt.clock_rate); } /* Get the remote ptime for our encoder. */ attr = pjmedia_sdp_attr_find2(rem_m->attr_count, rem_m->attr, - "ptime", NULL); + "ptime", NULL); if (attr) { - pj_str_t tmp_val = attr->value; - unsigned frm_per_pkt; + pj_str_t tmp_val = attr->value; + unsigned frm_per_pkt; - pj_strltrim(&tmp_val); + pj_strltrim(&tmp_val); - /* Round up ptime when the specified is not multiple of frm_ptime */ - frm_per_pkt = (pj_strtoul(&tmp_val) + - si->param->info.frm_ptime/2) / - si->param->info.frm_ptime; - if (frm_per_pkt != 0) { + /* Round up ptime when the specified is not multiple of frm_ptime */ + frm_per_pkt = (pj_strtoul(&tmp_val) + + si->param->info.frm_ptime/2) / + si->param->info.frm_ptime; + if (frm_per_pkt != 0) { si->param->setting.frm_per_pkt = (pj_uint8_t)frm_per_pkt; } } /* Get remote maxptime for our encoder. */ attr = pjmedia_sdp_attr_find2(rem_m->attr_count, rem_m->attr, - "maxptime", NULL); + "maxptime", NULL); if (attr) { - pj_str_t tmp_val = attr->value; + pj_str_t tmp_val = attr->value; - pj_strltrim(&tmp_val); - si->tx_maxptime = pj_strtoul(&tmp_val); + pj_strltrim(&tmp_val); + si->tx_maxptime = pj_strtoul(&tmp_val); } /* When direction is NONE (it means SDP negotiation has failed) we don't * need to return a failure here, as returning failure will cause * the whole SDP to be rejected. See ticket #: - * http:// + * http:// * * Thanks Alain Totouom */ if (status != PJ_SUCCESS && si->dir != PJMEDIA_DIR_NONE) - return status; + return status; /* Get incomming payload type for telephone-events */ si->rx_event_pt = -1; for (i=0; iattr_count; ++i) { - pjmedia_sdp_rtpmap r; - - attr = local_m->attr[i]; - if (pj_strcmp(&attr->name, &ID_RTPMAP) != 0) - continue; - if (pjmedia_sdp_attr_get_rtpmap(attr, &r) != PJ_SUCCESS) - continue; - if (pj_strcmp(&r.enc_name, &ID_TELEPHONE_EVENT) == 0) { - si->rx_event_pt = pj_strtoul(&r.pt); - rx_ev_clock_rate = r.clock_rate; - break; - } + pjmedia_sdp_rtpmap r; + + attr = local_m->attr[i]; + if (pj_strcmp(&attr->name, &ID_RTPMAP) != 0) + continue; + if (pjmedia_sdp_attr_get_rtpmap(attr, &r) != PJ_SUCCESS) + continue; + if (pj_strcmp(&r.enc_name, &ID_TELEPHONE_EVENT) == 0) { + si->rx_event_pt = pj_strtoul(&r.pt); + rx_ev_clock_rate = r.clock_rate; + break; + } } /* Get outgoing payload type for telephone-events */ si->tx_event_pt = -1; for (i=0; iattr_count; ++i) { - pjmedia_sdp_rtpmap r; - - attr = rem_m->attr[i]; - if (pj_strcmp(&attr->name, &ID_RTPMAP) != 0) - continue; - if (pjmedia_sdp_attr_get_rtpmap(attr, &r) != PJ_SUCCESS) - continue; - if (pj_strcmp(&r.enc_name, &ID_TELEPHONE_EVENT) == 0) { - /* Check if the clock rate matches local event's clock rate. */ - if (r.clock_rate == rx_ev_clock_rate) { - si->tx_event_pt = pj_strtoul(&r.pt); - break; - } else if (si->tx_event_pt == -1) { - si->tx_event_pt = pj_strtoul(&r.pt); - } - } + pjmedia_sdp_rtpmap r; + + attr = rem_m->attr[i]; + if (pj_strcmp(&attr->name, &ID_RTPMAP) != 0) + continue; + if (pjmedia_sdp_attr_get_rtpmap(attr, &r) != PJ_SUCCESS) + continue; + if (pj_strcmp(&r.enc_name, &ID_TELEPHONE_EVENT) == 0) { + /* Check if the clock rate matches local event's clock rate. */ + if (r.clock_rate == rx_ev_clock_rate) { + si->tx_event_pt = pj_strtoul(&r.pt); + break; + } else if (si->tx_event_pt == -1) { + si->tx_event_pt = pj_strtoul(&r.pt); + } + } } return PJ_SUCCESS; @@ -351,12 +350,12 @@ static pj_status_t get_audio_codec_info_param(pjmedia_stream_info *si, * Create stream info from SDP media line. */ PJ_DEF(pj_status_t) pjmedia_stream_info_from_sdp( - pjmedia_stream_info *si, - pj_pool_t *pool, - pjmedia_endpt *endpt, - const pjmedia_sdp_session *local, - const pjmedia_sdp_session *remote, - unsigned stream_idx) + pjmedia_stream_info *si, + pj_pool_t *pool, + pjmedia_endpt *endpt, + const pjmedia_sdp_session *local, + const pjmedia_sdp_session *remote, + unsigned stream_idx) { const pj_str_t STR_INACTIVE = { "inactive", 8 }; const pj_str_t STR_SENDONLY = { "sendonly", 8 }; @@ -384,15 +383,15 @@ PJ_DEF(pj_status_t) pjmedia_stream_info_from_sdp( local_conn = local_m->conn ? local_m->conn : local->conn; if (local_conn == NULL) - return PJMEDIA_SDP_EMISSINGCONN; + return PJMEDIA_SDP_EMISSINGCONN; rem_conn = rem_m->conn ? rem_m->conn : remote->conn; if (rem_conn == NULL) - return PJMEDIA_SDP_EMISSINGCONN; + return PJMEDIA_SDP_EMISSINGCONN; /* Media type must be audio */ if (pjmedia_get_type(&local_m->desc.media) != PJMEDIA_TYPE_AUDIO) - return PJMEDIA_EINVALIMEDIATYPE; + return PJMEDIA_EINVALIMEDIATYPE; /* Get codec manager. */ mgr = pjmedia_endpt_get_codec_mgr(endpt); @@ -415,171 +414,171 @@ PJ_DEF(pj_status_t) pjmedia_stream_info_from_sdp( * the transport instance will do more validation later. */ status = pjmedia_sdp_transport_cmp(&rem_m->desc.transport, - &local_m->desc.transport); + &local_m->desc.transport); if (status != PJ_SUCCESS) - return PJMEDIA_SDPNEG_EINVANSTP; + return PJMEDIA_SDPNEG_EINVANSTP; /* Get the transport protocol */ si->proto = pjmedia_sdp_transport_get_proto(&local_m->desc.transport); /* Just return success if stream is not RTP/AVP compatible */ if (!PJMEDIA_TP_PROTO_HAS_FLAG(si->proto, PJMEDIA_TP_PROTO_RTP_AVP)) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Check address family in remote SDP */ rem_af = pj_AF_UNSPEC(); if (pj_stricmp(&rem_conn->net_type, &ID_IN)==0) { - if (pj_stricmp(&rem_conn->addr_type, &ID_IP4)==0) { - rem_af = pj_AF_INET(); - } else if (pj_stricmp(&rem_conn->addr_type, &ID_IP6)==0) { - rem_af = pj_AF_INET6(); - } + if (pj_stricmp(&rem_conn->addr_type, &ID_IP4)==0) { + rem_af = pj_AF_INET(); + } else if (pj_stricmp(&rem_conn->addr_type, &ID_IP6)==0) { + rem_af = pj_AF_INET6(); + } } if (rem_af==pj_AF_UNSPEC()) { - /* Unsupported address family */ - return PJ_EAFNOTSUP; + /* Unsupported address family */ + return PJ_EAFNOTSUP; } /* Set remote address: */ status = pj_sockaddr_init(rem_af, &si->rem_addr, &rem_conn->addr, - rem_m->desc.port); + rem_m->desc.port); if (status == PJ_ERESOLVE && rem_af == pj_AF_INET()) { - /* Handle special case in NAT64 scenario where for some reason, server - * puts IPv6 (literal or FQDN) in SDP answer while indicating "IP4" - * in its address type, let's retry resolving using AF_INET6. - */ - status = pj_sockaddr_init(pj_AF_INET6(), &si->rem_addr, - &rem_conn->addr, rem_m->desc.port); + /* Handle special case in NAT64 scenario where for some reason, server + * puts IPv6 (literal or FQDN) in SDP answer while indicating "IP4" + * in its address type, let's retry resolving using AF_INET6. + */ + status = pj_sockaddr_init(pj_AF_INET6(), &si->rem_addr, + &rem_conn->addr, rem_m->desc.port); } if (status != PJ_SUCCESS) { - /* Invalid IP address. */ - return PJMEDIA_EINVALIDIP; + /* Invalid IP address. */ + return PJMEDIA_EINVALIDIP; } /* Check address family of local info */ local_af = pj_AF_UNSPEC(); if (pj_stricmp(&local_conn->net_type, &ID_IN)==0) { - if (pj_stricmp(&local_conn->addr_type, &ID_IP4)==0) { - local_af = pj_AF_INET(); - } else if (pj_stricmp(&local_conn->addr_type, &ID_IP6)==0) { - local_af = pj_AF_INET6(); - } + if (pj_stricmp(&local_conn->addr_type, &ID_IP4)==0) { + local_af = pj_AF_INET(); + } else if (pj_stricmp(&local_conn->addr_type, &ID_IP6)==0) { + local_af = pj_AF_INET6(); + } } if (local_af==pj_AF_UNSPEC()) { - /* Unsupported address family */ - return PJ_SUCCESS; + /* Unsupported address family */ + return PJ_SUCCESS; } /* Set remote address: */ status = pj_sockaddr_init(local_af, &si->local_addr, &local_conn->addr, - local_m->desc.port); + local_m->desc.port); if (status != PJ_SUCCESS) { - /* Invalid IP address. */ - return PJMEDIA_EINVALIDIP; + /* Invalid IP address. */ + return PJMEDIA_EINVALIDIP; } /* Local and remote address family must match, except when ICE is used * by both sides (see also ticket #1952). */ if (local_af != rem_af) { - const pj_str_t STR_ICE_CAND = { "candidate", 9 }; - if (pjmedia_sdp_media_find_attr(rem_m, &STR_ICE_CAND, NULL)==NULL || - pjmedia_sdp_media_find_attr(local_m, &STR_ICE_CAND, NULL)==NULL) - { - return PJ_EAFNOTSUP; - } + const pj_str_t STR_ICE_CAND = { "candidate", 9 }; + if (pjmedia_sdp_media_find_attr(rem_m, &STR_ICE_CAND, NULL)==NULL || + pjmedia_sdp_media_find_attr(local_m, &STR_ICE_CAND, NULL)==NULL) + { + return PJ_EAFNOTSUP; + } } /* Media direction: */ if (local_m->desc.port == 0 || - pj_sockaddr_has_addr(&si->local_addr)==PJ_FALSE || - pj_sockaddr_has_addr(&si->rem_addr)==PJ_FALSE || - pjmedia_sdp_media_find_attr(local_m, &STR_INACTIVE, NULL)!=NULL) + pj_sockaddr_has_addr(&si->local_addr)==PJ_FALSE || + pj_sockaddr_has_addr(&si->rem_addr)==PJ_FALSE || + pjmedia_sdp_media_find_attr(local_m, &STR_INACTIVE, NULL)!=NULL) { - /* Inactive stream. */ + /* Inactive stream. */ - si->dir = PJMEDIA_DIR_NONE; + si->dir = PJMEDIA_DIR_NONE; } else if (pjmedia_sdp_media_find_attr(local_m, &STR_SENDONLY, NULL)!=NULL) { - /* Send only stream. */ + /* Send only stream. */ - si->dir = PJMEDIA_DIR_ENCODING; + si->dir = PJMEDIA_DIR_ENCODING; } else if (pjmedia_sdp_media_find_attr(local_m, &STR_RECVONLY, NULL)!=NULL) { - /* Recv only stream. */ + /* Recv only stream. */ - si->dir = PJMEDIA_DIR_DECODING; + si->dir = PJMEDIA_DIR_DECODING; } else { - /* Send and receive stream. */ + /* Send and receive stream. */ - si->dir = PJMEDIA_DIR_ENCODING_DECODING; + si->dir = PJMEDIA_DIR_ENCODING_DECODING; } /* No need to do anything else if stream is rejected */ if (local_m->desc.port == 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Check if "rtcp-mux" is present in the SDP. */ attr = pjmedia_sdp_attr_find2(rem_m->attr_count, rem_m->attr, - "rtcp-mux", NULL); + "rtcp-mux", NULL); if (attr) - si->rtcp_mux = PJ_TRUE; + si->rtcp_mux = PJ_TRUE; /* If "rtcp" attribute is present in the SDP, set the RTCP address * from that attribute. Otherwise, calculate from RTP address. */ attr = pjmedia_sdp_attr_find2(rem_m->attr_count, rem_m->attr, - "rtcp", NULL); + "rtcp", NULL); if (attr) { - pjmedia_sdp_rtcp_attr rtcp; - status = pjmedia_sdp_attr_get_rtcp(attr, &rtcp); - if (status == PJ_SUCCESS) { - if (rtcp.addr.slen) { - status = pj_sockaddr_init(rem_af, &si->rem_rtcp, &rtcp.addr, - (pj_uint16_t)rtcp.port); - } else { - pj_sockaddr_init(rem_af, &si->rem_rtcp, NULL, - (pj_uint16_t)rtcp.port); - pj_memcpy(pj_sockaddr_get_addr(&si->rem_rtcp), - pj_sockaddr_get_addr(&si->rem_addr), - pj_sockaddr_get_addr_len(&si->rem_addr)); - } - } + pjmedia_sdp_rtcp_attr rtcp; + status = pjmedia_sdp_attr_get_rtcp(attr, &rtcp); + if (status == PJ_SUCCESS) { + if (rtcp.addr.slen) { + status = pj_sockaddr_init(rem_af, &si->rem_rtcp, &rtcp.addr, + (pj_uint16_t)rtcp.port); + } else { + pj_sockaddr_init(rem_af, &si->rem_rtcp, NULL, + (pj_uint16_t)rtcp.port); + pj_memcpy(pj_sockaddr_get_addr(&si->rem_rtcp), + pj_sockaddr_get_addr(&si->rem_addr), + pj_sockaddr_get_addr_len(&si->rem_addr)); + } + } } if (!pj_sockaddr_has_addr(&si->rem_rtcp)) { - int rtcp_port; + int rtcp_port; - pj_memcpy(&si->rem_rtcp, &si->rem_addr, sizeof(pj_sockaddr)); - rtcp_port = pj_sockaddr_get_port(&si->rem_addr) + 1; - pj_sockaddr_set_port(&si->rem_rtcp, (pj_uint16_t)rtcp_port); + pj_memcpy(&si->rem_rtcp, &si->rem_addr, sizeof(pj_sockaddr)); + rtcp_port = pj_sockaddr_get_port(&si->rem_addr) + 1; + pj_sockaddr_set_port(&si->rem_rtcp, (pj_uint16_t)rtcp_port); } /* Check if "ssrc" attribute is present in the SDP. */ for (i = 0; i < rem_m->attr_count; i++) { - if (pj_strcmp2(&rem_m->attr[i]->name, "ssrc") == 0) { - pjmedia_sdp_ssrc_attr ssrc; - - status = pjmedia_sdp_attr_get_ssrc( - (const pjmedia_sdp_attr *)rem_m->attr[i], &ssrc); - if (status == PJ_SUCCESS) { - si->has_rem_ssrc = PJ_TRUE; - si->rem_ssrc = ssrc.ssrc; - if (ssrc.cname.slen > 0) { - pj_strdup(pool, &si->rem_cname, &ssrc.cname); - break; - } - } - } + if (pj_strcmp2(&rem_m->attr[i]->name, "ssrc") == 0) { + pjmedia_sdp_ssrc_attr ssrc; + + status = pjmedia_sdp_attr_get_ssrc( + (const pjmedia_sdp_attr *)rem_m->attr[i], &ssrc); + if (status == PJ_SUCCESS) { + si->has_rem_ssrc = PJ_TRUE; + si->rem_ssrc = ssrc.ssrc; + if (ssrc.cname.slen > 0) { + pj_strdup(pool, &si->rem_cname, &ssrc.cname); + break; + } + } + } } /* Get the payload number for receive channel. */ @@ -592,20 +591,20 @@ PJ_DEF(pj_status_t) pjmedia_stream_info_from_sdp( // And codec must be numeric! if (!pj_isdigit(*local_m->desc.fmt[0].ptr) || - !pj_isdigit(*rem_m->desc.fmt[0].ptr)) + !pj_isdigit(*rem_m->desc.fmt[0].ptr)) { - return PJMEDIA_EINVALIDPT; + return PJMEDIA_EINVALIDPT; } pt = pj_strtoul(&local_m->desc.fmt[0]); pj_assert(PJMEDIA_RTP_PT_TELEPHONE_EVENTS==0 || - pt != PJMEDIA_RTP_PT_TELEPHONE_EVENTS); + pt != PJMEDIA_RTP_PT_TELEPHONE_EVENTS); */ /* Get codec info and param */ status = get_audio_codec_info_param(si, pool, mgr, local_m, rem_m); if (status != PJ_SUCCESS) - return status; + return status; /* Leave SSRC to random. */ si->ssrc = pj_rand(); @@ -616,15 +615,15 @@ PJ_DEF(pj_status_t) pjmedia_stream_info_from_sdp( /* Get local RTCP-FB info */ status = pjmedia_rtcp_fb_decode_sdp2(pool, endpt, NULL, local, stream_idx, - si->rx_pt, &si->loc_rtcp_fb); + si->rx_pt, &si->loc_rtcp_fb); if (status != PJ_SUCCESS) - return status; + return status; /* Get remote RTCP-FB info */ status = pjmedia_rtcp_fb_decode_sdp2(pool, endpt, NULL, remote, stream_idx, - si->tx_pt, &si->rem_rtcp_fb); + si->tx_pt, &si->rem_rtcp_fb); if (status != PJ_SUCCESS) - return status; + return status; return status; } diff --git a/pjmedia/src/pjmedia/tonegen.c b/pjmedia/src/pjmedia/tonegen.c index d9f5dcfac3..20b5fe8ff4 100644 --- a/pjmedia/src/pjmedia/tonegen.c +++ b/pjmedia/src/pjmedia/tonegen.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,7 +26,7 @@ #include /* amplitude */ -#define AMP PJMEDIA_TONEGEN_VOLUME +#define AMP PJMEDIA_TONEGEN_VOLUME #ifndef M_PI # define M_PI ((DATA)3.141592653589793238462643383279) @@ -35,7 +34,7 @@ #if PJMEDIA_TONEGEN_ALG==PJMEDIA_TONEGEN_SINE #include - #define DATA double + #define DATA double /* * This is the good old tone generator using sin(). @@ -46,19 +45,19 @@ */ struct gen { - DATA add; - DATA c; - DATA vol; + DATA add; + DATA c; + DATA vol; }; #define GEN_INIT(var,R,F,A) var.add = ((DATA)F)/R, var.c=0, var.vol=A #define GEN_SAMP(val,var) val = (short)(sin(var.c * 2 * M_PI) * \ - var.vol); \ - var.c += var.add + var.vol); \ + var.c += var.add #elif PJMEDIA_TONEGEN_ALG==PJMEDIA_TONEGEN_FLOATING_POINT #include - #define DATA float + #define DATA float /* * Default floating-point based tone generation using sine wave @@ -73,15 +72,15 @@ */ struct gen { - DATA a, s0, s1; + DATA a, s0, s1; }; #define GEN_INIT(var,R,F,A) var.a = (DATA) (2.0 * sin(M_PI * F / R)); \ - var.s0 = 0; \ - var.s1 = (DATA)(0 - (int)A) + var.s0 = 0; \ + var.s1 = (DATA)(0 - (int)A) #define GEN_SAMP(val,var) var.s0 = var.s0 - var.a * var.s1; \ - var.s1 = var.s1 + var.a * var.s0; \ - val = (short) var.s0 + var.s1 = var.s1 + var.a * var.s0; \ + val = (short) var.s0 #elif PJMEDIA_TONEGEN_ALG==PJMEDIA_TONEGEN_FIXED_POINT_CORDIC /* Cordic algorithm with 28 bit size, from: @@ -91,98 +90,98 @@ * approx. 6.01 MIPS * * ARM926EJ-S results: - * loop=7: 8,943 usec/1.77 MIPS - * loop=8: 9,872 usec/1.95 MIPS + * loop=7: 8,943 usec/1.77 MIPS + * loop=8: 9,872 usec/1.95 MIPS * loop=10: 11,662 usec/2.31 MIPS * loop=12: 13,561 usec/2.69 MIPS */ - #define CORDIC_1K 0x026DD3B6 - #define CORDIC_HALF_PI 0x06487ED5 - #define CORDIC_PI (CORDIC_HALF_PI * 2) - #define CORDIC_MUL_BITS 26 - #define CORDIC_MUL (1 << CORDIC_MUL_BITS) - #define CORDIC_NTAB 28 - #define CORDIC_LOOP PJMEDIA_TONEGEN_FIXED_POINT_CORDIC_LOOP + #define CORDIC_1K 0x026DD3B6 + #define CORDIC_HALF_PI 0x06487ED5 + #define CORDIC_PI (CORDIC_HALF_PI * 2) + #define CORDIC_MUL_BITS 26 + #define CORDIC_MUL (1 << CORDIC_MUL_BITS) + #define CORDIC_NTAB 28 + #define CORDIC_LOOP PJMEDIA_TONEGEN_FIXED_POINT_CORDIC_LOOP static int cordic_ctab [] = { - 0x03243F6A, 0x01DAC670, 0x00FADBAF, 0x007F56EA, 0x003FEAB7, - 0x001FFD55, 0x000FFFAA, 0x0007FFF5, 0x0003FFFE, 0x0001FFFF, - 0x0000FFFF, 0x00007FFF, 0x00003FFF, 0x00001FFF, 0x00000FFF, - 0x000007FF, 0x000003FF, 0x000001FF, 0x000000FF, 0x0000007F, - 0x0000003F, 0x0000001F, 0x0000000F, 0x00000007, 0x00000003, - 0x00000001, 0x00000000, 0x00000000 + 0x03243F6A, 0x01DAC670, 0x00FADBAF, 0x007F56EA, 0x003FEAB7, + 0x001FFD55, 0x000FFFAA, 0x0007FFF5, 0x0003FFFE, 0x0001FFFF, + 0x0000FFFF, 0x00007FFF, 0x00003FFF, 0x00001FFF, 0x00000FFF, + 0x000007FF, 0x000003FF, 0x000001FF, 0x000000FF, 0x0000007F, + 0x0000003F, 0x0000001F, 0x0000000F, 0x00000007, 0x00000003, + 0x00000001, 0x00000000, 0x00000000 }; static pj_int32_t cordic(pj_int32_t theta, unsigned n) { - unsigned k; - int d; - pj_int32_t tx; - pj_int32_t x = CORDIC_1K, y = 0, z = theta; - - for (k=0; k=0) ? 0 : -1; - #else - /* Only slightly (~2.5%) faster, but not portable? */ - d = z>>27; - #endif - tx = x - (((y>>k) ^ d) - d); - y = y + (((x>>k) ^ d) - d); - z = z - ((cordic_ctab[k] ^ d) - d); - x = tx; - } - return y; + unsigned k; + int d; + pj_int32_t tx; + pj_int32_t x = CORDIC_1K, y = 0, z = theta; + + for (k=0; k=0) ? 0 : -1; + #else + /* Only slightly (~2.5%) faster, but not portable? */ + d = z>>27; + #endif + tx = x - (((y>>k) ^ d) - d); + y = y + (((x>>k) ^ d) - d); + z = z - ((cordic_ctab[k] ^ d) - d); + x = tx; + } + return y; } /* Note: theta must be uint32 here */ static pj_int32_t cordic_sin(pj_uint32_t theta, unsigned n) { - if (theta < CORDIC_HALF_PI) - return cordic(theta, n); - else if (theta < CORDIC_PI) - return cordic(CORDIC_HALF_PI-(theta-CORDIC_HALF_PI), n); - else if (theta < CORDIC_PI + CORDIC_HALF_PI) - return -cordic(theta - CORDIC_PI, n); - else if (theta < 2 * CORDIC_PI) - return -cordic(CORDIC_HALF_PI-(theta-3*CORDIC_HALF_PI), n); - else { - pj_assert(!"Invalid cordic_sin() value"); - return 0; - } + if (theta < CORDIC_HALF_PI) + return cordic(theta, n); + else if (theta < CORDIC_PI) + return cordic(CORDIC_HALF_PI-(theta-CORDIC_HALF_PI), n); + else if (theta < CORDIC_PI + CORDIC_HALF_PI) + return -cordic(theta - CORDIC_PI, n); + else if (theta < 2 * CORDIC_PI) + return -cordic(CORDIC_HALF_PI-(theta-3*CORDIC_HALF_PI), n); + else { + pj_assert(!"Invalid cordic_sin() value"); + return 0; + } } struct gen { - unsigned add; - pj_uint32_t c; - unsigned vol; + unsigned add; + pj_uint32_t c; + unsigned vol; }; - #define VOL(var,v) (((v) * var.vol) >> 15) - #define GEN_INIT(var,R,F,A) gen_init(&var, R, F, A) - #define GEN_SAMP(val,var) val = gen_samp(&var) + #define VOL(var,v) (((v) * var.vol) >> 15) + #define GEN_INIT(var,R,F,A) gen_init(&var, R, F, A) + #define GEN_SAMP(val,var) val = gen_samp(&var) static void gen_init(struct gen *var, unsigned R, unsigned F, unsigned A) { - var->add = 2*CORDIC_PI/R * F; - var->c = 0; - var->vol = A; + var->add = 2*CORDIC_PI/R * F; + var->c = 0; + var->vol = A; } PJ_INLINE(short) gen_samp(struct gen *var) { - pj_int32_t val; - val = cordic_sin(var->c, CORDIC_LOOP); - /*val = (val * 32767) / CORDIC_MUL; - *val = VOL((*var), val); - */ - val = ((val >> 10) * var->vol) >> 16; - var->c += var->add; - if (var->c > 2*CORDIC_PI) - var->c -= (2 * CORDIC_PI); - return (short) val; + pj_int32_t val; + val = cordic_sin(var->c, CORDIC_LOOP); + /*val = (val * 32767) / CORDIC_MUL; + *val = VOL((*var), val); + */ + val = ((val >> 10) * var->vol) >> 16; + var->c += var->add; + if (var->c > 2*CORDIC_PI) + var->c -= (2 * CORDIC_PI); + return (short) val; } #elif PJMEDIA_TONEGEN_ALG==PJMEDIA_TONEGEN_FAST_FIXED_POINT @@ -199,27 +198,27 @@ * 1,449 usec/0.29 MIPS on ARM926EJ-S. */ PJ_INLINE(int) approximate_sin3(unsigned x) - { - unsigned s=-(int)(x>>31); - x+=x; - x=x>>16; - x*=x^0xffff; // x=x*(2-x) - x+=x; // optional - return x^s; + { + unsigned s=-(int)(x>>31); + x+=x; + x=x>>16; + x*=x^0xffff; // x=x*(2-x) + x+=x; // optional + return x^s; } struct gen { - unsigned add; - unsigned c; - unsigned vol; + unsigned add; + unsigned c; + unsigned vol; }; - #define MAXI ((unsigned)0xFFFFFFFF) - #define SIN approximate_sin3 - #define VOL(var,v) (((v) * var.vol) >> 15) - #define GEN_INIT(var,R,F,A) var.add = MAXI/R * F, var.c=0, var.vol=A - #define GEN_SAMP(val,var) val = (short) VOL(var,SIN(var.c)>>16); \ - var.c += var.add + #define MAXI ((unsigned)0xFFFFFFFF) + #define SIN approximate_sin3 + #define VOL(var,v) (((v) * var.vol) >> 15) + #define GEN_INIT(var,R,F,A) var.add = MAXI/R * F, var.c=0, var.vol=A + #define GEN_SAMP(val,var) val = (short) VOL(var,SIN(var.c)>>16); \ + var.c += var.add #else #error "PJMEDIA_TONEGEN_ALG is not set correctly" @@ -234,43 +233,43 @@ struct gen_state static void init_generate_single_tone(struct gen_state *state, - unsigned clock_rate, - unsigned freq, - unsigned vol) + unsigned clock_rate, + unsigned freq, + unsigned vol) { GEN_INIT(state->tone1,clock_rate,freq,vol); state->has_tone2 = PJ_FALSE; } static void generate_single_tone(struct gen_state *state, - unsigned channel_count, - unsigned samples, - short buf[]) + unsigned channel_count, + unsigned samples, + short buf[]) { short *end = buf + samples; if (channel_count==1) { - while (buf < end) { - GEN_SAMP(*buf++, state->tone1); - } + while (buf < end) { + GEN_SAMP(*buf++, state->tone1); + } } else if (channel_count == 2) { - while (buf < end) { - GEN_SAMP(*buf, state->tone1); - *(buf+1) = *buf; - buf += 2; - } + while (buf < end) { + GEN_SAMP(*buf, state->tone1); + *(buf+1) = *buf; + buf += 2; + } } } static void init_generate_dual_tone(struct gen_state *state, - unsigned clock_rate, - unsigned freq1, - unsigned freq2, - unsigned vol) + unsigned clock_rate, + unsigned freq1, + unsigned freq2, + unsigned vol) { GEN_INIT(state->tone1,clock_rate,freq1,vol); GEN_INIT(state->tone2,clock_rate,freq2,vol); @@ -279,56 +278,56 @@ static void init_generate_dual_tone(struct gen_state *state, static void generate_dual_tone(struct gen_state *state, - unsigned channel_count, - unsigned samples, - short buf[]) + unsigned channel_count, + unsigned samples, + short buf[]) { short *end = buf + samples; if (channel_count==1) { - int val, val2; - while (buf < end) { - GEN_SAMP(val, state->tone1); - GEN_SAMP(val2, state->tone2); - *buf++ = (short)((val+val2) >> 1); - } + int val, val2; + while (buf < end) { + GEN_SAMP(val, state->tone1); + GEN_SAMP(val2, state->tone2); + *buf++ = (short)((val+val2) >> 1); + } } else if (channel_count == 2) { - int val, val2; - while (buf < end) { + int val, val2; + while (buf < end) { - GEN_SAMP(val, state->tone1); - GEN_SAMP(val2, state->tone2); - val = (val + val2) >> 1; + GEN_SAMP(val, state->tone1); + GEN_SAMP(val2, state->tone2); + val = (val + val2) >> 1; - *buf++ = (short)val; - *buf++ = (short)val; - } + *buf++ = (short)val; + *buf++ = (short)val; + } } } static void init_generate_tone(struct gen_state *state, - unsigned clock_rate, - unsigned freq1, - unsigned freq2, - unsigned vol) + unsigned clock_rate, + unsigned freq1, + unsigned freq2, + unsigned vol) { if (freq2) - init_generate_dual_tone(state, clock_rate, freq1, freq2 ,vol); + init_generate_dual_tone(state, clock_rate, freq1, freq2 ,vol); else - init_generate_single_tone(state, clock_rate, freq1,vol); + init_generate_single_tone(state, clock_rate, freq1,vol); } static void generate_tone(struct gen_state *state, - unsigned channel_count, - unsigned samples, - short buf[]) + unsigned channel_count, + unsigned samples, + short buf[]) { if (!state->has_tone2) - generate_single_tone(state, channel_count, samples, buf); + generate_single_tone(state, channel_count, samples, buf); else - generate_dual_tone(state, channel_count, samples, buf); + generate_dual_tone(state, channel_count, samples, buf); } @@ -338,41 +337,41 @@ static void generate_tone(struct gen_state *state, #define THIS_FILE "tonegen.c" #if 0 -# define TRACE_(expr) PJ_LOG(4,expr) +# define TRACE_(expr) PJ_LOG(4,expr) #else # define TRACE_(expr) #endif enum flags { - PJMEDIA_TONE_INITIALIZED = 1, - PJMEDIA_TONE_ENABLE_FADE = 2 + PJMEDIA_TONE_INITIALIZED = 1, + PJMEDIA_TONE_ENABLE_FADE = 2 }; struct tonegen { - pjmedia_port base; + pjmedia_port base; /* options */ - unsigned options; - unsigned playback_options; - unsigned fade_in_len; /* fade in for this # of samples */ - unsigned fade_out_len; /* fade out for this # of samples*/ + unsigned options; + unsigned playback_options; + unsigned fade_in_len; /* fade in for this # of samples */ + unsigned fade_out_len; /* fade out for this # of samples*/ /* lock */ - pj_lock_t *lock; + pj_lock_t *lock; /* Digit map */ pjmedia_tone_digit_map *digit_map; /* Tone generation state */ - struct gen_state state; + struct gen_state state; /* Currently played digits: */ - unsigned count; /* # of digits */ - unsigned cur_digit; /* currently played */ - unsigned dig_samples; /* sample pos in cur digit */ - pjmedia_tone_desc digits[PJMEDIA_TONEGEN_MAX_DIGITS];/* array of digits*/ + unsigned count; /* # of digits */ + unsigned cur_digit; /* currently played */ + unsigned dig_samples; /* sample pos in cur digit */ + pjmedia_tone_desc digits[PJMEDIA_TONEGEN_MAX_DIGITS];/* array of digits*/ }; @@ -381,28 +380,28 @@ static pjmedia_tone_digit_map digit_map = { 16, { - { '0', 941, 1336 }, - { '1', 697, 1209 }, - { '2', 697, 1336 }, - { '3', 697, 1477 }, - { '4', 770, 1209 }, - { '5', 770, 1336 }, - { '6', 770, 1477 }, - { '7', 852, 1209 }, - { '8', 852, 1336 }, - { '9', 852, 1477 }, - { 'a', 697, 1633 }, - { 'b', 770, 1633 }, - { 'c', 852, 1633 }, - { 'd', 941, 1633 }, - { '*', 941, 1209 }, - { '#', 941, 1477 }, + { '0', 941, 1336 }, + { '1', 697, 1209 }, + { '2', 697, 1336 }, + { '3', 697, 1477 }, + { '4', 770, 1209 }, + { '5', 770, 1336 }, + { '6', 770, 1477 }, + { '7', 852, 1209 }, + { '8', 852, 1336 }, + { '9', 852, 1477 }, + { 'a', 697, 1633 }, + { 'b', 770, 1633 }, + { 'c', 852, 1633 }, + { 'd', 941, 1633 }, + { '*', 941, 1209 }, + { '#', 941, 1477 }, } }; static pj_status_t tonegen_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t tonegen_destroy(pjmedia_port *this_port); /* @@ -411,21 +410,21 @@ static pj_status_t tonegen_destroy(pjmedia_port *this_port); * default digit map. */ PJ_DEF(pj_status_t) pjmedia_tonegen_create2(pj_pool_t *pool, - const pj_str_t *name, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_port **p_port) + const pj_str_t *name, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_port **p_port) { const pj_str_t STR_TONE_GEN = pj_str("tonegen"); struct tonegen *tonegen; pj_status_t status; PJ_ASSERT_RETURN(pool && clock_rate && channel_count && - samples_per_frame && bits_per_sample == 16 && - p_port != NULL, PJ_EINVAL); + samples_per_frame && bits_per_sample == 16 && + p_port != NULL, PJ_EINVAL); /* Only support mono and stereo */ PJ_ASSERT_RETURN(channel_count==1 || channel_count==2, PJ_EINVAL); @@ -434,10 +433,10 @@ PJ_DEF(pj_status_t) pjmedia_tonegen_create2(pj_pool_t *pool, tonegen = PJ_POOL_ZALLOC_T(pool, struct tonegen); if (name == NULL || name->slen == 0) name = &STR_TONE_GEN; status = pjmedia_port_info_init(&tonegen->base.info, name, - SIGNATURE, clock_rate, channel_count, - bits_per_sample, samples_per_frame); + SIGNATURE, clock_rate, channel_count, + bits_per_sample, samples_per_frame); if (status != PJ_SUCCESS) - return status; + return status; tonegen->options = options; tonegen->base.get_frame = &tonegen_get_frame; @@ -449,17 +448,17 @@ PJ_DEF(pj_status_t) pjmedia_tonegen_create2(pj_pool_t *pool, /* Lock */ if (options & PJMEDIA_TONEGEN_NO_LOCK) { - status = pj_lock_create_null_mutex(pool, "tonegen", &tonegen->lock); + status = pj_lock_create_null_mutex(pool, "tonegen", &tonegen->lock); } else { - status = pj_lock_create_simple_mutex(pool, "tonegen", &tonegen->lock); + status = pj_lock_create_simple_mutex(pool, "tonegen", &tonegen->lock); } if (status != PJ_SUCCESS) { - return status; + return status; } TRACE_((THIS_FILE, "Tonegen created: %u/%u/%u/%u", clock_rate, - channel_count, samples_per_frame, bits_per_sample)); + channel_count, samples_per_frame, bits_per_sample)); /* Done */ *p_port = &tonegen->base; @@ -468,16 +467,16 @@ PJ_DEF(pj_status_t) pjmedia_tonegen_create2(pj_pool_t *pool, PJ_DEF(pj_status_t) pjmedia_tonegen_create( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned options, - pjmedia_port **p_port) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned options, + pjmedia_port **p_port) { return pjmedia_tonegen_create2(pool, NULL, clock_rate, channel_count, - samples_per_frame, bits_per_sample, - options, p_port); + samples_per_frame, bits_per_sample, + options, p_port); } @@ -570,7 +569,7 @@ static pj_status_t tonegen_destroy(pjmedia_port *port) * Fill a frame with tones. */ static pj_status_t tonegen_get_frame(pjmedia_port *port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct tonegen *tonegen = (struct tonegen*) port; short *dst, *end; @@ -581,195 +580,195 @@ static pj_status_t tonegen_get_frame(pjmedia_port *port, pj_lock_acquire(tonegen->lock); if (tonegen->count == 0) { - /* We don't have digits to play */ - frame->type = PJMEDIA_FRAME_TYPE_NONE; - goto on_return; + /* We don't have digits to play */ + frame->type = PJMEDIA_FRAME_TYPE_NONE; + goto on_return; } if (tonegen->cur_digit > tonegen->count) { - /* We have played all the digits */ - if ((tonegen->options|tonegen->playback_options)&PJMEDIA_TONEGEN_LOOP) - { - /* Reset back to the first tone */ - tonegen->cur_digit = 0; - tonegen->dig_samples = 0; - - TRACE_((THIS_FILE, "tonegen_get_frame(): rewind")); - - } else { - tonegen->count = 0; - tonegen->cur_digit = 0; - frame->type = PJMEDIA_FRAME_TYPE_NONE; - TRACE_((THIS_FILE, "tonegen_get_frame(): no more digit")); - goto on_return; - } + /* We have played all the digits */ + if ((tonegen->options|tonegen->playback_options)&PJMEDIA_TONEGEN_LOOP) + { + /* Reset back to the first tone */ + tonegen->cur_digit = 0; + tonegen->dig_samples = 0; + + TRACE_((THIS_FILE, "tonegen_get_frame(): rewind")); + + } else { + tonegen->count = 0; + tonegen->cur_digit = 0; + frame->type = PJMEDIA_FRAME_TYPE_NONE; + TRACE_((THIS_FILE, "tonegen_get_frame(): no more digit")); + goto on_return; + } } if (tonegen->dig_samples>=(tonegen->digits[tonegen->cur_digit].on_msec+ - tonegen->digits[tonegen->cur_digit].off_msec)* - clock_rate / 1000 * - PJMEDIA_PIA_CCNT(&port->info)) + tonegen->digits[tonegen->cur_digit].off_msec)* + clock_rate / 1000 * + PJMEDIA_PIA_CCNT(&port->info)) { - /* We have finished with current digit */ - tonegen->cur_digit++; - tonegen->dig_samples = 0; + /* We have finished with current digit */ + tonegen->cur_digit++; + tonegen->dig_samples = 0; - TRACE_((THIS_FILE, "tonegen_get_frame(): next digit")); + TRACE_((THIS_FILE, "tonegen_get_frame(): next digit")); } if (tonegen->cur_digit >= tonegen->count) { - /* After we're finished with the last digit, we have played all - * the digits - */ - if ((tonegen->options|tonegen->playback_options)&PJMEDIA_TONEGEN_LOOP) - { - /* Reset back to the first tone */ - tonegen->cur_digit = 0; - tonegen->dig_samples = 0; - - TRACE_((THIS_FILE, "tonegen_get_frame(): rewind")); - - } else { - tonegen->count = 0; - tonegen->cur_digit = 0; - frame->type = PJMEDIA_FRAME_TYPE_NONE; - TRACE_((THIS_FILE, "tonegen_get_frame(): no more digit")); - goto on_return; - } + /* After we're finished with the last digit, we have played all + * the digits + */ + if ((tonegen->options|tonegen->playback_options)&PJMEDIA_TONEGEN_LOOP) + { + /* Reset back to the first tone */ + tonegen->cur_digit = 0; + tonegen->dig_samples = 0; + + TRACE_((THIS_FILE, "tonegen_get_frame(): rewind")); + + } else { + tonegen->count = 0; + tonegen->cur_digit = 0; + frame->type = PJMEDIA_FRAME_TYPE_NONE; + TRACE_((THIS_FILE, "tonegen_get_frame(): no more digit")); + goto on_return; + } } dst = (short*) frame->buf; end = dst + PJMEDIA_PIA_SPF(&port->info); while (dst < end) { - pjmedia_tone_desc *dig = &tonegen->digits[tonegen->cur_digit]; - unsigned required, cnt, on_samp, off_samp; - - required = (unsigned)(end - dst); - on_samp = dig->on_msec * clock_rate / 1000 * - PJMEDIA_PIA_CCNT(&port->info); - off_samp = dig->off_msec * clock_rate / 1000 * - PJMEDIA_PIA_CCNT(&port->info); - - /* Init tonegen */ - if (tonegen->dig_samples == 0 && - (tonegen->count!=1 || !(dig->flags & PJMEDIA_TONE_INITIALIZED))) - { - init_generate_tone(&tonegen->state, - PJMEDIA_PIA_SRATE(&port->info), - dig->freq1, dig->freq2, dig->volume); - dig->flags |= PJMEDIA_TONE_INITIALIZED; - if (tonegen->cur_digit > 0) { - /* Clear initialized flag of previous digit */ - tonegen->digits[tonegen->cur_digit-1].flags &= - (~PJMEDIA_TONE_INITIALIZED); - } - } - - /* Add tone signal */ - if (tonegen->dig_samples < on_samp) { - cnt = on_samp - tonegen->dig_samples; - if (cnt > required) - cnt = required; - generate_tone(&tonegen->state, - PJMEDIA_PIA_CCNT(&port->info), - cnt, dst); - - dst += cnt; - tonegen->dig_samples += cnt; - required -= cnt; - - if ((dig->flags & PJMEDIA_TONE_ENABLE_FADE) && - tonegen->dig_samples == cnt) - { - /* Fade in */ - short *samp = (dst - cnt); - short *samp_end; - - if (cnt > tonegen->fade_in_len) - cnt = tonegen->fade_in_len; - samp_end = samp + cnt; - if (cnt) { - const unsigned step = 0xFFFF / cnt; - unsigned scale = 0; - - for (; samp < samp_end; ++samp) { - (*samp) = (short)(((*samp) * scale) >> 16); - scale += step; - } - } - } else if ((dig->flags & PJMEDIA_TONE_ENABLE_FADE) && - tonegen->dig_samples==on_samp) - { - /* Fade out */ - if (cnt > tonegen->fade_out_len) - cnt = tonegen->fade_out_len; - if (cnt) { - short *samp = (dst - cnt); - const unsigned step = 0xFFFF / cnt; - unsigned scale = 0xFFFF - step; - - for (; samp < dst; ++samp) { - (*samp) = (short)(((*samp) * scale) >> 16); - scale -= step; - } - } - } - - if (dst == end) - break; - } - - /* Add silence signal */ - cnt = off_samp + on_samp - tonegen->dig_samples; - if (cnt > required) - cnt = required; - pjmedia_zero_samples(dst, cnt); - dst += cnt; - tonegen->dig_samples += cnt; - - /* Move to next digit if we're finished with this tone */ - if (tonegen->dig_samples >= on_samp + off_samp) { - tonegen->cur_digit++; - tonegen->dig_samples = 0; - - if (tonegen->cur_digit >= tonegen->count) { - /* All digits have been played */ - if ((tonegen->options & PJMEDIA_TONEGEN_LOOP) || - (tonegen->playback_options & PJMEDIA_TONEGEN_LOOP)) - { - tonegen->cur_digit = 0; - } else { - break; - } - } - } + pjmedia_tone_desc *dig = &tonegen->digits[tonegen->cur_digit]; + unsigned required, cnt, on_samp, off_samp; + + required = (unsigned)(end - dst); + on_samp = dig->on_msec * clock_rate / 1000 * + PJMEDIA_PIA_CCNT(&port->info); + off_samp = dig->off_msec * clock_rate / 1000 * + PJMEDIA_PIA_CCNT(&port->info); + + /* Init tonegen */ + if (tonegen->dig_samples == 0 && + (tonegen->count!=1 || !(dig->flags & PJMEDIA_TONE_INITIALIZED))) + { + init_generate_tone(&tonegen->state, + PJMEDIA_PIA_SRATE(&port->info), + dig->freq1, dig->freq2, dig->volume); + dig->flags |= PJMEDIA_TONE_INITIALIZED; + if (tonegen->cur_digit > 0) { + /* Clear initialized flag of previous digit */ + tonegen->digits[tonegen->cur_digit-1].flags &= + (~PJMEDIA_TONE_INITIALIZED); + } + } + + /* Add tone signal */ + if (tonegen->dig_samples < on_samp) { + cnt = on_samp - tonegen->dig_samples; + if (cnt > required) + cnt = required; + generate_tone(&tonegen->state, + PJMEDIA_PIA_CCNT(&port->info), + cnt, dst); + + dst += cnt; + tonegen->dig_samples += cnt; + required -= cnt; + + if ((dig->flags & PJMEDIA_TONE_ENABLE_FADE) && + tonegen->dig_samples == cnt) + { + /* Fade in */ + short *samp = (dst - cnt); + short *samp_end; + + if (cnt > tonegen->fade_in_len) + cnt = tonegen->fade_in_len; + samp_end = samp + cnt; + if (cnt) { + const unsigned step = 0xFFFF / cnt; + unsigned scale = 0; + + for (; samp < samp_end; ++samp) { + (*samp) = (short)(((*samp) * scale) >> 16); + scale += step; + } + } + } else if ((dig->flags & PJMEDIA_TONE_ENABLE_FADE) && + tonegen->dig_samples==on_samp) + { + /* Fade out */ + if (cnt > tonegen->fade_out_len) + cnt = tonegen->fade_out_len; + if (cnt) { + short *samp = (dst - cnt); + const unsigned step = 0xFFFF / cnt; + unsigned scale = 0xFFFF - step; + + for (; samp < dst; ++samp) { + (*samp) = (short)(((*samp) * scale) >> 16); + scale -= step; + } + } + } + + if (dst == end) + break; + } + + /* Add silence signal */ + cnt = off_samp + on_samp - tonegen->dig_samples; + if (cnt > required) + cnt = required; + pjmedia_zero_samples(dst, cnt); + dst += cnt; + tonegen->dig_samples += cnt; + + /* Move to next digit if we're finished with this tone */ + if (tonegen->dig_samples >= on_samp + off_samp) { + tonegen->cur_digit++; + tonegen->dig_samples = 0; + + if (tonegen->cur_digit >= tonegen->count) { + /* All digits have been played */ + if ((tonegen->options & PJMEDIA_TONEGEN_LOOP) || + (tonegen->playback_options & PJMEDIA_TONEGEN_LOOP)) + { + tonegen->cur_digit = 0; + } else { + break; + } + } + } } if (dst < end) - pjmedia_zero_samples(dst, (unsigned)(end-dst)); + pjmedia_zero_samples(dst, (unsigned)(end-dst)); frame->type = PJMEDIA_FRAME_TYPE_AUDIO; frame->size = PJMEDIA_PIA_AVG_FSZ(&port->info); TRACE_((THIS_FILE, "tonegen_get_frame(): frame created, level=%u", - pjmedia_calc_avg_signal((pj_int16_t*)frame->buf, frame->size/2))); + pjmedia_calc_avg_signal((pj_int16_t*)frame->buf, frame->size/2))); if (tonegen->cur_digit >= tonegen->count) { - if ((tonegen->options|tonegen->playback_options)&PJMEDIA_TONEGEN_LOOP) - { - /* Reset back to the first tone */ - tonegen->cur_digit = 0; - tonegen->dig_samples = 0; + if ((tonegen->options|tonegen->playback_options)&PJMEDIA_TONEGEN_LOOP) + { + /* Reset back to the first tone */ + tonegen->cur_digit = 0; + tonegen->dig_samples = 0; - TRACE_((THIS_FILE, "tonegen_get_frame(): rewind")); + TRACE_((THIS_FILE, "tonegen_get_frame(): rewind")); - } else { - tonegen->count = 0; - tonegen->cur_digit = 0; + } else { + tonegen->count = 0; + tonegen->cur_digit = 0; - TRACE_((THIS_FILE, "tonegen_get_frame(): no more digit")); - } + TRACE_((THIS_FILE, "tonegen_get_frame(): no more digit")); + } } on_return: @@ -782,19 +781,19 @@ static pj_status_t tonegen_get_frame(pjmedia_port *port, * Play tones. */ PJ_DEF(pj_status_t) pjmedia_tonegen_play( pjmedia_port *port, - unsigned count, - const pjmedia_tone_desc tones[], - unsigned options) + unsigned count, + const pjmedia_tone_desc tones[], + unsigned options) { struct tonegen *tonegen = (struct tonegen*) port; unsigned i; PJ_ASSERT_RETURN(port && port->info.signature == SIGNATURE && - count && tones, PJ_EINVAL); + count && tones, PJ_EINVAL); /* Don't put more than available buffer */ PJ_ASSERT_RETURN(count+tonegen->count <= PJMEDIA_TONEGEN_MAX_DIGITS, - PJ_ETOOMANY); + PJ_ETOOMANY); pj_lock_acquire(tonegen->lock); @@ -803,22 +802,22 @@ PJ_DEF(pj_status_t) pjmedia_tonegen_play( pjmedia_port *port, /* Copy digits */ pj_memcpy(tonegen->digits + tonegen->count, - tones, count * sizeof(pjmedia_tone_desc)); + tones, count * sizeof(pjmedia_tone_desc)); /* Normalize volume, and check if we need to disable fading. * Disable fading if tone off time is zero. Application probably * wants to play this tone continuously (e.g. dial tone). */ for (i=0; idigits[i+tonegen->count]; - if (t->volume == 0) - t->volume = AMP; - else if (t->volume < 0) - t->volume = (short) -t->volume; - /* Reset flags */ - t->flags = 0; - if (t->off_msec != 0) - t->flags |= PJMEDIA_TONE_ENABLE_FADE; + pjmedia_tone_desc *t = &tonegen->digits[i+tonegen->count]; + if (t->volume == 0) + t->volume = AMP; + else if (t->volume < 0) + t->volume = (short) -t->volume; + /* Reset flags */ + t->flags = 0; + if (t->off_msec != 0) + t->flags |= PJMEDIA_TONE_ENABLE_FADE; } tonegen->count += count; @@ -833,9 +832,9 @@ PJ_DEF(pj_status_t) pjmedia_tonegen_play( pjmedia_port *port, * Play digits. */ PJ_DEF(pj_status_t) pjmedia_tonegen_play_digits( pjmedia_port *port, - unsigned count, - const pjmedia_tone_digit digits[], - unsigned options) + unsigned count, + const pjmedia_tone_digit digits[], + unsigned options) { struct tonegen *tonegen = (struct tonegen*) port; pjmedia_tone_desc tones[PJMEDIA_TONEGEN_MAX_DIGITS]; @@ -843,7 +842,7 @@ PJ_DEF(pj_status_t) pjmedia_tonegen_play_digits( pjmedia_port *port, unsigned i; PJ_ASSERT_RETURN(port && port->info.signature == SIGNATURE && - count && digits, PJ_EINVAL); + count && digits, PJ_EINVAL); PJ_ASSERT_RETURN(count < PJMEDIA_TONEGEN_MAX_DIGITS, PJ_ETOOMANY); pj_lock_acquire(tonegen->lock); @@ -851,24 +850,24 @@ PJ_DEF(pj_status_t) pjmedia_tonegen_play_digits( pjmedia_port *port, map = tonegen->digit_map; for (i=0; icount; ++j) { - if (d == map->digits[j].digit) - break; - } - if (j == map->count) { - pj_lock_release(tonegen->lock); - return PJMEDIA_RTP_EINDTMF; - } - - tones[i].freq1 = map->digits[j].freq1; - tones[i].freq2 = map->digits[j].freq2; - tones[i].on_msec = digits[i].on_msec; - tones[i].off_msec = digits[i].off_msec; - tones[i].volume = digits[i].volume; + int d = pj_tolower(digits[i].digit); + unsigned j; + + /* Translate ASCII digits with digitmap */ + for (j=0; jcount; ++j) { + if (d == map->digits[j].digit) + break; + } + if (j == map->count) { + pj_lock_release(tonegen->lock); + return PJMEDIA_RTP_EINDTMF; + } + + tones[i].freq1 = map->digits[j].freq1; + tones[i].freq2 = map->digits[j].freq2; + tones[i].on_msec = digits[i].on_msec; + tones[i].off_msec = digits[i].off_msec; + tones[i].volume = digits[i].volume; } pj_lock_release(tonegen->lock); @@ -881,7 +880,7 @@ PJ_DEF(pj_status_t) pjmedia_tonegen_play_digits( pjmedia_port *port, * Get the digit-map currently used by this tone generator. */ PJ_DEF(pj_status_t) pjmedia_tonegen_get_digit_map(pjmedia_port *port, - const pjmedia_tone_digit_map **m) + const pjmedia_tone_digit_map **m) { struct tonegen *tonegen = (struct tonegen*) port; @@ -898,7 +897,7 @@ PJ_DEF(pj_status_t) pjmedia_tonegen_get_digit_map(pjmedia_port *port, * Set digit map to be used by the tone generator. */ PJ_DEF(pj_status_t) pjmedia_tonegen_set_digit_map(pjmedia_port *port, - pjmedia_tone_digit_map *m) + pjmedia_tone_digit_map *m) { struct tonegen *tonegen = (struct tonegen*) port; diff --git a/pjmedia/src/pjmedia/transport_adapter_sample.c b/pjmedia/src/pjmedia/transport_adapter_sample.c index c51e81d1a8..b65ecb4a7a 100644 --- a/pjmedia/src/pjmedia/transport_adapter_sample.c +++ b/pjmedia/src/pjmedia/transport_adapter_sample.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,41 +24,41 @@ /* Transport functions prototypes */ static pj_status_t transport_get_info (pjmedia_transport *tp, - pjmedia_transport_info *info); + pjmedia_transport_info *info); static pj_status_t transport_attach2 (pjmedia_transport *tp, pjmedia_transport_attach_param *att_prm); -static void transport_detach (pjmedia_transport *tp, - void *strm); +static void transport_detach (pjmedia_transport *tp, + void *strm); static pj_status_t transport_send_rtp( pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); static pj_status_t transport_send_rtcp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, - const pj_sockaddr_t *addr, - unsigned addr_len, - const void *pkt, - pj_size_t size); + const pj_sockaddr_t *addr, + unsigned addr_len, + const void *pkt, + pj_size_t size); static pj_status_t transport_media_create(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - unsigned options, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index); + pj_pool_t *sdp_pool, + unsigned options, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index); static pj_status_t transport_encode_sdp(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *local_sdp, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index); + pj_pool_t *sdp_pool, + pjmedia_sdp_session *local_sdp, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index); static pj_status_t transport_media_start (pjmedia_transport *tp, - pj_pool_t *pool, - const pjmedia_sdp_session *local_sdp, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index); + pj_pool_t *pool, + const pjmedia_sdp_session *local_sdp, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index); static pj_status_t transport_media_stop(pjmedia_transport *tp); static pj_status_t transport_simulate_lost(pjmedia_transport *tp, - pjmedia_dir dir, - unsigned pct_lost); + pjmedia_dir dir, + unsigned pct_lost); static pj_status_t transport_destroy (pjmedia_transport *tp); @@ -85,25 +84,25 @@ static struct pjmedia_transport_op tp_adapter_op = /* The transport adapter instance */ struct tp_adapter { - pjmedia_transport base; - pj_bool_t del_base; + pjmedia_transport base; + pj_bool_t del_base; - pj_pool_t *pool; + pj_pool_t *pool; /* Stream information. */ - void *stream_user_data; + void *stream_user_data; void *stream_ref; - void (*stream_rtp_cb)(void *user_data, - void *pkt, - pj_ssize_t); - void (*stream_rtp_cb2)(pjmedia_tp_cb_param *param); - void (*stream_rtcp_cb)(void *user_data, - void *pkt, - pj_ssize_t); + void (*stream_rtp_cb)(void *user_data, + void *pkt, + pj_ssize_t); + void (*stream_rtp_cb2)(pjmedia_tp_cb_param *param); + void (*stream_rtcp_cb)(void *user_data, + void *pkt, + pj_ssize_t); /* Add your own member here.. */ - pjmedia_transport *slave_tp; + pjmedia_transport *slave_tp; }; @@ -111,25 +110,25 @@ struct tp_adapter * Create the adapter. */ PJ_DEF(pj_status_t) pjmedia_tp_adapter_create( pjmedia_endpt *endpt, - const char *name, - pjmedia_transport *transport, - pj_bool_t del_base, - pjmedia_transport **p_tp) + const char *name, + pjmedia_transport *transport, + pj_bool_t del_base, + pjmedia_transport **p_tp) { pj_pool_t *pool; struct tp_adapter *adapter; if (name == NULL) - name = "tpad%p"; + name = "tpad%p"; /* Create the pool and initialize the adapter structure */ pool = pjmedia_endpt_create_pool(endpt, name, 512, 512); adapter = PJ_POOL_ZALLOC_T(pool, struct tp_adapter); adapter->pool = pool; pj_ansi_strncpy(adapter->base.name, pool->obj_name, - sizeof(adapter->base.name)); + sizeof(adapter->base.name)); adapter->base.type = (pjmedia_transport_type) - (PJMEDIA_TRANSPORT_TYPE_USER + 1); + (PJMEDIA_TRANSPORT_TYPE_USER + 1); adapter->base.op = &tp_adapter_op; /* Save the transport as the slave transport */ @@ -147,7 +146,7 @@ PJ_DEF(pj_status_t) pjmedia_tp_adapter_create( pjmedia_endpt *endpt, * in SDP c= line and a=rtcp line. */ static pj_status_t transport_get_info(pjmedia_transport *tp, - pjmedia_transport_info *info) + pjmedia_transport_info *info) { struct tp_adapter *adapter = (struct tp_adapter*)tp; @@ -166,18 +165,18 @@ static void transport_rtp_cb2(pjmedia_tp_cb_param *param) struct tp_adapter *adapter = (struct tp_adapter*)param->user_data; pj_assert(adapter->stream_rtp_cb != NULL || - adapter->stream_rtp_cb2 != NULL); + adapter->stream_rtp_cb2 != NULL); /* Call stream's callback */ if (adapter->stream_rtp_cb2) { - pjmedia_tp_cb_param cbparam; - - pj_memcpy(&cbparam, param, sizeof(cbparam)); - cbparam.user_data = adapter->stream_user_data; - adapter->stream_rtp_cb2(&cbparam); + pjmedia_tp_cb_param cbparam; + + pj_memcpy(&cbparam, param, sizeof(cbparam)); + cbparam.user_data = adapter->stream_user_data; + adapter->stream_rtp_cb2(&cbparam); } else { - adapter->stream_rtp_cb(adapter->stream_user_data, param->pkt, - param->size); + adapter->stream_rtp_cb(adapter->stream_user_data, param->pkt, + param->size); } } @@ -225,12 +224,12 @@ static pj_status_t transport_attach2(pjmedia_transport *tp, status = pjmedia_transport_attach2(adapter->slave_tp, att_param); if (status != PJ_SUCCESS) { - adapter->stream_user_data = NULL; - adapter->stream_rtp_cb = NULL; - adapter->stream_rtp_cb2 = NULL; - adapter->stream_rtcp_cb = NULL; + adapter->stream_user_data = NULL; + adapter->stream_rtp_cb = NULL; + adapter->stream_rtp_cb2 = NULL; + adapter->stream_rtcp_cb = NULL; adapter->stream_ref = NULL; - return status; + return status; } return PJ_SUCCESS; @@ -247,11 +246,11 @@ static void transport_detach(pjmedia_transport *tp, void *strm) PJ_UNUSED_ARG(strm); if (adapter->stream_user_data != NULL) { - pjmedia_transport_detach(adapter->slave_tp, adapter); - adapter->stream_user_data = NULL; - adapter->stream_rtp_cb = NULL; - adapter->stream_rtp_cb2 = NULL; - adapter->stream_rtcp_cb = NULL; + pjmedia_transport_detach(adapter->slave_tp, adapter); + adapter->stream_user_data = NULL; + adapter->stream_rtp_cb = NULL; + adapter->stream_rtp_cb2 = NULL; + adapter->stream_rtcp_cb = NULL; adapter->stream_ref = NULL; } } @@ -262,8 +261,8 @@ static void transport_detach(pjmedia_transport *tp, void *strm) * contain both the RTP header and the payload. */ static pj_status_t transport_send_rtp( pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { struct tp_adapter *adapter = (struct tp_adapter*)tp; @@ -279,8 +278,8 @@ static pj_status_t transport_send_rtp( pjmedia_transport *tp, * contain the RTCP packet. */ static pj_status_t transport_send_rtcp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { struct tp_adapter *adapter = (struct tp_adapter*)tp; @@ -296,14 +295,14 @@ static pj_status_t transport_send_rtcp(pjmedia_transport *tp, * address in the argument. */ static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, - const pj_sockaddr_t *addr, - unsigned addr_len, - const void *pkt, - pj_size_t size) + const pj_sockaddr_t *addr, + unsigned addr_len, + const void *pkt, + pj_size_t size) { struct tp_adapter *adapter = (struct tp_adapter*)tp; return pjmedia_transport_send_rtcp2(adapter->slave_tp, addr, addr_len, - pkt, size); + pkt, size); } /* @@ -311,10 +310,10 @@ static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, * a new call. */ static pj_status_t transport_media_create(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - unsigned options, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *sdp_pool, + unsigned options, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { struct tp_adapter *adapter = (struct tp_adapter*)tp; @@ -324,14 +323,14 @@ static pj_status_t transport_media_create(pjmedia_transport *tp, * returning non-PJ_SUCCESS. */ if (rem_sdp) { - /* Do your stuff.. */ + /* Do your stuff.. */ } /* Once we're done with our initialization, pass the call to the * slave transports to let it do it's own initialization too. */ return pjmedia_transport_media_create(adapter->slave_tp, sdp_pool, options, - rem_sdp, media_index); + rem_sdp, media_index); } /* @@ -339,10 +338,10 @@ static pj_status_t transport_media_create(pjmedia_transport *tp, * either as SDP offer or as SDP answer. */ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *local_sdp, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *sdp_pool, + pjmedia_sdp_session *local_sdp, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { struct tp_adapter *adapter = (struct tp_adapter*)tp; @@ -351,23 +350,23 @@ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, * everything is okay before we send SDP. */ if (rem_sdp) { - /* Do checking stuffs here.. */ + /* Do checking stuffs here.. */ } /* You may do anything to the local_sdp, e.g. adding new attributes, or * even modifying the SDP if you want. */ if (1) { - /* Say we add a proprietary attribute here.. */ - pjmedia_sdp_attr *my_attr; + /* Say we add a proprietary attribute here.. */ + pjmedia_sdp_attr *my_attr; - my_attr = PJ_POOL_ALLOC_T(sdp_pool, pjmedia_sdp_attr); - pj_strdup2(sdp_pool, &my_attr->name, "X-adapter"); - pj_strdup2(sdp_pool, &my_attr->value, "some value"); + my_attr = PJ_POOL_ALLOC_T(sdp_pool, pjmedia_sdp_attr); + pj_strdup2(sdp_pool, &my_attr->name, "X-adapter"); + pj_strdup2(sdp_pool, &my_attr->value, "some value"); - pjmedia_sdp_attr_add(&local_sdp->media[media_index]->attr_count, - local_sdp->media[media_index]->attr, - my_attr); + pjmedia_sdp_attr_add(&local_sdp->media[media_index]->attr_count, + local_sdp->media[media_index]->attr, + my_attr); } /* And then pass the call to slave transport to let it encode its @@ -375,7 +374,7 @@ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, * first before adding your custom attributes if you want. */ return pjmedia_transport_encode_sdp(adapter->slave_tp, sdp_pool, local_sdp, - rem_sdp, media_index); + rem_sdp, media_index); } /* @@ -384,10 +383,10 @@ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, * committing our processing. */ static pj_status_t transport_media_start(pjmedia_transport *tp, - pj_pool_t *pool, - const pjmedia_sdp_session *local_sdp, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *pool, + const pjmedia_sdp_session *local_sdp, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { struct tp_adapter *adapter = (struct tp_adapter*)tp; @@ -395,7 +394,7 @@ static pj_status_t transport_media_start(pjmedia_transport *tp, /* And pass the call to the slave transport */ return pjmedia_transport_media_start(adapter->slave_tp, pool, local_sdp, - rem_sdp, media_index); + rem_sdp, media_index); } /* @@ -415,8 +414,8 @@ static pj_status_t transport_media_stop(pjmedia_transport *tp) * simulate_lost() is called to simulate packet lost */ static pj_status_t transport_simulate_lost(pjmedia_transport *tp, - pjmedia_dir dir, - unsigned pct_lost) + pjmedia_dir dir, + unsigned pct_lost) { struct tp_adapter *adapter = (struct tp_adapter*)tp; return pjmedia_transport_simulate_lost(adapter->slave_tp, dir, pct_lost); @@ -431,7 +430,7 @@ static pj_status_t transport_destroy (pjmedia_transport *tp) /* Close the slave transport */ if (adapter->del_base) { - pjmedia_transport_close(adapter->slave_tp); + pjmedia_transport_close(adapter->slave_tp); } /* Self destruct.. */ diff --git a/pjmedia/src/pjmedia/transport_ice.c b/pjmedia/src/pjmedia/transport_ice.c index a695eb2e49..54d308e52a 100644 --- a/pjmedia/src/pjmedia/transport_ice.c +++ b/pjmedia/src/pjmedia/transport_ice.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -40,68 +39,68 @@ enum oa_role struct sdp_state { - unsigned match_comp_cnt; /* Matching number of components */ - pj_bool_t ice_mismatch; /* Address doesn't match candidates */ - pj_bool_t ice_restart; /* Offer to restart ICE */ - pj_ice_sess_role local_role; /* Our role */ - pj_bool_t has_trickle; /* Has trickle ICE attribute */ + unsigned match_comp_cnt; /* Matching number of components */ + pj_bool_t ice_mismatch; /* Address doesn't match candidates */ + pj_bool_t ice_restart; /* Offer to restart ICE */ + pj_ice_sess_role local_role; /* Our role */ + pj_bool_t has_trickle; /* Has trickle ICE attribute */ }; /* ICE listener */ typedef struct ice_listener { PJ_DECL_LIST_MEMBER(struct ice_listener); - pjmedia_ice_cb cb; - void *user_data; + pjmedia_ice_cb cb; + void *user_data; } ice_listener; struct transport_ice { - pjmedia_transport base; - pj_pool_t *pool; - unsigned options; /**< Transport options. */ - - unsigned comp_cnt; - pj_ice_strans *ice_st; - - pjmedia_ice_cb cb; - ice_listener listener; - ice_listener listener_empty; - unsigned media_option; - - pj_bool_t initial_sdp; - enum oa_role oa_role; /**< Last role in SDP offer/answer */ - struct sdp_state rem_offer_state;/**< Describes the remote offer */ - - void *stream; - pj_sockaddr remote_rtp; - pj_sockaddr remote_rtcp; - unsigned addr_len; /**< Length of addresses. */ - - pj_bool_t use_ice; - pj_sockaddr rtp_src_addr; /**< Actual source RTP address. */ - unsigned rtp_src_cnt; /**< How many pkt from this addr. */ - pj_sockaddr rtcp_src_addr; /**< Actual source RTCP address. */ - unsigned rtcp_src_cnt; /**< How many pkt from this addr. */ - pj_bool_t enable_rtcp_mux;/**< Enable RTP& RTCP multiplexing?*/ - pj_bool_t use_rtcp_mux; /**< Use RTP & RTCP multiplexing? */ - - unsigned tx_drop_pct; /**< Percent of tx pkts to drop. */ - unsigned rx_drop_pct; /**< Percent of rx pkts to drop. */ - - pj_ice_sess_trickle trickle_ice; /**< Trickle ICE mode. */ - unsigned last_send_cand_cnt[PJ_ICE_MAX_COMP]; - /**< Last local candidate count. */ - pj_bool_t end_of_cand; /**< Local cand gathering done? */ - pj_str_t sdp_mid; /**< SDP "a=mid" attribute. */ - - void (*rtp_cb)(void*, - void*, - pj_ssize_t); - void (*rtp_cb2)(pjmedia_tp_cb_param*); - void (*rtcp_cb)(void*, - void*, - pj_ssize_t); + pjmedia_transport base; + pj_pool_t *pool; + unsigned options; /**< Transport options. */ + + unsigned comp_cnt; + pj_ice_strans *ice_st; + + pjmedia_ice_cb cb; + ice_listener listener; + ice_listener listener_empty; + unsigned media_option; + + pj_bool_t initial_sdp; + enum oa_role oa_role; /**< Last role in SDP offer/answer */ + struct sdp_state rem_offer_state;/**< Describes the remote offer */ + + void *stream; + pj_sockaddr remote_rtp; + pj_sockaddr remote_rtcp; + unsigned addr_len; /**< Length of addresses. */ + + pj_bool_t use_ice; + pj_sockaddr rtp_src_addr; /**< Actual source RTP address. */ + unsigned rtp_src_cnt; /**< How many pkt from this addr. */ + pj_sockaddr rtcp_src_addr; /**< Actual source RTCP address. */ + unsigned rtcp_src_cnt; /**< How many pkt from this addr. */ + pj_bool_t enable_rtcp_mux;/**< Enable RTP& RTCP multiplexing?*/ + pj_bool_t use_rtcp_mux; /**< Use RTP & RTCP multiplexing? */ + + unsigned tx_drop_pct; /**< Percent of tx pkts to drop. */ + unsigned rx_drop_pct; /**< Percent of rx pkts to drop. */ + + pj_ice_sess_trickle trickle_ice; /**< Trickle ICE mode. */ + unsigned last_send_cand_cnt[PJ_ICE_MAX_COMP]; + /**< Last local candidate count. */ + pj_bool_t end_of_cand; /**< Local cand gathering done? */ + pj_str_t sdp_mid; /**< SDP "a=mid" attribute. */ + + void (*rtp_cb)(void*, + void*, + pj_ssize_t); + void (*rtp_cb2)(pjmedia_tp_cb_param*); + void (*rtcp_cb)(void*, + void*, + pj_ssize_t); }; @@ -109,69 +108,69 @@ struct transport_ice * These are media transport operations. */ static pj_status_t transport_get_info (pjmedia_transport *tp, - pjmedia_transport_info *info); + pjmedia_transport_info *info); static pj_status_t transport_attach (pjmedia_transport *tp, - void *user_data, - const pj_sockaddr_t *rem_addr, - const pj_sockaddr_t *rem_rtcp, - unsigned addr_len, - void (*rtp_cb)(void*, - void*, - pj_ssize_t), - void (*rtcp_cb)(void*, - void*, - pj_ssize_t)); + void *user_data, + const pj_sockaddr_t *rem_addr, + const pj_sockaddr_t *rem_rtcp, + unsigned addr_len, + void (*rtp_cb)(void*, + void*, + pj_ssize_t), + void (*rtcp_cb)(void*, + void*, + pj_ssize_t)); static pj_status_t transport_attach2 (pjmedia_transport *tp, - pjmedia_transport_attach_param - *att_param); -static void transport_detach (pjmedia_transport *tp, - void *strm); + pjmedia_transport_attach_param + *att_param); +static void transport_detach (pjmedia_transport *tp, + void *strm); static pj_status_t transport_send_rtp( pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); static pj_status_t transport_send_rtcp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, - const pj_sockaddr_t *addr, - unsigned addr_len, - const void *pkt, - pj_size_t size); + const pj_sockaddr_t *addr, + unsigned addr_len, + const void *pkt, + pj_size_t size); static pj_status_t transport_media_create(pjmedia_transport *tp, - pj_pool_t *pool, - unsigned options, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index); + pj_pool_t *pool, + unsigned options, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index); static pj_status_t transport_encode_sdp(pjmedia_transport *tp, - pj_pool_t *tmp_pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index); + pj_pool_t *tmp_pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index); static pj_status_t transport_media_start(pjmedia_transport *tp, - pj_pool_t *pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index); + pj_pool_t *pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index); static pj_status_t transport_media_stop(pjmedia_transport *tp); static pj_status_t transport_simulate_lost(pjmedia_transport *tp, - pjmedia_dir dir, - unsigned pct_lost); + pjmedia_dir dir, + unsigned pct_lost); static pj_status_t transport_destroy (pjmedia_transport *tp); /* * And these are ICE callbacks. */ static void ice_on_rx_data(pj_ice_strans *ice_st, - unsigned comp_id, - void *pkt, pj_size_t size, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + unsigned comp_id, + void *pkt, pj_size_t size, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); static void ice_on_ice_complete(pj_ice_strans *ice_st, - pj_ice_strans_op op, - pj_status_t status); + pj_ice_strans_op op, + pj_status_t status); static void ice_on_new_candidate(pj_ice_strans *ice_st, - const pj_ice_sess_cand *cand, - pj_bool_t last); + const pj_ice_sess_cand *cand, + pj_bool_t last); /* * Clean up ICE resources. @@ -196,21 +195,21 @@ static pjmedia_transport_op transport_ice_op = &transport_attach2 }; -static const pj_str_t STR_CANDIDATE = { "candidate", 9}; -static const pj_str_t STR_REM_CAND = { "remote-candidates", 17 }; -static const pj_str_t STR_ICE_LITE = { "ice-lite", 8}; -static const pj_str_t STR_ICE_MISMATCH = { "ice-mismatch", 12}; -static const pj_str_t STR_ICE_UFRAG = { "ice-ufrag", 9 }; -static const pj_str_t STR_ICE_PWD = { "ice-pwd", 7 }; -static const pj_str_t STR_IP4 = { "IP4", 3 }; -static const pj_str_t STR_IP6 = { "IP6", 3 }; -static const pj_str_t STR_RTCP = { "rtcp", 4 }; -static const pj_str_t STR_RTCP_MUX = { "rtcp-mux", 8 }; -static const pj_str_t STR_BANDW_RR = { "RR", 2 }; -static const pj_str_t STR_BANDW_RS = { "RS", 2 }; -static const pj_str_t STR_ICE_OPTIONS = { "ice-options", 11 }; -static const pj_str_t STR_TRICKLE = { "trickle", 7 }; -static const pj_str_t STR_END_OF_CAND = { "end-of-candidates", 17 }; +static const pj_str_t STR_CANDIDATE = { "candidate", 9}; +static const pj_str_t STR_REM_CAND = { "remote-candidates", 17 }; +static const pj_str_t STR_ICE_LITE = { "ice-lite", 8}; +static const pj_str_t STR_ICE_MISMATCH = { "ice-mismatch", 12}; +static const pj_str_t STR_ICE_UFRAG = { "ice-ufrag", 9 }; +static const pj_str_t STR_ICE_PWD = { "ice-pwd", 7 }; +static const pj_str_t STR_IP4 = { "IP4", 3 }; +static const pj_str_t STR_IP6 = { "IP6", 3 }; +static const pj_str_t STR_RTCP = { "rtcp", 4 }; +static const pj_str_t STR_RTCP_MUX = { "rtcp-mux", 8 }; +static const pj_str_t STR_BANDW_RR = { "RR", 2 }; +static const pj_str_t STR_BANDW_RS = { "RS", 2 }; +static const pj_str_t STR_ICE_OPTIONS = { "ice-options", 11 }; +static const pj_str_t STR_TRICKLE = { "trickle", 7 }; +static const pj_str_t STR_END_OF_CAND = { "end-of-candidates", 17 }; enum { COMP_RTP = 1, @@ -221,26 +220,26 @@ enum { /* Forward declaration of internal functions */ static int print_sdp_cand_attr(char *buffer, int max_len, - const pj_ice_sess_cand *cand); + const pj_ice_sess_cand *cand); static void get_ice_attr(const pjmedia_sdp_session *rem_sdp, - const pjmedia_sdp_media *rem_m, - const pjmedia_sdp_attr **p_ice_ufrag, - const pjmedia_sdp_attr **p_ice_pwd); + const pjmedia_sdp_media *rem_m, + const pjmedia_sdp_attr **p_ice_ufrag, + const pjmedia_sdp_attr **p_ice_pwd); static pj_status_t parse_cand(const char *obj_name, - pj_pool_t *pool, - const pj_str_t *orig_input, - pj_ice_sess_cand *cand); + pj_pool_t *pool, + const pj_str_t *orig_input, + pj_ice_sess_cand *cand); /* * Create ICE media transport. */ PJ_DEF(pj_status_t) pjmedia_ice_create(pjmedia_endpt *endpt, - const char *name, - unsigned comp_cnt, - const pj_ice_strans_cfg *cfg, - const pjmedia_ice_cb *cb, - pjmedia_transport **p_tp) + const char *name, + unsigned comp_cnt, + const pj_ice_strans_cfg *cfg, + const pjmedia_ice_cb *cb, + pjmedia_transport **p_tp) { return pjmedia_ice_create2(endpt, name, comp_cnt, cfg, cb, 0, p_tp); } @@ -249,12 +248,12 @@ PJ_DEF(pj_status_t) pjmedia_ice_create(pjmedia_endpt *endpt, * Create ICE media transport. */ PJ_DEF(pj_status_t) pjmedia_ice_create2(pjmedia_endpt *endpt, - const char *name, - unsigned comp_cnt, - const pj_ice_strans_cfg *cfg, - const pjmedia_ice_cb *cb, - unsigned options, - pjmedia_transport **p_tp) + const char *name, + unsigned comp_cnt, + const pj_ice_strans_cfg *cfg, + const pjmedia_ice_cb *cb, + unsigned options, + pjmedia_transport **p_tp) { return pjmedia_ice_create3(endpt, name, comp_cnt, cfg, cb, options, NULL, p_tp); @@ -264,13 +263,13 @@ PJ_DEF(pj_status_t) pjmedia_ice_create2(pjmedia_endpt *endpt, * Create ICE media transport. */ PJ_DEF(pj_status_t) pjmedia_ice_create3(pjmedia_endpt *endpt, - const char *name, - unsigned comp_cnt, - const pj_ice_strans_cfg *cfg, - const pjmedia_ice_cb *cb, - unsigned options, - void *user_data, - pjmedia_transport **p_tp) + const char *name, + unsigned comp_cnt, + const pj_ice_strans_cfg *cfg, + const pjmedia_ice_cb *cb, + unsigned options, + void *user_data, + pjmedia_transport **p_tp) { pj_pool_t *pool; pj_ice_strans_cb ice_st_cb; @@ -299,7 +298,7 @@ PJ_DEF(pj_status_t) pjmedia_ice_create3(pjmedia_endpt *endpt, pj_memcpy(&ice_st_cfg, cfg, sizeof(pj_ice_strans_cfg)); if (cb) - pj_memcpy(&tp_ice->cb, cb, sizeof(pjmedia_ice_cb)); + pj_memcpy(&tp_ice->cb, cb, sizeof(pjmedia_ice_cb)); /* Assign return value first because ICE might call callback * in create() @@ -314,30 +313,30 @@ PJ_DEF(pj_status_t) pjmedia_ice_create3(pjmedia_endpt *endpt, /* Configure RTP socket buffer settings, if not set */ if (ice_st_cfg.comp[COMP_RTP-1].so_rcvbuf_size == 0) { - ice_st_cfg.comp[COMP_RTP-1].so_rcvbuf_size = - PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE; + ice_st_cfg.comp[COMP_RTP-1].so_rcvbuf_size = + PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE; } if (ice_st_cfg.comp[COMP_RTP-1].so_sndbuf_size == 0) { - ice_st_cfg.comp[COMP_RTP-1].so_sndbuf_size = - PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE; + ice_st_cfg.comp[COMP_RTP-1].so_sndbuf_size = + PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE; } if (ice_st_cfg.send_buf_size == 0) - ice_st_cfg.send_buf_size = PJMEDIA_MAX_MTU; + ice_st_cfg.send_buf_size = PJMEDIA_MAX_MTU; /* Create ICE */ status = pj_ice_strans_create(name, &ice_st_cfg, comp_cnt, tp_ice, - &ice_st_cb, &tp_ice->ice_st); + &ice_st_cb, &tp_ice->ice_st); if (status != PJ_SUCCESS) { - pj_pool_release(pool); - *p_tp = NULL; - return status; + pj_pool_release(pool); + *p_tp = NULL; + return status; } /* Sync to ICE */ { - pj_grp_lock_t *grp_lock = pj_ice_strans_get_grp_lock(tp_ice->ice_st); - pj_grp_lock_add_ref(grp_lock); - pj_grp_lock_add_handler(grp_lock, pool, tp_ice, &tp_ice_on_destroy); + pj_grp_lock_t *grp_lock = pj_ice_strans_get_grp_lock(tp_ice->ice_st); + pj_grp_lock_add_ref(grp_lock); + pj_grp_lock_add_handler(grp_lock, pool, tp_ice, &tp_ice_on_destroy); } /* Done */ @@ -356,8 +355,8 @@ PJ_DEF(pj_grp_lock_t *) pjmedia_ice_get_grp_lock(pjmedia_transport *tp) * transport. */ PJ_DEF(pj_status_t) pjmedia_ice_add_ice_cb( pjmedia_transport *tp, - const pjmedia_ice_cb *cb, - void *user_data) + const pjmedia_ice_cb *cb, + void *user_data) { struct transport_ice *tp_ice = (struct transport_ice*)tp; ice_listener *il; @@ -370,17 +369,17 @@ PJ_DEF(pj_status_t) pjmedia_ice_add_ice_cb( pjmedia_transport *tp, pj_grp_lock_acquire(grp_lock); if (!pj_list_empty(&tp_ice->listener_empty)) { - il = tp_ice->listener_empty.next; - pj_list_erase(il); - il->cb = *cb; - il->user_data = user_data; - pj_list_push_back(&tp_ice->listener, il); + il = tp_ice->listener_empty.next; + pj_list_erase(il); + il->cb = *cb; + il->user_data = user_data; + pj_list_push_back(&tp_ice->listener, il); } else { - il = PJ_POOL_ZALLOC_T(tp_ice->pool, ice_listener); - pj_list_init(il); - il->cb = *cb; - il->user_data = user_data; - pj_list_push_back(&tp_ice->listener, il); + il = PJ_POOL_ZALLOC_T(tp_ice->pool, ice_listener); + pj_list_init(il); + il->cb = *cb; + il->user_data = user_data; + pj_list_push_back(&tp_ice->listener, il); } pj_grp_lock_release(grp_lock); @@ -394,8 +393,8 @@ PJ_DEF(pj_status_t) pjmedia_ice_add_ice_cb( pjmedia_transport *tp, * ICE media transport. */ PJ_DEF(pj_status_t) pjmedia_ice_remove_ice_cb( pjmedia_transport *tp, - const pjmedia_ice_cb *cb, - void *user_data) + const pjmedia_ice_cb *cb, + void *user_data) { struct transport_ice *tp_ice = (struct transport_ice*)tp; ice_listener *il; @@ -408,12 +407,12 @@ PJ_DEF(pj_status_t) pjmedia_ice_remove_ice_cb( pjmedia_transport *tp, pj_grp_lock_acquire(grp_lock); for (il=tp_ice->listener.next; il!=&tp_ice->listener; il=il->next) { - if (pj_memcmp(&il->cb, cb, sizeof(cb))==0 && il->user_data==user_data) - break; + if (pj_memcmp(&il->cb, cb, sizeof(cb))==0 && il->user_data==user_data) + break; } if (il != &tp_ice->listener) { - pj_list_erase(il); - pj_list_push_back(&tp_ice->listener_empty, il); + pj_list_erase(il); + pj_list_push_back(&tp_ice->listener_empty, il); } pj_grp_lock_release(grp_lock); @@ -424,7 +423,7 @@ PJ_DEF(pj_status_t) pjmedia_ice_remove_ice_cb( pjmedia_transport *tp, /* Check if trickle support is signalled in the specified SDP. */ PJ_DEF(pj_bool_t) pjmedia_ice_sdp_has_trickle( const pjmedia_sdp_session *sdp, - unsigned med_idx) + unsigned med_idx) { const pjmedia_sdp_media *m; const pjmedia_sdp_attr *a; @@ -435,13 +434,13 @@ PJ_DEF(pj_bool_t) pjmedia_ice_sdp_has_trickle( const pjmedia_sdp_session *sdp, m = sdp->media[med_idx]; a = pjmedia_sdp_attr_find(m->attr_count, m->attr, &STR_ICE_OPTIONS, NULL); if (a && pj_strstr(&a->value, &STR_TRICKLE)) - return PJ_TRUE; + return PJ_TRUE; /* Find in session level */ a = pjmedia_sdp_attr_find(sdp->attr_count, sdp->attr, &STR_ICE_OPTIONS, - NULL); + NULL); if (a && pj_strstr(&a->value, &STR_TRICKLE)) - return PJ_TRUE; + return PJ_TRUE; return PJ_FALSE; } @@ -451,47 +450,47 @@ PJ_DEF(pj_bool_t) pjmedia_ice_sdp_has_trickle( const pjmedia_sdp_session *sdp, * or receiving update of remote ICE candidates in trickle ICE. */ PJ_DEF(pj_status_t) pjmedia_ice_trickle_update( - pjmedia_transport *tp, - const pj_str_t *rem_ufrag, - const pj_str_t *rem_passwd, - unsigned rcand_cnt, - const pj_ice_sess_cand rcand[], - pj_bool_t rcand_end) + pjmedia_transport *tp, + const pj_str_t *rem_ufrag, + const pj_str_t *rem_passwd, + unsigned rcand_cnt, + const pj_ice_sess_cand rcand[], + pj_bool_t rcand_end) { struct transport_ice *tp_ice = (struct transport_ice*)tp; pj_status_t status; PJ_ASSERT_RETURN(tp_ice && tp_ice->ice_st, PJ_EINVAL); PJ_ASSERT_RETURN(tp_ice->trickle_ice != PJ_ICE_SESS_TRICKLE_DISABLED, - PJ_EINVALIDOP); + PJ_EINVALIDOP); /* Update the checklist */ status = pj_ice_strans_update_check_list(tp_ice->ice_st, - rem_ufrag, rem_passwd, - rcand_cnt, rcand, rcand_end); + rem_ufrag, rem_passwd, + rcand_cnt, rcand, rcand_end); if (status != PJ_SUCCESS) - return status; + return status; /* Start ICE if both sides have sent their (initial) SDPs */ if (!pj_ice_strans_sess_is_running(tp_ice->ice_st)) { - unsigned i, comp_cnt; - - comp_cnt = pj_ice_strans_get_running_comp_cnt(tp_ice->ice_st); - for (i = 0; i < comp_cnt; ++i) { - if (tp_ice->last_send_cand_cnt[i] > 0) - break; - } - if (i != comp_cnt) { - pj_str_t rufrag; - pj_ice_strans_get_ufrag_pwd(tp_ice->ice_st, NULL, NULL, - &rufrag, NULL); - if (rufrag.slen > 0) { - PJ_LOG(3,(THIS_FILE,"Trickle ICE starts connectivity check")); - status = pj_ice_strans_start_ice(tp_ice->ice_st, NULL, NULL, - 0, NULL); - } - } + unsigned i, comp_cnt; + + comp_cnt = pj_ice_strans_get_running_comp_cnt(tp_ice->ice_st); + for (i = 0; i < comp_cnt; ++i) { + if (tp_ice->last_send_cand_cnt[i] > 0) + break; + } + if (i != comp_cnt) { + pj_str_t rufrag; + pj_ice_strans_get_ufrag_pwd(tp_ice->ice_st, NULL, NULL, + &rufrag, NULL); + if (rufrag.slen > 0) { + PJ_LOG(3,(THIS_FILE,"Trickle ICE starts connectivity check")); + status = pj_ice_strans_start_ice(tp_ice->ice_st, NULL, NULL, + 0, NULL); + } + } } return status; @@ -500,14 +499,14 @@ PJ_DEF(pj_status_t) pjmedia_ice_trickle_update( /* Fetch trickle ICE info from the specified SDP. */ PJ_DEF(pj_status_t) pjmedia_ice_trickle_decode_sdp( - const pjmedia_sdp_session *sdp, - unsigned media_index, - pj_str_t *mid, - pj_str_t *ufrag, - pj_str_t *passwd, - unsigned *cand_cnt, - pj_ice_sess_cand cand[], - pj_bool_t *end_of_cand) + const pjmedia_sdp_session *sdp, + unsigned media_index, + pj_str_t *mid, + pj_str_t *ufrag, + pj_str_t *passwd, + unsigned *cand_cnt, + pj_ice_sess_cand cand[], + pj_bool_t *end_of_cand) { const pjmedia_sdp_media *m; const pjmedia_sdp_attr *a; @@ -517,57 +516,57 @@ PJ_DEF(pj_status_t) pjmedia_ice_trickle_decode_sdp( m = sdp->media[media_index]; if (mid) { - a = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "mid", NULL); - if (a) { - *mid = a->value; - } else { - pj_bzero(mid, sizeof(*mid)); - } + a = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "mid", NULL); + if (a) { + *mid = a->value; + } else { + pj_bzero(mid, sizeof(*mid)); + } } if (ufrag && passwd) { - const pjmedia_sdp_attr *a_ufrag, *a_pwd; - get_ice_attr(sdp, m, &a_ufrag, &a_pwd); - if (a_ufrag && a_pwd) { - *ufrag = a_ufrag->value; - *passwd = a_pwd->value; - } else { - pj_bzero(ufrag, sizeof(*ufrag)); - pj_bzero(passwd, sizeof(*passwd)); - } + const pjmedia_sdp_attr *a_ufrag, *a_pwd; + get_ice_attr(sdp, m, &a_ufrag, &a_pwd); + if (a_ufrag && a_pwd) { + *ufrag = a_ufrag->value; + *passwd = a_pwd->value; + } else { + pj_bzero(ufrag, sizeof(*ufrag)); + pj_bzero(passwd, sizeof(*passwd)); + } } if (cand_cnt && cand && *cand_cnt > 0) { - pj_status_t status; - unsigned i, cnt = 0; - - for (i=0; iattr_count && cnt<*cand_cnt; ++i) { - a = m->attr[i]; - if (pj_strcmp(&a->name, &STR_CANDIDATE)!=0) - continue; - - /* Parse candidate */ - status = parse_cand("trickle-ice", NULL, &a->value, &cand[cnt]); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,("trickle-ice", status, - "Error in parsing SDP candidate attribute '%.*s', " - "candidate is ignored", - (int)a->value.slen, a->value.ptr)); - continue; - } - ++cnt; - } - *cand_cnt = cnt; + pj_status_t status; + unsigned i, cnt = 0; + + for (i=0; iattr_count && cnt<*cand_cnt; ++i) { + a = m->attr[i]; + if (pj_strcmp(&a->name, &STR_CANDIDATE)!=0) + continue; + + /* Parse candidate */ + status = parse_cand("trickle-ice", NULL, &a->value, &cand[cnt]); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,("trickle-ice", status, + "Error in parsing SDP candidate attribute '%.*s', " + "candidate is ignored", + (int)a->value.slen, a->value.ptr)); + continue; + } + ++cnt; + } + *cand_cnt = cnt; } if (end_of_cand) { - a = pjmedia_sdp_attr_find(m->attr_count, m->attr, &STR_END_OF_CAND, - NULL); - if (!a) { - a = pjmedia_sdp_attr_find(sdp->attr_count, sdp->attr, - &STR_END_OF_CAND, NULL); - } - *end_of_cand = (a != NULL); + a = pjmedia_sdp_attr_find(m->attr_count, m->attr, &STR_END_OF_CAND, + NULL); + if (!a) { + a = pjmedia_sdp_attr_find(sdp->attr_count, sdp->attr, + &STR_END_OF_CAND, NULL); + } + *end_of_cand = (a != NULL); } return PJ_SUCCESS; } @@ -575,14 +574,14 @@ PJ_DEF(pj_status_t) pjmedia_ice_trickle_decode_sdp( /* Generate SDP attributes for trickle ICE in the specified SDP. */ PJ_DEF(pj_status_t) pjmedia_ice_trickle_encode_sdp( - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp, - const pj_str_t *mid, - const pj_str_t *ufrag, - const pj_str_t *passwd, - unsigned cand_cnt, - const pj_ice_sess_cand cand[], - pj_bool_t end_of_cand) + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp, + const pj_str_t *mid, + const pj_str_t *ufrag, + const pj_str_t *passwd, + unsigned cand_cnt, + const pj_ice_sess_cand cand[], + pj_bool_t end_of_cand) { pjmedia_sdp_media *m = NULL; pjmedia_sdp_attr *a; @@ -592,92 +591,92 @@ PJ_DEF(pj_status_t) pjmedia_ice_trickle_encode_sdp( /* Find media by checking "a=mid"*/ for (i = 0; i < sdp->media_count; ++i) { - m = sdp->media[i]; - a = pjmedia_sdp_media_find_attr2(m, "mid", NULL); - if (a && pj_strcmp(&a->value, mid)==0) - break; + m = sdp->media[i]; + a = pjmedia_sdp_media_find_attr2(m, "mid", NULL); + if (a && pj_strcmp(&a->value, mid)==0) + break; } /* Media not exist, try to add it */ if (i == sdp->media_count) { - if (sdp->media_count >= PJMEDIA_MAX_SDP_MEDIA) { - PJ_LOG(3,(THIS_FILE,"Trickle ICE failed to encode candidates, " - "the specified SDP has too many media")); - return PJ_ETOOMANY; - } + if (sdp->media_count >= PJMEDIA_MAX_SDP_MEDIA) { + PJ_LOG(3,(THIS_FILE,"Trickle ICE failed to encode candidates, " + "the specified SDP has too many media")); + return PJ_ETOOMANY; + } - /* Add a new media to the SDP */ - m = PJ_POOL_ZALLOC_T(sdp_pool, pjmedia_sdp_media); - m->desc.media = pj_str("audio"); - m->desc.fmt_count = 1; - m->desc.fmt[0] = pj_str("0"); - m->desc.transport = pj_str("RTP/AVP"); - sdp->media[sdp->media_count++] = m; + /* Add a new media to the SDP */ + m = PJ_POOL_ZALLOC_T(sdp_pool, pjmedia_sdp_media); + m->desc.media = pj_str("audio"); + m->desc.fmt_count = 1; + m->desc.fmt[0] = pj_str("0"); + m->desc.transport = pj_str("RTP/AVP"); + sdp->media[sdp->media_count++] = m; - /* Add media ID attribute "a=mid" */ - a = pjmedia_sdp_attr_create(sdp_pool, "mid", mid); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, a); + /* Add media ID attribute "a=mid" */ + a = pjmedia_sdp_attr_create(sdp_pool, "mid", mid); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, a); } /* Add "a=ice-options:trickle" in session level */ a = pjmedia_sdp_attr_find(sdp->attr_count, sdp->attr, &STR_ICE_OPTIONS, - NULL); + NULL); if (!a || !pj_strstr(&a->value, &STR_TRICKLE)) { - a = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_OPTIONS.ptr, - &STR_TRICKLE); - pjmedia_sdp_attr_add(&sdp->attr_count, sdp->attr, a); + a = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_OPTIONS.ptr, + &STR_TRICKLE); + pjmedia_sdp_attr_add(&sdp->attr_count, sdp->attr, a); } /* Add "a=ice-options:trickle" in media level */ /* a = pjmedia_sdp_attr_find(m->attr_count, m->attr, &STR_ICE_OPTIONS, - NULL); + NULL); if (!a || !pj_strstr(&a->value, &STR_TRICKLE)) { - a = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_OPTIONS.ptr, - &STR_TRICKLE); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, a); + a = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_OPTIONS.ptr, + &STR_TRICKLE); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, a); } */ /* Add ice-ufrag & ice-pwd attributes */ if (ufrag && passwd && - !pjmedia_sdp_attr_find(m->attr_count, m->attr, &STR_ICE_UFRAG, NULL)) + !pjmedia_sdp_attr_find(m->attr_count, m->attr, &STR_ICE_UFRAG, NULL)) { - a = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_UFRAG.ptr, ufrag); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, a); + a = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_UFRAG.ptr, ufrag); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, a); - a = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_PWD.ptr, passwd); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, a); + a = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_PWD.ptr, passwd); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, a); } /* Add candidates */ for (i=0; iattr_count, m->attr, a); + value.ptr = attr_buf; + a = pjmedia_sdp_attr_create(sdp_pool, STR_CANDIDATE.ptr, &value); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, a); } /* Add "a=end-of-candidates" */ if (end_of_cand) { - a = pjmedia_sdp_attr_find(m->attr_count, m->attr, &STR_END_OF_CAND, - NULL); - if (!a) { - a = pjmedia_sdp_attr_create(sdp_pool, STR_END_OF_CAND.ptr, NULL); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, a); - } + a = pjmedia_sdp_attr_find(m->attr_count, m->attr, &STR_END_OF_CAND, + NULL); + if (!a) { + a = pjmedia_sdp_attr_create(sdp_pool, STR_END_OF_CAND.ptr, NULL); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, a); + } } return PJ_SUCCESS; @@ -691,16 +690,16 @@ PJ_DEF(pj_bool_t) pjmedia_ice_trickle_has_new_cand(pjmedia_transport *tp) /* Make sure ICE transport has session already */ if (!tp_ice->ice_st || !pj_ice_strans_has_sess(tp_ice->ice_st)) - return PJ_FALSE; + return PJ_FALSE; /* Count all local candidates */ comp_cnt = pj_ice_strans_get_running_comp_cnt(tp_ice->ice_st); for (i = 0; i < comp_cnt; ++i) { - if (tp_ice->last_send_cand_cnt[i] < - pj_ice_strans_get_cands_count(tp_ice->ice_st, i+1)) - { - return PJ_TRUE; - } + if (tp_ice->last_send_cand_cnt[i] < + pj_ice_strans_get_cands_count(tp_ice->ice_st, i+1)) + { + return PJ_TRUE; + } } return PJ_FALSE; } @@ -710,10 +709,10 @@ PJ_DEF(pj_bool_t) pjmedia_ice_trickle_has_new_cand(pjmedia_transport *tp) * remote (e.g: via SIP INFO). */ PJ_DEF(pj_status_t) pjmedia_ice_trickle_send_local_cand( - pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp, - pj_bool_t *p_end_of_cand) + pjmedia_transport *tp, + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp, + pj_bool_t *p_end_of_cand) { struct transport_ice *tp_ice = (struct transport_ice*)tp; pj_str_t ufrag, pwd; @@ -726,7 +725,7 @@ PJ_DEF(pj_status_t) pjmedia_ice_trickle_send_local_cand( /* Make sure ICE transport has session already */ if (!tp_ice->ice_st || !pj_ice_strans_has_sess(tp_ice->ice_st)) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; end_of_cand = tp_ice->end_of_cand; @@ -736,20 +735,20 @@ PJ_DEF(pj_status_t) pjmedia_ice_trickle_send_local_cand( cand_cnt = 0; comp_cnt = pj_ice_strans_get_running_comp_cnt(tp_ice->ice_st); for (i = 0; i < comp_cnt; ++i) { - unsigned cnt = PJ_ICE_MAX_CAND - cand_cnt; - - /* Get all local candidates for this comp */ - status = pj_ice_strans_enum_cands(tp_ice->ice_st, i+1, - &cnt, &cand[cand_cnt]); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(tp_ice->base.name, status, - "Failed enumerating local candidates for comp-id=%d", - i+1)); - continue; - } - cand_cnt += cnt; + unsigned cnt = PJ_ICE_MAX_CAND - cand_cnt; + + /* Get all local candidates for this comp */ + status = pj_ice_strans_enum_cands(tp_ice->ice_st, i+1, + &cnt, &cand[cand_cnt]); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(tp_ice->base.name, status, + "Failed enumerating local candidates for comp-id=%d", + i+1)); + continue; + } + cand_cnt += cnt; - tp_ice->last_send_cand_cnt[i] = cnt; + tp_ice->last_send_cand_cnt[i] = cnt; } /* Update the SDP with all local candidates (not just the new ones). @@ -760,15 +759,15 @@ PJ_DEF(pj_status_t) pjmedia_ice_trickle_send_local_cand( * in the same order as they were sent before. */ status = pjmedia_ice_trickle_encode_sdp(sdp_pool, sdp, &tp_ice->sdp_mid, - &ufrag, &pwd, cand_cnt, cand, - end_of_cand); + &ufrag, &pwd, cand_cnt, cand, + end_of_cand); if (status != PJ_SUCCESS) { - PJ_PERROR(3,(tp_ice->base.name, status, - "Failed encoding local candidates to SDP")); + PJ_PERROR(3,(tp_ice->base.name, status, + "Failed encoding local candidates to SDP")); } if (p_end_of_cand) - *p_end_of_cand = end_of_cand; + *p_end_of_cand = end_of_cand; return PJ_SUCCESS; } @@ -776,18 +775,18 @@ PJ_DEF(pj_status_t) pjmedia_ice_trickle_send_local_cand( /* Disable ICE when SDP from remote doesn't contain a=candidate line */ static void set_no_ice(struct transport_ice *tp_ice, const char *reason, - pj_status_t err) + pj_status_t err) { if (err != PJ_SUCCESS) { - PJ_PERROR(4,(tp_ice->base.name, err, - "Stopping ICE, reason=%s", reason)); + PJ_PERROR(4,(tp_ice->base.name, err, + "Stopping ICE, reason=%s", reason)); } else { - PJ_LOG(4,(tp_ice->base.name, - "Stopping ICE, reason=%s", reason)); + PJ_LOG(4,(tp_ice->base.name, + "Stopping ICE, reason=%s", reason)); } if (tp_ice->ice_st) { - pj_ice_strans_stop_ice(tp_ice->ice_st); + pj_ice_strans_stop_ice(tp_ice->ice_st); } tp_ice->use_ice = PJ_FALSE; @@ -796,44 +795,44 @@ static void set_no_ice(struct transport_ice *tp_ice, const char *reason, /* Create SDP candidate attribute */ static int print_sdp_cand_attr(char *buffer, int max_len, - const pj_ice_sess_cand *cand) + const pj_ice_sess_cand *cand) { char ipaddr[PJ_INET6_ADDRSTRLEN+2]; int len, len2; len = pj_ansi_snprintf( buffer, max_len, - "%.*s %u UDP %u %s %u typ ", - (int)cand->foundation.slen, - cand->foundation.ptr, - (unsigned)cand->comp_id, - cand->prio, - pj_sockaddr_print(&cand->addr, ipaddr, - sizeof(ipaddr), 0), - (unsigned)pj_sockaddr_get_port(&cand->addr)); + "%.*s %u UDP %u %s %u typ ", + (int)cand->foundation.slen, + cand->foundation.ptr, + (unsigned)cand->comp_id, + cand->prio, + pj_sockaddr_print(&cand->addr, ipaddr, + sizeof(ipaddr), 0), + (unsigned)pj_sockaddr_get_port(&cand->addr)); if (len < 1 || len >= max_len) - return -1; + return -1; switch (cand->type) { case PJ_ICE_CAND_TYPE_HOST: - len2 = pj_ansi_snprintf(buffer+len, max_len-len, "host"); - break; + len2 = pj_ansi_snprintf(buffer+len, max_len-len, "host"); + break; case PJ_ICE_CAND_TYPE_SRFLX: case PJ_ICE_CAND_TYPE_RELAYED: case PJ_ICE_CAND_TYPE_PRFLX: - len2 = pj_ansi_snprintf(buffer+len, max_len-len, - "%s raddr %s rport %d", - pj_ice_get_cand_type_name(cand->type), - pj_sockaddr_print(&cand->rel_addr, ipaddr, - sizeof(ipaddr), 0), - (int)pj_sockaddr_get_port(&cand->rel_addr)); - break; + len2 = pj_ansi_snprintf(buffer+len, max_len-len, + "%s raddr %s rport %d", + pj_ice_get_cand_type_name(cand->type), + pj_sockaddr_print(&cand->rel_addr, ipaddr, + sizeof(ipaddr), 0), + (int)pj_sockaddr_get_port(&cand->rel_addr)); + break; default: - pj_assert(!"Invalid candidate type"); - len2 = -1; - break; + pj_assert(!"Invalid candidate type"); + len2 = -1; + break; } if (len2 < 1 || len2 >= max_len-len) - return -1; + return -1; return len+len2; } @@ -841,29 +840,29 @@ static int print_sdp_cand_attr(char *buffer, int max_len, /* Get ice-ufrag and ice-pwd attribute */ static void get_ice_attr(const pjmedia_sdp_session *rem_sdp, - const pjmedia_sdp_media *rem_m, - const pjmedia_sdp_attr **p_ice_ufrag, - const pjmedia_sdp_attr **p_ice_pwd) + const pjmedia_sdp_media *rem_m, + const pjmedia_sdp_attr **p_ice_ufrag, + const pjmedia_sdp_attr **p_ice_pwd) { pjmedia_sdp_attr *attr; /* Find ice-ufrag attribute in media descriptor */ attr = pjmedia_sdp_attr_find(rem_m->attr_count, rem_m->attr, - &STR_ICE_UFRAG, NULL); + &STR_ICE_UFRAG, NULL); if (attr == NULL) { - /* Find ice-ufrag attribute in session descriptor */ - attr = pjmedia_sdp_attr_find(rem_sdp->attr_count, rem_sdp->attr, - &STR_ICE_UFRAG, NULL); + /* Find ice-ufrag attribute in session descriptor */ + attr = pjmedia_sdp_attr_find(rem_sdp->attr_count, rem_sdp->attr, + &STR_ICE_UFRAG, NULL); } *p_ice_ufrag = attr; /* Find ice-pwd attribute in media descriptor */ attr = pjmedia_sdp_attr_find(rem_m->attr_count, rem_m->attr, - &STR_ICE_PWD, NULL); + &STR_ICE_PWD, NULL); if (attr == NULL) { - /* Find ice-pwd attribute in session descriptor */ - attr = pjmedia_sdp_attr_find(rem_sdp->attr_count, rem_sdp->attr, - &STR_ICE_PWD, NULL); + /* Find ice-pwd attribute in session descriptor */ + attr = pjmedia_sdp_attr_find(rem_sdp->attr_count, rem_sdp->attr, + &STR_ICE_PWD, NULL); } *p_ice_pwd = attr; } @@ -871,8 +870,8 @@ static void get_ice_attr(const pjmedia_sdp_session *rem_sdp, /* Encode and add "a=ice-mismatch" attribute in the SDP */ static void encode_ice_mismatch(pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp_local, - unsigned media_index) + pjmedia_sdp_session *sdp_local, + unsigned media_index) { pjmedia_sdp_attr *attr; pjmedia_sdp_media *m = sdp_local->media[media_index]; @@ -886,17 +885,17 @@ static void encode_ice_mismatch(pj_pool_t *sdp_pool, /* Encode ICE information in SDP */ static pj_status_t encode_session_in_sdp(struct transport_ice *tp_ice, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp_local, - unsigned media_index, - unsigned comp_cnt, - pj_bool_t restart_session, - pj_bool_t rtcp_mux, - pj_bool_t trickle) + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp_local, + unsigned media_index, + unsigned comp_cnt, + pj_bool_t restart_session, + pj_bool_t rtcp_mux, + pj_bool_t trickle) { enum { - ATTR_BUF_LEN = 160, /* Max len of a=candidate attr */ - RATTR_BUF_LEN= 160 /* Max len of a=remote-candidates attr */ + ATTR_BUF_LEN = 160, /* Max len of a=candidate attr */ + RATTR_BUF_LEN= 160 /* Max len of a=remote-candidates attr */ }; pjmedia_sdp_media *m = sdp_local->media[media_index]; pj_str_t local_ufrag, local_pwd; @@ -908,7 +907,7 @@ static pj_status_t encode_session_in_sdp(struct transport_ice *tp_ice, /* Get ufrag and pwd from current session */ pj_ice_strans_get_ufrag_pwd(tp_ice->ice_st, &local_ufrag, &local_pwd, - NULL, NULL); + NULL, NULL); /* The listing of candidates depends on whether ICE has completed * or not. When ICE has completed: @@ -925,213 +924,213 @@ static pj_status_t encode_session_in_sdp(struct transport_ice *tp_ice, * new ufrag/pwd pair. */ if (!restart_session && pj_ice_strans_sess_is_complete(tp_ice->ice_st) && - pj_ice_strans_get_state(tp_ice->ice_st) != PJ_ICE_STRANS_STATE_FAILED) + pj_ice_strans_get_state(tp_ice->ice_st) != PJ_ICE_STRANS_STATE_FAILED) { - const pj_ice_sess_check *check; - char *attr_buf; - pjmedia_sdp_conn *conn; - pjmedia_sdp_attr *a_rtcp; - pj_str_t rem_cand; - unsigned comp; - - /* Encode ice-ufrag attribute */ - attr = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_UFRAG.ptr, - &local_ufrag); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); - - /* Encode ice-pwd attribute */ - attr = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_PWD.ptr, - &local_pwd); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); - - /* Prepare buffer */ - attr_buf = (char*) pj_pool_alloc(sdp_pool, ATTR_BUF_LEN); - rem_cand.ptr = (char*) pj_pool_alloc(sdp_pool, RATTR_BUF_LEN); - rem_cand.slen = 0; - - /* 9.1.2.2: Existing Media Streams with ICE Completed - * The default destination for media (i.e., the values of - * the IP addresses and ports in the m and c line used for - * that media stream) MUST be the local candidate from the - * highest priority nominated pair in the valid list for each - * component. - */ - check = pj_ice_strans_get_valid_pair(tp_ice->ice_st, 1); - if (check == NULL) { - pj_assert(!"Shouldn't happen"); - return PJ_EBUG; - } - - /* Override connection line address and media port number */ - conn = m->conn; - if (conn == NULL) - conn = sdp_local->conn; - - conn->addr.ptr = (char*) pj_pool_alloc(sdp_pool, - PJ_INET6_ADDRSTRLEN); - pj_sockaddr_print(&check->lcand->addr, conn->addr.ptr, - PJ_INET6_ADDRSTRLEN, 0); - conn->addr.slen = pj_ansi_strlen(conn->addr.ptr); - m->desc.port = pj_sockaddr_get_port(&check->lcand->addr); - - /* Override address RTCP attribute if it's present */ - if (comp_cnt == 2 && - (check = pj_ice_strans_get_valid_pair(tp_ice->ice_st, - COMP_RTCP)) != NULL && - (a_rtcp = pjmedia_sdp_attr_find(m->attr_count, m->attr, - &STR_RTCP, 0)) != NULL) - { - pjmedia_sdp_attr_remove(&m->attr_count, m->attr, a_rtcp); - - a_rtcp = pjmedia_sdp_attr_create_rtcp(sdp_pool, - &check->lcand->addr); - if (a_rtcp) - pjmedia_sdp_attr_add(&m->attr_count, m->attr, a_rtcp); - } - - /* Encode only candidates matching the default destination - * for each component - */ - for (comp=0; comp < comp_cnt; ++comp) { - int len; - pj_str_t value; - - /* Get valid pair for this component */ - check = pj_ice_strans_get_valid_pair(tp_ice->ice_st, comp+1); - if (check == NULL) - continue; - - /* Print and add local candidate in the pair */ - value.ptr = attr_buf; - value.slen = print_sdp_cand_attr(attr_buf, ATTR_BUF_LEN, - check->lcand); - if (value.slen < 0) { - pj_assert(!"Not enough attr_buf to print candidate"); - return PJ_EBUG; - } - - attr = pjmedia_sdp_attr_create(sdp_pool, STR_CANDIDATE.ptr, - &value); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); - - /* Append to a=remote-candidates attribute */ - if (pj_ice_strans_get_role(tp_ice->ice_st) == - PJ_ICE_SESS_ROLE_CONTROLLING) - { - char rem_addr[PJ_INET6_ADDRSTRLEN]; - - pj_sockaddr_print(&check->rcand->addr, rem_addr, - sizeof(rem_addr), 0); - len = pj_ansi_snprintf( - rem_cand.ptr + rem_cand.slen, - RATTR_BUF_LEN - rem_cand.slen, - "%s%u %s %u", - (rem_cand.slen==0? "" : " "), - comp+1, rem_addr, - pj_sockaddr_get_port(&check->rcand->addr) - ); - if (len < 1 || len >= RATTR_BUF_LEN - rem_cand.slen) { - pj_assert(!"Not enough buffer to print " - "remote-candidates"); - return PJ_EBUG; - } - - rem_cand.slen += len; - } - } - - /* 9.1.2.2: Existing Media Streams with ICE Completed - * In addition, if the agent is controlling, it MUST include - * the a=remote-candidates attribute for each media stream - * whose check list is in the Completed state. The attribute - * contains the remote candidates from the highest priority - * nominated pair in the valid list for each component of that - * media stream. - */ - if (pj_ice_strans_get_role(tp_ice->ice_st) == - PJ_ICE_SESS_ROLE_CONTROLLING) - { - attr = pjmedia_sdp_attr_create(sdp_pool, STR_REM_CAND.ptr, - &rem_cand); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); - } + const pj_ice_sess_check *check; + char *attr_buf; + pjmedia_sdp_conn *conn; + pjmedia_sdp_attr *a_rtcp; + pj_str_t rem_cand; + unsigned comp; + + /* Encode ice-ufrag attribute */ + attr = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_UFRAG.ptr, + &local_ufrag); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); + + /* Encode ice-pwd attribute */ + attr = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_PWD.ptr, + &local_pwd); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); + + /* Prepare buffer */ + attr_buf = (char*) pj_pool_alloc(sdp_pool, ATTR_BUF_LEN); + rem_cand.ptr = (char*) pj_pool_alloc(sdp_pool, RATTR_BUF_LEN); + rem_cand.slen = 0; + + /* 9.1.2.2: Existing Media Streams with ICE Completed + * The default destination for media (i.e., the values of + * the IP addresses and ports in the m and c line used for + * that media stream) MUST be the local candidate from the + * highest priority nominated pair in the valid list for each + * component. + */ + check = pj_ice_strans_get_valid_pair(tp_ice->ice_st, 1); + if (check == NULL) { + pj_assert(!"Shouldn't happen"); + return PJ_EBUG; + } + + /* Override connection line address and media port number */ + conn = m->conn; + if (conn == NULL) + conn = sdp_local->conn; + + conn->addr.ptr = (char*) pj_pool_alloc(sdp_pool, + PJ_INET6_ADDRSTRLEN); + pj_sockaddr_print(&check->lcand->addr, conn->addr.ptr, + PJ_INET6_ADDRSTRLEN, 0); + conn->addr.slen = pj_ansi_strlen(conn->addr.ptr); + m->desc.port = pj_sockaddr_get_port(&check->lcand->addr); + + /* Override address RTCP attribute if it's present */ + if (comp_cnt == 2 && + (check = pj_ice_strans_get_valid_pair(tp_ice->ice_st, + COMP_RTCP)) != NULL && + (a_rtcp = pjmedia_sdp_attr_find(m->attr_count, m->attr, + &STR_RTCP, 0)) != NULL) + { + pjmedia_sdp_attr_remove(&m->attr_count, m->attr, a_rtcp); + + a_rtcp = pjmedia_sdp_attr_create_rtcp(sdp_pool, + &check->lcand->addr); + if (a_rtcp) + pjmedia_sdp_attr_add(&m->attr_count, m->attr, a_rtcp); + } + + /* Encode only candidates matching the default destination + * for each component + */ + for (comp=0; comp < comp_cnt; ++comp) { + int len; + pj_str_t value; + + /* Get valid pair for this component */ + check = pj_ice_strans_get_valid_pair(tp_ice->ice_st, comp+1); + if (check == NULL) + continue; + + /* Print and add local candidate in the pair */ + value.ptr = attr_buf; + value.slen = print_sdp_cand_attr(attr_buf, ATTR_BUF_LEN, + check->lcand); + if (value.slen < 0) { + pj_assert(!"Not enough attr_buf to print candidate"); + return PJ_EBUG; + } + + attr = pjmedia_sdp_attr_create(sdp_pool, STR_CANDIDATE.ptr, + &value); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); + + /* Append to a=remote-candidates attribute */ + if (pj_ice_strans_get_role(tp_ice->ice_st) == + PJ_ICE_SESS_ROLE_CONTROLLING) + { + char rem_addr[PJ_INET6_ADDRSTRLEN]; + + pj_sockaddr_print(&check->rcand->addr, rem_addr, + sizeof(rem_addr), 0); + len = pj_ansi_snprintf( + rem_cand.ptr + rem_cand.slen, + RATTR_BUF_LEN - rem_cand.slen, + "%s%u %s %u", + (rem_cand.slen==0? "" : " "), + comp+1, rem_addr, + pj_sockaddr_get_port(&check->rcand->addr) + ); + if (len < 1 || len >= RATTR_BUF_LEN - rem_cand.slen) { + pj_assert(!"Not enough buffer to print " + "remote-candidates"); + return PJ_EBUG; + } + + rem_cand.slen += len; + } + } + + /* 9.1.2.2: Existing Media Streams with ICE Completed + * In addition, if the agent is controlling, it MUST include + * the a=remote-candidates attribute for each media stream + * whose check list is in the Completed state. The attribute + * contains the remote candidates from the highest priority + * nominated pair in the valid list for each component of that + * media stream. + */ + if (pj_ice_strans_get_role(tp_ice->ice_st) == + PJ_ICE_SESS_ROLE_CONTROLLING) + { + attr = pjmedia_sdp_attr_create(sdp_pool, STR_REM_CAND.ptr, + &rem_cand); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); + } } else if (pj_ice_strans_has_sess(tp_ice->ice_st) && - (restart_session || pj_ice_strans_get_state(tp_ice->ice_st) != - PJ_ICE_STRANS_STATE_FAILED)) + (restart_session || pj_ice_strans_get_state(tp_ice->ice_st) != + PJ_ICE_STRANS_STATE_FAILED)) { - /* Encode all candidates to SDP media */ - char *attr_buf; - unsigned comp; - - /* If ICE is not restarted, encode current ICE ufrag/pwd. - * Otherwise generate new one. - */ - if (!restart_session) { - attr = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_UFRAG.ptr, - &local_ufrag); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); - - attr = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_PWD.ptr, - &local_pwd); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); - - } else { - pj_str_t str; - - str.slen = PJ_ICE_UFRAG_LEN; - str.ptr = (char*) pj_pool_alloc(sdp_pool, str.slen); - pj_create_random_string(str.ptr, str.slen); - attr = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_UFRAG.ptr, &str); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); - - str.slen = PJ_ICE_PWD_LEN; - str.ptr = (char*) pj_pool_alloc(sdp_pool, str.slen); - pj_create_random_string(str.ptr, str.slen); - attr = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_PWD.ptr, &str); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); - } - - /* Create buffer to encode candidates as SDP attribute */ - attr_buf = (char*) pj_pool_alloc(sdp_pool, ATTR_BUF_LEN); - - for (comp=0; comp < comp_cnt; ++comp) { - unsigned cand_cnt; - pj_ice_sess_cand cand[PJ_ICE_ST_MAX_CAND]; - unsigned i; - - cand_cnt = PJ_ARRAY_SIZE(cand); - status = pj_ice_strans_enum_cands(tp_ice->ice_st, comp+1, - &cand_cnt, cand); - if (status != PJ_SUCCESS) - return status; - - for (i=0; iattr_count, m->attr, attr); - } - } + /* Encode all candidates to SDP media */ + char *attr_buf; + unsigned comp; + + /* If ICE is not restarted, encode current ICE ufrag/pwd. + * Otherwise generate new one. + */ + if (!restart_session) { + attr = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_UFRAG.ptr, + &local_ufrag); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); + + attr = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_PWD.ptr, + &local_pwd); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); + + } else { + pj_str_t str; + + str.slen = PJ_ICE_UFRAG_LEN; + str.ptr = (char*) pj_pool_alloc(sdp_pool, str.slen); + pj_create_random_string(str.ptr, str.slen); + attr = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_UFRAG.ptr, &str); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); + + str.slen = PJ_ICE_PWD_LEN; + str.ptr = (char*) pj_pool_alloc(sdp_pool, str.slen); + pj_create_random_string(str.ptr, str.slen); + attr = pjmedia_sdp_attr_create(sdp_pool, STR_ICE_PWD.ptr, &str); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); + } + + /* Create buffer to encode candidates as SDP attribute */ + attr_buf = (char*) pj_pool_alloc(sdp_pool, ATTR_BUF_LEN); + + for (comp=0; comp < comp_cnt; ++comp) { + unsigned cand_cnt; + pj_ice_sess_cand cand[PJ_ICE_ST_MAX_CAND]; + unsigned i; + + cand_cnt = PJ_ARRAY_SIZE(cand); + status = pj_ice_strans_enum_cands(tp_ice->ice_st, comp+1, + &cand_cnt, cand); + if (status != PJ_SUCCESS) + return status; + + for (i=0; iattr_count, m->attr, attr); + } + } } else { - /* ICE has failed, application should have terminated this call */ + /* ICE has failed, application should have terminated this call */ } /* Removing a=rtcp line when there is only one component. */ if (comp_cnt == 1) { - attr = pjmedia_sdp_attr_find(m->attr_count, m->attr, &STR_RTCP, NULL); - if (attr) - pjmedia_sdp_attr_remove(&m->attr_count, m->attr, attr); + attr = pjmedia_sdp_attr_find(m->attr_count, m->attr, &STR_RTCP, NULL); + if (attr) + pjmedia_sdp_attr_remove(&m->attr_count, m->attr, attr); /* If RTCP is not in use, we MUST send b=RS:0 and b=RR:0. */ pj_assert(m->bandw_count + 2 <= PJ_ARRAY_SIZE(m->bandw)); if (m->bandw_count + 2 <= PJ_ARRAY_SIZE(m->bandw)) { @@ -1150,33 +1149,33 @@ static pj_status_t encode_session_in_sdp(struct transport_ice *tp_ice, /* Add a=rtcp-mux attribute */ if (rtcp_mux) { - pjmedia_sdp_attr *add_attr; + pjmedia_sdp_attr *add_attr; - add_attr = PJ_POOL_ZALLOC_T(sdp_pool, pjmedia_sdp_attr); - add_attr->name = STR_RTCP_MUX; - m->attr[m->attr_count++] = add_attr; + add_attr = PJ_POOL_ZALLOC_T(sdp_pool, pjmedia_sdp_attr); + add_attr->name = STR_RTCP_MUX; + m->attr[m->attr_count++] = add_attr; } /* Add trickle ICE attributes */ if (trickle) { - pj_bool_t end_of_cand; - - /* Add media ID attribute "a=mid" */ - attr = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "mid", NULL); - if (!attr) { - attr = pjmedia_sdp_attr_create(sdp_pool, "mid", &tp_ice->sdp_mid); - pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); - } - - end_of_cand = tp_ice->end_of_cand; - status = pjmedia_ice_trickle_encode_sdp(sdp_pool, sdp_local, - &tp_ice->sdp_mid, NULL, NULL, - 0, NULL, end_of_cand); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(tp_ice->base.name, status, - "Failed in adding trickle ICE attributes")); - return status; - } + pj_bool_t end_of_cand; + + /* Add media ID attribute "a=mid" */ + attr = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "mid", NULL); + if (!attr) { + attr = pjmedia_sdp_attr_create(sdp_pool, "mid", &tp_ice->sdp_mid); + pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); + } + + end_of_cand = tp_ice->end_of_cand; + status = pjmedia_ice_trickle_encode_sdp(sdp_pool, sdp_local, + &tp_ice->sdp_mid, NULL, NULL, + 0, NULL, end_of_cand); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(tp_ice->base.name, status, + "Failed in adding trickle ICE attributes")); + return status; + } } return PJ_SUCCESS; @@ -1185,9 +1184,9 @@ static pj_status_t encode_session_in_sdp(struct transport_ice *tp_ice, /* Parse a=candidate line */ static pj_status_t parse_cand(const char *obj_name, - pj_pool_t *pool, - const pj_str_t *orig_input, - pj_ice_sess_cand *cand) + pj_pool_t *pool, + const pj_str_t *orig_input, + pj_ice_sess_cand *cand) { pj_str_t token, delim, host; int af; @@ -1202,102 +1201,102 @@ static pj_status_t parse_cand(const char *obj_name, delim = pj_str(" "); found_idx = pj_strtok(orig_input, &delim, &token, 0); if (found_idx == orig_input->slen) { - TRACE__((obj_name, "Expecting ICE foundation in candidate")); - goto on_return; + TRACE__((obj_name, "Expecting ICE foundation in candidate")); + goto on_return; } if (pool) { - pj_strdup(pool, &cand->foundation, &token); + pj_strdup(pool, &cand->foundation, &token); } else { - cand->foundation = token; + cand->foundation = token; } /* Component ID */ found_idx = pj_strtok(orig_input, &delim, &token, found_idx + token.slen); if (found_idx == orig_input->slen) { - TRACE__((obj_name, "Expecting ICE component ID in candidate")); - goto on_return; + TRACE__((obj_name, "Expecting ICE component ID in candidate")); + goto on_return; } cand->comp_id = (pj_uint8_t)pj_strtoul(&token); /* Transport */ found_idx = pj_strtok(orig_input, &delim, &token, found_idx + token.slen); if (found_idx == orig_input->slen) { - TRACE__((obj_name, "Expecting ICE transport in candidate")); - goto on_return; + TRACE__((obj_name, "Expecting ICE transport in candidate")); + goto on_return; } if (pj_stricmp2(&token, "UDP") != 0) { - TRACE__((obj_name, - "Expecting ICE UDP transport only in candidate")); - goto on_return; + TRACE__((obj_name, + "Expecting ICE UDP transport only in candidate")); + goto on_return; } /* Priority */ found_idx = pj_strtok(orig_input, &delim, &token, found_idx + token.slen); if (found_idx == orig_input->slen) { - TRACE__((obj_name, "Expecting ICE priority in candidate")); - goto on_return; + TRACE__((obj_name, "Expecting ICE priority in candidate")); + goto on_return; } cand->prio = pj_strtoul(&token); /* Host */ found_idx = pj_strtok(orig_input, &delim, &host, found_idx + token.slen); if (found_idx == orig_input->slen) { - TRACE__((obj_name, "Expecting ICE host in candidate")); - goto on_return; + TRACE__((obj_name, "Expecting ICE host in candidate")); + goto on_return; } /* Detect address family */ if (pj_strchr(&host, ':')) - af = pj_AF_INET6(); + af = pj_AF_INET6(); else - af = pj_AF_INET(); + af = pj_AF_INET(); /* Assign address */ if (pj_sockaddr_init(af, &cand->addr, &host, 0)) { - TRACE__((obj_name, "Invalid ICE candidate address")); - goto on_return; + TRACE__((obj_name, "Invalid ICE candidate address")); + goto on_return; } /* Port */ found_idx = pj_strtok(orig_input, &delim, &token, found_idx + host.slen); if (found_idx == orig_input->slen) { - TRACE__((obj_name, "Expecting ICE port number in candidate")); - goto on_return; + TRACE__((obj_name, "Expecting ICE port number in candidate")); + goto on_return; } pj_sockaddr_set_port(&cand->addr, (pj_uint16_t)pj_strtoul(&token)); /* typ */ found_idx = pj_strtok(orig_input, &delim, &token, found_idx + token.slen); if (found_idx == orig_input->slen) { - TRACE__((obj_name, "Expecting ICE \"typ\" in candidate")); - goto on_return; + TRACE__((obj_name, "Expecting ICE \"typ\" in candidate")); + goto on_return; } if (pj_stricmp2(&token, "typ") != 0) { - TRACE__((obj_name, "Expecting ICE \"typ\" in candidate")); - goto on_return; + TRACE__((obj_name, "Expecting ICE \"typ\" in candidate")); + goto on_return; } /* candidate type */ found_idx = pj_strtok(orig_input, &delim, &token, found_idx + token.slen); if (found_idx == orig_input->slen) { - TRACE__((obj_name, "Expecting ICE candidate type in candidate")); - goto on_return; + TRACE__((obj_name, "Expecting ICE candidate type in candidate")); + goto on_return; } if (pj_stricmp2(&token, "host") == 0) { - cand->type = PJ_ICE_CAND_TYPE_HOST; + cand->type = PJ_ICE_CAND_TYPE_HOST; } else if (pj_stricmp2(&token, "srflx") == 0) { - cand->type = PJ_ICE_CAND_TYPE_SRFLX; + cand->type = PJ_ICE_CAND_TYPE_SRFLX; } else if (pj_stricmp2(&token, "relay") == 0) { - cand->type = PJ_ICE_CAND_TYPE_RELAYED; + cand->type = PJ_ICE_CAND_TYPE_RELAYED; } else if (pj_stricmp2(&token, "prflx") == 0) { - cand->type = PJ_ICE_CAND_TYPE_PRFLX; + cand->type = PJ_ICE_CAND_TYPE_PRFLX; } else { - PJ_LOG(5,(obj_name, "Invalid ICE candidate type %.*s in candidate", - token.slen, token.ptr)); - goto on_return; + PJ_LOG(5,(obj_name, "Invalid ICE candidate type %.*s in candidate", + token.slen, token.ptr)); + goto on_return; } status = PJ_SUCCESS; @@ -1309,21 +1308,21 @@ static pj_status_t parse_cand(const char *obj_name, /* Create initial SDP offer */ static pj_status_t create_initial_offer(struct transport_ice *tp_ice, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *loc_sdp, - unsigned media_index) + pj_pool_t *sdp_pool, + pjmedia_sdp_session *loc_sdp, + unsigned media_index) { pj_status_t status; /* Encode ICE in SDP */ status = encode_session_in_sdp(tp_ice, sdp_pool, loc_sdp, media_index, - tp_ice->comp_cnt, PJ_FALSE, - tp_ice->enable_rtcp_mux, - tp_ice->trickle_ice != - PJ_ICE_SESS_TRICKLE_DISABLED); + tp_ice->comp_cnt, PJ_FALSE, + tp_ice->enable_rtcp_mux, + tp_ice->trickle_ice != + PJ_ICE_SESS_TRICKLE_DISABLED); if (status != PJ_SUCCESS) { - set_no_ice(tp_ice, "Error encoding SDP answer", status); - return status; + set_no_ice(tp_ice, "Error encoding SDP answer", status); + return status; } return PJ_SUCCESS; @@ -1332,11 +1331,11 @@ static pj_status_t create_initial_offer(struct transport_ice *tp_ice, /* Verify incoming offer */ static pj_status_t verify_ice_sdp(struct transport_ice *tp_ice, - pj_pool_t *tmp_pool, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index, - pj_ice_sess_role current_ice_role, - struct sdp_state *sdp_state) + pj_pool_t *tmp_pool, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index, + pj_ice_sess_role current_ice_role, + struct sdp_state *sdp_state) { const pjmedia_sdp_media *rem_m; const pjmedia_sdp_attr *ufrag_attr, *pwd_attr; @@ -1353,9 +1352,9 @@ static pj_status_t verify_ice_sdp(struct transport_ice *tp_ice, if (tp_ice->enable_rtcp_mux) { pjmedia_sdp_attr *attr; - attr = pjmedia_sdp_attr_find(rem_m->attr_count, rem_m->attr, - &STR_RTCP_MUX, NULL); - tp_ice->use_rtcp_mux = (attr? PJ_TRUE: PJ_FALSE); + attr = pjmedia_sdp_attr_find(rem_m->attr_count, rem_m->attr, + &STR_RTCP_MUX, NULL); + tp_ice->use_rtcp_mux = (attr? PJ_TRUE: PJ_FALSE); } /* Get the "ice-ufrag" and "ice-pwd" attributes */ @@ -1363,8 +1362,8 @@ static pj_status_t verify_ice_sdp(struct transport_ice *tp_ice, /* If "ice-ufrag" or "ice-pwd" are not found, disable ICE */ if (ufrag_attr==NULL || pwd_attr==NULL) { - sdp_state->match_comp_cnt = 0; - return PJ_SUCCESS; + sdp_state->match_comp_cnt = 0; + return PJ_SUCCESS; } /* Verify that default target for each component matches one of the @@ -1375,210 +1374,210 @@ static pj_status_t verify_ice_sdp(struct transport_ice *tp_ice, /* Component 1 is the c= line */ rem_conn = rem_m->conn; if (rem_conn == NULL) - rem_conn = rem_sdp->conn; + rem_conn = rem_sdp->conn; if (!rem_conn) - return PJMEDIA_SDP_EMISSINGCONN; + return PJMEDIA_SDP_EMISSINGCONN; /* Verify address family matches */ /* if ((tp_ice->af==pj_AF_INET() && - pj_strcmp(&rem_conn->addr_type, &STR_IP4)!=0) || - (tp_ice->af==pj_AF_INET6() && - pj_strcmp(&rem_conn->addr_type, &STR_IP6)!=0)) + pj_strcmp(&rem_conn->addr_type, &STR_IP4)!=0) || + (tp_ice->af==pj_AF_INET6() && + pj_strcmp(&rem_conn->addr_type, &STR_IP6)!=0)) { - return PJMEDIA_SDP_ETPORTNOTEQUAL; + return PJMEDIA_SDP_ETPORTNOTEQUAL; } */ /* Get remote address family */ if (pj_strcmp(&rem_conn->addr_type, &STR_IP4)==0) - rem_af = pj_AF_INET(); + rem_af = pj_AF_INET(); else if (pj_strcmp(&rem_conn->addr_type, &STR_IP6)==0) - rem_af = pj_AF_INET6(); + rem_af = pj_AF_INET6(); else - pj_assert(!"Unsupported address family"); + pj_assert(!"Unsupported address family"); /* Assign remote connection address */ status = pj_sockaddr_init(rem_af, &rem_conn_addr, &rem_conn->addr, - (pj_uint16_t)rem_m->desc.port); + (pj_uint16_t)rem_m->desc.port); if (status != PJ_SUCCESS) - return status; + return status; if (tp_ice->comp_cnt > 1) { - const pjmedia_sdp_attr *attr; - - /* Get default RTCP candidate from a=rtcp line, if present, otherwise - * calculate default RTCP candidate from default RTP target. - */ - attr = pjmedia_sdp_attr_find(rem_m->attr_count, rem_m->attr, - &STR_RTCP, NULL); - has_rtcp = (attr != NULL); - - if (attr) { - pjmedia_sdp_rtcp_attr rtcp_attr; - - status = pjmedia_sdp_attr_get_rtcp(attr, &rtcp_attr); - if (status != PJ_SUCCESS) { - /* Error parsing a=rtcp attribute */ - return status; - } - - if (rtcp_attr.addr.slen) { - /* Verify address family matches */ - /* - if ((tp_ice->af==pj_AF_INET() && - pj_strcmp(&rtcp_attr.addr_type, &STR_IP4)!=0) || - (tp_ice->af==pj_AF_INET6() && - pj_strcmp(&rtcp_attr.addr_type, &STR_IP6)!=0)) - { - return PJMEDIA_SDP_ETPORTNOTEQUAL; - } - */ - - /* Assign RTCP address */ - status = pj_sockaddr_init(rem_af, &rtcp_addr, - &rtcp_attr.addr, - (pj_uint16_t)rtcp_attr.port); - if (status != PJ_SUCCESS) { - return PJMEDIA_SDP_EINRTCP; - } - } else { - /* Assign RTCP address */ - status = pj_sockaddr_init(rem_af, &rtcp_addr, - NULL, - (pj_uint16_t)rtcp_attr.port); - if (status != PJ_SUCCESS) { - return PJMEDIA_SDP_EINRTCP; - } - pj_sockaddr_copy_addr(&rtcp_addr, &rem_conn_addr); - } - } else { - unsigned rtcp_port; - - rtcp_port = pj_sockaddr_get_port(&rem_conn_addr) + 1; - pj_sockaddr_cp(&rtcp_addr, &rem_conn_addr); - pj_sockaddr_set_port(&rtcp_addr, (pj_uint16_t)rtcp_port); - } + const pjmedia_sdp_attr *attr; + + /* Get default RTCP candidate from a=rtcp line, if present, otherwise + * calculate default RTCP candidate from default RTP target. + */ + attr = pjmedia_sdp_attr_find(rem_m->attr_count, rem_m->attr, + &STR_RTCP, NULL); + has_rtcp = (attr != NULL); + + if (attr) { + pjmedia_sdp_rtcp_attr rtcp_attr; + + status = pjmedia_sdp_attr_get_rtcp(attr, &rtcp_attr); + if (status != PJ_SUCCESS) { + /* Error parsing a=rtcp attribute */ + return status; + } + + if (rtcp_attr.addr.slen) { + /* Verify address family matches */ + /* + if ((tp_ice->af==pj_AF_INET() && + pj_strcmp(&rtcp_attr.addr_type, &STR_IP4)!=0) || + (tp_ice->af==pj_AF_INET6() && + pj_strcmp(&rtcp_attr.addr_type, &STR_IP6)!=0)) + { + return PJMEDIA_SDP_ETPORTNOTEQUAL; + } + */ + + /* Assign RTCP address */ + status = pj_sockaddr_init(rem_af, &rtcp_addr, + &rtcp_attr.addr, + (pj_uint16_t)rtcp_attr.port); + if (status != PJ_SUCCESS) { + return PJMEDIA_SDP_EINRTCP; + } + } else { + /* Assign RTCP address */ + status = pj_sockaddr_init(rem_af, &rtcp_addr, + NULL, + (pj_uint16_t)rtcp_attr.port); + if (status != PJ_SUCCESS) { + return PJMEDIA_SDP_EINRTCP; + } + pj_sockaddr_copy_addr(&rtcp_addr, &rem_conn_addr); + } + } else { + unsigned rtcp_port; + + rtcp_port = pj_sockaddr_get_port(&rem_conn_addr) + 1; + pj_sockaddr_cp(&rtcp_addr, &rem_conn_addr); + pj_sockaddr_set_port(&rtcp_addr, (pj_uint16_t)rtcp_port); + } } /* Find the default addresses in a=candidate attributes. */ for (i=0; iattr_count; ++i) { - pj_ice_sess_cand cand; + pj_ice_sess_cand cand; unsigned disable_ice_mismatch = tp_ice->options & PJMEDIA_ICE_DISABLE_ICE_MISMATCH; - if (pj_strcmp(&rem_m->attr[i]->name, &STR_CANDIDATE)!=0) - continue; - - status = parse_cand(tp_ice->base.name, tmp_pool, - &rem_m->attr[i]->value, &cand); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(tp_ice->base.name, status, - "Error in parsing SDP candidate attribute '%.*s', " - "candidate is ignored", - (int)rem_m->attr[i]->value.slen, - rem_m->attr[i]->value.ptr)); - continue; - } - - if (!comp1_found && cand.comp_id==COMP_RTP) - { + if (pj_strcmp(&rem_m->attr[i]->name, &STR_CANDIDATE)!=0) + continue; + + status = parse_cand(tp_ice->base.name, tmp_pool, + &rem_m->attr[i]->value, &cand); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(tp_ice->base.name, status, + "Error in parsing SDP candidate attribute '%.*s', " + "candidate is ignored", + (int)rem_m->attr[i]->value.slen, + rem_m->attr[i]->value.ptr)); + continue; + } + + if (!comp1_found && cand.comp_id==COMP_RTP) + { if ((disable_ice_mismatch) || (pj_sockaddr_cmp(&rem_conn_addr, &cand.addr) == 0)) { comp1_found = PJ_TRUE; } - } else if (!comp2_found && cand.comp_id==COMP_RTCP) - { + } else if (!comp2_found && cand.comp_id==COMP_RTCP) + { if ((disable_ice_mismatch) || (pj_sockaddr_cmp(&rtcp_addr, &cand.addr) == 0)) { comp2_found = PJ_TRUE; } - } + } - if (cand.comp_id == COMP_RTCP) - has_rtcp = PJ_TRUE; + if (cand.comp_id == COMP_RTCP) + has_rtcp = PJ_TRUE; - if (comp1_found && (comp2_found || tp_ice->comp_cnt==1)) - break; + if (comp1_found && (comp2_found || tp_ice->comp_cnt==1)) + break; } /* Check matched component count and ice_mismatch */ if (comp1_found && (tp_ice->comp_cnt==1 || !has_rtcp || tp_ice->use_rtcp_mux)) { - sdp_state->match_comp_cnt = 1; - sdp_state->ice_mismatch = PJ_FALSE; + sdp_state->match_comp_cnt = 1; + sdp_state->ice_mismatch = PJ_FALSE; } else if (comp1_found && comp2_found) { - sdp_state->match_comp_cnt = 2; - sdp_state->ice_mismatch = PJ_FALSE; + sdp_state->match_comp_cnt = 2; + sdp_state->ice_mismatch = PJ_FALSE; } else { - sdp_state->match_comp_cnt = (tp_ice->comp_cnt > 1 && has_rtcp)? 2 : 1; - sdp_state->ice_mismatch = PJ_TRUE; + sdp_state->match_comp_cnt = (tp_ice->comp_cnt > 1 && has_rtcp)? 2 : 1; + sdp_state->ice_mismatch = PJ_TRUE; } /* Detect remote restarting session */ if (pj_ice_strans_has_sess(tp_ice->ice_st) && - (pj_ice_strans_sess_is_running(tp_ice->ice_st) || - pj_ice_strans_sess_is_complete(tp_ice->ice_st))) + (pj_ice_strans_sess_is_running(tp_ice->ice_st) || + pj_ice_strans_sess_is_complete(tp_ice->ice_st))) { - pj_str_t rem_run_ufrag, rem_run_pwd; - pj_ice_strans_get_ufrag_pwd(tp_ice->ice_st, NULL, NULL, - &rem_run_ufrag, &rem_run_pwd); - if (pj_strcmp(&ufrag_attr->value, &rem_run_ufrag) || - pj_strcmp(&pwd_attr->value, &rem_run_pwd)) - { - /* Remote offers to restart ICE */ - sdp_state->ice_restart = PJ_TRUE; - } else { - sdp_state->ice_restart = PJ_FALSE; - } + pj_str_t rem_run_ufrag, rem_run_pwd; + pj_ice_strans_get_ufrag_pwd(tp_ice->ice_st, NULL, NULL, + &rem_run_ufrag, &rem_run_pwd); + if (pj_strcmp(&ufrag_attr->value, &rem_run_ufrag) || + pj_strcmp(&pwd_attr->value, &rem_run_pwd)) + { + /* Remote offers to restart ICE */ + sdp_state->ice_restart = PJ_TRUE; + } else { + sdp_state->ice_restart = PJ_FALSE; + } } else { - sdp_state->ice_restart = PJ_FALSE; + sdp_state->ice_restart = PJ_FALSE; } /* Detect our role */ if (pjmedia_sdp_attr_find(rem_sdp->attr_count, rem_sdp->attr, - &STR_ICE_LITE, NULL) != NULL) + &STR_ICE_LITE, NULL) != NULL) { - /* Remote is ICE lite, set our role as controlling */ - sdp_state->local_role = PJ_ICE_SESS_ROLE_CONTROLLING; + /* Remote is ICE lite, set our role as controlling */ + sdp_state->local_role = PJ_ICE_SESS_ROLE_CONTROLLING; } else { - if (current_ice_role==PJ_ICE_SESS_ROLE_CONTROLLING) { - sdp_state->local_role = PJ_ICE_SESS_ROLE_CONTROLLING; - } else { - sdp_state->local_role = PJ_ICE_SESS_ROLE_CONTROLLED; - } + if (current_ice_role==PJ_ICE_SESS_ROLE_CONTROLLING) { + sdp_state->local_role = PJ_ICE_SESS_ROLE_CONTROLLING; + } else { + sdp_state->local_role = PJ_ICE_SESS_ROLE_CONTROLLED; + } } /* Check trickle ICE indication */ if (tp_ice->trickle_ice != PJ_ICE_SESS_TRICKLE_DISABLED) { - sdp_state->has_trickle = pjmedia_ice_sdp_has_trickle(rem_sdp, - media_index); - - /* Reset ICE mismatch flag if conn addr is default address */ - if (sdp_state->ice_mismatch && sdp_state->has_trickle) { - pj_sockaddr def_addr; - pj_sockaddr_init(rem_af, &def_addr, NULL, 9); - if (pj_sockaddr_cmp(&rem_conn_addr, &def_addr)==0) - sdp_state->ice_mismatch = PJ_FALSE; - } + sdp_state->has_trickle = pjmedia_ice_sdp_has_trickle(rem_sdp, + media_index); + + /* Reset ICE mismatch flag if conn addr is default address */ + if (sdp_state->ice_mismatch && sdp_state->has_trickle) { + pj_sockaddr def_addr; + pj_sockaddr_init(rem_af, &def_addr, NULL, 9); + if (pj_sockaddr_cmp(&rem_conn_addr, &def_addr)==0) + sdp_state->ice_mismatch = PJ_FALSE; + } } else { - sdp_state->has_trickle = PJ_FALSE; + sdp_state->has_trickle = PJ_FALSE; } PJ_LOG(4,(tp_ice->base.name, - "Processing SDP: support ICE=%u, common comp_cnt=%u, " - "ice_mismatch=%u, ice_restart=%u, local_role=%s, trickle=%u", - (sdp_state->match_comp_cnt != 0), - sdp_state->match_comp_cnt, - sdp_state->ice_mismatch, - sdp_state->ice_restart, - pj_ice_sess_role_name(sdp_state->local_role), - sdp_state->has_trickle)); + "Processing SDP: support ICE=%u, common comp_cnt=%u, " + "ice_mismatch=%u, ice_restart=%u, local_role=%s, trickle=%u", + (sdp_state->match_comp_cnt != 0), + sdp_state->match_comp_cnt, + sdp_state->ice_mismatch, + sdp_state->ice_restart, + pj_ice_sess_role_name(sdp_state->local_role), + sdp_state->has_trickle)); return PJ_SUCCESS; @@ -1586,24 +1585,24 @@ static pj_status_t verify_ice_sdp(struct transport_ice *tp_ice, /* Encode information in SDP if ICE is not used */ static pj_status_t encode_no_ice_in_sdp( struct transport_ice *tp_ice, - pj_pool_t *pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { if (tp_ice->enable_rtcp_mux) { pjmedia_sdp_media *m = sdp_local->media[media_index]; pjmedia_sdp_attr *attr; pj_bool_t add_rtcp_mux = PJ_TRUE; - if (rem_sdp) - add_rtcp_mux = tp_ice->use_rtcp_mux; - else { - /* For subsequent offer, set it to false first since - * we are still waiting for remote answer. - */ - tp_ice->use_rtcp_mux = PJ_FALSE; - } + if (rem_sdp) + add_rtcp_mux = tp_ice->use_rtcp_mux; + else { + /* For subsequent offer, set it to false first since + * we are still waiting for remote answer. + */ + tp_ice->use_rtcp_mux = PJ_FALSE; + } /* Remove RTCP attribute because for subsequent offers/answers, * the address (obtained from transport_get_info() ) may be @@ -1612,28 +1611,28 @@ static pj_status_t encode_no_ice_in_sdp( struct transport_ice *tp_ice, * if remote rejects it. */ pjmedia_sdp_attr_remove_all(&m->attr_count, m->attr, "rtcp"); - - if (!tp_ice->use_rtcp_mux && tp_ice->comp_cnt > 1) { - pj_ice_sess_cand cand; - pj_status_t status; - - status = pj_ice_strans_get_def_cand(tp_ice->ice_st, 2, &cand); - if (status == PJ_SUCCESS) { - /* Add RTCP attribute if the remote doesn't offer or - * rejects it. - */ - attr = pjmedia_sdp_attr_create_rtcp(pool, &cand.addr); - if (attr) - pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); - } - } - - /* Add a=rtcp-mux attribute. */ - if (add_rtcp_mux) { - attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); - attr->name = STR_RTCP_MUX; - m->attr[m->attr_count++] = attr; - } + + if (!tp_ice->use_rtcp_mux && tp_ice->comp_cnt > 1) { + pj_ice_sess_cand cand; + pj_status_t status; + + status = pj_ice_strans_get_def_cand(tp_ice->ice_st, 2, &cand); + if (status == PJ_SUCCESS) { + /* Add RTCP attribute if the remote doesn't offer or + * rejects it. + */ + attr = pjmedia_sdp_attr_create_rtcp(pool, &cand.addr); + if (attr) + pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); + } + } + + /* Add a=rtcp-mux attribute. */ + if (add_rtcp_mux) { + attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); + attr->name = STR_RTCP_MUX; + m->attr[m->attr_count++] = attr; + } } return PJ_SUCCESS; } @@ -1641,10 +1640,10 @@ static pj_status_t encode_no_ice_in_sdp( struct transport_ice *tp_ice, /* Verify incoming offer and create initial answer */ static pj_status_t create_initial_answer(struct transport_ice *tp_ice, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *loc_sdp, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *sdp_pool, + pjmedia_sdp_session *loc_sdp, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { const pjmedia_sdp_media *rem_m = rem_sdp->media[media_index]; pj_bool_t with_trickle; @@ -1652,43 +1651,43 @@ static pj_status_t create_initial_answer(struct transport_ice *tp_ice, /* Check if media is removed (just in case) */ if (rem_m->desc.port == 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Verify the offer */ status = verify_ice_sdp(tp_ice, sdp_pool, rem_sdp, media_index, - PJ_ICE_SESS_ROLE_CONTROLLED, - &tp_ice->rem_offer_state); + PJ_ICE_SESS_ROLE_CONTROLLED, + &tp_ice->rem_offer_state); if (status != PJ_SUCCESS) { - set_no_ice(tp_ice, "Invalid SDP offer", status); - return status; + set_no_ice(tp_ice, "Invalid SDP offer", status); + return status; } /* Does remote support ICE? */ if (tp_ice->rem_offer_state.match_comp_cnt==0) { - set_no_ice(tp_ice, "No ICE found in SDP offer", PJ_SUCCESS); - encode_no_ice_in_sdp(tp_ice, sdp_pool, loc_sdp, rem_sdp, - media_index); - return PJ_SUCCESS; + set_no_ice(tp_ice, "No ICE found in SDP offer", PJ_SUCCESS); + encode_no_ice_in_sdp(tp_ice, sdp_pool, loc_sdp, rem_sdp, + media_index); + return PJ_SUCCESS; } /* ICE ice_mismatch? */ if (tp_ice->rem_offer_state.ice_mismatch) { - set_no_ice(tp_ice, "ICE ice_mismatch in remote offer", PJ_SUCCESS); - encode_ice_mismatch(sdp_pool, loc_sdp, media_index); - return PJ_SUCCESS; + set_no_ice(tp_ice, "ICE ice_mismatch in remote offer", PJ_SUCCESS); + encode_ice_mismatch(sdp_pool, loc_sdp, media_index); + return PJ_SUCCESS; } /* Encode ICE in SDP */ with_trickle = tp_ice->rem_offer_state.has_trickle && - tp_ice->trickle_ice != PJ_ICE_SESS_TRICKLE_DISABLED; + tp_ice->trickle_ice != PJ_ICE_SESS_TRICKLE_DISABLED; status = encode_session_in_sdp(tp_ice, sdp_pool, loc_sdp, media_index, - tp_ice->rem_offer_state.match_comp_cnt, - PJ_FALSE, tp_ice->use_rtcp_mux, - with_trickle); + tp_ice->rem_offer_state.match_comp_cnt, + PJ_FALSE, tp_ice->use_rtcp_mux, + with_trickle); if (status != PJ_SUCCESS) { - set_no_ice(tp_ice, "Error encoding SDP answer", status); - return status; + set_no_ice(tp_ice, "Error encoding SDP answer", status); + return status; } return PJ_SUCCESS; @@ -1697,110 +1696,110 @@ static pj_status_t create_initial_answer(struct transport_ice *tp_ice, /* Create subsequent SDP offer */ static pj_status_t create_subsequent_offer(struct transport_ice *tp_ice, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *loc_sdp, - unsigned media_index) + pj_pool_t *sdp_pool, + pjmedia_sdp_session *loc_sdp, + unsigned media_index) { unsigned comp_cnt; if (pj_ice_strans_has_sess(tp_ice->ice_st) == PJ_FALSE) { - /* We don't have ICE */ - encode_no_ice_in_sdp(tp_ice, sdp_pool, loc_sdp, NULL, media_index); - return PJ_SUCCESS; + /* We don't have ICE */ + encode_no_ice_in_sdp(tp_ice, sdp_pool, loc_sdp, NULL, media_index); + return PJ_SUCCESS; } comp_cnt = pj_ice_strans_get_running_comp_cnt(tp_ice->ice_st); return encode_session_in_sdp(tp_ice, sdp_pool, loc_sdp, media_index, - comp_cnt, PJ_FALSE, tp_ice->enable_rtcp_mux, - PJ_FALSE); + comp_cnt, PJ_FALSE, tp_ice->enable_rtcp_mux, + PJ_FALSE); } /* Create subsequent SDP answer */ static pj_status_t create_subsequent_answer(struct transport_ice *tp_ice, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *loc_sdp, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *sdp_pool, + pjmedia_sdp_session *loc_sdp, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { pj_status_t status; /* We have a session */ status = verify_ice_sdp(tp_ice, sdp_pool, rem_sdp, media_index, - PJ_ICE_SESS_ROLE_CONTROLLED, - &tp_ice->rem_offer_state); + PJ_ICE_SESS_ROLE_CONTROLLED, + &tp_ice->rem_offer_state); if (status != PJ_SUCCESS) { - /* Something wrong with the offer */ - return status; + /* Something wrong with the offer */ + return status; } if (pj_ice_strans_has_sess(tp_ice->ice_st)) { - /* - * Received subsequent offer while we have ICE active. - */ - - if (tp_ice->rem_offer_state.match_comp_cnt == 0) { - /* Remote no longer offers ICE */ - encode_no_ice_in_sdp(tp_ice, sdp_pool, loc_sdp, rem_sdp, - media_index); - return PJ_SUCCESS; - } - - if (tp_ice->rem_offer_state.ice_mismatch) { - encode_ice_mismatch(sdp_pool, loc_sdp, media_index); - return PJ_SUCCESS; - } - - status = encode_session_in_sdp(tp_ice, sdp_pool, loc_sdp, media_index, - tp_ice->rem_offer_state.match_comp_cnt, - tp_ice->rem_offer_state.ice_restart, - tp_ice->use_rtcp_mux, PJ_FALSE); - if (status != PJ_SUCCESS) - return status; - - /* Done */ + /* + * Received subsequent offer while we have ICE active. + */ + + if (tp_ice->rem_offer_state.match_comp_cnt == 0) { + /* Remote no longer offers ICE */ + encode_no_ice_in_sdp(tp_ice, sdp_pool, loc_sdp, rem_sdp, + media_index); + return PJ_SUCCESS; + } + + if (tp_ice->rem_offer_state.ice_mismatch) { + encode_ice_mismatch(sdp_pool, loc_sdp, media_index); + return PJ_SUCCESS; + } + + status = encode_session_in_sdp(tp_ice, sdp_pool, loc_sdp, media_index, + tp_ice->rem_offer_state.match_comp_cnt, + tp_ice->rem_offer_state.ice_restart, + tp_ice->use_rtcp_mux, PJ_FALSE); + if (status != PJ_SUCCESS) + return status; + + /* Done */ } else { - pj_bool_t with_trickle; - - /* - * Received subsequent offer while we DON'T have ICE active. - */ - - if (tp_ice->rem_offer_state.match_comp_cnt == 0) { - /* Remote does not support ICE */ - encode_no_ice_in_sdp(tp_ice, sdp_pool, loc_sdp, rem_sdp, - media_index); - return PJ_SUCCESS; - } - - if (tp_ice->rem_offer_state.ice_mismatch) { - encode_ice_mismatch(sdp_pool, loc_sdp, media_index); - return PJ_SUCCESS; - } - - /* Looks like now remote is offering ICE, so we need to create - * ICE session now. - */ - status = pj_ice_strans_init_ice(tp_ice->ice_st, - PJ_ICE_SESS_ROLE_CONTROLLED, - NULL, NULL); - if (status != PJ_SUCCESS) { - /* Fail to create new ICE session */ - return status; - } - - with_trickle = tp_ice->rem_offer_state.has_trickle && - tp_ice->trickle_ice != PJ_ICE_SESS_TRICKLE_DISABLED; - status = encode_session_in_sdp(tp_ice, sdp_pool, loc_sdp, media_index, - tp_ice->rem_offer_state.match_comp_cnt, - tp_ice->rem_offer_state.ice_restart, - tp_ice->use_rtcp_mux, - with_trickle); - if (status != PJ_SUCCESS) - return status; - - /* Done */ + pj_bool_t with_trickle; + + /* + * Received subsequent offer while we DON'T have ICE active. + */ + + if (tp_ice->rem_offer_state.match_comp_cnt == 0) { + /* Remote does not support ICE */ + encode_no_ice_in_sdp(tp_ice, sdp_pool, loc_sdp, rem_sdp, + media_index); + return PJ_SUCCESS; + } + + if (tp_ice->rem_offer_state.ice_mismatch) { + encode_ice_mismatch(sdp_pool, loc_sdp, media_index); + return PJ_SUCCESS; + } + + /* Looks like now remote is offering ICE, so we need to create + * ICE session now. + */ + status = pj_ice_strans_init_ice(tp_ice->ice_st, + PJ_ICE_SESS_ROLE_CONTROLLED, + NULL, NULL); + if (status != PJ_SUCCESS) { + /* Fail to create new ICE session */ + return status; + } + + with_trickle = tp_ice->rem_offer_state.has_trickle && + tp_ice->trickle_ice != PJ_ICE_SESS_TRICKLE_DISABLED; + status = encode_session_in_sdp(tp_ice, sdp_pool, loc_sdp, media_index, + tp_ice->rem_offer_state.match_comp_cnt, + tp_ice->rem_offer_state.ice_restart, + tp_ice->use_rtcp_mux, + with_trickle); + if (status != PJ_SUCCESS) + return status; + + /* Done */ } return PJ_SUCCESS; @@ -1812,10 +1811,10 @@ static pj_status_t create_subsequent_answer(struct transport_ice *tp_ice, * This will add ICE attributes to the SDP. */ static pj_status_t transport_media_create(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - unsigned options, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *sdp_pool, + unsigned options, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { struct transport_ice *tp_ice = (struct transport_ice*)tp; pj_ice_sess_role ice_role; @@ -1834,66 +1833,66 @@ static pj_status_t transport_media_create(pjmedia_transport *tp, */ tp_ice->sdp_mid.slen = 0; if (rem_sdp) { - pjmedia_sdp_media *m = rem_sdp->media[media_index]; - pjmedia_sdp_attr *a; - a = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "mid", NULL); - if (a) { - pj_strdup(tp_ice->pool, &tp_ice->sdp_mid, &a->value); - } + pjmedia_sdp_media *m = rem_sdp->media[media_index]; + pjmedia_sdp_attr *a; + a = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "mid", NULL); + if (a) { + pj_strdup(tp_ice->pool, &tp_ice->sdp_mid, &a->value); + } } if (tp_ice->sdp_mid.slen == 0) { - char tmp_buf[8]; - pj_ansi_snprintf(tmp_buf, sizeof(tmp_buf), "%d", media_index+1); - tp_ice->sdp_mid = pj_strdup3(tp_ice->pool, tmp_buf); + char tmp_buf[8]; + pj_ansi_snprintf(tmp_buf, sizeof(tmp_buf), "%d", media_index+1); + tp_ice->sdp_mid = pj_strdup3(tp_ice->pool, tmp_buf); } /* If RTCP mux is being used, set component count to 1 */ if (rem_sdp && tp_ice->enable_rtcp_mux) { - pjmedia_sdp_media *rem_m = rem_sdp->media[media_index]; + pjmedia_sdp_media *rem_m = rem_sdp->media[media_index]; pjmedia_sdp_attr *attr; - attr = pjmedia_sdp_attr_find(rem_m->attr_count, rem_m->attr, - &STR_RTCP_MUX, NULL); - tp_ice->use_rtcp_mux = (attr? PJ_TRUE: PJ_FALSE); + attr = pjmedia_sdp_attr_find(rem_m->attr_count, rem_m->attr, + &STR_RTCP_MUX, NULL); + tp_ice->use_rtcp_mux = (attr? PJ_TRUE: PJ_FALSE); } if (tp_ice->use_rtcp_mux && - pj_ice_strans_get_running_comp_cnt(tp_ice->ice_st)>1) + pj_ice_strans_get_running_comp_cnt(tp_ice->ice_st)>1) { - pj_ice_strans_update_comp_cnt(tp_ice->ice_st, 1); + pj_ice_strans_update_comp_cnt(tp_ice->ice_st, 1); } /* Init ICE, the initial role is set now based on availability of * rem_sdp, but it will be checked again later. */ ice_role = (rem_sdp==NULL ? PJ_ICE_SESS_ROLE_CONTROLLING : - PJ_ICE_SESS_ROLE_CONTROLLED); + PJ_ICE_SESS_ROLE_CONTROLLED); status = pj_ice_strans_init_ice(tp_ice->ice_st, ice_role, NULL, NULL); /* For trickle ICE, if remote SDP has been received, process any remote * ICE info now (ICE user fragment and/or initial ICE candidate list). */ if (rem_sdp && status == PJ_SUCCESS) { - if (tp_ice->trickle_ice != PJ_ICE_SESS_TRICKLE_DISABLED && - pjmedia_ice_sdp_has_trickle(rem_sdp, media_index)) - { - pj_str_t ufrag, pwd; - unsigned cand_cnt = PJ_ICE_ST_MAX_CAND; - pj_ice_sess_cand cand[PJ_ICE_ST_MAX_CAND]; - pj_bool_t end_of_cand; - - status = pjmedia_ice_trickle_decode_sdp(rem_sdp, media_index, - NULL, &ufrag, &pwd, - &cand_cnt, cand, - &end_of_cand); - if (status == PJ_SUCCESS) - status = pj_ice_strans_update_check_list( - tp_ice->ice_st, &ufrag, &pwd, - cand_cnt, cand, end_of_cand); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(tp_ice->base.name, status, - "Failed create checklist for trickling ICE")); - return status; - } - } + if (tp_ice->trickle_ice != PJ_ICE_SESS_TRICKLE_DISABLED && + pjmedia_ice_sdp_has_trickle(rem_sdp, media_index)) + { + pj_str_t ufrag, pwd; + unsigned cand_cnt = PJ_ICE_ST_MAX_CAND; + pj_ice_sess_cand cand[PJ_ICE_ST_MAX_CAND]; + pj_bool_t end_of_cand; + + status = pjmedia_ice_trickle_decode_sdp(rem_sdp, media_index, + NULL, &ufrag, &pwd, + &cand_cnt, cand, + &end_of_cand); + if (status == PJ_SUCCESS) + status = pj_ice_strans_update_check_list( + tp_ice->ice_st, &ufrag, &pwd, + cand_cnt, cand, end_of_cand); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(tp_ice->base.name, status, + "Failed create checklist for trickling ICE")); + return status; + } + } } /* Done */ @@ -1902,10 +1901,10 @@ static pj_status_t transport_media_create(pjmedia_transport *tp, static pj_status_t transport_encode_sdp(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { struct transport_ice *tp_ice = (struct transport_ice*)tp; pj_status_t status; @@ -1915,61 +1914,61 @@ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, * transport checking is disabled */ if ((tp_ice->media_option & PJMEDIA_TPMED_NO_TRANSPORT_CHECKING) == 0) { - pjmedia_sdp_media *m_rem, *m_loc; - pj_uint32_t tp_proto_loc, tp_proto_rem; - - m_rem = rem_sdp? rem_sdp->media[media_index] : NULL; - m_loc = sdp_local->media[media_index]; - - tp_proto_loc = pjmedia_sdp_transport_get_proto(&m_loc->desc.transport); - tp_proto_rem = m_rem? - pjmedia_sdp_transport_get_proto(&m_rem->desc.transport) : 0; - PJMEDIA_TP_PROTO_TRIM_FLAG(tp_proto_loc, PJMEDIA_TP_PROFILE_RTCP_FB); - PJMEDIA_TP_PROTO_TRIM_FLAG(tp_proto_rem, PJMEDIA_TP_PROFILE_RTCP_FB); - - if ((tp_proto_loc != PJMEDIA_TP_PROTO_RTP_AVP) || - (m_rem && tp_proto_rem != PJMEDIA_TP_PROTO_RTP_AVP)) - { - pjmedia_sdp_media_deactivate(sdp_pool, m_loc); - return PJMEDIA_SDP_EINPROTO; - } + pjmedia_sdp_media *m_rem, *m_loc; + pj_uint32_t tp_proto_loc, tp_proto_rem; + + m_rem = rem_sdp? rem_sdp->media[media_index] : NULL; + m_loc = sdp_local->media[media_index]; + + tp_proto_loc = pjmedia_sdp_transport_get_proto(&m_loc->desc.transport); + tp_proto_rem = m_rem? + pjmedia_sdp_transport_get_proto(&m_rem->desc.transport) : 0; + PJMEDIA_TP_PROTO_TRIM_FLAG(tp_proto_loc, PJMEDIA_TP_PROFILE_RTCP_FB); + PJMEDIA_TP_PROTO_TRIM_FLAG(tp_proto_rem, PJMEDIA_TP_PROFILE_RTCP_FB); + + if ((tp_proto_loc != PJMEDIA_TP_PROTO_RTP_AVP) || + (m_rem && tp_proto_rem != PJMEDIA_TP_PROTO_RTP_AVP)) + { + pjmedia_sdp_media_deactivate(sdp_pool, m_loc); + return PJMEDIA_SDP_EINPROTO; + } } if (tp_ice->initial_sdp) { - if (rem_sdp) { - status = create_initial_answer(tp_ice, sdp_pool, sdp_local, - rem_sdp, media_index); - } else { - status = create_initial_offer(tp_ice, sdp_pool, sdp_local, - media_index); - } + if (rem_sdp) { + status = create_initial_answer(tp_ice, sdp_pool, sdp_local, + rem_sdp, media_index); + } else { + status = create_initial_offer(tp_ice, sdp_pool, sdp_local, + media_index); + } } else { - if (rem_sdp) { - status = create_subsequent_answer(tp_ice, sdp_pool, sdp_local, - rem_sdp, media_index); - } else { - status = create_subsequent_offer(tp_ice, sdp_pool, sdp_local, - media_index); - } + if (rem_sdp) { + status = create_subsequent_answer(tp_ice, sdp_pool, sdp_local, + rem_sdp, media_index); + } else { + status = create_subsequent_offer(tp_ice, sdp_pool, sdp_local, + media_index); + } } if (status==PJ_SUCCESS) { - if (rem_sdp) - tp_ice->oa_role = ROLE_ANSWERER; - else - tp_ice->oa_role = ROLE_OFFERER; - - if (tp_ice->use_ice) { - /* Update last local candidate count, so trickle ICE can identify - * if there is any new local candidate. - */ - unsigned i, comp_cnt; - comp_cnt = pj_ice_strans_get_running_comp_cnt(tp_ice->ice_st); - for (i = 0; i < comp_cnt; ++i) { - tp_ice->last_send_cand_cnt[i] = - pj_ice_strans_get_cands_count(tp_ice->ice_st, i+1); - } - } + if (rem_sdp) + tp_ice->oa_role = ROLE_ANSWERER; + else + tp_ice->oa_role = ROLE_OFFERER; + + if (tp_ice->use_ice) { + /* Update last local candidate count, so trickle ICE can identify + * if there is any new local candidate. + */ + unsigned i, comp_cnt; + comp_cnt = pj_ice_strans_get_running_comp_cnt(tp_ice->ice_st); + for (i = 0; i < comp_cnt; ++i) { + tp_ice->last_send_cand_cnt[i] = + pj_ice_strans_get_cands_count(tp_ice->ice_st, i+1); + } + } } return status; @@ -1978,9 +1977,9 @@ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, /* Start ICE session with the specified remote SDP */ static pj_status_t start_ice(struct transport_ice *tp_ice, - pj_pool_t *tmp_pool, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *tmp_pool, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { pjmedia_sdp_media *rem_m = rem_sdp->media[media_index]; const pjmedia_sdp_attr *ufrag_attr, *pwd_attr; @@ -1992,37 +1991,37 @@ static pj_status_t start_ice(struct transport_ice *tp_ice, /* Allocate candidate array */ cand = (pj_ice_sess_cand*) - pj_pool_calloc(tmp_pool, PJ_ICE_MAX_CAND, - sizeof(pj_ice_sess_cand)); + pj_pool_calloc(tmp_pool, PJ_ICE_MAX_CAND, + sizeof(pj_ice_sess_cand)); /* Get all candidates in the media */ cand_cnt = 0; for (i=0; iattr_count && cand_cnt < PJ_ICE_MAX_CAND; ++i) { - pjmedia_sdp_attr *attr; + pjmedia_sdp_attr *attr; - attr = rem_m->attr[i]; + attr = rem_m->attr[i]; - if (pj_strcmp(&attr->name, &STR_CANDIDATE)!=0) - continue; + if (pj_strcmp(&attr->name, &STR_CANDIDATE)!=0) + continue; - /* Parse candidate */ - status = parse_cand(tp_ice->base.name, tmp_pool, &attr->value, - &cand[cand_cnt]); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(tp_ice->base.name, status, - "Error in parsing SDP candidate attribute '%.*s', " - "candidate is ignored", - (int)attr->value.slen, attr->value.ptr)); - continue; - } + /* Parse candidate */ + status = parse_cand(tp_ice->base.name, tmp_pool, &attr->value, + &cand[cand_cnt]); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(tp_ice->base.name, status, + "Error in parsing SDP candidate attribute '%.*s', " + "candidate is ignored", + (int)attr->value.slen, attr->value.ptr)); + continue; + } - if (!tp_ice->use_rtcp_mux || cand[cand_cnt].comp_id < 2) - cand_cnt++; + if (!tp_ice->use_rtcp_mux || cand[cand_cnt].comp_id < 2) + cand_cnt++; } /* Start ICE */ return pj_ice_strans_start_ice(tp_ice->ice_st, &ufrag_attr->value, - &pwd_attr->value, cand_cnt, cand); + &pwd_attr->value, cand_cnt, cand); } @@ -2031,10 +2030,10 @@ static pj_status_t start_ice(struct transport_ice *tp_ice, * by SDP negotiator. */ static pj_status_t transport_media_start(pjmedia_transport *tp, - pj_pool_t *tmp_pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *tmp_pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { struct transport_ice *tp_ice = (struct transport_ice*)tp; pjmedia_sdp_media *rem_m; @@ -2056,7 +2055,7 @@ static pj_status_t transport_media_start(pjmedia_transport *tp, /* Nothing to do if we don't have ICE session */ if (pj_ice_strans_has_sess(tp_ice->ice_st) == PJ_FALSE) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Special case for Session Timer. The re-INVITE for session refresh @@ -2064,148 +2063,148 @@ static pj_status_t transport_media_start(pjmedia_transport *tp, * be set to ROLE_NONE. This is a workaround. */ if (current_oa_role == ROLE_NONE) { - current_oa_role = ROLE_OFFERER; + current_oa_role = ROLE_OFFERER; } /* Processing depends on the offer/answer role */ if (current_oa_role == ROLE_OFFERER) { - /* - * We are offerer. So this will be the first time we see the - * remote's SDP. - */ - struct sdp_state answer_state; - - /* Verify the answer */ - status = verify_ice_sdp(tp_ice, tmp_pool, rem_sdp, media_index, - PJ_ICE_SESS_ROLE_CONTROLLING, &answer_state); - if (status != PJ_SUCCESS) { - /* Something wrong in the SDP answer */ - set_no_ice(tp_ice, "Invalid remote SDP answer", status); - return status; - } - - /* Does it have ICE? */ - if (answer_state.match_comp_cnt == 0) { - /* Remote doesn't support ICE */ - set_no_ice(tp_ice, "Remote answer doesn't support ICE", - PJ_SUCCESS); - return PJ_SUCCESS; - } - - /* Check if remote has reported ice-mismatch */ - if (pjmedia_sdp_attr_find(rem_m->attr_count, rem_m->attr, - &STR_ICE_MISMATCH, NULL) != NULL) - { - /* Remote has reported ice-mismatch */ - set_no_ice(tp_ice, - "Remote answer contains 'ice-mismatch' attribute", - PJ_SUCCESS); - return PJ_SUCCESS; - } - - /* Check if remote has indicated a restart */ - if (answer_state.ice_restart) { - PJ_LOG(2,(tp_ice->base.name, - "Warning: remote has signalled ICE restart in SDP " - "answer which is disallowed. Remote ICE negotiation" - " may fail.")); - } - - /* Check if the answer itself is mismatched */ - if (answer_state.ice_mismatch) { - /* This happens either when a B2BUA modified remote answer but - * strangely didn't modify our offer, or remote is not capable - * of detecting mismatch in our offer (it didn't put - * 'ice-mismatch' attribute in the answer). - */ - PJ_LOG(2,(tp_ice->base.name, - "Warning: remote answer mismatch, but it does not " - "reject our offer with 'ice-mismatch'. ICE negotiation " - "may fail")); - } - - /* Do nothing if ICE is complete or running */ - if (pj_ice_strans_sess_is_running(tp_ice->ice_st)) { - PJ_LOG(4,(tp_ice->base.name, - "Ignored offer/answer because ICE is running")); - return PJ_SUCCESS; - } - - if (pj_ice_strans_sess_is_complete(tp_ice->ice_st)) { - PJ_LOG(4,(tp_ice->base.name, "ICE session unchanged")); - return PJ_SUCCESS; - } - - /* Start ICE */ + /* + * We are offerer. So this will be the first time we see the + * remote's SDP. + */ + struct sdp_state answer_state; + + /* Verify the answer */ + status = verify_ice_sdp(tp_ice, tmp_pool, rem_sdp, media_index, + PJ_ICE_SESS_ROLE_CONTROLLING, &answer_state); + if (status != PJ_SUCCESS) { + /* Something wrong in the SDP answer */ + set_no_ice(tp_ice, "Invalid remote SDP answer", status); + return status; + } + + /* Does it have ICE? */ + if (answer_state.match_comp_cnt == 0) { + /* Remote doesn't support ICE */ + set_no_ice(tp_ice, "Remote answer doesn't support ICE", + PJ_SUCCESS); + return PJ_SUCCESS; + } + + /* Check if remote has reported ice-mismatch */ + if (pjmedia_sdp_attr_find(rem_m->attr_count, rem_m->attr, + &STR_ICE_MISMATCH, NULL) != NULL) + { + /* Remote has reported ice-mismatch */ + set_no_ice(tp_ice, + "Remote answer contains 'ice-mismatch' attribute", + PJ_SUCCESS); + return PJ_SUCCESS; + } + + /* Check if remote has indicated a restart */ + if (answer_state.ice_restart) { + PJ_LOG(2,(tp_ice->base.name, + "Warning: remote has signalled ICE restart in SDP " + "answer which is disallowed. Remote ICE negotiation" + " may fail.")); + } + + /* Check if the answer itself is mismatched */ + if (answer_state.ice_mismatch) { + /* This happens either when a B2BUA modified remote answer but + * strangely didn't modify our offer, or remote is not capable + * of detecting mismatch in our offer (it didn't put + * 'ice-mismatch' attribute in the answer). + */ + PJ_LOG(2,(tp_ice->base.name, + "Warning: remote answer mismatch, but it does not " + "reject our offer with 'ice-mismatch'. ICE negotiation " + "may fail")); + } + + /* Do nothing if ICE is complete or running */ + if (pj_ice_strans_sess_is_running(tp_ice->ice_st)) { + PJ_LOG(4,(tp_ice->base.name, + "Ignored offer/answer because ICE is running")); + return PJ_SUCCESS; + } + + if (pj_ice_strans_sess_is_complete(tp_ice->ice_st)) { + PJ_LOG(4,(tp_ice->base.name, "ICE session unchanged")); + return PJ_SUCCESS; + } + + /* Start ICE */ } else { - /* - * We are answerer. We've seen and negotiated remote's SDP - * before, and the result is in "rem_offer_state". - */ - const pjmedia_sdp_attr *ufrag_attr, *pwd_attr; - - /* Check for ICE in remote offer */ - if (tp_ice->rem_offer_state.match_comp_cnt == 0) { - /* No ICE attribute present */ - set_no_ice(tp_ice, "Remote no longer offers ICE", - PJ_SUCCESS); - return PJ_SUCCESS; - } - - /* Check for ICE ice_mismatch condition in the offer */ - if (tp_ice->rem_offer_state.ice_mismatch) { - set_no_ice(tp_ice, "Remote offer mismatch: ", - PJNATH_EICEMISMATCH); - return PJ_SUCCESS; - } - - /* If ICE is complete and remote doesn't request restart, - * then leave the session as is. - */ - if (!initial_oa && tp_ice->rem_offer_state.ice_restart == PJ_FALSE) { - /* Remote has not requested ICE restart, so session is - * unchanged. - */ - PJ_LOG(4,(tp_ice->base.name, "ICE session unchanged")); - return PJ_SUCCESS; - } - - /* Either remote has requested ICE restart or this is our - * first answer. - */ - - /* Stop ICE */ - if (!initial_oa) { - set_no_ice(tp_ice, "restarting by remote request..", PJ_SUCCESS); - - /* We have put new ICE ufrag and pwd in the answer. Now - * create a new ICE session with that ufrag/pwd pair. - */ - get_ice_attr(sdp_local, sdp_local->media[media_index], - &ufrag_attr, &pwd_attr); - status = pj_ice_strans_init_ice(tp_ice->ice_st, - tp_ice->rem_offer_state.local_role, - &ufrag_attr->value, - &pwd_attr->value); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(tp_ice->base.name, status, - "ICE re-initialization failed!")); - return status; - } - } - - /* Ticket #977: Update role if turns out we're supposed to be the - * Controlling agent (e.g. when talking to ice-lite peer). - */ - if (tp_ice->rem_offer_state.local_role==PJ_ICE_SESS_ROLE_CONTROLLING && - pj_ice_strans_has_sess(tp_ice->ice_st)) - { - pj_ice_strans_change_role(tp_ice->ice_st, - PJ_ICE_SESS_ROLE_CONTROLLING); - } - - /* start ICE */ + /* + * We are answerer. We've seen and negotiated remote's SDP + * before, and the result is in "rem_offer_state". + */ + const pjmedia_sdp_attr *ufrag_attr, *pwd_attr; + + /* Check for ICE in remote offer */ + if (tp_ice->rem_offer_state.match_comp_cnt == 0) { + /* No ICE attribute present */ + set_no_ice(tp_ice, "Remote no longer offers ICE", + PJ_SUCCESS); + return PJ_SUCCESS; + } + + /* Check for ICE ice_mismatch condition in the offer */ + if (tp_ice->rem_offer_state.ice_mismatch) { + set_no_ice(tp_ice, "Remote offer mismatch: ", + PJNATH_EICEMISMATCH); + return PJ_SUCCESS; + } + + /* If ICE is complete and remote doesn't request restart, + * then leave the session as is. + */ + if (!initial_oa && tp_ice->rem_offer_state.ice_restart == PJ_FALSE) { + /* Remote has not requested ICE restart, so session is + * unchanged. + */ + PJ_LOG(4,(tp_ice->base.name, "ICE session unchanged")); + return PJ_SUCCESS; + } + + /* Either remote has requested ICE restart or this is our + * first answer. + */ + + /* Stop ICE */ + if (!initial_oa) { + set_no_ice(tp_ice, "restarting by remote request..", PJ_SUCCESS); + + /* We have put new ICE ufrag and pwd in the answer. Now + * create a new ICE session with that ufrag/pwd pair. + */ + get_ice_attr(sdp_local, sdp_local->media[media_index], + &ufrag_attr, &pwd_attr); + status = pj_ice_strans_init_ice(tp_ice->ice_st, + tp_ice->rem_offer_state.local_role, + &ufrag_attr->value, + &pwd_attr->value); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(tp_ice->base.name, status, + "ICE re-initialization failed!")); + return status; + } + } + + /* Ticket #977: Update role if turns out we're supposed to be the + * Controlling agent (e.g. when talking to ice-lite peer). + */ + if (tp_ice->rem_offer_state.local_role==PJ_ICE_SESS_ROLE_CONTROLLING && + pj_ice_strans_has_sess(tp_ice->ice_st)) + { + pj_ice_strans_change_role(tp_ice->ice_st, + PJ_ICE_SESS_ROLE_CONTROLLING); + } + + /* start ICE */ } /* RFC 5245 section 8.1.1: @@ -2213,27 +2212,27 @@ static pj_status_t transport_media_start(pjmedia_transport *tp, * a regular nomination algorithm. */ if (pjmedia_sdp_attr_find(rem_sdp->attr_count, rem_sdp->attr, - &STR_ICE_LITE, NULL) != NULL) + &STR_ICE_LITE, NULL) != NULL) { pj_ice_sess_options opt; - pj_ice_strans_get_options(tp_ice->ice_st, &opt); - if (opt.aggressive) { - opt.aggressive = PJ_FALSE; - pj_ice_strans_set_options(tp_ice->ice_st, &opt); - PJ_LOG(4,(tp_ice->base.name, "Forcefully set ICE to use regular " - "nomination as remote is lite implementation")); - } + pj_ice_strans_get_options(tp_ice->ice_st, &opt); + if (opt.aggressive) { + opt.aggressive = PJ_FALSE; + pj_ice_strans_set_options(tp_ice->ice_st, &opt); + PJ_LOG(4,(tp_ice->base.name, "Forcefully set ICE to use regular " + "nomination as remote is lite implementation")); + } } /* Now start ICE, if not yet (trickle ICE may have started it earlier) */ if (!pj_ice_strans_sess_is_running(tp_ice->ice_st) && - !pj_ice_strans_sess_is_complete(tp_ice->ice_st)) + !pj_ice_strans_sess_is_complete(tp_ice->ice_st)) { - status = start_ice(tp_ice, tmp_pool, rem_sdp, media_index); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(tp_ice->base.name, status, "ICE restart failed!")); - return status; - } + status = start_ice(tp_ice, tmp_pool, rem_sdp, media_index); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(tp_ice->base.name, status, "ICE restart failed!")); + return status; + } } /* Done */ @@ -2254,7 +2253,7 @@ static pj_status_t transport_media_stop(pjmedia_transport *tp) static pj_status_t transport_get_info(pjmedia_transport *tp, - pjmedia_transport_info *info) + pjmedia_transport_info *info) { struct transport_ice *tp_ice = (struct transport_ice*)tp; pj_ice_sess_cand cand; @@ -2267,7 +2266,7 @@ static pj_status_t transport_get_info(pjmedia_transport *tp, /* Get RTP default address */ status = pj_ice_strans_get_def_cand(tp_ice->ice_st, 1, &cand); if (status != PJ_SUCCESS) - return status; + return status; /* Address of the default candidate may not be available (e.g: * STUN/TURN address is still being resolved), so let's find address @@ -2276,106 +2275,106 @@ static pj_status_t transport_get_info(pjmedia_transport *tp, */ addr = NULL; if (pj_sockaddr_has_addr(&cand.addr)) { - addr = &cand.addr; + addr = &cand.addr; } else if (pj_ice_strans_has_sess(tp_ice->ice_st)) { - unsigned i, cnt = PJ_ICE_ST_MAX_CAND; - pj_ice_sess_cand cands[PJ_ICE_ST_MAX_CAND]; - pj_ice_strans_enum_cands(tp_ice->ice_st, 1, &cnt, cands); - for (i = 0; i < cnt && !addr; ++i) { - if (pj_sockaddr_has_addr(&cands[i].addr)) - addr = &cands[i].addr; - } + unsigned i, cnt = PJ_ICE_ST_MAX_CAND; + pj_ice_sess_cand cands[PJ_ICE_ST_MAX_CAND]; + pj_ice_strans_enum_cands(tp_ice->ice_st, 1, &cnt, cands); + for (i = 0; i < cnt && !addr; ++i) { + if (pj_sockaddr_has_addr(&cands[i].addr)) + addr = &cands[i].addr; + } } if (addr) { - pj_sockaddr_cp(&info->sock_info.rtp_addr_name, addr); + pj_sockaddr_cp(&info->sock_info.rtp_addr_name, addr); } else { - pj_sockaddr_init(PJ_AF_INET, &info->sock_info.rtp_addr_name, NULL, 9); + pj_sockaddr_init(PJ_AF_INET, &info->sock_info.rtp_addr_name, NULL, 9); } /* Get RTCP default address */ if (tp_ice->use_rtcp_mux) { - pj_sockaddr_cp(&info->sock_info.rtcp_addr_name, addr); + pj_sockaddr_cp(&info->sock_info.rtcp_addr_name, addr); } else if (tp_ice->comp_cnt > 1) { - status = pj_ice_strans_get_def_cand(tp_ice->ice_st, 2, &cand); - if (status != PJ_SUCCESS) - return status; - - /* Address of the default candidate may not be available (e.g: - * STUN/TURN address is still being resolved), so let's find address - * of any other candidate. If none is available, SDP must not include - * "a=rtcp" attribute. - */ - addr = NULL; - if (pj_sockaddr_has_addr(&cand.addr)) { - addr = &cand.addr; - } else if (pj_ice_strans_has_sess(tp_ice->ice_st)) { - unsigned i, cnt = PJ_ICE_ST_MAX_CAND; - pj_ice_sess_cand cands[PJ_ICE_ST_MAX_CAND]; - pj_ice_strans_enum_cands(tp_ice->ice_st, 2, &cnt, cands); - for (i = 0; i < cnt && !addr; ++i) { - if (pj_sockaddr_has_addr(&cands[i].addr)) - addr = &cands[i].addr; - } - } - if (addr) { - pj_sockaddr_cp(&info->sock_info.rtcp_addr_name, addr); - } + status = pj_ice_strans_get_def_cand(tp_ice->ice_st, 2, &cand); + if (status != PJ_SUCCESS) + return status; + + /* Address of the default candidate may not be available (e.g: + * STUN/TURN address is still being resolved), so let's find address + * of any other candidate. If none is available, SDP must not include + * "a=rtcp" attribute. + */ + addr = NULL; + if (pj_sockaddr_has_addr(&cand.addr)) { + addr = &cand.addr; + } else if (pj_ice_strans_has_sess(tp_ice->ice_st)) { + unsigned i, cnt = PJ_ICE_ST_MAX_CAND; + pj_ice_sess_cand cands[PJ_ICE_ST_MAX_CAND]; + pj_ice_strans_enum_cands(tp_ice->ice_st, 2, &cnt, cands); + for (i = 0; i < cnt && !addr; ++i) { + if (pj_sockaddr_has_addr(&cands[i].addr)) + addr = &cands[i].addr; + } + } + if (addr) { + pj_sockaddr_cp(&info->sock_info.rtcp_addr_name, addr); + } } /* Set remote address originating RTP & RTCP if this transport has * ICE activated or received any packets. */ if (tp_ice->use_ice || tp_ice->rtp_src_cnt) { - info->src_rtp_name = tp_ice->rtp_src_addr; - if (tp_ice->use_rtcp_mux) - info->src_rtcp_name = tp_ice->rtp_src_addr; + info->src_rtp_name = tp_ice->rtp_src_addr; + if (tp_ice->use_rtcp_mux) + info->src_rtcp_name = tp_ice->rtp_src_addr; } if ((!tp_ice->use_rtcp_mux) && - (tp_ice->use_ice || tp_ice->rtcp_src_cnt)) + (tp_ice->use_ice || tp_ice->rtcp_src_cnt)) { - info->src_rtcp_name = tp_ice->rtcp_src_addr; + info->src_rtcp_name = tp_ice->rtcp_src_addr; } /* Fill up transport specific info */ if (info->specific_info_cnt < PJ_ARRAY_SIZE(info->spc_info)) { - pjmedia_transport_specific_info *tsi; - pjmedia_ice_transport_info *ii; - unsigned i; - - pj_assert(sizeof(*ii) <= sizeof(tsi->buffer)); - tsi = &info->spc_info[info->specific_info_cnt++]; - tsi->type = PJMEDIA_TRANSPORT_TYPE_ICE; - tsi->tp = tp; - tsi->cbsize = sizeof(*ii); - - ii = (pjmedia_ice_transport_info*) tsi->buffer; - pj_bzero(ii, sizeof(*ii)); - - ii->active = tp_ice->use_ice; - - if (pj_ice_strans_has_sess(tp_ice->ice_st)) { - ii->role = pj_ice_strans_get_role(tp_ice->ice_st); - pj_ice_strans_get_ufrag_pwd(tp_ice->ice_st, &ii->loc_ufrag, NULL, - &ii->rem_ufrag, NULL); - } else { - ii->role = PJ_ICE_SESS_ROLE_UNKNOWN; - } - ii->sess_state = pj_ice_strans_get_state(tp_ice->ice_st); - ii->comp_cnt = pj_ice_strans_get_running_comp_cnt(tp_ice->ice_st); - - for (i=1; i<=ii->comp_cnt && i<=PJ_ARRAY_SIZE(ii->comp); ++i) { - const pj_ice_sess_check *chk; - - chk = pj_ice_strans_get_valid_pair(tp_ice->ice_st, i); - if (chk) { - ii->comp[i-1].lcand_type = chk->lcand->type; - pj_sockaddr_cp(&ii->comp[i-1].lcand_addr, - &chk->lcand->addr); - ii->comp[i-1].rcand_type = chk->rcand->type; - pj_sockaddr_cp(&ii->comp[i-1].rcand_addr, - &chk->rcand->addr); - } - } + pjmedia_transport_specific_info *tsi; + pjmedia_ice_transport_info *ii; + unsigned i; + + pj_assert(sizeof(*ii) <= sizeof(tsi->buffer)); + tsi = &info->spc_info[info->specific_info_cnt++]; + tsi->type = PJMEDIA_TRANSPORT_TYPE_ICE; + tsi->tp = tp; + tsi->cbsize = sizeof(*ii); + + ii = (pjmedia_ice_transport_info*) tsi->buffer; + pj_bzero(ii, sizeof(*ii)); + + ii->active = tp_ice->use_ice; + + if (pj_ice_strans_has_sess(tp_ice->ice_st)) { + ii->role = pj_ice_strans_get_role(tp_ice->ice_st); + pj_ice_strans_get_ufrag_pwd(tp_ice->ice_st, &ii->loc_ufrag, NULL, + &ii->rem_ufrag, NULL); + } else { + ii->role = PJ_ICE_SESS_ROLE_UNKNOWN; + } + ii->sess_state = pj_ice_strans_get_state(tp_ice->ice_st); + ii->comp_cnt = pj_ice_strans_get_running_comp_cnt(tp_ice->ice_st); + + for (i=1; i<=ii->comp_cnt && i<=PJ_ARRAY_SIZE(ii->comp); ++i) { + const pj_ice_sess_check *chk; + + chk = pj_ice_strans_get_valid_pair(tp_ice->ice_st, i); + if (chk) { + ii->comp[i-1].lcand_type = chk->lcand->type; + pj_sockaddr_cp(&ii->comp[i-1].lcand_addr, + &chk->lcand->addr); + ii->comp[i-1].rcand_type = chk->rcand->type; + pj_sockaddr_cp(&ii->comp[i-1].rcand_addr, + &chk->rcand->addr); + } + } } return PJ_SUCCESS; @@ -2383,16 +2382,16 @@ static pj_status_t transport_get_info(pjmedia_transport *tp, static pj_status_t transport_attach (pjmedia_transport *tp, - void *stream, - const pj_sockaddr_t *rem_addr, - const pj_sockaddr_t *rem_rtcp, - unsigned addr_len, - void (*rtp_cb)(void*, - void*, - pj_ssize_t), - void (*rtcp_cb)(void*, - void*, - pj_ssize_t)) + void *stream, + const pj_sockaddr_t *rem_addr, + const pj_sockaddr_t *rem_rtcp, + unsigned addr_len, + void (*rtp_cb)(void*, + void*, + pj_ssize_t), + void (*rtcp_cb)(void*, + void*, + pj_ssize_t)) { pjmedia_transport_attach_param param; @@ -2408,8 +2407,8 @@ static pj_status_t transport_attach (pjmedia_transport *tp, static pj_status_t transport_attach2 (pjmedia_transport *tp, - pjmedia_transport_attach_param - *att_param) + pjmedia_transport_attach_param + *att_param) { struct transport_ice *tp_ice = (struct transport_ice*)tp; @@ -2420,8 +2419,8 @@ static pj_status_t transport_attach2 (pjmedia_transport *tp, /* Check again if we are multiplexing RTP & RTCP. */ tp_ice->use_rtcp_mux = (pj_sockaddr_has_addr(&att_param->rem_addr) && - pj_sockaddr_cmp(&att_param->rem_addr, - &att_param->rem_rtcp) == 0); + pj_sockaddr_cmp(&att_param->rem_addr, + &att_param->rem_rtcp) == 0); pj_memcpy(&tp_ice->remote_rtp, &att_param->rem_addr, att_param->addr_len); pj_memcpy(&tp_ice->remote_rtcp, &att_param->rem_rtcp, att_param->addr_len); @@ -2437,7 +2436,7 @@ static pj_status_t transport_attach2 (pjmedia_transport *tp, static void transport_detach(pjmedia_transport *tp, - void *strm) + void *strm) { struct transport_ice *tp_ice = (struct transport_ice*)tp; @@ -2453,25 +2452,25 @@ static void transport_detach(pjmedia_transport *tp, static pj_status_t transport_send_rtp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { struct transport_ice *tp_ice = (struct transport_ice*)tp; pj_status_t status; /* Simulate packet lost on TX direction */ if (tp_ice->tx_drop_pct) { - if ((pj_rand() % 100) <= (int)tp_ice->tx_drop_pct) { - PJ_LOG(5,(tp_ice->base.name, - "TX RTP packet dropped because of pkt lost " - "simulation")); - return PJ_SUCCESS; - } + if ((pj_rand() % 100) <= (int)tp_ice->tx_drop_pct) { + PJ_LOG(5,(tp_ice->base.name, + "TX RTP packet dropped because of pkt lost " + "simulation")); + return PJ_SUCCESS; + } } status = pj_ice_strans_sendto2(tp_ice->ice_st, 1, - pkt, size, &tp_ice->remote_rtp, - tp_ice->addr_len); + pkt, size, &tp_ice->remote_rtp, + tp_ice->addr_len); if (status == PJ_EPENDING) status = PJ_SUCCESS; @@ -2480,17 +2479,17 @@ static pj_status_t transport_send_rtp(pjmedia_transport *tp, static pj_status_t transport_send_rtcp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { return transport_send_rtcp2(tp, NULL, 0, pkt, size); } static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, - const pj_sockaddr_t *addr, - unsigned addr_len, - const void *pkt, - pj_size_t size) + const pj_sockaddr_t *addr, + unsigned addr_len, + const void *pkt, + pj_size_t size) { struct transport_ice *tp_ice = (struct transport_ice*)tp; @@ -2498,153 +2497,153 @@ static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, pj_status_t status; unsigned comp_id = (tp_ice->use_rtcp_mux? 1: 2); - if (addr == NULL) { - addr = &tp_ice->remote_rtcp; - addr_len = pj_sockaddr_get_len(addr); - } + if (addr == NULL) { + addr = &tp_ice->remote_rtcp; + addr_len = pj_sockaddr_get_len(addr); + } - status = pj_ice_strans_sendto2(tp_ice->ice_st, comp_id, pkt, size, - addr, addr_len); - if (status == PJ_EPENDING) - status = PJ_SUCCESS; + status = pj_ice_strans_sendto2(tp_ice->ice_st, comp_id, pkt, size, + addr, addr_len); + if (status == PJ_EPENDING) + status = PJ_SUCCESS; - return status; + return status; } else { - return PJ_SUCCESS; + return PJ_SUCCESS; } } static void ice_on_rx_data(pj_ice_strans *ice_st, unsigned comp_id, - void *pkt, pj_size_t size, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + void *pkt, pj_size_t size, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { struct transport_ice *tp_ice; pj_bool_t discard = PJ_FALSE; tp_ice = (struct transport_ice*) pj_ice_strans_get_user_data(ice_st); if (!tp_ice) { - /* Destroy on progress */ - return; + /* Destroy on progress */ + return; } if (comp_id == 1) { ++tp_ice->rtp_src_cnt; - pj_sockaddr_cp(&tp_ice->rtp_src_addr, src_addr); + pj_sockaddr_cp(&tp_ice->rtp_src_addr, src_addr); } else if (comp_id == 2) { - pj_sockaddr_cp(&tp_ice->rtcp_src_addr, src_addr); + pj_sockaddr_cp(&tp_ice->rtcp_src_addr, src_addr); } if (comp_id==1 && (tp_ice->rtp_cb || tp_ice->rtp_cb2)) { pj_bool_t rem_switch = PJ_FALSE; - /* Simulate packet lost on RX direction */ - if (tp_ice->rx_drop_pct) { - if ((pj_rand() % 100) <= (int)tp_ice->rx_drop_pct) { - PJ_LOG(5,(tp_ice->base.name, - "RX RTP packet dropped because of pkt lost " - "simulation")); - return; - } - } - - if (!discard) { - if (tp_ice->rtp_cb2) { - pjmedia_tp_cb_param param; - - param.user_data = tp_ice->stream; - param.pkt = pkt; - param.size = size; - param.src_addr = (tp_ice->use_ice? NULL: - (pj_sockaddr_t *)src_addr); - param.rem_switch = PJ_FALSE; - (*tp_ice->rtp_cb2)(¶m); - rem_switch = param.rem_switch; - } else { - (*tp_ice->rtp_cb)(tp_ice->stream, pkt, size); - } - } - + /* Simulate packet lost on RX direction */ + if (tp_ice->rx_drop_pct) { + if ((pj_rand() % 100) <= (int)tp_ice->rx_drop_pct) { + PJ_LOG(5,(tp_ice->base.name, + "RX RTP packet dropped because of pkt lost " + "simulation")); + return; + } + } + + if (!discard) { + if (tp_ice->rtp_cb2) { + pjmedia_tp_cb_param param; + + param.user_data = tp_ice->stream; + param.pkt = pkt; + param.size = size; + param.src_addr = (tp_ice->use_ice? NULL: + (pj_sockaddr_t *)src_addr); + param.rem_switch = PJ_FALSE; + (*tp_ice->rtp_cb2)(¶m); + rem_switch = param.rem_switch; + } else { + (*tp_ice->rtp_cb)(tp_ice->stream, pkt, size); + } + } + #if defined(PJMEDIA_TRANSPORT_SWITCH_REMOTE_ADDR) && \ (PJMEDIA_TRANSPORT_SWITCH_REMOTE_ADDR == 1) - if (rem_switch && - (tp_ice->options & PJMEDIA_ICE_NO_SRC_ADDR_CHECKING)==0) - { - char addr_text[PJ_INET6_ADDRSTRLEN+10]; - - /* Set remote RTP address to source address */ - pj_sockaddr_cp(&tp_ice->rtp_src_addr, src_addr); - pj_sockaddr_cp(&tp_ice->remote_rtp, src_addr); - tp_ice->addr_len = pj_sockaddr_get_len(&tp_ice->remote_rtp); - - PJ_LOG(4,(tp_ice->base.name, - "Remote RTP address switched to %s", - pj_sockaddr_print(&tp_ice->remote_rtp, addr_text, - sizeof(addr_text), 3))); - - if (tp_ice->use_rtcp_mux) { - pj_sockaddr_cp(&tp_ice->remote_rtcp, &tp_ice->remote_rtp); - } else if (!pj_sockaddr_has_addr(&tp_ice->rtcp_src_addr)) { - /* Also update remote RTCP address if actual RTCP source - * address is not heard yet. - */ - pj_uint16_t port; - - pj_sockaddr_cp(&tp_ice->remote_rtcp, &tp_ice->remote_rtp); - - port = (pj_uint16_t) - (pj_sockaddr_get_port(&tp_ice->remote_rtp)+1); - pj_sockaddr_set_port(&tp_ice->remote_rtcp, port); - - PJ_LOG(4,(tp_ice->base.name, - "Remote RTCP address switched to predicted " - "address %s", - pj_sockaddr_print(&tp_ice->remote_rtcp, - addr_text, - sizeof(addr_text), 3))); - } - } + if (rem_switch && + (tp_ice->options & PJMEDIA_ICE_NO_SRC_ADDR_CHECKING)==0) + { + char addr_text[PJ_INET6_ADDRSTRLEN+10]; + + /* Set remote RTP address to source address */ + pj_sockaddr_cp(&tp_ice->rtp_src_addr, src_addr); + pj_sockaddr_cp(&tp_ice->remote_rtp, src_addr); + tp_ice->addr_len = pj_sockaddr_get_len(&tp_ice->remote_rtp); + + PJ_LOG(4,(tp_ice->base.name, + "Remote RTP address switched to %s", + pj_sockaddr_print(&tp_ice->remote_rtp, addr_text, + sizeof(addr_text), 3))); + + if (tp_ice->use_rtcp_mux) { + pj_sockaddr_cp(&tp_ice->remote_rtcp, &tp_ice->remote_rtp); + } else if (!pj_sockaddr_has_addr(&tp_ice->rtcp_src_addr)) { + /* Also update remote RTCP address if actual RTCP source + * address is not heard yet. + */ + pj_uint16_t port; + + pj_sockaddr_cp(&tp_ice->remote_rtcp, &tp_ice->remote_rtp); + + port = (pj_uint16_t) + (pj_sockaddr_get_port(&tp_ice->remote_rtp)+1); + pj_sockaddr_set_port(&tp_ice->remote_rtcp, port); + + PJ_LOG(4,(tp_ice->base.name, + "Remote RTCP address switched to predicted " + "address %s", + pj_sockaddr_print(&tp_ice->remote_rtcp, + addr_text, + sizeof(addr_text), 3))); + } + } #endif } else if (comp_id==2 && tp_ice->rtcp_cb) { #if defined(PJMEDIA_TRANSPORT_SWITCH_REMOTE_ADDR) && \ (PJMEDIA_TRANSPORT_SWITCH_REMOTE_ADDR == 1) - /* Check if RTCP source address is the same as the configured - * remote address, and switch the address when they are - * different. - */ - if (!tp_ice->use_ice && - (tp_ice->options & PJMEDIA_ICE_NO_SRC_ADDR_CHECKING)==0) - { - if (pj_sockaddr_cmp(&tp_ice->remote_rtcp, src_addr) == 0) { - tp_ice->rtcp_src_cnt = 0; - } else { - char addr_text[PJ_INET6_ADDRSTRLEN+10]; - - ++tp_ice->rtcp_src_cnt; - if (tp_ice->rtcp_src_cnt < PJMEDIA_RTCP_NAT_PROBATION_CNT) { - discard = PJ_TRUE; - } else { - tp_ice->rtcp_src_cnt = 0; - pj_sockaddr_cp(&tp_ice->rtcp_src_addr, src_addr); - pj_sockaddr_cp(&tp_ice->remote_rtcp, src_addr); - - pj_assert(tp_ice->addr_len==pj_sockaddr_get_len(src_addr)); - - PJ_LOG(4,(tp_ice->base.name, - "Remote RTCP address switched to %s", - pj_sockaddr_print(&tp_ice->remote_rtcp, - addr_text, sizeof(addr_text), - 3))); - } - } - } + /* Check if RTCP source address is the same as the configured + * remote address, and switch the address when they are + * different. + */ + if (!tp_ice->use_ice && + (tp_ice->options & PJMEDIA_ICE_NO_SRC_ADDR_CHECKING)==0) + { + if (pj_sockaddr_cmp(&tp_ice->remote_rtcp, src_addr) == 0) { + tp_ice->rtcp_src_cnt = 0; + } else { + char addr_text[PJ_INET6_ADDRSTRLEN+10]; + + ++tp_ice->rtcp_src_cnt; + if (tp_ice->rtcp_src_cnt < PJMEDIA_RTCP_NAT_PROBATION_CNT) { + discard = PJ_TRUE; + } else { + tp_ice->rtcp_src_cnt = 0; + pj_sockaddr_cp(&tp_ice->rtcp_src_addr, src_addr); + pj_sockaddr_cp(&tp_ice->remote_rtcp, src_addr); + + pj_assert(tp_ice->addr_len==pj_sockaddr_get_len(src_addr)); + + PJ_LOG(4,(tp_ice->base.name, + "Remote RTCP address switched to %s", + pj_sockaddr_print(&tp_ice->remote_rtcp, + addr_text, sizeof(addr_text), + 3))); + } + } + } #endif - if (!discard) - (*tp_ice->rtcp_cb)(tp_ice->stream, pkt, size); + if (!discard) + (*tp_ice->rtcp_cb)(tp_ice->stream, pkt, size); } PJ_UNUSED_ARG(src_addr_len); @@ -2652,81 +2651,81 @@ static void ice_on_rx_data(pj_ice_strans *ice_st, unsigned comp_id, static void ice_on_ice_complete(pj_ice_strans *ice_st, - pj_ice_strans_op op, - pj_status_t result) + pj_ice_strans_op op, + pj_status_t result) { struct transport_ice *tp_ice; ice_listener *il; tp_ice = (struct transport_ice*) pj_ice_strans_get_user_data(ice_st); if (!tp_ice) { - /* Destroy on progress */ - return; + /* Destroy on progress */ + return; } /* Set the flag indicating that local candidate gathering is completed */ if (op == PJ_ICE_STRANS_OP_INIT && result == PJ_SUCCESS) - tp_ice->end_of_cand = PJ_TRUE; + tp_ice->end_of_cand = PJ_TRUE; pj_perror(5, tp_ice->base.name, result, "ICE operation complete" - " (op=%d%s)", op, - (op==PJ_ICE_STRANS_OP_INIT? "/initialization" : - (op==PJ_ICE_STRANS_OP_NEGOTIATION? "/negotiation":""))); + " (op=%d%s)", op, + (op==PJ_ICE_STRANS_OP_INIT? "/initialization" : + (op==PJ_ICE_STRANS_OP_NEGOTIATION? "/negotiation":""))); /* Notify application */ if (tp_ice->cb.on_ice_complete) - (*tp_ice->cb.on_ice_complete)(&tp_ice->base, op, result); + (*tp_ice->cb.on_ice_complete)(&tp_ice->base, op, result); for (il=tp_ice->listener.next; il!=&tp_ice->listener; il=il->next) { - if (il->cb.on_ice_complete2) { - (*il->cb.on_ice_complete2)(&tp_ice->base, op, result, - il->user_data); - } else if (il->cb.on_ice_complete) { - (*il->cb.on_ice_complete)(&tp_ice->base, op, result); - } + if (il->cb.on_ice_complete2) { + (*il->cb.on_ice_complete2)(&tp_ice->base, op, result, + il->user_data); + } else if (il->cb.on_ice_complete) { + (*il->cb.on_ice_complete)(&tp_ice->base, op, result); + } } } static void ice_on_new_candidate(pj_ice_strans *ice_st, - const pj_ice_sess_cand *cand, - pj_bool_t last) + const pj_ice_sess_cand *cand, + pj_bool_t last) { struct transport_ice *tp_ice; ice_listener *il; tp_ice = (struct transport_ice*) pj_ice_strans_get_user_data(ice_st); if (!tp_ice) { - /* Destroy on progress */ - return; + /* Destroy on progress */ + return; } /* Notify application */ if (tp_ice->cb.on_new_candidate) - (*tp_ice->cb.on_new_candidate)(&tp_ice->base, cand, last); + (*tp_ice->cb.on_new_candidate)(&tp_ice->base, cand, last); for (il=tp_ice->listener.next; il!=&tp_ice->listener; il=il->next) { - if (il->cb.on_new_candidate) { - (*il->cb.on_new_candidate)(&tp_ice->base, cand, last); - } + if (il->cb.on_new_candidate) { + (*il->cb.on_new_candidate)(&tp_ice->base, cand, last); + } } } /* Simulate lost */ static pj_status_t transport_simulate_lost(pjmedia_transport *tp, - pjmedia_dir dir, - unsigned pct_lost) + pjmedia_dir dir, + unsigned pct_lost) { struct transport_ice *ice = (struct transport_ice*) tp; PJ_ASSERT_RETURN(tp && pct_lost <= 100, PJ_EINVAL); if (dir & PJMEDIA_DIR_ENCODING) - ice->tx_drop_pct = pct_lost; + ice->tx_drop_pct = pct_lost; if (dir & PJMEDIA_DIR_DECODING) - ice->rx_drop_pct = pct_lost; + ice->rx_drop_pct = pct_lost; return PJ_SUCCESS; } @@ -2752,12 +2751,12 @@ static pj_status_t transport_destroy(pjmedia_transport *tp) tp_ice->rtcp_cb = NULL; if (tp_ice->ice_st) { - pj_grp_lock_t *grp_lock = pj_ice_strans_get_grp_lock(tp_ice->ice_st); - pj_ice_strans_destroy(tp_ice->ice_st); - tp_ice->ice_st = NULL; - pj_grp_lock_dec_ref(grp_lock); + pj_grp_lock_t *grp_lock = pj_ice_strans_get_grp_lock(tp_ice->ice_st); + pj_ice_strans_destroy(tp_ice->ice_st); + tp_ice->ice_st = NULL; + pj_grp_lock_dec_ref(grp_lock); } else { - tp_ice_on_destroy(tp); + tp_ice_on_destroy(tp); } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia/transport_loop.c b/pjmedia/src/pjmedia/transport_loop.c index a5cf7f605b..09650b2321 100644 --- a/pjmedia/src/pjmedia/transport_loop.c +++ b/pjmedia/src/pjmedia/transport_loop.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,30 +29,30 @@ struct tp_user { - pj_bool_t rx_disabled; /**< Doesn't want to receive pkt? */ - void *user_data; /**< Only valid when attached */ - void (*rtp_cb)( void*, /**< To report incoming RTP. */ - void*, - pj_ssize_t); - void (*rtp_cb2)( pjmedia_tp_cb_param*); - void (*rtcp_cb)( void*, /**< To report incoming RTCP. */ - void*, - pj_ssize_t); + pj_bool_t rx_disabled; /**< Doesn't want to receive pkt? */ + void *user_data; /**< Only valid when attached */ + void (*rtp_cb)( void*, /**< To report incoming RTP. */ + void*, + pj_ssize_t); + void (*rtp_cb2)( pjmedia_tp_cb_param*); + void (*rtcp_cb)( void*, /**< To report incoming RTCP. */ + void*, + pj_ssize_t); }; struct transport_loop { - pjmedia_transport base; /**< Base transport. */ + pjmedia_transport base; /**< Base transport. */ - pj_pool_t *pool; /**< Memory pool */ - unsigned user_cnt; /**< Number of attachments */ - struct tp_user users[4]; /**< Array of users. */ - pj_bool_t disable_rx; /**< Disable RX. */ + pj_pool_t *pool; /**< Memory pool */ + unsigned user_cnt; /**< Number of attachments */ + struct tp_user users[4]; /**< Array of users. */ + pj_bool_t disable_rx; /**< Disable RX. */ - pjmedia_loop_tp_setting setting; /**< Setting. */ + pjmedia_loop_tp_setting setting; /**< Setting. */ - unsigned tx_drop_pct; /**< Percent of tx pkts to drop. */ - unsigned rx_drop_pct; /**< Percent of rx pkts to drop. */ + unsigned tx_drop_pct; /**< Percent of tx pkts to drop. */ + unsigned rx_drop_pct; /**< Percent of rx pkts to drop. */ }; @@ -63,53 +62,53 @@ struct transport_loop * These are media transport operations. */ static pj_status_t transport_get_info (pjmedia_transport *tp, - pjmedia_transport_info *info); + pjmedia_transport_info *info); static pj_status_t transport_attach (pjmedia_transport *tp, - void *user_data, - const pj_sockaddr_t *rem_addr, - const pj_sockaddr_t *rem_rtcp, - unsigned addr_len, - void (*rtp_cb)(void*, - void*, - pj_ssize_t), - void (*rtcp_cb)(void*, - void*, - pj_ssize_t)); + void *user_data, + const pj_sockaddr_t *rem_addr, + const pj_sockaddr_t *rem_rtcp, + unsigned addr_len, + void (*rtp_cb)(void*, + void*, + pj_ssize_t), + void (*rtcp_cb)(void*, + void*, + pj_ssize_t)); static pj_status_t transport_attach2 (pjmedia_transport *tp, - pjmedia_transport_attach_param - *att_param); -static void transport_detach (pjmedia_transport *tp, - void *strm); + pjmedia_transport_attach_param + *att_param); +static void transport_detach (pjmedia_transport *tp, + void *strm); static pj_status_t transport_send_rtp( pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); static pj_status_t transport_send_rtcp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, - const pj_sockaddr_t *addr, - unsigned addr_len, - const void *pkt, - pj_size_t size); + const pj_sockaddr_t *addr, + unsigned addr_len, + const void *pkt, + pj_size_t size); static pj_status_t transport_media_create(pjmedia_transport *tp, - pj_pool_t *pool, - unsigned options, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *pool, + unsigned options, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t transport_encode_sdp(pjmedia_transport *tp, - pj_pool_t *pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index); + pj_pool_t *pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index); static pj_status_t transport_media_start (pjmedia_transport *tp, - pj_pool_t *pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t transport_media_stop(pjmedia_transport *tp); static pj_status_t transport_simulate_lost(pjmedia_transport *tp, - pjmedia_dir dir, - unsigned pct_lost); + pjmedia_dir dir, + unsigned pct_lost); static pj_status_t transport_destroy (pjmedia_transport *tp); @@ -146,7 +145,7 @@ PJ_DEF(void) pjmedia_loop_tp_setting_default(pjmedia_loop_tp_setting *opt) * Create loopback transport. */ PJ_DEF(pj_status_t) pjmedia_transport_loop_create(pjmedia_endpt *endpt, - pjmedia_transport **p_tp) + pjmedia_transport **p_tp) { pjmedia_loop_tp_setting opt; @@ -159,8 +158,8 @@ PJ_DEF(pj_status_t) pjmedia_transport_loop_create(pjmedia_endpt *endpt, PJ_DEF(pj_status_t) pjmedia_transport_loop_create2(pjmedia_endpt *endpt, - const pjmedia_loop_tp_setting *opt, - pjmedia_transport **p_tp) + const pjmedia_loop_tp_setting *opt, + pjmedia_transport **p_tp) { struct transport_loop *tp; pj_pool_t *pool; @@ -171,7 +170,7 @@ pjmedia_transport_loop_create2(pjmedia_endpt *endpt, /* Create transport structure */ pool = pjmedia_endpt_create_pool(endpt, "tploop", 512, 512); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; tp = PJ_POOL_ZALLOC_T(pool, struct transport_loop); tp->pool = pool; @@ -180,18 +179,18 @@ pjmedia_transport_loop_create2(pjmedia_endpt *endpt, tp->base.type = PJMEDIA_TRANSPORT_TYPE_UDP; if (opt) { - tp->setting = *opt; + tp->setting = *opt; } else { - pjmedia_loop_tp_setting_default(&tp->setting); + pjmedia_loop_tp_setting_default(&tp->setting); } if (tp->setting.addr.slen) { - pj_strdup(pool, &tp->setting.addr, &opt->addr); + pj_strdup(pool, &tp->setting.addr, &opt->addr); } else { - pj_strset2(&tp->setting.addr, (opt->af == pj_AF_INET())? - "127.0.0.1": "::1"); + pj_strset2(&tp->setting.addr, (opt->af == pj_AF_INET())? + "127.0.0.1": "::1"); } if (tp->setting.port == 0) - tp->setting.port = 4000; + tp->setting.port = 4000; /* Done */ *p_tp = &tp->base; @@ -200,17 +199,17 @@ pjmedia_transport_loop_create2(pjmedia_endpt *endpt, PJ_DEF(pj_status_t) pjmedia_transport_loop_disable_rx( pjmedia_transport *tp, - void *user, - pj_bool_t disabled) + void *user, + pj_bool_t disabled) { struct transport_loop *loop = (struct transport_loop*) tp; unsigned i; for (i=0; iuser_cnt; ++i) { - if (loop->users[i].user_data == user) { - loop->users[i].rx_disabled = disabled; - return PJ_SUCCESS; - } + if (loop->users[i].user_data == user) { + loop->users[i].rx_disabled = disabled; + return PJ_SUCCESS; + } } pj_assert(!"Invalid stream user"); return PJ_ENOTFOUND; @@ -234,16 +233,16 @@ static pj_status_t transport_destroy(pjmedia_transport *tp) /* Called to get the transport info */ static pj_status_t transport_get_info(pjmedia_transport *tp, - pjmedia_transport_info *info) + pjmedia_transport_info *info) { struct transport_loop *loop = (struct transport_loop*) tp; info->sock_info.rtp_sock = 1; pj_sockaddr_init(loop->setting.af, &info->sock_info.rtp_addr_name, - &loop->setting.addr, (pj_uint16_t)loop->setting.port); + &loop->setting.addr, (pj_uint16_t)loop->setting.port); info->sock_info.rtcp_sock = 2; pj_sockaddr_init(loop->setting.af, &info->sock_info.rtcp_addr_name, - &loop->setting.addr, (pj_uint16_t)loop->setting.port + 1); + &loop->setting.addr, (pj_uint16_t)loop->setting.port + 1); return PJ_SUCCESS; } @@ -251,17 +250,17 @@ static pj_status_t transport_get_info(pjmedia_transport *tp, /* Called by application to initialize the transport */ static pj_status_t tp_attach( pjmedia_transport *tp, - void *user_data, - const pj_sockaddr_t *rem_addr, - const pj_sockaddr_t *rem_rtcp, - unsigned addr_len, - void (*rtp_cb)(void*, - void*, - pj_ssize_t), - void (*rtp_cb2)(pjmedia_tp_cb_param*), - void (*rtcp_cb)(void*, - void*, - pj_ssize_t)) + void *user_data, + const pj_sockaddr_t *rem_addr, + const pj_sockaddr_t *rem_rtcp, + unsigned addr_len, + void (*rtp_cb)(void*, + void*, + pj_ssize_t), + void (*rtp_cb2)(pjmedia_tp_cb_param*), + void (*rtcp_cb)(void*, + void*, + pj_ssize_t)) { struct transport_loop *loop = (struct transport_loop*) tp; unsigned i; @@ -272,11 +271,11 @@ static pj_status_t tp_attach( pjmedia_transport *tp, /* Must not be "attached" to same user */ for (i=0; iuser_cnt; ++i) { - PJ_ASSERT_RETURN(loop->users[i].user_data != user_data, - PJ_EINVALIDOP); + PJ_ASSERT_RETURN(loop->users[i].user_data != user_data, + PJ_EINVALIDOP); } PJ_ASSERT_RETURN(loop->user_cnt != PJ_ARRAY_SIZE(loop->users), - PJ_ETOOMANY); + PJ_ETOOMANY); PJ_UNUSED_ARG(rem_rtcp); PJ_UNUSED_ARG(rtcp_addr); @@ -295,36 +294,36 @@ static pj_status_t tp_attach( pjmedia_transport *tp, } static pj_status_t transport_attach( pjmedia_transport *tp, - void *user_data, - const pj_sockaddr_t *rem_addr, - const pj_sockaddr_t *rem_rtcp, - unsigned addr_len, - void (*rtp_cb)(void*, - void*, - pj_ssize_t), - void (*rtcp_cb)(void*, - void*, - pj_ssize_t)) + void *user_data, + const pj_sockaddr_t *rem_addr, + const pj_sockaddr_t *rem_rtcp, + unsigned addr_len, + void (*rtp_cb)(void*, + void*, + pj_ssize_t), + void (*rtcp_cb)(void*, + void*, + pj_ssize_t)) { return tp_attach(tp, user_data, rem_addr, rem_rtcp, addr_len, - rtp_cb, NULL, rtcp_cb); + rtp_cb, NULL, rtcp_cb); } static pj_status_t transport_attach2(pjmedia_transport *tp, - pjmedia_transport_attach_param *att_param) + pjmedia_transport_attach_param *att_param) { return tp_attach(tp, att_param->user_data, - (pj_sockaddr_t*)&att_param->rem_addr, - (pj_sockaddr_t*)&att_param->rem_rtcp, - att_param->addr_len, att_param->rtp_cb, - att_param->rtp_cb2, - att_param->rtcp_cb); + (pj_sockaddr_t*)&att_param->rem_addr, + (pj_sockaddr_t*)&att_param->rem_rtcp, + att_param->addr_len, att_param->rtp_cb, + att_param->rtp_cb2, + att_param->rtcp_cb); } /* Called by application when it no longer needs the transport */ static void transport_detach( pjmedia_transport *tp, - void *user_data) + void *user_data) { struct transport_loop *loop = (struct transport_loop*) tp; unsigned i; @@ -332,62 +331,62 @@ static void transport_detach( pjmedia_transport *tp, pj_assert(tp); for (i=0; iuser_cnt; ++i) { - if (loop->users[i].user_data == user_data) - break; + if (loop->users[i].user_data == user_data) + break; } /* Remove this user */ if (i != loop->user_cnt) { - pj_array_erase(loop->users, sizeof(loop->users[0]), - loop->user_cnt, i); - --loop->user_cnt; + pj_array_erase(loop->users, sizeof(loop->users[0]), + loop->user_cnt, i); + --loop->user_cnt; } } /* Called by application to send RTP packet */ static pj_status_t transport_send_rtp( pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { struct transport_loop *loop = (struct transport_loop*)tp; unsigned i; /* Simulate packet lost on TX direction */ if (loop->tx_drop_pct) { - if ((pj_rand() % 100) <= (int)loop->tx_drop_pct) { - PJ_LOG(5,(loop->base.name, - "TX RTP packet dropped because of pkt lost " - "simulation")); - return PJ_SUCCESS; - } + if ((pj_rand() % 100) <= (int)loop->tx_drop_pct) { + PJ_LOG(5,(loop->base.name, + "TX RTP packet dropped because of pkt lost " + "simulation")); + return PJ_SUCCESS; + } } /* Simulate packet lost on RX direction */ if (loop->rx_drop_pct) { - if ((pj_rand() % 100) <= (int)loop->rx_drop_pct) { - PJ_LOG(5,(loop->base.name, - "RX RTP packet dropped because of pkt lost " - "simulation")); - return PJ_SUCCESS; - } + if ((pj_rand() % 100) <= (int)loop->rx_drop_pct) { + PJ_LOG(5,(loop->base.name, + "RX RTP packet dropped because of pkt lost " + "simulation")); + return PJ_SUCCESS; + } } /* Distribute to users */ for (i=0; iuser_cnt; ++i) { - if (loop->users[i].rx_disabled) continue; - if (loop->users[i].rtp_cb2) { - pjmedia_tp_cb_param param; - - pj_bzero(¶m, sizeof(param)); - param.user_data = loop->users[i].user_data; - param.pkt = (void *)pkt; - param.size = size; - (*loop->users[i].rtp_cb2)(¶m); - } else if (loop->users[i].rtp_cb) { - (*loop->users[i].rtp_cb)(loop->users[i].user_data, (void*)pkt, - size); - } + if (loop->users[i].rx_disabled) continue; + if (loop->users[i].rtp_cb2) { + pjmedia_tp_cb_param param; + + pj_bzero(¶m, sizeof(param)); + param.user_data = loop->users[i].user_data; + param.pkt = (void *)pkt; + param.size = size; + (*loop->users[i].rtp_cb2)(¶m); + } else if (loop->users[i].rtp_cb) { + (*loop->users[i].rtp_cb)(loop->users[i].user_data, (void*)pkt, + size); + } } return PJ_SUCCESS; @@ -395,8 +394,8 @@ static pj_status_t transport_send_rtp( pjmedia_transport *tp, /* Called by application to send RTCP packet */ static pj_status_t transport_send_rtcp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { return transport_send_rtcp2(tp, NULL, 0, pkt, size); } @@ -404,10 +403,10 @@ static pj_status_t transport_send_rtcp(pjmedia_transport *tp, /* Called by application to send RTCP packet */ static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, - const pj_sockaddr_t *addr, - unsigned addr_len, - const void *pkt, - pj_size_t size) + const pj_sockaddr_t *addr, + unsigned addr_len, + const void *pkt, + pj_size_t size) { struct transport_loop *loop = (struct transport_loop*)tp; unsigned i; @@ -417,9 +416,9 @@ static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, /* Distribute to users */ for (i=0; iuser_cnt; ++i) { - if (!loop->users[i].rx_disabled && loop->users[i].rtcp_cb) - (*loop->users[i].rtcp_cb)(loop->users[i].user_data, (void*)pkt, - size); + if (!loop->users[i].rx_disabled && loop->users[i].rtcp_cb) + (*loop->users[i].rtcp_cb)(loop->users[i].user_data, (void*)pkt, + size); } return PJ_SUCCESS; @@ -427,10 +426,10 @@ static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, static pj_status_t transport_media_create(pjmedia_transport *tp, - pj_pool_t *pool, - unsigned options, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *pool, + unsigned options, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { PJ_UNUSED_ARG(tp); PJ_UNUSED_ARG(pool); @@ -441,10 +440,10 @@ static pj_status_t transport_media_create(pjmedia_transport *tp, } static pj_status_t transport_encode_sdp(pjmedia_transport *tp, - pj_pool_t *pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { PJ_UNUSED_ARG(tp); PJ_UNUSED_ARG(pool); @@ -455,10 +454,10 @@ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, } static pj_status_t transport_media_start(pjmedia_transport *tp, - pj_pool_t *pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { PJ_UNUSED_ARG(tp); PJ_UNUSED_ARG(pool); @@ -475,18 +474,18 @@ static pj_status_t transport_media_stop(pjmedia_transport *tp) } static pj_status_t transport_simulate_lost(pjmedia_transport *tp, - pjmedia_dir dir, - unsigned pct_lost) + pjmedia_dir dir, + unsigned pct_lost) { struct transport_loop *loop = (struct transport_loop*)tp; PJ_ASSERT_RETURN(tp && pct_lost <= 100, PJ_EINVAL); if (dir & PJMEDIA_DIR_ENCODING) - loop->tx_drop_pct = pct_lost; + loop->tx_drop_pct = pct_lost; if (dir & PJMEDIA_DIR_DECODING) - loop->rx_drop_pct = pct_lost; + loop->rx_drop_pct = pct_lost; return PJ_SUCCESS; } diff --git a/pjmedia/src/pjmedia/transport_srtp.c b/pjmedia/src/pjmedia/transport_srtp.c index 39d06434ba..05103d29d5 100644 --- a/pjmedia/src/pjmedia/transport_srtp.c +++ b/pjmedia/src/pjmedia/transport_srtp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -54,34 +53,34 @@ #if defined(PJMEDIA_EXTERNAL_SRTP) -#if (PJMEDIA_EXTERNAL_SRTP == 1) /* External SRTP 1.x */ +#if (PJMEDIA_EXTERNAL_SRTP == 1) /* External SRTP 1.x */ # include # include -#define srtp_crypto_policy_t crypto_policy_t -#define srtp_cipher_type_id_t cipher_type_id_t -#define srtp_cipher_type_t cipher_type_t -#define srtp_auth_type_id_t auth_type_id_t -#define srtp_sec_serv_t sec_serv_t -#define srtp_err_status_t err_status_t -#define srtp_err_status_ok err_status_ok -#define srtp_err_status_replay_old err_status_replay_old -#define srtp_err_status_replay_fail err_status_replay_fail +#define srtp_crypto_policy_t crypto_policy_t +#define srtp_cipher_type_id_t cipher_type_id_t +#define srtp_cipher_type_t cipher_type_t +#define srtp_auth_type_id_t auth_type_id_t +#define srtp_sec_serv_t sec_serv_t +#define srtp_err_status_t err_status_t +#define srtp_err_status_ok err_status_ok +#define srtp_err_status_replay_old err_status_replay_old +#define srtp_err_status_replay_fail err_status_replay_fail #define srtp_crypto_policy_set_aes_cm_256_hmac_sha1_32 \ - crypto_policy_set_aes_cm_256_hmac_sha1_32 + crypto_policy_set_aes_cm_256_hmac_sha1_32 #define srtp_crypto_policy_set_aes_cm_256_hmac_sha1_80 \ - crypto_policy_set_aes_cm_256_hmac_sha1_80 -#define SRTP_NULL_CIPHER NULL_CIPHER -#define SRTP_NULL_AUTH NULL_AUTH -#define SRTP_AES_ICM_128 AES_ICM -#define SRTP_AES_ICM_192 AES_ICM -#define SRTP_AES_ICM_256 AES_ICM -#define SRTP_AES_GCM_128 AES_128_GCM -#define SRTP_AES_GCM_256 AES_256_GCM -#define SRTP_HMAC_SHA1 HMAC_SHA1 + crypto_policy_set_aes_cm_256_hmac_sha1_80 +#define SRTP_NULL_CIPHER NULL_CIPHER +#define SRTP_NULL_AUTH NULL_AUTH +#define SRTP_AES_ICM_128 AES_ICM +#define SRTP_AES_ICM_192 AES_ICM +#define SRTP_AES_ICM_256 AES_ICM +#define SRTP_AES_GCM_128 AES_128_GCM +#define SRTP_AES_GCM_256 AES_256_GCM +#define SRTP_HMAC_SHA1 HMAC_SHA1 #define srtp_aes_gcm_256_openssl aes_gcm_256_openssl #define srtp_aes_gcm_128_openssl aes_gcm_128_openssl -#else /* External SRTP 2.x */ +#else /* External SRTP 2.x */ # include # include @@ -89,16 +88,16 @@ * Instead it was named with ICM at the end: SRTP_AES_128_ICM. */ # ifdef SRTP_AES_128_ICM -# define SRTP_AES_ICM_128 SRTP_AES_128_ICM -# define SRTP_AES_ICM_192 SRTP_AES_192_ICM -# define SRTP_AES_ICM_256 SRTP_AES_256_ICM -# define SRTP_AES_GCM_128 SRTP_AES_128_GCM -# define SRTP_AES_GCM_256 SRTP_AES_256_GCM +# define SRTP_AES_ICM_128 SRTP_AES_128_ICM +# define SRTP_AES_ICM_192 SRTP_AES_192_ICM +# define SRTP_AES_ICM_256 SRTP_AES_256_ICM +# define SRTP_AES_GCM_128 SRTP_AES_128_GCM +# define SRTP_AES_GCM_256 SRTP_AES_256_GCM # endif #endif -#else /* Bundled SRTP */ +#else /* Bundled SRTP */ # include # include #endif @@ -106,17 +105,17 @@ #define THIS_FILE "transport_srtp.c" /* Maximum size of outgoing packet */ -#define MAX_RTP_BUFFER_LEN PJMEDIA_MAX_MTU -#define MAX_RTCP_BUFFER_LEN PJMEDIA_MAX_MTU +#define MAX_RTP_BUFFER_LEN PJMEDIA_MAX_MTU +#define MAX_RTCP_BUFFER_LEN PJMEDIA_MAX_MTU /* Maximum SRTP crypto key length */ -#define MAX_KEY_LEN 128 +#define MAX_KEY_LEN 128 /* Initial value of probation counter. When probation counter > 0, * it means SRTP is in probation state, and it may restart when * srtp_unprotect() returns err_status_replay_* */ -#define PROBATION_CNT_INIT 100 +#define PROBATION_CNT_INIT 100 #define DEACTIVATE_MEDIA(pool, m) pjmedia_sdp_media_deactivate(pool, m) @@ -127,7 +126,7 @@ #endif /* Maximum number of SRTP keying method */ -#define MAX_KEYING 2 +#define MAX_KEYING 2 static const pj_str_t ID_RTP_AVP = { "RTP/AVP", 7 }; static const pj_str_t ID_RTP_SAVP = { "RTP/SAVP", 8 }; @@ -138,15 +137,15 @@ typedef void (*crypto_method_t)(srtp_crypto_policy_t *policy); typedef struct crypto_suite { - char *name; + char *name; srtp_cipher_type_id_t cipher_type; - unsigned cipher_key_len; /* key + salt length */ - unsigned cipher_salt_len; /* salt only length */ - srtp_auth_type_id_t auth_type; - unsigned auth_key_len; - unsigned srtp_auth_tag_len; - unsigned srtcp_auth_tag_len; - srtp_sec_serv_t service; + unsigned cipher_key_len; /* key + salt length */ + unsigned cipher_salt_len; /* salt only length */ + srtp_auth_type_id_t auth_type; + unsigned auth_key_len; + unsigned srtp_auth_tag_len; + unsigned srtcp_auth_tag_len; + srtp_sec_serv_t service; /* This is an attempt to validate crypto support by libsrtp, i.e: it should * raise linking error if the libsrtp does not support the crypto. */ @@ -167,65 +166,65 @@ static crypto_suite crypto_suites[] = { /* cipher AES_GCM, NULL auth, auth tag len = 16 octets */ {"AEAD_AES_256_GCM", SRTP_AES_GCM_256, 44, 12, - SRTP_NULL_AUTH, 0, 16, 16, sec_serv_conf_and_auth, - &srtp_aes_gcm_256_openssl}, + SRTP_NULL_AUTH, 0, 16, 16, sec_serv_conf_and_auth, + &srtp_aes_gcm_256_openssl}, /* cipher AES_GCM, NULL auth, auth tag len = 8 octets */ {"AEAD_AES_256_GCM_8", SRTP_AES_GCM_256, 44, 12, - SRTP_NULL_AUTH, 0, 8, 8, sec_serv_conf_and_auth, - &srtp_aes_gcm_256_openssl}, + SRTP_NULL_AUTH, 0, 8, 8, sec_serv_conf_and_auth, + &srtp_aes_gcm_256_openssl}, #endif #if defined(PJMEDIA_SRTP_HAS_AES_CM_256)&&(PJMEDIA_SRTP_HAS_AES_CM_256!=0) /* cipher AES_CM_256, auth SRTP_HMAC_SHA1, auth tag len = 10 octets */ {"AES_256_CM_HMAC_SHA1_80", SRTP_AES_ICM_256, 46, 14, - SRTP_HMAC_SHA1, 20, 10, 10, sec_serv_conf_and_auth, - NULL, &srtp_crypto_policy_set_aes_cm_256_hmac_sha1_80}, + SRTP_HMAC_SHA1, 20, 10, 10, sec_serv_conf_and_auth, + NULL, &srtp_crypto_policy_set_aes_cm_256_hmac_sha1_80}, /* cipher AES_CM_256, auth SRTP_HMAC_SHA1, auth tag len = 10 octets */ {"AES_256_CM_HMAC_SHA1_32", SRTP_AES_ICM_256, 46, 14, - SRTP_HMAC_SHA1, 20, 4, 10, sec_serv_conf_and_auth, - NULL, &srtp_crypto_policy_set_aes_cm_256_hmac_sha1_32}, + SRTP_HMAC_SHA1, 20, 4, 10, sec_serv_conf_and_auth, + NULL, &srtp_crypto_policy_set_aes_cm_256_hmac_sha1_32}, #endif #if defined(PJMEDIA_SRTP_HAS_AES_CM_192)&&(PJMEDIA_SRTP_HAS_AES_CM_192!=0) /* cipher AES_CM_192, auth SRTP_HMAC_SHA1, auth tag len = 10 octets */ {"AES_192_CM_HMAC_SHA1_80", SRTP_AES_ICM_192, 38, 14, - SRTP_HMAC_SHA1, 20, 10, 10, sec_serv_conf_and_auth, - &srtp_aes_icm_192}, + SRTP_HMAC_SHA1, 20, 10, 10, sec_serv_conf_and_auth, + &srtp_aes_icm_192}, /* cipher AES_CM_192, auth SRTP_HMAC_SHA1, auth tag len = 4 octets */ {"AES_192_CM_HMAC_SHA1_32", SRTP_AES_ICM_192, 38, 14, - SRTP_HMAC_SHA1, 20, 4, 10, sec_serv_conf_and_auth, - &srtp_aes_icm_192}, + SRTP_HMAC_SHA1, 20, 4, 10, sec_serv_conf_and_auth, + &srtp_aes_icm_192}, #endif #if defined(PJMEDIA_SRTP_HAS_AES_GCM_128)&&(PJMEDIA_SRTP_HAS_AES_GCM_128!=0) /* cipher AES_GCM, NULL auth, auth tag len = 16 octets */ {"AEAD_AES_128_GCM", SRTP_AES_GCM_128, 28, 12, - SRTP_NULL_AUTH, 0, 16, 16, sec_serv_conf_and_auth, - &srtp_aes_gcm_128_openssl}, + SRTP_NULL_AUTH, 0, 16, 16, sec_serv_conf_and_auth, + &srtp_aes_gcm_128_openssl}, /* cipher AES_GCM, NULL auth, auth tag len = 8 octets */ {"AEAD_AES_128_GCM_8", SRTP_AES_GCM_128, 28, 12, - SRTP_NULL_AUTH, 0, 8, 8, sec_serv_conf_and_auth, - &srtp_aes_gcm_128_openssl}, + SRTP_NULL_AUTH, 0, 8, 8, sec_serv_conf_and_auth, + &srtp_aes_gcm_128_openssl}, #endif #if defined(PJMEDIA_SRTP_HAS_AES_CM_128)&&(PJMEDIA_SRTP_HAS_AES_CM_128!=0) /* cipher AES_CM_128, auth SRTP_HMAC_SHA1, auth tag len = 10 octets */ {"AES_CM_128_HMAC_SHA1_80", SRTP_AES_ICM_128, 30, 14, - SRTP_HMAC_SHA1, 20, 10, 10, sec_serv_conf_and_auth}, + SRTP_HMAC_SHA1, 20, 10, 10, sec_serv_conf_and_auth}, /* cipher AES_CM_128, auth SRTP_HMAC_SHA1, auth tag len = 4 octets */ {"AES_CM_128_HMAC_SHA1_32", SRTP_AES_ICM_128, 30, 14, - SRTP_HMAC_SHA1, 20, 4, 10, sec_serv_conf_and_auth}, + SRTP_HMAC_SHA1, 20, 4, 10, sec_serv_conf_and_auth}, #endif /* * F8_128_HMAC_SHA1_8 not supported by libsrtp? * {"F8_128_HMAC_SHA1_8", NULL_CIPHER, 0, 0, NULL_AUTH, 0, 0, 0, - * sec_serv_none} + * sec_serv_none} */ }; @@ -233,21 +232,21 @@ static crypto_suite crypto_suites[] = { /* SRTP transport */ typedef struct transport_srtp { - pjmedia_transport base; /**< Base transport interface. */ - pj_pool_t *pool; /**< Pool for transport SRTP. */ - pj_lock_t *mutex; /**< Mutex for libsrtp contexts.*/ - char rtp_tx_buffer[MAX_RTP_BUFFER_LEN]; - char rtcp_tx_buffer[MAX_RTCP_BUFFER_LEN]; + pjmedia_transport base; /**< Base transport interface. */ + pj_pool_t *pool; /**< Pool for transport SRTP. */ + pj_lock_t *mutex; /**< Mutex for libsrtp contexts.*/ + char rtp_tx_buffer[MAX_RTP_BUFFER_LEN]; + char rtcp_tx_buffer[MAX_RTCP_BUFFER_LEN]; pjmedia_srtp_setting setting; - unsigned media_option; - pj_bool_t use_rtcp_mux; /**< Use RTP& RTCP multiplexing?*/ + unsigned media_option; + pj_bool_t use_rtcp_mux; /**< Use RTP& RTCP multiplexing?*/ /* SRTP policy */ - pj_bool_t session_inited; - pj_bool_t offerer_side; - pj_bool_t bypass_srtp; - char tx_key[MAX_KEY_LEN]; - char rx_key[MAX_KEY_LEN]; + pj_bool_t session_inited; + pj_bool_t offerer_side; + pj_bool_t bypass_srtp; + char tx_key[MAX_KEY_LEN]; + char rx_key[MAX_KEY_LEN]; pjmedia_srtp_crypto tx_policy; pjmedia_srtp_crypto rx_policy; @@ -256,35 +255,35 @@ typedef struct transport_srtp pjmedia_srtp_crypto rx_policy_neg; /* libSRTP contexts */ - srtp_t srtp_tx_ctx; - srtp_t srtp_rx_ctx; + srtp_t srtp_tx_ctx; + srtp_t srtp_rx_ctx; /* Stream information */ - void *user_data; - void (*rtp_cb)( void *user_data, - void *pkt, - pj_ssize_t size); - void (*rtp_cb2)(pjmedia_tp_cb_param*); - void (*rtcp_cb)(void *user_data, - void *pkt, - pj_ssize_t size); + void *user_data; + void (*rtp_cb)( void *user_data, + void *pkt, + pj_ssize_t size); + void (*rtp_cb2)(pjmedia_tp_cb_param*); + void (*rtcp_cb)(void *user_data, + void *pkt, + pj_ssize_t size); /* Transport information */ - pjmedia_transport *member_tp; /**< Underlying transport. */ - pj_bool_t member_tp_attached; - pj_bool_t started; + pjmedia_transport *member_tp; /**< Underlying transport. */ + pj_bool_t member_tp_attached; + pj_bool_t started; /* SRTP usage policy of peer. This field is updated when media is starting. * This is useful when SRTP is in optional mode and peer is using mandatory * mode, so when local is about to reinvite/update, it should offer * RTP/SAVP instead of offering RTP/AVP. */ - pjmedia_srtp_use peer_use; + pjmedia_srtp_use peer_use; /* When probation counter > 0, it means SRTP is in probation state, * and it may restart when srtp_unprotect() returns err_status_replay_* */ - unsigned probation_cnt; + unsigned probation_cnt; /* SRTP keying methods. The keying is implemented using media transport * abstraction, so it will also be invoked when the SRTP media transport @@ -296,24 +295,24 @@ typedef struct transport_srtp * removed from the session. And once SRTP key is obtained via a keying * method, any other keying methods will be stopped and destroyed. */ - unsigned all_keying_cnt; - pjmedia_transport *all_keying[MAX_KEYING]; + unsigned all_keying_cnt; + pjmedia_transport *all_keying[MAX_KEYING]; /* Current active SRTP keying methods. */ - unsigned keying_cnt; - pjmedia_transport *keying[MAX_KEYING]; + unsigned keying_cnt; + pjmedia_transport *keying[MAX_KEYING]; /* If not zero, keying nego is ongoing (async-ly, e.g: by DTLS-SRTP). * This field may be updated by keying method. */ - unsigned keying_pending_cnt; + unsigned keying_pending_cnt; /* RTP SSRC in receiving direction, used in getting and setting SRTP * roll over counter (ROC) on SRTP restart. */ - pj_uint32_t rx_ssrc; + pj_uint32_t rx_ssrc; - pj_uint32_t tx_ssrc; + pj_uint32_t tx_ssrc; } transport_srtp; @@ -333,53 +332,53 @@ static void srtp_rtcp_cb( void *user_data, void *pkt, pj_ssize_t size); * These are media transport operations. */ static pj_status_t transport_get_info (pjmedia_transport *tp, - pjmedia_transport_info *info); + pjmedia_transport_info *info); //static pj_status_t transport_attach (pjmedia_transport *tp, -// void *user_data, -// const pj_sockaddr_t *rem_addr, -// const pj_sockaddr_t *rem_rtcp, -// unsigned addr_len, -// void (*rtp_cb)(void*, -// void*, -// pj_ssize_t), -// void (*rtcp_cb)(void*, -// void*, -// pj_ssize_t)); -static void transport_detach (pjmedia_transport *tp, - void *strm); +// void *user_data, +// const pj_sockaddr_t *rem_addr, +// const pj_sockaddr_t *rem_rtcp, +// unsigned addr_len, +// void (*rtp_cb)(void*, +// void*, +// pj_ssize_t), +// void (*rtcp_cb)(void*, +// void*, +// pj_ssize_t)); +static void transport_detach (pjmedia_transport *tp, + void *strm); static pj_status_t transport_send_rtp( pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); static pj_status_t transport_send_rtcp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, - const pj_sockaddr_t *addr, - unsigned addr_len, - const void *pkt, - pj_size_t size); + const pj_sockaddr_t *addr, + unsigned addr_len, + const void *pkt, + pj_size_t size); static pj_status_t transport_media_create(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - unsigned options, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *sdp_pool, + unsigned options, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t transport_encode_sdp(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t transport_media_start (pjmedia_transport *tp, - pj_pool_t *pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t transport_media_stop(pjmedia_transport *tp); static pj_status_t transport_simulate_lost(pjmedia_transport *tp, - pjmedia_dir dir, - unsigned pct_lost); + pjmedia_dir dir, + unsigned pct_lost); static pj_status_t transport_destroy (pjmedia_transport *tp); static pj_status_t transport_attach2 (pjmedia_transport *tp, - pjmedia_transport_attach_param *param); + pjmedia_transport_attach_param *param); @@ -408,7 +407,7 @@ static pj_bool_t srtp_crypto_empty(const pjmedia_srtp_crypto* c); /* Compare crypto, return zero if same */ static int srtp_crypto_cmp(const pjmedia_srtp_crypto* c1, - const pjmedia_srtp_crypto* c2); + const pjmedia_srtp_crypto* c2); /* Start SRTP */ static pj_status_t start_srtp(transport_srtp *srtp); @@ -425,41 +424,41 @@ const char* get_libsrtp_errstr(int err) { #if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0) static char *liberr[] = { - "ok", /* srtp_err_status_ok = 0 */ - "unspecified failure", /* err_status_fail = 1 */ - "unsupported parameter", /* err_status_bad_param = 2 */ - "couldn't allocate memory", /* err_status_alloc_fail = 3 */ - "couldn't deallocate properly", /* err_status_dealloc_fail = 4 */ - "couldn't initialize", /* err_status_init_fail = 5 */ - "can't process as much data as requested", - /* err_status_terminus = 6 */ - "authentication failure", /* err_status_auth_fail = 7 */ - "cipher failure", /* err_status_cipher_fail = 8 */ - "replay check failed (bad index)", /* err_status_replay_fail = 9 */ - "replay check failed (index too old)", - /* err_status_replay_old = 10 */ - "algorithm failed test routine", /* err_status_algo_fail = 11 */ - "unsupported operation", /* err_status_no_such_op = 12 */ - "no appropriate context found", /* err_status_no_ctx = 13 */ - "unable to perform desired validation", - /* err_status_cant_check = 14 */ - "can't use key any more", /* err_status_key_expired = 15 */ - "error in use of socket", /* err_status_socket_err = 16 */ - "error in use POSIX signals", /* err_status_signal_err = 17 */ - "nonce check failed", /* err_status_nonce_bad = 18 */ - "couldn't read data", /* err_status_read_fail = 19 */ - "couldn't write data", /* err_status_write_fail = 20 */ - "error pasring data", /* err_status_parse_err = 21 */ - "error encoding data", /* err_status_encode_err = 22 */ - "error while using semaphores", /* err_status_semaphore_err = 23 */ - "error while using pfkey" /* err_status_pfkey_err = 24 */ + "ok", /* srtp_err_status_ok = 0 */ + "unspecified failure", /* err_status_fail = 1 */ + "unsupported parameter", /* err_status_bad_param = 2 */ + "couldn't allocate memory", /* err_status_alloc_fail = 3 */ + "couldn't deallocate properly", /* err_status_dealloc_fail = 4 */ + "couldn't initialize", /* err_status_init_fail = 5 */ + "can't process as much data as requested", + /* err_status_terminus = 6 */ + "authentication failure", /* err_status_auth_fail = 7 */ + "cipher failure", /* err_status_cipher_fail = 8 */ + "replay check failed (bad index)", /* err_status_replay_fail = 9 */ + "replay check failed (index too old)", + /* err_status_replay_old = 10 */ + "algorithm failed test routine", /* err_status_algo_fail = 11 */ + "unsupported operation", /* err_status_no_such_op = 12 */ + "no appropriate context found", /* err_status_no_ctx = 13 */ + "unable to perform desired validation", + /* err_status_cant_check = 14 */ + "can't use key any more", /* err_status_key_expired = 15 */ + "error in use of socket", /* err_status_socket_err = 16 */ + "error in use POSIX signals", /* err_status_signal_err = 17 */ + "nonce check failed", /* err_status_nonce_bad = 18 */ + "couldn't read data", /* err_status_read_fail = 19 */ + "couldn't write data", /* err_status_write_fail = 20 */ + "error pasring data", /* err_status_parse_err = 21 */ + "error encoding data", /* err_status_encode_err = 22 */ + "error while using semaphores", /* err_status_semaphore_err = 23 */ + "error while using pfkey" /* err_status_pfkey_err = 24 */ }; if (err >= 0 && err < (int)PJ_ARRAY_SIZE(liberr)) { - return liberr[err]; + return liberr[err]; } else { - static char msg[32]; - pj_ansi_snprintf(msg, sizeof(msg), "Unknown libsrtp error %d", err); - return msg; + static char msg[32]; + pj_ansi_snprintf(msg, sizeof(msg), "Unknown libsrtp error %d", err); + return msg; } #else static char msg[32]; @@ -478,17 +477,17 @@ const char* get_libsrtp_errstr(int err) # include "transport_srtp_dtls.c" #else PJ_DEF(pj_status_t) pjmedia_transport_srtp_dtls_start_nego( - pjmedia_transport *srtp, - const pjmedia_srtp_dtls_nego_param *param) + pjmedia_transport *srtp, + const pjmedia_srtp_dtls_nego_param *param) { PJ_UNUSED_ARG(srtp); PJ_UNUSED_ARG(param); return PJ_ENOTSUP; } PJ_DEF(pj_status_t) pjmedia_transport_srtp_dtls_get_fingerprint( - pjmedia_transport *srtp, - const char *hash, - char *buf, pj_size_t *len) + pjmedia_transport *srtp, + const char *hash, + char *buf, pj_size_t *len) { PJ_UNUSED_ARG(srtp); PJ_UNUSED_ARG(hash); @@ -507,19 +506,19 @@ PJ_DEF(pj_status_t) pjmedia_srtp_init_lib(pjmedia_endpt *endpt) pj_status_t status = PJ_SUCCESS; if (libsrtp_initialized) - return PJ_SUCCESS; + return PJ_SUCCESS; #if PJMEDIA_LIBSRTP_AUTO_INIT_DEINIT /* Init libsrtp */ { - srtp_err_status_t err; + srtp_err_status_t err; - err = srtp_init(); - if (err != srtp_err_status_ok) { - PJ_LOG(4, (THIS_FILE, "Failed to initialize libsrtp: %s", - get_libsrtp_errstr(err))); - return PJMEDIA_ERRNO_FROM_LIBSRTP(err); - } + err = srtp_init(); + if (err != srtp_err_status_ok) { + PJ_LOG(4, (THIS_FILE, "Failed to initialize libsrtp: %s", + get_libsrtp_errstr(err))); + return PJMEDIA_ERRNO_FROM_LIBSRTP(err); + } } #endif @@ -529,16 +528,16 @@ PJ_DEF(pj_status_t) pjmedia_srtp_init_lib(pjmedia_endpt *endpt) status = pjmedia_endpt_atexit(endpt, pjmedia_srtp_deinit_lib); if (status != PJ_SUCCESS) { - /* There will be memory leak when it fails to schedule libsrtp - * deinitialization, however the memory leak could be harmless, - * since in modern OS's memory used by an application is released - * when the application terminates. - */ - PJ_PERROR(4, (THIS_FILE, status, - "Failed to register libsrtp deinit.")); + /* There will be memory leak when it fails to schedule libsrtp + * deinitialization, however the memory leak could be harmless, + * since in modern OS's memory used by an application is released + * when the application terminates. + */ + PJ_PERROR(4, (THIS_FILE, status, + "Failed to register libsrtp deinit.")); - /* Ignore this error */ - status = PJ_SUCCESS; + /* Ignore this error */ + status = PJ_SUCCESS; } libsrtp_initialized = PJ_TRUE; @@ -573,8 +572,8 @@ static void pjmedia_srtp_deinit_lib(pjmedia_endpt *endpt) err = srtp_err_status_ok; # endif if (err != srtp_err_status_ok) { - PJ_LOG(4, (THIS_FILE, "Failed to deinitialize libsrtp: %s", - get_libsrtp_errstr(err))); + PJ_LOG(4, (THIS_FILE, "Failed to deinitialize libsrtp: %s", + get_libsrtp_errstr(err))); } #endif // PJMEDIA_LIBSRTP_AUTO_INIT_DEINIT @@ -593,11 +592,11 @@ static int get_crypto_idx(const pj_str_t* crypto_name) /* treat unspecified crypto_name as crypto 'NULL' */ if (crypto_name->slen == 0) - return 0; + return 0; for (i=0; ikey, &c2->key); if (r != 0) - return r; + return r; r = pj_stricmp(&c1->name, &c2->name); if (r != 0) - return r; + return r; return (c1->flags != c2->flags); } @@ -640,7 +639,7 @@ PJ_DEF(void) pjmedia_srtp_setting_default(pjmedia_srtp_setting *opt) * Enumerate all SRTP cryptos, except "NULL". */ PJ_DEF(pj_status_t) pjmedia_srtp_enum_crypto(unsigned *count, - pjmedia_srtp_crypto crypto[]) + pjmedia_srtp_crypto crypto[]) { unsigned i, max; @@ -648,11 +647,11 @@ PJ_DEF(pj_status_t) pjmedia_srtp_enum_crypto(unsigned *count, max = sizeof(crypto_suites) / sizeof(crypto_suites[0]) - 1; if (*count > max) - *count = max; + *count = max; for (i=0; i<*count; ++i) { - pj_bzero(&crypto[i], sizeof(crypto[0])); - crypto[i].name = pj_str(crypto_suites[i+1].name); + pj_bzero(&crypto[i], sizeof(crypto[0])); + crypto[i].name = pj_str(crypto_suites[i+1].name); } return PJ_SUCCESS; @@ -663,7 +662,7 @@ PJ_DEF(pj_status_t) pjmedia_srtp_enum_crypto(unsigned *count, * Enumerate available SRTP keying methods. */ PJ_DEF(pj_status_t) pjmedia_srtp_enum_keying(unsigned *count, - pjmedia_srtp_keying_method keying[]) + pjmedia_srtp_keying_method keying[]) { unsigned max; @@ -674,11 +673,11 @@ PJ_DEF(pj_status_t) pjmedia_srtp_enum_keying(unsigned *count, #if defined(PJMEDIA_SRTP_HAS_SDES) && (PJMEDIA_SRTP_HAS_SDES != 0) if (*count < max) - keying[(*count)++] = PJMEDIA_SRTP_KEYING_SDES; + keying[(*count)++] = PJMEDIA_SRTP_KEYING_SDES; #endif #if defined(PJMEDIA_SRTP_HAS_DTLS) && (PJMEDIA_SRTP_HAS_DTLS != 0) if (*count < max) - keying[(*count)++] = PJMEDIA_SRTP_KEYING_DTLS_SRTP; + keying[(*count)++] = PJMEDIA_SRTP_KEYING_DTLS_SRTP; #endif return PJ_SUCCESS; @@ -689,10 +688,10 @@ PJ_DEF(pj_status_t) pjmedia_srtp_enum_keying(unsigned *count, * Create an SRTP media transport. */ PJ_DEF(pj_status_t) pjmedia_transport_srtp_create( - pjmedia_endpt *endpt, - pjmedia_transport *tp, - const pjmedia_srtp_setting *opt, - pjmedia_transport **p_tp) + pjmedia_endpt *endpt, + pjmedia_transport *tp, + const pjmedia_srtp_setting *opt, + pjmedia_transport **p_tp) { pj_pool_t *pool; transport_srtp *srtp; @@ -703,25 +702,25 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_create( /* Check crypto */ if (opt && opt->use != PJMEDIA_SRTP_DISABLED) { - for (i=0; i < opt->crypto_count; ++i) { - int cs_idx = get_crypto_idx(&opt->crypto[i].name); + for (i=0; i < opt->crypto_count; ++i) { + int cs_idx = get_crypto_idx(&opt->crypto[i].name); - /* check crypto name */ - if (cs_idx == -1) - return PJMEDIA_SRTP_ENOTSUPCRYPTO; + /* check crypto name */ + if (cs_idx == -1) + return PJMEDIA_SRTP_ENOTSUPCRYPTO; - /* check key length */ - if (opt->crypto[i].key.slen && - opt->crypto[i].key.slen < - (pj_ssize_t)crypto_suites[cs_idx].cipher_key_len) - return PJMEDIA_SRTP_EINKEYLEN; - } + /* check key length */ + if (opt->crypto[i].key.slen && + opt->crypto[i].key.slen < + (pj_ssize_t)crypto_suites[cs_idx].cipher_key_len) + return PJMEDIA_SRTP_EINKEYLEN; + } } /* Init libsrtp. */ status = pjmedia_srtp_init_lib(endpt); if (status != PJ_SUCCESS) - return status; + return status; pool = pjmedia_endpt_create_pool(endpt, "srtp%p", 1000, 1000); srtp = PJ_POOL_ZALLOC_T(pool, transport_srtp); @@ -732,49 +731,49 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_create( srtp->probation_cnt = PROBATION_CNT_INIT; if (opt) { - srtp->setting = *opt; - if (opt->use == PJMEDIA_SRTP_DISABLED) - srtp->setting.crypto_count = 0; - - for (i=0; i < srtp->setting.crypto_count; ++i) { - int cs_idx = get_crypto_idx(&opt->crypto[i].name); - pj_str_t tmp_key = opt->crypto[i].key; - - /* re-set crypto */ - srtp->setting.crypto[i].name = pj_str(crypto_suites[cs_idx].name); - /* cut key length */ - if (tmp_key.slen) - tmp_key.slen = crypto_suites[cs_idx].cipher_key_len; - pj_strdup(pool, &srtp->setting.crypto[i].key, &tmp_key); - } + srtp->setting = *opt; + if (opt->use == PJMEDIA_SRTP_DISABLED) + srtp->setting.crypto_count = 0; + + for (i=0; i < srtp->setting.crypto_count; ++i) { + int cs_idx = get_crypto_idx(&opt->crypto[i].name); + pj_str_t tmp_key = opt->crypto[i].key; + + /* re-set crypto */ + srtp->setting.crypto[i].name = pj_str(crypto_suites[cs_idx].name); + /* cut key length */ + if (tmp_key.slen) + tmp_key.slen = crypto_suites[cs_idx].cipher_key_len; + pj_strdup(pool, &srtp->setting.crypto[i].key, &tmp_key); + } } else { - pjmedia_srtp_setting_default(&srtp->setting); + pjmedia_srtp_setting_default(&srtp->setting); } /* If crypto count is set to zero, setup default crypto-suites, * i.e: all available crypto but 'NULL'. */ if (srtp->setting.crypto_count == 0 && - srtp->setting.use != PJMEDIA_SRTP_DISABLED) + srtp->setting.use != PJMEDIA_SRTP_DISABLED) { - srtp->setting.crypto_count = PJMEDIA_SRTP_MAX_CRYPTOS; - pjmedia_srtp_enum_crypto(&srtp->setting.crypto_count, - srtp->setting.crypto); + srtp->setting.crypto_count = PJMEDIA_SRTP_MAX_CRYPTOS; + pjmedia_srtp_enum_crypto(&srtp->setting.crypto_count, + srtp->setting.crypto); } status = pj_lock_create_recursive_mutex(pool, pool->obj_name, - &srtp->mutex); + &srtp->mutex); if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; + pj_pool_release(pool); + return status; } /* Initialize base pjmedia_transport */ pj_memcpy(srtp->base.name, pool->obj_name, PJ_MAX_OBJ_NAME); if (tp) - srtp->base.type = tp->type; + srtp->base.type = tp->type; else - srtp->base.type = PJMEDIA_TRANSPORT_TYPE_UDP; + srtp->base.type = PJMEDIA_TRANSPORT_TYPE_UDP; srtp->base.op = &transport_srtp_op; srtp->base.user_data = srtp->setting.user_data; @@ -786,30 +785,30 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_create( /* If keying count set to zero, setup default keying count & priorities */ if (srtp->setting.keying_count == 0) { - srtp->setting.keying_count = PJMEDIA_SRTP_KEYINGS_COUNT; - pjmedia_srtp_enum_keying(&srtp->setting.keying_count, - srtp->setting.keying); + srtp->setting.keying_count = PJMEDIA_SRTP_KEYINGS_COUNT; + pjmedia_srtp_enum_keying(&srtp->setting.keying_count, + srtp->setting.keying); } /* Initialize SRTP keying method. */ for (i = 0; i < srtp->setting.keying_count && i < MAX_KEYING; ++i) { - switch(srtp->setting.keying[i]) { + switch(srtp->setting.keying[i]) { - case PJMEDIA_SRTP_KEYING_SDES: + case PJMEDIA_SRTP_KEYING_SDES: #if defined(PJMEDIA_SRTP_HAS_SDES) && (PJMEDIA_SRTP_HAS_SDES != 0) - sdes_create(srtp, &srtp->all_keying[srtp->all_keying_cnt++]); + sdes_create(srtp, &srtp->all_keying[srtp->all_keying_cnt++]); #endif - break; + break; - case PJMEDIA_SRTP_KEYING_DTLS_SRTP: + case PJMEDIA_SRTP_KEYING_DTLS_SRTP: #if defined(PJMEDIA_SRTP_HAS_DTLS) && (PJMEDIA_SRTP_HAS_DTLS != 0) - dtls_create(srtp, &srtp->all_keying[srtp->all_keying_cnt++]); + dtls_create(srtp, &srtp->all_keying[srtp->all_keying_cnt++]); #endif - break; + break; - default: - break; - } + default: + break; + } } /* Done */ @@ -823,8 +822,8 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_create( * Get SRTP media transport setting. */ PJ_DEF(pj_status_t) pjmedia_transport_srtp_get_setting( - pjmedia_transport *tp, - pjmedia_srtp_setting *opt) + pjmedia_transport *tp, + pjmedia_srtp_setting *opt) { transport_srtp *srtp = (transport_srtp*) tp; *opt = srtp->setting; @@ -835,8 +834,8 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_get_setting( * Modify SRTP media transport setting. */ PJ_DEF(pj_status_t) pjmedia_transport_srtp_modify_setting( - pjmedia_transport *tp, - const pjmedia_srtp_setting *opt) + pjmedia_transport *tp, + const pjmedia_srtp_setting *opt) { transport_srtp *srtp = (transport_srtp*) tp; srtp->setting = *opt; @@ -848,107 +847,107 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_modify_setting( * Initialize and start SRTP session with the given parameters. */ PJ_DEF(pj_status_t) pjmedia_transport_srtp_start( - pjmedia_transport *tp, - const pjmedia_srtp_crypto *tx, - const pjmedia_srtp_crypto *rx) + pjmedia_transport *tp, + const pjmedia_srtp_crypto *tx, + const pjmedia_srtp_crypto *rx) { transport_srtp *srtp = (transport_srtp*) tp; srtp_policy_t tx_; srtp_policy_t rx_; srtp_err_status_t err; - int cr_tx_idx = 0; - int au_tx_idx = 0; - int cr_rx_idx = 0; - int au_rx_idx = 0; - pj_status_t status = PJ_SUCCESS; + int cr_tx_idx = 0; + int au_tx_idx = 0; + int cr_rx_idx = 0; + int au_rx_idx = 0; + pj_status_t status = PJ_SUCCESS; PJ_ASSERT_RETURN(tp && tx && rx, PJ_EINVAL); pj_lock_acquire(srtp->mutex); if (srtp->session_inited) { - pjmedia_transport_srtp_stop(tp); + pjmedia_transport_srtp_stop(tp); } /* Get encryption and authentication method */ cr_tx_idx = au_tx_idx = get_crypto_idx(&tx->name); if (tx->flags & PJMEDIA_SRTP_NO_ENCRYPTION) - cr_tx_idx = 0; + cr_tx_idx = 0; if (tx->flags & PJMEDIA_SRTP_NO_AUTHENTICATION) - au_tx_idx = 0; + au_tx_idx = 0; cr_rx_idx = au_rx_idx = get_crypto_idx(&rx->name); if (rx->flags & PJMEDIA_SRTP_NO_ENCRYPTION) - cr_rx_idx = 0; + cr_rx_idx = 0; if (rx->flags & PJMEDIA_SRTP_NO_AUTHENTICATION) - au_rx_idx = 0; + au_rx_idx = 0; /* Check whether the crypto-suite requested is supported */ if (cr_tx_idx == -1 || cr_rx_idx == -1 || au_tx_idx == -1 || - au_rx_idx == -1) + au_rx_idx == -1) { - status = PJMEDIA_SRTP_ENOTSUPCRYPTO; - goto on_return; + status = PJMEDIA_SRTP_ENOTSUPCRYPTO; + goto on_return; } /* If all options points to 'NULL' method, just bypass SRTP */ if (cr_tx_idx == 0 && cr_rx_idx == 0 && au_tx_idx == 0 && au_rx_idx == 0) { - srtp->bypass_srtp = PJ_TRUE; - goto on_return; + srtp->bypass_srtp = PJ_TRUE; + goto on_return; } /* Check key length */ if (tx->key.slen != (pj_ssize_t)crypto_suites[cr_tx_idx].cipher_key_len || rx->key.slen != (pj_ssize_t)crypto_suites[cr_rx_idx].cipher_key_len) { - status = PJMEDIA_SRTP_EINKEYLEN; - goto on_return; + status = PJMEDIA_SRTP_EINKEYLEN; + goto on_return; } /* Init transmit direction */ pj_bzero(&tx_, sizeof(srtp_policy_t)); pj_memmove(srtp->tx_key, tx->key.ptr, tx->key.slen); if (cr_tx_idx && au_tx_idx) - tx_.rtp.sec_serv = sec_serv_conf_and_auth; + tx_.rtp.sec_serv = sec_serv_conf_and_auth; else if (cr_tx_idx) - tx_.rtp.sec_serv = sec_serv_conf; + tx_.rtp.sec_serv = sec_serv_conf; else if (au_tx_idx) - tx_.rtp.sec_serv = sec_serv_auth; + tx_.rtp.sec_serv = sec_serv_auth; else - tx_.rtp.sec_serv = sec_serv_none; - tx_.key = (uint8_t*)srtp->tx_key; + tx_.rtp.sec_serv = sec_serv_none; + tx_.key = (uint8_t*)srtp->tx_key; if (srtp->setting.tx_roc.roc != 0 && srtp->setting.tx_roc.ssrc != 0) { - tx_.ssrc.type = ssrc_specific; - tx_.ssrc.value = srtp->setting.tx_roc.ssrc; + tx_.ssrc.type = ssrc_specific; + tx_.ssrc.value = srtp->setting.tx_roc.ssrc; } else { - tx_.ssrc.type = ssrc_any_outbound; - tx_.ssrc.value = 0; + tx_.ssrc.type = ssrc_any_outbound; + tx_.ssrc.value = 0; } - tx_.rtp.cipher_type = crypto_suites[cr_tx_idx].cipher_type; + tx_.rtp.cipher_type = crypto_suites[cr_tx_idx].cipher_type; tx_.rtp.cipher_key_len = crypto_suites[cr_tx_idx].cipher_key_len; - tx_.rtp.auth_type = crypto_suites[au_tx_idx].auth_type; + tx_.rtp.auth_type = crypto_suites[au_tx_idx].auth_type; tx_.rtp.auth_key_len = crypto_suites[au_tx_idx].auth_key_len; tx_.rtp.auth_tag_len = crypto_suites[au_tx_idx].srtp_auth_tag_len; - tx_.rtcp = tx_.rtp; + tx_.rtcp = tx_.rtp; tx_.rtcp.auth_tag_len = crypto_suites[au_tx_idx].srtcp_auth_tag_len; - tx_.next = NULL; + tx_.next = NULL; err = srtp_create(&srtp->srtp_tx_ctx, &tx_); if (err != srtp_err_status_ok) { - status = PJMEDIA_ERRNO_FROM_LIBSRTP(err); - goto on_return; + status = PJMEDIA_ERRNO_FROM_LIBSRTP(err); + goto on_return; } if (srtp->setting.tx_roc.roc != 0 && srtp->setting.tx_roc.ssrc != 0) { - err = srtp_set_stream_roc(srtp->srtp_tx_ctx, - srtp->setting.tx_roc.ssrc, - srtp->setting.tx_roc.roc); - PJ_LOG(4, (THIS_FILE, "Initializing SRTP TX ROC to SSRC %d with " - "ROC %d %s\n", srtp->setting.tx_roc.ssrc, - srtp->setting.tx_roc.roc, - (err == srtp_err_status_ok)? "succeeded": "failed")); + err = srtp_set_stream_roc(srtp->srtp_tx_ctx, + srtp->setting.tx_roc.ssrc, + srtp->setting.tx_roc.roc); + PJ_LOG(4, (THIS_FILE, "Initializing SRTP TX ROC to SSRC %d with " + "ROC %d %s\n", srtp->setting.tx_roc.ssrc, + srtp->setting.tx_roc.roc, + (err == srtp_err_status_ok)? "succeeded": "failed")); } srtp->tx_policy = *tx; pj_strset(&srtp->tx_policy.key, srtp->tx_key, tx->key.slen); @@ -959,48 +958,48 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_start( pj_bzero(&rx_, sizeof(srtp_policy_t)); pj_memmove(srtp->rx_key, rx->key.ptr, rx->key.slen); if (cr_rx_idx && au_rx_idx) - rx_.rtp.sec_serv = sec_serv_conf_and_auth; + rx_.rtp.sec_serv = sec_serv_conf_and_auth; else if (cr_rx_idx) - rx_.rtp.sec_serv = sec_serv_conf; + rx_.rtp.sec_serv = sec_serv_conf; else if (au_rx_idx) - rx_.rtp.sec_serv = sec_serv_auth; + rx_.rtp.sec_serv = sec_serv_auth; else - rx_.rtp.sec_serv = sec_serv_none; - rx_.key = (uint8_t*)srtp->rx_key; + rx_.rtp.sec_serv = sec_serv_none; + rx_.key = (uint8_t*)srtp->rx_key; if (srtp->setting.rx_roc.roc != 0 && srtp->setting.rx_roc.ssrc != 0) { - rx_.ssrc.type = ssrc_specific; - rx_.ssrc.value = srtp->setting.rx_roc.ssrc; + rx_.ssrc.type = ssrc_specific; + rx_.ssrc.value = srtp->setting.rx_roc.ssrc; } else { - rx_.ssrc.type = ssrc_any_inbound; - rx_.ssrc.value = 0; + rx_.ssrc.type = ssrc_any_inbound; + rx_.ssrc.value = 0; } - rx_.rtp.sec_serv = crypto_suites[cr_rx_idx].service; - rx_.rtp.cipher_type = crypto_suites[cr_rx_idx].cipher_type; + rx_.rtp.sec_serv = crypto_suites[cr_rx_idx].service; + rx_.rtp.cipher_type = crypto_suites[cr_rx_idx].cipher_type; rx_.rtp.cipher_key_len = crypto_suites[cr_rx_idx].cipher_key_len; - rx_.rtp.auth_type = crypto_suites[au_rx_idx].auth_type; + rx_.rtp.auth_type = crypto_suites[au_rx_idx].auth_type; rx_.rtp.auth_key_len = crypto_suites[au_rx_idx].auth_key_len; rx_.rtp.auth_tag_len = crypto_suites[au_rx_idx].srtp_auth_tag_len; - rx_.rtcp = rx_.rtp; + rx_.rtcp = rx_.rtp; rx_.rtcp.auth_tag_len = crypto_suites[au_rx_idx].srtcp_auth_tag_len; - rx_.next = NULL; + rx_.next = NULL; err = srtp_create(&srtp->srtp_rx_ctx, &rx_); if (err != srtp_err_status_ok) { - srtp_dealloc(srtp->srtp_tx_ctx); - status = PJMEDIA_ERRNO_FROM_LIBSRTP(err); - goto on_return; + srtp_dealloc(srtp->srtp_tx_ctx); + status = PJMEDIA_ERRNO_FROM_LIBSRTP(err); + goto on_return; } if (srtp->setting.rx_roc.roc != 0 && srtp->setting.rx_roc.ssrc != 0) { - err = srtp_set_stream_roc(srtp->srtp_rx_ctx, - srtp->setting.rx_roc.ssrc, - srtp->setting.rx_roc.roc); - PJ_LOG(4, (THIS_FILE, "Initializing SRTP RX ROC from SSRC %d with " - "ROC %d %s\n", - srtp->setting.rx_roc.ssrc, srtp->setting.rx_roc.roc, - (err == srtp_err_status_ok)? "succeeded": "failed")); + err = srtp_set_stream_roc(srtp->srtp_rx_ctx, + srtp->setting.rx_roc.ssrc, + srtp->setting.rx_roc.roc); + PJ_LOG(4, (THIS_FILE, "Initializing SRTP RX ROC from SSRC %d with " + "ROC %d %s\n", + srtp->setting.rx_roc.ssrc, srtp->setting.rx_roc.roc, + (err == srtp_err_status_ok)? "succeeded": "failed")); } srtp->rx_policy = *rx; pj_strset(&srtp->rx_policy.key, srtp->rx_key, rx->key.slen); @@ -1012,42 +1011,42 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_start( /* Logging stuffs */ #if PJ_LOG_MAX_LEVEL >= 5 { - char b64[PJ_BASE256_TO_BASE64_LEN(MAX_KEY_LEN)]; - int b64_len; - - /* TX crypto and key */ - b64_len = sizeof(b64); - status = pj_base64_encode((pj_uint8_t*)tx->key.ptr, (int)tx->key.slen, - b64, &b64_len); - if (status != PJ_SUCCESS) - b64_len = pj_ansi_sprintf(b64, "--key too long--"); - else - b64[b64_len] = '\0'; - - PJ_LOG(5, (srtp->pool->obj_name, "TX: %s key=%s", - srtp->tx_policy.name.ptr, b64)); - if (srtp->tx_policy.flags) { - PJ_LOG(5,(srtp->pool->obj_name, "TX: disable%s%s", - (cr_tx_idx?"":" enc"), - (au_tx_idx?"":" auth"))); - } - - /* RX crypto and key */ - b64_len = sizeof(b64); - status = pj_base64_encode((pj_uint8_t*)rx->key.ptr, (int)rx->key.slen, - b64, &b64_len); - if (status != PJ_SUCCESS) - b64_len = pj_ansi_sprintf(b64, "--key too long--"); - else - b64[b64_len] = '\0'; - - PJ_LOG(5, (srtp->pool->obj_name, "RX: %s key=%s", - srtp->rx_policy.name.ptr, b64)); - if (srtp->rx_policy.flags) { - PJ_LOG(5,(srtp->pool->obj_name,"RX: disable%s%s", - (cr_rx_idx?"":" enc"), - (au_rx_idx?"":" auth"))); - } + char b64[PJ_BASE256_TO_BASE64_LEN(MAX_KEY_LEN)]; + int b64_len; + + /* TX crypto and key */ + b64_len = sizeof(b64); + status = pj_base64_encode((pj_uint8_t*)tx->key.ptr, (int)tx->key.slen, + b64, &b64_len); + if (status != PJ_SUCCESS) + b64_len = pj_ansi_sprintf(b64, "--key too long--"); + else + b64[b64_len] = '\0'; + + PJ_LOG(5, (srtp->pool->obj_name, "TX: %s key=%s", + srtp->tx_policy.name.ptr, b64)); + if (srtp->tx_policy.flags) { + PJ_LOG(5,(srtp->pool->obj_name, "TX: disable%s%s", + (cr_tx_idx?"":" enc"), + (au_tx_idx?"":" auth"))); + } + + /* RX crypto and key */ + b64_len = sizeof(b64); + status = pj_base64_encode((pj_uint8_t*)rx->key.ptr, (int)rx->key.slen, + b64, &b64_len); + if (status != PJ_SUCCESS) + b64_len = pj_ansi_sprintf(b64, "--key too long--"); + else + b64[b64_len] = '\0'; + + PJ_LOG(5, (srtp->pool->obj_name, "RX: %s key=%s", + srtp->rx_policy.name.ptr, b64)); + if (srtp->rx_policy.flags) { + PJ_LOG(5,(srtp->pool->obj_name,"RX: disable%s%s", + (cr_rx_idx?"":" enc"), + (au_rx_idx?"":" auth"))); + } } #endif @@ -1069,21 +1068,21 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_stop(pjmedia_transport *srtp) pj_lock_acquire(p_srtp->mutex); if (!p_srtp->session_inited) { - pj_lock_release(p_srtp->mutex); - return PJ_SUCCESS; + pj_lock_release(p_srtp->mutex); + return PJ_SUCCESS; } err = srtp_dealloc(p_srtp->srtp_rx_ctx); if (err != srtp_err_status_ok) { - PJ_LOG(4, (p_srtp->pool->obj_name, - "Failed to dealloc RX SRTP context: %s", - get_libsrtp_errstr(err))); + PJ_LOG(4, (p_srtp->pool->obj_name, + "Failed to dealloc RX SRTP context: %s", + get_libsrtp_errstr(err))); } err = srtp_dealloc(p_srtp->srtp_tx_ctx); if (err != srtp_err_status_ok) { - PJ_LOG(4, (p_srtp->pool->obj_name, - "Failed to dealloc TX SRTP context: %s", - get_libsrtp_errstr(err))); + PJ_LOG(4, (p_srtp->pool->obj_name, + "Failed to dealloc TX SRTP context: %s", + get_libsrtp_errstr(err))); } p_srtp->srtp_rx_ctx = NULL; p_srtp->srtp_tx_ctx = NULL; @@ -1102,16 +1101,16 @@ static pj_status_t start_srtp(transport_srtp *srtp) { /* Make sure we have the SRTP policies */ if (srtp_crypto_empty(&srtp->tx_policy_neg) || - srtp_crypto_empty(&srtp->rx_policy_neg)) + srtp_crypto_empty(&srtp->rx_policy_neg)) { - srtp->bypass_srtp = PJ_TRUE; - srtp->peer_use = PJMEDIA_SRTP_DISABLED; - if (srtp->session_inited) { - pjmedia_transport_srtp_stop(&srtp->base); - } + srtp->bypass_srtp = PJ_TRUE; + srtp->peer_use = PJMEDIA_SRTP_DISABLED; + if (srtp->session_inited) { + pjmedia_transport_srtp_stop(&srtp->base); + } - PJ_LOG(4, (srtp->pool->obj_name, "SRTP not active")); - return PJ_SUCCESS; + PJ_LOG(4, (srtp->pool->obj_name, "SRTP not active")); + return PJ_SUCCESS; } /* Got policy_local & policy_remote, let's initalize the SRTP */ @@ -1121,23 +1120,23 @@ static pj_status_t start_srtp(transport_srtp *srtp) * when the SRTP policy settings are updated. */ if (srtp_crypto_cmp(&srtp->tx_policy_neg, &srtp->tx_policy) || - srtp_crypto_cmp(&srtp->rx_policy_neg, &srtp->rx_policy)) + srtp_crypto_cmp(&srtp->rx_policy_neg, &srtp->rx_policy)) { - pj_status_t status; - status = pjmedia_transport_srtp_start(&srtp->base, - &srtp->tx_policy_neg, - &srtp->rx_policy_neg); - if (status != PJ_SUCCESS) - return status; + pj_status_t status; + status = pjmedia_transport_srtp_start(&srtp->base, + &srtp->tx_policy_neg, + &srtp->rx_policy_neg); + if (status != PJ_SUCCESS) + return status; - /* Reset probation counts */ - srtp->probation_cnt = PROBATION_CNT_INIT; + /* Reset probation counts */ + srtp->probation_cnt = PROBATION_CNT_INIT; - PJ_LOG(4, (srtp->pool->obj_name, - "SRTP started, keying=%s, crypto=%s", - ((int)srtp->keying[0]->type==PJMEDIA_SRTP_KEYING_SDES? - "SDES":"DTLS-SRTP"), - srtp->tx_policy.name.ptr)); + PJ_LOG(4, (srtp->pool->obj_name, + "SRTP started, keying=%s, crypto=%s", + ((int)srtp->keying[0]->type==PJMEDIA_SRTP_KEYING_SDES? + "SDES":"DTLS-SRTP"), + srtp->tx_policy.name.ptr)); } srtp->bypass_srtp = PJ_FALSE; @@ -1147,7 +1146,7 @@ static pj_status_t start_srtp(transport_srtp *srtp) PJ_DEF(pjmedia_transport *) pjmedia_transport_srtp_get_member( - pjmedia_transport *tp) + pjmedia_transport *tp) { transport_srtp *srtp = (transport_srtp*) tp; @@ -1158,7 +1157,7 @@ PJ_DEF(pjmedia_transport *) pjmedia_transport_srtp_get_member( static pj_status_t transport_get_info(pjmedia_transport *tp, - pjmedia_transport_info *info) + pjmedia_transport_info *info) { transport_srtp *srtp = (transport_srtp*) tp; pjmedia_srtp_info srtp_info; @@ -1167,9 +1166,9 @@ static pj_status_t transport_get_info(pjmedia_transport *tp, PJ_ASSERT_RETURN(tp && info, PJ_EINVAL); PJ_ASSERT_RETURN(info->specific_info_cnt < - PJMEDIA_TRANSPORT_SPECIFIC_INFO_MAXCNT, PJ_ETOOMANY); + PJMEDIA_TRANSPORT_SPECIFIC_INFO_MAXCNT, PJ_ETOOMANY); PJ_ASSERT_RETURN(sizeof(pjmedia_srtp_info) <= - PJMEDIA_TRANSPORT_SPECIFIC_INFO_MAXSIZE, PJ_ENOMEM); + PJMEDIA_TRANSPORT_SPECIFIC_INFO_MAXSIZE, PJ_ENOMEM); srtp_info.active = srtp->session_inited; srtp_info.rx_policy = srtp->rx_policy; @@ -1181,20 +1180,20 @@ static pj_status_t transport_get_info(pjmedia_transport *tp, pj_bzero(&srtp_info.rx_roc, sizeof(srtp_info.rx_roc)); if (srtp->srtp_rx_ctx && srtp->rx_ssrc != 0) { - srtp_info.rx_roc.ssrc = srtp->rx_ssrc; - srtp_get_stream_roc(srtp->srtp_rx_ctx, srtp->rx_ssrc, - &srtp_info.rx_roc.roc); + srtp_info.rx_roc.ssrc = srtp->rx_ssrc; + srtp_get_stream_roc(srtp->srtp_rx_ctx, srtp->rx_ssrc, + &srtp_info.rx_roc.roc); } else if (srtp->setting.rx_roc.ssrc != 0) { - srtp_info.rx_roc.ssrc = srtp->setting.rx_roc.ssrc; - srtp_info.rx_roc.roc = srtp->setting.rx_roc.roc; + srtp_info.rx_roc.ssrc = srtp->setting.rx_roc.ssrc; + srtp_info.rx_roc.roc = srtp->setting.rx_roc.roc; } if (srtp->srtp_tx_ctx && srtp->tx_ssrc != 0) { - srtp_info.tx_roc.ssrc = srtp->tx_ssrc; - srtp_get_stream_roc(srtp->srtp_tx_ctx, srtp->tx_ssrc, - &srtp_info.tx_roc.roc); + srtp_info.tx_roc.ssrc = srtp->tx_ssrc; + srtp_get_stream_roc(srtp->srtp_tx_ctx, srtp->tx_ssrc, + &srtp_info.tx_roc.roc); } else if (srtp->setting.tx_roc.ssrc != 0) { - srtp_info.tx_roc.ssrc = srtp->setting.tx_roc.ssrc; - srtp_info.tx_roc.roc = srtp->setting.tx_roc.roc; + srtp_info.tx_roc.ssrc = srtp->setting.tx_roc.ssrc; + srtp_info.tx_roc.roc = srtp->setting.tx_roc.roc; } spc_info_idx = info->specific_info_cnt++; @@ -1202,17 +1201,17 @@ static pj_status_t transport_get_info(pjmedia_transport *tp, info->spc_info[spc_info_idx].tp = tp; info->spc_info[spc_info_idx].cbsize = sizeof(srtp_info); pj_memcpy(&info->spc_info[spc_info_idx].buffer, &srtp_info, - sizeof(srtp_info)); + sizeof(srtp_info)); /* Invoke get_info() from any active keying method */ for (i=0; i < srtp->keying_cnt; i++) - pjmedia_transport_get_info(srtp->keying[i], info); + pjmedia_transport_get_info(srtp->keying[i], info); return pjmedia_transport_get_info(srtp->member_tp, info); } static pj_status_t transport_attach2(pjmedia_transport *tp, - pjmedia_transport_attach_param *param) + pjmedia_transport_attach_param *param) { transport_srtp *srtp = (transport_srtp*) tp; pjmedia_transport_attach_param member_param; @@ -1223,13 +1222,13 @@ static pj_status_t transport_attach2(pjmedia_transport *tp, /* Save the callbacks */ pj_lock_acquire(srtp->mutex); if (param->rtp_cb || param->rtp_cb2) { - /* Do not update rtp_cb if not set, as attach() is called by - * keying method. - */ - srtp->rtp_cb = param->rtp_cb; - srtp->rtp_cb2 = param->rtp_cb2; - srtp->rtcp_cb = param->rtcp_cb; - srtp->user_data = param->user_data; + /* Do not update rtp_cb if not set, as attach() is called by + * keying method. + */ + srtp->rtp_cb = param->rtp_cb; + srtp->rtp_cb2 = param->rtp_cb2; + srtp->rtcp_cb = param->rtcp_cb; + srtp->user_data = param->user_data; } pj_lock_release(srtp->mutex); @@ -1241,18 +1240,18 @@ static pj_status_t transport_attach2(pjmedia_transport *tp, member_param.rtcp_cb = &srtp_rtcp_cb; status = pjmedia_transport_attach2(srtp->member_tp, &member_param); if (status != PJ_SUCCESS) { - pj_lock_acquire(srtp->mutex); - srtp->rtp_cb = NULL; - srtp->rtcp_cb = NULL; - srtp->user_data = NULL; - pj_lock_release(srtp->mutex); - return status; + pj_lock_acquire(srtp->mutex); + srtp->rtp_cb = NULL; + srtp->rtcp_cb = NULL; + srtp->user_data = NULL; + pj_lock_release(srtp->mutex); + return status; } /* Check if we are multiplexing RTP & RTCP. */ srtp->use_rtcp_mux = (pj_sockaddr_has_addr(¶m->rem_addr) && - pj_sockaddr_cmp(¶m->rem_addr, - ¶m->rem_rtcp) == 0); + pj_sockaddr_cmp(¶m->rem_addr, + ¶m->rem_rtcp) == 0); srtp->member_tp_attached = PJ_TRUE; return PJ_SUCCESS; } @@ -1265,7 +1264,7 @@ static void transport_detach(pjmedia_transport *tp, void *strm) PJ_ASSERT_ON_FAIL(tp, return); if (srtp->member_tp) { - pjmedia_transport_detach(srtp->member_tp, srtp); + pjmedia_transport_detach(srtp->member_tp, srtp); } /* Clear up application infos from transport */ @@ -1279,8 +1278,8 @@ static void transport_detach(pjmedia_transport *tp, void *strm) } static pj_status_t transport_send_rtp( pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { pj_status_t status; transport_srtp *srtp = (transport_srtp*) tp; @@ -1288,17 +1287,17 @@ static pj_status_t transport_send_rtp( pjmedia_transport *tp, srtp_err_status_t err; if (srtp->bypass_srtp) - return pjmedia_transport_send_rtp(srtp->member_tp, pkt, size); + return pjmedia_transport_send_rtp(srtp->member_tp, pkt, size); if (size > sizeof(srtp->rtp_tx_buffer) - MAX_TRAILER_LEN) - return PJ_ETOOBIG; + return PJ_ETOOBIG; pj_memcpy(srtp->rtp_tx_buffer, pkt, size); pj_lock_acquire(srtp->mutex); if (!srtp->session_inited) { - pj_lock_release(srtp->mutex); - return PJMEDIA_SRTP_EKEYNOTREADY; + pj_lock_release(srtp->mutex); + return PJMEDIA_SRTP_EKEYNOTREADY; } /* Save outgoing SSRC */ @@ -1306,15 +1305,15 @@ static pj_status_t transport_send_rtp( pjmedia_transport *tp, #if TEST_ROC if (srtp->setting.tx_roc.ssrc == 0) { - srtp_err_status_t status; - status = srtp_set_stream_roc(srtp->srtp_tx_ctx, srtp->tx_ssrc, - (srtp->offerer_side? 1: 2)); - if (status == srtp_err_status_ok) { - srtp->setting.tx_roc.ssrc = srtp->tx_ssrc; - srtp->setting.tx_roc.roc = (srtp->offerer_side? 1: 2); - PJ_LOG(4, (THIS_FILE, "Setting TX ROC to SSRC %d to %d", - srtp->tx_ssrc, srtp->setting.tx_roc.roc)); - } + srtp_err_status_t status; + status = srtp_set_stream_roc(srtp->srtp_tx_ctx, srtp->tx_ssrc, + (srtp->offerer_side? 1: 2)); + if (status == srtp_err_status_ok) { + srtp->setting.tx_roc.ssrc = srtp->tx_ssrc; + srtp->setting.tx_roc.roc = (srtp->offerer_side? 1: 2); + PJ_LOG(4, (THIS_FILE, "Setting TX ROC to SSRC %d to %d", + srtp->tx_ssrc, srtp->setting.tx_roc.roc)); + } } #endif @@ -1322,27 +1321,27 @@ static pj_status_t transport_send_rtp( pjmedia_transport *tp, pj_lock_release(srtp->mutex); if (err == srtp_err_status_ok) { - status = pjmedia_transport_send_rtp(srtp->member_tp, - srtp->rtp_tx_buffer, len); + status = pjmedia_transport_send_rtp(srtp->member_tp, + srtp->rtp_tx_buffer, len); } else { - status = PJMEDIA_ERRNO_FROM_LIBSRTP(err); + status = PJMEDIA_ERRNO_FROM_LIBSRTP(err); } return status; } static pj_status_t transport_send_rtcp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { return transport_send_rtcp2(tp, NULL, 0, pkt, size); } static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, - const pj_sockaddr_t *addr, - unsigned addr_len, - const void *pkt, - pj_size_t size) + const pj_sockaddr_t *addr, + unsigned addr_len, + const void *pkt, + pj_size_t size) { pj_status_t status; transport_srtp *srtp = (transport_srtp*) tp; @@ -1350,28 +1349,28 @@ static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, srtp_err_status_t err; if (srtp->bypass_srtp) { - return pjmedia_transport_send_rtcp2(srtp->member_tp, addr, addr_len, - pkt, size); + return pjmedia_transport_send_rtcp2(srtp->member_tp, addr, addr_len, + pkt, size); } if (size > sizeof(srtp->rtcp_tx_buffer) - (MAX_TRAILER_LEN+4)) - return PJ_ETOOBIG; + return PJ_ETOOBIG; pj_memcpy(srtp->rtcp_tx_buffer, pkt, size); pj_lock_acquire(srtp->mutex); if (!srtp->session_inited) { - pj_lock_release(srtp->mutex); - return PJMEDIA_SRTP_EKEYNOTREADY; + pj_lock_release(srtp->mutex); + return PJMEDIA_SRTP_EKEYNOTREADY; } err = srtp_protect_rtcp(srtp->srtp_tx_ctx, srtp->rtcp_tx_buffer, &len); pj_lock_release(srtp->mutex); if (err == srtp_err_status_ok) { - status = pjmedia_transport_send_rtcp2(srtp->member_tp, addr, addr_len, - srtp->rtcp_tx_buffer, len); + status = pjmedia_transport_send_rtcp2(srtp->member_tp, addr, addr_len, + srtp->rtcp_tx_buffer, len); } else { - status = PJMEDIA_ERRNO_FROM_LIBSRTP(err); + status = PJMEDIA_ERRNO_FROM_LIBSRTP(err); } return status; @@ -1379,8 +1378,8 @@ static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, static pj_status_t transport_simulate_lost(pjmedia_transport *tp, - pjmedia_dir dir, - unsigned pct_lost) + pjmedia_dir dir, + unsigned pct_lost) { transport_srtp *srtp = (transport_srtp *) tp; @@ -1402,11 +1401,11 @@ static pj_status_t transport_destroy (pjmedia_transport *tp) * without destroying SRTP transport. */ for (i=0; i < srtp->all_keying_cnt; i++) - pjmedia_transport_close(srtp->all_keying[i]); + pjmedia_transport_close(srtp->all_keying[i]); /* Close member if configured */ if (srtp->setting.close_member_tp && srtp->member_tp) { - pjmedia_transport_close(srtp->member_tp); + pjmedia_transport_close(srtp->member_tp); } status = pjmedia_transport_srtp_stop(tp); @@ -1442,13 +1441,13 @@ static void srtp_rtp_cb(pjmedia_tp_cb_param *param) srtp->rtp_cb2(¶m2); param->rem_switch = param2.rem_switch; } else if (srtp->rtp_cb) { - srtp->rtp_cb(srtp->user_data, pkt, size); - } - return; + srtp->rtp_cb(srtp->user_data, pkt, size); + } + return; } if (size < 0) { - return; + return; } /* Give the packet to keying first by invoking its send_rtp() op. @@ -1458,60 +1457,60 @@ static void srtp_rtp_cb(pjmedia_tp_cb_param *param) * by any keying method in the future. */ { - unsigned i; - pj_status_t status; - for (i=0; i < srtp->keying_cnt; i++) { - if (!srtp->keying[i]->op->send_rtp) - continue; - status = pjmedia_transport_send_rtp(srtp->keying[i], pkt, size); - if (status != PJ_EIGNORED) { - /* Packet is already consumed by the keying method */ - return; - } - } + unsigned i; + pj_status_t status; + for (i=0; i < srtp->keying_cnt; i++) { + if (!srtp->keying[i]->op->send_rtp) + continue; + status = pjmedia_transport_send_rtp(srtp->keying[i], pkt, size); + if (status != PJ_EIGNORED) { + /* Packet is already consumed by the keying method */ + return; + } + } } /* Make sure buffer is 32bit aligned */ PJ_ASSERT_ON_FAIL( (((pj_ssize_t)pkt) & 0x03)==0, return ); if (srtp->probation_cnt > 0) - --srtp->probation_cnt; + --srtp->probation_cnt; pj_lock_acquire(srtp->mutex); if (!srtp->session_inited) { - pj_lock_release(srtp->mutex); - return; + pj_lock_release(srtp->mutex); + return; } /* Check if multiplexing is allowed and the payload indicates RTCP. */ if (srtp->use_rtcp_mux) { - pjmedia_rtp_hdr *hdr = (pjmedia_rtp_hdr *)pkt; + pjmedia_rtp_hdr *hdr = (pjmedia_rtp_hdr *)pkt; - if (hdr->pt >= 64 && hdr->pt <= 95) { - pj_lock_release(srtp->mutex); - srtp_rtcp_cb(srtp, pkt, size); - return; - } + if (hdr->pt >= 64 && hdr->pt <= 95) { + pj_lock_release(srtp->mutex); + srtp_rtcp_cb(srtp, pkt, size); + return; + } } #if TEST_ROC if (srtp->setting.rx_roc.ssrc == 0) { - srtp_err_status_t status; - - srtp->rx_ssrc = ntohl(((pjmedia_rtp_hdr*)pkt)->ssrc); - status = srtp_set_stream_roc(srtp->srtp_rx_ctx, srtp->rx_ssrc, - (srtp->offerer_side? 2: 1)); - if (status == srtp_err_status_ok) { - srtp->setting.rx_roc.ssrc = srtp->rx_ssrc; - srtp->setting.rx_roc.roc = (srtp->offerer_side? 2: 1); - - PJ_LOG(4, (THIS_FILE, "Setting RX ROC from SSRC %d to %d", - srtp->rx_ssrc, srtp->setting.rx_roc.roc)); - } else { - PJ_LOG(4, (THIS_FILE, "Setting RX ROC %s", - get_libsrtp_errstr(status))); - } + srtp_err_status_t status; + + srtp->rx_ssrc = ntohl(((pjmedia_rtp_hdr*)pkt)->ssrc); + status = srtp_set_stream_roc(srtp->srtp_rx_ctx, srtp->rx_ssrc, + (srtp->offerer_side? 2: 1)); + if (status == srtp_err_status_ok) { + srtp->setting.rx_roc.ssrc = srtp->rx_ssrc; + srtp->setting.rx_roc.roc = (srtp->offerer_side? 2: 1); + + PJ_LOG(4, (THIS_FILE, "Setting RX ROC from SSRC %d to %d", + srtp->rx_ssrc, srtp->setting.rx_roc.roc)); + } else { + PJ_LOG(4, (THIS_FILE, "Setting RX ROC %s", + get_libsrtp_errstr(status))); + } } #endif @@ -1519,34 +1518,34 @@ static void srtp_rtp_cb(pjmedia_tp_cb_param *param) #if PJMEDIA_SRTP_CHECK_RTP_SEQ_ON_RESTART if (srtp->probation_cnt > 0 && - (err == srtp_err_status_replay_old || - err == srtp_err_status_replay_fail)) + (err == srtp_err_status_replay_old || + err == srtp_err_status_replay_fail)) { - /* Handle such condition that stream is updated (RTP seq is reinited - * & SRTP is restarted), but some old packets are still coming - * so SRTP is learning wrong RTP seq. While the newly inited RTP seq - * comes, SRTP thinks the RTP seq is replayed, so srtp_unprotect() - * will return err_status_replay_*. Restarting SRTP can resolve this. - */ - pjmedia_srtp_crypto tx, rx; - pj_status_t status; - - tx = srtp->tx_policy; - rx = srtp->rx_policy; - - /* Stop SRTP first, otherwise srtp_start() will maintain current - * roll-over counter. - */ - pjmedia_transport_srtp_stop((pjmedia_transport*)srtp); - - status = pjmedia_transport_srtp_start((pjmedia_transport*)srtp, - &tx, &rx); - if (status != PJ_SUCCESS) { - PJ_LOG(5,(srtp->pool->obj_name, "Failed to restart SRTP, err=%s", - get_libsrtp_errstr(err))); - } else if (!srtp->bypass_srtp) { - err = srtp_unprotect(srtp->srtp_rx_ctx, (pj_uint8_t*)pkt, &len); - } + /* Handle such condition that stream is updated (RTP seq is reinited + * & SRTP is restarted), but some old packets are still coming + * so SRTP is learning wrong RTP seq. While the newly inited RTP seq + * comes, SRTP thinks the RTP seq is replayed, so srtp_unprotect() + * will return err_status_replay_*. Restarting SRTP can resolve this. + */ + pjmedia_srtp_crypto tx, rx; + pj_status_t status; + + tx = srtp->tx_policy; + rx = srtp->rx_policy; + + /* Stop SRTP first, otherwise srtp_start() will maintain current + * roll-over counter. + */ + pjmedia_transport_srtp_stop((pjmedia_transport*)srtp); + + status = pjmedia_transport_srtp_start((pjmedia_transport*)srtp, + &tx, &rx); + if (status != PJ_SUCCESS) { + PJ_LOG(5,(srtp->pool->obj_name, "Failed to restart SRTP, err=%s", + get_libsrtp_errstr(err))); + } else if (!srtp->bypass_srtp) { + err = srtp_unprotect(srtp->srtp_rx_ctx, (pj_uint8_t*)pkt, &len); + } } #if PJMEDIA_SRTP_CHECK_ROC_ON_RESTART else @@ -1555,39 +1554,39 @@ static void srtp_rtp_cb(pjmedia_tp_cb_param *param) #if PJMEDIA_SRTP_CHECK_ROC_ON_RESTART if (srtp->probation_cnt > 0 && err == srtp_err_status_auth_fail && - srtp->setting.prev_rx_roc.ssrc != 0 && - srtp->setting.prev_rx_roc.ssrc == srtp->setting.rx_roc.ssrc && - srtp->setting.prev_rx_roc.roc != srtp->setting.rx_roc.roc) + srtp->setting.prev_rx_roc.ssrc != 0 && + srtp->setting.prev_rx_roc.ssrc == srtp->setting.rx_roc.ssrc && + srtp->setting.prev_rx_roc.roc != srtp->setting.rx_roc.roc) { unsigned roc, new_roc; - srtp_err_status_t status; - - srtp_get_stream_roc(srtp->srtp_rx_ctx, srtp->setting.rx_roc.ssrc, - &roc); - new_roc = (roc == srtp->setting.rx_roc.roc? - srtp->setting.prev_rx_roc.roc: srtp->setting.rx_roc.roc); - status = srtp_set_stream_roc(srtp->srtp_rx_ctx, - srtp->setting.rx_roc.ssrc, new_roc); - if (status == srtp_err_status_ok) { - PJ_LOG(4, (srtp->pool->obj_name, - "Retrying to unprotect SRTP from ROC %d to new ROC %d", - roc, new_roc)); - err = srtp_unprotect(srtp->srtp_rx_ctx, (pj_uint8_t*)pkt, &len); - } + srtp_err_status_t status; + + srtp_get_stream_roc(srtp->srtp_rx_ctx, srtp->setting.rx_roc.ssrc, + &roc); + new_roc = (roc == srtp->setting.rx_roc.roc? + srtp->setting.prev_rx_roc.roc: srtp->setting.rx_roc.roc); + status = srtp_set_stream_roc(srtp->srtp_rx_ctx, + srtp->setting.rx_roc.ssrc, new_roc); + if (status == srtp_err_status_ok) { + PJ_LOG(4, (srtp->pool->obj_name, + "Retrying to unprotect SRTP from ROC %d to new ROC %d", + roc, new_roc)); + err = srtp_unprotect(srtp->srtp_rx_ctx, (pj_uint8_t*)pkt, &len); + } } #endif if (err != srtp_err_status_ok) { - PJ_LOG(5,(srtp->pool->obj_name, - "Failed to unprotect SRTP, pkt size=%d, err=%s", - size, get_libsrtp_errstr(err))); + PJ_LOG(5,(srtp->pool->obj_name, + "Failed to unprotect SRTP, pkt size=%d, err=%s", + size, get_libsrtp_errstr(err))); } else { - cb = srtp->rtp_cb; - cb2 = srtp->rtp_cb2; - cb_data = srtp->user_data; + cb = srtp->rtp_cb; + cb2 = srtp->rtp_cb2; + cb_data = srtp->user_data; - /* Save SSRC after successful SRTP unprotect */ - srtp->rx_ssrc = ntohl(((pjmedia_rtp_hdr*)pkt)->ssrc); + /* Save SSRC after successful SRTP unprotect */ + srtp->rx_ssrc = ntohl(((pjmedia_rtp_hdr*)pkt)->ssrc); } pj_lock_release(srtp->mutex); @@ -1600,7 +1599,7 @@ static void srtp_rtp_cb(pjmedia_tp_cb_param *param) (*cb2)(¶m2); param->rem_switch = param2.rem_switch; } else if (cb) { - (*cb)(cb_data, pkt, len); + (*cb)(cb_data, pkt, len); } } @@ -1616,12 +1615,12 @@ static void srtp_rtcp_cb( void *user_data, void *pkt, pj_ssize_t size) void *cb_data = NULL; if (srtp->bypass_srtp) { - srtp->rtcp_cb(srtp->user_data, pkt, size); - return; + srtp->rtcp_cb(srtp->user_data, pkt, size); + return; } if (size < 0) { - return; + return; } /* Make sure buffer is 32bit aligned */ @@ -1630,32 +1629,32 @@ static void srtp_rtcp_cb( void *user_data, void *pkt, pj_ssize_t size) pj_lock_acquire(srtp->mutex); if (!srtp->session_inited) { - pj_lock_release(srtp->mutex); - return; + pj_lock_release(srtp->mutex); + return; } err = srtp_unprotect_rtcp(srtp->srtp_rx_ctx, (pj_uint8_t*)pkt, &len); if (err != srtp_err_status_ok) { - PJ_LOG(5,(srtp->pool->obj_name, - "Failed to unprotect SRTCP, pkt size=%d, err=%s", - size, get_libsrtp_errstr(err))); + PJ_LOG(5,(srtp->pool->obj_name, + "Failed to unprotect SRTCP, pkt size=%d, err=%s", + size, get_libsrtp_errstr(err))); } else { - cb = srtp->rtcp_cb; - cb_data = srtp->user_data; + cb = srtp->rtcp_cb; + cb_data = srtp->user_data; } pj_lock_release(srtp->mutex); if (cb) { - (*cb)(cb_data, pkt, len); + (*cb)(cb_data, pkt, len); } } static pj_status_t transport_media_create(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - unsigned options, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *sdp_pool, + unsigned options, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { struct transport_srtp *srtp = (struct transport_srtp*) tp; unsigned member_tp_option; @@ -1673,28 +1672,28 @@ static pj_status_t transport_media_create(pjmedia_transport *tp, srtp->offerer_side = (sdp_remote == NULL); if (srtp->offerer_side && srtp->setting.use == PJMEDIA_SRTP_DISABLED) { - /* If we are offerer and SRTP is disabled, simply bypass SRTP and - * skip keying. - */ - srtp->bypass_srtp = PJ_TRUE; - srtp->keying_cnt = 0; + /* If we are offerer and SRTP is disabled, simply bypass SRTP and + * skip keying. + */ + srtp->bypass_srtp = PJ_TRUE; + srtp->keying_cnt = 0; } else { - /* If we are answerer and SRTP is disabled, we need to verify that - * SRTP is disabled too in remote SDP, so we can't just skip keying. - */ - srtp->bypass_srtp = PJ_FALSE; - srtp->keying_cnt = srtp->all_keying_cnt; - for (i = 0; i < srtp->all_keying_cnt; ++i) - srtp->keying[i] = srtp->all_keying[i]; + /* If we are answerer and SRTP is disabled, we need to verify that + * SRTP is disabled too in remote SDP, so we can't just skip keying. + */ + srtp->bypass_srtp = PJ_FALSE; + srtp->keying_cnt = srtp->all_keying_cnt; + for (i = 0; i < srtp->all_keying_cnt; ++i) + srtp->keying[i] = srtp->all_keying[i]; - member_tp_option |= PJMEDIA_TPMED_NO_TRANSPORT_CHECKING; + member_tp_option |= PJMEDIA_TPMED_NO_TRANSPORT_CHECKING; } status = pjmedia_transport_media_create(srtp->member_tp, sdp_pool, - member_tp_option, sdp_remote, - media_index); + member_tp_option, sdp_remote, + media_index); if (status != PJ_SUCCESS) - return status; + return status; /* Invoke media_create() of all keying methods, keying actions for each * SRTP mode: @@ -1710,47 +1709,47 @@ static pj_status_t transport_media_create(pjmedia_transport *tp, * - as answerer, verify SRTP attr in remote SDP. */ for (i=0; i < srtp->keying_cnt; ) { - pj_status_t st; - st = pjmedia_transport_media_create(srtp->keying[i], sdp_pool, - options, sdp_remote, - media_index); - if (st != PJ_SUCCESS) { - /* This keying method returns error, remove it */ - pj_array_erase(srtp->keying, sizeof(srtp->keying[0]), - srtp->keying_cnt, i); - srtp->keying_cnt--; - keying_status = st; - continue; - } else if (srtp->offerer_side) { - /* Currently we can send one keying only in outgoing offer */ - srtp->keying[0] = srtp->keying[i]; - srtp->keying_cnt = 1; - break; - } - - ++i; + pj_status_t st; + st = pjmedia_transport_media_create(srtp->keying[i], sdp_pool, + options, sdp_remote, + media_index); + if (st != PJ_SUCCESS) { + /* This keying method returns error, remove it */ + pj_array_erase(srtp->keying, sizeof(srtp->keying[0]), + srtp->keying_cnt, i); + srtp->keying_cnt--; + keying_status = st; + continue; + } else if (srtp->offerer_side) { + /* Currently we can send one keying only in outgoing offer */ + srtp->keying[0] = srtp->keying[i]; + srtp->keying_cnt = 1; + break; + } + + ++i; } /* All keying method failed to process remote SDP? */ if (srtp->keying_cnt == 0) - return keying_status; + return keying_status; /* Bypass SRTP & skip keying as SRTP is disabled and verification on * remote SDP has been done. */ if (srtp->setting.use == PJMEDIA_SRTP_DISABLED) { - srtp->bypass_srtp = PJ_TRUE; - srtp->keying_cnt = 0; + srtp->bypass_srtp = PJ_TRUE; + srtp->keying_cnt = 0; } return PJ_SUCCESS; } static pj_status_t transport_encode_sdp(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { struct transport_srtp *srtp = (struct transport_srtp*) tp; pj_status_t keying_status = PJ_SUCCESS; @@ -1765,16 +1764,16 @@ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, srtp->offerer_side = (sdp_remote == NULL); if (!srtp->offerer_side && srtp->started) { - /* This is may be incoming reoffer that may change keying */ - srtp->keying_cnt = srtp->all_keying_cnt; - for (i = 0; i < srtp->all_keying_cnt; ++i) - srtp->keying[i] = srtp->all_keying[i]; + /* This is may be incoming reoffer that may change keying */ + srtp->keying_cnt = srtp->all_keying_cnt; + for (i = 0; i < srtp->all_keying_cnt; ++i) + srtp->keying[i] = srtp->all_keying[i]; } status = pjmedia_transport_encode_sdp(srtp->member_tp, sdp_pool, - sdp_local, sdp_remote, media_index); + sdp_local, sdp_remote, media_index); if (status != PJ_SUCCESS) - return status; + return status; /* Invoke encode_sdp() of all keying methods, keying actions for each * SRTP mode: @@ -1792,49 +1791,49 @@ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, * is being used) before touching local SDP. */ for (i=0; i < srtp->keying_cnt; ) { - pj_status_t st; - st = pjmedia_transport_encode_sdp(srtp->keying[i], sdp_pool, - sdp_local, sdp_remote, - media_index); - if (st != PJ_SUCCESS) { - /* This keying method returns error, remove it */ - pj_array_erase(srtp->keying, sizeof(srtp->keying[0]), - srtp->keying_cnt, i); - srtp->keying_cnt--; - keying_status = st; - continue; - } else if (!srtp->offerer_side) { - /* Answer with one keying only */ - srtp->keying[0] = srtp->keying[i]; - srtp->keying_cnt = 1; - break; - } - - i++; + pj_status_t st; + st = pjmedia_transport_encode_sdp(srtp->keying[i], sdp_pool, + sdp_local, sdp_remote, + media_index); + if (st != PJ_SUCCESS) { + /* This keying method returns error, remove it */ + pj_array_erase(srtp->keying, sizeof(srtp->keying[0]), + srtp->keying_cnt, i); + srtp->keying_cnt--; + keying_status = st; + continue; + } else if (!srtp->offerer_side) { + /* Answer with one keying only */ + srtp->keying[0] = srtp->keying[i]; + srtp->keying_cnt = 1; + break; + } + + i++; } /* All keying method failed to process remote SDP? */ if (srtp->keying_cnt == 0) { - if (keying_status != PJ_SUCCESS) { - DEACTIVATE_MEDIA(sdp_pool, sdp_local->media[media_index]); - } - return keying_status; + if (keying_status != PJ_SUCCESS) { + DEACTIVATE_MEDIA(sdp_pool, sdp_local->media[media_index]); + } + return keying_status; } /* Bypass SRTP & skip keying as SRTP is disabled and verification on * remote SDP has been done. */ if (srtp->setting.use == PJMEDIA_SRTP_DISABLED) { - srtp->bypass_srtp = PJ_TRUE; - srtp->keying_cnt = 0; + srtp->bypass_srtp = PJ_TRUE; + srtp->keying_cnt = 0; } if (srtp->keying_cnt != 0) { - /* At this point for now, keying count should be 1 */ - pj_assert(srtp->keying_cnt == 1); - PJ_LOG(4, (srtp->pool->obj_name, "SRTP uses keying method %s", - ((int)srtp->keying[0]->type==PJMEDIA_SRTP_KEYING_SDES? - "SDES":"DTLS-SRTP"))); + /* At this point for now, keying count should be 1 */ + pj_assert(srtp->keying_cnt == 1); + PJ_LOG(4, (srtp->pool->obj_name, "SRTP uses keying method %s", + ((int)srtp->keying[0]->type==PJMEDIA_SRTP_KEYING_SDES? + "SDES":"DTLS-SRTP"))); } return PJ_SUCCESS; @@ -1842,10 +1841,10 @@ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, static pj_status_t transport_media_start(pjmedia_transport *tp, - pj_pool_t *pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { struct transport_srtp *srtp = (struct transport_srtp*) tp; pj_status_t keying_status = PJ_SUCCESS; @@ -1860,10 +1859,10 @@ static pj_status_t transport_media_start(pjmedia_transport *tp, srtp->started = PJ_TRUE; status = pjmedia_transport_media_start(srtp->member_tp, pool, - sdp_local, sdp_remote, - media_index); + sdp_local, sdp_remote, + media_index); if (status != PJ_SUCCESS) - return status; + return status; /* Invoke media_start() of all keying methods, keying actions for each * SRTP mode: @@ -1879,40 +1878,40 @@ static pj_status_t transport_media_start(pjmedia_transport *tp, * encode_sdp()). */ for (i=0; i < srtp->keying_cnt; ) { - status = pjmedia_transport_media_start(srtp->keying[i], pool, - sdp_local, sdp_remote, - media_index); - if (status != PJ_SUCCESS) { - /* This keying method returns error, remove it */ - pj_array_erase(srtp->keying, sizeof(srtp->keying[0]), - srtp->keying_cnt, i); - srtp->keying_cnt--; - keying_status = status; - continue; - } - - if (!srtp_crypto_empty(&srtp->tx_policy_neg) && - !srtp_crypto_empty(&srtp->rx_policy_neg)) - { - /* SRTP nego is done */ - srtp->keying_cnt = 1; - srtp->keying[0] = srtp->keying[i]; - srtp->keying_pending_cnt = 0; - break; - } - - i++; + status = pjmedia_transport_media_start(srtp->keying[i], pool, + sdp_local, sdp_remote, + media_index); + if (status != PJ_SUCCESS) { + /* This keying method returns error, remove it */ + pj_array_erase(srtp->keying, sizeof(srtp->keying[0]), + srtp->keying_cnt, i); + srtp->keying_cnt--; + keying_status = status; + continue; + } + + if (!srtp_crypto_empty(&srtp->tx_policy_neg) && + !srtp_crypto_empty(&srtp->rx_policy_neg)) + { + /* SRTP nego is done */ + srtp->keying_cnt = 1; + srtp->keying[0] = srtp->keying[i]; + srtp->keying_pending_cnt = 0; + break; + } + + i++; } /* All keying method failed to process remote SDP? */ if (srtp->keying_cnt == 0) - return keying_status; + return keying_status; /* If SRTP key is being negotiated, just return now. * The keying method should start the SRTP once keying nego is done. */ if (srtp->keying_pending_cnt) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Start SRTP */ status = start_srtp(srtp); @@ -1933,14 +1932,14 @@ static pj_status_t transport_media_stop(pjmedia_transport *tp) /* Invoke media_stop() of all keying methods */ for (i=0; i < srtp->keying_cnt; ++i) { - pjmedia_transport_media_stop(srtp->keying[i]); + pjmedia_transport_media_stop(srtp->keying[i]); } /* Invoke media_stop() of member tp */ status = pjmedia_transport_media_stop(srtp->member_tp); if (status != PJ_SUCCESS) - PJ_PERROR(4, (srtp->pool->obj_name, status, - "SRTP failed stop underlying media transport.")); + PJ_PERROR(4, (srtp->pool->obj_name, status, + "SRTP failed stop underlying media transport.")); /* Finally, stop SRTP */ return pjmedia_transport_srtp_stop(tp); @@ -1949,15 +1948,15 @@ static pj_status_t transport_media_stop(pjmedia_transport *tp) /* Utility */ PJ_DEF(pj_status_t) pjmedia_transport_srtp_decrypt_pkt(pjmedia_transport *tp, - pj_bool_t is_rtp, - void *pkt, - int *pkt_len) + pj_bool_t is_rtp, + void *pkt, + int *pkt_len) { transport_srtp *srtp = (transport_srtp *)tp; srtp_err_status_t err; if (srtp->bypass_srtp) - return PJ_SUCCESS; + return PJ_SUCCESS; PJ_ASSERT_RETURN(tp && pkt && (*pkt_len>0), PJ_EINVAL); PJ_ASSERT_RETURN(srtp->session_inited, PJ_EINVALIDOP); @@ -1968,25 +1967,25 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_decrypt_pkt(pjmedia_transport *tp, pj_lock_acquire(srtp->mutex); if (!srtp->session_inited) { - pj_lock_release(srtp->mutex); - return PJ_EINVALIDOP; + pj_lock_release(srtp->mutex); + return PJ_EINVALIDOP; } if (is_rtp) - err = srtp_unprotect(srtp->srtp_rx_ctx, pkt, pkt_len); + err = srtp_unprotect(srtp->srtp_rx_ctx, pkt, pkt_len); else - err = srtp_unprotect_rtcp(srtp->srtp_rx_ctx, pkt, pkt_len); + err = srtp_unprotect_rtcp(srtp->srtp_rx_ctx, pkt, pkt_len); if (err != srtp_err_status_ok) { - PJ_LOG(5,(srtp->pool->obj_name, - "Failed to unprotect SRTP, pkt size=%d, err=%s", - *pkt_len, get_libsrtp_errstr(err))); + PJ_LOG(5,(srtp->pool->obj_name, + "Failed to unprotect SRTP, pkt size=%d, err=%s", + *pkt_len, get_libsrtp_errstr(err))); } pj_lock_release(srtp->mutex); return (err==srtp_err_status_ok) ? PJ_SUCCESS : - PJMEDIA_ERRNO_FROM_LIBSRTP(err); + PJMEDIA_ERRNO_FROM_LIBSRTP(err); } #endif diff --git a/pjmedia/src/pjmedia/transport_srtp_dtls.c b/pjmedia/src/pjmedia/transport_srtp_dtls.c index 9242c59500..e454b4bd9a 100644 --- a/pjmedia/src/pjmedia/transport_srtp_dtls.c +++ b/pjmedia/src/pjmedia/transport_srtp_dtls.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2017 Teluu Inc. (http://www.teluu.com) * @@ -34,8 +33,8 @@ #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ defined(OPENSSL_API_COMPAT) && OPENSSL_API_COMPAT >= 0x10100000L -# define X509_get_notBefore(x) X509_getm_notBefore(x) -# define X509_get_notAfter(x) X509_getm_notAfter(x) +# define X509_get_notBefore(x) X509_getm_notBefore(x) +# define X509_get_notAfter(x) X509_getm_notAfter(x) #endif /* Set to 1 to enable DTLS-SRTP debugging */ @@ -43,30 +42,30 @@ /* DTLS-SRTP transport op */ static pj_status_t dtls_media_create (pjmedia_transport *tp, - pj_pool_t *sdp_pool, - unsigned options, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *sdp_pool, + unsigned options, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t dtls_encode_sdp (pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t dtls_media_start (pjmedia_transport *tp, - pj_pool_t *tmp_pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *tmp_pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t dtls_media_stop (pjmedia_transport *tp); -static pj_status_t dtls_destroy (pjmedia_transport *tp); +static pj_status_t dtls_destroy (pjmedia_transport *tp); static pj_status_t dtls_on_recv_rtp (pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); static void on_ice_complete2(pjmedia_transport *tp, - pj_ice_strans_op op, - pj_status_t status, - void *user_data); + pj_ice_strans_op op, + pj_status_t status, + void *user_data); static pjmedia_transport_op dtls_op = @@ -74,7 +73,7 @@ static pjmedia_transport_op dtls_op = NULL, NULL, NULL, - &dtls_on_recv_rtp, // originally send_rtp() + &dtls_on_recv_rtp, // originally send_rtp() NULL, NULL, &dtls_media_create, @@ -98,38 +97,38 @@ typedef enum dtls_setup typedef struct dtls_srtp { - pjmedia_transport base; - pj_pool_t *pool; - transport_srtp *srtp; - - dtls_setup setup; - unsigned long last_err; - pj_bool_t use_ice; - pj_bool_t nego_started; - pj_bool_t nego_completed; - pj_str_t rem_fingerprint; /* Remote fingerprint in SDP */ - pj_status_t rem_fprint_status; /* Fingerprint verif. status */ - pj_sockaddr rem_addr; /* Remote address (from SDP/RTP)*/ - pj_sockaddr rem_rtcp; /* Remote RTCP address (SDP) */ - pj_bool_t pending_start; /* media_start() invoked but DTLS - nego not done yet, so start - the SRTP once the nego done */ - pj_bool_t got_keys; /* DTLS nego done & keys ready */ - pjmedia_srtp_crypto tx_crypto; - pjmedia_srtp_crypto rx_crypto; - - char buf[PJMEDIA_MAX_MTU]; - pjmedia_clock *clock; /* Timer workaround for retrans */ - - SSL_CTX *ossl_ctx; - SSL *ossl_ssl; - BIO *ossl_rbio; - BIO *ossl_wbio; + pjmedia_transport base; + pj_pool_t *pool; + transport_srtp *srtp; + + dtls_setup setup; + unsigned long last_err; + pj_bool_t use_ice; + pj_bool_t nego_started; + pj_bool_t nego_completed; + pj_str_t rem_fingerprint; /* Remote fingerprint in SDP */ + pj_status_t rem_fprint_status; /* Fingerprint verif. status */ + pj_sockaddr rem_addr; /* Remote address (from SDP/RTP)*/ + pj_sockaddr rem_rtcp; /* Remote RTCP address (SDP) */ + pj_bool_t pending_start; /* media_start() invoked but DTLS + nego not done yet, so start + the SRTP once the nego done */ + pj_bool_t got_keys; /* DTLS nego done & keys ready */ + pjmedia_srtp_crypto tx_crypto; + pjmedia_srtp_crypto rx_crypto; + + char buf[PJMEDIA_MAX_MTU]; + pjmedia_clock *clock; /* Timer workaround for retrans */ + + SSL_CTX *ossl_ctx; + SSL *ossl_ssl; + BIO *ossl_rbio; + BIO *ossl_wbio; } dtls_srtp; static const pj_str_t ID_TP_DTLS_SRTP = { "UDP/TLS/RTP/SAVP", 16 }; -static const pj_str_t ID_SETUP = { "setup", 5 }; +static const pj_str_t ID_SETUP = { "setup", 5 }; static const pj_str_t ID_ACTPASS = { "actpass", 7 }; static const pj_str_t ID_ACTIVE = { "active", 6 }; static const pj_str_t ID_PASSIVE = { "passive", 7 }; @@ -164,7 +163,7 @@ static unsigned valid_profiles_cnt; /* Certificate & private key */ -static X509 *dtls_cert; +static X509 *dtls_cert; static EVP_PKEY *dtls_priv_key; static pj_status_t ssl_generate_cert(X509 **p_cert, EVP_PKEY **p_priv_key); @@ -172,57 +171,57 @@ static pj_status_t dtls_init() { /* Make sure OpenSSL library has been initialized */ { - pj_ssl_cipher ciphers[1]; - unsigned cipher_num = 1; - pj_ssl_cipher_get_availables(ciphers, &cipher_num); + pj_ssl_cipher ciphers[1]; + unsigned cipher_num = 1; + pj_ssl_cipher_get_availables(ciphers, &cipher_num); } /* Generate cert if not yet */ if (!dtls_cert) { - pj_status_t status; - status = ssl_generate_cert(&dtls_cert, &dtls_priv_key); - if (status != PJ_SUCCESS) { - pj_perror(4, "DTLS-SRTP", status, - "Failed generating DTLS certificate"); - return status; - } + pj_status_t status; + status = ssl_generate_cert(&dtls_cert, &dtls_priv_key); + if (status != PJ_SUCCESS) { + pj_perror(4, "DTLS-SRTP", status, + "Failed generating DTLS certificate"); + return status; + } } if (valid_profiles_cnt == 0) { - unsigned n, j; - int rc; - char *p, *end, buf[OPENSSL_PROFILE_NUM*25]; - - /* Create DTLS context */ - SSL_CTX *ctx = SSL_CTX_new(DTLS_method()); - if (ctx == NULL) { - return PJ_ENOMEM; - } - - p = buf; - end = buf + sizeof(buf); - for (j=0; j 0) { - PJ_LOG(4,("DTLS-SRTP", "%s profile is supported", buf)); - } else { - PJ_PERROR(4, ("DTLS-SRTP", PJMEDIA_SRTP_DTLS_ENOPROFILE, - "Error getting SRTP profile")); - - return PJMEDIA_SRTP_DTLS_ENOPROFILE; - } + unsigned n, j; + int rc; + char *p, *end, buf[OPENSSL_PROFILE_NUM*25]; + + /* Create DTLS context */ + SSL_CTX *ctx = SSL_CTX_new(DTLS_method()); + if (ctx == NULL) { + return PJ_ENOMEM; + } + + p = buf; + end = buf + sizeof(buf); + for (j=0; j 0) { + PJ_LOG(4,("DTLS-SRTP", "%s profile is supported", buf)); + } else { + PJ_PERROR(4, ("DTLS-SRTP", PJMEDIA_SRTP_DTLS_ENOPROFILE, + "Error getting SRTP profile")); + + return PJMEDIA_SRTP_DTLS_ENOPROFILE; + } } return PJ_SUCCESS; @@ -231,11 +230,11 @@ static pj_status_t dtls_init() static void dtls_deinit() { if (dtls_cert) { - X509_free(dtls_cert); - dtls_cert = NULL; + X509_free(dtls_cert); + dtls_cert = NULL; - EVP_PKEY_free(dtls_priv_key); - dtls_priv_key = NULL; + EVP_PKEY_free(dtls_priv_key); + dtls_priv_key = NULL; } valid_profiles_cnt = 0; @@ -244,13 +243,13 @@ static void dtls_deinit() /* Create DTLS-SRTP keying instance */ static pj_status_t dtls_create(transport_srtp *srtp, - pjmedia_transport **p_keying) + pjmedia_transport **p_keying) { dtls_srtp *ds; pj_pool_t *pool; pool = pj_pool_create(srtp->pool->factory, "dtls%p", - 2000, 256, NULL); + 2000, 256, NULL); ds = PJ_POOL_ZALLOC_T(pool, dtls_srtp); ds->pool = pool; @@ -269,22 +268,22 @@ static pj_status_t dtls_create(transport_srtp *srtp, /** * Mapping from OpenSSL error codes to pjlib error space. */ -#define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + \ - PJ_ERRNO_SPACE_SIZE*6) +#define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + \ + PJ_ERRNO_SPACE_SIZE*6) -#define PJ_SSL_ERRNO_SPACE_SIZE PJ_ERRNO_SPACE_SIZE +#define PJ_SSL_ERRNO_SPACE_SIZE PJ_ERRNO_SPACE_SIZE /* Expected maximum value of reason component in OpenSSL error code */ -#define MAX_OSSL_ERR_REASON 1200 +#define MAX_OSSL_ERR_REASON 1200 static pj_status_t STATUS_FROM_SSL_ERR(dtls_srtp *ds, - unsigned long err) + unsigned long err) { pj_status_t status; /* General SSL error, dig more from OpenSSL error queue */ if (err == SSL_ERROR_SSL) - err = ERR_get_error(); + err = ERR_get_error(); /* OpenSSL error range is much wider than PJLIB errno space, so * if it exceeds the space, only the error reason will be kept. @@ -293,10 +292,10 @@ static pj_status_t STATUS_FROM_SSL_ERR(dtls_srtp *ds, */ status = ERR_GET_LIB(err)*MAX_OSSL_ERR_REASON + ERR_GET_REASON(err); if (status > PJ_SSL_ERRNO_SPACE_SIZE) - status = ERR_GET_REASON(err); + status = ERR_GET_REASON(err); if (status != PJ_SUCCESS) - status += PJ_SSL_ERRNO_START; + status += PJ_SSL_ERRNO_START; ds->last_err = err; return status; @@ -323,24 +322,24 @@ static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx) * be used, otherwise it is SHA-1. */ static pj_status_t ssl_get_fingerprint(X509 *cert, pj_bool_t is_sha256, - char *buf, pj_size_t *buf_len) + char *buf, pj_size_t *buf_len) { unsigned int len, st_out_len, i; unsigned char tmp[EVP_MAX_MD_SIZE]; char *p; if (!X509_digest(cert, (is_sha256?EVP_sha256():EVP_sha1()), tmp, &len)) - return PJ_EUNKNOWN; + return PJ_EUNKNOWN; st_out_len = len*3 + (is_sha256? 7 : 5); if (*buf_len < st_out_len + 1) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; /* Format fingerprint to "SHA-256 XX:XX:XX..." */ p = buf; p += pj_ansi_sprintf(p, "SHA-%s %.2X", (is_sha256?"256":"1"), tmp[0]); for (i=1; iossl_ssl) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Create DTLS context */ ctx = SSL_CTX_new(DTLS_method()); if (ctx == NULL) { - return GET_SSL_STATUS(ds); + return GET_SSL_STATUS(ds); } - if (valid_profiles_cnt == 0) { - return PJMEDIA_SRTP_DTLS_ENOPROFILE; + if (valid_profiles_cnt == 0) { + return PJMEDIA_SRTP_DTLS_ENOPROFILE; } /* Set crypto */ if (1) { - char *p, *end, buf[PJ_ARRAY_SIZE(ossl_profiles)*25]; - unsigned n; - - p = buf; - end = buf + sizeof(buf); - for (i=0; isrtp->setting.crypto_count && p < end; ++i) { - pjmedia_srtp_crypto *crypto = &ds->srtp->setting.crypto[i]; - unsigned j; - for (j=0; j < valid_profiles_cnt; ++j) { - if (!pj_ansi_strcmp(crypto->name.ptr, - valid_pj_profiles_list[j])) - { - n = pj_ansi_snprintf(p, end-p, ":%s", - valid_ossl_profiles_list[j]); - p += n; - break; - } - } - - } - rc = SSL_CTX_set_tlsext_use_srtp(ctx, buf+1); - PJ_LOG(4,(ds->base.name, "Setting crypto [%s], errcode=%d", buf, rc)); - if (rc != 0) { - SSL_CTX_free(ctx); - return GET_SSL_STATUS(ds); - } + char *p, *end, buf[PJ_ARRAY_SIZE(ossl_profiles)*25]; + unsigned n; + + p = buf; + end = buf + sizeof(buf); + for (i=0; isrtp->setting.crypto_count && p < end; ++i) { + pjmedia_srtp_crypto *crypto = &ds->srtp->setting.crypto[i]; + unsigned j; + for (j=0; j < valid_profiles_cnt; ++j) { + if (!pj_ansi_strcmp(crypto->name.ptr, + valid_pj_profiles_list[j])) + { + n = pj_ansi_snprintf(p, end-p, ":%s", + valid_ossl_profiles_list[j]); + p += n; + break; + } + } + + } + rc = SSL_CTX_set_tlsext_use_srtp(ctx, buf+1); + PJ_LOG(4,(ds->base.name, "Setting crypto [%s], errcode=%d", buf, rc)); + if (rc != 0) { + SSL_CTX_free(ctx); + return GET_SSL_STATUS(ds); + } } /* Set ciphers */ @@ -483,18 +482,18 @@ static pj_status_t ssl_create(dtls_srtp *ds) ds->ossl_ctx = ctx; ds->ossl_ssl = SSL_new(ds->ossl_ctx); if (ds->ossl_ssl == NULL) { - SSL_CTX_free(ctx); - return GET_SSL_STATUS(ds); + SSL_CTX_free(ctx); + return GET_SSL_STATUS(ds); } /* Set MTU */ #ifdef DTLS_CTRL_SET_LINK_MTU if (!SSL_ctrl(ds->ossl_ssl, DTLS_CTRL_SET_LINK_MTU, PJMEDIA_MAX_MTU, - NULL)) + NULL)) { - PJ_LOG(4, (ds->base.name, - "Ignored failure in setting MTU to %d (too small?)", - PJMEDIA_MAX_MTU)); + PJ_LOG(4, (ds->base.name, + "Ignored failure in setting MTU to %d (too small?)", + PJMEDIA_MAX_MTU)); } #endif @@ -518,25 +517,25 @@ static void ssl_destroy(dtls_srtp *ds) { /* Destroy SSL instance */ if (ds->ossl_ssl) { - /** - * Avoid calling SSL_shutdown() if handshake wasn't completed. - * OpenSSL 1.0.2f complains if SSL_shutdown() is called during an - * SSL handshake, while previous versions always return 0. - */ - if (SSL_in_init(ds->ossl_ssl) == 0) { - SSL_shutdown(ds->ossl_ssl); - } - SSL_free(ds->ossl_ssl); /* this will also close BIOs */ - ds->ossl_ssl = NULL; - /* thus reset the BIOs as well */ - ds->ossl_rbio = NULL; - ds->ossl_wbio = NULL; + /** + * Avoid calling SSL_shutdown() if handshake wasn't completed. + * OpenSSL 1.0.2f complains if SSL_shutdown() is called during an + * SSL handshake, while previous versions always return 0. + */ + if (SSL_in_init(ds->ossl_ssl) == 0) { + SSL_shutdown(ds->ossl_ssl); + } + SSL_free(ds->ossl_ssl); /* this will also close BIOs */ + ds->ossl_ssl = NULL; + /* thus reset the BIOs as well */ + ds->ossl_rbio = NULL; + ds->ossl_wbio = NULL; } /* Destroy SSL context */ if (ds->ossl_ctx) { - SSL_CTX_free(ds->ossl_ctx); - ds->ossl_ctx = NULL; + SSL_CTX_free(ds->ossl_ctx); + ds->ossl_ctx = NULL; } } @@ -551,8 +550,8 @@ static pj_status_t ssl_get_srtp_material(dtls_srtp *ds) /* Get selected crypto-suite */ profile = SSL_get_selected_srtp_profile(ds->ossl_ssl); if (!profile) { - status = PJMEDIA_SRTP_DTLS_ENOCRYPTO; - goto on_return; + status = PJMEDIA_SRTP_DTLS_ENOCRYPTO; + goto on_return; } tx = &ds->tx_crypto; @@ -560,54 +559,54 @@ static pj_status_t ssl_get_srtp_material(dtls_srtp *ds) pj_bzero(tx, sizeof(*tx)); pj_bzero(rx, sizeof(*rx)); for (i=0; iname, ossl_profiles[i])==0) { - pj_strset2(&tx->name, pj_profiles[i]); - pj_strset2(&rx->name, pj_profiles[i]); - crypto_idx = get_crypto_idx(&tx->name); - break; - } + if (pj_ansi_stricmp(profile->name, ossl_profiles[i])==0) { + pj_strset2(&tx->name, pj_profiles[i]); + pj_strset2(&rx->name, pj_profiles[i]); + crypto_idx = get_crypto_idx(&tx->name); + break; + } } if (crypto_idx == -1) { - status = PJMEDIA_SRTP_ENOTSUPCRYPTO; - goto on_return; + status = PJMEDIA_SRTP_ENOTSUPCRYPTO; + goto on_return; } /* Get keying material from DTLS nego. There seems to be no info about * material length returned by SSL_export_keying_material()? */ rc = SSL_export_keying_material(ds->ossl_ssl, material, sizeof(material), - "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0); + "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0); if (rc == 0) { - status = PJMEDIA_SRTP_EINKEYLEN; - goto on_return; + status = PJMEDIA_SRTP_EINKEYLEN; + goto on_return; } /* Parse SRTP master key & salt from keying material */ { - char *p = (char*)material; - char *k1, *k2; - crypto_suite *cs = &crypto_suites[crypto_idx]; - unsigned key_len, salt_len; - - key_len = cs->cipher_key_len - cs->cipher_salt_len; - salt_len = cs->cipher_salt_len; - - tx->key.ptr = (char*)pj_pool_alloc(ds->pool, key_len+salt_len); - tx->key.slen = key_len+salt_len; - rx->key.ptr = (char*)pj_pool_alloc(ds->pool, key_len+salt_len); - rx->key.slen = key_len+salt_len; - if (ds->setup == DTLS_SETUP_ACTIVE) { - k1 = tx->key.ptr; - k2 = rx->key.ptr; - } else { - k1 = rx->key.ptr; - k2 = tx->key.ptr; - } - pj_memcpy(k1, p, key_len); p += key_len; - pj_memcpy(k2, p, key_len); p += key_len; - pj_memcpy(k1+key_len, p, salt_len); p += salt_len; - pj_memcpy(k2+key_len, p, salt_len); - ds->got_keys = PJ_TRUE; + char *p = (char*)material; + char *k1, *k2; + crypto_suite *cs = &crypto_suites[crypto_idx]; + unsigned key_len, salt_len; + + key_len = cs->cipher_key_len - cs->cipher_salt_len; + salt_len = cs->cipher_salt_len; + + tx->key.ptr = (char*)pj_pool_alloc(ds->pool, key_len+salt_len); + tx->key.slen = key_len+salt_len; + rx->key.ptr = (char*)pj_pool_alloc(ds->pool, key_len+salt_len); + rx->key.slen = key_len+salt_len; + if (ds->setup == DTLS_SETUP_ACTIVE) { + k1 = tx->key.ptr; + k2 = rx->key.ptr; + } else { + k1 = rx->key.ptr; + k2 = tx->key.ptr; + } + pj_memcpy(k1, p, key_len); p += key_len; + pj_memcpy(k2, p, key_len); p += key_len; + pj_memcpy(k1+key_len, p, salt_len); p += salt_len; + pj_memcpy(k2+key_len, p, salt_len); + ds->got_keys = PJ_TRUE; } on_return: @@ -625,28 +624,28 @@ static pj_status_t ssl_match_fingerprint(dtls_srtp *ds) /* Check hash algo, currently we only support SHA-256 & SHA-1 */ if (!pj_strnicmp2(&ds->rem_fingerprint, "SHA-256 ", 8)) - is_sha256 = PJ_TRUE; + is_sha256 = PJ_TRUE; else if (!pj_strnicmp2(&ds->rem_fingerprint, "SHA-1 ", 6)) - is_sha256 = PJ_FALSE; + is_sha256 = PJ_FALSE; else { - PJ_LOG(4,(ds->base.name, "Hash algo specified in remote SDP for " - "its DTLS certificate fingerprint is not supported")); - return PJ_ENOTSUP; + PJ_LOG(4,(ds->base.name, "Hash algo specified in remote SDP for " + "its DTLS certificate fingerprint is not supported")); + return PJ_ENOTSUP; } /* Get remote cert & calculate the hash */ rem_cert = SSL_get_peer_certificate(ds->ossl_ssl); if (!rem_cert) - return PJMEDIA_SRTP_DTLS_EPEERNOCERT; + return PJMEDIA_SRTP_DTLS_EPEERNOCERT; status = ssl_get_fingerprint(rem_cert, is_sha256, buf, &buf_len); X509_free(rem_cert); if (status != PJ_SUCCESS) - return status; + return status; /* Do they match? */ if (pj_stricmp2(&ds->rem_fingerprint, buf)) - return PJMEDIA_SRTP_DTLS_EFPNOTMATCH; + return PJMEDIA_SRTP_DTLS_EFPNOTMATCH; return PJ_SUCCESS; } @@ -670,17 +669,17 @@ static pj_status_t udp_member_transport_media_start(dtls_srtp *ds) pj_status_t status; if (!ds->srtp->member_tp) - return PJ_SUCCESS; + return PJ_SUCCESS; pjmedia_transport_info_init(&info); status = pjmedia_transport_get_info(ds->srtp->member_tp, &info); if (status != PJ_SUCCESS) - return status; + return status; if (info.specific_info_cnt == 1 && - info.spc_info[0].type == PJMEDIA_TRANSPORT_TYPE_UDP) + info.spc_info[0].type == PJMEDIA_TRANSPORT_TYPE_UDP) { - return pjmedia_transport_media_start(ds->srtp->member_tp, 0, 0, 0, 0); + return pjmedia_transport_media_start(ds->srtp->member_tp, 0, 0, 0, 0); } return PJ_SUCCESS; @@ -693,30 +692,30 @@ static pj_status_t ssl_flush_wbio(dtls_srtp *ds) pj_size_t len; pj_status_t status = PJ_SUCCESS; - if (ds->ossl_wbio == NULL) return PJ_EGONE; + if (ds->ossl_wbio == NULL) return PJ_EGONE; /* Check whether there is data to send */ if (BIO_ctrl_pending(ds->ossl_wbio) > 0) { - /* Yes, get and send it */ - len = BIO_read(ds->ossl_wbio, ds->buf, sizeof(ds->buf)); - if (len > 0) { - status = send_raw(ds, ds->buf, len); - if (status != PJ_SUCCESS) { + /* Yes, get and send it */ + len = BIO_read(ds->ossl_wbio, ds->buf, sizeof(ds->buf)); + if (len > 0) { + status = send_raw(ds, ds->buf, len); + if (status != PJ_SUCCESS) { #if DTLS_DEBUG - pj_perror(2, ds->base.name, status, "Send error"); + pj_perror(2, ds->base.name, status, "Send error"); #endif - /* This error should be recoverable, remote will retransmit - * its packet when not receiving from us. - */ - } - } + /* This error should be recoverable, remote will retransmit + * its packet when not receiving from us. + */ + } + } } /* Just return if handshake completion procedure (key parsing, fingerprint * verification, etc) has been done or handshake is still in progress. */ if (ds->nego_completed || !SSL_is_init_finished(ds->ossl_ssl)) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Yes, SSL handshake is done! */ ds->nego_completed = PJ_TRUE; @@ -727,45 +726,45 @@ static pj_status_t ssl_flush_wbio(dtls_srtp *ds) * later in socket context. */ if (ds->clock) - pjmedia_clock_stop(ds->clock); + pjmedia_clock_stop(ds->clock); /* Get SRTP key material */ status = ssl_get_srtp_material(ds); if (status != PJ_SUCCESS) { - pj_perror(4, ds->base.name, status, - "Failed to get SRTP material"); - goto on_return; + pj_perror(4, ds->base.name, status, + "Failed to get SRTP material"); + goto on_return; } /* Verify remote fingerprint if we've already got one from SDP */ if (ds->rem_fingerprint.slen && ds->rem_fprint_status == PJ_EPENDING) { - ds->rem_fprint_status = status = ssl_match_fingerprint(ds); - if (status != PJ_SUCCESS) { - pj_perror(4, ds->base.name, status, - "Fingerprint specified in remote SDP doesn't match " - "to actual remote certificate fingerprint!"); - goto on_return; - } + ds->rem_fprint_status = status = ssl_match_fingerprint(ds); + if (status != PJ_SUCCESS) { + pj_perror(4, ds->base.name, status, + "Fingerprint specified in remote SDP doesn't match " + "to actual remote certificate fingerprint!"); + goto on_return; + } } /* If media_start() has been called, start SRTP now */ if (ds->pending_start) { - ds->pending_start = PJ_FALSE; - ds->srtp->keying_pending_cnt--; + ds->pending_start = PJ_FALSE; + ds->srtp->keying_pending_cnt--; - /* Copy negotiated policy to SRTP */ - ds->srtp->tx_policy_neg = ds->tx_crypto; - ds->srtp->rx_policy_neg = ds->rx_crypto; + /* Copy negotiated policy to SRTP */ + ds->srtp->tx_policy_neg = ds->tx_crypto; + ds->srtp->rx_policy_neg = ds->rx_crypto; - status = start_srtp(ds->srtp); - if (status != PJ_SUCCESS) - pj_perror(4, ds->base.name, status, "Failed starting SRTP"); + status = start_srtp(ds->srtp); + if (status != PJ_SUCCESS) + pj_perror(4, ds->base.name, status, "Failed starting SRTP"); } on_return: if (ds->srtp->setting.cb.on_srtp_nego_complete) { - (*ds->srtp->setting.cb.on_srtp_nego_complete) - (&ds->srtp->base, status); + (*ds->srtp->setting.cb.on_srtp_nego_complete) + (&ds->srtp->base, status); } return status; @@ -779,8 +778,8 @@ static void clock_cb(const pj_timestamp *ts, void *user_data) PJ_UNUSED_ARG(ts); if (ds->ossl_ssl) { - if (DTLSv1_handle_timeout(ds->ossl_ssl) > 0) - ssl_flush_wbio(ds); + if (DTLSv1_handle_timeout(ds->ossl_ssl) > 0) + ssl_flush_wbio(ds); } } @@ -794,54 +793,54 @@ static pj_status_t ssl_handshake(dtls_srtp *ds) /* Init DTLS (if not yet) */ status = ssl_create(ds); if (status != PJ_SUCCESS) - return status; + return status; /* Check if handshake has been initiated or even completed */ if (ds->nego_started || SSL_is_init_finished(ds->ossl_ssl)) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Perform SSL handshake */ if (ds->setup == DTLS_SETUP_ACTIVE) { - SSL_set_connect_state(ds->ossl_ssl); + SSL_set_connect_state(ds->ossl_ssl); } else { - SSL_set_accept_state(ds->ossl_ssl); + SSL_set_accept_state(ds->ossl_ssl); } err = SSL_do_handshake(ds->ossl_ssl); if (err < 0) { - err = SSL_get_error(ds->ossl_ssl, err); - if (err == SSL_ERROR_WANT_READ) { - status = ssl_flush_wbio(ds); - if (status != PJ_SUCCESS) - goto on_return; - } else if (err != SSL_ERROR_NONE) { - /* Handshake fails */ - status = STATUS_FROM_SSL_ERR(ds, err); - pj_perror(2, ds->base.name, status, "SSL_do_handshake() error"); - goto on_return; - } + err = SSL_get_error(ds->ossl_ssl, err); + if (err == SSL_ERROR_WANT_READ) { + status = ssl_flush_wbio(ds); + if (status != PJ_SUCCESS) + goto on_return; + } else if (err != SSL_ERROR_NONE) { + /* Handshake fails */ + status = STATUS_FROM_SSL_ERR(ds, err); + pj_perror(2, ds->base.name, status, "SSL_do_handshake() error"); + goto on_return; + } } /* Create and start clock @4Hz for retransmission */ if (!ds->clock) { - status = pjmedia_clock_create(ds->pool, 4, 1, 1, - PJMEDIA_CLOCK_NO_HIGHEST_PRIO, clock_cb, - ds, &ds->clock); - if (status != PJ_SUCCESS) - goto on_return; + status = pjmedia_clock_create(ds->pool, 4, 1, 1, + PJMEDIA_CLOCK_NO_HIGHEST_PRIO, clock_cb, + ds, &ds->clock); + if (status != PJ_SUCCESS) + goto on_return; } status = pjmedia_clock_start(ds->clock); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Finally, DTLS nego started! */ ds->nego_started = PJ_TRUE; PJ_LOG(4,(ds->base.name, "DTLS-SRTP negotiation initiated as %s", - (ds->setup==DTLS_SETUP_ACTIVE? "client":"server"))); + (ds->setup==DTLS_SETUP_ACTIVE? "client":"server"))); on_return: if (status != PJ_SUCCESS) { - if (ds->clock) - pjmedia_clock_stop(ds->clock); + if (ds->clock) + pjmedia_clock_stop(ds->clock); } return status; } @@ -852,9 +851,9 @@ static pj_status_t ssl_handshake(dtls_srtp *ds) * TODO: check those attributes in a=acap too? */ static pj_status_t parse_setup_finger_attr(dtls_srtp *ds, - pj_bool_t rem_as_offerer, - const pjmedia_sdp_session *sdp, - unsigned media_index) + pj_bool_t rem_as_offerer, + const pjmedia_sdp_session *sdp, + unsigned media_index) { pjmedia_sdp_media *m; pjmedia_sdp_attr *a; @@ -864,48 +863,48 @@ static pj_status_t parse_setup_finger_attr(dtls_srtp *ds, /* Parse a=setup */ a = pjmedia_sdp_media_find_attr(m, &ID_SETUP, NULL); if (!a) - a = pjmedia_sdp_attr_find(sdp->attr_count, - sdp->attr, &ID_SETUP, NULL); + a = pjmedia_sdp_attr_find(sdp->attr_count, + sdp->attr, &ID_SETUP, NULL); if (!a) - return PJMEDIA_SRTP_ESDPAMBIGUEANS; + return PJMEDIA_SRTP_ESDPAMBIGUEANS; if (pj_stristr(&a->value, &ID_PASSIVE) || - (rem_as_offerer && pj_stristr(&a->value, &ID_ACTPASS))) + (rem_as_offerer && pj_stristr(&a->value, &ID_ACTPASS))) { - /* Remote offers/answers 'passive' (or offers 'actpass'), so we are - * the client. - */ - ds->setup = DTLS_SETUP_ACTIVE; + /* Remote offers/answers 'passive' (or offers 'actpass'), so we are + * the client. + */ + ds->setup = DTLS_SETUP_ACTIVE; } else if (pj_stristr(&a->value, &ID_ACTIVE)) { - /* Remote offers/answers 'active' so we are the server. */ - ds->setup = DTLS_SETUP_PASSIVE; + /* Remote offers/answers 'active' so we are the server. */ + ds->setup = DTLS_SETUP_PASSIVE; } else { - /* Unknown value set in remote a=setup */ - return PJMEDIA_SRTP_ESDPAMBIGUEANS; + /* Unknown value set in remote a=setup */ + return PJMEDIA_SRTP_ESDPAMBIGUEANS; } /* Parse a=fingerprint */ a = pjmedia_sdp_media_find_attr(m, &ID_FINGERPRINT, NULL); if (!a) - a = pjmedia_sdp_attr_find(sdp->attr_count, - sdp->attr, &ID_FINGERPRINT, - NULL); + a = pjmedia_sdp_attr_find(sdp->attr_count, + sdp->attr, &ID_FINGERPRINT, + NULL); if (!a) { - /* No fingerprint attribute in remote SDP */ - return PJMEDIA_SRTP_DTLS_ENOFPRINT; + /* No fingerprint attribute in remote SDP */ + return PJMEDIA_SRTP_DTLS_ENOFPRINT; } else { - pj_str_t rem_fp = a->value; - pj_strtrim(&rem_fp); - if (pj_stricmp(&ds->rem_fingerprint, &rem_fp)) - pj_strdup(ds->pool, &ds->rem_fingerprint, &rem_fp); + pj_str_t rem_fp = a->value; + pj_strtrim(&rem_fp); + if (pj_stricmp(&ds->rem_fingerprint, &rem_fp)) + pj_strdup(ds->pool, &ds->rem_fingerprint, &rem_fp); } return PJ_SUCCESS; } static pj_status_t get_rem_addrs(dtls_srtp *ds, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index, pj_sockaddr *rem_rtp, pj_sockaddr *rem_rtcp, pj_bool_t *rtcp_mux) @@ -922,78 +921,78 @@ static pj_status_t get_rem_addrs(dtls_srtp *ds, /* If underlying transport is ICE, get remote addresses from ICE */ if (ds->use_ice) { - pjmedia_transport_info info; - pjmedia_ice_transport_info *ice_info; - - pjmedia_transport_info_init(&info); - pjmedia_transport_get_info(ds->srtp->member_tp, &info); - ice_info = (pjmedia_ice_transport_info*) - pjmedia_transport_info_get_spc_info( - &info, PJMEDIA_TRANSPORT_TYPE_ICE); - if (ice_info) { - *rem_rtp = ice_info->comp[0].rcand_addr; - if (ice_info->comp_cnt > 1) - *rem_rtcp = ice_info->comp[1].rcand_addr; - - use_ice_info = PJ_TRUE; - } + pjmedia_transport_info info; + pjmedia_ice_transport_info *ice_info; + + pjmedia_transport_info_init(&info); + pjmedia_transport_get_info(ds->srtp->member_tp, &info); + ice_info = (pjmedia_ice_transport_info*) + pjmedia_transport_info_get_spc_info( + &info, PJMEDIA_TRANSPORT_TYPE_ICE); + if (ice_info) { + *rem_rtp = ice_info->comp[0].rcand_addr; + if (ice_info->comp_cnt > 1) + *rem_rtcp = ice_info->comp[1].rcand_addr; + + use_ice_info = PJ_TRUE; + } } /* Get remote addresses from SDP */ if (!use_ice_info) { - /* Get RTP address */ - conn = m_rem->conn ? m_rem->conn : sdp_remote->conn; - if (pj_stricmp2(&conn->net_type, "IN")==0) { - if (pj_stricmp2(&conn->addr_type, "IP4")==0) { - af = pj_AF_INET(); - } else if (pj_stricmp2(&conn->addr_type, "IP6")==0) { - af = pj_AF_INET6(); - } - } - if (af != pj_AF_UNSPEC()) { - pj_sockaddr_init(af, rem_rtp, &conn->addr, - m_rem->desc.port); - } else { - return PJ_EAFNOTSUP; - } - - /* Get RTCP address. If "rtcp" attribute is present in the SDP, - * set the RTCP address from that attribute. Otherwise, calculate - * from RTP address. - */ - a = pjmedia_sdp_attr_find2(m_rem->attr_count, m_rem->attr, - "rtcp", NULL); - if (a) { - pjmedia_sdp_rtcp_attr rtcp; - pj_status_t status; - status = pjmedia_sdp_attr_get_rtcp(a, &rtcp); - if (status == PJ_SUCCESS) { - if (rtcp.addr.slen) { - pj_sockaddr_init(af, rem_rtcp, &rtcp.addr, - (pj_uint16_t)rtcp.port); - } else { - pj_sockaddr_init(af, rem_rtcp, NULL, - (pj_uint16_t)rtcp.port); - pj_memcpy(pj_sockaddr_get_addr(rem_rtcp), - pj_sockaddr_get_addr(rem_rtp), - pj_sockaddr_get_addr_len(rem_rtp)); - } - } - } - if (!pj_sockaddr_has_addr(rem_rtcp)) { - int rtcp_port; - pj_memcpy(rem_rtcp, rem_rtp, sizeof(pj_sockaddr)); - rtcp_port = pj_sockaddr_get_port(rem_rtp) + 1; - pj_sockaddr_set_port(rem_rtcp, (pj_uint16_t)rtcp_port); - } + /* Get RTP address */ + conn = m_rem->conn ? m_rem->conn : sdp_remote->conn; + if (pj_stricmp2(&conn->net_type, "IN")==0) { + if (pj_stricmp2(&conn->addr_type, "IP4")==0) { + af = pj_AF_INET(); + } else if (pj_stricmp2(&conn->addr_type, "IP6")==0) { + af = pj_AF_INET6(); + } + } + if (af != pj_AF_UNSPEC()) { + pj_sockaddr_init(af, rem_rtp, &conn->addr, + m_rem->desc.port); + } else { + return PJ_EAFNOTSUP; + } + + /* Get RTCP address. If "rtcp" attribute is present in the SDP, + * set the RTCP address from that attribute. Otherwise, calculate + * from RTP address. + */ + a = pjmedia_sdp_attr_find2(m_rem->attr_count, m_rem->attr, + "rtcp", NULL); + if (a) { + pjmedia_sdp_rtcp_attr rtcp; + pj_status_t status; + status = pjmedia_sdp_attr_get_rtcp(a, &rtcp); + if (status == PJ_SUCCESS) { + if (rtcp.addr.slen) { + pj_sockaddr_init(af, rem_rtcp, &rtcp.addr, + (pj_uint16_t)rtcp.port); + } else { + pj_sockaddr_init(af, rem_rtcp, NULL, + (pj_uint16_t)rtcp.port); + pj_memcpy(pj_sockaddr_get_addr(rem_rtcp), + pj_sockaddr_get_addr(rem_rtp), + pj_sockaddr_get_addr_len(rem_rtp)); + } + } + } + if (!pj_sockaddr_has_addr(rem_rtcp)) { + int rtcp_port; + pj_memcpy(rem_rtcp, rem_rtp, sizeof(pj_sockaddr)); + rtcp_port = pj_sockaddr_get_port(rem_rtp) + 1; + pj_sockaddr_set_port(rem_rtcp, (pj_uint16_t)rtcp_port); + } } /* Check if remote indicates the desire to use rtcp-mux in its SDP. */ if (rtcp_mux) { - a = pjmedia_sdp_attr_find2(m_rem->attr_count, m_rem->attr, - "rtcp-mux", NULL); - *rtcp_mux = (a? PJ_TRUE: PJ_FALSE); + a = pjmedia_sdp_attr_find2(m_rem->attr_count, m_rem->attr, + "rtcp-mux", NULL); + *rtcp_mux = (a? PJ_TRUE: PJ_FALSE); } return PJ_SUCCESS; @@ -1005,35 +1004,35 @@ static pj_status_t get_rem_addrs(dtls_srtp *ds, /* Received packet (SSL handshake) from socket */ static pj_status_t ssl_on_recv_packet(dtls_srtp *ds, - const void *data, pj_size_t len) + const void *data, pj_size_t len) { char tmp[128]; pj_size_t nwritten; - if (ds->ossl_rbio == NULL) return PJ_EGONE; + if (ds->ossl_rbio == NULL) return PJ_EGONE; nwritten = BIO_write(ds->ossl_rbio, data, (int)len); if (nwritten < len) { - /* Error? */ - pj_status_t status; - status = GET_SSL_STATUS(ds); + /* Error? */ + pj_status_t status; + status = GET_SSL_STATUS(ds); #if DTLS_DEBUG - pj_perror(2, ds->base.name, status, "BIO_write() error"); + pj_perror(2, ds->base.name, status, "BIO_write() error"); #endif - return status; + return status; } /* Consume (and ignore) the packet */ while (1) { - int rc = SSL_read(ds->ossl_ssl, tmp, sizeof(tmp)); - if (rc <= 0) { + int rc = SSL_read(ds->ossl_ssl, tmp, sizeof(tmp)); + if (rc <= 0) { #if DTLS_DEBUG - pj_status_t status = GET_SSL_STATUS(ds); - if (status != PJ_SUCCESS) - pj_perror(2, ds->base.name, status, "SSL_read() error"); + pj_status_t status = GET_SSL_STATUS(ds); + if (status != PJ_SUCCESS) + pj_perror(2, ds->base.name, status, "SSL_read() error"); #endif - break; - } + break; + } } /* Flush anything pending in the write BIO */ @@ -1042,9 +1041,9 @@ static pj_status_t ssl_on_recv_packet(dtls_srtp *ds, static void on_ice_complete2(pjmedia_transport *tp, - pj_ice_strans_op op, - pj_status_t status, - void *user_data) + pj_ice_strans_op op, + pj_status_t status, + void *user_data) { dtls_srtp *ds = (dtls_srtp*)user_data; pj_assert(ds); @@ -1052,12 +1051,12 @@ static void on_ice_complete2(pjmedia_transport *tp, PJ_UNUSED_ARG(tp); if (op == PJ_ICE_STRANS_OP_NEGOTIATION && status == PJ_SUCCESS && - ds->setup == DTLS_SETUP_ACTIVE) + ds->setup == DTLS_SETUP_ACTIVE) { - pj_status_t tmp_st; - tmp_st = ssl_handshake(ds); - if (tmp_st != PJ_SUCCESS) - pj_perror(4, ds->base.name, tmp_st, "Failed starting DTLS nego"); + pj_status_t tmp_st; + tmp_st = ssl_handshake(ds); + if (tmp_st != PJ_SUCCESS) + pj_perror(4, ds->base.name, tmp_st, "Failed starting DTLS nego"); } } @@ -1073,19 +1072,19 @@ static void on_ice_complete2(pjmedia_transport *tp, * Originally this is send_rtp() op. */ static pj_status_t dtls_on_recv_rtp( pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { dtls_srtp *ds = (dtls_srtp*)tp; /* Destroy the retransmission clock if handshake has been completed. */ if (ds->clock && ds->nego_completed) { - pjmedia_clock_destroy(ds->clock); - ds->clock = NULL; + pjmedia_clock_destroy(ds->clock); + ds->clock = NULL; } if (size < 1 || !IS_DTLS_PKT(pkt, size)) - return PJ_EIGNORED; + return PJ_EIGNORED; #if DTLS_DEBUG PJ_LOG(2,(ds->base.name, "DTLS-SRTP receiving %d bytes", size)); @@ -1098,56 +1097,56 @@ static pj_status_t dtls_on_recv_rtp( pjmedia_transport *tp, /* Check remote address info, reattach member tp if changed */ if (!ds->use_ice && !ds->nego_completed) { - pjmedia_transport_info info; - pjmedia_transport_get_info(ds->srtp->member_tp, &info); - if (pj_sockaddr_cmp(&ds->rem_addr, &info.src_rtp_name)) { - pjmedia_transport_attach_param ap; - - pj_bzero(&ap, sizeof(ap)); - ap.user_data = ds->srtp; - pj_sockaddr_cp(&ds->rem_addr, &info.src_rtp_name); - pj_sockaddr_cp(&ap.rem_addr, &ds->rem_addr); - ap.addr_len = pj_sockaddr_get_len(&ap.rem_addr); - if (pj_sockaddr_cmp(&info.sock_info.rtp_addr_name, - &info.sock_info.rtcp_addr_name) == 0) - { - /* Using RTP & RTCP multiplexing */ - pj_sockaddr_cp(&ds->rem_rtcp, &ds->rem_addr); - pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_rtcp); - } else if (pj_sockaddr_has_addr(&ds->rem_rtcp)) { - pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_rtcp); - } else { - pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_addr); - pj_sockaddr_set_port(&ap.rem_rtcp, - pj_sockaddr_get_port(&ds->rem_addr)+1); - } - - pjmedia_transport_attach2(&ds->srtp->base, &ap); + pjmedia_transport_info info; + pjmedia_transport_get_info(ds->srtp->member_tp, &info); + if (pj_sockaddr_cmp(&ds->rem_addr, &info.src_rtp_name)) { + pjmedia_transport_attach_param ap; + + pj_bzero(&ap, sizeof(ap)); + ap.user_data = ds->srtp; + pj_sockaddr_cp(&ds->rem_addr, &info.src_rtp_name); + pj_sockaddr_cp(&ap.rem_addr, &ds->rem_addr); + ap.addr_len = pj_sockaddr_get_len(&ap.rem_addr); + if (pj_sockaddr_cmp(&info.sock_info.rtp_addr_name, + &info.sock_info.rtcp_addr_name) == 0) + { + /* Using RTP & RTCP multiplexing */ + pj_sockaddr_cp(&ds->rem_rtcp, &ds->rem_addr); + pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_rtcp); + } else if (pj_sockaddr_has_addr(&ds->rem_rtcp)) { + pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_rtcp); + } else { + pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_addr); + pj_sockaddr_set_port(&ap.rem_rtcp, + pj_sockaddr_get_port(&ds->rem_addr)+1); + } + + pjmedia_transport_attach2(&ds->srtp->base, &ap); #if DTLS_DEBUG - { - char addr[PJ_INET6_ADDRSTRLEN]; - PJ_LOG(2,(ds->base.name, "Re-attached transport to update " - "remote addr=%s:%d", - pj_sockaddr_print(&ap.rem_addr, addr, - sizeof(addr), 2), - pj_sockaddr_get_port(&ap.rem_addr))); - } + { + char addr[PJ_INET6_ADDRSTRLEN]; + PJ_LOG(2,(ds->base.name, "Re-attached transport to update " + "remote addr=%s:%d", + pj_sockaddr_print(&ap.rem_addr, addr, + sizeof(addr), 2), + pj_sockaddr_get_port(&ap.rem_addr))); + } #endif - } + } } /* If our setup is ACTPASS, incoming packet may be a client hello, * so let's update setup to PASSIVE and initiate DTLS handshake. */ if (!ds->nego_started && - (ds->setup == DTLS_SETUP_ACTPASS || ds->setup == DTLS_SETUP_PASSIVE)) + (ds->setup == DTLS_SETUP_ACTPASS || ds->setup == DTLS_SETUP_PASSIVE)) { - pj_status_t status; - ds->setup = DTLS_SETUP_PASSIVE; - status = ssl_handshake(ds); - if (status != PJ_SUCCESS) - return status; + pj_status_t status; + ds->setup = DTLS_SETUP_PASSIVE; + status = ssl_handshake(ds); + if (status != PJ_SUCCESS) + return status; } /* Send it to OpenSSL */ @@ -1156,10 +1155,10 @@ static pj_status_t dtls_on_recv_rtp( pjmedia_transport *tp, } static pj_status_t dtls_media_create( pjmedia_transport *tp, - pj_pool_t *sdp_pool, - unsigned options, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *sdp_pool, + unsigned options, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { dtls_srtp *ds = (dtls_srtp*) tp; pj_status_t status = PJ_SUCCESS; @@ -1172,53 +1171,53 @@ static pj_status_t dtls_media_create( pjmedia_transport *tp, PJ_UNUSED_ARG(options); if (ds->srtp->offerer_side) { - /* As offerer: do nothing. */ + /* As offerer: do nothing. */ } else { - /* As answerer: - * Check for DTLS-SRTP support in remote SDP. Detect remote - * support of DTLS-SRTP by inspecting remote SDP offer for - * SDP a=fingerprint attribute. And currently we only support - * RTP/AVP transports. - */ - pjmedia_sdp_media *m_rem = sdp_remote->media[media_index]; - pjmedia_sdp_attr *attr_fp; - pj_uint32_t rem_proto = 0; - - /* Find SDP a=fingerprint line. */ - attr_fp = pjmedia_sdp_media_find_attr(m_rem, &ID_FINGERPRINT, NULL); - if (!attr_fp) - attr_fp = pjmedia_sdp_attr_find(sdp_remote->attr_count, - sdp_remote->attr, &ID_FINGERPRINT, - NULL); - - /* Get media transport proto */ - rem_proto = pjmedia_sdp_transport_get_proto(&m_rem->desc.transport); - if (!PJMEDIA_TP_PROTO_HAS_FLAG(rem_proto, PJMEDIA_TP_PROTO_RTP_AVP) || - !attr_fp) - { - /* Remote doesn't signal DTLS-SRTP */ - status = PJMEDIA_SRTP_ESDPINTRANSPORT; - goto on_return; - } - - /* Check for a=fingerprint in remote SDP. */ - switch (ds->srtp->setting.use) { - case PJMEDIA_SRTP_DISABLED: - if (attr_fp) { - status = PJMEDIA_SRTP_ESDPINTRANSPORT; - goto on_return; - } - break; - case PJMEDIA_SRTP_OPTIONAL: - break; - case PJMEDIA_SRTP_MANDATORY: - if (!attr_fp) { - /* Should never reach here, this is already checked */ - status = PJMEDIA_SRTP_ESDPINTRANSPORT; - goto on_return; - } - break; - } + /* As answerer: + * Check for DTLS-SRTP support in remote SDP. Detect remote + * support of DTLS-SRTP by inspecting remote SDP offer for + * SDP a=fingerprint attribute. And currently we only support + * RTP/AVP transports. + */ + pjmedia_sdp_media *m_rem = sdp_remote->media[media_index]; + pjmedia_sdp_attr *attr_fp; + pj_uint32_t rem_proto = 0; + + /* Find SDP a=fingerprint line. */ + attr_fp = pjmedia_sdp_media_find_attr(m_rem, &ID_FINGERPRINT, NULL); + if (!attr_fp) + attr_fp = pjmedia_sdp_attr_find(sdp_remote->attr_count, + sdp_remote->attr, &ID_FINGERPRINT, + NULL); + + /* Get media transport proto */ + rem_proto = pjmedia_sdp_transport_get_proto(&m_rem->desc.transport); + if (!PJMEDIA_TP_PROTO_HAS_FLAG(rem_proto, PJMEDIA_TP_PROTO_RTP_AVP) || + !attr_fp) + { + /* Remote doesn't signal DTLS-SRTP */ + status = PJMEDIA_SRTP_ESDPINTRANSPORT; + goto on_return; + } + + /* Check for a=fingerprint in remote SDP. */ + switch (ds->srtp->setting.use) { + case PJMEDIA_SRTP_DISABLED: + if (attr_fp) { + status = PJMEDIA_SRTP_ESDPINTRANSPORT; + goto on_return; + } + break; + case PJMEDIA_SRTP_OPTIONAL: + break; + case PJMEDIA_SRTP_MANDATORY: + if (!attr_fp) { + /* Should never reach here, this is already checked */ + status = PJMEDIA_SRTP_ESDPINTRANSPORT; + goto on_return; + } + break; + } } /* Set remote cert fingerprint verification status to PJ_EPENDING */ @@ -1227,17 +1226,17 @@ static pj_status_t dtls_media_create( pjmedia_transport *tp, on_return: #if DTLS_DEBUG if (status != PJ_SUCCESS) { - pj_perror(4, ds->base.name, status, "dtls_media_create() failed"); + pj_perror(4, ds->base.name, status, "dtls_media_create() failed"); } #endif return status; } static pj_status_t dtls_encode_sdp( pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { dtls_srtp *ds = (dtls_srtp *)tp; pjmedia_sdp_media *m_loc; @@ -1253,44 +1252,44 @@ static pj_status_t dtls_encode_sdp( pjmedia_transport *tp, m_loc = sdp_local->media[media_index]; if (ds->srtp->offerer_side) { - /* As offerer */ - - /* Add attribute a=setup if none (rfc5763 section 5) */ - a = pjmedia_sdp_media_find_attr(m_loc, &ID_SETUP, NULL); - if (!a) - a = pjmedia_sdp_attr_find(sdp_local->attr_count, - sdp_local->attr, &ID_SETUP, NULL); - if (!a) { - pj_str_t val; - - if (ds->setup == DTLS_SETUP_UNKNOWN) - ds->setup = DTLS_SETUP_ACTPASS; - - if (ds->setup == DTLS_SETUP_ACTIVE) - val = ID_ACTIVE; - else if (ds->setup == DTLS_SETUP_PASSIVE) - val = ID_PASSIVE; - else - val = ID_ACTPASS; - a = pjmedia_sdp_attr_create(ds->pool, ID_SETUP.ptr, &val); - pjmedia_sdp_media_add_attr(m_loc, a); - } + /* As offerer */ + + /* Add attribute a=setup if none (rfc5763 section 5) */ + a = pjmedia_sdp_media_find_attr(m_loc, &ID_SETUP, NULL); + if (!a) + a = pjmedia_sdp_attr_find(sdp_local->attr_count, + sdp_local->attr, &ID_SETUP, NULL); + if (!a) { + pj_str_t val; + + if (ds->setup == DTLS_SETUP_UNKNOWN) + ds->setup = DTLS_SETUP_ACTPASS; + + if (ds->setup == DTLS_SETUP_ACTIVE) + val = ID_ACTIVE; + else if (ds->setup == DTLS_SETUP_PASSIVE) + val = ID_PASSIVE; + else + val = ID_ACTPASS; + a = pjmedia_sdp_attr_create(ds->pool, ID_SETUP.ptr, &val); + pjmedia_sdp_media_add_attr(m_loc, a); + } } else { - /* As answerer */ - dtls_setup last_setup = ds->setup; - pj_str_t last_rem_fp = ds->rem_fingerprint; + /* As answerer */ + dtls_setup last_setup = ds->setup; + pj_str_t last_rem_fp = ds->rem_fingerprint; pj_bool_t rem_addr_changed = PJ_FALSE; - /* Parse a=setup and a=fingerprint */ - status = parse_setup_finger_attr(ds, PJ_TRUE, sdp_remote, - media_index); - if (status != PJ_SUCCESS) - goto on_return; + /* Parse a=setup and a=fingerprint */ + status = parse_setup_finger_attr(ds, PJ_TRUE, sdp_remote, + media_index); + if (status != PJ_SUCCESS) + goto on_return; - /* Add attribute a=setup:active/passive if we are client/server. */ - a = pjmedia_sdp_attr_create(ds->pool, ID_SETUP.ptr, - (ds->setup==DTLS_SETUP_ACTIVE? &ID_ACTIVE:&ID_PASSIVE)); - pjmedia_sdp_media_add_attr(m_loc, a); + /* Add attribute a=setup:active/passive if we are client/server. */ + a = pjmedia_sdp_attr_create(ds->pool, ID_SETUP.ptr, + (ds->setup==DTLS_SETUP_ACTIVE? &ID_ACTIVE:&ID_PASSIVE)); + pjmedia_sdp_media_add_attr(m_loc, a); if (last_setup != DTLS_SETUP_UNKNOWN && sdp_remote) { pj_sockaddr rem_rtp; @@ -1300,25 +1299,25 @@ static pj_status_t dtls_encode_sdp( pjmedia_transport *tp, status = get_rem_addrs(ds, sdp_remote, media_index, &rem_rtp, &rem_rtcp, &use_rtcp_mux); if (status == PJ_SUCCESS) { - if (use_rtcp_mux) { - /* Remote indicates it wants to use rtcp-mux */ - pjmedia_transport_info info; - - pjmedia_transport_info_init(&info); - pjmedia_transport_get_info(ds->srtp->member_tp, &info); - if (pj_sockaddr_cmp(&info.sock_info.rtp_addr_name, - &info.sock_info.rtcp_addr_name)) - { - /* But we do not wish to use rtcp mux */ - use_rtcp_mux = PJ_FALSE; - } - } + if (use_rtcp_mux) { + /* Remote indicates it wants to use rtcp-mux */ + pjmedia_transport_info info; + + pjmedia_transport_info_init(&info); + pjmedia_transport_get_info(ds->srtp->member_tp, &info); + if (pj_sockaddr_cmp(&info.sock_info.rtp_addr_name, + &info.sock_info.rtcp_addr_name)) + { + /* But we do not wish to use rtcp mux */ + use_rtcp_mux = PJ_FALSE; + } + } if (pj_sockaddr_has_addr(&ds->rem_addr) && - pj_sockaddr_has_addr(&rem_rtp) && - (pj_sockaddr_cmp(&ds->rem_addr, &rem_rtp) || + pj_sockaddr_has_addr(&rem_rtp) && + (pj_sockaddr_cmp(&ds->rem_addr, &rem_rtp) || (!use_rtcp_mux && - pj_sockaddr_has_addr(&ds->rem_rtcp) && - pj_sockaddr_has_addr(&rem_rtcp) && + pj_sockaddr_has_addr(&ds->rem_rtcp) && + pj_sockaddr_has_addr(&rem_rtcp) && pj_sockaddr_cmp(&ds->rem_rtcp, &rem_rtcp)))) { rem_addr_changed = PJ_TRUE; @@ -1326,20 +1325,20 @@ static pj_status_t dtls_encode_sdp( pjmedia_transport *tp, } } - /* Check if remote signals DTLS re-nego by changing its - * setup/fingerprint in SDP or media transport address in SDP. - */ - if ((last_setup != DTLS_SETUP_UNKNOWN && last_setup != ds->setup) || - (last_rem_fp.slen && - pj_memcmp(&last_rem_fp, &ds->rem_fingerprint, sizeof(pj_str_t)))|| + /* Check if remote signals DTLS re-nego by changing its + * setup/fingerprint in SDP or media transport address in SDP. + */ + if ((last_setup != DTLS_SETUP_UNKNOWN && last_setup != ds->setup) || + (last_rem_fp.slen && + pj_memcmp(&last_rem_fp, &ds->rem_fingerprint, sizeof(pj_str_t)))|| (rem_addr_changed)) - { - ssl_destroy(ds); - ds->nego_started = PJ_FALSE; - ds->nego_completed = PJ_FALSE; - ds->got_keys = PJ_FALSE; - ds->rem_fprint_status = PJ_EPENDING; - } + { + ssl_destroy(ds); + ds->nego_started = PJ_FALSE; + ds->nego_completed = PJ_FALSE; + ds->got_keys = PJ_FALSE; + ds->rem_fprint_status = PJ_EPENDING; + } } /* Set media transport to UDP/TLS/RTP/SAVP if we are the offerer, @@ -1347,88 +1346,88 @@ static pj_status_t dtls_encode_sdp( pjmedia_transport *tp, * UDP/TLS/RTP/SAVP in remote offer though). */ if (ds->srtp->offerer_side) { - m_loc->desc.transport = ID_TP_DTLS_SRTP; + m_loc->desc.transport = ID_TP_DTLS_SRTP; } else { - m_loc->desc.transport = - sdp_remote->media[media_index]->desc.transport; + m_loc->desc.transport = + sdp_remote->media[media_index]->desc.transport; } /* Add a=fingerprint attribute, fingerprint of our TLS certificate */ { - char buf[128]; - pj_size_t buf_len = sizeof(buf); - pj_str_t fp; + char buf[128]; + pj_size_t buf_len = sizeof(buf); + pj_str_t fp; - status = ssl_get_fingerprint(dtls_cert, PJ_TRUE, buf, &buf_len); - if (status != PJ_SUCCESS) - goto on_return; + status = ssl_get_fingerprint(dtls_cert, PJ_TRUE, buf, &buf_len); + if (status != PJ_SUCCESS) + goto on_return; - pj_strset(&fp, buf, buf_len); - a = pjmedia_sdp_attr_create(ds->pool, ID_FINGERPRINT.ptr, &fp); - pjmedia_sdp_media_add_attr(m_loc, a); + pj_strset(&fp, buf, buf_len); + a = pjmedia_sdp_attr_create(ds->pool, ID_FINGERPRINT.ptr, &fp); + pjmedia_sdp_media_add_attr(m_loc, a); } if (ds->nego_completed) { - /* This is subsequent SDP offer/answer and no DTLS re-nego has been - * signalled. - */ - goto on_return; + /* This is subsequent SDP offer/answer and no DTLS re-nego has been + * signalled. + */ + goto on_return; } /* Attach member transport, so we can receive DTLS init (if our setup * is PASSIVE/ACTPASS) or send DTLS init (if our setup is ACTIVE). */ { - pjmedia_transport_attach_param ap; - pjmedia_transport_info info; + pjmedia_transport_attach_param ap; + pjmedia_transport_info info; - pj_bzero(&ap, sizeof(ap)); - ap.user_data = ds->srtp; - pjmedia_transport_get_info(ds->srtp->member_tp, &info); + pj_bzero(&ap, sizeof(ap)); + ap.user_data = ds->srtp; + pjmedia_transport_get_info(ds->srtp->member_tp, &info); if (sdp_remote) { get_rem_addrs(ds, sdp_remote, media_index, &ds->rem_addr, &ds->rem_rtcp, NULL); } - if (pj_sockaddr_has_addr(&ds->rem_addr)) { - pj_sockaddr_cp(&ap.rem_addr, &ds->rem_addr); - } else if (pj_sockaddr_has_addr(&info.sock_info.rtp_addr_name)) { - pj_sockaddr_cp(&ap.rem_addr, &info.sock_info.rtp_addr_name); - } else { - pj_sockaddr_init(pj_AF_INET(), &ap.rem_addr, 0, 0); - } - - if (pj_sockaddr_cmp(&info.sock_info.rtp_addr_name, - &info.sock_info.rtcp_addr_name) == 0) - { - /* Using RTP & RTCP multiplexing */ - pj_sockaddr_cp(&ap.rem_rtcp, &ap.rem_addr); - } else if (pj_sockaddr_has_addr(&ds->rem_rtcp)) { - pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_rtcp); - } else if (pj_sockaddr_has_addr(&info.sock_info.rtcp_addr_name)) { - pj_sockaddr_cp(&ap.rem_rtcp, &info.sock_info.rtcp_addr_name); - } else { - pj_sockaddr_init(pj_AF_INET(), &ap.rem_rtcp, 0, 0); - } - - ap.addr_len = pj_sockaddr_get_len(&ap.rem_addr); - status = pjmedia_transport_attach2(&ds->srtp->base, &ap); - if (status != PJ_SUCCESS) - goto on_return; - - /* Start member transport if it is UDP, so we can receive packet - * (see also #2097). - */ - udp_member_transport_media_start(ds); + if (pj_sockaddr_has_addr(&ds->rem_addr)) { + pj_sockaddr_cp(&ap.rem_addr, &ds->rem_addr); + } else if (pj_sockaddr_has_addr(&info.sock_info.rtp_addr_name)) { + pj_sockaddr_cp(&ap.rem_addr, &info.sock_info.rtp_addr_name); + } else { + pj_sockaddr_init(pj_AF_INET(), &ap.rem_addr, 0, 0); + } + + if (pj_sockaddr_cmp(&info.sock_info.rtp_addr_name, + &info.sock_info.rtcp_addr_name) == 0) + { + /* Using RTP & RTCP multiplexing */ + pj_sockaddr_cp(&ap.rem_rtcp, &ap.rem_addr); + } else if (pj_sockaddr_has_addr(&ds->rem_rtcp)) { + pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_rtcp); + } else if (pj_sockaddr_has_addr(&info.sock_info.rtcp_addr_name)) { + pj_sockaddr_cp(&ap.rem_rtcp, &info.sock_info.rtcp_addr_name); + } else { + pj_sockaddr_init(pj_AF_INET(), &ap.rem_rtcp, 0, 0); + } + + ap.addr_len = pj_sockaddr_get_len(&ap.rem_addr); + status = pjmedia_transport_attach2(&ds->srtp->base, &ap); + if (status != PJ_SUCCESS) + goto on_return; + + /* Start member transport if it is UDP, so we can receive packet + * (see also #2097). + */ + udp_member_transport_media_start(ds); #if DTLS_DEBUG - { - char addr[PJ_INET6_ADDRSTRLEN]; - PJ_LOG(2,(ds->base.name, "Attached transport, remote addr=%s:%d", - pj_sockaddr_print(&ap.rem_addr, addr, sizeof(addr), 2), - pj_sockaddr_get_port(&ap.rem_addr))); - } + { + char addr[PJ_INET6_ADDRSTRLEN]; + PJ_LOG(2,(ds->base.name, "Attached transport, remote addr=%s:%d", + pj_sockaddr_print(&ap.rem_addr, addr, sizeof(addr), 2), + pj_sockaddr_get_port(&ap.rem_addr))); + } #endif } @@ -1436,27 +1435,27 @@ static pj_status_t dtls_encode_sdp( pjmedia_transport *tp, * start DTLS nego. */ if (ds->setup == DTLS_SETUP_ACTIVE) { - pjmedia_transport_info info; - pjmedia_ice_transport_info *ice_info; - - pjmedia_transport_info_init(&info); - pjmedia_transport_get_info(ds->srtp->member_tp, &info); - ice_info = (pjmedia_ice_transport_info*) - pjmedia_transport_info_get_spc_info( - &info, PJMEDIA_TRANSPORT_TYPE_ICE); - use_ice = ice_info && ice_info->comp_cnt; - if (!use_ice) { - /* Start SSL nego */ - status = ssl_handshake(ds); - if (status != PJ_SUCCESS) - goto on_return; - } + pjmedia_transport_info info; + pjmedia_ice_transport_info *ice_info; + + pjmedia_transport_info_init(&info); + pjmedia_transport_get_info(ds->srtp->member_tp, &info); + ice_info = (pjmedia_ice_transport_info*) + pjmedia_transport_info_get_spc_info( + &info, PJMEDIA_TRANSPORT_TYPE_ICE); + use_ice = ice_info && ice_info->comp_cnt; + if (!use_ice) { + /* Start SSL nego */ + status = ssl_handshake(ds); + if (status != PJ_SUCCESS) + goto on_return; + } } on_return: #if DTLS_DEBUG if (status != PJ_SUCCESS) { - pj_perror(4, ds->base.name, status, "dtls_encode_sdp() failed"); + pj_perror(4, ds->base.name, status, "dtls_encode_sdp() failed"); } #endif return status; @@ -1464,10 +1463,10 @@ static pj_status_t dtls_encode_sdp( pjmedia_transport *tp, static pj_status_t dtls_media_start( pjmedia_transport *tp, - pj_pool_t *tmp_pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *tmp_pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { dtls_srtp *ds = (dtls_srtp *)tp; pj_ice_strans_state ice_state; @@ -1483,76 +1482,76 @@ static pj_status_t dtls_media_start( pjmedia_transport *tp, PJ_UNUSED_ARG(sdp_local); if (ds->srtp->offerer_side) { - /* As offerer */ - dtls_setup last_setup = ds->setup; - pj_str_t last_rem_fp = ds->rem_fingerprint; - - /* Parse a=setup and a=fingerprint */ - status = parse_setup_finger_attr(ds, PJ_FALSE, sdp_remote, - media_index); - if (status != PJ_SUCCESS) - goto on_return; - - /* Check if remote signals DTLS re-nego by changing its - * setup/fingerprint in SDP. - */ - if ((last_setup != DTLS_SETUP_ACTPASS && last_setup != ds->setup) || - (last_rem_fp.slen && - pj_memcmp(&last_rem_fp, &ds->rem_fingerprint, sizeof(pj_str_t)))) - { - ssl_destroy(ds); - ds->nego_started = PJ_FALSE; - ds->nego_completed = PJ_FALSE; - ds->got_keys = PJ_FALSE; - ds->rem_fprint_status = PJ_EPENDING; - } + /* As offerer */ + dtls_setup last_setup = ds->setup; + pj_str_t last_rem_fp = ds->rem_fingerprint; + + /* Parse a=setup and a=fingerprint */ + status = parse_setup_finger_attr(ds, PJ_FALSE, sdp_remote, + media_index); + if (status != PJ_SUCCESS) + goto on_return; + + /* Check if remote signals DTLS re-nego by changing its + * setup/fingerprint in SDP. + */ + if ((last_setup != DTLS_SETUP_ACTPASS && last_setup != ds->setup) || + (last_rem_fp.slen && + pj_memcmp(&last_rem_fp, &ds->rem_fingerprint, sizeof(pj_str_t)))) + { + ssl_destroy(ds); + ds->nego_started = PJ_FALSE; + ds->nego_completed = PJ_FALSE; + ds->got_keys = PJ_FALSE; + ds->rem_fprint_status = PJ_EPENDING; + } } else { - /* As answerer */ - - /* Nothing to do? */ + /* As answerer */ + + /* Nothing to do? */ } /* Check and update ICE and rtcp-mux status */ { - pjmedia_transport_info info; - pjmedia_ice_transport_info *ice_info; - - pjmedia_transport_info_init(&info); - pjmedia_transport_get_info(ds->srtp->member_tp, &info); - if (pj_sockaddr_cmp(&info.sock_info.rtp_addr_name, - &info.sock_info.rtcp_addr_name) == 0) - { - use_rtcp_mux = PJ_TRUE; - } - ice_info = (pjmedia_ice_transport_info*) - pjmedia_transport_info_get_spc_info( - &info, PJMEDIA_TRANSPORT_TYPE_ICE); - ds->use_ice = ice_info && ice_info->active; - ice_state = ds->use_ice? ice_info->sess_state : 0; - - /* Update remote RTP & RTCP addresses */ - get_rem_addrs(ds, sdp_remote, media_index, &ds->rem_addr, + pjmedia_transport_info info; + pjmedia_ice_transport_info *ice_info; + + pjmedia_transport_info_init(&info); + pjmedia_transport_get_info(ds->srtp->member_tp, &info); + if (pj_sockaddr_cmp(&info.sock_info.rtp_addr_name, + &info.sock_info.rtcp_addr_name) == 0) + { + use_rtcp_mux = PJ_TRUE; + } + ice_info = (pjmedia_ice_transport_info*) + pjmedia_transport_info_get_spc_info( + &info, PJMEDIA_TRANSPORT_TYPE_ICE); + ds->use_ice = ice_info && ice_info->active; + ice_state = ds->use_ice? ice_info->sess_state : 0; + + /* Update remote RTP & RTCP addresses */ + get_rem_addrs(ds, sdp_remote, media_index, &ds->rem_addr, &ds->rem_rtcp, NULL); } /* Check if the background DTLS nego has completed */ - if (ds->got_keys) { - ds->srtp->tx_policy_neg = ds->tx_crypto; - ds->srtp->rx_policy_neg = ds->rx_crypto; - - /* Verify remote fingerprint (if available) */ - if (ds->rem_fingerprint.slen && ds->rem_fprint_status == PJ_EPENDING) - { - ds->rem_fprint_status = ssl_match_fingerprint(ds); - if (ds->rem_fprint_status != PJ_SUCCESS) { - pj_perror(4, ds->base.name, ds->rem_fprint_status, - "Fingerprint specified in remote SDP doesn't match " - "to actual remote certificate fingerprint!"); - return ds->rem_fprint_status; - } - } - - return PJ_SUCCESS; + if (ds->got_keys) { + ds->srtp->tx_policy_neg = ds->tx_crypto; + ds->srtp->rx_policy_neg = ds->rx_crypto; + + /* Verify remote fingerprint (if available) */ + if (ds->rem_fingerprint.slen && ds->rem_fprint_status == PJ_EPENDING) + { + ds->rem_fprint_status = ssl_match_fingerprint(ds); + if (ds->rem_fprint_status != PJ_SUCCESS) { + pj_perror(4, ds->base.name, ds->rem_fprint_status, + "Fingerprint specified in remote SDP doesn't match " + "to actual remote certificate fingerprint!"); + return ds->rem_fprint_status; + } + } + + return PJ_SUCCESS; } /* SRTP key is not ready, SRTP start is pending */ @@ -1566,64 +1565,64 @@ static pj_status_t dtls_media_start( pjmedia_transport *tp, * - start it now if there is no ICE. */ if (ds->setup == DTLS_SETUP_ACTIVE) { - if (ds->use_ice && ice_state < PJ_ICE_STRANS_STATE_RUNNING) { - /* Register ourselves to listen to ICE notifications */ - pjmedia_ice_cb ice_cb; - pj_bzero(&ice_cb, sizeof(ice_cb)); - ice_cb.on_ice_complete2 = &on_ice_complete2; - pjmedia_ice_add_ice_cb(ds->srtp->member_tp, &ice_cb, ds); - } else { - /* This can happen when we are SDP offerer and remote wants - * PASSIVE DTLS role. - */ - pjmedia_transport_attach_param ap; - pj_bzero(&ap, sizeof(ap)); - ap.user_data = ds->srtp; - - /* Attach ourselves to member transport for DTLS nego. */ - if (pj_sockaddr_has_addr(&ds->rem_addr)) - pj_sockaddr_cp(&ap.rem_addr, &ds->rem_addr); - else - pj_sockaddr_init(pj_AF_INET(), &ap.rem_addr, 0, 0); - - if (use_rtcp_mux) { - /* Using RTP & RTCP multiplexing */ - pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_addr); - } else if (pj_sockaddr_has_addr(&ds->rem_rtcp)) { - pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_rtcp); - } else if (pj_sockaddr_has_addr(&ds->rem_addr)) { - pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_addr); - pj_sockaddr_set_port(&ap.rem_rtcp, - pj_sockaddr_get_port(&ap.rem_rtcp) + 1); - } else { - pj_sockaddr_init(pj_AF_INET(), &ap.rem_rtcp, 0, 0); - } - - ap.addr_len = pj_sockaddr_get_len(&ap.rem_addr); - status = pjmedia_transport_attach2(&ds->srtp->base, &ap); - if (status != PJ_SUCCESS) - goto on_return; + if (ds->use_ice && ice_state < PJ_ICE_STRANS_STATE_RUNNING) { + /* Register ourselves to listen to ICE notifications */ + pjmedia_ice_cb ice_cb; + pj_bzero(&ice_cb, sizeof(ice_cb)); + ice_cb.on_ice_complete2 = &on_ice_complete2; + pjmedia_ice_add_ice_cb(ds->srtp->member_tp, &ice_cb, ds); + } else { + /* This can happen when we are SDP offerer and remote wants + * PASSIVE DTLS role. + */ + pjmedia_transport_attach_param ap; + pj_bzero(&ap, sizeof(ap)); + ap.user_data = ds->srtp; + + /* Attach ourselves to member transport for DTLS nego. */ + if (pj_sockaddr_has_addr(&ds->rem_addr)) + pj_sockaddr_cp(&ap.rem_addr, &ds->rem_addr); + else + pj_sockaddr_init(pj_AF_INET(), &ap.rem_addr, 0, 0); + + if (use_rtcp_mux) { + /* Using RTP & RTCP multiplexing */ + pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_addr); + } else if (pj_sockaddr_has_addr(&ds->rem_rtcp)) { + pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_rtcp); + } else if (pj_sockaddr_has_addr(&ds->rem_addr)) { + pj_sockaddr_cp(&ap.rem_rtcp, &ds->rem_addr); + pj_sockaddr_set_port(&ap.rem_rtcp, + pj_sockaddr_get_port(&ap.rem_rtcp) + 1); + } else { + pj_sockaddr_init(pj_AF_INET(), &ap.rem_rtcp, 0, 0); + } + + ap.addr_len = pj_sockaddr_get_len(&ap.rem_addr); + status = pjmedia_transport_attach2(&ds->srtp->base, &ap); + if (status != PJ_SUCCESS) + goto on_return; #if DTLS_DEBUG - { - char addr[PJ_INET6_ADDRSTRLEN]; - PJ_LOG(2,(ds->base.name, "Attached transport, " - "remote addr=%s:%d", - pj_sockaddr_print(&ap.rem_addr, addr, - sizeof(addr), 2), - pj_sockaddr_get_port(&ap.rem_addr))); - } + { + char addr[PJ_INET6_ADDRSTRLEN]; + PJ_LOG(2,(ds->base.name, "Attached transport, " + "remote addr=%s:%d", + pj_sockaddr_print(&ap.rem_addr, addr, + sizeof(addr), 2), + pj_sockaddr_get_port(&ap.rem_addr))); + } #endif - status = ssl_handshake(ds); - if (status != PJ_SUCCESS) - goto on_return; - } + status = ssl_handshake(ds); + if (status != PJ_SUCCESS) + goto on_return; + } } on_return: #if DTLS_DEBUG if (status != PJ_SUCCESS) { - pj_perror(4, ds->base.name, status, "dtls_media_start() failed"); + pj_perror(4, ds->base.name, status, "dtls_media_start() failed"); } #endif return status; @@ -1638,12 +1637,12 @@ static pj_status_t dtls_media_stop(pjmedia_transport *tp) #endif if (ds->clock) - pjmedia_clock_stop(ds->clock); + pjmedia_clock_stop(ds->clock); /* Reset DTLS state */ ssl_destroy(ds); ds->setup = DTLS_SETUP_UNKNOWN; - ds->use_ice = PJ_FALSE; + ds->use_ice = PJ_FALSE; ds->nego_started = PJ_FALSE; ds->nego_completed = PJ_FALSE; ds->got_keys = PJ_FALSE; @@ -1662,7 +1661,7 @@ static pj_status_t dtls_destroy(pjmedia_transport *tp) #endif if (ds->clock) - pjmedia_clock_destroy(ds->clock); + pjmedia_clock_destroy(ds->clock); ssl_destroy(ds); pj_pool_safe_release(&ds->pool); @@ -1672,26 +1671,26 @@ static pj_status_t dtls_destroy(pjmedia_transport *tp) /* Get fingerprint of local DTLS-SRTP certificate. */ PJ_DEF(pj_status_t) pjmedia_transport_srtp_dtls_get_fingerprint( - pjmedia_transport *tp, - const char *hash, - char *buf, pj_size_t *len) + pjmedia_transport *tp, + const char *hash, + char *buf, pj_size_t *len) { PJ_ASSERT_RETURN(dtls_cert, PJ_EINVALIDOP); PJ_ASSERT_RETURN(tp && hash && buf && len, PJ_EINVAL); PJ_ASSERT_RETURN(pj_ansi_strcmp(hash, "SHA-256")==0 || - pj_ansi_strcmp(hash, "SHA-1")==0, PJ_EINVAL); + pj_ansi_strcmp(hash, "SHA-1")==0, PJ_EINVAL); PJ_UNUSED_ARG(tp); return ssl_get_fingerprint(dtls_cert, - pj_ansi_strcmp(hash, "SHA-256")==0, - buf, len); + pj_ansi_strcmp(hash, "SHA-256")==0, + buf, len); } /* Manually start DTLS-SRTP negotiation (without SDP offer/answer) */ PJ_DEF(pj_status_t) pjmedia_transport_srtp_dtls_start_nego( - pjmedia_transport *tp, - const pjmedia_srtp_dtls_nego_param *param) + pjmedia_transport *tp, + const pjmedia_srtp_dtls_nego_param *param) { transport_srtp *srtp = (transport_srtp*)tp; dtls_srtp *ds = NULL; @@ -1704,15 +1703,15 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_dtls_start_nego( /* Find DTLS keying and destroy any other keying. */ for (j = 0; j < srtp->all_keying_cnt; ++j) { - if (srtp->all_keying[j]->op == &dtls_op) - ds = (dtls_srtp*)srtp->all_keying[j]; - else - pjmedia_transport_close(srtp->all_keying[j]); + if (srtp->all_keying[j]->op == &dtls_op) + ds = (dtls_srtp*)srtp->all_keying[j]; + else + pjmedia_transport_close(srtp->all_keying[j]); } /* DTLS-SRTP is not enabled */ if (!ds) - return PJ_ENOTSUP; + return PJ_ENOTSUP; /* Set SRTP keying to DTLS-SRTP only */ srtp->keying_cnt = 1; @@ -1738,14 +1737,14 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_dtls_start_nego( ap.addr_len = pj_sockaddr_get_len(&ap.rem_addr); status = pjmedia_transport_attach2(&ds->srtp->base, &ap); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; #if DTLS_DEBUG { - char addr[PJ_INET6_ADDRSTRLEN]; - PJ_LOG(2,(ds->base.name, "Attached transport, remote addr=%s:%d", - pj_sockaddr_print(&ap.rem_addr, addr, sizeof(addr), 2), - pj_sockaddr_get_port(&ap.rem_addr))); + char addr[PJ_INET6_ADDRSTRLEN]; + PJ_LOG(2,(ds->base.name, "Attached transport, remote addr=%s:%d", + pj_sockaddr_print(&ap.rem_addr, addr, sizeof(addr), 2), + pj_sockaddr_get_port(&ap.rem_addr))); } #endif @@ -1754,11 +1753,11 @@ PJ_DEF(pj_status_t) pjmedia_transport_srtp_dtls_start_nego( pj_bzero(&srtp->tx_policy_neg, sizeof(srtp->tx_policy_neg)); status = ssl_handshake(ds); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; on_return: if (status != PJ_SUCCESS) { - ssl_destroy(ds); + ssl_destroy(ds); } return status; } diff --git a/pjmedia/src/pjmedia/transport_srtp_sdes.c b/pjmedia/src/pjmedia/transport_srtp_sdes.c index dade8e3577..b6ecb066e0 100644 --- a/pjmedia/src/pjmedia/transport_srtp_sdes.c +++ b/pjmedia/src/pjmedia/transport_srtp_sdes.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2017 Teluu Inc. (http://www.teluu.com) * @@ -40,20 +39,20 @@ static pj_status_t sdes_media_create(pjmedia_transport *tp, - pj_pool_t *sdp_pool, - unsigned options, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *sdp_pool, + unsigned options, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t sdes_encode_sdp (pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t sdes_media_start (pjmedia_transport *tp, - pj_pool_t *pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t sdes_media_stop (pjmedia_transport *tp); @@ -75,7 +74,7 @@ static pjmedia_transport_op sdes_op = static pj_status_t sdes_create(transport_srtp *srtp, - pjmedia_transport **p_keying) + pjmedia_transport **p_keying) { pjmedia_transport *sdes; @@ -97,9 +96,9 @@ static pj_status_t sdes_create(transport_srtp *srtp, * and set buffer_len = 0. */ static pj_status_t generate_crypto_attr_value(pj_pool_t *pool, - char *buffer, int *buffer_len, - pjmedia_srtp_crypto *crypto, - int tag) + char *buffer, int *buffer_len, + pjmedia_srtp_crypto *crypto, + int tag) { pj_status_t status; int cs_idx = get_crypto_idx(&crypto->name); @@ -108,82 +107,82 @@ static pj_status_t generate_crypto_attr_value(pj_pool_t *pool, int print_len; if (cs_idx == -1) - return PJMEDIA_SRTP_ENOTSUPCRYPTO; + return PJMEDIA_SRTP_ENOTSUPCRYPTO; /* Crypto-suite NULL. */ if (cs_idx == 0) { - *buffer_len = 0; - return PJ_SUCCESS; + *buffer_len = 0; + return PJ_SUCCESS; } /* Generate key if not specified. */ if (crypto->key.slen == 0) { - pj_bool_t key_ok; - char key[MAX_KEY_LEN]; - unsigned i; + pj_bool_t key_ok; + char key[MAX_KEY_LEN]; + unsigned i; - PJ_ASSERT_RETURN(MAX_KEY_LEN >= crypto_suites[cs_idx].cipher_key_len, - PJ_ETOOSMALL); + PJ_ASSERT_RETURN(MAX_KEY_LEN >= crypto_suites[cs_idx].cipher_key_len, + PJ_ETOOSMALL); - do { + do { #if defined(PJ_HAS_SSL_SOCK) && (PJ_HAS_SSL_SOCK != 0) && \ (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_OPENSSL) - int err = RAND_bytes((unsigned char*)key, - crypto_suites[cs_idx].cipher_key_len); - if (err != 1) { - PJ_LOG(4,(THIS_FILE, "Failed generating random key " - "(native err=%d)", err)); - return PJMEDIA_ERRNO_FROM_LIBSRTP(1); - } + int err = RAND_bytes((unsigned char*)key, + crypto_suites[cs_idx].cipher_key_len); + if (err != 1) { + PJ_LOG(4,(THIS_FILE, "Failed generating random key " + "(native err=%d)", err)); + return PJMEDIA_ERRNO_FROM_LIBSRTP(1); + } #else - PJ_LOG(3,(THIS_FILE, "Warning: simple random generator is used " - "for generating SRTP key")); - for (i=0; ikey.ptr = (char*) - pj_pool_zalloc(pool, - crypto_suites[cs_idx].cipher_key_len); - pj_memcpy(crypto->key.ptr, key, crypto_suites[cs_idx].cipher_key_len); - crypto->key.slen = crypto_suites[cs_idx].cipher_key_len; + } while (!key_ok); + crypto->key.ptr = (char*) + pj_pool_zalloc(pool, + crypto_suites[cs_idx].cipher_key_len); + pj_memcpy(crypto->key.ptr, key, crypto_suites[cs_idx].cipher_key_len); + crypto->key.slen = crypto_suites[cs_idx].cipher_key_len; } if (crypto->key.slen != (pj_ssize_t)crypto_suites[cs_idx].cipher_key_len) - return PJMEDIA_SRTP_EINKEYLEN; + return PJMEDIA_SRTP_EINKEYLEN; /* Key transmitted via SDP should be base64 encoded. */ status = pj_base64_encode((pj_uint8_t*)crypto->key.ptr, - (int)crypto->key.slen, - b64_key, &b64_key_len); + (int)crypto->key.slen, + b64_key, &b64_key_len); if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Failed encoding plain key to base64")); - return status; + PJ_PERROR(4,(THIS_FILE, status, + "Failed encoding plain key to base64")); + return status; } b64_key[b64_key_len] = '\0'; PJ_ASSERT_RETURN(*buffer_len >= (crypto->name.slen + \ - b64_key_len + 16), PJ_ETOOSMALL); + b64_key_len + 16), PJ_ETOOSMALL); /* Print the crypto attribute value. */ print_len = pj_ansi_snprintf(buffer, *buffer_len, "%d %s inline:%s", - tag, - crypto_suites[cs_idx].name, - b64_key); + tag, + crypto_suites[cs_idx].name, + b64_key); if (print_len < 1 || print_len >= *buffer_len) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; *buffer_len = print_len; @@ -193,9 +192,9 @@ static pj_status_t generate_crypto_attr_value(pj_pool_t *pool, /* Parse crypto attribute line */ static pj_status_t parse_attr_crypto(pj_pool_t *pool, - const pjmedia_sdp_attr *attr, - pjmedia_srtp_crypto *crypto, - int *tag) + const pjmedia_sdp_attr *attr, + pjmedia_srtp_crypto *crypto, + int *tag) { pj_str_t token, delim; pj_status_t status; @@ -208,18 +207,18 @@ static pj_status_t parse_attr_crypto(pj_pool_t *pool, delim = pj_str(" "); found_idx = pj_strtok(&attr->value, &delim, &token, 0); if (found_idx == attr->value.slen) { - PJ_LOG(4,(THIS_FILE, "Attribute crypto expecting tag")); - return PJMEDIA_SDP_EINATTR; + PJ_LOG(4,(THIS_FILE, "Attribute crypto expecting tag")); + return PJMEDIA_SDP_EINATTR; } /* Tag must not use leading zeroes. */ if (token.slen > 1 && *token.ptr == '0') - return PJMEDIA_SDP_EINATTR; + return PJMEDIA_SDP_EINATTR; /* Tag must be decimal, i.e: contains only digit '0'-'9'. */ for (itmp = 0; itmp < token.slen; ++itmp) - if (!pj_isdigit(token.ptr[itmp])) - return PJMEDIA_SDP_EINATTR; + if (!pj_isdigit(token.ptr[itmp])) + return PJMEDIA_SDP_EINATTR; /* Get tag value. */ *tag = pj_strtoul(&token); @@ -227,8 +226,8 @@ static pj_status_t parse_attr_crypto(pj_pool_t *pool, /* Crypto-suite */ found_idx = pj_strtok(&attr->value, &delim, &token, found_idx+token.slen); if (found_idx == attr->value.slen) { - PJ_LOG(4,(THIS_FILE, "Attribute crypto expecting crypto suite")); - return PJMEDIA_SDP_EINATTR; + PJ_LOG(4,(THIS_FILE, "Attribute crypto expecting crypto suite")); + return PJMEDIA_SDP_EINATTR; } pj_strdup(pool, &crypto->name, &token); @@ -236,37 +235,37 @@ static pj_status_t parse_attr_crypto(pj_pool_t *pool, delim = pj_str(": "); found_idx = pj_strtok(&attr->value, &delim, &token, found_idx+token.slen); if (found_idx == attr->value.slen) { - PJ_LOG(4,(THIS_FILE, "Attribute crypto expecting key method")); - return PJMEDIA_SDP_EINATTR; + PJ_LOG(4,(THIS_FILE, "Attribute crypto expecting key method")); + return PJMEDIA_SDP_EINATTR; } if (pj_stricmp2(&token, "inline")) { - PJ_LOG(4,(THIS_FILE, "Attribute crypto key method '%.*s' " - "not supported!", token.slen, token.ptr)); - return PJMEDIA_SDP_EINATTR; + PJ_LOG(4,(THIS_FILE, "Attribute crypto key method '%.*s' " + "not supported!", token.slen, token.ptr)); + return PJMEDIA_SDP_EINATTR; } /* Key */ delim = pj_str("| "); found_idx = pj_strtok(&attr->value, &delim, &token, found_idx+token.slen); if (found_idx == attr->value.slen) { - PJ_LOG(4,(THIS_FILE, "Attribute crypto expecting key")); - return PJMEDIA_SDP_EINATTR; + PJ_LOG(4,(THIS_FILE, "Attribute crypto expecting key")); + return PJMEDIA_SDP_EINATTR; } if (PJ_BASE64_TO_BASE256_LEN(token.slen) > MAX_KEY_LEN) { - PJ_LOG(4,(THIS_FILE, "Key too long")); - return PJMEDIA_SRTP_EINKEYLEN; + PJ_LOG(4,(THIS_FILE, "Key too long")); + return PJMEDIA_SRTP_EINKEYLEN; } /* Decode key */ crypto->key.ptr = (char*) pj_pool_zalloc(pool, MAX_KEY_LEN); itmp = MAX_KEY_LEN; status = pj_base64_decode(&token, (pj_uint8_t*)crypto->key.ptr, - &itmp); + &itmp); if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Failed decoding crypto key from base64")); - return status; + PJ_PERROR(4,(THIS_FILE, status, + "Failed decoding crypto key from base64")); + return status; } crypto->key.slen = itmp; @@ -275,10 +274,10 @@ static pj_status_t parse_attr_crypto(pj_pool_t *pool, static pj_status_t sdes_media_create( pjmedia_transport *tp, - pj_pool_t *sdp_pool, - unsigned options, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *sdp_pool, + unsigned options, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { struct transport_srtp *srtp = (struct transport_srtp*)tp->user_data; pj_uint32_t rem_proto = 0; @@ -288,45 +287,45 @@ static pj_status_t sdes_media_create( pjmedia_transport *tp, /* Verify remote media transport, it has to be RTP/AVP or RTP/SAVP */ if (!srtp->offerer_side) { - pjmedia_sdp_media *m = sdp_remote->media[media_index]; - - /* Get transport protocol and drop any RTCP-FB flag */ - rem_proto = pjmedia_sdp_transport_get_proto(&m->desc.transport); - PJMEDIA_TP_PROTO_TRIM_FLAG(rem_proto, PJMEDIA_TP_PROFILE_RTCP_FB); - if (rem_proto != PJMEDIA_TP_PROTO_RTP_AVP && - rem_proto != PJMEDIA_TP_PROTO_RTP_SAVP) - { - return PJMEDIA_SRTP_ESDPINTRANSPORT; - } + pjmedia_sdp_media *m = sdp_remote->media[media_index]; + + /* Get transport protocol and drop any RTCP-FB flag */ + rem_proto = pjmedia_sdp_transport_get_proto(&m->desc.transport); + PJMEDIA_TP_PROTO_TRIM_FLAG(rem_proto, PJMEDIA_TP_PROFILE_RTCP_FB); + if (rem_proto != PJMEDIA_TP_PROTO_RTP_AVP && + rem_proto != PJMEDIA_TP_PROTO_RTP_SAVP) + { + return PJMEDIA_SRTP_ESDPINTRANSPORT; + } } /* Validations */ if (srtp->offerer_side) { - /* As offerer: do nothing. */ + /* As offerer: do nothing. */ } else { - /* Validate remote media transport based on SRTP usage option. */ - switch (srtp->setting.use) { - case PJMEDIA_SRTP_DISABLED: - if (rem_proto == PJMEDIA_TP_PROTO_RTP_SAVP) - return PJMEDIA_SRTP_ESDPINTRANSPORT; - break; - case PJMEDIA_SRTP_OPTIONAL: - break; - case PJMEDIA_SRTP_MANDATORY: - if (rem_proto != PJMEDIA_TP_PROTO_RTP_SAVP) - return PJMEDIA_SRTP_ESDPINTRANSPORT; - break; - } + /* Validate remote media transport based on SRTP usage option. */ + switch (srtp->setting.use) { + case PJMEDIA_SRTP_DISABLED: + if (rem_proto == PJMEDIA_TP_PROTO_RTP_SAVP) + return PJMEDIA_SRTP_ESDPINTRANSPORT; + break; + case PJMEDIA_SRTP_OPTIONAL: + break; + case PJMEDIA_SRTP_MANDATORY: + if (rem_proto != PJMEDIA_TP_PROTO_RTP_SAVP) + return PJMEDIA_SRTP_ESDPINTRANSPORT; + break; + } } return PJ_SUCCESS; } static pj_status_t sdes_encode_sdp( pjmedia_transport *tp, - pj_pool_t *sdp_pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *sdp_pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { struct transport_srtp *srtp = (struct transport_srtp*)tp->user_data; pjmedia_sdp_media *m_rem, *m_loc; @@ -343,17 +342,17 @@ static pj_status_t sdes_encode_sdp( pjmedia_transport *tp, /* Verify media transport, it has to be RTP/AVP or RTP/SAVP */ { - pjmedia_sdp_media *m = sdp_remote? m_rem : m_loc; - pj_uint32_t proto = 0; - - /* Get transport protocol and drop any RTCP-FB flag */ - proto = pjmedia_sdp_transport_get_proto(&m->desc.transport); - PJMEDIA_TP_PROTO_TRIM_FLAG(proto, PJMEDIA_TP_PROFILE_RTCP_FB); - if (proto != PJMEDIA_TP_PROTO_RTP_AVP && - proto != PJMEDIA_TP_PROTO_RTP_SAVP) - { - return PJMEDIA_SRTP_ESDPINTRANSPORT; - } + pjmedia_sdp_media *m = sdp_remote? m_rem : m_loc; + pj_uint32_t proto = 0; + + /* Get transport protocol and drop any RTCP-FB flag */ + proto = pjmedia_sdp_transport_get_proto(&m->desc.transport); + PJMEDIA_TP_PROTO_TRIM_FLAG(proto, PJMEDIA_TP_PROFILE_RTCP_FB); + if (proto != PJMEDIA_TP_PROTO_RTP_AVP && + proto != PJMEDIA_TP_PROTO_RTP_SAVP) + { + return PJMEDIA_SRTP_ESDPINTRANSPORT; + } } /* If the media is inactive, do nothing. */ @@ -364,8 +363,8 @@ static pj_status_t sdes_encode_sdp( pjmedia_transport *tp, */ /* if (pjmedia_sdp_media_find_attr(m_loc, &ID_INACTIVE, NULL) || - (m_rem && pjmedia_sdp_media_find_attr(m_rem, &ID_INACTIVE, NULL))) - goto BYPASS_SRTP; + (m_rem && pjmedia_sdp_media_find_attr(m_rem, &ID_INACTIVE, NULL))) + goto BYPASS_SRTP; */ /* Check remote media transport & set local media transport @@ -373,200 +372,200 @@ static pj_status_t sdes_encode_sdp( pjmedia_transport *tp, */ if (srtp->offerer_side) { - /* Generate transport */ - switch (srtp->setting.use) { - case PJMEDIA_SRTP_DISABLED: - /* Should never reach here */ - return PJ_SUCCESS; - case PJMEDIA_SRTP_OPTIONAL: - m_loc->desc.transport = - (srtp->peer_use == PJMEDIA_SRTP_MANDATORY)? - ID_RTP_SAVP : ID_RTP_AVP; - break; - case PJMEDIA_SRTP_MANDATORY: - m_loc->desc.transport = ID_RTP_SAVP; - break; - } - - /* Generate crypto attribute if not yet */ - if (pjmedia_sdp_media_find_attr(m_loc, &ID_CRYPTO, NULL) == NULL) { - int tag = 1; - - /* Offer only current active crypto if any, otherwise offer all - * crypto-suites in the setting. - */ - for (i=0; isetting.crypto_count; ++i) { - if (srtp->tx_policy.name.slen && - pj_stricmp(&srtp->tx_policy.name, - &srtp->setting.crypto[i].name) != 0) - { - continue; - } - - buffer_len = MAXLEN; - status = generate_crypto_attr_value(srtp->pool, buffer, - &buffer_len, - &srtp->setting.crypto[i], - tag); - if (status != PJ_SUCCESS) - return status; - - /* If buffer_len==0, just skip the crypto attribute. */ - if (buffer_len) { - pj_strset(&attr_value, buffer, buffer_len); - attr = pjmedia_sdp_attr_create(srtp->pool, ID_CRYPTO.ptr, - &attr_value); - m_loc->attr[m_loc->attr_count++] = attr; - ++tag; - } - } - } + /* Generate transport */ + switch (srtp->setting.use) { + case PJMEDIA_SRTP_DISABLED: + /* Should never reach here */ + return PJ_SUCCESS; + case PJMEDIA_SRTP_OPTIONAL: + m_loc->desc.transport = + (srtp->peer_use == PJMEDIA_SRTP_MANDATORY)? + ID_RTP_SAVP : ID_RTP_AVP; + break; + case PJMEDIA_SRTP_MANDATORY: + m_loc->desc.transport = ID_RTP_SAVP; + break; + } + + /* Generate crypto attribute if not yet */ + if (pjmedia_sdp_media_find_attr(m_loc, &ID_CRYPTO, NULL) == NULL) { + int tag = 1; + + /* Offer only current active crypto if any, otherwise offer all + * crypto-suites in the setting. + */ + for (i=0; isetting.crypto_count; ++i) { + if (srtp->tx_policy.name.slen && + pj_stricmp(&srtp->tx_policy.name, + &srtp->setting.crypto[i].name) != 0) + { + continue; + } + + buffer_len = MAXLEN; + status = generate_crypto_attr_value(srtp->pool, buffer, + &buffer_len, + &srtp->setting.crypto[i], + tag); + if (status != PJ_SUCCESS) + return status; + + /* If buffer_len==0, just skip the crypto attribute. */ + if (buffer_len) { + pj_strset(&attr_value, buffer, buffer_len); + attr = pjmedia_sdp_attr_create(srtp->pool, ID_CRYPTO.ptr, + &attr_value); + m_loc->attr[m_loc->attr_count++] = attr; + ++tag; + } + } + } } else { - /* Answerer side */ - pj_uint32_t rem_proto = 0; - - pj_assert(sdp_remote && m_rem); - - /* Get transport protocol and drop any RTCP-FB flag */ - rem_proto = pjmedia_sdp_transport_get_proto(&m_rem->desc.transport); - PJMEDIA_TP_PROTO_TRIM_FLAG(rem_proto, PJMEDIA_TP_PROFILE_RTCP_FB); - - /* Generate transport */ - switch (srtp->setting.use) { - case PJMEDIA_SRTP_DISABLED: - /* Should never reach here */ - if (rem_proto == PJMEDIA_TP_PROTO_RTP_SAVP) - return PJMEDIA_SRTP_ESDPINTRANSPORT; - return PJ_SUCCESS; - case PJMEDIA_SRTP_OPTIONAL: - break; - case PJMEDIA_SRTP_MANDATORY: - if (rem_proto != PJMEDIA_TP_PROTO_RTP_SAVP) - return PJMEDIA_SRTP_ESDPINTRANSPORT; - break; - } - - /* Generate crypto attribute if not yet */ - if (pjmedia_sdp_media_find_attr(m_loc, &ID_CRYPTO, NULL) == NULL) { - - pjmedia_srtp_crypto tmp_rx_crypto; - pj_bool_t has_crypto_attr = PJ_FALSE; - int matched_idx = -1; - int chosen_tag = 0; - int tags[64]; /* assume no more than 64 crypto attrs in a media */ - unsigned cr_attr_count = 0; - - /* Find supported crypto-suite, get the tag, and assign - * policy_local. - */ - for (i=0; iattr_count; ++i) { - if (pj_stricmp(&m_rem->attr[i]->name, &ID_CRYPTO) != 0) - continue; - - has_crypto_attr = PJ_TRUE; - - status = parse_attr_crypto(srtp->pool, m_rem->attr[i], - &tmp_rx_crypto, - &tags[cr_attr_count]); - if (status != PJ_SUCCESS) - return status; - - /* Check duplicated tag */ - for (j=0; jsetting.crypto_count; ++j) - if (pj_stricmp(&tmp_rx_crypto.name, - &srtp->setting.crypto[j].name) == 0) - { - int cs_idx = get_crypto_idx(&tmp_rx_crypto.name); - - if (cs_idx == -1) - return PJMEDIA_SRTP_ENOTSUPCRYPTO; - - if (tmp_rx_crypto.key.slen != - (int)crypto_suites[cs_idx].cipher_key_len) - return PJMEDIA_SRTP_EINKEYLEN; - - srtp->rx_policy_neg = tmp_rx_crypto; - chosen_tag = tags[cr_attr_count]; - matched_idx = j; - break; - } - } - cr_attr_count++; - } - - /* Check crypto negotiation result */ - switch (srtp->setting.use) { - case PJMEDIA_SRTP_DISABLED: - /* Should never reach here */ - break; - - case PJMEDIA_SRTP_OPTIONAL: - /* Bypass SDES if remote uses RTP/AVP and: - * - has no crypto-attr, or - * - has no matching crypto - */ - if ((!has_crypto_attr || matched_idx == -1) && - !PJMEDIA_TP_PROTO_HAS_FLAG(rem_proto, - PJMEDIA_TP_PROFILE_SRTP)) - { - return PJ_SUCCESS; - } - break; - - case PJMEDIA_SRTP_MANDATORY: - /* Do nothing, intentional */ - break; - } - - /* No crypto attr */ - if (!has_crypto_attr) { - //DEACTIVATE_MEDIA(sdp_pool, m_loc); - return PJMEDIA_SRTP_ESDPREQCRYPTO; - } - - /* No crypto match */ - if (matched_idx == -1) { - //DEACTIVATE_MEDIA(sdp_pool, m_loc); - return PJMEDIA_SRTP_ENOTSUPCRYPTO; - } - - /* we have to generate crypto answer, - * with srtp->tx_policy_neg matched the offer - * and rem_tag contains matched offer tag. - */ - buffer_len = MAXLEN; - status = generate_crypto_attr_value( - srtp->pool, buffer, &buffer_len, - &srtp->setting.crypto[matched_idx], - chosen_tag); - if (status != PJ_SUCCESS) - return status; - - srtp->tx_policy_neg = srtp->setting.crypto[matched_idx]; - - /* If buffer_len==0, just skip the crypto attribute. */ - if (buffer_len) { - pj_strset(&attr_value, buffer, buffer_len); - attr = pjmedia_sdp_attr_create(sdp_pool, ID_CRYPTO.ptr, - &attr_value); - m_loc->attr[m_loc->attr_count++] = attr; - } - - /* At this point, we get valid rx_policy_neg & tx_policy_neg. */ - } - - /* Update transport description in local media SDP */ - m_loc->desc.transport = m_rem->desc.transport; + /* Answerer side */ + pj_uint32_t rem_proto = 0; + + pj_assert(sdp_remote && m_rem); + + /* Get transport protocol and drop any RTCP-FB flag */ + rem_proto = pjmedia_sdp_transport_get_proto(&m_rem->desc.transport); + PJMEDIA_TP_PROTO_TRIM_FLAG(rem_proto, PJMEDIA_TP_PROFILE_RTCP_FB); + + /* Generate transport */ + switch (srtp->setting.use) { + case PJMEDIA_SRTP_DISABLED: + /* Should never reach here */ + if (rem_proto == PJMEDIA_TP_PROTO_RTP_SAVP) + return PJMEDIA_SRTP_ESDPINTRANSPORT; + return PJ_SUCCESS; + case PJMEDIA_SRTP_OPTIONAL: + break; + case PJMEDIA_SRTP_MANDATORY: + if (rem_proto != PJMEDIA_TP_PROTO_RTP_SAVP) + return PJMEDIA_SRTP_ESDPINTRANSPORT; + break; + } + + /* Generate crypto attribute if not yet */ + if (pjmedia_sdp_media_find_attr(m_loc, &ID_CRYPTO, NULL) == NULL) { + + pjmedia_srtp_crypto tmp_rx_crypto; + pj_bool_t has_crypto_attr = PJ_FALSE; + int matched_idx = -1; + int chosen_tag = 0; + int tags[64]; /* assume no more than 64 crypto attrs in a media */ + unsigned cr_attr_count = 0; + + /* Find supported crypto-suite, get the tag, and assign + * policy_local. + */ + for (i=0; iattr_count; ++i) { + if (pj_stricmp(&m_rem->attr[i]->name, &ID_CRYPTO) != 0) + continue; + + has_crypto_attr = PJ_TRUE; + + status = parse_attr_crypto(srtp->pool, m_rem->attr[i], + &tmp_rx_crypto, + &tags[cr_attr_count]); + if (status != PJ_SUCCESS) + return status; + + /* Check duplicated tag */ + for (j=0; jsetting.crypto_count; ++j) + if (pj_stricmp(&tmp_rx_crypto.name, + &srtp->setting.crypto[j].name) == 0) + { + int cs_idx = get_crypto_idx(&tmp_rx_crypto.name); + + if (cs_idx == -1) + return PJMEDIA_SRTP_ENOTSUPCRYPTO; + + if (tmp_rx_crypto.key.slen != + (int)crypto_suites[cs_idx].cipher_key_len) + return PJMEDIA_SRTP_EINKEYLEN; + + srtp->rx_policy_neg = tmp_rx_crypto; + chosen_tag = tags[cr_attr_count]; + matched_idx = j; + break; + } + } + cr_attr_count++; + } + + /* Check crypto negotiation result */ + switch (srtp->setting.use) { + case PJMEDIA_SRTP_DISABLED: + /* Should never reach here */ + break; + + case PJMEDIA_SRTP_OPTIONAL: + /* Bypass SDES if remote uses RTP/AVP and: + * - has no crypto-attr, or + * - has no matching crypto + */ + if ((!has_crypto_attr || matched_idx == -1) && + !PJMEDIA_TP_PROTO_HAS_FLAG(rem_proto, + PJMEDIA_TP_PROFILE_SRTP)) + { + return PJ_SUCCESS; + } + break; + + case PJMEDIA_SRTP_MANDATORY: + /* Do nothing, intentional */ + break; + } + + /* No crypto attr */ + if (!has_crypto_attr) { + //DEACTIVATE_MEDIA(sdp_pool, m_loc); + return PJMEDIA_SRTP_ESDPREQCRYPTO; + } + + /* No crypto match */ + if (matched_idx == -1) { + //DEACTIVATE_MEDIA(sdp_pool, m_loc); + return PJMEDIA_SRTP_ENOTSUPCRYPTO; + } + + /* we have to generate crypto answer, + * with srtp->tx_policy_neg matched the offer + * and rem_tag contains matched offer tag. + */ + buffer_len = MAXLEN; + status = generate_crypto_attr_value( + srtp->pool, buffer, &buffer_len, + &srtp->setting.crypto[matched_idx], + chosen_tag); + if (status != PJ_SUCCESS) + return status; + + srtp->tx_policy_neg = srtp->setting.crypto[matched_idx]; + + /* If buffer_len==0, just skip the crypto attribute. */ + if (buffer_len) { + pj_strset(&attr_value, buffer, buffer_len); + attr = pjmedia_sdp_attr_create(sdp_pool, ID_CRYPTO.ptr, + &attr_value); + m_loc->attr[m_loc->attr_count++] = attr; + } + + /* At this point, we get valid rx_policy_neg & tx_policy_neg. */ + } + + /* Update transport description in local media SDP */ + m_loc->desc.transport = m_rem->desc.transport; } return PJ_SUCCESS; @@ -574,35 +573,35 @@ static pj_status_t sdes_encode_sdp( pjmedia_transport *tp, static pj_status_t fill_local_crypto(pj_pool_t *pool, - const pjmedia_sdp_media *m_loc, - pjmedia_srtp_crypto loc_crypto[], - int *count) + const pjmedia_sdp_media *m_loc, + pjmedia_srtp_crypto loc_crypto[], + int *count) { int i; int crypto_count = 0; pj_status_t status = PJ_SUCCESS; for (i = 0; i < *count; ++i) { - pj_bzero(&loc_crypto[i], sizeof(loc_crypto[i])); + pj_bzero(&loc_crypto[i], sizeof(loc_crypto[i])); } - for (i = 0; i < (int)m_loc->attr_count; ++i) { - pjmedia_srtp_crypto tmp_crypto; - int loc_tag; + for (i = 0; i < (int)m_loc->attr_count; ++i) { + pjmedia_srtp_crypto tmp_crypto; + int loc_tag; - if (pj_stricmp(&m_loc->attr[i]->name, &ID_CRYPTO) != 0) - continue; + if (pj_stricmp(&m_loc->attr[i]->name, &ID_CRYPTO) != 0) + continue; - status = parse_attr_crypto(pool, m_loc->attr[i], - &tmp_crypto, &loc_tag); - if (status != PJ_SUCCESS) - return status; + status = parse_attr_crypto(pool, m_loc->attr[i], + &tmp_crypto, &loc_tag); + if (status != PJ_SUCCESS) + return status; - if (loc_tag > *count) - return PJMEDIA_SRTP_ESDPINCRYPTOTAG; + if (loc_tag > *count) + return PJMEDIA_SRTP_ESDPINCRYPTOTAG; - loc_crypto[loc_tag-1] = tmp_crypto; - ++crypto_count; + loc_crypto[loc_tag-1] = tmp_crypto; + ++crypto_count; } *count = crypto_count; return status; @@ -610,16 +609,16 @@ static pj_status_t fill_local_crypto(pj_pool_t *pool, static pj_status_t sdes_media_start( pjmedia_transport *tp, - pj_pool_t *pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { struct transport_srtp *srtp = (struct transport_srtp*)tp->user_data; pjmedia_sdp_media *m_rem, *m_loc; pj_status_t status; unsigned i; - pjmedia_srtp_crypto loc_crypto[PJMEDIA_SRTP_MAX_CRYPTOS]; + pjmedia_srtp_crypto loc_crypto[PJMEDIA_SRTP_MAX_CRYPTOS]; int loc_cryto_cnt = PJMEDIA_SRTP_MAX_CRYPTOS; pjmedia_srtp_crypto tmp_tx_crypto; pj_bool_t has_crypto_attr = PJ_FALSE; @@ -632,22 +631,22 @@ static pj_status_t sdes_media_start( pjmedia_transport *tp, /* Verify media transport, it has to be RTP/AVP or RTP/SAVP */ { - pj_uint32_t rem_proto; - - /* Get transport protocol and drop any RTCP-FB flag */ - rem_proto = pjmedia_sdp_transport_get_proto(&m_rem->desc.transport); - PJMEDIA_TP_PROTO_TRIM_FLAG(rem_proto, PJMEDIA_TP_PROFILE_RTCP_FB); - if (rem_proto != PJMEDIA_TP_PROTO_RTP_AVP && - rem_proto != PJMEDIA_TP_PROTO_RTP_SAVP) - { - return PJMEDIA_SRTP_ESDPINTRANSPORT; - } - - /* Also check if peer signal SRTP as mandatory */ - if (rem_proto == PJMEDIA_TP_PROTO_RTP_SAVP) - srtp->peer_use = PJMEDIA_SRTP_MANDATORY; - else - srtp->peer_use = PJMEDIA_SRTP_OPTIONAL; + pj_uint32_t rem_proto; + + /* Get transport protocol and drop any RTCP-FB flag */ + rem_proto = pjmedia_sdp_transport_get_proto(&m_rem->desc.transport); + PJMEDIA_TP_PROTO_TRIM_FLAG(rem_proto, PJMEDIA_TP_PROFILE_RTCP_FB); + if (rem_proto != PJMEDIA_TP_PROTO_RTP_AVP && + rem_proto != PJMEDIA_TP_PROTO_RTP_SAVP) + { + return PJMEDIA_SRTP_ESDPINTRANSPORT; + } + + /* Also check if peer signal SRTP as mandatory */ + if (rem_proto == PJMEDIA_TP_PROTO_RTP_SAVP) + srtp->peer_use = PJMEDIA_SRTP_MANDATORY; + else + srtp->peer_use = PJMEDIA_SRTP_OPTIONAL; } /* For answerer side, SRTP crypto policies have been populated in @@ -668,7 +667,7 @@ static pj_status_t sdes_media_start( pjmedia_transport *tp, (pj_stricmp(&srtp->tx_policy_neg.key, &loc_crypto[0].key) != 0)) { - srtp->tx_policy_neg = loc_crypto[0]; + srtp->tx_policy_neg = loc_crypto[0]; for (i = 0; isetting.crypto_count ;++i) { if ((pj_stricmp(&srtp->setting.crypto[i].name, &loc_crypto[0].name) == 0) && @@ -679,7 +678,7 @@ static pj_status_t sdes_media_start( pjmedia_transport *tp, &loc_crypto[0].key); } } - } + } return PJ_SUCCESS; } @@ -688,90 +687,90 @@ static pj_status_t sdes_media_start( pjmedia_transport *tp, * based on SRTP usage option. */ if (srtp->setting.use == PJMEDIA_SRTP_DISABLED) { - if (pjmedia_sdp_media_find_attr(m_rem, &ID_CRYPTO, NULL)) { - DEACTIVATE_MEDIA(pool, m_loc); - return PJMEDIA_SRTP_ESDPINCRYPTO; - } - return PJ_SUCCESS; + if (pjmedia_sdp_media_find_attr(m_rem, &ID_CRYPTO, NULL)) { + DEACTIVATE_MEDIA(pool, m_loc); + return PJMEDIA_SRTP_ESDPINCRYPTO; + } + return PJ_SUCCESS; } else if (srtp->setting.use == PJMEDIA_SRTP_OPTIONAL) { - // Regardless the answer's transport type (RTP/AVP or RTP/SAVP), - // the answer must be processed through in optional mode. - // Please note that at this point transport type is ensured to be - // RTP/AVP or RTP/SAVP, see sdes_media_create() - //if (pj_stricmp(&m_rem->desc.transport, &m_loc->desc.transport)) { - //DEACTIVATE_MEDIA(pool, m_loc); - //return PJMEDIA_SDP_EINPROTO; - //} - fill_local_crypto(srtp->pool, m_loc, loc_crypto, &loc_cryto_cnt); + // Regardless the answer's transport type (RTP/AVP or RTP/SAVP), + // the answer must be processed through in optional mode. + // Please note that at this point transport type is ensured to be + // RTP/AVP or RTP/SAVP, see sdes_media_create() + //if (pj_stricmp(&m_rem->desc.transport, &m_loc->desc.transport)) { + //DEACTIVATE_MEDIA(pool, m_loc); + //return PJMEDIA_SDP_EINPROTO; + //} + fill_local_crypto(srtp->pool, m_loc, loc_crypto, &loc_cryto_cnt); } else if (srtp->setting.use == PJMEDIA_SRTP_MANDATORY) { - if (srtp->peer_use != PJMEDIA_SRTP_MANDATORY) { - DEACTIVATE_MEDIA(pool, m_loc); - return PJMEDIA_SDP_EINPROTO; - } - fill_local_crypto(srtp->pool, m_loc, loc_crypto, &loc_cryto_cnt); + if (srtp->peer_use != PJMEDIA_SRTP_MANDATORY) { + DEACTIVATE_MEDIA(pool, m_loc); + return PJMEDIA_SDP_EINPROTO; + } + fill_local_crypto(srtp->pool, m_loc, loc_crypto, &loc_cryto_cnt); } /* find supported crypto-suite, get the tag, and assign policy_local */ for (i=0; iattr_count; ++i) { - if (pj_stricmp(&m_rem->attr[i]->name, &ID_CRYPTO) != 0) - continue; - - /* more than one crypto attribute in media answer */ - if (has_crypto_attr) { - DEACTIVATE_MEDIA(pool, m_loc); - return PJMEDIA_SRTP_ESDPAMBIGUEANS; - } - - has_crypto_attr = PJ_TRUE; - - status = parse_attr_crypto(srtp->pool, m_rem->attr[i], - &tmp_tx_crypto, &rem_tag); - if (status != PJ_SUCCESS) - return status; - - - /* Tag range check, our tags in the offer must be in the SRTP - * setting range, so does the remote answer's. The remote answer's - * tag must not exceed the tag range of the local offer. - */ - if (rem_tag < 1 || rem_tag > (int)srtp->setting.crypto_count || - rem_tag > loc_cryto_cnt) - { - DEACTIVATE_MEDIA(pool, m_loc); - return PJMEDIA_SRTP_ESDPINCRYPTOTAG; - } - - /* match the crypto name */ - if (pj_stricmp(&tmp_tx_crypto.name, &loc_crypto[rem_tag-1].name)) - { - DEACTIVATE_MEDIA(pool, m_loc); - return PJMEDIA_SRTP_ECRYPTONOTMATCH; - } - - /* Find the crypto from the local crypto. */ - for (j = 0; j < (int)loc_cryto_cnt; ++j) { - if (pj_stricmp(&tmp_tx_crypto.name, - &loc_crypto[j].name) == 0) - { - srtp->tx_policy_neg = loc_crypto[j]; - break; - } - } - - srtp->rx_policy_neg = tmp_tx_crypto; + if (pj_stricmp(&m_rem->attr[i]->name, &ID_CRYPTO) != 0) + continue; + + /* more than one crypto attribute in media answer */ + if (has_crypto_attr) { + DEACTIVATE_MEDIA(pool, m_loc); + return PJMEDIA_SRTP_ESDPAMBIGUEANS; + } + + has_crypto_attr = PJ_TRUE; + + status = parse_attr_crypto(srtp->pool, m_rem->attr[i], + &tmp_tx_crypto, &rem_tag); + if (status != PJ_SUCCESS) + return status; + + + /* Tag range check, our tags in the offer must be in the SRTP + * setting range, so does the remote answer's. The remote answer's + * tag must not exceed the tag range of the local offer. + */ + if (rem_tag < 1 || rem_tag > (int)srtp->setting.crypto_count || + rem_tag > loc_cryto_cnt) + { + DEACTIVATE_MEDIA(pool, m_loc); + return PJMEDIA_SRTP_ESDPINCRYPTOTAG; + } + + /* match the crypto name */ + if (pj_stricmp(&tmp_tx_crypto.name, &loc_crypto[rem_tag-1].name)) + { + DEACTIVATE_MEDIA(pool, m_loc); + return PJMEDIA_SRTP_ECRYPTONOTMATCH; + } + + /* Find the crypto from the local crypto. */ + for (j = 0; j < (int)loc_cryto_cnt; ++j) { + if (pj_stricmp(&tmp_tx_crypto.name, + &loc_crypto[j].name) == 0) + { + srtp->tx_policy_neg = loc_crypto[j]; + break; + } + } + + srtp->rx_policy_neg = tmp_tx_crypto; } if (srtp->setting.use == PJMEDIA_SRTP_DISABLED) { - /* should never reach here */ - return PJ_SUCCESS; + /* should never reach here */ + return PJ_SUCCESS; } else if (srtp->setting.use == PJMEDIA_SRTP_OPTIONAL) { - if (!has_crypto_attr) - return PJ_SUCCESS; + if (!has_crypto_attr) + return PJ_SUCCESS; } else if (srtp->setting.use == PJMEDIA_SRTP_MANDATORY) { - if (!has_crypto_attr) { - DEACTIVATE_MEDIA(pool, m_loc); - return PJMEDIA_SRTP_ESDPREQCRYPTO; - } + if (!has_crypto_attr) { + DEACTIVATE_MEDIA(pool, m_loc); + return PJMEDIA_SRTP_ESDPREQCRYPTO; + } } /* At this point, we get valid rx_policy_neg & tx_policy_neg. */ diff --git a/pjmedia/src/pjmedia/transport_udp.c b/pjmedia/src/pjmedia/transport_udp.c index 4094d2262e..4c9ebfee37 100644 --- a/pjmedia/src/pjmedia/transport_udp.c +++ b/pjmedia/src/pjmedia/transport_udp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,7 +28,7 @@ #include /* Maximum size of incoming RTP packet */ -#define RTP_LEN PJMEDIA_MAX_MRU +#define RTP_LEN PJMEDIA_MAX_MRU /* Maximum size of incoming RTCP packet */ #define RTCP_LEN 600 @@ -47,58 +46,58 @@ /* Pending write buffer */ typedef struct pending_write { - char buffer[PJMEDIA_MAX_MTU]; - pj_ioqueue_op_key_t op_key; - pj_bool_t is_pending; + char buffer[PJMEDIA_MAX_MTU]; + pj_ioqueue_op_key_t op_key; + pj_bool_t is_pending; } pending_write; struct transport_udp { - pjmedia_transport base; /**< Base transport. */ - - pj_pool_t *pool; /**< Memory pool */ - unsigned options; /**< Transport options. */ - unsigned media_options; /**< Transport media options. */ - void *user_data; /**< Only valid when attached */ - //pj_bool_t attached; /**< Has attachment? */ - pj_bool_t started; /**< Has started? */ - pj_sockaddr rem_rtp_addr; /**< Remote RTP address */ - pj_sockaddr rem_rtcp_addr; /**< Remote RTCP address */ - int addr_len; /**< Length of addresses. */ - void (*rtp_cb)( void*, /**< To report incoming RTP. */ - void*, - pj_ssize_t); + pjmedia_transport base; /**< Base transport. */ + + pj_pool_t *pool; /**< Memory pool */ + unsigned options; /**< Transport options. */ + unsigned media_options; /**< Transport media options. */ + void *user_data; /**< Only valid when attached */ + //pj_bool_t attached; /**< Has attachment? */ + pj_bool_t started; /**< Has started? */ + pj_sockaddr rem_rtp_addr; /**< Remote RTP address */ + pj_sockaddr rem_rtcp_addr; /**< Remote RTCP address */ + int addr_len; /**< Length of addresses. */ + void (*rtp_cb)( void*, /**< To report incoming RTP. */ + void*, + pj_ssize_t); void (*rtp_cb2)(pjmedia_tp_cb_param*); /**< To report incoming RTP. */ - void (*rtcp_cb)( void*, /**< To report incoming RTCP. */ - void*, - pj_ssize_t); - - unsigned tx_drop_pct; /**< Percent of tx pkts to drop. */ - unsigned rx_drop_pct; /**< Percent of rx pkts to drop. */ - pj_ioqueue_t *ioqueue; /**< Ioqueue instance. */ - - pj_sock_t rtp_sock; /**< RTP socket */ - pj_sockaddr rtp_addr_name; /**< Published RTP address. */ - pj_ioqueue_key_t *rtp_key; /**< RTP socket key in ioqueue */ - pj_ioqueue_op_key_t rtp_read_op; /**< Pending read operation */ - unsigned rtp_write_op_id;/**< Next write_op to use */ - pending_write rtp_pending_write[MAX_PENDING]; /**< Pending write */ - pj_sockaddr rtp_src_addr; /**< Actual packet src addr. */ - int rtp_addrlen; /**< Address length. */ - char rtp_pkt[RTP_LEN];/**< Incoming RTP packet buffer */ - - pj_bool_t enable_rtcp_mux;/**< Enable RTP & RTCP multiplexing?*/ - pj_bool_t use_rtcp_mux; /**< Use RTP & RTCP multiplexing? */ - pj_sock_t rtcp_sock; /**< RTCP socket */ - pj_sockaddr rtcp_addr_name; /**< Published RTCP address. */ - pj_sockaddr rtcp_src_addr; /**< Actual source RTCP address. */ - unsigned rtcp_src_cnt; /**< How many pkt from this addr. */ - int rtcp_addr_len; /**< Length of RTCP src address. */ - pj_ioqueue_key_t *rtcp_key; /**< RTCP socket key in ioqueue */ - pj_ioqueue_op_key_t rtcp_read_op; /**< Pending read operation */ - pj_ioqueue_op_key_t rtcp_write_op; /**< Pending write operation */ - char rtcp_pkt[RTCP_LEN];/**< Incoming RTCP packet buffer */ + void (*rtcp_cb)( void*, /**< To report incoming RTCP. */ + void*, + pj_ssize_t); + + unsigned tx_drop_pct; /**< Percent of tx pkts to drop. */ + unsigned rx_drop_pct; /**< Percent of rx pkts to drop. */ + pj_ioqueue_t *ioqueue; /**< Ioqueue instance. */ + + pj_sock_t rtp_sock; /**< RTP socket */ + pj_sockaddr rtp_addr_name; /**< Published RTP address. */ + pj_ioqueue_key_t *rtp_key; /**< RTP socket key in ioqueue */ + pj_ioqueue_op_key_t rtp_read_op; /**< Pending read operation */ + unsigned rtp_write_op_id;/**< Next write_op to use */ + pending_write rtp_pending_write[MAX_PENDING]; /**< Pending write */ + pj_sockaddr rtp_src_addr; /**< Actual packet src addr. */ + int rtp_addrlen; /**< Address length. */ + char rtp_pkt[RTP_LEN];/**< Incoming RTP packet buffer */ + + pj_bool_t enable_rtcp_mux;/**< Enable RTP & RTCP multiplexing?*/ + pj_bool_t use_rtcp_mux; /**< Use RTP & RTCP multiplexing? */ + pj_sock_t rtcp_sock; /**< RTCP socket */ + pj_sockaddr rtcp_addr_name; /**< Published RTCP address. */ + pj_sockaddr rtcp_src_addr; /**< Actual source RTCP address. */ + unsigned rtcp_src_cnt; /**< How many pkt from this addr. */ + int rtcp_addr_len; /**< Length of RTCP src address. */ + pj_ioqueue_key_t *rtcp_key; /**< RTCP socket key in ioqueue */ + pj_ioqueue_op_key_t rtcp_read_op; /**< Pending read operation */ + pj_ioqueue_op_key_t rtcp_write_op; /**< Pending write operation */ + char rtcp_pkt[RTCP_LEN];/**< Incoming RTCP packet buffer */ }; @@ -107,8 +106,8 @@ static void on_rx_rtp( pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, pj_ssize_t bytes_read); static void on_rtp_data_sent(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_sent); + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_sent); static void on_rx_rtcp(pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, pj_ssize_t bytes_read); @@ -117,56 +116,56 @@ static void on_rx_rtcp(pj_ioqueue_key_t *key, * These are media transport operations. */ static pj_status_t transport_get_info (pjmedia_transport *tp, - pjmedia_transport_info *info); + pjmedia_transport_info *info); static pj_status_t transport_attach (pjmedia_transport *tp, - void *user_data, - const pj_sockaddr_t *rem_addr, - const pj_sockaddr_t *rem_rtcp, - unsigned addr_len, - void (*rtp_cb)(void*, - void*, - pj_ssize_t), - void (*rtcp_cb)(void*, - void*, - pj_ssize_t)); + void *user_data, + const pj_sockaddr_t *rem_addr, + const pj_sockaddr_t *rem_rtcp, + unsigned addr_len, + void (*rtp_cb)(void*, + void*, + pj_ssize_t), + void (*rtcp_cb)(void*, + void*, + pj_ssize_t)); static pj_status_t transport_attach2 (pjmedia_transport *tp, - pjmedia_transport_attach_param - *att_param); -static void transport_detach (pjmedia_transport *tp, - void *strm); + pjmedia_transport_attach_param + *att_param); +static void transport_detach (pjmedia_transport *tp, + void *strm); static pj_status_t transport_send_rtp( pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); static pj_status_t transport_send_rtcp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size); + const void *pkt, + pj_size_t size); static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, - const pj_sockaddr_t *addr, - unsigned addr_len, - const void *pkt, - pj_size_t size); + const pj_sockaddr_t *addr, + unsigned addr_len, + const void *pkt, + pj_size_t size); static pj_status_t transport_media_create(pjmedia_transport *tp, - pj_pool_t *pool, - unsigned options, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *pool, + unsigned options, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t transport_encode_sdp(pjmedia_transport *tp, - pj_pool_t *pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index); + pj_pool_t *pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index); static pj_status_t transport_media_start (pjmedia_transport *tp, - pj_pool_t *pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index); + pj_pool_t *pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index); static pj_status_t transport_media_stop(pjmedia_transport *tp); static pj_status_t transport_simulate_lost(pjmedia_transport *tp, - pjmedia_dir dir, - unsigned pct_lost); + pjmedia_dir dir, + unsigned pct_lost); static pj_status_t transport_destroy (pjmedia_transport *tp); static pj_status_t transport_restart (pj_bool_t is_rtp, - struct transport_udp *udp); + struct transport_udp *udp); static pjmedia_transport_op transport_udp_op = { @@ -185,45 +184,45 @@ static pjmedia_transport_op transport_udp_op = &transport_attach2 }; -static const pj_str_t STR_RTCP_MUX = { "rtcp-mux", 8 }; +static const pj_str_t STR_RTCP_MUX = { "rtcp-mux", 8 }; /** * Create UDP stream transport. */ PJ_DEF(pj_status_t) pjmedia_transport_udp_create( pjmedia_endpt *endpt, - const char *name, - int port, - unsigned options, - pjmedia_transport **p_tp) + const char *name, + int port, + unsigned options, + pjmedia_transport **p_tp) { return pjmedia_transport_udp_create2(endpt, name, NULL, port, options, - p_tp); + p_tp); } /** * Create UDP stream transport. */ PJ_DEF(pj_status_t) pjmedia_transport_udp_create2(pjmedia_endpt *endpt, - const char *name, - const pj_str_t *addr, - int port, - unsigned options, - pjmedia_transport **p_tp) + const char *name, + const pj_str_t *addr, + int port, + unsigned options, + pjmedia_transport **p_tp) { return pjmedia_transport_udp_create3(endpt, pj_AF_INET(), name, - addr, port, options, p_tp); + addr, port, options, p_tp); } /** * Create UDP stream transport. */ PJ_DEF(pj_status_t) pjmedia_transport_udp_create3(pjmedia_endpt *endpt, - int af, - const char *name, - const pj_str_t *addr, - int port, - unsigned options, - pjmedia_transport **p_tp) + int af, + const char *name, + const pj_str_t *addr, + int port, + unsigned options, + pjmedia_transport **p_tp) { pjmedia_sock_info si; pj_status_t status; @@ -239,34 +238,34 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_create3(pjmedia_endpt *endpt, /* Create RTP socket */ status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &si.rtp_sock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Bind RTP socket */ status = pj_sockaddr_init(af, &si.rtp_addr_name, addr, (pj_uint16_t)port); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_sock_bind(si.rtp_sock, &si.rtp_addr_name, - pj_sockaddr_get_len(&si.rtp_addr_name)); + pj_sockaddr_get_len(&si.rtp_addr_name)); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create RTCP socket */ status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &si.rtcp_sock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Bind RTCP socket */ status = pj_sockaddr_init(af, &si.rtcp_addr_name, addr, - (pj_uint16_t)(port+1)); + (pj_uint16_t)(port+1)); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_sock_bind(si.rtcp_sock, &si.rtcp_addr_name, - pj_sockaddr_get_len(&si.rtcp_addr_name)); + pj_sockaddr_get_len(&si.rtcp_addr_name)); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create UDP transport by attaching socket info */ @@ -275,9 +274,9 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_create3(pjmedia_endpt *endpt, on_error: if (si.rtp_sock != PJ_INVALID_SOCKET) - pj_sock_close(si.rtp_sock); + pj_sock_close(si.rtp_sock); if (si.rtcp_sock != PJ_INVALID_SOCKET) - pj_sock_close(si.rtcp_sock); + pj_sock_close(si.rtcp_sock); return status; } @@ -286,10 +285,10 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_create3(pjmedia_endpt *endpt, * Create UDP stream transport from existing socket info. */ PJ_DEF(pj_status_t) pjmedia_transport_udp_attach( pjmedia_endpt *endpt, - const char *name, - const pjmedia_sock_info *si, - unsigned options, - pjmedia_transport **p_tp) + const char *name, + const pjmedia_sock_info *si, + unsigned options, + pjmedia_transport **p_tp) { struct transport_udp *tp; pj_pool_t *pool; @@ -305,12 +304,12 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_attach( pjmedia_endpt *endpt, ioqueue = pjmedia_endpt_get_ioqueue(endpt); if (name==NULL) - name = "udp%p"; + name = "udp%p"; /* Create transport structure */ pool = pjmedia_endpt_create_pool(endpt, name, 512, 512); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; tp = PJ_POOL_ZALLOC_T(pool, struct transport_udp); tp->pool = pool; @@ -327,22 +326,22 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_attach( pjmedia_endpt *endpt, /* If address is 0.0.0.0, use host's IP address */ if (!pj_sockaddr_has_addr(&tp->rtp_addr_name)) { - pj_sockaddr hostip; + pj_sockaddr hostip; - status = pj_gethostip(tp->rtp_addr_name.addr.sa_family, &hostip); - if (status != PJ_SUCCESS) - goto on_error; + status = pj_gethostip(tp->rtp_addr_name.addr.sa_family, &hostip); + if (status != PJ_SUCCESS) + goto on_error; - pj_memcpy(pj_sockaddr_get_addr(&tp->rtp_addr_name), - pj_sockaddr_get_addr(&hostip), - pj_sockaddr_get_addr_len(&hostip)); + pj_memcpy(pj_sockaddr_get_addr(&tp->rtp_addr_name), + pj_sockaddr_get_addr(&hostip), + pj_sockaddr_get_addr_len(&hostip)); } /* Same with RTCP */ if (!pj_sockaddr_has_addr(&tp->rtcp_addr_name)) { - pj_memcpy(pj_sockaddr_get_addr(&tp->rtcp_addr_name), - pj_sockaddr_get_addr(&tp->rtp_addr_name), - pj_sockaddr_get_addr_len(&tp->rtp_addr_name)); + pj_memcpy(pj_sockaddr_get_addr(&tp->rtcp_addr_name), + pj_sockaddr_get_addr(&tp->rtp_addr_name), + pj_sockaddr_get_addr_len(&tp->rtp_addr_name)); } /* Setup RTP socket with the ioqueue */ @@ -351,33 +350,33 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_attach( pjmedia_endpt *endpt, rtp_cb.on_write_complete = &on_rtp_data_sent; status = pj_ioqueue_register_sock(pool, ioqueue, tp->rtp_sock, tp, - &rtp_cb, &tp->rtp_key); + &rtp_cb, &tp->rtp_key); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Disallow concurrency so that detach() and destroy() are * synchronized with the callback. */ status = pj_ioqueue_set_concurrency(tp->rtp_key, PJ_FALSE); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #if 0 // See #2097: move read op kick-off to media_start() pj_ioqueue_op_key_init(&tp->rtp_read_op, sizeof(tp->rtp_read_op)); for (i=0; irtp_pending_write); ++i) { tp->rtp_pending_write[i].is_pending = PJ_FALSE; - pj_ioqueue_op_key_init(&tp->rtp_pending_write[i].op_key, - sizeof(tp->rtp_pending_write[i].op_key)); + pj_ioqueue_op_key_init(&tp->rtp_pending_write[i].op_key, + sizeof(tp->rtp_pending_write[i].op_key)); } /* Kick of pending RTP read from the ioqueue */ tp->rtp_addrlen = sizeof(tp->rtp_src_addr); size = sizeof(tp->rtp_pkt); status = pj_ioqueue_recvfrom(tp->rtp_key, &tp->rtp_read_op, - tp->rtp_pkt, &size, PJ_IOQUEUE_ALWAYS_ASYNC, - &tp->rtp_src_addr, &tp->rtp_addrlen); + tp->rtp_pkt, &size, PJ_IOQUEUE_ALWAYS_ASYNC, + &tp->rtp_src_addr, &tp->rtp_addrlen); if (status != PJ_EPENDING) - goto on_error; + goto on_error; #endif @@ -386,13 +385,13 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_attach( pjmedia_endpt *endpt, rtcp_cb.on_read_complete = &on_rx_rtcp; status = pj_ioqueue_register_sock(pool, ioqueue, tp->rtcp_sock, tp, - &rtcp_cb, &tp->rtcp_key); + &rtcp_cb, &tp->rtcp_key); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_ioqueue_set_concurrency(tp->rtcp_key, PJ_FALSE); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #if 0 // See #2097: move read op kick-off to media_start() pj_ioqueue_op_key_init(&tp->rtcp_read_op, sizeof(tp->rtcp_read_op)); @@ -402,11 +401,11 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_attach( pjmedia_endpt *endpt, size = sizeof(tp->rtcp_pkt); tp->rtcp_addr_len = sizeof(tp->rtcp_src_addr); status = pj_ioqueue_recvfrom( tp->rtcp_key, &tp->rtcp_read_op, - tp->rtcp_pkt, &size, PJ_IOQUEUE_ALWAYS_ASYNC, - &tp->rtcp_src_addr, &tp->rtcp_addr_len); + tp->rtcp_pkt, &size, PJ_IOQUEUE_ALWAYS_ASYNC, + &tp->rtcp_src_addr, &tp->rtcp_addr_len); if (status != PJ_EPENDING) - goto on_error; -#endif + goto on_error; +#endif tp->ioqueue = ioqueue; @@ -436,24 +435,24 @@ static pj_status_t transport_destroy(pjmedia_transport *tp) if (udp->rtp_key) { - /* This will block the execution if callback is still - * being called. - */ - pj_ioqueue_unregister(udp->rtp_key); - udp->rtp_key = NULL; - udp->rtp_sock = PJ_INVALID_SOCKET; + /* This will block the execution if callback is still + * being called. + */ + pj_ioqueue_unregister(udp->rtp_key); + udp->rtp_key = NULL; + udp->rtp_sock = PJ_INVALID_SOCKET; } else if (udp->rtp_sock != PJ_INVALID_SOCKET) { - pj_sock_close(udp->rtp_sock); - udp->rtp_sock = PJ_INVALID_SOCKET; + pj_sock_close(udp->rtp_sock); + udp->rtp_sock = PJ_INVALID_SOCKET; } if (udp->rtcp_key) { - pj_ioqueue_unregister(udp->rtcp_key); - udp->rtcp_key = NULL; - udp->rtcp_sock = PJ_INVALID_SOCKET; + pj_ioqueue_unregister(udp->rtcp_key); + udp->rtcp_key = NULL; + udp->rtcp_sock = PJ_INVALID_SOCKET; } else if (udp->rtcp_sock != PJ_INVALID_SOCKET) { - pj_sock_close(udp->rtcp_sock); - udp->rtcp_sock = PJ_INVALID_SOCKET; + pj_sock_close(udp->rtcp_sock); + udp->rtcp_sock = PJ_INVALID_SOCKET; } PJ_LOG(4,(udp->base.name, "UDP media transport destroyed")); @@ -464,7 +463,7 @@ static pj_status_t transport_destroy(pjmedia_transport *tp) /* Call RTP cb. */ static void call_rtp_cb(struct transport_udp *udp, pj_ssize_t bytes_read, - pj_bool_t *rem_switch) + pj_bool_t *rem_switch) { void (*cb)(void*,void*,pj_ssize_t); void (*cb2)(pjmedia_tp_cb_param*); @@ -475,18 +474,18 @@ static void call_rtp_cb(struct transport_udp *udp, pj_ssize_t bytes_read, user_data = udp->user_data; if (cb2) { - pjmedia_tp_cb_param param; - - param.user_data = user_data; - param.pkt = udp->rtp_pkt; - param.size = bytes_read; - param.src_addr = &udp->rtp_src_addr; - param.rem_switch = PJ_FALSE; - (*cb2)(¶m); - if (rem_switch) - *rem_switch = param.rem_switch; + pjmedia_tp_cb_param param; + + param.user_data = user_data; + param.pkt = udp->rtp_pkt; + param.size = bytes_read; + param.src_addr = &udp->rtp_src_addr; + param.rem_switch = PJ_FALSE; + (*cb2)(¶m); + if (rem_switch) + *rem_switch = param.rem_switch; } else if (cb) { - (*cb)(user_data, udp->rtp_pkt, bytes_read); + (*cb)(user_data, udp->rtp_pkt, bytes_read); } } @@ -500,13 +499,13 @@ static void call_rtcp_cb(struct transport_udp *udp, pj_ssize_t bytes_read) user_data = udp->user_data; if (cb) - (*cb)(user_data, udp->rtcp_pkt, bytes_read); + (*cb)(user_data, udp->rtcp_pkt, bytes_read); } /* Notification from ioqueue about incoming RTP packet */ static void on_rx_rtp(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_read) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_read) { struct transport_udp *udp; pj_status_t status; @@ -520,126 +519,126 @@ static void on_rx_rtp(pj_ioqueue_key_t *key, udp = (struct transport_udp*) pj_ioqueue_get_user_data(key); if (-bytes_read == PJ_ECANCELLED) { - TRACE_((udp->base.name, "on_rx_rtp(): got PJ_ECANCELLED")); - return; + TRACE_((udp->base.name, "on_rx_rtp(): got PJ_ECANCELLED")); + return; } if (-bytes_read == PJ_ESOCKETSTOP) { - TRACE_((udp->base.name, "on_rx_rtp(): got PJ_ESOCKETSTOP")); - - /* Try to recover by restarting the transport. */ - status = transport_restart(PJ_TRUE, udp); - if (status != PJ_SUCCESS) { - bytes_read = -PJ_ESOCKETSTOP; - call_rtp_cb(udp, bytes_read, NULL); - } - return; + TRACE_((udp->base.name, "on_rx_rtp(): got PJ_ESOCKETSTOP")); + + /* Try to recover by restarting the transport. */ + status = transport_restart(PJ_TRUE, udp); + if (status != PJ_SUCCESS) { + bytes_read = -PJ_ESOCKETSTOP; + call_rtp_cb(udp, bytes_read, NULL); + } + return; } do { - pj_bool_t discard = PJ_FALSE; - - /* Simulate packet lost on RX direction */ - if (udp->rx_drop_pct) { - if ((pj_rand() % 100) <= (int)udp->rx_drop_pct) { - PJ_LOG(5,(udp->base.name, - "RX RTP packet dropped because of pkt lost " - "simulation")); - discard = PJ_TRUE; - } - } - - //if (!discard && udp->attached && cb) - if (!discard && - (-bytes_read != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL))) - { - call_rtp_cb(udp, bytes_read, &rem_switch); - } + pj_bool_t discard = PJ_FALSE; + + /* Simulate packet lost on RX direction */ + if (udp->rx_drop_pct) { + if ((pj_rand() % 100) <= (int)udp->rx_drop_pct) { + PJ_LOG(5,(udp->base.name, + "RX RTP packet dropped because of pkt lost " + "simulation")); + discard = PJ_TRUE; + } + } + + //if (!discard && udp->attached && cb) + if (!discard && + (-bytes_read != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL))) + { + call_rtp_cb(udp, bytes_read, &rem_switch); + } #if defined(PJMEDIA_TRANSPORT_SWITCH_REMOTE_ADDR) && \ (PJMEDIA_TRANSPORT_SWITCH_REMOTE_ADDR == 1) - if (rem_switch && - (udp->options & PJMEDIA_UDP_NO_SRC_ADDR_CHECKING)==0) - { - char addr_text[PJ_INET6_ADDRSTRLEN+10]; - - /* Set remote RTP address to source address */ - pj_sockaddr_cp(&udp->rem_rtp_addr, &udp->rtp_src_addr); - - PJ_LOG(4,(udp->base.name, - "Remote RTP address switched to %s", - pj_sockaddr_print(&udp->rtp_src_addr, addr_text, - sizeof(addr_text), 3))); - - if (udp->use_rtcp_mux) { - pj_sockaddr_cp(&udp->rem_rtcp_addr, &udp->rem_rtp_addr); - pj_sockaddr_cp(&udp->rtcp_src_addr, &udp->rem_rtcp_addr); - } else if (!pj_sockaddr_has_addr(&udp->rtcp_src_addr)) { - /* Also update remote RTCP address if actual RTCP source - * address is not heard yet. - */ - pj_uint16_t port; - - pj_sockaddr_cp(&udp->rem_rtcp_addr, &udp->rem_rtp_addr); - port = (pj_uint16_t) - (pj_sockaddr_get_port(&udp->rem_rtp_addr)+1); - pj_sockaddr_set_port(&udp->rem_rtcp_addr, port); - - pj_sockaddr_cp(&udp->rtcp_src_addr, &udp->rem_rtcp_addr); - - PJ_LOG(4,(udp->base.name, - "Remote RTCP address switched to predicted" - " address %s", - pj_sockaddr_print(&udp->rtcp_src_addr, addr_text, - sizeof(addr_text), 3))); - } - } + if (rem_switch && + (udp->options & PJMEDIA_UDP_NO_SRC_ADDR_CHECKING)==0) + { + char addr_text[PJ_INET6_ADDRSTRLEN+10]; + + /* Set remote RTP address to source address */ + pj_sockaddr_cp(&udp->rem_rtp_addr, &udp->rtp_src_addr); + + PJ_LOG(4,(udp->base.name, + "Remote RTP address switched to %s", + pj_sockaddr_print(&udp->rtp_src_addr, addr_text, + sizeof(addr_text), 3))); + + if (udp->use_rtcp_mux) { + pj_sockaddr_cp(&udp->rem_rtcp_addr, &udp->rem_rtp_addr); + pj_sockaddr_cp(&udp->rtcp_src_addr, &udp->rem_rtcp_addr); + } else if (!pj_sockaddr_has_addr(&udp->rtcp_src_addr)) { + /* Also update remote RTCP address if actual RTCP source + * address is not heard yet. + */ + pj_uint16_t port; + + pj_sockaddr_cp(&udp->rem_rtcp_addr, &udp->rem_rtp_addr); + port = (pj_uint16_t) + (pj_sockaddr_get_port(&udp->rem_rtp_addr)+1); + pj_sockaddr_set_port(&udp->rem_rtcp_addr, port); + + pj_sockaddr_cp(&udp->rtcp_src_addr, &udp->rem_rtcp_addr); + + PJ_LOG(4,(udp->base.name, + "Remote RTCP address switched to predicted" + " address %s", + pj_sockaddr_print(&udp->rtcp_src_addr, addr_text, + sizeof(addr_text), 3))); + } + } #endif - bytes_read = sizeof(udp->rtp_pkt); - udp->rtp_addrlen = sizeof(udp->rtp_src_addr); - status = pj_ioqueue_recvfrom(udp->rtp_key, &udp->rtp_read_op, - udp->rtp_pkt, &bytes_read, 0, - &udp->rtp_src_addr, - &udp->rtp_addrlen); - - if (status != PJ_EPENDING && status != PJ_SUCCESS) { - if (transport_restarted && last_err == status) { - /* Still the same error after restart */ - bytes_read = -PJ_ESOCKETSTOP; - call_rtp_cb(udp, bytes_read, NULL); - break; - } else if (PJMEDIA_IGNORE_RECV_ERR_CNT) { - if (last_err == status) { - ++num_err; - } else { - num_err = 1; - last_err = status; - } - - if (status == PJ_ESOCKETSTOP || - num_err > PJMEDIA_IGNORE_RECV_ERR_CNT) - { - status = transport_restart(PJ_TRUE, udp); - if (status != PJ_SUCCESS) { - bytes_read = -PJ_ESOCKETSTOP; - call_rtp_cb(udp, bytes_read, NULL); - break; - } - transport_restarted = PJ_TRUE; - num_err = 0; - } - } - bytes_read = -status; - TRACE_((udp->base.name, "on_rx_rtp(): recvfrom error=%d", status)); - } + bytes_read = sizeof(udp->rtp_pkt); + udp->rtp_addrlen = sizeof(udp->rtp_src_addr); + status = pj_ioqueue_recvfrom(udp->rtp_key, &udp->rtp_read_op, + udp->rtp_pkt, &bytes_read, 0, + &udp->rtp_src_addr, + &udp->rtp_addrlen); + + if (status != PJ_EPENDING && status != PJ_SUCCESS) { + if (transport_restarted && last_err == status) { + /* Still the same error after restart */ + bytes_read = -PJ_ESOCKETSTOP; + call_rtp_cb(udp, bytes_read, NULL); + break; + } else if (PJMEDIA_IGNORE_RECV_ERR_CNT) { + if (last_err == status) { + ++num_err; + } else { + num_err = 1; + last_err = status; + } + + if (status == PJ_ESOCKETSTOP || + num_err > PJMEDIA_IGNORE_RECV_ERR_CNT) + { + status = transport_restart(PJ_TRUE, udp); + if (status != PJ_SUCCESS) { + bytes_read = -PJ_ESOCKETSTOP; + call_rtp_cb(udp, bytes_read, NULL); + break; + } + transport_restarted = PJ_TRUE; + num_err = 0; + } + } + bytes_read = -status; + TRACE_((udp->base.name, "on_rx_rtp(): recvfrom error=%d", status)); + } } while (status != PJ_EPENDING && status != PJ_ECANCELLED && - udp->started); + udp->started); } static void on_rtp_data_sent(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_sent) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_sent) { struct transport_udp *udp; unsigned i; @@ -649,10 +648,10 @@ static void on_rtp_data_sent(pj_ioqueue_key_t *key, udp = (struct transport_udp*) pj_ioqueue_get_user_data(key); for (i = 0; i < PJ_ARRAY_SIZE(udp->rtp_pending_write); ++i) { - if (&udp->rtp_pending_write[i].op_key == op_key) { - udp->rtp_pending_write[i].is_pending = PJ_FALSE; - break; - } + if (&udp->rtp_pending_write[i].op_key == op_key) { + udp->rtp_pending_write[i].is_pending = PJ_FALSE; + break; + } } } @@ -672,101 +671,101 @@ static void on_rx_rtcp(pj_ioqueue_key_t *key, udp = (struct transport_udp*) pj_ioqueue_get_user_data(key); if (-bytes_read == PJ_ECANCELLED) { - TRACE_((udp->base.name, "on_rx_rtcp(): got PJ_ECANCELLED")); - return; + TRACE_((udp->base.name, "on_rx_rtcp(): got PJ_ECANCELLED")); + return; } if (-bytes_read == PJ_ESOCKETSTOP) { - TRACE_((udp->base.name, "on_rx_rtcp(): got PJ_ESOCKETSTOP")); - - /* Try to recover by restarting the transport. */ - status = transport_restart(PJ_FALSE, udp); - if (status != PJ_SUCCESS) { - bytes_read = -PJ_ESOCKETSTOP; - call_rtcp_cb(udp, bytes_read); - } - return; + TRACE_((udp->base.name, "on_rx_rtcp(): got PJ_ESOCKETSTOP")); + + /* Try to recover by restarting the transport. */ + status = transport_restart(PJ_FALSE, udp); + if (status != PJ_SUCCESS) { + bytes_read = -PJ_ESOCKETSTOP; + call_rtcp_cb(udp, bytes_read); + } + return; } do { - call_rtcp_cb(udp, bytes_read); + call_rtcp_cb(udp, bytes_read); #if defined(PJMEDIA_TRANSPORT_SWITCH_REMOTE_ADDR) && \ (PJMEDIA_TRANSPORT_SWITCH_REMOTE_ADDR == 1) - /* Check if RTCP source address is the same as the configured - * remote address, and switch the address when they are - * different. - */ - if (bytes_read>0 && - (udp->options & PJMEDIA_UDP_NO_SRC_ADDR_CHECKING)==0) - { - if (pj_sockaddr_cmp(&udp->rem_rtcp_addr, &udp->rtcp_src_addr) == 0) { - /* Still receiving from rem_rtcp_addr, don't switch */ - udp->rtcp_src_cnt = 0; - } else { - ++udp->rtcp_src_cnt; - - if (udp->rtcp_src_cnt >= PJMEDIA_RTCP_NAT_PROBATION_CNT ) { - char addr_text[PJ_INET6_ADDRSTRLEN+10]; - - udp->rtcp_src_cnt = 0; - pj_memcpy(&udp->rem_rtcp_addr, &udp->rtcp_src_addr, - sizeof(pj_sockaddr)); - - PJ_LOG(4,(udp->base.name, - "Remote RTCP address switched to %s", - pj_sockaddr_print(&udp->rtcp_src_addr, addr_text, - sizeof(addr_text), 3))); - } - } - } + /* Check if RTCP source address is the same as the configured + * remote address, and switch the address when they are + * different. + */ + if (bytes_read>0 && + (udp->options & PJMEDIA_UDP_NO_SRC_ADDR_CHECKING)==0) + { + if (pj_sockaddr_cmp(&udp->rem_rtcp_addr, &udp->rtcp_src_addr) == 0) { + /* Still receiving from rem_rtcp_addr, don't switch */ + udp->rtcp_src_cnt = 0; + } else { + ++udp->rtcp_src_cnt; + + if (udp->rtcp_src_cnt >= PJMEDIA_RTCP_NAT_PROBATION_CNT ) { + char addr_text[PJ_INET6_ADDRSTRLEN+10]; + + udp->rtcp_src_cnt = 0; + pj_memcpy(&udp->rem_rtcp_addr, &udp->rtcp_src_addr, + sizeof(pj_sockaddr)); + + PJ_LOG(4,(udp->base.name, + "Remote RTCP address switched to %s", + pj_sockaddr_print(&udp->rtcp_src_addr, addr_text, + sizeof(addr_text), 3))); + } + } + } #endif - bytes_read = sizeof(udp->rtcp_pkt); - udp->rtcp_addr_len = sizeof(udp->rtcp_src_addr); - status = pj_ioqueue_recvfrom(udp->rtcp_key, &udp->rtcp_read_op, - udp->rtcp_pkt, &bytes_read, 0, - &udp->rtcp_src_addr, - &udp->rtcp_addr_len); - - if (status != PJ_EPENDING && status != PJ_SUCCESS) { - if (transport_restarted && last_err == status) { - /* Still the same error after restart */ - bytes_read = -PJ_ESOCKETSTOP; - call_rtcp_cb(udp, bytes_read); - break; - } else if (PJMEDIA_IGNORE_RECV_ERR_CNT) { - if (last_err == status) { - ++num_err; - } else { - num_err = 1; - last_err = status; - } - - if (status == PJ_ESOCKETSTOP || - num_err > PJMEDIA_IGNORE_RECV_ERR_CNT) - { - status = transport_restart(PJ_FALSE, udp); - if (status != PJ_SUCCESS) { - bytes_read = -PJ_ESOCKETSTOP; - call_rtcp_cb(udp, bytes_read); - break; - } - transport_restarted = PJ_TRUE; - num_err = 0; - } - } - bytes_read = -status; - TRACE_((udp->base.name, "on_rx_rtcp(): recvfrom error=%d", status)); - } + bytes_read = sizeof(udp->rtcp_pkt); + udp->rtcp_addr_len = sizeof(udp->rtcp_src_addr); + status = pj_ioqueue_recvfrom(udp->rtcp_key, &udp->rtcp_read_op, + udp->rtcp_pkt, &bytes_read, 0, + &udp->rtcp_src_addr, + &udp->rtcp_addr_len); + + if (status != PJ_EPENDING && status != PJ_SUCCESS) { + if (transport_restarted && last_err == status) { + /* Still the same error after restart */ + bytes_read = -PJ_ESOCKETSTOP; + call_rtcp_cb(udp, bytes_read); + break; + } else if (PJMEDIA_IGNORE_RECV_ERR_CNT) { + if (last_err == status) { + ++num_err; + } else { + num_err = 1; + last_err = status; + } + + if (status == PJ_ESOCKETSTOP || + num_err > PJMEDIA_IGNORE_RECV_ERR_CNT) + { + status = transport_restart(PJ_FALSE, udp); + if (status != PJ_SUCCESS) { + bytes_read = -PJ_ESOCKETSTOP; + call_rtcp_cb(udp, bytes_read); + break; + } + transport_restarted = PJ_TRUE; + num_err = 0; + } + } + bytes_read = -status; + TRACE_((udp->base.name, "on_rx_rtcp(): recvfrom error=%d", status)); + } } while (status != PJ_EPENDING && status != PJ_ECANCELLED && - udp->started); + udp->started); } /* Called to get the transport info */ static pj_status_t transport_get_info(pjmedia_transport *tp, - pjmedia_transport_info *info) + pjmedia_transport_info *info) { struct transport_udp *udp = (struct transport_udp*)tp; PJ_ASSERT_RETURN(tp && info, PJ_EINVAL); @@ -775,8 +774,8 @@ static pj_status_t transport_get_info(pjmedia_transport *tp, info->sock_info.rtp_addr_name = udp->rtp_addr_name; info->sock_info.rtcp_sock = udp->rtcp_sock; info->sock_info.rtcp_addr_name = (udp->use_rtcp_mux? - udp->rtp_addr_name: - udp->rtcp_addr_name); + udp->rtp_addr_name: + udp->rtcp_addr_name); /* Get remote address originating RTP & RTCP. */ info->src_rtp_name = udp->rtp_src_addr; @@ -784,29 +783,29 @@ static pj_status_t transport_get_info(pjmedia_transport *tp, /* Add empty specific info */ if (info->specific_info_cnt < PJ_ARRAY_SIZE(info->spc_info)) { - pjmedia_transport_specific_info *tsi; + pjmedia_transport_specific_info *tsi; - tsi = &info->spc_info[info->specific_info_cnt++]; - tsi->type = PJMEDIA_TRANSPORT_TYPE_UDP; - tsi->cbsize = 0; + tsi = &info->spc_info[info->specific_info_cnt++]; + tsi->type = PJMEDIA_TRANSPORT_TYPE_UDP; + tsi->cbsize = 0; } return PJ_SUCCESS; } -static pj_status_t tp_attach (pjmedia_transport *tp, - void *user_data, - const pj_sockaddr_t *rem_addr, - const pj_sockaddr_t *rem_rtcp, - unsigned addr_len, - void (*rtp_cb)(void*, - void*, - pj_ssize_t), - void (*rtp_cb2)(pjmedia_tp_cb_param*), - void (*rtcp_cb)(void*, - void*, - pj_ssize_t)) +static pj_status_t tp_attach (pjmedia_transport *tp, + void *user_data, + const pj_sockaddr_t *rem_addr, + const pj_sockaddr_t *rem_rtcp, + unsigned addr_len, + void (*rtp_cb)(void*, + void*, + pj_ssize_t), + void (*rtp_cb2)(pjmedia_tp_cb_param*), + void (*rtcp_cb)(void*, + void*, + pj_ssize_t)) { struct transport_udp *udp = (struct transport_udp*) tp; const pj_sockaddr *rtcp_addr; @@ -822,7 +821,7 @@ static pj_status_t tp_attach (pjmedia_transport *tp, /* Check again if we are multiplexing RTP & RTCP. */ udp->use_rtcp_mux = (pj_sockaddr_has_addr(rem_addr) && - pj_sockaddr_cmp(rem_addr, rem_rtcp) == 0); + pj_sockaddr_cmp(rem_addr, rem_rtcp) == 0); TRACE_((udp->base.name, "attach(): before locking keys")); @@ -841,10 +840,10 @@ static pj_status_t tp_attach (pjmedia_transport *tp, /* Synthesize address, if necessary. */ status = pj_sockaddr_synthesize(sock_addr.addr.sa_family, - &remote_addr, rem_addr); + &remote_addr, rem_addr); if (status != PJ_SUCCESS) { - pj_perror(3, tp->name, status, "Failed to synthesize the correct" - "IP address for RTP"); + pj_perror(3, tp->name, status, "Failed to synthesize the correct" + "IP address for RTP"); } rem_addr_len = pj_sockaddr_get_len(&remote_addr); @@ -855,20 +854,20 @@ static pj_status_t tp_attach (pjmedia_transport *tp, rtcp_addr = (const pj_sockaddr*) rem_rtcp; if (rtcp_addr && pj_sockaddr_has_addr(rtcp_addr)) { status = pj_sockaddr_synthesize(sock_addr.addr.sa_family, - &remote_rtcp, rem_rtcp); + &remote_rtcp, rem_rtcp); if (status != PJ_SUCCESS) { - pj_perror(3, tp->name, status, "Failed to synthesize the correct" - "IP address for RTCP"); + pj_perror(3, tp->name, status, "Failed to synthesize the correct" + "IP address for RTCP"); } - pj_memcpy(&udp->rem_rtcp_addr, &remote_rtcp, rem_addr_len); + pj_memcpy(&udp->rem_rtcp_addr, &remote_rtcp, rem_addr_len); } else { - unsigned rtcp_port; + unsigned rtcp_port; - /* Otherwise guess the RTCP address from the RTP address */ - pj_memcpy(&udp->rem_rtcp_addr, &udp->rem_rtp_addr, rem_addr_len); - rtcp_port = pj_sockaddr_get_port(&udp->rem_rtp_addr) + 1; - pj_sockaddr_set_port(&udp->rem_rtcp_addr, (pj_uint16_t)rtcp_port); + /* Otherwise guess the RTCP address from the RTP address */ + pj_memcpy(&udp->rem_rtcp_addr, &udp->rem_rtp_addr, rem_addr_len); + rtcp_port = pj_sockaddr_get_port(&udp->rem_rtp_addr) + 1; + pj_sockaddr_set_port(&udp->rem_rtcp_addr, (pj_uint16_t)rtcp_port); } /* Save the callbacks */ @@ -891,42 +890,42 @@ static pj_status_t tp_attach (pjmedia_transport *tp, /* Set buffer size for RTP socket */ #if PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE { - unsigned sobuf_size = PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE; - - status = pj_sock_setsockopt_sobuf(udp->rtp_sock, pj_SO_RCVBUF(), - PJ_TRUE, &sobuf_size); - if (status != PJ_SUCCESS) { - pj_perror(3, tp->name, status, "Failed setting SO_RCVBUF"); - } else { - if (sobuf_size < PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE) { - PJ_LOG(4, (tp->name, - "Warning! Cannot set SO_RCVBUF as configured, " - "now=%d, configured=%d", - sobuf_size, PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE)); - } else { - PJ_LOG(5, (tp->name, "SO_RCVBUF set to %d", sobuf_size)); - } - } + unsigned sobuf_size = PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE; + + status = pj_sock_setsockopt_sobuf(udp->rtp_sock, pj_SO_RCVBUF(), + PJ_TRUE, &sobuf_size); + if (status != PJ_SUCCESS) { + pj_perror(3, tp->name, status, "Failed setting SO_RCVBUF"); + } else { + if (sobuf_size < PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE) { + PJ_LOG(4, (tp->name, + "Warning! Cannot set SO_RCVBUF as configured, " + "now=%d, configured=%d", + sobuf_size, PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE)); + } else { + PJ_LOG(5, (tp->name, "SO_RCVBUF set to %d", sobuf_size)); + } + } } #endif #if PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE { - unsigned sobuf_size = PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE; - - status = pj_sock_setsockopt_sobuf(udp->rtp_sock, pj_SO_SNDBUF(), - PJ_TRUE, &sobuf_size); - if (status != PJ_SUCCESS) { - pj_perror(3, tp->name, status, "Failed setting SO_SNDBUF"); - } else { - if (sobuf_size < PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE) { - PJ_LOG(4, (tp->name, - "Warning! Cannot set SO_SNDBUF as configured, " - "now=%d, configured=%d", - sobuf_size, PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE)); - } else { - PJ_LOG(5, (tp->name, "SO_SNDBUF set to %d", sobuf_size)); - } - } + unsigned sobuf_size = PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE; + + status = pj_sock_setsockopt_sobuf(udp->rtp_sock, pj_SO_SNDBUF(), + PJ_TRUE, &sobuf_size); + if (status != PJ_SUCCESS) { + pj_perror(3, tp->name, status, "Failed setting SO_SNDBUF"); + } else { + if (sobuf_size < PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE) { + PJ_LOG(4, (tp->name, + "Warning! Cannot set SO_SNDBUF as configured, " + "now=%d, configured=%d", + sobuf_size, PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE)); + } else { + PJ_LOG(5, (tp->name, "SO_SNDBUF set to %d", sobuf_size)); + } + } } #endif @@ -942,37 +941,37 @@ static pj_status_t tp_attach (pjmedia_transport *tp, /* Called by application to initialize the transport */ static pj_status_t transport_attach( pjmedia_transport *tp, - void *user_data, - const pj_sockaddr_t *rem_addr, - const pj_sockaddr_t *rem_rtcp, - unsigned addr_len, - void (*rtp_cb)(void*, - void*, - pj_ssize_t), - void (*rtcp_cb)(void*, - void*, - pj_ssize_t)) + void *user_data, + const pj_sockaddr_t *rem_addr, + const pj_sockaddr_t *rem_rtcp, + unsigned addr_len, + void (*rtp_cb)(void*, + void*, + pj_ssize_t), + void (*rtcp_cb)(void*, + void*, + pj_ssize_t)) { return tp_attach(tp, user_data, rem_addr, rem_rtcp, addr_len, - rtp_cb, NULL, rtcp_cb); + rtp_cb, NULL, rtcp_cb); } static pj_status_t transport_attach2(pjmedia_transport *tp, - pjmedia_transport_attach_param *att_param) + pjmedia_transport_attach_param *att_param) { return tp_attach(tp, att_param->user_data, - (pj_sockaddr_t*)&att_param->rem_addr, - (pj_sockaddr_t*)&att_param->rem_rtcp, - att_param->addr_len, att_param->rtp_cb, - att_param->rtp_cb2, - att_param->rtcp_cb); + (pj_sockaddr_t*)&att_param->rem_addr, + (pj_sockaddr_t*)&att_param->rem_rtcp, + att_param->addr_len, att_param->rtp_cb, + att_param->rtp_cb2, + att_param->rtcp_cb); } /* Called by application when it no longer needs the transport */ static void transport_detach( pjmedia_transport *tp, - void *user_data) + void *user_data) { struct transport_udp *udp = (struct transport_udp*) tp; @@ -980,52 +979,52 @@ static void transport_detach( pjmedia_transport *tp, //if (udp->attached) { if (1) { - /* Lock the ioqueue keys to make sure that callbacks are - * not executed. See ticket #460 for details. - */ + /* Lock the ioqueue keys to make sure that callbacks are + * not executed. See ticket #460 for details. + */ - TRACE_((udp->base.name, "detach(): before locking keys")); + TRACE_((udp->base.name, "detach(): before locking keys")); - pj_ioqueue_lock_key(udp->rtp_key); - pj_ioqueue_lock_key(udp->rtcp_key); + pj_ioqueue_lock_key(udp->rtp_key); + pj_ioqueue_lock_key(udp->rtcp_key); - TRACE_((udp->base.name, "detach(): inside locked keys")); + TRACE_((udp->base.name, "detach(): inside locked keys")); - /* User data is unreferenced on Release build */ - PJ_UNUSED_ARG(user_data); + /* User data is unreferenced on Release build */ + PJ_UNUSED_ARG(user_data); - /* As additional checking, check if the same user data is specified */ - pj_assert(!udp->user_data || user_data == udp->user_data); + /* As additional checking, check if the same user data is specified */ + pj_assert(!udp->user_data || user_data == udp->user_data); - /* First, mark transport as unattached */ - //udp->attached = PJ_FALSE; + /* First, mark transport as unattached */ + //udp->attached = PJ_FALSE; - /* Clear up application infos from transport */ - udp->rtp_cb = NULL; - udp->rtp_cb2 = NULL; - udp->rtcp_cb = NULL; - udp->user_data = NULL; + /* Clear up application infos from transport */ + udp->rtp_cb = NULL; + udp->rtp_cb2 = NULL; + udp->rtcp_cb = NULL; + udp->user_data = NULL; - /* Cancel any outstanding operations */ - pj_ioqueue_clear_key(udp->rtp_key); - pj_ioqueue_clear_key(udp->rtcp_key); + /* Cancel any outstanding operations */ + pj_ioqueue_clear_key(udp->rtp_key); + pj_ioqueue_clear_key(udp->rtcp_key); - /* Set key status to 'stopped' as keys have been cleared */ - udp->started = PJ_FALSE; + /* Set key status to 'stopped' as keys have been cleared */ + udp->started = PJ_FALSE; - /* Unlock keys */ - pj_ioqueue_unlock_key(udp->rtcp_key); - pj_ioqueue_unlock_key(udp->rtp_key); + /* Unlock keys */ + pj_ioqueue_unlock_key(udp->rtcp_key); + pj_ioqueue_unlock_key(udp->rtp_key); - PJ_LOG(4,(udp->base.name, "UDP media transport detached")); + PJ_LOG(4,(udp->base.name, "UDP media transport detached")); } } /* Called by application to send RTP packet */ static pj_status_t transport_send_rtp( pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { struct transport_udp *udp = (struct transport_udp*)tp; pj_ssize_t sent; @@ -1040,26 +1039,26 @@ static pj_status_t transport_send_rtp( pjmedia_transport *tp, PJ_ASSERT_RETURN(size <= PJMEDIA_MAX_MTU, PJ_ETOOBIG); if (!udp->started) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Simulate packet lost on TX direction */ if (udp->tx_drop_pct) { - if ((pj_rand() % 100) <= (int)udp->tx_drop_pct) { - PJ_LOG(5,(udp->base.name, - "TX RTP packet dropped because of pkt lost " - "simulation")); - return PJ_SUCCESS; - } + if ((pj_rand() % 100) <= (int)udp->tx_drop_pct) { + PJ_LOG(5,(udp->base.name, + "TX RTP packet dropped because of pkt lost " + "simulation")); + return PJ_SUCCESS; + } } id = udp->rtp_write_op_id; pw = &udp->rtp_pending_write[id]; if (pw->is_pending) { - /* There is still currently pending operation for this buffer. */ - PJ_LOG(4,(udp->base.name, "Too many pending write operations")); - return PJ_EBUSY; + /* There is still currently pending operation for this buffer. */ + PJ_LOG(4,(udp->base.name, "Too many pending write operations")); + return PJ_EBUSY; } pw->is_pending = PJ_TRUE; @@ -1071,29 +1070,29 @@ static pj_status_t transport_send_rtp( pjmedia_transport *tp, sent = size; status = pj_ioqueue_sendto( udp->rtp_key, - &udp->rtp_pending_write[id].op_key, - pw->buffer, &sent, 0, - &udp->rem_rtp_addr, - udp->addr_len); + &udp->rtp_pending_write[id].op_key, + pw->buffer, &sent, 0, + &udp->rem_rtp_addr, + udp->addr_len); if (status != PJ_EPENDING) { - /* Send operation has completed immediately. Clear the flag. */ - pw->is_pending = PJ_FALSE; + /* Send operation has completed immediately. Clear the flag. */ + pw->is_pending = PJ_FALSE; } udp->rtp_write_op_id = (udp->rtp_write_op_id + 1) % - PJ_ARRAY_SIZE(udp->rtp_pending_write); + PJ_ARRAY_SIZE(udp->rtp_pending_write); if (status==PJ_SUCCESS || status==PJ_EPENDING) - return PJ_SUCCESS; + return PJ_SUCCESS; return status; } /* Called by application to send RTCP packet */ static pj_status_t transport_send_rtcp(pjmedia_transport *tp, - const void *pkt, - pj_size_t size) + const void *pkt, + pj_size_t size) { return transport_send_rtcp2(tp, NULL, 0, pkt, size); } @@ -1101,10 +1100,10 @@ static pj_status_t transport_send_rtcp(pjmedia_transport *tp, /* Called by application to send RTCP packet */ static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, - const pj_sockaddr_t *addr, - unsigned addr_len, - const void *pkt, - pj_size_t size) + const pj_sockaddr_t *addr, + unsigned addr_len, + const void *pkt, + pj_size_t size) { struct transport_udp *udp = (struct transport_udp*)tp; pj_ssize_t sent; @@ -1113,31 +1112,31 @@ static pj_status_t transport_send_rtcp2(pjmedia_transport *tp, //PJ_ASSERT_RETURN(udp->attached, PJ_EINVALIDOP); if (!udp->started) { - return PJ_SUCCESS; + return PJ_SUCCESS; } if (addr == NULL) { - addr = &udp->rem_rtcp_addr; - addr_len = udp->addr_len; + addr = &udp->rem_rtcp_addr; + addr_len = udp->addr_len; } sent = size; status = pj_ioqueue_sendto( (udp->use_rtcp_mux? udp->rtp_key: - udp->rtcp_key), &udp->rtcp_write_op, - pkt, &sent, 0, addr, addr_len); + udp->rtcp_key), &udp->rtcp_write_op, + pkt, &sent, 0, addr, addr_len); if (status==PJ_SUCCESS || status==PJ_EPENDING) - return PJ_SUCCESS; + return PJ_SUCCESS; return status; } static pj_status_t transport_media_create(pjmedia_transport *tp, - pj_pool_t *pool, - unsigned options, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *pool, + unsigned options, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { struct transport_udp *udp = (struct transport_udp*)tp; @@ -1154,34 +1153,34 @@ static pj_status_t transport_media_create(pjmedia_transport *tp, } static pj_status_t transport_encode_sdp(pjmedia_transport *tp, - pj_pool_t *pool, - pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *rem_sdp, - unsigned media_index) + pj_pool_t *pool, + pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *rem_sdp, + unsigned media_index) { struct transport_udp *udp = (struct transport_udp*)tp; /* Validate media transport */ /* By now, this transport only support RTP/AVP transport */ if ((udp->media_options & PJMEDIA_TPMED_NO_TRANSPORT_CHECKING) == 0) { - pjmedia_sdp_media *m_rem, *m_loc; - pj_uint32_t tp_proto_loc, tp_proto_rem; - - m_rem = rem_sdp? rem_sdp->media[media_index] : NULL; - m_loc = sdp_local->media[media_index]; - - tp_proto_loc = pjmedia_sdp_transport_get_proto(&m_loc->desc.transport); - tp_proto_rem = m_rem? - pjmedia_sdp_transport_get_proto(&m_rem->desc.transport) : 0; - PJMEDIA_TP_PROTO_TRIM_FLAG(tp_proto_loc, PJMEDIA_TP_PROFILE_RTCP_FB); - PJMEDIA_TP_PROTO_TRIM_FLAG(tp_proto_rem, PJMEDIA_TP_PROFILE_RTCP_FB); - - if ((tp_proto_loc != PJMEDIA_TP_PROTO_RTP_AVP) || - (m_rem && tp_proto_rem != PJMEDIA_TP_PROTO_RTP_AVP)) - { - pjmedia_sdp_media_deactivate(pool, m_loc); - return PJMEDIA_SDP_EINPROTO; - } + pjmedia_sdp_media *m_rem, *m_loc; + pj_uint32_t tp_proto_loc, tp_proto_rem; + + m_rem = rem_sdp? rem_sdp->media[media_index] : NULL; + m_loc = sdp_local->media[media_index]; + + tp_proto_loc = pjmedia_sdp_transport_get_proto(&m_loc->desc.transport); + tp_proto_rem = m_rem? + pjmedia_sdp_transport_get_proto(&m_rem->desc.transport) : 0; + PJMEDIA_TP_PROTO_TRIM_FLAG(tp_proto_loc, PJMEDIA_TP_PROFILE_RTCP_FB); + PJMEDIA_TP_PROTO_TRIM_FLAG(tp_proto_rem, PJMEDIA_TP_PROFILE_RTCP_FB); + + if ((tp_proto_loc != PJMEDIA_TP_PROTO_RTP_AVP) || + (m_rem && tp_proto_rem != PJMEDIA_TP_PROTO_RTP_AVP)) + { + pjmedia_sdp_media_deactivate(pool, m_loc); + return PJMEDIA_SDP_EINPROTO; + } } if (udp->enable_rtcp_mux) { @@ -1189,17 +1188,17 @@ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, pjmedia_sdp_attr *attr; pj_bool_t add_rtcp_mux = PJ_TRUE; - udp->use_rtcp_mux = PJ_FALSE; + udp->use_rtcp_mux = PJ_FALSE; - /* Check if remote wants RTCP mux */ - if (rem_sdp) { - pjmedia_sdp_media *rem_m = rem_sdp->media[media_index]; - - attr = pjmedia_sdp_attr_find(rem_m->attr_count, rem_m->attr, - &STR_RTCP_MUX, NULL); - udp->use_rtcp_mux = (attr? PJ_TRUE: PJ_FALSE); - add_rtcp_mux = udp->use_rtcp_mux; - } + /* Check if remote wants RTCP mux */ + if (rem_sdp) { + pjmedia_sdp_media *rem_m = rem_sdp->media[media_index]; + + attr = pjmedia_sdp_attr_find(rem_m->attr_count, rem_m->attr, + &STR_RTCP_MUX, NULL); + udp->use_rtcp_mux = (attr? PJ_TRUE: PJ_FALSE); + add_rtcp_mux = udp->use_rtcp_mux; + } /* Remove RTCP attribute because for subsequent offers/answers, * the address (obtained from transport_get_info() ) may be @@ -1208,23 +1207,23 @@ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, * if remote rejects it. */ pjmedia_sdp_attr_remove_all(&m->attr_count, m->attr, "rtcp"); - - if (!udp->use_rtcp_mux) { - /* Add RTCP attribute if the remote doesn't offer or - * rejects it. - */ - attr = pjmedia_sdp_attr_create_rtcp(pool, - &udp->rtcp_addr_name); - if (attr) - pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); - } - - /* Add a=rtcp-mux attribute. */ - if (add_rtcp_mux) { - attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); - attr->name = STR_RTCP_MUX; - m->attr[m->attr_count++] = attr; - } + + if (!udp->use_rtcp_mux) { + /* Add RTCP attribute if the remote doesn't offer or + * rejects it. + */ + attr = pjmedia_sdp_attr_create_rtcp(pool, + &udp->rtcp_addr_name); + if (attr) + pjmedia_sdp_attr_add(&m->attr_count, m->attr, attr); + } + + /* Add a=rtcp-mux attribute. */ + if (add_rtcp_mux) { + attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); + attr->name = STR_RTCP_MUX; + m->attr[m->attr_count++] = attr; + } } return PJ_SUCCESS; @@ -1232,10 +1231,10 @@ static pj_status_t transport_encode_sdp(pjmedia_transport *tp, static pj_status_t transport_media_start(pjmedia_transport *tp, - pj_pool_t *pool, - const pjmedia_sdp_session *sdp_local, - const pjmedia_sdp_session *sdp_remote, - unsigned media_index) + pj_pool_t *pool, + const pjmedia_sdp_session *sdp_local, + const pjmedia_sdp_session *sdp_remote, + unsigned media_index) { struct transport_udp *udp = (struct transport_udp*)tp; pj_ssize_t size; @@ -1251,14 +1250,14 @@ static pj_status_t transport_media_start(pjmedia_transport *tp, /* Just return success if there is already pending read */ if (udp->started) { - PJ_LOG(5,(udp->base.name, "UDP media transport already started")); - return PJ_SUCCESS; + PJ_LOG(5,(udp->base.name, "UDP media transport already started")); + return PJ_SUCCESS; } pj_ioqueue_op_key_init(&udp->rtp_read_op, sizeof(udp->rtp_read_op)); for (i=0; irtp_pending_write); ++i) { - pj_ioqueue_op_key_init(&udp->rtp_pending_write[i].op_key, - sizeof(udp->rtp_pending_write[i].op_key)); + pj_ioqueue_op_key_init(&udp->rtp_pending_write[i].op_key, + sizeof(udp->rtp_pending_write[i].op_key)); } pj_ioqueue_op_key_init(&udp->rtcp_read_op, sizeof(udp->rtcp_read_op)); @@ -1270,12 +1269,12 @@ static pj_status_t transport_media_start(pjmedia_transport *tp, udp->rtp_addrlen = sizeof(udp->rtp_src_addr); size = sizeof(udp->rtp_pkt); status = pj_ioqueue_recvfrom(udp->rtp_key, &udp->rtp_read_op, - udp->rtp_pkt, &size, PJ_IOQUEUE_ALWAYS_ASYNC, - &udp->rtp_src_addr, &udp->rtp_addrlen); + udp->rtp_pkt, &size, PJ_IOQUEUE_ALWAYS_ASYNC, + &udp->rtp_src_addr, &udp->rtp_addrlen); if (status != PJ_EPENDING) { - PJ_PERROR(3, (udp->base.name, status, - "media_start(): recvfrom RTP failed")); - return status; + PJ_PERROR(3, (udp->base.name, status, + "media_start(): recvfrom RTP failed")); + return status; } TRACE_((udp->base.name, "media_start(): before recvfrom RTCP")); @@ -1284,14 +1283,14 @@ static pj_status_t transport_media_start(pjmedia_transport *tp, udp->rtcp_addr_len = sizeof(udp->rtcp_src_addr); size = sizeof(udp->rtcp_pkt); status = pj_ioqueue_recvfrom(udp->rtcp_key, &udp->rtcp_read_op, - udp->rtcp_pkt, &size, - PJ_IOQUEUE_ALWAYS_ASYNC, - &udp->rtcp_src_addr, &udp->rtcp_addr_len); + udp->rtcp_pkt, &size, + PJ_IOQUEUE_ALWAYS_ASYNC, + &udp->rtcp_src_addr, &udp->rtcp_addr_len); if (status != PJ_EPENDING) { - PJ_PERROR(3, (udp->base.name, status, - "media_start(): recvfrom RTCP failed")); - pj_ioqueue_clear_key(udp->rtp_key); - return status; + PJ_PERROR(3, (udp->base.name, status, + "media_start(): recvfrom RTCP failed")); + pj_ioqueue_clear_key(udp->rtp_key); + return status; } udp->started = PJ_TRUE; @@ -1309,8 +1308,8 @@ static pj_status_t transport_media_stop(pjmedia_transport *tp) /* Just return success if there is no pending read */ if (!udp->started) { - PJ_LOG(5, (udp->base.name, "UDP media transport already stopped")); - return PJ_SUCCESS; + PJ_LOG(5, (udp->base.name, "UDP media transport already stopped")); + return PJ_SUCCESS; } pj_ioqueue_clear_key(udp->rtp_key); @@ -1324,24 +1323,24 @@ static pj_status_t transport_media_stop(pjmedia_transport *tp) } static pj_status_t transport_simulate_lost(pjmedia_transport *tp, - pjmedia_dir dir, - unsigned pct_lost) + pjmedia_dir dir, + unsigned pct_lost) { struct transport_udp *udp = (struct transport_udp*)tp; PJ_ASSERT_RETURN(tp && pct_lost <= 100, PJ_EINVAL); if (dir & PJMEDIA_DIR_ENCODING) - udp->tx_drop_pct = pct_lost; + udp->tx_drop_pct = pct_lost; if (dir & PJMEDIA_DIR_DECODING) - udp->rx_drop_pct = pct_lost; + udp->rx_drop_pct = pct_lost; return PJ_SUCCESS; } static pj_status_t transport_restart(pj_bool_t is_rtp, - struct transport_udp *udp) + struct transport_udp *udp) { PJ_UNUSED_ARG(udp); PJ_UNUSED_ARG(is_rtp); @@ -1370,22 +1369,22 @@ static pj_status_t transport_restart(pj_bool_t is_rtp, pj_ssize_t size; PJ_LOG(4, (udp->base.name, "Restarting %s transport", - (is_rtp)?"RTP":"RTCP")); + (is_rtp)?"RTP":"RTCP")); udp->started = PJ_FALSE; /* Destroy existing socket, if any. */ if (key) { - /* This will block the execution if callback is still - * being called. - */ - pj_ioqueue_unregister(key); - if (is_rtp) { - udp->rtp_key = NULL; - } else { - udp->rtcp_key = NULL; - } + /* This will block the execution if callback is still + * being called. + */ + pj_ioqueue_unregister(key); + if (is_rtp) { + udp->rtp_key = NULL; + } else { + udp->rtcp_key = NULL; + } } else if (*sock != PJ_INVALID_SOCKET) { - pj_sock_close(*sock); + pj_sock_close(*sock); } *sock = PJ_INVALID_SOCKET; @@ -1394,76 +1393,76 @@ static pj_status_t transport_restart(pj_bool_t is_rtp, status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, sock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; addr = (is_rtp) ? &udp->rtp_addr_name : &udp->rtcp_addr_name; status = pj_sock_bind(*sock, addr, pj_sockaddr_get_len(addr)); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Set buffer size for RTP socket */ #if PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE if (is_rtp) { - unsigned sobuf_size = PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE; + unsigned sobuf_size = PJMEDIA_TRANSPORT_SO_RCVBUF_SIZE; - pj_sock_setsockopt_sobuf(udp->rtp_sock, pj_SO_RCVBUF(), - PJ_TRUE, &sobuf_size); + pj_sock_setsockopt_sobuf(udp->rtp_sock, pj_SO_RCVBUF(), + PJ_TRUE, &sobuf_size); } #endif #if PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE if (is_rtp) { - unsigned sobuf_size = PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE; + unsigned sobuf_size = PJMEDIA_TRANSPORT_SO_SNDBUF_SIZE; - pj_sock_setsockopt_sobuf(udp->rtp_sock, pj_SO_SNDBUF(), - PJ_TRUE, &sobuf_size); + pj_sock_setsockopt_sobuf(udp->rtp_sock, pj_SO_SNDBUF(), + PJ_TRUE, &sobuf_size); } #endif pj_bzero(&cb, sizeof(cb)); if (is_rtp) { - cb.on_read_complete = &on_rx_rtp; - cb.on_write_complete = &on_rtp_data_sent; + cb.on_read_complete = &on_rx_rtp; + cb.on_write_complete = &on_rtp_data_sent; } else { - cb.on_read_complete = &on_rx_rtcp; + cb.on_read_complete = &on_rx_rtcp; } if (is_rtp) { - status = pj_ioqueue_register_sock(udp->pool, udp->ioqueue, *sock, udp, - &cb, &udp->rtp_key); + status = pj_ioqueue_register_sock(udp->pool, udp->ioqueue, *sock, udp, + &cb, &udp->rtp_key); } else { - status = pj_ioqueue_register_sock(udp->pool, udp->ioqueue, *sock, udp, - &cb, &udp->rtcp_key); + status = pj_ioqueue_register_sock(udp->pool, udp->ioqueue, *sock, udp, + &cb, &udp->rtcp_key); } if (status != PJ_SUCCESS) - goto on_error; + goto on_error; if (is_rtp) { - size = sizeof(udp->rtp_pkt); - status = pj_ioqueue_recvfrom(udp->rtp_key, &udp->rtp_read_op, - udp->rtp_pkt, &size, - PJ_IOQUEUE_ALWAYS_ASYNC, - &udp->rtp_src_addr, &udp->rtp_addrlen); + size = sizeof(udp->rtp_pkt); + status = pj_ioqueue_recvfrom(udp->rtp_key, &udp->rtp_read_op, + udp->rtp_pkt, &size, + PJ_IOQUEUE_ALWAYS_ASYNC, + &udp->rtp_src_addr, &udp->rtp_addrlen); } else { - size = sizeof(udp->rtcp_pkt); - status = pj_ioqueue_recvfrom(udp->rtcp_key, &udp->rtcp_read_op, - udp->rtcp_pkt, &size, - PJ_IOQUEUE_ALWAYS_ASYNC, - &udp->rtcp_src_addr, &udp->rtcp_addr_len); + size = sizeof(udp->rtcp_pkt); + status = pj_ioqueue_recvfrom(udp->rtcp_key, &udp->rtcp_read_op, + udp->rtcp_pkt, &size, + PJ_IOQUEUE_ALWAYS_ASYNC, + &udp->rtcp_src_addr, &udp->rtcp_addr_len); } if (status != PJ_EPENDING) - goto on_error; + goto on_error; udp->started = PJ_TRUE; PJ_LOG(4, (udp->base.name, "Success restarting %s transport", - (is_rtp)?"RTP":"RTCP")); + (is_rtp)?"RTP":"RTCP")); return PJ_SUCCESS; on_error: if (*sock != PJ_INVALID_SOCKET) { - pj_sock_close(*sock); - *sock = PJ_INVALID_SOCKET; + pj_sock_close(*sock); + *sock = PJ_INVALID_SOCKET; } PJ_PERROR(1, (udp->base.name, status, - "Error restarting %s transport", (is_rtp)?"RTP":"RTCP")); + "Error restarting %s transport", (is_rtp)?"RTP":"RTCP")); return status; #endif diff --git a/pjmedia/src/pjmedia/types.c b/pjmedia/src/pjmedia/types.c index 1b9c7fb594..cc94da6e5c 100644 --- a/pjmedia/src/pjmedia/types.c +++ b/pjmedia/src/pjmedia/types.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,11 +29,11 @@ typedef struct pjmedia_type_map { /* Internal mapping for pjmedia type names */ static pjmedia_type_map media_type_names[] = { - {PJMEDIA_TYPE_NONE, "none"}, - {PJMEDIA_TYPE_AUDIO, "audio"}, - {PJMEDIA_TYPE_VIDEO, "video"}, - {PJMEDIA_TYPE_APPLICATION, "application"}, - {PJMEDIA_TYPE_UNKNOWN, "unknown"} + {PJMEDIA_TYPE_NONE, "none"}, + {PJMEDIA_TYPE_AUDIO, "audio"}, + {PJMEDIA_TYPE_VIDEO, "video"}, + {PJMEDIA_TYPE_APPLICATION, "application"}, + {PJMEDIA_TYPE_UNKNOWN, "unknown"} }; /* @@ -46,9 +45,9 @@ PJ_DEF(const char*) pjmedia_type_name(pjmedia_type t) pj_assert(PJMEDIA_TYPE_UNKNOWN == 4); if (t < (int)PJ_ARRAY_SIZE(media_type_names)) - return media_type_names[t].name; + return media_type_names[t].name; else - return "??"; + return "??"; } /* @@ -58,8 +57,8 @@ PJ_DEF(pjmedia_type) pjmedia_get_type(const pj_str_t *name) { int i; for (i = 0; i < PJ_ARRAY_SIZE(media_type_names); ++i) { - if (pj_stricmp2(name, media_type_names[i].name)==0) - return media_type_names[i].type; + if (pj_stricmp2(name, media_type_names[i].name)==0) + return media_type_names[i].type; } return PJMEDIA_TYPE_UNKNOWN; } diff --git a/pjmedia/src/pjmedia/vid_codec.c b/pjmedia/src/pjmedia/vid_codec.c index 2f5d6551a8..d37707815e 100644 --- a/pjmedia/src/pjmedia/vid_codec.c +++ b/pjmedia/src/pjmedia/vid_codec.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,8 +35,8 @@ static pjmedia_vid_codec_mgr *def_vid_codec_mgr; /* Definition of default codecs parameters */ typedef struct pjmedia_vid_codec_default_param { - pj_pool_t *pool; - pjmedia_vid_codec_param *param; + pj_pool_t *pool; + pjmedia_vid_codec_param *param; } pjmedia_vid_codec_default_param; @@ -47,12 +46,12 @@ typedef struct pjmedia_vid_codec_default_param */ typedef struct pjmedia_vid_codec_desc { - pjmedia_vid_codec_info info; /**< Codec info. */ - pjmedia_codec_id id; /**< Fully qualified name */ - pjmedia_codec_priority prio; /**< Priority. */ - pjmedia_vid_codec_factory *factory; /**< The factory. */ + pjmedia_vid_codec_info info; /**< Codec info. */ + pjmedia_codec_id id; /**< Fully qualified name */ + pjmedia_codec_priority prio; /**< Priority. */ + pjmedia_vid_codec_factory *factory; /**< The factory. */ pjmedia_vid_codec_default_param *def_param; /**< Default codecs - parameters. */ + parameters. */ } pjmedia_vid_codec_desc; @@ -60,19 +59,19 @@ typedef struct pjmedia_vid_codec_desc struct pjmedia_vid_codec_mgr { /** Pool factory instance. */ - pj_pool_factory *pf; + pj_pool_factory *pf; /** Codec manager mutex. */ - pj_mutex_t *mutex; + pj_mutex_t *mutex; /** List of codec factories registered to codec manager. */ - pjmedia_vid_codec_factory factory_list; + pjmedia_vid_codec_factory factory_list; /** Number of supported codecs. */ - unsigned codec_cnt; + unsigned codec_cnt; /** Array of codec descriptor. */ - pjmedia_vid_codec_desc codec_desc[PJMEDIA_CODEC_MGR_MAX_CODECS]; + pjmedia_vid_codec_desc codec_desc[PJMEDIA_CODEC_MGR_MAX_CODECS]; }; @@ -86,8 +85,8 @@ static void sort_codecs(pjmedia_vid_codec_mgr *mgr); * Duplicate video codec parameter. */ PJ_DEF(pjmedia_vid_codec_param*) pjmedia_vid_codec_param_clone( - pj_pool_t *pool, - const pjmedia_vid_codec_param *src) + pj_pool_t *pool, + const pjmedia_vid_codec_param *src) { pjmedia_vid_codec_param *p; unsigned i; @@ -99,16 +98,16 @@ PJ_DEF(pjmedia_vid_codec_param*) pjmedia_vid_codec_param_clone( /* Update codec param */ pj_memcpy(p, src, sizeof(pjmedia_vid_codec_param)); for (i = 0; i < src->dec_fmtp.cnt; ++i) { - pj_strdup(pool, &p->dec_fmtp.param[i].name, - &src->dec_fmtp.param[i].name); - pj_strdup(pool, &p->dec_fmtp.param[i].val, - &src->dec_fmtp.param[i].val); + pj_strdup(pool, &p->dec_fmtp.param[i].name, + &src->dec_fmtp.param[i].name); + pj_strdup(pool, &p->dec_fmtp.param[i].val, + &src->dec_fmtp.param[i].val); } for (i = 0; i < src->enc_fmtp.cnt; ++i) { - pj_strdup(pool, &p->enc_fmtp.param[i].name, - &src->enc_fmtp.param[i].name); - pj_strdup(pool, &p->enc_fmtp.param[i].val, - &src->enc_fmtp.param[i].val); + pj_strdup(pool, &p->enc_fmtp.param[i].name, + &src->enc_fmtp.param[i].name); + pj_strdup(pool, &p->enc_fmtp.param[i].val, + &src->enc_fmtp.param[i].val); } return p; @@ -134,7 +133,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_create( /* Create mutex */ status = pj_mutex_create_recursive(pool, "vid-codec-mgr", &mgr->mutex); if (status != PJ_SUCCESS) - return status; + return status; if (!def_vid_codec_mgr) def_vid_codec_mgr = mgr; @@ -155,7 +154,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_destroy (pjmedia_vid_codec_mgr *mgr) /* Destroy mutex */ if (mgr->mutex) - pj_mutex_destroy(mgr->mutex); + pj_mutex_destroy(mgr->mutex); /* Just for safety, set codec manager states to zero */ pj_bzero(mgr, sizeof(pjmedia_vid_codec_mgr)); @@ -184,7 +183,7 @@ PJ_DEF(void) pjmedia_vid_codec_mgr_set_instance(pjmedia_vid_codec_mgr* mgr) */ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_register_factory( pjmedia_vid_codec_mgr *mgr, - pjmedia_vid_codec_factory *factory) + pjmedia_vid_codec_factory *factory) { pjmedia_vid_codec_info info[PJMEDIA_CODEC_MGR_MAX_CODECS]; unsigned i, count; @@ -199,26 +198,26 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_register_factory( count = PJ_ARRAY_SIZE(info); status = factory->op->enum_info(factory, &count, info); if (status != PJ_SUCCESS) - return status; + return status; pj_mutex_lock(mgr->mutex); /* Check codec count */ if (count + mgr->codec_cnt > PJ_ARRAY_SIZE(mgr->codec_desc)) { - pj_mutex_unlock(mgr->mutex); - return PJ_ETOOMANY; + pj_mutex_unlock(mgr->mutex); + return PJ_ETOOMANY; } /* Save the codecs */ for (i=0; icodec_desc[mgr->codec_cnt+i], - &info[i], sizeof(pjmedia_vid_codec_info)); - mgr->codec_desc[mgr->codec_cnt+i].prio = PJMEDIA_CODEC_PRIO_NORMAL; - mgr->codec_desc[mgr->codec_cnt+i].factory = factory; - pjmedia_vid_codec_info_to_id( &info[i], - mgr->codec_desc[mgr->codec_cnt+i].id, - sizeof(pjmedia_codec_id)); + pj_memcpy( &mgr->codec_desc[mgr->codec_cnt+i], + &info[i], sizeof(pjmedia_vid_codec_info)); + mgr->codec_desc[mgr->codec_cnt+i].prio = PJMEDIA_CODEC_PRIO_NORMAL; + mgr->codec_desc[mgr->codec_cnt+i].factory = factory; + pjmedia_vid_codec_info_to_id( &info[i], + mgr->codec_desc[mgr->codec_cnt+i].id, + sizeof(pjmedia_codec_id)); } /* Update count */ @@ -240,8 +239,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_register_factory( * Unregister a codec factory. */ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_unregister_factory( - pjmedia_vid_codec_mgr *mgr, - pjmedia_vid_codec_factory *factory) + pjmedia_vid_codec_mgr *mgr, + pjmedia_vid_codec_factory *factory) { unsigned i; PJ_ASSERT_RETURN(factory, PJ_EINVAL); @@ -253,8 +252,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_unregister_factory( /* Factory must be registered. */ if (pj_list_find_node(&mgr->factory_list, factory) != factory) { - pj_mutex_unlock(mgr->mutex); - return PJ_ENOTFOUND; + pj_mutex_unlock(mgr->mutex); + return PJ_ENOTFOUND; } /* Erase factory from the factory list */ @@ -266,15 +265,15 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_unregister_factory( */ for (i=0; icodec_cnt; ) { - if (mgr->codec_desc[i].factory == factory) { - /* Remove the codec from array of codec descriptions */ - pj_array_erase(mgr->codec_desc, sizeof(mgr->codec_desc[0]), - mgr->codec_cnt, i); - --mgr->codec_cnt; + if (mgr->codec_desc[i].factory == factory) { + /* Remove the codec from array of codec descriptions */ + pj_array_erase(mgr->codec_desc, sizeof(mgr->codec_desc[0]), + mgr->codec_cnt, i); + --mgr->codec_cnt; - } else { - ++i; - } + } else { + ++i; + } } pj_mutex_unlock(mgr->mutex); @@ -288,9 +287,9 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_unregister_factory( */ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_enum_codecs( pjmedia_vid_codec_mgr *mgr, - unsigned *count, - pjmedia_vid_codec_info codecs[], - unsigned *prio) + unsigned *count, + pjmedia_vid_codec_info codecs[], + unsigned *prio) { unsigned i; @@ -302,17 +301,17 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_enum_codecs( pj_mutex_lock(mgr->mutex); if (*count > mgr->codec_cnt) - *count = mgr->codec_cnt; + *count = mgr->codec_cnt; for (i=0; i<*count; ++i) { - pj_memcpy(&codecs[i], - &mgr->codec_desc[i].info, - sizeof(pjmedia_vid_codec_info)); + pj_memcpy(&codecs[i], + &mgr->codec_desc[i].info, + sizeof(pjmedia_vid_codec_info)); } if (prio) { - for (i=0; i < *count; ++i) - prio[i] = mgr->codec_desc[i].prio; + for (i=0; i < *count; ++i) + prio[i] = mgr->codec_desc[i].prio; } pj_mutex_unlock(mgr->mutex); @@ -326,8 +325,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_enum_codecs( */ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_get_codec_info( pjmedia_vid_codec_mgr *mgr, - unsigned pt, - const pjmedia_vid_codec_info **p_info) + unsigned pt, + const pjmedia_vid_codec_info **p_info) { unsigned i; @@ -339,12 +338,12 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_get_codec_info( pj_mutex_lock(mgr->mutex); for (i=0; icodec_cnt; ++i) { - if (mgr->codec_desc[i].info.pt == pt) { - *p_info = &mgr->codec_desc[i].info; + if (mgr->codec_desc[i].info.pt == pt) { + *p_info = &mgr->codec_desc[i].info; - pj_mutex_unlock(mgr->mutex); - return PJ_SUCCESS; - } + pj_mutex_unlock(mgr->mutex); + return PJ_SUCCESS; + } } pj_mutex_unlock(mgr->mutex); @@ -354,9 +353,9 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_get_codec_info( PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_get_codec_info2( - pjmedia_vid_codec_mgr *mgr, - pjmedia_format_id fmt_id, - const pjmedia_vid_codec_info **p_info) + pjmedia_vid_codec_mgr *mgr, + pjmedia_format_id fmt_id, + const pjmedia_vid_codec_info **p_info) { unsigned i; @@ -368,12 +367,12 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_get_codec_info2( pj_mutex_lock(mgr->mutex); for (i=0; icodec_cnt; ++i) { - if (mgr->codec_desc[i].info.fmt_id == fmt_id) { - *p_info = &mgr->codec_desc[i].info; + if (mgr->codec_desc[i].info.fmt_id == fmt_id) { + *p_info = &mgr->codec_desc[i].info; - pj_mutex_unlock(mgr->mutex); - return PJ_SUCCESS; - } + pj_mutex_unlock(mgr->mutex); + return PJ_SUCCESS; + } } pj_mutex_unlock(mgr->mutex); @@ -388,20 +387,20 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_get_codec_info2( */ PJ_DEF(char*) pjmedia_vid_codec_info_to_id( const pjmedia_vid_codec_info *info, - char *id, unsigned max_len ) + char *id, unsigned max_len ) { int len; PJ_ASSERT_RETURN(info && id && max_len, NULL); len = pj_ansi_snprintf(id, max_len, "%.*s/%u", - (int)info->encoding_name.slen, - info->encoding_name.ptr, - info->pt); + (int)info->encoding_name.slen, + info->encoding_name.ptr, + info->pt); if (len < 1 || len >= (int)max_len) { - id[0] = '\0'; - return NULL; + id[0] = '\0'; + return NULL; } return id; @@ -413,10 +412,10 @@ PJ_DEF(char*) pjmedia_vid_codec_info_to_id( */ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_find_codecs_by_id( pjmedia_vid_codec_mgr *mgr, - const pj_str_t *codec_id, - unsigned *count, - const pjmedia_vid_codec_info *p_info[], - unsigned prio[]) + const pj_str_t *codec_id, + unsigned *count, + const pjmedia_vid_codec_info *p_info[], + unsigned prio[]) { unsigned i, found = 0; @@ -429,21 +428,21 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_find_codecs_by_id( for (i=0; icodec_cnt; ++i) { - if (codec_id->slen == 0 || - pj_strnicmp2(codec_id, mgr->codec_desc[i].id, - codec_id->slen) == 0) - { + if (codec_id->slen == 0 || + pj_strnicmp2(codec_id, mgr->codec_desc[i].id, + codec_id->slen) == 0) + { - if (p_info) - p_info[found] = &mgr->codec_desc[i].info; - if (prio) - prio[found] = mgr->codec_desc[i].prio; + if (p_info) + p_info[found] = &mgr->codec_desc[i].info; + if (prio) + prio[found] = mgr->codec_desc[i].prio; - ++found; + ++found; - if (found >= *count) - break; - } + if (found >= *count) + break; + } } @@ -463,7 +462,7 @@ static void swap_codec(pjmedia_vid_codec_mgr *mgr, unsigned i, unsigned j) pj_memcpy(&tmp, &mgr->codec_desc[i], sizeof(pjmedia_vid_codec_desc)); pj_memcpy(&mgr->codec_desc[i], &mgr->codec_desc[j], - sizeof(pjmedia_vid_codec_desc)); + sizeof(pjmedia_vid_codec_desc)); pj_memcpy(&mgr->codec_desc[j], &tmp, sizeof(pjmedia_vid_codec_desc)); } @@ -476,23 +475,23 @@ static void sort_codecs(pjmedia_vid_codec_mgr *mgr) /* Re-sort */ for (i=0; icodec_cnt; ++i) { - unsigned j, max; + unsigned j, max; - for (max=i, j=i+1; jcodec_cnt; ++j) { - if (mgr->codec_desc[j].prio > mgr->codec_desc[max].prio) - max = j; - } + for (max=i, j=i+1; jcodec_cnt; ++j) { + if (mgr->codec_desc[j].prio > mgr->codec_desc[max].prio) + max = j; + } - if (max != i) - swap_codec(mgr, i, max); + if (max != i) + swap_codec(mgr, i, max); } /* Change PJMEDIA_CODEC_PRIO_HIGHEST codecs to NEXT_HIGHER */ for (i=0; icodec_cnt; ++i) { - if (mgr->codec_desc[i].prio == PJMEDIA_CODEC_PRIO_HIGHEST) - mgr->codec_desc[i].prio = PJMEDIA_CODEC_PRIO_NEXT_HIGHER; - else - break; + if (mgr->codec_desc[i].prio == PJMEDIA_CODEC_PRIO_HIGHEST) + mgr->codec_desc[i].prio = PJMEDIA_CODEC_PRIO_NEXT_HIGHER; + else + break; } } @@ -504,9 +503,9 @@ static void sort_codecs(pjmedia_vid_codec_mgr *mgr) * priorities of all those codecs. */ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_set_codec_priority( - pjmedia_vid_codec_mgr *mgr, - const pj_str_t *codec_id, - pj_uint8_t prio) + pjmedia_vid_codec_mgr *mgr, + const pj_str_t *codec_id, + pj_uint8_t prio) { unsigned i, found = 0; @@ -520,18 +519,18 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_set_codec_priority( /* Update the priorities of affected codecs */ for (i=0; icodec_cnt; ++i) { - if (codec_id->slen == 0 || - pj_strnicmp2(codec_id, mgr->codec_desc[i].id, - codec_id->slen) == 0) - { - mgr->codec_desc[i].prio = (pjmedia_codec_priority) prio; - ++found; - } + if (codec_id->slen == 0 || + pj_strnicmp2(codec_id, mgr->codec_desc[i].id, + codec_id->slen) == 0) + { + mgr->codec_desc[i].prio = (pjmedia_codec_priority) prio; + ++found; + } } if (!found) { - pj_mutex_unlock(mgr->mutex); - return PJ_ENOTFOUND; + pj_mutex_unlock(mgr->mutex); + return PJ_ENOTFOUND; } /* Re-sort codecs */ @@ -548,8 +547,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_set_codec_priority( */ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_alloc_codec( pjmedia_vid_codec_mgr *mgr, - const pjmedia_vid_codec_info *info, - pjmedia_vid_codec **p_codec) + const pjmedia_vid_codec_info *info, + pjmedia_vid_codec **p_codec) { pjmedia_vid_codec_factory *factory; pj_status_t status; @@ -566,17 +565,17 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_alloc_codec( factory = mgr->factory_list.next; while (factory != &mgr->factory_list) { - if ( (*factory->op->test_alloc)(factory, info) == PJ_SUCCESS ) { + if ( (*factory->op->test_alloc)(factory, info) == PJ_SUCCESS ) { - status = (*factory->op->alloc_codec)(factory, info, p_codec); - if (status == PJ_SUCCESS) { - pj_mutex_unlock(mgr->mutex); - return PJ_SUCCESS; - } + status = (*factory->op->alloc_codec)(factory, info, p_codec); + if (status == PJ_SUCCESS) { + pj_mutex_unlock(mgr->mutex); + return PJ_SUCCESS; + } - } + } - factory = factory->next; + factory = factory->next; } pj_mutex_unlock(mgr->mutex); @@ -590,8 +589,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_alloc_codec( */ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_get_default_param( pjmedia_vid_codec_mgr *mgr, - const pjmedia_vid_codec_info *info, - pjmedia_vid_codec_param *param ) + const pjmedia_vid_codec_info *info, + pjmedia_vid_codec_param *param ) { pjmedia_vid_codec_factory *factory; pj_status_t status; @@ -606,46 +605,46 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_get_default_param( if (!pjmedia_vid_codec_info_to_id(info, (char*)&codec_id, sizeof(codec_id))) - return PJ_EINVAL; + return PJ_EINVAL; pj_mutex_lock(mgr->mutex); /* First, lookup default param in codec desc */ for (i=0; i < mgr->codec_cnt; ++i) { - if (pj_ansi_stricmp(codec_id, mgr->codec_desc[i].id) == 0) { - codec_desc = &mgr->codec_desc[i]; - break; - } + if (pj_ansi_stricmp(codec_id, mgr->codec_desc[i].id) == 0) { + codec_desc = &mgr->codec_desc[i]; + break; + } } /* If we found the codec and its default param is set, return it */ if (codec_desc && codec_desc->def_param) { - pj_memcpy(param, codec_desc->def_param->param, - sizeof(pjmedia_vid_codec_param)); + pj_memcpy(param, codec_desc->def_param->param, + sizeof(pjmedia_vid_codec_param)); - pj_mutex_unlock(mgr->mutex); - return PJ_SUCCESS; + pj_mutex_unlock(mgr->mutex); + return PJ_SUCCESS; } /* Otherwise query the default param from codec factory */ factory = mgr->factory_list.next; while (factory != &mgr->factory_list) { - if ( (*factory->op->test_alloc)(factory, info) == PJ_SUCCESS ) { + if ( (*factory->op->test_alloc)(factory, info) == PJ_SUCCESS ) { - status = (*factory->op->default_attr)(factory, info, param); - if (status == PJ_SUCCESS) { - /* Check for invalid max_bps. */ - //if (param->info.max_bps < param->info.avg_bps) - // param->info.max_bps = param->info.avg_bps; + status = (*factory->op->default_attr)(factory, info, param); + if (status == PJ_SUCCESS) { + /* Check for invalid max_bps. */ + //if (param->info.max_bps < param->info.avg_bps) + // param->info.max_bps = param->info.avg_bps; - pj_mutex_unlock(mgr->mutex); - return PJ_SUCCESS; - } + pj_mutex_unlock(mgr->mutex); + return PJ_SUCCESS; + } - } + } - factory = factory->next; + factory = factory->next; } pj_mutex_unlock(mgr->mutex); @@ -659,9 +658,9 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_get_default_param( * Set default codec parameter. */ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_set_default_param( - pjmedia_vid_codec_mgr *mgr, - const pjmedia_vid_codec_info *info, - const pjmedia_vid_codec_param *param ) + pjmedia_vid_codec_mgr *mgr, + const pjmedia_vid_codec_info *info, + const pjmedia_vid_codec_param *param ) { unsigned i; pjmedia_codec_id codec_id; @@ -675,53 +674,53 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_set_default_param( PJ_ASSERT_RETURN(mgr, PJ_EINVAL); if (!pjmedia_vid_codec_info_to_id(info, (char*)&codec_id, sizeof(codec_id))) - return PJ_EINVAL; + return PJ_EINVAL; pj_mutex_lock(mgr->mutex); /* Lookup codec desc */ for (i=0; i < mgr->codec_cnt; ++i) { - if (pj_ansi_stricmp(codec_id, mgr->codec_desc[i].id) == 0) { - codec_desc = &mgr->codec_desc[i]; - break; - } + if (pj_ansi_stricmp(codec_id, mgr->codec_desc[i].id) == 0) { + codec_desc = &mgr->codec_desc[i]; + break; + } } /* Codec not found */ if (!codec_desc) { - pj_mutex_unlock(mgr->mutex); - return PJMEDIA_CODEC_EUNSUP; + pj_mutex_unlock(mgr->mutex); + return PJMEDIA_CODEC_EUNSUP; } /* If codec param is previously set */ if (codec_desc->def_param) { - pj_assert(codec_desc->def_param->pool); + pj_assert(codec_desc->def_param->pool); old_pool = codec_desc->def_param->pool; - codec_desc->def_param = NULL; + codec_desc->def_param = NULL; } /* When param is set to NULL, i.e: setting default codec param to library * default setting, just return PJ_SUCCESS. */ if (NULL == param) { - pj_mutex_unlock(mgr->mutex); + pj_mutex_unlock(mgr->mutex); if (old_pool) - pj_pool_release(old_pool); - return PJ_SUCCESS; + pj_pool_release(old_pool); + return PJ_SUCCESS; } /* Create new default codec param instance */ pool = pj_pool_create(mgr->pf, (char*)codec_id, 256, 256, NULL); codec_desc->def_param = PJ_POOL_ZALLOC_T(pool, - pjmedia_vid_codec_default_param); + pjmedia_vid_codec_default_param); p = codec_desc->def_param; p->pool = pool; /* Update codec default param */ p->param = pjmedia_vid_codec_param_clone(pool, param); if (!p->param) { - pj_mutex_unlock(mgr->mutex); - return PJ_EINVAL; + pj_mutex_unlock(mgr->mutex); + return PJ_EINVAL; } codec_desc->def_param = p; @@ -733,7 +732,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_set_default_param( * pjmedia_vid_codec_mgr_get_default_param() which doesn't do deep clone. */ if (old_pool) - pj_pool_release(old_pool); + pj_pool_release(old_pool); return PJ_SUCCESS; } @@ -744,7 +743,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_set_default_param( */ PJ_DEF(pj_status_t) pjmedia_vid_codec_mgr_dealloc_codec(pjmedia_vid_codec_mgr *mgr, - pjmedia_vid_codec *codec) + pjmedia_vid_codec *codec) { PJ_ASSERT_RETURN(codec, PJ_EINVAL); diff --git a/pjmedia/src/pjmedia/vid_codec_util.c b/pjmedia/src/pjmedia/vid_codec_util.c index 1a6c4f710e..947a96f977 100644 --- a/pjmedia/src/pjmedia/vid_codec_util.c +++ b/pjmedia/src/pjmedia/vid_codec_util.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,22 +35,22 @@ * SDP answer to match remote offer) is always active regardless the * value of this macro. */ -#define H264_STRICT_SDP_NEGO 0 +#define H264_STRICT_SDP_NEGO 0 /* Default frame rate, if not specified */ -#define DEFAULT_H264_FPS_NUM 10 -#define DEFAULT_H264_FPS_DENUM 1 +#define DEFAULT_H264_FPS_NUM 10 +#define DEFAULT_H264_FPS_DENUM 1 /* Default aspect ratio, if not specified */ -#define DEFAULT_H264_RATIO_NUM 4 +#define DEFAULT_H264_RATIO_NUM 4 #define DEFAULT_H264_RATIO_DENUM 3 /* ITU resolution definition */ struct mpi_resolution_t { - pj_str_t name; - pjmedia_rect_size size; + pj_str_t name; + pjmedia_rect_size size; } mpi_resolutions [] = { @@ -69,8 +68,8 @@ mpi_resolutions [] = /* Parse fmtp value for custom resolution, e.g: "CUSTOM=800,600,2" */ static pj_status_t parse_custom_res_fmtp(const pj_str_t *fmtp_val, - pjmedia_rect_size *size, - unsigned *mpi) + pjmedia_rect_size *size, + unsigned *mpi) { const char *p, *p_end; pj_str_t token; @@ -81,19 +80,19 @@ static pj_status_t parse_custom_res_fmtp(const pj_str_t *fmtp_val, p_end = p + fmtp_val->slen; while (p<=p_end && i32) - return PJ_EINVAL; + return PJ_EINVAL; size->w = val[0]; size->h = val[1]; @@ -104,8 +103,8 @@ static pj_status_t parse_custom_res_fmtp(const pj_str_t *fmtp_val, /* H263 fmtp parser */ PJ_DEF(pj_status_t) pjmedia_vid_codec_parse_h263_fmtp( - const pjmedia_codec_fmtp *fmtp, - pjmedia_vid_codec_h263_fmtp *h263_fmtp) + const pjmedia_codec_fmtp *fmtp, + pjmedia_vid_codec_h263_fmtp *h263_fmtp) { const pj_str_t CUSTOM = {"CUSTOM", 6}; unsigned i; @@ -113,48 +112,48 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_parse_h263_fmtp( pj_bzero(h263_fmtp, sizeof(*h263_fmtp)); for (i=0; icnt; ++i) { - unsigned j; - pj_bool_t parsed = PJ_FALSE; - - if (h263_fmtp->mpi_cnt >= PJ_ARRAY_SIZE(h263_fmtp->mpi)) { - pj_assert(!"Too small MPI array in H263 fmtp"); - continue; - } - - /* Standard size MPIs */ - for (j=0; jparam[i].name, &mpi_resolutions[j].name)==0) - { - unsigned mpi; - - mpi = pj_strtoul(&fmtp->param[i].val); - if (mpi<1 || mpi>32) - return PJMEDIA_SDP_EINFMTP; - - h263_fmtp->mpi[h263_fmtp->mpi_cnt].size = - mpi_resolutions[j].size; - h263_fmtp->mpi[h263_fmtp->mpi_cnt].val = mpi; - ++h263_fmtp->mpi_cnt; - parsed = PJ_TRUE; - } - } - if (parsed) - continue; - - /* Custom size MPIs */ - if (pj_stricmp(&fmtp->param[i].name, &CUSTOM)==0) { - pjmedia_rect_size size; - unsigned mpi; - pj_status_t status; - - status = parse_custom_res_fmtp(&fmtp->param[i].val, &size, &mpi); - if (status != PJ_SUCCESS) - return PJMEDIA_SDP_EINFMTP; - - h263_fmtp->mpi[h263_fmtp->mpi_cnt].size = size; - h263_fmtp->mpi[h263_fmtp->mpi_cnt].val = mpi; - ++h263_fmtp->mpi_cnt; - } + unsigned j; + pj_bool_t parsed = PJ_FALSE; + + if (h263_fmtp->mpi_cnt >= PJ_ARRAY_SIZE(h263_fmtp->mpi)) { + pj_assert(!"Too small MPI array in H263 fmtp"); + continue; + } + + /* Standard size MPIs */ + for (j=0; jparam[i].name, &mpi_resolutions[j].name)==0) + { + unsigned mpi; + + mpi = pj_strtoul(&fmtp->param[i].val); + if (mpi<1 || mpi>32) + return PJMEDIA_SDP_EINFMTP; + + h263_fmtp->mpi[h263_fmtp->mpi_cnt].size = + mpi_resolutions[j].size; + h263_fmtp->mpi[h263_fmtp->mpi_cnt].val = mpi; + ++h263_fmtp->mpi_cnt; + parsed = PJ_TRUE; + } + } + if (parsed) + continue; + + /* Custom size MPIs */ + if (pj_stricmp(&fmtp->param[i].name, &CUSTOM)==0) { + pjmedia_rect_size size; + unsigned mpi; + pj_status_t status; + + status = parse_custom_res_fmtp(&fmtp->param[i].val, &size, &mpi); + if (status != PJ_SUCCESS) + return PJMEDIA_SDP_EINFMTP; + + h263_fmtp->mpi[h263_fmtp->mpi_cnt].size = size; + h263_fmtp->mpi[h263_fmtp->mpi_cnt].val = mpi; + ++h263_fmtp->mpi_cnt; + } } return PJ_SUCCESS; @@ -176,127 +175,127 @@ static unsigned fps_to_mpi(const pjmedia_ratio *fps) } PJ_DEF(pj_status_t) pjmedia_vid_codec_h263_apply_fmtp( - pjmedia_vid_codec_param *param) + pjmedia_vid_codec_param *param) { if (param->dir & PJMEDIA_DIR_ENCODING) { - pjmedia_vid_codec_h263_fmtp fmtp_loc, fmtp_rem; - pjmedia_rect_size size = {0}; - unsigned mpi = 0; - pjmedia_video_format_detail *vfd; - pj_status_t status; - - vfd = pjmedia_format_get_video_format_detail(¶m->enc_fmt, - PJ_TRUE); - - /* Get local param */ - // Local param should be fetched from "param->enc_fmt" instead of - // "param->dec_fmtp". - //status = pjmedia_vid_codec_parse_h263_fmtp(¶m->dec_fmtp, - // &fmtp_loc); - //if (status != PJ_SUCCESS) - // return status; - fmtp_loc.mpi_cnt = 1; - fmtp_loc.mpi[0].size = vfd->size; - fmtp_loc.mpi[0].val = fps_to_mpi(&vfd->fps); - - /* Get remote param */ - status = pjmedia_vid_codec_parse_h263_fmtp(¶m->enc_fmtp, - &fmtp_rem); - if (status != PJ_SUCCESS) - return status; - - /* Negotiate size & MPI setting */ - if (fmtp_rem.mpi_cnt == 0) { - /* Remote doesn't specify MPI setting, send QCIF=1 */ - size.w = 176; - size.h = 144; - mpi = 1; - //} else if (fmtp_loc.mpi_cnt == 0) { - // /* Local MPI setting not set, just use remote preference. */ - // size = fmtp_rem.mpi[0].size; - // mpi = fmtp_rem.mpi[0].val; - } else { - /* Both have preferences, let's try to match them */ - unsigned i, j; - pj_bool_t matched = PJ_FALSE; - pj_uint32_t min_diff = 0xFFFFFFFF; - pj_uint32_t loc_sq, rem_sq, diff; - - /* Find the exact size match or the closest size, then choose - * the highest MPI among the match/closest pair. - */ - for (i = 0; i < fmtp_rem.mpi_cnt && !matched; ++i) { - rem_sq = fmtp_rem.mpi[i].size.w * fmtp_rem.mpi[i].size.h; - for (j = 0; j < fmtp_loc.mpi_cnt; ++j) { - /* See if we got exact match */ - if (fmtp_rem.mpi[i].size.w == fmtp_loc.mpi[j].size.w && - fmtp_rem.mpi[i].size.h == fmtp_loc.mpi[j].size.h) - { - size = fmtp_rem.mpi[i].size; - mpi = PJ_MAX(fmtp_rem.mpi[i].val, - fmtp_loc.mpi[j].val); - matched = PJ_TRUE; - break; - } - - /* Otherwise keep looking for the closest match */ - loc_sq = fmtp_loc.mpi[j].size.w * fmtp_loc.mpi[j].size.h; - diff = loc_sq>rem_sq? (loc_sq-rem_sq):(rem_sq-loc_sq); - if (diff < min_diff) { - size = rem_sqsize = size; - vfd->fps.num = 30000; - vfd->fps.denum = 1001 * mpi; + pjmedia_vid_codec_h263_fmtp fmtp_loc, fmtp_rem; + pjmedia_rect_size size = {0}; + unsigned mpi = 0; + pjmedia_video_format_detail *vfd; + pj_status_t status; + + vfd = pjmedia_format_get_video_format_detail(¶m->enc_fmt, + PJ_TRUE); + + /* Get local param */ + // Local param should be fetched from "param->enc_fmt" instead of + // "param->dec_fmtp". + //status = pjmedia_vid_codec_parse_h263_fmtp(¶m->dec_fmtp, + // &fmtp_loc); + //if (status != PJ_SUCCESS) + // return status; + fmtp_loc.mpi_cnt = 1; + fmtp_loc.mpi[0].size = vfd->size; + fmtp_loc.mpi[0].val = fps_to_mpi(&vfd->fps); + + /* Get remote param */ + status = pjmedia_vid_codec_parse_h263_fmtp(¶m->enc_fmtp, + &fmtp_rem); + if (status != PJ_SUCCESS) + return status; + + /* Negotiate size & MPI setting */ + if (fmtp_rem.mpi_cnt == 0) { + /* Remote doesn't specify MPI setting, send QCIF=1 */ + size.w = 176; + size.h = 144; + mpi = 1; + //} else if (fmtp_loc.mpi_cnt == 0) { + // /* Local MPI setting not set, just use remote preference. */ + // size = fmtp_rem.mpi[0].size; + // mpi = fmtp_rem.mpi[0].val; + } else { + /* Both have preferences, let's try to match them */ + unsigned i, j; + pj_bool_t matched = PJ_FALSE; + pj_uint32_t min_diff = 0xFFFFFFFF; + pj_uint32_t loc_sq, rem_sq, diff; + + /* Find the exact size match or the closest size, then choose + * the highest MPI among the match/closest pair. + */ + for (i = 0; i < fmtp_rem.mpi_cnt && !matched; ++i) { + rem_sq = fmtp_rem.mpi[i].size.w * fmtp_rem.mpi[i].size.h; + for (j = 0; j < fmtp_loc.mpi_cnt; ++j) { + /* See if we got exact match */ + if (fmtp_rem.mpi[i].size.w == fmtp_loc.mpi[j].size.w && + fmtp_rem.mpi[i].size.h == fmtp_loc.mpi[j].size.h) + { + size = fmtp_rem.mpi[i].size; + mpi = PJ_MAX(fmtp_rem.mpi[i].val, + fmtp_loc.mpi[j].val); + matched = PJ_TRUE; + break; + } + + /* Otherwise keep looking for the closest match */ + loc_sq = fmtp_loc.mpi[j].size.w * fmtp_loc.mpi[j].size.h; + diff = loc_sq>rem_sq? (loc_sq-rem_sq):(rem_sq-loc_sq); + if (diff < min_diff) { + size = rem_sqsize = size; + vfd->fps.num = 30000; + vfd->fps.denum = 1001 * mpi; } if (param->dir & PJMEDIA_DIR_DECODING) { - /* Here we just want to find the highest resolution and the lowest MPI - * we support and set it as the decoder param. - */ - pjmedia_vid_codec_h263_fmtp fmtp; - pjmedia_video_format_detail *vfd; - pj_status_t status; - - status = pjmedia_vid_codec_parse_h263_fmtp(¶m->dec_fmtp, - &fmtp); - if (status != PJ_SUCCESS) - return status; - - vfd = pjmedia_format_get_video_format_detail(¶m->dec_fmt, - PJ_TRUE); - - if (fmtp.mpi_cnt == 0) { - /* No resolution specified, lets just assume 4CIF=1! */ - vfd->size.w = 704; - vfd->size.h = 576; - vfd->fps.num = 30000; - vfd->fps.denum = 1001; - } else { - unsigned i, max_size = 0, max_size_idx = 0, min_mpi = 32; - - /* Get the largest size and the lowest MPI */ - for (i = 0; i < fmtp.mpi_cnt; ++i) { - if (fmtp.mpi[i].size.w * fmtp.mpi[i].size.h > max_size) { - max_size = fmtp.mpi[i].size.w * fmtp.mpi[i].size.h; - max_size_idx = i; - } - if (fmtp.mpi[i].val < min_mpi) - min_mpi = fmtp.mpi[i].val; - } - - vfd->size = fmtp.mpi[max_size_idx].size; - vfd->fps.num = 30000; - vfd->fps.denum = 1001 * min_mpi; - } + /* Here we just want to find the highest resolution and the lowest MPI + * we support and set it as the decoder param. + */ + pjmedia_vid_codec_h263_fmtp fmtp; + pjmedia_video_format_detail *vfd; + pj_status_t status; + + status = pjmedia_vid_codec_parse_h263_fmtp(¶m->dec_fmtp, + &fmtp); + if (status != PJ_SUCCESS) + return status; + + vfd = pjmedia_format_get_video_format_detail(¶m->dec_fmt, + PJ_TRUE); + + if (fmtp.mpi_cnt == 0) { + /* No resolution specified, lets just assume 4CIF=1! */ + vfd->size.w = 704; + vfd->size.h = 576; + vfd->fps.num = 30000; + vfd->fps.denum = 1001; + } else { + unsigned i, max_size = 0, max_size_idx = 0, min_mpi = 32; + + /* Get the largest size and the lowest MPI */ + for (i = 0; i < fmtp.mpi_cnt; ++i) { + if (fmtp.mpi[i].size.w * fmtp.mpi[i].size.h > max_size) { + max_size = fmtp.mpi[i].size.w * fmtp.mpi[i].size.h; + max_size_idx = i; + } + if (fmtp.mpi[i].val < min_mpi) + min_mpi = fmtp.mpi[i].val; + } + + vfd->size = fmtp.mpi[max_size_idx].size; + vfd->fps.num = 30000; + vfd->fps.denum = 1001 * min_mpi; + } } return PJ_SUCCESS; @@ -306,73 +305,73 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_h263_apply_fmtp( /* Declaration of H.264 level info */ typedef struct h264_level_info_t { - unsigned id; /* Level id. */ - unsigned max_mbps; /* Max macroblocks per second. */ - unsigned max_mb; /* Max macroblocks. */ - unsigned max_br; /* Max bitrate (kbps). */ + unsigned id; /* Level id. */ + unsigned max_mbps; /* Max macroblocks per second. */ + unsigned max_mb; /* Max macroblocks. */ + unsigned max_br; /* Max bitrate (kbps). */ } h264_level_info_t; /* Init H264 parameters based on profile-level-id */ static pj_status_t init_h264_profile(const pj_str_t *profile, - pjmedia_vid_codec_h264_fmtp *fmtp) + pjmedia_vid_codec_h264_fmtp *fmtp) { // Taken from https://www.itu.int/rec/T-REC-H.264 // H.264 (08/21) Table A-1 – Level limits const h264_level_info_t level_info[] = { - { 10, 1485, 99, 64 }, - { 9, 1485, 99, 128 }, /*< level 1b */ - { 11, 3000, 396, 192 }, - { 12, 6000, 396, 384 }, - { 13, 11880, 396, 768 }, - { 20, 11880, 396, 2000 }, - { 21, 19800, 792, 4000 }, - { 22, 20250, 1620, 4000 }, - { 30, 40500, 1620, 10000 }, - { 31, 108000, 3600, 14000 }, - { 32, 216000, 5120, 20000 }, - { 40, 245760, 8192, 20000 }, - { 41, 245760, 8192, 50000 }, - { 42, 522240, 8704, 50000 }, - { 50, 589824, 22080, 135000 }, - { 51, 983040, 36864, 240000 }, - { 52, 2073600, 36864, 240000 }, - { 60, 4177920, 139264, 240000 }, - { 61, 8355840, 139264, 480000 }, - { 62, 16711680, 139264, 800000 }, + { 10, 1485, 99, 64 }, + { 9, 1485, 99, 128 }, /*< level 1b */ + { 11, 3000, 396, 192 }, + { 12, 6000, 396, 384 }, + { 13, 11880, 396, 768 }, + { 20, 11880, 396, 2000 }, + { 21, 19800, 792, 4000 }, + { 22, 20250, 1620, 4000 }, + { 30, 40500, 1620, 10000 }, + { 31, 108000, 3600, 14000 }, + { 32, 216000, 5120, 20000 }, + { 40, 245760, 8192, 20000 }, + { 41, 245760, 8192, 50000 }, + { 42, 522240, 8704, 50000 }, + { 50, 589824, 22080, 135000 }, + { 51, 983040, 36864, 240000 }, + { 52, 2073600, 36864, 240000 }, + { 60, 4177920, 139264, 240000 }, + { 61, 8355840, 139264, 480000 }, + { 62, 16711680, 139264, 800000 }, }; unsigned i, tmp; pj_str_t endst; const h264_level_info_t *li = NULL; if (profile->slen != 6) - return PJMEDIA_SDP_EINFMTP; + return PJMEDIA_SDP_EINFMTP; tmp = pj_strtoul2(profile, &endst, 16); if (endst.slen) - return PJMEDIA_SDP_EINFMTP; + return PJMEDIA_SDP_EINFMTP; fmtp->profile_idc = (pj_uint8_t)((tmp >> 16) & 0xFF); fmtp->profile_iop = (pj_uint8_t)((tmp >> 8) & 0xFF); fmtp->level = (pj_uint8_t)(tmp & 0xFF); for (i = 0; i < PJ_ARRAY_SIZE(level_info); ++i) { - if (level_info[i].id == fmtp->level) { - li = &level_info[i]; - break; - } + if (level_info[i].id == fmtp->level) { + li = &level_info[i]; + break; + } } if (li == NULL) - return PJMEDIA_SDP_EINFMTP; + return PJMEDIA_SDP_EINFMTP; /* Init profile level spec */ if (fmtp->max_br == 0) - fmtp->max_br = li->max_br; + fmtp->max_br = li->max_br; if (fmtp->max_mbps == 0) - fmtp->max_mbps = li->max_mbps; + fmtp->max_mbps = li->max_mbps; if (fmtp->max_fs == 0) - fmtp->max_fs = li->max_mb; + fmtp->max_fs = li->max_mb; return PJ_SUCCESS; } @@ -380,16 +379,16 @@ static pj_status_t init_h264_profile(const pj_str_t *profile, /* H264 fmtp parser */ PJ_DEF(pj_status_t) pjmedia_vid_codec_h264_parse_fmtp( - const pjmedia_codec_fmtp *fmtp, - pjmedia_vid_codec_h264_fmtp *h264_fmtp) + const pjmedia_codec_fmtp *fmtp, + pjmedia_vid_codec_h264_fmtp *h264_fmtp) { - const pj_str_t PROFILE_LEVEL_ID = {"profile-level-id", 16}; - const pj_str_t MAX_MBPS = {"max-mbps", 8}; - const pj_str_t MAX_FS = {"max-fs", 6}; - const pj_str_t MAX_CPB = {"max-cpb", 7}; - const pj_str_t MAX_DPB = {"max-dpb", 7}; - const pj_str_t MAX_BR = {"max-br", 6}; - const pj_str_t PACKETIZATION_MODE = {"packetization-mode", 18}; + const pj_str_t PROFILE_LEVEL_ID = {"profile-level-id", 16}; + const pj_str_t MAX_MBPS = {"max-mbps", 8}; + const pj_str_t MAX_FS = {"max-fs", 6}; + const pj_str_t MAX_CPB = {"max-cpb", 7}; + const pj_str_t MAX_DPB = {"max-dpb", 7}; + const pj_str_t MAX_BR = {"max-br", 6}; + const pj_str_t PACKETIZATION_MODE = {"packetization-mode", 18}; const pj_str_t SPROP_PARAMETER_SETS = {"sprop-parameter-sets", 20}; unsigned i; pj_status_t status; @@ -397,96 +396,96 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_h264_parse_fmtp( pj_bzero(h264_fmtp, sizeof(*h264_fmtp)); for (i=0; icnt; ++i) { - unsigned tmp; - if (pj_stricmp(&fmtp->param[i].name, &PROFILE_LEVEL_ID)==0) { - /* Init H264 parameters based on level, if not set yet */ - status = init_h264_profile(&fmtp->param[i].val, h264_fmtp); - if (status != PJ_SUCCESS) - return status; - } else if (pj_stricmp(&fmtp->param[i].name, &PACKETIZATION_MODE)==0) { - tmp = pj_strtoul(&fmtp->param[i].val); - if (tmp <= 2) - h264_fmtp->packetization_mode = (pj_uint8_t)tmp; - else - return PJMEDIA_SDP_EINFMTP; - } else if (pj_stricmp(&fmtp->param[i].name, &MAX_MBPS)==0) { - tmp = pj_strtoul(&fmtp->param[i].val); - h264_fmtp->max_mbps = PJ_MAX(tmp, h264_fmtp->max_mbps); - } else if (pj_stricmp(&fmtp->param[i].name, &MAX_FS)==0) { - tmp = pj_strtoul(&fmtp->param[i].val); - h264_fmtp->max_fs = PJ_MAX(tmp, h264_fmtp->max_fs); - } else if (pj_stricmp(&fmtp->param[i].name, &MAX_CPB)==0) { - tmp = pj_strtoul(&fmtp->param[i].val); - h264_fmtp->max_cpb = PJ_MAX(tmp, h264_fmtp->max_cpb); - } else if (pj_stricmp(&fmtp->param[i].name, &MAX_DPB)==0) { - tmp = pj_strtoul(&fmtp->param[i].val); - h264_fmtp->max_dpb = PJ_MAX(tmp, h264_fmtp->max_dpb); - } else if (pj_stricmp(&fmtp->param[i].name, &MAX_BR)==0) { - tmp = pj_strtoul(&fmtp->param[i].val); - h264_fmtp->max_br = PJ_MAX(tmp, h264_fmtp->max_br); - } else if (pj_stricmp(&fmtp->param[i].name, &SPROP_PARAMETER_SETS)==0) - { - pj_str_t sps_st; - - sps_st = fmtp->param[i].val; - while (sps_st.slen) { - pj_str_t tmp_st; - int tmp_len; - const pj_uint8_t start_code[3] = {0, 0, 1}; - char *p; - pj_uint8_t *nal; - - /* Find field separator ',' */ - tmp_st = sps_st; - p = pj_strchr(&sps_st, ','); - if (p) { - tmp_st.slen = p - sps_st.ptr; - sps_st.ptr = p+1; - sps_st.slen -= (tmp_st.slen+1); - } else { - sps_st.slen = 0; - } - - /* Decode field and build NAL unit for this param */ - nal = &h264_fmtp->sprop_param_sets[ - h264_fmtp->sprop_param_sets_len]; - tmp_len = PJ_ARRAY_SIZE(h264_fmtp->sprop_param_sets) - - (int)h264_fmtp->sprop_param_sets_len - - PJ_ARRAY_SIZE(start_code); - status = pj_base64_decode(&tmp_st, - nal + PJ_ARRAY_SIZE(start_code), - &tmp_len); - if (status != PJ_SUCCESS) - return PJMEDIA_SDP_EINFMTP; - - tmp_len += PJ_ARRAY_SIZE(start_code); - pj_memcpy(nal, start_code, PJ_ARRAY_SIZE(start_code)); - h264_fmtp->sprop_param_sets_len += tmp_len; - } - } + unsigned tmp; + if (pj_stricmp(&fmtp->param[i].name, &PROFILE_LEVEL_ID)==0) { + /* Init H264 parameters based on level, if not set yet */ + status = init_h264_profile(&fmtp->param[i].val, h264_fmtp); + if (status != PJ_SUCCESS) + return status; + } else if (pj_stricmp(&fmtp->param[i].name, &PACKETIZATION_MODE)==0) { + tmp = pj_strtoul(&fmtp->param[i].val); + if (tmp <= 2) + h264_fmtp->packetization_mode = (pj_uint8_t)tmp; + else + return PJMEDIA_SDP_EINFMTP; + } else if (pj_stricmp(&fmtp->param[i].name, &MAX_MBPS)==0) { + tmp = pj_strtoul(&fmtp->param[i].val); + h264_fmtp->max_mbps = PJ_MAX(tmp, h264_fmtp->max_mbps); + } else if (pj_stricmp(&fmtp->param[i].name, &MAX_FS)==0) { + tmp = pj_strtoul(&fmtp->param[i].val); + h264_fmtp->max_fs = PJ_MAX(tmp, h264_fmtp->max_fs); + } else if (pj_stricmp(&fmtp->param[i].name, &MAX_CPB)==0) { + tmp = pj_strtoul(&fmtp->param[i].val); + h264_fmtp->max_cpb = PJ_MAX(tmp, h264_fmtp->max_cpb); + } else if (pj_stricmp(&fmtp->param[i].name, &MAX_DPB)==0) { + tmp = pj_strtoul(&fmtp->param[i].val); + h264_fmtp->max_dpb = PJ_MAX(tmp, h264_fmtp->max_dpb); + } else if (pj_stricmp(&fmtp->param[i].name, &MAX_BR)==0) { + tmp = pj_strtoul(&fmtp->param[i].val); + h264_fmtp->max_br = PJ_MAX(tmp, h264_fmtp->max_br); + } else if (pj_stricmp(&fmtp->param[i].name, &SPROP_PARAMETER_SETS)==0) + { + pj_str_t sps_st; + + sps_st = fmtp->param[i].val; + while (sps_st.slen) { + pj_str_t tmp_st; + int tmp_len; + const pj_uint8_t start_code[3] = {0, 0, 1}; + char *p; + pj_uint8_t *nal; + + /* Find field separator ',' */ + tmp_st = sps_st; + p = pj_strchr(&sps_st, ','); + if (p) { + tmp_st.slen = p - sps_st.ptr; + sps_st.ptr = p+1; + sps_st.slen -= (tmp_st.slen+1); + } else { + sps_st.slen = 0; + } + + /* Decode field and build NAL unit for this param */ + nal = &h264_fmtp->sprop_param_sets[ + h264_fmtp->sprop_param_sets_len]; + tmp_len = PJ_ARRAY_SIZE(h264_fmtp->sprop_param_sets) - + (int)h264_fmtp->sprop_param_sets_len - + PJ_ARRAY_SIZE(start_code); + status = pj_base64_decode(&tmp_st, + nal + PJ_ARRAY_SIZE(start_code), + &tmp_len); + if (status != PJ_SUCCESS) + return PJMEDIA_SDP_EINFMTP; + + tmp_len += PJ_ARRAY_SIZE(start_code); + pj_memcpy(nal, start_code, PJ_ARRAY_SIZE(start_code)); + h264_fmtp->sprop_param_sets_len += tmp_len; + } + } } /* When profile-level-id is not specified, use default value "42000A" */ if (h264_fmtp->profile_idc == 0) { - const pj_str_t DEF_PROFILE = {"42000A", 6}; + const pj_str_t DEF_PROFILE = {"42000A", 6}; - status = init_h264_profile(&DEF_PROFILE, h264_fmtp); - if (status != PJ_SUCCESS) - return status; + status = init_h264_profile(&DEF_PROFILE, h264_fmtp); + if (status != PJ_SUCCESS) + return status; } return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_vid_codec_h264_match_sdp(pj_pool_t *pool, - pjmedia_sdp_media *offer, - unsigned o_fmt_idx, - pjmedia_sdp_media *answer, - unsigned a_fmt_idx, - unsigned option) + pjmedia_sdp_media *offer, + unsigned o_fmt_idx, + pjmedia_sdp_media *answer, + unsigned a_fmt_idx, + unsigned option) { - const pj_str_t PROFILE_LEVEL_ID = {"profile-level-id", 16}; - const pj_str_t PACKETIZATION_MODE = {"packetization-mode", 18}; + const pj_str_t PROFILE_LEVEL_ID = {"profile-level-id", 16}; + const pj_str_t PACKETIZATION_MODE = {"packetization-mode", 18}; pjmedia_codec_fmtp o_fmtp_raw, a_fmtp_raw; pjmedia_vid_codec_h264_fmtp o_fmtp, a_fmtp; pj_status_t status; @@ -495,92 +494,92 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_h264_match_sdp(pj_pool_t *pool, /* Parse offer */ status = pjmedia_stream_info_parse_fmtp( - NULL, offer, - pj_strtoul(&offer->desc.fmt[o_fmt_idx]), - &o_fmtp_raw); + NULL, offer, + pj_strtoul(&offer->desc.fmt[o_fmt_idx]), + &o_fmtp_raw); if (status != PJ_SUCCESS) - return status; + return status; status = pjmedia_vid_codec_h264_parse_fmtp(&o_fmtp_raw, &o_fmtp); if (status != PJ_SUCCESS) - return status; + return status; /* Parse answer */ status = pjmedia_stream_info_parse_fmtp( - NULL, answer, - pj_strtoul(&answer->desc.fmt[a_fmt_idx]), - &a_fmtp_raw); + NULL, answer, + pj_strtoul(&answer->desc.fmt[a_fmt_idx]), + &a_fmtp_raw); if (status != PJ_SUCCESS) - return status; + return status; status = pjmedia_vid_codec_h264_parse_fmtp(&a_fmtp_raw, &a_fmtp); if (status != PJ_SUCCESS) - return status; + return status; if (option & PJMEDIA_SDP_NEG_FMT_MATCH_ALLOW_MODIFY_ANSWER) { - unsigned i; - - /* Flexible negotiation, if the answer has higher capability than - * the offer, adjust the answer capability to be match to the offer. - */ - if (a_fmtp.profile_idc >= o_fmtp.profile_idc) - a_fmtp.profile_idc = o_fmtp.profile_idc; - if (a_fmtp.profile_iop != o_fmtp.profile_iop) - a_fmtp.profile_iop = o_fmtp.profile_iop; - if (a_fmtp.level >= o_fmtp.level) - a_fmtp.level = o_fmtp.level; - if (a_fmtp.packetization_mode >= o_fmtp.packetization_mode) - a_fmtp.packetization_mode = o_fmtp.packetization_mode; - - /* Match them now */ + unsigned i; + + /* Flexible negotiation, if the answer has higher capability than + * the offer, adjust the answer capability to be match to the offer. + */ + if (a_fmtp.profile_idc >= o_fmtp.profile_idc) + a_fmtp.profile_idc = o_fmtp.profile_idc; + if (a_fmtp.profile_iop != o_fmtp.profile_iop) + a_fmtp.profile_iop = o_fmtp.profile_iop; + if (a_fmtp.level >= o_fmtp.level) + a_fmtp.level = o_fmtp.level; + if (a_fmtp.packetization_mode >= o_fmtp.packetization_mode) + a_fmtp.packetization_mode = o_fmtp.packetization_mode; + + /* Match them now */ #if H264_STRICT_SDP_NEGO - if (a_fmtp.profile_idc != o_fmtp.profile_idc || - a_fmtp.profile_iop != o_fmtp.profile_iop || - a_fmtp.level != o_fmtp.level || - a_fmtp.packetization_mode != o_fmtp.packetization_mode) - { - return PJMEDIA_SDP_EFORMATNOTEQUAL; - } + if (a_fmtp.profile_idc != o_fmtp.profile_idc || + a_fmtp.profile_iop != o_fmtp.profile_iop || + a_fmtp.level != o_fmtp.level || + a_fmtp.packetization_mode != o_fmtp.packetization_mode) + { + return PJMEDIA_SDP_EFORMATNOTEQUAL; + } #else - if (a_fmtp.profile_idc != o_fmtp.profile_idc) - { - return PJMEDIA_SDP_EFORMATNOTEQUAL; - } + if (a_fmtp.profile_idc != o_fmtp.profile_idc) + { + return PJMEDIA_SDP_EFORMATNOTEQUAL; + } #endif - /* Update the answer */ - for (i = 0; i < a_fmtp_raw.cnt; ++i) { - if (pj_stricmp(&a_fmtp_raw.param[i].name, &PROFILE_LEVEL_ID) == 0) - { - char *p = a_fmtp_raw.param[i].val.ptr; - pj_val_to_hex_digit(a_fmtp.profile_idc, p); - p += 2; - pj_val_to_hex_digit(a_fmtp.profile_iop, p); - p += 2; - pj_val_to_hex_digit(a_fmtp.level, p); - } - else if (pj_stricmp(&a_fmtp_raw.param[i].name, &PACKETIZATION_MODE) == 0) - { - char *p = a_fmtp_raw.param[i].val.ptr; - *p = '0' + a_fmtp.packetization_mode; - } - } + /* Update the answer */ + for (i = 0; i < a_fmtp_raw.cnt; ++i) { + if (pj_stricmp(&a_fmtp_raw.param[i].name, &PROFILE_LEVEL_ID) == 0) + { + char *p = a_fmtp_raw.param[i].val.ptr; + pj_val_to_hex_digit(a_fmtp.profile_idc, p); + p += 2; + pj_val_to_hex_digit(a_fmtp.profile_iop, p); + p += 2; + pj_val_to_hex_digit(a_fmtp.level, p); + } + else if (pj_stricmp(&a_fmtp_raw.param[i].name, &PACKETIZATION_MODE) == 0) + { + char *p = a_fmtp_raw.param[i].val.ptr; + *p = '0' + a_fmtp.packetization_mode; + } + } } else { #if H264_STRICT_SDP_NEGO - /* Strict negotiation */ - if (a_fmtp.profile_idc != o_fmtp.profile_idc || - a_fmtp.profile_iop != o_fmtp.profile_iop || - a_fmtp.level != o_fmtp.level || - a_fmtp.packetization_mode != o_fmtp.packetization_mode) - { - return PJMEDIA_SDP_EFORMATNOTEQUAL; - } + /* Strict negotiation */ + if (a_fmtp.profile_idc != o_fmtp.profile_idc || + a_fmtp.profile_iop != o_fmtp.profile_iop || + a_fmtp.level != o_fmtp.level || + a_fmtp.packetization_mode != o_fmtp.packetization_mode) + { + return PJMEDIA_SDP_EFORMATNOTEQUAL; + } #else - /* Permissive negotiation */ - if (a_fmtp.profile_idc != o_fmtp.profile_idc) - { - return PJMEDIA_SDP_EFORMATNOTEQUAL; - } + /* Permissive negotiation */ + if (a_fmtp.profile_idc != o_fmtp.profile_idc) + { + return PJMEDIA_SDP_EFORMATNOTEQUAL; + } #endif } @@ -592,9 +591,9 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_h264_match_sdp(pj_pool_t *pool, static unsigned gcd (unsigned a, unsigned b) { unsigned c; while (b) { - c = a % b; - a = b; - b = c; + c = a % b; + a = b; + b = c; } return a; } @@ -603,15 +602,15 @@ static unsigned gcd (unsigned a, unsigned b) { * aspect ratio. */ static pj_status_t find_highest_res(pjmedia_vid_codec_h264_fmtp *fmtp, - const pjmedia_ratio *fps, - const pjmedia_ratio *ratio, - pjmedia_rect_size *size, - pj_bool_t is_decoding) + const pjmedia_ratio *fps, + const pjmedia_ratio *ratio, + pjmedia_rect_size *size, + pj_bool_t is_decoding) { pjmedia_ratio def_ratio = { DEFAULT_H264_RATIO_NUM, - DEFAULT_H264_RATIO_DENUM }; + DEFAULT_H264_RATIO_DENUM }; pjmedia_ratio def_fps = { DEFAULT_H264_FPS_NUM, - DEFAULT_H264_FPS_DENUM }; + DEFAULT_H264_FPS_DENUM }; pjmedia_ratio asp_ratio, the_fps; unsigned max_fs, g, scale; @@ -619,9 +618,9 @@ static pj_status_t find_highest_res(pjmedia_vid_codec_h264_fmtp *fmtp, /* Get the ratio, or just use default if not provided. */ if (ratio && ratio->num && ratio->denum) { - asp_ratio = *ratio; + asp_ratio = *ratio; } else { - asp_ratio = def_ratio; + asp_ratio = def_ratio; } /* Normalize the aspect ratio */ @@ -631,9 +630,9 @@ static pj_status_t find_highest_res(pjmedia_vid_codec_h264_fmtp *fmtp, /* Get the frame rate, or just use default if not provided. */ if (fps && fps->num && fps->denum) { - the_fps = *fps; + the_fps = *fps; } else { - the_fps = def_fps; + the_fps = def_fps; } /* Calculate maximum size (in macroblocks) */ @@ -645,9 +644,9 @@ static pj_status_t find_highest_res(pjmedia_vid_codec_h264_fmtp *fmtp, */ if ((int)max_fs < asp_ratio.num * asp_ratio.denum) { if ((int)max_fs >= def_ratio.num * def_ratio.denum) - asp_ratio = def_ratio; - else - asp_ratio.num = asp_ratio.denum = 1; + asp_ratio = def_ratio; + else + asp_ratio.num = asp_ratio.denum = 1; } /* Calculate the scale factor for size */ @@ -661,11 +660,11 @@ static pj_status_t find_highest_res(pjmedia_vid_codec_h264_fmtp *fmtp, * so we need to make sure that frame size is not less than max_fs. */ if (is_decoding && ((size->w * size->h) >> 8) < max_fs) { - /* Size is less than max_fs, recalculate using ratio 1:1 and - * round up the scale. - */ - scale = pj_isqrt(max_fs) + 1; - size->w = size->h = scale * 16; + /* Size is less than max_fs, recalculate using ratio 1:1 and + * round up the scale. + */ + scale = pj_isqrt(max_fs) + 1; + size->w = size->h = scale * 16; } return PJ_SUCCESS; @@ -673,95 +672,95 @@ static pj_status_t find_highest_res(pjmedia_vid_codec_h264_fmtp *fmtp, PJ_DEF(pj_status_t) pjmedia_vid_codec_h264_apply_fmtp( - pjmedia_vid_codec_param *param) + pjmedia_vid_codec_param *param) { if (param->dir & PJMEDIA_DIR_ENCODING) { - pjmedia_vid_codec_h264_fmtp fmtp; - pjmedia_video_format_detail *vfd; - pj_status_t status; - - /* Get remote param */ - status = pjmedia_vid_codec_h264_parse_fmtp(¶m->enc_fmtp, - &fmtp); - if (status != PJ_SUCCESS) - return status; - - /* Adjust fps, size, and bitrate to conform to H.264 level - * specified by remote SDP fmtp. - */ - vfd = pjmedia_format_get_video_format_detail(¶m->enc_fmt, - PJ_TRUE); - - if (vfd->fps.num == 0 || vfd->fps.denum == 0) { - vfd->fps.num = DEFAULT_H264_FPS_NUM; - vfd->fps.denum = DEFAULT_H264_FPS_DENUM; - } - - if (vfd->size.w && vfd->size.h) { - unsigned mb, mbps; - - /* Scale down the resolution if it exceeds profile spec */ - mb = CALC_H264_MB_NUM(vfd->size); - mbps = CALC_H264_MBPS(vfd->size, vfd->fps); - if (mb > fmtp.max_fs || mbps > fmtp.max_mbps) { - pjmedia_ratio r; - r.num = vfd->size.w; - r.denum = vfd->size.h; - find_highest_res(&fmtp, &vfd->fps, &r, &vfd->size, PJ_FALSE); - } - } else { - /* When not specified, just use the highest res possible*/ - pjmedia_ratio r; - r.num = vfd->size.w; - r.denum = vfd->size.h; - find_highest_res(&fmtp, &vfd->fps, &r, &vfd->size, PJ_FALSE); - } - - /* Encoding bitrate must not be higher than H264 level spec */ - if (vfd->avg_bps > fmtp.max_br * 1000) - vfd->avg_bps = fmtp.max_br * 1000; - if (vfd->max_bps > fmtp.max_br * 1000) - vfd->max_bps = fmtp.max_br * 1000; + pjmedia_vid_codec_h264_fmtp fmtp; + pjmedia_video_format_detail *vfd; + pj_status_t status; + + /* Get remote param */ + status = pjmedia_vid_codec_h264_parse_fmtp(¶m->enc_fmtp, + &fmtp); + if (status != PJ_SUCCESS) + return status; + + /* Adjust fps, size, and bitrate to conform to H.264 level + * specified by remote SDP fmtp. + */ + vfd = pjmedia_format_get_video_format_detail(¶m->enc_fmt, + PJ_TRUE); + + if (vfd->fps.num == 0 || vfd->fps.denum == 0) { + vfd->fps.num = DEFAULT_H264_FPS_NUM; + vfd->fps.denum = DEFAULT_H264_FPS_DENUM; + } + + if (vfd->size.w && vfd->size.h) { + unsigned mb, mbps; + + /* Scale down the resolution if it exceeds profile spec */ + mb = CALC_H264_MB_NUM(vfd->size); + mbps = CALC_H264_MBPS(vfd->size, vfd->fps); + if (mb > fmtp.max_fs || mbps > fmtp.max_mbps) { + pjmedia_ratio r; + r.num = vfd->size.w; + r.denum = vfd->size.h; + find_highest_res(&fmtp, &vfd->fps, &r, &vfd->size, PJ_FALSE); + } + } else { + /* When not specified, just use the highest res possible*/ + pjmedia_ratio r; + r.num = vfd->size.w; + r.denum = vfd->size.h; + find_highest_res(&fmtp, &vfd->fps, &r, &vfd->size, PJ_FALSE); + } + + /* Encoding bitrate must not be higher than H264 level spec */ + if (vfd->avg_bps > fmtp.max_br * 1000) + vfd->avg_bps = fmtp.max_br * 1000; + if (vfd->max_bps > fmtp.max_br * 1000) + vfd->max_bps = fmtp.max_br * 1000; } if (param->dir & PJMEDIA_DIR_DECODING) { - /* Here we just want to find the highest resolution possible from the - * fmtp and set it as the decoder param. - */ - pjmedia_vid_codec_h264_fmtp fmtp; - pjmedia_video_format_detail *vfd; - pjmedia_ratio r; - pjmedia_rect_size highest_size; - pj_status_t status; - - status = pjmedia_vid_codec_h264_parse_fmtp(¶m->dec_fmtp, - &fmtp); - if (status != PJ_SUCCESS) - return status; - - vfd = pjmedia_format_get_video_format_detail(¶m->dec_fmt, - PJ_TRUE); - - if (vfd->fps.num == 0 || vfd->fps.denum == 0) { - vfd->fps.num = DEFAULT_H264_FPS_NUM; - vfd->fps.denum = DEFAULT_H264_FPS_DENUM; - } - - /* Normalize decoding resolution, i.e: it must not be lower than - * the H264 profile level setting used, as this may be used by - * app to allocate buffer. - */ - r.num = vfd->size.w; - r.denum = vfd->size.h; - find_highest_res(&fmtp, &vfd->fps, &r, &highest_size, PJ_TRUE); - if (vfd->size.w * vfd->size.h < highest_size.w * highest_size.h) - vfd->size = highest_size; - - /* Normalize decoding bitrate based on H264 level spec */ - if (vfd->avg_bps < fmtp.max_br * 1000) - vfd->avg_bps = fmtp.max_br * 1000; - if (vfd->max_bps < fmtp.max_br * 1000) - vfd->max_bps = fmtp.max_br * 1000; + /* Here we just want to find the highest resolution possible from the + * fmtp and set it as the decoder param. + */ + pjmedia_vid_codec_h264_fmtp fmtp; + pjmedia_video_format_detail *vfd; + pjmedia_ratio r; + pjmedia_rect_size highest_size; + pj_status_t status; + + status = pjmedia_vid_codec_h264_parse_fmtp(¶m->dec_fmtp, + &fmtp); + if (status != PJ_SUCCESS) + return status; + + vfd = pjmedia_format_get_video_format_detail(¶m->dec_fmt, + PJ_TRUE); + + if (vfd->fps.num == 0 || vfd->fps.denum == 0) { + vfd->fps.num = DEFAULT_H264_FPS_NUM; + vfd->fps.denum = DEFAULT_H264_FPS_DENUM; + } + + /* Normalize decoding resolution, i.e: it must not be lower than + * the H264 profile level setting used, as this may be used by + * app to allocate buffer. + */ + r.num = vfd->size.w; + r.denum = vfd->size.h; + find_highest_res(&fmtp, &vfd->fps, &r, &highest_size, PJ_TRUE); + if (vfd->size.w * vfd->size.h < highest_size.w * highest_size.h) + vfd->size = highest_size; + + /* Normalize decoding bitrate based on H264 level spec */ + if (vfd->avg_bps < fmtp.max_br * 1000) + vfd->avg_bps = fmtp.max_br * 1000; + if (vfd->max_bps < fmtp.max_br * 1000) + vfd->max_bps = fmtp.max_br * 1000; } return PJ_SUCCESS; @@ -770,31 +769,31 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_h264_apply_fmtp( /* VPX fmtp parser */ PJ_DEF(pj_status_t) pjmedia_vid_codec_vpx_parse_fmtp( - const pjmedia_codec_fmtp *fmtp, - pjmedia_vid_codec_vpx_fmtp *vpx_fmtp) + const pjmedia_codec_fmtp *fmtp, + pjmedia_vid_codec_vpx_fmtp *vpx_fmtp) { - const pj_str_t PROFILE_ID = {"profile-id", 10}; - const pj_str_t MAX_FR = {"max-fr", 6}; - const pj_str_t MAX_FS = {"max-fs", 6}; + const pj_str_t PROFILE_ID = {"profile-id", 10}; + const pj_str_t MAX_FR = {"max-fr", 6}; + const pj_str_t MAX_FS = {"max-fs", 6}; unsigned i; pj_bzero(vpx_fmtp, sizeof(*vpx_fmtp)); for (i = 0; i < fmtp->cnt; ++i) { - unsigned tmp; - - if (pj_stricmp(&fmtp->param[i].name, &MAX_FS) == 0) { - tmp = pj_strtoul(&fmtp->param[i].val); - vpx_fmtp->max_fs = PJ_MAX(tmp, vpx_fmtp->max_fs); - } else if (pj_stricmp(&fmtp->param[i].name, &MAX_FR) == 0) { - tmp = pj_strtoul(&fmtp->param[i].val); - vpx_fmtp->max_fr = PJ_MAX(tmp, vpx_fmtp->max_fr); - } else if (pj_stricmp(&fmtp->param[i].name, &PROFILE_ID) == 0) { - tmp = pj_strtoul(&fmtp->param[i].val); - vpx_fmtp->profile_id = (pj_uint8_t) - PJ_MAX(tmp, vpx_fmtp->profile_id); - } + unsigned tmp; + + if (pj_stricmp(&fmtp->param[i].name, &MAX_FS) == 0) { + tmp = pj_strtoul(&fmtp->param[i].val); + vpx_fmtp->max_fs = PJ_MAX(tmp, vpx_fmtp->max_fs); + } else if (pj_stricmp(&fmtp->param[i].name, &MAX_FR) == 0) { + tmp = pj_strtoul(&fmtp->param[i].val); + vpx_fmtp->max_fr = PJ_MAX(tmp, vpx_fmtp->max_fr); + } else if (pj_stricmp(&fmtp->param[i].name, &PROFILE_ID) == 0) { + tmp = pj_strtoul(&fmtp->param[i].val); + vpx_fmtp->profile_id = (pj_uint8_t) + PJ_MAX(tmp, vpx_fmtp->profile_id); + } } return PJ_SUCCESS; @@ -802,79 +801,79 @@ PJ_DEF(pj_status_t) pjmedia_vid_codec_vpx_parse_fmtp( PJ_DEF(pj_status_t) pjmedia_vid_codec_vpx_apply_fmtp( - pjmedia_vid_codec_param *param) + pjmedia_vid_codec_param *param) { if (param->dir & PJMEDIA_DIR_ENCODING) { - pjmedia_vid_codec_vpx_fmtp fmtp; - pjmedia_video_format_detail *vfd; - pj_status_t status; - - /* Get remote param */ - status = pjmedia_vid_codec_vpx_parse_fmtp(¶m->enc_fmtp, - &fmtp); - if (status != PJ_SUCCESS) - return status; - - /* Adjust fps and size to conform to the parameter - * specified by remote SDP fmtp. - */ - vfd = pjmedia_format_get_video_format_detail(¶m->enc_fmt, - PJ_TRUE); - - if (fmtp.max_fr > 0) { - if ((float)vfd->fps.num/vfd->fps.denum > (float)fmtp.max_fr) { - vfd->fps.num = fmtp.max_fr; - vfd->fps.denum = 1; - } - } - - if (fmtp.max_fs > 0) { - unsigned max_res = ((int)pj_isqrt(fmtp.max_fs * 8)) * 16; - - if (vfd->size.w > max_res || vfd->size.h > max_res) { - /* Here we maintain the aspect ratio. Or should we scale down - * to some predetermined resolution instead (for example, - * if the requested resolution is 640x480 and max_res is - * 600, should we scale down to 480x360)? - */ - unsigned larger = (vfd->size.w > vfd->size.h)? - vfd->size.w: vfd->size.h; - float scale = (float)max_res/larger; - - vfd->size.w = (int)(scale * vfd->size.w); - vfd->size.h = (int)(scale * vfd->size.h); - } - } + pjmedia_vid_codec_vpx_fmtp fmtp; + pjmedia_video_format_detail *vfd; + pj_status_t status; + + /* Get remote param */ + status = pjmedia_vid_codec_vpx_parse_fmtp(¶m->enc_fmtp, + &fmtp); + if (status != PJ_SUCCESS) + return status; + + /* Adjust fps and size to conform to the parameter + * specified by remote SDP fmtp. + */ + vfd = pjmedia_format_get_video_format_detail(¶m->enc_fmt, + PJ_TRUE); + + if (fmtp.max_fr > 0) { + if ((float)vfd->fps.num/vfd->fps.denum > (float)fmtp.max_fr) { + vfd->fps.num = fmtp.max_fr; + vfd->fps.denum = 1; + } + } + + if (fmtp.max_fs > 0) { + unsigned max_res = ((int)pj_isqrt(fmtp.max_fs * 8)) * 16; + + if (vfd->size.w > max_res || vfd->size.h > max_res) { + /* Here we maintain the aspect ratio. Or should we scale down + * to some predetermined resolution instead (for example, + * if the requested resolution is 640x480 and max_res is + * 600, should we scale down to 480x360)? + */ + unsigned larger = (vfd->size.w > vfd->size.h)? + vfd->size.w: vfd->size.h; + float scale = (float)max_res/larger; + + vfd->size.w = (int)(scale * vfd->size.w); + vfd->size.h = (int)(scale * vfd->size.h); + } + } } if (param->dir & PJMEDIA_DIR_DECODING) { - /* Here we just want to find the highest fps and resolution possible - * from the fmtp and set it as the decoder param. - */ - pjmedia_vid_codec_vpx_fmtp fmtp; - pjmedia_video_format_detail *vfd; - pj_status_t status; - - /* Get remote param */ - status = pjmedia_vid_codec_vpx_parse_fmtp(¶m->dec_fmtp, - &fmtp); - if (status != PJ_SUCCESS) - return status; - - vfd = pjmedia_format_get_video_format_detail(¶m->dec_fmt, - PJ_TRUE); - - if (fmtp.max_fr > 0) { - vfd->fps.num = fmtp.max_fr; - vfd->fps.denum = 1; - } - - if (fmtp.max_fs > 0) { - unsigned max_res = ((int)pj_isqrt(fmtp.max_fs * 8)) * 16; - - vfd->size.w = max_res; - vfd->size.h = max_res; - } + /* Here we just want to find the highest fps and resolution possible + * from the fmtp and set it as the decoder param. + */ + pjmedia_vid_codec_vpx_fmtp fmtp; + pjmedia_video_format_detail *vfd; + pj_status_t status; + + /* Get remote param */ + status = pjmedia_vid_codec_vpx_parse_fmtp(¶m->dec_fmtp, + &fmtp); + if (status != PJ_SUCCESS) + return status; + + vfd = pjmedia_format_get_video_format_detail(¶m->dec_fmt, + PJ_TRUE); + + if (fmtp.max_fr > 0) { + vfd->fps.num = fmtp.max_fr; + vfd->fps.denum = 1; + } + + if (fmtp.max_fs > 0) { + unsigned max_res = ((int)pj_isqrt(fmtp.max_fs * 8)) * 16; + + vfd->size.w = max_res; + vfd->size.h = max_res; + } } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia/vid_conf.c b/pjmedia/src/pjmedia/vid_conf.c index c47c4cc75b..ba9c065a06 100644 --- a/pjmedia/src/pjmedia/vid_conf.c +++ b/pjmedia/src/pjmedia/vid_conf.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2019 Teluu Inc. (http://www.teluu.com) * @@ -27,8 +26,8 @@ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -#define CONF_NAME "vidconf" -#define CONF_SIGN PJMEDIA_SIG_VID_CONF +#define CONF_NAME "vidconf" +#define CONF_SIGN PJMEDIA_SIG_VID_CONF /* If set, conf will stop clock when there is no ports connection. However, * this may cause stuck if port remove/disconnect is called from the clock @@ -40,10 +39,10 @@ #define MAX_ERR_COUNT 150 /* Clockrate for video timestamp unit */ -#define TS_CLOCK_RATE 90000 +#define TS_CLOCK_RATE 90000 -#define THIS_FILE "vid_conf.c" -#define TRACE_(x) PJ_LOG(5,x) +#define THIS_FILE "vid_conf.c" +#define TRACE_(x) PJ_LOG(5,x) /* Forward declarations */ @@ -54,16 +53,16 @@ typedef struct op_entry op_entry; */ struct pjmedia_vid_conf { - pjmedia_vid_conf_setting opt; /**< Settings. */ - pj_pool_t *pool; /**< Pool. */ - unsigned port_cnt; /**< Current number of ports. */ - unsigned connect_cnt; /**< Total number of connections */ - pj_mutex_t *mutex; /**< Conference mutex. */ - struct vconf_port **ports; /**< Array of ports. */ - pjmedia_clock *clock; /**< Clock. */ - - op_entry *op_queue; /**< Queue of operations. */ - op_entry *op_queue_free;/**< Queue of free entries. */ + pjmedia_vid_conf_setting opt; /**< Settings. */ + pj_pool_t *pool; /**< Pool. */ + unsigned port_cnt; /**< Current number of ports. */ + unsigned connect_cnt; /**< Total number of connections */ + pj_mutex_t *mutex; /**< Conference mutex. */ + struct vconf_port **ports; /**< Array of ports. */ + pjmedia_clock *clock; /**< Clock. */ + + op_entry *op_queue; /**< Queue of operations. */ + op_entry *op_queue_free;/**< Queue of free entries. */ }; @@ -72,15 +71,15 @@ struct pjmedia_vid_conf */ typedef struct render_state { - pjmedia_format_id src_fmt_id; /**< Source format ID. */ - pjmedia_rect_size src_frame_size; /**< Source frame size. */ - pjmedia_rect src_rect; /**< Source region to be rendered. */ + pjmedia_format_id src_fmt_id; /**< Source format ID. */ + pjmedia_rect_size src_frame_size; /**< Source frame size. */ + pjmedia_rect src_rect; /**< Source region to be rendered. */ - pjmedia_format_id dst_fmt_id; /**< Destination format ID. */ - pjmedia_rect_size dst_frame_size; /**< Destination frame size. */ - pjmedia_rect dst_rect; /**< Destination region. */ + pjmedia_format_id dst_fmt_id; /**< Destination format ID. */ + pjmedia_rect_size dst_frame_size; /**< Destination frame size. */ + pjmedia_rect dst_rect; /**< Destination region. */ - pjmedia_converter *converter; /**< Converter. */ + pjmedia_converter *converter; /**< Converter. */ } render_state; @@ -90,40 +89,40 @@ typedef struct render_state */ typedef struct vconf_port { - pj_pool_t *pool; /**< Pool. */ - unsigned idx; /**< Port index. */ - pj_str_t name; /**< Port name. */ - pjmedia_port *port; /**< Video port. */ - pjmedia_format format; /**< Copy of port format info. */ - pj_uint32_t ts_interval; /**< Port put/get interval. */ - pj_timestamp ts_next; /**< Time for next put/get_frame(). */ - void *get_buf; /**< Buffer for get_frame(). */ - pj_size_t get_buf_size; /**< Buffer size for get_frame(). */ - pj_bool_t got_frame; /**< Last get_frame() got frame? */ - void *put_buf; /**< Buffer for put_frame(). */ - pj_size_t put_buf_size; /**< Buffer size for put_frame(). */ - - unsigned listener_cnt; /**< Number of listeners. */ - unsigned *listener_slots;/**< Array of listeners (for info). */ - - unsigned transmitter_cnt;/**op_queue_free)) { - ope = conf->op_queue_free->next; - pj_list_erase(ope); + ope = conf->op_queue_free->next; + pj_list_erase(ope); } else { - ope = PJ_POOL_ZALLOC_T(conf->pool, op_entry); + ope = PJ_POOL_ZALLOC_T(conf->pool, op_entry); } return ope; } @@ -199,30 +198,30 @@ static void handle_op_queue(pjmedia_vid_conf *conf) op = conf->op_queue->next; while (op != conf->op_queue) { - next_op = op->next; - pj_list_erase(op); - - switch(op->type) { - case OP_REMOVE_PORT: - op_remove_port(conf, &op->param); - break; - case OP_CONNECT_PORTS: - op_connect_ports(conf, &op->param); - break; - case OP_DISCONNECT_PORTS: - op_disconnect_ports(conf, &op->param); - break; - case OP_UPDATE_PORT: - op_update_port(conf, &op->param); - break; - default: - pj_assert(!"Invalid sync-op in video conference"); - break; - } - - op->type = OP_UNKNOWN; - pj_list_push_back(conf->op_queue_free, op); - op = next_op; + next_op = op->next; + pj_list_erase(op); + + switch(op->type) { + case OP_REMOVE_PORT: + op_remove_port(conf, &op->param); + break; + case OP_CONNECT_PORTS: + op_connect_ports(conf, &op->param); + break; + case OP_DISCONNECT_PORTS: + op_disconnect_ports(conf, &op->param); + break; + case OP_UPDATE_PORT: + op_update_port(conf, &op->param); + break; + default: + pj_assert(!"Invalid sync-op in video conference"); + break; + } + + op->type = OP_UNKNOWN; + pj_list_push_back(conf->op_queue_free, op); + op = next_op; } } @@ -242,9 +241,9 @@ PJ_DEF(void) pjmedia_vid_conf_setting_default(pjmedia_vid_conf_setting *opt) * Create a video conference bridge. */ PJ_DEF(pj_status_t) pjmedia_vid_conf_create( - pj_pool_t *parent_pool, - const pjmedia_vid_conf_setting *opt, - pjmedia_vid_conf **p_vid_conf) + pj_pool_t *parent_pool, + const pjmedia_vid_conf_setting *opt, + pjmedia_vid_conf **p_vid_conf) { pj_pool_t *pool; pjmedia_vid_conf *vid_conf; @@ -256,7 +255,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_create( /* Create own pool */ pool = pj_pool_create(parent_pool->factory, "vidconf", 500, 500, NULL); if (!pool) { - return PJ_ENOMEM; + return PJ_ENOMEM; } /* Allocate conf structure */ @@ -266,25 +265,25 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_create( /* Init settings */ if (opt) { - vid_conf->opt = *opt; + vid_conf->opt = *opt; } else { - pjmedia_vid_conf_setting_default(&vid_conf->opt); + pjmedia_vid_conf_setting_default(&vid_conf->opt); } /* Allocate ports */ vid_conf->ports = (vconf_port**) - pj_pool_zalloc(pool, vid_conf->opt.max_slot_cnt * - sizeof(vconf_port*)); + pj_pool_zalloc(pool, vid_conf->opt.max_slot_cnt * + sizeof(vconf_port*)); if (!vid_conf->ports) { - pjmedia_vid_conf_destroy(vid_conf); - return PJ_ENOMEM; + pjmedia_vid_conf_destroy(vid_conf); + return PJ_ENOMEM; } /* Create mutex */ status = pj_mutex_create_recursive(pool, CONF_NAME, &vid_conf->mutex); if (status != PJ_SUCCESS) { - pjmedia_vid_conf_destroy(vid_conf); - return status; + pjmedia_vid_conf_destroy(vid_conf); + return status; } /* Create clock */ @@ -292,18 +291,18 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_create( clock_param.clock_rate = TS_CLOCK_RATE; clock_param.usec_interval = 1000000 / vid_conf->opt.frame_rate; status = pjmedia_clock_create2(pool, &clock_param, 0, &on_clock_tick, - vid_conf, &vid_conf->clock); + vid_conf, &vid_conf->clock); if (status != PJ_SUCCESS) { - pjmedia_vid_conf_destroy(vid_conf); - return status; + pjmedia_vid_conf_destroy(vid_conf); + return status; } /* Allocate synchronized operation queues */ vid_conf->op_queue = PJ_POOL_ZALLOC_T(pool, op_entry); vid_conf->op_queue_free = PJ_POOL_ZALLOC_T(pool, op_entry); if (!vid_conf->op_queue || !vid_conf->op_queue_free) { - pjmedia_vid_conf_destroy(vid_conf); - return PJ_ENOMEM; + pjmedia_vid_conf_destroy(vid_conf); + return PJ_ENOMEM; } pj_list_init(vid_conf->op_queue); pj_list_init(vid_conf->op_queue_free); @@ -312,7 +311,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_create( *p_vid_conf = vid_conf; PJ_LOG(5,(THIS_FILE, "Created video conference bridge with %d ports", - vid_conf->opt.max_slot_cnt)); + vid_conf->opt.max_slot_cnt)); return PJ_SUCCESS; } @@ -331,28 +330,28 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_destroy(pjmedia_vid_conf *vid_conf) /* Destroy clock */ if (vid_conf->clock) { - pjmedia_clock_destroy(vid_conf->clock); - vid_conf->clock = NULL; + pjmedia_clock_destroy(vid_conf->clock); + vid_conf->clock = NULL; } /* Remove any registered ports (at least to cleanup their pool) */ for (i=0; i < vid_conf->opt.max_slot_cnt; ++i) { - if (vid_conf->ports[i]) { - op_param prm; - prm.remove_port.port = i; - op_remove_port(vid_conf, &prm); - } + if (vid_conf->ports[i]) { + op_param prm; + prm.remove_port.port = i; + op_remove_port(vid_conf, &prm); + } } /* Destroy mutex */ if (vid_conf->mutex) { - pj_mutex_destroy(vid_conf->mutex); - vid_conf->mutex = NULL; + pj_mutex_destroy(vid_conf->mutex); + vid_conf->mutex = NULL; } /* Release pool */ if (vid_conf->pool) { - pj_pool_safe_release(&vid_conf->pool); + pj_pool_safe_release(&vid_conf->pool); } PJ_LOG(5,(THIS_FILE, "Video conference bridge destroyed")); @@ -365,11 +364,11 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_destroy(pjmedia_vid_conf *vid_conf) * Add a media port to the video conference bridge. */ PJ_DEF(pj_status_t) pjmedia_vid_conf_add_port( pjmedia_vid_conf *vid_conf, - pj_pool_t *parent_pool, - pjmedia_port *port, - const pj_str_t *name, - void *opt, - unsigned *p_slot) + pj_pool_t *parent_pool, + pjmedia_port *port, + const pj_str_t *name, + void *opt, + unsigned *p_slot) { pj_pool_t *pool = NULL; vconf_port *cport = NULL; @@ -378,41 +377,41 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_add_port( pjmedia_vid_conf *vid_conf, PJ_ASSERT_RETURN(vid_conf && parent_pool && port, PJ_EINVAL); PJ_ASSERT_RETURN(port->info.fmt.type==PJMEDIA_TYPE_VIDEO && - port->info.fmt.detail_type==PJMEDIA_FORMAT_DETAIL_VIDEO, - PJ_EINVAL); + port->info.fmt.detail_type==PJMEDIA_FORMAT_DETAIL_VIDEO, + PJ_EINVAL); PJ_UNUSED_ARG(opt); /* If name is not specified, use the port's name */ if (!name) - name = &port->info.name; + name = &port->info.name; pj_mutex_lock(vid_conf->mutex); if (vid_conf->port_cnt >= vid_conf->opt.max_slot_cnt) { - pj_assert(!"Too many ports"); - pj_mutex_unlock(vid_conf->mutex); - return PJ_ETOOMANY; + pj_assert(!"Too many ports"); + pj_mutex_unlock(vid_conf->mutex); + return PJ_ETOOMANY; } /* Find empty port in the conference bridge. */ for (index=0; index < vid_conf->opt.max_slot_cnt; ++index) { - if (vid_conf->ports[index] == NULL) - break; + if (vid_conf->ports[index] == NULL) + break; } pj_assert(index != vid_conf->opt.max_slot_cnt); /* Create pool */ pool = pj_pool_create(parent_pool->factory, name->ptr, 500, 500, NULL); if (!pool) { - status = PJ_ENOMEM; - goto on_error; + status = PJ_ENOMEM; + goto on_error; } /* Create port. */ cport = PJ_POOL_ZALLOC_T(pool, vconf_port); if (!cport) { - status = PJ_ENOMEM; - goto on_error; + status = PJ_ENOMEM; + goto on_error; } /* Set pool, port, index, and name */ @@ -424,9 +423,9 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_add_port( pjmedia_vid_conf *vid_conf, /* Setup port's group lock if not yet */ if (!port->grp_lock) { - status = pjmedia_port_init_grp_lock(port, pool, NULL); - if (status != PJ_SUCCESS) - goto on_error; + status = pjmedia_port_init_grp_lock(port, pool, NULL); + if (status != PJ_SUCCESS) + goto on_error; } /* Increase port ref count */ @@ -434,115 +433,115 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_add_port( pjmedia_vid_conf *vid_conf, /* Init put/get_frame() intervals */ { - pjmedia_ratio *fps = &port->info.fmt.det.vid.fps; - pj_uint32_t vconf_interval = (pj_uint32_t) - (TS_CLOCK_RATE * 1.0 / - vid_conf->opt.frame_rate); - cport->ts_interval = (pj_uint32_t)(TS_CLOCK_RATE * 1.0 / - fps->num * fps->denum); - - /* Normalize the interval */ - if (cport->ts_interval < vconf_interval) { - cport->ts_interval = vconf_interval; - PJ_LOG(3,(THIS_FILE, "Warning: frame rate of port %s is higher " - "than video conference bridge (%d > %d)", - name->ptr, (int)(fps->num/fps->denum), - vid_conf->opt.frame_rate)); - } + pjmedia_ratio *fps = &port->info.fmt.det.vid.fps; + pj_uint32_t vconf_interval = (pj_uint32_t) + (TS_CLOCK_RATE * 1.0 / + vid_conf->opt.frame_rate); + cport->ts_interval = (pj_uint32_t)(TS_CLOCK_RATE * 1.0 / + fps->num * fps->denum); + + /* Normalize the interval */ + if (cport->ts_interval < vconf_interval) { + cport->ts_interval = vconf_interval; + PJ_LOG(3,(THIS_FILE, "Warning: frame rate of port %s is higher " + "than video conference bridge (%d > %d)", + name->ptr, (int)(fps->num/fps->denum), + vid_conf->opt.frame_rate)); + } } /* Allocate buffer for put/get_frame() */ { - const pjmedia_video_format_info *vfi; - pjmedia_video_apply_fmt_param vafp; - - vfi = pjmedia_get_video_format_info(NULL, port->info.fmt.id); - if (!vfi) { - PJ_LOG(4,(THIS_FILE, "pjmedia_vid_conf_add_port(): " - "unrecognized format %04X", - port->info.fmt.id)); - status = PJMEDIA_EBADFMT; - goto on_error; - } - - pj_bzero(&vafp, sizeof(vafp)); - vafp.size = port->info.fmt.det.vid.size; - status = (*vfi->apply_fmt)(vfi, &vafp); - if (status != PJ_SUCCESS) { - PJ_LOG(4,(THIS_FILE, "pjmedia_vid_conf_add_port(): " - "Failed to apply format %04X", - port->info.fmt.id)); - goto on_error; - } - if (port->put_frame) { - cport->put_buf_size = vafp.framebytes; - cport->put_buf = pj_pool_zalloc(cport->pool, cport->put_buf_size); - - /* Initialize sink buffer with black color. */ - status = pjmedia_video_format_fill_black(&port->info.fmt, - cport->put_buf, - cport->put_buf_size); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Warning: failed to init sink buffer " - " with black")); - } - } - if (port->get_frame) { - cport->get_buf_size = vafp.framebytes; - cport->get_buf = pj_pool_zalloc(cport->pool, cport->get_buf_size); - - /* Initialize source buffer with black color. */ - status = pjmedia_video_format_fill_black(&port->info.fmt, - cport->get_buf, - cport->get_buf_size); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Warning: failed to init source buffer " - "with black")); - } - } + const pjmedia_video_format_info *vfi; + pjmedia_video_apply_fmt_param vafp; + + vfi = pjmedia_get_video_format_info(NULL, port->info.fmt.id); + if (!vfi) { + PJ_LOG(4,(THIS_FILE, "pjmedia_vid_conf_add_port(): " + "unrecognized format %04X", + port->info.fmt.id)); + status = PJMEDIA_EBADFMT; + goto on_error; + } + + pj_bzero(&vafp, sizeof(vafp)); + vafp.size = port->info.fmt.det.vid.size; + status = (*vfi->apply_fmt)(vfi, &vafp); + if (status != PJ_SUCCESS) { + PJ_LOG(4,(THIS_FILE, "pjmedia_vid_conf_add_port(): " + "Failed to apply format %04X", + port->info.fmt.id)); + goto on_error; + } + if (port->put_frame) { + cport->put_buf_size = vafp.framebytes; + cport->put_buf = pj_pool_zalloc(cport->pool, cport->put_buf_size); + + /* Initialize sink buffer with black color. */ + status = pjmedia_video_format_fill_black(&port->info.fmt, + cport->put_buf, + cport->put_buf_size); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, + "Warning: failed to init sink buffer " + " with black")); + } + } + if (port->get_frame) { + cport->get_buf_size = vafp.framebytes; + cport->get_buf = pj_pool_zalloc(cport->pool, cport->get_buf_size); + + /* Initialize source buffer with black color. */ + status = pjmedia_video_format_fill_black(&port->info.fmt, + cport->get_buf, + cport->get_buf_size); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, + "Warning: failed to init source buffer " + "with black")); + } + } } /* Create listener array */ cport->listener_slots = (unsigned*) - pj_pool_zalloc(pool, - vid_conf->opt.max_slot_cnt * - sizeof(unsigned)); - if (!cport->listener_slots) { - status = PJ_ENOMEM; - goto on_error; + pj_pool_zalloc(pool, + vid_conf->opt.max_slot_cnt * + sizeof(unsigned)); + if (!cport->listener_slots) { + status = PJ_ENOMEM; + goto on_error; } /* Create transmitter array */ cport->transmitter_slots = (unsigned*) - pj_pool_zalloc(pool, - vid_conf->opt.max_slot_cnt * - sizeof(unsigned)); + pj_pool_zalloc(pool, + vid_conf->opt.max_slot_cnt * + sizeof(unsigned)); if (!cport->transmitter_slots) { - status = PJ_ENOMEM; - goto on_error; + status = PJ_ENOMEM; + goto on_error; } /* Create pointer-to-render_state array */ cport->render_states = (render_state**) - pj_pool_zalloc(pool, - vid_conf->opt.max_slot_cnt * - sizeof(render_state*)); + pj_pool_zalloc(pool, + vid_conf->opt.max_slot_cnt * + sizeof(render_state*)); if (!cport->render_states) { - status = PJ_ENOMEM; - goto on_error; + status = PJ_ENOMEM; + goto on_error; } /* Create pointer-to-render-pool array */ cport->render_pool = (pj_pool_t**) - pj_pool_zalloc(pool, - vid_conf->opt.max_slot_cnt * - sizeof(pj_pool_t*)); + pj_pool_zalloc(pool, + vid_conf->opt.max_slot_cnt * + sizeof(pj_pool_t*)); if (!cport->render_pool) { - status = PJ_ENOMEM; - goto on_error; + status = PJ_ENOMEM; + goto on_error; } /* Register the conf port. */ @@ -550,20 +549,20 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_add_port( pjmedia_vid_conf *vid_conf, vid_conf->port_cnt++; PJ_LOG(4,(THIS_FILE,"Added port %d (%.*s)", - index, (int)cport->name.slen, cport->name.ptr)); + index, (int)cport->name.slen, cport->name.ptr)); pj_mutex_unlock(vid_conf->mutex); /* Done. */ if (p_slot) { - *p_slot = index; + *p_slot = index; } return PJ_SUCCESS; on_error: if (pool) - pj_pool_release(pool); + pj_pool_release(pool); pj_mutex_unlock(vid_conf->mutex); return status; @@ -574,7 +573,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_add_port( pjmedia_vid_conf *vid_conf, * Remove a media port from the video conference bridge. */ PJ_DEF(pj_status_t) pjmedia_vid_conf_remove_port( pjmedia_vid_conf *vid_conf, - unsigned slot) + unsigned slot) { vconf_port *cport; op_entry *ope; @@ -586,8 +585,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_remove_port( pjmedia_vid_conf *vid_conf, /* Port must be valid. */ cport = vid_conf->ports[slot]; if (cport == NULL) { - pj_mutex_unlock(vid_conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(vid_conf->mutex); + return PJ_EINVAL; } PJ_LOG(5,(THIS_FILE, "Video port %d remove requested", slot)); @@ -605,7 +604,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_remove_port( pjmedia_vid_conf *vid_conf, static void op_remove_port(pjmedia_vid_conf *vid_conf, - const op_param *prm) + const op_param *prm) { unsigned slot = prm->remove_port.port; vconf_port *cport = vid_conf->ports[slot]; @@ -614,18 +613,18 @@ static void op_remove_port(pjmedia_vid_conf *vid_conf, /* Disconnect slot -> listeners */ while (cport->listener_cnt) { - op_param p; - p.disconnect_ports.src = slot; - p.disconnect_ports.sink = cport->listener_slots[0]; - op_disconnect_ports(vid_conf, &p); + op_param p; + p.disconnect_ports.src = slot; + p.disconnect_ports.sink = cport->listener_slots[0]; + op_disconnect_ports(vid_conf, &p); } /* Disconnect transmitters -> slot */ while (cport->transmitter_cnt) { - op_param p; - p.disconnect_ports.src = cport->transmitter_slots[0]; - p.disconnect_ports.sink = slot; - op_disconnect_ports(vid_conf, &p); + op_param p; + p.disconnect_ports.src = cport->transmitter_slots[0]; + p.disconnect_ports.sink = slot; + op_disconnect_ports(vid_conf, &p); } /* Remove the port. */ @@ -633,7 +632,7 @@ static void op_remove_port(pjmedia_vid_conf *vid_conf, --vid_conf->port_cnt; PJ_LOG(4,(THIS_FILE,"Removed port %d (%.*s)", - slot, (int)cport->name.slen, cport->name.ptr)); + slot, (int)cport->name.slen, cport->name.ptr)); /* Decrease port ref count */ pjmedia_port_dec_ref(cport->port); @@ -642,13 +641,13 @@ static void op_remove_port(pjmedia_vid_conf *vid_conf, pj_pool_safe_release(&cport->pool); if (AUTO_STOP_CLOCK && vid_conf->connect_cnt == 0) { - pj_status_t status; + pj_status_t status; - /* Warning: will stuck if this is called from the clock thread */ - status = pjmedia_clock_stop(vid_conf->clock); - if (status != PJ_SUCCESS) { - PJ_PERROR(4, (THIS_FILE, status, "Failed to stop clock")); - } + /* Warning: will stuck if this is called from the clock thread */ + status = pjmedia_clock_stop(vid_conf->clock); + if (status != PJ_SUCCESS) { + PJ_PERROR(4, (THIS_FILE, status, "Failed to stop clock")); + } } } @@ -665,8 +664,8 @@ PJ_DEF(unsigned) pjmedia_vid_conf_get_port_count(pjmedia_vid_conf *vid_conf) * Enumerate occupied slots in the video conference bridge. */ PJ_DEF(pj_status_t) pjmedia_vid_conf_enum_ports( pjmedia_vid_conf *vid_conf, - unsigned slots[], - unsigned *count) + unsigned slots[], + unsigned *count) { unsigned i, tmp_count=0; @@ -676,10 +675,10 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_enum_ports( pjmedia_vid_conf *vid_conf, pj_mutex_lock(vid_conf->mutex); for (i=0; iopt.max_slot_cnt && tmp_count<*count; ++i) { - if (!vid_conf->ports[i]) - continue; + if (!vid_conf->ports[i]) + continue; - slots[tmp_count++] = i; + slots[tmp_count++] = i; } /* Unlock mutex */ @@ -695,9 +694,9 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_enum_ports( pjmedia_vid_conf *vid_conf, * Get port info. */ PJ_DEF(pj_status_t) pjmedia_vid_conf_get_port_info( - pjmedia_vid_conf *vid_conf, - unsigned slot, - pjmedia_vid_conf_port_info *info) + pjmedia_vid_conf *vid_conf, + unsigned slot, + pjmedia_vid_conf_port_info *info) { vconf_port *cp; @@ -710,8 +709,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_get_port_info( /* Port must be valid. */ cp = vid_conf->ports[slot]; if (cp == NULL) { - pj_mutex_unlock(vid_conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(vid_conf->mutex); + return PJ_EINVAL; } info->slot = slot; @@ -734,18 +733,18 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_get_port_info( * the specified sink slot. */ PJ_DEF(pj_status_t) pjmedia_vid_conf_connect_port( - pjmedia_vid_conf *vid_conf, - unsigned src_slot, - unsigned sink_slot, - void *opt) + pjmedia_vid_conf *vid_conf, + unsigned src_slot, + unsigned sink_slot, + void *opt) { vconf_port *src_port, *dst_port; unsigned i; /* Check arguments */ PJ_ASSERT_RETURN(vid_conf && - src_slotopt.max_slot_cnt && - sink_slotopt.max_slot_cnt, PJ_EINVAL); + src_slotopt.max_slot_cnt && + sink_slotopt.max_slot_cnt, PJ_EINVAL); PJ_UNUSED_ARG(opt); pj_mutex_lock(vid_conf->mutex); @@ -754,43 +753,43 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_connect_port( src_port = vid_conf->ports[src_slot]; dst_port = vid_conf->ports[sink_slot]; if (!src_port || !src_port->port->get_frame || - !dst_port || !dst_port->port->put_frame) + !dst_port || !dst_port->port->put_frame) { - PJ_LOG(4,(THIS_FILE,"Failed connecting video ports, make sure that " - "source has get_frame() & sink has put_frame()")); - pj_mutex_unlock(vid_conf->mutex); - return PJ_EINVAL; + PJ_LOG(4,(THIS_FILE,"Failed connecting video ports, make sure that " + "source has get_frame() & sink has put_frame()")); + pj_mutex_unlock(vid_conf->mutex); + return PJ_EINVAL; } /* Check if connection has been made */ for (i=0; ilistener_cnt; ++i) { - if (src_port->listener_slots[i] == sink_slot) - break; + if (src_port->listener_slots[i] == sink_slot) + break; } /* Queue the operation */ if (i == src_port->listener_cnt) { - op_entry *ope; + op_entry *ope; - PJ_LOG(5,(THIS_FILE, "Video connect ports %d->%d requested", - src_slot, sink_slot)); + PJ_LOG(5,(THIS_FILE, "Video connect ports %d->%d requested", + src_slot, sink_slot)); - ope = get_free_op_entry(vid_conf); - ope->type = OP_CONNECT_PORTS; - ope->param.connect_ports.src = src_slot; - ope->param.connect_ports.sink = sink_slot; - pj_list_push_back(vid_conf->op_queue, ope); + ope = get_free_op_entry(vid_conf); + ope->type = OP_CONNECT_PORTS; + ope->param.connect_ports.src = src_slot; + ope->param.connect_ports.sink = sink_slot; + pj_list_push_back(vid_conf->op_queue, ope); } /* Start clock (if not yet) */ if (vid_conf->connect_cnt == 0) { - pj_status_t status; - status = pjmedia_clock_start(vid_conf->clock); - if (status != PJ_SUCCESS) { - PJ_PERROR(4, (THIS_FILE, status, "Failed to start clock")); - pj_mutex_unlock(vid_conf->mutex); - return status; - } + pj_status_t status; + status = pjmedia_clock_start(vid_conf->clock); + if (status != PJ_SUCCESS) { + PJ_PERROR(4, (THIS_FILE, status, "Failed to start clock")); + pj_mutex_unlock(vid_conf->mutex); + return status; + } } pj_mutex_unlock(vid_conf->mutex); @@ -799,7 +798,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_connect_port( } static void op_connect_ports(pjmedia_vid_conf *vid_conf, - const op_param *prm) + const op_param *prm) { unsigned src_slot, sink_slot; vconf_port *src_port, *dst_port; @@ -815,8 +814,8 @@ static void op_connect_ports(pjmedia_vid_conf *vid_conf, /* Check if connection has been made */ for (i=0; ilistener_cnt; ++i) { - if (src_port->listener_slots[i] == sink_slot) - return; + if (src_port->listener_slots[i] == sink_slot) + return; } /* Connect ports */ @@ -829,12 +828,12 @@ static void op_connect_ports(pjmedia_vid_conf *vid_conf, update_render_state(vid_conf, dst_port); PJ_LOG(4,(THIS_FILE,"Port %d (%.*s) transmitting to port %d (%.*s)", - src_slot, - (int)src_port->name.slen, - src_port->name.ptr, - sink_slot, - (int)dst_port->name.slen, - dst_port->name.ptr)); + src_slot, + (int)src_port->name.slen, + src_port->name.ptr, + sink_slot, + (int)dst_port->name.slen, + dst_port->name.ptr)); } /* @@ -842,17 +841,17 @@ static void op_connect_ports(pjmedia_vid_conf *vid_conf, * the specified sink slot. */ PJ_DEF(pj_status_t) pjmedia_vid_conf_disconnect_port( - pjmedia_vid_conf *vid_conf, - unsigned src_slot, - unsigned sink_slot) + pjmedia_vid_conf *vid_conf, + unsigned src_slot, + unsigned sink_slot) { vconf_port *src_port, *dst_port; unsigned i, j; /* Check arguments */ PJ_ASSERT_RETURN(vid_conf && - src_slotopt.max_slot_cnt && - sink_slotopt.max_slot_cnt, PJ_EINVAL); + src_slotopt.max_slot_cnt && + sink_slotopt.max_slot_cnt, PJ_EINVAL); pj_mutex_lock(vid_conf->mutex); @@ -860,39 +859,39 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_disconnect_port( src_port = vid_conf->ports[src_slot]; dst_port = vid_conf->ports[sink_slot]; if (!src_port || !dst_port) { - pj_mutex_unlock(vid_conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(vid_conf->mutex); + return PJ_EINVAL; } /* Check if connection has been made */ for (i=0; ilistener_cnt; ++i) { - if (src_port->listener_slots[i] == sink_slot) - break; + if (src_port->listener_slots[i] == sink_slot) + break; } for (j=0; jtransmitter_cnt; ++j) { - if (dst_port->transmitter_slots[j] == src_slot) - break; + if (dst_port->transmitter_slots[j] == src_slot) + break; } if (i != src_port->listener_cnt && j != dst_port->transmitter_cnt) { - pj_assert(src_port->listener_cnt > 0 && - src_port->listener_cnt < vid_conf->opt.max_slot_cnt); - pj_assert(dst_port->transmitter_cnt > 0 && - dst_port->transmitter_cnt < vid_conf->opt.max_slot_cnt); - - /* Queue the operation */ - if (i == src_port->listener_cnt) { - op_entry *ope; - - PJ_LOG(5,(THIS_FILE, "Video disconnect ports %d->%d requested", - src_slot, sink_slot)); - - ope = get_free_op_entry(vid_conf); - ope->type = OP_DISCONNECT_PORTS; - ope->param.disconnect_ports.src = src_slot; - ope->param.disconnect_ports.sink = sink_slot; - pj_list_push_back(vid_conf->op_queue, ope); - } + pj_assert(src_port->listener_cnt > 0 && + src_port->listener_cnt < vid_conf->opt.max_slot_cnt); + pj_assert(dst_port->transmitter_cnt > 0 && + dst_port->transmitter_cnt < vid_conf->opt.max_slot_cnt); + + /* Queue the operation */ + if (i == src_port->listener_cnt) { + op_entry *ope; + + PJ_LOG(5,(THIS_FILE, "Video disconnect ports %d->%d requested", + src_slot, sink_slot)); + + ope = get_free_op_entry(vid_conf); + ope->type = OP_DISCONNECT_PORTS; + ope->param.disconnect_ports.src = src_slot; + ope->param.disconnect_ports.sink = sink_slot; + pj_list_push_back(vid_conf->op_queue, ope); + } } pj_mutex_unlock(vid_conf->mutex); @@ -901,7 +900,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_disconnect_port( } static void op_disconnect_ports(pjmedia_vid_conf *vid_conf, - const op_param *prm) + const op_param *prm) { unsigned src_slot, sink_slot; vconf_port *src_port, *dst_port; @@ -916,33 +915,33 @@ static void op_disconnect_ports(pjmedia_vid_conf *vid_conf, /* Check if connection has been made */ for (i=0; ilistener_cnt; ++i) { - if (src_port->listener_slots[i] == sink_slot) - break; + if (src_port->listener_slots[i] == sink_slot) + break; } for (j=0; jtransmitter_cnt; ++j) { - if (dst_port->transmitter_slots[j] == src_slot) - break; + if (dst_port->transmitter_slots[j] == src_slot) + break; } if (i == src_port->listener_cnt || j == dst_port->transmitter_cnt) - return; + return; pj_assert(src_port->listener_cnt > 0 && - src_port->listener_cnt < vid_conf->opt.max_slot_cnt); + src_port->listener_cnt < vid_conf->opt.max_slot_cnt); pj_assert(dst_port->transmitter_cnt > 0 && - dst_port->transmitter_cnt < vid_conf->opt.max_slot_cnt); + dst_port->transmitter_cnt < vid_conf->opt.max_slot_cnt); /* Cleanup all render states of the sink */ for (k=0; ktransmitter_cnt; ++k) - cleanup_render_state(dst_port, k); + cleanup_render_state(dst_port, k); /* Update listeners array of the source and transmitters array of * the sink. */ pj_array_erase(src_port->listener_slots, sizeof(unsigned), - src_port->listener_cnt, i); + src_port->listener_cnt, i); pj_array_erase(dst_port->transmitter_slots, sizeof(unsigned), - dst_port->transmitter_cnt, j); + dst_port->transmitter_cnt, j); --src_port->listener_cnt; --dst_port->transmitter_cnt; @@ -952,23 +951,23 @@ static void op_disconnect_ports(pjmedia_vid_conf *vid_conf, --vid_conf->connect_cnt; if (AUTO_STOP_CLOCK && vid_conf->connect_cnt == 0) { - pj_status_t status; - /* Warning: will stuck if this is called from the clock thread */ - status = pjmedia_clock_stop(vid_conf->clock); - if (status != PJ_SUCCESS) { - PJ_PERROR(4, (THIS_FILE, status, "Failed to stop clock")); - return; - } + pj_status_t status; + /* Warning: will stuck if this is called from the clock thread */ + status = pjmedia_clock_stop(vid_conf->clock); + if (status != PJ_SUCCESS) { + PJ_PERROR(4, (THIS_FILE, status, "Failed to stop clock")); + return; + } } PJ_LOG(4,(THIS_FILE, - "Port %d (%.*s) stop transmitting to port %d (%.*s)", - src_slot, - (int)src_port->name.slen, - src_port->name.ptr, - sink_slot, - (int)dst_port->name.slen, - dst_port->name.ptr)); + "Port %d (%.*s) stop transmitting to port %d (%.*s)", + src_slot, + (int)src_port->name.slen, + src_port->name.ptr, + sink_slot, + (int)dst_port->name.slen, + dst_port->name.ptr)); } @@ -980,7 +979,7 @@ static void op_disconnect_ports(pjmedia_vid_conf *vid_conf, static int cmp_fps(const pjmedia_format *fmt1, const pjmedia_format *fmt2) { return (fmt1->det.vid.fps.num != fmt2->det.vid.fps.num || - fmt1->det.vid.fps.denum != fmt2->det.vid.fps.denum); + fmt1->det.vid.fps.denum != fmt2->det.vid.fps.denum); } @@ -989,8 +988,8 @@ static int cmp_size(const pjmedia_format *fmt1, const pjmedia_format *fmt2) { /* Note that format ID changes may cause buffer size change */ return (fmt1->id != fmt2->id || - fmt1->det.vid.size.w != fmt2->det.vid.size.w || - fmt1->det.vid.size.h != fmt2->det.vid.size.h); + fmt1->det.vid.size.w != fmt2->det.vid.size.w || + fmt1->det.vid.size.h != fmt2->det.vid.size.h); } @@ -1006,9 +1005,9 @@ static void on_clock_tick(const pj_timestamp *now, void *user_data) * the clock such as connect, disonnect, remove, update. */ if (!pj_list_empty(vid_conf->op_queue)) { - pj_mutex_lock(vid_conf->mutex); - handle_op_queue(vid_conf); - pj_mutex_unlock(vid_conf->mutex); + pj_mutex_lock(vid_conf->mutex); + handle_op_queue(vid_conf); + pj_mutex_unlock(vid_conf->mutex); } /* No mutex from this point! Otherwise it may cause deadlock as @@ -1022,151 +1021,151 @@ static void on_clock_tick(const pj_timestamp *now, void *user_data) /* Iterate all (sink) ports */ for (i=0, ci=0; iopt.max_slot_cnt && - ciport_cnt; ++i) + ciport_cnt; ++i) { - unsigned j; - pj_bool_t frame_rendered = PJ_FALSE; - pj_bool_t ts_incremented = PJ_FALSE; - vconf_port *sink = vid_conf->ports[i]; - pjmedia_format *cur_fmt, *new_fmt; - - /* Skip empty port */ - if (!sink) - continue; - - /* Increment occupied port counter */ - ++ci; - - /* Skip non-sink port */ - if (!sink->port->put_frame) - continue; - - if (sink->ts_next.u64 == 0) - sink->ts_next = *now; - - /* Skip if too early for put_frame(), note: - * early = (now < ts_next) - * But careful for timestamp wrapped around. - */ - ts_diff = pj_timestamp_diff32(&sink->ts_next, now); - if (ts_diff < 0 || ts_diff > TS_CLOCK_RATE) - continue; - - /* There is a possibility that the sink port's format has - * changed, but we haven't received the event yet. - */ - cur_fmt = &sink->format; - new_fmt = &sink->port->info.fmt; - if (cmp_fps(cur_fmt, new_fmt) || cmp_size(cur_fmt, new_fmt)) { - op_param prm; - prm.update_port.port = sink->idx; - op_update_port(vid_conf, &prm); - } - - /* Iterate transmitters of this sink port */ - for (j=0; j < sink->transmitter_cnt; ++j) { - vconf_port *src = vid_conf->ports[sink->transmitter_slots[j]]; - pj_int32_t src_ts_diff; - - if (src->ts_next.u64 == 0) - src->ts_next = *now; - - /* Is it time for src->get_frame()? yes, if (now >= ts_next) */ - src_ts_diff = pj_timestamp_diff32(&src->ts_next, now); - if (src_ts_diff >= 0) { - - /* Call src->get_frame(). - * Possible optimization: if this src only has one listener, - * perhaps we can skip this src buffer and directly render it - * to sink buffer (but still need buffer if conversion any). - */ - pj_bzero(&frame, sizeof(frame)); - frame.type = PJMEDIA_FRAME_TYPE_VIDEO; - frame.timestamp = *now; - frame.buf = src->get_buf; - frame.size = src->get_buf_size; - status = pjmedia_port_get_frame(src->port, &frame); - if (status != PJ_SUCCESS) { - PJ_PERROR(5, (THIS_FILE, status, - "Failed to get frame from port %d [%s]!", - src->idx, src->port->info.name.ptr)); - src->got_frame = PJ_FALSE; - } else { - src->got_frame = (frame.size == src->get_buf_size); - - /* There is a possibility that the source port's format has - * changed, but we haven't received the event yet. - */ - cur_fmt = &src->format; - new_fmt = &src->port->info.fmt; - if (cmp_fps(cur_fmt, new_fmt) || - cmp_size(cur_fmt, new_fmt)) - { - op_param prm; - prm.update_port.port = src->idx; - op_update_port(vid_conf, &prm); - } - } - - /* Update next src put/get */ - pj_add_timestamp32(&src->ts_next, src->ts_interval); - ts_incremented = src==sink; - } - - if (src->got_frame) { - /* Render src get buffer to sink put buffer (based on - * sink layout settings, if any) - */ - status = render_src_frame(src, sink, j); - if (status == PJ_SUCCESS) { - frame_rendered = PJ_TRUE; - } else { - PJ_PERROR(5, (THIS_FILE, status, - "Failed to render frame from port %d [%s] " - "to port %d [%s]", - src->idx, src->port->info.name.ptr, - sink->idx, sink->port->info.name.ptr)); - } - } - } - - /* Call sink->put_frame() - * Note that if transmitter_cnt==0, we should still call put_frame() - * with zero frame size, as sink may need to send keep-alive packets - * and get timestamp update. - */ - pj_bzero(&frame, sizeof(frame)); - frame.type = PJMEDIA_FRAME_TYPE_VIDEO; - frame.timestamp = *now; - if (frame_rendered) { - frame.buf = sink->put_buf; - frame.size = sink->put_buf_size; - } - status = pjmedia_port_put_frame(sink->port, &frame); - if (frame_rendered && status != PJ_SUCCESS) { - sink->last_err_cnt++; - if (sink->last_err != status || - sink->last_err_cnt % MAX_ERR_COUNT == 0) - { - if (sink->last_err != status) - sink->last_err_cnt = 1; - sink->last_err = status; - PJ_PERROR(5, (THIS_FILE, status, - "Failed (%d time(s)) to put frame to port %d" - " [%s]!", sink->last_err_cnt, - sink->idx, sink->port->info.name.ptr)); - } - } else { - sink->last_err = status; - sink->last_err_cnt = 0; - } - - /* Update next put/get, careful that it may have been updated - * if this port transmits to itself! - */ - if (!ts_incremented) { - pj_add_timestamp32(&sink->ts_next, sink->ts_interval); - } + unsigned j; + pj_bool_t frame_rendered = PJ_FALSE; + pj_bool_t ts_incremented = PJ_FALSE; + vconf_port *sink = vid_conf->ports[i]; + pjmedia_format *cur_fmt, *new_fmt; + + /* Skip empty port */ + if (!sink) + continue; + + /* Increment occupied port counter */ + ++ci; + + /* Skip non-sink port */ + if (!sink->port->put_frame) + continue; + + if (sink->ts_next.u64 == 0) + sink->ts_next = *now; + + /* Skip if too early for put_frame(), note: + * early = (now < ts_next) + * But careful for timestamp wrapped around. + */ + ts_diff = pj_timestamp_diff32(&sink->ts_next, now); + if (ts_diff < 0 || ts_diff > TS_CLOCK_RATE) + continue; + + /* There is a possibility that the sink port's format has + * changed, but we haven't received the event yet. + */ + cur_fmt = &sink->format; + new_fmt = &sink->port->info.fmt; + if (cmp_fps(cur_fmt, new_fmt) || cmp_size(cur_fmt, new_fmt)) { + op_param prm; + prm.update_port.port = sink->idx; + op_update_port(vid_conf, &prm); + } + + /* Iterate transmitters of this sink port */ + for (j=0; j < sink->transmitter_cnt; ++j) { + vconf_port *src = vid_conf->ports[sink->transmitter_slots[j]]; + pj_int32_t src_ts_diff; + + if (src->ts_next.u64 == 0) + src->ts_next = *now; + + /* Is it time for src->get_frame()? yes, if (now >= ts_next) */ + src_ts_diff = pj_timestamp_diff32(&src->ts_next, now); + if (src_ts_diff >= 0) { + + /* Call src->get_frame(). + * Possible optimization: if this src only has one listener, + * perhaps we can skip this src buffer and directly render it + * to sink buffer (but still need buffer if conversion any). + */ + pj_bzero(&frame, sizeof(frame)); + frame.type = PJMEDIA_FRAME_TYPE_VIDEO; + frame.timestamp = *now; + frame.buf = src->get_buf; + frame.size = src->get_buf_size; + status = pjmedia_port_get_frame(src->port, &frame); + if (status != PJ_SUCCESS) { + PJ_PERROR(5, (THIS_FILE, status, + "Failed to get frame from port %d [%s]!", + src->idx, src->port->info.name.ptr)); + src->got_frame = PJ_FALSE; + } else { + src->got_frame = (frame.size == src->get_buf_size); + + /* There is a possibility that the source port's format has + * changed, but we haven't received the event yet. + */ + cur_fmt = &src->format; + new_fmt = &src->port->info.fmt; + if (cmp_fps(cur_fmt, new_fmt) || + cmp_size(cur_fmt, new_fmt)) + { + op_param prm; + prm.update_port.port = src->idx; + op_update_port(vid_conf, &prm); + } + } + + /* Update next src put/get */ + pj_add_timestamp32(&src->ts_next, src->ts_interval); + ts_incremented = src==sink; + } + + if (src->got_frame) { + /* Render src get buffer to sink put buffer (based on + * sink layout settings, if any) + */ + status = render_src_frame(src, sink, j); + if (status == PJ_SUCCESS) { + frame_rendered = PJ_TRUE; + } else { + PJ_PERROR(5, (THIS_FILE, status, + "Failed to render frame from port %d [%s] " + "to port %d [%s]", + src->idx, src->port->info.name.ptr, + sink->idx, sink->port->info.name.ptr)); + } + } + } + + /* Call sink->put_frame() + * Note that if transmitter_cnt==0, we should still call put_frame() + * with zero frame size, as sink may need to send keep-alive packets + * and get timestamp update. + */ + pj_bzero(&frame, sizeof(frame)); + frame.type = PJMEDIA_FRAME_TYPE_VIDEO; + frame.timestamp = *now; + if (frame_rendered) { + frame.buf = sink->put_buf; + frame.size = sink->put_buf_size; + } + status = pjmedia_port_put_frame(sink->port, &frame); + if (frame_rendered && status != PJ_SUCCESS) { + sink->last_err_cnt++; + if (sink->last_err != status || + sink->last_err_cnt % MAX_ERR_COUNT == 0) + { + if (sink->last_err != status) + sink->last_err_cnt = 1; + sink->last_err = status; + PJ_PERROR(5, (THIS_FILE, status, + "Failed (%d time(s)) to put frame to port %d" + " [%s]!", sink->last_err_cnt, + sink->idx, sink->port->info.name.ptr)); + } + } else { + sink->last_err = status; + sink->last_err_cnt = 0; + } + + /* Update next put/get, careful that it may have been updated + * if this port transmits to itself! + */ + if (!ts_incremented) { + pj_add_timestamp32(&sink->ts_next, sink->ts_interval); + } } } @@ -1179,7 +1178,7 @@ static pj_bool_t is_landscape(const pjmedia_rect_size *size) { * expanded). */ static void match_ratio_crop(pjmedia_rect_size *size, - const pjmedia_rect_size *ref_size) + const pjmedia_rect_size *ref_size) { pjmedia_rect_size res; @@ -1189,8 +1188,8 @@ static void match_ratio_crop(pjmedia_rect_size *size, /* If original height turns out to be shorther, match height */ if (size->h < res.h) { - res.w = ref_size->w * size->h / ref_size->h; - res.h = size->h; + res.w = ref_size->w * size->h / ref_size->h; + res.h = size->h; } *size = res; @@ -1202,21 +1201,21 @@ static void match_ratio_crop(pjmedia_rect_size *size, * when new connection has just been made. */ static void cleanup_render_state(vconf_port *cp, - unsigned transmitter_idx) + unsigned transmitter_idx) { render_state *rs = cp->render_states[transmitter_idx]; if (rs && rs->converter) { - pjmedia_converter_destroy(rs->converter); - rs->converter = NULL; + pjmedia_converter_destroy(rs->converter); + rs->converter = NULL; } cp->render_states[transmitter_idx] = NULL; if (cp->render_pool[transmitter_idx]) { - pj_pool_safe_release(&cp->render_pool[transmitter_idx]); + pj_pool_safe_release(&cp->render_pool[transmitter_idx]); - TRACE_((THIS_FILE, "Cleaned up render state for connection %d->%d", - cp->transmitter_slots[transmitter_idx], cp->idx)); + TRACE_((THIS_FILE, "Cleaned up render state for connection %d->%d", + cp->transmitter_slots[transmitter_idx], cp->idx)); } } @@ -1240,20 +1239,20 @@ static void update_render_state(pjmedia_vid_conf *vid_conf, vconf_port *cp) /* Nothing to render, just return */ if (cp->transmitter_cnt == 0) - return; + return; TRACE_((THIS_FILE, "Updating render state for port id %d (%d sources)..", - cp->idx, cp->transmitter_cnt)); + cp->idx, cp->transmitter_cnt)); for (i = 0; i < cp->transmitter_cnt; ++i) { - vconf_port *tr = vid_conf->ports[cp->transmitter_slots[i]]; + vconf_port *tr = vid_conf->ports[cp->transmitter_slots[i]]; - /* Cleanup render states & pool */ - cleanup_render_state(cp, i); + /* Cleanup render states & pool */ + cleanup_render_state(cp, i); - /* Gather format ID, size of each transmitter */ - tr_fmt_id[i] = tr->port->info.fmt.id; - tr_size[i] = tr->port->info.fmt.det.vid.size; + /* Gather format ID, size of each transmitter */ + tr_fmt_id[i] = tr->port->info.fmt.id; + tr_size[i] = tr->port->info.fmt.det.vid.size; } /* If only one transmitter and it has matched format & size, just use @@ -1261,156 +1260,156 @@ static void update_render_state(pjmedia_vid_conf *vid_conf, vconf_port *cp) * have matched format & size with its source. */ if (cp->transmitter_cnt == 1 && fmt_id == tr_fmt_id[0] && - size.w == tr_size[0].w && size.h == tr_size[0].h) + size.w == tr_size[0].w && size.h == tr_size[0].h) { - TRACE_((THIS_FILE, "This port only has single source with " - "matched format & size, no conversion needed")); - return; + TRACE_((THIS_FILE, "This port only has single source with " + "matched format & size, no conversion needed")); + return; } for (i = 0; i < cp->transmitter_cnt && i < 4; ++i) { - pj_pool_t *pool; - render_state *rs; - pjmedia_conversion_param cparam; - char tmp_buf[32]; - - /* Create pool & render state */ - pj_ansi_snprintf(tmp_buf, sizeof(tmp_buf), "vcport_rs_%d->%d", - cp->transmitter_slots[i], cp->idx); - pool = pj_pool_create(cp->pool->factory, tmp_buf, 128, 128, NULL); - cp->render_pool[i] = pool; - rs = cp->render_states[i] = PJ_POOL_ZALLOC_T(pool, render_state); - - TRACE_((THIS_FILE, "Created render state for connection %d->%d", - cp->transmitter_slots[i], cp->idx)); - - /* Setup format & frame */ - rs->src_fmt_id = tr_fmt_id[i]; - rs->dst_fmt_id = fmt_id; - rs->src_frame_size = tr_size[i]; - rs->dst_frame_size = size; - - /* For now, draw the whole source frame, will adjust ratio later */ - rs->src_rect.coord.x = rs->src_rect.coord.y = 0; - rs->src_rect.size = tr_size[i]; - - /* Setup layout */ - if (cp->transmitter_cnt == 1) { - rs->dst_rect.coord.x = rs->dst_rect.coord.y = 0; - rs->dst_rect.size = size; - } else if (cp->transmitter_cnt == 2) { - if (is_landscape(&size)) { - /* - * | - * Source 0 | Source 1 - * | - */ - rs->dst_rect.coord.x = i * (size.w/2); - rs->dst_rect.coord.y = 0; - rs->dst_rect.size.w = size.w / 2; - rs->dst_rect.size.h = size.h; - } else { - /* - * Source 0 - * -------- - * Source 1 - */ - rs->dst_rect.coord.x = 0; - rs->dst_rect.coord.y = i * (size.h/2); - rs->dst_rect.size.w = size.w; - rs->dst_rect.size.h = size.h / 2; - } - } else if (cp->transmitter_cnt == 3) { - if (is_landscape(&size)) { - /* - * | Source 1 - * Source 0 |--------- - * | Source 2 - */ - rs->dst_rect.coord.x = (i==0)? 0 : size.w/2; - rs->dst_rect.coord.y = (i!=2)? 0 : size.h/2; - rs->dst_rect.size.w = size.w / 2; - rs->dst_rect.size.h = (i==0)? size.h : size.h/2; - } else { - /* - * Source 0 - * -------- - * Source 1 - * -------- - * Source 2 - */ - rs->dst_rect.coord.x = 0; - rs->dst_rect.coord.y = i * size.h/3; - rs->dst_rect.size.w = size.w; - rs->dst_rect.size.h = size.h/3; - } - } else if (cp->transmitter_cnt == 4) { - if (is_landscape(&size)) { - /* - * Source 0 | Source 1 - * ---------|--------- - * Source 2 | Source 3 - */ - rs->dst_rect.coord.x = (i%2==0)? 0 : size.w/2; - rs->dst_rect.coord.y = (i/2==0)? 0 : size.h/2; - rs->dst_rect.size.w = size.w/2; - rs->dst_rect.size.h = size.h/2; - } else { - /* - * Source 0 - * -------- - * Source 1 - * -------- - * Source 2 - * -------- - * Source 3 - */ - rs->dst_rect.coord.x = 0; - rs->dst_rect.coord.y = i * size.h/4; - rs->dst_rect.size.w = size.w; - rs->dst_rect.size.h = size.h/4; - } - } - - /* Adjust source size to match aspect ratio of rendering space. */ - match_ratio_crop(&rs->src_rect.size, &rs->dst_rect.size); - - /* Now adjust source position after source size adjustment. */ - if (rs->src_rect.size.w < tr_size[i].w) - rs->src_rect.coord.x = (tr_size[i].w - rs->src_rect.size.w)/2; - if (rs->src_rect.size.h < tr_size[i].h) - rs->src_rect.coord.y = (tr_size[i].h - rs->src_rect.size.h)/2; - - TRACE_((THIS_FILE, "src#%d=%s/%dx%d->%dx%d@%d,%d dst=%dx%d@%d,%d", - i, pjmedia_fourcc_name(tr_fmt_id[i], tmp_buf), - tr_size[i].w, tr_size[i].h, - rs->src_rect.size.w, rs->src_rect.size.h, - rs->src_rect.coord.x, rs->src_rect.coord.y, - rs->dst_rect.size.w, rs->dst_rect.size.h, - rs->dst_rect.coord.x, rs->dst_rect.coord.y)); - - /* Create converter */ - pjmedia_format_init_video(&cparam.src, rs->src_fmt_id, - rs->src_rect.size.w, - rs->src_rect.size.h, - 0, 1); - pjmedia_format_init_video(&cparam.dst, rs->dst_fmt_id, - rs->dst_rect.size.w, - rs->dst_rect.size.h, - 0, 1); - status = pjmedia_converter_create(NULL, pool, &cparam, - &rs->converter); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Port %d failed creating converter " - "for source %d", cp->idx, i)); - } + pj_pool_t *pool; + render_state *rs; + pjmedia_conversion_param cparam; + char tmp_buf[32]; + + /* Create pool & render state */ + pj_ansi_snprintf(tmp_buf, sizeof(tmp_buf), "vcport_rs_%d->%d", + cp->transmitter_slots[i], cp->idx); + pool = pj_pool_create(cp->pool->factory, tmp_buf, 128, 128, NULL); + cp->render_pool[i] = pool; + rs = cp->render_states[i] = PJ_POOL_ZALLOC_T(pool, render_state); + + TRACE_((THIS_FILE, "Created render state for connection %d->%d", + cp->transmitter_slots[i], cp->idx)); + + /* Setup format & frame */ + rs->src_fmt_id = tr_fmt_id[i]; + rs->dst_fmt_id = fmt_id; + rs->src_frame_size = tr_size[i]; + rs->dst_frame_size = size; + + /* For now, draw the whole source frame, will adjust ratio later */ + rs->src_rect.coord.x = rs->src_rect.coord.y = 0; + rs->src_rect.size = tr_size[i]; + + /* Setup layout */ + if (cp->transmitter_cnt == 1) { + rs->dst_rect.coord.x = rs->dst_rect.coord.y = 0; + rs->dst_rect.size = size; + } else if (cp->transmitter_cnt == 2) { + if (is_landscape(&size)) { + /* + * | + * Source 0 | Source 1 + * | + */ + rs->dst_rect.coord.x = i * (size.w/2); + rs->dst_rect.coord.y = 0; + rs->dst_rect.size.w = size.w / 2; + rs->dst_rect.size.h = size.h; + } else { + /* + * Source 0 + * -------- + * Source 1 + */ + rs->dst_rect.coord.x = 0; + rs->dst_rect.coord.y = i * (size.h/2); + rs->dst_rect.size.w = size.w; + rs->dst_rect.size.h = size.h / 2; + } + } else if (cp->transmitter_cnt == 3) { + if (is_landscape(&size)) { + /* + * | Source 1 + * Source 0 |--------- + * | Source 2 + */ + rs->dst_rect.coord.x = (i==0)? 0 : size.w/2; + rs->dst_rect.coord.y = (i!=2)? 0 : size.h/2; + rs->dst_rect.size.w = size.w / 2; + rs->dst_rect.size.h = (i==0)? size.h : size.h/2; + } else { + /* + * Source 0 + * -------- + * Source 1 + * -------- + * Source 2 + */ + rs->dst_rect.coord.x = 0; + rs->dst_rect.coord.y = i * size.h/3; + rs->dst_rect.size.w = size.w; + rs->dst_rect.size.h = size.h/3; + } + } else if (cp->transmitter_cnt == 4) { + if (is_landscape(&size)) { + /* + * Source 0 | Source 1 + * ---------|--------- + * Source 2 | Source 3 + */ + rs->dst_rect.coord.x = (i%2==0)? 0 : size.w/2; + rs->dst_rect.coord.y = (i/2==0)? 0 : size.h/2; + rs->dst_rect.size.w = size.w/2; + rs->dst_rect.size.h = size.h/2; + } else { + /* + * Source 0 + * -------- + * Source 1 + * -------- + * Source 2 + * -------- + * Source 3 + */ + rs->dst_rect.coord.x = 0; + rs->dst_rect.coord.y = i * size.h/4; + rs->dst_rect.size.w = size.w; + rs->dst_rect.size.h = size.h/4; + } + } + + /* Adjust source size to match aspect ratio of rendering space. */ + match_ratio_crop(&rs->src_rect.size, &rs->dst_rect.size); + + /* Now adjust source position after source size adjustment. */ + if (rs->src_rect.size.w < tr_size[i].w) + rs->src_rect.coord.x = (tr_size[i].w - rs->src_rect.size.w)/2; + if (rs->src_rect.size.h < tr_size[i].h) + rs->src_rect.coord.y = (tr_size[i].h - rs->src_rect.size.h)/2; + + TRACE_((THIS_FILE, "src#%d=%s/%dx%d->%dx%d@%d,%d dst=%dx%d@%d,%d", + i, pjmedia_fourcc_name(tr_fmt_id[i], tmp_buf), + tr_size[i].w, tr_size[i].h, + rs->src_rect.size.w, rs->src_rect.size.h, + rs->src_rect.coord.x, rs->src_rect.coord.y, + rs->dst_rect.size.w, rs->dst_rect.size.h, + rs->dst_rect.coord.x, rs->dst_rect.coord.y)); + + /* Create converter */ + pjmedia_format_init_video(&cparam.src, rs->src_fmt_id, + rs->src_rect.size.w, + rs->src_rect.size.h, + 0, 1); + pjmedia_format_init_video(&cparam.dst, rs->dst_fmt_id, + rs->dst_rect.size.w, + rs->dst_rect.size.h, + 0, 1); + status = pjmedia_converter_create(NULL, pool, &cparam, + &rs->converter); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, + "Port %d failed creating converter " + "for source %d", cp->idx, i)); + } } } /* Render frame from source to sink buffer based on rendering settings. */ static pj_status_t render_src_frame(vconf_port *src, vconf_port *sink, - unsigned transmitter_idx) + unsigned transmitter_idx) { pj_status_t status; render_state *rs = sink->render_states[transmitter_idx]; @@ -1419,42 +1418,42 @@ static pj_status_t render_src_frame(vconf_port *src, vconf_port *sink, * changed, but we haven't received the event yet. */ if (pj_memcmp(&sink->format, &sink->port->info.fmt, - sizeof(pjmedia_format))) + sizeof(pjmedia_format))) { - return PJMEDIA_EVID_BADFORMAT; + return PJMEDIA_EVID_BADFORMAT; } if (sink->transmitter_cnt == 1 && (!rs || !rs->converter)) { - /* The only transmitter and no conversion needed */ - if (src->get_buf_size != sink->put_buf_size) - return PJMEDIA_EVID_BADFORMAT; - pj_memcpy(sink->put_buf, src->get_buf, src->get_buf_size); + /* The only transmitter and no conversion needed */ + if (src->get_buf_size != sink->put_buf_size) + return PJMEDIA_EVID_BADFORMAT; + pj_memcpy(sink->put_buf, src->get_buf, src->get_buf_size); } else if (rs && rs->converter) { - pjmedia_frame src_frame, dst_frame; - - pj_bzero(&src_frame, sizeof(src_frame)); - src_frame.buf = src->get_buf; - src_frame.size = src->get_buf_size; - - pj_bzero(&dst_frame, sizeof(dst_frame)); - dst_frame.buf = sink->put_buf; - dst_frame.size = sink->put_buf_size; - - status = pjmedia_converter_convert2(rs->converter, - &src_frame, - &rs->src_frame_size, - &rs->src_rect.coord, - &dst_frame, - &rs->dst_frame_size, - &rs->dst_rect.coord, - NULL); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Port id %d: converter failed in " - "rendering frame from port id %d", - sink->idx, transmitter_idx)); - return status; - } + pjmedia_frame src_frame, dst_frame; + + pj_bzero(&src_frame, sizeof(src_frame)); + src_frame.buf = src->get_buf; + src_frame.size = src->get_buf_size; + + pj_bzero(&dst_frame, sizeof(dst_frame)); + dst_frame.buf = sink->put_buf; + dst_frame.size = sink->put_buf_size; + + status = pjmedia_converter_convert2(rs->converter, + &src_frame, + &rs->src_frame_size, + &rs->src_rect.coord, + &dst_frame, + &rs->dst_frame_size, + &rs->dst_rect.coord, + NULL); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, + "Port id %d: converter failed in " + "rendering frame from port id %d", + sink->idx, transmitter_idx)); + return status; + } } return PJ_SUCCESS; @@ -1463,7 +1462,7 @@ static pj_status_t render_src_frame(vconf_port *src, vconf_port *sink, /* Update or refresh port states from video port info. */ PJ_DEF(pj_status_t) pjmedia_vid_conf_update_port( pjmedia_vid_conf *vid_conf, - unsigned slot) + unsigned slot) { vconf_port *cport; op_entry *ope; @@ -1475,8 +1474,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_update_port( pjmedia_vid_conf *vid_conf, /* Port must be valid. */ cport = vid_conf->ports[slot]; if (cport == NULL) { - pj_mutex_unlock(vid_conf->mutex); - return PJ_EINVAL; + pj_mutex_unlock(vid_conf->mutex); + return PJ_EINVAL; } /* Queue the operation */ @@ -1492,7 +1491,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_conf_update_port( pjmedia_vid_conf *vid_conf, static void op_update_port(pjmedia_vid_conf *vid_conf, - const op_param *prm) + const op_param *prm) { unsigned slot = prm->update_port.port; vconf_port *cport = vid_conf->ports[slot]; @@ -1509,96 +1508,96 @@ static void op_update_port(pjmedia_vid_conf *vid_conf, /* Update put/get_frame() intervals */ if (cmp_fps(new_fmt, old_fmt)) { - pjmedia_ratio *fps = &new_fmt->det.vid.fps; - pj_uint32_t vconf_interval = (pj_uint32_t) - (TS_CLOCK_RATE * 1.0 / - vid_conf->opt.frame_rate); - cport->ts_interval = (pj_uint32_t)(TS_CLOCK_RATE * 1.0 / - fps->num * fps->denum); - - /* Normalize the interval */ - if (cport->ts_interval < vconf_interval) { - cport->ts_interval = vconf_interval; - PJ_LOG(3,(THIS_FILE, "Warning: frame rate of port %s is higher " - "than video conference bridge (%d > %d)", - cport->name.ptr, (int)(fps->num/fps->denum), - vid_conf->opt.frame_rate)); - } - - PJ_LOG(4,(THIS_FILE, - "Port %d (%s): updated frame rate %d -> %d", - slot, cport->name.ptr, - (int)(old_fmt->det.vid.fps.num/old_fmt->det.vid.fps.denum), - (int)(fps->num/fps->denum))); + pjmedia_ratio *fps = &new_fmt->det.vid.fps; + pj_uint32_t vconf_interval = (pj_uint32_t) + (TS_CLOCK_RATE * 1.0 / + vid_conf->opt.frame_rate); + cport->ts_interval = (pj_uint32_t)(TS_CLOCK_RATE * 1.0 / + fps->num * fps->denum); + + /* Normalize the interval */ + if (cport->ts_interval < vconf_interval) { + cport->ts_interval = vconf_interval; + PJ_LOG(3,(THIS_FILE, "Warning: frame rate of port %s is higher " + "than video conference bridge (%d > %d)", + cport->name.ptr, (int)(fps->num/fps->denum), + vid_conf->opt.frame_rate)); + } + + PJ_LOG(4,(THIS_FILE, + "Port %d (%s): updated frame rate %d -> %d", + slot, cport->name.ptr, + (int)(old_fmt->det.vid.fps.num/old_fmt->det.vid.fps.denum), + (int)(fps->num/fps->denum))); } /* Update buffer for put/get_frame() */ if (cmp_size(new_fmt, old_fmt)) { - const pjmedia_video_format_info *vfi; - pjmedia_video_apply_fmt_param vafp; - pj_status_t status; - unsigned i; - - vfi = pjmedia_get_video_format_info(NULL, new_fmt->id); - if (!vfi) { - PJ_LOG(1,(THIS_FILE, "pjmedia_vid_conf_update_port(): " - "unrecognized format %04X", - new_fmt->id)); - return; - } - - pj_bzero(&vafp, sizeof(vafp)); - vafp.size = new_fmt->det.vid.size; - status = (*vfi->apply_fmt)(vfi, &vafp); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "pjmedia_vid_conf_update_port(): " - "Failed to apply format %04X", - new_fmt->id)); - return; - } - if (cport->port->put_frame) { - if (cport->put_buf_size < vafp.framebytes) - cport->put_buf = pj_pool_zalloc(cport->pool, vafp.framebytes); - cport->put_buf_size = vafp.framebytes; - - /* Initialize sink buffer with black color. */ - status = pjmedia_video_format_fill_black(&cport->port->info.fmt, - cport->put_buf, - cport->put_buf_size); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Warning: failed to init sink buffer " - " with black")); - } - } - if (cport->port->get_frame) { - if (cport->get_buf_size < vafp.framebytes) - cport->get_buf = pj_pool_zalloc(cport->pool, vafp.framebytes); - cport->get_buf_size = vafp.framebytes; - - /* When source port is updated, buffer should contain a new image - * with the correct latest format already, so don't fill black - * and don't reset the got_frame flag. - */ - //cport->got_frame = PJ_FALSE; - } - - /* Update render state */ - update_render_state(vid_conf, cport); - - /* Update render state of listeners */ - for (i=0; i < cport->listener_cnt; ++i) { - vconf_port *sink = vid_conf->ports[cport->listener_slots[i]]; - update_render_state(vid_conf, sink); - } - - PJ_LOG(4,(THIS_FILE, - "Port %d (%s): updated frame size %dx%d -> %dx%d", - slot, cport->name.ptr, - old_fmt->det.vid.size.w, old_fmt->det.vid.size.h, - new_fmt->det.vid.size.w, new_fmt->det.vid.size.h)); + const pjmedia_video_format_info *vfi; + pjmedia_video_apply_fmt_param vafp; + pj_status_t status; + unsigned i; + + vfi = pjmedia_get_video_format_info(NULL, new_fmt->id); + if (!vfi) { + PJ_LOG(1,(THIS_FILE, "pjmedia_vid_conf_update_port(): " + "unrecognized format %04X", + new_fmt->id)); + return; + } + + pj_bzero(&vafp, sizeof(vafp)); + vafp.size = new_fmt->det.vid.size; + status = (*vfi->apply_fmt)(vfi, &vafp); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "pjmedia_vid_conf_update_port(): " + "Failed to apply format %04X", + new_fmt->id)); + return; + } + if (cport->port->put_frame) { + if (cport->put_buf_size < vafp.framebytes) + cport->put_buf = pj_pool_zalloc(cport->pool, vafp.framebytes); + cport->put_buf_size = vafp.framebytes; + + /* Initialize sink buffer with black color. */ + status = pjmedia_video_format_fill_black(&cport->port->info.fmt, + cport->put_buf, + cport->put_buf_size); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, + "Warning: failed to init sink buffer " + " with black")); + } + } + if (cport->port->get_frame) { + if (cport->get_buf_size < vafp.framebytes) + cport->get_buf = pj_pool_zalloc(cport->pool, vafp.framebytes); + cport->get_buf_size = vafp.framebytes; + + /* When source port is updated, buffer should contain a new image + * with the correct latest format already, so don't fill black + * and don't reset the got_frame flag. + */ + //cport->got_frame = PJ_FALSE; + } + + /* Update render state */ + update_render_state(vid_conf, cport); + + /* Update render state of listeners */ + for (i=0; i < cport->listener_cnt; ++i) { + vconf_port *sink = vid_conf->ports[cport->listener_slots[i]]; + update_render_state(vid_conf, sink); + } + + PJ_LOG(4,(THIS_FILE, + "Port %d (%s): updated frame size %dx%d -> %dx%d", + slot, cport->name.ptr, + old_fmt->det.vid.size.w, old_fmt->det.vid.size.h, + new_fmt->det.vid.size.w, new_fmt->det.vid.size.h)); } /* Update cport format info */ diff --git a/pjmedia/src/pjmedia/vid_port.c b/pjmedia/src/pjmedia/vid_port.c index 78e663574c..fa9b1eec31 100644 --- a/pjmedia/src/pjmedia/vid_port.c +++ b/pjmedia/src/pjmedia/vid_port.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -28,8 +27,8 @@ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -#define SIGNATURE PJMEDIA_SIG_VID_PORT -#define THIS_FILE "vid_port.c" +#define SIGNATURE PJMEDIA_SIG_VID_PORT +#define THIS_FILE "vid_port.c" /* Enable/disable test of finding closest format algo */ @@ -40,7 +39,7 @@ * Enable this to trace the format matching process. */ #if 0 -# define TRACE_FIND_FMT(args) PJ_LOG(5,args) +# define TRACE_FIND_FMT(args) PJ_LOG(5,args) #else # define TRACE_FIND_FMT(args) #endif @@ -88,9 +87,9 @@ struct pjmedia_vid_port pj_bool_t destroy_client_port; struct { - pjmedia_converter *conv; - void *conv_buf; - pj_size_t conv_buf_size; + pjmedia_converter *conv; + void *conv_buf; + pj_size_t conv_buf_size; pjmedia_conversion_param conv_param; unsigned usec_ctr; unsigned usec_src, usec_dst; @@ -111,13 +110,13 @@ struct pjmedia_vid_port pjmedia_frame *frm_buf; pj_size_t frm_buf_size; pj_mutex_t *frm_mutex; - pj_size_t src_size; + pj_size_t src_size; }; struct vid_pasv_port { - pjmedia_port base; - pjmedia_vid_port *vp; + pjmedia_port base; + pjmedia_vid_port *vp; pj_bool_t is_destroying; }; @@ -129,11 +128,11 @@ struct fmt_prop }; static pj_status_t vidstream_cap_cb(pjmedia_vid_dev_stream *stream, - void *user_data, - pjmedia_frame *frame); + void *user_data, + pjmedia_frame *frame); static pj_status_t vidstream_render_cb(pjmedia_vid_dev_stream *stream, - void *user_data, - pjmedia_frame *frame); + void *user_data, + pjmedia_frame *frame); static pj_status_t vidstream_event_cb(pjmedia_event *event, void *user_data); static pj_status_t client_port_event_cb(pjmedia_event *event, @@ -143,10 +142,10 @@ static void enc_clock_cb(const pj_timestamp *ts, void *user_data); static void dec_clock_cb(const pj_timestamp *ts, void *user_data); static pj_status_t vid_pasv_port_put_frame(struct pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t vid_pasv_port_get_frame(struct pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t vid_pasv_port_on_destroy(struct pjmedia_port *this_port); @@ -161,23 +160,23 @@ static const char *vid_dir_name(pjmedia_dir dir) { switch (dir) { case PJMEDIA_DIR_CAPTURE: - return "capture"; + return "capture"; case PJMEDIA_DIR_RENDER: - return "render"; + return "render"; default: - return "??"; + return "??"; } } static pj_status_t get_vfi(const pjmedia_format *fmt, - const pjmedia_video_format_info **p_vfi, - pjmedia_video_apply_fmt_param *vafp) + const pjmedia_video_format_info **p_vfi, + pjmedia_video_apply_fmt_param *vafp) { const pjmedia_video_format_info *vfi; vfi = pjmedia_get_video_format_info(NULL, fmt->id); if (!vfi) - return PJMEDIA_EBADFMT; + return PJMEDIA_EBADFMT; if (p_vfi) *p_vfi = vfi; @@ -196,37 +195,37 @@ static pj_status_t create_converter(pjmedia_vid_port *vp) if (vp->conv.conv) { pjmedia_converter_destroy(vp->conv.conv); - vp->conv.conv = NULL; + vp->conv.conv = NULL; } /* Instantiate converter if necessary */ if (vp->conv.conv_param.src.id != vp->conv.conv_param.dst.id || - (vp->conv.conv_param.src.det.vid.size.w != + (vp->conv.conv_param.src.det.vid.size.w != vp->conv.conv_param.dst.det.vid.size.w) || - (vp->conv.conv_param.src.det.vid.size.h != + (vp->conv.conv_param.src.det.vid.size.h != vp->conv.conv_param.dst.det.vid.size.h)) { - /* Yes, we need converter */ - status = pjmedia_converter_create(NULL, vp->pool, &vp->conv.conv_param, - &vp->conv.conv); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, "Error creating converter")); - return status; - } + /* Yes, we need converter */ + status = pjmedia_converter_create(NULL, vp->pool, &vp->conv.conv_param, + &vp->conv.conv); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, "Error creating converter")); + return status; + } } if (vp->conv.conv || (vp->role==ROLE_ACTIVE && (vp->dir & PJMEDIA_DIR_ENCODING))) { - /* Allocate buffer for conversion */ - status = get_vfi(&vp->conv.conv_param.dst, NULL, &vafp); - if (status != PJ_SUCCESS) - return status; - - if (vafp.framebytes > vp->conv.conv_buf_size) { - vp->conv.conv_buf = pj_pool_alloc(vp->pool, vafp.framebytes); - vp->conv.conv_buf_size = vafp.framebytes; - } + /* Allocate buffer for conversion */ + status = get_vfi(&vp->conv.conv_param.dst, NULL, &vafp); + if (status != PJ_SUCCESS) + return status; + + if (vafp.framebytes > vp->conv.conv_buf_size) { + vp->conv.conv_buf = pj_pool_alloc(vp->pool, vafp.framebytes); + vp->conv.conv_buf_size = vafp.framebytes; + } } vp->conv.usec_ctr = 0; @@ -234,37 +233,37 @@ static pj_status_t create_converter(pjmedia_vid_port *vp) vp->conv.usec_dst = PJMEDIA_PTIME(&vp->conv.conv_param.dst.det.vid.fps); return PJ_SUCCESS; -} +} static pj_uint32_t match_format_id(pj_uint32_t req_id, - pj_uint32_t sup_id) + pj_uint32_t sup_id) { const pjmedia_video_format_info *req_fmt_info, *sup_fmt_info; if (req_id == sup_id) - return FMT_MATCH; + return FMT_MATCH; req_fmt_info = pjmedia_get_video_format_info( - pjmedia_video_format_mgr_instance(), - req_id); + pjmedia_video_format_mgr_instance(), + req_id); sup_fmt_info = pjmedia_get_video_format_info( - pjmedia_video_format_mgr_instance(), - sup_id); + pjmedia_video_format_mgr_instance(), + sup_id); if ((req_fmt_info == NULL) || (sup_fmt_info == NULL)) { - return FMT_DIFF_COLOR_SPACE; + return FMT_DIFF_COLOR_SPACE; } if (req_fmt_info->color_model == sup_fmt_info->color_model) { - return FMT_SAME_COLOR_SPACE; + return FMT_SAME_COLOR_SPACE; } return FMT_DIFF_COLOR_SPACE; } static pj_uint32_t get_match_format_id(pj_uint32_t req_fmt_id, - pjmedia_vid_dev_info *di) + pjmedia_vid_dev_info *di) { unsigned i, match_idx = 0, match_fmt = FMT_DIFF_COLOR_SPACE+1; @@ -273,15 +272,15 @@ static pj_uint32_t get_match_format_id(pj_uint32_t req_fmt_id, * use the first supported format on the list. */ for (i = 0; i < di->fmt_cnt; ++i) { - unsigned tmp_fmt = match_format_id(req_fmt_id, di->fmt[i].id); + unsigned tmp_fmt = match_format_id(req_fmt_id, di->fmt[i].id); - if (match_fmt == FMT_MATCH) - return req_fmt_id; + if (match_fmt == FMT_MATCH) + return req_fmt_id; - if (tmp_fmt < match_fmt) { - match_idx = i; - match_fmt = tmp_fmt; - } + if (tmp_fmt < match_fmt) { + match_idx = i; + match_fmt = tmp_fmt; + } } return di->fmt[match_idx].id; } @@ -301,9 +300,9 @@ static pj_uint32_t get_match_format_id(pj_uint32_t req_fmt_id, * the supported format. */ static struct fmt_prop find_closest_fmt(pj_uint32_t req_fmt_id, - pjmedia_rect_size *req_fmt_size, - pjmedia_ratio *req_fmt_fps, - pjmedia_vid_dev_info *di) + pjmedia_rect_size *req_fmt_size, + pjmedia_ratio *req_fmt_fps, + pjmedia_vid_dev_info *di) { unsigned i, match_idx = 0; pj_uint32_t match_fmt_id; @@ -311,15 +310,15 @@ static struct fmt_prop find_closest_fmt(pj_uint32_t req_fmt_id, struct fmt_prop ret_prop; pj_bool_t found_exact_match = PJ_FALSE; - #define GET_DIFF(x, y) ((x) > (y)? (x-y) : (y-x)) + #define GET_DIFF(x, y) ((x) > (y)? (x-y) : (y-x)) /* This will contain the supported format with lowest width difference */ pjmedia_rect_size nearest_width[PJMEDIA_VID_PORT_MATCH_WIDTH_ARRAY_SIZE]; /* Initialize the list. */ for (i=0;ifmt_cnt;++i) { - pjmedia_video_format_detail *vfd; - unsigned diff_width1, diff_width2; - - /* Ignore supported format with different format id. */ - if (di->fmt[i].id != match_fmt_id) - continue; - - vfd = pjmedia_format_get_video_format_detail(&di->fmt[i], PJ_TRUE); - - /* Exact match found. */ - if ((vfd->size.w == req_fmt_size->w) && - (vfd->size.h == req_fmt_size->h)) - { - nearest_width[0] = vfd->size; - found_exact_match = PJ_TRUE; - break; - } - - diff_width1 = GET_DIFF(vfd->size.w, req_fmt_size->w); - diff_width2 = GET_DIFF(nearest_width[0].w, req_fmt_size->w); - - /* Fill the nearest width list. */ - if (diff_width1 <= diff_width2) { - int k = 0; - while (((k < PJ_ARRAY_SIZE(nearest_width)) && - (!((vfd->size.w == nearest_width[k].w) && - (vfd->size.h == nearest_width[k].h))))) { - ++k; - } - if (k < PJ_ARRAY_SIZE(nearest_width)) { - /* resolution was already processed */ - continue; - - } - k = 1; - while(((k < PJ_ARRAY_SIZE(nearest_width)) && - (diff_width1 < (GET_DIFF(nearest_width[k].w, req_fmt_size->w))))) - { - nearest_width[k-1] = nearest_width[k]; - ++k; - } - nearest_width[k-1] = vfd->size; - } + pjmedia_video_format_detail *vfd; + unsigned diff_width1, diff_width2; + + /* Ignore supported format with different format id. */ + if (di->fmt[i].id != match_fmt_id) + continue; + + vfd = pjmedia_format_get_video_format_detail(&di->fmt[i], PJ_TRUE); + + /* Exact match found. */ + if ((vfd->size.w == req_fmt_size->w) && + (vfd->size.h == req_fmt_size->h)) + { + nearest_width[0] = vfd->size; + found_exact_match = PJ_TRUE; + break; + } + + diff_width1 = GET_DIFF(vfd->size.w, req_fmt_size->w); + diff_width2 = GET_DIFF(nearest_width[0].w, req_fmt_size->w); + + /* Fill the nearest width list. */ + if (diff_width1 <= diff_width2) { + int k = 0; + while (((k < PJ_ARRAY_SIZE(nearest_width)) && + (!((vfd->size.w == nearest_width[k].w) && + (vfd->size.h == nearest_width[k].h))))) { + ++k; + } + if (k < PJ_ARRAY_SIZE(nearest_width)) { + /* resolution was already processed */ + continue; + + } + k = 1; + while(((k < PJ_ARRAY_SIZE(nearest_width)) && + (diff_width1 < (GET_DIFF(nearest_width[k].w, req_fmt_size->w))))) + { + nearest_width[k-1] = nearest_width[k]; + ++k; + } + nearest_width[k-1] = vfd->size; + } } /* No need to calculate ratio if exact match is found. */ if (!found_exact_match) { - pj_bool_t found_match = PJ_FALSE; + pj_bool_t found_match = PJ_FALSE; - /* We have the list of supported format with nearest width. Now get the - * best ratio. - */ - req_ratio = (float)req_fmt_size->w / (float)req_fmt_size->h; - for (i=0;iw / (float)req_fmt_size->h; + for (i=0;isize.w, - vid_fd->size.h, - vid_fd->fps.num, - vid_fd->fps.denum)); + TRACE_FIND_FMT((THIS_FILE, "id:%s size:%d*%d fps:%d/%d", + fmt_name, + vid_fd->size.w, + vid_fd->size.h, + vid_fd->fps.num, + vid_fd->fps.denum)); } for (i = 0; i < PJ_ARRAY_SIZE(find_id); i++) { - for (j = 0; j < PJ_ARRAY_SIZE(find_fps); j++) { - - for (k = 0; k < PJ_ARRAY_SIZE(find_size); k++) { - struct fmt_prop match_prop; - - pjmedia_fourcc_name(find_id[i], fmt_name); - - TRACE_FIND_FMT((THIS_FILE, "Trying to find closest match " - "id:%s size:%dx%d fps:%d/%d", - fmt_name, - find_size[k].w, - find_size[k].h, - find_fps[j].num, - find_fps[j].denum)); - - match_prop = find_closest_fmt(find_id[i], - &find_size[k], - &find_fps[j], - di); - - if ((match_prop.id == find_id[i]) && - (match_prop.size.w == find_size[k].w) && - (match_prop.size.h == find_size[k].h) && - (match_prop.fps.num / match_prop.fps.denum == - find_fps[j].num * find_fps[j].denum)) - { - TRACE_FIND_FMT((THIS_FILE, "Exact Match found!!")); - } else { - pjmedia_fourcc_name(match_prop.id, fmt_name); - TRACE_FIND_FMT((THIS_FILE, "Closest format = "\ - "id:%s size:%dx%d fps:%d/%d", - fmt_name, - match_prop.size.w, - match_prop.size.h, - match_prop.fps.num, - match_prop.fps.denum)); - } - } - } + for (j = 0; j < PJ_ARRAY_SIZE(find_fps); j++) { + + for (k = 0; k < PJ_ARRAY_SIZE(find_size); k++) { + struct fmt_prop match_prop; + + pjmedia_fourcc_name(find_id[i], fmt_name); + + TRACE_FIND_FMT((THIS_FILE, "Trying to find closest match " + "id:%s size:%dx%d fps:%d/%d", + fmt_name, + find_size[k].w, + find_size[k].h, + find_fps[j].num, + find_fps[j].denum)); + + match_prop = find_closest_fmt(find_id[i], + &find_size[k], + &find_fps[j], + di); + + if ((match_prop.id == find_id[i]) && + (match_prop.size.w == find_size[k].w) && + (match_prop.size.h == find_size[k].h) && + (match_prop.fps.num / match_prop.fps.denum == + find_fps[j].num * find_fps[j].denum)) + { + TRACE_FIND_FMT((THIS_FILE, "Exact Match found!!")); + } else { + pjmedia_fourcc_name(match_prop.id, fmt_name); + TRACE_FIND_FMT((THIS_FILE, "Closest format = "\ + "id:%s size:%dx%d fps:%d/%d", + fmt_name, + match_prop.size.w, + match_prop.size.h, + match_prop.fps.num, + match_prop.fps.denum)); + } + } + } } } #endif PJ_DEF(pj_status_t) pjmedia_vid_port_create( pj_pool_t *pool, - const pjmedia_vid_port_param *prm, - pjmedia_vid_port **p_vid_port) + const pjmedia_vid_port_param *prm, + pjmedia_vid_port **p_vid_port) { pjmedia_vid_port *vp; pjmedia_video_format_detail *vfd; @@ -518,12 +517,12 @@ PJ_DEF(pj_status_t) pjmedia_vid_port_create( pj_pool_t *pool, PJ_ASSERT_RETURN(prm->vidparam.fmt.type == PJMEDIA_TYPE_VIDEO && prm->vidparam.dir != PJMEDIA_DIR_NONE && prm->vidparam.dir != PJMEDIA_DIR_CAPTURE_RENDER, - PJ_EINVAL); + PJ_EINVAL); /* Retrieve the video format detail */ vfd = pjmedia_format_get_video_format_detail(&prm->vidparam.fmt, PJ_TRUE); if (!vfd) - return PJ_EINVAL; + return PJ_EINVAL; PJ_ASSERT_RETURN(vfd->fps.num, PJ_EINVAL); @@ -549,44 +548,44 @@ PJ_DEF(pj_status_t) pjmedia_vid_port_create( pj_pool_t *pool, pj_ansi_snprintf(dev_name, sizeof(dev_name), "%s [%s]", di.name, di.driver); pjmedia_fourcc_name(vparam.fmt.id, fmt_name); PJ_LOG(4,(THIS_FILE, - "Opening device %s for %s: format=%s, size=%dx%d @%d:%d fps", - dev_name, - vid_dir_name(prm->vidparam.dir), fmt_name, - vfd->size.w, vfd->size.h, - vfd->fps.num, vfd->fps.denum)); + "Opening device %s for %s: format=%s, size=%dx%d @%d:%d fps", + dev_name, + vid_dir_name(prm->vidparam.dir), fmt_name, + vfd->size.w, vfd->size.h, + vfd->fps.num, vfd->fps.denum)); if (di.dir == PJMEDIA_DIR_RENDER) { - /* Find the matching format. If no exact match is found, find - * the supported format with the same color space. If no match is found, - * use the first supported format on the list. - */ - pj_assert(di.fmt_cnt != 0); - vparam.fmt.id = get_match_format_id(prm->vidparam.fmt.id, &di); + /* Find the matching format. If no exact match is found, find + * the supported format with the same color space. If no match is found, + * use the first supported format on the list. + */ + pj_assert(di.fmt_cnt != 0); + vparam.fmt.id = get_match_format_id(prm->vidparam.fmt.id, &di); } else { - struct fmt_prop match_prop; + struct fmt_prop match_prop; - if (di.fmt_cnt == 0) { - status = PJMEDIA_EVID_SYSERR; - PJ_PERROR(4,(THIS_FILE, status, "Device has no supported format")); - return status; - } + if (di.fmt_cnt == 0) { + status = PJMEDIA_EVID_SYSERR; + PJ_PERROR(4,(THIS_FILE, status, "Device has no supported format")); + return status; + } #if ENABLE_TEST_FIND_FMT - test_find_closest_fmt(&di); + test_find_closest_fmt(&di); #endif - match_prop = find_closest_fmt(prm->vidparam.fmt.id, - &vfd->size, - &vfd->fps, - &di); - - if ((match_prop.id != prm->vidparam.fmt.id) || - (match_prop.size.w != vfd->size.w) || - (match_prop.size.h != vfd->size.h)) - { - vparam.fmt.id = match_prop.id; - vparam.fmt.det.vid.size = match_prop.size; - } + match_prop = find_closest_fmt(prm->vidparam.fmt.id, + &vfd->size, + &vfd->fps, + &di); + + if ((match_prop.id != prm->vidparam.fmt.id) || + (match_prop.size.w != vfd->size.w) || + (match_prop.size.h != vfd->size.h)) + { + vparam.fmt.id = match_prop.id; + vparam.fmt.det.vid.size = match_prop.size; + } } pj_strdup2_with_null(pool, &vp->dev_name, di.name); @@ -605,44 +604,44 @@ PJ_DEF(pj_status_t) pjmedia_vid_port_create( pj_pool_t *pool, vid_cb.render_cb = &vidstream_render_cb; status = pjmedia_vid_dev_stream_create(&vparam, &vid_cb, vp, - &vp->strm); + &vp->strm); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; pjmedia_fourcc_name(vparam.fmt.id, fmt_name); PJ_LOG(4,(THIS_FILE, - "Device %s opened: format=%s, size=%dx%d @%d:%d fps", - dev_name, fmt_name, - vparam.fmt.det.vid.size.w, vparam.fmt.det.vid.size.h, - vparam.fmt.det.vid.fps.num, vparam.fmt.det.vid.fps.denum)); + "Device %s opened: format=%s, size=%dx%d @%d:%d fps", + dev_name, fmt_name, + vparam.fmt.det.vid.size.w, vparam.fmt.det.vid.size.h, + vparam.fmt.det.vid.fps.num, vparam.fmt.det.vid.fps.denum)); /* Subscribe to device's events */ pjmedia_event_subscribe(NULL, &vidstream_event_cb, vp, vp->strm); if (vp->dir & PJMEDIA_DIR_CAPTURE) { - pjmedia_format_copy(&vp->conv.conv_param.src, &vparam.fmt); - pjmedia_format_copy(&vp->conv.conv_param.dst, &prm->vidparam.fmt); + pjmedia_format_copy(&vp->conv.conv_param.src, &vparam.fmt); + pjmedia_format_copy(&vp->conv.conv_param.dst, &prm->vidparam.fmt); } else { - pjmedia_format_copy(&vp->conv.conv_param.src, &prm->vidparam.fmt); - pjmedia_format_copy(&vp->conv.conv_param.dst, &vparam.fmt); + pjmedia_format_copy(&vp->conv.conv_param.src, &prm->vidparam.fmt); + pjmedia_format_copy(&vp->conv.conv_param.dst, &vparam.fmt); } status = create_converter(vp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; if (vp->role==ROLE_ACTIVE && ((vp->dir & PJMEDIA_DIR_ENCODING) || vp->stream_role==ROLE_PASSIVE)) { pjmedia_clock_param param; - /* Active role is wanted, but our device is passive, so create - * master clocks to run the media flow. For encoding direction, + /* Active role is wanted, but our device is passive, so create + * master clocks to run the media flow. For encoding direction, * we also want to create our own clock since the device's clock * may run at a different rate. - */ - need_frame_buf = PJ_TRUE; + */ + need_frame_buf = PJ_TRUE; param.usec_interval = PJMEDIA_PTIME(&vfd->fps); param.clock_rate = prm->vidparam.clock_rate; @@ -655,29 +654,29 @@ PJ_DEF(pj_status_t) pjmedia_vid_port_create( pj_pool_t *pool, goto on_error; } else if (vp->role==ROLE_PASSIVE) { - vid_pasv_port *pp; - - /* Always need to create media port for passive role */ - vp->pasv_port = pp = PJ_POOL_ZALLOC_T(pool, vid_pasv_port); - pp->vp = vp; - if (prm->vidparam.dir & PJMEDIA_DIR_CAPTURE) - pp->base.get_frame = &vid_pasv_port_get_frame; - if (prm->vidparam.dir & PJMEDIA_DIR_RENDER) - pp->base.put_frame = &vid_pasv_port_put_frame; - pp->base.on_destroy = &vid_pasv_port_on_destroy; - pjmedia_port_info_init2(&pp->base.info, &vp->dev_name, - PJMEDIA_SIG_VID_PORT, - prm->vidparam.dir, &prm->vidparam.fmt); + vid_pasv_port *pp; + + /* Always need to create media port for passive role */ + vp->pasv_port = pp = PJ_POOL_ZALLOC_T(pool, vid_pasv_port); + pp->vp = vp; + if (prm->vidparam.dir & PJMEDIA_DIR_CAPTURE) + pp->base.get_frame = &vid_pasv_port_get_frame; + if (prm->vidparam.dir & PJMEDIA_DIR_RENDER) + pp->base.put_frame = &vid_pasv_port_put_frame; + pp->base.on_destroy = &vid_pasv_port_on_destroy; + pjmedia_port_info_init2(&pp->base.info, &vp->dev_name, + PJMEDIA_SIG_VID_PORT, + prm->vidparam.dir, &prm->vidparam.fmt); need_frame_buf = PJ_TRUE; } if (need_frame_buf) { - pjmedia_video_apply_fmt_param vafp; + pjmedia_video_apply_fmt_param vafp; - status = get_vfi(&vp->conv.conv_param.src, NULL, &vafp); - if (status != PJ_SUCCESS) - goto on_error; + status = get_vfi(&vp->conv.conv_param.src, NULL, &vafp); + if (status != PJ_SUCCESS) + goto on_error; vp->frm_buf = PJ_POOL_ZALLOC_T(pool, pjmedia_frame); vp->frm_buf_size = vafp.framebytes; @@ -685,14 +684,14 @@ PJ_DEF(pj_status_t) pjmedia_vid_port_create( pj_pool_t *pool, vp->frm_buf->size = vp->frm_buf_size; vp->frm_buf->type = PJMEDIA_FRAME_TYPE_NONE; - /* Initialize buffer with black color */ - status = pjmedia_video_format_fill_black(&vp->conv.conv_param.src, - vp->frm_buf->buf, - vp->frm_buf_size); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Warning: failed to init buffer with black")); - } + /* Initialize buffer with black color */ + status = pjmedia_video_format_fill_black(&vp->conv.conv_param.src, + vp->frm_buf->buf, + vp->frm_buf_size); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, + "Warning: failed to init buffer with black")); + } status = pj_mutex_create_simple(pool, vp->dev_name.ptr, &vp->frm_mutex); @@ -710,7 +709,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_port_create( pj_pool_t *pool, } PJ_DEF(void) pjmedia_vid_port_set_cb(pjmedia_vid_port *vid_port, - const pjmedia_vid_dev_cb *cb, + const pjmedia_vid_dev_cb *cb, void *user_data) { pj_assert(vid_port && cb); @@ -757,8 +756,8 @@ pjmedia_vid_port_set_clock_src( pjmedia_vid_port *vid_port, PJ_DEF(pj_status_t) pjmedia_vid_port_subscribe_event( - pjmedia_vid_port *vp, - pjmedia_port *port) + pjmedia_vid_port *vp, + pjmedia_port *port) { PJ_ASSERT_RETURN(vp && port, PJ_EINVAL); @@ -768,8 +767,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_port_subscribe_event( PJ_DEF(pj_status_t) pjmedia_vid_port_unsubscribe_event( - pjmedia_vid_port *vp, - pjmedia_port *port) + pjmedia_vid_port *vp, + pjmedia_port *port) { PJ_ASSERT_RETURN(vp && port, PJ_EINVAL); @@ -779,8 +778,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_port_unsubscribe_event( PJ_DEF(pj_status_t) pjmedia_vid_port_connect(pjmedia_vid_port *vp, - pjmedia_port *port, - pj_bool_t destroy) + pjmedia_port *port, + pj_bool_t destroy) { PJ_ASSERT_RETURN(vp && vp->role==ROLE_ACTIVE, PJ_EINVAL); vp->destroy_client_port = destroy; @@ -821,21 +820,21 @@ PJ_DEF(pj_status_t) pjmedia_vid_port_start(pjmedia_vid_port *vp) /* Initialize buffer with black color */ status = pjmedia_video_format_fill_black(&vp->conv.conv_param.src, - vp->frm_buf->buf, - vp->frm_buf_size); + vp->frm_buf->buf, + vp->frm_buf_size); if (status != PJ_SUCCESS) { PJ_PERROR(4,(THIS_FILE, status, - "Warning: failed to init buffer with black")); + "Warning: failed to init buffer with black")); } status = pjmedia_vid_dev_stream_start(vp->strm); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; if (vp->clock) { - status = pjmedia_clock_start(vp->clock); - if (status != PJ_SUCCESS) - goto on_error; + status = pjmedia_clock_start(vp->clock); + if (status != PJ_SUCCESS) + goto on_error; } return PJ_SUCCESS; @@ -857,7 +856,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_port_stop(pjmedia_vid_port *vp) PJ_ASSERT_RETURN(vp, PJ_EINVAL); if (vp->clock) { - status = pjmedia_clock_stop(vp->clock); + status = pjmedia_clock_stop(vp->clock); } status = pjmedia_vid_dev_stream_stop(vp->strm); @@ -883,21 +882,21 @@ static void vid_port_destroy(pjmedia_vid_port *vp) } if (vp->clock) { - pjmedia_clock_destroy(vp->clock); - vp->clock = NULL; + pjmedia_clock_destroy(vp->clock); + vp->clock = NULL; } if (vp->strm) { - pjmedia_vid_dev_stream_destroy(vp->strm); - vp->strm = NULL; + pjmedia_vid_dev_stream_destroy(vp->strm); + vp->strm = NULL; } if (vp->client_port) { - if (vp->destroy_client_port) - pjmedia_port_destroy(vp->client_port); - vp->client_port = NULL; + if (vp->destroy_client_port) + pjmedia_port_destroy(vp->client_port); + vp->client_port = NULL; } if (vp->frm_mutex) { - pj_mutex_destroy(vp->frm_mutex); - vp->frm_mutex = NULL; + pj_mutex_destroy(vp->frm_mutex); + vp->frm_mutex = NULL; } if (vp->conv.conv) { pjmedia_converter_destroy(vp->conv.conv); @@ -914,9 +913,9 @@ PJ_DEF(void) pjmedia_vid_port_destroy(pjmedia_vid_port *vp) /* This is a passive port, destroy via PJMEDIA port API */ if (vp->pasv_port) { - vp->pasv_port->is_destroying = PJ_TRUE; - pjmedia_port_destroy(&vp->pasv_port->base); - return; + vp->pasv_port->is_destroying = PJ_TRUE; + pjmedia_port_destroy(&vp->pasv_port->base); + return; } vid_port_destroy(vp); @@ -932,7 +931,7 @@ static void save_rgb_frame(int width, int height, const pjmedia_frame *frm) int y; if (counter > 10) - return; + return; // Open file sprintf(szFilename, "frame%02d.ppm", counter++); @@ -976,7 +975,7 @@ static pj_status_t client_port_event_cb(pjmedia_event *event, /* Retrieve the current video format detail */ pjmedia_vid_dev_stream_get_param(vp->strm, &vid_param); vfd_cur = pjmedia_format_get_video_format_detail( - &vid_param.fmt, PJ_TRUE); + &vid_param.fmt, PJ_TRUE); if (!vfd_cur) return PJMEDIA_EVID_BADFORMAT; @@ -986,50 +985,50 @@ static pj_status_t client_port_event_cb(pjmedia_event *event, if (!vfd || !vfd->fps.num || !vfd->fps.denum) return PJMEDIA_EVID_BADFORMAT; - /* Ticket #1876: if this is a passive renderer and only frame rate is - * changing, simply modify the clock. - */ - if (vp->dir == PJMEDIA_DIR_RENDER && - vp->stream_role == ROLE_PASSIVE && vp->role == ROLE_ACTIVE) - { - pj_bool_t fps_only; - pjmedia_video_format_detail tmp_vfd; - - tmp_vfd = *vfd_cur; - tmp_vfd.fps = vfd->fps; - fps_only = pj_memcmp(vfd, &tmp_vfd, sizeof(*vfd)) == 0; - if (fps_only) { - pjmedia_clock_param clock_param; - clock_param.usec_interval = PJMEDIA_PTIME(&vfd->fps); - clock_param.clock_rate = vid_param.clock_rate; - pjmedia_clock_modify(vp->clock, &clock_param); - - return pjmedia_event_publish(NULL, vp, event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); - } - } - - /* Ticket #1827: - * Stopping video port should not be necessary here because - * it will also try to stop the clock, from inside the clock's - * own thread, so it may get stuck. We just stop the video device - * stream instead. - * pjmedia_vid_port_stop(vp); - */ - pjmedia_vid_dev_stream_stop(vp->strm); + /* Ticket #1876: if this is a passive renderer and only frame rate is + * changing, simply modify the clock. + */ + if (vp->dir == PJMEDIA_DIR_RENDER && + vp->stream_role == ROLE_PASSIVE && vp->role == ROLE_ACTIVE) + { + pj_bool_t fps_only; + pjmedia_video_format_detail tmp_vfd; + + tmp_vfd = *vfd_cur; + tmp_vfd.fps = vfd->fps; + fps_only = pj_memcmp(vfd, &tmp_vfd, sizeof(*vfd)) == 0; + if (fps_only) { + pjmedia_clock_param clock_param; + clock_param.usec_interval = PJMEDIA_PTIME(&vfd->fps); + clock_param.clock_rate = vid_param.clock_rate; + pjmedia_clock_modify(vp->clock, &clock_param); + + return pjmedia_event_publish(NULL, vp, event, + PJMEDIA_EVENT_PUBLISH_POST_EVENT); + } + } + + /* Ticket #1827: + * Stopping video port should not be necessary here because + * it will also try to stop the clock, from inside the clock's + * own thread, so it may get stuck. We just stop the video device + * stream instead. + * pjmedia_vid_port_stop(vp); + */ + pjmedia_vid_dev_stream_stop(vp->strm); - /* Change the destination format to the new format */ - pjmedia_format_copy(&vp->conv.conv_param.src, - &event->data.fmt_changed.new_fmt); - /* Only copy the size here */ - vp->conv.conv_param.dst.det.vid.size = - event->data.fmt_changed.new_fmt.det.vid.size; - - status = create_converter(vp); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, "Error recreating converter")); - return status; - } + /* Change the destination format to the new format */ + pjmedia_format_copy(&vp->conv.conv_param.src, + &event->data.fmt_changed.new_fmt); + /* Only copy the size here */ + vp->conv.conv_param.dst.det.vid.size = + event->data.fmt_changed.new_fmt.det.vid.size; + + status = create_converter(vp); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, "Error recreating converter")); + return status; + } if (vid_param.fmt.id != vp->conv.conv_param.dst.id || (vid_param.fmt.det.vid.size.h != @@ -1041,21 +1040,21 @@ static pj_status_t client_port_event_cb(pjmedia_event *event, PJMEDIA_VID_DEV_CAP_FORMAT, &vp->conv.conv_param.dst); if (status != PJ_SUCCESS) { - pjmedia_event e; + pjmedia_event e; PJ_PERROR(3,(THIS_FILE, status, - "failure in changing the format of the video device")); + "failure in changing the format of the video device")); PJ_LOG(3, (THIS_FILE, "reverting to its original format: %s", status != PJMEDIA_EVID_ERR ? "success" : "failure")); - pjmedia_event_init(&e, PJMEDIA_EVENT_VID_DEV_ERROR, NULL, vp); - e.data.vid_dev_err.dir = vp->dir; - e.data.vid_dev_err.status = status; - e.data.vid_dev_err.id = (vp->dir==PJMEDIA_DIR_ENCODING? - vid_param.cap_id : vid_param.rend_id); - pjmedia_event_publish(NULL, vp, &e, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); + pjmedia_event_init(&e, PJMEDIA_EVENT_VID_DEV_ERROR, NULL, vp); + e.data.vid_dev_err.dir = vp->dir; + e.data.vid_dev_err.status = status; + e.data.vid_dev_err.id = (vp->dir==PJMEDIA_DIR_ENCODING? + vid_param.cap_id : vid_param.rend_id); + pjmedia_event_publish(NULL, vp, &e, + PJMEDIA_EVENT_PUBLISH_POST_EVENT); return status; } @@ -1075,14 +1074,14 @@ static pj_status_t client_port_event_cb(pjmedia_event *event, pjmedia_clock_modify(vp->clock, &clock_param); } - /* pjmedia_vid_port_start(vp); */ - pjmedia_vid_dev_stream_start(vp->strm); - - /* Update passive port info from the video stream */ - if (vp->role == ROLE_PASSIVE) { - pjmedia_format_copy(&vp->pasv_port->base.info.fmt, - &event->data.fmt_changed.new_fmt); - } + /* pjmedia_vid_port_start(vp); */ + pjmedia_vid_dev_stream_start(vp->strm); + + /* Update passive port info from the video stream */ + if (vp->role == ROLE_PASSIVE) { + pjmedia_format_copy(&vp->pasv_port->base.info.fmt, + &event->data.fmt_changed.new_fmt); + } } /* Republish the event, post the event to the event manager @@ -1101,13 +1100,13 @@ static pj_status_t convert_frame(pjmedia_vid_port *vp, if (vp->conv.conv) { if (!dst_frame->buf || dst_frame->size < vp->conv.conv_buf_size) { dst_frame->buf = vp->conv.conv_buf; - dst_frame->size = vp->conv.conv_buf_size; + dst_frame->size = vp->conv.conv_buf_size; } - dst_frame->type = src_frame->type; - dst_frame->timestamp = src_frame->timestamp; - dst_frame->bit_info = src_frame->bit_info; - status = pjmedia_converter_convert(vp->conv.conv, - src_frame, dst_frame); + dst_frame->type = src_frame->type; + dst_frame->timestamp = src_frame->timestamp; + dst_frame->bit_info = src_frame->bit_info; + status = pjmedia_converter_convert(vp->conv.conv, + src_frame, dst_frame); } return status; @@ -1152,7 +1151,7 @@ static void enc_clock_cb(const pj_timestamp *ts, void *user_data) PJ_UNUSED_ARG(ts); if (!vp->client_port) - return; + return; if (vp->stream_role == ROLE_PASSIVE) { while (vp->conv.usec_ctr < vp->conv.usec_dst) { @@ -1162,7 +1161,7 @@ static void enc_clock_cb(const pj_timestamp *ts, void *user_data) } vp->conv.usec_ctr -= vp->conv.usec_dst; if (status != PJ_SUCCESS) - return; + return; } //save_rgb_frame(vp->cap_size.w, vp->cap_size.h, vp->frm_buf); @@ -1192,19 +1191,19 @@ static void dec_clock_cb(const pj_timestamp *ts, void *user_data) PJ_UNUSED_ARG(ts); if (!vp->client_port) - return; + return; status = vidstream_render_cb(vp->strm, vp, &frame); if (status != PJ_SUCCESS) return; if (frame.size > 0) - status = pjmedia_vid_dev_stream_put_frame(vp->strm, &frame); + status = pjmedia_vid_dev_stream_put_frame(vp->strm, &frame); } static pj_status_t vidstream_cap_cb(pjmedia_vid_dev_stream *stream, - void *user_data, - pjmedia_frame *frame) + void *user_data, + pjmedia_frame *frame) { pjmedia_vid_port *vp = (pjmedia_vid_port*)user_data; @@ -1224,8 +1223,8 @@ static pj_status_t vidstream_cap_cb(pjmedia_vid_dev_stream *stream, } static pj_status_t vidstream_render_cb(pjmedia_vid_dev_stream *stream, - void *user_data, - pjmedia_frame *frame) + void *user_data, + pjmedia_frame *frame) { pjmedia_vid_port *vp = (pjmedia_vid_port*)user_data; pj_status_t status = PJ_SUCCESS; @@ -1342,11 +1341,11 @@ static pj_status_t vidstream_render_cb(pjmedia_vid_dev_stream *stream, pjmedia_clock_src_update(&vp->clocksrc, NULL); status = convert_frame(vp, vp->frm_buf, frame); - if (status != PJ_SUCCESS) + if (status != PJ_SUCCESS) return status; - if (!vp->conv.conv) - pj_memcpy(frame, vp->frm_buf, sizeof(*frame)); + if (!vp->conv.conv) + pj_memcpy(frame, vp->frm_buf, sizeof(*frame)); } else { /* The stream is active while we are passive so we need to get the * frame from the buffer. @@ -1360,13 +1359,13 @@ static pj_status_t vidstream_render_cb(pjmedia_vid_dev_stream *stream, } static pj_status_t vid_pasv_port_put_frame(struct pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct vid_pasv_port *vpp = (struct vid_pasv_port*)this_port; pjmedia_vid_port *vp = vpp->vp; if (vp->pasv_port->is_destroying) - return PJ_EGONE; + return PJ_EGONE; if (vp->stream_role==ROLE_PASSIVE) { /* We are passive and the stream is passive. @@ -1375,33 +1374,33 @@ static pj_status_t vid_pasv_port_put_frame(struct pjmedia_port *this_port, pj_status_t status; pjmedia_frame frame_; - if (frame->size != vp->src_size) { - if (frame->size > 0) { - PJ_LOG(4, (THIS_FILE, "Unexpected frame size %d, expected %d", - frame->size, vp->src_size)); - } + if (frame->size != vp->src_size) { + if (frame->size > 0) { + PJ_LOG(4, (THIS_FILE, "Unexpected frame size %d, expected %d", + frame->size, vp->src_size)); + } - pj_memcpy(&frame_, frame, sizeof(pjmedia_frame)); - frame_.buf = NULL; - frame_.size = 0; + pj_memcpy(&frame_, frame, sizeof(pjmedia_frame)); + frame_.buf = NULL; + frame_.size = 0; - /* Send heart beat for updating timestamp or keep-alive. */ - return pjmedia_vid_dev_stream_put_frame(vp->strm, &frame_); - } + /* Send heart beat for updating timestamp or keep-alive. */ + return pjmedia_vid_dev_stream_put_frame(vp->strm, &frame_); + } pj_bzero(&frame_, sizeof(frame_)); status = convert_frame(vp, frame, &frame_); if (status != PJ_SUCCESS) return status; - return pjmedia_vid_dev_stream_put_frame(vp->strm, (vp->conv.conv? + return pjmedia_vid_dev_stream_put_frame(vp->strm, (vp->conv.conv? &frame_: frame)); } else { /* We are passive while the stream is active so we just store the * frame in the buffer. * The encoding counterpart is located in vidstream_cap_cb() */ - if (frame->size == vp->src_size) + if (frame->size == vp->src_size) copy_frame_to_buffer(vp, frame); } @@ -1409,27 +1408,27 @@ static pj_status_t vid_pasv_port_put_frame(struct pjmedia_port *this_port, } static pj_status_t vid_pasv_port_get_frame(struct pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct vid_pasv_port *vpp = (struct vid_pasv_port*)this_port; pjmedia_vid_port *vp = vpp->vp; pj_status_t status = PJ_SUCCESS; if (vp->pasv_port->is_destroying) - return PJ_EGONE; + return PJ_EGONE; if (vp->stream_role==ROLE_PASSIVE) { /* We are passive and the stream is passive. * The decoding counterpart is in vid_pasv_port_put_frame(). */ - pjmedia_frame *get_frm = vp->conv.conv? vp->frm_buf : frame; + pjmedia_frame *get_frm = vp->conv.conv? vp->frm_buf : frame; - if (vp->conv.conv) + if (vp->conv.conv) get_frm->size = vp->frm_buf_size; - status = pjmedia_vid_dev_stream_get_frame(vp->strm, get_frm); - if (status != PJ_SUCCESS) - return status; + status = pjmedia_vid_dev_stream_get_frame(vp->strm, get_frm); + if (status != PJ_SUCCESS) + return status; status = convert_frame(vp, vp->frm_buf, frame); } else { diff --git a/pjmedia/src/pjmedia/vid_stream.c b/pjmedia/src/pjmedia/vid_stream.c index 309ebb45ec..39f8846482 100644 --- a/pjmedia/src/pjmedia/vid_stream.c +++ b/pjmedia/src/pjmedia/vid_stream.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011 Teluu Inc. (http://www.teluu.com) * @@ -33,39 +32,39 @@ #include #include #include -#include /* memcpy() */ +#include /* memcpy() */ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -#define THIS_FILE "vid_stream.c" -#define ERRLEVEL 1 -#define LOGERR_(expr) PJ_PERROR(4,expr) -#define TRC_(expr) PJ_LOG(5,expr) -#define SIGNATURE PJMEDIA_SIG_PORT_VID_STREAM +#define THIS_FILE "vid_stream.c" +#define ERRLEVEL 1 +#define LOGERR_(expr) PJ_PERROR(4,expr) +#define TRC_(expr) PJ_LOG(5,expr) +#define SIGNATURE PJMEDIA_SIG_PORT_VID_STREAM -#define TRACE_RC 0 +#define TRACE_RC 0 /* Tracing jitter buffer operations in a stream session to a CSV file. * The trace will contain JB operation timestamp, frame info, RTP info, and * the JB state right after the operation. */ -#define TRACE_JB 0 /* Enable/disable trace. */ -#define TRACE_JB_PATH_PREFIX "" /* Optional path/prefix - for the CSV filename. */ +#define TRACE_JB 0 /* Enable/disable trace. */ +#define TRACE_JB_PATH_PREFIX "" /* Optional path/prefix + for the CSV filename. */ #if TRACE_JB # include -# define TRACE_JB_INVALID_FD ((pj_oshandle_t)-1) -# define TRACE_JB_OPENED(s) (s->trace_jb_fd != TRACE_JB_INVALID_FD) +# define TRACE_JB_INVALID_FD ((pj_oshandle_t)-1) +# define TRACE_JB_OPENED(s) (s->trace_jb_fd != TRACE_JB_INVALID_FD) #endif #ifndef PJMEDIA_VSTREAM_SIZE -# define PJMEDIA_VSTREAM_SIZE 1000 +# define PJMEDIA_VSTREAM_SIZE 1000 #endif #ifndef PJMEDIA_VSTREAM_INC -# define PJMEDIA_VSTREAM_INC 1000 +# define PJMEDIA_VSTREAM_INC 1000 #endif /* Due to network MTU limitation, a picture bitstream may be splitted into @@ -73,24 +72,24 @@ * picture resolution and MTU. This constant specifies the minimum chunk * number to be allocated to store a picture bitstream in decoding direction. */ -#define MIN_CHUNKS_PER_FRM 30 +#define MIN_CHUNKS_PER_FRM 30 /* Number of send error before repeat the report. */ -#define SEND_ERR_COUNT_TO_REPORT 50 +#define SEND_ERR_COUNT_TO_REPORT 50 /** * Media channel. */ typedef struct pjmedia_vid_channel { - pjmedia_vid_stream *stream; /**< Parent stream. */ - pjmedia_dir dir; /**< Channel direction. */ - pjmedia_port port; /**< Port interface. */ - unsigned pt; /**< Payload type. */ - pj_bool_t paused; /**< Paused?. */ - void *buf; /**< Output buffer. */ - unsigned buf_size; /**< Size of output buffer. */ - pjmedia_rtp_session rtp; /**< RTP session. */ + pjmedia_vid_stream *stream; /**< Parent stream. */ + pjmedia_dir dir; /**< Channel direction. */ + pjmedia_port port; /**< Port interface. */ + unsigned pt; /**< Payload type. */ + pj_bool_t paused; /**< Paused?. */ + void *buf; /**< Output buffer. */ + unsigned buf_size; /**< Size of output buffer. */ + pjmedia_rtp_session rtp; /**< RTP session. */ } pjmedia_vid_channel; @@ -103,120 +102,120 @@ typedef struct pjmedia_vid_channel */ struct pjmedia_vid_stream { - pj_pool_t *own_pool; /**< Internal pool. */ - pjmedia_endpt *endpt; /**< Media endpoint. */ - pjmedia_vid_codec_mgr *codec_mgr; /**< Codec manager. */ - pjmedia_vid_stream_info info; /**< Stream info. */ - pj_grp_lock_t *grp_lock; /**< Stream lock. */ - - pjmedia_vid_channel *enc; /**< Encoding channel. */ - pjmedia_vid_channel *dec; /**< Decoding channel. */ - - pjmedia_dir dir; /**< Stream direction. */ - void *user_data; /**< User data. */ - pj_str_t name; /**< Stream name */ - pj_str_t cname; /**< SDES CNAME */ - - pjmedia_transport *transport; /**< Stream transport. */ - - pjmedia_jbuf *jb; /**< Jitter buffer. */ - char jb_last_frm; /**< Last frame type from jb */ - unsigned jb_last_frm_cnt;/**< Last JB frame type counter*/ - - pjmedia_rtcp_session rtcp; /**< RTCP for incoming RTP. */ - pj_timestamp rtcp_last_tx; /**< Last RTCP tx time. */ - pj_timestamp rtcp_fb_last_tx;/**< Last RTCP-FB tx time. */ - pj_uint32_t rtcp_interval; /**< Interval, in msec. */ - pj_bool_t initial_rr; /**< Initial RTCP RR sent */ + pj_pool_t *own_pool; /**< Internal pool. */ + pjmedia_endpt *endpt; /**< Media endpoint. */ + pjmedia_vid_codec_mgr *codec_mgr; /**< Codec manager. */ + pjmedia_vid_stream_info info; /**< Stream info. */ + pj_grp_lock_t *grp_lock; /**< Stream lock. */ + + pjmedia_vid_channel *enc; /**< Encoding channel. */ + pjmedia_vid_channel *dec; /**< Decoding channel. */ + + pjmedia_dir dir; /**< Stream direction. */ + void *user_data; /**< User data. */ + pj_str_t name; /**< Stream name */ + pj_str_t cname; /**< SDES CNAME */ + + pjmedia_transport *transport; /**< Stream transport. */ + + pjmedia_jbuf *jb; /**< Jitter buffer. */ + char jb_last_frm; /**< Last frame type from jb */ + unsigned jb_last_frm_cnt;/**< Last JB frame type counter*/ + + pjmedia_rtcp_session rtcp; /**< RTCP for incoming RTP. */ + pj_timestamp rtcp_last_tx; /**< Last RTCP tx time. */ + pj_timestamp rtcp_fb_last_tx;/**< Last RTCP-FB tx time. */ + pj_uint32_t rtcp_interval; /**< Interval, in msec. */ + pj_bool_t initial_rr; /**< Initial RTCP RR sent */ pj_bool_t rtcp_sdes_bye_disabled;/**< Send RTCP SDES/BYE?*/ - void *out_rtcp_pkt; /**< Outgoing RTCP packet. */ - unsigned out_rtcp_pkt_size; - /**< Outgoing RTCP packet size. */ - - unsigned dec_max_size; /**< Size of decoded/raw picture*/ - pjmedia_ratio dec_max_fps; /**< Max fps of decoding dir. */ - pjmedia_frame dec_frame; /**< Current decoded frame. */ - unsigned dec_delay_cnt; /**< Decoding delay (in frames).*/ - unsigned dec_max_delay; /**< Decoding max delay (in ts).*/ - pjmedia_event fmt_event; /**< Buffered fmt_changed event - to avoid deadlock */ + void *out_rtcp_pkt; /**< Outgoing RTCP packet. */ + unsigned out_rtcp_pkt_size; + /**< Outgoing RTCP packet size. */ + + unsigned dec_max_size; /**< Size of decoded/raw picture*/ + pjmedia_ratio dec_max_fps; /**< Max fps of decoding dir. */ + pjmedia_frame dec_frame; /**< Current decoded frame. */ + unsigned dec_delay_cnt; /**< Decoding delay (in frames).*/ + unsigned dec_max_delay; /**< Decoding max delay (in ts).*/ + pjmedia_event fmt_event; /**< Buffered fmt_changed event + to avoid deadlock */ pjmedia_event miss_keyframe_event; - /**< Buffered missing keyframe + /**< Buffered missing keyframe event for delayed republish*/ - unsigned frame_size; /**< Size of encoded base frame.*/ - unsigned frame_ts_len; /**< Frame length in timestamp. */ + unsigned frame_size; /**< Size of encoded base frame.*/ + unsigned frame_ts_len; /**< Frame length in timestamp. */ - unsigned rx_frame_cnt; /**< # of array in rx_frames */ - pjmedia_frame *rx_frames; /**< Temp. buffer for incoming - frame assembly. */ - pj_bool_t force_keyframe;/**< Forced to encode keyframe? */ - unsigned num_keyframe; /**< The number of keyframe needed - to be sent, e.g: after the - stream is created. */ - pj_timestamp last_keyframe_tx; - /**< Timestamp of the last - keyframe. */ + unsigned rx_frame_cnt; /**< # of array in rx_frames */ + pjmedia_frame *rx_frames; /**< Temp. buffer for incoming + frame assembly. */ + pj_bool_t force_keyframe;/**< Forced to encode keyframe? */ + unsigned num_keyframe; /**< The number of keyframe needed + to be sent, e.g: after the + stream is created. */ + pj_timestamp last_keyframe_tx; + /**< Timestamp of the last + keyframe. */ #if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0 - pj_bool_t use_ka; /**< Stream keep-alive with non- - codec-VAD mechanism is - enabled? */ - unsigned ka_interval; /**< The keepalive sending - interval */ - pj_time_val last_frm_ts_sent; /**< Time of last sending - packet */ - unsigned start_ka_count; /**< The number of keep-alive + pj_bool_t use_ka; /**< Stream keep-alive with non- + codec-VAD mechanism is + enabled? */ + unsigned ka_interval; /**< The keepalive sending + interval */ + pj_time_val last_frm_ts_sent; /**< Time of last sending + packet */ + unsigned start_ka_count; /**< The number of keep-alive to be sent after it is created */ - unsigned start_ka_interval;/**< The keepalive sending + unsigned start_ka_interval;/**< The keepalive sending interval after the stream is created */ - pj_timestamp last_start_ka_tx; /**< Timestamp of the last + pj_timestamp last_start_ka_tx; /**< Timestamp of the last keepalive sent */ #endif #if TRACE_JB - pj_oshandle_t trace_jb_fd; /**< Jitter tracing file handle.*/ - char *trace_jb_buf; /**< Jitter tracing buffer. */ + pj_oshandle_t trace_jb_fd; /**< Jitter tracing file handle.*/ + char *trace_jb_buf; /**< Jitter tracing buffer. */ #endif - pjmedia_vid_codec *codec; /**< Codec instance being used. */ - pj_uint32_t last_dec_ts; /**< Last decoded timestamp. */ - int last_dec_seq; /**< Last decoded sequence. */ - pj_uint32_t rtp_tx_err_cnt;/**< The number of RTP - send() error */ - pj_uint32_t rtcp_tx_err_cnt;/**< The number of RTCP - send() error */ + pjmedia_vid_codec *codec; /**< Codec instance being used. */ + pj_uint32_t last_dec_ts; /**< Last decoded timestamp. */ + int last_dec_seq; /**< Last decoded sequence. */ + pj_uint32_t rtp_tx_err_cnt;/**< The number of RTP + send() error */ + pj_uint32_t rtcp_tx_err_cnt;/**< The number of RTCP + send() error */ - pj_timestamp ts_freq; /**< Timestamp frequency. */ + pj_timestamp ts_freq; /**< Timestamp frequency. */ - pj_sockaddr rem_rtp_addr; /**< Remote RTP address */ - unsigned rem_rtp_flag; /**< Indicator flag about - packet from this addr. - 0=no pkt, 1=good ssrc pkts, - 2=bad ssrc pkts */ - pj_sockaddr rtp_src_addr; /**< Actual packet src addr. */ - unsigned rtp_src_cnt; /**< How many pkt from this addr*/ + pj_sockaddr rem_rtp_addr; /**< Remote RTP address */ + unsigned rem_rtp_flag; /**< Indicator flag about + packet from this addr. + 0=no pkt, 1=good ssrc pkts, + 2=bad ssrc pkts */ + pj_sockaddr rtp_src_addr; /**< Actual packet src addr. */ + unsigned rtp_src_cnt; /**< How many pkt from this addr*/ /* RTCP Feedback */ - pj_bool_t send_rtcp_fb_nack; /**< Send NACK? */ - int pending_rtcp_fb_nack; /**< Any pending NACK? */ - int rtcp_fb_nack_cap_idx; /**< RX NACK cap idx. */ - pjmedia_rtcp_fb_nack rtcp_fb_nack; /**< TX NACK state. */ + pj_bool_t send_rtcp_fb_nack; /**< Send NACK? */ + int pending_rtcp_fb_nack; /**< Any pending NACK? */ + int rtcp_fb_nack_cap_idx; /**< RX NACK cap idx. */ + pjmedia_rtcp_fb_nack rtcp_fb_nack; /**< TX NACK state. */ - pj_bool_t send_rtcp_fb_pli; /**< Send PLI? */ - int pending_rtcp_fb_pli; /**< Any pending PLI? */ - int rtcp_fb_pli_cap_idx; /**< RX PLI cap idx. */ + pj_bool_t send_rtcp_fb_pli; /**< Send PLI? */ + int pending_rtcp_fb_pli; /**< Any pending PLI? */ + int rtcp_fb_pli_cap_idx; /**< RX PLI cap idx. */ #if TRACE_RC - unsigned rc_total_sleep; - unsigned rc_total_pkt; - unsigned rc_total_img; - pj_timestamp tx_start; - pj_timestamp tx_end; + unsigned rc_total_sleep; + unsigned rc_total_pkt; + unsigned rc_total_img; + pj_timestamp tx_start; + pj_timestamp tx_end; #endif }; @@ -226,10 +225,10 @@ static pj_status_t decode_frame(pjmedia_vid_stream *stream, static pj_status_t send_rtcp(pjmedia_vid_stream *stream, - pj_bool_t with_sdes, - pj_bool_t with_bye, - pj_bool_t with_fb_nack, - pj_bool_t with_fb_pli); + pj_bool_t with_sdes, + pj_bool_t with_bye, + pj_bool_t with_fb_nack, + pj_bool_t with_fb_pli); static void on_rx_rtcp( void *data, void *pkt, @@ -247,7 +246,7 @@ PJ_INLINE(int) trace_jb_print_timestamp(char **buf, pj_ssize_t len) char *p = *buf; if (len < 14) - return -1; + return -1; pj_gettimeofday(&now); pj_time_decode(&now, &ptime); @@ -266,7 +265,7 @@ PJ_INLINE(int) trace_jb_print_timestamp(char **buf, pj_ssize_t len) } PJ_INLINE(int) trace_jb_print_state(pjmedia_vid_stream *stream, - char **buf, pj_ssize_t len) + char **buf, pj_ssize_t len) { char *p = *buf; char *endp = *buf + len; @@ -275,9 +274,9 @@ PJ_INLINE(int) trace_jb_print_state(pjmedia_vid_stream *stream, pjmedia_jbuf_get_state(stream->jb, &state); len = pj_ansi_snprintf(p, endp-p, "%d, %d, %d", - state.size, state.burst, state.prefetch); + state.size, state.burst, state.prefetch); if ((len < 0) || (len >= endp-p)) - return -1; + return -1; p += len; *buf = p; @@ -285,7 +284,7 @@ PJ_INLINE(int) trace_jb_print_state(pjmedia_vid_stream *stream, } static void trace_jb_get(pjmedia_vid_stream *stream, pjmedia_jb_frame_type ft, - pj_size_t fsize) + pj_size_t fsize) { char *p = stream->trace_jb_buf; char *endp = stream->trace_jb_buf + PJ_LOG_MAX_SIZE; @@ -293,44 +292,44 @@ static void trace_jb_get(pjmedia_vid_stream *stream, pjmedia_jb_frame_type ft, const char* ft_st; if (!TRACE_JB_OPENED(stream)) - return; + return; /* Print timestamp. */ if (trace_jb_print_timestamp(&p, endp-p)) - goto on_insuff_buffer; + goto on_insuff_buffer; /* Print frame type and size */ switch(ft) { - case PJMEDIA_JB_MISSING_FRAME: - ft_st = "missing"; - break; - case PJMEDIA_JB_NORMAL_FRAME: - ft_st = "normal"; - break; - case PJMEDIA_JB_ZERO_PREFETCH_FRAME: - ft_st = "prefetch"; - break; - case PJMEDIA_JB_ZERO_EMPTY_FRAME: - ft_st = "empty"; - break; - default: - ft_st = "unknown"; - break; + case PJMEDIA_JB_MISSING_FRAME: + ft_st = "missing"; + break; + case PJMEDIA_JB_NORMAL_FRAME: + ft_st = "normal"; + break; + case PJMEDIA_JB_ZERO_PREFETCH_FRAME: + ft_st = "prefetch"; + break; + case PJMEDIA_JB_ZERO_EMPTY_FRAME: + ft_st = "empty"; + break; + default: + ft_st = "unknown"; + break; } /* Print operation, size, frame count, frame type */ len = pj_ansi_snprintf(p, endp-p, "GET,%d,1,%s,,,,", fsize, ft_st); if ((len < 0) || (len >= endp-p)) - goto on_insuff_buffer; + goto on_insuff_buffer; p += len; /* Print JB state */ if (trace_jb_print_state(stream, &p, endp-p)) - goto on_insuff_buffer; + goto on_insuff_buffer; /* Print end of line */ if (endp-p < 2) - goto on_insuff_buffer; + goto on_insuff_buffer; *p++ = '\n'; /* Write and flush */ @@ -344,36 +343,36 @@ static void trace_jb_get(pjmedia_vid_stream *stream, pjmedia_jb_frame_type ft, } static void trace_jb_put(pjmedia_vid_stream *stream, - const pjmedia_rtp_hdr *hdr, - unsigned payloadlen, unsigned frame_cnt) + const pjmedia_rtp_hdr *hdr, + unsigned payloadlen, unsigned frame_cnt) { char *p = stream->trace_jb_buf; char *endp = stream->trace_jb_buf + PJ_LOG_MAX_SIZE; pj_ssize_t len = 0; if (!TRACE_JB_OPENED(stream)) - return; + return; /* Print timestamp. */ if (trace_jb_print_timestamp(&p, endp-p)) - goto on_insuff_buffer; + goto on_insuff_buffer; /* Print operation, size, frame count, RTP info */ len = pj_ansi_snprintf(p, endp-p, - "PUT,%d,%d,,%d,%d,%d,", - payloadlen, frame_cnt, - pj_ntohs(hdr->seq), pj_ntohl(hdr->ts), hdr->m); + "PUT,%d,%d,,%d,%d,%d,", + payloadlen, frame_cnt, + pj_ntohs(hdr->seq), pj_ntohl(hdr->ts), hdr->m); if ((len < 0) || (len >= endp-p)) - goto on_insuff_buffer; + goto on_insuff_buffer; p += len; /* Print JB state */ if (trace_jb_print_state(stream, &p, endp-p)) - goto on_insuff_buffer; + goto on_insuff_buffer; /* Print end of line */ if (endp-p < 2) - goto on_insuff_buffer; + goto on_insuff_buffer; *p++ = '\n'; /* Write and flush */ @@ -395,14 +394,14 @@ static void dump_port_info(const pjmedia_vid_channel *chan, char fourcc_name[5]; PJ_LOG(4, (pi->name.ptr, - " %s format %s: %dx%d %s%s %d/%d(~%d)fps", - (chan->dir==PJMEDIA_DIR_DECODING? "Decoding":"Encoding"), - event_name, - pi->fmt.det.vid.size.w, pi->fmt.det.vid.size.h, - pjmedia_fourcc_name(pi->fmt.id, fourcc_name), - (chan->dir==PJMEDIA_DIR_ENCODING?"->":"<-"), - pi->fmt.det.vid.fps.num, pi->fmt.det.vid.fps.denum, - pi->fmt.det.vid.fps.num/pi->fmt.det.vid.fps.denum)); + " %s format %s: %dx%d %s%s %d/%d(~%d)fps", + (chan->dir==PJMEDIA_DIR_DECODING? "Decoding":"Encoding"), + event_name, + pi->fmt.det.vid.size.w, pi->fmt.det.vid.size.h, + pjmedia_fourcc_name(pi->fmt.id, fourcc_name), + (chan->dir==PJMEDIA_DIR_ENCODING?"->":"<-"), + pi->fmt.det.vid.fps.num, pi->fmt.det.vid.fps.denum, + pi->fmt.det.vid.fps.num/pi->fmt.det.vid.fps.denum)); } /* @@ -414,69 +413,69 @@ static pj_status_t stream_event_cb(pjmedia_event *event, pjmedia_vid_stream *stream = (pjmedia_vid_stream*)user_data; if (event->epub == stream->codec) { - /* This is codec event */ - switch (event->type) { - case PJMEDIA_EVENT_FMT_CHANGED: - /* Copy the event to avoid deadlock if we publish the event - * now. This happens because fmt_event may trigger restart - * while we're still holding the stream lock. - */ - pj_memcpy(&stream->fmt_event, event, sizeof(*event)); - return PJ_SUCCESS; - - case PJMEDIA_EVENT_KEYFRAME_MISSING: - /* Republish this event later from get_frame(). */ - pj_memcpy(&stream->miss_keyframe_event, event, sizeof(*event)); - - if (stream->send_rtcp_fb_pli) { - /* Schedule sending RTCP-FB PLI to encoder, if configured, - * also perhaps better to make it redundant, in case the first - * packet is lost. - */ - stream->pending_rtcp_fb_pli = 2; - } - return PJ_SUCCESS; - - default: - break; - } + /* This is codec event */ + switch (event->type) { + case PJMEDIA_EVENT_FMT_CHANGED: + /* Copy the event to avoid deadlock if we publish the event + * now. This happens because fmt_event may trigger restart + * while we're still holding the stream lock. + */ + pj_memcpy(&stream->fmt_event, event, sizeof(*event)); + return PJ_SUCCESS; + + case PJMEDIA_EVENT_KEYFRAME_MISSING: + /* Republish this event later from get_frame(). */ + pj_memcpy(&stream->miss_keyframe_event, event, sizeof(*event)); + + if (stream->send_rtcp_fb_pli) { + /* Schedule sending RTCP-FB PLI to encoder, if configured, + * also perhaps better to make it redundant, in case the first + * packet is lost. + */ + stream->pending_rtcp_fb_pli = 2; + } + return PJ_SUCCESS; + + default: + break; + } } else if (event->epub == &stream->rtcp && - event->type==PJMEDIA_EVENT_RX_RTCP_FB) + event->type==PJMEDIA_EVENT_RX_RTCP_FB) { - /* This is RX RTCP-FB event */ - pjmedia_event_rx_rtcp_fb_data *data = - (pjmedia_event_rx_rtcp_fb_data*)&event->data.rx_rtcp_fb; - - /* Check if configured to listen to the RTCP-FB type */ - if (data->cap.type == PJMEDIA_RTCP_FB_NACK) { - if (data->cap.param.slen == 0 && - stream->rtcp_fb_nack_cap_idx >= 0) - { - /* Generic NACK */ - - /* Update event data capability before republishing */ - data->cap = stream->info.loc_rtcp_fb.caps[ - stream->rtcp_fb_nack_cap_idx]; - } - else if (pj_strcmp2(&data->cap.param, "pli") == 0 && - stream->rtcp_fb_pli_cap_idx >= 0) - { - /* PLI */ - - /* Tell encoder to generate keyframe */ - pjmedia_vid_stream_send_keyframe(stream); - - /* Update event data capability before republishing */ - data->cap = stream->info.loc_rtcp_fb.caps[ - stream->rtcp_fb_pli_cap_idx]; - - } - } + /* This is RX RTCP-FB event */ + pjmedia_event_rx_rtcp_fb_data *data = + (pjmedia_event_rx_rtcp_fb_data*)&event->data.rx_rtcp_fb; + + /* Check if configured to listen to the RTCP-FB type */ + if (data->cap.type == PJMEDIA_RTCP_FB_NACK) { + if (data->cap.param.slen == 0 && + stream->rtcp_fb_nack_cap_idx >= 0) + { + /* Generic NACK */ + + /* Update event data capability before republishing */ + data->cap = stream->info.loc_rtcp_fb.caps[ + stream->rtcp_fb_nack_cap_idx]; + } + else if (pj_strcmp2(&data->cap.param, "pli") == 0 && + stream->rtcp_fb_pli_cap_idx >= 0) + { + /* PLI */ + + /* Tell encoder to generate keyframe */ + pjmedia_vid_stream_send_keyframe(stream); + + /* Update event data capability before republishing */ + data->cap = stream->info.loc_rtcp_fb.caps[ + stream->rtcp_fb_pli_cap_idx]; + + } + } } /* Republish events */ return pjmedia_event_publish(NULL, stream, event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); + PJMEDIA_EVENT_PUBLISH_POST_EVENT); } @@ -484,10 +483,10 @@ static pj_status_t stream_event_cb(pjmedia_event *event, * Publish transport error event. */ static void publish_tp_event(pjmedia_event_type event_type, - pj_status_t status, - pj_bool_t is_rtp, - pjmedia_dir dir, - pjmedia_vid_stream *stream) + pj_status_t status, + pj_bool_t is_rtp, + pjmedia_dir dir, + pjmedia_vid_stream *stream) { pjmedia_event ev; pj_timestamp ts_now; @@ -497,7 +496,7 @@ static void publish_tp_event(pjmedia_event_type event_type, /* Publish event. */ pjmedia_event_init(&ev, event_type, - &ts_now, stream); + &ts_now, stream); ev.data.med_tp_err.type = PJMEDIA_TYPE_VIDEO; ev.data.med_tp_err.is_rtp = is_rtp; ev.data.med_tp_err.dir = dir; @@ -521,23 +520,23 @@ static void send_keep_alive_packet(pjmedia_vid_stream *stream) int pkt_len; if (!stream->transport) - return; + return; TRC_((channel->port.info.name.ptr, - "Sending keep-alive (RTCP and empty RTP)")); + "Sending keep-alive (RTCP and empty RTP)")); /* Send RTP */ status = pjmedia_rtp_encode_rtp( &stream->enc->rtp, - stream->enc->pt, 0, - 1, - 0, - (const void**)&pkt, - &pkt_len); + stream->enc->pt, 0, + 1, + 0, + (const void**)&pkt, + &pkt_len); pj_assert(status == PJ_SUCCESS); pj_memcpy(stream->enc->buf, pkt, pkt_len); pjmedia_transport_send_rtp(stream->transport, stream->enc->buf, - pkt_len); + pkt_len); /* Send RTCP */ send_rtcp(stream, PJ_TRUE, PJ_FALSE, PJ_FALSE, PJ_FALSE); @@ -553,17 +552,17 @@ static void send_keep_alive_packet(pjmedia_vid_stream *stream) const pj_str_t str_ka = PJMEDIA_STREAM_KA_USER_PKT; TRC_((channel->port.info.name.ptr, - "Sending keep-alive (custom RTP/RTCP packets)")); + "Sending keep-alive (custom RTP/RTCP packets)")); /* Send to RTP port */ pj_memcpy(stream->enc->buf, str_ka.ptr, str_ka.slen); pkt_len = str_ka.slen; pjmedia_transport_send_rtp(stream->transport, stream->enc->buf, - pkt_len); + pkt_len); /* Send to RTCP port */ pjmedia_transport_send_rtcp(stream->transport, stream->enc->buf, - pkt_len); + pkt_len); #else @@ -571,14 +570,14 @@ static void send_keep_alive_packet(pjmedia_vid_stream *stream) #endif } -#endif /* defined(PJMEDIA_STREAM_ENABLE_KA) */ +#endif /* defined(PJMEDIA_STREAM_ENABLE_KA) */ static pj_status_t send_rtcp(pjmedia_vid_stream *stream, - pj_bool_t with_sdes, - pj_bool_t with_bye, - pj_bool_t with_fb_nack, - pj_bool_t with_fb_pli) + pj_bool_t with_sdes, + pj_bool_t with_bye, + pj_bool_t with_fb_nack, + pj_bool_t with_fb_pli) { void *sr_rr_pkt; pj_uint8_t *pkt; @@ -589,81 +588,81 @@ static pj_status_t send_rtcp(pjmedia_vid_stream *stream, pjmedia_rtcp_build_rtcp(&stream->rtcp, &sr_rr_pkt, &len); if (with_sdes || with_bye || with_fb_nack || with_fb_pli) { - pkt = (pj_uint8_t*) stream->out_rtcp_pkt; - pj_memcpy(pkt, sr_rr_pkt, len); - max_len = stream->out_rtcp_pkt_size; + pkt = (pj_uint8_t*) stream->out_rtcp_pkt; + pj_memcpy(pkt, sr_rr_pkt, len); + max_len = stream->out_rtcp_pkt_size; } else { - pkt = (pj_uint8_t*)sr_rr_pkt; - max_len = len; + pkt = (pj_uint8_t*)sr_rr_pkt; + max_len = len; } /* Build RTCP SDES packet, forced if also send RTCP-FB */ with_sdes = with_sdes || with_fb_pli || with_fb_nack; if (with_sdes) { - pjmedia_rtcp_sdes sdes; - pj_size_t sdes_len; - - pj_bzero(&sdes, sizeof(sdes)); - sdes.cname = stream->cname; - sdes_len = max_len - len; - status = pjmedia_rtcp_build_rtcp_sdes(&stream->rtcp, pkt+len, - &sdes_len, &sdes); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stream->name.ptr, status, - "Error generating RTCP SDES")); - } else { - len += (int)sdes_len; - } + pjmedia_rtcp_sdes sdes; + pj_size_t sdes_len; + + pj_bzero(&sdes, sizeof(sdes)); + sdes.cname = stream->cname; + sdes_len = max_len - len; + status = pjmedia_rtcp_build_rtcp_sdes(&stream->rtcp, pkt+len, + &sdes_len, &sdes); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stream->name.ptr, status, + "Error generating RTCP SDES")); + } else { + len += (int)sdes_len; + } } /* Build RTCP BYE packet */ if (with_bye) { - pj_size_t bye_len = max_len - len; - status = pjmedia_rtcp_build_rtcp_bye(&stream->rtcp, pkt+len, - &bye_len, NULL); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stream->name.ptr, status, - "Error generating RTCP BYE")); - } else { - len += (int)bye_len; - } + pj_size_t bye_len = max_len - len; + status = pjmedia_rtcp_build_rtcp_bye(&stream->rtcp, pkt+len, + &bye_len, NULL); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stream->name.ptr, status, + "Error generating RTCP BYE")); + } else { + len += (int)bye_len; + } } /* Build RTCP-FB generic NACK packet */ if (with_fb_nack && stream->rtcp_fb_nack.pid >= 0) { - pj_size_t fb_len = max_len - len; - status = pjmedia_rtcp_fb_build_nack(&stream->rtcp, pkt+len, &fb_len, - 1, &stream->rtcp_fb_nack); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stream->name.ptr, status, - "Error generating RTCP-FB NACK")); - } else { - len += (int)fb_len; - } + pj_size_t fb_len = max_len - len; + status = pjmedia_rtcp_fb_build_nack(&stream->rtcp, pkt+len, &fb_len, + 1, &stream->rtcp_fb_nack); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stream->name.ptr, status, + "Error generating RTCP-FB NACK")); + } else { + len += (int)fb_len; + } } /* Build RTCP-FB PLI packet */ if (with_fb_pli) { - pj_size_t fb_len = max_len - len; - status = pjmedia_rtcp_fb_build_pli(&stream->rtcp, pkt+len, &fb_len); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stream->name.ptr, status, - "Error generating RTCP-FB PLI")); - } else { - len += (int)fb_len; - PJ_LOG(5,(stream->name.ptr, "Sending RTCP-FB PLI packet")); - } + pj_size_t fb_len = max_len - len; + status = pjmedia_rtcp_fb_build_pli(&stream->rtcp, pkt+len, &fb_len); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stream->name.ptr, status, + "Error generating RTCP-FB PLI")); + } else { + len += (int)fb_len; + PJ_LOG(5,(stream->name.ptr, "Sending RTCP-FB PLI packet")); + } } /* Send! */ status = pjmedia_transport_send_rtcp(stream->transport, pkt, len); if (status != PJ_SUCCESS) { - if (stream->rtcp_tx_err_cnt++ == 0) { - LOGERR_((stream->name.ptr, status, "Error sending RTCP")); - } - if (stream->rtcp_tx_err_cnt > SEND_ERR_COUNT_TO_REPORT) { - stream->rtcp_tx_err_cnt = 0; - } + if (stream->rtcp_tx_err_cnt++ == 0) { + LOGERR_((stream->name.ptr, status, "Error sending RTCP")); + } + if (stream->rtcp_tx_err_cnt > SEND_ERR_COUNT_TO_REPORT) { + stream->rtcp_tx_err_cnt = 0; + } } return status; } @@ -686,41 +685,41 @@ static void check_tx_rtcp(pjmedia_vid_stream *stream) */ pj_get_timestamp(&now); early = ((stream->pending_rtcp_fb_pli || stream->pending_rtcp_fb_nack) - && - (stream->rtcp_fb_last_tx.u64 == 0 || - pj_elapsed_msec(&stream->rtcp_fb_last_tx, &now) >= - PJMEDIA_RTCP_FB_INTERVAL)); + && + (stream->rtcp_fb_last_tx.u64 == 0 || + pj_elapsed_msec(&stream->rtcp_fb_last_tx, &now) >= + PJMEDIA_RTCP_FB_INTERVAL)); /* First check, unless RTCP is 'urgent', just init rtcp_last_tx. */ if (stream->rtcp_last_tx.u64 == 0 && !early) { - pj_get_timestamp(&stream->rtcp_last_tx); - return; + pj_get_timestamp(&stream->rtcp_last_tx); + return; } /* Build & send RTCP */ if (early || - pj_elapsed_msec(&stream->rtcp_last_tx, &now) >= stream->rtcp_interval) + pj_elapsed_msec(&stream->rtcp_last_tx, &now) >= stream->rtcp_interval) { - pj_status_t status; + pj_status_t status; - status = send_rtcp(stream, !stream->rtcp_sdes_bye_disabled, PJ_FALSE, - stream->pending_rtcp_fb_nack, - stream->pending_rtcp_fb_pli); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stream->name.ptr, status, - "Error sending RTCP")); - } + status = send_rtcp(stream, !stream->rtcp_sdes_bye_disabled, PJ_FALSE, + stream->pending_rtcp_fb_nack, + stream->pending_rtcp_fb_pli); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stream->name.ptr, status, + "Error sending RTCP")); + } - stream->rtcp_last_tx = now; + stream->rtcp_last_tx = now; - if (early) - stream->rtcp_fb_last_tx = now; + if (early) + stream->rtcp_fb_last_tx = now; - if (stream->pending_rtcp_fb_pli) - stream->pending_rtcp_fb_pli--; + if (stream->pending_rtcp_fb_pli) + stream->pending_rtcp_fb_pli--; - if (stream->pending_rtcp_fb_nack) - stream->pending_rtcp_fb_nack--; + if (stream->pending_rtcp_fb_nack) + stream->pending_rtcp_fb_nack--; } } @@ -732,19 +731,19 @@ static void dump_bin(const char *buf, unsigned len) PJ_LOG(3,(THIS_FILE, "begin dump")); for (i=0; iport.info.name.ptr, status, - "Unable to receive RTP packet")); + LOGERR_((channel->port.info.name.ptr, status, + "Unable to receive RTP packet")); - if (status == PJ_ESOCKETSTOP) { - /* Publish receive error event. */ - publish_tp_event(PJMEDIA_EVENT_MEDIA_TP_ERR, status, PJ_TRUE, - PJMEDIA_DIR_DECODING, stream); - } - return; + if (status == PJ_ESOCKETSTOP) { + /* Publish receive error event. */ + publish_tp_event(PJMEDIA_EVENT_MEDIA_TP_ERR, status, PJ_TRUE, + PJMEDIA_DIR_DECODING, stream); + } + return; } /* Ignore keep-alive packets */ if (bytes_read < (pj_ssize_t) sizeof(pjmedia_rtp_hdr)) - return; + return; /* Update RTP and RTCP session. */ status = pjmedia_rtp_decode_rtp(&channel->rtp, pkt, (int)bytes_read, - &hdr, &payload, &payloadlen); + &hdr, &payload, &payloadlen); if (status != PJ_SUCCESS) { - LOGERR_((channel->port.info.name.ptr, status, "RTP decode error")); - stream->rtcp.stat.rx.discard++; - return; + LOGERR_((channel->port.info.name.ptr, status, "RTP decode error")); + stream->rtcp.stat.rx.discard++; + return; } /* Check if multiplexing is allowed and the payload indicates RTCP. */ if (stream->info.rtcp_mux && hdr->pt >= 64 && hdr->pt <= 95) { - on_rx_rtcp(stream, pkt, bytes_read); - return; + on_rx_rtcp(stream, pkt, bytes_read); + return; } /* Ignore the packet if decoder is paused */ if (channel->paused) - goto on_return; + goto on_return; /* Update RTP session (also checks if RTP session can accept * the incoming packet. */ pjmedia_rtp_session_update2(&channel->rtp, hdr, &seq_st, - PJMEDIA_VID_STREAM_CHECK_RTP_PT); + PJMEDIA_VID_STREAM_CHECK_RTP_PT); #if !PJMEDIA_VID_STREAM_CHECK_RTP_PT if (hdr->pt != channel->rtp.out_pt) { - seq_st.status.flag.badpt = 1; + seq_st.status.flag.badpt = 1; } #endif if (seq_st.status.value) { - TRC_ ((channel->port.info.name.ptr, - "RTP status: badpt=%d, badssrc=%d, dup=%d, " - "outorder=%d, probation=%d, restart=%d", - seq_st.status.flag.badpt, - seq_st.status.flag.badssrc, - seq_st.status.flag.dup, - seq_st.status.flag.outorder, - seq_st.status.flag.probation, - seq_st.status.flag.restart)); - - if (seq_st.status.flag.badpt) { - PJ_LOG(4,(channel->port.info.name.ptr, - "Bad RTP pt %d (expecting %d)", - hdr->pt, channel->rtp.out_pt)); - } + TRC_ ((channel->port.info.name.ptr, + "RTP status: badpt=%d, badssrc=%d, dup=%d, " + "outorder=%d, probation=%d, restart=%d", + seq_st.status.flag.badpt, + seq_st.status.flag.badssrc, + seq_st.status.flag.dup, + seq_st.status.flag.outorder, + seq_st.status.flag.probation, + seq_st.status.flag.restart)); + + if (seq_st.status.flag.badpt) { + PJ_LOG(4,(channel->port.info.name.ptr, + "Bad RTP pt %d (expecting %d)", + hdr->pt, channel->rtp.out_pt)); + } - if (!stream->info.has_rem_ssrc && seq_st.status.flag.badssrc) { - PJ_LOG(4,(channel->port.info.name.ptr, - "Changed RTP peer SSRC %d (previously %d)", - channel->rtp.peer_ssrc, stream->rtcp.peer_ssrc)); - stream->rtcp.peer_ssrc = channel->rtp.peer_ssrc; - } + if (!stream->info.has_rem_ssrc && seq_st.status.flag.badssrc) { + PJ_LOG(4,(channel->port.info.name.ptr, + "Changed RTP peer SSRC %d (previously %d)", + channel->rtp.peer_ssrc, stream->rtcp.peer_ssrc)); + stream->rtcp.peer_ssrc = channel->rtp.peer_ssrc; + } } /* Skip bad RTP packet */ if (seq_st.status.flag.bad) { - pkt_discarded = PJ_TRUE; - goto on_return; + pkt_discarded = PJ_TRUE; + goto on_return; } /* Ignore if payloadlen is zero */ if (payloadlen == 0) { - pkt_discarded = PJ_TRUE; - goto on_return; + pkt_discarded = PJ_TRUE; + goto on_return; } /* See if source address of RTP packet is different than the @@ -865,54 +864,54 @@ static void on_rx_rtp( pjmedia_tp_cb_param *param) */ if (param->src_addr) { pj_bool_t badssrc = (stream->info.has_rem_ssrc && - seq_st.status.flag.badssrc); - - if (pj_sockaddr_cmp(&stream->rem_rtp_addr, param->src_addr) == 0) { - /* We're still receiving from rem_rtp_addr. */ - stream->rtp_src_cnt = 0; - stream->rem_rtp_flag = badssrc? 2: 1; - } else { - stream->rtp_src_cnt++; - - if (stream->rtp_src_cnt < PJMEDIA_RTP_NAT_PROBATION_CNT) { - if (stream->rem_rtp_flag == 1 || - (stream->rem_rtp_flag == 2 && badssrc)) - { - /* Only discard if: - * - we have ever received packet with good ssrc from - * remote address (rem_rtp_addr), or - * - we have ever received packet with bad ssrc from - * remote address and this packet also has bad ssrc. - */ - pkt_discarded = PJ_TRUE; - goto on_return; - } - if (stream->info.has_rem_ssrc && !seq_st.status.flag.badssrc - && stream->rem_rtp_flag != 1) - { - /* Immediately switch if we receive packet with the - * correct ssrc AND we never receive packets with - * good ssrc from rem_rtp_addr. - */ - param->rem_switch = PJ_TRUE; - } - } else { - /* Switch. We no longer receive packets from rem_rtp_addr. */ - param->rem_switch = PJ_TRUE; - } - - if (param->rem_switch) { - /* Set remote RTP address to source address */ - pj_sockaddr_cp(&stream->rem_rtp_addr, param->src_addr); - - /* Reset counter and flag */ - stream->rtp_src_cnt = 0; - stream->rem_rtp_flag = badssrc? 2: 1; - - /* Update RTCP peer ssrc */ - stream->rtcp.peer_ssrc = pj_ntohl(hdr->ssrc); - } - } + seq_st.status.flag.badssrc); + + if (pj_sockaddr_cmp(&stream->rem_rtp_addr, param->src_addr) == 0) { + /* We're still receiving from rem_rtp_addr. */ + stream->rtp_src_cnt = 0; + stream->rem_rtp_flag = badssrc? 2: 1; + } else { + stream->rtp_src_cnt++; + + if (stream->rtp_src_cnt < PJMEDIA_RTP_NAT_PROBATION_CNT) { + if (stream->rem_rtp_flag == 1 || + (stream->rem_rtp_flag == 2 && badssrc)) + { + /* Only discard if: + * - we have ever received packet with good ssrc from + * remote address (rem_rtp_addr), or + * - we have ever received packet with bad ssrc from + * remote address and this packet also has bad ssrc. + */ + pkt_discarded = PJ_TRUE; + goto on_return; + } + if (stream->info.has_rem_ssrc && !seq_st.status.flag.badssrc + && stream->rem_rtp_flag != 1) + { + /* Immediately switch if we receive packet with the + * correct ssrc AND we never receive packets with + * good ssrc from rem_rtp_addr. + */ + param->rem_switch = PJ_TRUE; + } + } else { + /* Switch. We no longer receive packets from rem_rtp_addr. */ + param->rem_switch = PJ_TRUE; + } + + if (param->rem_switch) { + /* Set remote RTP address to source address */ + pj_sockaddr_cp(&stream->rem_rtp_addr, param->src_addr); + + /* Reset counter and flag */ + stream->rtp_src_cnt = 0; + stream->rem_rtp_flag = badssrc? 2: 1; + + /* Update RTCP peer ssrc */ + stream->rtcp.peer_ssrc = pj_ntohl(hdr->ssrc); + } + } } pj_grp_lock_acquire( stream->grp_lock ); @@ -922,62 +921,62 @@ static void on_rx_rtp( pjmedia_tp_cb_param *param) */ ts_diff = pj_ntohl(hdr->ts) - stream->dec_frame.timestamp.u32.lo; if (ts_diff != 0 || hdr->m) { - if (PJMEDIA_VID_STREAM_SKIP_PACKETS_TO_REDUCE_LATENCY) { - /* Always decode whenever we have picture in jb and - * overwrite already decoded picture if necessary - */ - pj_size_t old_size = stream->dec_frame.size; - - stream->dec_frame.size = stream->dec_max_size; - if (decode_frame(stream, &stream->dec_frame) != PJ_SUCCESS) { - stream->dec_frame.size = old_size; - } - } else { - /* Only decode if we don't already have decoded one, - * unless the jb is full. - */ - pj_bool_t can_decode = PJ_FALSE; - - if (pjmedia_jbuf_is_full(stream->jb)) { - can_decode = PJ_TRUE; - } - else if (stream->dec_frame.size == 0) { - can_decode = PJ_TRUE; - } - /* For video, checking for a full jbuf above is not very useful - * since video jbuf has a rather large capacity (to accommodate - * many chunks per frame) and thus can typically store frames - * that are much longer than max latency/delay specified in jb_max - * setting. - * So we need to compare the last decoded frame's timestamp with - * the current timestamp. - */ - else if (ts_diff > (long)stream->dec_max_delay) { - can_decode = PJ_TRUE; - } - - if (can_decode) { - stream->dec_frame.size = stream->dec_max_size; - if (decode_frame(stream, &stream->dec_frame) != PJ_SUCCESS) { - stream->dec_frame.size = 0; - } - } - } + if (PJMEDIA_VID_STREAM_SKIP_PACKETS_TO_REDUCE_LATENCY) { + /* Always decode whenever we have picture in jb and + * overwrite already decoded picture if necessary + */ + pj_size_t old_size = stream->dec_frame.size; + + stream->dec_frame.size = stream->dec_max_size; + if (decode_frame(stream, &stream->dec_frame) != PJ_SUCCESS) { + stream->dec_frame.size = old_size; + } + } else { + /* Only decode if we don't already have decoded one, + * unless the jb is full. + */ + pj_bool_t can_decode = PJ_FALSE; + + if (pjmedia_jbuf_is_full(stream->jb)) { + can_decode = PJ_TRUE; + } + else if (stream->dec_frame.size == 0) { + can_decode = PJ_TRUE; + } + /* For video, checking for a full jbuf above is not very useful + * since video jbuf has a rather large capacity (to accommodate + * many chunks per frame) and thus can typically store frames + * that are much longer than max latency/delay specified in jb_max + * setting. + * So we need to compare the last decoded frame's timestamp with + * the current timestamp. + */ + else if (ts_diff > (long)stream->dec_max_delay) { + can_decode = PJ_TRUE; + } + + if (can_decode) { + stream->dec_frame.size = stream->dec_max_size; + if (decode_frame(stream, &stream->dec_frame) != PJ_SUCCESS) { + stream->dec_frame.size = 0; + } + } + } } /* Put "good" packet to jitter buffer, or reset the jitter buffer * when RTP session is restarted. */ if (seq_st.status.flag.restart) { - status = pjmedia_jbuf_reset(stream->jb); - PJ_LOG(4,(channel->port.info.name.ptr, "Jitter buffer reset")); + status = pjmedia_jbuf_reset(stream->jb); + PJ_LOG(4,(channel->port.info.name.ptr, "Jitter buffer reset")); } else { - /* Just put the payload into jitter buffer */ - pjmedia_jbuf_put_frame3(stream->jb, payload, payloadlen, 0, - pj_ntohs(hdr->seq), pj_ntohl(hdr->ts), NULL); + /* Just put the payload into jitter buffer */ + pjmedia_jbuf_put_frame3(stream->jb, payload, payloadlen, 0, + pj_ntohs(hdr->seq), pj_ntohl(hdr->ts), NULL); #if TRACE_JB - trace_jb_put(stream, hdr, payloadlen, count); + trace_jb_put(stream, hdr, payloadlen, count); #endif } @@ -985,16 +984,16 @@ static void on_rx_rtp( pjmedia_tp_cb_param *param) /* Check if we need to send RTCP-FB generic NACK */ if (stream->send_rtcp_fb_nack && seq_st.diff > 1 && - pj_ntohs(hdr->seq) >= seq_st.diff) + pj_ntohs(hdr->seq) >= seq_st.diff) { - int i; - pj_bzero(&stream->rtcp_fb_nack, sizeof(stream->rtcp_fb_nack)); - stream->rtcp_fb_nack.pid = pj_ntohs(hdr->seq) - seq_st.diff + 1; - for (i = 0; i < (seq_st.diff - 1); ++i) { - stream->rtcp_fb_nack.blp <<= 1; - stream->rtcp_fb_nack.blp |= 1; - } - stream->pending_rtcp_fb_nack = 1; + int i; + pj_bzero(&stream->rtcp_fb_nack, sizeof(stream->rtcp_fb_nack)); + stream->rtcp_fb_nack.pid = pj_ntohs(hdr->seq) - seq_st.diff + 1; + for (i = 0; i < (seq_st.diff - 1); ++i) { + stream->rtcp_fb_nack.blp <<= 1; + stream->rtcp_fb_nack.blp |= 1; + } + stream->pending_rtcp_fb_nack = 1; } /* Check if now is the time to transmit RTCP SR/RR report. @@ -1003,34 +1002,34 @@ static void on_rx_rtp( pjmedia_tp_cb_param *param) * because otherwise check_tx_rtcp() will be handled by put_frame() */ if (stream->dir == PJMEDIA_DIR_DECODING || stream->enc->paused) { - check_tx_rtcp(stream); + check_tx_rtcp(stream); } if (status != 0) { - LOGERR_((channel->port.info.name.ptr, status, - "Jitter buffer put() error")); - pkt_discarded = PJ_TRUE; - goto on_return; + LOGERR_((channel->port.info.name.ptr, status, + "Jitter buffer put() error")); + pkt_discarded = PJ_TRUE; + goto on_return; } on_return: /* Update RTCP session */ if (stream->rtcp.peer_ssrc == 0) - stream->rtcp.peer_ssrc = channel->rtp.peer_ssrc; + stream->rtcp.peer_ssrc = channel->rtp.peer_ssrc; pjmedia_rtcp_rx_rtp2(&stream->rtcp, pj_ntohs(hdr->seq), - pj_ntohl(hdr->ts), payloadlen, pkt_discarded); + pj_ntohl(hdr->ts), payloadlen, pkt_discarded); /* Send RTCP RR and SDES after we receive some RTP packets */ if (stream->rtcp.received >= 10 && !stream->initial_rr) { - status = send_rtcp(stream, !stream->rtcp_sdes_bye_disabled, - PJ_FALSE, PJ_FALSE, PJ_FALSE); + status = send_rtcp(stream, !stream->rtcp_sdes_bye_disabled, + PJ_FALSE, PJ_FALSE, PJ_FALSE); if (status != PJ_SUCCESS) { PJ_PERROR(4,(stream->name.ptr, status, - "Error sending initial RTCP RR")); - } else { - stream->initial_rr = PJ_TRUE; - } + "Error sending initial RTCP RR")); + } else { + stream->initial_rr = PJ_TRUE; + } } } @@ -1048,17 +1047,17 @@ static void on_rx_rtcp( void *data, /* Check for errors */ if (bytes_read < 0) { - status = (pj_status_t)-bytes_read; - if (status == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK)) { - return; - } - LOGERR_((stream->cname.ptr, status, "Unable to receive RTCP packet")); - if (status == PJ_ESOCKETSTOP) { - /* Publish receive error event. */ - publish_tp_event(PJMEDIA_EVENT_MEDIA_TP_ERR, status, PJ_FALSE, - PJMEDIA_DIR_DECODING, stream); - } - return; + status = (pj_status_t)-bytes_read; + if (status == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK)) { + return; + } + LOGERR_((stream->cname.ptr, status, "Unable to receive RTCP packet")); + if (status == PJ_ESOCKETSTOP) { + /* Publish receive error event. */ + publish_tp_event(PJMEDIA_EVENT_MEDIA_TP_ERR, status, PJ_FALSE, + PJMEDIA_DIR_DECODING, stream); + } + return; } pjmedia_rtcp_rx_rtcp(&stream->rtcp, pkt, bytes_read); @@ -1089,16 +1088,16 @@ static pj_status_t put_frame(pjmedia_port *port, if (stream->use_ka) { pj_uint32_t dtx_duration, ka_interval; - pj_time_val tm_now, tmp; + pj_time_val tm_now, tmp; - pj_gettimeofday(&tm_now); + pj_gettimeofday(&tm_now); - tmp = tm_now; - PJ_TIME_VAL_SUB(tmp, stream->last_frm_ts_sent); - dtx_duration = PJ_TIME_VAL_MSEC(tmp); + tmp = tm_now; + PJ_TIME_VAL_SUB(tmp, stream->last_frm_ts_sent); + dtx_duration = PJ_TIME_VAL_MSEC(tmp); if (stream->start_ka_count) { - ka_interval = stream->start_ka_interval; + ka_interval = stream->start_ka_interval; } else { ka_interval = stream->ka_interval * 1000; } @@ -1116,22 +1115,22 @@ static pj_status_t put_frame(pjmedia_port *port, /* Don't do anything if stream is paused, except updating RTP timestamp */ if (channel->paused) { - /* Update RTP session's timestamp. */ - status = pjmedia_rtp_encode_rtp( &channel->rtp, 0, 0, 0, rtp_ts_len, - NULL, NULL); + /* Update RTP session's timestamp. */ + status = pjmedia_rtp_encode_rtp( &channel->rtp, 0, 0, 0, rtp_ts_len, + NULL, NULL); /* Update RTCP stats with last RTP timestamp. */ - stream->rtcp.stat.rtp_tx_last_ts = + stream->rtcp.stat.rtp_tx_last_ts = pj_ntohl(channel->rtp.out_hdr.ts); - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Empty video frame? Just update RTP timestamp for now */ if (frame->type==PJMEDIA_FRAME_TYPE_VIDEO && frame->size==0) { - pjmedia_rtp_encode_rtp(&channel->rtp, channel->pt, 1, 0, - rtp_ts_len, (const void**)&rtphdr, - &rtphdrlen); - return PJ_SUCCESS; + pjmedia_rtp_encode_rtp(&channel->rtp, channel->pt, 1, 0, + rtp_ts_len, (const void**)&rtphdr, + &rtphdrlen); + return PJ_SUCCESS; } /* Init frame_out buffer. */ @@ -1141,29 +1140,29 @@ static pj_status_t put_frame(pjmedia_port *port, /* Check if need to send keyframe. */ pj_get_timestamp(&now); if (stream->num_keyframe && - (pj_cmp_timestamp(&null_ts, &stream->last_keyframe_tx) != 0)) + (pj_cmp_timestamp(&null_ts, &stream->last_keyframe_tx) != 0)) { - unsigned elapse_time; + unsigned elapse_time; - elapse_time = pj_elapsed_msec(&stream->last_keyframe_tx, &now); - if (elapse_time > stream->info.sk_cfg.interval) - { - stream->force_keyframe = PJ_TRUE; - --stream->num_keyframe; - } + elapse_time = pj_elapsed_msec(&stream->last_keyframe_tx, &now); + if (elapse_time > stream->info.sk_cfg.interval) + { + stream->force_keyframe = PJ_TRUE; + --stream->num_keyframe; + } } /* Init encoding option */ pj_bzero(&enc_opt, sizeof(enc_opt)); if (stream->force_keyframe && - pj_elapsed_msec(&stream->last_keyframe_tx, &now) >= - PJMEDIA_VID_STREAM_MIN_KEYFRAME_INTERVAL_MSEC) + pj_elapsed_msec(&stream->last_keyframe_tx, &now) >= + PJMEDIA_VID_STREAM_MIN_KEYFRAME_INTERVAL_MSEC) { - /* Force encoder to generate keyframe */ - enc_opt.force_keyframe = PJ_TRUE; - stream->force_keyframe = PJ_FALSE; - TRC_((channel->port.info.name.ptr, - "Forcing encoder to generate keyframe")); + /* Force encoder to generate keyframe */ + enc_opt.force_keyframe = PJ_TRUE; + stream->force_keyframe = PJ_FALSE; + TRC_((channel->port.info.name.ptr, + "Forcing encoder to generate keyframe")); } /* Encode! */ @@ -1173,127 +1172,127 @@ static pj_status_t put_frame(pjmedia_port *port, &frame_out, &has_more_data); if (status != PJ_SUCCESS) { - LOGERR_((channel->port.info.name.ptr, status, - "Codec encode_begin() error")); + LOGERR_((channel->port.info.name.ptr, status, + "Codec encode_begin() error")); - /* Update RTP timestamp */ - pjmedia_rtp_encode_rtp(&channel->rtp, channel->pt, 1, 0, - rtp_ts_len, (const void**)&rtphdr, - &rtphdrlen); - return status; + /* Update RTP timestamp */ + pjmedia_rtp_encode_rtp(&channel->rtp, channel->pt, 1, 0, + rtp_ts_len, (const void**)&rtphdr, + &rtphdrlen); + return status; } pj_get_timestamp(&initial_time); if ((frame_out.bit_info & PJMEDIA_VID_FRM_KEYFRAME) - == PJMEDIA_VID_FRM_KEYFRAME) + == PJMEDIA_VID_FRM_KEYFRAME) { - stream->last_keyframe_tx = initial_time; - TRC_((channel->port.info.name.ptr, "Keyframe generated")); + stream->last_keyframe_tx = initial_time; + TRC_((channel->port.info.name.ptr, "Keyframe generated")); } /* Loop while we have frame to send */ for (;;) { - status = pjmedia_rtp_encode_rtp(&channel->rtp, - channel->pt, - (has_more_data == PJ_FALSE ? 1 : 0), - (int)frame_out.size, - rtp_ts_len, - (const void**)&rtphdr, - &rtphdrlen); - if (status != PJ_SUCCESS) { - LOGERR_((channel->port.info.name.ptr, status, - "RTP encode_rtp() error")); - return status; - } - - /* When the payload length is zero, we should not send anything, - * but proceed the rest normally. - */ - if (frame_out.size != 0 && stream->transport) { - /* Copy RTP header to the beginning of packet */ - pj_memcpy(channel->buf, rtphdr, sizeof(pjmedia_rtp_hdr)); - - /* Send the RTP packet to the transport. */ - status = pjmedia_transport_send_rtp(stream->transport, - (char*)channel->buf, - frame_out.size + - sizeof(pjmedia_rtp_hdr)); - if (status != PJ_SUCCESS) { - if (stream->rtp_tx_err_cnt++ == 0) { - LOGERR_((channel->port.info.name.ptr, status, - "Error sending RTP")); - } - if (stream->rtp_tx_err_cnt > SEND_ERR_COUNT_TO_REPORT) { - stream->rtp_tx_err_cnt = 0; - } - } - pjmedia_rtcp_tx_rtp(&stream->rtcp, (unsigned)frame_out.size); - total_sent += frame_out.size; - pkt_cnt++; - } - - if (!has_more_data) - break; - - /* Next packets use same timestamp */ - rtp_ts_len = 0; - - frame_out.size = 0; - - /* Encode more! */ - status = pjmedia_vid_codec_encode_more(stream->codec, - channel->buf_size - - sizeof(pjmedia_rtp_hdr), - &frame_out, - &has_more_data); - if (status != PJ_SUCCESS) { - LOGERR_((channel->port.info.name.ptr, status, - "Codec encode_more() error")); - /* Ignore this error (?) */ - break; - } - - /* Send rate control */ - if (stream->info.rc_cfg.method==PJMEDIA_VID_STREAM_RC_SIMPLE_BLOCKING) - { - pj_timestamp next_send_ts, total_send_ts; - - total_send_ts.u64 = total_sent * stream->ts_freq.u64 * 8 / - stream->info.rc_cfg.bandwidth; - next_send_ts = initial_time; - pj_add_timestamp(&next_send_ts, &total_send_ts); - - pj_get_timestamp(&now); - if (pj_cmp_timestamp(&now, &next_send_ts) < 0) { - unsigned ms_sleep; - ms_sleep = pj_elapsed_msec(&now, &next_send_ts); - - if (ms_sleep > 10) - ms_sleep = 10; - - pj_thread_sleep(ms_sleep); - } - } + status = pjmedia_rtp_encode_rtp(&channel->rtp, + channel->pt, + (has_more_data == PJ_FALSE ? 1 : 0), + (int)frame_out.size, + rtp_ts_len, + (const void**)&rtphdr, + &rtphdrlen); + if (status != PJ_SUCCESS) { + LOGERR_((channel->port.info.name.ptr, status, + "RTP encode_rtp() error")); + return status; + } + + /* When the payload length is zero, we should not send anything, + * but proceed the rest normally. + */ + if (frame_out.size != 0 && stream->transport) { + /* Copy RTP header to the beginning of packet */ + pj_memcpy(channel->buf, rtphdr, sizeof(pjmedia_rtp_hdr)); + + /* Send the RTP packet to the transport. */ + status = pjmedia_transport_send_rtp(stream->transport, + (char*)channel->buf, + frame_out.size + + sizeof(pjmedia_rtp_hdr)); + if (status != PJ_SUCCESS) { + if (stream->rtp_tx_err_cnt++ == 0) { + LOGERR_((channel->port.info.name.ptr, status, + "Error sending RTP")); + } + if (stream->rtp_tx_err_cnt > SEND_ERR_COUNT_TO_REPORT) { + stream->rtp_tx_err_cnt = 0; + } + } + pjmedia_rtcp_tx_rtp(&stream->rtcp, (unsigned)frame_out.size); + total_sent += frame_out.size; + pkt_cnt++; + } + + if (!has_more_data) + break; + + /* Next packets use same timestamp */ + rtp_ts_len = 0; + + frame_out.size = 0; + + /* Encode more! */ + status = pjmedia_vid_codec_encode_more(stream->codec, + channel->buf_size - + sizeof(pjmedia_rtp_hdr), + &frame_out, + &has_more_data); + if (status != PJ_SUCCESS) { + LOGERR_((channel->port.info.name.ptr, status, + "Codec encode_more() error")); + /* Ignore this error (?) */ + break; + } + + /* Send rate control */ + if (stream->info.rc_cfg.method==PJMEDIA_VID_STREAM_RC_SIMPLE_BLOCKING) + { + pj_timestamp next_send_ts, total_send_ts; + + total_send_ts.u64 = total_sent * stream->ts_freq.u64 * 8 / + stream->info.rc_cfg.bandwidth; + next_send_ts = initial_time; + pj_add_timestamp(&next_send_ts, &total_send_ts); + + pj_get_timestamp(&now); + if (pj_cmp_timestamp(&now, &next_send_ts) < 0) { + unsigned ms_sleep; + ms_sleep = pj_elapsed_msec(&now, &next_send_ts); + + if (ms_sleep > 10) + ms_sleep = 10; + + pj_thread_sleep(ms_sleep); + } + } } #if TRACE_RC /* Trace log for rate control */ { - pj_timestamp end_time; - unsigned total_sleep; + pj_timestamp end_time; + unsigned total_sleep; - pj_get_timestamp(&end_time); - total_sleep = pj_elapsed_msec(&initial_time, &end_time); - PJ_LOG(5, (stream->name.ptr, "total pkt=%d size=%d sleep=%d", - pkt_cnt, total_sent, total_sleep)); + pj_get_timestamp(&end_time); + total_sleep = pj_elapsed_msec(&initial_time, &end_time); + PJ_LOG(5, (stream->name.ptr, "total pkt=%d size=%d sleep=%d", + pkt_cnt, total_sent, total_sleep)); - if (stream->tx_start.u64 == 0) - stream->tx_start = initial_time; - stream->tx_end = end_time; - stream->rc_total_pkt += pkt_cnt; - stream->rc_total_sleep += total_sleep; - stream->rc_total_img++; + if (stream->tx_start.u64 == 0) + stream->tx_start = initial_time; + stream->tx_end = end_time; + stream->rc_total_pkt += pkt_cnt; + stream->rc_total_sleep += total_sleep; + stream->rc_total_img++; } #endif @@ -1302,20 +1301,20 @@ static pj_status_t put_frame(pjmedia_port *port, * when it is, check_tx_rtcp() will be handled by get_frame(). */ if (stream->dir != PJMEDIA_DIR_DECODING && stream->transport) { - check_tx_rtcp(stream); + check_tx_rtcp(stream); } /* Do nothing if we have nothing to transmit */ if (total_sent == 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Update stat */ if (pkt_cnt) { - stream->rtcp.stat.rtp_tx_last_ts = - pj_ntohl(stream->enc->rtp.out_hdr.ts); - stream->rtcp.stat.rtp_tx_last_seq = - pj_ntohs(stream->enc->rtp.out_hdr.seq); + stream->rtcp.stat.rtp_tx_last_ts = + pj_ntohl(stream->enc->rtp.out_hdr.ts); + stream->rtcp.stat.rtp_tx_last_seq = + pj_ntohs(stream->enc->rtp.out_hdr.seq); } #if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0 @@ -1344,191 +1343,191 @@ static pj_status_t decode_frame(pjmedia_vid_stream *stream, /* Check if we got a decodable frame */ for (cnt=0; ; ) { - char ptype; - pj_uint32_t ts; - int seq; - - /* Peek frame from jitter buffer. */ - pjmedia_jbuf_peek_frame(stream->jb, cnt, NULL, NULL, - &ptype, NULL, &ts, &seq); - if (ptype == PJMEDIA_JB_NORMAL_FRAME) { - if (stream->last_dec_ts == ts) { - /* Remove any late packet (the frame has been decoded) */ - pjmedia_jbuf_remove_frame(stream->jb, 1); - continue; - } - - if (!last_ts_inited) { - last_ts = ts; - - /* Init timestamp and first seq of the first frame */ - frm_ts = ts; - frm_first_seq = seq; - last_ts_inited = PJ_TRUE; - } - if (ts != last_ts) { - last_ts = ts; - if (frm_pkt_cnt == 0) - frm_pkt_cnt = cnt; - - /* Is it time to decode? Check with minimum delay setting */ - if (++frm_cnt == stream->dec_delay_cnt) { - got_frame = PJ_TRUE; - break; - } - } - } else if (ptype == PJMEDIA_JB_ZERO_EMPTY_FRAME) { - /* No more packet in the jitter buffer */ - break; - } - - ++cnt; + char ptype; + pj_uint32_t ts; + int seq; + + /* Peek frame from jitter buffer. */ + pjmedia_jbuf_peek_frame(stream->jb, cnt, NULL, NULL, + &ptype, NULL, &ts, &seq); + if (ptype == PJMEDIA_JB_NORMAL_FRAME) { + if (stream->last_dec_ts == ts) { + /* Remove any late packet (the frame has been decoded) */ + pjmedia_jbuf_remove_frame(stream->jb, 1); + continue; + } + + if (!last_ts_inited) { + last_ts = ts; + + /* Init timestamp and first seq of the first frame */ + frm_ts = ts; + frm_first_seq = seq; + last_ts_inited = PJ_TRUE; + } + if (ts != last_ts) { + last_ts = ts; + if (frm_pkt_cnt == 0) + frm_pkt_cnt = cnt; + + /* Is it time to decode? Check with minimum delay setting */ + if (++frm_cnt == stream->dec_delay_cnt) { + got_frame = PJ_TRUE; + break; + } + } + } else if (ptype == PJMEDIA_JB_ZERO_EMPTY_FRAME) { + /* No more packet in the jitter buffer */ + break; + } + + ++cnt; } if (got_frame) { - unsigned i; - - /* Exclude any MISSING frames in the end of the packets array, as - * it may be part of the next video frame (late packets). - */ - for (; frm_pkt_cnt > 1; --frm_pkt_cnt) { - char ptype; - pjmedia_jbuf_peek_frame(stream->jb, frm_pkt_cnt, NULL, NULL, &ptype, - NULL, NULL, NULL); - if (ptype == PJMEDIA_JB_NORMAL_FRAME) - break; - } - - /* Check if the packet count for this frame exceeds the limit */ - if (frm_pkt_cnt > stream->rx_frame_cnt) { - PJ_LOG(1,(channel->port.info.name.ptr, - "Discarding %u frames because array is full!", - frm_pkt_cnt - stream->rx_frame_cnt)); - pjmedia_jbuf_remove_frame(stream->jb, - frm_pkt_cnt - stream->rx_frame_cnt); - frm_pkt_cnt = stream->rx_frame_cnt; - } - - /* Generate frame bitstream from the payload */ - for (i = 0; i < frm_pkt_cnt; ++i) { - char ptype; - - stream->rx_frames[i].type = PJMEDIA_FRAME_TYPE_VIDEO; - stream->rx_frames[i].timestamp.u64 = frm_ts; - stream->rx_frames[i].bit_info = 0; - - /* We use jbuf_peek_frame() as it will returns the pointer of - * the payload (no buffer and memcpy needed), just as we need. - */ - pjmedia_jbuf_peek_frame(stream->jb, i, - (const void**)&stream->rx_frames[i].buf, - &stream->rx_frames[i].size, &ptype, - NULL, NULL, &frm_last_seq); - - if (ptype != PJMEDIA_JB_NORMAL_FRAME) { - /* Packet lost, must set payload to NULL and keep going */ - stream->rx_frames[i].buf = NULL; - stream->rx_frames[i].size = 0; - stream->rx_frames[i].type = PJMEDIA_FRAME_TYPE_NONE; - continue; - } - } - - /* Decode */ - status = pjmedia_vid_codec_decode(stream->codec, frm_pkt_cnt, - stream->rx_frames, - (unsigned)frame->size, frame); - if (status != PJ_SUCCESS) { - LOGERR_((channel->port.info.name.ptr, status, - "codec decode() error")); - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - } - - pjmedia_jbuf_remove_frame(stream->jb, frm_pkt_cnt); + unsigned i; + + /* Exclude any MISSING frames in the end of the packets array, as + * it may be part of the next video frame (late packets). + */ + for (; frm_pkt_cnt > 1; --frm_pkt_cnt) { + char ptype; + pjmedia_jbuf_peek_frame(stream->jb, frm_pkt_cnt, NULL, NULL, &ptype, + NULL, NULL, NULL); + if (ptype == PJMEDIA_JB_NORMAL_FRAME) + break; + } + + /* Check if the packet count for this frame exceeds the limit */ + if (frm_pkt_cnt > stream->rx_frame_cnt) { + PJ_LOG(1,(channel->port.info.name.ptr, + "Discarding %u frames because array is full!", + frm_pkt_cnt - stream->rx_frame_cnt)); + pjmedia_jbuf_remove_frame(stream->jb, + frm_pkt_cnt - stream->rx_frame_cnt); + frm_pkt_cnt = stream->rx_frame_cnt; + } + + /* Generate frame bitstream from the payload */ + for (i = 0; i < frm_pkt_cnt; ++i) { + char ptype; + + stream->rx_frames[i].type = PJMEDIA_FRAME_TYPE_VIDEO; + stream->rx_frames[i].timestamp.u64 = frm_ts; + stream->rx_frames[i].bit_info = 0; + + /* We use jbuf_peek_frame() as it will returns the pointer of + * the payload (no buffer and memcpy needed), just as we need. + */ + pjmedia_jbuf_peek_frame(stream->jb, i, + (const void**)&stream->rx_frames[i].buf, + &stream->rx_frames[i].size, &ptype, + NULL, NULL, &frm_last_seq); + + if (ptype != PJMEDIA_JB_NORMAL_FRAME) { + /* Packet lost, must set payload to NULL and keep going */ + stream->rx_frames[i].buf = NULL; + stream->rx_frames[i].size = 0; + stream->rx_frames[i].type = PJMEDIA_FRAME_TYPE_NONE; + continue; + } + } + + /* Decode */ + status = pjmedia_vid_codec_decode(stream->codec, frm_pkt_cnt, + stream->rx_frames, + (unsigned)frame->size, frame); + if (status != PJ_SUCCESS) { + LOGERR_((channel->port.info.name.ptr, status, + "codec decode() error")); + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + } + + pjmedia_jbuf_remove_frame(stream->jb, frm_pkt_cnt); } /* Learn remote frame rate after successful decoding */ if (got_frame && frame->type == PJMEDIA_FRAME_TYPE_VIDEO && frame->size) { - /* Only check remote frame rate when timestamp is not wrapping and - * sequence is increased by 1. - */ - if (frm_ts > stream->last_dec_ts && - frm_first_seq - stream->last_dec_seq == 1) - { - pj_uint32_t ts_diff; - pjmedia_ratio new_fps; - - ts_diff = frm_ts - stream->last_dec_ts; - - /* Calculate new FPS based on RTP timestamp diff */ - if (stream->info.codec_info.clock_rate % ts_diff == 0) { - new_fps.num = stream->info.codec_info.clock_rate/ts_diff; - new_fps.denum = 1; - } else { - new_fps.num = stream->info.codec_info.clock_rate; - new_fps.denum = ts_diff; - } - - /* Only apply the new FPS when it is >0, <=100, and increasing */ - if (new_fps.num/new_fps.denum <= 100 && - new_fps.num/new_fps.denum > 0 && - new_fps.num*1.0/new_fps.denum > - stream->dec_max_fps.num*1.0/stream->dec_max_fps.denum) - { - pjmedia_video_format_detail *vfd; - vfd = pjmedia_format_get_video_format_detail( - &channel->port.info.fmt, PJ_TRUE); - - /* Update FPS in channel & stream info */ - vfd->fps = new_fps; - stream->info.codec_param->dec_fmt.det.vid.fps = new_fps; - - /* Update the decoding delay */ - { - pjmedia_jb_state jb_state; - pjmedia_jbuf_get_state(stream->jb, &jb_state); - - stream->dec_delay_cnt = - ((PJMEDIA_VID_STREAM_DECODE_MIN_DELAY_MSEC * - vfd->fps.num) + - (1000 * vfd->fps.denum) - 1) / - (1000 * vfd->fps.denum); - if (stream->dec_delay_cnt < 1) - stream->dec_delay_cnt = 1; - if (stream->dec_delay_cnt > jb_state.max_count * 4/5) - stream->dec_delay_cnt = jb_state.max_count * 4/5; - } - - /* Publish PJMEDIA_EVENT_FMT_CHANGED event */ - { - pjmedia_event *event = &stream->fmt_event; - - /* Update max fps of decoding dir */ - stream->dec_max_fps = vfd->fps; - - /* Use the buffered format changed event: - * - just update the framerate if there is pending event, - * - otherwise, init the whole event. - */ - if (stream->fmt_event.type != PJMEDIA_EVENT_NONE) { - event->data.fmt_changed.new_fmt.det.vid.fps = vfd->fps; - } else { - pjmedia_event_init(event, PJMEDIA_EVENT_FMT_CHANGED, - &frame->timestamp, &channel->port); - event->data.fmt_changed.dir = PJMEDIA_DIR_DECODING; - pj_memcpy(&event->data.fmt_changed.new_fmt, - &stream->info.codec_param->dec_fmt, - sizeof(pjmedia_format)); - } - } - } - } - - /* Update last frame seq and timestamp */ - stream->last_dec_seq = frm_last_seq; - stream->last_dec_ts = frm_ts; + /* Only check remote frame rate when timestamp is not wrapping and + * sequence is increased by 1. + */ + if (frm_ts > stream->last_dec_ts && + frm_first_seq - stream->last_dec_seq == 1) + { + pj_uint32_t ts_diff; + pjmedia_ratio new_fps; + + ts_diff = frm_ts - stream->last_dec_ts; + + /* Calculate new FPS based on RTP timestamp diff */ + if (stream->info.codec_info.clock_rate % ts_diff == 0) { + new_fps.num = stream->info.codec_info.clock_rate/ts_diff; + new_fps.denum = 1; + } else { + new_fps.num = stream->info.codec_info.clock_rate; + new_fps.denum = ts_diff; + } + + /* Only apply the new FPS when it is >0, <=100, and increasing */ + if (new_fps.num/new_fps.denum <= 100 && + new_fps.num/new_fps.denum > 0 && + new_fps.num*1.0/new_fps.denum > + stream->dec_max_fps.num*1.0/stream->dec_max_fps.denum) + { + pjmedia_video_format_detail *vfd; + vfd = pjmedia_format_get_video_format_detail( + &channel->port.info.fmt, PJ_TRUE); + + /* Update FPS in channel & stream info */ + vfd->fps = new_fps; + stream->info.codec_param->dec_fmt.det.vid.fps = new_fps; + + /* Update the decoding delay */ + { + pjmedia_jb_state jb_state; + pjmedia_jbuf_get_state(stream->jb, &jb_state); + + stream->dec_delay_cnt = + ((PJMEDIA_VID_STREAM_DECODE_MIN_DELAY_MSEC * + vfd->fps.num) + + (1000 * vfd->fps.denum) - 1) / + (1000 * vfd->fps.denum); + if (stream->dec_delay_cnt < 1) + stream->dec_delay_cnt = 1; + if (stream->dec_delay_cnt > jb_state.max_count * 4/5) + stream->dec_delay_cnt = jb_state.max_count * 4/5; + } + + /* Publish PJMEDIA_EVENT_FMT_CHANGED event */ + { + pjmedia_event *event = &stream->fmt_event; + + /* Update max fps of decoding dir */ + stream->dec_max_fps = vfd->fps; + + /* Use the buffered format changed event: + * - just update the framerate if there is pending event, + * - otherwise, init the whole event. + */ + if (stream->fmt_event.type != PJMEDIA_EVENT_NONE) { + event->data.fmt_changed.new_fmt.det.vid.fps = vfd->fps; + } else { + pjmedia_event_init(event, PJMEDIA_EVENT_FMT_CHANGED, + &frame->timestamp, &channel->port); + event->data.fmt_changed.dir = PJMEDIA_DIR_DECODING; + pj_memcpy(&event->data.fmt_changed.new_fmt, + &stream->info.codec_param->dec_fmt, + sizeof(pjmedia_format)); + } + } + } + } + + /* Update last frame seq and timestamp */ + stream->last_dec_seq = frm_last_seq; + stream->last_dec_ts = frm_ts; } return got_frame ? PJ_SUCCESS : PJ_ENOTFOUND; @@ -1543,9 +1542,9 @@ static pj_status_t get_frame(pjmedia_port *port, /* Return no frame is channel is paused */ if (channel->paused) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - return PJ_SUCCESS; + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + return PJ_SUCCESS; } /* Report pending events. Do not publish the event while holding the @@ -1554,69 +1553,69 @@ static pj_status_t get_frame(pjmedia_port *port, * would only occur once during the start of the media. */ if (stream->fmt_event.type != PJMEDIA_EVENT_NONE) { - pjmedia_event_fmt_changed_data *fmt_chg_data; - - fmt_chg_data = &stream->fmt_event.data.fmt_changed; - - /* Update stream info and decoding channel port info */ - if (fmt_chg_data->dir == PJMEDIA_DIR_DECODING) { - pjmedia_format_copy(&stream->info.codec_param->dec_fmt, - &fmt_chg_data->new_fmt); - pjmedia_format_copy(&stream->dec->port.info.fmt, - &fmt_chg_data->new_fmt); - - /* Override the framerate to be 1.5x higher in the event - * for the renderer. - */ - fmt_chg_data->new_fmt.det.vid.fps.num *= 3; - fmt_chg_data->new_fmt.det.vid.fps.num /= 2; - } else { - pjmedia_format_copy(&stream->info.codec_param->enc_fmt, - &fmt_chg_data->new_fmt); - pjmedia_format_copy(&stream->enc->port.info.fmt, - &fmt_chg_data->new_fmt); - } + pjmedia_event_fmt_changed_data *fmt_chg_data; + + fmt_chg_data = &stream->fmt_event.data.fmt_changed; + + /* Update stream info and decoding channel port info */ + if (fmt_chg_data->dir == PJMEDIA_DIR_DECODING) { + pjmedia_format_copy(&stream->info.codec_param->dec_fmt, + &fmt_chg_data->new_fmt); + pjmedia_format_copy(&stream->dec->port.info.fmt, + &fmt_chg_data->new_fmt); + + /* Override the framerate to be 1.5x higher in the event + * for the renderer. + */ + fmt_chg_data->new_fmt.det.vid.fps.num *= 3; + fmt_chg_data->new_fmt.det.vid.fps.num /= 2; + } else { + pjmedia_format_copy(&stream->info.codec_param->enc_fmt, + &fmt_chg_data->new_fmt); + pjmedia_format_copy(&stream->enc->port.info.fmt, + &fmt_chg_data->new_fmt); + } - dump_port_info(fmt_chg_data->dir==PJMEDIA_DIR_DECODING ? - stream->dec : stream->enc, - "changed"); + dump_port_info(fmt_chg_data->dir==PJMEDIA_DIR_DECODING ? + stream->dec : stream->enc, + "changed"); - pjmedia_event_publish(NULL, port, &stream->fmt_event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); + pjmedia_event_publish(NULL, port, &stream->fmt_event, + PJMEDIA_EVENT_PUBLISH_POST_EVENT); - stream->fmt_event.type = PJMEDIA_EVENT_NONE; + stream->fmt_event.type = PJMEDIA_EVENT_NONE; } if (stream->miss_keyframe_event.type != PJMEDIA_EVENT_NONE) { - pjmedia_event_publish(NULL, port, &stream->miss_keyframe_event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); - stream->miss_keyframe_event.type = PJMEDIA_EVENT_NONE; + pjmedia_event_publish(NULL, port, &stream->miss_keyframe_event, + PJMEDIA_EVENT_PUBLISH_POST_EVENT); + stream->miss_keyframe_event.type = PJMEDIA_EVENT_NONE; } pj_grp_lock_acquire( stream->grp_lock ); if (stream->dec_frame.size == 0) { - /* Don't have frame in buffer, try to decode one */ - if (decode_frame(stream, frame) != PJ_SUCCESS) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - } + /* Don't have frame in buffer, try to decode one */ + if (decode_frame(stream, frame) != PJ_SUCCESS) { + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + } } else { - if (frame->size < stream->dec_frame.size) { - PJ_LOG(4,(stream->dec->port.info.name.ptr, - "Error: not enough buffer for decoded frame " - "(supplied=%d, required=%d)", - (int)frame->size, (int)stream->dec_frame.size)); - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - } else { - frame->type = stream->dec_frame.type; - frame->timestamp = stream->dec_frame.timestamp; - frame->size = stream->dec_frame.size; - pj_memcpy(frame->buf, stream->dec_frame.buf, frame->size); - } - - stream->dec_frame.size = 0; + if (frame->size < stream->dec_frame.size) { + PJ_LOG(4,(stream->dec->port.info.name.ptr, + "Error: not enough buffer for decoded frame " + "(supplied=%d, required=%d)", + (int)frame->size, (int)stream->dec_frame.size)); + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + } else { + frame->type = stream->dec_frame.type; + frame->timestamp = stream->dec_frame.timestamp; + frame->size = stream->dec_frame.size; + pj_memcpy(frame->buf, stream->dec_frame.buf, frame->size); + } + + stream->dec_frame.size = 0; } pj_grp_lock_release( stream->grp_lock ); @@ -1628,11 +1627,11 @@ static pj_status_t get_frame(pjmedia_port *port, * Create media channel. */ static pj_status_t create_channel( pj_pool_t *pool, - pjmedia_vid_stream *stream, - pjmedia_dir dir, - unsigned pt, - const pjmedia_vid_stream_info *info, - pjmedia_vid_channel **p_channel) + pjmedia_vid_stream *stream, + pjmedia_dir dir, + unsigned pt, + const pjmedia_vid_stream_info *info, + pjmedia_vid_channel **p_channel) { enum { M = 32 }; pjmedia_vid_channel *channel; @@ -1653,11 +1652,11 @@ static pj_status_t create_channel( pj_pool_t *pool, /* Init vars */ if (dir==PJMEDIA_DIR_DECODING) { - type_name = "vstdec"; - fmt = &info->codec_param->dec_fmt; + type_name = "vstdec"; + fmt = &info->codec_param->dec_fmt; } else { - type_name = "vstenc"; - fmt = &info->codec_param->enc_fmt; + type_name = "vstenc"; + fmt = &info->codec_param->enc_fmt; } name.ptr = (char*) pj_pool_alloc(pool, M); name.slen = pj_ansi_snprintf(name.ptr, M, "%s%p", type_name, stream); @@ -1671,44 +1670,44 @@ static pj_status_t create_channel( pj_pool_t *pool, /* Allocate buffer for outgoing packet. */ if (dir == PJMEDIA_DIR_ENCODING) { - channel->buf_size = sizeof(pjmedia_rtp_hdr) + stream->frame_size; + channel->buf_size = sizeof(pjmedia_rtp_hdr) + stream->frame_size; - /* It should big enough to hold (minimally) RTCP SR with an SDES. */ - min_out_pkt_size = sizeof(pjmedia_rtcp_sr_pkt) + - sizeof(pjmedia_rtcp_common) + - (4 + (unsigned)stream->cname.slen) + - 32; + /* It should big enough to hold (minimally) RTCP SR with an SDES. */ + min_out_pkt_size = sizeof(pjmedia_rtcp_sr_pkt) + + sizeof(pjmedia_rtcp_common) + + (4 + (unsigned)stream->cname.slen) + + 32; - if (channel->buf_size < min_out_pkt_size) - channel->buf_size = min_out_pkt_size; + if (channel->buf_size < min_out_pkt_size) + channel->buf_size = min_out_pkt_size; - channel->buf = pj_pool_alloc(pool, channel->buf_size); - PJ_ASSERT_RETURN(channel->buf != NULL, PJ_ENOMEM); + channel->buf = pj_pool_alloc(pool, channel->buf_size); + PJ_ASSERT_RETURN(channel->buf != NULL, PJ_ENOMEM); } /* Create RTP and RTCP sessions: */ { - pjmedia_rtp_session_setting settings; + pjmedia_rtp_session_setting settings; - settings.flags = (pj_uint8_t)((info->rtp_seq_ts_set << 2) | - (info->has_rem_ssrc << 4) | 3); - settings.default_pt = pt; - settings.sender_ssrc = info->ssrc; - settings.peer_ssrc = info->rem_ssrc; - settings.seq = info->rtp_seq; - settings.ts = info->rtp_ts; - status = pjmedia_rtp_session_init2(&channel->rtp, settings); + settings.flags = (pj_uint8_t)((info->rtp_seq_ts_set << 2) | + (info->has_rem_ssrc << 4) | 3); + settings.default_pt = pt; + settings.sender_ssrc = info->ssrc; + settings.peer_ssrc = info->rem_ssrc; + settings.seq = info->rtp_seq; + settings.ts = info->rtp_ts; + status = pjmedia_rtp_session_init2(&channel->rtp, settings); } if (status != PJ_SUCCESS) - return status; + return status; /* Init port. */ pjmedia_port_info_init2(pi, &name, SIGNATURE, dir, fmt); if (dir == PJMEDIA_DIR_DECODING) { - channel->port.get_frame = &get_frame; + channel->port.get_frame = &get_frame; } else { - pi->fmt.id = info->codec_param->dec_fmt.id; - channel->port.put_frame = &put_frame; + pi->fmt.id = info->codec_param->dec_fmt.id; + channel->port.put_frame = &put_frame; } channel->port.port_data.pdata = stream; @@ -1716,15 +1715,15 @@ static pj_status_t create_channel( pj_pool_t *pool, channel->port.grp_lock = stream->grp_lock; PJ_LOG(5, (name.ptr, - "%s channel created %dx%d %s%s%.*s %d/%d(~%d)fps", - (dir==PJMEDIA_DIR_ENCODING?"Encoding":"Decoding"), - pi->fmt.det.vid.size.w, pi->fmt.det.vid.size.h, - pjmedia_fourcc_name(pi->fmt.id, fourcc_name), - (dir==PJMEDIA_DIR_ENCODING?"->":"<-"), - info->codec_info.encoding_name.slen, - info->codec_info.encoding_name.ptr, - pi->fmt.det.vid.fps.num, pi->fmt.det.vid.fps.denum, - pi->fmt.det.vid.fps.num/pi->fmt.det.vid.fps.denum)); + "%s channel created %dx%d %s%s%.*s %d/%d(~%d)fps", + (dir==PJMEDIA_DIR_ENCODING?"Encoding":"Decoding"), + pi->fmt.det.vid.size.w, pi->fmt.det.vid.size.h, + pjmedia_fourcc_name(pi->fmt.id, fourcc_name), + (dir==PJMEDIA_DIR_ENCODING?"->":"<-"), + info->codec_info.encoding_name.slen, + info->codec_info.encoding_name.ptr, + pi->fmt.det.vid.fps.num, pi->fmt.det.vid.fps.denum, + pi->fmt.det.vid.fps.num/pi->fmt.det.vid.fps.denum)); /* Done. */ *p_channel = channel; @@ -1736,12 +1735,12 @@ static pj_status_t create_channel( pj_pool_t *pool, * Create stream. */ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( - pjmedia_endpt *endpt, - pj_pool_t *pool, - pjmedia_vid_stream_info *info, - pjmedia_transport *tp, - void *user_data, - pjmedia_vid_stream **p_stream) + pjmedia_endpt *endpt, + pj_pool_t *pool, + pjmedia_vid_stream_info *info, + pjmedia_transport *tp, + void *user_data, + pjmedia_vid_stream **p_stream) { enum { M = 32 }; pj_pool_t *own_pool = NULL; @@ -1754,11 +1753,11 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( pjmedia_transport_attach_param att_param; if (!pool) { - own_pool = pjmedia_endpt_create_pool( endpt, "vstrm%p", - PJMEDIA_VSTREAM_SIZE, - PJMEDIA_VSTREAM_INC); - PJ_ASSERT_RETURN(own_pool != NULL, PJ_ENOMEM); - pool = own_pool; + own_pool = pjmedia_endpt_create_pool( endpt, "vstrm%p", + PJMEDIA_VSTREAM_SIZE, + PJMEDIA_VSTREAM_INC); + PJ_ASSERT_RETURN(own_pool != NULL, PJ_ENOMEM); + pool = own_pool; } /* Allocate stream */ @@ -1773,41 +1772,41 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( /* Init stream/port name */ stream->name.ptr = (char*) pj_pool_alloc(pool, M); stream->name.slen = pj_ansi_snprintf(stream->name.ptr, M, - "vstrm%p", stream); + "vstrm%p", stream); /* Create and initialize codec: */ status = pjmedia_vid_codec_mgr_alloc_codec(stream->codec_mgr, - &info->codec_info, - &stream->codec); + &info->codec_info, + &stream->codec); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Get codec param: */ if (!info->codec_param) { - pjmedia_vid_codec_param def_param; + pjmedia_vid_codec_param def_param; - status = pjmedia_vid_codec_mgr_get_default_param(stream->codec_mgr, - &info->codec_info, - &def_param); - if (status != PJ_SUCCESS) - goto err_cleanup; + status = pjmedia_vid_codec_mgr_get_default_param(stream->codec_mgr, + &info->codec_info, + &def_param); + if (status != PJ_SUCCESS) + goto err_cleanup; - info->codec_param = pjmedia_vid_codec_param_clone(pool, &def_param); - pj_assert(info->codec_param); + info->codec_param = pjmedia_vid_codec_param_clone(pool, &def_param); + pj_assert(info->codec_param); } /* Init codec param and adjust MTU */ info->codec_param->dir = info->dir; info->codec_param->enc_mtu -= (sizeof(pjmedia_rtp_hdr) + - PJMEDIA_STREAM_RESV_PAYLOAD_LEN); + PJMEDIA_STREAM_RESV_PAYLOAD_LEN); if (info->codec_param->enc_mtu > PJMEDIA_MAX_MTU) - info->codec_param->enc_mtu = PJMEDIA_MAX_MTU; + info->codec_param->enc_mtu = PJMEDIA_MAX_MTU; /* Packet size estimation for decoding direction */ vfd_enc = pjmedia_format_get_video_format_detail( - &info->codec_param->enc_fmt, PJ_TRUE); + &info->codec_param->enc_fmt, PJ_TRUE); vfd_dec = pjmedia_format_get_video_format_detail( - &info->codec_param->dec_fmt, PJ_TRUE); + &info->codec_param->dec_fmt, PJ_TRUE); /* Init stream: */ stream->endpt = endpt; @@ -1828,36 +1827,36 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( stream->cname = info->cname; if (stream->cname.slen == 0) { - /* Build random RTCP CNAME. CNAME has user@host format */ - stream->cname.ptr = p = (char*) pj_pool_alloc(pool, 20); - pj_create_random_string(p, 5); - p += 5; - *p++ = '@'; *p++ = 'p'; *p++ = 'j'; - pj_create_random_string(p, 6); - p += 6; - *p++ = '.'; *p++ = 'o'; *p++ = 'r'; *p++ = 'g'; - stream->cname.slen = p - stream->cname.ptr; + /* Build random RTCP CNAME. CNAME has user@host format */ + stream->cname.ptr = p = (char*) pj_pool_alloc(pool, 20); + pj_create_random_string(p, 5); + p += 5; + *p++ = '@'; *p++ = 'p'; *p++ = 'j'; + pj_create_random_string(p, 6); + p += 6; + *p++ = '.'; *p++ = 'o'; *p++ = 'r'; *p++ = 'g'; + stream->cname.slen = p - stream->cname.ptr; } /* Create group lock */ status = pj_grp_lock_create_w_handler(pool, NULL, stream, - &on_destroy, - &stream->grp_lock); + &on_destroy, + &stream->grp_lock); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Add ref count of group lock */ status = pj_grp_lock_add_ref(stream->grp_lock); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Init and open the codec. */ status = pjmedia_vid_codec_init(stream->codec, pool); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; status = pjmedia_vid_codec_open(stream->codec, info->codec_param); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Subscribe to codec events */ pjmedia_event_subscribe(NULL, &stream_event_cb, stream, @@ -1868,7 +1867,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( #if 0 stream->frame_size = vfd_enc->max_bps/8 * vfd_enc->fps.denum / - vfd_enc->fps.num; + vfd_enc->fps.num; /* As the maximum frame_size is not represented directly by maximum bps * (which includes intra and predicted frames), let's increase the @@ -1879,9 +1878,9 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( /* Validate the frame size */ if (stream->frame_size == 0 || - stream->frame_size > PJMEDIA_MAX_VIDEO_ENC_FRAME_SIZE) + stream->frame_size > PJMEDIA_MAX_VIDEO_ENC_FRAME_SIZE) { - stream->frame_size = PJMEDIA_MAX_VIDEO_ENC_FRAME_SIZE; + stream->frame_size = PJMEDIA_MAX_VIDEO_ENC_FRAME_SIZE; } /* Get frame length in timestamp unit */ @@ -1891,15 +1890,15 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( /* Initialize send rate states */ pj_get_timestamp_freq(&stream->ts_freq); if (info->rc_cfg.bandwidth == 0) - info->rc_cfg.bandwidth = vfd_enc->max_bps; + info->rc_cfg.bandwidth = vfd_enc->max_bps; /* For simple blocking, need to have bandwidth large enough, otherwise * we can slow down the transmission too much */ if (info->rc_cfg.method==PJMEDIA_VID_STREAM_RC_SIMPLE_BLOCKING && - info->rc_cfg.bandwidth < vfd_enc->avg_bps * 3) + info->rc_cfg.bandwidth < vfd_enc->avg_bps * 3) { - info->rc_cfg.bandwidth = vfd_enc->avg_bps * 3; + info->rc_cfg.bandwidth = vfd_enc->avg_bps * 3; } /* Override the initial framerate in the decoding direction. This initial @@ -1914,63 +1913,63 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( /* Create decoder channel */ status = create_channel( pool, stream, PJMEDIA_DIR_DECODING, - info->rx_pt, info, &stream->dec); + info->rx_pt, info, &stream->dec); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Create encoder channel */ status = create_channel( pool, stream, PJMEDIA_DIR_ENCODING, - info->tx_pt, info, &stream->enc); + info->tx_pt, info, &stream->enc); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Create temporary buffer for immediate decoding */ stream->dec_max_size = vfd_dec->size.w * vfd_dec->size.h * 4; stream->dec_frame.buf = pj_pool_alloc(pool, stream->dec_max_size); /* Init jitter buffer parameters: */ - frm_ptime = 1000 * vfd_dec->fps.denum / vfd_dec->fps.num; + frm_ptime = 1000 * vfd_dec->fps.denum / vfd_dec->fps.num; chunks_per_frm = stream->frame_size / PJMEDIA_MAX_MRU; if (chunks_per_frm < MIN_CHUNKS_PER_FRM) - chunks_per_frm = MIN_CHUNKS_PER_FRM; + chunks_per_frm = MIN_CHUNKS_PER_FRM; /* JB max count, default 500ms */ if (info->jb_max >= frm_ptime) { - jb_max = info->jb_max * chunks_per_frm / frm_ptime; - stream->dec_max_delay = info->codec_info.clock_rate * info->jb_max / - 1000; + jb_max = info->jb_max * chunks_per_frm / frm_ptime; + stream->dec_max_delay = info->codec_info.clock_rate * info->jb_max / + 1000; } else { - jb_max = 500 * chunks_per_frm / frm_ptime; - stream->dec_max_delay = info->codec_info.clock_rate * 500 / 1000; + jb_max = 500 * chunks_per_frm / frm_ptime; + stream->dec_max_delay = info->codec_info.clock_rate * 500 / 1000; } /* JB min prefetch, default 1 frame */ if (info->jb_min_pre >= frm_ptime) - jb_min_pre = info->jb_min_pre * chunks_per_frm / frm_ptime; + jb_min_pre = info->jb_min_pre * chunks_per_frm / frm_ptime; else - jb_min_pre = 1; + jb_min_pre = 1; /* JB max prefetch, default 4/5 JB max count */ if (info->jb_max_pre >= frm_ptime) - jb_max_pre = info->jb_max_pre * chunks_per_frm / frm_ptime; + jb_max_pre = info->jb_max_pre * chunks_per_frm / frm_ptime; else - jb_max_pre = jb_max * 4 / 5; + jb_max_pre = jb_max * 4 / 5; /* JB init prefetch, default 0 */ if (info->jb_init >= frm_ptime) - jb_init = info->jb_init * chunks_per_frm / frm_ptime; + jb_init = info->jb_init * chunks_per_frm / frm_ptime; else - jb_init = 0; + jb_init = 0; /* Calculate the decoding delay (in number of frames) based on FPS */ stream->dec_delay_cnt = ((PJMEDIA_VID_STREAM_DECODE_MIN_DELAY_MSEC * - vfd_dec->fps.num) + - (1000 * vfd_dec->fps.denum) - 1) / - (1000 * vfd_dec->fps.denum); + vfd_dec->fps.num) + + (1000 * vfd_dec->fps.denum) - 1) / + (1000 * vfd_dec->fps.denum); if (stream->dec_delay_cnt < 1) - stream->dec_delay_cnt = 1; + stream->dec_delay_cnt = 1; if (stream->dec_delay_cnt > jb_max * 4/5) - stream->dec_delay_cnt = jb_max * 4/5; + stream->dec_delay_cnt = jb_max * 4/5; /* Allocate array for temporary storage for assembly of incoming * frames. Add more just in case. @@ -1982,10 +1981,10 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( /* Create jitter buffer */ status = pjmedia_jbuf_create(pool, &stream->dec->port.info.name, PJMEDIA_MAX_MRU, - 1000 * vfd_enc->fps.denum / vfd_enc->fps.num, - jb_max, &stream->jb); + 1000 * vfd_enc->fps.denum / vfd_enc->fps.num, + jb_max, &stream->jb); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; /* Set up jitter buffer */ @@ -1994,36 +1993,36 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( /* Init RTCP session: */ { - pjmedia_rtcp_session_setting rtcp_setting; + pjmedia_rtcp_session_setting rtcp_setting; - pjmedia_rtcp_session_setting_default(&rtcp_setting); - rtcp_setting.name = stream->name.ptr; - rtcp_setting.ssrc = info->ssrc; - rtcp_setting.rtp_ts_base = pj_ntohl(stream->enc->rtp.out_hdr.ts); - rtcp_setting.clock_rate = info->codec_info.clock_rate; - rtcp_setting.samples_per_frame = 1; + pjmedia_rtcp_session_setting_default(&rtcp_setting); + rtcp_setting.name = stream->name.ptr; + rtcp_setting.ssrc = info->ssrc; + rtcp_setting.rtp_ts_base = pj_ntohl(stream->enc->rtp.out_hdr.ts); + rtcp_setting.clock_rate = info->codec_info.clock_rate; + rtcp_setting.samples_per_frame = 1; - pjmedia_rtcp_init2(&stream->rtcp, &rtcp_setting); + pjmedia_rtcp_init2(&stream->rtcp, &rtcp_setting); - if (info->rtp_seq_ts_set) { - stream->rtcp.stat.rtp_tx_last_seq = info->rtp_seq; - stream->rtcp.stat.rtp_tx_last_ts = info->rtp_ts; - } + if (info->rtp_seq_ts_set) { + stream->rtcp.stat.rtp_tx_last_seq = info->rtp_seq; + stream->rtcp.stat.rtp_tx_last_ts = info->rtp_ts; + } - /* Subscribe to RTCP events */ - pjmedia_event_subscribe(NULL, &stream_event_cb, stream, - &stream->rtcp); + /* Subscribe to RTCP events */ + pjmedia_event_subscribe(NULL, &stream_event_cb, stream, + &stream->rtcp); } /* Allocate outgoing RTCP buffer, should be enough to hold SR/RR, SDES, * BYE, Feedback, and XR. */ stream->out_rtcp_pkt_size = sizeof(pjmedia_rtcp_sr_pkt) + - sizeof(pjmedia_rtcp_common) + - (4 + (unsigned)stream->cname.slen) + - 32 + 32; + sizeof(pjmedia_rtcp_common) + + (4 + (unsigned)stream->cname.slen) + + 32 + 32; if (stream->out_rtcp_pkt_size > PJMEDIA_MAX_MTU) - stream->out_rtcp_pkt_size = PJMEDIA_MAX_MTU; + stream->out_rtcp_pkt_size = PJMEDIA_MAX_MTU; stream->out_rtcp_pkt = pj_pool_alloc(pool, stream->out_rtcp_pkt_size); pj_bzero(&att_param, sizeof(att_param)); @@ -2033,9 +2032,9 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( pj_sockaddr_cp(&att_param.rem_addr, &info->rem_addr); pj_sockaddr_cp(&stream->rem_rtp_addr, &info->rem_addr); if (info->rtcp_mux) { - pj_sockaddr_cp(&att_param.rem_rtcp, &info->rem_addr); + pj_sockaddr_cp(&att_param.rem_rtcp, &info->rem_addr); } else if (pj_sockaddr_has_addr(&info->rem_rtcp.addr)) { - pj_sockaddr_cp(&att_param.rem_rtcp, &info->rem_rtcp); + pj_sockaddr_cp(&att_param.rem_rtcp, &info->rem_rtcp); } att_param.addr_len = pj_sockaddr_get_len(&info->rem_addr); att_param.rtp_cb2 = &on_rx_rtp; @@ -2044,7 +2043,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( /* Only attach transport when stream is ready. */ status = pjmedia_transport_attach2(tp, &att_param); if (status != PJ_SUCCESS) - goto err_cleanup; + goto err_cleanup; stream->transport = tp; @@ -2056,86 +2055,86 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_create( #if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0 /* NAT hole punching by sending KA packet via RTP transport. */ if (stream->use_ka) - send_keep_alive_packet(stream); + send_keep_alive_packet(stream); #endif #if TRACE_JB { - char trace_name[PJ_MAXPATH]; - pj_ssize_t len; - - pj_ansi_snprintf(trace_name, sizeof(trace_name), - TRACE_JB_PATH_PREFIX "%s.csv", - channel->port.info.name.ptr); - status = pj_file_open(pool, trace_name, PJ_O_RDWR, - &stream->trace_jb_fd); - if (status != PJ_SUCCESS) { - stream->trace_jb_fd = TRACE_JB_INVALID_FD; - PJ_PERROR(3,(THIS_FILE, status, - "Failed creating RTP trace file '%s'", - trace_name)); - } else { - stream->trace_jb_buf = (char*)pj_pool_alloc(pool, PJ_LOG_MAX_SIZE); - - /* Print column header */ - len = pj_ansi_snprintf(stream->trace_jb_buf, PJ_LOG_MAX_SIZE, - "Time, Operation, Size, Frame Count, " - "Frame type, RTP Seq, RTP TS, RTP M, " - "JB size, JB burst level, JB prefetch\n"); - if (len < 1 || len >= PJ_LOG_MAX_SIZE) - len = PJ_LOG_MAX_SIZE - 1; - pj_file_write(stream->trace_jb_fd, stream->trace_jb_buf, &len); - pj_file_flush(stream->trace_jb_fd); - } + char trace_name[PJ_MAXPATH]; + pj_ssize_t len; + + pj_ansi_snprintf(trace_name, sizeof(trace_name), + TRACE_JB_PATH_PREFIX "%s.csv", + channel->port.info.name.ptr); + status = pj_file_open(pool, trace_name, PJ_O_RDWR, + &stream->trace_jb_fd); + if (status != PJ_SUCCESS) { + stream->trace_jb_fd = TRACE_JB_INVALID_FD; + PJ_PERROR(3,(THIS_FILE, status, + "Failed creating RTP trace file '%s'", + trace_name)); + } else { + stream->trace_jb_buf = (char*)pj_pool_alloc(pool, PJ_LOG_MAX_SIZE); + + /* Print column header */ + len = pj_ansi_snprintf(stream->trace_jb_buf, PJ_LOG_MAX_SIZE, + "Time, Operation, Size, Frame Count, " + "Frame type, RTP Seq, RTP TS, RTP M, " + "JB size, JB burst level, JB prefetch\n"); + if (len < 1 || len >= PJ_LOG_MAX_SIZE) + len = PJ_LOG_MAX_SIZE - 1; + pj_file_write(stream->trace_jb_fd, stream->trace_jb_buf, &len); + pj_file_flush(stream->trace_jb_fd); + } } #endif /* Save the stream info */ pj_memcpy(&stream->info, info, sizeof(*info)); stream->info.codec_param = pjmedia_vid_codec_param_clone( - pool, info->codec_param); + pool, info->codec_param); pjmedia_rtcp_fb_info_dup(pool, &stream->info.loc_rtcp_fb, - &info->loc_rtcp_fb); + &info->loc_rtcp_fb); pjmedia_rtcp_fb_info_dup(pool, &stream->info.rem_rtcp_fb, - &info->rem_rtcp_fb); + &info->rem_rtcp_fb); /* Check if we should send RTCP-FB */ if (stream->info.rem_rtcp_fb.cap_count) { - pjmedia_rtcp_fb_info *rfi = &stream->info.rem_rtcp_fb; - unsigned i; - - for (i = 0; i < rfi->cap_count; ++i) { - if (rfi->caps[i].type == PJMEDIA_RTCP_FB_NACK) { - if (rfi->caps[i].param.slen == 0) { - stream->send_rtcp_fb_nack = PJ_TRUE; - PJ_LOG(5,(stream->name.ptr, "Send RTCP-FB generic NACK")); - } else if (pj_stricmp2(&rfi->caps[i].param, "pli")==0) { - stream->send_rtcp_fb_pli = PJ_TRUE; - PJ_LOG(5,(stream->name.ptr, "Send RTCP-FB PLI")); - } - } - } + pjmedia_rtcp_fb_info *rfi = &stream->info.rem_rtcp_fb; + unsigned i; + + for (i = 0; i < rfi->cap_count; ++i) { + if (rfi->caps[i].type == PJMEDIA_RTCP_FB_NACK) { + if (rfi->caps[i].param.slen == 0) { + stream->send_rtcp_fb_nack = PJ_TRUE; + PJ_LOG(5,(stream->name.ptr, "Send RTCP-FB generic NACK")); + } else if (pj_stricmp2(&rfi->caps[i].param, "pli")==0) { + stream->send_rtcp_fb_pli = PJ_TRUE; + PJ_LOG(5,(stream->name.ptr, "Send RTCP-FB PLI")); + } + } + } } /* Check if we should process incoming RTCP-FB */ stream->rtcp_fb_nack_cap_idx = -1; stream->rtcp_fb_pli_cap_idx = -1; if (stream->info.loc_rtcp_fb.cap_count) { - pjmedia_rtcp_fb_info *lfi = &stream->info.loc_rtcp_fb; - unsigned i; - - for (i = 0; i < lfi->cap_count; ++i) { - if (lfi->caps[i].type == PJMEDIA_RTCP_FB_NACK) { - if (lfi->caps[i].param.slen == 0) { - stream->rtcp_fb_nack_cap_idx = i; - PJ_LOG(5,(stream->name.ptr, - "Receive RTCP-FB generic NACK")); - } else if (pj_stricmp2(&lfi->caps[i].param, "pli")==0) { - stream->rtcp_fb_pli_cap_idx = i; - PJ_LOG(5,(stream->name.ptr, "Receive RTCP-FB PLI")); - } - } - } + pjmedia_rtcp_fb_info *lfi = &stream->info.loc_rtcp_fb; + unsigned i; + + for (i = 0; i < lfi->cap_count; ++i) { + if (lfi->caps[i].type == PJMEDIA_RTCP_FB_NACK) { + if (lfi->caps[i].param.slen == 0) { + stream->rtcp_fb_nack_cap_idx = i; + PJ_LOG(5,(stream->name.ptr, + "Receive RTCP-FB generic NACK")); + } else if (pj_stricmp2(&lfi->caps[i].param, "pli")==0) { + stream->rtcp_fb_pli_cap_idx = i; + PJ_LOG(5,(stream->name.ptr, "Receive RTCP-FB PLI")); + } + } + } } /* Success! */ @@ -2162,20 +2161,20 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_destroy( pjmedia_vid_stream *stream ) /* Stop the streaming */ if (stream->enc) - stream->enc->port.put_frame = NULL; + stream->enc->port.put_frame = NULL; if (stream->dec) - stream->dec->port.get_frame = NULL; + stream->dec->port.get_frame = NULL; #if TRACE_RC { - unsigned total_time; + unsigned total_time; - total_time = pj_elapsed_msec(&stream->tx_start, &stream->tx_end); - PJ_LOG(5, (stream->name.ptr, - "RC stat: pkt_cnt=%.2f/image, sleep=%.2fms/s, fps=%.2f", - stream->rc_total_pkt*1.0/stream->rc_total_img, - stream->rc_total_sleep*1000.0/total_time, - stream->rc_total_img*1000.0/total_time)); + total_time = pj_elapsed_msec(&stream->tx_start, &stream->tx_end); + PJ_LOG(5, (stream->name.ptr, + "RC stat: pkt_cnt=%.2f/image, sleep=%.2fms/s, fps=%.2f", + stream->rc_total_pkt*1.0/stream->rc_total_img, + stream->rc_total_sleep*1000.0/total_time, + stream->rc_total_img*1000.0/total_time)); } #endif @@ -2188,7 +2187,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_destroy( pjmedia_vid_stream *stream ) /* Send RTCP BYE (also SDES) */ if (stream->transport && !stream->rtcp_sdes_bye_disabled) { - send_rtcp(stream, PJ_TRUE, PJ_TRUE, PJ_FALSE, PJ_FALSE); + send_rtcp(stream, PJ_TRUE, PJ_TRUE, PJ_FALSE, PJ_FALSE); } /* Detach from transport @@ -2196,17 +2195,17 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_destroy( pjmedia_vid_stream *stream ) * it may cause deadlock. See ticket #460 for the details. */ if (stream->transport) { - pjmedia_transport_detach(stream->transport, stream); - stream->transport = NULL; + pjmedia_transport_detach(stream->transport, stream); + stream->transport = NULL; } /* This function may be called when stream is partly initialized, * i.e: group lock may not be created yet. */ if (stream->grp_lock) { - return pj_grp_lock_dec_ref(stream->grp_lock); + return pj_grp_lock_dec_ref(stream->grp_lock); } else { - on_destroy(stream); + on_destroy(stream); } return PJ_SUCCESS; @@ -2225,9 +2224,9 @@ static void on_destroy( void *arg ) /* Free codec. */ if (stream->codec) { - pjmedia_vid_codec_close(stream->codec); - pjmedia_vid_codec_mgr_dealloc_codec(stream->codec_mgr, stream->codec); - stream->codec = NULL; + pjmedia_vid_codec_close(stream->codec); + pjmedia_vid_codec_mgr_dealloc_codec(stream->codec_mgr, stream->codec); + stream->codec = NULL; } /* Free mutex */ @@ -2235,14 +2234,14 @@ static void on_destroy( void *arg ) /* Destroy jitter buffer */ if (stream->jb) { - pjmedia_jbuf_destroy(stream->jb); - stream->jb = NULL; + pjmedia_jbuf_destroy(stream->jb); + stream->jb = NULL; } #if TRACE_JB if (TRACE_JB_OPENED(stream)) { - pj_file_close(stream->trace_jb_fd); - stream->trace_jb_fd = TRACE_JB_INVALID_FD; + pj_file_close(stream->trace_jb_fd); + stream->trace_jb_fd = TRACE_JB_INVALID_FD; } #endif @@ -2254,16 +2253,16 @@ static void on_destroy( void *arg ) * Get the port interface. */ PJ_DEF(pj_status_t) pjmedia_vid_stream_get_port(pjmedia_vid_stream *stream, - pjmedia_dir dir, - pjmedia_port **p_port ) + pjmedia_dir dir, + pjmedia_port **p_port ) { PJ_ASSERT_RETURN(dir==PJMEDIA_DIR_ENCODING || dir==PJMEDIA_DIR_DECODING, - PJ_EINVAL); + PJ_EINVAL); if (dir == PJMEDIA_DIR_ENCODING) - *p_port = &stream->enc->port; + *p_port = &stream->enc->port; else - *p_port = &stream->dec->port; + *p_port = &stream->dec->port; return PJ_SUCCESS; } @@ -2273,7 +2272,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_get_port(pjmedia_vid_stream *stream, * Get the transport object */ PJ_DEF(pjmedia_transport*) pjmedia_vid_stream_get_transport( - pjmedia_vid_stream *st) + pjmedia_vid_stream *st) { return st->transport; } @@ -2283,8 +2282,8 @@ PJ_DEF(pjmedia_transport*) pjmedia_vid_stream_get_transport( * Get stream statistics. */ PJ_DEF(pj_status_t) pjmedia_vid_stream_get_stat( - const pjmedia_vid_stream *stream, - pjmedia_rtcp_stat *stat) + const pjmedia_vid_stream *stream, + pjmedia_rtcp_stat *stat) { PJ_ASSERT_RETURN(stream && stat, PJ_EINVAL); @@ -2310,8 +2309,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_reset_stat(pjmedia_vid_stream *stream) * Get jitter buffer state. */ PJ_DEF(pj_status_t) pjmedia_vid_stream_get_stat_jbuf( - const pjmedia_vid_stream *stream, - pjmedia_jb_state *state) + const pjmedia_vid_stream *stream, + pjmedia_jb_state *state) { PJ_ASSERT_RETURN(stream && state, PJ_EINVAL); return pjmedia_jbuf_get_state(stream->jb, state); @@ -2322,8 +2321,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_get_stat_jbuf( * Get the stream info. */ PJ_DEF(pj_status_t) pjmedia_vid_stream_get_info( - const pjmedia_vid_stream *stream, - pjmedia_vid_stream_info *info) + const pjmedia_vid_stream *stream, + pjmedia_vid_stream_info *info) { PJ_ASSERT_RETURN(stream && info, PJ_EINVAL); pj_memcpy(info, &stream->info, sizeof(*info)); @@ -2340,19 +2339,19 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_start(pjmedia_vid_stream *stream) PJ_ASSERT_RETURN(stream && stream->enc && stream->dec, PJ_EINVALIDOP); if (stream->enc && (stream->dir & PJMEDIA_DIR_ENCODING)) { - stream->enc->paused = 0; - //pjmedia_snd_stream_start(stream->enc->snd_stream); - PJ_LOG(4,(stream->enc->port.info.name.ptr, "Encoder stream started")); + stream->enc->paused = 0; + //pjmedia_snd_stream_start(stream->enc->snd_stream); + PJ_LOG(4,(stream->enc->port.info.name.ptr, "Encoder stream started")); } else { - PJ_LOG(4,(stream->enc->port.info.name.ptr, "Encoder stream paused")); + PJ_LOG(4,(stream->enc->port.info.name.ptr, "Encoder stream paused")); } if (stream->dec && (stream->dir & PJMEDIA_DIR_DECODING)) { - stream->dec->paused = 0; - //pjmedia_snd_stream_start(stream->dec->snd_stream); - PJ_LOG(4,(stream->dec->port.info.name.ptr, "Decoder stream started")); + stream->dec->paused = 0; + //pjmedia_snd_stream_start(stream->dec->snd_stream); + PJ_LOG(4,(stream->dec->port.info.name.ptr, "Decoder stream started")); } else { - PJ_LOG(4,(stream->dec->port.info.name.ptr, "Decoder stream paused")); + PJ_LOG(4,(stream->dec->port.info.name.ptr, "Decoder stream paused")); } return PJ_SUCCESS; @@ -2370,11 +2369,11 @@ PJ_DEF(pj_bool_t) pjmedia_vid_stream_is_running(pjmedia_vid_stream *stream, PJ_ASSERT_RETURN(stream, PJ_FALSE); if (dir & PJMEDIA_DIR_ENCODING) { - is_running &= (stream->enc && !stream->enc->paused); + is_running &= (stream->enc && !stream->enc->paused); } if (dir & PJMEDIA_DIR_DECODING) { - is_running &= (stream->dec && !stream->dec->paused); + is_running &= (stream->dec && !stream->dec->paused); } return is_running; @@ -2384,24 +2383,24 @@ PJ_DEF(pj_bool_t) pjmedia_vid_stream_is_running(pjmedia_vid_stream *stream, * Pause stream. */ PJ_DEF(pj_status_t) pjmedia_vid_stream_pause(pjmedia_vid_stream *stream, - pjmedia_dir dir) + pjmedia_dir dir) { PJ_ASSERT_RETURN(stream, PJ_EINVAL); if ((dir & PJMEDIA_DIR_ENCODING) && stream->enc) { - stream->enc->paused = 1; - PJ_LOG(4,(stream->enc->port.info.name.ptr, "Encoder stream paused")); + stream->enc->paused = 1; + PJ_LOG(4,(stream->enc->port.info.name.ptr, "Encoder stream paused")); } if ((dir & PJMEDIA_DIR_DECODING) && stream->dec) { - stream->dec->paused = 1; + stream->dec->paused = 1; - /* Also reset jitter buffer */ - pj_grp_lock_acquire( stream->grp_lock ); - pjmedia_jbuf_reset(stream->jb); - pj_grp_lock_release( stream->grp_lock ); + /* Also reset jitter buffer */ + pj_grp_lock_acquire( stream->grp_lock ); + pjmedia_jbuf_reset(stream->jb); + pj_grp_lock_release( stream->grp_lock ); - PJ_LOG(4,(stream->dec->port.info.name.ptr, "Decoder stream paused")); + PJ_LOG(4,(stream->dec->port.info.name.ptr, "Decoder stream paused")); } return PJ_SUCCESS; @@ -2412,20 +2411,20 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_pause(pjmedia_vid_stream *stream, * Resume stream */ PJ_DEF(pj_status_t) pjmedia_vid_stream_resume(pjmedia_vid_stream *stream, - pjmedia_dir dir) + pjmedia_dir dir) { PJ_ASSERT_RETURN(stream, PJ_EINVAL); if ((dir & PJMEDIA_DIR_ENCODING) && stream->enc) { - stream->enc->paused = 0; - stream->force_keyframe = PJ_TRUE; - PJ_LOG(4,(stream->enc->port.info.name.ptr, "Encoder stream resumed")); + stream->enc->paused = 0; + stream->force_keyframe = PJ_TRUE; + PJ_LOG(4,(stream->enc->port.info.name.ptr, "Encoder stream resumed")); } if ((dir & PJMEDIA_DIR_DECODING) && stream->dec) { - stream->dec->paused = 0; - stream->last_dec_seq = 0; - PJ_LOG(4,(stream->dec->port.info.name.ptr, "Decoder stream resumed")); + stream->dec->paused = 0; + stream->last_dec_seq = 0; + PJ_LOG(4,(stream->dec->port.info.name.ptr, "Decoder stream resumed")); } return PJ_SUCCESS; @@ -2436,20 +2435,20 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_resume(pjmedia_vid_stream *stream, * Force stream to send video keyframe. */ PJ_DEF(pj_status_t) pjmedia_vid_stream_send_keyframe( - pjmedia_vid_stream *stream) + pjmedia_vid_stream *stream) { pj_timestamp now; PJ_ASSERT_RETURN(stream, PJ_EINVAL); if (!pjmedia_vid_stream_is_running(stream, PJMEDIA_DIR_ENCODING)) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; pj_get_timestamp(&now); if (pj_elapsed_msec(&stream->last_keyframe_tx, &now) < - PJMEDIA_VID_STREAM_MIN_KEYFRAME_INTERVAL_MSEC) + PJMEDIA_VID_STREAM_MIN_KEYFRAME_INTERVAL_MSEC) { - return PJ_ETOOMANY; + return PJ_ETOOMANY; } stream->force_keyframe = PJ_TRUE; @@ -2462,7 +2461,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_send_keyframe( * Send RTCP SDES. */ PJ_DEF(pj_status_t) pjmedia_vid_stream_send_rtcp_sdes( - pjmedia_vid_stream *stream) + pjmedia_vid_stream *stream) { PJ_ASSERT_RETURN(stream, PJ_EINVAL); @@ -2474,12 +2473,12 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_send_rtcp_sdes( * Send RTCP BYE. */ PJ_DEF(pj_status_t) pjmedia_vid_stream_send_rtcp_bye( - pjmedia_vid_stream *stream) + pjmedia_vid_stream *stream) { PJ_ASSERT_RETURN(stream, PJ_EINVAL); if (stream->enc && stream->transport) { - return send_rtcp(stream, PJ_TRUE, PJ_TRUE, PJ_FALSE, PJ_FALSE); + return send_rtcp(stream, PJ_TRUE, PJ_TRUE, PJ_FALSE, PJ_FALSE); } return PJ_SUCCESS; @@ -2490,12 +2489,12 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_send_rtcp_bye( * Send RTCP PLI. */ PJ_DEF(pj_status_t) pjmedia_vid_stream_send_rtcp_pli( - pjmedia_vid_stream *stream) + pjmedia_vid_stream *stream) { PJ_ASSERT_RETURN(stream, PJ_EINVAL); if (stream->transport) { - return send_rtcp(stream, PJ_FALSE, PJ_FALSE, PJ_FALSE, PJ_TRUE); + return send_rtcp(stream, PJ_FALSE, PJ_FALSE, PJ_FALSE, PJ_TRUE); } return PJ_SUCCESS; @@ -2530,7 +2529,7 @@ pjmedia_vid_stream_sk_config_default(pjmedia_vid_stream_sk_config *cfg) */ PJ_DEF(pj_status_t) pjmedia_vid_stream_get_rtp_session_info(pjmedia_vid_stream *stream, - pjmedia_stream_rtp_sess_info *session_info) + pjmedia_stream_rtp_sess_info *session_info) { session_info->rx_rtp = &stream->dec->rtp; session_info->tx_rtp = &stream->enc->rtp; diff --git a/pjmedia/src/pjmedia/vid_stream_info.c b/pjmedia/src/pjmedia/vid_stream_info.c index 2f88a62411..5b67dc5acb 100644 --- a/pjmedia/src/pjmedia/vid_stream_info.c +++ b/pjmedia/src/pjmedia/vid_stream_info.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011 Teluu Inc. (http://www.teluu.com) * @@ -34,10 +33,10 @@ static const pj_str_t ID_RTPMAP = { "rtpmap", 6 }; * Internal function for collecting codec info and param from the SDP media. */ static pj_status_t get_video_codec_info_param(pjmedia_vid_stream_info *si, - pj_pool_t *pool, - pjmedia_vid_codec_mgr *mgr, - const pjmedia_sdp_media *local_m, - const pjmedia_sdp_media *rem_m) + pj_pool_t *pool, + pjmedia_vid_codec_mgr *mgr, + const pjmedia_sdp_media *local_m, + const pjmedia_sdp_media *rem_m) { unsigned pt = 0; const pjmedia_vid_codec_info *p_info; @@ -50,64 +49,64 @@ static pj_status_t get_video_codec_info_param(pjmedia_vid_stream_info *si, /* Get codec info and payload type for transmitting direction. */ if (pt < 96) { - /* For static payload types, get the codec info from codec manager. */ - status = pjmedia_vid_codec_mgr_get_codec_info(mgr, pt, &p_info); - if (status != PJ_SUCCESS) - return status; + /* For static payload types, get the codec info from codec manager. */ + status = pjmedia_vid_codec_mgr_get_codec_info(mgr, pt, &p_info); + if (status != PJ_SUCCESS) + return status; - si->codec_info = *p_info; + si->codec_info = *p_info; - /* Get payload type for transmitting direction. - * For static payload type, pt's are symetric. - */ - si->tx_pt = pt; + /* Get payload type for transmitting direction. + * For static payload type, pt's are symetric. + */ + si->tx_pt = pt; } else { - const pjmedia_sdp_attr *attr; - pjmedia_sdp_rtpmap *rtpmap; - pjmedia_codec_id codec_id; - pj_str_t codec_id_st; - unsigned i; - - /* Determine payload type for outgoing channel, by finding - * dynamic payload type in remote SDP that matches the answer. - */ - si->tx_pt = 0xFFFF; - for (i=0; idesc.fmt_count; ++i) { - if (pjmedia_sdp_neg_fmt_match(NULL, - (pjmedia_sdp_media*)local_m, 0, - (pjmedia_sdp_media*)rem_m, i, 0) == - PJ_SUCCESS) - { - /* Found matched codec. */ - si->tx_pt = pj_strtoul(&rem_m->desc.fmt[i]); - break; - } - } - - if (si->tx_pt == 0xFFFF) - return PJMEDIA_EMISSINGRTPMAP; - - /* For dynamic payload types, get codec name from the rtpmap */ - attr = pjmedia_sdp_media_find_attr(local_m, &ID_RTPMAP, - &local_m->desc.fmt[0]); - if (attr == NULL) - return PJMEDIA_EMISSINGRTPMAP; - - status = pjmedia_sdp_attr_to_rtpmap(pool, attr, &rtpmap); - if (status != PJ_SUCCESS) - return status; - - /* Then get the codec info from the codec manager */ - pj_ansi_snprintf(codec_id, sizeof(codec_id), "%.*s/", - (int)rtpmap->enc_name.slen, rtpmap->enc_name.ptr); - codec_id_st = pj_str(codec_id); - i = 1; - status = pjmedia_vid_codec_mgr_find_codecs_by_id(mgr, &codec_id_st, - &i, &p_info, NULL); - if (status != PJ_SUCCESS) - return status; - - si->codec_info = *p_info; + const pjmedia_sdp_attr *attr; + pjmedia_sdp_rtpmap *rtpmap; + pjmedia_codec_id codec_id; + pj_str_t codec_id_st; + unsigned i; + + /* Determine payload type for outgoing channel, by finding + * dynamic payload type in remote SDP that matches the answer. + */ + si->tx_pt = 0xFFFF; + for (i=0; idesc.fmt_count; ++i) { + if (pjmedia_sdp_neg_fmt_match(NULL, + (pjmedia_sdp_media*)local_m, 0, + (pjmedia_sdp_media*)rem_m, i, 0) == + PJ_SUCCESS) + { + /* Found matched codec. */ + si->tx_pt = pj_strtoul(&rem_m->desc.fmt[i]); + break; + } + } + + if (si->tx_pt == 0xFFFF) + return PJMEDIA_EMISSINGRTPMAP; + + /* For dynamic payload types, get codec name from the rtpmap */ + attr = pjmedia_sdp_media_find_attr(local_m, &ID_RTPMAP, + &local_m->desc.fmt[0]); + if (attr == NULL) + return PJMEDIA_EMISSINGRTPMAP; + + status = pjmedia_sdp_attr_to_rtpmap(pool, attr, &rtpmap); + if (status != PJ_SUCCESS) + return status; + + /* Then get the codec info from the codec manager */ + pj_ansi_snprintf(codec_id, sizeof(codec_id), "%.*s/", + (int)rtpmap->enc_name.slen, rtpmap->enc_name.ptr); + codec_id_st = pj_str(codec_id); + i = 1; + status = pjmedia_vid_codec_mgr_find_codecs_by_id(mgr, &codec_id_st, + &i, &p_info, NULL); + if (status != PJ_SUCCESS) + return status; + + si->codec_info = *p_info; } @@ -117,53 +116,53 @@ static pj_status_t get_video_codec_info_param(pjmedia_vid_stream_info *si, /* Now that we have codec info, get the codec param. */ si->codec_param = PJ_POOL_ALLOC_T(pool, pjmedia_vid_codec_param); status = pjmedia_vid_codec_mgr_get_default_param(mgr, - &si->codec_info, - si->codec_param); + &si->codec_info, + si->codec_param); /* Adjust encoding bitrate, if higher than remote preference. The remote * bitrate preference is read from SDP "b=TIAS" line in media level. */ if ((si->dir & PJMEDIA_DIR_ENCODING) && rem_m->bandw_count) { - unsigned i, bandw = 0; - - for (i = 0; i < rem_m->bandw_count; ++i) { - const pj_str_t STR_BANDW_MODIFIER_TIAS = { "TIAS", 4 }; - if (!pj_stricmp(&rem_m->bandw[i]->modifier, - &STR_BANDW_MODIFIER_TIAS)) - { - bandw = rem_m->bandw[i]->value; - break; - } - } - - if (bandw) { - pjmedia_video_format_detail *enc_vfd; - enc_vfd = pjmedia_format_get_video_format_detail( - &si->codec_param->enc_fmt, PJ_TRUE); - if (!enc_vfd->avg_bps || enc_vfd->avg_bps > bandw) - enc_vfd->avg_bps = bandw * 3 / 4; - if (!enc_vfd->max_bps || enc_vfd->max_bps > bandw) - enc_vfd->max_bps = bandw; - } + unsigned i, bandw = 0; + + for (i = 0; i < rem_m->bandw_count; ++i) { + const pj_str_t STR_BANDW_MODIFIER_TIAS = { "TIAS", 4 }; + if (!pj_stricmp(&rem_m->bandw[i]->modifier, + &STR_BANDW_MODIFIER_TIAS)) + { + bandw = rem_m->bandw[i]->value; + break; + } + } + + if (bandw) { + pjmedia_video_format_detail *enc_vfd; + enc_vfd = pjmedia_format_get_video_format_detail( + &si->codec_param->enc_fmt, PJ_TRUE); + if (!enc_vfd->avg_bps || enc_vfd->avg_bps > bandw) + enc_vfd->avg_bps = bandw * 3 / 4; + if (!enc_vfd->max_bps || enc_vfd->max_bps > bandw) + enc_vfd->max_bps = bandw; + } } /* Get remote fmtp for our encoder. */ pjmedia_stream_info_parse_fmtp(pool, rem_m, si->tx_pt, - &si->codec_param->enc_fmtp); + &si->codec_param->enc_fmtp); /* Get local fmtp for our decoder. */ pjmedia_stream_info_parse_fmtp(pool, local_m, si->rx_pt, - &si->codec_param->dec_fmtp); + &si->codec_param->dec_fmtp); /* When direction is NONE (it means SDP negotiation has failed) we don't * need to return a failure here, as returning failure will cause * the whole SDP to be rejected. See ticket #: - * http:// + * http:// * * Thanks Alain Totouom */ if (status != PJ_SUCCESS && si->dir != PJMEDIA_DIR_NONE) - return status; + return status; return PJ_SUCCESS; } @@ -174,12 +173,12 @@ static pj_status_t get_video_codec_info_param(pjmedia_vid_stream_info *si, * Create stream info from SDP media line. */ PJ_DEF(pj_status_t) pjmedia_vid_stream_info_from_sdp( - pjmedia_vid_stream_info *si, - pj_pool_t *pool, - pjmedia_endpt *endpt, - const pjmedia_sdp_session *local, - const pjmedia_sdp_session *remote, - unsigned stream_idx) + pjmedia_vid_stream_info *si, + pj_pool_t *pool, + pjmedia_endpt *endpt, + const pjmedia_sdp_session *local, + const pjmedia_sdp_session *remote, + unsigned stream_idx) { const pj_str_t STR_INACTIVE = { "inactive", 8 }; const pj_str_t STR_SENDONLY = { "sendonly", 8 }; @@ -207,15 +206,15 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_info_from_sdp( local_conn = local_m->conn ? local_m->conn : local->conn; if (local_conn == NULL) - return PJMEDIA_SDP_EMISSINGCONN; + return PJMEDIA_SDP_EMISSINGCONN; rem_conn = rem_m->conn ? rem_m->conn : remote->conn; if (rem_conn == NULL) - return PJMEDIA_SDP_EMISSINGCONN; + return PJMEDIA_SDP_EMISSINGCONN; /* Media type must be video */ if (pjmedia_get_type(&local_m->desc.media) != PJMEDIA_TYPE_VIDEO) - return PJMEDIA_EINVALIMEDIATYPE; + return PJMEDIA_EINVALIMEDIATYPE; /* Reset: */ @@ -231,164 +230,164 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_info_from_sdp( * the transport instance will do more validation later. */ status = pjmedia_sdp_transport_cmp(&rem_m->desc.transport, - &local_m->desc.transport); + &local_m->desc.transport); if (status != PJ_SUCCESS) - return PJMEDIA_SDPNEG_EINVANSTP; + return PJMEDIA_SDPNEG_EINVANSTP; /* Get the transport protocol */ si->proto = pjmedia_sdp_transport_get_proto(&local_m->desc.transport); /* Return success if transport protocol is not RTP/AVP compatible */ if (!PJMEDIA_TP_PROTO_HAS_FLAG(si->proto, PJMEDIA_TP_PROTO_RTP_AVP)) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Check address family in remote SDP */ rem_af = pj_AF_UNSPEC(); if (pj_stricmp(&rem_conn->net_type, &ID_IN)==0) { - if (pj_stricmp(&rem_conn->addr_type, &ID_IP4)==0) { - rem_af = pj_AF_INET(); - } else if (pj_stricmp(&rem_conn->addr_type, &ID_IP6)==0) { - rem_af = pj_AF_INET6(); - } + if (pj_stricmp(&rem_conn->addr_type, &ID_IP4)==0) { + rem_af = pj_AF_INET(); + } else if (pj_stricmp(&rem_conn->addr_type, &ID_IP6)==0) { + rem_af = pj_AF_INET6(); + } } if (rem_af==pj_AF_UNSPEC()) { - /* Unsupported address family */ - return PJ_EAFNOTSUP; + /* Unsupported address family */ + return PJ_EAFNOTSUP; } /* Set remote address: */ status = pj_sockaddr_init(rem_af, &si->rem_addr, &rem_conn->addr, - rem_m->desc.port); + rem_m->desc.port); if (status != PJ_SUCCESS) { - /* Invalid IP address. */ - return PJMEDIA_EINVALIDIP; + /* Invalid IP address. */ + return PJMEDIA_EINVALIDIP; } /* Check address family of local info */ local_af = pj_AF_UNSPEC(); if (pj_stricmp(&local_conn->net_type, &ID_IN)==0) { - if (pj_stricmp(&local_conn->addr_type, &ID_IP4)==0) { - local_af = pj_AF_INET(); - } else if (pj_stricmp(&local_conn->addr_type, &ID_IP6)==0) { - local_af = pj_AF_INET6(); - } + if (pj_stricmp(&local_conn->addr_type, &ID_IP4)==0) { + local_af = pj_AF_INET(); + } else if (pj_stricmp(&local_conn->addr_type, &ID_IP6)==0) { + local_af = pj_AF_INET6(); + } } if (local_af==pj_AF_UNSPEC()) { - /* Unsupported address family */ - return PJ_SUCCESS; + /* Unsupported address family */ + return PJ_SUCCESS; } /* Set remote address: */ status = pj_sockaddr_init(local_af, &si->local_addr, &local_conn->addr, - local_m->desc.port); + local_m->desc.port); if (status != PJ_SUCCESS) { - /* Invalid IP address. */ - return PJMEDIA_EINVALIDIP; + /* Invalid IP address. */ + return PJMEDIA_EINVALIDIP; } /* Local and remote address family must match, except when ICE is used * by both sides (see also ticket #1952). */ if (local_af != rem_af) { - const pj_str_t STR_ICE_CAND = { "candidate", 9 }; - if (pjmedia_sdp_media_find_attr(rem_m, &STR_ICE_CAND, NULL)==NULL || - pjmedia_sdp_media_find_attr(local_m, &STR_ICE_CAND, NULL)==NULL) - { - return PJ_EAFNOTSUP; - } + const pj_str_t STR_ICE_CAND = { "candidate", 9 }; + if (pjmedia_sdp_media_find_attr(rem_m, &STR_ICE_CAND, NULL)==NULL || + pjmedia_sdp_media_find_attr(local_m, &STR_ICE_CAND, NULL)==NULL) + { + return PJ_EAFNOTSUP; + } } /* Media direction: */ if (local_m->desc.port == 0 || - pj_sockaddr_has_addr(&si->local_addr)==PJ_FALSE || - pj_sockaddr_has_addr(&si->rem_addr)==PJ_FALSE || - pjmedia_sdp_media_find_attr(local_m, &STR_INACTIVE, NULL)!=NULL) + pj_sockaddr_has_addr(&si->local_addr)==PJ_FALSE || + pj_sockaddr_has_addr(&si->rem_addr)==PJ_FALSE || + pjmedia_sdp_media_find_attr(local_m, &STR_INACTIVE, NULL)!=NULL) { - /* Inactive stream. */ + /* Inactive stream. */ - si->dir = PJMEDIA_DIR_NONE; + si->dir = PJMEDIA_DIR_NONE; } else if (pjmedia_sdp_media_find_attr(local_m, &STR_SENDONLY, NULL)!=NULL) { - /* Send only stream. */ + /* Send only stream. */ - si->dir = PJMEDIA_DIR_ENCODING; + si->dir = PJMEDIA_DIR_ENCODING; } else if (pjmedia_sdp_media_find_attr(local_m, &STR_RECVONLY, NULL)!=NULL) { - /* Recv only stream. */ + /* Recv only stream. */ - si->dir = PJMEDIA_DIR_DECODING; + si->dir = PJMEDIA_DIR_DECODING; } else { - /* Send and receive stream. */ + /* Send and receive stream. */ - si->dir = PJMEDIA_DIR_ENCODING_DECODING; + si->dir = PJMEDIA_DIR_ENCODING_DECODING; } /* No need to do anything else if stream is rejected */ if (local_m->desc.port == 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Check if "rtcp-mux" is present in the SDP. */ attr = pjmedia_sdp_attr_find2(rem_m->attr_count, rem_m->attr, - "rtcp-mux", NULL); + "rtcp-mux", NULL); if (attr) - si->rtcp_mux = PJ_TRUE; + si->rtcp_mux = PJ_TRUE; /* If "rtcp" attribute is present in the SDP, set the RTCP address * from that attribute. Otherwise, calculate from RTP address. */ attr = pjmedia_sdp_attr_find2(rem_m->attr_count, rem_m->attr, - "rtcp", NULL); + "rtcp", NULL); if (attr) { - pjmedia_sdp_rtcp_attr rtcp; - status = pjmedia_sdp_attr_get_rtcp(attr, &rtcp); - if (status == PJ_SUCCESS) { - if (rtcp.addr.slen) { - status = pj_sockaddr_init(rem_af, &si->rem_rtcp, &rtcp.addr, - (pj_uint16_t)rtcp.port); - } else { - pj_sockaddr_init(rem_af, &si->rem_rtcp, NULL, - (pj_uint16_t)rtcp.port); - pj_memcpy(pj_sockaddr_get_addr(&si->rem_rtcp), - pj_sockaddr_get_addr(&si->rem_addr), - pj_sockaddr_get_addr_len(&si->rem_addr)); - } - } + pjmedia_sdp_rtcp_attr rtcp; + status = pjmedia_sdp_attr_get_rtcp(attr, &rtcp); + if (status == PJ_SUCCESS) { + if (rtcp.addr.slen) { + status = pj_sockaddr_init(rem_af, &si->rem_rtcp, &rtcp.addr, + (pj_uint16_t)rtcp.port); + } else { + pj_sockaddr_init(rem_af, &si->rem_rtcp, NULL, + (pj_uint16_t)rtcp.port); + pj_memcpy(pj_sockaddr_get_addr(&si->rem_rtcp), + pj_sockaddr_get_addr(&si->rem_addr), + pj_sockaddr_get_addr_len(&si->rem_addr)); + } + } } if (!pj_sockaddr_has_addr(&si->rem_rtcp)) { - int rtcp_port; + int rtcp_port; - pj_memcpy(&si->rem_rtcp, &si->rem_addr, sizeof(pj_sockaddr)); - rtcp_port = pj_sockaddr_get_port(&si->rem_addr) + 1; - pj_sockaddr_set_port(&si->rem_rtcp, (pj_uint16_t)rtcp_port); + pj_memcpy(&si->rem_rtcp, &si->rem_addr, sizeof(pj_sockaddr)); + rtcp_port = pj_sockaddr_get_port(&si->rem_addr) + 1; + pj_sockaddr_set_port(&si->rem_rtcp, (pj_uint16_t)rtcp_port); } /* Check if "ssrc" attribute is present in the SDP. */ for (i = 0; i < rem_m->attr_count; i++) { - if (pj_strcmp2(&rem_m->attr[i]->name, "ssrc") == 0) { - pjmedia_sdp_ssrc_attr ssrc; - - status = pjmedia_sdp_attr_get_ssrc( - (const pjmedia_sdp_attr *)rem_m->attr[i], &ssrc); - if (status == PJ_SUCCESS) { - si->has_rem_ssrc = PJ_TRUE; - si->rem_ssrc = ssrc.ssrc; - if (ssrc.cname.slen > 0) { - pj_strdup(pool, &si->rem_cname, &ssrc.cname); - break; - } - } - } + if (pj_strcmp2(&rem_m->attr[i]->name, "ssrc") == 0) { + pjmedia_sdp_ssrc_attr ssrc; + + status = pjmedia_sdp_attr_get_ssrc( + (const pjmedia_sdp_attr *)rem_m->attr[i], &ssrc); + if (status == PJ_SUCCESS) { + si->has_rem_ssrc = PJ_TRUE; + si->rem_ssrc = ssrc.ssrc; + if (ssrc.cname.slen > 0) { + pj_strdup(pool, &si->rem_cname, &ssrc.cname); + break; + } + } + } } /* Get codec info and param */ @@ -402,15 +401,15 @@ PJ_DEF(pj_status_t) pjmedia_vid_stream_info_from_sdp( /* Get local RTCP-FB info */ status = pjmedia_rtcp_fb_decode_sdp2(pool, endpt, NULL, local, stream_idx, - si->rx_pt, &si->loc_rtcp_fb); + si->rx_pt, &si->loc_rtcp_fb); if (status != PJ_SUCCESS) - return status; + return status; /* Get remote RTCP-FB info */ status = pjmedia_rtcp_fb_decode_sdp2(pool, endpt, NULL, remote, stream_idx, - si->tx_pt, &si->rem_rtcp_fb); + si->tx_pt, &si->rem_rtcp_fb); if (status != PJ_SUCCESS) - return status; + return status; return status; } diff --git a/pjmedia/src/pjmedia/vid_tee.c b/pjmedia/src/pjmedia/vid_tee.c index d7c8ded7cb..f830895eef 100644 --- a/pjmedia/src/pjmedia/vid_tee.c +++ b/pjmedia/src/pjmedia/vid_tee.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011 Teluu Inc. (http://www.teluu.com) * @@ -27,31 +26,31 @@ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -#define TEE_PORT_NAME "vid_tee" -#define TEE_PORT_SIGN PJMEDIA_SIG_PORT_VID_TEE +#define TEE_PORT_NAME "vid_tee" +#define TEE_PORT_SIGN PJMEDIA_SIG_PORT_VID_TEE -#define THIS_FILE "vid_tee.c" +#define THIS_FILE "vid_tee.c" typedef struct vid_tee_dst_port { - pjmedia_port *dst; - unsigned option; + pjmedia_port *dst; + unsigned option; } vid_tee_dst_port; typedef struct vid_tee_port { - pjmedia_port base; + pjmedia_port base; pj_pool_t *pool; pj_pool_factory *pf; pj_pool_t *buf_pool; - void *buf[2]; + void *buf[2]; unsigned buf_cnt; - pj_size_t buf_size; - unsigned dst_port_maxcnt; - unsigned dst_port_cnt; - vid_tee_dst_port *dst_ports; - pj_uint8_t *put_frm_flag; + pj_size_t buf_size; + unsigned dst_port_maxcnt; + unsigned dst_port_cnt; + vid_tee_dst_port *dst_ports; + pj_uint8_t *put_frm_flag; struct vid_tee_conv_t { pjmedia_converter *conv; @@ -68,9 +67,9 @@ static pj_status_t tee_destroy(pjmedia_port *port); * Create a video tee port with the specified source media port. */ PJ_DEF(pj_status_t) pjmedia_vid_tee_create( pj_pool_t *pool, - const pjmedia_format *fmt, - unsigned max_dst_cnt, - pjmedia_port **p_vid_tee) + const pjmedia_format *fmt, + unsigned max_dst_cnt, + pjmedia_port **p_vid_tee) { vid_tee_port *tee; pj_str_t name_st; @@ -95,30 +94,30 @@ PJ_DEF(pj_status_t) pjmedia_vid_tee_create( pj_pool_t *pool, pj_pool_calloc(pool, max_dst_cnt, sizeof(struct vid_tee_conv_t)); tee->put_frm_flag = (pj_uint8_t*) - pj_pool_calloc(pool, max_dst_cnt, - sizeof(tee->put_frm_flag[0])); + pj_pool_calloc(pool, max_dst_cnt, + sizeof(tee->put_frm_flag[0])); /* Initialize video tee buffer, its size is one frame */ vfi = pjmedia_get_video_format_info(NULL, fmt->id); if (vfi == NULL) - return PJMEDIA_EBADFMT; + return PJMEDIA_EBADFMT; pj_bzero(&vafp, sizeof(vafp)); vafp.size = fmt->det.vid.size; status = vfi->apply_fmt(vfi, &vafp); if (status != PJ_SUCCESS) - return status; + return status; tee->buf_size = vafp.framebytes; /* Initialize video tee port */ status = pjmedia_port_info_init2(&tee->base.info, - pj_strset2(&name_st, (char*)TEE_PORT_NAME), - TEE_PORT_SIGN, - PJMEDIA_DIR_ENCODING, - fmt); + pj_strset2(&name_st, (char*)TEE_PORT_NAME), + TEE_PORT_SIGN, + PJMEDIA_DIR_ENCODING, + fmt); if (status != PJ_SUCCESS) - return status; + return status; tee->base.get_frame = &tee_get_frame; tee->base.put_frame = &tee_put_frame; @@ -164,24 +163,24 @@ static void realloc_buf(vid_tee_port *vid_tee, * Add a destination media port to the video tee. */ PJ_DEF(pj_status_t) pjmedia_vid_tee_add_dst_port(pjmedia_port *vid_tee, - unsigned option, - pjmedia_port *port) + unsigned option, + pjmedia_port *port) { vid_tee_port *tee = (vid_tee_port*)vid_tee; pjmedia_video_format_detail *vfd; PJ_ASSERT_RETURN(vid_tee && vid_tee->info.signature==TEE_PORT_SIGN, - PJ_EINVAL); + PJ_EINVAL); if (tee->dst_port_cnt >= tee->dst_port_maxcnt) - return PJ_ETOOMANY; + return PJ_ETOOMANY; if (vid_tee->info.fmt.id != port->info.fmt.id) - return PJMEDIA_EBADFMT; + return PJMEDIA_EBADFMT; vfd = pjmedia_format_get_video_format_detail(&port->info.fmt, PJ_TRUE); if (vfd->size.w != vid_tee->info.fmt.det.vid.size.w || - vfd->size.h != vid_tee->info.fmt.det.vid.size.h) + vfd->size.h != vid_tee->info.fmt.det.vid.size.h) { return PJMEDIA_EBADFMT; } @@ -203,17 +202,17 @@ PJ_DEF(pj_status_t) pjmedia_vid_tee_add_dst_port(pjmedia_port *vid_tee, * necessary. */ PJ_DEF(pj_status_t) pjmedia_vid_tee_add_dst_port2(pjmedia_port *vid_tee, - unsigned option, - pjmedia_port *port) + unsigned option, + pjmedia_port *port) { vid_tee_port *tee = (vid_tee_port*)vid_tee; pjmedia_video_format_detail *vfd; PJ_ASSERT_RETURN(vid_tee && vid_tee->info.signature==TEE_PORT_SIGN, - PJ_EINVAL); + PJ_EINVAL); if (tee->dst_port_cnt >= tee->dst_port_maxcnt) - return PJ_ETOOMANY; + return PJ_ETOOMANY; pj_bzero(&tee->tee_conv[tee->dst_port_cnt], sizeof(tee->tee_conv[0])); @@ -221,7 +220,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_tee_add_dst_port2(pjmedia_port *vid_tee, vfd = pjmedia_format_get_video_format_detail(&port->info.fmt, PJ_TRUE); if (vid_tee->info.fmt.id != port->info.fmt.id || vfd->size.w != vid_tee->info.fmt.det.vid.size.w || - vfd->size.h != vid_tee->info.fmt.det.vid.size.h) + vfd->size.h != vid_tee->info.fmt.det.vid.size.h) { const pjmedia_video_format_info *vfi; pjmedia_video_apply_fmt_param vafp; @@ -242,7 +241,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_tee_add_dst_port2(pjmedia_port *vid_tee, 2: 1, vafp.framebytes); pjmedia_format_copy(&conv_param.src, &vid_tee->info.fmt); - pjmedia_format_copy(&conv_param.dst, &port->info.fmt); + pjmedia_format_copy(&conv_param.dst, &port->info.fmt); status = pjmedia_converter_create( NULL, tee->pool, &conv_param, @@ -268,26 +267,26 @@ PJ_DEF(pj_status_t) pjmedia_vid_tee_add_dst_port2(pjmedia_port *vid_tee, * Remove a destination media port from the video tee. */ PJ_DEF(pj_status_t) pjmedia_vid_tee_remove_dst_port(pjmedia_port *vid_tee, - pjmedia_port *port) + pjmedia_port *port) { vid_tee_port *tee = (vid_tee_port*)vid_tee; unsigned i; PJ_ASSERT_RETURN(vid_tee && vid_tee->info.signature==TEE_PORT_SIGN, - PJ_EINVAL); + PJ_EINVAL); for (i = 0; i < tee->dst_port_cnt; ++i) { - if (tee->dst_ports[i].dst == port) { + if (tee->dst_ports[i].dst == port) { if (tee->tee_conv[i].conv) pjmedia_converter_destroy(tee->tee_conv[i].conv); - pj_array_erase(tee->dst_ports, sizeof(tee->dst_ports[0]), - tee->dst_port_cnt, i); + pj_array_erase(tee->dst_ports, sizeof(tee->dst_ports[0]), + tee->dst_port_cnt, i); pj_array_erase(tee->tee_conv, sizeof(tee->tee_conv[0]), - tee->dst_port_cnt, i); - --tee->dst_port_cnt; - return PJ_SUCCESS; - } + tee->dst_port_cnt, i); + --tee->dst_port_cnt; + return PJ_SUCCESS; + } } return PJ_ENOTFOUND; @@ -301,10 +300,10 @@ static pj_status_t tee_put_frame(pjmedia_port *port, pjmedia_frame *frame) const pj_uint8_t PUT_FRM_DONE = 1; pj_bzero(tee->put_frm_flag, tee->dst_port_cnt * - sizeof(tee->put_frm_flag[0])); + sizeof(tee->put_frm_flag[0])); for (i = 0; i < tee->dst_port_cnt; ++i) { - pjmedia_frame frame_ = *frame; + pjmedia_frame frame_ = *frame; if (tee->put_frm_flag[i]) continue; @@ -318,10 +317,10 @@ static pj_status_t tee_put_frame(pjmedia_port *port, pjmedia_frame *frame) frame, &frame_); if (status != PJ_SUCCESS) { PJ_PERROR(3, (THIS_FILE, status, - "Failed to convert frame for destination" - " port %d (%.*s)", i, - tee->dst_ports[i].dst->info.name.slen, - tee->dst_ports[i].dst->info.name.ptr)); + "Failed to convert frame for destination" + " port %d (%.*s)", i, + tee->dst_ports[i].dst->info.name.slen, + tee->dst_ports[i].dst->info.name.ptr)); continue; } } diff --git a/pjmedia/src/pjmedia/videodev.c b/pjmedia/src/pjmedia/videodev.c index a9584ebe22..aca91a9a3d 100644 --- a/pjmedia/src/pjmedia/videodev.c +++ b/pjmedia/src/pjmedia/videodev.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -29,7 +28,7 @@ #define THIS_FILE "videodev.c" -#define DEFINE_CAP(name, info) {name, info} +#define DEFINE_CAP(name, info) {name, info} /* Capability names */ static struct cap_info @@ -60,13 +59,13 @@ static struct cap_info * factory only. */ #define MAKE_DEV_ID(f_id, index) (((f_id & 0xFFFF) << 16) | (index & 0xFFFF)) -#define GET_INDEX(dev_id) ((dev_id) & 0xFFFF) -#define GET_FID(dev_id) ((dev_id) >> 16) -#define DEFAULT_DEV_ID 0 +#define GET_INDEX(dev_id) ((dev_id) & 0xFFFF) +#define GET_FID(dev_id) ((dev_id) >> 16) +#define DEFAULT_DEV_ID 0 -#define MAX_DRIVERS PJMEDIA_VID_DEV_MAX_DRIVERS -#define MAX_DEVS PJMEDIA_VID_DEV_MAX_DEVS +#define MAX_DRIVERS PJMEDIA_VID_DEV_MAX_DRIVERS +#define MAX_DEVS PJMEDIA_VID_DEV_MAX_DEVS static pjmedia_vid_subsys vid_subsys; @@ -80,7 +79,7 @@ PJ_DEF(pjmedia_vid_subsys*) pjmedia_get_vid_subsys(void) /* API: get capability name/info */ PJ_DEF(const char*) pjmedia_vid_dev_cap_name(pjmedia_vid_dev_cap cap, - const char **p_desc) + const char **p_desc) { const char *desc; unsigned i; @@ -88,13 +87,13 @@ PJ_DEF(const char*) pjmedia_vid_dev_cap_name(pjmedia_vid_dev_cap cap, if (p_desc==NULL) p_desc = &desc; for (i=0; iname; \ - *size = sizeof(param->name) + *size = sizeof(param->name) switch (cap) { case PJMEDIA_VID_DEV_CAP_FORMAT: - FIELD_INFO(fmt); - break; + FIELD_INFO(fmt); + break; case PJMEDIA_VID_DEV_CAP_INPUT_SCALE: - FIELD_INFO(disp_size); - break; + FIELD_INFO(disp_size); + break; case PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW: - FIELD_INFO(window); - break; + FIELD_INFO(window); + break; case PJMEDIA_VID_DEV_CAP_OUTPUT_RESIZE: - FIELD_INFO(disp_size); - break; + FIELD_INFO(disp_size); + break; case PJMEDIA_VID_DEV_CAP_OUTPUT_POSITION: - FIELD_INFO(window_pos); - break; + FIELD_INFO(window_pos); + break; case PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE: - FIELD_INFO(window_hide); - break; + FIELD_INFO(window_hide); + break; case PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW: - FIELD_INFO(native_preview); - break; + FIELD_INFO(native_preview); + break; case PJMEDIA_VID_DEV_CAP_ORIENTATION: - FIELD_INFO(orient); - break; + FIELD_INFO(orient); + break; /* The PJMEDIA_VID_DEV_CAP_SWITCH does not have an entry in the * param (it doesn't make sense to open a stream and tell it * to switch immediately). */ case PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS: - FIELD_INFO(window_flags); - break; + FIELD_INFO(window_flags); + break; case PJMEDIA_VID_DEV_CAP_OUTPUT_FULLSCREEN: - FIELD_INFO(window_fullscreen); - break; + FIELD_INFO(window_fullscreen); + break; default: - return PJMEDIA_EVID_INVCAP; + return PJMEDIA_EVID_INVCAP; } #undef FIELD_INFO @@ -156,8 +155,8 @@ static pj_status_t get_cap_pointer(const pjmedia_vid_dev_param *param, /* API: set cap value to param */ PJ_DEF(pj_status_t) pjmedia_vid_dev_param_set_cap( pjmedia_vid_dev_param *param, - pjmedia_vid_dev_cap cap, - const void *pval) + pjmedia_vid_dev_cap cap, + const void *pval) { void *cap_ptr; unsigned cap_size; @@ -165,7 +164,7 @@ pjmedia_vid_dev_param_set_cap( pjmedia_vid_dev_param *param, status = get_cap_pointer(param, cap, &cap_ptr, &cap_size); if (status != PJ_SUCCESS) - return status; + return status; pj_memcpy(cap_ptr, pval, cap_size); param->flags |= cap; @@ -176,8 +175,8 @@ pjmedia_vid_dev_param_set_cap( pjmedia_vid_dev_param *param, /* API: get cap value from param */ PJ_DEF(pj_status_t) pjmedia_vid_dev_param_get_cap( const pjmedia_vid_dev_param *param, - pjmedia_vid_dev_cap cap, - void *pval) + pjmedia_vid_dev_cap cap, + void *pval) { void *cap_ptr; unsigned cap_size; @@ -185,11 +184,11 @@ pjmedia_vid_dev_param_get_cap( const pjmedia_vid_dev_param *param, status = get_cap_pointer(param, cap, &cap_ptr, &cap_size); if (status != PJ_SUCCESS) - return status; + return status; if ((param->flags & cap) == 0) { - pj_bzero(cap_ptr, cap_size); - return PJMEDIA_EVID_INVCAP; + pj_bzero(cap_ptr, cap_size); + return PJMEDIA_EVID_INVCAP; } pj_memcpy(pval, cap_ptr, cap_size); @@ -198,7 +197,7 @@ pjmedia_vid_dev_param_get_cap( const pjmedia_vid_dev_param *param, /* API: init driver */ PJ_DEF(pj_status_t) pjmedia_vid_driver_init(unsigned drv_idx, - pj_bool_t refresh) + pj_bool_t refresh) { pjmedia_vid_driver *drv = &vid_subsys.drv[drv_idx]; pjmedia_vid_dev_factory *f; @@ -218,16 +217,16 @@ PJ_DEF(pj_status_t) pjmedia_vid_driver_init(unsigned drv_idx, return status; } } else { - f = drv->f; + f = drv->f; } /* Get number of devices */ dev_cnt = f->op->get_dev_count(f); if (dev_cnt + vid_subsys.dev_cnt > MAX_DEVS) { - PJ_LOG(4,(THIS_FILE, "%d device(s) cannot be registered because" - " there are too many devices", - vid_subsys.dev_cnt + dev_cnt - MAX_DEVS)); - dev_cnt = MAX_DEVS - vid_subsys.dev_cnt; + PJ_LOG(4,(THIS_FILE, "%d device(s) cannot be registered because" + " there are too many devices", + vid_subsys.dev_cnt + dev_cnt - MAX_DEVS)); + dev_cnt = MAX_DEVS - vid_subsys.dev_cnt; } /* enabling this will cause pjsua-lib initialization to fail when there @@ -235,41 +234,41 @@ PJ_DEF(pj_status_t) pjmedia_vid_driver_init(unsigned drv_idx, * run with --null-video * if (dev_cnt == 0) { - f->op->destroy(f); - return PJMEDIA_EVID_NODEV; + f->op->destroy(f); + return PJMEDIA_EVID_NODEV; } */ /* Fill in default devices */ drv->rend_dev_idx = drv->cap_dev_idx = -1; for (i=0; iop->get_dev_info(f, i, &info); - if (status != PJ_SUCCESS) { - f->op->destroy(f); - return status; - } - - if (drv->name[0]=='\0') { - /* Set driver name */ - pj_ansi_strncpy(drv->name, info.driver, sizeof(drv->name)); - drv->name[sizeof(drv->name)-1] = '\0'; - } - - if (drv->rend_dev_idx < 0 && (info.dir & PJMEDIA_DIR_RENDER)) { - /* Set default render device */ - drv->rend_dev_idx = i; - } - if (drv->cap_dev_idx < 0 && (info.dir & PJMEDIA_DIR_CAPTURE)) { - /* Set default capture device */ - drv->cap_dev_idx = i; - } + pjmedia_vid_dev_info info; + + status = f->op->get_dev_info(f, i, &info); + if (status != PJ_SUCCESS) { + f->op->destroy(f); + return status; + } + + if (drv->name[0]=='\0') { + /* Set driver name */ + pj_ansi_strncpy(drv->name, info.driver, sizeof(drv->name)); + drv->name[sizeof(drv->name)-1] = '\0'; + } + + if (drv->rend_dev_idx < 0 && (info.dir & PJMEDIA_DIR_RENDER)) { + /* Set default render device */ + drv->rend_dev_idx = i; + } + if (drv->cap_dev_idx < 0 && (info.dir & PJMEDIA_DIR_CAPTURE)) { + /* Set default capture device */ + drv->cap_dev_idx = i; + } if (drv->rend_dev_idx >= 0 && drv->cap_dev_idx >= 0) { - /* Done. */ - break; - } + /* Done. */ + break; + } } /* Register the factory */ @@ -280,7 +279,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_driver_init(unsigned drv_idx, /* Register devices to global list */ for (i=0; if) { - drv->f->op->destroy(drv->f); - drv->f = NULL; + drv->f->op->destroy(drv->f); + drv->f = NULL; } drv->dev_cnt = 0; @@ -308,16 +307,16 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_refresh(void) vid_subsys.dev_cnt = 0; for (i=0; if && drv->f->op->refresh) { - pj_status_t status = drv->f->op->refresh(drv->f); - if (status != PJ_SUCCESS) { - PJ_PERROR(4, (THIS_FILE, status, "Unable to refresh device " - "list for %s", drv->name)); - } - } - pjmedia_vid_driver_init(i, PJ_TRUE); + pjmedia_vid_driver *drv = &vid_subsys.drv[i]; + + if (drv->f && drv->f->op->refresh) { + pj_status_t status = drv->f->op->refresh(drv->f); + if (status != PJ_SUCCESS) { + PJ_PERROR(4, (THIS_FILE, status, "Unable to refresh device " + "list for %s", drv->name)); + } + } + pjmedia_vid_driver_init(i, PJ_TRUE); } return PJ_SUCCESS; } @@ -330,10 +329,10 @@ PJ_DEF(unsigned) pjmedia_vid_dev_count(void) /* Internal: convert local index to global device index */ static pj_status_t make_global_index(unsigned drv_idx, - pjmedia_vid_dev_index *id) + pjmedia_vid_dev_index *id) { if (*id < 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Check that factory still exists */ @@ -341,7 +340,7 @@ static pj_status_t make_global_index(unsigned drv_idx, /* Check that device index is valid */ PJ_ASSERT_RETURN(*id>=0 && *id<(int)vid_subsys.drv[drv_idx].dev_cnt, - PJ_EBUG); + PJ_EBUG); *id += vid_subsys.drv[drv_idx].start_idx; return PJ_SUCCESS; @@ -349,47 +348,47 @@ static pj_status_t make_global_index(unsigned drv_idx, /* Internal: lookup device id */ static pj_status_t lookup_dev(pjmedia_vid_dev_index id, - pjmedia_vid_dev_factory **p_f, - unsigned *p_local_index) + pjmedia_vid_dev_factory **p_f, + unsigned *p_local_index) { int f_id, index; if (id < 0) { - unsigned i; - - if (id <= PJMEDIA_VID_INVALID_DEV) - return PJMEDIA_EVID_INVDEV; - - for (i=0; icap_dev_idx >= 0) - { - id = drv->cap_dev_idx; - make_global_index(i, &id); - break; - } else if (id==PJMEDIA_VID_DEFAULT_RENDER_DEV && - drv->rend_dev_idx >= 0) - { - id = drv->rend_dev_idx; - make_global_index(i, &id); - break; - } - } - - if (id < 0) { - return PJMEDIA_EVID_NODEFDEV; - } + unsigned i; + + if (id <= PJMEDIA_VID_INVALID_DEV) + return PJMEDIA_EVID_INVDEV; + + for (i=0; icap_dev_idx >= 0) + { + id = drv->cap_dev_idx; + make_global_index(i, &id); + break; + } else if (id==PJMEDIA_VID_DEFAULT_RENDER_DEV && + drv->rend_dev_idx >= 0) + { + id = drv->rend_dev_idx; + make_global_index(i, &id); + break; + } + } + + if (id < 0) { + return PJMEDIA_EVID_NODEFDEV; + } } f_id = GET_FID(vid_subsys.dev_list[id]); index = GET_INDEX(vid_subsys.dev_list[id]); if (f_id < 0 || f_id >= (int)vid_subsys.drv_cnt) - return PJMEDIA_EVID_INVDEV; + return PJMEDIA_EVID_INVDEV; if (index < 0 || index >= (int)vid_subsys.drv[f_id].dev_cnt) - return PJMEDIA_EVID_INVDEV; + return PJMEDIA_EVID_INVDEV; *p_f = vid_subsys.drv[f_id].f; *p_local_index = (unsigned)index; @@ -421,7 +420,7 @@ pjmedia_vid_dev_get_global_index(const pjmedia_vid_dev_factory *f, /* API: Get device information. */ PJ_DEF(pj_status_t) pjmedia_vid_dev_get_info(pjmedia_vid_dev_index id, - pjmedia_vid_dev_info *info) + pjmedia_vid_dev_info *info) { pjmedia_vid_dev_factory *f; unsigned index; @@ -431,11 +430,11 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_get_info(pjmedia_vid_dev_index id, PJ_ASSERT_RETURN(vid_subsys.pf, PJMEDIA_EVID_INIT); if (id <= PJMEDIA_VID_INVALID_DEV) - return PJMEDIA_EVID_INVDEV; + return PJMEDIA_EVID_INVDEV; status = lookup_dev(id, &f, &index); if (status != PJ_SUCCESS) - return status; + return status; status = f->op->get_dev_info(f, index, info); @@ -448,8 +447,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_get_info(pjmedia_vid_dev_index id, /* API: find device */ PJ_DEF(pj_status_t) pjmedia_vid_dev_lookup( const char *drv_name, - const char *dev_name, - pjmedia_vid_dev_index *id) + const char *dev_name, + pjmedia_vid_dev_index *id) { pjmedia_vid_dev_factory *f = NULL; unsigned drv_idx, dev_idx; @@ -458,31 +457,31 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_lookup( const char *drv_name, PJ_ASSERT_RETURN(vid_subsys.pf, PJMEDIA_EVID_INIT); for (drv_idx=0; drv_idxop->get_dev_info(f, dev_idx, &info); - if (status != PJ_SUCCESS) - return status; + status = f->op->get_dev_info(f, dev_idx, &info); + if (status != PJ_SUCCESS) + return status; - if (!pj_ansi_stricmp(dev_name, info.name)) - break; + if (!pj_ansi_stricmp(dev_name, info.name)) + break; } if (dev_idx==vid_subsys.drv[drv_idx].dev_cnt) - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; *id = dev_idx; make_global_index(drv_idx, id); @@ -495,7 +494,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_lookup( const char *drv_name, */ PJ_DEF(pj_status_t) pjmedia_vid_dev_default_param(pj_pool_t *pool, pjmedia_vid_dev_index id, - pjmedia_vid_dev_param *param) + pjmedia_vid_dev_param *param) { pjmedia_vid_dev_factory *f; unsigned index; @@ -505,15 +504,15 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_default_param(pj_pool_t *pool, PJ_ASSERT_RETURN(vid_subsys.pf, PJMEDIA_EVID_INIT); if (id <= PJMEDIA_VID_INVALID_DEV) - return PJMEDIA_EVID_INVDEV; + return PJMEDIA_EVID_INVDEV; status = lookup_dev(id, &f, &index); if (status != PJ_SUCCESS) - return status; + return status; status = f->op->default_param(pool, f, index, param); if (status != PJ_SUCCESS) - return status; + return status; /* Normalize device IDs */ make_global_index(f->sys.drv_idx, ¶m->cap_id); @@ -524,10 +523,10 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_default_param(pj_pool_t *pool, /* API: Open video stream object using the specified parameters. */ PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_create( - pjmedia_vid_dev_param *prm, - const pjmedia_vid_dev_cb *cb, - void *user_data, - pjmedia_vid_dev_stream **p_vid_strm) + pjmedia_vid_dev_param *prm, + const pjmedia_vid_dev_cb *cb, + void *user_data, + pjmedia_vid_dev_stream **p_vid_strm) { pjmedia_vid_dev_factory *cap_f=NULL, *rend_f=NULL, *f=NULL; pj_status_t status; @@ -535,52 +534,52 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_create( PJ_ASSERT_RETURN(prm && prm->dir && p_vid_strm, PJ_EINVAL); PJ_ASSERT_RETURN(vid_subsys.pf, PJMEDIA_EVID_INIT); PJ_ASSERT_RETURN(prm->dir==PJMEDIA_DIR_CAPTURE || - prm->dir==PJMEDIA_DIR_RENDER || - prm->dir==PJMEDIA_DIR_CAPTURE_RENDER, - PJ_EINVAL); + prm->dir==PJMEDIA_DIR_RENDER || + prm->dir==PJMEDIA_DIR_CAPTURE_RENDER, + PJ_EINVAL); /* Normalize cap_id */ if (prm->dir & PJMEDIA_DIR_CAPTURE) { - unsigned index; + unsigned index; - if (prm->cap_id < 0) - prm->cap_id = PJMEDIA_VID_DEFAULT_CAPTURE_DEV; + if (prm->cap_id < 0) + prm->cap_id = PJMEDIA_VID_DEFAULT_CAPTURE_DEV; - status = lookup_dev(prm->cap_id, &cap_f, &index); - if (status != PJ_SUCCESS) - return status; + status = lookup_dev(prm->cap_id, &cap_f, &index); + if (status != PJ_SUCCESS) + return status; - prm->cap_id = index; - f = cap_f; + prm->cap_id = index; + f = cap_f; } /* Normalize rend_id */ if (prm->dir & PJMEDIA_DIR_RENDER) { - unsigned index; + unsigned index; - if (prm->rend_id < 0) - prm->rend_id = PJMEDIA_VID_DEFAULT_RENDER_DEV; + if (prm->rend_id < 0) + prm->rend_id = PJMEDIA_VID_DEFAULT_RENDER_DEV; - status = lookup_dev(prm->rend_id, &rend_f, &index); - if (status != PJ_SUCCESS) - return status; + status = lookup_dev(prm->rend_id, &rend_f, &index); + if (status != PJ_SUCCESS) + return status; - prm->rend_id = index; - f = rend_f; + prm->rend_id = index; + f = rend_f; } PJ_ASSERT_RETURN(f != NULL, PJ_EBUG); /* For now, cap_id and rend_id must belong to the same factory */ PJ_ASSERT_RETURN((prm->dir != PJMEDIA_DIR_CAPTURE_RENDER) || - (cap_f == rend_f), - PJMEDIA_EVID_INVDEV); + (cap_f == rend_f), + PJMEDIA_EVID_INVDEV); /* Create the stream */ status = f->op->create_stream(f, prm, cb, - user_data, p_vid_strm); + user_data, p_vid_strm); if (status != PJ_SUCCESS) - return status; + return status; /* Assign factory id to the stream */ (*p_vid_strm)->sys.drv_idx = f->sys.drv_idx; @@ -589,8 +588,8 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_create( /* API: Get the running parameters for the specified video stream. */ PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_get_param( - pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_param *param) + pjmedia_vid_dev_stream *strm, + pjmedia_vid_dev_param *param) { pj_status_t status; @@ -599,7 +598,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_get_param( status = strm->op->get_param(strm, param); if (status != PJ_SUCCESS) - return status; + return status; /* Normalize device id's */ make_global_index(strm->sys.drv_idx, ¶m->cap_id); @@ -610,38 +609,38 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_get_param( /* API: Get the value of a specific capability of the video stream. */ PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_get_cap( - pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - void *value) + pjmedia_vid_dev_stream *strm, + pjmedia_vid_dev_cap cap, + void *value) { return strm->op->get_cap(strm, cap, value); } /* API: Set the value of a specific capability of the video stream. */ PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_set_cap( - pjmedia_vid_dev_stream *strm, - pjmedia_vid_dev_cap cap, - const void *value) + pjmedia_vid_dev_stream *strm, + pjmedia_vid_dev_cap cap, + const void *value) { /* For fast switching, device global index needs to be converted to * local index before forwarding the request to the device stream. */ if (cap == PJMEDIA_VID_DEV_CAP_SWITCH) { - pjmedia_vid_dev_factory *f; - unsigned local_idx; - pj_status_t status; - pjmedia_vid_dev_switch_param p = *(pjmedia_vid_dev_switch_param*)value; + pjmedia_vid_dev_factory *f; + unsigned local_idx; + pj_status_t status; + pjmedia_vid_dev_switch_param p = *(pjmedia_vid_dev_switch_param*)value; - status = lookup_dev(p.target_id, &f, &local_idx); - if (status != PJ_SUCCESS) - return status; + status = lookup_dev(p.target_id, &f, &local_idx); + if (status != PJ_SUCCESS) + return status; - /* Make sure that current & target devices share the same factory */ - if (f->sys.drv_idx != strm->sys.drv_idx) - return PJMEDIA_EVID_INVDEV; + /* Make sure that current & target devices share the same factory */ + if (f->sys.drv_idx != strm->sys.drv_idx) + return PJMEDIA_EVID_INVDEV; - p.target_id = local_idx; - return strm->op->set_cap(strm, cap, &p); + p.target_id = local_idx; + return strm->op->set_cap(strm, cap, &p); } return strm->op->set_cap(strm, cap, value); @@ -653,11 +652,11 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_start(pjmedia_vid_dev_stream *strm) pj_status_t status; if (pjmedia_vid_dev_stream_is_running(strm)) - return PJ_SUCCESS; + return PJ_SUCCESS; status = strm->op->start(strm); if (status == PJ_SUCCESS) - strm->sys.is_running = PJ_TRUE; + strm->sys.is_running = PJ_TRUE; return status; } @@ -669,15 +668,15 @@ pjmedia_vid_dev_stream_is_running(pjmedia_vid_dev_stream *strm) } PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_get_frame( - pjmedia_vid_dev_stream *strm, - pjmedia_frame *frame) + pjmedia_vid_dev_stream *strm, + pjmedia_frame *frame) { pj_assert(strm->op->get_frame); return strm->op->get_frame(strm, frame); } PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_put_frame( - pjmedia_vid_dev_stream *strm, + pjmedia_vid_dev_stream *strm, const pjmedia_frame *frame) { pj_assert(strm->op->put_frame); @@ -693,7 +692,7 @@ PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_stop(pjmedia_vid_dev_stream *strm) /* API: Destroy the stream. */ PJ_DEF(pj_status_t) pjmedia_vid_dev_stream_destroy( - pjmedia_vid_dev_stream *strm) + pjmedia_vid_dev_stream *strm) { strm->sys.is_running = PJ_FALSE; return strm->op->destroy(strm); diff --git a/pjmedia/src/pjmedia/wav_player.c b/pjmedia/src/pjmedia/wav_player.c index 8053bdc117..83c874e902 100644 --- a/pjmedia/src/pjmedia/wav_player.c +++ b/pjmedia/src/pjmedia/wav_player.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,11 +31,11 @@ #define THIS_FILE "wav_player.c" -#define SIGNATURE PJMEDIA_SIG_PORT_WAV_PLAYER -#define BITS_PER_SAMPLE 16 +#define SIGNATURE PJMEDIA_SIG_PORT_WAV_PLAYER +#define BITS_PER_SAMPLE 16 #if 1 -# define TRACE_(x) PJ_LOG(4,x) +# define TRACE_(x) PJ_LOG(4,x) #else # define TRACE_(x) #endif @@ -44,10 +43,10 @@ #if defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN!=0 static void samples_to_host(pj_int16_t *samples, unsigned count) { - unsigned i; - for (i=0; ibase.info, &name, SIGNATURE, - 8000, 1, 16, 80); + 8000, 1, 16, 80); port->base.get_frame = &file_get_frame; port->base.on_destroy = &file_on_destroy; @@ -118,17 +117,17 @@ static pj_status_t fill_buffer(struct file_reader_port *fport) while (size_left > 0) { - /* Calculate how many bytes to read in this run. */ - size = size_to_read = size_left; - status = pj_file_read(fport->fd, - &fport->buf[fport->bufsize-size_left], - &size); - if (status != PJ_SUCCESS) - return status; - if (size < 0) { - /* Should return more appropriate error code here.. */ - return PJ_ECANCELLED; - } + /* Calculate how many bytes to read in this run. */ + size = size_to_read = size_left; + status = pj_file_read(fport->fd, + &fport->buf[fport->bufsize-size_left], + &size); + if (status != PJ_SUCCESS) + return status; + if (size < 0) { + /* Should return more appropriate error code here.. */ + return PJ_ECANCELLED; + } if (size > (pj_ssize_t)fport->data_left) { /* We passed the end of the data chunk, @@ -137,13 +136,13 @@ static pj_status_t fill_buffer(struct file_reader_port *fport) size = (pj_ssize_t)fport->data_left; } - size_left -= (pj_uint32_t)size; + size_left -= (pj_uint32_t)size; fport->data_left -= (pj_uint32_t)size; - fport->fpos += size; + fport->fpos += size; - /* If size is less than size_to_read, it indicates that we've - * encountered EOF. Rewind the file. - */ + /* If size is less than size_to_read, it indicates that we've + * encountered EOF. Rewind the file. + */ if (size < (pj_ssize_t)size_to_read) { fport->eof = PJ_TRUE; fport->eofpos = fport->buf + fport->bufsize - size_left; @@ -159,19 +158,19 @@ static pj_status_t fill_buffer(struct file_reader_port *fport) int val = pjmedia_linear2alaw(0); pj_memset(fport->eofpos, val, size_left); } - size_left = 0; + size_left = 0; } - /* Rewind file */ - fport->fpos = fport->start_data; - pj_file_setpos( fport->fd, fport->fpos, PJ_SEEK_SET); + /* Rewind file */ + fport->fpos = fport->start_data; + pj_file_setpos( fport->fd, fport->fpos, PJ_SEEK_SET); fport->data_left = fport->data_len; - } + } } /* Convert samples to host rep */ samples_to_host((pj_int16_t*)fport->buf, - fport->bufsize/fport->bytes_per_sample); + fport->bufsize/fport->bytes_per_sample); return PJ_SUCCESS; } @@ -181,11 +180,11 @@ static pj_status_t fill_buffer(struct file_reader_port *fport) * Create WAVE player port. */ PJ_DEF(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool, - const char *filename, - unsigned ptime, - unsigned options, - pj_ssize_t buff_size, - pjmedia_port **p_port ) + const char *filename, + unsigned ptime, + unsigned options, + pj_ssize_t buff_size, + pjmedia_port **p_port ) { pjmedia_wave_hdr wave_hdr; pj_ssize_t size_read; @@ -203,12 +202,12 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool, /* Check the file really exists. */ if (!pj_file_exists(filename)) { - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; } /* Normalize ptime */ if (ptime == 0) - ptime = 20; + ptime = 20; /* Normalize buff_size */ if (buff_size < 1) buff_size = PJMEDIA_FILE_PORT_BUFSIZE; @@ -217,7 +216,7 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool, /* Create fport instance. */ fport = create_file_port(pool); if (!fport) { - return PJ_ENOMEM; + return PJ_ENOMEM; } @@ -226,24 +225,24 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool, /* Size must be more than WAVE header size */ if (fport->fsize <= sizeof(pjmedia_wave_hdr)) { - return PJMEDIA_ENOTVALIDWAVE; + return PJMEDIA_ENOTVALIDWAVE; } /* Open file. */ status = pj_file_open( pool, filename, PJ_O_RDONLY, &fport->fd); if (status != PJ_SUCCESS) - return status; + return status; /* Read the file header plus fmt header only. */ size_to_read = size_read = sizeof(wave_hdr) - 8; status = pj_file_read( fport->fd, &wave_hdr, &size_read); if (status != PJ_SUCCESS) { - pj_file_close(fport->fd); - return status; + pj_file_close(fport->fd); + return status; } if (size_read != size_to_read) { - pj_file_close(fport->fd); - return PJMEDIA_ENOTVALIDWAVE; + pj_file_close(fport->fd); + return PJMEDIA_ENOTVALIDWAVE; } /* Normalize WAVE header fields values from little-endian to host @@ -253,91 +252,91 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool, /* Validate WAVE file. */ if (wave_hdr.riff_hdr.riff != PJMEDIA_RIFF_TAG || - wave_hdr.riff_hdr.wave != PJMEDIA_WAVE_TAG || - wave_hdr.fmt_hdr.fmt != PJMEDIA_FMT_TAG) + wave_hdr.riff_hdr.wave != PJMEDIA_WAVE_TAG || + wave_hdr.fmt_hdr.fmt != PJMEDIA_FMT_TAG) { - pj_file_close(fport->fd); - TRACE_((THIS_FILE, - "actual value|expected riff=%x|%x, wave=%x|%x fmt=%x|%x", - wave_hdr.riff_hdr.riff, PJMEDIA_RIFF_TAG, - wave_hdr.riff_hdr.wave, PJMEDIA_WAVE_TAG, - wave_hdr.fmt_hdr.fmt, PJMEDIA_FMT_TAG)); - return PJMEDIA_ENOTVALIDWAVE; + pj_file_close(fport->fd); + TRACE_((THIS_FILE, + "actual value|expected riff=%x|%x, wave=%x|%x fmt=%x|%x", + wave_hdr.riff_hdr.riff, PJMEDIA_RIFF_TAG, + wave_hdr.riff_hdr.wave, PJMEDIA_WAVE_TAG, + wave_hdr.fmt_hdr.fmt, PJMEDIA_FMT_TAG)); + return PJMEDIA_ENOTVALIDWAVE; } /* Validate format and its attributes (i.e: bits per sample, block align) */ switch (wave_hdr.fmt_hdr.fmt_tag) { case PJMEDIA_WAVE_FMT_TAG_PCM: - if (wave_hdr.fmt_hdr.bits_per_sample != 16 || - wave_hdr.fmt_hdr.block_align != 2 * wave_hdr.fmt_hdr.nchan) - status = PJMEDIA_EWAVEUNSUPP; - break; + if (wave_hdr.fmt_hdr.bits_per_sample != 16 || + wave_hdr.fmt_hdr.block_align != 2 * wave_hdr.fmt_hdr.nchan) + status = PJMEDIA_EWAVEUNSUPP; + break; case PJMEDIA_WAVE_FMT_TAG_ALAW: case PJMEDIA_WAVE_FMT_TAG_ULAW: - if (wave_hdr.fmt_hdr.bits_per_sample != 8 || - wave_hdr.fmt_hdr.block_align != wave_hdr.fmt_hdr.nchan) - status = PJMEDIA_ENOTVALIDWAVE; - break; + if (wave_hdr.fmt_hdr.bits_per_sample != 8 || + wave_hdr.fmt_hdr.block_align != wave_hdr.fmt_hdr.nchan) + status = PJMEDIA_ENOTVALIDWAVE; + break; default: - status = PJMEDIA_EWAVEUNSUPP; - break; + status = PJMEDIA_EWAVEUNSUPP; + break; } if (status != PJ_SUCCESS) { - pj_file_close(fport->fd); - return status; + pj_file_close(fport->fd); + return status; } fport->fmt_tag = (pjmedia_wave_fmt_tag)wave_hdr.fmt_hdr.fmt_tag; fport->bytes_per_sample = (pj_uint16_t) - (wave_hdr.fmt_hdr.bits_per_sample / 8); + (wave_hdr.fmt_hdr.bits_per_sample / 8); /* If length of fmt_header is greater than 16, skip the remaining * fmt header data. */ if (wave_hdr.fmt_hdr.len > 16) { - PJ_CHECK_OVERFLOW_UINT32_TO_LONG(wave_hdr.fmt_hdr.len - 16, - pj_file_close(fport->fd); return PJMEDIA_ENOTVALIDWAVE;); - size_to_read = (pj_off_t)wave_hdr.fmt_hdr.len - 16; - status = pj_file_setpos(fport->fd, size_to_read, PJ_SEEK_CUR); - if (status != PJ_SUCCESS) { - pj_file_close(fport->fd); - return status; - } + PJ_CHECK_OVERFLOW_UINT32_TO_LONG(wave_hdr.fmt_hdr.len - 16, + pj_file_close(fport->fd); return PJMEDIA_ENOTVALIDWAVE;); + size_to_read = (pj_off_t)wave_hdr.fmt_hdr.len - 16; + status = pj_file_setpos(fport->fd, size_to_read, PJ_SEEK_CUR); + if (status != PJ_SUCCESS) { + pj_file_close(fport->fd); + return status; + } } /* Repeat reading the WAVE file until we have 'data' chunk */ for (;;) { - pjmedia_wave_subchunk subchunk; - size_read = 8; - status = pj_file_read(fport->fd, &subchunk, &size_read); - if (status != PJ_SUCCESS || size_read != 8) { - pj_file_close(fport->fd); - return PJMEDIA_EWAVETOOSHORT; - } - - /* Normalize endianness */ - PJMEDIA_WAVE_NORMALIZE_SUBCHUNK(&subchunk); - - /* Break if this is "data" chunk */ - if (subchunk.id == PJMEDIA_DATA_TAG) { - wave_hdr.data_hdr.data = PJMEDIA_DATA_TAG; - wave_hdr.data_hdr.len = subchunk.len; - break; - } - - /* Otherwise skip the chunk contents */ - PJ_CHECK_OVERFLOW_UINT32_TO_LONG(subchunk.len, - pj_file_close(fport->fd); return PJMEDIA_ENOTVALIDWAVE;); - size_to_read = subchunk.len; - - status = pj_file_setpos(fport->fd, size_to_read, PJ_SEEK_CUR); - if (status != PJ_SUCCESS) { - pj_file_close(fport->fd); - return status; - } + pjmedia_wave_subchunk subchunk; + size_read = 8; + status = pj_file_read(fport->fd, &subchunk, &size_read); + if (status != PJ_SUCCESS || size_read != 8) { + pj_file_close(fport->fd); + return PJMEDIA_EWAVETOOSHORT; + } + + /* Normalize endianness */ + PJMEDIA_WAVE_NORMALIZE_SUBCHUNK(&subchunk); + + /* Break if this is "data" chunk */ + if (subchunk.id == PJMEDIA_DATA_TAG) { + wave_hdr.data_hdr.data = PJMEDIA_DATA_TAG; + wave_hdr.data_hdr.len = subchunk.len; + break; + } + + /* Otherwise skip the chunk contents */ + PJ_CHECK_OVERFLOW_UINT32_TO_LONG(subchunk.len, + pj_file_close(fport->fd); return PJMEDIA_ENOTVALIDWAVE;); + size_to_read = subchunk.len; + + status = pj_file_setpos(fport->fd, size_to_read, PJ_SEEK_CUR); + if (status != PJ_SUCCESS) { + pj_file_close(fport->fd); + return status; + } } /* Current file position now points to start of data */ @@ -348,19 +347,19 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool, /* Validate length. */ if (wave_hdr.data_hdr.len > fport->fsize - fport->start_data) { - /* Actual data length may be shorter than declared. We should still - * try to play whatever data is there instead of immediately returning - * error. - */ - wave_hdr.data_hdr.len = (pj_uint32_t)fport->fsize - fport->start_data; - // pj_file_close(fport->fd); - // return PJMEDIA_EWAVEUNSUPP; + /* Actual data length may be shorter than declared. We should still + * try to play whatever data is there instead of immediately returning + * error. + */ + wave_hdr.data_hdr.len = (pj_uint32_t)fport->fsize - fport->start_data; + // pj_file_close(fport->fd); + // return PJMEDIA_EWAVEUNSUPP; } if (wave_hdr.data_hdr.len < ptime * wave_hdr.fmt_hdr.sample_rate * - wave_hdr.fmt_hdr.nchan / 1000) + wave_hdr.fmt_hdr.nchan / 1000) { - pj_file_close(fport->fd); - return PJMEDIA_EWAVETOOSHORT; + pj_file_close(fport->fd); + return PJMEDIA_EWAVETOOSHORT; } /* It seems like we have a valid WAVE file. */ @@ -372,19 +371,19 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool, ad = pjmedia_format_get_audio_format_detail(&fport->base.info.fmt, 1); pj_strdup2(pool, &name, filename); samples_per_frame = ptime * wave_hdr.fmt_hdr.sample_rate * - wave_hdr.fmt_hdr.nchan / 1000; + wave_hdr.fmt_hdr.nchan / 1000; pjmedia_port_info_init(&fport->base.info, &name, SIGNATURE, - wave_hdr.fmt_hdr.sample_rate, - wave_hdr.fmt_hdr.nchan, - BITS_PER_SAMPLE, - samples_per_frame); + wave_hdr.fmt_hdr.sample_rate, + wave_hdr.fmt_hdr.nchan, + BITS_PER_SAMPLE, + samples_per_frame); /* If file is shorter than buffer size, adjust buffer size to file * size. Otherwise EOF callback will be called multiple times when * fill_buffer() is called. */ if (wave_hdr.data_hdr.len < (unsigned)buff_size) - buff_size = wave_hdr.data_hdr.len; + buff_size = wave_hdr.data_hdr.len; /* Create file buffer. */ @@ -395,15 +394,15 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool, * doesn't handle this case). */ if (samples_per_frame * fport->bytes_per_sample >= fport->bufsize) { - pj_file_close(fport->fd); - return PJ_EINVAL; + pj_file_close(fport->fd); + return PJ_EINVAL; } /* Create buffer. */ fport->buf = (char*) pj_pool_alloc(pool, fport->bufsize); if (!fport->buf) { - pj_file_close(fport->fd); - return PJ_ENOMEM; + pj_file_close(fport->fd); + return PJ_ENOMEM; } fport->readpos = fport->buf; @@ -414,8 +413,8 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool, /* Fill up the buffer. */ status = fill_buffer(fport); if (status != PJ_SUCCESS) { - pj_file_close(fport->fd); - return status; + pj_file_close(fport->fd); + return status; } /* Done. */ @@ -424,14 +423,14 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool, PJ_LOG(4,(THIS_FILE, - "File player '%.*s' created: samp.rate=%d, ch=%d, bufsize=%uKB, " - "filesize=%luKB", - (int)fport->base.info.name.slen, - fport->base.info.name.ptr, - ad->clock_rate, - ad->channel_count, - fport->bufsize / 1000, - (unsigned long)(fport->fsize / 1000))); + "File player '%.*s' created: samp.rate=%d, ch=%d, bufsize=%uKB, " + "filesize=%luKB", + (int)fport->base.info.name.slen, + fport->base.info.name.ptr, + ad->clock_rate, + ad->channel_count, + fport->bufsize / 1000, + (unsigned long)(fport->fsize / 1000))); return PJ_SUCCESS; } @@ -441,8 +440,8 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool, * Get additional info about the file player. */ PJ_DEF(pj_status_t) pjmedia_wav_player_get_info( - pjmedia_port *port, - pjmedia_wav_player_info *info) + pjmedia_port *port, + pjmedia_wav_player_info *info) { struct file_reader_port *fport; PJ_ASSERT_RETURN(port && info, PJ_EINVAL); @@ -455,22 +454,22 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_get_info( fport = (struct file_reader_port*) port; if (fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_PCM) { - info->fmt_id = PJMEDIA_FORMAT_PCM; - info->payload_bits_per_sample = 16; + info->fmt_id = PJMEDIA_FORMAT_PCM; + info->payload_bits_per_sample = 16; } else if (fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ULAW) { - info->fmt_id = PJMEDIA_FORMAT_ULAW; - info->payload_bits_per_sample = 8; + info->fmt_id = PJMEDIA_FORMAT_ULAW; + info->payload_bits_per_sample = 8; } else if (fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ALAW) { - info->fmt_id = PJMEDIA_FORMAT_ALAW; - info->payload_bits_per_sample = 8; + info->fmt_id = PJMEDIA_FORMAT_ALAW; + info->payload_bits_per_sample = 8; } else { - pj_assert(!"Unsupported format"); - return PJ_ENOTSUP; + pj_assert(!"Unsupported format"); + return PJ_ENOTSUP; } info->size_bytes = (pj_uint32_t)pjmedia_wav_player_get_len(port); info->size_samples = info->size_bytes / - (info->payload_bits_per_sample / 8); + (info->payload_bits_per_sample / 8); return PJ_SUCCESS; } @@ -500,7 +499,7 @@ PJ_DEF(pj_ssize_t) pjmedia_wav_player_get_len(pjmedia_port *port) * Set position. */ PJ_DEF(pj_status_t) pjmedia_wav_player_port_set_pos(pjmedia_port *port, - pj_uint32_t bytes ) + pj_uint32_t bytes ) { struct file_reader_port *fport; pj_status_t status; @@ -526,7 +525,7 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_port_set_pos(pjmedia_port *port, fport->eof = PJ_FALSE; status = fill_buffer(fport); if (status != PJ_SUCCESS) - return status; + return status; fport->readpos = fport->buf; @@ -552,11 +551,11 @@ PJ_DEF(pj_ssize_t) pjmedia_wav_player_port_get_pos( pjmedia_port *port ) payload_pos = (pj_size_t)(fport->fpos - fport->start_data); if (payload_pos == 0) - return 0; + return 0; else if (payload_pos >= fport->bufsize) - return payload_pos - fport->bufsize + (fport->readpos - fport->buf); + return payload_pos - fport->bufsize + (fport->readpos - fport->buf); else - return (fport->readpos - fport->buf) % payload_pos; + return (fport->readpos - fport->buf) % payload_pos; } @@ -566,9 +565,9 @@ PJ_DEF(pj_ssize_t) pjmedia_wav_player_port_get_pos( pjmedia_port *port ) * end of file. */ PJ_DEF(pj_status_t) pjmedia_wav_player_set_eof_cb( pjmedia_port *port, - void *user_data, - pj_status_t (*cb)(pjmedia_port *port, - void *usr_data)) + void *user_data, + pj_status_t (*cb)(pjmedia_port *port, + void *usr_data)) { struct file_reader_port *fport; @@ -579,7 +578,7 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_set_eof_cb( pjmedia_port *port, PJ_ASSERT_RETURN(port->info.signature == SIGNATURE, -PJ_EINVALIDOP); PJ_LOG(1, (THIS_FILE, "pjmedia_wav_player_set_eof_cb() is deprecated. " - "Use pjmedia_wav_player_set_eof_cb2() instead.")); + "Use pjmedia_wav_player_set_eof_cb2() instead.")); fport = (struct file_reader_port*) port; @@ -596,9 +595,9 @@ PJ_DEF(pj_status_t) pjmedia_wav_player_set_eof_cb( pjmedia_port *port, * end of file. */ PJ_DEF(pj_status_t) pjmedia_wav_player_set_eof_cb2(pjmedia_port *port, - void *user_data, - void (*cb)(pjmedia_port *port, - void *usr_data)) + void *user_data, + void (*cb)(pjmedia_port *port, + void *usr_data)) { struct file_reader_port *fport; @@ -623,8 +622,8 @@ static pj_status_t file_on_event(pjmedia_event *event, struct file_reader_port *fport = (struct file_reader_port*)user_data; if (event->type == PJMEDIA_EVENT_CALLBACK) { - if (fport->cb2) - (*fport->cb2)(&fport->base, fport->base.port_data.pdata); + if (fport->cb2) + (*fport->cb2)(&fport->base, fport->base.port_data.pdata); } return PJ_SUCCESS; @@ -635,7 +634,7 @@ static pj_status_t file_on_event(pjmedia_event *event, * Get frame from file. */ static pj_status_t file_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct file_reader_port *fport = (struct file_reader_port*)this_port; pj_size_t frame_size; @@ -646,78 +645,78 @@ static pj_status_t file_get_frame(pjmedia_port *this_port, /* EOF is set and readpos already passed the eofpos */ if (fport->eof && fport->readpos >= fport->eofpos) { - PJ_LOG(5,(THIS_FILE, "File port %.*s EOF", - (int)fport->base.info.name.slen, - fport->base.info.name.ptr)); - - /* Call callback, if any */ - if (fport->cb2) { - pj_bool_t no_loop = (fport->options & PJMEDIA_FILE_NO_LOOP); - - if (!fport->subscribed) { - status = pjmedia_event_subscribe(NULL, &file_on_event, - fport, fport); - fport->subscribed = (status == PJ_SUCCESS)? PJ_TRUE: - PJ_FALSE; - } - - if (fport->subscribed && fport->eof != 2) { - pjmedia_event event; - - if (no_loop) { - /* To prevent the callback from being called repeatedly */ - fport->eof = 2; - } else { - fport->eof = PJ_FALSE; - } - - pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, - NULL, fport); - pjmedia_event_publish(NULL, fport, &event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); - } - - /* Should not access player port after this since - * it might have been destroyed by the callback. - */ - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - - return (no_loop? PJ_EEOF: PJ_SUCCESS); - - } else if (fport->cb) { - status = (*fport->cb)(this_port, fport->base.port_data.pdata); - } - - /* If callback returns non PJ_SUCCESS or 'no loop' is specified, - * return immediately (and don't try to access player port since - * it might have been destroyed by the callback). - */ - if ((status != PJ_SUCCESS) || (fport->options & PJMEDIA_FILE_NO_LOOP)) - { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - return PJ_EEOF; - } + PJ_LOG(5,(THIS_FILE, "File port %.*s EOF", + (int)fport->base.info.name.slen, + fport->base.info.name.ptr)); + + /* Call callback, if any */ + if (fport->cb2) { + pj_bool_t no_loop = (fport->options & PJMEDIA_FILE_NO_LOOP); + + if (!fport->subscribed) { + status = pjmedia_event_subscribe(NULL, &file_on_event, + fport, fport); + fport->subscribed = (status == PJ_SUCCESS)? PJ_TRUE: + PJ_FALSE; + } + + if (fport->subscribed && fport->eof != 2) { + pjmedia_event event; + + if (no_loop) { + /* To prevent the callback from being called repeatedly */ + fport->eof = 2; + } else { + fport->eof = PJ_FALSE; + } + + pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, + NULL, fport); + pjmedia_event_publish(NULL, fport, &event, + PJMEDIA_EVENT_PUBLISH_POST_EVENT); + } + + /* Should not access player port after this since + * it might have been destroyed by the callback. + */ + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + + return (no_loop? PJ_EEOF: PJ_SUCCESS); + + } else if (fport->cb) { + status = (*fport->cb)(this_port, fport->base.port_data.pdata); + } + + /* If callback returns non PJ_SUCCESS or 'no loop' is specified, + * return immediately (and don't try to access player port since + * it might have been destroyed by the callback). + */ + if ((status != PJ_SUCCESS) || (fport->options & PJMEDIA_FILE_NO_LOOP)) + { + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + return PJ_EEOF; + } /* Rewind file */ - PJ_LOG(5,(THIS_FILE, "File port %.*s rewinding..", - (int)fport->base.info.name.slen, - fport->base.info.name.ptr)); - fport->eof = PJ_FALSE; + PJ_LOG(5,(THIS_FILE, "File port %.*s rewinding..", + (int)fport->base.info.name.slen, + fport->base.info.name.ptr)); + fport->eof = PJ_FALSE; } //pj_assert(frame->size == fport->base.info.bytes_per_frame); if (fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_PCM) { - frame_size = frame->size; - //frame->size = frame_size; + frame_size = frame->size; + //frame->size = frame_size; } else { - /* Must be ULAW or ALAW */ - pj_assert(fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ULAW || - fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ALAW); + /* Must be ULAW or ALAW */ + pj_assert(fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ULAW || + fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ALAW); - frame_size = frame->size >> 1; - frame->size = frame_size << 1; + frame_size = frame->size >> 1; + frame->size = frame_size << 1; } /* Copy frame from buffer. */ @@ -726,34 +725,34 @@ static pj_status_t file_get_frame(pjmedia_port *this_port, if ((fport->readpos + frame_size) <= (fport->buf + fport->bufsize)) { - /* Read contiguous buffer. */ - pj_memcpy(frame->buf, fport->readpos, frame_size); - - /* Fill up the buffer if all has been read. */ - fport->readpos += frame_size; - if (fport->readpos == fport->buf + fport->bufsize) { - fport->readpos = fport->buf; - - status = fill_buffer(fport); - if (status != PJ_SUCCESS) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - fport->readpos = fport->buf + fport->bufsize; - return status; - } - } + /* Read contiguous buffer. */ + pj_memcpy(frame->buf, fport->readpos, frame_size); + + /* Fill up the buffer if all has been read. */ + fport->readpos += frame_size; + if (fport->readpos == fport->buf + fport->bufsize) { + fport->readpos = fport->buf; + + status = fill_buffer(fport); + if (status != PJ_SUCCESS) { + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + fport->readpos = fport->buf + fport->bufsize; + return status; + } + } } else { - unsigned endread; + unsigned endread; - /* Split read. - * First stage: read until end of buffer. - */ - endread = (unsigned)((fport->buf+fport->bufsize) - fport->readpos); - pj_memcpy(frame->buf, fport->readpos, endread); + /* Split read. + * First stage: read until end of buffer. + */ + endread = (unsigned)((fport->buf+fport->bufsize) - fport->readpos); + pj_memcpy(frame->buf, fport->readpos, endread); - /* End Of Buffer and EOF and NO LOOP */ - if (fport->eof && (fport->options & PJMEDIA_FILE_NO_LOOP)) { - fport->readpos += endread; + /* End Of Buffer and EOF and NO LOOP */ + if (fport->eof && (fport->options & PJMEDIA_FILE_NO_LOOP)) { + fport->readpos += endread; if (fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_PCM) { pj_bzero((char*)frame->buf + endread, frame_size - endread); @@ -767,41 +766,41 @@ static pj_status_t file_get_frame(pjmedia_port *this_port, frame_size - endread); } - return PJ_SUCCESS; - } + return PJ_SUCCESS; + } - /* Second stage: fill up buffer, and read from the start of buffer. */ - status = fill_buffer(fport); - if (status != PJ_SUCCESS) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - fport->readpos = fport->buf + fport->bufsize; - return status; - } + /* Second stage: fill up buffer, and read from the start of buffer. */ + status = fill_buffer(fport); + if (status != PJ_SUCCESS) { + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + fport->readpos = fport->buf + fport->bufsize; + return status; + } - pj_memcpy(((char*)frame->buf)+endread, fport->buf, frame_size-endread); - fport->readpos = fport->buf + (frame_size - endread); + pj_memcpy(((char*)frame->buf)+endread, fport->buf, frame_size-endread); + fport->readpos = fport->buf + (frame_size - endread); } if (fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ULAW || - fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ALAW) + fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ALAW) { - unsigned i; - pj_uint16_t *dst; - pj_uint8_t *src; - - dst = (pj_uint16_t*)frame->buf + frame_size - 1; - src = (pj_uint8_t*)frame->buf + frame_size - 1; - - if (fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ULAW) { - for (i = 0; i < frame_size; ++i) { - *dst-- = (pj_uint16_t) pjmedia_ulaw2linear(*src--); - } - } else { - for (i = 0; i < frame_size; ++i) { - *dst-- = (pj_uint16_t) pjmedia_alaw2linear(*src--); - } - } + unsigned i; + pj_uint16_t *dst; + pj_uint8_t *src; + + dst = (pj_uint16_t*)frame->buf + frame_size - 1; + src = (pj_uint8_t*)frame->buf + frame_size - 1; + + if (fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ULAW) { + for (i = 0; i < frame_size; ++i) { + *dst-- = (pj_uint16_t) pjmedia_ulaw2linear(*src--); + } + } else { + for (i = 0; i < frame_size; ++i) { + *dst-- = (pj_uint16_t) pjmedia_alaw2linear(*src--); + } + } } return PJ_SUCCESS; @@ -819,8 +818,8 @@ static pj_status_t file_on_destroy(pjmedia_port *this_port) pj_file_close(fport->fd); if (fport->subscribed) { - pjmedia_event_unsubscribe(NULL, &file_on_event, fport, fport); - fport->subscribed = PJ_FALSE; + pjmedia_event_unsubscribe(NULL, &file_on_event, fport, fport); + fport->subscribed = PJ_FALSE; } return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia/wav_playlist.c b/pjmedia/src/pjmedia/wav_playlist.c index 4e2c31e0c2..6789dab2c7 100644 --- a/pjmedia/src/pjmedia/wav_playlist.c +++ b/pjmedia/src/pjmedia/wav_playlist.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,14 +29,14 @@ #include #include -#define THIS_FILE "wav_playlist.c" +#define THIS_FILE "wav_playlist.c" -#define SIGNATURE PJMEDIA_SIG_PORT_WAV_PLAYLIST +#define SIGNATURE PJMEDIA_SIG_PORT_WAV_PLAYLIST #define BYTES_PER_SAMPLE 2 #if 1 -# define TRACE_(x) PJ_LOG(4,x) +# define TRACE_(x) PJ_LOG(4,x) #else # define TRACE_(x) #endif @@ -45,10 +44,10 @@ #if defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN!=0 static void samples_to_host(pj_int16_t *samples, unsigned count) { - unsigned i; - for (i=0; ibase.info, name, SIGNATURE, - 8000, 1, 16, 80); + 8000, 1, 16, 80); port->base.get_frame = &file_list_get_frame; port->base.on_destroy = &file_list_on_destroy; @@ -112,8 +111,8 @@ static pj_status_t file_on_event(pjmedia_event *event, struct playlist_port *fport = (struct playlist_port*)user_data; if (event->type == PJMEDIA_EVENT_CALLBACK) { - if (fport->cb2) - (*fport->cb2)(&fport->base, fport->base.port_data.pdata); + if (fport->cb2) + (*fport->cb2)(&fport->base, fport->base.port_data.pdata); } return PJ_SUCCESS; @@ -133,23 +132,23 @@ static pj_status_t file_fill_buffer(struct playlist_port *fport) /* Can't read file if EOF and loop flag is disabled */ if (fport->eof) - return PJ_EEOF; + return PJ_EEOF; while (size_left > 0) { - /* Calculate how many bytes to read in this run. */ - size = size_to_read = size_left; - status = pj_file_read(fport->fd_list[current_file], - &fport->buf[fport->bufsize-size_left], - &size); - if (status != PJ_SUCCESS) - return status; - - if (size < 0) - { - /* Should return more appropriate error code here.. */ - return PJ_ECANCELLED; - } + /* Calculate how many bytes to read in this run. */ + size = size_to_read = size_left; + status = pj_file_read(fport->fd_list[current_file], + &fport->buf[fport->bufsize-size_left], + &size); + if (status != PJ_SUCCESS) + return status; + + if (size < 0) + { + /* Should return more appropriate error code here.. */ + return PJ_ECANCELLED; + } if (size > (pj_ssize_t)fport->data_left_list[current_file]) { /* We passed the end of the data chunk, @@ -157,129 +156,129 @@ static pj_status_t file_fill_buffer(struct playlist_port *fport) */ size = (pj_ssize_t)fport->data_left_list[current_file]; } - - size_left -= (pj_uint32_t)size; - fport->data_left_list[current_file] -= (pj_uint32_t)size; - fport->fpos_list[current_file] += size; - - /* If size is less than size_to_read, it indicates that we've - * encountered EOF. Rewind the file. - */ - if (size < (pj_ssize_t)size_to_read) - { - /* Rewind the file for the next iteration */ - fport->fpos_list[current_file] = - fport->start_data_list[current_file]; - pj_file_setpos(fport->fd_list[current_file], - fport->fpos_list[current_file], PJ_SEEK_SET); - fport->data_left_list[current_file] = - fport->data_len_list[current_file]; - - /* Move to next file */ - current_file++; - fport->current_file = current_file; - - if (fport->current_file == fport->max_file) - { - /* Clear the remaining part of the buffer first, to prevent - * old samples from being played. If the playback restarts, - * this will be overwritten by new reading. - */ - if (size_left > 0) { - pj_bzero(&fport->buf[fport->bufsize-size_left], - size_left); - } - - /* All files have been played. Call callback, if any. */ - if (fport->cb2) { - pj_bool_t no_loop = (fport->options & PJMEDIA_FILE_NO_LOOP); - - if (!fport->subscribed) { - status = pjmedia_event_subscribe(NULL, &file_on_event, - fport, fport); - fport->subscribed = (status == PJ_SUCCESS)? PJ_TRUE: - PJ_FALSE; - } - - if (fport->subscribed && fport->eof != 2) { - pjmedia_event event; - - if (no_loop) { - /* To prevent the callback from being called - * repeatedly. - */ - fport->eof = 2; - } else { - fport->eof = PJ_FALSE; - /* start with first file again. */ - fport->current_file = current_file = 0; - fport->fpos_list[0] = fport->start_data_list[0]; - pj_file_setpos(fport->fd_list[0], - fport->fpos_list[0], PJ_SEEK_SET); - fport->data_left_list[0] = fport->data_len_list[0]; - } - - pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, - NULL, fport); - pjmedia_event_publish(NULL, fport, &event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); - } - - /* Should not access player port after this since - * it might have been destroyed by the callback. - */ - return (no_loop? PJ_EEOF: PJ_SUCCESS); - - } else if (fport->cb) { - PJ_LOG(5,(THIS_FILE, - "File port %.*s EOF, calling callback", - (int)fport->base.info.name.slen, - fport->base.info.name.ptr)); - - fport->eof = PJ_TRUE; - - status = (*fport->cb)(&fport->base, - fport->base.port_data.pdata); - - if (status != PJ_SUCCESS) - { - /* This will crash if file port is destroyed in the - * callback, that's why we set the eof flag before - * calling the callback: - fport->eof = PJ_TRUE; - */ - return status; - } - - fport->eof = PJ_FALSE; - } - - - if (fport->options & PJMEDIA_FILE_NO_LOOP) - { - PJ_LOG(5,(THIS_FILE, "File port %.*s EOF, stopping..", - (int)fport->base.info.name.slen, - fport->base.info.name.ptr)); - fport->eof = PJ_TRUE; - return PJ_EEOF; - } - else - { - PJ_LOG(5,(THIS_FILE, "File port %.*s EOF, rewinding..", - (int)fport->base.info.name.slen, - fport->base.info.name.ptr)); - - /* start with first file again. */ - fport->current_file = current_file = 0; - fport->fpos_list[0] = fport->start_data_list[0]; - pj_file_setpos(fport->fd_list[0], fport->fpos_list[0], - PJ_SEEK_SET); - fport->data_left_list[0] = fport->data_len_list[0]; - } - - } /* if current_file == max_file */ - - } /* size < size_to_read */ + + size_left -= (pj_uint32_t)size; + fport->data_left_list[current_file] -= (pj_uint32_t)size; + fport->fpos_list[current_file] += size; + + /* If size is less than size_to_read, it indicates that we've + * encountered EOF. Rewind the file. + */ + if (size < (pj_ssize_t)size_to_read) + { + /* Rewind the file for the next iteration */ + fport->fpos_list[current_file] = + fport->start_data_list[current_file]; + pj_file_setpos(fport->fd_list[current_file], + fport->fpos_list[current_file], PJ_SEEK_SET); + fport->data_left_list[current_file] = + fport->data_len_list[current_file]; + + /* Move to next file */ + current_file++; + fport->current_file = current_file; + + if (fport->current_file == fport->max_file) + { + /* Clear the remaining part of the buffer first, to prevent + * old samples from being played. If the playback restarts, + * this will be overwritten by new reading. + */ + if (size_left > 0) { + pj_bzero(&fport->buf[fport->bufsize-size_left], + size_left); + } + + /* All files have been played. Call callback, if any. */ + if (fport->cb2) { + pj_bool_t no_loop = (fport->options & PJMEDIA_FILE_NO_LOOP); + + if (!fport->subscribed) { + status = pjmedia_event_subscribe(NULL, &file_on_event, + fport, fport); + fport->subscribed = (status == PJ_SUCCESS)? PJ_TRUE: + PJ_FALSE; + } + + if (fport->subscribed && fport->eof != 2) { + pjmedia_event event; + + if (no_loop) { + /* To prevent the callback from being called + * repeatedly. + */ + fport->eof = 2; + } else { + fport->eof = PJ_FALSE; + /* start with first file again. */ + fport->current_file = current_file = 0; + fport->fpos_list[0] = fport->start_data_list[0]; + pj_file_setpos(fport->fd_list[0], + fport->fpos_list[0], PJ_SEEK_SET); + fport->data_left_list[0] = fport->data_len_list[0]; + } + + pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, + NULL, fport); + pjmedia_event_publish(NULL, fport, &event, + PJMEDIA_EVENT_PUBLISH_POST_EVENT); + } + + /* Should not access player port after this since + * it might have been destroyed by the callback. + */ + return (no_loop? PJ_EEOF: PJ_SUCCESS); + + } else if (fport->cb) { + PJ_LOG(5,(THIS_FILE, + "File port %.*s EOF, calling callback", + (int)fport->base.info.name.slen, + fport->base.info.name.ptr)); + + fport->eof = PJ_TRUE; + + status = (*fport->cb)(&fport->base, + fport->base.port_data.pdata); + + if (status != PJ_SUCCESS) + { + /* This will crash if file port is destroyed in the + * callback, that's why we set the eof flag before + * calling the callback: + fport->eof = PJ_TRUE; + */ + return status; + } + + fport->eof = PJ_FALSE; + } + + + if (fport->options & PJMEDIA_FILE_NO_LOOP) + { + PJ_LOG(5,(THIS_FILE, "File port %.*s EOF, stopping..", + (int)fport->base.info.name.slen, + fport->base.info.name.ptr)); + fport->eof = PJ_TRUE; + return PJ_EEOF; + } + else + { + PJ_LOG(5,(THIS_FILE, "File port %.*s EOF, rewinding..", + (int)fport->base.info.name.slen, + fport->base.info.name.ptr)); + + /* start with first file again. */ + fport->current_file = current_file = 0; + fport->fpos_list[0] = fport->start_data_list[0]; + pj_file_setpos(fport->fd_list[0], fport->fpos_list[0], + PJ_SEEK_SET); + fport->data_left_list[0] = fport->data_len_list[0]; + } + + } /* if current_file == max_file */ + + } /* size < size_to_read */ } /* while () */ @@ -294,13 +293,13 @@ static pj_status_t file_fill_buffer(struct playlist_port *fport) * Create wave list player. */ PJ_DEF(pj_status_t) pjmedia_wav_playlist_create(pj_pool_t *pool, - const pj_str_t *port_label, - const pj_str_t file_list[], - int file_count, - unsigned ptime, - unsigned options, - pj_ssize_t buff_size, - pjmedia_port **p_port) + const pj_str_t *port_label, + const pj_str_t file_list[], + int file_count, + unsigned ptime, + unsigned options, + pj_ssize_t buff_size, + pjmedia_port **p_port) { struct playlist_port *fport; pjmedia_audio_format_detail *afd; @@ -309,7 +308,7 @@ PJ_DEF(pj_status_t) pjmedia_wav_playlist_create(pj_pool_t *pool, int index; pj_bool_t has_wave_info = PJ_FALSE; pj_str_t tmp_port_label; - char filename[PJ_MAXPATH]; /* filename for open operations. */ + char filename[PJ_MAXPATH]; /* filename for open operations. */ /* Check arguments. */ @@ -317,37 +316,37 @@ PJ_DEF(pj_status_t) pjmedia_wav_playlist_create(pj_pool_t *pool, /* Normalize port_label */ if (port_label == NULL || port_label->slen == 0) { - tmp_port_label = pj_str("WAV playlist"); - port_label = &tmp_port_label; + tmp_port_label = pj_str("WAV playlist"); + port_label = &tmp_port_label; } - /* Be sure all files exist */ + /* Be sure all files exist */ for (index=0; index= 0, PJ_ETOOSMALL); - if (file_list[index].slen >= PJ_MAXPATH) - return PJ_ENAMETOOLONG; + PJ_ASSERT_RETURN(file_list[index].slen >= 0, PJ_ETOOSMALL); + if (file_list[index].slen >= PJ_MAXPATH) + return PJ_ENAMETOOLONG; - pj_memcpy(filename, file_list[index].ptr, file_list[index].slen); - filename[file_list[index].slen] = '\0'; + pj_memcpy(filename, file_list[index].ptr, file_list[index].slen); + filename[file_list[index].slen] = '\0'; - /* Check the file really exists. */ - if (!pj_file_exists(filename)) { - PJ_LOG(4,(THIS_FILE, - "WAV playlist error: file '%s' not found", - filename)); - return PJ_ENOTFOUND; - } + /* Check the file really exists. */ + if (!pj_file_exists(filename)) { + PJ_LOG(4,(THIS_FILE, + "WAV playlist error: file '%s' not found", + filename)); + return PJ_ENOTFOUND; + } } /* Normalize ptime */ if (ptime == 0) - ptime = 20; + ptime = 20; /* Create fport instance. */ fport = create_file_list_port(pool, port_label); if (!fport) { - return PJ_ENOMEM; + return PJ_ENOMEM; } afd = pjmedia_format_get_audio_format_detail(&fport->base.info.fmt, 1); @@ -358,44 +357,44 @@ PJ_DEF(pj_status_t) pjmedia_wav_playlist_create(pj_pool_t *pool, /* Create file descriptor list */ fport->fd_list = (pj_oshandle_t*) - pj_pool_zalloc(pool, sizeof(pj_oshandle_t)*file_count); + pj_pool_zalloc(pool, sizeof(pj_oshandle_t)*file_count); if (!fport->fd_list) { - return PJ_ENOMEM; + return PJ_ENOMEM; } /* Create file size list */ fport->fsize_list = (pj_off_t*) - pj_pool_alloc(pool, sizeof(pj_off_t)*file_count); + pj_pool_alloc(pool, sizeof(pj_off_t)*file_count); if (!fport->fsize_list) { - return PJ_ENOMEM; + return PJ_ENOMEM; } /* Create start of WAVE data list */ fport->start_data_list = (unsigned*) - pj_pool_alloc(pool, sizeof(unsigned)*file_count); + pj_pool_alloc(pool, sizeof(unsigned)*file_count); if (!fport->start_data_list) { - return PJ_ENOMEM; + return PJ_ENOMEM; } /* Create data len list */ fport->data_len_list = (unsigned*) - pj_pool_alloc(pool, sizeof(unsigned)*file_count); + pj_pool_alloc(pool, sizeof(unsigned)*file_count); if (!fport->data_len_list) { - return PJ_ENOMEM; + return PJ_ENOMEM; } /* Create data left list */ fport->data_left_list = (unsigned*) - pj_pool_alloc(pool, sizeof(unsigned)*file_count); + pj_pool_alloc(pool, sizeof(unsigned)*file_count); if (!fport->data_left_list) { - return PJ_ENOMEM; + return PJ_ENOMEM; } /* Create file position list */ fport->fpos_list = (pj_off_t*) - pj_pool_alloc(pool, sizeof(pj_off_t)*file_count); + pj_pool_alloc(pool, sizeof(pj_off_t)*file_count); if (!fport->fpos_list) { - return PJ_ENOMEM; + return PJ_ENOMEM; } /* Create file buffer once for this operation. @@ -407,7 +406,7 @@ PJ_DEF(pj_status_t) pjmedia_wav_playlist_create(pj_pool_t *pool, /* Create buffer. */ fport->buf = (char*) pj_pool_alloc(pool, fport->bufsize); if (!fport->buf) { - return PJ_ENOMEM; + return PJ_ENOMEM; } /* Initialize port */ @@ -418,201 +417,201 @@ PJ_DEF(pj_status_t) pjmedia_wav_playlist_create(pj_pool_t *pool, /* ok run this for all files to be sure all are good for playback. */ for (index=file_count-1; index>=0; index--) { - pjmedia_wave_hdr wavehdr; - pj_ssize_t size_read; - pj_off_t size_to_read; - - /* we end with the last one so we are good to go if still in function*/ - pj_memcpy(filename, file_list[index].ptr, file_list[index].slen); - filename[file_list[index].slen] = '\0'; - - /* Get the file size. */ - fport->current_file = index; - fport->fsize_list[index] = pj_file_size(filename); - - /* Size must be more than WAVE header size */ - if (fport->fsize_list[index] <= sizeof(pjmedia_wave_hdr)) { - status = PJMEDIA_ENOTVALIDWAVE; - goto on_error; - } - - /* Open file. */ - status = pj_file_open( pool, filename, PJ_O_RDONLY, - &fport->fd_list[index]); - if (status != PJ_SUCCESS) - goto on_error; - - /* Read the file header plus fmt header only. */ - size_to_read = size_read = sizeof(wavehdr) - 8; - status = pj_file_read( fport->fd_list[index], &wavehdr, &size_read); - if (status != PJ_SUCCESS) { - goto on_error; - } - - if (size_read != size_to_read) { - status = PJMEDIA_ENOTVALIDWAVE; - goto on_error; - } - - /* Normalize WAVE header fields values from little-endian to host - * byte order. - */ - pjmedia_wave_hdr_file_to_host(&wavehdr); - - /* Validate WAVE file. */ - if (wavehdr.riff_hdr.riff != PJMEDIA_RIFF_TAG || - wavehdr.riff_hdr.wave != PJMEDIA_WAVE_TAG || - wavehdr.fmt_hdr.fmt != PJMEDIA_FMT_TAG) - { - TRACE_((THIS_FILE, - "actual value|expected riff=%x|%x, wave=%x|%x fmt=%x|%x", - wavehdr.riff_hdr.riff, PJMEDIA_RIFF_TAG, - wavehdr.riff_hdr.wave, PJMEDIA_WAVE_TAG, - wavehdr.fmt_hdr.fmt, PJMEDIA_FMT_TAG)); - status = PJMEDIA_ENOTVALIDWAVE; - goto on_error; - } - - /* Must be PCM with 16bits per sample */ - if (wavehdr.fmt_hdr.fmt_tag != 1 || - wavehdr.fmt_hdr.bits_per_sample != 16) - { - status = PJMEDIA_EWAVEUNSUPP; - goto on_error; - } - - /* Block align must be 2*nchannels */ - if (wavehdr.fmt_hdr.block_align != - wavehdr.fmt_hdr.nchan * BYTES_PER_SAMPLE) - { - status = PJMEDIA_EWAVEUNSUPP; - goto on_error; - } - - /* If length of fmt_header is greater than 16, skip the remaining - * fmt header data. - */ - if (wavehdr.fmt_hdr.len > 16) { - PJ_CHECK_OVERFLOW_UINT32_TO_LONG(wavehdr.fmt_hdr.len-16, - status = PJMEDIA_ENOTVALIDWAVE; goto on_error;); - size_to_read = (pj_off_t)wavehdr.fmt_hdr.len - 16; - status = pj_file_setpos(fport->fd_list[index], size_to_read, - PJ_SEEK_CUR); - if (status != PJ_SUCCESS) { - goto on_error; - } - } - - /* Repeat reading the WAVE file until we have 'data' chunk */ - for (;;) { - pjmedia_wave_subchunk subchunk; - size_read = 8; - status = pj_file_read(fport->fd_list[index], &subchunk, - &size_read); - if (status != PJ_SUCCESS || size_read != 8) { - status = PJMEDIA_EWAVETOOSHORT; - goto on_error; - } - - /* Normalize endianness */ - PJMEDIA_WAVE_NORMALIZE_SUBCHUNK(&subchunk); - - /* Break if this is "data" chunk */ - if (subchunk.id == PJMEDIA_DATA_TAG) { - wavehdr.data_hdr.data = PJMEDIA_DATA_TAG; - wavehdr.data_hdr.len = subchunk.len; - break; - } - - /* Otherwise skip the chunk contents */ - PJ_CHECK_OVERFLOW_UINT32_TO_LONG(subchunk.len, - status = PJMEDIA_ENOTVALIDWAVE; goto on_error;); - size_to_read = subchunk.len; - - status = pj_file_setpos(fport->fd_list[index], size_to_read, - PJ_SEEK_CUR); - if (status != PJ_SUCCESS) { - goto on_error; - } - } - - /* Current file position now points to start of data */ - status = pj_file_getpos(fport->fd_list[index], &pos); - fport->start_data_list[index] = (unsigned)pos; - fport->data_len_list[index] = wavehdr.data_hdr.len; - fport->data_left_list[index] = wavehdr.data_hdr.len; - - /* Validate length. */ - if (wavehdr.data_hdr.len > fport->fsize_list[index] - - fport->start_data_list[index]) - { - status = PJMEDIA_EWAVEUNSUPP; - goto on_error; - } - if (wavehdr.data_hdr.len < ptime * wavehdr.fmt_hdr.sample_rate * - wavehdr.fmt_hdr.nchan / 1000) - { - status = PJMEDIA_EWAVETOOSHORT; - goto on_error; - } - - /* It seems like we have a valid WAVE file. */ - - /* Update port info if we don't have one, otherwise check - * that the WAV file has the same attributes as previous files. - */ - if (!has_wave_info) { - afd->channel_count = wavehdr.fmt_hdr.nchan; - afd->clock_rate = wavehdr.fmt_hdr.sample_rate; - afd->bits_per_sample = wavehdr.fmt_hdr.bits_per_sample; - afd->frame_time_usec = ptime * 1000; - afd->avg_bps = afd->max_bps = afd->clock_rate * - afd->channel_count * - afd->bits_per_sample; - - has_wave_info = PJ_TRUE; - - } else { - - /* Check that this file has the same characteristics as the other - * files. - */ - if (wavehdr.fmt_hdr.nchan != afd->channel_count || - wavehdr.fmt_hdr.sample_rate != afd->clock_rate || - wavehdr.fmt_hdr.bits_per_sample != afd->bits_per_sample) - { - /* This file has different characteristics than the other - * files. - */ - PJ_LOG(4,(THIS_FILE, - "WAV playlist error: file '%s' has differrent number" - " of channels, sample rate, or bits per sample", - filename)); - status = PJMEDIA_EWAVEUNSUPP; - goto on_error; - } - - } - - /* If file is shorter than buffer size, adjust buffer size to file - * size. Otherwise EOF callback will be called multiple times when - * file_fill_buffer() is called. - */ - if (wavehdr.data_hdr.len < (unsigned)buff_size) - buff_size = wavehdr.data_hdr.len; - - /* Create file buffer. - */ - fport->bufsize = (pj_uint32_t)buff_size; - - /* Set initial position of the file. */ - fport->fpos_list[index] = fport->start_data_list[index]; + pjmedia_wave_hdr wavehdr; + pj_ssize_t size_read; + pj_off_t size_to_read; + + /* we end with the last one so we are good to go if still in function*/ + pj_memcpy(filename, file_list[index].ptr, file_list[index].slen); + filename[file_list[index].slen] = '\0'; + + /* Get the file size. */ + fport->current_file = index; + fport->fsize_list[index] = pj_file_size(filename); + + /* Size must be more than WAVE header size */ + if (fport->fsize_list[index] <= sizeof(pjmedia_wave_hdr)) { + status = PJMEDIA_ENOTVALIDWAVE; + goto on_error; + } + + /* Open file. */ + status = pj_file_open( pool, filename, PJ_O_RDONLY, + &fport->fd_list[index]); + if (status != PJ_SUCCESS) + goto on_error; + + /* Read the file header plus fmt header only. */ + size_to_read = size_read = sizeof(wavehdr) - 8; + status = pj_file_read( fport->fd_list[index], &wavehdr, &size_read); + if (status != PJ_SUCCESS) { + goto on_error; + } + + if (size_read != size_to_read) { + status = PJMEDIA_ENOTVALIDWAVE; + goto on_error; + } + + /* Normalize WAVE header fields values from little-endian to host + * byte order. + */ + pjmedia_wave_hdr_file_to_host(&wavehdr); + + /* Validate WAVE file. */ + if (wavehdr.riff_hdr.riff != PJMEDIA_RIFF_TAG || + wavehdr.riff_hdr.wave != PJMEDIA_WAVE_TAG || + wavehdr.fmt_hdr.fmt != PJMEDIA_FMT_TAG) + { + TRACE_((THIS_FILE, + "actual value|expected riff=%x|%x, wave=%x|%x fmt=%x|%x", + wavehdr.riff_hdr.riff, PJMEDIA_RIFF_TAG, + wavehdr.riff_hdr.wave, PJMEDIA_WAVE_TAG, + wavehdr.fmt_hdr.fmt, PJMEDIA_FMT_TAG)); + status = PJMEDIA_ENOTVALIDWAVE; + goto on_error; + } + + /* Must be PCM with 16bits per sample */ + if (wavehdr.fmt_hdr.fmt_tag != 1 || + wavehdr.fmt_hdr.bits_per_sample != 16) + { + status = PJMEDIA_EWAVEUNSUPP; + goto on_error; + } + + /* Block align must be 2*nchannels */ + if (wavehdr.fmt_hdr.block_align != + wavehdr.fmt_hdr.nchan * BYTES_PER_SAMPLE) + { + status = PJMEDIA_EWAVEUNSUPP; + goto on_error; + } + + /* If length of fmt_header is greater than 16, skip the remaining + * fmt header data. + */ + if (wavehdr.fmt_hdr.len > 16) { + PJ_CHECK_OVERFLOW_UINT32_TO_LONG(wavehdr.fmt_hdr.len-16, + status = PJMEDIA_ENOTVALIDWAVE; goto on_error;); + size_to_read = (pj_off_t)wavehdr.fmt_hdr.len - 16; + status = pj_file_setpos(fport->fd_list[index], size_to_read, + PJ_SEEK_CUR); + if (status != PJ_SUCCESS) { + goto on_error; + } + } + + /* Repeat reading the WAVE file until we have 'data' chunk */ + for (;;) { + pjmedia_wave_subchunk subchunk; + size_read = 8; + status = pj_file_read(fport->fd_list[index], &subchunk, + &size_read); + if (status != PJ_SUCCESS || size_read != 8) { + status = PJMEDIA_EWAVETOOSHORT; + goto on_error; + } + + /* Normalize endianness */ + PJMEDIA_WAVE_NORMALIZE_SUBCHUNK(&subchunk); + + /* Break if this is "data" chunk */ + if (subchunk.id == PJMEDIA_DATA_TAG) { + wavehdr.data_hdr.data = PJMEDIA_DATA_TAG; + wavehdr.data_hdr.len = subchunk.len; + break; + } + + /* Otherwise skip the chunk contents */ + PJ_CHECK_OVERFLOW_UINT32_TO_LONG(subchunk.len, + status = PJMEDIA_ENOTVALIDWAVE; goto on_error;); + size_to_read = subchunk.len; + + status = pj_file_setpos(fport->fd_list[index], size_to_read, + PJ_SEEK_CUR); + if (status != PJ_SUCCESS) { + goto on_error; + } + } + + /* Current file position now points to start of data */ + status = pj_file_getpos(fport->fd_list[index], &pos); + fport->start_data_list[index] = (unsigned)pos; + fport->data_len_list[index] = wavehdr.data_hdr.len; + fport->data_left_list[index] = wavehdr.data_hdr.len; + + /* Validate length. */ + if (wavehdr.data_hdr.len > fport->fsize_list[index] - + fport->start_data_list[index]) + { + status = PJMEDIA_EWAVEUNSUPP; + goto on_error; + } + if (wavehdr.data_hdr.len < ptime * wavehdr.fmt_hdr.sample_rate * + wavehdr.fmt_hdr.nchan / 1000) + { + status = PJMEDIA_EWAVETOOSHORT; + goto on_error; + } + + /* It seems like we have a valid WAVE file. */ + + /* Update port info if we don't have one, otherwise check + * that the WAV file has the same attributes as previous files. + */ + if (!has_wave_info) { + afd->channel_count = wavehdr.fmt_hdr.nchan; + afd->clock_rate = wavehdr.fmt_hdr.sample_rate; + afd->bits_per_sample = wavehdr.fmt_hdr.bits_per_sample; + afd->frame_time_usec = ptime * 1000; + afd->avg_bps = afd->max_bps = afd->clock_rate * + afd->channel_count * + afd->bits_per_sample; + + has_wave_info = PJ_TRUE; + + } else { + + /* Check that this file has the same characteristics as the other + * files. + */ + if (wavehdr.fmt_hdr.nchan != afd->channel_count || + wavehdr.fmt_hdr.sample_rate != afd->clock_rate || + wavehdr.fmt_hdr.bits_per_sample != afd->bits_per_sample) + { + /* This file has different characteristics than the other + * files. + */ + PJ_LOG(4,(THIS_FILE, + "WAV playlist error: file '%s' has differrent number" + " of channels, sample rate, or bits per sample", + filename)); + status = PJMEDIA_EWAVEUNSUPP; + goto on_error; + } + + } + + /* If file is shorter than buffer size, adjust buffer size to file + * size. Otherwise EOF callback will be called multiple times when + * file_fill_buffer() is called. + */ + if (wavehdr.data_hdr.len < (unsigned)buff_size) + buff_size = wavehdr.data_hdr.len; + + /* Create file buffer. + */ + fport->bufsize = (pj_uint32_t)buff_size; + + /* Set initial position of the file. */ + fport->fpos_list[index] = fport->start_data_list[index]; } /* Fill up the buffer. */ status = file_fill_buffer(fport); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } /* Done. */ @@ -620,19 +619,19 @@ PJ_DEF(pj_status_t) pjmedia_wav_playlist_create(pj_pool_t *pool, *p_port = &fport->base; PJ_LOG(4,(THIS_FILE, - "WAV playlist '%.*s' created: samp.rate=%d, ch=%d, bufsize=%uKB", - (int)port_label->slen, - port_label->ptr, - afd->clock_rate, - afd->channel_count, - fport->bufsize / 1000)); + "WAV playlist '%.*s' created: samp.rate=%d, ch=%d, bufsize=%uKB", + (int)port_label->slen, + port_label->ptr, + afd->clock_rate, + afd->channel_count, + fport->bufsize / 1000)); return PJ_SUCCESS; on_error: for (index=0; indexfd_list[index] != 0) - pj_file_close(fport->fd_list[index]); + if (fport->fd_list[index] != 0) + pj_file_close(fport->fd_list[index]); } return status; @@ -645,9 +644,9 @@ PJ_DEF(pj_status_t) pjmedia_wav_playlist_create(pj_pool_t *pool, * end of the last file. */ PJ_DEF(pj_status_t) pjmedia_wav_playlist_set_eof_cb(pjmedia_port *port, - void *user_data, - pj_status_t (*cb)(pjmedia_port *port, - void *usr_data)) + void *user_data, + pj_status_t (*cb)(pjmedia_port *port, + void *usr_data)) { struct playlist_port *fport; @@ -658,7 +657,7 @@ PJ_DEF(pj_status_t) pjmedia_wav_playlist_set_eof_cb(pjmedia_port *port, PJ_ASSERT_RETURN(port->info.signature == SIGNATURE, PJ_EINVALIDOP); PJ_LOG(1, (THIS_FILE, "pjmedia_wav_playlist_set_eof_cb() is deprecated. " - "Use pjmedia_wav_playlist_set_eof_cb2() instead.")); + "Use pjmedia_wav_playlist_set_eof_cb2() instead.")); fport = (struct playlist_port*) port; @@ -675,9 +674,9 @@ PJ_DEF(pj_status_t) pjmedia_wav_playlist_set_eof_cb(pjmedia_port *port, * end of the last file. */ PJ_DEF(pj_status_t) pjmedia_wav_playlist_set_eof_cb2(pjmedia_port *port, - void *user_data, - void (*cb)(pjmedia_port *port, - void *usr_data)) + void *user_data, + void (*cb)(pjmedia_port *port, + void *usr_data)) { struct playlist_port *fport; @@ -700,7 +699,7 @@ PJ_DEF(pj_status_t) pjmedia_wav_playlist_set_eof_cb2(pjmedia_port *port, * Get frame from file for file_list operation */ static pj_status_t file_list_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct playlist_port *fport = (struct playlist_port*)this_port; pj_size_t frame_size; @@ -719,39 +718,39 @@ static pj_status_t file_list_get_frame(pjmedia_port *this_port, if (fport->readpos + frame_size <= fport->buf + fport->bufsize) { - /* Read contiguous buffer. */ - pj_memcpy(frame->buf, fport->readpos, frame_size); - - /* Fill up the buffer if all has been read. */ - fport->readpos += frame_size; - if (fport->readpos == fport->buf + fport->bufsize) { - fport->readpos = fport->buf; - - status = file_fill_buffer(fport); - if (status != PJ_SUCCESS) { - frame->type = PJMEDIA_FRAME_TYPE_NONE; - frame->size = 0; - return status; - } - } + /* Read contiguous buffer. */ + pj_memcpy(frame->buf, fport->readpos, frame_size); + + /* Fill up the buffer if all has been read. */ + fport->readpos += frame_size; + if (fport->readpos == fport->buf + fport->bufsize) { + fport->readpos = fport->buf; + + status = file_fill_buffer(fport); + if (status != PJ_SUCCESS) { + frame->type = PJMEDIA_FRAME_TYPE_NONE; + frame->size = 0; + return status; + } + } } else { - unsigned endread; - - /* Split read. - * First stage: read until end of buffer. - */ - endread = (unsigned)((fport->buf+fport->bufsize) - fport->readpos); - pj_memcpy(frame->buf, fport->readpos, endread); - - /* Second stage: fill up buffer, and read from the start of buffer. */ - status = file_fill_buffer(fport); - if (status != PJ_SUCCESS) { - pj_bzero(((char*)frame->buf)+endread, frame_size-endread); - return status; - } - - pj_memcpy(((char*)frame->buf)+endread, fport->buf, frame_size-endread); - fport->readpos = fport->buf + (frame_size - endread); + unsigned endread; + + /* Split read. + * First stage: read until end of buffer. + */ + endread = (unsigned)((fport->buf+fport->bufsize) - fport->readpos); + pj_memcpy(frame->buf, fport->readpos, endread); + + /* Second stage: fill up buffer, and read from the start of buffer. */ + status = file_fill_buffer(fport); + if (status != PJ_SUCCESS) { + pj_bzero(((char*)frame->buf)+endread, frame_size-endread); + return status; + } + + pj_memcpy(((char*)frame->buf)+endread, fport->buf, frame_size-endread); + fport->readpos = fport->buf + (frame_size - endread); } return PJ_SUCCESS; @@ -769,12 +768,12 @@ static pj_status_t file_list_on_destroy(pjmedia_port *this_port) pj_assert(this_port->info.signature == SIGNATURE); if (fport->subscribed) { - pjmedia_event_unsubscribe(NULL, &file_on_event, fport, fport); - fport->subscribed = PJ_FALSE; + pjmedia_event_unsubscribe(NULL, &file_on_event, fport, fport); + fport->subscribed = PJ_FALSE; } for (index=0; indexmax_file; index++) - pj_file_close(fport->fd_list[index]); + pj_file_close(fport->fd_list[index]); return PJ_SUCCESS; } diff --git a/pjmedia/src/pjmedia/wav_writer.c b/pjmedia/src/pjmedia/wav_writer.c index aad8ca5892..065a076d9f 100644 --- a/pjmedia/src/pjmedia/wav_writer.c +++ b/pjmedia/src/pjmedia/wav_writer.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,34 +28,34 @@ #include -#define THIS_FILE "wav_writer.c" -#define SIGNATURE PJMEDIA_SIG_PORT_WAV_WRITER +#define THIS_FILE "wav_writer.c" +#define SIGNATURE PJMEDIA_SIG_PORT_WAV_WRITER struct file_port { pjmedia_port base; pjmedia_wave_fmt_tag fmt_tag; - pj_uint16_t bytes_per_sample; + pj_uint16_t bytes_per_sample; - pj_size_t bufsize; - char *buf; - char *writepos; - pj_size_t total; + pj_size_t bufsize; + char *buf; + char *writepos; + pj_size_t total; pj_oshandle_t fd; - pj_size_t cb_size; - pj_status_t (*cb)(pjmedia_port*, void*); - pj_bool_t subscribed; - pj_bool_t cb_called; - void (*cb2)(pjmedia_port*, void*); + pj_size_t cb_size; + pj_status_t (*cb)(pjmedia_port*, void*); + pj_bool_t subscribed; + pj_bool_t cb_called; + void (*cb2)(pjmedia_port*, void*); }; static pj_status_t file_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t file_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t file_on_destroy(pjmedia_port *this_port); @@ -64,14 +63,14 @@ static pj_status_t file_on_destroy(pjmedia_port *this_port); * Create file writer port. */ PJ_DEF(pj_status_t) pjmedia_wav_writer_port_create( pj_pool_t *pool, - const char *filename, - unsigned sampling_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - unsigned flags, - pj_ssize_t buff_size, - pjmedia_port **p_port ) + const char *filename, + unsigned sampling_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + unsigned flags, + pj_ssize_t buff_size, + pjmedia_port **p_port ) { struct file_port *fport; pjmedia_wave_hdr wave_hdr; @@ -94,22 +93,22 @@ PJ_DEF(pj_status_t) pjmedia_wav_writer_port_create( pj_pool_t *pool, /* Initialize port info. */ pj_strdup2(pool, &name, filename); pjmedia_port_info_init(&fport->base.info, &name, SIGNATURE, - sampling_rate, channel_count, bits_per_sample, - samples_per_frame); + sampling_rate, channel_count, bits_per_sample, + samples_per_frame); fport->base.get_frame = &file_get_frame; fport->base.put_frame = &file_put_frame; fport->base.on_destroy = &file_on_destroy; if (flags == PJMEDIA_FILE_WRITE_ALAW) { - fport->fmt_tag = PJMEDIA_WAVE_FMT_TAG_ALAW; - fport->bytes_per_sample = 1; + fport->fmt_tag = PJMEDIA_WAVE_FMT_TAG_ALAW; + fport->bytes_per_sample = 1; } else if (flags == PJMEDIA_FILE_WRITE_ULAW) { - fport->fmt_tag = PJMEDIA_WAVE_FMT_TAG_ULAW; - fport->bytes_per_sample = 1; + fport->fmt_tag = PJMEDIA_WAVE_FMT_TAG_ULAW; + fport->bytes_per_sample = 1; } else { - fport->fmt_tag = PJMEDIA_WAVE_FMT_TAG_PCM; - fport->bytes_per_sample = 2; + fport->fmt_tag = PJMEDIA_WAVE_FMT_TAG_PCM; + fport->bytes_per_sample = 2; } /* Open file in write and read mode. @@ -118,7 +117,7 @@ PJ_DEF(pj_status_t) pjmedia_wav_writer_port_create( pj_pool_t *pool, */ status = pj_file_open(pool, filename, PJ_O_WRONLY, &fport->fd); if (status != PJ_SUCCESS) - return status; + return status; /* Initialize WAVE header */ pj_bzero(&wave_hdr, sizeof(pjmedia_wave_hdr)); @@ -132,14 +131,14 @@ PJ_DEF(pj_status_t) pjmedia_wav_writer_port_create( pj_pool_t *pool, wave_hdr.fmt_hdr.nchan = (pj_int16_t)channel_count; wave_hdr.fmt_hdr.sample_rate = sampling_rate; wave_hdr.fmt_hdr.bytes_per_sec = sampling_rate * channel_count * - fport->bytes_per_sample; + fport->bytes_per_sample; wave_hdr.fmt_hdr.block_align = (pj_uint16_t) - (fport->bytes_per_sample * channel_count); + (fport->bytes_per_sample * channel_count); wave_hdr.fmt_hdr.bits_per_sample = (pj_uint16_t) - (fport->bytes_per_sample * 8); + (fport->bytes_per_sample * 8); wave_hdr.data_hdr.data = PJMEDIA_DATA_TAG; - wave_hdr.data_hdr.len = 0; /* will be filled later */ + wave_hdr.data_hdr.len = 0; /* will be filled later */ /* Convert WAVE header from host byte order to little endian @@ -150,50 +149,50 @@ PJ_DEF(pj_status_t) pjmedia_wav_writer_port_create( pj_pool_t *pool, /* Write WAVE header */ if (fport->fmt_tag != PJMEDIA_WAVE_FMT_TAG_PCM) { - pjmedia_wave_subchunk fact_chunk; - pj_uint32_t tmp = 0; - - fact_chunk.id = PJMEDIA_FACT_TAG; - fact_chunk.len = 4; - - PJMEDIA_WAVE_NORMALIZE_SUBCHUNK(&fact_chunk); - - /* Write WAVE header without DATA chunk header */ - size = sizeof(pjmedia_wave_hdr) - sizeof(wave_hdr.data_hdr); - status = pj_file_write(fport->fd, &wave_hdr, &size); - if (status != PJ_SUCCESS) { - pj_file_close(fport->fd); - return status; - } - - /* Write FACT chunk if it stores compressed data */ - size = sizeof(fact_chunk); - status = pj_file_write(fport->fd, &fact_chunk, &size); - if (status != PJ_SUCCESS) { - pj_file_close(fport->fd); - return status; - } - size = 4; - status = pj_file_write(fport->fd, &tmp, &size); - if (status != PJ_SUCCESS) { - pj_file_close(fport->fd); - return status; - } - - /* Write DATA chunk header */ - size = sizeof(wave_hdr.data_hdr); - status = pj_file_write(fport->fd, &wave_hdr.data_hdr, &size); - if (status != PJ_SUCCESS) { - pj_file_close(fport->fd); - return status; - } + pjmedia_wave_subchunk fact_chunk; + pj_uint32_t tmp = 0; + + fact_chunk.id = PJMEDIA_FACT_TAG; + fact_chunk.len = 4; + + PJMEDIA_WAVE_NORMALIZE_SUBCHUNK(&fact_chunk); + + /* Write WAVE header without DATA chunk header */ + size = sizeof(pjmedia_wave_hdr) - sizeof(wave_hdr.data_hdr); + status = pj_file_write(fport->fd, &wave_hdr, &size); + if (status != PJ_SUCCESS) { + pj_file_close(fport->fd); + return status; + } + + /* Write FACT chunk if it stores compressed data */ + size = sizeof(fact_chunk); + status = pj_file_write(fport->fd, &fact_chunk, &size); + if (status != PJ_SUCCESS) { + pj_file_close(fport->fd); + return status; + } + size = 4; + status = pj_file_write(fport->fd, &tmp, &size); + if (status != PJ_SUCCESS) { + pj_file_close(fport->fd); + return status; + } + + /* Write DATA chunk header */ + size = sizeof(wave_hdr.data_hdr); + status = pj_file_write(fport->fd, &wave_hdr.data_hdr, &size); + if (status != PJ_SUCCESS) { + pj_file_close(fport->fd); + return status; + } } else { - size = sizeof(pjmedia_wave_hdr); - status = pj_file_write(fport->fd, &wave_hdr, &size); - if (status != PJ_SUCCESS) { - pj_file_close(fport->fd); - return status; - } + size = sizeof(pjmedia_wave_hdr); + status = pj_file_write(fport->fd, &wave_hdr, &size); + if (status != PJ_SUCCESS) { + pj_file_close(fport->fd); + return status; + } } /* Set buffer size. */ @@ -207,8 +206,8 @@ PJ_DEF(pj_status_t) pjmedia_wav_writer_port_create( pj_pool_t *pool, /* Allocate buffer and set initial write position */ fport->buf = (char*) pj_pool_alloc(pool, fport->bufsize); if (fport->buf == NULL) { - pj_file_close(fport->fd); - return PJ_ENOMEM; + pj_file_close(fport->fd); + return PJ_ENOMEM; } fport->writepos = fport->buf; @@ -216,11 +215,11 @@ PJ_DEF(pj_status_t) pjmedia_wav_writer_port_create( pj_pool_t *pool, *p_port = &fport->base; PJ_LOG(4,(THIS_FILE, - "File writer '%.*s' created: samp.rate=%d, bufsize=%uKB", - (int)fport->base.info.name.slen, - fport->base.info.name.ptr, - PJMEDIA_PIA_SRATE(&fport->base.info), - fport->bufsize / 1000)); + "File writer '%.*s' created: samp.rate=%d, bufsize=%uKB", + (int)fport->base.info.name.slen, + fport->base.info.name.ptr, + PJMEDIA_PIA_SRATE(&fport->base.info), + fport->bufsize / 1000)); return PJ_SUCCESS; @@ -252,10 +251,10 @@ PJ_DEF(pj_ssize_t) pjmedia_wav_writer_port_get_pos( pjmedia_port *port ) * Register callback. */ PJ_DEF(pj_status_t) pjmedia_wav_writer_port_set_cb( pjmedia_port *port, - pj_size_t pos, - void *user_data, - pj_status_t (*cb)(pjmedia_port *port, - void *usr_data)) + pj_size_t pos, + void *user_data, + pj_status_t (*cb)(pjmedia_port *port, + void *usr_data)) { struct file_port *fport; @@ -266,7 +265,7 @@ PJ_DEF(pj_status_t) pjmedia_wav_writer_port_set_cb( pjmedia_port *port, PJ_ASSERT_RETURN(port->info.signature == SIGNATURE, PJ_EINVALIDOP); PJ_LOG(1, (THIS_FILE, "pjmedia_wav_writer_port_set_cb() is deprecated. " - "Use pjmedia_wav_writer_port_set_cb2() instead.")); + "Use pjmedia_wav_writer_port_set_cb2() instead.")); fport = (struct file_port*) port; @@ -283,10 +282,10 @@ PJ_DEF(pj_status_t) pjmedia_wav_writer_port_set_cb( pjmedia_port *port, * Register callback. */ PJ_DEF(pj_status_t) pjmedia_wav_writer_port_set_cb2(pjmedia_port *port, - pj_size_t pos, - void *user_data, - void (*cb)(pjmedia_port *port, - void *usr_data)) + pj_size_t pos, + void *user_data, + void (*cb)(pjmedia_port *port, + void *usr_data)) { struct file_port *fport; @@ -310,10 +309,10 @@ PJ_DEF(pj_status_t) pjmedia_wav_writer_port_set_cb2(pjmedia_port *port, #if defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN!=0 static void swap_samples(pj_int16_t *samples, unsigned count) { - unsigned i; - for (i=0; itype == PJMEDIA_EVENT_CALLBACK) { - if (fport->cb2) - (*fport->cb2)(&fport->base, fport->base.port_data.pdata); + if (fport->cb2) + (*fport->cb2)(&fport->base, fport->base.port_data.pdata); } return PJ_SUCCESS; @@ -357,45 +356,45 @@ static pj_status_t file_on_event(pjmedia_event *event, * to the file. */ static pj_status_t file_put_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct file_port *fport = (struct file_port *)this_port; pj_size_t frame_size; if (fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_PCM) - frame_size = frame->size; + frame_size = frame->size; else - frame_size = frame->size >> 1; + frame_size = frame->size >> 1; /* Flush buffer if we don't have enough room for the frame. */ if (fport->writepos + frame_size > fport->buf + fport->bufsize) { - pj_status_t status; - status = flush_buffer(fport); - if (status != PJ_SUCCESS) - return status; + pj_status_t status; + status = flush_buffer(fport); + if (status != PJ_SUCCESS) + return status; } /* Check if frame is not too large. */ PJ_ASSERT_RETURN(fport->writepos+frame_size <= fport->buf+fport->bufsize, - PJMEDIA_EFRMFILETOOBIG); + PJMEDIA_EFRMFILETOOBIG); /* Copy frame to buffer. */ if (fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_PCM) { - pj_memcpy(fport->writepos, frame->buf, frame->size); + pj_memcpy(fport->writepos, frame->buf, frame->size); } else { - unsigned i; - pj_int16_t *src = (pj_int16_t*)frame->buf; - pj_uint8_t *dst = (pj_uint8_t*)fport->writepos; - - if (fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ULAW) { - for (i = 0; i < frame_size; ++i) { - *dst++ = pjmedia_linear2ulaw(*src++); - } - } else { - for (i = 0; i < frame_size; ++i) { - *dst++ = pjmedia_linear2alaw(*src++); - } - } + unsigned i; + pj_int16_t *src = (pj_int16_t*)frame->buf; + pj_uint8_t *dst = (pj_uint8_t*)fport->writepos; + + if (fport->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ULAW) { + for (i = 0; i < frame_size; ++i) { + *dst++ = pjmedia_linear2ulaw(*src++); + } + } else { + for (i = 0; i < frame_size; ++i) { + *dst++ = pjmedia_linear2alaw(*src++); + } + } } fport->writepos += frame_size; @@ -403,37 +402,37 @@ static pj_status_t file_put_frame(pjmedia_port *this_port, /* Increment total written, and check if we need to call callback */ fport->total += frame_size; if (fport->total >= fport->cb_size) { - if (fport->cb2) { - if (!fport->subscribed) { - pj_status_t status; - - status = pjmedia_event_subscribe(NULL, &file_on_event, - fport, fport); - fport->subscribed = (status == PJ_SUCCESS)? PJ_TRUE: - PJ_FALSE; - } - - if (fport->subscribed && !fport->cb_called) { - pjmedia_event event; - - /* To prevent the callback from being called more than once. */ - fport->cb_called = PJ_TRUE; - - pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, - NULL, fport); - pjmedia_event_publish(NULL, fport, &event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); - } - } else if (fport->cb) { - pj_status_t (*cb)(pjmedia_port*, void*); - pj_status_t status; - - cb = fport->cb; - fport->cb = NULL; - - status = (*cb)(this_port, this_port->port_data.pdata); - return status; - } + if (fport->cb2) { + if (!fport->subscribed) { + pj_status_t status; + + status = pjmedia_event_subscribe(NULL, &file_on_event, + fport, fport); + fport->subscribed = (status == PJ_SUCCESS)? PJ_TRUE: + PJ_FALSE; + } + + if (fport->subscribed && !fport->cb_called) { + pjmedia_event event; + + /* To prevent the callback from being called more than once. */ + fport->cb_called = PJ_TRUE; + + pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, + NULL, fport); + pjmedia_event_publish(NULL, fport, &event, + PJMEDIA_EVENT_PUBLISH_POST_EVENT); + } + } else if (fport->cb) { + pj_status_t (*cb)(pjmedia_port*, void*); + pj_status_t status; + + cb = fport->cb; + fport->cb = NULL; + + status = (*cb)(this_port, this_port->port_data.pdata); + return status; + } } return PJ_SUCCESS; @@ -443,7 +442,7 @@ static pj_status_t file_put_frame(pjmedia_port *this_port, * Get frame, basicy is a no-op operation. */ static pj_status_t file_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { PJ_UNUSED_ARG(this_port); PJ_UNUSED_ARG(frame); @@ -465,19 +464,19 @@ static pj_status_t file_on_destroy(pjmedia_port *this_port) pj_uint32_t data_len_pos = DATA_LEN_POS; if (fport->subscribed) { - pjmedia_event_unsubscribe(NULL, &file_on_event, fport, fport); - fport->subscribed = PJ_FALSE; + pjmedia_event_unsubscribe(NULL, &file_on_event, fport, fport); + fport->subscribed = PJ_FALSE; } /* Flush remaining buffers. */ if (fport->writepos != fport->buf) - flush_buffer(fport); + flush_buffer(fport); /* Get file size. */ status = pj_file_getpos(fport->fd, &file_size); if (status != PJ_SUCCESS) { pj_file_close(fport->fd); - return status; + return status; } /* Calculate wave fields */ @@ -493,7 +492,7 @@ static pj_status_t file_on_destroy(pjmedia_port *this_port) status = pj_file_setpos(fport->fd, FILE_LEN_POS, PJ_SEEK_SET); if (status != PJ_SUCCESS) { pj_file_close(fport->fd); - return status; + return status; } /* Write file_len */ @@ -501,32 +500,32 @@ static pj_status_t file_on_destroy(pjmedia_port *this_port) status = pj_file_write(fport->fd, &wave_file_len, &bytes); if (status != PJ_SUCCESS) { pj_file_close(fport->fd); - return status; + return status; } /* Write samples_len in FACT chunk */ if (fport->fmt_tag != PJMEDIA_WAVE_FMT_TAG_PCM) { - enum { SAMPLES_LEN_POS = 44}; - pj_uint32_t wav_samples_len; + enum { SAMPLES_LEN_POS = 44}; + pj_uint32_t wav_samples_len; - /* Adjust wave_data_len & data_len_pos since there is FACT chunk */ - wave_data_len -= 12; - data_len_pos += 12; - wav_samples_len = wave_data_len; + /* Adjust wave_data_len & data_len_pos since there is FACT chunk */ + wave_data_len -= 12; + data_len_pos += 12; + wav_samples_len = wave_data_len; - /* Seek to samples_len field. */ - status = pj_file_setpos(fport->fd, SAMPLES_LEN_POS, PJ_SEEK_SET); + /* Seek to samples_len field. */ + status = pj_file_setpos(fport->fd, SAMPLES_LEN_POS, PJ_SEEK_SET); if (status != PJ_SUCCESS) { pj_file_close(fport->fd); - return status; + return status; } - /* Write samples_len */ - bytes = sizeof(wav_samples_len); - status = pj_file_write(fport->fd, &wav_samples_len, &bytes); - if (status != PJ_SUCCESS) { + /* Write samples_len */ + bytes = sizeof(wav_samples_len); + status = pj_file_write(fport->fd, &wav_samples_len, &bytes); + if (status != PJ_SUCCESS) { pj_file_close(fport->fd); - return status; + return status; } } @@ -534,7 +533,7 @@ static pj_status_t file_on_destroy(pjmedia_port *this_port) status = pj_file_setpos(fport->fd, data_len_pos, PJ_SEEK_SET); if (status != PJ_SUCCESS) { pj_file_close(fport->fd); - return status; + return status; } /* Write file_len */ @@ -542,13 +541,13 @@ static pj_status_t file_on_destroy(pjmedia_port *this_port) status = pj_file_write(fport->fd, &wave_data_len, &bytes); if (status != PJ_SUCCESS) { pj_file_close(fport->fd); - return status; + return status; } /* Close file */ status = pj_file_close(fport->fd); if (status != PJ_SUCCESS) - return status; + return status; /* Done. */ return PJ_SUCCESS; diff --git a/pjmedia/src/pjmedia/wave.c b/pjmedia/src/pjmedia/wave.c index 201a75b96f..69bbf2b775 100644 --- a/pjmedia/src/pjmedia/wave.c +++ b/pjmedia/src/pjmedia/wave.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,21 +24,21 @@ static void wave_hdr_swap_bytes( pjmedia_wave_hdr *hdr ) { #if defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN!=0 - hdr->riff_hdr.riff = pj_swap32(hdr->riff_hdr.riff); - hdr->riff_hdr.file_len = pj_swap32(hdr->riff_hdr.file_len); - hdr->riff_hdr.wave = pj_swap32(hdr->riff_hdr.wave); + hdr->riff_hdr.riff = pj_swap32(hdr->riff_hdr.riff); + hdr->riff_hdr.file_len = pj_swap32(hdr->riff_hdr.file_len); + hdr->riff_hdr.wave = pj_swap32(hdr->riff_hdr.wave); - hdr->fmt_hdr.fmt = pj_swap32(hdr->fmt_hdr.fmt); - hdr->fmt_hdr.len = pj_swap32(hdr->fmt_hdr.len); - hdr->fmt_hdr.fmt_tag = pj_swap16(hdr->fmt_hdr.fmt_tag); - hdr->fmt_hdr.nchan = pj_swap16(hdr->fmt_hdr.nchan); - hdr->fmt_hdr.sample_rate = pj_swap32(hdr->fmt_hdr.sample_rate); - hdr->fmt_hdr.bytes_per_sec = pj_swap32(hdr->fmt_hdr.bytes_per_sec); - hdr->fmt_hdr.block_align = pj_swap16(hdr->fmt_hdr.block_align); + hdr->fmt_hdr.fmt = pj_swap32(hdr->fmt_hdr.fmt); + hdr->fmt_hdr.len = pj_swap32(hdr->fmt_hdr.len); + hdr->fmt_hdr.fmt_tag = pj_swap16(hdr->fmt_hdr.fmt_tag); + hdr->fmt_hdr.nchan = pj_swap16(hdr->fmt_hdr.nchan); + hdr->fmt_hdr.sample_rate = pj_swap32(hdr->fmt_hdr.sample_rate); + hdr->fmt_hdr.bytes_per_sec = pj_swap32(hdr->fmt_hdr.bytes_per_sec); + hdr->fmt_hdr.block_align = pj_swap16(hdr->fmt_hdr.block_align); hdr->fmt_hdr.bits_per_sample = pj_swap16(hdr->fmt_hdr.bits_per_sample); - hdr->data_hdr.data = pj_swap32(hdr->data_hdr.data); - hdr->data_hdr.len = pj_swap32(hdr->data_hdr.len); + hdr->data_hdr.data = pj_swap32(hdr->data_hdr.data); + hdr->data_hdr.len = pj_swap32(hdr->data_hdr.len); #else PJ_UNUSED_ARG(hdr); #endif diff --git a/pjmedia/src/pjmedia/wsola.c b/pjmedia/src/pjmedia/wsola.c index 7bcdff8bf1..5a5d397c24 100644 --- a/pjmedia/src/pjmedia/wsola.c +++ b/pjmedia/src/pjmedia/wsola.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,13 +43,13 @@ #if 0 -# define TRACE_(x) PJ_LOG(4,x) +# define TRACE_(x) PJ_LOG(4,x) #else # define TRACE_(x) #endif #if 0 -# define CHECK_(x) pj_assert(x) +# define CHECK_(x) pj_assert(x) #else # define CHECK_(x) #endif @@ -64,30 +63,30 @@ */ /* Buffer size including history, in frames */ -#define FRAME_CNT 6 +#define FRAME_CNT 6 /* Number of history frames in buffer */ -#define HIST_CNT 1.5 +#define HIST_CNT 1.5 /* Template size, in msec */ -#define TEMPLATE_PTIME PJMEDIA_WSOLA_TEMPLATE_LENGTH_MSEC +#define TEMPLATE_PTIME PJMEDIA_WSOLA_TEMPLATE_LENGTH_MSEC /* Hanning window size, in msec */ -#define HANNING_PTIME PJMEDIA_WSOLA_DELAY_MSEC +#define HANNING_PTIME PJMEDIA_WSOLA_DELAY_MSEC /* Number of frames in erase buffer */ -#define ERASE_CNT ((unsigned)3) +#define ERASE_CNT ((unsigned)3) /* Minimum distance from template for find_pitch() of expansion, in frames */ -#define EXP_MIN_DIST 0.5 +#define EXP_MIN_DIST 0.5 /* Maximum distance from template for find_pitch() of expansion, in frames */ -#define EXP_MAX_DIST HIST_CNT +#define EXP_MAX_DIST HIST_CNT /* Duration of a continuous synthetic frames after which the volume * of the synthetic frame will be set to zero with fading-out effect. */ -#define MAX_EXPAND_MSEC PJMEDIA_WSOLA_MAX_EXPAND_MSEC +#define MAX_EXPAND_MSEC PJMEDIA_WSOLA_MAX_EXPAND_MSEC /* Buffer content: @@ -121,37 +120,37 @@ /* WSOLA structure */ struct pjmedia_wsola { - unsigned clock_rate; /* Sampling rate. */ - pj_uint16_t samples_per_frame; /* Samples per frame (const) */ - pj_uint16_t channel_count; /* Channel countt (const) */ - pj_uint16_t options; /* Options. */ - - pjmedia_circ_buf *buf; /* The buffer. */ - pj_int16_t *erase_buf; /* Temporary erase buffer. */ - pj_int16_t *merge_buf; /* Temporary merge buffer. */ - - pj_uint16_t buf_size; /* Total buffer size (const) */ - pj_uint16_t hanning_size; /* Hanning window size (const) */ - pj_uint16_t templ_size; /* Template size (const) */ - pj_uint16_t hist_size; /* History size (const) */ - - pj_uint16_t min_extra; /* Minimum extra (const) */ - unsigned max_expand_cnt; /* Max # of synthetic samples */ - unsigned fade_out_pos; /* Last fade-out position */ - pj_uint16_t expand_sr_min_dist;/* Minimum distance from template - for find_pitch() on expansion - (const) */ - pj_uint16_t expand_sr_max_dist;/* Maximum distance from template - for find_pitch() on expansion - (const) */ + unsigned clock_rate; /* Sampling rate. */ + pj_uint16_t samples_per_frame; /* Samples per frame (const) */ + pj_uint16_t channel_count; /* Channel countt (const) */ + pj_uint16_t options; /* Options. */ + + pjmedia_circ_buf *buf; /* The buffer. */ + pj_int16_t *erase_buf; /* Temporary erase buffer. */ + pj_int16_t *merge_buf; /* Temporary merge buffer. */ + + pj_uint16_t buf_size; /* Total buffer size (const) */ + pj_uint16_t hanning_size; /* Hanning window size (const) */ + pj_uint16_t templ_size; /* Template size (const) */ + pj_uint16_t hist_size; /* History size (const) */ + + pj_uint16_t min_extra; /* Minimum extra (const) */ + unsigned max_expand_cnt; /* Max # of synthetic samples */ + unsigned fade_out_pos; /* Last fade-out position */ + pj_uint16_t expand_sr_min_dist;/* Minimum distance from template + for find_pitch() on expansion + (const) */ + pj_uint16_t expand_sr_max_dist;/* Maximum distance from template + for find_pitch() on expansion + (const) */ #if defined(PJ_HAS_FLOATING_POINT) && PJ_HAS_FLOATING_POINT!=0 - float *hanning; /* Hanning window. */ + float *hanning; /* Hanning window. */ #else - pj_uint16_t *hanning; /* Hanning window. */ + pj_uint16_t *hanning; /* Hanning window. */ #endif - pj_timestamp ts; /* Running timestamp. */ + pj_timestamp ts; /* Running timestamp. */ }; @@ -166,7 +165,7 @@ struct pjmedia_wsola * diff level = (template[1]+..+template[n]) - (target[1]+..+target[n]) */ static pj_int16_t *find_pitch(pj_int16_t *frm, pj_int16_t *beg, pj_int16_t *end, - unsigned template_cnt, int first) + unsigned template_cnt, int first) { pj_int16_t *sr, *best=beg; int best_corr = 0x7FFFFFFF; @@ -174,41 +173,41 @@ static pj_int16_t *find_pitch(pj_int16_t *frm, pj_int16_t *beg, pj_int16_t *end, unsigned i; for (i = 0; i 0? corr : -corr; - - if (first) { - if (abs_corr < best_corr) { - best_corr = abs_corr; - best = sr; - } - } else { - if (abs_corr <= best_corr) { - best_corr = abs_corr; - best = sr; - } - } + int corr = frm_sum; + int abs_corr = 0; + + /* Do calculation on 8 samples at once */ + for (i = 0; i 0? corr : -corr; + + if (first) { + if (abs_corr < best_corr) { + best_corr = abs_corr; + best = sr; + } + } else { + if (abs_corr <= best_corr) { + best_corr = abs_corr; + best = sr; + } + } } /*TRACE_((THIS_FILE, "found pitch at %u", best-beg));*/ @@ -225,43 +224,43 @@ static pj_int16_t *find_pitch(pj_int16_t *frm, pj_int16_t *beg, pj_int16_t *end, #if (PJMEDIA_WSOLA_IMP==PJMEDIA_WSOLA_IMP_WSOLA) static pj_int16_t *find_pitch(pj_int16_t *frm, pj_int16_t *beg, pj_int16_t *end, - unsigned template_cnt, int first) + unsigned template_cnt, int first) { pj_int16_t *sr, *best=beg; double best_corr = 0; for (sr=beg; sr!=end; ++sr) { - double corr = 0; - unsigned i; - - /* Do calculation on 8 samples at once */ - for (i=0; i best_corr) { - best_corr = corr; - best = sr; - } - } else { - if (corr >= best_corr) { - best_corr = corr; - best = sr; - } - } + double corr = 0; + unsigned i; + + /* Do calculation on 8 samples at once */ + for (i=0; i best_corr) { + best_corr = corr; + best = sr; + } + } else { + if (corr >= best_corr) { + best_corr = corr; + best = sr; + } + } } /*TRACE_((THIS_FILE, "found pitch at %u", best-beg));*/ @@ -271,25 +270,25 @@ static pj_int16_t *find_pitch(pj_int16_t *frm, pj_int16_t *beg, pj_int16_t *end, #endif static void overlapp_add(pj_int16_t dst[], unsigned count, - pj_int16_t l[], pj_int16_t r[], - float w[]) + pj_int16_t l[], pj_int16_t r[], + float w[]) { unsigned i; for (i=0; i best_corr) { - best_corr = corr; - best = sr; - } - } else { - if (corr >= best_corr) { - best_corr = corr; - best = sr; - } - } + pj_int64_t corr = 0; + unsigned i; + + /* Do calculation on 8 samples at once */ + for (i=0; i best_corr) { + best_corr = corr; + best = sr; + } + } else { + if (corr >= best_corr) { + best_corr = corr; + best = sr; + } + } } /*TRACE_((THIS_FILE, "found pitch at %u", best-beg));*/ @@ -363,27 +362,27 @@ static pj_int16_t *find_pitch(pj_int16_t *frm, pj_int16_t *beg, pj_int16_t *end, static void overlapp_add(pj_int16_t dst[], unsigned count, - pj_int16_t l[], pj_int16_t r[], - pj_uint16_t w[]) + pj_int16_t l[], pj_int16_t r[], + pj_uint16_t w[]) { unsigned i; for (i=0; i> WINDOW_BITS); + dst[i] = (pj_int16_t)(((int)(l[i]) * (int)(w[count-1-i]) + + (int)(r[i]) * (int)(w[i])) >> WINDOW_BITS); } } static void overlapp_add_simple(pj_int16_t dst[], unsigned count, - pj_int16_t l[], pj_int16_t r[]) + pj_int16_t l[], pj_int16_t r[]) { int step = ((WINDOW_MAX_VAL+1) / count), - stepdown = WINDOW_MAX_VAL; + stepdown = WINDOW_MAX_VAL; unsigned i; for (i=0; i> WINDOW_BITS); - stepdown -= step; + dst[i]=(pj_int16_t)((l[i] * stepdown + r[i] * (1-stepdown)) >> WINDOW_BITS); + stepdown -= step; } } @@ -396,7 +395,7 @@ static pj_uint32_t approx_cos( pj_uint32_t x ) pj_uint32_t i,j,k; if( x == 0 ) - return 0xFFFFFFFF; + return 0xFFFFFFFF; i = x << 1; k = ((x + 0xBFFFFFFD) & 0x80000000) >> 30; @@ -407,47 +406,47 @@ static pj_uint32_t approx_cos( pj_uint32_t x ) return j; } -#endif /* PJ_HAS_INT64 && .. */ +#endif /* PJ_HAS_INT64 && .. */ static void create_win(pj_pool_t *pool, pj_uint16_t **pw, unsigned count) { unsigned i; pj_uint16_t *w = (pj_uint16_t*)pj_pool_calloc(pool, count, - sizeof(pj_uint16_t)); + sizeof(pj_uint16_t)); *pw = w; for (i=0; imax_expand_cnt; @@ -481,35 +480,35 @@ static void wsola_fade_out(pjmedia_wsola *wsola, #endif if (wsola->fade_out_pos == 0) { - pjmedia_zero_samples(buf, count); + pjmedia_zero_samples(buf, count); } else if (fade_pos < count) { - for (; fade_pos; --fade_pos, ++buf) { - *buf = (pj_int16_t)(*buf * fade_pos / fade_cnt); - } - if (buf != end) - pjmedia_zero_samples(buf, (unsigned)(end - buf)); - wsola->fade_out_pos = 0; + for (; fade_pos; --fade_pos, ++buf) { + *buf = (pj_int16_t)(*buf * fade_pos / fade_cnt); + } + if (buf != end) + pjmedia_zero_samples(buf, (unsigned)(end - buf)); + wsola->fade_out_pos = 0; } else { - for (; buf != end; --fade_pos, ++buf) { - *buf = (pj_int16_t)(*buf * fade_pos / fade_cnt); - } - wsola->fade_out_pos -= count; + for (; buf != end; --fade_pos, ++buf) { + *buf = (pj_int16_t)(*buf * fade_pos / fade_cnt); + } + wsola->fade_out_pos -= count; } } PJ_DEF(pj_status_t) pjmedia_wsola_create( pj_pool_t *pool, - unsigned clock_rate, - unsigned samples_per_frame, - unsigned channel_count, - unsigned options, - pjmedia_wsola **p_wsola) + unsigned clock_rate, + unsigned samples_per_frame, + unsigned channel_count, + unsigned options, + pjmedia_wsola **p_wsola) { pjmedia_wsola *wsola; pj_status_t status; PJ_ASSERT_RETURN(pool && clock_rate && samples_per_frame && p_wsola, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(clock_rate <= 65535, PJ_EINVAL); PJ_ASSERT_RETURN(samples_per_frame < clock_rate, PJ_EINVAL); PJ_ASSERT_RETURN(channel_count > 0, PJ_EINVAL); @@ -527,8 +526,8 @@ PJ_DEF(pj_status_t) pjmedia_wsola_create( pj_pool_t *pool, wsola->buf_size = (pj_uint16_t) (samples_per_frame * FRAME_CNT); status = pjmedia_circ_buf_create(pool, wsola->buf_size, &wsola->buf); if (status != PJ_SUCCESS) { - PJ_PERROR(3, (THIS_FILE, status, "Failed to create circular buf")); - return status; + PJ_PERROR(3, (THIS_FILE, status, "Failed to create circular buf")); + return status; } /* Calculate history size */ @@ -536,42 +535,42 @@ PJ_DEF(pj_status_t) pjmedia_wsola_create( pj_pool_t *pool, /* Calculate template size */ wsola->templ_size = (pj_uint16_t)(TEMPLATE_PTIME * clock_rate * - channel_count / 1000); + channel_count / 1000); if (wsola->templ_size > samples_per_frame) - wsola->templ_size = wsola->samples_per_frame; + wsola->templ_size = wsola->samples_per_frame; /* Calculate hanning window size */ wsola->hanning_size = (pj_uint16_t)(HANNING_PTIME * clock_rate * - channel_count / 1000); + channel_count / 1000); if (wsola->hanning_size > wsola->samples_per_frame) - wsola->hanning_size = wsola->samples_per_frame; + wsola->hanning_size = wsola->samples_per_frame; pj_assert(wsola->templ_size <= wsola->hanning_size); /* Create merge buffer */ wsola->merge_buf = (pj_int16_t*) pj_pool_calloc(pool, - wsola->hanning_size, - sizeof(pj_int16_t)); + wsola->hanning_size, + sizeof(pj_int16_t)); /* Setup with PLC */ if ((options & PJMEDIA_WSOLA_NO_PLC) == 0) { - wsola->min_extra = wsola->hanning_size; - wsola->expand_sr_min_dist = (pj_uint16_t) - (EXP_MIN_DIST * wsola->samples_per_frame); - wsola->expand_sr_max_dist = (pj_uint16_t) - (EXP_MAX_DIST * wsola->samples_per_frame); + wsola->min_extra = wsola->hanning_size; + wsola->expand_sr_min_dist = (pj_uint16_t) + (EXP_MIN_DIST * wsola->samples_per_frame); + wsola->expand_sr_max_dist = (pj_uint16_t) + (EXP_MAX_DIST * wsola->samples_per_frame); } /* Setup with hanning */ if ((options & PJMEDIA_WSOLA_NO_HANNING) == 0) { - create_win(pool, &wsola->hanning, wsola->hanning_size); + create_win(pool, &wsola->hanning, wsola->hanning_size); } /* Setup with discard */ if ((options & PJMEDIA_WSOLA_NO_DISCARD) == 0) { - wsola->erase_buf = (pj_int16_t*)pj_pool_calloc(pool, samples_per_frame * - ERASE_CNT, - sizeof(pj_int16_t)); + wsola->erase_buf = (pj_int16_t*)pj_pool_calloc(pool, samples_per_frame * + ERASE_CNT, + sizeof(pj_int16_t)); } /* Generate dummy extra */ @@ -591,7 +590,7 @@ PJ_DEF(pj_status_t) pjmedia_wsola_destroy(pjmedia_wsola *wsola) } PJ_DEF(pj_status_t) pjmedia_wsola_set_max_expand(pjmedia_wsola *wsola, - unsigned msec) + unsigned msec) { PJ_ASSERT_RETURN(wsola, PJ_EINVAL); wsola->max_expand_cnt = msec * wsola->clock_rate / 1000; @@ -599,7 +598,7 @@ PJ_DEF(pj_status_t) pjmedia_wsola_set_max_expand(pjmedia_wsola *wsola, } PJ_DEF(pj_status_t) pjmedia_wsola_reset( pjmedia_wsola *wsola, - unsigned options) + unsigned options) { PJ_ASSERT_RETURN(wsola && options==0, PJ_EINVAL); PJ_UNUSED_ARG(options); @@ -623,123 +622,123 @@ static void expand(pjmedia_wsola *wsola, unsigned needed) pjmedia_circ_buf_pack_buffer(wsola->buf); pjmedia_circ_buf_get_read_regions(wsola->buf, ®1, ®1_len, - ®2, ®2_len); + ®2, ®2_len); CHECK_(reg2_len == 0); for (rep=1;; ++rep) { - pj_int16_t *start, *templ; - unsigned dist; - - templ = reg1 + reg1_len - wsola->hanning_size; - CHECK_(templ - reg1 >= wsola->hist_size); - - start = find_pitch(templ, - templ - wsola->expand_sr_max_dist, - templ - wsola->expand_sr_min_dist, - wsola->templ_size, - 1); - - /* Should we make sure that "start" is really aligned to - * channel #0, in case of stereo? Probably not necessary, as - * find_pitch() should have found the best match anyway. - */ - - if (wsola->options & PJMEDIA_WSOLA_NO_HANNING) { - overlapp_add_simple(wsola->merge_buf, wsola->hanning_size, - templ, start); - } else { - /* Check if pointers are in the valid range */ - CHECK_(templ >= wsola->buf->buf && - templ + wsola->hanning_size <= - wsola->buf->buf + wsola->buf->capacity); - CHECK_(start >= wsola->buf->buf && - start + wsola->hanning_size <= - wsola->buf->buf + wsola->buf->capacity); - - overlapp_add(wsola->merge_buf, wsola->hanning_size, templ, - start, wsola->hanning); - } - - /* How many new samples do we have */ - dist = (unsigned)(templ - start); - - /* Not enough buffer to hold the result */ - if (reg1_len + dist > wsola->buf_size) { - pj_assert(!"WSOLA buffer size may be to small!"); - break; - } - - /* Copy the "tail" (excess frame) to the end */ - pjmedia_move_samples(templ + wsola->hanning_size, - start + wsola->hanning_size, - dist); - - /* Copy the merged frame */ - pjmedia_copy_samples(templ, wsola->merge_buf, wsola->hanning_size); - - /* We have new samples */ - reg1_len += dist; - pjmedia_circ_buf_set_len(wsola->buf, reg1_len); - - generated += dist; - - if (generated >= needed) { - TRACE_((THIS_FILE, "WSOLA frame expanded after %d iterations", - rep)); - break; - } + pj_int16_t *start, *templ; + unsigned dist; + + templ = reg1 + reg1_len - wsola->hanning_size; + CHECK_(templ - reg1 >= wsola->hist_size); + + start = find_pitch(templ, + templ - wsola->expand_sr_max_dist, + templ - wsola->expand_sr_min_dist, + wsola->templ_size, + 1); + + /* Should we make sure that "start" is really aligned to + * channel #0, in case of stereo? Probably not necessary, as + * find_pitch() should have found the best match anyway. + */ + + if (wsola->options & PJMEDIA_WSOLA_NO_HANNING) { + overlapp_add_simple(wsola->merge_buf, wsola->hanning_size, + templ, start); + } else { + /* Check if pointers are in the valid range */ + CHECK_(templ >= wsola->buf->buf && + templ + wsola->hanning_size <= + wsola->buf->buf + wsola->buf->capacity); + CHECK_(start >= wsola->buf->buf && + start + wsola->hanning_size <= + wsola->buf->buf + wsola->buf->capacity); + + overlapp_add(wsola->merge_buf, wsola->hanning_size, templ, + start, wsola->hanning); + } + + /* How many new samples do we have */ + dist = (unsigned)(templ - start); + + /* Not enough buffer to hold the result */ + if (reg1_len + dist > wsola->buf_size) { + pj_assert(!"WSOLA buffer size may be to small!"); + break; + } + + /* Copy the "tail" (excess frame) to the end */ + pjmedia_move_samples(templ + wsola->hanning_size, + start + wsola->hanning_size, + dist); + + /* Copy the merged frame */ + pjmedia_copy_samples(templ, wsola->merge_buf, wsola->hanning_size); + + /* We have new samples */ + reg1_len += dist; + pjmedia_circ_buf_set_len(wsola->buf, reg1_len); + + generated += dist; + + if (generated >= needed) { + TRACE_((THIS_FILE, "WSOLA frame expanded after %d iterations", + rep)); + break; + } } } static unsigned compress(pjmedia_wsola *wsola, pj_int16_t *buf, unsigned count, - unsigned del_cnt) + unsigned del_cnt) { unsigned samples_del = 0, rep; for (rep=1; ; ++rep) { - pj_int16_t *start, *end; - unsigned dist; - - if (count <= wsola->hanning_size + del_cnt) { - TRACE_((THIS_FILE, "Not enough samples to compress!")); - return samples_del; - } - - // Make start distance to del_cnt, so discard will be performed in - // only one iteration. - //start = buf + (frmsz >> 1); - start = buf + del_cnt - samples_del; - end = start + wsola->samples_per_frame; - - if (end + wsola->hanning_size > buf + count) { - end = buf+count-wsola->hanning_size; - } - - CHECK_(start < end); - - start = find_pitch(buf, start, end, wsola->templ_size, 0); - dist = (unsigned)(start - buf); - - if (wsola->options & PJMEDIA_WSOLA_NO_HANNING) { - overlapp_add_simple(buf, wsola->hanning_size, buf, start); - } else { - overlapp_add(buf, wsola->hanning_size, buf, start, wsola->hanning); - } - - pjmedia_move_samples(buf + wsola->hanning_size, - buf + wsola->hanning_size + dist, - count - wsola->hanning_size - dist); - - count -= dist; - samples_del += dist; - - if (samples_del >= del_cnt) { - TRACE_((THIS_FILE, - "Erased %d of %d requested after %d iteration(s)", - samples_del, del_cnt, rep)); - break; - } + pj_int16_t *start, *end; + unsigned dist; + + if (count <= wsola->hanning_size + del_cnt) { + TRACE_((THIS_FILE, "Not enough samples to compress!")); + return samples_del; + } + + // Make start distance to del_cnt, so discard will be performed in + // only one iteration. + //start = buf + (frmsz >> 1); + start = buf + del_cnt - samples_del; + end = start + wsola->samples_per_frame; + + if (end + wsola->hanning_size > buf + count) { + end = buf+count-wsola->hanning_size; + } + + CHECK_(start < end); + + start = find_pitch(buf, start, end, wsola->templ_size, 0); + dist = (unsigned)(start - buf); + + if (wsola->options & PJMEDIA_WSOLA_NO_HANNING) { + overlapp_add_simple(buf, wsola->hanning_size, buf, start); + } else { + overlapp_add(buf, wsola->hanning_size, buf, start, wsola->hanning); + } + + pjmedia_move_samples(buf + wsola->hanning_size, + buf + wsola->hanning_size + dist, + count - wsola->hanning_size - dist); + + count -= dist; + samples_del += dist; + + if (samples_del >= del_cnt) { + TRACE_((THIS_FILE, + "Erased %d of %d requested after %d iteration(s)", + samples_del, del_cnt, rep)); + break; + } } return samples_del; @@ -748,8 +747,8 @@ static unsigned compress(pjmedia_wsola *wsola, pj_int16_t *buf, unsigned count, PJ_DEF(pj_status_t) pjmedia_wsola_save( pjmedia_wsola *wsola, - pj_int16_t frm[], - pj_bool_t prev_lost) + pj_int16_t frm[], + pj_bool_t prev_lost) { unsigned buf_len; pj_status_t status; @@ -761,114 +760,114 @@ PJ_DEF(pj_status_t) pjmedia_wsola_save( pjmedia_wsola *wsola, /* If previous frame was lost, smoothen this frame with the generated one */ if (prev_lost) { - pj_int16_t *reg1, *reg2; - unsigned reg1_len, reg2_len; - pj_int16_t *ola_left; - - /* Trim excessive len */ - if ((int)buf_len > wsola->hist_size + (wsola->min_extra<<1)) { - buf_len = wsola->hist_size + (wsola->min_extra<<1); - pjmedia_circ_buf_set_len(wsola->buf, buf_len); - } - - pjmedia_circ_buf_get_read_regions(wsola->buf, ®1, ®1_len, - ®2, ®2_len); - - CHECK_(pjmedia_circ_buf_get_len(wsola->buf) >= - (unsigned)(wsola->hist_size + (wsola->min_extra<<1))); - - /* Continue applying fade out to the extra samples */ - if ((wsola->options & PJMEDIA_WSOLA_NO_FADING)==0) { - if (reg2_len == 0) { - wsola_fade_out(wsola, reg1 + reg1_len - (wsola->min_extra<<1), - (wsola->min_extra<<1)); - } else if ((int)reg2_len >= (wsola->min_extra<<1)) { - wsola_fade_out(wsola, reg2 + reg2_len - (wsola->min_extra<<1), - (wsola->min_extra<<1)); - } else { - unsigned tmp = (wsola->min_extra<<1) - reg2_len; - wsola_fade_out(wsola, reg1 + reg1_len - tmp, tmp); - wsola_fade_out(wsola, reg2, reg2_len); - } - } - - /* Get the region in buffer to be merged with the frame */ - if (reg2_len == 0) { - ola_left = reg1 + reg1_len - wsola->min_extra; - } else if (reg2_len >= wsola->min_extra) { - ola_left = reg2 + reg2_len - wsola->min_extra; - } else { - unsigned tmp; - - tmp = wsola->min_extra - reg2_len; - pjmedia_copy_samples(wsola->merge_buf, reg1 + reg1_len - tmp, tmp); - pjmedia_copy_samples(wsola->merge_buf + tmp, reg2, reg2_len); - ola_left = wsola->merge_buf; - } - - /* Apply fade-in to the frame before merging */ - if ((wsola->options & PJMEDIA_WSOLA_NO_FADING)==0) { - unsigned count = wsola->min_extra; - int fade_in_pos; - - /* Scale fade_in position based on last fade-out */ - fade_in_pos = wsola->fade_out_pos * count / - wsola->max_expand_cnt; - - /* Fade-in it */ - fade_in(frm, wsola->samples_per_frame, - fade_in_pos, count); - } - - /* Merge it */ - overlapp_add_simple(frm, wsola->min_extra, ola_left, frm); - - /* Trim len */ - buf_len -= wsola->min_extra; - pjmedia_circ_buf_set_len(wsola->buf, buf_len); + pj_int16_t *reg1, *reg2; + unsigned reg1_len, reg2_len; + pj_int16_t *ola_left; + + /* Trim excessive len */ + if ((int)buf_len > wsola->hist_size + (wsola->min_extra<<1)) { + buf_len = wsola->hist_size + (wsola->min_extra<<1); + pjmedia_circ_buf_set_len(wsola->buf, buf_len); + } + + pjmedia_circ_buf_get_read_regions(wsola->buf, ®1, ®1_len, + ®2, ®2_len); + + CHECK_(pjmedia_circ_buf_get_len(wsola->buf) >= + (unsigned)(wsola->hist_size + (wsola->min_extra<<1))); + + /* Continue applying fade out to the extra samples */ + if ((wsola->options & PJMEDIA_WSOLA_NO_FADING)==0) { + if (reg2_len == 0) { + wsola_fade_out(wsola, reg1 + reg1_len - (wsola->min_extra<<1), + (wsola->min_extra<<1)); + } else if ((int)reg2_len >= (wsola->min_extra<<1)) { + wsola_fade_out(wsola, reg2 + reg2_len - (wsola->min_extra<<1), + (wsola->min_extra<<1)); + } else { + unsigned tmp = (wsola->min_extra<<1) - reg2_len; + wsola_fade_out(wsola, reg1 + reg1_len - tmp, tmp); + wsola_fade_out(wsola, reg2, reg2_len); + } + } + + /* Get the region in buffer to be merged with the frame */ + if (reg2_len == 0) { + ola_left = reg1 + reg1_len - wsola->min_extra; + } else if (reg2_len >= wsola->min_extra) { + ola_left = reg2 + reg2_len - wsola->min_extra; + } else { + unsigned tmp; + + tmp = wsola->min_extra - reg2_len; + pjmedia_copy_samples(wsola->merge_buf, reg1 + reg1_len - tmp, tmp); + pjmedia_copy_samples(wsola->merge_buf + tmp, reg2, reg2_len); + ola_left = wsola->merge_buf; + } + + /* Apply fade-in to the frame before merging */ + if ((wsola->options & PJMEDIA_WSOLA_NO_FADING)==0) { + unsigned count = wsola->min_extra; + int fade_in_pos; + + /* Scale fade_in position based on last fade-out */ + fade_in_pos = wsola->fade_out_pos * count / + wsola->max_expand_cnt; + + /* Fade-in it */ + fade_in(frm, wsola->samples_per_frame, + fade_in_pos, count); + } + + /* Merge it */ + overlapp_add_simple(frm, wsola->min_extra, ola_left, frm); + + /* Trim len */ + buf_len -= wsola->min_extra; + pjmedia_circ_buf_set_len(wsola->buf, buf_len); } else if ((wsola->options & PJMEDIA_WSOLA_NO_FADING)==0 && - wsola->fade_out_pos != wsola->max_expand_cnt) + wsola->fade_out_pos != wsola->max_expand_cnt) { - unsigned count = wsola->min_extra; - int fade_in_pos; - - /* Fade out the remaining synthetic samples */ - if (buf_len > wsola->hist_size) { - pj_int16_t *reg1, *reg2; - unsigned reg1_len, reg2_len; - - /* Number of samples to fade out */ - count = buf_len - wsola->hist_size; - - pjmedia_circ_buf_get_read_regions(wsola->buf, ®1, ®1_len, - ®2, ®2_len); - - CHECK_(pjmedia_circ_buf_get_len(wsola->buf) >= - (unsigned)(wsola->hist_size + (wsola->min_extra<<1))); - - /* Continue applying fade out to the extra samples */ - if (reg2_len == 0) { - wsola_fade_out(wsola, reg1 + reg1_len - count, count); - } else if (reg2_len >= count) { - wsola_fade_out(wsola, reg2 + reg2_len - count, count); - } else { - unsigned tmp = count - reg2_len; - wsola_fade_out(wsola, reg1 + reg1_len - tmp, tmp); - wsola_fade_out(wsola, reg2, reg2_len); - } - } - - /* Apply fade-in to the frame */ - count = wsola->min_extra; - - /* Scale fade_in position based on last fade-out */ - fade_in_pos = wsola->fade_out_pos * count / - wsola->max_expand_cnt; - - /* Fade it in */ - fade_in(frm, wsola->samples_per_frame, - fade_in_pos, count); + unsigned count = wsola->min_extra; + int fade_in_pos; + + /* Fade out the remaining synthetic samples */ + if (buf_len > wsola->hist_size) { + pj_int16_t *reg1, *reg2; + unsigned reg1_len, reg2_len; + + /* Number of samples to fade out */ + count = buf_len - wsola->hist_size; + + pjmedia_circ_buf_get_read_regions(wsola->buf, ®1, ®1_len, + ®2, ®2_len); + + CHECK_(pjmedia_circ_buf_get_len(wsola->buf) >= + (unsigned)(wsola->hist_size + (wsola->min_extra<<1))); + + /* Continue applying fade out to the extra samples */ + if (reg2_len == 0) { + wsola_fade_out(wsola, reg1 + reg1_len - count, count); + } else if (reg2_len >= count) { + wsola_fade_out(wsola, reg2 + reg2_len - count, count); + } else { + unsigned tmp = count - reg2_len; + wsola_fade_out(wsola, reg1 + reg1_len - tmp, tmp); + wsola_fade_out(wsola, reg2, reg2_len); + } + } + + /* Apply fade-in to the frame */ + count = wsola->min_extra; + + /* Scale fade_in position based on last fade-out */ + fade_in_pos = wsola->fade_out_pos * count / + wsola->max_expand_cnt; + + /* Fade it in */ + fade_in(frm, wsola->samples_per_frame, + fade_in_pos, count); } @@ -876,15 +875,15 @@ PJ_DEF(pj_status_t) pjmedia_wsola_save( pjmedia_wsola *wsola, status = pjmedia_circ_buf_write(wsola->buf, frm, wsola->samples_per_frame); if (status != PJ_SUCCESS) { - TRACE_((THIS_FILE, "Failed writing to circbuf [err=%d]", status)); - return status; + TRACE_((THIS_FILE, "Failed writing to circbuf [err=%d]", status)); + return status; } status = pjmedia_circ_buf_copy(wsola->buf, wsola->hist_size, frm, - wsola->samples_per_frame); + wsola->samples_per_frame); if (status != PJ_SUCCESS) { - TRACE_((THIS_FILE, "Failed copying from circbuf [err=%d]", status)); - return status; + TRACE_((THIS_FILE, "Failed copying from circbuf [err=%d]", status)); + return status; } return pjmedia_circ_buf_adv_read_ptr(wsola->buf, wsola->samples_per_frame); @@ -892,13 +891,13 @@ PJ_DEF(pj_status_t) pjmedia_wsola_save( pjmedia_wsola *wsola, PJ_DEF(pj_status_t) pjmedia_wsola_generate( pjmedia_wsola *wsola, - pj_int16_t frm[]) + pj_int16_t frm[]) { unsigned samples_len, samples_req; pj_status_t status = PJ_SUCCESS; CHECK_(pjmedia_circ_buf_get_len(wsola->buf) >= wsola->hist_size + - wsola->min_extra); + wsola->min_extra); /* Calculate how many samples in the buffer */ samples_len = pjmedia_circ_buf_get_len(wsola->buf) - wsola->hist_size; @@ -909,24 +908,24 @@ PJ_DEF(pj_status_t) pjmedia_wsola_generate( pjmedia_wsola *wsola, wsola->ts.u64 += wsola->samples_per_frame; if (samples_len < samples_req) { - /* Expand buffer */ - expand(wsola, samples_req - samples_len); - TRACE_((THIS_FILE, "Buf size after expanded = %d", - pjmedia_circ_buf_get_len(wsola->buf))); + /* Expand buffer */ + expand(wsola, samples_req - samples_len); + TRACE_((THIS_FILE, "Buf size after expanded = %d", + pjmedia_circ_buf_get_len(wsola->buf))); } status = pjmedia_circ_buf_copy(wsola->buf, wsola->hist_size, frm, - wsola->samples_per_frame); + wsola->samples_per_frame); if (status != PJ_SUCCESS) { - TRACE_((THIS_FILE, "Failed copying from circbuf [err=%d]", status)); - return status; + TRACE_((THIS_FILE, "Failed copying from circbuf [err=%d]", status)); + return status; } pjmedia_circ_buf_adv_read_ptr(wsola->buf, wsola->samples_per_frame); /* Apply fade-out to the frame */ if ((wsola->options & PJMEDIA_WSOLA_NO_FADING)==0) { - wsola_fade_out(wsola, frm, wsola->samples_per_frame); + wsola_fade_out(wsola, frm, wsola->samples_per_frame); } return PJ_SUCCESS; @@ -934,111 +933,111 @@ PJ_DEF(pj_status_t) pjmedia_wsola_generate( pjmedia_wsola *wsola, PJ_DEF(pj_status_t) pjmedia_wsola_discard( pjmedia_wsola *wsola, - pj_int16_t buf1[], - unsigned buf1_cnt, - pj_int16_t buf2[], - unsigned buf2_cnt, - unsigned *del_cnt) + pj_int16_t buf1[], + unsigned buf1_cnt, + pj_int16_t buf2[], + unsigned buf2_cnt, + unsigned *del_cnt) { PJ_ASSERT_RETURN(wsola && buf1 && buf1_cnt && del_cnt, PJ_EINVAL); PJ_ASSERT_RETURN(*del_cnt, PJ_EINVAL); if (buf2_cnt == 0) { - /* The whole buffer is contiguous space, straight away. */ - *del_cnt = compress(wsola, buf1, buf1_cnt, *del_cnt); + /* The whole buffer is contiguous space, straight away. */ + *del_cnt = compress(wsola, buf1, buf1_cnt, *del_cnt); } else { - PJ_ASSERT_RETURN(buf2, PJ_EINVAL); - - if (buf1_cnt < ERASE_CNT * wsola->samples_per_frame && - buf2_cnt < ERASE_CNT * wsola->samples_per_frame && - wsola->erase_buf == NULL) - { - /* We need erase_buf but WSOLA was created with - * PJMEDIA_WSOLA_NO_DISCARD flag. - */ - pj_assert(!"WSOLA need erase buffer!"); - return PJ_EINVALIDOP; - } - - if (buf2_cnt >= ERASE_CNT * wsola->samples_per_frame) { - /* Enough space to perform compress in the second buffer. */ - *del_cnt = compress(wsola, buf2, buf2_cnt, *del_cnt); - } else if (buf1_cnt >= ERASE_CNT * wsola->samples_per_frame) { - /* Enough space to perform compress in the first buffer, but then - * we need to re-arrange the buffers so there is no gap between - * buffers. - */ - unsigned max; - - *del_cnt = compress(wsola, buf1, buf1_cnt, *del_cnt); - - max = *del_cnt; - if (max > buf2_cnt) - max = buf2_cnt; - - pjmedia_move_samples(buf1 + buf1_cnt - (*del_cnt), buf2, max); - - if (max < buf2_cnt) { - pjmedia_move_samples(buf2, buf2+(*del_cnt), - buf2_cnt-max); - } - } else { - /* Not enough samples in either buffers to perform compress. - * Need to combine the buffers in a contiguous space, the erase_buf. - */ - unsigned buf_size = buf1_cnt + buf2_cnt; - pj_int16_t *rem; /* remainder */ - unsigned rem_cnt; - - if (buf_size > ERASE_CNT * wsola->samples_per_frame) { - buf_size = ERASE_CNT * wsola->samples_per_frame; - - rem_cnt = buf1_cnt + buf2_cnt - buf_size; - rem = buf2 + buf2_cnt - rem_cnt; - - } else { - rem = NULL; - rem_cnt = 0; - } - - pjmedia_copy_samples(wsola->erase_buf, buf1, buf1_cnt); - pjmedia_copy_samples(wsola->erase_buf+buf1_cnt, buf2, - buf_size-buf1_cnt); - - *del_cnt = compress(wsola, wsola->erase_buf, buf_size, *del_cnt); - - buf_size -= (*del_cnt); - - /* Copy back to buffers */ - if (buf_size == buf1_cnt) { - pjmedia_copy_samples(buf1, wsola->erase_buf, buf_size); - if (rem_cnt) { - pjmedia_move_samples(buf2, rem, rem_cnt); - } - } else if (buf_size < buf1_cnt) { - pjmedia_copy_samples(buf1, wsola->erase_buf, buf_size); - if (rem_cnt) { - unsigned c = rem_cnt; - if (c > buf1_cnt-buf_size) { - c = buf1_cnt-buf_size; - } - pjmedia_copy_samples(buf1+buf_size, rem, c); - rem += c; - rem_cnt -= c; - if (rem_cnt) - pjmedia_move_samples(buf2, rem, rem_cnt); - } - } else { - pjmedia_copy_samples(buf1, wsola->erase_buf, buf1_cnt); - pjmedia_copy_samples(buf2, wsola->erase_buf+buf1_cnt, - buf_size-buf1_cnt); - if (rem_cnt) { - pjmedia_move_samples(buf2+buf_size-buf1_cnt, rem, - rem_cnt); - } - } - - } + PJ_ASSERT_RETURN(buf2, PJ_EINVAL); + + if (buf1_cnt < ERASE_CNT * wsola->samples_per_frame && + buf2_cnt < ERASE_CNT * wsola->samples_per_frame && + wsola->erase_buf == NULL) + { + /* We need erase_buf but WSOLA was created with + * PJMEDIA_WSOLA_NO_DISCARD flag. + */ + pj_assert(!"WSOLA need erase buffer!"); + return PJ_EINVALIDOP; + } + + if (buf2_cnt >= ERASE_CNT * wsola->samples_per_frame) { + /* Enough space to perform compress in the second buffer. */ + *del_cnt = compress(wsola, buf2, buf2_cnt, *del_cnt); + } else if (buf1_cnt >= ERASE_CNT * wsola->samples_per_frame) { + /* Enough space to perform compress in the first buffer, but then + * we need to re-arrange the buffers so there is no gap between + * buffers. + */ + unsigned max; + + *del_cnt = compress(wsola, buf1, buf1_cnt, *del_cnt); + + max = *del_cnt; + if (max > buf2_cnt) + max = buf2_cnt; + + pjmedia_move_samples(buf1 + buf1_cnt - (*del_cnt), buf2, max); + + if (max < buf2_cnt) { + pjmedia_move_samples(buf2, buf2+(*del_cnt), + buf2_cnt-max); + } + } else { + /* Not enough samples in either buffers to perform compress. + * Need to combine the buffers in a contiguous space, the erase_buf. + */ + unsigned buf_size = buf1_cnt + buf2_cnt; + pj_int16_t *rem; /* remainder */ + unsigned rem_cnt; + + if (buf_size > ERASE_CNT * wsola->samples_per_frame) { + buf_size = ERASE_CNT * wsola->samples_per_frame; + + rem_cnt = buf1_cnt + buf2_cnt - buf_size; + rem = buf2 + buf2_cnt - rem_cnt; + + } else { + rem = NULL; + rem_cnt = 0; + } + + pjmedia_copy_samples(wsola->erase_buf, buf1, buf1_cnt); + pjmedia_copy_samples(wsola->erase_buf+buf1_cnt, buf2, + buf_size-buf1_cnt); + + *del_cnt = compress(wsola, wsola->erase_buf, buf_size, *del_cnt); + + buf_size -= (*del_cnt); + + /* Copy back to buffers */ + if (buf_size == buf1_cnt) { + pjmedia_copy_samples(buf1, wsola->erase_buf, buf_size); + if (rem_cnt) { + pjmedia_move_samples(buf2, rem, rem_cnt); + } + } else if (buf_size < buf1_cnt) { + pjmedia_copy_samples(buf1, wsola->erase_buf, buf_size); + if (rem_cnt) { + unsigned c = rem_cnt; + if (c > buf1_cnt-buf_size) { + c = buf1_cnt-buf_size; + } + pjmedia_copy_samples(buf1+buf_size, rem, c); + rem += c; + rem_cnt -= c; + if (rem_cnt) + pjmedia_move_samples(buf2, rem, rem_cnt); + } + } else { + pjmedia_copy_samples(buf1, wsola->erase_buf, buf1_cnt); + pjmedia_copy_samples(buf2, wsola->erase_buf+buf1_cnt, + buf_size-buf1_cnt); + if (rem_cnt) { + pjmedia_move_samples(buf2+buf_size-buf1_cnt, rem, + rem_cnt); + } + } + + } } return (*del_cnt) > 0 ? PJ_SUCCESS : PJ_ETOOSMALL; @@ -1057,11 +1056,11 @@ struct pjmedia_wsola PJ_DEF(pj_status_t) pjmedia_wsola_create( pj_pool_t *pool, - unsigned clock_rate, - unsigned samples_per_frame, - unsigned channel_count, - unsigned options, - pjmedia_wsola **p_wsola) + unsigned clock_rate, + unsigned samples_per_frame, + unsigned channel_count, + unsigned options, + pjmedia_wsola **p_wsola) { pjmedia_wsola *wsola; @@ -1086,7 +1085,7 @@ PJ_DEF(pj_status_t) pjmedia_wsola_destroy(pjmedia_wsola *wsola) PJ_DEF(pj_status_t) pjmedia_wsola_reset( pjmedia_wsola *wsola, - unsigned options) + unsigned options) { PJ_UNUSED_ARG(wsola); PJ_UNUSED_ARG(options); @@ -1096,8 +1095,8 @@ PJ_DEF(pj_status_t) pjmedia_wsola_reset( pjmedia_wsola *wsola, PJ_DEF(pj_status_t) pjmedia_wsola_save( pjmedia_wsola *wsola, - pj_int16_t frm[], - pj_bool_t prev_lost) + pj_int16_t frm[], + pj_bool_t prev_lost) { PJ_UNUSED_ARG(wsola); PJ_UNUSED_ARG(frm); @@ -1108,7 +1107,7 @@ PJ_DEF(pj_status_t) pjmedia_wsola_save( pjmedia_wsola *wsola, PJ_DEF(pj_status_t) pjmedia_wsola_generate( pjmedia_wsola *wsola, - pj_int16_t frm[]) + pj_int16_t frm[]) { pjmedia_zero_samples(frm, wsola->samples_per_frame); return PJ_SUCCESS; @@ -1116,11 +1115,11 @@ PJ_DEF(pj_status_t) pjmedia_wsola_generate( pjmedia_wsola *wsola, PJ_DEF(pj_status_t) pjmedia_wsola_discard( pjmedia_wsola *wsola, - pj_int16_t buf1[], - unsigned buf1_cnt, - pj_int16_t buf2[], - unsigned buf2_cnt, - unsigned *del_cnt) + pj_int16_t buf1[], + unsigned buf1_cnt, + pj_int16_t buf2[], + unsigned buf2_cnt, + unsigned *del_cnt) { CHECK_(buf1_cnt + buf2_cnt >= wsola->samples_per_frame); @@ -1134,6 +1133,6 @@ PJ_DEF(pj_status_t) pjmedia_wsola_discard( pjmedia_wsola *wsola, return PJ_SUCCESS; } -#endif /* #if PJMEDIA_WSOLA_IMP.. */ +#endif /* #if PJMEDIA_WSOLA_IMP.. */ diff --git a/pjmedia/src/test/audio_tool.c b/pjmedia/src/test/audio_tool.c index 006e138d82..550340d072 100644 --- a/pjmedia/src/test/audio_tool.c +++ b/pjmedia/src/test/audio_tool.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,7 +20,7 @@ #include #include -#define THIS_FILE "audio_tool.c" +#define THIS_FILE "audio_tool.c" static pj_caching_pool caching_pool; static pj_pool_factory *pf; @@ -56,34 +55,34 @@ static char listener_sdp[] = "a=recvonly\r\n"; static pj_status_t play_callback(/* in */ void *user_data, - /* in */ pj_uint32_t timestamp, - /* out */ void *frame, - /* out */ unsigned size) + /* in */ pj_uint32_t timestamp, + /* out */ void *frame, + /* out */ unsigned size) { char pkt[160]; struct pjmedia_frame in, out; int frmsz = cattr.avg_bps / 8 * cattr.ptime / 1000; if (fread(pkt, frmsz, 1, fhnd) != 1) { - puts("EOF"); - return -1; + puts("EOF"); + return -1; } else { - in.type = PJMEDIA_FRAME_TYPE_AUDIO; - in.buf = pkt; - in.size = frmsz; - out.buf = frame; - if (codec->op->decode (codec, &in, size, &out) != 0) - return -1; - - size = out.size; - return 0; + in.type = PJMEDIA_FRAME_TYPE_AUDIO; + in.buf = pkt; + in.size = frmsz; + out.buf = frame; + if (codec->op->decode (codec, &in, size, &out) != 0) + return -1; + + size = out.size; + return 0; } } static pj_status_t rec_callback( /* in */ void *user_data, - /* in */ pj_uint32_t timestamp, - /* in */ const void *frame, - /* in*/ unsigned size) + /* in */ pj_uint32_t timestamp, + /* in */ const void *frame, + /* in*/ unsigned size) { char pkt[160]; struct pjmedia_frame in, out; @@ -99,10 +98,10 @@ static pj_status_t rec_callback( /* in */ void *user_data, out.buf = pkt; if (codec->op->encode(codec, &in, sizeof(pkt), &out) != 0) - return -1; + return -1; if (fwrite(pkt, out.size, 1, fhnd) != 1) - return -1; + return -1; return 0; } @@ -116,15 +115,15 @@ static pj_status_t init() pf = &caching_pool.factory; if (pj_snd_init(&caching_pool.factory)) - return -1; + return -1; PJ_LOG(3,(THIS_FILE, "Dumping audio devices:")); for (i=0; iname, - info->input_count, info->output_count)); + const pj_snd_dev_info *info; + info = pj_snd_get_dev_info(i); + PJ_LOG(3,(THIS_FILE, " %d: %s\t(%d in, %d out", + i, info->name, + info->input_count, info->output_count)); } mm = pj_med_mgr_create (&caching_pool.factory); @@ -163,12 +162,12 @@ static pj_status_t record_file (const char *filename) fhnd = fopen(filename, "wb"); if (!fhnd) - return -1; + return -1; #if WRITE_ORIGINAL_PCM fhnd_pcm = fopen("ORIGINAL.PCM", "wb"); if (!fhnd_pcm) - return -1; + return -1; #endif pj_bzero(&info, sizeof(info)); @@ -180,12 +179,12 @@ static pj_status_t record_file (const char *filename) stream = pj_snd_open_recorder(-1, &info, &rec_callback, NULL); if (!stream){ - goto on_error; + goto on_error; } status = pj_snd_stream_start(stream); if (status != 0) - goto on_error; + goto on_error; puts("Press to exit recording"); fgets(s, sizeof(s), stdin); @@ -222,7 +221,7 @@ static pj_status_t play_file (const char *filename) fhnd = fopen(filename, "rb"); if (!fhnd) - return -1; + return -1; pj_bzero(&info, sizeof(info)); info.bits_per_sample = 16; @@ -233,13 +232,13 @@ static pj_status_t play_file (const char *filename) stream = pj_snd_open_player(-1, &info, &play_callback, NULL); if (!stream){ - fclose(fhnd); - return -1; + fclose(fhnd); + return -1; } status = pj_snd_stream_start(stream); if (status != 0) - goto on_error; + goto on_error; puts("Press to exit playing"); fgets(s, sizeof(s), stdin); @@ -268,66 +267,66 @@ static int create_ses_by_remote_sdp(int local_port, char *sdp) pool = pj_pool_create(pf, "sdp", 1024, 0, NULL); if (!pool) { - PJ_LOG(1,(THIS_FILE, "Unable to create pool")); - return -1; + PJ_LOG(1,(THIS_FILE, "Unable to create pool")); + return -1; } pj_bzero(&skinfo, sizeof(skinfo)); skinfo.rtp_sock = skinfo.rtcp_sock = pj_sock_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, 0); if (skinfo.rtp_sock == PJ_INVALID_SOCKET) { - PJ_LOG(1,(THIS_FILE, "Unable to create socket")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Unable to create socket")); + goto on_error; } pj_sockaddr_init2(&skinfo.rtp_addr_name, "0.0.0.0", local_port); if (pj_sock_bind(skinfo.rtp_sock, (struct pj_sockaddr*)&skinfo.rtp_addr_name, sizeof(pj_sockaddr_in)) != 0) { - PJ_LOG(1,(THIS_FILE, "Unable to bind socket")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Unable to bind socket")); + goto on_error; } sdp_ses = pjsdp_parse(sdp, strlen(sdp), pool); if (!sdp_ses) { - PJ_LOG(1,(THIS_FILE, "Error parsing SDP")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Error parsing SDP")); + goto on_error; } ses = pj_media_session_create_from_sdp(mm, sdp_ses, &skinfo); if (!ses) { - PJ_LOG(1,(THIS_FILE, "Unable to create session from SDP")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Unable to create session from SDP")); + goto on_error; } if (pj_media_session_activate(ses) != 0) { - PJ_LOG(1,(THIS_FILE, "Error activating session")); - goto on_error; + PJ_LOG(1,(THIS_FILE, "Error activating session")); + goto on_error; } count = pj_media_session_enum_streams(ses, 2, info); printf("\nDumping streams: \n"); for (i=0; idir) { - case PJMEDIA_DIR_NONE: - dir = "- NONE -"; break; - case PJMEDIA_DIR_ENCODING: - dir = "SENDONLY"; break; - case PJMEDIA_DIR_DECODING: - dir = "RECVONLY"; break; - case PJMEDIA_DIR_ENCODING_DECODING: - dir = "SENDRECV"; break; - default: - dir = "?UNKNOWN"; break; - } - - local_ip = pj_sockaddr_get_str_addr(&info[i]->sock_info.rtp_addr_name); - - printf(" Stream %d: %.*s %s local=%s:%d remote=%.*s:%d\n", - i, info[i]->type.slen, info[i]->type.ptr, - dir, - local_ip, pj_sockaddr_get_port(&info[i]->sock_info.rtp_addr_name), - info[i]->rem_addr.slen, info[i]->rem_addr.ptr, info[i]->rem_port); + const char *dir; + char *local_ip; + + switch (info[i]->dir) { + case PJMEDIA_DIR_NONE: + dir = "- NONE -"; break; + case PJMEDIA_DIR_ENCODING: + dir = "SENDONLY"; break; + case PJMEDIA_DIR_DECODING: + dir = "RECVONLY"; break; + case PJMEDIA_DIR_ENCODING_DECODING: + dir = "SENDRECV"; break; + default: + dir = "?UNKNOWN"; break; + } + + local_ip = pj_sockaddr_get_str_addr(&info[i]->sock_info.rtp_addr_name); + + printf(" Stream %d: %.*s %s local=%s:%d remote=%.*s:%d\n", + i, info[i]->type.slen, info[i]->type.ptr, + dir, + local_ip, pj_sockaddr_get_port(&info[i]->sock_info.rtp_addr_name), + info[i]->rem_addr.slen, info[i]->rem_addr.ptr, info[i]->rem_port); } puts("Press to quit"); @@ -341,11 +340,11 @@ static int create_ses_by_remote_sdp(int local_port, char *sdp) on_error: if (ses) - pj_media_session_destroy(ses); + pj_media_session_destroy(ses); if (skinfo.rtp_sock != PJ_INVALID_SOCKET) - pj_sock_close(skinfo.rtp_sock); + pj_sock_close(skinfo.rtp_sock); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return -1; } @@ -358,23 +357,23 @@ static pj_status_t convert(const char *src, const char *dst) fhnd_pcm = fopen(src, "rb"); if (!fhnd_pcm) - return -1; + return -1; fhnd = fopen(dst, "wb"); if (!fhnd) - return -1; + return -1; while (fread(pcm, 320, 1, fhnd_pcm) == 1) { - in.type = PJMEDIA_FRAME_TYPE_AUDIO; - in.buf = pcm; - in.size = 320; - out.buf = frame; + in.type = PJMEDIA_FRAME_TYPE_AUDIO; + in.buf = pcm; + in.size = 320; + out.buf = frame; - if (codec->op->encode(codec, &in, 160, &out) != 0) - break; + if (codec->op->encode(codec, &in, 160, &out) != 0) + break; - if (fwrite(frame, out.size, 1, fhnd) != 1) - break; + if (fwrite(frame, out.size, 1, fhnd) != 1) + break; } @@ -394,8 +393,8 @@ static void usage(const char *exe) int main(int argc, char *argv[]) { if (argc < 2) { - usage(argv[0]); - return 1; + usage(argv[0]); + return 1; } pj_init(); @@ -403,15 +402,15 @@ int main(int argc, char *argv[]) init(); if (stricmp(argv[1], "record")==0) { - record_file("FILE.PCM"); + record_file("FILE.PCM"); } else if (stricmp(argv[1], "play")==0) { - play_file("FILE.PCM"); + play_file("FILE.PCM"); } else if (stricmp(argv[1], "send")==0) { - create_ses_by_remote_sdp(4002, listener_sdp); + create_ses_by_remote_sdp(4002, listener_sdp); } else if (stricmp(argv[1], "recv")==0) { - create_ses_by_remote_sdp(4000, talker_sdp); + create_ses_by_remote_sdp(4000, talker_sdp); } else { - usage(argv[0]); + usage(argv[0]); } deinit(); return 0; diff --git a/pjmedia/src/test/codec_vectors.c b/pjmedia/src/test/codec_vectors.c index 06d2ffaa67..6a55d4839d 100644 --- a/pjmedia/src/test/codec_vectors.c +++ b/pjmedia/src/test/codec_vectors.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -20,17 +19,17 @@ #include #define THIS_FILE "codec_vectors.c" -#define TMP_OUT "output.tmp" +#define TMP_OUT "output.tmp" /* * Encode test. Read input from WAV file, encode to temporary output file, * and compare the temporary output file to the reference file. */ static int codec_test_encode(pjmedia_codec_mgr *mgr, - char *codec_name, - unsigned bitrate, - const char *wav_file, - const char *ref_encoded_file) + char *codec_name, + unsigned bitrate, + const char *wav_file, + const char *ref_encoded_file) { pj_str_t codec_id = pj_str(codec_name); pj_pool_t *pool = NULL; @@ -47,28 +46,28 @@ static int codec_test_encode(pjmedia_codec_mgr *mgr, pool = pj_pool_create(mem, "codec-vectors", 512, 512, NULL); if (!pool) { - rc = -20; - goto on_return; + rc = -20; + goto on_return; } /* Find and open the codec */ count = 1; status = pjmedia_codec_mgr_find_codecs_by_id(mgr, &codec_id, &count, ci, NULL); if (status != PJ_SUCCESS) { - rc = -30; - goto on_return; + rc = -30; + goto on_return; } status = pjmedia_codec_mgr_alloc_codec(mgr, ci[0], &codec); if (status != PJ_SUCCESS) { - rc = -40; - goto on_return; + rc = -40; + goto on_return; } status = pjmedia_codec_mgr_get_default_param(mgr, ci[0], &codec_param); if (status != PJ_SUCCESS) { - rc = -50; - goto on_return; + rc = -50; + goto on_return; } codec_param.info.avg_bps = bitrate; @@ -79,36 +78,36 @@ static int codec_test_encode(pjmedia_codec_mgr *mgr, * just clear the SDP fmtp. */ if (pj_ansi_strstr(codec_name, "G7221/")) { - codec_param.setting.dec_fmtp.cnt = 0; + codec_param.setting.dec_fmtp.cnt = 0; } status = pjmedia_codec_init(codec, pool); if (status != PJ_SUCCESS) { - rc = -60; - goto on_return; + rc = -60; + goto on_return; } status = pjmedia_codec_open(codec, &codec_param); if (status != PJ_SUCCESS) { - rc = -70; - goto on_return; + rc = -70; + goto on_return; } /* Open WAV file */ status = pjmedia_wav_player_port_create(pool, wav_file, - codec_param.info.frm_ptime, - PJMEDIA_FILE_NO_LOOP, 0, - &wav_port); + codec_param.info.frm_ptime, + PJMEDIA_FILE_NO_LOOP, 0, + &wav_port); if (status != PJ_SUCCESS) { - rc = -80; - goto on_return; + rc = -80; + goto on_return; } /* Open output file */ output = fopen(TMP_OUT, "wb"); if (!output) { - rc = -90; - goto on_return; + rc = -90; + goto on_return; } /* Allocate buffer for PCM and encoded frames */ @@ -118,27 +117,27 @@ static int codec_test_encode(pjmedia_codec_mgr *mgr, /* Loop read WAV file and encode and write to output file */ for (;;) { - in_frame.size = samples_per_frame * 2; - in_frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - - status = pjmedia_port_get_frame(wav_port, &in_frame); - if (status != PJ_SUCCESS || in_frame.type != PJMEDIA_FRAME_TYPE_AUDIO) - break; - - out_frame.size = samples_per_frame; - status = pjmedia_codec_encode(codec, &in_frame, samples_per_frame, - &out_frame); - if (status != PJ_SUCCESS) { - rc = -95; - goto on_return; - } + in_frame.size = samples_per_frame * 2; + in_frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + + status = pjmedia_port_get_frame(wav_port, &in_frame); + if (status != PJ_SUCCESS || in_frame.type != PJMEDIA_FRAME_TYPE_AUDIO) + break; + + out_frame.size = samples_per_frame; + status = pjmedia_codec_encode(codec, &in_frame, samples_per_frame, + &out_frame); + if (status != PJ_SUCCESS) { + rc = -95; + goto on_return; + } - if (out_frame.size) { - fwrite(out_frame.buf, out_frame.size, 1, output); + if (out_frame.size) { + fwrite(out_frame.buf, out_frame.size, 1, output); - if (encoded_frame_len == 0) - encoded_frame_len = out_frame.size; - } + if (encoded_frame_len == 0) + encoded_frame_len = out_frame.size; + } } fclose(output); @@ -147,63 +146,63 @@ static int codec_test_encode(pjmedia_codec_mgr *mgr, /* Compare encoded files */ fref = fopen(ref_encoded_file, "rb"); if (!fref) { - rc = -100; - goto on_return; + rc = -100; + goto on_return; } output = fopen(TMP_OUT, "rb"); if (!output) { - rc = -110; - goto on_return; + rc = -110; + goto on_return; } pos = 0; for (;;) { - pj_size_t count2; - - count2 = fread(in_frame.buf, encoded_frame_len, 1, fref); - if (count2 != 1) - break; - - count2 = fread(out_frame.buf, encoded_frame_len, 1, output); - if (count2 != 1) - break; - - if (memcmp(in_frame.buf, out_frame.buf, encoded_frame_len)) { - unsigned i; - pj_uint8_t *in = (pj_uint8_t*)in_frame.buf; - pj_uint8_t *out = (pj_uint8_t*)out_frame.buf; - - for (i=0; i= 0) { - bit = in_array[j++]; - if (bit == zero) - bit = 0; - else if (bit == one) - bit = 1; - else - *p_frame_error_flag = 1; - - packed_word <<= 1; - packed_word = (short )(packed_word + bit); - bit_count--; + bit = in_array[j++]; + if (bit == zero) + bit = 0; + else if (bit == one) + bit = 1; + else + *p_frame_error_flag = 1; + + packed_word <<= 1; + packed_word = (short )(packed_word + bit); + bit_count--; } - if (swap_endian) - out_words[i] = pj_ntohs(packed_word); - else - out_words[i] = packed_word; + if (swap_endian) + out_words[i] = pj_ntohs(packed_word); + else + out_words[i] = packed_word; } } return (nsamp-1)/16; @@ -284,12 +283,12 @@ static int read_ITU_format(FILE *fp_bitstream, * this function with the "manip" function. */ static int codec_test_decode(pjmedia_codec_mgr *mgr, - char *codec_name, - unsigned bitrate, - unsigned encoded_len, - const char *in_encoded_file, - const char *ref_pcm_file, - void (*manip)(short *pcm, unsigned count)) + char *codec_name, + unsigned bitrate, + unsigned encoded_len, + const char *in_encoded_file, + const char *ref_pcm_file, + void (*manip)(short *pcm, unsigned count)) { pj_str_t codec_id = pj_str(codec_name); pj_pool_t *pool = NULL; @@ -306,28 +305,28 @@ static int codec_test_decode(pjmedia_codec_mgr *mgr, pool = pj_pool_create(mem, "codec-vectors", 512, 512, NULL); if (!pool) { - rc = -20; - goto on_return; + rc = -20; + goto on_return; } /* Find and open the codec */ count = 1; status = pjmedia_codec_mgr_find_codecs_by_id(mgr, &codec_id, &count, ci, NULL); if (status != PJ_SUCCESS) { - rc = -30; - goto on_return; + rc = -30; + goto on_return; } status = pjmedia_codec_mgr_alloc_codec(mgr, ci[0], &codec); if (status != PJ_SUCCESS) { - rc = -40; - goto on_return; + rc = -40; + goto on_return; } status = pjmedia_codec_mgr_get_default_param(mgr, ci[0], &codec_param); if (status != PJ_SUCCESS) { - rc = -50; - goto on_return; + rc = -50; + goto on_return; } codec_param.info.avg_bps = bitrate; @@ -338,37 +337,37 @@ static int codec_test_decode(pjmedia_codec_mgr *mgr, * just clear the SDP fmtp. */ if (pj_ansi_strstr(codec_name, "G7221/")) { - codec_param.setting.dec_fmtp.cnt = 0; + codec_param.setting.dec_fmtp.cnt = 0; } status = pjmedia_codec_init(codec, pool); if (status != PJ_SUCCESS) { - rc = -60; - goto on_return; + rc = -60; + goto on_return; } status = pjmedia_codec_open(codec, &codec_param); if (status != PJ_SUCCESS) { - rc = -70; - goto on_return; + rc = -70; + goto on_return; } /* Open input file */ input = fopen(in_encoded_file, "rb"); if (!input) { - rc = -80; - goto on_return; + rc = -80; + goto on_return; } /* Is the file in ITU format? */ is_itu_format = pj_ansi_stricmp(in_encoded_file+strlen(in_encoded_file)-4, - ".itu")==0; + ".itu")==0; /* Open output file */ output = fopen(TMP_OUT, "wb"); if (!output) { - rc = -90; - goto on_return; + rc = -90; + goto on_return; } /* Allocate buffer for PCM and encoded frames */ @@ -378,64 +377,64 @@ static int codec_test_decode(pjmedia_codec_mgr *mgr, /* Loop read WAV file and encode and write to output file */ for (;;) { - pjmedia_frame in_frame[2]; - pj_timestamp ts; - unsigned count2; - pj_bool_t has_frame; - - if (is_itu_format) { - int nsamp; - short frame_err = 0; - - nsamp = read_ITU_format(input, (short*)pkt, &frame_err, - encoded_len / 2, PJ_TRUE); - if (nsamp != (int)encoded_len / 2) - break; - - has_frame = !frame_err; - } else { - if (fread(pkt, encoded_len, 1, input) != 1) - break; - - has_frame = PJ_TRUE; - } - - if (has_frame) { - count2 = 2; - if (pjmedia_codec_parse(codec, pkt, encoded_len, &ts, - &count2, in_frame) != PJ_SUCCESS) - { - rc = -100; - goto on_return; - } - - if (count2 != 1) { - rc = -110; - goto on_return; - } - - if (pjmedia_codec_decode(codec, &in_frame[0], samples_per_frame*2, - &out_frame) != PJ_SUCCESS) - { - rc = -120; - goto on_return; - } - } else { - if (pjmedia_codec_recover(codec, samples_per_frame*2, - &out_frame) != PJ_SUCCESS) - { - rc = -125; - goto on_return; - } - } - - if (manip) - manip((short*)out_frame.buf, samples_per_frame); - - if (fwrite(out_frame.buf, out_frame.size, 1, output) != 1) { - rc = -130; - goto on_return; - } + pjmedia_frame in_frame[2]; + pj_timestamp ts; + unsigned count2; + pj_bool_t has_frame; + + if (is_itu_format) { + int nsamp; + short frame_err = 0; + + nsamp = read_ITU_format(input, (short*)pkt, &frame_err, + encoded_len / 2, PJ_TRUE); + if (nsamp != (int)encoded_len / 2) + break; + + has_frame = !frame_err; + } else { + if (fread(pkt, encoded_len, 1, input) != 1) + break; + + has_frame = PJ_TRUE; + } + + if (has_frame) { + count2 = 2; + if (pjmedia_codec_parse(codec, pkt, encoded_len, &ts, + &count2, in_frame) != PJ_SUCCESS) + { + rc = -100; + goto on_return; + } + + if (count2 != 1) { + rc = -110; + goto on_return; + } + + if (pjmedia_codec_decode(codec, &in_frame[0], samples_per_frame*2, + &out_frame) != PJ_SUCCESS) + { + rc = -120; + goto on_return; + } + } else { + if (pjmedia_codec_recover(codec, samples_per_frame*2, + &out_frame) != PJ_SUCCESS) + { + rc = -125; + goto on_return; + } + } + + if (manip) + manip((short*)out_frame.buf, samples_per_frame); + + if (fwrite(out_frame.buf, out_frame.size, 1, output) != 1) { + rc = -130; + goto on_return; + } } fclose(input); @@ -447,63 +446,63 @@ static int codec_test_decode(pjmedia_codec_mgr *mgr, /* Compare encoded files */ fref = fopen(ref_pcm_file, "rb"); if (!fref) { - rc = -140; - goto on_return; + rc = -140; + goto on_return; } output = fopen(TMP_OUT, "rb"); if (!output) { - rc = -110; - goto on_return; + rc = -110; + goto on_return; } pos = 0; for (;;) { - pj_size_t count2; - - count2 = fread(pkt, samples_per_frame*2, 1, fref); - if (count2 != 1) - break; - - count2 = fread(out_frame.buf, samples_per_frame*2, 1, output); - if (count2 != 1) - break; - - if (memcmp(pkt, out_frame.buf, samples_per_frame*2)) { - unsigned i; - pj_int16_t *in = (pj_int16_t*)pkt; - pj_int16_t *out = (pj_int16_t*)out_frame.buf; - - for (i=0; i %s", - enc_vectors[i].codec_name, - enc_vectors[i].bit_rate, - enc_vectors[i].wav_file, - enc_vectors[i].ref_encoded_file)); - rc = codec_test_encode(mgr, enc_vectors[i].codec_name, - enc_vectors[i].bit_rate, - enc_vectors[i].wav_file, - enc_vectors[i].ref_encoded_file); - if (rc != 0) - rc_final = rc; + if (!enc_vectors[i].codec_name) + continue; + PJ_LOG(3,(THIS_FILE," %s @%d bps %s ==> %s", + enc_vectors[i].codec_name, + enc_vectors[i].bit_rate, + enc_vectors[i].wav_file, + enc_vectors[i].ref_encoded_file)); + rc = codec_test_encode(mgr, enc_vectors[i].codec_name, + enc_vectors[i].bit_rate, + enc_vectors[i].wav_file, + enc_vectors[i].ref_encoded_file); + if (rc != 0) + rc_final = rc; } PJ_LOG(3,(THIS_FILE," decode tests:")); for (i=0; i %s", - dec_vectors[i].codec_name, - dec_vectors[i].bit_rate, - dec_vectors[i].enc_file, - dec_vectors[i].ref_pcm_file)); - rc = codec_test_decode(mgr, dec_vectors[i].codec_name, - dec_vectors[i].bit_rate, - dec_vectors[i].encoded_frame_len, - dec_vectors[i].enc_file, - dec_vectors[i].ref_pcm_file, - dec_vectors[i].manip); - if (rc != 0) - rc_final = rc; + if (!dec_vectors[i].codec_name) + continue; + PJ_LOG(3,(THIS_FILE," %s @%d bps %s ==> %s", + dec_vectors[i].codec_name, + dec_vectors[i].bit_rate, + dec_vectors[i].enc_file, + dec_vectors[i].ref_pcm_file)); + rc = codec_test_decode(mgr, dec_vectors[i].codec_name, + dec_vectors[i].bit_rate, + dec_vectors[i].encoded_frame_len, + dec_vectors[i].enc_file, + dec_vectors[i].ref_pcm_file, + dec_vectors[i].manip); + if (rc != 0) + rc_final = rc; } if (pj_file_exists(TMP_OUT)) - pj_file_delete(TMP_OUT); + pj_file_delete(TMP_OUT); pjmedia_endpt_destroy(endpt); return rc_final; diff --git a/pjmedia/src/test/jbuf_test.c b/pjmedia/src/test/jbuf_test.c index a84b5414cc..b7e03e7ef1 100644 --- a/pjmedia/src/test/jbuf_test.c +++ b/pjmedia/src/test/jbuf_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -23,10 +22,10 @@ #include "test.h" #define JB_INIT_PREFETCH 0 -#define JB_MIN_PREFETCH 0 -#define JB_MAX_PREFETCH 10 -#define JB_PTIME 20 -#define JB_BUF_SIZE 50 +#define JB_MIN_PREFETCH 0 +#define JB_MAX_PREFETCH 10 +#define JB_PTIME 20 +#define JB_BUF_SIZE 50 //#define REPORT //#define PRINT_COMMENT @@ -43,67 +42,67 @@ typedef struct test_cond_t { int discard; int lost; int empty; - int delay; /**< Average delay, in frames. */ - int delay_min; /**< Minimum delay, in frames. */ + int delay; /**< Average delay, in frames. */ + int delay_min; /**< Minimum delay, in frames. */ } test_cond_t; static pj_bool_t parse_test_headers(char *line, test_param_t *param, - test_cond_t *cond) + test_cond_t *cond) { char *p = line; if (*p == '%') { - /* Test params. */ - char mode_st[16]; + /* Test params. */ + char mode_st[16]; - sscanf(p+1, "%s %u %u %u", mode_st, ¶m->init_prefetch, - ¶m->min_prefetch, ¶m->max_prefetch); - param->adaptive = (pj_ansi_stricmp(mode_st, "adaptive") == 0); + sscanf(p+1, "%s %u %u %u", mode_st, ¶m->init_prefetch, + ¶m->min_prefetch, ¶m->max_prefetch); + param->adaptive = (pj_ansi_stricmp(mode_st, "adaptive") == 0); } else if (*p == '!') { - /* Success condition. */ - char cond_st[16]; - unsigned cond_val; - - sscanf(p+1, "%s %u", cond_st, &cond_val); - if (pj_ansi_stricmp(cond_st, "burst") == 0) - cond->burst = cond_val; - else if (pj_ansi_stricmp(cond_st, "delay") == 0) - cond->delay = cond_val; - else if (pj_ansi_stricmp(cond_st, "delay_min") == 0) - cond->delay_min = cond_val; - else if (pj_ansi_stricmp(cond_st, "discard") == 0) - cond->discard = cond_val; - else if (pj_ansi_stricmp(cond_st, "empty") == 0) - cond->empty = cond_val; - else if (pj_ansi_stricmp(cond_st, "lost") == 0) - cond->lost = cond_val; + /* Success condition. */ + char cond_st[16]; + unsigned cond_val; + + sscanf(p+1, "%s %u", cond_st, &cond_val); + if (pj_ansi_stricmp(cond_st, "burst") == 0) + cond->burst = cond_val; + else if (pj_ansi_stricmp(cond_st, "delay") == 0) + cond->delay = cond_val; + else if (pj_ansi_stricmp(cond_st, "delay_min") == 0) + cond->delay_min = cond_val; + else if (pj_ansi_stricmp(cond_st, "discard") == 0) + cond->discard = cond_val; + else if (pj_ansi_stricmp(cond_st, "empty") == 0) + cond->empty = cond_val; + else if (pj_ansi_stricmp(cond_st, "lost") == 0) + cond->lost = cond_val; } else if (*p == '=') { - /* Test title. */ - ++p; - while (*p && isspace(*p)) ++p; - printf("%s", p); + /* Test title. */ + ++p; + while (*p && isspace(*p)) ++p; + printf("%s", p); } else if (*p == '#') { - /* Ignore comment line. */ + /* Ignore comment line. */ } else { - /* Unknown header, perhaps this is the test data */ + /* Unknown header, perhaps this is the test data */ - /* Skip spaces */ - while (*p && isspace(*p)) ++p; + /* Skip spaces */ + while (*p && isspace(*p)) ++p; - /* Test data started.*/ - if (*p != 0) - return PJ_FALSE; + /* Test data started.*/ + if (*p != 0) + return PJ_FALSE; } return PJ_TRUE; } static pj_bool_t process_test_data(char data, pjmedia_jbuf *jb, - pj_uint16_t *seq, pj_uint16_t *last_seq) + pj_uint16_t *seq, pj_uint16_t *last_seq) { char frame[1]; char f_type; @@ -112,51 +111,51 @@ static pj_bool_t process_test_data(char data, pjmedia_jbuf *jb, switch (toupper(data)) { case 'G': /* Get */ - pjmedia_jbuf_get_frame(jb, frame, &f_type); - break; + pjmedia_jbuf_get_frame(jb, frame, &f_type); + break; case 'P': /* Put */ - pjmedia_jbuf_put_frame(jb, (void*)frame, 1, *seq); - *last_seq = *seq; - ++*seq; - break; + pjmedia_jbuf_put_frame(jb, (void*)frame, 1, *seq); + *last_seq = *seq; + ++*seq; + break; case 'L': /* Lost */ - *last_seq = *seq; - ++*seq; - printf("Lost\n"); - break; + *last_seq = *seq; + ++*seq; + printf("Lost\n"); + break; case 'R': /* Sequence restarts */ - *seq = 1; - printf("Sequence restarting, from %u to %u\n", *last_seq, *seq); - break; + *seq = 1; + printf("Sequence restarting, from %u to %u\n", *last_seq, *seq); + break; case 'J': /* Sequence jumps */ - (*seq) += 20; - printf("Sequence jumping, from %u to %u\n", *last_seq, *seq); - break; + (*seq) += 20; + printf("Sequence jumping, from %u to %u\n", *last_seq, *seq); + break; case 'D': /* Frame duplicated */ - pjmedia_jbuf_put_frame(jb, (void*)frame, 1, *seq - 1); - break; + pjmedia_jbuf_put_frame(jb, (void*)frame, 1, *seq - 1); + break; case 'O': /* Old/late frame */ - pjmedia_jbuf_put_frame(jb, (void*)frame, 1, *seq - 10 - pj_rand()%40); - break; + pjmedia_jbuf_put_frame(jb, (void*)frame, 1, *seq - 10 - pj_rand()%40); + break; case '.': /* End of test session. */ - data_eos = PJ_TRUE; - break; + data_eos = PJ_TRUE; + break; default: - print_state = PJ_FALSE; - printf("Unknown test data '%c'\n", data); - break; + print_state = PJ_FALSE; + printf("Unknown test data '%c'\n", data); + break; } if (data_eos) - return PJ_FALSE; + return PJ_FALSE; #ifdef REPORT if (print_state) { - pjmedia_jb_state state; + pjmedia_jb_state state; - pjmedia_jbuf_get_state(jb, &state); - printf("seq=%d\t%c\tsize=%d\tprefetch=%d\n", - *last_seq, toupper(data), state.size, state.prefetch); + pjmedia_jbuf_get_state(jb, &state); + printf("seq=%d\t%c\tsize=%d\tprefetch=%d\n", + *last_seq, toupper(data), state.size, state.prefetch); } #else PJ_UNUSED_ARG(print_state); /* Warning about variable set but unused */ @@ -173,9 +172,9 @@ int jbuf_main(void) int rc = 0; const char* input_filename = "Jbtest.dat"; const char* input_search_path[] = { - "../build", - "pjmedia/build", - "build" + "../build", + "pjmedia/build", + "build" }; /* Try to open test data file in the working directory */ @@ -183,165 +182,165 @@ int jbuf_main(void) /* If that fails, try to open test data file in specified search paths */ if (input == NULL) { - char input_path[PJ_MAXPATH]; - int i; - - for (i = 0; !input && i < PJ_ARRAY_SIZE(input_search_path); ++i) { - pj_ansi_snprintf(input_path, PJ_MAXPATH, "%s/%s", - input_search_path[i], - input_filename); - input = fopen(input_path, "rt"); - } + char input_path[PJ_MAXPATH]; + int i; + + for (i = 0; !input && i < PJ_ARRAY_SIZE(input_search_path); ++i) { + pj_ansi_snprintf(input_path, PJ_MAXPATH, "%s/%s", + input_search_path[i], + input_filename); + input = fopen(input_path, "rt"); + } } /* Failed to open test data file. */ if (input == NULL) { - printf("Failed to open test data file, Jbtest.dat\n"); - return -1; + printf("Failed to open test data file, Jbtest.dat\n"); + return -1; } old_log_level = pj_log_get_level(); pj_log_set_level(5); while (rc == 0 && !data_eof) { - pj_str_t jb_name = {"JBTEST", 6}; - pjmedia_jbuf *jb; - pj_pool_t *pool; - pjmedia_jb_state state; - pj_uint16_t last_seq = 0; - pj_uint16_t seq = 1; - char line[1024], *p = NULL; - - test_param_t param; - test_cond_t cond; - - param.adaptive = PJ_TRUE; - param.init_prefetch = JB_INIT_PREFETCH; - param.min_prefetch = JB_MIN_PREFETCH; - param.max_prefetch = JB_MAX_PREFETCH; - - cond.burst = -1; - cond.delay = -1; - cond.delay_min = -1; - cond.discard = -1; - cond.empty = -1; - cond.lost = -1; - - printf("\n\n"); - - /* Parse test session title, param, and conditions */ - do { - p = fgets(line, sizeof(line), input); - } while (p && parse_test_headers(line, ¶m, &cond)); - - /* EOF test data */ - if (p == NULL) - break; - - //printf("======================================================\n"); - - /* Initialize test session */ - pool = pj_pool_create(mem, "JBPOOL", 256*16, 256*16, NULL); - pjmedia_jbuf_create(pool, &jb_name, 1, JB_PTIME, JB_BUF_SIZE, &jb); - pjmedia_jbuf_reset(jb); - - if (param.adaptive) { - pjmedia_jbuf_set_adaptive(jb, - param.init_prefetch, - param.min_prefetch, - param.max_prefetch); - } else { - pjmedia_jbuf_set_fixed(jb, param.init_prefetch); - } + pj_str_t jb_name = {"JBTEST", 6}; + pjmedia_jbuf *jb; + pj_pool_t *pool; + pjmedia_jb_state state; + pj_uint16_t last_seq = 0; + pj_uint16_t seq = 1; + char line[1024], *p = NULL; + + test_param_t param; + test_cond_t cond; + + param.adaptive = PJ_TRUE; + param.init_prefetch = JB_INIT_PREFETCH; + param.min_prefetch = JB_MIN_PREFETCH; + param.max_prefetch = JB_MAX_PREFETCH; + + cond.burst = -1; + cond.delay = -1; + cond.delay_min = -1; + cond.discard = -1; + cond.empty = -1; + cond.lost = -1; + + printf("\n\n"); + + /* Parse test session title, param, and conditions */ + do { + p = fgets(line, sizeof(line), input); + } while (p && parse_test_headers(line, ¶m, &cond)); + + /* EOF test data */ + if (p == NULL) + break; + + //printf("======================================================\n"); + + /* Initialize test session */ + pool = pj_pool_create(mem, "JBPOOL", 256*16, 256*16, NULL); + pjmedia_jbuf_create(pool, &jb_name, 1, JB_PTIME, JB_BUF_SIZE, &jb); + pjmedia_jbuf_reset(jb); + + if (param.adaptive) { + pjmedia_jbuf_set_adaptive(jb, + param.init_prefetch, + param.min_prefetch, + param.max_prefetch); + } else { + pjmedia_jbuf_set_fixed(jb, param.init_prefetch); + } #ifdef REPORT - pjmedia_jbuf_get_state(jb, &state); - printf("Initial\tsize=%d\tprefetch=%d\tmin.pftch=%d\tmax.pftch=%d\n", - state.size, state.prefetch, state.min_prefetch, - state.max_prefetch); + pjmedia_jbuf_get_state(jb, &state); + printf("Initial\tsize=%d\tprefetch=%d\tmin.pftch=%d\tmax.pftch=%d\n", + state.size, state.prefetch, state.min_prefetch, + state.max_prefetch); #endif - /* Test session start */ - while (1) { - char c; + /* Test session start */ + while (1) { + char c; - /* Get next line of test data */ - if (!p || *p == 0) { - p = fgets(line, sizeof(line), input); - if (p == NULL) { - data_eof = PJ_TRUE; - break; - } - } + /* Get next line of test data */ + if (!p || *p == 0) { + p = fgets(line, sizeof(line), input); + if (p == NULL) { + data_eof = PJ_TRUE; + break; + } + } - /* Get next char of test data */ - c = *p++; + /* Get next char of test data */ + c = *p++; - /* Skip spaces */ - if (isspace(c)) - continue; + /* Skip spaces */ + if (isspace(c)) + continue; - /* Print comment line */ - if (c == '#') { + /* Print comment line */ + if (c == '#') { #ifdef PRINT_COMMENT - while (*p && isspace(*p)) ++p; - if (*p) printf("..%s", p); + while (*p && isspace(*p)) ++p; + if (*p) printf("..%s", p); #endif - *p = 0; - continue; - } - - /* Process test data */ - if (!process_test_data(c, jb, &seq, &last_seq)) - break; - } - - /* Print JB states */ - pjmedia_jbuf_get_state(jb, &state); - printf("------------------------------------------------------\n"); - printf("Summary:\n"); - printf(" size=%d prefetch=%d\n", state.size, state.prefetch); - printf(" delay (min/max/avg/dev)=%d/%d/%d/%d ms\n", - state.min_delay, state.max_delay, state.avg_delay, - state.dev_delay); - printf(" lost=%d discard=%d empty=%d burst(avg)=%d\n", - state.lost, state.discard, state.empty, state.avg_burst); - - /* Evaluate test session */ - if (cond.burst >= 0 && (int)state.avg_burst > cond.burst) { - printf("! 'Burst' should be %d, it is %d\n", - cond.burst, state.avg_burst); - rc |= 1; - } - if (cond.delay >= 0 && (int)state.avg_delay/JB_PTIME > cond.delay) { - printf("! 'Delay' should be %d, it is %d\n", - cond.delay, state.avg_delay/JB_PTIME); - rc |= 2; - } - if (cond.delay_min >= 0 && (int)state.min_delay/JB_PTIME > cond.delay_min) { - printf("! 'Minimum delay' should be %d, it is %d\n", - cond.delay_min, state.min_delay/JB_PTIME); - rc |= 32; - } - if (cond.discard >= 0 && (int)state.discard > cond.discard) { - printf("! 'Discard' should be %d, it is %d\n", - cond.discard, state.discard); - rc |= 4; - } - if (cond.empty >= 0 && (int)state.empty > cond.empty) { - printf("! 'Empty' should be %d, it is %d\n", - cond.empty, state.empty); - rc |= 8; - } - if (cond.lost >= 0 && (int)state.lost > cond.lost) { - printf("! 'Lost' should be %d, it is %d\n", - cond.lost, state.lost); - rc |= 16; - } - - pjmedia_jbuf_destroy(jb); - pj_pool_release(pool); + *p = 0; + continue; + } + + /* Process test data */ + if (!process_test_data(c, jb, &seq, &last_seq)) + break; + } + + /* Print JB states */ + pjmedia_jbuf_get_state(jb, &state); + printf("------------------------------------------------------\n"); + printf("Summary:\n"); + printf(" size=%d prefetch=%d\n", state.size, state.prefetch); + printf(" delay (min/max/avg/dev)=%d/%d/%d/%d ms\n", + state.min_delay, state.max_delay, state.avg_delay, + state.dev_delay); + printf(" lost=%d discard=%d empty=%d burst(avg)=%d\n", + state.lost, state.discard, state.empty, state.avg_burst); + + /* Evaluate test session */ + if (cond.burst >= 0 && (int)state.avg_burst > cond.burst) { + printf("! 'Burst' should be %d, it is %d\n", + cond.burst, state.avg_burst); + rc |= 1; + } + if (cond.delay >= 0 && (int)state.avg_delay/JB_PTIME > cond.delay) { + printf("! 'Delay' should be %d, it is %d\n", + cond.delay, state.avg_delay/JB_PTIME); + rc |= 2; + } + if (cond.delay_min >= 0 && (int)state.min_delay/JB_PTIME > cond.delay_min) { + printf("! 'Minimum delay' should be %d, it is %d\n", + cond.delay_min, state.min_delay/JB_PTIME); + rc |= 32; + } + if (cond.discard >= 0 && (int)state.discard > cond.discard) { + printf("! 'Discard' should be %d, it is %d\n", + cond.discard, state.discard); + rc |= 4; + } + if (cond.empty >= 0 && (int)state.empty > cond.empty) { + printf("! 'Empty' should be %d, it is %d\n", + cond.empty, state.empty); + rc |= 8; + } + if (cond.lost >= 0 && (int)state.lost > cond.lost) { + printf("! 'Lost' should be %d, it is %d\n", + cond.lost, state.lost); + rc |= 16; + } + + pjmedia_jbuf_destroy(jb); + pj_pool_release(pool); } fclose(input); diff --git a/pjmedia/src/test/main.c b/pjmedia/src/test/main.c index 53a0363260..77b49700cf 100644 --- a/pjmedia/src/test/main.c +++ b/pjmedia/src/test/main.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -70,26 +69,26 @@ static int main_func(int argc, char *argv[]) while (argc > 1) { char *arg = argv[--argc]; - if (*arg=='-' && *(arg+1)=='i') { - interractive = 1; + if (*arg=='-' && *(arg+1)=='i') { + interractive = 1; - } else if (*arg=='-' && *(arg+1)=='n') { - no_trap = 1; - } + } else if (*arg=='-' && *(arg+1)=='n') { + no_trap = 1; + } } if (!no_trap) { - init_signals(); + init_signals(); } rc = test_main(); if (interractive) { - char s[10]; - puts(""); - puts("Press to exit"); - if (!fgets(s, sizeof(s), stdin)) - return rc; + char s[10]; + puts(""); + puts("Press to exit"); + if (!fgets(s, sizeof(s), stdin)) + return rc; } return rc; diff --git a/pjmedia/src/test/mips_test.c b/pjmedia/src/test/mips_test.c index 37374404e0..15ea5b2e68 100644 --- a/pjmedia/src/test/mips_test.c +++ b/pjmedia/src/test/mips_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,51 +26,51 @@ For complete table see: http://en.wikipedia.org/wiki/Million_instructions_per_second - Processor IPS/MHz + Processor IPS/MHz ------------------------------------------- - PowerPC G3 2.253 MIPS/MHz - Intel Pentium III 2.708 MIPS/MHz - AMD Athlon 2.967 MIPS/MHz - Pentium 4 Extreme Edition 3.039 MIPS/MHz - AMD Athlon FX-57 4.285 MIPS/MHz + PowerPC G3 2.253 MIPS/MHz + Intel Pentium III 2.708 MIPS/MHz + AMD Athlon 2.967 MIPS/MHz + Pentium 4 Extreme Edition 3.039 MIPS/MHz + AMD Athlon FX-57 4.285 MIPS/MHz From: http://en.wikipedia.org/wiki/ARM_architecture - Family Arch Core IPS/MHz + Family Arch Core IPS/MHz ------------------------------------------------------- - ARM7TDMI ARMv4T ARM7TDMI 0.892 MIPS/MHz - ARM710T 0.900 MIPS/MHz - ARM720T 1.003 MIPS/MHz - ARM9TDMI ARMv4T ARM920T 1.111 MIPS/MHz - ARM9E ARMv5TEJ ARM926EJ-S 1.100 MIPS/MHz - XScale ARMv5TE PXA255 1.000 MIPS/MHz (?) - PXA27x 1.282 MIPS/MHz - Cortex ARMv7-A Cortex-A8 2.000 MIPS/MHz - Cortex-A9 2.000 MIPS/MHz - ARMv7-M Cortex-M3 1.250 MIPS/MHz + ARM7TDMI ARMv4T ARM7TDMI 0.892 MIPS/MHz + ARM710T 0.900 MIPS/MHz + ARM720T 1.003 MIPS/MHz + ARM9TDMI ARMv4T ARM920T 1.111 MIPS/MHz + ARM9E ARMv5TEJ ARM926EJ-S 1.100 MIPS/MHz + XScale ARMv5TE PXA255 1.000 MIPS/MHz (?) + PXA27x 1.282 MIPS/MHz + Cortex ARMv7-A Cortex-A8 2.000 MIPS/MHz + Cortex-A9 2.000 MIPS/MHz + ARMv7-M Cortex-M3 1.250 MIPS/MHz */ -# define CPU_MHZ (2666) -# define CPU_IPS (3.039 * CPU_MHZ * MEGA) /* P4 2.6GHz */ +# define CPU_MHZ (2666) +# define CPU_IPS (3.039 * CPU_MHZ * MEGA) /* P4 2.6GHz */ -//# define CPU_MHZ 700 -//# define CPU_IPS (700 * MEGA * 2.708) /* P3 700Mhz */ +//# define CPU_MHZ 700 +//# define CPU_IPS (700 * MEGA * 2.708) /* P3 700Mhz */ -//# define CPU_MHZ 180 -//# define CPU_IPS (CPU_MHZ * MEGA * 1.1) /* ARM926EJ-S */ +//# define CPU_MHZ 180 +//# define CPU_IPS (CPU_MHZ * MEGA * 1.1) /* ARM926EJ-S */ -//# define CPU_MHZ 312 -//# define CPU_IPS (CPU_MHZ * MEGA * 1.282) /* Dell Axim PDA */ +//# define CPU_MHZ 312 +//# define CPU_IPS (CPU_MHZ * MEGA * 1.282) /* Dell Axim PDA */ #endif #define HAS_AUDIO_CODECS (PJMEDIA_HAS_G711_CODEC || PJMEDIA_HAS_G722_CODEC ||\ - PJMEDIA_HAS_GSM_CODEC || PJMEDIA_HAS_ILBC_CODEC || \ - PJMEDIA_HAS_SPEEX_CODEC|| PJMEDIA_HAS_G7221_CODEC||\ - PJMEDIA_HAS_OPENCORE_AMRNB_CODEC ||\ - PJMEDIA_HAS_OPENCORE_AMRWB_CODEC ||\ - PJMEDIA_HAS_L16_CODEC) + PJMEDIA_HAS_GSM_CODEC || PJMEDIA_HAS_ILBC_CODEC || \ + PJMEDIA_HAS_SPEEX_CODEC|| PJMEDIA_HAS_G7221_CODEC||\ + PJMEDIA_HAS_OPENCORE_AMRNB_CODEC ||\ + PJMEDIA_HAS_OPENCORE_AMRWB_CODEC ||\ + PJMEDIA_HAS_L16_CODEC) /* Sample speech data, 360ms length, encoded at 8Khz */ @@ -366,11 +365,11 @@ static const pj_int16_t ref_signal[] = { 88, -140, -37, 160, 0, -92, 96, 24, -84, 0, }; -#define THIS_FILE "mips_test.c" -#define DURATION 5000 -#define PTIME 20 /* MUST be 20! */ -#define MEGA 1000000 -#define GIGA 1000000000 +#define THIS_FILE "mips_test.c" +#define DURATION 5000 +#define PTIME 20 /* MUST be 20! */ +#define MEGA 1000000 +#define GIGA 1000000000 enum op { @@ -382,69 +381,69 @@ enum op enum clock_rate { - K8 = 1, - K16 = 2, - K32 = 4, + K8 = 1, + K16 = 2, + K32 = 4, }; struct test_entry { - const char *title; - unsigned valid_op; - unsigned valid_clock_rate; + const char *title; + unsigned valid_op; + unsigned valid_clock_rate; pjmedia_port* (*init)(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *); - void (*custom_run)(struct test_entry*); - void (*custom_deinit)(struct test_entry*); - - void *pdata[4]; - unsigned idata[4]; + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *); + void (*custom_run)(struct test_entry*); + void (*custom_deinit)(struct test_entry*); + + void *pdata[4]; + unsigned idata[4]; }; /***************************************************************************/ /* pjmedia_port to supply with continuous frames */ static pjmedia_port* create_gen_port(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned pct_level) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned pct_level) { pjmedia_port *port; pj_status_t status; if (pct_level == 100 && channel_count==1) { - status = pjmedia_mem_player_create(pool, ref_signal, - sizeof(ref_signal), clock_rate, - channel_count, samples_per_frame, - 16, 0, &port); + status = pjmedia_mem_player_create(pool, ref_signal, + sizeof(ref_signal), clock_rate, + channel_count, samples_per_frame, + 16, 0, &port); } else { - pj_int16_t *buf; - unsigned c; - - buf = (pj_int16_t*) - pj_pool_alloc(pool, sizeof(ref_signal)*channel_count); - for (c=0; cpkt; out_frame.size = sizeof(cp->pkt); status = pjmedia_codec_encode(cp->codec, frame, sizeof(cp->pkt), - &out_frame); + &out_frame); pj_assert(status == PJ_SUCCESS); if (out_frame.size != 0) { - pjmedia_frame parsed_frm[2], pcm_frm; - unsigned frame_cnt = PJ_ARRAY_SIZE(parsed_frm); - unsigned i; - - status = pjmedia_codec_parse(cp->codec, out_frame.buf, - out_frame.size, &out_frame.timestamp, - &frame_cnt, parsed_frm); - pj_assert(status == PJ_SUCCESS); - - for (i=0; ipcm; - pcm_frm.size = sizeof(cp->pkt); - status = pjmedia_codec_decode(cp->codec, &parsed_frm[i], - sizeof(cp->pcm), &pcm_frm); - pj_assert(status == PJ_SUCCESS); - } + pjmedia_frame parsed_frm[2], pcm_frm; + unsigned frame_cnt = PJ_ARRAY_SIZE(parsed_frm); + unsigned i; + + status = pjmedia_codec_parse(cp->codec, out_frame.buf, + out_frame.size, &out_frame.timestamp, + &frame_cnt, parsed_frm); + pj_assert(status == PJ_SUCCESS); + + for (i=0; ipcm; + pcm_frm.size = sizeof(cp->pkt); + status = pjmedia_codec_decode(cp->codec, &parsed_frm[i], + sizeof(cp->pcm), &pcm_frm); + pj_assert(status == PJ_SUCCESS); + } } return status; @@ -730,7 +729,7 @@ static pj_status_t codec_on_destroy(struct pjmedia_port *this_port) pjmedia_codec_close(cp->codec); pjmedia_codec_mgr_dealloc_codec(pjmedia_endpt_get_codec_mgr(cp->endpt), - cp->codec); + cp->codec); cp->codec_deinit(); pjmedia_endpt_destroy(cp->endpt); return PJ_SUCCESS; @@ -738,14 +737,14 @@ static pj_status_t codec_on_destroy(struct pjmedia_port *this_port) #if HAS_AUDIO_CODECS static pjmedia_port* codec_encode_decode( pj_pool_t *pool, - const char *codec, - pj_status_t (*codec_init)(pjmedia_endpt*), - pj_status_t (*codec_deinit)(), - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + const char *codec, + pj_status_t (*codec_init)(pjmedia_endpt*), + pj_status_t (*codec_deinit)(), + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { struct codec_port *cp; pj_str_t codec_id; @@ -760,42 +759,42 @@ static pjmedia_port* codec_encode_decode( pj_pool_t *pool, codec_id = pj_str((char*)codec); cp = PJ_POOL_ZALLOC_T(pool, struct codec_port); pjmedia_port_info_init(&cp->base.info, &codec_id, 0x123456, clock_rate, - channel_count, 16, samples_per_frame); + channel_count, 16, samples_per_frame); cp->base.put_frame = &codec_put_frame; cp->base.on_destroy = &codec_on_destroy; cp->codec_deinit = codec_deinit; status = pjmedia_endpt_create(mem, NULL, 0, &cp->endpt); if (status != PJ_SUCCESS) - return NULL; + return NULL; status = codec_init(cp->endpt); if (status != PJ_SUCCESS) - return NULL; + return NULL; count = 1; status = pjmedia_codec_mgr_find_codecs_by_id(pjmedia_endpt_get_codec_mgr(cp->endpt), - &codec_id, &count, ci, NULL); + &codec_id, &count, ci, NULL); if (status != PJ_SUCCESS) - return NULL; + return NULL; status = pjmedia_codec_mgr_alloc_codec(pjmedia_endpt_get_codec_mgr(cp->endpt), - ci[0], &cp->codec); + ci[0], &cp->codec); if (status != PJ_SUCCESS) - return NULL; + return NULL; status = pjmedia_codec_mgr_get_default_param(pjmedia_endpt_get_codec_mgr(cp->endpt), - ci[0], &codec_param); + ci[0], &codec_param); if (status != PJ_SUCCESS) - return NULL; + return NULL; status = pjmedia_codec_init(cp->codec, pool); if (status != PJ_SUCCESS) - return NULL; + return NULL; status = pjmedia_codec_open(cp->codec, &codec_param); if (status != PJ_SUCCESS) - return NULL; + return NULL; return &cp->base; } @@ -804,32 +803,32 @@ static pjmedia_port* codec_encode_decode( pj_pool_t *pool, #if PJMEDIA_HAS_G711_CODEC /* G.711 benchmark */ static pjmedia_port* g711_encode_decode( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return codec_encode_decode(pool, "pcmu", &pjmedia_codec_g711_init, - &pjmedia_codec_g711_deinit, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_g711_deinit, + clock_rate, channel_count, + samples_per_frame, flags, te); } #endif /* GSM benchmark */ #if PJMEDIA_HAS_GSM_CODEC static pjmedia_port* gsm_encode_decode( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return codec_encode_decode(pool, "gsm", &pjmedia_codec_gsm_init, - &pjmedia_codec_gsm_deinit, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_gsm_deinit, + clock_rate, channel_count, + samples_per_frame, flags, te); } #endif @@ -841,98 +840,98 @@ static pj_status_t ilbc_init(pjmedia_endpt *endpt) /* iLBC benchmark */ static pjmedia_port* ilbc_encode_decode( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { samples_per_frame = 30 * clock_rate / 1000; return codec_encode_decode(pool, "ilbc", &ilbc_init, - &pjmedia_codec_ilbc_deinit, clock_rate, - channel_count, samples_per_frame, flags, te); + &pjmedia_codec_ilbc_deinit, clock_rate, + channel_count, samples_per_frame, flags, te); } #endif #if PJMEDIA_HAS_SPEEX_CODEC /* Speex narrowband benchmark */ static pjmedia_port* speex8_encode_decode(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return codec_encode_decode(pool, "speex/8000", - &pjmedia_codec_speex_init_default, - &pjmedia_codec_speex_deinit, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_speex_init_default, + &pjmedia_codec_speex_deinit, + clock_rate, channel_count, + samples_per_frame, flags, te); } /* Speex wideband benchmark */ static pjmedia_port* speex16_encode_decode(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return codec_encode_decode(pool, "speex/16000", - &pjmedia_codec_speex_init_default, - &pjmedia_codec_speex_deinit, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_speex_init_default, + &pjmedia_codec_speex_deinit, + clock_rate, channel_count, + samples_per_frame, flags, te); } #endif #if PJMEDIA_HAS_G722_CODEC /* G.722 benchmark benchmark */ static pjmedia_port* g722_encode_decode(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return codec_encode_decode(pool, "g722", &pjmedia_codec_g722_init, - &pjmedia_codec_g722_deinit, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_g722_deinit, + clock_rate, channel_count, + samples_per_frame, flags, te); } #endif #if PJMEDIA_HAS_G7221_CODEC /* G.722.1 benchmark benchmark */ static pjmedia_port* g7221_encode_decode(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return codec_encode_decode(pool, "g7221/16000", - &pjmedia_codec_g7221_init, - &pjmedia_codec_g7221_deinit, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_g7221_init, + &pjmedia_codec_g7221_deinit, + clock_rate, channel_count, + samples_per_frame, flags, te); } /* G.722.1 Annex C benchmark benchmark */ static pjmedia_port* g7221c_encode_decode(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return codec_encode_decode(pool, "g7221/32000", - &pjmedia_codec_g7221_init, - &pjmedia_codec_g7221_deinit, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_g7221_init, + &pjmedia_codec_g7221_deinit, + clock_rate, channel_count, + samples_per_frame, flags, te); } -#endif /* PJMEDIA_HAS_G7221_CODEC */ +#endif /* PJMEDIA_HAS_G7221_CODEC */ #if PJMEDIA_HAS_OPENCORE_AMRNB_CODEC /* AMR-NB benchmark benchmark */ @@ -944,12 +943,12 @@ static pjmedia_port* amr_encode_decode(pj_pool_t *pool, struct test_entry *te) { return codec_encode_decode(pool, "AMR/8000", - &pjmedia_codec_opencore_amrnb_init, - &pjmedia_codec_opencore_amrnb_deinit, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_opencore_amrnb_init, + &pjmedia_codec_opencore_amrnb_deinit, + clock_rate, channel_count, + samples_per_frame, flags, te); } -#endif /* PJMEDIA_HAS_OPENCORE_AMRNB_CODEC */ +#endif /* PJMEDIA_HAS_OPENCORE_AMRNB_CODEC */ #if PJMEDIA_HAS_OPENCORE_AMRWB_CODEC /* AMR-WB benchmark benchmark */ @@ -961,12 +960,12 @@ static pjmedia_port* amrwb_encode_decode(pj_pool_t *pool, struct test_entry *te) { return codec_encode_decode(pool, "AMR/16000", - &pjmedia_codec_opencore_amr_init_default, - &pjmedia_codec_opencore_amr_deinit, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_opencore_amr_init_default, + &pjmedia_codec_opencore_amr_deinit, + clock_rate, channel_count, + samples_per_frame, flags, te); } -#endif /* PJMEDIA_HAS_OPENCORE_AMRWB_CODEC */ +#endif /* PJMEDIA_HAS_OPENCORE_AMRWB_CODEC */ #if defined(PJMEDIA_HAS_L16_CODEC) && PJMEDIA_HAS_L16_CODEC!=0 static pj_status_t init_l16_default(pjmedia_endpt *endpt) @@ -976,30 +975,30 @@ static pj_status_t init_l16_default(pjmedia_endpt *endpt) /* L16/8000/1 benchmark */ static pjmedia_port* l16_8_encode_decode(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return codec_encode_decode(pool, "L16/8000/1", &init_l16_default, - &pjmedia_codec_l16_deinit, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_l16_deinit, + clock_rate, channel_count, + samples_per_frame, flags, te); } /* L16/16000/1 benchmark */ static pjmedia_port* l16_16_encode_decode(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return codec_encode_decode(pool, "L16/16000/1", &init_l16_default, - &pjmedia_codec_l16_deinit, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_l16_deinit, + clock_rate, channel_count, + samples_per_frame, flags, te); } #endif @@ -1011,30 +1010,30 @@ struct wsola_plc_port pjmedia_port base; pjmedia_wsola *wsola; pjmedia_port *gen_port; - int loss_pct; - pj_bool_t prev_lost; + int loss_pct; + pj_bool_t prev_lost; }; static pj_status_t wsola_plc_get_frame(struct pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct wsola_plc_port *wp = (struct wsola_plc_port*)this_port; pj_status_t status; if ((pj_rand() % 100) > wp->loss_pct) { - status = pjmedia_port_get_frame(wp->gen_port, frame); - pj_assert(status == PJ_SUCCESS); + status = pjmedia_port_get_frame(wp->gen_port, frame); + pj_assert(status == PJ_SUCCESS); - status = pjmedia_wsola_save(wp->wsola, (short*)frame->buf, - wp->prev_lost); - pj_assert(status == PJ_SUCCESS); + status = pjmedia_wsola_save(wp->wsola, (short*)frame->buf, + wp->prev_lost); + pj_assert(status == PJ_SUCCESS); - wp->prev_lost = PJ_FALSE; + wp->prev_lost = PJ_FALSE; } else { - status = pjmedia_wsola_generate(wp->wsola, (short*)frame->buf); - wp->prev_lost = PJ_TRUE; + status = pjmedia_wsola_generate(wp->wsola, (short*)frame->buf); + wp->prev_lost = PJ_TRUE; } return status; @@ -1049,12 +1048,12 @@ static pj_status_t wsola_plc_on_destroy(struct pjmedia_port *this_port) } static pjmedia_port* create_wsola_plc(unsigned loss_pct, - pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + pj_pool_t *pool, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { struct wsola_plc_port *wp; pj_str_t name = pj_str("wsola"); @@ -1069,20 +1068,20 @@ static pjmedia_port* create_wsola_plc(unsigned loss_pct, wp->base.get_frame = &wsola_plc_get_frame; wp->base.on_destroy = &wsola_plc_on_destroy; pjmedia_port_info_init(&wp->base.info, &name, 0x4123, clock_rate, - channel_count, 16, samples_per_frame); + channel_count, 16, samples_per_frame); if (loss_pct == 0) - opt |= PJMEDIA_WSOLA_NO_PLC; + opt |= PJMEDIA_WSOLA_NO_PLC; status = pjmedia_wsola_create(pool, clock_rate, samples_per_frame, - channel_count, opt, &wp->wsola); + channel_count, opt, &wp->wsola); if (status != PJ_SUCCESS) - return NULL; + return NULL; wp->gen_port = create_gen_port(pool, clock_rate, channel_count, - samples_per_frame, 100); + samples_per_frame, 100); if (wp->gen_port == NULL) - return NULL; + return NULL; return &wp->base; } @@ -1090,75 +1089,75 @@ static pjmedia_port* create_wsola_plc(unsigned loss_pct, /* WSOLA PLC with 0% packet loss */ static pjmedia_port* wsola_plc_0( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_wsola_plc(0, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* WSOLA PLC with 2% packet loss */ static pjmedia_port* wsola_plc_2( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_wsola_plc(2, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* WSOLA PLC with 5% packet loss */ static pjmedia_port* wsola_plc_5( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_wsola_plc(5, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* WSOLA PLC with 10% packet loss */ static pjmedia_port* wsola_plc_10(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_wsola_plc(10, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* WSOLA PLC with 20% packet loss */ static pjmedia_port* wsola_plc_20(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_wsola_plc(20, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* WSOLA PLC with 50% packet loss */ static pjmedia_port* wsola_plc_50(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_wsola_plc(50, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } @@ -1168,46 +1167,46 @@ static pjmedia_port* wsola_plc_50(pj_pool_t *pool, enum { CIRC_BUF_FRAME_CNT = 4 }; struct wsola_discard_port { - pjmedia_port base; - pjmedia_port *gen_port; - pjmedia_wsola *wsola; - pjmedia_circ_buf *circbuf; - unsigned discard_pct; + pjmedia_port base; + pjmedia_port *gen_port; + pjmedia_wsola *wsola; + pjmedia_circ_buf *circbuf; + unsigned discard_pct; }; static pj_status_t wsola_discard_get_frame(struct pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct wsola_discard_port *wp = (struct wsola_discard_port*)this_port; pj_status_t status = PJ_SUCCESS; while (pjmedia_circ_buf_get_len(wp->circbuf) < - PJMEDIA_PIA_SPF(&wp->base.info) * (CIRC_BUF_FRAME_CNT-1)) + PJMEDIA_PIA_SPF(&wp->base.info) * (CIRC_BUF_FRAME_CNT-1)) { - status = pjmedia_port_get_frame(wp->gen_port, frame); - pj_assert(status==PJ_SUCCESS); + status = pjmedia_port_get_frame(wp->gen_port, frame); + pj_assert(status==PJ_SUCCESS); - status = pjmedia_circ_buf_write(wp->circbuf, (short*)frame->buf, - PJMEDIA_PIA_SPF(&wp->base.info)); - pj_assert(status==PJ_SUCCESS); + status = pjmedia_circ_buf_write(wp->circbuf, (short*)frame->buf, + PJMEDIA_PIA_SPF(&wp->base.info)); + pj_assert(status==PJ_SUCCESS); } if ((pj_rand() % 100) < (int)wp->discard_pct) { - pj_int16_t *reg1, *reg2; - unsigned reg1_len, reg2_len; - unsigned del_cnt; + pj_int16_t *reg1, *reg2; + unsigned reg1_len, reg2_len; + unsigned del_cnt; - pjmedia_circ_buf_get_read_regions(wp->circbuf, ®1, ®1_len, - ®2, ®2_len); + pjmedia_circ_buf_get_read_regions(wp->circbuf, ®1, ®1_len, + ®2, ®2_len); - del_cnt = PJMEDIA_PIA_SPF(&wp->base.info); - status = pjmedia_wsola_discard(wp->wsola, reg1, reg1_len, reg2, - reg2_len, &del_cnt); - pj_assert(status==PJ_SUCCESS); + del_cnt = PJMEDIA_PIA_SPF(&wp->base.info); + status = pjmedia_wsola_discard(wp->wsola, reg1, reg1_len, reg2, + reg2_len, &del_cnt); + pj_assert(status==PJ_SUCCESS); - status = pjmedia_circ_buf_adv_read_ptr(wp->circbuf, del_cnt); - pj_assert(status==PJ_SUCCESS); + status = pjmedia_circ_buf_adv_read_ptr(wp->circbuf, del_cnt); + pj_assert(status==PJ_SUCCESS); } return status; @@ -1223,12 +1222,12 @@ static pj_status_t wsola_discard_on_destroy(struct pjmedia_port *this_port) static pjmedia_port* create_wsola_discard(unsigned discard_pct, - pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + pj_pool_t *pool, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { struct wsola_discard_port *wp; pj_str_t name = pj_str("wsola"); @@ -1243,40 +1242,40 @@ static pjmedia_port* create_wsola_discard(unsigned discard_pct, wp->base.get_frame = &wsola_discard_get_frame; wp->base.on_destroy = &wsola_discard_on_destroy; pjmedia_port_info_init(&wp->base.info, &name, 0x4123, clock_rate, - channel_count, 16, samples_per_frame); + channel_count, 16, samples_per_frame); if (discard_pct == 0) - opt |= PJMEDIA_WSOLA_NO_DISCARD; + opt |= PJMEDIA_WSOLA_NO_DISCARD; status = pjmedia_wsola_create(pool, clock_rate, samples_per_frame, - channel_count, opt, &wp->wsola); + channel_count, opt, &wp->wsola); if (status != PJ_SUCCESS) - return NULL; + return NULL; wp->gen_port = create_gen_port(pool, clock_rate, channel_count, - samples_per_frame, 100); + samples_per_frame, 100); if (wp->gen_port == NULL) - return NULL; + return NULL; status = pjmedia_circ_buf_create(pool, samples_per_frame * CIRC_BUF_FRAME_CNT, - &wp->circbuf); + &wp->circbuf); if (status != PJ_SUCCESS) - return NULL; + return NULL; /* fill up the circbuf */ for (i=0; i= samples_per_frame); - frm.buf = pcm; - frm.size = samples_per_frame * 2; + pj_assert(PJ_ARRAY_SIZE(pcm) >= samples_per_frame); + frm.buf = pcm; + frm.size = samples_per_frame * 2; - status = pjmedia_port_get_frame(wp->gen_port, &frm); - pj_assert(status==PJ_SUCCESS); + status = pjmedia_port_get_frame(wp->gen_port, &frm); + pj_assert(status==PJ_SUCCESS); - status = pjmedia_circ_buf_write(wp->circbuf, pcm, samples_per_frame); - pj_assert(status==PJ_SUCCESS); + status = pjmedia_circ_buf_write(wp->circbuf, pcm, samples_per_frame); + pj_assert(status==PJ_SUCCESS); } return &wp->base; @@ -1285,62 +1284,62 @@ static pjmedia_port* create_wsola_discard(unsigned discard_pct, /* WSOLA with 2% discard rate */ static pjmedia_port* wsola_discard_2( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_wsola_discard(2, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* WSOLA with 5% discard rate */ static pjmedia_port* wsola_discard_5( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_wsola_discard(5, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* WSOLA with 10% discard rate */ static pjmedia_port* wsola_discard_10(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_wsola_discard(10, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* WSOLA with 20% discard rate */ static pjmedia_port* wsola_discard_20(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_wsola_discard(20, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* WSOLA with 50% discard rate */ static pjmedia_port* wsola_discard_50(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_wsola_discard(50, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } @@ -1348,12 +1347,12 @@ static pjmedia_port* wsola_discard_50(pj_pool_t *pool, /***************************************************************************/ static pjmedia_port* ec_create(unsigned ec_tail_msec, - pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + pj_pool_t *pool, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { pjmedia_port *gen_port, *ec_port; pj_status_t status; @@ -1361,267 +1360,267 @@ static pjmedia_port* ec_create(unsigned ec_tail_msec, PJ_UNUSED_ARG(te); gen_port = create_gen_port(pool, clock_rate, channel_count, - samples_per_frame, 100); + samples_per_frame, 100); if (gen_port == NULL) - return NULL; + return NULL; status = pjmedia_echo_port_create(pool, gen_port, ec_tail_msec, 0, - flags, &ec_port); + flags, &ec_port); if (status != PJ_SUCCESS) - return NULL; + return NULL; return ec_port; } /* EC with 100ms tail length */ static pjmedia_port* ec_create_100(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = 0; return ec_create(100, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* EC with 128ms tail length */ static pjmedia_port* ec_create_128(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = 0; return ec_create(128, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* EC with 200ms tail length */ static pjmedia_port* ec_create_200(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = 0; return ec_create(200, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* EC with 256ms tail length */ static pjmedia_port* ec_create_256(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = 0; return ec_create(256, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* EC with 400ms tail length */ static pjmedia_port* ec_create_400(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = 0; return ec_create(400, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* EC with 500ms tail length */ static pjmedia_port* ec_create_500(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = 0; return ec_create(500, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* EC with 512ms tail length */ static pjmedia_port* ec_create_512(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = 0; return ec_create(512, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* EC with 600ms tail length */ static pjmedia_port* ec_create_600(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = 0; return ec_create(600, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* EC with 800ms tail length */ static pjmedia_port* ec_create_800(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = 0; return ec_create(800, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* Echo suppressor with 100ms tail length */ static pjmedia_port* es_create_100(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = PJMEDIA_ECHO_SIMPLE; return ec_create(100, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* Echo suppressor with 128ms tail length */ static pjmedia_port* es_create_128(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = PJMEDIA_ECHO_SIMPLE; return ec_create(128, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* Echo suppressor with 200ms tail length */ static pjmedia_port* es_create_200(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = PJMEDIA_ECHO_SIMPLE; return ec_create(200, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* Echo suppressor with 256ms tail length */ static pjmedia_port* es_create_256(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = PJMEDIA_ECHO_SIMPLE; return ec_create(256, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* Echo suppressor with 400ms tail length */ static pjmedia_port* es_create_400(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = PJMEDIA_ECHO_SIMPLE; return ec_create(400, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* Echo suppressor with 500ms tail length */ static pjmedia_port* es_create_500(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = PJMEDIA_ECHO_SIMPLE; return ec_create(500, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* Echo suppressor with 512ms tail length */ static pjmedia_port* es_create_512(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = PJMEDIA_ECHO_SIMPLE; return ec_create(512, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* Echo suppressor with 600ms tail length */ static pjmedia_port* es_create_600(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = PJMEDIA_ECHO_SIMPLE; return ec_create(600, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /* Echo suppressor with 800ms tail length */ static pjmedia_port* es_create_800(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { flags = PJMEDIA_ECHO_SIMPLE; return ec_create(800, pool, clock_rate, channel_count, samples_per_frame, - flags, te); + flags, te); } /***************************************************************************/ /* Tone generator, single frequency */ static pjmedia_port* create_tonegen(unsigned freq1, - unsigned freq2, - pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned freq2, + pj_pool_t *pool, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { pjmedia_port *tonegen; pjmedia_tone_desc tones[2]; @@ -1631,10 +1630,10 @@ static pjmedia_port* create_tonegen(unsigned freq1, PJ_UNUSED_ARG(te); status = pjmedia_tonegen_create(pool, clock_rate, channel_count, - samples_per_frame, 16, - PJMEDIA_TONEGEN_LOOP, &tonegen); + samples_per_frame, 16, + PJMEDIA_TONEGEN_LOOP, &tonegen); if (status != PJ_SUCCESS) - return NULL; + return NULL; pj_bzero(tones, sizeof(tones)); tones[0].freq1 = (short)freq1; @@ -1647,35 +1646,35 @@ static pjmedia_port* create_tonegen(unsigned freq1, tones[1].off_msec = 100; status = pjmedia_tonegen_play(tonegen, PJ_ARRAY_SIZE(tones), tones, - PJMEDIA_TONEGEN_LOOP); + PJMEDIA_TONEGEN_LOOP); if (status != PJ_SUCCESS) - return NULL; + return NULL; return tonegen; } /* Tonegen with single frequency */ static pjmedia_port* create_tonegen1(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_tonegen(400, 0, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* Tonegen with dual frequency */ static pjmedia_port* create_tonegen2(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_tonegen(400, 440, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } @@ -1685,11 +1684,11 @@ static pjmedia_port* create_tonegen2(pj_pool_t *pool, struct stream_port { - pjmedia_port base; - pj_status_t (*codec_deinit)(); - pjmedia_endpt *endpt; - pjmedia_stream *stream; - pjmedia_transport *transport; + pjmedia_port base; + pj_status_t (*codec_deinit)(); + pjmedia_endpt *endpt; + pjmedia_stream *stream; + pjmedia_transport *transport; }; @@ -1706,17 +1705,17 @@ static void stream_port_custom_deinit(struct test_entry *te) #if HAS_AUDIO_CODECS static pjmedia_port* create_stream( pj_pool_t *pool, - const char *codec, - pj_status_t (*codec_init)(pjmedia_endpt*), - pj_status_t (*codec_deinit)(), - pj_bool_t srtp_enabled, - pj_bool_t srtp_80, - pj_bool_t srtp_auth, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + const char *codec, + pj_status_t (*codec_init)(pjmedia_endpt*), + pj_status_t (*codec_deinit)(), + pj_bool_t srtp_enabled, + pj_bool_t srtp_80, + pj_bool_t srtp_auth, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { struct stream_port *sp; pj_str_t codec_id; @@ -1732,7 +1731,7 @@ static pjmedia_port* create_stream( pj_pool_t *pool, codec_id = pj_str((char*)codec); sp = PJ_POOL_ZALLOC_T(pool, struct stream_port); pjmedia_port_info_init(&sp->base.info, &codec_id, 0x123456, clock_rate, - channel_count, 16, samples_per_frame); + channel_count, 16, samples_per_frame); te->pdata[0] = sp; te->custom_deinit = &stream_port_custom_deinit; @@ -1740,24 +1739,24 @@ static pjmedia_port* create_stream( pj_pool_t *pool, status = pjmedia_endpt_create(mem, NULL, 0, &sp->endpt); if (status != PJ_SUCCESS) - return NULL; + return NULL; status = codec_init(sp->endpt); if (status != PJ_SUCCESS) - return NULL; + return NULL; count = 1; status = pjmedia_codec_mgr_find_codecs_by_id(pjmedia_endpt_get_codec_mgr(sp->endpt), - &codec_id, &count, ci, NULL); + &codec_id, &count, ci, NULL); if (status != PJ_SUCCESS) - return NULL; + return NULL; status = pjmedia_codec_mgr_get_default_param(pjmedia_endpt_get_codec_mgr(sp->endpt), - ci[0], &codec_param); + ci[0], &codec_param); if (status != PJ_SUCCESS) - return NULL; + return NULL; /* Create stream info */ pj_bzero(&si, sizeof(si)); @@ -1778,57 +1777,57 @@ static pjmedia_port* create_stream( pj_pool_t *pool, /* Create loop transport */ status = pjmedia_transport_loop_create(sp->endpt, &sp->transport); if (status != PJ_SUCCESS) - return NULL; + return NULL; #if PJMEDIA_HAS_SRTP if (srtp_enabled) { - pjmedia_srtp_setting opt; - pjmedia_srtp_crypto crypto; - pjmedia_transport *srtp; - - pjmedia_srtp_setting_default(&opt); - opt.close_member_tp = PJ_TRUE; - opt.use = PJMEDIA_SRTP_MANDATORY; - - status = pjmedia_transport_srtp_create(sp->endpt, sp->transport, &opt, - &srtp); - if (status != PJ_SUCCESS) - return NULL; - - pj_bzero(&crypto, sizeof(crypto)); - if (srtp_80) { - crypto.key = pj_str("123456789012345678901234567890"); - crypto.name = pj_str("AES_CM_128_HMAC_SHA1_80"); - } else { - crypto.key = pj_str("123456789012345678901234567890"); - crypto.name = pj_str("AES_CM_128_HMAC_SHA1_32"); - } - - if (!srtp_auth) - crypto.flags = PJMEDIA_SRTP_NO_AUTHENTICATION; - - status = pjmedia_transport_srtp_start(srtp, &crypto, &crypto); - if (status != PJ_SUCCESS) - return NULL; - - sp->transport = srtp; + pjmedia_srtp_setting opt; + pjmedia_srtp_crypto crypto; + pjmedia_transport *srtp; + + pjmedia_srtp_setting_default(&opt); + opt.close_member_tp = PJ_TRUE; + opt.use = PJMEDIA_SRTP_MANDATORY; + + status = pjmedia_transport_srtp_create(sp->endpt, sp->transport, &opt, + &srtp); + if (status != PJ_SUCCESS) + return NULL; + + pj_bzero(&crypto, sizeof(crypto)); + if (srtp_80) { + crypto.key = pj_str("123456789012345678901234567890"); + crypto.name = pj_str("AES_CM_128_HMAC_SHA1_80"); + } else { + crypto.key = pj_str("123456789012345678901234567890"); + crypto.name = pj_str("AES_CM_128_HMAC_SHA1_32"); + } + + if (!srtp_auth) + crypto.flags = PJMEDIA_SRTP_NO_AUTHENTICATION; + + status = pjmedia_transport_srtp_start(srtp, &crypto, &crypto); + if (status != PJ_SUCCESS) + return NULL; + + sp->transport = srtp; } #endif /* Create stream */ status = pjmedia_stream_create(sp->endpt, pool, &si, sp->transport, NULL, - &sp->stream); + &sp->stream); if (status != PJ_SUCCESS) - return NULL; + return NULL; /* Start stream */ status = pjmedia_stream_start(sp->stream); if (status != PJ_SUCCESS) - return NULL; + return NULL; status = pjmedia_stream_get_port(sp->stream, &port); if (status != PJ_SUCCESS) - return NULL; + return NULL; return port; } @@ -1837,205 +1836,205 @@ static pjmedia_port* create_stream( pj_pool_t *pool, #if PJMEDIA_HAS_G711_CODEC /* G.711 stream, no SRTP */ static pjmedia_port* create_stream_pcmu( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "pcmu", &pjmedia_codec_g711_init, - &pjmedia_codec_g711_deinit, - PJ_FALSE, PJ_FALSE, PJ_FALSE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_g711_deinit, + PJ_FALSE, PJ_FALSE, PJ_FALSE, + clock_rate, channel_count, + samples_per_frame, flags, te); } /* G.711 stream, SRTP 32bit key no auth */ static pjmedia_port* create_stream_pcmu_srtp32_no_auth( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "pcmu", &pjmedia_codec_g711_init, - &pjmedia_codec_g711_deinit, - PJ_TRUE, PJ_FALSE, PJ_FALSE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_g711_deinit, + PJ_TRUE, PJ_FALSE, PJ_FALSE, + clock_rate, channel_count, + samples_per_frame, flags, te); } /* G.711 stream, SRTP 32bit key with auth */ static pjmedia_port* create_stream_pcmu_srtp32_with_auth(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "pcmu", &pjmedia_codec_g711_init, - &pjmedia_codec_g711_deinit, - PJ_TRUE, PJ_FALSE, PJ_TRUE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_g711_deinit, + PJ_TRUE, PJ_FALSE, PJ_TRUE, + clock_rate, channel_count, + samples_per_frame, flags, te); } /* G.711 stream, SRTP 80bit key no auth */ static pjmedia_port* create_stream_pcmu_srtp80_no_auth( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "pcmu", &pjmedia_codec_g711_init, - &pjmedia_codec_g711_deinit, - PJ_TRUE, PJ_TRUE, PJ_FALSE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_g711_deinit, + PJ_TRUE, PJ_TRUE, PJ_FALSE, + clock_rate, channel_count, + samples_per_frame, flags, te); } /* G.711 stream, SRTP 80bit key with auth */ static pjmedia_port* create_stream_pcmu_srtp80_with_auth(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "pcmu", &pjmedia_codec_g711_init, - &pjmedia_codec_g711_deinit, - PJ_TRUE, PJ_TRUE, PJ_TRUE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_g711_deinit, + PJ_TRUE, PJ_TRUE, PJ_TRUE, + clock_rate, channel_count, + samples_per_frame, flags, te); } #endif #if PJMEDIA_HAS_GSM_CODEC /* GSM stream */ static pjmedia_port* create_stream_gsm( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "gsm", &pjmedia_codec_gsm_init, - &pjmedia_codec_gsm_deinit, - PJ_FALSE, PJ_FALSE, PJ_FALSE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_gsm_deinit, + PJ_FALSE, PJ_FALSE, PJ_FALSE, + clock_rate, channel_count, + samples_per_frame, flags, te); } /* GSM stream, SRTP 32bit, no auth */ static pjmedia_port* create_stream_gsm_srtp32_no_auth(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "gsm", &pjmedia_codec_gsm_init, - &pjmedia_codec_gsm_deinit, - PJ_TRUE, PJ_FALSE, PJ_FALSE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_gsm_deinit, + PJ_TRUE, PJ_FALSE, PJ_FALSE, + clock_rate, channel_count, + samples_per_frame, flags, te); } /* GSM stream, SRTP 32bit, with auth */ static pjmedia_port* create_stream_gsm_srtp32_with_auth(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "gsm", &pjmedia_codec_gsm_init, - &pjmedia_codec_gsm_deinit, - PJ_TRUE, PJ_FALSE, PJ_TRUE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_gsm_deinit, + PJ_TRUE, PJ_FALSE, PJ_TRUE, + clock_rate, channel_count, + samples_per_frame, flags, te); } /* GSM stream, SRTP 80bit, no auth */ static pjmedia_port* create_stream_gsm_srtp80_no_auth(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "gsm", &pjmedia_codec_gsm_init, - &pjmedia_codec_gsm_deinit, - PJ_TRUE, PJ_TRUE, PJ_FALSE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_gsm_deinit, + PJ_TRUE, PJ_TRUE, PJ_FALSE, + clock_rate, channel_count, + samples_per_frame, flags, te); } /* GSM stream, SRTP 80bit, with auth */ static pjmedia_port* create_stream_gsm_srtp80_with_auth(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "gsm", &pjmedia_codec_gsm_init, - &pjmedia_codec_gsm_deinit, - PJ_TRUE, PJ_TRUE, PJ_TRUE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_gsm_deinit, + PJ_TRUE, PJ_TRUE, PJ_TRUE, + clock_rate, channel_count, + samples_per_frame, flags, te); } #endif #if PJMEDIA_HAS_G722_CODEC /* G722 stream */ static pjmedia_port* create_stream_g722( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "g722", &pjmedia_codec_g722_init, - &pjmedia_codec_g722_deinit, - PJ_FALSE, PJ_FALSE, PJ_FALSE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_g722_deinit, + PJ_FALSE, PJ_FALSE, PJ_FALSE, + clock_rate, channel_count, + samples_per_frame, flags, te); } #endif #if PJMEDIA_HAS_G7221_CODEC /* G722.1 stream */ static pjmedia_port* create_stream_g7221( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "g7221/16000", &pjmedia_codec_g7221_init, - &pjmedia_codec_g7221_deinit, - PJ_FALSE, PJ_FALSE, PJ_FALSE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_g7221_deinit, + PJ_FALSE, PJ_FALSE, PJ_FALSE, + clock_rate, channel_count, + samples_per_frame, flags, te); } /* G722.1 Annex C stream */ static pjmedia_port* create_stream_g7221c( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_stream(pool, "g7221/32000", &pjmedia_codec_g7221_init, - &pjmedia_codec_g7221_deinit, - PJ_FALSE, PJ_FALSE, PJ_FALSE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_g7221_deinit, + PJ_FALSE, PJ_FALSE, PJ_FALSE, + clock_rate, channel_count, + samples_per_frame, flags, te); } -#endif /* PJMEDIA_HAS_G7221_CODEC */ +#endif /* PJMEDIA_HAS_G7221_CODEC */ /* AMR-NB stream */ #if PJMEDIA_HAS_OPENCORE_AMRNB_CODEC @@ -2047,12 +2046,12 @@ static pjmedia_port* create_stream_amr( pj_pool_t *pool, struct test_entry *te) { return create_stream(pool, "AMR/8000", &pjmedia_codec_opencore_amrnb_init, - &pjmedia_codec_opencore_amrnb_deinit, - PJ_FALSE, PJ_FALSE, PJ_FALSE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_opencore_amrnb_deinit, + PJ_FALSE, PJ_FALSE, PJ_FALSE, + clock_rate, channel_count, + samples_per_frame, flags, te); } -#endif /* PJMEDIA_HAS_OPENCORE_AMRNB_CODEC */ +#endif /* PJMEDIA_HAS_OPENCORE_AMRNB_CODEC */ /* AMR-WB stream */ #if PJMEDIA_HAS_OPENCORE_AMRWB_CODEC @@ -2065,27 +2064,27 @@ static pjmedia_port* create_stream_amrwb( pj_pool_t *pool, { return create_stream(pool, "AMR/16000", &pjmedia_codec_opencore_amr_init_default, - &pjmedia_codec_opencore_amr_deinit, - PJ_FALSE, PJ_FALSE, PJ_FALSE, - clock_rate, channel_count, - samples_per_frame, flags, te); + &pjmedia_codec_opencore_amr_deinit, + PJ_FALSE, PJ_FALSE, PJ_FALSE, + clock_rate, channel_count, + samples_per_frame, flags, te); } -#endif /* PJMEDIA_HAS_OPENCORE_AMRWB_CODEC */ +#endif /* PJMEDIA_HAS_OPENCORE_AMRWB_CODEC */ /***************************************************************************/ /* Delay buffer */ enum {DELAY_BUF_MAX_DELAY = 80}; struct delaybuf_port { - pjmedia_port base; + pjmedia_port base; pjmedia_delay_buf *delaybuf; - pjmedia_port *gen_port; - int drift_pct; + pjmedia_port *gen_port; + int drift_pct; }; static pj_status_t delaybuf_get_frame(struct pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct delaybuf_port *dp = (struct delaybuf_port*)this_port; pj_status_t status; @@ -2095,20 +2094,20 @@ static pj_status_t delaybuf_get_frame(struct pjmedia_port *this_port, /* Additional GET when drift_pct is negative */ if (dp->drift_pct < 0) { - int rnd; - rnd = pj_rand() % 100; + int rnd; + rnd = pj_rand() % 100; - if (rnd < -dp->drift_pct) { - status = pjmedia_delay_buf_get(dp->delaybuf, (pj_int16_t*)frame->buf); - pj_assert(status == PJ_SUCCESS); - } + if (rnd < -dp->drift_pct) { + status = pjmedia_delay_buf_get(dp->delaybuf, (pj_int16_t*)frame->buf); + pj_assert(status == PJ_SUCCESS); + } } return status; } static pj_status_t delaybuf_put_frame(struct pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { struct delaybuf_port *dp = (struct delaybuf_port*)this_port; pj_status_t status; @@ -2121,15 +2120,15 @@ static pj_status_t delaybuf_put_frame(struct pjmedia_port *this_port, /* Additional PUT when drift_pct is possitive */ if (dp->drift_pct > 0) { - int rnd; - rnd = pj_rand() % 100; - - if (rnd < dp->drift_pct) { - status = pjmedia_port_get_frame(dp->gen_port, &f); - pj_assert(status == PJ_SUCCESS); - status = pjmedia_delay_buf_put(dp->delaybuf, (pj_int16_t*)f.buf); - pj_assert(status == PJ_SUCCESS); - } + int rnd; + rnd = pj_rand() % 100; + + if (rnd < dp->drift_pct) { + status = pjmedia_port_get_frame(dp->gen_port, &f); + pj_assert(status == PJ_SUCCESS); + status = pjmedia_delay_buf_put(dp->delaybuf, (pj_int16_t*)f.buf); + pj_assert(status == PJ_SUCCESS); + } } return status; @@ -2144,12 +2143,12 @@ static pj_status_t delaybuf_on_destroy(struct pjmedia_port *this_port) } static pjmedia_port* create_delaybuf(int drift_pct, - pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + pj_pool_t *pool, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { struct delaybuf_port *dp; pj_str_t name = pj_str("delaybuf"); @@ -2165,19 +2164,19 @@ static pjmedia_port* create_delaybuf(int drift_pct, dp->base.put_frame = &delaybuf_put_frame; dp->base.on_destroy = &delaybuf_on_destroy; pjmedia_port_info_init(&dp->base.info, &name, 0x5678, clock_rate, - channel_count, 16, samples_per_frame); + channel_count, 16, samples_per_frame); status = pjmedia_delay_buf_create(pool, "mips_test", clock_rate, - samples_per_frame, channel_count, - DELAY_BUF_MAX_DELAY, - opt, &dp->delaybuf); + samples_per_frame, channel_count, + DELAY_BUF_MAX_DELAY, + opt, &dp->delaybuf); if (status != PJ_SUCCESS) - return NULL; + return NULL; dp->gen_port = create_gen_port(pool, clock_rate, channel_count, - samples_per_frame, 100); + samples_per_frame, 100); if (dp->gen_port == NULL) - return NULL; + return NULL; return &dp->base; } @@ -2185,111 +2184,111 @@ static pjmedia_port* create_delaybuf(int drift_pct, /* Delay buffer without drift */ static pjmedia_port* delaybuf_0( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_delaybuf(0, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* Delay buffer with 2% drift */ static pjmedia_port* delaybuf_p2( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_delaybuf(2, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* Delay buffer with 5% drift */ static pjmedia_port* delaybuf_p5( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_delaybuf(5, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* Delay buffer with 10% drift */ static pjmedia_port* delaybuf_p10(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_delaybuf(10, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* Delay buffer with 20% drift */ static pjmedia_port* delaybuf_p20(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_delaybuf(20, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* Delay buffer with -2% drift */ static pjmedia_port* delaybuf_n2( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_delaybuf(-2, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* Delay buffer with -5% drift */ static pjmedia_port* delaybuf_n5( pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_delaybuf(-5, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* Delay buffer with -10% drift */ static pjmedia_port* delaybuf_n10(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_delaybuf(-10, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } /* Delay buffer with -20% drift */ static pjmedia_port* delaybuf_n20(pj_pool_t *pool, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned flags, - struct test_entry *te) + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned flags, + struct test_entry *te) { return create_delaybuf(-20, pool, clock_rate, channel_count, - samples_per_frame, flags, te); + samples_per_frame, flags, te); } @@ -2310,71 +2309,71 @@ static pj_timestamp run_entry(unsigned clock_rate, struct test_entry *e) pool = pj_pool_create(mem, "pool", 1024, 1024, NULL); port = e->init(pool, clock_rate, 1, samples_per_frame, 0, e); if (port == NULL) { - t0.u64 = 0; - pj_pool_release(pool); - PJ_LOG(1,(THIS_FILE, " init error")); - return t0; + t0.u64 = 0; + pj_pool_release(pool); + PJ_LOG(1,(THIS_FILE, " init error")); + return t0; } /* Port may decide to use different ptime (e.g. iLBC) */ samples_per_frame = PJMEDIA_PIA_SPF(&port->info); gen_port = create_gen_port(pool, clock_rate, 1, - samples_per_frame, 100); + samples_per_frame, 100); if (gen_port == NULL) { - t0.u64 = 0; - pj_pool_release(pool); - return t0; + t0.u64 = 0; + pj_pool_release(pool); + return t0; } pj_get_timestamp(&t0); for (j=0; jvalid_op==OP_GET_PUT) { - frm.buf = (void*)pcm; - frm.size = samples_per_frame * 2; - frm.type = PJMEDIA_FRAME_TYPE_NONE; + if (e->valid_op==OP_GET_PUT) { + frm.buf = (void*)pcm; + frm.size = samples_per_frame * 2; + frm.type = PJMEDIA_FRAME_TYPE_NONE; - status = pjmedia_port_get_frame(port, &frm); - pj_assert(status == PJ_SUCCESS); + status = pjmedia_port_get_frame(port, &frm); + pj_assert(status == PJ_SUCCESS); - status = pjmedia_port_put_frame(port, &frm); - pj_assert(status == PJ_SUCCESS); + status = pjmedia_port_put_frame(port, &frm); + pj_assert(status == PJ_SUCCESS); - } else if (e->valid_op == OP_GET) { - frm.buf = (void*)pcm; - frm.size = samples_per_frame * 2; - frm.type = PJMEDIA_FRAME_TYPE_NONE; + } else if (e->valid_op == OP_GET) { + frm.buf = (void*)pcm; + frm.size = samples_per_frame * 2; + frm.type = PJMEDIA_FRAME_TYPE_NONE; - status = pjmedia_port_get_frame(port, &frm); - pj_assert(status == PJ_SUCCESS); + status = pjmedia_port_get_frame(port, &frm); + pj_assert(status == PJ_SUCCESS); - } else if (e->valid_op == OP_PUT) { - frm.buf = (void*)pcm; - frm.size = samples_per_frame * 2; - frm.type = PJMEDIA_FRAME_TYPE_NONE; + } else if (e->valid_op == OP_PUT) { + frm.buf = (void*)pcm; + frm.size = samples_per_frame * 2; + frm.type = PJMEDIA_FRAME_TYPE_NONE; - status = pjmedia_port_get_frame(gen_port, &frm); - pj_assert(status == PJ_SUCCESS); + status = pjmedia_port_get_frame(gen_port, &frm); + pj_assert(status == PJ_SUCCESS); - status = pjmedia_port_put_frame(port, &frm); - pj_assert(status == PJ_SUCCESS); + status = pjmedia_port_put_frame(port, &frm); + pj_assert(status == PJ_SUCCESS); - } else if (e->valid_op == OP_PUT_GET) { - frm.buf = (void*)pcm; - frm.size = samples_per_frame * 2; - frm.type = PJMEDIA_FRAME_TYPE_NONE; + } else if (e->valid_op == OP_PUT_GET) { + frm.buf = (void*)pcm; + frm.size = samples_per_frame * 2; + frm.type = PJMEDIA_FRAME_TYPE_NONE; - status = pjmedia_port_get_frame(gen_port, &frm); - pj_assert(status == PJ_SUCCESS); + status = pjmedia_port_get_frame(gen_port, &frm); + pj_assert(status == PJ_SUCCESS); - status = pjmedia_port_put_frame(port, &frm); - pj_assert(status == PJ_SUCCESS); + status = pjmedia_port_put_frame(port, &frm); + pj_assert(status == PJ_SUCCESS); - status = pjmedia_port_get_frame(port, &frm); - pj_assert(status == PJ_SUCCESS); - } + status = pjmedia_port_get_frame(port, &frm); + pj_assert(status == PJ_SUCCESS); + } } PJ_UNUSED_ARG(status); pj_get_timestamp(&t1); @@ -2382,7 +2381,7 @@ static pj_timestamp run_entry(unsigned clock_rate, struct test_entry *e) pj_sub_timestamp(&t1, &t0); if (e->custom_deinit) - e->custom_deinit(e); + e->custom_deinit(e); pjmedia_port_destroy(port); pj_pool_release(pool); @@ -2394,111 +2393,111 @@ static pj_timestamp run_entry(unsigned clock_rate, struct test_entry *e) int mips_test(void) { struct test_entry entries[] = { - { "get from memplayer", OP_GET, K8|K16, &gen_port_test_init}, - { "conference bridge with 1 call", OP_GET_PUT, K8|K16, &conf1_test_init}, - { "conference bridge with 2 calls", OP_GET_PUT, K8|K16, &conf2_test_init}, - { "conference bridge with 4 calls", OP_GET_PUT, K8|K16, &conf4_test_init}, - { "conference bridge with 8 calls", OP_GET_PUT, K8|K16, &conf8_test_init}, - { "conference bridge with 16 calls", OP_GET_PUT, K8|K16, &conf16_test_init}, - { "upsample+downsample - linear", OP_GET, K8|K16, &linear_resample}, - { "upsample+downsample - small filter", OP_GET, K8|K16, &small_filt_resample}, - { "upsample+downsample - large filter", OP_GET, K8|K16, &large_filt_resample}, - { "WSOLA PLC - 0% loss", OP_GET, K8|K16, &wsola_plc_0}, - { "WSOLA PLC - 2% loss", OP_GET, K8|K16, &wsola_plc_2}, - { "WSOLA PLC - 5% loss", OP_GET, K8|K16, &wsola_plc_5}, - { "WSOLA PLC - 10% loss", OP_GET, K8|K16, &wsola_plc_10}, - { "WSOLA PLC - 20% loss", OP_GET, K8|K16, &wsola_plc_20}, - { "WSOLA PLC - 50% loss", OP_GET, K8|K16, &wsola_plc_50}, - { "WSOLA discard 2% excess", OP_GET, K8|K16, &wsola_discard_2}, - { "WSOLA discard 5% excess", OP_GET, K8|K16, &wsola_discard_5}, - { "WSOLA discard 10% excess", OP_GET, K8|K16, &wsola_discard_10}, - { "WSOLA discard 20% excess", OP_GET, K8|K16, &wsola_discard_20}, - { "WSOLA discard 50% excess", OP_GET, K8|K16, &wsola_discard_50}, - { "Delay buffer", OP_GET_PUT, K8|K16, &delaybuf_0}, - { "Delay buffer - drift -2%", OP_GET_PUT, K8|K16, &delaybuf_n2}, - { "Delay buffer - drift -5%", OP_GET_PUT, K8|K16, &delaybuf_n5}, - { "Delay buffer - drift -10%", OP_GET_PUT, K8|K16, &delaybuf_n10}, - { "Delay buffer - drift -20%", OP_GET_PUT, K8|K16, &delaybuf_n20}, - { "Delay buffer - drift +2%", OP_GET_PUT, K8|K16, &delaybuf_p2}, - { "Delay buffer - drift +5%", OP_GET_PUT, K8|K16, &delaybuf_p5}, - { "Delay buffer - drift +10%", OP_GET_PUT, K8|K16, &delaybuf_p10}, - { "Delay buffer - drift +20%", OP_GET_PUT, K8|K16, &delaybuf_p20}, - { "echo canceller 100ms tail len", OP_GET_PUT, K8|K16, &ec_create_100}, - { "echo canceller 128ms tail len", OP_GET_PUT, K8|K16, &ec_create_128}, - { "echo canceller 200ms tail len", OP_GET_PUT, K8|K16, &ec_create_200}, - { "echo canceller 256ms tail len", OP_GET_PUT, K8|K16, &ec_create_256}, - { "echo canceller 400ms tail len", OP_GET_PUT, K8|K16, &ec_create_400}, - { "echo canceller 500ms tail len", OP_GET_PUT, K8|K16, &ec_create_500}, - { "echo canceller 512ms tail len", OP_GET_PUT, K8|K16, &ec_create_512}, - { "echo canceller 600ms tail len", OP_GET_PUT, K8|K16, &ec_create_600}, - { "echo canceller 800ms tail len", OP_GET_PUT, K8|K16, &ec_create_800}, - { "echo suppressor 100ms tail len", OP_GET_PUT, K8|K16, &es_create_100}, - { "echo suppressor 128ms tail len", OP_GET_PUT, K8|K16, &es_create_128}, - { "echo suppressor 200ms tail len", OP_GET_PUT, K8|K16, &es_create_200}, - { "echo suppressor 256ms tail len", OP_GET_PUT, K8|K16, &es_create_256}, - { "echo suppressor 400ms tail len", OP_GET_PUT, K8|K16, &es_create_400}, - { "echo suppressor 500ms tail len", OP_GET_PUT, K8|K16, &es_create_500}, - { "echo suppressor 512ms tail len", OP_GET_PUT, K8|K16, &es_create_512}, - { "echo suppressor 600ms tail len", OP_GET_PUT, K8|K16, &es_create_600}, - { "echo suppressor 800ms tail len", OP_GET_PUT, K8|K16, &es_create_800}, - { "tone generator with single freq", OP_GET, K8|K16, &create_tonegen1}, - { "tone generator with dual freq", OP_GET, K8|K16, &create_tonegen2}, + { "get from memplayer", OP_GET, K8|K16, &gen_port_test_init}, + { "conference bridge with 1 call", OP_GET_PUT, K8|K16, &conf1_test_init}, + { "conference bridge with 2 calls", OP_GET_PUT, K8|K16, &conf2_test_init}, + { "conference bridge with 4 calls", OP_GET_PUT, K8|K16, &conf4_test_init}, + { "conference bridge with 8 calls", OP_GET_PUT, K8|K16, &conf8_test_init}, + { "conference bridge with 16 calls", OP_GET_PUT, K8|K16, &conf16_test_init}, + { "upsample+downsample - linear", OP_GET, K8|K16, &linear_resample}, + { "upsample+downsample - small filter", OP_GET, K8|K16, &small_filt_resample}, + { "upsample+downsample - large filter", OP_GET, K8|K16, &large_filt_resample}, + { "WSOLA PLC - 0% loss", OP_GET, K8|K16, &wsola_plc_0}, + { "WSOLA PLC - 2% loss", OP_GET, K8|K16, &wsola_plc_2}, + { "WSOLA PLC - 5% loss", OP_GET, K8|K16, &wsola_plc_5}, + { "WSOLA PLC - 10% loss", OP_GET, K8|K16, &wsola_plc_10}, + { "WSOLA PLC - 20% loss", OP_GET, K8|K16, &wsola_plc_20}, + { "WSOLA PLC - 50% loss", OP_GET, K8|K16, &wsola_plc_50}, + { "WSOLA discard 2% excess", OP_GET, K8|K16, &wsola_discard_2}, + { "WSOLA discard 5% excess", OP_GET, K8|K16, &wsola_discard_5}, + { "WSOLA discard 10% excess", OP_GET, K8|K16, &wsola_discard_10}, + { "WSOLA discard 20% excess", OP_GET, K8|K16, &wsola_discard_20}, + { "WSOLA discard 50% excess", OP_GET, K8|K16, &wsola_discard_50}, + { "Delay buffer", OP_GET_PUT, K8|K16, &delaybuf_0}, + { "Delay buffer - drift -2%", OP_GET_PUT, K8|K16, &delaybuf_n2}, + { "Delay buffer - drift -5%", OP_GET_PUT, K8|K16, &delaybuf_n5}, + { "Delay buffer - drift -10%", OP_GET_PUT, K8|K16, &delaybuf_n10}, + { "Delay buffer - drift -20%", OP_GET_PUT, K8|K16, &delaybuf_n20}, + { "Delay buffer - drift +2%", OP_GET_PUT, K8|K16, &delaybuf_p2}, + { "Delay buffer - drift +5%", OP_GET_PUT, K8|K16, &delaybuf_p5}, + { "Delay buffer - drift +10%", OP_GET_PUT, K8|K16, &delaybuf_p10}, + { "Delay buffer - drift +20%", OP_GET_PUT, K8|K16, &delaybuf_p20}, + { "echo canceller 100ms tail len", OP_GET_PUT, K8|K16, &ec_create_100}, + { "echo canceller 128ms tail len", OP_GET_PUT, K8|K16, &ec_create_128}, + { "echo canceller 200ms tail len", OP_GET_PUT, K8|K16, &ec_create_200}, + { "echo canceller 256ms tail len", OP_GET_PUT, K8|K16, &ec_create_256}, + { "echo canceller 400ms tail len", OP_GET_PUT, K8|K16, &ec_create_400}, + { "echo canceller 500ms tail len", OP_GET_PUT, K8|K16, &ec_create_500}, + { "echo canceller 512ms tail len", OP_GET_PUT, K8|K16, &ec_create_512}, + { "echo canceller 600ms tail len", OP_GET_PUT, K8|K16, &ec_create_600}, + { "echo canceller 800ms tail len", OP_GET_PUT, K8|K16, &ec_create_800}, + { "echo suppressor 100ms tail len", OP_GET_PUT, K8|K16, &es_create_100}, + { "echo suppressor 128ms tail len", OP_GET_PUT, K8|K16, &es_create_128}, + { "echo suppressor 200ms tail len", OP_GET_PUT, K8|K16, &es_create_200}, + { "echo suppressor 256ms tail len", OP_GET_PUT, K8|K16, &es_create_256}, + { "echo suppressor 400ms tail len", OP_GET_PUT, K8|K16, &es_create_400}, + { "echo suppressor 500ms tail len", OP_GET_PUT, K8|K16, &es_create_500}, + { "echo suppressor 512ms tail len", OP_GET_PUT, K8|K16, &es_create_512}, + { "echo suppressor 600ms tail len", OP_GET_PUT, K8|K16, &es_create_600}, + { "echo suppressor 800ms tail len", OP_GET_PUT, K8|K16, &es_create_800}, + { "tone generator with single freq", OP_GET, K8|K16, &create_tonegen1}, + { "tone generator with dual freq", OP_GET, K8|K16, &create_tonegen2}, #if PJMEDIA_HAS_G711_CODEC - { "codec encode/decode - G.711", OP_PUT, K8, &g711_encode_decode}, + { "codec encode/decode - G.711", OP_PUT, K8, &g711_encode_decode}, #endif #if PJMEDIA_HAS_G722_CODEC - { "codec encode/decode - G.722", OP_PUT, K16, &g722_encode_decode}, + { "codec encode/decode - G.722", OP_PUT, K16, &g722_encode_decode}, #endif #if PJMEDIA_HAS_GSM_CODEC - { "codec encode/decode - GSM", OP_PUT, K8, &gsm_encode_decode}, + { "codec encode/decode - GSM", OP_PUT, K8, &gsm_encode_decode}, #endif #if PJMEDIA_HAS_ILBC_CODEC - { "codec encode/decode - iLBC", OP_PUT, K8, &ilbc_encode_decode}, + { "codec encode/decode - iLBC", OP_PUT, K8, &ilbc_encode_decode}, #endif #if PJMEDIA_HAS_SPEEX_CODEC - { "codec encode/decode - Speex 8Khz", OP_PUT, K8, &speex8_encode_decode}, - { "codec encode/decode - Speex 16Khz", OP_PUT, K16, &speex16_encode_decode}, + { "codec encode/decode - Speex 8Khz", OP_PUT, K8, &speex8_encode_decode}, + { "codec encode/decode - Speex 16Khz", OP_PUT, K16, &speex16_encode_decode}, #endif #if PJMEDIA_HAS_G7221_CODEC - { "codec encode/decode - G.722.1", OP_PUT, K16, &g7221_encode_decode}, - { "codec encode/decode - G.722.1c", OP_PUT, K32, &g7221c_encode_decode}, + { "codec encode/decode - G.722.1", OP_PUT, K16, &g7221_encode_decode}, + { "codec encode/decode - G.722.1c", OP_PUT, K32, &g7221c_encode_decode}, #endif #if PJMEDIA_HAS_OPENCORE_AMRNB_CODEC - { "codec encode/decode - AMR-NB", OP_PUT, K8, &amr_encode_decode}, + { "codec encode/decode - AMR-NB", OP_PUT, K8, &amr_encode_decode}, #endif #if PJMEDIA_HAS_OPENCORE_AMRWB_CODEC - { "codec encode/decode - AMR-WB", OP_PUT, K16, &amrwb_encode_decode}, + { "codec encode/decode - AMR-WB", OP_PUT, K16, &amrwb_encode_decode}, #endif #if PJMEDIA_HAS_L16_CODEC - { "codec encode/decode - L16/8000/1", OP_PUT, K8, &l16_8_encode_decode}, - { "codec encode/decode - L16/16000/1", OP_PUT, K16, &l16_16_encode_decode}, + { "codec encode/decode - L16/8000/1", OP_PUT, K8, &l16_8_encode_decode}, + { "codec encode/decode - L16/16000/1", OP_PUT, K16, &l16_16_encode_decode}, #endif #if PJMEDIA_HAS_G711_CODEC - { "stream TX/RX - G.711", OP_PUT_GET, K8, &create_stream_pcmu}, - { "stream TX/RX - G.711 SRTP 32bit", OP_PUT_GET, K8, &create_stream_pcmu_srtp32_no_auth}, - { "stream TX/RX - G.711 SRTP 32bit +auth", OP_PUT_GET, K8, &create_stream_pcmu_srtp32_with_auth}, - { "stream TX/RX - G.711 SRTP 80bit", OP_PUT_GET, K8, &create_stream_pcmu_srtp80_no_auth}, - { "stream TX/RX - G.711 SRTP 80bit +auth", OP_PUT_GET, K8, &create_stream_pcmu_srtp80_with_auth}, + { "stream TX/RX - G.711", OP_PUT_GET, K8, &create_stream_pcmu}, + { "stream TX/RX - G.711 SRTP 32bit", OP_PUT_GET, K8, &create_stream_pcmu_srtp32_no_auth}, + { "stream TX/RX - G.711 SRTP 32bit +auth", OP_PUT_GET, K8, &create_stream_pcmu_srtp32_with_auth}, + { "stream TX/RX - G.711 SRTP 80bit", OP_PUT_GET, K8, &create_stream_pcmu_srtp80_no_auth}, + { "stream TX/RX - G.711 SRTP 80bit +auth", OP_PUT_GET, K8, &create_stream_pcmu_srtp80_with_auth}, #endif #if PJMEDIA_HAS_G722_CODEC - { "stream TX/RX - G.722", OP_PUT_GET, K16, &create_stream_g722}, + { "stream TX/RX - G.722", OP_PUT_GET, K16, &create_stream_g722}, #endif #if PJMEDIA_HAS_GSM_CODEC - { "stream TX/RX - GSM", OP_PUT_GET, K8, &create_stream_gsm}, - { "stream TX/RX - GSM SRTP 32bit", OP_PUT_GET, K8, &create_stream_gsm_srtp32_no_auth}, - { "stream TX/RX - GSM SRTP 32bit + auth", OP_PUT_GET, K8, &create_stream_gsm_srtp32_with_auth}, - { "stream TX/RX - GSM SRTP 80bit", OP_PUT_GET, K8, &create_stream_gsm_srtp80_no_auth}, - { "stream TX/RX - GSM SRTP 80bit + auth", OP_PUT_GET, K8, &create_stream_gsm_srtp80_with_auth}, + { "stream TX/RX - GSM", OP_PUT_GET, K8, &create_stream_gsm}, + { "stream TX/RX - GSM SRTP 32bit", OP_PUT_GET, K8, &create_stream_gsm_srtp32_no_auth}, + { "stream TX/RX - GSM SRTP 32bit + auth", OP_PUT_GET, K8, &create_stream_gsm_srtp32_with_auth}, + { "stream TX/RX - GSM SRTP 80bit", OP_PUT_GET, K8, &create_stream_gsm_srtp80_no_auth}, + { "stream TX/RX - GSM SRTP 80bit + auth", OP_PUT_GET, K8, &create_stream_gsm_srtp80_with_auth}, #endif #if PJMEDIA_HAS_G7221_CODEC - { "stream TX/RX - G.722.1", OP_PUT_GET, K16, &create_stream_g7221}, - { "stream TX/RX - G.722.1c", OP_PUT_GET, K32, &create_stream_g7221c}, + { "stream TX/RX - G.722.1", OP_PUT_GET, K16, &create_stream_g7221}, + { "stream TX/RX - G.722.1c", OP_PUT_GET, K32, &create_stream_g7221c}, #endif #if PJMEDIA_HAS_OPENCORE_AMRNB_CODEC - { "stream TX/RX - AMR-NB", OP_PUT_GET, K8, &create_stream_amr}, + { "stream TX/RX - AMR-NB", OP_PUT_GET, K8, &create_stream_amr}, #endif #if PJMEDIA_HAS_OPENCORE_AMRWB_CODEC - { "stream TX/RX - AMR-WB", OP_PUT_GET, K16, &create_stream_amrwb}, + { "stream TX/RX - AMR-WB", OP_PUT_GET, K16, &create_stream_amrwb}, #endif }; @@ -2510,51 +2509,51 @@ int mips_test(void) PJ_LOG(3,(THIS_FILE, "----------------------------------------------------------------------")); for (c=0; cvalid_clock_rate & clks[c]) == 0) - continue; - - /* Run test */ - for (j=0; jtitle, usec, cpu_pct, mips_val)); - - } + for (i=0; ivalid_clock_rate & clks[c]) == 0) + continue; + + /* Run test */ + for (j=0; jtitle, usec, cpu_pct, mips_val)); + + } } return 0; diff --git a/pjmedia/src/test/rtp_test.c b/pjmedia/src/test/rtp_test.c index e8f8fdc6fe..119cc04c84 100644 --- a/pjmedia/src/test/rtp_test.c +++ b/pjmedia/src/test/rtp_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,13 +27,13 @@ int rtp_test() int hdrlen; if (!fhnd) - return -1; + return -1; pjmedia_rtp_session_init (&rtp, 4, 0x12345678); pjmedia_rtp_encode_rtp (&rtp, 4, 0, 0, 160, &rtphdr, &hdrlen); if (fwrite (rtphdr, hdrlen, 1, fhnd) != 1) { - fclose(fhnd); - return -1; + fclose(fhnd); + return -1; } fclose(fhnd); return 0; diff --git a/pjmedia/src/test/sdp_neg_test.c b/pjmedia/src/test/sdp_neg_test.c index 4894acba9a..a7d75e532a 100644 --- a/pjmedia/src/test/sdp_neg_test.c +++ b/pjmedia/src/test/sdp_neg_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,294 +31,294 @@ enum session_type }; struct offer_answer -{ - enum session_type type; /* LOCAL_OFFER: REMOTE_OFFER: */ - char *sdp1; /* local offer remote offer */ - char *sdp2; /* remote answer initial local */ - char *sdp3; /* local active media local answer */ +{ + enum session_type type; /* LOCAL_OFFER: REMOTE_OFFER: */ + char *sdp1; /* local offer remote offer */ + char *sdp2; /* remote answer initial local */ + char *sdp3; /* local active media local answer */ }; static struct test { - const char *title; - unsigned offer_answer_count; - struct offer_answer offer_answer[4]; + const char *title; + unsigned offer_answer_count; + struct offer_answer offer_answer[4]; } test[] = { /* test 0: */ { - /********************************************************************* - * RFC 3264 examples, section 10.1 (Alice's view) - * - * Difference from the example: - * - Bob's port number of the third media stream in the first answer - * is changed (make it different than Alice's) - * - in the second offer/answer exchange, Alice can't accept the - * additional line since she didn't specify the capability - * in the initial negotiator creation. - */ - - "RFC 3264 example 10.1 (Alice's view)", - 2, - { - { - LOCAL_OFFER, - /* Alice sends offer: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.anywhere.com\r\n" - "s= \r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 51372 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "m=video 53000 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n", - /* Received Bob's answer: */ - "v=0\r\n" - "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 49920 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "m=video 53002 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n", - /* Alice's SDP now: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.anywhere.com\r\n" - "s= \r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ - "m=video 53000 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n" - }, - { - REMOTE_OFFER, - /* Bob wants to change his local SDP - * (change local port for the first stream and add new stream) - * Received SDP from Bob: - */ - "v=0\r\n" - "o=bob 2890844730 2890844731 IN IP4 host.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 65422 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "m=video 53002 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n" - "m=audio 51434 RTP/AVP 110\r\n" - "a=rtpmap:110 telephone-events/8000\r\n" - "a=recvonly\r\n", - NULL, - /* Alice's SDP now */ - "v=0\r\n" - "o=alice 2890844526 2890844527 IN IP4 host.anywhere.com\r\n" - "s= \r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ - "m=video 53000 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n" - "m=audio 0 RTP/AVP 110\r\n" - /* <-- the following attributes are not necessary (port 0) */ - //"a=rtpmap:110 telephone-events/8000\r\n" - //"a=sendonly\r\n" - } - } + /********************************************************************* + * RFC 3264 examples, section 10.1 (Alice's view) + * + * Difference from the example: + * - Bob's port number of the third media stream in the first answer + * is changed (make it different than Alice's) + * - in the second offer/answer exchange, Alice can't accept the + * additional line since she didn't specify the capability + * in the initial negotiator creation. + */ + + "RFC 3264 example 10.1 (Alice's view)", + 2, + { + { + LOCAL_OFFER, + /* Alice sends offer: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.anywhere.com\r\n" + "s= \r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 51372 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "m=video 53000 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n", + /* Received Bob's answer: */ + "v=0\r\n" + "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 49920 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "m=video 53002 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n", + /* Alice's SDP now: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.anywhere.com\r\n" + "s= \r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ + "m=video 53000 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n" + }, + { + REMOTE_OFFER, + /* Bob wants to change his local SDP + * (change local port for the first stream and add new stream) + * Received SDP from Bob: + */ + "v=0\r\n" + "o=bob 2890844730 2890844731 IN IP4 host.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 65422 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "m=video 53002 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n" + "m=audio 51434 RTP/AVP 110\r\n" + "a=rtpmap:110 telephone-events/8000\r\n" + "a=recvonly\r\n", + NULL, + /* Alice's SDP now */ + "v=0\r\n" + "o=alice 2890844526 2890844527 IN IP4 host.anywhere.com\r\n" + "s= \r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ + "m=video 53000 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n" + "m=audio 0 RTP/AVP 110\r\n" + /* <-- the following attributes are not necessary (port 0) */ + //"a=rtpmap:110 telephone-events/8000\r\n" + //"a=sendonly\r\n" + } + } }, /* test 1: */ { - /********************************************************************* - * RFC 3264 examples, section 10.1. (Bob's view) - * - * Difference: - * - the SDP version in Bob's capability is changed to ver-1. - */ - - "RFC 3264 example 10.1 (Bob's view)", - 2, - { - { - REMOTE_OFFER, - /* Remote offer from Alice: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.anywhere.com\r\n" - "s= \r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 51372 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "m=video 53000 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n", - /* Bob's capability: */ - "v=0\r\n" - "o=bob 2890844730 2890844729 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 49920 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "m=video 53000 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n", - /* This's how Bob's answer should look like: */ - "v=0\r\n" - "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 49920 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "m=video 53000 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n" - }, - { - LOCAL_OFFER, - /* Bob wants to change his local SDP - * (change local port for the first stream and add new stream) - */ - "v=0\r\n" - "o=bob 2890844730 2890844731 IN IP4 host.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 65422 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "m=video 53000 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n" - "m=audio 51434 RTP/AVP 110\r\n" - "a=rtpmap:110 telephone-events/8000\r\n" - "a=recvonly\r\n", - /* Got answer from Alice */ - "v=0\r\n" - "o=alice 2890844526 2890844527 IN IP4 host.anywhere.com\r\n" - "s=-\r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "m=video 53000 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n" - "m=audio 53122 RTP/AVP 110\r\n" - "a=rtpmap:110 telephone-events/8000\r\n" - "a=sendonly\r\n", - /* This is how Bob's SDP should look like after negotiation */ - "v=0\r\n" - "o=bob 2890844730 2890844731 IN IP4 host.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 65422 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "m=video 53000 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n" - "m=audio 51434 RTP/AVP 110\r\n" - "a=rtpmap:110 telephone-events/8000\r\n" - "a=recvonly\r\n" - } - } + /********************************************************************* + * RFC 3264 examples, section 10.1. (Bob's view) + * + * Difference: + * - the SDP version in Bob's capability is changed to ver-1. + */ + + "RFC 3264 example 10.1 (Bob's view)", + 2, + { + { + REMOTE_OFFER, + /* Remote offer from Alice: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.anywhere.com\r\n" + "s= \r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 51372 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "m=video 53000 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n", + /* Bob's capability: */ + "v=0\r\n" + "o=bob 2890844730 2890844729 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 49920 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "m=video 53000 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n", + /* This's how Bob's answer should look like: */ + "v=0\r\n" + "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 49920 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "m=video 53000 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n" + }, + { + LOCAL_OFFER, + /* Bob wants to change his local SDP + * (change local port for the first stream and add new stream) + */ + "v=0\r\n" + "o=bob 2890844730 2890844731 IN IP4 host.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 65422 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "m=video 53000 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n" + "m=audio 51434 RTP/AVP 110\r\n" + "a=rtpmap:110 telephone-events/8000\r\n" + "a=recvonly\r\n", + /* Got answer from Alice */ + "v=0\r\n" + "o=alice 2890844526 2890844527 IN IP4 host.anywhere.com\r\n" + "s=-\r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "m=video 53000 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n" + "m=audio 53122 RTP/AVP 110\r\n" + "a=rtpmap:110 telephone-events/8000\r\n" + "a=sendonly\r\n", + /* This is how Bob's SDP should look like after negotiation */ + "v=0\r\n" + "o=bob 2890844730 2890844731 IN IP4 host.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 65422 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "m=video 53000 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n" + "m=audio 51434 RTP/AVP 110\r\n" + "a=rtpmap:110 telephone-events/8000\r\n" + "a=recvonly\r\n" + } + } }, /* test 2: */ { - /********************************************************************* - * RFC 3264 examples, section 10.2. - * This is from Alice's point of view. - */ - - "RFC 3264 example 10.2 (Alice's view)", - 2, - { - { - LOCAL_OFFER, - /* The initial offer from Alice to Bob indicates a single audio - * stream with the three audio codecs that are available in the - * DSP. The stream is marked as inactive, - */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.anywhere.com\r\n" - "s=-\r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 62986 RTP/AVP 0 4 18\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:4 G723/8000\r\n" - "a=rtpmap:18 G729/8000\r\n" - "a=inactive\r\n", - /* Bob can support dynamic switching between PCMU and G.723. So, - * he sends the following answer: - */ - "v=0\r\n" - "o=bob 2890844730 2890844731 IN IP4 host.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 54344 RTP/AVP 0 4\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:4 G723/8000\r\n" - "a=inactive\r\n", - /* This is how Alice's media should look like after negotiation */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.anywhere.com\r\n" - "s=-\r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 62986 RTP/AVP 0 4\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:4 G723/8000\r\n" - "a=inactive\r\n", - }, - { - LOCAL_OFFER, - /* Alice sends an updated offer with a sendrecv stream: */ - "v=0\r\n" - "o=alice 2890844526 2890844527 IN IP4 host.anywhere.com\r\n" - "s=-\r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 62986 RTP/AVP 4\r\n" - "a=rtpmap:4 G723/8000\r\n" - "a=sendrecv\r\n", - /* Bob accepts the single codec: */ - "v=0\r\n" - "o=bob 2890844730 2890844732 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 54344 RTP/AVP 4\r\n" - "a=rtpmap:4 G723/8000\r\n" - "a=sendrecv\r\n", - /* This is how Alice's media should look like after negotiation */ - "v=0\r\n" - "o=alice 2890844526 2890844527 IN IP4 host.anywhere.com\r\n" - "s=-\r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 62986 RTP/AVP 4\r\n" - "a=rtpmap:4 G723/8000\r\n" - "a=sendrecv\r\n" - } - } + /********************************************************************* + * RFC 3264 examples, section 10.2. + * This is from Alice's point of view. + */ + + "RFC 3264 example 10.2 (Alice's view)", + 2, + { + { + LOCAL_OFFER, + /* The initial offer from Alice to Bob indicates a single audio + * stream with the three audio codecs that are available in the + * DSP. The stream is marked as inactive, + */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.anywhere.com\r\n" + "s=-\r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 62986 RTP/AVP 0 4 18\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=rtpmap:18 G729/8000\r\n" + "a=inactive\r\n", + /* Bob can support dynamic switching between PCMU and G.723. So, + * he sends the following answer: + */ + "v=0\r\n" + "o=bob 2890844730 2890844731 IN IP4 host.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 54344 RTP/AVP 0 4\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=inactive\r\n", + /* This is how Alice's media should look like after negotiation */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.anywhere.com\r\n" + "s=-\r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 62986 RTP/AVP 0 4\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=inactive\r\n", + }, + { + LOCAL_OFFER, + /* Alice sends an updated offer with a sendrecv stream: */ + "v=0\r\n" + "o=alice 2890844526 2890844527 IN IP4 host.anywhere.com\r\n" + "s=-\r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 62986 RTP/AVP 4\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=sendrecv\r\n", + /* Bob accepts the single codec: */ + "v=0\r\n" + "o=bob 2890844730 2890844732 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 54344 RTP/AVP 4\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=sendrecv\r\n", + /* This is how Alice's media should look like after negotiation */ + "v=0\r\n" + "o=alice 2890844526 2890844527 IN IP4 host.anywhere.com\r\n" + "s=-\r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 62986 RTP/AVP 4\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=sendrecv\r\n" + } + } }, #if 0 @@ -330,1308 +329,1308 @@ static struct test /* test 3: */ { - /********************************************************************* - * RFC 3264 examples, section 10.2. - * This is from Bob's point of view. - * - * Difference: - * - The SDP version number in Bob's initial capability is ver-1 - */ - - "RFC 3264 example 10.2 (Bob's view)", - 2, - { - { - REMOTE_OFFER, - /* Bob received offer from Alice: - */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.anywhere.com\r\n" - "s=-\r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 62986 RTP/AVP 0 4 18\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:4 G723/8000\r\n" - "a=rtpmap:18 G729/8000\r\n" - "a=inactive\r\n", - /* Bob's capability: - */ - "v=0\r\n" - "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 54344 RTP/AVP 0 4\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:4 G723/8000\r\n" - "a=inactive\r\n", - /* This is how Bob's media should look like after negotiation */ - "v=0\r\n" - "o=bob 2890844730 2890844731 IN IP4 host.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 54344 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=inactive\r\n" - }, - { - REMOTE_OFFER, - /* Received updated Alice's SDP: offer with a sendrecv stream: */ - "v=0\r\n" - "o=alice 2890844526 2890844527 IN IP4 host.anywhere.com\r\n" - "s=-\r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 62986 RTP/AVP 4\r\n" - "a=rtpmap:4 G723/8000\r\n" - "a=sendrecv\r\n", - /* Bob accepts the single codec: */ - NULL, - /* This is how Bob's media should look like after negotiation */ - "v=0\r\n" - "o=bob 2890844730 2890844732 IN IP4 host.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 54344 RTP/AVP 4\r\n" - "a=rtpmap:4 G723/8000\r\n" - "a=sendrecv\r\n", - } - } + /********************************************************************* + * RFC 3264 examples, section 10.2. + * This is from Bob's point of view. + * + * Difference: + * - The SDP version number in Bob's initial capability is ver-1 + */ + + "RFC 3264 example 10.2 (Bob's view)", + 2, + { + { + REMOTE_OFFER, + /* Bob received offer from Alice: + */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.anywhere.com\r\n" + "s=-\r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 62986 RTP/AVP 0 4 18\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=rtpmap:18 G729/8000\r\n" + "a=inactive\r\n", + /* Bob's capability: + */ + "v=0\r\n" + "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 54344 RTP/AVP 0 4\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=inactive\r\n", + /* This is how Bob's media should look like after negotiation */ + "v=0\r\n" + "o=bob 2890844730 2890844731 IN IP4 host.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 54344 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=inactive\r\n" + }, + { + REMOTE_OFFER, + /* Received updated Alice's SDP: offer with a sendrecv stream: */ + "v=0\r\n" + "o=alice 2890844526 2890844527 IN IP4 host.anywhere.com\r\n" + "s=-\r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 62986 RTP/AVP 4\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=sendrecv\r\n", + /* Bob accepts the single codec: */ + NULL, + /* This is how Bob's media should look like after negotiation */ + "v=0\r\n" + "o=bob 2890844730 2890844732 IN IP4 host.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 54344 RTP/AVP 4\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=sendrecv\r\n", + } + } }, #endif /* test 4: */ { - /********************************************************************* - * RFC 4317 Sample 2.1: Audio and Video 1 (Alice's view) - * - * This common scenario shows a video and audio session in which - * multiple codecs are offered but only one is accepted. As a result of - * the exchange shown below, Alice and Bob may send only PCMU audio and - * MPV video. Note: Dynamic payload type 97 is used for iLBC codec - */ - "RFC 4317 section 2.1: Audio and Video 1 (Alice's view)", - 1, - { - { - LOCAL_OFFER, - /* Alice's local offer: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0 8 97\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:8 PCMA/8000\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "m=video 51372 RTP/AVP 31 32\r\n" - "a=rtpmap:31 H261/90000\r\n" - "a=rtpmap:32 MPV/90000\r\n", - /* Received answer from Bob: */ - "v=0\r\n" - "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49174 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 49170 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n", - /* This is how Alice's media should look like now: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 51372 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n" - } - } + /********************************************************************* + * RFC 4317 Sample 2.1: Audio and Video 1 (Alice's view) + * + * This common scenario shows a video and audio session in which + * multiple codecs are offered but only one is accepted. As a result of + * the exchange shown below, Alice and Bob may send only PCMU audio and + * MPV video. Note: Dynamic payload type 97 is used for iLBC codec + */ + "RFC 4317 section 2.1: Audio and Video 1 (Alice's view)", + 1, + { + { + LOCAL_OFFER, + /* Alice's local offer: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0 8 97\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:8 PCMA/8000\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "m=video 51372 RTP/AVP 31 32\r\n" + "a=rtpmap:31 H261/90000\r\n" + "a=rtpmap:32 MPV/90000\r\n", + /* Received answer from Bob: */ + "v=0\r\n" + "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49174 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 49170 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n", + /* This is how Alice's media should look like now: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 51372 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n" + } + } }, /* test 5: */ { - /********************************************************************* - * RFC 4317 Sample 2.1: Audio and Video 1 (Bob's view) - * - * This common scenario shows a video and audio session in which - * multiple codecs are offered but only one is accepted. As a result of - * the exchange shown below, Alice and Bob may send only PCMU audio and - * MPV video. Note: Dynamic payload type 97 is used for iLBC codec - * - * Difference: - * - Bob's initial capability version number - */ - "RFC 4317 section 2.1: Audio and Video 1 (Bob's view)", - 1, - { - { - REMOTE_OFFER, - /* Received Alice's local offer: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0 8 97\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:8 PCMA/8000\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "m=video 51372 RTP/AVP 31 32\r\n" - "a=rtpmap:31 H261/90000\r\n" - "a=rtpmap:32 MPV/90000\r\n", - /* Bob's capability: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49174 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 49170 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n", - /* This is how Bob's media should look like now: */ - "v=0\r\n" - "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" - "s=-\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49174 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 49170 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n" - } - } + /********************************************************************* + * RFC 4317 Sample 2.1: Audio and Video 1 (Bob's view) + * + * This common scenario shows a video and audio session in which + * multiple codecs are offered but only one is accepted. As a result of + * the exchange shown below, Alice and Bob may send only PCMU audio and + * MPV video. Note: Dynamic payload type 97 is used for iLBC codec + * + * Difference: + * - Bob's initial capability version number + */ + "RFC 4317 section 2.1: Audio and Video 1 (Bob's view)", + 1, + { + { + REMOTE_OFFER, + /* Received Alice's local offer: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0 8 97\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:8 PCMA/8000\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "m=video 51372 RTP/AVP 31 32\r\n" + "a=rtpmap:31 H261/90000\r\n" + "a=rtpmap:32 MPV/90000\r\n", + /* Bob's capability: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49174 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 49170 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n", + /* This is how Bob's media should look like now: */ + "v=0\r\n" + "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" + "s=-\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49174 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 49170 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n" + } + } }, /* test 6: */ { - /********************************************************************* - * RFC 4317 Sample 2.2: Audio and Video 2 (Alice's view) - * - * Difference: - * - Bob's initial capability version number - */ - "RFC 4317 section 2.2: Audio and Video 2 (Alice's view)", - 2, - { - { - LOCAL_OFFER, - /* Alice sends offer: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0 8 97\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:8 PCMA/8000\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "m=video 51372 RTP/AVP 31 32\r\n" - "a=rtpmap:31 H261/90000\r\n" - "a=rtpmap:32 MPV/90000\r\n", - /* Bob's answer: */ - "v=0\r\n" - "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49172 RTP/AVP 0 8\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:8 PCMA/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n", - /* This is how Alice's media should look like now: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0 8\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:8 PCMA/8000\r\n" - // By #1088, the formats won't be negotiated when the media has port 0. - //"m=video 0 RTP/AVP 31\r\n" - "m=video 0 RTP/AVP 31 32\r\n" - //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ - }, - { - LOCAL_OFFER, - /* Alice sends updated offer: */ - "v=0\r\n" - "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 51372 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n", - /* Bob's answer: */ - "v=0\r\n" - "o=bob 2808844564 2808844565 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49172 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n", - /* This is how Alice's SDP should look like: */ - "v=0\r\n" - "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 51372 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ - } - } + /********************************************************************* + * RFC 4317 Sample 2.2: Audio and Video 2 (Alice's view) + * + * Difference: + * - Bob's initial capability version number + */ + "RFC 4317 section 2.2: Audio and Video 2 (Alice's view)", + 2, + { + { + LOCAL_OFFER, + /* Alice sends offer: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0 8 97\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:8 PCMA/8000\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "m=video 51372 RTP/AVP 31 32\r\n" + "a=rtpmap:31 H261/90000\r\n" + "a=rtpmap:32 MPV/90000\r\n", + /* Bob's answer: */ + "v=0\r\n" + "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49172 RTP/AVP 0 8\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:8 PCMA/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n", + /* This is how Alice's media should look like now: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0 8\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:8 PCMA/8000\r\n" + // By #1088, the formats won't be negotiated when the media has port 0. + //"m=video 0 RTP/AVP 31\r\n" + "m=video 0 RTP/AVP 31 32\r\n" + //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ + }, + { + LOCAL_OFFER, + /* Alice sends updated offer: */ + "v=0\r\n" + "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 51372 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n", + /* Bob's answer: */ + "v=0\r\n" + "o=bob 2808844564 2808844565 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49172 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n", + /* This is how Alice's SDP should look like: */ + "v=0\r\n" + "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 51372 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ + } + } }, /* test 7: */ { - /********************************************************************* - * RFC 4317 Sample 2.2: Audio and Video 2 (Bob's view) - * - * Difference: - * - Bob's initial capability version number - */ - "RFC 4317 section 2.2: Audio and Video 2 (Bob's view)", - 2, - { - { - REMOTE_OFFER, - /* Received offer from alice: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0 8 97\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:8 PCMA/8000\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "m=video 51372 RTP/AVP 31 32\r\n" - "a=rtpmap:31 H261/90000\r\n" - "a=rtpmap:32 MPV/90000\r\n", - /* Bob's initial capability: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49172 RTP/AVP 0 8\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:8 PCMA/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n", - /* This is how Bob's answer should look like now: */ - "v=0\r\n" - "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49172 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - }, - { - REMOTE_OFFER, - /* Received updated offer from Alice: */ - "v=0\r\n" - "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 51372 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n", - /* Bob's answer: */ - NULL, - /* This is how Bob's answer should look like: */ - "v=0\r\n" + /********************************************************************* + * RFC 4317 Sample 2.2: Audio and Video 2 (Bob's view) + * + * Difference: + * - Bob's initial capability version number + */ + "RFC 4317 section 2.2: Audio and Video 2 (Bob's view)", + 2, + { + { + REMOTE_OFFER, + /* Received offer from alice: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0 8 97\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:8 PCMA/8000\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "m=video 51372 RTP/AVP 31 32\r\n" + "a=rtpmap:31 H261/90000\r\n" + "a=rtpmap:32 MPV/90000\r\n", + /* Bob's initial capability: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49172 RTP/AVP 0 8\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:8 PCMA/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n", + /* This is how Bob's answer should look like now: */ + "v=0\r\n" + "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49172 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + }, + { + REMOTE_OFFER, + /* Received updated offer from Alice: */ + "v=0\r\n" + "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 51372 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n", + /* Bob's answer: */ + NULL, + /* This is how Bob's answer should look like: */ + "v=0\r\n" #if PJMEDIA_SDP_NEG_COMPARE_BEFORE_INC_VERSION - "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" + "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" #else - "o=bob 2808844564 2808844565 IN IP4 host.biloxi.example.com\r\n" + "o=bob 2808844564 2808844565 IN IP4 host.biloxi.example.com\r\n" #endif - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49172 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ - } - } + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49172 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ + } + } }, /* test 8: */ { - /********************************************************************* - * RFC 4317 Sample 2.4: Audio and Telephone-Events (Alice's view) - * - */ - - "RFC 4317 section 2.4: Audio and Telephone-Events (Alice's view)", - 1, - { - { - LOCAL_OFFER, - /* Alice sends offer: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0 97\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "m=audio 49172 RTP/AVP 98\r\n" - "a=rtpmap:98 telephone-event/8000\r\n" - "a=sendonly\r\n", - /* Received Bob's answer: */ - "v=0\r\n" - "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49172 RTP/AVP 97\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "m=audio 49174 RTP/AVP 98\r\n" - "a=rtpmap:98 telephone-event/8000\r\n" - "a=recvonly\r\n", - /* Alice's SDP now: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 97\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "m=audio 49172 RTP/AVP 98\r\n" - "a=rtpmap:98 telephone-event/8000\r\n" - "a=sendonly\r\n" - } - } + /********************************************************************* + * RFC 4317 Sample 2.4: Audio and Telephone-Events (Alice's view) + * + */ + + "RFC 4317 section 2.4: Audio and Telephone-Events (Alice's view)", + 1, + { + { + LOCAL_OFFER, + /* Alice sends offer: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0 97\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "m=audio 49172 RTP/AVP 98\r\n" + "a=rtpmap:98 telephone-event/8000\r\n" + "a=sendonly\r\n", + /* Received Bob's answer: */ + "v=0\r\n" + "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49172 RTP/AVP 97\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "m=audio 49174 RTP/AVP 98\r\n" + "a=rtpmap:98 telephone-event/8000\r\n" + "a=recvonly\r\n", + /* Alice's SDP now: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 97\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "m=audio 49172 RTP/AVP 98\r\n" + "a=rtpmap:98 telephone-event/8000\r\n" + "a=sendonly\r\n" + } + } }, /* test 9: */ { - /********************************************************************* - * RFC 4317 Sample 2.4: Audio and Telephone-Events (Bob's view) - * - * Difference: - * - Bob's initial SDP version number - * - Bob's capability are added with more formats, and the - * stream order is interchanged to test the negotiator. - */ - - "RFC 4317 section 2.4: Audio and Telephone-Events (Bob's view)", - 1, - { - { - REMOTE_OFFER, - /* Received Alice's offer: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0 97\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "m=audio 49172 RTP/AVP 98\r\n" - "a=rtpmap:98 telephone-event/8000\r\n" - "a=sendonly\r\n", - /* Bob's initial capability: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49174 RTP/AVP 4 98\r\n" - "a=rtpmap:98 telephone-event/8000\r\n" - "m=audio 49172 RTP/AVP 97 8 99\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "a=rtpmap:99 telephone-event/8000\r\n", - /* Bob's answer should be: */ - "v=0\r\n" - "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49172 RTP/AVP 97\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "m=audio 49174 RTP/AVP 98\r\n" - "a=rtpmap:98 telephone-event/8000\r\n" - "a=recvonly\r\n" - } - } + /********************************************************************* + * RFC 4317 Sample 2.4: Audio and Telephone-Events (Bob's view) + * + * Difference: + * - Bob's initial SDP version number + * - Bob's capability are added with more formats, and the + * stream order is interchanged to test the negotiator. + */ + + "RFC 4317 section 2.4: Audio and Telephone-Events (Bob's view)", + 1, + { + { + REMOTE_OFFER, + /* Received Alice's offer: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0 97\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "m=audio 49172 RTP/AVP 98\r\n" + "a=rtpmap:98 telephone-event/8000\r\n" + "a=sendonly\r\n", + /* Bob's initial capability: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49174 RTP/AVP 4 98\r\n" + "a=rtpmap:98 telephone-event/8000\r\n" + "m=audio 49172 RTP/AVP 97 8 99\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "a=rtpmap:99 telephone-event/8000\r\n", + /* Bob's answer should be: */ + "v=0\r\n" + "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49172 RTP/AVP 97\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "m=audio 49174 RTP/AVP 98\r\n" + "a=rtpmap:98 telephone-event/8000\r\n" + "a=recvonly\r\n" + } + } }, /* test 10: */ { - /********************************************************************* - * RFC 4317 Sample 2.6: Audio with Telephone-Events (Alice's view) - * - */ - - "RFC 4317 section 2.6: Audio with Telephone-Events (Alice's view)", - 1, - { - { - LOCAL_OFFER, - /* Alice sends offer: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 51372 RTP/AVP 97 101\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "a=rtpmap:101 telephone-event/8000\r\n", - /* Received bob's answer: */ - "v=0\r\n" - "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 0 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 49170 RTP/AVP 97 101\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "a=rtpmap:101 telephone-event/8000\r\n", - /* Alice's local SDP should be: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 0 RTP/AVP 0\r\n" - //"a=rtpmap:0 PCMU/8000\r\n" /* <-- this is not necessary (port 0) */ - "m=audio 51372 RTP/AVP 97 101\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "a=rtpmap:101 telephone-event/8000\r\n" - } - } + /********************************************************************* + * RFC 4317 Sample 2.6: Audio with Telephone-Events (Alice's view) + * + */ + + "RFC 4317 section 2.6: Audio with Telephone-Events (Alice's view)", + 1, + { + { + LOCAL_OFFER, + /* Alice sends offer: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 51372 RTP/AVP 97 101\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "a=rtpmap:101 telephone-event/8000\r\n", + /* Received bob's answer: */ + "v=0\r\n" + "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 0 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 49170 RTP/AVP 97 101\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "a=rtpmap:101 telephone-event/8000\r\n", + /* Alice's local SDP should be: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 0 RTP/AVP 0\r\n" + //"a=rtpmap:0 PCMU/8000\r\n" /* <-- this is not necessary (port 0) */ + "m=audio 51372 RTP/AVP 97 101\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "a=rtpmap:101 telephone-event/8000\r\n" + } + } }, /* test 11: */ { - /********************************************************************* - * RFC 4317 Sample 2.6: Audio with Telephone-Events (Bob's view) - * - * Difference: - * - Bob's SDP version number - * - Bob's initial capability are expanded with multiple m lines - * and more formats - */ - - "RFC 4317 section 2.6: Audio with Telephone-Events (Bob's view)", - 1, - { - { - REMOTE_OFFER, - /* Received Alice's offer: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 51372 RTP/AVP 97 101\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "a=rtpmap:101 telephone-event/8000\r\n", - /* Bob's initial capability also has video: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 4 97 101\r\n" - "a=rtpmap:4 G723/8000\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "a=rtpmap:101 telephone-event/8000\r\n" - "m=video 1000 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n", - /* Bob's answer should be: */ - "v=0\r\n" - "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 0 RTP/AVP 0\r\n" - //"a=rtpmap:0 PCMU/8000\r\n" /* <-- this is not necessary (port 0) */ - "m=audio 49170 RTP/AVP 97 101\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "a=rtpmap:101 telephone-event/8000\r\n", - } - } + /********************************************************************* + * RFC 4317 Sample 2.6: Audio with Telephone-Events (Bob's view) + * + * Difference: + * - Bob's SDP version number + * - Bob's initial capability are expanded with multiple m lines + * and more formats + */ + + "RFC 4317 section 2.6: Audio with Telephone-Events (Bob's view)", + 1, + { + { + REMOTE_OFFER, + /* Received Alice's offer: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 51372 RTP/AVP 97 101\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "a=rtpmap:101 telephone-event/8000\r\n", + /* Bob's initial capability also has video: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 4 97 101\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "a=rtpmap:101 telephone-event/8000\r\n" + "m=video 1000 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n", + /* Bob's answer should be: */ + "v=0\r\n" + "o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 0 RTP/AVP 0\r\n" + //"a=rtpmap:0 PCMU/8000\r\n" /* <-- this is not necessary (port 0) */ + "m=audio 49170 RTP/AVP 97 101\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "a=rtpmap:101 telephone-event/8000\r\n", + } + } }, /* test 12: */ { - /********************************************************************* - * Ticket #527: More lenient SDP negotiator. - */ - - "Ticket #527 scenario #1: Partial answer", - 1, - { - { - LOCAL_OFFER, - /* Alice sends offer audio and video: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 4000 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n", - /* Receive Bob's answer only audio: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n", - /* Alice's local SDP should be: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ - "", - } - } + /********************************************************************* + * Ticket #527: More lenient SDP negotiator. + */ + + "Ticket #527 scenario #1: Partial answer", + 1, + { + { + LOCAL_OFFER, + /* Alice sends offer audio and video: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 4000 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n", + /* Receive Bob's answer only audio: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n", + /* Alice's local SDP should be: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ + "", + } + } }, /* test 13: */ { - /********************************************************************* - * Ticket #527: More lenient SDP negotiator. - */ - - "Ticket #527 scenario #1: Media mismatch in answer", - 1, - { - { - LOCAL_OFFER, - /* Alice sends offer audio and video: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 3000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 4000 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n", - /* Receive Bob's answer two audio: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 49172 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n", - /* Alice's local SDP should be: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 3000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ - "", - } - } + /********************************************************************* + * Ticket #527: More lenient SDP negotiator. + */ + + "Ticket #527 scenario #1: Media mismatch in answer", + 1, + { + { + LOCAL_OFFER, + /* Alice sends offer audio and video: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 3000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 4000 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n", + /* Receive Bob's answer two audio: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 49172 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n", + /* Alice's local SDP should be: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 3000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ + "", + } + } }, /* test 14: */ { - /********************************************************************* - * Ticket #527: More lenient SDP negotiator. - */ - - "Ticket #527 scenario #2: Modify offer - partial streams", - 2, - { - { - LOCAL_OFFER, - /* Alice sends offer: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 3000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 3100 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 3200 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - /* Receive Bob's answer: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 4000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 4100 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 4200 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - /* Alice's local SDP should be: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 3000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 3100 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 3200 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - }, - { - LOCAL_OFFER, - /* Alice modifies offer with only specify one audio: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 5200 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "", - /* Receive Bob's answer: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 7000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 0 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - /* Alice's local SDP should be: */ - "v=0\r\n" - "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 5200 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 0 RTP/AVP 0\r\n" - //"a=rtpmap:0 PCMU/8000\r\n" /* <-- this is not necessary (port 0) */ - "m=video 0 RTP/AVP 31\r\n" - //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ - "", - } - } + /********************************************************************* + * Ticket #527: More lenient SDP negotiator. + */ + + "Ticket #527 scenario #2: Modify offer - partial streams", + 2, + { + { + LOCAL_OFFER, + /* Alice sends offer: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 3000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 3100 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 3200 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + /* Receive Bob's answer: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 4000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 4100 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 4200 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + /* Alice's local SDP should be: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 3000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 3100 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 3200 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + }, + { + LOCAL_OFFER, + /* Alice modifies offer with only specify one audio: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 5200 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "", + /* Receive Bob's answer: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 7000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 0 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + /* Alice's local SDP should be: */ + "v=0\r\n" + "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 5200 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 0 RTP/AVP 0\r\n" + //"a=rtpmap:0 PCMU/8000\r\n" /* <-- this is not necessary (port 0) */ + "m=video 0 RTP/AVP 31\r\n" + //"a=rtpmap:31 H261/90000\r\n" /* <-- this is not necessary (port 0) */ + "", + } + } }, /* test 15: */ { - /********************************************************************* - * Ticket #527: More lenient SDP negotiator. - */ - - "Ticket #527 scenario #2: Modify offer - unordered m= lines", - 2, - { - { - LOCAL_OFFER, - /* Alice sends offer: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 3000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 3200 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - /* Receive Bob's answer: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 4000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 4200 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - /* Alice's local SDP should be: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 3000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 3200 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - }, - { - LOCAL_OFFER, - /* Alice modifies offer with unordered m= lines: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=video 5000 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "m=audio 5200 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "", - /* Receive Bob's answer: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 7000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 2000 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - /* Alice's local SDP should be: */ - "v=0\r\n" - "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 5200 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 5000 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - } - } + /********************************************************************* + * Ticket #527: More lenient SDP negotiator. + */ + + "Ticket #527 scenario #2: Modify offer - unordered m= lines", + 2, + { + { + LOCAL_OFFER, + /* Alice sends offer: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 3000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 3200 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + /* Receive Bob's answer: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 4000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 4200 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + /* Alice's local SDP should be: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 3000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 3200 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + }, + { + LOCAL_OFFER, + /* Alice modifies offer with unordered m= lines: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=video 5000 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "m=audio 5200 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "", + /* Receive Bob's answer: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 7000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 2000 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + /* Alice's local SDP should be: */ + "v=0\r\n" + "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 5200 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 5000 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + } + } }, /* test 16: */ { - /********************************************************************* - * Ticket #527: More lenient SDP negotiator. - */ - - "Ticket #527 scenario #2: Modify offer - partial & unordered streams", - 2, - { - { - LOCAL_OFFER, - /* Alice sends offer: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 3000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 3200 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 3400 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - /* Receive Bob's answer: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 4000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 4200 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 4400 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - /* Alice's local SDP should be: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 3000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 3200 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 3400 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - }, - { - LOCAL_OFFER, - /* Alice modifies offer by specifying partial and unordered media: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=video 5000 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "m=audio 7000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "", - /* Receive Bob's answer: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 4000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 0 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 4400 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - /* Alice's local SDP should be: */ - "v=0\r\n" - "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 7000 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=audio 0 RTP/AVP 0\r\n" - //"a=rtpmap:0 PCMU/8000\r\n" /* <-- this is not necessary (port 0) */ - "m=video 5000 RTP/AVP 31\r\n" - "a=rtpmap:31 H261/90000\r\n" - "", - } - } + /********************************************************************* + * Ticket #527: More lenient SDP negotiator. + */ + + "Ticket #527 scenario #2: Modify offer - partial & unordered streams", + 2, + { + { + LOCAL_OFFER, + /* Alice sends offer: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 3000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 3200 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 3400 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + /* Receive Bob's answer: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 4000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 4200 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 4400 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + /* Alice's local SDP should be: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 3000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 3200 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 3400 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + }, + { + LOCAL_OFFER, + /* Alice modifies offer by specifying partial and unordered media: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=video 5000 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "m=audio 7000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "", + /* Receive Bob's answer: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 4000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 0 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 4400 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + /* Alice's local SDP should be: */ + "v=0\r\n" + "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 7000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=audio 0 RTP/AVP 0\r\n" + //"a=rtpmap:0 PCMU/8000\r\n" /* <-- this is not necessary (port 0) */ + "m=video 5000 RTP/AVP 31\r\n" + "a=rtpmap:31 H261/90000\r\n" + "", + } + } }, /* test 17: */ { - /********************************************************************* - * Ticket #2088: : Handle multiple telephone-event formats. - */ - - "Ticket #2088: Handle multiple telephone-event formats", - 2, - { - { - REMOTE_OFFER, - /* Bob sends offer: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 3000 RTP/AVP 97 0 98 99\r\n" - "a=rtpmap:97 Speex/16000\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:98 telephone-event/8000\r\n" - "a=rtpmap:99 telephone-event/16000\r\n" - "", - /* Alice initial capability: */ - "v=0\r\n" - "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 4000 RTP/AVP 0 100 96 98\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:100 Speex/16000\r\n" - "a=rtpmap:96 telephone-event/8000\r\n" - "a=rtpmap:98 telephone-event/16000\r\n" - "", - /* Alice's local SDP should be: */ - "v=0\r\n" - "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 4000 RTP/AVP 97 99\r\n" - "a=rtpmap:97 Speex/16000\r\n" - "a=rtpmap:99 telephone-event/16000\r\n" - "", - }, - { - LOCAL_OFFER, - /* Alice updates offer */ - "v=0\r\n" - "o=alice 2890844526 2890844528 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 4000 RTP/AVP 0 97 98 99\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=rtpmap:97 Speex/16000\r\n" - "a=rtpmap:98 telephone-event/8000\r\n" - "a=rtpmap:99 telephone-event/16000\r\n" - "", - /* Receive Bob's answer: */ - "v=0\r\n" - "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" - "s=bob\r\n" - "c=IN IP4 host.biloxi.example.com\r\n" - "t=0 0\r\n" - "m=audio 3000 RTP/AVP 99 100\r\n" - "a=rtpmap:99 Speex/16000\r\n" - "a=rtpmap:100 telephone-event/16000\r\n" - "", - /* Alice's local SDP should be: */ - "v=0\r\n" - "o=alice 2890844526 2890844528 IN IP4 host.atlanta.example.com\r\n" - "s=alice\r\n" - "c=IN IP4 host.atlanta.example.com\r\n" - "t=0 0\r\n" - "m=audio 4000 RTP/AVP 97 99\r\n" - "a=rtpmap:97 Speex/16000\r\n" - "a=rtpmap:99 telephone-event/16000\r\n" - "", - } - } + /********************************************************************* + * Ticket #2088: : Handle multiple telephone-event formats. + */ + + "Ticket #2088: Handle multiple telephone-event formats", + 2, + { + { + REMOTE_OFFER, + /* Bob sends offer: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 3000 RTP/AVP 97 0 98 99\r\n" + "a=rtpmap:97 Speex/16000\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:98 telephone-event/8000\r\n" + "a=rtpmap:99 telephone-event/16000\r\n" + "", + /* Alice initial capability: */ + "v=0\r\n" + "o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 4000 RTP/AVP 0 100 96 98\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:100 Speex/16000\r\n" + "a=rtpmap:96 telephone-event/8000\r\n" + "a=rtpmap:98 telephone-event/16000\r\n" + "", + /* Alice's local SDP should be: */ + "v=0\r\n" + "o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 4000 RTP/AVP 97 99\r\n" + "a=rtpmap:97 Speex/16000\r\n" + "a=rtpmap:99 telephone-event/16000\r\n" + "", + }, + { + LOCAL_OFFER, + /* Alice updates offer */ + "v=0\r\n" + "o=alice 2890844526 2890844528 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 4000 RTP/AVP 0 97 98 99\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:97 Speex/16000\r\n" + "a=rtpmap:98 telephone-event/8000\r\n" + "a=rtpmap:99 telephone-event/16000\r\n" + "", + /* Receive Bob's answer: */ + "v=0\r\n" + "o=bob 2808844564 2808844563 IN IP4 host.biloxi.example.com\r\n" + "s=bob\r\n" + "c=IN IP4 host.biloxi.example.com\r\n" + "t=0 0\r\n" + "m=audio 3000 RTP/AVP 99 100\r\n" + "a=rtpmap:99 Speex/16000\r\n" + "a=rtpmap:100 telephone-event/16000\r\n" + "", + /* Alice's local SDP should be: */ + "v=0\r\n" + "o=alice 2890844526 2890844528 IN IP4 host.atlanta.example.com\r\n" + "s=alice\r\n" + "c=IN IP4 host.atlanta.example.com\r\n" + "t=0 0\r\n" + "m=audio 4000 RTP/AVP 97 99\r\n" + "a=rtpmap:97 Speex/16000\r\n" + "a=rtpmap:99 telephone-event/16000\r\n" + "", + } + } }, }; static const char *find_diff(const char *s1, const char *s2, - int *line) + int *line) { *line = 1; while (*s2 && *s1) { - if (*s2 != *s1) - return s2; - if (*s2 == '\n') - ++*line; - ++s2, ++s1; + if (*s2 != *s1) + return s2; + if (*s2 == '\n') + ++*line; + ++s2, ++s1; } return s2; } static int compare_sdp_string(const char *cmp_title, - const char *title1, - const pjmedia_sdp_session *sdp1, - const char *title2, - const pjmedia_sdp_session *sdp2, - pj_status_t logical_cmp) + const char *title1, + const pjmedia_sdp_session *sdp1, + const char *title2, + const pjmedia_sdp_session *sdp2, + pj_status_t logical_cmp) { char sdpbuf1[1024], sdpbuf2[1024]; pj_ssize_t len1, len2; len1 = pjmedia_sdp_print(sdp1, sdpbuf1, sizeof(sdpbuf1)); if (len1 < 1) { - PJ_LOG(3,(THIS_FILE," error: printing sdp1")); - return -1; + PJ_LOG(3,(THIS_FILE," error: printing sdp1")); + return -1; } sdpbuf1[len1] = '\0'; len2 = pjmedia_sdp_print(sdp2, sdpbuf2, sizeof(sdpbuf2)); if (len2 < 1) { - PJ_LOG(3,(THIS_FILE," error: printing sdp2")); - return -1; + PJ_LOG(3,(THIS_FILE," error: printing sdp2")); + return -1; } sdpbuf2[len2] = '\0'; if (logical_cmp != PJ_SUCCESS) { - char errbuf[80]; + char errbuf[80]; - pjmedia_strerror(logical_cmp, errbuf, sizeof(errbuf)); + pjmedia_strerror(logical_cmp, errbuf, sizeof(errbuf)); - PJ_LOG(3,(THIS_FILE,"%s mismatch: %s\n" - "%s:\n" - "%s\n" - "%s:\n" - "%s\n", - cmp_title, - errbuf, - title1, sdpbuf1, - title2, sdpbuf2)); + PJ_LOG(3,(THIS_FILE,"%s mismatch: %s\n" + "%s:\n" + "%s\n" + "%s:\n" + "%s\n", + cmp_title, + errbuf, + title1, sdpbuf1, + title2, sdpbuf2)); - return -1; + return -1; } else if (strcmp(sdpbuf1, sdpbuf2) != 0) { - int line; - const char *diff; - - PJ_LOG(3,(THIS_FILE,"%s mismatch:\n" - "%s:\n" - "%s\n" - "%s:\n" - "%s\n", - cmp_title, - title1, sdpbuf1, - title2, sdpbuf2)); - - diff = find_diff(sdpbuf1, sdpbuf2, &line); - PJ_LOG(3,(THIS_FILE,"Difference: line %d:\n" - "%s", - line, diff)); - return -1; + int line; + const char *diff; + + PJ_LOG(3,(THIS_FILE,"%s mismatch:\n" + "%s:\n" + "%s\n" + "%s:\n" + "%s\n", + cmp_title, + title1, sdpbuf1, + title2, sdpbuf2)); + + diff = find_diff(sdpbuf1, sdpbuf2, &line); + PJ_LOG(3,(THIS_FILE,"Difference: line %d:\n" + "%s", + line, diff)); + return -1; } else { - return 0; + return 0; } } static int offer_answer_test(pj_pool_t *pool, pjmedia_sdp_neg **p_neg, - struct offer_answer *oa) + struct offer_answer *oa) { pjmedia_sdp_session *sdp1; pjmedia_sdp_neg *neg; pj_status_t status; status = pjmedia_sdp_parse(pool, oa->sdp1, pj_ansi_strlen(oa->sdp1), - &sdp1); + &sdp1); if (status != PJ_SUCCESS) { - app_perror(status, " error: unexpected parse status for sdp1"); - return -10; + app_perror(status, " error: unexpected parse status for sdp1"); + return -10; } status = pjmedia_sdp_validate(sdp1); if (status != PJ_SUCCESS) { - app_perror(status, " error: sdp1 validation failed"); - return -15; + app_perror(status, " error: sdp1 validation failed"); + return -15; } neg = *p_neg; if (oa->type == LOCAL_OFFER) { - - /* - * Local creates offer first. - */ - pjmedia_sdp_session *sdp2, *sdp3; - const pjmedia_sdp_session *active; - - if (neg == NULL) { - /* Create negotiator with local offer. */ - status = pjmedia_sdp_neg_create_w_local_offer(pool, sdp1, &neg); - if (status != PJ_SUCCESS) { - app_perror(status, " error: pjmedia_sdp_neg_create_w_local_offer"); - return -20; - } - *p_neg = neg; - - } else { - /* Modify local offer */ - status = pjmedia_sdp_neg_modify_local_offer(pool, neg, sdp1); - if (status != PJ_SUCCESS) { - app_perror(status, " error: pjmedia_sdp_neg_modify_local_offer"); - return -30; - } - } - - /* Parse and validate remote answer */ - status = pjmedia_sdp_parse(pool, oa->sdp2, pj_ansi_strlen(oa->sdp2), - &sdp2); - if (status != PJ_SUCCESS) { - app_perror(status, " error: parsing sdp2"); - return -40; - } - - status = pjmedia_sdp_validate(sdp2); - if (status != PJ_SUCCESS) { - app_perror(status, " error: sdp2 validation failed"); - return -50; - } - - /* Give the answer to negotiator. */ - status = pjmedia_sdp_neg_set_remote_answer(pool, neg, sdp2); - if (status != PJ_SUCCESS) { - app_perror(status, " error: pjmedia_sdp_neg_rx_remote_answer"); - return -60; - } - - /* Negotiate remote answer with local answer */ - status = pjmedia_sdp_neg_negotiate(pool, neg, 0); - if (status != PJ_SUCCESS) { - app_perror(status, " error: pjmedia_sdp_neg_negotiate"); - return -70; - } - - /* Get the local active media. */ - status = pjmedia_sdp_neg_get_active_local(neg, &active); - if (status != PJ_SUCCESS) { - app_perror(status, " error: pjmedia_sdp_neg_get_local"); - return -80; - } - - /* Parse and validate the correct active media. */ - status = pjmedia_sdp_parse(pool, oa->sdp3, pj_ansi_strlen(oa->sdp3), - &sdp3); - if (status != PJ_SUCCESS) { - app_perror(status, " error: parsing sdp3"); - return -90; - } - - status = pjmedia_sdp_validate(sdp3); - if (status != PJ_SUCCESS) { - app_perror(status, " error: sdp3 validation failed"); - return -100; - } - - /* Compare active with sdp3 */ - status = pjmedia_sdp_session_cmp(active, sdp3, 0); - if (status != PJ_SUCCESS) { - app_perror(status, " error: active local comparison mismatch"); - compare_sdp_string("Logical cmp after negotiatin remote answer", - "Active local sdp from negotiator", active, - "The correct active local sdp", sdp3, - status); - return -110; - } - - /* Compare the string representation oa both sdps */ - status = compare_sdp_string("String cmp after negotiatin remote answer", - "Active local sdp from negotiator", active, - "The correct active local sdp", sdp3, - PJ_SUCCESS); - if (status != 0) - return -120; + + /* + * Local creates offer first. + */ + pjmedia_sdp_session *sdp2, *sdp3; + const pjmedia_sdp_session *active; + + if (neg == NULL) { + /* Create negotiator with local offer. */ + status = pjmedia_sdp_neg_create_w_local_offer(pool, sdp1, &neg); + if (status != PJ_SUCCESS) { + app_perror(status, " error: pjmedia_sdp_neg_create_w_local_offer"); + return -20; + } + *p_neg = neg; + + } else { + /* Modify local offer */ + status = pjmedia_sdp_neg_modify_local_offer(pool, neg, sdp1); + if (status != PJ_SUCCESS) { + app_perror(status, " error: pjmedia_sdp_neg_modify_local_offer"); + return -30; + } + } + + /* Parse and validate remote answer */ + status = pjmedia_sdp_parse(pool, oa->sdp2, pj_ansi_strlen(oa->sdp2), + &sdp2); + if (status != PJ_SUCCESS) { + app_perror(status, " error: parsing sdp2"); + return -40; + } + + status = pjmedia_sdp_validate(sdp2); + if (status != PJ_SUCCESS) { + app_perror(status, " error: sdp2 validation failed"); + return -50; + } + + /* Give the answer to negotiator. */ + status = pjmedia_sdp_neg_set_remote_answer(pool, neg, sdp2); + if (status != PJ_SUCCESS) { + app_perror(status, " error: pjmedia_sdp_neg_rx_remote_answer"); + return -60; + } + + /* Negotiate remote answer with local answer */ + status = pjmedia_sdp_neg_negotiate(pool, neg, 0); + if (status != PJ_SUCCESS) { + app_perror(status, " error: pjmedia_sdp_neg_negotiate"); + return -70; + } + + /* Get the local active media. */ + status = pjmedia_sdp_neg_get_active_local(neg, &active); + if (status != PJ_SUCCESS) { + app_perror(status, " error: pjmedia_sdp_neg_get_local"); + return -80; + } + + /* Parse and validate the correct active media. */ + status = pjmedia_sdp_parse(pool, oa->sdp3, pj_ansi_strlen(oa->sdp3), + &sdp3); + if (status != PJ_SUCCESS) { + app_perror(status, " error: parsing sdp3"); + return -90; + } + + status = pjmedia_sdp_validate(sdp3); + if (status != PJ_SUCCESS) { + app_perror(status, " error: sdp3 validation failed"); + return -100; + } + + /* Compare active with sdp3 */ + status = pjmedia_sdp_session_cmp(active, sdp3, 0); + if (status != PJ_SUCCESS) { + app_perror(status, " error: active local comparison mismatch"); + compare_sdp_string("Logical cmp after negotiatin remote answer", + "Active local sdp from negotiator", active, + "The correct active local sdp", sdp3, + status); + return -110; + } + + /* Compare the string representation oa both sdps */ + status = compare_sdp_string("String cmp after negotiatin remote answer", + "Active local sdp from negotiator", active, + "The correct active local sdp", sdp3, + PJ_SUCCESS); + if (status != 0) + return -120; } else { - /* - * Remote creates offer first. - */ - - pjmedia_sdp_session *sdp2 = NULL, *sdp3; - const pjmedia_sdp_session *answer; - - if (oa->sdp2) { - /* Parse and validate initial local capability */ - status = pjmedia_sdp_parse(pool, oa->sdp2, pj_ansi_strlen(oa->sdp2), - &sdp2); - if (status != PJ_SUCCESS) { - app_perror(status, " error: parsing sdp2"); - return -200; - } - - status = pjmedia_sdp_validate(sdp2); - if (status != PJ_SUCCESS) { - app_perror(status, " error: sdp2 validation failed"); - return -210; - } - } else if (neg) { - const pjmedia_sdp_session *lsdp; - status = pjmedia_sdp_neg_get_active_local(neg, &lsdp); - if (status != PJ_SUCCESS) { - app_perror(status, - " error: pjmedia_sdp_neg_get_active_local"); - return -215; - } - sdp2 = (pjmedia_sdp_session*)lsdp; - } - - if (neg == NULL) { - /* Create negotiator with remote offer. */ - status = pjmedia_sdp_neg_create_w_remote_offer(pool, sdp2, sdp1, &neg); - if (status != PJ_SUCCESS) { - app_perror(status, " error: pjmedia_sdp_neg_create_w_remote_offer"); - return -220; - } - *p_neg = neg; - - } else { - /* Received subsequent offer from remote. */ - status = pjmedia_sdp_neg_set_remote_offer(pool, neg, sdp1); - if (status != PJ_SUCCESS) { - app_perror(status, " error: pjmedia_sdp_neg_rx_remote_offer"); - return -230; - } - - status = pjmedia_sdp_neg_set_local_answer(pool, neg, sdp2); - if (status != PJ_SUCCESS) { - app_perror(status, " error: pjmedia_sdp_neg_set_local_answer"); - return -235; - } - } - - /* Negotiate. */ - status = pjmedia_sdp_neg_negotiate(pool, neg, 0); - if (status != PJ_SUCCESS) { - app_perror(status, " error: pjmedia_sdp_neg_negotiate"); - return -240; - } - - /* Get our answer. */ - status = pjmedia_sdp_neg_get_active_local(neg, &answer); - if (status != PJ_SUCCESS) { - app_perror(status, " error: pjmedia_sdp_neg_get_local"); - return -250; - } - - /* Parse the correct answer. */ - status = pjmedia_sdp_parse(pool, oa->sdp3, pj_ansi_strlen(oa->sdp3), - &sdp3); - if (status != PJ_SUCCESS) { - app_perror(status, " error: parsing sdp3"); - return -260; - } - - /* Validate the correct answer. */ - status = pjmedia_sdp_validate(sdp3); - if (status != PJ_SUCCESS) { - app_perror(status, " error: sdp3 validation failed"); - return -270; - } - - /* Compare answer from negotiator and the correct answer */ - status = pjmedia_sdp_session_cmp(sdp3, answer, 0); - if (status != PJ_SUCCESS) { - compare_sdp_string("Logical cmp after negotiating remote offer", - "Local answer from negotiator", answer, - "The correct local answer", sdp3, - status); - - return -280; - } - - /* Compare the string representation oa both answers */ - status = compare_sdp_string("String cmp after negotiating remote offer", - "Local answer from negotiator", answer, - "The correct local answer", sdp3, - PJ_SUCCESS); - if (status != 0) - return -290; + /* + * Remote creates offer first. + */ + + pjmedia_sdp_session *sdp2 = NULL, *sdp3; + const pjmedia_sdp_session *answer; + + if (oa->sdp2) { + /* Parse and validate initial local capability */ + status = pjmedia_sdp_parse(pool, oa->sdp2, pj_ansi_strlen(oa->sdp2), + &sdp2); + if (status != PJ_SUCCESS) { + app_perror(status, " error: parsing sdp2"); + return -200; + } + + status = pjmedia_sdp_validate(sdp2); + if (status != PJ_SUCCESS) { + app_perror(status, " error: sdp2 validation failed"); + return -210; + } + } else if (neg) { + const pjmedia_sdp_session *lsdp; + status = pjmedia_sdp_neg_get_active_local(neg, &lsdp); + if (status != PJ_SUCCESS) { + app_perror(status, + " error: pjmedia_sdp_neg_get_active_local"); + return -215; + } + sdp2 = (pjmedia_sdp_session*)lsdp; + } + + if (neg == NULL) { + /* Create negotiator with remote offer. */ + status = pjmedia_sdp_neg_create_w_remote_offer(pool, sdp2, sdp1, &neg); + if (status != PJ_SUCCESS) { + app_perror(status, " error: pjmedia_sdp_neg_create_w_remote_offer"); + return -220; + } + *p_neg = neg; + + } else { + /* Received subsequent offer from remote. */ + status = pjmedia_sdp_neg_set_remote_offer(pool, neg, sdp1); + if (status != PJ_SUCCESS) { + app_perror(status, " error: pjmedia_sdp_neg_rx_remote_offer"); + return -230; + } + + status = pjmedia_sdp_neg_set_local_answer(pool, neg, sdp2); + if (status != PJ_SUCCESS) { + app_perror(status, " error: pjmedia_sdp_neg_set_local_answer"); + return -235; + } + } + + /* Negotiate. */ + status = pjmedia_sdp_neg_negotiate(pool, neg, 0); + if (status != PJ_SUCCESS) { + app_perror(status, " error: pjmedia_sdp_neg_negotiate"); + return -240; + } + + /* Get our answer. */ + status = pjmedia_sdp_neg_get_active_local(neg, &answer); + if (status != PJ_SUCCESS) { + app_perror(status, " error: pjmedia_sdp_neg_get_local"); + return -250; + } + + /* Parse the correct answer. */ + status = pjmedia_sdp_parse(pool, oa->sdp3, pj_ansi_strlen(oa->sdp3), + &sdp3); + if (status != PJ_SUCCESS) { + app_perror(status, " error: parsing sdp3"); + return -260; + } + + /* Validate the correct answer. */ + status = pjmedia_sdp_validate(sdp3); + if (status != PJ_SUCCESS) { + app_perror(status, " error: sdp3 validation failed"); + return -270; + } + + /* Compare answer from negotiator and the correct answer */ + status = pjmedia_sdp_session_cmp(sdp3, answer, 0); + if (status != PJ_SUCCESS) { + compare_sdp_string("Logical cmp after negotiating remote offer", + "Local answer from negotiator", answer, + "The correct local answer", sdp3, + status); + + return -280; + } + + /* Compare the string representation oa both answers */ + status = compare_sdp_string("String cmp after negotiating remote offer", + "Local answer from negotiator", answer, + "The correct local answer", sdp3, + PJ_SUCCESS); + if (status != 0) + return -290; } @@ -1646,12 +1645,12 @@ static int perform_test(pj_pool_t *pool, int test_index) for (i=0; i @@ -69,10 +68,10 @@ static int sdp_perform_test(pj_pool_factory *pf) inputlen = strlen(sdp[0]); pj_gettimeofday(&start); for (i=0; i @@ -82,41 +81,41 @@ pj_status_t session_test (pj_pool_factory *pf) // Wait for (;;) { - int has_stat; - - printf("Enter q to exit, 1 or 2 to print statistics.\n"); - fgets (buf, 10, stdin); - has_stat = 0; - - switch (buf[0]) { - case 'q': - case 'Q': - goto done; - break; - case '1': - pj_media_session_get_stat (s1, 0, &tx_stat, &rx_stat); - has_stat = 1; - break; - case '2': - pj_media_session_get_stat (s2, 0, &tx_stat, &rx_stat); - has_stat = 1; - break; - } - - if (has_stat) { - pj_media_stream_stat *stat[2] = { &tx_stat, &rx_stat }; - const char *statname[2] = { "TX", "RX" }; - int i; - - for (i=0; i<2; ++i) { - printf("%s statistics:\n", statname[i]); - printf(" Pkt TX=%d RX=%d\n", stat[i]->pkt_tx, stat[i]->pkt_rx); - printf(" Octets TX=%d RX=%d\n", stat[i]->oct_tx, stat[i]->oct_rx); - printf(" Jitter %d ms\n", stat[i]->jitter); - printf(" Pkt lost %d\n", stat[i]->pkt_lost); - } - printf("\n"); - } + int has_stat; + + printf("Enter q to exit, 1 or 2 to print statistics.\n"); + fgets (buf, 10, stdin); + has_stat = 0; + + switch (buf[0]) { + case 'q': + case 'Q': + goto done; + break; + case '1': + pj_media_session_get_stat (s1, 0, &tx_stat, &rx_stat); + has_stat = 1; + break; + case '2': + pj_media_session_get_stat (s2, 0, &tx_stat, &rx_stat); + has_stat = 1; + break; + } + + if (has_stat) { + pj_media_stream_stat *stat[2] = { &tx_stat, &rx_stat }; + const char *statname[2] = { "TX", "RX" }; + int i; + + for (i=0; i<2; ++i) { + printf("%s statistics:\n", statname[i]); + printf(" Pkt TX=%d RX=%d\n", stat[i]->pkt_tx, stat[i]->pkt_rx); + printf(" Octets TX=%d RX=%d\n", stat[i]->oct_tx, stat[i]->oct_rx); + printf(" Jitter %d ms\n", stat[i]->jitter); + printf(" Pkt lost %d\n", stat[i]->pkt_lost); + } + printf("\n"); + } } done: diff --git a/pjmedia/src/test/test.c b/pjmedia/src/test/test.c index bf87fbc8f1..5023bdf6f0 100644 --- a/pjmedia/src/test/test.c +++ b/pjmedia/src/test/test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,14 +20,14 @@ #define THIS_FILE "test.c" -#define DO_TEST(test) do { \ - PJ_LOG(3, (THIS_FILE, "Running %s...", #test)); \ - rc = test; \ - PJ_LOG(3, (THIS_FILE, \ - "%s(%d)", \ - (rc ? "..ERROR" : "..success"), rc)); \ - if (rc!=0) goto on_return; \ - } while (0) +#define DO_TEST(test) do { \ + PJ_LOG(3, (THIS_FILE, "Running %s...", #test)); \ + rc = test; \ + PJ_LOG(3, (THIS_FILE, \ + "%s(%d)", \ + (rc ? "..ERROR" : "..success"), rc)); \ + if (rc!=0) goto on_return; \ + } while (0) pj_pool_factory *mem; @@ -65,7 +64,7 @@ int test_main(void) pool = pj_pool_create(&caching_pool.factory, "test", 1000, 512, NULL); pj_log_set_decor(PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_TIME | - PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_INDENT); + PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_INDENT); pj_log_set_level(3); mem = &caching_pool.factory; @@ -110,9 +109,9 @@ int test_main(void) on_return: if (rc != 0) { - PJ_LOG(3,(THIS_FILE,"Test completed with error(s)!")); + PJ_LOG(3,(THIS_FILE,"Test completed with error(s)!")); } else { - PJ_LOG(3,(THIS_FILE,"Looks like everything is okay!")); + PJ_LOG(3,(THIS_FILE,"Looks like everything is okay!")); } #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) diff --git a/pjmedia/src/test/test.h b/pjmedia/src/test/test.h index f0212d69ae..a4d2b48dcc 100644 --- a/pjmedia/src/test/test.h +++ b/pjmedia/src/test/test.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,20 +23,20 @@ #include #if defined(PJ_EXCLUDE_BENCHMARK_TESTS) && (PJ_EXCLUDE_BENCHMARK_TESTS==1) -# define WITH_BENCHMARK 0 +# define WITH_BENCHMARK 0 #else -# define WITH_BENCHMARK 1 +# define WITH_BENCHMARK 1 #endif -#define HAS_VID_DEV_TEST PJMEDIA_HAS_VIDEO -#define HAS_VID_PORT_TEST PJMEDIA_HAS_VIDEO +#define HAS_VID_DEV_TEST PJMEDIA_HAS_VIDEO +#define HAS_VID_PORT_TEST PJMEDIA_HAS_VIDEO #ifndef HAS_VID_CODEC_TEST - #define HAS_VID_CODEC_TEST PJMEDIA_HAS_VIDEO + #define HAS_VID_CODEC_TEST PJMEDIA_HAS_VIDEO #endif -#define HAS_SDP_NEG_TEST 1 -#define HAS_JBUF_TEST 1 -#define HAS_MIPS_TEST WITH_BENCHMARK -#define HAS_CODEC_VECTOR_TEST 1 +#define HAS_SDP_NEG_TEST 1 +#define HAS_JBUF_TEST 1 +#define HAS_MIPS_TEST WITH_BENCHMARK +#define HAS_CODEC_VECTOR_TEST 1 int session_test(void); int rtp_test(void); @@ -55,4 +54,4 @@ void app_perror(pj_status_t status, const char *title); int test_main(void); -#endif /* __PJMEDIA_TEST_H__ */ +#endif /* __PJMEDIA_TEST_H__ */ diff --git a/pjmedia/src/test/vectors/swapendian.c b/pjmedia/src/test/vectors/swapendian.c index 014fd91681..077136e9a1 100644 --- a/pjmedia/src/test/vectors/swapendian.c +++ b/pjmedia/src/test/vectors/swapendian.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -26,40 +25,40 @@ int main(int argc, char *argv[]) unsigned count; if (argc != 3) { - puts("Usage: swapendian input.pcm OUTPUT.PCM"); - return 1; + puts("Usage: swapendian input.pcm OUTPUT.PCM"); + return 1; } in = fopen(argv[1], "rb"); if (!in) { - puts("Open error"); - return 1; + puts("Open error"); + return 1; } out = fopen(argv[2], "wb"); if (!out) { - puts("Open error"); - fclose(in); - return 1; + puts("Open error"); + fclose(in); + return 1; } count = 0; for (;;) { - char tmp; + char tmp; - if (fread(frm, 2, 1, in) != 1) - break; + if (fread(frm, 2, 1, in) != 1) + break; - tmp = frm[0]; - frm[0] = frm[1]; - frm[1] = tmp; + tmp = frm[0]; + frm[0] = frm[1]; + frm[1] = tmp; - if (fwrite(frm, 2, 1, out) != 1) { - puts("Write error"); - break; - } + if (fwrite(frm, 2, 1, out) != 1) { + puts("Write error"); + break; + } - ++count; + ++count; } printf("%d samples converted\n", count); diff --git a/pjmedia/src/test/vid_codec_test.c b/pjmedia/src/test/vid_codec_test.c index 4aca8b6939..466657b41a 100644 --- a/pjmedia/src/test/vid_codec_test.c +++ b/pjmedia/src/test/vid_codec_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011 Teluu Inc. (http://www.teluu.com) * @@ -34,7 +33,7 @@ * -2 = any non-colorbar capture device (first found) * x = specified capture device id */ -#define CAPTURE_DEV -1 +#define CAPTURE_DEV -1 typedef struct codec_port_data_t @@ -53,27 +52,27 @@ static pj_status_t codec_on_event(pjmedia_event *event, codec_port_data_t *port_data = (codec_port_data_t*)user_data; if (event->type == PJMEDIA_EVENT_FMT_CHANGED) { - pjmedia_vid_codec *codec = port_data->codec; - pjmedia_vid_codec_param codec_param; - pj_status_t status; - - status = pjmedia_vid_codec_get_param(codec, &codec_param); - if (status != PJ_SUCCESS) - return status; - - status = pjmedia_vid_dev_stream_set_cap( - pjmedia_vid_port_get_stream(port_data->rdr_port), - PJMEDIA_VID_DEV_CAP_FORMAT, - &codec_param.dec_fmt); - if (status != PJ_SUCCESS) - return status; + pjmedia_vid_codec *codec = port_data->codec; + pjmedia_vid_codec_param codec_param; + pj_status_t status; + + status = pjmedia_vid_codec_get_param(codec, &codec_param); + if (status != PJ_SUCCESS) + return status; + + status = pjmedia_vid_dev_stream_set_cap( + pjmedia_vid_port_get_stream(port_data->rdr_port), + PJMEDIA_VID_DEV_CAP_FORMAT, + &codec_param.dec_fmt); + if (status != PJ_SUCCESS) + return status; } return PJ_SUCCESS; } static pj_status_t codec_put_frame(pjmedia_port *port, - pjmedia_frame *frame) + pjmedia_frame *frame) { enum { MAX_PACKETS = 50 }; codec_port_data_t *port_data = (codec_port_data_t*)port->port_data.pdata; @@ -103,37 +102,37 @@ static pj_status_t codec_put_frame(pjmedia_port *port, ++enc_cnt; while (has_more) { - enc_frames[enc_cnt].buf = enc_buf; - enc_frames[enc_cnt].size = enc_size_left; + enc_frames[enc_cnt].buf = enc_buf; + enc_frames[enc_cnt].size = enc_size_left; - status = pjmedia_vid_codec_encode_more(codec, enc_size_left, - &enc_frames[enc_cnt], - &has_more); - if (status != PJ_SUCCESS) - break; + status = pjmedia_vid_codec_encode_more(codec, enc_size_left, + &enc_frames[enc_cnt], + &has_more); + if (status != PJ_SUCCESS) + break; - enc_buf += enc_frames[enc_cnt].size; - enc_size_left -= (unsigned)enc_frames[enc_cnt].size; + enc_buf += enc_frames[enc_cnt].size; + enc_size_left -= (unsigned)enc_frames[enc_cnt].size; - ++enc_cnt; + ++enc_cnt; - if (enc_cnt >= MAX_PACKETS) { - assert(!"Too many packets!"); - break; - } + if (enc_cnt >= MAX_PACKETS) { + assert(!"Too many packets!"); + break; + } } /* * Decode */ status = pjmedia_vid_codec_decode(codec, enc_cnt, enc_frames, - (unsigned)frame->size, frame); + (unsigned)frame->size, frame); if (status != PJ_SUCCESS) goto on_error; /* Display */ status = pjmedia_port_put_frame( - pjmedia_vid_port_get_passive_port(port_data->rdr_port), - frame); + pjmedia_vid_port_get_passive_port(port_data->rdr_port), + frame); if (status != PJ_SUCCESS) goto on_error; return PJ_SUCCESS; @@ -204,18 +203,18 @@ static int encode_decode_test(pj_pool_t *pool, const char *codec_id, switch (packing) { case PJMEDIA_VID_PACKING_PACKETS: - packing_name = "framed"; - break; + packing_name = "framed"; + break; case PJMEDIA_VID_PACKING_WHOLE: - packing_name = "whole"; - break; + packing_name = "whole"; + break; default: - packing_name = "unknown"; - break; + packing_name = "unknown"; + break; } PJ_LOG(3, (THIS_FILE, " encode decode test: codec=%s, packing=%s", - codec_id, packing_name)); + codec_id, packing_name)); /* Lookup codec */ { @@ -237,33 +236,33 @@ static int encode_decode_test(pj_pool_t *pool, const char *codec_id, /* Lookup colorbar source */ status = pjmedia_vid_dev_lookup("Colorbar", "Colorbar generator", &cap_idx); if (status != PJ_SUCCESS) { - rc = 206; goto on_return; + rc = 206; goto on_return; } #elif CAPTURE_DEV == -2 /* Lookup any first non-colorbar source */ { - unsigned i, cnt; - pjmedia_vid_dev_info info; - - cap_idx = -1; - cnt = pjmedia_vid_dev_count(); - for (i = 0; i < cnt; ++i) { - status = pjmedia_vid_dev_get_info(i, &info); - if (status != PJ_SUCCESS) { - rc = 206; goto on_return; - } - if (info.dir & PJMEDIA_DIR_CAPTURE && - pj_ansi_stricmp(info.driver, "Colorbar")) - { - cap_idx = i; - break; - } - } - - if (cap_idx == -1) { - status = PJ_ENOTFOUND; - rc = 206; goto on_return; - } + unsigned i, cnt; + pjmedia_vid_dev_info info; + + cap_idx = -1; + cnt = pjmedia_vid_dev_count(); + for (i = 0; i < cnt; ++i) { + status = pjmedia_vid_dev_get_info(i, &info); + if (status != PJ_SUCCESS) { + rc = 206; goto on_return; + } + if (info.dir & PJMEDIA_DIR_CAPTURE && + pj_ansi_stricmp(info.driver, "Colorbar")) + { + cap_idx = i; + break; + } + } + + if (cap_idx == -1) { + status = PJ_ENOTFOUND; + rc = 206; goto on_return; + } } #else cap_idx = CAPTURE_DEV; @@ -272,7 +271,7 @@ static int encode_decode_test(pj_pool_t *pool, const char *codec_id, /* Lookup SDL renderer */ status = pjmedia_vid_dev_lookup("SDL", "SDL renderer", &rdr_idx); if (status != PJ_SUCCESS) { - rc = 207; goto on_return; + rc = 207; goto on_return; } /* Prepare codec */ @@ -303,26 +302,26 @@ static int encode_decode_test(pj_pool_t *pool, const char *codec_id, status = pjmedia_vid_codec_mgr_alloc_codec(NULL, codec_info, &codec); if (status != PJ_SUCCESS) { - rc = 250; goto on_return; + rc = 250; goto on_return; } status = pjmedia_vid_codec_init(codec, pool); if (status != PJ_SUCCESS) { - rc = 251; goto on_return; + rc = 251; goto on_return; } status = pjmedia_vid_codec_open(codec, &codec_param); if (status != PJ_SUCCESS) { - rc = 252; goto on_return; + rc = 252; goto on_return; } - /* After opened, codec will update the param, let's sync encoder & - * decoder format detail. - */ - codec_param.dec_fmt.det = codec_param.enc_fmt.det; + /* After opened, codec will update the param, let's sync encoder & + * decoder format detail. + */ + codec_param.dec_fmt.det = codec_param.enc_fmt.det; - /* Subscribe to codec events */ - pjmedia_event_subscribe(NULL, &codec_on_event, &codec_port_data, + /* Subscribe to codec events */ + pjmedia_event_subscribe(NULL, &codec_on_event, &codec_port_data, codec); } @@ -330,27 +329,27 @@ static int encode_decode_test(pj_pool_t *pool, const char *codec_id, /* Create capture, set it to active (master) */ status = pjmedia_vid_dev_default_param(pool, cap_idx, - &vport_param.vidparam); + &vport_param.vidparam); if (status != PJ_SUCCESS) { - rc = 220; goto on_return; + rc = 220; goto on_return; } pjmedia_format_copy(&vport_param.vidparam.fmt, &codec_param.dec_fmt); vport_param.vidparam.dir = PJMEDIA_DIR_CAPTURE; vport_param.active = PJ_TRUE; if (vport_param.vidparam.fmt.detail_type != PJMEDIA_FORMAT_DETAIL_VIDEO) { - rc = 221; goto on_return; + rc = 221; goto on_return; } vfd = pjmedia_format_get_video_format_detail(&vport_param.vidparam.fmt, - PJ_TRUE); + PJ_TRUE); if (vfd == NULL) { - rc = 225; goto on_return; + rc = 225; goto on_return; } status = pjmedia_vid_port_create(pool, &vport_param, &capture); if (status != PJ_SUCCESS) { - rc = 226; goto on_return; + rc = 226; goto on_return; } /* Create renderer, set it to passive (slave) */ @@ -361,7 +360,7 @@ static int encode_decode_test(pj_pool_t *pool, const char *codec_id, status = pjmedia_vid_port_create(pool, &vport_param, &renderer); if (status != PJ_SUCCESS) { - rc = 230; goto on_return; + rc = 230; goto on_return; } /* Init codec port */ @@ -370,34 +369,34 @@ static int encode_decode_test(pj_pool_t *pool, const char *codec_id, PJMEDIA_DIR_ENCODING, &codec_param.dec_fmt); if (status != PJ_SUCCESS) { - rc = 260; goto on_return; + rc = 260; goto on_return; } codec_port_data.codec = codec; codec_port_data.rdr_port = renderer; codec_port_data.enc_buf_size = codec_param.dec_fmt.det.vid.size.w * - codec_param.dec_fmt.det.vid.size.h * 4; + codec_param.dec_fmt.det.vid.size.h * 4; codec_port_data.enc_buf = pj_pool_alloc(pool, - codec_port_data.enc_buf_size); + codec_port_data.enc_buf_size); codec_port_data.pack_buf_size = codec_port_data.enc_buf_size; codec_port_data.pack_buf = pj_pool_alloc(pool, - codec_port_data.pack_buf_size); + codec_port_data.pack_buf_size); codec_port.put_frame = &codec_put_frame; codec_port.port_data.pdata = &codec_port_data; /* Connect capture to codec port */ status = pjmedia_vid_port_connect(capture, - &codec_port, - PJ_FALSE); + &codec_port, + PJ_FALSE); if (status != PJ_SUCCESS) { - rc = 270; goto on_return; + rc = 270; goto on_return; } PJ_LOG(3, (THIS_FILE, " starting codec test: %s<->%.*s %dx%d", - pjmedia_fourcc_name(codec_param.dec_fmt.id, codec_name), - codec_info->encoding_name.slen, - codec_info->encoding_name.ptr, + pjmedia_fourcc_name(codec_param.dec_fmt.id, codec_name), + codec_info->encoding_name.slen, + codec_info->encoding_name.ptr, codec_param.dec_fmt.det.vid.size.w, codec_param.dec_fmt.det.vid.size.h )); @@ -405,11 +404,11 @@ static int encode_decode_test(pj_pool_t *pool, const char *codec_id, /* Start streaming.. */ status = pjmedia_vid_port_start(renderer); if (status != PJ_SUCCESS) { - rc = 275; goto on_return; + rc = 275; goto on_return; } status = pjmedia_vid_port_start(capture); if (status != PJ_SUCCESS) { - rc = 280; goto on_return; + rc = 280; goto on_return; } /* Sleep while the video is being displayed... */ @@ -424,11 +423,11 @@ static int encode_decode_test(pj_pool_t *pool, const char *codec_id, if (renderer) pjmedia_vid_port_stop(renderer); if (capture) - pjmedia_vid_port_destroy(capture); + pjmedia_vid_port_destroy(capture); if (renderer) - pjmedia_vid_port_destroy(renderer); + pjmedia_vid_port_destroy(renderer); if (codec) { - pjmedia_event_unsubscribe(NULL, &codec_on_event, &codec_port_data, + pjmedia_event_unsubscribe(NULL, &codec_on_event, &codec_port_data, codec); pjmedia_vid_codec_close(codec); pjmedia_vid_codec_mgr_dealloc_codec(NULL, codec); @@ -458,21 +457,21 @@ int vid_codec_test(void) #if PJMEDIA_HAS_VIDEO && PJMEDIA_HAS_OPENH264_CODEC status = pjmedia_codec_openh264_vid_init(NULL, mem); if (status != PJ_SUCCESS) { - return -22; + return -22; } #endif #if PJMEDIA_HAS_VIDEO && PJMEDIA_HAS_VID_TOOLBOX_CODEC status = pjmedia_codec_vid_toolbox_init(NULL, mem); if (status != PJ_SUCCESS) { - return -23; + return -23; } #endif #if PJMEDIA_HAS_VIDEO && PJMEDIA_HAS_VPX_CODEC status = pjmedia_codec_vpx_vid_init(NULL, mem); if (status != PJ_SUCCESS) { - return -22; + return -22; } #endif @@ -484,16 +483,16 @@ int vid_codec_test(void) rc = enum_codecs(); if (rc != 0) - goto on_return; + goto on_return; #if PJMEDIA_HAS_FFMPEG_VID_CODEC rc = encode_decode_test(pool, "h263-1998", PJMEDIA_VID_PACKING_WHOLE); if (rc != 0) - goto on_return; + goto on_return; rc = encode_decode_test(pool, "h263-1998", PJMEDIA_VID_PACKING_PACKETS); if (rc != 0) - goto on_return; + goto on_return; #endif #if PJMEDIA_HAS_FFMPEG_VID_CODEC || PJMEDIA_HAS_OPENH264_CODEC || \ @@ -501,31 +500,31 @@ int vid_codec_test(void) rc = encode_decode_test(pool, "h264", PJMEDIA_VID_PACKING_WHOLE); if (rc != 0) - goto on_return; + goto on_return; rc = encode_decode_test(pool, "h264", PJMEDIA_VID_PACKING_PACKETS); if (rc != 0) - goto on_return; + goto on_return; #endif #if PJMEDIA_HAS_VPX_CODEC && PJMEDIA_HAS_VPX_CODEC_VP8 rc = encode_decode_test(pool, "vp8", PJMEDIA_VID_PACKING_WHOLE); if (rc != 0) - goto on_return; + goto on_return; rc = encode_decode_test(pool, "vp8", PJMEDIA_VID_PACKING_PACKETS); if (rc != 0) - goto on_return; + goto on_return; #endif #if PJMEDIA_HAS_VPX_CODEC && PJMEDIA_HAS_VPX_CODEC_VP9 rc = encode_decode_test(pool, "vp9", PJMEDIA_VID_PACKING_WHOLE); if (rc != 0) - goto on_return; + goto on_return; rc = encode_decode_test(pool, "vp9", PJMEDIA_VID_PACKING_PACKETS); if (rc != 0) - goto on_return; + goto on_return; #endif diff --git a/pjmedia/src/test/vid_dev_test.c b/pjmedia/src/test/vid_dev_test.c index d7e9b5d14b..354f9d07a4 100644 --- a/pjmedia/src/test/vid_dev_test.c +++ b/pjmedia/src/test/vid_dev_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,8 +26,8 @@ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -#define THIS_FILE "vid_dev_test.c" -#define LOOP_DURATION 10 +#define THIS_FILE "vid_dev_test.c" +#define LOOP_DURATION 10 static pj_bool_t is_quitting = PJ_FALSE; @@ -36,13 +35,13 @@ static const char *vid_dir_name(pjmedia_dir dir) { switch (dir) { case PJMEDIA_DIR_CAPTURE: - return "capture"; + return "capture"; case PJMEDIA_DIR_RENDER: - return "render"; + return "render"; case PJMEDIA_DIR_CAPTURE_RENDER: - return "capture & render"; + return "capture & render"; default: - return "unknown"; + return "unknown"; } } @@ -60,15 +59,15 @@ static int enum_devs(void) unsigned j; PJ_LOG(3, (THIS_FILE, " %3d: %s (%s) - %s", i, di.name, di.driver, - vid_dir_name(di.dir))); + vid_dir_name(di.dir))); PJ_LOG(3,(THIS_FILE, " Supported formats:")); for (j=0; jname : "unknown"))); + vfi = pjmedia_get_video_format_info(NULL, di.fmt[j].id); + PJ_LOG(3,(THIS_FILE, " %s", + (vfi ? vfi->name : "unknown"))); } } } @@ -102,50 +101,50 @@ static int capture_render_loopback(int cap_dev_id, int rend_dev_id, status = pjmedia_vid_dev_get_info(cap_dev_id, &cdi); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; status = pjmedia_vid_dev_get_info(rend_dev_id, &rdi); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; PJ_LOG(3,(THIS_FILE, - " %s (%s) ===> %s (%s)\t%s\t%dx%d\t@%d:%d fps", - cdi.name, cdi.driver, rdi.name, rdi.driver, - pjmedia_get_video_format_info(NULL, fmt->id)->name, - fmt->det.vid.size.w, fmt->det.vid.size.h, - fmt->det.vid.fps.num, fmt->det.vid.fps.denum)); + " %s (%s) ===> %s (%s)\t%s\t%dx%d\t@%d:%d fps", + cdi.name, cdi.driver, rdi.name, rdi.driver, + pjmedia_get_video_format_info(NULL, fmt->id)->name, + fmt->det.vid.size.w, fmt->det.vid.size.h, + fmt->det.vid.fps.num, fmt->det.vid.fps.denum)); pjmedia_vid_port_param_default(¶m); /* Create capture, set it to active (master) */ status = pjmedia_vid_dev_default_param(pool, cap_dev_id, - ¶m.vidparam); + ¶m.vidparam); if (status != PJ_SUCCESS) { - rc = 100; goto on_return; + rc = 100; goto on_return; } param.vidparam.dir = PJMEDIA_DIR_CAPTURE; param.vidparam.fmt = *fmt; param.active = PJ_TRUE; if (param.vidparam.fmt.detail_type != PJMEDIA_FORMAT_DETAIL_VIDEO) { - rc = 103; goto on_return; + rc = 103; goto on_return; } vfd = pjmedia_format_get_video_format_detail(¶m.vidparam.fmt, PJ_TRUE); if (vfd == NULL) { - rc = 105; goto on_return; + rc = 105; goto on_return; } status = pjmedia_vid_port_create(pool, ¶m, &capture); if (status != PJ_SUCCESS) { - rc = 110; goto on_return; + rc = 110; goto on_return; } /* Create renderer, set it to passive (slave) */ status = pjmedia_vid_dev_default_param(pool, rend_dev_id, - ¶m.vidparam); + ¶m.vidparam); if (status != PJ_SUCCESS) { - rc = 120; goto on_return; + rc = 120; goto on_return; } param.active = PJ_FALSE; @@ -156,7 +155,7 @@ static int capture_render_loopback(int cap_dev_id, int rend_dev_id, status = pjmedia_vid_port_create(pool, ¶m, &renderer); if (status != PJ_SUCCESS) { - rc = 130; goto on_return; + rc = 130; goto on_return; } /* Set event handler */ @@ -165,20 +164,20 @@ static int capture_render_loopback(int cap_dev_id, int rend_dev_id, /* Connect capture to renderer */ status = pjmedia_vid_port_connect( capture, - pjmedia_vid_port_get_passive_port(renderer), - PJ_FALSE); + pjmedia_vid_port_get_passive_port(renderer), + PJ_FALSE); if (status != PJ_SUCCESS) { - rc = 140; goto on_return; + rc = 140; goto on_return; } /* Start streaming.. */ status = pjmedia_vid_port_start(renderer); if (status != PJ_SUCCESS) { - rc = 150; goto on_return; + rc = 150; goto on_return; } status = pjmedia_vid_port_start(capture); if (status != PJ_SUCCESS) { - rc = 160; goto on_return; + rc = 160; goto on_return; } /* Sleep while the webcam is being displayed... */ @@ -188,17 +187,17 @@ static int capture_render_loopback(int cap_dev_id, int rend_dev_id, on_return: if (status != PJ_SUCCESS) - PJ_PERROR(3, (THIS_FILE, status, " error")); + PJ_PERROR(3, (THIS_FILE, status, " error")); if (capture) pjmedia_vid_port_stop(capture); if (renderer) pjmedia_vid_port_stop(renderer); if (capture) - pjmedia_vid_port_destroy(capture); + pjmedia_vid_port_destroy(capture); if (renderer) { pjmedia_event_unsubscribe(NULL, &vid_event_cb, NULL, renderer); - pjmedia_vid_port_destroy(renderer); + pjmedia_vid_port_destroy(renderer); } pj_pool_release(pool); @@ -210,19 +209,19 @@ static int loopback_test(void) unsigned count, i; pjmedia_format_id test_fmts[] = { #if defined(PJ_DARWINOS) && PJ_DARWINOS - PJMEDIA_FORMAT_I420 + PJMEDIA_FORMAT_I420 #else PJMEDIA_FORMAT_YUY2 #endif }; pjmedia_rect_size test_sizes[] = { - {176,144}, /* QCIF */ - {352,288}, /* CIF */ - {704,576} /* 4CIF */ + {176,144}, /* QCIF */ + {352,288}, /* CIF */ + {704,576} /* 4CIF */ }; pjmedia_ratio test_fpses[] = { - {25, 1}, - {30, 1}, + {25, 1}, + {30, 1}, }; pj_status_t status; @@ -230,51 +229,51 @@ static int loopback_test(void) count = pjmedia_vid_dev_count(); for (i=0; i @@ -27,8 +26,8 @@ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -#define THIS_FILE "vid_dev_test.c" -#define LOOP_DURATION 6 +#define THIS_FILE "vid_dev_test.c" +#define LOOP_DURATION 6 static pj_bool_t is_quitting = PJ_FALSE; @@ -44,7 +43,7 @@ static pj_status_t vid_event_cb(pjmedia_event *event, } static int capture_render_loopback(pj_bool_t active, - int cap_dev_id, int rend_dev_id, + int cap_dev_id, int rend_dev_id, const pjmedia_format *fmt) { pj_pool_t *pool; @@ -59,50 +58,50 @@ static int capture_render_loopback(pj_bool_t active, status = pjmedia_vid_dev_get_info(cap_dev_id, &cdi); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; status = pjmedia_vid_dev_get_info(rend_dev_id, &rdi); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; PJ_LOG(3,(THIS_FILE, - " %s (%s) ===> %s (%s)\t%s\t%dx%d\t@%d:%d fps", - cdi.name, cdi.driver, rdi.name, rdi.driver, - pjmedia_get_video_format_info(NULL, fmt->id)->name, - fmt->det.vid.size.w, fmt->det.vid.size.h, - fmt->det.vid.fps.num, fmt->det.vid.fps.denum)); + " %s (%s) ===> %s (%s)\t%s\t%dx%d\t@%d:%d fps", + cdi.name, cdi.driver, rdi.name, rdi.driver, + pjmedia_get_video_format_info(NULL, fmt->id)->name, + fmt->det.vid.size.w, fmt->det.vid.size.h, + fmt->det.vid.fps.num, fmt->det.vid.fps.denum)); pjmedia_vid_port_param_default(¶m); /* Create capture, set it to active (master) */ status = pjmedia_vid_dev_default_param(pool, cap_dev_id, - ¶m.vidparam); + ¶m.vidparam); if (status != PJ_SUCCESS) { - rc = 100; goto on_return; + rc = 100; goto on_return; } param.vidparam.dir = PJMEDIA_DIR_CAPTURE; param.vidparam.fmt = *fmt; param.active = (active? PJ_TRUE: PJ_FALSE); if (param.vidparam.fmt.detail_type != PJMEDIA_FORMAT_DETAIL_VIDEO) { - rc = 103; goto on_return; + rc = 103; goto on_return; } vfd = pjmedia_format_get_video_format_detail(¶m.vidparam.fmt, PJ_TRUE); if (vfd == NULL) { - rc = 105; goto on_return; + rc = 105; goto on_return; } status = pjmedia_vid_port_create(pool, ¶m, &capture); if (status != PJ_SUCCESS) { - rc = 110; goto on_return; + rc = 110; goto on_return; } /* Create renderer, set it to passive (slave) */ status = pjmedia_vid_dev_default_param(pool, rend_dev_id, - ¶m.vidparam); + ¶m.vidparam); if (status != PJ_SUCCESS) { - rc = 120; goto on_return; + rc = 120; goto on_return; } param.active = (active? PJ_FALSE: PJ_TRUE); @@ -113,7 +112,7 @@ static int capture_render_loopback(pj_bool_t active, status = pjmedia_vid_port_create(pool, ¶m, &renderer); if (status != PJ_SUCCESS) { - rc = 130; goto on_return; + rc = 130; goto on_return; } /* Set event handler */ @@ -121,21 +120,21 @@ static int capture_render_loopback(pj_bool_t active, /* Connect capture to renderer */ status = pjmedia_vid_port_connect( - (active? capture: renderer), - pjmedia_vid_port_get_passive_port(active? renderer: capture), - PJ_FALSE); + (active? capture: renderer), + pjmedia_vid_port_get_passive_port(active? renderer: capture), + PJ_FALSE); if (status != PJ_SUCCESS) { - rc = 140; goto on_return; + rc = 140; goto on_return; } /* Start streaming.. */ status = pjmedia_vid_port_start(renderer); if (status != PJ_SUCCESS) { - rc = 150; goto on_return; + rc = 150; goto on_return; } status = pjmedia_vid_port_start(capture); if (status != PJ_SUCCESS) { - rc = 160; goto on_return; + rc = 160; goto on_return; } /* Sleep while the webcam is being displayed... */ @@ -145,17 +144,17 @@ static int capture_render_loopback(pj_bool_t active, on_return: if (status != PJ_SUCCESS) - PJ_PERROR(3, (THIS_FILE, status, " error")); + PJ_PERROR(3, (THIS_FILE, status, " error")); if (capture) pjmedia_vid_port_stop(capture); if (renderer) pjmedia_vid_port_stop(renderer); if (capture) - pjmedia_vid_port_destroy(capture); + pjmedia_vid_port_destroy(capture); if (renderer) { pjmedia_event_unsubscribe(NULL, &vid_event_cb, NULL, renderer); - pjmedia_vid_port_destroy(renderer); + pjmedia_vid_port_destroy(renderer); } pj_pool_release(pool); @@ -163,17 +162,17 @@ static int capture_render_loopback(pj_bool_t active, } static int find_device(pjmedia_dir dir, - pj_bool_t has_callback) + pj_bool_t has_callback) { unsigned i, count = pjmedia_vid_dev_count(); for (i = 0; i < count; ++i) { - pjmedia_vid_dev_info cdi; + pjmedia_vid_dev_info cdi; - if (pjmedia_vid_dev_get_info(i, &cdi) != PJ_SUCCESS) - continue; - if ((cdi.dir & dir) != 0 && cdi.has_callback == has_callback) - return i; + if (pjmedia_vid_dev_get_info(i, &cdi) != PJ_SUCCESS) + continue; + if ((cdi.dir & dir) != 0 && cdi.has_callback == has_callback) + return i; } return -999; @@ -192,36 +191,36 @@ static int vidport_test(void) /* Capturer's role: active/passive. */ for (i = 1; i >= 0; i--) { - /* Capturer's device has_callback: TRUE/FALSE. */ - for (j = 1; j >= 0; j--) { - cap_id = find_device(PJMEDIA_DIR_CAPTURE, j); - if (cap_id < 0) - continue; - - /* Renderer's device has callback: TRUE/FALSE. */ - for (k = 1; k >= 0; k--) { - rend_id = find_device(PJMEDIA_DIR_RENDER, k); - if (rend_id < 0) - continue; - - /* Check various formats to test format conversion. */ - for (l = 0; l < PJ_ARRAY_SIZE(test_fmts); ++l) { - pjmedia_format fmt; - - PJ_LOG(3,(THIS_FILE, - "capturer %s (stream: %s) ===> " - "renderer %s (stream: %s)", - (i? "active": "passive"), - (j? "active": "passive"), - (i? "passive": "active"), - (k? "active": "passive"))); - - pjmedia_format_init_video(&fmt, test_fmts[l], - 640, 480, 25, 1); - capture_render_loopback(i, cap_id, rend_id, &fmt); - } - } - } + /* Capturer's device has_callback: TRUE/FALSE. */ + for (j = 1; j >= 0; j--) { + cap_id = find_device(PJMEDIA_DIR_CAPTURE, j); + if (cap_id < 0) + continue; + + /* Renderer's device has callback: TRUE/FALSE. */ + for (k = 1; k >= 0; k--) { + rend_id = find_device(PJMEDIA_DIR_RENDER, k); + if (rend_id < 0) + continue; + + /* Check various formats to test format conversion. */ + for (l = 0; l < PJ_ARRAY_SIZE(test_fmts); ++l) { + pjmedia_format fmt; + + PJ_LOG(3,(THIS_FILE, + "capturer %s (stream: %s) ===> " + "renderer %s (stream: %s)", + (i? "active": "passive"), + (j? "active": "passive"), + (i? "passive": "active"), + (k? "active": "passive"))); + + pjmedia_format_init_video(&fmt, test_fmts[l], + 640, 480, 25, 1); + capture_render_loopback(i, cap_id, rend_id, &fmt); + } + } + } } return 0; @@ -238,7 +237,7 @@ int vid_port_test(void) rc = vidport_test(); if (rc != 0) - goto on_return; + goto on_return; on_return: pjmedia_vid_dev_subsys_shutdown(); diff --git a/pjmedia/src/test/wince_main.c b/pjmedia/src/test/wince_main.c index 2e9078d87a..43a8c386ff 100644 --- a/pjmedia/src/test/wince_main.c +++ b/pjmedia/src/test/wince_main.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,8 +20,8 @@ #include #include -#define TITLE "PJMEDIA Test" -#define CAPTION "This will start pjmedia test. Please do not use the PDA while the test is in progress. The test may take couple of minutes to complete, and you will be notified again when it completes" +#define TITLE "PJMEDIA Test" +#define CAPTION "This will start pjmedia test. Please do not use the PDA while the test is in progress. The test may take couple of minutes to complete, and you will be notified again when it completes" static FILE *fLog; @@ -35,9 +34,9 @@ static void log_writer_cb(int level, const char *data, int len) int WINAPI WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) + HINSTANCE hPrevInstance, + LPTSTR lpCmdLine, + int nCmdShow) { int rc; @@ -48,12 +47,12 @@ int WINAPI WinMain(HINSTANCE hInstance, rc = MessageBox(0, TEXT(CAPTION), TEXT(TITLE), MB_OKCANCEL); if (rc != IDOK) - return TRUE; + return TRUE; fLog = fopen("\\pjmedia-test.txt", "wt"); if (fLog == NULL) { - MessageBox(0, TEXT("Unable to create result file"), TEXT(TITLE), MB_OK); - return TRUE; + MessageBox(0, TEXT("Unable to create result file"), TEXT(TITLE), MB_OK); + return TRUE; } pj_log_set_log_func(&log_writer_cb); rc = test_main(); @@ -61,12 +60,12 @@ int WINAPI WinMain(HINSTANCE hInstance, fclose(fLog); if (rc != 0) { - MessageBox(0, TEXT("Test failed"), TEXT(TITLE), MB_OK); - return TRUE; + MessageBox(0, TEXT("Test failed"), TEXT(TITLE), MB_OK); + return TRUE; } MessageBox(0, TEXT("Test has been successful. Please see the result in \"\\pjmedia-test.txt\" file"), - TEXT(TITLE), 0); + TEXT(TITLE), 0); return TRUE; } diff --git a/pjmedia/src/test/wsola_test.c b/pjmedia/src/test/wsola_test.c index 049f77d632..b35d56ee90 100644 --- a/pjmedia/src/test/wsola_test.c +++ b/pjmedia/src/test/wsola_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,20 +23,20 @@ #include #include -#define CLOCK_RATE 16000 +#define CLOCK_RATE 16000 #define SAMPLES_PER_FRAME (10 * CLOCK_RATE / 1000) -#define RESET() memset(buf1, 0, sizeof(buf1)), \ - memset(buf2, 0, sizeof(buf2)), \ - memset(frm1, 0, sizeof(frm1)), \ - memset(frm2, 0, sizeof(frm2)) +#define RESET() memset(buf1, 0, sizeof(buf1)), \ + memset(buf2, 0, sizeof(buf2)), \ + memset(frm1, 0, sizeof(frm1)), \ + memset(frm2, 0, sizeof(frm2)) #if 0 void test_find_pitch(void) { enum { ON = 111, FRM_PART_LEN=20 }; short buf2[SAMPLES_PER_FRAME*2], buf1[SAMPLES_PER_FRAME*2], - frm2[SAMPLES_PER_FRAME], frm1[SAMPLES_PER_FRAME]; + frm2[SAMPLES_PER_FRAME], frm1[SAMPLES_PER_FRAME]; short *ref, *pos; /* Case 1. all contiguous */ @@ -47,7 +46,7 @@ void test_find_pitch(void) frm1[0] = ON; pos = pjmedia_wsola_find_pitch(frm1, SAMPLES_PER_FRAME, NULL, 0, - buf1, SAMPLES_PER_FRAME*2, NULL, 0, PJ_TRUE); + buf1, SAMPLES_PER_FRAME*2, NULL, 0, PJ_TRUE); assert(pos == ref); /* Case 2: contiguous buffer, non-contiguous frame */ @@ -62,7 +61,7 @@ void test_find_pitch(void) buf1[0] = ON; pos = pjmedia_wsola_find_pitch(frm1, FRM_PART_LEN, frm2, SAMPLES_PER_FRAME - FRM_PART_LEN, - buf1, SAMPLES_PER_FRAME*2, NULL, 0, PJ_TRUE); + buf1, SAMPLES_PER_FRAME*2, NULL, 0, PJ_TRUE); assert(pos == ref); /* Case 3: non-contiguous buffer, contiguous frame, found in buf1 */ @@ -77,16 +76,16 @@ void test_find_pitch(void) buf1[0] = ON; pos = pjmedia_wsola_find_pitch(frm1, SAMPLES_PER_FRAME, NULL, 0, - buf1, FRM_PART_LEN, - buf2, SAMPLES_PER_FRAME, - PJ_TRUE); + buf1, FRM_PART_LEN, + buf2, SAMPLES_PER_FRAME, + PJ_TRUE); assert(pos == ref); } #endif int expand(pj_pool_t *pool, const char *filein, const char *fileout, - int expansion_rate100, int lost_rate10, int lost_burst) + int expansion_rate100, int lost_rate10, int lost_burst) { enum { LOST_RATE = 10 }; FILE *in, *out; @@ -110,70 +109,70 @@ int expand(pj_pool_t *pool, const char *filein, const char *fileout, elapsed.u64 = 0; while (fread(frame, SAMPLES_PER_FRAME*2, 1, in) == 1) { - pj_timestamp t1, t2; + pj_timestamp t1, t2; - if (lost_rate10 == 0) { + if (lost_rate10 == 0) { - /* Expansion */ - pj_get_timestamp(&t1); - pjmedia_wsola_save(wsola, frame, 0); - pj_get_timestamp(&t2); + /* Expansion */ + pj_get_timestamp(&t1); + pjmedia_wsola_save(wsola, frame, 0); + pj_get_timestamp(&t2); - pj_sub_timestamp(&t2, &t1); - pj_add_timestamp(&elapsed, &t2); + pj_sub_timestamp(&t2, &t1); + pj_add_timestamp(&elapsed, &t2); - fwrite(frame, SAMPLES_PER_FRAME*2, 1, out); + fwrite(frame, SAMPLES_PER_FRAME*2, 1, out); - samples += SAMPLES_PER_FRAME; + samples += SAMPLES_PER_FRAME; - if ((rand() % 100) < expansion_rate100) { + if ((rand() % 100) < expansion_rate100) { - pj_get_timestamp(&t1); - pjmedia_wsola_generate(wsola, frame); - pj_get_timestamp(&t2); + pj_get_timestamp(&t1); + pjmedia_wsola_generate(wsola, frame); + pj_get_timestamp(&t2); - pj_sub_timestamp(&t2, &t1); - pj_add_timestamp(&elapsed, &t2); + pj_sub_timestamp(&t2, &t1); + pj_add_timestamp(&elapsed, &t2); - samples += SAMPLES_PER_FRAME; + samples += SAMPLES_PER_FRAME; - fwrite(frame, SAMPLES_PER_FRAME*2, 1, out); - } + fwrite(frame, SAMPLES_PER_FRAME*2, 1, out); + } - } else { - /* Lost */ + } else { + /* Lost */ - if ((rand() % 10) < lost_rate10) { - int burst; + if ((rand() % 10) < lost_rate10) { + int burst; - for (burst=0; burst SAMPLES_PER_FRAME); - pjmedia_wsola_discard(wsola, buf, count-SAMPLES_PER_FRAME, - buf+count-SAMPLES_PER_FRAME, SAMPLES_PER_FRAME, - &to_del); + /* Method 2: split, majority in buf1 */ + assert(count > SAMPLES_PER_FRAME); + pjmedia_wsola_discard(wsola, buf, count-SAMPLES_PER_FRAME, + buf+count-SAMPLES_PER_FRAME, SAMPLES_PER_FRAME, + &to_del); #elif 0 - /* Method 3: split, majority in buf2 */ - assert(count > SAMPLES_PER_FRAME); - pjmedia_wsola_discard(wsola, buf, SAMPLES_PER_FRAME, - buf+SAMPLES_PER_FRAME, count-SAMPLES_PER_FRAME, - &to_del); + /* Method 3: split, majority in buf2 */ + assert(count > SAMPLES_PER_FRAME); + pjmedia_wsola_discard(wsola, buf, SAMPLES_PER_FRAME, + buf+SAMPLES_PER_FRAME, count-SAMPLES_PER_FRAME, + &to_del); #elif 1 - /* Method 4: split, each with small length */ - enum { TOT_LEN = 3 * SAMPLES_PER_FRAME }; - unsigned buf1_len = (rand() % TOT_LEN); - short *ptr = buf + count - TOT_LEN; - assert(count > TOT_LEN); - if (buf1_len==0) buf1_len=SAMPLES_PER_FRAME*2; - pjmedia_wsola_discard(wsola, ptr, buf1_len, - ptr+buf1_len, TOT_LEN-buf1_len, - &to_del); + /* Method 4: split, each with small length */ + enum { TOT_LEN = 3 * SAMPLES_PER_FRAME }; + unsigned buf1_len = (rand() % TOT_LEN); + short *ptr = buf + count - TOT_LEN; + assert(count > TOT_LEN); + if (buf1_len==0) buf1_len=SAMPLES_PER_FRAME*2; + pjmedia_wsola_discard(wsola, ptr, buf1_len, + ptr+buf1_len, TOT_LEN-buf1_len, + &to_del); #endif - count -= to_del; - size_del += to_del; - } - pj_get_timestamp(&t2); - - samples += BUF_CNT; + count -= to_del; + size_del += to_del; + } + pj_get_timestamp(&t2); + + samples += BUF_CNT; - pj_sub_timestamp(&t2, &t1); - pj_add_timestamp(&elapsed, &t2); + pj_sub_timestamp(&t2, &t1); + pj_add_timestamp(&elapsed, &t2); - assert(size_del >= SAMPLES_PER_FRAME); + assert(size_del >= SAMPLES_PER_FRAME); - fwrite(buf, count, 2, out); + fwrite(buf, count, 2, out); } pjmedia_wsola_destroy(wsola); @@ -289,9 +288,9 @@ int compress(pj_pool_t *pool, assert(zero.u32.hi == 0); PJ_LOG(3,("test.c", "Processing: %f Msamples per second", - zero.u32.lo/1000000.0)); + zero.u32.lo/1000000.0)); PJ_LOG(3,("test.c", "CPU load for current settings: %f%%", - CLOCK_RATE * 100.0 / zero.u32.lo)); + CLOCK_RATE * 100.0 / zero.u32.lo)); return 0; } @@ -307,15 +306,15 @@ static void mem_test(pj_pool_t *pool) elapsed.u64 = 0; while (samples < 50000000) { - pj_get_timestamp(&t1); - pjmedia_move_samples(frame, frame+160, 240+2*160); - pj_get_timestamp(&t2); - pj_sub_timestamp(&t2, &t1); + pj_get_timestamp(&t1); + pjmedia_move_samples(frame, frame+160, 240+2*160); + pj_get_timestamp(&t2); + pj_sub_timestamp(&t2, &t1); - elapsed.u64 += t2.u64; + elapsed.u64 += t2.u64; - memset(unused, 0, sizeof(unused)); - samples += 160; + memset(unused, 0, sizeof(unused)); + samples += 160; } @@ -328,9 +327,9 @@ static void mem_test(pj_pool_t *pool) assert(zero.u32.hi == 0); PJ_LOG(3,("test.c", "Processing: %f Msamples per second", - zero.u32.lo/1000000.0)); + zero.u32.lo/1000000.0)); PJ_LOG(3,("test.c", "CPU load for current settings: %f%%", - CLOCK_RATE * 100.0 / zero.u32.lo)); + CLOCK_RATE * 100.0 / zero.u32.lo)); } @@ -352,20 +351,20 @@ int main() rc = compress(pool, "temp1.pcm", "output.pcm", 1); for (i=0; i<2; ++i) { - rc = expand(pool, "output.pcm", "temp1.pcm", 20, 0, 0); - rc = compress(pool, "temp1.pcm", "output.pcm", 1); + rc = expand(pool, "output.pcm", "temp1.pcm", 20, 0, 0); + rc = compress(pool, "temp1.pcm", "output.pcm", 1); } if (rc != 0) { - puts("Error"); - return 1; + puts("Error"); + return 1; } #if 0 { - char s[10]; - puts("Press ENTER to quit"); - fgets(s, sizeof(s), stdin); + char s[10]; + puts("Press ENTER to quit"); + fgets(s, sizeof(s), stdin); } #endif diff --git a/pjnath/docs/doc_ice.h b/pjnath/docs/doc_ice.h index 6343e3301a..5c5d933337 100644 --- a/pjnath/docs/doc_ice.h +++ b/pjnath/docs/doc_ice.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjnath/docs/doc_mainpage.h b/pjnath/docs/doc_mainpage.h index 1b80501a27..d2794c3b19 100644 --- a/pjnath/docs/doc_mainpage.h +++ b/pjnath/docs/doc_mainpage.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjnath/docs/doc_nat.h b/pjnath/docs/doc_nat.h index d4f71fe1a9..ba931f2e2a 100644 --- a/pjnath/docs/doc_nat.h +++ b/pjnath/docs/doc_nat.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjnath/docs/doc_samples.h b/pjnath/docs/doc_samples.h index 4196e81813..02bc080347 100644 --- a/pjnath/docs/doc_samples.h +++ b/pjnath/docs/doc_samples.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjnath/docs/doc_stun.h b/pjnath/docs/doc_stun.h index 32c032d20b..99ad765ea5 100644 --- a/pjnath/docs/doc_stun.h +++ b/pjnath/docs/doc_stun.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjnath/docs/doc_turn.h b/pjnath/docs/doc_turn.h index c13417b9ae..1ed77c67ad 100644 --- a/pjnath/docs/doc_turn.h +++ b/pjnath/docs/doc_turn.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjnath/include/pjnath.h b/pjnath/include/pjnath.h index f8b86f66c3..5653999ffc 100644 --- a/pjnath/include/pjnath.h +++ b/pjnath/include/pjnath.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjnath/include/pjnath/config.h b/pjnath/include/pjnath/config.h index 2e1d03634a..e904c3ac48 100644 --- a/pjnath/include/pjnath/config.h +++ b/pjnath/include/pjnath/config.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,7 +45,7 @@ * default 1 */ #ifndef PJNATH_ERROR_LEVEL -# define PJNATH_ERROR_LEVEL 1 +# define PJNATH_ERROR_LEVEL 1 #endif @@ -61,7 +60,7 @@ * Default: 16 */ #ifndef PJ_STUN_MAX_ATTR -# define PJ_STUN_MAX_ATTR 16 +# define PJ_STUN_MAX_ATTR 16 #endif /** @@ -73,7 +72,7 @@ * retransmission. */ #ifndef PJ_STUN_RTO_VALUE -# define PJ_STUN_RTO_VALUE 100 +# define PJ_STUN_RTO_VALUE 100 #endif @@ -85,7 +84,7 @@ * The default value is 16x RTO (as per RFC 3489-bis). */ #ifndef PJ_STUN_TIMEOUT_VALUE -# define PJ_STUN_TIMEOUT_VALUE (16 * PJ_STUN_RTO_VALUE) +# define PJ_STUN_TIMEOUT_VALUE (16 * PJ_STUN_RTO_VALUE) #endif @@ -95,7 +94,7 @@ * Default: 7 (as per RFC 3489-bis) */ #ifndef PJ_STUN_MAX_TRANSMIT_COUNT -# define PJ_STUN_MAX_TRANSMIT_COUNT 7 +# define PJ_STUN_MAX_TRANSMIT_COUNT 7 #endif @@ -105,7 +104,7 @@ * Default: 10000 (as per RFC 3489-bis) */ #ifndef PJ_STUN_RES_CACHE_DURATION -# define PJ_STUN_RES_CACHE_DURATION 10000 +# define PJ_STUN_RES_CACHE_DURATION 10000 #endif @@ -113,14 +112,14 @@ * Maximum size of STUN message. */ #ifndef PJ_STUN_MAX_PKT_LEN -# define PJ_STUN_MAX_PKT_LEN 800 +# define PJ_STUN_MAX_PKT_LEN 800 #endif /** * Default STUN port as defined by RFC 3489. */ -#define PJ_STUN_PORT 3478 +#define PJ_STUN_PORT 3478 /** @@ -129,7 +128,7 @@ * Default: ASCII 0 */ #ifndef PJ_STUN_STRING_ATTR_PAD_CHR -# define PJ_STUN_STRING_ATTR_PAD_CHR 0 +# define PJ_STUN_STRING_ATTR_PAD_CHR 0 #endif @@ -139,7 +138,7 @@ * not backward compatible with current STUN specification. */ #ifndef PJ_STUN_OLD_STYLE_MI_FINGERPRINT -# define PJ_STUN_OLD_STYLE_MI_FINGERPRINT 0 +# define PJ_STUN_OLD_STYLE_MI_FINGERPRINT 0 #endif @@ -151,7 +150,7 @@ * The packet buffer size for the STUN transport. */ #ifndef PJ_STUN_SOCK_PKT_LEN -# define PJ_STUN_SOCK_PKT_LEN 2000 +# define PJ_STUN_SOCK_PKT_LEN 2000 #endif @@ -159,7 +158,7 @@ * The duration of the STUN keep-alive period, in seconds. */ #ifndef PJ_STUN_KEEP_ALIVE_SEC -# define PJ_STUN_KEEP_ALIVE_SEC 15 +# define PJ_STUN_KEEP_ALIVE_SEC 15 #endif @@ -171,7 +170,7 @@ * Maximum DNS SRV entries to be processed in the DNS SRV response */ #ifndef PJ_TURN_MAX_DNS_SRV_CNT -# define PJ_TURN_MAX_DNS_SRV_CNT 4 +# define PJ_TURN_MAX_DNS_SRV_CNT 4 #endif @@ -179,7 +178,7 @@ * Maximum TURN packet size to be supported. */ #ifndef PJ_TURN_MAX_PKT_LEN -# define PJ_TURN_MAX_PKT_LEN 3000 +# define PJ_TURN_MAX_PKT_LEN 3000 #endif @@ -188,7 +187,7 @@ * TURN protocol specification. */ #ifndef PJ_TURN_PERM_TIMEOUT -# define PJ_TURN_PERM_TIMEOUT 300 +# define PJ_TURN_PERM_TIMEOUT 300 #endif @@ -197,7 +196,7 @@ * TURN protocol specification. */ #ifndef PJ_TURN_CHANNEL_TIMEOUT -# define PJ_TURN_CHANNEL_TIMEOUT 600 +# define PJ_TURN_CHANNEL_TIMEOUT 600 #endif @@ -207,7 +206,7 @@ * PJ_TURN_PERM_TIMEOUT setting. */ #ifndef PJ_TURN_REFRESH_SEC_BEFORE -# define PJ_TURN_REFRESH_SEC_BEFORE 60 +# define PJ_TURN_REFRESH_SEC_BEFORE 60 #endif @@ -217,7 +216,7 @@ * need to be refreshed. */ #ifndef PJ_TURN_KEEP_ALIVE_SEC -# define PJ_TURN_KEEP_ALIVE_SEC 15 +# define PJ_TURN_KEEP_ALIVE_SEC 15 #endif /** @@ -225,7 +224,7 @@ * open/accept for each TURN allocation (or TURN control connection). */ #ifndef PJ_TURN_MAX_TCP_CONN_CNT -# define PJ_TURN_MAX_TCP_CONN_CNT 8 +# define PJ_TURN_MAX_TCP_CONN_CNT 8 #endif /* ************************************************************************** @@ -238,7 +237,7 @@ * Default: 16 */ #ifndef PJ_ICE_MAX_CAND -# define PJ_ICE_MAX_CAND 16 +# define PJ_ICE_MAX_CAND 16 #endif @@ -248,7 +247,7 @@ * Default: 8 */ #ifndef PJ_ICE_ST_MAX_CAND -# define PJ_ICE_ST_MAX_CAND 8 +# define PJ_ICE_ST_MAX_CAND 8 #endif @@ -259,7 +258,7 @@ * Default: 2 */ #ifndef PJ_ICE_MAX_STUN -# define PJ_ICE_MAX_STUN 2 +# define PJ_ICE_MAX_STUN 2 #endif @@ -270,7 +269,7 @@ * Default: 2 */ #ifndef PJ_ICE_MAX_TURN -# define PJ_ICE_MAX_TURN 3 +# define PJ_ICE_MAX_TURN 3 #endif @@ -279,20 +278,20 @@ * the maximum number of components (PJ_ICE_MAX_COMP) value. */ #ifndef PJ_ICE_COMP_BITS -# define PJ_ICE_COMP_BITS 1 +# define PJ_ICE_COMP_BITS 1 #endif /** * Maximum number of ICE components. */ -#define PJ_ICE_MAX_COMP (1< @@ -48,61 +47,61 @@ /** * Map STUN error code (300-699) into pj_status_t error space. */ -#define PJ_STATUS_FROM_STUN_CODE(code) (PJNATH_ERRNO_START+code) +#define PJ_STATUS_FROM_STUN_CODE(code) (PJNATH_ERRNO_START+code) /** * @hideinitializer * Invalid STUN message */ -#define PJNATH_EINSTUNMSG (PJNATH_ERRNO_START+1) /* 370001 */ +#define PJNATH_EINSTUNMSG (PJNATH_ERRNO_START+1) /* 370001 */ /** * @hideinitializer * Invalid STUN message length. */ -#define PJNATH_EINSTUNMSGLEN (PJNATH_ERRNO_START+2) /* 370002 */ +#define PJNATH_EINSTUNMSGLEN (PJNATH_ERRNO_START+2) /* 370002 */ /** * @hideinitializer * Invalid or unexpected STUN message type */ -#define PJNATH_EINSTUNMSGTYPE (PJNATH_ERRNO_START+3) /* 370003 */ +#define PJNATH_EINSTUNMSGTYPE (PJNATH_ERRNO_START+3) /* 370003 */ /** * @hideinitializer * STUN transaction has timed out */ -#define PJNATH_ESTUNTIMEDOUT (PJNATH_ERRNO_START+4) /* 370004 */ +#define PJNATH_ESTUNTIMEDOUT (PJNATH_ERRNO_START+4) /* 370004 */ /** * @hideinitializer * Too many STUN attributes. */ -#define PJNATH_ESTUNTOOMANYATTR (PJNATH_ERRNO_START+21) /* 370021 */ +#define PJNATH_ESTUNTOOMANYATTR (PJNATH_ERRNO_START+21) /* 370021 */ /** * @hideinitializer * Invalid STUN attribute length. */ -#define PJNATH_ESTUNINATTRLEN (PJNATH_ERRNO_START+22) /* 370022 */ +#define PJNATH_ESTUNINATTRLEN (PJNATH_ERRNO_START+22) /* 370022 */ /** * @hideinitializer * Found duplicate STUN attribute. */ -#define PJNATH_ESTUNDUPATTR (PJNATH_ERRNO_START+23) /* 370023 */ +#define PJNATH_ESTUNDUPATTR (PJNATH_ERRNO_START+23) /* 370023 */ /** * @hideinitializer * STUN FINGERPRINT verification failed */ -#define PJNATH_ESTUNFINGERPRINT (PJNATH_ERRNO_START+30) /* 370030 */ +#define PJNATH_ESTUNFINGERPRINT (PJNATH_ERRNO_START+30) /* 370030 */ /** * @hideinitializer * Invalid STUN attribute after MESSAGE-INTEGRITY. */ -#define PJNATH_ESTUNMSGINTPOS (PJNATH_ERRNO_START+31) /* 370031 */ +#define PJNATH_ESTUNMSGINTPOS (PJNATH_ERRNO_START+31) /* 370031 */ /** * @hideinitializer * Invalid STUN attribute after FINGERPRINT. */ -#define PJNATH_ESTUNFINGERPOS (PJNATH_ERRNO_START+33) /* 370033 */ +#define PJNATH_ESTUNFINGERPOS (PJNATH_ERRNO_START+33) /* 370033 */ /** @@ -114,18 +113,18 @@ * @hideinitializer * STUN IPv6 attribute not supported */ -#define PJNATH_ESTUNIPV6NOTSUPP (PJNATH_ERRNO_START+41) /* 370041 */ +#define PJNATH_ESTUNIPV6NOTSUPP (PJNATH_ERRNO_START+41) /* 370041 */ /** * @hideinitializer * Invalid address family value in STUN message. */ -#define PJNATH_EINVAF (PJNATH_ERRNO_START+42) /* 370042 */ +#define PJNATH_EINVAF (PJNATH_ERRNO_START+42) /* 370042 */ /** * @hideinitializer * Invalid STUN server or server not configured. */ -#define PJNATH_ESTUNINSERVER (PJNATH_ERRNO_START+50) /* 370050 */ +#define PJNATH_ESTUNINSERVER (PJNATH_ERRNO_START+50) /* 370050 */ /************************************************************ @@ -135,7 +134,7 @@ * @hideinitializer * STUN object has been destoyed. */ -#define PJNATH_ESTUNDESTROYED (PJNATH_ERRNO_START+60) /* 370060 */ +#define PJNATH_ESTUNDESTROYED (PJNATH_ERRNO_START+60) /* 370060 */ /************************************************************ @@ -146,12 +145,12 @@ * @hideinitializer * ICE session not available */ -#define PJNATH_ENOICE (PJNATH_ERRNO_START+80) /* 370080 */ +#define PJNATH_ENOICE (PJNATH_ERRNO_START+80) /* 370080 */ /** * @hideinitializer * ICE check is in progress */ -#define PJNATH_EICEINPROGRESS (PJNATH_ERRNO_START+81) /* 370081 */ +#define PJNATH_EICEINPROGRESS (PJNATH_ERRNO_START+81) /* 370081 */ /** * @hideinitializer * This error indicates that ICE connectivity check has failed, because @@ -161,52 +160,52 @@ * however other reasons may include software incompatibility between * the two agents, or incomplete candidates gathered by the agent(s). */ -#define PJNATH_EICEFAILED (PJNATH_ERRNO_START+82) /* 370082 */ +#define PJNATH_EICEFAILED (PJNATH_ERRNO_START+82) /* 370082 */ /** * @hideinitializer * Default destination does not match any ICE candidates */ -#define PJNATH_EICEMISMATCH (PJNATH_ERRNO_START+83) /* 370083 */ +#define PJNATH_EICEMISMATCH (PJNATH_ERRNO_START+83) /* 370083 */ /** * @hideinitializer * Invalid ICE component ID */ -#define PJNATH_EICEINCOMPID (PJNATH_ERRNO_START+86) /* 370086 */ +#define PJNATH_EICEINCOMPID (PJNATH_ERRNO_START+86) /* 370086 */ /** * @hideinitializer * Invalid ICE candidate ID */ -#define PJNATH_EICEINCANDID (PJNATH_ERRNO_START+87) /* 370087 */ +#define PJNATH_EICEINCANDID (PJNATH_ERRNO_START+87) /* 370087 */ /** * @hideinitializer * Source address mismatch. This error occurs if the source address * of the response for ICE connectivity check is different than * the destination address of the request. */ -#define PJNATH_EICEINSRCADDR (PJNATH_ERRNO_START+88) /* 370088 */ +#define PJNATH_EICEINSRCADDR (PJNATH_ERRNO_START+88) /* 370088 */ /** * @hideinitializer * Missing ICE SDP attribute */ -#define PJNATH_EICEMISSINGSDP (PJNATH_ERRNO_START+90) /* 370090 */ +#define PJNATH_EICEMISSINGSDP (PJNATH_ERRNO_START+90) /* 370090 */ /** * @hideinitializer * Invalid SDP "candidate" attribute */ -#define PJNATH_EICEINCANDSDP (PJNATH_ERRNO_START+91) /* 370091 */ +#define PJNATH_EICEINCANDSDP (PJNATH_ERRNO_START+91) /* 370091 */ /** * @hideinitializer * No host candidate associated with srflx. This error occurs when * a server reflexive candidate is added without the matching * host candidate. */ -#define PJNATH_EICENOHOSTCAND (PJNATH_ERRNO_START+92) /* 370092 */ +#define PJNATH_EICENOHOSTCAND (PJNATH_ERRNO_START+92) /* 370092 */ /** * @hideinitializer * Controlled agent timed-out in waiting for the controlling agent to * send nominated check after all connectivity checks have completed. */ -#define PJNATH_EICENOMTIMEOUT (PJNATH_ERRNO_START+93) /* 370093 */ +#define PJNATH_EICENOMTIMEOUT (PJNATH_ERRNO_START+93) /* 370093 */ /************************************************************ * TURN ERROR CODES @@ -215,7 +214,7 @@ * @hideinitializer * Invalid or unsupported TURN transport. */ -#define PJNATH_ETURNINTP (PJNATH_ERRNO_START+120) /* 370120 */ +#define PJNATH_ETURNINTP (PJNATH_ERRNO_START+120) /* 370120 */ @@ -223,4 +222,4 @@ * @} */ -#endif /* __PJNATH_ERRNO_H__ */ +#endif /* __PJNATH_ERRNO_H__ */ diff --git a/pjnath/include/pjnath/ice_session.h b/pjnath/include/pjnath/ice_session.h index 9f980d39b1..e796b2539a 100644 --- a/pjnath/include/pjnath/ice_session.h +++ b/pjnath/include/pjnath/ice_session.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -69,18 +68,18 @@ PJ_BEGIN_DECL * answerer: * - create ICE session with #pj_ice_sess_create(). Among other things, * application needs to specify: - * - STUN configuration (pj_stun_config), containing STUN settings - * such as timeout values and the instances of timer heap and - * ioqueue. - * - Session name, useful for identifying this session in the log. - * - Initial ICE role (#pj_ice_sess_role). The role can be changed - * at later time with #pj_ice_sess_change_role(), and ICE session - * can also change its role automatically when it detects role - * conflict. - * - Number of components in the media session. - * - Callback to receive ICE events (#pj_ice_sess_cb) - * - Optional local ICE username and password. If these arguments - * are NULL, they will be generated randomly. + * - STUN configuration (pj_stun_config), containing STUN settings + * such as timeout values and the instances of timer heap and + * ioqueue. + * - Session name, useful for identifying this session in the log. + * - Initial ICE role (#pj_ice_sess_role). The role can be changed + * at later time with #pj_ice_sess_change_role(), and ICE session + * can also change its role automatically when it detects role + * conflict. + * - Number of components in the media session. + * - Callback to receive ICE events (#pj_ice_sess_cb) + * - Optional local ICE username and password. If these arguments + * are NULL, they will be generated randomly. * - Add local candidates for each component, with #pj_ice_sess_add_cand(). * A candidate is represented with #pj_ice_sess_cand structure. * Each component must be provided with at least one candidate, and @@ -187,20 +186,20 @@ typedef struct pj_ice_sess_comp * has been successful. The value will be NULL if a no successful check * has not been found for this component. */ - pj_ice_sess_check *valid_check; + pj_ice_sess_check *valid_check; /** * Pointer to ICE check with highest priority which connectivity check * has been successful and it has been nominated. The value may be NULL * if there is no such check yet. */ - pj_ice_sess_check *nominated_check; + pj_ice_sess_check *nominated_check; /** * The STUN session to be used to send and receive STUN messages for this * component. */ - pj_stun_session *stun_sess; + pj_stun_session *stun_sess; } pj_ice_sess_comp; @@ -211,21 +210,21 @@ typedef struct pj_ice_sess_comp typedef struct pj_ice_msg_data { /** Transport ID for this message */ - unsigned transport_id; + unsigned transport_id; /** Flag to indicate whether data.req contains data */ - pj_bool_t has_req_data; + pj_bool_t has_req_data; /** The data */ union data { - /** Request data */ - struct request_data { - pj_ice_sess *ice; /**< ICE session */ - pj_ice_sess_checklist *clist; /**< Checklist */ - unsigned ckid; /**< Check ID */ - pj_ice_sess_cand *lcand; /**< Local cand */ - pj_ice_sess_cand *rcand; /**< Remote cand */ - } req; /**< Request data */ + /** Request data */ + struct request_data { + pj_ice_sess *ice; /**< ICE session */ + pj_ice_sess_checklist *clist; /**< Checklist */ + unsigned ckid; /**< Check ID */ + pj_ice_sess_cand *lcand; /**< Local cand */ + pj_ice_sess_cand *rcand; /**< Remote cand */ + } req; /**< Request data */ } data; /**< The data */ } pj_ice_msg_data; @@ -244,12 +243,12 @@ struct pj_ice_sess_cand /** * The candidate ID. */ - unsigned id; + unsigned id; /** * The candidate type, as described in #pj_ice_cand_type enumeration. */ - pj_ice_cand_type type; + pj_ice_cand_type type; /** * Status of this candidate. The value will be PJ_SUCCESS if candidate @@ -257,24 +256,24 @@ struct pj_ice_sess_cand * resolution process is in progress, or other value when the address * resolution has completed with failure. */ - pj_status_t status; + pj_status_t status; /** * The component ID of this candidate. Note that component IDs starts * with one for RTP and two for RTCP. In other words, it's not zero * based. */ - pj_uint8_t comp_id; + pj_uint8_t comp_id; /** * Transport ID to be used to send packets for this candidate. */ - pj_uint8_t transport_id; + pj_uint8_t transport_id; /** * Local preference value, which typically is 65535. */ - pj_uint16_t local_pref; + pj_uint16_t local_pref; /** * The foundation string, which is an identifier which value will be @@ -282,14 +281,14 @@ struct pj_ice_sess_cand * same base, and come from the same STUN server. The foundation is * used to optimize ICE performance in the Frozen algorithm. */ - pj_str_t foundation; + pj_str_t foundation; /** * The candidate's priority, a 32-bit unsigned value which value will be * calculated by the ICE session when a candidate is registered to the * ICE session. */ - pj_uint32_t prio; + pj_uint32_t prio; /** * IP address of this candidate. For host candidates, this represents @@ -300,7 +299,7 @@ struct pj_ice_sess_cand * will be the address allocated in the TURN server by STUN Allocate * request. */ - pj_sockaddr addr; + pj_sockaddr addr; /** * Base address of this candidate. "Base" refers to the address an agent @@ -310,13 +309,13 @@ struct pj_ice_sess_cand * the base address is the transport address allocated in the TURN server * for this candidate. */ - pj_sockaddr base_addr; + pj_sockaddr base_addr; /** * Related address, which is used for informational only and is not used * in any way by the ICE session. */ - pj_sockaddr rel_addr; + pj_sockaddr rel_addr; }; @@ -376,27 +375,27 @@ struct pj_ice_sess_check /** * Pointer to local candidate entry of this check. */ - pj_ice_sess_cand *lcand; + pj_ice_sess_cand *lcand; /** * Pointer to remote candidate entry of this check. */ - pj_ice_sess_cand *rcand; + pj_ice_sess_cand *rcand; /** * Foundation index, referring to foundation array defined in checklist. */ - int foundation_idx; + int foundation_idx; /** * Check priority. */ - pj_timestamp prio; + pj_timestamp prio; /** * Connectivity check state. */ - pj_ice_sess_check_state state; + pj_ice_sess_check_state state; /** * STUN transmit data containing STUN Binding request that was sent @@ -404,19 +403,19 @@ struct pj_ice_sess_check * has a pending transaction, and is used to cancel the transaction * when other check has succeeded. */ - pj_stun_tx_data *tdata; + pj_stun_tx_data *tdata; /** * Flag to indicate whether this check is nominated. A nominated check * contains USE-CANDIDATE attribute in its STUN Binding request. */ - pj_bool_t nominated; + pj_bool_t nominated; /** * When the check failed, this will contain the failure status of the * STUN transaction. */ - pj_status_t err_code; + pj_status_t err_code; }; @@ -459,27 +458,27 @@ struct pj_ice_sess_checklist /** * Number of candidate pairs (checks). */ - unsigned count; + unsigned count; /** * Array of candidate pairs (checks). */ - pj_ice_sess_check checks[PJ_ICE_MAX_CHECKS]; + pj_ice_sess_check checks[PJ_ICE_MAX_CHECKS]; /** * Number of foundations. */ - unsigned foundation_cnt; + unsigned foundation_cnt; /** * Array of foundations, check foundation index refers to this array. */ - pj_str_t foundation[PJ_ICE_MAX_CHECKS * 2]; + pj_str_t foundation[PJ_ICE_MAX_CHECKS * 2]; /** * A timer used to perform periodic check for this checklist. */ - pj_timer_entry timer; + pj_timer_entry timer; }; @@ -496,54 +495,54 @@ typedef struct pj_ice_sess_cb * * @param ice The ICE session. */ - void (*on_valid_pair)(pj_ice_sess *ice); + void (*on_valid_pair)(pj_ice_sess *ice); /** * An optional callback that will be called by the ICE session when * ICE negotiation has completed, successfully or with failure. * - * @param ice The ICE session. - * @param status Will contain PJ_SUCCESS if ICE negotiation is - * successful, or some error code. + * @param ice The ICE session. + * @param status Will contain PJ_SUCCESS if ICE negotiation is + * successful, or some error code. */ - void (*on_ice_complete)(pj_ice_sess *ice, pj_status_t status); + void (*on_ice_complete)(pj_ice_sess *ice, pj_status_t status); /** * A mandatory callback which will be called by the ICE session when * it needs to send outgoing STUN packet. * - * @param ice The ICE session. - * @param comp_id ICE component ID. + * @param ice The ICE session. + * @param comp_id ICE component ID. * @param transport_id Transport ID. - * @param pkt The STUN packet. - * @param size The size of the packet. - * @param dst_addr Packet destination address. + * @param pkt The STUN packet. + * @param size The size of the packet. + * @param dst_addr Packet destination address. * @param dst_addr_len Length of destination address. */ pj_status_t (*on_tx_pkt)(pj_ice_sess *ice, unsigned comp_id, - unsigned transport_id, - const void *pkt, pj_size_t size, - const pj_sockaddr_t *dst_addr, - unsigned dst_addr_len); + unsigned transport_id, + const void *pkt, pj_size_t size, + const pj_sockaddr_t *dst_addr, + unsigned dst_addr_len); /** * A mandatory callback which will be called by the ICE session when * it receives packet which is not part of ICE negotiation. * - * @param ice The ICE session. - * @param comp_id ICE component ID. + * @param ice The ICE session. + * @param comp_id ICE component ID. * @param transport_id Transport ID. - * @param pkt The whole packet. - * @param size Size of the packet. - * @param src_addr Source address where this packet was received - * from. + * @param pkt The whole packet. + * @param size Size of the packet. + * @param src_addr Source address where this packet was received + * from. * @param src_addr_len The length of source address. */ - void (*on_rx_data)(pj_ice_sess *ice, unsigned comp_id, - unsigned transport_id, - void *pkt, pj_size_t size, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + void (*on_rx_data)(pj_ice_sess *ice, unsigned comp_id, + unsigned transport_id, + void *pkt, pj_size_t size, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); } pj_ice_sess_cb; @@ -583,15 +582,15 @@ typedef struct pj_ice_rx_check { PJ_DECL_LIST_MEMBER(struct pj_ice_rx_check); /**< Standard list */ - unsigned comp_id; /**< Component ID. */ - unsigned transport_id; /**< Transport ID. */ + unsigned comp_id; /**< Component ID. */ + unsigned transport_id; /**< Transport ID. */ - pj_sockaddr src_addr; /**< Source address of request */ - unsigned src_addr_len; /**< Length of src address. */ + pj_sockaddr src_addr; /**< Source address of request */ + unsigned src_addr_len; /**< Length of src address. */ - pj_bool_t use_candidate; /**< USE-CANDIDATE is present? */ - pj_uint32_t priority; /**< PRIORITY value in the req. */ - pj_stun_uint64_attr *role_attr; /**< ICE-CONTROLLING/CONTROLLED */ + pj_bool_t use_candidate; /**< USE-CANDIDATE is present? */ + pj_uint32_t priority; /**< PRIORITY value in the req. */ + pj_stun_uint64_attr *role_attr; /**< ICE-CONTROLLING/CONTROLLED */ } pj_ice_rx_check; @@ -640,7 +639,7 @@ typedef struct pj_ice_sess_options * Specify whether to use aggressive nomination. This setting can only * be enabled when trickle ICE is disabled. */ - pj_bool_t aggressive; + pj_bool_t aggressive; /** * For controlling agent if it uses regular nomination, specify the delay @@ -649,7 +648,7 @@ typedef struct pj_ice_sess_options * * Default value is PJ_ICE_NOMINATED_CHECK_DELAY. */ - unsigned nominated_check_delay; + unsigned nominated_check_delay; /** * For a controlled agent, specify how long it wants to wait (in @@ -663,7 +662,7 @@ typedef struct pj_ice_sess_options * ICE_CONTROLLED_AGENT_WAIT_NOMINATION_TIMEOUT. Specify -1 to disable * this timer. */ - int controlled_agent_want_nom_timeout; + int controlled_agent_want_nom_timeout; /** * Trickle ICE mode. Note that, when enabled, aggressive nomination will @@ -671,7 +670,7 @@ typedef struct pj_ice_sess_options * * Default value is PJ_ICE_SESS_TRICKLE_DISABLED. */ - pj_ice_sess_trickle trickle; + pj_ice_sess_trickle trickle; } pj_ice_sess_options; @@ -687,69 +686,69 @@ typedef struct pj_ice_sess_options */ struct pj_ice_sess { - char obj_name[PJ_MAX_OBJ_NAME]; /**< Object name. */ - - pj_pool_t *pool; /**< Pool instance. */ - void *user_data; /**< App. data. */ - pj_grp_lock_t *grp_lock; /**< Group lock */ - pj_ice_sess_role role; /**< ICE role. */ - pj_ice_sess_options opt; /**< Options */ - pj_timestamp tie_breaker; /**< Tie breaker value */ - pj_uint8_t *prefs; /**< Type preference. */ - pj_bool_t is_nominating; /**< Nominating stage */ - pj_bool_t is_complete; /**< Complete? */ - pj_bool_t is_destroying; /**< Destroy is called */ + char obj_name[PJ_MAX_OBJ_NAME]; /**< Object name. */ + + pj_pool_t *pool; /**< Pool instance. */ + void *user_data; /**< App. data. */ + pj_grp_lock_t *grp_lock; /**< Group lock */ + pj_ice_sess_role role; /**< ICE role. */ + pj_ice_sess_options opt; /**< Options */ + pj_timestamp tie_breaker; /**< Tie breaker value */ + pj_uint8_t *prefs; /**< Type preference. */ + pj_bool_t is_nominating; /**< Nominating stage */ + pj_bool_t is_complete; /**< Complete? */ + pj_bool_t is_destroying; /**< Destroy is called */ pj_bool_t valid_pair_found; /**< First pair found */ - pj_bool_t is_trickling; /**< End-of-candidates ind - sent/received? */ - pj_status_t ice_status; /**< Error status. */ - pj_timer_entry timer; /**< ICE timer. */ - pj_timer_entry timer_end_of_cand; /**< End-of-cand timer. */ - pj_ice_sess_cb cb; /**< Callback. */ + pj_bool_t is_trickling; /**< End-of-candidates ind + sent/received? */ + pj_status_t ice_status; /**< Error status. */ + pj_timer_entry timer; /**< ICE timer. */ + pj_timer_entry timer_end_of_cand; /**< End-of-cand timer. */ + pj_ice_sess_cb cb; /**< Callback. */ - pj_stun_config stun_cfg; /**< STUN settings. */ + pj_stun_config stun_cfg; /**< STUN settings. */ /* STUN credentials */ - pj_str_t tx_ufrag; /**< Remote ufrag. */ - pj_str_t tx_uname; /**< Uname for TX. */ - pj_str_t tx_pass; /**< Remote password. */ - pj_str_t rx_ufrag; /**< Local ufrag. */ - pj_str_t rx_uname; /**< Uname for RX */ - pj_str_t rx_pass; /**< Local password. */ + pj_str_t tx_ufrag; /**< Remote ufrag. */ + pj_str_t tx_uname; /**< Uname for TX. */ + pj_str_t tx_pass; /**< Remote password. */ + pj_str_t rx_ufrag; /**< Local ufrag. */ + pj_str_t rx_uname; /**< Uname for RX */ + pj_str_t rx_pass; /**< Local password. */ /* Components */ - unsigned comp_cnt; /**< # of components. */ - pj_ice_sess_comp comp[PJ_ICE_MAX_COMP]; /**< Component array */ - unsigned comp_ka; /**< Next comp for KA */ + unsigned comp_cnt; /**< # of components. */ + pj_ice_sess_comp comp[PJ_ICE_MAX_COMP]; /**< Component array */ + unsigned comp_ka; /**< Next comp for KA */ /* Local candidates */ - unsigned lcand_cnt; /**< # of local cand. */ - pj_ice_sess_cand lcand[PJ_ICE_MAX_CAND]; /**< Array of cand. */ - unsigned lcand_paired; /**< # of local cand - paired (trickling) */ + unsigned lcand_cnt; /**< # of local cand. */ + pj_ice_sess_cand lcand[PJ_ICE_MAX_CAND]; /**< Array of cand. */ + unsigned lcand_paired; /**< # of local cand + paired (trickling) */ /* Remote candidates */ - unsigned rcand_cnt; /**< # of remote cand. */ - pj_ice_sess_cand rcand[PJ_ICE_MAX_CAND]; /**< Array of cand. */ - unsigned rcand_paired; /**< # of remote cand - paired (trickling) */ + unsigned rcand_cnt; /**< # of remote cand. */ + pj_ice_sess_cand rcand[PJ_ICE_MAX_CAND]; /**< Array of cand. */ + unsigned rcand_paired; /**< # of remote cand + paired (trickling) */ /** Array of transport datas */ - pj_ice_msg_data tp_data[PJ_ICE_MAX_STUN + PJ_ICE_MAX_TURN]; + pj_ice_msg_data tp_data[PJ_ICE_MAX_STUN + PJ_ICE_MAX_TURN]; /* List of eearly checks */ - pj_ice_rx_check early_check; /**< Early checks. */ + pj_ice_rx_check early_check; /**< Early checks. */ /* Checklist */ - pj_ice_sess_checklist clist; /**< Active checklist */ + pj_ice_sess_checklist clist; /**< Active checklist */ /* Valid list */ - pj_ice_sess_checklist valid_list; /**< Valid list. */ + pj_ice_sess_checklist valid_list; /**< Valid list. */ /** Temporary buffer for misc stuffs to avoid using stack too much */ union { - char txt[128]; - char errmsg[PJ_ERR_MSG_SIZE]; + char txt[128]; + char errmsg[PJ_ERR_MSG_SIZE]; } tmp; }; @@ -758,9 +757,9 @@ struct pj_ice_sess * This is a utility function to retrieve the string name for the * particular candidate type. * - * @param type Candidate type. + * @param type Candidate type. * - * @return The string representation of the candidate type. + * @return The string representation of the candidate type. */ PJ_DECL(const char*) pj_ice_get_cand_type_name(pj_ice_cand_type type); @@ -769,9 +768,9 @@ PJ_DECL(const char*) pj_ice_get_cand_type_name(pj_ice_cand_type type); * This is a utility function to retrieve the string name for the * particular role type. * - * @param role Role type. + * @param role Role type. * - * @return The string representation of the role. + * @return The string representation of the role. */ PJ_DECL(const char*) pj_ice_sess_role_name(pj_ice_sess_role role); @@ -780,20 +779,20 @@ PJ_DECL(const char*) pj_ice_sess_role_name(pj_ice_sess_role role); * This is a utility function to calculate the foundation identification * for a candidate. * - * @param pool Pool to allocate the foundation string. - * @param foundation Pointer to receive the foundation string. - * @param type Candidate type. - * @param base_addr Base address of the candidate. + * @param pool Pool to allocate the foundation string. + * @param foundation Pointer to receive the foundation string. + * @param type Candidate type. + * @param base_addr Base address of the candidate. */ PJ_DECL(void) pj_ice_calc_foundation(pj_pool_t *pool, - pj_str_t *foundation, - pj_ice_cand_type type, - const pj_sockaddr *base_addr); + pj_str_t *foundation, + pj_ice_cand_type type, + const pj_sockaddr *base_addr); /** * Initialize ICE session options with library default values. * - * @param opt ICE session options. + * @param opt ICE session options. */ PJ_DECL(void) pj_ice_sess_options_default(pj_ice_sess_options *opt); @@ -804,46 +803,46 @@ PJ_DECL(void) pj_ice_sess_options_default(pj_ice_sess_options *opt); * application can register candidates to the ICE session by calling * #pj_ice_sess_add_cand() function. * - * @param stun_cfg The STUN configuration settings, containing among - * other things the timer heap instance to be used - * by the ICE session. - * @param name Optional name to identify this ICE instance in - * the log file. - * @param role ICE role. - * @param comp_cnt Number of components. - * @param cb ICE callback. - * @param local_ufrag Optional string to be used as local username to - * authenticate incoming STUN binding request. If - * the value is NULL, a random string will be - * generated. - * @param local_passwd Optional string to be used as local password. - * @param grp_lock Optional group lock to be used by this session. - * If NULL, the session will create one itself. - * @param p_ice Pointer to receive the ICE session instance. + * @param stun_cfg The STUN configuration settings, containing among + * other things the timer heap instance to be used + * by the ICE session. + * @param name Optional name to identify this ICE instance in + * the log file. + * @param role ICE role. + * @param comp_cnt Number of components. + * @param cb ICE callback. + * @param local_ufrag Optional string to be used as local username to + * authenticate incoming STUN binding request. If + * the value is NULL, a random string will be + * generated. + * @param local_passwd Optional string to be used as local password. + * @param grp_lock Optional group lock to be used by this session. + * If NULL, the session will create one itself. + * @param p_ice Pointer to receive the ICE session instance. * - * @return PJ_SUCCESS if ICE session is created successfully. + * @return PJ_SUCCESS if ICE session is created successfully. */ PJ_DECL(pj_status_t) pj_ice_sess_create(pj_stun_config *stun_cfg, - const char *name, - pj_ice_sess_role role, - unsigned comp_cnt, - const pj_ice_sess_cb *cb, - const pj_str_t *local_ufrag, - const pj_str_t *local_passwd, - pj_grp_lock_t *grp_lock, - pj_ice_sess **p_ice); + const char *name, + pj_ice_sess_role role, + unsigned comp_cnt, + const pj_ice_sess_cb *cb, + const pj_str_t *local_ufrag, + const pj_str_t *local_passwd, + pj_grp_lock_t *grp_lock, + pj_ice_sess **p_ice); /** * Get the value of various options of the ICE session. * - * @param ice The ICE session. - * @param opt The options to be initialized with the values - * from the ICE session. + * @param ice The ICE session. + * @param opt The options to be initialized with the values + * from the ICE session. * - * @return PJ_SUCCESS on success, or the appropriate error. + * @return PJ_SUCCESS on success, or the appropriate error. */ PJ_DECL(pj_status_t) pj_ice_sess_get_options(pj_ice_sess *ice, - pj_ice_sess_options *opt); + pj_ice_sess_options *opt); /** * Specify various options for this ICE session. Application MUST only @@ -853,13 +852,13 @@ PJ_DECL(pj_status_t) pj_ice_sess_get_options(pj_ice_sess *ice, * Application should call #pj_ice_sess_get_options() to initialize the * options with their default values. * - * @param ice The ICE session. - * @param opt Options to be applied to the ICE session. + * @param ice The ICE session. + * @param opt Options to be applied to the ICE session. * - * @return PJ_SUCCESS on success, or the appropriate error. + * @return PJ_SUCCESS on success, or the appropriate error. */ PJ_DECL(pj_status_t) pj_ice_sess_set_options(pj_ice_sess *ice, - const pj_ice_sess_options *opt); + const pj_ice_sess_options *opt); /** @@ -872,14 +871,14 @@ PJ_DECL(pj_status_t) pj_ice_sess_set_options(pj_ice_sess *ice, * (by calling the group lock handler) without waiting for the group lock * destroy to avoid memory bloat. * - * @param ice ICE session instance. - * @param handler Pointer to receive the group lock handler of - * this ICE session. + * @param ice ICE session instance. + * @param handler Pointer to receive the group lock handler of + * this ICE session. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pj_ice_sess_detach_grp_lock(pj_ice_sess *ice, - pj_grp_lock_handler *handler); + pj_grp_lock_handler *handler); /** @@ -887,9 +886,9 @@ PJ_DECL(pj_status_t) pj_ice_sess_detach_grp_lock(pj_ice_sess *ice, * running, if any, and any other events scheduled by this session, as well * as all memory resources. * - * @param ice ICE session instance. + * @param ice ICE session instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pj_ice_sess_destroy(pj_ice_sess *ice); @@ -900,13 +899,13 @@ PJ_DECL(pj_status_t) pj_ice_sess_destroy(pj_ice_sess *ice); * that the offer contains "a=ice-lite" attribute when the SDP gets * inspected. * - * @param ice The ICE session. - * @param new_role The new role to be set. + * @param ice The ICE session. + * @param new_role The new role to be set. * - * @return PJ_SUCCESS on success, or the appropriate error. + * @return PJ_SUCCESS on success, or the appropriate error. */ PJ_DECL(pj_status_t) pj_ice_sess_change_role(pj_ice_sess *ice, - pj_ice_sess_role new_role); + pj_ice_sess_role new_role); /** @@ -919,15 +918,15 @@ PJ_DECL(pj_status_t) pj_ice_sess_change_role(pj_ice_sess *ice, * Note that this function must be called before any candidates are added * to the ICE session. * - * @param ice The ICE session. - * @param prefs Array of candidate preference value. The values are - * put in the array indexed by the candidate type as - * specified in pj_ice_cand_type. + * @param ice The ICE session. + * @param prefs Array of candidate preference value. The values are + * put in the array indexed by the candidate type as + * specified in pj_ice_cand_type. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ice_sess_set_prefs(pj_ice_sess *ice, - const pj_uint8_t prefs[4]); + const pj_uint8_t prefs[4]); @@ -936,33 +935,33 @@ PJ_DECL(pj_status_t) pj_ice_sess_set_prefs(pj_ice_sess *ice, * each components ID before it can start pairing the candidates and * performing connectivity checks. * - * @param ice ICE session instance. - * @param comp_id Component ID of this candidate. - * @param transport_id Transport ID to be used to send packets for this - * candidate. - * @param type Candidate type. - * @param local_pref Local preference for this candidate, which - * normally should be set to 65535. - * @param foundation Foundation identification. - * @param addr The candidate address. - * @param base_addr The candidate's base address. - * @param rel_addr Optional related address. - * @param addr_len Length of addresses. - * @param p_cand_id Optional pointer to receive the candidate ID. + * @param ice ICE session instance. + * @param comp_id Component ID of this candidate. + * @param transport_id Transport ID to be used to send packets for this + * candidate. + * @param type Candidate type. + * @param local_pref Local preference for this candidate, which + * normally should be set to 65535. + * @param foundation Foundation identification. + * @param addr The candidate address. + * @param base_addr The candidate's base address. + * @param rel_addr Optional related address. + * @param addr_len Length of addresses. + * @param p_cand_id Optional pointer to receive the candidate ID. * - * @return PJ_SUCCESS if candidate is successfully added. + * @return PJ_SUCCESS if candidate is successfully added. */ PJ_DECL(pj_status_t) pj_ice_sess_add_cand(pj_ice_sess *ice, - unsigned comp_id, - unsigned transport_id, - pj_ice_cand_type type, - pj_uint16_t local_pref, - const pj_str_t *foundation, - const pj_sockaddr_t *addr, - const pj_sockaddr_t *base_addr, - const pj_sockaddr_t *rel_addr, - int addr_len, - unsigned *p_cand_id); + unsigned comp_id, + unsigned transport_id, + pj_ice_cand_type type, + pj_uint16_t local_pref, + const pj_str_t *foundation, + const pj_sockaddr_t *addr, + const pj_sockaddr_t *base_addr, + const pj_sockaddr_t *rel_addr, + int addr_len, + unsigned *p_cand_id); /** * Find default candidate for the specified component ID, using this @@ -972,15 +971,15 @@ PJ_DECL(pj_status_t) pj_ice_sess_add_cand(pj_ice_sess *ice, * - otherwise a relay, reflexive, or host candidate will be selected * on that specified order. * - * @param ice The ICE session instance. - * @param comp_id The component ID. - * @param p_cand_id Pointer to receive the candidate ID. + * @param ice The ICE session instance. + * @param comp_id The component ID. + * @param p_cand_id Pointer to receive the candidate ID. * - * @return PJ_SUCCESS if a candidate has been selected. + * @return PJ_SUCCESS if a candidate has been selected. */ PJ_DECL(pj_status_t) pj_ice_sess_find_default_cand(pj_ice_sess *ice, - unsigned comp_id, - int *p_cand_id); + unsigned comp_id, + int *p_cand_id); /** * Pair the local and remote candidates to create check list. Application @@ -991,24 +990,24 @@ PJ_DECL(pj_status_t) pj_ice_sess_find_default_cand(pj_ice_sess *ice, * Note that ICE connectivity check will not start until application calls * #pj_ice_sess_start_check(). * - * @param ice ICE session instance. - * @param rem_ufrag Remote ufrag, as seen in the SDP received from - * the remote agent. - * @param rem_passwd Remote password, as seen in the SDP received from - * the remote agent. - * @param rem_cand_cnt Number of remote candidates. - * @param rem_cand Remote candidate array. Remote candidates are - * gathered from the SDP received from the remote - * agent. + * @param ice ICE session instance. + * @param rem_ufrag Remote ufrag, as seen in the SDP received from + * the remote agent. + * @param rem_passwd Remote password, as seen in the SDP received from + * the remote agent. + * @param rem_cand_cnt Number of remote candidates. + * @param rem_cand Remote candidate array. Remote candidates are + * gathered from the SDP received from the remote + * agent. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ice_sess_create_check_list(pj_ice_sess *ice, - const pj_str_t *rem_ufrag, - const pj_str_t *rem_passwd, - unsigned rem_cand_cnt, - const pj_ice_sess_cand rem_cand[]); + const pj_str_t *rem_ufrag, + const pj_str_t *rem_passwd, + unsigned rem_cand_cnt, + const pj_ice_sess_cand rem_cand[]); /** @@ -1020,29 +1019,29 @@ pj_ice_sess_create_check_list(pj_ice_sess *ice, * * This function is only applicable when trickle ICE is not disabled. * - * @param ice ICE session instance. - * @param rem_ufrag Remote ufrag, as seen in the SDP received from - * the remote agent. - * @param rem_passwd Remote password, as seen in the SDP received from - * the remote agent. - * @param rem_cand_cnt Number of remote candidates. - * @param rem_cand Remote candidate array. Remote candidates are - * gathered from the SDP received from the remote - * agent. - * @param trickle_done Flag to indicate end of trickling, set to PJ_TRUE - * after all local candidates have been gathered AND - * after receiving end-of-candidate indication from - * remote. + * @param ice ICE session instance. + * @param rem_ufrag Remote ufrag, as seen in the SDP received from + * the remote agent. + * @param rem_passwd Remote password, as seen in the SDP received from + * the remote agent. + * @param rem_cand_cnt Number of remote candidates. + * @param rem_cand Remote candidate array. Remote candidates are + * gathered from the SDP received from the remote + * agent. + * @param trickle_done Flag to indicate end of trickling, set to PJ_TRUE + * after all local candidates have been gathered AND + * after receiving end-of-candidate indication from + * remote. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ice_sess_update_check_list(pj_ice_sess *ice, - const pj_str_t *rem_ufrag, - const pj_str_t *rem_passwd, - unsigned rem_cand_cnt, - const pj_ice_sess_cand rem_cand[], - pj_bool_t trickle_done); + const pj_str_t *rem_ufrag, + const pj_str_t *rem_passwd, + unsigned rem_cand_cnt, + const pj_ice_sess_cand rem_cand[], + pj_bool_t trickle_done); /** @@ -1050,9 +1049,9 @@ pj_ice_sess_update_check_list(pj_ice_sess *ice, * application will be notified about the connectivity check status in * #pj_ice_sess_cb callback. * - * @param ice The ICE session instance. + * @param ice The ICE session instance. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ice_sess_start_check(pj_ice_sess *ice); @@ -1067,20 +1066,20 @@ PJ_DECL(pj_status_t) pj_ice_sess_start_check(pj_ice_sess *ice); * This function will in turn call \a on_tx_pkt function in * #pj_ice_sess_cb callback to actually send the packet to the wire. * - * @param ice The ICE session. - * @param comp_id Component ID. - * @param data The data or packet to be sent. - * @param data_len Size of data or packet, in bytes. + * @param ice The ICE session. + * @param comp_id Component ID. + * @param data The data or packet to be sent. + * @param data_len Size of data or packet, in bytes. * - * @return If the callback \a on_tx_pkt() is called, this - * will contain the return value of the callback. - * Otherwise, it will indicate failure with - * the appropriate error code. + * @return If the callback \a on_tx_pkt() is called, this + * will contain the return value of the callback. + * Otherwise, it will indicate failure with + * the appropriate error code. */ PJ_DECL(pj_status_t) pj_ice_sess_send_data(pj_ice_sess *ice, - unsigned comp_id, - const void *data, - pj_size_t data_len); + unsigned comp_id, + const void *data, + pj_size_t data_len); /** * Report the arrival of packet to the ICE session. Since ICE session @@ -1089,25 +1088,25 @@ PJ_DECL(pj_status_t) pj_ice_sess_send_data(pj_ice_sess *ice, * If the packet is not a STUN packet, this packet will be given back * to application via \a on_rx_data() callback in #pj_ice_sess_cb. * - * @param ice The ICE session. - * @param comp_id Component ID. - * @param transport_id Number to identify where this packet was received - * from. This parameter will be returned back to - * application in \a on_tx_pkt() callback. - * @param pkt Incoming packet. - * @param pkt_size Size of incoming packet. - * @param src_addr Source address of the packet. - * @param src_addr_len Length of the address. + * @param ice The ICE session. + * @param comp_id Component ID. + * @param transport_id Number to identify where this packet was received + * from. This parameter will be returned back to + * application in \a on_tx_pkt() callback. + * @param pkt Incoming packet. + * @param pkt_size Size of incoming packet. + * @param src_addr Source address of the packet. + * @param src_addr_len Length of the address. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ice_sess_on_rx_pkt(pj_ice_sess *ice, - unsigned comp_id, - unsigned transport_id, - void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *src_addr, - int src_addr_len); + unsigned comp_id, + unsigned transport_id, + void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *src_addr, + int src_addr_len); @@ -1119,5 +1118,5 @@ PJ_DECL(pj_status_t) pj_ice_sess_on_rx_pkt(pj_ice_sess *ice, PJ_END_DECL -#endif /* __PJNATH_ICE_SESSION_H__ */ +#endif /* __PJNATH_ICE_SESSION_H__ */ diff --git a/pjnath/include/pjnath/ice_strans.h b/pjnath/include/pjnath/ice_strans.h index b9ccfc6ea4..0f2510aa43 100644 --- a/pjnath/include/pjnath/ice_strans.h +++ b/pjnath/include/pjnath/ice_strans.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -61,10 +60,10 @@ PJ_BEGIN_DECL * the STUN and TURN settings.\n\n * - create the instance with #pj_ice_strans_create(). Among other things, * the function needs the following arguments: - * - the #pj_ice_strans_cfg structure for the main configurations - * - number of components to be supported - * - instance of #pj_ice_strans_cb structure to report callbacks to - * application.\n\n + * - the #pj_ice_strans_cfg structure for the main configurations + * - number of components to be supported + * - instance of #pj_ice_strans_cb structure to report callbacks to + * application.\n\n * - while the #pj_ice_strans_create() call completes immediately, the * initialization will be running in the background to gather the * candidates (for example STUN and TURN candidates, if they are enabled @@ -77,9 +76,9 @@ PJ_BEGIN_DECL * - the application now typically will need to communicate local ICE * information to remote host. It can achieve this by using the following * functions to query local ICE information: - * - #pj_ice_strans_get_ufrag_pwd() - * - #pj_ice_strans_enum_cands() - * - #pj_ice_strans_get_def_cand()\n + * - #pj_ice_strans_get_ufrag_pwd() + * - #pj_ice_strans_enum_cands() + * - #pj_ice_strans_get_def_cand()\n * The application may need to encode the above information as SDP.\n\n * - when the application receives remote ICE information (for example, from * the SDP received from remote), it can now start ICE negotiation, by @@ -118,7 +117,7 @@ PJ_BEGIN_DECL * https://github.com/pjsip/pjproject/issues/2229 for more details. */ #ifndef DEPRECATED_FOR_TICKET_2229 -# define DEPRECATED_FOR_TICKET_2229 0 +# define DEPRECATED_FOR_TICKET_2229 0 #endif /** Forward declaration for ICE stream transport. */ @@ -155,50 +154,50 @@ typedef struct pj_ice_strans_cb * incoming packet from the sockets which is not related to ICE * (for example, normal RTP/RTCP packet destined for application). * - * @param ice_st The ICE stream transport. - * @param comp_id The component ID. - * @param pkt The packet. - * @param size Size of the packet. - * @param src_addr Source address of the packet. + * @param ice_st The ICE stream transport. + * @param comp_id The component ID. + * @param pkt The packet. + * @param size Size of the packet. + * @param src_addr Source address of the packet. * @param src_addr_len Length of the source address. */ void (*on_rx_data)(pj_ice_strans *ice_st, - unsigned comp_id, - void *pkt, pj_size_t size, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + unsigned comp_id, + void *pkt, pj_size_t size, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); /** * This callback is optional and will be called to notify the status of * async send operations. * - * @param ice_st The ICE stream transport. - * @param sent If value is positive non-zero it indicates the - * number of data sent. When the value is negative, - * it contains the error code which can be retrieved - * by negating the value (i.e. status=-sent). + * @param ice_st The ICE stream transport. + * @param sent If value is positive non-zero it indicates the + * number of data sent. When the value is negative, + * it contains the error code which can be retrieved + * by negating the value (i.e. status=-sent). */ void (*on_data_sent)(pj_ice_strans *sock, - pj_ssize_t sent); + pj_ssize_t sent); /** * An optional callback that will be called by the ICE transport when a * valid pair has been found during ICE negotiation. * - * @param ice_st The ICE stream transport. + * @param ice_st The ICE stream transport. */ void (*on_valid_pair)(pj_ice_strans *ice_st); /** * Callback to report status of various ICE operations. * - * @param ice_st The ICE stream transport. - * @param op The operation which status is being reported. - * @param status Operation status. + * @param ice_st The ICE stream transport. + * @param op The operation which status is being reported. + * @param status Operation status. */ void (*on_ice_complete)(pj_ice_strans *ice_st, - pj_ice_strans_op op, - pj_status_t status); + pj_ice_strans_op op, + pj_status_t status); /** * Callback to report a new ICE local candidate, e.g: after successful @@ -210,14 +209,14 @@ typedef struct pj_ice_strans_cb * Trickle ICE can use this callback to convey the new candidate * to remote agent and monitor end-of-candidate indication. * - * @param ice_st The ICE stream transport. - * @param cand The new local candidate, can be NULL when the last - * local candidate initialization failed/timeout. + * @param ice_st The ICE stream transport. + * @param cand The new local candidate, can be NULL when the last + * local candidate initialization failed/timeout. * @param end_of_cand PJ_TRUE if this is the last of local candidate. */ void (*on_new_candidate)(pj_ice_strans *ice_st, - const pj_ice_sess_cand *cand, - pj_bool_t end_of_cand); + const pj_ice_sess_cand *cand, + pj_bool_t end_of_cand); } pj_ice_strans_cb; @@ -232,13 +231,13 @@ typedef struct pj_ice_strans_stun_cfg * * Default value is pj_AF_INET() (IPv4) */ - int af; + int af; /** * Optional configuration for STUN transport. The default * value will be initialized with #pj_stun_sock_cfg_default(). */ - pj_stun_sock_cfg cfg; + pj_stun_sock_cfg cfg; /** * Maximum number of host candidates to be added. If the @@ -246,14 +245,14 @@ typedef struct pj_ice_strans_stun_cfg * * Default: 64 */ - unsigned max_host_cands; + unsigned max_host_cands; /** * Include loopback addresses in the host candidates. * * Default: PJ_FALSE */ - pj_bool_t loop_addr; + pj_bool_t loop_addr; /** * Specify the STUN server domain or hostname or IP address. @@ -279,7 +278,7 @@ typedef struct pj_ice_strans_stun_cfg * * The default value is empty. */ - pj_str_t server; + pj_str_t server; /** * The port number of the STUN server, when \a server @@ -291,7 +290,7 @@ typedef struct pj_ice_strans_stun_cfg * * The default value is PJ_STUN_PORT. */ - pj_uint16_t port; + pj_uint16_t port; /** * Ignore STUN resolution error and proceed with just local @@ -299,7 +298,7 @@ typedef struct pj_ice_strans_stun_cfg * * The default is PJ_FALSE */ - pj_bool_t ignore_stun_error; + pj_bool_t ignore_stun_error; } pj_ice_strans_stun_cfg; @@ -314,14 +313,14 @@ typedef struct pj_ice_strans_turn_cfg * * Default value is pj_AF_INET() (IPv4) */ - int af; + int af; /** * Optional TURN socket settings. The default values will be * initialized by #pj_turn_sock_cfg_default(). This contains * settings such as QoS. */ - pj_turn_sock_cfg cfg; + pj_turn_sock_cfg cfg; /** * Specify the TURN server domain or hostname or IP address. @@ -340,7 +339,7 @@ typedef struct pj_ice_strans_turn_cfg * * The default value is empty. */ - pj_str_t server; + pj_str_t server; /** * The port number of the TURN server, when \a server @@ -352,14 +351,14 @@ typedef struct pj_ice_strans_turn_cfg * * Default is zero. */ - pj_uint16_t port; + pj_uint16_t port; /** * Type of connection to the TURN server. * * Default is PJ_TURN_TP_UDP. */ - pj_turn_tp_type conn_type; + pj_turn_tp_type conn_type; /** * Credential to be used for the TURN session. This setting @@ -367,13 +366,13 @@ typedef struct pj_ice_strans_turn_cfg * * Default is to have no credential. */ - pj_stun_auth_cred auth_cred; + pj_stun_auth_cred auth_cred; /** * Optional TURN Allocate parameter. The default value will be * initialized by #pj_turn_alloc_param_default(). */ - pj_turn_alloc_param alloc_param; + pj_turn_alloc_param alloc_param; } pj_ice_strans_turn_cfg; @@ -393,7 +392,7 @@ typedef struct pj_ice_strans_cfg * * The default value is pj_AF_INET() (IPv4). */ - int af; + int af; /** * STUN configuration which contains the timer heap and @@ -403,7 +402,7 @@ typedef struct pj_ice_strans_cfg * The default value is all zero. Application must initialize * this setting with #pj_stun_config_init(). */ - pj_stun_config stun_cfg; + pj_stun_config stun_cfg; /** * DNS resolver to be used to resolve servers. If DNS SRV @@ -411,14 +410,14 @@ typedef struct pj_ice_strans_cfg * * The default value is NULL. */ - pj_dns_resolver *resolver; + pj_dns_resolver *resolver; /** * This contains various STUN session options. Once the ICE stream * transport is created, application may also change the options * with #pj_ice_strans_set_options(). */ - pj_ice_sess_options opt; + pj_ice_sess_options opt; /** * Warning: this field is deprecated, please use \a stun_tp field instead. @@ -435,7 +434,7 @@ typedef struct pj_ice_strans_cfg * * Default: 0 */ - unsigned stun_tp_cnt; + unsigned stun_tp_cnt; /** * STUN and local transport settings. This specifies the settings @@ -457,7 +456,7 @@ typedef struct pj_ice_strans_cfg * * Default: 0 */ - unsigned turn_tp_cnt; + unsigned turn_tp_cnt; /** * TURN transport settings. @@ -475,14 +474,14 @@ typedef struct pj_ice_strans_cfg * * Default: 4 */ - unsigned num_send_buf; + unsigned num_send_buf; /** * Buffer size used for pj_ice_strans_sendto2(). * * Default: 0 (size determined by the size of the first packet sent). */ - unsigned send_buf_size; + unsigned send_buf_size; /** * Component specific settings, which will override the settings in @@ -491,58 +490,58 @@ typedef struct pj_ice_strans_cfg * traffic type for RTP and RTCP component. */ struct { - /** - * QoS traffic type to be set on this transport. When application - * wants to apply QoS tagging to the transport, it's preferable to - * set this field rather than \a qos_param fields since this is - * more portable. - * - * Default value is PJ_QOS_TYPE_BEST_EFFORT. - */ - pj_qos_type qos_type; - - /** - * Set the low level QoS parameters to the transport. This is a - * lower level operation than setting the \a qos_type field and - * may not be supported on all platforms. - * - * By default all settings in this structure are disabled. - */ - pj_qos_params qos_params; - - /** - * Specify target value for socket receive buffer size. It will be - * applied using setsockopt(). When it fails to set the specified - * size, it will try with lower value until the highest possible is - * successfully set. - * - * When this is set to zero, this component will apply socket receive - * buffer size settings specified in STUN and TURN socket config - * above, i.e: \a stun::cfg::so_rcvbuf_size and - * \a turn::cfg::so_rcvbuf_size. Otherwise, this setting will be - * applied to STUN and TURN sockets for this component, overriding - * the setting specified in STUN/TURN socket config. - * - * Default: 0 - */ - unsigned so_rcvbuf_size; - - /** - * Specify target value for socket send buffer size. It will be - * applied using setsockopt(). When it fails to set the specified - * size, it will try with lower value until the highest possible is - * successfully set. - * - * When this is set to zero, this component will apply socket send - * buffer size settings specified in STUN and TURN socket config - * above, i.e: \a stun::cfg::so_sndbuf_size and - * \a turn::cfg::so_sndbuf_size. Otherwise, this setting will be - * applied to STUN and TURN sockets for this component, overriding - * the setting specified in STUN/TURN socket config. - * - * Default: 0 - */ - unsigned so_sndbuf_size; + /** + * QoS traffic type to be set on this transport. When application + * wants to apply QoS tagging to the transport, it's preferable to + * set this field rather than \a qos_param fields since this is + * more portable. + * + * Default value is PJ_QOS_TYPE_BEST_EFFORT. + */ + pj_qos_type qos_type; + + /** + * Set the low level QoS parameters to the transport. This is a + * lower level operation than setting the \a qos_type field and + * may not be supported on all platforms. + * + * By default all settings in this structure are disabled. + */ + pj_qos_params qos_params; + + /** + * Specify target value for socket receive buffer size. It will be + * applied using setsockopt(). When it fails to set the specified + * size, it will try with lower value until the highest possible is + * successfully set. + * + * When this is set to zero, this component will apply socket receive + * buffer size settings specified in STUN and TURN socket config + * above, i.e: \a stun::cfg::so_rcvbuf_size and + * \a turn::cfg::so_rcvbuf_size. Otherwise, this setting will be + * applied to STUN and TURN sockets for this component, overriding + * the setting specified in STUN/TURN socket config. + * + * Default: 0 + */ + unsigned so_rcvbuf_size; + + /** + * Specify target value for socket send buffer size. It will be + * applied using setsockopt(). When it fails to set the specified + * size, it will try with lower value until the highest possible is + * successfully set. + * + * When this is set to zero, this component will apply socket send + * buffer size settings specified in STUN and TURN socket config + * above, i.e: \a stun::cfg::so_sndbuf_size and + * \a turn::cfg::so_sndbuf_size. Otherwise, this setting will be + * applied to STUN and TURN sockets for this component, overriding + * the setting specified in STUN/TURN socket config. + * + * Default: 0 + */ + unsigned so_sndbuf_size; } comp[PJ_ICE_MAX_COMP]; @@ -597,7 +596,7 @@ typedef enum pj_ice_strans_state /** * Initialize ICE transport configuration with default values. * - * @param cfg The configuration to be initialized. + * @param cfg The configuration to be initialized. */ PJ_DECL(void) pj_ice_strans_cfg_default(pj_ice_strans_cfg *cfg); @@ -605,7 +604,7 @@ PJ_DECL(void) pj_ice_strans_cfg_default(pj_ice_strans_cfg *cfg); /** * Initialize ICE STUN transport configuration with default values. * - * @param cfg The configuration to be initialized. + * @param cfg The configuration to be initialized. */ PJ_DECL(void) pj_ice_strans_stun_cfg_default(pj_ice_strans_stun_cfg *cfg); @@ -613,7 +612,7 @@ PJ_DECL(void) pj_ice_strans_stun_cfg_default(pj_ice_strans_stun_cfg *cfg); /** * Initialize ICE TURN transport configuration with default values. * - * @param cfg The configuration to be initialized. + * @param cfg The configuration to be initialized. */ PJ_DECL(void) pj_ice_strans_turn_cfg_default(pj_ice_strans_turn_cfg *cfg); @@ -621,44 +620,44 @@ PJ_DECL(void) pj_ice_strans_turn_cfg_default(pj_ice_strans_turn_cfg *cfg); /** * Copy configuration. * - * @param pool Pool. - * @param dst Destination. - * @param src Source. + * @param pool Pool. + * @param dst Destination. + * @param src Source. */ PJ_DECL(void) pj_ice_strans_cfg_copy(pj_pool_t *pool, - pj_ice_strans_cfg *dst, - const pj_ice_strans_cfg *src); + pj_ice_strans_cfg *dst, + const pj_ice_strans_cfg *src); /** * Create and initialize the ICE stream transport with the specified * parameters. * - * @param name Optional name for logging identification. - * @param cfg Configuration. - * @param comp_cnt Number of components. - * @param user_data Arbitrary user data to be associated with this - * ICE stream transport. - * @param cb Callback. - * @param p_ice_st Pointer to receive the ICE stream transport - * instance. - * - * @return PJ_SUCCESS if ICE stream transport is created - * successfully. + * @param name Optional name for logging identification. + * @param cfg Configuration. + * @param comp_cnt Number of components. + * @param user_data Arbitrary user data to be associated with this + * ICE stream transport. + * @param cb Callback. + * @param p_ice_st Pointer to receive the ICE stream transport + * instance. + * + * @return PJ_SUCCESS if ICE stream transport is created + * successfully. */ PJ_DECL(pj_status_t) pj_ice_strans_create(const char *name, - const pj_ice_strans_cfg *cfg, - unsigned comp_cnt, - void *user_data, - const pj_ice_strans_cb *cb, - pj_ice_strans **p_ice_st); + const pj_ice_strans_cfg *cfg, + unsigned comp_cnt, + void *user_data, + const pj_ice_strans_cb *cb, + pj_ice_strans **p_ice_st); /** * Get ICE session state. * - * @param ice_st The ICE stream transport. + * @param ice_st The ICE stream transport. * - * @return ICE session state. + * @return ICE session state. */ PJ_DECL(pj_ice_strans_state) pj_ice_strans_get_state(pj_ice_strans *ice_st); @@ -666,9 +665,9 @@ PJ_DECL(pj_ice_strans_state) pj_ice_strans_get_state(pj_ice_strans *ice_st); /** * Get string representation of ICE state. * - * @param state ICE stream transport state. + * @param state ICE stream transport state. * - * @return String. + * @return String. */ PJ_DECL(const char*) pj_ice_strans_state_name(pj_ice_strans_state state); @@ -678,9 +677,9 @@ PJ_DECL(const char*) pj_ice_strans_state_name(pj_ice_strans_state state); * inside the ICE stream transport, close all sockets and release all * other resources. * - * @param ice_st The ICE stream transport. + * @param ice_st The ICE stream transport. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ice_strans_destroy(pj_ice_strans *ice_st); @@ -688,9 +687,9 @@ PJ_DECL(pj_status_t) pj_ice_strans_destroy(pj_ice_strans *ice_st); /** * Get the user data associated with the ICE stream transport. * - * @param ice_st The ICE stream transport. + * @param ice_st The ICE stream transport. * - * @return The user data. + * @return The user data. */ PJ_DECL(void*) pj_ice_strans_get_user_data(pj_ice_strans *ice_st); @@ -698,47 +697,47 @@ PJ_DECL(void*) pj_ice_strans_get_user_data(pj_ice_strans *ice_st); /** * Get the value of various options of the ICE stream transport. * - * @param ice_st The ICE stream transport. - * @param opt The options to be initialized with the values - * from the ICE stream transport. + * @param ice_st The ICE stream transport. + * @param opt The options to be initialized with the values + * from the ICE stream transport. * - * @return PJ_SUCCESS on success, or the appropriate error. + * @return PJ_SUCCESS on success, or the appropriate error. */ PJ_DECL(pj_status_t) pj_ice_strans_get_options(pj_ice_strans *ice_st, - pj_ice_sess_options *opt); + pj_ice_sess_options *opt); /** * Specify various options for this ICE stream transport. Application * should call #pj_ice_strans_get_options() to initialize the options * with their default values. * - * @param ice_st The ICE stream transport. - * @param opt Options to be applied to this ICE stream transport. + * @param ice_st The ICE stream transport. + * @param opt Options to be applied to this ICE stream transport. * - * @return PJ_SUCCESS on success, or the appropriate error. + * @return PJ_SUCCESS on success, or the appropriate error. */ PJ_DECL(pj_status_t) pj_ice_strans_set_options(pj_ice_strans *ice_st, - const pj_ice_sess_options *opt); + const pj_ice_sess_options *opt); /** * Update number of components of the ICE stream transport. This can only * reduce the number of components from the initial value specified in * pj_ice_strans_create() and before ICE session is initialized. * - * @param ice_st The ICE stream transport. - * @param comp_cnt Number of components. + * @param ice_st The ICE stream transport. + * @param comp_cnt Number of components. * - * @return PJ_SUCCESS on success, or the appropriate error. + * @return PJ_SUCCESS on success, or the appropriate error. */ PJ_DECL(pj_status_t) pj_ice_strans_update_comp_cnt(pj_ice_strans *ice_st, - unsigned comp_cnt); + unsigned comp_cnt); /** * Get the group lock for this ICE stream transport. * - * @param ice_st The ICE stream transport. + * @param ice_st The ICE stream transport. * - * @return The group lock. + * @return The group lock. */ PJ_DECL(pj_grp_lock_t *) pj_ice_strans_get_grp_lock(pj_ice_strans *ice_st); @@ -752,26 +751,26 @@ PJ_DECL(pj_grp_lock_t *) pj_ice_strans_get_grp_lock(pj_ice_strans *ice_st); * candidates by calling #pj_ice_strans_enum_cands(), and encode these * candidates in the SDP to be sent to remote agent. * - * @param ice_st The ICE stream transport. - * @param role ICE role. - * @param local_ufrag Optional local username fragment. - * @param local_passwd Optional local password. + * @param ice_st The ICE stream transport. + * @param role ICE role. + * @param local_ufrag Optional local username fragment. + * @param local_passwd Optional local password. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ice_strans_init_ice(pj_ice_strans *ice_st, - pj_ice_sess_role role, - const pj_str_t *local_ufrag, - const pj_str_t *local_passwd); + pj_ice_sess_role role, + const pj_str_t *local_ufrag, + const pj_str_t *local_passwd); /** * Check if the ICE stream transport has the ICE session created. The * ICE session is created with #pj_ice_strans_init_ice(). * - * @param ice_st The ICE stream transport. + * @param ice_st The ICE stream transport. * - * @return PJ_TRUE if #pj_ice_strans_init_ice() has been - * called. + * @return PJ_TRUE if #pj_ice_strans_init_ice() has been + * called. */ PJ_DECL(pj_bool_t) pj_ice_strans_has_sess(pj_ice_strans *ice_st); @@ -779,10 +778,10 @@ PJ_DECL(pj_bool_t) pj_ice_strans_has_sess(pj_ice_strans *ice_st); /** * Check if ICE negotiation is still running. * - * @param ice_st The ICE stream transport. + * @param ice_st The ICE stream transport. * - * @return PJ_TRUE if ICE session has been created and ICE - * negotiation negotiation is in progress. + * @return PJ_TRUE if ICE session has been created and ICE + * negotiation negotiation is in progress. */ PJ_DECL(pj_bool_t) pj_ice_strans_sess_is_running(pj_ice_strans *ice_st); @@ -790,10 +789,10 @@ PJ_DECL(pj_bool_t) pj_ice_strans_sess_is_running(pj_ice_strans *ice_st); /** * Check if ICE negotiation has completed. * - * @param ice_st The ICE stream transport. + * @param ice_st The ICE stream transport. * - * @return PJ_TRUE if ICE session has been created and the - * negotiation is complete. + * @return PJ_TRUE if ICE session has been created and the + * negotiation is complete. */ PJ_DECL(pj_bool_t) pj_ice_strans_sess_is_complete(pj_ice_strans *ice_st); @@ -805,9 +804,9 @@ PJ_DECL(pj_bool_t) pj_ice_strans_sess_is_complete(pj_ice_strans *ice_st); * started, the number of components will be the lowest number of * component between local and remote agents. * - * @param ice_st The ICE stream transport. + * @param ice_st The ICE stream transport. * - * @return The running number of components. + * @return The running number of components. */ PJ_DECL(unsigned) pj_ice_strans_get_running_comp_cnt(pj_ice_strans *ice_st); @@ -825,54 +824,54 @@ PJ_DECL(unsigned) pj_ice_strans_get_running_comp_cnt(pj_ice_strans *ice_st); * #pj_ice_strans_stop_ice(), the pointer in the string will no longer be * valid. * - * @param ice_st The ICE stream transport. - * @param loc_ufrag Optional pointer to receive ICE username fragment - * of local endpoint from the ICE session. - * @param loc_pwd Optional pointer to receive ICE password of local - * endpoint from the ICE session. - * @param rem_ufrag Optional pointer to receive ICE username fragment - * of remote endpoint from the ICE session. - * @param rem_pwd Optional pointer to receive ICE password of remote - * endpoint from the ICE session. - * - * @return PJ_SUCCESS if the strings have been retrieved - * successfully. + * @param ice_st The ICE stream transport. + * @param loc_ufrag Optional pointer to receive ICE username fragment + * of local endpoint from the ICE session. + * @param loc_pwd Optional pointer to receive ICE password of local + * endpoint from the ICE session. + * @param rem_ufrag Optional pointer to receive ICE username fragment + * of remote endpoint from the ICE session. + * @param rem_pwd Optional pointer to receive ICE password of remote + * endpoint from the ICE session. + * + * @return PJ_SUCCESS if the strings have been retrieved + * successfully. */ PJ_DECL(pj_status_t) pj_ice_strans_get_ufrag_pwd(pj_ice_strans *ice_st, - pj_str_t *loc_ufrag, - pj_str_t *loc_pwd, - pj_str_t *rem_ufrag, - pj_str_t *rem_pwd); + pj_str_t *loc_ufrag, + pj_str_t *loc_pwd, + pj_str_t *rem_ufrag, + pj_str_t *rem_pwd); /** * Get the number of local candidates for the specified component ID. * - * @param ice_st The ICE stream transport. - * @param comp_id Component ID. + * @param ice_st The ICE stream transport. + * @param comp_id Component ID. * - * @return The number of candidates. + * @return The number of candidates. */ PJ_DECL(unsigned) pj_ice_strans_get_cands_count(pj_ice_strans *ice_st, - unsigned comp_id); + unsigned comp_id); /** * Enumerate the local candidates for the specified component. * - * @param ice_st The ICE stream transport. - * @param comp_id Component ID. - * @param count On input, it specifies the maximum number of - * elements. On output, it will be filled with - * the number of candidates copied to the - * array. - * @param cand Array of candidates. + * @param ice_st The ICE stream transport. + * @param comp_id Component ID. + * @param count On input, it specifies the maximum number of + * elements. On output, it will be filled with + * the number of candidates copied to the + * array. + * @param cand Array of candidates. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ice_strans_enum_cands(pj_ice_strans *ice_st, - unsigned comp_id, - unsigned *count, - pj_ice_sess_cand cand[]); + unsigned comp_id, + unsigned *count, + pj_ice_sess_cand cand[]); /** * Get the default candidate for the specified component. When this @@ -881,22 +880,22 @@ PJ_DECL(pj_status_t) pj_ice_strans_enum_cands(pj_ice_strans *ice_st, * this function is called after ICE negotiation completes, the * default candidate is the candidate that forms the valid pair. * - * @param ice_st The ICE stream transport. - * @param comp_id Component ID. - * @param cand Pointer to receive the default candidate - * information. + * @param ice_st The ICE stream transport. + * @param comp_id Component ID. + * @param cand Pointer to receive the default candidate + * information. */ PJ_DECL(pj_status_t) pj_ice_strans_get_def_cand(pj_ice_strans *ice_st, - unsigned comp_id, - pj_ice_sess_cand *cand); + unsigned comp_id, + pj_ice_sess_cand *cand); /** * Get the current ICE role. ICE session must have been initialized * before this function can be called. * - * @param ice_st The ICE stream transport. + * @param ice_st The ICE stream transport. * - * @return Current ICE role. + * @return Current ICE role. */ PJ_DECL(pj_ice_sess_role) pj_ice_strans_get_role(pj_ice_strans *ice_st); @@ -908,13 +907,13 @@ PJ_DECL(pj_ice_sess_role) pj_ice_strans_get_role(pj_ice_strans *ice_st); * inspected. ICE session must have been initialized before this function * can be called. * - * @param ice_st The ICE stream transport. - * @param new_role The new role to be set. + * @param ice_st The ICE stream transport. + * @param new_role The new role to be set. * - * @return PJ_SUCCESS on success, or the appropriate error. + * @return PJ_SUCCESS on success, or the appropriate error. */ PJ_DECL(pj_status_t) pj_ice_strans_change_role(pj_ice_strans *ice_st, - pj_ice_sess_role new_role); + pj_ice_sess_role new_role); /** @@ -929,21 +928,21 @@ PJ_DECL(pj_status_t) pj_ice_strans_change_role(pj_ice_strans *ice_st, * via the callback when ICE connectivity checks completes, either * successfully or with failure. * - * @param ice_st The ICE stream transport. - * @param rem_ufrag Remote ufrag, as seen in the SDP received from - * the remote agent. - * @param rem_passwd Remote password, as seen in the SDP received from - * the remote agent. - * @param rcand_cnt Number of remote candidates in the array. - * @param rcand Remote candidates array. + * @param ice_st The ICE stream transport. + * @param rem_ufrag Remote ufrag, as seen in the SDP received from + * the remote agent. + * @param rem_passwd Remote password, as seen in the SDP received from + * the remote agent. + * @param rcand_cnt Number of remote candidates in the array. + * @param rcand Remote candidates array. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ice_strans_start_ice(pj_ice_strans *ice_st, - const pj_str_t *rem_ufrag, - const pj_str_t *rem_passwd, - unsigned rcand_cnt, - const pj_ice_sess_cand rcand[]); + const pj_str_t *rem_ufrag, + const pj_str_t *rem_passwd, + unsigned rcand_cnt, + const pj_ice_sess_cand rcand[]); /** @@ -955,40 +954,40 @@ PJ_DECL(pj_status_t) pj_ice_strans_start_ice(pj_ice_strans *ice_st, * This function is only applicable when trickle ICE is not disabled and * after ICE session has been created using pj_ice_strans_init_ice(). * - * @param ice_st The ICE stream transport. - * @param rem_ufrag Remote ufrag, as seen in the SDP received from - * the remote agent. - * @param rem_passwd Remote password, as seen in the SDP received from - * the remote agent. - * @param rcand_cnt Number of new remote candidates in the array. - * @param rcand New remote candidates array. - * @param rcand_end Set to PJ_TRUE if remote has signalled - * end-of-candidate. - * - * @return PJ_SUCCESS, or the appropriate error code. + * @param ice_st The ICE stream transport. + * @param rem_ufrag Remote ufrag, as seen in the SDP received from + * the remote agent. + * @param rem_passwd Remote password, as seen in the SDP received from + * the remote agent. + * @param rcand_cnt Number of new remote candidates in the array. + * @param rcand New remote candidates array. + * @param rcand_end Set to PJ_TRUE if remote has signalled + * end-of-candidate. + * + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ice_strans_update_check_list( - pj_ice_strans *ice_st, - const pj_str_t *rem_ufrag, - const pj_str_t *rem_passwd, - unsigned rcand_cnt, - const pj_ice_sess_cand rcand[], - pj_bool_t rcand_end); + pj_ice_strans *ice_st, + const pj_str_t *rem_ufrag, + const pj_str_t *rem_passwd, + unsigned rcand_cnt, + const pj_ice_sess_cand rcand[], + pj_bool_t rcand_end); /** * Retrieve the candidate pair that has been nominated and successfully * checked for the specified component. If ICE negotiation is still in * progress or it has failed, this function will return NULL. * - * @param ice_st The ICE stream transport. - * @param comp_id Component ID. + * @param ice_st The ICE stream transport. + * @param comp_id Component ID. * - * @return The valid pair as ICE checklist structure if the - * pair exist. + * @return The valid pair as ICE checklist structure if the + * pair exist. */ PJ_DECL(const pj_ice_sess_check*) pj_ice_strans_get_valid_pair(const pj_ice_strans *ice_st, - unsigned comp_id); + unsigned comp_id); /** * Stop and destroy the ICE session inside this media transport. Application @@ -1008,9 +1007,9 @@ pj_ice_strans_get_valid_pair(const pj_ice_strans *ice_st, * subsequent calls, it must call #pj_ice_strans_destroy() to destroy the * ICE stream transport altogether. * - * @param ice_st The ICE stream transport. + * @param ice_st The ICE stream transport. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_ice_strans_stop_ice(pj_ice_strans *ice_st); @@ -1041,22 +1040,22 @@ PJ_DECL(pj_status_t) pj_ice_strans_stop_ice(pj_ice_strans *ice_st); * pj_ice_strans_sendto2() to avoid inconsistent calling of * on_data_sent() callback. * - * @param ice_st The ICE stream transport. - * @param comp_id Component ID. - * @param data The data or packet to be sent. - * @param data_len Size of data or packet, in bytes. - * @param dst_addr The destination address. - * @param dst_addr_len Length of destination address. + * @param ice_st The ICE stream transport. + * @param comp_id Component ID. + * @param data The data or packet to be sent. + * @param data_len Size of data or packet, in bytes. + * @param dst_addr The destination address. + * @param dst_addr_len Length of destination address. * - * @return PJ_SUCCESS if data has been sent, or will be sent - * later. No callback will be called. + * @return PJ_SUCCESS if data has been sent, or will be sent + * later. No callback will be called. */ PJ_DECL(pj_status_t) pj_ice_strans_sendto(pj_ice_strans *ice_st, - unsigned comp_id, - const void *data, - pj_size_t data_len, - const pj_sockaddr_t *dst_addr, - int dst_addr_len); + unsigned comp_id, + const void *data, + pj_size_t data_len, + const pj_sockaddr_t *dst_addr, + int dst_addr_len); #endif @@ -1079,25 +1078,25 @@ PJ_DECL(pj_status_t) pj_ice_strans_sendto(pj_ice_strans *ice_st, * pj_ice_strans_sendto2() to avoid inconsistent calling of * on_data_sent() callback. * - * @param ice_st The ICE stream transport. - * @param comp_id Component ID. - * @param data The data or packet to be sent. - * @param data_len Size of data or packet, in bytes. - * @param dst_addr The destination address. - * @param dst_addr_len Length of destination address. - * - * @return PJ_SUCCESS if data has been sent, or - * PJ_EPENDING if data cannot be sent immediately. In - * this case the \a on_data_sent() callback will be - * called when data is actually sent. Any other return - * value indicates error condition. + * @param ice_st The ICE stream transport. + * @param comp_id Component ID. + * @param data The data or packet to be sent. + * @param data_len Size of data or packet, in bytes. + * @param dst_addr The destination address. + * @param dst_addr_len Length of destination address. + * + * @return PJ_SUCCESS if data has been sent, or + * PJ_EPENDING if data cannot be sent immediately. In + * this case the \a on_data_sent() callback will be + * called when data is actually sent. Any other return + * value indicates error condition. */ PJ_DECL(pj_status_t) pj_ice_strans_sendto2(pj_ice_strans *ice_st, - unsigned comp_id, - const void *data, - pj_size_t data_len, - const pj_sockaddr_t *dst_addr, - int dst_addr_len); + unsigned comp_id, + const void *data, + pj_size_t data_len, + const pj_sockaddr_t *dst_addr, + int dst_addr_len); /** @@ -1109,5 +1108,5 @@ PJ_END_DECL -#endif /* __PJNATH_ICE_STRANS_H__ */ +#endif /* __PJNATH_ICE_STRANS_H__ */ diff --git a/pjnath/include/pjnath/nat_detect.h b/pjnath/include/pjnath/nat_detect.h index e49f94e8be..bf589a4865 100644 --- a/pjnath/include/pjnath/nat_detect.h +++ b/pjnath/include/pjnath/nat_detect.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -129,23 +128,23 @@ typedef struct pj_stun_nat_detect_result * the detection has failed and \a nat_type field will contain * PJ_STUN_NAT_TYPE_UNKNOWN. */ - pj_status_t status; + pj_status_t status; /** * The text describing the status, if the status is not PJ_SUCCESS. */ - const char *status_text; + const char *status_text; /** * This contains the NAT type as detected by the detection procedure. * This value is only valid when the \a status is PJ_SUCCESS. */ - pj_stun_nat_type nat_type; + pj_stun_nat_type nat_type; /** * Text describing that NAT type. */ - const char *nat_type_name; + const char *nat_type_name; } pj_stun_nat_detect_result; @@ -155,15 +154,15 @@ typedef struct pj_stun_nat_detect_result * completed. */ typedef void pj_stun_nat_detect_cb(void *user_data, - const pj_stun_nat_detect_result *res); + const pj_stun_nat_detect_result *res); /** * Get the NAT name from the specified NAT type. * - * @param type NAT type. + * @param type NAT type. * - * @return NAT name. + * @return NAT name. */ PJ_DECL(const char*) pj_stun_get_nat_name(pj_stun_nat_type type); @@ -177,49 +176,49 @@ PJ_DECL(const char*) pj_stun_get_nat_name(pj_stun_nat_type type); * * See also #pj_stun_detect_nat_type2() which supports IPv6. * - * @param server STUN server address. - * @param stun_cfg A structure containing various STUN configurations, - * such as the ioqueue and timer heap instance used - * to receive network I/O and timer events. - * @param user_data Application data, which will be returned back - * in the callback. - * @param cb Callback to be registered to receive notification - * about detection result. + * @param server STUN server address. + * @param stun_cfg A structure containing various STUN configurations, + * such as the ioqueue and timer heap instance used + * to receive network I/O and timer events. + * @param user_data Application data, which will be returned back + * in the callback. + * @param cb Callback to be registered to receive notification + * about detection result. * - * @return If this function returns PJ_SUCCESS, the procedure - * will complete asynchronously and callback will be - * called when it completes. For other return - * values, it means that an error has occured and - * the procedure did not start. + * @return If this function returns PJ_SUCCESS, the procedure + * will complete asynchronously and callback will be + * called when it completes. For other return + * values, it means that an error has occured and + * the procedure did not start. */ PJ_DECL(pj_status_t) pj_stun_detect_nat_type(const pj_sockaddr_in *server, - pj_stun_config *stun_cfg, - void *user_data, - pj_stun_nat_detect_cb *cb); + pj_stun_config *stun_cfg, + void *user_data, + pj_stun_nat_detect_cb *cb); /** * Variant of #pj_stun_detect_nat_type() that supports IPv6. * - * @param server STUN server address. - * @param stun_cfg A structure containing various STUN configurations, - * such as the ioqueue and timer heap instance used - * to receive network I/O and timer events. - * @param user_data Application data, which will be returned back - * in the callback. - * @param cb Callback to be registered to receive notification - * about detection result. + * @param server STUN server address. + * @param stun_cfg A structure containing various STUN configurations, + * such as the ioqueue and timer heap instance used + * to receive network I/O and timer events. + * @param user_data Application data, which will be returned back + * in the callback. + * @param cb Callback to be registered to receive notification + * about detection result. * - * @return If this function returns PJ_SUCCESS, the procedure - * will complete asynchronously and callback will be - * called when it completes. For other return - * values, it means that an error has occured and - * the procedure did not start. + * @return If this function returns PJ_SUCCESS, the procedure + * will complete asynchronously and callback will be + * called when it completes. For other return + * values, it means that an error has occured and + * the procedure did not start. */ PJ_DECL(pj_status_t) pj_stun_detect_nat_type2(const pj_sockaddr *server, - pj_stun_config *stun_cfg, - void *user_data, - pj_stun_nat_detect_cb *cb); + pj_stun_config *stun_cfg, + void *user_data, + pj_stun_nat_detect_cb *cb); /** @@ -230,5 +229,5 @@ PJ_DECL(pj_status_t) pj_stun_detect_nat_type2(const pj_sockaddr *server, PJ_END_DECL -#endif /* __PJNATH_NAT_DETECT_H__ */ +#endif /* __PJNATH_NAT_DETECT_H__ */ diff --git a/pjnath/include/pjnath/stun_auth.h b/pjnath/include/pjnath/stun_auth.h index 97a8b3bacd..f4116bd924 100644 --- a/pjnath/include/pjnath/stun_auth.h +++ b/pjnath/include/pjnath/stun_auth.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -116,175 +115,175 @@ typedef struct pj_stun_auth_cred /** * The type of authentication information in this structure. */ - pj_stun_auth_cred_type type; + pj_stun_auth_cred_type type; /** * This union contains the authentication data. */ union { - /** - * This structure contains static data for performing authentication. - * A non-empty realm indicates whether short term or long term - * credential is used. - */ - struct - { - /** - * If not-empty, it indicates that this is a long term credential. - */ - pj_str_t realm; - - /** - * The username of the credential. - */ - pj_str_t username; - - /** - * Data type to indicate the type of password in the \a data field. - */ - pj_stun_passwd_type data_type; - - /** - * The data, which depends depends on the value of \a data_type - * field. When \a data_type is zero, this field will contain the - * plaintext password. - */ - pj_str_t data; - - /** - * Optional NONCE. - */ - pj_str_t nonce; - - } static_cred; - - /** - * This structure contains callback to be called by the framework - * to authenticate the incoming message. - */ - struct - { - /** - * User data which will be passed back to callback functions. - */ - void *user_data; - - /** - * This callback is called by pj_stun_verify_credential() when - * server needs to challenge the request with 401 response. - * - * @param user_data The user data as specified in the credential. - * @param pool Pool to allocate memory. - * @param realm On return, the function should fill in with - * realm if application wants to use long term - * credential. Otherwise application should set - * empty string for the realm. - * @param nonce On return, if application wants to use long - * term credential, it MUST fill in the nonce - * with some value. Otherwise if short term - * credential is wanted, it MAY set this value. - * If short term credential is wanted and the - * application doesn't want to include NONCE, - * then it must set this to empty string. - * - * @return The callback should return PJ_SUCCESS, or - * otherwise response message will not be - * created. - */ - pj_status_t (*get_auth)(void *user_data, - pj_pool_t *pool, - pj_str_t *realm, - pj_str_t *nonce); - - /** - * Get the credential to be put in outgoing request. - * - * @param msg The outgoing message where the credential is - * to be applied. - * @param user_data The user data as specified in the credential. - * @param pool Pool where the callback can allocate memory - * to fill in the credential. - * @param realm On return, the callback may specify the realm - * if long term credential is desired, otherwise - * this string must be set to empty. - * @param username On return, the callback must fill in with the - * username. - * @param nonce On return, the callback may optionally fill in - * this argument with NONCE value if desired, - * otherwise this argument must be set to empty. - * @param data_type On return, the callback must set this argument - * with the type of password in the data argument. - * @param data On return, the callback must set this with - * the password, encoded according to data_type - * argument. - * - * @return The callback must return PJ_SUCCESS, otherwise - * the message transmission will be cancelled. - */ - pj_status_t (*get_cred)(const pj_stun_msg *msg, - void *user_data, - pj_pool_t *pool, - pj_str_t *realm, - pj_str_t *username, - pj_str_t *nonce, - pj_stun_passwd_type *data_type, - pj_str_t *data); - - /** - * Get the password for the specified username. This function - * is also used to check whether the username is valid. - * - * @param msg The STUN message where the password will be - * applied to. - * @param user_data The user data as specified in the credential. - * @param realm The realm as specified in the message. - * @param username The username as specified in the message. - * @param pool Pool to allocate memory when necessary. - * @param data_type On return, application should fill up this - * argument with the type of data (which should - * be zero if data is a plaintext password). - * @param data On return, application should fill up this - * argument with the password according to - * data_type. - * - * @return The callback should return PJ_SUCCESS if - * username has been successfully verified - * and password was obtained. If non-PJ_SUCCESS - * is returned, it is assumed that the - * username is not valid. - */ - pj_status_t (*get_password)(const pj_stun_msg *msg, - void *user_data, - const pj_str_t *realm, - const pj_str_t *username, - pj_pool_t *pool, - pj_stun_passwd_type *data_type, - pj_str_t *data); - - /** - * This callback will be called to verify that the NONCE given - * in the message can be accepted. If this callback returns - * PJ_FALSE, 438 (Stale Nonce) response will be created. - * - * This callback is optional. - * - * @param msg The STUN message where the nonce was received. - * @param user_data The user data as specified in the credential. - * @param realm The realm as specified in the message. - * @param username The username as specified in the message. - * @param nonce The nonce to be verified. - * - * @return The callback MUST return non-zero if the - * NONCE can be accepted. - */ - pj_bool_t (*verify_nonce)(const pj_stun_msg *msg, - void *user_data, - const pj_str_t *realm, - const pj_str_t *username, - const pj_str_t *nonce); - - } dyn_cred; + /** + * This structure contains static data for performing authentication. + * A non-empty realm indicates whether short term or long term + * credential is used. + */ + struct + { + /** + * If not-empty, it indicates that this is a long term credential. + */ + pj_str_t realm; + + /** + * The username of the credential. + */ + pj_str_t username; + + /** + * Data type to indicate the type of password in the \a data field. + */ + pj_stun_passwd_type data_type; + + /** + * The data, which depends depends on the value of \a data_type + * field. When \a data_type is zero, this field will contain the + * plaintext password. + */ + pj_str_t data; + + /** + * Optional NONCE. + */ + pj_str_t nonce; + + } static_cred; + + /** + * This structure contains callback to be called by the framework + * to authenticate the incoming message. + */ + struct + { + /** + * User data which will be passed back to callback functions. + */ + void *user_data; + + /** + * This callback is called by pj_stun_verify_credential() when + * server needs to challenge the request with 401 response. + * + * @param user_data The user data as specified in the credential. + * @param pool Pool to allocate memory. + * @param realm On return, the function should fill in with + * realm if application wants to use long term + * credential. Otherwise application should set + * empty string for the realm. + * @param nonce On return, if application wants to use long + * term credential, it MUST fill in the nonce + * with some value. Otherwise if short term + * credential is wanted, it MAY set this value. + * If short term credential is wanted and the + * application doesn't want to include NONCE, + * then it must set this to empty string. + * + * @return The callback should return PJ_SUCCESS, or + * otherwise response message will not be + * created. + */ + pj_status_t (*get_auth)(void *user_data, + pj_pool_t *pool, + pj_str_t *realm, + pj_str_t *nonce); + + /** + * Get the credential to be put in outgoing request. + * + * @param msg The outgoing message where the credential is + * to be applied. + * @param user_data The user data as specified in the credential. + * @param pool Pool where the callback can allocate memory + * to fill in the credential. + * @param realm On return, the callback may specify the realm + * if long term credential is desired, otherwise + * this string must be set to empty. + * @param username On return, the callback must fill in with the + * username. + * @param nonce On return, the callback may optionally fill in + * this argument with NONCE value if desired, + * otherwise this argument must be set to empty. + * @param data_type On return, the callback must set this argument + * with the type of password in the data argument. + * @param data On return, the callback must set this with + * the password, encoded according to data_type + * argument. + * + * @return The callback must return PJ_SUCCESS, otherwise + * the message transmission will be cancelled. + */ + pj_status_t (*get_cred)(const pj_stun_msg *msg, + void *user_data, + pj_pool_t *pool, + pj_str_t *realm, + pj_str_t *username, + pj_str_t *nonce, + pj_stun_passwd_type *data_type, + pj_str_t *data); + + /** + * Get the password for the specified username. This function + * is also used to check whether the username is valid. + * + * @param msg The STUN message where the password will be + * applied to. + * @param user_data The user data as specified in the credential. + * @param realm The realm as specified in the message. + * @param username The username as specified in the message. + * @param pool Pool to allocate memory when necessary. + * @param data_type On return, application should fill up this + * argument with the type of data (which should + * be zero if data is a plaintext password). + * @param data On return, application should fill up this + * argument with the password according to + * data_type. + * + * @return The callback should return PJ_SUCCESS if + * username has been successfully verified + * and password was obtained. If non-PJ_SUCCESS + * is returned, it is assumed that the + * username is not valid. + */ + pj_status_t (*get_password)(const pj_stun_msg *msg, + void *user_data, + const pj_str_t *realm, + const pj_str_t *username, + pj_pool_t *pool, + pj_stun_passwd_type *data_type, + pj_str_t *data); + + /** + * This callback will be called to verify that the NONCE given + * in the message can be accepted. If this callback returns + * PJ_FALSE, 438 (Stale Nonce) response will be created. + * + * This callback is optional. + * + * @param msg The STUN message where the nonce was received. + * @param user_data The user data as specified in the credential. + * @param realm The realm as specified in the message. + * @param username The username as specified in the message. + * @param nonce The nonce to be verified. + * + * @return The callback MUST return non-zero if the + * NONCE can be accepted. + */ + pj_bool_t (*verify_nonce)(const pj_stun_msg *msg, + void *user_data, + const pj_str_t *realm, + const pj_str_t *username, + const pj_str_t *nonce); + + } dyn_cred; } data; @@ -302,17 +301,17 @@ typedef struct pj_stun_req_cred_info * The REALM value found in the incoming request. If short term * credential is used, the value will be empty. */ - pj_str_t realm; + pj_str_t realm; /** * The USERNAME value found in the incoming request. */ - pj_str_t username; + pj_str_t username; /** * Optional NONCE. */ - pj_str_t nonce; + pj_str_t nonce; /** * Authentication key that was used to authenticate the incoming @@ -320,7 +319,7 @@ typedef struct pj_stun_req_cred_info * it can be used to encode the credential of the outgoing * response. */ - pj_str_t auth_key; + pj_str_t auth_key; } pj_stun_req_cred_info; @@ -328,24 +327,24 @@ typedef struct pj_stun_req_cred_info /** * Duplicate authentication credential. * - * @param pool Pool to be used to allocate memory. - * @param dst Destination credential. - * @param src Source credential. + * @param pool Pool to be used to allocate memory. + * @param dst Destination credential. + * @param src Source credential. */ PJ_DECL(void) pj_stun_auth_cred_dup(pj_pool_t *pool, - pj_stun_auth_cred *dst, - const pj_stun_auth_cred *src); + pj_stun_auth_cred *dst, + const pj_stun_auth_cred *src); /** * Duplicate request credential. * - * @param pool Pool to be used to allocate memory. - * @param dst Destination credential. - * @param src Source credential. + * @param pool Pool to be used to allocate memory. + * @param dst Destination credential. + * @param src Source credential. */ PJ_DECL(void) pj_stun_req_cred_info_dup(pj_pool_t *pool, - pj_stun_req_cred_info *dst, - const pj_stun_req_cred_info *src); + pj_stun_req_cred_info *dst, + const pj_stun_req_cred_info *src); /** @@ -355,21 +354,21 @@ PJ_DECL(void) pj_stun_req_cred_info_dup(pj_pool_t *pool, * If long term credential is used, the key will be calculated from the * MD5 hash of the realm, username, and password. * - * @param pool Pool to allocate memory for the key. - * @param key String to receive the key. - * @param realm The realm of the credential, if long term credential - * is to be used. If short term credential is wanted, - * application can put NULL or empty string here. - * @param username The username. - * @param data_type Password encoding. - * @param data The password. + * @param pool Pool to allocate memory for the key. + * @param key String to receive the key. + * @param realm The realm of the credential, if long term credential + * is to be used. If short term credential is wanted, + * application can put NULL or empty string here. + * @param username The username. + * @param data_type Password encoding. + * @param data The password. */ PJ_DECL(void) pj_stun_create_key(pj_pool_t *pool, - pj_str_t *key, - const pj_str_t *realm, - const pj_str_t *username, - pj_stun_passwd_type data_type, - const pj_str_t *data); + pj_str_t *key, + const pj_str_t *realm, + const pj_str_t *username, + pj_stun_passwd_type data_type, + const pj_str_t *data); /** * Verify credential in the STUN request. Note that before calling this @@ -378,34 +377,34 @@ PJ_DECL(void) pj_stun_create_key(pj_pool_t *pool, * function, because this function will reject the message with 401 error * if it doesn't contain PJ_STUN_ATTR_MESSAGE_INTEGRITY attribute. * - * @param pkt The original packet which has been parsed into - * the message. This packet MUST NOT have been modified - * after the parsing. - * @param pkt_len The length of the packet. - * @param msg The parsed message to be verified. - * @param cred Pointer to credential to be used to authenticate - * the message. - * @param pool If response is to be created, then memory will - * be allocated from this pool. - * @param info Optional pointer to receive authentication information - * found in the request and the credential that is used - * to authenticate the request. - * @param p_response Optional pointer to receive the response message - * then the credential in the request fails to - * authenticate. + * @param pkt The original packet which has been parsed into + * the message. This packet MUST NOT have been modified + * after the parsing. + * @param pkt_len The length of the packet. + * @param msg The parsed message to be verified. + * @param cred Pointer to credential to be used to authenticate + * the message. + * @param pool If response is to be created, then memory will + * be allocated from this pool. + * @param info Optional pointer to receive authentication information + * found in the request and the credential that is used + * to authenticate the request. + * @param p_response Optional pointer to receive the response message + * then the credential in the request fails to + * authenticate. * - * @return PJ_SUCCESS if credential is verified successfully. - * If the verification fails and \a p_response is not - * NULL, an appropriate response will be returned in - * \a p_response. + * @return PJ_SUCCESS if credential is verified successfully. + * If the verification fails and \a p_response is not + * NULL, an appropriate response will be returned in + * \a p_response. */ PJ_DECL(pj_status_t) pj_stun_authenticate_request(const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_msg *msg, - pj_stun_auth_cred *cred, - pj_pool_t *pool, - pj_stun_req_cred_info *info, - pj_stun_msg **p_response); + unsigned pkt_len, + const pj_stun_msg *msg, + pj_stun_auth_cred *cred, + pj_pool_t *pool, + pj_stun_req_cred_info *info, + pj_stun_msg **p_response); /** @@ -414,9 +413,9 @@ PJ_DECL(pj_status_t) pj_stun_authenticate_request(const pj_uint8_t *pkt, * MESSAGE-INTEGRITY attribute. STUN Indication messages also cannot * be authenticated. * - * @param msg The STUN message. + * @param msg The STUN message. * - * @return Non-zero if the STUN message can be authenticated. + * @return Non-zero if the STUN message can be authenticated. */ PJ_DECL(pj_bool_t) pj_stun_auth_valid_for_msg(const pj_stun_msg *msg); @@ -428,21 +427,21 @@ PJ_DECL(pj_bool_t) pj_stun_auth_valid_for_msg(const pj_stun_msg *msg); * function, because otherwise this function will report authentication * failure. * - * @param pkt The original packet which has been parsed into - * the message. This packet MUST NOT have been modified - * after the parsing. - * @param pkt_len The length of the packet. - * @param msg The parsed message to be verified. - * @param key Authentication key to calculate MESSAGE-INTEGRITY - * value. Application can create this key by using - * #pj_stun_create_key() function. + * @param pkt The original packet which has been parsed into + * the message. This packet MUST NOT have been modified + * after the parsing. + * @param pkt_len The length of the packet. + * @param msg The parsed message to be verified. + * @param key Authentication key to calculate MESSAGE-INTEGRITY + * value. Application can create this key by using + * #pj_stun_create_key() function. * - * @return PJ_SUCCESS if credential is verified successfully. + * @return PJ_SUCCESS if credential is verified successfully. */ PJ_DECL(pj_status_t) pj_stun_authenticate_response(const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_msg *msg, - const pj_str_t *key); + unsigned pkt_len, + const pj_stun_msg *msg, + const pj_str_t *key); /** @@ -453,5 +452,5 @@ PJ_DECL(pj_status_t) pj_stun_authenticate_response(const pj_uint8_t *pkt, PJ_END_DECL -#endif /* __PJNATH_STUN_AUTH_H__ */ +#endif /* __PJNATH_STUN_AUTH_H__ */ diff --git a/pjnath/include/pjnath/stun_config.h b/pjnath/include/pjnath/stun_config.h index d23096eeb7..98d97aa22f 100644 --- a/pjnath/include/pjnath/stun_config.h +++ b/pjnath/include/pjnath/stun_config.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -50,28 +49,28 @@ typedef struct pj_stun_config /** * Pool factory to be used. */ - pj_pool_factory *pf; + pj_pool_factory *pf; /** * Ioqueue. */ - pj_ioqueue_t *ioqueue; + pj_ioqueue_t *ioqueue; /** * Timer heap instance. */ - pj_timer_heap_t *timer_heap; + pj_timer_heap_t *timer_heap; /** * Options. */ - unsigned options; + unsigned options; /** * The default initial STUN round-trip time estimation in msecs. * The value normally is PJ_STUN_RTO_VALUE. */ - unsigned rto_msec; + unsigned rto_msec; /** * The interval to cache outgoing STUN response in the STUN session, @@ -79,14 +78,14 @@ typedef struct pj_stun_config * * Default 10000 (10 seconds). */ - unsigned res_cache_msec; + unsigned res_cache_msec; /** * Software name to be included in all STUN requests and responses. * * Default: PJNATH_STUN_SOFTWARE_NAME. */ - pj_str_t software_name; + pj_str_t software_name; } pj_stun_config; @@ -96,10 +95,10 @@ typedef struct pj_stun_config * Initialize STUN config. */ PJ_INLINE(void) pj_stun_config_init(pj_stun_config *cfg, - pj_pool_factory *factory, - unsigned options, - pj_ioqueue_t *ioqueue, - pj_timer_heap_t *timer_heap) + pj_pool_factory *factory, + unsigned options, + pj_ioqueue_t *ioqueue, + pj_timer_heap_t *timer_heap) { pj_bzero(cfg, sizeof(*cfg)); @@ -119,7 +118,7 @@ PJ_INLINE(void) pj_stun_config_init(pj_stun_config *cfg, PJ_INLINE(pj_status_t) pj_stun_config_check_valid(const pj_stun_config *cfg) { PJ_ASSERT_RETURN(cfg->ioqueue && cfg->pf && cfg->timer_heap && - cfg->rto_msec && cfg->res_cache_msec, PJ_EINVAL); + cfg->rto_msec && cfg->res_cache_msec, PJ_EINVAL); return PJ_SUCCESS; } @@ -132,5 +131,5 @@ PJ_INLINE(pj_status_t) pj_stun_config_check_valid(const pj_stun_config *cfg) PJ_END_DECL -#endif /* __PJNATH_STUN_CONFIG_H__ */ +#endif /* __PJNATH_STUN_CONFIG_H__ */ diff --git a/pjnath/include/pjnath/stun_msg.h b/pjnath/include/pjnath/stun_msg.h index 6b5fc0f214..b52f95c586 100644 --- a/pjnath/include/pjnath/stun_msg.h +++ b/pjnath/include/pjnath/stun_msg.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,7 +43,7 @@ PJ_BEGIN_DECL /** * STUN magic cookie. */ -#define PJ_STUN_MAGIC 0x2112A442 +#define PJ_STUN_MAGIC 0x2112A442 /** @@ -55,57 +54,57 @@ enum pj_stun_method_e /** * STUN Binding method as defined by RFC 3489-bis. */ - PJ_STUN_BINDING_METHOD = 1, + PJ_STUN_BINDING_METHOD = 1, /** * STUN Shared Secret method as defined by RFC 3489-bis. */ - PJ_STUN_SHARED_SECRET_METHOD = 2, + PJ_STUN_SHARED_SECRET_METHOD = 2, /** * STUN/TURN Allocate method as defined by draft-ietf-behave-turn */ - PJ_STUN_ALLOCATE_METHOD = 3, + PJ_STUN_ALLOCATE_METHOD = 3, /** * STUN/TURN Refresh method as defined by draft-ietf-behave-turn */ - PJ_STUN_REFRESH_METHOD = 4, + PJ_STUN_REFRESH_METHOD = 4, /** * STUN/TURN Send indication as defined by draft-ietf-behave-turn */ - PJ_STUN_SEND_METHOD = 6, + PJ_STUN_SEND_METHOD = 6, /** * STUN/TURN Data indication as defined by draft-ietf-behave-turn */ - PJ_STUN_DATA_METHOD = 7, + PJ_STUN_DATA_METHOD = 7, /** * STUN/TURN CreatePermission method as defined by draft-ietf-behave-turn */ - PJ_STUN_CREATE_PERM_METHOD = 8, + PJ_STUN_CREATE_PERM_METHOD = 8, /** * STUN/TURN ChannelBind as defined by draft-ietf-behave-turn */ - PJ_STUN_CHANNEL_BIND_METHOD = 9, + PJ_STUN_CHANNEL_BIND_METHOD = 9, /** * STUN/TURN Connect as defined by RFC 6062 */ - PJ_STUN_CONNECT_METHOD = 10, + PJ_STUN_CONNECT_METHOD = 10, /** * STUN/TURN ConnectionBind as defined by RFC 6062 */ - PJ_STUN_CONNECTION_BIND_METHOD = 11, + PJ_STUN_CONNECTION_BIND_METHOD = 11, /** * STUN/TURN ConnectionAttempt as defined by RFC 6062 */ - PJ_STUN_CONNECTION_ATTEMPT_METHOD = 12, + PJ_STUN_CONNECTION_ATTEMPT_METHOD = 12, /** * All known methods. @@ -118,7 +117,7 @@ enum pj_stun_method_e * Retrieve the STUN method from the message-type field of the STUN * message. */ -#define PJ_STUN_GET_METHOD(msg_type) ((msg_type) & 0xFEEF) +#define PJ_STUN_GET_METHOD(msg_type) ((msg_type) & 0xFEEF) /** @@ -129,29 +128,29 @@ enum pj_stun_msg_class_e /** * This specifies that the message type is a STUN request message. */ - PJ_STUN_REQUEST_CLASS = 0, + PJ_STUN_REQUEST_CLASS = 0, /** * This specifies that the message type is a STUN indication message. */ - PJ_STUN_INDICATION_CLASS = 1, + PJ_STUN_INDICATION_CLASS = 1, /** * This specifies that the message type is a STUN successful response. */ - PJ_STUN_SUCCESS_CLASS = 2, + PJ_STUN_SUCCESS_CLASS = 2, /** * This specifies that the message type is a STUN error response. */ - PJ_STUN_ERROR_CLASS = 3 + PJ_STUN_ERROR_CLASS = 3 }; /** * Determine if the message type is a request. */ -#define PJ_STUN_IS_REQUEST(msg_type) (((msg_type) & 0x0110) == 0x0000) +#define PJ_STUN_IS_REQUEST(msg_type) (((msg_type) & 0x0110) == 0x0000) /** @@ -162,7 +161,7 @@ enum pj_stun_msg_class_e /** * The response bit in the message type. */ -#define PJ_STUN_SUCCESS_RESPONSE_BIT (0x0100) +#define PJ_STUN_SUCCESS_RESPONSE_BIT (0x0100) /** @@ -173,7 +172,7 @@ enum pj_stun_msg_class_e /** * The error response bit in the message type. */ -#define PJ_STUN_ERROR_RESPONSE_BIT (0x0110) +#define PJ_STUN_ERROR_RESPONSE_BIT (0x0110) /** * Determine if the message type is a response. @@ -184,12 +183,12 @@ enum pj_stun_msg_class_e /** * Determine if the message type is an indication message. */ -#define PJ_STUN_IS_INDICATION(msg_type) (((msg_type) & 0x0110) == 0x0010) +#define PJ_STUN_IS_INDICATION(msg_type) (((msg_type) & 0x0110) == 0x0010) /** * The error response bit in the message type. */ -#define PJ_STUN_INDICATION_BIT (0x0010) +#define PJ_STUN_INDICATION_BIT (0x0010) /** @@ -200,32 +199,32 @@ typedef enum pj_stun_msg_type /** * STUN BINDING request. */ - PJ_STUN_BINDING_REQUEST = 0x0001, + PJ_STUN_BINDING_REQUEST = 0x0001, /** * Successful response to STUN BINDING-REQUEST. */ - PJ_STUN_BINDING_RESPONSE = 0x0101, + PJ_STUN_BINDING_RESPONSE = 0x0101, /** * Error response to STUN BINDING-REQUEST. */ - PJ_STUN_BINDING_ERROR_RESPONSE = 0x0111, + PJ_STUN_BINDING_ERROR_RESPONSE = 0x0111, /** * Binding Indication (ICE) */ - PJ_STUN_BINDING_INDICATION = 0x0011, + PJ_STUN_BINDING_INDICATION = 0x0011, /** * STUN SHARED-SECRET reqeust. */ - PJ_STUN_SHARED_SECRET_REQUEST = 0x0002, + PJ_STUN_SHARED_SECRET_REQUEST = 0x0002, /** * Successful response to STUN SHARED-SECRET reqeust. */ - PJ_STUN_SHARED_SECRET_RESPONSE = 0x0102, + PJ_STUN_SHARED_SECRET_RESPONSE = 0x0102, /** * Error response to STUN SHARED-SECRET reqeust. @@ -236,77 +235,77 @@ typedef enum pj_stun_msg_type /** * STUN/TURN Allocate Request */ - PJ_STUN_ALLOCATE_REQUEST = 0x0003, + PJ_STUN_ALLOCATE_REQUEST = 0x0003, /** * Successful response to STUN/TURN Allocate Request */ - PJ_STUN_ALLOCATE_RESPONSE = 0x0103, + PJ_STUN_ALLOCATE_RESPONSE = 0x0103, /** * Failure response to STUN/TURN Allocate Request */ - PJ_STUN_ALLOCATE_ERROR_RESPONSE = 0x0113, + PJ_STUN_ALLOCATE_ERROR_RESPONSE = 0x0113, /** * STUN/TURN REFRESH Request */ - PJ_STUN_REFRESH_REQUEST = 0x0004, + PJ_STUN_REFRESH_REQUEST = 0x0004, /** * Successful response to STUN REFRESH request */ - PJ_STUN_REFRESH_RESPONSE = 0x0104, + PJ_STUN_REFRESH_RESPONSE = 0x0104, /** * Error response to STUN REFRESH request. */ - PJ_STUN_REFRESH_ERROR_RESPONSE = 0x0114, + PJ_STUN_REFRESH_ERROR_RESPONSE = 0x0114, /** * TURN Send indication */ - PJ_STUN_SEND_INDICATION = 0x0016, + PJ_STUN_SEND_INDICATION = 0x0016, /** * TURN Data indication */ - PJ_STUN_DATA_INDICATION = 0x0017, + PJ_STUN_DATA_INDICATION = 0x0017, /** * TURN CreatePermission request */ - PJ_STUN_CREATE_PERM_REQUEST = 0x0008, + PJ_STUN_CREATE_PERM_REQUEST = 0x0008, /** * TURN CreatePermission successful response. */ - PJ_STUN_CREATE_PERM_RESPONSE = 0x0108, + PJ_STUN_CREATE_PERM_RESPONSE = 0x0108, /** * TURN CreatePermission failure response */ - PJ_STUN_CREATE_PERM_ERROR_RESPONSE = 0x0118, + PJ_STUN_CREATE_PERM_ERROR_RESPONSE = 0x0118, /** * STUN/TURN ChannelBind Request */ - PJ_STUN_CHANNEL_BIND_REQUEST = 0x0009, + PJ_STUN_CHANNEL_BIND_REQUEST = 0x0009, /** * Successful response to STUN ChannelBind request */ - PJ_STUN_CHANNEL_BIND_RESPONSE = 0x0109, + PJ_STUN_CHANNEL_BIND_RESPONSE = 0x0109, /** * Error response to STUN ChannelBind request. */ - PJ_STUN_CHANNEL_BIND_ERROR_RESPONSE = 0x0119, + PJ_STUN_CHANNEL_BIND_ERROR_RESPONSE = 0x0119, /** * STUN/TURN Connect Request @@ -316,7 +315,7 @@ typedef enum pj_stun_msg_type /** * STUN/TURN ConnectBind Request */ - PJ_STUN_CONNECTION_BIND_REQUEST = 0x000b, + PJ_STUN_CONNECTION_BIND_REQUEST = 0x000b, /** * TURN ConnectionAttempt indication @@ -332,49 +331,49 @@ typedef enum pj_stun_msg_type */ typedef enum pj_stun_attr_type { - PJ_STUN_ATTR_MAPPED_ADDR = 0x0001,/**< MAPPED-ADDRESS. */ - PJ_STUN_ATTR_RESPONSE_ADDR = 0x0002,/**< RESPONSE-ADDRESS (deprcatd)*/ - PJ_STUN_ATTR_CHANGE_REQUEST = 0x0003,/**< CHANGE-REQUEST (deprecated)*/ - PJ_STUN_ATTR_SOURCE_ADDR = 0x0004,/**< SOURCE-ADDRESS (deprecated)*/ - PJ_STUN_ATTR_CHANGED_ADDR = 0x0005,/**< CHANGED-ADDRESS (deprecatd)*/ - PJ_STUN_ATTR_USERNAME = 0x0006,/**< USERNAME attribute. */ - PJ_STUN_ATTR_PASSWORD = 0x0007,/**< was PASSWORD attribute. */ - PJ_STUN_ATTR_MESSAGE_INTEGRITY = 0x0008,/**< MESSAGE-INTEGRITY. */ - PJ_STUN_ATTR_ERROR_CODE = 0x0009,/**< ERROR-CODE. */ - PJ_STUN_ATTR_UNKNOWN_ATTRIBUTES = 0x000A,/**< UNKNOWN-ATTRIBUTES. */ - PJ_STUN_ATTR_REFLECTED_FROM = 0x000B,/**< REFLECTED-FROM (deprecatd)*/ - PJ_STUN_ATTR_CHANNEL_NUMBER = 0x000C,/**< TURN CHANNEL-NUMBER */ - PJ_STUN_ATTR_LIFETIME = 0x000D,/**< TURN LIFETIME attr. */ - PJ_STUN_ATTR_MAGIC_COOKIE = 0x000F,/**< MAGIC-COOKIE attr (deprec)*/ - PJ_STUN_ATTR_BANDWIDTH = 0x0010,/**< TURN BANDWIDTH (deprec) */ - PJ_STUN_ATTR_XOR_PEER_ADDR = 0x0012,/**< TURN XOR-PEER-ADDRESS */ - PJ_STUN_ATTR_DATA = 0x0013,/**< DATA attribute. */ - PJ_STUN_ATTR_REALM = 0x0014,/**< REALM attribute. */ - PJ_STUN_ATTR_NONCE = 0x0015,/**< NONCE attribute. */ + PJ_STUN_ATTR_MAPPED_ADDR = 0x0001,/**< MAPPED-ADDRESS. */ + PJ_STUN_ATTR_RESPONSE_ADDR = 0x0002,/**< RESPONSE-ADDRESS (deprcatd)*/ + PJ_STUN_ATTR_CHANGE_REQUEST = 0x0003,/**< CHANGE-REQUEST (deprecated)*/ + PJ_STUN_ATTR_SOURCE_ADDR = 0x0004,/**< SOURCE-ADDRESS (deprecated)*/ + PJ_STUN_ATTR_CHANGED_ADDR = 0x0005,/**< CHANGED-ADDRESS (deprecatd)*/ + PJ_STUN_ATTR_USERNAME = 0x0006,/**< USERNAME attribute. */ + PJ_STUN_ATTR_PASSWORD = 0x0007,/**< was PASSWORD attribute. */ + PJ_STUN_ATTR_MESSAGE_INTEGRITY = 0x0008,/**< MESSAGE-INTEGRITY. */ + PJ_STUN_ATTR_ERROR_CODE = 0x0009,/**< ERROR-CODE. */ + PJ_STUN_ATTR_UNKNOWN_ATTRIBUTES = 0x000A,/**< UNKNOWN-ATTRIBUTES. */ + PJ_STUN_ATTR_REFLECTED_FROM = 0x000B,/**< REFLECTED-FROM (deprecatd)*/ + PJ_STUN_ATTR_CHANNEL_NUMBER = 0x000C,/**< TURN CHANNEL-NUMBER */ + PJ_STUN_ATTR_LIFETIME = 0x000D,/**< TURN LIFETIME attr. */ + PJ_STUN_ATTR_MAGIC_COOKIE = 0x000F,/**< MAGIC-COOKIE attr (deprec)*/ + PJ_STUN_ATTR_BANDWIDTH = 0x0010,/**< TURN BANDWIDTH (deprec) */ + PJ_STUN_ATTR_XOR_PEER_ADDR = 0x0012,/**< TURN XOR-PEER-ADDRESS */ + PJ_STUN_ATTR_DATA = 0x0013,/**< DATA attribute. */ + PJ_STUN_ATTR_REALM = 0x0014,/**< REALM attribute. */ + PJ_STUN_ATTR_NONCE = 0x0015,/**< NONCE attribute. */ PJ_STUN_ATTR_XOR_RELAYED_ADDR = 0x0016,/**< TURN XOR-RELAYED-ADDRESS */ - PJ_STUN_ATTR_REQ_ADDR_TYPE = 0x0017,/**< REQUESTED-ADDRESS-TYPE */ + PJ_STUN_ATTR_REQ_ADDR_TYPE = 0x0017,/**< REQUESTED-ADDRESS-TYPE */ PJ_STUN_ATTR_REQ_ADDR_FAMILY = 0x0017,/**< REQUESTED-ADDRESS-FAMILY */ - PJ_STUN_ATTR_EVEN_PORT = 0x0018,/**< TURN EVEN-PORT */ - PJ_STUN_ATTR_REQ_TRANSPORT = 0x0019,/**< TURN REQUESTED-TRANSPORT */ - PJ_STUN_ATTR_DONT_FRAGMENT = 0x001A,/**< TURN DONT-FRAGMENT */ - PJ_STUN_ATTR_XOR_MAPPED_ADDR = 0x0020,/**< XOR-MAPPED-ADDRESS */ - PJ_STUN_ATTR_TIMER_VAL = 0x0021,/**< TIMER-VAL attribute. */ + PJ_STUN_ATTR_EVEN_PORT = 0x0018,/**< TURN EVEN-PORT */ + PJ_STUN_ATTR_REQ_TRANSPORT = 0x0019,/**< TURN REQUESTED-TRANSPORT */ + PJ_STUN_ATTR_DONT_FRAGMENT = 0x001A,/**< TURN DONT-FRAGMENT */ + PJ_STUN_ATTR_XOR_MAPPED_ADDR = 0x0020,/**< XOR-MAPPED-ADDRESS */ + PJ_STUN_ATTR_TIMER_VAL = 0x0021,/**< TIMER-VAL attribute. */ PJ_STUN_ATTR_RESERVATION_TOKEN = 0x0022,/**< TURN RESERVATION-TOKEN */ - PJ_STUN_ATTR_XOR_REFLECTED_FROM = 0x0023,/**< XOR-REFLECTED-FROM */ - PJ_STUN_ATTR_PRIORITY = 0x0024,/**< PRIORITY */ - PJ_STUN_ATTR_USE_CANDIDATE = 0x0025,/**< USE-CANDIDATE */ - PJ_STUN_ATTR_CONNECTION_ID = 0x002a,/**< CONNECTION-ID */ - PJ_STUN_ATTR_ICMP = 0x0030,/**< ICMP (TURN) */ + PJ_STUN_ATTR_XOR_REFLECTED_FROM = 0x0023,/**< XOR-REFLECTED-FROM */ + PJ_STUN_ATTR_PRIORITY = 0x0024,/**< PRIORITY */ + PJ_STUN_ATTR_USE_CANDIDATE = 0x0025,/**< USE-CANDIDATE */ + PJ_STUN_ATTR_CONNECTION_ID = 0x002a,/**< CONNECTION-ID */ + PJ_STUN_ATTR_ICMP = 0x0030,/**< ICMP (TURN) */ PJ_STUN_ATTR_END_MANDATORY_ATTR, PJ_STUN_ATTR_START_EXTENDED_ATTR= 0x8021, - PJ_STUN_ATTR_SOFTWARE = 0x8022,/**< SOFTWARE attribute. */ - PJ_STUN_ATTR_ALTERNATE_SERVER = 0x8023,/**< ALTERNATE-SERVER. */ - PJ_STUN_ATTR_REFRESH_INTERVAL = 0x8024,/**< REFRESH-INTERVAL. */ - PJ_STUN_ATTR_FINGERPRINT = 0x8028,/**< FINGERPRINT attribute. */ - PJ_STUN_ATTR_ICE_CONTROLLED = 0x8029,/**< ICE-CCONTROLLED attribute.*/ + PJ_STUN_ATTR_SOFTWARE = 0x8022,/**< SOFTWARE attribute. */ + PJ_STUN_ATTR_ALTERNATE_SERVER = 0x8023,/**< ALTERNATE-SERVER. */ + PJ_STUN_ATTR_REFRESH_INTERVAL = 0x8024,/**< REFRESH-INTERVAL. */ + PJ_STUN_ATTR_FINGERPRINT = 0x8028,/**< FINGERPRINT attribute. */ + PJ_STUN_ATTR_ICE_CONTROLLED = 0x8029,/**< ICE-CCONTROLLED attribute.*/ PJ_STUN_ATTR_ICE_CONTROLLING = 0x802a,/**< ICE-CCONTROLLING attribute*/ PJ_STUN_ATTR_END_EXTENDED_ATTR @@ -387,37 +386,37 @@ typedef enum pj_stun_attr_type */ typedef enum pj_stun_status { - PJ_STUN_SC_TRY_ALTERNATE = 300, /**< Try Alternate */ - PJ_STUN_SC_BAD_REQUEST = 400, /**< Bad Request */ - PJ_STUN_SC_UNAUTHORIZED = 401, /**< Unauthorized */ - PJ_STUN_SC_FORBIDDEN = 403, /**< Forbidden (TURN) */ - PJ_STUN_SC_UNKNOWN_ATTRIBUTE = 420, /**< Unknown Attribute */ + PJ_STUN_SC_TRY_ALTERNATE = 300, /**< Try Alternate */ + PJ_STUN_SC_BAD_REQUEST = 400, /**< Bad Request */ + PJ_STUN_SC_UNAUTHORIZED = 401, /**< Unauthorized */ + PJ_STUN_SC_FORBIDDEN = 403, /**< Forbidden (TURN) */ + PJ_STUN_SC_UNKNOWN_ATTRIBUTE = 420, /**< Unknown Attribute */ #if 0 /* These were obsolete in recent rfc3489bis */ - //PJ_STUN_SC_STALE_CREDENTIALS = 430, /**< Stale Credentials */ - //PJ_STUN_SC_INTEGRITY_CHECK_FAILURE= 431, /**< Integrity Chk Fail */ - //PJ_STUN_SC_MISSING_USERNAME = 432, /**< Missing Username */ - //PJ_STUN_SC_USE_TLS = 433, /**< Use TLS */ - //PJ_STUN_SC_MISSING_REALM = 434, /**< Missing Realm */ - //PJ_STUN_SC_MISSING_NONCE = 435, /**< Missing Nonce */ - //PJ_STUN_SC_UNKNOWN_USERNAME = 436, /**< Unknown Username */ + //PJ_STUN_SC_STALE_CREDENTIALS = 430, /**< Stale Credentials */ + //PJ_STUN_SC_INTEGRITY_CHECK_FAILURE= 431, /**< Integrity Chk Fail */ + //PJ_STUN_SC_MISSING_USERNAME = 432, /**< Missing Username */ + //PJ_STUN_SC_USE_TLS = 433, /**< Use TLS */ + //PJ_STUN_SC_MISSING_REALM = 434, /**< Missing Realm */ + //PJ_STUN_SC_MISSING_NONCE = 435, /**< Missing Nonce */ + //PJ_STUN_SC_UNKNOWN_USERNAME = 436, /**< Unknown Username */ #endif PJ_STUN_SC_ALLOCATION_MISMATCH = 437, /**< TURN Alloc Mismatch */ - PJ_STUN_SC_STALE_NONCE = 438, /**< Stale Nonce */ - PJ_STUN_SC_TRANSITIONING = 439, /**< Transitioning. */ - PJ_STUN_SC_WRONG_CREDENTIALS = 441, /**< TURN Wrong Credentials */ + PJ_STUN_SC_STALE_NONCE = 438, /**< Stale Nonce */ + PJ_STUN_SC_TRANSITIONING = 439, /**< Transitioning. */ + PJ_STUN_SC_WRONG_CREDENTIALS = 441, /**< TURN Wrong Credentials */ PJ_STUN_SC_UNSUPP_TRANSPORT_PROTO = 442, /**< Unsupported Transport or - Protocol (TURN) */ - PJ_STUN_SC_OPER_TCP_ONLY = 445, /**< Operation for TCP Only */ - PJ_STUN_SC_CONNECTION_FAILURE = 446, /**< Connection Failure */ - PJ_STUN_SC_CONNECTION_TIMEOUT = 447, /**< Connection Timeout */ + Protocol (TURN) */ + PJ_STUN_SC_OPER_TCP_ONLY = 445, /**< Operation for TCP Only */ + PJ_STUN_SC_CONNECTION_FAILURE = 446, /**< Connection Failure */ + PJ_STUN_SC_CONNECTION_TIMEOUT = 447, /**< Connection Timeout */ PJ_STUN_SC_ALLOCATION_QUOTA_REACHED = 486, /**< Allocation Quota Reached - (TURN) */ - PJ_STUN_SC_ROLE_CONFLICT = 487, /**< Role Conflict */ - PJ_STUN_SC_SERVER_ERROR = 500, /**< Server Error */ - PJ_STUN_SC_INSUFFICIENT_CAPACITY = 508, /**< Insufficient Capacity - (TURN) */ - PJ_STUN_SC_GLOBAL_FAILURE = 600 /**< Global Failure */ + (TURN) */ + PJ_STUN_SC_ROLE_CONFLICT = 487, /**< Role Conflict */ + PJ_STUN_SC_SERVER_ERROR = 500, /**< Server Error */ + PJ_STUN_SC_INSUFFICIENT_CAPACITY = 508, /**< Insufficient Capacity + (TURN) */ + PJ_STUN_SC_GLOBAL_FAILURE = 600 /**< Global Failure */ } pj_stun_status; @@ -448,20 +447,20 @@ typedef struct pj_stun_msg_hdr /** * STUN message type, which the first two bits must be zeroes. */ - pj_uint16_t type; + pj_uint16_t type; /** * The message length is the size, in bytes, of the message not * including the 20 byte STUN header. */ - pj_uint16_t length; + pj_uint16_t length; /** * The magic cookie is a fixed value, 0x2112A442 (PJ_STUN_MAGIC constant). * In the previous version of this specification [15] this field was part * of the transaction ID. */ - pj_uint32_t magic; + pj_uint32_t magic; /** * The transaction ID is a 96 bit identifier. STUN transactions are @@ -471,7 +470,7 @@ typedef struct pj_stun_msg_hdr * that STUN client. The transaction ID MUST be uniformly and randomly * distributed between 0 and 2**96 - 1. */ - pj_uint8_t tsx_id[12]; + pj_uint8_t tsx_id[12]; } pj_stun_msg_hdr; @@ -496,7 +495,7 @@ typedef struct pj_stun_attr_hdr /** * STUN attribute type. */ - pj_uint16_t type; + pj_uint16_t type; /** * The Length refers to the length of the actual useful content of the @@ -504,7 +503,7 @@ typedef struct pj_stun_attr_hdr * in the Length field refers to the length of the Value part of the * attribute prior to padding - i.e., the useful content. */ - pj_uint16_t length; + pj_uint16_t length; } pj_stun_attr_hdr; @@ -539,18 +538,18 @@ typedef struct pj_stun_sockaddr_attr /** * Standard STUN attribute header. */ - pj_stun_attr_hdr hdr; + pj_stun_attr_hdr hdr; /** * Flag to indicate whether this attribute should be sent in XOR-ed * format, or has been received in XOR-ed format. */ - pj_bool_t xor_ed; + pj_bool_t xor_ed; /** * The socket address */ - pj_sockaddr sockaddr; + pj_sockaddr sockaddr; } pj_stun_sockaddr_attr; @@ -564,7 +563,7 @@ typedef struct pj_stun_empty_attr /** * Standard STUN attribute header. */ - pj_stun_attr_hdr hdr; + pj_stun_attr_hdr hdr; } pj_stun_empty_attr; @@ -578,12 +577,12 @@ typedef struct pj_stun_string_attr /** * Standard STUN attribute header. */ - pj_stun_attr_hdr hdr; + pj_stun_attr_hdr hdr; /** * The string value. */ - pj_str_t value; + pj_str_t value; } pj_stun_string_attr; @@ -597,12 +596,12 @@ typedef struct pj_stun_uint_attr /** * Standard STUN attribute header. */ - pj_stun_attr_hdr hdr; + pj_stun_attr_hdr hdr; /** * The 32bit value, in host byte order. */ - pj_uint32_t value; + pj_uint32_t value; } pj_stun_uint_attr; @@ -616,12 +615,12 @@ typedef struct pj_stun_uint64_attr /** * Standard STUN attribute header. */ - pj_stun_attr_hdr hdr; + pj_stun_attr_hdr hdr; /** * The 64bit value, in host byte order, represented with pj_timestamp. */ - pj_timestamp value; + pj_timestamp value; } pj_stun_uint64_attr; @@ -635,23 +634,23 @@ typedef struct pj_stun_binary_attr /** * Standard STUN attribute header. */ - pj_stun_attr_hdr hdr; + pj_stun_attr_hdr hdr; /** * Special signature to indicate that this is a valid attribute even * though we don't have meta-data to describe this attribute. */ - pj_uint32_t magic; + pj_uint32_t magic; /** * Length of the data. */ - unsigned length; + unsigned length; /** * The raw data. */ - pj_uint8_t *data; + pj_uint8_t *data; } pj_stun_binary_attr; @@ -668,12 +667,12 @@ typedef struct pj_stun_msgint_attr /** * Standard STUN attribute header. */ - pj_stun_attr_hdr hdr; + pj_stun_attr_hdr hdr; /** * The 20 bytes hmac value. */ - pj_uint8_t hmac[20]; + pj_uint8_t hmac[20]; } pj_stun_msgint_attr; @@ -710,17 +709,17 @@ typedef struct pj_stun_errcode_attr /** * Standard STUN attribute header. */ - pj_stun_attr_hdr hdr; + pj_stun_attr_hdr hdr; /** * STUN error code. */ - int err_code; + int err_code; /** * The reason phrase. */ - pj_str_t reason; + pj_str_t reason; } pj_stun_errcode_attr; @@ -760,17 +759,17 @@ typedef struct pj_stun_unknown_attr /** * Standard STUN attribute header. */ - pj_stun_attr_hdr hdr; + pj_stun_attr_hdr hdr; /** * Number of unknown attributes in the array. */ - unsigned attr_count; + unsigned attr_count; /** * Array of unknown attribute IDs. */ - pj_uint16_t attrs[PJ_STUN_MAX_ATTR]; + pj_uint16_t attrs[PJ_STUN_MAX_ATTR]; } pj_stun_unknown_attr; @@ -936,7 +935,7 @@ typedef struct pj_stun_uint_attr pj_stun_channel_number_attr; * after they have been parsed from the PDU, so no need to do ntohs() * here. */ -#define PJ_STUN_GET_CH_NB(u32) ((pj_uint16_t)(u32>>16)) +#define PJ_STUN_GET_CH_NB(u32) ((pj_uint16_t)(u32>>16)) /** * Convert 16bit channel number into 32bit integral value. @@ -1179,7 +1178,7 @@ typedef struct pj_stun_msg /** * Number of attributes in the STUN message. */ - unsigned attr_count; + unsigned attr_count; /** * Array of STUN attributes. @@ -1196,7 +1195,7 @@ enum pj_stun_decode_options * Tell the decoder that the message was received from datagram * oriented transport (such as UDP). */ - PJ_STUN_IS_DATAGRAM = 1, + PJ_STUN_IS_DATAGRAM = 1, /** * Tell pj_stun_msg_decode() to check the validity of the STUN @@ -1225,9 +1224,9 @@ enum pj_stun_decode_options /** * Get STUN message method name. * - * @param msg_type The STUN message type (in host byte order) + * @param msg_type The STUN message type (in host byte order) * - * @return The STUN message method name string. + * @return The STUN message method name string. */ PJ_DECL(const char*) pj_stun_get_method_name(unsigned msg_type); @@ -1235,9 +1234,9 @@ PJ_DECL(const char*) pj_stun_get_method_name(unsigned msg_type); /** * Get STUN message class name. * - * @param msg_type The STUN message type (in host byte order) + * @param msg_type The STUN message type (in host byte order) * - * @return The STUN message class name string. + * @return The STUN message class name string. */ PJ_DECL(const char*) pj_stun_get_class_name(unsigned msg_type); @@ -1245,9 +1244,9 @@ PJ_DECL(const char*) pj_stun_get_class_name(unsigned msg_type); /** * Get STUN attribute name. * - * @return attr_type The STUN attribute type (in host byte order). + * @return attr_type The STUN attribute type (in host byte order). * - * @return The STUN attribute type name string. + * @return The STUN attribute type name string. */ PJ_DECL(const char*) pj_stun_get_attr_name(unsigned attr_type); @@ -1255,9 +1254,9 @@ PJ_DECL(const char*) pj_stun_get_attr_name(unsigned attr_type); /** * Get STUN standard reason phrase for the specified error code. * - * @param err_code The STUN error code. + * @param err_code The STUN error code. * - * @return The STUN error reason phrase. + * @return The STUN error reason phrase. */ PJ_DECL(pj_str_t) pj_stun_get_err_reason(int err_code); @@ -1266,7 +1265,7 @@ PJ_DECL(pj_str_t) pj_stun_get_err_reason(int err_code); * Internal: set the padding character for string attribute. * The default padding character is PJ_STUN_STRING_ATTR_PAD_CHR. * - * @return The previous padding character. + * @return The previous padding character. */ PJ_DECL(int) pj_stun_set_padding_char(int chr); @@ -1274,85 +1273,85 @@ PJ_DECL(int) pj_stun_set_padding_char(int chr); /** * Initialize a generic STUN message. * - * @param msg The message structure to be initialized. - * @param msg_type The 14bit message type (see pj_stun_msg_type - * constants). - * @param magic Magic value to be put to the mesage; for requests, - * the value normally should be PJ_STUN_MAGIC. - * @param tsx_id Optional transaction ID, or NULL to let the - * function generates a random transaction ID. + * @param msg The message structure to be initialized. + * @param msg_type The 14bit message type (see pj_stun_msg_type + * constants). + * @param magic Magic value to be put to the mesage; for requests, + * the value normally should be PJ_STUN_MAGIC. + * @param tsx_id Optional transaction ID, or NULL to let the + * function generates a random transaction ID. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pj_stun_msg_init(pj_stun_msg *msg, - unsigned msg_type, - pj_uint32_t magic, - const pj_uint8_t tsx_id[12]); + unsigned msg_type, + pj_uint32_t magic, + const pj_uint8_t tsx_id[12]); /** * Create a generic STUN message. * - * @param pool Pool to create the STUN message. - * @param msg_type The 14bit message type. - * @param magic Magic value to be put to the mesage; for requests, - * the value should be PJ_STUN_MAGIC. - * @param tsx_id Optional transaction ID, or NULL to let the - * function generates a random transaction ID. - * @param p_msg Pointer to receive the message. + * @param pool Pool to create the STUN message. + * @param msg_type The 14bit message type. + * @param magic Magic value to be put to the mesage; for requests, + * the value should be PJ_STUN_MAGIC. + * @param tsx_id Optional transaction ID, or NULL to let the + * function generates a random transaction ID. + * @param p_msg Pointer to receive the message. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pj_stun_msg_create(pj_pool_t *pool, - unsigned msg_type, - pj_uint32_t magic, - const pj_uint8_t tsx_id[12], - pj_stun_msg **p_msg); + unsigned msg_type, + pj_uint32_t magic, + const pj_uint8_t tsx_id[12], + pj_stun_msg **p_msg); /** * Clone a STUN message with all of its attributes. * - * @param pool Pool to allocate memory for the new message. - * @param msg The message to be cloned. + * @param pool Pool to allocate memory for the new message. + * @param msg The message to be cloned. * - * @return The duplicate message. + * @return The duplicate message. */ PJ_DECL(pj_stun_msg*) pj_stun_msg_clone(pj_pool_t *pool, - const pj_stun_msg *msg); + const pj_stun_msg *msg); /** * Create STUN response message. * - * @param pool Pool to create the mesage. - * @param req_msg The request message. - * @param err_code STUN error code. If this value is not zero, - * then error response will be created, otherwise - * successful response will be created. - * @param err_msg Optional error message to explain err_code. - * If this value is NULL and err_code is not zero, - * the error string will be taken from the default - * STUN error message. - * @param p_response Pointer to receive the response. + * @param pool Pool to create the mesage. + * @param req_msg The request message. + * @param err_code STUN error code. If this value is not zero, + * then error response will be created, otherwise + * successful response will be created. + * @param err_msg Optional error message to explain err_code. + * If this value is NULL and err_code is not zero, + * the error string will be taken from the default + * STUN error message. + * @param p_response Pointer to receive the response. * - * @return PJ_SUCCESS on success, or the appropriate error. + * @return PJ_SUCCESS on success, or the appropriate error. */ PJ_DECL(pj_status_t) pj_stun_msg_create_response(pj_pool_t *pool, - const pj_stun_msg *req_msg, - unsigned err_code, - const pj_str_t *err_msg, - pj_stun_msg **p_response); + const pj_stun_msg *req_msg, + unsigned err_code, + const pj_str_t *err_msg, + pj_stun_msg **p_response); /** * Add STUN attribute to STUN message. * - * @param msg The STUN message. - * @param attr The STUN attribute to be added to the message. + * @param msg The STUN message. + * @param attr The STUN attribute to be added to the message. * - * @return PJ_SUCCESS on success, or PJ_ETOOMANY if there are - * already too many attributes in the message. + * @return PJ_SUCCESS on success, or PJ_ETOOMANY if there are + * already too many attributes in the message. */ PJ_DECL(pj_status_t) pj_stun_msg_add_attr(pj_stun_msg *msg, - pj_stun_attr_hdr *attr); + pj_stun_attr_hdr *attr); /** @@ -1374,26 +1373,26 @@ PJ_DECL(pj_status_t) pj_stun_msg_add_attr(pj_stun_msg *msg, * the FINGERPRINT CRC attribute for the message. The FINGERPRINT MUST * be added as the last attribute of the message. * - * @param msg The STUN message to be printed. Upon return, - * some fields in the header (such as message - * length) will be updated. - * @param pkt_buf The buffer to be filled with the packet. - * @param buf_size Size of the buffer. - * @param options Options, which currently must be zero. - * @param key Authentication key to calculate MESSAGE-INTEGRITY - * value. Application can create this key by using - * #pj_stun_create_key() function. - * @param p_msg_len Upon return, it will be filed with the size of - * the packet in bytes, or negative value on error. + * @param msg The STUN message to be printed. Upon return, + * some fields in the header (such as message + * length) will be updated. + * @param pkt_buf The buffer to be filled with the packet. + * @param buf_size Size of the buffer. + * @param options Options, which currently must be zero. + * @param key Authentication key to calculate MESSAGE-INTEGRITY + * value. Application can create this key by using + * #pj_stun_create_key() function. + * @param p_msg_len Upon return, it will be filed with the size of + * the packet in bytes, or negative value on error. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_msg_encode(pj_stun_msg *msg, - pj_uint8_t *pkt_buf, - pj_size_t buf_size, - unsigned options, - const pj_str_t *key, - pj_size_t *p_msg_len); + pj_uint8_t *pkt_buf, + pj_size_t buf_size, + unsigned options, + const pj_str_t *key, + pj_size_t *p_msg_len); /** * Check that the PDU is potentially a valid STUN message. This function @@ -1404,66 +1403,66 @@ PJ_DECL(pj_status_t) pj_stun_msg_encode(pj_stun_msg *msg, * Note that we cannot be sure that the PDU is a really valid STUN message * until we actually parse the PDU. * - * @param pdu The packet buffer. - * @param pdu_len The length of the packet buffer. - * @param options Additional options to be applied in the checking, - * which can be taken from pj_stun_decode_options. One - * of the useful option is PJ_STUN_IS_DATAGRAM which - * means that the pdu represents a whole STUN packet. + * @param pdu The packet buffer. + * @param pdu_len The length of the packet buffer. + * @param options Additional options to be applied in the checking, + * which can be taken from pj_stun_decode_options. One + * of the useful option is PJ_STUN_IS_DATAGRAM which + * means that the pdu represents a whole STUN packet. * - * @return PJ_SUCCESS if the PDU is a potentially valid STUN - * message. + * @return PJ_SUCCESS if the PDU is a potentially valid STUN + * message. */ PJ_DECL(pj_status_t) pj_stun_msg_check(const pj_uint8_t *pdu, - pj_size_t pdu_len, unsigned options); + pj_size_t pdu_len, unsigned options); /** * Decode incoming packet into STUN message. * - * @param pool Pool to allocate the message. - * @param pdu The incoming packet to be parsed. - * @param pdu_len The length of the incoming packet. - * @param options Parsing flags, according to pj_stun_decode_options. - * @param p_msg Pointer to receive the parsed message. - * @param p_parsed_len Optional pointer to receive how many bytes have - * been parsed for the STUN message. This is useful - * when the packet is received over stream oriented - * transport. - * @param p_response Optional pointer to receive an instance of response - * message, if one can be created. If the packet being - * decoded is a request message, and it contains error, - * and a response can be created, then the STUN - * response message will be returned on this argument. - * - * @return PJ_SUCCESS if a STUN message has been successfully - * decoded. + * @param pool Pool to allocate the message. + * @param pdu The incoming packet to be parsed. + * @param pdu_len The length of the incoming packet. + * @param options Parsing flags, according to pj_stun_decode_options. + * @param p_msg Pointer to receive the parsed message. + * @param p_parsed_len Optional pointer to receive how many bytes have + * been parsed for the STUN message. This is useful + * when the packet is received over stream oriented + * transport. + * @param p_response Optional pointer to receive an instance of response + * message, if one can be created. If the packet being + * decoded is a request message, and it contains error, + * and a response can be created, then the STUN + * response message will be returned on this argument. + * + * @return PJ_SUCCESS if a STUN message has been successfully + * decoded. */ PJ_DECL(pj_status_t) pj_stun_msg_decode(pj_pool_t *pool, - const pj_uint8_t *pdu, - pj_size_t pdu_len, - unsigned options, - pj_stun_msg **p_msg, - pj_size_t *p_parsed_len, - pj_stun_msg **p_response); + const pj_uint8_t *pdu, + pj_size_t pdu_len, + unsigned options, + pj_stun_msg **p_msg, + pj_size_t *p_parsed_len, + pj_stun_msg **p_response); /** * Dump STUN message to a printable string output. * - * @param msg The STUN message - * @param buffer Buffer where the printable string output will - * be printed on. - * @param length Specify the maximum length of the buffer. - * @param printed_len Optional pointer, which on output will be filled - * up with the actual length of the output string. + * @param msg The STUN message + * @param buffer Buffer where the printable string output will + * be printed on. + * @param length Specify the maximum length of the buffer. + * @param printed_len Optional pointer, which on output will be filled + * up with the actual length of the output string. * - * @return The message string output. + * @return The message string output. */ #if PJ_LOG_MAX_LEVEL > 0 PJ_DECL(char*) pj_stun_msg_dump(const pj_stun_msg *msg, - char *buffer, - unsigned length, - unsigned *printed_len); + char *buffer, + unsigned length, + unsigned *printed_len); #else # define pj_stun_msg_dump(msg, buf, length, printed_len) "" #endif @@ -1473,30 +1472,30 @@ PJ_DECL(char*) pj_stun_msg_dump(const pj_stun_msg *msg, * Find STUN attribute in the STUN message, starting from the specified * index. * - * @param msg The STUN message. - * @param attr_type The attribute type to be found, from pj_stun_attr_type. - * @param start_index The start index of the attribute in the message. - * Specify zero to start searching from the first - * attribute. + * @param msg The STUN message. + * @param attr_type The attribute type to be found, from pj_stun_attr_type. + * @param start_index The start index of the attribute in the message. + * Specify zero to start searching from the first + * attribute. * - * @return The attribute instance, or NULL if it cannot be - * found. + * @return The attribute instance, or NULL if it cannot be + * found. */ PJ_DECL(pj_stun_attr_hdr*) pj_stun_msg_find_attr(const pj_stun_msg *msg, - int attr_type, - unsigned start_index); + int attr_type, + unsigned start_index); /** * Clone a STUN attribute. * - * @param pool Pool to allocate memory. - * @param attr Attribute to clone. + * @param pool Pool to allocate memory. + * @param attr Attribute to clone. * - * @return Duplicate attribute. + * @return Duplicate attribute. */ PJ_DECL(pj_stun_attr_hdr*) pj_stun_attr_clone(pj_pool_t *pool, - const pj_stun_attr_hdr *attr); + const pj_stun_attr_hdr *attr); /** @@ -1504,42 +1503,42 @@ PJ_DECL(pj_stun_attr_hdr*) pj_stun_attr_clone(pj_pool_t *pool, * \a addr parameters specify whether the address is IPv4 or IPv4 * address. * - * @param attr The socket address attribute to initialize. - * @param attr_type Attribute type, from #pj_stun_attr_type. - * @param xor_ed If non-zero, the port and address will be XOR-ed - * with magic, to make the XOR-MAPPED-ADDRESS attribute. - * @param addr A pj_sockaddr_in or pj_sockaddr_in6 structure. - * @param addr_len Length of \a addr parameter. + * @param attr The socket address attribute to initialize. + * @param attr_type Attribute type, from #pj_stun_attr_type. + * @param xor_ed If non-zero, the port and address will be XOR-ed + * with magic, to make the XOR-MAPPED-ADDRESS attribute. + * @param addr A pj_sockaddr_in or pj_sockaddr_in6 structure. + * @param addr_len Length of \a addr parameter. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_sockaddr_attr_init(pj_stun_sockaddr_attr *attr, - int attr_type, - pj_bool_t xor_ed, - const pj_sockaddr_t *addr, - unsigned addr_len); + int attr_type, + pj_bool_t xor_ed, + const pj_sockaddr_t *addr, + unsigned addr_len); /** * Create a generic STUN IP address attribute. The \a addr_len and * \a addr parameters specify whether the address is IPv4 or IPv4 * address. * - * @param pool The pool to allocate memory from. - * @param attr_type Attribute type, from #pj_stun_attr_type. - * @param xor_ed If non-zero, the port and address will be XOR-ed - * with magic, to make the XOR-MAPPED-ADDRESS attribute. - * @param addr A pj_sockaddr_in or pj_sockaddr_in6 structure. - * @param addr_len Length of \a addr parameter. - * @param p_attr Pointer to receive the attribute. + * @param pool The pool to allocate memory from. + * @param attr_type Attribute type, from #pj_stun_attr_type. + * @param xor_ed If non-zero, the port and address will be XOR-ed + * with magic, to make the XOR-MAPPED-ADDRESS attribute. + * @param addr A pj_sockaddr_in or pj_sockaddr_in6 structure. + * @param addr_len Length of \a addr parameter. + * @param p_attr Pointer to receive the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_sockaddr_attr_create(pj_pool_t *pool, - int attr_type, - pj_bool_t xor_ed, - const pj_sockaddr_t *addr, - unsigned addr_len, - pj_stun_sockaddr_attr **p_attr); + int attr_type, + pj_bool_t xor_ed, + const pj_sockaddr_t *addr, + unsigned addr_len, + pj_stun_sockaddr_attr **p_attr); /** @@ -1547,299 +1546,299 @@ PJ_DECL(pj_status_t) pj_stun_sockaddr_attr_create(pj_pool_t *pool, * The \a addr_len and \a addr parameters specify whether the address is * IPv4 or IPv4 address. * - * @param pool The pool to allocate memory from. - * @param msg The STUN message. - * @param attr_type Attribute type, from #pj_stun_attr_type. - * @param xor_ed If non-zero, the port and address will be XOR-ed - * with magic, to make the XOR-MAPPED-ADDRESS attribute. - * @param addr A pj_sockaddr_in or pj_sockaddr_in6 structure. - * @param addr_len Length of \a addr parameter. + * @param pool The pool to allocate memory from. + * @param msg The STUN message. + * @param attr_type Attribute type, from #pj_stun_attr_type. + * @param xor_ed If non-zero, the port and address will be XOR-ed + * with magic, to make the XOR-MAPPED-ADDRESS attribute. + * @param addr A pj_sockaddr_in or pj_sockaddr_in6 structure. + * @param addr_len Length of \a addr parameter. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_msg_add_sockaddr_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int attr_type, - pj_bool_t xor_ed, - const pj_sockaddr_t *addr, - unsigned addr_len); + pj_stun_msg *msg, + int attr_type, + pj_bool_t xor_ed, + const pj_sockaddr_t *addr, + unsigned addr_len); /** * Initialize a STUN generic string attribute. * - * @param attr The string attribute to be initialized. - * @param pool Pool to duplicate the value into the attribute, - * if value is not NULL or empty. - * @param attr_type Attribute type, from #pj_stun_attr_type. - * @param value The string value to be assigned to the attribute. + * @param attr The string attribute to be initialized. + * @param pool Pool to duplicate the value into the attribute, + * if value is not NULL or empty. + * @param attr_type Attribute type, from #pj_stun_attr_type. + * @param value The string value to be assigned to the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_string_attr_init(pj_stun_string_attr *attr, - pj_pool_t *pool, - int attr_type, - const pj_str_t *value); + pj_pool_t *pool, + int attr_type, + const pj_str_t *value); /** * Create a STUN generic string attribute. * - * @param pool The pool to allocate memory from. - * @param attr_type Attribute type, from #pj_stun_attr_type. - * @param value The string value to be assigned to the attribute. - * @param p_attr Pointer to receive the attribute. + * @param pool The pool to allocate memory from. + * @param attr_type Attribute type, from #pj_stun_attr_type. + * @param value The string value to be assigned to the attribute. + * @param p_attr Pointer to receive the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_string_attr_create(pj_pool_t *pool, - int attr_type, - const pj_str_t *value, - pj_stun_string_attr **p_attr); + int attr_type, + const pj_str_t *value, + pj_stun_string_attr **p_attr); /** * Create and add STUN generic string attribute to the message. * - * @param pool The pool to allocate memory from. - * @param msg The STUN message. - * @param attr_type Attribute type, from #pj_stun_attr_type. - * @param value The string value to be assigned to the attribute. + * @param pool The pool to allocate memory from. + * @param msg The STUN message. + * @param attr_type Attribute type, from #pj_stun_attr_type. + * @param value The string value to be assigned to the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_msg_add_string_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int attr_type, - const pj_str_t *value); + pj_stun_msg *msg, + int attr_type, + const pj_str_t *value); /** * Create a STUN generic 32bit value attribute. * - * @param pool The pool to allocate memory from. - * @param attr_type Attribute type, from #pj_stun_attr_type. - * @param value The 32bit value to be assigned to the attribute. - * @param p_attr Pointer to receive the attribute. + * @param pool The pool to allocate memory from. + * @param attr_type Attribute type, from #pj_stun_attr_type. + * @param value The 32bit value to be assigned to the attribute. + * @param p_attr Pointer to receive the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_uint_attr_create(pj_pool_t *pool, - int attr_type, - pj_uint32_t value, - pj_stun_uint_attr **p_attr); + int attr_type, + pj_uint32_t value, + pj_stun_uint_attr **p_attr); /** * Create and add STUN generic 32bit value attribute to the message. * - * @param pool The pool to allocate memory from. - * @param msg The STUN message - * @param attr_type Attribute type, from #pj_stun_attr_type. - * @param value The 32bit value to be assigned to the attribute. + * @param pool The pool to allocate memory from. + * @param msg The STUN message + * @param attr_type Attribute type, from #pj_stun_attr_type. + * @param value The 32bit value to be assigned to the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_msg_add_uint_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int attr_type, - pj_uint32_t value); + pj_stun_msg *msg, + int attr_type, + pj_uint32_t value); /** * Create a STUN generic 64bit value attribute. * - * @param pool Pool to allocate memory from. - * @param attr_type Attribute type, from #pj_stun_attr_type. - * @param value Optional value to be assigned. - * @param p_attr Pointer to receive the attribute. + * @param pool Pool to allocate memory from. + * @param attr_type Attribute type, from #pj_stun_attr_type. + * @param value Optional value to be assigned. + * @param p_attr Pointer to receive the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_uint64_attr_create(pj_pool_t *pool, - int attr_type, - const pj_timestamp *value, - pj_stun_uint64_attr **p_attr); + int attr_type, + const pj_timestamp *value, + pj_stun_uint64_attr **p_attr); /** * Create and add STUN generic 64bit value attribute to the message. * - * @param pool The pool to allocate memory from. - * @param msg The STUN message - * @param attr_type Attribute type, from #pj_stun_attr_type. - * @param value The 64bit value to be assigned to the attribute. + * @param pool The pool to allocate memory from. + * @param msg The STUN message + * @param attr_type Attribute type, from #pj_stun_attr_type. + * @param value The 64bit value to be assigned to the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_msg_add_uint64_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int attr_type, - const pj_timestamp *value); + pj_stun_msg *msg, + int attr_type, + const pj_timestamp *value); /** * Create a STUN MESSAGE-INTEGRITY attribute. * - * @param pool The pool to allocate memory from. - * @param p_attr Pointer to receive the attribute. + * @param pool The pool to allocate memory from. + * @param p_attr Pointer to receive the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_msgint_attr_create(pj_pool_t *pool, - pj_stun_msgint_attr **p_attr); + pj_stun_msgint_attr **p_attr); /** * Create and add STUN MESSAGE-INTEGRITY attribute. * - * @param pool The pool to allocate memory from. - * @param msg The STUN message + * @param pool The pool to allocate memory from. + * @param msg The STUN message * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_msg_add_msgint_attr(pj_pool_t *pool, - pj_stun_msg *msg); + pj_stun_msg *msg); /** * Create a STUN ERROR-CODE attribute. * - * @param pool The pool to allocate memory from. - * @param err_code STUN error code. - * @param err_reason Optional STUN error reason. If NULL is given, the - * standard error reason will be given. - * @param p_attr Pointer to receive the attribute. + * @param pool The pool to allocate memory from. + * @param err_code STUN error code. + * @param err_reason Optional STUN error reason. If NULL is given, the + * standard error reason will be given. + * @param p_attr Pointer to receive the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_errcode_attr_create(pj_pool_t *pool, - int err_code, - const pj_str_t *err_reason, - pj_stun_errcode_attr **p_attr); + int err_code, + const pj_str_t *err_reason, + pj_stun_errcode_attr **p_attr); /** * Create and add STUN ERROR-CODE attribute to the message. * - * @param pool The pool to allocate memory from. - * @param msg The STUN mesage. - * @param err_code STUN error code. - * @param err_reason Optional STUN error reason. If NULL is given, the - * standard error reason will be given. + * @param pool The pool to allocate memory from. + * @param msg The STUN mesage. + * @param err_code STUN error code. + * @param err_reason Optional STUN error reason. If NULL is given, the + * standard error reason will be given. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_msg_add_errcode_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int err_code, - const pj_str_t *err_reason); + pj_stun_msg *msg, + int err_code, + const pj_str_t *err_reason); /** * Create instance of STUN UNKNOWN-ATTRIBUTES attribute and copy the * unknown attribute array to the attribute. * - * @param pool The pool to allocate memory from. - * @param attr_cnt Number of attributes in the array (can be zero). - * @param attr Optional array of attributes. - * @param p_attr Pointer to receive the attribute. + * @param pool The pool to allocate memory from. + * @param attr_cnt Number of attributes in the array (can be zero). + * @param attr Optional array of attributes. + * @param p_attr Pointer to receive the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_unknown_attr_create(pj_pool_t *pool, - unsigned attr_cnt, - const pj_uint16_t attr[], - pj_stun_unknown_attr **p_attr); + unsigned attr_cnt, + const pj_uint16_t attr[], + pj_stun_unknown_attr **p_attr); /** * Create and add STUN UNKNOWN-ATTRIBUTES attribute to the message. * - * @param pool The pool to allocate memory from. - * @param msg The STUN message. - * @param attr_cnt Number of attributes in the array (can be zero). - * @param attr Optional array of attribute types. + * @param pool The pool to allocate memory from. + * @param msg The STUN message. + * @param attr_cnt Number of attributes in the array (can be zero). + * @param attr Optional array of attribute types. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_msg_add_unknown_attr(pj_pool_t *pool, - pj_stun_msg *msg, - unsigned attr_cnt, - const pj_uint16_t attr[]); + pj_stun_msg *msg, + unsigned attr_cnt, + const pj_uint16_t attr[]); /** * Initialize STUN binary attribute. * - * @param attr The attribute to be initialized. - * @param pool Pool to copy data, if the data and length are set. - * @param attr_type The attribute type, from #pj_stun_attr_type. - * @param data Data to be coped to the attribute, or NULL - * if no data to be copied now. - * @param length Length of data, or zero if no data is to be - * copied now. + * @param attr The attribute to be initialized. + * @param pool Pool to copy data, if the data and length are set. + * @param attr_type The attribute type, from #pj_stun_attr_type. + * @param data Data to be coped to the attribute, or NULL + * if no data to be copied now. + * @param length Length of data, or zero if no data is to be + * copied now. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_binary_attr_init(pj_stun_binary_attr *attr, - pj_pool_t *pool, - int attr_type, - const pj_uint8_t *data, - unsigned length); + pj_pool_t *pool, + int attr_type, + const pj_uint8_t *data, + unsigned length); /** * Create STUN binary attribute. * - * @param pool The pool to allocate memory from. - * @param attr_type The attribute type, from #pj_stun_attr_type. - * @param data Data to be coped to the attribute, or NULL - * if no data to be copied now. - * @param length Length of data, or zero if no data is to be - * copied now. - * @param p_attr Pointer to receive the attribute. + * @param pool The pool to allocate memory from. + * @param attr_type The attribute type, from #pj_stun_attr_type. + * @param data Data to be coped to the attribute, or NULL + * if no data to be copied now. + * @param length Length of data, or zero if no data is to be + * copied now. + * @param p_attr Pointer to receive the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_binary_attr_create(pj_pool_t *pool, - int attr_type, - const pj_uint8_t *data, - unsigned length, - pj_stun_binary_attr **p_attr); + int attr_type, + const pj_uint8_t *data, + unsigned length, + pj_stun_binary_attr **p_attr); /** * Create STUN binary attribute and add the attribute to the message. * - * @param pool The pool to allocate memory from. - * @param msg The STUN message. - * @param attr_type The attribute type, from #pj_stun_attr_type. - * @param data Data to be coped to the attribute, or NULL - * if no data to be copied now. - * @param length Length of data, or zero if no data is to be - * copied now. + * @param pool The pool to allocate memory from. + * @param msg The STUN message. + * @param attr_type The attribute type, from #pj_stun_attr_type. + * @param data Data to be coped to the attribute, or NULL + * if no data to be copied now. + * @param length Length of data, or zero if no data is to be + * copied now. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_msg_add_binary_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int attr_type, - const pj_uint8_t *data, - unsigned length); + pj_stun_msg *msg, + int attr_type, + const pj_uint8_t *data, + unsigned length); /** * Create STUN empty attribute. * - * @param pool The pool to allocate memory from. - * @param attr_type The attribute type, from #pj_stun_attr_type. - * @param p_attr Pointer to receive the attribute. + * @param pool The pool to allocate memory from. + * @param attr_type The attribute type, from #pj_stun_attr_type. + * @param p_attr Pointer to receive the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_empty_attr_create(pj_pool_t *pool, - int attr_type, - pj_stun_empty_attr **p_attr); + int attr_type, + pj_stun_empty_attr **p_attr); /** * Create STUN empty attribute and add the attribute to the message. * - * @param pool The pool to allocate memory from. - * @param msg The STUN message. - * @param attr_type The attribute type, from #pj_stun_attr_type. + * @param pool The pool to allocate memory from. + * @param msg The STUN message. + * @param attr_type The attribute type, from #pj_stun_attr_type. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_msg_add_empty_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int attr_type); + pj_stun_msg *msg, + int attr_type); /** * @} @@ -1849,5 +1848,5 @@ PJ_DECL(pj_status_t) pj_stun_msg_add_empty_attr(pj_pool_t *pool, PJ_END_DECL -#endif /* __PJNATH_STUN_MSG_H__ */ +#endif /* __PJNATH_STUN_MSG_H__ */ diff --git a/pjnath/include/pjnath/stun_session.h b/pjnath/include/pjnath/stun_session.h index 18909993af..4a5076bb1b 100644 --- a/pjnath/include/pjnath/stun_session.h +++ b/pjnath/include/pjnath/stun_session.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -185,30 +184,30 @@ typedef struct pj_stun_session_cb /** * Callback to be called by the STUN session to send outgoing message. * - * @param sess The STUN session. - * @param token The token associated with this outgoing message - * and was set by the application. This token was - * set by application in pj_stun_session_send_msg() - * for outgoing messages that are initiated by the - * application, or in pj_stun_session_on_rx_pkt() - * if this message is a response that was internally - * generated by the STUN session (for example, an - * 401/Unauthorized response). Application may use - * this facility for any purposes. - * @param pkt Packet to be sent. - * @param pkt_size Size of the packet to be sent. - * @param dst_addr The destination address. - * @param addr_len Length of destination address. + * @param sess The STUN session. + * @param token The token associated with this outgoing message + * and was set by the application. This token was + * set by application in pj_stun_session_send_msg() + * for outgoing messages that are initiated by the + * application, or in pj_stun_session_on_rx_pkt() + * if this message is a response that was internally + * generated by the STUN session (for example, an + * 401/Unauthorized response). Application may use + * this facility for any purposes. + * @param pkt Packet to be sent. + * @param pkt_size Size of the packet to be sent. + * @param dst_addr The destination address. + * @param addr_len Length of destination address. * - * @return The callback should return the status of the - * packet sending. + * @return The callback should return the status of the + * packet sending. */ pj_status_t (*on_send_msg)(pj_stun_session *sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len); + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len); /** * Callback to be called on incoming STUN request message. This function @@ -220,26 +219,26 @@ typedef struct pj_stun_session_cb * with pj_stun_session_send_msg() function, before returning from * the callback. * - * @param sess The STUN session. - * @param pkt Pointer to the original STUN packet. - * @param pkt_len Length of the STUN packet. - * @param rdata Data containing incoming request message. - * @param token The token that was set by the application when - * calling pj_stun_session_on_rx_pkt() function. - * @param src_addr Source address of the packet. + * @param sess The STUN session. + * @param pkt Pointer to the original STUN packet. + * @param pkt_len Length of the STUN packet. + * @param rdata Data containing incoming request message. + * @param token The token that was set by the application when + * calling pj_stun_session_on_rx_pkt() function. + * @param src_addr Source address of the packet. * @param src_addr_len Length of the source address. * - * @return The return value of this callback will be - * returned back to pj_stun_session_on_rx_pkt() - * function. + * @return The return value of this callback will be + * returned back to pj_stun_session_on_rx_pkt() + * function. */ pj_status_t (*on_rx_request)(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_rx_data *rdata, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_rx_data *rdata, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); /** * Callback to be called when response is received or the transaction @@ -249,35 +248,35 @@ typedef struct pj_stun_session_cb * the STUN client transaction has timed-out before a STUN response is * received. * - * @param sess The STUN session. - * @param status Status of the request. If the value if not - * PJ_SUCCESS, the transaction has timed-out - * or other error has occurred, and the response - * argument may be NULL. - * Note that when the status is not success, the - * response may contain non-NULL value if the - * response contains STUN ERROR-CODE attribute. - * @param token The token that was set by the application when - * calling pj_stun_session_send_msg() function. - * Please not that this token IS NOT the token - * that was given in pj_stun_session_on_rx_pkt(). - * @param tdata The original STUN request. - * @param response The response message, on successful transaction, - * or otherwise MAY BE NULL if status is not success. - * Note that when the status is not success, this - * argument may contain non-NULL value if the - * response contains STUN ERROR-CODE attribute. - * @param src_addr The source address where the response was - * received, or NULL if the response is NULL. + * @param sess The STUN session. + * @param status Status of the request. If the value if not + * PJ_SUCCESS, the transaction has timed-out + * or other error has occurred, and the response + * argument may be NULL. + * Note that when the status is not success, the + * response may contain non-NULL value if the + * response contains STUN ERROR-CODE attribute. + * @param token The token that was set by the application when + * calling pj_stun_session_send_msg() function. + * Please not that this token IS NOT the token + * that was given in pj_stun_session_on_rx_pkt(). + * @param tdata The original STUN request. + * @param response The response message, on successful transaction, + * or otherwise MAY BE NULL if status is not success. + * Note that when the status is not success, this + * argument may contain non-NULL value if the + * response contains STUN ERROR-CODE attribute. + * @param src_addr The source address where the response was + * received, or NULL if the response is NULL. * @param src_addr_len The length of the source address. */ void (*on_request_complete)(pj_stun_session *sess, - pj_status_t status, - void *token, - pj_stun_tx_data *tdata, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + pj_status_t status, + void *token, + pj_stun_tx_data *tdata, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); /** @@ -286,26 +285,26 @@ typedef struct pj_stun_session_cb * the STUN session has detected that the incoming STUN message is a * STUN indication message. * - * @param sess The STUN session. - * @param pkt Pointer to the original STUN packet. - * @param pkt_len Length of the STUN packet. - * @param msg The parsed STUN indication. - * @param token The token that was set by the application when - * calling pj_stun_session_on_rx_pkt() function. - * @param src_addr Source address of the packet. + * @param sess The STUN session. + * @param pkt Pointer to the original STUN packet. + * @param pkt_len Length of the STUN packet. + * @param msg The parsed STUN indication. + * @param token The token that was set by the application when + * calling pj_stun_session_on_rx_pkt() function. + * @param src_addr Source address of the packet. * @param src_addr_len Length of the source address. * - * @return The return value of this callback will be - * returned back to pj_stun_session_on_rx_pkt() - * function. + * @return The return value of this callback will be + * returned back to pj_stun_session_on_rx_pkt() + * function. */ pj_status_t (*on_rx_indication)(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_msg *msg, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_msg *msg, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); } pj_stun_session_cb; @@ -318,7 +317,7 @@ struct pj_stun_rx_data /** * The parsed request message. */ - pj_stun_msg *msg; + pj_stun_msg *msg; /** * Credential information that is found and used to authenticate @@ -338,30 +337,30 @@ struct pj_stun_tx_data /** PJLIB list interface */ PJ_DECL_LIST_MEMBER(struct pj_stun_tx_data); - pj_pool_t *pool; /**< Pool. */ - pj_stun_session *sess; /**< The STUN session. */ - pj_stun_msg *msg; /**< The STUN message. */ - pj_bool_t is_destroying; /**< Is destroying? */ + pj_pool_t *pool; /**< Pool. */ + pj_stun_session *sess; /**< The STUN session. */ + pj_stun_msg *msg; /**< The STUN message. */ + pj_bool_t is_destroying; /**< Is destroying? */ - void *token; /**< The token. */ + void *token; /**< The token. */ - pj_stun_client_tsx *client_tsx; /**< Client STUN transaction. */ - pj_bool_t retransmit; /**< Retransmit request? */ - pj_uint32_t msg_magic; /**< Message magic. */ - pj_uint8_t msg_key[12]; /**< Message/transaction key. */ + pj_stun_client_tsx *client_tsx; /**< Client STUN transaction. */ + pj_bool_t retransmit; /**< Retransmit request? */ + pj_uint32_t msg_magic; /**< Message magic. */ + pj_uint8_t msg_key[12]; /**< Message/transaction key. */ - pj_grp_lock_t *grp_lock; /**< Group lock (for resp cache). */ + pj_grp_lock_t *grp_lock; /**< Group lock (for resp cache). */ - pj_stun_req_cred_info auth_info; /**< Credential info */ + pj_stun_req_cred_info auth_info; /**< Credential info */ - void *pkt; /**< The STUN packet. */ - unsigned max_len; /**< Length of packet buffer. */ - pj_size_t pkt_size; /**< The actual length of STUN pkt. */ + void *pkt; /**< The STUN packet. */ + unsigned max_len; /**< Length of packet buffer. */ + pj_size_t pkt_size; /**< The actual length of STUN pkt. */ - unsigned addr_len; /**< Length of destination address. */ - const pj_sockaddr_t *dst_addr; /**< Destination address. */ + unsigned addr_len; /**< Length of destination address. */ + const pj_sockaddr_t *dst_addr; /**< Destination address. */ - pj_timer_entry res_timer; /**< Response cache timer. */ + pj_timer_entry res_timer; /**< Response cache timer. */ }; @@ -370,48 +369,48 @@ struct pj_stun_tx_data */ typedef enum pj_stun_sess_msg_log_flag { - PJ_STUN_SESS_LOG_TX_REQ=1, /**< Log outgoing STUN requests. */ - PJ_STUN_SESS_LOG_TX_RES=2, /**< Log outgoing STUN responses. */ - PJ_STUN_SESS_LOG_TX_IND=4, /**< Log outgoing STUN indications. */ + PJ_STUN_SESS_LOG_TX_REQ=1, /**< Log outgoing STUN requests. */ + PJ_STUN_SESS_LOG_TX_RES=2, /**< Log outgoing STUN responses. */ + PJ_STUN_SESS_LOG_TX_IND=4, /**< Log outgoing STUN indications. */ - PJ_STUN_SESS_LOG_RX_REQ=8, /**< Log incoming STUN requests. */ - PJ_STUN_SESS_LOG_RX_RES=16, /**< Log incoming STUN responses */ - PJ_STUN_SESS_LOG_RX_IND=32 /**< Log incoming STUN indications */ + PJ_STUN_SESS_LOG_RX_REQ=8, /**< Log incoming STUN requests. */ + PJ_STUN_SESS_LOG_RX_RES=16, /**< Log incoming STUN responses */ + PJ_STUN_SESS_LOG_RX_IND=32 /**< Log incoming STUN indications */ } pj_stun_sess_msg_log_flag; /** * Create a STUN session. * - * @param cfg The STUN endpoint, to be used to register timers etc. - * @param name Optional name to be associated with this instance. The - * name will be used for example for logging purpose. - * @param cb Session callback. - * @param fingerprint Enable message fingerprint for outgoing messages. - * @param grp_lock Optional group lock to be used by this session. - * If NULL, the session will create one itself. - * @param p_sess Pointer to receive STUN session instance. + * @param cfg The STUN endpoint, to be used to register timers etc. + * @param name Optional name to be associated with this instance. The + * name will be used for example for logging purpose. + * @param cb Session callback. + * @param fingerprint Enable message fingerprint for outgoing messages. + * @param grp_lock Optional group lock to be used by this session. + * If NULL, the session will create one itself. + * @param p_sess Pointer to receive STUN session instance. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_session_create(pj_stun_config *cfg, - const char *name, - const pj_stun_session_cb *cb, - pj_bool_t fingerprint, - pj_grp_lock_t *grp_lock, - pj_stun_session **p_sess); + const char *name, + const pj_stun_session_cb *cb, + pj_bool_t fingerprint, + pj_grp_lock_t *grp_lock, + pj_stun_session **p_sess); /** * Destroy the STUN session and all objects created in the context of * this session. * - * @param sess The STUN session instance. + * @param sess The STUN session instance. * - * @return PJ_SUCCESS on success, or the appropriate error code. - * This function will return PJ_EPENDING if the operation - * cannot be performed immediately because callbacks are - * being called; in this case the session will be destroyed - * as soon as the last callback returns. + * @return PJ_SUCCESS on success, or the appropriate error code. + * This function will return PJ_EPENDING if the operation + * cannot be performed immediately because callbacks are + * being called; in this case the session will be destroyed + * as soon as the last callback returns. */ PJ_DECL(pj_status_t) pj_stun_session_destroy(pj_stun_session *sess); @@ -419,45 +418,45 @@ PJ_DECL(pj_status_t) pj_stun_session_destroy(pj_stun_session *sess); * Associated an arbitrary data with this STUN session. The user data may * be retrieved later with pj_stun_session_get_user_data() function. * - * @param sess The STUN session instance. + * @param sess The STUN session instance. * @param user_data The user data. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_session_set_user_data(pj_stun_session *sess, - void *user_data); + void *user_data); /** * Retrieve the user data previously associated to this STUN session with * pj_stun_session_set_user_data(). * - * @param sess The STUN session instance. + * @param sess The STUN session instance. * - * @return The user data associated with this STUN session. + * @return The user data associated with this STUN session. */ PJ_DECL(void*) pj_stun_session_get_user_data(pj_stun_session *sess); /** * Get the group lock for this STUN session. * - * @param sess The STUN session instance. + * @param sess The STUN session instance. * - * @return The group lock. + * @return The group lock. */ PJ_DECL(pj_grp_lock_t *) pj_stun_session_get_grp_lock(pj_stun_session *sess); /** * Set SOFTWARE name to be included in all requests and responses. * - * @param sess The STUN session instance. - * @param sw Software name string. If this argument is NULL or - * empty, the session will not include SOFTWARE attribute - * in STUN requests and responses. + * @param sess The STUN session instance. + * @param sw Software name string. If this argument is NULL or + * empty, the session will not include SOFTWARE attribute + * in STUN requests and responses. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_session_set_software_name(pj_stun_session *sess, - const pj_str_t *sw); + const pj_str_t *sw); /** * Set credential to be used by this session. Once credential is set, all @@ -467,75 +466,75 @@ PJ_DECL(pj_status_t) pj_stun_session_set_software_name(pj_stun_session *sess, * To disable authentication after it has been set, call this function * again with NULL as the argument. * - * @param sess The STUN session instance. + * @param sess The STUN session instance. * @param auth_type Type of authentication. - * @param cred The credential to be used by this session. If NULL - * is specified, authentication will be disabled. + * @param cred The credential to be used by this session. If NULL + * is specified, authentication will be disabled. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_session_set_credential(pj_stun_session *sess, - pj_stun_auth_type auth_type, - const pj_stun_auth_cred *cred); + pj_stun_auth_type auth_type, + const pj_stun_auth_cred *cred); /** * Configure message logging. By default all flags are enabled. * - * @param sess The STUN session instance. - * @param flags Bitmask combination of #pj_stun_sess_msg_log_flag + * @param sess The STUN session instance. + * @param flags Bitmask combination of #pj_stun_sess_msg_log_flag */ PJ_DECL(void) pj_stun_session_set_log(pj_stun_session *sess, - unsigned flags); + unsigned flags); /** * Configure whether the STUN session should utilize FINGERPRINT in * outgoing messages. * - * @param sess The STUN session instance. - * @param use Boolean for the setting. + * @param sess The STUN session instance. + * @param use Boolean for the setting. * - * @return The previous configured value of FINGERPRINT - * utilization of the sessoin. + * @return The previous configured value of FINGERPRINT + * utilization of the sessoin. */ PJ_DECL(pj_bool_t) pj_stun_session_use_fingerprint(pj_stun_session *sess, - pj_bool_t use); + pj_bool_t use); /** * Create a STUN request message. After the message has been successfully * created, application can send the message by calling * pj_stun_session_send_msg(). * - * @param sess The STUN session instance. + * @param sess The STUN session instance. * @param msg_type The STUN request message type, from pj_stun_method_e or - * from pj_stun_msg_type. - * @param magic STUN magic, use PJ_STUN_MAGIC. + * from pj_stun_msg_type. + * @param magic STUN magic, use PJ_STUN_MAGIC. * @param tsx_id Optional transaction ID. * @param p_tdata Pointer to receive STUN transmit data instance containing - * the request. + * the request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_session_create_req(pj_stun_session *sess, - int msg_type, - pj_uint32_t magic, - const pj_uint8_t tsx_id[12], - pj_stun_tx_data **p_tdata); + int msg_type, + pj_uint32_t magic, + const pj_uint8_t tsx_id[12], + pj_stun_tx_data **p_tdata); /** * Create a STUN Indication message. After the message has been successfully * created, application can send the message by calling * pj_stun_session_send_msg(). * - * @param sess The STUN session instance. + * @param sess The STUN session instance. * @param msg_type The STUN request message type, from pj_stun_method_e or - * from pj_stun_msg_type. This function will add the - * indication bit as necessary. + * from pj_stun_msg_type. This function will add the + * indication bit as necessary. * @param p_tdata Pointer to receive STUN transmit data instance containing - * the message. + * the message. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_session_create_ind(pj_stun_session *sess, - int msg_type, - pj_stun_tx_data **p_tdata); + int msg_type, + pj_stun_tx_data **p_tdata); /** * Create a STUN response message. After the message has been @@ -544,25 +543,25 @@ PJ_DECL(pj_status_t) pj_stun_session_create_ind(pj_stun_session *sess, * pj_stun_session_respond() to create and send response in one function * call. * - * @param sess The STUN session instance. - * @param rdata The STUN request where the response is to be created. + * @param sess The STUN session instance. + * @param rdata The STUN request where the response is to be created. * @param err_code Error code to be set in the response, if error response - * is to be created, according to pj_stun_status enumeration. - * This argument MUST be zero if successful response is - * to be created. + * is to be created, according to pj_stun_status enumeration. + * This argument MUST be zero if successful response is + * to be created. * @param err_msg Optional pointer for the error message string, when - * creating error response. If the value is NULL and the - * \a err_code is non-zero, then default error message will - * be used. + * creating error response. If the value is NULL and the + * \a err_code is non-zero, then default error message will + * be used. * @param p_tdata Pointer to receive the response message created. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_session_create_res(pj_stun_session *sess, - const pj_stun_rx_data *rdata, - unsigned err_code, - const pj_str_t *err_msg, - pj_stun_tx_data **p_tdata); + const pj_stun_rx_data *rdata, + unsigned err_code, + const pj_str_t *err_msg, + pj_stun_tx_data **p_tdata); /** * Send STUN message to the specified destination. This function will encode @@ -574,39 +573,39 @@ PJ_DECL(pj_status_t) pj_stun_session_create_res(pj_stun_session *sess, * (which is registered when the STUN session is created) will be called * to actually send the message to the wire. * - * @param sess The STUN session instance. - * @param token Optional token which will be given back to application in - * \a on_send_msg() callback and \a on_request_complete() - * callback, if the message is a STUN request message. - * Internally this function will put the token in the - * \a token field of pj_stun_tx_data, hence it will - * overwrite any value that the application puts there. + * @param sess The STUN session instance. + * @param token Optional token which will be given back to application in + * \a on_send_msg() callback and \a on_request_complete() + * callback, if the message is a STUN request message. + * Internally this function will put the token in the + * \a token field of pj_stun_tx_data, hence it will + * overwrite any value that the application puts there. * @param cache_res If the message is a response message for an incoming - * request, specify PJ_TRUE to instruct the STUN session - * to cache this response for subsequent incoming request - * retransmission. Otherwise this parameter will be ignored - * for non-response message. + * request, specify PJ_TRUE to instruct the STUN session + * to cache this response for subsequent incoming request + * retransmission. Otherwise this parameter will be ignored + * for non-response message. * @param retransmit If the message is a request message, specify whether the - * request should be retransmitted. Normally application will - * specify TRUE if the underlying transport is UDP and FALSE - * if the underlying transport is TCP or TLS. + * request should be retransmitted. Normally application will + * specify TRUE if the underlying transport is UDP and FALSE + * if the underlying transport is TCP or TLS. * @param dst_addr The destination socket address. * @param addr_len Length of destination address. - * @param tdata The STUN transmit data containing the STUN message to - * be sent. + * @param tdata The STUN transmit data containing the STUN message to + * be sent. * - * @return PJ_SUCCESS on success, or the appropriate error code. - * This function will return PJNATH_ESTUNDESTROYED if - * application has destroyed the session in - * \a on_send_msg() callback. + * @return PJ_SUCCESS on success, or the appropriate error code. + * This function will return PJNATH_ESTUNDESTROYED if + * application has destroyed the session in + * \a on_send_msg() callback. */ PJ_DECL(pj_status_t) pj_stun_session_send_msg(pj_stun_session *sess, - void *token, - pj_bool_t cache_res, - pj_bool_t retransmit, - const pj_sockaddr_t *dst_addr, - unsigned addr_len, - pj_stun_tx_data *tdata); + void *token, + pj_bool_t cache_res, + pj_bool_t retransmit, + const pj_sockaddr_t *dst_addr, + unsigned addr_len, + pj_stun_tx_data *tdata); /** * This is a utility function to create and send response for an incoming @@ -614,84 +613,84 @@ PJ_DECL(pj_status_t) pj_stun_session_send_msg(pj_stun_session *sess, * and pj_stun_session_send_msg(). It is provided here as a matter of * convenience. * - * @param sess The STUN session instance. - * @param rdata The STUN request message to be responded. - * @param code Error code to be set in the response, if error response - * is to be created, according to pj_stun_status enumeration. - * This argument MUST be zero if successful response is - * to be created. + * @param sess The STUN session instance. + * @param rdata The STUN request message to be responded. + * @param code Error code to be set in the response, if error response + * is to be created, according to pj_stun_status enumeration. + * This argument MUST be zero if successful response is + * to be created. * @param err_msg Optional pointer for the error message string, when - * creating error response. If the value is NULL and the - * \a err_code is non-zero, then default error message will - * be used. - * @param token Optional token which will be given back to application in - * \a on_send_msg() callback and \a on_request_complete() - * callback, if the message is a STUN request message. - * Internally this function will put the token in the - * \a token field of pj_stun_tx_data, hence it will - * overwrite any value that the application puts there. - * @param cache Specify whether session should cache this response for - * future request retransmission. If TRUE, subsequent request - * retransmission will be handled by the session and it - * will not call request callback. + * creating error response. If the value is NULL and the + * \a err_code is non-zero, then default error message will + * be used. + * @param token Optional token which will be given back to application in + * \a on_send_msg() callback and \a on_request_complete() + * callback, if the message is a STUN request message. + * Internally this function will put the token in the + * \a token field of pj_stun_tx_data, hence it will + * overwrite any value that the application puts there. + * @param cache Specify whether session should cache this response for + * future request retransmission. If TRUE, subsequent request + * retransmission will be handled by the session and it + * will not call request callback. * @param dst_addr Destination address of the response (or equal to the - * source address of the original request). + * source address of the original request). * @param addr_len Address length. * - * @return PJ_SUCCESS on success, or the appropriate error code. - * This function will return PJNATH_ESTUNDESTROYED if - * application has destroyed the session in - * \a on_send_msg() callback. + * @return PJ_SUCCESS on success, or the appropriate error code. + * This function will return PJNATH_ESTUNDESTROYED if + * application has destroyed the session in + * \a on_send_msg() callback. */ PJ_DECL(pj_status_t) pj_stun_session_respond(pj_stun_session *sess, - const pj_stun_rx_data *rdata, - unsigned code, - const char *err_msg, - void *token, - pj_bool_t cache, - const pj_sockaddr_t *dst_addr, - unsigned addr_len); + const pj_stun_rx_data *rdata, + unsigned code, + const char *err_msg, + void *token, + pj_bool_t cache, + const pj_sockaddr_t *dst_addr, + unsigned addr_len); /** * Cancel outgoing STUN transaction. This operation is only valid for outgoing * STUN request, to cease retransmission of the request and destroy the * STUN client transaction that is used to send the request. * - * @param sess The STUN session instance. - * @param tdata The request message previously sent. + * @param sess The STUN session instance. + * @param tdata The request message previously sent. * @param notify Specify whether \a on_request_complete() callback should - * be called. + * be called. * @param status If \a on_request_complete() callback is to be called, - * specify the error status to be given when calling the - * callback. This error status MUST NOT be PJ_SUCCESS. + * specify the error status to be given when calling the + * callback. This error status MUST NOT be PJ_SUCCESS. * - * @return PJ_SUCCESS if transaction is successfully cancelled. - * This function will return PJNATH_ESTUNDESTROYED if - * application has destroyed the session in - * \a on_request_complete() callback. + * @return PJ_SUCCESS if transaction is successfully cancelled. + * This function will return PJNATH_ESTUNDESTROYED if + * application has destroyed the session in + * \a on_request_complete() callback. */ PJ_DECL(pj_status_t) pj_stun_session_cancel_req(pj_stun_session *sess, - pj_stun_tx_data *tdata, - pj_bool_t notify, - pj_status_t status); + pj_stun_tx_data *tdata, + pj_bool_t notify, + pj_status_t status); /** * Explicitly request retransmission of the request. Normally application * doesn't need to do this, but this functionality is needed by ICE to * speed up connectivity check completion. * - * @param sess The STUN session instance. - * @param tdata The request message previously sent. + * @param sess The STUN session instance. + * @param tdata The request message previously sent. * @param mod_count Boolean flag to indicate whether transmission count * needs to be incremented. * - * @return PJ_SUCCESS on success, or the appropriate error. - * This function will return PJNATH_ESTUNDESTROYED if - * application has destroyed the session in \a on_send_msg() - * callback. + * @return PJ_SUCCESS on success, or the appropriate error. + * This function will return PJNATH_ESTUNDESTROYED if + * application has destroyed the session in \a on_send_msg() + * callback. */ PJ_DECL(pj_status_t) pj_stun_session_retransmit_req(pj_stun_session *sess, - pj_stun_tx_data *tdata, + pj_stun_tx_data *tdata, pj_bool_t mod_count); @@ -709,48 +708,48 @@ PJ_DECL(pj_status_t) pj_stun_session_retransmit_req(pj_stun_session *sess, * On successful message processing, application will be notified about * the message via one of the pj_stun_session_cb callback. * - * @param sess The STUN session instance. - * @param packet The packet containing STUN message. - * @param pkt_size Size of the packet. - * @param options Options, from #pj_stun_decode_options. - * @param parsed_len Optional pointer to receive the size of the parsed - * STUN message (useful if packet is received via a - * stream oriented protocol). - * @param token Optional token which will be given back to application - * in the \a on_rx_request(), \a on_rx_indication() and - * \a on_send_msg() callbacks. The token can be used to - * associate processing or incoming request or indication - * with some context. - * @param src_addr The source address of the packet, which will also - * be given back to application callbacks, along with - * source address length. - * @param src_addr_len Length of the source address. - * - * @return PJ_SUCCESS on success, or the appropriate error code. - * This function will return PJNATH_ESTUNDESTROYED if - * application has destroyed the session in one of the - * callback. + * @param sess The STUN session instance. + * @param packet The packet containing STUN message. + * @param pkt_size Size of the packet. + * @param options Options, from #pj_stun_decode_options. + * @param parsed_len Optional pointer to receive the size of the parsed + * STUN message (useful if packet is received via a + * stream oriented protocol). + * @param token Optional token which will be given back to application + * in the \a on_rx_request(), \a on_rx_indication() and + * \a on_send_msg() callbacks. The token can be used to + * associate processing or incoming request or indication + * with some context. + * @param src_addr The source address of the packet, which will also + * be given back to application callbacks, along with + * source address length. + * @param src_addr_len Length of the source address. + * + * @return PJ_SUCCESS on success, or the appropriate error code. + * This function will return PJNATH_ESTUNDESTROYED if + * application has destroyed the session in one of the + * callback. */ PJ_DECL(pj_status_t) pj_stun_session_on_rx_pkt(pj_stun_session *sess, - const void *packet, - pj_size_t pkt_size, - unsigned options, - void *token, - pj_size_t *parsed_len, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + const void *packet, + pj_size_t pkt_size, + unsigned options, + void *token, + pj_size_t *parsed_len, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); /** * Destroy the transmit data. Call this function only when tdata has been * created but application doesn't want to send the message (perhaps * because of other error). * - * @param sess The STUN session. - * @param tdata The transmit data. + * @param sess The STUN session. + * @param tdata The transmit data. * */ PJ_DECL(void) pj_stun_msg_destroy_tdata(pj_stun_session *sess, - pj_stun_tx_data *tdata); + pj_stun_tx_data *tdata); /** @@ -760,5 +759,5 @@ PJ_DECL(void) pj_stun_msg_destroy_tdata(pj_stun_session *sess, PJ_END_DECL -#endif /* __PJNATH_STUN_SESSION_H__ */ +#endif /* __PJNATH_STUN_SESSION_H__ */ diff --git a/pjnath/include/pjnath/stun_sock.h b/pjnath/include/pjnath/stun_sock.h index fe99292de9..a6610335ee 100644 --- a/pjnath/include/pjnath/stun_sock.h +++ b/pjnath/include/pjnath/stun_sock.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -71,7 +70,7 @@ typedef enum pj_stun_sock_op /** * Asynchronous DNS resolution. */ - PJ_STUN_SOCK_DNS_OP = 1, + PJ_STUN_SOCK_DNS_OP = 1, /** * Initial STUN Binding request. @@ -102,74 +101,74 @@ typedef struct pj_stun_sock_cb /** * Notification when incoming packet has been received. * - * @param stun_sock The STUN transport. - * @param data The packet. - * @param data_len Length of the packet. - * @param src_addr The source address of the packet. - * @param addr_len The length of the source address. + * @param stun_sock The STUN transport. + * @param data The packet. + * @param data_len Length of the packet. + * @param src_addr The source address of the packet. + * @param addr_len The length of the source address. * - * @return Application should normally return PJ_TRUE to let - * the STUN transport continue its operation. However - * it must return PJ_FALSE if it has destroyed the - * STUN transport in this callback. + * @return Application should normally return PJ_TRUE to let + * the STUN transport continue its operation. However + * it must return PJ_FALSE if it has destroyed the + * STUN transport in this callback. */ pj_bool_t (*on_rx_data)(pj_stun_sock *stun_sock, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *src_addr, - unsigned addr_len); + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *src_addr, + unsigned addr_len); /** * Notifification when asynchronous send operation has completed. * - * @param stun_sock The STUN transport. - * @param send_key The send operation key that was given in - * #pj_stun_sock_sendto(). - * @param sent If value is positive non-zero it indicates the - * number of data sent. When the value is negative, - * it contains the error code which can be retrieved - * by negating the value (i.e. status=-sent). + * @param stun_sock The STUN transport. + * @param send_key The send operation key that was given in + * #pj_stun_sock_sendto(). + * @param sent If value is positive non-zero it indicates the + * number of data sent. When the value is negative, + * it contains the error code which can be retrieved + * by negating the value (i.e. status=-sent). * - * @return Application should normally return PJ_TRUE to let - * the STUN transport continue its operation. However - * it must return PJ_FALSE if it has destroyed the - * STUN transport in this callback. + * @return Application should normally return PJ_TRUE to let + * the STUN transport continue its operation. However + * it must return PJ_FALSE if it has destroyed the + * STUN transport in this callback. */ pj_bool_t (*on_data_sent)(pj_stun_sock *stun_sock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent); + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent); /** * Notification when the status of the STUN transport has changed. This * callback may be called for the following conditions: - * - the first time the publicly mapped address has been resolved from - * the STUN server, this callback will be called with \a op argument + * - the first time the publicly mapped address has been resolved from + * the STUN server, this callback will be called with \a op argument * set to PJ_STUN_SOCK_BINDING_OP \a status argument set to * PJ_SUCCESS. - * - anytime when the transport has detected that the publicly mapped + * - anytime when the transport has detected that the publicly mapped * address has changed, this callback will be called with \a op * argument set to PJ_STUN_SOCK_KEEP_ALIVE_OP and \a status * argument set to PJ_SUCCESS. On this case and the case above, * application will get the resolved public address in the * #pj_stun_sock_info structure. - * - for any terminal error (such as STUN time-out, DNS resolution + * - for any terminal error (such as STUN time-out, DNS resolution * failure, or keep-alive failure), this callback will be called - * with the \a status argument set to non-PJ_SUCCESS. + * with the \a status argument set to non-PJ_SUCCESS. * - * @param stun_sock The STUN transport. - * @param op The operation that triggers the callback. - * @param status The status. + * @param stun_sock The STUN transport. + * @param op The operation that triggers the callback. + * @param status The status. * - * @return Must return PJ_FALSE if it has destroyed the - * STUN transport in this callback. Application should - * normally destroy the socket and return PJ_FALSE - * upon encountering terminal error, otherwise it - * should return PJ_TRUE to let the STUN socket operation - * continues. + * @return Must return PJ_FALSE if it has destroyed the + * STUN transport in this callback. Application should + * normally destroy the socket and return PJ_FALSE + * upon encountering terminal error, otherwise it + * should return PJ_TRUE to let the STUN socket operation + * continues. */ - pj_bool_t (*on_status)(pj_stun_sock *stun_sock, - pj_stun_sock_op op, - pj_status_t status); + pj_bool_t (*on_status)(pj_stun_sock *stun_sock, + pj_stun_sock_op op, + pj_status_t status); } pj_stun_sock_cb; @@ -183,30 +182,30 @@ typedef struct pj_stun_sock_info /** * The bound address of the socket. */ - pj_sockaddr bound_addr; + pj_sockaddr bound_addr; /** * IP address of the STUN server. */ - pj_sockaddr srv_addr; + pj_sockaddr srv_addr; /** * The publicly mapped address. It may contain zero address when the * mapped address has not been resolved. Application may query whether * this field contains valid address with pj_sockaddr_has_addr(). */ - pj_sockaddr mapped_addr; + pj_sockaddr mapped_addr; /** * Number of interface address aliases. The interface address aliases * are list of all interface addresses in this host. */ - unsigned alias_cnt; + unsigned alias_cnt; /** * Array of interface address aliases. */ - pj_sockaddr aliases[PJ_ICE_ST_MAX_CAND]; + pj_sockaddr aliases[PJ_ICE_ST_MAX_CAND]; } pj_stun_sock_info; @@ -259,7 +258,7 @@ typedef struct pj_stun_sock_cfg * * Default value is zero. */ - pj_uint16_t port_range; + pj_uint16_t port_range; /** * Specify the STUN keep-alive duration, in seconds. The STUN transport @@ -328,7 +327,7 @@ PJ_DECL(const char*) pj_stun_sock_op_name(pj_stun_sock_op op); /** * Initialize the STUN transport setting with its default values. * - * @param cfg The STUN transport config. + * @param cfg The STUN transport config. */ PJ_DECL(void) pj_stun_sock_cfg_default(pj_stun_sock_cfg *cfg); @@ -338,29 +337,29 @@ PJ_DECL(void) pj_stun_sock_cfg_default(pj_stun_sock_cfg *cfg); * the STUN transport has been create, application should call * #pj_stun_sock_start() to start the transport. * - * @param stun_cfg The STUN configuration which contains among other - * things the ioqueue and timer heap instance for - * the operation of this transport. - * @param af Address family of socket. Currently pj_AF_INET() - * and pj_AF_INET6() are supported. - * @param name Optional name to be given to this transport to - * assist debugging. - * @param cb Callback to receive events/data from the transport. - * @param cfg Optional transport settings. - * @param user_data Arbitrary application data to be associated with - * this transport. - * @param p_sock Pointer to receive the created transport instance. + * @param stun_cfg The STUN configuration which contains among other + * things the ioqueue and timer heap instance for + * the operation of this transport. + * @param af Address family of socket. Currently pj_AF_INET() + * and pj_AF_INET6() are supported. + * @param name Optional name to be given to this transport to + * assist debugging. + * @param cb Callback to receive events/data from the transport. + * @param cfg Optional transport settings. + * @param user_data Arbitrary application data to be associated with + * this transport. + * @param p_sock Pointer to receive the created transport instance. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_stun_sock_create(pj_stun_config *stun_cfg, - const char *name, - int af, - const pj_stun_sock_cb *cb, - const pj_stun_sock_cfg *cfg, - void *user_data, - pj_stun_sock **p_sock); + const char *name, + int af, + const pj_stun_sock_cb *cb, + const pj_stun_sock_cfg *cfg, + void *user_data, + pj_stun_sock **p_sock); /** @@ -370,41 +369,41 @@ PJ_DECL(pj_status_t) pj_stun_sock_create(pj_stun_config *stun_cfg, * Once the initial STUN Binding response is received, the keep-alive * timer will be started. * - * @param stun_sock The STUN transport instance. - * @param domain The domain, hostname, or IP address of the STUN - * server. When this parameter contains domain name, - * the \a resolver parameter must be set to activate - * DNS SRV resolution. - * @param default_port The default STUN port number to use when DNS SRV - * resolution is not used. If DNS SRV resolution is - * used, the server port number will be set from the - * DNS SRV records. The recommended value for this - * parameter is PJ_STUN_PORT. - * @param resolver If this parameter is not NULL, then the \a domain - * parameter will be first resolved with DNS SRV and - * then fallback to using DNS A/AAAA resolution when - * DNS SRV resolution fails. If this parameter is - * NULL, the \a domain parameter will be resolved as - * hostname. + * @param stun_sock The STUN transport instance. + * @param domain The domain, hostname, or IP address of the STUN + * server. When this parameter contains domain name, + * the \a resolver parameter must be set to activate + * DNS SRV resolution. + * @param default_port The default STUN port number to use when DNS SRV + * resolution is not used. If DNS SRV resolution is + * used, the server port number will be set from the + * DNS SRV records. The recommended value for this + * parameter is PJ_STUN_PORT. + * @param resolver If this parameter is not NULL, then the \a domain + * parameter will be first resolved with DNS SRV and + * then fallback to using DNS A/AAAA resolution when + * DNS SRV resolution fails. If this parameter is + * NULL, the \a domain parameter will be resolved as + * hostname. * - * @return PJ_SUCCESS if the operation has been successfully - * queued, or the appropriate error code on failure. - * When this function returns PJ_SUCCESS, the final - * result of the allocation process will be notified - * to application in \a on_status() callback. + * @return PJ_SUCCESS if the operation has been successfully + * queued, or the appropriate error code on failure. + * When this function returns PJ_SUCCESS, the final + * result of the allocation process will be notified + * to application in \a on_status() callback. */ PJ_DECL(pj_status_t) pj_stun_sock_start(pj_stun_sock *stun_sock, - const pj_str_t *domain, - pj_uint16_t default_port, - pj_dns_resolver *resolver); + const pj_str_t *domain, + pj_uint16_t default_port, + pj_dns_resolver *resolver); /** * Destroy the STUN transport. * - * @param sock The STUN transport socket. + * @param sock The STUN transport socket. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_stun_sock_destroy(pj_stun_sock *sock); @@ -413,22 +412,22 @@ PJ_DECL(pj_status_t) pj_stun_sock_destroy(pj_stun_sock *sock); * Associate a user data with this STUN transport. The user data may then * be retrieved later with #pj_stun_sock_get_user_data(). * - * @param stun_sock The STUN transport instance. - * @param user_data Arbitrary data. + * @param stun_sock The STUN transport instance. + * @param user_data Arbitrary data. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_stun_sock_set_user_data(pj_stun_sock *stun_sock, - void *user_data); + void *user_data); /** * Retrieve the previously assigned user data associated with this STUN * transport. * - * @param stun_sock The STUN transport instance. + * @param stun_sock The STUN transport instance. * - * @return The user/application data. + * @return The user/application data. */ PJ_DECL(void*) pj_stun_sock_get_user_data(pj_stun_sock *stun_sock); @@ -436,9 +435,9 @@ PJ_DECL(void*) pj_stun_sock_get_user_data(pj_stun_sock *stun_sock); /** * Get the group lock for this STUN transport. * - * @param stun_sock The STUN transport instance. + * @param stun_sock The STUN transport instance. * - * @return The group lock. + * @return The group lock. */ PJ_DECL(pj_grp_lock_t *) pj_stun_sock_get_grp_lock(pj_stun_sock *stun_sock); @@ -447,43 +446,43 @@ PJ_DECL(pj_grp_lock_t *) pj_stun_sock_get_grp_lock(pj_stun_sock *stun_sock); * Get the STUN transport info. The transport info contains, among other * things, the allocated relay address. * - * @param stun_sock The STUN transport instance. - * @param info Pointer to be filled with STUN transport info. + * @param stun_sock The STUN transport instance. + * @param info Pointer to be filled with STUN transport info. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_stun_sock_get_info(pj_stun_sock *stun_sock, - pj_stun_sock_info *info); + pj_stun_sock_info *info); /** * Send a data to the specified address. This function may complete * asynchronously and in this case \a on_data_sent() will be called. * - * @param stun_sock The STUN transport instance. - * @param send_key Optional send key for sending the packet down to - * the ioqueue. This value will be given back to - * \a on_data_sent() callback - * @param pkt The data/packet to be sent to peer. - * @param pkt_len Length of the data. - * @param flag pj_ioqueue_sendto() flag. - * @param dst_addr The remote address. - * @param addr_len Length of the address. + * @param stun_sock The STUN transport instance. + * @param send_key Optional send key for sending the packet down to + * the ioqueue. This value will be given back to + * \a on_data_sent() callback + * @param pkt The data/packet to be sent to peer. + * @param pkt_len Length of the data. + * @param flag pj_ioqueue_sendto() flag. + * @param dst_addr The remote address. + * @param addr_len Length of the address. * - * @return PJ_SUCCESS if data has been sent immediately, or - * PJ_EPENDING if data cannot be sent immediately. In - * this case the \a on_data_sent() callback will be - * called when data is actually sent. Any other return - * value indicates error condition. + * @return PJ_SUCCESS if data has been sent immediately, or + * PJ_EPENDING if data cannot be sent immediately. In + * this case the \a on_data_sent() callback will be + * called when data is actually sent. Any other return + * value indicates error condition. */ PJ_DECL(pj_status_t) pj_stun_sock_sendto(pj_stun_sock *stun_sock, - pj_ioqueue_op_key_t *send_key, - const void *pkt, - unsigned pkt_len, - unsigned flag, - const pj_sockaddr_t *dst_addr, - unsigned addr_len); + pj_ioqueue_op_key_t *send_key, + const void *pkt, + unsigned pkt_len, + unsigned flag, + const pj_sockaddr_t *dst_addr, + unsigned addr_len); /** * @} @@ -493,5 +492,5 @@ PJ_DECL(pj_status_t) pj_stun_sock_sendto(pj_stun_sock *stun_sock, PJ_END_DECL -#endif /* __PJNATH_STUN_SOCK_H__ */ +#endif /* __PJNATH_STUN_SOCK_H__ */ diff --git a/pjnath/include/pjnath/stun_transaction.h b/pjnath/include/pjnath/stun_transaction.h index 437401069d..bd6aba6df4 100644 --- a/pjnath/include/pjnath/stun_transaction.h +++ b/pjnath/include/pjnath/stun_transaction.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -66,38 +65,38 @@ typedef struct pj_stun_tsx_cb /** * This callback is called when the STUN transaction completed. * - * @param tsx The STUN transaction. - * @param status Status of the transaction. Status PJ_SUCCESS - * means that the request has received a successful - * response. - * @param response The STUN response, which value may be NULL if - * \a status is not PJ_SUCCESS. - * @param src_addr The source address of the response, if response - * is not NULL. + * @param tsx The STUN transaction. + * @param status Status of the transaction. Status PJ_SUCCESS + * means that the request has received a successful + * response. + * @param response The STUN response, which value may be NULL if + * \a status is not PJ_SUCCESS. + * @param src_addr The source address of the response, if response + * is not NULL. * @param src_addr_len The length of the source address. */ - void (*on_complete)(pj_stun_client_tsx *tsx, - pj_status_t status, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + void (*on_complete)(pj_stun_client_tsx *tsx, + pj_status_t status, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); /** * This callback is called by the STUN transaction when it wants to send * outgoing message. * - * @param tsx The STUN transaction instance. - * @param stun_pkt The STUN packet to be sent. - * @param pkt_size Size of the STUN packet. + * @param tsx The STUN transaction instance. + * @param stun_pkt The STUN packet to be sent. + * @param pkt_size Size of the STUN packet. * - * @return If return value of the callback is not PJ_SUCCESS, - * the transaction will fail. Application MUST return - * PJNATH_ESTUNDESTROYED if it has destroyed the - * transaction in this callback. + * @return If return value of the callback is not PJ_SUCCESS, + * the transaction will fail. Application MUST return + * PJNATH_ESTUNDESTROYED if it has destroyed the + * transaction in this callback. */ pj_status_t (*on_send_msg)(pj_stun_client_tsx *tsx, - const void *stun_pkt, - pj_size_t pkt_size); + const void *stun_pkt, + pj_size_t pkt_size); /** * This callback is called after the timer that was scheduled by @@ -108,7 +107,7 @@ typedef struct pj_stun_tsx_cb * This callback is optional if application will not call * #pj_stun_client_tsx_schedule_destroy(). * - * @param tsx The STUN transaction instance. + * @param tsx The STUN transaction instance. */ void (*on_destroy)(pj_stun_client_tsx *tsx); @@ -122,22 +121,22 @@ typedef struct pj_stun_tsx_cb * ensure the reliability of the request by periodically retransmitting * the request, if necessary. * - * @param cfg The STUN endpoint, which will be used to retrieve - * various settings for the transaction. - * @param pool Pool to be used to allocate memory from. - * @param grp_lock Group lock to synchronize. - * @param cb Callback structure, to be used by the transaction - * to send message and to notify the application about - * the completion of the transaction. - * @param p_tsx Pointer to receive the transaction instance. + * @param cfg The STUN endpoint, which will be used to retrieve + * various settings for the transaction. + * @param pool Pool to be used to allocate memory from. + * @param grp_lock Group lock to synchronize. + * @param cb Callback structure, to be used by the transaction + * to send message and to notify the application about + * the completion of the transaction. + * @param p_tsx Pointer to receive the transaction instance. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ -PJ_DECL(pj_status_t) pj_stun_client_tsx_create( pj_stun_config *cfg, - pj_pool_t *pool, - pj_grp_lock_t *grp_lock, - const pj_stun_tsx_cb *cb, - pj_stun_client_tsx **p_tsx); +PJ_DECL(pj_status_t) pj_stun_client_tsx_create( pj_stun_config *cfg, + pj_pool_t *pool, + pj_grp_lock_t *grp_lock, + const pj_stun_tsx_cb *cb, + pj_stun_client_tsx **p_tsx); /** * Schedule timer to destroy the transaction after the transaction is @@ -150,24 +149,24 @@ PJ_DECL(pj_status_t) pj_stun_client_tsx_create( pj_stun_config *cfg, * this, it can destroy the transaction immediately by calling * #pj_stun_client_tsx_destroy(). * - * @param tsx The STUN transaction. - * @param delay The delay interval before on_destroy() callback - * is called. + * @param tsx The STUN transaction. + * @param delay The delay interval before on_destroy() callback + * is called. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_client_tsx_schedule_destroy(pj_stun_client_tsx *tsx, - const pj_time_val *delay); + const pj_time_val *delay); /** * Destroy the STUN transaction immediately after the transaction is complete. * Application normally calls this function in the on_complete() callback. * - * @param tsx The STUN transaction. + * @param tsx The STUN transaction. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_client_tsx_destroy(pj_stun_client_tsx *tsx); @@ -175,10 +174,10 @@ PJ_DECL(pj_status_t) pj_stun_client_tsx_destroy(pj_stun_client_tsx *tsx); /** * Stop the client transaction. * - * @param tsx The STUN transaction. + * @param tsx The STUN transaction. * - * @return PJ_SUCCESS on success or PJ_EINVAL if the parameter - * is NULL. + * @return PJ_SUCCESS on success or PJ_EINVAL if the parameter + * is NULL. */ PJ_DECL(pj_status_t) pj_stun_client_tsx_stop(pj_stun_client_tsx *tsx); @@ -186,9 +185,9 @@ PJ_DECL(pj_status_t) pj_stun_client_tsx_stop(pj_stun_client_tsx *tsx); /** * Check if transaction has completed. * - * @param tsx The STUN transaction. + * @param tsx The STUN transaction. * - * @return Non-zero if transaction has completed. + * @return Non-zero if transaction has completed. */ PJ_DECL(pj_bool_t) pj_stun_client_tsx_is_complete(pj_stun_client_tsx *tsx); @@ -198,23 +197,23 @@ PJ_DECL(pj_bool_t) pj_stun_client_tsx_is_complete(pj_stun_client_tsx *tsx); * can be then retrieved later from the transaction, by using * pj_stun_client_tsx_get_data() function. * - * @param tsx The STUN client transaction. - * @param data Application data to be associated with the - * STUN transaction. + * @param tsx The STUN client transaction. + * @param data Application data to be associated with the + * STUN transaction. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pj_stun_client_tsx_set_data(pj_stun_client_tsx *tsx, - void *data); + void *data); /** * Get the user data that was previously associated with the STUN * transaction. * - * @param tsx The STUN client transaction. + * @param tsx The STUN client transaction. * - * @return The user data. + * @return The user data. */ PJ_DECL(void*) pj_stun_client_tsx_get_data(pj_stun_client_tsx *tsx); @@ -225,35 +224,35 @@ PJ_DECL(void*) pj_stun_client_tsx_get_data(pj_stun_client_tsx *tsx); * the retransmit flag should be set to PJ_FALSE because reliablity * will be assured by the transport layer. * - * @param tsx The STUN client transaction. - * @param retransmit Should this message be retransmitted by the - * STUN transaction. - * @param pkt The STUN packet to send. - * @param pkt_len Length of STUN packet. + * @param tsx The STUN client transaction. + * @param retransmit Should this message be retransmitted by the + * STUN transaction. + * @param pkt The STUN packet to send. + * @param pkt_len Length of STUN packet. * - * @return PJ_SUCCESS on success, or PJNATH_ESTUNDESTROYED - * when the user has destroyed the transaction in - * \a on_send_msg() callback, or any other error code - * as returned by \a on_send_msg() callback. + * @return PJ_SUCCESS on success, or PJNATH_ESTUNDESTROYED + * when the user has destroyed the transaction in + * \a on_send_msg() callback, or any other error code + * as returned by \a on_send_msg() callback. */ PJ_DECL(pj_status_t) pj_stun_client_tsx_send_msg(pj_stun_client_tsx *tsx, - pj_bool_t retransmit, - void *pkt, - unsigned pkt_len); + pj_bool_t retransmit, + void *pkt, + unsigned pkt_len); /** * Request to retransmit the request. Normally application should not need * to call this function since retransmission would be handled internally, * but this functionality is needed by ICE. * - * @param tsx The STUN client transaction instance. + * @param tsx The STUN client transaction instance. * @param mod_count Boolean flag to indicate whether transmission count * needs to be incremented. * - * @return PJ_SUCCESS on success, or PJNATH_ESTUNDESTROYED - * when the user has destroyed the transaction in - * \a on_send_msg() callback, or any other error code - * as returned by \a on_send_msg() callback. + * @return PJ_SUCCESS on success, or PJNATH_ESTUNDESTROYED + * when the user has destroyed the transaction in + * \a on_send_msg() callback, or any other error code + * as returned by \a on_send_msg() callback. */ PJ_DECL(pj_status_t) pj_stun_client_tsx_retransmit(pj_stun_client_tsx *tsx, pj_bool_t mod_count); @@ -267,17 +266,17 @@ PJ_DECL(pj_status_t) pj_stun_client_tsx_retransmit(pj_stun_client_tsx *tsx, * will cease, but application must still call this function again * with a final response later to allow the transaction to complete. * - * @param tsx The STUN client transaction instance. - * @param msg The incoming STUN message. - * @param src_addr The source address of the packet. - * @param src_addr_len The length of the source address. + * @param tsx The STUN client transaction instance. + * @param msg The incoming STUN message. + * @param src_addr The source address of the packet. + * @param src_addr_len The length of the source address. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pj_stun_client_tsx_on_rx_msg(pj_stun_client_tsx *tsx, - const pj_stun_msg *msg, - const pj_sockaddr_t*src_addr, - unsigned src_addr_len); + const pj_stun_msg *msg, + const pj_sockaddr_t*src_addr, + unsigned src_addr_len); /** @@ -288,5 +287,5 @@ PJ_DECL(pj_status_t) pj_stun_client_tsx_on_rx_msg(pj_stun_client_tsx *tsx, PJ_END_DECL -#endif /* __PJNATH_STUN_TRANSACTION_H__ */ +#endif /* __PJNATH_STUN_TRANSACTION_H__ */ diff --git a/pjnath/include/pjnath/turn_session.h b/pjnath/include/pjnath/turn_session.h index f4416d7987..d49991ffd6 100644 --- a/pjnath/include/pjnath/turn_session.h +++ b/pjnath/include/pjnath/turn_session.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -218,8 +217,8 @@ typedef enum pj_turn_state_t */ typedef struct pj_turn_channel_data { - pj_uint16_t ch_number; /**< Channel number. */ - pj_uint16_t length; /**< Payload length. */ + pj_uint16_t ch_number; /**< Channel number. */ + pj_uint16_t length; /**< Payload length. */ } pj_turn_channel_data; @@ -239,20 +238,20 @@ typedef struct pj_turn_session_cb * If the callback \a on_stun_send_pkt() is implemented, outgoing * messages will use that callback instead. * - * @param sess The TURN session. - * @param pkt The packet/data to be sent. - * @param pkt_len Length of the packet/data. - * @param dst_addr Destination address of the packet. - * @param addr_len Length of the destination address. + * @param sess The TURN session. + * @param pkt The packet/data to be sent. + * @param pkt_len Length of the packet/data. + * @param dst_addr Destination address of the packet. + * @param addr_len Length of the destination address. * - * @return The callback should return the status of the - * send operation. + * @return The callback should return the status of the + * send operation. */ pj_status_t (*on_send_pkt)(pj_turn_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_sockaddr_t *dst_addr, - unsigned addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_sockaddr_t *dst_addr, + unsigned addr_len); /** * This callback will be called by the TURN session whenever it @@ -261,20 +260,20 @@ typedef struct pj_turn_session_cb * callback is not implemented, the callback \a on_send_pkt() * will be called instead. * - * @param sess The TURN session. - * @param pkt The packet/data to be sent. - * @param pkt_len Length of the packet/data. - * @param dst_addr Destination address of the packet. - * @param addr_len Length of the destination address. + * @param sess The TURN session. + * @param pkt The packet/data to be sent. + * @param pkt_len Length of the packet/data. + * @param dst_addr Destination address of the packet. + * @param addr_len Length of the destination address. * - * @return The callback should return the status of the - * send operation. + * @return The callback should return the status of the + * send operation. */ pj_status_t (*on_stun_send_pkt)(pj_turn_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_sockaddr_t *dst_addr, - unsigned addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_sockaddr_t *dst_addr, + unsigned addr_len); /** * Notification when peer address has been bound successfully to @@ -283,46 +282,46 @@ typedef struct pj_turn_session_cb * This callback is optional since the nature of this callback is * for information only. * - * @param sess The TURN session. - * @param peer_addr The peer address. - * @param addr_len Length of the peer address. - * @param ch_num The channel number associated with this peer address. + * @param sess The TURN session. + * @param peer_addr The peer address. + * @param addr_len Length of the peer address. + * @param ch_num The channel number associated with this peer address. */ void (*on_channel_bound)(pj_turn_session *sess, - const pj_sockaddr_t *peer_addr, - unsigned addr_len, - unsigned ch_num); + const pj_sockaddr_t *peer_addr, + unsigned addr_len, + unsigned ch_num); /** * Notification when incoming data has been received, either through * Data indication or ChannelData message from the TURN server. * - * @param sess The TURN session. - * @param pkt The data/payload of the Data Indication or ChannelData - * packet. - * @param pkt_len Length of the data/payload. - * @param peer_addr Peer address where this payload was received by - * the TURN server. - * @param addr_len Length of the peer address. + * @param sess The TURN session. + * @param pkt The data/payload of the Data Indication or ChannelData + * packet. + * @param pkt_len Length of the data/payload. + * @param peer_addr Peer address where this payload was received by + * the TURN server. + * @param addr_len Length of the peer address. */ void (*on_rx_data)(pj_turn_session *sess, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); /** * Notification when TURN session state has changed. Application should * implement this callback at least to know that the TURN session is * going to be destroyed. * - * @param sess The TURN session. - * @param old_state The previous state of the session. - * @param new_state The current state of the session. + * @param sess The TURN session. + * @param old_state The previous state of the session. + * @param new_state The current state of the session. */ void (*on_state)(pj_turn_session *sess, - pj_turn_state_t old_state, - pj_turn_state_t new_state); + pj_turn_state_t old_state, + pj_turn_state_t new_state); /** * Notification when TURN client received a ConnectionAttempt Indication @@ -335,47 +334,47 @@ typedef struct pj_turn_session_cb * pj_turn_session_connection_bind()). After the connection binding * succeeds, this new connection will become a data only connection. * - * @param sess The TURN session. - * @param conn_id The connection ID assigned by TURN server. - * @param peer_addr Peer address that tried to connect to the TURN server. - * @param addr_len Length of the peer address. + * @param sess The TURN session. + * @param conn_id The connection ID assigned by TURN server. + * @param peer_addr Peer address that tried to connect to the TURN server. + * @param addr_len Length of the peer address. */ void (*on_connection_attempt)(pj_turn_session *sess, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); /** * Notification for ConnectionBind request sent using * pj_turn_session_connection_bind(). * - * @param sess The TURN session. - * @param status The status code. - * @param conn_id The connection ID. - * @param peer_addr Peer address. - * @param addr_len Length of the peer address. + * @param sess The TURN session. + * @param status The status code. + * @param conn_id The connection ID. + * @param peer_addr Peer address. + * @param addr_len Length of the peer address. */ void (*on_connection_bind_status)(pj_turn_session *sess, - pj_status_t status, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + pj_status_t status, + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); /** * Notification for Connect request sent using * pj_turn_session_connect(). * - * @param sess The TURN session. - * @param status The status code. - * @param conn_id The connection ID. - * @param peer_addr Peer address. - * @param addr_len Length of the peer address. + * @param sess The TURN session. + * @param status The status code. + * @param conn_id The connection ID. + * @param peer_addr Peer address. + * @param addr_len Length of the peer address. */ void (*on_connect_complete)(pj_turn_session *sess, - pj_status_t status, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + pj_status_t status, + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); } pj_turn_session_cb; @@ -394,20 +393,20 @@ typedef struct pj_turn_alloc_param * after TURN-08 draft, hence application should only use this * attribute when talking to TURN-07 or older version. */ - int bandwidth; + int bandwidth; /** * The requested LIFETIME. Default is zero to not request any * explicit allocation lifetime. */ - int lifetime; + int lifetime; /** * If set to non-zero, the TURN session will periodically send blank * Send Indication every PJ_TURN_KEEP_ALIVE_SEC to refresh local * NAT bindings. Default is zero. */ - int ka_interval; + int ka_interval; /** * The requested ADDRESS-FAMILY. Default is zero to request relay with @@ -416,7 +415,7 @@ typedef struct pj_turn_alloc_param * * Default value is zero. */ - int af; + int af; /** * Type of connection to from TURN server to peer. Supported values are @@ -442,7 +441,7 @@ typedef struct pj_turn_session_info /** * Last error (if session was terminated because of error) */ - pj_status_t last_status; + pj_status_t last_status; /** * Type of connection to the TURN server. @@ -452,22 +451,22 @@ typedef struct pj_turn_session_info /** * The selected TURN server address. */ - pj_sockaddr server; + pj_sockaddr server; /** * Mapped address, as reported by the TURN server. */ - pj_sockaddr mapped_addr; + pj_sockaddr mapped_addr; /** * The relay address */ - pj_sockaddr relay_addr; + pj_sockaddr relay_addr; /** * Current seconds before allocation expires. */ - int lifetime; + int lifetime; } pj_turn_session_info; @@ -481,27 +480,27 @@ typedef struct pj_turn_session_on_rx_pkt_param * The packet as received from the TURN server. This should contain * either STUN encapsulated message or a ChannelData packet. */ - void *pkt; + void *pkt; /** * The length of the packet. */ - pj_size_t pkt_len; + pj_size_t pkt_len; /** * The number of parsed or processed data from the packet. */ - pj_size_t parsed_len; + pj_size_t parsed_len; /** * Source address where the packet is received from. */ - const pj_sockaddr_t *src_addr; + const pj_sockaddr_t *src_addr; /** * Length of the source address. */ - unsigned src_addr_len; + unsigned src_addr_len; } pj_turn_session_on_rx_pkt_param; @@ -509,7 +508,7 @@ typedef struct pj_turn_session_on_rx_pkt_param /** * Initialize pj_turn_alloc_param with the default values. * - * @param prm The TURN allocation parameter to be initialized. + * @param prm The TURN allocation parameter to be initialized. */ PJ_DECL(void) pj_turn_alloc_param_default(pj_turn_alloc_param *prm); @@ -517,20 +516,20 @@ PJ_DECL(void) pj_turn_alloc_param_default(pj_turn_alloc_param *prm); /** * Duplicate pj_turn_alloc_param. * - * @param pool Pool to allocate memory (currently not used) - * @param dst Destination parameter. - * @param src Source parameter. + * @param pool Pool to allocate memory (currently not used) + * @param dst Destination parameter. + * @param src Source parameter. */ PJ_DECL(void) pj_turn_alloc_param_copy(pj_pool_t *pool, - pj_turn_alloc_param *dst, - const pj_turn_alloc_param *src); + pj_turn_alloc_param *dst, + const pj_turn_alloc_param *src); /** * Get string representation for the given TURN state. * - * @param state The TURN session state. + * @param state The TURN session state. * - * @return The state name as NULL terminated string. + * @return The state name as NULL terminated string. */ PJ_DECL(const char*) pj_turn_state_name(pj_turn_state_t state); @@ -541,44 +540,44 @@ PJ_DECL(const char*) pj_turn_state_name(pj_turn_state_t state); * must call pj_turn_session_alloc() to allocate a relay address in the TURN * server. * - * @param cfg The STUN configuration which contains among other - * things the ioqueue and timer heap instance for - * the operation of this session. - * @param name Optional name to identify this session in the log. - * @param af Address family of the client connection. Currently - * pj_AF_INET() and pj_AF_INET6() are supported. - * @param conn_type Connection type to the TURN server. - * @param grp_lock Optional group lock object to be used by this session. - * If this value is NULL, the session will create - * a group lock internally. - * @param cb Callback to receive events from the TURN session. - * @param options Option flags, currently this value must be zero. - * @param user_data Arbitrary application data to be associated with - * this transport. - * @param p_sess Pointer to receive the created instance of the - * TURN session. - * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @param cfg The STUN configuration which contains among other + * things the ioqueue and timer heap instance for + * the operation of this session. + * @param name Optional name to identify this session in the log. + * @param af Address family of the client connection. Currently + * pj_AF_INET() and pj_AF_INET6() are supported. + * @param conn_type Connection type to the TURN server. + * @param grp_lock Optional group lock object to be used by this session. + * If this value is NULL, the session will create + * a group lock internally. + * @param cb Callback to receive events from the TURN session. + * @param options Option flags, currently this value must be zero. + * @param user_data Arbitrary application data to be associated with + * this transport. + * @param p_sess Pointer to receive the created instance of the + * TURN session. + * + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_session_create(const pj_stun_config *cfg, - const char *name, - int af, - pj_turn_tp_type conn_type, - pj_grp_lock_t *grp_lock, - const pj_turn_session_cb *cb, - unsigned options, - void *user_data, - pj_turn_session **p_sess); + const char *name, + int af, + pj_turn_tp_type conn_type, + pj_grp_lock_t *grp_lock, + const pj_turn_session_cb *cb, + unsigned options, + void *user_data, + pj_turn_session **p_sess); /** * Shutdown TURN client session. This will gracefully deallocate and * destroy the client session. * - * @param sess The TURN client session. + * @param sess The TURN client session. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_session_shutdown(pj_turn_session *sess); @@ -588,56 +587,56 @@ PJ_DECL(pj_status_t) pj_turn_session_shutdown(pj_turn_session *sess); * immediately. If there is an active allocation, the server will not * be notified about the client destruction. * - * @param sess The TURN client session. - * @param last_err Optional error code to be set to the session, - * which would be returned back in the \a info - * parameter of #pj_turn_session_get_info(). If - * this argument value is PJ_SUCCESS, the error - * code will not be set. If the session already - * has an error code set, this function will not - * overwrite that error code either. + * @param sess The TURN client session. + * @param last_err Optional error code to be set to the session, + * which would be returned back in the \a info + * parameter of #pj_turn_session_get_info(). If + * this argument value is PJ_SUCCESS, the error + * code will not be set. If the session already + * has an error code set, this function will not + * overwrite that error code either. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_session_destroy(pj_turn_session *sess, - pj_status_t last_err); + pj_status_t last_err); /** * Get the information about this TURN session and the allocation, if * any. * - * @param sess The TURN client session. - * @param info The structure to be initialized with the TURN - * session info. + * @param sess The TURN client session. + * @param info The structure to be initialized with the TURN + * session info. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_session_get_info(pj_turn_session *sess, - pj_turn_session_info *info); + pj_turn_session_info *info); /** * Associate a user data with this TURN session. The user data may then * be retrieved later with pj_turn_session_get_user_data(). * - * @param sess The TURN client session. - * @param user_data Arbitrary data. + * @param sess The TURN client session. + * @param user_data Arbitrary data. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_session_set_user_data(pj_turn_session *sess, - void *user_data); + void *user_data); /** * Retrieve the previously assigned user data associated with this TURN * session. * - * @param sess The TURN client session. + * @param sess The TURN client session. * - * @return The user/application data. + * @return The user/application data. */ PJ_DECL(void*) pj_turn_session_get_user_data(pj_turn_session *sess); @@ -645,9 +644,9 @@ PJ_DECL(void*) pj_turn_session_get_user_data(pj_turn_session *sess); /** * Get the group lock for this TURN session. * - * @param sess The TURN client session. + * @param sess The TURN client session. * - * @return The group lock. + * @return The group lock. */ PJ_DECL(pj_grp_lock_t *) pj_turn_session_get_grp_lock(pj_turn_session *sess); @@ -655,26 +654,26 @@ PJ_DECL(pj_grp_lock_t *) pj_turn_session_get_grp_lock(pj_turn_session *sess); /** * Configure message logging. By default all flags are enabled. * - * @param sess The TURN client session. - * @param flags Bitmask combination of #pj_stun_sess_msg_log_flag + * @param sess The TURN client session. + * @param flags Bitmask combination of #pj_stun_sess_msg_log_flag */ PJ_DECL(void) pj_turn_session_set_log(pj_turn_session *sess, - unsigned flags); + unsigned flags); /** * Configure the SOFTWARE name to be sent in all STUN requests by the * TURN session. * - * @param sess The TURN client session. - * @param sw Software name string. If this argument is NULL or - * empty, the session will not include SOFTWARE attribute - * in STUN requests and responses. + * @param sess The TURN client session. + * @param sw Software name string. If this argument is NULL or + * empty, the session will not include SOFTWARE attribute + * in STUN requests and responses. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_turn_session_set_software_name(pj_turn_session *sess, - const pj_str_t *sw); + const pj_str_t *sw); /** @@ -690,32 +689,32 @@ PJ_DECL(pj_status_t) pj_turn_session_set_software_name(pj_turn_session *sess, * resolution completes. In this case, the operation will be queued by * the session, and it will be sent once the server resolution completes. * - * @param sess The TURN client session. - * @param domain The domain, hostname, or IP address of the TURN - * server. When this parameter contains domain name, - * the \a resolver parameter must be set to activate - * DNS SRV resolution. - * @param default_port The default TURN port number to use when DNS SRV - * resolution is not used. If DNS SRV resolution is - * used, the server port number will be set from the - * DNS SRV records. - * @param resolver If this parameter is not NULL, then the \a domain - * parameter will be first resolved with DNS SRV and - * then fallback to using DNS A/AAAA resolution when - * DNS SRV resolution fails. If this parameter is - * NULL, the \a domain parameter will be resolved as - * hostname. - * - * @return PJ_SUCCESS if the operation has been successfully - * queued, or the appropriate error code on failure. - * When this function returns PJ_SUCCESS, the final - * result of the resolution process will be notified - * to application in \a on_state() callback. + * @param sess The TURN client session. + * @param domain The domain, hostname, or IP address of the TURN + * server. When this parameter contains domain name, + * the \a resolver parameter must be set to activate + * DNS SRV resolution. + * @param default_port The default TURN port number to use when DNS SRV + * resolution is not used. If DNS SRV resolution is + * used, the server port number will be set from the + * DNS SRV records. + * @param resolver If this parameter is not NULL, then the \a domain + * parameter will be first resolved with DNS SRV and + * then fallback to using DNS A/AAAA resolution when + * DNS SRV resolution fails. If this parameter is + * NULL, the \a domain parameter will be resolved as + * hostname. + * + * @return PJ_SUCCESS if the operation has been successfully + * queued, or the appropriate error code on failure. + * When this function returns PJ_SUCCESS, the final + * result of the resolution process will be notified + * to application in \a on_state() callback. */ PJ_DECL(pj_status_t) pj_turn_session_set_server(pj_turn_session *sess, - const pj_str_t *domain, - int default_port, - pj_dns_resolver *resolver); + const pj_str_t *domain, + int default_port, + pj_dns_resolver *resolver); /** @@ -723,14 +722,14 @@ PJ_DECL(pj_status_t) pj_turn_session_set_server(pj_turn_session *sess, * Application must call this function before sending Allocate request * with pj_turn_session_alloc(). * - * @param sess The TURN client session - * @param cred STUN credential to be used. + * @param sess The TURN client session + * @param cred STUN credential to be used. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_session_set_credential(pj_turn_session *sess, - const pj_stun_auth_cred *cred); + const pj_stun_auth_cred *cred); /** @@ -749,14 +748,14 @@ PJ_DECL(pj_status_t) pj_turn_session_set_credential(pj_turn_session *sess, * allocation alive until the session is destroyed, by sending periodic * allocation refresh to the TURN server. * - * @param sess The TURN client session. - * @param param Optional TURN allocation parameter. + * @param sess The TURN client session. + * @param param Optional TURN allocation parameter. * - * @return PJ_SUCCESS if the operation has been successfully - * initiated or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successfully + * initiated or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_session_alloc(pj_turn_session *sess, - const pj_turn_alloc_param *param); + const pj_turn_alloc_param *param); /** @@ -765,22 +764,22 @@ PJ_DECL(pj_status_t) pj_turn_session_alloc(pj_turn_session *sess, * IP address before it sends any data to that IP address, or otherwise * the TURN server will drop the data. * - * @param sess The TURN client session. - * @param addr_cnt Number of IP addresses. - * @param addr Array of peer IP addresses. Only the address family - * and IP address portion of the socket address matter. - * @param options Specify 1 to let the TURN client session automatically - * renew the permission later when they are about to - * expire. + * @param sess The TURN client session. + * @param addr_cnt Number of IP addresses. + * @param addr Array of peer IP addresses. Only the address family + * and IP address portion of the socket address matter. + * @param options Specify 1 to let the TURN client session automatically + * renew the permission later when they are about to + * expire. * - * @return PJ_SUCCESS if the operation has been successfully - * issued, or the appropriate error code. Note that - * the operation itself will complete asynchronously. + * @return PJ_SUCCESS if the operation has been successfully + * issued, or the appropriate error code. Note that + * the operation itself will complete asynchronously. */ PJ_DECL(pj_status_t) pj_turn_session_set_perm(pj_turn_session *sess, - unsigned addr_cnt, - const pj_sockaddr addr[], - unsigned options); + unsigned addr_cnt, + const pj_sockaddr addr[], + unsigned options); /** @@ -796,23 +795,23 @@ PJ_DECL(pj_status_t) pj_turn_session_set_perm(pj_turn_session *sess, * ultimately call \a on_send_pkt() callback to request the application * to actually send the packet containing the data to the TURN server. * - * @param sess The TURN client session. - * @param pkt The data/packet to be sent to peer. - * @param pkt_len Length of the data. - * @param peer_addr The remote peer address (the ultimate destination - * of the data, and not the TURN server address). - * @param addr_len Length of the address. + * @param sess The TURN client session. + * @param pkt The data/packet to be sent to peer. + * @param pkt_len Length of the data. + * @param peer_addr The remote peer address (the ultimate destination + * of the data, and not the TURN server address). + * @param addr_len Length of the address. * - * @return If the callback \a on_send_pkt() is called, this - * will contain the return value of the callback. - * Otherwise, it will indicate failure with - * the appropriate error code. + * @return If the callback \a on_send_pkt() is called, this + * will contain the return value of the callback. + * Otherwise, it will indicate failure with + * the appropriate error code. */ PJ_DECL(pj_status_t) pj_turn_session_sendto(pj_turn_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); /** * Optionally establish channel binding for the specified a peer address. @@ -826,16 +825,16 @@ PJ_DECL(pj_status_t) pj_turn_session_sendto(pj_turn_session *sess, * This function will complete asynchronously, and application will be * notified about the result in \a on_channel_bound() callback. * - * @param sess The TURN client session. - * @param peer The remote peer address. - * @param addr_len Length of the address. + * @param sess The TURN client session. + * @param peer The remote peer address. + * @param addr_len Length of the address. * - * @return PJ_SUCCESS if the operation has been successfully - * initiated, or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successfully + * initiated, or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_session_bind_channel(pj_turn_session *sess, - const pj_sockaddr_t *peer, - unsigned addr_len); + const pj_sockaddr_t *peer, + unsigned addr_len); /** * Notify TURN client session upon receiving a packet from server. Since @@ -846,22 +845,22 @@ PJ_DECL(pj_status_t) pj_turn_session_bind_channel(pj_turn_session *sess, * data to be reported back to user, which in this case it will call the * \a on_rx_data() callback. * - * @param sess The TURN client session. - * @param pkt The packet as received from the TURN server. This - * should contain either STUN encapsulated message or - * a ChannelData packet. - * @param pkt_len The length of the packet. - * @param parsed_len Optional argument to receive the number of parsed - * or processed data from the packet. + * @param sess The TURN client session. + * @param pkt The packet as received from the TURN server. This + * should contain either STUN encapsulated message or + * a ChannelData packet. + * @param pkt_len The length of the packet. + * @param parsed_len Optional argument to receive the number of parsed + * or processed data from the packet. * - * @return The function may return non-PJ_SUCCESS if it receives - * non-STUN and non-ChannelData packet, or if the - * \a on_rx_data() returns non-PJ_SUCCESS; + * @return The function may return non-PJ_SUCCESS if it receives + * non-STUN and non-ChannelData packet, or if the + * \a on_rx_data() returns non-PJ_SUCCESS; */ PJ_DECL(pj_status_t) pj_turn_session_on_rx_pkt(pj_turn_session *sess, - void *pkt, - pj_size_t pkt_len, - pj_size_t *parsed_len); + void *pkt, + pj_size_t pkt_len, + pj_size_t *parsed_len); /** * Notify TURN client session upon receiving a packet from server. Since @@ -879,16 +878,16 @@ PJ_DECL(pj_status_t) pj_turn_session_on_rx_pkt(pj_turn_session *sess, * for example in RFC 6062 scenario that there can be some data connection * and a control connection. * - * @param sess The TURN client session. - * @param prm The function parameters, e.g: packet, source address. + * @param sess The TURN client session. + * @param prm The function parameters, e.g: packet, source address. * - * @return The function may return non-PJ_SUCCESS if it receives - * non-STUN and non-ChannelData packet, or if the - * \a on_rx_data() returns non-PJ_SUCCESS; + * @return The function may return non-PJ_SUCCESS if it receives + * non-STUN and non-ChannelData packet, or if the + * \a on_rx_data() returns non-PJ_SUCCESS; */ PJ_DECL(pj_status_t) pj_turn_session_on_rx_pkt2( - pj_turn_session *sess, - pj_turn_session_on_rx_pkt_param *prm); + pj_turn_session *sess, + pj_turn_session_on_rx_pkt_param *prm); /** * Initiate connection binding to the specified peer using ConnectionBind @@ -897,22 +896,22 @@ PJ_DECL(pj_status_t) pj_turn_session_on_rx_pkt2( * opening/accepting connection to/from peer. The connection binding status * will be notified via on_connection_bind_status callback. * - * @param sess The TURN session. - * @param pool The memory pool. - * @param conn_id The connection ID assigned by TURN server. - * @param peer_addr Peer address. - * @param addr_len Length of the peer address. + * @param sess The TURN session. + * @param pool The memory pool. + * @param conn_id The connection ID assigned by TURN server. + * @param peer_addr Peer address. + * @param addr_len Length of the peer address. * - * @return PJ_SUCCESS if the operation has been successfully - * issued, or the appropriate error code. Note that - * the operation itself will complete asynchronously. + * @return PJ_SUCCESS if the operation has been successfully + * issued, or the appropriate error code. Note that + * the operation itself will complete asynchronously. */ PJ_DECL(pj_status_t) pj_turn_session_connection_bind( - pj_turn_session *sess, - pj_pool_t *pool, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + pj_turn_session *sess, + pj_pool_t *pool, + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); /** * Initiate connection to the specified peer using Connect request. * Application must call this function when it uses RFC 6062 (TURN TCP @@ -925,13 +924,13 @@ PJ_DECL(pj_status_t) pj_turn_session_connection_bind( * (with pj_turn_session_alloc(), set TURN allocation parameter peer_conn_type * to PJ_TURN_TP_TCP) before calling this function. * - * @param sess The TURN client session. - * @param peer_addr Peer address. - * @param addr_len Length of the peer address. + * @param sess The TURN client session. + * @param peer_addr Peer address. + * @param addr_len Length of the peer address. * - * @return PJ_SUCCESS if the operation has been successfully - * issued, or the appropriate error code. Note that - * the operation itself will complete asynchronously. + * @return PJ_SUCCESS if the operation has been successfully + * issued, or the appropriate error code. Note that + * the operation itself will complete asynchronously. */ PJ_DECL(pj_status_t) pj_turn_session_connect(pj_turn_session *sess, const pj_sockaddr_t *peer_addr, @@ -945,5 +944,5 @@ PJ_DECL(pj_status_t) pj_turn_session_connect(pj_turn_session *sess, PJ_END_DECL -#endif /* __PJNATH_TURN_SESSION_H__ */ +#endif /* __PJNATH_TURN_SESSION_H__ */ diff --git a/pjnath/include/pjnath/turn_sock.h b/pjnath/include/pjnath/turn_sock.h index afb764bd4d..f5b3014a8b 100644 --- a/pjnath/include/pjnath/turn_sock.h +++ b/pjnath/include/pjnath/turn_sock.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -75,46 +74,46 @@ typedef struct pj_turn_sock_cb * such as Data Indication or ChannelData will be removed before this * function is called). * - * @param turn_sock The TURN client transport. - * @param data The data as received from the peer. - * @param data_len Length of the data. - * @param peer_addr The peer address. - * @param addr_len The length of the peer address. + * @param turn_sock The TURN client transport. + * @param data The data as received from the peer. + * @param data_len Length of the data. + * @param peer_addr The peer address. + * @param addr_len The length of the peer address. */ void (*on_rx_data)(pj_turn_sock *turn_sock, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); /** * Notifification when asynchronous send operation has completed. * - * @param turn_sock The TURN transport. - * @param sent If value is positive non-zero it indicates the - * number of data sent. When the value is negative, - * it contains the error code which can be retrieved - * by negating the value (i.e. status=-sent). + * @param turn_sock The TURN transport. + * @param sent If value is positive non-zero it indicates the + * number of data sent. When the value is negative, + * it contains the error code which can be retrieved + * by negating the value (i.e. status=-sent). * - * @return Application should normally return PJ_TRUE to let - * the TURN transport continue its operation. However - * it must return PJ_FALSE if it has destroyed the - * TURN transport in this callback. + * @return Application should normally return PJ_TRUE to let + * the TURN transport continue its operation. However + * it must return PJ_FALSE if it has destroyed the + * TURN transport in this callback. */ pj_bool_t (*on_data_sent)(pj_turn_sock *sock, - pj_ssize_t sent); + pj_ssize_t sent); /** * Notification when TURN session state has changed. Application should * implement this callback to monitor the progress of the TURN session. * - * @param turn_sock The TURN client transport. - * @param old_state Previous state. - * @param new_state Current state. + * @param turn_sock The TURN client transport. + * @param old_state Previous state. + * @param new_state Current state. */ void (*on_state)(pj_turn_sock *turn_sock, - pj_turn_state_t old_state, - pj_turn_state_t new_state); + pj_turn_state_t old_state, + pj_turn_state_t new_state); /** * Notification when TURN client received a ConnectionAttempt Indication @@ -129,35 +128,35 @@ typedef struct pj_turn_sock_cb * request, and eventually will notify application via * on_connection_status callback, if implemented. * - * @param turn_sock The TURN client transport. - * @param conn_id The connection ID assigned by TURN server. - * @param peer_addr Peer address that tried to connect to the - * TURN server. - * @param addr_len Length of the peer address. + * @param turn_sock The TURN client transport. + * @param conn_id The connection ID assigned by TURN server. + * @param peer_addr Peer address that tried to connect to the + * TURN server. + * @param addr_len Length of the peer address. * - * @return The callback must return PJ_SUCCESS to accept - * the connection attempt. + * @return The callback must return PJ_SUCCESS to accept + * the connection attempt. */ pj_status_t (*on_connection_attempt)(pj_turn_sock *turn_sock, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); /** * Notification for initiated TCP data connection to peer (RFC 6062), * for example after peer connection attempt is accepted. * - * @param turn_sock The TURN client transport. - * @param status The status code. - * @param conn_id The connection ID. - * @param peer_addr Peer address. - * @param addr_len Length of the peer address. + * @param turn_sock The TURN client transport. + * @param status The status code. + * @param conn_id The connection ID. + * @param peer_addr Peer address. + * @param addr_len Length of the peer address. */ void (*on_connection_status)(pj_turn_sock *turn_sock, - pj_status_t status, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + pj_status_t status, + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); } pj_turn_sock_cb; @@ -168,8 +167,8 @@ typedef struct pj_turn_sock_cb */ #ifndef PJ_TURN_TLS_DEFAULT_PROTO # define PJ_TURN_TLS_DEFAULT_PROTO (PJ_SSL_SOCK_PROTO_TLS1 | \ - PJ_SSL_SOCK_PROTO_TLS1_1 | \ - PJ_SSL_SOCK_PROTO_TLS1_2) + PJ_SSL_SOCK_PROTO_TLS1_1 | \ + PJ_SSL_SOCK_PROTO_TLS1_2) #endif /** @@ -180,23 +179,23 @@ typedef struct pj_turn_sock_tls_cfg /** * Certificate of Authority (CA) list file. */ - pj_str_t ca_list_file; + pj_str_t ca_list_file; /** * Certificate of Authority (CA) list directory path. */ - pj_str_t ca_list_path; + pj_str_t ca_list_path; /** * Public endpoint certificate file, which will be used as client- * side certificate for outgoing TLS connection. */ - pj_str_t cert_file; + pj_str_t cert_file; /** * Optional private key of the endpoint certificate to be used. */ - pj_str_t privkey_file; + pj_str_t privkey_file; /** * Certificate of Authority (CA) buffer. If ca_list_file, ca_list_path, @@ -222,7 +221,7 @@ typedef struct pj_turn_sock_tls_cfg /** * Password to open private key. */ - pj_str_t password; + pj_str_t password; /** * The ssl socket parameter. @@ -253,13 +252,13 @@ typedef struct pj_turn_sock_tls_cfg /** * Duplicate TLS setting. * - * @param pool The pool to duplicate strings etc. - * @param dst Destination structure. - * @param src Source structure. + * @param pool The pool to duplicate strings etc. + * @param dst Destination structure. + * @param src Source structure. */ PJ_DECL(void) pj_turn_sock_tls_cfg_dup(pj_pool_t *pool, - pj_turn_sock_tls_cfg *dst, - const pj_turn_sock_tls_cfg *src); + pj_turn_sock_tls_cfg *dst, + const pj_turn_sock_tls_cfg *src); /** * Wipe out certificates and keys in the TLS setting. @@ -332,7 +331,7 @@ typedef struct pj_turn_sock_cfg * * Default value is zero. */ - pj_uint16_t port_range; + pj_uint16_t port_range; /** * Specify target value for socket receive buffer size. It will be @@ -375,32 +374,32 @@ PJ_DECL(void) pj_turn_sock_cfg_default(pj_turn_sock_cfg *cfg); * must call pj_turn_sock_alloc() to allocate a relay address in the TURN * server. * - * @param cfg The STUN configuration which contains among other - * things the ioqueue and timer heap instance for - * the operation of this transport. - * @param af Address family of the client connection. Currently - * pj_AF_INET() and pj_AF_INET6() are supported. - * @param conn_type Connection type to the TURN server. Both TCP and - * UDP are supported. - * @param cb Callback to receive events from the TURN transport. - * @param setting Optional settings to be specified to the transport. - * If this parameter is NULL, default values will be - * used. - * @param user_data Arbitrary application data to be associated with - * this transport. - * @param p_turn_sock Pointer to receive the created instance of the - * TURN transport. - * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @param cfg The STUN configuration which contains among other + * things the ioqueue and timer heap instance for + * the operation of this transport. + * @param af Address family of the client connection. Currently + * pj_AF_INET() and pj_AF_INET6() are supported. + * @param conn_type Connection type to the TURN server. Both TCP and + * UDP are supported. + * @param cb Callback to receive events from the TURN transport. + * @param setting Optional settings to be specified to the transport. + * If this parameter is NULL, default values will be + * used. + * @param user_data Arbitrary application data to be associated with + * this transport. + * @param p_turn_sock Pointer to receive the created instance of the + * TURN transport. + * + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_sock_create(pj_stun_config *cfg, - int af, - pj_turn_tp_type conn_type, - const pj_turn_sock_cb *cb, - const pj_turn_sock_cfg *setting, - void *user_data, - pj_turn_sock **p_turn_sock); + int af, + pj_turn_tp_type conn_type, + const pj_turn_sock_cb *cb, + const pj_turn_sock_cfg *setting, + void *user_data, + pj_turn_sock **p_turn_sock); /** * Destroy the TURN transport instance. This will gracefully close the @@ -409,7 +408,7 @@ PJ_DECL(pj_status_t) pj_turn_sock_create(pj_stun_config *cfg, * in the background and the application may still get state changes * notifications from this transport. * - * @param turn_sock The TURN transport instance. + * @param turn_sock The TURN transport instance. */ PJ_DECL(void) pj_turn_sock_destroy(pj_turn_sock *turn_sock); @@ -418,22 +417,22 @@ PJ_DECL(void) pj_turn_sock_destroy(pj_turn_sock *turn_sock); * Associate a user data with this TURN transport. The user data may then * be retrieved later with #pj_turn_sock_get_user_data(). * - * @param turn_sock The TURN transport instance. - * @param user_data Arbitrary data. + * @param turn_sock The TURN transport instance. + * @param user_data Arbitrary data. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_sock_set_user_data(pj_turn_sock *turn_sock, - void *user_data); + void *user_data); /** * Retrieve the previously assigned user data associated with this TURN * transport. * - * @param turn_sock The TURN transport instance. + * @param turn_sock The TURN transport instance. * - * @return The user/application data. + * @return The user/application data. */ PJ_DECL(void*) pj_turn_sock_get_user_data(pj_turn_sock *turn_sock); @@ -441,9 +440,9 @@ PJ_DECL(void*) pj_turn_sock_get_user_data(pj_turn_sock *turn_sock); /** * Get the group lock for this TURN transport. * - * @param turn_sock The TURN transport instance. + * @param turn_sock The TURN transport instance. * - * @return The group lock. + * @return The group lock. */ PJ_DECL(pj_grp_lock_t *) pj_turn_sock_get_grp_lock(pj_turn_sock *turn_sock); @@ -452,24 +451,24 @@ PJ_DECL(pj_grp_lock_t *) pj_turn_sock_get_grp_lock(pj_turn_sock *turn_sock); * Get the TURN transport info. The transport info contains, among other * things, the allocated relay address. * - * @param turn_sock The TURN transport instance. - * @param info Pointer to be filled with TURN transport info. + * @param turn_sock The TURN transport instance. + * @param info Pointer to be filled with TURN transport info. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_sock_get_info(pj_turn_sock *turn_sock, - pj_turn_session_info *info); + pj_turn_session_info *info); /** * Acquire the internal mutex of the TURN transport. Application may need * to call this function to synchronize access to other objects alongside * the TURN transport, to avoid deadlock. * - * @param turn_sock The TURN transport instance. + * @param turn_sock The TURN transport instance. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_sock_lock(pj_turn_sock *turn_sock); @@ -477,10 +476,10 @@ PJ_DECL(pj_status_t) pj_turn_sock_lock(pj_turn_sock *turn_sock); /** * Release the internal mutex previously held with pj_turn_sock_lock(). * - * @param turn_sock The TURN transport instance. + * @param turn_sock The TURN transport instance. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_sock_unlock(pj_turn_sock *turn_sock); @@ -489,25 +488,25 @@ PJ_DECL(pj_status_t) pj_turn_sock_unlock(pj_turn_sock *turn_sock); * Set STUN message logging for this TURN session. * See #pj_stun_session_set_log(). * - * @param turn_sock The TURN transport instance. - * @param flags Bitmask combination of #pj_stun_sess_msg_log_flag + * @param turn_sock The TURN transport instance. + * @param flags Bitmask combination of #pj_stun_sess_msg_log_flag */ PJ_DECL(void) pj_turn_sock_set_log(pj_turn_sock *turn_sock, - unsigned flags); + unsigned flags); /** * Configure the SOFTWARE name to be sent in all STUN requests by the * TURN session. * - * @param turn_sock The TURN transport instance. - * @param sw Software name string. If this argument is NULL or - * empty, the session will not include SOFTWARE attribute - * in STUN requests and responses. + * @param turn_sock The TURN transport instance. + * @param sw Software name string. If this argument is NULL or + * empty, the session will not include SOFTWARE attribute + * in STUN requests and responses. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pj_turn_sock_set_software_name(pj_turn_sock *turn_sock, - const pj_str_t *sw); + const pj_str_t *sw); /** @@ -520,37 +519,37 @@ PJ_DECL(pj_status_t) pj_turn_sock_set_software_name(pj_turn_sock *turn_sock, * PJ_TURN_STATE_READY. If the allocation fails, the state will be set * to PJ_TURN_STATE_DEALLOCATING or greater. * - * @param turn_sock The TURN transport instance. - * @param domain The domain, hostname, or IP address of the TURN - * server. When this parameter contains domain name, - * the \a resolver parameter must be set to activate - * DNS SRV resolution. - * @param default_port The default TURN port number to use when DNS SRV - * resolution is not used. If DNS SRV resolution is - * used, the server port number will be set from the - * DNS SRV records. - * @param resolver If this parameter is not NULL, then the \a domain - * parameter will be first resolved with DNS SRV and - * then fallback to using DNS A/AAAA resolution when - * DNS SRV resolution fails. If this parameter is - * NULL, the \a domain parameter will be resolved as - * hostname. - * @param cred The STUN credential to be used for the TURN server. - * @param param Optional TURN allocation parameter. - * - * @return PJ_SUCCESS if the operation has been successfully - * queued, or the appropriate error code on failure. - * When this function returns PJ_SUCCESS, the final - * result of the allocation process will be notified - * to application in \a on_state() callback. - * + * @param turn_sock The TURN transport instance. + * @param domain The domain, hostname, or IP address of the TURN + * server. When this parameter contains domain name, + * the \a resolver parameter must be set to activate + * DNS SRV resolution. + * @param default_port The default TURN port number to use when DNS SRV + * resolution is not used. If DNS SRV resolution is + * used, the server port number will be set from the + * DNS SRV records. + * @param resolver If this parameter is not NULL, then the \a domain + * parameter will be first resolved with DNS SRV and + * then fallback to using DNS A/AAAA resolution when + * DNS SRV resolution fails. If this parameter is + * NULL, the \a domain parameter will be resolved as + * hostname. + * @param cred The STUN credential to be used for the TURN server. + * @param param Optional TURN allocation parameter. + * + * @return PJ_SUCCESS if the operation has been successfully + * queued, or the appropriate error code on failure. + * When this function returns PJ_SUCCESS, the final + * result of the allocation process will be notified + * to application in \a on_state() callback. + * */ PJ_DECL(pj_status_t) pj_turn_sock_alloc(pj_turn_sock *turn_sock, - const pj_str_t *domain, - int default_port, - pj_dns_resolver *resolver, - const pj_stun_auth_cred *cred, - const pj_turn_alloc_param *param); + const pj_str_t *domain, + int default_port, + pj_dns_resolver *resolver, + const pj_stun_auth_cred *cred, + const pj_turn_alloc_param *param); /** * Create or renew permission in the TURN server for the specified peer IP @@ -558,22 +557,22 @@ PJ_DECL(pj_status_t) pj_turn_sock_alloc(pj_turn_sock *turn_sock, * IP address before it sends any data to that IP address, or otherwise * the TURN server will drop the data. * - * @param turn_sock The TURN transport instance. - * @param addr_cnt Number of IP addresses. - * @param addr Array of peer IP addresses. Only the address family - * and IP address portion of the socket address matter. - * @param options Specify 1 to let the TURN client session automatically - * renew the permission later when they are about to - * expire. - * - * @return PJ_SUCCESS if the operation has been successfully - * issued, or the appropriate error code. Note that - * the operation itself will complete asynchronously. + * @param turn_sock The TURN transport instance. + * @param addr_cnt Number of IP addresses. + * @param addr Array of peer IP addresses. Only the address family + * and IP address portion of the socket address matter. + * @param options Specify 1 to let the TURN client session automatically + * renew the permission later when they are about to + * expire. + * + * @return PJ_SUCCESS if the operation has been successfully + * issued, or the appropriate error code. Note that + * the operation itself will complete asynchronously. */ PJ_DECL(pj_status_t) pj_turn_sock_set_perm(pj_turn_sock *turn_sock, - unsigned addr_cnt, - const pj_sockaddr addr[], - unsigned options); + unsigned addr_cnt, + const pj_sockaddr addr[], + unsigned options); /** * Send a data to the specified peer address via the TURN relay. This @@ -584,24 +583,24 @@ PJ_DECL(pj_status_t) pj_turn_sock_set_perm(pj_turn_sock *turn_sock, * The allocation (pj_turn_sock_alloc()) must have been successfully * created before application can relay any data. * - * @param turn_sock The TURN transport instance. - * @param pkt The data/packet to be sent to peer. - * @param pkt_len Length of the data. - * @param peer_addr The remote peer address (the ultimate destination - * of the data, and not the TURN server address). - * @param addr_len Length of the address. - * - * @return PJ_SUCCESS if data has been sent immediately, or - * PJ_EPENDING if data cannot be sent immediately. In - * this case the \a on_data_sent() callback will be - * called when data is actually sent. Any other return - * value indicates error condition. + * @param turn_sock The TURN transport instance. + * @param pkt The data/packet to be sent to peer. + * @param pkt_len Length of the data. + * @param peer_addr The remote peer address (the ultimate destination + * of the data, and not the TURN server address). + * @param addr_len Length of the address. + * + * @return PJ_SUCCESS if data has been sent immediately, or + * PJ_EPENDING if data cannot be sent immediately. In + * this case the \a on_data_sent() callback will be + * called when data is actually sent. Any other return + * value indicates error condition. */ PJ_DECL(pj_status_t) pj_turn_sock_sendto(pj_turn_sock *turn_sock, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); /** * Optionally establish channel binding for the specified a peer address. @@ -612,16 +611,16 @@ PJ_DECL(pj_status_t) pj_turn_sock_sendto(pj_turn_sock *turn_sock, * lower bandwidth overhead than Send Indication (the default format used * when peer address is not bound to a channel). * - * @param turn_sock The TURN transport instance. - * @param peer The remote peer address. - * @param addr_len Length of the address. + * @param turn_sock The TURN transport instance. + * @param peer The remote peer address. + * @param addr_len Length of the address. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_sock_bind_channel(pj_turn_sock *turn_sock, - const pj_sockaddr_t *peer, - unsigned addr_len); + const pj_sockaddr_t *peer, + unsigned addr_len); /** * Initiate connection to the specified peer using Connect request. * Application must call this function when it uses RFC 6062 (TURN TCP @@ -634,31 +633,31 @@ PJ_DECL(pj_status_t) pj_turn_sock_bind_channel(pj_turn_sock *turn_sock, * parameter peer_conn_type to PJ_TURN_TP_TCP) before calling this function. * * - * @param turn_sock The TURN transport instance. - * @param peer The remote peer address. - * @param addr_len Length of the address. + * @param turn_sock The TURN transport instance. + * @param peer The remote peer address. + * @param addr_len Length of the address. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_sock_connect(pj_turn_sock *turn_sock, - const pj_sockaddr_t *peer, - unsigned addr_len); + const pj_sockaddr_t *peer, + unsigned addr_len); /** * Close previous TCP data connection for the specified peer. * According to RFC 6062, when the client wishes to terminate its relayed * connection to the peer, it closes the data connection to the server. * - * @param turn_sock The TURN transport instance. - * @param peer The remote peer address. - * @param addr_len Length of the address. + * @param turn_sock The TURN transport instance. + * @param peer The remote peer address. + * @param addr_len Length of the address. * - * @return PJ_SUCCESS if the operation has been successful, - * or the appropriate error code on failure. + * @return PJ_SUCCESS if the operation has been successful, + * or the appropriate error code on failure. */ PJ_DECL(pj_status_t) pj_turn_sock_disconnect(pj_turn_sock *turn_sock, - const pj_sockaddr_t *peer, - unsigned addr_len); + const pj_sockaddr_t *peer, + unsigned addr_len); /** @@ -669,5 +668,5 @@ PJ_DECL(pj_status_t) pj_turn_sock_disconnect(pj_turn_sock *turn_sock, PJ_END_DECL -#endif /* __PJNATH_TURN_SOCK_H__ */ +#endif /* __PJNATH_TURN_SOCK_H__ */ diff --git a/pjnath/include/pjnath/types.h b/pjnath/include/pjnath/types.h index 1ac627670a..49612f8bd9 100644 --- a/pjnath/include/pjnath/types.h +++ b/pjnath/include/pjnath/types.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,13 +38,13 @@ PJ_BEGIN_DECL * This constant describes a number to be used to identify an invalid TURN * channel number. */ -#define PJ_TURN_INVALID_CHANNEL 0xFFFF +#define PJ_TURN_INVALID_CHANNEL 0xFFFF /** * Initialize pjnath library. * - * @return Initialization status. + * @return Initialization status. */ PJ_DECL(pj_status_t) pjnath_init(void); @@ -54,12 +53,12 @@ PJ_DECL(pj_status_t) pjnath_init(void); * Display error to the log. * * @param sender The sender name. - * @param title Title message. + * @param title Title message. * @param status The error status. */ #if PJNATH_ERROR_LEVEL <= PJ_LOG_MAX_LEVEL PJ_DECL(void) pjnath_perror(const char *sender, const char *title, - pj_status_t status); + pj_status_t status); #else # define pjnath_perror(sender, title, status) #endif @@ -72,5 +71,5 @@ PJ_END_DECL * @} */ -#endif /* __PJNATH_TYPES_H__ */ +#endif /* __PJNATH_TYPES_H__ */ diff --git a/pjnath/include/pjnath/upnp.h b/pjnath/include/pjnath/upnp.h index 45b9ae20a7..7cd4b012f5 100644 --- a/pjnath/include/pjnath/upnp.h +++ b/pjnath/include/pjnath/upnp.h @@ -54,29 +54,29 @@ typedef struct pj_upnp_init_param * * If NULL, the library will use the first suitable interface found. */ - const char *if_name; + const char *if_name; /** * The port number to use for all UPnP operations. * * If 0, the library will pick an arbitrary free port. */ - unsigned port; + unsigned port; /** * The time duration to search for IGD devices (in seconds). * * If 0, the library will use PJ_UPNP_DEFAULT_SEARCH_TIME. */ - int search_time; + int search_time; /** * The callback to notify application when the initialization * has completed. * - * @param status The initialization status. + * @param status The initialization status. */ - void (*upnp_cb)(pj_status_t status); + void (*upnp_cb)(pj_status_t status); } pj_upnp_init_param; @@ -86,10 +86,10 @@ typedef struct pj_upnp_init_param * Initialize UPnP library and initiate the search for valid Internet * Gateway Devices (IGD) in the network. * - * @param param The UPnP initialization parameter. + * @param param The UPnP initialization parameter. * - * @return PJ_SUCCESS on success, or the appropriate error - * status. + * @return PJ_SUCCESS on success, or the appropriate error + * status. */ PJ_DECL(pj_status_t) pj_upnp_init(const pj_upnp_init_param *param); @@ -97,8 +97,8 @@ PJ_DECL(pj_status_t) pj_upnp_init(const pj_upnp_init_param *param); /** * Deinitialize UPnP library. * - * @return PJ_SUCCESS on success, or the appropriate error - * status. + * @return PJ_SUCCESS on success, or the appropriate error + * status. */ PJ_DECL(pj_status_t) pj_upnp_deinit(void); @@ -108,32 +108,32 @@ PJ_DECL(pj_status_t) pj_upnp_deinit(void); * the Internet Gateway Device will redirect communication received on * the specified external ports to the local sockets. * - * @param sock_cnt Number of sockets in the socket array. - * @param sock Array of local UDP sockets that will be mapped. - * @param ext_port (Optional) Array of external port numbers. If NULL, - * the external port numbers requested will be identical - * to the sockets' local port numbers. - * @param mapped_addr Array to receive the mapped public addresses and - * ports of the local UDP sockets, when the function - * returns PJ_SUCCESS. + * @param sock_cnt Number of sockets in the socket array. + * @param sock Array of local UDP sockets that will be mapped. + * @param ext_port (Optional) Array of external port numbers. If NULL, + * the external port numbers requested will be identical + * to the sockets' local port numbers. + * @param mapped_addr Array to receive the mapped public addresses and + * ports of the local UDP sockets, when the function + * returns PJ_SUCCESS. * - * @return PJ_SUCCESS on success, or the appropriate error - * status. + * @return PJ_SUCCESS on success, or the appropriate error + * status. */ PJ_DECL(pj_status_t)pj_upnp_add_port_mapping(unsigned sock_cnt, - const pj_sock_t sock[], - unsigned ext_port[], - pj_sockaddr mapped_addr[]); + const pj_sock_t sock[], + unsigned ext_port[], + pj_sockaddr mapped_addr[]); /** * Send request to delete a port mapping. * - * @param mapped_addr The public address and external port mapping to - * be deleted. + * @param mapped_addr The public address and external port mapping to + * be deleted. * - * @return PJ_SUCCESS on success, or the appropriate error - * status. + * @return PJ_SUCCESS on success, or the appropriate error + * status. */ PJ_DECL(pj_status_t)pj_upnp_del_port_mapping(const pj_sockaddr *mapped_addr); @@ -144,4 +144,4 @@ PJ_END_DECL * @} */ -#endif /* __PJ_UPNP_H__ */ +#endif /* __PJ_UPNP_H__ */ diff --git a/pjnath/src/pjnath-test/concur_test.c b/pjnath/src/pjnath-test/concur_test.c index d9076c0867..9b377d0e25 100644 --- a/pjnath/src/pjnath-test/concur_test.c +++ b/pjnath/src/pjnath-test/concur_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,36 +20,36 @@ #if INCLUDE_CONCUR_TEST -#define THIS_FILE "concur_test.c" +#define THIS_FILE "concur_test.c" /****************************************************************************/ -#define WORKER_THREAD_CNT 4 -#define SERVER_THREAD_CNT 4 -#define MAX_SOCK_CLIENTS (PJ_IOQUEUE_MAX_HANDLES/2) +#define WORKER_THREAD_CNT 4 +#define SERVER_THREAD_CNT 4 +#define MAX_SOCK_CLIENTS (PJ_IOQUEUE_MAX_HANDLES/2) struct stun_test_session { - pj_stun_config stun_cfg; + pj_stun_config stun_cfg; - pj_lock_t *lock; + pj_lock_t *lock; - pj_thread_t *worker_threads[WORKER_THREAD_CNT]; + pj_thread_t *worker_threads[WORKER_THREAD_CNT]; - pj_sock_t server_sock; - int server_port; - pj_thread_t *server_threads[SERVER_THREAD_CNT]; - pj_event_t *server_event; + pj_sock_t server_sock; + int server_port; + pj_thread_t *server_threads[SERVER_THREAD_CNT]; + pj_event_t *server_event; - pj_bool_t thread_quit_flag; + pj_bool_t thread_quit_flag; /* Test parameters: */ struct { - int client_got_response; + int client_got_response; - pj_bool_t server_wait_for_event; - pj_bool_t server_drop_request; - int client_sleep_after_start; - int client_sleep_before_destroy; + pj_bool_t server_wait_for_event; + pj_bool_t server_drop_request; + int client_sleep_after_start; + int client_sleep_before_destroy; } param; }; @@ -65,70 +64,70 @@ static int server_thread_proc(void *p) pool = pj_pool_create(test_sess->stun_cfg.pf, "server", 512, 512, NULL); while (!test_sess->thread_quit_flag) { - pj_time_val timeout = {0, 10}; - pj_fd_set_t rdset; - int n; - - /* Serve client */ - PJ_FD_ZERO(&rdset); - PJ_FD_SET(test_sess->server_sock, &rdset); - n = pj_sock_select((int)test_sess->server_sock+1, &rdset, - NULL, NULL, &timeout); - if (n==1 && PJ_FD_ISSET(test_sess->server_sock, &rdset)) { - pj_uint8_t pkt[512]; - pj_ssize_t pkt_len; - pj_size_t res_len; - pj_sockaddr client_addr; - int addr_len; - - pj_stun_msg *stun_req, *stun_res; - - pj_pool_reset(pool); - - /* Got query */ - pkt_len = sizeof(pkt); - addr_len = sizeof(client_addr); - status = pj_sock_recvfrom(test_sess->server_sock, pkt, &pkt_len, - 0, &client_addr, &addr_len); - if (status != PJ_SUCCESS) { - continue; - } - - status = pj_stun_msg_decode(pool, pkt, pkt_len, - PJ_STUN_IS_DATAGRAM, - &stun_req, NULL, NULL); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "STUN request decode error")); - continue; - } - - status = pj_stun_msg_create_response(pool, stun_req, - PJ_STUN_SC_BAD_REQUEST, NULL, - &stun_res); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "STUN create response error")); - continue; - } - - status = pj_stun_msg_encode(stun_res, pkt, sizeof(pkt), 0, - NULL, &res_len); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "STUN encode error")); - continue; - } - - /* Ignore request */ - if (test_sess->param.server_drop_request) - continue; - - /* Wait for signal to continue */ - if (test_sess->param.server_wait_for_event) - pj_event_wait(test_sess->server_event); - - pkt_len = res_len; - pj_sock_sendto(test_sess->server_sock, pkt, &pkt_len, 0, - &client_addr, pj_sockaddr_get_len(&client_addr)); - } + pj_time_val timeout = {0, 10}; + pj_fd_set_t rdset; + int n; + + /* Serve client */ + PJ_FD_ZERO(&rdset); + PJ_FD_SET(test_sess->server_sock, &rdset); + n = pj_sock_select((int)test_sess->server_sock+1, &rdset, + NULL, NULL, &timeout); + if (n==1 && PJ_FD_ISSET(test_sess->server_sock, &rdset)) { + pj_uint8_t pkt[512]; + pj_ssize_t pkt_len; + pj_size_t res_len; + pj_sockaddr client_addr; + int addr_len; + + pj_stun_msg *stun_req, *stun_res; + + pj_pool_reset(pool); + + /* Got query */ + pkt_len = sizeof(pkt); + addr_len = sizeof(client_addr); + status = pj_sock_recvfrom(test_sess->server_sock, pkt, &pkt_len, + 0, &client_addr, &addr_len); + if (status != PJ_SUCCESS) { + continue; + } + + status = pj_stun_msg_decode(pool, pkt, pkt_len, + PJ_STUN_IS_DATAGRAM, + &stun_req, NULL, NULL); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, "STUN request decode error")); + continue; + } + + status = pj_stun_msg_create_response(pool, stun_req, + PJ_STUN_SC_BAD_REQUEST, NULL, + &stun_res); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, "STUN create response error")); + continue; + } + + status = pj_stun_msg_encode(stun_res, pkt, sizeof(pkt), 0, + NULL, &res_len); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, "STUN encode error")); + continue; + } + + /* Ignore request */ + if (test_sess->param.server_drop_request) + continue; + + /* Wait for signal to continue */ + if (test_sess->param.server_wait_for_event) + pj_event_wait(test_sess->server_event); + + pkt_len = res_len; + pj_sock_sendto(test_sess->server_sock, pkt, &pkt_len, 0, + &client_addr, pj_sockaddr_get_len(&client_addr)); + } } pj_pool_release(pool); @@ -144,9 +143,9 @@ static int worker_thread_proc(void *p) PJ_LOG(4,(THIS_FILE, "Worker thread running")); while (!test_sess->thread_quit_flag) { - pj_time_val timeout = {0, 10}; - pj_timer_heap_poll(test_sess->stun_cfg.timer_heap, NULL); - pj_ioqueue_poll(test_sess->stun_cfg.ioqueue, &timeout); + pj_time_val timeout = {0, 10}; + pj_timer_heap_poll(test_sess->stun_cfg.timer_heap, NULL); + pj_ioqueue_poll(test_sess->stun_cfg.ioqueue, &timeout); } PJ_LOG(4,(THIS_FILE, "Worker thread quitting")); @@ -181,26 +180,26 @@ static int stun_destroy_test_session(struct stun_test_session *test_sess) /* Create all clients first */ for (i=0; istun_cfg, name, pj_AF_INET(), - &stun_cb, NULL, test_sess, - &stun_sock[i]); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "Error creating stun socket")); - return -10; - } + char name[10]; + sprintf(name, "stun%02d", i); + status = pj_stun_sock_create(&test_sess->stun_cfg, name, pj_AF_INET(), + &stun_cb, NULL, test_sess, + &stun_sock[i]); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, "Error creating stun socket")); + return -10; + } } /* Start resolution */ for (i=0; iserver_port, NULL); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "Error starting stun socket")); - return -20; - } + pj_str_t server_ip = pj_str("127.0.0.1"); + status = pj_stun_sock_start(stun_sock[i], &server_ip, + (pj_uint16_t)test_sess->server_port, NULL); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, "Error starting stun socket")); + return -20; + } } /* settle down */ @@ -213,10 +212,10 @@ static int stun_destroy_test_session(struct stun_test_session *test_sess) /* Destroy clients */ for (i=0; i @@ -22,113 +21,113 @@ enum { - NO = 0, - YES = 1, - SRV = 3, + NO = 0, + YES = 1, + SRV = 3, }; -#define NODELAY 0xFFFFFFFF -#define SRV_DOMAIN "pjsip.lab.domain" -#define MAX_THREADS 16 +#define NODELAY 0xFFFFFFFF +#define SRV_DOMAIN "pjsip.lab.domain" +#define MAX_THREADS 16 -#define THIS_FILE "ice_test.c" -#define INDENT " " +#define THIS_FILE "ice_test.c" +#define INDENT " " /* Client flags */ enum { - WRONG_TURN = 1, - DEL_ON_ERR = 2, - CLIENT_IPV4 = 4, - CLIENT_IPV6 = 8 + WRONG_TURN = 1, + DEL_ON_ERR = 2, + CLIENT_IPV4 = 4, + CLIENT_IPV6 = 8 }; /* Test results */ struct test_result { - pj_status_t start_status; /* start ice successful? */ - pj_status_t init_status; /* init successful? */ - pj_status_t nego_status; /* negotiation successful? */ - unsigned rx_cnt[4]; /* Number of data received */ + pj_status_t start_status; /* start ice successful? */ + pj_status_t init_status; /* init successful? */ + pj_status_t nego_status; /* negotiation successful? */ + unsigned rx_cnt[4]; /* Number of data received */ }; /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ /* Test session configuration */ struct test_cfg { - pj_ice_sess_role role; /* Role. */ - unsigned comp_cnt; /* Component count */ - unsigned enable_host; /* Enable host candidates */ - unsigned enable_stun; /* Enable srflx candidates */ - unsigned enable_turn; /* Enable turn candidates */ - unsigned client_flag; /* Client flags */ + pj_ice_sess_role role; /* Role. */ + unsigned comp_cnt; /* Component count */ + unsigned enable_host; /* Enable host candidates */ + unsigned enable_stun; /* Enable srflx candidates */ + unsigned enable_turn; /* Enable turn candidates */ + unsigned client_flag; /* Client flags */ - unsigned answer_delay; /* Delay before sending SDP */ - unsigned send_delay; /* unused */ - unsigned destroy_delay; /* unused */ + unsigned answer_delay; /* Delay before sending SDP */ + unsigned send_delay; /* unused */ + unsigned destroy_delay; /* unused */ - struct test_result expected;/* Expected result */ + struct test_result expected;/* Expected result */ - pj_bool_t nom_regular; /* Use regular nomination? */ - pj_ice_sess_trickle trickle; /* Trickle ICE mode */ + pj_bool_t nom_regular; /* Use regular nomination? */ + pj_ice_sess_trickle trickle; /* Trickle ICE mode */ }; /* ICE endpoint state */ struct ice_ept { - struct test_cfg cfg; /* Configuratino. */ - pj_ice_strans *ice; /* ICE stream transport */ - struct test_result result;/* Test result. */ + struct test_cfg cfg; /* Configuratino. */ + pj_ice_strans *ice; /* ICE stream transport */ + struct test_result result;/* Test result. */ - pj_str_t ufrag; /* username fragment. */ - pj_str_t pass; /* password */ + pj_str_t ufrag; /* username fragment. */ + pj_str_t pass; /* password */ /* Trickle ICE */ - pj_bool_t last_cand; /* Got last candidate? */ + pj_bool_t last_cand; /* Got last candidate? */ }; /* Session param */ struct sess_param { - unsigned worker_cnt; - unsigned worker_timeout; - pj_bool_t worker_quit; + unsigned worker_cnt; + unsigned worker_timeout; + pj_bool_t worker_quit; - pj_bool_t destroy_after_create; - pj_bool_t destroy_after_one_done; + pj_bool_t destroy_after_create; + pj_bool_t destroy_after_one_done; }; /* The test session */ struct test_sess { - pj_pool_t *pool; - pj_stun_config *stun_cfg; - pj_dns_resolver *resolver; + pj_pool_t *pool; + pj_stun_config *stun_cfg; + pj_dns_resolver *resolver; - struct sess_param *param; + struct sess_param *param; - test_server *server1; /* Test server for IPv4. */ - test_server *server2; /* Test server for IPv6. */ + test_server *server1; /* Test server for IPv4. */ + test_server *server2; /* Test server for IPv6. */ - pj_thread_t *worker_threads[MAX_THREADS]; + pj_thread_t *worker_threads[MAX_THREADS]; - unsigned server_flag; - struct ice_ept caller; - struct ice_ept callee; + unsigned server_flag; + struct ice_ept caller; + struct ice_ept callee; }; static void ice_on_rx_data(pj_ice_strans *ice_st, - unsigned comp_id, - void *pkt, pj_size_t size, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + unsigned comp_id, + void *pkt, pj_size_t size, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); static void ice_on_ice_complete(pj_ice_strans *ice_st, - pj_ice_strans_op op, - pj_status_t status); + pj_ice_strans_op op, + pj_status_t status); static void ice_on_new_candidate(pj_ice_strans *ice_st, - const pj_ice_sess_cand *cand, - pj_bool_t last); + const pj_ice_sess_cand *cand, + pj_bool_t last); static void destroy_sess(struct test_sess *sess, unsigned wait_msec); @@ -139,16 +138,16 @@ static pj_bool_t enable_ipv6_test() pj_sockaddr addr; pj_bool_t retval = PJ_TRUE; if (pj_gethostip(pj_AF_INET6(), &addr) == PJ_SUCCESS) { - const pj_in6_addr *a = &addr.ipv6.sin6_addr; - if (a->s6_addr[0] == 0xFE && (a->s6_addr[1] & 0xC0) == 0x80) { - retval = PJ_FALSE; - PJ_LOG(3,(THIS_FILE, INDENT "Skipping IPv6 test due to link-local " - "address")); - } + const pj_in6_addr *a = &addr.ipv6.sin6_addr; + if (a->s6_addr[0] == 0xFE && (a->s6_addr[1] & 0xC0) == 0x80) { + retval = PJ_FALSE; + PJ_LOG(3,(THIS_FILE, INDENT "Skipping IPv6 test due to link-local " + "address")); + } } else { - retval = PJ_FALSE; - PJ_LOG(3,(THIS_FILE, INDENT "Skipping IPv6 test due to fail getting " - "IPv6 address")); + retval = PJ_FALSE; + PJ_LOG(3,(THIS_FILE, INDENT "Skipping IPv6 test due to fail getting " + "IPv6 address")); } return retval; } @@ -156,65 +155,65 @@ static pj_bool_t enable_ipv6_test() #endif static void set_stun_turn_cfg(struct ice_ept *ept, - pj_ice_strans_cfg *ice_cfg, - char *serverip, - pj_bool_t use_ipv6) + pj_ice_strans_cfg *ice_cfg, + char *serverip, + pj_bool_t use_ipv6) { if (ept->cfg.enable_stun & YES) { - unsigned stun_idx = ice_cfg->stun_tp_cnt++; - pj_ice_strans_stun_cfg_default(&ice_cfg->stun_tp[stun_idx]); + unsigned stun_idx = ice_cfg->stun_tp_cnt++; + pj_ice_strans_stun_cfg_default(&ice_cfg->stun_tp[stun_idx]); - if ((ept->cfg.enable_stun & SRV) == SRV) { - ice_cfg->stun_tp[stun_idx].server = pj_str(SRV_DOMAIN); - } else { - ice_cfg->stun_tp[stun_idx].server = pj_str(serverip); - } - ice_cfg->stun_tp[stun_idx].port = STUN_SERVER_PORT; + if ((ept->cfg.enable_stun & SRV) == SRV) { + ice_cfg->stun_tp[stun_idx].server = pj_str(SRV_DOMAIN); + } else { + ice_cfg->stun_tp[stun_idx].server = pj_str(serverip); + } + ice_cfg->stun_tp[stun_idx].port = STUN_SERVER_PORT; - ice_cfg->stun_tp[stun_idx].af = GET_AF(use_ipv6); + ice_cfg->stun_tp[stun_idx].af = GET_AF(use_ipv6); } ice_cfg->stun.af = GET_AF(use_ipv6); - if (ept->cfg.enable_host == 0) { - ice_cfg->stun.max_host_cands = 0; + if (ept->cfg.enable_host == 0) { + ice_cfg->stun.max_host_cands = 0; } else { - //ice_cfg.stun.no_host_cands = PJ_FALSE; - ice_cfg->stun.loop_addr = PJ_TRUE; + //ice_cfg.stun.no_host_cands = PJ_FALSE; + ice_cfg->stun.loop_addr = PJ_TRUE; } if (ept->cfg.enable_turn & YES) { - unsigned turn_idx = ice_cfg->turn_tp_cnt++; - pj_ice_strans_turn_cfg_default(&ice_cfg->turn_tp[turn_idx]); - - if ((ept->cfg.enable_turn & SRV) == SRV) { - ice_cfg->turn_tp[turn_idx].server = pj_str(SRV_DOMAIN); - } else { - ice_cfg->turn_tp[turn_idx].server = pj_str(serverip); - } - ice_cfg->turn_tp[turn_idx].port = TURN_SERVER_PORT; - ice_cfg->turn_tp[turn_idx].conn_type = PJ_TURN_TP_UDP; - ice_cfg->turn_tp[turn_idx].auth_cred.type = PJ_STUN_AUTH_CRED_STATIC; - ice_cfg->turn_tp[turn_idx].auth_cred.data.static_cred.realm = - pj_str(SRV_DOMAIN); - if (ept->cfg.client_flag & WRONG_TURN) - ice_cfg->turn_tp[turn_idx].auth_cred.data.static_cred.username = - pj_str("xxx"); - else - ice_cfg->turn_tp[turn_idx].auth_cred.data.static_cred.username = - pj_str(TURN_USERNAME); - - ice_cfg->turn_tp[turn_idx].auth_cred.data.static_cred.data_type = - PJ_STUN_PASSWD_PLAIN; - ice_cfg->turn_tp[turn_idx].auth_cred.data.static_cred.data = - pj_str(TURN_PASSWD); - - ice_cfg->turn_tp[turn_idx].af = GET_AF(use_ipv6); + unsigned turn_idx = ice_cfg->turn_tp_cnt++; + pj_ice_strans_turn_cfg_default(&ice_cfg->turn_tp[turn_idx]); + + if ((ept->cfg.enable_turn & SRV) == SRV) { + ice_cfg->turn_tp[turn_idx].server = pj_str(SRV_DOMAIN); + } else { + ice_cfg->turn_tp[turn_idx].server = pj_str(serverip); + } + ice_cfg->turn_tp[turn_idx].port = TURN_SERVER_PORT; + ice_cfg->turn_tp[turn_idx].conn_type = PJ_TURN_TP_UDP; + ice_cfg->turn_tp[turn_idx].auth_cred.type = PJ_STUN_AUTH_CRED_STATIC; + ice_cfg->turn_tp[turn_idx].auth_cred.data.static_cred.realm = + pj_str(SRV_DOMAIN); + if (ept->cfg.client_flag & WRONG_TURN) + ice_cfg->turn_tp[turn_idx].auth_cred.data.static_cred.username = + pj_str("xxx"); + else + ice_cfg->turn_tp[turn_idx].auth_cred.data.static_cred.username = + pj_str(TURN_USERNAME); + + ice_cfg->turn_tp[turn_idx].auth_cred.data.static_cred.data_type = + PJ_STUN_PASSWD_PLAIN; + ice_cfg->turn_tp[turn_idx].auth_cred.data.static_cred.data = + pj_str(TURN_PASSWD); + + ice_cfg->turn_tp[turn_idx].af = GET_AF(use_ipv6); } } /* Create ICE stream transport */ static int create_ice_strans(struct test_sess *test_sess, - struct ice_ept *ept, - pj_ice_strans **p_ice) + struct ice_ept *ept, + pj_ice_strans **p_ice) { pj_ice_strans *ice; pj_ice_strans_cb ice_cb; @@ -227,16 +226,16 @@ static int create_ice_strans(struct test_sess *test_sess, status = pj_gethostip(pj_AF_INET(), &hostip); if (status != PJ_SUCCESS) - return -1030; + return -1030; pj_sockaddr_print(&hostip, serveripv4, sizeof(serveripv4), 0); if (flag & CLIENT_IPV6) { - status = pj_gethostip(pj_AF_INET6(), &hostip); - if (status != PJ_SUCCESS) - return -1031; + status = pj_gethostip(pj_AF_INET6(), &hostip); + if (status != PJ_SUCCESS) + return -1031; - pj_sockaddr_print(&hostip, serveripv6, sizeof(serveripv6), 0); + pj_sockaddr_print(&hostip, serveripv6, sizeof(serveripv6), 0); } /* Init callback structure */ @@ -250,23 +249,23 @@ static int create_ice_strans(struct test_sess *test_sess, ice_cfg.opt.trickle = ept->cfg.trickle; pj_memcpy(&ice_cfg.stun_cfg, test_sess->stun_cfg, sizeof(pj_stun_config)); if ((ept->cfg.enable_stun & SRV)==SRV || (ept->cfg.enable_turn & SRV)==SRV) - ice_cfg.resolver = test_sess->resolver; + ice_cfg.resolver = test_sess->resolver; if (flag & CLIENT_IPV4) { - set_stun_turn_cfg(ept, &ice_cfg, serveripv4, PJ_FALSE); + set_stun_turn_cfg(ept, &ice_cfg, serveripv4, PJ_FALSE); } if (flag & CLIENT_IPV6) { - set_stun_turn_cfg(ept, &ice_cfg, serveripv6, PJ_TRUE); + set_stun_turn_cfg(ept, &ice_cfg, serveripv6, PJ_TRUE); } /* Create ICE stream transport */ status = pj_ice_strans_create(NULL, &ice_cfg, ept->cfg.comp_cnt, - (void*)ept, &ice_cb, - &ice); + (void*)ept, &ice_cb, + &ice); if (status != PJ_SUCCESS) { - app_perror(INDENT "err: pj_ice_strans_create()", status); - return status; + app_perror(INDENT "err: pj_ice_strans_create()", status); + return status; } pj_create_unique_string(test_sess->pool, &ept->ufrag); @@ -279,11 +278,11 @@ static int create_ice_strans(struct test_sess *test_sess, /* Create test session */ static int create_sess(pj_stun_config *stun_cfg, - unsigned server_flag, - struct test_cfg *caller_cfg, - struct test_cfg *callee_cfg, - struct sess_param *test_param, - struct test_sess **p_sess) + unsigned server_flag, + struct test_cfg *caller_cfg, + struct test_cfg *callee_cfg, + struct sess_param *test_param, + struct test_sess **p_sess) { pj_pool_t *pool; struct test_sess *sess; @@ -308,66 +307,66 @@ static int create_sess(pj_stun_config *stun_cfg, /* Create server */ flags = server_flag; if (flags & SERVER_IPV4) { - status = create_test_server(stun_cfg, (flags & ~SERVER_IPV6), - SRV_DOMAIN, &sess->server1); + status = create_test_server(stun_cfg, (flags & ~SERVER_IPV6), + SRV_DOMAIN, &sess->server1); } if ((status == PJ_SUCCESS) && (flags & SERVER_IPV6)) { - status = create_test_server(stun_cfg, (flags & ~SERVER_IPV4), - SRV_DOMAIN, &sess->server2); + status = create_test_server(stun_cfg, (flags & ~SERVER_IPV4), + SRV_DOMAIN, &sess->server2); } if (status != PJ_SUCCESS) { - app_perror(INDENT "error: create_test_server()", status); - destroy_sess(sess, 500); - return -10; + app_perror(INDENT "error: create_test_server()", status); + destroy_sess(sess, 500); + return -10; } if (flags & SERVER_IPV4) { - sess->server1->turn_respond_allocate = - sess->server1->turn_respond_refresh = PJ_TRUE; + sess->server1->turn_respond_allocate = + sess->server1->turn_respond_refresh = PJ_TRUE; } if (flags & SERVER_IPV6) { - sess->server2->turn_respond_allocate = - sess->server2->turn_respond_refresh = PJ_TRUE; + sess->server2->turn_respond_allocate = + sess->server2->turn_respond_refresh = PJ_TRUE; } /* Create resolver */ if ((sess->callee.cfg.enable_stun & SRV)==SRV || - (sess->callee.cfg.enable_turn & SRV)==SRV || - (sess->caller.cfg.enable_stun & SRV)==SRV || - (sess->caller.cfg.enable_turn & SRV)==SRV) + (sess->callee.cfg.enable_turn & SRV)==SRV || + (sess->caller.cfg.enable_stun & SRV)==SRV || + (sess->caller.cfg.enable_turn & SRV)==SRV) { - status = pj_dns_resolver_create(mem, NULL, 0, stun_cfg->timer_heap, - stun_cfg->ioqueue, &sess->resolver); - if (status != PJ_SUCCESS) { - app_perror(INDENT "error: pj_dns_resolver_create()", status); - destroy_sess(sess, 500); - return -20; - } - - ns_ip = (flags & SERVER_IPV6)?pj_str("::1"):pj_str("127.0.0.1"); - ns_port = (pj_uint16_t)DNS_SERVER_PORT; - status = pj_dns_resolver_set_ns(sess->resolver, 1, &ns_ip, &ns_port); - if (status != PJ_SUCCESS) { - app_perror(INDENT "error: pj_dns_resolver_set_ns()", status); - destroy_sess(sess, 500); - return -21; - } + status = pj_dns_resolver_create(mem, NULL, 0, stun_cfg->timer_heap, + stun_cfg->ioqueue, &sess->resolver); + if (status != PJ_SUCCESS) { + app_perror(INDENT "error: pj_dns_resolver_create()", status); + destroy_sess(sess, 500); + return -20; + } + + ns_ip = (flags & SERVER_IPV6)?pj_str("::1"):pj_str("127.0.0.1"); + ns_port = (pj_uint16_t)DNS_SERVER_PORT; + status = pj_dns_resolver_set_ns(sess->resolver, 1, &ns_ip, &ns_port); + if (status != PJ_SUCCESS) { + app_perror(INDENT "error: pj_dns_resolver_set_ns()", status); + destroy_sess(sess, 500); + return -21; + } } /* Create caller ICE stream transport */ status = create_ice_strans(sess, &sess->caller, &sess->caller.ice); if (status != PJ_SUCCESS) { - destroy_sess(sess, 500); - return -30; + destroy_sess(sess, 500); + return -30; } /* Create callee ICE stream transport */ status = create_ice_strans(sess, &sess->callee, &sess->callee.ice); if (status != PJ_SUCCESS) { - destroy_sess(sess, 500); - return -40; + destroy_sess(sess, 500); + return -40; } *p_sess = sess; @@ -380,46 +379,46 @@ static void destroy_sess(struct test_sess *sess, unsigned wait_msec) unsigned i; if (sess->caller.ice) { - pj_ice_strans_destroy(sess->caller.ice); - sess->caller.ice = NULL; + pj_ice_strans_destroy(sess->caller.ice); + sess->caller.ice = NULL; } if (sess->callee.ice) { - pj_ice_strans_destroy(sess->callee.ice); - sess->callee.ice = NULL; + pj_ice_strans_destroy(sess->callee.ice); + sess->callee.ice = NULL; } sess->param->worker_quit = PJ_TRUE; for (i=0; iparam->worker_cnt; ++i) { - if (sess->worker_threads[i]) - pj_thread_join(sess->worker_threads[i]); + if (sess->worker_threads[i]) + pj_thread_join(sess->worker_threads[i]); } poll_events(sess->stun_cfg, wait_msec, PJ_FALSE); if (sess->resolver) { - pj_dns_resolver_destroy(sess->resolver, PJ_FALSE); - sess->resolver = NULL; + pj_dns_resolver_destroy(sess->resolver, PJ_FALSE); + sess->resolver = NULL; } if (sess->server1) { - destroy_test_server(sess->server1); - sess->server1 = NULL; + destroy_test_server(sess->server1); + sess->server1 = NULL; } if (sess->server2) { - destroy_test_server(sess->server2); - sess->server2 = NULL; + destroy_test_server(sess->server2); + sess->server2 = NULL; } pj_pool_safe_release(&sess->pool); } static void ice_on_rx_data(pj_ice_strans *ice_st, - unsigned comp_id, - void *pkt, pj_size_t size, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + unsigned comp_id, + void *pkt, pj_size_t size, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { struct ice_ept *ept; @@ -434,37 +433,37 @@ static void ice_on_rx_data(pj_ice_strans *ice_st, static void ice_on_ice_complete(pj_ice_strans *ice_st, - pj_ice_strans_op op, - pj_status_t status) + pj_ice_strans_op op, + pj_status_t status) { struct ice_ept *ept; ept = (struct ice_ept*) pj_ice_strans_get_user_data(ice_st); if (!ept) - return; + return; switch (op) { case PJ_ICE_STRANS_OP_INIT: - ept->result.init_status = status; - if (status != PJ_SUCCESS && (ept->cfg.client_flag & DEL_ON_ERR)) { - pj_ice_strans_destroy(ice_st); - ept->ice = NULL; - } - break; + ept->result.init_status = status; + if (status != PJ_SUCCESS && (ept->cfg.client_flag & DEL_ON_ERR)) { + pj_ice_strans_destroy(ice_st); + ept->ice = NULL; + } + break; case PJ_ICE_STRANS_OP_NEGOTIATION: - ept->result.nego_status = status; - break; + ept->result.nego_status = status; + break; case PJ_ICE_STRANS_OP_KEEP_ALIVE: - /* keep alive failed? */ - break; + /* keep alive failed? */ + break; default: - pj_assert(!"Unknown op"); + pj_assert(!"Unknown op"); } } static void ice_on_new_candidate(pj_ice_strans *ice_st, - const pj_ice_sess_cand *cand, - pj_bool_t last) + const pj_ice_sess_cand *cand, + pj_bool_t last) { struct ice_ept *ept; char buf1[PJ_INET6_ADDRSTRLEN+10]; @@ -472,20 +471,20 @@ static void ice_on_new_candidate(pj_ice_strans *ice_st, ept = (struct ice_ept*) pj_ice_strans_get_user_data(ice_st); if (!ept) - return; + return; ept->last_cand = last; if (cand) { - PJ_LOG(4,(THIS_FILE, INDENT "%p: discovered a new candidate " - "comp=%d, type=%s, addr=%s, baseaddr=%s, end=%d", - ept->ice, cand->comp_id, - pj_ice_get_cand_type_name(cand->type), - pj_sockaddr_print(&cand->addr, buf1, sizeof(buf1), 3), - pj_sockaddr_print(&cand->base_addr, buf2, sizeof(buf2), 3), - last)); + PJ_LOG(4,(THIS_FILE, INDENT "%p: discovered a new candidate " + "comp=%d, type=%s, addr=%s, baseaddr=%s, end=%d", + ept->ice, cand->comp_id, + pj_ice_get_cand_type_name(cand->type), + pj_sockaddr_print(&cand->addr, buf1, sizeof(buf1), 3), + pj_sockaddr_print(&cand->base_addr, buf2, sizeof(buf2), 3), + last)); } else if (ept->ice && last) { - PJ_LOG(4,(THIS_FILE, INDENT "%p: end of candidate", ept->ice)); + PJ_LOG(4,(THIS_FILE, INDENT "%p: end of candidate", ept->ice)); } } @@ -500,24 +499,24 @@ static pj_status_t start_ice(struct ice_ept *ept, const struct ice_ept *remote) /* Enum remote candidates */ if (ept->cfg.trickle == PJ_ICE_SESS_TRICKLE_DISABLED) { - unsigned i; - for (i=0; icfg.comp_cnt; ++i) { - unsigned cnt = PJ_ARRAY_SIZE(rcand) - rcand_cnt; - status = pj_ice_strans_enum_cands(remote->ice, i+1, &cnt, rcand+rcand_cnt); - if (status != PJ_SUCCESS) { - app_perror(INDENT "err: pj_ice_strans_enum_cands()", status); - return status; - } - rcand_cnt += cnt; - } + unsigned i; + for (i=0; icfg.comp_cnt; ++i) { + unsigned cnt = PJ_ARRAY_SIZE(rcand) - rcand_cnt; + status = pj_ice_strans_enum_cands(remote->ice, i+1, &cnt, rcand+rcand_cnt); + if (status != PJ_SUCCESS) { + app_perror(INDENT "err: pj_ice_strans_enum_cands()", status); + return status; + } + rcand_cnt += cnt; + } } status = pj_ice_strans_start_ice(ept->ice, &remote->ufrag, &remote->pass, - rcand_cnt, rcand); + rcand_cnt, rcand); if (status != ept->cfg.expected.start_status) { - app_perror(INDENT "err: pj_ice_strans_start_ice()", status); - return status; + app_perror(INDENT "err: pj_ice_strans_start_ice()", status); + return status; } return status; @@ -526,60 +525,60 @@ static pj_status_t start_ice(struct ice_ept *ept, const struct ice_ept *remote) /* Check that the pair in both agents are matched */ static int check_pair(const struct ice_ept *ept1, const struct ice_ept *ept2, - int start_err) + int start_err) { unsigned i, min_cnt, max_cnt; if (ept1->cfg.comp_cnt < ept2->cfg.comp_cnt) { - min_cnt = ept1->cfg.comp_cnt; - max_cnt = ept2->cfg.comp_cnt; + min_cnt = ept1->cfg.comp_cnt; + max_cnt = ept2->cfg.comp_cnt; } else { - min_cnt = ept2->cfg.comp_cnt; - max_cnt = ept1->cfg.comp_cnt; + min_cnt = ept2->cfg.comp_cnt; + max_cnt = ept1->cfg.comp_cnt; } /* Must have valid pair for common components */ for (i=0; iice, i+1); - if (c1 == NULL) { - PJ_LOG(3,(THIS_FILE, INDENT "err: unable to get valid pair for ice1 " - "component %d", i+1)); - return start_err - 2; - } - - c2 = pj_ice_strans_get_valid_pair(ept2->ice, i+1); - if (c2 == NULL) { - PJ_LOG(3,(THIS_FILE, INDENT "err: unable to get valid pair for ice2 " - "component %d", i+1)); - return start_err - 4; - } - - if (pj_sockaddr_cmp(&c1->rcand->addr, &c2->lcand->addr) != 0) { - PJ_LOG(3,(THIS_FILE, INDENT "err: candidate pair does not match " - "for component %d", i+1)); - return start_err - 6; - } + const pj_ice_sess_check *c1; + const pj_ice_sess_check *c2; + + c1 = pj_ice_strans_get_valid_pair(ept1->ice, i+1); + if (c1 == NULL) { + PJ_LOG(3,(THIS_FILE, INDENT "err: unable to get valid pair for ice1 " + "component %d", i+1)); + return start_err - 2; + } + + c2 = pj_ice_strans_get_valid_pair(ept2->ice, i+1); + if (c2 == NULL) { + PJ_LOG(3,(THIS_FILE, INDENT "err: unable to get valid pair for ice2 " + "component %d", i+1)); + return start_err - 4; + } + + if (pj_sockaddr_cmp(&c1->rcand->addr, &c2->lcand->addr) != 0) { + PJ_LOG(3,(THIS_FILE, INDENT "err: candidate pair does not match " + "for component %d", i+1)); + return start_err - 6; + } } /* Extra components must not have valid pair */ for (; icfg.comp_cnt>i && - pj_ice_strans_get_valid_pair(ept1->ice, i+1) != NULL) - { - PJ_LOG(3,(THIS_FILE, INDENT "err: ice1 shouldn't have valid pair " - "for component %d", i+1)); - return start_err - 8; - } - if (ept2->cfg.comp_cnt>i && - pj_ice_strans_get_valid_pair(ept2->ice, i+1) != NULL) - { - PJ_LOG(3,(THIS_FILE, INDENT "err: ice2 shouldn't have valid pair " - "for component %d", i+1)); - return start_err - 9; - } + if (ept1->cfg.comp_cnt>i && + pj_ice_strans_get_valid_pair(ept1->ice, i+1) != NULL) + { + PJ_LOG(3,(THIS_FILE, INDENT "err: ice1 shouldn't have valid pair " + "for component %d", i+1)); + return start_err - 8; + } + if (ept2->cfg.comp_cnt>i && + pj_ice_strans_get_valid_pair(ept2->ice, i+1) != NULL) + { + PJ_LOG(3,(THIS_FILE, INDENT "err: ice2 shouldn't have valid pair " + "for component %d", i+1)); + return start_err - 9; + } } return 0; @@ -587,21 +586,21 @@ static int check_pair(const struct ice_ept *ept1, const struct ice_ept *ept2, #define WAIT_UNTIL(timeout,expr, RC) { \ - pj_time_val t0, t; \ - pj_gettimeofday(&t0); \ - RC = -1; \ - for (;;) { \ - poll_events(stun_cfg, 10, PJ_FALSE); \ - pj_gettimeofday(&t); \ - if (expr) { \ - RC = PJ_SUCCESS; \ - break; \ - } \ - PJ_TIME_VAL_SUB(t, t0); \ - if ((unsigned)PJ_TIME_VAL_MSEC(t) >= (timeout)) \ - break; \ - } \ - } + pj_time_val t0, t; \ + pj_gettimeofday(&t0); \ + RC = -1; \ + for (;;) { \ + poll_events(stun_cfg, 10, PJ_FALSE); \ + pj_gettimeofday(&t); \ + if (expr) { \ + RC = PJ_SUCCESS; \ + break; \ + } \ + PJ_TIME_VAL_SUB(t, t0); \ + if ((unsigned)PJ_TIME_VAL_MSEC(t) >= (timeout)) \ + break; \ + } \ + } int worker_thread_proc(void *data) { @@ -611,19 +610,19 @@ int worker_thread_proc(void *data) /* Wait until negotiation is complete on both endpoints */ #define ALL_DONE (sess->param->worker_quit || \ - (sess->caller.result.nego_status!=PJ_EPENDING && \ - sess->callee.result.nego_status!=PJ_EPENDING)) + (sess->caller.result.nego_status!=PJ_EPENDING && \ + sess->callee.result.nego_status!=PJ_EPENDING)) WAIT_UNTIL(sess->param->worker_timeout, ALL_DONE, rc); PJ_UNUSED_ARG(rc); return 0; } static int perform_test2(const char *title, - pj_stun_config *stun_cfg, + pj_stun_config *stun_cfg, unsigned server_flag, - struct test_cfg *caller_cfg, - struct test_cfg *callee_cfg, - struct sess_param *test_param) + struct test_cfg *caller_cfg, + struct test_cfg *callee_cfg, + struct sess_param *test_param) { pjlib_state pjlib_state; struct test_sess *sess; @@ -632,13 +631,13 @@ static int perform_test2(const char *title, char add_title1[16]; char add_title2[16]; pj_bool_t client_mix_test = ((callee_cfg->client_flag & - (CLIENT_IPV4+CLIENT_IPV6)) != - (caller_cfg->client_flag & - (CLIENT_IPV4+CLIENT_IPV6))); + (CLIENT_IPV4+CLIENT_IPV6)) != + (caller_cfg->client_flag & + (CLIENT_IPV4+CLIENT_IPV6))); sprintf(add_title1, "%s%s%s", (server_flag & SERVER_IPV4)?"IPv4":"", - ((server_flag & SERVER_IPV4)&&(server_flag & SERVER_IPV6))?"+":"", - (server_flag & SERVER_IPV6)?"IPv6":""); + ((server_flag & SERVER_IPV4)&&(server_flag & SERVER_IPV6))?"+":"", + (server_flag & SERVER_IPV6)?"IPv6":""); sprintf(add_title2, "%s", client_mix_test?"Mix test":""); @@ -647,131 +646,131 @@ static int perform_test2(const char *title, capture_pjlib_state(stun_cfg, &pjlib_state); rc = create_sess(stun_cfg, server_flag, caller_cfg, callee_cfg, test_param, - &sess); + &sess); if (rc != 0) - return rc; + return rc; #define ALL_READY (sess->caller.result.init_status!=PJ_EPENDING && \ - sess->callee.result.init_status!=PJ_EPENDING) + sess->callee.result.init_status!=PJ_EPENDING) /* Wait until both ICE transports are initialized */ WAIT_UNTIL(30000, ALL_READY, rc); if (!ALL_READY) { - PJ_LOG(3,(THIS_FILE, INDENT "err: init timed-out")); - destroy_sess(sess, 500); - return -100; + PJ_LOG(3,(THIS_FILE, INDENT "err: init timed-out")); + destroy_sess(sess, 500); + return -100; } if (sess->caller.result.init_status != sess->caller.cfg.expected.init_status) { - app_perror(INDENT "err: caller init", sess->caller.result.init_status); - destroy_sess(sess, 500); - return -102; + app_perror(INDENT "err: caller init", sess->caller.result.init_status); + destroy_sess(sess, 500); + return -102; } if (sess->callee.result.init_status != sess->callee.cfg.expected.init_status) { - app_perror(INDENT "err: callee init", sess->callee.result.init_status); - destroy_sess(sess, 500); - return -104; + app_perror(INDENT "err: callee init", sess->callee.result.init_status); + destroy_sess(sess, 500); + return -104; } /* Failure condition */ if (sess->caller.result.init_status != PJ_SUCCESS || - sess->callee.result.init_status != PJ_SUCCESS) + sess->callee.result.init_status != PJ_SUCCESS) { - rc = 0; - goto on_return; + rc = 0; + goto on_return; } /* Init ICE on caller */ rc = pj_ice_strans_init_ice(sess->caller.ice, sess->caller.cfg.role, - &sess->caller.ufrag, &sess->caller.pass); + &sess->caller.ufrag, &sess->caller.pass); if (rc != PJ_SUCCESS) { - app_perror(INDENT "err: caller pj_ice_strans_init_ice()", rc); - destroy_sess(sess, 500); - return -100; + app_perror(INDENT "err: caller pj_ice_strans_init_ice()", rc); + destroy_sess(sess, 500); + return -100; } /* Init ICE on callee */ rc = pj_ice_strans_init_ice(sess->callee.ice, sess->callee.cfg.role, - &sess->callee.ufrag, &sess->callee.pass); + &sess->callee.ufrag, &sess->callee.pass); if (rc != PJ_SUCCESS) { - app_perror(INDENT "err: callee pj_ice_strans_init_ice()", rc); - destroy_sess(sess, 500); - return -110; + app_perror(INDENT "err: callee pj_ice_strans_init_ice()", rc); + destroy_sess(sess, 500); + return -110; } /* Start ICE on callee */ rc = start_ice(&sess->callee, &sess->caller); if (rc != PJ_SUCCESS) { - int retval = (rc == sess->callee.cfg.expected.start_status)?0:-120; - destroy_sess(sess, 500); - return retval; + int retval = (rc == sess->callee.cfg.expected.start_status)?0:-120; + destroy_sess(sess, 500); + return retval; } /* Wait for callee's answer_delay */ poll_events(stun_cfg, sess->callee.cfg.answer_delay, PJ_FALSE); /* Start ICE on caller */ rc = start_ice(&sess->caller, &sess->callee); if (rc != PJ_SUCCESS) { - int retval = (rc == sess->caller.cfg.expected.start_status)?0:-130; - destroy_sess(sess, 500); - return retval; + int retval = (rc == sess->caller.cfg.expected.start_status)?0:-130; + destroy_sess(sess, 500); + return retval; } for (i=0; iparam->worker_cnt; ++i) { - pj_status_t status; + pj_status_t status; - status = pj_thread_create(sess->pool, "worker_thread", - worker_thread_proc, sess, 0, 0, - &sess->worker_threads[i]); - if (status != PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, INDENT "err: create thread")); - destroy_sess(sess, 500); - return -135; - } + status = pj_thread_create(sess->pool, "worker_thread", + worker_thread_proc, sess, 0, 0, + &sess->worker_threads[i]); + if (status != PJ_SUCCESS) { + PJ_LOG(3,(THIS_FILE, INDENT "err: create thread")); + destroy_sess(sess, 500); + return -135; + } } if (sess->param->destroy_after_create) - goto on_destroy; + goto on_destroy; if (sess->param->destroy_after_one_done) { - while (sess->caller.result.init_status==PJ_EPENDING && - sess->callee.result.init_status==PJ_EPENDING) - { - if (sess->param->worker_cnt) - pj_thread_sleep(0); - else - poll_events(stun_cfg, 0, PJ_FALSE); - } - goto on_destroy; + while (sess->caller.result.init_status==PJ_EPENDING && + sess->callee.result.init_status==PJ_EPENDING) + { + if (sess->param->worker_cnt) + pj_thread_sleep(0); + else + poll_events(stun_cfg, 0, PJ_FALSE); + } + goto on_destroy; } WAIT_UNTIL(30000, ALL_DONE, rc); if (!ALL_DONE) { - PJ_LOG(3,(THIS_FILE, INDENT "err: negotiation timed-out")); - destroy_sess(sess, 500); - return -140; + PJ_LOG(3,(THIS_FILE, INDENT "err: negotiation timed-out")); + destroy_sess(sess, 500); + return -140; } if (sess->caller.result.nego_status != sess->caller.cfg.expected.nego_status) { - app_perror(INDENT "err: caller negotiation failed", sess->caller.result.nego_status); - destroy_sess(sess, 500); - return -150; + app_perror(INDENT "err: caller negotiation failed", sess->caller.result.nego_status); + destroy_sess(sess, 500); + return -150; } if (sess->callee.result.nego_status != sess->callee.cfg.expected.nego_status) { - app_perror(INDENT "err: callee negotiation failed", sess->callee.result.nego_status); - destroy_sess(sess, 500); - return -160; + app_perror(INDENT "err: callee negotiation failed", sess->callee.result.nego_status); + destroy_sess(sess, 500); + return -160; } /* Verify that both agents have agreed on the same pair */ rc = check_pair(&sess->caller, &sess->callee, -170); if (rc != 0) { - destroy_sess(sess, 500); - return rc; + destroy_sess(sess, 500); + return rc; } rc = check_pair(&sess->callee, &sess->caller, -180); if (rc != 0) { - destroy_sess(sess, 500); - return rc; + destroy_sess(sess, 500); + return rc; } /* Looks like everything is okay */ @@ -782,13 +781,13 @@ static int perform_test2(const char *title, * we wait for long time in the last poll_events() below). */ if (sess->caller.ice) { - pj_ice_strans_destroy(sess->caller.ice); - sess->caller.ice = NULL; + pj_ice_strans_destroy(sess->caller.ice); + sess->caller.ice = NULL; } if (sess->callee.ice) { - pj_ice_strans_destroy(sess->callee.ice); - sess->callee.ice = NULL; + pj_ice_strans_destroy(sess->callee.ice); + sess->callee.ice = NULL; } on_return: @@ -803,22 +802,22 @@ static int perform_test2(const char *title, rc = check_pjlib_state(stun_cfg, &pjlib_state); if (rc != 0) { - return rc; + return rc; } return rc; } static void set_client_server_flag(unsigned server_flag, - unsigned caller_flag, - unsigned callee_flag, - unsigned *res_server_flag, - unsigned *res_caller_flag, - unsigned *res_callee_flag) + unsigned caller_flag, + unsigned callee_flag, + unsigned *res_server_flag, + unsigned *res_caller_flag, + unsigned *res_callee_flag) { enum { - RST_CLT_FLAG = CLIENT_IPV4+CLIENT_IPV6, - RST_SRV_FLAG = SERVER_IPV4+SERVER_IPV6 + RST_CLT_FLAG = CLIENT_IPV4+CLIENT_IPV6, + RST_SRV_FLAG = SERVER_IPV4+SERVER_IPV6 }; *res_server_flag = (*res_server_flag & ~RST_SRV_FLAG) | server_flag; @@ -838,58 +837,58 @@ static int perform_test(const char *title, int expected_callee_start_ice = callee_cfg->expected.start_status; set_client_server_flag(SERVER_IPV4, CLIENT_IPV4, CLIENT_IPV4, - &server_flag, &caller_cfg->client_flag, - &callee_cfg->client_flag); + &server_flag, &caller_cfg->client_flag, + &callee_cfg->client_flag); pj_bzero(&test_param, sizeof(test_param)); rc = perform_test2(title, stun_cfg, server_flag, caller_cfg, - callee_cfg, &test_param); + callee_cfg, &test_param); #if USE_IPV6 if (enable_ipv6_test()) { - /* Test for IPV6. */ - if (rc == PJ_SUCCESS) { - pj_bzero(&test_param, sizeof(test_param)); - set_client_server_flag(SERVER_IPV6, CLIENT_IPV6, CLIENT_IPV6, - &server_flag, &caller_cfg->client_flag, - &callee_cfg->client_flag); - - rc = perform_test2(title, stun_cfg, server_flag, caller_cfg, - callee_cfg, &test_param); - } - - /* Test for IPV4+IPV6. */ - if (rc == PJ_SUCCESS) { - pj_bzero(&test_param, sizeof(test_param)); - set_client_server_flag(SERVER_IPV4+SERVER_IPV6, - CLIENT_IPV4+CLIENT_IPV6, - CLIENT_IPV4+CLIENT_IPV6, - &server_flag, - &caller_cfg->client_flag, - &callee_cfg->client_flag); - - rc = perform_test2(title, stun_cfg, server_flag, caller_cfg, - callee_cfg, &test_param); - } - - /* Test controller(IPV4) vs controlled(IPV6). */ - if (rc == PJ_SUCCESS) { - pj_bzero(&test_param, sizeof(test_param)); - set_client_server_flag(SERVER_IPV4+SERVER_IPV6, - CLIENT_IPV4, - CLIENT_IPV6, - &server_flag, - &caller_cfg->client_flag, - &callee_cfg->client_flag); - caller_cfg->expected.start_status = PJ_ENOTFOUND; - callee_cfg->expected.start_status = PJ_ENOTFOUND; - - rc = perform_test2(title, stun_cfg, server_flag, caller_cfg, - callee_cfg, &test_param); - } + /* Test for IPV6. */ + if (rc == PJ_SUCCESS) { + pj_bzero(&test_param, sizeof(test_param)); + set_client_server_flag(SERVER_IPV6, CLIENT_IPV6, CLIENT_IPV6, + &server_flag, &caller_cfg->client_flag, + &callee_cfg->client_flag); + + rc = perform_test2(title, stun_cfg, server_flag, caller_cfg, + callee_cfg, &test_param); + } + + /* Test for IPV4+IPV6. */ + if (rc == PJ_SUCCESS) { + pj_bzero(&test_param, sizeof(test_param)); + set_client_server_flag(SERVER_IPV4+SERVER_IPV6, + CLIENT_IPV4+CLIENT_IPV6, + CLIENT_IPV4+CLIENT_IPV6, + &server_flag, + &caller_cfg->client_flag, + &callee_cfg->client_flag); + + rc = perform_test2(title, stun_cfg, server_flag, caller_cfg, + callee_cfg, &test_param); + } + + /* Test controller(IPV4) vs controlled(IPV6). */ + if (rc == PJ_SUCCESS) { + pj_bzero(&test_param, sizeof(test_param)); + set_client_server_flag(SERVER_IPV4+SERVER_IPV6, + CLIENT_IPV4, + CLIENT_IPV6, + &server_flag, + &caller_cfg->client_flag, + &callee_cfg->client_flag); + caller_cfg->expected.start_status = PJ_ENOTFOUND; + callee_cfg->expected.start_status = PJ_ENOTFOUND; + + rc = perform_test2(title, stun_cfg, server_flag, caller_cfg, + callee_cfg, &test_param); + } } #endif callee_cfg->expected.start_status = expected_callee_start_ice; @@ -898,8 +897,8 @@ static int perform_test(const char *title, return rc; } -#define ROLE1 PJ_ICE_SESS_ROLE_CONTROLLED -#define ROLE2 PJ_ICE_SESS_ROLE_CONTROLLING +#define ROLE1 PJ_ICE_SESS_ROLE_CONTROLLED +#define ROLE2 PJ_ICE_SESS_ROLE_CONTROLLING int ice_test(void) { @@ -908,271 +907,271 @@ int ice_test(void) unsigned i; int rc; struct sess_cfg_t { - const char *title; - unsigned server_flag; - struct test_cfg ua1; - struct test_cfg ua2; + const char *title; + unsigned server_flag; + struct test_cfg ua1; + struct test_cfg ua2; } sess_cfg[] = { - /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ - { - "hosts candidates only", - 0x1FFF, - {ROLE1, 1, YES, NO, NO, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, YES, NO, NO, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} - }, - { - "host and srflxes", - 0x1FFF, - {ROLE1, 1, YES, YES, NO, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, YES, YES, NO, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} - }, - { - "host vs relay", - 0x1FFF, - {ROLE1, 1, YES, NO, NO, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, NO, NO, YES, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} - }, - { - "relay vs host", - 0x1FFF, - {ROLE1, 1, NO, NO, YES, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, YES, NO, NO, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} - }, - { - "relay vs relay", - 0x1FFF, - {ROLE1, 1, NO, NO, YES, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, NO, NO, YES, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} - }, - { - "all candidates", - 0x1FFF, - {ROLE1, 1, YES, YES, YES, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, YES, YES, YES, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} - }, + /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ + { + "hosts candidates only", + 0x1FFF, + {ROLE1, 1, YES, NO, NO, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, YES, NO, NO, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + }, + { + "host and srflxes", + 0x1FFF, + {ROLE1, 1, YES, YES, NO, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, YES, YES, NO, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + }, + { + "host vs relay", + 0x1FFF, + {ROLE1, 1, YES, NO, NO, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, NO, NO, YES, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + }, + { + "relay vs host", + 0x1FFF, + {ROLE1, 1, NO, NO, YES, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, YES, NO, NO, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + }, + { + "relay vs relay", + 0x1FFF, + {ROLE1, 1, NO, NO, YES, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, NO, NO, YES, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + }, + { + "all candidates", + 0x1FFF, + {ROLE1, 1, YES, YES, YES, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, YES, YES, YES, NO, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + }, }; pool = pj_pool_create(mem, NULL, 512, 512, NULL); rc = create_stun_config(pool, &stun_cfg); if (rc != PJ_SUCCESS) { - pj_pool_release(pool); - return -7; + pj_pool_release(pool); + return -7; } /* Simple test first with host candidate */ if (1) { - struct sess_cfg_t cfg = - { - "Basic with host candidates", - 0x0, - /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ - {ROLE1, 1, YES, NO, NO, 0, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, YES, NO, NO, 0, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} - }; - - rc = perform_test(cfg.title, &stun_cfg, cfg.server_flag, - &cfg.ua1, &cfg.ua2); - if (rc != 0) - goto on_return; - - cfg.ua1.comp_cnt = 2; - cfg.ua2.comp_cnt = 2; - rc = perform_test("Basic with host candidates, 2 components", - &stun_cfg, cfg.server_flag, - &cfg.ua1, &cfg.ua2); - if (rc != 0) - goto on_return; + struct sess_cfg_t cfg = + { + "Basic with host candidates", + 0x0, + /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ + {ROLE1, 1, YES, NO, NO, 0, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, YES, NO, NO, 0, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + }; + + rc = perform_test(cfg.title, &stun_cfg, cfg.server_flag, + &cfg.ua1, &cfg.ua2); + if (rc != 0) + goto on_return; + + cfg.ua1.comp_cnt = 2; + cfg.ua2.comp_cnt = 2; + rc = perform_test("Basic with host candidates, 2 components", + &stun_cfg, cfg.server_flag, + &cfg.ua1, &cfg.ua2); + if (rc != 0) + goto on_return; } /* Simple test first with srflx candidate */ if (1) { - struct sess_cfg_t cfg = - { - "Basic with srflx candidates", - 0xFFFF, - /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ - {ROLE1, 1, YES, YES, NO, 0, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, YES, YES, NO, 0, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} - }; - - rc = perform_test(cfg.title, &stun_cfg, cfg.server_flag, - &cfg.ua1, &cfg.ua2); - if (rc != 0) - goto on_return; - - cfg.ua1.comp_cnt = 2; - cfg.ua2.comp_cnt = 2; - - rc = perform_test("Basic with srflx candidates, 2 components", - &stun_cfg, cfg.server_flag, - &cfg.ua1, &cfg.ua2); - if (rc != 0) - goto on_return; + struct sess_cfg_t cfg = + { + "Basic with srflx candidates", + 0xFFFF, + /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ + {ROLE1, 1, YES, YES, NO, 0, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, YES, YES, NO, 0, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + }; + + rc = perform_test(cfg.title, &stun_cfg, cfg.server_flag, + &cfg.ua1, &cfg.ua2); + if (rc != 0) + goto on_return; + + cfg.ua1.comp_cnt = 2; + cfg.ua2.comp_cnt = 2; + + rc = perform_test("Basic with srflx candidates, 2 components", + &stun_cfg, cfg.server_flag, + &cfg.ua1, &cfg.ua2); + if (rc != 0) + goto on_return; } /* Simple test with relay candidate */ if (1) { - struct sess_cfg_t cfg = - { - "Basic with relay candidates", - 0xFFFF, - /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ - {ROLE1, 1, NO, NO, YES, 0, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, NO, NO, YES, 0, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} - }; - - rc = perform_test(cfg.title, &stun_cfg, cfg.server_flag, - &cfg.ua1, &cfg.ua2); - if (rc != 0) - goto on_return; - - cfg.ua1.comp_cnt = 2; - cfg.ua2.comp_cnt = 2; - - rc = perform_test("Basic with relay candidates, 2 components", - &stun_cfg, cfg.server_flag, - &cfg.ua1, &cfg.ua2); - if (rc != 0) - goto on_return; + struct sess_cfg_t cfg = + { + "Basic with relay candidates", + 0xFFFF, + /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ + {ROLE1, 1, NO, NO, YES, 0, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, NO, NO, YES, 0, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + }; + + rc = perform_test(cfg.title, &stun_cfg, cfg.server_flag, + &cfg.ua1, &cfg.ua2); + if (rc != 0) + goto on_return; + + cfg.ua1.comp_cnt = 2; + cfg.ua2.comp_cnt = 2; + + rc = perform_test("Basic with relay candidates, 2 components", + &stun_cfg, cfg.server_flag, + &cfg.ua1, &cfg.ua2); + if (rc != 0) + goto on_return; } /* Failure test with STUN resolution */ if (1) { - struct sess_cfg_t cfg = - { - "STUN resolution failure", - 0x0, - /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ - {ROLE1, 2, NO, YES, NO, 0, 0, 0, 0, {PJ_SUCCESS, PJNATH_ESTUNTIMEDOUT, -1}}, - {ROLE2, 2, NO, YES, NO, 0, 0, 0, 0, {PJ_SUCCESS, PJNATH_ESTUNTIMEDOUT, -1}} - }; - - rc = perform_test(cfg.title, &stun_cfg, cfg.server_flag, - &cfg.ua1, &cfg.ua2); - if (rc != 0) - goto on_return; - - cfg.ua1.client_flag |= DEL_ON_ERR; - cfg.ua2.client_flag |= DEL_ON_ERR; - - rc = perform_test("STUN resolution failure with destroy on callback", - &stun_cfg, cfg.server_flag, - &cfg.ua1, &cfg.ua2); - if (rc != 0) - goto on_return; + struct sess_cfg_t cfg = + { + "STUN resolution failure", + 0x0, + /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ + {ROLE1, 2, NO, YES, NO, 0, 0, 0, 0, {PJ_SUCCESS, PJNATH_ESTUNTIMEDOUT, -1}}, + {ROLE2, 2, NO, YES, NO, 0, 0, 0, 0, {PJ_SUCCESS, PJNATH_ESTUNTIMEDOUT, -1}} + }; + + rc = perform_test(cfg.title, &stun_cfg, cfg.server_flag, + &cfg.ua1, &cfg.ua2); + if (rc != 0) + goto on_return; + + cfg.ua1.client_flag |= DEL_ON_ERR; + cfg.ua2.client_flag |= DEL_ON_ERR; + + rc = perform_test("STUN resolution failure with destroy on callback", + &stun_cfg, cfg.server_flag, + &cfg.ua1, &cfg.ua2); + if (rc != 0) + goto on_return; } /* Failure test with TURN resolution */ if (1) { - struct sess_cfg_t cfg = - { - "TURN allocation failure", - 0xFFFF, - /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ - {ROLE1, 2, NO, NO, YES, WRONG_TURN, 0, 0, 0, {PJ_SUCCESS, PJ_STATUS_FROM_STUN_CODE(401), -1}}, - {ROLE2, 2, NO, NO, YES, WRONG_TURN, 0, 0, 0, {PJ_SUCCESS, PJ_STATUS_FROM_STUN_CODE(401), -1}} - }; + struct sess_cfg_t cfg = + { + "TURN allocation failure", + 0xFFFF, + /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ + {ROLE1, 2, NO, NO, YES, WRONG_TURN, 0, 0, 0, {PJ_SUCCESS, PJ_STATUS_FROM_STUN_CODE(401), -1}}, + {ROLE2, 2, NO, NO, YES, WRONG_TURN, 0, 0, 0, {PJ_SUCCESS, PJ_STATUS_FROM_STUN_CODE(401), -1}} + }; - rc = perform_test(cfg.title, &stun_cfg, cfg.server_flag, - &cfg.ua1, &cfg.ua2); - if (rc != 0) - goto on_return; + rc = perform_test(cfg.title, &stun_cfg, cfg.server_flag, + &cfg.ua1, &cfg.ua2); + if (rc != 0) + goto on_return; - cfg.ua1.client_flag |= DEL_ON_ERR; - cfg.ua2.client_flag |= DEL_ON_ERR; + cfg.ua1.client_flag |= DEL_ON_ERR; + cfg.ua2.client_flag |= DEL_ON_ERR; - rc = perform_test("TURN allocation failure with destroy on callback", - &stun_cfg, cfg.server_flag, - &cfg.ua1, &cfg.ua2); - if (rc != 0) - goto on_return; + rc = perform_test("TURN allocation failure with destroy on callback", + &stun_cfg, cfg.server_flag, + &cfg.ua1, &cfg.ua2); + if (rc != 0) + goto on_return; } /* STUN failure, testing TURN deallocation */ if (1) { - struct sess_cfg_t cfg = - { - "STUN failure, testing TURN deallocation", - 0xFFFF & (~(CREATE_STUN_SERVER)), - /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ - {ROLE1, 1, YES, YES, YES, 0, 0, 0, 0, {PJ_SUCCESS, PJNATH_ESTUNTIMEDOUT, -1}}, - {ROLE2, 1, YES, YES, YES, 0, 0, 0, 0, {PJ_SUCCESS, PJNATH_ESTUNTIMEDOUT, -1}} - }; - - rc = perform_test(cfg.title, &stun_cfg, cfg.server_flag, - &cfg.ua1, &cfg.ua2); - if (rc != 0) - goto on_return; - - cfg.ua1.client_flag |= DEL_ON_ERR; - cfg.ua2.client_flag |= DEL_ON_ERR; - - rc = perform_test("STUN failure, testing TURN deallocation (cb)", - &stun_cfg, cfg.server_flag, - &cfg.ua1, &cfg.ua2); - if (rc != 0) - goto on_return; + struct sess_cfg_t cfg = + { + "STUN failure, testing TURN deallocation", + 0xFFFF & (~(CREATE_STUN_SERVER)), + /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ + {ROLE1, 1, YES, YES, YES, 0, 0, 0, 0, {PJ_SUCCESS, PJNATH_ESTUNTIMEDOUT, -1}}, + {ROLE2, 1, YES, YES, YES, 0, 0, 0, 0, {PJ_SUCCESS, PJNATH_ESTUNTIMEDOUT, -1}} + }; + + rc = perform_test(cfg.title, &stun_cfg, cfg.server_flag, + &cfg.ua1, &cfg.ua2); + if (rc != 0) + goto on_return; + + cfg.ua1.client_flag |= DEL_ON_ERR; + cfg.ua2.client_flag |= DEL_ON_ERR; + + rc = perform_test("STUN failure, testing TURN deallocation (cb)", + &stun_cfg, cfg.server_flag, + &cfg.ua1, &cfg.ua2); + if (rc != 0) + goto on_return; } rc = 0; /* Iterate each test item */ for (i=0; ititle)); - - /* For each test item, test with various answer delay */ - for (d=0; dua1.answer_delay = delay[d]; - cfg->ua2.answer_delay = delay[d]; - - /* For each test item, test with role conflict scenarios */ - for (j=0; jua1.role = role[j].ua1; - cfg->ua2.role = role[j].ua2; - - /* For each test item, test with different number of components */ - for (k1=1; k1<=2; ++k1) { - unsigned k2; - - cfg->ua1.comp_cnt = k1; - - for (k2=1; k2<=2; ++k2) { - char title[120]; - - sprintf(title, - "%s/%s, %dms answer delay, %d vs %d components", - pj_ice_sess_role_name(role[j].ua1), - pj_ice_sess_role_name(role[j].ua2), - delay[d], k1, k2); - - cfg->ua2.comp_cnt = k2; - rc = perform_test(title, &stun_cfg, cfg->server_flag, - &cfg->ua1, &cfg->ua2); - if (rc != 0) - goto on_return; - } - } - } - } + struct sess_cfg_t *cfg = &sess_cfg[i]; + unsigned delay[] = { 50, 2000 }; + unsigned d; + + PJ_LOG(3,(THIS_FILE, " %s", cfg->title)); + + /* For each test item, test with various answer delay */ + for (d=0; dua1.answer_delay = delay[d]; + cfg->ua2.answer_delay = delay[d]; + + /* For each test item, test with role conflict scenarios */ + for (j=0; jua1.role = role[j].ua1; + cfg->ua2.role = role[j].ua2; + + /* For each test item, test with different number of components */ + for (k1=1; k1<=2; ++k1) { + unsigned k2; + + cfg->ua1.comp_cnt = k1; + + for (k2=1; k2<=2; ++k2) { + char title[120]; + + sprintf(title, + "%s/%s, %dms answer delay, %d vs %d components", + pj_ice_sess_role_name(role[j].ua1), + pj_ice_sess_role_name(role[j].ua2), + delay[d], k1, k2); + + cfg->ua2.comp_cnt = k2; + rc = perform_test(title, &stun_cfg, cfg->server_flag, + &cfg->ua1, &cfg->ua2); + if (rc != 0) + goto on_return; + } + } + } + } } on_return: @@ -1184,17 +1183,17 @@ int ice_test(void) int ice_one_conc_test(pj_stun_config *stun_cfg, int err_quit) { struct sess_cfg_t { - const char *title; - unsigned server_flag; - struct test_cfg ua1; - struct test_cfg ua2; + const char *title; + unsigned server_flag; + struct test_cfg ua1; + struct test_cfg ua2; } cfg = { - "Concurrency test", - 0x1FFF, - /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ - {ROLE1, 1, YES, YES, YES, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, YES, YES, YES, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + "Concurrency test", + 0x1FFF, + /* Role comp# host? stun? turn? flag? ans_del snd_del des_del */ + {ROLE1, 1, YES, YES, YES, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, YES, YES, YES, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} }; struct sess_param test_param; int rc; @@ -1247,15 +1246,15 @@ int ice_conc_test(void) pool = pj_pool_create(mem, NULL, 512, 512, NULL); rc = create_stun_config(pool, &stun_cfg); if (rc != PJ_SUCCESS) { - pj_pool_release(pool); - return -7; + pj_pool_release(pool); + return -7; } for (i = 0; i < LOOP; i++) { - PJ_LOG(3,(THIS_FILE, INDENT "Test %d of %d", i+1, LOOP)); - rc = ice_one_conc_test(&stun_cfg, PJ_TRUE); - if (rc) - break; + PJ_LOG(3,(THIS_FILE, INDENT "Test %d of %d", i+1, LOOP)); + rc = ice_one_conc_test(&stun_cfg, PJ_TRUE); + if (rc) + break; } /* Avoid compiler warning */ @@ -1270,9 +1269,9 @@ int ice_conc_test(void) struct timer_data { - struct test_sess *sess; - unsigned caller_last_cand_cnt[PJ_ICE_MAX_COMP]; - unsigned callee_last_cand_cnt[PJ_ICE_MAX_COMP]; + struct test_sess *sess; + unsigned caller_last_cand_cnt[PJ_ICE_MAX_COMP]; + unsigned callee_last_cand_cnt[PJ_ICE_MAX_COMP]; }; @@ -1289,115 +1288,115 @@ static void timer_new_cand(pj_timer_heap_t *th, pj_timer_entry *te) /* ICE transport may have been destroyed */ if (!caller->ice || !callee->ice) - return; + return; caller_last_cand = caller->last_cand; callee_last_cand = callee->last_cand; //PJ_LOG(3,(THIS_FILE, INDENT "End-of-cand status: caller=%d callee=%d", - // caller_last_cand, callee_last_cand)); + // caller_last_cand, callee_last_cand)); ncomp = PJ_MIN(caller->cfg.comp_cnt, callee->cfg.comp_cnt); for (i = 0; i < ncomp; ++i) { - pj_ice_sess_cand cand[PJ_ICE_ST_MAX_CAND]; - unsigned j, cnt; - - /* Check caller candidates */ - cnt = PJ_ICE_ST_MAX_CAND; - rc = pj_ice_strans_enum_cands(caller->ice, i+1, &cnt, cand); - if (rc != PJ_SUCCESS) { - app_perror(INDENT "err: caller pj_ice_strans_enum_cands()", rc); - continue; - } - - if (cnt > data->caller_last_cand_cnt[i]) { - unsigned new_cnt = cnt - data->caller_last_cand_cnt[i]; - - /* Update remote with new candidates */ - rc = pj_ice_strans_update_check_list(callee->ice, - &caller->ufrag, - &caller->pass, - new_cnt, &cand[cnt - new_cnt], - caller_last_cand && (i==ncomp-1)); - if (rc != PJ_SUCCESS) { - app_perror(INDENT "err: callee pj_ice_strans_update_check_list()", rc); - continue; - } - - data->caller_last_cand_cnt[i] = cnt; - PJ_LOG(4,(THIS_FILE, INDENT "Updated callee with %d new candidates %s", - new_cnt, (caller_last_cand?"(last)":""))); - - for (j = 0; j < new_cnt; ++j) { - pj_ice_sess_cand *c = &cand[cnt - new_cnt + j]; - char buf1[PJ_INET6_ADDRSTRLEN+10]; - char buf2[PJ_INET6_ADDRSTRLEN+10]; - PJ_LOG(4,(THIS_FILE, INDENT - "%d: comp=%d, type=%s, addr=%s, baseaddr=%s", - j+1, c->comp_id, - pj_ice_get_cand_type_name(c->type), - pj_sockaddr_print(&c->addr, buf1, sizeof(buf1), 3), - pj_sockaddr_print(&c->base_addr, buf2, sizeof(buf2), 3) - )); - } - } - - /* Check callee candidates */ - cnt = PJ_ICE_ST_MAX_CAND; - rc = pj_ice_strans_enum_cands(callee->ice, i+1, &cnt, cand); - if (rc != PJ_SUCCESS) { - app_perror(INDENT "err: caller pj_ice_strans_enum_cands()", rc); - continue; - } - - if (cnt > data->callee_last_cand_cnt[i]) { - unsigned new_cnt = cnt - data->callee_last_cand_cnt[i]; - - /* Update remote with new candidates */ - rc = pj_ice_strans_update_check_list(caller->ice, - &callee->ufrag, - &callee->pass, - new_cnt, &cand[cnt - new_cnt], - callee_last_cand && (i==ncomp-1)); - if (rc != PJ_SUCCESS) { - app_perror(INDENT "err: caller pj_ice_strans_update_check_list()", rc); - continue; - } - - data->callee_last_cand_cnt[i] = cnt; - PJ_LOG(4,(THIS_FILE, INDENT "Updated caller with %d new candidates %s", - new_cnt, (callee_last_cand?"(last)":""))); - - for (j = 0; j < new_cnt; ++j) { - pj_ice_sess_cand *c = &cand[cnt - new_cnt + j]; - char buf1[PJ_INET6_ADDRSTRLEN+10]; - char buf2[PJ_INET6_ADDRSTRLEN+10]; - PJ_LOG(4,(THIS_FILE, INDENT - "%d: comp=%d, type=%s, addr=%s, baseaddr=%s", - j+1, c->comp_id, - pj_ice_get_cand_type_name(c->type), - pj_sockaddr_print(&c->addr, buf1, sizeof(buf1), 3), - pj_sockaddr_print(&c->base_addr, buf2, sizeof(buf2), 3) - )); - } - } + pj_ice_sess_cand cand[PJ_ICE_ST_MAX_CAND]; + unsigned j, cnt; + + /* Check caller candidates */ + cnt = PJ_ICE_ST_MAX_CAND; + rc = pj_ice_strans_enum_cands(caller->ice, i+1, &cnt, cand); + if (rc != PJ_SUCCESS) { + app_perror(INDENT "err: caller pj_ice_strans_enum_cands()", rc); + continue; + } + + if (cnt > data->caller_last_cand_cnt[i]) { + unsigned new_cnt = cnt - data->caller_last_cand_cnt[i]; + + /* Update remote with new candidates */ + rc = pj_ice_strans_update_check_list(callee->ice, + &caller->ufrag, + &caller->pass, + new_cnt, &cand[cnt - new_cnt], + caller_last_cand && (i==ncomp-1)); + if (rc != PJ_SUCCESS) { + app_perror(INDENT "err: callee pj_ice_strans_update_check_list()", rc); + continue; + } + + data->caller_last_cand_cnt[i] = cnt; + PJ_LOG(4,(THIS_FILE, INDENT "Updated callee with %d new candidates %s", + new_cnt, (caller_last_cand?"(last)":""))); + + for (j = 0; j < new_cnt; ++j) { + pj_ice_sess_cand *c = &cand[cnt - new_cnt + j]; + char buf1[PJ_INET6_ADDRSTRLEN+10]; + char buf2[PJ_INET6_ADDRSTRLEN+10]; + PJ_LOG(4,(THIS_FILE, INDENT + "%d: comp=%d, type=%s, addr=%s, baseaddr=%s", + j+1, c->comp_id, + pj_ice_get_cand_type_name(c->type), + pj_sockaddr_print(&c->addr, buf1, sizeof(buf1), 3), + pj_sockaddr_print(&c->base_addr, buf2, sizeof(buf2), 3) + )); + } + } + + /* Check callee candidates */ + cnt = PJ_ICE_ST_MAX_CAND; + rc = pj_ice_strans_enum_cands(callee->ice, i+1, &cnt, cand); + if (rc != PJ_SUCCESS) { + app_perror(INDENT "err: caller pj_ice_strans_enum_cands()", rc); + continue; + } + + if (cnt > data->callee_last_cand_cnt[i]) { + unsigned new_cnt = cnt - data->callee_last_cand_cnt[i]; + + /* Update remote with new candidates */ + rc = pj_ice_strans_update_check_list(caller->ice, + &callee->ufrag, + &callee->pass, + new_cnt, &cand[cnt - new_cnt], + callee_last_cand && (i==ncomp-1)); + if (rc != PJ_SUCCESS) { + app_perror(INDENT "err: caller pj_ice_strans_update_check_list()", rc); + continue; + } + + data->callee_last_cand_cnt[i] = cnt; + PJ_LOG(4,(THIS_FILE, INDENT "Updated caller with %d new candidates %s", + new_cnt, (callee_last_cand?"(last)":""))); + + for (j = 0; j < new_cnt; ++j) { + pj_ice_sess_cand *c = &cand[cnt - new_cnt + j]; + char buf1[PJ_INET6_ADDRSTRLEN+10]; + char buf2[PJ_INET6_ADDRSTRLEN+10]; + PJ_LOG(4,(THIS_FILE, INDENT + "%d: comp=%d, type=%s, addr=%s, baseaddr=%s", + j+1, c->comp_id, + pj_ice_get_cand_type_name(c->type), + pj_sockaddr_print(&c->addr, buf1, sizeof(buf1), 3), + pj_sockaddr_print(&c->base_addr, buf2, sizeof(buf2), 3) + )); + } + } } if (!caller_last_cand || !callee_last_cand) { - /* Reschedule until all candidates are gathered */ - pj_time_val timeout = {0, 10}; - pj_time_val_normalize(&timeout); - pj_timer_heap_schedule(th, te, &timeout); - //PJ_LOG(3,(THIS_FILE, INDENT "Rescheduled new candidate check")); + /* Reschedule until all candidates are gathered */ + pj_time_val timeout = {0, 10}; + pj_time_val_normalize(&timeout); + pj_timer_heap_schedule(th, te, &timeout); + //PJ_LOG(3,(THIS_FILE, INDENT "Rescheduled new candidate check")); } } static int perform_trickle_test(const char *title, - pj_stun_config *stun_cfg, - unsigned server_flag, - struct test_cfg *caller_cfg, - struct test_cfg *callee_cfg, - struct sess_param *test_param) + pj_stun_config *stun_cfg, + unsigned server_flag, + struct test_cfg *caller_cfg, + struct test_cfg *callee_cfg, + struct sess_param *test_param) { pjlib_state pjlib_state; struct test_sess *sess; @@ -1406,92 +1405,92 @@ static int perform_trickle_test(const char *title, int rc; PJ_LOG(3,(THIS_FILE, "%s, %d vs %d components", - title, caller_cfg->comp_cnt, callee_cfg->comp_cnt)); + title, caller_cfg->comp_cnt, callee_cfg->comp_cnt)); capture_pjlib_state(stun_cfg, &pjlib_state); rc = create_sess(stun_cfg, server_flag, caller_cfg, callee_cfg, - test_param, &sess); + test_param, &sess); if (rc != 0) - return rc; + return rc; /* Init ICE on caller */ rc = pj_ice_strans_init_ice(sess->caller.ice, sess->caller.cfg.role, - &sess->caller.ufrag, &sess->caller.pass); + &sess->caller.ufrag, &sess->caller.pass); if (rc != PJ_SUCCESS) { - app_perror(INDENT "err: caller pj_ice_strans_init_ice()", rc); - rc = -100; - goto on_return; + app_perror(INDENT "err: caller pj_ice_strans_init_ice()", rc); + rc = -100; + goto on_return; } /* Init ICE on callee */ rc = pj_ice_strans_init_ice(sess->callee.ice, sess->callee.cfg.role, - &sess->callee.ufrag, &sess->callee.pass); + &sess->callee.ufrag, &sess->callee.pass); if (rc != PJ_SUCCESS) { - app_perror(INDENT "err: callee pj_ice_strans_init_ice()", rc); - rc = -110; - goto on_return; + app_perror(INDENT "err: callee pj_ice_strans_init_ice()", rc); + rc = -110; + goto on_return; } /* Start ICE on callee */ rc = start_ice(&sess->callee, &sess->caller); if (rc != PJ_SUCCESS) { - int retval = (rc == sess->callee.cfg.expected.start_status)?0:-120; - rc = retval; - goto on_return; + int retval = (rc == sess->callee.cfg.expected.start_status)?0:-120; + rc = retval; + goto on_return; } /* Start ICE on caller */ rc = start_ice(&sess->caller, &sess->callee); if (rc != PJ_SUCCESS) { - int retval = (rc == sess->caller.cfg.expected.start_status)?0:-130; - rc = retval; - goto on_return; + int retval = (rc == sess->caller.cfg.expected.start_status)?0:-130; + rc = retval; + goto on_return; } /* Start polling new candidate */ //if (!sess->caller.last_cand || !sess->callee.last_cand) { - pj_time_val timeout = {0, 10}; + pj_time_val timeout = {0, 10}; - pj_bzero(&timer_data, sizeof(timer_data)); - timer_data.sess = sess; + pj_bzero(&timer_data, sizeof(timer_data)); + timer_data.sess = sess; - pj_time_val_normalize(&timeout); - pj_timer_entry_init(&te_new_cand, 0, &timer_data, &timer_new_cand); - pj_timer_heap_schedule(stun_cfg->timer_heap, &te_new_cand, &timeout); + pj_time_val_normalize(&timeout); + pj_timer_entry_init(&te_new_cand, 0, &timer_data, &timer_new_cand); + pj_timer_heap_schedule(stun_cfg->timer_heap, &te_new_cand, &timeout); } WAIT_UNTIL(30000, ALL_DONE, rc); if (!ALL_DONE) { - PJ_LOG(3,(THIS_FILE, INDENT "err: negotiation timed-out")); - rc = -140; - goto on_return; + PJ_LOG(3,(THIS_FILE, INDENT "err: negotiation timed-out")); + rc = -140; + goto on_return; } if (rc != 0) - goto on_return; + goto on_return; if (sess->caller.result.nego_status != sess->caller.cfg.expected.nego_status) { - app_perror(INDENT "err: caller negotiation failed", sess->caller.result.nego_status); - rc = -150; - goto on_return; + app_perror(INDENT "err: caller negotiation failed", sess->caller.result.nego_status); + rc = -150; + goto on_return; } if (sess->callee.result.nego_status != sess->callee.cfg.expected.nego_status) { - app_perror(INDENT "err: callee negotiation failed", sess->callee.result.nego_status); - rc = -160; - goto on_return; + app_perror(INDENT "err: callee negotiation failed", sess->callee.result.nego_status); + rc = -160; + goto on_return; } /* Verify that both agents have agreed on the same pair */ rc = check_pair(&sess->caller, &sess->callee, -170); if (rc != 0) { - goto on_return; + goto on_return; } rc = check_pair(&sess->callee, &sess->caller, -180); if (rc != 0) { - goto on_return; + goto on_return; } /* Looks like everything is okay */ @@ -1501,13 +1500,13 @@ static int perform_trickle_test(const char *title, * we wait for long time in the last poll_events() below). */ if (sess->caller.ice) { - pj_ice_strans_destroy(sess->caller.ice); - sess->caller.ice = NULL; + pj_ice_strans_destroy(sess->caller.ice); + sess->caller.ice = NULL; } if (sess->callee.ice) { - pj_ice_strans_destroy(sess->callee.ice); - sess->callee.ice = NULL; + pj_ice_strans_destroy(sess->callee.ice); + sess->callee.ice = NULL; } on_return: @@ -1521,7 +1520,7 @@ static int perform_trickle_test(const char *title, poll_events(stun_cfg, 100, PJ_FALSE); if (rc == 0) - rc = check_pjlib_state(stun_cfg, &pjlib_state); + rc = check_pjlib_state(stun_cfg, &pjlib_state); return rc; } @@ -1537,32 +1536,32 @@ int trickle_ice_test(void) int rc; struct sess_cfg_t { - const char *title; - unsigned server_flag; - struct test_cfg ua1; - struct test_cfg ua2; + const char *title; + unsigned server_flag; + struct test_cfg ua1; + struct test_cfg ua2; } cfg[] = { { - "With host-only", - 0x1FFF, - /*Role comp# host? stun? turn? flag? ans_del snd_del des_del */ - {ROLE1, 1, YES, NO, NO, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, YES, NO, NO, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + "With host-only", + 0x1FFF, + /*Role comp# host? stun? turn? flag? ans_del snd_del des_del */ + {ROLE1, 1, YES, NO, NO, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, YES, NO, NO, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} }, { - "With turn-only", - 0x1FFF, - /*Role comp# host? stun? turn? flag? ans_del snd_del des_del */ - {ROLE1, 1, NO, NO, YES, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, NO, NO, YES, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + "With turn-only", + 0x1FFF, + /*Role comp# host? stun? turn? flag? ans_del snd_del des_del */ + {ROLE1, 1, NO, NO, YES, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, NO, NO, YES, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} }, { - /* STUN candidates will be pruned */ - "With host+turn", - 0x1FFF, - /*Role comp# host? stun? turn? flag? ans_del snd_del des_del */ - {ROLE1, 1, YES, YES, YES, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, - {ROLE2, 1, YES, YES, YES, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} + /* STUN candidates will be pruned */ + "With host+turn", + 0x1FFF, + /*Role comp# host? stun? turn? flag? ans_del snd_del des_del */ + {ROLE1, 1, YES, YES, YES, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}}, + {ROLE2, 1, YES, YES, YES, CLIENT_IPV4, 0, 0, 0, {PJ_SUCCESS, PJ_SUCCESS, PJ_SUCCESS}} }}; PJ_LOG(3,(THIS_FILE, "Trickle ICE")); @@ -1572,28 +1571,28 @@ int trickle_ice_test(void) rc = create_stun_config(pool, &stun_cfg); if (rc != PJ_SUCCESS) { - pj_pool_release(pool); - pj_log_pop_indent(); - return -10; + pj_pool_release(pool); + pj_log_pop_indent(); + return -10; } for (i = 0; i < PJ_ARRAY_SIZE(cfg) && !rc; ++i) { - unsigned c1, c2; - cfg[i].ua1.trickle = PJ_ICE_SESS_TRICKLE_FULL; - cfg[i].ua2.trickle = PJ_ICE_SESS_TRICKLE_FULL; - for (c1 = 1; c1 <= 2 && !rc; ++c1) { - for (c2 = 1; c2 <= 2 && !rc; ++c2) { - pj_bzero(&test_param, sizeof(test_param)); - cfg[i].ua1.comp_cnt = c1; - cfg[i].ua2.comp_cnt = c2; - rc = perform_trickle_test(cfg[i].title, - &stun_cfg, - cfg[i].server_flag, - &cfg[i].ua1, - &cfg[i].ua2, - &test_param); - } - } + unsigned c1, c2; + cfg[i].ua1.trickle = PJ_ICE_SESS_TRICKLE_FULL; + cfg[i].ua2.trickle = PJ_ICE_SESS_TRICKLE_FULL; + for (c1 = 1; c1 <= 2 && !rc; ++c1) { + for (c2 = 1; c2 <= 2 && !rc; ++c2) { + pj_bzero(&test_param, sizeof(test_param)); + cfg[i].ua1.comp_cnt = c1; + cfg[i].ua2.comp_cnt = c2; + rc = perform_trickle_test(cfg[i].title, + &stun_cfg, + cfg[i].server_flag, + &cfg[i].ua1, + &cfg[i].ua2, + &test_param); + } + } } destroy_stun_config(&stun_cfg); diff --git a/pjnath/src/pjnath-test/main.c b/pjnath/src/pjnath-test/main.c index 0371976423..9ecc43e948 100644 --- a/pjnath/src/pjnath-test/main.c +++ b/pjnath/src/pjnath-test/main.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -73,26 +72,26 @@ int main(int argc, char *argv[]) while (argc > 1) { char *arg = argv[--argc]; - if (*arg=='-' && *(arg+1)=='i') { - interractive = 1; + if (*arg=='-' && *(arg+1)=='i') { + interractive = 1; - } else if (*arg=='-' && *(arg+1)=='n') { - no_trap = 1; - } + } else if (*arg=='-' && *(arg+1)=='n') { + no_trap = 1; + } } if (!no_trap) { - init_signals(); + init_signals(); } rc = test_main(); if (interractive) { - char s[10]; - puts(""); - puts("Press to exit"); - if (!fgets(s, sizeof(s), stdin)) - return rc; + char s[10]; + puts(""); + puts("Press to exit"); + if (!fgets(s, sizeof(s), stdin)) + return rc; } return rc; diff --git a/pjnath/src/pjnath-test/server.c b/pjnath/src/pjnath-test/server.c index a367c127b4..446dfec040 100644 --- a/pjnath/src/pjnath-test/server.c +++ b/pjnath/src/pjnath-test/server.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -20,70 +19,70 @@ #include "server.h" #include "test.h" -#define THIS_FILE "server.c" -#define MAX_STUN_PKT 1500 -#define TURN_NONCE "thenonce" -#define CERT_DIR "../../pjlib/build/" -#define CERT_CA_FILE CERT_DIR "cacert.pem" -#define CERT_FILE CERT_DIR "cacert.pem" -#define CERT_PRIVKEY_FILE CERT_DIR "privkey.pem" -#define CERT_PRIVKEY_PASS "privkeypass" +#define THIS_FILE "server.c" +#define MAX_STUN_PKT 1500 +#define TURN_NONCE "thenonce" +#define CERT_DIR "../../pjlib/build/" +#define CERT_CA_FILE CERT_DIR "cacert.pem" +#define CERT_FILE CERT_DIR "cacert.pem" +#define CERT_PRIVKEY_FILE CERT_DIR "privkey.pem" +#define CERT_PRIVKEY_PASS "privkeypass" -#define RETURN_ERROR(rc) {app_perror("", rc);return rc;} +#define RETURN_ERROR(rc) {app_perror("", rc);return rc;} static pj_bool_t stun_on_data_recvfrom(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status); + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status); static pj_bool_t turn_tcp_on_data_read(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder); + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder); #if USE_TLS static pj_bool_t turn_tls_on_data_read(pj_ssl_sock_t *ssock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder); + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder); #endif static pj_bool_t turn_udp_on_data_recvfrom(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status); + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status); static pj_bool_t turn_on_data_read(test_server *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status); + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status); static pj_bool_t turn_tcp_on_accept_complete(pj_activesock_t *asock, - pj_sock_t newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len, - pj_status_t status); + pj_sock_t newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len, + pj_status_t status); #if USE_TLS static pj_bool_t turn_tls_on_accept_complete2(pj_ssl_sock_t *ssock, - pj_ssl_sock_t *newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len, - pj_status_t status); + pj_ssl_sock_t *newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len, + pj_status_t status); #endif static pj_bool_t alloc_on_data_recvfrom(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status); + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status); pj_status_t create_test_server(pj_stun_config *stun_cfg, - pj_uint32_t flags, - const char *domain, - test_server **p_test_srv) + pj_uint32_t flags, + const char *domain, + test_server **p_test_srv) { pj_pool_t *pool; test_server *test_srv; @@ -95,15 +94,15 @@ pj_status_t create_test_server(pj_stun_config *stun_cfg, PJ_ASSERT_RETURN(stun_cfg && domain && p_test_srv, PJ_EINVAL); if (use_ipv6) { - /* pj_gethostip() may return IPv6 link-local and will cause EINVAL - * error, so let's just hardcode it. - */ - pj_sockaddr_init(pj_AF_INET6(), &hostip, NULL, 0); - hostip.ipv6.sin6_addr.s6_addr[15] = 1; + /* pj_gethostip() may return IPv6 link-local and will cause EINVAL + * error, so let's just hardcode it. + */ + pj_sockaddr_init(pj_AF_INET6(), &hostip, NULL, 0); + hostip.ipv6.sin6_addr.s6_addr[15] = 1; } else { - status = pj_gethostip(GET_AF(use_ipv6), &hostip); - if (status != PJ_SUCCESS) - RETURN_ERROR(status); + status = pj_gethostip(GET_AF(use_ipv6), &hostip); + if (status != PJ_SUCCESS) + RETURN_ERROR(status); } pool = pj_pool_create(mem, THIS_FILE, 512, 512, NULL); @@ -119,248 +118,248 @@ pj_status_t create_test_server(pj_stun_config *stun_cfg, pj_ioqueue_op_key_init(&test_srv->send_key, sizeof(test_srv->send_key)); if (flags & CREATE_DNS_SERVER) { - status = pj_dns_server_create(mem, test_srv->stun_cfg->ioqueue, - GET_AF(use_ipv6), DNS_SERVER_PORT, - 0, &test_srv->dns_server); - if (status != PJ_SUCCESS) { - destroy_test_server(test_srv); - RETURN_ERROR(status); - } - - /* Add DNS A record for the domain, for fallback */ - if (flags & CREATE_A_RECORD_FOR_DOMAIN) { - pj_dns_parsed_rr rr; - pj_str_t res_name; - - pj_strdup2(pool, &res_name, domain); - - if (use_ipv6) { - pj_dns_init_aaaa_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, - &hostip.ipv6.sin6_addr); - } else { - pj_dns_init_a_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, - &hostip.ipv4.sin_addr); - } - - pj_dns_server_add_rec(test_srv->dns_server, 1, &rr); - } + status = pj_dns_server_create(mem, test_srv->stun_cfg->ioqueue, + GET_AF(use_ipv6), DNS_SERVER_PORT, + 0, &test_srv->dns_server); + if (status != PJ_SUCCESS) { + destroy_test_server(test_srv); + RETURN_ERROR(status); + } + + /* Add DNS A record for the domain, for fallback */ + if (flags & CREATE_A_RECORD_FOR_DOMAIN) { + pj_dns_parsed_rr rr; + pj_str_t res_name; + + pj_strdup2(pool, &res_name, domain); + + if (use_ipv6) { + pj_dns_init_aaaa_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, + &hostip.ipv6.sin6_addr); + } else { + pj_dns_init_a_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, + &hostip.ipv4.sin_addr); + } + + pj_dns_server_add_rec(test_srv->dns_server, 1, &rr); + } } if (flags & CREATE_STUN_SERVER) { - pj_activesock_cb stun_sock_cb; - pj_sockaddr bound_addr; - - pj_bzero(&stun_sock_cb, sizeof(stun_sock_cb)); - stun_sock_cb.on_data_recvfrom = &stun_on_data_recvfrom; - - pj_sockaddr_init(GET_AF(use_ipv6), &bound_addr, - NULL, STUN_SERVER_PORT); - - status = pj_activesock_create_udp(pool, &bound_addr, NULL, - test_srv->stun_cfg->ioqueue, - &stun_sock_cb, test_srv, - &test_srv->stun_sock, NULL); - if (status != PJ_SUCCESS) { - destroy_test_server(test_srv); - RETURN_ERROR(status); - } - - status = pj_activesock_start_recvfrom(test_srv->stun_sock, pool, - MAX_STUN_PKT, 0); - if (status != PJ_SUCCESS) { - destroy_test_server(test_srv); - RETURN_ERROR(status); - } - - if (test_srv->dns_server && (flags & CREATE_STUN_SERVER_DNS_SRV)) { - pj_str_t res_name, target; - pj_dns_parsed_rr rr; - - /* Add DNS entries: - * _stun._udp.domain 60 IN SRV 0 0 PORT stun.domain. - * stun.domain IN A 127.0.0.1 - */ - pj_ansi_snprintf(strbuf, sizeof(strbuf), - "_stun._udp.%s", domain); - pj_strdup2(pool, &res_name, strbuf); - pj_ansi_snprintf(strbuf, sizeof(strbuf), - "stun.%s", domain); - pj_strdup2(pool, &target, strbuf); - pj_dns_init_srv_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, 0, 0, - STUN_SERVER_PORT, &target); - pj_dns_server_add_rec(test_srv->dns_server, 1, &rr); - - res_name = target; - if (use_ipv6) { - pj_dns_init_aaaa_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, - &hostip.ipv6.sin6_addr); - } else { - pj_dns_init_a_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, - &hostip.ipv4.sin_addr); - } - pj_dns_server_add_rec(test_srv->dns_server, 1, &rr); - } + pj_activesock_cb stun_sock_cb; + pj_sockaddr bound_addr; + + pj_bzero(&stun_sock_cb, sizeof(stun_sock_cb)); + stun_sock_cb.on_data_recvfrom = &stun_on_data_recvfrom; + + pj_sockaddr_init(GET_AF(use_ipv6), &bound_addr, + NULL, STUN_SERVER_PORT); + + status = pj_activesock_create_udp(pool, &bound_addr, NULL, + test_srv->stun_cfg->ioqueue, + &stun_sock_cb, test_srv, + &test_srv->stun_sock, NULL); + if (status != PJ_SUCCESS) { + destroy_test_server(test_srv); + RETURN_ERROR(status); + } + + status = pj_activesock_start_recvfrom(test_srv->stun_sock, pool, + MAX_STUN_PKT, 0); + if (status != PJ_SUCCESS) { + destroy_test_server(test_srv); + RETURN_ERROR(status); + } + + if (test_srv->dns_server && (flags & CREATE_STUN_SERVER_DNS_SRV)) { + pj_str_t res_name, target; + pj_dns_parsed_rr rr; + + /* Add DNS entries: + * _stun._udp.domain 60 IN SRV 0 0 PORT stun.domain. + * stun.domain IN A 127.0.0.1 + */ + pj_ansi_snprintf(strbuf, sizeof(strbuf), + "_stun._udp.%s", domain); + pj_strdup2(pool, &res_name, strbuf); + pj_ansi_snprintf(strbuf, sizeof(strbuf), + "stun.%s", domain); + pj_strdup2(pool, &target, strbuf); + pj_dns_init_srv_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, 0, 0, + STUN_SERVER_PORT, &target); + pj_dns_server_add_rec(test_srv->dns_server, 1, &rr); + + res_name = target; + if (use_ipv6) { + pj_dns_init_aaaa_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, + &hostip.ipv6.sin6_addr); + } else { + pj_dns_init_a_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, + &hostip.ipv4.sin_addr); + } + pj_dns_server_add_rec(test_srv->dns_server, 1, &rr); + } } if (flags & CREATE_TURN_SERVER) { - - pj_sockaddr bound_addr; - pj_turn_tp_type tp_type = get_turn_tp_type(flags); - - pj_sockaddr_init(GET_AF(use_ipv6), &bound_addr, NULL, TURN_SERVER_PORT); - - if (tp_type == PJ_TURN_TP_UDP) { - pj_activesock_cb turn_sock_cb; - - pj_bzero(&turn_sock_cb, sizeof(turn_sock_cb)); - turn_sock_cb.on_data_recvfrom = &turn_udp_on_data_recvfrom; - - status = pj_activesock_create_udp(pool, &bound_addr, NULL, - test_srv->stun_cfg->ioqueue, - &turn_sock_cb, test_srv, - &test_srv->turn_sock, NULL); - - if (status != PJ_SUCCESS) { - destroy_test_server(test_srv); - RETURN_ERROR(status); - } - - status = pj_activesock_start_recvfrom(test_srv->turn_sock, pool, - MAX_STUN_PKT, 0); - } else if (tp_type == PJ_TURN_TP_TCP) { - pj_sock_t sock_fd; - pj_activesock_cb turn_sock_cb; - - pj_bzero(&turn_sock_cb, sizeof(turn_sock_cb)); - turn_sock_cb.on_accept_complete2 = &turn_tcp_on_accept_complete; - status = pj_sock_socket(GET_AF(use_ipv6), pj_SOCK_STREAM(), 0, - &sock_fd); - if (status != PJ_SUCCESS) { - RETURN_ERROR(status); - } - - { - int val = 1; - pj_sock_setsockopt(sock_fd, pj_SOL_SOCKET(), pj_SO_REUSEADDR(), - &val, sizeof(val)); - } - - status = pj_sock_bind(sock_fd, &bound_addr, - pj_sockaddr_get_len(&bound_addr)); - if (status != PJ_SUCCESS) { - pj_sock_close(sock_fd); - RETURN_ERROR(status); - } - - status = pj_sock_listen(sock_fd, 4); - if (status != PJ_SUCCESS) { - pj_sock_close(sock_fd); - RETURN_ERROR(status); - } - - status = pj_activesock_create(pool, sock_fd, pj_SOCK_STREAM(), - NULL, - test_srv->stun_cfg->ioqueue, - &turn_sock_cb, test_srv, - &test_srv->turn_sock); - if (status != PJ_SUCCESS) { - pj_sock_close(sock_fd); - RETURN_ERROR(status); - } - - status = pj_activesock_start_accept(test_srv->turn_sock, - pool); - } + + pj_sockaddr bound_addr; + pj_turn_tp_type tp_type = get_turn_tp_type(flags); + + pj_sockaddr_init(GET_AF(use_ipv6), &bound_addr, NULL, TURN_SERVER_PORT); + + if (tp_type == PJ_TURN_TP_UDP) { + pj_activesock_cb turn_sock_cb; + + pj_bzero(&turn_sock_cb, sizeof(turn_sock_cb)); + turn_sock_cb.on_data_recvfrom = &turn_udp_on_data_recvfrom; + + status = pj_activesock_create_udp(pool, &bound_addr, NULL, + test_srv->stun_cfg->ioqueue, + &turn_sock_cb, test_srv, + &test_srv->turn_sock, NULL); + + if (status != PJ_SUCCESS) { + destroy_test_server(test_srv); + RETURN_ERROR(status); + } + + status = pj_activesock_start_recvfrom(test_srv->turn_sock, pool, + MAX_STUN_PKT, 0); + } else if (tp_type == PJ_TURN_TP_TCP) { + pj_sock_t sock_fd; + pj_activesock_cb turn_sock_cb; + + pj_bzero(&turn_sock_cb, sizeof(turn_sock_cb)); + turn_sock_cb.on_accept_complete2 = &turn_tcp_on_accept_complete; + status = pj_sock_socket(GET_AF(use_ipv6), pj_SOCK_STREAM(), 0, + &sock_fd); + if (status != PJ_SUCCESS) { + RETURN_ERROR(status); + } + + { + int val = 1; + pj_sock_setsockopt(sock_fd, pj_SOL_SOCKET(), pj_SO_REUSEADDR(), + &val, sizeof(val)); + } + + status = pj_sock_bind(sock_fd, &bound_addr, + pj_sockaddr_get_len(&bound_addr)); + if (status != PJ_SUCCESS) { + pj_sock_close(sock_fd); + RETURN_ERROR(status); + } + + status = pj_sock_listen(sock_fd, 4); + if (status != PJ_SUCCESS) { + pj_sock_close(sock_fd); + RETURN_ERROR(status); + } + + status = pj_activesock_create(pool, sock_fd, pj_SOCK_STREAM(), + NULL, + test_srv->stun_cfg->ioqueue, + &turn_sock_cb, test_srv, + &test_srv->turn_sock); + if (status != PJ_SUCCESS) { + pj_sock_close(sock_fd); + RETURN_ERROR(status); + } + + status = pj_activesock_start_accept(test_srv->turn_sock, + pool); + } #if USE_TLS - else if (tp_type == PJ_TURN_TP_TLS) { - pj_ssl_sock_t *ssock_serv = NULL; - pj_ssl_sock_param ssl_param; - pj_ssl_cert_t *cert = NULL; - pj_str_t ca_file = pj_str(CERT_CA_FILE); - pj_str_t cert_file = pj_str(CERT_FILE); - pj_str_t privkey_file = pj_str(CERT_PRIVKEY_FILE); - pj_str_t privkey_pass = pj_str(CERT_PRIVKEY_PASS); - - pj_ssl_sock_param_default(&ssl_param); - ssl_param.cb.on_accept_complete2 = &turn_tls_on_accept_complete2; - ssl_param.cb.on_data_read = &turn_tls_on_data_read; - ssl_param.ioqueue = test_srv->stun_cfg->ioqueue; - ssl_param.timer_heap = test_srv->stun_cfg->timer_heap; - ssl_param.user_data = test_srv; - ssl_param.sock_af = GET_AF(use_ipv6); - - status = pj_ssl_sock_create(pool, &ssl_param, &ssock_serv); - if (status != PJ_SUCCESS) { - if (ssock_serv) - pj_ssl_sock_close(ssock_serv); - } - - status = pj_ssl_cert_load_from_files(pool, &ca_file, &cert_file, - &privkey_file, &privkey_pass, - &cert); - if (status != PJ_SUCCESS) { - if (ssock_serv) - pj_ssl_sock_close(ssock_serv); - } - - status = pj_ssl_sock_set_certificate(ssock_serv, pool, cert); - if (status != PJ_SUCCESS) { - if (ssock_serv) - pj_ssl_sock_close(ssock_serv); - } - test_srv->ssl_srv_sock = ssock_serv; - status = pj_ssl_sock_start_accept(ssock_serv, pool, &bound_addr, - pj_sockaddr_get_len(&bound_addr)); - } + else if (tp_type == PJ_TURN_TP_TLS) { + pj_ssl_sock_t *ssock_serv = NULL; + pj_ssl_sock_param ssl_param; + pj_ssl_cert_t *cert = NULL; + pj_str_t ca_file = pj_str(CERT_CA_FILE); + pj_str_t cert_file = pj_str(CERT_FILE); + pj_str_t privkey_file = pj_str(CERT_PRIVKEY_FILE); + pj_str_t privkey_pass = pj_str(CERT_PRIVKEY_PASS); + + pj_ssl_sock_param_default(&ssl_param); + ssl_param.cb.on_accept_complete2 = &turn_tls_on_accept_complete2; + ssl_param.cb.on_data_read = &turn_tls_on_data_read; + ssl_param.ioqueue = test_srv->stun_cfg->ioqueue; + ssl_param.timer_heap = test_srv->stun_cfg->timer_heap; + ssl_param.user_data = test_srv; + ssl_param.sock_af = GET_AF(use_ipv6); + + status = pj_ssl_sock_create(pool, &ssl_param, &ssock_serv); + if (status != PJ_SUCCESS) { + if (ssock_serv) + pj_ssl_sock_close(ssock_serv); + } + + status = pj_ssl_cert_load_from_files(pool, &ca_file, &cert_file, + &privkey_file, &privkey_pass, + &cert); + if (status != PJ_SUCCESS) { + if (ssock_serv) + pj_ssl_sock_close(ssock_serv); + } + + status = pj_ssl_sock_set_certificate(ssock_serv, pool, cert); + if (status != PJ_SUCCESS) { + if (ssock_serv) + pj_ssl_sock_close(ssock_serv); + } + test_srv->ssl_srv_sock = ssock_serv; + status = pj_ssl_sock_start_accept(ssock_serv, pool, &bound_addr, + pj_sockaddr_get_len(&bound_addr)); + } #endif - if (status != PJ_SUCCESS) { - destroy_test_server(test_srv); - RETURN_ERROR(status); - } - - if (test_srv->dns_server && (flags & CREATE_TURN_SERVER_DNS_SRV)) { - pj_str_t res_name, target; - pj_dns_parsed_rr rr; - - /* Add DNS entries: - * _turn._udp.domain 60 IN SRV 0 0 PORT turn.domain. - * turn.domain IN A 127.0.0.1 - */ - switch (tp_type) { - case PJ_TURN_TP_TCP: - pj_ansi_snprintf(strbuf, sizeof(strbuf), - "_turn._tcp.%s", domain); - break; - case PJ_TURN_TP_TLS: - pj_ansi_snprintf(strbuf, sizeof(strbuf), - "_turns._tcp.%s", domain); - break; - default: - pj_ansi_snprintf(strbuf, sizeof(strbuf), - "_turn._udp.%s", domain); - - } - pj_strdup2(pool, &res_name, strbuf); - pj_ansi_snprintf(strbuf, sizeof(strbuf), - "turn.%s", domain); - pj_strdup2(pool, &target, strbuf); - pj_dns_init_srv_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, 0, 0, - TURN_SERVER_PORT, &target); - pj_dns_server_add_rec(test_srv->dns_server, 1, &rr); - - res_name = target; - - if (use_ipv6) { - pj_dns_init_aaaa_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, - &hostip.ipv6.sin6_addr); - } else { - pj_dns_init_a_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, - &hostip.ipv4.sin_addr); - } - pj_dns_server_add_rec(test_srv->dns_server, 1, &rr); - } + if (status != PJ_SUCCESS) { + destroy_test_server(test_srv); + RETURN_ERROR(status); + } + + if (test_srv->dns_server && (flags & CREATE_TURN_SERVER_DNS_SRV)) { + pj_str_t res_name, target; + pj_dns_parsed_rr rr; + + /* Add DNS entries: + * _turn._udp.domain 60 IN SRV 0 0 PORT turn.domain. + * turn.domain IN A 127.0.0.1 + */ + switch (tp_type) { + case PJ_TURN_TP_TCP: + pj_ansi_snprintf(strbuf, sizeof(strbuf), + "_turn._tcp.%s", domain); + break; + case PJ_TURN_TP_TLS: + pj_ansi_snprintf(strbuf, sizeof(strbuf), + "_turns._tcp.%s", domain); + break; + default: + pj_ansi_snprintf(strbuf, sizeof(strbuf), + "_turn._udp.%s", domain); + + } + pj_strdup2(pool, &res_name, strbuf); + pj_ansi_snprintf(strbuf, sizeof(strbuf), + "turn.%s", domain); + pj_strdup2(pool, &target, strbuf); + pj_dns_init_srv_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, 0, 0, + TURN_SERVER_PORT, &target); + pj_dns_server_add_rec(test_srv->dns_server, 1, &rr); + + res_name = target; + + if (use_ipv6) { + pj_dns_init_aaaa_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, + &hostip.ipv6.sin6_addr); + } else { + pj_dns_init_a_rr(&rr, &res_name, PJ_DNS_CLASS_IN, 60, + &hostip.ipv4.sin_addr); + } + pj_dns_server_add_rec(test_srv->dns_server, 1, &rr); + } } *p_test_srv = test_srv; @@ -374,51 +373,51 @@ void destroy_test_server(test_server *test_srv) PJ_ASSERT_ON_FAIL(test_srv, return); for (i=0; iturn_alloc_cnt; ++i) { - pj_activesock_close(test_srv->turn_alloc[i].sock); - pj_pool_release(test_srv->turn_alloc[i].pool); + pj_activesock_close(test_srv->turn_alloc[i].sock); + pj_pool_release(test_srv->turn_alloc[i].pool); } test_srv->turn_alloc_cnt = 0; if (test_srv->turn_sock) { - pj_activesock_close(test_srv->turn_sock); - test_srv->turn_sock = NULL; + pj_activesock_close(test_srv->turn_sock); + test_srv->turn_sock = NULL; } if (test_srv->cl_turn_sock) { - pj_activesock_close(test_srv->cl_turn_sock); - test_srv->cl_turn_sock = NULL; + pj_activesock_close(test_srv->cl_turn_sock); + test_srv->cl_turn_sock = NULL; } #if USE_TLS if (test_srv->ssl_srv_sock) { - pj_ssl_sock_close(test_srv->ssl_srv_sock); - test_srv->ssl_srv_sock = NULL; + pj_ssl_sock_close(test_srv->ssl_srv_sock); + test_srv->ssl_srv_sock = NULL; } if (test_srv->ssl_cl_sock) { - pj_ssl_sock_close(test_srv->ssl_cl_sock); - test_srv->ssl_cl_sock = NULL; + pj_ssl_sock_close(test_srv->ssl_cl_sock); + test_srv->ssl_cl_sock = NULL; } #endif if (test_srv->stun_sock) { - pj_activesock_close(test_srv->stun_sock); - test_srv->stun_sock = NULL; + pj_activesock_close(test_srv->stun_sock); + test_srv->stun_sock = NULL; } if (test_srv->dns_server) { - pj_dns_server_destroy(test_srv->dns_server); - test_srv->dns_server = NULL; + pj_dns_server_destroy(test_srv->dns_server); + test_srv->dns_server = NULL; } pj_pool_safe_release(&test_srv->pool); } static pj_bool_t stun_on_data_recvfrom(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status) + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status) { test_server *test_srv; pj_stun_msg *req, *resp = NULL; @@ -426,39 +425,39 @@ static pj_bool_t stun_on_data_recvfrom(pj_activesock_t *asock, pj_ssize_t len; if (status != PJ_SUCCESS) - return PJ_TRUE; + return PJ_TRUE; test_srv = (test_server*) pj_activesock_get_user_data(asock); pool = pj_pool_create(test_srv->stun_cfg->pf, NULL, 512, 512, NULL); status = pj_stun_msg_decode(pool, (pj_uint8_t*)data, size, - PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET, - &req, NULL, NULL); + PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET, + &req, NULL, NULL); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; if (req->hdr.type != PJ_STUN_BINDING_REQUEST) { - pj_stun_msg_create_response(pool, req, PJ_STUN_SC_BAD_REQUEST, - NULL, &resp); - goto send_pkt; + pj_stun_msg_create_response(pool, req, PJ_STUN_SC_BAD_REQUEST, + NULL, &resp); + goto send_pkt; } status = pj_stun_msg_create_response(pool, req, 0, NULL, &resp); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; pj_stun_msg_add_sockaddr_attr(pool, resp, PJ_STUN_ATTR_XOR_MAPPED_ADDR, - PJ_TRUE, src_addr, addr_len); + PJ_TRUE, src_addr, addr_len); send_pkt: status = pj_stun_msg_encode(resp, (pj_uint8_t*)data, MAX_STUN_PKT, - 0, NULL, &size); + 0, NULL, &size); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; len = size; status = pj_activesock_sendto(asock, &test_srv->send_key, data, &len, - 0, src_addr, addr_len); + 0, src_addr, addr_len); on_return: pj_pool_release(pool); @@ -467,11 +466,11 @@ static pj_bool_t stun_on_data_recvfrom(pj_activesock_t *asock, static pj_stun_msg* create_success_response(test_server *test_srv, - turn_allocation *alloc, - pj_stun_msg *req, - pj_pool_t *pool, - unsigned lifetime, - pj_str_t *auth_key) + turn_allocation *alloc, + pj_stun_msg *req, + pj_pool_t *pool, + unsigned lifetime, + pj_str_t *auth_key) { pj_stun_msg *resp; pj_str_t tmp; @@ -480,19 +479,19 @@ static pj_stun_msg* create_success_response(test_server *test_srv, /* Create response */ status = pj_stun_msg_create_response(pool, req, 0, NULL, &resp); if (status != PJ_SUCCESS) { - return NULL; + return NULL; } /* Add TURN_NONCE */ pj_stun_msg_add_string_attr(pool, resp, PJ_STUN_ATTR_NONCE, pj_cstr(&tmp, TURN_NONCE)); /* Add LIFETIME */ pj_stun_msg_add_uint_attr(pool, resp, PJ_STUN_ATTR_LIFETIME, lifetime); if (lifetime != 0) { - /* Add XOR-RELAYED-ADDRESS */ - pj_stun_msg_add_sockaddr_attr(pool, resp, PJ_STUN_ATTR_XOR_RELAYED_ADDR, PJ_TRUE, &alloc->alloc_addr, - pj_sockaddr_get_len(&alloc->alloc_addr)); - /* Add XOR-MAPPED-ADDRESS */ - pj_stun_msg_add_sockaddr_attr(pool, resp, PJ_STUN_ATTR_XOR_MAPPED_ADDR, PJ_TRUE, &alloc->client_addr, - pj_sockaddr_get_len(&alloc->client_addr)); + /* Add XOR-RELAYED-ADDRESS */ + pj_stun_msg_add_sockaddr_attr(pool, resp, PJ_STUN_ATTR_XOR_RELAYED_ADDR, PJ_TRUE, &alloc->alloc_addr, + pj_sockaddr_get_len(&alloc->alloc_addr)); + /* Add XOR-MAPPED-ADDRESS */ + pj_stun_msg_add_sockaddr_attr(pool, resp, PJ_STUN_ATTR_XOR_MAPPED_ADDR, PJ_TRUE, &alloc->client_addr, + pj_sockaddr_get_len(&alloc->client_addr)); } /* Add blank MESSAGE-INTEGRITY */ @@ -500,47 +499,47 @@ static pj_stun_msg* create_success_response(test_server *test_srv, /* Set auth key */ pj_stun_create_key(pool, auth_key, &test_srv->domain, &test_srv->username, - PJ_STUN_PASSWD_PLAIN, &test_srv->passwd); + PJ_STUN_PASSWD_PLAIN, &test_srv->passwd); return resp; } static pj_bool_t turn_tcp_on_data_read(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { test_server *test_srv = (test_server *)pj_activesock_get_user_data(asock); PJ_UNUSED_ARG(remainder); return turn_on_data_read(test_srv, data, size, &test_srv->remote_addr, - sizeof(test_srv->remote_addr), status); + sizeof(test_srv->remote_addr), status); } #if USE_TLS static pj_bool_t turn_tls_on_data_read(pj_ssl_sock_t *ssl_sock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { test_server *test_srv = (test_server *)pj_ssl_sock_get_user_data(ssl_sock); PJ_UNUSED_ARG(remainder); return turn_on_data_read(test_srv, data, size, - &test_srv->remote_addr, - sizeof(test_srv->remote_addr), - status); + &test_srv->remote_addr, + sizeof(test_srv->remote_addr), + status); } #endif static pj_bool_t turn_udp_on_data_recvfrom(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status) + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status) { test_server *test_srv; test_srv = (test_server*) pj_activesock_get_user_data(asock); @@ -548,11 +547,11 @@ static pj_bool_t turn_udp_on_data_recvfrom(pj_activesock_t *asock, } static pj_bool_t turn_on_data_read(test_server *test_srv, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status) + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status) { pj_pool_t *pool; @@ -565,7 +564,7 @@ static pj_bool_t turn_on_data_read(test_server *test_srv, pj_bool_t use_ipv6 = PJ_FALSE; if (status != PJ_SUCCESS) - return PJ_TRUE; + return PJ_TRUE; pj_sockaddr_print(src_addr, client_info, sizeof(client_info), 3); @@ -574,360 +573,360 @@ static pj_bool_t turn_on_data_read(test_server *test_srv, /* Find the client */ for (i=0; iturn_alloc_cnt; i++) { - if (pj_sockaddr_cmp(&test_srv->turn_alloc[i].client_addr, src_addr)==0) - break; + if (pj_sockaddr_cmp(&test_srv->turn_alloc[i].client_addr, src_addr)==0) + break; } if (pj_stun_msg_check((pj_uint8_t*)data, size, - PJ_STUN_NO_FINGERPRINT_CHECK)!=PJ_SUCCESS) + PJ_STUN_NO_FINGERPRINT_CHECK)!=PJ_SUCCESS) { - /* Not STUN message, this probably is a ChannelData */ - pj_turn_channel_data cd; - const pj_turn_channel_data *pcd = (const pj_turn_channel_data*)data; - char peer_info[PJ_INET6_ADDRSTRLEN]; - pj_ssize_t sent; - unsigned j; - - if (i==test_srv->turn_alloc_cnt) { - /* Invalid data */ - PJ_LOG(1,(THIS_FILE, - "TURN Server received strayed data")); - goto on_return; - } - - alloc = &test_srv->turn_alloc[i]; - - cd.ch_number = pj_ntohs(pcd->ch_number); - cd.length = pj_ntohs(pcd->length); - - /* For UDP check the packet length */ - if (size < cd.length+sizeof(cd)) { - PJ_LOG(1,(THIS_FILE, - "TURN Server: ChannelData discarded: UDP size error")); - goto on_return; - } - - /* Lookup peer */ - for (j=0; jperm_cnt; ++j) { - if (alloc->chnum[j] == cd.ch_number) - break; - } - - if (j==alloc->perm_cnt) { - PJ_LOG(1,(THIS_FILE, - "TURN Server: ChannelData discarded: invalid channel number")); - goto on_return; - } - - /* Relay the data to peer */ - pj_sockaddr_print(&alloc->perm[j], peer_info, sizeof(peer_info), 3); - PJ_LOG(5,(THIS_FILE, "Relaying %d bytes data from client %s to peer %s", - cd.length, client_info, peer_info)); - sent = cd.length; - pj_activesock_sendto(alloc->sock, &alloc->send_key, - pcd+1, &sent, 0, - &alloc->perm[j], - pj_sockaddr_get_len(&alloc->perm[j])); - - /* Done */ - goto on_return; + /* Not STUN message, this probably is a ChannelData */ + pj_turn_channel_data cd; + const pj_turn_channel_data *pcd = (const pj_turn_channel_data*)data; + char peer_info[PJ_INET6_ADDRSTRLEN]; + pj_ssize_t sent; + unsigned j; + + if (i==test_srv->turn_alloc_cnt) { + /* Invalid data */ + PJ_LOG(1,(THIS_FILE, + "TURN Server received strayed data")); + goto on_return; + } + + alloc = &test_srv->turn_alloc[i]; + + cd.ch_number = pj_ntohs(pcd->ch_number); + cd.length = pj_ntohs(pcd->length); + + /* For UDP check the packet length */ + if (size < cd.length+sizeof(cd)) { + PJ_LOG(1,(THIS_FILE, + "TURN Server: ChannelData discarded: UDP size error")); + goto on_return; + } + + /* Lookup peer */ + for (j=0; jperm_cnt; ++j) { + if (alloc->chnum[j] == cd.ch_number) + break; + } + + if (j==alloc->perm_cnt) { + PJ_LOG(1,(THIS_FILE, + "TURN Server: ChannelData discarded: invalid channel number")); + goto on_return; + } + + /* Relay the data to peer */ + pj_sockaddr_print(&alloc->perm[j], peer_info, sizeof(peer_info), 3); + PJ_LOG(5,(THIS_FILE, "Relaying %d bytes data from client %s to peer %s", + cd.length, client_info, peer_info)); + sent = cd.length; + pj_activesock_sendto(alloc->sock, &alloc->send_key, + pcd+1, &sent, 0, + &alloc->perm[j], + pj_sockaddr_get_len(&alloc->perm[j])); + + /* Done */ + goto on_return; } status = pj_stun_msg_decode(pool, (pj_uint8_t*)data, size, - PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET | - PJ_STUN_NO_FINGERPRINT_CHECK, - &req, NULL, NULL); + PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET | + PJ_STUN_NO_FINGERPRINT_CHECK, + &req, NULL, NULL); if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(1,("", "STUN message decode error from client %s: %s", client_info, errmsg)); - goto on_return; + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(1,("", "STUN message decode error from client %s: %s", client_info, errmsg)); + goto on_return; } if (i==test_srv->turn_alloc_cnt) { - /* New client */ - //pj_str_t ip_addr; - pj_stun_username_attr *uname; - pj_activesock_cb alloc_sock_cb; - ///turn_allocation *alloc; - - /* Must be Allocate request */ - if (req->hdr.type != PJ_STUN_ALLOCATE_REQUEST) { - PJ_LOG(1,(THIS_FILE, "Invalid %s %s from client %s", - pj_stun_get_method_name(req->hdr.type), - pj_stun_get_class_name(req->hdr.type), - client_info)); - - if (PJ_STUN_IS_REQUEST(req->hdr.type)) - pj_stun_msg_create_response(pool, req, PJ_STUN_SC_BAD_REQUEST, NULL, &resp); - goto send_pkt; - } - - test_srv->turn_stat.rx_allocate_cnt++; - - /* Skip if we're not responding to Allocate request */ - if (!test_srv->turn_respond_allocate) - return PJ_TRUE; - - /* Check if we have too many clients */ - if (test_srv->turn_alloc_cnt == MAX_TURN_ALLOC) { - pj_stun_msg_create_response(pool, req, PJ_STUN_SC_INSUFFICIENT_CAPACITY, NULL, &resp); - goto send_pkt; - } - - /* Get USERNAME attribute */ - uname = (pj_stun_username_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_USERNAME, 0); - - /* Reject if it doesn't have MESSAGE-INTEGRITY or USERNAME attributes or - * the user is incorrect - */ - if (pj_stun_msg_find_attr(req, PJ_STUN_ATTR_MESSAGE_INTEGRITY, 0) == NULL || - uname==NULL || pj_stricmp2(&uname->value, TURN_USERNAME) != 0) - { - pj_str_t tmp; - - pj_stun_msg_create_response(pool, req, PJ_STUN_SC_UNAUTHORIZED, NULL, &resp); - pj_stun_msg_add_string_attr(pool, resp, PJ_STUN_ATTR_REALM, &test_srv->domain); - pj_stun_msg_add_string_attr(pool, resp, PJ_STUN_ATTR_NONCE, pj_cstr(&tmp, TURN_NONCE)); - goto send_pkt; - } - - pj_bzero(&alloc_sock_cb, sizeof(alloc_sock_cb)); - alloc_sock_cb.on_data_recvfrom = &alloc_on_data_recvfrom; - - /* Create allocation */ - alloc = &test_srv->turn_alloc[test_srv->turn_alloc_cnt]; - alloc->perm_cnt = 0; - alloc->test_srv = test_srv; - pj_memcpy(&alloc->client_addr, src_addr, addr_len); - pj_ioqueue_op_key_init(&alloc->send_key, sizeof(alloc->send_key)); - - alloc->pool = pj_pool_create(test_srv->stun_cfg->pf, "alloc", 512, 512, NULL); - - /* Create relay socket */ - pj_sockaddr_init(GET_AF(use_ipv6), &alloc->alloc_addr, NULL, 0); - if (use_ipv6) { - /* pj_gethostip() may return IPv6 link-local and will cause EINVAL - * error, so let's just hardcode it. - */ - pj_sockaddr_init(pj_AF_INET6(), &alloc->alloc_addr, NULL, 0); - alloc->alloc_addr.ipv6.sin6_addr.s6_addr[15] = 1; - } else { - status = pj_gethostip(GET_AF(use_ipv6), &alloc->alloc_addr); - if (status != PJ_SUCCESS) { - pj_pool_release(alloc->pool); - pj_stun_msg_create_response(pool, req, PJ_STUN_SC_SERVER_ERROR, - NULL, &resp); - goto send_pkt; - } - } - - status = pj_activesock_create_udp(alloc->pool, &alloc->alloc_addr, NULL, - test_srv->stun_cfg->ioqueue, - &alloc_sock_cb, alloc, - &alloc->sock, &alloc->alloc_addr); - if (status != PJ_SUCCESS) { - pj_pool_release(alloc->pool); - pj_stun_msg_create_response(pool, req, PJ_STUN_SC_SERVER_ERROR, NULL, &resp); - goto send_pkt; - } - //pj_sockaddr_set_str_addr(pj_AF_INET(), &alloc->alloc_addr, &ip_addr); - - pj_activesock_set_user_data(alloc->sock, alloc); - - status = pj_activesock_start_recvfrom(alloc->sock, alloc->pool, 1500, 0); - if (status != PJ_SUCCESS) { - pj_activesock_close(alloc->sock); - pj_pool_release(alloc->pool); - pj_stun_msg_create_response(pool, req, PJ_STUN_SC_SERVER_ERROR, NULL, &resp); - goto send_pkt; - } - - /* Create Data indication */ - status = pj_stun_msg_create(alloc->pool, PJ_STUN_DATA_INDICATION, - PJ_STUN_MAGIC, NULL, &alloc->data_ind); - if (status != PJ_SUCCESS) { - pj_activesock_close(alloc->sock); - pj_pool_release(alloc->pool); - pj_stun_msg_create_response(pool, req, PJ_STUN_SC_SERVER_ERROR, NULL, &resp); - goto send_pkt; - } - pj_stun_msg_add_sockaddr_attr(alloc->pool, alloc->data_ind, - PJ_STUN_ATTR_XOR_PEER_ADDR, PJ_TRUE, - &alloc->alloc_addr, - pj_sockaddr_get_len(&alloc->alloc_addr)); - pj_stun_msg_add_binary_attr(alloc->pool, alloc->data_ind, - PJ_STUN_ATTR_DATA, (pj_uint8_t*)"", 1); - - /* Create response */ - resp = create_success_response(test_srv, alloc, req, pool, 600, &auth_key); - if (resp == NULL) { - pj_activesock_close(alloc->sock); - pj_pool_release(alloc->pool); - pj_stun_msg_create_response(pool, req, PJ_STUN_SC_SERVER_ERROR, NULL, &resp); - goto send_pkt; - } - - ++test_srv->turn_alloc_cnt; + /* New client */ + //pj_str_t ip_addr; + pj_stun_username_attr *uname; + pj_activesock_cb alloc_sock_cb; + ///turn_allocation *alloc; + + /* Must be Allocate request */ + if (req->hdr.type != PJ_STUN_ALLOCATE_REQUEST) { + PJ_LOG(1,(THIS_FILE, "Invalid %s %s from client %s", + pj_stun_get_method_name(req->hdr.type), + pj_stun_get_class_name(req->hdr.type), + client_info)); + + if (PJ_STUN_IS_REQUEST(req->hdr.type)) + pj_stun_msg_create_response(pool, req, PJ_STUN_SC_BAD_REQUEST, NULL, &resp); + goto send_pkt; + } + + test_srv->turn_stat.rx_allocate_cnt++; + + /* Skip if we're not responding to Allocate request */ + if (!test_srv->turn_respond_allocate) + return PJ_TRUE; + + /* Check if we have too many clients */ + if (test_srv->turn_alloc_cnt == MAX_TURN_ALLOC) { + pj_stun_msg_create_response(pool, req, PJ_STUN_SC_INSUFFICIENT_CAPACITY, NULL, &resp); + goto send_pkt; + } + + /* Get USERNAME attribute */ + uname = (pj_stun_username_attr*) + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_USERNAME, 0); + + /* Reject if it doesn't have MESSAGE-INTEGRITY or USERNAME attributes or + * the user is incorrect + */ + if (pj_stun_msg_find_attr(req, PJ_STUN_ATTR_MESSAGE_INTEGRITY, 0) == NULL || + uname==NULL || pj_stricmp2(&uname->value, TURN_USERNAME) != 0) + { + pj_str_t tmp; + + pj_stun_msg_create_response(pool, req, PJ_STUN_SC_UNAUTHORIZED, NULL, &resp); + pj_stun_msg_add_string_attr(pool, resp, PJ_STUN_ATTR_REALM, &test_srv->domain); + pj_stun_msg_add_string_attr(pool, resp, PJ_STUN_ATTR_NONCE, pj_cstr(&tmp, TURN_NONCE)); + goto send_pkt; + } + + pj_bzero(&alloc_sock_cb, sizeof(alloc_sock_cb)); + alloc_sock_cb.on_data_recvfrom = &alloc_on_data_recvfrom; + + /* Create allocation */ + alloc = &test_srv->turn_alloc[test_srv->turn_alloc_cnt]; + alloc->perm_cnt = 0; + alloc->test_srv = test_srv; + pj_memcpy(&alloc->client_addr, src_addr, addr_len); + pj_ioqueue_op_key_init(&alloc->send_key, sizeof(alloc->send_key)); + + alloc->pool = pj_pool_create(test_srv->stun_cfg->pf, "alloc", 512, 512, NULL); + + /* Create relay socket */ + pj_sockaddr_init(GET_AF(use_ipv6), &alloc->alloc_addr, NULL, 0); + if (use_ipv6) { + /* pj_gethostip() may return IPv6 link-local and will cause EINVAL + * error, so let's just hardcode it. + */ + pj_sockaddr_init(pj_AF_INET6(), &alloc->alloc_addr, NULL, 0); + alloc->alloc_addr.ipv6.sin6_addr.s6_addr[15] = 1; + } else { + status = pj_gethostip(GET_AF(use_ipv6), &alloc->alloc_addr); + if (status != PJ_SUCCESS) { + pj_pool_release(alloc->pool); + pj_stun_msg_create_response(pool, req, PJ_STUN_SC_SERVER_ERROR, + NULL, &resp); + goto send_pkt; + } + } + + status = pj_activesock_create_udp(alloc->pool, &alloc->alloc_addr, NULL, + test_srv->stun_cfg->ioqueue, + &alloc_sock_cb, alloc, + &alloc->sock, &alloc->alloc_addr); + if (status != PJ_SUCCESS) { + pj_pool_release(alloc->pool); + pj_stun_msg_create_response(pool, req, PJ_STUN_SC_SERVER_ERROR, NULL, &resp); + goto send_pkt; + } + //pj_sockaddr_set_str_addr(pj_AF_INET(), &alloc->alloc_addr, &ip_addr); + + pj_activesock_set_user_data(alloc->sock, alloc); + + status = pj_activesock_start_recvfrom(alloc->sock, alloc->pool, 1500, 0); + if (status != PJ_SUCCESS) { + pj_activesock_close(alloc->sock); + pj_pool_release(alloc->pool); + pj_stun_msg_create_response(pool, req, PJ_STUN_SC_SERVER_ERROR, NULL, &resp); + goto send_pkt; + } + + /* Create Data indication */ + status = pj_stun_msg_create(alloc->pool, PJ_STUN_DATA_INDICATION, + PJ_STUN_MAGIC, NULL, &alloc->data_ind); + if (status != PJ_SUCCESS) { + pj_activesock_close(alloc->sock); + pj_pool_release(alloc->pool); + pj_stun_msg_create_response(pool, req, PJ_STUN_SC_SERVER_ERROR, NULL, &resp); + goto send_pkt; + } + pj_stun_msg_add_sockaddr_attr(alloc->pool, alloc->data_ind, + PJ_STUN_ATTR_XOR_PEER_ADDR, PJ_TRUE, + &alloc->alloc_addr, + pj_sockaddr_get_len(&alloc->alloc_addr)); + pj_stun_msg_add_binary_attr(alloc->pool, alloc->data_ind, + PJ_STUN_ATTR_DATA, (pj_uint8_t*)"", 1); + + /* Create response */ + resp = create_success_response(test_srv, alloc, req, pool, 600, &auth_key); + if (resp == NULL) { + pj_activesock_close(alloc->sock); + pj_pool_release(alloc->pool); + pj_stun_msg_create_response(pool, req, PJ_STUN_SC_SERVER_ERROR, NULL, &resp); + goto send_pkt; + } + + ++test_srv->turn_alloc_cnt; } else { - alloc = &test_srv->turn_alloc[i]; - - if (req->hdr.type == PJ_STUN_ALLOCATE_REQUEST) { - - test_srv->turn_stat.rx_allocate_cnt++; - - /* Skip if we're not responding to Allocate request */ - if (!test_srv->turn_respond_allocate) - return PJ_TRUE; - - resp = create_success_response(test_srv, alloc, req, pool, 0, &auth_key); - - } else if (req->hdr.type == PJ_STUN_REFRESH_REQUEST) { - pj_stun_lifetime_attr *lf_attr; - - test_srv->turn_stat.rx_refresh_cnt++; - - /* Skip if we're not responding to Refresh request */ - if (!test_srv->turn_respond_refresh) - return PJ_TRUE; - - lf_attr = (pj_stun_lifetime_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_LIFETIME, 0); - if (lf_attr && lf_attr->value != 0) { - resp = create_success_response(test_srv, alloc, req, pool, 600, &auth_key); - pj_array_erase(test_srv->turn_alloc, sizeof(test_srv->turn_alloc[0]), - test_srv->turn_alloc_cnt, i); - --test_srv->turn_alloc_cnt; - } else - resp = create_success_response(test_srv, alloc, req, pool, 0, &auth_key); - } else if (req->hdr.type == PJ_STUN_CREATE_PERM_REQUEST) { - for (i=0; iattr_count; ++i) { - if (req->attr[i]->type == PJ_STUN_ATTR_XOR_PEER_ADDR) { - pj_stun_xor_peer_addr_attr *pa = (pj_stun_xor_peer_addr_attr*)req->attr[i]; - unsigned j; - - for (j=0; jperm_cnt; ++j) { - if (pj_sockaddr_cmp(&alloc->perm[j], &pa->sockaddr)==0) - break; - } - - if (j==alloc->perm_cnt && alloc->perm_cnt < MAX_TURN_PERM) { - char peer_info[PJ_INET6_ADDRSTRLEN]; - pj_sockaddr_print(&pa->sockaddr, peer_info, sizeof(peer_info), 3); - - pj_sockaddr_cp(&alloc->perm[alloc->perm_cnt], &pa->sockaddr); - ++alloc->perm_cnt; - - PJ_LOG(5,("", "Permission %s added to client %s, perm_cnt=%d", - peer_info, client_info, alloc->perm_cnt)); - } - - } - } - resp = create_success_response(test_srv, alloc, req, pool, 0, &auth_key); - } else if (req->hdr.type == PJ_STUN_SEND_INDICATION) { - pj_stun_xor_peer_addr_attr *pa; - pj_stun_data_attr *da; - - test_srv->turn_stat.rx_send_ind_cnt++; - - pa = (pj_stun_xor_peer_addr_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_XOR_PEER_ADDR, 0); - da = (pj_stun_data_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_DATA, 0); - if (pa && da) { - unsigned j; - char peer_info[PJ_INET6_ADDRSTRLEN]; - pj_ssize_t sent; - - pj_sockaddr_print(&pa->sockaddr, peer_info, sizeof(peer_info), 3); - - for (j=0; jperm_cnt; ++j) { - if (pj_sockaddr_cmp(&alloc->perm[j], &pa->sockaddr)==0) - break; - } - - if (j==alloc->perm_cnt) { - PJ_LOG(5,("", "SendIndication to %s is rejected (no permission)", - peer_info, client_info, alloc->perm_cnt)); - } else { - PJ_LOG(5,(THIS_FILE, "Relaying %d bytes data from client %s to peer %s, " - "perm_cnt=%d", - da->length, client_info, peer_info, alloc->perm_cnt)); - - sent = da->length; - pj_activesock_sendto(alloc->sock, &alloc->send_key, - da->data, &sent, 0, - &pa->sockaddr, - pj_sockaddr_get_len(&pa->sockaddr)); - } - } else { - PJ_LOG(1,(THIS_FILE, "Invalid Send Indication from %s", client_info)); - } - } else if (req->hdr.type == PJ_STUN_CHANNEL_BIND_REQUEST) { - pj_stun_xor_peer_addr_attr *pa; - pj_stun_channel_number_attr *cna; - unsigned j, cn; - - pa = (pj_stun_xor_peer_addr_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_XOR_PEER_ADDR, 0); - cna = (pj_stun_channel_number_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_CHANNEL_NUMBER, 0); - cn = PJ_STUN_GET_CH_NB(cna->value); - - resp = create_success_response(test_srv, alloc, req, pool, 0, &auth_key); - - for (j=0; jperm_cnt; ++j) { - if (pj_sockaddr_cmp(&alloc->perm[j], &pa->sockaddr)==0) - break; - } - - if (j==alloc->perm_cnt) { - if (alloc->perm_cnt==MAX_TURN_PERM) { - pj_stun_msg_create_response(pool, req, PJ_STUN_SC_INSUFFICIENT_CAPACITY, NULL, &resp); - goto send_pkt; - } - pj_sockaddr_cp(&alloc->perm[j], &pa->sockaddr); - ++alloc->perm_cnt; - } - alloc->chnum[j] = cn; - - resp = create_success_response(test_srv, alloc, req, pool, 0, &auth_key); - - } else if (PJ_STUN_IS_REQUEST(req->hdr.type)) { - pj_stun_msg_create_response(pool, req, PJ_STUN_SC_BAD_REQUEST, NULL, &resp); - } + alloc = &test_srv->turn_alloc[i]; + + if (req->hdr.type == PJ_STUN_ALLOCATE_REQUEST) { + + test_srv->turn_stat.rx_allocate_cnt++; + + /* Skip if we're not responding to Allocate request */ + if (!test_srv->turn_respond_allocate) + return PJ_TRUE; + + resp = create_success_response(test_srv, alloc, req, pool, 0, &auth_key); + + } else if (req->hdr.type == PJ_STUN_REFRESH_REQUEST) { + pj_stun_lifetime_attr *lf_attr; + + test_srv->turn_stat.rx_refresh_cnt++; + + /* Skip if we're not responding to Refresh request */ + if (!test_srv->turn_respond_refresh) + return PJ_TRUE; + + lf_attr = (pj_stun_lifetime_attr*) + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_LIFETIME, 0); + if (lf_attr && lf_attr->value != 0) { + resp = create_success_response(test_srv, alloc, req, pool, 600, &auth_key); + pj_array_erase(test_srv->turn_alloc, sizeof(test_srv->turn_alloc[0]), + test_srv->turn_alloc_cnt, i); + --test_srv->turn_alloc_cnt; + } else + resp = create_success_response(test_srv, alloc, req, pool, 0, &auth_key); + } else if (req->hdr.type == PJ_STUN_CREATE_PERM_REQUEST) { + for (i=0; iattr_count; ++i) { + if (req->attr[i]->type == PJ_STUN_ATTR_XOR_PEER_ADDR) { + pj_stun_xor_peer_addr_attr *pa = (pj_stun_xor_peer_addr_attr*)req->attr[i]; + unsigned j; + + for (j=0; jperm_cnt; ++j) { + if (pj_sockaddr_cmp(&alloc->perm[j], &pa->sockaddr)==0) + break; + } + + if (j==alloc->perm_cnt && alloc->perm_cnt < MAX_TURN_PERM) { + char peer_info[PJ_INET6_ADDRSTRLEN]; + pj_sockaddr_print(&pa->sockaddr, peer_info, sizeof(peer_info), 3); + + pj_sockaddr_cp(&alloc->perm[alloc->perm_cnt], &pa->sockaddr); + ++alloc->perm_cnt; + + PJ_LOG(5,("", "Permission %s added to client %s, perm_cnt=%d", + peer_info, client_info, alloc->perm_cnt)); + } + + } + } + resp = create_success_response(test_srv, alloc, req, pool, 0, &auth_key); + } else if (req->hdr.type == PJ_STUN_SEND_INDICATION) { + pj_stun_xor_peer_addr_attr *pa; + pj_stun_data_attr *da; + + test_srv->turn_stat.rx_send_ind_cnt++; + + pa = (pj_stun_xor_peer_addr_attr*) + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_XOR_PEER_ADDR, 0); + da = (pj_stun_data_attr*) + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_DATA, 0); + if (pa && da) { + unsigned j; + char peer_info[PJ_INET6_ADDRSTRLEN]; + pj_ssize_t sent; + + pj_sockaddr_print(&pa->sockaddr, peer_info, sizeof(peer_info), 3); + + for (j=0; jperm_cnt; ++j) { + if (pj_sockaddr_cmp(&alloc->perm[j], &pa->sockaddr)==0) + break; + } + + if (j==alloc->perm_cnt) { + PJ_LOG(5,("", "SendIndication to %s is rejected (no permission)", + peer_info, client_info, alloc->perm_cnt)); + } else { + PJ_LOG(5,(THIS_FILE, "Relaying %d bytes data from client %s to peer %s, " + "perm_cnt=%d", + da->length, client_info, peer_info, alloc->perm_cnt)); + + sent = da->length; + pj_activesock_sendto(alloc->sock, &alloc->send_key, + da->data, &sent, 0, + &pa->sockaddr, + pj_sockaddr_get_len(&pa->sockaddr)); + } + } else { + PJ_LOG(1,(THIS_FILE, "Invalid Send Indication from %s", client_info)); + } + } else if (req->hdr.type == PJ_STUN_CHANNEL_BIND_REQUEST) { + pj_stun_xor_peer_addr_attr *pa; + pj_stun_channel_number_attr *cna; + unsigned j, cn; + + pa = (pj_stun_xor_peer_addr_attr*) + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_XOR_PEER_ADDR, 0); + cna = (pj_stun_channel_number_attr*) + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_CHANNEL_NUMBER, 0); + cn = PJ_STUN_GET_CH_NB(cna->value); + + resp = create_success_response(test_srv, alloc, req, pool, 0, &auth_key); + + for (j=0; jperm_cnt; ++j) { + if (pj_sockaddr_cmp(&alloc->perm[j], &pa->sockaddr)==0) + break; + } + + if (j==alloc->perm_cnt) { + if (alloc->perm_cnt==MAX_TURN_PERM) { + pj_stun_msg_create_response(pool, req, PJ_STUN_SC_INSUFFICIENT_CAPACITY, NULL, &resp); + goto send_pkt; + } + pj_sockaddr_cp(&alloc->perm[j], &pa->sockaddr); + ++alloc->perm_cnt; + } + alloc->chnum[j] = cn; + + resp = create_success_response(test_srv, alloc, req, pool, 0, &auth_key); + + } else if (PJ_STUN_IS_REQUEST(req->hdr.type)) { + pj_stun_msg_create_response(pool, req, PJ_STUN_SC_BAD_REQUEST, NULL, &resp); + } } send_pkt: if (resp) { - pj_turn_tp_type tp_type = get_turn_tp_type(test_srv->flags); - - status = pj_stun_msg_encode(resp, (pj_uint8_t*)data, MAX_STUN_PKT, - 0, &auth_key, &size); - if (status != PJ_SUCCESS) - goto on_return; - - len = size; - switch (tp_type) { - case PJ_TURN_TP_TCP: - status = pj_activesock_send(test_srv->cl_turn_sock, - &test_srv->send_key, data, &len, 0); - break; + pj_turn_tp_type tp_type = get_turn_tp_type(test_srv->flags); + + status = pj_stun_msg_encode(resp, (pj_uint8_t*)data, MAX_STUN_PKT, + 0, &auth_key, &size); + if (status != PJ_SUCCESS) + goto on_return; + + len = size; + switch (tp_type) { + case PJ_TURN_TP_TCP: + status = pj_activesock_send(test_srv->cl_turn_sock, + &test_srv->send_key, data, &len, 0); + break; #if USE_TLS - case PJ_TURN_TP_TLS: - status = pj_ssl_sock_send(test_srv->ssl_cl_sock, - &test_srv->send_key, data, &len, 0); - break; + case PJ_TURN_TP_TLS: + status = pj_ssl_sock_send(test_srv->ssl_cl_sock, + &test_srv->send_key, data, &len, 0); + break; #endif - default: - status = pj_activesock_sendto(test_srv->turn_sock, - &test_srv->send_key, data, - &len, 0, src_addr, addr_len); - } + default: + status = pj_activesock_sendto(test_srv->turn_sock, + &test_srv->send_key, data, + &len, 0, src_addr, addr_len); + } } on_return: @@ -936,10 +935,10 @@ static pj_bool_t turn_on_data_read(test_server *test_srv, } static pj_bool_t turn_tcp_on_accept_complete(pj_activesock_t *asock, - pj_sock_t newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len, - pj_status_t status) + pj_sock_t newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len, + pj_status_t status) { pj_status_t sstatus; pj_activesock_cb asock_cb; @@ -957,14 +956,14 @@ static pj_bool_t turn_tcp_on_accept_complete(pj_activesock_t *asock, sstatus = pj_activesock_create(test_srv->pool, newsock, pj_SOCK_STREAM(), NULL, test_srv->stun_cfg->ioqueue, - &asock_cb, test_srv, - &test_srv->cl_turn_sock); + &asock_cb, test_srv, + &test_srv->cl_turn_sock); if (sstatus != PJ_SUCCESS) { goto on_exit; } sstatus = pj_activesock_start_read(test_srv->cl_turn_sock, - test_srv->pool, MAX_STUN_PKT, 0); + test_srv->pool, MAX_STUN_PKT, 0); if (sstatus != PJ_SUCCESS) { goto on_exit; } @@ -977,7 +976,7 @@ static pj_bool_t turn_tcp_on_accept_complete(pj_activesock_t *asock, if (test_srv->cl_turn_sock) pj_activesock_close(test_srv->turn_sock); else - pj_sock_close(newsock); + pj_sock_close(newsock); return PJ_FALSE; @@ -985,10 +984,10 @@ static pj_bool_t turn_tcp_on_accept_complete(pj_activesock_t *asock, #if USE_TLS static pj_bool_t turn_tls_on_accept_complete2(pj_ssl_sock_t *ssock, - pj_ssl_sock_t *newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len, - pj_status_t status) + pj_ssl_sock_t *newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len, + pj_status_t status) { pj_status_t sstatus; test_server *test_srv = (test_server *) pj_ssl_sock_get_user_data(ssock); @@ -1005,8 +1004,8 @@ static pj_bool_t turn_tls_on_accept_complete2(pj_ssl_sock_t *ssock, sstatus = pj_ssl_sock_start_read(newsock, test_srv->pool, MAX_STUN_PKT, 0); if (sstatus != PJ_SUCCESS) { - pj_ssl_sock_close(newsock); - test_srv->ssl_cl_sock = NULL; + pj_ssl_sock_close(newsock); + test_srv->ssl_cl_sock = NULL; } return PJ_TRUE; @@ -1015,11 +1014,11 @@ static pj_bool_t turn_tls_on_accept_complete2(pj_ssl_sock_t *ssock, /* On received data from peer */ static pj_bool_t alloc_on_data_recvfrom(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status) + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status) { turn_allocation *alloc; pj_stun_xor_peer_addr_attr *pa; @@ -1033,7 +1032,7 @@ static pj_bool_t alloc_on_data_recvfrom(pj_activesock_t *asock, PJ_UNUSED_ARG(addr_len); if (status != PJ_SUCCESS) - return PJ_TRUE; + return PJ_TRUE; alloc = (turn_allocation*) pj_activesock_get_user_data(asock); @@ -1042,24 +1041,24 @@ static pj_bool_t alloc_on_data_recvfrom(pj_activesock_t *asock, /* Check that this peer has a permission */ for (i=0; iperm_cnt; ++i) { - if (pj_sockaddr_cmp(&alloc->perm[i], src_addr) == 0) - { - break; - } + if (pj_sockaddr_cmp(&alloc->perm[i], src_addr) == 0) + { + break; + } } if (i==alloc->perm_cnt) { - PJ_LOG(5,("", "Client %s received %d bytes unauthorized data from peer %s", - client_info, size, peer_info)); - if (alloc->perm_cnt == 0) - PJ_LOG(5,("", "Client %s has no permission", client_info)); - return PJ_TRUE; + PJ_LOG(5,("", "Client %s received %d bytes unauthorized data from peer %s", + client_info, size, peer_info)); + if (alloc->perm_cnt == 0) + PJ_LOG(5,("", "Client %s has no permission", client_info)); + return PJ_TRUE; } /* Format a Data indication */ pa = (pj_stun_xor_peer_addr_attr*) - pj_stun_msg_find_attr(alloc->data_ind, PJ_STUN_ATTR_XOR_PEER_ADDR, 0); + pj_stun_msg_find_attr(alloc->data_ind, PJ_STUN_ATTR_XOR_PEER_ADDR, 0); da = (pj_stun_data_attr*) - pj_stun_msg_find_attr(alloc->data_ind, PJ_STUN_ATTR_DATA, 0); + pj_stun_msg_find_attr(alloc->data_ind, PJ_STUN_ATTR_DATA, 0); pj_assert(pa && da); pj_sockaddr_cp(&pa->sockaddr, src_addr); @@ -1068,18 +1067,18 @@ static pj_bool_t alloc_on_data_recvfrom(pj_activesock_t *asock, /* Encode Data indication */ status = pj_stun_msg_encode(alloc->data_ind, buffer, sizeof(buffer), 0, - NULL, &size); + NULL, &size); if (status != PJ_SUCCESS) - return PJ_TRUE; + return PJ_TRUE; /* Send */ sent = size; PJ_LOG(5,("", "Forwarding %d bytes data from peer %s to client %s", - sent, peer_info, client_info)); + sent, peer_info, client_info)); pj_activesock_sendto(alloc->test_srv->turn_sock, &alloc->send_key, buffer, - &sent, 0, &alloc->client_addr, - pj_sockaddr_get_len(&alloc->client_addr)); + &sent, 0, &alloc->client_addr, + pj_sockaddr_get_len(&alloc->client_addr)); return PJ_TRUE; } diff --git a/pjnath/src/pjnath-test/server.h b/pjnath/src/pjnath-test/server.h index 2eb1838ef0..bb9a9baeb3 100644 --- a/pjnath/src/pjnath-test/server.h +++ b/pjnath/src/pjnath-test/server.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,33 +23,33 @@ #include #include -#define DNS_SERVER_PORT 55533 +#define DNS_SERVER_PORT 55533 #define STUN_SERVER_PORT 33478 #define TURN_SERVER_PORT 33479 -#define TURN_USERNAME "auser" -#define TURN_PASSWD "apass" +#define TURN_USERNAME "auser" +#define TURN_PASSWD "apass" -#define MAX_TURN_ALLOC 16 -#define MAX_TURN_PERM 16 +#define MAX_TURN_ALLOC 16 +#define MAX_TURN_PERM 16 enum test_server_flags { - CREATE_DNS_SERVER = (1 << 0), - CREATE_A_RECORD_FOR_DOMAIN = (1 << 1), + CREATE_DNS_SERVER = (1 << 0), + CREATE_A_RECORD_FOR_DOMAIN = (1 << 1), - CREATE_STUN_SERVER = (1 << 4), - CREATE_STUN_SERVER_DNS_SRV = (1 << 5), + CREATE_STUN_SERVER = (1 << 4), + CREATE_STUN_SERVER_DNS_SRV = (1 << 5), - CREATE_TURN_SERVER = (1 << 8), - CREATE_TURN_SERVER_DNS_SRV = (1 << 9), + CREATE_TURN_SERVER = (1 << 8), + CREATE_TURN_SERVER_DNS_SRV = (1 << 9), - SERVER_IPV4 = (1 << 12), - SERVER_IPV6 = (1 << 13), + SERVER_IPV4 = (1 << 12), + SERVER_IPV6 = (1 << 13), - TURN_UDP = (1 << 16), - TURN_TCP = (1 << 17), - TURN_TLS = (1 << 18) + TURN_UDP = (1 << 16), + TURN_TCP = (1 << 17), + TURN_TLS = (1 << 18) }; typedef struct test_server test_server; @@ -58,16 +57,16 @@ typedef struct test_server test_server; /* TURN allocation */ typedef struct turn_allocation { - test_server *test_srv; - pj_pool_t *pool; - pj_activesock_t *sock; - pj_ioqueue_op_key_t send_key; - pj_sockaddr client_addr; - pj_sockaddr alloc_addr; - unsigned perm_cnt; - pj_sockaddr perm[MAX_TURN_PERM]; - unsigned chnum[MAX_TURN_PERM]; - pj_stun_msg *data_ind; + test_server *test_srv; + pj_pool_t *pool; + pj_activesock_t *sock; + pj_ioqueue_op_key_t send_key; + pj_sockaddr client_addr; + pj_sockaddr alloc_addr; + unsigned perm_cnt; + pj_sockaddr perm[MAX_TURN_PERM]; + unsigned chnum[MAX_TURN_PERM]; + pj_stun_msg *data_ind; } turn_allocation; /* @@ -76,49 +75,49 @@ typedef struct turn_allocation */ struct test_server { - pj_pool_t *pool; - pj_uint32_t flags; - pj_stun_config *stun_cfg; - pj_ioqueue_op_key_t send_key; + pj_pool_t *pool; + pj_uint32_t flags; + pj_stun_config *stun_cfg; + pj_ioqueue_op_key_t send_key; - pj_dns_server *dns_server; + pj_dns_server *dns_server; - pj_activesock_t *stun_sock; + pj_activesock_t *stun_sock; - pj_activesock_t *turn_sock; + pj_activesock_t *turn_sock; - pj_ssl_sock_t *ssl_srv_sock; + pj_ssl_sock_t *ssl_srv_sock; - pj_ssl_sock_t *ssl_cl_sock; + pj_ssl_sock_t *ssl_cl_sock; - pj_activesock_t *cl_turn_sock; + pj_activesock_t *cl_turn_sock; - pj_sockaddr remote_addr; - unsigned turn_alloc_cnt; - turn_allocation turn_alloc[MAX_TURN_ALLOC]; - pj_bool_t turn_respond_allocate; - pj_bool_t turn_respond_refresh; + pj_sockaddr remote_addr; + unsigned turn_alloc_cnt; + turn_allocation turn_alloc[MAX_TURN_ALLOC]; + pj_bool_t turn_respond_allocate; + pj_bool_t turn_respond_refresh; struct turn_stat { - unsigned rx_allocate_cnt; - unsigned rx_refresh_cnt; - unsigned rx_send_ind_cnt; + unsigned rx_allocate_cnt; + unsigned rx_refresh_cnt; + unsigned rx_send_ind_cnt; } turn_stat; - pj_str_t domain; - pj_str_t username; - pj_str_t passwd; + pj_str_t domain; + pj_str_t username; + pj_str_t passwd; }; pj_status_t create_test_server(pj_stun_config *stun_cfg, - pj_uint32_t flags, - const char *domain, - test_server **p_test_srv); + pj_uint32_t flags, + const char *domain, + test_server **p_test_srv); void destroy_test_server(test_server *test_srv); void test_server_poll_events(test_server *test_srv); -#endif /* __PJNATH_TEST_SERVER_H__ */ +#endif /* __PJNATH_TEST_SERVER_H__ */ diff --git a/pjnath/src/pjnath-test/sess_auth.c b/pjnath/src/pjnath-test/sess_auth.c index 055eaad615..f0e308bbac 100644 --- a/pjnath/src/pjnath-test/sess_auth.c +++ b/pjnath/src/pjnath-test/sess_auth.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,10 +20,10 @@ #define THIS_FILE "sess_auth.c" -#define REALM "STUN session test" +#define REALM "STUN session test" #define USERNAME "theusername" #define PASSWORD "thepassword" -#define NONCE "thenonce" +#define NONCE "thenonce" /* STUN config */ @@ -40,27 +39,27 @@ static pj_stun_config stun_cfg; /* Server instance */ static struct server { - pj_pool_t *pool; - pj_sockaddr addr; - pj_stun_session *sess; + pj_pool_t *pool; + pj_sockaddr addr; + pj_stun_session *sess; - pj_bool_t responding; - unsigned recv_count; - pj_stun_auth_type auth_type; + pj_bool_t responding; + unsigned recv_count; + pj_stun_auth_type auth_type; - pj_sock_t sock; + pj_sock_t sock; - pj_bool_t quit; - pj_thread_t *thread; + pj_bool_t quit; + pj_thread_t *thread; } *server; static pj_status_t server_send_msg(pj_stun_session *sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len) + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len) { pj_ssize_t len = pkt_size; @@ -71,35 +70,35 @@ static pj_status_t server_send_msg(pj_stun_session *sess, } static pj_status_t server_on_rx_request(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_rx_data *rdata, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_rx_data *rdata, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { PJ_UNUSED_ARG(pkt); PJ_UNUSED_ARG(pkt_len); PJ_UNUSED_ARG(token); return pj_stun_session_respond(sess, rdata, 0, NULL, NULL, PJ_TRUE, - src_addr, src_addr_len); + src_addr, src_addr_len); } static pj_status_t server_get_auth(void *user_data, - pj_pool_t *pool, - pj_str_t *realm, - pj_str_t *nonce) + pj_pool_t *pool, + pj_str_t *realm, + pj_str_t *nonce) { PJ_UNUSED_ARG(user_data); PJ_UNUSED_ARG(pool); if (server->auth_type == PJ_STUN_AUTH_SHORT_TERM) { - realm->slen = nonce->slen = 0; + realm->slen = nonce->slen = 0; } else { - *realm = pj_str(REALM); - *nonce = pj_str(NONCE); + *realm = pj_str(REALM); + *nonce = pj_str(NONCE); } return PJ_SUCCESS; @@ -107,32 +106,32 @@ static pj_status_t server_get_auth(void *user_data, static pj_status_t server_get_password( const pj_stun_msg *msg, - void *user_data, - const pj_str_t *realm, - const pj_str_t *username, - pj_pool_t *pool, - pj_stun_passwd_type *data_type, - pj_str_t *data) + void *user_data, + const pj_str_t *realm, + const pj_str_t *username, + pj_pool_t *pool, + pj_stun_passwd_type *data_type, + pj_str_t *data) { PJ_UNUSED_ARG(msg); PJ_UNUSED_ARG(user_data); PJ_UNUSED_ARG(pool); if (server->auth_type == PJ_STUN_AUTH_SHORT_TERM) { - if (realm && realm->slen) { - PJ_LOG(4,(THIS_FILE, " server expecting short term")); - return -1; - } + if (realm && realm->slen) { + PJ_LOG(4,(THIS_FILE, " server expecting short term")); + return -1; + } } else { - if (realm==NULL || realm->slen==0) { - PJ_LOG(4,(THIS_FILE, " realm not present")); - return -1; - } + if (realm==NULL || realm->slen==0) { + PJ_LOG(4,(THIS_FILE, " realm not present")); + return -1; + } } if (pj_strcmp2(username, USERNAME) != 0) { - PJ_LOG(4,(THIS_FILE, " wrong username")); - return -1; + PJ_LOG(4,(THIS_FILE, " wrong username")); + return -1; } *data_type = PJ_STUN_PASSWD_PLAIN; @@ -143,10 +142,10 @@ static pj_status_t server_get_password( const pj_stun_msg *msg, static pj_bool_t server_verify_nonce(const pj_stun_msg *msg, - void *user_data, - const pj_str_t *realm, - const pj_str_t *username, - const pj_str_t *nonce) + void *user_data, + const pj_str_t *realm, + const pj_str_t *username, + const pj_str_t *nonce) { PJ_UNUSED_ARG(msg); PJ_UNUSED_ARG(user_data); @@ -154,7 +153,7 @@ static pj_bool_t server_verify_nonce(const pj_stun_msg *msg, PJ_UNUSED_ARG(username); if (pj_strcmp2(nonce, NONCE) != 0) - return PJ_FALSE; + return PJ_FALSE; return PJ_TRUE; } @@ -167,39 +166,39 @@ static int server_thread(void *unused) PJ_LOG(5,("", " server thread started")); while (!server->quit) { - pj_fd_set_t readset; - pj_time_val delay = {0, 10}; - - PJ_FD_ZERO(&readset); - PJ_FD_SET(server->sock, &readset); - - if (pj_sock_select((int)server->sock+1, &readset, NULL, NULL, &delay)==1 - && PJ_FD_ISSET(server->sock, &readset)) - { - char pkt[1000]; - pj_ssize_t len; - pj_status_t status; - pj_sockaddr src_addr; - int src_addr_len; - - len = sizeof(pkt); - src_addr_len = sizeof(src_addr); - - status = pj_sock_recvfrom(server->sock, pkt, &len, 0, &src_addr, &src_addr_len); - if (status != PJ_SUCCESS) - continue; - - /* Increment server's receive count */ - server->recv_count++; - - /* Only pass to server if we allow to respond */ - if (!server->responding) - continue; - - pj_stun_session_on_rx_pkt(server->sess, pkt, len, - PJ_STUN_CHECK_PACKET | PJ_STUN_IS_DATAGRAM, - NULL, NULL, &src_addr, src_addr_len); - } + pj_fd_set_t readset; + pj_time_val delay = {0, 10}; + + PJ_FD_ZERO(&readset); + PJ_FD_SET(server->sock, &readset); + + if (pj_sock_select((int)server->sock+1, &readset, NULL, NULL, &delay)==1 + && PJ_FD_ISSET(server->sock, &readset)) + { + char pkt[1000]; + pj_ssize_t len; + pj_status_t status; + pj_sockaddr src_addr; + int src_addr_len; + + len = sizeof(pkt); + src_addr_len = sizeof(src_addr); + + status = pj_sock_recvfrom(server->sock, pkt, &len, 0, &src_addr, &src_addr_len); + if (status != PJ_SUCCESS) + continue; + + /* Increment server's receive count */ + server->recv_count++; + + /* Only pass to server if we allow to respond */ + if (!server->responding) + continue; + + pj_stun_session_on_rx_pkt(server->sess, pkt, len, + PJ_STUN_CHECK_PACKET | PJ_STUN_IS_DATAGRAM, + NULL, NULL, &src_addr, src_addr_len); + } } return 0; @@ -210,17 +209,17 @@ static int server_thread(void *unused) static void destroy_server(void) { if (server->thread) { - server->quit = PJ_TRUE; - pj_thread_join(server->thread); - pj_thread_destroy(server->thread); + server->quit = PJ_TRUE; + pj_thread_join(server->thread); + pj_thread_destroy(server->thread); } if (server->sock) { - pj_sock_close(server->sock); + pj_sock_close(server->sock); } if (server->sess) { - pj_stun_session_destroy(server->sess); + pj_stun_session_destroy(server->sess); } pj_pool_release(server->pool); @@ -229,8 +228,8 @@ static void destroy_server(void) /* Instantiate standard server */ static int create_std_server(pj_stun_auth_type auth_type, - pj_bool_t responding, - pj_bool_t use_ipv6) + pj_bool_t responding, + pj_bool_t use_ipv6) { pj_pool_t *pool; pj_stun_session_cb sess_cb; @@ -250,8 +249,8 @@ static int create_std_server(pj_stun_auth_type auth_type, sess_cb.on_send_msg = &server_send_msg; status = pj_stun_session_create(&stun_cfg, "server", &sess_cb, PJ_FALSE, NULL, &server->sess); if (status != PJ_SUCCESS) { - destroy_server(); - return -10; + destroy_server(); + return -10; } /* Configure credential */ @@ -262,57 +261,57 @@ static int create_std_server(pj_stun_auth_type auth_type, cred.data.dyn_cred.verify_nonce = &server_verify_nonce; status = pj_stun_session_set_credential(server->sess, auth_type, &cred); if (status != PJ_SUCCESS) { - destroy_server(); - return -20; + destroy_server(); + return -20; } /* Create socket */ status = pj_sock_socket(GET_AF(use_ipv6), pj_SOCK_DGRAM(), 0, &server->sock); if (status != PJ_SUCCESS) { - destroy_server(); - return -30; + destroy_server(); + return -30; } /* Bind */ pj_sockaddr_init(GET_AF(use_ipv6), &server->addr, NULL, 0); status = pj_sock_bind(server->sock, &server->addr, pj_sockaddr_get_len(&server->addr)); if (status != PJ_SUCCESS) { - destroy_server(); - return -40; + destroy_server(); + return -40; } else { - /* Get the bound IP address */ - int namelen = sizeof(server->addr); - pj_sockaddr addr; - - status = pj_sock_getsockname(server->sock, &server->addr, &namelen); - if (status != PJ_SUCCESS) { - destroy_server(); - return -43; - } - - if (use_ipv6) { - /* pj_gethostip() may return IPv6 link-local and currently it will cause - * 'no route to host' error, so let's just hardcode to [::1] - */ - pj_sockaddr_init(pj_AF_INET6(), &addr, NULL, 0); - addr.ipv6.sin6_addr.s6_addr[15] = 1; - } else { - status = pj_gethostip(GET_AF(use_ipv6), &addr); - if (status != PJ_SUCCESS) { - destroy_server(); - return -45; - } + /* Get the bound IP address */ + int namelen = sizeof(server->addr); + pj_sockaddr addr; + + status = pj_sock_getsockname(server->sock, &server->addr, &namelen); + if (status != PJ_SUCCESS) { + destroy_server(); + return -43; + } + + if (use_ipv6) { + /* pj_gethostip() may return IPv6 link-local and currently it will cause + * 'no route to host' error, so let's just hardcode to [::1] + */ + pj_sockaddr_init(pj_AF_INET6(), &addr, NULL, 0); + addr.ipv6.sin6_addr.s6_addr[15] = 1; + } else { + status = pj_gethostip(GET_AF(use_ipv6), &addr); + if (status != PJ_SUCCESS) { + destroy_server(); + return -45; + } } - pj_sockaddr_copy_addr(&server->addr, &addr); + pj_sockaddr_copy_addr(&server->addr, &addr); } /* Create worker thread */ status = pj_thread_create(pool, "server", &server_thread, 0, 0, 0, &server->thread); if (status != PJ_SUCCESS) { - destroy_server(); - return -30; + destroy_server(); + return -30; } return 0; @@ -326,28 +325,28 @@ static int create_std_server(pj_stun_auth_type auth_type, static struct client { - pj_pool_t *pool; + pj_pool_t *pool; pj_stun_session *sess; - pj_sem_t *test_complete; - pj_sock_t sock; + pj_sem_t *test_complete; + pj_sock_t sock; - pj_bool_t responding; - unsigned recv_count; + pj_bool_t responding; + unsigned recv_count; - pj_status_t response_status; - pj_stun_msg *response; + pj_status_t response_status; + pj_stun_msg *response; - pj_bool_t quit; - pj_thread_t *thread; + pj_bool_t quit; + pj_thread_t *thread; } *client; static pj_status_t client_send_msg(pj_stun_session *sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len) + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len) { pj_ssize_t len = pkt_size; @@ -359,12 +358,12 @@ static pj_status_t client_send_msg(pj_stun_session *sess, static void client_on_request_complete( pj_stun_session *sess, - pj_status_t status, - void *token, - pj_stun_tx_data *tdata, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + pj_status_t status, + void *token, + pj_stun_tx_data *tdata, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { PJ_UNUSED_ARG(sess); PJ_UNUSED_ARG(token); @@ -374,7 +373,7 @@ static void client_on_request_complete( pj_stun_session *sess, client->response_status = status; if (response) - client->response = pj_stun_msg_clone(client->pool, response); + client->response = pj_stun_msg_clone(client->pool, response); pj_sem_post(client->test_complete); } @@ -385,43 +384,43 @@ static int client_thread(void *unused) PJ_UNUSED_ARG(unused); while (!client->quit) { - pj_fd_set_t readset; - pj_time_val delay = {0, 10}; - - /* Also poll the timer heap */ - pj_timer_heap_poll(stun_cfg.timer_heap, NULL); - - /* Poll client socket */ - PJ_FD_ZERO(&readset); - PJ_FD_SET(client->sock, &readset); - - if (pj_sock_select((int)client->sock+1, &readset, NULL, NULL, &delay)==1 - && PJ_FD_ISSET(client->sock, &readset)) - { - char pkt[1000]; - pj_ssize_t len; - pj_status_t status; - pj_sockaddr src_addr; - int src_addr_len; - - len = sizeof(pkt); - src_addr_len = sizeof(src_addr); - - status = pj_sock_recvfrom(client->sock, pkt, &len, 0, &src_addr, &src_addr_len); - if (status != PJ_SUCCESS) - continue; - - /* Increment client's receive count */ - client->recv_count++; - - /* Only pass to client if we allow to respond */ - if (!client->responding) - continue; - - pj_stun_session_on_rx_pkt(client->sess, pkt, len, - PJ_STUN_CHECK_PACKET | PJ_STUN_IS_DATAGRAM, - NULL, NULL, &src_addr, src_addr_len); - } + pj_fd_set_t readset; + pj_time_val delay = {0, 10}; + + /* Also poll the timer heap */ + pj_timer_heap_poll(stun_cfg.timer_heap, NULL); + + /* Poll client socket */ + PJ_FD_ZERO(&readset); + PJ_FD_SET(client->sock, &readset); + + if (pj_sock_select((int)client->sock+1, &readset, NULL, NULL, &delay)==1 + && PJ_FD_ISSET(client->sock, &readset)) + { + char pkt[1000]; + pj_ssize_t len; + pj_status_t status; + pj_sockaddr src_addr; + int src_addr_len; + + len = sizeof(pkt); + src_addr_len = sizeof(src_addr); + + status = pj_sock_recvfrom(client->sock, pkt, &len, 0, &src_addr, &src_addr_len); + if (status != PJ_SUCCESS) + continue; + + /* Increment client's receive count */ + client->recv_count++; + + /* Only pass to client if we allow to respond */ + if (!client->responding) + continue; + + pj_stun_session_on_rx_pkt(client->sess, pkt, len, + PJ_STUN_CHECK_PACKET | PJ_STUN_IS_DATAGRAM, + NULL, NULL, &src_addr, src_addr_len); + } } @@ -432,42 +431,42 @@ static int client_thread(void *unused) static void destroy_client_server(void) { if (client->thread) { - client->quit = 1; - pj_thread_join(client->thread); - pj_thread_destroy(client->thread); + client->quit = 1; + pj_thread_join(client->thread); + pj_thread_destroy(client->thread); } if (client->sess) - pj_stun_session_destroy(client->sess); + pj_stun_session_destroy(client->sess); if (client->sock) - pj_sock_close(client->sock); + pj_sock_close(client->sock); if (client->test_complete) - pj_sem_destroy(client->test_complete); + pj_sem_destroy(client->test_complete); if (server) - destroy_server(); + destroy_server(); } static int run_client_test(const char *title, - pj_bool_t server_responding, - pj_stun_auth_type server_auth_type, - - pj_stun_auth_type client_auth_type, - const char *realm, - const char *username, - const char *nonce, - const char *password, - pj_bool_t dummy_mi, - pj_bool_t use_ipv6, - pj_bool_t expected_error, - pj_status_t expected_code, - const char *expected_realm, - const char *expected_nonce, - - int (*more_check)(void)) + pj_bool_t server_responding, + pj_stun_auth_type server_auth_type, + + pj_stun_auth_type client_auth_type, + const char *realm, + const char *username, + const char *nonce, + const char *password, + pj_bool_t dummy_mi, + pj_bool_t use_ipv6, + pj_bool_t expected_error, + pj_status_t expected_code, + const char *expected_realm, + const char *expected_nonce, + + int (*more_check)(void)) { pj_pool_t *pool; pj_stun_session_cb sess_cb; @@ -491,37 +490,37 @@ static int run_client_test(const char *title, sess_cb.on_send_msg = &client_send_msg; status = pj_stun_session_create(&stun_cfg, "client", &sess_cb, PJ_FALSE, NULL, &client->sess); if (status != PJ_SUCCESS) { - destroy_client_server(); - return -200; + destroy_client_server(); + return -200; } /* Create semaphore */ status = pj_sem_create(pool, "client", 0, 1, &client->test_complete); if (status != PJ_SUCCESS) { - destroy_client_server(); - return -205; + destroy_client_server(); + return -205; } /* Create client socket */ status = pj_sock_socket(GET_AF(use_ipv6), pj_SOCK_DGRAM(), 0, &client->sock); if (status != PJ_SUCCESS) { - destroy_client_server(); - return -210; + destroy_client_server(); + return -210; } /* Bind client socket */ pj_sockaddr_init(GET_AF(use_ipv6), &addr, NULL, 0); status = pj_sock_bind(client->sock, &addr, pj_sockaddr_get_len(&addr)); if (status != PJ_SUCCESS) { - destroy_client_server(); - return -220; + destroy_client_server(); + return -220; } /* Create client thread */ status = pj_thread_create(pool, "client", &client_thread, NULL, 0, 0, &client->thread); if (status != PJ_SUCCESS) { - destroy_client_server(); - return -230; + destroy_client_server(); + return -230; } /* Initialize credential */ @@ -534,52 +533,52 @@ static int run_client_test(const char *title, cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN; status = pj_stun_session_set_credential(client->sess, client_auth_type, &cred); if (status != PJ_SUCCESS) { - destroy_client_server(); - return -240; + destroy_client_server(); + return -240; } /* Create the server */ status = create_std_server(server_auth_type, server_responding, use_ipv6); if (status != 0) { - destroy_client_server(); - return status; + destroy_client_server(); + return status; } /* Create request */ status = pj_stun_session_create_req(client->sess, PJ_STUN_BINDING_REQUEST, - PJ_STUN_MAGIC, NULL, &tdata); + PJ_STUN_MAGIC, NULL, &tdata); if (status != PJ_SUCCESS) { - destroy_client_server(); - return -250; + destroy_client_server(); + return -250; } /* Add our own attributes if client authentication is set to none */ if (client_auth_type == PJ_STUN_AUTH_NONE) { - pj_str_t tmp; - if (realm) - pj_stun_msg_add_string_attr(tdata->pool, tdata->msg, PJ_STUN_ATTR_REALM, pj_cstr(&tmp, realm)); - if (username) - pj_stun_msg_add_string_attr(tdata->pool, tdata->msg, PJ_STUN_ATTR_USERNAME, pj_cstr(&tmp, username)); - if (nonce) - pj_stun_msg_add_string_attr(tdata->pool, tdata->msg, PJ_STUN_ATTR_NONCE, pj_cstr(&tmp, nonce)); - if (password) { - // ignored - } - if (dummy_mi) { - pj_stun_msgint_attr *mi; - - pj_stun_msgint_attr_create(tdata->pool, &mi); - pj_stun_msg_add_attr(tdata->msg, &mi->hdr); - } - + pj_str_t tmp; + if (realm) + pj_stun_msg_add_string_attr(tdata->pool, tdata->msg, PJ_STUN_ATTR_REALM, pj_cstr(&tmp, realm)); + if (username) + pj_stun_msg_add_string_attr(tdata->pool, tdata->msg, PJ_STUN_ATTR_USERNAME, pj_cstr(&tmp, username)); + if (nonce) + pj_stun_msg_add_string_attr(tdata->pool, tdata->msg, PJ_STUN_ATTR_NONCE, pj_cstr(&tmp, nonce)); + if (password) { + // ignored + } + if (dummy_mi) { + pj_stun_msgint_attr *mi; + + pj_stun_msgint_attr_create(tdata->pool, &mi); + pj_stun_msg_add_attr(tdata->msg, &mi->hdr); + } + } /* Send the request */ status = pj_stun_session_send_msg(client->sess, NULL, PJ_FALSE, PJ_TRUE, &server->addr, - pj_sockaddr_get_len(&server->addr), tdata); + pj_sockaddr_get_len(&server->addr), tdata); if (status != PJ_SUCCESS) { - destroy_client_server(); - return -270; + destroy_client_server(); + return -270; } /* Wait until test complete */ @@ -588,104 +587,104 @@ static int run_client_test(const char *title, /* Verify response */ if (expected_error) { - if (expected_code != client->response_status) { - char e1[PJ_ERR_MSG_SIZE], e2[PJ_ERR_MSG_SIZE]; + if (expected_code != client->response_status) { + char e1[PJ_ERR_MSG_SIZE], e2[PJ_ERR_MSG_SIZE]; - pj_strerror(expected_code, e1, sizeof(e1)); - pj_strerror(client->response_status, e2, sizeof(e2)); + pj_strerror(expected_code, e1, sizeof(e1)); + pj_strerror(client->response_status, e2, sizeof(e2)); - PJ_LOG(3,(THIS_FILE, " err: expecting %d (%s) but got %d (%s) response", - expected_code, e1, client->response_status, e2)); - rc = -500; - } + PJ_LOG(3,(THIS_FILE, " err: expecting %d (%s) but got %d (%s) response", + expected_code, e1, client->response_status, e2)); + rc = -500; + } } else { - int res_code = 0; - pj_stun_realm_attr *arealm; - pj_stun_nonce_attr *anonce; - - if (client->response_status != 0) { - PJ_LOG(3,(THIS_FILE, " err: expecting successful operation but got error %d", - client->response_status)); - rc = -600; - goto done; - } - - if (PJ_STUN_IS_ERROR_RESPONSE(client->response->hdr.type)) { - pj_stun_errcode_attr *aerr = NULL; - - aerr = (pj_stun_errcode_attr*) - pj_stun_msg_find_attr(client->response, - PJ_STUN_ATTR_ERROR_CODE, 0); - if (aerr == NULL) { - PJ_LOG(3,(THIS_FILE, " err: received error response without ERROR-CODE")); - rc = -610; - goto done; - } - - res_code = aerr->err_code; - } else { - res_code = 0; - } - - /* Check that code matches */ - if (expected_code != res_code) { - PJ_LOG(3,(THIS_FILE, " err: expecting response code %d but got %d", - expected_code, res_code)); - rc = -620; - goto done; - } - - /* Find REALM and NONCE attributes */ - arealm = (pj_stun_realm_attr*) - pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_REALM, 0); - anonce = (pj_stun_nonce_attr*) - pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_NONCE, 0); - - if (expected_realm) { - if (arealm == NULL) { - PJ_LOG(3,(THIS_FILE, " err: expecting REALM in esponse")); - rc = -630; - goto done; - } - if (pj_strcmp2(&arealm->value, expected_realm)!=0) { - PJ_LOG(3,(THIS_FILE, " err: REALM mismatch in response")); - rc = -640; - goto done; - } - } else { - if (arealm != NULL) { - PJ_LOG(3,(THIS_FILE, " err: non expecting REALM in response")); - rc = -650; - goto done; - } - } - - if (expected_nonce) { - if (anonce == NULL) { - PJ_LOG(3,(THIS_FILE, " err: expecting NONCE in esponse")); - rc = -660; - goto done; - } - if (pj_strcmp2(&anonce->value, expected_nonce)!=0) { - PJ_LOG(3,(THIS_FILE, " err: NONCE mismatch in response")); - rc = -670; - goto done; - } - } else { - if (anonce != NULL) { - PJ_LOG(3,(THIS_FILE, " err: non expecting NONCE in response")); - rc = -680; - goto done; - } - } + int res_code = 0; + pj_stun_realm_attr *arealm; + pj_stun_nonce_attr *anonce; + + if (client->response_status != 0) { + PJ_LOG(3,(THIS_FILE, " err: expecting successful operation but got error %d", + client->response_status)); + rc = -600; + goto done; + } + + if (PJ_STUN_IS_ERROR_RESPONSE(client->response->hdr.type)) { + pj_stun_errcode_attr *aerr = NULL; + + aerr = (pj_stun_errcode_attr*) + pj_stun_msg_find_attr(client->response, + PJ_STUN_ATTR_ERROR_CODE, 0); + if (aerr == NULL) { + PJ_LOG(3,(THIS_FILE, " err: received error response without ERROR-CODE")); + rc = -610; + goto done; + } + + res_code = aerr->err_code; + } else { + res_code = 0; + } + + /* Check that code matches */ + if (expected_code != res_code) { + PJ_LOG(3,(THIS_FILE, " err: expecting response code %d but got %d", + expected_code, res_code)); + rc = -620; + goto done; + } + + /* Find REALM and NONCE attributes */ + arealm = (pj_stun_realm_attr*) + pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_REALM, 0); + anonce = (pj_stun_nonce_attr*) + pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_NONCE, 0); + + if (expected_realm) { + if (arealm == NULL) { + PJ_LOG(3,(THIS_FILE, " err: expecting REALM in esponse")); + rc = -630; + goto done; + } + if (pj_strcmp2(&arealm->value, expected_realm)!=0) { + PJ_LOG(3,(THIS_FILE, " err: REALM mismatch in response")); + rc = -640; + goto done; + } + } else { + if (arealm != NULL) { + PJ_LOG(3,(THIS_FILE, " err: non expecting REALM in response")); + rc = -650; + goto done; + } + } + + if (expected_nonce) { + if (anonce == NULL) { + PJ_LOG(3,(THIS_FILE, " err: expecting NONCE in esponse")); + rc = -660; + goto done; + } + if (pj_strcmp2(&anonce->value, expected_nonce)!=0) { + PJ_LOG(3,(THIS_FILE, " err: NONCE mismatch in response")); + rc = -670; + goto done; + } + } else { + if (anonce != NULL) { + PJ_LOG(3,(THIS_FILE, " err: non expecting NONCE in response")); + rc = -680; + goto done; + } + } } /* Our tests are okay so far. Let caller do some more tests if * it wants to. */ if (rc==0 && more_check) { - rc = (*more_check)(); + rc = (*more_check)(); } @@ -694,21 +693,21 @@ static int run_client_test(const char *title, /* If IPv6 is enabled, test again for IPv4. */ if ((rc == 0) && use_ipv6) { - rc = run_client_test(title, - server_responding, - server_auth_type, - client_auth_type, - realm, - username, - nonce, - password, - dummy_mi, - 0, - expected_error, - expected_code, - expected_realm, - expected_nonce, - more_check); + rc = run_client_test(title, + server_responding, + server_auth_type, + client_auth_type, + realm, + username, + nonce, + password, + dummy_mi, + 0, + expected_error, + expected_code, + expected_realm, + expected_nonce, + more_check); } return rc; @@ -725,12 +724,12 @@ static int retransmit_check(void) { if (server->recv_count != PJ_STUN_MAX_TRANSMIT_COUNT) { - PJ_LOG(3,("", " expecting %d retransmissions, got %d", - PJ_STUN_MAX_TRANSMIT_COUNT, server->recv_count)); - return -700; + PJ_LOG(3,("", " expecting %d retransmissions, got %d", + PJ_STUN_MAX_TRANSMIT_COUNT, server->recv_count)); + return -700; } if (client->recv_count != 0) - return -710; + return -710; return 0; } @@ -739,9 +738,9 @@ static int long_term_check1(void) { /* SHOULD NOT contain USERNAME or MESSAGE-INTEGRITY */ if (pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_USERNAME, 0)) - return -800; + return -800; if (pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_MESSAGE_INTEGRITY, 0)) - return -800; + return -800; return 0; } @@ -752,13 +751,13 @@ static int long_term_check2(void) * MESSAGE-INTEGRITY attribute. */ if (pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_USERNAME, 0)) - return -900; + return -900; if (pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_NONCE, 0)) - return -910; + return -910; if (pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_REALM, 0)) - return -920; + return -920; if (pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_MESSAGE_INTEGRITY, 0)) - return -930; + return -930; return 0; } @@ -767,11 +766,11 @@ static int long_term_check3(void) { /* response SHOULD NOT include a USERNAME, NONCE, and REALM */ if (pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_USERNAME, 0)) - return -1000; + return -1000; if (pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_NONCE, 0)) - return -1010; + return -1010; if (pj_stun_msg_find_attr(client->response, PJ_STUN_ATTR_REALM, 0)) - return -1020; + return -1020; return 0; } @@ -795,29 +794,29 @@ int sess_auth_test(void) /* Create pool and timer heap */ pool = pj_pool_create(mem, "authtest", 200, 200, NULL); if (pj_timer_heap_create(pool, 20, &stun_cfg.timer_heap)) { - pj_pool_release(pool); - return -5; + pj_pool_release(pool); + return -5; } /* Basic retransmission test */ rc = run_client_test("Retransmission", // title - PJ_FALSE, // server responding - PJ_STUN_AUTH_NONE, // server auth - PJ_STUN_AUTH_NONE, // client auth - NULL, // realm - NULL, // username - NULL, // nonce - NULL, // password - PJ_FALSE, // dummy MI - USE_IPV6, // use IPv6 - PJ_TRUE, // expected error - PJNATH_ESTUNTIMEDOUT,// expected code - NULL, // expected realm - NULL, // expected nonce - &retransmit_check // more check - ); + PJ_FALSE, // server responding + PJ_STUN_AUTH_NONE, // server auth + PJ_STUN_AUTH_NONE, // client auth + NULL, // realm + NULL, // username + NULL, // nonce + NULL, // password + PJ_FALSE, // dummy MI + USE_IPV6, // use IPv6 + PJ_TRUE, // expected error + PJNATH_ESTUNTIMEDOUT,// expected code + NULL, // expected realm + NULL, // expected nonce + &retransmit_check // more check + ); if (rc != 0) { - goto done; + goto done; } /* @@ -832,23 +831,23 @@ int sess_auth_test(void) * use an error code of 400 (Bad Request). */ rc = run_client_test("Missing MESSAGE-INTEGRITY (short term)", // title - PJ_TRUE, // server responding - PJ_STUN_AUTH_SHORT_TERM, // server auth - PJ_STUN_AUTH_NONE, // client auth - NULL, // realm - NULL, // username - NULL, // nonce - NULL, // password - PJ_FALSE, // dummy MI - USE_IPV6, // use IPv6 - PJ_TRUE, // expected error - PJ_STATUS_FROM_STUN_CODE(400),// expected code - NULL, // expected realm - NULL, // expected nonce - NULL // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_SHORT_TERM, // server auth + PJ_STUN_AUTH_NONE, // client auth + NULL, // realm + NULL, // username + NULL, // nonce + NULL, // password + PJ_FALSE, // dummy MI + USE_IPV6, // use IPv6 + PJ_TRUE, // expected error + PJ_STATUS_FROM_STUN_CODE(400),// expected code + NULL, // expected realm + NULL, // expected nonce + NULL // more check + ); if (rc != 0) { - goto done; + goto done; } /* If the USERNAME does not contain a username value currently valid @@ -857,23 +856,23 @@ int sess_auth_test(void) * an error code of 401 (Unauthorized). */ rc = run_client_test("USERNAME mismatch (short term)", // title - PJ_TRUE, // server responding - PJ_STUN_AUTH_SHORT_TERM, // server auth - PJ_STUN_AUTH_SHORT_TERM, // client auth - NULL, // realm - "anotheruser", // username - NULL, // nonce - "anotherpass", // password - PJ_FALSE, // dummy MI - USE_IPV6, // use IPv6 - PJ_TRUE, // expected error - PJ_STATUS_FROM_STUN_CODE(401),// expected code - NULL, // expected realm - NULL, // expected nonce - NULL // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_SHORT_TERM, // server auth + PJ_STUN_AUTH_SHORT_TERM, // client auth + NULL, // realm + "anotheruser", // username + NULL, // nonce + "anotherpass", // password + PJ_FALSE, // dummy MI + USE_IPV6, // use IPv6 + PJ_TRUE, // expected error + PJ_STATUS_FROM_STUN_CODE(401),// expected code + NULL, // expected realm + NULL, // expected nonce + NULL // more check + ); if (rc != 0) { - goto done; + goto done; } /* Using the password associated with the username, compute the value @@ -886,67 +885,67 @@ int sess_auth_test(void) * of 401 (Unauthorized). */ rc = run_client_test("MESSAGE-INTEGRITY mismatch (short term)", // title - PJ_TRUE, // server responding - PJ_STUN_AUTH_SHORT_TERM, // server auth - PJ_STUN_AUTH_SHORT_TERM, // client auth - NULL, // realm - USERNAME, // username - NULL, // nonce - "anotherpass", // password - PJ_FALSE, // dummy MI - USE_IPV6, // use IPv6 - PJ_TRUE, // expected error - PJ_STATUS_FROM_STUN_CODE(401),// expected code - NULL, // expected realm - NULL, // expected nonce - NULL // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_SHORT_TERM, // server auth + PJ_STUN_AUTH_SHORT_TERM, // client auth + NULL, // realm + USERNAME, // username + NULL, // nonce + "anotherpass", // password + PJ_FALSE, // dummy MI + USE_IPV6, // use IPv6 + PJ_TRUE, // expected error + PJ_STATUS_FROM_STUN_CODE(401),// expected code + NULL, // expected realm + NULL, // expected nonce + NULL // more check + ); if (rc != 0) { - goto done; + goto done; } /* USERNAME is not present, server must respond with 400 (Bad * Request). */ rc = run_client_test("Missing USERNAME (short term)",// title - PJ_TRUE, // server responding - PJ_STUN_AUTH_SHORT_TERM, // server auth - PJ_STUN_AUTH_NONE, // client auth - NULL, // realm - NULL, // username - NULL, // nonce - NULL, // password - PJ_TRUE, // dummy MI - USE_IPV6, // use IPv6 - PJ_TRUE, // expected error - PJ_STATUS_FROM_STUN_CODE(400), // expected code - NULL, // expected realm - NULL, // expected nonce - NULL // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_SHORT_TERM, // server auth + PJ_STUN_AUTH_NONE, // client auth + NULL, // realm + NULL, // username + NULL, // nonce + NULL, // password + PJ_TRUE, // dummy MI + USE_IPV6, // use IPv6 + PJ_TRUE, // expected error + PJ_STATUS_FROM_STUN_CODE(400), // expected code + NULL, // expected realm + NULL, // expected nonce + NULL // more check + ); if (rc != 0) { - goto done; + goto done; } /* Successful short term authentication */ rc = run_client_test("Successful scenario (short term)", // title - PJ_TRUE, // server responding - PJ_STUN_AUTH_SHORT_TERM, // server auth - PJ_STUN_AUTH_SHORT_TERM, // client auth - NULL, // realm - USERNAME, // username - NULL, // nonce - PASSWORD, // password - PJ_FALSE, // dummy MI - USE_IPV6, // use IPv6 - PJ_FALSE, // expected error - PJ_SUCCESS, // expected code - NULL, // expected realm - NULL, // expected nonce - NULL // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_SHORT_TERM, // server auth + PJ_STUN_AUTH_SHORT_TERM, // client auth + NULL, // realm + USERNAME, // username + NULL, // nonce + PASSWORD, // password + PJ_FALSE, // dummy MI + USE_IPV6, // use IPv6 + PJ_FALSE, // expected error + PJ_SUCCESS, // expected code + NULL, // expected realm + NULL, // expected nonce + NULL // more check + ); if (rc != 0) { - goto done; + goto done; } /* @@ -957,23 +956,23 @@ int sess_auth_test(void) * REALM, reject with .... 401 ??? */ rc = run_client_test("Unwanted REALM (short term)", // title - PJ_TRUE, // server responding - PJ_STUN_AUTH_SHORT_TERM, // server auth - PJ_STUN_AUTH_NONE, // client auth - REALM, // realm - USERNAME, // username - NULL, // nonce - PASSWORD, // password - PJ_TRUE, // dummy MI - USE_IPV6, // use IPv6 - PJ_TRUE, // expected error - PJ_STATUS_FROM_STUN_CODE(401), // expected code - NULL, // expected realm - NULL, // expected nonce - &long_term_check2 // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_SHORT_TERM, // server auth + PJ_STUN_AUTH_NONE, // client auth + REALM, // realm + USERNAME, // username + NULL, // nonce + PASSWORD, // password + PJ_TRUE, // dummy MI + USE_IPV6, // use IPv6 + PJ_TRUE, // expected error + PJ_STATUS_FROM_STUN_CODE(401), // expected code + NULL, // expected realm + NULL, // expected nonce + &long_term_check2 // more check + ); if (rc != 0) { - goto done; + goto done; } @@ -991,23 +990,23 @@ int sess_auth_test(void) * USERNAME or MESSAGE-INTEGRITY attribute. */ rc = run_client_test("Missing M-I (long term)", // title - PJ_TRUE, // server responding - PJ_STUN_AUTH_LONG_TERM, // server auth - PJ_STUN_AUTH_NONE, // client auth - NULL, // client realm - NULL, // client username - NULL, // client nonce - NULL, // client password - PJ_FALSE, // client dummy MI - USE_IPV6, // use IPv6 - PJ_TRUE, // expected error - PJ_STATUS_FROM_STUN_CODE(401), // expected code - REALM, // expected realm - NONCE, // expected nonce - &long_term_check1 // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_LONG_TERM, // server auth + PJ_STUN_AUTH_NONE, // client auth + NULL, // client realm + NULL, // client username + NULL, // client nonce + NULL, // client password + PJ_FALSE, // client dummy MI + USE_IPV6, // use IPv6 + PJ_TRUE, // expected error + PJ_STATUS_FROM_STUN_CODE(401), // expected code + REALM, // expected realm + NONCE, // expected nonce + &long_term_check1 // more check + ); if (rc != 0) { - goto done; + goto done; } /* If the message contains a MESSAGE-INTEGRITY attribute, but is @@ -1018,65 +1017,65 @@ int sess_auth_test(void) */ /* Missing USERNAME */ rc = run_client_test("Missing USERNAME (long term)", // title - PJ_TRUE, // server responding - PJ_STUN_AUTH_LONG_TERM, // server auth - PJ_STUN_AUTH_NONE, // client auth - REALM, // client realm - NULL, // client username - NONCE, // client nonce - PASSWORD, // client password - PJ_TRUE, // client dummy MI - USE_IPV6, // use IPv6 - PJ_TRUE, // expected error - PJ_STATUS_FROM_STUN_CODE(400), // expected code - NULL, // expected realm - NULL, // expected nonce - &long_term_check2 // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_LONG_TERM, // server auth + PJ_STUN_AUTH_NONE, // client auth + REALM, // client realm + NULL, // client username + NONCE, // client nonce + PASSWORD, // client password + PJ_TRUE, // client dummy MI + USE_IPV6, // use IPv6 + PJ_TRUE, // expected error + PJ_STATUS_FROM_STUN_CODE(400), // expected code + NULL, // expected realm + NULL, // expected nonce + &long_term_check2 // more check + ); if (rc != 0) { - goto done; + goto done; } /* Missing REALM */ rc = run_client_test("Missing REALM (long term)", // title - PJ_TRUE, // server responding - PJ_STUN_AUTH_LONG_TERM, // server auth - PJ_STUN_AUTH_NONE, // client auth - NULL, // client realm - USERNAME, // client username - NONCE, // client nonce - PASSWORD, // client password - PJ_TRUE, // client dummy MI - USE_IPV6, // use IPv6 - PJ_TRUE, // expected error - PJ_STATUS_FROM_STUN_CODE(400), // expected code - NULL, // expected realm - NULL, // expected nonce - &long_term_check2 // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_LONG_TERM, // server auth + PJ_STUN_AUTH_NONE, // client auth + NULL, // client realm + USERNAME, // client username + NONCE, // client nonce + PASSWORD, // client password + PJ_TRUE, // client dummy MI + USE_IPV6, // use IPv6 + PJ_TRUE, // expected error + PJ_STATUS_FROM_STUN_CODE(400), // expected code + NULL, // expected realm + NULL, // expected nonce + &long_term_check2 // more check + ); if (rc != 0) { - goto done; + goto done; } /* Missing NONCE */ rc = run_client_test("Missing NONCE (long term)", // title - PJ_TRUE, // server responding - PJ_STUN_AUTH_LONG_TERM, // server auth - PJ_STUN_AUTH_NONE, // client auth - REALM, // client realm - USERNAME, // client username - NULL, // client nonce - PASSWORD, // client password - PJ_TRUE, // client dummy MI - USE_IPV6, // use IPv6 - PJ_TRUE, // expected error - PJ_STATUS_FROM_STUN_CODE(400), // expected code - NULL, // expected realm - NULL, // expected nonce - &long_term_check2 // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_LONG_TERM, // server auth + PJ_STUN_AUTH_NONE, // client auth + REALM, // client realm + USERNAME, // client username + NULL, // client nonce + PASSWORD, // client password + PJ_TRUE, // client dummy MI + USE_IPV6, // use IPv6 + PJ_TRUE, // expected error + PJ_STATUS_FROM_STUN_CODE(400), // expected code + NULL, // expected realm + NULL, // expected nonce + &long_term_check2 // more check + ); if (rc != 0) { - goto done; + goto done; } /* If the NONCE is no longer valid, the server MUST generate an error @@ -1097,44 +1096,44 @@ int sess_auth_test(void) * USERNAME or MESSAGE-INTEGRITY attribute. */ rc = run_client_test("Invalid username (long term)", // title - PJ_TRUE, // server responding - PJ_STUN_AUTH_LONG_TERM, // server auth - PJ_STUN_AUTH_LONG_TERM, // client auth - REALM, // client realm - "anotheruser", // client username - "a nonce", // client nonce - "somepassword", // client password - PJ_FALSE, // client dummy MI - USE_IPV6, // use IPv6 - PJ_TRUE, // expected error - PJ_STATUS_FROM_STUN_CODE(401), // expected code - REALM, // expected realm - NONCE, // expected nonce - &long_term_check1 // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_LONG_TERM, // server auth + PJ_STUN_AUTH_LONG_TERM, // client auth + REALM, // client realm + "anotheruser", // client username + "a nonce", // client nonce + "somepassword", // client password + PJ_FALSE, // client dummy MI + USE_IPV6, // use IPv6 + PJ_TRUE, // expected error + PJ_STATUS_FROM_STUN_CODE(401), // expected code + REALM, // expected realm + NONCE, // expected nonce + &long_term_check1 // more check + ); if (rc != 0) { - goto done; + goto done; } /* Successful long term authentication */ rc = run_client_test("Successful scenario (long term)", // title - PJ_TRUE, // server responding - PJ_STUN_AUTH_LONG_TERM, // server auth - PJ_STUN_AUTH_LONG_TERM, // client auth - REALM, // client realm - USERNAME, // client username - "anothernonce", // client nonce - PASSWORD, // client password - PJ_FALSE, // client dummy MI - USE_IPV6, // use IPv6 - PJ_FALSE, // expected error - 0, // expected code - NULL, // expected realm - NULL, // expected nonce - &long_term_check3 // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_LONG_TERM, // server auth + PJ_STUN_AUTH_LONG_TERM, // client auth + REALM, // client realm + USERNAME, // client username + "anothernonce", // client nonce + PASSWORD, // client password + PJ_FALSE, // client dummy MI + USE_IPV6, // use IPv6 + PJ_FALSE, // expected error + 0, // expected code + NULL, // expected realm + NULL, // expected nonce + &long_term_check3 // more check + ); if (rc != 0) { - goto done; + goto done; } /* @@ -1149,23 +1148,23 @@ int sess_auth_test(void) // authenticate successfully. rc = run_client_test("Invalid REALM (long term)", // title - PJ_TRUE, // server responding - PJ_STUN_AUTH_LONG_TERM, // server auth - PJ_STUN_AUTH_LONG_TERM, // client auth - "anotherrealm", // client realm - USERNAME, // client username - NONCE, // client nonce - PASSWORD, // client password - PJ_FALSE, // client dummy MI - USE_IPV6, // use IPv6 - PJ_TRUE, // expected error - PJ_STATUS_FROM_STUN_CODE(401), // expected code - REALM, // expected realm - NONCE, // expected nonce - &long_term_check1 // more check - ); + PJ_TRUE, // server responding + PJ_STUN_AUTH_LONG_TERM, // server auth + PJ_STUN_AUTH_LONG_TERM, // client auth + "anotherrealm", // client realm + USERNAME, // client username + NONCE, // client nonce + PASSWORD, // client password + PJ_FALSE, // client dummy MI + USE_IPV6, // use IPv6 + PJ_TRUE, // expected error + PJ_STATUS_FROM_STUN_CODE(401), // expected code + REALM, // expected realm + NONCE, // expected nonce + &long_term_check1 // more check + ); if (rc != 0) { - goto done; + goto done; } #endif diff --git a/pjnath/src/pjnath-test/stun.c b/pjnath/src/pjnath-test/stun.c index 5329e4d2fc..2fb692dd06 100644 --- a/pjnath/src/pjnath-test/stun.c +++ b/pjnath/src/pjnath-test/stun.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,7 +28,7 @@ static int verify5(pj_stun_msg*); static struct test { const char *title; - char *pdu; + char *pdu; unsigned pdu_len; pj_stun_msg* (*create)(pj_pool_t*); pj_status_t expected_status; @@ -37,184 +36,184 @@ static struct test } tests[] = { { - "Invalid message type", - "\x11\x01\x00\x00\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", - 20, - NULL, - PJNATH_EINSTUNMSGTYPE, - NULL + "Invalid message type", + "\x11\x01\x00\x00\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", + 20, + NULL, + PJNATH_EINSTUNMSGTYPE, + NULL }, { - "Short message (1) (partial header)", - "\x00\x01", - 2, - NULL, - PJNATH_EINSTUNMSGLEN, - NULL + "Short message (1) (partial header)", + "\x00\x01", + 2, + NULL, + PJNATH_EINSTUNMSGLEN, + NULL }, { - "Short message (2) (partial header)", - "\x00\x01\x00\x00\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00", - 16, - NULL, - PJNATH_EINSTUNMSGLEN, - NULL + "Short message (2) (partial header)", + "\x00\x01\x00\x00\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00", + 16, + NULL, + PJNATH_EINSTUNMSGLEN, + NULL }, { - "Short message (3), (missing attribute)", - "\x00\x01\x00\x08\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", - 20, - NULL, - PJNATH_EINSTUNMSGLEN, - NULL + "Short message (3), (missing attribute)", + "\x00\x01\x00\x08\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", + 20, + NULL, + PJNATH_EINSTUNMSGLEN, + NULL }, { - "Short message (4), (partial attribute header)", - "\x00\x01\x00\x08\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x80\x28", - 22, - NULL, - PJNATH_EINSTUNMSGLEN, - NULL + "Short message (4), (partial attribute header)", + "\x00\x01\x00\x08\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x80\x28", + 22, + NULL, + PJNATH_EINSTUNMSGLEN, + NULL }, { - "Short message (5), (partial attribute header)", - "\x00\x01\x00\x08\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x80\x28\x00", - 23, - NULL, - PJNATH_EINSTUNMSGLEN, - NULL + "Short message (5), (partial attribute header)", + "\x00\x01\x00\x08\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x80\x28\x00", + 23, + NULL, + PJNATH_EINSTUNMSGLEN, + NULL }, { - "Short message (6), (partial attribute header)", - "\x00\x01\x00\x08\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x80\x28\x00\x04", - 24, - NULL, - PJNATH_EINSTUNMSGLEN, - NULL + "Short message (6), (partial attribute header)", + "\x00\x01\x00\x08\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x80\x28\x00\x04", + 24, + NULL, + PJNATH_EINSTUNMSGLEN, + NULL }, { - "Short message (7), (partial attribute body)", - "\x00\x01\x00\x08\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x80\x28\x00\x04\x00\x00\x00", - 27, - NULL, - PJNATH_EINSTUNMSGLEN, - NULL + "Short message (7), (partial attribute body)", + "\x00\x01\x00\x08\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x80\x28\x00\x04\x00\x00\x00", + 27, + NULL, + PJNATH_EINSTUNMSGLEN, + NULL }, { - "Message length in header is too long", - "\x00\x01\xff\xff\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x80\x28\x00\x04\x00\x00\x00", - 27, - NULL, - PJNATH_EINSTUNMSGLEN, - NULL + "Message length in header is too long", + "\x00\x01\xff\xff\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x80\x28\x00\x04\x00\x00\x00", + 27, + NULL, + PJNATH_EINSTUNMSGLEN, + NULL }, { - "Message length in header is shorter", - "\x00\x01\x00\x04\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x80\x28\x00\x04\x00\x00\x00\x00", - 28, - NULL, - PJNATH_EINSTUNMSGLEN, - NULL + "Message length in header is shorter", + "\x00\x01\x00\x04\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x80\x28\x00\x04\x00\x00\x00\x00", + 28, + NULL, + PJNATH_EINSTUNMSGLEN, + NULL }, { - "Invalid magic", - "\x00\x01\x00\x08\x00\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x80\x28\x00\x04\x00\x00\x00\x00", - 28, - NULL, - PJ_SUCCESS, - NULL + "Invalid magic", + "\x00\x01\x00\x08\x00\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x80\x28\x00\x04\x00\x00\x00\x00", + 28, + NULL, + PJ_SUCCESS, + NULL }, { - "Character beyond message", - "\x00\x01\x00\x08\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x80\x28\x00\x04\x00\x00\x00\x00\x0a", - 29, - NULL, - PJNATH_EINSTUNMSGLEN, - NULL + "Character beyond message", + "\x00\x01\x00\x08\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x80\x28\x00\x04\x00\x00\x00\x00\x0a", + 29, + NULL, + PJNATH_EINSTUNMSGLEN, + NULL }, { - "Respond unknown mandatory attribute with 420 and " - "UNKNOWN-ATTRIBUTES attribute", - NULL, - 0, - &create1, - 0, - &verify1 + "Respond unknown mandatory attribute with 420 and " + "UNKNOWN-ATTRIBUTES attribute", + NULL, + 0, + &create1, + 0, + &verify1 }, { - "Unknown but non-mandatory should be okay", - "\x00\x01\x00\x08\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x80\xff\x00\x03\x00\x00\x00\x00", - 28, - NULL, - PJ_SUCCESS, - &verify2 + "Unknown but non-mandatory should be okay", + "\x00\x01\x00\x08\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x80\xff\x00\x03\x00\x00\x00\x00", + 28, + NULL, + PJ_SUCCESS, + &verify2 }, { - "String attr length larger than message", - "\x00\x01\x00\x08\x00\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x00\x06\x00\xff\x00\x00\x00\x00", - 28, - NULL, - PJNATH_ESTUNINATTRLEN, - NULL + "String attr length larger than message", + "\x00\x01\x00\x08\x00\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\x06\x00\xff\x00\x00\x00\x00", + 28, + NULL, + PJNATH_ESTUNINATTRLEN, + NULL }, { - "Attribute other than FINGERPRINT after MESSAGE-INTEGRITY is allowed", - "\x00\x01\x00\x20\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x00\x08\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" // M-I - "\x80\x24\x00\x04\x00\x00\x00\x00", // REFRESH-INTERVAL - 52, - NULL, - PJ_SUCCESS, - NULL + "Attribute other than FINGERPRINT after MESSAGE-INTEGRITY is allowed", + "\x00\x01\x00\x20\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\x08\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" // M-I + "\x80\x24\x00\x04\x00\x00\x00\x00", // REFRESH-INTERVAL + 52, + NULL, + PJ_SUCCESS, + NULL }, { - "Attribute between MESSAGE-INTEGRITY and FINGERPRINT is allowed", - "\x00\x01\x00\x28\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x00\x08\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" // M-I - "\x80\x24\x00\x04\x00\x00\x00\x00" // REFRESH-INTERVAL - "\x80\x28\x00\x04\xc7\xde\xdd\x65", // FINGERPRINT - 60, - NULL, - PJ_SUCCESS, - &verify5 + "Attribute between MESSAGE-INTEGRITY and FINGERPRINT is allowed", + "\x00\x01\x00\x28\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\x08\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" // M-I + "\x80\x24\x00\x04\x00\x00\x00\x00" // REFRESH-INTERVAL + "\x80\x28\x00\x04\xc7\xde\xdd\x65", // FINGERPRINT + 60, + NULL, + PJ_SUCCESS, + &verify5 }, { - "Attribute past FINGERPRINT is not allowed", - "\x00\x01\x00\x10\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x80\x28\x00\x04\x00\x00\x00\x00" - "\x80\x24\x00\x04\x00\x00\x00\x00", - 36, - NULL, - PJNATH_ESTUNFINGERPOS, - NULL + "Attribute past FINGERPRINT is not allowed", + "\x00\x01\x00\x10\x21\x12\xa4\x42" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x80\x28\x00\x04\x00\x00\x00\x00" + "\x80\x24\x00\x04\x00\x00\x00\x00", + 36, + NULL, + PJNATH_ESTUNFINGERPOS, + NULL } }; @@ -239,68 +238,68 @@ static int decode_test(void) PJ_LOG(3,(THIS_FILE, " STUN decode test")); for (i=0; ititle)); - - if (t->pdu) { - status = pj_stun_msg_decode(pool, (pj_uint8_t*)t->pdu, t->pdu_len, - PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET, - &msg, NULL, NULL); - - /* Check expected decode result */ - if (t->expected_status != status) { - PJ_LOG(1,(THIS_FILE, " expecting status %d, got %d", - t->expected_status, status)); - rc = -10; - goto on_return; - } - - } else { - msg = t->create(pool); - status = PJ_SUCCESS; - } - - if (status != PJ_SUCCESS) - continue; - - /* Try to encode message */ - pj_stun_create_key(pool, &key, NULL, &USERNAME, PJ_STUN_PASSWD_PLAIN, &PASSWORD); - status = pj_stun_msg_encode(msg, buf, sizeof(buf), 0, &key, &len); - if (status != PJ_SUCCESS) { - PJ_LOG(1,(THIS_FILE, " encode error: %s", err(status))); - rc = -40; - goto on_return; - } - - /* Try to decode it once more */ - status = pj_stun_msg_decode(pool, buf, len, - PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET, - &msg2, NULL, NULL); - if (status != PJ_SUCCESS) { - PJ_LOG(1,(THIS_FILE, " subsequent decoding failed: %s", err(status))); - rc = -50; - goto on_return; - } - - /* Verify */ - if (t->verify) { - rc = t->verify(msg); - if (rc != 0) { - goto on_return; - } - } + struct test *t = &tests[i]; + pj_stun_msg *msg, *msg2; + pj_uint8_t buf[1500]; + pj_str_t key; + pj_size_t len; + pj_status_t status; + + PJ_LOG(3,(THIS_FILE, " %s", t->title)); + + if (t->pdu) { + status = pj_stun_msg_decode(pool, (pj_uint8_t*)t->pdu, t->pdu_len, + PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET, + &msg, NULL, NULL); + + /* Check expected decode result */ + if (t->expected_status != status) { + PJ_LOG(1,(THIS_FILE, " expecting status %d, got %d", + t->expected_status, status)); + rc = -10; + goto on_return; + } + + } else { + msg = t->create(pool); + status = PJ_SUCCESS; + } + + if (status != PJ_SUCCESS) + continue; + + /* Try to encode message */ + pj_stun_create_key(pool, &key, NULL, &USERNAME, PJ_STUN_PASSWD_PLAIN, &PASSWORD); + status = pj_stun_msg_encode(msg, buf, sizeof(buf), 0, &key, &len); + if (status != PJ_SUCCESS) { + PJ_LOG(1,(THIS_FILE, " encode error: %s", err(status))); + rc = -40; + goto on_return; + } + + /* Try to decode it once more */ + status = pj_stun_msg_decode(pool, buf, len, + PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET, + &msg2, NULL, NULL); + if (status != PJ_SUCCESS) { + PJ_LOG(1,(THIS_FILE, " subsequent decoding failed: %s", err(status))); + rc = -50; + goto on_return; + } + + /* Verify */ + if (t->verify) { + rc = t->verify(msg); + if (rc != 0) { + goto on_return; + } + } } on_return: pj_pool_release(pool); if (rc == 0) - PJ_LOG(3,(THIS_FILE, "...success!")); + PJ_LOG(3,(THIS_FILE, "...success!")); return rc; } @@ -308,15 +307,15 @@ static int decode_test(void) static pj_stun_msg* create1(pj_pool_t *pool) { char *pdu = "\x00\x01\x00\x08\x21\x12\xa4\x42" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x00\xff\x00\x04\x00\x00\x00\x00"; + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\xff\x00\x04\x00\x00\x00\x00"; unsigned pdu_len = 28; pj_stun_msg *msg, *res; pj_status_t status; status = pj_stun_msg_decode(pool, (pj_uint8_t*)pdu, pdu_len, - PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET, - &msg, NULL, &res); + PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET, + &msg, NULL, &res); pj_assert(status != PJ_SUCCESS); PJ_UNUSED_ARG(status); pj_assert(res != NULL); @@ -332,37 +331,37 @@ static int verify1(pj_stun_msg *msg) pj_stun_unknown_attr *aunk; if (!PJ_STUN_IS_ERROR_RESPONSE(msg->hdr.type)) { - PJ_LOG(1,(THIS_FILE, " expecting error message")); - return -100; + PJ_LOG(1,(THIS_FILE, " expecting error message")); + return -100; } aerr = (pj_stun_errcode_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_ERROR_CODE, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_ERROR_CODE, 0); if (aerr == NULL) { - PJ_LOG(1,(THIS_FILE, " missing ERROR-CODE attribute")); - return -110; + PJ_LOG(1,(THIS_FILE, " missing ERROR-CODE attribute")); + return -110; } if (aerr->err_code != 420) { - PJ_LOG(1,(THIS_FILE, " expecting 420 error")); - return -120; + PJ_LOG(1,(THIS_FILE, " expecting 420 error")); + return -120; } aunk = (pj_stun_unknown_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_UNKNOWN_ATTRIBUTES, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_UNKNOWN_ATTRIBUTES, 0); if (aunk == NULL) { - PJ_LOG(1,(THIS_FILE, " missing UNKNOWN-ATTRIBUTE attribute")); - return -130; + PJ_LOG(1,(THIS_FILE, " missing UNKNOWN-ATTRIBUTE attribute")); + return -130; } if (aunk->attr_count != 1) { - PJ_LOG(1,(THIS_FILE, " expecting one unknown attribute")); - return -140; + PJ_LOG(1,(THIS_FILE, " expecting one unknown attribute")); + return -140; } if (aunk->attrs[0] != 0xff) { - PJ_LOG(1,(THIS_FILE, " expecting 0xff as unknown attribute")); - return -150; + PJ_LOG(1,(THIS_FILE, " expecting 0xff as unknown attribute")); + return -150; } return 0; @@ -374,26 +373,26 @@ static int verify2(pj_stun_msg *msg) pj_stun_binary_attr *bin_attr; if (msg->attr_count != 1) { - PJ_LOG(1,(THIS_FILE, " expecting one attribute count")); - return -200; + PJ_LOG(1,(THIS_FILE, " expecting one attribute count")); + return -200; } bin_attr = (pj_stun_binary_attr*)msg->attr[0]; if (bin_attr->hdr.type != 0x80ff) { - PJ_LOG(1,(THIS_FILE, " expecting attribute type 0x80ff")); - return -210; + PJ_LOG(1,(THIS_FILE, " expecting attribute type 0x80ff")); + return -210; } if (bin_attr->hdr.length != 3) { - PJ_LOG(1,(THIS_FILE, " expecting attribute length = 4")); - return -220; + PJ_LOG(1,(THIS_FILE, " expecting attribute length = 4")); + return -220; } if (bin_attr->magic != PJ_STUN_MAGIC) { - PJ_LOG(1,(THIS_FILE, " expecting PJ_STUN_MAGIC for unknown attr")); - return -230; + PJ_LOG(1,(THIS_FILE, " expecting PJ_STUN_MAGIC for unknown attr")); + return -230; } if (bin_attr->length != 3) { - PJ_LOG(1,(THIS_FILE, " expecting data length 4")); - return -240; + PJ_LOG(1,(THIS_FILE, " expecting data length 4")); + return -240; } return 0; @@ -404,21 +403,21 @@ static int verify2(pj_stun_msg *msg) static int verify5(pj_stun_msg *msg) { if (msg->attr_count != 3) { - PJ_LOG(1,(THIS_FILE, " expecting 3 attribute count")); - return -500; + PJ_LOG(1,(THIS_FILE, " expecting 3 attribute count")); + return -500; } if (msg->attr[0]->type != PJ_STUN_ATTR_MESSAGE_INTEGRITY) { - PJ_LOG(1,(THIS_FILE, " expecting MESSAGE-INTEGRITY")); - return -510; + PJ_LOG(1,(THIS_FILE, " expecting MESSAGE-INTEGRITY")); + return -510; } if (msg->attr[1]->type != PJ_STUN_ATTR_REFRESH_INTERVAL) { - PJ_LOG(1,(THIS_FILE, " expecting REFRESH-INTERVAL")); - return -520; + PJ_LOG(1,(THIS_FILE, " expecting REFRESH-INTERVAL")); + return -520; } if (msg->attr[2]->type != PJ_STUN_ATTR_FINGERPRINT) { - PJ_LOG(1,(THIS_FILE, " expecting FINGERPRINT")); - return -530; + PJ_LOG(1,(THIS_FILE, " expecting FINGERPRINT")); + return -530; } return 0; @@ -444,67 +443,67 @@ static pj_stun_msg* create_msgint3(pj_pool_t *pool, test_vector *v); enum { USE_MESSAGE_INTEGRITY = 1, - USE_FINGERPRINT = 2 + USE_FINGERPRINT = 2 }; static struct test_vector { - unsigned msg_type; - char *tsx_id; - char *pdu; - unsigned pdu_len; - unsigned options; - char *username; - char *password; - char *realm; - char *nonce; + unsigned msg_type; + char *tsx_id; + char *pdu; + unsigned pdu_len; + unsigned options; + char *username; + char *password; + char *realm; + char *nonce; pj_stun_msg* (*create)(pj_pool_t*, test_vector*); } test_vectors[] = { { - PJ_STUN_BINDING_REQUEST, - "\xb7\xe7\xa7\x01\xbc\x34\xd6\x86\xfa\x87\xdf\xae", - "\x00\x01\x00\x44\x21\x12\xa4\x42\xb7\xe7" - "\xa7\x01\xbc\x34\xd6\x86\xfa\x87\xdf\xae" - "\x00\x24\x00\x04\x6e\x00\x01\xff\x80\x29" - "\x00\x08\x93\x2f\xf9\xb1\x51\x26\x3b\x36" - "\x00\x06\x00\x09\x65\x76\x74\x6a\x3a\x68" - "\x36\x76\x59\x20\x20\x20\x00\x08\x00\x14" - "\x62\x4e\xeb\xdc\x3c\xc9\x2d\xd8\x4b\x74" - "\xbf\x85\xd1\xc0\xf5\xde\x36\x87\xbd\x33" - "\x80\x28\x00\x04\xad\x8a\x85\xff", - 88, - USE_MESSAGE_INTEGRITY | USE_FINGERPRINT, - "evtj:h6vY", - "VOkJxbRl1RmTxUk/WvJxBt", - "", - "", - &create_msgint1 + PJ_STUN_BINDING_REQUEST, + "\xb7\xe7\xa7\x01\xbc\x34\xd6\x86\xfa\x87\xdf\xae", + "\x00\x01\x00\x44\x21\x12\xa4\x42\xb7\xe7" + "\xa7\x01\xbc\x34\xd6\x86\xfa\x87\xdf\xae" + "\x00\x24\x00\x04\x6e\x00\x01\xff\x80\x29" + "\x00\x08\x93\x2f\xf9\xb1\x51\x26\x3b\x36" + "\x00\x06\x00\x09\x65\x76\x74\x6a\x3a\x68" + "\x36\x76\x59\x20\x20\x20\x00\x08\x00\x14" + "\x62\x4e\xeb\xdc\x3c\xc9\x2d\xd8\x4b\x74" + "\xbf\x85\xd1\xc0\xf5\xde\x36\x87\xbd\x33" + "\x80\x28\x00\x04\xad\x8a\x85\xff", + 88, + USE_MESSAGE_INTEGRITY | USE_FINGERPRINT, + "evtj:h6vY", + "VOkJxbRl1RmTxUk/WvJxBt", + "", + "", + &create_msgint1 } /* disabled: see https://github.com/pjsip/pjproject/issues/960 , { - PJ_STUN_BINDING_RESPONSE, - "\xb7\xe7\xa7\x01\xbc\x34\xd6\x86\xfa\x87\xdf\xae", - "\x01\x01\x00\x3c" - "\x21\x12\xa4\x42" - "\xb7\xe7\xa7\x01\xbc\x34\xd6\x86\xfa\x87\xdf\xae" - "\x80\x22\x00\x0b" - "\x74\x65\x73\x74\x20\x76\x65\x63\x74\x6f\x72\x20" - "\x00\x20\x00\x08" - "\x00\x01\xa1\x47\xe1\x12\xa6\x43" - "\x00\x08\x00\x14" - "\x2b\x91\xf5\x99\xfd\x9e\x90\xc3\x8c\x74\x89\xf9" - "\x2a\xf9\xba\x53\xf0\x6b\xe7\xd7" - "\x80\x28\x00\x04" - "\xc0\x7d\x4c\x96", - 80, - USE_MESSAGE_INTEGRITY | USE_FINGERPRINT, - "evtj:h6vY", - "VOkJxbRl1RmTxUk/WvJxBt", - "", - "", - &create_msgint2 + PJ_STUN_BINDING_RESPONSE, + "\xb7\xe7\xa7\x01\xbc\x34\xd6\x86\xfa\x87\xdf\xae", + "\x01\x01\x00\x3c" + "\x21\x12\xa4\x42" + "\xb7\xe7\xa7\x01\xbc\x34\xd6\x86\xfa\x87\xdf\xae" + "\x80\x22\x00\x0b" + "\x74\x65\x73\x74\x20\x76\x65\x63\x74\x6f\x72\x20" + "\x00\x20\x00\x08" + "\x00\x01\xa1\x47\xe1\x12\xa6\x43" + "\x00\x08\x00\x14" + "\x2b\x91\xf5\x99\xfd\x9e\x90\xc3\x8c\x74\x89\xf9" + "\x2a\xf9\xba\x53\xf0\x6b\xe7\xd7" + "\x80\x28\x00\x04" + "\xc0\x7d\x4c\x96", + 80, + USE_MESSAGE_INTEGRITY | USE_FINGERPRINT, + "evtj:h6vY", + "VOkJxbRl1RmTxUk/WvJxBt", + "", + "", + &create_msgint2 } */ @@ -512,9 +511,9 @@ static struct test_vector #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6!=0 , { - PJ_STUN_BINDING_RESPONSE, - "\xb7\xe7\xa7\x01\xbc\x34\xd6\x86\xfa\x87\xdf\xae", - "\x01\x01\x00\x48" // Response type and message length + PJ_STUN_BINDING_RESPONSE, + "\xb7\xe7\xa7\x01\xbc\x34\xd6\x86\xfa\x87\xdf\xae", + "\x01\x01\x00\x48" // Response type and message length "\x21\x12\xa4\x42" // Message cookie "\xb7\xe7\xa7\x01" // } "\xbc\x34\xd6\x86" // } Transaction ID @@ -538,14 +537,14 @@ static struct test_vector "\xbf\xe3\xed\x41" // } "\x80\x28\x00\x04" // FINGERPRINT attribute header "\xc8\xfb\x0b\x4c" // CRC32 fingerprint - , - 92, - USE_MESSAGE_INTEGRITY | USE_FINGERPRINT, - "evtj:h6vY", - "VOkJxbRl1RmTxUk/WvJxBt", - "", - "", - &create_msgint3 + , + 92, + USE_MESSAGE_INTEGRITY | USE_FINGERPRINT, + "evtj:h6vY", + "VOkJxbRl1RmTxUk/WvJxBt", + "", + "", + &create_msgint3 } #endif */ @@ -560,21 +559,21 @@ static char* print_binary(const pj_uint8_t *data, unsigned data_len) unsigned i; for (i=0; ipdu, v->pdu_len))); - - /* Try to parse the reference message first */ - status = pj_stun_msg_decode(pool, (pj_uint8_t*)v->pdu, v->pdu_len, - PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET, - &ref_msg, &parsed_len, NULL); - if (status != PJ_SUCCESS) { - PJ_LOG(1,(THIS_FILE, " Error decoding reference message")); - rc = -1010; - goto on_return; - } - - if (parsed_len != v->pdu_len) { - PJ_LOG(1,(THIS_FILE, " Parsed len error")); - rc = -1020; - goto on_return; - } - - /* Print the reference message */ - pj_stun_msg_dump(ref_msg, print, sizeof(print), NULL); - PJ_LOG(4,(THIS_FILE, "Reference message:\n%s", print)); - - /* Create our message */ - msg = v->create(pool, v); - if (msg == NULL) { - PJ_LOG(1,(THIS_FILE, " Error creating stun message")); - rc = -1030; - goto on_return; - } - - /* Encode message */ - if (v->options & USE_MESSAGE_INTEGRITY) { - pj_str_t s1, s2, r; - - pj_stun_create_key(pool, &key, pj_cstr(&r, v->realm), - pj_cstr(&s1, v->username), - PJ_STUN_PASSWD_PLAIN, - pj_cstr(&s2, v->password)); - pj_stun_msg_encode(msg, buf, sizeof(buf), 0, &key, &len); - - } else { - pj_stun_msg_encode(msg, buf, sizeof(buf), 0, NULL, &len); - } - - /* Print our raw message */ - PJ_LOG(4,(THIS_FILE, "Message PDU:\n%s", - print_binary((pj_uint8_t*)buf, (unsigned)len))); - - /* Print our message */ - pj_stun_msg_dump(msg, print, sizeof(print), NULL); - PJ_LOG(4,(THIS_FILE, "Message is:\n%s", print)); - - /* Compare message length */ - if (len != v->pdu_len) { - PJ_LOG(1,(THIS_FILE, " Message length mismatch")); - rc = -1050; - goto on_return; - } - - pos = cmp_buf(buf, (const pj_uint8_t*)v->pdu, (unsigned)len); - if (pos != (unsigned)-1) { - PJ_LOG(1,(THIS_FILE, " Message mismatch at byte %d", pos)); - rc = -1060; - goto on_return; - } - - /* Authenticate the request/response */ - if (v->options & USE_MESSAGE_INTEGRITY) { - if (PJ_STUN_IS_REQUEST(msg->hdr.type)) { - pj_stun_auth_cred cred; - pj_status_t status2; - - pj_bzero(&cred, sizeof(cred)); - cred.type = PJ_STUN_AUTH_CRED_STATIC; - cred.data.static_cred.realm = pj_str(v->realm); - cred.data.static_cred.username = pj_str(v->username); - cred.data.static_cred.data = pj_str(v->password); - cred.data.static_cred.nonce = pj_str(v->nonce); - - status2 = pj_stun_authenticate_request(buf, (unsigned)len, msg, - &cred, pool, NULL, NULL); - if (status2 != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status2, errmsg, sizeof(errmsg)); - PJ_LOG(1,(THIS_FILE, - " Request authentication failed: %s", - errmsg)); - rc = -1070; - goto on_return; - } - - } else if (PJ_STUN_IS_RESPONSE(msg->hdr.type)) { - pj_status_t status2; - status2 = pj_stun_authenticate_response(buf, (unsigned)len, - msg, &key); - if (status2 != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status2, errmsg, sizeof(errmsg)); - PJ_LOG(1,(THIS_FILE, - " Response authentication failed: %s", - errmsg)); - rc = -1080; - goto on_return; - } - } - } + struct test_vector *v; + pj_stun_msg *ref_msg, *msg; + pj_size_t parsed_len; + pj_size_t len; + unsigned pos; + pj_uint8_t buf[1500]; + char print[1500]; + pj_str_t key; + + PJ_LOG(3,(THIS_FILE, " Running test %d/%d", i, + PJ_ARRAY_SIZE(test_vectors))); + + v = &test_vectors[i]; + + /* Print reference message */ + PJ_LOG(4,(THIS_FILE, "Reference message PDU:\n%s", + print_binary((pj_uint8_t*)v->pdu, v->pdu_len))); + + /* Try to parse the reference message first */ + status = pj_stun_msg_decode(pool, (pj_uint8_t*)v->pdu, v->pdu_len, + PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET, + &ref_msg, &parsed_len, NULL); + if (status != PJ_SUCCESS) { + PJ_LOG(1,(THIS_FILE, " Error decoding reference message")); + rc = -1010; + goto on_return; + } + + if (parsed_len != v->pdu_len) { + PJ_LOG(1,(THIS_FILE, " Parsed len error")); + rc = -1020; + goto on_return; + } + + /* Print the reference message */ + pj_stun_msg_dump(ref_msg, print, sizeof(print), NULL); + PJ_LOG(4,(THIS_FILE, "Reference message:\n%s", print)); + + /* Create our message */ + msg = v->create(pool, v); + if (msg == NULL) { + PJ_LOG(1,(THIS_FILE, " Error creating stun message")); + rc = -1030; + goto on_return; + } + + /* Encode message */ + if (v->options & USE_MESSAGE_INTEGRITY) { + pj_str_t s1, s2, r; + + pj_stun_create_key(pool, &key, pj_cstr(&r, v->realm), + pj_cstr(&s1, v->username), + PJ_STUN_PASSWD_PLAIN, + pj_cstr(&s2, v->password)); + pj_stun_msg_encode(msg, buf, sizeof(buf), 0, &key, &len); + + } else { + pj_stun_msg_encode(msg, buf, sizeof(buf), 0, NULL, &len); + } + + /* Print our raw message */ + PJ_LOG(4,(THIS_FILE, "Message PDU:\n%s", + print_binary((pj_uint8_t*)buf, (unsigned)len))); + + /* Print our message */ + pj_stun_msg_dump(msg, print, sizeof(print), NULL); + PJ_LOG(4,(THIS_FILE, "Message is:\n%s", print)); + + /* Compare message length */ + if (len != v->pdu_len) { + PJ_LOG(1,(THIS_FILE, " Message length mismatch")); + rc = -1050; + goto on_return; + } + + pos = cmp_buf(buf, (const pj_uint8_t*)v->pdu, (unsigned)len); + if (pos != (unsigned)-1) { + PJ_LOG(1,(THIS_FILE, " Message mismatch at byte %d", pos)); + rc = -1060; + goto on_return; + } + + /* Authenticate the request/response */ + if (v->options & USE_MESSAGE_INTEGRITY) { + if (PJ_STUN_IS_REQUEST(msg->hdr.type)) { + pj_stun_auth_cred cred; + pj_status_t status2; + + pj_bzero(&cred, sizeof(cred)); + cred.type = PJ_STUN_AUTH_CRED_STATIC; + cred.data.static_cred.realm = pj_str(v->realm); + cred.data.static_cred.username = pj_str(v->username); + cred.data.static_cred.data = pj_str(v->password); + cred.data.static_cred.nonce = pj_str(v->nonce); + + status2 = pj_stun_authenticate_request(buf, (unsigned)len, msg, + &cred, pool, NULL, NULL); + if (status2 != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status2, errmsg, sizeof(errmsg)); + PJ_LOG(1,(THIS_FILE, + " Request authentication failed: %s", + errmsg)); + rc = -1070; + goto on_return; + } + + } else if (PJ_STUN_IS_RESPONSE(msg->hdr.type)) { + pj_status_t status2; + status2 = pj_stun_authenticate_response(buf, (unsigned)len, + msg, &key); + if (status2 != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status2, errmsg, sizeof(errmsg)); + PJ_LOG(1,(THIS_FILE, + " Response authentication failed: %s", + errmsg)); + rc = -1080; + goto on_return; + } + } + } } @@ -745,34 +744,34 @@ static pj_stun_msg* create_msgint1(pj_pool_t *pool, test_vector *v) pj_status_t status; status = pj_stun_msg_create(pool, v->msg_type, PJ_STUN_MAGIC, - (pj_uint8_t*)v->tsx_id, &msg); + (pj_uint8_t*)v->tsx_id, &msg); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_stun_msg_add_uint_attr(pool, msg, PJ_STUN_ATTR_PRIORITY, - 0x6e0001ff); + 0x6e0001ff); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; u64.u32.hi = 0x932ff9b1; u64.u32.lo = 0x51263b36; status = pj_stun_msg_add_uint64_attr(pool, msg, - PJ_STUN_ATTR_ICE_CONTROLLED, &u64); + PJ_STUN_ATTR_ICE_CONTROLLED, &u64); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_stun_msg_add_string_attr(pool, msg, PJ_STUN_ATTR_USERNAME, - pj_cstr(&s1, v->username)); + pj_cstr(&s1, v->username)); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_stun_msg_add_msgint_attr(pool, msg); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_stun_msg_add_uint_attr(pool, msg, PJ_STUN_ATTR_FINGERPRINT, 0); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; return msg; @@ -789,34 +788,34 @@ static pj_stun_msg* create_msgint2(pj_pool_t *pool, test_vector *v) pj_status_t status; status = pj_stun_msg_create(pool, v->msg_type, PJ_STUN_MAGIC, - (pj_uint8_t*)v->tsx_id, &msg); + (pj_uint8_t*)v->tsx_id, &msg); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_stun_msg_add_string_attr(pool, msg, PJ_STUN_ATTR_SOFTWARE, - pj_cstr(&s1, "test vector")); + pj_cstr(&s1, "test vector")); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_sockaddr_in_init(&mapped_addr, pj_cstr(&s1, "192.0.2.1"), - 32853); + 32853); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_stun_msg_add_sockaddr_attr(pool, msg, - PJ_STUN_ATTR_XOR_MAPPED_ADDR, - PJ_TRUE, &mapped_addr, - sizeof(pj_sockaddr_in)); + PJ_STUN_ATTR_XOR_MAPPED_ADDR, + PJ_TRUE, &mapped_addr, + sizeof(pj_sockaddr_in)); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_stun_msg_add_msgint_attr(pool, msg); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_stun_msg_add_uint_attr(pool, msg, PJ_STUN_ATTR_FINGERPRINT, 0); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; return msg; @@ -834,35 +833,35 @@ static pj_stun_msg* create_msgint3(pj_pool_t *pool, test_vector *v) pj_status_t status; status = pj_stun_msg_create(pool, v->msg_type, PJ_STUN_MAGIC, - (pj_uint8_t*)v->tsx_id, &msg); + (pj_uint8_t*)v->tsx_id, &msg); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_stun_msg_add_string_attr(pool, msg, PJ_STUN_ATTR_SOFTWARE, - pj_cstr(&s1, "test vector")); + pj_cstr(&s1, "test vector")); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_sockaddr_init(pj_AF_INET6(), &mapped_addr, - pj_cstr(&s1, "2001:db8:1234:5678:11:2233:4455:6677"), - 32853); + pj_cstr(&s1, "2001:db8:1234:5678:11:2233:4455:6677"), + 32853); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_stun_msg_add_sockaddr_attr(pool, msg, - PJ_STUN_ATTR_XOR_MAPPED_ADDR, - PJ_TRUE, &mapped_addr, - sizeof(pj_sockaddr)); + PJ_STUN_ATTR_XOR_MAPPED_ADDR, + PJ_TRUE, &mapped_addr, + sizeof(pj_sockaddr)); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_stun_msg_add_msgint_attr(pool, msg); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_stun_msg_add_uint_attr(pool, msg, PJ_STUN_ATTR_FINGERPRINT, 0); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; return msg; @@ -878,24 +877,24 @@ static int cmp_msg(const pj_stun_msg *msg1, const pj_stun_msg *msg2) unsigned i; if (msg1->hdr.type != msg2->hdr.type) - return -10; + return -10; if (msg1->hdr.length != msg2->hdr.length) - return -20; + return -20; if (msg1->hdr.magic != msg2->hdr.magic) - return -30; + return -30; if (pj_memcmp(msg1->hdr.tsx_id, msg2->hdr.tsx_id, sizeof(msg1->hdr.tsx_id))) - return -40; + return -40; if (msg1->attr_count != msg2->attr_count) - return -50; + return -50; for (i=0; iattr_count; ++i) { - const pj_stun_attr_hdr *a1 = msg1->attr[i]; - const pj_stun_attr_hdr *a2 = msg2->attr[i]; + const pj_stun_attr_hdr *a1 = msg1->attr[i]; + const pj_stun_attr_hdr *a2 = msg2->attr[i]; - if (a1->type != a2->type) - return -60; - if (a1->length != a2->length) - return -70; + if (a1->type != a2->type) + return -60; + if (a1->length != a2->length) + return -70; } return 0; @@ -923,17 +922,17 @@ static int handle_unknown_non_mandatory(void) #if 0 if (1) { - unsigned i; - puts(""); - printf("{ "); - for (i=0; i @@ -23,9 +22,9 @@ enum { RESPOND_STUN = 1, - WITH_MAPPED = 2, + WITH_MAPPED = 2, WITH_XOR_MAPPED = 4, - ECHO = 8 + ECHO = 8 }; /* @@ -33,21 +32,21 @@ enum { */ struct stun_srv { - pj_activesock_t *asock; - unsigned flag; - pj_sockaddr addr; - unsigned rx_cnt; - pj_ioqueue_op_key_t send_key; - pj_str_t ip_to_send; - pj_uint16_t port_to_send; + pj_activesock_t *asock; + unsigned flag; + pj_sockaddr addr; + unsigned rx_cnt; + pj_ioqueue_op_key_t send_key; + pj_str_t ip_to_send; + pj_uint16_t port_to_send; }; static pj_bool_t srv_on_data_recvfrom(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status) + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status) { struct stun_srv *srv; pj_ssize_t sent; @@ -56,79 +55,79 @@ static pj_bool_t srv_on_data_recvfrom(pj_activesock_t *asock, /* Ignore error */ if (status != PJ_SUCCESS) - return PJ_TRUE; + return PJ_TRUE; ++srv->rx_cnt; /* Ignore if we're not responding */ if (srv->flag & RESPOND_STUN) { - pj_pool_t *pool; - pj_stun_msg *req_msg, *res_msg; + pj_pool_t *pool; + pj_stun_msg *req_msg, *res_msg; - pool = pj_pool_create(mem, "stunsrv", 512, 512, NULL); + pool = pj_pool_create(mem, "stunsrv", 512, 512, NULL); - /* Parse request */ - status = pj_stun_msg_decode(pool, (pj_uint8_t*)data, size, - PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET, - &req_msg, NULL, NULL); - if (status != PJ_SUCCESS) { - app_perror(" pj_stun_msg_decode()", status); - pj_pool_release(pool); - return PJ_TRUE; - } - - /* Create response */ - status = pj_stun_msg_create(pool, PJ_STUN_BINDING_RESPONSE, PJ_STUN_MAGIC, - req_msg->hdr.tsx_id, &res_msg); - if (status != PJ_SUCCESS) { - app_perror(" pj_stun_msg_create()", status); - pj_pool_release(pool); - return PJ_TRUE; - } - - /* Add MAPPED-ADDRESS or XOR-MAPPED-ADDRESS (or don't add) */ - if (srv->flag & WITH_MAPPED) { - pj_sockaddr addr; - pj_bool_t use_ipv6 = (srv->addr.addr.sa_family == pj_AF_INET6()); - - pj_sockaddr_init(GET_AF(use_ipv6), &addr, &srv->ip_to_send, - srv->port_to_send); - - pj_stun_msg_add_sockaddr_attr(pool, res_msg, PJ_STUN_ATTR_MAPPED_ADDR, - PJ_FALSE, &addr, sizeof(addr)); - } else if (srv->flag & WITH_XOR_MAPPED) { - pj_sockaddr addr; - pj_bool_t use_ipv6 = (srv->addr.addr.sa_family == pj_AF_INET6()); - - pj_sockaddr_init(GET_AF(use_ipv6), &addr, &srv->ip_to_send, - srv->port_to_send); - - pj_stun_msg_add_sockaddr_attr(pool, res_msg, - PJ_STUN_ATTR_XOR_MAPPED_ADDR, - PJ_TRUE, &addr, sizeof(addr)); - } - - /* Encode */ - status = pj_stun_msg_encode(res_msg, (pj_uint8_t*)data, 100, 0, - NULL, &size); - if (status != PJ_SUCCESS) { - app_perror(" pj_stun_msg_encode()", status); - pj_pool_release(pool); - return PJ_TRUE; - } - - /* Send back */ - sent = size; - pj_activesock_sendto(asock, &srv->send_key, data, &sent, 0, - src_addr, addr_len); - - pj_pool_release(pool); + /* Parse request */ + status = pj_stun_msg_decode(pool, (pj_uint8_t*)data, size, + PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET, + &req_msg, NULL, NULL); + if (status != PJ_SUCCESS) { + app_perror(" pj_stun_msg_decode()", status); + pj_pool_release(pool); + return PJ_TRUE; + } + + /* Create response */ + status = pj_stun_msg_create(pool, PJ_STUN_BINDING_RESPONSE, PJ_STUN_MAGIC, + req_msg->hdr.tsx_id, &res_msg); + if (status != PJ_SUCCESS) { + app_perror(" pj_stun_msg_create()", status); + pj_pool_release(pool); + return PJ_TRUE; + } + + /* Add MAPPED-ADDRESS or XOR-MAPPED-ADDRESS (or don't add) */ + if (srv->flag & WITH_MAPPED) { + pj_sockaddr addr; + pj_bool_t use_ipv6 = (srv->addr.addr.sa_family == pj_AF_INET6()); + + pj_sockaddr_init(GET_AF(use_ipv6), &addr, &srv->ip_to_send, + srv->port_to_send); + + pj_stun_msg_add_sockaddr_attr(pool, res_msg, PJ_STUN_ATTR_MAPPED_ADDR, + PJ_FALSE, &addr, sizeof(addr)); + } else if (srv->flag & WITH_XOR_MAPPED) { + pj_sockaddr addr; + pj_bool_t use_ipv6 = (srv->addr.addr.sa_family == pj_AF_INET6()); + + pj_sockaddr_init(GET_AF(use_ipv6), &addr, &srv->ip_to_send, + srv->port_to_send); + + pj_stun_msg_add_sockaddr_attr(pool, res_msg, + PJ_STUN_ATTR_XOR_MAPPED_ADDR, + PJ_TRUE, &addr, sizeof(addr)); + } + + /* Encode */ + status = pj_stun_msg_encode(res_msg, (pj_uint8_t*)data, 100, 0, + NULL, &size); + if (status != PJ_SUCCESS) { + app_perror(" pj_stun_msg_encode()", status); + pj_pool_release(pool); + return PJ_TRUE; + } + + /* Send back */ + sent = size; + pj_activesock_sendto(asock, &srv->send_key, data, &sent, 0, + src_addr, addr_len); + + pj_pool_release(pool); } else if (srv->flag & ECHO) { - /* Send back */ - sent = size; - pj_activesock_sendto(asock, &srv->send_key, data, &sent, 0, - src_addr, addr_len); + /* Send back */ + sent = size; + pj_activesock_sendto(asock, &srv->send_key, data, &sent, 0, + src_addr, addr_len); } @@ -136,10 +135,10 @@ static pj_bool_t srv_on_data_recvfrom(pj_activesock_t *asock, } static pj_status_t create_server(pj_pool_t *pool, - pj_ioqueue_t *ioqueue, - unsigned flag, - pj_bool_t use_ipv6, - struct stun_srv **p_srv) + pj_ioqueue_t *ioqueue, + unsigned flag, + pj_bool_t use_ipv6, + struct stun_srv **p_srv) { struct stun_srv *srv; pj_activesock_cb activesock_cb; @@ -152,22 +151,22 @@ static pj_status_t create_server(pj_pool_t *pool, status = pj_sockaddr_init(GET_AF(use_ipv6), &srv->addr, NULL, 0); if (status != PJ_SUCCESS) - return status; + return status; pj_bzero(&activesock_cb, sizeof(activesock_cb)); activesock_cb.on_data_recvfrom = &srv_on_data_recvfrom; status = pj_activesock_create_udp(pool, &srv->addr, NULL, ioqueue, - &activesock_cb, srv, &srv->asock, - &srv->addr); + &activesock_cb, srv, &srv->asock, + &srv->addr); if (status != PJ_SUCCESS) - return status; + return status; pj_ioqueue_op_key_init(&srv->send_key, sizeof(srv->send_key)); status = pj_activesock_start_recvfrom(srv->asock, pool, 512, 0); if (status != PJ_SUCCESS) { - pj_activesock_close(srv->asock); - return status; + pj_activesock_close(srv->asock); + return status; } *p_srv = srv; @@ -182,22 +181,22 @@ static void destroy_server(struct stun_srv *srv) struct stun_client { - pj_pool_t *pool; - pj_stun_sock *sock; + pj_pool_t *pool; + pj_stun_sock *sock; - pj_ioqueue_op_key_t send_key; - pj_bool_t destroy_on_err; + pj_ioqueue_op_key_t send_key; + pj_bool_t destroy_on_err; - unsigned on_status_cnt; - pj_stun_sock_op last_op; - pj_status_t last_status; + unsigned on_status_cnt; + pj_stun_sock_op last_op; + pj_status_t last_status; - unsigned on_rx_data_cnt; + unsigned on_rx_data_cnt; }; static pj_bool_t stun_sock_on_status(pj_stun_sock *stun_sock, - pj_stun_sock_op op, - pj_status_t status) + pj_stun_sock_op op, + pj_status_t status) { struct stun_client *client; @@ -207,19 +206,19 @@ static pj_bool_t stun_sock_on_status(pj_stun_sock *stun_sock, client->last_status = status; if (status != PJ_SUCCESS && client->destroy_on_err) { - pj_stun_sock_destroy(client->sock); - client->sock = NULL; - return PJ_FALSE; + pj_stun_sock_destroy(client->sock); + client->sock = NULL; + return PJ_FALSE; } return PJ_TRUE; } static pj_bool_t stun_sock_on_rx_data(pj_stun_sock *stun_sock, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *src_addr, - unsigned addr_len) + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *src_addr, + unsigned addr_len) { struct stun_client *client; @@ -235,9 +234,9 @@ static pj_bool_t stun_sock_on_rx_data(pj_stun_sock *stun_sock, } static pj_status_t create_client(pj_stun_config *cfg, - struct stun_client **p_client, - pj_bool_t destroy_on_err, - pj_bool_t use_ipv6) + struct stun_client **p_client, + pj_bool_t destroy_on_err, + pj_bool_t use_ipv6) { pj_pool_t *pool; struct stun_client *client; @@ -255,11 +254,11 @@ static pj_status_t create_client(pj_stun_config *cfg, cb.on_status = &stun_sock_on_status; cb.on_rx_data = &stun_sock_on_rx_data; status = pj_stun_sock_create(cfg, NULL, GET_AF(use_ipv6), &cb, &sock_cfg, - client, &client->sock); + client, &client->sock); if (status != PJ_SUCCESS) { - app_perror(" pj_stun_sock_create()", status); - pj_pool_release(pool); - return status; + app_perror(" pj_stun_sock_create()", status); + pj_pool_release(pool); + return status; } pj_stun_sock_set_user_data(client->sock, client); @@ -277,8 +276,8 @@ static pj_status_t create_client(pj_stun_config *cfg, static void destroy_client(struct stun_client *client) { if (client->sock) { - pj_stun_sock_destroy(client->sock); - client->sock = NULL; + pj_stun_sock_destroy(client->sock); + client->sock = NULL; } pj_pool_release(client->pool); } @@ -300,7 +299,7 @@ static void handle_events(pj_stun_config *cfg, unsigned msec_delay) * Timeout test: scenario when no response is received from server */ static int timeout_test(pj_stun_config *cfg, pj_bool_t destroy_on_err, - pj_bool_t use_ipv6) + pj_bool_t use_ipv6) { struct stun_srv *srv; struct stun_client *client; @@ -310,70 +309,70 @@ static int timeout_test(pj_stun_config *cfg, pj_bool_t destroy_on_err, pj_status_t status; PJ_LOG(3,(THIS_FILE, " timeout test [%d] - (%s)", destroy_on_err, - (use_ipv6)?"IPv6":"IPv4")); + (use_ipv6)?"IPv6":"IPv4")); status = create_client(cfg, &client, destroy_on_err, use_ipv6); if (status != PJ_SUCCESS) - return -10; + return -10; status = create_server(client->pool, cfg->ioqueue, 0, use_ipv6, &srv); if (status != PJ_SUCCESS) { - destroy_client(client); - return -20; + destroy_client(client); + return -20; } srv_addr = (use_ipv6)?pj_str("::1"):pj_str("127.0.0.1"); status = pj_stun_sock_start(client->sock, &srv_addr, - pj_sockaddr_get_port(&srv->addr), NULL); + pj_sockaddr_get_port(&srv->addr), NULL); if (status != PJ_SUCCESS) { - destroy_server(srv); - destroy_client(client); - return -30; + destroy_server(srv); + destroy_client(client); + return -30; } /* Wait until on_status() callback is called with the failure */ pj_gettimeofday(&timeout); timeout.sec += 60; do { - handle_events(cfg, 100); - pj_gettimeofday(&t); + handle_events(cfg, 100); + pj_gettimeofday(&t); } while (client->on_status_cnt==0 && PJ_TIME_VAL_LT(t, timeout)); /* Check that callback with correct operation is called */ if (client->last_op != PJ_STUN_SOCK_BINDING_OP) { - PJ_LOG(3,(THIS_FILE, " error: expecting Binding operation status")); - ret = -40; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: expecting Binding operation status")); + ret = -40; + goto on_return; } /* .. and with the correct status */ if (client->last_status != PJNATH_ESTUNTIMEDOUT) { - PJ_LOG(3,(THIS_FILE, " error: expecting PJNATH_ESTUNTIMEDOUT")); - ret = -50; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: expecting PJNATH_ESTUNTIMEDOUT")); + ret = -50; + goto on_return; } /* Check that server received correct retransmissions */ if (srv->rx_cnt != PJ_STUN_MAX_TRANSMIT_COUNT) { - PJ_LOG(3,(THIS_FILE, " error: expecting %d retransmissions, got %d", - PJ_STUN_MAX_TRANSMIT_COUNT, srv->rx_cnt)); - ret = -60; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: expecting %d retransmissions, got %d", + PJ_STUN_MAX_TRANSMIT_COUNT, srv->rx_cnt)); + ret = -60; + goto on_return; } /* Check that client doesn't receive anything */ if (client->on_rx_data_cnt != 0) { - PJ_LOG(3,(THIS_FILE, " error: client shouldn't have received anything")); - ret = -70; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: client shouldn't have received anything")); + ret = -70; + goto on_return; } on_return: destroy_server(srv); destroy_client(client); for (i=0; i<7; ++i) - handle_events(cfg, 100); + handle_events(cfg, 100); if ((ret == 0) && use_ipv6) - ret = timeout_test(cfg, destroy_on_err, 0); + ret = timeout_test(cfg, destroy_on_err, 0); return ret; } @@ -384,7 +383,7 @@ static int timeout_test(pj_stun_config *cfg, pj_bool_t destroy_on_err, * XOR-MAPPED-ADDRESS attribute. */ static int missing_attr_test(pj_stun_config *cfg, pj_bool_t destroy_on_err, - pj_bool_t use_ipv6) + pj_bool_t use_ipv6) { struct stun_srv *srv; struct stun_client *client; @@ -394,62 +393,62 @@ static int missing_attr_test(pj_stun_config *cfg, pj_bool_t destroy_on_err, pj_status_t status; PJ_LOG(3,(THIS_FILE, " missing attribute test [%d] - (%s)", - destroy_on_err, (use_ipv6)?"IPv6":"IPv4")); + destroy_on_err, (use_ipv6)?"IPv6":"IPv4")); status = create_client(cfg, &client, destroy_on_err, use_ipv6); if (status != PJ_SUCCESS) - return -110; + return -110; status = create_server(client->pool, cfg->ioqueue, RESPOND_STUN, use_ipv6, - &srv); + &srv); if (status != PJ_SUCCESS) { - destroy_client(client); - return -120; + destroy_client(client); + return -120; } srv_addr = (use_ipv6)?pj_str("::1"):pj_str("127.0.0.1"); status = pj_stun_sock_start(client->sock, &srv_addr, - pj_sockaddr_get_port(&srv->addr), NULL); + pj_sockaddr_get_port(&srv->addr), NULL); if (status != PJ_SUCCESS) { - destroy_server(srv); - destroy_client(client); - return -130; + destroy_server(srv); + destroy_client(client); + return -130; } /* Wait until on_status() callback is called with the failure */ pj_gettimeofday(&timeout); timeout.sec += 60; do { - handle_events(cfg, 100); - pj_gettimeofday(&t); + handle_events(cfg, 100); + pj_gettimeofday(&t); } while (client->on_status_cnt==0 && PJ_TIME_VAL_LT(t, timeout)); /* Check that callback with correct operation is called */ if (client->last_op != PJ_STUN_SOCK_BINDING_OP) { - PJ_LOG(3,(THIS_FILE, " error: expecting Binding operation status")); - ret = -140; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: expecting Binding operation status")); + ret = -140; + goto on_return; } if (client->last_status != PJNATH_ESTUNNOMAPPEDADDR) { - PJ_LOG(3,(THIS_FILE, " error: expecting PJNATH_ESTUNNOMAPPEDADDR")); - ret = -150; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: expecting PJNATH_ESTUNNOMAPPEDADDR")); + ret = -150; + goto on_return; } /* Check that client doesn't receive anything */ if (client->on_rx_data_cnt != 0) { - PJ_LOG(3,(THIS_FILE, " error: client shouldn't have received anything")); - ret = -170; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: client shouldn't have received anything")); + ret = -170; + goto on_return; } on_return: destroy_server(srv); destroy_client(client); for (i=0; i<7; ++i) - handle_events(cfg, 100); + handle_events(cfg, 100); if ((ret == 0) && use_ipv6) - ret = missing_attr_test(cfg, destroy_on_err, 0); + ret = missing_attr_test(cfg, destroy_on_err, 0); return ret; } @@ -469,17 +468,17 @@ static int keep_alive_test(pj_stun_config *cfg, pj_bool_t use_ipv6) pj_status_t status; PJ_LOG(3,(THIS_FILE, " normal operation - (%s)", - (use_ipv6)?"IPv6":"IPv4")); + (use_ipv6)?"IPv6":"IPv4")); status = create_client(cfg, &client, PJ_TRUE, use_ipv6); if (status != PJ_SUCCESS) - return -310; + return -310; status = create_server(client->pool, cfg->ioqueue, RESPOND_STUN|WITH_XOR_MAPPED, - use_ipv6, &srv); + use_ipv6, &srv); if (status != PJ_SUCCESS) { - destroy_client(client); - return -320; + destroy_client(client); + return -320; } /* @@ -490,37 +489,37 @@ static int keep_alive_test(pj_stun_config *cfg, pj_bool_t use_ipv6) srv_addr = (use_ipv6)?pj_str("::1"):pj_str("127.0.0.1"); status = pj_stun_sock_start(client->sock, &srv_addr, - pj_sockaddr_get_port(&srv->addr), NULL); + pj_sockaddr_get_port(&srv->addr), NULL); if (status != PJ_SUCCESS) { - destroy_server(srv); - destroy_client(client); - return -330; + destroy_server(srv); + destroy_client(client); + return -330; } /* Wait until on_status() callback is called with success status */ pj_gettimeofday(&timeout); timeout.sec += 60; do { - handle_events(cfg, 100); - pj_gettimeofday(&t); + handle_events(cfg, 100); + pj_gettimeofday(&t); } while (client->on_status_cnt==0 && PJ_TIME_VAL_LT(t, timeout)); /* Check that callback with correct operation is called */ if (client->last_op != PJ_STUN_SOCK_BINDING_OP) { - PJ_LOG(3,(THIS_FILE, " error: expecting Binding operation status")); - ret = -340; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: expecting Binding operation status")); + ret = -340; + goto on_return; } if (client->last_status != PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, " error: expecting PJ_SUCCESS status")); - ret = -350; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: expecting PJ_SUCCESS status")); + ret = -350; + goto on_return; } /* Check that client doesn't receive anything */ if (client->on_rx_data_cnt != 0) { - PJ_LOG(3,(THIS_FILE, " error: client shouldn't have received anything")); - ret = -370; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: client shouldn't have received anything")); + ret = -370; + goto on_return; } /* Get info */ @@ -529,41 +528,41 @@ static int keep_alive_test(pj_stun_config *cfg, pj_bool_t use_ipv6) /* Check that we have server address */ if (!pj_sockaddr_has_addr(&info.srv_addr)) { - PJ_LOG(3,(THIS_FILE, " error: missing server address")); - ret = -380; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: missing server address")); + ret = -380; + goto on_return; } /* .. and bound address port must not be zero */ if (pj_sockaddr_get_port(&info.bound_addr)==0) { - PJ_LOG(3,(THIS_FILE, " error: bound address is zero")); - ret = -381; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: bound address is zero")); + ret = -381; + goto on_return; } /* .. and mapped address */ if (!pj_sockaddr_has_addr(&info.mapped_addr)) { - PJ_LOG(3,(THIS_FILE, " error: missing mapped address")); - ret = -382; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: missing mapped address")); + ret = -382; + goto on_return; } /* verify the mapped address */ pj_sockaddr_init(GET_AF(use_ipv6), &mapped_addr, - &srv->ip_to_send, srv->port_to_send); + &srv->ip_to_send, srv->port_to_send); if (pj_sockaddr_cmp(&info.mapped_addr, &mapped_addr) != 0) { - PJ_LOG(3,(THIS_FILE, " error: mapped address mismatched")); - ret = -383; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: mapped address mismatched")); + ret = -383; + goto on_return; } /* .. and at least one alias */ if (info.alias_cnt == 0) { - PJ_LOG(3,(THIS_FILE, " error: must have at least one alias")); - ret = -384; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: must have at least one alias")); + ret = -384; + goto on_return; } if (!pj_sockaddr_has_addr(&info.aliases[0])) { - PJ_LOG(3,(THIS_FILE, " error: missing alias")); - ret = -386; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: missing alias")); + ret = -386; + goto on_return; } @@ -580,16 +579,16 @@ static int keep_alive_test(pj_stun_config *cfg, pj_bool_t use_ipv6) /* Client sending data to echo server */ { - char txt[100]; - PJ_LOG(3,(THIS_FILE, " sending to %s", pj_sockaddr_print(&info.srv_addr, txt, sizeof(txt), 3))); + char txt[100]; + PJ_LOG(3,(THIS_FILE, " sending to %s", pj_sockaddr_print(&info.srv_addr, txt, sizeof(txt), 3))); } status = pj_stun_sock_sendto(client->sock, NULL, &ret, sizeof(ret), - 0, &info.srv_addr, - pj_sockaddr_get_len(&info.srv_addr)); + 0, &info.srv_addr, + pj_sockaddr_get_len(&info.srv_addr)); if (status != PJ_SUCCESS && status != PJ_EPENDING) { - app_perror(" error: server sending data", status); - ret = -390; - goto on_return; + app_perror(" error: server sending data", status); + ret = -390; + goto on_return; } /* Wait for a short period until client receives data. We can't wait for @@ -598,28 +597,28 @@ static int keep_alive_test(pj_stun_config *cfg, pj_bool_t use_ipv6) pj_gettimeofday(&timeout); timeout.sec += 1; do { - handle_events(cfg, 100); - pj_gettimeofday(&t); + handle_events(cfg, 100); + pj_gettimeofday(&t); } while (client->on_rx_data_cnt==0 && PJ_TIME_VAL_LT(t, timeout)); /* Check that data is received in server */ if (srv->rx_cnt == 0) { - PJ_LOG(3,(THIS_FILE, " error: server didn't receive data")); - ret = -395; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: server didn't receive data")); + ret = -395; + goto on_return; } /* Check that status is still OK */ if (client->last_status != PJ_SUCCESS) { - app_perror(" error: client has failed", client->last_status); - ret = -400; - goto on_return; + app_perror(" error: client has failed", client->last_status); + ret = -400; + goto on_return; } /* Check that data has been received */ if (client->on_rx_data_cnt == 0) { - PJ_LOG(3,(THIS_FILE, " error: client doesn't receive data")); - ret = -410; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: client doesn't receive data")); + ret = -410; + goto on_return; } /* @@ -644,15 +643,15 @@ static int keep_alive_test(pj_stun_config *cfg, pj_bool_t use_ipv6) pj_gettimeofday(&timeout); timeout.sec += (PJ_STUN_KEEP_ALIVE_SEC + 1); do { - handle_events(cfg, 100); - pj_gettimeofday(&t); + handle_events(cfg, 100); + pj_gettimeofday(&t); } while (PJ_TIME_VAL_LT(t, timeout)); /* Check that server receives some packets */ if (srv->rx_cnt == 0) { - PJ_LOG(3, (THIS_FILE, " error: no keep-alive was received")); - ret = -420; - goto on_return; + PJ_LOG(3, (THIS_FILE, " error: no keep-alive was received")); + ret = -420; + goto on_return; } /* Check that client status is still okay and on_status() callback is NOT * called @@ -661,17 +660,17 @@ static int keep_alive_test(pj_stun_config *cfg, pj_bool_t use_ipv6) * https://github.com/pjsip/pjproject/issues/742 if (client->on_status_cnt != 0) { - PJ_LOG(3, (THIS_FILE, " error: on_status() must not be called on successful" - "keep-alive when mapped-address does not change")); - ret = -430; - goto on_return; + PJ_LOG(3, (THIS_FILE, " error: on_status() must not be called on successful" + "keep-alive when mapped-address does not change")); + ret = -430; + goto on_return; } */ /* Check that client doesn't receive anything */ if (client->on_rx_data_cnt != 0) { - PJ_LOG(3,(THIS_FILE, " error: client shouldn't have received anything")); - ret = -440; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: client shouldn't have received anything")); + ret = -440; + goto on_return; } @@ -701,41 +700,41 @@ static int keep_alive_test(pj_stun_config *cfg, pj_bool_t use_ipv6) pj_gettimeofday(&timeout); timeout.sec += (PJ_STUN_KEEP_ALIVE_SEC + 1); do { - handle_events(cfg, 100); - pj_gettimeofday(&t); + handle_events(cfg, 100); + pj_gettimeofday(&t); } while (PJ_TIME_VAL_LT(t, timeout)); /* Check that server receives some packets */ if (srv->rx_cnt == 0) { - PJ_LOG(3, (THIS_FILE, " error: no keep-alive was received")); - ret = -450; - goto on_return; + PJ_LOG(3, (THIS_FILE, " error: no keep-alive was received")); + ret = -450; + goto on_return; } /* Check that on_status() callback is called (because mapped address * has changed) */ if (client->on_status_cnt != 1) { - PJ_LOG(3, (THIS_FILE, " error: on_status() was not called")); - ret = -460; - goto on_return; + PJ_LOG(3, (THIS_FILE, " error: on_status() was not called")); + ret = -460; + goto on_return; } /* Check that callback was called with correct operation */ if (client->last_op != PJ_STUN_SOCK_MAPPED_ADDR_CHANGE) { - PJ_LOG(3,(THIS_FILE, " error: expecting keep-alive operation status")); - ret = -470; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: expecting keep-alive operation status")); + ret = -470; + goto on_return; } /* Check that last status is still success */ if (client->last_status != PJ_SUCCESS) { - PJ_LOG(3, (THIS_FILE, " error: expecting successful status")); - ret = -480; - goto on_return; + PJ_LOG(3, (THIS_FILE, " error: expecting successful status")); + ret = -480; + goto on_return; } /* Check that client doesn't receive anything */ if (client->on_rx_data_cnt != 0) { - PJ_LOG(3,(THIS_FILE, " error: client shouldn't have received anything")); - ret = -490; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: client shouldn't have received anything")); + ret = -490; + goto on_return; } /* Get info */ @@ -744,35 +743,35 @@ static int keep_alive_test(pj_stun_config *cfg, pj_bool_t use_ipv6) /* Check that we have server address */ if (!pj_sockaddr_has_addr(&info.srv_addr)) { - PJ_LOG(3,(THIS_FILE, " error: missing server address")); - ret = -500; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: missing server address")); + ret = -500; + goto on_return; } /* .. and mapped address */ if (!pj_sockaddr_has_addr(&info.mapped_addr)) { - PJ_LOG(3,(THIS_FILE, " error: missing mapped address")); - ret = -510; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: missing mapped address")); + ret = -510; + goto on_return; } /* verify the mapped address */ pj_sockaddr_init(GET_AF(use_ipv6), &mapped_addr, - &srv->ip_to_send, srv->port_to_send); + &srv->ip_to_send, srv->port_to_send); if (pj_sockaddr_cmp(&info.mapped_addr, &mapped_addr) != 0) { - PJ_LOG(3,(THIS_FILE, " error: mapped address mismatched")); - ret = -520; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: mapped address mismatched")); + ret = -520; + goto on_return; } /* .. and at least one alias */ if (info.alias_cnt == 0) { - PJ_LOG(3,(THIS_FILE, " error: must have at least one alias")); - ret = -530; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: must have at least one alias")); + ret = -530; + goto on_return; } if (!pj_sockaddr_has_addr(&info.aliases[0])) { - PJ_LOG(3,(THIS_FILE, " error: missing alias")); - ret = -540; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: missing alias")); + ret = -540; + goto on_return; } @@ -796,26 +795,26 @@ static int keep_alive_test(pj_stun_config *cfg, pj_bool_t use_ipv6) pj_gettimeofday(&timeout); timeout.sec += (PJ_STUN_KEEP_ALIVE_SEC + PJ_STUN_TIMEOUT_VALUE + 5); do { - handle_events(cfg, 100); - pj_gettimeofday(&t); + handle_events(cfg, 100); + pj_gettimeofday(&t); } while (client->on_status_cnt==0 && PJ_TIME_VAL_LT(t, timeout)); /* Check that callback with correct operation is called */ if (client->last_op != PJ_STUN_SOCK_KEEP_ALIVE_OP) { - PJ_LOG(3,(THIS_FILE, " error: expecting keep-alive operation status")); - ret = -600; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: expecting keep-alive operation status")); + ret = -600; + goto on_return; } if (client->last_status == PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, " error: expecting failed keep-alive")); - ret = -610; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: expecting failed keep-alive")); + ret = -610; + goto on_return; } /* Check that client doesn't receive anything */ if (client->on_rx_data_cnt != 0) { - PJ_LOG(3,(THIS_FILE, " error: client shouldn't have received anything")); - ret = -620; - goto on_return; + PJ_LOG(3,(THIS_FILE, " error: client shouldn't have received anything")); + ret = -620; + goto on_return; } @@ -823,21 +822,21 @@ static int keep_alive_test(pj_stun_config *cfg, pj_bool_t use_ipv6) destroy_server(srv); destroy_client(client); for (i=0; i<7; ++i) - handle_events(cfg, 100); + handle_events(cfg, 100); if ((ret == 0) && use_ipv6) - ret = keep_alive_test(cfg, 0); + ret = keep_alive_test(cfg, 0); return ret; } -#define DO_TEST(expr) \ - capture_pjlib_state(&stun_cfg, &pjlib_state); \ - ret = expr; \ - if (ret != 0) goto on_return; \ - ret = check_pjlib_state(&stun_cfg, &pjlib_state); \ - if (ret != 0) goto on_return; +#define DO_TEST(expr) \ + capture_pjlib_state(&stun_cfg, &pjlib_state); \ + ret = expr; \ + if (ret != 0) goto on_return; \ + ret = check_pjlib_state(&stun_cfg, &pjlib_state); \ + if (ret != 0) goto on_return; int stun_sock_test(void) @@ -854,16 +853,16 @@ int stun_sock_test(void) status = pj_ioqueue_create(pool, 12, &ioqueue); if (status != PJ_SUCCESS) { - app_perror(" pj_ioqueue_create()", status); - ret = -4; - goto on_return; + app_perror(" pj_ioqueue_create()", status); + ret = -4; + goto on_return; } status = pj_timer_heap_create(pool, 100, &timer_heap); if (status != PJ_SUCCESS) { - app_perror(" pj_timer_heap_create()", status); - ret = -8; - goto on_return; + app_perror(" pj_timer_heap_create()", status); + ret = -8; + goto on_return; } pj_stun_config_init(&stun_cfg, mem, 0, ioqueue, timer_heap); diff --git a/pjnath/src/pjnath-test/test.c b/pjnath/src/pjnath-test/test.c index 22f6978af8..8626ac80d9 100644 --- a/pjnath/src/pjnath-test/test.c +++ b/pjnath/src/pjnath-test/test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -22,7 +21,7 @@ #include void app_perror_dbg(const char *msg, pj_status_t rc, - const char *file, int line) + const char *file, int line) { char errbuf[256]; @@ -30,7 +29,7 @@ void app_perror_dbg(const char *msg, pj_status_t rc, pj_strerror(rc, errbuf, sizeof(errbuf)); PJ_LOG(1,("test", "%s:%d: %s: [pj_status_t=%d] %s", file, line, msg, - rc, errbuf)); + rc, errbuf)); } /* Set socket to nonblocking. */ @@ -56,15 +55,15 @@ pj_status_t create_stun_config(pj_pool_t *pool, pj_stun_config *stun_cfg) status = pj_ioqueue_create(pool, 64, &ioqueue); if (status != PJ_SUCCESS) { - app_perror(" pj_ioqueue_create()", status); - return status; + app_perror(" pj_ioqueue_create()", status); + return status; } status = pj_timer_heap_create(pool, 256, &timer_heap); if (status != PJ_SUCCESS) { - app_perror(" pj_timer_heap_create()", status); - pj_ioqueue_destroy(ioqueue); - return status; + app_perror(" pj_timer_heap_create()", status); + pj_ioqueue_destroy(ioqueue); + return status; } pj_lock_create_recursive_mutex(pool, NULL, &lock); @@ -78,17 +77,17 @@ pj_status_t create_stun_config(pj_pool_t *pool, pj_stun_config *stun_cfg) void destroy_stun_config(pj_stun_config *stun_cfg) { if (stun_cfg->timer_heap) { - pj_timer_heap_destroy(stun_cfg->timer_heap); - stun_cfg->timer_heap = NULL; + pj_timer_heap_destroy(stun_cfg->timer_heap); + stun_cfg->timer_heap = NULL; } if (stun_cfg->ioqueue) { - pj_ioqueue_destroy(stun_cfg->ioqueue); - stun_cfg->ioqueue = NULL; + pj_ioqueue_destroy(stun_cfg->ioqueue); + stun_cfg->ioqueue = NULL; } } void poll_events(pj_stun_config *stun_cfg, unsigned msec, - pj_bool_t first_event_only) + pj_bool_t first_event_only) { pj_time_val stop_time; int count = 0; @@ -99,24 +98,24 @@ void poll_events(pj_stun_config *stun_cfg, unsigned msec, /* Process all events for the specified duration. */ for (;;) { - pj_time_val timeout = {0, 1}, now; - int c; + pj_time_val timeout = {0, 1}, now; + int c; - c = pj_timer_heap_poll( stun_cfg->timer_heap, NULL ); - if (c > 0) - count += c; + c = pj_timer_heap_poll( stun_cfg->timer_heap, NULL ); + if (c > 0) + count += c; - //timeout.sec = timeout.msec = 0; - c = pj_ioqueue_poll( stun_cfg->ioqueue, &timeout); - if (c > 0) - count += c; + //timeout.sec = timeout.msec = 0; + c = pj_ioqueue_poll( stun_cfg->ioqueue, &timeout); + if (c > 0) + count += c; - pj_gettimeofday(&now); - if (PJ_TIME_VAL_GTE(now, stop_time)) - break; + pj_gettimeofday(&now); + if (PJ_TIME_VAL_GTE(now, stop_time)) + break; - if (first_event_only && count >= 0) - break; + if (first_event_only && count >= 0) + break; } } @@ -131,7 +130,7 @@ void capture_pjlib_state(pj_stun_config *cfg, struct pjlib_state *st) } int check_pjlib_state(pj_stun_config *cfg, - const struct pjlib_state *initial_st) + const struct pjlib_state *initial_st) { struct pjlib_state current_state; int rc = 0; @@ -139,39 +138,39 @@ int check_pjlib_state(pj_stun_config *cfg, capture_pjlib_state(cfg, ¤t_state); if (current_state.timer_cnt > initial_st->timer_cnt) { - PJ_LOG(3,("", " error: possibly leaking timer")); - rc |= ERR_TIMER_LEAK; + PJ_LOG(3,("", " error: possibly leaking timer")); + rc |= ERR_TIMER_LEAK; #if PJ_TIMER_DEBUG - pj_timer_heap_dump(cfg->timer_heap); + pj_timer_heap_dump(cfg->timer_heap); #endif } if (current_state.pool_used_cnt > initial_st->pool_used_cnt) { - PJ_LOG(3,("", " error: possibly leaking memory")); - PJ_LOG(3,("", " dumping memory pool:")); - pj_pool_factory_dump(mem, PJ_TRUE); - rc |= ERR_MEMORY_LEAK; + PJ_LOG(3,("", " error: possibly leaking memory")); + PJ_LOG(3,("", " dumping memory pool:")); + pj_pool_factory_dump(mem, PJ_TRUE); + rc |= ERR_MEMORY_LEAK; } return rc; } -#define DO_TEST(test) do { \ - PJ_LOG(3, ("test", "Running %s...", #test)); \ - rc = test; \ - PJ_LOG(3, ("test", \ - "%s(%d)", \ - (char*)(rc ? "..ERROR" : "..success"), rc)); \ - if (rc!=0) goto on_return; \ - } while (0) +#define DO_TEST(test) do { \ + PJ_LOG(3, ("test", "Running %s...", #test)); \ + rc = test; \ + PJ_LOG(3, ("test", \ + "%s(%d)", \ + (char*)(rc ? "..ERROR" : "..success"), rc)); \ + if (rc!=0) goto on_return; \ + } while (0) pj_pool_factory *mem; int param_log_decor = PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_TIME | PJ_LOG_HAS_SENDER | - PJ_LOG_HAS_MICRO_SEC; + PJ_LOG_HAS_MICRO_SEC; pj_log_func *orig_log_func; FILE *log_file; @@ -179,10 +178,10 @@ FILE *log_file; static void test_log_func(int level, const char *data, int len) { if (log_file) { - fwrite(data, len, 1, log_file); + fwrite(data, len, 1, log_file); } if (level <= 3) - orig_log_func(level, data, len); + orig_log_func(level, data, len); } static int test_inner(void) @@ -205,8 +204,8 @@ static int test_inner(void) rc = pj_init(); if (rc != 0) { - app_perror("pj_init() error!!", rc); - goto on_return; + app_perror("pj_init() error!!", rc); + goto on_return; } pj_dump_config(); @@ -242,7 +241,7 @@ static int test_inner(void) on_return: if (log_file) - fclose(log_file); + fclose(log_file); return rc; } diff --git a/pjnath/src/pjnath-test/test.h b/pjnath/src/pjnath-test/test.h index 9b37e6715a..76bb9a0f7d 100644 --- a/pjnath/src/pjnath-test/test.h +++ b/pjnath/src/pjnath-test/test.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -22,30 +21,30 @@ #include #if defined(PJ_EXCLUDE_BENCHMARK_TESTS) && (PJ_EXCLUDE_BENCHMARK_TESTS==1) -# define WITH_BENCHMARK 0 +# define WITH_BENCHMARK 0 #else -# define WITH_BENCHMARK 1 +# define WITH_BENCHMARK 1 #endif -#define INCLUDE_STUN_TEST 1 -#define INCLUDE_ICE_TEST 1 +#define INCLUDE_STUN_TEST 1 +#define INCLUDE_ICE_TEST 1 #define INCLUDE_TRICKLE_ICE_TEST 1 -#define INCLUDE_STUN_SOCK_TEST 1 -#define INCLUDE_TURN_SOCK_TEST 1 -#define INCLUDE_CONCUR_TEST 1 +#define INCLUDE_STUN_SOCK_TEST 1 +#define INCLUDE_TURN_SOCK_TEST 1 +#define INCLUDE_CONCUR_TEST 1 #define GET_AF(use_ipv6) (use_ipv6?pj_AF_INET6():pj_AF_INET()) #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6 -# define USE_IPV6 1 +# define USE_IPV6 1 #else -# define USE_IPV6 0 +# define USE_IPV6 0 #endif #if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK -# define USE_TLS 1 +# define USE_TLS 1 #else -# define USE_TLS 0 +# define USE_TLS 0 #endif int stun_test(void); @@ -59,7 +58,7 @@ int test_main(void); #define app_perror(msg, rc) app_perror_dbg(msg, rc, __FILE__, __LINE__) extern void app_perror_dbg(const char *msg, pj_status_t rc, - const char *file, int line); + const char *file, int line); extern void app_set_sock_nb(pj_sock_t sock); extern pj_pool_factory *mem; @@ -73,21 +72,21 @@ pj_status_t create_stun_config(pj_pool_t *pool, pj_stun_config *stun_cfg); void destroy_stun_config(pj_stun_config *stun_cfg); void poll_events(pj_stun_config *stun_cfg, unsigned msec, - pj_bool_t first_event_only); + pj_bool_t first_event_only); typedef struct pjlib_state { - unsigned timer_cnt; /* Number of timer entries */ - unsigned pool_used_cnt; /* Number of app pools */ + unsigned timer_cnt; /* Number of timer entries */ + unsigned pool_used_cnt; /* Number of app pools */ } pjlib_state; void capture_pjlib_state(pj_stun_config *cfg, struct pjlib_state *st); int check_pjlib_state(pj_stun_config *cfg, - const struct pjlib_state *initial_st); + const struct pjlib_state *initial_st); pj_turn_tp_type get_turn_tp_type(pj_uint32_t flag); -#define ERR_MEMORY_LEAK 1 -#define ERR_TIMER_LEAK 2 +#define ERR_MEMORY_LEAK 1 +#define ERR_TIMER_LEAK 2 diff --git a/pjnath/src/pjnath-test/turn_sock_test.c b/pjnath/src/pjnath-test/turn_sock_test.c index eac6fd881d..283f3749f2 100644 --- a/pjnath/src/pjnath-test/turn_sock_test.c +++ b/pjnath/src/pjnath-test/turn_sock_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -20,8 +19,8 @@ #include "test.h" #include "server.h" -#define SRV_DOMAIN "pjsip.lab.domain" -#define KA_INTERVAL 50 +#define SRV_DOMAIN "pjsip.lab.domain" +#define KA_INTERVAL 50 struct test_result { @@ -31,77 +30,77 @@ struct test_result struct test_session { - pj_pool_t *pool; - pj_stun_config *stun_cfg; - pj_turn_sock *turn_sock; - pj_dns_resolver *resolver; - test_server *test_srv; - - pj_bool_t destroy_called; - int destroy_on_state; - struct test_result result; + pj_pool_t *pool; + pj_stun_config *stun_cfg; + pj_turn_sock *turn_sock; + pj_dns_resolver *resolver; + test_server *test_srv; + + pj_bool_t destroy_called; + int destroy_on_state; + struct test_result result; }; struct test_session_cfg { struct { - pj_bool_t enable_dns_srv; - int destroy_on_state; + pj_bool_t enable_dns_srv; + int destroy_on_state; } client; struct { - pj_uint32_t flags; - pj_bool_t respond_allocate; - pj_bool_t respond_refresh; + pj_uint32_t flags; + pj_bool_t respond_allocate; + pj_bool_t respond_refresh; } srv; }; static void turn_on_rx_data(pj_turn_sock *turn_sock, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); static void turn_on_state(pj_turn_sock *turn_sock, - pj_turn_state_t old_state, - pj_turn_state_t new_state); + pj_turn_state_t old_state, + pj_turn_state_t new_state); static void destroy_session(struct test_session *sess) { if (sess->resolver) { - pj_dns_resolver_destroy(sess->resolver, PJ_TRUE); - sess->resolver = NULL; + pj_dns_resolver_destroy(sess->resolver, PJ_TRUE); + sess->resolver = NULL; } if (sess->turn_sock) { - if (!sess->destroy_called) { - sess->destroy_called = PJ_TRUE; - pj_turn_sock_destroy(sess->turn_sock); - } - sess->turn_sock = NULL; + if (!sess->destroy_called) { + sess->destroy_called = PJ_TRUE; + pj_turn_sock_destroy(sess->turn_sock); + } + sess->turn_sock = NULL; } if (sess->test_srv) { - destroy_test_server(sess->test_srv); - sess->test_srv = NULL; + destroy_test_server(sess->test_srv); + sess->test_srv = NULL; } if (sess->pool) { - pj_pool_release(sess->pool); + pj_pool_release(sess->pool); } } pj_turn_tp_type get_turn_tp_type(pj_uint32_t flag) { if (flag & TURN_TCP) { - return PJ_TURN_TP_TCP; + return PJ_TURN_TP_TCP; } else if (flag & TURN_TLS) { - return PJ_TURN_TP_TLS; + return PJ_TURN_TP_TLS; } return PJ_TURN_TP_UDP; } static int create_test_session(pj_stun_config *stun_cfg, - const struct test_session_cfg *cfg, - struct test_session **p_sess) + const struct test_session_cfg *cfg, + struct test_session **p_sess) { struct test_session *sess; pj_pool_t *pool; @@ -123,23 +122,23 @@ static int create_test_session(pj_stun_config *stun_cfg, turn_sock_cb.on_rx_data = &turn_on_rx_data; turn_sock_cb.on_state = &turn_on_state; status = pj_turn_sock_create(sess->stun_cfg, - GET_AF(use_ipv6), - tp_type, - &turn_sock_cb, - 0, - sess, - &sess->turn_sock); + GET_AF(use_ipv6), + tp_type, + &turn_sock_cb, + 0, + sess, + &sess->turn_sock); if (status != PJ_SUCCESS) { - destroy_session(sess); - return -20; + destroy_session(sess); + return -20; } /* Create test server */ status = create_test_server(sess->stun_cfg, cfg->srv.flags, SRV_DOMAIN, - &sess->test_srv); + &sess->test_srv); if (status != PJ_SUCCESS) { - destroy_session(sess); - return -30; + destroy_session(sess); + return -30; } sess->test_srv->turn_respond_allocate = cfg->srv.respond_allocate; @@ -147,20 +146,20 @@ static int create_test_session(pj_stun_config *stun_cfg, /* Create client resolver */ status = pj_dns_resolver_create(mem, "resolver", 0, sess->stun_cfg->timer_heap, - sess->stun_cfg->ioqueue, &sess->resolver); + sess->stun_cfg->ioqueue, &sess->resolver); if (status != PJ_SUCCESS) { - destroy_session(sess); - return -40; + destroy_session(sess); + return -40; } else { - pj_str_t dns_srv = use_ipv6?pj_str("::1") : pj_str("127.0.0.1"); - pj_uint16_t dns_srv_port = (pj_uint16_t) DNS_SERVER_PORT; - status = pj_dns_resolver_set_ns(sess->resolver, 1, &dns_srv, &dns_srv_port); - - if (status != PJ_SUCCESS) { - destroy_session(sess); - return -50; - } + pj_str_t dns_srv = use_ipv6?pj_str("::1") : pj_str("127.0.0.1"); + pj_uint16_t dns_srv_port = (pj_uint16_t) DNS_SERVER_PORT; + status = pj_dns_resolver_set_ns(sess->resolver, 1, &dns_srv, &dns_srv_port); + + if (status != PJ_SUCCESS) { + destroy_session(sess); + return -50; + } } /* Init TURN credential */ @@ -177,24 +176,24 @@ static int create_test_session(pj_stun_config *stun_cfg, /* Start the client */ if (cfg->client.enable_dns_srv) { - /* Use DNS SRV to resolve server, may fallback to DNS A */ - pj_str_t domain = pj_str(SRV_DOMAIN); - status = pj_turn_sock_alloc(sess->turn_sock, &domain, TURN_SERVER_PORT, - sess->resolver, &cred, &alloc_param); + /* Use DNS SRV to resolve server, may fallback to DNS A */ + pj_str_t domain = pj_str(SRV_DOMAIN); + status = pj_turn_sock_alloc(sess->turn_sock, &domain, TURN_SERVER_PORT, + sess->resolver, &cred, &alloc_param); } else { - /* Explicitly specify server address */ - pj_str_t host = use_ipv6?pj_str("::1") : pj_str("127.0.0.1"); - status = pj_turn_sock_alloc(sess->turn_sock, &host, TURN_SERVER_PORT, - NULL, &cred, &alloc_param); + /* Explicitly specify server address */ + pj_str_t host = use_ipv6?pj_str("::1") : pj_str("127.0.0.1"); + status = pj_turn_sock_alloc(sess->turn_sock, &host, TURN_SERVER_PORT, + NULL, &cred, &alloc_param); } if (status != PJ_SUCCESS) { - if (cfg->client.destroy_on_state >= PJ_TURN_STATE_READY) { - destroy_session(sess); - return -70; - } + if (cfg->client.destroy_on_state >= PJ_TURN_STATE_READY) { + destroy_session(sess); + return -70; + } } *p_sess = sess; @@ -203,10 +202,10 @@ static int create_test_session(pj_stun_config *stun_cfg, static void turn_on_rx_data(pj_turn_sock *turn_sock, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *peer_addr, - unsigned addr_len) + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *peer_addr, + unsigned addr_len) { struct test_session *sess; @@ -217,15 +216,15 @@ static void turn_on_rx_data(pj_turn_sock *turn_sock, sess = (struct test_session*) pj_turn_sock_get_user_data(turn_sock); if (sess == NULL) - return; + return; sess->result.rx_data_cnt++; } static void turn_on_state(pj_turn_sock *turn_sock, - pj_turn_state_t old_state, - pj_turn_state_t new_state) + pj_turn_state_t old_state, + pj_turn_state_t new_state) { struct test_session *sess; unsigned i, mask; @@ -234,7 +233,7 @@ static void turn_on_state(pj_turn_sock *turn_sock, sess = (struct test_session*) pj_turn_sock_get_user_data(turn_sock); if (sess == NULL) - return; + return; /* This state must not be called before */ pj_assert((sess->result.state_called & (1<result.state_called |= (1 << new_state); if (new_state >= sess->destroy_on_state && !sess->destroy_called) { - sess->destroy_called = PJ_TRUE; - pj_turn_sock_destroy(turn_sock); + sess->destroy_called = PJ_TRUE; + pj_turn_sock_destroy(turn_sock); } if (new_state >= PJ_TURN_STATE_DESTROYING) { - pj_turn_sock_set_user_data(sess->turn_sock, NULL); - sess->turn_sock = NULL; + pj_turn_sock_set_user_data(sess->turn_sock, NULL); + sess->turn_sock = NULL; } } @@ -265,158 +264,158 @@ static void turn_on_state(pj_turn_sock *turn_sock, ///////////////////////////////////////////////////////////////////// static void set_server_flag(struct test_session_cfg *test_cfg, - pj_bool_t use_ipv6, - pj_turn_tp_type tp_type) + pj_bool_t use_ipv6, + pj_turn_tp_type tp_type) { pj_uint32_t flag = TURN_UDP; test_cfg->srv.flags &= ~(SERVER_IPV4+SERVER_IPV6+ - TURN_UDP+TURN_TCP+TURN_TLS); + TURN_UDP+TURN_TCP+TURN_TLS); switch (tp_type) { - case PJ_TURN_TP_TCP: - flag = TURN_TCP; - break; - case PJ_TURN_TP_TLS: - flag = TURN_TLS; - break; - default: - break; + case PJ_TURN_TP_TCP: + flag = TURN_TCP; + break; + case PJ_TURN_TP_TLS: + flag = TURN_TLS; + break; + default: + break; } test_cfg->srv.flags |= ((use_ipv6)?SERVER_IPV6:SERVER_IPV4)+flag; } static int state_progression_test(pj_stun_config *stun_cfg, - pj_bool_t use_ipv6, - pj_turn_tp_type tp_type) + pj_bool_t use_ipv6, + pj_turn_tp_type tp_type) { struct test_session_cfg test_cfg = { - { /* Client cfg */ - PJ_TRUE, /* DNS SRV */ - 0xFFFF /* Destroy on state */ - }, - { /* Server cfg */ - 0xFFFFFFFF, /* flags */ - PJ_TRUE, /* respond to allocate */ - PJ_TRUE /* respond to refresh */ - } + { /* Client cfg */ + PJ_TRUE, /* DNS SRV */ + 0xFFFF /* Destroy on state */ + }, + { /* Server cfg */ + 0xFFFFFFFF, /* flags */ + PJ_TRUE, /* respond to allocate */ + PJ_TRUE /* respond to refresh */ + } }; struct test_session *sess; unsigned i; int rc = 0; PJ_LOG(3,("", " state progression tests - (%s) (%s)", - use_ipv6?"IPv6":"IPv4", - (tp_type==PJ_TURN_TP_UDP)?"UDP": - (tp_type==PJ_TURN_TP_TCP)?"TCP":"TLS")); + use_ipv6?"IPv6":"IPv4", + (tp_type==PJ_TURN_TP_UDP)?"UDP": + (tp_type==PJ_TURN_TP_TCP)?"TCP":"TLS")); set_server_flag(&test_cfg, use_ipv6, tp_type); for (i=0; i<=1; ++i) { - enum { TIMEOUT = 60 }; - pjlib_state pjlib_state; - pj_turn_session_info info; - struct test_result result; - pj_time_val tstart; - - PJ_LOG(3,("", " %s DNS SRV resolution", - (i==0? "without" : "with"))); - - capture_pjlib_state(stun_cfg, &pjlib_state); - - test_cfg.client.enable_dns_srv = i; - - rc = create_test_session(stun_cfg, &test_cfg, &sess); - if (rc != 0) - return rc; - - pj_bzero(&info, sizeof(info)); - - /* Wait until state is READY */ - pj_gettimeofday(&tstart); - while (sess->turn_sock) { - pj_time_val now; - - poll_events(stun_cfg, 10, PJ_FALSE); - if (sess->turn_sock == NULL) { - break; - } - rc = pj_turn_sock_get_info(sess->turn_sock, &info); - if (rc!=PJ_SUCCESS) - break; - - if (info.state >= PJ_TURN_STATE_READY) - break; - - pj_gettimeofday(&now); - if (now.sec - tstart.sec > TIMEOUT) { - PJ_LOG(3,("", " timed-out")); - break; - } - } - - if (info.state != PJ_TURN_STATE_READY) { - PJ_LOG(3,("", " error: state is not READY")); - destroy_session(sess); - return -130; - } - - /* Deallocate */ - pj_turn_sock_destroy(sess->turn_sock); - - /* Wait for couple of seconds. - * We can't poll the session info since the session may have - * been destroyed - */ - poll_events(stun_cfg, 2000, PJ_FALSE); - sess->turn_sock = NULL; - pj_memcpy(&result, &sess->result, sizeof(result)); - destroy_session(sess); - - /* Check the result */ - if ((result.state_called & (1<turn_sock) { + pj_time_val now; + + poll_events(stun_cfg, 10, PJ_FALSE); + if (sess->turn_sock == NULL) { + break; + } + rc = pj_turn_sock_get_info(sess->turn_sock, &info); + if (rc!=PJ_SUCCESS) + break; + + if (info.state >= PJ_TURN_STATE_READY) + break; + + pj_gettimeofday(&now); + if (now.sec - tstart.sec > TIMEOUT) { + PJ_LOG(3,("", " timed-out")); + break; + } + } + + if (info.state != PJ_TURN_STATE_READY) { + PJ_LOG(3,("", " error: state is not READY")); + destroy_session(sess); + return -130; + } + + /* Deallocate */ + pj_turn_sock_destroy(sess->turn_sock); + + /* Wait for couple of seconds. + * We can't poll the session info since the session may have + * been destroyed + */ + poll_events(stun_cfg, 2000, PJ_FALSE); + sess->turn_sock = NULL; + pj_memcpy(&result, &sess->result, sizeof(result)); + destroy_session(sess); + + /* Check the result */ + if ((result.state_called & (1<turn_sock) { - pj_time_val now; - - poll_events(stun_cfg, 100, PJ_FALSE); - - pj_gettimeofday(&now); - if (now.sec - tstart.sec > TIMEOUT) { - rc = -7; - break; - } - } - - } else { - pj_gettimeofday(&tstart); - rc = 0; - while (sess->turn_sock) { - pj_time_val now; - - poll_events(stun_cfg, 1, PJ_FALSE); - - pj_turn_sock_get_info(sess->turn_sock, &info); - - if (info.state >= target_state) { - pj_turn_sock_destroy(sess->turn_sock); - break; - } - - pj_gettimeofday(&now); - if (now.sec - tstart.sec > TIMEOUT) { - rc = -8; - break; - } - } - } - - - if (rc != 0) { - PJ_LOG(3,("", " error: timeout")); - return rc; - } - - poll_events(stun_cfg, 1000, PJ_FALSE); - destroy_session(sess); - - rc = check_pjlib_state(stun_cfg, &pjlib_state); - if (rc != 0) { - PJ_LOG(3,("", " error: memory/timer-heap leak detected")); - return rc; - } + enum { TIMEOUT = 60 }; + pjlib_state pjlib_state; + pj_turn_session_info info; + pj_time_val tstart; + + capture_pjlib_state(stun_cfg, &pjlib_state); + + PJ_LOG(3,("", " %s", pj_turn_state_name((pj_turn_state_t)target_state))); + + if (in_callback) + test_cfg.client.destroy_on_state = target_state; + + rc = create_test_session(stun_cfg, &test_cfg, &sess); + if (rc != 0) + return rc; + + if (in_callback) { + pj_gettimeofday(&tstart); + rc = 0; + while (sess->turn_sock) { + pj_time_val now; + + poll_events(stun_cfg, 100, PJ_FALSE); + + pj_gettimeofday(&now); + if (now.sec - tstart.sec > TIMEOUT) { + rc = -7; + break; + } + } + + } else { + pj_gettimeofday(&tstart); + rc = 0; + while (sess->turn_sock) { + pj_time_val now; + + poll_events(stun_cfg, 1, PJ_FALSE); + + pj_turn_sock_get_info(sess->turn_sock, &info); + + if (info.state >= target_state) { + pj_turn_sock_destroy(sess->turn_sock); + break; + } + + pj_gettimeofday(&now); + if (now.sec - tstart.sec > TIMEOUT) { + rc = -8; + break; + } + } + } + + + if (rc != 0) { + PJ_LOG(3,("", " error: timeout")); + return rc; + } + + poll_events(stun_cfg, 1000, PJ_FALSE); + destroy_session(sess); + + rc = check_pjlib_state(stun_cfg, &pjlib_state); + if (rc != 0) { + PJ_LOG(3,("", " error: memory/timer-heap leak detected")); + return rc; + } } return 0; @@ -541,36 +540,36 @@ int turn_sock_test(void) pool = pj_pool_create(mem, "turntest", 512, 512, NULL); rc = create_stun_config(pool, &stun_cfg); if (rc != PJ_SUCCESS) { - pj_pool_release(pool); - return -2; + pj_pool_release(pool); + return -2; } for (n = 0; n <= 2; ++n) { - pj_turn_tp_type tp_type = PJ_TURN_TP_UDP; - - if ((n == 2) && !USE_TLS) - break; - - switch (n) { - case 1: - tp_type = PJ_TURN_TP_TCP; - break; - case 2: - tp_type = PJ_TURN_TP_TLS; - } - - rc = state_progression_test(&stun_cfg, USE_IPV6, tp_type); - if (rc != 0) - goto on_return; - - for (i=0; i<=1; ++i) { - int j; - for (j=0; j<=1; ++j) { - rc = destroy_test(&stun_cfg, i, j, USE_IPV6, tp_type); - if (rc != 0) - goto on_return; - } - } + pj_turn_tp_type tp_type = PJ_TURN_TP_UDP; + + if ((n == 2) && !USE_TLS) + break; + + switch (n) { + case 1: + tp_type = PJ_TURN_TP_TCP; + break; + case 2: + tp_type = PJ_TURN_TP_TLS; + } + + rc = state_progression_test(&stun_cfg, USE_IPV6, tp_type); + if (rc != 0) + goto on_return; + + for (i=0; i<=1; ++i) { + int j; + for (j=0; j<=1; ++j) { + rc = destroy_test(&stun_cfg, i, j, USE_IPV6, tp_type); + if (rc != 0) + goto on_return; + } + } } on_return: diff --git a/pjnath/src/pjnath/errno.c b/pjnath/src/pjnath/errno.c index bbe940d8e8..eed7ac6200 100644 --- a/pjnath/src/pjnath/errno.c +++ b/pjnath/src/pjnath/errno.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -37,14 +36,14 @@ static const struct } err_str[] = { /* STUN related error codes */ - PJ_BUILD_ERR( PJNATH_EINSTUNMSG, "Invalid STUN message"), - PJ_BUILD_ERR( PJNATH_EINSTUNMSGLEN, "Invalid STUN message length"), + PJ_BUILD_ERR( PJNATH_EINSTUNMSG, "Invalid STUN message"), + PJ_BUILD_ERR( PJNATH_EINSTUNMSGLEN, "Invalid STUN message length"), PJ_BUILD_ERR( PJNATH_EINSTUNMSGTYPE, "Invalid or unexpected STUN message type"), - PJ_BUILD_ERR( PJNATH_ESTUNTIMEDOUT, "STUN transaction has timed out"), + PJ_BUILD_ERR( PJNATH_ESTUNTIMEDOUT, "STUN transaction has timed out"), PJ_BUILD_ERR( PJNATH_ESTUNTOOMANYATTR, "Too many STUN attributes"), PJ_BUILD_ERR( PJNATH_ESTUNINATTRLEN, "Invalid STUN attribute length"), - PJ_BUILD_ERR( PJNATH_ESTUNDUPATTR, "Found duplicate STUN attribute"), + PJ_BUILD_ERR( PJNATH_ESTUNDUPATTR, "Found duplicate STUN attribute"), PJ_BUILD_ERR( PJNATH_ESTUNFINGERPRINT, "STUN FINGERPRINT verification failed"), PJ_BUILD_ERR( PJNATH_ESTUNMSGINTPOS, "Invalid STUN attribute after MESSAGE-INTEGRITY"), @@ -52,96 +51,96 @@ static const struct PJ_BUILD_ERR( PJNATH_ESTUNNOMAPPEDADDR, "STUN (XOR-)MAPPED-ADDRESS attribute not found"), PJ_BUILD_ERR( PJNATH_ESTUNIPV6NOTSUPP, "STUN IPv6 attribute not supported"), - PJ_BUILD_ERR( PJNATH_EINVAF, "Invalid STUN address family value"), - PJ_BUILD_ERR( PJNATH_ESTUNINSERVER, "Invalid STUN server or server not configured"), + PJ_BUILD_ERR( PJNATH_EINVAF, "Invalid STUN address family value"), + PJ_BUILD_ERR( PJNATH_ESTUNINSERVER, "Invalid STUN server or server not configured"), PJ_BUILD_ERR( PJNATH_ESTUNDESTROYED, "STUN object has been destoyed"), /* ICE related errors */ - PJ_BUILD_ERR( PJNATH_ENOICE, "ICE session not available"), + PJ_BUILD_ERR( PJNATH_ENOICE, "ICE session not available"), PJ_BUILD_ERR( PJNATH_EICEINPROGRESS, "ICE check is in progress"), - PJ_BUILD_ERR( PJNATH_EICEFAILED, "All ICE checklists failed"), - PJ_BUILD_ERR( PJNATH_EICEMISMATCH, "Default target doesn't match any ICE candidates"), - PJ_BUILD_ERR( PJNATH_EICEINCOMPID, "Invalid ICE component ID"), - PJ_BUILD_ERR( PJNATH_EICEINCANDID, "Invalid ICE candidate ID"), - PJ_BUILD_ERR( PJNATH_EICEINSRCADDR, "Source address mismatch"), + PJ_BUILD_ERR( PJNATH_EICEFAILED, "All ICE checklists failed"), + PJ_BUILD_ERR( PJNATH_EICEMISMATCH, "Default target doesn't match any ICE candidates"), + PJ_BUILD_ERR( PJNATH_EICEINCOMPID, "Invalid ICE component ID"), + PJ_BUILD_ERR( PJNATH_EICEINCANDID, "Invalid ICE candidate ID"), + PJ_BUILD_ERR( PJNATH_EICEINSRCADDR, "Source address mismatch"), PJ_BUILD_ERR( PJNATH_EICEMISSINGSDP, "Missing ICE SDP attribute"), - PJ_BUILD_ERR( PJNATH_EICEINCANDSDP, "Invalid SDP \"candidate\" attribute"), + PJ_BUILD_ERR( PJNATH_EICEINCANDSDP, "Invalid SDP \"candidate\" attribute"), PJ_BUILD_ERR( PJNATH_EICENOHOSTCAND, "No host candidate associated with srflx"), PJ_BUILD_ERR( PJNATH_EICENOMTIMEOUT, "Controlled agent timed out waiting for nomination"), /* TURN related errors */ - PJ_BUILD_ERR( PJNATH_ETURNINTP, "Invalid/unsupported transport"), + PJ_BUILD_ERR( PJNATH_ETURNINTP, "Invalid/unsupported transport"), }; -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ /* * pjnath_strerror() */ static pj_str_t pjnath_strerror(pj_status_t statcode, - char *buf, pj_size_t bufsize ) + char *buf, pj_size_t bufsize ) { pj_str_t errstr; #if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0) if (statcode >= PJNATH_ERRNO_START && - statcode < PJNATH_ERRNO_START + PJ_ERRNO_SPACE_SIZE) + statcode < PJNATH_ERRNO_START + PJ_ERRNO_SPACE_SIZE) { - /* Find the error in the table. - * Use binary search! - */ - int first = 0; - int n = PJ_ARRAY_SIZE(err_str); - - while (n > 0) { - int half = n/2; - int mid = first + half; - - if (err_str[mid].code < statcode) { - first = mid+1; - n -= (half+1); - } else if (err_str[mid].code > statcode) { - n = half; - } else { - first = mid; - break; - } - } - - - if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { - pj_str_t msg; - - msg.ptr = (char*)err_str[first].msg; - msg.slen = pj_ansi_strlen(err_str[first].msg); - - errstr.ptr = buf; - pj_strncpy_with_null(&errstr, &msg, bufsize); - return errstr; - - } + /* Find the error in the table. + * Use binary search! + */ + int first = 0; + int n = PJ_ARRAY_SIZE(err_str); + + while (n > 0) { + int half = n/2; + int mid = first + half; + + if (err_str[mid].code < statcode) { + first = mid+1; + n -= (half+1); + } else if (err_str[mid].code > statcode) { + n = half; + } else { + first = mid; + break; + } + } + + + if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { + pj_str_t msg; + + msg.ptr = (char*)err_str[first].msg; + msg.slen = pj_ansi_strlen(err_str[first].msg); + + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, &msg, bufsize); + return errstr; + + } } -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ /* Error not found. */ errstr.ptr = buf; errstr.slen = pj_ansi_snprintf(buf, bufsize, - "Unknown pjnath error %d", - statcode); + "Unknown pjnath error %d", + statcode); if (errstr.slen < 1 || errstr.slen >= (int)bufsize) - errstr.slen = bufsize-1; + errstr.slen = bufsize-1; return errstr; } static pj_str_t pjnath_strerror2(pj_status_t statcode, - char *buf, pj_size_t bufsize ) + char *buf, pj_size_t bufsize ) { int stun_code = statcode - PJ_STATUS_FROM_STUN_CODE(0); const pj_str_t cmsg = pj_stun_get_err_reason(stun_code); @@ -150,22 +149,22 @@ static pj_str_t pjnath_strerror2(pj_status_t statcode, buf[bufsize-1] = '\0'; if (cmsg.slen == 0) { - /* Not found */ - errstr.ptr = buf; - errstr.slen = pj_ansi_snprintf(buf, bufsize, - "Unknown STUN err-code %d", - stun_code); + /* Not found */ + errstr.ptr = buf; + errstr.slen = pj_ansi_snprintf(buf, bufsize, + "Unknown STUN err-code %d", + stun_code); } else { - errstr.ptr = buf; - pj_strncpy(&errstr, &cmsg, bufsize); - if (errstr.slen < (int)bufsize) - buf[errstr.slen] = '\0'; - else - buf[bufsize-1] = '\0'; + errstr.ptr = buf; + pj_strncpy(&errstr, &cmsg, bufsize); + if (errstr.slen < (int)bufsize) + buf[errstr.slen] = '\0'; + else + buf[bufsize-1] = '\0'; } if (errstr.slen < 1 || errstr.slen >= (int)bufsize) - errstr.slen = bufsize-1; + errstr.slen = bufsize-1; return errstr; } @@ -176,12 +175,12 @@ PJ_DEF(pj_status_t) pjnath_init(void) pj_status_t status; status = pj_register_strerror(PJNATH_ERRNO_START, 299, - &pjnath_strerror); + &pjnath_strerror); pj_assert(status == PJ_SUCCESS); status = pj_register_strerror(PJ_STATUS_FROM_STUN_CODE(300), - 699 - 300, - &pjnath_strerror2); + 699 - 300, + &pjnath_strerror2); pj_assert(status == PJ_SUCCESS); return status; @@ -191,7 +190,7 @@ PJ_DEF(pj_status_t) pjnath_init(void) #if PJNATH_ERROR_LEVEL <= PJ_LOG_MAX_LEVEL PJ_DEF(void) pjnath_perror(const char *sender, const char *title, - pj_status_t status) + pj_status_t status) { #if PJNATH_ERROR_LEVEL==1 PJ_PERROR(1,(sender, status, title)); @@ -208,5 +207,5 @@ PJ_DEF(void) pjnath_perror(const char *sender, const char *title, #endif } -#endif /* PJNATH_ERROR_LEVEL <= PJ_LOG_MAX_LEVEL */ +#endif /* PJNATH_ERROR_LEVEL <= PJ_LOG_MAX_LEVEL */ diff --git a/pjnath/src/pjnath/ice_session.c b/pjnath/src/pjnath/ice_session.c index 2eed817795..a215ec99de 100644 --- a/pjnath/src/pjnath/ice_session.c +++ b/pjnath/src/pjnath/ice_session.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -56,7 +55,7 @@ static const char *clist_state_name[] = "Running", "Completed" }; -#endif /* PJ_LOG_MAX_LEVEL >= 4 */ +#endif /* PJ_LOG_MAX_LEVEL >= 4 */ static const char *role_names[] = { @@ -67,15 +66,15 @@ static const char *role_names[] = enum timer_type { - TIMER_NONE, /**< Timer not active */ - TIMER_COMPLETION_CALLBACK, /**< Call on_ice_complete() callback */ - TIMER_CONTROLLED_WAIT_NOM, /**< Controlled agent is waiting for - controlling agent to send connectivity - check with nominated flag after it has - valid check for every components. */ + TIMER_NONE, /**< Timer not active */ + TIMER_COMPLETION_CALLBACK, /**< Call on_ice_complete() callback */ + TIMER_CONTROLLED_WAIT_NOM, /**< Controlled agent is waiting for + controlling agent to send connectivity + check with nominated flag after it has + valid check for every components. */ TIMER_START_NOMINATED_CHECK,/**< Controlling agent start connectivity - checks with USE-CANDIDATE flag. */ - TIMER_KEEP_ALIVE /**< ICE keep-alive timer. */ + checks with USE-CANDIDATE flag. */ + TIMER_KEEP_ALIVE /**< ICE keep-alive timer. */ }; @@ -84,25 +83,25 @@ static pj_uint8_t cand_type_prefs[PJ_ICE_CAND_TYPE_MAX] = { #if PJ_ICE_CAND_TYPE_PREF_BITS < 8 /* Keep it to 2 bits */ - 3, /**< PJ_ICE_HOST_PREF */ - 1, /**< PJ_ICE_SRFLX_PREF. */ - 2, /**< PJ_ICE_PRFLX_PREF */ - 0 /**< PJ_ICE_RELAYED_PREF */ + 3, /**< PJ_ICE_HOST_PREF */ + 1, /**< PJ_ICE_SRFLX_PREF. */ + 2, /**< PJ_ICE_PRFLX_PREF */ + 0 /**< PJ_ICE_RELAYED_PREF */ #else /* Default ICE session preferences, according to draft-ice */ - 126, /**< PJ_ICE_HOST_PREF */ - 100, /**< PJ_ICE_SRFLX_PREF. */ - 110, /**< PJ_ICE_PRFLX_PREF */ - 0 /**< PJ_ICE_RELAYED_PREF */ + 126, /**< PJ_ICE_HOST_PREF */ + 100, /**< PJ_ICE_SRFLX_PREF. */ + 110, /**< PJ_ICE_PRFLX_PREF */ + 0 /**< PJ_ICE_RELAYED_PREF */ #endif }; -#define THIS_FILE "ice_session.c" -#define CHECK_NAME_LEN 128 -#define LOG4(expr) PJ_LOG(4,expr) -#define LOG5(expr) PJ_LOG(4,expr) -#define GET_LCAND_ID(cand) (unsigned)(cand - ice->lcand) -#define GET_CHECK_ID(cl, chk) (chk - (cl)->checks) +#define THIS_FILE "ice_session.c" +#define CHECK_NAME_LEN 128 +#define LOG4(expr) PJ_LOG(4,expr) +#define LOG5(expr) PJ_LOG(4,expr) +#define GET_LCAND_ID(cand) (unsigned)(cand - ice->lcand) +#define GET_CHECK_ID(cl, chk) (chk - (cl)->checks) /* The data that will be attached to the STUN session on each @@ -110,9 +109,9 @@ static pj_uint8_t cand_type_prefs[PJ_ICE_CAND_TYPE_MAX] = */ typedef struct stun_data { - pj_ice_sess *ice; - unsigned comp_id; - pj_ice_sess_comp *comp; + pj_ice_sess *ice; + unsigned comp_id; + pj_ice_sess_comp *comp; } stun_data; @@ -121,7 +120,7 @@ typedef struct stun_data */ typedef struct timer_data { - pj_ice_sess *ice; + pj_ice_sess *ice; pj_ice_sess_checklist *clist; } timer_data; @@ -137,66 +136,66 @@ static void on_ice_complete(pj_ice_sess *ice, pj_status_t status); static void ice_keep_alive(pj_ice_sess *ice, pj_bool_t send_now); static void ice_on_destroy(void *obj); static void destroy_ice(pj_ice_sess *ice, - pj_status_t reason); + pj_status_t reason); static pj_status_t start_periodic_check(pj_timer_heap_t *th, - pj_timer_entry *te); + pj_timer_entry *te); static void start_nominated_check(pj_ice_sess *ice); static void periodic_timer(pj_timer_heap_t *th, - pj_timer_entry *te); + pj_timer_entry *te); static void handle_incoming_check(pj_ice_sess *ice, - const pj_ice_rx_check *rcheck); + const pj_ice_rx_check *rcheck); static void end_of_cand_ind_timer(pj_timer_heap_t *th, - pj_timer_entry *te); + pj_timer_entry *te); /* These are the callbacks registered to the STUN sessions */ static pj_status_t on_stun_send_msg(pj_stun_session *sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len); + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len); static pj_status_t on_stun_rx_request(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_rx_data *rdata, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_rx_data *rdata, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); static void on_stun_request_complete(pj_stun_session *stun_sess, - pj_status_t status, - void *token, - pj_stun_tx_data *tdata, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + pj_status_t status, + void *token, + pj_stun_tx_data *tdata, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); static pj_status_t on_stun_rx_indication(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_msg *msg, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_msg *msg, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); /* These are the callbacks for performing STUN authentication */ static pj_status_t stun_auth_get_auth(void *user_data, - pj_pool_t *pool, - pj_str_t *realm, - pj_str_t *nonce); + pj_pool_t *pool, + pj_str_t *realm, + pj_str_t *nonce); static pj_status_t stun_auth_get_cred(const pj_stun_msg *msg, - void *user_data, - pj_pool_t *pool, - pj_str_t *realm, - pj_str_t *username, - pj_str_t *nonce, - pj_stun_passwd_type *data_type, - pj_str_t *data); + void *user_data, + pj_pool_t *pool, + pj_str_t *realm, + pj_str_t *username, + pj_str_t *nonce, + pj_stun_passwd_type *data_type, + pj_str_t *data); static pj_status_t stun_auth_get_password(const pj_stun_msg *msg, - void *user_data, - const pj_str_t *realm, - const pj_str_t *username, - pj_pool_t *pool, - pj_stun_passwd_type *data_type, - pj_str_t *data); + void *user_data, + const pj_str_t *realm, + const pj_str_t *username, + pj_pool_t *pool, + pj_stun_passwd_type *data_type, + pj_str_t *data); PJ_DEF(const char*) pj_ice_get_cand_type_name(pj_ice_cand_type type) @@ -210,13 +209,13 @@ PJ_DEF(const char*) pj_ice_sess_role_name(pj_ice_sess_role role) { switch (role) { case PJ_ICE_SESS_ROLE_UNKNOWN: - return "Unknown"; + return "Unknown"; case PJ_ICE_SESS_ROLE_CONTROLLED: - return "Controlled"; + return "Controlled"; case PJ_ICE_SESS_ROLE_CONTROLLING: - return "Controlling"; + return "Controlling"; default: - return "??"; + return "??"; } } @@ -225,13 +224,13 @@ PJ_DEF(const char*) pj_ice_sess_role_name(pj_ice_sess_role role) static int get_type_prefix(pj_ice_cand_type type) { switch (type) { - case PJ_ICE_CAND_TYPE_HOST: return 'H'; + case PJ_ICE_CAND_TYPE_HOST: return 'H'; case PJ_ICE_CAND_TYPE_SRFLX: return 'S'; case PJ_ICE_CAND_TYPE_PRFLX: return 'P'; case PJ_ICE_CAND_TYPE_RELAYED: return 'R'; default: - pj_assert(!"Invalid type"); - return 'U'; + pj_assert(!"Invalid type"); + return 'U'; } } @@ -242,22 +241,22 @@ static int get_type_prefix(pj_ice_cand_type type) * different. */ PJ_DEF(void) pj_ice_calc_foundation(pj_pool_t *pool, - pj_str_t *foundation, - pj_ice_cand_type type, - const pj_sockaddr *base_addr) + pj_str_t *foundation, + pj_ice_cand_type type, + const pj_sockaddr *base_addr) { #if PJNATH_ICE_PRIO_STD char buf[64]; pj_uint32_t val; if (base_addr->addr.sa_family == pj_AF_INET()) { - val = pj_ntohl(base_addr->ipv4.sin_addr.s_addr); + val = pj_ntohl(base_addr->ipv4.sin_addr.s_addr); } else { - val = pj_hash_calc(0, pj_sockaddr_get_addr(base_addr), - pj_sockaddr_get_addr_len(base_addr)); + val = pj_hash_calc(0, pj_sockaddr_get_addr(base_addr), + pj_sockaddr_get_addr_len(base_addr)); } pj_ansi_snprintf(buf, sizeof(buf), "%c%x", - get_type_prefix(type), val); + get_type_prefix(type), val); pj_strdup2(pool, foundation, buf); #else /* Much shorter version, valid for candidates added by @@ -274,8 +273,8 @@ PJ_DEF(void) pj_ice_calc_foundation(pj_pool_t *pool, /* Init component */ static pj_status_t init_comp(pj_ice_sess *ice, - unsigned comp_id, - pj_ice_sess_comp *comp) + unsigned comp_id, + pj_ice_sess_comp *comp) { pj_stun_session_cb sess_cb; pj_stun_auth_cred auth_cred; @@ -291,11 +290,11 @@ static pj_status_t init_comp(pj_ice_sess *ice, /* Create STUN session for this candidate */ status = pj_stun_session_create(&ice->stun_cfg, NULL, - &sess_cb, PJ_TRUE, - ice->grp_lock, - &comp->stun_sess); + &sess_cb, PJ_TRUE, + ice->grp_lock, + &comp->stun_sess); if (status != PJ_SUCCESS) - return status; + return status; /* Associate data with this STUN session */ sd = PJ_POOL_ZALLOC_T(ice->pool, struct stun_data); @@ -312,7 +311,7 @@ static pj_status_t init_comp(pj_ice_sess *ice, auth_cred.data.dyn_cred.get_password = &stun_auth_get_password; auth_cred.data.dyn_cred.user_data = comp->stun_sess; pj_stun_session_set_credential(comp->stun_sess, PJ_STUN_AUTH_SHORT_TERM, - &auth_cred); + &auth_cred); return PJ_SUCCESS; } @@ -324,7 +323,7 @@ PJ_DEF(void) pj_ice_sess_options_default(pj_ice_sess_options *opt) opt->aggressive = PJ_TRUE; opt->nominated_check_delay = PJ_ICE_NOMINATED_CHECK_DELAY; opt->controlled_agent_want_nom_timeout = - ICE_CONTROLLED_AGENT_WAIT_NOMINATION_TIMEOUT; + ICE_CONTROLLED_AGENT_WAIT_NOMINATION_TIMEOUT; opt->trickle = PJ_ICE_SESS_TRICKLE_DISABLED; } @@ -332,14 +331,14 @@ PJ_DEF(void) pj_ice_sess_options_default(pj_ice_sess_options *opt) * Create ICE session. */ PJ_DEF(pj_status_t) pj_ice_sess_create(pj_stun_config *stun_cfg, - const char *name, - pj_ice_sess_role role, - unsigned comp_cnt, - const pj_ice_sess_cb *cb, - const pj_str_t *local_ufrag, - const pj_str_t *local_passwd, - pj_grp_lock_t *grp_lock, - pj_ice_sess **p_ice) + const char *name, + pj_ice_sess_role role, + unsigned comp_cnt, + const pj_ice_sess_cb *cb, + const pj_str_t *local_ufrag, + const pj_str_t *local_passwd, + pj_grp_lock_t *grp_lock, + pj_ice_sess **p_ice) { pj_pool_t *pool; pj_ice_sess *ice; @@ -349,10 +348,10 @@ PJ_DEF(pj_status_t) pj_ice_sess_create(pj_stun_config *stun_cfg, PJ_ASSERT_RETURN(stun_cfg && cb && p_ice, PJ_EINVAL); if (name == NULL) - name = "icess%p"; + name = "icess%p"; pool = pj_pool_create(stun_cfg->pf, name, PJNATH_POOL_LEN_ICE_SESS, - PJNATH_POOL_INC_ICE_SESS, NULL); + PJNATH_POOL_INC_ICE_SESS, NULL); ice = PJ_POOL_ZALLOC_T(pool, pj_ice_sess); ice->pool = pool; ice->role = role; @@ -364,16 +363,16 @@ PJ_DEF(pj_status_t) pj_ice_sess_create(pj_stun_config *stun_cfg, pj_timer_entry_init(&ice->timer, TIMER_NONE, (void*)ice, &on_timer); pj_ansi_snprintf(ice->obj_name, sizeof(ice->obj_name), - name, ice); + name, ice); if (grp_lock) { - ice->grp_lock = grp_lock; + ice->grp_lock = grp_lock; } else { - status = pj_grp_lock_create(pool, NULL, &ice->grp_lock); - if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; - } + status = pj_grp_lock_create(pool, NULL, &ice->grp_lock); + if (status != PJ_SUCCESS) { + pj_pool_release(pool); + return status; + } } pj_grp_lock_add_ref(ice->grp_lock); @@ -385,38 +384,38 @@ PJ_DEF(pj_status_t) pj_ice_sess_create(pj_stun_config *stun_cfg, ice->comp_cnt = comp_cnt; for (i=0; icomp[i]; - comp->valid_check = NULL; - comp->nominated_check = NULL; - - status = init_comp(ice, i+1, comp); - if (status != PJ_SUCCESS) { - destroy_ice(ice, status); - return status; - } + pj_ice_sess_comp *comp; + comp = &ice->comp[i]; + comp->valid_check = NULL; + comp->nominated_check = NULL; + + status = init_comp(ice, i+1, comp); + if (status != PJ_SUCCESS) { + destroy_ice(ice, status); + return status; + } } /* Initialize transport datas */ for (i=0; itp_data); ++i) { - ice->tp_data[i].transport_id = 0; - ice->tp_data[i].has_req_data = PJ_FALSE; + ice->tp_data[i].transport_id = 0; + ice->tp_data[i].has_req_data = PJ_FALSE; } if (local_ufrag == NULL) { - ice->rx_ufrag.ptr = (char*) pj_pool_alloc(ice->pool, PJ_ICE_UFRAG_LEN); - pj_create_random_string(ice->rx_ufrag.ptr, PJ_ICE_UFRAG_LEN); - ice->rx_ufrag.slen = PJ_ICE_UFRAG_LEN; + ice->rx_ufrag.ptr = (char*) pj_pool_alloc(ice->pool, PJ_ICE_UFRAG_LEN); + pj_create_random_string(ice->rx_ufrag.ptr, PJ_ICE_UFRAG_LEN); + ice->rx_ufrag.slen = PJ_ICE_UFRAG_LEN; } else { - pj_strdup(ice->pool, &ice->rx_ufrag, local_ufrag); + pj_strdup(ice->pool, &ice->rx_ufrag, local_ufrag); } if (local_passwd == NULL) { - ice->rx_pass.ptr = (char*) pj_pool_alloc(ice->pool, PJ_ICE_PWD_LEN); - pj_create_random_string(ice->rx_pass.ptr, PJ_ICE_PWD_LEN); - ice->rx_pass.slen = PJ_ICE_PWD_LEN; + ice->rx_pass.ptr = (char*) pj_pool_alloc(ice->pool, PJ_ICE_PWD_LEN); + pj_create_random_string(ice->rx_pass.ptr, PJ_ICE_PWD_LEN); + ice->rx_pass.slen = PJ_ICE_PWD_LEN; } else { - pj_strdup(ice->pool, &ice->rx_pass, local_passwd); + pj_strdup(ice->pool, &ice->rx_pass, local_passwd); } pj_list_init(&ice->early_check); @@ -427,8 +426,8 @@ PJ_DEF(pj_status_t) pj_ice_sess_create(pj_stun_config *stun_cfg, *p_ice = ice; LOG4((ice->obj_name, - "ICE session created, comp_cnt=%d, role is %s agent", - comp_cnt, role_names[ice->role])); + "ICE session created, comp_cnt=%d, role is %s agent", + comp_cnt, role_names[ice->role])); return PJ_SUCCESS; } @@ -438,7 +437,7 @@ PJ_DEF(pj_status_t) pj_ice_sess_create(pj_stun_config *stun_cfg, * Get the value of various options of the ICE session. */ PJ_DEF(pj_status_t) pj_ice_sess_get_options(pj_ice_sess *ice, - pj_ice_sess_options *opt) + pj_ice_sess_options *opt) { PJ_ASSERT_RETURN(ice, PJ_EINVAL); pj_memcpy(opt, &ice->opt, sizeof(*opt)); @@ -449,25 +448,25 @@ PJ_DEF(pj_status_t) pj_ice_sess_get_options(pj_ice_sess *ice, * Specify various options for this ICE session. */ PJ_DEF(pj_status_t) pj_ice_sess_set_options(pj_ice_sess *ice, - const pj_ice_sess_options *opt) + const pj_ice_sess_options *opt) { PJ_ASSERT_RETURN(ice && opt, PJ_EINVAL); pj_memcpy(&ice->opt, opt, sizeof(*opt)); ice->is_trickling = (ice->opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED); if (ice->is_trickling) { - LOG5((ice->obj_name, "Trickle ICE is active (%s mode)", - (ice->opt.trickle==PJ_ICE_SESS_TRICKLE_HALF? "half":"full"))); - - if (ice->opt.aggressive) { - /* Disable aggressive when ICE trickle is active */ - ice->opt.aggressive = PJ_FALSE; - LOG4((ice->obj_name, "Warning: aggressive nomination is disabled" - " as trickle ICE is active")); - } + LOG5((ice->obj_name, "Trickle ICE is active (%s mode)", + (ice->opt.trickle==PJ_ICE_SESS_TRICKLE_HALF? "half":"full"))); + + if (ice->opt.aggressive) { + /* Disable aggressive when ICE trickle is active */ + ice->opt.aggressive = PJ_FALSE; + LOG4((ice->obj_name, "Warning: aggressive nomination is disabled" + " as trickle ICE is active")); + } } LOG5((ice->obj_name, "ICE nomination type set to %s", - (ice->opt.aggressive ? "aggressive" : "regular"))); + (ice->opt.aggressive ? "aggressive" : "regular"))); return PJ_SUCCESS; } @@ -488,19 +487,19 @@ static void ice_on_destroy(void *obj) * Destroy */ static void destroy_ice(pj_ice_sess *ice, - pj_status_t reason) + pj_status_t reason) { unsigned i; if (reason == PJ_SUCCESS) { - LOG4((ice->obj_name, "Destroying ICE session %p", ice)); + LOG4((ice->obj_name, "Destroying ICE session %p", ice)); } pj_grp_lock_acquire(ice->grp_lock); if (ice->is_destroying) { - pj_grp_lock_release(ice->grp_lock); - return; + pj_grp_lock_release(ice->grp_lock); + return; } ice->is_destroying = PJ_TRUE; @@ -509,10 +508,10 @@ static void destroy_ice(pj_ice_sess *ice, &ice->timer, PJ_FALSE); for (i=0; icomp_cnt; ++i) { - if (ice->comp[i].stun_sess) { - pj_stun_session_destroy(ice->comp[i].stun_sess); - ice->comp[i].stun_sess = NULL; - } + if (ice->comp[i].stun_sess) { + pj_stun_session_destroy(ice->comp[i].stun_sess); + ice->comp[i].stun_sess = NULL; + } } pj_timer_heap_cancel_if_active(ice->stun_cfg.timer_heap, @@ -539,7 +538,7 @@ PJ_DEF(pj_status_t) pj_ice_sess_destroy(pj_ice_sess *ice) * Detach ICE session from group lock. */ PJ_DEF(pj_status_t) pj_ice_sess_detach_grp_lock(pj_ice_sess *ice, - pj_grp_lock_handler *handler) + pj_grp_lock_handler *handler) { PJ_ASSERT_RETURN(ice && handler, PJ_EINVAL); @@ -555,13 +554,13 @@ PJ_DEF(pj_status_t) pj_ice_sess_detach_grp_lock(pj_ice_sess *ice, * Change session role. */ PJ_DEF(pj_status_t) pj_ice_sess_change_role(pj_ice_sess *ice, - pj_ice_sess_role new_role) + pj_ice_sess_role new_role) { PJ_ASSERT_RETURN(ice, PJ_EINVAL); if (new_role != ice->role) { - ice->role = new_role; - LOG4((ice->obj_name, "Role changed to %s", role_names[new_role])); + ice->role = new_role; + LOG4((ice->obj_name, "Role changed to %s", role_names[new_role])); } return PJ_SUCCESS; @@ -572,17 +571,17 @@ PJ_DEF(pj_status_t) pj_ice_sess_change_role(pj_ice_sess *ice, * Change type preference */ PJ_DEF(pj_status_t) pj_ice_sess_set_prefs(pj_ice_sess *ice, - const pj_uint8_t prefs[4]) + const pj_uint8_t prefs[4]) { unsigned i; PJ_ASSERT_RETURN(ice && prefs, PJ_EINVAL); ice->prefs = (pj_uint8_t*) pj_pool_calloc(ice->pool, PJ_ICE_CAND_TYPE_MAX, - sizeof(pj_uint8_t)); + sizeof(pj_uint8_t)); for (i=0; iprefs[i] = prefs[i]; + ice->prefs[i] = prefs[i]; } return PJ_SUCCESS; } @@ -594,7 +593,7 @@ static pj_ice_sess_comp *find_comp(const pj_ice_sess *ice, unsigned comp_id) /* Ticket #1844: possible wrong assertion when remote has less ICE comp */ //pj_assert(comp_id > 0 && comp_id <= ice->comp_cnt); if (comp_id > ice->comp_cnt) - return NULL; + return NULL; return (pj_ice_sess_comp*) &ice->comp[comp_id-1]; } @@ -602,9 +601,9 @@ static pj_ice_sess_comp *find_comp(const pj_ice_sess *ice, unsigned comp_id) /* Callback by STUN authentication when it needs to send 401 */ static pj_status_t stun_auth_get_auth(void *user_data, - pj_pool_t *pool, - pj_str_t *realm, - pj_str_t *nonce) + pj_pool_t *pool, + pj_str_t *realm, + pj_str_t *nonce) { PJ_UNUSED_ARG(user_data); PJ_UNUSED_ARG(pool); @@ -618,13 +617,13 @@ static pj_status_t stun_auth_get_auth(void *user_data, /* Get credential to be sent with outgoing message */ static pj_status_t stun_auth_get_cred(const pj_stun_msg *msg, - void *user_data, - pj_pool_t *pool, - pj_str_t *realm, - pj_str_t *username, - pj_str_t *nonce, - pj_stun_passwd_type *data_type, - pj_str_t *data) + void *user_data, + pj_pool_t *pool, + pj_str_t *realm, + pj_str_t *username, + pj_str_t *nonce, + pj_stun_passwd_type *data_type, + pj_str_t *data) { pj_stun_session *sess = (pj_stun_session *)user_data; stun_data *sd = (stun_data*) pj_stun_session_get_user_data(sess); @@ -634,17 +633,17 @@ static pj_status_t stun_auth_get_cred(const pj_stun_msg *msg, realm->slen = nonce->slen = 0; if (PJ_STUN_IS_RESPONSE(msg->hdr.type)) { - /* Outgoing responses need to have the same credential as - * incoming requests. - */ - *username = ice->rx_uname; - *data_type = PJ_STUN_PASSWD_PLAIN; - *data = ice->rx_pass; + /* Outgoing responses need to have the same credential as + * incoming requests. + */ + *username = ice->rx_uname; + *data_type = PJ_STUN_PASSWD_PLAIN; + *data = ice->rx_pass; } else { - *username = ice->tx_uname; - *data_type = PJ_STUN_PASSWD_PLAIN; - *data = ice->tx_pass; + *username = ice->tx_uname; + *data_type = PJ_STUN_PASSWD_PLAIN; + *data = ice->tx_pass; } return PJ_SUCCESS; @@ -652,12 +651,12 @@ static pj_status_t stun_auth_get_cred(const pj_stun_msg *msg, /* Get password to be used to authenticate incoming message */ static pj_status_t stun_auth_get_password(const pj_stun_msg *msg, - void *user_data, - const pj_str_t *realm, - const pj_str_t *username, - pj_pool_t *pool, - pj_stun_passwd_type *data_type, - pj_str_t *data) + void *user_data, + const pj_str_t *realm, + const pj_str_t *username, + pj_pool_t *pool, + pj_stun_passwd_type *data_type, + pj_str_t *data) { pj_stun_session *sess = (pj_stun_session *)user_data; stun_data *sd = (stun_data*) pj_stun_session_get_user_data(sess); @@ -667,39 +666,39 @@ static pj_status_t stun_auth_get_password(const pj_stun_msg *msg, PJ_UNUSED_ARG(pool); if (PJ_STUN_IS_SUCCESS_RESPONSE(msg->hdr.type) || - PJ_STUN_IS_ERROR_RESPONSE(msg->hdr.type)) + PJ_STUN_IS_ERROR_RESPONSE(msg->hdr.type)) { - /* Incoming response is authenticated with TX credential */ - /* Verify username */ - if (pj_strcmp(username, &ice->tx_uname) != 0) - return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNAUTHORIZED); - *data_type = PJ_STUN_PASSWD_PLAIN; - *data = ice->tx_pass; + /* Incoming response is authenticated with TX credential */ + /* Verify username */ + if (pj_strcmp(username, &ice->tx_uname) != 0) + return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNAUTHORIZED); + *data_type = PJ_STUN_PASSWD_PLAIN; + *data = ice->tx_pass; } else { - /* Incoming request is authenticated with RX credential */ - /* The agent MUST accept a credential if the username consists - * of two values separated by a colon, where the first value is - * equal to the username fragment generated by the agent in an offer - * or answer for a session in-progress, and the MESSAGE-INTEGRITY - * is the output of a hash of the password and the STUN packet's - * contents. - */ - const char *pos; - pj_str_t ufrag; + /* Incoming request is authenticated with RX credential */ + /* The agent MUST accept a credential if the username consists + * of two values separated by a colon, where the first value is + * equal to the username fragment generated by the agent in an offer + * or answer for a session in-progress, and the MESSAGE-INTEGRITY + * is the output of a hash of the password and the STUN packet's + * contents. + */ + const char *pos; + pj_str_t ufrag; - pos = (const char*)pj_memchr(username->ptr, ':', username->slen); - if (pos == NULL) - return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNAUTHORIZED); + pos = (const char*)pj_memchr(username->ptr, ':', username->slen); + if (pos == NULL) + return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNAUTHORIZED); - ufrag.ptr = (char*)username->ptr; - ufrag.slen = (pos - username->ptr); + ufrag.ptr = (char*)username->ptr; + ufrag.slen = (pos - username->ptr); - if (pj_strcmp(&ufrag, &ice->rx_ufrag) != 0) - return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNAUTHORIZED); + if (pj_strcmp(&ufrag, &ice->rx_ufrag) != 0) + return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNAUTHORIZED); - *data_type = PJ_STUN_PASSWD_PLAIN; - *data = ice->rx_pass; + *data_type = PJ_STUN_PASSWD_PLAIN; + *data = ice->rx_pass; } @@ -708,30 +707,30 @@ static pj_status_t stun_auth_get_password(const pj_stun_msg *msg, static pj_uint32_t CALC_CAND_PRIO(pj_ice_sess *ice, - pj_ice_cand_type type, - pj_uint32_t local_pref, - pj_uint32_t comp_id) + pj_ice_cand_type type, + pj_uint32_t local_pref, + pj_uint32_t comp_id) { #if PJNATH_ICE_PRIO_STD return ((ice->prefs[type] & 0xFF) << 24) + - ((local_pref & 0xFFFF) << 8) + - (((256 - comp_id) & 0xFF) << 0); + ((local_pref & 0xFFFF) << 8) + + (((256 - comp_id) & 0xFF) << 0); #else enum { - type_mask = ((1 << PJ_ICE_CAND_TYPE_PREF_BITS) - 1), - local_mask = ((1 << PJ_ICE_LOCAL_PREF_BITS) - 1), - comp_mask = ((1 << PJ_ICE_COMP_BITS) - 1), + type_mask = ((1 << PJ_ICE_CAND_TYPE_PREF_BITS) - 1), + local_mask = ((1 << PJ_ICE_LOCAL_PREF_BITS) - 1), + comp_mask = ((1 << PJ_ICE_COMP_BITS) - 1), - comp_shift = 0, - local_shift = (PJ_ICE_COMP_BITS), - type_shift = (comp_shift + local_shift), + comp_shift = 0, + local_shift = (PJ_ICE_COMP_BITS), + type_shift = (comp_shift + local_shift), - max_comp = (2<prefs[type] & type_mask) << type_shift) + - ((local_pref & local_mask) << local_shift) + - (((max_comp - comp_id) & comp_mask) << comp_shift); + ((local_pref & local_mask) << local_shift) + + (((max_comp - comp_id) & comp_mask) << comp_shift); #endif } @@ -740,16 +739,16 @@ static pj_uint32_t CALC_CAND_PRIO(pj_ice_sess *ice, * Add ICE candidate */ PJ_DEF(pj_status_t) pj_ice_sess_add_cand(pj_ice_sess *ice, - unsigned comp_id, - unsigned transport_id, - pj_ice_cand_type type, - pj_uint16_t local_pref, - const pj_str_t *foundation, - const pj_sockaddr_t *addr, - const pj_sockaddr_t *base_addr, - const pj_sockaddr_t *rel_addr, - int addr_len, - unsigned *p_cand_id) + unsigned comp_id, + unsigned transport_id, + pj_ice_cand_type type, + pj_uint16_t local_pref, + const pj_str_t *foundation, + const pj_sockaddr_t *addr, + const pj_sockaddr_t *base_addr, + const pj_sockaddr_t *rel_addr, + int addr_len, + unsigned *p_cand_id) { pj_ice_sess_cand *lcand; pj_status_t status = PJ_SUCCESS; @@ -757,37 +756,37 @@ PJ_DEF(pj_status_t) pj_ice_sess_add_cand(pj_ice_sess *ice, unsigned i; PJ_ASSERT_RETURN(ice && comp_id && - foundation && addr && base_addr && addr_len, - PJ_EINVAL); + foundation && addr && base_addr && addr_len, + PJ_EINVAL); PJ_ASSERT_RETURN(comp_id <= ice->comp_cnt, PJ_EINVAL); pj_grp_lock_acquire(ice->grp_lock); if (ice->lcand_cnt >= PJ_ARRAY_SIZE(ice->lcand)) { - status = PJ_ETOOMANY; - goto on_return; + status = PJ_ETOOMANY; + goto on_return; } if (ice->opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED) { - /* Trickle ICE: - * Make sure that candidate has not been added - */ - for (i=0; ilcand_cnt; ++i) { - const pj_ice_sess_cand *c = &ice->lcand[i]; - if (c->comp_id==comp_id && c->type == type && - pj_sockaddr_cmp(&c->addr, addr)==0 && - pj_sockaddr_cmp(&c->base_addr, base_addr)==0) - { - break; - } - } - - /* Skip candidate, it has been added */ - if (i < ice->lcand_cnt) { - if (p_cand_id) - *p_cand_id = i; - goto on_return; - } + /* Trickle ICE: + * Make sure that candidate has not been added + */ + for (i=0; ilcand_cnt; ++i) { + const pj_ice_sess_cand *c = &ice->lcand[i]; + if (c->comp_id==comp_id && c->type == type && + pj_sockaddr_cmp(&c->addr, addr)==0 && + pj_sockaddr_cmp(&c->base_addr, base_addr)==0) + { + break; + } + } + + /* Skip candidate, it has been added */ + if (i < ice->lcand_cnt) { + if (p_cand_id) + *p_cand_id = i; + goto on_return; + } } lcand = &ice->lcand[ice->lcand_cnt]; @@ -801,42 +800,42 @@ PJ_DEF(pj_status_t) pj_ice_sess_add_cand(pj_ice_sess *ice, pj_sockaddr_cp(&lcand->addr, addr); pj_sockaddr_cp(&lcand->base_addr, base_addr); if (rel_addr == NULL) - rel_addr = base_addr; + rel_addr = base_addr; pj_memcpy(&lcand->rel_addr, rel_addr, addr_len); /* Update transport data */ for (i = 0; i < PJ_ARRAY_SIZE(ice->tp_data); ++i) { - /* Check if this transport has been registered */ - if (ice->tp_data[i].transport_id == transport_id) - break; - - if (ice->tp_data[i].transport_id == 0) { - /* Found an empty slot, register this transport here */ - ice->tp_data[i].transport_id = transport_id; - break; - } + /* Check if this transport has been registered */ + if (ice->tp_data[i].transport_id == transport_id) + break; + + if (ice->tp_data[i].transport_id == 0) { + /* Found an empty slot, register this transport here */ + ice->tp_data[i].transport_id = transport_id; + break; + } } pj_assert(i < PJ_ARRAY_SIZE(ice->tp_data) && - ice->tp_data[i].transport_id == transport_id); + ice->tp_data[i].transport_id == transport_id); pj_ansi_strcpy(ice->tmp.txt, pj_sockaddr_print(&lcand->addr, address, sizeof(address), 2)); LOG4((ice->obj_name, - "Candidate %d added: comp_id=%d, type=%s, foundation=%.*s, " - "addr=%s:%d, base=%s:%d, prio=0x%x (%u)", - lcand->id, - lcand->comp_id, - cand_type_names[lcand->type], - (int)lcand->foundation.slen, - lcand->foundation.ptr, - ice->tmp.txt, - pj_sockaddr_get_port(&lcand->addr), - pj_sockaddr_print(&lcand->base_addr, address, sizeof(address), 2), - pj_sockaddr_get_port(&lcand->base_addr), - lcand->prio, lcand->prio)); + "Candidate %d added: comp_id=%d, type=%s, foundation=%.*s, " + "addr=%s:%d, base=%s:%d, prio=0x%x (%u)", + lcand->id, + lcand->comp_id, + cand_type_names[lcand->type], + (int)lcand->foundation.slen, + lcand->foundation.ptr, + ice->tmp.txt, + pj_sockaddr_get_port(&lcand->addr), + pj_sockaddr_print(&lcand->base_addr, address, sizeof(address), 2), + pj_sockaddr_get_port(&lcand->base_addr), + lcand->prio, lcand->prio)); if (p_cand_id) - *p_cand_id = lcand->id; + *p_cand_id = lcand->id; ++ice->lcand_cnt; @@ -848,8 +847,8 @@ PJ_DEF(pj_status_t) pj_ice_sess_add_cand(pj_ice_sess *ice, /* Find default candidate ID for the component */ PJ_DEF(pj_status_t) pj_ice_sess_find_default_cand(pj_ice_sess *ice, - unsigned comp_id, - int *cand_id) + unsigned comp_id, + int *cand_id) { unsigned i; @@ -862,50 +861,50 @@ PJ_DEF(pj_status_t) pj_ice_sess_find_default_cand(pj_ice_sess *ice, /* First find in valid list if we have nominated pair */ for (i=0; ivalid_list.count; ++i) { - pj_ice_sess_check *check = &ice->valid_list.checks[i]; - - if (check->lcand->comp_id == comp_id) { - *cand_id = GET_LCAND_ID(check->lcand); - pj_grp_lock_release(ice->grp_lock); - return PJ_SUCCESS; - } + pj_ice_sess_check *check = &ice->valid_list.checks[i]; + + if (check->lcand->comp_id == comp_id) { + *cand_id = GET_LCAND_ID(check->lcand); + pj_grp_lock_release(ice->grp_lock); + return PJ_SUCCESS; + } } /* If there's no nominated pair, find relayed candidate */ for (i=0; ilcand_cnt; ++i) { - pj_ice_sess_cand *lcand = &ice->lcand[i]; - if (lcand->comp_id==comp_id && - lcand->type == PJ_ICE_CAND_TYPE_RELAYED) - { - *cand_id = GET_LCAND_ID(lcand); - pj_grp_lock_release(ice->grp_lock); - return PJ_SUCCESS; - } + pj_ice_sess_cand *lcand = &ice->lcand[i]; + if (lcand->comp_id==comp_id && + lcand->type == PJ_ICE_CAND_TYPE_RELAYED) + { + *cand_id = GET_LCAND_ID(lcand); + pj_grp_lock_release(ice->grp_lock); + return PJ_SUCCESS; + } } /* If there's no relayed candidate, find reflexive candidate */ for (i=0; ilcand_cnt; ++i) { - pj_ice_sess_cand *lcand = &ice->lcand[i]; - if (lcand->comp_id==comp_id && - (lcand->type == PJ_ICE_CAND_TYPE_SRFLX || - lcand->type == PJ_ICE_CAND_TYPE_PRFLX)) - { - *cand_id = GET_LCAND_ID(lcand); - pj_grp_lock_release(ice->grp_lock); - return PJ_SUCCESS; - } + pj_ice_sess_cand *lcand = &ice->lcand[i]; + if (lcand->comp_id==comp_id && + (lcand->type == PJ_ICE_CAND_TYPE_SRFLX || + lcand->type == PJ_ICE_CAND_TYPE_PRFLX)) + { + *cand_id = GET_LCAND_ID(lcand); + pj_grp_lock_release(ice->grp_lock); + return PJ_SUCCESS; + } } /* Otherwise return host candidate */ for (i=0; ilcand_cnt; ++i) { - pj_ice_sess_cand *lcand = &ice->lcand[i]; - if (lcand->comp_id==comp_id && - lcand->type == PJ_ICE_CAND_TYPE_HOST) - { - *cand_id = GET_LCAND_ID(lcand); - pj_grp_lock_release(ice->grp_lock); - return PJ_SUCCESS; - } + pj_ice_sess_cand *lcand = &ice->lcand[i]; + if (lcand->comp_id==comp_id && + lcand->type == PJ_ICE_CAND_TYPE_HOST) + { + *cand_id = GET_LCAND_ID(lcand); + pj_grp_lock_release(ice->grp_lock); + return PJ_SUCCESS; + } } /* Still no candidate is found! :( */ @@ -925,8 +924,8 @@ PJ_DEF(pj_status_t) pj_ice_sess_find_default_cand(pj_ice_sess *ice, #endif static pj_timestamp CALC_CHECK_PRIO(const pj_ice_sess *ice, - const pj_ice_sess_cand *lcand, - const pj_ice_sess_cand *rcand) + const pj_ice_sess_cand *lcand, + const pj_ice_sess_cand *rcand) { pj_uint32_t O, A; pj_timestamp prio; @@ -936,16 +935,16 @@ static pj_timestamp CALC_CHECK_PRIO(const pj_ice_sess *ice, */ if (ice->role == PJ_ICE_SESS_ROLE_CONTROLLING) { - O = lcand->prio; - A = rcand->prio; + O = lcand->prio; + A = rcand->prio; } else { - O = rcand->prio; - A = lcand->prio; + O = rcand->prio; + A = lcand->prio; } /* return ((pj_uint64_t)1 << 32) * MIN(O, A) + - (pj_uint64_t)2 * MAX(O, A) + (O>A ? 1 : 0); + (pj_uint64_t)2 * MAX(O, A) + (O>A ? 1 : 0); */ prio.u32.hi = MIN(O,A); @@ -955,18 +954,18 @@ static pj_timestamp CALC_CHECK_PRIO(const pj_ice_sess *ice, } PJ_INLINE(int) CMP_CHECK_STATE(const pj_ice_sess_check *c1, - const pj_ice_sess_check *c2) + const pj_ice_sess_check *c2) { /* SUCCEEDED has higher state than FAILED */ if (c1->state == PJ_ICE_SESS_CHECK_STATE_SUCCEEDED && - c2->state == PJ_ICE_SESS_CHECK_STATE_FAILED) + c2->state == PJ_ICE_SESS_CHECK_STATE_FAILED) { - return 1; + return 1; } if (c2->state == PJ_ICE_SESS_CHECK_STATE_SUCCEEDED && - c1->state == PJ_ICE_SESS_CHECK_STATE_FAILED) + c1->state == PJ_ICE_SESS_CHECK_STATE_FAILED) { - return -1; + return -1; } /* Other state, just compare the state value */ @@ -975,7 +974,7 @@ PJ_INLINE(int) CMP_CHECK_STATE(const pj_ice_sess_check *c1, PJ_INLINE(int) CMP_CHECK_PRIO(const pj_ice_sess_check *c1, - const pj_ice_sess_check *c2) + const pj_ice_sess_check *c2) { return pj_cmp_timestamp(&c1->prio, &c2->prio); } @@ -983,8 +982,8 @@ PJ_INLINE(int) CMP_CHECK_PRIO(const pj_ice_sess_check *c1, #if PJ_LOG_MAX_LEVEL >= 4 static const char *dump_check(char *buffer, unsigned bufsize, - const pj_ice_sess_checklist *clist, - const pj_ice_sess_check *check) + const pj_ice_sess_checklist *clist, + const pj_ice_sess_check *check) { const pj_ice_sess_cand *lcand = check->lcand; const pj_ice_sess_cand *rcand = check->rcand; @@ -994,37 +993,37 @@ static const char *dump_check(char *buffer, unsigned bufsize, PJ_CHECK_STACK(); len = pj_ansi_snprintf(buffer, bufsize, - "%d: [%d] %s:%d-->%s:%d", - (int)GET_CHECK_ID(clist, check), - check->lcand->comp_id, - pj_sockaddr_print(&lcand->addr, laddr, - sizeof(laddr), 2), - pj_sockaddr_get_port(&lcand->addr), - pj_sockaddr_print(&rcand->addr, raddr, - sizeof(raddr), 2), - pj_sockaddr_get_port(&rcand->addr)); + "%d: [%d] %s:%d-->%s:%d", + (int)GET_CHECK_ID(clist, check), + check->lcand->comp_id, + pj_sockaddr_print(&lcand->addr, laddr, + sizeof(laddr), 2), + pj_sockaddr_get_port(&lcand->addr), + pj_sockaddr_print(&rcand->addr, raddr, + sizeof(raddr), 2), + pj_sockaddr_get_port(&rcand->addr)); if (len < 0) - len = 0; + len = 0; else if (len >= (int)bufsize) - len = bufsize - 1; + len = bufsize - 1; buffer[len] = '\0'; return buffer; } static void dump_checklist(const char *title, pj_ice_sess *ice, - const pj_ice_sess_checklist *clist) + const pj_ice_sess_checklist *clist) { unsigned i; LOG4((ice->obj_name, "%s", title)); for (i=0; icount; ++i) { - const pj_ice_sess_check *c = &clist->checks[i]; - LOG4((ice->obj_name, " %s (%s, state=%s)", - dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), clist, c), - (c->nominated ? "nominated" : "not nominated"), - check_state_name[c->state])); + const pj_ice_sess_check *c = &clist->checks[i]; + LOG4((ice->obj_name, " %s (%s, state=%s)", + dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), clist, c), + (c->nominated ? "nominated" : "not nominated"), + check_state_name[c->state])); } } @@ -1033,13 +1032,13 @@ static void dump_checklist(const char *title, pj_ice_sess *ice, #endif static void check_set_state(pj_ice_sess *ice, pj_ice_sess_check *check, - pj_ice_sess_check_state st, - pj_status_t err_code) + pj_ice_sess_check_state st, + pj_status_t err_code) { LOG5((ice->obj_name, "Check %s: state changed from %s to %s", - dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), &ice->clist, check), - check_state_name[check->state], - check_state_name[st])); + dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), &ice->clist, check), + check_state_name[check->state], + check_state_name[st])); /* Put the assert after printing log for debugging purpose */ // There is corner case, nomination (in non-aggressive ICE mode) may be @@ -1054,13 +1053,13 @@ static void check_set_state(pj_ice_sess *ice, pj_ice_sess_check *check, } static void clist_set_state(pj_ice_sess *ice, pj_ice_sess_checklist *clist, - pj_ice_sess_checklist_state st) + pj_ice_sess_checklist_state st) { if (clist->state != st) { - LOG5((ice->obj_name, "Checklist: state changed from %s to %s", - clist_state_name[clist->state], - clist_state_name[st])); - clist->state = st; + LOG5((ice->obj_name, "Checklist: state changed from %s to %s", + clist_state_name[clist->state], + clist_state_name[st])); + clist->state = st; } } @@ -1074,64 +1073,64 @@ static void sort_checklist(pj_ice_sess *ice, pj_ice_sess_checklist *clist) unsigned check_ptr_cnt = 0; for (i=0; icomp_cnt; ++i) { - if (ice->comp[i].valid_check) { - check_ptr[check_ptr_cnt++] = &ice->comp[i].valid_check; - } - if (ice->comp[i].nominated_check) { - check_ptr[check_ptr_cnt++] = &ice->comp[i].nominated_check; - } + if (ice->comp[i].valid_check) { + check_ptr[check_ptr_cnt++] = &ice->comp[i].valid_check; + } + if (ice->comp[i].nominated_check) { + check_ptr[check_ptr_cnt++] = &ice->comp[i].nominated_check; + } } pj_assert(clist->count > 0); for (i=0; icount-1; ++i) { - unsigned j, highest = i; - - for (j=i+1; jcount; ++j) { - int cmp_state = CMP_CHECK_STATE(&clist->checks[j], - &clist->checks[highest]); - if (cmp_state > 0 || - (cmp_state==0 && CMP_CHECK_PRIO(&clist->checks[j], - &clist->checks[highest]) > 0)) - { - highest = j; - } - } - - if (highest != i) { - pj_ice_sess_check tmp; - unsigned k; - - pj_memcpy(&tmp, &clist->checks[i], sizeof(pj_ice_sess_check)); - pj_memcpy(&clist->checks[i], &clist->checks[highest], - sizeof(pj_ice_sess_check)); - pj_memcpy(&clist->checks[highest], &tmp, - sizeof(pj_ice_sess_check)); - - /* Update valid and nominated check pointers, since we're moving - * around checks - */ - for (k=0; kchecks[highest]) - *check_ptr[k] = &clist->checks[i]; - else if (*check_ptr[k] == &clist->checks[i]) - *check_ptr[k] = &clist->checks[highest]; - } - } + unsigned j, highest = i; + + for (j=i+1; jcount; ++j) { + int cmp_state = CMP_CHECK_STATE(&clist->checks[j], + &clist->checks[highest]); + if (cmp_state > 0 || + (cmp_state==0 && CMP_CHECK_PRIO(&clist->checks[j], + &clist->checks[highest]) > 0)) + { + highest = j; + } + } + + if (highest != i) { + pj_ice_sess_check tmp; + unsigned k; + + pj_memcpy(&tmp, &clist->checks[i], sizeof(pj_ice_sess_check)); + pj_memcpy(&clist->checks[i], &clist->checks[highest], + sizeof(pj_ice_sess_check)); + pj_memcpy(&clist->checks[highest], &tmp, + sizeof(pj_ice_sess_check)); + + /* Update valid and nominated check pointers, since we're moving + * around checks + */ + for (k=0; kchecks[highest]) + *check_ptr[k] = &clist->checks[i]; + else if (*check_ptr[k] == &clist->checks[i]) + *check_ptr[k] = &clist->checks[highest]; + } + } } } /* Remove a check pair from checklist */ static void remove_check(pj_ice_sess *ice, pj_ice_sess_checklist *clist, - unsigned check_idx, - const char *reason) + unsigned check_idx, + const char *reason) { LOG5((ice->obj_name, "Check %s pruned (%s)", - dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), - clist, &clist->checks[check_idx]), - reason)); + dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), + clist, &clist->checks[check_idx]), + reason)); pj_array_erase(clist->checks, sizeof(clist->checks[0]), - clist->count, check_idx); + clist->count, check_idx); --clist->count; } @@ -1139,7 +1138,7 @@ static void remove_check(pj_ice_sess *ice, pj_ice_sess_checklist *clist, * is sorted. */ static pj_status_t prune_checklist(pj_ice_sess *ice, - pj_ice_sess_checklist *clist) + pj_ice_sess_checklist *clist) { unsigned i; @@ -1155,38 +1154,38 @@ static pj_status_t prune_checklist(pj_ice_sess *ice, */ /* First replace SRFLX candidates with their base */ for (i=0; icount; ++i) { - pj_ice_sess_cand *srflx = clist->checks[i].lcand; - - if (srflx->type == PJ_ICE_CAND_TYPE_SRFLX || - srflx->type == PJ_ICE_CAND_TYPE_PRFLX) - { - /* Find the base for this candidate */ - unsigned j; - for (j=0; jlcand_cnt; ++j) { - pj_ice_sess_cand *host = &ice->lcand[j]; - - if (host->type != PJ_ICE_CAND_TYPE_HOST) - continue; - - if (pj_sockaddr_cmp(&srflx->base_addr, &host->addr) == 0) { - /* Replace this SRFLX/PRFLX with its BASE */ - clist->checks[i].lcand = host; - break; - } - } - - if (j==ice->lcand_cnt) { - char baddr[PJ_INET6_ADDRSTRLEN]; - /* Host candidate not found this this srflx! */ - LOG4((ice->obj_name, - "Base candidate %s:%d not found for srflx candidate %d", - pj_sockaddr_print(&srflx->base_addr, baddr, - sizeof(baddr), 2), - pj_sockaddr_get_port(&srflx->base_addr), - GET_LCAND_ID(srflx))); - return PJNATH_EICENOHOSTCAND; - } - } + pj_ice_sess_cand *srflx = clist->checks[i].lcand; + + if (srflx->type == PJ_ICE_CAND_TYPE_SRFLX || + srflx->type == PJ_ICE_CAND_TYPE_PRFLX) + { + /* Find the base for this candidate */ + unsigned j; + for (j=0; jlcand_cnt; ++j) { + pj_ice_sess_cand *host = &ice->lcand[j]; + + if (host->type != PJ_ICE_CAND_TYPE_HOST) + continue; + + if (pj_sockaddr_cmp(&srflx->base_addr, &host->addr) == 0) { + /* Replace this SRFLX/PRFLX with its BASE */ + clist->checks[i].lcand = host; + break; + } + } + + if (j==ice->lcand_cnt) { + char baddr[PJ_INET6_ADDRSTRLEN]; + /* Host candidate not found this this srflx! */ + LOG4((ice->obj_name, + "Base candidate %s:%d not found for srflx candidate %d", + pj_sockaddr_print(&srflx->base_addr, baddr, + sizeof(baddr), 2), + pj_sockaddr_get_port(&srflx->base_addr), + GET_LCAND_ID(srflx))); + return PJNATH_EICENOHOSTCAND; + } + } } /* Next remove a pair if its local and remote candidates are identical @@ -1198,39 +1197,39 @@ static pj_status_t prune_checklist(pj_ice_sess *ice, * Remove host candidates if their base are the the same! */ for (i=0; icount; ++i) { - pj_ice_sess_cand *licand = clist->checks[i].lcand; - pj_ice_sess_cand *ricand = clist->checks[i].rcand; - unsigned j; - - for (j=i+1; jcount;) { - pj_ice_sess_cand *ljcand = clist->checks[j].lcand; - pj_ice_sess_cand *rjcand = clist->checks[j].rcand; - const char *reason = NULL; - - /* Only discard Frozen/Waiting checks */ - if (clist->checks[j].state != PJ_ICE_SESS_CHECK_STATE_FROZEN && - clist->checks[j].state != PJ_ICE_SESS_CHECK_STATE_WAITING) - { - ++j; - continue; - } - - if ((licand == ljcand) && (ricand == rjcand)) { - reason = "duplicate found"; - } else if ((rjcand == ricand) && - (pj_sockaddr_cmp(&ljcand->base_addr, - &licand->base_addr)==0)) - { - reason = "equal base"; - } - - if (reason != NULL) { - /* Found duplicate, remove it */ - remove_check(ice, clist, j, reason); - } else { - ++j; - } - } + pj_ice_sess_cand *licand = clist->checks[i].lcand; + pj_ice_sess_cand *ricand = clist->checks[i].rcand; + unsigned j; + + for (j=i+1; jcount;) { + pj_ice_sess_cand *ljcand = clist->checks[j].lcand; + pj_ice_sess_cand *rjcand = clist->checks[j].rcand; + const char *reason = NULL; + + /* Only discard Frozen/Waiting checks */ + if (clist->checks[j].state != PJ_ICE_SESS_CHECK_STATE_FROZEN && + clist->checks[j].state != PJ_ICE_SESS_CHECK_STATE_WAITING) + { + ++j; + continue; + } + + if ((licand == ljcand) && (ricand == rjcand)) { + reason = "duplicate found"; + } else if ((rjcand == ricand) && + (pj_sockaddr_cmp(&ljcand->base_addr, + &licand->base_addr)==0)) + { + reason = "equal base"; + } + + if (reason != NULL) { + /* Found duplicate, remove it */ + remove_check(ice, clist, j, reason); + } else { + ++j; + } + } } return PJ_SUCCESS; @@ -1249,49 +1248,49 @@ static void on_timer(pj_timer_heap_t *th, pj_timer_entry *te) te->id = TIMER_NONE; if (ice->is_destroying) { - /* Stray timer, could happen when destroy is invoked while callback - * is pending. */ - pj_grp_lock_release(ice->grp_lock); - return; + /* Stray timer, could happen when destroy is invoked while callback + * is pending. */ + pj_grp_lock_release(ice->grp_lock); + return; } switch (type) { case TIMER_CONTROLLED_WAIT_NOM: - LOG4((ice->obj_name, - "Controlled agent timed-out in waiting for the controlling " - "agent to send nominated check. Setting state to fail now..")); - on_ice_complete(ice, PJNATH_EICENOMTIMEOUT); - break; + LOG4((ice->obj_name, + "Controlled agent timed-out in waiting for the controlling " + "agent to send nominated check. Setting state to fail now..")); + on_ice_complete(ice, PJNATH_EICENOMTIMEOUT); + break; case TIMER_COMPLETION_CALLBACK: - { - void (*on_ice_complete)(pj_ice_sess *ice, pj_status_t status); - pj_status_t ice_status; - - /* Start keep-alive timer but don't send any packets yet. - * Need to do it here just in case app destroy the session - * in the callback. - */ - if (ice->ice_status == PJ_SUCCESS) - ice_keep_alive(ice, PJ_FALSE); - - /* Release mutex in case app destroy us in the callback */ - ice_status = ice->ice_status; - on_ice_complete = ice->cb.on_ice_complete; - - /* Notify app about ICE completion*/ - if (on_ice_complete) - (*on_ice_complete)(ice, ice_status); - } - break; + { + void (*on_ice_complete)(pj_ice_sess *ice, pj_status_t status); + pj_status_t ice_status; + + /* Start keep-alive timer but don't send any packets yet. + * Need to do it here just in case app destroy the session + * in the callback. + */ + if (ice->ice_status == PJ_SUCCESS) + ice_keep_alive(ice, PJ_FALSE); + + /* Release mutex in case app destroy us in the callback */ + ice_status = ice->ice_status; + on_ice_complete = ice->cb.on_ice_complete; + + /* Notify app about ICE completion*/ + if (on_ice_complete) + (*on_ice_complete)(ice, ice_status); + } + break; case TIMER_START_NOMINATED_CHECK: - start_nominated_check(ice); - break; + start_nominated_check(ice); + break; case TIMER_KEEP_ALIVE: - ice_keep_alive(ice, PJ_TRUE); - break; + ice_keep_alive(ice, PJ_TRUE); + break; case TIMER_NONE: - /* Nothing to do, just to get rid of gcc warning */ - break; + /* Nothing to do, just to get rid of gcc warning */ + break; } pj_grp_lock_release(ice->grp_lock); @@ -1301,66 +1300,66 @@ static void on_timer(pj_timer_heap_t *th, pj_timer_entry *te) static void ice_keep_alive(pj_ice_sess *ice, pj_bool_t send_now) { if (send_now) { - /* Send Binding Indication for the component */ - pj_ice_sess_comp *comp = &ice->comp[ice->comp_ka]; - pj_stun_tx_data *tdata; - pj_ice_sess_check *the_check; - pj_ice_msg_data *msg_data; - int addr_len; - pj_bool_t saved; - pj_status_t status; - - /* Must have nominated check by now */ - pj_assert(comp->nominated_check != NULL); - the_check = comp->nominated_check; - - /* Create the Binding Indication */ - status = pj_stun_session_create_ind(comp->stun_sess, - PJ_STUN_BINDING_INDICATION, - &tdata); - if (status != PJ_SUCCESS) - goto done; - - /* Need the transport_id */ - msg_data = PJ_POOL_ZALLOC_T(tdata->pool, pj_ice_msg_data); - msg_data->transport_id = the_check->lcand->transport_id; - - /* RFC 5245 Section 10: - * The Binding Indication SHOULD contain the FINGERPRINT attribute - * to aid in demultiplexing, but SHOULD NOT contain any other - * attributes. - */ - saved = pj_stun_session_use_fingerprint(comp->stun_sess, PJ_TRUE); - - /* Send to session */ - addr_len = pj_sockaddr_get_len(&the_check->rcand->addr); - status = pj_stun_session_send_msg(comp->stun_sess, msg_data, - PJ_FALSE, PJ_FALSE, - &the_check->rcand->addr, - addr_len, tdata); - - /* Restore FINGERPRINT usage */ - pj_stun_session_use_fingerprint(comp->stun_sess, saved); + /* Send Binding Indication for the component */ + pj_ice_sess_comp *comp = &ice->comp[ice->comp_ka]; + pj_stun_tx_data *tdata; + pj_ice_sess_check *the_check; + pj_ice_msg_data *msg_data; + int addr_len; + pj_bool_t saved; + pj_status_t status; + + /* Must have nominated check by now */ + pj_assert(comp->nominated_check != NULL); + the_check = comp->nominated_check; + + /* Create the Binding Indication */ + status = pj_stun_session_create_ind(comp->stun_sess, + PJ_STUN_BINDING_INDICATION, + &tdata); + if (status != PJ_SUCCESS) + goto done; + + /* Need the transport_id */ + msg_data = PJ_POOL_ZALLOC_T(tdata->pool, pj_ice_msg_data); + msg_data->transport_id = the_check->lcand->transport_id; + + /* RFC 5245 Section 10: + * The Binding Indication SHOULD contain the FINGERPRINT attribute + * to aid in demultiplexing, but SHOULD NOT contain any other + * attributes. + */ + saved = pj_stun_session_use_fingerprint(comp->stun_sess, PJ_TRUE); + + /* Send to session */ + addr_len = pj_sockaddr_get_len(&the_check->rcand->addr); + status = pj_stun_session_send_msg(comp->stun_sess, msg_data, + PJ_FALSE, PJ_FALSE, + &the_check->rcand->addr, + addr_len, tdata); + + /* Restore FINGERPRINT usage */ + pj_stun_session_use_fingerprint(comp->stun_sess, saved); done: - ice->comp_ka = (ice->comp_ka + 1) % ice->comp_cnt; + ice->comp_ka = (ice->comp_ka + 1) % ice->comp_cnt; } if (ice->timer.id == TIMER_NONE) { - pj_time_val delay = { 0, 0 }; + pj_time_val delay = { 0, 0 }; - delay.msec = (PJ_ICE_SESS_KEEP_ALIVE_MIN + - (pj_rand() % PJ_ICE_SESS_KEEP_ALIVE_MAX_RAND)) * 1000 / - ice->comp_cnt; - pj_time_val_normalize(&delay); + delay.msec = (PJ_ICE_SESS_KEEP_ALIVE_MIN + + (pj_rand() % PJ_ICE_SESS_KEEP_ALIVE_MAX_RAND)) * 1000 / + ice->comp_cnt; + pj_time_val_normalize(&delay); - pj_timer_heap_schedule_w_grp_lock(ice->stun_cfg.timer_heap, - &ice->timer, &delay, - TIMER_KEEP_ALIVE, - ice->grp_lock); + pj_timer_heap_schedule_w_grp_lock(ice->stun_cfg.timer_heap, + &ice->timer, &delay, + TIMER_KEEP_ALIVE, + ice->grp_lock); } else { - pj_assert(!"Not expected any timer active"); + pj_assert(!"Not expected any timer active"); } } @@ -1368,69 +1367,69 @@ static void ice_keep_alive(pj_ice_sess *ice, pj_bool_t send_now) static void on_ice_complete(pj_ice_sess *ice, pj_status_t status) { if (!ice->is_complete) { - ice->is_complete = PJ_TRUE; - ice->ice_status = status; + ice->is_complete = PJ_TRUE; + ice->ice_status = status; - pj_timer_heap_cancel_if_active(ice->stun_cfg.timer_heap, &ice->timer, - TIMER_NONE); + pj_timer_heap_cancel_if_active(ice->stun_cfg.timer_heap, &ice->timer, + TIMER_NONE); - /* Log message */ - LOG4((ice->obj_name, "ICE process complete, status=%s", - pj_strerror(status, ice->tmp.errmsg, - sizeof(ice->tmp.errmsg)).ptr)); + /* Log message */ + LOG4((ice->obj_name, "ICE process complete, status=%s", + pj_strerror(status, ice->tmp.errmsg, + sizeof(ice->tmp.errmsg)).ptr)); - dump_checklist("Valid list", ice, &ice->valid_list); + dump_checklist("Valid list", ice, &ice->valid_list); - /* Call callback */ - if (ice->cb.on_ice_complete) { - pj_time_val delay = {0, 0}; + /* Call callback */ + if (ice->cb.on_ice_complete) { + pj_time_val delay = {0, 0}; - pj_timer_heap_schedule_w_grp_lock(ice->stun_cfg.timer_heap, - &ice->timer, &delay, - TIMER_COMPLETION_CALLBACK, - ice->grp_lock); - } + pj_timer_heap_schedule_w_grp_lock(ice->stun_cfg.timer_heap, + &ice->timer, &delay, + TIMER_COMPLETION_CALLBACK, + ice->grp_lock); + } } } /* Update valid check and nominated check for the candidate */ static void update_comp_check(pj_ice_sess *ice, unsigned comp_id, - pj_ice_sess_check *check) + pj_ice_sess_check *check) { pj_ice_sess_comp *comp; comp = find_comp(ice, comp_id); if (comp->valid_check == NULL) { - comp->valid_check = check; + comp->valid_check = check; } else { - pj_bool_t update = PJ_FALSE; - - /* Update component's valid check with conditions: - * - it is the first nominated check, or - * - it has higher prio, as long as nomination status is NOT degraded - * (existing is nominated -> new is not-nominated). - */ - if (!comp->nominated_check && check->nominated) - { - update = PJ_TRUE; - } else if (CMP_CHECK_PRIO(comp->valid_check, check) < 0 && - (!comp->nominated_check || check->nominated)) - { - update = PJ_TRUE; - } - - if (update) - comp->valid_check = check; + pj_bool_t update = PJ_FALSE; + + /* Update component's valid check with conditions: + * - it is the first nominated check, or + * - it has higher prio, as long as nomination status is NOT degraded + * (existing is nominated -> new is not-nominated). + */ + if (!comp->nominated_check && check->nominated) + { + update = PJ_TRUE; + } else if (CMP_CHECK_PRIO(comp->valid_check, check) < 0 && + (!comp->nominated_check || check->nominated)) + { + update = PJ_TRUE; + } + + if (update) + comp->valid_check = check; } if (check->nominated) { - /* Update the nominated check for the component */ - if (comp->nominated_check == NULL) { - comp->nominated_check = check; - } else { - if (CMP_CHECK_PRIO(comp->nominated_check, check) < 0) - comp->nominated_check = check; - } + /* Update the nominated check for the component */ + if (comp->nominated_check == NULL) { + comp->nominated_check = check; + } else { + if (CMP_CHECK_PRIO(comp->nominated_check, check) < 0) + comp->nominated_check = check; + } } } @@ -1461,13 +1460,13 @@ static pj_bool_t check_ice_complete(pj_ice_sess *ice) * ICE processing as success, otherwise wait. */ for (i=0; icomp_cnt; ++i) { - if (ice->comp[i].nominated_check == NULL) - break; + if (ice->comp[i].nominated_check == NULL) + break; } if (i == ice->comp_cnt) { - /* All components have nominated pair */ - on_ice_complete(ice, PJ_SUCCESS); - return PJ_TRUE; + /* All components have nominated pair */ + on_ice_complete(ice, PJ_SUCCESS); + return PJ_TRUE; } /* Note: this is the stuffs that we don't do in 7.1.2.2.2, since our @@ -1498,98 +1497,98 @@ static pj_bool_t check_ice_complete(pj_ice_sess *ice) * then mark ICE processing as failed. */ if (!ice->is_trickling) { - for (i=0; iclist.count; ++i) { - pj_ice_sess_check *c = &ice->clist.checks[i]; - if (c->state < PJ_ICE_SESS_CHECK_STATE_SUCCEEDED) { - break; - } - } - no_pending_check = (i == ice->clist.count); + for (i=0; iclist.count; ++i) { + pj_ice_sess_check *c = &ice->clist.checks[i]; + if (c->state < PJ_ICE_SESS_CHECK_STATE_SUCCEEDED) { + break; + } + } + no_pending_check = (i == ice->clist.count); } if (no_pending_check) { - /* All checks have completed, but we don't have nominated pair. - * If agent's role is controlled, check if all components have - * valid pair. If it does, this means the controlled agent has - * finished the check list and it's waiting for controlling - * agent to send checks with USE-CANDIDATE flag set. - */ - if (ice->role == PJ_ICE_SESS_ROLE_CONTROLLED) { - for (i=0; i < ice->comp_cnt; ++i) { - if (ice->comp[i].valid_check == NULL) - break; - } - - if (i < ice->comp_cnt) { - /* This component ID doesn't have valid pair. - * Mark ICE as failed. - */ - on_ice_complete(ice, PJNATH_EICEFAILED); - return PJ_TRUE; - } else { - /* All components have a valid pair. - * We should wait until we receive nominated checks. - */ - if (ice->timer.id == TIMER_NONE && - ice->opt.controlled_agent_want_nom_timeout >= 0) - { - pj_time_val delay; - - delay.sec = 0; - delay.msec = ice->opt.controlled_agent_want_nom_timeout; - pj_time_val_normalize(&delay); - - pj_timer_heap_schedule_w_grp_lock( - ice->stun_cfg.timer_heap, - &ice->timer, &delay, - TIMER_CONTROLLED_WAIT_NOM, - ice->grp_lock); - - LOG5((ice->obj_name, - "All checks have completed. Controlled agent now " - "waits for nomination from controlling agent " - "(timeout=%d msec)", - ice->opt.controlled_agent_want_nom_timeout)); - } - return PJ_FALSE; - } - - /* Unreached */ - - } else if (ice->is_nominating) { - /* We are controlling agent and all checks have completed but - * there's at least one component without nominated pair (or - * more likely we don't have any nominated pairs at all). - */ - on_ice_complete(ice, PJNATH_EICEFAILED); - return PJ_TRUE; - - } else { - /* We are controlling agent and all checks have completed. If - * we have valid list for every component, then move on to - * sending nominated check, otherwise we have failed. - */ - for (i=0; icomp_cnt; ++i) { - if (ice->comp[i].valid_check == NULL) - break; - } - - if (i < ice->comp_cnt) { - /* At least one component doesn't have a valid check. Mark - * ICE as failed. - */ - on_ice_complete(ice, PJNATH_EICEFAILED); - return PJ_TRUE; - } - - /* Now it's time to send connectivity check with nomination - * flag set. - */ - LOG4((ice->obj_name, - "All checks have completed, starting nominated checks now")); - start_nominated_check(ice); - return PJ_FALSE; - } + /* All checks have completed, but we don't have nominated pair. + * If agent's role is controlled, check if all components have + * valid pair. If it does, this means the controlled agent has + * finished the check list and it's waiting for controlling + * agent to send checks with USE-CANDIDATE flag set. + */ + if (ice->role == PJ_ICE_SESS_ROLE_CONTROLLED) { + for (i=0; i < ice->comp_cnt; ++i) { + if (ice->comp[i].valid_check == NULL) + break; + } + + if (i < ice->comp_cnt) { + /* This component ID doesn't have valid pair. + * Mark ICE as failed. + */ + on_ice_complete(ice, PJNATH_EICEFAILED); + return PJ_TRUE; + } else { + /* All components have a valid pair. + * We should wait until we receive nominated checks. + */ + if (ice->timer.id == TIMER_NONE && + ice->opt.controlled_agent_want_nom_timeout >= 0) + { + pj_time_val delay; + + delay.sec = 0; + delay.msec = ice->opt.controlled_agent_want_nom_timeout; + pj_time_val_normalize(&delay); + + pj_timer_heap_schedule_w_grp_lock( + ice->stun_cfg.timer_heap, + &ice->timer, &delay, + TIMER_CONTROLLED_WAIT_NOM, + ice->grp_lock); + + LOG5((ice->obj_name, + "All checks have completed. Controlled agent now " + "waits for nomination from controlling agent " + "(timeout=%d msec)", + ice->opt.controlled_agent_want_nom_timeout)); + } + return PJ_FALSE; + } + + /* Unreached */ + + } else if (ice->is_nominating) { + /* We are controlling agent and all checks have completed but + * there's at least one component without nominated pair (or + * more likely we don't have any nominated pairs at all). + */ + on_ice_complete(ice, PJNATH_EICEFAILED); + return PJ_TRUE; + + } else { + /* We are controlling agent and all checks have completed. If + * we have valid list for every component, then move on to + * sending nominated check, otherwise we have failed. + */ + for (i=0; icomp_cnt; ++i) { + if (ice->comp[i].valid_check == NULL) + break; + } + + if (i < ice->comp_cnt) { + /* At least one component doesn't have a valid check. Mark + * ICE as failed. + */ + on_ice_complete(ice, PJNATH_EICEFAILED); + return PJ_TRUE; + } + + /* Now it's time to send connectivity check with nomination + * flag set. + */ + LOG4((ice->obj_name, + "All checks have completed, starting nominated checks now")); + start_nominated_check(ice); + return PJ_FALSE; + } } /* If this connectivity check has been successful, scan all components @@ -1598,43 +1597,43 @@ static pj_bool_t check_ice_complete(pj_ice_sess *ice) */ /* Always scan regardless the last connectivity check result */ if (/*check->err_code == PJ_SUCCESS && */ - ice->role==PJ_ICE_SESS_ROLE_CONTROLLING && - !ice->is_nominating && - ice->timer.id == TIMER_NONE) + ice->role==PJ_ICE_SESS_ROLE_CONTROLLING && + !ice->is_nominating && + ice->timer.id == TIMER_NONE) { - pj_time_val delay; + pj_time_val delay; - for (i=0; icomp_cnt; ++i) { - if (ice->comp[i].valid_check == NULL) - break; - } + for (i=0; icomp_cnt; ++i) { + if (ice->comp[i].valid_check == NULL) + break; + } - if (i < ice->comp_cnt) { - /* Some components still don't have valid pair, continue - * processing. - */ - return PJ_FALSE; - } + if (i < ice->comp_cnt) { + /* Some components still don't have valid pair, continue + * processing. + */ + return PJ_FALSE; + } - LOG4((ice->obj_name, - "Scheduling nominated check in %d ms", - ice->opt.nominated_check_delay)); + LOG4((ice->obj_name, + "Scheduling nominated check in %d ms", + ice->opt.nominated_check_delay)); - pj_timer_heap_cancel_if_active(ice->stun_cfg.timer_heap, &ice->timer, - TIMER_NONE); + pj_timer_heap_cancel_if_active(ice->stun_cfg.timer_heap, &ice->timer, + TIMER_NONE); - /* All components have valid pair. Let connectivity checks run for - * a little bit more time, then start our nominated check. - */ - delay.sec = 0; - delay.msec = ice->opt.nominated_check_delay; - pj_time_val_normalize(&delay); + /* All components have valid pair. Let connectivity checks run for + * a little bit more time, then start our nominated check. + */ + delay.sec = 0; + delay.msec = ice->opt.nominated_check_delay; + pj_time_val_normalize(&delay); - pj_timer_heap_schedule_w_grp_lock(ice->stun_cfg.timer_heap, - &ice->timer, &delay, - TIMER_START_NOMINATED_CHECK, - ice->grp_lock); - return PJ_FALSE; + pj_timer_heap_schedule_w_grp_lock(ice->stun_cfg.timer_heap, + &ice->timer, &delay, + TIMER_START_NOMINATED_CHECK, + ice->grp_lock); + return PJ_FALSE; } /* We still have checks to perform */ @@ -1643,7 +1642,7 @@ static pj_bool_t check_ice_complete(pj_ice_sess *ice) /* This function is called when one check completes */ static pj_bool_t on_check_complete(pj_ice_sess *ice, - pj_ice_sess_check *check) + pj_ice_sess_check *check) { pj_ice_sess_comp *comp; unsigned i; @@ -1666,27 +1665,27 @@ static pj_bool_t on_check_complete(pj_ice_sess *ice, */ if (check->err_code==PJ_SUCCESS) { - for (i=0; iclist.count; ++i) { - pj_ice_sess_check *c = &ice->clist.checks[i]; - if (c->foundation_idx == check->foundation_idx && - c->state == PJ_ICE_SESS_CHECK_STATE_FROZEN) - { - check_set_state(ice, c, PJ_ICE_SESS_CHECK_STATE_WAITING, 0); - } - } + for (i=0; iclist.count; ++i) { + pj_ice_sess_check *c = &ice->clist.checks[i]; + if (c->foundation_idx == check->foundation_idx && + c->state == PJ_ICE_SESS_CHECK_STATE_FROZEN) + { + check_set_state(ice, c, PJ_ICE_SESS_CHECK_STATE_WAITING, 0); + } + } - LOG5((ice->obj_name, "Check %d is successful%s", - GET_CHECK_ID(&ice->clist, check), - (check->nominated ? " and nominated" : ""))); + LOG5((ice->obj_name, "Check %d is successful%s", + GET_CHECK_ID(&ice->clist, check), + (check->nominated ? " and nominated" : ""))); - /* On the first valid pair, we call the callback, if present */ - if (ice->valid_pair_found == PJ_FALSE) { - ice->valid_pair_found = PJ_TRUE; + /* On the first valid pair, we call the callback, if present */ + if (ice->valid_pair_found == PJ_FALSE) { + ice->valid_pair_found = PJ_TRUE; - if (ice->cb.on_valid_pair) { - (*ice->cb.on_valid_pair)(ice); - } - } + if (ice->cb.on_valid_pair) { + (*ice->cb.on_valid_pair)(ice); + } + } } /* 8.2. Updating States @@ -1712,42 +1711,42 @@ static pj_bool_t on_check_complete(pj_ice_sess *ice, */ if (check->err_code==PJ_SUCCESS && check->nominated) { - for (i=0; iclist.count; ++i) { - - pj_ice_sess_check *c = &ice->clist.checks[i]; - - if (c->lcand->comp_id == check->lcand->comp_id) { - - if (c->state < PJ_ICE_SESS_CHECK_STATE_IN_PROGRESS) { - - /* Just fail Frozen/Waiting check */ - LOG5((ice->obj_name, - "Check %s to be failed because state is %s", - dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), - &ice->clist, c), - check_state_name[c->state])); - check_set_state(ice, c, PJ_ICE_SESS_CHECK_STATE_FAILED, - PJ_ECANCELLED); - - } else if (c->state == PJ_ICE_SESS_CHECK_STATE_IN_PROGRESS - && (PJ_ICE_CANCEL_ALL || - CMP_CHECK_PRIO(c, check) < 0)) { - - /* State is IN_PROGRESS, cancel transaction */ - if (c->tdata) { - LOG5((ice->obj_name, - "Cancelling check %s (In Progress)", - dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), - &ice->clist, c))); - pj_stun_session_cancel_req(comp->stun_sess, - c->tdata, PJ_FALSE, 0); - c->tdata = NULL; - check_set_state(ice, c, PJ_ICE_SESS_CHECK_STATE_FAILED, - PJ_ECANCELLED); - } - } - } - } + for (i=0; iclist.count; ++i) { + + pj_ice_sess_check *c = &ice->clist.checks[i]; + + if (c->lcand->comp_id == check->lcand->comp_id) { + + if (c->state < PJ_ICE_SESS_CHECK_STATE_IN_PROGRESS) { + + /* Just fail Frozen/Waiting check */ + LOG5((ice->obj_name, + "Check %s to be failed because state is %s", + dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), + &ice->clist, c), + check_state_name[c->state])); + check_set_state(ice, c, PJ_ICE_SESS_CHECK_STATE_FAILED, + PJ_ECANCELLED); + + } else if (c->state == PJ_ICE_SESS_CHECK_STATE_IN_PROGRESS + && (PJ_ICE_CANCEL_ALL || + CMP_CHECK_PRIO(c, check) < 0)) { + + /* State is IN_PROGRESS, cancel transaction */ + if (c->tdata) { + LOG5((ice->obj_name, + "Cancelling check %s (In Progress)", + dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), + &ice->clist, c))); + pj_stun_session_cancel_req(comp->stun_sess, + c->tdata, PJ_FALSE, 0); + c->tdata = NULL; + check_set_state(ice, c, PJ_ICE_SESS_CHECK_STATE_FAILED, + PJ_ECANCELLED); + } + } + } + } } return check_ice_complete(ice); @@ -1759,26 +1758,26 @@ static pj_bool_t on_check_complete(pj_ice_sess *ice, * to checklist. */ static int get_check_foundation_idx(pj_ice_sess *ice, - const pj_ice_sess_cand *lcand, - const pj_ice_sess_cand *rcand, - pj_bool_t add_if_not_found) + const pj_ice_sess_cand *lcand, + const pj_ice_sess_cand *rcand, + pj_bool_t add_if_not_found) { pj_ice_sess_checklist *clist = &ice->clist; char fnd_str[65]; unsigned i; pj_ansi_snprintf(fnd_str, sizeof(fnd_str), "%.*s|%.*s", - (int)lcand->foundation.slen, lcand->foundation.ptr, - (int)rcand->foundation.slen, rcand->foundation.ptr); + (int)lcand->foundation.slen, lcand->foundation.ptr, + (int)rcand->foundation.slen, rcand->foundation.ptr); for (i=0; ifoundation_cnt; ++i) { - if (pj_strcmp2(&clist->foundation[i], fnd_str) == 0) - return i; + if (pj_strcmp2(&clist->foundation[i], fnd_str) == 0) + return i; } if (add_if_not_found && clist->foundation_cnt < PJ_ICE_MAX_CHECKS) { - pj_strdup2(ice->pool, &clist->foundation[i], fnd_str); - ++clist->foundation_cnt; - return i; + pj_strdup2(ice->pool, &clist->foundation[i], fnd_str); + ++clist->foundation_cnt; + return i; } return -1; @@ -1788,25 +1787,25 @@ static int get_check_foundation_idx(pj_ice_sess *ice, * than prio_lower_than. */ static int discard_check(pj_ice_sess *ice, pj_ice_sess_checklist *clist, - const pj_timestamp *prio_lower_than) + const pj_timestamp *prio_lower_than) { /* Discard any Failed check */ unsigned k; for (k=0; k < clist->count; ++k) { - if (clist->checks[k].state==PJ_ICE_SESS_CHECK_STATE_FAILED) { - remove_check(ice, clist, k, "too many, drop Failed"); - return 1; - } + if (clist->checks[k].state==PJ_ICE_SESS_CHECK_STATE_FAILED) { + remove_check(ice, clist, k, "too many, drop Failed"); + return 1; + } } /* If none, discard the lowest prio */ /* Re-sort before discarding the last */ sort_checklist(ice, clist); if (!prio_lower_than || - pj_cmp_timestamp(&clist->checks[k-1].prio, prio_lower_than) < 0) + pj_cmp_timestamp(&clist->checks[k-1].prio, prio_lower_than) < 0) { - remove_check(ice, clist, k-1, "too many, drop low-prio"); - return 1; + remove_check(ice, clist, k-1, "too many, drop low-prio"); + return 1; } return 0; @@ -1815,7 +1814,7 @@ static int discard_check(pj_ice_sess *ice, pj_ice_sess_checklist *clist, /* Timer callback for end of candidate indication from remote */ static void end_of_cand_ind_timer(pj_timer_heap_t *th, - pj_timer_entry *te) + pj_timer_entry *te) { pj_ice_sess *ice = (pj_ice_sess*)te->user_data; PJ_UNUSED_ARG(th); @@ -1823,12 +1822,12 @@ static void end_of_cand_ind_timer(pj_timer_heap_t *th, pj_grp_lock_acquire(ice->grp_lock); if (ice->is_trickling && !ice->is_complete) { - LOG5((ice->obj_name, "End-of-candidate timer timeout, any future " - "remote candidate update will be ignored")); - ice->is_trickling = PJ_FALSE; + LOG5((ice->obj_name, "End-of-candidate timer timeout, any future " + "remote candidate update will be ignored")); + ice->is_trickling = PJ_FALSE; - /* ICE checks may have been completed/failed */ - check_ice_complete(ice); + /* ICE checks may have been completed/failed */ + check_ice_complete(ice); } pj_grp_lock_release(ice->grp_lock); @@ -1837,10 +1836,10 @@ static void end_of_cand_ind_timer(pj_timer_heap_t *th, /* Add remote candidates and create/update checklist */ static pj_status_t add_rcand_and_update_checklist( - pj_ice_sess *ice, - unsigned rem_cand_cnt, - const pj_ice_sess_cand rem_cand[], - pj_bool_t trickle_done) + pj_ice_sess *ice, + unsigned rem_cand_cnt, + const pj_ice_sess_cand rem_cand[], + pj_bool_t trickle_done) { pj_ice_sess_checklist *clist; unsigned i, j, new_pair = 0; @@ -1848,171 +1847,171 @@ static pj_status_t add_rcand_and_update_checklist( /* Save remote candidates */ for (i=0; ircand[ice->rcand_cnt]; - - /* Check component ID */ - if (rem_cand[i].comp_id==0 || rem_cand[i].comp_id > ice->comp_cnt) - { - continue; - } - - if (ice->opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED) { - /* Trickle ICE: - * Make sure that candidate has not been added - */ - for (j=0; jrcand_cnt; ++j) { - const pj_ice_sess_cand *c1 = &rem_cand[i]; - const pj_ice_sess_cand *c2 = &ice->rcand[j]; - if (c1->comp_id==c2->comp_id && c1->type==c2->type && - pj_sockaddr_cmp(&c1->addr, &c2->addr)==0) - { - break; - } - } - - /* Skip candidate, it has been added */ - if (j < ice->rcand_cnt) - continue; - } - - /* Available cand slot? */ - if (ice->rcand_cnt >= PJ_ICE_MAX_CAND) { - char tmp[PJ_INET6_ADDRSTRLEN + 10]; - PJ_PERROR(3,(ice->obj_name, PJ_ETOOMANY, - "Cannot add remote candidate %s", - pj_sockaddr_print(&rem_cand[i].addr, - tmp, sizeof(tmp), 3))); - continue; - } - - /* Add this candidate */ - pj_memcpy(cn, &rem_cand[i], sizeof(pj_ice_sess_cand)); - pj_strdup(ice->pool, &cn->foundation, &rem_cand[i].foundation); - cn->id = ice->rcand_cnt++; + pj_ice_sess_cand *cn = &ice->rcand[ice->rcand_cnt]; + + /* Check component ID */ + if (rem_cand[i].comp_id==0 || rem_cand[i].comp_id > ice->comp_cnt) + { + continue; + } + + if (ice->opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED) { + /* Trickle ICE: + * Make sure that candidate has not been added + */ + for (j=0; jrcand_cnt; ++j) { + const pj_ice_sess_cand *c1 = &rem_cand[i]; + const pj_ice_sess_cand *c2 = &ice->rcand[j]; + if (c1->comp_id==c2->comp_id && c1->type==c2->type && + pj_sockaddr_cmp(&c1->addr, &c2->addr)==0) + { + break; + } + } + + /* Skip candidate, it has been added */ + if (j < ice->rcand_cnt) + continue; + } + + /* Available cand slot? */ + if (ice->rcand_cnt >= PJ_ICE_MAX_CAND) { + char tmp[PJ_INET6_ADDRSTRLEN + 10]; + PJ_PERROR(3,(ice->obj_name, PJ_ETOOMANY, + "Cannot add remote candidate %s", + pj_sockaddr_print(&rem_cand[i].addr, + tmp, sizeof(tmp), 3))); + continue; + } + + /* Add this candidate */ + pj_memcpy(cn, &rem_cand[i], sizeof(pj_ice_sess_cand)); + pj_strdup(ice->pool, &cn->foundation, &rem_cand[i].foundation); + cn->id = ice->rcand_cnt++; } /* Generate checklist */ clist = &ice->clist; for (i=0; ilcand_cnt; ++i) { - /* First index of remote cand to be paired with this local cand */ - unsigned rstart = (i >= ice->lcand_paired)? 0 : ice->rcand_paired; - for (j=rstart; jrcand_cnt; ++j) { - - pj_ice_sess_cand *lcand = &ice->lcand[i]; - pj_ice_sess_cand *rcand = &ice->rcand[j]; - pj_ice_sess_check *chk = NULL; - - if (clist->count >= PJ_ICE_MAX_CHECKS) { - // Instead of returning PJ_ETOOMANY, discard Failed/low-prio. - // If this check is actually the lowest prio, just skip it. - //return PJ_ETOOMANY; - pj_timestamp max_prio = CALC_CHECK_PRIO(ice, lcand, rcand); - if (discard_check(ice, clist, &max_prio) == 0) - continue; - } - - /* A local candidate is paired with a remote candidate if - * and only if the two candidates have the same component ID - * and have the same IP address version. - */ - if ((lcand->comp_id != rcand->comp_id) || - (lcand->addr.addr.sa_family != rcand->addr.addr.sa_family)) - { - continue; - } + /* First index of remote cand to be paired with this local cand */ + unsigned rstart = (i >= ice->lcand_paired)? 0 : ice->rcand_paired; + for (j=rstart; jrcand_cnt; ++j) { + + pj_ice_sess_cand *lcand = &ice->lcand[i]; + pj_ice_sess_cand *rcand = &ice->rcand[j]; + pj_ice_sess_check *chk = NULL; + + if (clist->count >= PJ_ICE_MAX_CHECKS) { + // Instead of returning PJ_ETOOMANY, discard Failed/low-prio. + // If this check is actually the lowest prio, just skip it. + //return PJ_ETOOMANY; + pj_timestamp max_prio = CALC_CHECK_PRIO(ice, lcand, rcand); + if (discard_check(ice, clist, &max_prio) == 0) + continue; + } + + /* A local candidate is paired with a remote candidate if + * and only if the two candidates have the same component ID + * and have the same IP address version. + */ + if ((lcand->comp_id != rcand->comp_id) || + (lcand->addr.addr.sa_family != rcand->addr.addr.sa_family)) + { + continue; + } #if 0 - /* Trickle ICE: - * Make sure that pair has not been added to checklist - */ - // Should not happen, paired cands are already marked using - // lcand_paired & rcand_paired. - if (ice->opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED) { - unsigned k; - for (k=0; kcount; ++k) { - chk = &clist->checks[k]; - if (chk->lcand == lcand && chk->rcand == rcand) - break; - } - - /* Pair already exists */ - if (k < clist->count) - continue; - } + /* Trickle ICE: + * Make sure that pair has not been added to checklist + */ + // Should not happen, paired cands are already marked using + // lcand_paired & rcand_paired. + if (ice->opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED) { + unsigned k; + for (k=0; kcount; ++k) { + chk = &clist->checks[k]; + if (chk->lcand == lcand && chk->rcand == rcand) + break; + } + + /* Pair already exists */ + if (k < clist->count) + continue; + } #endif - /* Add the pair */ - chk = &clist->checks[clist->count]; - chk->lcand = lcand; - chk->rcand = rcand; - chk->prio = CALC_CHECK_PRIO(ice, lcand, rcand); - chk->state = PJ_ICE_SESS_CHECK_STATE_FROZEN; - chk->foundation_idx = get_check_foundation_idx(ice, lcand, rcand, - PJ_TRUE); - - /* Check if foundation cannot be added (e.g: list is full) */ - if (chk->foundation_idx < 0) - continue; - - /* Check if the check can be unfrozen */ - if (ice->is_trickling) { - unsigned k; - - /* For this foundation, unfreeze if this pair has the lowest - * comp ID, or the highest priority among existing pairs with - * same comp ID, or any other checks in Succeeded. - */ - for (k=0; kcount; ++k) { - if (clist->checks[k].foundation_idx != chk->foundation_idx) - continue; - - /* Unfreeze if there is already check in Succeeded */ - if (clist->checks[k].state==PJ_ICE_SESS_CHECK_STATE_SUCCEEDED) - { - k = clist->count; - break; - } - - /* Don't unfreeze if there is already check in Waiting or - * In Progress. - */ - if (clist->checks[k].state==PJ_ICE_SESS_CHECK_STATE_WAITING || - clist->checks[k].state==PJ_ICE_SESS_CHECK_STATE_IN_PROGRESS) - { - break; - } - - /* Don't unfreeze if this pair does not have the lowest - * comp ID. - */ - if (clist->checks[k].lcand->comp_id < lcand->comp_id) - break; - - /* Don't unfreeze if this pair has the lowest comp ID, but - * does not have the highest prio. - */ - if (clist->checks[k].lcand->comp_id == lcand->comp_id && - pj_cmp_timestamp(&clist->checks[k].prio, &chk->prio) > 0) - { - break; - } - } - - /* Unfreeze */ - if (k == clist->count) - check_set_state(ice, chk, PJ_ICE_SESS_CHECK_STATE_WAITING, 0); - } - - clist->count++; - new_pair++; - } + /* Add the pair */ + chk = &clist->checks[clist->count]; + chk->lcand = lcand; + chk->rcand = rcand; + chk->prio = CALC_CHECK_PRIO(ice, lcand, rcand); + chk->state = PJ_ICE_SESS_CHECK_STATE_FROZEN; + chk->foundation_idx = get_check_foundation_idx(ice, lcand, rcand, + PJ_TRUE); + + /* Check if foundation cannot be added (e.g: list is full) */ + if (chk->foundation_idx < 0) + continue; + + /* Check if the check can be unfrozen */ + if (ice->is_trickling) { + unsigned k; + + /* For this foundation, unfreeze if this pair has the lowest + * comp ID, or the highest priority among existing pairs with + * same comp ID, or any other checks in Succeeded. + */ + for (k=0; kcount; ++k) { + if (clist->checks[k].foundation_idx != chk->foundation_idx) + continue; + + /* Unfreeze if there is already check in Succeeded */ + if (clist->checks[k].state==PJ_ICE_SESS_CHECK_STATE_SUCCEEDED) + { + k = clist->count; + break; + } + + /* Don't unfreeze if there is already check in Waiting or + * In Progress. + */ + if (clist->checks[k].state==PJ_ICE_SESS_CHECK_STATE_WAITING || + clist->checks[k].state==PJ_ICE_SESS_CHECK_STATE_IN_PROGRESS) + { + break; + } + + /* Don't unfreeze if this pair does not have the lowest + * comp ID. + */ + if (clist->checks[k].lcand->comp_id < lcand->comp_id) + break; + + /* Don't unfreeze if this pair has the lowest comp ID, but + * does not have the highest prio. + */ + if (clist->checks[k].lcand->comp_id == lcand->comp_id && + pj_cmp_timestamp(&clist->checks[k].prio, &chk->prio) > 0) + { + break; + } + } + + /* Unfreeze */ + if (k == clist->count) + check_set_state(ice, chk, PJ_ICE_SESS_CHECK_STATE_WAITING, 0); + } + + clist->count++; + new_pair++; + } } /* This could happen if candidates have no matching address families */ if (clist->count==0 && trickle_done) { - LOG4((ice->obj_name, "Error: no checklist can be created")); - return PJ_ENOTFOUND; + LOG4((ice->obj_name, "Error: no checklist can be created")); + return PJ_ENOTFOUND; } /* Update paired candidate counts */ @@ -2020,69 +2019,69 @@ static pj_status_t add_rcand_and_update_checklist( ice->rcand_paired = ice->rcand_cnt; if (new_pair) { - /* Sort checklist based on priority */ - //dump_checklist("Checklist before sort:", ice, &ice->clist); - sort_checklist(ice, clist); + /* Sort checklist based on priority */ + //dump_checklist("Checklist before sort:", ice, &ice->clist); + sort_checklist(ice, clist); - /* Prune the checklist */ - //dump_checklist("Checklist before prune:", ice, &ice->clist); - status = prune_checklist(ice, clist); - if (status != PJ_SUCCESS) - return status; + /* Prune the checklist */ + //dump_checklist("Checklist before prune:", ice, &ice->clist); + status = prune_checklist(ice, clist); + if (status != PJ_SUCCESS) + return status; } /* Regular ICE or trickle ICE after end-of-candidates indication: * Disable our components which don't have matching component */ if (trickle_done) { - unsigned highest_comp = 0; + unsigned highest_comp = 0; - for (i=0; ircand_cnt; ++i) { - if (ice->rcand[i].comp_id > highest_comp) - highest_comp = ice->rcand[i].comp_id; - } + for (i=0; ircand_cnt; ++i) { + if (ice->rcand[i].comp_id > highest_comp) + highest_comp = ice->rcand[i].comp_id; + } - for (i=highest_comp; icomp_cnt; ++i) { - if (ice->comp[i].stun_sess) { - pj_stun_session_destroy(ice->comp[i].stun_sess); - pj_bzero(&ice->comp[i], sizeof(ice->comp[i])); - } - } - ice->comp_cnt = highest_comp; + for (i=highest_comp; icomp_cnt; ++i) { + if (ice->comp[i].stun_sess) { + pj_stun_session_destroy(ice->comp[i].stun_sess); + pj_bzero(&ice->comp[i], sizeof(ice->comp[i])); + } + } + ice->comp_cnt = highest_comp; - /* If using trickle ICE and end-of-candidate has been signalled, - * check for ICE nego completion. - */ - if (ice->opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED) - check_ice_complete(ice); + /* If using trickle ICE and end-of-candidate has been signalled, + * check for ICE nego completion. + */ + if (ice->opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED) + check_ice_complete(ice); } /* For trickle ICE: resume the periodic check, it may be halted when * there is no available check pair. */ if (ice->opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED && - clist->count > 0 && !ice->is_complete && - clist->state == PJ_ICE_SESS_CHECKLIST_ST_RUNNING) + clist->count > 0 && !ice->is_complete && + clist->state == PJ_ICE_SESS_CHECKLIST_ST_RUNNING) { - if (!pj_timer_entry_running(&clist->timer)) { - pj_time_val delay = {0, 0}; - status = pj_timer_heap_schedule_w_grp_lock( - ice->stun_cfg.timer_heap, - &clist->timer, &delay, - PJ_TRUE, - ice->grp_lock); - if (status == PJ_SUCCESS) { - LOG5((ice->obj_name, - "Trickle ICE resumes periodic check because " - "check pair is available")); - } - } + if (!pj_timer_entry_running(&clist->timer)) { + pj_time_val delay = {0, 0}; + status = pj_timer_heap_schedule_w_grp_lock( + ice->stun_cfg.timer_heap, + &clist->timer, &delay, + PJ_TRUE, + ice->grp_lock); + if (status == PJ_SUCCESS) { + LOG5((ice->obj_name, + "Trickle ICE resumes periodic check because " + "check pair is available")); + } + } } /* Stop the end-of-candidates indication timer if trickling is done */ if (trickle_done && pj_timer_entry_running(&ice->timer_end_of_cand)) { - pj_timer_heap_cancel_if_active(ice->stun_cfg.timer_heap, - &ice->timer_end_of_cand, 0); + pj_timer_heap_cancel_if_active(ice->stun_cfg.timer_heap, + &ice->timer_end_of_cand, 0); } return PJ_SUCCESS; @@ -2091,11 +2090,11 @@ static pj_status_t add_rcand_and_update_checklist( /* Create checklist by pairing local candidates with remote candidates */ PJ_DEF(pj_status_t) pj_ice_sess_create_check_list( - pj_ice_sess *ice, - const pj_str_t *rem_ufrag, - const pj_str_t *rem_passwd, - unsigned rem_cand_cnt, - const pj_ice_sess_cand rem_cand[]) + pj_ice_sess *ice, + const pj_str_t *rem_ufrag, + const pj_str_t *rem_passwd, + unsigned rem_cand_cnt, + const pj_ice_sess_cand rem_cand[]) { pj_ice_sess_checklist *clist; char buf[128]; @@ -2108,9 +2107,9 @@ PJ_DEF(pj_status_t) pj_ice_sess_create_check_list( pj_grp_lock_acquire(ice->grp_lock); if (ice->tx_ufrag.slen) { - /* Checklist has been created */ - pj_grp_lock_release(ice->grp_lock); - return PJ_SUCCESS; + /* Checklist has been created */ + pj_grp_lock_release(ice->grp_lock); + return PJ_SUCCESS; } /* Save credentials */ @@ -2145,15 +2144,15 @@ PJ_DEF(pj_status_t) pj_ice_sess_create_check_list( /* Build checklist only if both sides have candidates already */ if (ice->lcand_cnt > 0 && rem_cand_cnt > 0) { - status = add_rcand_and_update_checklist(ice, rem_cand_cnt, rem_cand, - !ice->is_trickling); - if (status != PJ_SUCCESS) { - pj_grp_lock_release(ice->grp_lock); - return status; - } + status = add_rcand_and_update_checklist(ice, rem_cand_cnt, rem_cand, + !ice->is_trickling); + if (status != PJ_SUCCESS) { + pj_grp_lock_release(ice->grp_lock); + return status; + } - /* Log checklist */ - dump_checklist("Checklist created:", ice, clist); + /* Log checklist */ + dump_checklist("Checklist created:", ice, clist); } pj_grp_lock_release(ice->grp_lock); @@ -2164,60 +2163,60 @@ PJ_DEF(pj_status_t) pj_ice_sess_create_check_list( /* Update checklist by pairing local candidates with remote candidates */ PJ_DEF(pj_status_t) pj_ice_sess_update_check_list( - pj_ice_sess *ice, - const pj_str_t *rem_ufrag, - const pj_str_t *rem_passwd, - unsigned rem_cand_cnt, - const pj_ice_sess_cand rem_cand[], - pj_bool_t trickle_done) + pj_ice_sess *ice, + const pj_str_t *rem_ufrag, + const pj_str_t *rem_passwd, + unsigned rem_cand_cnt, + const pj_ice_sess_cand rem_cand[], + pj_bool_t trickle_done) { pj_status_t status = PJ_SUCCESS; PJ_ASSERT_RETURN(ice && ((rem_cand_cnt==0) || - (rem_ufrag && rem_passwd && rem_cand)), - PJ_EINVAL); + (rem_ufrag && rem_passwd && rem_cand)), + PJ_EINVAL); pj_grp_lock_acquire(ice->grp_lock); /* Ignore if remote ufrag has not known yet */ if (ice->tx_ufrag.slen == 0) { - LOG5((ice->obj_name, - "Cannot update ICE checklist when remote ufrag is unknown")); - pj_grp_lock_release(ice->grp_lock); - return PJ_EINVALIDOP; + LOG5((ice->obj_name, + "Cannot update ICE checklist when remote ufrag is unknown")); + pj_grp_lock_release(ice->grp_lock); + return PJ_EINVALIDOP; } /* Ignore if trickle has been stopped (e.g: received end-of-candidate) */ if (!ice->is_trickling && rem_cand_cnt) { - LOG5((ice->obj_name, - "Ignored remote candidate update as ICE trickling has ended")); - pj_grp_lock_release(ice->grp_lock); - return PJ_SUCCESS; + LOG5((ice->obj_name, + "Ignored remote candidate update as ICE trickling has ended")); + pj_grp_lock_release(ice->grp_lock); + return PJ_SUCCESS; } /* Verify remote ufrag & passwd, if remote candidate specified */ if (rem_cand_cnt && (pj_strcmp(&ice->tx_ufrag, rem_ufrag) || - pj_strcmp(&ice->tx_pass, rem_passwd))) + pj_strcmp(&ice->tx_pass, rem_passwd))) { - LOG5((ice->obj_name, "Ignored remote candidate update due to remote " - "ufrag/pwd mismatch")); - rem_cand_cnt = 0; + LOG5((ice->obj_name, "Ignored remote candidate update due to remote " + "ufrag/pwd mismatch")); + rem_cand_cnt = 0; } if (status == PJ_SUCCESS) { - status = add_rcand_and_update_checklist(ice, rem_cand_cnt, rem_cand, - trickle_done); + status = add_rcand_and_update_checklist(ice, rem_cand_cnt, rem_cand, + trickle_done); } /* Log checklist */ if (status == PJ_SUCCESS) - dump_checklist("Checklist updated:", ice, &ice->clist); + dump_checklist("Checklist updated:", ice, &ice->clist); if (trickle_done && ice->is_trickling) { - LOG5((ice->obj_name, "Remote signalled end-of-candidates " - "and local candidates gathering completed, " - "will ignore any candidate update")); - ice->is_trickling = PJ_FALSE; + LOG5((ice->obj_name, "Remote signalled end-of-candidates " + "and local candidates gathering completed, " + "will ignore any candidate update")); + ice->is_trickling = PJ_FALSE; } pj_grp_lock_release(ice->grp_lock); @@ -2227,9 +2226,9 @@ PJ_DEF(pj_status_t) pj_ice_sess_update_check_list( /* Perform check on the specified candidate pair. */ static pj_status_t perform_check(pj_ice_sess *ice, - pj_ice_sess_checklist *clist, - unsigned check_id, - pj_bool_t nominate) + pj_ice_sess_checklist *clist, + unsigned check_id, + pj_bool_t nominate) { pj_ice_sess_comp *comp; pj_ice_msg_data *msg_data; @@ -2245,18 +2244,18 @@ static pj_status_t perform_check(pj_ice_sess *ice, comp = find_comp(ice, lcand->comp_id); LOG5((ice->obj_name, - "Sending connectivity check for check %s", - dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), clist, check))); + "Sending connectivity check for check %s", + dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), clist, check))); pj_log_push_indent(); /* Create request */ status = pj_stun_session_create_req(comp->stun_sess, - PJ_STUN_BINDING_REQUEST, PJ_STUN_MAGIC, - NULL, &check->tdata); + PJ_STUN_BINDING_REQUEST, PJ_STUN_MAGIC, + NULL, &check->tdata); if (status != PJ_SUCCESS) { - pjnath_perror(ice->obj_name, "Error creating STUN request", status); - pj_log_pop_indent(); - return status; + pjnath_perror(ice->obj_name, "Error creating STUN request", status); + pj_log_pop_indent(); + return status; } /* Attach data to be retrieved later when STUN request transaction @@ -2274,33 +2273,33 @@ static pj_status_t perform_check(pj_ice_sess *ice, /* Add PRIORITY */ #if PJNATH_ICE_PRIO_STD prio = CALC_CAND_PRIO(ice, PJ_ICE_CAND_TYPE_PRFLX, 65535 - lcand->id, - lcand->comp_id); + lcand->comp_id); #else prio = CALC_CAND_PRIO(ice, PJ_ICE_CAND_TYPE_PRFLX, - ((1 << PJ_ICE_LOCAL_PREF_BITS) - 1) - lcand->id, - lcand->comp_id); + ((1 << PJ_ICE_LOCAL_PREF_BITS) - 1) - lcand->id, + lcand->comp_id); #endif pj_stun_msg_add_uint_attr(check->tdata->pool, check->tdata->msg, - PJ_STUN_ATTR_PRIORITY, prio); + PJ_STUN_ATTR_PRIORITY, prio); /* Add USE-CANDIDATE and set this check to nominated. * Also add ICE-CONTROLLING or ICE-CONTROLLED */ if (ice->role == PJ_ICE_SESS_ROLE_CONTROLLING) { - if (nominate) { - pj_stun_msg_add_empty_attr(check->tdata->pool, check->tdata->msg, - PJ_STUN_ATTR_USE_CANDIDATE); - check->nominated = PJ_TRUE; - } + if (nominate) { + pj_stun_msg_add_empty_attr(check->tdata->pool, check->tdata->msg, + PJ_STUN_ATTR_USE_CANDIDATE); + check->nominated = PJ_TRUE; + } - pj_stun_msg_add_uint64_attr(check->tdata->pool, check->tdata->msg, - PJ_STUN_ATTR_ICE_CONTROLLING, - &ice->tie_breaker); + pj_stun_msg_add_uint64_attr(check->tdata->pool, check->tdata->msg, + PJ_STUN_ATTR_ICE_CONTROLLING, + &ice->tie_breaker); } else { - pj_stun_msg_add_uint64_attr(check->tdata->pool, check->tdata->msg, - PJ_STUN_ATTR_ICE_CONTROLLED, - &ice->tie_breaker); + pj_stun_msg_add_uint64_attr(check->tdata->pool, check->tdata->msg, + PJ_STUN_ATTR_ICE_CONTROLLED, + &ice->tie_breaker); } @@ -2310,18 +2309,18 @@ static pj_status_t perform_check(pj_ice_sess *ice, /* Initiate STUN transaction to send the request */ status = pj_stun_session_send_msg(comp->stun_sess, msg_data, PJ_FALSE, - PJ_TRUE, &rcand->addr, - pj_sockaddr_get_len(&rcand->addr), - check->tdata); + PJ_TRUE, &rcand->addr, + pj_sockaddr_get_len(&rcand->addr), + check->tdata); if (status != PJ_SUCCESS) { - check->tdata = NULL; - pjnath_perror(ice->obj_name, "Error sending STUN request", status); - pj_log_pop_indent(); - return status; + check->tdata = NULL; + pjnath_perror(ice->obj_name, "Error sending STUN request", status); + pj_log_pop_indent(); + return status; } check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_IN_PROGRESS, - PJ_SUCCESS); + PJ_SUCCESS); pj_log_pop_indent(); return PJ_SUCCESS; } @@ -2331,7 +2330,7 @@ static pj_status_t perform_check(pj_ice_sess *ice, * This callback is called by timer on every Ta (20msec by default) */ static pj_status_t start_periodic_check(pj_timer_heap_t *th, - pj_timer_entry *te) + pj_timer_entry *te) { timer_data *td; pj_ice_sess *ice; @@ -2346,8 +2345,8 @@ static pj_status_t start_periodic_check(pj_timer_heap_t *th, pj_grp_lock_acquire(ice->grp_lock); if (ice->is_destroying) { - pj_grp_lock_release(ice->grp_lock); - return PJ_SUCCESS; + pj_grp_lock_release(ice->grp_lock); + return PJ_SUCCESS; } /* Set timer ID to FALSE first */ @@ -2363,40 +2362,40 @@ static pj_status_t start_periodic_check(pj_timer_heap_t *th, * Waiting state. */ for (i=0; icount; ++i) { - pj_ice_sess_check *check = &clist->checks[i]; - - if (check->state == PJ_ICE_SESS_CHECK_STATE_WAITING) { - status = perform_check(ice, clist, i, ice->is_nominating); - if (status != PJ_SUCCESS) { - check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_FAILED, - status); - on_check_complete(ice, check); - } + pj_ice_sess_check *check = &clist->checks[i]; + + if (check->state == PJ_ICE_SESS_CHECK_STATE_WAITING) { + status = perform_check(ice, clist, i, ice->is_nominating); + if (status != PJ_SUCCESS) { + check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_FAILED, + status); + on_check_complete(ice, check); + } - ++start_count; - break; - } + ++start_count; + break; + } } /* If we don't have anything in Waiting state, perform check to * highest priority pair that is in Frozen state. */ if (start_count==0) { - for (i=0; icount; ++i) { - pj_ice_sess_check *check = &clist->checks[i]; - - if (check->state == PJ_ICE_SESS_CHECK_STATE_FROZEN) { - status = perform_check(ice, clist, i, ice->is_nominating); - if (status != PJ_SUCCESS) { - check_set_state(ice, check, - PJ_ICE_SESS_CHECK_STATE_FAILED, status); - on_check_complete(ice, check); - } - - ++start_count; - break; - } - } + for (i=0; icount; ++i) { + pj_ice_sess_check *check = &clist->checks[i]; + + if (check->state == PJ_ICE_SESS_CHECK_STATE_FROZEN) { + status = perform_check(ice, clist, i, ice->is_nominating); + if (status != PJ_SUCCESS) { + check_set_state(ice, check, + PJ_ICE_SESS_CHECK_STATE_FAILED, status); + on_check_complete(ice, check); + } + + ++start_count; + break; + } + } } /* Schedule next check for next candidate pair, unless there is no @@ -2404,11 +2403,11 @@ static pj_status_t start_periodic_check(pj_timer_heap_t *th, * checklist). */ if (start_count!=0) { - pj_time_val timeout = {0, PJ_ICE_TA_VAL}; + pj_time_val timeout = {0, PJ_ICE_TA_VAL}; - pj_time_val_normalize(&timeout); - pj_timer_heap_schedule_w_grp_lock(th, te, &timeout, PJ_TRUE, - ice->grp_lock); + pj_time_val_normalize(&timeout); + pj_timer_heap_schedule_w_grp_lock(th, te, &timeout, PJ_TRUE, + ice->grp_lock); } pj_grp_lock_release(ice->grp_lock); @@ -2431,38 +2430,38 @@ static void start_nominated_check(pj_ice_sess *ice) /* Stop trickling if not yet */ if (ice->is_trickling) { - ice->is_trickling = PJ_FALSE; - LOG5((ice->obj_name, "Trickling stopped as nomination started.")); + ice->is_trickling = PJ_FALSE; + LOG5((ice->obj_name, "Trickling stopped as nomination started.")); } /* Stop our timer if it's active */ if (ice->timer.id == TIMER_START_NOMINATED_CHECK) { - pj_timer_heap_cancel_if_active(ice->stun_cfg.timer_heap, &ice->timer, - TIMER_NONE); + pj_timer_heap_cancel_if_active(ice->stun_cfg.timer_heap, &ice->timer, + TIMER_NONE); } /* For each component, set the check state of valid check with * highest priority to Waiting (it should have Success state now). */ for (i=0; icomp_cnt; ++i) { - unsigned j; - const pj_ice_sess_check *vc = ice->comp[i].valid_check; - - pj_assert(ice->comp[i].nominated_check == NULL); - pj_assert(vc->err_code == PJ_SUCCESS); - - for (j=0; jclist.count; ++j) { - pj_ice_sess_check *c = &ice->clist.checks[j]; - if (c->lcand->transport_id == vc->lcand->transport_id && - c->rcand == vc->rcand) - { - pj_assert(c->err_code == PJ_SUCCESS); - c->state = PJ_ICE_SESS_CHECK_STATE_FROZEN; - check_set_state(ice, c, PJ_ICE_SESS_CHECK_STATE_WAITING, - PJ_SUCCESS); - break; - } - } + unsigned j; + const pj_ice_sess_check *vc = ice->comp[i].valid_check; + + pj_assert(ice->comp[i].nominated_check == NULL); + pj_assert(vc->err_code == PJ_SUCCESS); + + for (j=0; jclist.count; ++j) { + pj_ice_sess_check *c = &ice->clist.checks[j]; + if (c->lcand->transport_id == vc->lcand->transport_id && + c->rcand == vc->rcand) + { + pj_assert(c->err_code == PJ_SUCCESS); + c->state = PJ_ICE_SESS_CHECK_STATE_FROZEN; + check_set_state(ice, c, PJ_ICE_SESS_CHECK_STATE_WAITING, + PJ_SUCCESS); + break; + } + } } /* And (re)start the periodic check */ @@ -2475,7 +2474,7 @@ static void start_nominated_check(pj_ice_sess *ice) PJ_TRUE, ice->grp_lock); if (status == PJ_SUCCESS) { - LOG5((ice->obj_name, "Periodic timer rescheduled..")); + LOG5((ice->obj_name, "Periodic timer rescheduled..")); } ice->is_nominating = PJ_TRUE; @@ -2484,7 +2483,7 @@ static void start_nominated_check(pj_ice_sess *ice) /* Timer callback to perform periodic check */ static void periodic_timer(pj_timer_heap_t *th, - pj_timer_entry *te) + pj_timer_entry *te) { start_periodic_check(th, te); } @@ -2506,7 +2505,7 @@ PJ_DEF(pj_status_t) pj_ice_sess_start_check(pj_ice_sess *ice) /* Checklist must have been created */ if (ice->clist.count == 0 && !ice->is_trickling) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; /* Lock session */ pj_grp_lock_acquire(ice->grp_lock); @@ -2516,7 +2515,7 @@ PJ_DEF(pj_status_t) pj_ice_sess_start_check(pj_ice_sess *ice) /* If we are using aggressive nomination, set the is_nominating state */ if (ice->opt.aggressive) - ice->is_nominating = PJ_TRUE; + ice->is_nominating = PJ_TRUE; /* The agent examines the check list for the first media stream (a * media stream is the first media stream when it is described by @@ -2532,53 +2531,53 @@ PJ_DEF(pj_status_t) pj_ice_sess_start_check(pj_ice_sess *ice) clist = &ice->clist; for (i=0; i < clist->foundation_cnt; ++i) { - unsigned k; - pj_ice_sess_check *chk = NULL; - - for (k=0; k < clist->count; ++k) { - pj_ice_sess_check *c = &clist->checks[k]; - if (c->foundation_idx != (int)i || - c->state != PJ_ICE_SESS_CHECK_STATE_FROZEN) - { - continue; - } - - /* First pair of this foundation */ - if (chk == NULL) { - chk = c; - continue; - } - - /* Found the lowest comp ID so far */ - if (c->lcand->comp_id < chk->lcand->comp_id) { - chk = c; - continue; - } - - /* Found the lowest comp ID and the highest prio so far */ - if (c->lcand->comp_id == chk->lcand->comp_id && - pj_cmp_timestamp(&c->prio, &chk->prio) > 0) - { - chk = c; - continue; - } - } - - /* Unfreeze */ - if (chk) - check_set_state(ice, chk, PJ_ICE_SESS_CHECK_STATE_WAITING, 0); + unsigned k; + pj_ice_sess_check *chk = NULL; + + for (k=0; k < clist->count; ++k) { + pj_ice_sess_check *c = &clist->checks[k]; + if (c->foundation_idx != (int)i || + c->state != PJ_ICE_SESS_CHECK_STATE_FROZEN) + { + continue; + } + + /* First pair of this foundation */ + if (chk == NULL) { + chk = c; + continue; + } + + /* Found the lowest comp ID so far */ + if (c->lcand->comp_id < chk->lcand->comp_id) { + chk = c; + continue; + } + + /* Found the lowest comp ID and the highest prio so far */ + if (c->lcand->comp_id == chk->lcand->comp_id && + pj_cmp_timestamp(&c->prio, &chk->prio) > 0) + { + chk = c; + continue; + } + } + + /* Unfreeze */ + if (chk) + check_set_state(ice, chk, PJ_ICE_SESS_CHECK_STATE_WAITING, 0); } /* First, perform all pending triggered checks, simultaneously. */ rcheck = ice->early_check.next; while (rcheck != &ice->early_check) { - LOG4((ice->obj_name, - "Performing delayed triggerred check for component %d", - rcheck->comp_id)); - pj_log_push_indent(); - handle_incoming_check(ice, rcheck); - rcheck = rcheck->next; - pj_log_pop_indent(); + LOG4((ice->obj_name, + "Performing delayed triggerred check for component %d", + rcheck->comp_id)); + pj_log_push_indent(); + handle_incoming_check(ice, rcheck); + rcheck = rcheck->next; + pj_log_pop_indent(); } pj_list_init(&ice->early_check); @@ -2588,10 +2587,10 @@ PJ_DEF(pj_status_t) pj_ice_sess_start_check(pj_ice_sess *ice) * return start_periodic_check(ice->stun_cfg.timer_heap, &clist->timer); */ if (!pj_timer_entry_running(&clist->timer)) { - pj_time_val delay = {0, 0}; - status = pj_timer_heap_schedule_w_grp_lock(ice->stun_cfg.timer_heap, - &clist->timer, &delay, - PJ_TRUE, ice->grp_lock); + pj_time_val delay = {0, 0}; + status = pj_timer_heap_schedule_w_grp_lock(ice->stun_cfg.timer_heap, + &clist->timer, &delay, + PJ_TRUE, ice->grp_lock); } /* For trickle ICE, start timer for end-of-candidates indication from @@ -2599,18 +2598,18 @@ PJ_DEF(pj_status_t) pj_ice_sess_start_check(pj_ice_sess *ice) */ if (ice->is_trickling && !pj_timer_entry_running(&ice->timer_end_of_cand)) { - pj_time_val delay = {PJ_TRICKLE_ICE_END_OF_CAND_TIMEOUT, 0}; - pj_timer_entry_init(&ice->timer_end_of_cand, 0, ice, - &end_of_cand_ind_timer); - status = pj_timer_heap_schedule_w_grp_lock( - ice->stun_cfg.timer_heap, - &ice->timer_end_of_cand, - &delay, PJ_TRUE, - ice->grp_lock); - if (status != PJ_SUCCESS) { - LOG4((ice->obj_name, - "Failed to schedule end-of-candidate indication timer")); - } + pj_time_val delay = {PJ_TRICKLE_ICE_END_OF_CAND_TIMEOUT, 0}; + pj_timer_entry_init(&ice->timer_end_of_cand, 0, ice, + &end_of_cand_ind_timer); + status = pj_timer_heap_schedule_w_grp_lock( + ice->stun_cfg.timer_heap, + &ice->timer_end_of_cand, + &delay, PJ_TRUE, + ice->grp_lock); + if (status != PJ_SUCCESS) { + LOG4((ice->obj_name, + "Failed to schedule end-of-candidate indication timer")); + } } pj_grp_lock_release(ice->grp_lock); @@ -2625,11 +2624,11 @@ PJ_DEF(pj_status_t) pj_ice_sess_start_check(pj_ice_sess *ice) * STUN session also doesn't have a transport, remember?! */ static pj_status_t on_stun_send_msg(pj_stun_session *sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len) + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len) { stun_data *sd = (stun_data*) pj_stun_session_get_user_data(sess); pj_ice_sess *ice = sd->ice; @@ -2639,14 +2638,14 @@ static pj_status_t on_stun_send_msg(pj_stun_session *sess, pj_grp_lock_acquire(ice->grp_lock); if (ice->is_destroying) { - /* Stray retransmit timer that could happen while - * we're being destroyed */ - pj_grp_lock_release(ice->grp_lock); - return PJ_EINVALIDOP; + /* Stray retransmit timer that could happen while + * we're being destroyed */ + pj_grp_lock_release(ice->grp_lock); + return PJ_EINVALIDOP; } status = (*ice->cb.on_tx_pkt)(ice, sd->comp_id, msg_data->transport_id, - pkt, pkt_size, dst_addr, addr_len); + pkt, pkt_size, dst_addr, addr_len); pj_grp_lock_release(ice->grp_lock); return status; @@ -2655,12 +2654,12 @@ static pj_status_t on_stun_send_msg(pj_stun_session *sess, /* This callback is called when outgoing STUN request completed */ static void on_stun_request_complete(pj_stun_session *stun_sess, - pj_status_t status, - void *token, - pj_stun_tx_data *tdata, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + pj_status_t status, + void *token, + pj_stun_tx_data *tdata, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_ice_msg_data *msg_data = (pj_ice_msg_data*) token; pj_ice_sess *ice; @@ -2684,29 +2683,29 @@ static void on_stun_request_complete(pj_stun_session *stun_sess, pj_grp_lock_acquire(ice->grp_lock); if (ice->is_destroying) { - /* Not sure if this is possible but just in case */ - pj_grp_lock_release(ice->grp_lock); - return; + /* Not sure if this is possible but just in case */ + pj_grp_lock_release(ice->grp_lock); + return; } /* Verify check (check ID may change as trickle ICE re-sort the list */ if (tdata != check->tdata) { - /* Okay, it was re-sorted, lookup using lcand & rcand */ - for (i = 0; i < clist->count; ++i) { - if (clist->checks[i].lcand == msg_data->data.req.lcand && - clist->checks[i].rcand == msg_data->data.req.rcand) - { - check = &clist->checks[i]; - ckid = i; - break; - } - } - if (i == clist->count) { - /* The check may have been pruned (due to low prio) */ - check->tdata = NULL; - pj_grp_lock_release(ice->grp_lock); - return; - } + /* Okay, it was re-sorted, lookup using lcand & rcand */ + for (i = 0; i < clist->count; ++i) { + if (clist->checks[i].lcand == msg_data->data.req.lcand && + clist->checks[i].rcand == msg_data->data.req.rcand) + { + check = &clist->checks[i]; + ckid = i; + break; + } + } + if (i == clist->count) { + /* The check may have been pruned (due to low prio) */ + check->tdata = NULL; + pj_grp_lock_release(ice->grp_lock); + return; + } } /* Mark STUN transaction as complete */ @@ -2720,66 +2719,66 @@ static void on_stun_request_complete(pj_stun_session *stun_sess, lcand = NULL; if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - - if (status==PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_ROLE_CONFLICT)) { - - /* Role conclict response. - * - * 7.1.2.1. Failure Cases: - * - * If the request had contained the ICE-CONTROLLED attribute, - * the agent MUST switch to the controlling role if it has not - * already done so. If the request had contained the - * ICE-CONTROLLING attribute, the agent MUST switch to the - * controlled role if it has not already done so. Once it has - * switched, the agent MUST immediately retry the request with - * the ICE-CONTROLLING or ICE-CONTROLLED attribute reflecting - * its new role. - */ - pj_ice_sess_role new_role = PJ_ICE_SESS_ROLE_UNKNOWN; - pj_stun_msg *req = tdata->msg; - - if (pj_stun_msg_find_attr(req, PJ_STUN_ATTR_ICE_CONTROLLING, 0)) { - new_role = PJ_ICE_SESS_ROLE_CONTROLLED; - } else if (pj_stun_msg_find_attr(req, PJ_STUN_ATTR_ICE_CONTROLLED, - 0)) { - new_role = PJ_ICE_SESS_ROLE_CONTROLLING; - } else { - pj_assert(!"We should have put CONTROLLING/CONTROLLED attr!"); - new_role = PJ_ICE_SESS_ROLE_CONTROLLED; - } - - if (new_role != ice->role) { - LOG4((ice->obj_name, - "Changing role because of role conflict response")); - pj_ice_sess_change_role(ice, new_role); - } - - /* Resend request */ - LOG4((ice->obj_name, "Resending check because of role conflict")); - pj_log_push_indent(); - check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_WAITING, 0); - perform_check(ice, clist, ckid, - check->nominated || ice->is_nominating); - pj_log_pop_indent(); - pj_grp_lock_release(ice->grp_lock); - return; - } - - pj_strerror(status, errmsg, sizeof(errmsg)); - LOG4((ice->obj_name, - "Check %s%s: connectivity check FAILED: %s", - dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), - &ice->clist, check), - (check->nominated ? " (nominated)" : " (not nominated)"), - errmsg)); - pj_log_push_indent(); - check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_FAILED, status); - on_check_complete(ice, check); - pj_log_pop_indent(); - pj_grp_lock_release(ice->grp_lock); - return; + char errmsg[PJ_ERR_MSG_SIZE]; + + if (status==PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_ROLE_CONFLICT)) { + + /* Role conclict response. + * + * 7.1.2.1. Failure Cases: + * + * If the request had contained the ICE-CONTROLLED attribute, + * the agent MUST switch to the controlling role if it has not + * already done so. If the request had contained the + * ICE-CONTROLLING attribute, the agent MUST switch to the + * controlled role if it has not already done so. Once it has + * switched, the agent MUST immediately retry the request with + * the ICE-CONTROLLING or ICE-CONTROLLED attribute reflecting + * its new role. + */ + pj_ice_sess_role new_role = PJ_ICE_SESS_ROLE_UNKNOWN; + pj_stun_msg *req = tdata->msg; + + if (pj_stun_msg_find_attr(req, PJ_STUN_ATTR_ICE_CONTROLLING, 0)) { + new_role = PJ_ICE_SESS_ROLE_CONTROLLED; + } else if (pj_stun_msg_find_attr(req, PJ_STUN_ATTR_ICE_CONTROLLED, + 0)) { + new_role = PJ_ICE_SESS_ROLE_CONTROLLING; + } else { + pj_assert(!"We should have put CONTROLLING/CONTROLLED attr!"); + new_role = PJ_ICE_SESS_ROLE_CONTROLLED; + } + + if (new_role != ice->role) { + LOG4((ice->obj_name, + "Changing role because of role conflict response")); + pj_ice_sess_change_role(ice, new_role); + } + + /* Resend request */ + LOG4((ice->obj_name, "Resending check because of role conflict")); + pj_log_push_indent(); + check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_WAITING, 0); + perform_check(ice, clist, ckid, + check->nominated || ice->is_nominating); + pj_log_pop_indent(); + pj_grp_lock_release(ice->grp_lock); + return; + } + + pj_strerror(status, errmsg, sizeof(errmsg)); + LOG4((ice->obj_name, + "Check %s%s: connectivity check FAILED: %s", + dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), + &ice->clist, check), + (check->nominated ? " (nominated)" : " (not nominated)"), + errmsg)); + pj_log_push_indent(); + check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_FAILED, status); + on_check_complete(ice, check); + pj_log_pop_indent(); + pj_grp_lock_release(ice->grp_lock); + return; } @@ -2799,29 +2798,29 @@ static void on_stun_request_complete(pj_stun_session *stun_sess, * is synthesized from IPv4). */ pj_sockaddr synth_addr; - - status = pj_sockaddr_synthesize(pj_AF_INET6(), &synth_addr, - &check->rcand->addr); - if (status == PJ_SUCCESS && - pj_sockaddr_cmp(&synth_addr, src_addr) == 0) - { - source_addr = &check->rcand->addr; - } + + status = pj_sockaddr_synthesize(pj_AF_INET6(), &synth_addr, + &check->rcand->addr); + if (status == PJ_SUCCESS && + pj_sockaddr_cmp(&synth_addr, src_addr) == 0) + { + source_addr = &check->rcand->addr; + } } if (pj_sockaddr_cmp(&check->rcand->addr, source_addr) != 0) { - status = PJNATH_EICEINSRCADDR; - LOG4((ice->obj_name, - "Check %s%s: connectivity check FAILED: source address mismatch", - dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), - &ice->clist, check), - (check->nominated ? " (nominated)" : " (not nominated)"))); - pj_log_push_indent(); - check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_FAILED, status); - on_check_complete(ice, check); - pj_log_pop_indent(); - pj_grp_lock_release(ice->grp_lock); - return; + status = PJNATH_EICEINSRCADDR; + LOG4((ice->obj_name, + "Check %s%s: connectivity check FAILED: source address mismatch", + dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), + &ice->clist, check), + (check->nominated ? " (nominated)" : " (not nominated)"))); + pj_log_push_indent(); + check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_FAILED, status); + on_check_complete(ice, check); + pj_log_pop_indent(); + pj_grp_lock_release(ice->grp_lock); + return; } /* 7.1.2.2. Success Cases @@ -2841,84 +2840,84 @@ static void on_stun_request_complete(pj_stun_session *stun_sess, LOG4((ice->obj_name, - "Check %s%s: connectivity check SUCCESS", - dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), - &ice->clist, check), - (check->nominated ? " (nominated)" : " (not nominated)"))); + "Check %s%s: connectivity check SUCCESS", + dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), + &ice->clist, check), + (check->nominated ? " (nominated)" : " (not nominated)"))); /* Get the STUN XOR-MAPPED-ADDRESS attribute. */ xaddr = (pj_stun_xor_mapped_addr_attr*) - pj_stun_msg_find_attr(response, PJ_STUN_ATTR_XOR_MAPPED_ADDR,0); + pj_stun_msg_find_attr(response, PJ_STUN_ATTR_XOR_MAPPED_ADDR,0); if (!xaddr) { - check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_FAILED, - PJNATH_ESTUNNOMAPPEDADDR); - on_check_complete(ice, check); - pj_grp_lock_release(ice->grp_lock); - return; + check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_FAILED, + PJNATH_ESTUNNOMAPPEDADDR); + on_check_complete(ice, check); + pj_grp_lock_release(ice->grp_lock); + return; } /* Find local candidate that matches the XOR-MAPPED-ADDRESS */ pj_assert(lcand == NULL); for (i=0; ilcand_cnt; ++i) { - /* Ticket #1891: apply additional check as there may be a shared - * mapped address for different base/local addresses. - */ - if (pj_sockaddr_cmp(&xaddr->sockaddr, &ice->lcand[i].addr) == 0 && - pj_sockaddr_cmp(&check->lcand->base_addr, - &ice->lcand[i].base_addr) == 0) - { - /* Match */ - lcand = &ice->lcand[i]; + /* Ticket #1891: apply additional check as there may be a shared + * mapped address for different base/local addresses. + */ + if (pj_sockaddr_cmp(&xaddr->sockaddr, &ice->lcand[i].addr) == 0 && + pj_sockaddr_cmp(&check->lcand->base_addr, + &ice->lcand[i].base_addr) == 0) + { + /* Match */ + lcand = &ice->lcand[i]; #if 0 - // The following code tries to verify if the STUN request belongs - // to the correct ICE check (so if it doesn't, it will set current - // ICE check state to FAILED (why?) and try to find the correct - // check). However, ICE check verification has been added in - // the beginning of this function, so the following block should - // not be needed anymore. - - /* Verify lcand==check->lcand, this may happen when a STUN socket - * corresponds to multiple host candidates. - */ - if (lcand != check->lcand) { - unsigned j; - - pj_log_push_indent(); - LOG4((ice->obj_name, - "Check %s%s: local candidate mismatch", - dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), - &ice->clist, check), - (check->nominated ? " (nominated)" : " (not nominated)"))); - - - /* Local candidate does not belong to this check! Set current - * check state to Failed. - */ - check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_FAILED, - PJNATH_ESTUNNOMAPPEDADDR); - - /* Find the matching check */ - for (j = 0; j < clist->count; ++j) { - if (clist->checks[j].lcand == lcand && - clist->checks[j].rcand == check->rcand) - { - check = &clist->checks[j]; - break; - } - } - if (j == clist->count) { - on_check_complete(ice, check); - pj_log_pop_indent(); - pj_grp_lock_release(ice->grp_lock); - return; - } - - pj_log_pop_indent(); - } + // The following code tries to verify if the STUN request belongs + // to the correct ICE check (so if it doesn't, it will set current + // ICE check state to FAILED (why?) and try to find the correct + // check). However, ICE check verification has been added in + // the beginning of this function, so the following block should + // not be needed anymore. + + /* Verify lcand==check->lcand, this may happen when a STUN socket + * corresponds to multiple host candidates. + */ + if (lcand != check->lcand) { + unsigned j; + + pj_log_push_indent(); + LOG4((ice->obj_name, + "Check %s%s: local candidate mismatch", + dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), + &ice->clist, check), + (check->nominated ? " (nominated)" : " (not nominated)"))); + + + /* Local candidate does not belong to this check! Set current + * check state to Failed. + */ + check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_FAILED, + PJNATH_ESTUNNOMAPPEDADDR); + + /* Find the matching check */ + for (j = 0; j < clist->count; ++j) { + if (clist->checks[j].lcand == lcand && + clist->checks[j].rcand == check->rcand) + { + check = &clist->checks[j]; + break; + } + } + if (j == clist->count) { + on_check_complete(ice, check); + pj_log_pop_indent(); + pj_grp_lock_release(ice->grp_lock); + return; + } + + pj_log_pop_indent(); + } #endif - break; - } + break; + } } /* 7.1.2.2.1. Discovering Peer Reflexive Candidates @@ -2927,55 +2926,55 @@ static void on_stun_request_complete(pj_stun_session *stun_sess, * address represents a new candidate - a peer reflexive candidate. */ if (lcand == NULL) { - unsigned cand_id = ice->lcand_cnt; - pj_str_t foundation; + unsigned cand_id = ice->lcand_cnt; + pj_str_t foundation; - pj_ice_calc_foundation(ice->pool, &foundation, PJ_ICE_CAND_TYPE_PRFLX, - &check->lcand->base_addr); + pj_ice_calc_foundation(ice->pool, &foundation, PJ_ICE_CAND_TYPE_PRFLX, + &check->lcand->base_addr); - /* Still in 7.1.2.2.1. Discovering Peer Reflexive Candidates - * Its priority is set equal to the value of the PRIORITY attribute + /* Still in 7.1.2.2.1. Discovering Peer Reflexive Candidates + * Its priority is set equal to the value of the PRIORITY attribute * in the Binding Request. - * - * I think the priority calculated by add_cand() should be the same - * as the one calculated in perform_check(), so there's no need to - * get the priority from the PRIORITY attribute. - */ - - /* Add new peer reflexive candidate */ - status = pj_ice_sess_add_cand(ice, check->lcand->comp_id, - msg_data->transport_id, - PJ_ICE_CAND_TYPE_PRFLX, + * + * I think the priority calculated by add_cand() should be the same + * as the one calculated in perform_check(), so there's no need to + * get the priority from the PRIORITY attribute. + */ + + /* Add new peer reflexive candidate */ + status = pj_ice_sess_add_cand(ice, check->lcand->comp_id, + msg_data->transport_id, + PJ_ICE_CAND_TYPE_PRFLX, #if PJNATH_ICE_PRIO_STD - 65535 - (pj_uint16_t)ice->lcand_cnt, + 65535 - (pj_uint16_t)ice->lcand_cnt, #else - ((1 << PJ_ICE_LOCAL_PREF_BITS) - 1) - - ice->lcand_cnt, + ((1 << PJ_ICE_LOCAL_PREF_BITS) - 1) - + ice->lcand_cnt, #endif - &foundation, - &xaddr->sockaddr, - &check->lcand->base_addr, - &check->lcand->base_addr, - pj_sockaddr_get_len(&xaddr->sockaddr), - &cand_id); - // Note: for IPv6, pj_ice_sess_add_cand can return SUCCESS - // without adding any candidates if the candidate is - // deprecated (because the ICE MUST NOT fail) - // In this case, cand_id == ice->lcand_cnt will be true. - if (status != PJ_SUCCESS || cand_id == ice->lcand_cnt) { - if (cand_id == ice->lcand_cnt) { + &foundation, + &xaddr->sockaddr, + &check->lcand->base_addr, + &check->lcand->base_addr, + pj_sockaddr_get_len(&xaddr->sockaddr), + &cand_id); + // Note: for IPv6, pj_ice_sess_add_cand can return SUCCESS + // without adding any candidates if the candidate is + // deprecated (because the ICE MUST NOT fail) + // In this case, cand_id == ice->lcand_cnt will be true. + if (status != PJ_SUCCESS || cand_id == ice->lcand_cnt) { + if (cand_id == ice->lcand_cnt) { LOG4((ice->obj_name, "Cannot add any candidate, all IPv6 seems deprecated")); - } - check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_FAILED, - status); - on_check_complete(ice, check); - pj_grp_lock_release(ice->grp_lock); - return; - } + } + check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_FAILED, + status); + on_check_complete(ice, check); + pj_grp_lock_release(ice->grp_lock); + return; + } - /* Update local candidate */ - lcand = &ice->lcand[cand_id]; + /* Update local candidate */ + lcand = &ice->lcand[cand_id]; } /* 7.1.2.2.3. Constructing a Valid Pair @@ -2988,23 +2987,23 @@ static void on_stun_request_complete(pj_stun_session *stun_sess, * nominated flag */ for (i=0; ivalid_list.count; ++i) { - if (ice->valid_list.checks[i].lcand == lcand && - ice->valid_list.checks[i].rcand == check->rcand) - break; + if (ice->valid_list.checks[i].lcand == lcand && + ice->valid_list.checks[i].rcand == check->rcand) + break; } if (i==ice->valid_list.count) { - pj_assert(ice->valid_list.count < PJ_ICE_MAX_CHECKS); - new_check = &ice->valid_list.checks[ice->valid_list.count++]; - new_check->lcand = lcand; - new_check->rcand = check->rcand; - new_check->prio = CALC_CHECK_PRIO(ice, lcand, check->rcand); - new_check->state = PJ_ICE_SESS_CHECK_STATE_SUCCEEDED; - new_check->nominated = check->nominated; - new_check->err_code = PJ_SUCCESS; + pj_assert(ice->valid_list.count < PJ_ICE_MAX_CHECKS); + new_check = &ice->valid_list.checks[ice->valid_list.count++]; + new_check->lcand = lcand; + new_check->rcand = check->rcand; + new_check->prio = CALC_CHECK_PRIO(ice, lcand, check->rcand); + new_check->state = PJ_ICE_SESS_CHECK_STATE_SUCCEEDED; + new_check->nominated = check->nominated; + new_check->err_code = PJ_SUCCESS; } else { - new_check = &ice->valid_list.checks[i]; - ice->valid_list.checks[i].nominated = check->nominated; + new_check = &ice->valid_list.checks[i]; + ice->valid_list.checks[i].nominated = check->nominated; } /* Update valid check and nominated check for the component */ @@ -3022,15 +3021,15 @@ static void on_stun_request_complete(pj_stun_session *stun_sess, * other checks to change as well. */ check_set_state(ice, check, PJ_ICE_SESS_CHECK_STATE_SUCCEEDED, - PJ_SUCCESS); + PJ_SUCCESS); /* Perform 7.1.2.2.2. Updating Pair States. * This may terminate ICE processing. */ if (on_check_complete(ice, check)) { - /* ICE complete! */ - pj_grp_lock_release(ice->grp_lock); - return; + /* ICE complete! */ + pj_grp_lock_release(ice->grp_lock); + return; } pj_grp_lock_release(ice->grp_lock); @@ -3041,12 +3040,12 @@ static void on_stun_request_complete(pj_stun_session *stun_sess, * when it receives incoming request. */ static pj_status_t on_stun_rx_request(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_rx_data *rdata, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_rx_data *rdata, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { stun_data *sd; const pj_stun_msg *msg = rdata->msg; @@ -3066,10 +3065,10 @@ static pj_status_t on_stun_rx_request(pj_stun_session *sess, /* Reject any requests except Binding request */ if (msg->hdr.type != PJ_STUN_BINDING_REQUEST) { - pj_stun_session_respond(sess, rdata, PJ_STUN_SC_BAD_REQUEST, - NULL, token, PJ_TRUE, - src_addr, src_addr_len); - return PJ_SUCCESS; + pj_stun_session_respond(sess, rdata, PJ_STUN_SC_BAD_REQUEST, + NULL, token, PJ_TRUE, + src_addr, src_addr_len); + return PJ_SUCCESS; } @@ -3079,8 +3078,8 @@ static pj_status_t on_stun_rx_request(pj_stun_session *sess, pj_grp_lock_acquire(ice->grp_lock); if (ice->is_destroying) { - pj_grp_lock_release(ice->grp_lock); - return PJ_EINVALIDOP; + pj_grp_lock_release(ice->grp_lock); + return PJ_EINVALIDOP; } /* @@ -3093,24 +3092,24 @@ static pj_status_t on_stun_rx_request(pj_stun_session *sess, /* Get PRIORITY attribute */ prio_attr = (pj_stun_priority_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_PRIORITY, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_PRIORITY, 0); if (prio_attr == NULL) { - LOG5((ice->obj_name, "Received Binding request with no PRIORITY")); - pj_grp_lock_release(ice->grp_lock); - return PJ_SUCCESS; + LOG5((ice->obj_name, "Received Binding request with no PRIORITY")); + pj_grp_lock_release(ice->grp_lock); + return PJ_SUCCESS; } /* Get USE-CANDIDATE attribute */ uc_attr = (pj_stun_use_candidate_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_USE_CANDIDATE, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_USE_CANDIDATE, 0); /* Get ICE-CONTROLLING or ICE-CONTROLLED */ role_attr = (pj_stun_uint64_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_ICE_CONTROLLING, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_ICE_CONTROLLING, 0); if (role_attr == NULL) { - role_attr = (pj_stun_uint64_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_ICE_CONTROLLED, 0); + role_attr = (pj_stun_uint64_attr*) + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_ICE_CONTROLLED, 0); } /* Handle the case when request comes before SDP answer is received. @@ -3118,49 +3117,49 @@ static pj_status_t on_stun_rx_request(pj_stun_session *sess, * got the SDP answer, copy the username from the request. */ if (ice->tx_ufrag.slen == 0) { - pj_stun_string_attr *uname_attr; + pj_stun_string_attr *uname_attr; - uname_attr = (pj_stun_string_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_USERNAME, 0); - pj_assert(uname_attr != NULL); - pj_strdup(ice->pool, &ice->rx_uname, &uname_attr->value); + uname_attr = (pj_stun_string_attr*) + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_USERNAME, 0); + pj_assert(uname_attr != NULL); + pj_strdup(ice->pool, &ice->rx_uname, &uname_attr->value); } /* 7.2.1.1. Detecting and Repairing Role Conflicts */ if (ice->role == PJ_ICE_SESS_ROLE_CONTROLLING && - role_attr && role_attr->hdr.type == PJ_STUN_ATTR_ICE_CONTROLLING) + role_attr && role_attr->hdr.type == PJ_STUN_ATTR_ICE_CONTROLLING) { - if (pj_cmp_timestamp(&ice->tie_breaker, &role_attr->value) < 0) { - /* Switch role to controlled */ - LOG4((ice->obj_name, - "Changing role because of ICE-CONTROLLING attribute")); - pj_ice_sess_change_role(ice, PJ_ICE_SESS_ROLE_CONTROLLED); - } else { - /* Generate 487 response */ - pj_stun_session_respond(sess, rdata, PJ_STUN_SC_ROLE_CONFLICT, - NULL, token, PJ_TRUE, - src_addr, src_addr_len); - pj_grp_lock_release(ice->grp_lock); - return PJ_SUCCESS; - } + if (pj_cmp_timestamp(&ice->tie_breaker, &role_attr->value) < 0) { + /* Switch role to controlled */ + LOG4((ice->obj_name, + "Changing role because of ICE-CONTROLLING attribute")); + pj_ice_sess_change_role(ice, PJ_ICE_SESS_ROLE_CONTROLLED); + } else { + /* Generate 487 response */ + pj_stun_session_respond(sess, rdata, PJ_STUN_SC_ROLE_CONFLICT, + NULL, token, PJ_TRUE, + src_addr, src_addr_len); + pj_grp_lock_release(ice->grp_lock); + return PJ_SUCCESS; + } } else if (ice->role == PJ_ICE_SESS_ROLE_CONTROLLED && - role_attr && role_attr->hdr.type == PJ_STUN_ATTR_ICE_CONTROLLED) + role_attr && role_attr->hdr.type == PJ_STUN_ATTR_ICE_CONTROLLED) { - if (pj_cmp_timestamp(&ice->tie_breaker, &role_attr->value) < 0) { - /* Generate 487 response */ - pj_stun_session_respond(sess, rdata, PJ_STUN_SC_ROLE_CONFLICT, - NULL, token, PJ_TRUE, - src_addr, src_addr_len); - pj_grp_lock_release(ice->grp_lock); - return PJ_SUCCESS; - } else { - /* Switch role to controlled */ - LOG4((ice->obj_name, - "Changing role because of ICE-CONTROLLED attribute")); - pj_ice_sess_change_role(ice, PJ_ICE_SESS_ROLE_CONTROLLING); - } + if (pj_cmp_timestamp(&ice->tie_breaker, &role_attr->value) < 0) { + /* Generate 487 response */ + pj_stun_session_respond(sess, rdata, PJ_STUN_SC_ROLE_CONFLICT, + NULL, token, PJ_TRUE, + src_addr, src_addr_len); + pj_grp_lock_release(ice->grp_lock); + return PJ_SUCCESS; + } else { + /* Switch role to controlled */ + LOG4((ice->obj_name, + "Changing role because of ICE-CONTROLLED attribute")); + pj_ice_sess_change_role(ice, PJ_ICE_SESS_ROLE_CONTROLLING); + } } /* @@ -3168,8 +3167,8 @@ static pj_status_t on_stun_rx_request(pj_stun_session *sess, */ status = pj_stun_session_create_res(sess, rdata, 0, NULL, &tdata); if (status != PJ_SUCCESS) { - pj_grp_lock_release(ice->grp_lock); - return status; + pj_grp_lock_release(ice->grp_lock); + return status; } if (((pj_sockaddr *)src_addr)->addr.sa_family == pj_AF_INET6()) { @@ -3177,38 +3176,38 @@ static pj_status_t on_stun_rx_request(pj_stun_session *sess, unsigned transport_id = ((pj_ice_msg_data*)token)->transport_id; pj_ice_sess_cand *lcand = NULL; - for (i = 0; i < ice->clist.count; ++i) { - pj_ice_sess_check *c = &ice->clist.checks[i]; - if (c->lcand->comp_id == sd->comp_id && - c->lcand->transport_id == transport_id) - { - lcand = c->lcand; - break; - } - } - - if (lcand != NULL && lcand->addr.addr.sa_family == pj_AF_INET()) { - /* We are behind NAT64, so src_addr is a synthesized IPv6 - * address. Instead of putting this synth IPv6 address as + for (i = 0; i < ice->clist.count; ++i) { + pj_ice_sess_check *c = &ice->clist.checks[i]; + if (c->lcand->comp_id == sd->comp_id && + c->lcand->transport_id == transport_id) + { + lcand = c->lcand; + break; + } + } + + if (lcand != NULL && lcand->addr.addr.sa_family == pj_AF_INET()) { + /* We are behind NAT64, so src_addr is a synthesized IPv6 + * address. Instead of putting this synth IPv6 address as * the XOR-MAPPED-ADDRESS, we need to find its original * IPv4 address. */ for (i = 0; i < ice->rcand_cnt; ++i) { - pj_sockaddr synth_addr; + pj_sockaddr synth_addr; - if (ice->rcand[i].addr.addr.sa_family != pj_AF_INET()) + if (ice->rcand[i].addr.addr.sa_family != pj_AF_INET()) continue; - status = pj_sockaddr_synthesize(pj_AF_INET6(), &synth_addr, - &ice->rcand[i].addr); - if (status == PJ_SUCCESS && - pj_sockaddr_cmp(src_addr, &synth_addr) == 0) - { - /* We find the original IPv4 address. */ - source_addr = &ice->rcand[i].addr; - source_addr_len = pj_sockaddr_get_len(source_addr); - break; - } + status = pj_sockaddr_synthesize(pj_AF_INET6(), &synth_addr, + &ice->rcand[i].addr); + if (status == PJ_SUCCESS && + pj_sockaddr_cmp(src_addr, &synth_addr) == 0) + { + /* We find the original IPv4 address. */ + source_addr = &ice->rcand[i].addr; + source_addr_len = pj_sockaddr_get_len(source_addr); + break; + } } } } @@ -3216,9 +3215,9 @@ static pj_status_t on_stun_rx_request(pj_stun_session *sess, /* Add XOR-MAPPED-ADDRESS attribute */ status = pj_stun_msg_add_sockaddr_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_XOR_MAPPED_ADDR, - PJ_TRUE, source_addr, - source_addr_len); + PJ_STUN_ATTR_XOR_MAPPED_ADDR, + PJ_TRUE, source_addr, + source_addr_len); /* Create a msg_data to be associated with this response */ msg_data = PJ_POOL_ZALLOC_T(tdata->pool, pj_ice_msg_data); @@ -3227,7 +3226,7 @@ static pj_status_t on_stun_rx_request(pj_stun_session *sess, /* Send the response */ status = pj_stun_session_send_msg(sess, msg_data, PJ_TRUE, PJ_TRUE, - src_addr, src_addr_len, tdata); + src_addr, src_addr_len, tdata); /* @@ -3239,9 +3238,9 @@ static pj_status_t on_stun_rx_request(pj_stun_session *sess, * triggered check array to be acted upon later. */ if (ice->tx_ufrag.slen == 0) { - rcheck = PJ_POOL_ZALLOC_T(ice->pool, pj_ice_rx_check); + rcheck = PJ_POOL_ZALLOC_T(ice->pool, pj_ice_rx_check); } else { - rcheck = &tmp_rcheck; + rcheck = &tmp_rcheck; } /* Init rcheck */ @@ -3254,13 +3253,13 @@ static pj_status_t on_stun_rx_request(pj_stun_session *sess, rcheck->role_attr = role_attr; if (ice->tx_ufrag.slen == 0) { - /* We don't have answer yet, so keep this request for later */ - LOG4((ice->obj_name, "Received an early check for comp %d", - rcheck->comp_id)); - pj_list_push_back(&ice->early_check, rcheck); + /* We don't have answer yet, so keep this request for later */ + LOG4((ice->obj_name, "Received an early check for comp %d", + rcheck->comp_id)); + pj_list_push_back(&ice->early_check, rcheck); } else { - /* Handle this check */ - handle_incoming_check(ice, rcheck); + /* Handle this check */ + handle_incoming_check(ice, rcheck); } pj_grp_lock_release(ice->grp_lock); @@ -3273,7 +3272,7 @@ static pj_status_t on_stun_rx_request(pj_stun_session *sess, * SDP answer is received and we have received early checks. */ static void handle_incoming_check(pj_ice_sess *ice, - const pj_ice_rx_check *rcheck) + const pj_ice_rx_check *rcheck) { pj_ice_sess_comp *comp; pj_ice_sess_cand *lcand = NULL; @@ -3286,8 +3285,8 @@ static void handle_incoming_check(pj_ice_sess *ice, * the request. */ for (i=0; ircand_cnt; ++i) { - if (pj_sockaddr_cmp(&rcheck->src_addr, &ice->rcand[i].addr)==0) - break; + if (pj_sockaddr_cmp(&rcheck->src_addr, &ice->rcand[i].addr)==0) + break; } /* 7.2.1.3. Learning Peer Reflexive Candidates @@ -3296,35 +3295,35 @@ static void handle_incoming_check(pj_ice_sess *ice, * candidate. */ if (i == ice->rcand_cnt) { - char raddr[PJ_INET6_ADDRSTRLEN]; - void *p; - - if (ice->rcand_cnt >= PJ_ICE_MAX_CAND) { - LOG4((ice->obj_name, - "Unable to add new peer reflexive candidate: too many " - "candidates already (%d)", PJ_ICE_MAX_CAND)); - return; - } - - rcand = &ice->rcand[ice->rcand_cnt++]; - rcand->comp_id = (pj_uint8_t)rcheck->comp_id; - rcand->type = PJ_ICE_CAND_TYPE_PRFLX; - rcand->prio = rcheck->priority; - pj_sockaddr_cp(&rcand->addr, &rcheck->src_addr); - - /* Foundation is random, unique from other foundation */ - rcand->foundation.ptr = p = (char*) pj_pool_alloc(ice->pool, 36); - rcand->foundation.slen = pj_ansi_snprintf(rcand->foundation.ptr, 36, - "f%p", p); - - LOG4((ice->obj_name, - "Added new remote candidate from the request: %s:%d", - pj_sockaddr_print(&rcand->addr, raddr, sizeof(raddr), 2), - pj_sockaddr_get_port(&rcand->addr))); + char raddr[PJ_INET6_ADDRSTRLEN]; + void *p; + + if (ice->rcand_cnt >= PJ_ICE_MAX_CAND) { + LOG4((ice->obj_name, + "Unable to add new peer reflexive candidate: too many " + "candidates already (%d)", PJ_ICE_MAX_CAND)); + return; + } + + rcand = &ice->rcand[ice->rcand_cnt++]; + rcand->comp_id = (pj_uint8_t)rcheck->comp_id; + rcand->type = PJ_ICE_CAND_TYPE_PRFLX; + rcand->prio = rcheck->priority; + pj_sockaddr_cp(&rcand->addr, &rcheck->src_addr); + + /* Foundation is random, unique from other foundation */ + rcand->foundation.ptr = p = (char*) pj_pool_alloc(ice->pool, 36); + rcand->foundation.slen = pj_ansi_snprintf(rcand->foundation.ptr, 36, + "f%p", p); + + LOG4((ice->obj_name, + "Added new remote candidate from the request: %s:%d", + pj_sockaddr_print(&rcand->addr, raddr, sizeof(raddr), 2), + pj_sockaddr_get_port(&rcand->addr))); } else { - /* Remote candidate found */ - rcand = &ice->rcand[i]; + /* Remote candidate found */ + rcand = &ice->rcand[i]; } #if 0 @@ -3335,34 +3334,34 @@ static void handle_incoming_check(pj_ice_sess *ice, * and we will end up creating a new check unnecessarily. */ for (i=0; iclist.count; ++i) { - pj_ice_sess_check *c = &ice->clist.checks[i]; - if (/*c->lcand == lcand ||*/ - pj_sockaddr_cmp(&c->lcand->base_addr, &lcand->base_addr)==0) - { - lcand = c->lcand; - break; - } + pj_ice_sess_check *c = &ice->clist.checks[i]; + if (/*c->lcand == lcand ||*/ + pj_sockaddr_cmp(&c->lcand->base_addr, &lcand->base_addr)==0) + { + lcand = c->lcand; + break; + } } #else /* Just get candidate with the highest priority and same transport ID * for the specified component ID in the checklist. */ for (i=0; iclist.count; ++i) { - pj_ice_sess_check *c = &ice->clist.checks[i]; - if (c->lcand->comp_id == rcheck->comp_id && - c->lcand->transport_id == rcheck->transport_id) - { - lcand = c->lcand; - break; - } + pj_ice_sess_check *c = &ice->clist.checks[i]; + if (c->lcand->comp_id == rcheck->comp_id && + c->lcand->transport_id == rcheck->transport_id) + { + lcand = c->lcand; + break; + } } if (lcand == NULL) { - /* Should not happen, but just in case remote is sending a - * Binding request for a component which it doesn't have. - */ - LOG4((ice->obj_name, - "Received Binding request but no local candidate is found!")); - return; + /* Should not happen, but just in case remote is sending a + * Binding request for a component which it doesn't have. + */ + LOG4((ice->obj_name, + "Received Binding request but no local candidate is found!")); + return; } #endif @@ -3377,9 +3376,9 @@ static void handle_incoming_check(pj_ice_sess *ice, * have this pair in our checklist. */ for (i=0; iclist.count; ++i) { - pj_ice_sess_check *c = &ice->clist.checks[i]; - if (c->lcand == lcand && c->rcand == rcand) - break; + pj_ice_sess_check *c = &ice->clist.checks[i]; + if (c->lcand == lcand && c->rcand == rcand) + break; } /* If the pair is already on the check list: @@ -3396,80 +3395,80 @@ static void handle_incoming_check(pj_ice_sess *ice, * check is sent. */ if (i != ice->clist.count) { - pj_ice_sess_check *c = &ice->clist.checks[i]; - - /* If USE-CANDIDATE is present, set nominated flag - * Note: DO NOT overwrite nominated flag if one is already set. - */ - c->nominated = ((rcheck->use_candidate) || c->nominated); - - if (c->state == PJ_ICE_SESS_CHECK_STATE_FROZEN || - c->state == PJ_ICE_SESS_CHECK_STATE_WAITING) - { - /* If we are nominating in regular nomination, don't nominate this - * triggered check immediately, just wait for its scheduled check. - */ - if (ice->is_nominating && !ice->opt.aggressive) { - LOG5((ice->obj_name, "Triggered check for check %d not " - "performed because nomination is in progress", i)); - } else { - /* See if we shall nominate this check */ - pj_bool_t nominate = (c->nominated || ice->is_nominating); - - LOG5((ice->obj_name, "Performing triggered check for " - "check %d",i)); - pj_log_push_indent(); - perform_check(ice, &ice->clist, i, nominate); - pj_log_pop_indent(); - } - } else if (c->state == PJ_ICE_SESS_CHECK_STATE_IN_PROGRESS) { - /* Should retransmit immediately - */ - LOG5((ice->obj_name, "Triggered check for check %d not performed " - "because it's in progress. Retransmitting", i)); - pj_log_push_indent(); - pj_stun_session_retransmit_req(comp->stun_sess, c->tdata, PJ_FALSE); - pj_log_pop_indent(); - - } else if (c->state == PJ_ICE_SESS_CHECK_STATE_SUCCEEDED) { - /* Check complete for this component. - * Note this may end ICE process. - */ - pj_bool_t complete; - unsigned j; - - /* If this check is nominated, scan the valid_list for the - * same check and update the nominated flag. A controlled - * agent might have finished the check earlier. - */ - if (rcheck->use_candidate) { - for (j=0; jvalid_list.count; ++j) { - pj_ice_sess_check *vc = &ice->valid_list.checks[j]; - if (vc->lcand->transport_id == c->lcand->transport_id && - vc->rcand == c->rcand) - { - /* Set nominated flag */ - vc->nominated = PJ_TRUE; - - /* Update valid check and nominated check for the component */ - update_comp_check(ice, vc->lcand->comp_id, vc); - - LOG5((ice->obj_name, "Valid check %s is nominated", - dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), - &ice->valid_list, vc))); - } - } - } - - LOG5((ice->obj_name, "Triggered check for check %d not performed " - "because it's completed", i)); - pj_log_push_indent(); - complete = on_check_complete(ice, c); - pj_log_pop_indent(); - if (complete) { - return; - } - } + pj_ice_sess_check *c = &ice->clist.checks[i]; + + /* If USE-CANDIDATE is present, set nominated flag + * Note: DO NOT overwrite nominated flag if one is already set. + */ + c->nominated = ((rcheck->use_candidate) || c->nominated); + + if (c->state == PJ_ICE_SESS_CHECK_STATE_FROZEN || + c->state == PJ_ICE_SESS_CHECK_STATE_WAITING) + { + /* If we are nominating in regular nomination, don't nominate this + * triggered check immediately, just wait for its scheduled check. + */ + if (ice->is_nominating && !ice->opt.aggressive) { + LOG5((ice->obj_name, "Triggered check for check %d not " + "performed because nomination is in progress", i)); + } else { + /* See if we shall nominate this check */ + pj_bool_t nominate = (c->nominated || ice->is_nominating); + + LOG5((ice->obj_name, "Performing triggered check for " + "check %d",i)); + pj_log_push_indent(); + perform_check(ice, &ice->clist, i, nominate); + pj_log_pop_indent(); + } + } else if (c->state == PJ_ICE_SESS_CHECK_STATE_IN_PROGRESS) { + /* Should retransmit immediately + */ + LOG5((ice->obj_name, "Triggered check for check %d not performed " + "because it's in progress. Retransmitting", i)); + pj_log_push_indent(); + pj_stun_session_retransmit_req(comp->stun_sess, c->tdata, PJ_FALSE); + pj_log_pop_indent(); + + } else if (c->state == PJ_ICE_SESS_CHECK_STATE_SUCCEEDED) { + /* Check complete for this component. + * Note this may end ICE process. + */ + pj_bool_t complete; + unsigned j; + + /* If this check is nominated, scan the valid_list for the + * same check and update the nominated flag. A controlled + * agent might have finished the check earlier. + */ + if (rcheck->use_candidate) { + for (j=0; jvalid_list.count; ++j) { + pj_ice_sess_check *vc = &ice->valid_list.checks[j]; + if (vc->lcand->transport_id == c->lcand->transport_id && + vc->rcand == c->rcand) + { + /* Set nominated flag */ + vc->nominated = PJ_TRUE; + + /* Update valid check and nominated check for the component */ + update_comp_check(ice, vc->lcand->comp_id, vc); + + LOG5((ice->obj_name, "Valid check %s is nominated", + dump_check(ice->tmp.txt, sizeof(ice->tmp.txt), + &ice->valid_list, vc))); + } + } + } + + LOG5((ice->obj_name, "Triggered check for check %d not performed " + "because it's completed", i)); + pj_log_push_indent(); + complete = on_check_complete(ice, c); + pj_log_pop_indent(); + if (complete) { + return; + } + } } /* If the pair is not already on the check list: @@ -3480,61 +3479,61 @@ static void handle_incoming_check(pj_ice_sess *ice, /* Note: only do this if we don't have too many checks in checklist */ else if (ice->clist.count < PJ_ICE_MAX_CHECKS) { - pj_ice_sess_check *c = &ice->clist.checks[ice->clist.count]; - unsigned check_id = ice->clist.count; - - c->lcand = lcand; - c->rcand = rcand; - c->prio = CALC_CHECK_PRIO(ice, lcand, rcand); - c->state = PJ_ICE_SESS_CHECK_STATE_WAITING; - c->nominated = rcheck->use_candidate; - c->err_code = PJ_SUCCESS; - ++ice->clist.count; - - LOG4((ice->obj_name, "New triggered check added: %d", check_id)); - - /* If we are nominating in regular nomination, don't nominate this - * newly found pair. - */ - if (ice->is_nominating && !ice->opt.aggressive) { - LOG5((ice->obj_name, "Triggered check for check %d not " - "performed because nomination is in progress", check_id)); - - /* Just in case the periodic check has been stopped (due to no more - * pair to check), let's restart it for this pair. - */ - if (!pj_timer_entry_running(&ice->clist.timer)) { - pj_time_val delay = {0, 0}; - pj_timer_heap_schedule_w_grp_lock(ice->stun_cfg.timer_heap, - &ice->clist.timer, &delay, - PJ_TRUE, ice->grp_lock); - } - } else { - pj_bool_t nominate; - nominate = (c->nominated || ice->is_nominating); - - pj_log_push_indent(); - perform_check(ice, &ice->clist, check_id, nominate); - pj_log_pop_indent(); - } - - /* Re-sort the list because of the newly added pair. */ - sort_checklist(ice, &ice->clist); + pj_ice_sess_check *c = &ice->clist.checks[ice->clist.count]; + unsigned check_id = ice->clist.count; + + c->lcand = lcand; + c->rcand = rcand; + c->prio = CALC_CHECK_PRIO(ice, lcand, rcand); + c->state = PJ_ICE_SESS_CHECK_STATE_WAITING; + c->nominated = rcheck->use_candidate; + c->err_code = PJ_SUCCESS; + ++ice->clist.count; + + LOG4((ice->obj_name, "New triggered check added: %d", check_id)); + + /* If we are nominating in regular nomination, don't nominate this + * newly found pair. + */ + if (ice->is_nominating && !ice->opt.aggressive) { + LOG5((ice->obj_name, "Triggered check for check %d not " + "performed because nomination is in progress", check_id)); + + /* Just in case the periodic check has been stopped (due to no more + * pair to check), let's restart it for this pair. + */ + if (!pj_timer_entry_running(&ice->clist.timer)) { + pj_time_val delay = {0, 0}; + pj_timer_heap_schedule_w_grp_lock(ice->stun_cfg.timer_heap, + &ice->clist.timer, &delay, + PJ_TRUE, ice->grp_lock); + } + } else { + pj_bool_t nominate; + nominate = (c->nominated || ice->is_nominating); + + pj_log_push_indent(); + perform_check(ice, &ice->clist, check_id, nominate); + pj_log_pop_indent(); + } + + /* Re-sort the list because of the newly added pair. */ + sort_checklist(ice, &ice->clist); } else { - LOG4((ice->obj_name, "Error: unable to perform triggered check: " - "TOO MANY CHECKS IN CHECKLIST!")); + LOG4((ice->obj_name, "Error: unable to perform triggered check: " + "TOO MANY CHECKS IN CHECKLIST!")); } } static pj_status_t on_stun_rx_indication(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_msg *msg, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_msg *msg, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { struct stun_data *sd; @@ -3551,12 +3550,12 @@ static pj_status_t on_stun_rx_indication(pj_stun_session *sess, pj_log_push_indent(); if (msg->hdr.type == PJ_STUN_BINDING_INDICATION) { - LOG5((sd->ice->obj_name, "Received Binding Indication keep-alive " - "for component %d", sd->comp_id)); + LOG5((sd->ice->obj_name, "Received Binding Indication keep-alive " + "for component %d", sd->comp_id)); } else { - LOG4((sd->ice->obj_name, "Received unexpected %s indication " - "for component %d", pj_stun_get_method_name(msg->hdr.type), - sd->comp_id)); + LOG4((sd->ice->obj_name, "Received unexpected %s indication " + "for component %d", pj_stun_get_method_name(msg->hdr.type), + sd->comp_id)); } pj_log_pop_indent(); @@ -3566,9 +3565,9 @@ static pj_status_t on_stun_rx_indication(pj_stun_session *sess, PJ_DEF(pj_status_t) pj_ice_sess_send_data(pj_ice_sess *ice, - unsigned comp_id, - const void *data, - pj_size_t data_len) + unsigned comp_id, + const void *data, + pj_size_t data_len) { pj_status_t status = PJ_SUCCESS; pj_ice_sess_comp *comp; @@ -3582,27 +3581,27 @@ PJ_DEF(pj_status_t) pj_ice_sess_send_data(pj_ice_sess *ice, * doesn't support all the components that we have. */ if (comp_id > ice->comp_cnt) { - return PJNATH_EICEINCOMPID; + return PJNATH_EICEINCOMPID; } pj_grp_lock_acquire(ice->grp_lock); if (ice->is_destroying) { - pj_grp_lock_release(ice->grp_lock); - return PJ_EINVALIDOP; + pj_grp_lock_release(ice->grp_lock); + return PJ_EINVALIDOP; } comp = find_comp(ice, comp_id); if (comp == NULL) { - status = PJNATH_EICEINCOMPID; - pj_grp_lock_release(ice->grp_lock); - goto on_return; + status = PJNATH_EICEINCOMPID; + pj_grp_lock_release(ice->grp_lock); + goto on_return; } if (comp->valid_check == NULL) { - status = PJNATH_EICEINPROGRESS; - pj_grp_lock_release(ice->grp_lock); - goto on_return; + status = PJNATH_EICEINPROGRESS; + pj_grp_lock_release(ice->grp_lock); + goto on_return; } cand = comp->valid_check->lcand; @@ -3615,9 +3614,9 @@ PJ_DEF(pj_status_t) pj_ice_sess_send_data(pj_ice_sess *ice, PJ_RACE_ME(5); status = (*ice->cb.on_tx_pkt)(ice, comp_id, transport_id, - data, data_len, - &addr, - pj_sockaddr_get_len(&addr)); + data, data_len, + &addr, + pj_sockaddr_get_len(&addr)); on_return: return status; @@ -3625,12 +3624,12 @@ PJ_DEF(pj_status_t) pj_ice_sess_send_data(pj_ice_sess *ice, PJ_DEF(pj_status_t) pj_ice_sess_on_rx_pkt(pj_ice_sess *ice, - unsigned comp_id, - unsigned transport_id, - void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *src_addr, - int src_addr_len) + unsigned comp_id, + unsigned transport_id, + void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *src_addr, + int src_addr_len) { pj_status_t status = PJ_SUCCESS; pj_ice_sess_comp *comp; @@ -3642,27 +3641,27 @@ PJ_DEF(pj_status_t) pj_ice_sess_on_rx_pkt(pj_ice_sess *ice, pj_grp_lock_acquire(ice->grp_lock); if (ice->is_destroying) { - pj_grp_lock_release(ice->grp_lock); - return PJ_EINVALIDOP; + pj_grp_lock_release(ice->grp_lock); + return PJ_EINVALIDOP; } comp = find_comp(ice, comp_id); if (comp == NULL) { - pj_grp_lock_release(ice->grp_lock); - return PJNATH_EICEINCOMPID; + pj_grp_lock_release(ice->grp_lock); + return PJNATH_EICEINCOMPID; } /* Find transport */ for (i=0; itp_data); ++i) { - if (ice->tp_data[i].transport_id == transport_id) { - msg_data = &ice->tp_data[i]; - break; - } + if (ice->tp_data[i].transport_id == transport_id) { + msg_data = &ice->tp_data[i]; + break; + } } if (msg_data == NULL) { - pj_assert(!"Invalid transport ID"); - pj_grp_lock_release(ice->grp_lock); - return PJ_EINVAL; + pj_assert(!"Invalid transport ID"); + pj_grp_lock_release(ice->grp_lock); + return PJ_EINVAL; } /* Don't check fingerprint. We only need to distinguish STUN and non-STUN @@ -3670,29 +3669,29 @@ PJ_DEF(pj_status_t) pj_ice_sess_on_rx_pkt(pj_ice_sess *ice, * will be done by the user. */ status = pj_stun_msg_check((const pj_uint8_t*)pkt, pkt_size, - PJ_STUN_IS_DATAGRAM | - PJ_STUN_NO_FINGERPRINT_CHECK); + PJ_STUN_IS_DATAGRAM | + PJ_STUN_NO_FINGERPRINT_CHECK); if (status == PJ_SUCCESS) { - status = pj_stun_session_on_rx_pkt(comp->stun_sess, pkt, pkt_size, - PJ_STUN_IS_DATAGRAM, msg_data, - NULL, src_addr, src_addr_len); - if (status != PJ_SUCCESS) { - pj_strerror(status, ice->tmp.errmsg, sizeof(ice->tmp.errmsg)); - LOG4((ice->obj_name, "Error processing incoming message: %s", - ice->tmp.errmsg)); - } - pj_grp_lock_release(ice->grp_lock); + status = pj_stun_session_on_rx_pkt(comp->stun_sess, pkt, pkt_size, + PJ_STUN_IS_DATAGRAM, msg_data, + NULL, src_addr, src_addr_len); + if (status != PJ_SUCCESS) { + pj_strerror(status, ice->tmp.errmsg, sizeof(ice->tmp.errmsg)); + LOG4((ice->obj_name, "Error processing incoming message: %s", + ice->tmp.errmsg)); + } + pj_grp_lock_release(ice->grp_lock); } else { - /* Not a STUN packet. Call application's callback instead, but release - * the mutex now or otherwise we may get deadlock. - */ - pj_grp_lock_release(ice->grp_lock); + /* Not a STUN packet. Call application's callback instead, but release + * the mutex now or otherwise we may get deadlock. + */ + pj_grp_lock_release(ice->grp_lock); - PJ_RACE_ME(5); + PJ_RACE_ME(5); - (*ice->cb.on_rx_data)(ice, comp_id, transport_id, pkt, pkt_size, - src_addr, src_addr_len); - status = PJ_SUCCESS; + (*ice->cb.on_rx_data)(ice, comp_id, transport_id, pkt, pkt_size, + src_addr, src_addr_len); + status = PJ_SUCCESS; } return status; diff --git a/pjnath/src/pjnath/ice_strans.c b/pjnath/src/pjnath/ice_strans.c index a3e03ee451..8fa8781014 100644 --- a/pjnath/src/pjnath/ice_strans.c +++ b/pjnath/src/pjnath/ice_strans.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,7 +33,7 @@ #define ENABLE_TRACE 0 #if defined(ENABLE_TRACE) && (ENABLE_TRACE != 0) -# define TRACE_PKT(expr) PJ_LOG(5,expr) +# define TRACE_PKT(expr) PJ_LOG(5,expr) #else # define TRACE_PKT(expr) #endif @@ -49,7 +48,7 @@ enum tp_type }; -#define CREATE_TP_ID(type, idx) (pj_uint8_t)((type << 6) | idx) +#define CREATE_TP_ID(type, idx) (pj_uint8_t)((type << 6) | idx) #define GET_TP_TYPE(transport_id) ((transport_id & 0xC0) >> 6) #define GET_TP_IDX(transport_id) (transport_id & 0x3F) @@ -74,64 +73,64 @@ enum tp_type static pj_uint8_t srflx_pref_table[PJ_ICE_CAND_TYPE_MAX] = { #if PJNATH_ICE_PRIO_STD - 100, /**< PJ_ICE_HOST_PREF */ - 110, /**< PJ_ICE_SRFLX_PREF */ - 126, /**< PJ_ICE_PRFLX_PREF */ - 0 /**< PJ_ICE_RELAYED_PREF */ + 100, /**< PJ_ICE_HOST_PREF */ + 110, /**< PJ_ICE_SRFLX_PREF */ + 126, /**< PJ_ICE_PRFLX_PREF */ + 0 /**< PJ_ICE_RELAYED_PREF */ #else /* Keep it to 2 bits */ - 1, /**< PJ_ICE_HOST_PREF */ - 2, /**< PJ_ICE_SRFLX_PREF */ - 3, /**< PJ_ICE_PRFLX_PREF */ - 0 /**< PJ_ICE_RELAYED_PREF */ + 1, /**< PJ_ICE_HOST_PREF */ + 2, /**< PJ_ICE_SRFLX_PREF */ + 3, /**< PJ_ICE_PRFLX_PREF */ + 0 /**< PJ_ICE_RELAYED_PREF */ #endif }; /* ICE callbacks */ -static void on_valid_pair(pj_ice_sess *ice); -static void on_ice_complete(pj_ice_sess *ice, pj_status_t status); +static void on_valid_pair(pj_ice_sess *ice); +static void on_ice_complete(pj_ice_sess *ice, pj_status_t status); static pj_status_t ice_tx_pkt(pj_ice_sess *ice, - unsigned comp_id, - unsigned transport_id, - const void *pkt, pj_size_t size, - const pj_sockaddr_t *dst_addr, - unsigned dst_addr_len); -static void ice_rx_data(pj_ice_sess *ice, - unsigned comp_id, - unsigned transport_id, - void *pkt, pj_size_t size, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + unsigned comp_id, + unsigned transport_id, + const void *pkt, pj_size_t size, + const pj_sockaddr_t *dst_addr, + unsigned dst_addr_len); +static void ice_rx_data(pj_ice_sess *ice, + unsigned comp_id, + unsigned transport_id, + void *pkt, pj_size_t size, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); /* STUN socket callbacks */ /* Notification when incoming packet has been received. */ static pj_bool_t stun_on_rx_data(pj_stun_sock *stun_sock, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *src_addr, - unsigned addr_len); + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *src_addr, + unsigned addr_len); /* Notifification when asynchronous send operation has completed. */ static pj_bool_t stun_on_data_sent(pj_stun_sock *stun_sock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent); + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent); /* Notification when the status of the STUN transport has changed. */ static pj_bool_t stun_on_status(pj_stun_sock *stun_sock, - pj_stun_sock_op op, - pj_status_t status); + pj_stun_sock_op op, + pj_status_t status); /* TURN callbacks */ static void turn_on_rx_data(pj_turn_sock *turn_sock, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); static pj_bool_t turn_on_data_sent(pj_turn_sock *turn_sock, - pj_ssize_t sent); + pj_ssize_t sent); static void turn_on_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, - pj_turn_state_t new_state); + pj_turn_state_t new_state); @@ -156,29 +155,29 @@ static void sess_init_update(pj_ice_strans *ice_st); */ typedef struct pj_ice_strans_comp { - pj_ice_strans *ice_st; /**< ICE stream transport. */ - unsigned comp_id; /**< Component ID. */ + pj_ice_strans *ice_st; /**< ICE stream transport. */ + unsigned comp_id; /**< Component ID. */ struct { - pj_stun_sock *sock; /**< STUN transport. */ + pj_stun_sock *sock; /**< STUN transport. */ } stun[PJ_ICE_MAX_STUN]; struct { - pj_turn_sock *sock; /**< TURN relay transport. */ - pj_bool_t log_off; /**< TURN loggin off? */ - unsigned err_cnt; /**< TURN disconnected count. */ + pj_turn_sock *sock; /**< TURN relay transport. */ + pj_bool_t log_off; /**< TURN loggin off? */ + unsigned err_cnt; /**< TURN disconnected count. */ } turn[PJ_ICE_MAX_TURN]; - pj_bool_t creating; /**< Is creating the candidates?*/ - unsigned cand_cnt; /**< # of candidates/aliaes. */ - pj_ice_sess_cand cand_list[PJ_ICE_ST_MAX_CAND]; /**< Cand array */ + pj_bool_t creating; /**< Is creating the candidates?*/ + unsigned cand_cnt; /**< # of candidates/aliaes. */ + pj_ice_sess_cand cand_list[PJ_ICE_ST_MAX_CAND]; /**< Cand array */ - pj_bool_t ipv4_mapped; /**< Is IPv6 addr mapped to IPv4?*/ - pj_sockaddr dst_addr; /**< Destination address */ - pj_sockaddr synth_addr; /**< Synthesized dest address */ - unsigned synth_addr_len;/**< Synthesized dest addr len */ + pj_bool_t ipv4_mapped; /**< Is IPv6 addr mapped to IPv4?*/ + pj_sockaddr dst_addr; /**< Destination address */ + pj_sockaddr synth_addr; /**< Synthesized dest address */ + unsigned synth_addr_len;/**< Synthesized dest addr len */ - unsigned default_cand; /**< Default candidate. */ + unsigned default_cand; /**< Default candidate. */ } pj_ice_strans_comp; @@ -186,11 +185,11 @@ typedef struct pj_ice_strans_comp /* Pending send buffer */ typedef struct pending_send { - void *buffer; - unsigned comp_id; - pj_size_t data_len; - pj_sockaddr dst_addr; - int dst_addr_len; + void *buffer; + unsigned comp_id; + pj_size_t data_len; + pj_sockaddr dst_addr; + int dst_addr_len; } pending_send; /** @@ -198,41 +197,41 @@ typedef struct pending_send */ struct pj_ice_strans { - char *obj_name; /**< Log ID. */ - pj_pool_factory *pf; /**< Pool factory. */ - pj_pool_t *pool; /**< Pool used by this object. */ - void *user_data; /**< Application data. */ - pj_ice_strans_cfg cfg; /**< Configuration. */ - pj_ice_strans_cb cb; /**< Application callback. */ - pj_grp_lock_t *grp_lock; /**< Group lock. */ - - pj_ice_strans_state state; /**< Session state. */ - pj_ice_sess *ice; /**< ICE session. */ - pj_ice_sess *ice_prev; /**< Previous ICE session. */ - pj_grp_lock_handler ice_prev_hndlr; /**< Handler of prev ICE */ - pj_time_val start_time;/**< Time when ICE was started */ - - unsigned comp_cnt; /**< Number of components. */ - pj_ice_strans_comp **comp; /**< Components array. */ - - pj_pool_t *buf_pool; /**< Pool for buffers. */ - unsigned num_buf; /**< Number of buffers. */ - unsigned buf_idx; /**< Index of buffer. */ - unsigned empty_idx; /**< Index of empty buffer. */ - unsigned buf_size; /**< Buffer size. */ - pending_send *send_buf; /**< Send buffers. */ - pj_bool_t is_pending;/**< Any pending send? */ - - pj_timer_entry ka_timer; /**< STUN keep-alive timer. */ - - pj_bool_t destroy_req;/**< Destroy has been called? */ - pj_bool_t cb_called; /**< Init error callback called?*/ - pj_bool_t call_send_cb;/**< Need to call send cb? */ - - pj_bool_t rem_cand_end;/**< Trickle ICE: remote has - signalled end of candidate? */ - pj_bool_t loc_cand_end;/**< Trickle ICE: local has - signalled end of candidate? */ + char *obj_name; /**< Log ID. */ + pj_pool_factory *pf; /**< Pool factory. */ + pj_pool_t *pool; /**< Pool used by this object. */ + void *user_data; /**< Application data. */ + pj_ice_strans_cfg cfg; /**< Configuration. */ + pj_ice_strans_cb cb; /**< Application callback. */ + pj_grp_lock_t *grp_lock; /**< Group lock. */ + + pj_ice_strans_state state; /**< Session state. */ + pj_ice_sess *ice; /**< ICE session. */ + pj_ice_sess *ice_prev; /**< Previous ICE session. */ + pj_grp_lock_handler ice_prev_hndlr; /**< Handler of prev ICE */ + pj_time_val start_time;/**< Time when ICE was started */ + + unsigned comp_cnt; /**< Number of components. */ + pj_ice_strans_comp **comp; /**< Components array. */ + + pj_pool_t *buf_pool; /**< Pool for buffers. */ + unsigned num_buf; /**< Number of buffers. */ + unsigned buf_idx; /**< Index of buffer. */ + unsigned empty_idx; /**< Index of empty buffer. */ + unsigned buf_size; /**< Buffer size. */ + pending_send *send_buf; /**< Send buffers. */ + pj_bool_t is_pending;/**< Any pending send? */ + + pj_timer_entry ka_timer; /**< STUN keep-alive timer. */ + + pj_bool_t destroy_req;/**< Destroy has been called? */ + pj_bool_t cb_called; /**< Init error callback called?*/ + pj_bool_t call_send_cb;/**< Need to call send cb? */ + + pj_bool_t rem_cand_end;/**< Trickle ICE: remote has + signalled end of candidate? */ + pj_bool_t loc_cand_end;/**< Trickle ICE: local has + signalled end of candidate? */ }; @@ -242,8 +241,8 @@ struct pj_ice_strans */ typedef struct sock_user_data { - pj_ice_strans_comp *comp; - pj_uint8_t transport_id; + pj_ice_strans_comp *comp; + pj_uint8_t transport_id; } sock_user_data; @@ -255,7 +254,7 @@ static pj_status_t pj_ice_strans_cfg_check_valid(const pj_ice_strans_cfg *cfg) status = pj_stun_config_check_valid(&cfg->stun_cfg); if (!status) - return status; + return status; return PJ_SUCCESS; } @@ -311,32 +310,32 @@ PJ_DEF(void) pj_ice_strans_turn_cfg_default(pj_ice_strans_turn_cfg *cfg) * Copy configuration. */ PJ_DEF(void) pj_ice_strans_cfg_copy( pj_pool_t *pool, - pj_ice_strans_cfg *dst, - const pj_ice_strans_cfg *src) + pj_ice_strans_cfg *dst, + const pj_ice_strans_cfg *src) { unsigned i; pj_memcpy(dst, src, sizeof(*src)); if (src->stun.server.slen) - pj_strdup(pool, &dst->stun.server, &src->stun.server); + pj_strdup(pool, &dst->stun.server, &src->stun.server); for (i = 0; i < src->stun_tp_cnt; ++i) { - if (src->stun_tp[i].server.slen) - pj_strdup(pool, &dst->stun_tp[i].server, - &src->stun_tp[i].server); + if (src->stun_tp[i].server.slen) + pj_strdup(pool, &dst->stun_tp[i].server, + &src->stun_tp[i].server); } if (src->turn.server.slen) - pj_strdup(pool, &dst->turn.server, &src->turn.server); + pj_strdup(pool, &dst->turn.server, &src->turn.server); pj_stun_auth_cred_dup(pool, &dst->turn.auth_cred, &src->turn.auth_cred); for (i = 0; i < src->turn_tp_cnt; ++i) { - if (src->turn_tp[i].server.slen) - pj_strdup(pool, &dst->turn_tp[i].server, - &src->turn_tp[i].server); - pj_stun_auth_cred_dup(pool, &dst->turn_tp[i].auth_cred, - &src->turn_tp[i].auth_cred); + if (src->turn_tp[i].server.slen) + pj_strdup(pool, &dst->turn_tp[i].server, + &src->turn_tp[i].server); + pj_stun_auth_cred_dup(pool, &dst->turn_tp[i].auth_cred, + &src->turn_tp[i].auth_cred); } } @@ -345,9 +344,9 @@ PJ_DEF(void) pj_ice_strans_cfg_copy( pj_pool_t *pool, * Add or update TURN candidate. */ static pj_status_t add_update_turn(pj_ice_strans *ice_st, - pj_ice_strans_comp *comp, - unsigned idx, - unsigned max_cand_cnt) + pj_ice_strans_comp *comp, + unsigned idx, + unsigned max_cand_cnt) { pj_ice_sess_cand *cand = NULL; pj_ice_strans_turn_cfg *turn_cfg = &ice_st->cfg.turn_tp[idx]; @@ -362,40 +361,40 @@ static pj_status_t add_update_turn(pj_ice_strans *ice_st, /* Check if TURN transport is configured */ if (turn_cfg->server.slen == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Find relayed candidate in the component */ tp_id = CREATE_TP_ID(TP_TURN, idx); for (i=0; icand_cnt; ++i) { - if (comp->cand_list[i].transport_id == tp_id) { - cand = &comp->cand_list[i]; - break; - } + if (comp->cand_list[i].transport_id == tp_id) { + cand = &comp->cand_list[i]; + break; + } } /* If candidate is found, invalidate it first */ if (cand) { - cand->status = PJ_EPENDING; - - /* Also if this component's default candidate is set to relay, - * move it temporarily to something else. - */ - if ((int)comp->default_cand == cand - comp->cand_list) { - /* Init to something */ - comp->default_cand = 0; - /* Use srflx candidate as the default, if any */ - for (i=0; icand_cnt; ++i) { - if (comp->cand_list[i].type == PJ_ICE_CAND_TYPE_SRFLX) { - comp->default_cand = i; - if (ice_st->cfg.af == pj_AF_UNSPEC() || - comp->cand_list[i].base_addr.addr.sa_family == - ice_st->cfg.af) - { - break; - } - } - } - } + cand->status = PJ_EPENDING; + + /* Also if this component's default candidate is set to relay, + * move it temporarily to something else. + */ + if ((int)comp->default_cand == cand - comp->cand_list) { + /* Init to something */ + comp->default_cand = 0; + /* Use srflx candidate as the default, if any */ + for (i=0; icand_cnt; ++i) { + if (comp->cand_list[i].type == PJ_ICE_CAND_TYPE_SRFLX) { + comp->default_cand = i; + if (ice_st->cfg.af == pj_AF_UNSPEC() || + comp->cand_list[i].base_addr.addr.sa_family == + ice_st->cfg.af) + { + break; + } + } + } + } } /* Init TURN socket */ @@ -406,29 +405,29 @@ static pj_status_t add_update_turn(pj_ice_strans *ice_st, /* Override with component specific QoS settings, if any */ if (ice_st->cfg.comp[comp_idx].qos_type) - sock_cfg->qos_type = ice_st->cfg.comp[comp_idx].qos_type; + sock_cfg->qos_type = ice_st->cfg.comp[comp_idx].qos_type; if (ice_st->cfg.comp[comp_idx].qos_params.flags) - pj_memcpy(&sock_cfg->qos_params, - &ice_st->cfg.comp[comp_idx].qos_params, - sizeof(sock_cfg->qos_params)); + pj_memcpy(&sock_cfg->qos_params, + &ice_st->cfg.comp[comp_idx].qos_params, + sizeof(sock_cfg->qos_params)); /* Override with component specific socket buffer size settings, if any */ if (ice_st->cfg.comp[comp_idx].so_rcvbuf_size > 0) - sock_cfg->so_rcvbuf_size = ice_st->cfg.comp[comp_idx].so_rcvbuf_size; + sock_cfg->so_rcvbuf_size = ice_st->cfg.comp[comp_idx].so_rcvbuf_size; if (ice_st->cfg.comp[comp_idx].so_sndbuf_size > 0) - sock_cfg->so_sndbuf_size = ice_st->cfg.comp[comp_idx].so_sndbuf_size; + sock_cfg->so_sndbuf_size = ice_st->cfg.comp[comp_idx].so_sndbuf_size; /* Add relayed candidate with pending status if there's no existing one */ if (cand == NULL) { - PJ_ASSERT_RETURN(max_cand_cnt > 0, PJ_ETOOSMALL); + PJ_ASSERT_RETURN(max_cand_cnt > 0, PJ_ETOOSMALL); - cand = &comp->cand_list[comp->cand_cnt]; - cand->type = PJ_ICE_CAND_TYPE_RELAYED; - cand->status = PJ_EPENDING; - cand->local_pref = (pj_uint16_t)(RELAY_PREF - idx); - cand->transport_id = tp_id; - cand->comp_id = (pj_uint8_t) comp->comp_id; - new_cand = PJ_TRUE; + cand = &comp->cand_list[comp->cand_cnt]; + cand->type = PJ_ICE_CAND_TYPE_RELAYED; + cand->status = PJ_EPENDING; + cand->local_pref = (pj_uint16_t)(RELAY_PREF - idx); + cand->transport_id = tp_id; + cand->comp_id = (pj_uint8_t) comp->comp_id; + new_cand = PJ_TRUE; } /* Allocate and initialize TURN socket data */ @@ -438,19 +437,19 @@ static pj_status_t add_update_turn(pj_ice_strans *ice_st, /* Create the TURN transport */ status = pj_turn_sock_create(&ice_st->cfg.stun_cfg, turn_cfg->af, - turn_cfg->conn_type, - &turn_sock_cb, sock_cfg, - data, &comp->turn[idx].sock); + turn_cfg->conn_type, + &turn_sock_cb, sock_cfg, + data, &comp->turn[idx].sock); if (status != PJ_SUCCESS) { - return status; + return status; } if (new_cand) { - /* Commit the relayed candidate before pj_turn_sock_alloc(), as - * otherwise there can be race condition, please check - * https://github.com/pjsip/pjproject/pull/2525 for more info. - */ - comp->cand_cnt++; + /* Commit the relayed candidate before pj_turn_sock_alloc(), as + * otherwise there can be race condition, please check + * https://github.com/pjsip/pjproject/pull/2525 for more info. + */ + comp->cand_cnt++; } /* Add pending job */ @@ -458,27 +457,27 @@ static pj_status_t add_update_turn(pj_ice_strans *ice_st, /* Start allocation */ status=pj_turn_sock_alloc(comp->turn[idx].sock, - &turn_cfg->server, - turn_cfg->port, - ice_st->cfg.resolver, - &turn_cfg->auth_cred, - &turn_cfg->alloc_param); + &turn_cfg->server, + turn_cfg->port, + ice_st->cfg.resolver, + &turn_cfg->auth_cred, + &turn_cfg->alloc_param); if (status != PJ_SUCCESS) { - ///sess_dec_ref(ice_st); - cand->status = status; - return status; + ///sess_dec_ref(ice_st); + cand->status = status; + return status; } PJ_LOG(4,(ice_st->obj_name, - "Comp %d/%d: TURN relay candidate (tpid=%d) " - "waiting for allocation", - comp->comp_id, comp->cand_cnt-1, cand->transport_id)); + "Comp %d/%d: TURN relay candidate (tpid=%d) " + "waiting for allocation", + comp->comp_id, comp->cand_cnt-1, cand->transport_id)); return PJ_SUCCESS; } static pj_bool_t ice_cand_equals(pj_ice_sess_cand *lcand, - pj_ice_sess_cand *rcand) + pj_ice_sess_cand *rcand) { if (lcand == NULL && rcand == NULL){ return PJ_TRUE; @@ -491,7 +490,7 @@ static pj_bool_t ice_cand_equals(pj_ice_sess_cand *lcand, || lcand->status != rcand->status || lcand->comp_id != rcand->comp_id || lcand->transport_id != rcand->transport_id - // local pref is no longer a constant, so it may be different + // local pref is no longer a constant, so it may be different //|| lcand->local_pref != rcand->local_pref || lcand->prio != rcand->prio || pj_sockaddr_cmp(&lcand->addr, &rcand->addr) != 0 @@ -505,9 +504,9 @@ static pj_bool_t ice_cand_equals(pj_ice_sess_cand *lcand, static pj_status_t add_stun_and_host(pj_ice_strans *ice_st, - pj_ice_strans_comp *comp, - unsigned idx, - unsigned max_cand_cnt) + pj_ice_strans_comp *comp, + unsigned idx, + unsigned max_cand_cnt) { pj_ice_sess_cand *cand; pj_ice_strans_stun_cfg *stun_cfg = &ice_st->cfg.stun_tp[idx]; @@ -521,7 +520,7 @@ static pj_status_t add_stun_and_host(pj_ice_strans *ice_st, /* Check if STUN transport or host candidate is configured */ if (stun_cfg->server.slen == 0 && stun_cfg->max_host_cands == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Initialize STUN socket callback */ pj_bzero(&stun_sock_cb, sizeof(stun_sock_cb)); @@ -531,20 +530,20 @@ static pj_status_t add_stun_and_host(pj_ice_strans *ice_st, /* Override component specific QoS settings, if any */ if (ice_st->cfg.comp[comp_idx].qos_type) { - sock_cfg->qos_type = ice_st->cfg.comp[comp_idx].qos_type; + sock_cfg->qos_type = ice_st->cfg.comp[comp_idx].qos_type; } if (ice_st->cfg.comp[comp_idx].qos_params.flags) { - pj_memcpy(&sock_cfg->qos_params, - &ice_st->cfg.comp[comp_idx].qos_params, - sizeof(sock_cfg->qos_params)); + pj_memcpy(&sock_cfg->qos_params, + &ice_st->cfg.comp[comp_idx].qos_params, + sizeof(sock_cfg->qos_params)); } /* Override component specific socket buffer size settings, if any */ if (ice_st->cfg.comp[comp_idx].so_rcvbuf_size > 0) { - sock_cfg->so_rcvbuf_size = ice_st->cfg.comp[comp_idx].so_rcvbuf_size; + sock_cfg->so_rcvbuf_size = ice_st->cfg.comp[comp_idx].so_rcvbuf_size; } if (ice_st->cfg.comp[comp_idx].so_sndbuf_size > 0) { - sock_cfg->so_sndbuf_size = ice_st->cfg.comp[comp_idx].so_sndbuf_size; + sock_cfg->so_sndbuf_size = ice_st->cfg.comp[comp_idx].so_sndbuf_size; } /* Prepare srflx candidate with pending status. */ @@ -562,186 +561,186 @@ static pj_status_t add_stun_and_host(pj_ice_strans *ice_st, /* Create the STUN transport */ status = pj_stun_sock_create(&ice_st->cfg.stun_cfg, NULL, - stun_cfg->af, &stun_sock_cb, - sock_cfg, data, &comp->stun[idx].sock); + stun_cfg->af, &stun_sock_cb, + sock_cfg, data, &comp->stun[idx].sock); if (status != PJ_SUCCESS) - return status; + return status; /* Start STUN Binding resolution and add srflx candidate only if server * is set. When any error occur during STUN Binding resolution, let's * just skip it and generate host candidates. */ while (stun_cfg->server.slen) { - pj_stun_sock_info stun_sock_info; - - /* Add pending job */ - ///sess_add_ref(ice_st); - - PJ_LOG(4,(ice_st->obj_name, - "Comp %d: srflx candidate (tpid=%d) starts " - "Binding discovery", - comp->comp_id, cand->transport_id)); - - pj_log_push_indent(); - - /* Start Binding resolution */ - status = pj_stun_sock_start(comp->stun[idx].sock, &stun_cfg->server, - stun_cfg->port, ice_st->cfg.resolver); - if (status != PJ_SUCCESS) { - ///sess_dec_ref(ice_st); - PJ_PERROR(5,(ice_st->obj_name, status, - "Comp %d: srflx candidate (tpid=%d) failed in " - "pj_stun_sock_start()", - comp->comp_id, cand->transport_id)); - pj_log_pop_indent(); - break; - } - - /* Enumerate addresses */ - status = pj_stun_sock_get_info(comp->stun[idx].sock, &stun_sock_info); - if (status != PJ_SUCCESS) { - ///sess_dec_ref(ice_st); - PJ_PERROR(5,(ice_st->obj_name, status, - "Comp %d: srflx candidate (tpid=%d) failed in " - "pj_stun_sock_get_info()", - comp->comp_id, cand->transport_id)); - pj_log_pop_indent(); - break; - } - - /* Update and commit the srflx candidate. */ - pj_sockaddr_cp(&cand->base_addr, &stun_sock_info.aliases[0]); - pj_sockaddr_cp(&cand->rel_addr, &cand->base_addr); - pj_ice_calc_foundation(ice_st->pool, &cand->foundation, - cand->type, &cand->base_addr); - comp->cand_cnt++; - max_cand_cnt--; - - /* Set default candidate to srflx */ - if (comp->cand_list[comp->default_cand].type != PJ_ICE_CAND_TYPE_SRFLX - || (ice_st->cfg.af != pj_AF_UNSPEC() && - comp->cand_list[comp->default_cand].base_addr.addr.sa_family - != ice_st->cfg.af)) - { - comp->default_cand = (unsigned)(cand - comp->cand_list); - } - - pj_log_pop_indent(); - - /* Not really a loop, just trying to avoid complex 'if' blocks */ - break; + pj_stun_sock_info stun_sock_info; + + /* Add pending job */ + ///sess_add_ref(ice_st); + + PJ_LOG(4,(ice_st->obj_name, + "Comp %d: srflx candidate (tpid=%d) starts " + "Binding discovery", + comp->comp_id, cand->transport_id)); + + pj_log_push_indent(); + + /* Start Binding resolution */ + status = pj_stun_sock_start(comp->stun[idx].sock, &stun_cfg->server, + stun_cfg->port, ice_st->cfg.resolver); + if (status != PJ_SUCCESS) { + ///sess_dec_ref(ice_st); + PJ_PERROR(5,(ice_st->obj_name, status, + "Comp %d: srflx candidate (tpid=%d) failed in " + "pj_stun_sock_start()", + comp->comp_id, cand->transport_id)); + pj_log_pop_indent(); + break; + } + + /* Enumerate addresses */ + status = pj_stun_sock_get_info(comp->stun[idx].sock, &stun_sock_info); + if (status != PJ_SUCCESS) { + ///sess_dec_ref(ice_st); + PJ_PERROR(5,(ice_st->obj_name, status, + "Comp %d: srflx candidate (tpid=%d) failed in " + "pj_stun_sock_get_info()", + comp->comp_id, cand->transport_id)); + pj_log_pop_indent(); + break; + } + + /* Update and commit the srflx candidate. */ + pj_sockaddr_cp(&cand->base_addr, &stun_sock_info.aliases[0]); + pj_sockaddr_cp(&cand->rel_addr, &cand->base_addr); + pj_ice_calc_foundation(ice_st->pool, &cand->foundation, + cand->type, &cand->base_addr); + comp->cand_cnt++; + max_cand_cnt--; + + /* Set default candidate to srflx */ + if (comp->cand_list[comp->default_cand].type != PJ_ICE_CAND_TYPE_SRFLX + || (ice_st->cfg.af != pj_AF_UNSPEC() && + comp->cand_list[comp->default_cand].base_addr.addr.sa_family + != ice_st->cfg.af)) + { + comp->default_cand = (unsigned)(cand - comp->cand_list); + } + + pj_log_pop_indent(); + + /* Not really a loop, just trying to avoid complex 'if' blocks */ + break; } /* Add local addresses to host candidates, unless max_host_cands * is set to zero. */ if (stun_cfg->max_host_cands) { - pj_stun_sock_info stun_sock_info; - unsigned i, cand_cnt = 0; - - /* Enumerate addresses */ - status = pj_stun_sock_get_info(comp->stun[idx].sock, &stun_sock_info); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(ice_st->obj_name, status, - "Failed in querying STUN socket info")); - return status; - } - - for (i = 0; i < stun_sock_info.alias_cnt && - cand_cnt < stun_cfg->max_host_cands; ++i) - { - unsigned j; - pj_bool_t cand_duplicate = PJ_FALSE; - char addrinfo[PJ_INET6_ADDRSTRLEN+10]; - const pj_sockaddr *addr = &stun_sock_info.aliases[i]; - - if (max_cand_cnt==0) { - PJ_LOG(4,(ice_st->obj_name, "Too many host candidates")); - break; - } - - /* Ignore loopback addresses if cfg->stun.loop_addr is unset */ - if (stun_cfg->loop_addr==PJ_FALSE) { - if (stun_cfg->af == pj_AF_INET() && - (pj_ntohl(addr->ipv4.sin_addr.s_addr)>>24)==127) - { - continue; - } - else if (stun_cfg->af == pj_AF_INET6()) { - pj_in6_addr in6addr = {{{0}}}; - in6addr.s6_addr[15] = 1; - if (pj_memcmp(&in6addr, &addr->ipv6.sin6_addr, - sizeof(in6addr))==0) - { - continue; - } - } - } - - /* Ignore IPv6 link-local address, unless it is the default - * address (first alias). - */ - if (stun_cfg->af == pj_AF_INET6() && i != 0) { - const pj_in6_addr *a = &addr->ipv6.sin6_addr; - if (a->s6_addr[0] == 0xFE && (a->s6_addr[1] & 0xC0) == 0x80) - continue; - } - - cand = &comp->cand_list[comp->cand_cnt]; - - cand->type = PJ_ICE_CAND_TYPE_HOST; - cand->status = PJ_SUCCESS; - cand->local_pref = (pj_uint16_t)(HOST_PREF - cand_cnt); - cand->transport_id = CREATE_TP_ID(TP_STUN, idx); - cand->comp_id = (pj_uint8_t) comp->comp_id; - pj_sockaddr_cp(&cand->addr, addr); - pj_sockaddr_cp(&cand->base_addr, addr); - pj_bzero(&cand->rel_addr, sizeof(cand->rel_addr)); + pj_stun_sock_info stun_sock_info; + unsigned i, cand_cnt = 0; + + /* Enumerate addresses */ + status = pj_stun_sock_get_info(comp->stun[idx].sock, &stun_sock_info); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(ice_st->obj_name, status, + "Failed in querying STUN socket info")); + return status; + } + + for (i = 0; i < stun_sock_info.alias_cnt && + cand_cnt < stun_cfg->max_host_cands; ++i) + { + unsigned j; + pj_bool_t cand_duplicate = PJ_FALSE; + char addrinfo[PJ_INET6_ADDRSTRLEN+10]; + const pj_sockaddr *addr = &stun_sock_info.aliases[i]; + + if (max_cand_cnt==0) { + PJ_LOG(4,(ice_st->obj_name, "Too many host candidates")); + break; + } + + /* Ignore loopback addresses if cfg->stun.loop_addr is unset */ + if (stun_cfg->loop_addr==PJ_FALSE) { + if (stun_cfg->af == pj_AF_INET() && + (pj_ntohl(addr->ipv4.sin_addr.s_addr)>>24)==127) + { + continue; + } + else if (stun_cfg->af == pj_AF_INET6()) { + pj_in6_addr in6addr = {{{0}}}; + in6addr.s6_addr[15] = 1; + if (pj_memcmp(&in6addr, &addr->ipv6.sin6_addr, + sizeof(in6addr))==0) + { + continue; + } + } + } + + /* Ignore IPv6 link-local address, unless it is the default + * address (first alias). + */ + if (stun_cfg->af == pj_AF_INET6() && i != 0) { + const pj_in6_addr *a = &addr->ipv6.sin6_addr; + if (a->s6_addr[0] == 0xFE && (a->s6_addr[1] & 0xC0) == 0x80) + continue; + } + + cand = &comp->cand_list[comp->cand_cnt]; + + cand->type = PJ_ICE_CAND_TYPE_HOST; + cand->status = PJ_SUCCESS; + cand->local_pref = (pj_uint16_t)(HOST_PREF - cand_cnt); + cand->transport_id = CREATE_TP_ID(TP_STUN, idx); + cand->comp_id = (pj_uint8_t) comp->comp_id; + pj_sockaddr_cp(&cand->addr, addr); + pj_sockaddr_cp(&cand->base_addr, addr); + pj_bzero(&cand->rel_addr, sizeof(cand->rel_addr)); - /* Check if not already in list */ - for (j=0; jcand_cnt; j++) { - if (ice_cand_equals(cand, &comp->cand_list[j])) { - cand_duplicate = PJ_TRUE; - break; - } - } - - if (cand_duplicate) { - PJ_LOG(4, (ice_st->obj_name, - "Comp %d: host candidate %s (tpid=%d) is a duplicate", - comp->comp_id, pj_sockaddr_print(&cand->addr, addrinfo, - sizeof(addrinfo), 3), cand->transport_id)); - - pj_bzero(&cand->addr, sizeof(cand->addr)); - pj_bzero(&cand->base_addr, sizeof(cand->base_addr)); - continue; - } else { - comp->cand_cnt+=1; - cand_cnt++; - max_cand_cnt--; - } + /* Check if not already in list */ + for (j=0; jcand_cnt; j++) { + if (ice_cand_equals(cand, &comp->cand_list[j])) { + cand_duplicate = PJ_TRUE; + break; + } + } + + if (cand_duplicate) { + PJ_LOG(4, (ice_st->obj_name, + "Comp %d: host candidate %s (tpid=%d) is a duplicate", + comp->comp_id, pj_sockaddr_print(&cand->addr, addrinfo, + sizeof(addrinfo), 3), cand->transport_id)); + + pj_bzero(&cand->addr, sizeof(cand->addr)); + pj_bzero(&cand->base_addr, sizeof(cand->base_addr)); + continue; + } else { + comp->cand_cnt+=1; + cand_cnt++; + max_cand_cnt--; + } - pj_ice_calc_foundation(ice_st->pool, &cand->foundation, - cand->type, &cand->base_addr); - - /* Set default candidate with the preferred default - * address family - */ - if (comp->ice_st->cfg.af != pj_AF_UNSPEC() && - addr->addr.sa_family == comp->ice_st->cfg.af && - comp->cand_list[comp->default_cand].base_addr.addr.sa_family != - ice_st->cfg.af) - { - comp->default_cand = (unsigned)(cand - comp->cand_list); - } - - PJ_LOG(4,(ice_st->obj_name, - "Comp %d/%d: host candidate %s (tpid=%d) added", - comp->comp_id, comp->cand_cnt-1, - pj_sockaddr_print(&cand->addr, addrinfo, - sizeof(addrinfo), 3), - cand->transport_id)); - } + pj_ice_calc_foundation(ice_st->pool, &cand->foundation, + cand->type, &cand->base_addr); + + /* Set default candidate with the preferred default + * address family + */ + if (comp->ice_st->cfg.af != pj_AF_UNSPEC() && + addr->addr.sa_family == comp->ice_st->cfg.af && + comp->cand_list[comp->default_cand].base_addr.addr.sa_family != + ice_st->cfg.af) + { + comp->default_cand = (unsigned)(cand - comp->cand_list); + } + + PJ_LOG(4,(ice_st->obj_name, + "Comp %d/%d: host candidate %s (tpid=%d) added", + comp->comp_id, comp->cand_cnt-1, + pj_sockaddr_print(&cand->addr, addrinfo, + sizeof(addrinfo), 3), + cand->transport_id)); + } } return status; @@ -776,40 +775,40 @@ static pj_status_t create_comp(pj_ice_strans *ice_st, unsigned comp_id) /* Create STUN transport if configured */ for (i=0; icfg.stun_tp_cnt; ++i) { - unsigned max_cand_cnt = PJ_ICE_ST_MAX_CAND - comp->cand_cnt - - ice_st->cfg.turn_tp_cnt; + unsigned max_cand_cnt = PJ_ICE_ST_MAX_CAND - comp->cand_cnt - + ice_st->cfg.turn_tp_cnt; - status = PJ_ETOOSMALL; + status = PJ_ETOOSMALL; - if ((max_cand_cnt > 0) && (max_cand_cnt <= PJ_ICE_ST_MAX_CAND)) - status = add_stun_and_host(ice_st, comp, i, max_cand_cnt); + if ((max_cand_cnt > 0) && (max_cand_cnt <= PJ_ICE_ST_MAX_CAND)) + status = add_stun_and_host(ice_st, comp, i, max_cand_cnt); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(ice_st->obj_name, status, - "Failed creating STUN transport #%d for comp %d", - i, comp->comp_id)); - //return status; - } + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(ice_st->obj_name, status, + "Failed creating STUN transport #%d for comp %d", + i, comp->comp_id)); + //return status; + } } /* Create TURN relay if configured. */ for (i=0; icfg.turn_tp_cnt; ++i) { - unsigned max_cand_cnt = PJ_ICE_ST_MAX_CAND - comp->cand_cnt; + unsigned max_cand_cnt = PJ_ICE_ST_MAX_CAND - comp->cand_cnt; - status = PJ_ETOOSMALL; + status = PJ_ETOOSMALL; - if ((max_cand_cnt > 0) && (max_cand_cnt <= PJ_ICE_ST_MAX_CAND)) - status = add_update_turn(ice_st, comp, i, max_cand_cnt); + if ((max_cand_cnt > 0) && (max_cand_cnt <= PJ_ICE_ST_MAX_CAND)) + status = add_update_turn(ice_st, comp, i, max_cand_cnt); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(ice_st->obj_name, status, - "Failed creating TURN transport #%d for comp %d", - i, comp->comp_id)); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(ice_st->obj_name, status, + "Failed creating TURN transport #%d for comp %d", + i, comp->comp_id)); - //return status; - } else if (max_cand_cnt > 0) { - max_cand_cnt = PJ_ICE_ST_MAX_CAND - comp->cand_cnt; - } + //return status; + } else if (max_cand_cnt > 0) { + max_cand_cnt = PJ_ICE_ST_MAX_CAND - comp->cand_cnt; + } } /* Done creating all the candidates */ @@ -817,9 +816,9 @@ static pj_status_t create_comp(pj_ice_strans *ice_st, unsigned comp_id) /* It's possible that we end up without any candidates */ if (comp->cand_cnt == 0) { - PJ_LOG(4,(ice_st->obj_name, - "Error: no candidate is created due to settings")); - return PJ_EINVAL; + PJ_LOG(4,(ice_st->obj_name, + "Error: no candidate is created due to settings")); + return PJ_EINVAL; } return PJ_SUCCESS; @@ -835,22 +834,22 @@ static pj_status_t alloc_send_buf(pj_ice_strans *ice_st, unsigned buf_size) return PJ_EBUSY; } - pj_pool_safe_release(&ice_st->buf_pool); + pj_pool_safe_release(&ice_st->buf_pool); - ice_st->buf_pool = pj_pool_create(ice_st->pf, "ice_buf", - (buf_size + sizeof(pending_send)) * - ice_st->num_buf, 512, NULL); - if (!ice_st->buf_pool) - return PJ_ENOMEM; + ice_st->buf_pool = pj_pool_create(ice_st->pf, "ice_buf", + (buf_size + sizeof(pending_send)) * + ice_st->num_buf, 512, NULL); + if (!ice_st->buf_pool) + return PJ_ENOMEM; - ice_st->buf_size = buf_size; - ice_st->send_buf = pj_pool_calloc(ice_st->buf_pool, ice_st->num_buf, - sizeof(pending_send)); - for (i = 0; i < ice_st->num_buf; i++) { - ice_st->send_buf[i].buffer = pj_pool_alloc(ice_st->buf_pool, - buf_size); - } - ice_st->buf_idx = ice_st->empty_idx = 0; + ice_st->buf_size = buf_size; + ice_st->send_buf = pj_pool_calloc(ice_st->buf_pool, ice_st->num_buf, + sizeof(pending_send)); + for (i = 0; i < ice_st->num_buf; i++) { + ice_st->send_buf[i].buffer = pj_pool_alloc(ice_st->buf_pool, + buf_size); + } + ice_st->buf_idx = ice_st->empty_idx = 0; } return PJ_SUCCESS; @@ -860,11 +859,11 @@ static pj_status_t alloc_send_buf(pj_ice_strans *ice_st, unsigned buf_size) * Create ICE stream transport */ PJ_DEF(pj_status_t) pj_ice_strans_create( const char *name, - const pj_ice_strans_cfg *cfg, - unsigned comp_cnt, - void *user_data, - const pj_ice_strans_cb *cb, - pj_ice_strans **p_ice_st) + const pj_ice_strans_cfg *cfg, + unsigned comp_cnt, + void *user_data, + const pj_ice_strans_cb *cb, + pj_ice_strans **p_ice_st) { pj_pool_t *pool; pj_ice_strans *ice_st; @@ -873,16 +872,16 @@ PJ_DEF(pj_status_t) pj_ice_strans_create( const char *name, status = pj_ice_strans_cfg_check_valid(cfg); if (status != PJ_SUCCESS) - return status; + return status; PJ_ASSERT_RETURN(comp_cnt && cb && p_ice_st && - comp_cnt <= PJ_ICE_MAX_COMP , PJ_EINVAL); + comp_cnt <= PJ_ICE_MAX_COMP , PJ_EINVAL); if (name == NULL) - name = "ice%p"; + name = "ice%p"; pool = pj_pool_create(cfg->stun_cfg.pf, name, PJNATH_POOL_LEN_ICE_STRANS, - PJNATH_POOL_INC_ICE_STRANS, NULL); + PJNATH_POOL_INC_ICE_STRANS, NULL); ice_st = PJ_POOL_ZALLOC_T(pool, pj_ice_strans); ice_st->pool = pool; ice_st->pf = cfg->stun_cfg.pf; @@ -890,29 +889,29 @@ PJ_DEF(pj_status_t) pj_ice_strans_create( const char *name, ice_st->user_data = user_data; PJ_LOG(4,(ice_st->obj_name, - "Creating ICE stream transport with %d component(s)", - comp_cnt)); + "Creating ICE stream transport with %d component(s)", + comp_cnt)); pj_log_push_indent(); status = pj_grp_lock_create(pool, NULL, &ice_st->grp_lock); if (status != PJ_SUCCESS) { - pj_pool_release(pool); - pj_log_pop_indent(); - return status; + pj_pool_release(pool); + pj_log_pop_indent(); + return status; } /* Allocate send buffer */ ice_st->num_buf = cfg->num_send_buf; status = alloc_send_buf(ice_st, cfg->send_buf_size); if (status != PJ_SUCCESS) { - destroy_ice_st(ice_st); - pj_log_pop_indent(); - return status; + destroy_ice_st(ice_st); + pj_log_pop_indent(); + return status; } pj_grp_lock_add_ref(ice_st->grp_lock); pj_grp_lock_add_handler(ice_st->grp_lock, pool, ice_st, - &ice_st_on_destroy); + &ice_st_on_destroy); pj_ice_strans_cfg_copy(pool, &ice_st->cfg, cfg); @@ -920,25 +919,25 @@ PJ_DEF(pj_status_t) pj_ice_strans_create( const char *name, * and the new setting is not, copy the value to the new setting. */ if (cfg->stun_tp_cnt == 0 && - (cfg->stun.server.slen || cfg->stun.max_host_cands)) + (cfg->stun.server.slen || cfg->stun.max_host_cands)) { - ice_st->cfg.stun_tp_cnt = 1; - ice_st->cfg.stun_tp[0] = ice_st->cfg.stun; + ice_st->cfg.stun_tp_cnt = 1; + ice_st->cfg.stun_tp[0] = ice_st->cfg.stun; } if (cfg->turn_tp_cnt == 0 && cfg->turn.server.slen) { - ice_st->cfg.turn_tp_cnt = 1; - ice_st->cfg.turn_tp[0] = ice_st->cfg.turn; + ice_st->cfg.turn_tp_cnt = 1; + ice_st->cfg.turn_tp[0] = ice_st->cfg.turn; } for (i=0; icfg.stun_tp_cnt; ++i) - ice_st->cfg.stun_tp[i].cfg.grp_lock = ice_st->grp_lock; + ice_st->cfg.stun_tp[i].cfg.grp_lock = ice_st->grp_lock; for (i=0; icfg.turn_tp_cnt; ++i) - ice_st->cfg.turn_tp[i].cfg.grp_lock = ice_st->grp_lock; + ice_st->cfg.turn_tp[i].cfg.grp_lock = ice_st->grp_lock; pj_memcpy(&ice_st->cb, cb, sizeof(*cb)); ice_st->comp_cnt = comp_cnt; ice_st->comp = (pj_ice_strans_comp**) - pj_pool_calloc(pool, comp_cnt, sizeof(pj_ice_strans_comp*)); + pj_pool_calloc(pool, comp_cnt, sizeof(pj_ice_strans_comp*)); /* Move state to candidate gathering */ ice_st->state = PJ_ICE_STRANS_STATE_INIT; @@ -949,13 +948,13 @@ PJ_DEF(pj_status_t) pj_ice_strans_create( const char *name, pj_grp_lock_acquire(ice_st->grp_lock); for (i=0; igrp_lock); - destroy_ice_st(ice_st); - pj_log_pop_indent(); - return status; - } + status = create_comp(ice_st, i+1); + if (status != PJ_SUCCESS) { + pj_grp_lock_release(ice_st->grp_lock); + destroy_ice_st(ice_st); + pj_log_pop_indent(); + return status; + } } /* Done with initialization */ @@ -972,9 +971,9 @@ PJ_DEF(pj_status_t) pj_ice_strans_create( const char *name, * on_new_candidate() callback. */ if (ice_st->state==PJ_ICE_STRANS_STATE_READY && - ice_st->cb.on_new_candidate) + ice_st->cb.on_new_candidate) { - (*ice_st->cb.on_new_candidate)(ice_st, NULL, PJ_TRUE); + (*ice_st->cb.on_new_candidate)(ice_st, NULL, PJ_TRUE); } pj_log_pop_indent(); @@ -989,8 +988,8 @@ static void ice_st_on_destroy(void *obj) /* Destroy any previous ICE session */ if (ice_st->ice_prev) { - (*ice_st->ice_prev_hndlr)(ice_st->ice_prev); - ice_st->ice_prev = NULL; + (*ice_st->ice_prev_hndlr)(ice_st->ice_prev); + ice_st->ice_prev = NULL; } PJ_LOG(4,(ice_st->obj_name, "ICE stream transport %p destroyed", obj)); @@ -1006,7 +1005,7 @@ static void destroy_ice_st(pj_ice_strans *ice_st) unsigned i; PJ_LOG(5,(ice_st->obj_name, "ICE stream transport %p destroy request..", - ice_st)); + ice_st)); pj_log_push_indent(); /* Reset callback and user data */ @@ -1016,37 +1015,37 @@ static void destroy_ice_st(pj_ice_strans *ice_st) pj_grp_lock_acquire(ice_st->grp_lock); if (ice_st->destroy_req) { - pj_grp_lock_release(ice_st->grp_lock); - return; + pj_grp_lock_release(ice_st->grp_lock); + return; } ice_st->destroy_req = PJ_TRUE; /* Destroy ICE if we have ICE */ if (ice_st->ice) { - pj_ice_sess *ice = ice_st->ice; - ice_st->ice = NULL; - pj_ice_sess_destroy(ice); + pj_ice_sess *ice = ice_st->ice; + ice_st->ice = NULL; + pj_ice_sess_destroy(ice); } /* Destroy all components */ for (i=0; icomp_cnt; ++i) { - if (ice_st->comp[i]) { - pj_ice_strans_comp *comp = ice_st->comp[i]; - unsigned j; - for (j = 0; j < ice_st->cfg.stun_tp_cnt; ++j) { - if (comp->stun[j].sock) { - pj_stun_sock_destroy(comp->stun[j].sock); - comp->stun[j].sock = NULL; - } - } - for (j = 0; j < ice_st->cfg.turn_tp_cnt; ++j) { - if (comp->turn[j].sock) { - pj_turn_sock_destroy(comp->turn[j].sock); - comp->turn[j].sock = NULL; - } - } - } + if (ice_st->comp[i]) { + pj_ice_strans_comp *comp = ice_st->comp[i]; + unsigned j; + for (j = 0; j < ice_st->cfg.stun_tp_cnt; ++j) { + if (comp->stun[j].sock) { + pj_stun_sock_destroy(comp->stun[j].sock); + comp->stun[j].sock = NULL; + } + } + for (j = 0; j < ice_st->cfg.turn_tp_cnt; ++j) { + if (comp->turn[j].sock) { + pj_turn_sock_destroy(comp->turn[j].sock); + comp->turn[j].sock = NULL; + } + } + } } pj_grp_lock_dec_ref(ice_st->grp_lock); @@ -1065,13 +1064,13 @@ PJ_DEF(pj_ice_strans_state) pj_ice_strans_get_state(pj_ice_strans *ice_st) PJ_DEF(const char*) pj_ice_strans_state_name(pj_ice_strans_state state) { const char *names[] = { - "Null", - "Candidate Gathering", - "Candidate Gathering Complete", - "Session Initialized", - "Negotiation In Progress", - "Negotiation Success", - "Negotiation Failed" + "Null", + "Candidate Gathering", + "Candidate Gathering Complete", + "Session Initialized", + "Negotiation In Progress", + "Negotiation Success", + "Negotiation Failed" }; PJ_ASSERT_RETURN(state <= PJ_ICE_STRANS_STATE_FAILED, "???"); @@ -1080,21 +1079,21 @@ PJ_DEF(const char*) pj_ice_strans_state_name(pj_ice_strans_state state) /* Notification about failure */ static void sess_fail(pj_ice_strans *ice_st, pj_ice_strans_op op, - const char *title, pj_status_t status) + const char *title, pj_status_t status) { PJ_PERROR(4,(ice_st->obj_name, status, title)); pj_log_push_indent(); if (op==PJ_ICE_STRANS_OP_INIT && ice_st->cb_called) { - pj_log_pop_indent(); - return; + pj_log_pop_indent(); + return; } ice_st->cb_called = PJ_TRUE; if (ice_st->cb.on_ice_complete) - (*ice_st->cb.on_ice_complete)(ice_st, op, status); + (*ice_st->cb.on_ice_complete)(ice_st, op, status); pj_log_pop_indent(); } @@ -1107,45 +1106,45 @@ static void sess_init_update(pj_ice_strans *ice_st) /* Ignore if ICE is destroying or init callback has been called */ if (ice_st->destroy_req || ice_st->cb_called) - return; + return; /* Notify application when all candidates have been gathered */ for (i=0; icomp_cnt; ++i) { - unsigned j; - pj_ice_strans_comp *comp = ice_st->comp[i]; - - /* This function can be called when all components or candidates - * have not been created. - */ - if (!comp || comp->creating) { - PJ_LOG(5, (ice_st->obj_name, "ICE init update: creating comp %d", - (comp?comp->comp_id:(i+1)) )); - return; - } - - status = PJ_EUNKNOWN; - for (j=0; jcand_cnt; ++j) { - pj_ice_sess_cand *cand = &comp->cand_list[j]; - - if (cand->status == PJ_EPENDING) { - PJ_LOG(5, (ice_st->obj_name, "ICE init update: " - "comp %d/%d[%s] is pending", - comp->comp_id, j, - pj_ice_get_cand_type_name(cand->type))); - return; - } - - if (status == PJ_EUNKNOWN) { - status = cand->status; - } else { - /* We only need one successful candidate. */ - if (cand->status == PJ_SUCCESS) - status = PJ_SUCCESS; - } - } - - if (status != PJ_SUCCESS) - break; + unsigned j; + pj_ice_strans_comp *comp = ice_st->comp[i]; + + /* This function can be called when all components or candidates + * have not been created. + */ + if (!comp || comp->creating) { + PJ_LOG(5, (ice_st->obj_name, "ICE init update: creating comp %d", + (comp?comp->comp_id:(i+1)) )); + return; + } + + status = PJ_EUNKNOWN; + for (j=0; jcand_cnt; ++j) { + pj_ice_sess_cand *cand = &comp->cand_list[j]; + + if (cand->status == PJ_EPENDING) { + PJ_LOG(5, (ice_st->obj_name, "ICE init update: " + "comp %d/%d[%s] is pending", + comp->comp_id, j, + pj_ice_get_cand_type_name(cand->type))); + return; + } + + if (status == PJ_EUNKNOWN) { + status = cand->status; + } else { + /* We only need one successful candidate. */ + if (cand->status == PJ_SUCCESS) + status = PJ_SUCCESS; + } + } + + if (status != PJ_SUCCESS) + break; } /* All candidates have been gathered or there's no successful @@ -1154,14 +1153,14 @@ static void sess_init_update(pj_ice_strans *ice_st) ice_st->cb_called = PJ_TRUE; ice_st->state = PJ_ICE_STRANS_STATE_READY; if (ice_st->cb.on_ice_complete) - (*ice_st->cb.on_ice_complete)(ice_st, PJ_ICE_STRANS_OP_INIT, - status); + (*ice_st->cb.on_ice_complete)(ice_st, PJ_ICE_STRANS_OP_INIT, + status); /* Tell ICE session that trickling is done */ ice_st->loc_cand_end = PJ_TRUE; if (ice_st->ice && ice_st->ice->is_trickling && ice_st->rem_cand_end) { - pj_ice_sess_update_check_list(ice_st->ice, NULL, NULL, 0, NULL, - PJ_TRUE); + pj_ice_sess_update_check_list(ice_st->ice, NULL, NULL, 0, NULL, + PJ_TRUE); } } @@ -1189,7 +1188,7 @@ PJ_DEF(void*) pj_ice_strans_get_user_data(pj_ice_strans *ice_st) * Get the value of various options of the ICE stream transport. */ PJ_DEF(pj_status_t) pj_ice_strans_get_options( pj_ice_strans *ice_st, - pj_ice_sess_options *opt) + pj_ice_sess_options *opt) { PJ_ASSERT_RETURN(ice_st && opt, PJ_EINVAL); pj_memcpy(opt, &ice_st->cfg.opt, sizeof(*opt)); @@ -1200,12 +1199,12 @@ PJ_DEF(pj_status_t) pj_ice_strans_get_options( pj_ice_strans *ice_st, * Specify various options for this ICE stream transport. */ PJ_DEF(pj_status_t) pj_ice_strans_set_options(pj_ice_strans *ice_st, - const pj_ice_sess_options *opt) + const pj_ice_sess_options *opt) { PJ_ASSERT_RETURN(ice_st && opt, PJ_EINVAL); pj_memcpy(&ice_st->cfg.opt, opt, sizeof(*opt)); if (ice_st->ice) - pj_ice_sess_set_options(ice_st->ice, &ice_st->cfg.opt); + pj_ice_sess_set_options(ice_st->ice, &ice_st->cfg.opt); return PJ_SUCCESS; } @@ -1213,7 +1212,7 @@ PJ_DEF(pj_status_t) pj_ice_strans_set_options(pj_ice_strans *ice_st, * Update number of components of the ICE stream transport. */ PJ_DEF(pj_status_t) pj_ice_strans_update_comp_cnt( pj_ice_strans *ice_st, - unsigned comp_cnt) + unsigned comp_cnt) { unsigned i; @@ -1223,31 +1222,31 @@ PJ_DEF(pj_status_t) pj_ice_strans_update_comp_cnt( pj_ice_strans *ice_st, pj_grp_lock_acquire(ice_st->grp_lock); for (i=comp_cnt; icomp_cnt; ++i) { - pj_ice_strans_comp *comp = ice_st->comp[i]; - unsigned j; - - /* Destroy the component */ - for (j = 0; j < ice_st->cfg.stun_tp_cnt; ++j) { - if (comp->stun[j].sock) { - pj_stun_sock_destroy(comp->stun[j].sock); - comp->stun[j].sock = NULL; - } - } - for (j = 0; j < ice_st->cfg.turn_tp_cnt; ++j) { - if (comp->turn[j].sock) { - pj_turn_sock_destroy(comp->turn[j].sock); - comp->turn[j].sock = NULL; - } - } - comp->cand_cnt = 0; - ice_st->comp[i] = NULL; + pj_ice_strans_comp *comp = ice_st->comp[i]; + unsigned j; + + /* Destroy the component */ + for (j = 0; j < ice_st->cfg.stun_tp_cnt; ++j) { + if (comp->stun[j].sock) { + pj_stun_sock_destroy(comp->stun[j].sock); + comp->stun[j].sock = NULL; + } + } + for (j = 0; j < ice_st->cfg.turn_tp_cnt; ++j) { + if (comp->turn[j].sock) { + pj_turn_sock_destroy(comp->turn[j].sock); + comp->turn[j].sock = NULL; + } + } + comp->cand_cnt = 0; + ice_st->comp[i] = NULL; } ice_st->comp_cnt = comp_cnt; pj_grp_lock_release(ice_st->grp_lock); PJ_LOG(4,(ice_st->obj_name, - "Updated ICE stream transport components number to %d", - comp_cnt)); + "Updated ICE stream transport components number to %d", + comp_cnt)); return PJ_SUCCESS; } @@ -1265,9 +1264,9 @@ PJ_DEF(pj_grp_lock_t *) pj_ice_strans_get_grp_lock(pj_ice_strans *ice_st) * Create ICE! */ PJ_DEF(pj_status_t) pj_ice_strans_init_ice(pj_ice_strans *ice_st, - pj_ice_sess_role role, - const pj_str_t *local_ufrag, - const pj_str_t *local_passwd) + pj_ice_sess_role role, + const pj_str_t *local_ufrag, + const pj_str_t *local_passwd) { pj_status_t status; unsigned i; @@ -1293,18 +1292,18 @@ PJ_DEF(pj_status_t) pj_ice_strans_init_ice(pj_ice_strans *ice_st, * (due to group lock). */ if (ice_st->ice_prev) { - (*ice_st->ice_prev_hndlr)(ice_st->ice_prev); - ice_st->ice_prev = NULL; + (*ice_st->ice_prev_hndlr)(ice_st->ice_prev); + ice_st->ice_prev = NULL; } /* Create! */ status = pj_ice_sess_create(&ice_st->cfg.stun_cfg, ice_st->obj_name, role, - ice_st->comp_cnt, &ice_cb, - local_ufrag, local_passwd, - ice_st->grp_lock, - &ice_st->ice); + ice_st->comp_cnt, &ice_cb, + local_ufrag, local_passwd, + ice_st->grp_lock, + &ice_st->ice); if (status != PJ_SUCCESS) - return status; + return status; /* Associate user data */ ice_st->ice->user_data = (void*)ice_st; @@ -1317,64 +1316,64 @@ PJ_DEF(pj_status_t) pj_ice_strans_init_ice(pj_ice_strans *ice_st, * checked first. */ if (ice_st->comp[0]->cand_list[ice_st->comp[0]->default_cand].type - == PJ_ICE_CAND_TYPE_SRFLX) + == PJ_ICE_CAND_TYPE_SRFLX) { - pj_ice_sess_set_prefs(ice_st->ice, srflx_pref_table); + pj_ice_sess_set_prefs(ice_st->ice, srflx_pref_table); } /* Add components/candidates */ for (i=0; icomp_cnt; ++i) { - unsigned j; - pj_ice_strans_comp *comp = ice_st->comp[i]; - - /* Re-enable logging for Send/Data indications */ - if (ice_st->cfg.turn_tp_cnt) { - PJ_LOG(5,(ice_st->obj_name, - "Enabling STUN Indication logging for " - "component %d", i+1)); - } - for (j = 0; j < ice_st->cfg.turn_tp_cnt; ++j) { - if (comp->turn[j].sock) { - pj_turn_sock_set_log(comp->turn[j].sock, 0xFFFF); - comp->turn[j].log_off = PJ_FALSE; - } - } - - for (j=0; jcand_cnt; ++j) { - pj_ice_sess_cand *cand = &comp->cand_list[j]; - unsigned ice_cand_id; - - /* Skip if candidate is not ready */ - if (cand->status != PJ_SUCCESS) { - PJ_LOG(5,(ice_st->obj_name, - "Candidate %d of comp %d is not added (pending)", - j, i)); - continue; - } - - /* Must have address */ - pj_assert(pj_sockaddr_has_addr(&cand->addr)); - - /* Skip if we are mapped to IPv4 address and this candidate - * is not IPv4. - */ - if (comp->ipv4_mapped && - cand->addr.addr.sa_family != pj_AF_INET()) - { - continue; - } - - /* Add the candidate */ - status = pj_ice_sess_add_cand(ice_st->ice, comp->comp_id, - cand->transport_id, cand->type, - cand->local_pref, - &cand->foundation, &cand->addr, - &cand->base_addr, &cand->rel_addr, - pj_sockaddr_get_len(&cand->addr), - (unsigned*)&ice_cand_id); - if (status != PJ_SUCCESS) - goto on_error; - } + unsigned j; + pj_ice_strans_comp *comp = ice_st->comp[i]; + + /* Re-enable logging for Send/Data indications */ + if (ice_st->cfg.turn_tp_cnt) { + PJ_LOG(5,(ice_st->obj_name, + "Enabling STUN Indication logging for " + "component %d", i+1)); + } + for (j = 0; j < ice_st->cfg.turn_tp_cnt; ++j) { + if (comp->turn[j].sock) { + pj_turn_sock_set_log(comp->turn[j].sock, 0xFFFF); + comp->turn[j].log_off = PJ_FALSE; + } + } + + for (j=0; jcand_cnt; ++j) { + pj_ice_sess_cand *cand = &comp->cand_list[j]; + unsigned ice_cand_id; + + /* Skip if candidate is not ready */ + if (cand->status != PJ_SUCCESS) { + PJ_LOG(5,(ice_st->obj_name, + "Candidate %d of comp %d is not added (pending)", + j, i)); + continue; + } + + /* Must have address */ + pj_assert(pj_sockaddr_has_addr(&cand->addr)); + + /* Skip if we are mapped to IPv4 address and this candidate + * is not IPv4. + */ + if (comp->ipv4_mapped && + cand->addr.addr.sa_family != pj_AF_INET()) + { + continue; + } + + /* Add the candidate */ + status = pj_ice_sess_add_cand(ice_st->ice, comp->comp_id, + cand->transport_id, cand->type, + cand->local_pref, + &cand->foundation, &cand->addr, + &cand->base_addr, &cand->rel_addr, + pj_sockaddr_get_len(&cand->addr), + (unsigned*)&ice_cand_id); + if (status != PJ_SUCCESS) + goto on_error; + } } /* ICE session is ready for negotiation */ @@ -1403,8 +1402,8 @@ PJ_DEF(pj_bool_t) pj_ice_strans_sess_is_running(pj_ice_strans *ice_st) { // Trickle ICE can start ICE before remote candidate list is received return ice_st && ice_st->ice && /* ice_st->ice->rcand_cnt && */ - ice_st->ice->clist.state == PJ_ICE_SESS_CHECKLIST_ST_RUNNING && - !pj_ice_strans_sess_is_complete(ice_st); + ice_st->ice->clist.state == PJ_ICE_SESS_CHECKLIST_ST_RUNNING && + !pj_ice_strans_sess_is_complete(ice_st); } @@ -1425,9 +1424,9 @@ PJ_DEF(unsigned) pj_ice_strans_get_running_comp_cnt(pj_ice_strans *ice_st) PJ_ASSERT_RETURN(ice_st, PJ_EINVAL); if (ice_st->ice && ice_st->ice->rcand_cnt) { - return ice_st->ice->comp_cnt; + return ice_st->ice->comp_cnt; } else { - return ice_st->comp_cnt; + return ice_st->comp_cnt; } } @@ -1436,10 +1435,10 @@ PJ_DEF(unsigned) pj_ice_strans_get_running_comp_cnt(pj_ice_strans *ice_st) * Get the ICE username fragment and password of the ICE session. */ PJ_DEF(pj_status_t) pj_ice_strans_get_ufrag_pwd( pj_ice_strans *ice_st, - pj_str_t *loc_ufrag, - pj_str_t *loc_pwd, - pj_str_t *rem_ufrag, - pj_str_t *rem_pwd) + pj_str_t *loc_ufrag, + pj_str_t *loc_pwd, + pj_str_t *rem_ufrag, + pj_str_t *rem_pwd) { PJ_ASSERT_RETURN(ice_st && ice_st->ice, PJ_EINVALIDOP); @@ -1447,10 +1446,10 @@ PJ_DEF(pj_status_t) pj_ice_strans_get_ufrag_pwd( pj_ice_strans *ice_st, if (loc_pwd) *loc_pwd = ice_st->ice->rx_pass; if (rem_ufrag || rem_pwd) { - // In trickle ICE, remote may send initial SDP with empty candidates - //PJ_ASSERT_RETURN(ice_st->ice->rcand_cnt != 0, PJ_EINVALIDOP); - if (rem_ufrag) *rem_ufrag = ice_st->ice->tx_ufrag; - if (rem_pwd) *rem_pwd = ice_st->ice->tx_pass; + // In trickle ICE, remote may send initial SDP with empty candidates + //PJ_ASSERT_RETURN(ice_st->ice->rcand_cnt != 0, PJ_EINVALIDOP); + if (rem_ufrag) *rem_ufrag = ice_st->ice->tx_ufrag; + if (rem_pwd) *rem_pwd = ice_st->ice->tx_pass; } return PJ_SUCCESS; @@ -1460,18 +1459,18 @@ PJ_DEF(pj_status_t) pj_ice_strans_get_ufrag_pwd( pj_ice_strans *ice_st, * Get number of candidates */ PJ_DEF(unsigned) pj_ice_strans_get_cands_count(pj_ice_strans *ice_st, - unsigned comp_id) + unsigned comp_id) { unsigned i, cnt; PJ_ASSERT_RETURN(ice_st && ice_st->ice && comp_id && - comp_id <= ice_st->comp_cnt, 0); + comp_id <= ice_st->comp_cnt, 0); cnt = 0; for (i=0; iice->lcand_cnt; ++i) { - if (ice_st->ice->lcand[i].comp_id != comp_id) - continue; - ++cnt; + if (ice_st->ice->lcand[i].comp_id != comp_id) + continue; + ++cnt; } return cnt; @@ -1481,22 +1480,22 @@ PJ_DEF(unsigned) pj_ice_strans_get_cands_count(pj_ice_strans *ice_st, * Enum candidates */ PJ_DEF(pj_status_t) pj_ice_strans_enum_cands(pj_ice_strans *ice_st, - unsigned comp_id, - unsigned *count, - pj_ice_sess_cand cand[]) + unsigned comp_id, + unsigned *count, + pj_ice_sess_cand cand[]) { unsigned i, cnt; PJ_ASSERT_RETURN(ice_st && ice_st->ice && comp_id && - comp_id <= ice_st->comp_cnt && count && cand, PJ_EINVAL); + comp_id <= ice_st->comp_cnt && count && cand, PJ_EINVAL); cnt = 0; for (i=0; iice->lcand_cnt && cnt<*count; ++i) { - if (ice_st->ice->lcand[i].comp_id != comp_id) - continue; - pj_memcpy(&cand[cnt], &ice_st->ice->lcand[i], - sizeof(pj_ice_sess_cand)); - ++cnt; + if (ice_st->ice->lcand[i].comp_id != comp_id) + continue; + pj_memcpy(&cand[cnt], &ice_st->ice->lcand[i], + sizeof(pj_ice_sess_cand)); + ++cnt; } *count = cnt; @@ -1507,22 +1506,22 @@ PJ_DEF(pj_status_t) pj_ice_strans_enum_cands(pj_ice_strans *ice_st, * Get default candidate. */ PJ_DEF(pj_status_t) pj_ice_strans_get_def_cand( pj_ice_strans *ice_st, - unsigned comp_id, - pj_ice_sess_cand *cand) + unsigned comp_id, + pj_ice_sess_cand *cand) { const pj_ice_sess_check *valid_pair; PJ_ASSERT_RETURN(ice_st && comp_id && comp_id <= ice_st->comp_cnt && - cand, PJ_EINVAL); + cand, PJ_EINVAL); valid_pair = pj_ice_strans_get_valid_pair(ice_st, comp_id); if (valid_pair) { - pj_memcpy(cand, valid_pair->lcand, sizeof(pj_ice_sess_cand)); + pj_memcpy(cand, valid_pair->lcand, sizeof(pj_ice_sess_cand)); } else { - pj_ice_strans_comp *comp = ice_st->comp[comp_id - 1]; - pj_assert(comp->default_candcand_cnt); - pj_memcpy(cand, &comp->cand_list[comp->default_cand], - sizeof(pj_ice_sess_cand)); + pj_ice_strans_comp *comp = ice_st->comp[comp_id - 1]; + pj_assert(comp->default_candcand_cnt); + pj_memcpy(cand, &comp->cand_list[comp->default_cand], + sizeof(pj_ice_sess_cand)); } return PJ_SUCCESS; } @@ -1540,7 +1539,7 @@ PJ_DEF(pj_ice_sess_role) pj_ice_strans_get_role(pj_ice_strans *ice_st) * Change session role. */ PJ_DEF(pj_status_t) pj_ice_strans_change_role( pj_ice_strans *ice_st, - pj_ice_sess_role new_role) + pj_ice_sess_role new_role) { PJ_ASSERT_RETURN(ice_st && ice_st->ice, PJ_EINVALIDOP); return pj_ice_sess_change_role(ice_st->ice, new_role); @@ -1552,49 +1551,49 @@ static pj_status_t setup_turn_perm( pj_ice_strans *ice_st) pj_status_t status; for (n = 0; n < ice_st->cfg.turn_tp_cnt; ++n) { - unsigned i, comp_cnt; - - comp_cnt = pj_ice_strans_get_running_comp_cnt(ice_st); - for (i=0; icomp[i]; - pj_turn_session_info info; - pj_sockaddr addrs[PJ_ICE_ST_MAX_CAND]; - unsigned j, count=0; - unsigned rem_cand_cnt; - const pj_ice_sess_cand *rem_cand; - - if (!comp->turn[n].sock) - continue; - - status = pj_turn_sock_get_info(comp->turn[n].sock, &info); - if (status != PJ_SUCCESS || info.state != PJ_TURN_STATE_READY) - continue; - - /* Gather remote addresses for this component */ - rem_cand_cnt = ice_st->ice->rcand_cnt; - rem_cand = ice_st->ice->rcand; - if (status != PJ_SUCCESS) - continue; - - for (j=0; jcfg.turn_tp[n].af) - { - pj_sockaddr_cp(&addrs[count++], &rem_cand[j].addr); - } - } - - if (count && !comp->turn[n].err_cnt && comp->turn[n].sock) { - status = pj_turn_sock_set_perm( - comp->turn[n].sock, count, - addrs, PJ_ICE_ST_USE_TURN_PERMANENT_PERM); - if (status != PJ_SUCCESS) { - pj_ice_strans_stop_ice(ice_st); - return status; - } - } - } + unsigned i, comp_cnt; + + comp_cnt = pj_ice_strans_get_running_comp_cnt(ice_st); + for (i=0; icomp[i]; + pj_turn_session_info info; + pj_sockaddr addrs[PJ_ICE_ST_MAX_CAND]; + unsigned j, count=0; + unsigned rem_cand_cnt; + const pj_ice_sess_cand *rem_cand; + + if (!comp->turn[n].sock) + continue; + + status = pj_turn_sock_get_info(comp->turn[n].sock, &info); + if (status != PJ_SUCCESS || info.state != PJ_TURN_STATE_READY) + continue; + + /* Gather remote addresses for this component */ + rem_cand_cnt = ice_st->ice->rcand_cnt; + rem_cand = ice_st->ice->rcand; + if (status != PJ_SUCCESS) + continue; + + for (j=0; jcfg.turn_tp[n].af) + { + pj_sockaddr_cp(&addrs[count++], &rem_cand[j].addr); + } + } + + if (count && !comp->turn[n].err_cnt && comp->turn[n].sock) { + status = pj_turn_sock_set_perm( + comp->turn[n].sock, count, + addrs, PJ_ICE_ST_USE_TURN_PERMANENT_PERM); + if (status != PJ_SUCCESS) { + pj_ice_strans_stop_ice(ice_st); + return status; + } + } + } } return PJ_SUCCESS; @@ -1604,10 +1603,10 @@ static pj_status_t setup_turn_perm( pj_ice_strans *ice_st) * Start ICE processing ! */ PJ_DEF(pj_status_t) pj_ice_strans_start_ice( pj_ice_strans *ice_st, - const pj_str_t *rem_ufrag, - const pj_str_t *rem_passwd, - unsigned rem_cand_cnt, - const pj_ice_sess_cand rem_cand[]) + const pj_str_t *rem_ufrag, + const pj_str_t *rem_passwd, + unsigned rem_cand_cnt, + const pj_ice_sess_cand rem_cand[]) { pj_status_t status; @@ -1619,23 +1618,23 @@ PJ_DEF(pj_status_t) pj_ice_strans_start_ice( pj_ice_strans *ice_st, /* Update check list */ status = pj_ice_strans_update_check_list(ice_st, rem_ufrag, rem_passwd, - rem_cand_cnt, rem_cand, - !ice_st->ice->is_trickling); + rem_cand_cnt, rem_cand, + !ice_st->ice->is_trickling); if (status != PJ_SUCCESS) - return status; + return status; /* If we have TURN candidate, now is the time to create the permissions */ status = setup_turn_perm(ice_st); if (status != PJ_SUCCESS) { - pj_ice_strans_stop_ice(ice_st); - return status; + pj_ice_strans_stop_ice(ice_st); + return status; } /* Start ICE negotiation! */ status = pj_ice_sess_start_check(ice_st->ice); if (status != PJ_SUCCESS) { - pj_ice_strans_stop_ice(ice_st); - return status; + pj_ice_strans_stop_ice(ice_st); + return status; } ice_st->state = PJ_ICE_STRANS_STATE_NEGO; @@ -1648,19 +1647,19 @@ PJ_DEF(pj_status_t) pj_ice_strans_start_ice( pj_ice_strans *ice_st, * or receiving update of remote ICE candidates in trickle ICE. */ PJ_DEF(pj_status_t) pj_ice_strans_update_check_list( - pj_ice_strans *ice_st, - const pj_str_t *rem_ufrag, - const pj_str_t *rem_passwd, - unsigned rem_cand_cnt, - const pj_ice_sess_cand rem_cand[], - pj_bool_t rcand_end) + pj_ice_strans *ice_st, + const pj_str_t *rem_ufrag, + const pj_str_t *rem_passwd, + unsigned rem_cand_cnt, + const pj_ice_sess_cand rem_cand[], + pj_bool_t rcand_end) { pj_bool_t checklist_created; pj_status_t status; PJ_ASSERT_RETURN(ice_st && ((rem_cand_cnt==0) || - (rem_ufrag && rem_passwd && rem_cand)), - PJ_EINVAL); + (rem_ufrag && rem_passwd && rem_cand)), + PJ_EINVAL); PJ_ASSERT_RETURN(ice_st->ice, PJ_EINVALIDOP); pj_grp_lock_acquire(ice_st->grp_lock); @@ -1669,43 +1668,43 @@ PJ_DEF(pj_status_t) pj_ice_strans_update_check_list( /* Create checklist (if not yet) */ if (rem_ufrag && !checklist_created) { - status = pj_ice_sess_create_check_list(ice_st->ice, rem_ufrag, - rem_passwd, rem_cand_cnt, - rem_cand); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(ice_st->obj_name, status, - "Failed setting up remote ufrag")); - pj_grp_lock_release(ice_st->grp_lock); - return status; - } + status = pj_ice_sess_create_check_list(ice_st->ice, rem_ufrag, + rem_passwd, rem_cand_cnt, + rem_cand); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(ice_st->obj_name, status, + "Failed setting up remote ufrag")); + pj_grp_lock_release(ice_st->grp_lock); + return status; + } } /* Update checklist for trickling ICE */ if (ice_st->ice->is_trickling) { - if (rcand_end && !ice_st->rem_cand_end) - ice_st->rem_cand_end = PJ_TRUE; - - status = pj_ice_sess_update_check_list( - ice_st->ice, rem_ufrag, rem_passwd, - (checklist_created? rem_cand_cnt:0), rem_cand, - (ice_st->rem_cand_end && ice_st->loc_cand_end)); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(ice_st->obj_name, status, - "Failed updating checklist")); - pj_grp_lock_release(ice_st->grp_lock); - return status; - } + if (rcand_end && !ice_st->rem_cand_end) + ice_st->rem_cand_end = PJ_TRUE; + + status = pj_ice_sess_update_check_list( + ice_st->ice, rem_ufrag, rem_passwd, + (checklist_created? rem_cand_cnt:0), rem_cand, + (ice_st->rem_cand_end && ice_st->loc_cand_end)); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(ice_st->obj_name, status, + "Failed updating checklist")); + pj_grp_lock_release(ice_st->grp_lock); + return status; + } } /* Update TURN permissions if periodic check has been started. */ if (pj_ice_strans_sess_is_running(ice_st)) { - status = setup_turn_perm(ice_st); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(ice_st->obj_name, status, - "Failed setting up TURN permission")); - pj_grp_lock_release(ice_st->grp_lock); - return status; - } + status = setup_turn_perm(ice_st); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(ice_st->obj_name, status, + "Failed setting up TURN permission")); + pj_grp_lock_release(ice_st->grp_lock); + return status; + } } pj_grp_lock_release(ice_st->grp_lock); @@ -1719,13 +1718,13 @@ PJ_DEF(pj_status_t) pj_ice_strans_update_check_list( */ PJ_DEF(const pj_ice_sess_check*) pj_ice_strans_get_valid_pair(const pj_ice_strans *ice_st, - unsigned comp_id) + unsigned comp_id) { PJ_ASSERT_RETURN(ice_st && comp_id && comp_id <= ice_st->comp_cnt, - NULL); + NULL); if (ice_st->ice == NULL) - return NULL; + return NULL; return ice_st->ice->comp[comp_id-1].valid_check; } @@ -1744,10 +1743,10 @@ PJ_DEF(pj_status_t) pj_ice_strans_stop_ice(pj_ice_strans *ice_st) pj_grp_lock_acquire(ice_st->grp_lock); if (ice_st->ice) { - ice_st->ice_prev = ice_st->ice; - ice_st->ice = NULL; - pj_ice_sess_detach_grp_lock(ice_st->ice_prev, &ice_st->ice_prev_hndlr); - pj_ice_sess_destroy(ice_st->ice_prev); + ice_st->ice_prev = ice_st->ice; + ice_st->ice = NULL; + pj_ice_sess_detach_grp_lock(ice_st->ice_prev, &ice_st->ice_prev_hndlr); + pj_ice_sess_destroy(ice_st->ice_prev); } ice_st->state = PJ_ICE_STRANS_STATE_INIT; @@ -1758,12 +1757,12 @@ PJ_DEF(pj_status_t) pj_ice_strans_stop_ice(pj_ice_strans *ice_st) } static pj_status_t use_buffer( pj_ice_strans *ice_st, - unsigned comp_id, - const void *data, - pj_size_t data_len, - const pj_sockaddr_t *dst_addr, - int dst_addr_len, - void **buffer ) + unsigned comp_id, + const void *data, + pj_size_t data_len, + const pj_sockaddr_t *dst_addr, + int dst_addr_len, + void **buffer ) { unsigned idx; pj_status_t status; @@ -1771,11 +1770,11 @@ static pj_status_t use_buffer( pj_ice_strans *ice_st, /* Allocate send buffer, if necessary. */ status = alloc_send_buf(ice_st, (unsigned)data_len); if (status != PJ_SUCCESS) - return status; + return status; if (ice_st->is_pending && ice_st->empty_idx == ice_st->buf_idx) { - /* We don't use buffer or there's no more empty buffer. */ - return PJ_EBUSY; + /* We don't use buffer or there's no more empty buffer. */ + return PJ_EBUSY; } idx = ice_st->empty_idx; @@ -1790,7 +1789,7 @@ static pj_status_t use_buffer( pj_ice_strans *ice_st, if (ice_st->is_pending) { /* We'll continue later since there's still a pending send. */ - return PJ_EPENDING; + return PJ_EPENDING; } ice_st->is_pending = PJ_TRUE; @@ -1803,13 +1802,13 @@ static pj_status_t use_buffer( pj_ice_strans *ice_st, * Application wants to send outgoing packet. */ static pj_status_t send_data(pj_ice_strans *ice_st, - unsigned comp_id, - const void *data, - pj_size_t data_len, - const pj_sockaddr_t *dst_addr, - int dst_addr_len, - pj_bool_t use_buf, - pj_bool_t call_cb) + unsigned comp_id, + const void *data, + pj_size_t data_len, + const pj_sockaddr_t *dst_addr, + int dst_addr_len, + pj_bool_t use_buf, + pj_bool_t call_cb) { pj_ice_strans_comp *comp; pj_ice_sess_cand *def_cand; @@ -1817,16 +1816,16 @@ static pj_status_t send_data(pj_ice_strans *ice_st, pj_status_t status; PJ_ASSERT_RETURN(ice_st && comp_id && comp_id <= ice_st->comp_cnt && - dst_addr && dst_addr_len, PJ_EINVAL); + dst_addr && dst_addr_len, PJ_EINVAL); comp = ice_st->comp[comp_id-1]; /* Check that default candidate for the component exists */ if (comp->default_cand >= comp->cand_cnt) { - status = PJ_EINVALIDOP; - if (call_cb) - on_data_sent(ice_st, -status); - return status; + status = PJ_EINVALIDOP; + if (call_cb) + on_data_sent(ice_st, -status); + return status; } /* Protect with group lock, since this may cause race condition with @@ -1836,13 +1835,13 @@ static pj_status_t send_data(pj_ice_strans *ice_st, pj_grp_lock_acquire(ice_st->grp_lock); if (use_buf && ice_st->num_buf > 0) { - status = use_buffer(ice_st, comp_id, data, data_len, dst_addr, - dst_addr_len, &buf); + status = use_buffer(ice_st, comp_id, data, data_len, dst_addr, + dst_addr_len, &buf); - if (status == PJ_EPENDING || status != PJ_SUCCESS) { - pj_grp_lock_release(ice_st->grp_lock); - return status; - } + if (status == PJ_EPENDING || status != PJ_SUCCESS) { + pj_grp_lock_release(ice_st->grp_lock); + return status; + } } /* If ICE is available, send data with ICE. If ICE nego is not completed @@ -1854,11 +1853,11 @@ static pj_status_t send_data(pj_ice_strans *ice_st, * Once ICE has failed, also send data with the default candidate. */ if (ice_st->ice && ice_st->state <= PJ_ICE_STRANS_STATE_RUNNING) { - status = pj_ice_sess_send_data(ice_st->ice, comp_id, buf, data_len); - if (status == PJ_SUCCESS || status == PJ_EPENDING) { - pj_grp_lock_release(ice_st->grp_lock); - goto on_return; - } + status = pj_ice_sess_send_data(ice_st->ice, comp_id, buf, data_len); + if (status == PJ_SUCCESS || status == PJ_EPENDING) { + pj_grp_lock_release(ice_st->grp_lock); + goto on_return; + } } pj_grp_lock_release(ice_st->grp_lock); @@ -1866,81 +1865,81 @@ static pj_status_t send_data(pj_ice_strans *ice_st, def_cand = &comp->cand_list[comp->default_cand]; if (def_cand->status == PJ_SUCCESS) { - unsigned tp_idx = GET_TP_IDX(def_cand->transport_id); - - if (def_cand->type == PJ_ICE_CAND_TYPE_RELAYED) { - - enum { - msg_disable_ind = 0xFFFF & - ~(PJ_STUN_SESS_LOG_TX_IND| - PJ_STUN_SESS_LOG_RX_IND) - }; - - /* https://github.com/pjsip/pjproject/issues/1316 */ - if (comp->turn[tp_idx].sock == NULL) { - /* TURN socket error */ - status = PJ_EINVALIDOP; - goto on_return; - } - - if (!comp->turn[tp_idx].log_off) { - /* Disable logging for Send/Data indications */ - PJ_LOG(5,(ice_st->obj_name, - "Disabling STUN Indication logging for " - "component %d", comp->comp_id)); - pj_turn_sock_set_log(comp->turn[tp_idx].sock, - msg_disable_ind); - comp->turn[tp_idx].log_off = PJ_TRUE; - } - - status = pj_turn_sock_sendto(comp->turn[tp_idx].sock, - (const pj_uint8_t*)buf, - (unsigned)data_len, - dst_addr, dst_addr_len); - goto on_return; - } else { - const pj_sockaddr_t *dest_addr; - unsigned dest_addr_len; - - if (comp->ipv4_mapped) { - if (comp->synth_addr_len == 0 || - pj_sockaddr_cmp(&comp->dst_addr, dst_addr) != 0) - { - status = pj_sockaddr_synthesize(pj_AF_INET6(), - &comp->synth_addr, - dst_addr); - if (status != PJ_SUCCESS) - goto on_return; - - pj_sockaddr_cp(&comp->dst_addr, dst_addr); - comp->synth_addr_len = pj_sockaddr_get_len( - &comp->synth_addr); - } - dest_addr = &comp->synth_addr; - dest_addr_len = comp->synth_addr_len; - } else { - dest_addr = dst_addr; - dest_addr_len = dst_addr_len; - } - - status = pj_stun_sock_sendto(comp->stun[tp_idx].sock, NULL, buf, - (unsigned)data_len, 0, dest_addr, - dest_addr_len); - goto on_return; - } + unsigned tp_idx = GET_TP_IDX(def_cand->transport_id); + + if (def_cand->type == PJ_ICE_CAND_TYPE_RELAYED) { + + enum { + msg_disable_ind = 0xFFFF & + ~(PJ_STUN_SESS_LOG_TX_IND| + PJ_STUN_SESS_LOG_RX_IND) + }; + + /* https://github.com/pjsip/pjproject/issues/1316 */ + if (comp->turn[tp_idx].sock == NULL) { + /* TURN socket error */ + status = PJ_EINVALIDOP; + goto on_return; + } + + if (!comp->turn[tp_idx].log_off) { + /* Disable logging for Send/Data indications */ + PJ_LOG(5,(ice_st->obj_name, + "Disabling STUN Indication logging for " + "component %d", comp->comp_id)); + pj_turn_sock_set_log(comp->turn[tp_idx].sock, + msg_disable_ind); + comp->turn[tp_idx].log_off = PJ_TRUE; + } + + status = pj_turn_sock_sendto(comp->turn[tp_idx].sock, + (const pj_uint8_t*)buf, + (unsigned)data_len, + dst_addr, dst_addr_len); + goto on_return; + } else { + const pj_sockaddr_t *dest_addr; + unsigned dest_addr_len; + + if (comp->ipv4_mapped) { + if (comp->synth_addr_len == 0 || + pj_sockaddr_cmp(&comp->dst_addr, dst_addr) != 0) + { + status = pj_sockaddr_synthesize(pj_AF_INET6(), + &comp->synth_addr, + dst_addr); + if (status != PJ_SUCCESS) + goto on_return; + + pj_sockaddr_cp(&comp->dst_addr, dst_addr); + comp->synth_addr_len = pj_sockaddr_get_len( + &comp->synth_addr); + } + dest_addr = &comp->synth_addr; + dest_addr_len = comp->synth_addr_len; + } else { + dest_addr = dst_addr; + dest_addr_len = dst_addr_len; + } + + status = pj_stun_sock_sendto(comp->stun[tp_idx].sock, NULL, buf, + (unsigned)data_len, 0, dest_addr, + dest_addr_len); + goto on_return; + } } else - status = PJ_EINVALIDOP; + status = PJ_EINVALIDOP; on_return: /* We continue later in on_data_sent() callback. */ if (status == PJ_EPENDING) - return status; + return status; if (call_cb) { - on_data_sent(ice_st, (status == PJ_SUCCESS? data_len: -status)); + on_data_sent(ice_st, (status == PJ_SUCCESS? data_len: -status)); } else { - check_pending_send(ice_st); + check_pending_send(ice_st); } return status; @@ -1952,21 +1951,21 @@ static pj_status_t send_data(pj_ice_strans *ice_st, * Application wants to send outgoing packet. */ PJ_DEF(pj_status_t) pj_ice_strans_sendto( pj_ice_strans *ice_st, - unsigned comp_id, - const void *data, - pj_size_t data_len, - const pj_sockaddr_t *dst_addr, - int dst_addr_len) + unsigned comp_id, + const void *data, + pj_size_t data_len, + const pj_sockaddr_t *dst_addr, + int dst_addr_len) { pj_status_t status; PJ_LOG(1, (ice_st->obj_name, "pj_ice_strans_sendto() is deprecated. " - "Application is recommended to use " - "pj_ice_strans_sendto2() instead.")); + "Application is recommended to use " + "pj_ice_strans_sendto2() instead.")); status = send_data(ice_st, comp_id, data, data_len, dst_addr, - dst_addr_len, PJ_TRUE, PJ_FALSE); + dst_addr_len, PJ_TRUE, PJ_FALSE); if (status == PJ_EPENDING) - status = PJ_SUCCESS; + status = PJ_SUCCESS; return status; } @@ -1977,15 +1976,15 @@ PJ_DEF(pj_status_t) pj_ice_strans_sendto( pj_ice_strans *ice_st, * Application wants to send outgoing packet. */ PJ_DEF(pj_status_t) pj_ice_strans_sendto2(pj_ice_strans *ice_st, - unsigned comp_id, - const void *data, - pj_size_t data_len, - const pj_sockaddr_t *dst_addr, - int dst_addr_len) + unsigned comp_id, + const void *data, + pj_size_t data_len, + const pj_sockaddr_t *dst_addr, + int dst_addr_len) { ice_st->call_send_cb = PJ_TRUE; return send_data(ice_st, comp_id, data, data_len, dst_addr, - dst_addr_len, PJ_TRUE, PJ_FALSE); + dst_addr_len, PJ_TRUE, PJ_FALSE); } static void on_valid_pair(pj_ice_sess *ice) @@ -2003,67 +2002,67 @@ static void on_valid_pair(pj_ice_sess *ice) msec = PJ_TIME_VAL_MSEC(t); if (cb.on_valid_pair) { - unsigned i; - enum { - msg_disable_ind = 0xFFFF & ~(PJ_STUN_SESS_LOG_TX_IND | - PJ_STUN_SESS_LOG_RX_IND) - }; - - PJ_LOG(4, - (ice_st->obj_name, "First ICE candidate nominated in %ds:%03d", - msec / 1000, msec % 1000)); - - for (i = 0; i < ice_st->comp_cnt; ++i) { - const pj_ice_sess_check *check; - pj_ice_strans_comp *comp = ice_st->comp[i]; - - check = pj_ice_strans_get_valid_pair(ice_st, i + 1); - if (check) { - char lip[PJ_INET6_ADDRSTRLEN + 10]; - char rip[PJ_INET6_ADDRSTRLEN + 10]; - unsigned tp_idx = GET_TP_IDX(check->lcand->transport_id); - unsigned tp_typ = GET_TP_TYPE(check->lcand->transport_id); - - pj_sockaddr_print(&check->lcand->addr, lip, sizeof(lip), 3); - pj_sockaddr_print(&check->rcand->addr, rip, sizeof(rip), 3); - - if (tp_typ == TP_TURN) { - /* Activate channel binding for the remote address - * for more efficient data transfer using TURN. - */ - status = pj_turn_sock_bind_channel( - comp->turn[tp_idx].sock, &check->rcand->addr, - sizeof(check->rcand->addr)); - - /* Disable logging for Send/Data indications */ - PJ_LOG(5, (ice_st->obj_name, - "Disabling STUN Indication logging for " - "component %d", - i + 1)); - pj_turn_sock_set_log(comp->turn[tp_idx].sock, - msg_disable_ind); - comp->turn[tp_idx].log_off = PJ_TRUE; - } - - PJ_LOG(4, (ice_st->obj_name, - " Comp %d: " - "sending from %s candidate %s to " - "%s candidate %s", - i + 1, pj_ice_get_cand_type_name(check->lcand->type), - lip, pj_ice_get_cand_type_name(check->rcand->type), - rip)); - - } else { - PJ_LOG(4, (ice_st->obj_name, "Comp %d: disabled", i + 1)); - } - } - - ice_st->state = (status == PJ_SUCCESS) ? PJ_ICE_STRANS_STATE_RUNNING : - PJ_ICE_STRANS_STATE_FAILED; - - pj_log_push_indent(); - (*cb.on_valid_pair)(ice_st); - pj_log_pop_indent(); + unsigned i; + enum { + msg_disable_ind = 0xFFFF & ~(PJ_STUN_SESS_LOG_TX_IND | + PJ_STUN_SESS_LOG_RX_IND) + }; + + PJ_LOG(4, + (ice_st->obj_name, "First ICE candidate nominated in %ds:%03d", + msec / 1000, msec % 1000)); + + for (i = 0; i < ice_st->comp_cnt; ++i) { + const pj_ice_sess_check *check; + pj_ice_strans_comp *comp = ice_st->comp[i]; + + check = pj_ice_strans_get_valid_pair(ice_st, i + 1); + if (check) { + char lip[PJ_INET6_ADDRSTRLEN + 10]; + char rip[PJ_INET6_ADDRSTRLEN + 10]; + unsigned tp_idx = GET_TP_IDX(check->lcand->transport_id); + unsigned tp_typ = GET_TP_TYPE(check->lcand->transport_id); + + pj_sockaddr_print(&check->lcand->addr, lip, sizeof(lip), 3); + pj_sockaddr_print(&check->rcand->addr, rip, sizeof(rip), 3); + + if (tp_typ == TP_TURN) { + /* Activate channel binding for the remote address + * for more efficient data transfer using TURN. + */ + status = pj_turn_sock_bind_channel( + comp->turn[tp_idx].sock, &check->rcand->addr, + sizeof(check->rcand->addr)); + + /* Disable logging for Send/Data indications */ + PJ_LOG(5, (ice_st->obj_name, + "Disabling STUN Indication logging for " + "component %d", + i + 1)); + pj_turn_sock_set_log(comp->turn[tp_idx].sock, + msg_disable_ind); + comp->turn[tp_idx].log_off = PJ_TRUE; + } + + PJ_LOG(4, (ice_st->obj_name, + " Comp %d: " + "sending from %s candidate %s to " + "%s candidate %s", + i + 1, pj_ice_get_cand_type_name(check->lcand->type), + lip, pj_ice_get_cand_type_name(check->rcand->type), + rip)); + + } else { + PJ_LOG(4, (ice_st->obj_name, "Comp %d: disabled", i + 1)); + } + } + + ice_st->state = (status == PJ_SUCCESS) ? PJ_ICE_STRANS_STATE_RUNNING : + PJ_ICE_STRANS_STATE_FAILED; + + pj_log_push_indent(); + (*cb.on_valid_pair)(ice_st); + pj_log_pop_indent(); } pj_grp_lock_dec_ref(ice_st->grp_lock); @@ -2087,78 +2086,78 @@ static void on_ice_complete(pj_ice_sess *ice, pj_status_t status) msec = PJ_TIME_VAL_MSEC(t); if (cb.on_ice_complete) { - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(ice_st->obj_name, status, - "ICE negotiation failed after %ds:%03d", - msec/1000, msec%1000)); - } else { - unsigned i; - enum { - msg_disable_ind = 0xFFFF & - ~(PJ_STUN_SESS_LOG_TX_IND| - PJ_STUN_SESS_LOG_RX_IND) - }; - - PJ_LOG(4,(ice_st->obj_name, - "ICE negotiation success after %ds:%03d", - msec/1000, msec%1000)); - - for (i=0; icomp_cnt; ++i) { - const pj_ice_sess_check *check; - pj_ice_strans_comp *comp = ice_st->comp[i]; - - check = pj_ice_strans_get_valid_pair(ice_st, i+1); - if (check) { - char lip[PJ_INET6_ADDRSTRLEN+10]; - char rip[PJ_INET6_ADDRSTRLEN+10]; - unsigned tp_idx = GET_TP_IDX(check->lcand->transport_id); - unsigned tp_typ = GET_TP_TYPE(check->lcand->transport_id); - - pj_sockaddr_print(&check->lcand->addr, lip, - sizeof(lip), 3); - pj_sockaddr_print(&check->rcand->addr, rip, - sizeof(rip), 3); - - if (tp_typ == TP_TURN) { - /* Activate channel binding for the remote address - * for more efficient data transfer using TURN. - */ - status = pj_turn_sock_bind_channel( - comp->turn[tp_idx].sock, - &check->rcand->addr, - sizeof(check->rcand->addr)); - - /* Disable logging for Send/Data indications */ - PJ_LOG(5,(ice_st->obj_name, - "Disabling STUN Indication logging for " - "component %d", i+1)); - pj_turn_sock_set_log(comp->turn[tp_idx].sock, - msg_disable_ind); - comp->turn[tp_idx].log_off = PJ_TRUE; - } - - PJ_LOG(4,(ice_st->obj_name, " Comp %d: " - "sending from %s candidate %s to " - "%s candidate %s", - i+1, - pj_ice_get_cand_type_name(check->lcand->type), - lip, - pj_ice_get_cand_type_name(check->rcand->type), - rip)); - - } else { - PJ_LOG(4,(ice_st->obj_name, - "Comp %d: disabled", i+1)); - } - } - } - - ice_st->state = (status==PJ_SUCCESS) ? PJ_ICE_STRANS_STATE_RUNNING : - PJ_ICE_STRANS_STATE_FAILED; - - pj_log_push_indent(); - (*cb.on_ice_complete)(ice_st, PJ_ICE_STRANS_OP_NEGOTIATION, status); - pj_log_pop_indent(); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(ice_st->obj_name, status, + "ICE negotiation failed after %ds:%03d", + msec/1000, msec%1000)); + } else { + unsigned i; + enum { + msg_disable_ind = 0xFFFF & + ~(PJ_STUN_SESS_LOG_TX_IND| + PJ_STUN_SESS_LOG_RX_IND) + }; + + PJ_LOG(4,(ice_st->obj_name, + "ICE negotiation success after %ds:%03d", + msec/1000, msec%1000)); + + for (i=0; icomp_cnt; ++i) { + const pj_ice_sess_check *check; + pj_ice_strans_comp *comp = ice_st->comp[i]; + + check = pj_ice_strans_get_valid_pair(ice_st, i+1); + if (check) { + char lip[PJ_INET6_ADDRSTRLEN+10]; + char rip[PJ_INET6_ADDRSTRLEN+10]; + unsigned tp_idx = GET_TP_IDX(check->lcand->transport_id); + unsigned tp_typ = GET_TP_TYPE(check->lcand->transport_id); + + pj_sockaddr_print(&check->lcand->addr, lip, + sizeof(lip), 3); + pj_sockaddr_print(&check->rcand->addr, rip, + sizeof(rip), 3); + + if (tp_typ == TP_TURN) { + /* Activate channel binding for the remote address + * for more efficient data transfer using TURN. + */ + status = pj_turn_sock_bind_channel( + comp->turn[tp_idx].sock, + &check->rcand->addr, + sizeof(check->rcand->addr)); + + /* Disable logging for Send/Data indications */ + PJ_LOG(5,(ice_st->obj_name, + "Disabling STUN Indication logging for " + "component %d", i+1)); + pj_turn_sock_set_log(comp->turn[tp_idx].sock, + msg_disable_ind); + comp->turn[tp_idx].log_off = PJ_TRUE; + } + + PJ_LOG(4,(ice_st->obj_name, " Comp %d: " + "sending from %s candidate %s to " + "%s candidate %s", + i+1, + pj_ice_get_cand_type_name(check->lcand->type), + lip, + pj_ice_get_cand_type_name(check->rcand->type), + rip)); + + } else { + PJ_LOG(4,(ice_st->obj_name, + "Comp %d: disabled", i+1)); + } + } + } + + ice_st->state = (status==PJ_SUCCESS) ? PJ_ICE_STRANS_STATE_RUNNING : + PJ_ICE_STRANS_STATE_FAILED; + + pj_log_push_indent(); + (*cb.on_ice_complete)(ice_st, PJ_ICE_STRANS_OP_NEGOTIATION, status); + pj_log_pop_indent(); } @@ -2169,11 +2168,11 @@ static void on_ice_complete(pj_ice_sess *ice, pj_status_t status) * Callback called by ICE session when it wants to send outgoing packet. */ static pj_status_t ice_tx_pkt(pj_ice_sess *ice, - unsigned comp_id, - unsigned transport_id, - const void *pkt, pj_size_t size, - const pj_sockaddr_t *dst_addr, - unsigned dst_addr_len) + unsigned comp_id, + unsigned transport_id, + const void *pkt, pj_size_t size, + const pj_sockaddr_t *dst_addr, + unsigned dst_addr_len) { pj_ice_strans *ice_st = (pj_ice_strans*)ice->user_data; pj_ice_strans_comp *comp; @@ -2194,74 +2193,74 @@ static pj_status_t ice_tx_pkt(pj_ice_sess *ice, ice_st->send_buf[ice_st->buf_idx].buffer != pkt)) { use_buf = PJ_TRUE; - status = use_buffer(ice_st, comp_id, pkt, size, dst_addr, - dst_addr_len, &buf); - if (status == PJ_EPENDING || status != PJ_SUCCESS) { - pj_grp_lock_release(ice_st->grp_lock); - return status; - } + status = use_buffer(ice_st, comp_id, pkt, size, dst_addr, + dst_addr_len, &buf); + if (status == PJ_EPENDING || status != PJ_SUCCESS) { + pj_grp_lock_release(ice_st->grp_lock); + return status; + } } pj_grp_lock_release(ice_st->grp_lock); comp = ice_st->comp[comp_id-1]; TRACE_PKT((comp->ice_st->obj_name, - "Component %d TX packet to %s:%d with transport %d", - comp_id, - pj_sockaddr_print(dst_addr, daddr, sizeof(addr), 2), - pj_sockaddr_get_port(dst_addr), - tp_typ)); + "Component %d TX packet to %s:%d with transport %d", + comp_id, + pj_sockaddr_print(dst_addr, daddr, sizeof(addr), 2), + pj_sockaddr_get_port(dst_addr), + tp_typ)); if (tp_typ == TP_TURN) { - if (comp->turn[tp_idx].sock) { - status = pj_turn_sock_sendto(comp->turn[tp_idx].sock, - (const pj_uint8_t*)buf, - (unsigned)size, - dst_addr, dst_addr_len); - } else { - status = PJ_EINVALIDOP; - } + if (comp->turn[tp_idx].sock) { + status = pj_turn_sock_sendto(comp->turn[tp_idx].sock, + (const pj_uint8_t*)buf, + (unsigned)size, + dst_addr, dst_addr_len); + } else { + status = PJ_EINVALIDOP; + } } else if (tp_typ == TP_STUN) { - const pj_sockaddr_t *dest_addr; - unsigned dest_addr_len; - - if (comp->ipv4_mapped) { - if (comp->synth_addr_len == 0 || - pj_sockaddr_cmp(&comp->dst_addr, dst_addr) != 0) - { - status = pj_sockaddr_synthesize(pj_AF_INET6(), - &comp->synth_addr, dst_addr); - if (status != PJ_SUCCESS) { - goto on_return; - } - - pj_sockaddr_cp(&comp->dst_addr, dst_addr); - comp->synth_addr_len = pj_sockaddr_get_len(&comp->synth_addr); - } - dest_addr = &comp->synth_addr; - dest_addr_len = comp->synth_addr_len; - } else { - dest_addr = dst_addr; - dest_addr_len = dst_addr_len; - } - - status = pj_stun_sock_sendto(comp->stun[tp_idx].sock, NULL, - buf, (unsigned)size, 0, - dest_addr, dest_addr_len); + const pj_sockaddr_t *dest_addr; + unsigned dest_addr_len; + + if (comp->ipv4_mapped) { + if (comp->synth_addr_len == 0 || + pj_sockaddr_cmp(&comp->dst_addr, dst_addr) != 0) + { + status = pj_sockaddr_synthesize(pj_AF_INET6(), + &comp->synth_addr, dst_addr); + if (status != PJ_SUCCESS) { + goto on_return; + } + + pj_sockaddr_cp(&comp->dst_addr, dst_addr); + comp->synth_addr_len = pj_sockaddr_get_len(&comp->synth_addr); + } + dest_addr = &comp->synth_addr; + dest_addr_len = comp->synth_addr_len; + } else { + dest_addr = dst_addr; + dest_addr_len = dst_addr_len; + } + + status = pj_stun_sock_sendto(comp->stun[tp_idx].sock, NULL, + buf, (unsigned)size, 0, + dest_addr, dest_addr_len); } else { - pj_assert(!"Invalid transport ID"); - status = PJ_EINVALIDOP; + pj_assert(!"Invalid transport ID"); + status = PJ_EINVALIDOP; } on_return: if (use_buf && status != PJ_EPENDING) { pj_grp_lock_acquire(ice_st->grp_lock); - if (ice_st->num_buf > 0) { - ice_st->buf_idx = (ice_st->buf_idx + 1) % ice_st->num_buf; - pj_assert(ice_st->buf_idx == ice_st->empty_idx); - } - ice_st->is_pending = PJ_FALSE; - pj_grp_lock_release(ice_st->grp_lock); + if (ice_st->num_buf > 0) { + ice_st->buf_idx = (ice_st->buf_idx + 1) % ice_st->num_buf; + pj_assert(ice_st->buf_idx == ice_st->empty_idx); + } + ice_st->is_pending = PJ_FALSE; + pj_grp_lock_release(ice_st->grp_lock); } return status; @@ -2271,19 +2270,19 @@ static pj_status_t ice_tx_pkt(pj_ice_sess *ice, * Callback called by ICE session when it receives application data. */ static void ice_rx_data(pj_ice_sess *ice, - unsigned comp_id, - unsigned transport_id, - void *pkt, pj_size_t size, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + unsigned comp_id, + unsigned transport_id, + void *pkt, pj_size_t size, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_ice_strans *ice_st = (pj_ice_strans*)ice->user_data; PJ_UNUSED_ARG(transport_id); if (ice_st->cb.on_rx_data) { - (*ice_st->cb.on_rx_data)(ice_st, comp_id, pkt, size, - src_addr, src_addr_len); + (*ice_st->cb.on_rx_data)(ice_st, comp_id, pkt, size, + src_addr, src_addr_len); } } @@ -2295,15 +2294,15 @@ static void check_pending_send(pj_ice_strans *ice_st) ice_st->buf_idx = (ice_st->buf_idx + 1) % ice_st->num_buf; if (ice_st->num_buf > 0 && ice_st->buf_idx != ice_st->empty_idx) { - /* There's some pending send. Send it one by one. */ + /* There's some pending send. Send it one by one. */ pending_send *ps = &ice_st->send_buf[ice_st->buf_idx]; - pj_grp_lock_release(ice_st->grp_lock); - send_data(ice_st, ps->comp_id, ps->buffer, ps->data_len, - &ps->dst_addr, ps->dst_addr_len, PJ_FALSE, PJ_TRUE); + pj_grp_lock_release(ice_st->grp_lock); + send_data(ice_st, ps->comp_id, ps->buffer, ps->data_len, + &ps->dst_addr, ps->dst_addr_len, PJ_FALSE, PJ_TRUE); } else { - ice_st->is_pending = PJ_FALSE; - pj_grp_lock_release(ice_st->grp_lock); + ice_st->is_pending = PJ_FALSE; + pj_grp_lock_release(ice_st->grp_lock); } } @@ -2313,10 +2312,10 @@ static void check_pending_send(pj_ice_strans *ice_st) static pj_bool_t on_data_sent(pj_ice_strans *ice_st, pj_ssize_t sent) { if (ice_st->destroy_req || !ice_st->is_pending) - return PJ_TRUE; + return PJ_TRUE; if (ice_st->call_send_cb && ice_st->cb.on_data_sent) { - (*ice_st->cb.on_data_sent)(ice_st, sent); + (*ice_st->cb.on_data_sent)(ice_st, sent); } check_pending_send(ice_st); @@ -2328,10 +2327,10 @@ static pj_bool_t on_data_sent(pj_ice_strans *ice_st, pj_ssize_t sent) * the STUN socket. */ static pj_bool_t stun_on_rx_data(pj_stun_sock *stun_sock, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *src_addr, - unsigned addr_len) + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *src_addr, + unsigned addr_len) { sock_user_data *data; pj_ice_strans_comp *comp; @@ -2340,8 +2339,8 @@ static pj_bool_t stun_on_rx_data(pj_stun_sock *stun_sock, data = (sock_user_data*) pj_stun_sock_get_user_data(stun_sock); if (data == NULL) { - /* We have disassociated ourselves from the STUN socket */ - return PJ_FALSE; + /* We have disassociated ourselves from the STUN socket */ + return PJ_FALSE; } comp = data->comp; @@ -2350,27 +2349,27 @@ static pj_bool_t stun_on_rx_data(pj_stun_sock *stun_sock, pj_grp_lock_add_ref(ice_st->grp_lock); if (ice_st->ice == NULL) { - /* The ICE session is gone, but we're still receiving packets. - * This could also happen if remote doesn't do ICE. So just - * report this to application. - */ - if (ice_st->cb.on_rx_data) { - (*ice_st->cb.on_rx_data)(ice_st, comp->comp_id, pkt, pkt_len, - src_addr, addr_len); - } + /* The ICE session is gone, but we're still receiving packets. + * This could also happen if remote doesn't do ICE. So just + * report this to application. + */ + if (ice_st->cb.on_rx_data) { + (*ice_st->cb.on_rx_data)(ice_st, comp->comp_id, pkt, pkt_len, + src_addr, addr_len); + } } else { - /* Hand over the packet to ICE session */ - status = pj_ice_sess_on_rx_pkt(comp->ice_st->ice, comp->comp_id, - data->transport_id, - pkt, pkt_len, - src_addr, addr_len); + /* Hand over the packet to ICE session */ + status = pj_ice_sess_on_rx_pkt(comp->ice_st->ice, comp->comp_id, + data->transport_id, + pkt, pkt_len, + src_addr, addr_len); - if (status != PJ_SUCCESS) { - ice_st_perror(comp->ice_st, "Error processing packet", - status); - } + if (status != PJ_SUCCESS) { + ice_st_perror(comp->ice_st, "Error processing packet", + status); + } } return pj_grp_lock_dec_ref(ice_st->grp_lock) ? PJ_FALSE : PJ_TRUE; @@ -2380,8 +2379,8 @@ static pj_bool_t stun_on_rx_data(pj_stun_sock *stun_sock, * has completed. */ static pj_bool_t stun_on_data_sent(pj_stun_sock *stun_sock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent) + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent) { sock_user_data *data; @@ -2395,8 +2394,8 @@ static pj_bool_t stun_on_data_sent(pj_stun_sock *stun_sock, /* Notification when the status of the STUN transport has changed. */ static pj_bool_t stun_on_status(pj_stun_sock *stun_sock, - pj_stun_sock_op op, - pj_status_t status) + pj_stun_sock_op op, + pj_status_t status) { sock_user_data *data; pj_ice_strans_comp *comp; @@ -2418,12 +2417,12 @@ static pj_bool_t stun_on_status(pj_stun_sock *stun_sock, /* Find the srflx cancidate */ for (i=0; icand_cnt; ++i) { - if (comp->cand_list[i].type == PJ_ICE_CAND_TYPE_SRFLX && - comp->cand_list[i].transport_id == data->transport_id) - { - cand = &comp->cand_list[i]; - break; - } + if (comp->cand_list[i].type == PJ_ICE_CAND_TYPE_SRFLX && + comp->cand_list[i].transport_id == data->transport_id) + { + cand = &comp->cand_list[i]; + break; + } } pj_grp_lock_release(ice_st->grp_lock); @@ -2433,203 +2432,203 @@ static pj_bool_t stun_on_status(pj_stun_sock *stun_sock, * candidate due to initialization error. */ if (cand == NULL) { - return pj_grp_lock_dec_ref(ice_st->grp_lock) ? PJ_FALSE : PJ_TRUE; + return pj_grp_lock_dec_ref(ice_st->grp_lock) ? PJ_FALSE : PJ_TRUE; } tp_idx = GET_TP_IDX(data->transport_id); switch (op) { case PJ_STUN_SOCK_DNS_OP: - if (status != PJ_SUCCESS) { - /* May not have cand, e.g. when error during init */ - if (cand) - cand->status = status; - if (!ice_st->cfg.stun_tp[tp_idx].ignore_stun_error) { - sess_fail(ice_st, PJ_ICE_STRANS_OP_INIT, - "DNS resolution failed", status); - } else { - PJ_LOG(4,(ice_st->obj_name, - "STUN error is ignored for comp %d", - comp->comp_id)); - } - } - break; + if (status != PJ_SUCCESS) { + /* May not have cand, e.g. when error during init */ + if (cand) + cand->status = status; + if (!ice_st->cfg.stun_tp[tp_idx].ignore_stun_error) { + sess_fail(ice_st, PJ_ICE_STRANS_OP_INIT, + "DNS resolution failed", status); + } else { + PJ_LOG(4,(ice_st->obj_name, + "STUN error is ignored for comp %d", + comp->comp_id)); + } + } + break; case PJ_STUN_SOCK_BINDING_OP: case PJ_STUN_SOCK_MAPPED_ADDR_CHANGE: - if (status == PJ_SUCCESS) { - pj_stun_sock_info info; - - status = pj_stun_sock_get_info(stun_sock, &info); - if (status == PJ_SUCCESS) { - char ipaddr[PJ_INET6_ADDRSTRLEN+10]; - const char *op_name = (op==PJ_STUN_SOCK_BINDING_OP) ? - "Binding discovery complete" : - "srflx address changed"; - pj_bool_t dup = PJ_FALSE; - pj_bool_t init_done; - - if (info.mapped_addr.addr.sa_family == pj_AF_INET() && - cand->base_addr.addr.sa_family == pj_AF_INET6()) - { - /* We get an IPv4 mapped address for our IPv6 - * host address. - */ - comp->ipv4_mapped = PJ_TRUE; - - /* Find other host candidates with the same (IPv6) - * address, and replace it with the new (IPv4) - * mapped address. - */ - for (i = 0; i < comp->cand_cnt; ++i) { - pj_sockaddr *a1, *a2; - - if (comp->cand_list[i].type != PJ_ICE_CAND_TYPE_HOST) - continue; - - a1 = &comp->cand_list[i].addr; - a2 = &cand->base_addr; - if (pj_memcmp(pj_sockaddr_get_addr(a1), - pj_sockaddr_get_addr(a2), - pj_sockaddr_get_addr_len(a1)) == 0) - { - pj_uint16_t port = pj_sockaddr_get_port(a1); - pj_sockaddr_cp(a1, &info.mapped_addr); - if (port != pj_sockaddr_get_port(a2)) - pj_sockaddr_set_port(a1, port); - pj_sockaddr_cp(&comp->cand_list[i].base_addr, a1); - } - } - pj_sockaddr_cp(&cand->base_addr, &info.mapped_addr); - pj_sockaddr_cp(&cand->rel_addr, &info.mapped_addr); - } - - /* Eliminate the srflx candidate if the address is - * equal to other (host) candidates. - */ - for (i=0; icand_cnt; ++i) { - if (comp->cand_list[i].type == PJ_ICE_CAND_TYPE_HOST && - pj_sockaddr_cmp(&comp->cand_list[i].addr, - &info.mapped_addr) == 0) - { - dup = PJ_TRUE; - break; - } - } - - if (dup) { - /* Duplicate found, remove the srflx candidate */ - unsigned idx = (unsigned)(cand - comp->cand_list); - - /* Update default candidate index */ - if (comp->default_cand > idx) { - --comp->default_cand; - } else if (comp->default_cand == idx) { - comp->default_cand = 0; - } - - /* Remove srflx candidate */ - pj_array_erase(comp->cand_list, sizeof(comp->cand_list[0]), - comp->cand_cnt, idx); - --comp->cand_cnt; - } else { - /* Otherwise update the address */ - pj_sockaddr_cp(&cand->addr, &info.mapped_addr); - cand->status = PJ_SUCCESS; - - /* Add the candidate (for trickle ICE) */ - if (pj_ice_strans_has_sess(ice_st)) { - status = pj_ice_sess_add_cand( - ice_st->ice, - comp->comp_id, - cand->transport_id, - cand->type, - cand->local_pref, - &cand->foundation, - &cand->addr, - &cand->base_addr, - &cand->rel_addr, - pj_sockaddr_get_len(&cand->addr), - NULL); - } - } - - PJ_LOG(4,(comp->ice_st->obj_name, - "Comp %d: %s, " - "srflx address is %s", - comp->comp_id, op_name, - pj_sockaddr_print(&info.mapped_addr, ipaddr, - sizeof(ipaddr), 3))); - - sess_init_update(ice_st); - - /* Invoke on_new_candidate() callback */ - init_done = (ice_st->state==PJ_ICE_STRANS_STATE_READY); - if (op == PJ_STUN_SOCK_BINDING_OP && status == PJ_SUCCESS && - ice_st->cb.on_new_candidate && (!dup || init_done)) - { - (*ice_st->cb.on_new_candidate) - (ice_st, (dup? NULL:cand), init_done); - } - - if (op == PJ_STUN_SOCK_MAPPED_ADDR_CHANGE && - ice_st->cb.on_ice_complete) - { - (*ice_st->cb.on_ice_complete)(ice_st, - PJ_ICE_STRANS_OP_ADDR_CHANGE, - status); - } - } - } - - if (status != PJ_SUCCESS) { - /* May not have cand, e.g. when error during init */ - if (cand) - cand->status = status; - if (!ice_st->cfg.stun_tp[tp_idx].ignore_stun_error || - comp->cand_cnt==1) - { - sess_fail(ice_st, PJ_ICE_STRANS_OP_INIT, - "STUN binding request failed", status); - } else { - pj_bool_t init_done; - - PJ_LOG(4,(ice_st->obj_name, - "STUN error is ignored for comp %d", - comp->comp_id)); - - if (cand) { - unsigned idx = (unsigned)(cand - comp->cand_list); - - /* Update default candidate index */ - if (comp->default_cand == idx) { - comp->default_cand = !idx; - } - } - - sess_init_update(ice_st); - - /* Invoke on_new_candidate() callback */ - init_done = (ice_st->state==PJ_ICE_STRANS_STATE_READY); - if (op == PJ_STUN_SOCK_BINDING_OP && - ice_st->cb.on_new_candidate && init_done) - { - (*ice_st->cb.on_new_candidate) (ice_st, NULL, PJ_TRUE); - } - } - } - break; + if (status == PJ_SUCCESS) { + pj_stun_sock_info info; + + status = pj_stun_sock_get_info(stun_sock, &info); + if (status == PJ_SUCCESS) { + char ipaddr[PJ_INET6_ADDRSTRLEN+10]; + const char *op_name = (op==PJ_STUN_SOCK_BINDING_OP) ? + "Binding discovery complete" : + "srflx address changed"; + pj_bool_t dup = PJ_FALSE; + pj_bool_t init_done; + + if (info.mapped_addr.addr.sa_family == pj_AF_INET() && + cand->base_addr.addr.sa_family == pj_AF_INET6()) + { + /* We get an IPv4 mapped address for our IPv6 + * host address. + */ + comp->ipv4_mapped = PJ_TRUE; + + /* Find other host candidates with the same (IPv6) + * address, and replace it with the new (IPv4) + * mapped address. + */ + for (i = 0; i < comp->cand_cnt; ++i) { + pj_sockaddr *a1, *a2; + + if (comp->cand_list[i].type != PJ_ICE_CAND_TYPE_HOST) + continue; + + a1 = &comp->cand_list[i].addr; + a2 = &cand->base_addr; + if (pj_memcmp(pj_sockaddr_get_addr(a1), + pj_sockaddr_get_addr(a2), + pj_sockaddr_get_addr_len(a1)) == 0) + { + pj_uint16_t port = pj_sockaddr_get_port(a1); + pj_sockaddr_cp(a1, &info.mapped_addr); + if (port != pj_sockaddr_get_port(a2)) + pj_sockaddr_set_port(a1, port); + pj_sockaddr_cp(&comp->cand_list[i].base_addr, a1); + } + } + pj_sockaddr_cp(&cand->base_addr, &info.mapped_addr); + pj_sockaddr_cp(&cand->rel_addr, &info.mapped_addr); + } + + /* Eliminate the srflx candidate if the address is + * equal to other (host) candidates. + */ + for (i=0; icand_cnt; ++i) { + if (comp->cand_list[i].type == PJ_ICE_CAND_TYPE_HOST && + pj_sockaddr_cmp(&comp->cand_list[i].addr, + &info.mapped_addr) == 0) + { + dup = PJ_TRUE; + break; + } + } + + if (dup) { + /* Duplicate found, remove the srflx candidate */ + unsigned idx = (unsigned)(cand - comp->cand_list); + + /* Update default candidate index */ + if (comp->default_cand > idx) { + --comp->default_cand; + } else if (comp->default_cand == idx) { + comp->default_cand = 0; + } + + /* Remove srflx candidate */ + pj_array_erase(comp->cand_list, sizeof(comp->cand_list[0]), + comp->cand_cnt, idx); + --comp->cand_cnt; + } else { + /* Otherwise update the address */ + pj_sockaddr_cp(&cand->addr, &info.mapped_addr); + cand->status = PJ_SUCCESS; + + /* Add the candidate (for trickle ICE) */ + if (pj_ice_strans_has_sess(ice_st)) { + status = pj_ice_sess_add_cand( + ice_st->ice, + comp->comp_id, + cand->transport_id, + cand->type, + cand->local_pref, + &cand->foundation, + &cand->addr, + &cand->base_addr, + &cand->rel_addr, + pj_sockaddr_get_len(&cand->addr), + NULL); + } + } + + PJ_LOG(4,(comp->ice_st->obj_name, + "Comp %d: %s, " + "srflx address is %s", + comp->comp_id, op_name, + pj_sockaddr_print(&info.mapped_addr, ipaddr, + sizeof(ipaddr), 3))); + + sess_init_update(ice_st); + + /* Invoke on_new_candidate() callback */ + init_done = (ice_st->state==PJ_ICE_STRANS_STATE_READY); + if (op == PJ_STUN_SOCK_BINDING_OP && status == PJ_SUCCESS && + ice_st->cb.on_new_candidate && (!dup || init_done)) + { + (*ice_st->cb.on_new_candidate) + (ice_st, (dup? NULL:cand), init_done); + } + + if (op == PJ_STUN_SOCK_MAPPED_ADDR_CHANGE && + ice_st->cb.on_ice_complete) + { + (*ice_st->cb.on_ice_complete)(ice_st, + PJ_ICE_STRANS_OP_ADDR_CHANGE, + status); + } + } + } + + if (status != PJ_SUCCESS) { + /* May not have cand, e.g. when error during init */ + if (cand) + cand->status = status; + if (!ice_st->cfg.stun_tp[tp_idx].ignore_stun_error || + comp->cand_cnt==1) + { + sess_fail(ice_st, PJ_ICE_STRANS_OP_INIT, + "STUN binding request failed", status); + } else { + pj_bool_t init_done; + + PJ_LOG(4,(ice_st->obj_name, + "STUN error is ignored for comp %d", + comp->comp_id)); + + if (cand) { + unsigned idx = (unsigned)(cand - comp->cand_list); + + /* Update default candidate index */ + if (comp->default_cand == idx) { + comp->default_cand = !idx; + } + } + + sess_init_update(ice_st); + + /* Invoke on_new_candidate() callback */ + init_done = (ice_st->state==PJ_ICE_STRANS_STATE_READY); + if (op == PJ_STUN_SOCK_BINDING_OP && + ice_st->cb.on_new_candidate && init_done) + { + (*ice_st->cb.on_new_candidate) (ice_st, NULL, PJ_TRUE); + } + } + } + break; case PJ_STUN_SOCK_KEEP_ALIVE_OP: - if (status != PJ_SUCCESS) { - pj_assert(cand != NULL); - cand->status = status; - if (!ice_st->cfg.stun_tp[tp_idx].ignore_stun_error) { - sess_fail(ice_st, PJ_ICE_STRANS_OP_INIT, - "STUN keep-alive failed", status); - } else { - PJ_LOG(4,(ice_st->obj_name, "STUN error is ignored")); - } - } - break; + if (status != PJ_SUCCESS) { + pj_assert(cand != NULL); + cand->status = status; + if (!ice_st->cfg.stun_tp[tp_idx].ignore_stun_error) { + sess_fail(ice_st, PJ_ICE_STRANS_OP_INIT, + "STUN keep-alive failed", status); + } else { + PJ_LOG(4,(ice_st->obj_name, "STUN error is ignored")); + } + } + break; } return pj_grp_lock_dec_ref(ice_st->grp_lock)? PJ_FALSE : PJ_TRUE; @@ -2637,10 +2636,10 @@ static pj_bool_t stun_on_status(pj_stun_sock *stun_sock, /* Callback when TURN socket has received a packet */ static void turn_on_rx_data(pj_turn_sock *turn_sock, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *peer_addr, - unsigned addr_len) + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *peer_addr, + unsigned addr_len) { pj_ice_strans_comp *comp; sock_user_data *data; @@ -2648,8 +2647,8 @@ static void turn_on_rx_data(pj_turn_sock *turn_sock, data = (sock_user_data*) pj_turn_sock_get_user_data(turn_sock); if (data == NULL) { - /* We have disassociated ourselves from the TURN socket */ - return; + /* We have disassociated ourselves from the TURN socket */ + return; } comp = data->comp; @@ -2657,28 +2656,28 @@ static void turn_on_rx_data(pj_turn_sock *turn_sock, pj_grp_lock_add_ref(comp->ice_st->grp_lock); if (comp->ice_st->ice == NULL) { - /* The ICE session is gone, but we're still receiving packets. - * This could also happen if remote doesn't do ICE and application - * specifies TURN as the default address in SDP. - * So in this case just give the packet to application. - */ - if (comp->ice_st->cb.on_rx_data) { - (*comp->ice_st->cb.on_rx_data)(comp->ice_st, comp->comp_id, pkt, - pkt_len, peer_addr, addr_len); - } + /* The ICE session is gone, but we're still receiving packets. + * This could also happen if remote doesn't do ICE and application + * specifies TURN as the default address in SDP. + * So in this case just give the packet to application. + */ + if (comp->ice_st->cb.on_rx_data) { + (*comp->ice_st->cb.on_rx_data)(comp->ice_st, comp->comp_id, pkt, + pkt_len, peer_addr, addr_len); + } } else { - /* Hand over the packet to ICE */ - status = pj_ice_sess_on_rx_pkt(comp->ice_st->ice, comp->comp_id, - data->transport_id, pkt, pkt_len, - peer_addr, addr_len); + /* Hand over the packet to ICE */ + status = pj_ice_sess_on_rx_pkt(comp->ice_st->ice, comp->comp_id, + data->transport_id, pkt, pkt_len, + peer_addr, addr_len); - if (status != PJ_SUCCESS) { - ice_st_perror(comp->ice_st, - "Error processing packet from TURN relay", - status); - } + if (status != PJ_SUCCESS) { + ice_st_perror(comp->ice_st, + "Error processing packet from TURN relay", + status); + } } pj_grp_lock_dec_ref(comp->ice_st->grp_lock); @@ -2688,7 +2687,7 @@ static void turn_on_rx_data(pj_turn_sock *turn_sock, * has completed. */ static pj_bool_t turn_on_data_sent(pj_turn_sock *turn_sock, - pj_ssize_t sent) + pj_ssize_t sent) { sock_user_data *data; @@ -2700,7 +2699,7 @@ static pj_bool_t turn_on_data_sent(pj_turn_sock *turn_sock, /* Callback when TURN client state has changed */ static void turn_on_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, - pj_turn_state_t new_state) + pj_turn_state_t new_state) { pj_ice_strans_comp *comp; sock_user_data *data; @@ -2708,242 +2707,242 @@ static void turn_on_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, data = (sock_user_data*) pj_turn_sock_get_user_data(turn_sock); if (data == NULL) { - /* Not interested in further state notification once the relay is - * disconnecting. - */ - return; + /* Not interested in further state notification once the relay is + * disconnecting. + */ + return; } comp = data->comp; tp_idx = GET_TP_IDX(data->transport_id); PJ_LOG(5,(comp->ice_st->obj_name, "TURN client state changed %s --> %s", - pj_turn_state_name(old_state), pj_turn_state_name(new_state))); + pj_turn_state_name(old_state), pj_turn_state_name(new_state))); pj_log_push_indent(); pj_grp_lock_add_ref(comp->ice_st->grp_lock); if (new_state == PJ_TURN_STATE_READY) { - pj_turn_session_info rel_info; - char ipaddr[PJ_INET6_ADDRSTRLEN+8]; - pj_ice_sess_cand *cand = NULL; - unsigned i, cand_idx = 0xFF; - - comp->turn[tp_idx].err_cnt = 0; - - /* Get allocation info */ - pj_turn_sock_get_info(turn_sock, &rel_info); - - /* Wait until initialization completes */ - pj_grp_lock_acquire(comp->ice_st->grp_lock); - - /* Find relayed candidate in the component */ - for (i=0; icand_cnt; ++i) { - if (comp->cand_list[i].type == PJ_ICE_CAND_TYPE_RELAYED && - comp->cand_list[i].transport_id == data->transport_id) - { - cand = &comp->cand_list[i]; - cand_idx = i; - break; - } - } - - pj_grp_lock_release(comp->ice_st->grp_lock); - - if (cand == NULL) - goto on_return; - - /* Update candidate */ - pj_sockaddr_cp(&cand->addr, &rel_info.relay_addr); - pj_sockaddr_cp(&cand->base_addr, &rel_info.relay_addr); - pj_sockaddr_cp(&cand->rel_addr, &rel_info.mapped_addr); - pj_ice_calc_foundation(comp->ice_st->pool, &cand->foundation, - PJ_ICE_CAND_TYPE_RELAYED, - &rel_info.relay_addr); - cand->status = PJ_SUCCESS; - - /* Set default candidate to relay */ - if (comp->cand_list[comp->default_cand].type!=PJ_ICE_CAND_TYPE_RELAYED - || (comp->ice_st->cfg.af != pj_AF_UNSPEC() && - comp->cand_list[comp->default_cand].addr.addr.sa_family - != comp->ice_st->cfg.af)) - { - comp->default_cand = (unsigned)(cand - comp->cand_list); - } - - /* Prefer IPv4 relay as default candidate for better connectivity - * with IPv4 endpoints. - */ - /* - if (cand->addr.addr.sa_family != pj_AF_INET()) { - for (i=0; icand_cnt; ++i) { - if (comp->cand_list[i].type == PJ_ICE_CAND_TYPE_RELAYED && - comp->cand_list[i].addr.addr.sa_family == pj_AF_INET() && - comp->cand_list[i].status == PJ_SUCCESS) - { - comp->default_cand = i; - break; - } - } - } - */ - - PJ_LOG(4,(comp->ice_st->obj_name, - "Comp %d/%d: TURN allocation (tpid=%d) complete, " - "relay address is %s", - comp->comp_id, cand_idx, cand->transport_id, - pj_sockaddr_print(&rel_info.relay_addr, ipaddr, - sizeof(ipaddr), 3))); - - /* For trickle ICE, add the candidate to ICE session and setup TURN - * permission for remote candidates. - */ - if (comp->ice_st->cfg.opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED && - pj_ice_strans_has_sess(comp->ice_st)) - { - pj_sockaddr addrs[PJ_ICE_ST_MAX_CAND]; - pj_ice_sess *sess = comp->ice_st->ice; - unsigned j, count=0; - pj_status_t status; - - /* Add the candidate */ - status = pj_ice_sess_add_cand(comp->ice_st->ice, - comp->comp_id, - cand->transport_id, - cand->type, - cand->local_pref, - &cand->foundation, - &cand->addr, - &cand->base_addr, - &cand->rel_addr, - pj_sockaddr_get_len(&cand->addr), - NULL); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(comp->ice_st->obj_name, status, - "Comp %d/%d: failed to add TURN (tpid=%d) to ICE", - comp->comp_id, cand_idx, cand->transport_id)); - sess_fail(comp->ice_st, PJ_ICE_STRANS_OP_INIT, - "adding TURN candidate failed", status); - } - - /* Gather remote addresses for this component */ - for (j=0; jrcand_cnt && countrcand[j].addr.addr.sa_family== - rel_info.relay_addr.addr.sa_family) - { - pj_sockaddr_cp(&addrs[count++], &sess->rcand[j].addr); - } - } - - if (count) { - status = pj_turn_sock_set_perm(turn_sock, count, addrs, 0); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(comp->ice_st->obj_name, status, - "Comp %d/%d: TURN set perm (tpid=%d) failed", - comp->comp_id, cand_idx, cand->transport_id)); - sess_fail(comp->ice_st, PJ_ICE_STRANS_OP_INIT, - "TURN set permission failed", status); - } - } - } - - sess_init_update(comp->ice_st); - - /* Invoke on_new_candidate() callback */ - if (comp->ice_st->cb.on_new_candidate) { - (*comp->ice_st->cb.on_new_candidate) - (comp->ice_st, cand, - (comp->ice_st->state==PJ_ICE_STRANS_STATE_READY)); - } + pj_turn_session_info rel_info; + char ipaddr[PJ_INET6_ADDRSTRLEN+8]; + pj_ice_sess_cand *cand = NULL; + unsigned i, cand_idx = 0xFF; + + comp->turn[tp_idx].err_cnt = 0; + + /* Get allocation info */ + pj_turn_sock_get_info(turn_sock, &rel_info); + + /* Wait until initialization completes */ + pj_grp_lock_acquire(comp->ice_st->grp_lock); + + /* Find relayed candidate in the component */ + for (i=0; icand_cnt; ++i) { + if (comp->cand_list[i].type == PJ_ICE_CAND_TYPE_RELAYED && + comp->cand_list[i].transport_id == data->transport_id) + { + cand = &comp->cand_list[i]; + cand_idx = i; + break; + } + } + + pj_grp_lock_release(comp->ice_st->grp_lock); + + if (cand == NULL) + goto on_return; + + /* Update candidate */ + pj_sockaddr_cp(&cand->addr, &rel_info.relay_addr); + pj_sockaddr_cp(&cand->base_addr, &rel_info.relay_addr); + pj_sockaddr_cp(&cand->rel_addr, &rel_info.mapped_addr); + pj_ice_calc_foundation(comp->ice_st->pool, &cand->foundation, + PJ_ICE_CAND_TYPE_RELAYED, + &rel_info.relay_addr); + cand->status = PJ_SUCCESS; + + /* Set default candidate to relay */ + if (comp->cand_list[comp->default_cand].type!=PJ_ICE_CAND_TYPE_RELAYED + || (comp->ice_st->cfg.af != pj_AF_UNSPEC() && + comp->cand_list[comp->default_cand].addr.addr.sa_family + != comp->ice_st->cfg.af)) + { + comp->default_cand = (unsigned)(cand - comp->cand_list); + } + + /* Prefer IPv4 relay as default candidate for better connectivity + * with IPv4 endpoints. + */ + /* + if (cand->addr.addr.sa_family != pj_AF_INET()) { + for (i=0; icand_cnt; ++i) { + if (comp->cand_list[i].type == PJ_ICE_CAND_TYPE_RELAYED && + comp->cand_list[i].addr.addr.sa_family == pj_AF_INET() && + comp->cand_list[i].status == PJ_SUCCESS) + { + comp->default_cand = i; + break; + } + } + } + */ + + PJ_LOG(4,(comp->ice_st->obj_name, + "Comp %d/%d: TURN allocation (tpid=%d) complete, " + "relay address is %s", + comp->comp_id, cand_idx, cand->transport_id, + pj_sockaddr_print(&rel_info.relay_addr, ipaddr, + sizeof(ipaddr), 3))); + + /* For trickle ICE, add the candidate to ICE session and setup TURN + * permission for remote candidates. + */ + if (comp->ice_st->cfg.opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED && + pj_ice_strans_has_sess(comp->ice_st)) + { + pj_sockaddr addrs[PJ_ICE_ST_MAX_CAND]; + pj_ice_sess *sess = comp->ice_st->ice; + unsigned j, count=0; + pj_status_t status; + + /* Add the candidate */ + status = pj_ice_sess_add_cand(comp->ice_st->ice, + comp->comp_id, + cand->transport_id, + cand->type, + cand->local_pref, + &cand->foundation, + &cand->addr, + &cand->base_addr, + &cand->rel_addr, + pj_sockaddr_get_len(&cand->addr), + NULL); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(comp->ice_st->obj_name, status, + "Comp %d/%d: failed to add TURN (tpid=%d) to ICE", + comp->comp_id, cand_idx, cand->transport_id)); + sess_fail(comp->ice_st, PJ_ICE_STRANS_OP_INIT, + "adding TURN candidate failed", status); + } + + /* Gather remote addresses for this component */ + for (j=0; jrcand_cnt && countrcand[j].addr.addr.sa_family== + rel_info.relay_addr.addr.sa_family) + { + pj_sockaddr_cp(&addrs[count++], &sess->rcand[j].addr); + } + } + + if (count) { + status = pj_turn_sock_set_perm(turn_sock, count, addrs, 0); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(comp->ice_st->obj_name, status, + "Comp %d/%d: TURN set perm (tpid=%d) failed", + comp->comp_id, cand_idx, cand->transport_id)); + sess_fail(comp->ice_st, PJ_ICE_STRANS_OP_INIT, + "TURN set permission failed", status); + } + } + } + + sess_init_update(comp->ice_st); + + /* Invoke on_new_candidate() callback */ + if (comp->ice_st->cb.on_new_candidate) { + (*comp->ice_st->cb.on_new_candidate) + (comp->ice_st, cand, + (comp->ice_st->state==PJ_ICE_STRANS_STATE_READY)); + } } else if ((old_state == PJ_TURN_STATE_RESOLVING || old_state == PJ_TURN_STATE_RESOLVED || old_state == PJ_TURN_STATE_ALLOCATING) && - new_state >= PJ_TURN_STATE_DEALLOCATING) + new_state >= PJ_TURN_STATE_DEALLOCATING) { - pj_ice_sess_cand *cand = NULL; - unsigned i, cand_idx = 0xFF; - - /* DNS resolution or TURN transport creation/allocation - * has failed. - */ - ++comp->turn[tp_idx].err_cnt; - - /* Unregister ourself from the TURN relay */ - pj_turn_sock_set_user_data(turn_sock, NULL); - comp->turn[tp_idx].sock = NULL; - - /* Wait until initialization completes */ - pj_grp_lock_acquire(comp->ice_st->grp_lock); - - /* Find relayed candidate in the component */ - for (i=0; icand_cnt; ++i) { - if (comp->cand_list[i].type == PJ_ICE_CAND_TYPE_RELAYED && - comp->cand_list[i].transport_id == data->transport_id) - { - cand = &comp->cand_list[i]; - cand_idx = i; - break; - } - } - - pj_grp_lock_release(comp->ice_st->grp_lock); - - /* If the error happens during pj_turn_sock_create() or - * pj_turn_sock_alloc(), the candidate hasn't been added - * to the list. - */ - if (cand) { - pj_turn_session_info info; - - pj_turn_sock_get_info(turn_sock, &info); - cand->status = (old_state == PJ_TURN_STATE_RESOLVING)? - PJ_ERESOLVE : info.last_status; - PJ_LOG(4,(comp->ice_st->obj_name, - "Comp %d/%d: TURN error (tpid=%d) during state %s", - comp->comp_id, cand_idx, cand->transport_id, - pj_turn_state_name(old_state))); - } - - sess_init_update(comp->ice_st); - - /* Invoke on_new_candidate() callback */ - if (comp->ice_st->cb.on_new_candidate && - comp->ice_st->state==PJ_ICE_STRANS_STATE_READY) - { - (*comp->ice_st->cb.on_new_candidate)(comp->ice_st, NULL, PJ_TRUE); - } + pj_ice_sess_cand *cand = NULL; + unsigned i, cand_idx = 0xFF; + + /* DNS resolution or TURN transport creation/allocation + * has failed. + */ + ++comp->turn[tp_idx].err_cnt; + + /* Unregister ourself from the TURN relay */ + pj_turn_sock_set_user_data(turn_sock, NULL); + comp->turn[tp_idx].sock = NULL; + + /* Wait until initialization completes */ + pj_grp_lock_acquire(comp->ice_st->grp_lock); + + /* Find relayed candidate in the component */ + for (i=0; icand_cnt; ++i) { + if (comp->cand_list[i].type == PJ_ICE_CAND_TYPE_RELAYED && + comp->cand_list[i].transport_id == data->transport_id) + { + cand = &comp->cand_list[i]; + cand_idx = i; + break; + } + } + + pj_grp_lock_release(comp->ice_st->grp_lock); + + /* If the error happens during pj_turn_sock_create() or + * pj_turn_sock_alloc(), the candidate hasn't been added + * to the list. + */ + if (cand) { + pj_turn_session_info info; + + pj_turn_sock_get_info(turn_sock, &info); + cand->status = (old_state == PJ_TURN_STATE_RESOLVING)? + PJ_ERESOLVE : info.last_status; + PJ_LOG(4,(comp->ice_st->obj_name, + "Comp %d/%d: TURN error (tpid=%d) during state %s", + comp->comp_id, cand_idx, cand->transport_id, + pj_turn_state_name(old_state))); + } + + sess_init_update(comp->ice_st); + + /* Invoke on_new_candidate() callback */ + if (comp->ice_st->cb.on_new_candidate && + comp->ice_st->state==PJ_ICE_STRANS_STATE_READY) + { + (*comp->ice_st->cb.on_new_candidate)(comp->ice_st, NULL, PJ_TRUE); + } } else if (new_state >= PJ_TURN_STATE_DEALLOCATING) { - pj_turn_session_info info; - - ++comp->turn[tp_idx].err_cnt; - - pj_turn_sock_get_info(turn_sock, &info); - - /* Unregister ourself from the TURN relay */ - pj_turn_sock_set_user_data(turn_sock, NULL); - comp->turn[tp_idx].sock = NULL; - - /* Set session to fail on error. last_status PJ_SUCCESS means normal - * deallocation, which should not trigger sess_fail as it may have - * been initiated by ICE destroy - */ - if (info.last_status != PJ_SUCCESS) { - if (comp->ice_st->state < PJ_ICE_STRANS_STATE_READY) { - sess_fail(comp->ice_st, PJ_ICE_STRANS_OP_INIT, - "TURN allocation failed", info.last_status); - } else if (comp->turn[tp_idx].err_cnt > 1) { - sess_fail(comp->ice_st, PJ_ICE_STRANS_OP_KEEP_ALIVE, - "TURN refresh failed", info.last_status); - } else { - PJ_PERROR(4,(comp->ice_st->obj_name, info.last_status, - "Comp %d: TURN allocation failed, retrying", - comp->comp_id)); - add_update_turn(comp->ice_st, comp, tp_idx, - PJ_ICE_ST_MAX_CAND - comp->cand_cnt); - } - } + pj_turn_session_info info; + + ++comp->turn[tp_idx].err_cnt; + + pj_turn_sock_get_info(turn_sock, &info); + + /* Unregister ourself from the TURN relay */ + pj_turn_sock_set_user_data(turn_sock, NULL); + comp->turn[tp_idx].sock = NULL; + + /* Set session to fail on error. last_status PJ_SUCCESS means normal + * deallocation, which should not trigger sess_fail as it may have + * been initiated by ICE destroy + */ + if (info.last_status != PJ_SUCCESS) { + if (comp->ice_st->state < PJ_ICE_STRANS_STATE_READY) { + sess_fail(comp->ice_st, PJ_ICE_STRANS_OP_INIT, + "TURN allocation failed", info.last_status); + } else if (comp->turn[tp_idx].err_cnt > 1) { + sess_fail(comp->ice_st, PJ_ICE_STRANS_OP_KEEP_ALIVE, + "TURN refresh failed", info.last_status); + } else { + PJ_PERROR(4,(comp->ice_st->obj_name, info.last_status, + "Comp %d: TURN allocation failed, retrying", + comp->comp_id)); + add_update_turn(comp->ice_st, comp, tp_idx, + PJ_ICE_ST_MAX_CAND - comp->cand_cnt); + } + } } on_return: diff --git a/pjnath/src/pjnath/nat_detect.c b/pjnath/src/pjnath/nat_detect.c index db0de10bcb..2612de3011 100644 --- a/pjnath/src/pjnath/nat_detect.c +++ b/pjnath/src/pjnath/nat_detect.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,10 +43,10 @@ static const char *nat_type_names[] = }; -#define CHANGE_IP_FLAG 4 -#define CHANGE_PORT_FLAG 2 -#define CHANGE_IP_PORT_FLAG (CHANGE_IP_FLAG | CHANGE_PORT_FLAG) -#define TEST_INTERVAL 50 +#define CHANGE_IP_FLAG 4 +#define CHANGE_PORT_FLAG 2 +#define CHANGE_IP_PORT_FLAG (CHANGE_IP_FLAG | CHANGE_PORT_FLAG) +#define TEST_INTERVAL 50 enum test_type { @@ -68,43 +67,43 @@ static const char *test_names[] = enum timer_type { - TIMER_TEST = 1, + TIMER_TEST = 1, TIMER_DESTROY = 2 }; typedef struct nat_detect_session { - pj_pool_t *pool; - pj_grp_lock_t *grp_lock; + pj_pool_t *pool; + pj_grp_lock_t *grp_lock; - pj_timer_heap_t *timer_heap; - pj_timer_entry timer; - unsigned timer_executed; + pj_timer_heap_t *timer_heap; + pj_timer_entry timer; + unsigned timer_executed; - void *user_data; + void *user_data; pj_stun_nat_detect_cb *cb; - pj_sock_t sock; - pj_sockaddr local_addr; - pj_ioqueue_key_t *key; - pj_sockaddr server; - pj_sockaddr *cur_server; - pj_sockaddr cur_addr; - pj_stun_session *stun_sess; - - pj_ioqueue_op_key_t read_op, write_op; - pj_uint8_t rx_pkt[PJ_STUN_MAX_PKT_LEN]; - pj_ssize_t rx_pkt_len; - pj_sockaddr src_addr; - int src_addr_len; + pj_sock_t sock; + pj_sockaddr local_addr; + pj_ioqueue_key_t *key; + pj_sockaddr server; + pj_sockaddr *cur_server; + pj_sockaddr cur_addr; + pj_stun_session *stun_sess; + + pj_ioqueue_op_key_t read_op, write_op; + pj_uint8_t rx_pkt[PJ_STUN_MAX_PKT_LEN]; + pj_ssize_t rx_pkt_len; + pj_sockaddr src_addr; + int src_addr_len; struct result { - pj_bool_t executed; - pj_bool_t complete; - pj_status_t status; - pj_sockaddr ma; - pj_sockaddr ca; - pj_stun_tx_data *tdata; + pj_bool_t executed; + pj_bool_t complete; + pj_status_t status; + pj_sockaddr ma; + pj_sockaddr ca; + pj_stun_tx_data *tdata; } result[ST_MAX]; } nat_detect_session; @@ -114,25 +113,25 @@ static void on_read_complete(pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, pj_ssize_t bytes_read); static void on_request_complete(pj_stun_session *sess, - pj_status_t status, - void *token, - pj_stun_tx_data *tdata, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + pj_status_t status, + void *token, + pj_stun_tx_data *tdata, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); static pj_status_t on_send_msg(pj_stun_session *sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len); + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len); static pj_status_t send_test(nat_detect_session *sess, - enum test_type test_id, - const pj_sockaddr *alt_addr, - pj_uint32_t change_flag); + enum test_type test_id, + const pj_sockaddr *alt_addr, + pj_uint32_t change_flag); static void on_sess_timer(pj_timer_heap_t *th, - pj_timer_entry *te); + pj_timer_entry *te); static void sess_destroy(nat_detect_session *sess); static void sess_on_destroy(void *member); @@ -142,7 +141,7 @@ static void sess_on_destroy(void *member); PJ_DEF(const char*) pj_stun_get_nat_name(pj_stun_nat_type type) { PJ_ASSERT_RETURN(type >= 0 && type <= PJ_STUN_NAT_TYPE_PORT_RESTRICTED, - "*Invalid*"); + "*Invalid*"); return nat_type_names[type]; } @@ -151,8 +150,8 @@ static int test_executed(nat_detect_session *sess) { unsigned i, count; for (i=0, count=0; iresult); ++i) { - if (sess->result[i].executed) - ++count; + if (sess->result[i].executed) + ++count; } return count; } @@ -161,14 +160,14 @@ static int test_completed(nat_detect_session *sess) { unsigned i, count; for (i=0, count=0; iresult); ++i) { - if (sess->result[i].complete) - ++count; + if (sess->result[i].complete) + ++count; } return count; } static pj_status_t get_local_interface(const pj_sockaddr *server, - pj_sockaddr *local_addr) + pj_sockaddr *local_addr) { pj_sock_t sock; pj_sockaddr tmp, local; @@ -176,28 +175,28 @@ static pj_status_t get_local_interface(const pj_sockaddr *server, pj_status_t status; status = pj_sock_socket(server->addr.sa_family, pj_SOCK_DGRAM(), - 0, &sock); + 0, &sock); if (status != PJ_SUCCESS) - return status; + return status; addr_len = pj_sockaddr_get_len(server); pj_sockaddr_init(server->addr.sa_family, &local, NULL, 0); status = pj_sock_bind(sock, &local, addr_len); if (status != PJ_SUCCESS) { - pj_sock_close(sock); - return status; + pj_sock_close(sock); + return status; } status = pj_sock_connect(sock, server, addr_len); if (status != PJ_SUCCESS) { - pj_sock_close(sock); - return status; + pj_sock_close(sock); + return status; } status = pj_sock_getsockname(sock, &tmp, &addr_len); if (status != PJ_SUCCESS) { - pj_sock_close(sock); - return status; + pj_sock_close(sock); + return status; } pj_sockaddr_cp(local_addr, &tmp); @@ -208,22 +207,22 @@ static pj_status_t get_local_interface(const pj_sockaddr *server, PJ_DEF(pj_status_t) pj_stun_detect_nat_type(const pj_sockaddr_in *server, - pj_stun_config *stun_cfg, - void *user_data, - pj_stun_nat_detect_cb *cb) + pj_stun_config *stun_cfg, + void *user_data, + pj_stun_nat_detect_cb *cb) { pj_sockaddr srv; if (server) - pj_sockaddr_cp(&srv, server); + pj_sockaddr_cp(&srv, server); return pj_stun_detect_nat_type2(&srv, stun_cfg, user_data, cb); } PJ_DEF(pj_status_t) pj_stun_detect_nat_type2(const pj_sockaddr *server, - pj_stun_config *stun_cfg, - void *user_data, - pj_stun_nat_detect_cb *cb) + pj_stun_config *stun_cfg, + void *user_data, + pj_stun_nat_detect_cb *cb) { pj_pool_t *pool; nat_detect_session *sess; @@ -235,15 +234,15 @@ PJ_DEF(pj_status_t) pj_stun_detect_nat_type2(const pj_sockaddr *server, PJ_ASSERT_RETURN(server && stun_cfg, PJ_EINVAL); PJ_ASSERT_RETURN(stun_cfg->pf && stun_cfg->ioqueue && stun_cfg->timer_heap, - PJ_EINVAL); + PJ_EINVAL); /* * Init NAT detection session. */ pool = pj_pool_create(stun_cfg->pf, "natck%p", PJNATH_POOL_LEN_NATCK, - PJNATH_POOL_INC_NATCK, NULL); + PJNATH_POOL_INC_NATCK, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; sess = PJ_POOL_ZALLOC_T(pool, nat_detect_session); sess->pool = pool; @@ -252,9 +251,9 @@ PJ_DEF(pj_status_t) pj_stun_detect_nat_type2(const pj_sockaddr *server, status = pj_grp_lock_create(pool, NULL, &sess->grp_lock); if (status != PJ_SUCCESS) { - /* Group lock not created yet, just destroy pool and return */ - pj_pool_release(pool); - return status; + /* Group lock not created yet, just destroy pool and return */ + pj_pool_release(pool); + return status; } pj_grp_lock_add_ref(sess->grp_lock); @@ -276,7 +275,7 @@ PJ_DEF(pj_status_t) pj_stun_detect_nat_type2(const pj_sockaddr *server, af = server->addr.sa_family; status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &sess->sock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* * Bind to any. @@ -285,29 +284,29 @@ PJ_DEF(pj_status_t) pj_stun_detect_nat_type2(const pj_sockaddr *server, pj_sockaddr_init(server->addr.sa_family, &sess->local_addr, NULL, 0); status = pj_sock_bind(sess->sock, &sess->local_addr, addr_len); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* * Get local/bound address. */ status = pj_sock_getsockname(sess->sock, &sess->local_addr, &addr_len); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* * Find out which interface is used to send to the server. */ status = get_local_interface(server, &sess->local_addr); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; PJ_LOG(5,(sess->pool->obj_name, "Local address is %s:%d", - pj_sockaddr_print(&sess->local_addr, addr, sizeof(addr), 2), - pj_sockaddr_get_port(&sess->local_addr))); + pj_sockaddr_print(&sess->local_addr, addr, sizeof(addr), 2), + pj_sockaddr_get_port(&sess->local_addr))); PJ_LOG(5,(sess->pool->obj_name, "Server set to %s:%d", - pj_sockaddr_print(server, addr, sizeof(addr), 2), - pj_sockaddr_get_port(server))); + pj_sockaddr_print(server, addr, sizeof(addr), 2), + pj_sockaddr_get_port(server))); /* * Register socket to ioqueue to receive asynchronous input @@ -317,10 +316,10 @@ PJ_DEF(pj_status_t) pj_stun_detect_nat_type2(const pj_sockaddr *server, ioqueue_cb.on_read_complete = &on_read_complete; status = pj_ioqueue_register_sock2(sess->pool, stun_cfg->ioqueue, - sess->sock, sess->grp_lock, sess, - &ioqueue_cb, &sess->key); + sess->sock, sess->grp_lock, sess, + &ioqueue_cb, &sess->key); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* * Create STUN session. @@ -329,9 +328,9 @@ PJ_DEF(pj_status_t) pj_stun_detect_nat_type2(const pj_sockaddr *server, sess_cb.on_request_complete = &on_request_complete; sess_cb.on_send_msg = &on_send_msg; status = pj_stun_session_create(stun_cfg, pool->obj_name, &sess_cb, - PJ_FALSE, sess->grp_lock, &sess->stun_sess); + PJ_FALSE, sess->grp_lock, &sess->stun_sess); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; pj_stun_session_set_user_data(sess->stun_sess, sess); @@ -359,21 +358,21 @@ PJ_DEF(pj_status_t) pj_stun_detect_nat_type2(const pj_sockaddr *server, static void sess_destroy(nat_detect_session *sess) { if (sess->stun_sess) { - pj_stun_session_destroy(sess->stun_sess); - sess->stun_sess = NULL; + pj_stun_session_destroy(sess->stun_sess); + sess->stun_sess = NULL; } if (sess->key) { - pj_ioqueue_unregister(sess->key); - sess->key = NULL; - sess->sock = PJ_INVALID_SOCKET; + pj_ioqueue_unregister(sess->key); + sess->key = NULL; + sess->sock = PJ_INVALID_SOCKET; } else if (sess->sock && sess->sock != PJ_INVALID_SOCKET) { - pj_sock_close(sess->sock); - sess->sock = PJ_INVALID_SOCKET; + pj_sock_close(sess->sock); + sess->sock = PJ_INVALID_SOCKET; } if (sess->grp_lock) { - pj_grp_lock_dec_ref(sess->grp_lock); + pj_grp_lock_dec_ref(sess->grp_lock); } } @@ -381,21 +380,21 @@ static void sess_on_destroy(void *member) { nat_detect_session *sess = (nat_detect_session*)member; if (sess->pool) { - pj_pool_release(sess->pool); + pj_pool_release(sess->pool); } } static void end_session(nat_detect_session *sess, - pj_status_t status, - pj_stun_nat_type nat_type) + pj_status_t status, + pj_stun_nat_type nat_type) { pj_stun_nat_detect_result result; char errmsg[PJ_ERR_MSG_SIZE]; pj_time_val delay; if (sess->timer.id != 0) { - pj_timer_heap_cancel(sess->timer_heap, &sess->timer); - sess->timer.id = 0; + pj_timer_heap_cancel(sess->timer_heap, &sess->timer); + sess->timer.id = 0; } pj_bzero(&result, sizeof(result)); @@ -408,7 +407,7 @@ static void end_session(nat_detect_session *sess, result.nat_type_name = nat_type_names[result.nat_type]; if (sess->cb) - (*sess->cb)(sess->user_data, &result); + (*sess->cb)(sess->user_data, &result); delay.sec = 0; delay.msec = 0; @@ -435,36 +434,36 @@ static void on_read_complete(pj_ioqueue_key_t *key, /* Ignore packet when STUN session has been destroyed */ if (!sess->stun_sess) - goto on_return; + goto on_return; if (bytes_read < 0) { - if (-bytes_read != PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK) && - -bytes_read != PJ_STATUS_FROM_OS(OSERR_EINPROGRESS) && - -bytes_read != PJ_STATUS_FROM_OS(OSERR_ECONNRESET)) - { - /* Permanent error */ - end_session(sess, (pj_status_t)-bytes_read, - PJ_STUN_NAT_TYPE_ERR_UNKNOWN); - goto on_return; - } + if (-bytes_read != PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK) && + -bytes_read != PJ_STATUS_FROM_OS(OSERR_EINPROGRESS) && + -bytes_read != PJ_STATUS_FROM_OS(OSERR_ECONNRESET)) + { + /* Permanent error */ + end_session(sess, (pj_status_t)-bytes_read, + PJ_STUN_NAT_TYPE_ERR_UNKNOWN); + goto on_return; + } } else if (bytes_read > 0) { - pj_stun_session_on_rx_pkt(sess->stun_sess, sess->rx_pkt, bytes_read, - PJ_STUN_IS_DATAGRAM|PJ_STUN_CHECK_PACKET, - NULL, NULL, - &sess->src_addr, sess->src_addr_len); + pj_stun_session_on_rx_pkt(sess->stun_sess, sess->rx_pkt, bytes_read, + PJ_STUN_IS_DATAGRAM|PJ_STUN_CHECK_PACKET, + NULL, NULL, + &sess->src_addr, sess->src_addr_len); } sess->rx_pkt_len = sizeof(sess->rx_pkt); sess->src_addr_len = sizeof(sess->src_addr); status = pj_ioqueue_recvfrom(key, op_key, sess->rx_pkt, &sess->rx_pkt_len, - PJ_IOQUEUE_ALWAYS_ASYNC, - &sess->src_addr, &sess->src_addr_len); + PJ_IOQUEUE_ALWAYS_ASYNC, + &sess->src_addr, &sess->src_addr_len); if (status != PJ_EPENDING) { - pj_assert(status != PJ_SUCCESS); - end_session(sess, status, PJ_STUN_NAT_TYPE_ERR_UNKNOWN); + pj_assert(status != PJ_SUCCESS); + end_session(sess, status, PJ_STUN_NAT_TYPE_ERR_UNKNOWN); } on_return: @@ -476,11 +475,11 @@ static void on_read_complete(pj_ioqueue_key_t *key, * Callback to send outgoing packet from STUN session. */ static pj_status_t on_send_msg(pj_stun_session *stun_sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len) + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len) { nat_detect_session *sess; pj_ssize_t pkt_len; @@ -492,7 +491,7 @@ static pj_status_t on_send_msg(pj_stun_session *stun_sess, pkt_len = pkt_size; status = pj_ioqueue_sendto(sess->key, &sess->write_op, pkt, &pkt_len, 0, - dst_addr, addr_len); + dst_addr, addr_len); return status; @@ -502,12 +501,12 @@ static pj_status_t on_send_msg(pj_stun_session *stun_sess, * Callback upon request completion. */ static void on_request_complete(pj_stun_session *stun_sess, - pj_status_t status, - void *token, - pj_stun_tx_data *tdata, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + pj_status_t status, + void *token, + pj_stun_tx_data *tdata, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { nat_detect_session *sess; pj_stun_sockaddr_attr *mattr = NULL; @@ -528,45 +527,45 @@ static void on_request_complete(pj_stun_session *stun_sess, /* Find errors in the response */ if (status == PJ_SUCCESS) { - /* Check error message */ - if (PJ_STUN_IS_ERROR_RESPONSE(response->hdr.type)) { - pj_stun_errcode_attr *eattr; - int err_code; + /* Check error message */ + if (PJ_STUN_IS_ERROR_RESPONSE(response->hdr.type)) { + pj_stun_errcode_attr *eattr; + int err_code; - eattr = (pj_stun_errcode_attr*) - pj_stun_msg_find_attr(response, PJ_STUN_ATTR_ERROR_CODE, 0); + eattr = (pj_stun_errcode_attr*) + pj_stun_msg_find_attr(response, PJ_STUN_ATTR_ERROR_CODE, 0); - if (eattr != NULL) - err_code = eattr->err_code; - else - err_code = PJ_STUN_SC_SERVER_ERROR; + if (eattr != NULL) + err_code = eattr->err_code; + else + err_code = PJ_STUN_SC_SERVER_ERROR; - status = PJ_STATUS_FROM_STUN_CODE(err_code); + status = PJ_STATUS_FROM_STUN_CODE(err_code); - } else { + } else { - /* Get MAPPED-ADDRESS or XOR-MAPPED-ADDRESS */ - mattr = (pj_stun_sockaddr_attr*) - pj_stun_msg_find_attr(response, PJ_STUN_ATTR_XOR_MAPPED_ADDR, 0); - if (mattr == NULL) { - mattr = (pj_stun_sockaddr_attr*) - pj_stun_msg_find_attr(response, PJ_STUN_ATTR_MAPPED_ADDR, 0); - } + /* Get MAPPED-ADDRESS or XOR-MAPPED-ADDRESS */ + mattr = (pj_stun_sockaddr_attr*) + pj_stun_msg_find_attr(response, PJ_STUN_ATTR_XOR_MAPPED_ADDR, 0); + if (mattr == NULL) { + mattr = (pj_stun_sockaddr_attr*) + pj_stun_msg_find_attr(response, PJ_STUN_ATTR_MAPPED_ADDR, 0); + } - if (mattr == NULL) { - status = PJNATH_ESTUNNOMAPPEDADDR; - } + if (mattr == NULL) { + status = PJNATH_ESTUNNOMAPPEDADDR; + } - /* Get CHANGED-ADDRESS attribute */ - ca = (pj_stun_changed_addr_attr*) - pj_stun_msg_find_attr(response, PJ_STUN_ATTR_CHANGED_ADDR, 0); + /* Get CHANGED-ADDRESS attribute */ + ca = (pj_stun_changed_addr_attr*) + pj_stun_msg_find_attr(response, PJ_STUN_ATTR_CHANGED_ADDR, 0); - if (ca == NULL) { - status = PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_SERVER_ERROR); - } + if (ca == NULL) { + status = PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_SERVER_ERROR); + } - } + } } /* Save the result */ @@ -574,39 +573,39 @@ static void on_request_complete(pj_stun_session *stun_sess, test_id = tsx_id[2]; if (test_id >= ST_MAX) { - PJ_LOG(4,(sess->pool->obj_name, "Invalid transaction ID %u in response", - test_id)); - end_session(sess, PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_SERVER_ERROR), - PJ_STUN_NAT_TYPE_ERR_UNKNOWN); - goto on_return; + PJ_LOG(4,(sess->pool->obj_name, "Invalid transaction ID %u in response", + test_id)); + end_session(sess, PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_SERVER_ERROR), + PJ_STUN_NAT_TYPE_ERR_UNKNOWN); + goto on_return; } PJ_PERROR(5,(sess->pool->obj_name, status, "Completed %s", - test_names[test_id])); + test_names[test_id])); sess->result[test_id].complete = PJ_TRUE; sess->result[test_id].status = status; if (status == PJ_SUCCESS) { - pj_sockaddr_cp(&sess->result[test_id].ma, &mattr->sockaddr); - pj_sockaddr_cp(&sess->result[test_id].ca, &ca->sockaddr); + pj_sockaddr_cp(&sess->result[test_id].ma, &mattr->sockaddr); + pj_sockaddr_cp(&sess->result[test_id].ca, &ca->sockaddr); } /* Send Test 1B only when Test 2 completes. Must not send Test 1B * before Test 2 completes to avoid creating mapping on the NAT. */ if (!sess->result[ST_TEST_1B].executed && - sess->result[ST_TEST_2].complete && - sess->result[ST_TEST_2].status != PJ_SUCCESS && - sess->result[ST_TEST_1].complete && - sess->result[ST_TEST_1].status == PJ_SUCCESS) + sess->result[ST_TEST_2].complete && + sess->result[ST_TEST_2].status != PJ_SUCCESS && + sess->result[ST_TEST_1].complete && + sess->result[ST_TEST_1].status == PJ_SUCCESS) { - cmp = pj_sockaddr_cmp(&sess->local_addr, &sess->result[ST_TEST_1].ma); - if (cmp != 0) - send_test(sess, ST_TEST_1B, &sess->result[ST_TEST_1].ca, 0); + cmp = pj_sockaddr_cmp(&sess->local_addr, &sess->result[ST_TEST_1].ma); + if (cmp != 0) + send_test(sess, ST_TEST_1B, &sess->result[ST_TEST_1].ca, 0); } if (test_completed(sess)<3 || test_completed(sess)!=test_executed(sess)) - goto on_return; + goto on_return; /* Handle the test result according to RFC 3489 page 22: @@ -659,158 +658,158 @@ static void on_request_complete(pj_stun_session *stun_sess, switch (sess->result[ST_TEST_1].status) { case PJNATH_ESTUNTIMEDOUT: - /* - * Test 1 has timed-out. Conclude with NAT_TYPE_BLOCKED. - */ - end_session(sess, PJ_SUCCESS, PJ_STUN_NAT_TYPE_BLOCKED); - break; + /* + * Test 1 has timed-out. Conclude with NAT_TYPE_BLOCKED. + */ + end_session(sess, PJ_SUCCESS, PJ_STUN_NAT_TYPE_BLOCKED); + break; case PJ_SUCCESS: - /* - * Test 1 is successful. Further tests are needed to detect - * NAT type. Compare the MAPPED-ADDRESS with the local address. - */ - cmp = pj_sockaddr_cmp(&sess->local_addr, &sess->result[ST_TEST_1].ma); - if (cmp==0) { - /* - * MAPPED-ADDRESS and local address is equal. Need one more - * test to determine NAT type. - */ - switch (sess->result[ST_TEST_2].status) { - case PJ_SUCCESS: - /* - * Test 2 is also successful. We're in the open. - */ - end_session(sess, PJ_SUCCESS, PJ_STUN_NAT_TYPE_OPEN); - break; - case PJNATH_ESTUNTIMEDOUT: - /* - * Test 2 has timed out. We're behind somekind of UDP - * firewall. - */ - end_session(sess, PJ_SUCCESS, PJ_STUN_NAT_TYPE_SYMMETRIC_UDP); - break; - default: - /* - * We've got other error with Test 2. - */ - end_session(sess, sess->result[ST_TEST_2].status, - PJ_STUN_NAT_TYPE_ERR_UNKNOWN); - break; - } - } else { - /* - * MAPPED-ADDRESS is different than local address. - * We're behind NAT. - */ - switch (sess->result[ST_TEST_2].status) { - case PJ_SUCCESS: - /* - * Test 2 is successful. We're behind a full-cone NAT. - */ - end_session(sess, PJ_SUCCESS, PJ_STUN_NAT_TYPE_FULL_CONE); - break; - case PJNATH_ESTUNTIMEDOUT: - /* - * Test 2 has timed-out Check result of test 1B.. - */ - switch (sess->result[ST_TEST_1B].status) { - case PJ_SUCCESS: - /* - * Compare the MAPPED-ADDRESS of test 1B with the - * MAPPED-ADDRESS returned in test 1.. - */ - cmp = pj_sockaddr_cmp(&sess->result[ST_TEST_1].ma, - &sess->result[ST_TEST_1B].ma); - if (cmp != 0) { - /* - * MAPPED-ADDRESS is different, we're behind a - * symmetric NAT. - */ - end_session(sess, PJ_SUCCESS, - PJ_STUN_NAT_TYPE_SYMMETRIC); - } else { - /* - * MAPPED-ADDRESS is equal. We're behind a restricted - * or port-restricted NAT, depending on the result of - * test 3. - */ - switch (sess->result[ST_TEST_3].status) { - case PJ_SUCCESS: - /* - * Test 3 is successful, we're behind a restricted - * NAT. - */ - end_session(sess, PJ_SUCCESS, - PJ_STUN_NAT_TYPE_RESTRICTED); - break; - case PJNATH_ESTUNTIMEDOUT: - /* - * Test 3 failed, we're behind a port restricted - * NAT. - */ - end_session(sess, PJ_SUCCESS, - PJ_STUN_NAT_TYPE_PORT_RESTRICTED); - break; - default: - /* - * Got other error with test 3. - */ - end_session(sess, sess->result[ST_TEST_3].status, - PJ_STUN_NAT_TYPE_ERR_UNKNOWN); - break; - } - } - break; - case PJNATH_ESTUNTIMEDOUT: - /* - * Strangely test 1B has failed. Maybe connectivity was - * lost? Or perhaps port 3489 (the usual port number in - * CHANGED-ADDRESS) is blocked? - */ - switch (sess->result[ST_TEST_3].status) { - case PJ_SUCCESS: - /* Although test 1B failed, test 3 was successful. - * It could be that port 3489 is blocked, while the - * NAT itself looks to be a Restricted one. - */ - end_session(sess, PJ_SUCCESS, - PJ_STUN_NAT_TYPE_RESTRICTED); - break; - default: - /* Can't distinguish between Symmetric and Port - * Restricted, so set the type to Unknown - */ - end_session(sess, PJ_SUCCESS, - PJ_STUN_NAT_TYPE_ERR_UNKNOWN); - break; - } - break; - default: - /* - * Got other error with test 1B. - */ - end_session(sess, sess->result[ST_TEST_1B].status, - PJ_STUN_NAT_TYPE_ERR_UNKNOWN); - break; - } - break; - default: - /* - * We've got other error with Test 2. - */ - end_session(sess, sess->result[ST_TEST_2].status, - PJ_STUN_NAT_TYPE_ERR_UNKNOWN); - break; - } - } - break; + /* + * Test 1 is successful. Further tests are needed to detect + * NAT type. Compare the MAPPED-ADDRESS with the local address. + */ + cmp = pj_sockaddr_cmp(&sess->local_addr, &sess->result[ST_TEST_1].ma); + if (cmp==0) { + /* + * MAPPED-ADDRESS and local address is equal. Need one more + * test to determine NAT type. + */ + switch (sess->result[ST_TEST_2].status) { + case PJ_SUCCESS: + /* + * Test 2 is also successful. We're in the open. + */ + end_session(sess, PJ_SUCCESS, PJ_STUN_NAT_TYPE_OPEN); + break; + case PJNATH_ESTUNTIMEDOUT: + /* + * Test 2 has timed out. We're behind somekind of UDP + * firewall. + */ + end_session(sess, PJ_SUCCESS, PJ_STUN_NAT_TYPE_SYMMETRIC_UDP); + break; + default: + /* + * We've got other error with Test 2. + */ + end_session(sess, sess->result[ST_TEST_2].status, + PJ_STUN_NAT_TYPE_ERR_UNKNOWN); + break; + } + } else { + /* + * MAPPED-ADDRESS is different than local address. + * We're behind NAT. + */ + switch (sess->result[ST_TEST_2].status) { + case PJ_SUCCESS: + /* + * Test 2 is successful. We're behind a full-cone NAT. + */ + end_session(sess, PJ_SUCCESS, PJ_STUN_NAT_TYPE_FULL_CONE); + break; + case PJNATH_ESTUNTIMEDOUT: + /* + * Test 2 has timed-out Check result of test 1B.. + */ + switch (sess->result[ST_TEST_1B].status) { + case PJ_SUCCESS: + /* + * Compare the MAPPED-ADDRESS of test 1B with the + * MAPPED-ADDRESS returned in test 1.. + */ + cmp = pj_sockaddr_cmp(&sess->result[ST_TEST_1].ma, + &sess->result[ST_TEST_1B].ma); + if (cmp != 0) { + /* + * MAPPED-ADDRESS is different, we're behind a + * symmetric NAT. + */ + end_session(sess, PJ_SUCCESS, + PJ_STUN_NAT_TYPE_SYMMETRIC); + } else { + /* + * MAPPED-ADDRESS is equal. We're behind a restricted + * or port-restricted NAT, depending on the result of + * test 3. + */ + switch (sess->result[ST_TEST_3].status) { + case PJ_SUCCESS: + /* + * Test 3 is successful, we're behind a restricted + * NAT. + */ + end_session(sess, PJ_SUCCESS, + PJ_STUN_NAT_TYPE_RESTRICTED); + break; + case PJNATH_ESTUNTIMEDOUT: + /* + * Test 3 failed, we're behind a port restricted + * NAT. + */ + end_session(sess, PJ_SUCCESS, + PJ_STUN_NAT_TYPE_PORT_RESTRICTED); + break; + default: + /* + * Got other error with test 3. + */ + end_session(sess, sess->result[ST_TEST_3].status, + PJ_STUN_NAT_TYPE_ERR_UNKNOWN); + break; + } + } + break; + case PJNATH_ESTUNTIMEDOUT: + /* + * Strangely test 1B has failed. Maybe connectivity was + * lost? Or perhaps port 3489 (the usual port number in + * CHANGED-ADDRESS) is blocked? + */ + switch (sess->result[ST_TEST_3].status) { + case PJ_SUCCESS: + /* Although test 1B failed, test 3 was successful. + * It could be that port 3489 is blocked, while the + * NAT itself looks to be a Restricted one. + */ + end_session(sess, PJ_SUCCESS, + PJ_STUN_NAT_TYPE_RESTRICTED); + break; + default: + /* Can't distinguish between Symmetric and Port + * Restricted, so set the type to Unknown + */ + end_session(sess, PJ_SUCCESS, + PJ_STUN_NAT_TYPE_ERR_UNKNOWN); + break; + } + break; + default: + /* + * Got other error with test 1B. + */ + end_session(sess, sess->result[ST_TEST_1B].status, + PJ_STUN_NAT_TYPE_ERR_UNKNOWN); + break; + } + break; + default: + /* + * We've got other error with Test 2. + */ + end_session(sess, sess->result[ST_TEST_2].status, + PJ_STUN_NAT_TYPE_ERR_UNKNOWN); + break; + } + } + break; default: - /* - * We've got other error with Test 1. - */ - end_session(sess, sess->result[ST_TEST_1].status, - PJ_STUN_NAT_TYPE_ERR_UNKNOWN); - break; + /* + * We've got other error with Test 1. + */ + end_session(sess, sess->result[ST_TEST_1].status, + PJ_STUN_NAT_TYPE_ERR_UNKNOWN); + break; } on_return: @@ -820,9 +819,9 @@ static void on_request_complete(pj_stun_session *stun_sess, /* Perform test */ static pj_status_t send_test(nat_detect_session *sess, - enum test_type test_id, - const pj_sockaddr *alt_addr, - pj_uint32_t change_flag) + enum test_type test_id, + const pj_sockaddr *alt_addr, + pj_uint32_t change_flag) { pj_uint32_t magic, tsx_id[3]; char addr[PJ_INET6_ADDRSTRLEN]; @@ -832,7 +831,7 @@ static pj_status_t send_test(nat_detect_session *sess, /* Randomize tsx id */ do { - magic = pj_rand(); + magic = pj_rand(); } while (magic == PJ_STUN_MAGIC); tsx_id[0] = pj_rand(); @@ -841,45 +840,45 @@ static pj_status_t send_test(nat_detect_session *sess, /* Create BIND request */ status = pj_stun_session_create_req(sess->stun_sess, - PJ_STUN_BINDING_REQUEST, magic, - (pj_uint8_t*)tsx_id, - &sess->result[test_id].tdata); + PJ_STUN_BINDING_REQUEST, magic, + (pj_uint8_t*)tsx_id, + &sess->result[test_id].tdata); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Add CHANGE-REQUEST attribute */ status = pj_stun_msg_add_uint_attr(sess->pool, - sess->result[test_id].tdata->msg, - PJ_STUN_ATTR_CHANGE_REQUEST, - change_flag); + sess->result[test_id].tdata->msg, + PJ_STUN_ATTR_CHANGE_REQUEST, + change_flag); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Configure alternate address, synthesize it if necessary */ if (alt_addr) { status = pj_sockaddr_synthesize(sess->server.addr.sa_family, - &sess->cur_addr, alt_addr); + &sess->cur_addr, alt_addr); if (status != PJ_SUCCESS) goto on_error; - sess->cur_server = &sess->cur_addr; + sess->cur_server = &sess->cur_addr; } else { - sess->cur_server = &sess->server; + sess->cur_server = &sess->server; } PJ_LOG(5,(sess->pool->obj_name, "Performing %s to %s:%d", - test_names[test_id], - pj_sockaddr_print(sess->cur_server, addr, sizeof(addr), 2), - pj_sockaddr_get_port(sess->cur_server))); + test_names[test_id], + pj_sockaddr_print(sess->cur_server, addr, sizeof(addr), 2), + pj_sockaddr_get_port(sess->cur_server))); /* Send the request */ status = pj_stun_session_send_msg(sess->stun_sess, NULL, PJ_TRUE, - PJ_TRUE, sess->cur_server, - pj_sockaddr_get_len(sess->cur_server), - sess->result[test_id].tdata); + PJ_TRUE, sess->cur_server, + pj_sockaddr_get_len(sess->cur_server), + sess->result[test_id].tdata); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; return PJ_SUCCESS; @@ -893,55 +892,55 @@ static pj_status_t send_test(nat_detect_session *sess, /* Timer callback */ static void on_sess_timer(pj_timer_heap_t *th, - pj_timer_entry *te) + pj_timer_entry *te) { nat_detect_session *sess; sess = (nat_detect_session*) te->user_data; if (te->id == TIMER_DESTROY) { - pj_grp_lock_acquire(sess->grp_lock); - pj_ioqueue_unregister(sess->key); - sess->key = NULL; - sess->sock = PJ_INVALID_SOCKET; - te->id = 0; - pj_grp_lock_release(sess->grp_lock); + pj_grp_lock_acquire(sess->grp_lock); + pj_ioqueue_unregister(sess->key); + sess->key = NULL; + sess->sock = PJ_INVALID_SOCKET; + te->id = 0; + pj_grp_lock_release(sess->grp_lock); - sess_destroy(sess); + sess_destroy(sess); } else if (te->id == TIMER_TEST) { - pj_bool_t next_timer; + pj_bool_t next_timer; - pj_grp_lock_acquire(sess->grp_lock); + pj_grp_lock_acquire(sess->grp_lock); - next_timer = PJ_FALSE; + next_timer = PJ_FALSE; - if (sess->timer_executed == 0) { - send_test(sess, ST_TEST_1, NULL, 0); - next_timer = PJ_TRUE; - } else if (sess->timer_executed == 1) { - send_test(sess, ST_TEST_2, NULL, CHANGE_IP_PORT_FLAG); - next_timer = PJ_TRUE; - } else if (sess->timer_executed == 2) { - send_test(sess, ST_TEST_3, NULL, CHANGE_PORT_FLAG); - } else { - pj_assert(!"Shouldn't have timer at this state"); - } + if (sess->timer_executed == 0) { + send_test(sess, ST_TEST_1, NULL, 0); + next_timer = PJ_TRUE; + } else if (sess->timer_executed == 1) { + send_test(sess, ST_TEST_2, NULL, CHANGE_IP_PORT_FLAG); + next_timer = PJ_TRUE; + } else if (sess->timer_executed == 2) { + send_test(sess, ST_TEST_3, NULL, CHANGE_PORT_FLAG); + } else { + pj_assert(!"Shouldn't have timer at this state"); + } - ++sess->timer_executed; + ++sess->timer_executed; - if (next_timer) { - pj_time_val delay = {0, TEST_INTERVAL}; - pj_timer_heap_schedule(th, te, &delay); - } else { - te->id = 0; - } + if (next_timer) { + pj_time_val delay = {0, TEST_INTERVAL}; + pj_timer_heap_schedule(th, te, &delay); + } else { + te->id = 0; + } - pj_grp_lock_release(sess->grp_lock); + pj_grp_lock_release(sess->grp_lock); } else { - pj_assert(!"Invalid timer ID"); + pj_assert(!"Invalid timer ID"); } } diff --git a/pjnath/src/pjnath/stun_auth.c b/pjnath/src/pjnath/stun_auth.c index 7b34b7463c..22b607e941 100644 --- a/pjnath/src/pjnath/stun_auth.c +++ b/pjnath/src/pjnath/stun_auth.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,27 +30,27 @@ /* Duplicate credential */ PJ_DEF(void) pj_stun_auth_cred_dup( pj_pool_t *pool, - pj_stun_auth_cred *dst, - const pj_stun_auth_cred *src) + pj_stun_auth_cred *dst, + const pj_stun_auth_cred *src) { dst->type = src->type; switch (src->type) { case PJ_STUN_AUTH_CRED_STATIC: - pj_strdup(pool, &dst->data.static_cred.realm, - &src->data.static_cred.realm); - pj_strdup(pool, &dst->data.static_cred.username, - &src->data.static_cred.username); - dst->data.static_cred.data_type = src->data.static_cred.data_type; - pj_strdup(pool, &dst->data.static_cred.data, - &src->data.static_cred.data); - pj_strdup(pool, &dst->data.static_cred.nonce, - &src->data.static_cred.nonce); - break; + pj_strdup(pool, &dst->data.static_cred.realm, + &src->data.static_cred.realm); + pj_strdup(pool, &dst->data.static_cred.username, + &src->data.static_cred.username); + dst->data.static_cred.data_type = src->data.static_cred.data_type; + pj_strdup(pool, &dst->data.static_cred.data, + &src->data.static_cred.data); + pj_strdup(pool, &dst->data.static_cred.nonce, + &src->data.static_cred.nonce); + break; case PJ_STUN_AUTH_CRED_DYNAMIC: - pj_memcpy(&dst->data.dyn_cred, &src->data.dyn_cred, - sizeof(src->data.dyn_cred)); - break; + pj_memcpy(&dst->data.dyn_cred, &src->data.dyn_cred, + sizeof(src->data.dyn_cred)); + break; } } @@ -60,8 +59,8 @@ PJ_DEF(void) pj_stun_auth_cred_dup( pj_pool_t *pool, * Duplicate request credential. */ PJ_DEF(void) pj_stun_req_cred_info_dup( pj_pool_t *pool, - pj_stun_req_cred_info *dst, - const pj_stun_req_cred_info *src) + pj_stun_req_cred_info *dst, + const pj_stun_req_cred_info *src) { pj_strdup(pool, &dst->realm, &src->realm); pj_strdup(pool, &dst->username, &src->username); @@ -74,9 +73,9 @@ PJ_DEF(void) pj_stun_req_cred_info_dup( pj_pool_t *pool, * MD5 digest of username, realm, and password. */ static void calc_md5_key(pj_uint8_t digest[16], - const pj_str_t *realm, - const pj_str_t *username, - const pj_str_t *passwd) + const pj_str_t *realm, + const pj_str_t *username, + const pj_str_t *passwd) { /* The 16-byte key for MESSAGE-INTEGRITY HMAC is formed by taking * the MD5 hash of the result of concatenating the following five @@ -90,10 +89,10 @@ static void calc_md5_key(pj_uint8_t digest[16], pj_md5_init(&ctx); -#define REMOVE_QUOTE(s) if (s.slen && *s.ptr=='"') \ - s.ptr++, s.slen--; \ - if (s.slen && s.ptr[s.slen-1]=='"') \ - s.slen--; +#define REMOVE_QUOTE(s) if (s.slen && *s.ptr=='"') \ + s.ptr++, s.slen--; \ + if (s.slen && s.ptr[s.slen-1]=='"') \ + s.slen--; /* Add username */ s = *username; @@ -126,25 +125,25 @@ static void calc_md5_key(pj_uint8_t digest[16], * MESSAGE-INTEGRITY. */ PJ_DEF(void) pj_stun_create_key(pj_pool_t *pool, - pj_str_t *key, - const pj_str_t *realm, - const pj_str_t *username, - pj_stun_passwd_type data_type, - const pj_str_t *data) + pj_str_t *key, + const pj_str_t *realm, + const pj_str_t *username, + pj_stun_passwd_type data_type, + const pj_str_t *data) { PJ_ASSERT_ON_FAIL(pool && key && username && data, return); if (realm && realm->slen) { - if (data_type == PJ_STUN_PASSWD_PLAIN) { - key->ptr = (char*) pj_pool_alloc(pool, 16); - calc_md5_key((pj_uint8_t*)key->ptr, realm, username, data); - key->slen = 16; - } else { - pj_strdup(pool, key, data); - } + if (data_type == PJ_STUN_PASSWD_PLAIN) { + key->ptr = (char*) pj_pool_alloc(pool, 16); + calc_md5_key((pj_uint8_t*)key->ptr, realm, username, data); + key->slen = 16; + } else { + pj_strdup(pool, key, data); + } } else { - pj_assert(data_type == PJ_STUN_PASSWD_PLAIN); - pj_strdup(pool, key, data); + pj_assert(data_type == PJ_STUN_PASSWD_PLAIN); + pj_strdup(pool, key, data); } } @@ -164,12 +163,12 @@ PJ_INLINE(void) PUT_VAL16(pj_uint8_t *buf, unsigned pos, pj_uint16_t hval) /* Send 401 response */ static pj_status_t create_challenge(pj_pool_t *pool, - const pj_stun_msg *msg, - int err_code, - const char *errstr, - const pj_str_t *realm, - const pj_str_t *nonce, - pj_stun_msg **p_response) + const pj_stun_msg *msg, + int err_code, + const char *errstr, + const pj_str_t *realm, + const pj_str_t *nonce, + pj_stun_msg **p_response) { pj_stun_msg *response; pj_str_t tmp_nonce; @@ -177,32 +176,32 @@ static pj_status_t create_challenge(pj_pool_t *pool, pj_status_t rc; rc = pj_stun_msg_create_response(pool, msg, err_code, - (errstr?pj_cstr(&err_msg, errstr):NULL), - &response); + (errstr?pj_cstr(&err_msg, errstr):NULL), + &response); if (rc != PJ_SUCCESS) - return rc; + return rc; /* SHOULD NOT add REALM, NONCE, USERNAME, and M-I on 400 response */ if (err_code!=400 && realm && realm->slen) { - rc = pj_stun_msg_add_string_attr(pool, response, - PJ_STUN_ATTR_REALM, - realm); - if (rc != PJ_SUCCESS) - return rc; - - /* long term must include nonce */ - if (!nonce || nonce->slen == 0) { - tmp_nonce = pj_str("pjstun"); - nonce = &tmp_nonce; - } + rc = pj_stun_msg_add_string_attr(pool, response, + PJ_STUN_ATTR_REALM, + realm); + if (rc != PJ_SUCCESS) + return rc; + + /* long term must include nonce */ + if (!nonce || nonce->slen == 0) { + tmp_nonce = pj_str("pjstun"); + nonce = &tmp_nonce; + } } if (err_code!=400 && nonce && nonce->slen) { - rc = pj_stun_msg_add_string_attr(pool, response, - PJ_STUN_ATTR_NONCE, - nonce); - if (rc != PJ_SUCCESS) - return rc; + rc = pj_stun_msg_add_string_attr(pool, response, + PJ_STUN_ATTR_NONCE, + nonce); + if (rc != PJ_SUCCESS) + return rc; } *p_response = response; @@ -213,12 +212,12 @@ static pj_status_t create_challenge(pj_pool_t *pool, /* Verify credential in the request */ PJ_DEF(pj_status_t) pj_stun_authenticate_request(const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_msg *msg, - pj_stun_auth_cred *cred, - pj_pool_t *pool, - pj_stun_req_cred_info *p_info, - pj_stun_msg **p_response) + unsigned pkt_len, + const pj_stun_msg *msg, + pj_stun_auth_cred *cred, + pj_pool_t *pool, + pj_stun_req_cred_info *p_info, + pj_stun_msg **p_response) { pj_stun_req_cred_info tmp_info; const pj_stun_msgint_attr *amsgi; @@ -240,30 +239,30 @@ PJ_DEF(pj_status_t) pj_stun_authenticate_request(const pj_uint8_t *pkt, PJ_ASSERT_RETURN(!p_response || pool, PJ_EINVAL); if (p_response) - *p_response = NULL; + *p_response = NULL; if (!PJ_STUN_IS_REQUEST(msg->hdr.type)) - p_response = NULL; + p_response = NULL; if (p_info == NULL) - p_info = &tmp_info; + p_info = &tmp_info; pj_bzero(p_info, sizeof(pj_stun_req_cred_info)); /* Get realm and nonce from credential */ p_info->realm.slen = p_info->nonce.slen = 0; if (cred->type == PJ_STUN_AUTH_CRED_STATIC) { - p_info->realm = cred->data.static_cred.realm; - p_info->nonce = cred->data.static_cred.nonce; + p_info->realm = cred->data.static_cred.realm; + p_info->nonce = cred->data.static_cred.nonce; } else if (cred->type == PJ_STUN_AUTH_CRED_DYNAMIC) { - status = cred->data.dyn_cred.get_auth(cred->data.dyn_cred.user_data, - pool, &p_info->realm, - &p_info->nonce); - if (status != PJ_SUCCESS) - return status; + status = cred->data.dyn_cred.get_auth(cred->data.dyn_cred.user_data, + pool, &p_info->realm, + &p_info->nonce); + if (status != PJ_SUCCESS) + return status; } else { - pj_assert(!"Invalid credential type"); - return PJ_EBUG; + pj_assert(!"Invalid credential type"); + return PJ_EBUG; } /* Look for MESSAGE-INTEGRITY while counting the position */ @@ -271,179 +270,179 @@ PJ_DEF(pj_status_t) pj_stun_authenticate_request(const pj_uint8_t *pkt, has_attr_beyond_mi = PJ_FALSE; amsgi = NULL; for (i=0; iattr_count; ++i) { - if (msg->attr[i]->type == PJ_STUN_ATTR_MESSAGE_INTEGRITY) { - amsgi = (const pj_stun_msgint_attr*) msg->attr[i]; - } else if (amsgi) { - has_attr_beyond_mi = PJ_TRUE; - break; - } else { - amsgi_pos += ((msg->attr[i]->length+3) & ~0x03) + 4; - } + if (msg->attr[i]->type == PJ_STUN_ATTR_MESSAGE_INTEGRITY) { + amsgi = (const pj_stun_msgint_attr*) msg->attr[i]; + } else if (amsgi) { + has_attr_beyond_mi = PJ_TRUE; + break; + } else { + amsgi_pos += ((msg->attr[i]->length+3) & ~0x03) + 4; + } } if (amsgi == NULL) { - /* According to rfc3489bis-10 Sec 10.1.2/10.2.2, we should return 400 - for short term, and 401 for long term. - The rule has been changed from rfc3489bis-06 - */ - err_code = p_info->realm.slen ? PJ_STUN_SC_UNAUTHORIZED : - PJ_STUN_SC_BAD_REQUEST; - goto on_auth_failed; + /* According to rfc3489bis-10 Sec 10.1.2/10.2.2, we should return 400 + for short term, and 401 for long term. + The rule has been changed from rfc3489bis-06 + */ + err_code = p_info->realm.slen ? PJ_STUN_SC_UNAUTHORIZED : + PJ_STUN_SC_BAD_REQUEST; + goto on_auth_failed; } /* Next check that USERNAME is present */ auser = (const pj_stun_username_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_USERNAME, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_USERNAME, 0); if (auser == NULL) { - /* According to rfc3489bis-10 Sec 10.1.2/10.2.2, we should return 400 - for both short and long term, since M-I is present. - The rule has been changed from rfc3489bis-06 - */ - err_code = PJ_STUN_SC_BAD_REQUEST; - err_text = "Missing USERNAME"; - goto on_auth_failed; + /* According to rfc3489bis-10 Sec 10.1.2/10.2.2, we should return 400 + for both short and long term, since M-I is present. + The rule has been changed from rfc3489bis-06 + */ + err_code = PJ_STUN_SC_BAD_REQUEST; + err_text = "Missing USERNAME"; + goto on_auth_failed; } /* Get REALM, if any */ arealm = (const pj_stun_realm_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_REALM, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_REALM, 0); /* Reject with 400 if we have long term credential and the request * is missing REALM attribute. */ if (p_info->realm.slen && arealm==NULL) { - err_code = PJ_STUN_SC_BAD_REQUEST; - err_text = "Missing REALM"; - goto on_auth_failed; + err_code = PJ_STUN_SC_BAD_REQUEST; + err_text = "Missing REALM"; + goto on_auth_failed; } /* Check if username match */ if (cred->type == PJ_STUN_AUTH_CRED_STATIC) { - pj_bool_t username_ok; - username_ok = !pj_strcmp(&auser->value, - &cred->data.static_cred.username); - if (username_ok) { - pj_strdup(pool, &p_info->username, - &cred->data.static_cred.username); - pj_stun_create_key(pool, &p_info->auth_key, &p_info->realm, - &auser->value, cred->data.static_cred.data_type, - &cred->data.static_cred.data); - } else { - /* Username mismatch */ - /* According to rfc3489bis-10 Sec 10.1.2/10.2.2, we should - * return 401 - */ - err_code = PJ_STUN_SC_UNAUTHORIZED; - goto on_auth_failed; - } + pj_bool_t username_ok; + username_ok = !pj_strcmp(&auser->value, + &cred->data.static_cred.username); + if (username_ok) { + pj_strdup(pool, &p_info->username, + &cred->data.static_cred.username); + pj_stun_create_key(pool, &p_info->auth_key, &p_info->realm, + &auser->value, cred->data.static_cred.data_type, + &cred->data.static_cred.data); + } else { + /* Username mismatch */ + /* According to rfc3489bis-10 Sec 10.1.2/10.2.2, we should + * return 401 + */ + err_code = PJ_STUN_SC_UNAUTHORIZED; + goto on_auth_failed; + } } else if (cred->type == PJ_STUN_AUTH_CRED_DYNAMIC) { - pj_stun_passwd_type data_type = PJ_STUN_PASSWD_PLAIN; - pj_str_t password; - pj_status_t rc; - - rc = cred->data.dyn_cred.get_password(msg, - cred->data.dyn_cred.user_data, - (arealm?&arealm->value:NULL), - &auser->value, pool, - &data_type, &password); - if (rc == PJ_SUCCESS) { - pj_strdup(pool, &p_info->username, &auser->value); - pj_stun_create_key(pool, &p_info->auth_key, - (arealm?&arealm->value:NULL), &auser->value, - data_type, &password); - } else { - err_code = PJ_STUN_SC_UNAUTHORIZED; - goto on_auth_failed; - } + pj_stun_passwd_type data_type = PJ_STUN_PASSWD_PLAIN; + pj_str_t password; + pj_status_t rc; + + rc = cred->data.dyn_cred.get_password(msg, + cred->data.dyn_cred.user_data, + (arealm?&arealm->value:NULL), + &auser->value, pool, + &data_type, &password); + if (rc == PJ_SUCCESS) { + pj_strdup(pool, &p_info->username, &auser->value); + pj_stun_create_key(pool, &p_info->auth_key, + (arealm?&arealm->value:NULL), &auser->value, + data_type, &password); + } else { + err_code = PJ_STUN_SC_UNAUTHORIZED; + goto on_auth_failed; + } } else { - pj_assert(!"Invalid credential type"); - return PJ_EBUG; + pj_assert(!"Invalid credential type"); + return PJ_EBUG; } /* Get NONCE attribute */ anonce = (pj_stun_nonce_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_NONCE, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_NONCE, 0); /* Check for long term/short term requirements. */ if (p_info->realm.slen != 0 && arealm == NULL) { - /* Long term credential is required and REALM is not present */ - err_code = PJ_STUN_SC_BAD_REQUEST; - err_text = "Missing REALM"; - goto on_auth_failed; + /* Long term credential is required and REALM is not present */ + err_code = PJ_STUN_SC_BAD_REQUEST; + err_text = "Missing REALM"; + goto on_auth_failed; } else if (p_info->realm.slen != 0 && arealm != NULL) { - /* We want long term, and REALM is present */ + /* We want long term, and REALM is present */ - /* NONCE must be present. */ - if (anonce == NULL && p_info->nonce.slen) { - err_code = PJ_STUN_SC_BAD_REQUEST; - err_text = "Missing NONCE"; - goto on_auth_failed; - } + /* NONCE must be present. */ + if (anonce == NULL && p_info->nonce.slen) { + err_code = PJ_STUN_SC_BAD_REQUEST; + err_text = "Missing NONCE"; + goto on_auth_failed; + } - /* Verify REALM matches */ - if (pj_stricmp(&arealm->value, &p_info->realm)) { - /* REALM doesn't match */ - err_code = PJ_STUN_SC_UNAUTHORIZED; - err_text = "Invalid REALM"; - goto on_auth_failed; - } + /* Verify REALM matches */ + if (pj_stricmp(&arealm->value, &p_info->realm)) { + /* REALM doesn't match */ + err_code = PJ_STUN_SC_UNAUTHORIZED; + err_text = "Invalid REALM"; + goto on_auth_failed; + } - /* Valid case, will validate the message integrity later */ + /* Valid case, will validate the message integrity later */ } else if (p_info->realm.slen == 0 && arealm != NULL) { - /* We want to use short term credential, but client uses long - * term credential. The draft doesn't mention anything about - * switching between long term and short term. - */ - - /* For now just accept the credential, anyway it will probably - * cause wrong message integrity value later. - */ + /* We want to use short term credential, but client uses long + * term credential. The draft doesn't mention anything about + * switching between long term and short term. + */ + + /* For now just accept the credential, anyway it will probably + * cause wrong message integrity value later. + */ } else if (p_info->realm.slen==0 && arealm == NULL) { - /* Short term authentication is wanted, and one is supplied */ - - /* Application MAY request NONCE to be supplied */ - if (p_info->nonce.slen != 0) { - err_code = PJ_STUN_SC_UNAUTHORIZED; - err_text = "NONCE required"; - goto on_auth_failed; - } + /* Short term authentication is wanted, and one is supplied */ + + /* Application MAY request NONCE to be supplied */ + if (p_info->nonce.slen != 0) { + err_code = PJ_STUN_SC_UNAUTHORIZED; + err_text = "NONCE required"; + goto on_auth_failed; + } } /* If NONCE is present, validate it */ if (anonce) { - pj_bool_t ok; - - if (cred->type == PJ_STUN_AUTH_CRED_DYNAMIC && - cred->data.dyn_cred.verify_nonce != NULL) - { - ok=cred->data.dyn_cred.verify_nonce(msg, - cred->data.dyn_cred.user_data, - (arealm?&arealm->value:NULL), - &auser->value, - &anonce->value); - } else if (cred->type == PJ_STUN_AUTH_CRED_DYNAMIC) { - ok = PJ_TRUE; - } else { - if (p_info->nonce.slen) { - ok = !pj_strcmp(&anonce->value, &p_info->nonce); - } else { - ok = PJ_TRUE; - } - } - - if (!ok) { - err_code = PJ_STUN_SC_STALE_NONCE; - goto on_auth_failed; - } + pj_bool_t ok; + + if (cred->type == PJ_STUN_AUTH_CRED_DYNAMIC && + cred->data.dyn_cred.verify_nonce != NULL) + { + ok=cred->data.dyn_cred.verify_nonce(msg, + cred->data.dyn_cred.user_data, + (arealm?&arealm->value:NULL), + &auser->value, + &anonce->value); + } else if (cred->type == PJ_STUN_AUTH_CRED_DYNAMIC) { + ok = PJ_TRUE; + } else { + if (p_info->nonce.slen) { + ok = !pj_strcmp(&anonce->value, &p_info->nonce); + } else { + ok = PJ_TRUE; + } + } + + if (!ok) { + err_code = PJ_STUN_SC_STALE_NONCE; + goto on_auth_failed; + } } /* Now calculate HMAC of the message. */ pj_hmac_sha1_init(&ctx, (pj_uint8_t*)p_info->auth_key.ptr, - (unsigned)p_info->auth_key.slen); + (unsigned)p_info->auth_key.slen); #if PJ_STUN_OLD_STYLE_MI_FINGERPRINT /* Pre rfc3489bis-06 style of calculation */ @@ -454,23 +453,23 @@ PJ_DEF(pj_status_t) pj_stun_authenticate_request(const pj_uint8_t *pkt, * is present in the message. */ if (has_attr_beyond_mi) { - pj_uint8_t hdr_copy[20]; - pj_memcpy(hdr_copy, pkt, 20); - PUT_VAL16(hdr_copy, 2, (pj_uint16_t)(amsgi_pos + 24)); - pj_hmac_sha1_update(&ctx, hdr_copy, 20); + pj_uint8_t hdr_copy[20]; + pj_memcpy(hdr_copy, pkt, 20); + PUT_VAL16(hdr_copy, 2, (pj_uint16_t)(amsgi_pos + 24)); + pj_hmac_sha1_update(&ctx, hdr_copy, 20); } else { - pj_hmac_sha1_update(&ctx, pkt, 20); + pj_hmac_sha1_update(&ctx, pkt, 20); } -#endif /* PJ_STUN_OLD_STYLE_MI_FINGERPRINT */ +#endif /* PJ_STUN_OLD_STYLE_MI_FINGERPRINT */ /* Now update with the message body */ pj_hmac_sha1_update(&ctx, pkt+20, amsgi_pos); #if PJ_STUN_OLD_STYLE_MI_FINGERPRINT // This is no longer necessary as per rfc3489bis-08 if ((amsgi_pos+20) & 0x3F) { - pj_uint8_t zeroes[64]; - pj_bzero(zeroes, sizeof(zeroes)); - pj_hmac_sha1_update(&ctx, zeroes, 64-((amsgi_pos+20) & 0x3F)); + pj_uint8_t zeroes[64]; + pj_bzero(zeroes, sizeof(zeroes)); + pj_hmac_sha1_update(&ctx, zeroes, 64-((amsgi_pos+20) & 0x3F)); } #endif pj_hmac_sha1_final(&ctx, digest); @@ -478,11 +477,11 @@ PJ_DEF(pj_status_t) pj_stun_authenticate_request(const pj_uint8_t *pkt, /* Compare HMACs */ if (pj_memcmp(amsgi->hmac, digest, 20)) { - /* HMAC value mismatch */ - /* According to rfc3489bis-10 Sec 10.1.2 we should return 401 */ - err_code = PJ_STUN_SC_UNAUTHORIZED; - err_text = "MESSAGE-INTEGRITY mismatch"; - goto on_auth_failed; + /* HMAC value mismatch */ + /* According to rfc3489bis-10 Sec 10.1.2 we should return 401 */ + err_code = PJ_STUN_SC_UNAUTHORIZED; + err_text = "MESSAGE-INTEGRITY mismatch"; + goto on_auth_failed; } /* Everything looks okay! */ @@ -490,8 +489,8 @@ PJ_DEF(pj_status_t) pj_stun_authenticate_request(const pj_uint8_t *pkt, on_auth_failed: if (p_response) { - create_challenge(pool, msg, err_code, err_text, - &p_info->realm, &p_info->nonce, p_response); + create_challenge(pool, msg, err_code, err_text, + &p_info->realm, &p_info->nonce, p_response); } return PJ_STATUS_FROM_STUN_CODE(err_code); } @@ -505,46 +504,46 @@ PJ_DEF(pj_bool_t) pj_stun_auth_valid_for_msg(const pj_stun_msg *msg) /* STUN requests and success response can be authenticated */ if (!PJ_STUN_IS_ERROR_RESPONSE(msg_type) && - !PJ_STUN_IS_INDICATION(msg_type)) + !PJ_STUN_IS_INDICATION(msg_type)) { - return PJ_TRUE; + return PJ_TRUE; } /* STUN Indication cannot be authenticated */ if (PJ_STUN_IS_INDICATION(msg_type)) - return PJ_FALSE; + return PJ_FALSE; /* Authentication for STUN error responses depend on the error * code. */ err_attr = (const pj_stun_errcode_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_ERROR_CODE, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_ERROR_CODE, 0); if (err_attr == NULL) { - PJ_LOG(4,(THIS_FILE, "STUN error code attribute not present in " - "error response")); - return PJ_TRUE; + PJ_LOG(4,(THIS_FILE, "STUN error code attribute not present in " + "error response")); + return PJ_TRUE; } switch (err_attr->err_code) { - case PJ_STUN_SC_BAD_REQUEST: /* 400 (Bad Request) */ - case PJ_STUN_SC_UNAUTHORIZED: /* 401 (Unauthorized) */ - case PJ_STUN_SC_STALE_NONCE: /* 438 (Stale Nonce) */ + case PJ_STUN_SC_BAD_REQUEST: /* 400 (Bad Request) */ + case PJ_STUN_SC_UNAUTHORIZED: /* 401 (Unauthorized) */ + case PJ_STUN_SC_STALE_NONCE: /* 438 (Stale Nonce) */ /* Due to the way this response is generated here, we can't really - * authenticate 420 (Unknown Attribute) response */ + * authenticate 420 (Unknown Attribute) response */ case PJ_STUN_SC_UNKNOWN_ATTRIBUTE: - return PJ_FALSE; + return PJ_FALSE; default: - return PJ_TRUE; + return PJ_TRUE; } } /* Authenticate MESSAGE-INTEGRITY in the response */ PJ_DEF(pj_status_t) pj_stun_authenticate_response(const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_msg *msg, - const pj_str_t *key) + unsigned pkt_len, + const pj_stun_msg *msg, + const pj_str_t *key) { const pj_stun_msgint_attr *amsgi; unsigned i, amsgi_pos; @@ -556,15 +555,15 @@ PJ_DEF(pj_status_t) pj_stun_authenticate_response(const pj_uint8_t *pkt, /* First check that MESSAGE-INTEGRITY is present */ amsgi = (const pj_stun_msgint_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_MESSAGE_INTEGRITY, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_MESSAGE_INTEGRITY, 0); if (amsgi == NULL) { - return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNAUTHORIZED); + return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNAUTHORIZED); } /* Check that message length is valid */ if (msg->hdr.length < 24) { - return PJNATH_EINSTUNMSGLEN; + return PJNATH_EINSTUNMSGLEN; } /* Look for MESSAGE-INTEGRITY while counting the position */ @@ -572,18 +571,18 @@ PJ_DEF(pj_status_t) pj_stun_authenticate_response(const pj_uint8_t *pkt, has_attr_beyond_mi = PJ_FALSE; amsgi = NULL; for (i=0; iattr_count; ++i) { - if (msg->attr[i]->type == PJ_STUN_ATTR_MESSAGE_INTEGRITY) { - amsgi = (const pj_stun_msgint_attr*) msg->attr[i]; - } else if (amsgi) { - has_attr_beyond_mi = PJ_TRUE; - break; - } else { - amsgi_pos += ((msg->attr[i]->length+3) & ~0x03) + 4; - } + if (msg->attr[i]->type == PJ_STUN_ATTR_MESSAGE_INTEGRITY) { + amsgi = (const pj_stun_msgint_attr*) msg->attr[i]; + } else if (amsgi) { + has_attr_beyond_mi = PJ_TRUE; + break; + } else { + amsgi_pos += ((msg->attr[i]->length+3) & ~0x03) + 4; + } } if (amsgi == NULL) { - return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_BAD_REQUEST); + return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_BAD_REQUEST); } /* Now calculate HMAC of the message. */ @@ -598,31 +597,31 @@ PJ_DEF(pj_status_t) pj_stun_authenticate_response(const pj_uint8_t *pkt, * is present in the message. */ if (has_attr_beyond_mi) { - pj_uint8_t hdr_copy[20]; - pj_memcpy(hdr_copy, pkt, 20); - PUT_VAL16(hdr_copy, 2, (pj_uint16_t)(amsgi_pos+24)); - pj_hmac_sha1_update(&ctx, hdr_copy, 20); + pj_uint8_t hdr_copy[20]; + pj_memcpy(hdr_copy, pkt, 20); + PUT_VAL16(hdr_copy, 2, (pj_uint16_t)(amsgi_pos+24)); + pj_hmac_sha1_update(&ctx, hdr_copy, 20); } else { - pj_hmac_sha1_update(&ctx, pkt, 20); + pj_hmac_sha1_update(&ctx, pkt, 20); } -#endif /* PJ_STUN_OLD_STYLE_MI_FINGERPRINT */ +#endif /* PJ_STUN_OLD_STYLE_MI_FINGERPRINT */ /* Now update with the message body */ pj_hmac_sha1_update(&ctx, pkt+20, amsgi_pos); #if PJ_STUN_OLD_STYLE_MI_FINGERPRINT // This is no longer necessary as per rfc3489bis-08 if ((amsgi_pos+20) & 0x3F) { - pj_uint8_t zeroes[64]; - pj_bzero(zeroes, sizeof(zeroes)); - pj_hmac_sha1_update(&ctx, zeroes, 64-((amsgi_pos+20) & 0x3F)); + pj_uint8_t zeroes[64]; + pj_bzero(zeroes, sizeof(zeroes)); + pj_hmac_sha1_update(&ctx, zeroes, 64-((amsgi_pos+20) & 0x3F)); } #endif pj_hmac_sha1_final(&ctx, digest); /* Compare HMACs */ if (pj_memcmp(amsgi->hmac, digest, 20)) { - /* HMAC value mismatch */ - return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNAUTHORIZED); + /* HMAC value mismatch */ + return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNAUTHORIZED); } /* Everything looks okay! */ diff --git a/pjnath/src/pjnath/stun_msg.c b/pjnath/src/pjnath/stun_msg.c index bd83351e65..3def6b3eac 100644 --- a/pjnath/src/pjnath/stun_msg.c +++ b/pjnath/src/pjnath/stun_msg.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,26 +27,26 @@ #include #include -#define THIS_FILE "stun_msg.c" -#define STUN_XOR_FINGERPRINT 0x5354554eL +#define THIS_FILE "stun_msg.c" +#define STUN_XOR_FINGERPRINT 0x5354554eL static int padding_char; static const char *stun_method_names[PJ_STUN_METHOD_MAX] = { - "Unknown", /* 0 */ - "Binding", /* 1 */ - "SharedSecret", /* 2 */ - "Allocate", /* 3 */ - "Refresh", /* 4 */ - "???", /* 5 */ - "Send", /* 6 */ - "Data", /* 7 */ - "CreatePermission", /* 8 */ - "ChannelBind", /* 9 */ - "Connect", /* 10 */ - "ConnectionBind", /* 11 */ - "ConnectionAttempt", /* 12 */ + "Unknown", /* 0 */ + "Binding", /* 1 */ + "SharedSecret", /* 2 */ + "Allocate", /* 3 */ + "Refresh", /* 4 */ + "???", /* 5 */ + "Send", /* 6 */ + "Data", /* 7 */ + "CreatePermission", /* 8 */ + "ChannelBind", /* 9 */ + "Connect", /* 10 */ + "ConnectionBind", /* 11 */ + "ConnectionAttempt", /* 12 */ }; static struct @@ -56,31 +55,31 @@ static struct const char *err_msg; } stun_err_msg_map[] = { - { PJ_STUN_SC_TRY_ALTERNATE, "Try Alternate"}, - { PJ_STUN_SC_BAD_REQUEST, "Bad Request"}, - { PJ_STUN_SC_UNAUTHORIZED, "Unauthorized"}, - { PJ_STUN_SC_FORBIDDEN, "Forbidden"}, - { PJ_STUN_SC_UNKNOWN_ATTRIBUTE, "Unknown Attribute"}, - //{ PJ_STUN_SC_STALE_CREDENTIALS, "Stale Credentials"}, + { PJ_STUN_SC_TRY_ALTERNATE, "Try Alternate"}, + { PJ_STUN_SC_BAD_REQUEST, "Bad Request"}, + { PJ_STUN_SC_UNAUTHORIZED, "Unauthorized"}, + { PJ_STUN_SC_FORBIDDEN, "Forbidden"}, + { PJ_STUN_SC_UNKNOWN_ATTRIBUTE, "Unknown Attribute"}, + //{ PJ_STUN_SC_STALE_CREDENTIALS, "Stale Credentials"}, //{ PJ_STUN_SC_INTEGRITY_CHECK_FAILURE, "Integrity Check Failure"}, - //{ PJ_STUN_SC_MISSING_USERNAME, "Missing Username"}, - //{ PJ_STUN_SC_USE_TLS, "Use TLS"}, - //{ PJ_STUN_SC_MISSING_REALM, "Missing Realm"}, - //{ PJ_STUN_SC_MISSING_NONCE, "Missing Nonce"}, - //{ PJ_STUN_SC_UNKNOWN_USERNAME, "Unknown Username"}, - { PJ_STUN_SC_ALLOCATION_MISMATCH, "Allocation Mismatch"}, - { PJ_STUN_SC_STALE_NONCE, "Stale Nonce"}, - { PJ_STUN_SC_TRANSITIONING, "Active Destination Already Set"}, - { PJ_STUN_SC_WRONG_CREDENTIALS, "Wrong Credentials"}, + //{ PJ_STUN_SC_MISSING_USERNAME, "Missing Username"}, + //{ PJ_STUN_SC_USE_TLS, "Use TLS"}, + //{ PJ_STUN_SC_MISSING_REALM, "Missing Realm"}, + //{ PJ_STUN_SC_MISSING_NONCE, "Missing Nonce"}, + //{ PJ_STUN_SC_UNKNOWN_USERNAME, "Unknown Username"}, + { PJ_STUN_SC_ALLOCATION_MISMATCH, "Allocation Mismatch"}, + { PJ_STUN_SC_STALE_NONCE, "Stale Nonce"}, + { PJ_STUN_SC_TRANSITIONING, "Active Destination Already Set"}, + { PJ_STUN_SC_WRONG_CREDENTIALS, "Wrong Credentials"}, { PJ_STUN_SC_UNSUPP_TRANSPORT_PROTO, "Unsupported Transport Protocol"}, - { PJ_STUN_SC_OPER_TCP_ONLY, "Operation for TCP Only"}, - { PJ_STUN_SC_CONNECTION_FAILURE, "Connection Failure"}, - { PJ_STUN_SC_CONNECTION_TIMEOUT, "Connection Timeout"}, + { PJ_STUN_SC_OPER_TCP_ONLY, "Operation for TCP Only"}, + { PJ_STUN_SC_CONNECTION_FAILURE, "Connection Failure"}, + { PJ_STUN_SC_CONNECTION_TIMEOUT, "Connection Timeout"}, { PJ_STUN_SC_ALLOCATION_QUOTA_REACHED, "Allocation Quota Reached"}, - { PJ_STUN_SC_ROLE_CONFLICT, "Role Conflict"}, - { PJ_STUN_SC_SERVER_ERROR, "Server Error"}, - { PJ_STUN_SC_INSUFFICIENT_CAPACITY, "Insufficient Capacity"}, - { PJ_STUN_SC_GLOBAL_FAILURE, "Global Failure"} + { PJ_STUN_SC_ROLE_CONFLICT, "Role Conflict"}, + { PJ_STUN_SC_SERVER_ERROR, "Server Error"}, + { PJ_STUN_SC_INSUFFICIENT_CAPACITY, "Insufficient Capacity"}, + { PJ_STUN_SC_GLOBAL_FAILURE, "Global Failure"} }; @@ -88,527 +87,527 @@ static struct struct attr_desc { const char *name; - pj_status_t (*decode_attr)(pj_pool_t *pool, const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, void **p_attr); + pj_status_t (*decode_attr)(pj_pool_t *pool, const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, void **p_attr); pj_status_t (*encode_attr)(const void *a, pj_uint8_t *buf, - unsigned len, const pj_stun_msg_hdr *msghdr, - unsigned *printed); + unsigned len, const pj_stun_msg_hdr *msghdr, + unsigned *printed); void* (*clone_attr)(pj_pool_t *pool, const void *src); }; static pj_status_t decode_sockaddr_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr); + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr); static pj_status_t decode_xored_sockaddr_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr); + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr); static pj_status_t encode_sockaddr_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed); + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed); static void* clone_sockaddr_attr(pj_pool_t *pool, const void *src); static pj_status_t decode_string_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr); + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr); static pj_status_t encode_string_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed); + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed); static void* clone_string_attr(pj_pool_t *pool, const void *src); static pj_status_t decode_msgint_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr); + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr); static pj_status_t encode_msgint_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed); + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed); static void* clone_msgint_attr(pj_pool_t *pool, const void *src); static pj_status_t decode_errcode_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr); + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr); static pj_status_t encode_errcode_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed); + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed); static void* clone_errcode_attr(pj_pool_t *pool, const void *src); static pj_status_t decode_unknown_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr); + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr); static pj_status_t encode_unknown_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed); + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed); static void* clone_unknown_attr(pj_pool_t *pool, const void *src); static pj_status_t decode_uint_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr); + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr); static pj_status_t encode_uint_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed); + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed); static void* clone_uint_attr(pj_pool_t *pool, const void *src); static pj_status_t decode_uint64_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr); + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr); static pj_status_t encode_uint64_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed); + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed); static void* clone_uint64_attr(pj_pool_t *pool, const void *src); static pj_status_t decode_binary_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr); + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr); static pj_status_t encode_binary_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed); + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed); static void* clone_binary_attr(pj_pool_t *pool, const void *src); static pj_status_t decode_empty_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr); + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr); static pj_status_t encode_empty_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed); + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed); static void* clone_empty_attr(pj_pool_t *pool, const void *src); static struct attr_desc mandatory_attr_desc[] = { { - /* type zero */ - NULL, - NULL, - NULL, - NULL + /* type zero */ + NULL, + NULL, + NULL, + NULL }, { - /* PJ_STUN_ATTR_MAPPED_ADDR, */ - "MAPPED-ADDRESS", - &decode_sockaddr_attr, - &encode_sockaddr_attr, - &clone_sockaddr_attr + /* PJ_STUN_ATTR_MAPPED_ADDR, */ + "MAPPED-ADDRESS", + &decode_sockaddr_attr, + &encode_sockaddr_attr, + &clone_sockaddr_attr }, { - /* PJ_STUN_ATTR_RESPONSE_ADDR, */ - "RESPONSE-ADDRESS", - &decode_sockaddr_attr, - &encode_sockaddr_attr, - &clone_sockaddr_attr + /* PJ_STUN_ATTR_RESPONSE_ADDR, */ + "RESPONSE-ADDRESS", + &decode_sockaddr_attr, + &encode_sockaddr_attr, + &clone_sockaddr_attr }, { - /* PJ_STUN_ATTR_CHANGE_REQUEST, */ - "CHANGE-REQUEST", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_CHANGE_REQUEST, */ + "CHANGE-REQUEST", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* PJ_STUN_ATTR_SOURCE_ADDR, */ - "SOURCE-ADDRESS", - &decode_sockaddr_attr, - &encode_sockaddr_attr, - &clone_sockaddr_attr + /* PJ_STUN_ATTR_SOURCE_ADDR, */ + "SOURCE-ADDRESS", + &decode_sockaddr_attr, + &encode_sockaddr_attr, + &clone_sockaddr_attr }, { - /* PJ_STUN_ATTR_CHANGED_ADDR, */ - "CHANGED-ADDRESS", - &decode_sockaddr_attr, - &encode_sockaddr_attr, - &clone_sockaddr_attr + /* PJ_STUN_ATTR_CHANGED_ADDR, */ + "CHANGED-ADDRESS", + &decode_sockaddr_attr, + &encode_sockaddr_attr, + &clone_sockaddr_attr }, { - /* PJ_STUN_ATTR_USERNAME, */ - "USERNAME", - &decode_string_attr, - &encode_string_attr, - &clone_string_attr + /* PJ_STUN_ATTR_USERNAME, */ + "USERNAME", + &decode_string_attr, + &encode_string_attr, + &clone_string_attr }, { - /* PJ_STUN_ATTR_PASSWORD, */ - "PASSWORD", - &decode_string_attr, - &encode_string_attr, - &clone_string_attr + /* PJ_STUN_ATTR_PASSWORD, */ + "PASSWORD", + &decode_string_attr, + &encode_string_attr, + &clone_string_attr }, { - /* PJ_STUN_ATTR_MESSAGE_INTEGRITY, */ - "MESSAGE-INTEGRITY", - &decode_msgint_attr, - &encode_msgint_attr, - &clone_msgint_attr + /* PJ_STUN_ATTR_MESSAGE_INTEGRITY, */ + "MESSAGE-INTEGRITY", + &decode_msgint_attr, + &encode_msgint_attr, + &clone_msgint_attr }, { - /* PJ_STUN_ATTR_ERROR_CODE, */ - "ERROR-CODE", - &decode_errcode_attr, - &encode_errcode_attr, - &clone_errcode_attr + /* PJ_STUN_ATTR_ERROR_CODE, */ + "ERROR-CODE", + &decode_errcode_attr, + &encode_errcode_attr, + &clone_errcode_attr }, { - /* PJ_STUN_ATTR_UNKNOWN_ATTRIBUTES, */ - "UNKNOWN-ATTRIBUTES", - &decode_unknown_attr, - &encode_unknown_attr, - &clone_unknown_attr + /* PJ_STUN_ATTR_UNKNOWN_ATTRIBUTES, */ + "UNKNOWN-ATTRIBUTES", + &decode_unknown_attr, + &encode_unknown_attr, + &clone_unknown_attr }, { - /* PJ_STUN_ATTR_REFLECTED_FROM, */ - "REFLECTED-FROM", - &decode_sockaddr_attr, - &encode_sockaddr_attr, - &clone_sockaddr_attr + /* PJ_STUN_ATTR_REFLECTED_FROM, */ + "REFLECTED-FROM", + &decode_sockaddr_attr, + &encode_sockaddr_attr, + &clone_sockaddr_attr }, { - /* PJ_STUN_ATTR_CHANNEL_NUMBER (0x000C) */ - "CHANNEL-NUMBER", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_CHANNEL_NUMBER (0x000C) */ + "CHANNEL-NUMBER", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* PJ_STUN_ATTR_LIFETIME, */ - "LIFETIME", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_LIFETIME, */ + "LIFETIME", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* ID 0x000E is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x000E is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* PJ_STUN_ATTR_MAGIC_COOKIE */ - "MAGIC-COOKIE", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_MAGIC_COOKIE */ + "MAGIC-COOKIE", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* PJ_STUN_ATTR_BANDWIDTH, */ - "BANDWIDTH", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_BANDWIDTH, */ + "BANDWIDTH", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* ID 0x0011 is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x0011 is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* PJ_STUN_ATTR_XOR_PEER_ADDRESS, */ - "XOR-PEER-ADDRESS", - &decode_xored_sockaddr_attr, - &encode_sockaddr_attr, - &clone_sockaddr_attr + /* PJ_STUN_ATTR_XOR_PEER_ADDRESS, */ + "XOR-PEER-ADDRESS", + &decode_xored_sockaddr_attr, + &encode_sockaddr_attr, + &clone_sockaddr_attr }, { - /* PJ_STUN_ATTR_DATA, */ - "DATA", - &decode_binary_attr, - &encode_binary_attr, - &clone_binary_attr + /* PJ_STUN_ATTR_DATA, */ + "DATA", + &decode_binary_attr, + &encode_binary_attr, + &clone_binary_attr }, { - /* PJ_STUN_ATTR_REALM, */ - "REALM", - &decode_string_attr, - &encode_string_attr, - &clone_string_attr + /* PJ_STUN_ATTR_REALM, */ + "REALM", + &decode_string_attr, + &encode_string_attr, + &clone_string_attr }, { - /* PJ_STUN_ATTR_NONCE, */ - "NONCE", - &decode_string_attr, - &encode_string_attr, - &clone_string_attr + /* PJ_STUN_ATTR_NONCE, */ + "NONCE", + &decode_string_attr, + &encode_string_attr, + &clone_string_attr }, { - /* PJ_STUN_ATTR_XOR_RELAYED_ADDR, */ - "XOR-RELAYED-ADDRESS", - &decode_xored_sockaddr_attr, - &encode_sockaddr_attr, - &clone_sockaddr_attr + /* PJ_STUN_ATTR_XOR_RELAYED_ADDR, */ + "XOR-RELAYED-ADDRESS", + &decode_xored_sockaddr_attr, + &encode_sockaddr_attr, + &clone_sockaddr_attr }, { - /* PJ_STUN_ATTR_REQUESTED_ADDR_FAMILY, */ - "REQUESTED-ADDRESS-FAMILY", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_REQUESTED_ADDR_FAMILY, */ + "REQUESTED-ADDRESS-FAMILY", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* PJ_STUN_ATTR_EVEN_PORT, */ - "EVEN-PORT", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_EVEN_PORT, */ + "EVEN-PORT", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* PJ_STUN_ATTR_REQUESTED_TRANSPORT, */ - "REQUESTED-TRANSPORT", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_REQUESTED_TRANSPORT, */ + "REQUESTED-TRANSPORT", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* PJ_STUN_ATTR_DONT_FRAGMENT */ - "DONT-FRAGMENT", - &decode_empty_attr, - &encode_empty_attr, - &clone_empty_attr + /* PJ_STUN_ATTR_DONT_FRAGMENT */ + "DONT-FRAGMENT", + &decode_empty_attr, + &encode_empty_attr, + &clone_empty_attr }, { - /* ID 0x001B is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x001B is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* ID 0x001C is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x001C is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* ID 0x001D is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x001D is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* ID 0x001E is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x001E is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* ID 0x001F is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x001F is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* PJ_STUN_ATTR_XOR_MAPPED_ADDRESS, */ - "XOR-MAPPED-ADDRESS", - &decode_xored_sockaddr_attr, - &encode_sockaddr_attr, - &clone_sockaddr_attr + /* PJ_STUN_ATTR_XOR_MAPPED_ADDRESS, */ + "XOR-MAPPED-ADDRESS", + &decode_xored_sockaddr_attr, + &encode_sockaddr_attr, + &clone_sockaddr_attr }, { - /* PJ_STUN_ATTR_TIMER_VAL, */ - "TIMER-VAL", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_TIMER_VAL, */ + "TIMER-VAL", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* PJ_STUN_ATTR_RESERVATION_TOKEN, */ - "RESERVATION-TOKEN", - &decode_uint64_attr, - &encode_uint64_attr, - &clone_uint64_attr + /* PJ_STUN_ATTR_RESERVATION_TOKEN, */ + "RESERVATION-TOKEN", + &decode_uint64_attr, + &encode_uint64_attr, + &clone_uint64_attr }, { - /* PJ_STUN_ATTR_XOR_REFLECTED_FROM, */ - "XOR-REFLECTED-FROM", - &decode_xored_sockaddr_attr, - &encode_sockaddr_attr, - &clone_sockaddr_attr + /* PJ_STUN_ATTR_XOR_REFLECTED_FROM, */ + "XOR-REFLECTED-FROM", + &decode_xored_sockaddr_attr, + &encode_sockaddr_attr, + &clone_sockaddr_attr }, { - /* PJ_STUN_ATTR_PRIORITY, */ - "PRIORITY", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_PRIORITY, */ + "PRIORITY", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* PJ_STUN_ATTR_USE_CANDIDATE, */ - "USE-CANDIDATE", - &decode_empty_attr, - &encode_empty_attr, - &clone_empty_attr + /* PJ_STUN_ATTR_USE_CANDIDATE, */ + "USE-CANDIDATE", + &decode_empty_attr, + &encode_empty_attr, + &clone_empty_attr }, { - /* ID 0x0026 is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x0026 is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* ID 0x0027 is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x0027 is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* ID 0x0028 is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x0028 is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* ID 0x0029 is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x0029 is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* PJ_STUN_ATTR_CONNECTION_ID, */ - "CONNECTION-ID", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_CONNECTION_ID, */ + "CONNECTION-ID", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* ID 0x002b is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x002b is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* ID 0x002c is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x002c is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* ID 0x002d is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x002d is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* ID 0x002e is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x002e is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* ID 0x002f is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x002f is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* PJ_STUN_ATTR_ICMP, */ - "ICMP", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_ICMP, */ + "ICMP", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, /* Sentinel */ { - /* PJ_STUN_ATTR_END_MANDATORY_ATTR */ - NULL, - NULL, - NULL, - NULL + /* PJ_STUN_ATTR_END_MANDATORY_ATTR */ + NULL, + NULL, + NULL, + NULL } }; static struct attr_desc extended_attr_desc[] = { { - /* ID 0x8021 is not assigned */ - NULL, - NULL, - NULL, - NULL + /* ID 0x8021 is not assigned */ + NULL, + NULL, + NULL, + NULL }, { - /* PJ_STUN_ATTR_SOFTWARE, */ - "SOFTWARE", - &decode_string_attr, - &encode_string_attr, - &clone_string_attr + /* PJ_STUN_ATTR_SOFTWARE, */ + "SOFTWARE", + &decode_string_attr, + &encode_string_attr, + &clone_string_attr }, { - /* PJ_STUN_ATTR_ALTERNATE_SERVER, */ - "ALTERNATE-SERVER", - &decode_sockaddr_attr, - &encode_sockaddr_attr, - &clone_sockaddr_attr + /* PJ_STUN_ATTR_ALTERNATE_SERVER, */ + "ALTERNATE-SERVER", + &decode_sockaddr_attr, + &encode_sockaddr_attr, + &clone_sockaddr_attr }, { - /* PJ_STUN_ATTR_REFRESH_INTERVAL, */ - "REFRESH-INTERVAL", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_REFRESH_INTERVAL, */ + "REFRESH-INTERVAL", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* ID 0x8025 is not assigned*/ - NULL, - NULL, - NULL, - NULL + /* ID 0x8025 is not assigned*/ + NULL, + NULL, + NULL, + NULL }, { - /* PADDING, 0x8026 */ - NULL, - NULL, - NULL, - NULL + /* PADDING, 0x8026 */ + NULL, + NULL, + NULL, + NULL }, { - /* CACHE-TIMEOUT, 0x8027 */ - NULL, - NULL, - NULL, - NULL + /* CACHE-TIMEOUT, 0x8027 */ + NULL, + NULL, + NULL, + NULL }, { - /* PJ_STUN_ATTR_FINGERPRINT, */ - "FINGERPRINT", - &decode_uint_attr, - &encode_uint_attr, - &clone_uint_attr + /* PJ_STUN_ATTR_FINGERPRINT, */ + "FINGERPRINT", + &decode_uint_attr, + &encode_uint_attr, + &clone_uint_attr }, { - /* PJ_STUN_ATTR_ICE_CONTROLLED, */ - "ICE-CONTROLLED", - &decode_uint64_attr, - &encode_uint64_attr, - &clone_uint64_attr + /* PJ_STUN_ATTR_ICE_CONTROLLED, */ + "ICE-CONTROLLED", + &decode_uint64_attr, + &encode_uint64_attr, + &clone_uint64_attr }, { - /* PJ_STUN_ATTR_ICE_CONTROLLING, */ - "ICE-CONTROLLING", - &decode_uint64_attr, - &encode_uint64_attr, - &clone_uint64_attr + /* PJ_STUN_ATTR_ICE_CONTROLLING, */ + "ICE-CONTROLLING", + &decode_uint64_attr, + &encode_uint64_attr, + &clone_uint64_attr } }; @@ -622,7 +621,7 @@ PJ_DEF(const char*) pj_stun_get_method_name(unsigned msg_type) unsigned method = PJ_STUN_GET_METHOD(msg_type); if (method >= PJ_ARRAY_SIZE(stun_method_names)) - return "???"; + return "???"; return stun_method_names[method]; } @@ -634,15 +633,15 @@ PJ_DEF(const char*) pj_stun_get_method_name(unsigned msg_type) PJ_DEF(const char*) pj_stun_get_class_name(unsigned msg_type) { if (PJ_STUN_IS_REQUEST(msg_type)) - return "request"; + return "request"; else if (PJ_STUN_IS_SUCCESS_RESPONSE(msg_type)) - return "success response"; + return "success response"; else if (PJ_STUN_IS_ERROR_RESPONSE(msg_type)) - return "error response"; + return "error response"; else if (PJ_STUN_IS_INDICATION(msg_type)) - return "indication"; + return "indication"; else - return "???"; + return "???"; } @@ -652,21 +651,21 @@ static const struct attr_desc *find_attr_desc(unsigned attr_type) /* Check that attr_desc array is valid */ pj_assert(PJ_ARRAY_SIZE(mandatory_attr_desc)== - PJ_STUN_ATTR_END_MANDATORY_ATTR+1); + PJ_STUN_ATTR_END_MANDATORY_ATTR+1); pj_assert(mandatory_attr_desc[PJ_STUN_ATTR_END_MANDATORY_ATTR].decode_attr - == NULL); + == NULL); pj_assert(mandatory_attr_desc[PJ_STUN_ATTR_USE_CANDIDATE].decode_attr - == &decode_empty_attr); + == &decode_empty_attr); pj_assert(PJ_ARRAY_SIZE(extended_attr_desc) == - PJ_STUN_ATTR_END_EXTENDED_ATTR-PJ_STUN_ATTR_START_EXTENDED_ATTR); + PJ_STUN_ATTR_END_EXTENDED_ATTR-PJ_STUN_ATTR_START_EXTENDED_ATTR); if (attr_type < PJ_STUN_ATTR_END_MANDATORY_ATTR) - desc = &mandatory_attr_desc[attr_type]; + desc = &mandatory_attr_desc[attr_type]; else if (attr_type >= PJ_STUN_ATTR_START_EXTENDED_ATTR && - attr_type < PJ_STUN_ATTR_END_EXTENDED_ATTR) - desc = &extended_attr_desc[attr_type-PJ_STUN_ATTR_START_EXTENDED_ATTR]; + attr_type < PJ_STUN_ATTR_END_EXTENDED_ATTR) + desc = &extended_attr_desc[attr_type-PJ_STUN_ATTR_START_EXTENDED_ATTR]; else - return NULL; + return NULL; return desc->decode_attr == NULL ? NULL : desc; } @@ -681,7 +680,7 @@ PJ_DEF(const char*) pj_stun_get_attr_name(unsigned attr_type) attr_desc = find_attr_desc(attr_type); if (!attr_desc || attr_desc->name==NULL) - return "???"; + return "???"; return attr_desc->name; } @@ -697,8 +696,8 @@ PJ_DEF(pj_str_t) pj_stun_get_err_reason(int err_code) unsigned i; for (i=0; i 0) { - int half = n/2; - int mid = first + half; - - if (stun_err_msg_map[mid].err_code < err_code) { - first = mid+1; - n -= (half+1); - } else if (stun_err_msg_map[mid].err_code > err_code) { - n = half; - } else { - first = mid; - break; - } + int half = n/2; + int mid = first + half; + + if (stun_err_msg_map[mid].err_code < err_code) { + first = mid+1; + n -= (half+1); + } else if (stun_err_msg_map[mid].err_code > err_code) { + n = half; + } else { + first = mid; + break; + } } if (stun_err_msg_map[first].err_code == err_code) { - return pj_str((char*)stun_err_msg_map[first].err_msg); + return pj_str((char*)stun_err_msg_map[first].err_msg); } else { - return pj_str(NULL); + return pj_str(NULL); } #endif } @@ -746,13 +745,13 @@ PJ_DEF(int) pj_stun_set_padding_char(int chr) #define INIT_ATTR(a,t,l) (a)->hdr.type=(pj_uint16_t)(t), \ - (a)->hdr.length=(pj_uint16_t)(l) -#define ATTR_HDR_LEN 4 + (a)->hdr.length=(pj_uint16_t)(l) +#define ATTR_HDR_LEN 4 static pj_uint16_t GETVAL16H(const pj_uint8_t *buf, unsigned pos) { return (pj_uint16_t) ((buf[pos + 0] << 8) | \ - (buf[pos + 1] << 0)); + (buf[pos + 1] << 0)); } /*unused PJ_INLINE(pj_uint16_t) GETVAL16N(const pj_uint8_t *buf, unsigned pos) @@ -769,9 +768,9 @@ static void PUTVAL16H(pj_uint8_t *buf, unsigned pos, pj_uint16_t hval) PJ_INLINE(pj_uint32_t) GETVAL32H(const pj_uint8_t *buf, unsigned pos) { return (pj_uint32_t) ((buf[pos + 0] << 24UL) | \ - (buf[pos + 1] << 16UL) | \ - (buf[pos + 2] << 8UL) | \ - (buf[pos + 3] << 0UL)); + (buf[pos + 1] << 16UL) | \ + (buf[pos + 2] << 8UL) | \ + (buf[pos + 3] << 0UL)); } /*unused PJ_INLINE(pj_uint32_t) GETVAL32N(const pj_uint8_t *buf, unsigned pos) @@ -810,23 +809,23 @@ static void GETATTRHDR(const pj_uint8_t *buf, pj_stun_attr_hdr *hdr) /* * STUN generic IP address container */ -#define STUN_GENERIC_IPV4_ADDR_LEN 8 -#define STUN_GENERIC_IPV6_ADDR_LEN 20 +#define STUN_GENERIC_IPV4_ADDR_LEN 8 +#define STUN_GENERIC_IPV6_ADDR_LEN 20 /* * Init sockaddr attr */ PJ_DEF(pj_status_t) pj_stun_sockaddr_attr_init( pj_stun_sockaddr_attr *attr, - int attr_type, - pj_bool_t xor_ed, - const pj_sockaddr_t *addr, - unsigned addr_len) + int attr_type, + pj_bool_t xor_ed, + const pj_sockaddr_t *addr, + unsigned addr_len) { unsigned attr_len; PJ_ASSERT_RETURN(attr && addr_len && addr, PJ_EINVAL); PJ_ASSERT_RETURN(addr_len == sizeof(pj_sockaddr_in) || - addr_len == sizeof(pj_sockaddr_in6), PJ_EINVAL); + addr_len == sizeof(pj_sockaddr_in6), PJ_EINVAL); attr_len = pj_sockaddr_get_addr_len(addr) + 4; INIT_ATTR(attr, attr_type, attr_len); @@ -842,11 +841,11 @@ PJ_DEF(pj_status_t) pj_stun_sockaddr_attr_init( pj_stun_sockaddr_attr *attr, * Create a generic STUN IP address attribute for IPv4 address. */ PJ_DEF(pj_status_t) pj_stun_sockaddr_attr_create(pj_pool_t *pool, - int attr_type, - pj_bool_t xor_ed, - const pj_sockaddr_t *addr, - unsigned addr_len, - pj_stun_sockaddr_attr **p_attr) + int attr_type, + pj_bool_t xor_ed, + const pj_sockaddr_t *addr, + unsigned addr_len, + pj_stun_sockaddr_attr **p_attr) { pj_stun_sockaddr_attr *attr; @@ -854,7 +853,7 @@ PJ_DEF(pj_status_t) pj_stun_sockaddr_attr_create(pj_pool_t *pool, attr = PJ_POOL_ZALLOC_T(pool, pj_stun_sockaddr_attr); *p_attr = attr; return pj_stun_sockaddr_attr_init(attr, attr_type, xor_ed, - addr, addr_len); + addr, addr_len); } @@ -862,27 +861,27 @@ PJ_DEF(pj_status_t) pj_stun_sockaddr_attr_create(pj_pool_t *pool, * Create and add generic STUN IP address attribute to a STUN message. */ PJ_DEF(pj_status_t) pj_stun_msg_add_sockaddr_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int attr_type, - pj_bool_t xor_ed, - const pj_sockaddr_t *addr, - unsigned addr_len) + pj_stun_msg *msg, + int attr_type, + pj_bool_t xor_ed, + const pj_sockaddr_t *addr, + unsigned addr_len) { pj_stun_sockaddr_attr *attr; pj_status_t status; status = pj_stun_sockaddr_attr_create(pool, attr_type, xor_ed, - addr, addr_len, &attr); + addr, addr_len, &attr); if (status != PJ_SUCCESS) - return status; + return status; return pj_stun_msg_add_attr(msg, &attr->hdr); } static pj_status_t decode_sockaddr_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr) + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr) { pj_stun_sockaddr_attr *attr; int af; @@ -899,9 +898,9 @@ static pj_status_t decode_sockaddr_attr(pj_pool_t *pool, /* Check that the attribute length is valid */ if (attr->hdr.length != STUN_GENERIC_IPV4_ADDR_LEN && - attr->hdr.length != STUN_GENERIC_IPV6_ADDR_LEN) + attr->hdr.length != STUN_GENERIC_IPV6_ADDR_LEN) { - return PJNATH_ESTUNINATTRLEN; + return PJNATH_ESTUNINATTRLEN; } /* Check address family */ @@ -909,27 +908,27 @@ static pj_status_t decode_sockaddr_attr(pj_pool_t *pool, /* Check address family is valid */ if (val == 1) { - if (attr->hdr.length != STUN_GENERIC_IPV4_ADDR_LEN) - return PJNATH_ESTUNINATTRLEN; - af = pj_AF_INET(); - addr_len = 4; + if (attr->hdr.length != STUN_GENERIC_IPV4_ADDR_LEN) + return PJNATH_ESTUNINATTRLEN; + af = pj_AF_INET(); + addr_len = 4; } else if (val == 2) { - if (attr->hdr.length != STUN_GENERIC_IPV6_ADDR_LEN) - return PJNATH_ESTUNINATTRLEN; - af = pj_AF_INET6(); - addr_len = 16; + if (attr->hdr.length != STUN_GENERIC_IPV6_ADDR_LEN) + return PJNATH_ESTUNINATTRLEN; + af = pj_AF_INET6(); + addr_len = 16; } else { - /* Invalid address family */ - return PJNATH_EINVAF; + /* Invalid address family */ + return PJNATH_EINVAF; } /* Get port and address */ pj_sockaddr_init(af, &attr->sockaddr, NULL, 0); pj_sockaddr_set_port(&attr->sockaddr, - GETVAL16H(buf, ATTR_HDR_LEN+2)); + GETVAL16H(buf, ATTR_HDR_LEN+2)); pj_memcpy(pj_sockaddr_get_addr(&attr->sockaddr), - buf+ATTR_HDR_LEN+4, - addr_len); + buf+ATTR_HDR_LEN+4, + addr_len); /* Done */ *p_attr = (void*)attr; @@ -939,47 +938,47 @@ static pj_status_t decode_sockaddr_attr(pj_pool_t *pool, static pj_status_t decode_xored_sockaddr_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr) + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr) { pj_stun_sockaddr_attr *attr; pj_status_t status; status = decode_sockaddr_attr(pool, buf, msghdr, p_attr); if (status != PJ_SUCCESS) - return status; + return status; attr = *(pj_stun_sockaddr_attr**)p_attr; attr->xor_ed = PJ_TRUE; if (attr->sockaddr.addr.sa_family == pj_AF_INET()) { - attr->sockaddr.ipv4.sin_port ^= pj_htons(PJ_STUN_MAGIC >> 16); - attr->sockaddr.ipv4.sin_addr.s_addr ^= pj_htonl(PJ_STUN_MAGIC); + attr->sockaddr.ipv4.sin_port ^= pj_htons(PJ_STUN_MAGIC >> 16); + attr->sockaddr.ipv4.sin_addr.s_addr ^= pj_htonl(PJ_STUN_MAGIC); } else if (attr->sockaddr.addr.sa_family == pj_AF_INET6()) { - unsigned i; - pj_uint8_t *dst = (pj_uint8_t*) &attr->sockaddr.ipv6.sin6_addr; - pj_uint32_t magic = pj_htonl(PJ_STUN_MAGIC); - - attr->sockaddr.ipv6.sin6_port ^= pj_htons(PJ_STUN_MAGIC >> 16); - - /* If the IP address family is IPv6, X-Address is computed by - * taking the mapped IP address in host byte order, XOR'ing it - * with the concatenation of the magic cookie and the 96-bit - * transaction ID, and converting the result to network byte - * order. - */ - for (i=0; i<4; ++i) { - dst[i] ^= ((const pj_uint8_t*)&magic)[i]; - } - pj_assert(sizeof(msghdr->tsx_id[0]) == 1); - for (i=0; i<12; ++i) { - dst[i+4] ^= msghdr->tsx_id[i]; - } + unsigned i; + pj_uint8_t *dst = (pj_uint8_t*) &attr->sockaddr.ipv6.sin6_addr; + pj_uint32_t magic = pj_htonl(PJ_STUN_MAGIC); + + attr->sockaddr.ipv6.sin6_port ^= pj_htons(PJ_STUN_MAGIC >> 16); + + /* If the IP address family is IPv6, X-Address is computed by + * taking the mapped IP address in host byte order, XOR'ing it + * with the concatenation of the magic cookie and the 96-bit + * transaction ID, and converting the result to network byte + * order. + */ + for (i=0; i<4; ++i) { + dst[i] ^= ((const pj_uint8_t*)&magic)[i]; + } + pj_assert(sizeof(msghdr->tsx_id[0]) == 1); + for (i=0; i<12; ++i) { + dst[i+4] ^= msghdr->tsx_id[i]; + } } else { - return PJNATH_EINVAF; + return PJNATH_EINVAF; } /* Done */ @@ -990,13 +989,13 @@ static pj_status_t decode_xored_sockaddr_attr(pj_pool_t *pool, static pj_status_t encode_sockaddr_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed) + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed) { pj_uint8_t *start_buf = buf; const pj_stun_sockaddr_attr *ca = - (const pj_stun_sockaddr_attr *)a; + (const pj_stun_sockaddr_attr *)a; PJ_CHECK_STACK(); @@ -1004,113 +1003,113 @@ static pj_status_t encode_sockaddr_attr(const void *a, pj_uint8_t *buf, PUTVAL16H(buf, 0, ca->hdr.type); if (ca->sockaddr.addr.sa_family == pj_AF_INET()) { - enum { - ATTR_LEN = ATTR_HDR_LEN + STUN_GENERIC_IPV4_ADDR_LEN - }; + enum { + ATTR_LEN = ATTR_HDR_LEN + STUN_GENERIC_IPV4_ADDR_LEN + }; - if (len < ATTR_LEN) - return PJ_ETOOSMALL; + if (len < ATTR_LEN) + return PJ_ETOOSMALL; - /* attribute len */ - PUTVAL16H(buf, 2, STUN_GENERIC_IPV4_ADDR_LEN); - buf += ATTR_HDR_LEN; + /* attribute len */ + PUTVAL16H(buf, 2, STUN_GENERIC_IPV4_ADDR_LEN); + buf += ATTR_HDR_LEN; - /* Ignored */ - *buf++ = '\0'; + /* Ignored */ + *buf++ = '\0'; - /* Address family, 1 for IPv4 */ - *buf++ = 1; + /* Address family, 1 for IPv4 */ + *buf++ = 1; - /* IPv4 address */ - if (ca->xor_ed) { - pj_uint32_t addr; - pj_uint16_t port; + /* IPv4 address */ + if (ca->xor_ed) { + pj_uint32_t addr; + pj_uint16_t port; - addr = ca->sockaddr.ipv4.sin_addr.s_addr; - port = ca->sockaddr.ipv4.sin_port; + addr = ca->sockaddr.ipv4.sin_addr.s_addr; + port = ca->sockaddr.ipv4.sin_port; - port ^= pj_htons(PJ_STUN_MAGIC >> 16); - addr ^= pj_htonl(PJ_STUN_MAGIC); + port ^= pj_htons(PJ_STUN_MAGIC >> 16); + addr ^= pj_htonl(PJ_STUN_MAGIC); - /* Port */ - pj_memcpy(buf, &port, 2); - buf += 2; + /* Port */ + pj_memcpy(buf, &port, 2); + buf += 2; - /* Address */ - pj_memcpy(buf, &addr, 4); - buf += 4; + /* Address */ + pj_memcpy(buf, &addr, 4); + buf += 4; - } else { - /* Port */ - pj_memcpy(buf, &ca->sockaddr.ipv4.sin_port, 2); - buf += 2; + } else { + /* Port */ + pj_memcpy(buf, &ca->sockaddr.ipv4.sin_port, 2); + buf += 2; - /* Address */ - pj_memcpy(buf, &ca->sockaddr.ipv4.sin_addr, 4); - buf += 4; - } + /* Address */ + pj_memcpy(buf, &ca->sockaddr.ipv4.sin_addr, 4); + buf += 4; + } - pj_assert(buf - start_buf == ATTR_LEN); + pj_assert(buf - start_buf == ATTR_LEN); } else if (ca->sockaddr.addr.sa_family == pj_AF_INET6()) { - /* IPv6 address */ - enum { - ATTR_LEN = ATTR_HDR_LEN + STUN_GENERIC_IPV6_ADDR_LEN - }; + /* IPv6 address */ + enum { + ATTR_LEN = ATTR_HDR_LEN + STUN_GENERIC_IPV6_ADDR_LEN + }; - if (len < ATTR_LEN) - return PJ_ETOOSMALL; + if (len < ATTR_LEN) + return PJ_ETOOSMALL; - /* attribute len */ - PUTVAL16H(buf, 2, STUN_GENERIC_IPV6_ADDR_LEN); - buf += ATTR_HDR_LEN; + /* attribute len */ + PUTVAL16H(buf, 2, STUN_GENERIC_IPV6_ADDR_LEN); + buf += ATTR_HDR_LEN; - /* Ignored */ - *buf++ = '\0'; - - /* Address family, 2 for IPv6 */ - *buf++ = 2; - - /* IPv6 address */ - if (ca->xor_ed) { - unsigned i; - pj_uint8_t *dst; - const pj_uint8_t *src; - pj_uint32_t magic = pj_htonl(PJ_STUN_MAGIC); - pj_uint16_t port = ca->sockaddr.ipv6.sin6_port; - - /* Port */ - port ^= pj_htons(PJ_STUN_MAGIC >> 16); - pj_memcpy(buf, &port, 2); - buf += 2; - - /* Address */ - dst = buf; - src = (const pj_uint8_t*) &ca->sockaddr.ipv6.sin6_addr; - for (i=0; i<4; ++i) { - dst[i] = (pj_uint8_t)(src[i] ^ ((const pj_uint8_t*)&magic)[i]); - } - pj_assert(sizeof(msghdr->tsx_id[0]) == 1); - for (i=0; i<12; ++i) { - dst[i+4] = (pj_uint8_t)(src[i+4] ^ msghdr->tsx_id[i]); - } - - buf += 16; - - } else { - /* Port */ - pj_memcpy(buf, &ca->sockaddr.ipv6.sin6_port, 2); - buf += 2; - - /* Address */ - pj_memcpy(buf, &ca->sockaddr.ipv6.sin6_addr, 16); - buf += 16; - } - - pj_assert(buf - start_buf == ATTR_LEN); + /* Ignored */ + *buf++ = '\0'; + + /* Address family, 2 for IPv6 */ + *buf++ = 2; + + /* IPv6 address */ + if (ca->xor_ed) { + unsigned i; + pj_uint8_t *dst; + const pj_uint8_t *src; + pj_uint32_t magic = pj_htonl(PJ_STUN_MAGIC); + pj_uint16_t port = ca->sockaddr.ipv6.sin6_port; + + /* Port */ + port ^= pj_htons(PJ_STUN_MAGIC >> 16); + pj_memcpy(buf, &port, 2); + buf += 2; + + /* Address */ + dst = buf; + src = (const pj_uint8_t*) &ca->sockaddr.ipv6.sin6_addr; + for (i=0; i<4; ++i) { + dst[i] = (pj_uint8_t)(src[i] ^ ((const pj_uint8_t*)&magic)[i]); + } + pj_assert(sizeof(msghdr->tsx_id[0]) == 1); + for (i=0; i<12; ++i) { + dst[i+4] = (pj_uint8_t)(src[i+4] ^ msghdr->tsx_id[i]); + } + + buf += 16; + + } else { + /* Port */ + pj_memcpy(buf, &ca->sockaddr.ipv6.sin6_port, 2); + buf += 2; + + /* Address */ + pj_memcpy(buf, &ca->sockaddr.ipv6.sin6_addr, 16); + buf += 16; + } + + pj_assert(buf - start_buf == ATTR_LEN); } else { - return PJNATH_EINVAF; + return PJNATH_EINVAF; } /* Done */ @@ -1136,16 +1135,16 @@ static void* clone_sockaddr_attr(pj_pool_t *pool, const void *src) * Initialize a STUN generic string attribute. */ PJ_DEF(pj_status_t) pj_stun_string_attr_init( pj_stun_string_attr *attr, - pj_pool_t *pool, - int attr_type, - const pj_str_t *value) + pj_pool_t *pool, + int attr_type, + const pj_str_t *value) { if (value && value->slen) { - INIT_ATTR(attr, attr_type, value->slen); - attr->value.slen = value->slen; - pj_strdup(pool, &attr->value, value); + INIT_ATTR(attr, attr_type, value->slen); + attr->value.slen = value->slen; + pj_strdup(pool, &attr->value, value); } else { - INIT_ATTR(attr, attr_type, 0); + INIT_ATTR(attr, attr_type, 0); } return PJ_SUCCESS; } @@ -1155,9 +1154,9 @@ PJ_DEF(pj_status_t) pj_stun_string_attr_init( pj_stun_string_attr *attr, * Create a STUN generic string attribute. */ PJ_DEF(pj_status_t) pj_stun_string_attr_create(pj_pool_t *pool, - int attr_type, - const pj_str_t *value, - pj_stun_string_attr **p_attr) + int attr_type, + const pj_str_t *value, + pj_stun_string_attr **p_attr) { pj_stun_string_attr *attr; @@ -1174,26 +1173,26 @@ PJ_DEF(pj_status_t) pj_stun_string_attr_create(pj_pool_t *pool, * Create and add STUN generic string attribute to the message. */ PJ_DEF(pj_status_t) pj_stun_msg_add_string_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int attr_type, - const pj_str_t *value) + pj_stun_msg *msg, + int attr_type, + const pj_str_t *value) { pj_stun_string_attr *attr = NULL; pj_status_t status; status = pj_stun_string_attr_create(pool, attr_type, value, - &attr); + &attr); if (status != PJ_SUCCESS) - return status; + return status; return pj_stun_msg_add_attr(msg, &attr->hdr); } static pj_status_t decode_string_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr) + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr) { pj_stun_string_attr *attr; pj_str_t value; @@ -1220,12 +1219,12 @@ static pj_status_t decode_string_attr(pj_pool_t *pool, static pj_status_t encode_string_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed) + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed) { const pj_stun_string_attr *ca = - (const pj_stun_string_attr*)a; + (const pj_stun_string_attr*)a; PJ_CHECK_STACK(); @@ -1234,8 +1233,8 @@ static pj_status_t encode_string_attr(const void *a, pj_uint8_t *buf, /* Calculated total attr_len (add padding if necessary) */ *printed = ((unsigned)ca->value.slen + ATTR_HDR_LEN + 3) & (~3); if (len < *printed) { - *printed = 0; - return PJ_ETOOSMALL; + *printed = 0; + return PJ_ETOOSMALL; } PUTVAL16H(buf, 0, ca->hdr.type); @@ -1246,15 +1245,15 @@ static pj_status_t encode_string_attr(const void *a, pj_uint8_t *buf, * rules with RFC 5389. */ if (msghdr->magic != PJ_STUN_MAGIC || - ca->hdr.type == PJ_STUN_ATTR_SOFTWARE) + ca->hdr.type == PJ_STUN_ATTR_SOFTWARE) { - /* Set the length to be 4-bytes aligned so that we can - * communicate with RFC 3489 endpoints - */ - PUTVAL16H(buf, 2, (pj_uint16_t)((ca->value.slen + 3) & (~3))); + /* Set the length to be 4-bytes aligned so that we can + * communicate with RFC 3489 endpoints + */ + PUTVAL16H(buf, 2, (pj_uint16_t)((ca->value.slen + 3) & (~3))); } else { - /* Use RFC 5389 rule */ - PUTVAL16H(buf, 2, (pj_uint16_t)ca->value.slen); + /* Use RFC 5389 rule */ + PUTVAL16H(buf, 2, (pj_uint16_t)ca->value.slen); } /* Copy the string */ @@ -1262,10 +1261,10 @@ static pj_status_t encode_string_attr(const void *a, pj_uint8_t *buf, /* Add padding character, if string is not 4-bytes aligned. */ if (ca->value.slen & 0x03) { - pj_uint8_t pad[3]; - pj_memset(pad, padding_char, sizeof(pad)); - pj_memcpy(buf+ATTR_HDR_LEN+ca->value.slen, pad, - 4-(ca->value.slen & 0x03)); + pj_uint8_t pad[3]; + pj_memset(pad, padding_char, sizeof(pad)); + pj_memcpy(buf+ATTR_HDR_LEN+ca->value.slen, pad, + 4-(ca->value.slen & 0x03)); } /* Done */ @@ -1293,8 +1292,8 @@ static void* clone_string_attr(pj_pool_t *pool, const void *src) * Create a STUN empty attribute. */ PJ_DEF(pj_status_t) pj_stun_empty_attr_create(pj_pool_t *pool, - int attr_type, - pj_stun_empty_attr **p_attr) + int attr_type, + pj_stun_empty_attr **p_attr) { pj_stun_empty_attr *attr; @@ -1313,23 +1312,23 @@ PJ_DEF(pj_status_t) pj_stun_empty_attr_create(pj_pool_t *pool, * Create STUN empty attribute and add the attribute to the message. */ PJ_DEF(pj_status_t) pj_stun_msg_add_empty_attr( pj_pool_t *pool, - pj_stun_msg *msg, - int attr_type) + pj_stun_msg *msg, + int attr_type) { pj_stun_empty_attr *attr = NULL; pj_status_t status; status = pj_stun_empty_attr_create(pool, attr_type, &attr); if (status != PJ_SUCCESS) - return status; + return status; return pj_stun_msg_add_attr(msg, &attr->hdr); } static pj_status_t decode_empty_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr) + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr) { pj_stun_empty_attr *attr; @@ -1344,7 +1343,7 @@ static pj_status_t decode_empty_attr(pj_pool_t *pool, /* Check that the attribute length is valid */ if (attr->hdr.length != 0) - return PJNATH_ESTUNINATTRLEN; + return PJNATH_ESTUNINATTRLEN; /* Done */ *p_attr = attr; @@ -1354,16 +1353,16 @@ static pj_status_t decode_empty_attr(pj_pool_t *pool, static pj_status_t encode_empty_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed) + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed) { const pj_stun_empty_attr *ca = (pj_stun_empty_attr*)a; PJ_UNUSED_ARG(msghdr); if (len < ATTR_HDR_LEN) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; PUTVAL16H(buf, 0, ca->hdr.type); PUTVAL16H(buf, 2, 0); @@ -1393,9 +1392,9 @@ static void* clone_empty_attr(pj_pool_t *pool, const void *src) * Create a STUN generic 32bit value attribute. */ PJ_DEF(pj_status_t) pj_stun_uint_attr_create(pj_pool_t *pool, - int attr_type, - pj_uint32_t value, - pj_stun_uint_attr **p_attr) + int attr_type, + pj_uint32_t value, + pj_stun_uint_attr **p_attr) { pj_stun_uint_attr *attr; @@ -1412,24 +1411,24 @@ PJ_DEF(pj_status_t) pj_stun_uint_attr_create(pj_pool_t *pool, /* Create and add STUN generic 32bit value attribute to the message. */ PJ_DEF(pj_status_t) pj_stun_msg_add_uint_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int attr_type, - pj_uint32_t value) + pj_stun_msg *msg, + int attr_type, + pj_uint32_t value) { pj_stun_uint_attr *attr = NULL; pj_status_t status; status = pj_stun_uint_attr_create(pool, attr_type, value, &attr); if (status != PJ_SUCCESS) - return status; + return status; return pj_stun_msg_add_attr(msg, &attr->hdr); } static pj_status_t decode_uint_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr) + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr) { pj_stun_uint_attr *attr; @@ -1443,7 +1442,7 @@ static pj_status_t decode_uint_attr(pj_pool_t *pool, /* Check that the attribute length is valid */ if (attr->hdr.length != 4) - return PJNATH_ESTUNINATTRLEN; + return PJNATH_ESTUNINATTRLEN; /* Done */ *p_attr = attr; @@ -1453,9 +1452,9 @@ static pj_status_t decode_uint_attr(pj_pool_t *pool, static pj_status_t encode_uint_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed) + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed) { const pj_stun_uint_attr *ca = (const pj_stun_uint_attr*)a; @@ -1464,7 +1463,7 @@ static pj_status_t encode_uint_attr(const void *a, pj_uint8_t *buf, PJ_UNUSED_ARG(msghdr); if (len < 8) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; PUTVAL16H(buf, 0, ca->hdr.type); PUTVAL16H(buf, 2, (pj_uint16_t)4); @@ -1492,9 +1491,9 @@ static void* clone_uint_attr(pj_pool_t *pool, const void *src) * Create a STUN generic 64bit value attribute. */ PJ_DEF(pj_status_t) pj_stun_uint64_attr_create(pj_pool_t *pool, - int attr_type, - const pj_timestamp *value, - pj_stun_uint64_attr **p_attr) + int attr_type, + const pj_timestamp *value, + pj_stun_uint64_attr **p_attr) { pj_stun_uint64_attr *attr; @@ -1504,8 +1503,8 @@ PJ_DEF(pj_status_t) pj_stun_uint64_attr_create(pj_pool_t *pool, INIT_ATTR(attr, attr_type, 8); if (value) { - attr->value.u32.hi = value->u32.hi; - attr->value.u32.lo = value->u32.lo; + attr->value.u32.hi = value->u32.hi; + attr->value.u32.lo = value->u32.lo; } *p_attr = attr; @@ -1515,24 +1514,24 @@ PJ_DEF(pj_status_t) pj_stun_uint64_attr_create(pj_pool_t *pool, /* Create and add STUN generic 64bit value attribute to the message. */ PJ_DEF(pj_status_t) pj_stun_msg_add_uint64_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int attr_type, - const pj_timestamp *value) + pj_stun_msg *msg, + int attr_type, + const pj_timestamp *value) { pj_stun_uint64_attr *attr = NULL; pj_status_t status; status = pj_stun_uint64_attr_create(pool, attr_type, value, &attr); if (status != PJ_SUCCESS) - return status; + return status; return pj_stun_msg_add_attr(msg, &attr->hdr); } static pj_status_t decode_uint64_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr) + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr) { pj_stun_uint64_attr *attr; @@ -1543,9 +1542,9 @@ static pj_status_t decode_uint64_attr(pj_pool_t *pool, GETATTRHDR(buf, &attr->hdr); if (attr->hdr.length != 8) - return PJNATH_ESTUNINATTRLEN; + return PJNATH_ESTUNINATTRLEN; - GETVAL64H(buf, 4, &attr->value); + GETVAL64H(buf, 4, &attr->value); /* Done */ *p_attr = attr; @@ -1555,9 +1554,9 @@ static pj_status_t decode_uint64_attr(pj_pool_t *pool, static pj_status_t encode_uint64_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed) + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed) { const pj_stun_uint64_attr *ca = (const pj_stun_uint64_attr*)a; @@ -1566,7 +1565,7 @@ static pj_status_t encode_uint64_attr(const void *a, pj_uint8_t *buf, PJ_UNUSED_ARG(msghdr); if (len < 12) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; PUTVAL16H(buf, 0, ca->hdr.type); PUTVAL16H(buf, 2, (pj_uint16_t)8); @@ -1598,7 +1597,7 @@ static void* clone_uint64_attr(pj_pool_t *pool, const void *src) * Create a STUN MESSAGE-INTEGRITY attribute. */ PJ_DEF(pj_status_t) pj_stun_msgint_attr_create(pj_pool_t *pool, - pj_stun_msgint_attr **p_attr) + pj_stun_msgint_attr **p_attr) { pj_stun_msgint_attr *attr; @@ -1614,22 +1613,22 @@ PJ_DEF(pj_status_t) pj_stun_msgint_attr_create(pj_pool_t *pool, PJ_DEF(pj_status_t) pj_stun_msg_add_msgint_attr(pj_pool_t *pool, - pj_stun_msg *msg) + pj_stun_msg *msg) { pj_stun_msgint_attr *attr = NULL; pj_status_t status; status = pj_stun_msgint_attr_create(pool, &attr); if (status != PJ_SUCCESS) - return status; + return status; return pj_stun_msg_add_attr(msg, &attr->hdr); } static pj_status_t decode_msgint_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr) + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr) { pj_stun_msgint_attr *attr; @@ -1641,7 +1640,7 @@ static pj_status_t decode_msgint_attr(pj_pool_t *pool, /* Check that the attribute length is valid */ if (attr->hdr.length != 20) - return PJNATH_ESTUNINATTRLEN; + return PJNATH_ESTUNINATTRLEN; /* Copy hmac */ pj_memcpy(attr->hmac, buf+4, 20); @@ -1653,9 +1652,9 @@ static pj_status_t decode_msgint_attr(pj_pool_t *pool, static pj_status_t encode_msgint_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed) + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed) { const pj_stun_msgint_attr *ca = (const pj_stun_msgint_attr*)a; @@ -1664,7 +1663,7 @@ static pj_status_t encode_msgint_attr(const void *a, pj_uint8_t *buf, PJ_UNUSED_ARG(msghdr); if (len < 24) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; /* Copy and convert attribute to network byte order */ PUTVAL16H(buf, 0, ca->hdr.type); @@ -1697,9 +1696,9 @@ static void* clone_msgint_attr(pj_pool_t *pool, const void *src) * Create a STUN ERROR-CODE attribute. */ PJ_DEF(pj_status_t) pj_stun_errcode_attr_create(pj_pool_t *pool, - int err_code, - const pj_str_t *err_reason, - pj_stun_errcode_attr **p_attr) + int err_code, + const pj_str_t *err_reason, + pj_stun_errcode_attr **p_attr) { pj_stun_errcode_attr *attr; char err_buf[80]; @@ -1708,13 +1707,13 @@ PJ_DEF(pj_status_t) pj_stun_errcode_attr_create(pj_pool_t *pool, PJ_ASSERT_RETURN(pool && err_code && p_attr, PJ_EINVAL); if (err_reason == NULL) { - str = pj_stun_get_err_reason(err_code); - if (str.slen == 0) { - str.slen = pj_ansi_snprintf(err_buf, sizeof(err_buf), - "Unknown error %d", err_code); - str.ptr = err_buf; - } - err_reason = &str; + str = pj_stun_get_err_reason(err_code); + if (str.slen == 0) { + str.slen = pj_ansi_snprintf(err_buf, sizeof(err_buf), + "Unknown error %d", err_code); + str.ptr = err_buf; + } + err_reason = &str; } attr = PJ_POOL_ZALLOC_T(pool, pj_stun_errcode_attr); @@ -1729,25 +1728,25 @@ PJ_DEF(pj_status_t) pj_stun_errcode_attr_create(pj_pool_t *pool, PJ_DEF(pj_status_t) pj_stun_msg_add_errcode_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int err_code, - const pj_str_t *err_reason) + pj_stun_msg *msg, + int err_code, + const pj_str_t *err_reason) { pj_stun_errcode_attr *err_attr = NULL; pj_status_t status; status = pj_stun_errcode_attr_create(pool, err_code, err_reason, - &err_attr); + &err_attr); if (status != PJ_SUCCESS) - return status; + return status; return pj_stun_msg_add_attr(msg, &err_attr->hdr); } static pj_status_t decode_errcode_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr) + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr) { pj_stun_errcode_attr *attr; pj_str_t value; @@ -1765,7 +1764,7 @@ static pj_status_t decode_errcode_attr(pj_pool_t *pool, value.slen = attr->hdr.length - 4; /* Make sure the length is never negative */ if (value.slen < 0) - value.slen = 0; + value.slen = 0; /* Copy the string to the attribute */ pj_strdup(pool, &attr->reason, &value); @@ -1778,19 +1777,19 @@ static pj_status_t decode_errcode_attr(pj_pool_t *pool, static pj_status_t encode_errcode_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed) + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed) { const pj_stun_errcode_attr *ca = - (const pj_stun_errcode_attr*)a; + (const pj_stun_errcode_attr*)a; PJ_CHECK_STACK(); PJ_UNUSED_ARG(msghdr); if (len < ATTR_HDR_LEN + 4 + (unsigned)ca->reason.slen) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; /* Copy and convert attribute to network byte order */ PUTVAL16H(buf, 0, ca->hdr.type); @@ -1828,15 +1827,15 @@ static void* clone_errcode_attr(pj_pool_t *pool, const void *src) /* * Create an empty instance of STUN UNKNOWN-ATTRIBUTES attribute. * - * @param pool The pool to allocate memory from. - * @param p_attr Pointer to receive the attribute. + * @param pool The pool to allocate memory from. + * @param p_attr Pointer to receive the attribute. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DEF(pj_status_t) pj_stun_unknown_attr_create(pj_pool_t *pool, - unsigned attr_cnt, - const pj_uint16_t attr_array[], - pj_stun_unknown_attr **p_attr) + unsigned attr_cnt, + const pj_uint16_t attr_array[], + pj_stun_unknown_attr **p_attr) { pj_stun_unknown_attr *attr; unsigned i; @@ -1848,7 +1847,7 @@ PJ_DEF(pj_status_t) pj_stun_unknown_attr_create(pj_pool_t *pool, attr->attr_count = attr_cnt; for (i=0; iattrs[i] = attr_array[i]; + attr->attrs[i] = attr_array[i]; } /* If the number of unknown attributes is an odd number, one of the @@ -1856,7 +1855,7 @@ PJ_DEF(pj_status_t) pj_stun_unknown_attr_create(pj_pool_t *pool, */ /* No longer necessary if ((attr_cnt & 0x01)) { - attr->attrs[attr_cnt] = attr_array[attr_cnt-1]; + attr->attrs[attr_cnt] = attr_array[attr_cnt-1]; } */ @@ -1868,24 +1867,24 @@ PJ_DEF(pj_status_t) pj_stun_unknown_attr_create(pj_pool_t *pool, /* Create and add STUN UNKNOWN-ATTRIBUTES attribute to the message. */ PJ_DEF(pj_status_t) pj_stun_msg_add_unknown_attr(pj_pool_t *pool, - pj_stun_msg *msg, - unsigned attr_cnt, - const pj_uint16_t attr_type[]) + pj_stun_msg *msg, + unsigned attr_cnt, + const pj_uint16_t attr_type[]) { pj_stun_unknown_attr *attr = NULL; pj_status_t status; status = pj_stun_unknown_attr_create(pool, attr_cnt, attr_type, &attr); if (status != PJ_SUCCESS) - return status; + return status; return pj_stun_msg_add_attr(msg, &attr->hdr); } static pj_status_t decode_unknown_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr) + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr) { pj_stun_unknown_attr *attr; const pj_uint16_t *punk_attr; @@ -1898,11 +1897,11 @@ static pj_status_t decode_unknown_attr(pj_pool_t *pool, attr->attr_count = (attr->hdr.length >> 1); if (attr->attr_count > PJ_STUN_MAX_ATTR) - return PJ_ETOOMANY; + return PJ_ETOOMANY; punk_attr = (const pj_uint16_t*)(buf + ATTR_HDR_LEN); for (i=0; iattr_count; ++i) { - attr->attrs[i] = pj_ntohs(punk_attr[i]); + attr->attrs[i] = pj_ntohs(punk_attr[i]); } /* Done */ @@ -1913,9 +1912,9 @@ static pj_status_t decode_unknown_attr(pj_pool_t *pool, static pj_status_t encode_unknown_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed) + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed) { const pj_stun_unknown_attr *ca = (const pj_stun_unknown_attr*) a; pj_uint16_t *dst_unk_attr; @@ -1927,7 +1926,7 @@ static pj_status_t encode_unknown_attr(const void *a, pj_uint8_t *buf, /* Check that buffer is enough */ if (len < ATTR_HDR_LEN + (ca->attr_count << 1)) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; PUTVAL16H(buf, 0, ca->hdr.type); PUTVAL16H(buf, 2, (pj_uint16_t)(ca->attr_count << 1)); @@ -1935,7 +1934,7 @@ static pj_status_t encode_unknown_attr(const void *a, pj_uint8_t *buf, /* Copy individual attribute */ dst_unk_attr = (pj_uint16_t*)(buf + ATTR_HDR_LEN); for (i=0; i < ca->attr_count; ++i, ++dst_unk_attr) { - *dst_unk_attr = pj_htons(ca->attrs[i]); + *dst_unk_attr = pj_htons(ca->attrs[i]); } /* Done */ @@ -1963,10 +1962,10 @@ static void* clone_unknown_attr(pj_pool_t *pool, const void *src) * Initialize STUN binary attribute. */ PJ_DEF(pj_status_t) pj_stun_binary_attr_init( pj_stun_binary_attr *attr, - pj_pool_t *pool, - int attr_type, - const pj_uint8_t *data, - unsigned length) + pj_pool_t *pool, + int attr_type, + const pj_uint8_t *data, + unsigned length) { PJ_ASSERT_RETURN(attr_type, PJ_EINVAL); @@ -1975,12 +1974,12 @@ PJ_DEF(pj_status_t) pj_stun_binary_attr_init( pj_stun_binary_attr *attr, attr->magic = PJ_STUN_MAGIC; if (data && length) { - attr->length = length; - attr->data = (pj_uint8_t*) pj_pool_alloc(pool, length); - pj_memcpy(attr->data, data, length); + attr->length = length; + attr->data = (pj_uint8_t*) pj_pool_alloc(pool, length); + pj_memcpy(attr->data, data, length); } else { - attr->data = NULL; - attr->length = 0; + attr->data = NULL; + attr->length = 0; } return PJ_SUCCESS; @@ -1991,10 +1990,10 @@ PJ_DEF(pj_status_t) pj_stun_binary_attr_init( pj_stun_binary_attr *attr, * Create a blank binary attribute. */ PJ_DEF(pj_status_t) pj_stun_binary_attr_create(pj_pool_t *pool, - int attr_type, - const pj_uint8_t *data, - unsigned length, - pj_stun_binary_attr **p_attr) + int attr_type, + const pj_uint8_t *data, + unsigned length, + pj_stun_binary_attr **p_attr) { pj_stun_binary_attr *attr; @@ -2007,27 +2006,27 @@ PJ_DEF(pj_status_t) pj_stun_binary_attr_create(pj_pool_t *pool, /* Create and add binary attr. */ PJ_DEF(pj_status_t) pj_stun_msg_add_binary_attr(pj_pool_t *pool, - pj_stun_msg *msg, - int attr_type, - const pj_uint8_t *data, - unsigned length) + pj_stun_msg *msg, + int attr_type, + const pj_uint8_t *data, + unsigned length) { pj_stun_binary_attr *attr = NULL; pj_status_t status; status = pj_stun_binary_attr_create(pool, attr_type, - data, length, &attr); + data, length, &attr); if (status != PJ_SUCCESS) - return status; + return status; return pj_stun_msg_add_attr(msg, &attr->hdr); } static pj_status_t decode_binary_attr(pj_pool_t *pool, - const pj_uint8_t *buf, - const pj_stun_msg_hdr *msghdr, - void **p_attr) + const pj_uint8_t *buf, + const pj_stun_msg_hdr *msghdr, + void **p_attr) { pj_stun_binary_attr *attr; @@ -2051,9 +2050,9 @@ static pj_status_t decode_binary_attr(pj_pool_t *pool, static pj_status_t encode_binary_attr(const void *a, pj_uint8_t *buf, - unsigned len, - const pj_stun_msg_hdr *msghdr, - unsigned *printed) + unsigned len, + const pj_stun_msg_hdr *msghdr, + unsigned *printed) { const pj_stun_binary_attr *ca = (const pj_stun_binary_attr*)a; @@ -2064,7 +2063,7 @@ static pj_status_t encode_binary_attr(const void *a, pj_uint8_t *buf, /* Calculated total attr_len (add padding if necessary) */ *printed = (ca->length + ATTR_HDR_LEN + 3) & (~3); if (len < *printed) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; PUTVAL16H(buf, 0, ca->hdr.type); PUTVAL16H(buf, 2, (pj_uint16_t) ca->length); @@ -2085,8 +2084,8 @@ static void* clone_binary_attr(pj_pool_t *pool, const void *src) pj_memcpy(dst, src, sizeof(pj_stun_binary_attr)); if (asrc->length) { - dst->data = (pj_uint8_t*) pj_pool_alloc(pool, asrc->length); - pj_memcpy(dst->data, asrc->data, asrc->length); + dst->data = (pj_uint8_t*) pj_pool_alloc(pool, asrc->length); + pj_memcpy(dst->data, asrc->data, asrc->length); } return (void*)dst; @@ -2098,9 +2097,9 @@ static void* clone_binary_attr(pj_pool_t *pool, const void *src) * Initialize a generic STUN message. */ PJ_DEF(pj_status_t) pj_stun_msg_init( pj_stun_msg *msg, - unsigned msg_type, - pj_uint32_t magic, - const pj_uint8_t tsx_id[12]) + unsigned msg_type, + pj_uint32_t magic, + const pj_uint8_t tsx_id[12]) { PJ_ASSERT_RETURN(msg && msg_type, PJ_EINVAL); @@ -2110,24 +2109,24 @@ PJ_DEF(pj_status_t) pj_stun_msg_init( pj_stun_msg *msg, msg->attr_count = 0; if (tsx_id) { - pj_memcpy(&msg->hdr.tsx_id, tsx_id, sizeof(msg->hdr.tsx_id)); + pj_memcpy(&msg->hdr.tsx_id, tsx_id, sizeof(msg->hdr.tsx_id)); } else { - struct transaction_id - { - pj_uint32_t proc_id; - pj_uint32_t random; - pj_uint32_t counter; - } id; - static pj_uint32_t pj_stun_tsx_id_counter; - - if (!pj_stun_tsx_id_counter) - pj_stun_tsx_id_counter = pj_rand(); - - id.proc_id = pj_getpid(); - id.random = pj_rand(); - id.counter = pj_stun_tsx_id_counter++; - - pj_memcpy(&msg->hdr.tsx_id, &id, sizeof(msg->hdr.tsx_id)); + struct transaction_id + { + pj_uint32_t proc_id; + pj_uint32_t random; + pj_uint32_t counter; + } id; + static pj_uint32_t pj_stun_tsx_id_counter; + + if (!pj_stun_tsx_id_counter) + pj_stun_tsx_id_counter = pj_rand(); + + id.proc_id = pj_getpid(); + id.random = pj_rand(); + id.counter = pj_stun_tsx_id_counter++; + + pj_memcpy(&msg->hdr.tsx_id, &id, sizeof(msg->hdr.tsx_id)); } return PJ_SUCCESS; @@ -2138,10 +2137,10 @@ PJ_DEF(pj_status_t) pj_stun_msg_init( pj_stun_msg *msg, * Create a blank STUN message. */ PJ_DEF(pj_status_t) pj_stun_msg_create( pj_pool_t *pool, - unsigned msg_type, - pj_uint32_t magic, - const pj_uint8_t tsx_id[12], - pj_stun_msg **p_msg) + unsigned msg_type, + pj_uint32_t magic, + const pj_uint8_t tsx_id[12], + pj_stun_msg **p_msg) { pj_stun_msg *msg; @@ -2157,7 +2156,7 @@ PJ_DEF(pj_status_t) pj_stun_msg_create( pj_pool_t *pool, * Clone a STUN message with all of its attributes. */ PJ_DEF(pj_stun_msg*) pj_stun_msg_clone( pj_pool_t *pool, - const pj_stun_msg *src) + const pj_stun_msg *src) { pj_stun_msg *dst; unsigned i; @@ -2169,9 +2168,9 @@ PJ_DEF(pj_stun_msg*) pj_stun_msg_clone( pj_pool_t *pool, /* Duplicate the attributes */ for (i=0, dst->attr_count=0; iattr_count; ++i) { - dst->attr[dst->attr_count] = pj_stun_attr_clone(pool, src->attr[i]); - if (dst->attr[dst->attr_count]) - ++dst->attr_count; + dst->attr[dst->attr_count] = pj_stun_attr_clone(pool, src->attr[i]); + if (dst->attr[dst->attr_count]) + ++dst->attr_count; } return dst; @@ -2182,7 +2181,7 @@ PJ_DEF(pj_stun_msg*) pj_stun_msg_clone( pj_pool_t *pool, * Add STUN attribute to STUN message. */ PJ_DEF(pj_status_t) pj_stun_msg_add_attr(pj_stun_msg *msg, - pj_stun_attr_hdr *attr) + pj_stun_attr_hdr *attr) { PJ_ASSERT_RETURN(msg && attr, PJ_EINVAL); PJ_ASSERT_RETURN(msg->attr_count < PJ_STUN_MAX_ATTR, PJ_ETOOMANY); @@ -2196,32 +2195,32 @@ PJ_DEF(pj_status_t) pj_stun_msg_add_attr(pj_stun_msg *msg, * Check that the PDU is potentially a valid STUN message. */ PJ_DEF(pj_status_t) pj_stun_msg_check(const pj_uint8_t *pdu, pj_size_t pdu_len, - unsigned options) + unsigned options) { pj_uint32_t msg_len; PJ_ASSERT_RETURN(pdu, PJ_EINVAL); if (pdu_len < sizeof(pj_stun_msg_hdr)) - return PJNATH_EINSTUNMSGLEN; + return PJNATH_EINSTUNMSGLEN; /* First byte of STUN message is always 0x00 or 0x01. */ if (*pdu != 0x00 && *pdu != 0x01) - return PJNATH_EINSTUNMSGTYPE; + return PJNATH_EINSTUNMSGTYPE; /* Check the PDU length */ msg_len = GETVAL16H(pdu, 2); if ((msg_len + 20 > pdu_len) || - ((options & PJ_STUN_IS_DATAGRAM) && msg_len + 20 != pdu_len)) + ((options & PJ_STUN_IS_DATAGRAM) && msg_len + 20 != pdu_len)) { - return PJNATH_EINSTUNMSGLEN; + return PJNATH_EINSTUNMSGLEN; } /* STUN message is always padded to the nearest 4 bytes, thus * the last two bits of the length field are always zero. */ if ((msg_len & 0x03) != 0) { - return PJNATH_EINSTUNMSGLEN; + return PJNATH_EINSTUNMSGLEN; } /* If magic is set, then there is great possibility that this is @@ -2229,23 +2228,23 @@ PJ_DEF(pj_status_t) pj_stun_msg_check(const pj_uint8_t *pdu, pj_size_t pdu_len, */ if (GETVAL32H(pdu, 4) == PJ_STUN_MAGIC) { - /* Check if FINGERPRINT attribute is present */ - if ((options & PJ_STUN_NO_FINGERPRINT_CHECK )==0 && - GETVAL16H(pdu, msg_len + 20 - 8) == PJ_STUN_ATTR_FINGERPRINT) - { - pj_uint16_t attr_len = GETVAL16H(pdu, msg_len + 20 - 8 + 2); - pj_uint32_t fingerprint = GETVAL32H(pdu, msg_len + 20 - 8 + 4); - pj_uint32_t crc; + /* Check if FINGERPRINT attribute is present */ + if ((options & PJ_STUN_NO_FINGERPRINT_CHECK )==0 && + GETVAL16H(pdu, msg_len + 20 - 8) == PJ_STUN_ATTR_FINGERPRINT) + { + pj_uint16_t attr_len = GETVAL16H(pdu, msg_len + 20 - 8 + 2); + pj_uint32_t fingerprint = GETVAL32H(pdu, msg_len + 20 - 8 + 4); + pj_uint32_t crc; - if (attr_len != 4) - return PJNATH_ESTUNINATTRLEN; + if (attr_len != 4) + return PJNATH_ESTUNINATTRLEN; - crc = pj_crc32_calc(pdu, msg_len + 20 - 8); - crc ^= STUN_XOR_FINGERPRINT; + crc = pj_crc32_calc(pdu, msg_len + 20 - 8); + crc ^= STUN_XOR_FINGERPRINT; - if (crc != fingerprint) - return PJNATH_ESTUNFINGERPRINT; - } + if (crc != fingerprint) + return PJNATH_ESTUNFINGERPRINT; + } } /* Could be a STUN message */ @@ -2255,10 +2254,10 @@ PJ_DEF(pj_status_t) pj_stun_msg_check(const pj_uint8_t *pdu, pj_size_t pdu_len, /* Create error response */ PJ_DEF(pj_status_t) pj_stun_msg_create_response(pj_pool_t *pool, - const pj_stun_msg *req_msg, - unsigned err_code, - const pj_str_t *err_msg, - pj_stun_msg **p_response) + const pj_stun_msg *req_msg, + unsigned err_code, + const pj_str_t *err_msg, + pj_stun_msg **p_response) { unsigned msg_type = req_msg->hdr.type; pj_stun_msg *response = NULL; @@ -2267,27 +2266,27 @@ PJ_DEF(pj_status_t) pj_stun_msg_create_response(pj_pool_t *pool, PJ_ASSERT_RETURN(pool && p_response, PJ_EINVAL); PJ_ASSERT_RETURN(PJ_STUN_IS_REQUEST(msg_type), - PJNATH_EINSTUNMSGTYPE); + PJNATH_EINSTUNMSGTYPE); /* Create response or error response */ if (err_code) - msg_type |= PJ_STUN_ERROR_RESPONSE_BIT; + msg_type |= PJ_STUN_ERROR_RESPONSE_BIT; else - msg_type |= PJ_STUN_SUCCESS_RESPONSE_BIT; + msg_type |= PJ_STUN_SUCCESS_RESPONSE_BIT; status = pj_stun_msg_create(pool, msg_type, req_msg->hdr.magic, - req_msg->hdr.tsx_id, &response); + req_msg->hdr.tsx_id, &response); if (status != PJ_SUCCESS) { - return status; + return status; } /* Add error code attribute */ if (err_code) { - status = pj_stun_msg_add_errcode_attr(pool, response, - err_code, err_msg); - if (status != PJ_SUCCESS) { - return status; - } + status = pj_stun_msg_add_errcode_attr(pool, response, + err_code, err_msg); + if (status != PJ_SUCCESS) { + return status; + } } *p_response = response; @@ -2299,12 +2298,12 @@ PJ_DEF(pj_status_t) pj_stun_msg_create_response(pj_pool_t *pool, * Parse incoming packet into STUN message. */ PJ_DEF(pj_status_t) pj_stun_msg_decode(pj_pool_t *pool, - const pj_uint8_t *pdu, - pj_size_t pdu_len, - unsigned options, - pj_stun_msg **p_msg, - pj_size_t *p_parsed_len, - pj_stun_msg **p_response) + const pj_uint8_t *pdu, + pj_size_t pdu_len, + unsigned options, + pj_stun_msg **p_msg, + pj_size_t *p_parsed_len, + pj_stun_msg **p_response) { pj_stun_msg *msg; @@ -2319,15 +2318,15 @@ PJ_DEF(pj_status_t) pj_stun_msg_decode(pj_pool_t *pool, PJ_ASSERT_RETURN(sizeof(pj_stun_msg_hdr) == 20, PJ_EBUG); if (p_parsed_len) - *p_parsed_len = 0; + *p_parsed_len = 0; if (p_response) - *p_response = NULL; + *p_response = NULL; /* Check if this is a STUN message, if necessary */ if (options & PJ_STUN_CHECK_PACKET) { - status = pj_stun_msg_check(pdu, pdu_len, options); - if (status != PJ_SUCCESS) - return status; + status = pj_stun_msg_check(pdu, pdu_len, options); + if (status != PJ_SUCCESS) + return status; } /* Create the message, copy the header, and convert to host byte order */ @@ -2343,211 +2342,211 @@ PJ_DEF(pj_status_t) pj_stun_msg_decode(pj_pool_t *pool, /* No need to create response if this is not a request */ if (!PJ_STUN_IS_REQUEST(msg->hdr.type)) - p_response = NULL; + p_response = NULL; /* Parse attributes */ while (pdu_len >= 4) { - unsigned attr_type, attr_val_len; - const struct attr_desc *adesc; - - /* Get attribute type and length. If length is not aligned - * to 4 bytes boundary, add padding. - */ - attr_type = GETVAL16H(pdu, 0); - attr_val_len = GETVAL16H(pdu, 2); - attr_val_len = (attr_val_len + 3) & (~3); - - /* Check length */ - if (pdu_len < attr_val_len) { - pj_str_t err_msg; - char err_msg_buf[80]; - - err_msg.ptr = err_msg_buf; - err_msg.slen = pj_ansi_snprintf(err_msg_buf, sizeof(err_msg_buf), - "Attribute %s has invalid length", - pj_stun_get_attr_name(attr_type)); - - PJ_LOG(4,(THIS_FILE, "Error decoding message: %.*s", - (int)err_msg.slen, err_msg.ptr)); - - if (p_response) { - pj_stun_msg_create_response(pool, msg, - PJ_STUN_SC_BAD_REQUEST, - &err_msg, p_response); - } - return PJNATH_ESTUNINATTRLEN; - } - - /* Get the attribute descriptor */ - adesc = find_attr_desc(attr_type); - - if (adesc == NULL) { - /* Unrecognized attribute */ - pj_stun_binary_attr *attr = NULL; - - PJ_LOG(5,(THIS_FILE, "Unrecognized attribute type 0x%x", - attr_type)); - - /* Is this a fatal condition? */ - if (attr_type <= 0x7FFF) { - /* This is a mandatory attribute, we must return error - * if we don't understand the attribute. - */ - if (p_response) { - unsigned err_code = PJ_STUN_SC_UNKNOWN_ATTRIBUTE; - - status = pj_stun_msg_create_response(pool, msg, - err_code, NULL, - p_response); - if (status==PJ_SUCCESS) { - pj_uint16_t d = (pj_uint16_t)attr_type; - pj_stun_msg_add_unknown_attr(pool, *p_response, 1, &d); - } - } - - return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNKNOWN_ATTRIBUTE); - } - - /* Make sure we have rooms for the new attribute */ - if (msg->attr_count >= PJ_STUN_MAX_ATTR) { - if (p_response) { - pj_stun_msg_create_response(pool, msg, - PJ_STUN_SC_SERVER_ERROR, - NULL, p_response); - } - return PJNATH_ESTUNTOOMANYATTR; - } - - /* Create binary attribute to represent this */ - status = pj_stun_binary_attr_create(pool, attr_type, pdu+4, - GETVAL16H(pdu, 2), &attr); - if (status != PJ_SUCCESS) { - if (p_response) { - pj_stun_msg_create_response(pool, msg, - PJ_STUN_SC_SERVER_ERROR, - NULL, p_response); - } - - PJ_LOG(4,(THIS_FILE, - "Error parsing unknown STUN attribute type %d", - attr_type)); - - return status; - } - - /* Add the attribute */ - msg->attr[msg->attr_count++] = &attr->hdr; - - } else { - void *attr; - char err_msg1[PJ_ERR_MSG_SIZE], - err_msg2[PJ_ERR_MSG_SIZE]; - - /* Parse the attribute */ - status = (adesc->decode_attr)(pool, pdu, &msg->hdr, &attr); - - if (status != PJ_SUCCESS) { - pj_strerror(status, err_msg1, sizeof(err_msg1)); - - if (p_response) { - pj_str_t e; - - e.ptr = err_msg2; - e.slen= pj_ansi_snprintf(err_msg2, sizeof(err_msg2), - "%s in %s", - err_msg1, - pj_stun_get_attr_name(attr_type)); - if (e.slen < 1 || e.slen >= (int)sizeof(err_msg2)) - e.slen = sizeof(err_msg2) - 1; - pj_stun_msg_create_response(pool, msg, - PJ_STUN_SC_BAD_REQUEST, - &e, p_response); - } - - PJ_LOG(4,(THIS_FILE, - "Error parsing STUN attribute %s: %s", - pj_stun_get_attr_name(attr_type), - err_msg1)); - - return status; - } - - if (attr_type == PJ_STUN_ATTR_MESSAGE_INTEGRITY && - !has_fingerprint) - { - if (has_msg_int) { - /* Already has MESSAGE-INTEGRITY */ - if (p_response) { - pj_stun_msg_create_response(pool, msg, - PJ_STUN_SC_BAD_REQUEST, - NULL, p_response); - } - return PJNATH_ESTUNDUPATTR; - } - has_msg_int = PJ_TRUE; - - } else if (attr_type == PJ_STUN_ATTR_FINGERPRINT) { - if (has_fingerprint) { - /* Already has FINGERPRINT */ - if (p_response) { - pj_stun_msg_create_response(pool, msg, - PJ_STUN_SC_BAD_REQUEST, - NULL, p_response); - } - return PJNATH_ESTUNDUPATTR; - } - has_fingerprint = PJ_TRUE; - } else { - if (has_fingerprint) { - /* Another attribute is found which is not FINGERPRINT - * after FINGERPRINT. Note that non-FINGERPRINT is - * allowed to appear after M-I - */ - if (p_response) { - pj_stun_msg_create_response(pool, msg, - PJ_STUN_SC_BAD_REQUEST, - NULL, p_response); - } - return PJNATH_ESTUNFINGERPOS; - } - } - - /* Make sure we have rooms for the new attribute */ - if (msg->attr_count >= PJ_STUN_MAX_ATTR) { - if (p_response) { - pj_stun_msg_create_response(pool, msg, - PJ_STUN_SC_SERVER_ERROR, - NULL, p_response); - } - return PJNATH_ESTUNTOOMANYATTR; - } - - /* Add the attribute */ - msg->attr[msg->attr_count++] = (pj_stun_attr_hdr*)attr; - } - - /* Next attribute */ - if (attr_val_len + 4 >= pdu_len) { - pdu += pdu_len; - pdu_len = 0; - } else { - pdu += (attr_val_len + 4); - pdu_len -= (attr_val_len + 4); - } + unsigned attr_type, attr_val_len; + const struct attr_desc *adesc; + + /* Get attribute type and length. If length is not aligned + * to 4 bytes boundary, add padding. + */ + attr_type = GETVAL16H(pdu, 0); + attr_val_len = GETVAL16H(pdu, 2); + attr_val_len = (attr_val_len + 3) & (~3); + + /* Check length */ + if (pdu_len < attr_val_len) { + pj_str_t err_msg; + char err_msg_buf[80]; + + err_msg.ptr = err_msg_buf; + err_msg.slen = pj_ansi_snprintf(err_msg_buf, sizeof(err_msg_buf), + "Attribute %s has invalid length", + pj_stun_get_attr_name(attr_type)); + + PJ_LOG(4,(THIS_FILE, "Error decoding message: %.*s", + (int)err_msg.slen, err_msg.ptr)); + + if (p_response) { + pj_stun_msg_create_response(pool, msg, + PJ_STUN_SC_BAD_REQUEST, + &err_msg, p_response); + } + return PJNATH_ESTUNINATTRLEN; + } + + /* Get the attribute descriptor */ + adesc = find_attr_desc(attr_type); + + if (adesc == NULL) { + /* Unrecognized attribute */ + pj_stun_binary_attr *attr = NULL; + + PJ_LOG(5,(THIS_FILE, "Unrecognized attribute type 0x%x", + attr_type)); + + /* Is this a fatal condition? */ + if (attr_type <= 0x7FFF) { + /* This is a mandatory attribute, we must return error + * if we don't understand the attribute. + */ + if (p_response) { + unsigned err_code = PJ_STUN_SC_UNKNOWN_ATTRIBUTE; + + status = pj_stun_msg_create_response(pool, msg, + err_code, NULL, + p_response); + if (status==PJ_SUCCESS) { + pj_uint16_t d = (pj_uint16_t)attr_type; + pj_stun_msg_add_unknown_attr(pool, *p_response, 1, &d); + } + } + + return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNKNOWN_ATTRIBUTE); + } + + /* Make sure we have rooms for the new attribute */ + if (msg->attr_count >= PJ_STUN_MAX_ATTR) { + if (p_response) { + pj_stun_msg_create_response(pool, msg, + PJ_STUN_SC_SERVER_ERROR, + NULL, p_response); + } + return PJNATH_ESTUNTOOMANYATTR; + } + + /* Create binary attribute to represent this */ + status = pj_stun_binary_attr_create(pool, attr_type, pdu+4, + GETVAL16H(pdu, 2), &attr); + if (status != PJ_SUCCESS) { + if (p_response) { + pj_stun_msg_create_response(pool, msg, + PJ_STUN_SC_SERVER_ERROR, + NULL, p_response); + } + + PJ_LOG(4,(THIS_FILE, + "Error parsing unknown STUN attribute type %d", + attr_type)); + + return status; + } + + /* Add the attribute */ + msg->attr[msg->attr_count++] = &attr->hdr; + + } else { + void *attr; + char err_msg1[PJ_ERR_MSG_SIZE], + err_msg2[PJ_ERR_MSG_SIZE]; + + /* Parse the attribute */ + status = (adesc->decode_attr)(pool, pdu, &msg->hdr, &attr); + + if (status != PJ_SUCCESS) { + pj_strerror(status, err_msg1, sizeof(err_msg1)); + + if (p_response) { + pj_str_t e; + + e.ptr = err_msg2; + e.slen= pj_ansi_snprintf(err_msg2, sizeof(err_msg2), + "%s in %s", + err_msg1, + pj_stun_get_attr_name(attr_type)); + if (e.slen < 1 || e.slen >= (int)sizeof(err_msg2)) + e.slen = sizeof(err_msg2) - 1; + pj_stun_msg_create_response(pool, msg, + PJ_STUN_SC_BAD_REQUEST, + &e, p_response); + } + + PJ_LOG(4,(THIS_FILE, + "Error parsing STUN attribute %s: %s", + pj_stun_get_attr_name(attr_type), + err_msg1)); + + return status; + } + + if (attr_type == PJ_STUN_ATTR_MESSAGE_INTEGRITY && + !has_fingerprint) + { + if (has_msg_int) { + /* Already has MESSAGE-INTEGRITY */ + if (p_response) { + pj_stun_msg_create_response(pool, msg, + PJ_STUN_SC_BAD_REQUEST, + NULL, p_response); + } + return PJNATH_ESTUNDUPATTR; + } + has_msg_int = PJ_TRUE; + + } else if (attr_type == PJ_STUN_ATTR_FINGERPRINT) { + if (has_fingerprint) { + /* Already has FINGERPRINT */ + if (p_response) { + pj_stun_msg_create_response(pool, msg, + PJ_STUN_SC_BAD_REQUEST, + NULL, p_response); + } + return PJNATH_ESTUNDUPATTR; + } + has_fingerprint = PJ_TRUE; + } else { + if (has_fingerprint) { + /* Another attribute is found which is not FINGERPRINT + * after FINGERPRINT. Note that non-FINGERPRINT is + * allowed to appear after M-I + */ + if (p_response) { + pj_stun_msg_create_response(pool, msg, + PJ_STUN_SC_BAD_REQUEST, + NULL, p_response); + } + return PJNATH_ESTUNFINGERPOS; + } + } + + /* Make sure we have rooms for the new attribute */ + if (msg->attr_count >= PJ_STUN_MAX_ATTR) { + if (p_response) { + pj_stun_msg_create_response(pool, msg, + PJ_STUN_SC_SERVER_ERROR, + NULL, p_response); + } + return PJNATH_ESTUNTOOMANYATTR; + } + + /* Add the attribute */ + msg->attr[msg->attr_count++] = (pj_stun_attr_hdr*)attr; + } + + /* Next attribute */ + if (attr_val_len + 4 >= pdu_len) { + pdu += pdu_len; + pdu_len = 0; + } else { + pdu += (attr_val_len + 4); + pdu_len -= (attr_val_len + 4); + } } if (pdu_len > 0) { - /* Stray trailing bytes */ - PJ_LOG(4,(THIS_FILE, - "Error decoding STUN message: unparsed trailing %d bytes", - pdu_len)); - return PJNATH_EINSTUNMSGLEN; + /* Stray trailing bytes */ + PJ_LOG(4,(THIS_FILE, + "Error decoding STUN message: unparsed trailing %d bytes", + pdu_len)); + return PJNATH_EINSTUNMSGLEN; } *p_msg = msg; if (p_parsed_len) - *p_parsed_len = (pdu - start_pdu); + *p_parsed_len = (pdu - start_pdu); return PJ_SUCCESS; } @@ -2560,15 +2559,15 @@ static char *print_binary(const pj_uint8_t *data, unsigned data_len) unsigned length=sizeof(static_buffer), i; if (length < data_len * 2 + 8) - return ""; + return ""; pj_ansi_sprintf(buffer, ", data="); buffer += 7; for (i=0; ihdr.type); PUTVAL16H(buf, 2, 0); /* length will be calculated later */ @@ -2616,39 +2615,39 @@ PJ_DEF(pj_status_t) pj_stun_msg_encode(pj_stun_msg *msg, /* Encode each attribute to the message */ for (i=0; iattr_count; ++i) { - const struct attr_desc *adesc; - const pj_stun_attr_hdr *attr_hdr = msg->attr[i]; - - if (attr_hdr->type == PJ_STUN_ATTR_MESSAGE_INTEGRITY) { - pj_assert(amsgint == NULL); - amsgint = (pj_stun_msgint_attr*) attr_hdr; - - /* Stop when encountering MESSAGE-INTEGRITY */ - break; - - } else if (attr_hdr->type == PJ_STUN_ATTR_FINGERPRINT) { - afingerprint = (pj_stun_fingerprint_attr*) attr_hdr; - break; - } - - adesc = find_attr_desc(attr_hdr->type); - if (adesc) { - status = adesc->encode_attr(attr_hdr, buf, (unsigned)buf_size, - &msg->hdr, &printed); - } else { - /* This may be a generic attribute */ - const pj_stun_binary_attr *bin_attr = (const pj_stun_binary_attr*) - attr_hdr; - PJ_ASSERT_RETURN(bin_attr->magic == PJ_STUN_MAGIC, PJ_EBUG); - status = encode_binary_attr(bin_attr, buf, (unsigned)buf_size, - &msg->hdr, &printed); - } - - if (status != PJ_SUCCESS) - return status; - - buf += printed; - buf_size -= printed; + const struct attr_desc *adesc; + const pj_stun_attr_hdr *attr_hdr = msg->attr[i]; + + if (attr_hdr->type == PJ_STUN_ATTR_MESSAGE_INTEGRITY) { + pj_assert(amsgint == NULL); + amsgint = (pj_stun_msgint_attr*) attr_hdr; + + /* Stop when encountering MESSAGE-INTEGRITY */ + break; + + } else if (attr_hdr->type == PJ_STUN_ATTR_FINGERPRINT) { + afingerprint = (pj_stun_fingerprint_attr*) attr_hdr; + break; + } + + adesc = find_attr_desc(attr_hdr->type); + if (adesc) { + status = adesc->encode_attr(attr_hdr, buf, (unsigned)buf_size, + &msg->hdr, &printed); + } else { + /* This may be a generic attribute */ + const pj_stun_binary_attr *bin_attr = (const pj_stun_binary_attr*) + attr_hdr; + PJ_ASSERT_RETURN(bin_attr->magic == PJ_STUN_MAGIC, PJ_EBUG); + status = encode_binary_attr(bin_attr, buf, (unsigned)buf_size, + &msg->hdr, &printed); + } + + if (status != PJ_SUCCESS) + return status; + + buf += printed; + buf_size -= printed; } /* We may have stopped printing attribute because we found @@ -2656,20 +2655,20 @@ PJ_DEF(pj_status_t) pj_stun_msg_encode(pj_stun_msg *msg, * attributes. */ for ( ++i; iattr_count; ++i) { - const pj_stun_attr_hdr *attr_hdr = msg->attr[i]; + const pj_stun_attr_hdr *attr_hdr = msg->attr[i]; - /* There mustn't any attribute after FINGERPRINT */ - PJ_ASSERT_RETURN(afingerprint == NULL, PJNATH_ESTUNFINGERPOS); + /* There mustn't any attribute after FINGERPRINT */ + PJ_ASSERT_RETURN(afingerprint == NULL, PJNATH_ESTUNFINGERPOS); - if (attr_hdr->type == PJ_STUN_ATTR_MESSAGE_INTEGRITY) { - /* There mustn't be MESSAGE-INTEGRITY before */ - PJ_ASSERT_RETURN(amsgint == NULL, - PJNATH_ESTUNMSGINTPOS); - amsgint = (pj_stun_msgint_attr*) attr_hdr; + if (attr_hdr->type == PJ_STUN_ATTR_MESSAGE_INTEGRITY) { + /* There mustn't be MESSAGE-INTEGRITY before */ + PJ_ASSERT_RETURN(amsgint == NULL, + PJNATH_ESTUNMSGINTPOS); + amsgint = (pj_stun_msgint_attr*) attr_hdr; - } else if (attr_hdr->type == PJ_STUN_ATTR_FINGERPRINT) { - afingerprint = (pj_stun_fingerprint_attr*) attr_hdr; - } + } else if (attr_hdr->type == PJ_STUN_ATTR_FINGERPRINT) { + afingerprint = (pj_stun_fingerprint_attr*) attr_hdr; + } } #if PJ_STUN_OLD_STYLE_MI_FINGERPRINT @@ -2682,100 +2681,100 @@ PJ_DEF(pj_status_t) pj_stun_msg_encode(pj_stun_msg *msg, * Note that length is not including the 20 bytes header. */ if (amsgint && afingerprint) { - body_len = (pj_uint16_t)((buf - start) - 20 + 24 + 8); + body_len = (pj_uint16_t)((buf - start) - 20 + 24 + 8); } else if (amsgint) { - body_len = (pj_uint16_t)((buf - start) - 20 + 24); + body_len = (pj_uint16_t)((buf - start) - 20 + 24); } else if (afingerprint) { - body_len = (pj_uint16_t)((buf - start) - 20 + 8); + body_len = (pj_uint16_t)((buf - start) - 20 + 8); } else { - body_len = (pj_uint16_t)((buf - start) - 20); + body_len = (pj_uint16_t)((buf - start) - 20); } #else /* If MESSAGE-INTEGRITY is present, include the M-I attribute * in message length before calculating M-I */ if (amsgint) { - body_len = (pj_uint16_t)((buf - start) - 20 + 24); + body_len = (pj_uint16_t)((buf - start) - 20 + 24); } else { - body_len = (pj_uint16_t)((buf - start) - 20); + body_len = (pj_uint16_t)((buf - start) - 20); } -#endif /* PJ_STUN_OLD_STYLE_MI_FINGERPRINT */ +#endif /* PJ_STUN_OLD_STYLE_MI_FINGERPRINT */ /* hdr->length = pj_htons(length); */ PUTVAL16H(start, 2, (pj_uint16_t)body_len); /* Calculate message integrity, if present */ if (amsgint != NULL) { - pj_hmac_sha1_context ctx; - - /* Key MUST be specified */ - PJ_ASSERT_RETURN(key, PJ_EINVALIDOP); - - /* MESSAGE-INTEGRITY must be the last attribute in the message, or - * the last attribute before FINGERPRINT. - */ - if (msg->attr_count>1 && i < msg->attr_count-2) { - /* Should not happen for message generated by us */ - pj_assert(PJ_FALSE); - return PJNATH_ESTUNMSGINTPOS; - - } else if (i == msg->attr_count-2) { - if (msg->attr[i+1]->type != PJ_STUN_ATTR_FINGERPRINT) { - /* Should not happen for message generated by us */ - pj_assert(PJ_FALSE); - return PJNATH_ESTUNMSGINTPOS; - } else { - afingerprint = (pj_stun_fingerprint_attr*) msg->attr[i+1]; - } - } - - /* Calculate HMAC-SHA1 digest, add zero padding to input - * if necessary to make the input 64 bytes aligned. - */ - pj_hmac_sha1_init(&ctx, (const pj_uint8_t*)key->ptr, - (unsigned)key->slen); - pj_hmac_sha1_update(&ctx, (const pj_uint8_t*)start, - (unsigned)(buf-start)); + pj_hmac_sha1_context ctx; + + /* Key MUST be specified */ + PJ_ASSERT_RETURN(key, PJ_EINVALIDOP); + + /* MESSAGE-INTEGRITY must be the last attribute in the message, or + * the last attribute before FINGERPRINT. + */ + if (msg->attr_count>1 && i < msg->attr_count-2) { + /* Should not happen for message generated by us */ + pj_assert(PJ_FALSE); + return PJNATH_ESTUNMSGINTPOS; + + } else if (i == msg->attr_count-2) { + if (msg->attr[i+1]->type != PJ_STUN_ATTR_FINGERPRINT) { + /* Should not happen for message generated by us */ + pj_assert(PJ_FALSE); + return PJNATH_ESTUNMSGINTPOS; + } else { + afingerprint = (pj_stun_fingerprint_attr*) msg->attr[i+1]; + } + } + + /* Calculate HMAC-SHA1 digest, add zero padding to input + * if necessary to make the input 64 bytes aligned. + */ + pj_hmac_sha1_init(&ctx, (const pj_uint8_t*)key->ptr, + (unsigned)key->slen); + pj_hmac_sha1_update(&ctx, (const pj_uint8_t*)start, + (unsigned)(buf-start)); #if PJ_STUN_OLD_STYLE_MI_FINGERPRINT - // These are obsoleted in rfc3489bis-08 - if ((buf-start) & 0x3F) { - pj_uint8_t zeroes[64]; - pj_bzero(zeroes, sizeof(zeroes)); - pj_hmac_sha1_update(&ctx, zeroes, 64-((buf-start) & 0x3F)); - } -#endif /* PJ_STUN_OLD_STYLE_MI_FINGERPRINT */ - pj_hmac_sha1_final(&ctx, amsgint->hmac); - - /* Put this attribute in the message */ - status = encode_msgint_attr(amsgint, buf, (unsigned)buf_size, - &msg->hdr, &printed); - if (status != PJ_SUCCESS) - return status; - - buf += printed; - buf_size -= printed; + // These are obsoleted in rfc3489bis-08 + if ((buf-start) & 0x3F) { + pj_uint8_t zeroes[64]; + pj_bzero(zeroes, sizeof(zeroes)); + pj_hmac_sha1_update(&ctx, zeroes, 64-((buf-start) & 0x3F)); + } +#endif /* PJ_STUN_OLD_STYLE_MI_FINGERPRINT */ + pj_hmac_sha1_final(&ctx, amsgint->hmac); + + /* Put this attribute in the message */ + status = encode_msgint_attr(amsgint, buf, (unsigned)buf_size, + &msg->hdr, &printed); + if (status != PJ_SUCCESS) + return status; + + buf += printed; + buf_size -= printed; } /* Calculate FINGERPRINT if present */ if (afingerprint != NULL) { #if !PJ_STUN_OLD_STYLE_MI_FINGERPRINT - /* Update message length */ - PUTVAL16H(start, 2, - (pj_uint16_t)(GETVAL16H(start, 2)+8)); + /* Update message length */ + PUTVAL16H(start, 2, + (pj_uint16_t)(GETVAL16H(start, 2)+8)); #endif - afingerprint->value = pj_crc32_calc(start, buf-start); - afingerprint->value ^= STUN_XOR_FINGERPRINT; + afingerprint->value = pj_crc32_calc(start, buf-start); + afingerprint->value ^= STUN_XOR_FINGERPRINT; - /* Put this attribute in the message */ - status = encode_uint_attr(afingerprint, buf, (unsigned)buf_size, - &msg->hdr, &printed); - if (status != PJ_SUCCESS) - return status; + /* Put this attribute in the message */ + status = encode_uint_attr(afingerprint, buf, (unsigned)buf_size, + &msg->hdr, &printed); + if (status != PJ_SUCCESS) + return status; - buf += printed; - buf_size -= printed; + buf += printed; + buf_size -= printed; } /* Update message length. */ @@ -2783,7 +2782,7 @@ PJ_DEF(pj_status_t) pj_stun_msg_encode(pj_stun_msg *msg, /* Return the length */ if (p_msg_len) - *p_msg_len = (buf - start); + *p_msg_len = (buf - start); return PJ_SUCCESS; } @@ -2794,14 +2793,14 @@ PJ_DEF(pj_status_t) pj_stun_msg_encode(pj_stun_msg *msg, * index. */ PJ_DEF(pj_stun_attr_hdr*) pj_stun_msg_find_attr( const pj_stun_msg *msg, - int attr_type, - unsigned index) + int attr_type, + unsigned index) { PJ_ASSERT_RETURN(msg, NULL); for (; index < msg->attr_count; ++index) { - if (msg->attr[index]->type == attr_type) - return (pj_stun_attr_hdr*) msg->attr[index]; + if (msg->attr[index]->type == attr_type) + return (pj_stun_attr_hdr*) msg->attr[index]; } return NULL; @@ -2812,24 +2811,24 @@ PJ_DEF(pj_stun_attr_hdr*) pj_stun_msg_find_attr( const pj_stun_msg *msg, * Clone a STUN attribute. */ PJ_DEF(pj_stun_attr_hdr*) pj_stun_attr_clone( pj_pool_t *pool, - const pj_stun_attr_hdr *attr) + const pj_stun_attr_hdr *attr) { const struct attr_desc *adesc; /* Get the attribute descriptor */ adesc = find_attr_desc(attr->type); if (adesc) { - return (pj_stun_attr_hdr*) (*adesc->clone_attr)(pool, attr); + return (pj_stun_attr_hdr*) (*adesc->clone_attr)(pool, attr); } else { - /* Clone generic attribute */ - const pj_stun_binary_attr *bin_attr = (const pj_stun_binary_attr*) - attr; - PJ_ASSERT_RETURN(bin_attr->magic == PJ_STUN_MAGIC, NULL); - if (bin_attr->magic == PJ_STUN_MAGIC) { - return (pj_stun_attr_hdr*) clone_binary_attr(pool, attr); - } else { - return NULL; - } + /* Clone generic attribute */ + const pj_stun_binary_attr *bin_attr = (const pj_stun_binary_attr*) + attr; + PJ_ASSERT_RETURN(bin_attr->magic == PJ_STUN_MAGIC, NULL); + if (bin_attr->magic == PJ_STUN_MAGIC) { + return (pj_stun_attr_hdr*) clone_binary_attr(pool, attr); + } else { + return NULL; + } } } diff --git a/pjnath/src/pjnath/stun_msg_dump.c b/pjnath/src/pjnath/stun_msg_dump.c index 91d41c7ac8..8f2a054130 100644 --- a/pjnath/src/pjnath/stun_msg_dump.c +++ b/pjnath/src/pjnath/stun_msg_dump.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -26,25 +25,25 @@ #if PJ_LOG_MAX_LEVEL > 0 -#define APPLY() if (len < 1 || len >= (end-p)) \ - goto on_return; \ - p += len +#define APPLY() if (len < 1 || len >= (end-p)) \ + goto on_return; \ + p += len static int print_binary(char *buffer, unsigned length, - const pj_uint8_t *data, unsigned data_len) + const pj_uint8_t *data, unsigned data_len) { unsigned i; if (length < data_len * 2 + 8) - return -1; + return -1; pj_ansi_sprintf(buffer, ", data="); buffer += 7; for (i=0; itype); @@ -62,15 +61,15 @@ static int print_attr(char *buffer, unsigned length, int len; if (*attr_name == '?') { - pj_ansi_snprintf(attr_buf, sizeof(attr_buf), "Attr 0x%x", - ahdr->type); - attr_name = attr_buf; + pj_ansi_snprintf(attr_buf, sizeof(attr_buf), "Attr 0x%x", + ahdr->type); + attr_name = attr_buf; } len = pj_ansi_snprintf(p, end-p, - " %s: length=%d", - attr_name, - (int)ahdr->length); + " %s: length=%d", + attr_name, + (int)ahdr->length); APPLY(); @@ -85,40 +84,40 @@ static int print_attr(char *buffer, unsigned length, case PJ_STUN_ATTR_XOR_MAPPED_ADDR: case PJ_STUN_ATTR_XOR_REFLECTED_FROM: case PJ_STUN_ATTR_ALTERNATE_SERVER: - { - char addr[PJ_INET6_ADDRSTRLEN]; - const pj_stun_sockaddr_attr *attr; - pj_uint16_t af; - - attr = (const pj_stun_sockaddr_attr*)ahdr; - af = attr->sockaddr.addr.sa_family; - - if ((af == pj_AF_INET()) || (af == pj_AF_INET6())) { - len = pj_ansi_snprintf(p, end-p, - ", %s addr=%s\n", - (af == pj_AF_INET())?"IPv4":"IPv6", - pj_sockaddr_print(&attr->sockaddr, - addr, sizeof(addr),3)); - } else { - len = pj_ansi_snprintf(p, end-p, - ", INVALID ADDRESS FAMILY!\n"); - } - APPLY(); - } - break; + { + char addr[PJ_INET6_ADDRSTRLEN]; + const pj_stun_sockaddr_attr *attr; + pj_uint16_t af; + + attr = (const pj_stun_sockaddr_attr*)ahdr; + af = attr->sockaddr.addr.sa_family; + + if ((af == pj_AF_INET()) || (af == pj_AF_INET6())) { + len = pj_ansi_snprintf(p, end-p, + ", %s addr=%s\n", + (af == pj_AF_INET())?"IPv4":"IPv6", + pj_sockaddr_print(&attr->sockaddr, + addr, sizeof(addr),3)); + } else { + len = pj_ansi_snprintf(p, end-p, + ", INVALID ADDRESS FAMILY!\n"); + } + APPLY(); + } + break; case PJ_STUN_ATTR_CHANNEL_NUMBER: - { - const pj_stun_uint_attr *attr; - - attr = (const pj_stun_uint_attr*)ahdr; - len = pj_ansi_snprintf(p, end-p, - ", chnum=%u (0x%x)\n", - (int)PJ_STUN_GET_CH_NB(attr->value), - (int)PJ_STUN_GET_CH_NB(attr->value)); - APPLY(); - } - break; + { + const pj_stun_uint_attr *attr; + + attr = (const pj_stun_uint_attr*)ahdr; + len = pj_ansi_snprintf(p, end-p, + ", chnum=%u (0x%x)\n", + (int)PJ_STUN_GET_CH_NB(attr->value), + (int)PJ_STUN_GET_CH_NB(attr->value)); + APPLY(); + } + break; case PJ_STUN_ATTR_CHANGE_REQUEST: case PJ_STUN_ATTR_LIFETIME: @@ -131,111 +130,111 @@ static int print_attr(char *buffer, unsigned length, case PJ_STUN_ATTR_FINGERPRINT: case PJ_STUN_ATTR_REFRESH_INTERVAL: case PJ_STUN_ATTR_ICMP: - { - const pj_stun_uint_attr *attr; - - attr = (const pj_stun_uint_attr*)ahdr; - len = pj_ansi_snprintf(p, end-p, - ", value=%u (0x%x)\n", - (pj_uint32_t)attr->value, - (pj_uint32_t)attr->value); - APPLY(); - } - break; + { + const pj_stun_uint_attr *attr; + + attr = (const pj_stun_uint_attr*)ahdr; + len = pj_ansi_snprintf(p, end-p, + ", value=%u (0x%x)\n", + (pj_uint32_t)attr->value, + (pj_uint32_t)attr->value); + APPLY(); + } + break; case PJ_STUN_ATTR_USERNAME: case PJ_STUN_ATTR_PASSWORD: case PJ_STUN_ATTR_REALM: case PJ_STUN_ATTR_NONCE: case PJ_STUN_ATTR_SOFTWARE: - { - const pj_stun_string_attr *attr; - - attr = (pj_stun_string_attr*)ahdr; - len = pj_ansi_snprintf(p, end-p, - ", value=\"%.*s\"\n", - (int)attr->value.slen, - attr->value.ptr); - APPLY(); - } - break; + { + const pj_stun_string_attr *attr; + + attr = (pj_stun_string_attr*)ahdr; + len = pj_ansi_snprintf(p, end-p, + ", value=\"%.*s\"\n", + (int)attr->value.slen, + attr->value.ptr); + APPLY(); + } + break; case PJ_STUN_ATTR_ERROR_CODE: - { - const pj_stun_errcode_attr *attr; - - attr = (const pj_stun_errcode_attr*) ahdr; - len = pj_ansi_snprintf(p, end-p, - ", err_code=%d, reason=\"%.*s\"\n", - attr->err_code, - (int)attr->reason.slen, - attr->reason.ptr); - APPLY(); - } - break; + { + const pj_stun_errcode_attr *attr; + + attr = (const pj_stun_errcode_attr*) ahdr; + len = pj_ansi_snprintf(p, end-p, + ", err_code=%d, reason=\"%.*s\"\n", + attr->err_code, + (int)attr->reason.slen, + attr->reason.ptr); + APPLY(); + } + break; case PJ_STUN_ATTR_UNKNOWN_ATTRIBUTES: - { - const pj_stun_unknown_attr *attr; - unsigned j; + { + const pj_stun_unknown_attr *attr; + unsigned j; - attr = (const pj_stun_unknown_attr*) ahdr; + attr = (const pj_stun_unknown_attr*) ahdr; - len = pj_ansi_snprintf(p, end-p, - ", unknown list:"); - APPLY(); + len = pj_ansi_snprintf(p, end-p, + ", unknown list:"); + APPLY(); - for (j=0; jattr_count; ++j) { - len = pj_ansi_snprintf(p, end-p, - " %d", - (int)attr->attrs[j]); - APPLY(); - } - } - break; + for (j=0; jattr_count; ++j) { + len = pj_ansi_snprintf(p, end-p, + " %d", + (int)attr->attrs[j]); + APPLY(); + } + } + break; case PJ_STUN_ATTR_MESSAGE_INTEGRITY: - { - const pj_stun_msgint_attr *attr; + { + const pj_stun_msgint_attr *attr; - attr = (const pj_stun_msgint_attr*) ahdr; - len = print_binary(p, (unsigned)(end-p), attr->hmac, 20); - APPLY(); - } - break; + attr = (const pj_stun_msgint_attr*) ahdr; + len = print_binary(p, (unsigned)(end-p), attr->hmac, 20); + APPLY(); + } + break; case PJ_STUN_ATTR_DATA: - { - const pj_stun_binary_attr *attr; - - attr = (const pj_stun_binary_attr*) ahdr; - len = print_binary(p, (unsigned)(end-p), attr->data, attr->length); - APPLY(); - } - break; + { + const pj_stun_binary_attr *attr; + + attr = (const pj_stun_binary_attr*) ahdr; + len = print_binary(p, (unsigned)(end-p), attr->data, attr->length); + APPLY(); + } + break; case PJ_STUN_ATTR_ICE_CONTROLLED: case PJ_STUN_ATTR_ICE_CONTROLLING: case PJ_STUN_ATTR_RESERVATION_TOKEN: - { - const pj_stun_uint64_attr *attr; - pj_uint8_t data[8]; - int i; + { + const pj_stun_uint64_attr *attr; + pj_uint8_t data[8]; + int i; - attr = (const pj_stun_uint64_attr*) ahdr; + attr = (const pj_stun_uint64_attr*) ahdr; - for (i=0; i<8; ++i) - data[i] = ((const pj_uint8_t*)&attr->value)[7-i]; + for (i=0; i<8; ++i) + data[i] = ((const pj_uint8_t*)&attr->value)[7-i]; - len = print_binary(p, (unsigned)(end-p), data, 8); - APPLY(); - } - break; + len = print_binary(p, (unsigned)(end-p), data, 8); + APPLY(); + } + break; case PJ_STUN_ATTR_USE_CANDIDATE: case PJ_STUN_ATTR_DONT_FRAGMENT: default: - len = pj_ansi_snprintf(p, end-p, "\n"); - APPLY(); - break; + len = pj_ansi_snprintf(p, end-p, "\n"); + APPLY(); + break; } return (int)(p-buffer); @@ -249,9 +248,9 @@ static int print_attr(char *buffer, unsigned length, * Dump STUN message to a printable string output. */ PJ_DEF(char*) pj_stun_msg_dump(const pj_stun_msg *msg, - char *buffer, - unsigned length, - unsigned *printed_len) + char *buffer, + unsigned length, + unsigned *printed_len) { char *p, *end; int len; @@ -266,35 +265,35 @@ PJ_DEF(char*) pj_stun_msg_dump(const pj_stun_msg *msg, end = buffer + length; len = pj_ansi_snprintf(p, end-p, "STUN %s %s\n", - pj_stun_get_method_name(msg->hdr.type), - pj_stun_get_class_name(msg->hdr.type)); + pj_stun_get_method_name(msg->hdr.type), + pj_stun_get_class_name(msg->hdr.type)); APPLY(); pj_memcpy(tsx_id, msg->hdr.tsx_id, sizeof(msg->hdr.tsx_id)); len = pj_ansi_snprintf(p, end-p, - " Hdr: length=%d, magic=%08x, tsx_id=%08x%08x%08x\n" - " Attributes:\n", - msg->hdr.length, - msg->hdr.magic, - tsx_id[0], - tsx_id[1], - tsx_id[2]); + " Hdr: length=%d, magic=%08x, tsx_id=%08x%08x%08x\n" + " Attributes:\n", + msg->hdr.length, + msg->hdr.magic, + tsx_id[0], + tsx_id[1], + tsx_id[2]); APPLY(); for (i=0; iattr_count; ++i) { - len = print_attr(p, (unsigned)(end-p), msg->attr[i]); - APPLY(); + len = print_attr(p, (unsigned)(end-p), msg->attr[i]); + APPLY(); } on_return: *p = '\0'; if (printed_len) - *printed_len = (unsigned)(p-buffer); + *printed_len = (unsigned)(p-buffer); return buffer; #undef APPLY } -#endif /* PJ_LOG_MAX_LEVEL > 0 */ +#endif /* PJ_LOG_MAX_LEVEL > 0 */ diff --git a/pjnath/src/pjnath/stun_session.c b/pjnath/src/pjnath/stun_session.c index c87f6e643c..94ab225182 100644 --- a/pjnath/src/pjnath/stun_session.c +++ b/pjnath/src/pjnath/stun_session.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -23,57 +22,57 @@ struct pj_stun_session { - pj_stun_config *cfg; - pj_pool_t *pool; - pj_grp_lock_t *grp_lock; - pj_stun_session_cb cb; - void *user_data; - pj_bool_t is_destroying; + pj_stun_config *cfg; + pj_pool_t *pool; + pj_grp_lock_t *grp_lock; + pj_stun_session_cb cb; + void *user_data; + pj_bool_t is_destroying; - pj_bool_t use_fingerprint; + pj_bool_t use_fingerprint; - pj_pool_t *rx_pool; + pj_pool_t *rx_pool; #if PJ_LOG_MAX_LEVEL >= 5 - char dump_buf[1000]; + char dump_buf[1000]; #endif - unsigned log_flag; + unsigned log_flag; - pj_stun_auth_type auth_type; - pj_stun_auth_cred cred; - int auth_retry; - pj_str_t next_nonce; - pj_str_t server_realm; + pj_stun_auth_type auth_type; + pj_stun_auth_cred cred; + int auth_retry; + pj_str_t next_nonce; + pj_str_t server_realm; - pj_str_t srv_name; + pj_str_t srv_name; - pj_stun_tx_data pending_request_list; - pj_stun_tx_data cached_response_list; + pj_stun_tx_data pending_request_list; + pj_stun_tx_data cached_response_list; }; -#define SNAME(s_) ((s_)->pool->obj_name) -#define THIS_FILE "stun_session.c" +#define SNAME(s_) ((s_)->pool->obj_name) +#define THIS_FILE "stun_session.c" #if 1 -# define TRACE_(expr) PJ_LOG(5,expr) +# define TRACE_(expr) PJ_LOG(5,expr) #else # define TRACE_(expr) #endif #define LOG_ERR_(sess,title,rc) PJ_PERROR(3,(sess->pool->obj_name,rc,title)) -#define TDATA_POOL_SIZE PJNATH_POOL_LEN_STUN_TDATA -#define TDATA_POOL_INC PJNATH_POOL_INC_STUN_TDATA +#define TDATA_POOL_SIZE PJNATH_POOL_LEN_STUN_TDATA +#define TDATA_POOL_INC PJNATH_POOL_INC_STUN_TDATA static void stun_tsx_on_complete(pj_stun_client_tsx *tsx, - pj_status_t status, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + pj_status_t status, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); static pj_status_t stun_tsx_on_send_msg(pj_stun_client_tsx *tsx, - const void *stun_pkt, - pj_size_t pkt_size); + const void *stun_pkt, + pj_size_t pkt_size); static void stun_tsx_on_destroy(pj_stun_client_tsx *tsx); static void stun_sess_on_destroy(void *comp); static void destroy_tdata(pj_stun_tx_data *tdata, pj_bool_t force); @@ -87,14 +86,14 @@ static pj_stun_tsx_cb tsx_cb = static pj_status_t tsx_add(pj_stun_session *sess, - pj_stun_tx_data *tdata) + pj_stun_tx_data *tdata) { pj_list_push_front(&sess->pending_request_list, tdata); return PJ_SUCCESS; } static pj_status_t tsx_erase(pj_stun_session *sess, - pj_stun_tx_data *tdata) + pj_stun_tx_data *tdata) { PJ_UNUSED_ARG(sess); pj_list_erase(tdata); @@ -102,34 +101,34 @@ static pj_status_t tsx_erase(pj_stun_session *sess, } static pj_stun_tx_data* tsx_lookup(pj_stun_session *sess, - const pj_stun_msg *msg) + const pj_stun_msg *msg) { pj_stun_tx_data *tdata; tdata = sess->pending_request_list.next; while (tdata != &sess->pending_request_list) { - pj_assert(sizeof(tdata->msg_key)==sizeof(msg->hdr.tsx_id)); - if (tdata->msg_magic == msg->hdr.magic && - pj_memcmp(tdata->msg_key, msg->hdr.tsx_id, - sizeof(msg->hdr.tsx_id))==0) - { - return tdata; - } - tdata = tdata->next; + pj_assert(sizeof(tdata->msg_key)==sizeof(msg->hdr.tsx_id)); + if (tdata->msg_magic == msg->hdr.magic && + pj_memcmp(tdata->msg_key, msg->hdr.tsx_id, + sizeof(msg->hdr.tsx_id))==0) + { + return tdata; + } + tdata = tdata->next; } return NULL; } static pj_status_t create_tdata(pj_stun_session *sess, - pj_stun_tx_data **p_tdata) + pj_stun_tx_data **p_tdata) { pj_pool_t *pool; pj_stun_tx_data *tdata; /* Create pool and initialize basic tdata attributes */ pool = pj_pool_create(sess->cfg->pf, "tdata%p", - TDATA_POOL_SIZE, TDATA_POOL_INC, NULL); + TDATA_POOL_SIZE, TDATA_POOL_INC, NULL); PJ_ASSERT_RETURN(pool, PJ_ENOMEM); tdata = PJ_POOL_ZALLOC_T(pool, pj_stun_tx_data); @@ -153,9 +152,9 @@ static void stun_tsx_on_destroy(pj_stun_client_tsx *tsx) pj_stun_session *sess = tdata->sess; pj_grp_lock_acquire(sess->grp_lock); - tsx_erase(sess, tdata); - destroy_tdata(tdata, PJ_TRUE); - pj_grp_lock_release(sess->grp_lock); + tsx_erase(sess, tdata); + destroy_tdata(tdata, PJ_TRUE); + pj_grp_lock_release(sess->grp_lock); } pj_stun_client_tsx_destroy(tsx); @@ -168,7 +167,7 @@ static void tdata_on_destroy(void *arg) pj_stun_tx_data *tdata = (pj_stun_tx_data*)arg; if (tdata->grp_lock) { - pj_grp_lock_dec_ref(tdata->sess->grp_lock); + pj_grp_lock_dec_ref(tdata->sess->grp_lock); } pj_pool_safe_release(&tdata->pool); @@ -177,49 +176,49 @@ static void tdata_on_destroy(void *arg) static void destroy_tdata(pj_stun_tx_data *tdata, pj_bool_t force) { TRACE_((THIS_FILE, - "tdata %p destroy request, force=%d, tsx=%p, destroying=%d", - tdata, force, tdata->client_tsx, tdata->is_destroying)); + "tdata %p destroy request, force=%d, tsx=%p, destroying=%d", + tdata, force, tdata->client_tsx, tdata->is_destroying)); /* Just return if destroy has been requested before */ if (tdata->is_destroying) - return; + return; /* STUN session may have been destroyed, except when tdata is cached. */ tdata->is_destroying = PJ_TRUE; if (tdata->res_timer.id != PJ_FALSE) { - pj_timer_heap_cancel_if_active(tdata->sess->cfg->timer_heap, - &tdata->res_timer, PJ_FALSE); + pj_timer_heap_cancel_if_active(tdata->sess->cfg->timer_heap, + &tdata->res_timer, PJ_FALSE); } if (force) { - pj_list_erase(tdata); - if (tdata->client_tsx) { - pj_stun_client_tsx_stop(tdata->client_tsx); - pj_stun_client_tsx_set_data(tdata->client_tsx, NULL); - } - if (tdata->grp_lock) { - pj_grp_lock_dec_ref(tdata->grp_lock); - } else { - tdata_on_destroy(tdata); - } + pj_list_erase(tdata); + if (tdata->client_tsx) { + pj_stun_client_tsx_stop(tdata->client_tsx); + pj_stun_client_tsx_set_data(tdata->client_tsx, NULL); + } + if (tdata->grp_lock) { + pj_grp_lock_dec_ref(tdata->grp_lock); + } else { + tdata_on_destroy(tdata); + } } else { - if (tdata->client_tsx) { - /* "Probably" this is to absorb retransmission */ - pj_time_val delay = {0, 300}; - pj_stun_client_tsx_schedule_destroy(tdata->client_tsx, &delay); - tdata->is_destroying = PJ_FALSE; - - } else { - pj_list_erase(tdata); - if (tdata->grp_lock) { - pj_grp_lock_dec_ref(tdata->grp_lock); - } else { - tdata_on_destroy(tdata); - } - } + if (tdata->client_tsx) { + /* "Probably" this is to absorb retransmission */ + pj_time_val delay = {0, 300}; + pj_stun_client_tsx_schedule_destroy(tdata->client_tsx, &delay); + tdata->is_destroying = PJ_FALSE; + + } else { + pj_list_erase(tdata); + if (tdata->grp_lock) { + pj_grp_lock_dec_ref(tdata->grp_lock); + } else { + tdata_on_destroy(tdata); + } + } } } @@ -227,7 +226,7 @@ static void destroy_tdata(pj_stun_tx_data *tdata, pj_bool_t force) * Destroy the transmit data. */ PJ_DEF(void) pj_stun_msg_destroy_tdata( pj_stun_session *sess, - pj_stun_tx_data *tdata) + pj_stun_tx_data *tdata) { PJ_UNUSED_ARG(sess); destroy_tdata(tdata, PJ_FALSE); @@ -236,7 +235,7 @@ PJ_DEF(void) pj_stun_msg_destroy_tdata( pj_stun_session *sess, /* Timer callback to be called when it's time to destroy response cache */ static void on_cache_timeout(pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { pj_stun_tx_data *tdata; pj_stun_session *sess; @@ -249,8 +248,8 @@ static void on_cache_timeout(pj_timer_heap_t *timer_heap, pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying || tdata->is_destroying) { - pj_grp_lock_release(sess->grp_lock); - return; + pj_grp_lock_release(sess->grp_lock); + return; } PJ_LOG(5,(SNAME(tdata->sess), "Response cache deleted")); @@ -261,9 +260,9 @@ static void on_cache_timeout(pj_timer_heap_t *timer_heap, } static pj_status_t apply_msg_options(pj_stun_session *sess, - pj_pool_t *pool, - const pj_stun_req_cred_info *auth_info, - pj_stun_msg *msg) + pj_pool_t *pool, + const pj_stun_req_cred_info *auth_info, + pj_stun_msg *msg) { pj_status_t status = 0; pj_str_t realm, username, nonce, auth_key; @@ -276,191 +275,191 @@ static pj_status_t apply_msg_options(pj_stun_session *sess, * responses. */ if (sess->srv_name.slen && - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_SOFTWARE, 0)==NULL && - (PJ_STUN_IS_RESPONSE(msg->hdr.type) || - (PJ_STUN_IS_REQUEST(msg->hdr.type) && msg->hdr.magic==PJ_STUN_MAGIC))) + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_SOFTWARE, 0)==NULL && + (PJ_STUN_IS_RESPONSE(msg->hdr.type) || + (PJ_STUN_IS_REQUEST(msg->hdr.type) && msg->hdr.magic==PJ_STUN_MAGIC))) { - pj_stun_msg_add_string_attr(pool, msg, PJ_STUN_ATTR_SOFTWARE, - &sess->srv_name); + pj_stun_msg_add_string_attr(pool, msg, PJ_STUN_ATTR_SOFTWARE, + &sess->srv_name); } if (pj_stun_auth_valid_for_msg(msg) && auth_info) { - realm = auth_info->realm; - username = auth_info->username; - nonce = auth_info->nonce; - auth_key = auth_info->auth_key; + realm = auth_info->realm; + username = auth_info->username; + nonce = auth_info->nonce; + auth_key = auth_info->auth_key; } else { - realm.slen = username.slen = nonce.slen = auth_key.slen = 0; + realm.slen = username.slen = nonce.slen = auth_key.slen = 0; } /* Create and add USERNAME attribute if needed */ if (username.slen && PJ_STUN_IS_REQUEST(msg->hdr.type)) { - status = pj_stun_msg_add_string_attr(pool, msg, - PJ_STUN_ATTR_USERNAME, - &username); - PJ_ASSERT_RETURN(status==PJ_SUCCESS, status); + status = pj_stun_msg_add_string_attr(pool, msg, + PJ_STUN_ATTR_USERNAME, + &username); + PJ_ASSERT_RETURN(status==PJ_SUCCESS, status); } /* Add REALM only when long term credential is used */ if (realm.slen && PJ_STUN_IS_REQUEST(msg->hdr.type)) { - status = pj_stun_msg_add_string_attr(pool, msg, - PJ_STUN_ATTR_REALM, - &realm); - PJ_ASSERT_RETURN(status==PJ_SUCCESS, status); + status = pj_stun_msg_add_string_attr(pool, msg, + PJ_STUN_ATTR_REALM, + &realm); + PJ_ASSERT_RETURN(status==PJ_SUCCESS, status); } /* Add NONCE when desired */ if (nonce.slen && - (PJ_STUN_IS_REQUEST(msg->hdr.type) || - PJ_STUN_IS_ERROR_RESPONSE(msg->hdr.type))) + (PJ_STUN_IS_REQUEST(msg->hdr.type) || + PJ_STUN_IS_ERROR_RESPONSE(msg->hdr.type))) { - status = pj_stun_msg_add_string_attr(pool, msg, - PJ_STUN_ATTR_NONCE, - &nonce); + status = pj_stun_msg_add_string_attr(pool, msg, + PJ_STUN_ATTR_NONCE, + &nonce); } /* Add MESSAGE-INTEGRITY attribute */ if (username.slen && auth_key.slen) { - status = pj_stun_msg_add_msgint_attr(pool, msg); - PJ_ASSERT_RETURN(status==PJ_SUCCESS, status); + status = pj_stun_msg_add_msgint_attr(pool, msg); + PJ_ASSERT_RETURN(status==PJ_SUCCESS, status); } /* Add FINGERPRINT attribute if necessary */ if (sess->use_fingerprint) { - status = pj_stun_msg_add_uint_attr(pool, msg, - PJ_STUN_ATTR_FINGERPRINT, 0); - PJ_ASSERT_RETURN(status==PJ_SUCCESS, status); + status = pj_stun_msg_add_uint_attr(pool, msg, + PJ_STUN_ATTR_FINGERPRINT, 0); + PJ_ASSERT_RETURN(status==PJ_SUCCESS, status); } return PJ_SUCCESS; } static pj_status_t handle_auth_challenge(pj_stun_session *sess, - const pj_stun_tx_data *request, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len, - pj_bool_t *notify_user) + const pj_stun_tx_data *request, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len, + pj_bool_t *notify_user) { const pj_stun_errcode_attr *ea; *notify_user = PJ_TRUE; if (response==NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; if (sess->auth_type != PJ_STUN_AUTH_LONG_TERM) - return PJ_SUCCESS; + return PJ_SUCCESS; if (!PJ_STUN_IS_ERROR_RESPONSE(response->hdr.type)) { - sess->auth_retry = 0; - return PJ_SUCCESS; + sess->auth_retry = 0; + return PJ_SUCCESS; } ea = (const pj_stun_errcode_attr*) - pj_stun_msg_find_attr(response, PJ_STUN_ATTR_ERROR_CODE, 0); + pj_stun_msg_find_attr(response, PJ_STUN_ATTR_ERROR_CODE, 0); if (!ea) { - PJ_LOG(4,(SNAME(sess), "Invalid error response: no ERROR-CODE" - " attribute")); - *notify_user = PJ_FALSE; - return PJNATH_EINSTUNMSG; + PJ_LOG(4,(SNAME(sess), "Invalid error response: no ERROR-CODE" + " attribute")); + *notify_user = PJ_FALSE; + return PJNATH_EINSTUNMSG; } if (ea->err_code == PJ_STUN_SC_UNAUTHORIZED || - ea->err_code == PJ_STUN_SC_STALE_NONCE) + ea->err_code == PJ_STUN_SC_STALE_NONCE) { - const pj_stun_nonce_attr *anonce; - const pj_stun_realm_attr *arealm; - pj_stun_tx_data *tdata; - unsigned i; - pj_status_t status; - - anonce = (const pj_stun_nonce_attr*) - pj_stun_msg_find_attr(response, PJ_STUN_ATTR_NONCE, 0); - if (!anonce) { - PJ_LOG(4,(SNAME(sess), "Invalid response: missing NONCE")); - *notify_user = PJ_FALSE; - return PJNATH_EINSTUNMSG; - } - - /* Bail out if we've supplied the correct nonce */ - if (pj_strcmp(&anonce->value, &sess->next_nonce)==0) { - return PJ_SUCCESS; - } - - /* Bail out if we've tried too many */ - if (++sess->auth_retry > 3) { - PJ_LOG(4,(SNAME(sess), "Error: authentication failed (too " - "many retries)")); - return PJ_STATUS_FROM_STUN_CODE(401); - } - - /* Save next_nonce */ - pj_strdup(sess->pool, &sess->next_nonce, &anonce->value); - - /* Copy the realm from the response */ - arealm = (pj_stun_realm_attr*) - pj_stun_msg_find_attr(response, PJ_STUN_ATTR_REALM, 0); - if (arealm) { - pj_strdup(sess->pool, &sess->server_realm, &arealm->value); - while (sess->server_realm.slen && - !sess->server_realm.ptr[sess->server_realm.slen-1]) - { - --sess->server_realm.slen; - } - } - - /* Create new request */ - status = pj_stun_session_create_req(sess, request->msg->hdr.type, - request->msg->hdr.magic, - NULL, &tdata); - if (status != PJ_SUCCESS) - return status; - - /* Duplicate all the attributes in the old request, except - * USERNAME, REALM, M-I, and NONCE, which will be filled in - * later. - */ - for (i=0; imsg->attr_count; ++i) { - const pj_stun_attr_hdr *asrc = request->msg->attr[i]; - - if (asrc->type == PJ_STUN_ATTR_USERNAME || - asrc->type == PJ_STUN_ATTR_REALM || - asrc->type == PJ_STUN_ATTR_MESSAGE_INTEGRITY || - asrc->type == PJ_STUN_ATTR_NONCE) - { - continue; - } - - tdata->msg->attr[tdata->msg->attr_count++] = - pj_stun_attr_clone(tdata->pool, asrc); - } - - /* Will retry the request with authentication, no need to - * notify user. - */ - *notify_user = PJ_FALSE; - - PJ_LOG(4,(SNAME(sess), "Retrying request with new authentication")); - - /* Retry the request */ - status = pj_stun_session_send_msg(sess, request->token, PJ_TRUE, - request->retransmit, src_addr, - src_addr_len, tdata); + const pj_stun_nonce_attr *anonce; + const pj_stun_realm_attr *arealm; + pj_stun_tx_data *tdata; + unsigned i; + pj_status_t status; + + anonce = (const pj_stun_nonce_attr*) + pj_stun_msg_find_attr(response, PJ_STUN_ATTR_NONCE, 0); + if (!anonce) { + PJ_LOG(4,(SNAME(sess), "Invalid response: missing NONCE")); + *notify_user = PJ_FALSE; + return PJNATH_EINSTUNMSG; + } + + /* Bail out if we've supplied the correct nonce */ + if (pj_strcmp(&anonce->value, &sess->next_nonce)==0) { + return PJ_SUCCESS; + } + + /* Bail out if we've tried too many */ + if (++sess->auth_retry > 3) { + PJ_LOG(4,(SNAME(sess), "Error: authentication failed (too " + "many retries)")); + return PJ_STATUS_FROM_STUN_CODE(401); + } + + /* Save next_nonce */ + pj_strdup(sess->pool, &sess->next_nonce, &anonce->value); + + /* Copy the realm from the response */ + arealm = (pj_stun_realm_attr*) + pj_stun_msg_find_attr(response, PJ_STUN_ATTR_REALM, 0); + if (arealm) { + pj_strdup(sess->pool, &sess->server_realm, &arealm->value); + while (sess->server_realm.slen && + !sess->server_realm.ptr[sess->server_realm.slen-1]) + { + --sess->server_realm.slen; + } + } + + /* Create new request */ + status = pj_stun_session_create_req(sess, request->msg->hdr.type, + request->msg->hdr.magic, + NULL, &tdata); + if (status != PJ_SUCCESS) + return status; + + /* Duplicate all the attributes in the old request, except + * USERNAME, REALM, M-I, and NONCE, which will be filled in + * later. + */ + for (i=0; imsg->attr_count; ++i) { + const pj_stun_attr_hdr *asrc = request->msg->attr[i]; + + if (asrc->type == PJ_STUN_ATTR_USERNAME || + asrc->type == PJ_STUN_ATTR_REALM || + asrc->type == PJ_STUN_ATTR_MESSAGE_INTEGRITY || + asrc->type == PJ_STUN_ATTR_NONCE) + { + continue; + } + + tdata->msg->attr[tdata->msg->attr_count++] = + pj_stun_attr_clone(tdata->pool, asrc); + } + + /* Will retry the request with authentication, no need to + * notify user. + */ + *notify_user = PJ_FALSE; + + PJ_LOG(4,(SNAME(sess), "Retrying request with new authentication")); + + /* Retry the request */ + status = pj_stun_session_send_msg(sess, request->token, PJ_TRUE, + request->retransmit, src_addr, + src_addr_len, tdata); } else { - sess->auth_retry = 0; + sess->auth_retry = 0; } return PJ_SUCCESS; } static void stun_tsx_on_complete(pj_stun_client_tsx *tsx, - pj_status_t status, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + pj_status_t status, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_stun_session *sess; pj_bool_t notify_user = PJ_TRUE; @@ -472,35 +471,35 @@ static void stun_tsx_on_complete(pj_stun_client_tsx *tsx, /* Lock the session and prevent user from destroying us in the callback */ pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying) { - pj_stun_msg_destroy_tdata(sess, tdata); - pj_grp_lock_release(sess->grp_lock); - return; + pj_stun_msg_destroy_tdata(sess, tdata); + pj_grp_lock_release(sess->grp_lock); + return; } /* Handle authentication challenge */ handle_auth_challenge(sess, tdata, response, src_addr, - src_addr_len, ¬ify_user); + src_addr_len, ¬ify_user); if (notify_user && sess->cb.on_request_complete) { - (*sess->cb.on_request_complete)(sess, status, tdata->token, tdata, - response, src_addr, src_addr_len); + (*sess->cb.on_request_complete)(sess, status, tdata->token, tdata, + response, src_addr, src_addr_len); } /* Destroy the transmit data. This will remove the transaction * from the pending list too. */ if (status == PJNATH_ESTUNTIMEDOUT) - destroy_tdata(tdata, PJ_TRUE); + destroy_tdata(tdata, PJ_TRUE); else - destroy_tdata(tdata, PJ_FALSE); + destroy_tdata(tdata, PJ_FALSE); tdata = NULL; pj_grp_lock_release(sess->grp_lock); } static pj_status_t stun_tsx_on_send_msg(pj_stun_client_tsx *tsx, - const void *stun_pkt, - pj_size_t pkt_size) + const void *stun_pkt, + pj_size_t pkt_size) { pj_stun_tx_data *tdata; pj_stun_session *sess; @@ -513,16 +512,16 @@ static pj_status_t stun_tsx_on_send_msg(pj_stun_client_tsx *tsx, pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying) { - /* Stray timer */ - pj_grp_lock_release(sess->grp_lock); - return PJ_EINVALIDOP; + /* Stray timer */ + pj_grp_lock_release(sess->grp_lock); + return PJ_EINVALIDOP; } status = sess->cb.on_send_msg(tdata->sess, tdata->token, stun_pkt, - pkt_size, tdata->dst_addr, - tdata->addr_len); + pkt_size, tdata->dst_addr, + tdata->addr_len); if (pj_grp_lock_release(sess->grp_lock)) - return PJ_EGONE; + return PJ_EGONE; return status; } @@ -530,23 +529,23 @@ static pj_status_t stun_tsx_on_send_msg(pj_stun_client_tsx *tsx, /* **************************************************************************/ PJ_DEF(pj_status_t) pj_stun_session_create( pj_stun_config *cfg, - const char *name, - const pj_stun_session_cb *cb, - pj_bool_t fingerprint, - pj_grp_lock_t *grp_lock, - pj_stun_session **p_sess) + const char *name, + const pj_stun_session_cb *cb, + pj_bool_t fingerprint, + pj_grp_lock_t *grp_lock, + pj_stun_session **p_sess) { - pj_pool_t *pool; + pj_pool_t *pool; pj_stun_session *sess; pj_status_t status; PJ_ASSERT_RETURN(cfg && cb && p_sess, PJ_EINVAL); if (name==NULL) - name = "stuse%p"; + name = "stuse%p"; pool = pj_pool_create(cfg->pf, name, PJNATH_POOL_LEN_STUN_SESS, - PJNATH_POOL_INC_STUN_SESS, NULL); + PJNATH_POOL_INC_STUN_SESS, NULL); PJ_ASSERT_RETURN(pool, PJ_ENOMEM); sess = PJ_POOL_ZALLOC_T(pool, pj_stun_session); @@ -557,13 +556,13 @@ PJ_DEF(pj_status_t) pj_stun_session_create( pj_stun_config *cfg, sess->log_flag = 0xFFFF; if (grp_lock) { - sess->grp_lock = grp_lock; + sess->grp_lock = grp_lock; } else { - status = pj_grp_lock_create(pool, NULL, &sess->grp_lock); - if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; - } + status = pj_grp_lock_create(pool, NULL, &sess->grp_lock); + if (status != PJ_SUCCESS) { + pj_pool_release(pool); + return status; + } } pj_grp_lock_add_ref(sess->grp_lock); @@ -573,8 +572,8 @@ PJ_DEF(pj_status_t) pj_stun_session_create( pj_stun_config *cfg, pj_stun_session_set_software_name(sess, &cfg->software_name); sess->rx_pool = pj_pool_create(sess->cfg->pf, name, - PJNATH_POOL_LEN_STUN_TDATA, - PJNATH_POOL_INC_STUN_TDATA, NULL); + PJNATH_POOL_LEN_STUN_TDATA, + PJNATH_POOL_INC_STUN_TDATA, NULL); pj_list_init(&sess->pending_request_list); pj_list_init(&sess->cached_response_list); @@ -589,8 +588,8 @@ static void stun_sess_on_destroy(void *comp) pj_stun_session *sess = (pj_stun_session*)comp; while (!pj_list_empty(&sess->pending_request_list)) { - pj_stun_tx_data *tdata = sess->pending_request_list.next; - destroy_tdata(tdata, PJ_TRUE); + pj_stun_tx_data *tdata = sess->pending_request_list.next; + destroy_tdata(tdata, PJ_TRUE); } pj_pool_safe_release(&sess->rx_pool); @@ -606,14 +605,14 @@ PJ_DEF(pj_status_t) pj_stun_session_destroy(pj_stun_session *sess) PJ_ASSERT_RETURN(sess, PJ_EINVAL); TRACE_((SNAME(sess), "STUN session %p destroy request, ref_cnt=%d", - sess, pj_grp_lock_get_ref(sess->grp_lock))); + sess, pj_grp_lock_get_ref(sess->grp_lock))); pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying) { - /* Prevent from decrementing the ref counter more than once */ - pj_grp_lock_release(sess->grp_lock); - return PJ_EINVALIDOP; + /* Prevent from decrementing the ref counter more than once */ + pj_grp_lock_release(sess->grp_lock); + return PJ_EINVALIDOP; } sess->is_destroying = PJ_TRUE; @@ -623,17 +622,17 @@ PJ_DEF(pj_status_t) pj_stun_session_destroy(pj_stun_session *sess) */ tdata = sess->pending_request_list.next; while (tdata != &sess->pending_request_list) { - if (tdata->client_tsx) - pj_stun_client_tsx_stop(tdata->client_tsx); - tdata = tdata->next; + if (tdata->client_tsx) + pj_stun_client_tsx_stop(tdata->client_tsx); + tdata = tdata->next; } /* Destroy cached response within session lock protection to avoid * race scenario with on_cache_timeout(). */ while (!pj_list_empty(&sess->cached_response_list)) { - pj_stun_tx_data *tmp_tdata = sess->cached_response_list.next; - destroy_tdata(tmp_tdata, PJ_TRUE); + pj_stun_tx_data *tmp_tdata = sess->cached_response_list.next; + destroy_tdata(tmp_tdata, PJ_TRUE); } pj_grp_lock_dec_ref(sess->grp_lock); @@ -643,7 +642,7 @@ PJ_DEF(pj_status_t) pj_stun_session_destroy(pj_stun_session *sess) PJ_DEF(pj_status_t) pj_stun_session_set_user_data( pj_stun_session *sess, - void *user_data) + void *user_data) { PJ_ASSERT_RETURN(sess, PJ_EINVAL); pj_grp_lock_acquire(sess->grp_lock); @@ -665,31 +664,31 @@ PJ_DEF(pj_grp_lock_t *) pj_stun_session_get_grp_lock(pj_stun_session *sess) } PJ_DEF(pj_status_t) pj_stun_session_set_software_name(pj_stun_session *sess, - const pj_str_t *sw) + const pj_str_t *sw) { PJ_ASSERT_RETURN(sess, PJ_EINVAL); pj_grp_lock_acquire(sess->grp_lock); if (sw && sw->slen) - pj_strdup(sess->pool, &sess->srv_name, sw); + pj_strdup(sess->pool, &sess->srv_name, sw); else - sess->srv_name.slen = 0; + sess->srv_name.slen = 0; pj_grp_lock_release(sess->grp_lock); return PJ_SUCCESS; } PJ_DEF(pj_status_t) pj_stun_session_set_credential(pj_stun_session *sess, - pj_stun_auth_type auth_type, - const pj_stun_auth_cred *cred) + pj_stun_auth_type auth_type, + const pj_stun_auth_cred *cred) { PJ_ASSERT_RETURN(sess, PJ_EINVAL); pj_grp_lock_acquire(sess->grp_lock); sess->auth_type = auth_type; if (cred) { - pj_stun_auth_cred_dup(sess->pool, &sess->cred, cred); + pj_stun_auth_cred_dup(sess->pool, &sess->cred, cred); } else { - sess->auth_type = PJ_STUN_AUTH_NONE; - pj_bzero(&sess->cred, sizeof(sess->cred)); + sess->auth_type = PJ_STUN_AUTH_NONE; + pj_bzero(&sess->cred, sizeof(sess->cred)); } pj_grp_lock_release(sess->grp_lock); @@ -697,14 +696,14 @@ PJ_DEF(pj_status_t) pj_stun_session_set_credential(pj_stun_session *sess, } PJ_DEF(void) pj_stun_session_set_log( pj_stun_session *sess, - unsigned flags) + unsigned flags) { PJ_ASSERT_ON_FAIL(sess, return); sess->log_flag = flags; } PJ_DEF(pj_bool_t) pj_stun_session_use_fingerprint(pj_stun_session *sess, - pj_bool_t use) + pj_bool_t use) { pj_bool_t old_use; @@ -716,52 +715,52 @@ PJ_DEF(pj_bool_t) pj_stun_session_use_fingerprint(pj_stun_session *sess, } static pj_status_t get_auth(pj_stun_session *sess, - pj_stun_tx_data *tdata) + pj_stun_tx_data *tdata) { if (sess->cred.type == PJ_STUN_AUTH_CRED_STATIC) { - //tdata->auth_info.realm = sess->cred.data.static_cred.realm; - tdata->auth_info.realm = sess->server_realm; - tdata->auth_info.username = sess->cred.data.static_cred.username; - tdata->auth_info.nonce = sess->cred.data.static_cred.nonce; + //tdata->auth_info.realm = sess->cred.data.static_cred.realm; + tdata->auth_info.realm = sess->server_realm; + tdata->auth_info.username = sess->cred.data.static_cred.username; + tdata->auth_info.nonce = sess->cred.data.static_cred.nonce; - pj_stun_create_key(tdata->pool, &tdata->auth_info.auth_key, - &tdata->auth_info.realm, - &tdata->auth_info.username, - sess->cred.data.static_cred.data_type, - &sess->cred.data.static_cred.data); + pj_stun_create_key(tdata->pool, &tdata->auth_info.auth_key, + &tdata->auth_info.realm, + &tdata->auth_info.username, + sess->cred.data.static_cred.data_type, + &sess->cred.data.static_cred.data); } else if (sess->cred.type == PJ_STUN_AUTH_CRED_DYNAMIC) { - pj_str_t password; - void *user_data = sess->cred.data.dyn_cred.user_data; - pj_stun_passwd_type data_type = PJ_STUN_PASSWD_PLAIN; - pj_status_t rc; - - rc = (*sess->cred.data.dyn_cred.get_cred)(tdata->msg, user_data, - tdata->pool, - &tdata->auth_info.realm, - &tdata->auth_info.username, - &tdata->auth_info.nonce, - &data_type, &password); - if (rc != PJ_SUCCESS) - return rc; - - pj_stun_create_key(tdata->pool, &tdata->auth_info.auth_key, - &tdata->auth_info.realm, &tdata->auth_info.username, - data_type, &password); + pj_str_t password; + void *user_data = sess->cred.data.dyn_cred.user_data; + pj_stun_passwd_type data_type = PJ_STUN_PASSWD_PLAIN; + pj_status_t rc; + + rc = (*sess->cred.data.dyn_cred.get_cred)(tdata->msg, user_data, + tdata->pool, + &tdata->auth_info.realm, + &tdata->auth_info.username, + &tdata->auth_info.nonce, + &data_type, &password); + if (rc != PJ_SUCCESS) + return rc; + + pj_stun_create_key(tdata->pool, &tdata->auth_info.auth_key, + &tdata->auth_info.realm, &tdata->auth_info.username, + data_type, &password); } else { - pj_assert(!"Unknown credential type"); - return PJ_EBUG; + pj_assert(!"Unknown credential type"); + return PJ_EBUG; } return PJ_SUCCESS; } PJ_DEF(pj_status_t) pj_stun_session_create_req(pj_stun_session *sess, - int method, - pj_uint32_t magic, - const pj_uint8_t tsx_id[12], - pj_stun_tx_data **p_tdata) + int method, + pj_uint32_t magic, + const pj_uint8_t tsx_id[12], + pj_stun_tx_data **p_tdata) { pj_stun_tx_data *tdata = NULL; pj_status_t status; @@ -770,53 +769,53 @@ PJ_DEF(pj_status_t) pj_stun_session_create_req(pj_stun_session *sess, pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying) { - pj_grp_lock_release(sess->grp_lock); - return PJ_EINVALIDOP; + pj_grp_lock_release(sess->grp_lock); + return PJ_EINVALIDOP; } status = create_tdata(sess, &tdata); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create STUN message */ status = pj_stun_msg_create(tdata->pool, method, magic, - tsx_id, &tdata->msg); + tsx_id, &tdata->msg); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* copy the request's transaction ID as the transaction key. */ pj_assert(sizeof(tdata->msg_key)==sizeof(tdata->msg->hdr.tsx_id)); tdata->msg_magic = tdata->msg->hdr.magic; pj_memcpy(tdata->msg_key, tdata->msg->hdr.tsx_id, - sizeof(tdata->msg->hdr.tsx_id)); + sizeof(tdata->msg->hdr.tsx_id)); /* Get authentication information for the request */ if (sess->auth_type == PJ_STUN_AUTH_NONE) { - /* No authentication */ + /* No authentication */ } else if (sess->auth_type == PJ_STUN_AUTH_SHORT_TERM) { - /* MUST put authentication in request */ - status = get_auth(sess, tdata); - if (status != PJ_SUCCESS) - goto on_error; + /* MUST put authentication in request */ + status = get_auth(sess, tdata); + if (status != PJ_SUCCESS) + goto on_error; } else if (sess->auth_type == PJ_STUN_AUTH_LONG_TERM) { - /* Only put authentication information if we've received - * response from server. - */ - if (sess->next_nonce.slen != 0) { - status = get_auth(sess, tdata); - if (status != PJ_SUCCESS) - goto on_error; - tdata->auth_info.nonce = sess->next_nonce; - tdata->auth_info.realm = sess->server_realm; - } + /* Only put authentication information if we've received + * response from server. + */ + if (sess->next_nonce.slen != 0) { + status = get_auth(sess, tdata); + if (status != PJ_SUCCESS) + goto on_error; + tdata->auth_info.nonce = sess->next_nonce; + tdata->auth_info.realm = sess->server_realm; + } } else { - pj_assert(!"Invalid authentication type"); - status = PJ_EBUG; - goto on_error; + pj_assert(!"Invalid authentication type"); + status = PJ_EBUG; + goto on_error; } *p_tdata = tdata; @@ -825,14 +824,14 @@ PJ_DEF(pj_status_t) pj_stun_session_create_req(pj_stun_session *sess, on_error: if (tdata) - pj_pool_safe_release(&tdata->pool); + pj_pool_safe_release(&tdata->pool); pj_grp_lock_release(sess->grp_lock); return status; } PJ_DEF(pj_status_t) pj_stun_session_create_ind(pj_stun_session *sess, - int msg_type, - pj_stun_tx_data **p_tdata) + int msg_type, + pj_stun_tx_data **p_tdata) { pj_stun_tx_data *tdata = NULL; pj_status_t status; @@ -841,24 +840,24 @@ PJ_DEF(pj_status_t) pj_stun_session_create_ind(pj_stun_session *sess, pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying) { - pj_grp_lock_release(sess->grp_lock); - return PJ_EINVALIDOP; + pj_grp_lock_release(sess->grp_lock); + return PJ_EINVALIDOP; } status = create_tdata(sess, &tdata); if (status != PJ_SUCCESS) { - pj_grp_lock_release(sess->grp_lock); - return status; + pj_grp_lock_release(sess->grp_lock); + return status; } /* Create STUN message */ msg_type |= PJ_STUN_INDICATION_BIT; status = pj_stun_msg_create(tdata->pool, msg_type, PJ_STUN_MAGIC, - NULL, &tdata->msg); + NULL, &tdata->msg); if (status != PJ_SUCCESS) { - pj_pool_safe_release(&tdata->pool); - pj_grp_lock_release(sess->grp_lock); - return status; + pj_pool_safe_release(&tdata->pool); + pj_grp_lock_release(sess->grp_lock); + return status; } *p_tdata = tdata; @@ -871,40 +870,40 @@ PJ_DEF(pj_status_t) pj_stun_session_create_ind(pj_stun_session *sess, * Create a STUN response message. */ PJ_DEF(pj_status_t) pj_stun_session_create_res( pj_stun_session *sess, - const pj_stun_rx_data *rdata, - unsigned err_code, - const pj_str_t *err_msg, - pj_stun_tx_data **p_tdata) + const pj_stun_rx_data *rdata, + unsigned err_code, + const pj_str_t *err_msg, + pj_stun_tx_data **p_tdata) { pj_status_t status; pj_stun_tx_data *tdata = NULL; pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying) { - pj_grp_lock_release(sess->grp_lock); - return PJ_EINVALIDOP; + pj_grp_lock_release(sess->grp_lock); + return PJ_EINVALIDOP; } status = create_tdata(sess, &tdata); if (status != PJ_SUCCESS) { - pj_grp_lock_release(sess->grp_lock); - return status; + pj_grp_lock_release(sess->grp_lock); + return status; } /* Create STUN response message */ status = pj_stun_msg_create_response(tdata->pool, rdata->msg, - err_code, err_msg, &tdata->msg); + err_code, err_msg, &tdata->msg); if (status != PJ_SUCCESS) { - pj_pool_safe_release(&tdata->pool); - pj_grp_lock_release(sess->grp_lock); - return status; + pj_pool_safe_release(&tdata->pool); + pj_grp_lock_release(sess->grp_lock); + return status; } /* copy the request's transaction ID as the transaction key. */ pj_assert(sizeof(tdata->msg_key)==sizeof(rdata->msg->hdr.tsx_id)); tdata->msg_magic = rdata->msg->hdr.magic; pj_memcpy(tdata->msg_key, rdata->msg->hdr.tsx_id, - sizeof(rdata->msg->hdr.tsx_id)); + sizeof(rdata->msg->hdr.tsx_id)); /* copy the credential found in the request */ pj_stun_req_cred_info_dup(tdata->pool, &tdata->auth_info, &rdata->info); @@ -919,41 +918,41 @@ PJ_DEF(pj_status_t) pj_stun_session_create_res( pj_stun_session *sess, /* Print outgoing message to log */ static void dump_tx_msg(pj_stun_session *sess, const pj_stun_msg *msg, - unsigned pkt_size, const pj_sockaddr_t *addr) + unsigned pkt_size, const pj_sockaddr_t *addr) { char dst_name[PJ_INET6_ADDRSTRLEN+10]; if ((PJ_STUN_IS_REQUEST(msg->hdr.type) && - (sess->log_flag & PJ_STUN_SESS_LOG_TX_REQ)==0) || - (PJ_STUN_IS_RESPONSE(msg->hdr.type) && - (sess->log_flag & PJ_STUN_SESS_LOG_TX_RES)==0) || - (PJ_STUN_IS_INDICATION(msg->hdr.type) && - (sess->log_flag & PJ_STUN_SESS_LOG_TX_IND)==0)) + (sess->log_flag & PJ_STUN_SESS_LOG_TX_REQ)==0) || + (PJ_STUN_IS_RESPONSE(msg->hdr.type) && + (sess->log_flag & PJ_STUN_SESS_LOG_TX_RES)==0) || + (PJ_STUN_IS_INDICATION(msg->hdr.type) && + (sess->log_flag & PJ_STUN_SESS_LOG_TX_IND)==0)) { - return; + return; } pj_sockaddr_print(addr, dst_name, sizeof(dst_name), 3); PJ_LOG(5,(SNAME(sess), - "TX %d bytes STUN message to %s:\n" - "--- begin STUN message ---\n" - "%s" - "--- end of STUN message ---\n", - pkt_size, dst_name, - pj_stun_msg_dump(msg, sess->dump_buf, sizeof(sess->dump_buf), - NULL))); + "TX %d bytes STUN message to %s:\n" + "--- begin STUN message ---\n" + "%s" + "--- end of STUN message ---\n", + pkt_size, dst_name, + pj_stun_msg_dump(msg, sess->dump_buf, sizeof(sess->dump_buf), + NULL))); } PJ_DEF(pj_status_t) pj_stun_session_send_msg( pj_stun_session *sess, - void *token, - pj_bool_t cache_res, - pj_bool_t retransmit, - const pj_sockaddr_t *server, - unsigned addr_len, - pj_stun_tx_data *tdata) + void *token, + pj_bool_t cache_res, + pj_bool_t retransmit, + const pj_sockaddr_t *server, + unsigned addr_len, + pj_stun_tx_data *tdata) { pj_status_t status; @@ -962,8 +961,8 @@ PJ_DEF(pj_status_t) pj_stun_session_send_msg( pj_stun_session *sess, /* Lock the session and prevent user from destroying us in the callback */ pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying) { - pj_grp_lock_release(sess->grp_lock); - return PJ_EINVALIDOP; + pj_grp_lock_release(sess->grp_lock); + return PJ_EINVALIDOP; } pj_log_push_indent(); @@ -977,22 +976,22 @@ PJ_DEF(pj_status_t) pj_stun_session_send_msg( pj_stun_session *sess, /* Apply options */ status = apply_msg_options(sess, tdata->pool, &tdata->auth_info, - tdata->msg); + tdata->msg); if (status != PJ_SUCCESS) { - pj_stun_msg_destroy_tdata(sess, tdata); - LOG_ERR_(sess, "Error applying options", status); - goto on_return; + pj_stun_msg_destroy_tdata(sess, tdata); + LOG_ERR_(sess, "Error applying options", status); + goto on_return; } /* Encode message */ status = pj_stun_msg_encode(tdata->msg, (pj_uint8_t*)tdata->pkt, - tdata->max_len, 0, - &tdata->auth_info.auth_key, - &tdata->pkt_size); + tdata->max_len, 0, + &tdata->auth_info.auth_key, + &tdata->pkt_size); if (status != PJ_SUCCESS) { - pj_stun_msg_destroy_tdata(sess, tdata); - LOG_ERR_(sess, "STUN encode() error", status); - goto on_return; + pj_stun_msg_destroy_tdata(sess, tdata); + LOG_ERR_(sess, "STUN encode() error", status); + goto on_return; } /* Dump packet */ @@ -1003,95 +1002,95 @@ PJ_DEF(pj_status_t) pj_stun_session_send_msg( pj_stun_session *sess, */ if (PJ_STUN_IS_REQUEST(tdata->msg->hdr.type)) { - /* Create STUN client transaction */ - status = pj_stun_client_tsx_create(sess->cfg, tdata->pool, - sess->grp_lock, - &tsx_cb, &tdata->client_tsx); - PJ_ASSERT_RETURN(status==PJ_SUCCESS, status); - pj_stun_client_tsx_set_data(tdata->client_tsx, (void*)tdata); - - /* Save the remote address */ - tdata->addr_len = addr_len; - tdata->dst_addr = server; - - /* Send the request! */ - status = pj_stun_client_tsx_send_msg(tdata->client_tsx, retransmit, - tdata->pkt, - (unsigned)tdata->pkt_size); - if (status != PJ_SUCCESS && status != PJ_EPENDING) { - pj_stun_msg_destroy_tdata(sess, tdata); - LOG_ERR_(sess, "Error sending STUN request", status); - goto on_return; - } - - /* Add to pending request list */ - tsx_add(sess, tdata); + /* Create STUN client transaction */ + status = pj_stun_client_tsx_create(sess->cfg, tdata->pool, + sess->grp_lock, + &tsx_cb, &tdata->client_tsx); + PJ_ASSERT_RETURN(status==PJ_SUCCESS, status); + pj_stun_client_tsx_set_data(tdata->client_tsx, (void*)tdata); + + /* Save the remote address */ + tdata->addr_len = addr_len; + tdata->dst_addr = server; + + /* Send the request! */ + status = pj_stun_client_tsx_send_msg(tdata->client_tsx, retransmit, + tdata->pkt, + (unsigned)tdata->pkt_size); + if (status != PJ_SUCCESS && status != PJ_EPENDING) { + pj_stun_msg_destroy_tdata(sess, tdata); + LOG_ERR_(sess, "Error sending STUN request", status); + goto on_return; + } + + /* Add to pending request list */ + tsx_add(sess, tdata); } else { - /* Otherwise for non-request message, send directly to transport. */ - if (cache_res && - (PJ_STUN_IS_SUCCESS_RESPONSE(tdata->msg->hdr.type) || - PJ_STUN_IS_ERROR_RESPONSE(tdata->msg->hdr.type))) - { - /* Requested to keep the response in the cache */ - pj_time_val timeout; - - status = pj_grp_lock_create(tdata->pool, NULL, &tdata->grp_lock); - if (status != PJ_SUCCESS) { - pj_stun_msg_destroy_tdata(sess, tdata); - LOG_ERR_(sess, "Error creating group lock", status); - goto on_return; - } - pj_grp_lock_add_ref(tdata->grp_lock); - pj_grp_lock_add_handler(tdata->grp_lock, tdata->pool, tdata, - &tdata_on_destroy); - - /* Also add ref session group lock to make sure that the session - * is still valid when cache timeout callback is called. - */ - pj_grp_lock_add_ref(sess->grp_lock); - - pj_memset(&tdata->res_timer, 0, sizeof(tdata->res_timer)); - pj_timer_entry_init(&tdata->res_timer, PJ_FALSE, tdata, - &on_cache_timeout); - - timeout.sec = sess->cfg->res_cache_msec / 1000; - timeout.msec = sess->cfg->res_cache_msec % 1000; - - status = pj_timer_heap_schedule_w_grp_lock(sess->cfg->timer_heap, - &tdata->res_timer, - &timeout, PJ_TRUE, - tdata->grp_lock); - if (status != PJ_SUCCESS) { - pj_stun_msg_destroy_tdata(sess, tdata); - LOG_ERR_(sess, "Error scheduling response timer", status); - goto on_return; - } - - pj_list_push_back(&sess->cached_response_list, tdata); - } - - /* Send to transport directly. */ - status = sess->cb.on_send_msg(sess, token, tdata->pkt, - tdata->pkt_size, server, addr_len); - - if (status != PJ_SUCCESS && status != PJ_EPENDING) { - pj_stun_msg_destroy_tdata(sess, tdata); - LOG_ERR_(sess, "Error sending STUN request", status); - goto on_return; - } - - /* Destroy only when response is not cached*/ - if (tdata->res_timer.id == 0) { - pj_stun_msg_destroy_tdata(sess, tdata); - } + /* Otherwise for non-request message, send directly to transport. */ + if (cache_res && + (PJ_STUN_IS_SUCCESS_RESPONSE(tdata->msg->hdr.type) || + PJ_STUN_IS_ERROR_RESPONSE(tdata->msg->hdr.type))) + { + /* Requested to keep the response in the cache */ + pj_time_val timeout; + + status = pj_grp_lock_create(tdata->pool, NULL, &tdata->grp_lock); + if (status != PJ_SUCCESS) { + pj_stun_msg_destroy_tdata(sess, tdata); + LOG_ERR_(sess, "Error creating group lock", status); + goto on_return; + } + pj_grp_lock_add_ref(tdata->grp_lock); + pj_grp_lock_add_handler(tdata->grp_lock, tdata->pool, tdata, + &tdata_on_destroy); + + /* Also add ref session group lock to make sure that the session + * is still valid when cache timeout callback is called. + */ + pj_grp_lock_add_ref(sess->grp_lock); + + pj_memset(&tdata->res_timer, 0, sizeof(tdata->res_timer)); + pj_timer_entry_init(&tdata->res_timer, PJ_FALSE, tdata, + &on_cache_timeout); + + timeout.sec = sess->cfg->res_cache_msec / 1000; + timeout.msec = sess->cfg->res_cache_msec % 1000; + + status = pj_timer_heap_schedule_w_grp_lock(sess->cfg->timer_heap, + &tdata->res_timer, + &timeout, PJ_TRUE, + tdata->grp_lock); + if (status != PJ_SUCCESS) { + pj_stun_msg_destroy_tdata(sess, tdata); + LOG_ERR_(sess, "Error scheduling response timer", status); + goto on_return; + } + + pj_list_push_back(&sess->cached_response_list, tdata); + } + + /* Send to transport directly. */ + status = sess->cb.on_send_msg(sess, token, tdata->pkt, + tdata->pkt_size, server, addr_len); + + if (status != PJ_SUCCESS && status != PJ_EPENDING) { + pj_stun_msg_destroy_tdata(sess, tdata); + LOG_ERR_(sess, "Error sending STUN request", status); + goto on_return; + } + + /* Destroy only when response is not cached*/ + if (tdata->res_timer.id == 0) { + pj_stun_msg_destroy_tdata(sess, tdata); + } } on_return: pj_log_pop_indent(); if (pj_grp_lock_release(sess->grp_lock)) - return PJ_EGONE; + return PJ_EGONE; return status; } @@ -1101,13 +1100,13 @@ PJ_DEF(pj_status_t) pj_stun_session_send_msg( pj_stun_session *sess, * Create and send STUN response message. */ PJ_DEF(pj_status_t) pj_stun_session_respond( pj_stun_session *sess, - const pj_stun_rx_data *rdata, - unsigned code, - const char *errmsg, - void *token, - pj_bool_t cache, - const pj_sockaddr_t *dst_addr, - unsigned addr_len) + const pj_stun_rx_data *rdata, + unsigned code, + const char *errmsg, + void *token, + pj_bool_t cache, + const pj_sockaddr_t *dst_addr, + unsigned addr_len) { pj_status_t status; pj_str_t reason; @@ -1115,16 +1114,16 @@ PJ_DEF(pj_status_t) pj_stun_session_respond( pj_stun_session *sess, pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying) { - pj_grp_lock_release(sess->grp_lock); - return PJ_EINVALIDOP; + pj_grp_lock_release(sess->grp_lock); + return PJ_EINVALIDOP; } status = pj_stun_session_create_res(sess, rdata, code, - (errmsg?pj_cstr(&reason,errmsg):NULL), - &tdata); + (errmsg?pj_cstr(&reason,errmsg):NULL), + &tdata); if (status != PJ_SUCCESS) { - pj_grp_lock_release(sess->grp_lock); - return status; + pj_grp_lock_release(sess->grp_lock); + return status; } status = pj_stun_session_send_msg(sess, token, cache, PJ_FALSE, @@ -1139,9 +1138,9 @@ PJ_DEF(pj_status_t) pj_stun_session_respond( pj_stun_session *sess, * Cancel outgoing STUN transaction. */ PJ_DEF(pj_status_t) pj_stun_session_cancel_req( pj_stun_session *sess, - pj_stun_tx_data *tdata, - pj_bool_t notify, - pj_status_t notify_status) + pj_stun_tx_data *tdata, + pj_bool_t notify, + pj_status_t notify_status) { PJ_ASSERT_RETURN(sess && tdata, PJ_EINVAL); PJ_ASSERT_RETURN(!notify || notify_status!=PJ_SUCCESS, PJ_EINVAL); @@ -1150,13 +1149,13 @@ PJ_DEF(pj_status_t) pj_stun_session_cancel_req( pj_stun_session *sess, /* Lock the session and prevent user from destroying us in the callback */ pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying) { - pj_grp_lock_release(sess->grp_lock); - return PJ_EINVALIDOP; + pj_grp_lock_release(sess->grp_lock); + return PJ_EINVALIDOP; } if (notify) { - (sess->cb.on_request_complete)(sess, notify_status, tdata->token, - tdata, NULL, NULL, 0); + (sess->cb.on_request_complete)(sess, notify_status, tdata->token, + tdata, NULL, NULL, 0); } /* Just destroy tdata. This will destroy the transaction as well */ @@ -1171,7 +1170,7 @@ PJ_DEF(pj_status_t) pj_stun_session_cancel_req( pj_stun_session *sess, * Explicitly request retransmission of the request. */ PJ_DEF(pj_status_t) pj_stun_session_retransmit_req(pj_stun_session *sess, - pj_stun_tx_data *tdata, + pj_stun_tx_data *tdata, pj_bool_t mod_count) { pj_status_t status; @@ -1182,8 +1181,8 @@ PJ_DEF(pj_status_t) pj_stun_session_retransmit_req(pj_stun_session *sess, /* Lock the session and prevent user from destroying us in the callback */ pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying) { - pj_grp_lock_release(sess->grp_lock); - return PJ_EINVALIDOP; + pj_grp_lock_release(sess->grp_lock); + return PJ_EINVALIDOP; } status = pj_stun_client_tsx_retransmit(tdata->client_tsx, mod_count); @@ -1196,10 +1195,10 @@ PJ_DEF(pj_status_t) pj_stun_session_retransmit_req(pj_stun_session *sess, /* Send response */ static pj_status_t send_response(pj_stun_session *sess, void *token, - pj_pool_t *pool, pj_stun_msg *response, - const pj_stun_req_cred_info *auth_info, - pj_bool_t retransmission, - const pj_sockaddr_t *addr, unsigned addr_len) + pj_pool_t *pool, pj_stun_msg *response, + const pj_stun_req_cred_info *auth_info, + pj_bool_t retransmission, + const pj_sockaddr_t *addr, unsigned addr_len) { pj_uint8_t *out_pkt; pj_size_t out_max_len, out_len; @@ -1207,9 +1206,9 @@ static pj_status_t send_response(pj_stun_session *sess, void *token, /* Apply options */ if (!retransmission) { - status = apply_msg_options(sess, pool, auth_info, response); - if (status != PJ_SUCCESS) - return status; + status = apply_msg_options(sess, pool, auth_info, response); + if (status != PJ_SUCCESS) + return status; } /* Alloc packet buffer */ @@ -1218,10 +1217,10 @@ static pj_status_t send_response(pj_stun_session *sess, void *token, /* Encode */ status = pj_stun_msg_encode(response, out_pkt, out_max_len, 0, - &auth_info->auth_key, &out_len); + &auth_info->auth_key, &out_len); if (status != PJ_SUCCESS) { - LOG_ERR_(sess, "Error encoding message", status); - return status; + LOG_ERR_(sess, "Error encoding message", status); + return status; } /* Print log */ @@ -1229,37 +1228,37 @@ static pj_status_t send_response(pj_stun_session *sess, void *token, /* Send packet */ status = sess->cb.on_send_msg(sess, token, out_pkt, (unsigned)out_len, - addr, addr_len); + addr, addr_len); return status; } /* Authenticate incoming message */ static pj_status_t authenticate_req(pj_stun_session *sess, - void *token, - const pj_uint8_t *pkt, - unsigned pkt_len, - pj_stun_rx_data *rdata, - pj_pool_t *tmp_pool, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + void *token, + const pj_uint8_t *pkt, + unsigned pkt_len, + pj_stun_rx_data *rdata, + pj_pool_t *tmp_pool, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_stun_msg *response; pj_status_t status; if (PJ_STUN_IS_ERROR_RESPONSE(rdata->msg->hdr.type) || - sess->auth_type == PJ_STUN_AUTH_NONE) + sess->auth_type == PJ_STUN_AUTH_NONE) { - return PJ_SUCCESS; + return PJ_SUCCESS; } status = pj_stun_authenticate_request(pkt, pkt_len, rdata->msg, - &sess->cred, tmp_pool, &rdata->info, - &response); + &sess->cred, tmp_pool, &rdata->info, + &response); if (status != PJ_SUCCESS && response != NULL) { - PJ_PERROR(5,(SNAME(sess), status, "Message authentication failed")); - send_response(sess, token, tmp_pool, response, &rdata->info, - PJ_FALSE, src_addr, src_addr_len); + PJ_PERROR(5,(SNAME(sess), status, "Message authentication failed")); + send_response(sess, token, tmp_pool, response, &rdata->info, + PJ_FALSE, src_addr, src_addr_len); } return status; @@ -1268,12 +1267,12 @@ static pj_status_t authenticate_req(pj_stun_session *sess, /* Handle incoming response */ static pj_status_t on_incoming_response(pj_stun_session *sess, - unsigned options, - const pj_uint8_t *pkt, - unsigned pkt_len, - pj_stun_msg *msg, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + unsigned options, + const pj_uint8_t *pkt, + unsigned pkt_len, + pj_stun_msg *msg, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_stun_tx_data *tdata; pj_status_t status; @@ -1281,28 +1280,28 @@ static pj_status_t on_incoming_response(pj_stun_session *sess, /* Lookup pending client transaction */ tdata = tsx_lookup(sess, msg); if (tdata == NULL) { - PJ_LOG(5,(SNAME(sess), - "Transaction not found, response silently discarded")); - return PJ_SUCCESS; + PJ_LOG(5,(SNAME(sess), + "Transaction not found, response silently discarded")); + return PJ_SUCCESS; } if (sess->auth_type == PJ_STUN_AUTH_NONE) - options |= PJ_STUN_NO_AUTHENTICATE; + options |= PJ_STUN_NO_AUTHENTICATE; /* Authenticate the message, unless PJ_STUN_NO_AUTHENTICATE * is specified in the option. */ if ((options & PJ_STUN_NO_AUTHENTICATE) == 0 && - tdata->auth_info.auth_key.slen != 0 && - pj_stun_auth_valid_for_msg(msg)) + tdata->auth_info.auth_key.slen != 0 && + pj_stun_auth_valid_for_msg(msg)) { - status = pj_stun_authenticate_response(pkt, pkt_len, msg, - &tdata->auth_info.auth_key); - if (status != PJ_SUCCESS) { - PJ_PERROR(5,(SNAME(sess), status, - "Response authentication failed")); - return status; - } + status = pj_stun_authenticate_response(pkt, pkt_len, msg, + &tdata->auth_info.auth_key); + if (status != PJ_SUCCESS) { + PJ_PERROR(5,(SNAME(sess), status, + "Response authentication failed")); + return status; + } } /* Pass the response to the transaction. @@ -1310,9 +1309,9 @@ static pj_status_t on_incoming_response(pj_stun_session *sess, * and this will call the session callback too. */ status = pj_stun_client_tsx_on_rx_msg(tdata->client_tsx, msg, - src_addr, src_addr_len); + src_addr, src_addr_len); if (status != PJ_SUCCESS) { - return status; + return status; } return PJ_SUCCESS; @@ -1321,35 +1320,35 @@ static pj_status_t on_incoming_response(pj_stun_session *sess, /* For requests, check if we cache the response */ static pj_status_t check_cached_response(pj_stun_session *sess, - pj_pool_t *tmp_pool, - const pj_stun_msg *msg, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + pj_pool_t *tmp_pool, + const pj_stun_msg *msg, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_stun_tx_data *t; /* First lookup response in response cache */ t = sess->cached_response_list.next; while (t != &sess->cached_response_list) { - if (t->msg_magic == msg->hdr.magic && - t->msg->hdr.type == msg->hdr.type && - pj_memcmp(t->msg_key, msg->hdr.tsx_id, - sizeof(msg->hdr.tsx_id))==0) - { - break; - } - t = t->next; + if (t->msg_magic == msg->hdr.magic && + t->msg->hdr.type == msg->hdr.type && + pj_memcmp(t->msg_key, msg->hdr.tsx_id, + sizeof(msg->hdr.tsx_id))==0) + { + break; + } + t = t->next; } if (t != &sess->cached_response_list) { - /* Found response in the cache */ + /* Found response in the cache */ - PJ_LOG(5,(SNAME(sess), - "Request retransmission, sending cached response")); + PJ_LOG(5,(SNAME(sess), + "Request retransmission, sending cached response")); - send_response(sess, t->token, tmp_pool, t->msg, &t->auth_info, - PJ_TRUE, src_addr, src_addr_len); - return PJ_SUCCESS; + send_response(sess, t->token, tmp_pool, t->msg, &t->auth_info, + PJ_TRUE, src_addr, src_addr_len); + return PJ_SUCCESS; } return PJ_ENOTFOUND; @@ -1357,14 +1356,14 @@ static pj_status_t check_cached_response(pj_stun_session *sess, /* Handle incoming request */ static pj_status_t on_incoming_request(pj_stun_session *sess, - unsigned options, - void *token, - pj_pool_t *tmp_pool, - const pj_uint8_t *in_pkt, - unsigned in_pkt_len, - pj_stun_msg *msg, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + unsigned options, + void *token, + pj_pool_t *tmp_pool, + const pj_uint8_t *in_pkt, + unsigned in_pkt_len, + pj_stun_msg *msg, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_stun_rx_data rdata; pj_status_t status; @@ -1374,36 +1373,36 @@ static pj_status_t on_incoming_request(pj_stun_session *sess, pj_bzero(&rdata.info, sizeof(rdata.info)); if (sess->auth_type == PJ_STUN_AUTH_NONE) - options |= PJ_STUN_NO_AUTHENTICATE; + options |= PJ_STUN_NO_AUTHENTICATE; /* Authenticate the message, unless PJ_STUN_NO_AUTHENTICATE * is specified in the option. */ if ((options & PJ_STUN_NO_AUTHENTICATE) == 0) { - status = authenticate_req(sess, token, (const pj_uint8_t*) in_pkt, - in_pkt_len,&rdata, tmp_pool, src_addr, - src_addr_len); - if (status != PJ_SUCCESS) { - return status; - } + status = authenticate_req(sess, token, (const pj_uint8_t*) in_pkt, + in_pkt_len,&rdata, tmp_pool, src_addr, + src_addr_len); + if (status != PJ_SUCCESS) { + return status; + } } /* Distribute to handler, or respond with Bad Request */ if (sess->cb.on_rx_request) { - status = (*sess->cb.on_rx_request)(sess, in_pkt, in_pkt_len, &rdata, - token, src_addr, src_addr_len); + status = (*sess->cb.on_rx_request)(sess, in_pkt, in_pkt_len, &rdata, + token, src_addr, src_addr_len); } else { - pj_str_t err_text; - pj_stun_msg *response; - - err_text = pj_str("Callback is not set to handle request"); - status = pj_stun_msg_create_response(tmp_pool, msg, - PJ_STUN_SC_BAD_REQUEST, - &err_text, &response); - if (status == PJ_SUCCESS && response) { - status = send_response(sess, token, tmp_pool, response, - NULL, PJ_FALSE, src_addr, src_addr_len); - } + pj_str_t err_text; + pj_stun_msg *response; + + err_text = pj_str("Callback is not set to handle request"); + status = pj_stun_msg_create_response(tmp_pool, msg, + PJ_STUN_SC_BAD_REQUEST, + &err_text, &response); + if (status == PJ_SUCCESS && response) { + status = send_response(sess, token, tmp_pool, response, + NULL, PJ_FALSE, src_addr, src_addr_len); + } } return status; @@ -1412,64 +1411,64 @@ static pj_status_t on_incoming_request(pj_stun_session *sess, /* Handle incoming indication */ static pj_status_t on_incoming_indication(pj_stun_session *sess, - void *token, - pj_pool_t *tmp_pool, - const pj_uint8_t *in_pkt, - unsigned in_pkt_len, - const pj_stun_msg *msg, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + void *token, + pj_pool_t *tmp_pool, + const pj_uint8_t *in_pkt, + unsigned in_pkt_len, + const pj_stun_msg *msg, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { PJ_UNUSED_ARG(tmp_pool); /* Distribute to handler */ if (sess->cb.on_rx_indication) { - return (*sess->cb.on_rx_indication)(sess, in_pkt, in_pkt_len, msg, - token, src_addr, src_addr_len); + return (*sess->cb.on_rx_indication)(sess, in_pkt, in_pkt_len, msg, + token, src_addr, src_addr_len); } else { - return PJ_SUCCESS; + return PJ_SUCCESS; } } /* Print outgoing message to log */ static void dump_rx_msg(pj_stun_session *sess, const pj_stun_msg *msg, - unsigned pkt_size, const pj_sockaddr_t *addr) + unsigned pkt_size, const pj_sockaddr_t *addr) { char src_info[PJ_INET6_ADDRSTRLEN+10]; if ((PJ_STUN_IS_REQUEST(msg->hdr.type) && - (sess->log_flag & PJ_STUN_SESS_LOG_RX_REQ)==0) || - (PJ_STUN_IS_RESPONSE(msg->hdr.type) && - (sess->log_flag & PJ_STUN_SESS_LOG_RX_RES)==0) || - (PJ_STUN_IS_INDICATION(msg->hdr.type) && - (sess->log_flag & PJ_STUN_SESS_LOG_RX_IND)==0)) + (sess->log_flag & PJ_STUN_SESS_LOG_RX_REQ)==0) || + (PJ_STUN_IS_RESPONSE(msg->hdr.type) && + (sess->log_flag & PJ_STUN_SESS_LOG_RX_RES)==0) || + (PJ_STUN_IS_INDICATION(msg->hdr.type) && + (sess->log_flag & PJ_STUN_SESS_LOG_RX_IND)==0)) { - return; + return; } pj_sockaddr_print(addr, src_info, sizeof(src_info), 3); PJ_LOG(5,(SNAME(sess), - "RX %d bytes STUN message from %s:\n" - "--- begin STUN message ---\n" - "%s" - "--- end of STUN message ---\n", - pkt_size, src_info, - pj_stun_msg_dump(msg, sess->dump_buf, sizeof(sess->dump_buf), - NULL))); + "RX %d bytes STUN message from %s:\n" + "--- begin STUN message ---\n" + "%s" + "--- end of STUN message ---\n", + pkt_size, src_info, + pj_stun_msg_dump(msg, sess->dump_buf, sizeof(sess->dump_buf), + NULL))); } /* Incoming packet */ PJ_DEF(pj_status_t) pj_stun_session_on_rx_pkt(pj_stun_session *sess, - const void *packet, - pj_size_t pkt_size, - unsigned options, - void *token, - pj_size_t *parsed_len, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + const void *packet, + pj_size_t pkt_size, + unsigned options, + void *token, + pj_size_t *parsed_len, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_stun_msg *msg, *response; pj_status_t status; @@ -1480,8 +1479,8 @@ PJ_DEF(pj_status_t) pj_stun_session_on_rx_pkt(pj_stun_session *sess, pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying) { - pj_grp_lock_release(sess->grp_lock); - return PJ_EINVALIDOP; + pj_grp_lock_release(sess->grp_lock); + return PJ_EINVALIDOP; } pj_log_push_indent(); @@ -1491,59 +1490,59 @@ PJ_DEF(pj_status_t) pj_stun_session_on_rx_pkt(pj_stun_session *sess, /* Try to parse the message */ status = pj_stun_msg_decode(sess->rx_pool, (const pj_uint8_t*)packet, - pkt_size, options, - &msg, parsed_len, &response); + pkt_size, options, + &msg, parsed_len, &response); if (status != PJ_SUCCESS) { - LOG_ERR_(sess, "STUN msg_decode() error", status); - if (response) { - send_response(sess, token, sess->rx_pool, response, NULL, - PJ_FALSE, src_addr, src_addr_len); - } - goto on_return; + LOG_ERR_(sess, "STUN msg_decode() error", status); + if (response) { + send_response(sess, token, sess->rx_pool, response, NULL, + PJ_FALSE, src_addr, src_addr_len); + } + goto on_return; } dump_rx_msg(sess, msg, (unsigned)pkt_size, src_addr); /* For requests, check if we have cached response */ status = check_cached_response(sess, sess->rx_pool, msg, - src_addr, src_addr_len); + src_addr, src_addr_len); if (status == PJ_SUCCESS) { - goto on_return; + goto on_return; } /* Handle message */ if (PJ_STUN_IS_SUCCESS_RESPONSE(msg->hdr.type) || - PJ_STUN_IS_ERROR_RESPONSE(msg->hdr.type)) + PJ_STUN_IS_ERROR_RESPONSE(msg->hdr.type)) { - status = on_incoming_response(sess, options, - (const pj_uint8_t*) packet, - (unsigned)pkt_size, msg, - src_addr, src_addr_len); + status = on_incoming_response(sess, options, + (const pj_uint8_t*) packet, + (unsigned)pkt_size, msg, + src_addr, src_addr_len); } else if (PJ_STUN_IS_REQUEST(msg->hdr.type)) { - status = on_incoming_request(sess, options, token, sess->rx_pool, - (const pj_uint8_t*) packet, - (unsigned)pkt_size, - msg, src_addr, src_addr_len); + status = on_incoming_request(sess, options, token, sess->rx_pool, + (const pj_uint8_t*) packet, + (unsigned)pkt_size, + msg, src_addr, src_addr_len); } else if (PJ_STUN_IS_INDICATION(msg->hdr.type)) { - status = on_incoming_indication(sess, token, sess->rx_pool, - (const pj_uint8_t*) packet, - (unsigned)pkt_size, msg, src_addr, - src_addr_len); + status = on_incoming_indication(sess, token, sess->rx_pool, + (const pj_uint8_t*) packet, + (unsigned)pkt_size, msg, src_addr, + src_addr_len); } else { - pj_assert(!"Unexpected!"); - status = PJ_EBUG; + pj_assert(!"Unexpected!"); + status = PJ_EBUG; } on_return: pj_log_pop_indent(); if (pj_grp_lock_release(sess->grp_lock)) - return PJ_EGONE; + return PJ_EGONE; return status; } diff --git a/pjnath/src/pjnath/stun_sock.c b/pjnath/src/pjnath/stun_sock.c index 5fe825cf5c..14b8f8550f 100644 --- a/pjnath/src/pjnath/stun_sock.c +++ b/pjnath/src/pjnath/stun_sock.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -33,7 +32,7 @@ #include #if 1 -# define TRACE_(x) PJ_LOG(5,x) +# define TRACE_(x) PJ_LOG(5,x) #else # define TRACE_(x) #endif @@ -42,30 +41,30 @@ enum { MAX_BIND_RETRY = 100 }; struct pj_stun_sock { - char *obj_name; /* Log identification */ - pj_pool_t *pool; /* Pool */ - void *user_data; /* Application user data */ - pj_bool_t is_destroying; /* Destroy already called */ - int af; /* Address family */ - pj_stun_config stun_cfg; /* STUN config (ioqueue etc)*/ - pj_stun_sock_cb cb; /* Application callbacks */ - - int ka_interval; /* Keep alive interval */ - pj_timer_entry ka_timer; /* Keep alive timer. */ - - pj_sockaddr srv_addr; /* Resolved server addr */ - pj_sockaddr mapped_addr; /* Our public address */ - - pj_dns_srv_async_query *q; /* Pending DNS query */ - pj_sock_t sock_fd; /* Socket descriptor */ - pj_activesock_t *active_sock; /* Active socket object */ - pj_ioqueue_op_key_t send_key; /* Default send key for app */ - pj_ioqueue_op_key_t int_send_key; /* Send key for internal */ - pj_status_t last_err; /* Last error status */ - - pj_uint16_t tsx_id[6]; /* .. to match STUN msg */ - pj_stun_session *stun_sess; /* STUN session */ - pj_grp_lock_t *grp_lock; /* Session group lock */ + char *obj_name; /* Log identification */ + pj_pool_t *pool; /* Pool */ + void *user_data; /* Application user data */ + pj_bool_t is_destroying; /* Destroy already called */ + int af; /* Address family */ + pj_stun_config stun_cfg; /* STUN config (ioqueue etc)*/ + pj_stun_sock_cb cb; /* Application callbacks */ + + int ka_interval; /* Keep alive interval */ + pj_timer_entry ka_timer; /* Keep alive timer. */ + + pj_sockaddr srv_addr; /* Resolved server addr */ + pj_sockaddr mapped_addr; /* Our public address */ + + pj_dns_srv_async_query *q; /* Pending DNS query */ + pj_sock_t sock_fd; /* Socket descriptor */ + pj_activesock_t *active_sock; /* Active socket object */ + pj_ioqueue_op_key_t send_key; /* Default send key for app */ + pj_ioqueue_op_key_t int_send_key; /* Send key for internal */ + pj_status_t last_err; /* Last error status */ + + pj_uint16_t tsx_id[6]; /* .. to match STUN msg */ + pj_stun_session *stun_sess; /* STUN session */ + pj_grp_lock_t *grp_lock; /* Session group lock */ }; /* @@ -77,42 +76,42 @@ static void stun_sock_destructor(void *obj); /* This callback is called by the STUN session to send packet */ static pj_status_t sess_on_send_msg(pj_stun_session *sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len); + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len); /* This callback is called by the STUN session when outgoing transaction * is complete */ static void sess_on_request_complete(pj_stun_session *sess, - pj_status_t status, - void *token, - pj_stun_tx_data *tdata, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + pj_status_t status, + void *token, + pj_stun_tx_data *tdata, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); /* DNS resolver callback */ static void dns_srv_resolver_cb(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec); + pj_status_t status, + const pj_dns_srv_record *rec); /* Start sending STUN Binding request */ static pj_status_t get_mapped_addr(pj_stun_sock *stun_sock); /* Callback from active socket when incoming packet is received */ static pj_bool_t on_data_recvfrom(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status); + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status); /* Callback from active socket about send status */ static pj_bool_t on_data_sent(pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent); + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent); /* Schedule keep-alive timer */ static void start_ka_timer(pj_stun_sock *stun_sock); @@ -129,11 +128,11 @@ static void ka_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te); PJ_DEF(const char*) pj_stun_sock_op_name(pj_stun_sock_op op) { const char *names[] = { - "?", - "DNS resolution", - "STUN Binding request", - "Keep-alive", - "Mapped addr. changed" + "?", + "DNS resolution", + "STUN Binding request", + "Keep-alive", + "Mapped addr. changed" }; return op < PJ_ARRAY_SIZE(names) ? names[op] : "???"; @@ -164,12 +163,12 @@ static pj_bool_t pj_stun_sock_cfg_is_valid(const pj_stun_sock_cfg *cfg) * Create the STUN transport using the specified configuration. */ PJ_DEF(pj_status_t) pj_stun_sock_create( pj_stun_config *stun_cfg, - const char *name, - int af, - const pj_stun_sock_cb *cb, - const pj_stun_sock_cfg *cfg, - void *user_data, - pj_stun_sock **p_stun_sock) + const char *name, + int af, + const pj_stun_sock_cb *cb, + const pj_stun_sock_cfg *cfg, + void *user_data, + pj_stun_sock **p_stun_sock) { pj_pool_t *pool; pj_stun_sock *stun_sock; @@ -186,14 +185,14 @@ PJ_DEF(pj_status_t) pj_stun_sock_create( pj_stun_config *stun_cfg, status = pj_stun_config_check_valid(stun_cfg); if (status != PJ_SUCCESS) - return status; + return status; if (name == NULL) - name = "stuntp%p"; + name = "stuntp%p"; if (cfg == NULL) { - pj_stun_sock_cfg_default(&default_cfg); - cfg = &default_cfg; + pj_stun_sock_cfg_default(&default_cfg); + cfg = &default_cfg; } @@ -210,155 +209,155 @@ PJ_DEF(pj_status_t) pj_stun_sock_create( pj_stun_config *stun_cfg, stun_sock->ka_interval = cfg->ka_interval; if (stun_sock->ka_interval == 0) - stun_sock->ka_interval = PJ_STUN_KEEP_ALIVE_SEC; + stun_sock->ka_interval = PJ_STUN_KEEP_ALIVE_SEC; if (cfg->grp_lock) { - stun_sock->grp_lock = cfg->grp_lock; + stun_sock->grp_lock = cfg->grp_lock; } else { - status = pj_grp_lock_create(pool, NULL, &stun_sock->grp_lock); - if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; - } + status = pj_grp_lock_create(pool, NULL, &stun_sock->grp_lock); + if (status != PJ_SUCCESS) { + pj_pool_release(pool); + return status; + } } pj_grp_lock_add_ref(stun_sock->grp_lock); pj_grp_lock_add_handler(stun_sock->grp_lock, pool, stun_sock, - &stun_sock_destructor); + &stun_sock_destructor); /* Create socket and bind socket */ status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &stun_sock->sock_fd); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Apply QoS, if specified */ status = pj_sock_apply_qos2(stun_sock->sock_fd, cfg->qos_type, - &cfg->qos_params, 2, stun_sock->obj_name, - NULL); + &cfg->qos_params, 2, stun_sock->obj_name, + NULL); if (status != PJ_SUCCESS && !cfg->qos_ignore_error) - goto on_error; + goto on_error; /* Apply socket buffer size */ if (cfg->so_rcvbuf_size > 0) { - unsigned sobuf_size = cfg->so_rcvbuf_size; - status = pj_sock_setsockopt_sobuf(stun_sock->sock_fd, pj_SO_RCVBUF(), - PJ_TRUE, &sobuf_size); - if (status != PJ_SUCCESS) { - PJ_PERROR(3, (stun_sock->obj_name, status, - "Failed setting SO_RCVBUF")); - } else { - if (sobuf_size < cfg->so_rcvbuf_size) { - PJ_LOG(4, (stun_sock->obj_name, - "Warning! Cannot set SO_RCVBUF as configured, " - "now=%d, configured=%d", - sobuf_size, cfg->so_rcvbuf_size)); - } else { - PJ_LOG(5, (stun_sock->obj_name, "SO_RCVBUF set to %d", - sobuf_size)); - } - } + unsigned sobuf_size = cfg->so_rcvbuf_size; + status = pj_sock_setsockopt_sobuf(stun_sock->sock_fd, pj_SO_RCVBUF(), + PJ_TRUE, &sobuf_size); + if (status != PJ_SUCCESS) { + PJ_PERROR(3, (stun_sock->obj_name, status, + "Failed setting SO_RCVBUF")); + } else { + if (sobuf_size < cfg->so_rcvbuf_size) { + PJ_LOG(4, (stun_sock->obj_name, + "Warning! Cannot set SO_RCVBUF as configured, " + "now=%d, configured=%d", + sobuf_size, cfg->so_rcvbuf_size)); + } else { + PJ_LOG(5, (stun_sock->obj_name, "SO_RCVBUF set to %d", + sobuf_size)); + } + } } if (cfg->so_sndbuf_size > 0) { - unsigned sobuf_size = cfg->so_sndbuf_size; - status = pj_sock_setsockopt_sobuf(stun_sock->sock_fd, pj_SO_SNDBUF(), - PJ_TRUE, &sobuf_size); - if (status != PJ_SUCCESS) { - PJ_PERROR(3, (stun_sock->obj_name, status, - "Failed setting SO_SNDBUF")); - } else { - if (sobuf_size < cfg->so_sndbuf_size) { - PJ_LOG(4, (stun_sock->obj_name, - "Warning! Cannot set SO_SNDBUF as configured, " - "now=%d, configured=%d", - sobuf_size, cfg->so_sndbuf_size)); - } else { - PJ_LOG(5, (stun_sock->obj_name, "SO_SNDBUF set to %d", - sobuf_size)); - } - } + unsigned sobuf_size = cfg->so_sndbuf_size; + status = pj_sock_setsockopt_sobuf(stun_sock->sock_fd, pj_SO_SNDBUF(), + PJ_TRUE, &sobuf_size); + if (status != PJ_SUCCESS) { + PJ_PERROR(3, (stun_sock->obj_name, status, + "Failed setting SO_SNDBUF")); + } else { + if (sobuf_size < cfg->so_sndbuf_size) { + PJ_LOG(4, (stun_sock->obj_name, + "Warning! Cannot set SO_SNDBUF as configured, " + "now=%d, configured=%d", + sobuf_size, cfg->so_sndbuf_size)); + } else { + PJ_LOG(5, (stun_sock->obj_name, "SO_SNDBUF set to %d", + sobuf_size)); + } + } } /* Bind socket */ max_bind_retry = MAX_BIND_RETRY; if (cfg->port_range && cfg->port_range < max_bind_retry) - max_bind_retry = cfg->port_range; + max_bind_retry = cfg->port_range; pj_sockaddr_init(af, &bound_addr, NULL, 0); if (cfg->bound_addr.addr.sa_family == pj_AF_INET() || - cfg->bound_addr.addr.sa_family == pj_AF_INET6()) + cfg->bound_addr.addr.sa_family == pj_AF_INET6()) { - pj_sockaddr_cp(&bound_addr, &cfg->bound_addr); + pj_sockaddr_cp(&bound_addr, &cfg->bound_addr); } status = pj_sock_bind_random(stun_sock->sock_fd, &bound_addr, - cfg->port_range, max_bind_retry); + cfg->port_range, max_bind_retry); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create more useful information string about this transport */ #if 0 { - pj_sockaddr bound_addr; - int addr_len = sizeof(bound_addr); + pj_sockaddr bound_addr; + int addr_len = sizeof(bound_addr); - status = pj_sock_getsockname(stun_sock->sock_fd, &bound_addr, - &addr_len); - if (status != PJ_SUCCESS) - goto on_error; + status = pj_sock_getsockname(stun_sock->sock_fd, &bound_addr, + &addr_len); + if (status != PJ_SUCCESS) + goto on_error; - stun_sock->info = pj_pool_alloc(pool, PJ_INET6_ADDRSTRLEN+10); - pj_sockaddr_print(&bound_addr, stun_sock->info, - PJ_INET6_ADDRSTRLEN, 3); + stun_sock->info = pj_pool_alloc(pool, PJ_INET6_ADDRSTRLEN+10); + pj_sockaddr_print(&bound_addr, stun_sock->info, + PJ_INET6_ADDRSTRLEN, 3); } #endif /* Init active socket configuration */ { - pj_activesock_cfg activesock_cfg; - pj_activesock_cb activesock_cb; - - pj_activesock_cfg_default(&activesock_cfg); - activesock_cfg.grp_lock = stun_sock->grp_lock; - activesock_cfg.async_cnt = cfg->async_cnt; - activesock_cfg.concurrency = 0; - - /* Create the active socket */ - pj_bzero(&activesock_cb, sizeof(activesock_cb)); - activesock_cb.on_data_recvfrom = &on_data_recvfrom; - activesock_cb.on_data_sent = &on_data_sent; - status = pj_activesock_create(pool, stun_sock->sock_fd, - pj_SOCK_DGRAM(), - &activesock_cfg, stun_cfg->ioqueue, - &activesock_cb, stun_sock, - &stun_sock->active_sock); - if (status != PJ_SUCCESS) - goto on_error; - - /* Start asynchronous read operations */ - status = pj_activesock_start_recvfrom(stun_sock->active_sock, pool, - cfg->max_pkt_size, 0); - if (status != PJ_SUCCESS) - goto on_error; - - /* Init send keys */ - pj_ioqueue_op_key_init(&stun_sock->send_key, - sizeof(stun_sock->send_key)); - pj_ioqueue_op_key_init(&stun_sock->int_send_key, - sizeof(stun_sock->int_send_key)); + pj_activesock_cfg activesock_cfg; + pj_activesock_cb activesock_cb; + + pj_activesock_cfg_default(&activesock_cfg); + activesock_cfg.grp_lock = stun_sock->grp_lock; + activesock_cfg.async_cnt = cfg->async_cnt; + activesock_cfg.concurrency = 0; + + /* Create the active socket */ + pj_bzero(&activesock_cb, sizeof(activesock_cb)); + activesock_cb.on_data_recvfrom = &on_data_recvfrom; + activesock_cb.on_data_sent = &on_data_sent; + status = pj_activesock_create(pool, stun_sock->sock_fd, + pj_SOCK_DGRAM(), + &activesock_cfg, stun_cfg->ioqueue, + &activesock_cb, stun_sock, + &stun_sock->active_sock); + if (status != PJ_SUCCESS) + goto on_error; + + /* Start asynchronous read operations */ + status = pj_activesock_start_recvfrom(stun_sock->active_sock, pool, + cfg->max_pkt_size, 0); + if (status != PJ_SUCCESS) + goto on_error; + + /* Init send keys */ + pj_ioqueue_op_key_init(&stun_sock->send_key, + sizeof(stun_sock->send_key)); + pj_ioqueue_op_key_init(&stun_sock->int_send_key, + sizeof(stun_sock->int_send_key)); } /* Create STUN session */ { - pj_stun_session_cb sess_cb; - - pj_bzero(&sess_cb, sizeof(sess_cb)); - sess_cb.on_request_complete = &sess_on_request_complete; - sess_cb.on_send_msg = &sess_on_send_msg; - status = pj_stun_session_create(&stun_sock->stun_cfg, - stun_sock->obj_name, - &sess_cb, PJ_FALSE, - stun_sock->grp_lock, - &stun_sock->stun_sess); - if (status != PJ_SUCCESS) - goto on_error; + pj_stun_session_cb sess_cb; + + pj_bzero(&sess_cb, sizeof(sess_cb)); + sess_cb.on_request_complete = &sess_on_request_complete; + sess_cb.on_send_msg = &sess_on_send_msg; + status = pj_stun_session_create(&stun_sock->stun_cfg, + stun_sock->obj_name, + &sess_cb, PJ_FALSE, + stun_sock->grp_lock, + &stun_sock->stun_sess); + if (status != PJ_SUCCESS) + goto on_error; } /* Associate us with the STUN session */ @@ -370,7 +369,7 @@ PJ_DEF(pj_status_t) pj_stun_sock_create( pj_stun_config *stun_cfg, * The last 16bit value in the array is a counter. */ for (i=0; itsx_id); ++i) { - stun_sock->tsx_id[i] = (pj_uint16_t) pj_rand(); + stun_sock->tsx_id[i] = (pj_uint16_t) pj_rand(); } stun_sock->tsx_id[5] = 0; @@ -390,9 +389,9 @@ PJ_DEF(pj_status_t) pj_stun_sock_create( pj_stun_config *stun_cfg, /* Start socket. */ PJ_DEF(pj_status_t) pj_stun_sock_start( pj_stun_sock *stun_sock, - const pj_str_t *domain, - pj_uint16_t default_port, - pj_dns_resolver *resolver) + const pj_str_t *domain, + pj_uint16_t default_port, + pj_dns_resolver *resolver) { pj_status_t status; @@ -403,75 +402,75 @@ PJ_DEF(pj_status_t) pj_stun_sock_start( pj_stun_sock *stun_sock, /* Check whether the domain contains IP address */ stun_sock->srv_addr.addr.sa_family = (pj_uint16_t)stun_sock->af; status = pj_inet_pton(stun_sock->af, domain, - pj_sockaddr_get_addr(&stun_sock->srv_addr)); + pj_sockaddr_get_addr(&stun_sock->srv_addr)); if (status != PJ_SUCCESS) { - stun_sock->srv_addr.addr.sa_family = (pj_uint16_t)0; + stun_sock->srv_addr.addr.sa_family = (pj_uint16_t)0; } /* If resolver is set, try to resolve with DNS SRV first. It * will fallback to DNS A/AAAA when no SRV record is found. */ if (status != PJ_SUCCESS && resolver) { - const pj_str_t res_name = pj_str("_stun._udp."); - unsigned opt; - - pj_assert(stun_sock->q == NULL); - - /* Init DNS resolution option */ - if (stun_sock->af == pj_AF_INET6()) - opt = (PJ_DNS_SRV_RESOLVE_AAAA_ONLY | PJ_DNS_SRV_FALLBACK_AAAA); - else - opt = PJ_DNS_SRV_FALLBACK_A; - - stun_sock->last_err = PJ_SUCCESS; - status = pj_dns_srv_resolve(domain, &res_name, default_port, - stun_sock->pool, resolver, opt, - stun_sock, &dns_srv_resolver_cb, - &stun_sock->q); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stun_sock->obj_name, status, - "Failed in pj_dns_srv_resolve()")); - } else { - /* DNS SRV callback may have been called here, such as when - * the result is cached, so we need to check the last error - * status. If the callback hasn't been called, processing - * will resume later. - */ - status = stun_sock->last_err; - if (stun_sock->last_err != PJ_SUCCESS) { - PJ_PERROR(4,(stun_sock->obj_name, status, - "Failed in sending Binding request (2)")); - } - } + const pj_str_t res_name = pj_str("_stun._udp."); + unsigned opt; + + pj_assert(stun_sock->q == NULL); + + /* Init DNS resolution option */ + if (stun_sock->af == pj_AF_INET6()) + opt = (PJ_DNS_SRV_RESOLVE_AAAA_ONLY | PJ_DNS_SRV_FALLBACK_AAAA); + else + opt = PJ_DNS_SRV_FALLBACK_A; + + stun_sock->last_err = PJ_SUCCESS; + status = pj_dns_srv_resolve(domain, &res_name, default_port, + stun_sock->pool, resolver, opt, + stun_sock, &dns_srv_resolver_cb, + &stun_sock->q); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stun_sock->obj_name, status, + "Failed in pj_dns_srv_resolve()")); + } else { + /* DNS SRV callback may have been called here, such as when + * the result is cached, so we need to check the last error + * status. If the callback hasn't been called, processing + * will resume later. + */ + status = stun_sock->last_err; + if (stun_sock->last_err != PJ_SUCCESS) { + PJ_PERROR(4,(stun_sock->obj_name, status, + "Failed in sending Binding request (2)")); + } + } } else { - if (status != PJ_SUCCESS) { - pj_addrinfo ai; - unsigned cnt = 1; + if (status != PJ_SUCCESS) { + pj_addrinfo ai; + unsigned cnt = 1; - status = pj_getaddrinfo(stun_sock->af, domain, &cnt, &ai); - if (cnt == 0) - status = PJ_EAFNOTSUP; + status = pj_getaddrinfo(stun_sock->af, domain, &cnt, &ai); + if (cnt == 0) + status = PJ_EAFNOTSUP; - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stun_sock->obj_name, status, - "Failed in pj_getaddrinfo()")); - pj_grp_lock_release(stun_sock->grp_lock); - return status; - } + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stun_sock->obj_name, status, + "Failed in pj_getaddrinfo()")); + pj_grp_lock_release(stun_sock->grp_lock); + return status; + } - pj_sockaddr_cp(&stun_sock->srv_addr, &ai.ai_addr); - } + pj_sockaddr_cp(&stun_sock->srv_addr, &ai.ai_addr); + } - pj_sockaddr_set_port(&stun_sock->srv_addr, (pj_uint16_t)default_port); + pj_sockaddr_set_port(&stun_sock->srv_addr, (pj_uint16_t)default_port); - /* Start sending Binding request */ - status = get_mapped_addr(stun_sock); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stun_sock->obj_name, status, - "Failed in sending Binding request")); - } + /* Start sending Binding request */ + status = get_mapped_addr(stun_sock); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stun_sock->obj_name, status, + "Failed in sending Binding request")); + } } pj_grp_lock_release(stun_sock->grp_lock); @@ -484,14 +483,14 @@ static void stun_sock_destructor(void *obj) pj_stun_sock *stun_sock = (pj_stun_sock*)obj; if (stun_sock->q) { - pj_dns_srv_cancel_query(stun_sock->q, PJ_FALSE); - stun_sock->q = NULL; + pj_dns_srv_cancel_query(stun_sock->q, PJ_FALSE); + stun_sock->q = NULL; } /* if (stun_sock->stun_sess) { - pj_stun_session_destroy(stun_sock->stun_sess); - stun_sock->stun_sess = NULL; + pj_stun_session_destroy(stun_sock->stun_sess); + stun_sock->stun_sess = NULL; } */ @@ -505,13 +504,13 @@ static void stun_sock_destructor(void *obj) PJ_DEF(pj_status_t) pj_stun_sock_destroy(pj_stun_sock *stun_sock) { TRACE_((stun_sock->obj_name, "STUN sock %p request, ref_cnt=%d", - stun_sock, pj_grp_lock_get_ref(stun_sock->grp_lock))); + stun_sock, pj_grp_lock_get_ref(stun_sock->grp_lock))); pj_grp_lock_acquire(stun_sock->grp_lock); if (stun_sock->is_destroying) { - /* Destroy already called */ - pj_grp_lock_release(stun_sock->grp_lock); - return PJ_EINVALIDOP; + /* Destroy already called */ + pj_grp_lock_release(stun_sock->grp_lock); + return PJ_EINVALIDOP; } stun_sock->is_destroying = PJ_TRUE; @@ -519,15 +518,15 @@ PJ_DEF(pj_status_t) pj_stun_sock_destroy(pj_stun_sock *stun_sock) &stun_sock->ka_timer, 0); if (stun_sock->active_sock != NULL) { - stun_sock->sock_fd = PJ_INVALID_SOCKET; - pj_activesock_close(stun_sock->active_sock); + stun_sock->sock_fd = PJ_INVALID_SOCKET; + pj_activesock_close(stun_sock->active_sock); } else if (stun_sock->sock_fd != PJ_INVALID_SOCKET) { - pj_sock_close(stun_sock->sock_fd); - stun_sock->sock_fd = PJ_INVALID_SOCKET; + pj_sock_close(stun_sock->sock_fd); + stun_sock->sock_fd = PJ_INVALID_SOCKET; } if (stun_sock->stun_sess) { - pj_stun_session_destroy(stun_sock->stun_sess); + pj_stun_session_destroy(stun_sock->stun_sess); } pj_grp_lock_dec_ref(stun_sock->grp_lock); pj_grp_lock_release(stun_sock->grp_lock); @@ -536,7 +535,7 @@ PJ_DEF(pj_status_t) pj_stun_sock_destroy(pj_stun_sock *stun_sock) /* Associate user data */ PJ_DEF(pj_status_t) pj_stun_sock_set_user_data( pj_stun_sock *stun_sock, - void *user_data) + void *user_data) { PJ_ASSERT_RETURN(stun_sock, PJ_EINVAL); stun_sock->user_data = user_data; @@ -560,14 +559,14 @@ PJ_DECL(pj_grp_lock_t *) pj_stun_sock_get_grp_lock(pj_stun_sock *stun_sock) /* Notify application that session has failed */ static pj_bool_t sess_fail(pj_stun_sock *stun_sock, - pj_stun_sock_op op, - pj_status_t status) + pj_stun_sock_op op, + pj_status_t status) { pj_bool_t ret; PJ_PERROR(4,(stun_sock->obj_name, status, - "Session failed because %s failed", - pj_stun_sock_op_name(op))); + "Session failed because %s failed", + pj_stun_sock_op_name(op))); ret = (*stun_sock->cb.on_status)(stun_sock, op, status); @@ -576,8 +575,8 @@ static pj_bool_t sess_fail(pj_stun_sock *stun_sock, /* DNS resolver callback */ static void dns_srv_resolver_cb(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec) + pj_status_t status, + const pj_dns_srv_record *rec) { pj_stun_sock *stun_sock = (pj_stun_sock*) user_data; @@ -589,9 +588,9 @@ static void dns_srv_resolver_cb(void *user_data, /* Handle error */ if (status != PJ_SUCCESS) { stun_sock->last_err = status; - sess_fail(stun_sock, PJ_STUN_SOCK_DNS_OP, status); - pj_grp_lock_release(stun_sock->grp_lock); - return; + sess_fail(stun_sock, PJ_STUN_SOCK_DNS_OP, status); + pj_grp_lock_release(stun_sock->grp_lock); + return; } pj_assert(rec->count); @@ -600,13 +599,13 @@ static void dns_srv_resolver_cb(void *user_data, /* Set the address */ pj_sockaddr_init(stun_sock->af, &stun_sock->srv_addr, NULL, - rec->entry[0].port); + rec->entry[0].port); if (stun_sock->af == pj_AF_INET6()) { - stun_sock->srv_addr.ipv6.sin6_addr = - rec->entry[0].server.addr[0].ip.v6; + stun_sock->srv_addr.ipv6.sin6_addr = + rec->entry[0].server.addr[0].ip.v6; } else { - stun_sock->srv_addr.ipv4.sin_addr = - rec->entry[0].server.addr[0].ip.v4; + stun_sock->srv_addr.ipv4.sin_addr = + rec->entry[0].server.addr[0].ip.v4; } /* Start sending Binding request */ @@ -625,20 +624,20 @@ static pj_status_t get_mapped_addr(pj_stun_sock *stun_sock) /* Increment request counter and create STUN Binding request */ ++stun_sock->tsx_id[5]; status = pj_stun_session_create_req(stun_sock->stun_sess, - PJ_STUN_BINDING_REQUEST, - PJ_STUN_MAGIC, - (const pj_uint8_t*)stun_sock->tsx_id, - &tdata); + PJ_STUN_BINDING_REQUEST, + PJ_STUN_MAGIC, + (const pj_uint8_t*)stun_sock->tsx_id, + &tdata); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Send request */ status=pj_stun_session_send_msg(stun_sock->stun_sess, INTERNAL_MSG_TOKEN, - PJ_FALSE, PJ_TRUE, &stun_sock->srv_addr, - pj_sockaddr_get_len(&stun_sock->srv_addr), - tdata); + PJ_FALSE, PJ_TRUE, &stun_sock->srv_addr, + pj_sockaddr_get_len(&stun_sock->srv_addr), + tdata); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; return PJ_SUCCESS; @@ -649,7 +648,7 @@ static pj_status_t get_mapped_addr(pj_stun_sock *stun_sock) /* Get info */ PJ_DEF(pj_status_t) pj_stun_sock_get_info( pj_stun_sock *stun_sock, - pj_stun_sock_info *info) + pj_stun_sock_info *info) { int addr_len; pj_status_t status; @@ -660,17 +659,17 @@ PJ_DEF(pj_status_t) pj_stun_sock_get_info( pj_stun_sock *stun_sock, /* Copy STUN server address and mapped address */ pj_memcpy(&info->srv_addr, &stun_sock->srv_addr, - sizeof(pj_sockaddr)); + sizeof(pj_sockaddr)); pj_memcpy(&info->mapped_addr, &stun_sock->mapped_addr, - sizeof(pj_sockaddr)); + sizeof(pj_sockaddr)); /* Retrieve bound address */ addr_len = sizeof(info->bound_addr); status = pj_sock_getsockname(stun_sock->sock_fd, &info->bound_addr, - &addr_len); + &addr_len); if (status != PJ_SUCCESS) { - pj_grp_lock_release(stun_sock->grp_lock); - return status; + pj_grp_lock_release(stun_sock->grp_lock); + return status; } /* If socket is bound to a specific interface, then only put that @@ -678,64 +677,64 @@ PJ_DEF(pj_status_t) pj_stun_sock_get_info( pj_stun_sock *stun_sock, * in the host. */ if (pj_sockaddr_has_addr(&info->bound_addr)) { - info->alias_cnt = 1; - pj_sockaddr_cp(&info->aliases[0], &info->bound_addr); + info->alias_cnt = 1; + pj_sockaddr_cp(&info->aliases[0], &info->bound_addr); } else { - pj_sockaddr def_addr; - pj_uint16_t port = pj_sockaddr_get_port(&info->bound_addr); - pj_enum_ip_option enum_opt; - unsigned i; - - /* Get the default address */ - status = pj_gethostip(stun_sock->af, &def_addr); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(stun_sock->obj_name, status, - "Failed in getting default address for STUN info")); - pj_grp_lock_release(stun_sock->grp_lock); - return status; - } - - pj_sockaddr_set_port(&def_addr, port); - - /* Enum all IP interfaces in the host */ - pj_enum_ip_option_default(&enum_opt); - enum_opt.af = stun_sock->af; - enum_opt.omit_deprecated_ipv6 = PJ_TRUE; - info->alias_cnt = PJ_ARRAY_SIZE(info->aliases); - status = pj_enum_ip_interface2(&enum_opt, &info->alias_cnt, - info->aliases); - if (status == PJ_ENOTSUP) { - /* Try again without omitting deprecated IPv6 addresses */ - enum_opt.omit_deprecated_ipv6 = PJ_FALSE; - status = pj_enum_ip_interface2(&enum_opt, &info->alias_cnt, - info->aliases); - } - - if (status != PJ_SUCCESS) { - /* If enumeration fails, just return the default address */ - PJ_PERROR(4,(stun_sock->obj_name, status, - "Failed in enumerating interfaces for STUN info, " - "returning default address only")); - info->alias_cnt = 1; - pj_sockaddr_cp(&info->aliases[0], &def_addr); - } - - /* Set the port number for each address. - */ - for (i=0; ialias_cnt; ++i) { - pj_sockaddr_set_port(&info->aliases[i], port); - } - - /* Put the default IP in the first slot */ - for (i=0; ialias_cnt; ++i) { - if (pj_sockaddr_cmp(&info->aliases[i], &def_addr)==0) { - if (i!=0) { - pj_sockaddr_cp(&info->aliases[i], &info->aliases[0]); - pj_sockaddr_cp(&info->aliases[0], &def_addr); - } - break; - } - } + pj_sockaddr def_addr; + pj_uint16_t port = pj_sockaddr_get_port(&info->bound_addr); + pj_enum_ip_option enum_opt; + unsigned i; + + /* Get the default address */ + status = pj_gethostip(stun_sock->af, &def_addr); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(stun_sock->obj_name, status, + "Failed in getting default address for STUN info")); + pj_grp_lock_release(stun_sock->grp_lock); + return status; + } + + pj_sockaddr_set_port(&def_addr, port); + + /* Enum all IP interfaces in the host */ + pj_enum_ip_option_default(&enum_opt); + enum_opt.af = stun_sock->af; + enum_opt.omit_deprecated_ipv6 = PJ_TRUE; + info->alias_cnt = PJ_ARRAY_SIZE(info->aliases); + status = pj_enum_ip_interface2(&enum_opt, &info->alias_cnt, + info->aliases); + if (status == PJ_ENOTSUP) { + /* Try again without omitting deprecated IPv6 addresses */ + enum_opt.omit_deprecated_ipv6 = PJ_FALSE; + status = pj_enum_ip_interface2(&enum_opt, &info->alias_cnt, + info->aliases); + } + + if (status != PJ_SUCCESS) { + /* If enumeration fails, just return the default address */ + PJ_PERROR(4,(stun_sock->obj_name, status, + "Failed in enumerating interfaces for STUN info, " + "returning default address only")); + info->alias_cnt = 1; + pj_sockaddr_cp(&info->aliases[0], &def_addr); + } + + /* Set the port number for each address. + */ + for (i=0; ialias_cnt; ++i) { + pj_sockaddr_set_port(&info->aliases[i], port); + } + + /* Put the default IP in the first slot */ + for (i=0; ialias_cnt; ++i) { + if (pj_sockaddr_cmp(&info->aliases[i], &def_addr)==0) { + if (i!=0) { + pj_sockaddr_cp(&info->aliases[i], &info->aliases[0]); + pj_sockaddr_cp(&info->aliases[0], &def_addr); + } + break; + } + } } pj_grp_lock_release(stun_sock->grp_lock); @@ -744,12 +743,12 @@ PJ_DEF(pj_status_t) pj_stun_sock_get_info( pj_stun_sock *stun_sock, /* Send application data */ PJ_DEF(pj_status_t) pj_stun_sock_sendto( pj_stun_sock *stun_sock, - pj_ioqueue_op_key_t *send_key, - const void *pkt, - unsigned pkt_len, - unsigned flag, - const pj_sockaddr_t *dst_addr, - unsigned addr_len) + pj_ioqueue_op_key_t *send_key, + const void *pkt, + unsigned pkt_len, + unsigned flag, + const pj_sockaddr_t *dst_addr, + unsigned addr_len) { pj_ssize_t size; pj_status_t status; @@ -759,15 +758,15 @@ PJ_DEF(pj_status_t) pj_stun_sock_sendto( pj_stun_sock *stun_sock, pj_grp_lock_acquire(stun_sock->grp_lock); if (!stun_sock->active_sock) { - /* We have been shutdown, but this callback may still get called - * by retransmit timer. - */ - pj_grp_lock_release(stun_sock->grp_lock); - return PJ_EINVALIDOP; + /* We have been shutdown, but this callback may still get called + * by retransmit timer. + */ + pj_grp_lock_release(stun_sock->grp_lock); + return PJ_EINVALIDOP; } if (send_key==NULL) - send_key = &stun_sock->send_key; + send_key = &stun_sock->send_key; size = pkt_len; status = pj_activesock_sendto(stun_sock->active_sock, send_key, @@ -779,21 +778,21 @@ PJ_DEF(pj_status_t) pj_stun_sock_sendto( pj_stun_sock *stun_sock, /* This callback is called by the STUN session to send packet */ static pj_status_t sess_on_send_msg(pj_stun_session *sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len) + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len) { pj_stun_sock *stun_sock; pj_ssize_t size; stun_sock = (pj_stun_sock *) pj_stun_session_get_user_data(sess); if (!stun_sock || !stun_sock->active_sock) { - /* We have been shutdown, but this callback may still get called - * by retransmit timer. - */ - return PJ_EINVALIDOP; + /* We have been shutdown, but this callback may still get called + * by retransmit timer. + */ + return PJ_EINVALIDOP; } pj_assert(token==INTERNAL_MSG_TOKEN); @@ -801,20 +800,20 @@ static pj_status_t sess_on_send_msg(pj_stun_session *sess, size = pkt_size; return pj_activesock_sendto(stun_sock->active_sock, - &stun_sock->int_send_key, - pkt, &size, 0, dst_addr, addr_len); + &stun_sock->int_send_key, + pkt, &size, 0, dst_addr, addr_len); } /* This callback is called by the STUN session when outgoing transaction * is complete */ static void sess_on_request_complete(pj_stun_session *sess, - pj_status_t status, - void *token, - pj_stun_tx_data *tdata, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + pj_status_t status, + void *token, + pj_stun_tx_data *tdata, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_stun_sock *stun_sock; const pj_stun_sockaddr_attr *mapped_attr; @@ -824,7 +823,7 @@ static void sess_on_request_complete(pj_stun_session *sess, stun_sock = (pj_stun_sock *) pj_stun_session_get_user_data(sess); if (!stun_sock) - return; + return; PJ_UNUSED_ARG(tdata); PJ_UNUSED_ARG(token); @@ -833,53 +832,53 @@ static void sess_on_request_complete(pj_stun_session *sess, /* Check if this is a keep-alive or the first Binding request */ if (pj_sockaddr_has_addr(&stun_sock->mapped_addr)) - op = PJ_STUN_SOCK_KEEP_ALIVE_OP; + op = PJ_STUN_SOCK_KEEP_ALIVE_OP; else - op = PJ_STUN_SOCK_BINDING_OP; + op = PJ_STUN_SOCK_BINDING_OP; /* Handle failure */ if (status != PJ_SUCCESS) { - resched = sess_fail(stun_sock, op, status); - goto on_return; + resched = sess_fail(stun_sock, op, status); + goto on_return; } /* Get XOR-MAPPED-ADDRESS, or MAPPED-ADDRESS when XOR-MAPPED-ADDRESS * doesn't exist. */ mapped_attr = (const pj_stun_sockaddr_attr*) - pj_stun_msg_find_attr(response, PJ_STUN_ATTR_XOR_MAPPED_ADDR, - 0); + pj_stun_msg_find_attr(response, PJ_STUN_ATTR_XOR_MAPPED_ADDR, + 0); if (mapped_attr==NULL) { - mapped_attr = (const pj_stun_sockaddr_attr*) - pj_stun_msg_find_attr(response, PJ_STUN_ATTR_MAPPED_ADDR, - 0); + mapped_attr = (const pj_stun_sockaddr_attr*) + pj_stun_msg_find_attr(response, PJ_STUN_ATTR_MAPPED_ADDR, + 0); } if (mapped_attr == NULL) { - resched = sess_fail(stun_sock, op, PJNATH_ESTUNNOMAPPEDADDR); - goto on_return; + resched = sess_fail(stun_sock, op, PJNATH_ESTUNNOMAPPEDADDR); + goto on_return; } /* Determine if mapped address has changed, and save the new mapped * address and call callback if so */ mapped_changed = !pj_sockaddr_has_addr(&stun_sock->mapped_addr) || - pj_sockaddr_cmp(&stun_sock->mapped_addr, - &mapped_attr->sockaddr) != 0; + pj_sockaddr_cmp(&stun_sock->mapped_addr, + &mapped_attr->sockaddr) != 0; if (mapped_changed) { - /* Print mapped adress */ - { - char addrinfo[PJ_INET6_ADDRSTRLEN+10]; - PJ_LOG(4,(stun_sock->obj_name, - "STUN mapped address found/changed: %s", - pj_sockaddr_print(&mapped_attr->sockaddr, - addrinfo, sizeof(addrinfo), 3))); - } - - pj_sockaddr_cp(&stun_sock->mapped_addr, &mapped_attr->sockaddr); - - if (op==PJ_STUN_SOCK_KEEP_ALIVE_OP) - op = PJ_STUN_SOCK_MAPPED_ADDR_CHANGE; + /* Print mapped adress */ + { + char addrinfo[PJ_INET6_ADDRSTRLEN+10]; + PJ_LOG(4,(stun_sock->obj_name, + "STUN mapped address found/changed: %s", + pj_sockaddr_print(&mapped_attr->sockaddr, + addrinfo, sizeof(addrinfo), 3))); + } + + pj_sockaddr_cp(&stun_sock->mapped_addr, &mapped_attr->sockaddr); + + if (op==PJ_STUN_SOCK_KEEP_ALIVE_OP) + op = PJ_STUN_SOCK_MAPPED_ADDR_CHANGE; } /* Notify user */ @@ -888,7 +887,7 @@ static void sess_on_request_complete(pj_stun_session *sess, on_return: /* Start/restart keep-alive timer */ if (resched) - start_ka_timer(stun_sock); + start_ka_timer(stun_sock); } /* Schedule keep-alive timer */ @@ -899,15 +898,15 @@ static void start_ka_timer(pj_stun_sock *stun_sock) pj_assert(stun_sock->ka_interval != 0); if (stun_sock->ka_interval > 0 && !stun_sock->is_destroying) { - pj_time_val delay; + pj_time_val delay; - delay.sec = stun_sock->ka_interval; - delay.msec = 0; + delay.sec = stun_sock->ka_interval; + delay.msec = 0; - pj_timer_heap_schedule_w_grp_lock(stun_sock->stun_cfg.timer_heap, - &stun_sock->ka_timer, - &delay, PJ_TRUE, - stun_sock->grp_lock); + pj_timer_heap_schedule_w_grp_lock(stun_sock->stun_cfg.timer_heap, + &stun_sock->ka_timer, + &delay, PJ_TRUE, + stun_sock->grp_lock); } } @@ -923,8 +922,8 @@ static void ka_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te) /* Time to send STUN Binding request */ if (get_mapped_addr(stun_sock) != PJ_SUCCESS) { - pj_grp_lock_release(stun_sock->grp_lock); - return; + pj_grp_lock_release(stun_sock->grp_lock); + return; } /* Next keep-alive timer will be scheduled once the request @@ -935,11 +934,11 @@ static void ka_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te) /* Callback from active socket when incoming packet is received */ static pj_bool_t on_data_recvfrom(pj_activesock_t *asock, - void *data, - pj_size_t size, - const pj_sockaddr_t *src_addr, - int addr_len, - pj_status_t status) + void *data, + pj_size_t size, + const pj_sockaddr_t *src_addr, + int addr_len, + pj_status_t status) { pj_stun_sock *stun_sock; pj_stun_msg_hdr *hdr; @@ -947,22 +946,22 @@ static pj_bool_t on_data_recvfrom(pj_activesock_t *asock, stun_sock = (pj_stun_sock*) pj_activesock_get_user_data(asock); if (!stun_sock) - return PJ_FALSE; + return PJ_FALSE; /* Log socket error */ if (status != PJ_SUCCESS) { - PJ_PERROR(2,(stun_sock->obj_name, status, "recvfrom() error")); - return PJ_TRUE; + PJ_PERROR(2,(stun_sock->obj_name, status, "recvfrom() error")); + return PJ_TRUE; } pj_grp_lock_acquire(stun_sock->grp_lock); /* Check that this is STUN message */ status = pj_stun_msg_check((const pj_uint8_t*)data, size, - PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET); + PJ_STUN_IS_DATAGRAM | PJ_STUN_CHECK_PACKET); if (status != PJ_SUCCESS) { - /* Not STUN -- give it to application */ - goto process_app_data; + /* Not STUN -- give it to application */ + goto process_app_data; } /* Treat packet as STUN header and copy the STUN message type. @@ -979,19 +978,19 @@ static pj_bool_t on_data_recvfrom(pj_activesock_t *asock, * Give it to our STUN session. */ if (!PJ_STUN_IS_RESPONSE(type) || - PJ_STUN_GET_METHOD(type) != PJ_STUN_BINDING_METHOD || - pj_memcmp(hdr->tsx_id, stun_sock->tsx_id, 10) != 0) + PJ_STUN_GET_METHOD(type) != PJ_STUN_BINDING_METHOD || + pj_memcmp(hdr->tsx_id, stun_sock->tsx_id, 10) != 0) { - /* Not STUN Binding response, or STUN transaction ID mismatch. - * This is not our message too -- give it to application. - */ - goto process_app_data; + /* Not STUN Binding response, or STUN transaction ID mismatch. + * This is not our message too -- give it to application. + */ + goto process_app_data; } /* This is our STUN Binding response. Give it to the STUN session */ status = pj_stun_session_on_rx_pkt(stun_sock->stun_sess, data, size, - PJ_STUN_IS_DATAGRAM, NULL, NULL, - src_addr, addr_len); + PJ_STUN_IS_DATAGRAM, NULL, NULL, + src_addr, addr_len); status = pj_grp_lock_release(stun_sock->grp_lock); @@ -999,10 +998,10 @@ static pj_bool_t on_data_recvfrom(pj_activesock_t *asock, process_app_data: if (stun_sock->cb.on_rx_data) { - (*stun_sock->cb.on_rx_data)(stun_sock, data, (unsigned)size, - src_addr, addr_len); - status = pj_grp_lock_release(stun_sock->grp_lock); - return status!=PJ_EGONE ? PJ_TRUE : PJ_FALSE; + (*stun_sock->cb.on_rx_data)(stun_sock, data, (unsigned)size, + src_addr, addr_len); + status = pj_grp_lock_release(stun_sock->grp_lock); + return status!=PJ_EGONE ? PJ_TRUE : PJ_FALSE; } status = pj_grp_lock_release(stun_sock->grp_lock); @@ -1011,37 +1010,37 @@ static pj_bool_t on_data_recvfrom(pj_activesock_t *asock, /* Callback from active socket about send status */ static pj_bool_t on_data_sent(pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent) + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent) { pj_stun_sock *stun_sock; stun_sock = (pj_stun_sock*) pj_activesock_get_user_data(asock); if (!stun_sock) - return PJ_FALSE; + return PJ_FALSE; /* Don't report to callback if this is internal message */ if (send_key == &stun_sock->int_send_key) { - return PJ_TRUE; + return PJ_TRUE; } /* Report to callback */ if (stun_sock->cb.on_data_sent) { - pj_bool_t ret; + pj_bool_t ret; - pj_grp_lock_acquire(stun_sock->grp_lock); + pj_grp_lock_acquire(stun_sock->grp_lock); - /* If app gives NULL send_key in sendto() function, then give - * NULL in the callback too - */ - if (send_key == &stun_sock->send_key) - send_key = NULL; + /* If app gives NULL send_key in sendto() function, then give + * NULL in the callback too + */ + if (send_key == &stun_sock->send_key) + send_key = NULL; - /* Call callback */ - ret = (*stun_sock->cb.on_data_sent)(stun_sock, send_key, sent); + /* Call callback */ + ret = (*stun_sock->cb.on_data_sent)(stun_sock, send_key, sent); - pj_grp_lock_release(stun_sock->grp_lock); - return ret; + pj_grp_lock_release(stun_sock->grp_lock); + return ret; } return PJ_TRUE; diff --git a/pjnath/src/pjnath/stun_transaction.c b/pjnath/src/pjnath/stun_transaction.c index e4d67db0fc..4d9145388f 100644 --- a/pjnath/src/pjnath/stun_transaction.c +++ b/pjnath/src/pjnath/stun_transaction.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -26,54 +25,54 @@ #include -#define THIS_FILE "stun_transaction.c" -#define TIMER_INACTIVE 0 -#define TIMER_ACTIVE 1 +#define THIS_FILE "stun_transaction.c" +#define TIMER_INACTIVE 0 +#define TIMER_ACTIVE 1 struct pj_stun_client_tsx { - char obj_name[PJ_MAX_OBJ_NAME]; - pj_stun_tsx_cb cb; - void *user_data; - pj_grp_lock_t *grp_lock; + char obj_name[PJ_MAX_OBJ_NAME]; + pj_stun_tsx_cb cb; + void *user_data; + pj_grp_lock_t *grp_lock; - pj_bool_t complete; + pj_bool_t complete; - pj_bool_t require_retransmit; - unsigned rto_msec; - pj_timer_entry retransmit_timer; - unsigned transmit_count; - pj_time_val retransmit_time; - pj_timer_heap_t *timer_heap; + pj_bool_t require_retransmit; + unsigned rto_msec; + pj_timer_entry retransmit_timer; + unsigned transmit_count; + pj_time_val retransmit_time; + pj_timer_heap_t *timer_heap; - pj_timer_entry destroy_timer; + pj_timer_entry destroy_timer; - void *last_pkt; - unsigned last_pkt_size; + void *last_pkt; + unsigned last_pkt_size; }; #if 1 -# define TRACE_(expr) PJ_LOG(5,expr) +# define TRACE_(expr) PJ_LOG(5,expr) #else # define TRACE_(expr) #endif static void retransmit_timer_callback(pj_timer_heap_t *timer_heap, - pj_timer_entry *timer); + pj_timer_entry *timer); static void destroy_timer_callback(pj_timer_heap_t *timer_heap, - pj_timer_entry *timer); + pj_timer_entry *timer); /* * Create a STUN client transaction. */ PJ_DEF(pj_status_t) pj_stun_client_tsx_create(pj_stun_config *cfg, - pj_pool_t *pool, - pj_grp_lock_t *grp_lock, - const pj_stun_tsx_cb *cb, - pj_stun_client_tsx **p_tsx) + pj_pool_t *pool, + pj_grp_lock_t *grp_lock, + const pj_stun_tsx_cb *cb, + pj_stun_client_tsx **p_tsx) { pj_stun_client_tsx *tsx; @@ -102,8 +101,8 @@ PJ_DEF(pj_status_t) pj_stun_client_tsx_create(pj_stun_config *cfg, PJ_DEF(pj_status_t) pj_stun_client_tsx_schedule_destroy( - pj_stun_client_tsx *tsx, - const pj_time_val *delay) + pj_stun_client_tsx *tsx, + const pj_time_val *delay) { pj_status_t status; @@ -124,8 +123,8 @@ PJ_DEF(pj_status_t) pj_stun_client_tsx_schedule_destroy( &tsx->destroy_timer, delay, TIMER_ACTIVE, tsx->grp_lock); if (status != PJ_SUCCESS) { - pj_grp_lock_release(tsx->grp_lock); - return status; + pj_grp_lock_release(tsx->grp_lock); + return status; } tsx->cb.on_complete = NULL; @@ -165,7 +164,7 @@ PJ_DEF(pj_status_t) pj_stun_client_tsx_stop(pj_stun_client_tsx *tsx) TIMER_INACTIVE); PJ_LOG(5,(tsx->obj_name, "STUN client transaction %p stopped, ref_cnt=%d", - tsx, pj_grp_lock_get_ref(tsx->grp_lock))); + tsx, pj_grp_lock_get_ref(tsx->grp_lock))); return PJ_SUCCESS; } @@ -185,7 +184,7 @@ PJ_DEF(pj_bool_t) pj_stun_client_tsx_is_complete(pj_stun_client_tsx *tsx) * Set user data. */ PJ_DEF(pj_status_t) pj_stun_client_tsx_set_data(pj_stun_client_tsx *tsx, - void *data) + void *data) { PJ_ASSERT_RETURN(tsx, PJ_EINVAL); tsx->user_data = data; @@ -212,40 +211,40 @@ static pj_status_t tsx_transmit_msg(pj_stun_client_tsx *tsx, pj_status_t status; PJ_ASSERT_RETURN(tsx->retransmit_timer.id == TIMER_INACTIVE || - !tsx->require_retransmit || !mod_count, PJ_EBUSY); + !tsx->require_retransmit || !mod_count, PJ_EBUSY); if (tsx->require_retransmit && mod_count) { - /* Calculate retransmit/timeout delay */ - if (tsx->transmit_count == 0) { - tsx->retransmit_time.sec = 0; - tsx->retransmit_time.msec = tsx->rto_msec; - - } else if (tsx->transmit_count < PJ_STUN_MAX_TRANSMIT_COUNT-1) { - unsigned msec; - - msec = PJ_TIME_VAL_MSEC(tsx->retransmit_time); - msec <<= 1; - tsx->retransmit_time.sec = msec / 1000; - tsx->retransmit_time.msec = msec % 1000; - - } else { - tsx->retransmit_time.sec = PJ_STUN_TIMEOUT_VALUE / 1000; - tsx->retransmit_time.msec = PJ_STUN_TIMEOUT_VALUE % 1000; - } - - /* Schedule timer first because when send_msg() failed we can - * cancel it (as opposed to when schedule_timer() failed we cannot - * cancel transmission). - */; - status = pj_timer_heap_schedule_w_grp_lock(tsx->timer_heap, - &tsx->retransmit_timer, - &tsx->retransmit_time, - TIMER_ACTIVE, - tsx->grp_lock); - if (status != PJ_SUCCESS) { - tsx->retransmit_timer.id = TIMER_INACTIVE; - return status; - } + /* Calculate retransmit/timeout delay */ + if (tsx->transmit_count == 0) { + tsx->retransmit_time.sec = 0; + tsx->retransmit_time.msec = tsx->rto_msec; + + } else if (tsx->transmit_count < PJ_STUN_MAX_TRANSMIT_COUNT-1) { + unsigned msec; + + msec = PJ_TIME_VAL_MSEC(tsx->retransmit_time); + msec <<= 1; + tsx->retransmit_time.sec = msec / 1000; + tsx->retransmit_time.msec = msec % 1000; + + } else { + tsx->retransmit_time.sec = PJ_STUN_TIMEOUT_VALUE / 1000; + tsx->retransmit_time.msec = PJ_STUN_TIMEOUT_VALUE % 1000; + } + + /* Schedule timer first because when send_msg() failed we can + * cancel it (as opposed to when schedule_timer() failed we cannot + * cancel transmission). + */; + status = pj_timer_heap_schedule_w_grp_lock(tsx->timer_heap, + &tsx->retransmit_timer, + &tsx->retransmit_time, + TIMER_ACTIVE, + tsx->grp_lock); + if (status != PJ_SUCCESS) { + tsx->retransmit_timer.id = TIMER_INACTIVE; + return status; + } } @@ -253,23 +252,23 @@ static pj_status_t tsx_transmit_msg(pj_stun_client_tsx *tsx, tsx->transmit_count++; PJ_LOG(5,(tsx->obj_name, "STUN sending message (transmit count=%d)", - tsx->transmit_count)); + tsx->transmit_count)); pj_log_push_indent(); /* Send message */ status = tsx->cb.on_send_msg(tsx, tsx->last_pkt, tsx->last_pkt_size); if (status == PJ_EPENDING || status == PJ_EBUSY) - status = PJ_SUCCESS; + status = PJ_SUCCESS; if (status == PJNATH_ESTUNDESTROYED) { - /* We've been destroyed, don't access the object. */ + /* We've been destroyed, don't access the object. */ } else if (status != PJ_SUCCESS) { - if (mod_count || status == PJ_EINVALIDOP) { - pj_timer_heap_cancel_if_active( tsx->timer_heap, - &tsx->retransmit_timer, - TIMER_INACTIVE); - } - PJ_PERROR(4, (tsx->obj_name, status, "STUN error sending message")); + if (mod_count || status == PJ_EINVALIDOP) { + pj_timer_heap_cancel_if_active( tsx->timer_heap, + &tsx->retransmit_timer, + TIMER_INACTIVE); + } + PJ_PERROR(4, (tsx->obj_name, status, "STUN error sending message")); } pj_log_pop_indent(); @@ -281,9 +280,9 @@ static pj_status_t tsx_transmit_msg(pj_stun_client_tsx *tsx, * Send outgoing message and start STUN transaction. */ PJ_DEF(pj_status_t) pj_stun_client_tsx_send_msg(pj_stun_client_tsx *tsx, - pj_bool_t retransmit, - void *pkt, - unsigned pkt_len) + pj_bool_t retransmit, + void *pkt, + unsigned pkt_len) { pj_status_t status; @@ -304,39 +303,39 @@ PJ_DEF(pj_status_t) pj_stun_client_tsx_send_msg(pj_stun_client_tsx *tsx, * retransmit timer. */ if (!retransmit) { - unsigned timeout; - - pj_assert(tsx->retransmit_timer.id == 0); - tsx->transmit_count = PJ_STUN_MAX_TRANSMIT_COUNT; - - timeout = tsx->rto_msec * 16; - tsx->retransmit_time.sec = timeout / 1000; - tsx->retransmit_time.msec = timeout % 1000; - - /* Schedule timer first because when send_msg() failed we can - * cancel it (as opposed to when schedule_timer() failed we cannot - * cancel transmission). - */; - status = pj_timer_heap_schedule_w_grp_lock(tsx->timer_heap, - &tsx->retransmit_timer, - &tsx->retransmit_time, - TIMER_ACTIVE, - tsx->grp_lock); - if (status != PJ_SUCCESS) { - tsx->retransmit_timer.id = TIMER_INACTIVE; - pj_grp_lock_release(tsx->grp_lock); - return status; - } + unsigned timeout; + + pj_assert(tsx->retransmit_timer.id == 0); + tsx->transmit_count = PJ_STUN_MAX_TRANSMIT_COUNT; + + timeout = tsx->rto_msec * 16; + tsx->retransmit_time.sec = timeout / 1000; + tsx->retransmit_time.msec = timeout % 1000; + + /* Schedule timer first because when send_msg() failed we can + * cancel it (as opposed to when schedule_timer() failed we cannot + * cancel transmission). + */; + status = pj_timer_heap_schedule_w_grp_lock(tsx->timer_heap, + &tsx->retransmit_timer, + &tsx->retransmit_time, + TIMER_ACTIVE, + tsx->grp_lock); + if (status != PJ_SUCCESS) { + tsx->retransmit_timer.id = TIMER_INACTIVE; + pj_grp_lock_release(tsx->grp_lock); + return status; + } } /* Send the message */ status = tsx_transmit_msg(tsx, PJ_TRUE); if (status != PJ_SUCCESS) { - pj_timer_heap_cancel_if_active(tsx->timer_heap, - &tsx->retransmit_timer, - TIMER_INACTIVE); - pj_grp_lock_release(tsx->grp_lock); - return status; + pj_timer_heap_cancel_if_active(tsx->timer_heap, + &tsx->retransmit_timer, + TIMER_INACTIVE); + pj_grp_lock_release(tsx->grp_lock); + return status; } pj_grp_lock_release(tsx->grp_lock); @@ -346,7 +345,7 @@ PJ_DEF(pj_status_t) pj_stun_client_tsx_send_msg(pj_stun_client_tsx *tsx, /* Retransmit timer callback */ static void retransmit_timer_callback(pj_timer_heap_t *timer_heap, - pj_timer_entry *timer) + pj_timer_entry *timer) { pj_stun_client_tsx *tsx = (pj_stun_client_tsx *) timer->user_data; pj_status_t status; @@ -358,32 +357,32 @@ static void retransmit_timer_callback(pj_timer_heap_t *timer_heap, /* tsx may be destroyed when calling the callback below */ pj_grp_lock_t *grp_lock = tsx->grp_lock; - /* Retransmission count exceeded. Transaction has failed */ - tsx->retransmit_timer.id = 0; - PJ_LOG(4,(tsx->obj_name, "STUN timeout waiting for response")); - pj_log_push_indent(); - if (!tsx->complete) { - tsx->complete = PJ_TRUE; - if (tsx->cb.on_complete) { - tsx->cb.on_complete(tsx, PJNATH_ESTUNTIMEDOUT, NULL, NULL, 0); - } - } - pj_grp_lock_release(grp_lock); - /* We might have been destroyed, don't try to access the object */ - pj_log_pop_indent(); - return; + /* Retransmission count exceeded. Transaction has failed */ + tsx->retransmit_timer.id = 0; + PJ_LOG(4,(tsx->obj_name, "STUN timeout waiting for response")); + pj_log_push_indent(); + if (!tsx->complete) { + tsx->complete = PJ_TRUE; + if (tsx->cb.on_complete) { + tsx->cb.on_complete(tsx, PJNATH_ESTUNTIMEDOUT, NULL, NULL, 0); + } + } + pj_grp_lock_release(grp_lock); + /* We might have been destroyed, don't try to access the object */ + pj_log_pop_indent(); + return; } tsx->retransmit_timer.id = 0; status = tsx_transmit_msg(tsx, PJ_TRUE); if (status != PJ_SUCCESS) { - tsx->retransmit_timer.id = 0; - if (!tsx->complete) { - tsx->complete = PJ_TRUE; - if (tsx->cb.on_complete) { - tsx->cb.on_complete(tsx, status, NULL, NULL, 0); - } - } + tsx->retransmit_timer.id = 0; + if (!tsx->complete) { + tsx->complete = PJ_TRUE; + if (tsx->cb.on_complete) { + tsx->cb.on_complete(tsx, status, NULL, NULL, 0); + } + } } pj_grp_lock_release(tsx->grp_lock); @@ -397,7 +396,7 @@ PJ_DEF(pj_status_t) pj_stun_client_tsx_retransmit(pj_stun_client_tsx *tsx, pj_bool_t mod_count) { if (tsx->destroy_timer.id != 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } if (mod_count) { @@ -410,7 +409,7 @@ PJ_DEF(pj_status_t) pj_stun_client_tsx_retransmit(pj_stun_client_tsx *tsx, /* Timer callback to destroy transaction */ static void destroy_timer_callback(pj_timer_heap_t *timer_heap, - pj_timer_entry *timer) + pj_timer_entry *timer) { pj_stun_client_tsx *tsx = (pj_stun_client_tsx *) timer->user_data; @@ -427,20 +426,20 @@ static void destroy_timer_callback(pj_timer_heap_t *timer_heap, * Notify the STUN transaction about the arrival of STUN response. */ PJ_DEF(pj_status_t) pj_stun_client_tsx_on_rx_msg(pj_stun_client_tsx *tsx, - const pj_stun_msg *msg, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + const pj_stun_msg *msg, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_stun_errcode_attr *err_attr; pj_status_t status; /* Must be STUN response message */ if (!PJ_STUN_IS_SUCCESS_RESPONSE(msg->hdr.type) && - !PJ_STUN_IS_ERROR_RESPONSE(msg->hdr.type)) + !PJ_STUN_IS_ERROR_RESPONSE(msg->hdr.type)) { - PJ_LOG(4,(tsx->obj_name, - "STUN rx_msg() error: not response message")); - return PJNATH_EINSTUNMSGTYPE; + PJ_LOG(4,(tsx->obj_name, + "STUN rx_msg() error: not response message")); + return PJNATH_EINSTUNMSGTYPE; } @@ -452,34 +451,34 @@ PJ_DEF(pj_status_t) pj_stun_client_tsx_on_rx_msg(pj_stun_client_tsx *tsx, /* Find STUN error code attribute */ err_attr = (pj_stun_errcode_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_ERROR_CODE, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_ERROR_CODE, 0); if (err_attr && err_attr->err_code <= 200) { - /* draft-ietf-behave-rfc3489bis-05.txt Section 8.3.2: - * Any response between 100 and 299 MUST result in the cessation - * of request retransmissions, but otherwise is discarded. - */ - PJ_LOG(4,(tsx->obj_name, - "STUN rx_msg() error: received provisional %d code (%.*s)", - err_attr->err_code, - (int)err_attr->reason.slen, - err_attr->reason.ptr)); - return PJ_SUCCESS; + /* draft-ietf-behave-rfc3489bis-05.txt Section 8.3.2: + * Any response between 100 and 299 MUST result in the cessation + * of request retransmissions, but otherwise is discarded. + */ + PJ_LOG(4,(tsx->obj_name, + "STUN rx_msg() error: received provisional %d code (%.*s)", + err_attr->err_code, + (int)err_attr->reason.slen, + err_attr->reason.ptr)); + return PJ_SUCCESS; } if (err_attr == NULL) { - status = PJ_SUCCESS; + status = PJ_SUCCESS; } else { - status = PJ_STATUS_FROM_STUN_CODE(err_attr->err_code); + status = PJ_STATUS_FROM_STUN_CODE(err_attr->err_code); } /* Call callback */ if (!tsx->complete) { - tsx->complete = PJ_TRUE; - if (tsx->cb.on_complete) { - tsx->cb.on_complete(tsx, status, msg, src_addr, src_addr_len); - } - /* We might have been destroyed, don't try to access the object */ + tsx->complete = PJ_TRUE; + if (tsx->cb.on_complete) { + tsx->cb.on_complete(tsx, status, msg, src_addr, src_addr_len); + } + /* We might have been destroyed, don't try to access the object */ } return PJ_SUCCESS; diff --git a/pjnath/src/pjnath/turn_session.c b/pjnath/src/pjnath/turn_session.c index c7d961e730..b9f7b2dd67 100644 --- a/pjnath/src/pjnath/turn_session.c +++ b/pjnath/src/pjnath/turn_session.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,8 +30,8 @@ #include #include -#define PJ_TURN_CHANNEL_MIN 0x4000 -#define PJ_TURN_CHANNEL_MAX 0x7FFF /* inclusive */ +#define PJ_TURN_CHANNEL_MIN 0x4000 +#define PJ_TURN_CHANNEL_MAX 0x7FFF /* inclusive */ #define PJ_TURN_CHANNEL_HTABLE_SIZE 8 #define PJ_TURN_PERM_HTABLE_SIZE 8 @@ -61,18 +60,18 @@ enum timer_id_t struct ch_t { /* The channel number */ - pj_uint16_t num; + pj_uint16_t num; /* PJ_TRUE if we've received successful response to ChannelBind request * for this channel. */ - pj_bool_t bound; + pj_bool_t bound; /* The peer IP address and port */ - pj_sockaddr addr; + pj_sockaddr addr; /* The channel binding expiration */ - pj_time_val expiry; + pj_time_val expiry; }; @@ -82,82 +81,82 @@ struct ch_t struct perm_t { /* Cache of hash value to speed-up lookup */ - pj_uint32_t hval; + pj_uint32_t hval; /* The permission IP address. The port number MUST be zero */ - pj_sockaddr addr; + pj_sockaddr addr; /* Number of peers that uses this permission. */ - unsigned peer_cnt; + unsigned peer_cnt; /* Automatically renew this permission once it expires? */ - pj_bool_t renew; + pj_bool_t renew; /* The permission expiration */ - pj_time_val expiry; + pj_time_val expiry; /* Arbitrary/random pointer value (token) to map this perm with the * request to create it. It is used to invalidate this perm when the * request fails. */ - void *req_token; + void *req_token; }; struct conn_bind_t { - pj_uint32_t id; /* Connection ID. */ - pj_sockaddr peer_addr; /* Peer address. */ - unsigned peer_addr_len; + pj_uint32_t id; /* Connection ID. */ + pj_sockaddr peer_addr; /* Peer address. */ + unsigned peer_addr_len; }; /* The TURN client session structure */ struct pj_turn_session { - pj_pool_t *pool; - const char *obj_name; - pj_turn_session_cb cb; - void *user_data; - pj_stun_config stun_cfg; - pj_bool_t is_destroying; + pj_pool_t *pool; + const char *obj_name; + pj_turn_session_cb cb; + void *user_data; + pj_stun_config stun_cfg; + pj_bool_t is_destroying; - pj_grp_lock_t *grp_lock; - int busy; + pj_grp_lock_t *grp_lock; + int busy; - pj_turn_state_t state; - pj_status_t last_status; - pj_bool_t pending_destroy; + pj_turn_state_t state; + pj_status_t last_status; + pj_bool_t pending_destroy; - pj_stun_session *stun; + pj_stun_session *stun; - unsigned lifetime; - int ka_interval; - pj_time_val expiry; + unsigned lifetime; + int ka_interval; + pj_time_val expiry; - pj_timer_heap_t *timer_heap; - pj_timer_entry timer; + pj_timer_heap_t *timer_heap; + pj_timer_entry timer; - pj_uint16_t default_port; + pj_uint16_t default_port; - pj_uint16_t af; - pj_turn_tp_type conn_type; - pj_uint16_t srv_addr_cnt; - pj_sockaddr *srv_addr_list; - pj_sockaddr *srv_addr; + pj_uint16_t af; + pj_turn_tp_type conn_type; + pj_uint16_t srv_addr_cnt; + pj_sockaddr *srv_addr_list; + pj_sockaddr *srv_addr; - pj_bool_t pending_alloc; - pj_turn_alloc_param alloc_param; + pj_bool_t pending_alloc; + pj_turn_alloc_param alloc_param; - pj_sockaddr mapped_addr; - pj_sockaddr relay_addr; + pj_sockaddr mapped_addr; + pj_sockaddr relay_addr; - pj_hash_table_t *ch_table; - pj_hash_table_t *perm_table; + pj_hash_table_t *ch_table; + pj_hash_table_t *perm_table; - pj_uint32_t send_ind_tsx_id[3]; + pj_uint32_t send_ind_tsx_id[3]; /* tx_pkt must be 16bit aligned */ - pj_uint8_t tx_pkt[PJ_TURN_MAX_PKT_LEN]; + pj_uint8_t tx_pkt[PJ_TURN_MAX_PKT_LEN]; - pj_uint16_t next_ch; + pj_uint16_t next_ch; }; @@ -165,46 +164,46 @@ struct pj_turn_session * Prototypes. */ static void sess_shutdown(pj_turn_session *sess, - pj_status_t status); + pj_status_t status); static void turn_sess_on_destroy(void *comp); static void do_destroy(pj_turn_session *sess); static void send_refresh(pj_turn_session *sess, int lifetime); static pj_status_t stun_on_send_msg(pj_stun_session *sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len); + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len); static void stun_on_request_complete(pj_stun_session *sess, - pj_status_t status, - void *token, - pj_stun_tx_data *tdata, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + pj_status_t status, + void *token, + pj_stun_tx_data *tdata, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); static pj_status_t stun_on_rx_indication(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_msg *msg, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_msg *msg, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); static void dns_srv_resolver_cb(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec); + pj_status_t status, + const pj_dns_srv_record *rec); static struct ch_t *lookup_ch_by_addr(pj_turn_session *sess, - const pj_sockaddr_t *addr, - unsigned addr_len, - pj_bool_t update, - pj_bool_t bind_channel); + const pj_sockaddr_t *addr, + unsigned addr_len, + pj_bool_t update, + pj_bool_t bind_channel); static struct ch_t *lookup_ch_by_chnum(pj_turn_session *sess, - pj_uint16_t chnum); + pj_uint16_t chnum); static struct perm_t *lookup_perm(pj_turn_session *sess, - const pj_sockaddr_t *addr, - unsigned addr_len, - pj_bool_t update); + const pj_sockaddr_t *addr, + unsigned addr_len, + pj_bool_t update); static void invalidate_perm(pj_turn_session *sess, - struct perm_t *perm); + struct perm_t *perm); static void on_timer_event(pj_timer_heap_t *th, pj_timer_entry *e); @@ -221,8 +220,8 @@ PJ_DEF(void) pj_turn_alloc_param_default(pj_turn_alloc_param *prm) * Duplicate pj_turn_alloc_param. */ PJ_DEF(void) pj_turn_alloc_param_copy( pj_pool_t *pool, - pj_turn_alloc_param *dst, - const pj_turn_alloc_param *src) + pj_turn_alloc_param *dst, + const pj_turn_alloc_param *src) { PJ_UNUSED_ARG(pool); pj_memcpy(dst, src, sizeof(*dst)); @@ -240,14 +239,14 @@ PJ_DEF(const char*) pj_turn_state_name(pj_turn_state_t state) * Create TURN client session. */ PJ_DEF(pj_status_t) pj_turn_session_create( const pj_stun_config *cfg, - const char *name, - int af, - pj_turn_tp_type conn_type, - pj_grp_lock_t *grp_lock, - const pj_turn_session_cb *cb, - unsigned options, - void *user_data, - pj_turn_session **p_sess) + const char *name, + int af, + pj_turn_tp_type conn_type, + pj_grp_lock_t *grp_lock, + const pj_turn_session_cb *cb, + unsigned options, + void *user_data, + pj_turn_session **p_sess) { pj_pool_t *pool; pj_turn_session *sess; @@ -260,11 +259,11 @@ PJ_DEF(pj_status_t) pj_turn_session_create( const pj_stun_config *cfg, PJ_UNUSED_ARG(options); if (name == NULL) - name = "turn%p"; + name = "turn%p"; /* Allocate and create TURN session */ pool = pj_pool_create(cfg->pf, name, PJNATH_POOL_LEN_TURN_SESS, - PJNATH_POOL_INC_TURN_SESS, NULL); + PJNATH_POOL_INC_TURN_SESS, NULL); sess = PJ_POOL_ZALLOC_T(pool, pj_turn_session); sess->pool = pool; sess->obj_name = pool->obj_name; @@ -289,13 +288,13 @@ PJ_DEF(pj_status_t) pj_turn_session_create( const pj_stun_config *cfg, /* Session lock */ if (grp_lock) { - sess->grp_lock = grp_lock; + sess->grp_lock = grp_lock; } else { - status = pj_grp_lock_create(pool, NULL, &sess->grp_lock); - if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; - } + status = pj_grp_lock_create(pool, NULL, &sess->grp_lock); + if (status != PJ_SUCCESS) { + pj_pool_release(pool); + return status; + } } pj_grp_lock_add_ref(sess->grp_lock); @@ -311,10 +310,10 @@ PJ_DEF(pj_status_t) pj_turn_session_create( const pj_stun_config *cfg, stun_cb.on_request_complete = &stun_on_request_complete; stun_cb.on_rx_indication = &stun_on_rx_indication; status = pj_stun_session_create(&sess->stun_cfg, sess->obj_name, &stun_cb, - PJ_FALSE, sess->grp_lock, &sess->stun); + PJ_FALSE, sess->grp_lock, &sess->stun); if (status != PJ_SUCCESS) { - do_destroy(sess); - return status; + do_destroy(sess); + return status; } /* Attach ourself to STUN session */ @@ -335,8 +334,8 @@ static void turn_sess_on_destroy(void *comp) /* Destroy pool */ if (sess->pool) { - PJ_LOG(4,(sess->obj_name, "TURN client session destroyed")); - pj_pool_safe_release(&sess->pool); + PJ_LOG(4,(sess->obj_name, "TURN client session destroyed")); + pj_pool_safe_release(&sess->pool); } } @@ -344,12 +343,12 @@ static void turn_sess_on_destroy(void *comp) static void do_destroy(pj_turn_session *sess) { PJ_LOG(4,(sess->obj_name, "TURN session destroy request, ref_cnt=%d", - pj_grp_lock_get_ref(sess->grp_lock))); + pj_grp_lock_get_ref(sess->grp_lock))); pj_grp_lock_acquire(sess->grp_lock); if (sess->is_destroying) { - pj_grp_lock_release(sess->grp_lock); - return; + pj_grp_lock_release(sess->grp_lock); + return; } sess->is_destroying = PJ_TRUE; @@ -367,14 +366,14 @@ static void set_state(pj_turn_session *sess, enum pj_turn_state_t state) pj_turn_state_t old_state = sess->state; if (state==sess->state) - return; + return; PJ_LOG(4,(sess->obj_name, "State changed %s --> %s", - state_names[old_state], state_names[state])); + state_names[old_state], state_names[state])); sess->state = state; if (sess->cb.on_state) { - (*sess->cb.on_state)(sess, old_state, state); + (*sess->cb.on_state)(sess, old_state, state); } } @@ -382,65 +381,65 @@ static void set_state(pj_turn_session *sess, enum pj_turn_state_t state) * Notify application and shutdown the TURN session. */ static void sess_shutdown(pj_turn_session *sess, - pj_status_t status) + pj_status_t status) { pj_bool_t can_destroy = PJ_TRUE; PJ_LOG(4,(sess->obj_name, "Request to shutdown in state %s, cause:%d", - state_names[sess->state], status)); + state_names[sess->state], status)); if (sess->last_status == PJ_SUCCESS && status != PJ_SUCCESS) - sess->last_status = status; + sess->last_status = status; switch (sess->state) { case PJ_TURN_STATE_NULL: - break; + break; case PJ_TURN_STATE_RESOLVING: - /* Wait for DNS callback invoked, it will call the this function - * again. If the callback happens to get pending_destroy==FALSE, - * the TURN allocation will call this function again. - */ - sess->pending_destroy = PJ_TRUE; - can_destroy = PJ_FALSE; - break; + /* Wait for DNS callback invoked, it will call the this function + * again. If the callback happens to get pending_destroy==FALSE, + * the TURN allocation will call this function again. + */ + sess->pending_destroy = PJ_TRUE; + can_destroy = PJ_FALSE; + break; case PJ_TURN_STATE_RESOLVED: - break; + break; case PJ_TURN_STATE_ALLOCATING: - /* We need to wait until allocation complete */ - sess->pending_destroy = PJ_TRUE; - can_destroy = PJ_FALSE; - break; + /* We need to wait until allocation complete */ + sess->pending_destroy = PJ_TRUE; + can_destroy = PJ_FALSE; + break; case PJ_TURN_STATE_READY: - /* Send REFRESH with LIFETIME=0 */ - can_destroy = PJ_FALSE; - send_refresh(sess, 0); - break; + /* Send REFRESH with LIFETIME=0 */ + can_destroy = PJ_FALSE; + send_refresh(sess, 0); + break; case PJ_TURN_STATE_DEALLOCATING: - can_destroy = PJ_FALSE; - /* This may recursively call this function again with - * state==PJ_TURN_STATE_DEALLOCATED. - */ - /* No need to deallocate as we're already deallocating! - * See https://github.com/pjsip/pjproject/issues/1551 - send_refresh(sess, 0); - */ - break; + can_destroy = PJ_FALSE; + /* This may recursively call this function again with + * state==PJ_TURN_STATE_DEALLOCATED. + */ + /* No need to deallocate as we're already deallocating! + * See https://github.com/pjsip/pjproject/issues/1551 + send_refresh(sess, 0); + */ + break; case PJ_TURN_STATE_DEALLOCATED: case PJ_TURN_STATE_DESTROYING: - break; + break; } if (can_destroy) { - /* Schedule destroy */ - pj_time_val delay = {0, 0}; + /* Schedule destroy */ + pj_time_val delay = {0, 0}; - set_state(sess, PJ_TURN_STATE_DESTROYING); + set_state(sess, PJ_TURN_STATE_DESTROYING); - pj_timer_heap_cancel_if_active(sess->timer_heap, &sess->timer, - TIMER_NONE); - pj_timer_heap_schedule_w_grp_lock(sess->timer_heap, &sess->timer, - &delay, TIMER_DESTROY, - sess->grp_lock); + pj_timer_heap_cancel_if_active(sess->timer_heap, &sess->timer, + TIMER_NONE); + pj_timer_heap_schedule_w_grp_lock(sess->timer_heap, &sess->timer, + &delay, TIMER_DESTROY, + sess->grp_lock); } } @@ -466,12 +465,12 @@ PJ_DEF(pj_status_t) pj_turn_session_shutdown(pj_turn_session *sess) * Forcefully destroy the TURN session. */ PJ_DEF(pj_status_t) pj_turn_session_destroy( pj_turn_session *sess, - pj_status_t last_err) + pj_status_t last_err) { PJ_ASSERT_RETURN(sess, PJ_EINVAL); if (last_err != PJ_SUCCESS && sess->last_status == PJ_SUCCESS) - sess->last_status = last_err; + sess->last_status = last_err; set_state(sess, PJ_TURN_STATE_DEALLOCATED); sess_shutdown(sess, PJ_SUCCESS); return PJ_SUCCESS; @@ -482,7 +481,7 @@ PJ_DEF(pj_status_t) pj_turn_session_destroy( pj_turn_session *sess, * Get TURN session info. */ PJ_DEF(pj_status_t) pj_turn_session_get_info( pj_turn_session *sess, - pj_turn_session_info *info) + pj_turn_session_info *info) { pj_time_val now; @@ -496,14 +495,14 @@ PJ_DEF(pj_status_t) pj_turn_session_get_info( pj_turn_session *sess, info->last_status = sess->last_status; if (sess->srv_addr) - pj_memcpy(&info->server, sess->srv_addr, sizeof(info->server)); + pj_memcpy(&info->server, sess->srv_addr, sizeof(info->server)); else - pj_bzero(&info->server, sizeof(info->server)); + pj_bzero(&info->server, sizeof(info->server)); pj_memcpy(&info->mapped_addr, &sess->mapped_addr, - sizeof(sess->mapped_addr)); + sizeof(sess->mapped_addr)); pj_memcpy(&info->relay_addr, &sess->relay_addr, - sizeof(sess->relay_addr)); + sizeof(sess->relay_addr)); return PJ_SUCCESS; } @@ -513,7 +512,7 @@ PJ_DEF(pj_status_t) pj_turn_session_get_info( pj_turn_session *sess, * Re-assign user data. */ PJ_DEF(pj_status_t) pj_turn_session_set_user_data( pj_turn_session *sess, - void *user_data) + void *user_data) { sess->user_data = user_data; return PJ_SUCCESS; @@ -540,11 +539,11 @@ PJ_DEF(pj_grp_lock_t *) pj_turn_session_get_grp_lock(pj_turn_session *sess) /* * Configure message logging. By default all flags are enabled. * - * @param sess The TURN client session. - * @param flags Bitmask combination of #pj_stun_sess_msg_log_flag + * @param sess The TURN client session. + * @param flags Bitmask combination of #pj_stun_sess_msg_log_flag */ PJ_DEF(void) pj_turn_session_set_log( pj_turn_session *sess, - unsigned flags) + unsigned flags) { pj_stun_session_set_log(sess->stun, flags); } @@ -554,7 +553,7 @@ PJ_DEF(void) pj_turn_session_set_log( pj_turn_session *sess, * Set software name */ PJ_DEF(pj_status_t) pj_turn_session_set_software_name( pj_turn_session *sess, - const pj_str_t *sw) + const pj_str_t *sw) { pj_status_t status; @@ -570,9 +569,9 @@ PJ_DEF(pj_status_t) pj_turn_session_set_software_name( pj_turn_session *sess, * Set the server or domain name of the server. */ PJ_DEF(pj_status_t) pj_turn_session_set_server( pj_turn_session *sess, - const pj_str_t *domain, - int default_port, - pj_dns_resolver *resolver) + const pj_str_t *domain, + int default_port, + pj_dns_resolver *resolver) { pj_sockaddr tmp_addr; pj_bool_t is_ip_addr; @@ -586,109 +585,109 @@ PJ_DEF(pj_status_t) pj_turn_session_set_server( pj_turn_session *sess, /* See if "domain" contains just IP address */ tmp_addr.addr.sa_family = sess->af; status = pj_inet_pton(sess->af, domain, - pj_sockaddr_get_addr(&tmp_addr)); + pj_sockaddr_get_addr(&tmp_addr)); is_ip_addr = (status == PJ_SUCCESS); if (!is_ip_addr && resolver) { - /* Resolve with DNS SRV resolution, and fallback to DNS A resolution - * if default_port is specified. - */ - unsigned opt = 0; - pj_str_t res_name; - - switch (sess->conn_type) { - case PJ_TURN_TP_UDP: - res_name = pj_str("_turn._udp."); - break; - case PJ_TURN_TP_TCP: - res_name = pj_str("_turn._tcp."); - break; - case PJ_TURN_TP_TLS: - res_name = pj_str("_turns._tcp."); - break; - default: - status = PJNATH_ETURNINTP; - goto on_return; - } - - /* Init DNS resolution option for IPv6 */ - if (sess->af == pj_AF_INET6()) - opt |= PJ_DNS_SRV_RESOLVE_AAAA_ONLY; - - /* Fallback to DNS A only if default port is specified */ - if (default_port>0 && default_port<65536) { - if (sess->af == pj_AF_INET6()) - opt |= PJ_DNS_SRV_FALLBACK_AAAA; - else - opt |= PJ_DNS_SRV_FALLBACK_A; - sess->default_port = (pj_uint16_t)default_port; - } - - PJ_LOG(5,(sess->obj_name, "Resolving %.*s%.*s with DNS SRV", - (int)res_name.slen, res_name.ptr, - (int)domain->slen, domain->ptr)); - set_state(sess, PJ_TURN_STATE_RESOLVING); - - /* User may have destroyed us in the callback */ - if (sess->state != PJ_TURN_STATE_RESOLVING) { - status = PJ_ECANCELLED; - goto on_return; - } - - /* Add reference before async DNS resolution */ - pj_grp_lock_add_ref(sess->grp_lock); - - status = pj_dns_srv_resolve(domain, &res_name, default_port, - sess->pool, resolver, opt, sess, - &dns_srv_resolver_cb, NULL); - if (status != PJ_SUCCESS) { - set_state(sess, PJ_TURN_STATE_NULL); - pj_grp_lock_dec_ref(sess->grp_lock); - goto on_return; - } + /* Resolve with DNS SRV resolution, and fallback to DNS A resolution + * if default_port is specified. + */ + unsigned opt = 0; + pj_str_t res_name; + + switch (sess->conn_type) { + case PJ_TURN_TP_UDP: + res_name = pj_str("_turn._udp."); + break; + case PJ_TURN_TP_TCP: + res_name = pj_str("_turn._tcp."); + break; + case PJ_TURN_TP_TLS: + res_name = pj_str("_turns._tcp."); + break; + default: + status = PJNATH_ETURNINTP; + goto on_return; + } + + /* Init DNS resolution option for IPv6 */ + if (sess->af == pj_AF_INET6()) + opt |= PJ_DNS_SRV_RESOLVE_AAAA_ONLY; + + /* Fallback to DNS A only if default port is specified */ + if (default_port>0 && default_port<65536) { + if (sess->af == pj_AF_INET6()) + opt |= PJ_DNS_SRV_FALLBACK_AAAA; + else + opt |= PJ_DNS_SRV_FALLBACK_A; + sess->default_port = (pj_uint16_t)default_port; + } + + PJ_LOG(5,(sess->obj_name, "Resolving %.*s%.*s with DNS SRV", + (int)res_name.slen, res_name.ptr, + (int)domain->slen, domain->ptr)); + set_state(sess, PJ_TURN_STATE_RESOLVING); + + /* User may have destroyed us in the callback */ + if (sess->state != PJ_TURN_STATE_RESOLVING) { + status = PJ_ECANCELLED; + goto on_return; + } + + /* Add reference before async DNS resolution */ + pj_grp_lock_add_ref(sess->grp_lock); + + status = pj_dns_srv_resolve(domain, &res_name, default_port, + sess->pool, resolver, opt, sess, + &dns_srv_resolver_cb, NULL); + if (status != PJ_SUCCESS) { + set_state(sess, PJ_TURN_STATE_NULL); + pj_grp_lock_dec_ref(sess->grp_lock); + goto on_return; + } } else { - /* Resolver is not specified, resolve with standard gethostbyname(). - * The default_port MUST be specified in this case. - */ - pj_addrinfo *ai; - unsigned i, cnt; - - /* Default port must be specified */ - PJ_ASSERT_RETURN(default_port>0 && default_port<65536, PJ_EINVAL); - sess->default_port = (pj_uint16_t)default_port; - - cnt = PJ_TURN_MAX_DNS_SRV_CNT; - ai = (pj_addrinfo*) - pj_pool_calloc(sess->pool, cnt, sizeof(pj_addrinfo)); - - PJ_LOG(5,(sess->obj_name, "Resolving %.*s with DNS A", - (int)domain->slen, domain->ptr)); - set_state(sess, PJ_TURN_STATE_RESOLVING); - - /* User may have destroyed us in the callback */ - if (sess->state != PJ_TURN_STATE_RESOLVING) { - status = PJ_ECANCELLED; - goto on_return; - } - - status = pj_getaddrinfo(sess->af, domain, &cnt, ai); - if (status != PJ_SUCCESS) - goto on_return; - - sess->srv_addr_cnt = (pj_uint16_t)cnt; - sess->srv_addr_list = (pj_sockaddr*) - pj_pool_calloc(sess->pool, cnt, - sizeof(pj_sockaddr)); - for (i=0; isrv_addr_list[i]; - pj_memcpy(addr, &ai[i].ai_addr, sizeof(pj_sockaddr)); - addr->addr.sa_family = sess->af; - pj_sockaddr_set_port(addr, sess->default_port); - } - - sess->srv_addr = &sess->srv_addr_list[0]; - set_state(sess, PJ_TURN_STATE_RESOLVED); + /* Resolver is not specified, resolve with standard gethostbyname(). + * The default_port MUST be specified in this case. + */ + pj_addrinfo *ai; + unsigned i, cnt; + + /* Default port must be specified */ + PJ_ASSERT_RETURN(default_port>0 && default_port<65536, PJ_EINVAL); + sess->default_port = (pj_uint16_t)default_port; + + cnt = PJ_TURN_MAX_DNS_SRV_CNT; + ai = (pj_addrinfo*) + pj_pool_calloc(sess->pool, cnt, sizeof(pj_addrinfo)); + + PJ_LOG(5,(sess->obj_name, "Resolving %.*s with DNS A", + (int)domain->slen, domain->ptr)); + set_state(sess, PJ_TURN_STATE_RESOLVING); + + /* User may have destroyed us in the callback */ + if (sess->state != PJ_TURN_STATE_RESOLVING) { + status = PJ_ECANCELLED; + goto on_return; + } + + status = pj_getaddrinfo(sess->af, domain, &cnt, ai); + if (status != PJ_SUCCESS) + goto on_return; + + sess->srv_addr_cnt = (pj_uint16_t)cnt; + sess->srv_addr_list = (pj_sockaddr*) + pj_pool_calloc(sess->pool, cnt, + sizeof(pj_sockaddr)); + for (i=0; isrv_addr_list[i]; + pj_memcpy(addr, &ai[i].ai_addr, sizeof(pj_sockaddr)); + addr->addr.sa_family = sess->af; + pj_sockaddr_set_port(addr, sess->default_port); + } + + sess->srv_addr = &sess->srv_addr_list[0]; + set_state(sess, PJ_TURN_STATE_RESOLVED); } on_return: @@ -701,7 +700,7 @@ PJ_DEF(pj_status_t) pj_turn_session_set_server( pj_turn_session *sess, * Set credential to be used by the session. */ PJ_DEF(pj_status_t) pj_turn_session_set_credential(pj_turn_session *sess, - const pj_stun_auth_cred *cred) + const pj_stun_auth_cred *cred) { PJ_ASSERT_RETURN(sess && cred, PJ_EINVAL); PJ_ASSERT_RETURN(sess->stun, PJ_EINVALIDOP); @@ -720,7 +719,7 @@ PJ_DEF(pj_status_t) pj_turn_session_set_credential(pj_turn_session *sess, * Create TURN allocation. */ PJ_DEF(pj_status_t) pj_turn_session_alloc(pj_turn_session *sess, - const pj_turn_alloc_param *param) + const pj_turn_alloc_param *param) { pj_stun_tx_data *tdata; pj_bool_t retransmit; @@ -728,31 +727,31 @@ PJ_DEF(pj_status_t) pj_turn_session_alloc(pj_turn_session *sess, PJ_ASSERT_RETURN(sess, PJ_EINVAL); PJ_ASSERT_RETURN(sess->state>PJ_TURN_STATE_NULL && - sess->state<=PJ_TURN_STATE_RESOLVED, - PJ_EINVALIDOP); + sess->state<=PJ_TURN_STATE_RESOLVED, + PJ_EINVALIDOP); PJ_ASSERT_RETURN(param->peer_conn_type == PJ_TURN_TP_UDP || param->peer_conn_type == PJ_TURN_TP_TCP, PJ_EINVAL); /* Verify address family in allocation param */ if (param && param->af) { - PJ_ASSERT_RETURN(param->af==pj_AF_INET() || param->af==pj_AF_INET6(), - PJ_EINVAL); + PJ_ASSERT_RETURN(param->af==pj_AF_INET() || param->af==pj_AF_INET6(), + PJ_EINVAL); } pj_grp_lock_acquire(sess->grp_lock); if (param && param != &sess->alloc_param) - pj_turn_alloc_param_copy(sess->pool, &sess->alloc_param, param); + pj_turn_alloc_param_copy(sess->pool, &sess->alloc_param, param); if (sess->state < PJ_TURN_STATE_RESOLVED) { - sess->pending_alloc = PJ_TRUE; + sess->pending_alloc = PJ_TRUE; - PJ_LOG(4,(sess->obj_name, "Pending ALLOCATE in state %s", - state_names[sess->state])); + PJ_LOG(4,(sess->obj_name, "Pending ALLOCATE in state %s", + state_names[sess->state])); - pj_grp_lock_release(sess->grp_lock); - return PJ_SUCCESS; + pj_grp_lock_release(sess->grp_lock); + return PJ_SUCCESS; } @@ -761,46 +760,46 @@ PJ_DEF(pj_status_t) pj_turn_session_alloc(pj_turn_session *sess, /* Create a bare request */ status = pj_stun_session_create_req(sess->stun, PJ_STUN_ALLOCATE_REQUEST, - PJ_STUN_MAGIC, NULL, &tdata); + PJ_STUN_MAGIC, NULL, &tdata); if (status != PJ_SUCCESS) { - pj_grp_lock_release(sess->grp_lock); - return status; + pj_grp_lock_release(sess->grp_lock); + return status; } /* MUST include REQUESTED-TRANSPORT attribute */ pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_REQ_TRANSPORT, - PJ_STUN_SET_RT_PROTO(param->peer_conn_type)); + PJ_STUN_ATTR_REQ_TRANSPORT, + PJ_STUN_SET_RT_PROTO(param->peer_conn_type)); /* Include BANDWIDTH if requested */ if (sess->alloc_param.bandwidth > 0) { - pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_BANDWIDTH, - sess->alloc_param.bandwidth); + pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, + PJ_STUN_ATTR_BANDWIDTH, + sess->alloc_param.bandwidth); } /* Include LIFETIME if requested */ if (sess->alloc_param.lifetime > 0) { - pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_LIFETIME, - sess->alloc_param.lifetime); + pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, + PJ_STUN_ATTR_LIFETIME, + sess->alloc_param.lifetime); } /* Include ADDRESS-FAMILY if requested */ if (sess->alloc_param.af || sess->af == pj_AF_INET6()) { - enum { IPV4_AF_TYPE = 0x01 << 24, - IPV6_AF_TYPE = 0x02 << 24 }; - - if (sess->alloc_param.af == pj_AF_INET6() || - (sess->alloc_param.af == 0 && sess->af == pj_AF_INET6())) - { - pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_REQ_ADDR_TYPE, IPV6_AF_TYPE); - } else if (sess->alloc_param.af == pj_AF_INET()) { - /* For IPv4, only add the attribute when explicitly requested */ - pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_REQ_ADDR_TYPE, IPV4_AF_TYPE); - } + enum { IPV4_AF_TYPE = 0x01 << 24, + IPV6_AF_TYPE = 0x02 << 24 }; + + if (sess->alloc_param.af == pj_AF_INET6() || + (sess->alloc_param.af == 0 && sess->af == pj_AF_INET6())) + { + pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, + PJ_STUN_ATTR_REQ_ADDR_TYPE, IPV6_AF_TYPE); + } else if (sess->alloc_param.af == pj_AF_INET()) { + /* For IPv4, only add the attribute when explicitly requested */ + pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, + PJ_STUN_ATTR_REQ_ADDR_TYPE, IPV4_AF_TYPE); + } } /* Server address must be set */ @@ -810,15 +809,15 @@ PJ_DEF(pj_status_t) pj_turn_session_alloc(pj_turn_session *sess, set_state(sess, PJ_TURN_STATE_ALLOCATING); retransmit = (sess->conn_type == PJ_TURN_TP_UDP); status = pj_stun_session_send_msg(sess->stun, NULL, PJ_FALSE, - retransmit, sess->srv_addr, - pj_sockaddr_get_len(sess->srv_addr), - tdata); + retransmit, sess->srv_addr, + pj_sockaddr_get_len(sess->srv_addr), + tdata); if (status != PJ_SUCCESS) { - /* Set state back to RESOLVED. We don't want to destroy session now, - * let the application do it if it wants to. - */ - /* Set state back to RESOLVED may cause infinite loop (see #1942). */ - //set_state(sess, PJ_TURN_STATE_RESOLVED); + /* Set state back to RESOLVED. We don't want to destroy session now, + * let the application do it if it wants to. + */ + /* Set state back to RESOLVED may cause infinite loop (see #1942). */ + //set_state(sess, PJ_TURN_STATE_RESOLVED); } pj_grp_lock_release(sess->grp_lock); @@ -830,9 +829,9 @@ PJ_DEF(pj_status_t) pj_turn_session_alloc(pj_turn_session *sess, * Install or renew permissions */ PJ_DEF(pj_status_t) pj_turn_session_set_perm( pj_turn_session *sess, - unsigned addr_cnt, - const pj_sockaddr addr[], - unsigned options) + unsigned addr_cnt, + const pj_sockaddr addr[], + unsigned options) { pj_stun_tx_data *tdata; pj_hash_iterator_t it_buf, *it; @@ -846,11 +845,11 @@ PJ_DEF(pj_status_t) pj_turn_session_set_perm( pj_turn_session *sess, /* Create a bare CreatePermission request */ status = pj_stun_session_create_req(sess->stun, - PJ_STUN_CREATE_PERM_REQUEST, - PJ_STUN_MAGIC, NULL, &tdata); + PJ_STUN_CREATE_PERM_REQUEST, + PJ_STUN_MAGIC, NULL, &tdata); if (status != PJ_SUCCESS) { - pj_grp_lock_release(sess->grp_lock); - return status; + pj_grp_lock_release(sess->grp_lock); + return status; } /* Create request token to map the request to the perm structures @@ -860,49 +859,49 @@ PJ_DEF(pj_status_t) pj_turn_session_set_perm( pj_turn_session *sess, /* Process the addresses */ for (i=0; irenew = (options & 0x01); - - /* Only add to the request if the request doesn't contain this - * address yet. - */ - if (perm->req_token != req_token) { - perm->req_token = req_token; - - /* Add XOR-PEER-ADDRESS */ - status = pj_stun_msg_add_sockaddr_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_XOR_PEER_ADDR, - PJ_TRUE, - &addr[i], - sizeof(addr[i])); - if (status != PJ_SUCCESS) - goto on_error; - - ++attr_added; - } + struct perm_t *perm; + + /* Lookup the perm structure and create if it doesn't exist */ + perm = lookup_perm(sess, &addr[i], pj_sockaddr_get_len(&addr[i]), + PJ_TRUE); + perm->renew = (options & 0x01); + + /* Only add to the request if the request doesn't contain this + * address yet. + */ + if (perm->req_token != req_token) { + perm->req_token = req_token; + + /* Add XOR-PEER-ADDRESS */ + status = pj_stun_msg_add_sockaddr_attr(tdata->pool, tdata->msg, + PJ_STUN_ATTR_XOR_PEER_ADDR, + PJ_TRUE, + &addr[i], + sizeof(addr[i])); + if (status != PJ_SUCCESS) + goto on_error; + + ++attr_added; + } } /* No address to set */ if (attr_added == 0) { - pj_stun_msg_destroy_tdata(sess->stun, tdata); - pj_grp_lock_release(sess->grp_lock); - return PJ_SUCCESS; + pj_stun_msg_destroy_tdata(sess->stun, tdata); + pj_grp_lock_release(sess->grp_lock); + return PJ_SUCCESS; } /* Send the request */ status = pj_stun_session_send_msg(sess->stun, req_token, PJ_FALSE, - (sess->conn_type==PJ_TURN_TP_UDP), - sess->srv_addr, - pj_sockaddr_get_len(sess->srv_addr), - tdata); + (sess->conn_type==PJ_TURN_TP_UDP), + sess->srv_addr, + pj_sockaddr_get_len(sess->srv_addr), + tdata); if (status != PJ_SUCCESS) { - /* tdata is already destroyed */ - tdata = NULL; - goto on_error; + /* tdata is already destroyed */ + tdata = NULL; + goto on_error; } pj_grp_lock_release(sess->grp_lock); @@ -911,16 +910,16 @@ PJ_DEF(pj_status_t) pj_turn_session_set_perm( pj_turn_session *sess, on_error: /* destroy tdata */ if (tdata) { - pj_stun_msg_destroy_tdata(sess->stun, tdata); + pj_stun_msg_destroy_tdata(sess->stun, tdata); } /* invalidate perm structures associated with this request */ it = pj_hash_first(sess->perm_table, &it_buf); while (it) { - struct perm_t *perm = (struct perm_t*) - pj_hash_this(sess->perm_table, it); - it = pj_hash_next(sess->perm_table, it); - if (perm->req_token == req_token) - invalidate_perm(sess, perm); + struct perm_t *perm = (struct perm_t*) + pj_hash_this(sess->perm_table, it); + it = pj_hash_next(sess->perm_table, it); + if (perm->req_token == req_token) + invalidate_perm(sess, perm); } pj_grp_lock_release(sess->grp_lock); return status; @@ -938,35 +937,35 @@ static void send_refresh(pj_turn_session *sess, int lifetime) /* Create a bare REFRESH request */ status = pj_stun_session_create_req(sess->stun, PJ_STUN_REFRESH_REQUEST, - PJ_STUN_MAGIC, NULL, &tdata); + PJ_STUN_MAGIC, NULL, &tdata); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Add LIFETIME */ if (lifetime >= 0) { - pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_LIFETIME, lifetime); + pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, + PJ_STUN_ATTR_LIFETIME, lifetime); } /* Send request */ if (lifetime == 0) { - set_state(sess, PJ_TURN_STATE_DEALLOCATING); + set_state(sess, PJ_TURN_STATE_DEALLOCATING); } status = pj_stun_session_send_msg(sess->stun, NULL, PJ_FALSE, - (sess->conn_type==PJ_TURN_TP_UDP), - sess->srv_addr, - pj_sockaddr_get_len(sess->srv_addr), - tdata); + (sess->conn_type==PJ_TURN_TP_UDP), + sess->srv_addr, + pj_sockaddr_get_len(sess->srv_addr), + tdata); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; return; on_error: if (lifetime == 0) { - set_state(sess, PJ_TURN_STATE_DEALLOCATED); - sess_shutdown(sess, status); + set_state(sess, PJ_TURN_STATE_DEALLOCATED); + sess_shutdown(sess, status); } } @@ -975,21 +974,21 @@ static void send_refresh(pj_turn_session *sess, int lifetime) * Relay data to the specified peer through the session. */ PJ_DEF(pj_status_t) pj_turn_session_sendto( pj_turn_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_sockaddr_t *addr, - unsigned addr_len) + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_sockaddr_t *addr, + unsigned addr_len) { struct ch_t *ch; struct perm_t *perm; pj_status_t status; PJ_ASSERT_RETURN(sess && pkt && pkt_len && addr && addr_len, - PJ_EINVAL); + PJ_EINVAL); /* Return error if we're not ready */ if (sess->state != PJ_TURN_STATE_READY) { - return PJ_EIGNORED; + return PJ_EIGNORED; } /* Lock session now */ @@ -998,95 +997,95 @@ PJ_DEF(pj_status_t) pj_turn_session_sendto( pj_turn_session *sess, /* Lookup permission first */ perm = lookup_perm(sess, addr, pj_sockaddr_get_len(addr), PJ_FALSE); if (perm == NULL) { - /* Permission doesn't exist, install it first */ - char ipstr[PJ_INET6_ADDRSTRLEN+2]; - - PJ_LOG(4,(sess->obj_name, - "sendto(): IP %s has no permission, requesting it first..", - pj_sockaddr_print(addr, ipstr, sizeof(ipstr), 2))); - - status = pj_turn_session_set_perm(sess, 1, (const pj_sockaddr*)addr, - 0); - if (status != PJ_SUCCESS) { - pj_grp_lock_release(sess->grp_lock); - return status; - } + /* Permission doesn't exist, install it first */ + char ipstr[PJ_INET6_ADDRSTRLEN+2]; + + PJ_LOG(4,(sess->obj_name, + "sendto(): IP %s has no permission, requesting it first..", + pj_sockaddr_print(addr, ipstr, sizeof(ipstr), 2))); + + status = pj_turn_session_set_perm(sess, 1, (const pj_sockaddr*)addr, + 0); + if (status != PJ_SUCCESS) { + pj_grp_lock_release(sess->grp_lock); + return status; + } } /* If peer connection is TCP (RFC 6062), send it directly */ if (sess->alloc_param.peer_conn_type == PJ_TURN_TP_TCP) { - status = sess->cb.on_send_pkt(sess, pkt, pkt_len, addr, addr_len); - goto on_return; + status = sess->cb.on_send_pkt(sess, pkt, pkt_len, addr, addr_len); + goto on_return; } /* See if the peer is bound to a channel number */ ch = lookup_ch_by_addr(sess, addr, pj_sockaddr_get_len(addr), - PJ_FALSE, PJ_FALSE); + PJ_FALSE, PJ_FALSE); if (ch && ch->num != PJ_TURN_INVALID_CHANNEL && ch->bound) { - unsigned total_len; - - /* Peer is assigned a channel number, we can use ChannelData */ - pj_turn_channel_data *cd = (pj_turn_channel_data*)sess->tx_pkt; - - pj_assert(sizeof(*cd)==4); - - /* Calculate total length, including paddings */ - total_len = (pkt_len + sizeof(*cd) + 3) & (~3); - if (total_len > sizeof(sess->tx_pkt)) { - status = PJ_ETOOBIG; - goto on_return; - } + unsigned total_len; + + /* Peer is assigned a channel number, we can use ChannelData */ + pj_turn_channel_data *cd = (pj_turn_channel_data*)sess->tx_pkt; + + pj_assert(sizeof(*cd)==4); + + /* Calculate total length, including paddings */ + total_len = (pkt_len + sizeof(*cd) + 3) & (~3); + if (total_len > sizeof(sess->tx_pkt)) { + status = PJ_ETOOBIG; + goto on_return; + } - cd->ch_number = pj_htons((pj_uint16_t)ch->num); - cd->length = pj_htons((pj_uint16_t)pkt_len); - pj_memcpy(cd+1, pkt, pkt_len); + cd->ch_number = pj_htons((pj_uint16_t)ch->num); + cd->length = pj_htons((pj_uint16_t)pkt_len); + pj_memcpy(cd+1, pkt, pkt_len); - pj_assert(sess->srv_addr != NULL); + pj_assert(sess->srv_addr != NULL); - status = sess->cb.on_send_pkt(sess, sess->tx_pkt, total_len, - sess->srv_addr, - pj_sockaddr_get_len(sess->srv_addr)); + status = sess->cb.on_send_pkt(sess, sess->tx_pkt, total_len, + sess->srv_addr, + pj_sockaddr_get_len(sess->srv_addr)); } else { - /* Use Send Indication. */ - pj_stun_sockaddr_attr peer_attr; - pj_stun_binary_attr data_attr; - pj_stun_msg send_ind; - pj_size_t send_ind_len; - - /* Increment counter */ - ++sess->send_ind_tsx_id[2]; - - /* Create blank SEND-INDICATION */ - status = pj_stun_msg_init(&send_ind, PJ_STUN_SEND_INDICATION, - PJ_STUN_MAGIC, - (const pj_uint8_t*)sess->send_ind_tsx_id); - if (status != PJ_SUCCESS) - goto on_return; - - /* Add XOR-PEER-ADDRESS */ - pj_stun_sockaddr_attr_init(&peer_attr, PJ_STUN_ATTR_XOR_PEER_ADDR, - PJ_TRUE, addr, addr_len); - pj_stun_msg_add_attr(&send_ind, (pj_stun_attr_hdr*)&peer_attr); - - /* Add DATA attribute */ - pj_stun_binary_attr_init(&data_attr, NULL, PJ_STUN_ATTR_DATA, NULL, 0); - data_attr.data = (pj_uint8_t*)pkt; - data_attr.length = pkt_len; - pj_stun_msg_add_attr(&send_ind, (pj_stun_attr_hdr*)&data_attr); - - /* Encode the message */ - status = pj_stun_msg_encode(&send_ind, sess->tx_pkt, - sizeof(sess->tx_pkt), 0, - NULL, &send_ind_len); - if (status != PJ_SUCCESS) - goto on_return; - - /* Send the Send Indication */ - status = sess->cb.on_send_pkt(sess, sess->tx_pkt, - (unsigned)send_ind_len, - sess->srv_addr, - pj_sockaddr_get_len(sess->srv_addr)); + /* Use Send Indication. */ + pj_stun_sockaddr_attr peer_attr; + pj_stun_binary_attr data_attr; + pj_stun_msg send_ind; + pj_size_t send_ind_len; + + /* Increment counter */ + ++sess->send_ind_tsx_id[2]; + + /* Create blank SEND-INDICATION */ + status = pj_stun_msg_init(&send_ind, PJ_STUN_SEND_INDICATION, + PJ_STUN_MAGIC, + (const pj_uint8_t*)sess->send_ind_tsx_id); + if (status != PJ_SUCCESS) + goto on_return; + + /* Add XOR-PEER-ADDRESS */ + pj_stun_sockaddr_attr_init(&peer_attr, PJ_STUN_ATTR_XOR_PEER_ADDR, + PJ_TRUE, addr, addr_len); + pj_stun_msg_add_attr(&send_ind, (pj_stun_attr_hdr*)&peer_attr); + + /* Add DATA attribute */ + pj_stun_binary_attr_init(&data_attr, NULL, PJ_STUN_ATTR_DATA, NULL, 0); + data_attr.data = (pj_uint8_t*)pkt; + data_attr.length = pkt_len; + pj_stun_msg_add_attr(&send_ind, (pj_stun_attr_hdr*)&data_attr); + + /* Encode the message */ + status = pj_stun_msg_encode(&send_ind, sess->tx_pkt, + sizeof(sess->tx_pkt), 0, + NULL, &send_ind_len); + if (status != PJ_SUCCESS) + goto on_return; + + /* Send the Send Indication */ + status = sess->cb.on_send_pkt(sess, sess->tx_pkt, + (unsigned)send_ind_len, + sess->srv_addr, + pj_sockaddr_get_len(sess->srv_addr)); } on_return: @@ -1099,8 +1098,8 @@ PJ_DEF(pj_status_t) pj_turn_session_sendto( pj_turn_session *sess, * Bind a peer address to a channel number. */ PJ_DEF(pj_status_t) pj_turn_session_bind_channel(pj_turn_session *sess, - const pj_sockaddr_t *peer_adr, - unsigned addr_len) + const pj_sockaddr_t *peer_adr, + unsigned addr_len) { struct ch_t *ch; pj_stun_tx_data *tdata; @@ -1114,43 +1113,43 @@ PJ_DEF(pj_status_t) pj_turn_session_bind_channel(pj_turn_session *sess, /* Create blank ChannelBind request */ status = pj_stun_session_create_req(sess->stun, - PJ_STUN_CHANNEL_BIND_REQUEST, - PJ_STUN_MAGIC, NULL, &tdata); + PJ_STUN_CHANNEL_BIND_REQUEST, + PJ_STUN_MAGIC, NULL, &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Lookup if this peer has already been assigned a number */ ch = lookup_ch_by_addr(sess, peer_adr, pj_sockaddr_get_len(peer_adr), - PJ_TRUE, PJ_FALSE); + PJ_TRUE, PJ_FALSE); pj_assert(ch); if (ch->num != PJ_TURN_INVALID_CHANNEL) { - /* Channel is already bound. This is a refresh request. */ - ch_num = ch->num; + /* Channel is already bound. This is a refresh request. */ + ch_num = ch->num; } else { - PJ_ASSERT_ON_FAIL(sess->next_ch <= PJ_TURN_CHANNEL_MAX, - {status=PJ_ETOOMANY; goto on_return;}); - ch->num = ch_num = sess->next_ch++; + PJ_ASSERT_ON_FAIL(sess->next_ch <= PJ_TURN_CHANNEL_MAX, + {status=PJ_ETOOMANY; goto on_return;}); + ch->num = ch_num = sess->next_ch++; } /* Add CHANNEL-NUMBER attribute */ pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_CHANNEL_NUMBER, - PJ_STUN_SET_CH_NB(ch_num)); + PJ_STUN_ATTR_CHANNEL_NUMBER, + PJ_STUN_SET_CH_NB(ch_num)); /* Add XOR-PEER-ADDRESS attribute */ pj_stun_msg_add_sockaddr_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_XOR_PEER_ADDR, PJ_TRUE, - peer_adr, addr_len); + PJ_STUN_ATTR_XOR_PEER_ADDR, PJ_TRUE, + peer_adr, addr_len); /* Send the request, associate peer data structure with tdata * for future reference when we receive the ChannelBind response. */ status = pj_stun_session_send_msg(sess->stun, ch, PJ_FALSE, - (sess->conn_type==PJ_TURN_TP_UDP), - sess->srv_addr, - pj_sockaddr_get_len(sess->srv_addr), - tdata); + (sess->conn_type==PJ_TURN_TP_UDP), + sess->srv_addr, + pj_sockaddr_get_len(sess->srv_addr), + tdata); on_return: pj_grp_lock_release(sess->grp_lock); @@ -1162,33 +1161,33 @@ PJ_DEF(pj_status_t) pj_turn_session_bind_channel(pj_turn_session *sess, * Send ConnectionBind request. */ PJ_DEF(pj_status_t) pj_turn_session_connection_bind( - pj_turn_session *sess, - pj_pool_t *pool, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len) + pj_turn_session *sess, + pj_pool_t *pool, + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len) { pj_stun_tx_data *tdata; struct conn_bind_t *conn_bind; pj_status_t status; PJ_ASSERT_RETURN(sess && pool && conn_id && peer_addr && addr_len, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(sess->state == PJ_TURN_STATE_READY, PJ_EINVALIDOP); pj_grp_lock_acquire(sess->grp_lock); /* Create blank ConnectionBind request */ status = pj_stun_session_create_req(sess->stun, - PJ_STUN_CONNECTION_BIND_REQUEST, - PJ_STUN_MAGIC, NULL, &tdata); + PJ_STUN_CONNECTION_BIND_REQUEST, + PJ_STUN_MAGIC, NULL, &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Add CONNECTION_ID attribute */ pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_CONNECTION_ID, - conn_id); + PJ_STUN_ATTR_CONNECTION_ID, + conn_id); conn_bind = PJ_POOL_ZALLOC_T(pool, struct conn_bind_t); conn_bind->id = conn_id; @@ -1199,7 +1198,7 @@ PJ_DEF(pj_status_t) pj_turn_session_connection_bind( * for future reference when we receive the ConnectionBind response. */ status = pj_stun_session_send_msg(sess->stun, conn_bind, PJ_FALSE, - PJ_FALSE, peer_addr, addr_len, tdata); + PJ_FALSE, peer_addr, addr_len, tdata); on_return: pj_grp_lock_release(sess->grp_lock); @@ -1210,8 +1209,8 @@ PJ_DEF(pj_status_t) pj_turn_session_connection_bind( * Send Connect request. */ PJ_DEF(pj_status_t) pj_turn_session_connect(pj_turn_session *sess, - const pj_sockaddr_t *peer_addr, - unsigned addr_len) + const pj_sockaddr_t *peer_addr, + unsigned addr_len) { pj_stun_tx_data *tdata; pj_status_t status; @@ -1223,18 +1222,18 @@ PJ_DEF(pj_status_t) pj_turn_session_connect(pj_turn_session *sess, /* Create blank Connect request */ status = pj_stun_session_create_req(sess->stun, PJ_STUN_CONNECT_REQUEST, - PJ_STUN_MAGIC, NULL, &tdata); + PJ_STUN_MAGIC, NULL, &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; status = pj_stun_msg_add_sockaddr_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_XOR_PEER_ADDR, - PJ_TRUE, peer_addr, addr_len); + PJ_STUN_ATTR_XOR_PEER_ADDR, + PJ_TRUE, peer_addr, addr_len); if (status != PJ_SUCCESS) goto on_return; status = pj_stun_session_send_msg(sess->stun, (void *)peer_addr, PJ_FALSE, - PJ_FALSE, sess->srv_addr, - pj_sockaddr_get_len(sess->srv_addr), - tdata); + PJ_FALSE, sess->srv_addr, + pj_sockaddr_get_len(sess->srv_addr), + tdata); on_return: pj_grp_lock_release(sess->grp_lock); @@ -1242,9 +1241,9 @@ PJ_DEF(pj_status_t) pj_turn_session_connect(pj_turn_session *sess, } PJ_DEF(pj_status_t) pj_turn_session_on_rx_pkt(pj_turn_session *sess, - void *pkt, - pj_size_t pkt_len, - pj_size_t *parsed_len) + void *pkt, + pj_size_t pkt_len, + pj_size_t *parsed_len) { pj_turn_session_on_rx_pkt_param prm; pj_status_t status; @@ -1254,7 +1253,7 @@ PJ_DEF(pj_status_t) pj_turn_session_on_rx_pkt(pj_turn_session *sess, prm.pkt_len = pkt_len; status = pj_turn_session_on_rx_pkt2(sess, &prm); if (status == PJ_SUCCESS && parsed_len) - *parsed_len = prm.parsed_len; + *parsed_len = prm.parsed_len; return status; } @@ -1263,8 +1262,8 @@ PJ_DEF(pj_status_t) pj_turn_session_on_rx_pkt(pj_turn_session *sess, * The packet maybe a STUN packet or ChannelData packet. */ PJ_DEF(pj_status_t) pj_turn_session_on_rx_pkt2( - pj_turn_session *sess, - pj_turn_session_on_rx_pkt_param *prm) + pj_turn_session *sess, + pj_turn_session_on_rx_pkt_param *prm) { pj_bool_t is_stun; pj_status_t status; @@ -1283,67 +1282,67 @@ PJ_DEF(pj_status_t) pj_turn_session_on_rx_pkt2( is_stun = ((((pj_uint8_t*)prm->pkt)[0] & 0xC0) == 0); if (is_stun) { - /* This looks like STUN, give it to the STUN session */ - unsigned options; - const pj_sockaddr_t *src_addr = prm->src_addr? - prm->src_addr:sess->srv_addr; - unsigned src_addr_len = prm->src_addr_len? prm->src_addr_len: - pj_sockaddr_get_len(sess->srv_addr); - - options = PJ_STUN_CHECK_PACKET | PJ_STUN_NO_FINGERPRINT_CHECK; - if (is_datagram) - options |= PJ_STUN_IS_DATAGRAM; - status=pj_stun_session_on_rx_pkt(sess->stun, prm->pkt, prm->pkt_len, - options, NULL, &prm->parsed_len, - src_addr, src_addr_len); + /* This looks like STUN, give it to the STUN session */ + unsigned options; + const pj_sockaddr_t *src_addr = prm->src_addr? + prm->src_addr:sess->srv_addr; + unsigned src_addr_len = prm->src_addr_len? prm->src_addr_len: + pj_sockaddr_get_len(sess->srv_addr); + + options = PJ_STUN_CHECK_PACKET | PJ_STUN_NO_FINGERPRINT_CHECK; + if (is_datagram) + options |= PJ_STUN_IS_DATAGRAM; + status=pj_stun_session_on_rx_pkt(sess->stun, prm->pkt, prm->pkt_len, + options, NULL, &prm->parsed_len, + src_addr, src_addr_len); } else { - /* This must be ChannelData. */ - pj_turn_channel_data cd; - struct ch_t *ch; - - if (prm->pkt_len < 4) { - prm->parsed_len = 0; - status = PJ_ETOOSMALL; - goto on_return; - } - - /* Decode ChannelData packet */ - pj_memcpy(&cd, prm->pkt, sizeof(pj_turn_channel_data)); - cd.ch_number = pj_ntohs(cd.ch_number); - cd.length = pj_ntohs(cd.length); - - /* Check that size is sane */ - if (prm->pkt_len < cd.length+sizeof(cd)) { - if (is_datagram) { - /* Discard the datagram */ - prm->parsed_len = prm->pkt_len; - } else { - /* Insufficient fragment */ - prm->parsed_len = 0; - } - status = PJ_ETOOSMALL; - goto on_return; - } else { - /* Apply padding too */ - prm->parsed_len = ((cd.length + 3) & (~3)) + sizeof(cd); - } - - /* Lookup channel */ - ch = lookup_ch_by_chnum(sess, cd.ch_number); - if (!ch || !ch->bound) { - status = PJ_ENOTFOUND; - goto on_return; - } - - /* Notify application */ - if (sess->cb.on_rx_data) { - (*sess->cb.on_rx_data)(sess, ((pj_uint8_t*)prm->pkt)+sizeof(cd), - cd.length, &ch->addr, - pj_sockaddr_get_len(&ch->addr)); - } - - status = PJ_SUCCESS; + /* This must be ChannelData. */ + pj_turn_channel_data cd; + struct ch_t *ch; + + if (prm->pkt_len < 4) { + prm->parsed_len = 0; + status = PJ_ETOOSMALL; + goto on_return; + } + + /* Decode ChannelData packet */ + pj_memcpy(&cd, prm->pkt, sizeof(pj_turn_channel_data)); + cd.ch_number = pj_ntohs(cd.ch_number); + cd.length = pj_ntohs(cd.length); + + /* Check that size is sane */ + if (prm->pkt_len < cd.length+sizeof(cd)) { + if (is_datagram) { + /* Discard the datagram */ + prm->parsed_len = prm->pkt_len; + } else { + /* Insufficient fragment */ + prm->parsed_len = 0; + } + status = PJ_ETOOSMALL; + goto on_return; + } else { + /* Apply padding too */ + prm->parsed_len = ((cd.length + 3) & (~3)) + sizeof(cd); + } + + /* Lookup channel */ + ch = lookup_ch_by_chnum(sess, cd.ch_number); + if (!ch || !ch->bound) { + status = PJ_ENOTFOUND; + goto on_return; + } + + /* Notify application */ + if (sess->cb.on_rx_data) { + (*sess->cb.on_rx_data)(sess, ((pj_uint8_t*)prm->pkt)+sizeof(cd), + cd.length, &ch->addr, + pj_sockaddr_get_len(&ch->addr)); + } + + status = PJ_SUCCESS; } on_return: @@ -1356,11 +1355,11 @@ PJ_DEF(pj_status_t) pj_turn_session_on_rx_pkt2( * This is a callback from STUN session to send outgoing packet. */ static pj_status_t stun_on_send_msg(pj_stun_session *stun, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len) + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len) { pj_turn_session *sess; @@ -1368,13 +1367,13 @@ static pj_status_t stun_on_send_msg(pj_stun_session *stun, sess = (pj_turn_session*) pj_stun_session_get_user_data(stun); if (sess->cb.on_stun_send_pkt) { - return (*sess->cb.on_stun_send_pkt)(sess, (const pj_uint8_t*)pkt, - (unsigned)pkt_size, - dst_addr, addr_len); + return (*sess->cb.on_stun_send_pkt)(sess, (const pj_uint8_t*)pkt, + (unsigned)pkt_size, + dst_addr, addr_len); } else { - return (*sess->cb.on_send_pkt)(sess, (const pj_uint8_t*)pkt, - (unsigned)pkt_size, - dst_addr, addr_len); + return (*sess->cb.on_send_pkt)(sess, (const pj_uint8_t*)pkt, + (unsigned)pkt_size, + dst_addr, addr_len); } } @@ -1384,54 +1383,54 @@ static pj_status_t stun_on_send_msg(pj_stun_session *stun, * server if we have one. */ static void on_session_fail( pj_turn_session *sess, - enum pj_stun_method_e method, - pj_status_t status, - const pj_str_t *reason) + enum pj_stun_method_e method, + pj_status_t status, + const pj_str_t *reason) { sess->last_status = status; do { - pj_str_t reason1; - char err_msg[PJ_ERR_MSG_SIZE]; - - if (reason == NULL) { - pj_strerror(status, err_msg, sizeof(err_msg)); - reason1 = pj_str(err_msg); - reason = &reason1; - } - - PJ_LOG(4,(sess->obj_name, "%s error: %.*s", - pj_stun_get_method_name(method), - (int)reason->slen, reason->ptr)); - - /* If this is ALLOCATE response and we don't have more server - * addresses to try, notify application and destroy the TURN - * session. - */ - if (method==PJ_STUN_ALLOCATE_METHOD && - sess->srv_addr == &sess->srv_addr_list[sess->srv_addr_cnt-1]) - { - - set_state(sess, PJ_TURN_STATE_DEALLOCATED); - sess_shutdown(sess, status); - return; - } - - /* Otherwise if this is not ALLOCATE response, notify application - * that session has been TERMINATED. - */ - if (method!=PJ_STUN_ALLOCATE_METHOD) { - set_state(sess, PJ_TURN_STATE_DEALLOCATED); - sess_shutdown(sess, status); - return; - } - - /* Try next server */ - ++sess->srv_addr; - reason = NULL; - - PJ_LOG(4,(sess->obj_name, "Trying next server")); - set_state(sess, PJ_TURN_STATE_RESOLVED); + pj_str_t reason1; + char err_msg[PJ_ERR_MSG_SIZE]; + + if (reason == NULL) { + pj_strerror(status, err_msg, sizeof(err_msg)); + reason1 = pj_str(err_msg); + reason = &reason1; + } + + PJ_LOG(4,(sess->obj_name, "%s error: %.*s", + pj_stun_get_method_name(method), + (int)reason->slen, reason->ptr)); + + /* If this is ALLOCATE response and we don't have more server + * addresses to try, notify application and destroy the TURN + * session. + */ + if (method==PJ_STUN_ALLOCATE_METHOD && + sess->srv_addr == &sess->srv_addr_list[sess->srv_addr_cnt-1]) + { + + set_state(sess, PJ_TURN_STATE_DEALLOCATED); + sess_shutdown(sess, status); + return; + } + + /* Otherwise if this is not ALLOCATE response, notify application + * that session has been TERMINATED. + */ + if (method!=PJ_STUN_ALLOCATE_METHOD) { + set_state(sess, PJ_TURN_STATE_DEALLOCATED); + sess_shutdown(sess, status); + return; + } + + /* Try next server */ + ++sess->srv_addr; + reason = NULL; + + PJ_LOG(4,(sess->obj_name, "Trying next server")); + set_state(sess, PJ_TURN_STATE_RESOLVED); } while (0); } @@ -1441,8 +1440,8 @@ static void on_session_fail( pj_turn_session *sess, * Handle successful response to ALLOCATE or REFRESH request. */ static void on_allocate_success(pj_turn_session *sess, - enum pj_stun_method_e method, - const pj_stun_msg *msg) + enum pj_stun_method_e method, + const pj_stun_msg *msg) { const pj_stun_lifetime_attr *lf_attr; const pj_stun_xor_relayed_addr_attr *raddr_attr; @@ -1451,18 +1450,18 @@ static void on_allocate_success(pj_turn_session *sess, /* Must have LIFETIME attribute */ lf_attr = (const pj_stun_lifetime_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_LIFETIME, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_LIFETIME, 0); if (lf_attr == NULL) { - on_session_fail(sess, method, PJNATH_EINSTUNMSG, - pj_cstr(&s, "Error: Missing LIFETIME attribute")); - return; + on_session_fail(sess, method, PJNATH_EINSTUNMSG, + pj_cstr(&s, "Error: Missing LIFETIME attribute")); + return; } /* If LIFETIME is zero, this is a deallocation */ if (lf_attr->value == 0) { - set_state(sess, PJ_TURN_STATE_DEALLOCATED); - sess_shutdown(sess, PJ_SUCCESS); - return; + set_state(sess, PJ_TURN_STATE_DEALLOCATED); + sess_shutdown(sess, PJ_SUCCESS); + return; } /* Update lifetime and keep-alive interval */ @@ -1470,79 +1469,79 @@ static void on_allocate_success(pj_turn_session *sess, pj_gettimeofday(&sess->expiry); if (sess->lifetime < PJ_TURN_KEEP_ALIVE_SEC) { - if (sess->lifetime <= 2) { - on_session_fail(sess, method, PJ_ETOOSMALL, - pj_cstr(&s, "Error: LIFETIME too small")); - return; - } - sess->ka_interval = sess->lifetime - 2; - sess->expiry.sec += (sess->ka_interval-1); + if (sess->lifetime <= 2) { + on_session_fail(sess, method, PJ_ETOOSMALL, + pj_cstr(&s, "Error: LIFETIME too small")); + return; + } + sess->ka_interval = sess->lifetime - 2; + sess->expiry.sec += (sess->ka_interval-1); } else { - int timeout; + int timeout; - sess->ka_interval = PJ_TURN_KEEP_ALIVE_SEC; + sess->ka_interval = PJ_TURN_KEEP_ALIVE_SEC; - timeout = sess->lifetime - PJ_TURN_REFRESH_SEC_BEFORE; - if (timeout < sess->ka_interval) - timeout = sess->ka_interval - 1; + timeout = sess->lifetime - PJ_TURN_REFRESH_SEC_BEFORE; + if (timeout < sess->ka_interval) + timeout = sess->ka_interval - 1; - sess->expiry.sec += timeout; + sess->expiry.sec += timeout; } /* Check that relayed transport address contains correct * address family. */ raddr_attr = (const pj_stun_xor_relayed_addr_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_XOR_RELAYED_ADDR, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_XOR_RELAYED_ADDR, 0); if (raddr_attr == NULL && method==PJ_STUN_ALLOCATE_METHOD) { - on_session_fail(sess, method, PJNATH_EINSTUNMSG, - pj_cstr(&s, "Error: Received ALLOCATE without " - "RELAY-ADDRESS attribute")); - return; + on_session_fail(sess, method, PJNATH_EINSTUNMSG, + pj_cstr(&s, "Error: Received ALLOCATE without " + "RELAY-ADDRESS attribute")); + return; } if (raddr_attr && - ((sess->alloc_param.af != 0 && - raddr_attr->sockaddr.addr.sa_family != sess->alloc_param.af) || - (sess->alloc_param.af == 0 && - raddr_attr->sockaddr.addr.sa_family != sess->af))) + ((sess->alloc_param.af != 0 && + raddr_attr->sockaddr.addr.sa_family != sess->alloc_param.af) || + (sess->alloc_param.af == 0 && + raddr_attr->sockaddr.addr.sa_family != sess->af))) { - on_session_fail(sess, method, PJNATH_EINSTUNMSG, - pj_cstr(&s, "Error: Mismatched RELAY-ADDRESS " - "address family")); - return; + on_session_fail(sess, method, PJNATH_EINSTUNMSG, + pj_cstr(&s, "Error: Mismatched RELAY-ADDRESS " + "address family")); + return; } if (raddr_attr && !pj_sockaddr_has_addr(&raddr_attr->sockaddr)) { - on_session_fail(sess, method, PJNATH_EINSTUNMSG, - pj_cstr(&s, "Error: Invalid IP address in " - "RELAY-ADDRESS attribute")); - return; + on_session_fail(sess, method, PJNATH_EINSTUNMSG, + pj_cstr(&s, "Error: Invalid IP address in " + "RELAY-ADDRESS attribute")); + return; } /* Save relayed address */ if (raddr_attr) { - /* If we already have relay address, check if the relay address - * in the response matches our relay address. - */ - if (pj_sockaddr_has_addr(&sess->relay_addr)) { - if (pj_sockaddr_cmp(&sess->relay_addr, &raddr_attr->sockaddr)) { - on_session_fail(sess, method, PJNATH_EINSTUNMSG, - pj_cstr(&s, "Error: different RELAY-ADDRESS is" - "returned by server")); - return; - } - } else { - /* Otherwise save the relayed address */ - pj_memcpy(&sess->relay_addr, &raddr_attr->sockaddr, - sizeof(pj_sockaddr)); - } + /* If we already have relay address, check if the relay address + * in the response matches our relay address. + */ + if (pj_sockaddr_has_addr(&sess->relay_addr)) { + if (pj_sockaddr_cmp(&sess->relay_addr, &raddr_attr->sockaddr)) { + on_session_fail(sess, method, PJNATH_EINSTUNMSG, + pj_cstr(&s, "Error: different RELAY-ADDRESS is" + "returned by server")); + return; + } + } else { + /* Otherwise save the relayed address */ + pj_memcpy(&sess->relay_addr, &raddr_attr->sockaddr, + sizeof(pj_sockaddr)); + } } /* Get mapped address */ mapped_attr = (const pj_stun_sockaddr_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_XOR_MAPPED_ADDR, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_XOR_MAPPED_ADDR, 0); if (mapped_attr) { - pj_memcpy(&sess->mapped_addr, &mapped_attr->sockaddr, - sizeof(mapped_attr->sockaddr)); + pj_memcpy(&sess->mapped_addr, &mapped_attr->sockaddr, + sizeof(mapped_attr->sockaddr)); } /* Success */ @@ -1550,21 +1549,21 @@ static void on_allocate_success(pj_turn_session *sess, /* Cancel existing keep-alive timer, if any */ pj_assert(sess->timer.id != TIMER_DESTROY); if (sess->timer.id == TIMER_KEEP_ALIVE) { - pj_timer_heap_cancel_if_active(sess->timer_heap, &sess->timer, - TIMER_NONE); + pj_timer_heap_cancel_if_active(sess->timer_heap, &sess->timer, + TIMER_NONE); } /* Start keep-alive timer once allocation succeeds */ if (sess->state < PJ_TURN_STATE_DEALLOCATING) { - pj_time_val timeout; - timeout.sec = sess->ka_interval; - timeout.msec = 0; + pj_time_val timeout; + timeout.sec = sess->ka_interval; + timeout.msec = 0; - pj_timer_heap_schedule_w_grp_lock(sess->timer_heap, &sess->timer, - &timeout, TIMER_KEEP_ALIVE, - sess->grp_lock); + pj_timer_heap_schedule_w_grp_lock(sess->timer_heap, &sess->timer, + &timeout, TIMER_KEEP_ALIVE, + sess->grp_lock); - set_state(sess, PJ_TURN_STATE_READY); + set_state(sess, PJ_TURN_STATE_READY); } } @@ -1572,16 +1571,16 @@ static void on_allocate_success(pj_turn_session *sess, * Notification from STUN session on request completion. */ static void stun_on_request_complete(pj_stun_session *stun, - pj_status_t status, - void *token, - pj_stun_tx_data *tdata, - const pj_stun_msg *response, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + pj_status_t status, + void *token, + pj_stun_tx_data *tdata, + const pj_stun_msg *response, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_turn_session *sess; enum pj_stun_method_e method = (enum pj_stun_method_e) - PJ_STUN_GET_METHOD(tdata->msg->hdr.type); + PJ_STUN_GET_METHOD(tdata->msg->hdr.type); PJ_UNUSED_ARG(src_addr); PJ_UNUSED_ARG(src_addr_len); @@ -1590,260 +1589,260 @@ static void stun_on_request_complete(pj_stun_session *stun, if (method == PJ_STUN_ALLOCATE_METHOD) { - /* Destroy if we have pending destroy request */ - if (sess->pending_destroy) { - if (status == PJ_SUCCESS) - sess->state = PJ_TURN_STATE_READY; - else - sess->state = PJ_TURN_STATE_DEALLOCATED; - sess_shutdown(sess, PJ_SUCCESS); - return; - } - - /* Handle ALLOCATE response */ - if (status==PJ_SUCCESS && - PJ_STUN_IS_SUCCESS_RESPONSE(response->hdr.type)) - { - - /* Successful Allocate response */ - on_allocate_success(sess, method, response); - - } else { - /* Failed Allocate request */ - const pj_str_t *err_msg = NULL; - - if (status == PJ_SUCCESS) { - const pj_stun_errcode_attr *err_attr; - err_attr = (const pj_stun_errcode_attr*) - pj_stun_msg_find_attr(response, - PJ_STUN_ATTR_ERROR_CODE, 0); - if (err_attr) { - status = PJ_STATUS_FROM_STUN_CODE(err_attr->err_code); - err_msg = &err_attr->reason; - } else { - status = PJNATH_EINSTUNMSG; - } - } - - on_session_fail(sess, method, status, err_msg); - } + /* Destroy if we have pending destroy request */ + if (sess->pending_destroy) { + if (status == PJ_SUCCESS) + sess->state = PJ_TURN_STATE_READY; + else + sess->state = PJ_TURN_STATE_DEALLOCATED; + sess_shutdown(sess, PJ_SUCCESS); + return; + } + + /* Handle ALLOCATE response */ + if (status==PJ_SUCCESS && + PJ_STUN_IS_SUCCESS_RESPONSE(response->hdr.type)) + { + + /* Successful Allocate response */ + on_allocate_success(sess, method, response); + + } else { + /* Failed Allocate request */ + const pj_str_t *err_msg = NULL; + + if (status == PJ_SUCCESS) { + const pj_stun_errcode_attr *err_attr; + err_attr = (const pj_stun_errcode_attr*) + pj_stun_msg_find_attr(response, + PJ_STUN_ATTR_ERROR_CODE, 0); + if (err_attr) { + status = PJ_STATUS_FROM_STUN_CODE(err_attr->err_code); + err_msg = &err_attr->reason; + } else { + status = PJNATH_EINSTUNMSG; + } + } + + on_session_fail(sess, method, status, err_msg); + } } else if (method == PJ_STUN_REFRESH_METHOD) { - /* Handle Refresh response */ - if (status==PJ_SUCCESS && - PJ_STUN_IS_SUCCESS_RESPONSE(response->hdr.type)) - { - /* Success, schedule next refresh. */ - on_allocate_success(sess, method, response); - - } else { - /* Failed Refresh request */ - const pj_str_t *err_msg = NULL; - - pj_assert(status != PJ_SUCCESS); - - if (response) { - const pj_stun_errcode_attr *err_attr; - err_attr = (const pj_stun_errcode_attr*) - pj_stun_msg_find_attr(response, - PJ_STUN_ATTR_ERROR_CODE, 0); - if (err_attr) { - status = PJ_STATUS_FROM_STUN_CODE(err_attr->err_code); - err_msg = &err_attr->reason; - } - } - - /* Notify and destroy */ - on_session_fail(sess, method, status, err_msg); - } + /* Handle Refresh response */ + if (status==PJ_SUCCESS && + PJ_STUN_IS_SUCCESS_RESPONSE(response->hdr.type)) + { + /* Success, schedule next refresh. */ + on_allocate_success(sess, method, response); + + } else { + /* Failed Refresh request */ + const pj_str_t *err_msg = NULL; + + pj_assert(status != PJ_SUCCESS); + + if (response) { + const pj_stun_errcode_attr *err_attr; + err_attr = (const pj_stun_errcode_attr*) + pj_stun_msg_find_attr(response, + PJ_STUN_ATTR_ERROR_CODE, 0); + if (err_attr) { + status = PJ_STATUS_FROM_STUN_CODE(err_attr->err_code); + err_msg = &err_attr->reason; + } + } + + /* Notify and destroy */ + on_session_fail(sess, method, status, err_msg); + } } else if (method == PJ_STUN_CHANNEL_BIND_METHOD) { - /* Handle ChannelBind response */ - if (status==PJ_SUCCESS && - PJ_STUN_IS_SUCCESS_RESPONSE(response->hdr.type)) - { - /* Successful ChannelBind response */ - struct ch_t *ch = (struct ch_t*)token; - - pj_assert(ch->num != PJ_TURN_INVALID_CHANNEL); - ch->bound = PJ_TRUE; - - /* Update hash table */ - lookup_ch_by_addr(sess, &ch->addr, - pj_sockaddr_get_len(&ch->addr), - PJ_TRUE, PJ_TRUE); - - } else { - /* Failed ChannelBind response */ - pj_str_t reason = {"", 0}; - int err_code = 0; - char errbuf[PJ_ERR_MSG_SIZE]; - - pj_assert(status != PJ_SUCCESS); - - if (response) { - const pj_stun_errcode_attr *err_attr; - err_attr = (const pj_stun_errcode_attr*) - pj_stun_msg_find_attr(response, - PJ_STUN_ATTR_ERROR_CODE, 0); - if (err_attr) { - err_code = err_attr->err_code; - status = PJ_STATUS_FROM_STUN_CODE(err_attr->err_code); - reason = err_attr->reason; - } - } else { - err_code = status; - reason = pj_strerror(status, errbuf, sizeof(errbuf)); - } - - PJ_LOG(1,(sess->obj_name, "ChannelBind failed: %d/%.*s", - err_code, (int)reason.slen, reason.ptr)); - - if (err_code == PJ_STUN_SC_ALLOCATION_MISMATCH) { - /* Allocation mismatch means allocation no longer exists */ - on_session_fail(sess, PJ_STUN_CHANNEL_BIND_METHOD, - status, &reason); - return; - } - } + /* Handle ChannelBind response */ + if (status==PJ_SUCCESS && + PJ_STUN_IS_SUCCESS_RESPONSE(response->hdr.type)) + { + /* Successful ChannelBind response */ + struct ch_t *ch = (struct ch_t*)token; + + pj_assert(ch->num != PJ_TURN_INVALID_CHANNEL); + ch->bound = PJ_TRUE; + + /* Update hash table */ + lookup_ch_by_addr(sess, &ch->addr, + pj_sockaddr_get_len(&ch->addr), + PJ_TRUE, PJ_TRUE); + + } else { + /* Failed ChannelBind response */ + pj_str_t reason = {"", 0}; + int err_code = 0; + char errbuf[PJ_ERR_MSG_SIZE]; + + pj_assert(status != PJ_SUCCESS); + + if (response) { + const pj_stun_errcode_attr *err_attr; + err_attr = (const pj_stun_errcode_attr*) + pj_stun_msg_find_attr(response, + PJ_STUN_ATTR_ERROR_CODE, 0); + if (err_attr) { + err_code = err_attr->err_code; + status = PJ_STATUS_FROM_STUN_CODE(err_attr->err_code); + reason = err_attr->reason; + } + } else { + err_code = status; + reason = pj_strerror(status, errbuf, sizeof(errbuf)); + } + + PJ_LOG(1,(sess->obj_name, "ChannelBind failed: %d/%.*s", + err_code, (int)reason.slen, reason.ptr)); + + if (err_code == PJ_STUN_SC_ALLOCATION_MISMATCH) { + /* Allocation mismatch means allocation no longer exists */ + on_session_fail(sess, PJ_STUN_CHANNEL_BIND_METHOD, + status, &reason); + return; + } + } } else if (method == PJ_STUN_CREATE_PERM_METHOD) { - /* Handle CreatePermission response */ - if (status==PJ_SUCCESS && - PJ_STUN_IS_SUCCESS_RESPONSE(response->hdr.type)) - { - /* No special handling when the request is successful. */ - } else { - /* Iterate the permission table and invalidate all permissions - * that are related to this request. - */ - pj_hash_iterator_t it_buf, *it; - char ipstr[PJ_INET6_ADDRSTRLEN+10]; - int err_code; - char errbuf[PJ_ERR_MSG_SIZE]; - pj_str_t reason; - - pj_assert(status != PJ_SUCCESS); - - if (response) { - const pj_stun_errcode_attr *eattr; - - eattr = (const pj_stun_errcode_attr*) - pj_stun_msg_find_attr(response, - PJ_STUN_ATTR_ERROR_CODE, 0); - if (eattr) { - err_code = eattr->err_code; - reason = eattr->reason; - } else { - err_code = -1; - reason = pj_str("?"); - } - } else { - err_code = status; - reason = pj_strerror(status, errbuf, sizeof(errbuf)); - } - - it = pj_hash_first(sess->perm_table, &it_buf); - while (it) { - struct perm_t *perm = (struct perm_t*) - pj_hash_this(sess->perm_table, it); - it = pj_hash_next(sess->perm_table, it); - - if (perm->req_token == token) { - PJ_LOG(1,(sess->obj_name, - "CreatePermission failed for IP %s: %d/%.*s", - pj_sockaddr_print(&perm->addr, ipstr, - sizeof(ipstr), 2), - err_code, (int)reason.slen, reason.ptr)); - - invalidate_perm(sess, perm); - } - } - - if (err_code == PJ_STUN_SC_ALLOCATION_MISMATCH) { - /* Allocation mismatch means allocation no longer exists */ - on_session_fail(sess, PJ_STUN_CREATE_PERM_METHOD, - status, &reason); - return; - } - } + /* Handle CreatePermission response */ + if (status==PJ_SUCCESS && + PJ_STUN_IS_SUCCESS_RESPONSE(response->hdr.type)) + { + /* No special handling when the request is successful. */ + } else { + /* Iterate the permission table and invalidate all permissions + * that are related to this request. + */ + pj_hash_iterator_t it_buf, *it; + char ipstr[PJ_INET6_ADDRSTRLEN+10]; + int err_code; + char errbuf[PJ_ERR_MSG_SIZE]; + pj_str_t reason; + + pj_assert(status != PJ_SUCCESS); + + if (response) { + const pj_stun_errcode_attr *eattr; + + eattr = (const pj_stun_errcode_attr*) + pj_stun_msg_find_attr(response, + PJ_STUN_ATTR_ERROR_CODE, 0); + if (eattr) { + err_code = eattr->err_code; + reason = eattr->reason; + } else { + err_code = -1; + reason = pj_str("?"); + } + } else { + err_code = status; + reason = pj_strerror(status, errbuf, sizeof(errbuf)); + } + + it = pj_hash_first(sess->perm_table, &it_buf); + while (it) { + struct perm_t *perm = (struct perm_t*) + pj_hash_this(sess->perm_table, it); + it = pj_hash_next(sess->perm_table, it); + + if (perm->req_token == token) { + PJ_LOG(1,(sess->obj_name, + "CreatePermission failed for IP %s: %d/%.*s", + pj_sockaddr_print(&perm->addr, ipstr, + sizeof(ipstr), 2), + err_code, (int)reason.slen, reason.ptr)); + + invalidate_perm(sess, perm); + } + } + + if (err_code == PJ_STUN_SC_ALLOCATION_MISMATCH) { + /* Allocation mismatch means allocation no longer exists */ + on_session_fail(sess, PJ_STUN_CREATE_PERM_METHOD, + status, &reason); + return; + } + } } else if (method == PJ_STUN_CONNECTION_BIND_METHOD) { - /* Handle ConnectionBind response */ - struct conn_bind_t *conn_bind = (struct conn_bind_t*)token; - - if (status != PJ_SUCCESS || - !PJ_STUN_IS_SUCCESS_RESPONSE(response->hdr.type)) - { - pj_str_t reason = {0}; - if (status == PJ_SUCCESS) { - const pj_stun_errcode_attr *err_attr; - err_attr = (const pj_stun_errcode_attr*) - pj_stun_msg_find_attr(response, - PJ_STUN_ATTR_ERROR_CODE, 0); - if (err_attr) { - status = PJ_STATUS_FROM_STUN_CODE(err_attr->err_code); - reason = err_attr->reason; - } else { - status = PJNATH_EINSTUNMSG; - } - } - pj_perror(1, sess->obj_name, status, "ConnectionBind failed: %.*s", - (int)reason.slen, reason.ptr); - } - - /* Notify app */ - if (sess->cb.on_connection_bind_status) { - (*sess->cb.on_connection_bind_status) - (sess, status, conn_bind->id, - &conn_bind->peer_addr, conn_bind->peer_addr_len); - } + /* Handle ConnectionBind response */ + struct conn_bind_t *conn_bind = (struct conn_bind_t*)token; + + if (status != PJ_SUCCESS || + !PJ_STUN_IS_SUCCESS_RESPONSE(response->hdr.type)) + { + pj_str_t reason = {0}; + if (status == PJ_SUCCESS) { + const pj_stun_errcode_attr *err_attr; + err_attr = (const pj_stun_errcode_attr*) + pj_stun_msg_find_attr(response, + PJ_STUN_ATTR_ERROR_CODE, 0); + if (err_attr) { + status = PJ_STATUS_FROM_STUN_CODE(err_attr->err_code); + reason = err_attr->reason; + } else { + status = PJNATH_EINSTUNMSG; + } + } + pj_perror(1, sess->obj_name, status, "ConnectionBind failed: %.*s", + (int)reason.slen, reason.ptr); + } + + /* Notify app */ + if (sess->cb.on_connection_bind_status) { + (*sess->cb.on_connection_bind_status) + (sess, status, conn_bind->id, + &conn_bind->peer_addr, conn_bind->peer_addr_len); + } } else if (method == PJ_STUN_CONNECT_METHOD) { - /* Handle Connct response */ - struct pj_sockaddr_t *peer_addr = (struct pj_sockaddr_t*)token; - pj_uint32_t conn_id = 0; - - if (status != PJ_SUCCESS || - !PJ_STUN_IS_SUCCESS_RESPONSE(response->hdr.type)) - { - pj_str_t reason = {0}; - if (status == PJ_SUCCESS) { - const pj_stun_errcode_attr *err_attr; - err_attr = (const pj_stun_errcode_attr*) - pj_stun_msg_find_attr(response, - PJ_STUN_ATTR_ERROR_CODE, 0); - if (err_attr) { - status = PJ_STATUS_FROM_STUN_CODE(err_attr->err_code); - reason = err_attr->reason; - } else { - status = PJNATH_EINSTUNMSG; - } - } - pj_perror(1, sess->obj_name, status, "Connect failed: %.*s", - (int)reason.slen, reason.ptr); - } else { - const pj_stun_uint_attr *conn_id_attr; - conn_id_attr = (const pj_stun_uint_attr*) - pj_stun_msg_find_attr(response, PJ_STUN_ATTR_CONNECTION_ID, 0); - if (conn_id_attr == NULL) { - status = PJNATH_EINSTUNMSG; - pj_perror(1, sess->obj_name, status, - "Error: Missing CONNECTION-ID attribute"); - } - else { - conn_id = conn_id_attr->value; - } - } - - /* Notify app */ - if (sess->cb.on_connect_complete) { - (*sess->cb.on_connect_complete) - (sess, status, conn_id, - peer_addr, pj_sockaddr_get_len(peer_addr)); - } + /* Handle Connct response */ + struct pj_sockaddr_t *peer_addr = (struct pj_sockaddr_t*)token; + pj_uint32_t conn_id = 0; + + if (status != PJ_SUCCESS || + !PJ_STUN_IS_SUCCESS_RESPONSE(response->hdr.type)) + { + pj_str_t reason = {0}; + if (status == PJ_SUCCESS) { + const pj_stun_errcode_attr *err_attr; + err_attr = (const pj_stun_errcode_attr*) + pj_stun_msg_find_attr(response, + PJ_STUN_ATTR_ERROR_CODE, 0); + if (err_attr) { + status = PJ_STATUS_FROM_STUN_CODE(err_attr->err_code); + reason = err_attr->reason; + } else { + status = PJNATH_EINSTUNMSG; + } + } + pj_perror(1, sess->obj_name, status, "Connect failed: %.*s", + (int)reason.slen, reason.ptr); + } else { + const pj_stun_uint_attr *conn_id_attr; + conn_id_attr = (const pj_stun_uint_attr*) + pj_stun_msg_find_attr(response, PJ_STUN_ATTR_CONNECTION_ID, 0); + if (conn_id_attr == NULL) { + status = PJNATH_EINSTUNMSG; + pj_perror(1, sess->obj_name, status, + "Error: Missing CONNECTION-ID attribute"); + } + else { + conn_id = conn_id_attr->value; + } + } + + /* Notify app */ + if (sess->cb.on_connect_complete) { + (*sess->cb.on_connect_complete) + (sess, status, conn_id, + peer_addr, pj_sockaddr_get_len(peer_addr)); + } } else { - PJ_LOG(4,(sess->obj_name, "Unexpected STUN %s response", - pj_stun_get_method_name(response->hdr.type))); + PJ_LOG(4,(sess->obj_name, "Unexpected STUN %s response", + pj_stun_get_method_name(response->hdr.type))); } } @@ -1853,12 +1852,12 @@ static void stun_on_request_complete(pj_stun_session *stun, * message. */ static pj_status_t stun_on_rx_indication(pj_stun_session *stun, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_msg *msg, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_msg *msg, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_turn_session *sess; pj_stun_xor_peer_addr_attr *peer_attr; @@ -1889,16 +1888,16 @@ static pj_status_t stun_on_rx_indication(pj_stun_session *stun, if (!peer_attr || !connection_id_attr) { PJ_LOG(4,(sess->obj_name, "Received ConnectionAttempt indication with missing " - "attributes")); + "attributes")); return PJ_EINVALIDOP; } /* Notify application */ if (sess->cb.on_connection_attempt) { (*sess->cb.on_connection_attempt) - (sess, - connection_id_attr->value, - &peer_attr->sockaddr, + (sess, + connection_id_attr->value, + &peer_attr->sockaddr, pj_sockaddr_get_len(&peer_attr->sockaddr)); } return PJ_SUCCESS; @@ -1906,39 +1905,39 @@ static pj_status_t stun_on_rx_indication(pj_stun_session *stun, /* Next, expecting Data Indication only */ if (msg->hdr.type != PJ_STUN_DATA_INDICATION) { - PJ_LOG(4,(sess->obj_name, "Unexpected STUN %s indication", - pj_stun_get_method_name(msg->hdr.type))); - return PJ_EINVALIDOP; + PJ_LOG(4,(sess->obj_name, "Unexpected STUN %s indication", + pj_stun_get_method_name(msg->hdr.type))); + return PJ_EINVALIDOP; } /* Check if there is ICMP attribute in the message */ icmp = (pj_stun_icmp_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_ICMP, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_ICMP, 0); if (icmp != NULL) { - /* This is a forwarded ICMP packet. Ignore it for now */ - return PJ_SUCCESS; + /* This is a forwarded ICMP packet. Ignore it for now */ + return PJ_SUCCESS; } /* Get XOR-PEER-ADDRESS attribute */ peer_attr = (pj_stun_xor_peer_addr_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_XOR_PEER_ADDR, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_XOR_PEER_ADDR, 0); /* Get DATA attribute */ data_attr = (pj_stun_data_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_DATA, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_DATA, 0); /* Must have both XOR-PEER-ADDRESS and DATA attributes */ if (!peer_attr || !data_attr) { - PJ_LOG(4,(sess->obj_name, - "Received Data indication with missing attributes")); - return PJ_EINVALIDOP; + PJ_LOG(4,(sess->obj_name, + "Received Data indication with missing attributes")); + return PJ_EINVALIDOP; } /* Notify application */ if (sess->cb.on_rx_data) { - (*sess->cb.on_rx_data)(sess, data_attr->data, data_attr->length, - &peer_attr->sockaddr, - pj_sockaddr_get_len(&peer_attr->sockaddr)); + (*sess->cb.on_rx_data)(sess, data_attr->data, data_attr->length, + &peer_attr->sockaddr, + pj_sockaddr_get_len(&peer_attr->sockaddr)); } return PJ_SUCCESS; @@ -1949,54 +1948,54 @@ static pj_status_t stun_on_rx_indication(pj_stun_session *stun, * Notification on completion of DNS SRV resolution. */ static void dns_srv_resolver_cb(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec) + pj_status_t status, + const pj_dns_srv_record *rec) { pj_turn_session *sess = (pj_turn_session*) user_data; unsigned i, cnt, tot_cnt; /* Check failure */ if (status != PJ_SUCCESS || sess->pending_destroy) { - set_state(sess, PJ_TURN_STATE_DESTROYING); - sess_shutdown(sess, status); - pj_grp_lock_dec_ref(sess->grp_lock); - return; + set_state(sess, PJ_TURN_STATE_DESTROYING); + sess_shutdown(sess, status); + pj_grp_lock_dec_ref(sess->grp_lock); + return; } /* Calculate total number of server entries in the response */ tot_cnt = 0; for (i=0; icount; ++i) { - tot_cnt += rec->entry[i].server.addr_count; + tot_cnt += rec->entry[i].server.addr_count; } if (tot_cnt > PJ_TURN_MAX_DNS_SRV_CNT) - tot_cnt = PJ_TURN_MAX_DNS_SRV_CNT; + tot_cnt = PJ_TURN_MAX_DNS_SRV_CNT; /* Allocate server entries */ sess->srv_addr_list = (pj_sockaddr*) - pj_pool_calloc(sess->pool, tot_cnt, - sizeof(pj_sockaddr)); + pj_pool_calloc(sess->pool, tot_cnt, + sizeof(pj_sockaddr)); /* Copy results to server entries */ for (i=0, cnt=0; icount && cntentry[i].server.addr_count && - cntentry[i].server.addr[j].af == sess->af) { - pj_sockaddr *addr = &sess->srv_addr_list[cnt]; - - addr->addr.sa_family = sess->af; - pj_sockaddr_set_port(addr, rec->entry[i].port); - if (sess->af == pj_AF_INET6()) - addr->ipv6.sin6_addr = rec->entry[i].server.addr[j].ip.v6; - else - addr->ipv4.sin_addr = rec->entry[i].server.addr[j].ip.v4; - - ++cnt; - } - } + unsigned j; + + for (j=0; jentry[i].server.addr_count && + cntentry[i].server.addr[j].af == sess->af) { + pj_sockaddr *addr = &sess->srv_addr_list[cnt]; + + addr->addr.sa_family = sess->af; + pj_sockaddr_set_port(addr, rec->entry[i].port); + if (sess->af == pj_AF_INET6()) + addr->ipv6.sin6_addr = rec->entry[i].server.addr[j].ip.v6; + else + addr->ipv4.sin_addr = rec->entry[i].server.addr[j].ip.v4; + + ++cnt; + } + } } sess->srv_addr_cnt = (pj_uint16_t)cnt; @@ -2008,10 +2007,10 @@ static void dns_srv_resolver_cb(void *user_data, /* Run pending allocation */ if (sess->pending_alloc) { - pj_status_t status2; - status2 = pj_turn_session_alloc(sess, NULL); - if (status2 != PJ_SUCCESS) - on_session_fail(sess, PJ_STUN_ALLOCATE_METHOD, status2, NULL); + pj_status_t status2; + status2 = pj_turn_session_alloc(sess, NULL); + if (status2 != PJ_SUCCESS) + on_session_fail(sess, PJ_STUN_ALLOCATE_METHOD, status2, NULL); } pj_grp_lock_dec_ref(sess->grp_lock); @@ -2022,41 +2021,41 @@ static void dns_srv_resolver_cb(void *user_data, * Lookup peer descriptor from its address. */ static struct ch_t *lookup_ch_by_addr(pj_turn_session *sess, - const pj_sockaddr_t *addr, - unsigned addr_len, - pj_bool_t update, - pj_bool_t bind_channel) + const pj_sockaddr_t *addr, + unsigned addr_len, + pj_bool_t update, + pj_bool_t bind_channel) { pj_uint32_t hval = 0; struct ch_t *ch; ch = (struct ch_t*) - pj_hash_get(sess->ch_table, addr, addr_len, &hval); + pj_hash_get(sess->ch_table, addr, addr_len, &hval); if (ch == NULL && update) { - ch = PJ_POOL_ZALLOC_T(sess->pool, struct ch_t); - ch->num = PJ_TURN_INVALID_CHANNEL; - pj_memcpy(&ch->addr, addr, addr_len); + ch = PJ_POOL_ZALLOC_T(sess->pool, struct ch_t); + ch->num = PJ_TURN_INVALID_CHANNEL; + pj_memcpy(&ch->addr, addr, addr_len); - /* Register by peer address */ - pj_hash_set(sess->pool, sess->ch_table, &ch->addr, addr_len, - hval, ch); + /* Register by peer address */ + pj_hash_set(sess->pool, sess->ch_table, &ch->addr, addr_len, + hval, ch); } if (ch && update) { - pj_gettimeofday(&ch->expiry); - ch->expiry.sec += PJ_TURN_PERM_TIMEOUT - sess->ka_interval - 1; - - if (bind_channel) { - pj_uint32_t hval2 = 0; - /* Register by channel number */ - pj_assert(ch->num != PJ_TURN_INVALID_CHANNEL && ch->bound); - - if (pj_hash_get(sess->ch_table, &ch->num, - sizeof(ch->num), &hval2)==0) { - pj_hash_set(sess->pool, sess->ch_table, &ch->num, - sizeof(ch->num), hval2, ch); - } - } + pj_gettimeofday(&ch->expiry); + ch->expiry.sec += PJ_TURN_PERM_TIMEOUT - sess->ka_interval - 1; + + if (bind_channel) { + pj_uint32_t hval2 = 0; + /* Register by channel number */ + pj_assert(ch->num != PJ_TURN_INVALID_CHANNEL && ch->bound); + + if (pj_hash_get(sess->ch_table, &ch->num, + sizeof(ch->num), &hval2)==0) { + pj_hash_set(sess->pool, sess->ch_table, &ch->num, + sizeof(ch->num), hval2, ch); + } + } } /* Also create/update permission for this destination. Ideally we @@ -2065,7 +2064,7 @@ static struct ch_t *lookup_ch_by_addr(pj_turn_session *sess, * during refreshing. */ if (ch && update) { - lookup_perm(sess, &ch->addr, pj_sockaddr_get_len(&ch->addr), PJ_TRUE); + lookup_perm(sess, &ch->addr, pj_sockaddr_get_len(&ch->addr), PJ_TRUE); } return ch; @@ -2076,10 +2075,10 @@ static struct ch_t *lookup_ch_by_addr(pj_turn_session *sess, * Lookup channel descriptor from its channel number. */ static struct ch_t *lookup_ch_by_chnum(pj_turn_session *sess, - pj_uint16_t chnum) + pj_uint16_t chnum) { return (struct ch_t*) pj_hash_get(sess->ch_table, &chnum, - sizeof(chnum), NULL); + sizeof(chnum), NULL); } @@ -2087,9 +2086,9 @@ static struct ch_t *lookup_ch_by_chnum(pj_turn_session *sess, * Lookup permission and optionally create if it doesn't exist. */ static struct perm_t *lookup_perm(pj_turn_session *sess, - const pj_sockaddr_t *addr, - unsigned addr_len, - pj_bool_t update) + const pj_sockaddr_t *addr, + unsigned addr_len, + pj_bool_t update) { pj_uint32_t hval = 0; pj_sockaddr perm_addr; @@ -2097,26 +2096,26 @@ static struct perm_t *lookup_perm(pj_turn_session *sess, /* make sure port number if zero */ if (pj_sockaddr_get_port(addr) != 0) { - pj_memcpy(&perm_addr, addr, addr_len); - pj_sockaddr_set_port(&perm_addr, 0); - addr = &perm_addr; + pj_memcpy(&perm_addr, addr, addr_len); + pj_sockaddr_set_port(&perm_addr, 0); + addr = &perm_addr; } /* lookup and create if it doesn't exist and wanted */ perm = (struct perm_t*) - pj_hash_get(sess->perm_table, addr, addr_len, &hval); + pj_hash_get(sess->perm_table, addr, addr_len, &hval); if (perm == NULL && update) { - perm = PJ_POOL_ZALLOC_T(sess->pool, struct perm_t); - pj_memcpy(&perm->addr, addr, addr_len); - perm->hval = hval; + perm = PJ_POOL_ZALLOC_T(sess->pool, struct perm_t); + pj_memcpy(&perm->addr, addr, addr_len); + perm->hval = hval; - pj_hash_set(sess->pool, sess->perm_table, &perm->addr, addr_len, - perm->hval, perm); + pj_hash_set(sess->pool, sess->perm_table, &perm->addr, addr_len, + perm->hval, perm); } if (perm && update) { - pj_gettimeofday(&perm->expiry); - perm->expiry.sec += PJ_TURN_PERM_TIMEOUT - sess->ka_interval - 1; + pj_gettimeofday(&perm->expiry); + perm->expiry.sec += PJ_TURN_PERM_TIMEOUT - sess->ka_interval - 1; } @@ -2127,17 +2126,17 @@ static struct perm_t *lookup_perm(pj_turn_session *sess, * Delete permission */ static void invalidate_perm(pj_turn_session *sess, - struct perm_t *perm) + struct perm_t *perm) { pj_hash_set(NULL, sess->perm_table, &perm->addr, - pj_sockaddr_get_len(&perm->addr), perm->hval, NULL); + pj_sockaddr_get_len(&perm->addr), perm->hval, NULL); } /* * Scan permission's hash table to refresh the permission. */ static unsigned refresh_permissions(pj_turn_session *sess, - const pj_time_val *now) + const pj_time_val *now) { pj_stun_tx_data *tdata = NULL; unsigned count = 0; @@ -2147,69 +2146,69 @@ static unsigned refresh_permissions(pj_turn_session *sess, it = pj_hash_first(sess->perm_table, &itbuf); while (it) { - struct perm_t *perm = (struct perm_t*) - pj_hash_this(sess->perm_table, it); - - it = pj_hash_next(sess->perm_table, it); - - if (perm->expiry.sec-1 <= now->sec) { - if (perm->renew) { - /* Renew this permission */ - if (tdata == NULL) { - /* Create a bare CreatePermission request */ - status = pj_stun_session_create_req( - sess->stun, - PJ_STUN_CREATE_PERM_REQUEST, - PJ_STUN_MAGIC, NULL, &tdata); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(sess->obj_name, status, - "Error creating CreatePermission request")); - return 0; - } - - /* Create request token to map the request to the perm - * structures which the request belongs. - */ - req_token = (void*)(pj_ssize_t)pj_rand(); - } - - status = pj_stun_msg_add_sockaddr_attr( - tdata->pool, - tdata->msg, - PJ_STUN_ATTR_XOR_PEER_ADDR, - PJ_TRUE, - &perm->addr, - sizeof(perm->addr)); - if (status != PJ_SUCCESS) { - pj_stun_msg_destroy_tdata(sess->stun, tdata); - return 0; - } - - perm->expiry = *now; - perm->expiry.sec += PJ_TURN_PERM_TIMEOUT-sess->ka_interval-1; - perm->req_token = req_token; - ++count; - - } else { - /* This permission has expired and app doesn't want - * us to renew, so delete it from the hash table. - */ - invalidate_perm(sess, perm); - } - } + struct perm_t *perm = (struct perm_t*) + pj_hash_this(sess->perm_table, it); + + it = pj_hash_next(sess->perm_table, it); + + if (perm->expiry.sec-1 <= now->sec) { + if (perm->renew) { + /* Renew this permission */ + if (tdata == NULL) { + /* Create a bare CreatePermission request */ + status = pj_stun_session_create_req( + sess->stun, + PJ_STUN_CREATE_PERM_REQUEST, + PJ_STUN_MAGIC, NULL, &tdata); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(sess->obj_name, status, + "Error creating CreatePermission request")); + return 0; + } + + /* Create request token to map the request to the perm + * structures which the request belongs. + */ + req_token = (void*)(pj_ssize_t)pj_rand(); + } + + status = pj_stun_msg_add_sockaddr_attr( + tdata->pool, + tdata->msg, + PJ_STUN_ATTR_XOR_PEER_ADDR, + PJ_TRUE, + &perm->addr, + sizeof(perm->addr)); + if (status != PJ_SUCCESS) { + pj_stun_msg_destroy_tdata(sess->stun, tdata); + return 0; + } + + perm->expiry = *now; + perm->expiry.sec += PJ_TURN_PERM_TIMEOUT-sess->ka_interval-1; + perm->req_token = req_token; + ++count; + + } else { + /* This permission has expired and app doesn't want + * us to renew, so delete it from the hash table. + */ + invalidate_perm(sess, perm); + } + } } if (tdata) { - status = pj_stun_session_send_msg(sess->stun, req_token, PJ_FALSE, - (sess->conn_type==PJ_TURN_TP_UDP), - sess->srv_addr, - pj_sockaddr_get_len(sess->srv_addr), - tdata); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(sess->obj_name, status, - "Error sending CreatePermission request")); - count = 0; - } + status = pj_stun_session_send_msg(sess->stun, req_token, PJ_FALSE, + (sess->conn_type==PJ_TURN_TP_UDP), + sess->srv_addr, + pj_sockaddr_get_len(sess->srv_addr), + tdata); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(sess->obj_name, status, + "Error sending CreatePermission request")); + count = 0; + } } @@ -2232,92 +2231,92 @@ static void on_timer_event(pj_timer_heap_t *th, pj_timer_entry *e) e->id = TIMER_NONE; if (eid == TIMER_KEEP_ALIVE) { - pj_time_val now; - pj_hash_iterator_t itbuf, *it; - pj_bool_t resched = PJ_TRUE; - pj_bool_t pkt_sent = PJ_FALSE; - - if (sess->state >= PJ_TURN_STATE_DEALLOCATING) { - /* Ignore if we're deallocating */ - goto on_return; - } - - pj_gettimeofday(&now); - - /* Refresh allocation if it's time to do so */ - if (PJ_TIME_VAL_LTE(sess->expiry, now)) { - int lifetime = sess->alloc_param.lifetime; - - if (lifetime == 0) - lifetime = -1; - - send_refresh(sess, lifetime); - resched = PJ_FALSE; - pkt_sent = PJ_TRUE; - } - - /* Scan hash table to refresh bound channels */ - it = pj_hash_first(sess->ch_table, &itbuf); - while (it) { - struct ch_t *ch = (struct ch_t*) - pj_hash_this(sess->ch_table, it); - if (ch->bound && PJ_TIME_VAL_LTE(ch->expiry, now)) { - - /* Send ChannelBind to refresh channel binding and - * permission. - */ - pj_turn_session_bind_channel(sess, &ch->addr, - pj_sockaddr_get_len(&ch->addr)); - pkt_sent = PJ_TRUE; - } - - it = pj_hash_next(sess->ch_table, it); - } - - /* Scan permission table to refresh permissions */ - if (refresh_permissions(sess, &now)) - pkt_sent = PJ_TRUE; - - /* If no packet is sent, send a blank Send indication to - * refresh local NAT. - */ - if (!pkt_sent && sess->alloc_param.ka_interval > 0) { - pj_stun_tx_data *tdata; - pj_status_t rc; - - /* Create blank SEND-INDICATION */ - rc = pj_stun_session_create_ind(sess->stun, - PJ_STUN_SEND_INDICATION, &tdata); - if (rc == PJ_SUCCESS) { - /* Add DATA attribute with zero length */ - pj_stun_msg_add_binary_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_DATA, NULL, 0); - - /* Send the indication */ - pj_stun_session_send_msg(sess->stun, NULL, PJ_FALSE, - PJ_FALSE, sess->srv_addr, - pj_sockaddr_get_len(sess->srv_addr), - tdata); - } - } - - /* Reshcedule timer */ - if (resched) { - pj_time_val delay; - - delay.sec = sess->ka_interval; - delay.msec = 0; - - pj_timer_heap_schedule_w_grp_lock(sess->timer_heap, &sess->timer, - &delay, TIMER_KEEP_ALIVE, - sess->grp_lock); - } + pj_time_val now; + pj_hash_iterator_t itbuf, *it; + pj_bool_t resched = PJ_TRUE; + pj_bool_t pkt_sent = PJ_FALSE; + + if (sess->state >= PJ_TURN_STATE_DEALLOCATING) { + /* Ignore if we're deallocating */ + goto on_return; + } + + pj_gettimeofday(&now); + + /* Refresh allocation if it's time to do so */ + if (PJ_TIME_VAL_LTE(sess->expiry, now)) { + int lifetime = sess->alloc_param.lifetime; + + if (lifetime == 0) + lifetime = -1; + + send_refresh(sess, lifetime); + resched = PJ_FALSE; + pkt_sent = PJ_TRUE; + } + + /* Scan hash table to refresh bound channels */ + it = pj_hash_first(sess->ch_table, &itbuf); + while (it) { + struct ch_t *ch = (struct ch_t*) + pj_hash_this(sess->ch_table, it); + if (ch->bound && PJ_TIME_VAL_LTE(ch->expiry, now)) { + + /* Send ChannelBind to refresh channel binding and + * permission. + */ + pj_turn_session_bind_channel(sess, &ch->addr, + pj_sockaddr_get_len(&ch->addr)); + pkt_sent = PJ_TRUE; + } + + it = pj_hash_next(sess->ch_table, it); + } + + /* Scan permission table to refresh permissions */ + if (refresh_permissions(sess, &now)) + pkt_sent = PJ_TRUE; + + /* If no packet is sent, send a blank Send indication to + * refresh local NAT. + */ + if (!pkt_sent && sess->alloc_param.ka_interval > 0) { + pj_stun_tx_data *tdata; + pj_status_t rc; + + /* Create blank SEND-INDICATION */ + rc = pj_stun_session_create_ind(sess->stun, + PJ_STUN_SEND_INDICATION, &tdata); + if (rc == PJ_SUCCESS) { + /* Add DATA attribute with zero length */ + pj_stun_msg_add_binary_attr(tdata->pool, tdata->msg, + PJ_STUN_ATTR_DATA, NULL, 0); + + /* Send the indication */ + pj_stun_session_send_msg(sess->stun, NULL, PJ_FALSE, + PJ_FALSE, sess->srv_addr, + pj_sockaddr_get_len(sess->srv_addr), + tdata); + } + } + + /* Reshcedule timer */ + if (resched) { + pj_time_val delay; + + delay.sec = sess->ka_interval; + delay.msec = 0; + + pj_timer_heap_schedule_w_grp_lock(sess->timer_heap, &sess->timer, + &delay, TIMER_KEEP_ALIVE, + sess->grp_lock); + } } else if (eid == TIMER_DESTROY) { - /* Time to destroy */ - do_destroy(sess); + /* Time to destroy */ + do_destroy(sess); } else { - pj_assert(!"Unknown timer event"); + pj_assert(!"Unknown timer event"); } on_return: diff --git a/pjnath/src/pjnath/turn_sock.c b/pjnath/src/pjnath/turn_sock.c index 891483e62f..b96ddac9ff 100644 --- a/pjnath/src/pjnath/turn_sock.c +++ b/pjnath/src/pjnath/turn_sock.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,7 +37,7 @@ enum enum { MAX_BIND_RETRY = 100 }; -#define INIT 0x1FFFFFFF +#define INIT 0x1FFFFFFF enum { DATACONN_STATE_NULL, @@ -52,54 +51,54 @@ enum { */ typedef struct tcp_data_conn_t { - pj_pool_t *pool; + pj_pool_t *pool; - pj_uint32_t id; /* Connection ID. */ - int state; /* Connection state. */ - pj_sockaddr peer_addr; /* Peer address (mapped). */ - unsigned peer_addr_len; + pj_uint32_t id; /* Connection ID. */ + int state; /* Connection state. */ + pj_sockaddr peer_addr; /* Peer address (mapped). */ + unsigned peer_addr_len; - pj_activesock_t *asock; /* Active socket. */ + pj_activesock_t *asock; /* Active socket. */ pj_ioqueue_op_key_t send_key; - pj_turn_sock *turn_sock; /* TURN socket parent. */ + pj_turn_sock *turn_sock; /* TURN socket parent. */ } tcp_data_conn_t; struct pj_turn_sock { - pj_pool_t *pool; - const char *obj_name; - pj_turn_session *sess; - pj_turn_sock_cb cb; - void *user_data; + pj_pool_t *pool; + const char *obj_name; + pj_turn_session *sess; + pj_turn_sock_cb cb; + void *user_data; - pj_bool_t is_destroying; - pj_grp_lock_t *grp_lock; + pj_bool_t is_destroying; + pj_grp_lock_t *grp_lock; - pj_turn_alloc_param alloc_param; - pj_stun_config cfg; - pj_turn_sock_cfg setting; + pj_turn_alloc_param alloc_param; + pj_stun_config cfg; + pj_turn_sock_cfg setting; - pj_timer_entry timer; + pj_timer_entry timer; - int af; - pj_turn_tp_type conn_type; - pj_activesock_t *active_sock; + int af; + pj_turn_tp_type conn_type; + pj_activesock_t *active_sock; #if PJ_HAS_SSL_SOCK pj_ssl_sock_t *ssl_sock; pj_ssl_cert_t *cert; pj_str_t server_name; #endif - pj_ioqueue_op_key_t send_key; - pj_ioqueue_op_key_t int_send_key; - unsigned pkt_len; - unsigned body_len; + pj_ioqueue_op_key_t send_key; + pj_ioqueue_op_key_t int_send_key; + unsigned pkt_len; + unsigned body_len; /* Data connection, when peer_conn_type==PJ_TURN_TP_TCP (RFC 6062) */ - unsigned data_conn_cnt; - tcp_data_conn_t data_conn[PJ_TURN_MAX_TCP_CONN_CNT]; + unsigned data_conn_cnt; + tcp_data_conn_t data_conn[PJ_TURN_MAX_TCP_CONN_CNT]; }; @@ -107,90 +106,90 @@ struct pj_turn_sock * Callback prototypes. */ static pj_status_t turn_on_send_pkt(pj_turn_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_sockaddr_t *dst_addr, - unsigned dst_addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_sockaddr_t *dst_addr, + unsigned dst_addr_len); static pj_status_t turn_on_stun_send_pkt(pj_turn_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_sockaddr_t *dst_addr, - unsigned dst_addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_sockaddr_t *dst_addr, + unsigned dst_addr_len); static void turn_on_channel_bound(pj_turn_session *sess, - const pj_sockaddr_t *peer_addr, - unsigned addr_len, - unsigned ch_num); + const pj_sockaddr_t *peer_addr, + unsigned addr_len, + unsigned ch_num); static void turn_on_rx_data(pj_turn_session *sess, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); static void turn_on_state(pj_turn_session *sess, - pj_turn_state_t old_state, - pj_turn_state_t new_state); + pj_turn_state_t old_state, + pj_turn_state_t new_state); static void turn_on_connection_attempt(pj_turn_session *sess, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); static void turn_on_connection_bind_status(pj_turn_session *sess, - pj_status_t status, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + pj_status_t status, + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); static void turn_on_connect_complete(pj_turn_session *sess, - pj_status_t status, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + pj_status_t status, + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); static pj_bool_t on_data_read(pj_turn_sock *turn_sock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder); + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder); static pj_bool_t on_data_sent(pj_turn_sock *turn_sock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent); + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent); static pj_bool_t on_connect_complete(pj_turn_sock *turn_sock, - pj_status_t status); + pj_status_t status); /* * Activesock callback */ static pj_bool_t on_connect_complete_asock(pj_activesock_t *asock, - pj_status_t status); + pj_status_t status); static pj_bool_t on_data_read_asock(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder); + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder); static pj_bool_t on_data_sent_asock(pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent); + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent); /* * SSL sock callback */ #if PJ_HAS_SSL_SOCK static pj_bool_t on_connect_complete_ssl_sock(pj_ssl_sock_t *ssl_sock, - pj_status_t status); + pj_status_t status); static pj_bool_t on_data_read_ssl_sock(pj_ssl_sock_t *ssl_sock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder); + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder); #endif static pj_bool_t dataconn_on_data_read(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder); + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder); static pj_bool_t dataconn_on_data_sent(pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent); + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent); static pj_bool_t dataconn_on_connect_complete(pj_activesock_t *asock, - pj_status_t status); + pj_status_t status); static void dataconn_cleanup(tcp_data_conn_t *conn); static void turn_sock_on_destroy(void *comp); @@ -221,8 +220,8 @@ PJ_DEF(void) pj_turn_sock_tls_cfg_default(pj_turn_sock_tls_cfg *tls_cfg) } PJ_DEF(void) pj_turn_sock_tls_cfg_dup(pj_pool_t *pool, - pj_turn_sock_tls_cfg *dst, - const pj_turn_sock_tls_cfg *src) + pj_turn_sock_tls_cfg *dst, + const pj_turn_sock_tls_cfg *src) { pj_memcpy(dst, src, sizeof(*dst)); pj_strdup_with_null(pool, &dst->ca_list_file, &src->ca_list_file); @@ -261,12 +260,12 @@ PJ_DEF(void) pj_turn_sock_tls_cfg_wipe_keys(pj_turn_sock_tls_cfg *tls_cfg) * Create. */ PJ_DEF(pj_status_t) pj_turn_sock_create(pj_stun_config *cfg, - int af, - pj_turn_tp_type conn_type, - const pj_turn_sock_cb *cb, - const pj_turn_sock_cfg *setting, - void *user_data, - pj_turn_sock **p_turn_sock) + int af, + pj_turn_tp_type conn_type, + const pj_turn_sock_cb *cb, + const pj_turn_sock_cfg *setting, + void *user_data, + pj_turn_sock **p_turn_sock) { pj_turn_sock *turn_sock; pj_turn_session_cb sess_cb; @@ -281,31 +280,31 @@ PJ_DEF(pj_status_t) pj_turn_sock_create(pj_stun_config *cfg, PJ_ASSERT_RETURN(conn_type!=PJ_TURN_TP_TLS || PJ_HAS_SSL_SOCK, PJ_EINVAL); if (!setting) { - pj_turn_sock_cfg_default(&default_setting); - setting = &default_setting; + pj_turn_sock_cfg_default(&default_setting); + setting = &default_setting; } switch (conn_type) { case PJ_TURN_TP_UDP: - name_tmpl = "udprel%p"; - break; + name_tmpl = "udprel%p"; + break; case PJ_TURN_TP_TCP: - name_tmpl = "tcprel%p"; - break; + name_tmpl = "tcprel%p"; + break; #if PJ_HAS_SSL_SOCK case PJ_TURN_TP_TLS: - name_tmpl = "tlsrel%p"; - break; + name_tmpl = "tlsrel%p"; + break; #endif default: - PJ_ASSERT_RETURN(!"Invalid TURN conn_type", PJ_EINVAL); - name_tmpl = "tcprel%p"; - break; + PJ_ASSERT_RETURN(!"Invalid TURN conn_type", PJ_EINVAL); + name_tmpl = "tcprel%p"; + break; } /* Create and init basic data structure */ pool = pj_pool_create(cfg->pf, name_tmpl, PJNATH_POOL_LEN_TURN_SOCK, - PJNATH_POOL_INC_TURN_SOCK, NULL); + PJNATH_POOL_INC_TURN_SOCK, NULL); turn_sock = PJ_POOL_ZALLOC_T(pool, pj_turn_sock); turn_sock->pool = pool; turn_sock->obj_name = pool->obj_name; @@ -320,23 +319,23 @@ PJ_DEF(pj_status_t) pj_turn_sock_create(pj_stun_config *cfg, pj_memcpy(&turn_sock->setting, setting, sizeof(*setting)); #if PJ_HAS_SSL_SOCK pj_turn_sock_tls_cfg_dup(turn_sock->pool, &turn_sock->setting.tls_cfg, - &setting->tls_cfg); + &setting->tls_cfg); #endif /* Set callback */ if (cb) { - pj_memcpy(&turn_sock->cb, cb, sizeof(*cb)); + pj_memcpy(&turn_sock->cb, cb, sizeof(*cb)); } /* Session lock */ if (setting && setting->grp_lock) { - turn_sock->grp_lock = setting->grp_lock; + turn_sock->grp_lock = setting->grp_lock; } else { - status = pj_grp_lock_create(pool, NULL, &turn_sock->grp_lock); - if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; - } + status = pj_grp_lock_create(pool, NULL, &turn_sock->grp_lock); + if (status != PJ_SUCCESS) { + pj_pool_release(pool); + return status; + } } pj_grp_lock_add_ref(turn_sock->grp_lock); @@ -360,8 +359,8 @@ PJ_DEF(pj_status_t) pj_turn_sock_create(pj_stun_config *cfg, turn_sock->grp_lock, &sess_cb, 0, turn_sock, &turn_sock->sess); if (status != PJ_SUCCESS) { - destroy(turn_sock); - return status; + destroy(turn_sock); + return status; } /* Note: socket and ioqueue will be created later once the TURN server @@ -380,8 +379,8 @@ static void turn_sock_on_destroy(void *comp) pj_turn_sock *turn_sock = (pj_turn_sock*) comp; if (turn_sock->pool) { - PJ_LOG(4,(turn_sock->obj_name, "TURN socket destroyed")); - pj_pool_safe_release(&turn_sock->pool); + PJ_LOG(4,(turn_sock->obj_name, "TURN socket destroyed")); + pj_pool_safe_release(&turn_sock->pool); } } @@ -390,26 +389,26 @@ static void destroy(pj_turn_sock *turn_sock) unsigned i; PJ_LOG(4,(turn_sock->obj_name, "TURN socket destroy request, ref_cnt=%d", - pj_grp_lock_get_ref(turn_sock->grp_lock))); + pj_grp_lock_get_ref(turn_sock->grp_lock))); pj_grp_lock_acquire(turn_sock->grp_lock); if (turn_sock->is_destroying) { - pj_grp_lock_release(turn_sock->grp_lock); - return; + pj_grp_lock_release(turn_sock->grp_lock); + return; } turn_sock->is_destroying = PJ_TRUE; if (turn_sock->sess) - pj_turn_session_shutdown(turn_sock->sess); + pj_turn_session_shutdown(turn_sock->sess); if (turn_sock->active_sock) - pj_activesock_close(turn_sock->active_sock); + pj_activesock_close(turn_sock->active_sock); #if PJ_HAS_SSL_SOCK if (turn_sock->ssl_sock) - pj_ssl_sock_close(turn_sock->ssl_sock); + pj_ssl_sock_close(turn_sock->ssl_sock); #endif for (i=0; i < PJ_TURN_MAX_TCP_CONN_CNT; ++i) { - dataconn_cleanup(&turn_sock->data_conn[i]); + dataconn_cleanup(&turn_sock->data_conn[i]); } turn_sock->data_conn_cnt = 0; @@ -421,18 +420,18 @@ PJ_DEF(void) pj_turn_sock_destroy(pj_turn_sock *turn_sock) { pj_grp_lock_acquire(turn_sock->grp_lock); if (turn_sock->is_destroying) { - pj_grp_lock_release(turn_sock->grp_lock); - return; + pj_grp_lock_release(turn_sock->grp_lock); + return; } if (turn_sock->sess) { - pj_turn_session_shutdown(turn_sock->sess); - /* This will ultimately call our state callback, and when - * session state is DESTROYING we will schedule a timer to - * destroy ourselves. - */ + pj_turn_session_shutdown(turn_sock->sess); + /* This will ultimately call our state callback, and when + * session state is DESTROYING we will schedule a timer to + * destroy ourselves. + */ } else { - destroy(turn_sock); + destroy(turn_sock); } pj_grp_lock_release(turn_sock->grp_lock); @@ -451,29 +450,29 @@ static void timer_cb(pj_timer_heap_t *th, pj_timer_entry *e) switch (eid) { case TIMER_DESTROY: - destroy(turn_sock); - break; + destroy(turn_sock); + break; default: - pj_assert(!"Invalid timer id"); - break; + pj_assert(!"Invalid timer id"); + break; } } /* Display error */ static void show_err(pj_turn_sock *turn_sock, const char *title, - pj_status_t status) + pj_status_t status) { PJ_PERROR(4,(turn_sock->obj_name, status, title)); } /* On error, terminate session */ static void sess_fail(pj_turn_sock *turn_sock, const char *title, - pj_status_t status) + pj_status_t status) { show_err(turn_sock, title, status); if (turn_sock->sess) { - pj_turn_session_destroy(turn_sock->sess, status); + pj_turn_session_destroy(turn_sock->sess, status); } } @@ -481,7 +480,7 @@ static void sess_fail(pj_turn_sock *turn_sock, const char *title, * Set user data. */ PJ_DEF(pj_status_t) pj_turn_sock_set_user_data( pj_turn_sock *turn_sock, - void *user_data) + void *user_data) { PJ_ASSERT_RETURN(turn_sock, PJ_EINVAL); turn_sock->user_data = user_data; @@ -510,16 +509,16 @@ PJ_DEF(pj_grp_lock_t *) pj_turn_sock_get_grp_lock(pj_turn_sock *turn_sock) * Get info. */ PJ_DEF(pj_status_t) pj_turn_sock_get_info(pj_turn_sock *turn_sock, - pj_turn_session_info *info) + pj_turn_session_info *info) { PJ_ASSERT_RETURN(turn_sock && info, PJ_EINVAL); if (turn_sock->sess) { - return pj_turn_session_get_info(turn_sock->sess, info); + return pj_turn_session_get_info(turn_sock->sess, info); } else { - pj_bzero(info, sizeof(*info)); - info->state = PJ_TURN_STATE_NULL; - return PJ_SUCCESS; + pj_bzero(info, sizeof(*info)); + info->state = PJ_TURN_STATE_NULL; + return PJ_SUCCESS; } } @@ -544,7 +543,7 @@ PJ_DEF(pj_status_t) pj_turn_sock_unlock(pj_turn_sock *turn_sock) * Set STUN message logging for this TURN session. */ PJ_DEF(void) pj_turn_sock_set_log( pj_turn_sock *turn_sock, - unsigned flags) + unsigned flags) { pj_turn_session_set_log(turn_sock->sess, flags); } @@ -553,7 +552,7 @@ PJ_DEF(void) pj_turn_sock_set_log( pj_turn_sock *turn_sock, * Set software name */ PJ_DEF(pj_status_t) pj_turn_sock_set_software_name( pj_turn_sock *turn_sock, - const pj_str_t *sw) + const pj_str_t *sw) { return pj_turn_session_set_software_name(turn_sock->sess, sw); } @@ -562,11 +561,11 @@ PJ_DEF(pj_status_t) pj_turn_sock_set_software_name( pj_turn_sock *turn_sock, * Initialize. */ PJ_DEF(pj_status_t) pj_turn_sock_alloc(pj_turn_sock *turn_sock, - const pj_str_t *domain, - int default_port, - pj_dns_resolver *resolver, - const pj_stun_auth_cred *cred, - const pj_turn_alloc_param *param) + const pj_str_t *domain, + int default_port, + pj_dns_resolver *resolver, + const pj_stun_auth_cred *cred, + const pj_turn_alloc_param *param) { pj_status_t status; @@ -579,41 +578,41 @@ PJ_DEF(pj_status_t) pj_turn_sock_alloc(pj_turn_sock *turn_sock, * server address has been resolved. */ if (param) { - pj_turn_alloc_param_copy(turn_sock->pool, &turn_sock->alloc_param, param); + pj_turn_alloc_param_copy(turn_sock->pool, &turn_sock->alloc_param, param); } else { - pj_turn_alloc_param_default(&turn_sock->alloc_param); + pj_turn_alloc_param_default(&turn_sock->alloc_param); } /* Set credental */ if (cred) { - status = pj_turn_session_set_credential(turn_sock->sess, cred); - if (status != PJ_SUCCESS) { - sess_fail(turn_sock, "Error setting credential", status); - pj_grp_lock_release(turn_sock->grp_lock); - return status; - } + status = pj_turn_session_set_credential(turn_sock->sess, cred); + if (status != PJ_SUCCESS) { + sess_fail(turn_sock, "Error setting credential", status); + pj_grp_lock_release(turn_sock->grp_lock); + return status; + } } #if PJ_HAS_SSL_SOCK if (turn_sock->conn_type == PJ_TURN_TP_TLS) { - pj_strdup_with_null(turn_sock->pool, &turn_sock->server_name, domain); + pj_strdup_with_null(turn_sock->pool, &turn_sock->server_name, domain); } #endif /* Resolve server */ status = pj_turn_session_set_server(turn_sock->sess, domain, default_port, - resolver); + resolver); if (status != PJ_SUCCESS) { - sess_fail(turn_sock, "Error setting TURN server", status); - pj_grp_lock_release(turn_sock->grp_lock); - return status; + sess_fail(turn_sock, "Error setting TURN server", status); + pj_grp_lock_release(turn_sock->grp_lock); + return status; } else if (!turn_sock->sess) { - /* TURN session may have been destroyed here, i.e: when DNS resolution - * completed synchronously and TURN allocation failed. - */ - PJ_LOG(4,(turn_sock->obj_name, "TURN session destroyed in setting " - "TURN server")); - pj_grp_lock_release(turn_sock->grp_lock); - return PJ_EGONE; + /* TURN session may have been destroyed here, i.e: when DNS resolution + * completed synchronously and TURN allocation failed. + */ + PJ_LOG(4,(turn_sock->obj_name, "TURN session destroyed in setting " + "TURN server")); + pj_grp_lock_release(turn_sock->grp_lock); + return PJ_EGONE; } /* Done for now. The next work will be done when session state moved @@ -627,12 +626,12 @@ PJ_DEF(pj_status_t) pj_turn_sock_alloc(pj_turn_sock *turn_sock, * Install permission */ PJ_DEF(pj_status_t) pj_turn_sock_set_perm( pj_turn_sock *turn_sock, - unsigned addr_cnt, - const pj_sockaddr addr[], - unsigned options) + unsigned addr_cnt, + const pj_sockaddr addr[], + unsigned options) { if (turn_sock->sess == NULL) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; return pj_turn_session_set_perm(turn_sock->sess, addr_cnt, addr, options); } @@ -641,30 +640,30 @@ PJ_DEF(pj_status_t) pj_turn_sock_set_perm( pj_turn_sock *turn_sock, * Send packet. */ PJ_DEF(pj_status_t) pj_turn_sock_sendto( pj_turn_sock *turn_sock, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_sockaddr_t *addr, - unsigned addr_len) + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_sockaddr_t *addr, + unsigned addr_len) { PJ_ASSERT_RETURN(turn_sock && addr && addr_len, PJ_EINVAL); if (turn_sock->sess == NULL) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; /* TURN session may add some headers to the packet, so we need * to store our actual data length to be sent here. */ turn_sock->body_len = pkt_len; return pj_turn_session_sendto(turn_sock->sess, pkt, pkt_len, - addr, addr_len); + addr, addr_len); } /* * Bind a peer address to a channel number. */ PJ_DEF(pj_status_t) pj_turn_sock_bind_channel( pj_turn_sock *turn_sock, - const pj_sockaddr_t *peer, - unsigned addr_len) + const pj_sockaddr_t *peer, + unsigned addr_len) { PJ_ASSERT_RETURN(turn_sock && peer && addr_len, PJ_EINVAL); PJ_ASSERT_RETURN(turn_sock->sess != NULL, PJ_EINVALIDOP); @@ -676,8 +675,8 @@ PJ_DEF(pj_status_t) pj_turn_sock_bind_channel( pj_turn_sock *turn_sock, * Send Connect request for the specified a peer address. */ PJ_DEF(pj_status_t) pj_turn_sock_connect( pj_turn_sock *turn_sock, - const pj_sockaddr_t *peer_addr, - unsigned addr_len) + const pj_sockaddr_t *peer_addr, + unsigned addr_len) { PJ_ASSERT_RETURN(turn_sock && peer_addr && addr_len, PJ_EINVAL); PJ_ASSERT_RETURN(turn_sock->sess != NULL, PJ_EINVALIDOP); @@ -689,8 +688,8 @@ PJ_DEF(pj_status_t) pj_turn_sock_connect( pj_turn_sock *turn_sock, * Close existing connection to the peer address. */ PJ_DEF(pj_status_t) pj_turn_sock_disconnect( pj_turn_sock *turn_sock, - const pj_sockaddr_t *peer_addr, - unsigned addr_len) + const pj_sockaddr_t *peer_addr, + unsigned addr_len) { unsigned i; @@ -701,19 +700,19 @@ PJ_DEF(pj_status_t) pj_turn_sock_disconnect( pj_turn_sock *turn_sock, pj_grp_lock_acquire(turn_sock->grp_lock); for (i=0; i < PJ_TURN_MAX_TCP_CONN_CNT; ++i) { - tcp_data_conn_t *conn = &turn_sock->data_conn[i]; - if (conn->state < DATACONN_STATE_CONN_BINDING) - continue; - if (pj_sockaddr_cmp(&conn->peer_addr, peer_addr) == 0) { - dataconn_cleanup(conn); - --turn_sock->data_conn_cnt; - pj_grp_lock_release(turn_sock->grp_lock); - return PJ_SUCCESS; - } + tcp_data_conn_t *conn = &turn_sock->data_conn[i]; + if (conn->state < DATACONN_STATE_CONN_BINDING) + continue; + if (pj_sockaddr_cmp(&conn->peer_addr, peer_addr) == 0) { + dataconn_cleanup(conn); + --turn_sock->data_conn_cnt; + pj_grp_lock_release(turn_sock->grp_lock); + return PJ_SUCCESS; + } } PJ_LOG(4, (turn_sock->obj_name, "Connection for peer %s is not exist", - pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3))); + pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3))); pj_grp_lock_release(turn_sock->grp_lock); return PJ_ENOTFOUND; @@ -724,7 +723,7 @@ PJ_DEF(pj_status_t) pj_turn_sock_disconnect( pj_turn_sock *turn_sock, * Notification when outgoing TCP socket has been connected. */ static pj_bool_t on_connect_complete(pj_turn_sock *turn_sock, - pj_status_t status) + pj_status_t status) { pj_grp_lock_acquire(turn_sock->grp_lock); @@ -732,51 +731,51 @@ static pj_bool_t on_connect_complete(pj_turn_sock *turn_sock, * See ticket #1557 (https://github.com/pjsip/pjproject/issues/1557). */ if (!turn_sock->sess) { - sess_fail(turn_sock, "TURN session already destroyed", status); - pj_grp_lock_release(turn_sock->grp_lock); - return PJ_FALSE; + sess_fail(turn_sock, "TURN session already destroyed", status); + pj_grp_lock_release(turn_sock->grp_lock); + return PJ_FALSE; } if (status != PJ_SUCCESS) { - if (turn_sock->conn_type == PJ_TURN_TP_UDP) - sess_fail(turn_sock, "UDP connect() error", status); - else if (turn_sock->conn_type == PJ_TURN_TP_TCP) - sess_fail(turn_sock, "TCP connect() error", status); - else if (turn_sock->conn_type == PJ_TURN_TP_TLS) - sess_fail(turn_sock, "TLS connect() error", status); + if (turn_sock->conn_type == PJ_TURN_TP_UDP) + sess_fail(turn_sock, "UDP connect() error", status); + else if (turn_sock->conn_type == PJ_TURN_TP_TCP) + sess_fail(turn_sock, "TCP connect() error", status); + else if (turn_sock->conn_type == PJ_TURN_TP_TLS) + sess_fail(turn_sock, "TLS connect() error", status); - pj_grp_lock_release(turn_sock->grp_lock); - return PJ_FALSE; + pj_grp_lock_release(turn_sock->grp_lock); + return PJ_FALSE; } if (turn_sock->conn_type != PJ_TURN_TP_UDP) { - PJ_LOG(5, (turn_sock->obj_name, "%s connected", - turn_sock->conn_type == PJ_TURN_TP_TCP ? "TCP" : "TLS")); + PJ_LOG(5, (turn_sock->obj_name, "%s connected", + turn_sock->conn_type == PJ_TURN_TP_TCP ? "TCP" : "TLS")); } /* Kick start pending read operation */ if (turn_sock->conn_type != PJ_TURN_TP_TLS) - status = pj_activesock_start_read(turn_sock->active_sock, - turn_sock->pool, - turn_sock->setting.max_pkt_size, - 0); + status = pj_activesock_start_read(turn_sock->active_sock, + turn_sock->pool, + turn_sock->setting.max_pkt_size, + 0); #if PJ_HAS_SSL_SOCK else - status = pj_ssl_sock_start_read(turn_sock->ssl_sock, turn_sock->pool, - turn_sock->setting.max_pkt_size, 0); + status = pj_ssl_sock_start_read(turn_sock->ssl_sock, turn_sock->pool, + turn_sock->setting.max_pkt_size, 0); #endif /* Init send_key */ pj_ioqueue_op_key_init(&turn_sock->send_key, sizeof(turn_sock->send_key)); pj_ioqueue_op_key_init(&turn_sock->int_send_key, - sizeof(turn_sock->int_send_key)); + sizeof(turn_sock->int_send_key)); /* Send Allocate request */ status = pj_turn_session_alloc(turn_sock->sess, &turn_sock->alloc_param); if (status != PJ_SUCCESS) { - sess_fail(turn_sock, "Error sending ALLOCATE", status); - pj_grp_lock_release(turn_sock->grp_lock); - return PJ_FALSE; + sess_fail(turn_sock, "Error sending ALLOCATE", status); + pj_grp_lock_release(turn_sock->grp_lock); + return PJ_FALSE; } pj_grp_lock_release(turn_sock->grp_lock); @@ -784,26 +783,26 @@ static pj_bool_t on_connect_complete(pj_turn_sock *turn_sock, } static pj_bool_t on_connect_complete_asock(pj_activesock_t *asock, - pj_status_t status) + pj_status_t status) { pj_turn_sock *turn_sock; turn_sock = (pj_turn_sock*)pj_activesock_get_user_data(asock); if (!turn_sock) - return PJ_FALSE; + return PJ_FALSE; return on_connect_complete(turn_sock, status); } #if PJ_HAS_SSL_SOCK static pj_bool_t on_connect_complete_ssl_sock(pj_ssl_sock_t *ssl_sock, - pj_status_t status) + pj_status_t status) { pj_turn_sock *turn_sock; turn_sock = (pj_turn_sock*)pj_ssl_sock_get_user_data(ssl_sock); if (!turn_sock) - return PJ_FALSE; + return PJ_FALSE; return on_connect_complete(turn_sock, status); } @@ -812,7 +811,7 @@ static pj_bool_t on_connect_complete_ssl_sock(pj_ssl_sock_t *ssl_sock, static pj_uint16_t GETVAL16H(const pj_uint8_t *buf, unsigned pos) { return (pj_uint16_t) ((buf[pos + 0] << 8) | \ - (buf[pos + 1] << 0)); + (buf[pos + 1] << 0)); } /* Quick check to determine if there is enough packet to process in the @@ -823,32 +822,32 @@ static unsigned has_packet(pj_turn_sock *turn_sock, const void *buf, pj_size_t b pj_bool_t is_stun; if (turn_sock->conn_type == PJ_TURN_TP_UDP) - return (unsigned)bufsize; + return (unsigned)bufsize; /* Quickly check if this is STUN message, by checking the first two bits and * size field which must be multiple of 4 bytes */ is_stun = ((((pj_uint8_t*)buf)[0] & 0xC0) == 0) && - ((GETVAL16H((const pj_uint8_t*)buf, 2) & 0x03)==0); + ((GETVAL16H((const pj_uint8_t*)buf, 2) & 0x03)==0); if (is_stun) { - pj_size_t msg_len = GETVAL16H((const pj_uint8_t*)buf, 2); - return (unsigned)((msg_len+20 <= bufsize) ? msg_len+20 : 0); + pj_size_t msg_len = GETVAL16H((const pj_uint8_t*)buf, 2); + return (unsigned)((msg_len+20 <= bufsize) ? msg_len+20 : 0); } else { - /* This must be ChannelData. */ - pj_turn_channel_data cd; + /* This must be ChannelData. */ + pj_turn_channel_data cd; - if (bufsize < 4) - return 0; + if (bufsize < 4) + return 0; - /* Decode ChannelData packet */ - pj_memcpy(&cd, buf, sizeof(pj_turn_channel_data)); - cd.length = pj_ntohs(cd.length); + /* Decode ChannelData packet */ + pj_memcpy(&cd, buf, sizeof(pj_turn_channel_data)); + cd.length = pj_ntohs(cd.length); - if (bufsize >= cd.length+sizeof(cd)) - return (cd.length+sizeof(cd)+3) & (~3); - else - return 0; + if (bufsize >= cd.length+sizeof(cd)) + return (cd.length+sizeof(cd)+3) & (~3); + else + return 0; } } @@ -856,66 +855,66 @@ static unsigned has_packet(pj_turn_sock *turn_sock, const void *buf, pj_size_t b * Notification from ioqueue when incoming UDP packet is received. */ static pj_bool_t on_data_read(pj_turn_sock *turn_sock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { pj_bool_t ret = PJ_TRUE; pj_grp_lock_acquire(turn_sock->grp_lock); if (status == PJ_SUCCESS && turn_sock->sess && !turn_sock->is_destroying) { - /* Report incoming packet to TURN session, repeat while we have - * "packet" in the buffer (required for stream-oriented transports) - */ - unsigned pkt_len; - - //PJ_LOG(5,(turn_sock->pool->obj_name, - // "Incoming data, %lu bytes total buffer", size)); - - while ((pkt_len=has_packet(turn_sock, data, size)) != 0) { - pj_size_t parsed_len; - //const pj_uint8_t *pkt = (const pj_uint8_t*)data; - - //PJ_LOG(5,(turn_sock->pool->obj_name, - // "Packet start: %02X %02X %02X %02X", - // pkt[0], pkt[1], pkt[2], pkt[3])); - - //PJ_LOG(5,(turn_sock->pool->obj_name, - // "Processing %lu bytes packet of %lu bytes total buffer", - // pkt_len, size)); - - parsed_len = (unsigned)size; - pj_turn_session_on_rx_pkt(turn_sock->sess, data, size, &parsed_len); - - /* parsed_len may be zero if we have parsing error, so use our - * previous calculation to exhaust the bad packet. - */ - if (parsed_len == 0) - parsed_len = pkt_len; - - if (parsed_len < (unsigned)size) { - *remainder = size - parsed_len; - pj_memmove(data, ((char*)data)+parsed_len, *remainder); - } else { - *remainder = 0; - } - size = *remainder; - - //PJ_LOG(5,(turn_sock->pool->obj_name, - // "Buffer size now %lu bytes", size)); - } + /* Report incoming packet to TURN session, repeat while we have + * "packet" in the buffer (required for stream-oriented transports) + */ + unsigned pkt_len; + + //PJ_LOG(5,(turn_sock->pool->obj_name, + // "Incoming data, %lu bytes total buffer", size)); + + while ((pkt_len=has_packet(turn_sock, data, size)) != 0) { + pj_size_t parsed_len; + //const pj_uint8_t *pkt = (const pj_uint8_t*)data; + + //PJ_LOG(5,(turn_sock->pool->obj_name, + // "Packet start: %02X %02X %02X %02X", + // pkt[0], pkt[1], pkt[2], pkt[3])); + + //PJ_LOG(5,(turn_sock->pool->obj_name, + // "Processing %lu bytes packet of %lu bytes total buffer", + // pkt_len, size)); + + parsed_len = (unsigned)size; + pj_turn_session_on_rx_pkt(turn_sock->sess, data, size, &parsed_len); + + /* parsed_len may be zero if we have parsing error, so use our + * previous calculation to exhaust the bad packet. + */ + if (parsed_len == 0) + parsed_len = pkt_len; + + if (parsed_len < (unsigned)size) { + *remainder = size - parsed_len; + pj_memmove(data, ((char*)data)+parsed_len, *remainder); + } else { + *remainder = 0; + } + size = *remainder; + + //PJ_LOG(5,(turn_sock->pool->obj_name, + // "Buffer size now %lu bytes", size)); + } } else if (status != PJ_SUCCESS) { - if (turn_sock->conn_type == PJ_TURN_TP_UDP) - sess_fail(turn_sock, "UDP connection closed", status); - else if (turn_sock->conn_type == PJ_TURN_TP_TCP) - sess_fail(turn_sock, "TCP connection closed", status); - else if (turn_sock->conn_type == PJ_TURN_TP_TLS) - sess_fail(turn_sock, "TLS connection closed", status); + if (turn_sock->conn_type == PJ_TURN_TP_UDP) + sess_fail(turn_sock, "UDP connection closed", status); + else if (turn_sock->conn_type == PJ_TURN_TP_TCP) + sess_fail(turn_sock, "TCP connection closed", status); + else if (turn_sock->conn_type == PJ_TURN_TP_TLS) + sess_fail(turn_sock, "TLS connection closed", status); - ret = PJ_FALSE; - goto on_return; + ret = PJ_FALSE; + goto on_return; } on_return: @@ -925,10 +924,10 @@ static pj_bool_t on_data_read(pj_turn_sock *turn_sock, } static pj_bool_t on_data_read_asock(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { pj_turn_sock *turn_sock; @@ -938,21 +937,21 @@ static pj_bool_t on_data_read_asock(pj_activesock_t *asock, } static pj_bool_t on_data_sent(pj_turn_sock *turn_sock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent) + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent) { /* Don't report to callback if this is internal message. */ if (send_key == &turn_sock->int_send_key) { - return PJ_TRUE; + return PJ_TRUE; } if (turn_sock->cb.on_data_sent) { - pj_ssize_t header_len, sent_size; + pj_ssize_t header_len, sent_size; /* Remove the length of packet header from sent size. */ - header_len = turn_sock->pkt_len - turn_sock->body_len; - sent_size = (sent > header_len)? (sent - header_len) : 0; - (*turn_sock->cb.on_data_sent)(turn_sock, sent_size); + header_len = turn_sock->pkt_len - turn_sock->body_len; + sent_size = (sent > header_len)? (sent - header_len) : 0; + (*turn_sock->cb.on_data_sent)(turn_sock, sent_size); } return PJ_TRUE; @@ -960,8 +959,8 @@ static pj_bool_t on_data_sent(pj_turn_sock *turn_sock, static pj_bool_t on_data_sent_asock(pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent) + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent) { pj_turn_sock *turn_sock; @@ -973,10 +972,10 @@ static pj_bool_t on_data_sent_asock(pj_activesock_t *asock, #if PJ_HAS_SSL_SOCK static pj_bool_t on_data_read_ssl_sock(pj_ssl_sock_t *ssl_sock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { pj_turn_sock *turn_sock; @@ -986,8 +985,8 @@ static pj_bool_t on_data_read_ssl_sock(pj_ssl_sock_t *ssl_sock, } static pj_bool_t on_data_sent_ssl_sock(pj_ssl_sock_t *ssl_sock, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_sent) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_sent) { pj_turn_sock *turn_sock; @@ -997,14 +996,14 @@ static pj_bool_t on_data_sent_ssl_sock(pj_ssl_sock_t *ssl_sock, /* Check for error/closure */ if (bytes_sent <= 0) { - pj_status_t status; + pj_status_t status; - status = (bytes_sent == 0) ? PJ_RETURN_OS_ERROR(OSERR_ENOTCONN) : - (pj_status_t)-bytes_sent; + status = (bytes_sent == 0) ? PJ_RETURN_OS_ERROR(OSERR_ENOTCONN) : + (pj_status_t)-bytes_sent; - sess_fail(turn_sock, "TLS send() error", status); + sess_fail(turn_sock, "TLS send() error", status); - return PJ_FALSE; + return PJ_FALSE; } return on_data_sent(turn_sock, op_key, bytes_sent); @@ -1013,73 +1012,73 @@ static pj_bool_t on_data_sent_ssl_sock(pj_ssl_sock_t *ssl_sock, static pj_status_t send_pkt(pj_turn_session *sess, - pj_bool_t internal, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_sockaddr_t *dst_addr, - unsigned dst_addr_len) + pj_bool_t internal, + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_sockaddr_t *dst_addr, + unsigned dst_addr_len) { pj_turn_sock *turn_sock = (pj_turn_sock*) - pj_turn_session_get_user_data(sess); + pj_turn_session_get_user_data(sess); pj_ssize_t len = pkt_len; pj_status_t status = PJ_SUCCESS; pj_ioqueue_op_key_t *send_key = &turn_sock->send_key; if (turn_sock == NULL || turn_sock->is_destroying) { - /* We've been destroyed */ - // https://github.com/pjsip/pjproject/issues/1316 - //pj_assert(!"We should shutdown gracefully"); - return PJ_EINVALIDOP; + /* We've been destroyed */ + // https://github.com/pjsip/pjproject/issues/1316 + //pj_assert(!"We should shutdown gracefully"); + return PJ_EINVALIDOP; } if (internal) - send_key = &turn_sock->int_send_key; + send_key = &turn_sock->int_send_key; turn_sock->pkt_len = pkt_len; if (turn_sock->conn_type == PJ_TURN_TP_UDP) { - status = pj_activesock_sendto(turn_sock->active_sock, - send_key, pkt, &len, 0, - dst_addr, dst_addr_len); + status = pj_activesock_sendto(turn_sock->active_sock, + send_key, pkt, &len, 0, + dst_addr, dst_addr_len); } else if (turn_sock->alloc_param.peer_conn_type == PJ_TURN_TP_TCP) { - pj_turn_session_info info; - pj_turn_session_get_info(turn_sock->sess, &info); - if (pj_sockaddr_cmp(&info.server, dst_addr) == 0) { - /* Destination address is TURN server */ - status = pj_activesock_send(turn_sock->active_sock, - send_key, pkt, &len, 0); - } else { - /* Destination address is peer, lookup data connection */ - unsigned i; - - status = PJ_ENOTFOUND; - for (i=0; i < PJ_TURN_MAX_TCP_CONN_CNT; ++i) { - tcp_data_conn_t *conn = &turn_sock->data_conn[i]; - if (conn->state < DATACONN_STATE_CONN_BINDING) - continue; - if (pj_sockaddr_cmp(&conn->peer_addr, dst_addr) == 0) { - status = pj_activesock_send(conn->asock, - &conn->send_key, - pkt, &len, 0); - break; - } - } - } + pj_turn_session_info info; + pj_turn_session_get_info(turn_sock->sess, &info); + if (pj_sockaddr_cmp(&info.server, dst_addr) == 0) { + /* Destination address is TURN server */ + status = pj_activesock_send(turn_sock->active_sock, + send_key, pkt, &len, 0); + } else { + /* Destination address is peer, lookup data connection */ + unsigned i; + + status = PJ_ENOTFOUND; + for (i=0; i < PJ_TURN_MAX_TCP_CONN_CNT; ++i) { + tcp_data_conn_t *conn = &turn_sock->data_conn[i]; + if (conn->state < DATACONN_STATE_CONN_BINDING) + continue; + if (pj_sockaddr_cmp(&conn->peer_addr, dst_addr) == 0) { + status = pj_activesock_send(conn->asock, + &conn->send_key, + pkt, &len, 0); + break; + } + } + } } else if (turn_sock->conn_type == PJ_TURN_TP_TCP) { - status = pj_activesock_send(turn_sock->active_sock, - send_key, pkt, &len, 0); + status = pj_activesock_send(turn_sock->active_sock, + send_key, pkt, &len, 0); } #if PJ_HAS_SSL_SOCK else if (turn_sock->conn_type == PJ_TURN_TP_TLS) { - status = pj_ssl_sock_send(turn_sock->ssl_sock, - send_key, pkt, &len, 0); + status = pj_ssl_sock_send(turn_sock->ssl_sock, + send_key, pkt, &len, 0); } #endif else { - PJ_ASSERT_RETURN(!"Invalid TURN conn_type", PJ_EINVAL); + PJ_ASSERT_RETURN(!"Invalid TURN conn_type", PJ_EINVAL); } if (status != PJ_SUCCESS && status != PJ_EPENDING) { - show_err(turn_sock, "socket send()", status); + show_err(turn_sock, "socket send()", status); } return status; @@ -1090,23 +1089,23 @@ static pj_status_t send_pkt(pj_turn_session *sess, * Callback from TURN session to send outgoing packet. */ static pj_status_t turn_on_send_pkt(pj_turn_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_sockaddr_t *dst_addr, - unsigned dst_addr_len) + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_sockaddr_t *dst_addr, + unsigned dst_addr_len) { return send_pkt(sess, PJ_FALSE, pkt, pkt_len, - dst_addr, dst_addr_len); + dst_addr, dst_addr_len); } static pj_status_t turn_on_stun_send_pkt(pj_turn_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_sockaddr_t *dst_addr, - unsigned dst_addr_len) + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_sockaddr_t *dst_addr, + unsigned dst_addr_len) { return send_pkt(sess, PJ_TRUE, pkt, pkt_len, - dst_addr, dst_addr_len); + dst_addr, dst_addr_len); } @@ -1114,9 +1113,9 @@ static pj_status_t turn_on_stun_send_pkt(pj_turn_session *sess, * Callback from TURN session when a channel is successfully bound. */ static void turn_on_channel_bound(pj_turn_session *sess, - const pj_sockaddr_t *peer_addr, - unsigned addr_len, - unsigned ch_num) + const pj_sockaddr_t *peer_addr, + unsigned addr_len, + unsigned ch_num) { PJ_UNUSED_ARG(sess); PJ_UNUSED_ARG(peer_addr); @@ -1129,26 +1128,26 @@ static void turn_on_channel_bound(pj_turn_session *sess, * Callback from TURN session upon incoming data. */ static void turn_on_rx_data(pj_turn_session *sess, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *peer_addr, - unsigned addr_len) + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *peer_addr, + unsigned addr_len) { pj_turn_sock *turn_sock = (pj_turn_sock*) - pj_turn_session_get_user_data(sess); + pj_turn_session_get_user_data(sess); if (turn_sock == NULL || turn_sock->is_destroying) { - /* We've been destroyed */ - return; + /* We've been destroyed */ + return; } if (turn_sock->alloc_param.peer_conn_type != PJ_TURN_TP_UDP) { - /* Data traffic for RFC 6062 is not via TURN session */ - return; + /* Data traffic for RFC 6062 is not via TURN session */ + return; } if (turn_sock->cb.on_rx_data) { - (*turn_sock->cb.on_rx_data)(turn_sock, pkt, pkt_len, - peer_addr, addr_len); + (*turn_sock->cb.on_rx_data)(turn_sock, pkt, pkt_len, + peer_addr, addr_len); } } @@ -1157,316 +1156,316 @@ static void turn_on_rx_data(pj_turn_session *sess, * Callback from TURN session when state has changed */ static void turn_on_state(pj_turn_session *sess, - pj_turn_state_t old_state, - pj_turn_state_t new_state) + pj_turn_state_t old_state, + pj_turn_state_t new_state) { pj_turn_sock *turn_sock = (pj_turn_sock*) - pj_turn_session_get_user_data(sess); + pj_turn_session_get_user_data(sess); pj_status_t status = PJ_SUCCESS; if (turn_sock == NULL) { - /* We've been destroyed */ - return; + /* We've been destroyed */ + return; } /* Notify app first */ if (turn_sock->cb.on_state) { - (*turn_sock->cb.on_state)(turn_sock, old_state, new_state); + (*turn_sock->cb.on_state)(turn_sock, old_state, new_state); } /* Make sure user hasn't destroyed us in the callback */ if (turn_sock->sess && new_state == PJ_TURN_STATE_RESOLVED) { - pj_turn_session_info info; - pj_turn_session_get_info(turn_sock->sess, &info); - new_state = info.state; + pj_turn_session_info info; + pj_turn_session_get_info(turn_sock->sess, &info); + new_state = info.state; } if (turn_sock->sess && new_state == PJ_TURN_STATE_RESOLVED) { - /* - * Once server has been resolved, initiate outgoing TCP - * connection to the server. - */ - pj_turn_session_info info; - char addrtxt[PJ_INET6_ADDRSTRLEN+8]; - int sock_type; - pj_sock_t sock; - pj_activesock_cfg asock_cfg; - pj_activesock_cb asock_cb; - pj_sockaddr bound_addr, *cfg_bind_addr; - pj_uint16_t max_bind_retry; - - /* Close existing connection, if any. This happens when - * we're switching to alternate TURN server when either TCP - * connection or ALLOCATE request failed. - */ - if ((turn_sock->conn_type != PJ_TURN_TP_TLS) && - (turn_sock->active_sock)) - { - pj_activesock_close(turn_sock->active_sock); - turn_sock->active_sock = NULL; - } + /* + * Once server has been resolved, initiate outgoing TCP + * connection to the server. + */ + pj_turn_session_info info; + char addrtxt[PJ_INET6_ADDRSTRLEN+8]; + int sock_type; + pj_sock_t sock; + pj_activesock_cfg asock_cfg; + pj_activesock_cb asock_cb; + pj_sockaddr bound_addr, *cfg_bind_addr; + pj_uint16_t max_bind_retry; + + /* Close existing connection, if any. This happens when + * we're switching to alternate TURN server when either TCP + * connection or ALLOCATE request failed. + */ + if ((turn_sock->conn_type != PJ_TURN_TP_TLS) && + (turn_sock->active_sock)) + { + pj_activesock_close(turn_sock->active_sock); + turn_sock->active_sock = NULL; + } #if PJ_HAS_SSL_SOCK - else if ((turn_sock->conn_type == PJ_TURN_TP_TLS) && - (turn_sock->ssl_sock)) - { - pj_ssl_sock_close(turn_sock->ssl_sock); - turn_sock->ssl_sock = NULL; - } + else if ((turn_sock->conn_type == PJ_TURN_TP_TLS) && + (turn_sock->ssl_sock)) + { + pj_ssl_sock_close(turn_sock->ssl_sock); + turn_sock->ssl_sock = NULL; + } #endif - /* Get server address from session info */ - pj_turn_session_get_info(sess, &info); - - if (turn_sock->conn_type == PJ_TURN_TP_UDP) - sock_type = pj_SOCK_DGRAM(); - else - sock_type = pj_SOCK_STREAM(); - - cfg_bind_addr = &turn_sock->setting.bound_addr; - max_bind_retry = MAX_BIND_RETRY; - if (turn_sock->setting.port_range && - turn_sock->setting.port_range < max_bind_retry) - { - max_bind_retry = turn_sock->setting.port_range; - } - pj_sockaddr_init(turn_sock->af, &bound_addr, NULL, 0); - if (cfg_bind_addr->addr.sa_family == pj_AF_INET() || - cfg_bind_addr->addr.sa_family == pj_AF_INET6()) - { - pj_sockaddr_cp(&bound_addr, cfg_bind_addr); - } - - if (turn_sock->conn_type != PJ_TURN_TP_TLS) { - /* Init socket */ - status = pj_sock_socket(turn_sock->af, sock_type, 0, &sock); - if (status != PJ_SUCCESS) { - pj_turn_sock_destroy(turn_sock); - return; - } - - /* Bind socket */ - status = pj_sock_bind_random(sock, &bound_addr, - turn_sock->setting.port_range, - max_bind_retry); - if (status != PJ_SUCCESS) { - pj_sock_close(sock); - pj_turn_sock_destroy(turn_sock); - return; - } - /* Apply QoS, if specified */ - status = pj_sock_apply_qos2(sock, turn_sock->setting.qos_type, - &turn_sock->setting.qos_params, - (turn_sock->setting.qos_ignore_error?2:1), - turn_sock->pool->obj_name, NULL); - if (status != PJ_SUCCESS && !turn_sock->setting.qos_ignore_error) - { - pj_sock_close(sock); - pj_turn_sock_destroy(turn_sock); - return; - } - - /* Apply socket buffer size */ - if (turn_sock->setting.so_rcvbuf_size > 0) { - unsigned sobuf_size = turn_sock->setting.so_rcvbuf_size; - status = pj_sock_setsockopt_sobuf(sock, pj_SO_RCVBUF(), - PJ_TRUE, &sobuf_size); - if (status != PJ_SUCCESS) { - pj_perror(3, turn_sock->obj_name, status, - "Failed setting SO_RCVBUF"); - } else { - if (sobuf_size < turn_sock->setting.so_rcvbuf_size) { - PJ_LOG(4, (turn_sock->obj_name, - "Warning! Cannot set SO_RCVBUF as configured," - " now=%d, configured=%d", sobuf_size, - turn_sock->setting.so_rcvbuf_size)); - } else { - PJ_LOG(5, (turn_sock->obj_name, "SO_RCVBUF set to %d", - sobuf_size)); - } - } - } - if (turn_sock->setting.so_sndbuf_size > 0) { - unsigned sobuf_size = turn_sock->setting.so_sndbuf_size; - status = pj_sock_setsockopt_sobuf(sock, pj_SO_SNDBUF(), - PJ_TRUE, &sobuf_size); - if (status != PJ_SUCCESS) { - pj_perror(3, turn_sock->obj_name, status, - "Failed setting SO_SNDBUF"); - } else { - if (sobuf_size < turn_sock->setting.so_sndbuf_size) { - PJ_LOG(4, (turn_sock->obj_name, - "Warning! Cannot set SO_SNDBUF as configured," - " now=%d, configured=%d", sobuf_size, - turn_sock->setting.so_sndbuf_size)); - } else { - PJ_LOG(5, (turn_sock->obj_name, "SO_SNDBUF set to %d", - sobuf_size)); - } - } - } - - /* Create active socket */ - pj_activesock_cfg_default(&asock_cfg); - asock_cfg.grp_lock = turn_sock->grp_lock; - - pj_bzero(&asock_cb, sizeof(asock_cb)); - asock_cb.on_data_read = &on_data_read_asock; - asock_cb.on_data_sent = &on_data_sent_asock; - asock_cb.on_connect_complete = &on_connect_complete_asock; - status = pj_activesock_create(turn_sock->pool, sock, - sock_type, &asock_cfg, - turn_sock->cfg.ioqueue, &asock_cb, - turn_sock, - &turn_sock->active_sock); - if (status != PJ_SUCCESS) - pj_sock_close(sock); - } + /* Get server address from session info */ + pj_turn_session_get_info(sess, &info); + + if (turn_sock->conn_type == PJ_TURN_TP_UDP) + sock_type = pj_SOCK_DGRAM(); + else + sock_type = pj_SOCK_STREAM(); + + cfg_bind_addr = &turn_sock->setting.bound_addr; + max_bind_retry = MAX_BIND_RETRY; + if (turn_sock->setting.port_range && + turn_sock->setting.port_range < max_bind_retry) + { + max_bind_retry = turn_sock->setting.port_range; + } + pj_sockaddr_init(turn_sock->af, &bound_addr, NULL, 0); + if (cfg_bind_addr->addr.sa_family == pj_AF_INET() || + cfg_bind_addr->addr.sa_family == pj_AF_INET6()) + { + pj_sockaddr_cp(&bound_addr, cfg_bind_addr); + } + + if (turn_sock->conn_type != PJ_TURN_TP_TLS) { + /* Init socket */ + status = pj_sock_socket(turn_sock->af, sock_type, 0, &sock); + if (status != PJ_SUCCESS) { + pj_turn_sock_destroy(turn_sock); + return; + } + + /* Bind socket */ + status = pj_sock_bind_random(sock, &bound_addr, + turn_sock->setting.port_range, + max_bind_retry); + if (status != PJ_SUCCESS) { + pj_sock_close(sock); + pj_turn_sock_destroy(turn_sock); + return; + } + /* Apply QoS, if specified */ + status = pj_sock_apply_qos2(sock, turn_sock->setting.qos_type, + &turn_sock->setting.qos_params, + (turn_sock->setting.qos_ignore_error?2:1), + turn_sock->pool->obj_name, NULL); + if (status != PJ_SUCCESS && !turn_sock->setting.qos_ignore_error) + { + pj_sock_close(sock); + pj_turn_sock_destroy(turn_sock); + return; + } + + /* Apply socket buffer size */ + if (turn_sock->setting.so_rcvbuf_size > 0) { + unsigned sobuf_size = turn_sock->setting.so_rcvbuf_size; + status = pj_sock_setsockopt_sobuf(sock, pj_SO_RCVBUF(), + PJ_TRUE, &sobuf_size); + if (status != PJ_SUCCESS) { + pj_perror(3, turn_sock->obj_name, status, + "Failed setting SO_RCVBUF"); + } else { + if (sobuf_size < turn_sock->setting.so_rcvbuf_size) { + PJ_LOG(4, (turn_sock->obj_name, + "Warning! Cannot set SO_RCVBUF as configured," + " now=%d, configured=%d", sobuf_size, + turn_sock->setting.so_rcvbuf_size)); + } else { + PJ_LOG(5, (turn_sock->obj_name, "SO_RCVBUF set to %d", + sobuf_size)); + } + } + } + if (turn_sock->setting.so_sndbuf_size > 0) { + unsigned sobuf_size = turn_sock->setting.so_sndbuf_size; + status = pj_sock_setsockopt_sobuf(sock, pj_SO_SNDBUF(), + PJ_TRUE, &sobuf_size); + if (status != PJ_SUCCESS) { + pj_perror(3, turn_sock->obj_name, status, + "Failed setting SO_SNDBUF"); + } else { + if (sobuf_size < turn_sock->setting.so_sndbuf_size) { + PJ_LOG(4, (turn_sock->obj_name, + "Warning! Cannot set SO_SNDBUF as configured," + " now=%d, configured=%d", sobuf_size, + turn_sock->setting.so_sndbuf_size)); + } else { + PJ_LOG(5, (turn_sock->obj_name, "SO_SNDBUF set to %d", + sobuf_size)); + } + } + } + + /* Create active socket */ + pj_activesock_cfg_default(&asock_cfg); + asock_cfg.grp_lock = turn_sock->grp_lock; + + pj_bzero(&asock_cb, sizeof(asock_cb)); + asock_cb.on_data_read = &on_data_read_asock; + asock_cb.on_data_sent = &on_data_sent_asock; + asock_cb.on_connect_complete = &on_connect_complete_asock; + status = pj_activesock_create(turn_sock->pool, sock, + sock_type, &asock_cfg, + turn_sock->cfg.ioqueue, &asock_cb, + turn_sock, + &turn_sock->active_sock); + if (status != PJ_SUCCESS) + pj_sock_close(sock); + } #if PJ_HAS_SSL_SOCK - else { - //TURN TLS - pj_ssl_sock_param param, *ssock_param; - - ssock_param = &turn_sock->setting.tls_cfg.ssock_param; - pj_ssl_sock_param_default(¶m); - - pj_ssl_sock_param_copy(turn_sock->pool, ¶m, ssock_param); - param.cb.on_connect_complete = &on_connect_complete_ssl_sock; - param.cb.on_data_read = &on_data_read_ssl_sock; - param.cb.on_data_sent = &on_data_sent_ssl_sock; - param.ioqueue = turn_sock->cfg.ioqueue; - param.timer_heap = turn_sock->cfg.timer_heap; - param.grp_lock = turn_sock->grp_lock; - param.server_name = turn_sock->server_name; - param.user_data = turn_sock; - param.sock_type = sock_type; - param.sock_af = turn_sock->af; - if (param.send_buffer_size < PJ_TURN_MAX_PKT_LEN) - param.send_buffer_size = PJ_TURN_MAX_PKT_LEN; - if (param.read_buffer_size < PJ_TURN_MAX_PKT_LEN) - param.read_buffer_size = PJ_TURN_MAX_PKT_LEN; - - param.qos_type = turn_sock->setting.qos_type; - param.qos_ignore_error = turn_sock->setting.qos_ignore_error; - pj_memcpy(¶m.qos_params, &turn_sock->setting.qos_params, - sizeof(param.qos_params)); - - if (turn_sock->setting.tls_cfg.cert_file.slen || - turn_sock->setting.tls_cfg.ca_list_file.slen || - turn_sock->setting.tls_cfg.ca_list_path.slen || - turn_sock->setting.tls_cfg.privkey_file.slen) - { - status = pj_ssl_cert_load_from_files2( - turn_sock->pool, - &turn_sock->setting.tls_cfg.ca_list_file, - &turn_sock->setting.tls_cfg.ca_list_path, - &turn_sock->setting.tls_cfg.cert_file, - &turn_sock->setting.tls_cfg.privkey_file, - &turn_sock->setting.tls_cfg.password, - &turn_sock->cert); - - } else if (turn_sock->setting.tls_cfg.ca_buf.slen || - turn_sock->setting.tls_cfg.cert_buf.slen || - turn_sock->setting.tls_cfg.privkey_buf.slen) - { - status = pj_ssl_cert_load_from_buffer( - turn_sock->pool, - &turn_sock->setting.tls_cfg.ca_buf, - &turn_sock->setting.tls_cfg.cert_buf, - &turn_sock->setting.tls_cfg.privkey_buf, - &turn_sock->setting.tls_cfg.password, - &turn_sock->cert); - } - if (status != PJ_SUCCESS) { - pj_turn_sock_destroy(turn_sock); - return; - } - if (turn_sock->cert) { - pj_turn_sock_tls_cfg_wipe_keys(&turn_sock->setting.tls_cfg); - } - - status = pj_ssl_sock_create(turn_sock->pool, ¶m, - &turn_sock->ssl_sock); - - if (status != PJ_SUCCESS) { - pj_turn_sock_destroy(turn_sock); - return; - } - - if (turn_sock->cert) { - status = pj_ssl_sock_set_certificate(turn_sock->ssl_sock, - turn_sock->pool, - turn_sock->cert); - - pj_ssl_cert_wipe_keys(turn_sock->cert); - turn_sock->cert = NULL; - } - - } + else { + //TURN TLS + pj_ssl_sock_param param, *ssock_param; + + ssock_param = &turn_sock->setting.tls_cfg.ssock_param; + pj_ssl_sock_param_default(¶m); + + pj_ssl_sock_param_copy(turn_sock->pool, ¶m, ssock_param); + param.cb.on_connect_complete = &on_connect_complete_ssl_sock; + param.cb.on_data_read = &on_data_read_ssl_sock; + param.cb.on_data_sent = &on_data_sent_ssl_sock; + param.ioqueue = turn_sock->cfg.ioqueue; + param.timer_heap = turn_sock->cfg.timer_heap; + param.grp_lock = turn_sock->grp_lock; + param.server_name = turn_sock->server_name; + param.user_data = turn_sock; + param.sock_type = sock_type; + param.sock_af = turn_sock->af; + if (param.send_buffer_size < PJ_TURN_MAX_PKT_LEN) + param.send_buffer_size = PJ_TURN_MAX_PKT_LEN; + if (param.read_buffer_size < PJ_TURN_MAX_PKT_LEN) + param.read_buffer_size = PJ_TURN_MAX_PKT_LEN; + + param.qos_type = turn_sock->setting.qos_type; + param.qos_ignore_error = turn_sock->setting.qos_ignore_error; + pj_memcpy(¶m.qos_params, &turn_sock->setting.qos_params, + sizeof(param.qos_params)); + + if (turn_sock->setting.tls_cfg.cert_file.slen || + turn_sock->setting.tls_cfg.ca_list_file.slen || + turn_sock->setting.tls_cfg.ca_list_path.slen || + turn_sock->setting.tls_cfg.privkey_file.slen) + { + status = pj_ssl_cert_load_from_files2( + turn_sock->pool, + &turn_sock->setting.tls_cfg.ca_list_file, + &turn_sock->setting.tls_cfg.ca_list_path, + &turn_sock->setting.tls_cfg.cert_file, + &turn_sock->setting.tls_cfg.privkey_file, + &turn_sock->setting.tls_cfg.password, + &turn_sock->cert); + + } else if (turn_sock->setting.tls_cfg.ca_buf.slen || + turn_sock->setting.tls_cfg.cert_buf.slen || + turn_sock->setting.tls_cfg.privkey_buf.slen) + { + status = pj_ssl_cert_load_from_buffer( + turn_sock->pool, + &turn_sock->setting.tls_cfg.ca_buf, + &turn_sock->setting.tls_cfg.cert_buf, + &turn_sock->setting.tls_cfg.privkey_buf, + &turn_sock->setting.tls_cfg.password, + &turn_sock->cert); + } + if (status != PJ_SUCCESS) { + pj_turn_sock_destroy(turn_sock); + return; + } + if (turn_sock->cert) { + pj_turn_sock_tls_cfg_wipe_keys(&turn_sock->setting.tls_cfg); + } + + status = pj_ssl_sock_create(turn_sock->pool, ¶m, + &turn_sock->ssl_sock); + + if (status != PJ_SUCCESS) { + pj_turn_sock_destroy(turn_sock); + return; + } + + if (turn_sock->cert) { + status = pj_ssl_sock_set_certificate(turn_sock->ssl_sock, + turn_sock->pool, + turn_sock->cert); + + pj_ssl_cert_wipe_keys(turn_sock->cert); + turn_sock->cert = NULL; + } + + } #endif - if (status != PJ_SUCCESS) { - pj_turn_sock_destroy(turn_sock); - return; - } + if (status != PJ_SUCCESS) { + pj_turn_sock_destroy(turn_sock); + return; + } - PJ_LOG(5,(turn_sock->pool->obj_name, - "Connecting to %s", - pj_sockaddr_print(&info.server, addrtxt, - sizeof(addrtxt), 3))); + PJ_LOG(5,(turn_sock->pool->obj_name, + "Connecting to %s", + pj_sockaddr_print(&info.server, addrtxt, + sizeof(addrtxt), 3))); - /* Initiate non-blocking connect */ - if (turn_sock->conn_type == PJ_TURN_TP_UDP) { - status = PJ_SUCCESS; - } + /* Initiate non-blocking connect */ + if (turn_sock->conn_type == PJ_TURN_TP_UDP) { + status = PJ_SUCCESS; + } #if PJ_HAS_TCP - else if (turn_sock->conn_type == PJ_TURN_TP_TCP) { - status=pj_activesock_start_connect( - turn_sock->active_sock, - turn_sock->pool, - &info.server, - pj_sockaddr_get_len(&info.server)); - } -#endif + else if (turn_sock->conn_type == PJ_TURN_TP_TCP) { + status=pj_activesock_start_connect( + turn_sock->active_sock, + turn_sock->pool, + &info.server, + pj_sockaddr_get_len(&info.server)); + } +#endif #if PJ_HAS_SSL_SOCK - else if (turn_sock->conn_type == PJ_TURN_TP_TLS) { - pj_ssl_start_connect_param connect_param; - connect_param.pool = turn_sock->pool; - connect_param.localaddr = &bound_addr; - connect_param.local_port_range = turn_sock->setting.port_range; - connect_param.remaddr = &info.server; - connect_param.addr_len = pj_sockaddr_get_len(&info.server); - - status = pj_ssl_sock_start_connect2(turn_sock->ssl_sock, - &connect_param); - } + else if (turn_sock->conn_type == PJ_TURN_TP_TLS) { + pj_ssl_start_connect_param connect_param; + connect_param.pool = turn_sock->pool; + connect_param.localaddr = &bound_addr; + connect_param.local_port_range = turn_sock->setting.port_range; + connect_param.remaddr = &info.server; + connect_param.addr_len = pj_sockaddr_get_len(&info.server); + + status = pj_ssl_sock_start_connect2(turn_sock->ssl_sock, + &connect_param); + } #endif - if (status == PJ_SUCCESS) { - on_connect_complete(turn_sock, PJ_SUCCESS); - } else if (status != PJ_EPENDING) { + if (status == PJ_SUCCESS) { + on_connect_complete(turn_sock, PJ_SUCCESS); + } else if (status != PJ_EPENDING) { PJ_PERROR(3, (turn_sock->pool->obj_name, status, - "Failed to connect to %s", - pj_sockaddr_print(&info.server, addrtxt, - sizeof(addrtxt), 3))); - pj_turn_sock_destroy(turn_sock); - return; - } + "Failed to connect to %s", + pj_sockaddr_print(&info.server, addrtxt, + sizeof(addrtxt), 3))); + pj_turn_sock_destroy(turn_sock); + return; + } - /* Done for now. Subsequent work will be done in - * on_connect_complete() callback. - */ + /* Done for now. Subsequent work will be done in + * on_connect_complete() callback. + */ } if (new_state >= PJ_TURN_STATE_DESTROYING && turn_sock->sess) { - pj_time_val delay = {0, 0}; + pj_time_val delay = {0, 0}; - turn_sock->sess = NULL; - pj_turn_session_set_user_data(sess, NULL); + turn_sock->sess = NULL; + pj_turn_session_set_user_data(sess, NULL); - pj_timer_heap_cancel_if_active(turn_sock->cfg.timer_heap, - &turn_sock->timer, 0); - pj_timer_heap_schedule_w_grp_lock(turn_sock->cfg.timer_heap, - &turn_sock->timer, - &delay, TIMER_DESTROY, - turn_sock->grp_lock); + pj_timer_heap_cancel_if_active(turn_sock->cfg.timer_heap, + &turn_sock->timer, 0); + pj_timer_heap_schedule_w_grp_lock(turn_sock->cfg.timer_heap, + &turn_sock->timer, + &delay, TIMER_DESTROY, + turn_sock->grp_lock); } } @@ -1474,7 +1473,7 @@ static void turn_on_state(pj_turn_session *sess, static void dataconn_cleanup(tcp_data_conn_t *conn) { if (conn->asock) - pj_activesock_close(conn->asock); + pj_activesock_close(conn->asock); pj_pool_safe_release(&conn->pool); @@ -1482,59 +1481,59 @@ static void dataconn_cleanup(tcp_data_conn_t *conn) } static pj_bool_t dataconn_on_data_read(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { tcp_data_conn_t *conn = (tcp_data_conn_t*) - pj_activesock_get_user_data(asock); + pj_activesock_get_user_data(asock); pj_turn_sock *turn_sock = conn->turn_sock; pj_grp_lock_acquire(turn_sock->grp_lock); if (size == 0 && status != PJ_SUCCESS) { - /* Connection gone, release data connection */ - dataconn_cleanup(conn); - --turn_sock->data_conn_cnt; - pj_grp_lock_release(turn_sock->grp_lock); - return PJ_FALSE; + /* Connection gone, release data connection */ + dataconn_cleanup(conn); + --turn_sock->data_conn_cnt; + pj_grp_lock_release(turn_sock->grp_lock); + return PJ_FALSE; } *remainder = size; while (*remainder > 0) { - if (conn->state == DATACONN_STATE_READY) { - /* Application data */ - if (turn_sock->cb.on_rx_data) { - (*turn_sock->cb.on_rx_data)(turn_sock, data, (unsigned)*remainder, - &conn->peer_addr, - conn->peer_addr_len); - } - *remainder = 0; - } else if (conn->state == DATACONN_STATE_CONN_BINDING) { - /* Waiting for ConnectionBind response */ - pj_bool_t is_stun; - pj_turn_session_on_rx_pkt_param prm; - - /* Ignore if this is not a STUN message */ - is_stun = ((((pj_uint8_t*)data)[0] & 0xC0) == 0); - if (!is_stun) - goto on_return; - - pj_bzero(&prm, sizeof(prm)); - prm.pkt = data; - prm.pkt_len = *remainder; - prm.src_addr = &conn->peer_addr; - prm.src_addr_len = conn->peer_addr_len; - pj_turn_session_on_rx_pkt2(conn->turn_sock->sess, &prm); - /* Got remainder? */ - if (prm.parsed_len < *remainder && prm.parsed_len > 0) { - pj_memmove(data, (pj_uint8_t*)data + prm.parsed_len, - *remainder); - } - *remainder -= prm.parsed_len; - } else - goto on_return; + if (conn->state == DATACONN_STATE_READY) { + /* Application data */ + if (turn_sock->cb.on_rx_data) { + (*turn_sock->cb.on_rx_data)(turn_sock, data, (unsigned)*remainder, + &conn->peer_addr, + conn->peer_addr_len); + } + *remainder = 0; + } else if (conn->state == DATACONN_STATE_CONN_BINDING) { + /* Waiting for ConnectionBind response */ + pj_bool_t is_stun; + pj_turn_session_on_rx_pkt_param prm; + + /* Ignore if this is not a STUN message */ + is_stun = ((((pj_uint8_t*)data)[0] & 0xC0) == 0); + if (!is_stun) + goto on_return; + + pj_bzero(&prm, sizeof(prm)); + prm.pkt = data; + prm.pkt_len = *remainder; + prm.src_addr = &conn->peer_addr; + prm.src_addr_len = conn->peer_addr_len; + pj_turn_session_on_rx_pkt2(conn->turn_sock->sess, &prm); + /* Got remainder? */ + if (prm.parsed_len < *remainder && prm.parsed_len > 0) { + pj_memmove(data, (pj_uint8_t*)data + prm.parsed_len, + *remainder); + } + *remainder -= prm.parsed_len; + } else + goto on_return; } on_return: @@ -1543,42 +1542,42 @@ static pj_bool_t dataconn_on_data_read(pj_activesock_t *asock, } static pj_bool_t dataconn_on_data_sent(pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent) + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent) { tcp_data_conn_t *conn = (tcp_data_conn_t*) - pj_activesock_get_user_data(asock); + pj_activesock_get_user_data(asock); pj_turn_sock *turn_sock = conn->turn_sock; return on_data_sent(turn_sock, send_key, sent); } static pj_bool_t dataconn_on_connect_complete(pj_activesock_t *asock, - pj_status_t status) + pj_status_t status) { tcp_data_conn_t *conn = (tcp_data_conn_t*) - pj_activesock_get_user_data(asock); + pj_activesock_get_user_data(asock); pj_turn_sock *turn_sock = conn->turn_sock; pj_grp_lock_acquire(turn_sock->grp_lock); if (status == PJ_SUCCESS) { - status = pj_activesock_start_read(asock, turn_sock->pool, - turn_sock->setting.max_pkt_size, 0); + status = pj_activesock_start_read(asock, turn_sock->pool, + turn_sock->setting.max_pkt_size, 0); } if (status == PJ_SUCCESS) { - conn->state = DATACONN_STATE_CONN_BINDING; - status = pj_turn_session_connection_bind(turn_sock->sess, - conn->pool, - conn->id, - &conn->peer_addr, - conn->peer_addr_len); + conn->state = DATACONN_STATE_CONN_BINDING; + status = pj_turn_session_connection_bind(turn_sock->sess, + conn->pool, + conn->id, + &conn->peer_addr, + conn->peer_addr_len); } if (status != PJ_SUCCESS) { - dataconn_cleanup(conn); - --turn_sock->data_conn_cnt; - pj_grp_lock_release(turn_sock->grp_lock); - return PJ_FALSE; + dataconn_cleanup(conn); + --turn_sock->data_conn_cnt; + pj_grp_lock_release(turn_sock->grp_lock); + return PJ_FALSE; } pj_grp_lock_release(turn_sock->grp_lock); @@ -1587,12 +1586,12 @@ static pj_bool_t dataconn_on_connect_complete(pj_activesock_t *asock, static void turn_on_connection_attempt(pj_turn_session *sess, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len) + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len) { pj_turn_sock *turn_sock = (pj_turn_sock*) - pj_turn_session_get_user_data(sess); + pj_turn_session_get_user_data(sess); pj_pool_t *pool; tcp_data_conn_t *new_conn; pj_turn_session_info info; @@ -1606,44 +1605,44 @@ static void turn_on_connection_attempt(pj_turn_session *sess, unsigned i; PJ_ASSERT_ON_FAIL(turn_sock->conn_type == PJ_TURN_TP_TCP && - turn_sock->alloc_param.peer_conn_type == PJ_TURN_TP_TCP, - return); + turn_sock->alloc_param.peer_conn_type == PJ_TURN_TP_TCP, + return); PJ_LOG(5,(turn_sock->pool->obj_name, "Connection attempt from peer %s", - pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3))); + pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3))); if (turn_sock == NULL) { - /* We've been destroyed */ - return; + /* We've been destroyed */ + return; } pj_grp_lock_acquire(turn_sock->grp_lock); if (turn_sock->data_conn_cnt == PJ_TURN_MAX_TCP_CONN_CNT) { - /* Data connection has reached limit */ - pj_grp_lock_release(turn_sock->grp_lock); - return; + /* Data connection has reached limit */ + pj_grp_lock_release(turn_sock->grp_lock); + return; } /* Check if app wants to accept this connection */ status = PJ_SUCCESS; if (turn_sock->cb.on_connection_attempt) { - status = (*turn_sock->cb.on_connection_attempt)(turn_sock, conn_id, - peer_addr, addr_len); + status = (*turn_sock->cb.on_connection_attempt)(turn_sock, conn_id, + peer_addr, addr_len); } /* App rejects it */ if (status != PJ_SUCCESS) { - pj_perror(4, turn_sock->pool->obj_name, status, - "Rejected connection attempt from peer %s", - pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3)); - pj_grp_lock_release(turn_sock->grp_lock); - return; + pj_perror(4, turn_sock->pool->obj_name, status, + "Rejected connection attempt from peer %s", + pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3)); + pj_grp_lock_release(turn_sock->grp_lock); + return; } /* Find free data connection slot */ for (i=0; i < PJ_TURN_MAX_TCP_CONN_CNT; ++i) { - if (turn_sock->data_conn[i].state == DATACONN_STATE_NULL) - break; + if (turn_sock->data_conn[i].state == DATACONN_STATE_NULL) + break; } /* Verify that a free slot is found */ @@ -1665,66 +1664,66 @@ static void turn_on_connection_attempt(pj_turn_session *sess, /* Init socket */ status = pj_sock_socket(turn_sock->af, pj_SOCK_STREAM(), 0, &sock); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Bind socket */ cfg_bind_addr = &turn_sock->setting.bound_addr; max_bind_retry = MAX_BIND_RETRY; if (turn_sock->setting.port_range && - turn_sock->setting.port_range < max_bind_retry) + turn_sock->setting.port_range < max_bind_retry) { - max_bind_retry = turn_sock->setting.port_range; + max_bind_retry = turn_sock->setting.port_range; } pj_sockaddr_init(turn_sock->af, &bound_addr, NULL, 0); if (cfg_bind_addr->addr.sa_family == pj_AF_INET() || - cfg_bind_addr->addr.sa_family == pj_AF_INET6()) + cfg_bind_addr->addr.sa_family == pj_AF_INET6()) { - pj_sockaddr_cp(&bound_addr, cfg_bind_addr); + pj_sockaddr_cp(&bound_addr, cfg_bind_addr); } status = pj_sock_bind_random(sock, &bound_addr, - turn_sock->setting.port_range, - max_bind_retry); + turn_sock->setting.port_range, + max_bind_retry); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Apply socket buffer size */ if (turn_sock->setting.so_rcvbuf_size > 0) { - unsigned sobuf_size = turn_sock->setting.so_rcvbuf_size; - status = pj_sock_setsockopt_sobuf(sock, pj_SO_RCVBUF(), PJ_TRUE, - &sobuf_size); - if (status != PJ_SUCCESS) { - pj_perror(3, turn_sock->obj_name, status, - "Failed setting SO_RCVBUF"); - } else { - if (sobuf_size < turn_sock->setting.so_rcvbuf_size) { - PJ_LOG(4, (turn_sock->obj_name, - "Warning! Cannot set SO_RCVBUF as configured," - " now=%d, configured=%d", sobuf_size, - turn_sock->setting.so_rcvbuf_size)); - } else { - PJ_LOG(5, (turn_sock->obj_name, "SO_RCVBUF set to %d", - sobuf_size)); - } - } + unsigned sobuf_size = turn_sock->setting.so_rcvbuf_size; + status = pj_sock_setsockopt_sobuf(sock, pj_SO_RCVBUF(), PJ_TRUE, + &sobuf_size); + if (status != PJ_SUCCESS) { + pj_perror(3, turn_sock->obj_name, status, + "Failed setting SO_RCVBUF"); + } else { + if (sobuf_size < turn_sock->setting.so_rcvbuf_size) { + PJ_LOG(4, (turn_sock->obj_name, + "Warning! Cannot set SO_RCVBUF as configured," + " now=%d, configured=%d", sobuf_size, + turn_sock->setting.so_rcvbuf_size)); + } else { + PJ_LOG(5, (turn_sock->obj_name, "SO_RCVBUF set to %d", + sobuf_size)); + } + } } if (turn_sock->setting.so_sndbuf_size > 0) { - unsigned sobuf_size = turn_sock->setting.so_sndbuf_size; - status = pj_sock_setsockopt_sobuf(sock, pj_SO_SNDBUF(), PJ_TRUE, - &sobuf_size); - if (status != PJ_SUCCESS) { - pj_perror(3, turn_sock->obj_name, status, - "Failed setting SO_SNDBUF"); - } else { - if (sobuf_size < turn_sock->setting.so_sndbuf_size) { - PJ_LOG(4, (turn_sock->obj_name, - "Warning! Cannot set SO_SNDBUF as configured," - " now=%d, configured=%d", sobuf_size, - turn_sock->setting.so_sndbuf_size)); - } else { - PJ_LOG(5, (turn_sock->obj_name, "SO_SNDBUF set to %d", - sobuf_size)); - } - } + unsigned sobuf_size = turn_sock->setting.so_sndbuf_size; + status = pj_sock_setsockopt_sobuf(sock, pj_SO_SNDBUF(), PJ_TRUE, + &sobuf_size); + if (status != PJ_SUCCESS) { + pj_perror(3, turn_sock->obj_name, status, + "Failed setting SO_SNDBUF"); + } else { + if (sobuf_size < turn_sock->setting.so_sndbuf_size) { + PJ_LOG(4, (turn_sock->obj_name, + "Warning! Cannot set SO_SNDBUF as configured," + " now=%d, configured=%d", sobuf_size, + turn_sock->setting.so_sndbuf_size)); + } else { + PJ_LOG(5, (turn_sock->obj_name, "SO_SNDBUF set to %d", + sobuf_size)); + } + } } /* Create active socket */ @@ -1736,102 +1735,102 @@ static void turn_on_connection_attempt(pj_turn_session *sess, asock_cb.on_data_sent = &dataconn_on_data_sent; asock_cb.on_connect_complete = &dataconn_on_connect_complete; status = pj_activesock_create(pool, sock, - pj_SOCK_STREAM(), &asock_cfg, - turn_sock->cfg.ioqueue, &asock_cb, - new_conn, &new_conn->asock); + pj_SOCK_STREAM(), &asock_cfg, + turn_sock->cfg.ioqueue, &asock_cb, + new_conn, &new_conn->asock); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Connect to TURN server for data connection */ pj_turn_session_get_info(turn_sock->sess, &info); status = pj_activesock_start_connect(new_conn->asock, - pool, - &info.server, - pj_sockaddr_get_len(&info.server)); + pool, + &info.server, + pj_sockaddr_get_len(&info.server)); if (status == PJ_SUCCESS) { - dataconn_on_connect_complete(new_conn->asock, PJ_SUCCESS); - pj_grp_lock_release(turn_sock->grp_lock); - return; + dataconn_on_connect_complete(new_conn->asock, PJ_SUCCESS); + pj_grp_lock_release(turn_sock->grp_lock); + return; } on_return: if (status == PJ_EPENDING) { - PJ_LOG(5,(pool->obj_name, - "Accepting connection from peer %s", - pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3))); + PJ_LOG(5,(pool->obj_name, + "Accepting connection from peer %s", + pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3))); } else { - /* not PJ_SUCCESS */ - pj_perror(4, pool->obj_name, status, - "Failed in accepting connection from peer %s", - pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3)); + /* not PJ_SUCCESS */ + pj_perror(4, pool->obj_name, status, + "Failed in accepting connection from peer %s", + pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3)); - if (!new_conn->asock && sock != PJ_INVALID_SOCKET) - pj_sock_close(sock); + if (!new_conn->asock && sock != PJ_INVALID_SOCKET) + pj_sock_close(sock); - dataconn_cleanup(new_conn); - --turn_sock->data_conn_cnt; + dataconn_cleanup(new_conn); + --turn_sock->data_conn_cnt; - /* Notify app for failure */ - if (turn_sock->cb.on_connection_status) { - (*turn_sock->cb.on_connection_status)(turn_sock, status, conn_id, - peer_addr, addr_len); - } + /* Notify app for failure */ + if (turn_sock->cb.on_connection_status) { + (*turn_sock->cb.on_connection_status)(turn_sock, status, conn_id, + peer_addr, addr_len); + } } pj_grp_lock_release(turn_sock->grp_lock); } static void turn_on_connection_bind_status(pj_turn_session *sess, - pj_status_t status, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len) + pj_status_t status, + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len) { pj_turn_sock *turn_sock = (pj_turn_sock*) - pj_turn_session_get_user_data(sess); + pj_turn_session_get_user_data(sess); tcp_data_conn_t *conn = NULL; unsigned i; pj_grp_lock_acquire(turn_sock->grp_lock); for (i=0; i < PJ_TURN_MAX_TCP_CONN_CNT; ++i) { - tcp_data_conn_t *c = &turn_sock->data_conn[i]; - if (c->id == conn_id && - pj_sockaddr_cmp(peer_addr, &c->peer_addr) == 0) - { - conn = c; - break; - } + tcp_data_conn_t *c = &turn_sock->data_conn[i]; + if (c->id == conn_id && + pj_sockaddr_cmp(peer_addr, &c->peer_addr) == 0) + { + conn = c; + break; + } } if (!conn) { - PJ_LOG(5,(turn_sock->pool->obj_name, - "Warning: stray connection bind event")); - pj_grp_lock_release(turn_sock->grp_lock); - return; + PJ_LOG(5,(turn_sock->pool->obj_name, + "Warning: stray connection bind event")); + pj_grp_lock_release(turn_sock->grp_lock); + return; } if (status == PJ_SUCCESS) { - conn->state = DATACONN_STATE_READY; + conn->state = DATACONN_STATE_READY; } else { - dataconn_cleanup(conn); - --turn_sock->data_conn_cnt; + dataconn_cleanup(conn); + --turn_sock->data_conn_cnt; } pj_grp_lock_release(turn_sock->grp_lock); if (turn_sock->cb.on_connection_status) { - (*turn_sock->cb.on_connection_status)(turn_sock, status, conn_id, - peer_addr, addr_len); + (*turn_sock->cb.on_connection_status)(turn_sock, status, conn_id, + peer_addr, addr_len); } } static void turn_on_connect_complete(pj_turn_session *sess, - pj_status_t status, - pj_uint32_t conn_id, - const pj_sockaddr_t *peer_addr, - unsigned addr_len) + pj_status_t status, + pj_uint32_t conn_id, + const pj_sockaddr_t *peer_addr, + unsigned addr_len) { pj_turn_sock *turn_sock = (pj_turn_sock*) - pj_turn_session_get_user_data(sess); + pj_turn_session_get_user_data(sess); pj_pool_t *pool; tcp_data_conn_t *new_conn; pj_turn_session_info info; @@ -1844,40 +1843,40 @@ static void turn_on_connect_complete(pj_turn_session *sess, unsigned i; if (turn_sock == NULL) { - /* We've been destroyed */ - return; + /* We've been destroyed */ + return; } PJ_ASSERT_ON_FAIL(turn_sock->conn_type == PJ_TURN_TP_TCP && - turn_sock->alloc_param.peer_conn_type == PJ_TURN_TP_TCP, - return); + turn_sock->alloc_param.peer_conn_type == PJ_TURN_TP_TCP, + return); PJ_LOG(5,(turn_sock->pool->obj_name, "Trying to connect to peer %s", - pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3))); + pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3))); pj_grp_lock_acquire(turn_sock->grp_lock); if (turn_sock->data_conn_cnt == PJ_TURN_MAX_TCP_CONN_CNT) { - /* Data connection has reached limit */ + /* Data connection has reached limit */ - status = PJ_ETOOMANY; - pj_perror(4, turn_sock->pool->obj_name, status, - "Failed in connect to peer %s", - pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3)); + status = PJ_ETOOMANY; + pj_perror(4, turn_sock->pool->obj_name, status, + "Failed in connect to peer %s", + pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3)); - /* Notify app for failure */ - if (turn_sock->cb.on_connection_status) { - (*turn_sock->cb.on_connection_status)(turn_sock, status, conn_id, - peer_addr, addr_len); - } + /* Notify app for failure */ + if (turn_sock->cb.on_connection_status) { + (*turn_sock->cb.on_connection_status)(turn_sock, status, conn_id, + peer_addr, addr_len); + } - pj_grp_lock_release(turn_sock->grp_lock); - return; + pj_grp_lock_release(turn_sock->grp_lock); + return; } /* Find free data connection slot */ for (i=0; i < PJ_TURN_MAX_TCP_CONN_CNT; ++i) { - if (turn_sock->data_conn[i].state == DATACONN_STATE_NULL) - break; + if (turn_sock->data_conn[i].state == DATACONN_STATE_NULL) + break; } /* Verify that a free slot is found */ @@ -1899,66 +1898,66 @@ static void turn_on_connect_complete(pj_turn_session *sess, /* Init socket */ status = pj_sock_socket(turn_sock->af, pj_SOCK_STREAM(), 0, &sock); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Bind socket */ cfg_bind_addr = &turn_sock->setting.bound_addr; max_bind_retry = MAX_BIND_RETRY; if (turn_sock->setting.port_range && - turn_sock->setting.port_range < max_bind_retry) + turn_sock->setting.port_range < max_bind_retry) { - max_bind_retry = turn_sock->setting.port_range; + max_bind_retry = turn_sock->setting.port_range; } pj_sockaddr_init(turn_sock->af, &bound_addr, NULL, 0); if (cfg_bind_addr->addr.sa_family == pj_AF_INET() || - cfg_bind_addr->addr.sa_family == pj_AF_INET6()) + cfg_bind_addr->addr.sa_family == pj_AF_INET6()) { - pj_sockaddr_cp(&bound_addr, cfg_bind_addr); + pj_sockaddr_cp(&bound_addr, cfg_bind_addr); } status = pj_sock_bind_random(sock, &bound_addr, - turn_sock->setting.port_range, - max_bind_retry); + turn_sock->setting.port_range, + max_bind_retry); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Apply socket buffer size */ if (turn_sock->setting.so_rcvbuf_size > 0) { - unsigned sobuf_size = turn_sock->setting.so_rcvbuf_size; - status = pj_sock_setsockopt_sobuf(sock, pj_SO_RCVBUF(), PJ_TRUE, - &sobuf_size); - if (status != PJ_SUCCESS) { - pj_perror(3, turn_sock->obj_name, status, - "Failed setting SO_RCVBUF"); - } else { - if (sobuf_size < turn_sock->setting.so_rcvbuf_size) { - PJ_LOG(4, (turn_sock->obj_name, - "Warning! Cannot set SO_RCVBUF as configured," - " now=%d, configured=%d", sobuf_size, - turn_sock->setting.so_rcvbuf_size)); - } else { - PJ_LOG(5, (turn_sock->obj_name, "SO_RCVBUF set to %d", - sobuf_size)); - } - } + unsigned sobuf_size = turn_sock->setting.so_rcvbuf_size; + status = pj_sock_setsockopt_sobuf(sock, pj_SO_RCVBUF(), PJ_TRUE, + &sobuf_size); + if (status != PJ_SUCCESS) { + pj_perror(3, turn_sock->obj_name, status, + "Failed setting SO_RCVBUF"); + } else { + if (sobuf_size < turn_sock->setting.so_rcvbuf_size) { + PJ_LOG(4, (turn_sock->obj_name, + "Warning! Cannot set SO_RCVBUF as configured," + " now=%d, configured=%d", sobuf_size, + turn_sock->setting.so_rcvbuf_size)); + } else { + PJ_LOG(5, (turn_sock->obj_name, "SO_RCVBUF set to %d", + sobuf_size)); + } + } } if (turn_sock->setting.so_sndbuf_size > 0) { - unsigned sobuf_size = turn_sock->setting.so_sndbuf_size; - status = pj_sock_setsockopt_sobuf(sock, pj_SO_SNDBUF(), PJ_TRUE, - &sobuf_size); - if (status != PJ_SUCCESS) { - pj_perror(3, turn_sock->obj_name, status, - "Failed setting SO_SNDBUF"); - } else { - if (sobuf_size < turn_sock->setting.so_sndbuf_size) { - PJ_LOG(4, (turn_sock->obj_name, - "Warning! Cannot set SO_SNDBUF as configured," - " now=%d, configured=%d", sobuf_size, - turn_sock->setting.so_sndbuf_size)); - } else { - PJ_LOG(5, (turn_sock->obj_name, "SO_SNDBUF set to %d", - sobuf_size)); - } - } + unsigned sobuf_size = turn_sock->setting.so_sndbuf_size; + status = pj_sock_setsockopt_sobuf(sock, pj_SO_SNDBUF(), PJ_TRUE, + &sobuf_size); + if (status != PJ_SUCCESS) { + pj_perror(3, turn_sock->obj_name, status, + "Failed setting SO_SNDBUF"); + } else { + if (sobuf_size < turn_sock->setting.so_sndbuf_size) { + PJ_LOG(4, (turn_sock->obj_name, + "Warning! Cannot set SO_SNDBUF as configured," + " now=%d, configured=%d", sobuf_size, + turn_sock->setting.so_sndbuf_size)); + } else { + PJ_LOG(5, (turn_sock->obj_name, "SO_SNDBUF set to %d", + sobuf_size)); + } + } } /* Create active socket */ @@ -1970,46 +1969,46 @@ static void turn_on_connect_complete(pj_turn_session *sess, asock_cb.on_data_sent = &dataconn_on_data_sent; asock_cb.on_connect_complete = &dataconn_on_connect_complete; status = pj_activesock_create(pool, sock, - pj_SOCK_STREAM(), &asock_cfg, - turn_sock->cfg.ioqueue, &asock_cb, - new_conn, &new_conn->asock); + pj_SOCK_STREAM(), &asock_cfg, + turn_sock->cfg.ioqueue, &asock_cb, + new_conn, &new_conn->asock); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Connect to TURN server for data connection */ pj_turn_session_get_info(turn_sock->sess, &info); status = pj_activesock_start_connect(new_conn->asock, - pool, - &info.server, - pj_sockaddr_get_len(&info.server)); + pool, + &info.server, + pj_sockaddr_get_len(&info.server)); if (status == PJ_SUCCESS) { - dataconn_on_connect_complete(new_conn->asock, PJ_SUCCESS); - pj_grp_lock_release(turn_sock->grp_lock); - return; + dataconn_on_connect_complete(new_conn->asock, PJ_SUCCESS); + pj_grp_lock_release(turn_sock->grp_lock); + return; } on_return: if (status == PJ_EPENDING) { - PJ_LOG(5,(pool->obj_name, - "Connecting to peer %s", - pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3))); + PJ_LOG(5,(pool->obj_name, + "Connecting to peer %s", + pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3))); } else { - /* not PJ_SUCCESS */ - pj_perror(4, pool->obj_name, status, - "Failed in connect to peer %s", - pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3)); - - if (!new_conn->asock && sock != PJ_INVALID_SOCKET) - pj_sock_close(sock); - - dataconn_cleanup(new_conn); - --turn_sock->data_conn_cnt; - - /* Notify app for failure */ - if (turn_sock->cb.on_connection_status) { - (*turn_sock->cb.on_connection_status)(turn_sock, status, conn_id, - peer_addr, addr_len); - } + /* not PJ_SUCCESS */ + pj_perror(4, pool->obj_name, status, + "Failed in connect to peer %s", + pj_sockaddr_print(peer_addr, addrtxt, sizeof(addrtxt), 3)); + + if (!new_conn->asock && sock != PJ_INVALID_SOCKET) + pj_sock_close(sock); + + dataconn_cleanup(new_conn); + --turn_sock->data_conn_cnt; + + /* Notify app for failure */ + if (turn_sock->cb.on_connection_status) { + (*turn_sock->cb.on_connection_status)(turn_sock, status, conn_id, + peer_addr, addr_len); + } } pj_grp_lock_release(turn_sock->grp_lock); } diff --git a/pjnath/src/pjnath/upnp.c b/pjnath/src/pjnath/upnp.c index c9050ed625..db961d26c3 100644 --- a/pjnath/src/pjnath/upnp.c +++ b/pjnath/src/pjnath/upnp.c @@ -30,7 +30,7 @@ #include #include -#define THIS_FILE "upnp.c" +#define THIS_FILE "upnp.c" #define TRACE_(...) // PJ_LOG(6, (THIS_FILE, ##__VA_ARGS__)) @@ -58,34 +58,34 @@ static const char* UPNP_WANPPP_SERVICE = /* Structure for IGD device. */ struct igd { - pj_str_t dev_id; - pj_str_t url; - pj_str_t service_type; - pj_str_t control_url; - pj_str_t public_ip; + pj_str_t dev_id; + pj_str_t url; + pj_str_t service_type; + pj_str_t control_url; + pj_str_t public_ip; pj_sockaddr public_ip_addr; - pj_bool_t valid; - pj_bool_t alive; + pj_bool_t valid; + pj_bool_t alive; }; /* UPnP manager. */ static struct upnp { - unsigned initialized; - pj_pool_t *pool; - pj_thread_desc thread_desc; - pj_thread_t *thread; - pj_mutex_t *mutex; - int search_cnt; - pj_status_t status; - - unsigned igd_cnt; - struct igd igd_devs[20]; - int primary_igd_idx; - - UpnpClient_Handle client_hnd; - void (*upnp_cb)(pj_status_t status); + unsigned initialized; + pj_pool_t *pool; + pj_thread_desc thread_desc; + pj_thread_t *thread; + pj_mutex_t *mutex; + int search_cnt; + pj_status_t status; + + unsigned igd_cnt; + struct igd igd_devs[20]; + int primary_igd_idx; + + UpnpClient_Handle client_hnd; + void (*upnp_cb)(pj_status_t status); } upnp_mgr; @@ -134,7 +134,7 @@ static const char * check_error_response(IXML_Document *doc) const char *error_desc = doc_get_elmt_value(doc, "errorDescription"); PJ_LOG(3, (THIS_FILE, "Response error code: %s (%s)", - error_code, error_desc)); + error_code, error_desc)); } return error_code; @@ -152,7 +152,7 @@ static const char *action_get_external_ip(struct igd *igd) /* Create action XML. */ action = UpnpMakeAction(action_name, igd->service_type.ptr, 0, NULL); if (!action) { - PJ_LOG(3, (THIS_FILE, "Failed to make GetExternalIPAddress action")); + PJ_LOG(3, (THIS_FILE, "Failed to make GetExternalIPAddress action")); return NULL; } @@ -161,7 +161,7 @@ static const char *action_get_external_ip(struct igd *igd) igd->service_type.ptr, NULL, action, &response); if (upnp_err != UPNP_E_SUCCESS || !response) { PJ_LOG(3, (THIS_FILE, "Failed to send GetExternalIPAddress action: %s", - UpnpGetErrorMessage(upnp_err))); + UpnpGetErrorMessage(upnp_err))); goto on_error; } @@ -176,7 +176,7 @@ static const char *action_get_external_ip(struct igd *igd) } pj_strdup2_with_null(upnp_mgr.pool, &igd->public_ip, public_ip); pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &igd->public_ip, - &igd->public_ip_addr); + &igd->public_ip_addr); public_ip = igd->public_ip.ptr; on_error: @@ -205,7 +205,7 @@ static void download_igd_xml(unsigned dev_idx) upnp_err = UpnpDownloadXmlDoc(url, &doc); if (upnp_err != UPNP_E_SUCCESS || !doc) { PJ_LOG(3, (THIS_FILE, "Error downloading device XML doc from %s: %s", - url, UpnpGetErrorMessage(upnp_err))); + url, UpnpGetErrorMessage(upnp_err))); goto on_error; } @@ -220,7 +220,7 @@ static void download_igd_xml(unsigned dev_idx) /* Get friendly name. */ friendly_name = doc_get_elmt_value(doc, "friendlyName"); if (!friendly_name) - friendly_name = ""; + friendly_name = ""; /* Get base URL. */ base_url = doc_get_elmt_value(doc, "URLBase"); @@ -262,37 +262,37 @@ static void download_igd_xml(unsigned dev_idx) upnp_err = UpnpResolveURL2(base_url, control_url, &abs_control_url); if (upnp_err == UPNP_E_SUCCESS) { pj_strdup2_with_null(upnp_mgr.pool, &igd_dev->control_url, - abs_control_url); + abs_control_url); free(abs_control_url); } else { PJ_LOG(4, (THIS_FILE, "Error resolving absolute controlURL: %s", - UpnpGetErrorMessage(upnp_err))); + UpnpGetErrorMessage(upnp_err))); pj_strdup2_with_null(upnp_mgr.pool, &igd_dev->control_url, - control_url); + control_url); } pj_strdup2_with_null(upnp_mgr.pool, &igd_dev->service_type, service_type); - /* Get the public IP of the IGD. */ - public_ip = action_get_external_ip(igd_dev); - if (!public_ip) - break; + /* Get the public IP of the IGD. */ + public_ip = action_get_external_ip(igd_dev); + if (!public_ip) + break; /* We find a valid IGD. */ igd_dev->valid = PJ_TRUE; igd_dev->alive = PJ_TRUE; PJ_LOG(4, (THIS_FILE, "Valid IGD:\n" - "\tUDN : %s\n" - "\tName : %s\n" - "\tService Type : %s\n" - "\tControl URL : %s\n" - "\tPublic IP : %s", - igd_dev->dev_id.ptr, - friendly_name, - igd_dev->service_type.ptr, - igd_dev->control_url.ptr, - public_ip)); + "\tUDN : %s\n" + "\tName : %s\n" + "\tService Type : %s\n" + "\tControl URL : %s\n" + "\tPublic IP : %s", + igd_dev->dev_id.ptr, + friendly_name, + igd_dev->service_type.ptr, + igd_dev->control_url.ptr, + public_ip)); /* Use this as primary IGD if we haven't had one. */ pj_mutex_lock(upnp_mgr.mutex); @@ -314,7 +314,7 @@ static void download_igd_xml(unsigned dev_idx) if (service_list) ixmlNodeList_free(service_list); if (doc) - ixmlDocument_free(doc); + ixmlDocument_free(doc); } /* Add a newly discovered IGD. */ @@ -323,25 +323,25 @@ static void add_device(const char *dev_id, const char *url) unsigned i; if (upnp_mgr.igd_cnt >= MAX_DEVS) { - PJ_LOG(3, (THIS_FILE, "Warning: Too many UPnP devices discovered")); - return; + PJ_LOG(3, (THIS_FILE, "Warning: Too many UPnP devices discovered")); + return; } pj_mutex_lock(upnp_mgr.mutex); for (i = 0; i < upnp_mgr.igd_cnt; i++) { - if (!pj_strcmp2(&upnp_mgr.igd_devs[i].dev_id, dev_id) && - !pj_strcmp2(&upnp_mgr.igd_devs[i].url, url)) - { - /* Device exists. */ - pj_mutex_unlock(upnp_mgr.mutex); - return; - } + if (!pj_strcmp2(&upnp_mgr.igd_devs[i].dev_id, dev_id) && + !pj_strcmp2(&upnp_mgr.igd_devs[i].url, url)) + { + /* Device exists. */ + pj_mutex_unlock(upnp_mgr.mutex); + return; + } } pj_strdup2_with_null(upnp_mgr.pool, - &upnp_mgr.igd_devs[upnp_mgr.igd_cnt].dev_id, dev_id); + &upnp_mgr.igd_devs[upnp_mgr.igd_cnt].dev_id, dev_id); pj_strdup2_with_null(upnp_mgr.pool, - &upnp_mgr.igd_devs[upnp_mgr.igd_cnt++].url, url); + &upnp_mgr.igd_devs[upnp_mgr.igd_cnt++].url, url); pj_mutex_unlock(upnp_mgr.mutex); PJ_LOG(4, (THIS_FILE, "Discovered a new IGD %s, url: %s", dev_id, url)); @@ -356,22 +356,22 @@ static void set_device_online(const char *dev_id) unsigned i; for (i = 0; i < upnp_mgr.igd_cnt; i++) { - struct igd *igd = &upnp_mgr.igd_devs[i]; - - /* We are only interested in valid IGDs that we can use. */ - if (!pj_strcmp2(&igd->dev_id, dev_id) && igd->valid) { - igd->alive = PJ_TRUE; - - if (upnp_mgr.primary_igd_idx < 0) { - /* If we don't have a primary IGD, use this. */ - pj_mutex_lock(upnp_mgr.mutex); - upnp_mgr.primary_igd_idx = i; - pj_mutex_unlock(upnp_mgr.mutex); - - PJ_LOG(4, (THIS_FILE, "Using primary IGD %s", - upnp_mgr.igd_devs[i].dev_id.ptr)); - } - } + struct igd *igd = &upnp_mgr.igd_devs[i]; + + /* We are only interested in valid IGDs that we can use. */ + if (!pj_strcmp2(&igd->dev_id, dev_id) && igd->valid) { + igd->alive = PJ_TRUE; + + if (upnp_mgr.primary_igd_idx < 0) { + /* If we don't have a primary IGD, use this. */ + pj_mutex_lock(upnp_mgr.mutex); + upnp_mgr.primary_igd_idx = i; + pj_mutex_unlock(upnp_mgr.mutex); + + PJ_LOG(4, (THIS_FILE, "Using primary IGD %s", + upnp_mgr.igd_devs[i].dev_id.ptr)); + } + } } } @@ -381,39 +381,39 @@ static void set_device_offline(const char *dev_id) int i; for (i = 0; i < (int)upnp_mgr.igd_cnt; i++) { - struct igd *igd = &upnp_mgr.igd_devs[i]; + struct igd *igd = &upnp_mgr.igd_devs[i]; - /* We are only interested in valid IGDs that we can use. */ - if (!pj_strcmp2(&igd->dev_id, dev_id) && igd->valid) { - igd->alive = PJ_FALSE; + /* We are only interested in valid IGDs that we can use. */ + if (!pj_strcmp2(&igd->dev_id, dev_id) && igd->valid) { + igd->alive = PJ_FALSE; - pj_mutex_lock(upnp_mgr.mutex); - if (i == upnp_mgr.primary_igd_idx) { - unsigned j; - - /* The primary IGD is offline, try to find another one. */ - upnp_mgr.primary_igd_idx = -1; - for (j = 0; j < upnp_mgr.igd_cnt; j++) { - igd = &upnp_mgr.igd_devs[j]; - if (igd->valid && igd->alive) { - upnp_mgr.primary_igd_idx = j; - break; - } - } - - PJ_LOG(4, (THIS_FILE, "Device %s offline, now using IGD %s", - upnp_mgr.igd_devs[i].dev_id.ptr, - (upnp_mgr.primary_igd_idx < 0? "(none)": - igd->dev_id.ptr))); - } - pj_mutex_unlock(upnp_mgr.mutex); - } + pj_mutex_lock(upnp_mgr.mutex); + if (i == upnp_mgr.primary_igd_idx) { + unsigned j; + + /* The primary IGD is offline, try to find another one. */ + upnp_mgr.primary_igd_idx = -1; + for (j = 0; j < upnp_mgr.igd_cnt; j++) { + igd = &upnp_mgr.igd_devs[j]; + if (igd->valid && igd->alive) { + upnp_mgr.primary_igd_idx = j; + break; + } + } + + PJ_LOG(4, (THIS_FILE, "Device %s offline, now using IGD %s", + upnp_mgr.igd_devs[i].dev_id.ptr, + (upnp_mgr.primary_igd_idx < 0? "(none)": + igd->dev_id.ptr))); + } + pj_mutex_unlock(upnp_mgr.mutex); + } } } /* UPnP client callback. */ static int client_cb(Upnp_EventType event_type, const void *event, - void * user_data) + void * user_data) { /* Ignore if already uninitialized or incorrect user data. */ if (!upnp_mgr.initialized || user_data != &upnp_mgr) @@ -422,7 +422,7 @@ static int client_cb(Upnp_EventType event_type, const void *event, if (!pj_thread_is_registered()) { pj_bzero(upnp_mgr.thread_desc, sizeof(pj_thread_desc)); pj_thread_register("upnp_cb", upnp_mgr.thread_desc, - &upnp_mgr.thread); + &upnp_mgr.thread); } switch (event_type) { @@ -434,7 +434,7 @@ static int client_cb(Upnp_EventType event_type, const void *event, if (upnp_status != UPNP_E_SUCCESS) { PJ_LOG(4, (THIS_FILE, "UPnP discovery error: %s", - UpnpGetErrorMessage(upnp_status))); + UpnpGetErrorMessage(upnp_status))); break; } @@ -448,7 +448,7 @@ static int client_cb(Upnp_EventType event_type, const void *event, { const UpnpDiscovery* d_event = (const UpnpDiscovery*) event; set_device_online(UpnpDiscovery_get_DeviceID_cstr(d_event)); - break; + break; } case UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE: @@ -460,18 +460,18 @@ static int client_cb(Upnp_EventType event_type, const void *event, case UPNP_DISCOVERY_SEARCH_TIMEOUT: { - pj_bool_t call_cb = PJ_FALSE; - - pj_mutex_lock(upnp_mgr.mutex); - if (upnp_mgr.search_cnt > 0) { - --upnp_mgr.search_cnt; - if (upnp_mgr.search_cnt == 0 && upnp_mgr.primary_igd_idx < 0) { - PJ_LOG(4,(THIS_FILE, "Search timed out, no valid IGD found")); - call_cb = PJ_TRUE; + pj_bool_t call_cb = PJ_FALSE; + + pj_mutex_lock(upnp_mgr.mutex); + if (upnp_mgr.search_cnt > 0) { + --upnp_mgr.search_cnt; + if (upnp_mgr.search_cnt == 0 && upnp_mgr.primary_igd_idx < 0) { + PJ_LOG(4,(THIS_FILE, "Search timed out, no valid IGD found")); + call_cb = PJ_TRUE; upnp_mgr.status = PJ_ENOTFOUND; - } - } - pj_mutex_unlock(upnp_mgr.mutex); + } + } + pj_mutex_unlock(upnp_mgr.mutex); if (call_cb && upnp_mgr.upnp_cb) { (*upnp_mgr.upnp_cb)(upnp_mgr.status); @@ -481,7 +481,7 @@ static int client_cb(Upnp_EventType event_type, const void *event, } case UPNP_CONTROL_ACTION_COMPLETE: { - int err_code; + int err_code; IXML_Document *response = NULL; const UpnpActionComplete* a_event = (const UpnpActionComplete *) event; if (!a_event) @@ -493,18 +493,18 @@ static int client_cb(Upnp_EventType event_type, const void *event, err_code = UpnpActionComplete_get_ErrCode(a_event); if (err_code != UPNP_E_SUCCESS) { PJ_LOG(4, (THIS_FILE, "Port mapping deletion action complete " - "error: %d (%s)", err_code, - UpnpGetErrorMessage(err_code))); + "error: %d (%s)", err_code, + UpnpGetErrorMessage(err_code))); break; } response = UpnpActionComplete_get_ActionResult(a_event); if (!response) { PJ_LOG(4, (THIS_FILE, "Failed to get response to delete port " - "mapping")); + "mapping")); } else { if (!check_error_response(response)) { - PJ_LOG(4, (THIS_FILE, "Successfully deleted port mapping")); + PJ_LOG(4, (THIS_FILE, "Successfully deleted port mapping")); } ixmlDocument_free(response); } @@ -527,31 +527,31 @@ static void search_igd(int search_time) upnp_mgr.search_cnt = 4; err = UpnpSearchAsync(upnp_mgr.client_hnd, search_time, - UPNP_ROOT_DEVICE, &upnp_mgr); + UPNP_ROOT_DEVICE, &upnp_mgr); if (err != UPNP_E_SUCCESS) { PJ_LOG(4, (THIS_FILE, "Searching for UPNP_ROOT_DEVICE failed: %s", - UpnpGetErrorMessage(err))); + UpnpGetErrorMessage(err))); } err = UpnpSearchAsync(upnp_mgr.client_hnd, search_time, - UPNP_IGD_DEVICE, &upnp_mgr); + UPNP_IGD_DEVICE, &upnp_mgr); if (err != UPNP_E_SUCCESS) { PJ_LOG(4, (THIS_FILE, "Searching for UPNP_IGD_DEVICE failed: %s", - UpnpGetErrorMessage(err))); + UpnpGetErrorMessage(err))); } err = UpnpSearchAsync(upnp_mgr.client_hnd, search_time, - UPNP_WANIP_SERVICE, &upnp_mgr); + UPNP_WANIP_SERVICE, &upnp_mgr); if (err != UPNP_E_SUCCESS) { PJ_LOG(4, (THIS_FILE, "Searching for UPNP_WANIP_SERVICE failed: %s", - UpnpGetErrorMessage(err))); + UpnpGetErrorMessage(err))); } err = UpnpSearchAsync(upnp_mgr.client_hnd, search_time, - UPNP_WANPPP_SERVICE, &upnp_mgr); + UPNP_WANPPP_SERVICE, &upnp_mgr); if (err != UPNP_E_SUCCESS) { PJ_LOG(4, (THIS_FILE, "Searching for UPNP_WANPPP_SERVICE failed: %s", - UpnpGetErrorMessage(err))); + UpnpGetErrorMessage(err))); } } @@ -565,15 +565,15 @@ PJ_DEF(pj_status_t) pj_upnp_init(const pj_upnp_init_param *param) unsigned short port6 = 0; if (upnp_mgr.initialized) - return PJ_SUCCESS; + return PJ_SUCCESS; #if ENABLE_LOG UpnpSetLogLevel(UPNP_ALL); UpnpSetLogFileNames("upnp.log", NULL); upnp_err = UpnpInitLog(); if (upnp_err != UPNP_E_SUCCESS) { - PJ_LOG(4, (THIS_FILE, "Failed to initialize UPnP log: %s", - UpnpGetErrorMessage(upnp_err))); + PJ_LOG(4, (THIS_FILE, "Failed to initialize UPnP log: %s", + UpnpGetErrorMessage(upnp_err))); } #endif @@ -581,9 +581,9 @@ PJ_DEF(pj_status_t) pj_upnp_init(const pj_upnp_init_param *param) upnp_err = UpnpInit2(param->if_name, (unsigned short)param->port); if (upnp_err != UPNP_E_SUCCESS) { PJ_LOG(1, (THIS_FILE, "Failed to initialize libupnp with " - "interface %s: %s", - (param->if_name? param->if_name: "NULL"), - UpnpGetErrorMessage(upnp_err))); + "interface %s: %s", + (param->if_name? param->if_name: "NULL"), + UpnpGetErrorMessage(upnp_err))); return PJ_EUNKNOWN; } @@ -591,7 +591,7 @@ PJ_DEF(pj_status_t) pj_upnp_init(const pj_upnp_init_param *param) upnp_err = UpnpRegisterClient(client_cb, &upnp_mgr, &upnp_mgr.client_hnd); if (upnp_err != UPNP_E_SUCCESS) { PJ_LOG(1, (THIS_FILE, "Failed to register client: %s", - UpnpGetErrorMessage(upnp_err))); + UpnpGetErrorMessage(upnp_err))); UpnpFinish(); return PJ_EINVALIDOP; } @@ -625,12 +625,12 @@ PJ_DEF(pj_status_t) pj_upnp_init(const pj_upnp_init_param *param) #endif if (param->if_name) { PJ_LOG(4, (THIS_FILE, "UPnP initialized with interface %s", - param->if_name)); + param->if_name)); } if (ip_address6 && port6) { PJ_LOG(4, (THIS_FILE, "UPnP initialized on %s:%u (IPv4) and " - "%s:%u (IPv6)", ip_address, port, - ip_address6, port6)); + "%s:%u (IPv6)", ip_address, port, + ip_address6, port6)); } else { PJ_LOG(4, (THIS_FILE, "UPnP initialized on %s:%u", ip_address, port)); } @@ -638,7 +638,7 @@ PJ_DEF(pj_status_t) pj_upnp_init(const pj_upnp_init_param *param) /* Search for Internet Gateway Devices. */ upnp_mgr.status = PJ_EPENDING; search_igd(param->search_time > 0? param->search_time: - PJ_UPNP_DEFAULT_SEARCH_TIME); + PJ_UPNP_DEFAULT_SEARCH_TIME); return PJ_SUCCESS; } @@ -654,10 +654,10 @@ PJ_DEF(pj_status_t) pj_upnp_deinit(void) UpnpFinish(); if (upnp_mgr.mutex) - pj_mutex_destroy(upnp_mgr.mutex); + pj_mutex_destroy(upnp_mgr.mutex); if (upnp_mgr.pool) - pj_pool_release(upnp_mgr.pool); + pj_pool_release(upnp_mgr.pool); pj_bzero(&upnp_mgr, sizeof(upnp_mgr)); upnp_mgr.primary_igd_idx = -1; @@ -670,9 +670,9 @@ PJ_DEF(pj_status_t) pj_upnp_deinit(void) /* Send request to add port mapping. */ PJ_DECL(pj_status_t)pj_upnp_add_port_mapping(unsigned sock_cnt, - const pj_sock_t sock[], - unsigned ext_port[], - pj_sockaddr mapped_addr[]) + const pj_sock_t sock[], + unsigned ext_port[], + pj_sockaddr mapped_addr[]) { unsigned max_wait = 20; unsigned i; @@ -680,22 +680,22 @@ PJ_DECL(pj_status_t)pj_upnp_add_port_mapping(unsigned sock_cnt, pj_status_t status = PJ_SUCCESS; if (!upnp_mgr.initialized) { - PJ_LOG(3, (THIS_FILE, "UPnP not initialized yet")); + PJ_LOG(3, (THIS_FILE, "UPnP not initialized yet")); return PJ_EINVALIDOP; } /* If IGD search hasn't completed, wait momentarily. */ while (upnp_mgr.status == PJ_EPENDING && max_wait > 0) { - pj_thread_sleep(100); - max_wait--; + pj_thread_sleep(100); + max_wait--; } /* Need to lock in case the device becomes offline at the same time. */ pj_mutex_lock(upnp_mgr.mutex); if (upnp_mgr.primary_igd_idx < 0) { - PJ_LOG(3, (THIS_FILE, "No valid IGD")); + PJ_LOG(3, (THIS_FILE, "No valid IGD")); pj_mutex_unlock(upnp_mgr.mutex); - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; } igd = &upnp_mgr.igd_devs[upnp_mgr.primary_igd_idx]; @@ -707,98 +707,98 @@ PJ_DECL(pj_status_t)pj_upnp_add_port_mapping(unsigned sock_cnt, int upnp_err; IXML_Document *action = NULL; IXML_Document *response = NULL; - char int_port_buf[10], ext_port_buf[10]; - char addr_buf[PJ_INET6_ADDRSTRLEN]; - unsigned int_port; - pj_sockaddr bound_addr; - int namelen = sizeof(pj_sockaddr); - const char *pext_port = (ext_port? ext_port_buf: int_port_buf); - - /* Get socket's bound address. */ - status = pj_sock_getsockname(sock[i], &bound_addr, &namelen); - if (status != PJ_SUCCESS) { - PJ_LOG(3, (THIS_FILE, "getsockname() error")); - goto on_error; - } - - if (!pj_sockaddr_has_addr(&bound_addr)) { - pj_sockaddr addr; - - /* Get local IP address. */ - status = pj_gethostip(bound_addr.addr.sa_family, &addr); - if (status != PJ_SUCCESS) - goto on_error; - - pj_sockaddr_copy_addr(&bound_addr, &addr); - } - - pj_sockaddr_print(&bound_addr, addr_buf, sizeof(addr_buf), 0); - int_port = pj_sockaddr_get_port(&bound_addr); - pj_utoa(int_port, int_port_buf); - if (ext_port) - pj_utoa(ext_port[i], ext_port_buf); + char int_port_buf[10], ext_port_buf[10]; + char addr_buf[PJ_INET6_ADDRSTRLEN]; + unsigned int_port; + pj_sockaddr bound_addr; + int namelen = sizeof(pj_sockaddr); + const char *pext_port = (ext_port? ext_port_buf: int_port_buf); + + /* Get socket's bound address. */ + status = pj_sock_getsockname(sock[i], &bound_addr, &namelen); + if (status != PJ_SUCCESS) { + PJ_LOG(3, (THIS_FILE, "getsockname() error")); + goto on_error; + } + + if (!pj_sockaddr_has_addr(&bound_addr)) { + pj_sockaddr addr; + + /* Get local IP address. */ + status = pj_gethostip(bound_addr.addr.sa_family, &addr); + if (status != PJ_SUCCESS) + goto on_error; + + pj_sockaddr_copy_addr(&bound_addr, &addr); + } + + pj_sockaddr_print(&bound_addr, addr_buf, sizeof(addr_buf), 0); + int_port = pj_sockaddr_get_port(&bound_addr); + pj_utoa(int_port, int_port_buf); + if (ext_port) + pj_utoa(ext_port[i], ext_port_buf); /* Create action XML. */ UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, - igd->service_type.ptr, "NewRemoteHost", ""); - UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, - igd->service_type.ptr, "NewExternalPort", pext_port); - UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, - igd->service_type.ptr, "NewProtocol", "UDP"); - UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, - igd->service_type.ptr, "NewInternalPort",int_port_buf); + igd->service_type.ptr, "NewRemoteHost", ""); + UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, + igd->service_type.ptr, "NewExternalPort", pext_port); + UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, + igd->service_type.ptr, "NewProtocol", "UDP"); + UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, + igd->service_type.ptr, "NewInternalPort",int_port_buf); + UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, + igd->service_type.ptr, "NewInternalClient", addr_buf); + UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, + igd->service_type.ptr, "NewEnabled", "1"); + UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, + igd->service_type.ptr, + "NewPortMappingDescription", PORT_MAPPING_DESCRIPTION); UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, - igd->service_type.ptr, "NewInternalClient", addr_buf); - UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, - igd->service_type.ptr, "NewEnabled", "1"); - UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, - igd->service_type.ptr, - "NewPortMappingDescription", PORT_MAPPING_DESCRIPTION); - UpnpAddToAction(&action, ACTION_ADD_PORT_MAPPING, - igd->service_type.ptr, "NewLeaseDuration","0"); - - /* Send the action XML. */ - upnp_err = UpnpSendAction(upnp_mgr.client_hnd, igd->control_url.ptr, - igd->service_type.ptr, NULL, action, - &response); - if (upnp_err != UPNP_E_SUCCESS || !response) { + igd->service_type.ptr, "NewLeaseDuration","0"); + + /* Send the action XML. */ + upnp_err = UpnpSendAction(upnp_mgr.client_hnd, igd->control_url.ptr, + igd->service_type.ptr, NULL, action, + &response); + if (upnp_err != UPNP_E_SUCCESS || !response) { PJ_LOG(3, (THIS_FILE, "Failed to %s IGD %s to add port mapping " - "for %s:%s -> %s:%s: %d (%s)", - response? "send action to": - "get response from", - igd->dev_id.ptr, - igd->public_ip.ptr, pext_port, - addr_buf, int_port_buf, upnp_err, - UpnpGetErrorMessage(upnp_err))); + "for %s:%s -> %s:%s: %d (%s)", + response? "send action to": + "get response from", + igd->dev_id.ptr, + igd->public_ip.ptr, pext_port, + addr_buf, int_port_buf, upnp_err, + UpnpGetErrorMessage(upnp_err))); status = PJ_ETIMEDOUT; } - TRACE_("Add port mapping XML action:\n%s", - ixmlPrintDocument(action)); - TRACE_("Add port mapping XML response:\n%s", - (response? ixmlPrintDocument(response): "empty")); + TRACE_("Add port mapping XML action:\n%s", + ixmlPrintDocument(action)); + TRACE_("Add port mapping XML response:\n%s", + (response? ixmlPrintDocument(response): "empty")); if (response && check_error_response(response)) { /* The error detail will be printed by check_error_response(). */ status = PJ_EINVALIDOP; } - ixmlDocument_free(action); - if (response) ixmlDocument_free(response); - + ixmlDocument_free(action); + if (response) ixmlDocument_free(response); + pj_sockaddr_cp(&mapped_addr[i], &bound_addr); pj_sockaddr_set_str_addr(bound_addr.addr.sa_family, - &mapped_addr[i], &igd->public_ip); + &mapped_addr[i], &igd->public_ip); pj_sockaddr_set_port(&mapped_addr[i], - (pj_uint16_t)(ext_port? ext_port[i]: int_port)); + (pj_uint16_t)(ext_port? ext_port[i]: int_port)); - if (status != PJ_SUCCESS) - goto on_error; + if (status != PJ_SUCCESS) + goto on_error; PJ_LOG(4, (THIS_FILE, "Successfully add port mapping to IGD %s: " - "%s:%s -> %s:%s", igd->dev_id.ptr, - igd->public_ip.ptr, pext_port, - addr_buf, int_port_buf)); + "%s:%s -> %s:%s", igd->dev_id.ptr, + igd->public_ip.ptr, pext_port, + addr_buf, int_port_buf)); } return PJ_SUCCESS; @@ -808,7 +808,7 @@ PJ_DECL(pj_status_t)pj_upnp_add_port_mapping(unsigned sock_cnt, * the previous port mappings. */ while (i > 0) { - pj_upnp_del_port_mapping(&mapped_addr[--i]); + pj_upnp_del_port_mapping(&mapped_addr[--i]); } return status; @@ -828,14 +828,14 @@ PJ_DEF(pj_status_t)pj_upnp_del_port_mapping(const pj_sockaddr *mapped_addr) char ext_port_buf[10]; if (!upnp_mgr.initialized) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; /* Need to lock in case the device becomes offline at the same time. */ pj_mutex_lock(upnp_mgr.mutex); if (upnp_mgr.primary_igd_idx < 0) { - PJ_LOG(3, (THIS_FILE, "No valid IGD")); + PJ_LOG(3, (THIS_FILE, "No valid IGD")); pj_mutex_unlock(upnp_mgr.mutex); - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; } igd = &upnp_mgr.igd_devs[upnp_mgr.primary_igd_idx]; @@ -845,35 +845,35 @@ PJ_DEF(pj_status_t)pj_upnp_del_port_mapping(const pj_sockaddr *mapped_addr) pj_sockaddr_cp(&host_addr, mapped_addr); pj_sockaddr_set_port(&host_addr, 0); if (pj_sockaddr_cmp(&igd->public_ip_addr, &host_addr)) { - unsigned i; - - /* The primary IGD's public IP is different. Find the IGD - * that matches the mapped address. - */ - igd = NULL; - for (i = 0; i < upnp_mgr.igd_cnt; i++, igd = NULL) { - igd = &upnp_mgr.igd_devs[i]; - if (igd->valid && igd->alive && - !pj_sockaddr_cmp(&igd->public_ip_addr, &host_addr)) - { - break; - } - } + unsigned i; + + /* The primary IGD's public IP is different. Find the IGD + * that matches the mapped address. + */ + igd = NULL; + for (i = 0; i < upnp_mgr.igd_cnt; i++, igd = NULL) { + igd = &upnp_mgr.igd_devs[i]; + if (igd->valid && igd->alive && + !pj_sockaddr_cmp(&igd->public_ip_addr, &host_addr)) + { + break; + } + } } if (!igd) { - /* Either the IGD we previously requested to add port mapping has become - * offline, or the address is actually not a valid. - */ - PJ_LOG(3, (THIS_FILE, "The IGD is offline or invalid mapped address")); - return PJ_EGONE; + /* Either the IGD we previously requested to add port mapping has become + * offline, or the address is actually not a valid. + */ + PJ_LOG(3, (THIS_FILE, "The IGD is offline or invalid mapped address")); + return PJ_EGONE; } ext_port = pj_sockaddr_get_port(mapped_addr); if (ext_port == 0) { - /* Deleting port zero should be harmless, but it's a waste of time. */ - PJ_LOG(3, (THIS_FILE, "Invalid port number to be deleted")); - return PJ_EINVALIDOP; + /* Deleting port zero should be harmless, but it's a waste of time. */ + PJ_LOG(3, (THIS_FILE, "Invalid port number to be deleted")); + return PJ_EINVALIDOP; } pj_utoa(ext_port, ext_port_buf); @@ -893,15 +893,15 @@ PJ_DEF(pj_status_t)pj_upnp_del_port_mapping(const pj_sockaddr *mapped_addr) client_cb, &upnp_mgr); if (upnp_err == UPNP_E_SUCCESS) { PJ_LOG(4, (THIS_FILE, "Successfully sending async action to " - "delete port mapping to IGD %s for " - "%s:%s", igd->dev_id.ptr, - igd->public_ip.ptr, ext_port_buf)); + "delete port mapping to IGD %s for " + "%s:%s", igd->dev_id.ptr, + igd->public_ip.ptr, ext_port_buf)); } else { PJ_LOG(3, (THIS_FILE, "Failed to send action to IGD %s to delete " - "port mapping for %s:%s: %d (%s)", - igd->dev_id.ptr, igd->public_ip.ptr, - ext_port_buf, upnp_err, - UpnpGetErrorMessage(upnp_err))); + "port mapping for %s:%s: %d (%s)", + igd->dev_id.ptr, igd->public_ip.ptr, + ext_port_buf, upnp_err, + UpnpGetErrorMessage(upnp_err))); status = PJ_EINVALIDOP; } diff --git a/pjnath/src/pjturn-client/client_main.c b/pjnath/src/pjturn-client/client_main.c index 6f9f1ff1aa..90dbbc1242 100644 --- a/pjnath/src/pjturn-client/client_main.c +++ b/pjnath/src/pjturn-client/client_main.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -22,71 +21,71 @@ #include -#define THIS_FILE "client_main.c" -#define LOCAL_PORT 1998 -#define BANDWIDTH 64 /* -1 to disable */ -#define LIFETIME 600 /* -1 to disable */ -#define REQ_TRANSPORT -1 /* 0: udp, 1: tcp, -1: disable */ -#define REQ_PORT_PROPS -1 /* -1 to disable */ -#define REQ_IP 0 /* IP address string */ +#define THIS_FILE "client_main.c" +#define LOCAL_PORT 1998 +#define BANDWIDTH 64 /* -1 to disable */ +#define LIFETIME 600 /* -1 to disable */ +#define REQ_TRANSPORT -1 /* 0: udp, 1: tcp, -1: disable */ +#define REQ_PORT_PROPS -1 /* -1 to disable */ +#define REQ_IP 0 /* IP address string */ -//#define OPTIONS PJ_STUN_NO_AUTHENTICATE -#define OPTIONS 0 +//#define OPTIONS PJ_STUN_NO_AUTHENTICATE +#define OPTIONS 0 struct peer { pj_stun_sock *stun_sock; - pj_sockaddr mapped_addr; + pj_sockaddr mapped_addr; }; static struct global { - pj_caching_pool cp; - pj_pool_t *pool; - pj_stun_config stun_config; - pj_thread_t *thread; - pj_bool_t quit; + pj_caching_pool cp; + pj_pool_t *pool; + pj_stun_config stun_config; + pj_thread_t *thread; + pj_bool_t quit; - pj_dns_resolver *resolver; + pj_dns_resolver *resolver; - pj_turn_sock *relay; - pj_sockaddr relay_addr; + pj_turn_sock *relay; + pj_sockaddr relay_addr; - struct peer peer[2]; + struct peer peer[2]; } g; static struct options { - pj_bool_t use_tcp; - char *srv_addr; - char *srv_port; - char *realm; - char *user_name; - char *password; - pj_bool_t use_fingerprint; - char *stun_server; - char *nameserver; + pj_bool_t use_tcp; + char *srv_addr; + char *srv_port; + char *realm; + char *user_name; + char *password; + pj_bool_t use_fingerprint; + char *stun_server; + char *nameserver; } o; static int worker_thread(void *unused); static void turn_on_rx_data(pj_turn_sock *relay, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *peer_addr, - unsigned addr_len); + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *peer_addr, + unsigned addr_len); static void turn_on_state(pj_turn_sock *relay, pj_turn_state_t old_state, - pj_turn_state_t new_state); + pj_turn_state_t new_state); static pj_bool_t stun_sock_on_status(pj_stun_sock *stun_sock, - pj_stun_sock_op op, - pj_status_t status); + pj_stun_sock_op op, + pj_status_t status); static pj_bool_t stun_sock_on_rx_data(pj_stun_sock *stun_sock, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *src_addr, - unsigned addr_len); + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *src_addr, + unsigned addr_len); static void my_perror(const char *title, pj_status_t status) @@ -97,11 +96,11 @@ static void my_perror(const char *title, pj_status_t status) PJ_LOG(3,(THIS_FILE, "%s: %s", title, errmsg)); } -#define CHECK(expr) status=expr; \ - if (status!=PJ_SUCCESS) { \ - my_perror(#expr, status); \ - return status; \ - } +#define CHECK(expr) status=expr; \ + if (status!=PJ_SUCCESS) { \ + my_perror(#expr, status); \ + return status; \ + } static int init() { @@ -114,8 +113,8 @@ static int init() /* Check that server is specified */ if (!o.srv_addr) { - printf("Error: server must be specified\n"); - return PJ_EINVAL; + printf("Error: server must be specified\n"); + return PJ_EINVAL; } pj_caching_pool_init(&g.cp, &pj_pool_factory_default_policy, 0); @@ -135,46 +134,46 @@ static int init() * Create peers */ for (i=0; i<(int)PJ_ARRAY_SIZE(g.peer); ++i) { - pj_stun_sock_cb stun_sock_cb; - char name[] = "peer0"; - pj_uint16_t port; - pj_stun_sock_cfg ss_cfg; - pj_str_t server; + pj_stun_sock_cb stun_sock_cb; + char name[] = "peer0"; + pj_uint16_t port; + pj_stun_sock_cfg ss_cfg; + pj_str_t server; - pj_bzero(&stun_sock_cb, sizeof(stun_sock_cb)); - stun_sock_cb.on_rx_data = &stun_sock_on_rx_data; - stun_sock_cb.on_status = &stun_sock_on_status; + pj_bzero(&stun_sock_cb, sizeof(stun_sock_cb)); + stun_sock_cb.on_rx_data = &stun_sock_on_rx_data; + stun_sock_cb.on_status = &stun_sock_on_status; - g.peer[i].mapped_addr.addr.sa_family = pj_AF_INET(); + g.peer[i].mapped_addr.addr.sa_family = pj_AF_INET(); - pj_stun_sock_cfg_default(&ss_cfg); + pj_stun_sock_cfg_default(&ss_cfg); #if 1 - /* make reading the log easier */ - ss_cfg.ka_interval = 300; + /* make reading the log easier */ + ss_cfg.ka_interval = 300; #endif - name[strlen(name)-1] = '0'+i; - status = pj_stun_sock_create(&g.stun_config, name, pj_AF_INET(), - &stun_sock_cb, &ss_cfg, - &g.peer[i], &g.peer[i].stun_sock); - if (status != PJ_SUCCESS) { - my_perror("pj_stun_sock_create()", status); - return status; - } - - if (o.stun_server) { - server = pj_str(o.stun_server); - port = PJ_STUN_PORT; - } else { - server = pj_str(o.srv_addr); - port = (pj_uint16_t)(o.srv_port?atoi(o.srv_port):PJ_STUN_PORT); - } - status = pj_stun_sock_start(g.peer[i].stun_sock, &server, - port, NULL); - if (status != PJ_SUCCESS) { - my_perror("pj_stun_sock_start()", status); - return status; - } + name[strlen(name)-1] = '0'+i; + status = pj_stun_sock_create(&g.stun_config, name, pj_AF_INET(), + &stun_sock_cb, &ss_cfg, + &g.peer[i], &g.peer[i].stun_sock); + if (status != PJ_SUCCESS) { + my_perror("pj_stun_sock_create()", status); + return status; + } + + if (o.stun_server) { + server = pj_str(o.stun_server); + port = PJ_STUN_PORT; + } else { + server = pj_str(o.srv_addr); + port = (pj_uint16_t)(o.srv_port?atoi(o.srv_port):PJ_STUN_PORT); + } + status = pj_stun_sock_start(g.peer[i].stun_sock, &server, + port, NULL); + if (status != PJ_SUCCESS) { + my_perror("pj_stun_sock_start()", status); + return status; + } } /* Start the worker thread */ @@ -190,32 +189,32 @@ static int client_shutdown() unsigned i; if (g.thread) { - g.quit = 1; - pj_thread_join(g.thread); - pj_thread_destroy(g.thread); - g.thread = NULL; + g.quit = 1; + pj_thread_join(g.thread); + pj_thread_destroy(g.thread); + g.thread = NULL; } if (g.relay) { - pj_turn_sock_destroy(g.relay); - g.relay = NULL; + pj_turn_sock_destroy(g.relay); + g.relay = NULL; } for (i=0; i %s", pj_turn_state_name(old_state), - pj_turn_state_name(new_state))); + pj_turn_state_name(new_state))); if (new_state == PJ_TURN_STATE_READY) { - pj_turn_session_info info; - pj_turn_sock_get_info(relay, &info); - pj_memcpy(&g.relay_addr, &info.relay_addr, sizeof(pj_sockaddr)); + pj_turn_session_info info; + pj_turn_sock_get_info(relay, &info); + pj_memcpy(&g.relay_addr, &info.relay_addr, sizeof(pj_sockaddr)); } else if (new_state > PJ_TURN_STATE_READY && g.relay) { - PJ_LOG(3,(THIS_FILE, "Relay shutting down..")); - g.relay = NULL; + PJ_LOG(3,(THIS_FILE, "Relay shutting down..")); + g.relay = NULL; } } static pj_bool_t stun_sock_on_status(pj_stun_sock *stun_sock, - pj_stun_sock_op op, - pj_status_t status) + pj_stun_sock_op op, + pj_status_t status) { struct peer *peer = (struct peer*) pj_stun_sock_get_user_data(stun_sock); if (status == PJ_SUCCESS) { - PJ_LOG(4,(THIS_FILE, "peer%d: %s success", peer-g.peer, - pj_stun_sock_op_name(op))); + PJ_LOG(4,(THIS_FILE, "peer%d: %s success", peer-g.peer, + pj_stun_sock_op_name(op))); } else { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(1,(THIS_FILE, "peer%d: %s error: %s", peer-g.peer, - pj_stun_sock_op_name(op), errmsg)); - return PJ_FALSE; + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(1,(THIS_FILE, "peer%d: %s error: %s", peer-g.peer, + pj_stun_sock_op_name(op), errmsg)); + return PJ_FALSE; } if (op==PJ_STUN_SOCK_BINDING_OP || op==PJ_STUN_SOCK_KEEP_ALIVE_OP) { - pj_stun_sock_info info; - int cmp; + pj_stun_sock_info info; + int cmp; - pj_stun_sock_get_info(stun_sock, &info); - cmp = pj_sockaddr_cmp(&info.mapped_addr, &peer->mapped_addr); + pj_stun_sock_get_info(stun_sock, &info); + cmp = pj_sockaddr_cmp(&info.mapped_addr, &peer->mapped_addr); - if (cmp) { - char straddr[PJ_INET6_ADDRSTRLEN+10]; + if (cmp) { + char straddr[PJ_INET6_ADDRSTRLEN+10]; - pj_sockaddr_cp(&peer->mapped_addr, &info.mapped_addr); - pj_sockaddr_print(&peer->mapped_addr, straddr, sizeof(straddr), 3); - PJ_LOG(3,(THIS_FILE, "peer%d: STUN mapped address is %s", - peer-g.peer, straddr)); - } + pj_sockaddr_cp(&peer->mapped_addr, &info.mapped_addr); + pj_sockaddr_print(&peer->mapped_addr, straddr, sizeof(straddr), 3); + PJ_LOG(3,(THIS_FILE, "peer%d: STUN mapped address is %s", + peer-g.peer, straddr)); + } } return PJ_TRUE; } static pj_bool_t stun_sock_on_rx_data(pj_stun_sock *stun_sock, - void *pkt, - unsigned pkt_len, - const pj_sockaddr_t *src_addr, - unsigned addr_len) + void *pkt, + unsigned pkt_len, + const pj_sockaddr_t *src_addr, + unsigned addr_len) { struct peer *peer = (struct peer*) pj_stun_sock_get_user_data(stun_sock); char straddr[PJ_INET6_ADDRSTRLEN+10]; @@ -394,7 +393,7 @@ static pj_bool_t stun_sock_on_rx_data(pj_stun_sock *stun_sock, pj_sockaddr_print(src_addr, straddr, sizeof(straddr), 3); PJ_LOG(3,(THIS_FILE, "peer%d: received %d bytes data from %s: %s", - peer-g.peer, pkt_len, straddr, (char*)pkt)); + peer-g.peer, pkt_len, straddr, (char*)pkt)); return PJ_TRUE; } @@ -406,15 +405,15 @@ static void menu(void) char client_state[20], relay_addr[80], peer0_addr[80], peer1_addr[80]; if (g.relay) { - pj_turn_sock_get_info(g.relay, &info); - strcpy(client_state, pj_turn_state_name(info.state)); - if (info.state >= PJ_TURN_STATE_READY) - pj_sockaddr_print(&info.relay_addr, relay_addr, sizeof(relay_addr), 3); - else - strcpy(relay_addr, "0.0.0.0:0"); + pj_turn_sock_get_info(g.relay, &info); + strcpy(client_state, pj_turn_state_name(info.state)); + if (info.state >= PJ_TURN_STATE_READY) + pj_sockaddr_print(&info.relay_addr, relay_addr, sizeof(relay_addr), 3); + else + strcpy(relay_addr, "0.0.0.0:0"); } else { - strcpy(client_state, "NULL"); - strcpy(relay_addr, "0.0.0.0:0"); + strcpy(client_state, "NULL"); + strcpy(relay_addr, "0.0.0.0:0"); } pj_sockaddr_print(&g.peer[0].mapped_addr, peer0_addr, sizeof(peer0_addr), 3); @@ -426,16 +425,16 @@ static void menu(void) puts("| CLIENT | PEER-0 |"); puts("| | |"); printf("| State : %-12s | Address: %-21s |\n", - client_state, peer0_addr); + client_state, peer0_addr); printf("| Relay addr: %-21s | |\n", - relay_addr); + relay_addr); puts("| | 0 Send data to relay address |"); puts("| a Allocate relay | |"); puts("| p,pp Set permission for peer 0/1 +--------------------------------+"); puts("| s,ss Send data to peer 0/1 | PEER-1 |"); puts("| b,bb BindChannel to peer 0/1 | |"); printf("| x Delete allocation | Address: %-21s |\n", - peer1_addr); + peer1_addr); puts("+------------------------------------+ |"); puts("| q Quit d Dump | 1 Send data to relay adderss |"); puts("+------------------------------------+--------------------------------+"); @@ -447,91 +446,91 @@ static void menu(void) static void console_main(void) { while (!g.quit) { - char input[32]; - struct peer *peer; - pj_status_t status; - - menu(); - - if (fgets(input, sizeof(input), stdin) == NULL) - break; - - switch (input[0]) { - case 'a': - create_relay(); - break; - case 'd': - pj_pool_factory_dump(&g.cp.factory, PJ_TRUE); - break; - case 's': - if (g.relay == NULL) { - puts("Error: no relay"); - continue; - } - if (input[1]!='s') - peer = &g.peer[0]; - else - peer = &g.peer[1]; - - strcpy(input, "Hello from client"); - status = pj_turn_sock_sendto(g.relay, (const pj_uint8_t*)input, - strlen(input)+1, - &peer->mapped_addr, - pj_sockaddr_get_len(&peer->mapped_addr)); - if (status != PJ_SUCCESS && status != PJ_EPENDING) - my_perror("turn_udp_sendto() failed", status); - break; - case 'b': - if (g.relay == NULL) { - puts("Error: no relay"); - continue; - } - if (input[1]!='b') - peer = &g.peer[0]; - else - peer = &g.peer[1]; - - status = pj_turn_sock_bind_channel(g.relay, &peer->mapped_addr, - pj_sockaddr_get_len(&peer->mapped_addr)); - if (status != PJ_SUCCESS) - my_perror("turn_udp_bind_channel() failed", status); - break; - case 'p': - if (g.relay == NULL) { - puts("Error: no relay"); - continue; - } - if (input[1]!='p') - peer = &g.peer[0]; - else - peer = &g.peer[1]; - - status = pj_turn_sock_set_perm(g.relay, 1, &peer->mapped_addr, 1); - if (status != PJ_SUCCESS) - my_perror("pj_turn_sock_set_perm() failed", status); - break; - case 'x': - if (g.relay == NULL) { - puts("Error: no relay"); - continue; - } - destroy_relay(); - break; - case '0': - case '1': - if (g.relay == NULL) { - puts("No relay"); - break; - } - peer = &g.peer[input[0]-'0']; - sprintf(input, "Hello from peer%d", input[0]-'0'); - pj_stun_sock_sendto(peer->stun_sock, NULL, input, strlen(input)+1, 0, - &g.relay_addr, pj_sockaddr_get_len(&g.relay_addr)); - break; - case 'q': - g.quit = PJ_TRUE; - break; - } + char input[32]; + struct peer *peer; + pj_status_t status; + + menu(); + + if (fgets(input, sizeof(input), stdin) == NULL) + break; + + switch (input[0]) { + case 'a': + create_relay(); + break; + case 'd': + pj_pool_factory_dump(&g.cp.factory, PJ_TRUE); + break; + case 's': + if (g.relay == NULL) { + puts("Error: no relay"); + continue; + } + if (input[1]!='s') + peer = &g.peer[0]; + else + peer = &g.peer[1]; + + strcpy(input, "Hello from client"); + status = pj_turn_sock_sendto(g.relay, (const pj_uint8_t*)input, + strlen(input)+1, + &peer->mapped_addr, + pj_sockaddr_get_len(&peer->mapped_addr)); + if (status != PJ_SUCCESS && status != PJ_EPENDING) + my_perror("turn_udp_sendto() failed", status); + break; + case 'b': + if (g.relay == NULL) { + puts("Error: no relay"); + continue; + } + if (input[1]!='b') + peer = &g.peer[0]; + else + peer = &g.peer[1]; + + status = pj_turn_sock_bind_channel(g.relay, &peer->mapped_addr, + pj_sockaddr_get_len(&peer->mapped_addr)); + if (status != PJ_SUCCESS) + my_perror("turn_udp_bind_channel() failed", status); + break; + case 'p': + if (g.relay == NULL) { + puts("Error: no relay"); + continue; + } + if (input[1]!='p') + peer = &g.peer[0]; + else + peer = &g.peer[1]; + + status = pj_turn_sock_set_perm(g.relay, 1, &peer->mapped_addr, 1); + if (status != PJ_SUCCESS) + my_perror("pj_turn_sock_set_perm() failed", status); + break; + case 'x': + if (g.relay == NULL) { + puts("Error: no relay"); + continue; + } + destroy_relay(); + break; + case '0': + case '1': + if (g.relay == NULL) { + puts("No relay"); + break; + } + peer = &g.peer[input[0]-'0']; + sprintf(input, "Hello from peer%d", input[0]-'0'); + pj_stun_sock_sendto(peer->stun_sock, NULL, input, strlen(input)+1, 0, + &g.relay_addr, pj_sockaddr_get_len(&g.relay_addr)); + break; + case 'q': + g.quit = PJ_TRUE; + break; + } } } @@ -556,71 +555,71 @@ static void usage(void) int main(int argc, char *argv[]) { struct pj_getopt_option long_options[] = { - { "realm", 1, 0, 'r'}, - { "username", 1, 0, 'u'}, - { "password", 1, 0, 'p'}, - { "fingerprint",0, 0, 'F'}, - { "tcp", 0, 0, 'T'}, - { "help", 0, 0, 'h'}, - { "stun-srv", 1, 0, 'S'}, - { "nameserver", 1, 0, 'N'} + { "realm", 1, 0, 'r'}, + { "username", 1, 0, 'u'}, + { "password", 1, 0, 'p'}, + { "fingerprint",0, 0, 'F'}, + { "tcp", 0, 0, 'T'}, + { "help", 0, 0, 'h'}, + { "stun-srv", 1, 0, 'S'}, + { "nameserver", 1, 0, 'N'} }; int c, opt_id; char *pos; pj_status_t status; while((c=pj_getopt_long(argc,argv, "r:u:p:S:N:hFT", long_options, &opt_id))!=-1) { - switch (c) { - case 'r': - o.realm = pj_optarg; - break; - case 'u': - o.user_name = pj_optarg; - break; - case 'p': - o.password = pj_optarg; - break; - case 'h': - usage(); - return 0; - case 'F': - o.use_fingerprint = PJ_TRUE; - break; - case 'T': - o.use_tcp = PJ_TRUE; - break; - case 'S': - o.stun_server = pj_optarg; - break; - case 'N': - o.nameserver = pj_optarg; - break; - default: - printf("Argument \"%s\" is not valid. Use -h to see help", - argv[pj_optind]); - return 1; - } + switch (c) { + case 'r': + o.realm = pj_optarg; + break; + case 'u': + o.user_name = pj_optarg; + break; + case 'p': + o.password = pj_optarg; + break; + case 'h': + usage(); + return 0; + case 'F': + o.use_fingerprint = PJ_TRUE; + break; + case 'T': + o.use_tcp = PJ_TRUE; + break; + case 'S': + o.stun_server = pj_optarg; + break; + case 'N': + o.nameserver = pj_optarg; + break; + default: + printf("Argument \"%s\" is not valid. Use -h to see help", + argv[pj_optind]); + return 1; + } } if (pj_optind == argc) { - puts("Error: TARGET is needed"); - usage(); - return 1; + puts("Error: TARGET is needed"); + usage(); + return 1; } if ((pos=pj_ansi_strchr(argv[pj_optind], ':')) != NULL) { - o.srv_addr = argv[pj_optind]; - *pos = '\0'; - o.srv_port = pos+1; + o.srv_addr = argv[pj_optind]; + *pos = '\0'; + o.srv_port = pos+1; } else { - o.srv_addr = argv[pj_optind]; + o.srv_addr = argv[pj_optind]; } if ((status=init()) != 0) - goto on_return; + goto on_return; //if ((status=create_relay()) != 0) - // goto on_return; + // goto on_return; console_main(); diff --git a/pjnath/src/pjturn-srv/allocation.c b/pjnath/src/pjturn-srv/allocation.c index 6c9c9ce116..69c14650a6 100644 --- a/pjnath/src/pjturn-srv/allocation.c +++ b/pjnath/src/pjturn-srv/allocation.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,26 +29,26 @@ enum { TIMER_ID_DESTROY }; -#define DESTROY_DELAY {0, 500} -#define PEER_TABLE_SIZE 32 +#define DESTROY_DELAY {0, 500} +#define PEER_TABLE_SIZE 32 -#define MAX_CLIENT_BANDWIDTH 128 /* In Kbps */ -#define DEFA_CLIENT_BANDWIDTH 64 +#define MAX_CLIENT_BANDWIDTH 128 /* In Kbps */ +#define DEFA_CLIENT_BANDWIDTH 64 -#define MIN_LIFETIME 30 -#define MAX_LIFETIME 600 -#define DEF_LIFETIME 300 +#define MIN_LIFETIME 30 +#define MAX_LIFETIME 600 +#define DEF_LIFETIME 300 /* Parsed Allocation request. */ typedef struct alloc_request { - unsigned tp_type; /* Requested transport */ - char addr[PJ_INET6_ADDRSTRLEN]; /* Requested IP */ - unsigned bandwidth; /* Requested bandwidth */ - unsigned lifetime; /* Lifetime. */ - unsigned rpp_bits; /* A bits */ - unsigned rpp_port; /* Requested port */ + unsigned tp_type; /* Requested transport */ + char addr[PJ_INET6_ADDRSTRLEN]; /* Requested IP */ + unsigned bandwidth; /* Requested bandwidth */ + unsigned lifetime; /* Lifetime. */ + unsigned rpp_bits; /* A bits */ + unsigned rpp_port; /* Requested port */ } alloc_request; @@ -57,53 +56,53 @@ typedef struct alloc_request /* Prototypes */ static void destroy_allocation(pj_turn_allocation *alloc); static pj_status_t create_relay(pj_turn_srv *srv, - pj_turn_allocation *alloc, - const pj_stun_msg *msg, - const alloc_request *req, - pj_turn_relay_res *relay); + pj_turn_allocation *alloc, + const pj_stun_msg *msg, + const alloc_request *req, + pj_turn_relay_res *relay); static void destroy_relay(pj_turn_relay_res *relay); static void on_rx_from_peer(pj_ioqueue_key_t *key, pj_ioqueue_op_key_t *op_key, pj_ssize_t bytes_read); static pj_status_t stun_on_send_msg(pj_stun_session *sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len); + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len); static pj_status_t stun_on_rx_request(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_rx_data *rdata, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_rx_data *rdata, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); static pj_status_t stun_on_rx_indication(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_msg *msg, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_msg *msg, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); /* Log allocation error */ static void alloc_err(pj_turn_allocation *alloc, const char *title, - pj_status_t status) + pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; pj_strerror(status, errmsg, sizeof(errmsg)); PJ_LOG(4,(alloc->obj_name, "%s for client %s: %s", - title, alloc->info, errmsg)); + title, alloc->info, errmsg)); } /* Parse ALLOCATE request */ static pj_status_t parse_allocate_req(alloc_request *cfg, - pj_stun_session *sess, - const pj_stun_rx_data *rdata, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + pj_stun_session *sess, + const pj_stun_rx_data *rdata, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { const pj_stun_msg *req = rdata->msg; pj_stun_bandwidth_attr *attr_bw; @@ -115,69 +114,69 @@ static pj_status_t parse_allocate_req(alloc_request *cfg, /* Get BANDWIDTH attribute, if any. */ attr_bw = (pj_stun_uint_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_BANDWIDTH, 0); + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_BANDWIDTH, 0); if (attr_bw) { - cfg->bandwidth = attr_bw->value; + cfg->bandwidth = attr_bw->value; } else { - cfg->bandwidth = DEFA_CLIENT_BANDWIDTH; + cfg->bandwidth = DEFA_CLIENT_BANDWIDTH; } /* Check if we can satisfy the bandwidth */ if (cfg->bandwidth > MAX_CLIENT_BANDWIDTH) { - pj_stun_session_respond(sess, rdata, - PJ_STUN_SC_ALLOCATION_QUOTA_REACHED, - "Invalid bandwidth", NULL, PJ_TRUE, - src_addr, src_addr_len); - return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_ALLOCATION_QUOTA_REACHED); + pj_stun_session_respond(sess, rdata, + PJ_STUN_SC_ALLOCATION_QUOTA_REACHED, + "Invalid bandwidth", NULL, PJ_TRUE, + src_addr, src_addr_len); + return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_ALLOCATION_QUOTA_REACHED); } /* MUST have REQUESTED-TRANSPORT attribute */ attr_req_tp = (pj_stun_uint_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_REQ_TRANSPORT, 0); + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_REQ_TRANSPORT, 0); if (attr_req_tp == NULL) { - pj_stun_session_respond(sess, rdata, PJ_STUN_SC_BAD_REQUEST, - "Missing REQUESTED-TRANSPORT attribute", - NULL, PJ_TRUE, src_addr, src_addr_len); - return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_BAD_REQUEST); + pj_stun_session_respond(sess, rdata, PJ_STUN_SC_BAD_REQUEST, + "Missing REQUESTED-TRANSPORT attribute", + NULL, PJ_TRUE, src_addr, src_addr_len); + return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_BAD_REQUEST); } cfg->tp_type = PJ_STUN_GET_RT_PROTO(attr_req_tp->value); /* Can only support UDP for now */ if (cfg->tp_type != PJ_TURN_TP_UDP) { - pj_stun_session_respond(sess, rdata, PJ_STUN_SC_UNSUPP_TRANSPORT_PROTO, - NULL, NULL, PJ_TRUE, src_addr, src_addr_len); - return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNSUPP_TRANSPORT_PROTO); + pj_stun_session_respond(sess, rdata, PJ_STUN_SC_UNSUPP_TRANSPORT_PROTO, + NULL, NULL, PJ_TRUE, src_addr, src_addr_len); + return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_UNSUPP_TRANSPORT_PROTO); } /* Get RESERVATION-TOKEN attribute, if any */ attr_res_token = (pj_stun_res_token_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_RESERVATION_TOKEN, - 0); + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_RESERVATION_TOKEN, + 0); if (attr_res_token) { - /* We don't support RESERVATION-TOKEN for now */ - pj_stun_session_respond(sess, rdata, - PJ_STUN_SC_BAD_REQUEST, - "RESERVATION-TOKEN is not supported", NULL, - PJ_TRUE, src_addr, src_addr_len); - return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_BAD_REQUEST); + /* We don't support RESERVATION-TOKEN for now */ + pj_stun_session_respond(sess, rdata, + PJ_STUN_SC_BAD_REQUEST, + "RESERVATION-TOKEN is not supported", NULL, + PJ_TRUE, src_addr, src_addr_len); + return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_BAD_REQUEST); } /* Get LIFETIME attribute */ attr_lifetime = (pj_stun_uint_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_LIFETIME, 0); + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_LIFETIME, 0); if (attr_lifetime) { - cfg->lifetime = attr_lifetime->value; - if (cfg->lifetime < MIN_LIFETIME) { - pj_stun_session_respond(sess, rdata, PJ_STUN_SC_BAD_REQUEST, - "LIFETIME too short", NULL, - PJ_TRUE, src_addr, src_addr_len); - return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_BAD_REQUEST); - } - if (cfg->lifetime > MAX_LIFETIME) - cfg->lifetime = MAX_LIFETIME; + cfg->lifetime = attr_lifetime->value; + if (cfg->lifetime < MIN_LIFETIME) { + pj_stun_session_respond(sess, rdata, PJ_STUN_SC_BAD_REQUEST, + "LIFETIME too short", NULL, + PJ_TRUE, src_addr, src_addr_len); + return PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_BAD_REQUEST); + } + if (cfg->lifetime > MAX_LIFETIME) + cfg->lifetime = MAX_LIFETIME; } else { - cfg->lifetime = DEF_LIFETIME; + cfg->lifetime = DEF_LIFETIME; } return PJ_SUCCESS; @@ -186,9 +185,9 @@ static pj_status_t parse_allocate_req(alloc_request *cfg, /* Respond to ALLOCATE request */ static pj_status_t send_allocate_response(pj_turn_allocation *alloc, - pj_stun_session *srv_sess, - pj_turn_transport *transport, - const pj_stun_rx_data *rdata) + pj_stun_session *srv_sess, + pj_turn_transport *transport, + const pj_stun_rx_data *rdata) { pj_stun_tx_data *tdata; pj_status_t status; @@ -196,38 +195,38 @@ static pj_status_t send_allocate_response(pj_turn_allocation *alloc, /* Respond the original ALLOCATE request */ status = pj_stun_session_create_res(srv_sess, rdata, 0, NULL, &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Add XOR-RELAYED-ADDRESS attribute */ pj_stun_msg_add_sockaddr_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_XOR_RELAYED_ADDR, PJ_TRUE, - &alloc->relay.hkey.addr, - pj_sockaddr_get_len(&alloc->relay.hkey.addr)); + PJ_STUN_ATTR_XOR_RELAYED_ADDR, PJ_TRUE, + &alloc->relay.hkey.addr, + pj_sockaddr_get_len(&alloc->relay.hkey.addr)); /* Add LIFETIME. */ pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_LIFETIME, - (unsigned)alloc->relay.lifetime); + PJ_STUN_ATTR_LIFETIME, + (unsigned)alloc->relay.lifetime); /* Add BANDWIDTH */ pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_BANDWIDTH, - alloc->bandwidth); + PJ_STUN_ATTR_BANDWIDTH, + alloc->bandwidth); /* Add RESERVATION-TOKEN */ PJ_TODO(ADD_RESERVATION_TOKEN); /* Add XOR-MAPPED-ADDRESS */ pj_stun_msg_add_sockaddr_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_XOR_MAPPED_ADDR, PJ_TRUE, - &alloc->hkey.clt_addr, - pj_sockaddr_get_len(&alloc->hkey.clt_addr)); + PJ_STUN_ATTR_XOR_MAPPED_ADDR, PJ_TRUE, + &alloc->hkey.clt_addr, + pj_sockaddr_get_len(&alloc->hkey.clt_addr)); /* Send the response */ return pj_stun_session_send_msg(srv_sess, transport, PJ_TRUE, - PJ_FALSE, &alloc->hkey.clt_addr, - pj_sockaddr_get_len(&alloc->hkey.clt_addr), - tdata); + PJ_FALSE, &alloc->hkey.clt_addr, + pj_sockaddr_get_len(&alloc->hkey.clt_addr), + tdata); } @@ -243,24 +242,24 @@ static pj_status_t init_cred(pj_turn_allocation *alloc, const pj_stun_msg *req) pj_status_t status; realm = (const pj_stun_realm_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_REALM, 0); + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_REALM, 0); PJ_ASSERT_RETURN(realm != NULL, PJ_EBUG); user = (const pj_stun_username_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_USERNAME, 0); + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_USERNAME, 0); PJ_ASSERT_RETURN(user != NULL, PJ_EBUG); nonce = (const pj_stun_nonce_attr*) - pj_stun_msg_find_attr(req, PJ_STUN_ATTR_NONCE, 0); + pj_stun_msg_find_attr(req, PJ_STUN_ATTR_NONCE, 0); PJ_ASSERT_RETURN(nonce != NULL, PJ_EBUG); /* Lookup the password */ status = pj_turn_get_password(NULL, NULL, &realm->value, - &user->value, alloc->pool, - &alloc->cred.data.static_cred.data_type, - &alloc->cred.data.static_cred.data); + &user->value, alloc->pool, + &alloc->cred.data.static_cred.data_type, + &alloc->cred.data.static_cred.data); if (status != PJ_SUCCESS) - return status; + return status; /* Save credential */ alloc->cred.type = PJ_STUN_AUTH_CRED_STATIC; @@ -276,11 +275,11 @@ static pj_status_t init_cred(pj_turn_allocation *alloc, const pj_stun_msg *req) * Create new allocation. */ PJ_DEF(pj_status_t) pj_turn_allocation_create(pj_turn_transport *transport, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len, - const pj_stun_rx_data *rdata, - pj_stun_session *srv_sess, - pj_turn_allocation **p_alloc) + const pj_sockaddr_t *src_addr, + unsigned src_addr_len, + const pj_stun_rx_data *rdata, + pj_stun_session *srv_sess, + pj_turn_allocation **p_alloc) { pj_turn_srv *srv = transport->listener->server; const pj_stun_msg *msg = rdata->msg; @@ -294,7 +293,7 @@ PJ_DEF(pj_status_t) pj_turn_allocation_create(pj_turn_transport *transport, /* Parse ALLOCATE request */ status = parse_allocate_req(&req, srv_sess, rdata, src_addr, src_addr_len); if (status != PJ_SUCCESS) - return status; + return status; pool = pj_pool_create(srv->core.pf, "alloc%p", 1000, 1000, NULL); @@ -315,9 +314,9 @@ PJ_DEF(pj_status_t) pj_turn_allocation_create(pj_turn_transport *transport, pj_memcpy(&alloc->hkey.clt_addr, src_addr, src_addr_len); status = pj_lock_create_recursive_mutex(pool, alloc->obj_name, - &alloc->lock); + &alloc->lock); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } /* Create peer hash table */ @@ -328,7 +327,7 @@ PJ_DEF(pj_status_t) pj_turn_allocation_create(pj_turn_transport *transport, /* Print info */ pj_ansi_strcpy(alloc->info, - pj_turn_tp_type_name(transport->listener->tp_type)); + pj_turn_tp_type_name(transport->listener->tp_type)); alloc->info[3] = ':'; pj_sockaddr_print(src_addr, alloc->info+4, sizeof(alloc->info)-4, 3); @@ -338,9 +337,9 @@ PJ_DEF(pj_status_t) pj_turn_allocation_create(pj_turn_transport *transport, sess_cb.on_rx_request = &stun_on_rx_request; sess_cb.on_rx_indication = &stun_on_rx_indication; status = pj_stun_session_create(&srv->core.stun_cfg, alloc->obj_name, - &sess_cb, PJ_FALSE, NULL, &alloc->sess); + &sess_cb, PJ_FALSE, NULL, &alloc->sess); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } /* Attach to STUN session */ @@ -349,17 +348,17 @@ PJ_DEF(pj_status_t) pj_turn_allocation_create(pj_turn_transport *transport, /* Init authentication credential */ status = init_cred(alloc, msg); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } /* Attach authentication credential to STUN session */ pj_stun_session_set_credential(alloc->sess, PJ_STUN_AUTH_LONG_TERM, - &alloc->cred); + &alloc->cred); /* Create the relay resource */ status = create_relay(srv, alloc, msg, &req, &alloc->relay); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } /* Register this allocation */ @@ -368,13 +367,13 @@ PJ_DEF(pj_status_t) pj_turn_allocation_create(pj_turn_transport *transport, /* Respond to ALLOCATE request */ status = send_allocate_response(alloc, srv_sess, transport, rdata); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Done */ pj_sockaddr_print(&alloc->relay.hkey.addr, str_tmp, - sizeof(str_tmp), 3); + sizeof(str_tmp), 3); PJ_LOG(4,(alloc->obj_name, "Client %s created, relay addr=%s:%s", - alloc->info, pj_turn_tp_type_name(req.tp_type), str_tmp)); + alloc->info, pj_turn_tp_type_name(req.tp_type), str_tmp)); /* Success */ *p_alloc = alloc; @@ -384,7 +383,7 @@ PJ_DEF(pj_status_t) pj_turn_allocation_create(pj_turn_transport *transport, /* Send reply to the ALLOCATE request */ pj_strerror(status, str_tmp, sizeof(str_tmp)); pj_stun_session_respond(srv_sess, rdata, PJ_STUN_SC_BAD_REQUEST, str_tmp, - transport, PJ_TRUE, src_addr, src_addr_len); + transport, PJ_TRUE, src_addr, src_addr_len); /* Cleanup */ destroy_allocation(alloc); @@ -396,18 +395,18 @@ PJ_DEF(pj_status_t) pj_turn_allocation_create(pj_turn_transport *transport, static void destroy_relay(pj_turn_relay_res *relay) { if (relay->timer.id) { - pj_timer_heap_cancel(relay->allocation->server->core.timer_heap, - &relay->timer); - relay->timer.id = PJ_FALSE; + pj_timer_heap_cancel(relay->allocation->server->core.timer_heap, + &relay->timer); + relay->timer.id = PJ_FALSE; } if (relay->tp.key) { - pj_ioqueue_unregister(relay->tp.key); - relay->tp.key = NULL; - relay->tp.sock = PJ_INVALID_SOCKET; + pj_ioqueue_unregister(relay->tp.key); + relay->tp.key = NULL; + relay->tp.sock = PJ_INVALID_SOCKET; } else if (relay->tp.sock != PJ_INVALID_SOCKET) { - pj_sock_close(relay->tp.sock); - relay->tp.sock = PJ_INVALID_SOCKET; + pj_sock_close(relay->tp.sock); + relay->tp.sock = PJ_INVALID_SOCKET; } /* Mark as shutdown */ @@ -430,33 +429,33 @@ static void destroy_allocation(pj_turn_allocation *alloc) /* Must lock only after destroying relay otherwise deadlock */ if (alloc->lock) { - pj_lock_acquire(alloc->lock); + pj_lock_acquire(alloc->lock); } /* Unreference transport */ if (alloc->transport) { - pj_turn_transport_dec_ref(alloc->transport, alloc); - alloc->transport = NULL; + pj_turn_transport_dec_ref(alloc->transport, alloc); + alloc->transport = NULL; } /* Destroy STUN session */ if (alloc->sess) { - pj_stun_session_destroy(alloc->sess); - alloc->sess = NULL; + pj_stun_session_destroy(alloc->sess); + alloc->sess = NULL; } /* Destroy lock */ if (alloc->lock) { - pj_lock_release(alloc->lock); - pj_lock_destroy(alloc->lock); - alloc->lock = NULL; + pj_lock_release(alloc->lock); + pj_lock_destroy(alloc->lock); + alloc->lock = NULL; } /* Destroy pool */ pool = alloc->pool; if (pool) { - alloc->pool = NULL; - pj_pool_release(pool); + alloc->pool = NULL; + pj_pool_release(pool); } } @@ -471,10 +470,10 @@ PJ_DECL(void) pj_turn_allocation_destroy(pj_turn_allocation *alloc) * Handle transport closure. */ PJ_DEF(void) pj_turn_allocation_on_transport_closed( pj_turn_allocation *alloc, - pj_turn_transport *tp) + pj_turn_transport *tp) { PJ_LOG(5,(alloc->obj_name, "Transport %s unexpectedly closed, destroying " - "allocation %s", tp->info, alloc->info)); + "allocation %s", tp->info, alloc->info)); pj_turn_transport_dec_ref(tp, alloc); alloc->transport = NULL; destroy_allocation(alloc); @@ -491,16 +490,16 @@ static void alloc_shutdown(pj_turn_allocation *alloc) /* Work with existing schedule */ if (alloc->relay.timer.id == TIMER_ID_TIMEOUT) { - /* Cancel existing shutdown timer */ - pj_timer_heap_cancel(alloc->server->core.timer_heap, - &alloc->relay.timer); - alloc->relay.timer.id = TIMER_ID_NONE; + /* Cancel existing shutdown timer */ + pj_timer_heap_cancel(alloc->server->core.timer_heap, + &alloc->relay.timer); + alloc->relay.timer.id = TIMER_ID_NONE; } else if (alloc->relay.timer.id == TIMER_ID_DESTROY) { - /* We've been scheduled to be destroyed, ignore this - * shutdown request. - */ - return; + /* We've been scheduled to be destroyed, ignore this + * shutdown request. + */ + return; } pj_assert(alloc->relay.timer.id == TIMER_ID_NONE); @@ -515,7 +514,7 @@ static void alloc_shutdown(pj_turn_allocation *alloc) /* Schedule destroy timer */ alloc->relay.timer.id = TIMER_ID_DESTROY; pj_timer_heap_schedule(alloc->server->core.timer_heap, - &alloc->relay.timer, &destroy_delay); + &alloc->relay.timer, &destroy_delay); } @@ -530,9 +529,9 @@ static pj_status_t resched_timeout(pj_turn_allocation *alloc) pj_assert(alloc->relay.timer.id != TIMER_ID_DESTROY); if (alloc->relay.timer.id != 0) { - pj_timer_heap_cancel(alloc->server->core.timer_heap, - &alloc->relay.timer); - alloc->relay.timer.id = TIMER_ID_NONE; + pj_timer_heap_cancel(alloc->server->core.timer_heap, + &alloc->relay.timer); + alloc->relay.timer.id = TIMER_ID_NONE; } delay.sec = alloc->relay.lifetime; @@ -540,10 +539,10 @@ static pj_status_t resched_timeout(pj_turn_allocation *alloc) alloc->relay.timer.id = TIMER_ID_TIMEOUT; status = pj_timer_heap_schedule(alloc->server->core.timer_heap, - &alloc->relay.timer, &delay); + &alloc->relay.timer, &delay); if (status != PJ_SUCCESS) { - alloc->relay.timer.id = TIMER_ID_NONE; - return status; + alloc->relay.timer.id = TIMER_ID_NONE; + return status; } return PJ_SUCCESS; @@ -563,21 +562,21 @@ static void relay_timeout_cb(pj_timer_heap_t *heap, pj_timer_entry *e) if (e->id == TIMER_ID_TIMEOUT) { - e->id = TIMER_ID_NONE; + e->id = TIMER_ID_NONE; - PJ_LOG(4,(alloc->obj_name, - "Client %s refresh timed-out, shutting down..", - alloc->info)); + PJ_LOG(4,(alloc->obj_name, + "Client %s refresh timed-out, shutting down..", + alloc->info)); - alloc_shutdown(alloc); + alloc_shutdown(alloc); } else if (e->id == TIMER_ID_DESTROY) { - e->id = TIMER_ID_NONE; + e->id = TIMER_ID_NONE; - PJ_LOG(4,(alloc->obj_name, "Client %s destroying..", - alloc->info)); + PJ_LOG(4,(alloc->obj_name, "Client %s destroying..", + alloc->info)); - destroy_allocation(alloc); + destroy_allocation(alloc); } } @@ -586,10 +585,10 @@ static void relay_timeout_cb(pj_timer_heap_t *heap, pj_timer_entry *e) * Create relay. */ static pj_status_t create_relay(pj_turn_srv *srv, - pj_turn_allocation *alloc, - const pj_stun_msg *msg, - const alloc_request *req, - pj_turn_relay_res *relay) + pj_turn_allocation *alloc, + const pj_stun_msg *msg, + const alloc_request *req, + pj_turn_relay_res *relay) { enum { RETRY = 40 }; pj_pool_t *pool = alloc->pool; @@ -609,20 +608,20 @@ static pj_status_t create_relay(pj_turn_srv *srv, /* Save realm */ sa = (pj_stun_string_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_REALM, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_REALM, 0); PJ_ASSERT_RETURN(sa, PJ_EINVALIDOP); pj_strdup(pool, &relay->realm, &sa->value); /* Save username */ sa = (pj_stun_string_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_USERNAME, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_USERNAME, 0); PJ_ASSERT_RETURN(sa, PJ_EINVALIDOP); pj_strdup(pool, &relay->user, &sa->value); /* Lifetime and timeout */ relay->lifetime = req->lifetime; pj_timer_entry_init(&relay->timer, TIMER_ID_NONE, relay, - &relay_timeout_cb); + &relay_timeout_cb); resched_timeout(alloc); /* Transport type */ @@ -630,85 +629,85 @@ static pj_status_t create_relay(pj_turn_srv *srv, /* Create the socket */ if (req->tp_type == PJ_TURN_TP_UDP) { - sock_type = pj_SOCK_DGRAM(); + sock_type = pj_SOCK_DGRAM(); } else if (req->tp_type == PJ_TURN_TP_TCP) { - sock_type = pj_SOCK_STREAM(); + sock_type = pj_SOCK_STREAM(); } else { - pj_assert(!"Unknown transport"); - return PJ_EINVALIDOP; + pj_assert(!"Unknown transport"); + return PJ_EINVALIDOP; } status = pj_sock_socket(af, sock_type, 0, &relay->tp.sock); if (status != PJ_SUCCESS) { - pj_bzero(relay, sizeof(*relay)); - return status; + pj_bzero(relay, sizeof(*relay)); + return status; } /* Find suitable port for this allocation */ if (req->rpp_port) { - retry_max = 1; + retry_max = 1; } else { - retry_max = RETRY; + retry_max = RETRY; } for (retry=0; retrycore.lock); - - if (req->rpp_port) { - port = (pj_uint16_t) req->rpp_port; - } else if (req->tp_type == PJ_TURN_TP_UDP) { - port = (pj_uint16_t) srv->ports.next_udp++; - if (srv->ports.next_udp > srv->ports.max_udp) - srv->ports.next_udp = srv->ports.min_udp; - } else if (req->tp_type == PJ_TURN_TP_TCP) { - port = (pj_uint16_t) srv->ports.next_tcp++; - if (srv->ports.next_tcp > srv->ports.max_tcp) - srv->ports.next_tcp = srv->ports.min_tcp; - } else { - pj_assert(!"Invalid transport"); - port = 0; - } - - pj_lock_release(srv->core.lock); - - pj_sockaddr_init(af, &bound_addr, NULL, port); - - status = pj_sock_bind(relay->tp.sock, &bound_addr, - pj_sockaddr_get_len(&bound_addr)); - if (status == PJ_SUCCESS) - break; + pj_uint16_t port; + pj_sockaddr bound_addr; + + pj_lock_acquire(srv->core.lock); + + if (req->rpp_port) { + port = (pj_uint16_t) req->rpp_port; + } else if (req->tp_type == PJ_TURN_TP_UDP) { + port = (pj_uint16_t) srv->ports.next_udp++; + if (srv->ports.next_udp > srv->ports.max_udp) + srv->ports.next_udp = srv->ports.min_udp; + } else if (req->tp_type == PJ_TURN_TP_TCP) { + port = (pj_uint16_t) srv->ports.next_tcp++; + if (srv->ports.next_tcp > srv->ports.max_tcp) + srv->ports.next_tcp = srv->ports.min_tcp; + } else { + pj_assert(!"Invalid transport"); + port = 0; + } + + pj_lock_release(srv->core.lock); + + pj_sockaddr_init(af, &bound_addr, NULL, port); + + status = pj_sock_bind(relay->tp.sock, &bound_addr, + pj_sockaddr_get_len(&bound_addr)); + if (status == PJ_SUCCESS) + break; } if (status != PJ_SUCCESS) { - /* Unable to allocate port */ - PJ_LOG(4,(THIS_FILE, "Unable to allocate relay, giving up: err %d", - status)); - pj_sock_close(relay->tp.sock); - relay->tp.sock = PJ_INVALID_SOCKET; - return status; + /* Unable to allocate port */ + PJ_LOG(4,(THIS_FILE, "Unable to allocate relay, giving up: err %d", + status)); + pj_sock_close(relay->tp.sock); + relay->tp.sock = PJ_INVALID_SOCKET; + return status; } /* Init relay key */ namelen = sizeof(relay->hkey.addr); status = pj_sock_getsockname(relay->tp.sock, &relay->hkey.addr, &namelen); if (status != PJ_SUCCESS) { - PJ_LOG(4,(THIS_FILE, "pj_sock_getsockname() failed: err %d", - status)); - pj_sock_close(relay->tp.sock); - relay->tp.sock = PJ_INVALID_SOCKET; - return status; + PJ_LOG(4,(THIS_FILE, "pj_sock_getsockname() failed: err %d", + status)); + pj_sock_close(relay->tp.sock); + relay->tp.sock = PJ_INVALID_SOCKET; + return status; } if (!pj_sockaddr_has_addr(&relay->hkey.addr)) { - pj_sockaddr_copy_addr(&relay->hkey.addr, - &alloc->transport->listener->addr); + pj_sockaddr_copy_addr(&relay->hkey.addr, + &alloc->transport->listener->addr); } if (!pj_sockaddr_has_addr(&relay->hkey.addr)) { - pj_sockaddr tmp_addr; - pj_gethostip(af, &tmp_addr); - pj_sockaddr_copy_addr(&relay->hkey.addr, &tmp_addr); + pj_sockaddr tmp_addr; + pj_gethostip(af, &tmp_addr); + pj_sockaddr_copy_addr(&relay->hkey.addr, &tmp_addr); } /* Init ioqueue */ @@ -716,13 +715,13 @@ static pj_status_t create_relay(pj_turn_srv *srv, icb.on_read_complete = &on_rx_from_peer; status = pj_ioqueue_register_sock(pool, srv->core.ioqueue, relay->tp.sock, - relay, &icb, &relay->tp.key); + relay, &icb, &relay->tp.key); if (status != PJ_SUCCESS) { - PJ_LOG(4,(THIS_FILE, "pj_ioqueue_register_sock() failed: err %d", - status)); - pj_sock_close(relay->tp.sock); - relay->tp.sock = PJ_INVALID_SOCKET; - return status; + PJ_LOG(4,(THIS_FILE, "pj_ioqueue_register_sock() failed: err %d", + status)); + pj_sock_close(relay->tp.sock); + relay->tp.sock = PJ_INVALID_SOCKET; + return status; } /* Kick off pending read operation */ @@ -735,24 +734,24 @@ static pj_status_t create_relay(pj_turn_srv *srv, /* Create and send error response */ static void send_reply_err(pj_turn_allocation *alloc, - const pj_stun_rx_data *rdata, - pj_bool_t cache, - int code, const char *errmsg) + const pj_stun_rx_data *rdata, + pj_bool_t cache, + int code, const char *errmsg) { pj_status_t status; status = pj_stun_session_respond(alloc->sess, rdata, code, errmsg, NULL, - cache, &alloc->hkey.clt_addr, - pj_sockaddr_get_len(&alloc->hkey.clt_addr.addr)); + cache, &alloc->hkey.clt_addr, + pj_sockaddr_get_len(&alloc->hkey.clt_addr.addr)); if (status != PJ_SUCCESS) { - alloc_err(alloc, "Error sending STUN error response", status); - return; + alloc_err(alloc, "Error sending STUN error response", status); + return; } } /* Create and send successful response */ static void send_reply_ok(pj_turn_allocation *alloc, - const pj_stun_rx_data *rdata) + const pj_stun_rx_data *rdata) { pj_status_t status; unsigned interval; @@ -760,47 +759,47 @@ static void send_reply_ok(pj_turn_allocation *alloc, status = pj_stun_session_create_res(alloc->sess, rdata, 0, NULL, &tdata); if (status != PJ_SUCCESS) { - alloc_err(alloc, "Error creating STUN success response", status); - return; + alloc_err(alloc, "Error creating STUN success response", status); + return; } /* Calculate time to expiration */ if (alloc->relay.lifetime != 0) { - pj_time_val now; - pj_gettimeofday(&now); - interval = alloc->relay.expiry.sec - now.sec; + pj_time_val now; + pj_gettimeofday(&now); + interval = alloc->relay.expiry.sec - now.sec; } else { - interval = 0; + interval = 0; } /* Add LIFETIME if this is not ChannelBind. */ if (PJ_STUN_GET_METHOD(tdata->msg->hdr.type)!=PJ_STUN_CHANNEL_BIND_METHOD){ - pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_LIFETIME, interval); - - /* Add BANDWIDTH if lifetime is not zero */ - if (interval != 0) { - pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_BANDWIDTH, - alloc->bandwidth); - } + pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, + PJ_STUN_ATTR_LIFETIME, interval); + + /* Add BANDWIDTH if lifetime is not zero */ + if (interval != 0) { + pj_stun_msg_add_uint_attr(tdata->pool, tdata->msg, + PJ_STUN_ATTR_BANDWIDTH, + alloc->bandwidth); + } } status = pj_stun_session_send_msg(alloc->sess, NULL, PJ_TRUE, - PJ_FALSE, &alloc->hkey.clt_addr, - pj_sockaddr_get_len(&alloc->hkey.clt_addr), - tdata); + PJ_FALSE, &alloc->hkey.clt_addr, + pj_sockaddr_get_len(&alloc->hkey.clt_addr), + tdata); if (status != PJ_SUCCESS) { - alloc_err(alloc, "Error sending STUN success response", status); - return; + alloc_err(alloc, "Error sending STUN success response", status); + return; } } /* Create new permission */ static pj_turn_permission *create_permission(pj_turn_allocation *alloc, - const pj_sockaddr_t *peer_addr, - unsigned addr_len) + const pj_sockaddr_t *peer_addr, + unsigned addr_len) { pj_turn_permission *perm; @@ -815,8 +814,8 @@ static pj_turn_permission *create_permission(pj_turn_allocation *alloc, /* Register to hash table (only the address part!) */ pj_hash_set(alloc->pool, alloc->peer_table, - pj_sockaddr_get_addr(&perm->hkey.peer_addr), - pj_sockaddr_get_addr_len(&perm->hkey.peer_addr), 0, perm); + pj_sockaddr_get_addr(&perm->hkey.peer_addr), + pj_sockaddr_get_addr_len(&perm->hkey.peer_addr), 0, perm); return perm; } @@ -829,19 +828,19 @@ static pj_turn_permission *check_permission_expiry(pj_turn_permission *perm) pj_gettimeofday(&now); if (PJ_TIME_VAL_GT(perm->expiry, now)) { - /* Permission has not expired */ - return perm; + /* Permission has not expired */ + return perm; } /* Remove from permission hash table */ pj_hash_set(NULL, alloc->peer_table, - pj_sockaddr_get_addr(&perm->hkey.peer_addr), - pj_sockaddr_get_addr_len(&perm->hkey.peer_addr), 0, NULL); + pj_sockaddr_get_addr(&perm->hkey.peer_addr), + pj_sockaddr_get_addr_len(&perm->hkey.peer_addr), 0, NULL); /* Remove from channel hash table, if assigned a channel number */ if (perm->channel != PJ_TURN_INVALID_CHANNEL) { - pj_hash_set(NULL, alloc->ch_table, &perm->channel, - sizeof(perm->channel), 0, NULL); + pj_hash_set(NULL, alloc->ch_table, &perm->channel, + sizeof(perm->channel), 0, NULL); } return NULL; @@ -850,8 +849,8 @@ static pj_turn_permission *check_permission_expiry(pj_turn_permission *perm) /* Lookup permission in hash table by the peer address */ static pj_turn_permission* lookup_permission_by_addr(pj_turn_allocation *alloc, - const pj_sockaddr_t *peer_addr, - unsigned addr_len) + const pj_sockaddr_t *peer_addr, + unsigned addr_len) { pj_turn_permission *perm; @@ -859,24 +858,24 @@ lookup_permission_by_addr(pj_turn_allocation *alloc, /* Lookup in peer hash table */ perm = (pj_turn_permission*) - pj_hash_get(alloc->peer_table, - pj_sockaddr_get_addr(peer_addr), - pj_sockaddr_get_addr_len(peer_addr), - NULL); + pj_hash_get(alloc->peer_table, + pj_sockaddr_get_addr(peer_addr), + pj_sockaddr_get_addr_len(peer_addr), + NULL); return perm ? check_permission_expiry(perm) : NULL; } /* Lookup permission in hash table by the channel number */ static pj_turn_permission* lookup_permission_by_chnum(pj_turn_allocation *alloc, - unsigned chnum) + unsigned chnum) { pj_uint16_t chnum16 = (pj_uint16_t)chnum; pj_turn_permission *perm; /* Lookup in peer hash table */ perm = (pj_turn_permission*) pj_hash_get(alloc->ch_table, &chnum16, - sizeof(chnum16), NULL); + sizeof(chnum16), NULL); return perm ? check_permission_expiry(perm) : NULL; } @@ -887,9 +886,9 @@ static pj_bool_t refresh_permission(pj_turn_permission *perm) { pj_gettimeofday(&perm->expiry); if (perm->channel == PJ_TURN_INVALID_CHANNEL) - perm->expiry.sec += PJ_TURN_PERM_TIMEOUT; + perm->expiry.sec += PJ_TURN_PERM_TIMEOUT; else - perm->expiry.sec += PJ_TURN_CHANNEL_TIMEOUT; + perm->expiry.sec += PJ_TURN_CHANNEL_TIMEOUT; return PJ_TRUE; } @@ -898,7 +897,7 @@ static pj_bool_t refresh_permission(pj_turn_permission *perm) * server upon receiving packet from a listener. */ PJ_DEF(void) pj_turn_allocation_on_rx_client_pkt(pj_turn_allocation *alloc, - pj_turn_pkt *pkt) + pj_turn_pkt *pkt) { pj_bool_t is_stun; pj_status_t status; @@ -910,85 +909,85 @@ PJ_DEF(void) pj_turn_allocation_on_rx_client_pkt(pj_turn_allocation *alloc, is_stun = ((*((pj_uint8_t*)pkt->pkt) & 0xC0) == 0); if (is_stun) { - /* - * This could be an incoming STUN requests or indications. - * Pass this through to the STUN session, which will call - * our stun_on_rx_request() or stun_on_rx_indication() - * callbacks. - * - * Note: currently it is necessary to specify the - * PJ_STUN_NO_FINGERPRINT_CHECK otherwise the FINGERPRINT - * attribute inside STUN Send Indication message will mess up - * with fingerprint checking. - */ - unsigned options = PJ_STUN_CHECK_PACKET | PJ_STUN_NO_FINGERPRINT_CHECK; - pj_size_t parsed_len = 0; - - if (pkt->transport->listener->tp_type == PJ_TURN_TP_UDP) - options |= PJ_STUN_IS_DATAGRAM; - - status = pj_stun_session_on_rx_pkt(alloc->sess, pkt->pkt, pkt->len, - options, NULL, &parsed_len, - &pkt->src.clt_addr, - pkt->src_addr_len); - - if (pkt->transport->listener->tp_type == PJ_TURN_TP_UDP) { - pkt->len = 0; - } else if (parsed_len > 0) { - if (parsed_len == pkt->len) { - pkt->len = 0; - } else { - pj_memmove(pkt->pkt, pkt->pkt+parsed_len, - pkt->len - parsed_len); - pkt->len -= parsed_len; - } - } - - if (status != PJ_SUCCESS) { - alloc_err(alloc, "Error handling STUN packet", status); - goto on_return; - } + /* + * This could be an incoming STUN requests or indications. + * Pass this through to the STUN session, which will call + * our stun_on_rx_request() or stun_on_rx_indication() + * callbacks. + * + * Note: currently it is necessary to specify the + * PJ_STUN_NO_FINGERPRINT_CHECK otherwise the FINGERPRINT + * attribute inside STUN Send Indication message will mess up + * with fingerprint checking. + */ + unsigned options = PJ_STUN_CHECK_PACKET | PJ_STUN_NO_FINGERPRINT_CHECK; + pj_size_t parsed_len = 0; + + if (pkt->transport->listener->tp_type == PJ_TURN_TP_UDP) + options |= PJ_STUN_IS_DATAGRAM; + + status = pj_stun_session_on_rx_pkt(alloc->sess, pkt->pkt, pkt->len, + options, NULL, &parsed_len, + &pkt->src.clt_addr, + pkt->src_addr_len); + + if (pkt->transport->listener->tp_type == PJ_TURN_TP_UDP) { + pkt->len = 0; + } else if (parsed_len > 0) { + if (parsed_len == pkt->len) { + pkt->len = 0; + } else { + pj_memmove(pkt->pkt, pkt->pkt+parsed_len, + pkt->len - parsed_len); + pkt->len -= parsed_len; + } + } + + if (status != PJ_SUCCESS) { + alloc_err(alloc, "Error handling STUN packet", status); + goto on_return; + } } else { - /* - * This is not a STUN packet, must be ChannelData packet. - */ - pj_turn_channel_data *cd = (pj_turn_channel_data*)pkt->pkt; - pj_turn_permission *perm; - pj_ssize_t len; - - pj_assert(sizeof(*cd)==4); - - /* For UDP check the packet length */ - if (alloc->transport->listener->tp_type == PJ_TURN_TP_UDP) { - if (pkt->len < pj_ntohs(cd->length)+sizeof(*cd)) { - PJ_LOG(4,(alloc->obj_name, - "ChannelData from %s discarded: UDP size error", - alloc->info)); - goto on_return; - } - } else { - pj_assert(!"Unsupported transport"); - goto on_return; - } - - perm = lookup_permission_by_chnum(alloc, pj_ntohs(cd->ch_number)); - if (!perm) { - /* Discard */ - PJ_LOG(4,(alloc->obj_name, - "ChannelData from %s discarded: ch#0x%x not found", - alloc->info, pj_ntohs(cd->ch_number))); - goto on_return; - } - - /* Relay the data */ - len = pj_ntohs(cd->length); - pj_sock_sendto(alloc->relay.tp.sock, cd+1, &len, 0, - &perm->hkey.peer_addr, - pj_sockaddr_get_len(&perm->hkey.peer_addr)); - - /* Refresh permission */ - refresh_permission(perm); + /* + * This is not a STUN packet, must be ChannelData packet. + */ + pj_turn_channel_data *cd = (pj_turn_channel_data*)pkt->pkt; + pj_turn_permission *perm; + pj_ssize_t len; + + pj_assert(sizeof(*cd)==4); + + /* For UDP check the packet length */ + if (alloc->transport->listener->tp_type == PJ_TURN_TP_UDP) { + if (pkt->len < pj_ntohs(cd->length)+sizeof(*cd)) { + PJ_LOG(4,(alloc->obj_name, + "ChannelData from %s discarded: UDP size error", + alloc->info)); + goto on_return; + } + } else { + pj_assert(!"Unsupported transport"); + goto on_return; + } + + perm = lookup_permission_by_chnum(alloc, pj_ntohs(cd->ch_number)); + if (!perm) { + /* Discard */ + PJ_LOG(4,(alloc->obj_name, + "ChannelData from %s discarded: ch#0x%x not found", + alloc->info, pj_ntohs(cd->ch_number))); + goto on_return; + } + + /* Relay the data */ + len = pj_ntohs(cd->length); + pj_sock_sendto(alloc->relay.tp.sock, cd+1, &len, 0, + &perm->hkey.peer_addr, + pj_sockaddr_get_len(&perm->hkey.peer_addr)); + + /* Refresh permission */ + refresh_permission(perm); } on_return: @@ -1002,71 +1001,71 @@ PJ_DEF(void) pj_turn_allocation_on_rx_client_pkt(pj_turn_allocation *alloc, * on_rx_from_peer(). */ static void handle_peer_pkt(pj_turn_allocation *alloc, - pj_turn_relay_res *rel, - char *pkt, pj_size_t len, - const pj_sockaddr *src_addr) + pj_turn_relay_res *rel, + char *pkt, pj_size_t len, + const pj_sockaddr *src_addr) { pj_turn_permission *perm; /* Lookup permission */ perm = lookup_permission_by_addr(alloc, src_addr, - pj_sockaddr_get_len(src_addr)); + pj_sockaddr_get_len(src_addr)); if (perm == NULL) { - /* No permission, discard data */ - return; + /* No permission, discard data */ + return; } /* Send Data Indication or ChannelData, depends on whether * this permission is attached to a channel number. */ if (perm->channel != PJ_TURN_INVALID_CHANNEL) { - /* Send ChannelData */ - pj_turn_channel_data *cd = (pj_turn_channel_data*)rel->tp.tx_pkt; - - if (len > PJ_TURN_MAX_PKT_LEN) { - char peer_addr[80]; - pj_sockaddr_print(src_addr, peer_addr, sizeof(peer_addr), 3); - PJ_LOG(4,(alloc->obj_name, "Client %s: discarded data from %s " - "because it's too long (%d bytes)", - alloc->info, peer_addr, len)); - return; - } - - /* Init header */ - cd->ch_number = pj_htons(perm->channel); - cd->length = pj_htons((pj_uint16_t)len); - - /* Copy data */ - pj_memcpy(rel->tp.tx_pkt+sizeof(pj_turn_channel_data), pkt, len); - - /* Send to client */ - alloc->transport->sendto(alloc->transport, rel->tp.tx_pkt, - len+sizeof(pj_turn_channel_data), 0, - &alloc->hkey.clt_addr, - pj_sockaddr_get_len(&alloc->hkey.clt_addr)); + /* Send ChannelData */ + pj_turn_channel_data *cd = (pj_turn_channel_data*)rel->tp.tx_pkt; + + if (len > PJ_TURN_MAX_PKT_LEN) { + char peer_addr[80]; + pj_sockaddr_print(src_addr, peer_addr, sizeof(peer_addr), 3); + PJ_LOG(4,(alloc->obj_name, "Client %s: discarded data from %s " + "because it's too long (%d bytes)", + alloc->info, peer_addr, len)); + return; + } + + /* Init header */ + cd->ch_number = pj_htons(perm->channel); + cd->length = pj_htons((pj_uint16_t)len); + + /* Copy data */ + pj_memcpy(rel->tp.tx_pkt+sizeof(pj_turn_channel_data), pkt, len); + + /* Send to client */ + alloc->transport->sendto(alloc->transport, rel->tp.tx_pkt, + len+sizeof(pj_turn_channel_data), 0, + &alloc->hkey.clt_addr, + pj_sockaddr_get_len(&alloc->hkey.clt_addr)); } else { - /* Send Data Indication */ - pj_stun_tx_data *tdata; - pj_status_t status; - - status = pj_stun_session_create_ind(alloc->sess, - PJ_STUN_DATA_INDICATION, &tdata); - if (status != PJ_SUCCESS) { - alloc_err(alloc, "Error creating Data indication", status); - return; - } - - pj_stun_msg_add_sockaddr_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_XOR_PEER_ADDR, PJ_TRUE, - src_addr, pj_sockaddr_get_len(src_addr)); - pj_stun_msg_add_binary_attr(tdata->pool, tdata->msg, - PJ_STUN_ATTR_DATA, - (const pj_uint8_t*)pkt, len); - - pj_stun_session_send_msg(alloc->sess, NULL, PJ_FALSE, - PJ_FALSE, &alloc->hkey.clt_addr, - pj_sockaddr_get_len(&alloc->hkey.clt_addr), - tdata); + /* Send Data Indication */ + pj_stun_tx_data *tdata; + pj_status_t status; + + status = pj_stun_session_create_ind(alloc->sess, + PJ_STUN_DATA_INDICATION, &tdata); + if (status != PJ_SUCCESS) { + alloc_err(alloc, "Error creating Data indication", status); + return; + } + + pj_stun_msg_add_sockaddr_attr(tdata->pool, tdata->msg, + PJ_STUN_ATTR_XOR_PEER_ADDR, PJ_TRUE, + src_addr, pj_sockaddr_get_len(src_addr)); + pj_stun_msg_add_binary_attr(tdata->pool, tdata->msg, + PJ_STUN_ATTR_DATA, + (const pj_uint8_t*)pkt, len); + + pj_stun_session_send_msg(alloc->sess, NULL, PJ_FALSE, + PJ_FALSE, &alloc->hkey.clt_addr, + pj_sockaddr_get_len(&alloc->hkey.clt_addr), + tdata); } } @@ -1086,21 +1085,21 @@ static void on_rx_from_peer(pj_ioqueue_key_t *key, pj_lock_acquire(rel->allocation->lock); do { - if (bytes_read > 0) { - handle_peer_pkt(rel->allocation, rel, rel->tp.rx_pkt, - bytes_read, &rel->tp.src_addr); - } - - /* Read next packet */ - bytes_read = sizeof(rel->tp.rx_pkt); - rel->tp.src_addr_len = sizeof(rel->tp.src_addr); - status = pj_ioqueue_recvfrom(key, op_key, - rel->tp.rx_pkt, &bytes_read, 0, - &rel->tp.src_addr, - &rel->tp.src_addr_len); - - if (status != PJ_EPENDING && status != PJ_SUCCESS) - bytes_read = -status; + if (bytes_read > 0) { + handle_peer_pkt(rel->allocation, rel, rel->tp.rx_pkt, + bytes_read, &rel->tp.src_addr); + } + + /* Read next packet */ + bytes_read = sizeof(rel->tp.rx_pkt); + rel->tp.src_addr_len = sizeof(rel->tp.src_addr); + status = pj_ioqueue_recvfrom(key, op_key, + rel->tp.rx_pkt, &bytes_read, 0, + &rel->tp.src_addr, + &rel->tp.src_addr_len); + + if (status != PJ_EPENDING && status != PJ_SUCCESS) + bytes_read = -status; } while (status != PJ_EPENDING && status != PJ_ECANCELLED); @@ -1113,11 +1112,11 @@ static void on_rx_from_peer(pj_ioqueue_key_t *key, * a STUN message towards the client. */ static pj_status_t stun_on_send_msg(pj_stun_session *sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len) + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len) { pj_turn_allocation *alloc; @@ -1126,7 +1125,7 @@ static pj_status_t stun_on_send_msg(pj_stun_session *sess, alloc = (pj_turn_allocation*) pj_stun_session_get_user_data(sess); return alloc->transport->sendto(alloc->transport, pkt, pkt_size, 0, - dst_addr, addr_len); + dst_addr, addr_len); } /* @@ -1135,12 +1134,12 @@ static pj_status_t stun_on_send_msg(pj_stun_session *sess, * processing in pj_turn_allocation_on_rx_client_pkt(). */ static pj_status_t stun_on_rx_request(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_rx_data *rdata, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_rx_data *rdata, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { const pj_stun_msg *msg = rdata->msg; pj_turn_allocation *alloc; @@ -1155,155 +1154,155 @@ static pj_status_t stun_on_rx_request(pj_stun_session *sess, /* Refuse to serve any request if we've been shutdown */ if (alloc->relay.lifetime == 0) { - /* Reject with 437 if we're shutting down */ - send_reply_err(alloc, rdata, PJ_TRUE, - PJ_STUN_SC_ALLOCATION_MISMATCH, NULL); - return PJ_SUCCESS; + /* Reject with 437 if we're shutting down */ + send_reply_err(alloc, rdata, PJ_TRUE, + PJ_STUN_SC_ALLOCATION_MISMATCH, NULL); + return PJ_SUCCESS; } if (msg->hdr.type == PJ_STUN_REFRESH_REQUEST) { - /* - * Handle REFRESH request - */ - pj_stun_lifetime_attr *lifetime; - pj_stun_bandwidth_attr *bandwidth; + /* + * Handle REFRESH request + */ + pj_stun_lifetime_attr *lifetime; + pj_stun_bandwidth_attr *bandwidth; - /* Get LIFETIME attribute */ - lifetime = (pj_stun_lifetime_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_LIFETIME, 0); + /* Get LIFETIME attribute */ + lifetime = (pj_stun_lifetime_attr*) + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_LIFETIME, 0); - /* Get BANDWIDTH attribute */ - bandwidth = (pj_stun_bandwidth_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_BANDWIDTH, 0); + /* Get BANDWIDTH attribute */ + bandwidth = (pj_stun_bandwidth_attr*) + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_BANDWIDTH, 0); - /* TODO: process bandwidth */ - PJ_UNUSED_ARG(bandwidth); + /* TODO: process bandwidth */ + PJ_UNUSED_ARG(bandwidth); - if (lifetime && lifetime->value==0) { - /* - * This is deallocation request. - */ - alloc->relay.lifetime = 0; + if (lifetime && lifetime->value==0) { + /* + * This is deallocation request. + */ + alloc->relay.lifetime = 0; - /* Respond first */ - send_reply_ok(alloc, rdata); + /* Respond first */ + send_reply_ok(alloc, rdata); - /* Shutdown allocation */ - PJ_LOG(4,(alloc->obj_name, - "Client %s request to dealloc, shutting down", - alloc->info)); + /* Shutdown allocation */ + PJ_LOG(4,(alloc->obj_name, + "Client %s request to dealloc, shutting down", + alloc->info)); - alloc_shutdown(alloc); + alloc_shutdown(alloc); - } else { - /* - * This is a refresh request. - */ + } else { + /* + * This is a refresh request. + */ - /* Update lifetime */ - if (lifetime) { - alloc->relay.lifetime = lifetime->value; - } + /* Update lifetime */ + if (lifetime) { + alloc->relay.lifetime = lifetime->value; + } - /* Update bandwidth */ - // TODO: + /* Update bandwidth */ + // TODO: - /* Update expiration timer */ - resched_timeout(alloc); + /* Update expiration timer */ + resched_timeout(alloc); - /* Send reply */ - send_reply_ok(alloc, rdata); - } + /* Send reply */ + send_reply_ok(alloc, rdata); + } } else if (msg->hdr.type == PJ_STUN_CHANNEL_BIND_REQUEST) { - /* - * ChannelBind request. - */ - pj_stun_channel_number_attr *ch_attr; - pj_stun_xor_peer_addr_attr *peer_attr; - pj_turn_permission *p1, *p2; - - ch_attr = (pj_stun_channel_number_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_CHANNEL_NUMBER, 0); - peer_attr = (pj_stun_xor_peer_addr_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_XOR_PEER_ADDR, 0); - - if (!ch_attr || !peer_attr) { - send_reply_err(alloc, rdata, PJ_TRUE, - PJ_STUN_SC_BAD_REQUEST, NULL); - return PJ_SUCCESS; - } - - /* Find permission with the channel number */ - p1 = lookup_permission_by_chnum(alloc, PJ_STUN_GET_CH_NB(ch_attr->value)); - - /* If permission is found, this is supposed to be a channel bind - * refresh. Make sure it's for the same peer. - */ - if (p1) { - if (pj_sockaddr_cmp(&p1->hkey.peer_addr, &peer_attr->sockaddr)) { - /* Address mismatch. Send 400 */ - send_reply_err(alloc, rdata, PJ_TRUE, - PJ_STUN_SC_BAD_REQUEST, - "Peer address mismatch"); - return PJ_SUCCESS; - } - - /* Refresh permission */ - refresh_permission(p1); - - /* Send response */ - send_reply_ok(alloc, rdata); - - /* Done */ - return PJ_SUCCESS; - } - - /* If permission is not found, create a new one. Make sure the peer - * has not alreadyy assigned with a channel number. - */ - p2 = lookup_permission_by_addr(alloc, &peer_attr->sockaddr, - pj_sockaddr_get_len(&peer_attr->sockaddr)); - if (p2 && p2->channel != PJ_TURN_INVALID_CHANNEL) { - send_reply_err(alloc, rdata, PJ_TRUE, PJ_STUN_SC_BAD_REQUEST, - "Peer address already assigned a channel number"); - return PJ_SUCCESS; - } - - /* Create permission if it doesn't exist */ - if (!p2) { - p2 = create_permission(alloc, &peer_attr->sockaddr, - pj_sockaddr_get_len(&peer_attr->sockaddr)); - if (!p2) - return PJ_SUCCESS; - } - - /* Assign channel number to permission */ - p2->channel = PJ_STUN_GET_CH_NB(ch_attr->value); - - /* Register to hash table */ - pj_assert(sizeof(p2->channel)==2); - pj_hash_set(alloc->pool, alloc->ch_table, &p2->channel, - sizeof(p2->channel), 0, p2); - - /* Update */ - refresh_permission(p2); - - /* Reply */ - send_reply_ok(alloc, rdata); - - return PJ_SUCCESS; + /* + * ChannelBind request. + */ + pj_stun_channel_number_attr *ch_attr; + pj_stun_xor_peer_addr_attr *peer_attr; + pj_turn_permission *p1, *p2; + + ch_attr = (pj_stun_channel_number_attr*) + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_CHANNEL_NUMBER, 0); + peer_attr = (pj_stun_xor_peer_addr_attr*) + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_XOR_PEER_ADDR, 0); + + if (!ch_attr || !peer_attr) { + send_reply_err(alloc, rdata, PJ_TRUE, + PJ_STUN_SC_BAD_REQUEST, NULL); + return PJ_SUCCESS; + } + + /* Find permission with the channel number */ + p1 = lookup_permission_by_chnum(alloc, PJ_STUN_GET_CH_NB(ch_attr->value)); + + /* If permission is found, this is supposed to be a channel bind + * refresh. Make sure it's for the same peer. + */ + if (p1) { + if (pj_sockaddr_cmp(&p1->hkey.peer_addr, &peer_attr->sockaddr)) { + /* Address mismatch. Send 400 */ + send_reply_err(alloc, rdata, PJ_TRUE, + PJ_STUN_SC_BAD_REQUEST, + "Peer address mismatch"); + return PJ_SUCCESS; + } + + /* Refresh permission */ + refresh_permission(p1); + + /* Send response */ + send_reply_ok(alloc, rdata); + + /* Done */ + return PJ_SUCCESS; + } + + /* If permission is not found, create a new one. Make sure the peer + * has not alreadyy assigned with a channel number. + */ + p2 = lookup_permission_by_addr(alloc, &peer_attr->sockaddr, + pj_sockaddr_get_len(&peer_attr->sockaddr)); + if (p2 && p2->channel != PJ_TURN_INVALID_CHANNEL) { + send_reply_err(alloc, rdata, PJ_TRUE, PJ_STUN_SC_BAD_REQUEST, + "Peer address already assigned a channel number"); + return PJ_SUCCESS; + } + + /* Create permission if it doesn't exist */ + if (!p2) { + p2 = create_permission(alloc, &peer_attr->sockaddr, + pj_sockaddr_get_len(&peer_attr->sockaddr)); + if (!p2) + return PJ_SUCCESS; + } + + /* Assign channel number to permission */ + p2->channel = PJ_STUN_GET_CH_NB(ch_attr->value); + + /* Register to hash table */ + pj_assert(sizeof(p2->channel)==2); + pj_hash_set(alloc->pool, alloc->ch_table, &p2->channel, + sizeof(p2->channel), 0, p2); + + /* Update */ + refresh_permission(p2); + + /* Reply */ + send_reply_ok(alloc, rdata); + + return PJ_SUCCESS; } else if (msg->hdr.type == PJ_STUN_ALLOCATE_REQUEST) { - /* Respond with 437 (section 6.3 turn-07) */ - send_reply_err(alloc, rdata, PJ_TRUE, PJ_STUN_SC_ALLOCATION_MISMATCH, - NULL); + /* Respond with 437 (section 6.3 turn-07) */ + send_reply_err(alloc, rdata, PJ_TRUE, PJ_STUN_SC_ALLOCATION_MISMATCH, + NULL); } else { - /* Respond with Bad Request? */ - send_reply_err(alloc, rdata, PJ_TRUE, PJ_STUN_SC_BAD_REQUEST, NULL); + /* Respond with Bad Request? */ + send_reply_err(alloc, rdata, PJ_TRUE, PJ_STUN_SC_BAD_REQUEST, NULL); } @@ -1316,12 +1315,12 @@ static pj_status_t stun_on_rx_request(pj_stun_session *sess, * processing in pj_turn_allocation_on_rx_client_pkt(). */ static pj_status_t stun_on_rx_indication(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_msg *msg, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_msg *msg, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_stun_xor_peer_addr_attr *peer_attr; pj_stun_data_attr *data_attr; @@ -1339,40 +1338,40 @@ static pj_status_t stun_on_rx_indication(pj_stun_session *sess, /* Only expect Send Indication */ if (msg->hdr.type != PJ_STUN_SEND_INDICATION) { - /* Ignore */ - return PJ_SUCCESS; + /* Ignore */ + return PJ_SUCCESS; } /* Get XOR-PEER-ADDRESS attribute */ peer_attr = (pj_stun_xor_peer_addr_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_XOR_PEER_ADDR, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_XOR_PEER_ADDR, 0); /* MUST have XOR-PEER-ADDRESS attribute */ if (!peer_attr) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Get DATA attribute */ data_attr = (pj_stun_data_attr*) - pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_DATA, 0); + pj_stun_msg_find_attr(msg, PJ_STUN_ATTR_DATA, 0); /* Create/update/refresh the permission */ perm = lookup_permission_by_addr(alloc, &peer_attr->sockaddr, - pj_sockaddr_get_len(&peer_attr->sockaddr)); + pj_sockaddr_get_len(&peer_attr->sockaddr)); if (perm == NULL) { - perm = create_permission(alloc, &peer_attr->sockaddr, - pj_sockaddr_get_len(&peer_attr->sockaddr)); + perm = create_permission(alloc, &peer_attr->sockaddr, + pj_sockaddr_get_len(&peer_attr->sockaddr)); } refresh_permission(perm); /* Return if we don't have data */ if (data_attr == NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Relay the data to peer */ len = data_attr->length; pj_sock_sendto(alloc->relay.tp.sock, data_attr->data, - &len, 0, &peer_attr->sockaddr, - pj_sockaddr_get_len(&peer_attr->sockaddr)); + &len, 0, &peer_attr->sockaddr, + pj_sockaddr_get_len(&peer_attr->sockaddr)); return PJ_SUCCESS; } diff --git a/pjnath/src/pjturn-srv/auth.c b/pjnath/src/pjturn-srv/auth.c index 82e182d0ac..e932165c00 100644 --- a/pjnath/src/pjturn-srv/auth.c +++ b/pjnath/src/pjturn-srv/auth.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,10 +20,10 @@ #include -#define MAX_REALM 80 -#define MAX_USERNAME 32 -#define MAX_PASSWORD 32 -#define MAX_NONCE 32 +#define MAX_REALM 80 +#define MAX_USERNAME 32 +#define MAX_PASSWORD 32 +#define MAX_NONCE 32 static char g_realm[MAX_REALM]; @@ -39,9 +38,9 @@ static struct cred_t { "701", "701" } }; -#define THIS_FILE "auth.c" -#define THE_NONCE "pjnath" -#define LOG(expr) PJ_LOG(3,expr) +#define THIS_FILE "auth.c" +#define THE_NONCE "pjnath" +#define LOG(expr) PJ_LOG(3,expr) /* @@ -68,9 +67,9 @@ PJ_DEF(void) pj_turn_auth_dinit(void) * server needs to challenge the request with 401 response. */ PJ_DEF(pj_status_t) pj_turn_get_auth(void *user_data, - pj_pool_t *pool, - pj_str_t *realm, - pj_str_t *nonce) + pj_pool_t *pool, + pj_str_t *realm, + pj_str_t *nonce) { PJ_UNUSED_ARG(user_data); PJ_UNUSED_ARG(pool); @@ -86,12 +85,12 @@ PJ_DEF(pj_status_t) pj_turn_get_auth(void *user_data, * This function is also used to check whether the username is valid. */ PJ_DEF(pj_status_t) pj_turn_get_password(const pj_stun_msg *msg, - void *user_data, - const pj_str_t *realm, - const pj_str_t *username, - pj_pool_t *pool, - pj_stun_passwd_type *data_type, - pj_str_t *data) + void *user_data, + const pj_str_t *realm, + const pj_str_t *username, + pj_pool_t *pool, + pj_stun_passwd_type *data_type, + pj_str_t *data) { unsigned i; @@ -100,21 +99,21 @@ PJ_DEF(pj_status_t) pj_turn_get_password(const pj_stun_msg *msg, PJ_UNUSED_ARG(pool); if (pj_stricmp2(realm, g_realm)) { - LOG((THIS_FILE, "auth error: invalid realm '%.*s'", - (int)realm->slen, realm->ptr)); - return PJ_EINVAL; + LOG((THIS_FILE, "auth error: invalid realm '%.*s'", + (int)realm->slen, realm->ptr)); + return PJ_EINVAL; } for (i=0; islen, username->ptr)); + (int)username->slen, username->ptr)); return PJ_ENOTFOUND; } @@ -124,10 +123,10 @@ PJ_DEF(pj_status_t) pj_turn_get_password(const pj_stun_msg *msg, * PJ_FALSE, 438 (Stale Nonce) response will be created. */ PJ_DEF(pj_bool_t) pj_turn_verify_nonce(const pj_stun_msg *msg, - void *user_data, - const pj_str_t *realm, - const pj_str_t *username, - const pj_str_t *nonce) + void *user_data, + const pj_str_t *realm, + const pj_str_t *username, + const pj_str_t *nonce) { PJ_UNUSED_ARG(msg); PJ_UNUSED_ARG(user_data); @@ -135,9 +134,9 @@ PJ_DEF(pj_bool_t) pj_turn_verify_nonce(const pj_stun_msg *msg, PJ_UNUSED_ARG(username); if (pj_stricmp2(nonce, THE_NONCE)) { - LOG((THIS_FILE, "auth error: invalid nonce '%.*s'", - (int)nonce->slen, nonce->ptr)); - return PJ_FALSE; + LOG((THIS_FILE, "auth error: invalid nonce '%.*s'", + (int)nonce->slen, nonce->ptr)); + return PJ_FALSE; } return PJ_TRUE; diff --git a/pjnath/src/pjturn-srv/auth.h b/pjnath/src/pjturn-srv/auth.h index c403952e5a..3527b3f9b4 100644 --- a/pjnath/src/pjturn-srv/auth.h +++ b/pjnath/src/pjturn-srv/auth.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,7 +24,7 @@ /** * Initialize TURN authentication subsystem. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pj_turn_auth_init(const char *realm); @@ -38,79 +37,79 @@ PJ_DECL(void) pj_turn_auth_dinit(void); * This function is called by pj_stun_verify_credential() when * server needs to challenge the request with 401 response. * - * @param user_data Should be ignored. - * @param pool Pool to allocate memory. - * @param realm On return, the function should fill in with - * realm if application wants to use long term - * credential. Otherwise application should set - * empty string for the realm. - * @param nonce On return, if application wants to use long - * term credential, it MUST fill in the nonce - * with some value. Otherwise if short term - * credential is wanted, it MAY set this value. - * If short term credential is wanted and the - * application doesn't want to include NONCE, - * then it must set this to empty string. + * @param user_data Should be ignored. + * @param pool Pool to allocate memory. + * @param realm On return, the function should fill in with + * realm if application wants to use long term + * credential. Otherwise application should set + * empty string for the realm. + * @param nonce On return, if application wants to use long + * term credential, it MUST fill in the nonce + * with some value. Otherwise if short term + * credential is wanted, it MAY set this value. + * If short term credential is wanted and the + * application doesn't want to include NONCE, + * then it must set this to empty string. * - * @return The callback should return PJ_SUCCESS, or - * otherwise response message will not be - * created. + * @return The callback should return PJ_SUCCESS, or + * otherwise response message will not be + * created. */ PJ_DECL(pj_status_t) pj_turn_get_auth(void *user_data, - pj_pool_t *pool, - pj_str_t *realm, - pj_str_t *nonce); + pj_pool_t *pool, + pj_str_t *realm, + pj_str_t *nonce); /** * This function is called to get the password for the specified username. * This function is also used to check whether the username is valid. * - * @param msg The STUN message where the password will be - * applied to. - * @param user_data Should be ignored. - * @param realm The realm as specified in the message. - * @param username The username as specified in the message. - * @param pool Pool to allocate memory when necessary. - * @param data_type On return, application should fill up this - * argument with the type of data (which should - * be zero if data is a plaintext password). - * @param data On return, application should fill up this - * argument with the password according to - * data_type. + * @param msg The STUN message where the password will be + * applied to. + * @param user_data Should be ignored. + * @param realm The realm as specified in the message. + * @param username The username as specified in the message. + * @param pool Pool to allocate memory when necessary. + * @param data_type On return, application should fill up this + * argument with the type of data (which should + * be zero if data is a plaintext password). + * @param data On return, application should fill up this + * argument with the password according to + * data_type. * - * @return The callback should return PJ_SUCCESS if - * username has been successfully verified - * and password was obtained. If non-PJ_SUCCESS - * is returned, it is assumed that the - * username is not valid. + * @return The callback should return PJ_SUCCESS if + * username has been successfully verified + * and password was obtained. If non-PJ_SUCCESS + * is returned, it is assumed that the + * username is not valid. */ PJ_DECL(pj_status_t) pj_turn_get_password(const pj_stun_msg *msg, - void *user_data, - const pj_str_t *realm, - const pj_str_t *username, - pj_pool_t *pool, - pj_stun_passwd_type *data_type, - pj_str_t *data); + void *user_data, + const pj_str_t *realm, + const pj_str_t *username, + pj_pool_t *pool, + pj_stun_passwd_type *data_type, + pj_str_t *data); /** * This function will be called to verify that the NONCE given * in the message can be accepted. If this callback returns * PJ_FALSE, 438 (Stale Nonce) response will be created. * - * @param msg The STUN message where the nonce was received. - * @param user_data Should be ignored. - * @param realm The realm as specified in the message. - * @param username The username as specified in the message. - * @param nonce The nonce to be verified. + * @param msg The STUN message where the nonce was received. + * @param user_data Should be ignored. + * @param realm The realm as specified in the message. + * @param username The username as specified in the message. + * @param nonce The nonce to be verified. * - * @return The callback MUST return non-zero if the - * NONCE can be accepted. + * @return The callback MUST return non-zero if the + * NONCE can be accepted. */ PJ_DECL(pj_bool_t) pj_turn_verify_nonce(const pj_stun_msg *msg, - void *user_data, - const pj_str_t *realm, - const pj_str_t *username, - const pj_str_t *nonce); + void *user_data, + const pj_str_t *realm, + const pj_str_t *username, + const pj_str_t *nonce); -#endif /* __PJ_TURN_SRV_AUTH_H__ */ +#endif /* __PJ_TURN_SRV_AUTH_H__ */ diff --git a/pjnath/src/pjturn-srv/listener_tcp.c b/pjnath/src/pjturn-srv/listener_tcp.c index 796ed471b7..906874ce25 100644 --- a/pjnath/src/pjturn-srv/listener_tcp.c +++ b/pjnath/src/pjturn-srv/listener_tcp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,31 +23,31 @@ struct accept_op { - pj_ioqueue_op_key_t op_key; - pj_sock_t sock; - pj_sockaddr src_addr; - int src_addr_len; + pj_ioqueue_op_key_t op_key; + pj_sock_t sock; + pj_sockaddr src_addr; + int src_addr_len; }; struct tcp_listener { - pj_turn_listener base; - pj_ioqueue_key_t *key; - unsigned accept_cnt; - struct accept_op *accept_op; /* Array of accept_op's */ + pj_turn_listener base; + pj_ioqueue_key_t *key; + unsigned accept_cnt; + struct accept_op *accept_op; /* Array of accept_op's */ }; static void lis_on_accept_complete(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_sock_t sock, - pj_status_t status); + pj_ioqueue_op_key_t *op_key, + pj_sock_t sock, + pj_status_t status); static pj_status_t lis_destroy(pj_turn_listener *listener); static void transport_create(pj_sock_t sock, pj_turn_listener *lis, - pj_sockaddr_t *src_addr, int src_addr_len); + pj_sockaddr_t *src_addr, int src_addr_len); static void show_err(const char *sender, const char *title, - pj_status_t status) + pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; @@ -61,12 +60,12 @@ static void show_err(const char *sender, const char *title, * Create a new listener on the specified port. */ PJ_DEF(pj_status_t) pj_turn_listener_create_tcp(pj_turn_srv *srv, - int af, - const pj_str_t *bound_addr, - unsigned port, - unsigned concurrency_cnt, - unsigned flags, - pj_turn_listener **p_listener) + int af, + const pj_str_t *bound_addr, + unsigned port, + unsigned concurrency_cnt, + unsigned flags, + pj_turn_listener **p_listener) { pj_pool_t *pool; struct tcp_listener *tcp_lis; @@ -90,49 +89,49 @@ PJ_DEF(pj_status_t) pj_turn_listener_create_tcp(pj_turn_srv *srv, /* Create socket */ status = pj_sock_socket(af, pj_SOCK_STREAM(), 0, &tcp_lis->base.sock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Init bind address */ status = pj_sockaddr_init(af, &tcp_lis->base.addr, bound_addr, - (pj_uint16_t)port); + (pj_uint16_t)port); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create info */ pj_ansi_strcpy(tcp_lis->base.info, "TCP:"); pj_sockaddr_print(&tcp_lis->base.addr, tcp_lis->base.info+4, - sizeof(tcp_lis->base.info)-4, 3); + sizeof(tcp_lis->base.info)-4, 3); /* Bind socket */ status = pj_sock_bind(tcp_lis->base.sock, &tcp_lis->base.addr, - pj_sockaddr_get_len(&tcp_lis->base.addr)); + pj_sockaddr_get_len(&tcp_lis->base.addr)); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Listen() */ status = pj_sock_listen(tcp_lis->base.sock, 5); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Register to ioqueue */ pj_bzero(&ioqueue_cb, sizeof(ioqueue_cb)); ioqueue_cb.on_accept_complete = &lis_on_accept_complete; status = pj_ioqueue_register_sock(pool, srv->core.ioqueue, tcp_lis->base.sock, - tcp_lis, &ioqueue_cb, &tcp_lis->key); + tcp_lis, &ioqueue_cb, &tcp_lis->key); /* Create op keys */ tcp_lis->accept_op = (struct accept_op*)pj_pool_calloc(pool, concurrency_cnt, - sizeof(struct accept_op)); + sizeof(struct accept_op)); /* Create each accept_op and kick off read operation */ for (i=0; ikey, &tcp_lis->accept_op[i].op_key, - PJ_INVALID_SOCKET, PJ_EPENDING); + lis_on_accept_complete(tcp_lis->key, &tcp_lis->accept_op[i].op_key, + PJ_INVALID_SOCKET, PJ_EPENDING); } /* Done */ PJ_LOG(4,(tcp_lis->base.obj_name, "Listener %s created", - tcp_lis->base.info)); + tcp_lis->base.info)); *p_listener = &tcp_lis->base; return PJ_SUCCESS; @@ -153,26 +152,26 @@ static pj_status_t lis_destroy(pj_turn_listener *listener) unsigned i; if (tcp_lis->key) { - pj_ioqueue_unregister(tcp_lis->key); - tcp_lis->key = NULL; - tcp_lis->base.sock = PJ_INVALID_SOCKET; + pj_ioqueue_unregister(tcp_lis->key); + tcp_lis->key = NULL; + tcp_lis->base.sock = PJ_INVALID_SOCKET; } else if (tcp_lis->base.sock != PJ_INVALID_SOCKET) { - pj_sock_close(tcp_lis->base.sock); - tcp_lis->base.sock = PJ_INVALID_SOCKET; + pj_sock_close(tcp_lis->base.sock); + tcp_lis->base.sock = PJ_INVALID_SOCKET; } for (i=0; iaccept_cnt; ++i) { - /* Nothing to do */ + /* Nothing to do */ } if (tcp_lis->base.pool) { - pj_pool_t *pool = tcp_lis->base.pool; + pj_pool_t *pool = tcp_lis->base.pool; - PJ_LOG(4,(tcp_lis->base.obj_name, "Listener %s destroyed", - tcp_lis->base.info)); + PJ_LOG(4,(tcp_lis->base.obj_name, "Listener %s destroyed", + tcp_lis->base.info)); - tcp_lis->base.pool = NULL; - pj_pool_release(pool); + tcp_lis->base.pool = NULL; + pj_pool_release(pool); } return PJ_SUCCESS; } @@ -182,9 +181,9 @@ static pj_status_t lis_destroy(pj_turn_listener *listener) * Callback on new TCP connection. */ static void lis_on_accept_complete(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_sock_t sock, - pj_status_t status) + pj_ioqueue_op_key_t *op_key, + pj_sock_t sock, + pj_status_t status) { struct tcp_listener *tcp_lis; struct accept_op *accept_op = (struct accept_op*) op_key; @@ -194,27 +193,27 @@ static void lis_on_accept_complete(pj_ioqueue_key_t *key, PJ_UNUSED_ARG(sock); do { - /* Report new connection. */ - if (status == PJ_SUCCESS) { - char addr[PJ_INET6_ADDRSTRLEN+8]; - PJ_LOG(5,(tcp_lis->base.obj_name, "Incoming TCP from %s", - pj_sockaddr_print(&accept_op->src_addr, addr, - sizeof(addr), 3))); - transport_create(accept_op->sock, &tcp_lis->base, - &accept_op->src_addr, accept_op->src_addr_len); - } else if (status != PJ_EPENDING) { - show_err(tcp_lis->base.obj_name, "accept()", status); - } - - /* Prepare next accept() */ - accept_op->src_addr_len = sizeof(accept_op->src_addr); - status = pj_ioqueue_accept(key, op_key, &accept_op->sock, - NULL, - &accept_op->src_addr, - &accept_op->src_addr_len); + /* Report new connection. */ + if (status == PJ_SUCCESS) { + char addr[PJ_INET6_ADDRSTRLEN+8]; + PJ_LOG(5,(tcp_lis->base.obj_name, "Incoming TCP from %s", + pj_sockaddr_print(&accept_op->src_addr, addr, + sizeof(addr), 3))); + transport_create(accept_op->sock, &tcp_lis->base, + &accept_op->src_addr, accept_op->src_addr_len); + } else if (status != PJ_EPENDING) { + show_err(tcp_lis->base.obj_name, "accept()", status); + } + + /* Prepare next accept() */ + accept_op->src_addr_len = sizeof(accept_op->src_addr); + status = pj_ioqueue_accept(key, op_key, &accept_op->sock, + NULL, + &accept_op->src_addr, + &accept_op->src_addr_len); } while (status != PJ_EPENDING && status != PJ_ECANCELLED && - status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)); + status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)); } @@ -237,46 +236,46 @@ enum struct recv_op { - pj_ioqueue_op_key_t op_key; - pj_turn_pkt pkt; + pj_ioqueue_op_key_t op_key; + pj_turn_pkt pkt; }; struct tcp_transport { - pj_turn_transport base; - pj_pool_t *pool; - pj_timer_entry timer; + pj_turn_transport base; + pj_pool_t *pool; + pj_timer_entry timer; - pj_turn_allocation *alloc; - int ref_cnt; + pj_turn_allocation *alloc; + int ref_cnt; - pj_sock_t sock; - pj_ioqueue_key_t *key; - struct recv_op recv_op; - pj_ioqueue_op_key_t send_op; + pj_sock_t sock; + pj_ioqueue_key_t *key; + struct recv_op recv_op; + pj_ioqueue_op_key_t send_op; }; static void tcp_on_read_complete(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_read); + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_read); static pj_status_t tcp_sendto(pj_turn_transport *tp, - const void *packet, - pj_size_t size, - unsigned flag, - const pj_sockaddr_t *addr, - int addr_len); + const void *packet, + pj_size_t size, + unsigned flag, + const pj_sockaddr_t *addr, + int addr_len); static void tcp_destroy(struct tcp_transport *tcp); static void tcp_add_ref(pj_turn_transport *tp, - pj_turn_allocation *alloc); + pj_turn_allocation *alloc); static void tcp_dec_ref(pj_turn_transport *tp, - pj_turn_allocation *alloc); + pj_turn_allocation *alloc); static void timer_callback(pj_timer_heap_t *timer_heap, - pj_timer_entry *entry); + pj_timer_entry *entry); static void transport_create(pj_sock_t sock, pj_turn_listener *lis, - pj_sockaddr_t *src_addr, int src_addr_len) + pj_sockaddr_t *src_addr, int src_addr_len) { pj_pool_t *pool; struct tcp_transport *tcp; @@ -301,15 +300,15 @@ static void transport_create(pj_sock_t sock, pj_turn_listener *lis, pj_bzero(&cb, sizeof(cb)); cb.on_read_complete = &tcp_on_read_complete; status = pj_ioqueue_register_sock(pool, lis->server->core.ioqueue, sock, - tcp, &cb, &tcp->key); + tcp, &cb, &tcp->key); if (status != PJ_SUCCESS) { - tcp_destroy(tcp); - return; + tcp_destroy(tcp); + return; } /* Init pkt */ tcp->recv_op.pkt.pool = pj_pool_create(lis->server->core.pf, "tcpkt%p", - 1000, 1000, NULL); + 1000, 1000, NULL); tcp->recv_op.pkt.transport = &tcp->base; tcp->recv_op.pkt.src.tp_type = PJ_TURN_TP_TCP; tcp->recv_op.pkt.src_addr_len = src_addr_len; @@ -323,22 +322,22 @@ static void transport_create(pj_sock_t sock, pj_turn_listener *lis, static void tcp_destroy(struct tcp_transport *tcp) { if (tcp->key) { - pj_ioqueue_unregister(tcp->key); - tcp->key = NULL; - tcp->sock = 0; + pj_ioqueue_unregister(tcp->key); + tcp->key = NULL; + tcp->sock = 0; } else if (tcp->sock) { - pj_sock_close(tcp->sock); - tcp->sock = 0; + pj_sock_close(tcp->sock); + tcp->sock = 0; } if (tcp->pool) { - pj_pool_release(tcp->pool); + pj_pool_release(tcp->pool); } } static void timer_callback(pj_timer_heap_t *timer_heap, - pj_timer_entry *entry) + pj_timer_entry *entry) { struct tcp_transport *tcp = (struct tcp_transport*) entry->user_data; @@ -349,8 +348,8 @@ static void timer_callback(pj_timer_heap_t *timer_heap, static void tcp_on_read_complete(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_read) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_read) { struct tcp_transport *tcp; struct recv_op *recv_op = (struct recv_op*) op_key; @@ -359,78 +358,78 @@ static void tcp_on_read_complete(pj_ioqueue_key_t *key, tcp = (struct tcp_transport*) pj_ioqueue_get_user_data(key); do { - /* Report to server or allocation, if we have allocation */ - if (bytes_read > 0) { - - recv_op->pkt.len = bytes_read; - pj_gettimeofday(&recv_op->pkt.rx_time); - - tcp_add_ref(&tcp->base, NULL); - - if (tcp->alloc) { - pj_turn_allocation_on_rx_client_pkt(tcp->alloc, &recv_op->pkt); - } else { - pj_turn_srv_on_rx_pkt(tcp->base.listener->server, &recv_op->pkt); - } - - pj_assert(tcp->ref_cnt > 0); - tcp_dec_ref(&tcp->base, NULL); - - } else if (bytes_read != -PJ_EPENDING) { - /* TCP connection closed/error. Notify client and then destroy - * ourselves. - * Note: the -PJ_EPENDING is the value passed during init. - */ - ++tcp->ref_cnt; - - if (tcp->alloc) { - if (bytes_read != 0) { - show_err(tcp->base.obj_name, "TCP socket error", - -bytes_read); - } else { - PJ_LOG(5,(tcp->base.obj_name, "TCP socket closed")); - } - pj_turn_allocation_on_transport_closed(tcp->alloc, &tcp->base); - tcp->alloc = NULL; - } - - pj_assert(tcp->ref_cnt > 0); - if (--tcp->ref_cnt == 0) { - tcp_destroy(tcp); - return; - } - } - - /* Reset pool */ - pj_pool_reset(recv_op->pkt.pool); - - /* If packet is full discard it */ - if (recv_op->pkt.len == sizeof(recv_op->pkt.pkt)) { - PJ_LOG(4,(tcp->base.obj_name, "Buffer discarded")); - recv_op->pkt.len = 0; - } - - /* Read next packet */ - bytes_read = sizeof(recv_op->pkt.pkt) - recv_op->pkt.len; - status = pj_ioqueue_recv(tcp->key, op_key, - recv_op->pkt.pkt + recv_op->pkt.len, - &bytes_read, 0); - - if (status != PJ_EPENDING && status != PJ_SUCCESS) - bytes_read = -status; + /* Report to server or allocation, if we have allocation */ + if (bytes_read > 0) { + + recv_op->pkt.len = bytes_read; + pj_gettimeofday(&recv_op->pkt.rx_time); + + tcp_add_ref(&tcp->base, NULL); + + if (tcp->alloc) { + pj_turn_allocation_on_rx_client_pkt(tcp->alloc, &recv_op->pkt); + } else { + pj_turn_srv_on_rx_pkt(tcp->base.listener->server, &recv_op->pkt); + } + + pj_assert(tcp->ref_cnt > 0); + tcp_dec_ref(&tcp->base, NULL); + + } else if (bytes_read != -PJ_EPENDING) { + /* TCP connection closed/error. Notify client and then destroy + * ourselves. + * Note: the -PJ_EPENDING is the value passed during init. + */ + ++tcp->ref_cnt; + + if (tcp->alloc) { + if (bytes_read != 0) { + show_err(tcp->base.obj_name, "TCP socket error", + -bytes_read); + } else { + PJ_LOG(5,(tcp->base.obj_name, "TCP socket closed")); + } + pj_turn_allocation_on_transport_closed(tcp->alloc, &tcp->base); + tcp->alloc = NULL; + } + + pj_assert(tcp->ref_cnt > 0); + if (--tcp->ref_cnt == 0) { + tcp_destroy(tcp); + return; + } + } + + /* Reset pool */ + pj_pool_reset(recv_op->pkt.pool); + + /* If packet is full discard it */ + if (recv_op->pkt.len == sizeof(recv_op->pkt.pkt)) { + PJ_LOG(4,(tcp->base.obj_name, "Buffer discarded")); + recv_op->pkt.len = 0; + } + + /* Read next packet */ + bytes_read = sizeof(recv_op->pkt.pkt) - recv_op->pkt.len; + status = pj_ioqueue_recv(tcp->key, op_key, + recv_op->pkt.pkt + recv_op->pkt.len, + &bytes_read, 0); + + if (status != PJ_EPENDING && status != PJ_SUCCESS) + bytes_read = -status; } while (status != PJ_EPENDING && status != PJ_ECANCELLED && - status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)); + status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)); } static pj_status_t tcp_sendto(pj_turn_transport *tp, - const void *packet, - pj_size_t size, - unsigned flag, - const pj_sockaddr_t *addr, - int addr_len) + const void *packet, + pj_size_t size, + unsigned flag, + const pj_sockaddr_t *addr, + int addr_len) { struct tcp_transport *tcp = (struct tcp_transport*) tp; pj_ssize_t length = size; @@ -443,48 +442,48 @@ static pj_status_t tcp_sendto(pj_turn_transport *tp, static void tcp_add_ref(pj_turn_transport *tp, - pj_turn_allocation *alloc) + pj_turn_allocation *alloc) { struct tcp_transport *tcp = (struct tcp_transport*) tp; ++tcp->ref_cnt; if (tcp->alloc == NULL && alloc) { - tcp->alloc = alloc; + tcp->alloc = alloc; } /* Cancel shutdown timer if it's running */ if (tcp->timer.id != TIMER_NONE) { - pj_timer_heap_cancel(tcp->base.listener->server->core.timer_heap, - &tcp->timer); - tcp->timer.id = TIMER_NONE; + pj_timer_heap_cancel(tcp->base.listener->server->core.timer_heap, + &tcp->timer); + tcp->timer.id = TIMER_NONE; } } static void tcp_dec_ref(pj_turn_transport *tp, - pj_turn_allocation *alloc) + pj_turn_allocation *alloc) { struct tcp_transport *tcp = (struct tcp_transport*) tp; --tcp->ref_cnt; if (alloc && alloc == tcp->alloc) { - tcp->alloc = NULL; + tcp->alloc = NULL; } if (tcp->ref_cnt == 0 && tcp->timer.id == TIMER_NONE) { - pj_time_val delay = { SHUTDOWN_DELAY, 0 }; - tcp->timer.id = TIMER_DESTROY; - pj_timer_heap_schedule(tcp->base.listener->server->core.timer_heap, - &tcp->timer, &delay); + pj_time_val delay = { SHUTDOWN_DELAY, 0 }; + tcp->timer.id = TIMER_DESTROY; + pj_timer_heap_schedule(tcp->base.listener->server->core.timer_heap, + &tcp->timer, &delay); } } -#else /* PJ_HAS_TCP */ +#else /* PJ_HAS_TCP */ /* To avoid empty translation unit warning */ int listener_tcp_dummy = 0; -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ diff --git a/pjnath/src/pjturn-srv/listener_udp.c b/pjnath/src/pjturn-srv/listener_udp.c index 9eec80a561..dfddfc841e 100644 --- a/pjnath/src/pjturn-srv/listener_udp.c +++ b/pjnath/src/pjturn-srv/listener_udp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -22,49 +21,49 @@ struct read_op { - pj_ioqueue_op_key_t op_key; - pj_turn_pkt pkt; + pj_ioqueue_op_key_t op_key; + pj_turn_pkt pkt; }; struct udp_listener { - pj_turn_listener base; + pj_turn_listener base; - pj_ioqueue_key_t *key; - unsigned read_cnt; - struct read_op **read_op; /* Array of read_op's */ + pj_ioqueue_key_t *key; + unsigned read_cnt; + struct read_op **read_op; /* Array of read_op's */ - pj_turn_transport tp; /* Transport instance */ + pj_turn_transport tp; /* Transport instance */ }; static pj_status_t udp_destroy(pj_turn_listener *udp); static void on_read_complete(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_read); + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_read); static pj_status_t udp_sendto(pj_turn_transport *tp, - const void *packet, - pj_size_t size, - unsigned flag, - const pj_sockaddr_t *addr, - int addr_len); + const void *packet, + pj_size_t size, + unsigned flag, + const pj_sockaddr_t *addr, + int addr_len); static void udp_add_ref(pj_turn_transport *tp, - pj_turn_allocation *alloc); + pj_turn_allocation *alloc); static void udp_dec_ref(pj_turn_transport *tp, - pj_turn_allocation *alloc); + pj_turn_allocation *alloc); /* * Create a new listener on the specified port. */ PJ_DEF(pj_status_t) pj_turn_listener_create_udp( pj_turn_srv *srv, - int af, - const pj_str_t *bound_addr, - unsigned port, - unsigned concurrency_cnt, - unsigned flags, - pj_turn_listener **p_listener) + int af, + const pj_str_t *bound_addr, + unsigned port, + unsigned concurrency_cnt, + unsigned flags, + pj_turn_listener **p_listener) { pj_pool_t *pool; struct udp_listener *udp; @@ -94,44 +93,44 @@ PJ_DEF(pj_status_t) pj_turn_listener_create_udp( pj_turn_srv *srv, /* Create socket */ status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &udp->base.sock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Init bind address */ status = pj_sockaddr_init(af, &udp->base.addr, bound_addr, - (pj_uint16_t)port); + (pj_uint16_t)port); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create info */ pj_ansi_strcpy(udp->base.info, "UDP:"); pj_sockaddr_print(&udp->base.addr, udp->base.info+4, - sizeof(udp->base.info)-4, 3); + sizeof(udp->base.info)-4, 3); /* Bind socket */ status = pj_sock_bind(udp->base.sock, &udp->base.addr, - pj_sockaddr_get_len(&udp->base.addr)); + pj_sockaddr_get_len(&udp->base.addr)); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Register to ioqueue */ pj_bzero(&ioqueue_cb, sizeof(ioqueue_cb)); ioqueue_cb.on_read_complete = on_read_complete; status = pj_ioqueue_register_sock(pool, srv->core.ioqueue, udp->base.sock, - udp, &ioqueue_cb, &udp->key); + udp, &ioqueue_cb, &udp->key); /* Create op keys */ udp->read_op = (struct read_op**)pj_pool_calloc(pool, concurrency_cnt, - sizeof(struct read_op*)); + sizeof(struct read_op*)); /* Create each read_op and kick off read operation */ for (i=0; icore.pf, "rop%p", - 1000, 1000, NULL); + pj_pool_t *rpool = pj_pool_create(srv->core.pf, "rop%p", + 1000, 1000, NULL); - udp->read_op[i] = PJ_POOL_ZALLOC_T(pool, struct read_op); - udp->read_op[i]->pkt.pool = rpool; + udp->read_op[i] = PJ_POOL_ZALLOC_T(pool, struct read_op); + udp->read_op[i]->pkt.pool = rpool; - on_read_complete(udp->key, &udp->read_op[i]->op_key, 0); + on_read_complete(udp->key, &udp->read_op[i]->op_key, 0); } /* Done */ @@ -156,30 +155,30 @@ static pj_status_t udp_destroy(pj_turn_listener *listener) unsigned i; if (udp->key) { - pj_ioqueue_unregister(udp->key); - udp->key = NULL; - udp->base.sock = PJ_INVALID_SOCKET; + pj_ioqueue_unregister(udp->key); + udp->key = NULL; + udp->base.sock = PJ_INVALID_SOCKET; } else if (udp->base.sock != PJ_INVALID_SOCKET) { - pj_sock_close(udp->base.sock); - udp->base.sock = PJ_INVALID_SOCKET; + pj_sock_close(udp->base.sock); + udp->base.sock = PJ_INVALID_SOCKET; } for (i=0; iread_cnt; ++i) { - if (udp->read_op[i]->pkt.pool) { - pj_pool_t *rpool = udp->read_op[i]->pkt.pool; - udp->read_op[i]->pkt.pool = NULL; - pj_pool_release(rpool); - } + if (udp->read_op[i]->pkt.pool) { + pj_pool_t *rpool = udp->read_op[i]->pkt.pool; + udp->read_op[i]->pkt.pool = NULL; + pj_pool_release(rpool); + } } if (udp->base.pool) { - pj_pool_t *pool = udp->base.pool; + pj_pool_t *pool = udp->base.pool; - PJ_LOG(4,(udp->base.obj_name, "Listener %s destroyed", - udp->base.info)); + PJ_LOG(4,(udp->base.obj_name, "Listener %s destroyed", + udp->base.info)); - udp->base.pool = NULL; - pj_pool_release(pool); + udp->base.pool = NULL; + pj_pool_release(pool); } return PJ_SUCCESS; } @@ -188,11 +187,11 @@ static pj_status_t udp_destroy(pj_turn_listener *listener) * Callback to send packet. */ static pj_status_t udp_sendto(pj_turn_transport *tp, - const void *packet, - pj_size_t size, - unsigned flag, - const pj_sockaddr_t *addr, - int addr_len) + const void *packet, + pj_size_t size, + unsigned flag, + const pj_sockaddr_t *addr, + int addr_len) { pj_ssize_t len = size; return pj_sock_sendto(tp->listener->sock, packet, &len, flag, addr, addr_len); @@ -200,7 +199,7 @@ static pj_status_t udp_sendto(pj_turn_transport *tp, static void udp_add_ref(pj_turn_transport *tp, - pj_turn_allocation *alloc) + pj_turn_allocation *alloc) { /* Do nothing */ PJ_UNUSED_ARG(tp); @@ -208,7 +207,7 @@ static void udp_add_ref(pj_turn_transport *tp, } static void udp_dec_ref(pj_turn_transport *tp, - pj_turn_allocation *alloc) + pj_turn_allocation *alloc) { /* Do nothing */ PJ_UNUSED_ARG(tp); @@ -220,8 +219,8 @@ static void udp_dec_ref(pj_turn_transport *tp, * Callback on received packet. */ static void on_read_complete(pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_read) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_read) { struct udp_listener *udp; struct read_op *read_op = (struct read_op*) op_key; @@ -230,37 +229,37 @@ static void on_read_complete(pj_ioqueue_key_t *key, udp = (struct udp_listener*) pj_ioqueue_get_user_data(key); do { - pj_pool_t *rpool; + pj_pool_t *rpool; - /* Report to server */ - if (bytes_read > 0) { - read_op->pkt.len = bytes_read; - pj_gettimeofday(&read_op->pkt.rx_time); + /* Report to server */ + if (bytes_read > 0) { + read_op->pkt.len = bytes_read; + pj_gettimeofday(&read_op->pkt.rx_time); - pj_turn_srv_on_rx_pkt(udp->base.server, &read_op->pkt); - } + pj_turn_srv_on_rx_pkt(udp->base.server, &read_op->pkt); + } - /* Reset pool */ - rpool = read_op->pkt.pool; - pj_pool_reset(rpool); - read_op->pkt.pool = rpool; - read_op->pkt.transport = &udp->tp; - read_op->pkt.src.tp_type = udp->base.tp_type; + /* Reset pool */ + rpool = read_op->pkt.pool; + pj_pool_reset(rpool); + read_op->pkt.pool = rpool; + read_op->pkt.transport = &udp->tp; + read_op->pkt.src.tp_type = udp->base.tp_type; - /* Read next packet */ - bytes_read = sizeof(read_op->pkt.pkt); - read_op->pkt.src_addr_len = sizeof(read_op->pkt.src.clt_addr); - pj_bzero(&read_op->pkt.src.clt_addr, sizeof(read_op->pkt.src.clt_addr)); + /* Read next packet */ + bytes_read = sizeof(read_op->pkt.pkt); + read_op->pkt.src_addr_len = sizeof(read_op->pkt.src.clt_addr); + pj_bzero(&read_op->pkt.src.clt_addr, sizeof(read_op->pkt.src.clt_addr)); - status = pj_ioqueue_recvfrom(udp->key, op_key, - read_op->pkt.pkt, &bytes_read, 0, - &read_op->pkt.src.clt_addr, - &read_op->pkt.src_addr_len); + status = pj_ioqueue_recvfrom(udp->key, op_key, + read_op->pkt.pkt, &bytes_read, 0, + &read_op->pkt.src.clt_addr, + &read_op->pkt.src_addr_len); - if (status != PJ_EPENDING && status != PJ_SUCCESS) - bytes_read = -status; + if (status != PJ_EPENDING && status != PJ_SUCCESS) + bytes_read = -status; } while (status != PJ_EPENDING && status != PJ_ECANCELLED && - status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)); + status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)); } diff --git a/pjnath/src/pjturn-srv/main.c b/pjnath/src/pjturn-srv/main.c index 674298de8b..33ff4877e5 100644 --- a/pjnath/src/pjturn-srv/main.c +++ b/pjnath/src/pjturn-srv/main.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -20,10 +19,10 @@ #include "turn.h" #include "auth.h" -#define REALM "pjsip.org" -//#define TURN_PORT PJ_STUN_TURN_PORT -#define TURN_PORT 34780 -#define LOG_LEVEL 4 +#define REALM "pjsip.org" +//#define TURN_PORT PJ_STUN_TURN_PORT +#define TURN_PORT 34780 +#define LOG_LEVEL 4 static pj_caching_pool g_cp; @@ -45,23 +44,23 @@ static void dump_status(pj_turn_srv *srv) unsigned i; for (i=0; icore.lis_cnt; ++i) { - pj_turn_listener *lis = srv->core.listener[i]; - printf("Server address : %s\n", lis->info); + pj_turn_listener *lis = srv->core.listener[i]; + printf("Server address : %s\n", lis->info); } printf("Worker threads : %d\n", srv->core.thread_cnt); printf("Total mem usage: %u.%03uMB\n", (unsigned)(g_cp.used_size / 1000000), - (unsigned)((g_cp.used_size % 1000000)/1000)); + (unsigned)((g_cp.used_size % 1000000)/1000)); printf("UDP port range : %u %u %u (next/min/max)\n", srv->ports.next_udp, - srv->ports.min_udp, srv->ports.max_udp); + srv->ports.min_udp, srv->ports.max_udp); printf("TCP port range : %u %u %u (next/min/max)\n", srv->ports.next_tcp, - srv->ports.min_tcp, srv->ports.max_tcp); + srv->ports.min_tcp, srv->ports.max_tcp); printf("Clients # : %u\n", pj_hash_count(srv->tables.alloc)); puts(""); if (pj_hash_count(srv->tables.alloc)==0) { - return; + return; } puts("# Client addr. Alloc addr. Username Lftm Expy #prm #chl"); @@ -72,21 +71,21 @@ static void dump_status(pj_turn_srv *srv) it = pj_hash_first(srv->tables.alloc, &itbuf); i=1; while (it) { - pj_turn_allocation *alloc = (pj_turn_allocation*) - pj_hash_this(srv->tables.alloc, it); - printf("%-3d %-22s %-22s %-8.*s %-4d %-4ld %-4d %-4d\n", - i, - alloc->info, - pj_sockaddr_print(&alloc->relay.hkey.addr, addr, sizeof(addr), 3), - (int)alloc->cred.data.static_cred.username.slen, - alloc->cred.data.static_cred.username.ptr, - alloc->relay.lifetime, - alloc->relay.expiry.sec - now.sec, - pj_hash_count(alloc->peer_table), - pj_hash_count(alloc->ch_table)); - - it = pj_hash_next(srv->tables.alloc, it); - ++i; + pj_turn_allocation *alloc = (pj_turn_allocation*) + pj_hash_this(srv->tables.alloc, it); + printf("%-3d %-22s %-22s %-8.*s %-4d %-4ld %-4d %-4d\n", + i, + alloc->info, + pj_sockaddr_print(&alloc->relay.hkey.addr, addr, sizeof(addr), 3), + (int)alloc->cred.data.static_cred.username.slen, + alloc->cred.data.static_cred.username.ptr, + alloc->relay.lifetime, + alloc->relay.expiry.sec - now.sec, + pj_hash_count(alloc->peer_table), + pj_hash_count(alloc->ch_table)); + + it = pj_hash_next(srv->tables.alloc, it); + ++i; } } @@ -104,21 +103,21 @@ static void console_main(pj_turn_srv *srv) pj_bool_t quit = PJ_FALSE; while (!quit) { - char line[10]; - - menu(); - - if (fgets(line, sizeof(line), stdin) == NULL) - break; - - switch (line[0]) { - case 'd': - dump_status(srv); - break; - case 'q': - quit = PJ_TRUE; - break; - } + char line[10]; + + menu(); + + if (fgets(line, sizeof(line), stdin) == NULL) + break; + + switch (line[0]) { + case 'd': + dump_status(srv); + break; + case 'q': + quit = PJ_TRUE; + break; + } } } @@ -130,7 +129,7 @@ int main() status = pj_init(); if (status != PJ_SUCCESS) - return err("pj_init() error", status); + return err("pj_init() error", status); pjlib_util_init(); pjnath_init(); @@ -141,23 +140,23 @@ int main() status = pj_turn_srv_create(&g_cp.factory, &srv); if (status != PJ_SUCCESS) - return err("Error creating server", status); + return err("Error creating server", status); status = pj_turn_listener_create_udp(srv, pj_AF_INET(), NULL, - TURN_PORT, 1, 0, &listener); + TURN_PORT, 1, 0, &listener); if (status != PJ_SUCCESS) - return err("Error creating UDP listener", status); + return err("Error creating UDP listener", status); #if PJ_HAS_TCP status = pj_turn_listener_create_tcp(srv, pj_AF_INET(), NULL, - TURN_PORT, 1, 0, &listener); + TURN_PORT, 1, 0, &listener); if (status != PJ_SUCCESS) - return err("Error creating listener", status); + return err("Error creating listener", status); #endif status = pj_turn_srv_add_listener(srv, listener); if (status != PJ_SUCCESS) - return err("Error adding listener", status); + return err("Error adding listener", status); puts("Server is running"); diff --git a/pjnath/src/pjturn-srv/server.c b/pjnath/src/pjturn-srv/server.c index 94dda29a31..48b62ce13c 100644 --- a/pjnath/src/pjturn-srv/server.c +++ b/pjnath/src/pjturn-srv/server.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -20,39 +19,39 @@ #include "turn.h" #include "auth.h" -#define MAX_CLIENTS 32 -#define MAX_PEERS_PER_CLIENT 8 -//#define MAX_HANDLES (MAX_CLIENTS*MAX_PEERS_PER_CLIENT+MAX_LISTENERS) -#define MAX_HANDLES PJ_IOQUEUE_MAX_HANDLES -#define MAX_TIMER (MAX_HANDLES * 2) -#define MIN_PORT 49152 -#define MAX_PORT 65535 -#define MAX_LISTENERS 16 -#define MAX_THREADS 2 -#define MAX_NET_EVENTS 1000 +#define MAX_CLIENTS 32 +#define MAX_PEERS_PER_CLIENT 8 +//#define MAX_HANDLES (MAX_CLIENTS*MAX_PEERS_PER_CLIENT+MAX_LISTENERS) +#define MAX_HANDLES PJ_IOQUEUE_MAX_HANDLES +#define MAX_TIMER (MAX_HANDLES * 2) +#define MIN_PORT 49152 +#define MAX_PORT 65535 +#define MAX_LISTENERS 16 +#define MAX_THREADS 2 +#define MAX_NET_EVENTS 1000 /* Prototypes */ static int server_thread_proc(void *arg); static pj_status_t on_tx_stun_msg( pj_stun_session *sess, - void *token, - const void *pkt, - pj_size_t pkt_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len); + void *token, + const void *pkt, + pj_size_t pkt_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len); static pj_status_t on_rx_stun_request(pj_stun_session *sess, - const pj_uint8_t *pkt, - unsigned pkt_len, - const pj_stun_rx_data *rdata, - void *user_data, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len); + const pj_uint8_t *pkt, + unsigned pkt_len, + const pj_stun_rx_data *rdata, + void *user_data, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len); struct saved_cred { pj_str_t realm; pj_str_t username; pj_str_t nonce; - int data_type; + int data_type; pj_str_t data; }; @@ -64,12 +63,12 @@ PJ_DEF(const char*) pj_turn_tp_type_name(int tp_type) { /* Must be 3 characters long! */ if (tp_type == PJ_TURN_TP_UDP) { - return "UDP"; + return "UDP"; } else if (tp_type == PJ_TURN_TP_TCP) { - return "TCP"; + return "TCP"; } else { - pj_assert(!"Unsupported transport"); - return "???"; + pj_assert(!"Unsupported transport"); + return "???"; } } @@ -77,7 +76,7 @@ PJ_DEF(const char*) pj_turn_tp_type_name(int tp_type) * Create server. */ PJ_DEF(pj_status_t) pj_turn_srv_create(pj_pool_factory *pf, - pj_turn_srv **p_srv) + pj_turn_srv **p_srv) { pj_pool_t *pool; pj_stun_session_cb sess_cb; @@ -98,35 +97,35 @@ PJ_DEF(pj_status_t) pj_turn_srv_create(pj_pool_factory *pf, /* Create ioqueue */ status = pj_ioqueue_create(pool, MAX_HANDLES, &srv->core.ioqueue); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Server mutex */ status = pj_lock_create_recursive_mutex(pool, srv->obj_name, - &srv->core.lock); + &srv->core.lock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Allocate TLS */ status = pj_thread_local_alloc(&srv->core.tls_key); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_thread_local_alloc(&srv->core.tls_data); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create timer heap */ status = pj_timer_heap_create(pool, MAX_TIMER, &srv->core.timer_heap); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Configure lock for the timer heap */ pj_timer_heap_set_lock(srv->core.timer_heap, srv->core.lock, PJ_FALSE); /* Array of listeners */ srv->core.listener = (pj_turn_listener**) - pj_pool_calloc(pool, MAX_LISTENERS, - sizeof(srv->core.listener[0])); + pj_pool_calloc(pool, MAX_LISTENERS, + sizeof(srv->core.listener[0])); /* Create hash tables */ srv->tables.alloc = pj_hash_create(pool, MAX_CLIENTS); @@ -140,7 +139,7 @@ PJ_DEF(pj_status_t) pj_turn_srv_create(pj_pool_factory *pf, /* Init STUN config */ pj_stun_config_init(&srv->core.stun_cfg, pf, 0, srv->core.ioqueue, - srv->core.timer_heap); + srv->core.timer_heap); /* Init STUN credential */ srv->core.cred.type = PJ_STUN_AUTH_CRED_DYNAMIC; @@ -155,34 +154,34 @@ PJ_DEF(pj_status_t) pj_turn_srv_create(pj_pool_factory *pf, sess_cb.on_send_msg = &on_tx_stun_msg; status = pj_stun_session_create(&srv->core.stun_cfg, srv->obj_name, - &sess_cb, PJ_FALSE, NULL, - &srv->core.stun_sess); + &sess_cb, PJ_FALSE, NULL, + &srv->core.stun_sess); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } pj_stun_session_set_user_data(srv->core.stun_sess, srv); pj_stun_session_set_credential(srv->core.stun_sess, PJ_STUN_AUTH_LONG_TERM, - &srv->core.cred); + &srv->core.cred); /* Array of worker threads */ srv->core.thread_cnt = MAX_THREADS; srv->core.thread = (pj_thread_t**) - pj_pool_calloc(pool, srv->core.thread_cnt, - sizeof(pj_thread_t*)); + pj_pool_calloc(pool, srv->core.thread_cnt, + sizeof(pj_thread_t*)); /* Start the worker threads */ for (i=0; icore.thread_cnt; ++i) { - status = pj_thread_create(pool, srv->obj_name, &server_thread_proc, - srv, 0, 0, &srv->core.thread[i]); - if (status != PJ_SUCCESS) - goto on_error; + status = pj_thread_create(pool, srv->obj_name, &server_thread_proc, + srv, 0, 0, &srv->core.thread[i]); + if (status != PJ_SUCCESS) + goto on_error; } /* We're done. Application should add listeners now */ PJ_LOG(4,(srv->obj_name, "TURN server v%s is running", - pj_get_version())); + pj_get_version())); *p_srv = srv; return PJ_SUCCESS; @@ -219,7 +218,7 @@ static void srv_handle_events(pj_turn_srv *srv, const pj_time_val *max_timeout) * the timeout to wait from timer, and use the minimum value. */ if (max_timeout && PJ_TIME_VAL_GT(timeout, *max_timeout)) { - timeout = *max_timeout; + timeout = *max_timeout; } /* Poll ioqueue. @@ -234,16 +233,16 @@ static void srv_handle_events(pj_turn_srv *srv, const pj_time_val *max_timeout) * reported in timely manner. */ do { - c = pj_ioqueue_poll( srv->core.ioqueue, &timeout); - if (c < 0) { - pj_thread_sleep(PJ_TIME_VAL_MSEC(timeout)); - return; - } else if (c == 0) { - break; - } else { - net_event_count += c; - timeout.sec = timeout.msec = 0; - } + c = pj_ioqueue_poll( srv->core.ioqueue, &timeout); + if (c < 0) { + pj_thread_sleep(PJ_TIME_VAL_MSEC(timeout)); + return; + } else if (c == 0) { + break; + } else { + net_event_count += c; + timeout.sec = timeout.msec = 0; + } } while (c > 0 && net_event_count < MAX_NET_EVENTS); } @@ -256,8 +255,8 @@ static int server_thread_proc(void *arg) pj_turn_srv *srv = (pj_turn_srv*)arg; while (!srv->core.quit) { - pj_time_val timeout_max = {0, 100}; - srv_handle_events(srv, &timeout_max); + pj_time_val timeout_max = {0, 100}; + srv_handle_events(srv, &timeout_max); } return 0; @@ -274,78 +273,78 @@ PJ_DEF(pj_status_t) pj_turn_srv_destroy(pj_turn_srv *srv) /* Stop all worker threads */ srv->core.quit = PJ_TRUE; for (i=0; icore.thread_cnt; ++i) { - if (srv->core.thread[i]) { - pj_thread_join(srv->core.thread[i]); - pj_thread_destroy(srv->core.thread[i]); - srv->core.thread[i] = NULL; - } + if (srv->core.thread[i]) { + pj_thread_join(srv->core.thread[i]); + pj_thread_destroy(srv->core.thread[i]); + srv->core.thread[i] = NULL; + } } /* Destroy all allocations FIRST */ if (srv->tables.alloc) { - it = pj_hash_first(srv->tables.alloc, &itbuf); - while (it != NULL) { - pj_turn_allocation *alloc = (pj_turn_allocation*) - pj_hash_this(srv->tables.alloc, it); - pj_hash_iterator_t *next = pj_hash_next(srv->tables.alloc, it); - pj_turn_allocation_destroy(alloc); - it = next; - } + it = pj_hash_first(srv->tables.alloc, &itbuf); + while (it != NULL) { + pj_turn_allocation *alloc = (pj_turn_allocation*) + pj_hash_this(srv->tables.alloc, it); + pj_hash_iterator_t *next = pj_hash_next(srv->tables.alloc, it); + pj_turn_allocation_destroy(alloc); + it = next; + } } /* Destroy all listeners. */ for (i=0; icore.lis_cnt; ++i) { - if (srv->core.listener[i]) { - pj_turn_listener_destroy(srv->core.listener[i]); - srv->core.listener[i] = NULL; - } + if (srv->core.listener[i]) { + pj_turn_listener_destroy(srv->core.listener[i]); + srv->core.listener[i] = NULL; + } } /* Destroy STUN session */ if (srv->core.stun_sess) { - pj_stun_session_destroy(srv->core.stun_sess); - srv->core.stun_sess = NULL; + pj_stun_session_destroy(srv->core.stun_sess); + srv->core.stun_sess = NULL; } /* Destroy hash tables (well, sort of) */ if (srv->tables.alloc) { - srv->tables.alloc = NULL; - srv->tables.res = NULL; + srv->tables.alloc = NULL; + srv->tables.res = NULL; } /* Destroy timer heap */ if (srv->core.timer_heap) { - pj_timer_heap_destroy(srv->core.timer_heap); - srv->core.timer_heap = NULL; + pj_timer_heap_destroy(srv->core.timer_heap); + srv->core.timer_heap = NULL; } /* Destroy ioqueue */ if (srv->core.ioqueue) { - pj_ioqueue_destroy(srv->core.ioqueue); - srv->core.ioqueue = NULL; + pj_ioqueue_destroy(srv->core.ioqueue); + srv->core.ioqueue = NULL; } /* Destroy thread local IDs */ if (srv->core.tls_key != -1) { - pj_thread_local_free(srv->core.tls_key); - srv->core.tls_key = -1; + pj_thread_local_free(srv->core.tls_key); + srv->core.tls_key = -1; } if (srv->core.tls_data != -1) { - pj_thread_local_free(srv->core.tls_data); - srv->core.tls_data = -1; + pj_thread_local_free(srv->core.tls_data); + srv->core.tls_data = -1; } /* Destroy server lock */ if (srv->core.lock) { - pj_lock_destroy(srv->core.lock); - srv->core.lock = NULL; + pj_lock_destroy(srv->core.lock); + srv->core.lock = NULL; } /* Release pool */ if (srv->core.pool) { - pj_pool_t *pool = srv->core.pool; - srv->core.pool = NULL; - pj_pool_release(pool); + pj_pool_t *pool = srv->core.pool; + srv->core.pool = NULL; + pj_pool_release(pool); } /* Done */ @@ -357,7 +356,7 @@ PJ_DEF(pj_status_t) pj_turn_srv_destroy(pj_turn_srv *srv) * Add listener. */ PJ_DEF(pj_status_t) pj_turn_srv_add_listener(pj_turn_srv *srv, - pj_turn_listener *lis) + pj_turn_listener *lis) { unsigned index; @@ -372,7 +371,7 @@ PJ_DEF(pj_status_t) pj_turn_srv_add_listener(pj_turn_srv *srv, srv->core.lis_cnt++; PJ_LOG(4,(srv->obj_name, "Listener %s/%s added at index %d", - lis->obj_name, lis->info, lis->id)); + lis->obj_name, lis->info, lis->id)); return PJ_SUCCESS; } @@ -389,12 +388,12 @@ PJ_DEF(pj_status_t) pj_turn_listener_destroy(pj_turn_listener *listener) /* Remove from our listener list */ pj_lock_acquire(srv->core.lock); for (i=0; icore.lis_cnt; ++i) { - if (srv->core.listener[i] == listener) { - srv->core.listener[i] = NULL; - srv->core.lis_cnt--; - listener->id = PJ_TURN_INVALID_LIS_ID; - break; - } + if (srv->core.listener[i] == listener) { + srv->core.listener[i] = NULL; + srv->core.lis_cnt--; + listener->id = PJ_TURN_INVALID_LIS_ID; + break; + } } pj_lock_release(srv->core.lock); @@ -407,7 +406,7 @@ PJ_DEF(pj_status_t) pj_turn_listener_destroy(pj_turn_listener *listener) * Add a reference to a transport. */ PJ_DEF(void) pj_turn_transport_add_ref( pj_turn_transport *transport, - pj_turn_allocation *alloc) + pj_turn_allocation *alloc) { transport->add_ref(transport, alloc); } @@ -417,7 +416,7 @@ PJ_DEF(void) pj_turn_transport_add_ref( pj_turn_transport *transport, * Decrement transport reference counter. */ PJ_DEF(void) pj_turn_transport_dec_ref( pj_turn_transport *transport, - pj_turn_allocation *alloc) + pj_turn_allocation *alloc) { transport->dec_ref(transport, alloc); } @@ -427,15 +426,15 @@ PJ_DEF(void) pj_turn_transport_dec_ref( pj_turn_transport *transport, * Register an allocation to the hash tables. */ PJ_DEF(pj_status_t) pj_turn_srv_register_allocation(pj_turn_srv *srv, - pj_turn_allocation *alloc) + pj_turn_allocation *alloc) { /* Add to hash tables */ pj_lock_acquire(srv->core.lock); pj_hash_set(alloc->pool, srv->tables.alloc, - &alloc->hkey, sizeof(alloc->hkey), 0, alloc); + &alloc->hkey, sizeof(alloc->hkey), 0, alloc); pj_hash_set(alloc->pool, srv->tables.res, - &alloc->relay.hkey, sizeof(alloc->relay.hkey), 0, - &alloc->relay); + &alloc->relay.hkey, sizeof(alloc->relay.hkey), 0, + &alloc->relay); pj_lock_release(srv->core.lock); return PJ_SUCCESS; @@ -446,14 +445,14 @@ PJ_DEF(pj_status_t) pj_turn_srv_register_allocation(pj_turn_srv *srv, * Unregister an allocation from the hash tables. */ PJ_DEF(pj_status_t) pj_turn_srv_unregister_allocation(pj_turn_srv *srv, - pj_turn_allocation *alloc) + pj_turn_allocation *alloc) { /* Unregister from hash tables */ pj_lock_acquire(srv->core.lock); pj_hash_set(alloc->pool, srv->tables.alloc, - &alloc->hkey, sizeof(alloc->hkey), 0, NULL); + &alloc->hkey, sizeof(alloc->hkey), 0, NULL); pj_hash_set(alloc->pool, srv->tables.res, - &alloc->relay.hkey, sizeof(alloc->relay.hkey), 0, NULL); + &alloc->relay.hkey, sizeof(alloc->relay.hkey), 0, NULL); pj_lock_release(srv->core.lock); return PJ_SUCCESS; @@ -464,11 +463,11 @@ PJ_DEF(pj_status_t) pj_turn_srv_unregister_allocation(pj_turn_srv *srv, * outgoing STUN packet. */ static pj_status_t on_tx_stun_msg( pj_stun_session *sess, - void *token, - const void *pdu, - pj_size_t pdu_size, - const pj_sockaddr_t *dst_addr, - unsigned addr_len) + void *token, + const void *pdu, + pj_size_t pdu_size, + const pj_sockaddr_t *dst_addr, + unsigned addr_len) { pj_turn_transport *transport = (pj_turn_transport*) token; @@ -477,19 +476,19 @@ static pj_status_t on_tx_stun_msg( pj_stun_session *sess, PJ_UNUSED_ARG(sess); return transport->sendto(transport, pdu, pdu_size, 0, - dst_addr, addr_len); + dst_addr, addr_len); } /* Respond to STUN request */ static pj_status_t stun_respond(pj_stun_session *sess, - pj_turn_transport *transport, - const pj_stun_rx_data *rdata, - unsigned code, - const char *errmsg, - pj_bool_t cache, - const pj_sockaddr_t *dst_addr, - unsigned addr_len) + pj_turn_transport *transport, + const pj_stun_rx_data *rdata, + unsigned code, + const char *errmsg, + pj_bool_t cache, + const pj_sockaddr_t *dst_addr, + unsigned addr_len) { pj_status_t status; pj_str_t reason; @@ -497,14 +496,14 @@ static pj_status_t stun_respond(pj_stun_session *sess, /* Create response */ status = pj_stun_session_create_res(sess, rdata, code, - (errmsg?pj_cstr(&reason,errmsg):NULL), - &tdata); + (errmsg?pj_cstr(&reason,errmsg):NULL), + &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Send the response */ return pj_stun_session_send_msg(sess, transport, cache, PJ_FALSE, - dst_addr, addr_len, tdata); + dst_addr, addr_len, tdata); } @@ -513,12 +512,12 @@ static pj_status_t stun_respond(pj_stun_session *sess, * pj_turn_srv_on_rx_pkt() function below. */ static pj_status_t on_rx_stun_request(pj_stun_session *sess, - const pj_uint8_t *pdu, - unsigned pdu_len, - const pj_stun_rx_data *rdata, - void *token, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + const pj_uint8_t *pdu, + unsigned pdu_len, + const pj_stun_rx_data *rdata, + void *token, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { pj_turn_transport *transport; const pj_stun_msg *msg = rdata->msg; @@ -532,19 +531,19 @@ static pj_status_t on_rx_stun_request(pj_stun_session *sess, /* Respond any requests other than ALLOCATE with 437 response */ if (msg->hdr.type != PJ_STUN_ALLOCATE_REQUEST) { - stun_respond(sess, transport, rdata, PJ_STUN_SC_ALLOCATION_MISMATCH, - NULL, PJ_FALSE, src_addr, src_addr_len); - return PJ_SUCCESS; + stun_respond(sess, transport, rdata, PJ_STUN_SC_ALLOCATION_MISMATCH, + NULL, PJ_FALSE, src_addr, src_addr_len); + return PJ_SUCCESS; } /* Create new allocation. The relay resource will be allocated * in this function. */ status = pj_turn_allocation_create(transport, src_addr, src_addr_len, - rdata, sess, &alloc); + rdata, sess, &alloc); if (status != PJ_SUCCESS) { - /* STUN response has been sent, no need to reply here */ - return PJ_SUCCESS; + /* STUN response has been sent, no need to reply here */ + return PJ_SUCCESS; } /* Done. */ @@ -553,7 +552,7 @@ static pj_status_t on_rx_stun_request(pj_stun_session *sess, /* Handle STUN Binding request */ static void handle_binding_request(pj_turn_pkt *pkt, - unsigned options) + unsigned options) { pj_stun_msg *request, *response; pj_uint8_t pdu[200]; @@ -562,31 +561,31 @@ static void handle_binding_request(pj_turn_pkt *pkt, /* Decode request */ status = pj_stun_msg_decode(pkt->pool, pkt->pkt, pkt->len, options, - &request, NULL, NULL); + &request, NULL, NULL); if (status != PJ_SUCCESS) - return; + return; /* Create response */ status = pj_stun_msg_create_response(pkt->pool, request, 0, NULL, - &response); + &response); if (status != PJ_SUCCESS) - return; + return; /* Add XOR-MAPPED-ADDRESS */ pj_stun_msg_add_sockaddr_attr(pkt->pool, response, - PJ_STUN_ATTR_XOR_MAPPED_ADDR, - PJ_TRUE, - &pkt->src.clt_addr, - pkt->src_addr_len); + PJ_STUN_ATTR_XOR_MAPPED_ADDR, + PJ_TRUE, + &pkt->src.clt_addr, + pkt->src_addr_len); /* Encode */ status = pj_stun_msg_encode(response, pdu, sizeof(pdu), 0, NULL, &len); if (status != PJ_SUCCESS) - return; + return; /* Send response */ pkt->transport->sendto(pkt->transport, pdu, len, 0, - &pkt->src.clt_addr, pkt->src_addr_len); + &pkt->src.clt_addr, pkt->src_addr_len); } /* @@ -597,101 +596,101 @@ static void handle_binding_request(pj_turn_pkt *pkt, * if an allocation is not found. */ PJ_DEF(void) pj_turn_srv_on_rx_pkt(pj_turn_srv *srv, - pj_turn_pkt *pkt) + pj_turn_pkt *pkt) { pj_turn_allocation *alloc; /* Get TURN allocation from the source address */ pj_lock_acquire(srv->core.lock); alloc = (pj_turn_allocation*) - pj_hash_get(srv->tables.alloc, &pkt->src, sizeof(pkt->src), NULL); + pj_hash_get(srv->tables.alloc, &pkt->src, sizeof(pkt->src), NULL); pj_lock_release(srv->core.lock); /* If allocation is found, just hand over the packet to the * allocation. */ if (alloc) { - pj_turn_allocation_on_rx_client_pkt(alloc, pkt); + pj_turn_allocation_on_rx_client_pkt(alloc, pkt); } else { - /* Otherwise this is a new client */ - unsigned options; - pj_size_t parsed_len; - pj_status_t status; - - /* Check that this is a STUN message */ - options = PJ_STUN_CHECK_PACKET | PJ_STUN_NO_FINGERPRINT_CHECK; - if (pkt->transport->listener->tp_type == PJ_TURN_TP_UDP) - options |= PJ_STUN_IS_DATAGRAM; - - status = pj_stun_msg_check(pkt->pkt, pkt->len, options); - if (status != PJ_SUCCESS) { - /* If the first byte are not STUN, drop the packet. First byte - * of STUN message is always 0x00 or 0x01. Otherwise wait for - * more data as the data might have come from TCP. - * - * Also drop packet if it's unreasonably too big, as this might - * indicate invalid data that's building up in the buffer. - * - * Or if packet is a datagram. - */ - if ((*pkt->pkt != 0x00 && *pkt->pkt != 0x01) || - pkt->len > 1600 || - (options & PJ_STUN_IS_DATAGRAM)) - { - char errmsg[PJ_ERR_MSG_SIZE]; - char ip[PJ_INET6_ADDRSTRLEN+10]; - - pkt->len = 0; - - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(5,(srv->obj_name, - "Non-STUN packet from %s is dropped: %s", - pj_sockaddr_print(&pkt->src.clt_addr, ip, sizeof(ip), 3), - errmsg)); - } - return; - } - - /* Special handling for Binding Request. We won't give it to the - * STUN session since this request is not authenticated. - */ - if (pkt->pkt[1] == 1) { - handle_binding_request(pkt, options); - return; - } - - /* Hand over processing to STUN session. This will trigger - * on_rx_stun_request() callback to be called if the STUN - * message is a request. - */ - options &= ~PJ_STUN_CHECK_PACKET; - parsed_len = 0; - status = pj_stun_session_on_rx_pkt(srv->core.stun_sess, pkt->pkt, - pkt->len, options, pkt->transport, - &parsed_len, &pkt->src.clt_addr, - pkt->src_addr_len); - if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - char ip[PJ_INET6_ADDRSTRLEN+10]; - - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(5,(srv->obj_name, - "Error processing STUN packet from %s: %s", - pj_sockaddr_print(&pkt->src.clt_addr, ip, sizeof(ip), 3), - errmsg)); - } - - if (pkt->transport->listener->tp_type == PJ_TURN_TP_UDP) { - pkt->len = 0; - } else if (parsed_len > 0) { - if (parsed_len == pkt->len) { - pkt->len = 0; - } else { - pj_memmove(pkt->pkt, pkt->pkt+parsed_len, - pkt->len - parsed_len); - pkt->len -= parsed_len; - } - } + /* Otherwise this is a new client */ + unsigned options; + pj_size_t parsed_len; + pj_status_t status; + + /* Check that this is a STUN message */ + options = PJ_STUN_CHECK_PACKET | PJ_STUN_NO_FINGERPRINT_CHECK; + if (pkt->transport->listener->tp_type == PJ_TURN_TP_UDP) + options |= PJ_STUN_IS_DATAGRAM; + + status = pj_stun_msg_check(pkt->pkt, pkt->len, options); + if (status != PJ_SUCCESS) { + /* If the first byte are not STUN, drop the packet. First byte + * of STUN message is always 0x00 or 0x01. Otherwise wait for + * more data as the data might have come from TCP. + * + * Also drop packet if it's unreasonably too big, as this might + * indicate invalid data that's building up in the buffer. + * + * Or if packet is a datagram. + */ + if ((*pkt->pkt != 0x00 && *pkt->pkt != 0x01) || + pkt->len > 1600 || + (options & PJ_STUN_IS_DATAGRAM)) + { + char errmsg[PJ_ERR_MSG_SIZE]; + char ip[PJ_INET6_ADDRSTRLEN+10]; + + pkt->len = 0; + + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(5,(srv->obj_name, + "Non-STUN packet from %s is dropped: %s", + pj_sockaddr_print(&pkt->src.clt_addr, ip, sizeof(ip), 3), + errmsg)); + } + return; + } + + /* Special handling for Binding Request. We won't give it to the + * STUN session since this request is not authenticated. + */ + if (pkt->pkt[1] == 1) { + handle_binding_request(pkt, options); + return; + } + + /* Hand over processing to STUN session. This will trigger + * on_rx_stun_request() callback to be called if the STUN + * message is a request. + */ + options &= ~PJ_STUN_CHECK_PACKET; + parsed_len = 0; + status = pj_stun_session_on_rx_pkt(srv->core.stun_sess, pkt->pkt, + pkt->len, options, pkt->transport, + &parsed_len, &pkt->src.clt_addr, + pkt->src_addr_len); + if (status != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + char ip[PJ_INET6_ADDRSTRLEN+10]; + + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(5,(srv->obj_name, + "Error processing STUN packet from %s: %s", + pj_sockaddr_print(&pkt->src.clt_addr, ip, sizeof(ip), 3), + errmsg)); + } + + if (pkt->transport->listener->tp_type == PJ_TURN_TP_UDP) { + pkt->len = 0; + } else if (parsed_len > 0) { + if (parsed_len == pkt->len) { + pkt->len = 0; + } else { + pj_memmove(pkt->pkt, pkt->pkt+parsed_len, + pkt->len - parsed_len); + pkt->len -= parsed_len; + } + } } } diff --git a/pjnath/src/pjturn-srv/turn.h b/pjnath/src/pjturn-srv/turn.h index 2267ec1f29..3f6bc97f79 100644 --- a/pjnath/src/pjturn-srv/turn.h +++ b/pjnath/src/pjturn-srv/turn.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,15 +23,15 @@ #include typedef struct pj_turn_relay_res pj_turn_relay_res; -typedef struct pj_turn_listener pj_turn_listener; +typedef struct pj_turn_listener pj_turn_listener; typedef struct pj_turn_transport pj_turn_transport; typedef struct pj_turn_permission pj_turn_permission; typedef struct pj_turn_allocation pj_turn_allocation; -typedef struct pj_turn_srv pj_turn_srv; -typedef struct pj_turn_pkt pj_turn_pkt; +typedef struct pj_turn_srv pj_turn_srv; +typedef struct pj_turn_pkt pj_turn_pkt; -#define PJ_TURN_INVALID_LIS_ID ((unsigned)-1) +#define PJ_TURN_INVALID_LIS_ID ((unsigned)-1) /** * Get transport type name string. @@ -47,53 +46,53 @@ struct pj_turn_relay_res { /** Hash table key */ struct { - /** Transport type. */ - int tp_type; + /** Transport type. */ + int tp_type; - /** Transport/relay address */ - pj_sockaddr addr; + /** Transport/relay address */ + pj_sockaddr addr; } hkey; /** Allocation who requested or reserved this resource. */ pj_turn_allocation *allocation; /** Username used in credential */ - pj_str_t user; + pj_str_t user; /** Realm used in credential. */ - pj_str_t realm; + pj_str_t realm; /** Lifetime, in seconds. */ - unsigned lifetime; + unsigned lifetime; /** Relay/allocation expiration time */ - pj_time_val expiry; + pj_time_val expiry; /** Timeout timer entry */ pj_timer_entry timer; /** Transport. */ struct { - /** Transport/relay socket */ - pj_sock_t sock; + /** Transport/relay socket */ + pj_sock_t sock; - /** Transport/relay ioqueue */ - pj_ioqueue_key_t *key; + /** Transport/relay ioqueue */ + pj_ioqueue_key_t *key; - /** Read operation key. */ - pj_ioqueue_op_key_t read_key; + /** Read operation key. */ + pj_ioqueue_op_key_t read_key; - /** The incoming packet buffer */ - char rx_pkt[PJ_TURN_MAX_PKT_LEN]; + /** The incoming packet buffer */ + char rx_pkt[PJ_TURN_MAX_PKT_LEN]; - /** Source address of the packet. */ - pj_sockaddr src_addr; + /** Source address of the packet. */ + pj_sockaddr src_addr; - /** Source address length */ - int src_addr_len; + /** Source address length */ + int src_addr_len; - /** The outgoing packet buffer. This must be 3wbit aligned. */ - char tx_pkt[PJ_TURN_MAX_PKT_LEN+4]; + /** The outgoing packet buffer. This must be 3wbit aligned. */ + char tx_pkt[PJ_TURN_MAX_PKT_LEN+4]; } tp; }; @@ -109,8 +108,8 @@ struct pj_turn_relay_res */ typedef struct pj_turn_allocation_key { - int tp_type; /**< Transport type. */ - pj_sockaddr clt_addr; /**< Client's address. */ + int tp_type; /**< Transport type. */ + pj_sockaddr clt_addr; /**< Client's address. */ } pj_turn_allocation_key; @@ -123,43 +122,43 @@ struct pj_turn_allocation pj_turn_allocation_key hkey; /** Pool for this allocation. */ - pj_pool_t *pool; + pj_pool_t *pool; /** Object name for logging identification */ - char *obj_name; + char *obj_name; /** Client info (IP address and port) */ - char info[80]; + char info[80]; /** Mutex */ - pj_lock_t *lock; + pj_lock_t *lock; /** Server instance. */ - pj_turn_srv *server; + pj_turn_srv *server; /** Transport to send/receive packets to/from client. */ - pj_turn_transport *transport; + pj_turn_transport *transport; /** The relay resource for this allocation. */ - pj_turn_relay_res relay; + pj_turn_relay_res relay; /** Relay resource reserved by this allocation, if any */ - pj_turn_relay_res *resv; + pj_turn_relay_res *resv; /** Requested bandwidth */ - unsigned bandwidth; + unsigned bandwidth; /** STUN session for this client */ - pj_stun_session *sess; + pj_stun_session *sess; /** Credential for this STUN session. */ - pj_stun_auth_cred cred; + pj_stun_auth_cred cred; /** Peer hash table (keyed by peer address) */ - pj_hash_table_t *peer_table; + pj_hash_table_t *peer_table; /** Channel hash table (keyed by channel number) */ - pj_hash_table_t *ch_table; + pj_hash_table_t *ch_table; }; @@ -170,7 +169,7 @@ struct pj_turn_allocation typedef struct pj_turn_permission_key { /** Peer address. */ - pj_sockaddr peer_addr; + pj_sockaddr peer_addr; } pj_turn_permission_key; @@ -184,26 +183,26 @@ struct pj_turn_permission pj_turn_permission_key hkey; /** TURN allocation that owns this permission/channel */ - pj_turn_allocation *allocation; + pj_turn_allocation *allocation; /** Optional channel number, or PJ_TURN_INVALID_CHANNEL if channel number * is not requested for this permission. */ - pj_uint16_t channel; + pj_uint16_t channel; /** Permission expiration time. */ - pj_time_val expiry; + pj_time_val expiry; }; /** * Create new allocation. */ PJ_DECL(pj_status_t) pj_turn_allocation_create(pj_turn_transport *transport, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len, - const pj_stun_rx_data *rdata, - pj_stun_session *srv_sess, - pj_turn_allocation **p_alloc); + const pj_sockaddr_t *src_addr, + unsigned src_addr_len, + const pj_stun_rx_data *rdata, + pj_stun_session *srv_sess, + pj_turn_allocation **p_alloc); /** * Destroy allocation. */ @@ -214,13 +213,13 @@ PJ_DECL(void) pj_turn_allocation_destroy(pj_turn_allocation *alloc); * Handle incoming packet from client. */ PJ_DECL(void) pj_turn_allocation_on_rx_client_pkt(pj_turn_allocation *alloc, - pj_turn_pkt *pkt); + pj_turn_pkt *pkt); /** * Handle transport closure. */ PJ_DECL(void) pj_turn_allocation_on_transport_closed(pj_turn_allocation *alloc, - pj_turn_transport *tp); + pj_turn_transport *tp); /****************************************************************************/ /* @@ -234,34 +233,34 @@ PJ_DECL(void) pj_turn_allocation_on_transport_closed(pj_turn_allocation *alloc, struct pj_turn_listener { /** Object name/identification */ - char *obj_name; + char *obj_name; /** Slightly longer info about this listener */ - char info[80]; + char info[80]; /** TURN server instance. */ - pj_turn_srv *server; + pj_turn_srv *server; /** Listener index in the server */ - unsigned id; + unsigned id; /** Pool for this listener. */ - pj_pool_t *pool; + pj_pool_t *pool; /** Transport type. */ - int tp_type; + int tp_type; /** Bound address of this listener. */ - pj_sockaddr addr; + pj_sockaddr addr; /** Socket. */ - pj_sock_t sock; + pj_sock_t sock; /** Flags. */ - unsigned flags; + unsigned flags; /** Destroy handler */ - pj_status_t (*destroy)(pj_turn_listener*); + pj_status_t (*destroy)(pj_turn_listener*); }; @@ -272,29 +271,29 @@ struct pj_turn_listener struct pj_turn_transport { /** Object name/identification */ - char *obj_name; + char *obj_name; /** Slightly longer info about this listener */ - char *info; + char *info; /** Listener instance */ - pj_turn_listener *listener; + pj_turn_listener *listener; /** Sendto handler */ - pj_status_t (*sendto)(pj_turn_transport *tp, - const void *packet, - pj_size_t size, - unsigned flag, - const pj_sockaddr_t *addr, - int addr_len); + pj_status_t (*sendto)(pj_turn_transport *tp, + const void *packet, + pj_size_t size, + unsigned flag, + const pj_sockaddr_t *addr, + int addr_len); /** Addref handler */ - void (*add_ref)(pj_turn_transport *tp, - pj_turn_allocation *alloc); + void (*add_ref)(pj_turn_transport *tp, + pj_turn_allocation *alloc); /** Decref handler */ - void (*dec_ref)(pj_turn_transport *tp, - pj_turn_allocation *alloc); + void (*dec_ref)(pj_turn_transport *tp, + pj_turn_allocation *alloc); }; @@ -305,25 +304,25 @@ struct pj_turn_transport struct pj_turn_pkt { /** Pool for this packet */ - pj_pool_t *pool; + pj_pool_t *pool; /** Transport where the packet was received. */ - pj_turn_transport *transport; + pj_turn_transport *transport; /** Packet buffer (must be 32bit aligned). */ - pj_uint8_t pkt[PJ_TURN_MAX_PKT_LEN]; + pj_uint8_t pkt[PJ_TURN_MAX_PKT_LEN]; /** Size of the packet */ - pj_size_t len; + pj_size_t len; /** Arrival time. */ - pj_time_val rx_time; + pj_time_val rx_time; /** Source transport type and source address. */ pj_turn_allocation_key src; /** Source address length. */ - int src_addr_len; + int src_addr_len; }; @@ -331,23 +330,23 @@ struct pj_turn_pkt * Create a UDP listener on the specified port. */ PJ_DECL(pj_status_t) pj_turn_listener_create_udp(pj_turn_srv *srv, - int af, - const pj_str_t *bound_addr, - unsigned port, - unsigned concurrency_cnt, - unsigned flags, - pj_turn_listener **p_lis); + int af, + const pj_str_t *bound_addr, + unsigned port, + unsigned concurrency_cnt, + unsigned flags, + pj_turn_listener **p_lis); /** * Create a TCP listener on the specified port. */ PJ_DECL(pj_status_t) pj_turn_listener_create_tcp(pj_turn_srv *srv, - int af, - const pj_str_t *bound_addr, - unsigned port, - unsigned concurrency_cnt, - unsigned flags, - pj_turn_listener **p_lis); + int af, + const pj_str_t *bound_addr, + unsigned port, + unsigned concurrency_cnt, + unsigned flags, + pj_turn_listener **p_lis); /** * Destroy listener. @@ -359,14 +358,14 @@ PJ_DECL(pj_status_t) pj_turn_listener_destroy(pj_turn_listener *listener); * Add a reference to a transport. */ PJ_DECL(void) pj_turn_transport_add_ref(pj_turn_transport *transport, - pj_turn_allocation *alloc); + pj_turn_allocation *alloc); /** * Decrement transport reference counter. */ PJ_DECL(void) pj_turn_transport_dec_ref(pj_turn_transport *transport, - pj_turn_allocation *alloc); + pj_turn_allocation *alloc); @@ -380,89 +379,89 @@ PJ_DECL(void) pj_turn_transport_dec_ref(pj_turn_transport *transport, struct pj_turn_srv { /** Object name */ - char *obj_name; + char *obj_name; /** Core settings */ struct { - /** Pool factory */ - pj_pool_factory *pf; + /** Pool factory */ + pj_pool_factory *pf; - /** Pool for this server instance. */ - pj_pool_t *pool; + /** Pool for this server instance. */ + pj_pool_t *pool; - /** Global Ioqueue */ - pj_ioqueue_t *ioqueue; + /** Global Ioqueue */ + pj_ioqueue_t *ioqueue; - /** Mutex */ - pj_lock_t *lock; + /** Mutex */ + pj_lock_t *lock; - /** Global timer heap instance. */ - pj_timer_heap_t *timer_heap; + /** Global timer heap instance. */ + pj_timer_heap_t *timer_heap; - /** Number of listeners */ - unsigned lis_cnt; + /** Number of listeners */ + unsigned lis_cnt; - /** Array of listeners. */ - pj_turn_listener **listener; + /** Array of listeners. */ + pj_turn_listener **listener; - /** STUN session to handle initial Allocate request. */ - pj_stun_session *stun_sess; + /** STUN session to handle initial Allocate request. */ + pj_stun_session *stun_sess; - /** Number of worker threads. */ - unsigned thread_cnt; + /** Number of worker threads. */ + unsigned thread_cnt; - /** Array of worker threads. */ - pj_thread_t **thread; + /** Array of worker threads. */ + pj_thread_t **thread; - /** Thread quit signal */ - pj_bool_t quit; + /** Thread quit signal */ + pj_bool_t quit; - /** STUN config. */ - pj_stun_config stun_cfg; + /** STUN config. */ + pj_stun_config stun_cfg; - /** STUN auth credential. */ - pj_stun_auth_cred cred; + /** STUN auth credential. */ + pj_stun_auth_cred cred; - /** Thread local ID for storing credential */ - long tls_key, tls_data; + /** Thread local ID for storing credential */ + long tls_key, tls_data; } core; /** Hash tables */ struct { - /** Allocations hash table, indexed by transport type and - * client address. - */ - pj_hash_table_t *alloc; + /** Allocations hash table, indexed by transport type and + * client address. + */ + pj_hash_table_t *alloc; - /** Relay resource hash table, indexed by transport type and - * relay address. - */ - pj_hash_table_t *res; + /** Relay resource hash table, indexed by transport type and + * relay address. + */ + pj_hash_table_t *res; } tables; /** Ports settings */ struct { - /** Minimum UDP port number. */ - pj_uint16_t min_udp; + /** Minimum UDP port number. */ + pj_uint16_t min_udp; - /** Maximum UDP port number. */ - pj_uint16_t max_udp; + /** Maximum UDP port number. */ + pj_uint16_t max_udp; - /** Next UDP port number. */ - pj_uint16_t next_udp; + /** Next UDP port number. */ + pj_uint16_t next_udp; - /** Minimum TCP port number. */ - pj_uint16_t min_tcp; + /** Minimum TCP port number. */ + pj_uint16_t min_tcp; - /** Maximum TCP port number. */ - pj_uint16_t max_tcp; + /** Maximum TCP port number. */ + pj_uint16_t max_tcp; - /** Next TCP port number. */ - pj_uint16_t next_tcp; + /** Next TCP port number. */ + pj_uint16_t next_tcp; } ports; }; @@ -472,7 +471,7 @@ struct pj_turn_srv * Create server. */ PJ_DECL(pj_status_t) pj_turn_srv_create(pj_pool_factory *pf, - pj_turn_srv **p_srv); + pj_turn_srv **p_srv); /** * Destroy server. @@ -483,26 +482,26 @@ PJ_DECL(pj_status_t) pj_turn_srv_destroy(pj_turn_srv *srv); * Add listener. */ PJ_DECL(pj_status_t) pj_turn_srv_add_listener(pj_turn_srv *srv, - pj_turn_listener *lis); + pj_turn_listener *lis); /** * Register an allocation. */ PJ_DECL(pj_status_t) pj_turn_srv_register_allocation(pj_turn_srv *srv, - pj_turn_allocation *alloc); + pj_turn_allocation *alloc); /** * Unregister an allocation. */ PJ_DECL(pj_status_t) pj_turn_srv_unregister_allocation(pj_turn_srv *srv, - pj_turn_allocation *alloc); + pj_turn_allocation *alloc); /** * This callback is called by UDP listener on incoming packet. */ PJ_DECL(void) pj_turn_srv_on_rx_pkt(pj_turn_srv *srv, - pj_turn_pkt *pkt); + pj_turn_pkt *pkt); -#endif /* __PJ_TURN_SRV_TURN_H__ */ +#endif /* __PJ_TURN_SRV_TURN_H__ */ diff --git a/pjsip-apps/build/dummy.c b/pjsip-apps/build/dummy.c index 5da5da3cba..47b1a6e11c 100644 --- a/pjsip-apps/build/dummy.c +++ b/pjsip-apps/build/dummy.c @@ -1,4 +1,3 @@ -/* $Id$ */ /** * This is an empty C file for helping libpjproject so it gets built properly. diff --git a/pjsip-apps/build/get-footprint.py b/pjsip-apps/build/get-footprint.py index cb6f686884..3dbb8c82e6 100644 --- a/pjsip-apps/build/get-footprint.py +++ b/pjsip-apps/build/get-footprint.py @@ -1,4 +1,3 @@ -# $Id$ # # This file is used to generate PJSIP/PJMEDIA footprint report. # To use this file, just run it in pjsip-apps/build directory, to diff --git a/pjsip-apps/src/3rdparty_media_sample/alt_pjsua_aud.c b/pjsip-apps/src/3rdparty_media_sample/alt_pjsua_aud.c index ee082e514a..180211dd6d 100644 --- a/pjsip-apps/src/3rdparty_media_sample/alt_pjsua_aud.c +++ b/pjsip-apps/src/3rdparty_media_sample/alt_pjsua_aud.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -24,8 +23,8 @@ #endif -#define THIS_FILE "alt_pjsua_aud.c" -#define UNIMPLEMENTED(func) PJ_LOG(2,(THIS_FILE, "*** Call to unimplemented function %s ***", #func)); +#define THIS_FILE "alt_pjsua_aud.c" +#define UNIMPLEMENTED(func) PJ_LOG(2,(THIS_FILE, "*** Call to unimplemented function %s ***", #func)); /***************************************************************************** @@ -37,13 +36,13 @@ */ static struct alt_codec { - pj_str_t encoding_name; - pj_uint8_t payload_type; - unsigned clock_rate; - unsigned channel_cnt; - unsigned frm_ptime; - unsigned avg_bps; - unsigned max_bps; + pj_str_t encoding_name; + pj_uint8_t payload_type; + unsigned clock_rate; + unsigned channel_cnt; + unsigned frm_ptime; + unsigned avg_bps; + unsigned max_bps; } codec_list[] = { /* G.729 */ @@ -56,7 +55,7 @@ static struct alt_codec static struct alt_codec_factory { - pjmedia_codec_factory base; + pjmedia_codec_factory base; } alt_codec_factory; static pj_status_t alt_codec_test_alloc( pjmedia_codec_factory *factory, @@ -64,8 +63,8 @@ static pj_status_t alt_codec_test_alloc( pjmedia_codec_factory *factory, { unsigned i; for (i=0; iencoding_name, &codec_list[i].encoding_name)==0) - return PJ_SUCCESS; + if (pj_stricmp(&id->encoding_name, &codec_list[i].encoding_name)==0) + return PJ_SUCCESS; } return PJ_ENOTSUP; } @@ -80,11 +79,11 @@ static pj_status_t alt_codec_default_attr( pjmedia_codec_factory *factory, PJ_UNUSED_ARG(factory); for (i=0; iencoding_name, &codec_list[i].encoding_name)==0) - break; + if (pj_stricmp(&id->encoding_name, &codec_list[i].encoding_name)==0) + break; } if (i == PJ_ARRAY_SIZE(codec_list)) - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; ac = &codec_list[i]; @@ -105,19 +104,19 @@ static pj_status_t alt_codec_default_attr( pjmedia_codec_factory *factory, } static pj_status_t alt_codec_enum_codecs(pjmedia_codec_factory *factory, - unsigned *count, - pjmedia_codec_info codecs[]) + unsigned *count, + pjmedia_codec_info codecs[]) { unsigned i; for (i=0; i<*count && iencoding_name; - codecs[i].pt = ac->payload_type; - codecs[i].type = PJMEDIA_TYPE_AUDIO; - codecs[i].clock_rate = ac->clock_rate; - codecs[i].channel_cnt = ac->channel_cnt; + struct alt_codec *ac = &codec_list[i]; + pj_bzero(&codecs[i], sizeof(pjmedia_codec_info)); + codecs[i].encoding_name = ac->encoding_name; + codecs[i].pt = ac->payload_type; + codecs[i].type = PJMEDIA_TYPE_AUDIO; + codecs[i].clock_rate = ac->clock_rate; + codecs[i].channel_cnt = ac->channel_cnt; } *count = i; @@ -126,8 +125,8 @@ static pj_status_t alt_codec_enum_codecs(pjmedia_codec_factory *factory, } static pj_status_t alt_codec_alloc_codec(pjmedia_codec_factory *factory, - const pjmedia_codec_info *id, - pjmedia_codec **p_codec) + const pjmedia_codec_info *id, + pjmedia_codec **p_codec) { /* This will never get called since we won't be using this codec */ UNIMPLEMENTED(alt_codec_alloc_codec) @@ -176,9 +175,9 @@ pj_status_t pjsua_aud_subsys_init() alt_codec_factory.base.op = &alt_codec_factory_op; codec_mgr = pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt); status = pjmedia_codec_mgr_register_factory(codec_mgr, - &alt_codec_factory.base); + &alt_codec_factory.base); if (status != PJ_SUCCESS) - return status; + return status; /* TODO: initialize your evil library here */ return PJ_SUCCESS; @@ -225,9 +224,9 @@ static void timer_to_send_aud_rtp(void *user_data) const char *pkt = "Not RTP packet"; if (!call_med->call || !call_med->call->inv || !call_med->tp) { - /* Call has been disconnected. There is race condition here as - * this cb may be called sometime after call has been disconnected */ - return; + /* Call has been disconnected. There is race condition here as + * this cb may be called sometime after call has been disconnected */ + return; } pjmedia_transport_send_rtp(call_med->tp, pkt, strlen(pkt)); @@ -241,9 +240,9 @@ static void timer_to_send_aud_rtcp(void *user_data) const char *pkt = "Not RTCP packet"; if (!call_med->call || !call_med->call->inv || !call_med->tp) { - /* Call has been disconnected. There is race condition here as - * this cb may be called sometime after call has been disconnected */ - return; + /* Call has been disconnected. There is race condition here as + * this cb may be called sometime after call has been disconnected */ + return; } pjmedia_transport_send_rtcp(call_med->tp, pkt, strlen(pkt)); @@ -256,7 +255,7 @@ void pjsua_aud_stop_stream(pjsua_call_media *call_med) { /* Detach our RTP/RTCP callbacks from transport */ if (call_med->tp) { - pjmedia_transport_detach(call_med->tp, call_med); + pjmedia_transport_detach(call_med->tp, call_med); } /* TODO: destroy your audio stream here */ @@ -270,8 +269,8 @@ void pjsua_aud_stop_stream(pjsua_call_media *call_med) pj_status_t pjsua_aud_channel_update(pjsua_call_media *call_med, pj_pool_t *tmp_pool, pjmedia_stream_info *si, - const pjmedia_sdp_session *local_sdp, - const pjmedia_sdp_session *remote_sdp) + const pjmedia_sdp_session *local_sdp, + const pjmedia_sdp_session *remote_sdp) { pj_status_t status = PJ_SUCCESS; @@ -280,22 +279,22 @@ pj_status_t pjsua_aud_channel_update(pjsua_call_media *call_med, /* Check if no media is active */ if (si->dir != PJMEDIA_DIR_NONE) { - /* Attach our RTP and RTCP callbacks to the media transport */ - status = pjmedia_transport_attach(call_med->tp, call_med, - &si->rem_addr, &si->rem_rtcp, - pj_sockaddr_get_len(&si->rem_addr), - &aud_rtp_cb, &aud_rtcp_cb); - - /* For a demonstration, let's use a timer to send "RTP" packet - * periodically. - */ - pjsua_schedule_timer2(&timer_to_send_aud_rtp, call_med, 0); - pjsua_schedule_timer2(&timer_to_send_aud_rtcp, call_med, 2500); - - /* TODO: - * - Create and start your media stream based on the parameters - * in si - */ + /* Attach our RTP and RTCP callbacks to the media transport */ + status = pjmedia_transport_attach(call_med->tp, call_med, + &si->rem_addr, &si->rem_rtcp, + pj_sockaddr_get_len(&si->rem_addr), + &aud_rtp_cb, &aud_rtcp_cb); + + /* For a demonstration, let's use a timer to send "RTP" packet + * periodically. + */ + pjsua_schedule_timer2(&timer_to_send_aud_rtp, call_med, 0); + pjsua_schedule_timer2(&timer_to_send_aud_rtcp, call_med, 2500); + + /* TODO: + * - Create and start your media stream based on the parameters + * in si + */ } on_return: @@ -331,7 +330,7 @@ PJ_DEF(pjsua_conf_port_id) pjsua_call_get_conf_port(pjsua_call_id call_id) PJ_DEF(pj_status_t) pjsua_call_aud_stream_modify_codec_param(pjsua_call_id call_id, int med_idx, - const pjmedia_codec_param *param) + const pjmedia_codec_param *param) { UNIMPLEMENTED(pjsua_call_aud_stream_modify_codec_param) return PJ_ENOTSUP; @@ -361,7 +360,7 @@ PJ_DEF(pj_status_t) pjsua_call_get_stream_stat( pjsua_call_id call_id, * Send DTMF digits to remote using RFC 2833 payload formats. */ PJ_DEF(pj_status_t) pjsua_call_dial_dtmf( pjsua_call_id call_id, - const pj_str_t *digits) + const pj_str_t *digits) { UNIMPLEMENTED(pjsua_call_dial_dtmf) return PJ_ENOTSUP; @@ -393,7 +392,7 @@ PJ_DEF(unsigned) pjsua_conf_get_active_ports(void) /* Enumerate all conference ports. */ PJ_DEF(pj_status_t) pjsua_enum_conf_ports(pjsua_conf_port_id id[], - unsigned *count) + unsigned *count) { *count = 0; UNIMPLEMENTED(pjsua_enum_conf_ports) @@ -402,7 +401,7 @@ PJ_DEF(pj_status_t) pjsua_enum_conf_ports(pjsua_conf_port_id id[], /* Get information about the specified conference port */ PJ_DEF(pj_status_t) pjsua_conf_get_port_info( pjsua_conf_port_id id, - pjsua_conf_port_info *info) + pjsua_conf_port_info *info) { UNIMPLEMENTED(pjsua_conf_get_port_info) return PJ_ENOTSUP; @@ -410,8 +409,8 @@ PJ_DEF(pj_status_t) pjsua_conf_get_port_info( pjsua_conf_port_id id, /* Add arbitrary media port to PJSUA's conference bridge. */ PJ_DEF(pj_status_t) pjsua_conf_add_port( pj_pool_t *pool, - pjmedia_port *port, - pjsua_conf_port_id *p_id) + pjmedia_port *port, + pjsua_conf_port_id *p_id) { *p_id = PJSUA_INVALID_ID; UNIMPLEMENTED(pjsua_conf_add_port) @@ -430,7 +429,7 @@ PJ_DEF(pj_status_t) pjsua_conf_remove_port(pjsua_conf_port_id id) /* Establish unidirectional media flow from souce to sink. */ PJ_DEF(pj_status_t) pjsua_conf_connect( pjsua_conf_port_id source, - pjsua_conf_port_id sink) + pjsua_conf_port_id sink) { UNIMPLEMENTED(pjsua_conf_connect) return PJ_ENOTSUP; @@ -441,8 +440,8 @@ PJ_DEF(pj_status_t) pjsua_conf_connect( pjsua_conf_port_id source, * level adjustment. */ PJ_DEF(pj_status_t) pjsua_conf_connect2( pjsua_conf_port_id source, - pjsua_conf_port_id sink, - const pjsua_conf_connect_param *prm) + pjsua_conf_port_id sink, + const pjsua_conf_connect_param *prm) { UNIMPLEMENTED(pjsua_conf_connect2) return PJ_ENOTSUP; @@ -450,7 +449,7 @@ PJ_DEF(pj_status_t) pjsua_conf_connect2( pjsua_conf_port_id source, /* Disconnect media flow from the source to destination port. */ PJ_DEF(pj_status_t) pjsua_conf_disconnect( pjsua_conf_port_id source, - pjsua_conf_port_id sink) + pjsua_conf_port_id sink) { UNIMPLEMENTED(pjsua_conf_disconnect) return PJ_ENOTSUP; @@ -460,7 +459,7 @@ PJ_DEF(pj_status_t) pjsua_conf_disconnect( pjsua_conf_port_id source, * specified port by making it louder or quieter. */ PJ_DEF(pj_status_t) pjsua_conf_adjust_tx_level(pjsua_conf_port_id slot, - float level) + float level) { UNIMPLEMENTED(pjsua_conf_adjust_tx_level) return PJ_ENOTSUP; @@ -470,7 +469,7 @@ PJ_DEF(pj_status_t) pjsua_conf_adjust_tx_level(pjsua_conf_port_id slot, * the bridge) by making it louder or quieter. */ PJ_DEF(pj_status_t) pjsua_conf_adjust_rx_level(pjsua_conf_port_id slot, - float level) + float level) { UNIMPLEMENTED(pjsua_conf_adjust_rx_level) return PJ_ENOTSUP; @@ -479,8 +478,8 @@ PJ_DEF(pj_status_t) pjsua_conf_adjust_rx_level(pjsua_conf_port_id slot, /* Get last signal level transmitted to or received from the specified port. */ PJ_DEF(pj_status_t) pjsua_conf_get_signal_level(pjsua_conf_port_id slot, - unsigned *tx_level, - unsigned *rx_level) + unsigned *tx_level, + unsigned *rx_level) { UNIMPLEMENTED(pjsua_conf_get_signal_level) return PJ_ENOTSUP; @@ -490,8 +489,8 @@ PJ_DEF(pj_status_t) pjsua_conf_get_signal_level(pjsua_conf_port_id slot, * the conference bridge. */ PJ_DEF(pj_status_t) pjsua_player_create( const pj_str_t *filename, - unsigned options, - pjsua_player_id *p_id) + unsigned options, + pjsua_player_id *p_id) { UNIMPLEMENTED(pjsua_player_create) return PJ_ENOTSUP; @@ -501,10 +500,10 @@ PJ_DEF(pj_status_t) pjsua_player_create( const pj_str_t *filename, * to the conference bridge. */ PJ_DEF(pj_status_t) pjsua_playlist_create( const pj_str_t file_names[], - unsigned file_count, - const pj_str_t *label, - unsigned options, - pjsua_player_id *p_id) + unsigned file_count, + const pj_str_t *label, + unsigned options, + pjsua_player_id *p_id) { UNIMPLEMENTED(pjsua_playlist_create) return PJ_ENOTSUP; @@ -519,7 +518,7 @@ PJ_DEF(pjsua_conf_port_id) pjsua_player_get_conf_port(pjsua_player_id id) /* Get the media port for the player. */ PJ_DEF(pj_status_t) pjsua_player_get_port( pjsua_player_id id, - pjmedia_port **p_port) + pjmedia_port **p_port) { UNIMPLEMENTED(pjsua_player_get_port) return PJ_ENOTSUP; @@ -542,7 +541,7 @@ PJ_DEF(pj_ssize_t) pjsua_player_get_pos(pjsua_player_id id) /* Set playback position. */ PJ_DEF(pj_status_t) pjsua_player_set_pos( pjsua_player_id id, - pj_uint32_t samples) + pj_uint32_t samples) { UNIMPLEMENTED(pjsua_player_set_pos) return PJ_ENOTSUP; @@ -561,11 +560,11 @@ PJ_DEF(pj_status_t) pjsua_player_destroy(pjsua_player_id id) * the conference bridge. */ PJ_DEF(pj_status_t) pjsua_recorder_create( const pj_str_t *filename, - unsigned enc_type, - void *enc_param, - pj_ssize_t max_size, - unsigned options, - pjsua_recorder_id *p_id) + unsigned enc_type, + void *enc_param, + pj_ssize_t max_size, + unsigned options, + pjsua_recorder_id *p_id) { UNIMPLEMENTED(pjsua_recorder_create) return PJ_ENOTSUP; @@ -581,7 +580,7 @@ PJ_DEF(pjsua_conf_port_id) pjsua_recorder_get_conf_port(pjsua_recorder_id id) /* Get the media port for the recorder. */ PJ_DEF(pj_status_t) pjsua_recorder_get_port( pjsua_recorder_id id, - pjmedia_port **p_port) + pjmedia_port **p_port) { UNIMPLEMENTED(pjsua_recorder_get_port) return PJ_ENOTSUP; @@ -596,14 +595,14 @@ PJ_DEF(pj_status_t) pjsua_recorder_destroy(pjsua_recorder_id id) /* Enum sound devices. */ PJ_DEF(pj_status_t) pjsua_enum_aud_devs( pjmedia_aud_dev_info info[], - unsigned *count) + unsigned *count) { UNIMPLEMENTED(pjsua_enum_aud_devs) return PJ_ENOTSUP; } PJ_DEF(pj_status_t) pjsua_enum_snd_devs( pjmedia_snd_dev_info info[], - unsigned *count) + unsigned *count) { UNIMPLEMENTED(pjsua_enum_snd_devs) return PJ_ENOTSUP; @@ -678,7 +677,7 @@ PJ_DEF(pj_bool_t) pjsua_snd_is_active(void) /* Configure sound device setting to the sound device being used. */ PJ_DEF(pj_status_t) pjsua_snd_set_setting( pjmedia_aud_dev_cap cap, - const void *pval, pj_bool_t keep) + const void *pval, pj_bool_t keep) { UNIMPLEMENTED(pjsua_snd_set_setting) return PJ_ENOTSUP; @@ -693,7 +692,7 @@ PJ_DEF(pj_status_t) pjsua_snd_get_setting(pjmedia_aud_dev_cap cap, void *pval) /* Create an extra sound device and register it to conference bridge. */ PJ_DEF(pj_status_t) pjsua_ext_snd_dev_create( pjmedia_snd_port_param *param, - pjsua_ext_snd_dev **p_snd) + pjsua_ext_snd_dev **p_snd) { UNIMPLEMENTED(pjsua_ext_snd_dev_create) return PJ_ENOTSUP; @@ -708,7 +707,7 @@ PJ_DEF(pj_status_t) pjsua_ext_snd_dev_destroy(pjsua_ext_snd_dev *snd) /* Get sound port instance of an extra sound device. */ PJ_DEF(pjmedia_snd_port*) pjsua_ext_snd_dev_get_snd_port( - pjsua_ext_snd_dev *snd) + pjsua_ext_snd_dev *snd) { UNIMPLEMENTED(pjsua_ext_snd_dev_get_snd_port) return NULL; @@ -716,7 +715,7 @@ PJ_DEF(pjmedia_snd_port*) pjsua_ext_snd_dev_get_snd_port( /* Get conference port ID of an extra sound device. */ PJ_DEF(pjsua_conf_port_id) pjsua_ext_snd_dev_get_conf_port( - pjsua_ext_snd_dev *snd) + pjsua_ext_snd_dev *snd) { UNIMPLEMENTED(pjsua_ext_snd_dev_get_conf_port) return PJSUA_INVALID_ID; diff --git a/pjsip-apps/src/3rdparty_media_sample/alt_pjsua_vid.c b/pjsip-apps/src/3rdparty_media_sample/alt_pjsua_vid.c index a17f918d33..376659b947 100644 --- a/pjsip-apps/src/3rdparty_media_sample/alt_pjsua_vid.c +++ b/pjsip-apps/src/3rdparty_media_sample/alt_pjsua_vid.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011-2011 Teluu Inc. (http://www.teluu.com) * @@ -25,8 +24,8 @@ #if PJSUA_HAS_VIDEO -#define THIS_FILE "alt_pjsua_vid.c" -#define UNIMPLEMENTED(func) PJ_LOG(2,(THIS_FILE, "*** Call to unimplemented function %s ***", #func)); +#define THIS_FILE "alt_pjsua_vid.c" +#define UNIMPLEMENTED(func) PJ_LOG(2,(THIS_FILE, "*** Call to unimplemented function %s ***", #func)); /***************************************************************************** * Our video codec descriptors @@ -35,21 +34,21 @@ struct alt_codec_desc { /* Predefined info */ pjmedia_vid_codec_info info; - pjmedia_format_id base_fmt_id; - pj_uint32_t avg_bps; - pj_uint32_t max_bps; - pjmedia_codec_fmtp dec_fmtp; + pjmedia_format_id base_fmt_id; + pj_uint32_t avg_bps; + pj_uint32_t max_bps; + pjmedia_codec_fmtp dec_fmtp; } alt_vid_codecs[] = { /* H.263+ */ { - {PJMEDIA_FORMAT_H263P, PJMEDIA_RTP_PT_H263P, {"H263-1998",9}, - {"H.263 codec", 11}, 90000, PJMEDIA_DIR_ENCODING_DECODING, - 0, {PJMEDIA_FORMAT_RGB24}, PJMEDIA_VID_PACKING_PACKETS - }, - PJMEDIA_FORMAT_H263, 256000, 512000, - {2, { {{"CIF",3}, {"1",1}}, - {{"QCIF",4}, {"1",1}}, } }, + {PJMEDIA_FORMAT_H263P, PJMEDIA_RTP_PT_H263P, {"H263-1998",9}, + {"H.263 codec", 11}, 90000, PJMEDIA_DIR_ENCODING_DECODING, + 0, {PJMEDIA_FORMAT_RGB24}, PJMEDIA_VID_PACKING_PACKETS + }, + PJMEDIA_FORMAT_H263, 256000, 512000, + {2, { {{"CIF",3}, {"1",1}}, + {{"QCIF",4}, {"1",1}}, } }, } }; @@ -57,11 +56,11 @@ static const struct alt_codec_desc* find_codec_desc_by_info(const pjmedia_vid_co { unsigned i; for (i=0; iinfo.fmt_id == info->fmt_id) && + struct alt_codec_desc *desc = &alt_vid_codecs[i]; + if ((desc->info.fmt_id == info->fmt_id) && ((desc->info.dir & info->dir) == info->dir) && - (desc->info.pt == info->pt) && - (desc->info.packings & info->packings)) + (desc->info.pt == info->pt) && + (desc->info.packings & info->packings)) { return desc; } @@ -92,15 +91,15 @@ static pj_status_t alt_vid_codec_default_attr( pjmedia_vid_codec_factory *factor /* Scan the requested packings and use the lowest number */ attr->packing = 0; for (i=0; i<15; ++i) { - unsigned packing = (1 << i); - if ((desc->info.packings & info->packings) & packing) { - attr->packing = (pjmedia_vid_packing)packing; - break; - } + unsigned packing = (1 << i); + if ((desc->info.packings & info->packings) & packing) { + attr->packing = (pjmedia_vid_packing)packing; + break; + } } if (attr->packing == 0) { - /* No supported packing in info */ - return PJMEDIA_CODEC_EUNSUP; + /* No supported packing in info */ + return PJMEDIA_CODEC_EUNSUP; } /* Direction */ @@ -130,8 +129,8 @@ static pj_status_t alt_vid_codec_default_attr( pjmedia_vid_codec_factory *factor static pj_status_t alt_vid_codec_enum_codecs( pjmedia_vid_codec_factory *factory, - unsigned *count, - pjmedia_vid_codec_info codecs[]) + unsigned *count, + pjmedia_vid_codec_info codecs[]) { unsigned i, max_cnt; @@ -141,9 +140,9 @@ static pj_status_t alt_vid_codec_enum_codecs( pjmedia_vid_codec_factory *factory *count = 0; for (i=0; itp) { - pjmedia_transport_detach(call_med->tp, call_med); + pjmedia_transport_detach(call_med->tp, call_med); } /* @@ -298,9 +297,9 @@ static void timer_to_send_vid_rtp(void *user_data) const char *pkt = "Not RTP packet"; if (!call_med->call || !call_med->call->inv || !call_med->tp) { - /* Call has been disconnected. There is race condition here as - * this cb may be called sometime after call has been disconnected */ - return; + /* Call has been disconnected. There is race condition here as + * this cb may be called sometime after call has been disconnected */ + return; } pjmedia_transport_send_rtp(call_med->tp, pkt, strlen(pkt)); @@ -314,9 +313,9 @@ static void timer_to_send_vid_rtcp(void *user_data) const char *pkt = "Not RTCP packet"; if (!call_med->call || !call_med->call->inv || !call_med->tp) { - /* Call has been disconnected. There is race condition here as - * this cb may be called sometime after call has been disconnected */ - return; + /* Call has been disconnected. There is race condition here as + * this cb may be called sometime after call has been disconnected */ + return; } pjmedia_transport_send_rtcp(call_med->tp, pkt, strlen(pkt)); @@ -326,10 +325,10 @@ static void timer_to_send_vid_rtcp(void *user_data) /* update video channel after SDP negotiation */ pj_status_t pjsua_vid_channel_update(pjsua_call_media *call_med, - pj_pool_t *tmp_pool, - pjmedia_vid_stream_info *si, - const pjmedia_sdp_session *local_sdp, - const pjmedia_sdp_session *remote_sdp) + pj_pool_t *tmp_pool, + pjmedia_vid_stream_info *si, + const pjmedia_sdp_session *local_sdp, + const pjmedia_sdp_session *remote_sdp) { pj_status_t status; @@ -338,22 +337,22 @@ pj_status_t pjsua_vid_channel_update(pjsua_call_media *call_med, /* Check if no media is active */ if (si->dir != PJMEDIA_DIR_NONE) { - /* Attach our RTP and RTCP callbacks to the media transport */ - status = pjmedia_transport_attach(call_med->tp, call_med, - &si->rem_addr, &si->rem_rtcp, - pj_sockaddr_get_len(&si->rem_addr), - &vid_rtp_cb, &vid_rtcp_cb); - /* - * TODO: - * - Create and start your video stream based on the parameters - * in si - */ - - /* For a demonstration, let's use a timer to send "RTP" packet - * periodically. - */ - pjsua_schedule_timer2(&timer_to_send_vid_rtp, call_med, 1000); - pjsua_schedule_timer2(&timer_to_send_vid_rtcp, call_med, 3500); + /* Attach our RTP and RTCP callbacks to the media transport */ + status = pjmedia_transport_attach(call_med->tp, call_med, + &si->rem_addr, &si->rem_rtcp, + pj_sockaddr_get_len(&si->rem_addr), + &vid_rtp_cb, &vid_rtcp_cb); + /* + * TODO: + * - Create and start your video stream based on the parameters + * in si + */ + + /* For a demonstration, let's use a timer to send "RTP" packet + * periodically. + */ + pjsua_schedule_timer2(&timer_to_send_vid_rtp, call_med, 1000); + pjsua_schedule_timer2(&timer_to_send_vid_rtcp, call_med, 3500); } pj_log_pop_indent(); @@ -388,7 +387,7 @@ PJ_DEF(pjsua_vid_win_id) pjsua_vid_preview_get_win(pjmedia_vid_dev_index id) /* Get video conference slot ID of the specified capture device. */ PJ_DEF(pjsua_conf_port_id) pjsua_vid_preview_get_vid_conf_port( - pjmedia_vid_dev_index id) + pjmedia_vid_dev_index id) { UNIMPLEMENTED(pjsua_vid_preview_get_vid_conf_port) return PJSUA_INVALID_ID; @@ -451,7 +450,7 @@ PJ_DEF(pj_status_t) pjsua_vid_dev_get_info(pjmedia_vid_dev_index id, /* Enum all video devices installed in the system. */ PJ_DEF(pj_status_t) pjsua_vid_enum_devs(pjmedia_vid_dev_info info[], - unsigned *count) + unsigned *count) { UNIMPLEMENTED(pjsua_vid_enum_devs) return PJ_ENOTSUP; @@ -466,9 +465,9 @@ PJ_DEF(pj_bool_t) pjsua_vid_dev_is_active(pjmedia_vid_dev_index id) /* Set the capability of the video device. */ PJ_DEF(pj_status_t) pjsua_vid_dev_set_setting( pjmedia_vid_dev_index id, - pjmedia_vid_dev_cap cap, - const void *pval, - pj_bool_t keep) + pjmedia_vid_dev_cap cap, + const void *pval, + pj_bool_t keep) { UNIMPLEMENTED(pjsua_vid_dev_set_setting) return PJ_ENOTSUP; @@ -476,8 +475,8 @@ PJ_DEF(pj_status_t) pjsua_vid_dev_set_setting( pjmedia_vid_dev_index id, /* Get the value of the video device capability. */ PJ_DEF(pj_status_t) pjsua_vid_dev_get_setting( pjmedia_vid_dev_index id, - pjmedia_vid_dev_cap cap, - void *pval) + pjmedia_vid_dev_cap cap, + void *pval) { UNIMPLEMENTED(pjsua_vid_dev_get_setting) return PJ_ENOTSUP; @@ -489,7 +488,7 @@ PJ_DEF(pj_status_t) pjsua_vid_dev_get_setting( pjmedia_vid_dev_index id, /* Enum all supported video codecs in the system. */ PJ_DEF(pj_status_t) pjsua_vid_enum_codecs( pjsua_codec_info id[], - unsigned *p_count ) + unsigned *p_count ) { pjmedia_vid_codec_info info[32]; unsigned i, j, count, prio[32]; @@ -498,25 +497,25 @@ PJ_DEF(pj_status_t) pjsua_vid_enum_codecs( pjsua_codec_info id[], count = PJ_ARRAY_SIZE(info); status = pjmedia_vid_codec_mgr_enum_codecs(NULL, &count, info, prio); if (status != PJ_SUCCESS) { - *p_count = 0; - return status; + *p_count = 0; + return status; } for (i=0, j=0; isubmenu_cnt]; NSMutableArray *smenu; for (int i = 0; i < menu->submenu_cnt; i++) { - NSString *str = [NSString stringWithFormat:@"%s" , menu->submenus[i]->title]; - [view.titles addObject: str]; - smenu = [NSMutableArray arrayWithCapacity:menu->submenus[i]->submenu_cnt]; - /* We do not need the last two menus of the "Tests" menu (NULL and "Exit"), - * so subtract by 2 - */ - for (int j = 0; j < menu->submenus[i]->submenu_cnt - (i==0? 2: 0); j++) { - str = [NSString stringWithFormat:@"%s" , menu->submenus[i]->submenus[j]->title]; - [smenu addObject:str]; - } - [view.menus addObject:smenu]; + NSString *str = [NSString stringWithFormat:@"%s" , menu->submenus[i]->title]; + [view.titles addObject: str]; + smenu = [NSMutableArray arrayWithCapacity:menu->submenus[i]->submenu_cnt]; + /* We do not need the last two menus of the "Tests" menu (NULL and "Exit"), + * so subtract by 2 + */ + for (int j = 0; j < menu->submenus[i]->submenu_cnt - (i==0? 2: 0); j++) { + str = [NSString stringWithFormat:@"%s" , menu->submenus[i]->submenus[j]->title]; + [smenu addObject:str]; + } + [view.menus addObject:smenu]; } gmenu = menu; @@ -87,16 +86,16 @@ enum gui_key gui_msgbox(const char *title, const char *message, enum gui_flag fl view.testView.key = 0; while(view.testView.key == 0) { - /* Let the main thread do its job (refresh the view) while we wait for - * user interaction (button click) - */ - [NSThread sleepForTimeInterval:SLEEP_INTERVAL]; + /* Let the main thread do its job (refresh the view) while we wait for + * user interaction (button click) + */ + [NSThread sleepForTimeInterval:SLEEP_INTERVAL]; } if (view.testView.key == 1) - return KEY_OK; + return KEY_OK; else - return (flag == WITH_YESNO? KEY_NO: KEY_CANCEL); + return (flag == WITH_YESNO? KEY_NO: KEY_CANCEL); } /* AUX: sleep */ @@ -126,7 +125,7 @@ - (void)viewDidLoad { [NSThread detachNewThreadSelector:@selector(startTest) toTarget:self withObject:nil]; /* Let our new thread initialize */ while (!systest_initialized) { - [NSThread sleepForTimeInterval:SLEEP_INTERVAL]; + [NSThread sleepForTimeInterval:SLEEP_INTERVAL]; } // Uncomment the following line to display an Edit button in the navigation bar for this view controller. @@ -218,21 +217,21 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N - (void)startTest { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (systest_init() != PJ_SUCCESS) { - [pool release]; - return; + [pool release]; + return; } systest_run(); systest_initialized = 1; while(!thread_quit) { - section = -1; - while (section == -1) { - [NSThread sleepForTimeInterval:SLEEP_INTERVAL]; - } - (*gmenu->submenus[section]->submenus[row]->handler)(); - cmsg = NULL; - [view performSelectorOnMainThread:@selector(showMsg) withObject:nil waitUntilDone:YES]; + section = -1; + while (section == -1) { + [NSThread sleepForTimeInterval:SLEEP_INTERVAL]; + } + (*gmenu->submenus[section]->submenus[row]->handler)(); + cmsg = NULL; + [view performSelectorOnMainThread:@selector(showMsg) withObject:nil waitUntilDone:YES]; } systest_deinit(); @@ -241,11 +240,11 @@ - (void)startTest { - (void)showMsg { if (cmsg == NULL) { - self.testView.testDesc.text = [self.testView.testDesc.text stringByAppendingString: @"Finished"]; - [self.testView.testDesc scrollRangeToVisible:NSMakeRange([self.testView.testDesc.text length] - 1, 1)]; - [self.testView.button1 setHidden:true]; - [self.testView.button2 setHidden:true]; - return; + self.testView.testDesc.text = [self.testView.testDesc.text stringByAppendingString: @"Finished"]; + [self.testView.testDesc scrollRangeToVisible:NSMakeRange([self.testView.testDesc.text length] - 1, 1)]; + [self.testView.button1 setHidden:true]; + [self.testView.button2 setHidden:true]; + return; } self.testView.title = [NSString stringWithFormat:@"%s", ctitle]; self.testView.testDesc.text = [self.testView.testDesc.text stringByAppendingString: [NSString stringWithFormat:@"%s\n\n", cmsg]]; @@ -254,14 +253,14 @@ - (void)showMsg { [self.testView.button1 setHidden:false]; [self.testView.button2 setHidden:false]; if (cflag == WITH_YESNO) { - [self.testView.button1 setTitle:@"Yes" forState:UIControlStateNormal]; - [self.testView.button2 setTitle:@"No" forState:UIControlStateNormal]; + [self.testView.button1 setTitle:@"Yes" forState:UIControlStateNormal]; + [self.testView.button2 setTitle:@"No" forState:UIControlStateNormal]; } else if (cflag == WITH_OK) { - [self.testView.button1 setTitle:@"OK" forState:UIControlStateNormal]; - [self.testView.button2 setHidden:true]; + [self.testView.button1 setTitle:@"OK" forState:UIControlStateNormal]; + [self.testView.button2 setHidden:true]; } else if (cflag == WITH_OKCANCEL) { - [self.testView.button1 setTitle:@"OK" forState:UIControlStateNormal]; - [self.testView.button2 setTitle:@"Cancel" forState:UIControlStateNormal]; + [self.testView.button1 setTitle:@"OK" forState:UIControlStateNormal]; + [self.testView.button2 setTitle:@"Cancel" forState:UIControlStateNormal]; } } @@ -275,7 +274,7 @@ - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath // [anotherViewController release]; if (self.testView == nil) { - self.testView = [[TestViewController alloc] initWithNibName:@"TestViewController" bundle:[NSBundle mainBundle]]; + self.testView = [[TestViewController alloc] initWithNibName:@"TestViewController" bundle:[NSBundle mainBundle]]; } [self.navigationController pushViewController:self.testView animated:YES]; @@ -300,11 +299,11 @@ - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *) - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { - // Delete the row from the data source. - [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; + // Delete the row from the data source. + [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { - // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. + // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } */ diff --git a/pjsip-apps/src/ipjsystest/Classes/TestViewController.h b/pjsip-apps/src/ipjsystest/Classes/TestViewController.h index 7186f28652..b8bb9ef0b7 100644 --- a/pjsip-apps/src/ipjsystest/Classes/TestViewController.h +++ b/pjsip-apps/src/ipjsystest/Classes/TestViewController.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * @@ -21,8 +20,8 @@ @interface TestViewController : UIViewController { IBOutlet UITextView *testDesc; - IBOutlet UIButton *button1; - IBOutlet UIButton *button2; + IBOutlet UIButton *button1; + IBOutlet UIButton *button2; NSInteger key; } diff --git a/pjsip-apps/src/ipjsystest/Classes/TestViewController.m b/pjsip-apps/src/ipjsystest/Classes/TestViewController.m index ae816cccfb..b2e03427d9 100644 --- a/pjsip-apps/src/ipjsystest/Classes/TestViewController.m +++ b/pjsip-apps/src/ipjsystest/Classes/TestViewController.m @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjsip-apps/src/ipjsystest/Classes/ipjsystestAppDelegate.h b/pjsip-apps/src/ipjsystest/Classes/ipjsystestAppDelegate.h index 9e357aa431..3dc22f1ca3 100644 --- a/pjsip-apps/src/ipjsystest/Classes/ipjsystestAppDelegate.h +++ b/pjsip-apps/src/ipjsystest/Classes/ipjsystestAppDelegate.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * @@ -18,7 +17,7 @@ */ @interface ipjsystestAppDelegate : NSObject { - UIWindow *window; + UIWindow *window; UINavigationController *navigationController; } diff --git a/pjsip-apps/src/ipjsystest/Classes/ipjsystestAppDelegate.m b/pjsip-apps/src/ipjsystest/Classes/ipjsystestAppDelegate.m index 7e2f591245..ff5277547f 100644 --- a/pjsip-apps/src/ipjsystest/Classes/ipjsystestAppDelegate.m +++ b/pjsip-apps/src/ipjsystest/Classes/ipjsystestAppDelegate.m @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjsip-apps/src/ipjsystest/main.m b/pjsip-apps/src/ipjsystest/main.m index ac388411f8..2b01c71f6b 100644 --- a/pjsip-apps/src/ipjsystest/main.m +++ b/pjsip-apps/src/ipjsystest/main.m @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjsip-apps/src/pjsua/android/app/src/main/java/MainActivity.java b/pjsip-apps/src/pjsua/android/app/src/main/java/MainActivity.java index b7114ce8c4..abe7814fd5 100644 --- a/pjsip-apps/src/pjsua/android/app/src/main/java/MainActivity.java +++ b/pjsip-apps/src/pjsua/android/app/src/main/java/MainActivity.java @@ -39,30 +39,30 @@ class CONST { public static final String TAG = "pjsua"; public static final Boolean AUTOKILL_ON_FINISH = true; public enum MSG_TYPE { - STR_DEBUG, - STR_INFO, - STR_ERROR, - CLI_STOP, - CLI_RESTART, - QUIT + STR_DEBUG, + STR_INFO, + STR_ERROR, + CLI_STOP, + CLI_RESTART, + QUIT }; } class LOG { public static void DEBUG(Handler h, String str) { - Message msg = Message.obtain(h, CONST.MSG_TYPE.STR_DEBUG.ordinal(), - str); - msg.sendToTarget(); - } + Message msg = Message.obtain(h, CONST.MSG_TYPE.STR_DEBUG.ordinal(), + str); + msg.sendToTarget(); + } public static void INFO(Handler h, String str) { - Message msg = Message.obtain(h, CONST.MSG_TYPE.STR_INFO.ordinal(), - str); - msg.sendToTarget(); + Message msg = Message.obtain(h, CONST.MSG_TYPE.STR_INFO.ordinal(), + str); + msg.sendToTarget(); } public static void ERROR(Handler h, String str) { - Message msg = Message.obtain(h, CONST.MSG_TYPE.STR_ERROR.ordinal(), - str); - msg.sendToTarget(); + Message msg = Message.obtain(h, CONST.MSG_TYPE.STR_ERROR.ordinal(), + str); + msg.sendToTarget(); } } @@ -71,76 +71,76 @@ public class MainActivity extends Activity implements SurfaceHolder.Callback { private static MyCallback callback; private static class MyHandler extends Handler { - private final WeakReference mTarget; - - public MyHandler(MainActivity target) { - mTarget = new WeakReference(target); - } - - @Override - public void handleMessage(Message m) { - MainActivity target = mTarget.get(); - if (target == null) - return; - - if (m.what == CONST.MSG_TYPE.STR_DEBUG.ordinal()) { - Log.d(CONST.TAG, (String)m.obj); - } else if (m.what == CONST.MSG_TYPE.STR_INFO.ordinal()) { - target.updateStatus((String)m.obj); - Log.i(CONST.TAG, (String)m.obj); - } else if (m.what == CONST.MSG_TYPE.STR_ERROR.ordinal()) { - target.updateStatus((String)m.obj); - Log.e(CONST.TAG, (String)m.obj); - } else if (m.what == CONST.MSG_TYPE.CLI_STOP.ordinal()) { - pjsua.pjsuaDestroy(); - LOG.INFO(this, "Telnet Unavailable"); - } else if (m.what == CONST.MSG_TYPE.CLI_RESTART.ordinal()) { - int status = pjsua.pjsuaRestart(); - if (status != 0) { - LOG.INFO(this, "Failed restarting telnet"); - } - } else if (m.what == CONST.MSG_TYPE.QUIT.ordinal()) { - target.finish(); - System.gc(); - android.os.Process.killProcess(android.os.Process.myPid()); - } - } + private final WeakReference mTarget; + + public MyHandler(MainActivity target) { + mTarget = new WeakReference(target); + } + + @Override + public void handleMessage(Message m) { + MainActivity target = mTarget.get(); + if (target == null) + return; + + if (m.what == CONST.MSG_TYPE.STR_DEBUG.ordinal()) { + Log.d(CONST.TAG, (String)m.obj); + } else if (m.what == CONST.MSG_TYPE.STR_INFO.ordinal()) { + target.updateStatus((String)m.obj); + Log.i(CONST.TAG, (String)m.obj); + } else if (m.what == CONST.MSG_TYPE.STR_ERROR.ordinal()) { + target.updateStatus((String)m.obj); + Log.e(CONST.TAG, (String)m.obj); + } else if (m.what == CONST.MSG_TYPE.CLI_STOP.ordinal()) { + pjsua.pjsuaDestroy(); + LOG.INFO(this, "Telnet Unavailable"); + } else if (m.what == CONST.MSG_TYPE.CLI_RESTART.ordinal()) { + int status = pjsua.pjsuaRestart(); + if (status != 0) { + LOG.INFO(this, "Failed restarting telnet"); + } + } else if (m.what == CONST.MSG_TYPE.QUIT.ordinal()) { + target.finish(); + System.gc(); + android.os.Process.killProcess(android.os.Process.myPid()); + } + } } /** Callback object **/ private static class MyCallback extends PjsuaAppCallback { - private WeakReference ui_handler; - - public MyCallback(Handler in_ui_handler) { - set_ui_handler(in_ui_handler); - } - - public void set_ui_handler(Handler in_ui_handler) { - ui_handler = new WeakReference(in_ui_handler); - } - - @Override - public void onStarted(String msg) { - Handler ui = ui_handler.get(); - LOG.INFO(ui, msg); - } - - @Override - public void onStopped(int restart) { - Handler ui = ui_handler.get(); - /** Use timer to stopped/restart **/ - if (restart != 0) { - LOG.INFO(ui, "Telnet Restarting"); - Message msg = Message.obtain(ui, - CONST.MSG_TYPE.CLI_RESTART.ordinal()); - ui.sendMessageDelayed(msg, 100); - } else { - LOG.INFO(ui, "Telnet Stopping"); - Message msg = Message.obtain(ui, - CONST.MSG_TYPE.CLI_STOP.ordinal()); - ui.sendMessageDelayed(msg, 100); - } - } + private WeakReference ui_handler; + + public MyCallback(Handler in_ui_handler) { + set_ui_handler(in_ui_handler); + } + + public void set_ui_handler(Handler in_ui_handler) { + ui_handler = new WeakReference(in_ui_handler); + } + + @Override + public void onStarted(String msg) { + Handler ui = ui_handler.get(); + LOG.INFO(ui, msg); + } + + @Override + public void onStopped(int restart) { + Handler ui = ui_handler.get(); + /** Use timer to stopped/restart **/ + if (restart != 0) { + LOG.INFO(ui, "Telnet Restarting"); + Message msg = Message.obtain(ui, + CONST.MSG_TYPE.CLI_RESTART.ordinal()); + ui.sendMessageDelayed(msg, 100); + } else { + LOG.INFO(ui, "Telnet Stopping"); + Message msg = Message.obtain(ui, + CONST.MSG_TYPE.CLI_STOP.ordinal()); + ui.sendMessageDelayed(msg, 100); + } + } @Override public void onCallVideoStart() { @@ -155,124 +155,124 @@ public void onCallVideoStart() { } private void updateStatus(String output) { - TextView tStatus = (TextView) findViewById(R.id.textStatus); - tStatus.setText(output); + TextView tStatus = (TextView) findViewById(R.id.textStatus); + tStatus.setText(output); } @Override protected void onCreate(Bundle savedInstanceState) { - LOG.DEBUG(ui_handler, "=== Activity::onCreate() ==="); - super.onCreate(savedInstanceState); - CameraManager cm = (CameraManager)getSystemService(Context.CAMERA_SERVICE); - PjCameraInfo2.SetCameraManager(cm); + LOG.DEBUG(ui_handler, "=== Activity::onCreate() ==="); + super.onCreate(savedInstanceState); + CameraManager cm = (CameraManager)getSystemService(Context.CAMERA_SERVICE); + PjCameraInfo2.SetCameraManager(cm); - init_view(); + init_view(); - init_lib(); + init_lib(); } @Override protected void onStart() { - LOG.DEBUG(ui_handler, "=== Activity::onStart() ==="); - super.onStart(); + LOG.DEBUG(ui_handler, "=== Activity::onStart() ==="); + super.onStart(); } @Override protected void onRestart() { - LOG.DEBUG(ui_handler, "=== Activity::onRestart() ==="); - super.onRestart(); + LOG.DEBUG(ui_handler, "=== Activity::onRestart() ==="); + super.onRestart(); } @Override protected void onResume() { - LOG.DEBUG(ui_handler, "=== Activity::onResume() ==="); - super.onResume(); + LOG.DEBUG(ui_handler, "=== Activity::onResume() ==="); + super.onResume(); } @Override protected void onPause() { - LOG.DEBUG(ui_handler, "=== Activity::onPause() ==="); - super.onPause(); + LOG.DEBUG(ui_handler, "=== Activity::onPause() ==="); + super.onPause(); } @Override protected void onStop() { - LOG.DEBUG(ui_handler, "=== Activity::onStop() ==="); - super.onStop(); + LOG.DEBUG(ui_handler, "=== Activity::onStop() ==="); + super.onStop(); } @Override protected void onDestroy() { - LOG.DEBUG(ui_handler, "=== Activity::onDestroy() ==="); - super.onDestroy(); + LOG.DEBUG(ui_handler, "=== Activity::onDestroy() ==="); + super.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); + super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { - super.onRestoreInstanceState(savedInstanceState); + super.onRestoreInstanceState(savedInstanceState); } private void init_view() { - setContentView(R.layout.activity_main); + setContentView(R.layout.activity_main); } private int init_lib() { - LOG.INFO(ui_handler, "Loading module..."); - - // Try loading video dependency libs - try { - System.loadLibrary("openh264"); - System.loadLibrary("yuv"); - } catch (UnsatisfiedLinkError e) { - LOG.ERROR(ui_handler, "UnsatisfiedLinkError: " + e.getMessage()); - LOG.ERROR(ui_handler, "This could be safely ignored if you "+ - "don't need video."); - } - - // Load pjsua - try { - System.loadLibrary(CONST.LIB_FILENAME); - } catch (UnsatisfiedLinkError e) { - LOG.ERROR(ui_handler, "UnsatisfiedLinkError: " + e.getMessage()); - return -1; - } - - // Wait for GDB to init, for native debugging only - if (false && (getApplicationInfo().flags & - ApplicationInfo.FLAG_DEBUGGABLE) != 0) - { - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - LOG.ERROR(ui_handler, "InterruptedException: " + - e.getMessage()); - } - } - - // Set callback object - if (callback == null) - callback = new MyCallback(ui_handler); - - pjsua.setCallbackObject(callback); - - SurfaceView surfaceView = (SurfaceView) - findViewById(R.id.surfaceViewIncomingCall); - surfaceView.getHolder().addCallback(this); - - LOG.INFO(ui_handler, "Starting module.."); - - int rc = pjsua.pjsuaStart(); - - if (rc != 0) { - LOG.INFO(ui_handler, "Failed starting telnet"); - } - - return 0; + LOG.INFO(ui_handler, "Loading module..."); + + // Try loading video dependency libs + try { + System.loadLibrary("openh264"); + System.loadLibrary("yuv"); + } catch (UnsatisfiedLinkError e) { + LOG.ERROR(ui_handler, "UnsatisfiedLinkError: " + e.getMessage()); + LOG.ERROR(ui_handler, "This could be safely ignored if you "+ + "don't need video."); + } + + // Load pjsua + try { + System.loadLibrary(CONST.LIB_FILENAME); + } catch (UnsatisfiedLinkError e) { + LOG.ERROR(ui_handler, "UnsatisfiedLinkError: " + e.getMessage()); + return -1; + } + + // Wait for GDB to init, for native debugging only + if (false && (getApplicationInfo().flags & + ApplicationInfo.FLAG_DEBUGGABLE) != 0) + { + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + LOG.ERROR(ui_handler, "InterruptedException: " + + e.getMessage()); + } + } + + // Set callback object + if (callback == null) + callback = new MyCallback(ui_handler); + + pjsua.setCallbackObject(callback); + + SurfaceView surfaceView = (SurfaceView) + findViewById(R.id.surfaceViewIncomingCall); + surfaceView.getHolder().addCallback(this); + + LOG.INFO(ui_handler, "Starting module.."); + + int rc = pjsua.pjsuaStart(); + + if (rc != 0) { + LOG.INFO(ui_handler, "Failed starting telnet"); + } + + return 0; } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) diff --git a/pjsip-apps/src/pjsua/android/jni/pjsua_app_callback.cpp b/pjsip-apps/src/pjsua/android/jni/pjsua_app_callback.cpp index b8b9ca6460..05b7408de7 100644 --- a/pjsip-apps/src/pjsua/android/jni/pjsua_app_callback.cpp +++ b/pjsip-apps/src/pjsua/android/jni/pjsua_app_callback.cpp @@ -38,12 +38,12 @@ void setVideoWindow(const WindowHandle& win) vhwnd.info.window = win.window; if (winId != PJSUA_INVALID_ID) - pjsua_vid_win_set_win(winId, &vhwnd); + pjsua_vid_win_set_win(winId, &vhwnd); } extern const char *pjsua_app_def_argv[]; -#define THIS_FILE "pjsua_app_callback.cpp" +#define THIS_FILE "pjsua_app_callback.cpp" extern "C" { static void log_writer(int level, const char *data, int len) @@ -62,20 +62,20 @@ static void on_call_media_state(pjsua_call_id call_id) for (mi=0; mitype == PJMEDIA_TYPE_VIDEO && - med_info->status == PJSUA_CALL_MEDIA_ACTIVE && - med_info->stream.vid.win_in != PJSUA_INVALID_ID) - { - winId = med_info->stream.vid.win_in; - registeredCallbackObject->onCallVideoStart(); - break; - } + if (med_info->type == PJMEDIA_TYPE_VIDEO && + med_info->status == PJSUA_CALL_MEDIA_ACTIVE && + med_info->stream.vid.win_in != PJSUA_INVALID_ID) + { + winId = med_info->stream.vid.win_in; + registeredCallbackObject->onCallVideoStart(); + break; + } } #endif /* Forward to original callback */ if (pjsua_cb_orig.on_call_media_state) - (*pjsua_cb_orig.on_call_media_state)(call_id); + (*pjsua_cb_orig.on_call_media_state)(call_id); } /** Callback wrapper **/ @@ -92,23 +92,23 @@ static void on_cli_started(pj_status_t status, const char *msg) { char errmsg[PJ_ERR_MSG_SIZE]; if (registeredCallbackObject) { - if ((status != PJ_SUCCESS) && (!msg || !*msg)) { - pj_strerror(status, errmsg, sizeof(errmsg)); - msg = errmsg; - } - registeredCallbackObject->onStarted(msg); + if ((status != PJ_SUCCESS) && (!msg || !*msg)) { + pj_strerror(status, errmsg, sizeof(errmsg)); + msg = errmsg; + } + registeredCallbackObject->onStarted(msg); } } static void on_cli_stopped(pj_bool_t restart, int argc, char **argv) { if (restart) { - restart_argc = argc; - restart_argv = argv; + restart_argc = argc; + restart_argv = argv; } if (registeredCallbackObject) { - registeredCallbackObject->onStopped(restart); + registeredCallbackObject->onStopped(restart); } } @@ -120,9 +120,9 @@ static int initMain(int argc, char **argv) status = pjsua_app_init(&android_app_config); if (status == PJ_SUCCESS) { - status = pjsua_app_run(PJ_FALSE); + status = pjsua_app_run(PJ_FALSE); } else { - pjsua_app_destroy(); + pjsua_app_destroy(); } return status; diff --git a/pjsip-apps/src/pjsua/android/jni/pjsua_app_callback.h b/pjsip-apps/src/pjsua/android/jni/pjsua_app_callback.h index b90ef60d24..e5727848bb 100644 --- a/pjsip-apps/src/pjsua/android/jni/pjsua_app_callback.h +++ b/pjsip-apps/src/pjsua/android/jni/pjsua_app_callback.h @@ -28,7 +28,7 @@ class PjsuaAppCallback { }; typedef struct WindowHandle { - void *window; + void *window; } WindowHandle; void setVideoWindow(const WindowHandle& win); diff --git a/pjsip-apps/src/pjsua/bb10/src/applicationui.cpp b/pjsip-apps/src/pjsua/bb10/src/applicationui.cpp index 73c0d3c4e2..bcbf46f2f8 100644 --- a/pjsip-apps/src/pjsua/bb10/src/applicationui.cpp +++ b/pjsip-apps/src/pjsua/bb10/src/applicationui.cpp @@ -6,7 +6,7 @@ #include #include -#define THIS_FILE "applicationui.cpp" +#define THIS_FILE "applicationui.cpp" using namespace bb::cascades; @@ -19,8 +19,8 @@ void ApplicationUI::extDisplayMsg(const char *msg) { /* Qt's way to invoke method from "foreign" thread */ QMetaObject::invokeMethod((QObject*)ApplicationUI::instance(), - "displayMsg", Qt::AutoConnection, - Q_ARG(QString,msg)); + "displayMsg", Qt::AutoConnection, + Q_ARG(QString,msg)); } @@ -29,11 +29,11 @@ void ApplicationUI::pjsuaOnStartedCb(pj_status_t status, const char* msg) char errmsg[PJ_ERR_MSG_SIZE]; if (status != PJ_SUCCESS && (!msg || !*msg)) { - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(3,(THIS_FILE, "Error: %s", errmsg)); - msg = errmsg; + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(3,(THIS_FILE, "Error: %s", errmsg)); + msg = errmsg; } else { - PJ_LOG(3,(THIS_FILE, "Started: %s", msg)); + PJ_LOG(3,(THIS_FILE, "Started: %s", msg)); } ApplicationUI::extDisplayMsg(msg); @@ -41,20 +41,20 @@ void ApplicationUI::pjsuaOnStartedCb(pj_status_t status, const char* msg) void ApplicationUI::pjsuaOnStoppedCb(pj_bool_t restart, - int argc, char** argv) + int argc, char** argv) { PJ_LOG(3,("ipjsua", "CLI %s request", (restart? "restart" : "shutdown"))); if (restart) { - ApplicationUI::extDisplayMsg("Restarting.."); - pj_thread_sleep(100); - ApplicationUI::instance()->extRestartRequest(argc, argv); + ApplicationUI::extDisplayMsg("Restarting.."); + pj_thread_sleep(100); + ApplicationUI::instance()->extRestartRequest(argc, argv); } else { - ApplicationUI::extDisplayMsg("Shutting down.."); - pj_thread_sleep(100); - ApplicationUI::instance()->isShuttingDown = true; + ApplicationUI::extDisplayMsg("Shutting down.."); + pj_thread_sleep(100); + ApplicationUI::instance()->isShuttingDown = true; - bb::cascades::Application *app = bb::cascades::Application::instance(); - app->quit(); + bb::cascades::Application *app = bb::cascades::Application::instance(); + app->quit(); } } @@ -70,7 +70,7 @@ void ApplicationUI::extRestartRequest(int argc, char **argv) restartArgc = argc; restartArgv = argv; QMetaObject::invokeMethod((QObject*)this, "restartPjsua", - Qt::QueuedConnection); + Qt::QueuedConnection); } @@ -87,11 +87,11 @@ void ApplicationUI::pjsuaStart() pj_bzero(&app_cfg, sizeof(app_cfg)); if (restartArgc) { - app_cfg.argc = restartArgc; - app_cfg.argv = restartArgv; + app_cfg.argc = restartArgc; + app_cfg.argv = restartArgv; } else { - app_cfg.argc = argc; - app_cfg.argv = (char**)argv; + app_cfg.argc = argc; + app_cfg.argv = (char**)argv; } app_cfg.on_started = &pjsuaOnStartedCb; app_cfg.on_stopped = &pjsuaOnStoppedCb; @@ -99,19 +99,19 @@ void ApplicationUI::pjsuaStart() status = pjsua_app_init(&app_cfg); if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - displayMsg(QString("Init error:") + errmsg); - pjsua_app_destroy(); - return; + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + displayMsg(QString("Init error:") + errmsg); + pjsua_app_destroy(); + return; } status = pjsua_app_run(PJ_FALSE); if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - displayMsg(QString("Error:") + errmsg); - pjsua_app_destroy(); + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + displayMsg(QString("Error:") + errmsg); + pjsua_app_destroy(); } restartArgv = NULL; @@ -155,9 +155,9 @@ ApplicationUI* ApplicationUI::instance() void ApplicationUI::aboutToQuit() { if (!isShuttingDown) { - isShuttingDown = true; - PJ_LOG(3,(THIS_FILE, "Quit signal from GUI, shutting down pjsua..")); - pjsuaDestroy(); + isShuttingDown = true; + PJ_LOG(3,(THIS_FILE, "Quit signal from GUI, shutting down pjsua..")); + pjsuaDestroy(); } } @@ -167,7 +167,7 @@ void ApplicationUI::displayMsg(const QString &msg) bb::cascades::Application *app = bb::cascades::Application::instance(); Label *telnetMsg = app->scene()->findChild("telnetMsg"); if (telnetMsg) { - telnetMsg->setText(msg); + telnetMsg->setText(msg); } } diff --git a/pjsip-apps/src/pjsua/gui.h b/pjsip-apps/src/pjsua/gui.h index 21ab7481e2..7b49a481bb 100644 --- a/pjsip-apps/src/pjsua/gui.h +++ b/pjsip-apps/src/pjsua/gui.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -36,4 +35,4 @@ pj_bool_t showNotification(pjsua_call_id call_id); PJ_END_DECL -#endif /* __GUI_H__ */ +#endif /* __GUI_H__ */ diff --git a/pjsip-apps/src/pjsua/ios/ipjsua/Reachability.h b/pjsip-apps/src/pjsua/ios/ipjsua/Reachability.h index 50c048c137..a495066436 100644 --- a/pjsip-apps/src/pjsua/ios/ipjsua/Reachability.h +++ b/pjsip-apps/src/pjsua/ios/ipjsua/Reachability.h @@ -12,9 +12,9 @@ typedef enum : NSInteger { - NotReachable = 0, - ReachableViaWiFi, - ReachableViaWWAN + NotReachable = 0, + ReachableViaWiFi, + ReachableViaWWAN } NetworkStatus; #pragma mark IPv6 Support diff --git a/pjsip-apps/src/pjsua/ios/ipjsua/Reachability.m b/pjsip-apps/src/pjsua/ios/ipjsua/Reachability.m index f081a16aa4..e16ca88b6f 100644 --- a/pjsip-apps/src/pjsua/ios/ipjsua/Reachability.m +++ b/pjsip-apps/src/pjsua/ios/ipjsua/Reachability.m @@ -32,7 +32,7 @@ static void PrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* #if kShouldPrintReachabilityFlags NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n", - (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-', + (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-', (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-', (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-', @@ -51,8 +51,8 @@ static void PrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info) { #pragma unused (target, flags) - NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback"); - NSCAssert([(__bridge NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback"); + NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback"); + NSCAssert([(__bridge NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback"); Reachability* noteObject = (__bridge Reachability *)info; // Post a notification to notify the client that the network reachability changed. @@ -64,55 +64,55 @@ static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReach @implementation Reachability { - SCNetworkReachabilityRef _reachabilityRef; + SCNetworkReachabilityRef _reachabilityRef; } + (instancetype)reachabilityWithHostName:(NSString *)hostName { - Reachability* returnValue = NULL; - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]); - if (reachability != NULL) - { - returnValue= [[self alloc] init]; - if (returnValue != NULL) - { - returnValue->_reachabilityRef = reachability; - } + Reachability* returnValue = NULL; + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]); + if (reachability != NULL) + { + returnValue= [[self alloc] init]; + if (returnValue != NULL) + { + returnValue->_reachabilityRef = reachability; + } else { CFRelease(reachability); } - } - return returnValue; + } + return returnValue; } + (instancetype)reachabilityWithAddress:(const struct sockaddr *)hostAddress { - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, hostAddress); + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, hostAddress); - Reachability* returnValue = NULL; + Reachability* returnValue = NULL; - if (reachability != NULL) - { - returnValue = [[self alloc] init]; - if (returnValue != NULL) - { - returnValue->_reachabilityRef = reachability; - } + if (reachability != NULL) + { + returnValue = [[self alloc] init]; + if (returnValue != NULL) + { + returnValue->_reachabilityRef = reachability; + } else { CFRelease(reachability); } - } - return returnValue; + } + return returnValue; } + (instancetype)reachabilityForInternetConnection { - struct sockaddr_in zeroAddress; - bzero(&zeroAddress, sizeof(zeroAddress)); - zeroAddress.sin_len = sizeof(zeroAddress); - zeroAddress.sin_family = AF_INET; + struct sockaddr_in zeroAddress; + bzero(&zeroAddress, sizeof(zeroAddress)); + zeroAddress.sin_len = sizeof(zeroAddress); + zeroAddress.sin_family = AF_INET; return [self reachabilityWithAddress: (const struct sockaddr *) &zeroAddress]; } @@ -127,37 +127,37 @@ + (instancetype)reachabilityForInternetConnection - (BOOL)startNotifier { - BOOL returnValue = NO; - SCNetworkReachabilityContext context = {0, (__bridge void *)(self), NULL, NULL, NULL}; - - if (SCNetworkReachabilitySetCallback(_reachabilityRef, ReachabilityCallback, &context)) - { - if (SCNetworkReachabilityScheduleWithRunLoop(_reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) - { - returnValue = YES; - } - } + BOOL returnValue = NO; + SCNetworkReachabilityContext context = {0, (__bridge void *)(self), NULL, NULL, NULL}; + + if (SCNetworkReachabilitySetCallback(_reachabilityRef, ReachabilityCallback, &context)) + { + if (SCNetworkReachabilityScheduleWithRunLoop(_reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) + { + returnValue = YES; + } + } - return returnValue; + return returnValue; } - (void)stopNotifier { - if (_reachabilityRef != NULL) - { - SCNetworkReachabilityUnscheduleFromRunLoop(_reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); - } + if (_reachabilityRef != NULL) + { + SCNetworkReachabilityUnscheduleFromRunLoop(_reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); + } } - (void)dealloc { - [self stopNotifier]; - if (_reachabilityRef != NULL) - { - CFRelease(_reachabilityRef); - } + [self stopNotifier]; + if (_reachabilityRef != NULL) + { + CFRelease(_reachabilityRef); + } } @@ -165,26 +165,26 @@ - (void)dealloc - (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags { - PrintReachabilityFlags(flags, "networkStatusForFlags"); - if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) - { - // The target host is not reachable. - return NotReachable; - } + PrintReachabilityFlags(flags, "networkStatusForFlags"); + if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) + { + // The target host is not reachable. + return NotReachable; + } NetworkStatus returnValue = NotReachable; - if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) - { - /* + if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) + { + /* If the target host is reachable and no connection is required then we'll assume (for now) that you're on Wi-Fi... */ - returnValue = ReachableViaWiFi; - } + returnValue = ReachableViaWiFi; + } - if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || + if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)) - { + { /* ... and the connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs... */ @@ -198,27 +198,27 @@ - (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags } } - if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) - { - /* + if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) + { + /* ... but WWAN connections are OK if the calling application is using the CFNetwork APIs. */ - returnValue = ReachableViaWWAN; - } + returnValue = ReachableViaWWAN; + } - return returnValue; + return returnValue; } - (BOOL)connectionRequired { - NSAssert(_reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef"); - SCNetworkReachabilityFlags flags; + NSAssert(_reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef"); + SCNetworkReachabilityFlags flags; - if (SCNetworkReachabilityGetFlags(_reachabilityRef, &flags)) - { - return (flags & kSCNetworkReachabilityFlagsConnectionRequired); - } + if (SCNetworkReachabilityGetFlags(_reachabilityRef, &flags)) + { + return (flags & kSCNetworkReachabilityFlagsConnectionRequired); + } return NO; } @@ -226,16 +226,16 @@ - (BOOL)connectionRequired - (NetworkStatus)currentReachabilityStatus { - NSAssert(_reachabilityRef != NULL, @"currentNetworkStatus called with NULL SCNetworkReachabilityRef"); - NetworkStatus returnValue = NotReachable; - SCNetworkReachabilityFlags flags; + NSAssert(_reachabilityRef != NULL, @"currentNetworkStatus called with NULL SCNetworkReachabilityRef"); + NetworkStatus returnValue = NotReachable; + SCNetworkReachabilityFlags flags; - if (SCNetworkReachabilityGetFlags(_reachabilityRef, &flags)) - { + if (SCNetworkReachabilityGetFlags(_reachabilityRef, &flags)) + { returnValue = [self networkStatusForFlags:flags]; - } + } - return returnValue; + return returnValue; } diff --git a/pjsip-apps/src/pjsua/ios/ipjsua/ipjsuaAppDelegate.m b/pjsip-apps/src/pjsua/ios/ipjsua/ipjsuaAppDelegate.m index c35e51298d..01e801dff4 100644 --- a/pjsip-apps/src/pjsua/ios/ipjsua/ipjsuaAppDelegate.m +++ b/pjsip-apps/src/pjsua/ios/ipjsua/ipjsuaAppDelegate.m @@ -31,7 +31,7 @@ @implementation ipjsuaAppDelegate -#define THIS_FILE "ipjsuaAppDelegate.m" +#define THIS_FILE "ipjsuaAppDelegate.m" #define KEEP_ALIVE_INTERVAL 600 @@ -98,11 +98,11 @@ static void pjsuaOnStartedCb(pj_status_t status, const char* msg) char errmsg[PJ_ERR_MSG_SIZE]; if (status != PJ_SUCCESS && (!msg || !*msg)) { - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(3,(THIS_FILE, "Error: %s", errmsg)); - msg = errmsg; + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(3,(THIS_FILE, "Error: %s", errmsg)); + msg = errmsg; } else { - PJ_LOG(3,(THIS_FILE, "Started: %s", msg)); + PJ_LOG(3,(THIS_FILE, "Started: %s", msg)); } displayMsg(msg); @@ -114,12 +114,12 @@ static void pjsuaOnStoppedCb(pj_bool_t restart, PJ_LOG(3,("ipjsua", "CLI %s request", (restart? "restart" : "shutdown"))); if (restart) { displayMsg("Restarting.."); - pj_thread_sleep(100); + pj_thread_sleep(100); app_cfg.argc = argc; app_cfg.argv = argv; } else { displayMsg("Shutting down.."); - pj_thread_sleep(100); + pj_thread_sleep(100); isShuttingDown = true; } } @@ -141,11 +141,11 @@ - (void)pjsuaStart pj_bzero(&app_cfg, sizeof(app_cfg)); if (restartArgc) { - app_cfg.argc = restartArgc; - app_cfg.argv = restartArgv; + app_cfg.argc = restartArgc; + app_cfg.argv = restartArgv; } else { - app_cfg.argc = argc; - app_cfg.argv = (char**)argv; + app_cfg.argc = argc; + app_cfg.argv = (char**)argv; } app_cfg.on_started = &pjsuaOnStartedCb; app_cfg.on_stopped = &pjsuaOnStoppedCb; @@ -272,7 +272,7 @@ - (void)keepAlive { int i; if (!pj_thread_is_registered()) { - pj_thread_register("ipjsua", a_thread_desc, &a_thread); + pj_thread_register("ipjsua", a_thread_desc, &a_thread); } /* Since iOS requires that the minimum keep alive interval is 600s, @@ -295,7 +295,7 @@ - (void)applicationDidEnterBackground:(UIApplication *)application #if 0 /* setKeepAliveTimeout is deprecated. Use PushKit instead. */ [application setKeepAliveTimeout:KEEP_ALIVE_INTERVAL handler: ^{ - [self performSelectorOnMainThread:@selector(keepAlive) withObject:nil waitUntilDone:YES]; + [self performSelectorOnMainThread:@selector(keepAlive) withObject:nil waitUntilDone:YES]; }]; #endif } @@ -326,14 +326,14 @@ pj_bool_t showNotification(pjsua_call_id call_id) UILocalNotification* alert = [[UILocalNotification alloc] init]; if (alert) { - alert.repeatInterval = 0; - alert.alertBody = @"Incoming call received..."; + alert.repeatInterval = 0; + alert.alertBody = @"Incoming call received..."; /* This action just brings the app to the FG, it doesn't * automatically answer the call (unless you specify the * --auto-answer option). */ - alert.alertAction = @"Activate app"; - + alert.alertAction = @"Activate app"; + dispatch_async(dispatch_get_main_queue(), ^{[[UIApplication sharedApplication] presentLocalNotificationNow:alert];}); @@ -352,7 +352,7 @@ void displayWindow(pjsua_vid_win_id wid) last = (wid == PJSUA_INVALID_ID) ? PJSUA_MAX_VID_WINS : wid+1; for (;i < last; ++i) { - pjsua_vid_win_info wi; + pjsua_vid_win_info wi; if (pjsua_vid_win_get_info(i, &wi) == PJ_SUCCESS) { dispatch_async(dispatch_get_main_queue(), ^{ diff --git a/pjsip-apps/src/pjsua/main.c b/pjsip-apps/src/pjsua/main.c index 0d1442b47c..35b31f3941 100644 --- a/pjsip-apps/src/pjsua/main.c +++ b/pjsip-apps/src/pjsua/main.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -19,12 +18,12 @@ */ #include "pjsua_app.h" -#define THIS_FILE "main.c" +#define THIS_FILE "main.c" -static pj_bool_t running = PJ_TRUE; -static pj_status_t receive_end_sig; -static pj_thread_t *sig_thread; -static pjsua_app_cfg_t cfg; +static pj_bool_t running = PJ_TRUE; +static pj_status_t receive_end_sig; +static pj_thread_t *sig_thread; +static pjsua_app_cfg_t cfg; /* Called when CLI (re)started */ void on_app_started(pj_status_t status, const char *msg) @@ -35,8 +34,8 @@ void on_app_started(pj_status_t status, const char *msg) void on_app_stopped(pj_bool_t restart, int argc, char** argv) { if (argv) { - cfg.argc = argc; - cfg.argv = argv; + cfg.argc = argc; + cfg.argv = argv; } running = restart; @@ -58,11 +57,11 @@ static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType) case CTRL_BREAK_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: - pj_thread_register("ctrlhandler", handler_desc, &sig_thread); - PJ_LOG(3,(THIS_FILE, "Ctrl-C detected, quitting..")); - receive_end_sig = PJ_TRUE; - pjsua_app_destroy(); - ExitProcess(1); + pj_thread_register("ctrlhandler", handler_desc, &sig_thread); + PJ_LOG(3,(THIS_FILE, "Ctrl-C detected, quitting..")); + receive_end_sig = PJ_TRUE; + pjsua_app_destroy(); + ExitProcess(1); PJ_UNREACHED(return TRUE;) default: @@ -136,21 +135,21 @@ int main_func(int argc, char *argv[]) setup_socket_signal(); while (running) { - status = pjsua_app_init(&cfg); - if (status == PJ_SUCCESS) { - status = pjsua_app_run(PJ_TRUE); - } else { - running = PJ_FALSE; - } - - if (!receive_end_sig) { - pjsua_app_destroy(); - - /* This is on purpose */ - pjsua_app_destroy(); - } else { - pj_thread_join(sig_thread); - } + status = pjsua_app_init(&cfg); + if (status == PJ_SUCCESS) { + status = pjsua_app_run(PJ_TRUE); + } else { + running = PJ_FALSE; + } + + if (!receive_end_sig) { + pjsua_app_destroy(); + + /* This is on purpose */ + pjsua_app_destroy(); + } else { + pj_thread_join(sig_thread); + } } return 0; } diff --git a/pjsip-apps/src/pjsua/pjsua_app.c b/pjsip-apps/src/pjsua/pjsua_app.c index 6acee0a1c3..1d42e3eb6d 100644 --- a/pjsip-apps/src/pjsua/pjsua_app.c +++ b/pjsip-apps/src/pjsua/pjsua_app.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -19,28 +18,28 @@ */ #include "pjsua_app.h" -#define THIS_FILE "pjsua_app.c" +#define THIS_FILE "pjsua_app.c" //#define STEREO_DEMO //#define TRANSPORT_ADAPTER_SAMPLE //#define HAVE_MULTIPART_TEST -/* Ringtones US UK */ -#define RINGBACK_FREQ1 440 /* 400 */ -#define RINGBACK_FREQ2 480 /* 450 */ -#define RINGBACK_ON 2000 /* 400 */ -#define RINGBACK_OFF 4000 /* 200 */ -#define RINGBACK_CNT 1 /* 2 */ +/* Ringtones US UK */ +#define RINGBACK_FREQ1 440 /* 400 */ +#define RINGBACK_FREQ2 480 /* 450 */ +#define RINGBACK_ON 2000 /* 400 */ +#define RINGBACK_OFF 4000 /* 200 */ +#define RINGBACK_CNT 1 /* 2 */ #define RINGBACK_INTERVAL 4000 /* 2000 */ -#define RING_FREQ1 800 -#define RING_FREQ2 640 -#define RING_ON 200 -#define RING_OFF 100 -#define RING_CNT 3 -#define RING_INTERVAL 3000 +#define RING_FREQ1 800 +#define RING_FREQ2 640 +#define RING_ON 200 +#define RING_OFF 100 +#define RING_CNT 3 +#define RING_INTERVAL 3000 -#define current_acc pjsua_acc_get_default() +#define current_acc pjsua_acc_get_default() #ifdef STEREO_DEMO static void stereo_demo(); @@ -57,8 +56,8 @@ static pj_status_t app_init(void); static pj_status_t app_destroy(void); static pjsua_app_cfg_t app_cfg; -pj_str_t uri_arg; -pj_bool_t app_running = PJ_FALSE; +pj_str_t uri_arg; +pj_bool_t app_running = PJ_FALSE; /***************************************************************************** * Configuration manipulation @@ -70,64 +69,64 @@ pj_bool_t app_running = PJ_FALSE; static void ringback_start(pjsua_call_id call_id) { if (app_config.no_tones) - return; + return; if (app_config.call_data[call_id].ringback_on) - return; + return; app_config.call_data[call_id].ringback_on = PJ_TRUE; if (++app_config.ringback_cnt==1 && - app_config.ringback_slot!=PJSUA_INVALID_ID) + app_config.ringback_slot!=PJSUA_INVALID_ID) { - pjsua_conf_connect(app_config.ringback_slot, 0); + pjsua_conf_connect(app_config.ringback_slot, 0); } } static void ring_stop(pjsua_call_id call_id) { if (app_config.no_tones) - return; + return; if (app_config.call_data[call_id].ringback_on) { - app_config.call_data[call_id].ringback_on = PJ_FALSE; + app_config.call_data[call_id].ringback_on = PJ_FALSE; - pj_assert(app_config.ringback_cnt>0); - if (--app_config.ringback_cnt == 0 && - app_config.ringback_slot!=PJSUA_INVALID_ID) - { - pjsua_conf_disconnect(app_config.ringback_slot, 0); - pjmedia_tonegen_rewind(app_config.ringback_port); - } + pj_assert(app_config.ringback_cnt>0); + if (--app_config.ringback_cnt == 0 && + app_config.ringback_slot!=PJSUA_INVALID_ID) + { + pjsua_conf_disconnect(app_config.ringback_slot, 0); + pjmedia_tonegen_rewind(app_config.ringback_port); + } } if (app_config.call_data[call_id].ring_on) { - app_config.call_data[call_id].ring_on = PJ_FALSE; + app_config.call_data[call_id].ring_on = PJ_FALSE; - pj_assert(app_config.ring_cnt>0); - if (--app_config.ring_cnt == 0 && - app_config.ring_slot!=PJSUA_INVALID_ID) - { - pjsua_conf_disconnect(app_config.ring_slot, 0); - pjmedia_tonegen_rewind(app_config.ring_port); - } + pj_assert(app_config.ring_cnt>0); + if (--app_config.ring_cnt == 0 && + app_config.ring_slot!=PJSUA_INVALID_ID) + { + pjsua_conf_disconnect(app_config.ring_slot, 0); + pjmedia_tonegen_rewind(app_config.ring_port); + } } } static void ring_start(pjsua_call_id call_id) { if (app_config.no_tones) - return; + return; if (app_config.call_data[call_id].ring_on) - return; + return; app_config.call_data[call_id].ring_on = PJ_TRUE; if (++app_config.ring_cnt==1 && - app_config.ring_slot!=PJSUA_INVALID_ID) + app_config.ring_slot!=PJSUA_INVALID_ID) { - pjsua_conf_connect(app_config.ring_slot, 0); + pjsua_conf_connect(app_config.ring_slot, 0); } } @@ -135,7 +134,7 @@ static void ring_start(pjsua_call_id call_id) * exceeded. */ static void call_timeout_callback(pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { pjsua_call_id call_id = entry->id; pjsua_msg_data msg_data_; @@ -146,8 +145,8 @@ static void call_timeout_callback(pj_timer_heap_t *timer_heap, PJ_UNUSED_ARG(timer_heap); if (call_id == PJSUA_INVALID_ID) { - PJ_LOG(1,(THIS_FILE, "Invalid call ID in timer callback")); - return; + PJ_LOG(1,(THIS_FILE, "Invalid call ID in timer callback")); + return; } /* Add warning header */ @@ -157,8 +156,8 @@ static void call_timeout_callback(pj_timer_heap_t *timer_heap, /* Call duration has been exceeded; disconnect the call */ PJ_LOG(3,(THIS_FILE, "Duration (%d seconds) has been exceeded " - "for call %d, disconnecting the call", - app_config.duration, call_id)); + "for call %d, disconnecting the call", + app_config.duration, call_id)); entry->id = PJSUA_INVALID_ID; pjsua_call_hangup(call_id, 200, NULL, &msg_data_); } @@ -176,99 +175,99 @@ static void on_call_state(pjsua_call_id call_id, pjsip_event *e) if (call_info.state == PJSIP_INV_STATE_DISCONNECTED) { - /* Stop all ringback for this call */ - ring_stop(call_id); - - /* Cancel duration timer, if any */ - if (app_config.call_data[call_id].timer.id != PJSUA_INVALID_ID) { - app_call_data *cd = &app_config.call_data[call_id]; - pjsip_endpoint *endpt = pjsua_get_pjsip_endpt(); - - cd->timer.id = PJSUA_INVALID_ID; - pjsip_endpt_cancel_timer(endpt, &cd->timer); - } - - /* Rewind play file when hangup automatically, - * since file is not looped - */ - if (app_config.auto_play_hangup) - pjsua_player_set_pos(app_config.wav_id, 0); - - - PJ_LOG(3,(THIS_FILE, "Call %d is DISCONNECTED [reason=%d (%.*s)]", - call_id, - call_info.last_status, - (int)call_info.last_status_text.slen, - call_info.last_status_text.ptr)); - - if (call_id == current_call) { - find_next_call(); - } - - /* Dump media state upon disconnected. - * Now pjsua_media_channel_deinit() automatically log the call dump. - */ - if (0) { - PJ_LOG(5,(THIS_FILE, - "Call %d disconnected, dumping media stats..", - call_id)); - log_call_dump(call_id); - } + /* Stop all ringback for this call */ + ring_stop(call_id); + + /* Cancel duration timer, if any */ + if (app_config.call_data[call_id].timer.id != PJSUA_INVALID_ID) { + app_call_data *cd = &app_config.call_data[call_id]; + pjsip_endpoint *endpt = pjsua_get_pjsip_endpt(); + + cd->timer.id = PJSUA_INVALID_ID; + pjsip_endpt_cancel_timer(endpt, &cd->timer); + } + + /* Rewind play file when hangup automatically, + * since file is not looped + */ + if (app_config.auto_play_hangup) + pjsua_player_set_pos(app_config.wav_id, 0); + + + PJ_LOG(3,(THIS_FILE, "Call %d is DISCONNECTED [reason=%d (%.*s)]", + call_id, + call_info.last_status, + (int)call_info.last_status_text.slen, + call_info.last_status_text.ptr)); + + if (call_id == current_call) { + find_next_call(); + } + + /* Dump media state upon disconnected. + * Now pjsua_media_channel_deinit() automatically log the call dump. + */ + if (0) { + PJ_LOG(5,(THIS_FILE, + "Call %d disconnected, dumping media stats..", + call_id)); + log_call_dump(call_id); + } } else { - if (app_config.duration != PJSUA_APP_NO_LIMIT_DURATION && - call_info.state == PJSIP_INV_STATE_CONFIRMED) - { - /* Schedule timer to hangup call after the specified duration */ - app_call_data *cd = &app_config.call_data[call_id]; - pjsip_endpoint *endpt = pjsua_get_pjsip_endpt(); - pj_time_val delay; - - cd->timer.id = call_id; - delay.sec = app_config.duration; - delay.msec = 0; - pjsip_endpt_schedule_timer(endpt, &cd->timer, &delay); - } - - if (call_info.state == PJSIP_INV_STATE_EARLY) { - int code; - pj_str_t reason; - pjsip_msg *msg; - - /* This can only occur because of TX or RX message */ - pj_assert(e->type == PJSIP_EVENT_TSX_STATE); - - if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - msg = e->body.tsx_state.src.rdata->msg_info.msg; - } else { - msg = e->body.tsx_state.src.tdata->msg; - } - - code = msg->line.status.code; - reason = msg->line.status.reason; - - /* Start ringback for 180 for UAC unless there's SDP in 180 */ - if (call_info.role==PJSIP_ROLE_UAC && code==180 && - msg->body == NULL && - call_info.media_status==PJSUA_CALL_MEDIA_NONE) - { - ringback_start(call_id); - } - - PJ_LOG(3,(THIS_FILE, "Call %d state changed to %.*s (%d %.*s)", - call_id, (int)call_info.state_text.slen, + if (app_config.duration != PJSUA_APP_NO_LIMIT_DURATION && + call_info.state == PJSIP_INV_STATE_CONFIRMED) + { + /* Schedule timer to hangup call after the specified duration */ + app_call_data *cd = &app_config.call_data[call_id]; + pjsip_endpoint *endpt = pjsua_get_pjsip_endpt(); + pj_time_val delay; + + cd->timer.id = call_id; + delay.sec = app_config.duration; + delay.msec = 0; + pjsip_endpt_schedule_timer(endpt, &cd->timer, &delay); + } + + if (call_info.state == PJSIP_INV_STATE_EARLY) { + int code; + pj_str_t reason; + pjsip_msg *msg; + + /* This can only occur because of TX or RX message */ + pj_assert(e->type == PJSIP_EVENT_TSX_STATE); + + if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { + msg = e->body.tsx_state.src.rdata->msg_info.msg; + } else { + msg = e->body.tsx_state.src.tdata->msg; + } + + code = msg->line.status.code; + reason = msg->line.status.reason; + + /* Start ringback for 180 for UAC unless there's SDP in 180 */ + if (call_info.role==PJSIP_ROLE_UAC && code==180 && + msg->body == NULL && + call_info.media_status==PJSUA_CALL_MEDIA_NONE) + { + ringback_start(call_id); + } + + PJ_LOG(3,(THIS_FILE, "Call %d state changed to %.*s (%d %.*s)", + call_id, (int)call_info.state_text.slen, call_info.state_text.ptr, code, (int)reason.slen, reason.ptr)); - } else { - PJ_LOG(3,(THIS_FILE, "Call %d state changed to %.*s", - call_id, - (int)call_info.state_text.slen, - call_info.state_text.ptr)); - } + } else { + PJ_LOG(3,(THIS_FILE, "Call %d state changed to %.*s", + call_id, + (int)call_info.state_text.slen, + call_info.state_text.ptr)); + } - if (current_call==PJSUA_INVALID_ID) - current_call = call_id; + if (current_call==PJSUA_INVALID_ID) + current_call = call_id; } } @@ -278,16 +277,16 @@ static void on_call_state(pjsua_call_id call_id, pjsip_event *e) */ static void on_stream_destroyed(pjsua_call_id call_id, pjmedia_stream *strm, - unsigned stream_idx) + unsigned stream_idx) { PJ_UNUSED_ARG(strm); /* Now pjsua_media_channel_deinit() automatically log the call dump. */ if (0) { - PJ_LOG(5,(THIS_FILE, - "Call %d stream %d destroyed, dumping media stats..", - call_id, stream_idx)); - log_call_dump(call_id); + PJ_LOG(5,(THIS_FILE, + "Call %d stream %d destroyed, dumping media stats..", + call_id, stream_idx)); + log_call_dump(call_id); } } @@ -295,7 +294,7 @@ static void on_stream_destroyed(pjsua_call_id call_id, * Handler when there is incoming call. */ static void on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, - pjsip_rx_data *rdata) + pjsip_rx_data *rdata) { pjsua_call_info call_info; @@ -305,7 +304,7 @@ static void on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, pjsua_call_get_info(call_id, &call_info); if (current_call==PJSUA_INVALID_ID) - current_call = call_id; + current_call = call_id; #ifdef USE_GUI showNotification(call_id); @@ -313,49 +312,49 @@ static void on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, /* Start ringback */ if (call_info.rem_aud_cnt) - ring_start(call_id); + ring_start(call_id); if (app_config.auto_answer > 0) { - pjsua_call_setting opt; + pjsua_call_setting opt; - pjsua_call_setting_default(&opt); - opt.aud_cnt = app_config.aud_cnt; - opt.vid_cnt = app_config.vid.vid_cnt; + pjsua_call_setting_default(&opt); + opt.aud_cnt = app_config.aud_cnt; + opt.vid_cnt = app_config.vid.vid_cnt; - pjsua_call_answer2(call_id, &opt, app_config.auto_answer, NULL, - NULL); + pjsua_call_answer2(call_id, &opt, app_config.auto_answer, NULL, + NULL); } if (app_config.auto_answer < 200) { - char notif_st[80] = {0}; + char notif_st[80] = {0}; #if PJSUA_HAS_VIDEO - if (call_info.rem_offerer && call_info.rem_vid_cnt) { - snprintf(notif_st, sizeof(notif_st), - "To %s the video, type \"vid %s\" first, " - "before answering the call!\n", - (app_config.vid.vid_cnt? "reject":"accept"), - (app_config.vid.vid_cnt? "disable":"enable")); - } + if (call_info.rem_offerer && call_info.rem_vid_cnt) { + snprintf(notif_st, sizeof(notif_st), + "To %s the video, type \"vid %s\" first, " + "before answering the call!\n", + (app_config.vid.vid_cnt? "reject":"accept"), + (app_config.vid.vid_cnt? "disable":"enable")); + } #endif - PJ_LOG(3,(THIS_FILE, - "Incoming call for account %d!\n" - "Media count: %d audio & %d video\n" - "%s" - "From: %.*s\n" - "To: %.*s\n" - "Press %s to answer or %s to reject call", - acc_id, - call_info.rem_aud_cnt, - call_info.rem_vid_cnt, - notif_st, - (int)call_info.remote_info.slen, - call_info.remote_info.ptr, - (int)call_info.local_info.slen, - call_info.local_info.ptr, - (app_config.use_cli?"ca a":"a"), - (app_config.use_cli?"g":"h"))); + PJ_LOG(3,(THIS_FILE, + "Incoming call for account %d!\n" + "Media count: %d audio & %d video\n" + "%s" + "From: %.*s\n" + "To: %.*s\n" + "Press %s to answer or %s to reject call", + acc_id, + call_info.rem_aud_cnt, + call_info.rem_vid_cnt, + notif_st, + (int)call_info.remote_info.slen, + call_info.remote_info.ptr, + (int)call_info.local_info.slen, + call_info.local_info.ptr, + (app_config.use_cli?"ca a":"a"), + (app_config.use_cli?"g":"h"))); } } @@ -377,8 +376,8 @@ static void on_call_generic_media_state(pjsua_call_info *ci, unsigned mi, pj_assert(PJSUA_CALL_MEDIA_ERROR == 4); PJ_LOG(4,(THIS_FILE, "Call %d media %d [type=%s], status is %s", - ci->id, mi, pjmedia_type_name(ci->media[mi].type), - status_name[ci->media[mi].status])); + ci->id, mi, pjmedia_type_name(ci->media[mi].type), + status_name[ci->media[mi].status])); } /* Process audio media state. "mi" is the media index. */ @@ -394,97 +393,97 @@ static void on_call_audio_state(pjsua_call_info *ci, unsigned mi, * otherwise we should NOT connect the ports. */ if (ci->media[mi].status == PJSUA_CALL_MEDIA_ACTIVE || - ci->media[mi].status == PJSUA_CALL_MEDIA_REMOTE_HOLD) + ci->media[mi].status == PJSUA_CALL_MEDIA_REMOTE_HOLD) { - pj_bool_t connect_sound = PJ_TRUE; - pj_bool_t disconnect_mic = PJ_FALSE; - pjsua_conf_port_id call_conf_slot; - - call_conf_slot = ci->media[mi].stream.aud.conf_slot; - - /* Make sure conf slot is valid (e.g: media dir is not "inactive") */ - if (call_conf_slot == PJSUA_INVALID_ID) - return; - - /* Loopback sound, if desired */ - if (app_config.auto_loop) { - pjsua_conf_connect(call_conf_slot, call_conf_slot); - connect_sound = PJ_FALSE; - } - - /* Automatically record conversation, if desired */ - if (app_config.auto_rec && app_config.rec_port != PJSUA_INVALID_ID) { - pjsua_conf_connect(call_conf_slot, app_config.rec_port); - } - - /* Stream a file, if desired */ - if ((app_config.auto_play || app_config.auto_play_hangup) && - app_config.wav_port != PJSUA_INVALID_ID) - { - pjsua_conf_connect(app_config.wav_port, call_conf_slot); - connect_sound = PJ_FALSE; - } - - /* Stream AVI, if desired */ - if (app_config.avi_auto_play && - app_config.avi_def_idx != PJSUA_INVALID_ID && - app_config.avi[app_config.avi_def_idx].slot != PJSUA_INVALID_ID) - { - pjsua_conf_connect(app_config.avi[app_config.avi_def_idx].slot, - call_conf_slot); - disconnect_mic = PJ_TRUE; - } - - /* Put call in conference with other calls, if desired */ - if (app_config.auto_conf) { - pjsua_call_id call_ids[PJSUA_MAX_CALLS]; - unsigned call_cnt=PJ_ARRAY_SIZE(call_ids); - unsigned i; - - /* Get all calls, and establish media connection between - * this call and other calls. - */ - pjsua_enum_calls(call_ids, &call_cnt); - - for (i=0; iid) - continue; - - if (!pjsua_call_has_media(call_ids[i])) - continue; - - pjsua_conf_connect(call_conf_slot, - pjsua_call_get_conf_port(call_ids[i])); - pjsua_conf_connect(pjsua_call_get_conf_port(call_ids[i]), - call_conf_slot); - - /* Automatically record conversation, if desired */ - if (app_config.auto_rec && app_config.rec_port != - PJSUA_INVALID_ID) - { - pjsua_conf_connect(pjsua_call_get_conf_port(call_ids[i]), - app_config.rec_port); - } - - } - - /* Also connect call to local sound device */ - connect_sound = PJ_TRUE; - } - - /* Otherwise connect to sound device */ - if (connect_sound) { - pjsua_conf_connect(call_conf_slot, 0); - if (!disconnect_mic) - pjsua_conf_connect(0, call_conf_slot); - - /* Automatically record conversation, if desired */ - if (app_config.auto_rec && app_config.rec_port != PJSUA_INVALID_ID) - { - pjsua_conf_connect(call_conf_slot, app_config.rec_port); - pjsua_conf_connect(0, app_config.rec_port); - } - } + pj_bool_t connect_sound = PJ_TRUE; + pj_bool_t disconnect_mic = PJ_FALSE; + pjsua_conf_port_id call_conf_slot; + + call_conf_slot = ci->media[mi].stream.aud.conf_slot; + + /* Make sure conf slot is valid (e.g: media dir is not "inactive") */ + if (call_conf_slot == PJSUA_INVALID_ID) + return; + + /* Loopback sound, if desired */ + if (app_config.auto_loop) { + pjsua_conf_connect(call_conf_slot, call_conf_slot); + connect_sound = PJ_FALSE; + } + + /* Automatically record conversation, if desired */ + if (app_config.auto_rec && app_config.rec_port != PJSUA_INVALID_ID) { + pjsua_conf_connect(call_conf_slot, app_config.rec_port); + } + + /* Stream a file, if desired */ + if ((app_config.auto_play || app_config.auto_play_hangup) && + app_config.wav_port != PJSUA_INVALID_ID) + { + pjsua_conf_connect(app_config.wav_port, call_conf_slot); + connect_sound = PJ_FALSE; + } + + /* Stream AVI, if desired */ + if (app_config.avi_auto_play && + app_config.avi_def_idx != PJSUA_INVALID_ID && + app_config.avi[app_config.avi_def_idx].slot != PJSUA_INVALID_ID) + { + pjsua_conf_connect(app_config.avi[app_config.avi_def_idx].slot, + call_conf_slot); + disconnect_mic = PJ_TRUE; + } + + /* Put call in conference with other calls, if desired */ + if (app_config.auto_conf) { + pjsua_call_id call_ids[PJSUA_MAX_CALLS]; + unsigned call_cnt=PJ_ARRAY_SIZE(call_ids); + unsigned i; + + /* Get all calls, and establish media connection between + * this call and other calls. + */ + pjsua_enum_calls(call_ids, &call_cnt); + + for (i=0; iid) + continue; + + if (!pjsua_call_has_media(call_ids[i])) + continue; + + pjsua_conf_connect(call_conf_slot, + pjsua_call_get_conf_port(call_ids[i])); + pjsua_conf_connect(pjsua_call_get_conf_port(call_ids[i]), + call_conf_slot); + + /* Automatically record conversation, if desired */ + if (app_config.auto_rec && app_config.rec_port != + PJSUA_INVALID_ID) + { + pjsua_conf_connect(pjsua_call_get_conf_port(call_ids[i]), + app_config.rec_port); + } + + } + + /* Also connect call to local sound device */ + connect_sound = PJ_TRUE; + } + + /* Otherwise connect to sound device */ + if (connect_sound) { + pjsua_conf_connect(call_conf_slot, 0); + if (!disconnect_mic) + pjsua_conf_connect(0, call_conf_slot); + + /* Automatically record conversation, if desired */ + if (app_config.auto_rec && app_config.rec_port != PJSUA_INVALID_ID) + { + pjsua_conf_connect(call_conf_slot, app_config.rec_port); + pjsua_conf_connect(0, app_config.rec_port); + } + } } } @@ -493,7 +492,7 @@ static void on_call_video_state(pjsua_call_info *ci, unsigned mi, pj_bool_t *has_error) { if (ci->media_status != PJSUA_CALL_MEDIA_ACTIVE) - return; + return; arrange_window(ci->media[mi].stream.vid.win_in); @@ -514,40 +513,40 @@ static void on_call_media_state(pjsua_call_id call_id) pjsua_call_get_info(call_id, &call_info); for (mi=0; mimethod) { case PJSUA_DTMF_METHOD_RFC2833: - pj_ansi_snprintf(method, sizeof(method), "RFC2833"); - break; + pj_ansi_snprintf(method, sizeof(method), "RFC2833"); + break; case PJSUA_DTMF_METHOD_SIP_INFO: - pj_ansi_snprintf(method, sizeof(method), "SIP INFO"); - pj_ansi_snprintf(duration, sizeof(duration), ":duration(%d)", - info->duration); - break; + pj_ansi_snprintf(method, sizeof(method), "SIP INFO"); + pj_ansi_snprintf(duration, sizeof(duration), ":duration(%d)", + info->duration); + break; }; PJ_LOG(3,(THIS_FILE, "Incoming DTMF on call %d: %c%s, using %s method", - call_id, info->digit, duration, method)); + call_id, info->digit, duration, method)); } /* * Redirection handler. */ static pjsip_redirect_op call_on_redirected(pjsua_call_id call_id, - const pjsip_uri *target, - const pjsip_event *e) + const pjsip_uri *target, + const pjsip_event *e) { PJ_UNUSED_ARG(e); if (app_config.redir_op == PJSIP_REDIRECT_PENDING) { - char uristr[PJSIP_MAX_URL_SIZE]; - int len; + char uristr[PJSIP_MAX_URL_SIZE]; + int len; - len = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, target, uristr, - sizeof(uristr)); - if (len < 1) { - pj_ansi_strcpy(uristr, "--URI too long--"); - } + len = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, target, uristr, + sizeof(uristr)); + if (len < 1) { + pj_ansi_strcpy(uristr, "--URI too long--"); + } - PJ_LOG(3,(THIS_FILE, "Call %d is being redirected to %.*s. " - "Press 'Ra' to accept+replace To header, 'RA' to accept, " - "'Rr' to reject, or 'Rd' to disconnect.", - call_id, len, uristr)); + PJ_LOG(3,(THIS_FILE, "Call %d is being redirected to %.*s. " + "Press 'Ra' to accept+replace To header, 'RA' to accept, " + "'Rr' to reject, or 'Rd' to disconnect.", + call_id, len, uristr)); } return app_config.redir_op; @@ -626,13 +625,13 @@ static void on_reg_state(pjsua_acc_id acc_id) * Handler for incoming presence subscription request */ static void on_incoming_subscribe(pjsua_acc_id acc_id, - pjsua_srv_pres *srv_pres, - pjsua_buddy_id buddy_id, - const pj_str_t *from, - pjsip_rx_data *rdata, - pjsip_status_code *code, - pj_str_t *reason, - pjsua_msg_data *msg_data_) + pjsua_srv_pres *srv_pres, + pjsua_buddy_id buddy_id, + const pj_str_t *from, + pjsip_rx_data *rdata, + pjsip_status_code *code, + pj_str_t *reason, + pjsua_msg_data *msg_data_) { /* Just accept the request (the default behavior) */ PJ_UNUSED_ARG(acc_id); @@ -655,15 +654,15 @@ static void on_buddy_state(pjsua_buddy_id buddy_id) pjsua_buddy_get_info(buddy_id, &info); PJ_LOG(3,(THIS_FILE, "%.*s status is %.*s, subscription state is %s " - "(last termination reason code=%d %.*s)", - (int)info.uri.slen, - info.uri.ptr, - (int)info.status_text.slen, - info.status_text.ptr, - info.sub_state_name, - info.sub_term_code, - (int)info.sub_term_reason.slen, - info.sub_term_reason.ptr)); + "(last termination reason code=%d %.*s)", + (int)info.uri.slen, + info.uri.ptr, + (int)info.status_text.slen, + info.status_text.ptr, + info.sub_state_name, + info.sub_term_code, + (int)info.sub_term_reason.slen, + info.sub_term_reason.ptr)); } @@ -671,8 +670,8 @@ static void on_buddy_state(pjsua_buddy_id buddy_id) * Subscription state has changed. */ static void on_buddy_evsub_state(pjsua_buddy_id buddy_id, - pjsip_evsub *sub, - pjsip_event *event) + pjsip_evsub *sub, + pjsip_event *event) { char event_info[80]; @@ -681,19 +680,19 @@ static void on_buddy_evsub_state(pjsua_buddy_id buddy_id, event_info[0] = '\0'; if (event->type == PJSIP_EVENT_TSX_STATE && - event->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + event->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; - snprintf(event_info, sizeof(event_info), - " (RX %s)", - pjsip_rx_data_get_info(rdata)); + pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; + snprintf(event_info, sizeof(event_info), + " (RX %s)", + pjsip_rx_data_get_info(rdata)); } PJ_LOG(4,(THIS_FILE, - "Buddy %d: subscription state: %s (event: %s%s)", - buddy_id, pjsip_evsub_get_state_name(sub), - pjsip_event_str(event->type), - event_info)); + "Buddy %d: subscription state: %s (event: %s%s)", + buddy_id, pjsip_evsub_get_state_name(sub), + pjsip_event_str(event->type), + event_info)); } @@ -702,8 +701,8 @@ static void on_buddy_evsub_state(pjsua_buddy_id buddy_id, * Incoming IM message (i.e. MESSAGE request)! */ static void on_pager(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - const pj_str_t *mime_type, const pj_str_t *text) + const pj_str_t *to, const pj_str_t *contact, + const pj_str_t *mime_type, const pj_str_t *text) { /* Note: call index may be -1 */ PJ_UNUSED_ARG(call_id); @@ -712,9 +711,9 @@ static void on_pager(pjsua_call_id call_id, const pj_str_t *from, PJ_UNUSED_ARG(mime_type); PJ_LOG(3,(THIS_FILE,"MESSAGE from %.*s: %.*s (%.*s)", - (int)from->slen, from->ptr, - (int)text->slen, text->ptr, - (int)mime_type->slen, mime_type->ptr)); + (int)from->slen, from->ptr, + (int)text->slen, text->ptr, + (int)mime_type->slen, mime_type->ptr)); } @@ -722,16 +721,16 @@ static void on_pager(pjsua_call_id call_id, const pj_str_t *from, * Received typing indication */ static void on_typing(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - pj_bool_t is_typing) + const pj_str_t *to, const pj_str_t *contact, + pj_bool_t is_typing) { PJ_UNUSED_ARG(call_id); PJ_UNUSED_ARG(to); PJ_UNUSED_ARG(contact); PJ_LOG(3,(THIS_FILE, "IM indication: %.*s %s", - (int)from->slen, from->ptr, - (is_typing?"is typing..":"has stopped typing"))); + (int)from->slen, from->ptr, + (is_typing?"is typing..":"has stopped typing"))); } @@ -739,22 +738,22 @@ static void on_typing(pjsua_call_id call_id, const pj_str_t *from, * Call transfer request status. */ static void on_call_transfer_status(pjsua_call_id call_id, - int status_code, - const pj_str_t *status_text, - pj_bool_t final, - pj_bool_t *p_cont) + int status_code, + const pj_str_t *status_text, + pj_bool_t final, + pj_bool_t *p_cont) { PJ_LOG(3,(THIS_FILE, "Call %d: transfer status=%d (%.*s) %s", - call_id, status_code, - (int)status_text->slen, status_text->ptr, - (final ? "[final]" : ""))); + call_id, status_code, + (int)status_text->slen, status_text->ptr, + (final ? "[final]" : ""))); if (status_code/100 == 2) { - PJ_LOG(3,(THIS_FILE, - "Call %d: call transferred successfully, disconnecting call", - call_id)); - pjsua_call_hangup(call_id, PJSIP_SC_GONE, NULL, NULL); - *p_cont = PJ_FALSE; + PJ_LOG(3,(THIS_FILE, + "Call %d: call transferred successfully, disconnecting call", + call_id)); + pjsua_call_hangup(call_id, PJSIP_SC_GONE, NULL, NULL); + *p_cont = PJ_FALSE; } } @@ -763,7 +762,7 @@ static void on_call_transfer_status(pjsua_call_id call_id, * Notification that call is being replaced. */ static void on_call_replaced(pjsua_call_id old_call_id, - pjsua_call_id new_call_id) + pjsua_call_id new_call_id) { pjsua_call_info old_ci, new_ci; @@ -771,11 +770,11 @@ static void on_call_replaced(pjsua_call_id old_call_id, pjsua_call_get_info(new_call_id, &new_ci); PJ_LOG(3,(THIS_FILE, "Call %d with %.*s is being replaced by " - "call %d with %.*s", - old_call_id, - (int)old_ci.remote_info.slen, old_ci.remote_info.ptr, - new_call_id, - (int)new_ci.remote_info.slen, new_ci.remote_info.ptr)); + "call %d with %.*s", + old_call_id, + (int)old_ci.remote_info.slen, old_ci.remote_info.ptr, + new_call_id, + (int)new_ci.remote_info.slen, new_ci.remote_info.ptr)); } @@ -785,9 +784,9 @@ static void on_call_replaced(pjsua_call_id old_call_id, static void on_nat_detect(const pj_stun_nat_detect_result *res) { if (res->status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "NAT detection failed", res->status); + pjsua_perror(THIS_FILE, "NAT detection failed", res->status); } else { - PJ_LOG(3, (THIS_FILE, "NAT detected as %s", res->nat_type_name)); + PJ_LOG(3, (THIS_FILE, "NAT detected as %s", res->nat_type_name)); } } @@ -802,18 +801,18 @@ static void on_mwi_info(pjsua_acc_id acc_id, pjsua_mwi_info *mwi_info) PJ_LOG(3,(THIS_FILE, "Received MWI for acc %d:", acc_id)); if (mwi_info->rdata->msg_info.ctype) { - const pjsip_ctype_hdr *ctype = mwi_info->rdata->msg_info.ctype; + const pjsip_ctype_hdr *ctype = mwi_info->rdata->msg_info.ctype; - PJ_LOG(3,(THIS_FILE, " Content-Type: %.*s/%.*s", - (int)ctype->media.type.slen, - ctype->media.type.ptr, - (int)ctype->media.subtype.slen, - ctype->media.subtype.ptr)); + PJ_LOG(3,(THIS_FILE, " Content-Type: %.*s/%.*s", + (int)ctype->media.type.slen, + ctype->media.type.ptr, + (int)ctype->media.subtype.slen, + ctype->media.subtype.ptr)); } if (!mwi_info->rdata->msg_info.msg->body) { - PJ_LOG(3,(THIS_FILE, " no message body")); - return; + PJ_LOG(3,(THIS_FILE, " no message body")); + return; } body.ptr = (char *)mwi_info->rdata->msg_info.msg->body->data; @@ -827,79 +826,79 @@ static void on_mwi_info(pjsua_acc_id acc_id, pjsua_mwi_info *mwi_info) * Transport status notification */ static void on_transport_state(pjsip_transport *tp, - pjsip_transport_state state, - const pjsip_transport_state_info *info) + pjsip_transport_state state, + const pjsip_transport_state_info *info) { char host_port[128]; pj_addr_str_print(&tp->remote_name.host, - tp->remote_name.port, host_port, sizeof(host_port), 1); + tp->remote_name.port, host_port, sizeof(host_port), 1); switch (state) { case PJSIP_TP_STATE_CONNECTED: - { - PJ_LOG(3,(THIS_FILE, "SIP %s transport is connected to %s", - tp->type_name, host_port)); - } - break; + { + PJ_LOG(3,(THIS_FILE, "SIP %s transport is connected to %s", + tp->type_name, host_port)); + } + break; case PJSIP_TP_STATE_DISCONNECTED: - { - char buf[100]; - int len; + { + char buf[100]; + int len; - len = pj_ansi_snprintf(buf, sizeof(buf), "SIP %s transport is " - "disconnected from %s", tp->type_name, host_port); - PJ_CHECK_TRUNC_STR(len, buf, sizeof(buf)); - pjsua_perror(THIS_FILE, buf, info->status); - } - break; + len = pj_ansi_snprintf(buf, sizeof(buf), "SIP %s transport is " + "disconnected from %s", tp->type_name, host_port); + PJ_CHECK_TRUNC_STR(len, buf, sizeof(buf)); + pjsua_perror(THIS_FILE, buf, info->status); + } + break; default: - break; + break; } #if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0 if (!pj_ansi_stricmp(tp->type_name, "tls") && info->ext_info && - (state == PJSIP_TP_STATE_CONNECTED || - ((pjsip_tls_state_info*)info->ext_info)-> - ssl_sock_info->verify_status != PJ_SUCCESS)) + (state == PJSIP_TP_STATE_CONNECTED || + ((pjsip_tls_state_info*)info->ext_info)-> + ssl_sock_info->verify_status != PJ_SUCCESS)) { - pjsip_tls_state_info *tls_info = (pjsip_tls_state_info*)info->ext_info; - pj_ssl_sock_info *ssl_sock_info = tls_info->ssl_sock_info; - char buf[2048]; - const char *verif_msgs[32]; - unsigned verif_msg_cnt; - - /* Dump server TLS cipher */ - PJ_LOG(4,(THIS_FILE, "TLS cipher used: 0x%06X/%s", - ssl_sock_info->cipher, - pj_ssl_cipher_name(ssl_sock_info->cipher) )); - - /* Dump server TLS certificate */ - pj_ssl_cert_info_dump(ssl_sock_info->remote_cert_info, " ", - buf, sizeof(buf)); - PJ_LOG(4,(THIS_FILE, "TLS cert info of %s:\n%s", host_port, buf)); - - /* Dump server TLS certificate verification result */ - verif_msg_cnt = PJ_ARRAY_SIZE(verif_msgs); - pj_ssl_cert_get_verify_status_strings(ssl_sock_info->verify_status, - verif_msgs, &verif_msg_cnt); - PJ_LOG(3,(THIS_FILE, "TLS cert verification result of %s : %s", - host_port, - (verif_msg_cnt == 1? verif_msgs[0]:""))); - if (verif_msg_cnt > 1) { - unsigned i; - for (i = 0; i < verif_msg_cnt; ++i) - PJ_LOG(3,(THIS_FILE, "- %s", verif_msgs[i])); - } - - if (ssl_sock_info->verify_status && - !app_config.udp_cfg.tls_setting.verify_server) - { - PJ_LOG(3,(THIS_FILE, "PJSUA is configured to ignore TLS cert " - "verification errors")); - } + pjsip_tls_state_info *tls_info = (pjsip_tls_state_info*)info->ext_info; + pj_ssl_sock_info *ssl_sock_info = tls_info->ssl_sock_info; + char buf[2048]; + const char *verif_msgs[32]; + unsigned verif_msg_cnt; + + /* Dump server TLS cipher */ + PJ_LOG(4,(THIS_FILE, "TLS cipher used: 0x%06X/%s", + ssl_sock_info->cipher, + pj_ssl_cipher_name(ssl_sock_info->cipher) )); + + /* Dump server TLS certificate */ + pj_ssl_cert_info_dump(ssl_sock_info->remote_cert_info, " ", + buf, sizeof(buf)); + PJ_LOG(4,(THIS_FILE, "TLS cert info of %s:\n%s", host_port, buf)); + + /* Dump server TLS certificate verification result */ + verif_msg_cnt = PJ_ARRAY_SIZE(verif_msgs); + pj_ssl_cert_get_verify_status_strings(ssl_sock_info->verify_status, + verif_msgs, &verif_msg_cnt); + PJ_LOG(3,(THIS_FILE, "TLS cert verification result of %s : %s", + host_port, + (verif_msg_cnt == 1? verif_msgs[0]:""))); + if (verif_msg_cnt > 1) { + unsigned i; + for (i = 0; i < verif_msg_cnt; ++i) + PJ_LOG(3,(THIS_FILE, "- %s", verif_msgs[i])); + } + + if (ssl_sock_info->verify_status && + !app_config.udp_cfg.tls_setting.verify_server) + { + PJ_LOG(3,(THIS_FILE, "PJSUA is configured to ignore TLS cert " + "verification errors")); + } } #endif @@ -910,12 +909,12 @@ static void on_transport_state(pjsip_transport *tp, * Notification on ICE error. */ static void on_ice_transport_error(int index, pj_ice_strans_op op, - pj_status_t status, void *param) + pj_status_t status, void *param) { PJ_UNUSED_ARG(op); PJ_UNUSED_ARG(param); PJ_PERROR(1,(THIS_FILE, status, - "ICE keep alive failure for transport %d", index)); + "ICE keep alive failure for transport %d", index)); } /* @@ -927,20 +926,20 @@ static pj_status_t on_snd_dev_operation(int operation) pjsua_get_snd_dev(&cap_dev, &play_dev); PJ_LOG(3,(THIS_FILE, "Turning sound device %d %d %s", cap_dev, play_dev, - (operation? "ON":"OFF"))); + (operation? "ON":"OFF"))); return PJ_SUCCESS; } static char *get_media_dir(pjmedia_dir dir) { switch (dir) { case PJMEDIA_DIR_ENCODING: - return "TX"; + return "TX"; case PJMEDIA_DIR_DECODING: - return "RX"; + return "RX"; case PJMEDIA_DIR_ENCODING+PJMEDIA_DIR_DECODING: - return "TX+RX"; + return "TX+RX"; default: - return "unknown dir"; + return "unknown dir"; } } @@ -952,43 +951,43 @@ static void on_call_media_event(pjsua_call_id call_id, char event_name[5]; PJ_LOG(5,(THIS_FILE, "Event %s", - pjmedia_fourcc_name(event->type, event_name))); + pjmedia_fourcc_name(event->type, event_name))); if (event->type == PJMEDIA_EVENT_MEDIA_TP_ERR) { - pjmedia_event_media_tp_err_data *err_data; + pjmedia_event_media_tp_err_data *err_data; - err_data = &event->data.med_tp_err; - PJ_PERROR(3, (THIS_FILE, err_data->status, - "Media transport error event (%s %s %s)", - (err_data->type==PJMEDIA_TYPE_AUDIO)?"Audio":"Video", - (err_data->is_rtp)?"RTP":"RTCP", - get_media_dir(err_data->dir))); + err_data = &event->data.med_tp_err; + PJ_PERROR(3, (THIS_FILE, err_data->status, + "Media transport error event (%s %s %s)", + (err_data->type==PJMEDIA_TYPE_AUDIO)?"Audio":"Video", + (err_data->is_rtp)?"RTP":"RTCP", + get_media_dir(err_data->dir))); } #if PJSUA_HAS_VIDEO else if (event->type == PJMEDIA_EVENT_FMT_CHANGED) { - /* Adjust renderer window size to original video size */ - pjsua_call_info ci; + /* Adjust renderer window size to original video size */ + pjsua_call_info ci; - pjsua_call_get_info(call_id, &ci); + pjsua_call_get_info(call_id, &ci); - if ((ci.media[med_idx].type == PJMEDIA_TYPE_VIDEO) && - (ci.media[med_idx].dir & PJMEDIA_DIR_DECODING)) - { - pjsua_vid_win_id wid; - pjmedia_rect_size size; - pjsua_vid_win_info win_info; + if ((ci.media[med_idx].type == PJMEDIA_TYPE_VIDEO) && + (ci.media[med_idx].dir & PJMEDIA_DIR_DECODING)) + { + pjsua_vid_win_id wid; + pjmedia_rect_size size; + pjsua_vid_win_info win_info; - wid = ci.media[med_idx].stream.vid.win_in; - pjsua_vid_win_get_info(wid, &win_info); + wid = ci.media[med_idx].stream.vid.win_in; + pjsua_vid_win_get_info(wid, &win_info); - size = event->data.fmt_changed.new_fmt.det.vid.size; - if (size.w != win_info.size.w || size.h != win_info.size.h) { - pjsua_vid_win_set_size(wid, &size); + size = event->data.fmt_changed.new_fmt.det.vid.size; + if (size.w != win_info.size.w || size.h != win_info.size.h) { + pjsua_vid_win_set_size(wid, &size); - /* Re-arrange video windows */ - arrange_window(PJSUA_INVALID_ID); - } - } + /* Re-arrange video windows */ + arrange_window(PJSUA_INVALID_ID); + } + } } #else PJ_UNUSED_ARG(call_id); @@ -1001,9 +1000,9 @@ static void on_call_media_event(pjsua_call_id call_id, * This callback is called when media transport needs to be created. */ static pjmedia_transport* on_create_media_transport(pjsua_call_id call_id, - unsigned media_idx, - pjmedia_transport *base_tp, - unsigned flags) + unsigned media_idx, + pjmedia_transport *base_tp, + unsigned flags) { pjmedia_transport *adapter; pj_status_t status; @@ -1014,12 +1013,12 @@ static pjmedia_transport* on_create_media_transport(pjsua_call_id call_id, (flags & PJSUA_MED_TP_CLOSE_MEMBER), &adapter); if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "Error creating adapter")); - return NULL; + PJ_PERROR(1,(THIS_FILE, status, "Error creating adapter")); + return NULL; } PJ_LOG(3,(THIS_FILE, "Media transport is created for call %d media %d", - call_id, media_idx)); + call_id, media_idx)); return adapter; } @@ -1035,91 +1034,91 @@ void on_playfile_done(pjmedia_port *port, void *usr_data) /* Just rewind WAV when it is played outside of call */ if (pjsua_call_get_count() == 0) { - pjsua_player_set_pos(app_config.wav_id, 0); + pjsua_player_set_pos(app_config.wav_id, 0); } /* Timer is already active */ if (app_config.auto_hangup_timer.id == 1) - return; + return; app_config.auto_hangup_timer.id = 1; delay.sec = 0; delay.msec = 200; /* Give 200 ms before hangup */ pjsip_endpt_schedule_timer(pjsua_get_pjsip_endpt(), - &app_config.auto_hangup_timer, - &delay); + &app_config.auto_hangup_timer, + &delay); } /* IP change progress callback. */ void on_ip_change_progress(pjsua_ip_change_op op, - pj_status_t status, - const pjsua_ip_change_op_info *info) + pj_status_t status, + const pjsua_ip_change_op_info *info) { char info_str[128]; pjsua_acc_info acc_info; pjsua_transport_info tp_info; if (status == PJ_SUCCESS) { - switch (op) { - case PJSUA_IP_CHANGE_OP_RESTART_LIS: - pjsua_transport_get_info(info->lis_restart.transport_id, &tp_info); - pj_ansi_snprintf(info_str, sizeof(info_str), - "restart transport %.*s", - (int)tp_info.info.slen, tp_info.info.ptr); - break; - case PJSUA_IP_CHANGE_OP_ACC_SHUTDOWN_TP: - pjsua_acc_get_info(info->acc_shutdown_tp.acc_id, &acc_info); - - pj_ansi_snprintf(info_str, sizeof(info_str), - "transport shutdown for account %.*s", - (int)acc_info.acc_uri.slen, - acc_info.acc_uri.ptr); - break; - case PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT: - pjsua_acc_get_info(info->acc_shutdown_tp.acc_id, &acc_info); - if (info->acc_update_contact.code) { - pj_ansi_snprintf(info_str, sizeof(info_str), - "update contact for account %.*s, code[%d]", - (int)acc_info.acc_uri.slen, - acc_info.acc_uri.ptr, - info->acc_update_contact.code); - } else { - pj_ansi_snprintf(info_str, sizeof(info_str), - "update contact for account %.*s", - (int)acc_info.acc_uri.slen, - acc_info.acc_uri.ptr); - } - break; - case PJSUA_IP_CHANGE_OP_ACC_HANGUP_CALLS: - pjsua_acc_get_info(info->acc_shutdown_tp.acc_id, &acc_info); - pj_ansi_snprintf(info_str, sizeof(info_str), - "hangup call for account %.*s, call_id[%d]", - (int)acc_info.acc_uri.slen, acc_info.acc_uri.ptr, - info->acc_hangup_calls.call_id); - break; - case PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS: - pjsua_acc_get_info(info->acc_shutdown_tp.acc_id, &acc_info); - pj_ansi_snprintf(info_str, sizeof(info_str), - "reinvite call for account %.*s, call_id[%d]", - (int)acc_info.acc_uri.slen, acc_info.acc_uri.ptr, - info->acc_reinvite_calls.call_id); - break; - case PJSUA_IP_CHANGE_OP_COMPLETED: - pj_ansi_snprintf(info_str, sizeof(info_str), - "done"); - default: - break; - } - PJ_LOG(3,(THIS_FILE, "IP change progress report : %s", info_str)); + switch (op) { + case PJSUA_IP_CHANGE_OP_RESTART_LIS: + pjsua_transport_get_info(info->lis_restart.transport_id, &tp_info); + pj_ansi_snprintf(info_str, sizeof(info_str), + "restart transport %.*s", + (int)tp_info.info.slen, tp_info.info.ptr); + break; + case PJSUA_IP_CHANGE_OP_ACC_SHUTDOWN_TP: + pjsua_acc_get_info(info->acc_shutdown_tp.acc_id, &acc_info); + + pj_ansi_snprintf(info_str, sizeof(info_str), + "transport shutdown for account %.*s", + (int)acc_info.acc_uri.slen, + acc_info.acc_uri.ptr); + break; + case PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT: + pjsua_acc_get_info(info->acc_shutdown_tp.acc_id, &acc_info); + if (info->acc_update_contact.code) { + pj_ansi_snprintf(info_str, sizeof(info_str), + "update contact for account %.*s, code[%d]", + (int)acc_info.acc_uri.slen, + acc_info.acc_uri.ptr, + info->acc_update_contact.code); + } else { + pj_ansi_snprintf(info_str, sizeof(info_str), + "update contact for account %.*s", + (int)acc_info.acc_uri.slen, + acc_info.acc_uri.ptr); + } + break; + case PJSUA_IP_CHANGE_OP_ACC_HANGUP_CALLS: + pjsua_acc_get_info(info->acc_shutdown_tp.acc_id, &acc_info); + pj_ansi_snprintf(info_str, sizeof(info_str), + "hangup call for account %.*s, call_id[%d]", + (int)acc_info.acc_uri.slen, acc_info.acc_uri.ptr, + info->acc_hangup_calls.call_id); + break; + case PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS: + pjsua_acc_get_info(info->acc_shutdown_tp.acc_id, &acc_info); + pj_ansi_snprintf(info_str, sizeof(info_str), + "reinvite call for account %.*s, call_id[%d]", + (int)acc_info.acc_uri.slen, acc_info.acc_uri.ptr, + info->acc_reinvite_calls.call_id); + break; + case PJSUA_IP_CHANGE_OP_COMPLETED: + pj_ansi_snprintf(info_str, sizeof(info_str), + "done"); + default: + break; + } + PJ_LOG(3,(THIS_FILE, "IP change progress report : %s", info_str)); } else { - PJ_PERROR(3,(THIS_FILE, status, "IP change progress fail")); + PJ_PERROR(3,(THIS_FILE, status, "IP change progress fail")); } } /* Auto hangup timer callback */ static void hangup_timeout_callback(pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { PJ_UNUSED_ARG(timer_heap); PJ_UNUSED_ARG(entry); @@ -1141,35 +1140,35 @@ static void simple_registrar(pjsip_rx_data *rdata) pj_status_t status; status = pjsip_endpt_create_response(pjsua_get_pjsip_endpt(), - rdata, 200, NULL, &tdata); + rdata, 200, NULL, &tdata); if (status != PJ_SUCCESS) return; exp = (pjsip_expires_hdr *)pjsip_msg_find_hdr(rdata->msg_info.msg, - PJSIP_H_EXPIRES, NULL); + PJSIP_H_EXPIRES, NULL); h = rdata->msg_info.msg->hdr.next; while (h != &rdata->msg_info.msg->hdr) { - if (h->type == PJSIP_H_CONTACT) { - const pjsip_contact_hdr *c = (const pjsip_contact_hdr*)h; - unsigned e = c->expires; - - if (e != PJSIP_EXPIRES_NOT_SPECIFIED) { - if (exp) - e = exp->ivalue; - else - e = 3600; - } - - if (e > 0) { - pjsip_contact_hdr *nc = (pjsip_contact_hdr *)pjsip_hdr_clone( - tdata->pool, h); - nc->expires = e; - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)nc); - ++cnt; - } - } - h = h->next; + if (h->type == PJSIP_H_CONTACT) { + const pjsip_contact_hdr *c = (const pjsip_contact_hdr*)h; + unsigned e = c->expires; + + if (e != PJSIP_EXPIRES_NOT_SPECIFIED) { + if (exp) + e = exp->ivalue; + else + e = 3600; + } + + if (e > 0) { + pjsip_contact_hdr *nc = (pjsip_contact_hdr *)pjsip_hdr_clone( + tdata->pool, h); + nc->expires = e; + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)nc); + ++cnt; + } + } + h = h->next; } srv = pjsip_generic_string_hdr_create(tdata->pool, NULL, NULL); @@ -1178,10 +1177,10 @@ static void simple_registrar(pjsip_rx_data *rdata) pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)srv); status = pjsip_endpt_send_response2(pjsua_get_pjsip_endpt(), - rdata, tdata, NULL, NULL); - if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - } + rdata, tdata, NULL, NULL); + if (status != PJ_SUCCESS) { + pjsip_tx_data_dec_ref(tdata); + } } @@ -1199,66 +1198,66 @@ static pj_bool_t default_mod_on_rx_request(pjsip_rx_data *rdata) /* Don't respond to ACK! */ if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, - &pjsip_ack_method) == 0) - return PJ_TRUE; + &pjsip_ack_method) == 0) + return PJ_TRUE; /* Simple registrar */ if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_register_method) == 0) { - simple_registrar(rdata); - return PJ_TRUE; + simple_registrar(rdata); + return PJ_TRUE; } /* Create basic response. */ if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, - &pjsip_notify_method) == 0) + &pjsip_notify_method) == 0) { - /* Unsolicited NOTIFY's, send with Bad Request */ - status_code = PJSIP_SC_BAD_REQUEST; + /* Unsolicited NOTIFY's, send with Bad Request */ + status_code = PJSIP_SC_BAD_REQUEST; } else { - /* Probably unknown method */ - status_code = PJSIP_SC_METHOD_NOT_ALLOWED; + /* Probably unknown method */ + status_code = PJSIP_SC_METHOD_NOT_ALLOWED; } status = pjsip_endpt_create_response(pjsua_get_pjsip_endpt(), - rdata, status_code, - NULL, &tdata); + rdata, status_code, + NULL, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create response", status); - return PJ_TRUE; + pjsua_perror(THIS_FILE, "Unable to create response", status); + return PJ_TRUE; } /* Add Allow if we're responding with 405 */ if (status_code == PJSIP_SC_METHOD_NOT_ALLOWED) { - const pjsip_hdr *cap_hdr; - cap_hdr = pjsip_endpt_get_capability(pjsua_get_pjsip_endpt(), - PJSIP_H_ALLOW, NULL); - if (cap_hdr) { - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *)pjsip_hdr_clone( - tdata->pool, cap_hdr)); - } + const pjsip_hdr *cap_hdr; + cap_hdr = pjsip_endpt_get_capability(pjsua_get_pjsip_endpt(), + PJSIP_H_ALLOW, NULL); + if (cap_hdr) { + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *)pjsip_hdr_clone( + tdata->pool, cap_hdr)); + } } /* Add User-Agent header */ { - pj_str_t user_agent; - char tmp[80]; - const pj_str_t USER_AGENT = { "User-Agent", 10}; - pjsip_hdr *h; + pj_str_t user_agent; + char tmp[80]; + const pj_str_t USER_AGENT = { "User-Agent", 10}; + pjsip_hdr *h; - pj_ansi_snprintf(tmp, sizeof(tmp), "PJSUA v%s/%s", - pj_get_version(), PJ_OS_NAME); - pj_strdup2_with_null(tdata->pool, &user_agent, tmp); + pj_ansi_snprintf(tmp, sizeof(tmp), "PJSUA v%s/%s", + pj_get_version(), PJ_OS_NAME); + pj_strdup2_with_null(tdata->pool, &user_agent, tmp); - h = (pjsip_hdr*) pjsip_generic_string_hdr_create(tdata->pool, - &USER_AGENT, - &user_agent); - pjsip_msg_add_hdr(tdata->msg, h); + h = (pjsip_hdr*) pjsip_generic_string_hdr_create(tdata->pool, + &USER_AGENT, + &user_agent); + pjsip_msg_add_hdr(tdata->msg, h); } status = pjsip_endpt_send_response2(pjsua_get_pjsip_endpt(), rdata, tdata, - NULL, NULL); - if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(tdata); + NULL, NULL); + if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(tdata); return PJ_TRUE; } @@ -1266,19 +1265,19 @@ static pj_bool_t default_mod_on_rx_request(pjsip_rx_data *rdata) /* The module instance. */ static pjsip_module mod_default_handler = { - NULL, NULL, /* prev, next. */ - { "mod-default-handler", 19 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION+99, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &default_mod_on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-default-handler", 19 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION+99, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &default_mod_on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -1289,17 +1288,17 @@ void cli_on_started(pj_status_t status) { /* Notify app */ if (app_cfg.on_started) { - if (status == PJ_SUCCESS) { - char info[128]; - cli_get_info(info, sizeof(info)); - if (app_cfg.on_started) { - (*app_cfg.on_started)(status, info); - } - } else { - if (app_cfg.on_started) { - (*app_cfg.on_started)(status, NULL); - } - } + if (status == PJ_SUCCESS) { + char info[128]; + cli_get_info(info, sizeof(info)); + if (app_cfg.on_started) { + (*app_cfg.on_started)(status, info); + } + } else { + if (app_cfg.on_started) { + (*app_cfg.on_started)(status, NULL); + } + } } } @@ -1308,7 +1307,7 @@ void cli_on_stopped(pj_bool_t restart, int argc, char* argv[]) { /* Notify app */ if (app_cfg.on_stopped) - (*app_cfg.on_stopped)(restart, argc, argv); + (*app_cfg.on_stopped)(restart, argc, argv); } @@ -1317,7 +1316,7 @@ void legacy_on_stopped(pj_bool_t restart) { /* Notify app */ if (app_cfg.on_stopped) - (*app_cfg.on_stopped)(restart, 1, NULL); + (*app_cfg.on_stopped)(restart, 1, NULL); } /***************************************************************************** @@ -1334,12 +1333,12 @@ int stdout_refresh_proc(void *arg) * stdout output */ pj_thread_set_prio(pj_thread_this(), - pj_thread_get_prio_min(pj_thread_this())); + pj_thread_get_prio_min(pj_thread_this())); while (!stdout_refresh_quit) { - pj_thread_sleep(stdout_refresh * 1000); - puts(stdout_refresh_text); - fflush(stdout); + pj_thread_sleep(stdout_refresh * 1000); + puts(stdout_refresh_text); + fflush(stdout); } return 0; @@ -1357,7 +1356,7 @@ static pj_status_t app_init(void) /** Create pjsua **/ status = pjsua_create(); if (status != PJ_SUCCESS) - return status; + return status; /* Create pool for application */ app_config.pool = pjsua_pool_create("pjsua-app", 1000, 1000); @@ -1365,17 +1364,17 @@ static pj_status_t app_init(void) /* Init CLI & its FE settings */ if (!app_running) { - pj_cli_cfg_default(&app_config.cli_cfg.cfg); - pj_cli_telnet_cfg_default(&app_config.cli_cfg.telnet_cfg); - pj_cli_console_cfg_default(&app_config.cli_cfg.console_cfg); - app_config.cli_cfg.telnet_cfg.on_started = cli_on_started; + pj_cli_cfg_default(&app_config.cli_cfg.cfg); + pj_cli_telnet_cfg_default(&app_config.cli_cfg.telnet_cfg); + pj_cli_console_cfg_default(&app_config.cli_cfg.console_cfg); + app_config.cli_cfg.telnet_cfg.on_started = cli_on_started; } /** Parse args **/ status = load_config(app_cfg.argc, app_cfg.argv, &uri_arg); if (status != PJ_SUCCESS) { - pj_pool_release(tmp_pool); - return status; + pj_pool_release(tmp_pool); + return status; } /* Initialize application callbacks */ @@ -1406,26 +1405,26 @@ static pj_status_t app_init(void) /* Set sound device latency */ if (app_config.capture_lat > 0) - app_config.media_cfg.snd_rec_latency = app_config.capture_lat; + app_config.media_cfg.snd_rec_latency = app_config.capture_lat; if (app_config.playback_lat) - app_config.media_cfg.snd_play_latency = app_config.playback_lat; + app_config.media_cfg.snd_play_latency = app_config.playback_lat; if (app_cfg.on_config_init) - (*app_cfg.on_config_init)(&app_config); + (*app_cfg.on_config_init)(&app_config); /* Initialize pjsua */ status = pjsua_init(&app_config.cfg, &app_config.log_cfg, - &app_config.media_cfg); + &app_config.media_cfg); if (status != PJ_SUCCESS) { - pj_pool_release(tmp_pool); - return status; + pj_pool_release(tmp_pool); + return status; } /* Initialize our module to handle otherwise unhandled request */ status = pjsip_endpt_register_module(pjsua_get_pjsip_endpt(), - &mod_default_handler); + &mod_default_handler); if (status != PJ_SUCCESS) - return status; + return status; #ifdef STEREO_DEMO stereo_demo(); @@ -1433,360 +1432,360 @@ static pj_status_t app_init(void) /* Initialize calls data */ for (i=0; iinfo.fmt; - - pjmedia_fourcc_name(fmt->id, fmt_name); - - if (fmt->id == PJMEDIA_FORMAT_PCM) { - status = pjsua_conf_add_port(app_config.pool, aud, - &slot); - if (status == PJ_SUCCESS) { - PJ_LOG(4,(THIS_FILE, - "AVI %.*s: audio added to slot %d", - (int)avdp.title.slen, avdp.title.ptr, - slot)); - app_config.avi[i].slot = slot; - } - } else { - PJ_LOG(4,(THIS_FILE, - "AVI %.*s: audio ignored, format=%s", - (int)avdp.title.slen, avdp.title.ptr, - fmt_name)); - } - } - } + pjmedia_vid_dev_factory *avi_factory; + + status = pjmedia_avi_dev_create_factory(pjsua_get_pool_factory(), + app_config.avi_cnt, + &avi_factory); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, "Error creating AVI factory")); + goto on_error; + } + + for (i=0; iinfo.fmt; + + pjmedia_fourcc_name(fmt->id, fmt_name); + + if (fmt->id == PJMEDIA_FORMAT_PCM) { + status = pjsua_conf_add_port(app_config.pool, aud, + &slot); + if (status == PJ_SUCCESS) { + PJ_LOG(4,(THIS_FILE, + "AVI %.*s: audio added to slot %d", + (int)avdp.title.slen, avdp.title.ptr, + slot)); + app_config.avi[i].slot = slot; + } + } else { + PJ_LOG(4,(THIS_FILE, + "AVI %.*s: audio ignored, format=%s", + (int)avdp.title.slen, avdp.title.ptr, + fmt_name)); + } + } + } #else - PJ_LOG(2,(THIS_FILE, - "Warning: --play-avi is ignored because AVI is disabled")); -#endif /* PJMEDIA_VIDEO_DEV_HAS_AVI */ + PJ_LOG(2,(THIS_FILE, + "Warning: --play-avi is ignored because AVI is disabled")); +#endif /* PJMEDIA_VIDEO_DEV_HAS_AVI */ } /* Add UDP transport unless it's disabled. */ if (!app_config.no_udp) { - pjsua_acc_id aid; - pjsip_transport_type_e type = PJSIP_TRANSPORT_UDP; + pjsua_acc_id aid; + pjsip_transport_type_e type = PJSIP_TRANSPORT_UDP; - status = pjsua_transport_create(type, - &app_config.udp_cfg, - &transport_id); - if (status != PJ_SUCCESS) - goto on_error; + status = pjsua_transport_create(type, + &app_config.udp_cfg, + &transport_id); + if (status != PJ_SUCCESS) + goto on_error; - /* Add local account */ - pjsua_acc_add_local(transport_id, PJ_TRUE, &aid); + /* Add local account */ + pjsua_acc_add_local(transport_id, PJ_TRUE, &aid); - /* Adjust local account config based on pjsua app config */ - { - pjsua_acc_config acc_cfg; - pjsua_acc_get_config(aid, tmp_pool, &acc_cfg); + /* Adjust local account config based on pjsua app config */ + { + pjsua_acc_config acc_cfg; + pjsua_acc_get_config(aid, tmp_pool, &acc_cfg); - app_config_init_video(&acc_cfg); - acc_cfg.rtp_cfg = app_config.rtp_cfg; - pjsua_acc_modify(aid, &acc_cfg); - } + app_config_init_video(&acc_cfg); + acc_cfg.rtp_cfg = app_config.rtp_cfg; + pjsua_acc_modify(aid, &acc_cfg); + } - //pjsua_acc_set_transport(aid, transport_id); - pjsua_acc_set_online_status(current_acc, PJ_TRUE); + //pjsua_acc_set_transport(aid, transport_id); + pjsua_acc_set_online_status(current_acc, PJ_TRUE); - if (app_config.udp_cfg.port == 0) { - pjsua_transport_info ti; - pj_sockaddr_in *a; + if (app_config.udp_cfg.port == 0) { + pjsua_transport_info ti; + pj_sockaddr_in *a; - pjsua_transport_get_info(transport_id, &ti); - a = (pj_sockaddr_in*)&ti.local_addr; + pjsua_transport_get_info(transport_id, &ti); + a = (pj_sockaddr_in*)&ti.local_addr; - tcp_cfg.port = pj_ntohs(a->sin_port); - } + tcp_cfg.port = pj_ntohs(a->sin_port); + } } /* Add UDP IPv6 transport unless it's disabled. */ if (!app_config.no_udp && app_config.ipv6) { - pjsua_acc_id aid; - pjsip_transport_type_e type = PJSIP_TRANSPORT_UDP6; - pjsua_transport_config udp_cfg; - - udp_cfg = app_config.udp_cfg; - if (udp_cfg.port == 0) - udp_cfg.port = 5060; - else - udp_cfg.port += 10; - status = pjsua_transport_create(type, - &udp_cfg, - &transport_id); - if (status != PJ_SUCCESS) - goto on_error; - - /* Add local account */ - pjsua_acc_add_local(transport_id, PJ_TRUE, &aid); - - /* Adjust local account config based on pjsua app config */ - { - pjsua_acc_config acc_cfg; - pjsua_acc_get_config(aid, tmp_pool, &acc_cfg); - - app_config_init_video(&acc_cfg); - acc_cfg.rtp_cfg = app_config.rtp_cfg; - acc_cfg.ipv6_media_use = PJSUA_IPV6_ENABLED; - pjsua_acc_modify(aid, &acc_cfg); - } - - //pjsua_acc_set_transport(aid, transport_id); - pjsua_acc_set_online_status(current_acc, PJ_TRUE); - - if (app_config.udp_cfg.port == 0) { - pjsua_transport_info ti; - - pjsua_transport_get_info(transport_id, &ti); - tcp_cfg.port = pj_sockaddr_get_port(&ti.local_addr); - } + pjsua_acc_id aid; + pjsip_transport_type_e type = PJSIP_TRANSPORT_UDP6; + pjsua_transport_config udp_cfg; + + udp_cfg = app_config.udp_cfg; + if (udp_cfg.port == 0) + udp_cfg.port = 5060; + else + udp_cfg.port += 10; + status = pjsua_transport_create(type, + &udp_cfg, + &transport_id); + if (status != PJ_SUCCESS) + goto on_error; + + /* Add local account */ + pjsua_acc_add_local(transport_id, PJ_TRUE, &aid); + + /* Adjust local account config based on pjsua app config */ + { + pjsua_acc_config acc_cfg; + pjsua_acc_get_config(aid, tmp_pool, &acc_cfg); + + app_config_init_video(&acc_cfg); + acc_cfg.rtp_cfg = app_config.rtp_cfg; + acc_cfg.ipv6_media_use = PJSUA_IPV6_ENABLED; + pjsua_acc_modify(aid, &acc_cfg); + } + + //pjsua_acc_set_transport(aid, transport_id); + pjsua_acc_set_online_status(current_acc, PJ_TRUE); + + if (app_config.udp_cfg.port == 0) { + pjsua_transport_info ti; + + pjsua_transport_get_info(transport_id, &ti); + tcp_cfg.port = pj_sockaddr_get_port(&ti.local_addr); + } } /* Add TCP transport unless it's disabled */ if (!app_config.no_tcp) { - pjsua_acc_id aid; + pjsua_acc_id aid; - status = pjsua_transport_create(PJSIP_TRANSPORT_TCP, - &tcp_cfg, - &transport_id); - if (status != PJ_SUCCESS) - goto on_error; + status = pjsua_transport_create(PJSIP_TRANSPORT_TCP, + &tcp_cfg, + &transport_id); + if (status != PJ_SUCCESS) + goto on_error; - /* Add local account */ - pjsua_acc_add_local(transport_id, PJ_TRUE, &aid); + /* Add local account */ + pjsua_acc_add_local(transport_id, PJ_TRUE, &aid); - /* Adjust local account config based on pjsua app config */ - { - pjsua_acc_config acc_cfg; - pjsua_acc_get_config(aid, tmp_pool, &acc_cfg); + /* Adjust local account config based on pjsua app config */ + { + pjsua_acc_config acc_cfg; + pjsua_acc_get_config(aid, tmp_pool, &acc_cfg); - app_config_init_video(&acc_cfg); - acc_cfg.rtp_cfg = app_config.rtp_cfg; - pjsua_acc_modify(aid, &acc_cfg); - } + app_config_init_video(&acc_cfg); + acc_cfg.rtp_cfg = app_config.rtp_cfg; + pjsua_acc_modify(aid, &acc_cfg); + } - pjsua_acc_set_online_status(current_acc, PJ_TRUE); + pjsua_acc_set_online_status(current_acc, PJ_TRUE); } /* Add TCP IPv6 transport unless it's disabled. */ if (!app_config.no_tcp && app_config.ipv6) { - pjsua_acc_id aid; - pjsip_transport_type_e type = PJSIP_TRANSPORT_TCP6; + pjsua_acc_id aid; + pjsip_transport_type_e type = PJSIP_TRANSPORT_TCP6; - tcp_cfg.port += 10; + tcp_cfg.port += 10; - status = pjsua_transport_create(type, - &tcp_cfg, - &transport_id); - if (status != PJ_SUCCESS) - goto on_error; + status = pjsua_transport_create(type, + &tcp_cfg, + &transport_id); + if (status != PJ_SUCCESS) + goto on_error; - /* Add local account */ - pjsua_acc_add_local(transport_id, PJ_TRUE, &aid); + /* Add local account */ + pjsua_acc_add_local(transport_id, PJ_TRUE, &aid); - /* Adjust local account config based on pjsua app config */ - { - pjsua_acc_config acc_cfg; - pjsua_acc_get_config(aid, tmp_pool, &acc_cfg); + /* Adjust local account config based on pjsua app config */ + { + pjsua_acc_config acc_cfg; + pjsua_acc_get_config(aid, tmp_pool, &acc_cfg); - app_config_init_video(&acc_cfg); - acc_cfg.rtp_cfg = app_config.rtp_cfg; - acc_cfg.ipv6_media_use = PJSUA_IPV6_ENABLED; - pjsua_acc_modify(aid, &acc_cfg); - } + app_config_init_video(&acc_cfg); + acc_cfg.rtp_cfg = app_config.rtp_cfg; + acc_cfg.ipv6_media_use = PJSUA_IPV6_ENABLED; + pjsua_acc_modify(aid, &acc_cfg); + } - //pjsua_acc_set_transport(aid, transport_id); - pjsua_acc_set_online_status(current_acc, PJ_TRUE); + //pjsua_acc_set_transport(aid, transport_id); + pjsua_acc_set_online_status(current_acc, PJ_TRUE); } @@ -1794,137 +1793,137 @@ static pj_status_t app_init(void) /* Add TLS transport when application wants one */ if (app_config.use_tls) { - pjsua_acc_id acc_id; + pjsua_acc_id acc_id; - /* Copy the QoS settings */ - tcp_cfg.tls_setting.qos_type = tcp_cfg.qos_type; - pj_memcpy(&tcp_cfg.tls_setting.qos_params, &tcp_cfg.qos_params, - sizeof(tcp_cfg.qos_params)); + /* Copy the QoS settings */ + tcp_cfg.tls_setting.qos_type = tcp_cfg.qos_type; + pj_memcpy(&tcp_cfg.tls_setting.qos_params, &tcp_cfg.qos_params, + sizeof(tcp_cfg.qos_params)); - /* Set TLS port as TCP port+1 */ - tcp_cfg.port++; - status = pjsua_transport_create(PJSIP_TRANSPORT_TLS, - &tcp_cfg, - &transport_id); - tcp_cfg.port--; - if (status != PJ_SUCCESS) - goto on_error; - - /* Add local account */ - pjsua_acc_add_local(transport_id, PJ_FALSE, &acc_id); + /* Set TLS port as TCP port+1 */ + tcp_cfg.port++; + status = pjsua_transport_create(PJSIP_TRANSPORT_TLS, + &tcp_cfg, + &transport_id); + tcp_cfg.port--; + if (status != PJ_SUCCESS) + goto on_error; + + /* Add local account */ + pjsua_acc_add_local(transport_id, PJ_FALSE, &acc_id); - /* Adjust local account config based on pjsua app config */ - { - pjsua_acc_config acc_cfg; - pjsua_acc_get_config(acc_id, tmp_pool, &acc_cfg); + /* Adjust local account config based on pjsua app config */ + { + pjsua_acc_config acc_cfg; + pjsua_acc_get_config(acc_id, tmp_pool, &acc_cfg); - app_config_init_video(&acc_cfg); - acc_cfg.rtp_cfg = app_config.rtp_cfg; - pjsua_acc_modify(acc_id, &acc_cfg); - } + app_config_init_video(&acc_cfg); + acc_cfg.rtp_cfg = app_config.rtp_cfg; + pjsua_acc_modify(acc_id, &acc_cfg); + } - pjsua_acc_set_online_status(acc_id, PJ_TRUE); + pjsua_acc_set_online_status(acc_id, PJ_TRUE); } /* Add TLS IPv6 transport unless it's disabled. */ if (app_config.use_tls && app_config.ipv6) { - pjsua_acc_id aid; - pjsip_transport_type_e type = PJSIP_TRANSPORT_TLS6; + pjsua_acc_id aid; + pjsip_transport_type_e type = PJSIP_TRANSPORT_TLS6; - tcp_cfg.port += 10; + tcp_cfg.port += 10; - status = pjsua_transport_create(type, - &tcp_cfg, - &transport_id); - if (status != PJ_SUCCESS) - goto on_error; + status = pjsua_transport_create(type, + &tcp_cfg, + &transport_id); + if (status != PJ_SUCCESS) + goto on_error; - /* Add local account */ - pjsua_acc_add_local(transport_id, PJ_TRUE, &aid); + /* Add local account */ + pjsua_acc_add_local(transport_id, PJ_TRUE, &aid); - /* Adjust local account config based on pjsua app config */ - { - pjsua_acc_config acc_cfg; - pjsua_acc_get_config(aid, tmp_pool, &acc_cfg); + /* Adjust local account config based on pjsua app config */ + { + pjsua_acc_config acc_cfg; + pjsua_acc_get_config(aid, tmp_pool, &acc_cfg); - app_config_init_video(&acc_cfg); - acc_cfg.rtp_cfg = app_config.rtp_cfg; - acc_cfg.ipv6_media_use = PJSUA_IPV6_ENABLED; - pjsua_acc_modify(aid, &acc_cfg); - } + app_config_init_video(&acc_cfg); + acc_cfg.rtp_cfg = app_config.rtp_cfg; + acc_cfg.ipv6_media_use = PJSUA_IPV6_ENABLED; + pjsua_acc_modify(aid, &acc_cfg); + } - //pjsua_acc_set_transport(aid, transport_id); - pjsua_acc_set_online_status(current_acc, PJ_TRUE); + //pjsua_acc_set_transport(aid, transport_id); + pjsua_acc_set_online_status(current_acc, PJ_TRUE); } #endif if (transport_id == -1) { - PJ_LOG(1,(THIS_FILE, "Error: no transport is configured")); - status = -1; - goto on_error; + PJ_LOG(1,(THIS_FILE, "Error: no transport is configured")); + status = -1; + goto on_error; } /* Add accounts */ for (i=0; i 0) { - pj_thread_create(app_config.pool, "stdout", &stdout_refresh_proc, - NULL, 0, 0, &stdout_refresh_thread); + pj_thread_create(app_config.pool, "stdout", &stdout_refresh_proc, + NULL, 0, 0, &stdout_refresh_thread); } status = pjsua_start(); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; if (app_config.use_cli && (app_config.cli_cfg.cli_fe & CLI_FE_TELNET)) { - char info[128]; - cli_get_info(info, sizeof(info)); - if (app_cfg.on_started) { - (*app_cfg.on_started)(status, info); - } + char info[128]; + cli_get_info(info, sizeof(info)); + if (app_cfg.on_started) { + (*app_cfg.on_started)(status, info); + } } else { - if (app_cfg.on_started) { - (*app_cfg.on_started)(status, "Ready"); - } + if (app_cfg.on_started) { + (*app_cfg.on_started)(status, "Ready"); + } } /* If user specifies URI to call, then call the URI */ if (uri_arg.slen) { - pjsua_call_setting_default(&call_opt); - call_opt.aud_cnt = app_config.aud_cnt; - call_opt.vid_cnt = app_config.vid.vid_cnt; + pjsua_call_setting_default(&call_opt); + call_opt.aud_cnt = app_config.aud_cnt; + call_opt.vid_cnt = app_config.vid.vid_cnt; - pjsua_call_make_call(current_acc, &uri_arg, &call_opt, NULL, - NULL, NULL); + pjsua_call_make_call(current_acc, &uri_arg, &call_opt, NULL, + NULL, NULL); } app_running = PJ_TRUE; if (app_config.use_cli) - cli_main(wait_telnet_cli); + cli_main(wait_telnet_cli); else - legacy_main(); + legacy_main(); status = PJ_SUCCESS; on_return: if (stdout_refresh_thread) { - stdout_refresh_quit = PJ_TRUE; - pj_thread_join(stdout_refresh_thread); - pj_thread_destroy(stdout_refresh_thread); - stdout_refresh_quit = PJ_FALSE; + stdout_refresh_quit = PJ_TRUE; + pj_thread_join(stdout_refresh_thread); + pj_thread_destroy(stdout_refresh_thread); + stdout_refresh_quit = PJ_FALSE; } return status; } @@ -2034,73 +2033,73 @@ static pj_status_t app_destroy(void) #ifdef STEREO_DEMO if (app_config.snd) { - pjmedia_snd_port_destroy(app_config.snd); - app_config.snd = NULL; + pjmedia_snd_port_destroy(app_config.snd); + app_config.snd = NULL; } if (app_config.sc_ch1) { - pjsua_conf_remove_port(app_config.sc_ch1_slot); - app_config.sc_ch1_slot = PJSUA_INVALID_ID; - pjmedia_port_destroy(app_config.sc_ch1); - app_config.sc_ch1 = NULL; + pjsua_conf_remove_port(app_config.sc_ch1_slot); + app_config.sc_ch1_slot = PJSUA_INVALID_ID; + pjmedia_port_destroy(app_config.sc_ch1); + app_config.sc_ch1 = NULL; } if (app_config.sc) { - pjmedia_port_destroy(app_config.sc); - app_config.sc = NULL; + pjmedia_port_destroy(app_config.sc); + app_config.sc = NULL; } #endif /* Close avi devs and ports */ for (i=0; iinfo) /* clock rate */, - 2 /* stereo */, - 2 * PJMEDIA_PIA_SPF(&conf->info), - PJMEDIA_PIA_BITS(&conf->info), - 0 /* options */, - &app_config.sc); + PJMEDIA_PIA_SRATE(&conf->info) /* clock rate */, + 2 /* stereo */, + 2 * PJMEDIA_PIA_SPF(&conf->info), + PJMEDIA_PIA_BITS(&conf->info), + 0 /* options */, + &app_config.sc); pj_assert(status == PJ_SUCCESS); /* Connect channel0 (left channel?) to conference port slot0 */ status = pjmedia_splitcomb_set_channel(app_config.sc, 0 /* ch0 */, - 0 /*options*/, - conf); + 0 /*options*/, + conf); pj_assert(status == PJ_SUCCESS); /* Create reverse channel for channel1 (right channel?)... */ status = pjmedia_splitcomb_create_rev_channel(app_config.pool, - app_config.sc, - 1 /* ch1 */, - 0 /* options */, - &app_config.sc_ch1); + app_config.sc, + 1 /* ch1 */, + 0 /* options */, + &app_config.sc_ch1); pj_assert(status == PJ_SUCCESS); /* .. and register it to conference bridge (it would be slot1 * if there's no other devices connected to the bridge) */ status = pjsua_conf_add_port(app_config.pool, app_config.sc_ch1, - &app_config.sc_ch1_slot); + &app_config.sc_ch1_slot); pj_assert(status == PJ_SUCCESS); /* Create sound device */ status = pjmedia_snd_port_create(app_config.pool, -1, -1, - PJMEDIA_PIA_SRATE(&conf->info), - 2 /* stereo */, - 2 * PJMEDIA_PIA_SPF(&conf->info), - PJMEDIA_PIA_BITS(&conf->info), - 0, &app_config.snd); + PJMEDIA_PIA_SRATE(&conf->info), + 2 /* stereo */, + 2 * PJMEDIA_PIA_SPF(&conf->info), + PJMEDIA_PIA_BITS(&conf->info), + 0, &app_config.snd); pj_assert(status == PJ_SUCCESS); diff --git a/pjsip-apps/src/pjsua/pjsua_app.h b/pjsip-apps/src/pjsua/pjsua_app.h index 3c46fd029f..99330e73f2 100644 --- a/pjsip-apps/src/pjsua/pjsua_app.h +++ b/pjsip-apps/src/pjsua/pjsua_app.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -85,4 +84,4 @@ pj_status_t pjsua_app_destroy(void); PJ_END_DECL -#endif /* __PJSUA_APP_H__ */ +#endif /* __PJSUA_APP_H__ */ diff --git a/pjsip-apps/src/pjsua/pjsua_app_cli.c b/pjsip-apps/src/pjsua/pjsua_app_cli.c index b3205134ba..e4b37d6a9b 100644 --- a/pjsip-apps/src/pjsua/pjsua_app_cli.c +++ b/pjsip-apps/src/pjsua/pjsua_app_cli.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -20,141 +19,141 @@ #include "pjsua_app_common.h" -#define THIS_FILE "pjsua_app_cli.c" +#define THIS_FILE "pjsua_app_cli.c" #define CHECK_PJSUA_RUNNING() if (pjsua_get_state()!=PJSUA_STATE_RUNNING) \ - return PJ_EINVALIDOP + return PJ_EINVALIDOP /* CLI command id */ /* level 1 command */ -#define CMD_CALL 100 -#define CMD_PRESENCE 200 -#define CMD_ACCOUNT 300 -#define CMD_MEDIA 400 -#define CMD_CONFIG 500 -#define CMD_VIDEO 600 -#define CMD_SLEEP 700 -#define CMD_ECHO 800 -#define CMD_NETWORK 900 -#define CMD_QUIT 110 -#define CMD_RESTART 120 -#define CMD_HANDLE_IP_CHANGE 130 +#define CMD_CALL 100 +#define CMD_PRESENCE 200 +#define CMD_ACCOUNT 300 +#define CMD_MEDIA 400 +#define CMD_CONFIG 500 +#define CMD_VIDEO 600 +#define CMD_SLEEP 700 +#define CMD_ECHO 800 +#define CMD_NETWORK 900 +#define CMD_QUIT 110 +#define CMD_RESTART 120 +#define CMD_HANDLE_IP_CHANGE 130 /* call level 2 command */ -#define CMD_CALL_NEW ((CMD_CALL*10)+1) -#define CMD_CALL_MULTI ((CMD_CALL*10)+2) -#define CMD_CALL_ANSWER ((CMD_CALL*10)+3) -#define CMD_CALL_HANGUP ((CMD_CALL*10)+4) -#define CMD_CALL_HANGUP_ALL ((CMD_CALL*10)+5) -#define CMD_CALL_HOLD ((CMD_CALL*10)+6) -#define CMD_CALL_REINVITE ((CMD_CALL*10)+7) -#define CMD_CALL_UPDATE ((CMD_CALL*10)+8) -#define CMD_CALL_NEXT ((CMD_CALL*10)+9) -#define CMD_CALL_PREVIOUS ((CMD_CALL*10)+10) -#define CMD_CALL_TRANSFER ((CMD_CALL*10)+11) +#define CMD_CALL_NEW ((CMD_CALL*10)+1) +#define CMD_CALL_MULTI ((CMD_CALL*10)+2) +#define CMD_CALL_ANSWER ((CMD_CALL*10)+3) +#define CMD_CALL_HANGUP ((CMD_CALL*10)+4) +#define CMD_CALL_HANGUP_ALL ((CMD_CALL*10)+5) +#define CMD_CALL_HOLD ((CMD_CALL*10)+6) +#define CMD_CALL_REINVITE ((CMD_CALL*10)+7) +#define CMD_CALL_UPDATE ((CMD_CALL*10)+8) +#define CMD_CALL_NEXT ((CMD_CALL*10)+9) +#define CMD_CALL_PREVIOUS ((CMD_CALL*10)+10) +#define CMD_CALL_TRANSFER ((CMD_CALL*10)+11) #define CMD_CALL_TRANSFER_REPLACE ((CMD_CALL*10)+12) -#define CMD_CALL_REDIRECT ((CMD_CALL*10)+13) -#define CMD_CALL_D2833 ((CMD_CALL*10)+14) -#define CMD_CALL_INFO ((CMD_CALL*10)+15) -#define CMD_CALL_DUMP_Q ((CMD_CALL*10)+16) -#define CMD_CALL_SEND_ARB ((CMD_CALL*10)+17) -#define CMD_CALL_LIST ((CMD_CALL*10)+18) +#define CMD_CALL_REDIRECT ((CMD_CALL*10)+13) +#define CMD_CALL_D2833 ((CMD_CALL*10)+14) +#define CMD_CALL_INFO ((CMD_CALL*10)+15) +#define CMD_CALL_DUMP_Q ((CMD_CALL*10)+16) +#define CMD_CALL_SEND_ARB ((CMD_CALL*10)+17) +#define CMD_CALL_LIST ((CMD_CALL*10)+18) /* im & presence level 2 command */ -#define CMD_PRESENCE_ADD_BUDDY ((CMD_PRESENCE*10)+1) -#define CMD_PRESENCE_DEL_BUDDY ((CMD_PRESENCE*10)+2) -#define CMD_PRESENCE_SEND_IM ((CMD_PRESENCE*10)+3) -#define CMD_PRESENCE_SUB ((CMD_PRESENCE*10)+4) -#define CMD_PRESENCE_UNSUB ((CMD_PRESENCE*10)+5) -#define CMD_PRESENCE_TOG_STATE ((CMD_PRESENCE*10)+6) -#define CMD_PRESENCE_TEXT ((CMD_PRESENCE*10)+7) -#define CMD_PRESENCE_LIST ((CMD_PRESENCE*10)+8) +#define CMD_PRESENCE_ADD_BUDDY ((CMD_PRESENCE*10)+1) +#define CMD_PRESENCE_DEL_BUDDY ((CMD_PRESENCE*10)+2) +#define CMD_PRESENCE_SEND_IM ((CMD_PRESENCE*10)+3) +#define CMD_PRESENCE_SUB ((CMD_PRESENCE*10)+4) +#define CMD_PRESENCE_UNSUB ((CMD_PRESENCE*10)+5) +#define CMD_PRESENCE_TOG_STATE ((CMD_PRESENCE*10)+6) +#define CMD_PRESENCE_TEXT ((CMD_PRESENCE*10)+7) +#define CMD_PRESENCE_LIST ((CMD_PRESENCE*10)+8) /* account level 2 command */ -#define CMD_ACCOUNT_ADD ((CMD_ACCOUNT*10)+1) -#define CMD_ACCOUNT_DEL ((CMD_ACCOUNT*10)+2) -#define CMD_ACCOUNT_MOD ((CMD_ACCOUNT*10)+3) -#define CMD_ACCOUNT_REG ((CMD_ACCOUNT*10)+4) -#define CMD_ACCOUNT_UNREG ((CMD_ACCOUNT*10)+5) -#define CMD_ACCOUNT_NEXT ((CMD_ACCOUNT*10)+6) -#define CMD_ACCOUNT_PREV ((CMD_ACCOUNT*10)+7) -#define CMD_ACCOUNT_SHOW ((CMD_ACCOUNT*10)+8) +#define CMD_ACCOUNT_ADD ((CMD_ACCOUNT*10)+1) +#define CMD_ACCOUNT_DEL ((CMD_ACCOUNT*10)+2) +#define CMD_ACCOUNT_MOD ((CMD_ACCOUNT*10)+3) +#define CMD_ACCOUNT_REG ((CMD_ACCOUNT*10)+4) +#define CMD_ACCOUNT_UNREG ((CMD_ACCOUNT*10)+5) +#define CMD_ACCOUNT_NEXT ((CMD_ACCOUNT*10)+6) +#define CMD_ACCOUNT_PREV ((CMD_ACCOUNT*10)+7) +#define CMD_ACCOUNT_SHOW ((CMD_ACCOUNT*10)+8) /* conference & media level 2 command */ -#define CMD_MEDIA_LIST ((CMD_MEDIA*10)+1) -#define CMD_MEDIA_CONF_CONNECT ((CMD_MEDIA*10)+2) +#define CMD_MEDIA_LIST ((CMD_MEDIA*10)+1) +#define CMD_MEDIA_CONF_CONNECT ((CMD_MEDIA*10)+2) #define CMD_MEDIA_CONF_DISCONNECT ((CMD_MEDIA*10)+3) -#define CMD_MEDIA_ADJUST_VOL ((CMD_MEDIA*10)+4) -#define CMD_MEDIA_CODEC_PRIO ((CMD_MEDIA*10)+5) +#define CMD_MEDIA_ADJUST_VOL ((CMD_MEDIA*10)+4) +#define CMD_MEDIA_CODEC_PRIO ((CMD_MEDIA*10)+5) #define CMD_MEDIA_SPEAKER_TOGGLE ((CMD_MEDIA*10)+6) /* status & config level 2 command */ -#define CMD_CONFIG_DUMP_STAT ((CMD_CONFIG*10)+1) -#define CMD_CONFIG_DUMP_DETAIL ((CMD_CONFIG*10)+2) -#define CMD_CONFIG_DUMP_CONF ((CMD_CONFIG*10)+3) +#define CMD_CONFIG_DUMP_STAT ((CMD_CONFIG*10)+1) +#define CMD_CONFIG_DUMP_DETAIL ((CMD_CONFIG*10)+2) +#define CMD_CONFIG_DUMP_CONF ((CMD_CONFIG*10)+3) #define CMD_CONFIG_WRITE_SETTING ((CMD_CONFIG*10)+4) /* video level 2 command */ -#define CMD_VIDEO_ENABLE ((CMD_VIDEO*10)+1) -#define CMD_VIDEO_DISABLE ((CMD_VIDEO*10)+2) -#define CMD_VIDEO_ACC ((CMD_VIDEO*10)+3) -#define CMD_VIDEO_CALL ((CMD_VIDEO*10)+4) -#define CMD_VIDEO_DEVICE ((CMD_VIDEO*10)+5) -#define CMD_VIDEO_CODEC ((CMD_VIDEO*10)+6) -#define CMD_VIDEO_WIN ((CMD_VIDEO*10)+7) -#define CMD_VIDEO_CONF ((CMD_VIDEO*10)+8) +#define CMD_VIDEO_ENABLE ((CMD_VIDEO*10)+1) +#define CMD_VIDEO_DISABLE ((CMD_VIDEO*10)+2) +#define CMD_VIDEO_ACC ((CMD_VIDEO*10)+3) +#define CMD_VIDEO_CALL ((CMD_VIDEO*10)+4) +#define CMD_VIDEO_DEVICE ((CMD_VIDEO*10)+5) +#define CMD_VIDEO_CODEC ((CMD_VIDEO*10)+6) +#define CMD_VIDEO_WIN ((CMD_VIDEO*10)+7) +#define CMD_VIDEO_CONF ((CMD_VIDEO*10)+8) /* video level 3 command */ -#define CMD_VIDEO_ACC_SHOW ((CMD_VIDEO_ACC*10)+1) -#define CMD_VIDEO_ACC_AUTORX ((CMD_VIDEO_ACC*10)+2) -#define CMD_VIDEO_ACC_AUTOTX ((CMD_VIDEO_ACC*10)+3) -#define CMD_VIDEO_ACC_CAP_ID ((CMD_VIDEO_ACC*10)+4) -#define CMD_VIDEO_ACC_REN_ID ((CMD_VIDEO_ACC*10)+5) -#define CMD_VIDEO_CALL_RX ((CMD_VIDEO_CALL*10)+1) -#define CMD_VIDEO_CALL_TX ((CMD_VIDEO_CALL*10)+2) -#define CMD_VIDEO_CALL_ADD ((CMD_VIDEO_CALL*10)+3) -#define CMD_VIDEO_CALL_ENABLE ((CMD_VIDEO_CALL*10)+4) -#define CMD_VIDEO_CALL_DISABLE ((CMD_VIDEO_CALL*10)+5) -#define CMD_VIDEO_CALL_CAP ((CMD_VIDEO_CALL*10)+6) -#define CMD_VIDEO_DEVICE_LIST ((CMD_VIDEO_DEVICE*10)+1) +#define CMD_VIDEO_ACC_SHOW ((CMD_VIDEO_ACC*10)+1) +#define CMD_VIDEO_ACC_AUTORX ((CMD_VIDEO_ACC*10)+2) +#define CMD_VIDEO_ACC_AUTOTX ((CMD_VIDEO_ACC*10)+3) +#define CMD_VIDEO_ACC_CAP_ID ((CMD_VIDEO_ACC*10)+4) +#define CMD_VIDEO_ACC_REN_ID ((CMD_VIDEO_ACC*10)+5) +#define CMD_VIDEO_CALL_RX ((CMD_VIDEO_CALL*10)+1) +#define CMD_VIDEO_CALL_TX ((CMD_VIDEO_CALL*10)+2) +#define CMD_VIDEO_CALL_ADD ((CMD_VIDEO_CALL*10)+3) +#define CMD_VIDEO_CALL_ENABLE ((CMD_VIDEO_CALL*10)+4) +#define CMD_VIDEO_CALL_DISABLE ((CMD_VIDEO_CALL*10)+5) +#define CMD_VIDEO_CALL_CAP ((CMD_VIDEO_CALL*10)+6) +#define CMD_VIDEO_DEVICE_LIST ((CMD_VIDEO_DEVICE*10)+1) #define CMD_VIDEO_DEVICE_REFRESH ((CMD_VIDEO_DEVICE*10)+2) #define CMD_VIDEO_DEVICE_PREVIEW ((CMD_VIDEO_DEVICE*10)+3) -#define CMD_VIDEO_CODEC_LIST ((CMD_VIDEO_CODEC*10)+1) -#define CMD_VIDEO_CODEC_PRIO ((CMD_VIDEO_CODEC*10)+2) -#define CMD_VIDEO_CODEC_FPS ((CMD_VIDEO_CODEC*10)+3) -#define CMD_VIDEO_CODEC_BITRATE ((CMD_VIDEO_CODEC*10)+4) -#define CMD_VIDEO_CODEC_SIZE ((CMD_VIDEO_CODEC*10)+5) -#define CMD_VIDEO_WIN_LIST ((CMD_VIDEO_WIN*10)+1) -#define CMD_VIDEO_WIN_ARRANGE ((CMD_VIDEO_WIN*10)+2) -#define CMD_VIDEO_WIN_SHOW ((CMD_VIDEO_WIN*10)+3) -#define CMD_VIDEO_WIN_HIDE ((CMD_VIDEO_WIN*10)+4) -#define CMD_VIDEO_WIN_MOVE ((CMD_VIDEO_WIN*10)+5) -#define CMD_VIDEO_WIN_RESIZE ((CMD_VIDEO_WIN*10)+6) -#define CMD_VIDEO_CONF_LIST ((CMD_VIDEO_CONF*10)+1) -#define CMD_VIDEO_CONF_CONNECT ((CMD_VIDEO_CONF*10)+2) +#define CMD_VIDEO_CODEC_LIST ((CMD_VIDEO_CODEC*10)+1) +#define CMD_VIDEO_CODEC_PRIO ((CMD_VIDEO_CODEC*10)+2) +#define CMD_VIDEO_CODEC_FPS ((CMD_VIDEO_CODEC*10)+3) +#define CMD_VIDEO_CODEC_BITRATE ((CMD_VIDEO_CODEC*10)+4) +#define CMD_VIDEO_CODEC_SIZE ((CMD_VIDEO_CODEC*10)+5) +#define CMD_VIDEO_WIN_LIST ((CMD_VIDEO_WIN*10)+1) +#define CMD_VIDEO_WIN_ARRANGE ((CMD_VIDEO_WIN*10)+2) +#define CMD_VIDEO_WIN_SHOW ((CMD_VIDEO_WIN*10)+3) +#define CMD_VIDEO_WIN_HIDE ((CMD_VIDEO_WIN*10)+4) +#define CMD_VIDEO_WIN_MOVE ((CMD_VIDEO_WIN*10)+5) +#define CMD_VIDEO_WIN_RESIZE ((CMD_VIDEO_WIN*10)+6) +#define CMD_VIDEO_CONF_LIST ((CMD_VIDEO_CONF*10)+1) +#define CMD_VIDEO_CONF_CONNECT ((CMD_VIDEO_CONF*10)+2) #define CMD_VIDEO_CONF_DISCONNECT ((CMD_VIDEO_CONF*10)+3) /* dynamic choice argument list */ -#define DYN_CHOICE_START 9900 -#define DYN_CHOICE_BUDDY_ID (DYN_CHOICE_START)+1 -#define DYN_CHOICE_ACCOUNT_ID (DYN_CHOICE_START)+2 -#define DYN_CHOICE_MEDIA_PORT (DYN_CHOICE_START)+3 +#define DYN_CHOICE_START 9900 +#define DYN_CHOICE_BUDDY_ID (DYN_CHOICE_START)+1 +#define DYN_CHOICE_ACCOUNT_ID (DYN_CHOICE_START)+2 +#define DYN_CHOICE_MEDIA_PORT (DYN_CHOICE_START)+3 #define DYN_CHOICE_AUDIO_CODEC_ID (DYN_CHOICE_START)+4 -#define DYN_CHOICE_CAP_DEV_ID (DYN_CHOICE_START)+5 -#define DYN_CHOICE_REN_DEV_ID (DYN_CHOICE_START)+6 -#define DYN_CHOICE_VID_DEV_ID (DYN_CHOICE_START)+7 -#define DYN_CHOICE_STREAM_ID (DYN_CHOICE_START)+8 +#define DYN_CHOICE_CAP_DEV_ID (DYN_CHOICE_START)+5 +#define DYN_CHOICE_REN_DEV_ID (DYN_CHOICE_START)+6 +#define DYN_CHOICE_VID_DEV_ID (DYN_CHOICE_START)+7 +#define DYN_CHOICE_STREAM_ID (DYN_CHOICE_START)+8 #define DYN_CHOICE_VIDEO_CODEC_ID (DYN_CHOICE_START)+9 -#define DYN_CHOICE_WIN_ID (DYN_CHOICE_START)+10 -#define DYN_CHOICE_CALL_ID (DYN_CHOICE_START)+11 +#define DYN_CHOICE_WIN_ID (DYN_CHOICE_START)+10 +#define DYN_CHOICE_CALL_ID (DYN_CHOICE_START)+11 #define DYN_CHOICE_ADDED_BUDDY_ID (DYN_CHOICE_START)+12 -static pj_bool_t pj_inited = PJ_FALSE; -static pj_caching_pool cli_cp; -static pj_bool_t cli_cp_inited = PJ_FALSE; -static pj_cli_t *cli = NULL; -static pj_cli_sess *cli_cons_sess = NULL; -static pj_cli_front_end *telnet_front_end = NULL; +static pj_bool_t pj_inited = PJ_FALSE; +static pj_caching_pool cli_cp; +static pj_bool_t cli_cp_inited = PJ_FALSE; +static pj_cli_t *cli = NULL; +static pj_cli_sess *cli_cons_sess = NULL; +static pj_cli_front_end *telnet_front_end = NULL; #ifdef USE_GUI void displayLog(const char *msg, int len); @@ -170,9 +169,9 @@ PJ_DEF(void) cli_get_info(char *info, pj_size_t size) pj_cli_telnet_get_info(telnet_front_end, &telnet_info); pj_ansi_snprintf(info, size, "Telnet to %.*s:%d", - (int)telnet_info.ip_address.slen, - telnet_info.ip_address.ptr, - telnet_info.port); + (int)telnet_info.ip_address.slen, + telnet_info.ip_address.ptr, + telnet_info.port); } static void cli_log_writer(int level, const char *buffer, int len) @@ -193,14 +192,14 @@ pj_status_t cli_init(void) /* Init PJLIB */ status = pj_init(); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; pj_inited = PJ_TRUE; /* Init PJLIB-UTIL */ status = pjlib_util_init(); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Init CLI */ pj_caching_pool_init(&cli_cp, NULL, 0); @@ -210,30 +209,30 @@ pj_status_t cli_init(void) cfg->title = pj_str("Pjsua CLI Application"); status = pj_cli_create(cfg, &cli); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = cli_setup_command(cli); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Init telnet frontend */ if (app_config.cli_cfg.cli_fe & CLI_FE_TELNET) { - pj_cli_telnet_cfg *fe_cfg = &app_config.cli_cfg.telnet_cfg; + pj_cli_telnet_cfg *fe_cfg = &app_config.cli_cfg.telnet_cfg; - status = pj_cli_telnet_create(cli, fe_cfg, &telnet_front_end); - if (status != PJ_SUCCESS) - goto on_error; + status = pj_cli_telnet_create(cli, fe_cfg, &telnet_front_end); + if (status != PJ_SUCCESS) + goto on_error; } /* Init console frontend */ if (app_config.cli_cfg.cli_fe & CLI_FE_CONSOLE) { - pj_cli_console_cfg *fe_cfg = &app_config.cli_cfg.console_cfg; + pj_cli_console_cfg *fe_cfg = &app_config.cli_cfg.console_cfg; - fe_cfg->quit_command = pj_str("shutdown"); - status = pj_cli_console_create(cli, fe_cfg, - &cli_cons_sess, NULL); - if (status != PJ_SUCCESS) - goto on_error; + fe_cfg->quit_command = pj_str("shutdown"); + status = pj_cli_console_create(cli, fe_cfg, + &cli_cons_sess, NULL); + if (status != PJ_SUCCESS) + goto on_error; } return PJ_SUCCESS; @@ -252,15 +251,15 @@ pj_status_t cli_main(pj_bool_t wait_telnet_cli) pjsua_reconfigure_logging(&app_config.log_cfg); if (app_config.cli_cfg.cli_fe & CLI_FE_CONSOLE) { - /* Main loop for CLI FE console */ - while (!pj_cli_is_quitting(cli)) { - pj_cli_console_process(cli_cons_sess, cmdline, sizeof(cmdline)); - } + /* Main loop for CLI FE console */ + while (!pj_cli_is_quitting(cli)) { + pj_cli_console_process(cli_cons_sess, cmdline, sizeof(cmdline)); + } } else if (wait_telnet_cli) { - /* Just wait for CLI quit */ - while (!pj_cli_is_quitting(cli)) { - pj_thread_sleep(200); - } + /* Just wait for CLI quit */ + while (!pj_cli_is_quitting(cli)) { + pj_thread_sleep(200); + } } return PJ_SUCCESS; @@ -270,28 +269,28 @@ void cli_destroy(void) { /* Destroy CLI, it will automatically destroy any FEs */ if (cli) { - pj_cli_destroy(cli); - cli = NULL; + pj_cli_destroy(cli); + cli = NULL; } /* Destroy CLI caching pool factory */ if (cli_cp_inited) { - pj_caching_pool_destroy(&cli_cp); - cli_cp_inited = PJ_FALSE; + pj_caching_pool_destroy(&cli_cp); + cli_cp_inited = PJ_FALSE; } /* Shutdown PJLIB */ if (pj_inited) { - pj_shutdown(); - pj_inited = PJ_FALSE; + pj_shutdown(); + pj_inited = PJ_FALSE; } } /* Get input URL */ static void get_input_url(char *buf, - pj_size_t len, - pj_cli_cmd_val *cval, - struct input_result *result) + pj_size_t len, + pj_cli_cmd_val *cval, + struct input_result *result) { static const pj_str_t err_invalid_input = {"Invalid input\n", 15}; result->nb_result = PJSUA_APP_NO_NB; @@ -301,58 +300,58 @@ static void get_input_url(char *buf, /* Left trim */ while (pj_isspace(*buf)) { - ++buf; - --len; + ++buf; + --len; } /* Remove trailing newlines */ while (len && (buf[len-1] == '\r' || buf[len-1] == '\n')) - buf[--len] = '\0'; + buf[--len] = '\0'; if (len == 0 || buf[0]=='q') - return; + return; if (pj_isdigit(*buf) || *buf=='-') { - unsigned i; + unsigned i; - if (*buf=='-') - i = 1; - else - i = 0; + if (*buf=='-') + i = 1; + else + i = 0; - for (; isess, err_invalid_input.ptr, - (int)err_invalid_input.slen); - return; - } - } + for (; isess, err_invalid_input.ptr, + (int)err_invalid_input.slen); + return; + } + } - result->nb_result = my_atoi(buf); + result->nb_result = my_atoi(buf); - if (result->nb_result >= 0 && - result->nb_result <= (int)pjsua_get_buddy_count()) - { - return; - } - if (result->nb_result == -1) - return; + if (result->nb_result >= 0 && + result->nb_result <= (int)pjsua_get_buddy_count()) + { + return; + } + if (result->nb_result == -1) + return; - pj_cli_sess_write_msg(cval->sess, err_invalid_input.ptr, - (int)err_invalid_input.slen); - result->nb_result = PJSUA_APP_NO_NB; - return; + pj_cli_sess_write_msg(cval->sess, err_invalid_input.ptr, + (int)err_invalid_input.slen); + result->nb_result = PJSUA_APP_NO_NB; + return; } else { - pj_status_t status; + pj_status_t status; - if ((status=pjsua_verify_url(buf)) != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Invalid URL", status); - return; - } + if ((status=pjsua_verify_url(buf)) != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Invalid URL", status); + return; + } - result->uri_result = buf; + result->uri_result = buf; } } @@ -361,84 +360,84 @@ static void get_input_url(char *buf, static void get_buddy_id(pj_cli_dyn_choice_param *param) { if (param->cnt < param->max_cnt) { - pjsua_buddy_id ids[64]; - int i = 0; - unsigned count = PJ_ARRAY_SIZE(ids); - char data_out[64]; - - pjsua_enum_buddies(ids, &count); - - if (count > 0) { - for (i=0; i<(int)count; ++i) { - pjsua_buddy_info info; - - if (pjsua_buddy_get_info(ids[i], &info) != PJ_SUCCESS) - continue; - - /* Fill buddy id */ - pj_ansi_snprintf(data_out, sizeof(data_out), "%d", ids[i]+1); - pj_strdup2(param->pool, ¶m->choice[param->cnt].value, - data_out); - pj_bzero(data_out, PJ_ARRAY_SIZE(data_out)); - - /* Format & fill description */ - pj_ansi_snprintf(data_out, - sizeof(data_out), - "<%.*s> %.*s", - (int)info.status_text.slen, - info.status_text.ptr, - (int)info.uri.slen, - info.uri.ptr); - - pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, - data_out); - if (++param->cnt >= (param->max_cnt-1)) - break; - } - } - if (param->arg_id == DYN_CHOICE_BUDDY_ID) { - /* Add URL input option */ - pj_ansi_snprintf(data_out, sizeof(data_out), "URL"); - pj_strdup2(param->pool, ¶m->choice[param->cnt].value, data_out); - pj_ansi_snprintf(data_out, sizeof(data_out), "An URL"); - pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, data_out); - ++param->cnt; - } + pjsua_buddy_id ids[64]; + int i = 0; + unsigned count = PJ_ARRAY_SIZE(ids); + char data_out[64]; + + pjsua_enum_buddies(ids, &count); + + if (count > 0) { + for (i=0; i<(int)count; ++i) { + pjsua_buddy_info info; + + if (pjsua_buddy_get_info(ids[i], &info) != PJ_SUCCESS) + continue; + + /* Fill buddy id */ + pj_ansi_snprintf(data_out, sizeof(data_out), "%d", ids[i]+1); + pj_strdup2(param->pool, ¶m->choice[param->cnt].value, + data_out); + pj_bzero(data_out, PJ_ARRAY_SIZE(data_out)); + + /* Format & fill description */ + pj_ansi_snprintf(data_out, + sizeof(data_out), + "<%.*s> %.*s", + (int)info.status_text.slen, + info.status_text.ptr, + (int)info.uri.slen, + info.uri.ptr); + + pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, + data_out); + if (++param->cnt >= (param->max_cnt-1)) + break; + } + } + if (param->arg_id == DYN_CHOICE_BUDDY_ID) { + /* Add URL input option */ + pj_ansi_snprintf(data_out, sizeof(data_out), "URL"); + pj_strdup2(param->pool, ¶m->choice[param->cnt].value, data_out); + pj_ansi_snprintf(data_out, sizeof(data_out), "An URL"); + pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, data_out); + ++param->cnt; + } } } static void get_account_id(pj_cli_dyn_choice_param *param) { if (param->cnt < param->max_cnt) { - char buf[8]; - char buf_out[80]; - pjsua_acc_info info; + char buf[8]; + char buf_out[80]; + pjsua_acc_info info; - pjsua_acc_id acc_ids[16]; - unsigned count = PJ_ARRAY_SIZE(acc_ids); - int i; + pjsua_acc_id acc_ids[16]; + unsigned count = PJ_ARRAY_SIZE(acc_ids); + int i; - pjsua_enum_accs(acc_ids, &count); + pjsua_enum_accs(acc_ids, &count); - for (i=0; i<(int)count; ++i) { - pj_bzero(&buf_out[0], PJ_ARRAY_SIZE(buf_out)); + for (i=0; i<(int)count; ++i) { + pj_bzero(&buf_out[0], PJ_ARRAY_SIZE(buf_out)); - pjsua_acc_get_info(acc_ids[i], &info); + pjsua_acc_get_info(acc_ids[i], &info); - pj_ansi_snprintf(buf_out, - sizeof(buf_out), - "%c%.*s", - (acc_ids[i]==current_acc?'*':' '), - (int)info.acc_uri.slen, - info.acc_uri.ptr); + pj_ansi_snprintf(buf_out, + sizeof(buf_out), + "%c%.*s", + (acc_ids[i]==current_acc?'*':' '), + (int)info.acc_uri.slen, + info.acc_uri.ptr); - pj_bzero(buf, sizeof(buf)); - pj_ansi_snprintf(buf, sizeof(buf), "%d", acc_ids[i]); - pj_strdup2(param->pool, ¶m->choice[param->cnt].value, buf); - pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, buf_out); - if (++param->cnt >= param->max_cnt) - break; - } + pj_bzero(buf, sizeof(buf)); + pj_ansi_snprintf(buf, sizeof(buf), "%d", acc_ids[i]); + pj_strdup2(param->pool, ¶m->choice[param->cnt].value, buf); + pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, buf_out); + if (++param->cnt >= param->max_cnt) + break; + } } } @@ -451,76 +450,76 @@ static void get_media_port(pj_cli_dyn_choice_param *param) pjsua_enum_conf_ports(id, &count); for (i=0; ipool, ¶m->choice[param->cnt].value, slot_id); - - txlist[0] = '\0'; - for (j=0; jpool, ¶m->choice[param->cnt].desc, desc); - if (++param->cnt >= param->max_cnt) - break; + char slot_id[8]; + char desc[512]; + char txlist[256]; + unsigned j; + int len; + pjsua_conf_port_info info; + + pjsua_conf_get_port_info(id[i], &info); + + pj_ansi_snprintf(slot_id, sizeof(slot_id), + "%d", info.slot_id); + pj_strdup2(param->pool, ¶m->choice[param->cnt].value, slot_id); + + txlist[0] = '\0'; + for (j=0; jpool, ¶m->choice[param->cnt].desc, desc); + if (++param->cnt >= param->max_cnt) + break; } } static void get_audio_codec_id(pj_cli_dyn_choice_param *param) { if (param->cnt < param->max_cnt) { - pjsua_codec_info c[32]; - unsigned i, count = PJ_ARRAY_SIZE(c); - char codec_id[64]; - char desc[128]; - pj_str_t all_codec_id = pj_str("*"); - - pjsua_enum_codecs(c, &count); - for (i=0; i<=count; ++i) { - pj_str_t cid; - cid = (i==count?all_codec_id : c[i].codec_id); - - pj_ansi_snprintf(codec_id, sizeof(codec_id), - "%.*s", (int)cid.slen, cid.ptr); - - if (i < count) { - pj_ansi_snprintf(desc, sizeof(desc), - "Audio, prio: %d%s%.*s", - c[i].priority, - c[i].desc.slen ? " - " : "", - (int)c[i].desc.slen, - c[i].desc.ptr); - } else { - pj_ansi_snprintf(desc, sizeof(desc), "Audio (All)"); - } - pj_strdup2(param->pool, ¶m->choice[param->cnt].value, - codec_id); - pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, desc); - if (++param->cnt >= param->max_cnt) - break; - } + pjsua_codec_info c[32]; + unsigned i, count = PJ_ARRAY_SIZE(c); + char codec_id[64]; + char desc[128]; + pj_str_t all_codec_id = pj_str("*"); + + pjsua_enum_codecs(c, &count); + for (i=0; i<=count; ++i) { + pj_str_t cid; + cid = (i==count?all_codec_id : c[i].codec_id); + + pj_ansi_snprintf(codec_id, sizeof(codec_id), + "%.*s", (int)cid.slen, cid.ptr); + + if (i < count) { + pj_ansi_snprintf(desc, sizeof(desc), + "Audio, prio: %d%s%.*s", + c[i].priority, + c[i].desc.slen ? " - " : "", + (int)c[i].desc.slen, + c[i].desc.ptr); + } else { + pj_ansi_snprintf(desc, sizeof(desc), "Audio (All)"); + } + pj_strdup2(param->pool, ¶m->choice[param->cnt].value, + codec_id); + pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, desc); + if (++param->cnt >= param->max_cnt) + break; + } } } @@ -528,212 +527,212 @@ static void get_audio_codec_id(pj_cli_dyn_choice_param *param) static void get_video_stream_id(pj_cli_dyn_choice_param *param) { if (param->cnt < param->max_cnt) { - pjsua_call_info call_info; - - if (current_call != PJSUA_INVALID_ID) { - unsigned i; - pjsua_call_get_info(current_call, &call_info); - for (i=0; ipool, ¶m->choice[param->cnt].value, - med_idx); - - switch (call_info.media[i].status) { - case PJSUA_CALL_MEDIA_NONE: - pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, - "Status:None"); - break; - case PJSUA_CALL_MEDIA_ACTIVE: - pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, - "Status:Active"); - break; - case PJSUA_CALL_MEDIA_LOCAL_HOLD: - pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, - "Status:Local Hold"); - break; - case PJSUA_CALL_MEDIA_REMOTE_HOLD: - pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, - "Status:Remote Hold"); - break; - case PJSUA_CALL_MEDIA_ERROR: - pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, - "Status:Media Error"); - break; - } - if (++param->cnt >= param->max_cnt) - break; - } - } - } + pjsua_call_info call_info; + + if (current_call != PJSUA_INVALID_ID) { + unsigned i; + pjsua_call_get_info(current_call, &call_info); + for (i=0; ipool, ¶m->choice[param->cnt].value, + med_idx); + + switch (call_info.media[i].status) { + case PJSUA_CALL_MEDIA_NONE: + pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, + "Status:None"); + break; + case PJSUA_CALL_MEDIA_ACTIVE: + pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, + "Status:Active"); + break; + case PJSUA_CALL_MEDIA_LOCAL_HOLD: + pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, + "Status:Local Hold"); + break; + case PJSUA_CALL_MEDIA_REMOTE_HOLD: + pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, + "Status:Remote Hold"); + break; + case PJSUA_CALL_MEDIA_ERROR: + pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, + "Status:Media Error"); + break; + } + if (++param->cnt >= param->max_cnt) + break; + } + } + } } } static void get_video_dev_hint(pj_cli_dyn_choice_param *param, - pjmedia_vid_dev_info *vdi, - unsigned vid_dev_id) + pjmedia_vid_dev_info *vdi, + unsigned vid_dev_id) { char desc[128]; char dev_id[8]; pj_ansi_snprintf(dev_id, sizeof(dev_id), - "%d", vid_dev_id); + "%d", vid_dev_id); pj_ansi_snprintf(desc, sizeof(desc), "%s [%s]", - vdi->name, vdi->driver); + vdi->name, vdi->driver); pj_strdup2(param->pool, ¶m->choice[param->cnt].value, - dev_id); + dev_id); pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, - desc); + desc); } static void get_video_dev_id(pj_cli_dyn_choice_param *param, - pj_bool_t all, - pj_bool_t capture) + pj_bool_t all, + pj_bool_t capture) { if (param->cnt < param->max_cnt) { - unsigned i, count; - pjmedia_vid_dev_info vdi; - pj_status_t status; - - count = pjsua_vid_dev_count(); - if (count == 0) { - return; - } - - for (i=0; icnt >= param->max_cnt) - break; - } - } - } + unsigned i, count; + pjmedia_vid_dev_info vdi; + pj_status_t status; + + count = pjsua_vid_dev_count(); + if (count == 0) { + return; + } + + for (i=0; icnt >= param->max_cnt) + break; + } + } + } } } static void get_video_codec_id(pj_cli_dyn_choice_param *param) { if (param->cnt < param->max_cnt) { - pjsua_codec_info ci[32]; - unsigned i, count = PJ_ARRAY_SIZE(ci); - char codec_id[64]; - char desc[128]; - pj_str_t all_codec_id = pj_str("*"); - - pjsua_vid_enum_codecs(ci, &count); - for (i = 0; i <= count; ++i) { - pjmedia_vid_codec_param cp; - pjmedia_video_format_detail *vfd; - pj_status_t status = PJ_SUCCESS; - pj_str_t cur_ci; - - pj_bzero(&cur_ci, sizeof(cur_ci)); - if (i < count) { - status = pjsua_vid_codec_get_param(&ci[i].codec_id, &cp); - if (status != PJ_SUCCESS) - continue; - - cur_ci = ci[i].codec_id; - - } else { - cur_ci = all_codec_id; - } - vfd = pjmedia_format_get_video_format_detail(&cp.enc_fmt, PJ_TRUE); - - pj_ansi_snprintf(codec_id, sizeof(codec_id), - "%.*s", (int)cur_ci.slen, - cur_ci.ptr); - - if (i < count) { - pj_ansi_snprintf(desc, sizeof(desc), - "Video, p[%d], f[%.2f], b[%d/%d], s[%dx%d]", - ci[i].priority, - (vfd->fps.num*1.0 / vfd->fps.denum), - vfd->avg_bps / 1000, vfd->max_bps / 1000, - vfd->size.w, vfd->size.h); - } else { - pj_ansi_snprintf(desc, sizeof(desc), "Video (All)"); - } - - pj_strdup2(param->pool, ¶m->choice[param->cnt].value, - codec_id); - pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, desc); - if (++param->cnt >= param->max_cnt) - break; - } + pjsua_codec_info ci[32]; + unsigned i, count = PJ_ARRAY_SIZE(ci); + char codec_id[64]; + char desc[128]; + pj_str_t all_codec_id = pj_str("*"); + + pjsua_vid_enum_codecs(ci, &count); + for (i = 0; i <= count; ++i) { + pjmedia_vid_codec_param cp; + pjmedia_video_format_detail *vfd; + pj_status_t status = PJ_SUCCESS; + pj_str_t cur_ci; + + pj_bzero(&cur_ci, sizeof(cur_ci)); + if (i < count) { + status = pjsua_vid_codec_get_param(&ci[i].codec_id, &cp); + if (status != PJ_SUCCESS) + continue; + + cur_ci = ci[i].codec_id; + + } else { + cur_ci = all_codec_id; + } + vfd = pjmedia_format_get_video_format_detail(&cp.enc_fmt, PJ_TRUE); + + pj_ansi_snprintf(codec_id, sizeof(codec_id), + "%.*s", (int)cur_ci.slen, + cur_ci.ptr); + + if (i < count) { + pj_ansi_snprintf(desc, sizeof(desc), + "Video, p[%d], f[%.2f], b[%d/%d], s[%dx%d]", + ci[i].priority, + (vfd->fps.num*1.0 / vfd->fps.denum), + vfd->avg_bps / 1000, vfd->max_bps / 1000, + vfd->size.w, vfd->size.h); + } else { + pj_ansi_snprintf(desc, sizeof(desc), "Video (All)"); + } + + pj_strdup2(param->pool, ¶m->choice[param->cnt].value, + codec_id); + pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, desc); + if (++param->cnt >= param->max_cnt) + break; + } } } static void get_video_window_id(pj_cli_dyn_choice_param *param) { if (param->cnt < param->max_cnt) { - pjsua_vid_win_id wids[PJSUA_MAX_VID_WINS]; - unsigned i, cnt = PJ_ARRAY_SIZE(wids); - char win_id[64]; - char desc[128]; + pjsua_vid_win_id wids[PJSUA_MAX_VID_WINS]; + unsigned i, cnt = PJ_ARRAY_SIZE(wids); + char win_id[64]; + char desc[128]; - pjsua_vid_enum_wins(wids, &cnt); + pjsua_vid_enum_wins(wids, &cnt); - for (i = 0; i < cnt; ++i) { - pjsua_vid_win_info wi; + for (i = 0; i < cnt; ++i) { + pjsua_vid_win_info wi; - pjsua_vid_win_get_info(wids[i], &wi); - pj_ansi_snprintf(win_id, sizeof(win_id), "%d", wids[i]); - pj_strdup2(param->pool, ¶m->choice[param->cnt].value, win_id); + pjsua_vid_win_get_info(wids[i], &wi); + pj_ansi_snprintf(win_id, sizeof(win_id), "%d", wids[i]); + pj_strdup2(param->pool, ¶m->choice[param->cnt].value, win_id); - pj_ansi_snprintf(desc, sizeof(desc), - "Show:%c Pos(%d,%d) Size(%dx%d)", - (wi.show?'Y':'N'), wi.pos.x, wi.pos.y, - wi.size.w, wi.size.h); + pj_ansi_snprintf(desc, sizeof(desc), + "Show:%c Pos(%d,%d) Size(%dx%d)", + (wi.show?'Y':'N'), wi.pos.x, wi.pos.y, + wi.size.w, wi.size.h); - pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, desc); - if (++param->cnt >= param->max_cnt) - break; - } + pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, desc); + if (++param->cnt >= param->max_cnt) + break; + } } } static void get_call_id(pj_cli_dyn_choice_param *param) { if (param->cnt < param->max_cnt) { - char call_id[64]; - char desc[128]; - unsigned i, count; - pjsua_call_id ids[PJSUA_MAX_CALLS]; - int call = current_call; + char call_id[64]; + char desc[128]; + unsigned i, count; + pjsua_call_id ids[PJSUA_MAX_CALLS]; + int call = current_call; - count = PJ_ARRAY_SIZE(ids); - pjsua_enum_calls(ids, &count); + count = PJ_ARRAY_SIZE(ids); + pjsua_enum_calls(ids, &count); - if (count > 1) { - for (i=0; i 1) { + for (i=0; ipool, ¶m->choice[param->cnt].value, - call_id); - pj_ansi_snprintf(desc, sizeof(desc), "%.*s [%.*s]", - (int)call_info.remote_info.slen, - call_info.remote_info.ptr, - (int)call_info.state_text.slen, - call_info.state_text.ptr); - pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, desc); - if (++param->cnt >= param->max_cnt) - break; + pjsua_call_get_info(ids[i], &call_info); + pj_ansi_snprintf(call_id, sizeof(call_id), "%d", ids[i]); + pj_strdup2(param->pool, ¶m->choice[param->cnt].value, + call_id); + pj_ansi_snprintf(desc, sizeof(desc), "%.*s [%.*s]", + (int)call_info.remote_info.slen, + call_info.remote_info.ptr, + (int)call_info.state_text.slen, + call_info.state_text.ptr); + pj_strdup2(param->pool, ¶m->choice[param->cnt].desc, desc); + if (++param->cnt >= param->max_cnt) + break; - } - } + } + } } } @@ -744,41 +743,41 @@ static void get_choice_value(pj_cli_dyn_choice_param *param) switch (param->arg_id) { case DYN_CHOICE_BUDDY_ID: case DYN_CHOICE_ADDED_BUDDY_ID: - get_buddy_id(param); - break; + get_buddy_id(param); + break; case DYN_CHOICE_ACCOUNT_ID: - get_account_id(param); - break; + get_account_id(param); + break; case DYN_CHOICE_MEDIA_PORT: - get_media_port(param); - break; + get_media_port(param); + break; case DYN_CHOICE_AUDIO_CODEC_ID: - get_audio_codec_id(param); - break; + get_audio_codec_id(param); + break; #if PJSUA_HAS_VIDEO case DYN_CHOICE_CAP_DEV_ID: case DYN_CHOICE_REN_DEV_ID: case DYN_CHOICE_VID_DEV_ID: - get_video_dev_id(param, - (param->arg_id==DYN_CHOICE_VID_DEV_ID), - (param->arg_id==DYN_CHOICE_CAP_DEV_ID)); - break; + get_video_dev_id(param, + (param->arg_id==DYN_CHOICE_VID_DEV_ID), + (param->arg_id==DYN_CHOICE_CAP_DEV_ID)); + break; case DYN_CHOICE_STREAM_ID: - get_video_stream_id(param); - break; + get_video_stream_id(param); + break; case DYN_CHOICE_VIDEO_CODEC_ID: - get_video_codec_id(param); - break; + get_video_codec_id(param); + break; case DYN_CHOICE_WIN_ID: - get_video_window_id(param); - break; + get_video_window_id(param); + break; case DYN_CHOICE_CALL_ID: - get_call_id(param); - break; + get_call_id(param); + break; #endif default: - param->cnt = 0; - break; + param->cnt = 0; + break; } } @@ -807,7 +806,7 @@ static pj_status_t cmd_add_account(pj_cli_cmd_val *cval) status = pjsua_acc_add(&acc_cfg, PJ_TRUE, NULL); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error adding new account", status); + pjsua_perror(THIS_FILE, "Error adding new account", status); } return status; @@ -822,16 +821,16 @@ static pj_status_t cmd_del_account(pj_cli_cmd_val *cval) int i = my_atoi2(&cval->argv[1]); if (!pjsua_acc_is_valid(i)) { - pj_ansi_snprintf(out_str, sizeof(out_str), - "Invalid account id %d\n", i); - str_len = (unsigned)pj_ansi_strlen(out_str); - pj_cli_sess_write_msg(cval->sess, out_str, str_len); + pj_ansi_snprintf(out_str, sizeof(out_str), + "Invalid account id %d\n", i); + str_len = (unsigned)pj_ansi_strlen(out_str); + pj_cli_sess_write_msg(cval->sess, out_str, str_len); } else { - pjsua_acc_del(i); - pj_ansi_snprintf(out_str, sizeof(out_str), - "Account %d deleted\n", i); - str_len = (unsigned)pj_ansi_strlen(out_str); - pj_cli_sess_write_msg(cval->sess, out_str, str_len); + pjsua_acc_del(i); + pj_ansi_snprintf(out_str, sizeof(out_str), + "Account %d deleted\n", i); + str_len = (unsigned)pj_ansi_strlen(out_str); + pj_cli_sess_write_msg(cval->sess, out_str, str_len); } return PJ_SUCCESS; } @@ -862,10 +861,10 @@ static pj_status_t cmd_next_account(pj_cli_cmd_val *cval) { int i = my_atoi2(&cval->argv[1]); if (pjsua_acc_is_valid(i)) { - pjsua_acc_set_default(i); - PJ_LOG(3,(THIS_FILE, "Current account changed to %d", i)); + pjsua_acc_set_default(i); + PJ_LOG(3,(THIS_FILE, "Current account changed to %d", i)); } else { - PJ_LOG(3,(THIS_FILE, "Invalid account id %d", i)); + PJ_LOG(3,(THIS_FILE, "Invalid account id %d", i)); } return PJ_SUCCESS; } @@ -882,41 +881,41 @@ static pj_status_t cmd_show_account(pj_cli_cmd_val *cval) pj_cli_sess_write_msg(cval->sess, header.ptr, header.slen); for (i=0; i<(int)count; ++i) { - char acc_info[80]; - char out_str[160]; - pjsua_acc_info info; + char acc_info[80]; + char out_str[160]; + pjsua_acc_info info; - pjsua_acc_get_info(acc_ids[i], &info); + pjsua_acc_get_info(acc_ids[i], &info); - if (!info.has_registration) { - pj_ansi_snprintf(acc_info, sizeof(acc_info), "%.*s", - (int)info.status_text.slen, - info.status_text.ptr); + if (!info.has_registration) { + pj_ansi_snprintf(acc_info, sizeof(acc_info), "%.*s", + (int)info.status_text.slen, + info.status_text.ptr); - } else { - pj_ansi_snprintf(acc_info, sizeof(acc_info), - "%d/%.*s (expires=%d)", - info.status, - (int)info.status_text.slen, - info.status_text.ptr, - info.expires); + } else { + pj_ansi_snprintf(acc_info, sizeof(acc_info), + "%d/%.*s (expires=%d)", + info.status, + (int)info.status_text.slen, + info.status_text.ptr, + info.expires); - } + } - pj_ansi_snprintf(out_str, sizeof(out_str), - " %c[%2d] %.*s: %s\n", - (acc_ids[i]==current_acc?'*':' '), acc_ids[i], - (int)info.acc_uri.slen, info.acc_uri.ptr, - acc_info); - pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); + pj_ansi_snprintf(out_str, sizeof(out_str), + " %c[%2d] %.*s: %s\n", + (acc_ids[i]==current_acc?'*':' '), acc_ids[i], + (int)info.acc_uri.slen, info.acc_uri.ptr, + acc_info); + pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); - pj_bzero(out_str, sizeof(out_str)); - pj_ansi_snprintf(out_str, sizeof(out_str), - " Online status: %.*s\n", - (int)info.online_status_text.slen, - info.online_status_text.ptr); + pj_bzero(out_str, sizeof(out_str)); + pj_ansi_snprintf(out_str, sizeof(out_str), + " Online status: %.*s\n", + (int)info.online_status_text.slen, + info.online_status_text.ptr); - pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); + pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); } return PJ_SUCCESS; @@ -931,27 +930,27 @@ pj_status_t cmd_account_handler(pj_cli_cmd_val *cval) switch(pj_cli_get_cmd_id(cval->cmd)) { case CMD_ACCOUNT_ADD: - status = cmd_add_account(cval); - break; + status = cmd_add_account(cval); + break; case CMD_ACCOUNT_DEL: - status = cmd_del_account(cval); - break; + status = cmd_del_account(cval); + break; case CMD_ACCOUNT_MOD: - status = cmd_mod_account(cval); - break; + status = cmd_mod_account(cval); + break; case CMD_ACCOUNT_REG: - status = cmd_reg_account(); - break; + status = cmd_reg_account(); + break; case CMD_ACCOUNT_UNREG: - status = cmd_unreg_account(); - break; + status = cmd_unreg_account(); + break; case CMD_ACCOUNT_NEXT: case CMD_ACCOUNT_PREV: - status = cmd_next_account(cval); - break; + status = cmd_next_account(cval); + break; case CMD_ACCOUNT_SHOW: - status = cmd_show_account(cval); - break; + status = cmd_show_account(cval); + break; } return status; } @@ -966,20 +965,20 @@ static pj_status_t cmd_add_buddy(pj_cli_cmd_val *cval) cval->argv[1].ptr[cval->argv[1].slen] = 0; if (pjsua_verify_url(cval->argv[1].ptr) != PJ_SUCCESS) { - pj_ansi_snprintf(out_str, sizeof(out_str), - "Invalid URI '%s'\n", cval->argv[1].ptr); + pj_ansi_snprintf(out_str, sizeof(out_str), + "Invalid URI '%s'\n", cval->argv[1].ptr); } else { - pj_bzero(&buddy_cfg, sizeof(pjsua_buddy_config)); + pj_bzero(&buddy_cfg, sizeof(pjsua_buddy_config)); - buddy_cfg.uri = pj_str(cval->argv[1].ptr); - buddy_cfg.subscribe = PJ_TRUE; + buddy_cfg.uri = pj_str(cval->argv[1].ptr); + buddy_cfg.subscribe = PJ_TRUE; - status = pjsua_buddy_add(&buddy_cfg, &buddy_id); - if (status == PJ_SUCCESS) { - pj_ansi_snprintf(out_str, sizeof(out_str), - "New buddy '%s' added at index %d\n", - cval->argv[1].ptr, buddy_id+1); - } + status = pjsua_buddy_add(&buddy_cfg, &buddy_id); + if (status == PJ_SUCCESS) { + pj_ansi_snprintf(out_str, sizeof(out_str), + "New buddy '%s' added at index %d\n", + cval->argv[1].ptr, buddy_id+1); + } } pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); return status; @@ -992,12 +991,12 @@ static pj_status_t cmd_del_buddy(pj_cli_cmd_val *cval) char out_str[80]; if (!pjsua_buddy_is_valid(i)) { - pj_ansi_snprintf(out_str, sizeof(out_str), - "Invalid buddy id %d\n", i); + pj_ansi_snprintf(out_str, sizeof(out_str), + "Invalid buddy id %d\n", i); } else { - pjsua_buddy_del(i); - pj_ansi_snprintf(out_str, sizeof(out_str), - "Buddy %d deleted\n", i); + pjsua_buddy_del(i); + pj_ansi_snprintf(out_str, sizeof(out_str), + "Buddy %d deleted\n", i); } pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); return PJ_SUCCESS; @@ -1020,38 +1019,38 @@ static pj_status_t cmd_send_im(pj_cli_cmd_val *cval) get_input_url(tmp.ptr, tmp.slen, cval, &result); if (result.nb_result != PJSUA_APP_NO_NB) { - if (result.nb_result == -1) { - static const pj_str_t err_msg = {"you can't send broadcast im " - "like that!\n", 40 }; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); - return PJ_SUCCESS; - } else if (result.nb_result == 0) { - i = current_call; - } else { - pjsua_buddy_info binfo; - pjsua_buddy_get_info(result.nb_result-1, &binfo); - pj_strncpy_with_null(&tmp, &binfo.uri, sizeof(dest)); - uri = tmp.ptr; - } + if (result.nb_result == -1) { + static const pj_str_t err_msg = {"you can't send broadcast im " + "like that!\n", 40 }; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + return PJ_SUCCESS; + } else if (result.nb_result == 0) { + i = current_call; + } else { + pjsua_buddy_info binfo; + pjsua_buddy_get_info(result.nb_result-1, &binfo); + pj_strncpy_with_null(&tmp, &binfo.uri, sizeof(dest)); + uri = tmp.ptr; + } } else if (result.uri_result) { - uri = result.uri_result; + uri = result.uri_result; } /* send typing indication. */ if (i != -1) - pjsua_call_send_typing_ind(i, PJ_TRUE, NULL); + pjsua_call_send_typing_ind(i, PJ_TRUE, NULL); else { - pj_str_t tmp_uri = pj_str(uri); - pjsua_im_typing(current_acc, &tmp_uri, PJ_TRUE, NULL); + pj_str_t tmp_uri = pj_str(uri); + pjsua_im_typing(current_acc, &tmp_uri, PJ_TRUE, NULL); } /* send the im */ if (i != -1) - pjsua_call_send_im(i, NULL, &cval->argv[2], NULL, NULL); + pjsua_call_send_im(i, NULL, &cval->argv[2], NULL, NULL); else { - pj_str_t tmp_uri = pj_str(uri); - pjsua_im_send(current_acc, &tmp_uri, NULL, &cval->argv[2], NULL, NULL); + pj_str_t tmp_uri = pj_str(uri); + pjsua_im_send(current_acc, &tmp_uri, NULL, &cval->argv[2], NULL, NULL); } return PJ_SUCCESS; } @@ -1066,25 +1065,25 @@ static pj_status_t cmd_subs_pres(pj_cli_cmd_val *cval, pj_bool_t subscribe) pj_strncpy_with_null(&tmp, &cval->argv[1], sizeof(dest)); get_input_url(tmp.ptr, tmp.slen, cval, &result); if (result.nb_result != PJSUA_APP_NO_NB) { - if (result.nb_result == -1) { - int i, count; - count = pjsua_get_buddy_count(); - for (i=0; isess, err_msg.ptr, err_msg.slen); - } else { - pjsua_buddy_subscribe_pres(result.nb_result-1, subscribe); - } + if (result.nb_result == -1) { + int i, count; + count = pjsua_get_buddy_count(); + for (i=0; isess, err_msg.ptr, err_msg.slen); + } else { + pjsua_buddy_subscribe_pres(result.nb_result-1, subscribe); + } } else if (result.uri_result) { - static const pj_str_t err_msg = {"Sorry, can only subscribe to " - "buddy's presence, not arbitrary " - "URL (for now)\n", 76}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + static const pj_str_t err_msg = {"Sorry, can only subscribe to " + "buddy's presence, not arbitrary " + "URL (for now)\n", 76}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); } return PJ_SUCCESS; } @@ -1099,9 +1098,9 @@ static pj_status_t cmd_toggle_state(pj_cli_cmd_val *cval) acc_info.online_status = !acc_info.online_status; pjsua_acc_set_online_status(current_acc, acc_info.online_status); pj_ansi_snprintf(out_str, sizeof(out_str), - "Setting %s online status to %s\n", - acc_info.acc_uri.ptr, - (acc_info.online_status?"online":"offline")); + "Setting %s online status to %s\n", + acc_info.acc_uri.ptr, + (acc_info.online_status?"online":"offline")); pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); return PJ_SUCCESS; } @@ -1114,7 +1113,7 @@ static pj_status_t cmd_set_presence_text(pj_cli_cmd_val *cval) pj_bool_t online_status; enum { - AVAILABLE, BUSY, OTP, IDLE, AWAY, BRB, OFFLINE, OPT_MAX + AVAILABLE, BUSY, OTP, IDLE, AWAY, BRB, OFFLINE, OPT_MAX }; choice = (int)pj_strtol(&cval->argv[1]) - 1; @@ -1126,30 +1125,30 @@ static pj_status_t cmd_set_presence_text(pj_cli_cmd_val *cval) switch (choice) { case AVAILABLE: - break; + break; case BUSY: - elem.activity = PJRPID_ACTIVITY_BUSY; - elem.note = pj_str("Busy"); - break; + elem.activity = PJRPID_ACTIVITY_BUSY; + elem.note = pj_str("Busy"); + break; case OTP: - elem.activity = PJRPID_ACTIVITY_BUSY; - elem.note = pj_str("On the phone"); - break; + elem.activity = PJRPID_ACTIVITY_BUSY; + elem.note = pj_str("On the phone"); + break; case IDLE: - elem.activity = PJRPID_ACTIVITY_UNKNOWN; - elem.note = pj_str("Idle"); - break; + elem.activity = PJRPID_ACTIVITY_UNKNOWN; + elem.note = pj_str("Idle"); + break; case AWAY: - elem.activity = PJRPID_ACTIVITY_AWAY; - elem.note = pj_str("Away"); - break; + elem.activity = PJRPID_ACTIVITY_AWAY; + elem.note = pj_str("Away"); + break; case BRB: - elem.activity = PJRPID_ACTIVITY_UNKNOWN; - elem.note = pj_str("Be right back"); - break; + elem.activity = PJRPID_ACTIVITY_UNKNOWN; + elem.note = pj_str("Be right back"); + break; case OFFLINE: - online_status = PJ_FALSE; - break; + online_status = PJ_FALSE; + break; } pjsua_acc_set_online_status2(current_acc, online_status, &elem); return PJ_SUCCESS; @@ -1169,26 +1168,26 @@ static pj_status_t cmd_show_buddy(pj_cli_cmd_val *cval) pjsua_enum_buddies(ids, &count); if (count == 0) { - pj_ansi_snprintf(out_str, sizeof(out_str), " -none-\n"); - pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); + pj_ansi_snprintf(out_str, sizeof(out_str), " -none-\n"); + pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); } else { - for (i=0; i<(int)count; ++i) { - pjsua_buddy_info info; - pj_bzero(out_str, sizeof(out_str)); + for (i=0; i<(int)count; ++i) { + pjsua_buddy_info info; + pj_bzero(out_str, sizeof(out_str)); - if (pjsua_buddy_get_info(ids[i], &info) != PJ_SUCCESS) - continue; + if (pjsua_buddy_get_info(ids[i], &info) != PJ_SUCCESS) + continue; - pj_ansi_snprintf(out_str, sizeof(out_str), - " [%2d] <%.*s> %.*s\n", - ids[i]+1, - (int)info.status_text.slen, - info.status_text.ptr, - (int)info.uri.slen, - info.uri.ptr); + pj_ansi_snprintf(out_str, sizeof(out_str), + " [%2d] <%.*s> %.*s\n", + ids[i]+1, + (int)info.status_text.slen, + info.status_text.ptr, + (int)info.uri.slen, + info.uri.ptr); - pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); - } + pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); + } } return PJ_SUCCESS; } @@ -1202,28 +1201,28 @@ pj_status_t cmd_presence_handler(pj_cli_cmd_val *cval) switch(pj_cli_get_cmd_id(cval->cmd)) { case CMD_PRESENCE_ADD_BUDDY: - status = cmd_add_buddy(cval); - break; + status = cmd_add_buddy(cval); + break; case CMD_PRESENCE_DEL_BUDDY: - status = cmd_del_buddy(cval); - break; + status = cmd_del_buddy(cval); + break; case CMD_PRESENCE_SEND_IM: - status = cmd_send_im(cval); - break; + status = cmd_send_im(cval); + break; case CMD_PRESENCE_SUB: case CMD_PRESENCE_UNSUB: - status = cmd_subs_pres(cval, - pj_cli_get_cmd_id(cval->cmd)==CMD_PRESENCE_SUB); - break; + status = cmd_subs_pres(cval, + pj_cli_get_cmd_id(cval->cmd)==CMD_PRESENCE_SUB); + break; case CMD_PRESENCE_TOG_STATE: - status = cmd_toggle_state(cval); - break; + status = cmd_toggle_state(cval); + break; case CMD_PRESENCE_TEXT: - status = cmd_set_presence_text(cval); - break; + status = cmd_set_presence_text(cval); + break; case CMD_PRESENCE_LIST: - status = cmd_show_buddy(cval); - break; + status = cmd_show_buddy(cval); + break; } return status; @@ -1242,30 +1241,30 @@ static pj_status_t cmd_media_list(pj_cli_cmd_val *cval) pjsua_enum_conf_ports(id, &count); for (i=0; isess, out_str, pj_ansi_strlen(out_str)); + char out_str[128]; + char txlist[16]; + unsigned j; + pjsua_conf_port_info info; + + pjsua_conf_get_port_info(id[i], &info); + + pj_bzero(txlist, sizeof(txlist)); + for (j=0; jsess, out_str, pj_ansi_strlen(out_str)); } return PJ_SUCCESS; } @@ -1276,18 +1275,18 @@ static pj_status_t cmd_media_connect(pj_cli_cmd_val *cval, pj_bool_t connect) pj_status_t status; if (connect) - status = pjsua_conf_connect((int)pj_strtol(&cval->argv[1]), - (int)pj_strtol(&cval->argv[2])); + status = pjsua_conf_connect((int)pj_strtol(&cval->argv[1]), + (int)pj_strtol(&cval->argv[2])); else - status = pjsua_conf_disconnect((int)pj_strtol(&cval->argv[1]), - (int)pj_strtol(&cval->argv[2])); + status = pjsua_conf_disconnect((int)pj_strtol(&cval->argv[1]), + (int)pj_strtol(&cval->argv[2])); if (status == PJ_SUCCESS) { - static const pj_str_t success_msg = {"Success\n", 9}; - pj_cli_sess_write_msg(cval->sess, success_msg.ptr, success_msg.slen); + static const pj_str_t success_msg = {"Success\n", 9}; + pj_cli_sess_write_msg(cval->sess, success_msg.ptr, success_msg.slen); } else { - static const pj_str_t err_msg = {"ERROR!!\n", 9}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + static const pj_str_t err_msg = {"ERROR!!\n", 9}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); } return status; } @@ -1308,8 +1307,8 @@ static pj_status_t cmd_adjust_vol(pj_cli_cmd_val *cval) pjsua_conf_adjust_rx_level(0, app_config.mic_level); pj_ansi_snprintf(buf, sizeof(buf), - "Adjust mic level: [%4.1fx] -> [%4.1fx]\n", - orig_level, app_config.mic_level); + "Adjust mic level: [%4.1fx] -> [%4.1fx]\n", + orig_level, app_config.mic_level); pj_cli_sess_write_msg(cval->sess, buf, pj_ansi_strlen(buf)); @@ -1320,8 +1319,8 @@ static pj_status_t cmd_adjust_vol(pj_cli_cmd_val *cval) pjsua_conf_adjust_tx_level(0, app_config.speaker_level); pj_ansi_snprintf(buf, sizeof(buf), - "Adjust speaker level: [%4.1fx] -> [%4.1fx]\n", - orig_level, app_config.speaker_level); + "Adjust speaker level: [%4.1fx] -> [%4.1fx]\n", + orig_level, app_config.speaker_level); pj_cli_sess_write_msg(cval->sess, buf, pj_ansi_strlen(buf)); @@ -1336,20 +1335,20 @@ static pj_status_t cmd_set_codec_prio(pj_cli_cmd_val *cval) new_prio = (int)pj_strtol(&cval->argv[2]); if (new_prio < 0) - new_prio = 0; + new_prio = 0; else if (new_prio > PJMEDIA_CODEC_PRIO_HIGHEST) - new_prio = PJMEDIA_CODEC_PRIO_HIGHEST; + new_prio = PJMEDIA_CODEC_PRIO_HIGHEST; status = pjsua_codec_set_priority(&cval->argv[1], - (pj_uint8_t)new_prio); + (pj_uint8_t)new_prio); #if PJSUA_HAS_VIDEO if (status != PJ_SUCCESS) { - status = pjsua_vid_codec_set_priority(&cval->argv[1], - (pj_uint8_t)new_prio); + status = pjsua_vid_codec_set_priority(&cval->argv[1], + (pj_uint8_t)new_prio); } #endif if (status != PJ_SUCCESS) - pjsua_perror(THIS_FILE, "Error setting codec priority", status); + pjsua_perror(THIS_FILE, "Error setting codec priority", status); return status; } @@ -1363,44 +1362,44 @@ pj_status_t cmd_media_handler(pj_cli_cmd_val *cval) switch(pj_cli_get_cmd_id(cval->cmd)) { case CMD_MEDIA_LIST: - status = cmd_media_list(cval); - break; + status = cmd_media_list(cval); + break; case CMD_MEDIA_CONF_CONNECT: case CMD_MEDIA_CONF_DISCONNECT: - status = cmd_media_connect(cval, - pj_cli_get_cmd_id(cval->cmd)==CMD_MEDIA_CONF_CONNECT); - break; + status = cmd_media_connect(cval, + pj_cli_get_cmd_id(cval->cmd)==CMD_MEDIA_CONF_CONNECT); + break; case CMD_MEDIA_ADJUST_VOL: - status = cmd_adjust_vol(cval); - break; + status = cmd_adjust_vol(cval); + break; case CMD_MEDIA_CODEC_PRIO: - status = cmd_set_codec_prio(cval); - break; + status = cmd_set_codec_prio(cval); + break; case CMD_MEDIA_SPEAKER_TOGGLE: - { - static int route = PJMEDIA_AUD_DEV_ROUTE_DEFAULT; - status = pjsua_snd_get_setting(PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, - &route); - if (status != PJ_SUCCESS) { - PJ_PERROR(2, (THIS_FILE, status, - "Warning: unable to retrieve route setting")); - } - - if (route == PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER) - route = PJMEDIA_AUD_DEV_ROUTE_DEFAULT; - else - route = PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; - - PJ_LOG(4,(THIS_FILE, "Setting output route to %s %s", - (route==PJMEDIA_AUD_DEV_ROUTE_DEFAULT? - "default" : "loudspeaker"), - (status? "anyway" : ""))); - - status = pjsua_snd_set_setting(PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, - &route, PJ_TRUE); - PJ_PERROR(4,(THIS_FILE, status, "Result")); - } - break; + { + static int route = PJMEDIA_AUD_DEV_ROUTE_DEFAULT; + status = pjsua_snd_get_setting(PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, + &route); + if (status != PJ_SUCCESS) { + PJ_PERROR(2, (THIS_FILE, status, + "Warning: unable to retrieve route setting")); + } + + if (route == PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER) + route = PJMEDIA_AUD_DEV_ROUTE_DEFAULT; + else + route = PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; + + PJ_LOG(4,(THIS_FILE, "Setting output route to %s %s", + (route==PJMEDIA_AUD_DEV_ROUTE_DEFAULT? + "default" : "loudspeaker"), + (status? "anyway" : ""))); + + status = pjsua_snd_set_setting(PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, + &route, PJ_TRUE); + PJ_PERROR(4,(THIS_FILE, status, "Result")); + } + break; } return status; @@ -1420,11 +1419,11 @@ static pj_status_t cmd_show_config() len = write_settings(&app_config, settings, sizeof(settings)); if (len < 1) - PJ_LOG(1,(THIS_FILE, "Error: not enough buffer")); + PJ_LOG(1,(THIS_FILE, "Error: not enough buffer")); else - PJ_LOG(3,(THIS_FILE, - "Dumping configuration (%d bytes):\n%s\n", - len, settings)); + PJ_LOG(3,(THIS_FILE, + "Dumping configuration (%d bytes):\n%s\n", + len, settings)); return PJ_SUCCESS; } @@ -1440,25 +1439,25 @@ static pj_status_t cmd_write_config(pj_cli_cmd_val *cval) len = write_settings(&app_config, settings, sizeof(settings)); if (len < 1) - PJ_LOG(1,(THIS_FILE, "Error: not enough buffer")); + PJ_LOG(1,(THIS_FILE, "Error: not enough buffer")); else { - pj_oshandle_t fd; - pj_status_t status; + pj_oshandle_t fd; + pj_status_t status; - status = pj_file_open(app_config.pool, buf, PJ_O_WRONLY, &fd); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to open file", status); - } else { - char out_str[256]; - pj_ssize_t size = len; - pj_file_write(fd, settings, &size); - pj_file_close(fd); + status = pj_file_open(app_config.pool, buf, PJ_O_WRONLY, &fd); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to open file", status); + } else { + char out_str[256]; + pj_ssize_t size = len; + pj_file_write(fd, settings, &size); + pj_file_close(fd); - pj_ansi_snprintf(out_str, sizeof(out_str), - "Settings successfully written to '%s'\n", buf); + pj_ansi_snprintf(out_str, sizeof(out_str), + "Settings successfully written to '%s'\n", buf); - pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); - } + pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); + } } return PJ_SUCCESS; @@ -1473,17 +1472,17 @@ pj_status_t cmd_config_handler(pj_cli_cmd_val *cval) switch(pj_cli_get_cmd_id(cval->cmd)) { case CMD_CONFIG_DUMP_STAT: - status = cmd_stat_dump(PJ_FALSE); - break; + status = cmd_stat_dump(PJ_FALSE); + break; case CMD_CONFIG_DUMP_DETAIL: - status = cmd_stat_dump(PJ_TRUE); - break; + status = cmd_stat_dump(PJ_TRUE); + break; case CMD_CONFIG_DUMP_CONF: - status = cmd_show_config(); - break; + status = cmd_show_config(); + break; case CMD_CONFIG_WRITE_SETTING: - status = cmd_write_config(cval); - break; + status = cmd_write_config(cval); + break; } return status; @@ -1500,34 +1499,34 @@ static pj_status_t cmd_make_single_call(pj_cli_cmd_val *cval) pj_strncpy_with_null(&tmp, &cval->argv[1], sizeof(dest)); pj_ansi_snprintf(out_str, - sizeof(out_str), - "(You currently have %d calls)\n", - pjsua_call_get_count()); + sizeof(out_str), + "(You currently have %d calls)\n", + pjsua_call_get_count()); pj_cli_sess_write_msg(cval->sess, out_str, pj_ansi_strlen(out_str)); /* input destination. */ get_input_url(tmp.ptr, tmp.slen, cval, &result); if (result.nb_result != PJSUA_APP_NO_NB) { - pjsua_buddy_info binfo; - if (result.nb_result == -1 || result.nb_result == 0) { - static const pj_str_t err_msg = - {"You can't do that with make call!\n", 35}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); - return PJ_SUCCESS; - } - pjsua_buddy_get_info(result.nb_result-1, &binfo); - pj_strncpy(&tmp, &binfo.uri, sizeof(dest)); + pjsua_buddy_info binfo; + if (result.nb_result == -1 || result.nb_result == 0) { + static const pj_str_t err_msg = + {"You can't do that with make call!\n", 35}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + return PJ_SUCCESS; + } + pjsua_buddy_get_info(result.nb_result-1, &binfo); + pj_strncpy(&tmp, &binfo.uri, sizeof(dest)); } else if (result.uri_result) { - tmp = pj_str(result.uri_result); + tmp = pj_str(result.uri_result); } else { - tmp.slen = 0; + tmp.slen = 0; } pjsua_msg_data_init(&msg_data); TEST_MULTIPART(&msg_data); pjsua_call_make_call(current_acc, &tmp, &call_opt, NULL, - &msg_data, ¤t_call); + &msg_data, ¤t_call); return PJ_SUCCESS; } @@ -1541,39 +1540,39 @@ static pj_status_t cmd_make_multi_call(pj_cli_cmd_val *cval) pj_str_t tmp = pj_str(dest); pj_ansi_snprintf(out_str, - sizeof(out_str), - "(You currently have %d calls)\n", - pjsua_call_get_count()); + sizeof(out_str), + "(You currently have %d calls)\n", + pjsua_call_get_count()); count = (int)pj_strtol(&cval->argv[1]); if (count < 1) - return PJ_SUCCESS; + return PJ_SUCCESS; pj_strncpy_with_null(&tmp, &cval->argv[2], sizeof(dest)); /* input destination. */ get_input_url(tmp.ptr, tmp.slen, cval, &result); if (result.nb_result != PJSUA_APP_NO_NB) { - pjsua_buddy_info binfo; - if (result.nb_result == -1 || result.nb_result == 0) { - static const pj_str_t err_msg = - {"You can't do that with make call!\n", 35}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); - return PJ_SUCCESS; - } - pjsua_buddy_get_info(result.nb_result-1, &binfo); - pj_strncpy(&tmp, &binfo.uri, sizeof(dest)); + pjsua_buddy_info binfo; + if (result.nb_result == -1 || result.nb_result == 0) { + static const pj_str_t err_msg = + {"You can't do that with make call!\n", 35}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + return PJ_SUCCESS; + } + pjsua_buddy_get_info(result.nb_result-1, &binfo); + pj_strncpy(&tmp, &binfo.uri, sizeof(dest)); } else { - tmp = pj_str(result.uri_result); + tmp = pj_str(result.uri_result); } for (i=0; i= PJSIP_INV_STATE_CONNECTING) + call_info.role != PJSIP_ROLE_UAS || + call_info.state >= PJSIP_INV_STATE_CONNECTING) { - static const pj_str_t err_msg = {"No pending incoming call\n", 26}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + static const pj_str_t err_msg = {"No pending incoming call\n", 26}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); } else { - int st_code; - char contact[120]; - pj_str_t hname = { "Contact", 7 }; - pj_str_t hvalue; - pjsip_generic_string_hdr hcontact; - - st_code = (int)pj_strtol(&cval->argv[1]); - if ((st_code < 100) || (st_code > 699)) - return PJ_SUCCESS; - - pjsua_msg_data_init(&msg_data); - - if (st_code/100 == 3) { - if (cval->argc < 3) { - static const pj_str_t err_msg = {"Enter URL to be put " - "in Contact\n", 32}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); - return PJ_SUCCESS; - } - - hvalue = pj_str(contact); - pjsip_generic_string_hdr_init2(&hcontact, &hname, &hvalue); - - pj_list_push_back(&msg_data.hdr_list, &hcontact); - } - - /* - * Must check again! - * Call may have been disconnected while we're waiting for - * keyboard input. - */ - if (current_call == PJSUA_INVALID_ID) { - static const pj_str_t err_msg = {"Call has been disconnected\n", - 28}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); - } - - pjsua_call_answer2(current_call, &call_opt, st_code, NULL, &msg_data); + int st_code; + char contact[120]; + pj_str_t hname = { "Contact", 7 }; + pj_str_t hvalue; + pjsip_generic_string_hdr hcontact; + + st_code = (int)pj_strtol(&cval->argv[1]); + if ((st_code < 100) || (st_code > 699)) + return PJ_SUCCESS; + + pjsua_msg_data_init(&msg_data); + + if (st_code/100 == 3) { + if (cval->argc < 3) { + static const pj_str_t err_msg = {"Enter URL to be put " + "in Contact\n", 32}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + return PJ_SUCCESS; + } + + hvalue = pj_str(contact); + pjsip_generic_string_hdr_init2(&hcontact, &hname, &hvalue); + + pj_list_push_back(&msg_data.hdr_list, &hcontact); + } + + /* + * Must check again! + * Call may have been disconnected while we're waiting for + * keyboard input. + */ + if (current_call == PJSUA_INVALID_ID) { + static const pj_str_t err_msg = {"Call has been disconnected\n", + 28}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + } + + pjsua_call_answer2(current_call, &call_opt, st_code, NULL, &msg_data); } return PJ_SUCCESS; } @@ -1645,13 +1644,13 @@ static pj_status_t cmd_answer_call(pj_cli_cmd_val *cval) static pj_status_t cmd_hangup_call(pj_cli_cmd_val *cval, pj_bool_t all) { if (current_call == PJSUA_INVALID_ID) { - static const pj_str_t err_msg = {"No current call\n", 17}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + static const pj_str_t err_msg = {"No current call\n", 17}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); } else { - if (all) - pjsua_call_hangup_all(); - else - pjsua_call_hangup(current_call, 0, NULL, NULL); + if (all) + pjsua_call_hangup_all(); + else + pjsua_call_hangup(current_call, 0, NULL, NULL); } return PJ_SUCCESS; } @@ -1660,10 +1659,10 @@ static pj_status_t cmd_hangup_call(pj_cli_cmd_val *cval, pj_bool_t all) static pj_status_t cmd_hold_call() { if (current_call != PJSUA_INVALID_ID) { - pjsua_call_set_hold(current_call, NULL); + pjsua_call_set_hold(current_call, NULL); } else { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } return PJ_SUCCESS; } @@ -1672,14 +1671,14 @@ static pj_status_t cmd_hold_call() static pj_status_t cmd_call_reinvite() { if (current_call != PJSUA_INVALID_ID) { - /* - * re-INVITE - */ - call_opt.flag |= PJSUA_CALL_UNHOLD; - pjsua_call_reinvite2(current_call, &call_opt, NULL); + /* + * re-INVITE + */ + call_opt.flag |= PJSUA_CALL_UNHOLD; + pjsua_call_reinvite2(current_call, &call_opt, NULL); } else { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } return PJ_SUCCESS; } @@ -1688,9 +1687,9 @@ static pj_status_t cmd_call_reinvite() static pj_status_t cmd_call_update() { if (current_call != PJSUA_INVALID_ID) { - pjsua_call_update2(current_call, &call_opt, NULL); + pjsua_call_update2(current_call, &call_opt, NULL); } else { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } return PJ_SUCCESS; } @@ -1702,21 +1701,21 @@ static pj_status_t cmd_next_call(pj_bool_t next) * Cycle next/prev dialog. */ if (next) { - find_next_call(); + find_next_call(); } else { - find_prev_call(); + find_prev_call(); } if (current_call != PJSUA_INVALID_ID) { - pjsua_call_info call_info; + pjsua_call_info call_info; - pjsua_call_get_info(current_call, &call_info); - PJ_LOG(3,(THIS_FILE,"Current dialog: %.*s", - (int)call_info.remote_info.slen, - call_info.remote_info.ptr)); + pjsua_call_get_info(current_call, &call_info); + PJ_LOG(3,(THIS_FILE,"Current dialog: %.*s", + (int)call_info.remote_info.slen, + call_info.remote_info.ptr)); } else { - PJ_LOG(3,(THIS_FILE,"No current dialog")); + PJ_LOG(3,(THIS_FILE,"No current dialog")); } return PJ_SUCCESS; } @@ -1726,61 +1725,61 @@ static pj_status_t cmd_transfer_call(pj_cli_cmd_val *cval) { if (current_call == PJSUA_INVALID_ID) { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } else { - char out_str[64]; - int call = current_call; - char dest[64] = {0}; - pj_str_t tmp = pj_str(dest); - struct input_result result; - pjsip_generic_string_hdr refer_sub; - pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 }; - pj_str_t STR_FALSE = { "false", 5 }; - pjsua_call_info ci; - - pj_strncpy_with_null(&tmp, &cval->argv[1], sizeof(dest)); - - pjsua_call_get_info(current_call, &ci); - pj_ansi_snprintf(out_str, - sizeof(out_str), - "Transferring current call [%d] %.*s\n", - current_call, - (int)ci.remote_info.slen, - ci.remote_info.ptr); - - get_input_url(tmp.ptr, tmp.slen, cval, &result); - - /* Check if call is still there. */ - - if (call != current_call) { - puts("Call has been disconnected"); - return PJ_SUCCESS; - } - - pjsua_msg_data_init(&msg_data); - if (app_config.no_refersub) { - /* Add Refer-Sub: false in outgoing REFER request */ - pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB, - &STR_FALSE); - pj_list_push_back(&msg_data.hdr_list, &refer_sub); - } - if (result.nb_result != PJSUA_APP_NO_NB) { - if (result.nb_result == -1 || result.nb_result == 0) { - static const pj_str_t err_msg = {"You can't do that with " - "transfer call!\n", 39}; - - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); - } else { - pjsua_buddy_info binfo; - pjsua_buddy_get_info(result.nb_result-1, &binfo); - pjsua_call_xfer( current_call, &binfo.uri, &msg_data); - } - } else if (result.uri_result) { - pj_str_t tmp2; - tmp2 = pj_str(result.uri_result); - pjsua_call_xfer( current_call, &tmp2, &msg_data); - } + char out_str[64]; + int call = current_call; + char dest[64] = {0}; + pj_str_t tmp = pj_str(dest); + struct input_result result; + pjsip_generic_string_hdr refer_sub; + pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 }; + pj_str_t STR_FALSE = { "false", 5 }; + pjsua_call_info ci; + + pj_strncpy_with_null(&tmp, &cval->argv[1], sizeof(dest)); + + pjsua_call_get_info(current_call, &ci); + pj_ansi_snprintf(out_str, + sizeof(out_str), + "Transferring current call [%d] %.*s\n", + current_call, + (int)ci.remote_info.slen, + ci.remote_info.ptr); + + get_input_url(tmp.ptr, tmp.slen, cval, &result); + + /* Check if call is still there. */ + + if (call != current_call) { + puts("Call has been disconnected"); + return PJ_SUCCESS; + } + + pjsua_msg_data_init(&msg_data); + if (app_config.no_refersub) { + /* Add Refer-Sub: false in outgoing REFER request */ + pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB, + &STR_FALSE); + pj_list_push_back(&msg_data.hdr_list, &refer_sub); + } + if (result.nb_result != PJSUA_APP_NO_NB) { + if (result.nb_result == -1 || result.nb_result == 0) { + static const pj_str_t err_msg = {"You can't do that with " + "transfer call!\n", 39}; + + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + } else { + pjsua_buddy_info binfo; + pjsua_buddy_get_info(result.nb_result-1, &binfo); + pjsua_call_xfer( current_call, &binfo.uri, &msg_data); + } + } else if (result.uri_result) { + pj_str_t tmp2; + tmp2 = pj_str(result.uri_result); + pjsua_call_xfer( current_call, &tmp2, &msg_data); + } } return PJ_SUCCESS; } @@ -1789,76 +1788,76 @@ static pj_status_t cmd_transfer_call(pj_cli_cmd_val *cval) static pj_status_t cmd_transfer_replace_call(pj_cli_cmd_val *cval) { if (current_call == -1) { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } else { - int call = current_call; - int dst_call; - pjsip_generic_string_hdr refer_sub; - pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 }; - pj_str_t STR_FALSE = { "false", 5 }; - pjsua_call_id ids[PJSUA_MAX_CALLS]; - pjsua_msg_data msg_data_; - unsigned count; - static const pj_str_t err_invalid_num = - {"Invalid destination call number\n", 32 }; - count = PJ_ARRAY_SIZE(ids); - pjsua_enum_calls(ids, &count); - - if (count <= 1) { - static const pj_str_t err_no_other_call = - {"There are no other calls\n", 25}; - - pj_cli_sess_write_msg(cval->sess, err_no_other_call.ptr, - err_no_other_call.slen); - return PJ_SUCCESS; - } - - dst_call = my_atoi2(&cval->argv[1]); - - /* Check if call is still there. */ - if (call != current_call) { - static pj_str_t err_call_dc = - {"Call has been disconnected\n", 27}; - - pj_cli_sess_write_msg(cval->sess, err_call_dc.ptr, - err_call_dc.slen); - return PJ_SUCCESS; - } - - /* Check that destination call is valid. */ - if (dst_call == call) { - static pj_str_t err_same_num = - {"Destination call number must not be the " - "same as the call being transferred\n", 74}; - - pj_cli_sess_write_msg(cval->sess, err_same_num.ptr, - err_same_num.slen); - return PJ_SUCCESS; - } - - if (dst_call >= PJSUA_MAX_CALLS) { - pj_cli_sess_write_msg(cval->sess, err_invalid_num.ptr, - err_invalid_num.slen); - return PJ_SUCCESS; - } - - if (!pjsua_call_is_active(dst_call)) { - pj_cli_sess_write_msg(cval->sess, err_invalid_num.ptr, - err_invalid_num.slen); - return PJ_SUCCESS; - } - - pjsua_msg_data_init(&msg_data_); - if (app_config.no_refersub) { - /* Add Refer-Sub: false in outgoing REFER request */ - pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB, - &STR_FALSE); - pj_list_push_back(&msg_data_.hdr_list, &refer_sub); - } - - pjsua_call_xfer_replaces(call, dst_call, - PJSUA_XFER_NO_REQUIRE_REPLACES, - &msg_data_); + int call = current_call; + int dst_call; + pjsip_generic_string_hdr refer_sub; + pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 }; + pj_str_t STR_FALSE = { "false", 5 }; + pjsua_call_id ids[PJSUA_MAX_CALLS]; + pjsua_msg_data msg_data_; + unsigned count; + static const pj_str_t err_invalid_num = + {"Invalid destination call number\n", 32 }; + count = PJ_ARRAY_SIZE(ids); + pjsua_enum_calls(ids, &count); + + if (count <= 1) { + static const pj_str_t err_no_other_call = + {"There are no other calls\n", 25}; + + pj_cli_sess_write_msg(cval->sess, err_no_other_call.ptr, + err_no_other_call.slen); + return PJ_SUCCESS; + } + + dst_call = my_atoi2(&cval->argv[1]); + + /* Check if call is still there. */ + if (call != current_call) { + static pj_str_t err_call_dc = + {"Call has been disconnected\n", 27}; + + pj_cli_sess_write_msg(cval->sess, err_call_dc.ptr, + err_call_dc.slen); + return PJ_SUCCESS; + } + + /* Check that destination call is valid. */ + if (dst_call == call) { + static pj_str_t err_same_num = + {"Destination call number must not be the " + "same as the call being transferred\n", 74}; + + pj_cli_sess_write_msg(cval->sess, err_same_num.ptr, + err_same_num.slen); + return PJ_SUCCESS; + } + + if (dst_call >= PJSUA_MAX_CALLS) { + pj_cli_sess_write_msg(cval->sess, err_invalid_num.ptr, + err_invalid_num.slen); + return PJ_SUCCESS; + } + + if (!pjsua_call_is_active(dst_call)) { + pj_cli_sess_write_msg(cval->sess, err_invalid_num.ptr, + err_invalid_num.slen); + return PJ_SUCCESS; + } + + pjsua_msg_data_init(&msg_data_); + if (app_config.no_refersub) { + /* Add Refer-Sub: false in outgoing REFER request */ + pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB, + &STR_FALSE); + pj_list_push_back(&msg_data_.hdr_list, &refer_sub); + } + + pjsua_call_xfer_replaces(call, dst_call, + PJSUA_XFER_NO_REQUIRE_REPLACES, + &msg_data_); } return PJ_SUCCESS; } @@ -1866,32 +1865,32 @@ static pj_status_t cmd_transfer_replace_call(pj_cli_cmd_val *cval) static pj_status_t cmd_redirect_call(pj_cli_cmd_val *cval) { if (current_call == PJSUA_INVALID_ID) { - PJ_LOG(3,(THIS_FILE, "No current call")); - return PJ_SUCCESS; + PJ_LOG(3,(THIS_FILE, "No current call")); + return PJ_SUCCESS; } if (!pjsua_call_is_active(current_call)) { - PJ_LOG(1,(THIS_FILE, "Call %d has gone", current_call)); + PJ_LOG(1,(THIS_FILE, "Call %d has gone", current_call)); } else { - enum { - ACCEPT_REPLACE, ACCEPT, REJECT, STOP - }; - int choice = (int)pj_strtol(&cval->argv[1]); - - switch (choice) { - case ACCEPT_REPLACE: - pjsua_call_process_redirect(current_call, - PJSIP_REDIRECT_ACCEPT_REPLACE); - break; - case ACCEPT: - pjsua_call_process_redirect(current_call, PJSIP_REDIRECT_ACCEPT); - break; - case REJECT: - pjsua_call_process_redirect(current_call, PJSIP_REDIRECT_REJECT); - break; - default: - pjsua_call_process_redirect(current_call, PJSIP_REDIRECT_STOP); - break; - } + enum { + ACCEPT_REPLACE, ACCEPT, REJECT, STOP + }; + int choice = (int)pj_strtol(&cval->argv[1]); + + switch (choice) { + case ACCEPT_REPLACE: + pjsua_call_process_redirect(current_call, + PJSIP_REDIRECT_ACCEPT_REPLACE); + break; + case ACCEPT: + pjsua_call_process_redirect(current_call, PJSIP_REDIRECT_ACCEPT); + break; + case REJECT: + pjsua_call_process_redirect(current_call, PJSIP_REDIRECT_REJECT); + break; + default: + pjsua_call_process_redirect(current_call, PJSIP_REDIRECT_STOP); + break; + } } return PJ_SUCCESS; } @@ -1901,31 +1900,31 @@ static pj_status_t cmd_dtmf_2833(pj_cli_cmd_val *cval) { if (current_call == PJSUA_INVALID_ID) { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } else if (!pjsua_call_has_media(current_call)) { - PJ_LOG(3,(THIS_FILE, "Media is not established yet!")); + PJ_LOG(3,(THIS_FILE, "Media is not established yet!")); } else { - int call = current_call; - pj_status_t status; - - if (call != current_call) { - static const pj_str_t err_msg = {"Call has been disconnected\n", - 28}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); - return PJ_SUCCESS;; - } - - status = pjsua_call_dial_dtmf(current_call, &cval->argv[1]); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send DTMF", status); - } else { - static const pj_str_t msg = {"DTMF digits enqueued " - "for transmission\n", 39}; - pj_cli_sess_write_msg(cval->sess, msg.ptr, msg.slen); - } + int call = current_call; + pj_status_t status; + + if (call != current_call) { + static const pj_str_t err_msg = {"Call has been disconnected\n", + 28}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + return PJ_SUCCESS;; + } + + status = pjsua_call_dial_dtmf(current_call, &cval->argv[1]); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to send DTMF", status); + } else { + static const pj_str_t msg = {"DTMF digits enqueued " + "for transmission\n", 39}; + pj_cli_sess_write_msg(cval->sess, msg.ptr, msg.slen); + } } return PJ_SUCCESS; } @@ -1935,41 +1934,41 @@ static pj_status_t cmd_call_info(pj_cli_cmd_val *cval) { if (current_call == PJSUA_INVALID_ID) { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } else { - const pj_str_t SIP_INFO = pj_str("INFO"); - int call = current_call; - int i; - pj_status_t status; - - if (call != current_call) { - static const pj_str_t err_msg = {"Call has been disconnected\n", - 28}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); - return PJ_SUCCESS;; - } - - for (i=0; iargv[1].slen; ++i) { - char body[64]; - - pjsua_msg_data_init(&msg_data); - msg_data.content_type = pj_str("application/dtmf-relay"); - - pj_ansi_snprintf(body, - sizeof(body), - "Signal=%c\n" - "Duration=160", - cval->argv[1].ptr[i]); - - msg_data.msg_body = pj_str(body); - - status = pjsua_call_send_request(current_call, &SIP_INFO, - &msg_data); - if (status != PJ_SUCCESS) { - break; - } - } + const pj_str_t SIP_INFO = pj_str("INFO"); + int call = current_call; + int i; + pj_status_t status; + + if (call != current_call) { + static const pj_str_t err_msg = {"Call has been disconnected\n", + 28}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + return PJ_SUCCESS;; + } + + for (i=0; iargv[1].slen; ++i) { + char body[64]; + + pjsua_msg_data_init(&msg_data); + msg_data.content_type = pj_str("application/dtmf-relay"); + + pj_ansi_snprintf(body, + sizeof(body), + "Signal=%c\n" + "Duration=160", + cval->argv[1].ptr[i]); + + msg_data.msg_body = pj_str(body); + + status = pjsua_call_send_request(current_call, &SIP_INFO, + &msg_data); + if (status != PJ_SUCCESS) { + break; + } + } } return PJ_SUCCESS; } @@ -1978,9 +1977,9 @@ static pj_status_t cmd_call_info(pj_cli_cmd_val *cval) static pj_status_t cmd_call_quality() { if (current_call != PJSUA_INVALID_ID) { - log_call_dump(current_call); + log_call_dump(current_call); } else { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } return PJ_SUCCESS; } @@ -1989,65 +1988,65 @@ static pj_status_t cmd_call_quality() static pj_status_t cmd_send_arbitrary(pj_cli_cmd_val *cval) { if (pjsua_acc_get_count() == 0) { - static const pj_str_t err_msg = {"Sorry, need at least one " - "account configured\n", 45}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + static const pj_str_t err_msg = {"Sorry, need at least one " + "account configured\n", 45}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); } else { - char *uri; - char dest[64] = {0}; - pj_str_t tmp = pj_str(dest); - struct input_result result; - static const pj_str_t header = {"Send arbitrary request to " - "remote host\n", 39}; - - pj_cli_sess_write_msg(cval->sess, header.ptr, header.slen); - - pj_strncpy_with_null(&tmp, &cval->argv[2], sizeof(dest)); - /* Input destination URI */ - uri = NULL; - get_input_url(tmp.ptr, tmp.slen, cval, &result); - if (result.nb_result != PJSUA_APP_NO_NB) { - if (result.nb_result == -1) { - static const pj_str_t err_msg = {"Sorry you can't do that!\n", - 26}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); - return PJ_SUCCESS; - } else if (result.nb_result == 0) { - uri = NULL; - if (current_call == PJSUA_INVALID_ID) { - static const pj_str_t err_msg = {"No current call\n", - 17}; - pj_cli_sess_write_msg(cval->sess, err_msg.ptr, - err_msg.slen); - - return PJ_SUCCESS; - } - } else { - pjsua_buddy_info binfo; - pjsua_buddy_get_info(result.nb_result-1, &binfo); - pj_strncpy_with_null(&tmp, &binfo.uri, sizeof(dest)); - uri = tmp.ptr; - } - } else if (result.uri_result) { - uri = result.uri_result; - } else { - return PJ_SUCCESS;; - } - - if (uri) { - char method[64] = {0}; - pj_str_t tmp_method = pj_str(method); - pj_strncpy_with_null(&tmp_method, &cval->argv[1], sizeof(method)); - tmp = pj_str(uri); - send_request(method, &tmp); - } else { - /* If you send call control request using this method - * (such requests includes BYE, CANCEL, etc.), it will - * not go well with the call state, so don't do it - * unless it's for testing. - */ - pjsua_call_send_request(current_call, &cval->argv[1], NULL); - } + char *uri; + char dest[64] = {0}; + pj_str_t tmp = pj_str(dest); + struct input_result result; + static const pj_str_t header = {"Send arbitrary request to " + "remote host\n", 39}; + + pj_cli_sess_write_msg(cval->sess, header.ptr, header.slen); + + pj_strncpy_with_null(&tmp, &cval->argv[2], sizeof(dest)); + /* Input destination URI */ + uri = NULL; + get_input_url(tmp.ptr, tmp.slen, cval, &result); + if (result.nb_result != PJSUA_APP_NO_NB) { + if (result.nb_result == -1) { + static const pj_str_t err_msg = {"Sorry you can't do that!\n", + 26}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, err_msg.slen); + return PJ_SUCCESS; + } else if (result.nb_result == 0) { + uri = NULL; + if (current_call == PJSUA_INVALID_ID) { + static const pj_str_t err_msg = {"No current call\n", + 17}; + pj_cli_sess_write_msg(cval->sess, err_msg.ptr, + err_msg.slen); + + return PJ_SUCCESS; + } + } else { + pjsua_buddy_info binfo; + pjsua_buddy_get_info(result.nb_result-1, &binfo); + pj_strncpy_with_null(&tmp, &binfo.uri, sizeof(dest)); + uri = tmp.ptr; + } + } else if (result.uri_result) { + uri = result.uri_result; + } else { + return PJ_SUCCESS;; + } + + if (uri) { + char method[64] = {0}; + pj_str_t tmp_method = pj_str(method); + pj_strncpy_with_null(&tmp_method, &cval->argv[1], sizeof(method)); + tmp = pj_str(uri); + send_request(method, &tmp); + } else { + /* If you send call control request using this method + * (such requests includes BYE, CANCEL, etc.), it will + * not go well with the call state, so don't do it + * unless it's for testing. + */ + pjsua_call_send_request(current_call, &cval->argv[1], NULL); + } } return PJ_SUCCESS; } @@ -2057,22 +2056,22 @@ static pj_status_t cmd_show_current_call(pj_cli_cmd_val *cval) char out_str[128]; int i = pjsua_call_get_count(); pj_ansi_snprintf(out_str, sizeof(out_str), - "You have %d active call%s\n", i, (i>1?"s":"")); + "You have %d active call%s\n", i, (i>1?"s":"")); pj_cli_sess_write_msg(cval->sess, out_str, - pj_ansi_strlen(out_str)); + pj_ansi_strlen(out_str)); if (current_call != PJSUA_INVALID_ID) { - pjsua_call_info ci; - if (pjsua_call_get_info(current_call, &ci)==PJ_SUCCESS) { - pj_ansi_snprintf(out_str, sizeof(out_str), - "Current call id=%d to %.*s [%.*s]\n", current_call, - (int)ci.remote_info.slen, ci.remote_info.ptr, - (int)ci.state_text.slen, ci.state_text.ptr); + pjsua_call_info ci; + if (pjsua_call_get_info(current_call, &ci)==PJ_SUCCESS) { + pj_ansi_snprintf(out_str, sizeof(out_str), + "Current call id=%d to %.*s [%.*s]\n", current_call, + (int)ci.remote_info.slen, ci.remote_info.ptr, + (int)ci.state_text.slen, ci.state_text.ptr); - pj_cli_sess_write_msg(cval->sess, out_str, - pj_ansi_strlen(out_str)); - } + pj_cli_sess_write_msg(cval->sess, out_str, + pj_ansi_strlen(out_str)); + } } return PJ_SUCCESS; } @@ -2087,55 +2086,55 @@ pj_status_t cmd_call_handler(pj_cli_cmd_val *cval) switch(cmd_id) { case CMD_CALL_NEW: - status = cmd_make_single_call(cval); - break; + status = cmd_make_single_call(cval); + break; case CMD_CALL_MULTI: - status = cmd_make_multi_call(cval); - break; + status = cmd_make_multi_call(cval); + break; case CMD_CALL_ANSWER: - status = cmd_answer_call(cval); - break; + status = cmd_answer_call(cval); + break; case CMD_CALL_HANGUP: case CMD_CALL_HANGUP_ALL: - status = cmd_hangup_call(cval, (cmd_id==CMD_CALL_HANGUP_ALL)); - break; + status = cmd_hangup_call(cval, (cmd_id==CMD_CALL_HANGUP_ALL)); + break; case CMD_CALL_HOLD: - status = cmd_hold_call(); - break; + status = cmd_hold_call(); + break; case CMD_CALL_REINVITE: - status = cmd_call_reinvite(); - break; + status = cmd_call_reinvite(); + break; case CMD_CALL_UPDATE: - status = cmd_call_update(); - break; + status = cmd_call_update(); + break; case CMD_CALL_NEXT: case CMD_CALL_PREVIOUS: - status = cmd_next_call(cmd_id==CMD_CALL_NEXT); - break; + status = cmd_next_call(cmd_id==CMD_CALL_NEXT); + break; case CMD_CALL_TRANSFER: - status = cmd_transfer_call(cval); - break; + status = cmd_transfer_call(cval); + break; case CMD_CALL_TRANSFER_REPLACE: - status = cmd_transfer_replace_call(cval); - break; + status = cmd_transfer_replace_call(cval); + break; case CMD_CALL_REDIRECT: - status = cmd_redirect_call(cval); - break; + status = cmd_redirect_call(cval); + break; case CMD_CALL_D2833: - status = cmd_dtmf_2833(cval); - break; + status = cmd_dtmf_2833(cval); + break; case CMD_CALL_INFO: - status = cmd_call_info(cval); - break; + status = cmd_call_info(cval); + break; case CMD_CALL_DUMP_Q: - status = cmd_call_quality(); - break; + status = cmd_call_quality(); + break; case CMD_CALL_SEND_ARB: - status = cmd_send_arbitrary(cval); - break; + status = cmd_send_arbitrary(cval); + break; case CMD_CALL_LIST: - status = cmd_show_current_call(cval); - break; + status = cmd_show_current_call(cval); + break; } return status; @@ -2146,7 +2145,7 @@ static pj_status_t cmd_set_video_enable(pj_bool_t enabled) { app_config.vid.vid_cnt = (enabled ? 1 : 0); PJ_LOG(3,(THIS_FILE, "Video will be %s in next offer/answer", - (enabled?"enabled":"disabled"))); + (enabled?"enabled":"disabled"))); return PJ_SUCCESS; } @@ -2155,8 +2154,8 @@ static pj_status_t modify_video_account(pjsua_acc_config *acc_cfg) { pj_status_t status = pjsua_acc_modify(current_acc, acc_cfg); if (status != PJ_SUCCESS) - PJ_PERROR(1,(THIS_FILE, status, "Error modifying account %d", - current_acc)); + PJ_PERROR(1,(THIS_FILE, status, "Error modifying account %d", + current_acc)); return status; } @@ -2185,26 +2184,26 @@ static pj_status_t cmd_video_acc_handler(pj_cli_cmd_val *cval) switch(cmd_id) { case CMD_VIDEO_ACC_AUTORX: case CMD_VIDEO_ACC_AUTOTX: - { - int on = (pj_ansi_strnicmp(cval->argv[1].ptr, "On", 2)==0); - - if (cmd_id == CMD_VIDEO_ACC_AUTORX) - acc_cfg.vid_in_auto_show = on; - else - acc_cfg.vid_out_auto_transmit = on; - } - break; + { + int on = (pj_ansi_strnicmp(cval->argv[1].ptr, "On", 2)==0); + + if (cmd_id == CMD_VIDEO_ACC_AUTORX) + acc_cfg.vid_in_auto_show = on; + else + acc_cfg.vid_out_auto_transmit = on; + } + break; case CMD_VIDEO_ACC_CAP_ID: case CMD_VIDEO_ACC_REN_ID: - { - int dev = (int)pj_strtol(&cval->argv[1]); + { + int dev = (int)pj_strtol(&cval->argv[1]); - if (cmd_id == CMD_VIDEO_ACC_CAP_ID) - acc_cfg.vid_cap_dev = dev; - else - acc_cfg.vid_rend_dev = dev; - } - break; + if (cmd_id == CMD_VIDEO_ACC_CAP_ID) + acc_cfg.vid_cap_dev = dev; + else + acc_cfg.vid_rend_dev = dev; + } + break; } modify_video_account(&acc_cfg); pj_pool_release(pool); @@ -2214,7 +2213,7 @@ static pj_status_t cmd_video_acc_handler(pj_cli_cmd_val *cval) static pj_status_t cmd_add_vid_strm() { return pjsua_call_set_vid_strm(current_call, - PJSUA_CALL_VID_STRM_ADD, NULL); + PJSUA_CALL_VID_STRM_ADD, NULL); } static pj_status_t cmd_enable_vid_rx(pj_cli_cmd_val *cval) @@ -2228,18 +2227,18 @@ static pj_status_t cmd_enable_vid_rx(pj_cli_cmd_val *cval) param.med_idx = (int)pj_strtol(&cval->argv[2]); if (pjsua_call_get_stream_info(current_call, param.med_idx, &si) || - si.type != PJMEDIA_TYPE_VIDEO) + si.type != PJMEDIA_TYPE_VIDEO) { - PJ_PERROR(1,(THIS_FILE, PJ_EINVAL, "Invalid stream")); - return status; + PJ_PERROR(1,(THIS_FILE, PJ_EINVAL, "Invalid stream")); + return status; } if (on) param.dir = (si.info.vid.dir | PJMEDIA_DIR_DECODING); else param.dir = (si.info.vid.dir & PJMEDIA_DIR_ENCODING); status = pjsua_call_set_vid_strm(current_call, - PJSUA_CALL_VID_STRM_CHANGE_DIR, - ¶m); + PJSUA_CALL_VID_STRM_CHANGE_DIR, + ¶m); return status; } @@ -2250,7 +2249,7 @@ static pj_status_t cmd_enable_vid_tx(pj_cli_cmd_val *cval) pj_bool_t on = (pj_ansi_strnicmp(cval->argv[1].ptr, "On", 2) == 0); pjsua_call_vid_strm_op op = on? PJSUA_CALL_VID_STRM_START_TRANSMIT : - PJSUA_CALL_VID_STRM_STOP_TRANSMIT; + PJSUA_CALL_VID_STRM_STOP_TRANSMIT; pjsua_call_vid_strm_op_param_default(¶m); @@ -2261,11 +2260,11 @@ static pj_status_t cmd_enable_vid_tx(pj_cli_cmd_val *cval) } static pj_status_t cmd_enable_vid_stream(pj_cli_cmd_val *cval, - pj_bool_t enable) + pj_bool_t enable) { pjsua_call_vid_strm_op_param param; pjsua_call_vid_strm_op op = enable? PJSUA_CALL_VID_STRM_CHANGE_DIR : - PJSUA_CALL_VID_STRM_REMOVE; + PJSUA_CALL_VID_STRM_REMOVE; pjsua_call_vid_strm_op_param_default(¶m); @@ -2287,8 +2286,8 @@ static pj_status_t cmd_set_cap_dev_id(pj_cli_cmd_val *cval) PJMEDIA_VID_DEFAULT_CAPTURE_DEV; return pjsua_call_set_vid_strm(current_call, - PJSUA_CALL_VID_STRM_CHANGE_CAP_DEV, - ¶m); + PJSUA_CALL_VID_STRM_CHANGE_CAP_DEV, + ¶m); } static pj_status_t cmd_list_vid_dev() @@ -2309,22 +2308,22 @@ static pj_status_t cmd_vid_device_preview(pj_cli_cmd_val *cval) pj_bool_t on = (pj_ansi_strnicmp(cval->argv[1].ptr, "On", 2) == 0); if (on) { - pjsua_vid_preview_param param; + pjsua_vid_preview_param param; - pjsua_vid_preview_param_default(¶m); - param.wnd_flags = PJMEDIA_VID_DEV_WND_BORDER | - PJMEDIA_VID_DEV_WND_RESIZABLE; - pjsua_vid_preview_start(dev_id, ¶m); - arrange_window(pjsua_vid_preview_get_win(dev_id)); + pjsua_vid_preview_param_default(¶m); + param.wnd_flags = PJMEDIA_VID_DEV_WND_BORDER | + PJMEDIA_VID_DEV_WND_RESIZABLE; + pjsua_vid_preview_start(dev_id, ¶m); + arrange_window(pjsua_vid_preview_get_win(dev_id)); } else { - pjsua_vid_win_id wid; - wid = pjsua_vid_preview_get_win(dev_id); - if (wid != PJSUA_INVALID_ID) { - /* Preview window hiding once it is stopped is - * responsibility of app */ - pjsua_vid_win_set_show(wid, PJ_FALSE); - pjsua_vid_preview_stop(dev_id); - } + pjsua_vid_win_id wid; + wid = pjsua_vid_preview_get_win(dev_id); + if (wid != PJSUA_INVALID_ID) { + /* Preview window hiding once it is stopped is + * responsibility of app */ + pjsua_vid_win_set_show(wid, PJ_FALSE); + pjsua_vid_preview_stop(dev_id); + } } return PJ_SUCCESS; } @@ -2335,30 +2334,30 @@ static pj_status_t cmd_vid_codec_list() unsigned count = PJ_ARRAY_SIZE(ci); pj_status_t status = pjsua_vid_enum_codecs(ci, &count); if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "Error enumerating codecs")); + PJ_PERROR(1,(THIS_FILE, status, "Error enumerating codecs")); } else { - unsigned i; - PJ_LOG(3,(THIS_FILE, "Found %d video codecs:", count)); - PJ_LOG(3,(THIS_FILE, "codec id prio fps bw(kbps) size")); - PJ_LOG(3,(THIS_FILE, "------------------------------------------")); - for (i=0; ifps.num*1.0/vfd->fps.denum), - vfd->avg_bps/1000, vfd->max_bps/1000, - vfd->size.w, vfd->size.h)); - } + unsigned i; + PJ_LOG(3,(THIS_FILE, "Found %d video codecs:", count)); + PJ_LOG(3,(THIS_FILE, "codec id prio fps bw(kbps) size")); + PJ_LOG(3,(THIS_FILE, "------------------------------------------")); + for (i=0; ifps.num*1.0/vfd->fps.denum), + vfd->avg_bps/1000, vfd->max_bps/1000, + vfd->size.w, vfd->size.h)); + } } return PJ_SUCCESS; } @@ -2370,7 +2369,7 @@ static pj_status_t cmd_set_vid_codec_prio(pj_cli_cmd_val *cval) status = pjsua_vid_codec_set_priority(&cval->argv[1], (pj_uint8_t)prio); if (status != PJ_SUCCESS) - PJ_PERROR(1,(THIS_FILE, status, "Set codec priority error")); + PJ_PERROR(1,(THIS_FILE, status, "Set codec priority error")); return PJ_SUCCESS; } @@ -2385,12 +2384,12 @@ static pj_status_t cmd_set_vid_codec_fps(pj_cli_cmd_val *cval) N = (int)pj_strtol(&cval->argv[3]); status = pjsua_vid_codec_get_param(&cval->argv[1], &cp); if (status == PJ_SUCCESS) { - cp.enc_fmt.det.vid.fps.num = M; - cp.enc_fmt.det.vid.fps.denum = N; - status = pjsua_vid_codec_set_param(&cval->argv[1], &cp); + cp.enc_fmt.det.vid.fps.num = M; + cp.enc_fmt.det.vid.fps.denum = N; + status = pjsua_vid_codec_set_param(&cval->argv[1], &cp); } if (status != PJ_SUCCESS) - PJ_PERROR(1,(THIS_FILE, status, "Set codec framerate error")); + PJ_PERROR(1,(THIS_FILE, status, "Set codec framerate error")); return PJ_SUCCESS; } @@ -2405,12 +2404,12 @@ static pj_status_t cmd_set_vid_codec_bitrate(pj_cli_cmd_val *cval) N = (int)pj_strtol(&cval->argv[3]); status = pjsua_vid_codec_get_param(&cval->argv[1], &cp); if (status == PJ_SUCCESS) { - cp.enc_fmt.det.vid.avg_bps = M * 1000; - cp.enc_fmt.det.vid.max_bps = N * 1000; - status = pjsua_vid_codec_set_param(&cval->argv[1], &cp); + cp.enc_fmt.det.vid.avg_bps = M * 1000; + cp.enc_fmt.det.vid.max_bps = N * 1000; + status = pjsua_vid_codec_set_param(&cval->argv[1], &cp); } if (status != PJ_SUCCESS) - PJ_PERROR(1,(THIS_FILE, status, "Set codec bitrate error")); + PJ_PERROR(1,(THIS_FILE, status, "Set codec bitrate error")); return status; } @@ -2425,12 +2424,12 @@ static pj_status_t cmd_set_vid_codec_size(pj_cli_cmd_val *cval) N = (int)pj_strtol(&cval->argv[3]); status = pjsua_vid_codec_get_param(&cval->argv[1], &cp); if (status == PJ_SUCCESS) { - cp.enc_fmt.det.vid.size.w = M; - cp.enc_fmt.det.vid.size.h = N; - status = pjsua_vid_codec_set_param(&cval->argv[1], &cp); + cp.enc_fmt.det.vid.size.w = M; + cp.enc_fmt.det.vid.size.h = N; + status = pjsua_vid_codec_set_param(&cval->argv[1], &cp); } if (status != PJ_SUCCESS) - PJ_PERROR(1,(THIS_FILE, status, "Set codec size error")); + PJ_PERROR(1,(THIS_FILE, status, "Set codec size error")); return status; } @@ -2446,11 +2445,11 @@ static pj_status_t cmd_vid_win_list() PJ_LOG(3,(THIS_FILE, "WID show pos size")); PJ_LOG(3,(THIS_FILE, "------------------------------")); for (i = 0; i < cnt; ++i) { - pjsua_vid_win_info wi; - pjsua_vid_win_get_info(wids[i], &wi); - PJ_LOG(3,(THIS_FILE, "%3d %c (%d,%d) %dx%d", - wids[i], (wi.show?'Y':'N'), wi.pos.x, wi.pos.y, - wi.size.w, wi.size.h)); + pjsua_vid_win_info wi; + pjsua_vid_win_get_info(wids[i], &wi); + PJ_LOG(3,(THIS_FILE, "%3d %c (%d,%d) %dx%d", + wids[i], (wi.show?'Y':'N'), wi.pos.x, wi.pos.y, + wi.size.w, wi.size.h)); } return PJ_SUCCESS; } @@ -2496,55 +2495,55 @@ static pj_status_t cmd_vid_conf_list() status = pjsua_vid_conf_enum_ports(id, &count); if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "Failed enumerating video conf bridge ports")); - return status; + PJ_PERROR(1,(THIS_FILE, status, + "Failed enumerating video conf bridge ports")); + return status; } PJ_LOG(3,(THIS_FILE," Video conference has %d ports:\n", count)); PJ_LOG(3,(THIS_FILE," id name format rx-from tx-to \n")); PJ_LOG(3,(THIS_FILE," ------------------------------------------------------------------\n")); for (i=0; iw, size->h, (float)(fps->num*1.0/fps->denum)); - PJ_LOG(3,(THIS_FILE,"%3d %.*s%.*s %s%.*s %s%.*s %s\n", - id[i], - (int)info.name.slen, info.name.ptr, - 22-(int)info.name.slen, " ", - s, - 20-pj_ansi_strlen(s), " ", - tr_list, - 12-pj_ansi_strlen(tr_list), " ", - li_list)); + char li_list[PJSUA_MAX_CALLS*4]; + char tr_list[PJSUA_MAX_CALLS*4]; + char s[32]; + unsigned j; + pjsua_vid_conf_port_info info; + pjmedia_rect_size *size; + pjmedia_ratio *fps; + + pjsua_vid_conf_get_port_info(id[i], &info); + size = &info.format.det.vid.size; + fps = &info.format.det.vid.fps; + + li_list[0] = '\0'; + for (j=0; jw, size->h, (float)(fps->num*1.0/fps->denum)); + PJ_LOG(3,(THIS_FILE,"%3d %.*s%.*s %s%.*s %s%.*s %s\n", + id[i], + (int)info.name.slen, info.name.ptr, + 22-(int)info.name.slen, " ", + s, + 20-pj_ansi_strlen(s), " ", + tr_list, + 12-pj_ansi_strlen(tr_list), " ", + li_list)); } return PJ_SUCCESS; } @@ -2556,9 +2555,9 @@ static pj_status_t cmd_vid_conf_connect(pj_cli_cmd_val *cval, pj_bool_t connect) P = (int)pj_strtol(&cval->argv[1]); Q = (int)pj_strtol(&cval->argv[2]); if (connect) - return pjsua_vid_conf_connect(P, Q, NULL); + return pjsua_vid_conf_connect(P, Q, NULL); else - return pjsua_vid_conf_disconnect(P, Q); + return pjsua_vid_conf_disconnect(P, Q); } @@ -2572,83 +2571,83 @@ static pj_status_t cmd_video_handler(pj_cli_cmd_val *cval) switch(cmd_id) { case CMD_VIDEO_ENABLE: - status = cmd_set_video_enable(PJ_TRUE); - break; + status = cmd_set_video_enable(PJ_TRUE); + break; case CMD_VIDEO_DISABLE: - status = cmd_set_video_enable(PJ_FALSE); - break; + status = cmd_set_video_enable(PJ_FALSE); + break; case CMD_VIDEO_ACC_SHOW: - status = cmd_show_account_video(); - break; + status = cmd_show_account_video(); + break; case CMD_VIDEO_ACC_AUTORX: case CMD_VIDEO_ACC_AUTOTX: case CMD_VIDEO_ACC_CAP_ID: case CMD_VIDEO_ACC_REN_ID: - status = cmd_video_acc_handler(cval); - break; + status = cmd_video_acc_handler(cval); + break; case CMD_VIDEO_CALL_ADD: - status = cmd_add_vid_strm(); - break; + status = cmd_add_vid_strm(); + break; case CMD_VIDEO_CALL_RX: - status = cmd_enable_vid_rx(cval); - break; + status = cmd_enable_vid_rx(cval); + break; case CMD_VIDEO_CALL_TX: - status = cmd_enable_vid_tx(cval); - break; + status = cmd_enable_vid_tx(cval); + break; case CMD_VIDEO_CALL_ENABLE: case CMD_VIDEO_CALL_DISABLE: - status = cmd_enable_vid_stream(cval, (cmd_id==CMD_VIDEO_CALL_ENABLE)); - break; + status = cmd_enable_vid_stream(cval, (cmd_id==CMD_VIDEO_CALL_ENABLE)); + break; case CMD_VIDEO_CALL_CAP: - status = cmd_set_cap_dev_id(cval); - break; + status = cmd_set_cap_dev_id(cval); + break; case CMD_VIDEO_DEVICE_LIST: - status = cmd_list_vid_dev(); - break; + status = cmd_list_vid_dev(); + break; case CMD_VIDEO_DEVICE_REFRESH: - status = cmd_vid_device_refresh(); - break; + status = cmd_vid_device_refresh(); + break; case CMD_VIDEO_DEVICE_PREVIEW: - status = cmd_vid_device_preview(cval); - break; + status = cmd_vid_device_preview(cval); + break; case CMD_VIDEO_CODEC_LIST: - status = cmd_vid_codec_list(); - break; + status = cmd_vid_codec_list(); + break; case CMD_VIDEO_CODEC_PRIO: - status = cmd_set_vid_codec_prio(cval); - break; + status = cmd_set_vid_codec_prio(cval); + break; case CMD_VIDEO_CODEC_FPS: - status = cmd_set_vid_codec_fps(cval); - break; + status = cmd_set_vid_codec_fps(cval); + break; case CMD_VIDEO_CODEC_BITRATE: - status = cmd_set_vid_codec_bitrate(cval); - break; + status = cmd_set_vid_codec_bitrate(cval); + break; case CMD_VIDEO_CODEC_SIZE: - status = cmd_set_vid_codec_size(cval); - break; + status = cmd_set_vid_codec_size(cval); + break; case CMD_VIDEO_WIN_LIST: - status = cmd_vid_win_list(); - break; + status = cmd_vid_win_list(); + break; case CMD_VIDEO_WIN_ARRANGE: - status = cmd_arrange_vid_win(); - break; + status = cmd_arrange_vid_win(); + break; case CMD_VIDEO_WIN_SHOW: case CMD_VIDEO_WIN_HIDE: - status = cmd_show_vid_win(cval, (cmd_id==CMD_VIDEO_WIN_SHOW)); - break; + status = cmd_show_vid_win(cval, (cmd_id==CMD_VIDEO_WIN_SHOW)); + break; case CMD_VIDEO_WIN_MOVE: - status = cmd_move_vid_win(cval); - break; + status = cmd_move_vid_win(cval); + break; case CMD_VIDEO_WIN_RESIZE: - status = cmd_resize_vid_win(cval); - break; + status = cmd_resize_vid_win(cval); + break; case CMD_VIDEO_CONF_LIST: - status = cmd_vid_conf_list(); - break; + status = cmd_vid_conf_list(); + break; case CMD_VIDEO_CONF_CONNECT: case CMD_VIDEO_CONF_DISCONNECT: - status = cmd_vid_conf_connect(cval, (cmd_id==CMD_VIDEO_CONF_CONNECT)); - break; + status = cmd_vid_conf_connect(cval, (cmd_id==CMD_VIDEO_CONF_CONNECT)); + break; } return status; @@ -2676,7 +2675,7 @@ static pj_status_t cmd_network_handler(pj_cli_cmd_val *cval) status = pjsua_detect_nat_type(); if (status != PJ_SUCCESS) - pjsua_perror(THIS_FILE, "Error", status); + pjsua_perror(THIS_FILE, "Error", status); return status; } @@ -2701,9 +2700,9 @@ static pj_status_t cmd_ip_change_handler(pj_cli_cmd_val *cval) pjsua_ip_change_param_default(¶m); status = pjsua_handle_ip_change(¶m); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "IP change failed", status); + pjsua_perror(THIS_FILE, "IP change failed", status); } else { - PJ_LOG(3,(THIS_FILE, "IP change succeeded")); + PJ_LOG(3,(THIS_FILE, "IP change succeeded")); } return PJ_SUCCESS; @@ -2725,7 +2724,7 @@ static void on_syntax_error(pj_scanner *scanner) * @argv Array of argument string */ static pj_status_t get_options(pj_str_t *options, unsigned *argc, - pj_str_t argv[]) + pj_str_t argv[]) { pj_scanner scanner; unsigned max_argc = *argc; @@ -2733,23 +2732,23 @@ static pj_status_t get_options(pj_str_t *options, unsigned *argc, PJ_USE_EXCEPTION; if (!options) - return PJ_SUCCESS; + return PJ_SUCCESS; pj_scan_init(&scanner, options->ptr, options->slen, PJ_SCAN_AUTOSKIP_WS, - &on_syntax_error); + &on_syntax_error); PJ_TRY { - *argc = 0; - while (!pj_scan_is_eof(&scanner) && (max_argc > *argc)) { - pj_str_t str; + *argc = 0; + while (!pj_scan_is_eof(&scanner) && (max_argc > *argc)) { + pj_str_t str; - pj_scan_get_until_chr(&scanner, " \t\r\n", &str); - argv[*argc] = str; - ++(*argc); - } + pj_scan_get_until_chr(&scanner, " \t\r\n", &str); + argv[*argc] = str; + ++(*argc); + } } PJ_CATCH_ANY { - pj_scan_fini(&scanner); - return PJ_GET_EXCEPTION(); + pj_scan_fini(&scanner); + return PJ_GET_EXCEPTION(); } PJ_END; return PJ_SUCCESS; @@ -2769,18 +2768,18 @@ static pj_status_t cmd_restart_handler(pj_cli_cmd_val *cval) /** Get the pjsua option **/ for (i=1; i < cval->argc; i++) { - pj_str_t argvst[MAX_ARGC]; - unsigned j, ac; + pj_str_t argvst[MAX_ARGC]; + unsigned j, ac; - ac = MAX_ARGC - argc; - get_options(&cval->argv[i], &ac, argvst); - for (j = 0; j < ac; j++) { - pj_ansi_strncpy(pbuf, argvst[j].ptr, argvst[j].slen); - pbuf[argvst[j].slen] = '\0'; - argv[argc + j] = pbuf; - pbuf += argvst[j].slen + 1; - } - argc += ac; + ac = MAX_ARGC - argc; + get_options(&cval->argv[i], &ac, argvst); + for (j = 0; j < ac; j++) { + pj_ansi_strncpy(pbuf, argvst[j].ptr, argvst[j].slen); + pbuf[argvst[j].slen] = '\0'; + argv[argc + j] = pbuf; + pbuf += argvst[j].slen + 1; + } + argc += ac; } /* Invoke CLI stop callback (defined in pjsua_app.c) */ @@ -2792,417 +2791,417 @@ static pj_status_t cmd_restart_handler(pj_cli_cmd_val *cval) static pj_status_t add_call_command(pj_cli_t *c) { char* call_command = - "" - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - ""; + "" + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + ""; pj_str_t xml = pj_str(call_command); return pj_cli_add_cmd_from_xml(c, NULL, - &xml, cmd_call_handler, - NULL, get_choice_value); + &xml, cmd_call_handler, + NULL, get_choice_value); } static pj_status_t add_presence_command(pj_cli_t *c) { char* presence_command = - "" - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - ""; + "" + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + ""; pj_str_t xml = pj_str(presence_command); return pj_cli_add_cmd_from_xml(c, NULL, - &xml, cmd_presence_handler, - NULL, get_choice_value); + &xml, cmd_presence_handler, + NULL, get_choice_value); } static pj_status_t add_account_command(pj_cli_t *c) { char* account_command = - "" - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - ""; + "" + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + ""; pj_str_t xml = pj_str(account_command); return pj_cli_add_cmd_from_xml(c, NULL, - &xml, cmd_account_handler, - NULL, get_choice_value); + &xml, cmd_account_handler, + NULL, get_choice_value); } static pj_status_t add_media_command(pj_cli_t *c) { char* media_command = - "" - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - ""; + "" + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + ""; pj_str_t xml = pj_str(media_command); return pj_cli_add_cmd_from_xml(c, NULL, - &xml, cmd_media_handler, - NULL, get_choice_value); + &xml, cmd_media_handler, + NULL, get_choice_value); } static pj_status_t add_config_command(pj_cli_t *c) { char* config_command = - "" - " " - " " - " " - " " - " " - " " - ""; + "" + " " + " " + " " + " " + " " + " " + ""; pj_str_t xml = pj_str(config_command); return pj_cli_add_cmd_from_xml(c, NULL, - &xml, cmd_config_handler, - NULL, get_choice_value); + &xml, cmd_config_handler, + NULL, get_choice_value); } #if PJSUA_HAS_VIDEO static pj_status_t add_video_command(pj_cli_t *c) { char* video_command = - "" - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - ""; + "" + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + ""; pj_str_t xml = pj_str(video_command); return pj_cli_add_cmd_from_xml(c, NULL, - &xml, cmd_video_handler, - NULL, get_choice_value); + &xml, cmd_video_handler, + NULL, get_choice_value); } #endif static pj_status_t add_other_command(pj_cli_t *c) { char* sleep_command = - "" - " " - ""; + "" + " " + ""; char* network_command = - ""; + ""; char* shutdown_command = - ""; + ""; char* restart_command = - "" - " " - " " - " " - " " - ""; + "" + " " + " " + " " + " " + ""; char* ip_change_command = - ""; + ""; pj_status_t status; pj_str_t sleep_xml = pj_str(sleep_command); @@ -3212,34 +3211,34 @@ static pj_status_t add_other_command(pj_cli_t *c) pj_str_t ip_change_xml = pj_str(ip_change_command); status = pj_cli_add_cmd_from_xml(c, NULL, - &sleep_xml, cmd_sleep_handler, - NULL, NULL); + &sleep_xml, cmd_sleep_handler, + NULL, NULL); if (status != PJ_SUCCESS) - return status; + return status; status = pj_cli_add_cmd_from_xml(c, NULL, - &network_xml, cmd_network_handler, - NULL, NULL); + &network_xml, cmd_network_handler, + NULL, NULL); if (status != PJ_SUCCESS) - return status; + return status; status = pj_cli_add_cmd_from_xml(c, NULL, - &shutdown_xml, cmd_quit_handler, - NULL, NULL); + &shutdown_xml, cmd_quit_handler, + NULL, NULL); if (status != PJ_SUCCESS) - return status; + return status; status = pj_cli_add_cmd_from_xml(c, NULL, - &restart_xml, cmd_restart_handler, - NULL, NULL); + &restart_xml, cmd_restart_handler, + NULL, NULL); if (status != PJ_SUCCESS) - return status; + return status; status = pj_cli_add_cmd_from_xml(c, NULL, - &ip_change_xml, cmd_ip_change_handler, - NULL, NULL); + &ip_change_xml, cmd_ip_change_handler, + NULL, NULL); return status; } @@ -3250,28 +3249,28 @@ pj_status_t cli_setup_command(pj_cli_t *c) status = add_call_command(c); if (status != PJ_SUCCESS) - return status; + return status; status = add_presence_command(c); if (status != PJ_SUCCESS) - return status; + return status; status = add_account_command(c); if (status != PJ_SUCCESS) - return status; + return status; status = add_media_command(c); if (status != PJ_SUCCESS) - return status; + return status; status = add_config_command(c); if (status != PJ_SUCCESS) - return status; + return status; #if PJSUA_HAS_VIDEO status = add_video_command(c); if (status != PJ_SUCCESS) - return status; + return status; #endif status = add_other_command(c); diff --git a/pjsip-apps/src/pjsua/pjsua_app_common.c b/pjsip-apps/src/pjsua/pjsua_app_common.c index 6b0d9ebd69..f9a292fc99 100644 --- a/pjsip-apps/src/pjsua/pjsua_app_common.c +++ b/pjsip-apps/src/pjsua/pjsua_app_common.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -20,12 +19,12 @@ #include "pjsua_app_common.h" -#define THIS_FILE "pjsua_app_common.c" +#define THIS_FILE "pjsua_app_common.c" #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) -# define SOME_BUF_SIZE (1024 * 10) +# define SOME_BUF_SIZE (1024 * 10) #else -# define SOME_BUF_SIZE (1024 * 3) +# define SOME_BUF_SIZE (1024 * 3) #endif #ifdef USE_GUI @@ -35,12 +34,12 @@ void displayWindow(pjsua_vid_win_id wid); static char some_buf[SOME_BUF_SIZE]; /** Variable definition **/ -int stdout_refresh = -1; -pj_bool_t stdout_refresh_quit = PJ_FALSE; -pjsua_call_id current_call = PJSUA_INVALID_ID; +int stdout_refresh = -1; +pj_bool_t stdout_refresh_quit = PJ_FALSE; +pjsua_call_id current_call = PJSUA_INVALID_ID; pjsua_app_config app_config; pjsua_call_setting call_opt; -pjsua_msg_data msg_data; +pjsua_msg_data msg_data; int my_atoi(const char *cs) { @@ -55,13 +54,13 @@ int my_atoi2(const pj_str_t *str) pj_str_t s = *str; if (cs[0] == '-') { - s.ptr++; s.slen--; - return 0 - (int)pj_strtoul(&s); + s.ptr++; s.slen--; + return 0 - (int)pj_strtoul(&s); } else if (cs[0] == '+') { - s.ptr++; s.slen--; - return (int)pj_strtoul(&s); + s.ptr++; s.slen--; + return (int)pj_strtoul(&s); } else { - return (int)pj_strtoul(&s); + return (int)pj_strtoul(&s); } } @@ -75,17 +74,17 @@ pj_bool_t find_next_call(void) max = pjsua_call_get_max_count(); for (i=current_call+1; i=0; --i) { - if (pjsua_call_is_active(i)) { - current_call = i; - return PJ_TRUE; - } + if (pjsua_call_is_active(i)) { + current_call = i; + return PJ_TRUE; + } } for (i=max-1; i>current_call; --i) { - if (pjsua_call_is_active(i)) { - current_call = i; - return PJ_TRUE; - } + if (pjsua_call_is_active(i)) { + current_call = i; + return PJ_TRUE; + } } current_call = PJSUA_INVALID_ID; @@ -135,8 +134,8 @@ void send_request(char *cstr_method, const pj_str_t *dst_uri) status = pjsip_endpt_send_request(endpt, tdata, -1, NULL, NULL); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send request", status); - return; + pjsua_perror(THIS_FILE, "Unable to send request", status); + return; } } @@ -163,16 +162,16 @@ void log_call_dump(int call_id) part_idx = 0; part_len = PJ_LOG_MAX_SIZE-80; while (part_idx < call_dump_len) { - char p_orig, *p; - - p = &some_buf[part_idx]; - if (part_idx + part_len > call_dump_len) - part_len = call_dump_len - part_idx; - p_orig = p[part_len]; - p[part_len] = '\0'; - PJ_LOG(3,(THIS_FILE, "%s", p)); - p[part_len] = p_orig; - part_idx += part_len; + char p_orig, *p; + + p = &some_buf[part_idx]; + if (part_idx + part_len > call_dump_len) + part_len = call_dump_len - part_idx; + p_orig = p[part_len]; + p[part_len] = '\0'; + PJ_LOG(3,(THIS_FILE, "%s", p)); + p[part_len] = p_orig; + part_idx += part_len; } pj_log_set_decor(log_decor); } @@ -191,10 +190,10 @@ void app_config_init_video(pjsua_acc_config *acc_cfg) acc_cfg->vid_rend_dev = app_config.vid.vrender_dev; if (app_config.avi_auto_play && - app_config.avi_def_idx != PJSUA_INVALID_ID && - app_config.avi[app_config.avi_def_idx].dev_id != PJMEDIA_VID_INVALID_DEV) + app_config.avi_def_idx != PJSUA_INVALID_ID && + app_config.avi[app_config.avi_def_idx].dev_id != PJMEDIA_VID_INVALID_DEV) { - acc_cfg->vid_cap_dev = app_config.avi[app_config.avi_def_idx].dev_id; + acc_cfg->vid_cap_dev = app_config.avi[app_config.avi_def_idx].dev_id; } } #else @@ -214,15 +213,15 @@ void app_config_init_video(pjsua_acc_config *acc_cfg) static pjsip_multipart_part *alt_part; if (!alt_part) { - pj_str_t type, subtype, content; + pj_str_t type, subtype, content; - alt_part = pjsip_multipart_create_part(app_config.pool); + alt_part = pjsip_multipart_create_part(app_config.pool); - type = pj_str("text"); - subtype = pj_str("plain"); - content = pj_str("Sample text body of a multipart bodies"); - alt_part->body = pjsip_msg_body_create(app_config.pool, &type, - &subtype, &content); + type = pj_str("text"); + subtype = pj_str("plain"); + content = pj_str("Sample text body of a multipart bodies"); + alt_part->body = pjsip_msg_body_create(app_config.pool, &type, + &subtype, &content); } msg_data->multipart_ctype.type = pj_str("multipart"); @@ -246,22 +245,22 @@ void arrange_window(pjsua_vid_win_id wid) last = (wid == PJSUA_INVALID_ID) ? PJSUA_MAX_VID_WINS : wid; for (i=0; idir == PJMEDIA_DIR_CAPTURE_RENDER) { - dirname = "capture, render"; + dirname = "capture, render"; } else if (vdi->dir == PJMEDIA_DIR_CAPTURE) { - dirname = "capture"; + dirname = "capture"; } else { - dirname = "render"; + dirname = "render"; } capnames[0] = '\0'; st_len = 0; for (i=0; icaps & (1 << i)) { - const char *capname = pjmedia_vid_dev_cap_name(1 << i, NULL); - if (capname) { - int tmp_len = (int)strlen(capname); - if ((int)sizeof(capnames) - st_len <= tmp_len) - break; - - st_len += (tmp_len + 2); - if (*capnames) - strcat(capnames, ", "); - strcat(capnames, capname); - } - } + if (vdi->caps & (1 << i)) { + const char *capname = pjmedia_vid_dev_cap_name(1 << i, NULL); + if (capname) { + int tmp_len = (int)strlen(capname); + if ((int)sizeof(capnames) - st_len <= tmp_len) + break; + + st_len += (tmp_len + 2); + if (*capnames) + strcat(capnames, ", "); + strcat(capnames, capname); + } + } } formats[0] = '\0'; st_len = 0; for (i=0; ifmt_cnt; ++i) { - const pjmedia_video_format_info *vfi = - pjmedia_get_video_format_info(NULL, vdi->fmt[i].id); - if (vfi) { - int tmp_len = (int)strlen(vfi->name); - if ((int)sizeof(formats) - st_len <= tmp_len) { - st_len = -1; - break; - } - - st_len += (tmp_len + 2); - if (*formats) - strcat(formats, ", "); - strcat(formats, vfi->name); - } + const pjmedia_video_format_info *vfi = + pjmedia_get_video_format_info(NULL, vdi->fmt[i].id); + if (vfi) { + int tmp_len = (int)strlen(vfi->name); + if ((int)sizeof(formats) - st_len <= tmp_len) { + st_len = -1; + break; + } + + st_len += (tmp_len + 2); + if (*formats) + strcat(formats, ", "); + strcat(formats, vfi->name); + } } PJ_LOG(3,(THIS_FILE, "%3d %s [%s][%s] %s", id, vdi->name, vdi->driver, - dirname, title)); + dirname, title)); PJ_LOG(3,(THIS_FILE, " Supported capabilities: %s", capnames)); PJ_LOG(3,(THIS_FILE, " Supported formats: %s%s", formats, - (st_len<0? " ..." : ""))); + (st_len<0? " ..." : ""))); } void vid_list_devs(void) @@ -344,42 +343,42 @@ void vid_list_devs(void) PJ_LOG(3,(THIS_FILE, "Video device list:")); count = pjsua_vid_dev_count(); if (count == 0) { - PJ_LOG(3,(THIS_FILE, " - no device detected -")); - return; + PJ_LOG(3,(THIS_FILE, " - no device detected -")); + return; } else { - PJ_LOG(3,(THIS_FILE, "%d device(s) detected:", count)); + PJ_LOG(3,(THIS_FILE, "%d device(s) detected:", count)); } status = pjsua_vid_dev_get_info(PJMEDIA_VID_DEFAULT_RENDER_DEV, &vdi); if (status == PJ_SUCCESS) - vid_print_dev(PJMEDIA_VID_DEFAULT_RENDER_DEV, &vdi, - "(default renderer device)"); + vid_print_dev(PJMEDIA_VID_DEFAULT_RENDER_DEV, &vdi, + "(default renderer device)"); status = pjsua_vid_dev_get_info(PJMEDIA_VID_DEFAULT_CAPTURE_DEV, &vdi); if (status == PJ_SUCCESS) - vid_print_dev(PJMEDIA_VID_DEFAULT_CAPTURE_DEV, &vdi, - "(default capture device)"); + vid_print_dev(PJMEDIA_VID_DEFAULT_CAPTURE_DEV, &vdi, + "(default capture device)"); for (i=0; ivid_in_auto_show, - acc_cfg->vid_out_auto_transmit, - acc_cfg->vid_cap_dev, - acc_cfg->vid_rend_dev)); + "Account %d:\n" + " RX auto show: %d\n" + " TX auto transmit: %d\n" + " Capture dev: %d\n" + " Render dev: %d", + acc_id, + acc_cfg->vid_in_auto_show, + acc_cfg->vid_out_auto_transmit, + acc_cfg->vid_cap_dev, + acc_cfg->vid_rend_dev)); } diff --git a/pjsip-apps/src/pjsua/pjsua_app_common.h b/pjsip-apps/src/pjsua/pjsua_app_common.h index 0fa8e032f0..fa50f01d79 100644 --- a/pjsip-apps/src/pjsua/pjsua_app_common.h +++ b/pjsip-apps/src/pjsua/pjsua_app_common.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -23,150 +22,150 @@ PJ_BEGIN_DECL -#define current_acc pjsua_acc_get_default() +#define current_acc pjsua_acc_get_default() -#define PJSUA_APP_NO_LIMIT_DURATION (int)0x7FFFFFFF -#define PJSUA_APP_MAX_AVI 4 -#define PJSUA_APP_NO_NB -2 +#define PJSUA_APP_NO_LIMIT_DURATION (int)0x7FFFFFFF +#define PJSUA_APP_MAX_AVI 4 +#define PJSUA_APP_NO_NB -2 typedef struct input_result { - int nb_result; + int nb_result; char *uri_result; } input_result; /* Call specific data */ typedef struct app_call_data { - pj_timer_entry timer; - pj_bool_t ringback_on; - pj_bool_t ring_on; + pj_timer_entry timer; + pj_bool_t ringback_on; + pj_bool_t ring_on; } app_call_data; /* Video settings */ typedef struct app_vid { - unsigned vid_cnt; - int vcapture_dev; - int vrender_dev; - pj_bool_t in_auto_show; - pj_bool_t out_auto_transmit; + unsigned vid_cnt; + int vcapture_dev; + int vrender_dev; + pj_bool_t in_auto_show; + pj_bool_t out_auto_transmit; } app_vid; /* Enumeration of CLI frontends */ typedef enum { - CLI_FE_CONSOLE = 1, - CLI_FE_TELNET = 2 + CLI_FE_CONSOLE = 1, + CLI_FE_TELNET = 2 } CLI_FE; /** CLI config **/ typedef struct cli_cfg_t { /** Bitmask of CLI_FE **/ - int cli_fe; - pj_cli_cfg cfg; - pj_cli_telnet_cfg telnet_cfg; - pj_cli_console_cfg console_cfg; + int cli_fe; + pj_cli_cfg cfg; + pj_cli_telnet_cfg telnet_cfg; + pj_cli_console_cfg console_cfg; } cli_cfg_t; /* Pjsua application data */ typedef struct pjsua_app_config { - pjsua_config cfg; + pjsua_config cfg; pjsua_logging_config log_cfg; - pjsua_media_config media_cfg; - pj_bool_t no_refersub; - pj_bool_t ipv6; - pj_bool_t enable_qos; - pj_bool_t no_tcp; - pj_bool_t no_udp; - pj_bool_t use_tls; + pjsua_media_config media_cfg; + pj_bool_t no_refersub; + pj_bool_t ipv6; + pj_bool_t enable_qos; + pj_bool_t no_tcp; + pj_bool_t no_udp; + pj_bool_t use_tls; pjsua_transport_config udp_cfg; pjsua_transport_config rtp_cfg; - pjsip_redirect_op redir_op; - int srtp_keying; + pjsip_redirect_op redir_op; + int srtp_keying; - unsigned acc_cnt; - pjsua_acc_config acc_cfg[PJSUA_MAX_ACC]; + unsigned acc_cnt; + pjsua_acc_config acc_cfg[PJSUA_MAX_ACC]; - unsigned buddy_cnt; - pjsua_buddy_config buddy_cfg[PJSUA_MAX_BUDDIES]; + unsigned buddy_cnt; + pjsua_buddy_config buddy_cfg[PJSUA_MAX_BUDDIES]; - app_call_data call_data[PJSUA_MAX_CALLS]; + app_call_data call_data[PJSUA_MAX_CALLS]; - pj_pool_t *pool; + pj_pool_t *pool; /* Compatibility with older pjsua */ - unsigned codec_cnt; - pj_str_t codec_arg[32]; - unsigned codec_dis_cnt; + unsigned codec_cnt; + pj_str_t codec_arg[32]; + unsigned codec_dis_cnt; pj_str_t codec_dis[32]; - pj_bool_t null_audio; - unsigned wav_count; - pj_str_t wav_files[32]; - unsigned tone_count; - pjmedia_tone_desc tones[32]; - pjsua_conf_port_id tone_slots[32]; - pjsua_player_id wav_id; - pjsua_conf_port_id wav_port; - pj_bool_t auto_play; - pj_bool_t auto_play_hangup; - pj_timer_entry auto_hangup_timer; - pj_bool_t auto_loop; - pj_bool_t auto_conf; - pj_str_t rec_file; - pj_bool_t auto_rec; - pjsua_recorder_id rec_id; - pjsua_conf_port_id rec_port; - unsigned auto_answer; - unsigned duration; + pj_bool_t null_audio; + unsigned wav_count; + pj_str_t wav_files[32]; + unsigned tone_count; + pjmedia_tone_desc tones[32]; + pjsua_conf_port_id tone_slots[32]; + pjsua_player_id wav_id; + pjsua_conf_port_id wav_port; + pj_bool_t auto_play; + pj_bool_t auto_play_hangup; + pj_timer_entry auto_hangup_timer; + pj_bool_t auto_loop; + pj_bool_t auto_conf; + pj_str_t rec_file; + pj_bool_t auto_rec; + pjsua_recorder_id rec_id; + pjsua_conf_port_id rec_port; + unsigned auto_answer; + unsigned duration; #ifdef STEREO_DEMO - pjmedia_snd_port *snd; - pjmedia_port *sc, *sc_ch1; - pjsua_conf_port_id sc_ch1_slot; + pjmedia_snd_port *snd; + pjmedia_port *sc, *sc_ch1; + pjsua_conf_port_id sc_ch1_slot; #endif - float mic_level, - speaker_level; + float mic_level, + speaker_level; - int capture_dev, playback_dev; - unsigned capture_lat, playback_lat; + int capture_dev, playback_dev; + unsigned capture_lat, playback_lat; - pj_bool_t no_tones; - int ringback_slot; - int ringback_cnt; - pjmedia_port *ringback_port; - int ring_slot; - int ring_cnt; - pjmedia_port *ring_port; + pj_bool_t no_tones; + int ringback_slot; + int ringback_cnt; + pjmedia_port *ringback_port; + int ring_slot; + int ring_cnt; + pjmedia_port *ring_port; - app_vid vid; - unsigned aud_cnt; + app_vid vid; + unsigned aud_cnt; /* AVI to play */ unsigned avi_cnt; struct { - pj_str_t path; - pjmedia_vid_dev_index dev_id; - pjsua_conf_port_id slot; + pj_str_t path; + pjmedia_vid_dev_index dev_id; + pjsua_conf_port_id slot; } avi[PJSUA_APP_MAX_AVI]; pj_bool_t avi_auto_play; - int avi_def_idx; + int avi_def_idx; /* CLI setting */ - pj_bool_t use_cli; - cli_cfg_t cli_cfg; + pj_bool_t use_cli; + cli_cfg_t cli_cfg; } pjsua_app_config; /** Extern variable declaration **/ -extern pjsua_call_id current_call; -extern pjsua_app_config app_config; -extern int stdout_refresh; -extern pj_bool_t stdout_refresh_quit; +extern pjsua_call_id current_call; +extern pjsua_app_config app_config; +extern int stdout_refresh; +extern pj_bool_t stdout_refresh_quit; extern pjsua_call_setting call_opt; -extern pjsua_msg_data msg_data; -extern pj_bool_t app_running; +extern pjsua_msg_data msg_data; +extern pj_bool_t app_running; int my_atoi(const char *cs); int my_atoi2(const pj_str_t *s); @@ -213,7 +212,7 @@ void app_config_show_video(int acc_id, const pjsua_acc_config *acc_cfg); * multipart bodies. */ void add_multipart(pjsua_msg_data *msg_data); -# define TEST_MULTIPART(msg_data) add_multipart(msg_data) +# define TEST_MULTIPART(msg_data) add_multipart(msg_data) #else # define TEST_MULTIPART(msg_data) #endif @@ -221,5 +220,5 @@ void app_config_show_video(int acc_id, const pjsua_acc_config *acc_cfg); PJ_END_DECL -#endif /* __PJSUA_APP_COMMON_H__ */ +#endif /* __PJSUA_APP_COMMON_H__ */ diff --git a/pjsip-apps/src/pjsua/pjsua_app_config.c b/pjsip-apps/src/pjsua/pjsua_app_config.c index b55b439ddd..a28902c2da 100644 --- a/pjsip-apps/src/pjsua/pjsua_app_config.c +++ b/pjsip-apps/src/pjsua/pjsua_app_config.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -19,7 +18,7 @@ */ #include "pjsua_app_common.h" -#define THIS_FILE "pjsua_app_config.c" +#define THIS_FILE "pjsua_app_config.c" #define MAX_APP_OPTIONS 128 @@ -62,9 +61,9 @@ static void usage(void) puts (" --proxy=url Optional URL of proxy server to visit"); puts (" May be specified multiple times"); printf(" --reg-timeout=SEC Optional registration interval (default %d)\n", - PJSUA_REG_INTERVAL); + PJSUA_REG_INTERVAL); printf(" --rereg-delay=SEC Optional auto retry registration interval (default %d)\n", - PJSUA_REG_RETRY_INTERVAL); + PJSUA_REG_RETRY_INTERVAL); puts (" --reg-use-proxy=N Control the use of proxy settings in REGISTER."); puts (" 0=no proxy, 1=outbound only, 2=acc only, 3=all (default)"); puts (" --publish Send presence PUBLISH for this account"); @@ -79,7 +78,7 @@ static void usage(void) puts (" --use-timer=N Use SIP session timers? (default=1)"); puts (" 0:inactive, 1:optional, 2:mandatory, 3:always"); printf(" --timer-se=N Session timers expiration period, in secs (def:%d)\n", - PJSIP_SESS_TIMER_DEF_SE); + PJSIP_SESS_TIMER_DEF_SE); puts (" --timer-min-se=N Session timers minimum expiration period, in secs (def:90)"); puts (" --outb-rid=string Set SIP outbound reg-id (default:1)"); puts (" --auto-update-nat=N Where N is 0 or 1 to enable/disable SIP traversal behind"); @@ -148,21 +147,21 @@ static void usage(void) puts (" --rec-file=file Open file recorder (extension can be .wav or .mp3)"); puts (" --auto-rec Automatically record conversation"); puts (" --quality=N Specify media quality (0-10, default=" - xstr(PJSUA_DEFAULT_CODEC_QUALITY) ")"); + xstr(PJSUA_DEFAULT_CODEC_QUALITY) ")"); puts (" --ptime=MSEC Override codec ptime to MSEC (default=codec specific)"); puts (" --no-vad Disable VAD/silence detector (default=codec specific)"); puts (" --ec-tail=MSEC Set echo canceller tail length (default=" - xstr(PJSUA_DEFAULT_EC_TAIL_LEN) ")"); + xstr(PJSUA_DEFAULT_EC_TAIL_LEN) ")"); puts (" --ec-opt=OPT Select echo canceller algorithm (0=default, "); puts (" 1=speex, 2=suppressor, 3=WebRtc, 4=WebRtc AEC3)"); puts (" --ilbc-mode=MODE Set iLBC codec mode (20 or 30, default is " - xstr(PJSUA_DEFAULT_ILBC_MODE) ")"); + xstr(PJSUA_DEFAULT_ILBC_MODE) ")"); puts (" --capture-dev=id Audio capture device ID (default=-1)"); puts (" --playback-dev=id Audio playback device ID (default=-1)"); puts (" --capture-lat=N Audio capture latency, in ms (default=" - xstr(PJMEDIA_SND_DEFAULT_REC_LATENCY) ")"); + xstr(PJMEDIA_SND_DEFAULT_REC_LATENCY) ")"); puts (" --playback-lat=N Audio playback latency, in ms (default=" - xstr(PJMEDIA_SND_DEFAULT_PLAY_LATENCY) ")"); + xstr(PJMEDIA_SND_DEFAULT_PLAY_LATENCY) ")"); puts (" --snd-auto-close=N Auto close audio device when idle for N secs (default=1)"); puts (" Specify N=-1 to disable this feature."); puts (" Specify N=0 for instant close when unused."); @@ -252,7 +251,7 @@ static void log_writer_nobuf(int level, const char *buffer, int len) * Read command arguments from config file. */ static int read_config_file(pj_pool_t *pool, const char *filename, - int *app_argc, char ***app_argv) + int *app_argc, char ***app_argv) { int i; FILE *fhnd; @@ -268,82 +267,82 @@ static int read_config_file(pj_pool_t *pool, const char *filename, /* Open config file. */ fhnd = fopen(filename, "rt"); if (!fhnd) { - PJ_LOG(1,(THIS_FILE, "Unable to open config file %s", filename)); - fflush(stdout); - return -1; + PJ_LOG(1,(THIS_FILE, "Unable to open config file %s", filename)); + fflush(stdout); + return -1; } /* Scan tokens in the file. */ while (argc < MAX_ARGS && !feof(fhnd)) { - char *token; - char *p; - const char *whitespace = " \t\r\n"; - char cDelimiter; - pj_size_t len; - int token_len; + char *token; + char *p; + const char *whitespace = " \t\r\n"; + char cDelimiter; + pj_size_t len; + int token_len; - pj_bzero(line, sizeof(line)); - if (fgets(line, sizeof(line), fhnd) == NULL) break; + pj_bzero(line, sizeof(line)); + if (fgets(line, sizeof(line), fhnd) == NULL) break; - // Trim ending newlines - len = strlen(line); - if (len > 0 && line[len-1]=='\n') - line[--len] = '\0'; - if (len > 0 && line[len-1]=='\r') - line[--len] = '\0'; + // Trim ending newlines + len = strlen(line); + if (len > 0 && line[len-1]=='\n') + line[--len] = '\0'; + if (len > 0 && line[len-1]=='\r') + line[--len] = '\0'; - if (len==0) continue; + if (len==0) continue; - for (p = line; *p != '\0' && argc < MAX_ARGS; p++) { - // first, scan whitespaces - while (*p != '\0' && strchr(whitespace, *p) != NULL) p++; + for (p = line; *p != '\0' && argc < MAX_ARGS; p++) { + // first, scan whitespaces + while (*p != '\0' && strchr(whitespace, *p) != NULL) p++; - if (*p == '\0') // are we done yet? - break; + if (*p == '\0') // are we done yet? + break; - if (*p == '"' || *p == '\'') { // is token a quoted string - cDelimiter = *p++; // save quote delimiter - token = p; + if (*p == '"' || *p == '\'') { // is token a quoted string + cDelimiter = *p++; // save quote delimiter + token = p; - while (*p != '\0' && *p != cDelimiter) p++; + while (*p != '\0' && *p != cDelimiter) p++; - if (*p == '\0') // found end of the line, but, - cDelimiter = '\0'; // didn't find a matching quote + if (*p == '\0') // found end of the line, but, + cDelimiter = '\0'; // didn't find a matching quote - } else { // token's not a quoted string - token = p; + } else { // token's not a quoted string + token = p; - while (*p != '\0' && strchr(whitespace, *p) == NULL) p++; + while (*p != '\0' && strchr(whitespace, *p) == NULL) p++; - cDelimiter = *p; - } + cDelimiter = *p; + } - *p = '\0'; - token_len = (int)(p-token); + *p = '\0'; + token_len = (int)(p-token); - if (token_len > 0) { - if (*token == '#') - break; // ignore remainder of line + if (token_len > 0) { + if (*token == '#') + break; // ignore remainder of line - argv[argc] = pj_pool_alloc(pool, token_len + 1); - pj_memcpy(argv[argc], token, token_len + 1); - ++argc; - } + argv[argc] = pj_pool_alloc(pool, token_len + 1); + pj_memcpy(argv[argc], token, token_len + 1); + ++argc; + } - *p = cDelimiter; - } + *p = cDelimiter; + } } /* Copy arguments from command line */ for (i=1; i<*app_argc && argc < MAX_ARGS; ++i) - argv[argc++] = (*app_argv)[i]; + argv[argc++] = (*app_argv)[i]; if (argc == MAX_ARGS && (i!=*app_argc || !feof(fhnd))) { - PJ_LOG(1,(THIS_FILE, - "Too many arguments specified in cmd line/config file")); - fflush(stdout); - fclose(fhnd); - return -1; + PJ_LOG(1,(THIS_FILE, + "Too many arguments specified in cmd line/config file")); + fflush(stdout); + fclose(fhnd); + return -1; } fclose(fhnd); @@ -356,198 +355,198 @@ static int read_config_file(pj_pool_t *pool, const char *filename, /* Parse arguments. */ static pj_status_t parse_args(int argc, char *argv[], - pj_str_t *uri_to_call) + pj_str_t *uri_to_call) { int c; int option_index; pjsua_app_config *cfg = &app_config; enum { OPT_CONFIG_FILE=127, OPT_LOG_FILE, OPT_LOG_LEVEL, OPT_APP_LOG_LEVEL, - OPT_LOG_APPEND, OPT_COLOR, OPT_NO_COLOR, OPT_LIGHT_BG, OPT_NO_STDERR, - OPT_HELP, OPT_VERSION, OPT_NULL_AUDIO, OPT_SND_AUTO_CLOSE, - OPT_LOCAL_PORT, OPT_IP_ADDR, OPT_PROXY, OPT_OUTBOUND_PROXY, - OPT_REGISTRAR, OPT_REG_TIMEOUT, OPT_PUBLISH, OPT_ID, OPT_CONTACT, - OPT_BOUND_ADDR, OPT_CONTACT_PARAMS, OPT_CONTACT_URI_PARAMS, - OPT_100REL, OPT_USE_IMS, OPT_REALM, OPT_USERNAME, OPT_PASSWORD, - OPT_REG_RETRY_INTERVAL, OPT_REG_USE_PROXY, - OPT_MWI, OPT_NAMESERVER, OPT_STUN_SRV, OPT_UPNP, OPT_OUTB_RID, - OPT_ADD_BUDDY, OPT_OFFER_X_MS_MSG, OPT_NO_PRESENCE, - OPT_AUTO_ANSWER, OPT_AUTO_PLAY, OPT_AUTO_PLAY_HANGUP, OPT_AUTO_LOOP, - OPT_AUTO_CONF, OPT_CLOCK_RATE, OPT_SND_CLOCK_RATE, OPT_STEREO, - OPT_USE_ICE, OPT_ICE_REGULAR, OPT_ICE_TRICKLE, - OPT_USE_SRTP, OPT_SRTP_SECURE, - OPT_USE_TURN, OPT_ICE_MAX_HOSTS, OPT_ICE_NO_RTCP, OPT_TURN_SRV, - OPT_TURN_TCP, OPT_TURN_USER, OPT_TURN_PASSWD, OPT_TURN_TLS, - OPT_TURN_TLS_CA_FILE, OPT_TURN_TLS_CERT_FILE, - OPT_TURN_TLS_NEG_TIMEOUT, OPT_TURN_TLS_CIPHER, - OPT_TURN_TLS_PRIV_FILE, OPT_TURN_TLS_PASSWORD, - OPT_RTCP_MUX, OPT_SRTP_KEYING, - OPT_PLAY_FILE, OPT_PLAY_TONE, OPT_RTP_PORT, OPT_ADD_CODEC, - OPT_ILBC_MODE, OPT_REC_FILE, OPT_AUTO_REC, - OPT_COMPLEXITY, OPT_QUALITY, OPT_PTIME, OPT_NO_VAD, - OPT_RX_DROP_PCT, OPT_TX_DROP_PCT, OPT_EC_TAIL, OPT_EC_OPT, - OPT_NEXT_ACCOUNT, OPT_NEXT_CRED, OPT_MAX_CALLS, - OPT_DURATION, OPT_NO_TCP, OPT_NO_UDP, OPT_THREAD_CNT, - OPT_NOREFERSUB, OPT_ACCEPT_REDIRECT, - OPT_USE_TLS, OPT_TLS_CA_FILE, OPT_TLS_CERT_FILE, OPT_TLS_PRIV_FILE, - OPT_TLS_PASSWORD, OPT_TLS_VERIFY_SERVER, OPT_TLS_VERIFY_CLIENT, - OPT_TLS_NEG_TIMEOUT, OPT_TLS_CIPHER, - OPT_CAPTURE_DEV, OPT_PLAYBACK_DEV, - OPT_CAPTURE_LAT, OPT_PLAYBACK_LAT, OPT_NO_TONES, OPT_JB_MAX_SIZE, - OPT_STDOUT_REFRESH, OPT_STDOUT_REFRESH_TEXT, OPT_IPV6, OPT_QOS, + OPT_LOG_APPEND, OPT_COLOR, OPT_NO_COLOR, OPT_LIGHT_BG, OPT_NO_STDERR, + OPT_HELP, OPT_VERSION, OPT_NULL_AUDIO, OPT_SND_AUTO_CLOSE, + OPT_LOCAL_PORT, OPT_IP_ADDR, OPT_PROXY, OPT_OUTBOUND_PROXY, + OPT_REGISTRAR, OPT_REG_TIMEOUT, OPT_PUBLISH, OPT_ID, OPT_CONTACT, + OPT_BOUND_ADDR, OPT_CONTACT_PARAMS, OPT_CONTACT_URI_PARAMS, + OPT_100REL, OPT_USE_IMS, OPT_REALM, OPT_USERNAME, OPT_PASSWORD, + OPT_REG_RETRY_INTERVAL, OPT_REG_USE_PROXY, + OPT_MWI, OPT_NAMESERVER, OPT_STUN_SRV, OPT_UPNP, OPT_OUTB_RID, + OPT_ADD_BUDDY, OPT_OFFER_X_MS_MSG, OPT_NO_PRESENCE, + OPT_AUTO_ANSWER, OPT_AUTO_PLAY, OPT_AUTO_PLAY_HANGUP, OPT_AUTO_LOOP, + OPT_AUTO_CONF, OPT_CLOCK_RATE, OPT_SND_CLOCK_RATE, OPT_STEREO, + OPT_USE_ICE, OPT_ICE_REGULAR, OPT_ICE_TRICKLE, + OPT_USE_SRTP, OPT_SRTP_SECURE, + OPT_USE_TURN, OPT_ICE_MAX_HOSTS, OPT_ICE_NO_RTCP, OPT_TURN_SRV, + OPT_TURN_TCP, OPT_TURN_USER, OPT_TURN_PASSWD, OPT_TURN_TLS, + OPT_TURN_TLS_CA_FILE, OPT_TURN_TLS_CERT_FILE, + OPT_TURN_TLS_NEG_TIMEOUT, OPT_TURN_TLS_CIPHER, + OPT_TURN_TLS_PRIV_FILE, OPT_TURN_TLS_PASSWORD, + OPT_RTCP_MUX, OPT_SRTP_KEYING, + OPT_PLAY_FILE, OPT_PLAY_TONE, OPT_RTP_PORT, OPT_ADD_CODEC, + OPT_ILBC_MODE, OPT_REC_FILE, OPT_AUTO_REC, + OPT_COMPLEXITY, OPT_QUALITY, OPT_PTIME, OPT_NO_VAD, + OPT_RX_DROP_PCT, OPT_TX_DROP_PCT, OPT_EC_TAIL, OPT_EC_OPT, + OPT_NEXT_ACCOUNT, OPT_NEXT_CRED, OPT_MAX_CALLS, + OPT_DURATION, OPT_NO_TCP, OPT_NO_UDP, OPT_THREAD_CNT, + OPT_NOREFERSUB, OPT_ACCEPT_REDIRECT, + OPT_USE_TLS, OPT_TLS_CA_FILE, OPT_TLS_CERT_FILE, OPT_TLS_PRIV_FILE, + OPT_TLS_PASSWORD, OPT_TLS_VERIFY_SERVER, OPT_TLS_VERIFY_CLIENT, + OPT_TLS_NEG_TIMEOUT, OPT_TLS_CIPHER, + OPT_CAPTURE_DEV, OPT_PLAYBACK_DEV, + OPT_CAPTURE_LAT, OPT_PLAYBACK_LAT, OPT_NO_TONES, OPT_JB_MAX_SIZE, + OPT_STDOUT_REFRESH, OPT_STDOUT_REFRESH_TEXT, OPT_IPV6, OPT_QOS, #ifdef _IONBF - OPT_STDOUT_NO_BUF, + OPT_STDOUT_NO_BUF, #endif - OPT_AUTO_UPDATE_NAT,OPT_USE_COMPACT_FORM,OPT_DIS_CODEC, - OPT_DISABLE_STUN, OPT_NO_FORCE_LR, - OPT_TIMER, OPT_TIMER_SE, OPT_TIMER_MIN_SE, - OPT_VIDEO, OPT_EXTRA_AUDIO, - OPT_VCAPTURE_DEV, OPT_VRENDER_DEV, OPT_PLAY_AVI, OPT_AUTO_PLAY_AVI, - OPT_USE_CLI, OPT_CLI_TELNET_PORT, OPT_DISABLE_CLI_CONSOLE + OPT_AUTO_UPDATE_NAT,OPT_USE_COMPACT_FORM,OPT_DIS_CODEC, + OPT_DISABLE_STUN, OPT_NO_FORCE_LR, + OPT_TIMER, OPT_TIMER_SE, OPT_TIMER_MIN_SE, + OPT_VIDEO, OPT_EXTRA_AUDIO, + OPT_VCAPTURE_DEV, OPT_VRENDER_DEV, OPT_PLAY_AVI, OPT_AUTO_PLAY_AVI, + OPT_USE_CLI, OPT_CLI_TELNET_PORT, OPT_DISABLE_CLI_CONSOLE }; struct pj_getopt_option long_options[] = { - { "config-file",1, 0, OPT_CONFIG_FILE}, - { "log-file", 1, 0, OPT_LOG_FILE}, - { "log-level", 1, 0, OPT_LOG_LEVEL}, - { "app-log-level",1,0,OPT_APP_LOG_LEVEL}, - { "log-append", 0, 0, OPT_LOG_APPEND}, - { "color", 0, 0, OPT_COLOR}, - { "no-color", 0, 0, OPT_NO_COLOR}, - { "light-bg", 0, 0, OPT_LIGHT_BG}, - { "no-stderr", 0, 0, OPT_NO_STDERR}, - { "help", 0, 0, OPT_HELP}, - { "version", 0, 0, OPT_VERSION}, - { "clock-rate", 1, 0, OPT_CLOCK_RATE}, - { "snd-clock-rate", 1, 0, OPT_SND_CLOCK_RATE}, - { "stereo", 0, 0, OPT_STEREO}, - { "null-audio", 0, 0, OPT_NULL_AUDIO}, - { "local-port", 1, 0, OPT_LOCAL_PORT}, - { "ip-addr", 1, 0, OPT_IP_ADDR}, - { "bound-addr", 1, 0, OPT_BOUND_ADDR}, - { "no-tcp", 0, 0, OPT_NO_TCP}, - { "no-udp", 0, 0, OPT_NO_UDP}, - { "norefersub", 0, 0, OPT_NOREFERSUB}, - { "proxy", 1, 0, OPT_PROXY}, - { "outbound", 1, 0, OPT_OUTBOUND_PROXY}, - { "registrar", 1, 0, OPT_REGISTRAR}, - { "reg-timeout",1, 0, OPT_REG_TIMEOUT}, - { "publish", 0, 0, OPT_PUBLISH}, - { "mwi", 0, 0, OPT_MWI}, - { "use-100rel", 0, 0, OPT_100REL}, - { "use-ims", 0, 0, OPT_USE_IMS}, - { "id", 1, 0, OPT_ID}, - { "contact", 1, 0, OPT_CONTACT}, - { "contact-params",1,0, OPT_CONTACT_PARAMS}, - { "contact-uri-params",1,0, OPT_CONTACT_URI_PARAMS}, - { "auto-update-nat", 1, 0, OPT_AUTO_UPDATE_NAT}, - { "disable-stun",0,0, OPT_DISABLE_STUN}, - { "use-compact-form", 0, 0, OPT_USE_COMPACT_FORM}, - { "accept-redirect", 1, 0, OPT_ACCEPT_REDIRECT}, - { "no-force-lr",0, 0, OPT_NO_FORCE_LR}, - { "realm", 1, 0, OPT_REALM}, - { "username", 1, 0, OPT_USERNAME}, - { "password", 1, 0, OPT_PASSWORD}, - { "rereg-delay",1, 0, OPT_REG_RETRY_INTERVAL}, - { "reg-use-proxy", 1, 0, OPT_REG_USE_PROXY}, - { "nameserver", 1, 0, OPT_NAMESERVER}, - { "stun-srv", 1, 0, OPT_STUN_SRV}, - { "upnp", 2, 0, OPT_UPNP}, - { "add-buddy", 1, 0, OPT_ADD_BUDDY}, - { "offer-x-ms-msg",0,0,OPT_OFFER_X_MS_MSG}, - { "no-presence", 0, 0, OPT_NO_PRESENCE}, - { "auto-answer",1, 0, OPT_AUTO_ANSWER}, - { "auto-play", 0, 0, OPT_AUTO_PLAY}, - { "auto-play-hangup",0, 0, OPT_AUTO_PLAY_HANGUP}, - { "auto-rec", 0, 0, OPT_AUTO_REC}, - { "auto-loop", 0, 0, OPT_AUTO_LOOP}, - { "auto-conf", 0, 0, OPT_AUTO_CONF}, - { "play-file", 1, 0, OPT_PLAY_FILE}, - { "play-tone", 1, 0, OPT_PLAY_TONE}, - { "rec-file", 1, 0, OPT_REC_FILE}, - { "rtp-port", 1, 0, OPT_RTP_PORT}, - - { "use-ice", 0, 0, OPT_USE_ICE}, - { "ice-regular",0, 0, OPT_ICE_REGULAR}, - { "ice-trickle",1, 0, OPT_ICE_TRICKLE}, - { "ice-max-hosts",1, 0, OPT_ICE_MAX_HOSTS}, - { "ice-no-rtcp",0, 0, OPT_ICE_NO_RTCP}, - { "use-turn", 0, 0, OPT_USE_TURN}, - { "turn-srv", 1, 0, OPT_TURN_SRV}, - { "turn-tcp", 0, 0, OPT_TURN_TCP}, + { "config-file",1, 0, OPT_CONFIG_FILE}, + { "log-file", 1, 0, OPT_LOG_FILE}, + { "log-level", 1, 0, OPT_LOG_LEVEL}, + { "app-log-level",1,0,OPT_APP_LOG_LEVEL}, + { "log-append", 0, 0, OPT_LOG_APPEND}, + { "color", 0, 0, OPT_COLOR}, + { "no-color", 0, 0, OPT_NO_COLOR}, + { "light-bg", 0, 0, OPT_LIGHT_BG}, + { "no-stderr", 0, 0, OPT_NO_STDERR}, + { "help", 0, 0, OPT_HELP}, + { "version", 0, 0, OPT_VERSION}, + { "clock-rate", 1, 0, OPT_CLOCK_RATE}, + { "snd-clock-rate", 1, 0, OPT_SND_CLOCK_RATE}, + { "stereo", 0, 0, OPT_STEREO}, + { "null-audio", 0, 0, OPT_NULL_AUDIO}, + { "local-port", 1, 0, OPT_LOCAL_PORT}, + { "ip-addr", 1, 0, OPT_IP_ADDR}, + { "bound-addr", 1, 0, OPT_BOUND_ADDR}, + { "no-tcp", 0, 0, OPT_NO_TCP}, + { "no-udp", 0, 0, OPT_NO_UDP}, + { "norefersub", 0, 0, OPT_NOREFERSUB}, + { "proxy", 1, 0, OPT_PROXY}, + { "outbound", 1, 0, OPT_OUTBOUND_PROXY}, + { "registrar", 1, 0, OPT_REGISTRAR}, + { "reg-timeout",1, 0, OPT_REG_TIMEOUT}, + { "publish", 0, 0, OPT_PUBLISH}, + { "mwi", 0, 0, OPT_MWI}, + { "use-100rel", 0, 0, OPT_100REL}, + { "use-ims", 0, 0, OPT_USE_IMS}, + { "id", 1, 0, OPT_ID}, + { "contact", 1, 0, OPT_CONTACT}, + { "contact-params",1,0, OPT_CONTACT_PARAMS}, + { "contact-uri-params",1,0, OPT_CONTACT_URI_PARAMS}, + { "auto-update-nat", 1, 0, OPT_AUTO_UPDATE_NAT}, + { "disable-stun",0,0, OPT_DISABLE_STUN}, + { "use-compact-form", 0, 0, OPT_USE_COMPACT_FORM}, + { "accept-redirect", 1, 0, OPT_ACCEPT_REDIRECT}, + { "no-force-lr",0, 0, OPT_NO_FORCE_LR}, + { "realm", 1, 0, OPT_REALM}, + { "username", 1, 0, OPT_USERNAME}, + { "password", 1, 0, OPT_PASSWORD}, + { "rereg-delay",1, 0, OPT_REG_RETRY_INTERVAL}, + { "reg-use-proxy", 1, 0, OPT_REG_USE_PROXY}, + { "nameserver", 1, 0, OPT_NAMESERVER}, + { "stun-srv", 1, 0, OPT_STUN_SRV}, + { "upnp", 2, 0, OPT_UPNP}, + { "add-buddy", 1, 0, OPT_ADD_BUDDY}, + { "offer-x-ms-msg",0,0,OPT_OFFER_X_MS_MSG}, + { "no-presence", 0, 0, OPT_NO_PRESENCE}, + { "auto-answer",1, 0, OPT_AUTO_ANSWER}, + { "auto-play", 0, 0, OPT_AUTO_PLAY}, + { "auto-play-hangup",0, 0, OPT_AUTO_PLAY_HANGUP}, + { "auto-rec", 0, 0, OPT_AUTO_REC}, + { "auto-loop", 0, 0, OPT_AUTO_LOOP}, + { "auto-conf", 0, 0, OPT_AUTO_CONF}, + { "play-file", 1, 0, OPT_PLAY_FILE}, + { "play-tone", 1, 0, OPT_PLAY_TONE}, + { "rec-file", 1, 0, OPT_REC_FILE}, + { "rtp-port", 1, 0, OPT_RTP_PORT}, + + { "use-ice", 0, 0, OPT_USE_ICE}, + { "ice-regular",0, 0, OPT_ICE_REGULAR}, + { "ice-trickle",1, 0, OPT_ICE_TRICKLE}, + { "ice-max-hosts",1, 0, OPT_ICE_MAX_HOSTS}, + { "ice-no-rtcp",0, 0, OPT_ICE_NO_RTCP}, + { "use-turn", 0, 0, OPT_USE_TURN}, + { "turn-srv", 1, 0, OPT_TURN_SRV}, + { "turn-tcp", 0, 0, OPT_TURN_TCP}, #if PJ_HAS_SSL_SOCK - { "turn-tls", 0, 0, OPT_TURN_TLS}, - { "turn-tls-ca-file",1, 0, OPT_TURN_TLS_CA_FILE}, - { "turn-tls-cert-file",1,0, OPT_TURN_TLS_CERT_FILE}, - { "turn-tls-privkey-file",1,0, OPT_TURN_TLS_PRIV_FILE}, - { "turn-tls-privkey-pwd",1,0, OPT_TURN_TLS_PASSWORD}, - { "turn-tls-neg-timeout", 1, 0, OPT_TURN_TLS_NEG_TIMEOUT}, - { "turn-tls-cipher", 1, 0, OPT_TURN_TLS_CIPHER}, + { "turn-tls", 0, 0, OPT_TURN_TLS}, + { "turn-tls-ca-file",1, 0, OPT_TURN_TLS_CA_FILE}, + { "turn-tls-cert-file",1,0, OPT_TURN_TLS_CERT_FILE}, + { "turn-tls-privkey-file",1,0, OPT_TURN_TLS_PRIV_FILE}, + { "turn-tls-privkey-pwd",1,0, OPT_TURN_TLS_PASSWORD}, + { "turn-tls-neg-timeout", 1, 0, OPT_TURN_TLS_NEG_TIMEOUT}, + { "turn-tls-cipher", 1, 0, OPT_TURN_TLS_CIPHER}, #endif - { "turn-user", 1, 0, OPT_TURN_USER}, - { "turn-passwd",1, 0, OPT_TURN_PASSWD}, - { "rtcp-mux", 0, 0, OPT_RTCP_MUX}, + { "turn-user", 1, 0, OPT_TURN_USER}, + { "turn-passwd",1, 0, OPT_TURN_PASSWD}, + { "rtcp-mux", 0, 0, OPT_RTCP_MUX}, #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - { "use-srtp", 1, 0, OPT_USE_SRTP}, - { "srtp-secure",1, 0, OPT_SRTP_SECURE}, - { "srtp-keying",1, 0, OPT_SRTP_KEYING}, + { "use-srtp", 1, 0, OPT_USE_SRTP}, + { "srtp-secure",1, 0, OPT_SRTP_SECURE}, + { "srtp-keying",1, 0, OPT_SRTP_KEYING}, #endif - { "add-codec", 1, 0, OPT_ADD_CODEC}, - { "dis-codec", 1, 0, OPT_DIS_CODEC}, - { "complexity", 1, 0, OPT_COMPLEXITY}, - { "quality", 1, 0, OPT_QUALITY}, - { "ptime", 1, 0, OPT_PTIME}, - { "no-vad", 0, 0, OPT_NO_VAD}, - { "ec-tail", 1, 0, OPT_EC_TAIL}, - { "ec-opt", 1, 0, OPT_EC_OPT}, - { "ilbc-mode", 1, 0, OPT_ILBC_MODE}, - { "rx-drop-pct",1, 0, OPT_RX_DROP_PCT}, - { "tx-drop-pct",1, 0, OPT_TX_DROP_PCT}, - { "next-account",0,0, OPT_NEXT_ACCOUNT}, - { "next-cred", 0, 0, OPT_NEXT_CRED}, - { "max-calls", 1, 0, OPT_MAX_CALLS}, - { "duration", 1, 0, OPT_DURATION}, - { "thread-cnt", 1, 0, OPT_THREAD_CNT}, + { "add-codec", 1, 0, OPT_ADD_CODEC}, + { "dis-codec", 1, 0, OPT_DIS_CODEC}, + { "complexity", 1, 0, OPT_COMPLEXITY}, + { "quality", 1, 0, OPT_QUALITY}, + { "ptime", 1, 0, OPT_PTIME}, + { "no-vad", 0, 0, OPT_NO_VAD}, + { "ec-tail", 1, 0, OPT_EC_TAIL}, + { "ec-opt", 1, 0, OPT_EC_OPT}, + { "ilbc-mode", 1, 0, OPT_ILBC_MODE}, + { "rx-drop-pct",1, 0, OPT_RX_DROP_PCT}, + { "tx-drop-pct",1, 0, OPT_TX_DROP_PCT}, + { "next-account",0,0, OPT_NEXT_ACCOUNT}, + { "next-cred", 0, 0, OPT_NEXT_CRED}, + { "max-calls", 1, 0, OPT_MAX_CALLS}, + { "duration", 1, 0, OPT_DURATION}, + { "thread-cnt", 1, 0, OPT_THREAD_CNT}, #if defined(PJSIP_HAS_TLS_TRANSPORT) && (PJSIP_HAS_TLS_TRANSPORT != 0) - { "use-tls", 0, 0, OPT_USE_TLS}, - { "tls-ca-file",1, 0, OPT_TLS_CA_FILE}, - { "tls-cert-file",1,0, OPT_TLS_CERT_FILE}, - { "tls-privkey-file",1,0, OPT_TLS_PRIV_FILE}, - { "tls-password",1,0, OPT_TLS_PASSWORD}, - { "tls-verify-server", 0, 0, OPT_TLS_VERIFY_SERVER}, - { "tls-verify-client", 0, 0, OPT_TLS_VERIFY_CLIENT}, - { "tls-neg-timeout", 1, 0, OPT_TLS_NEG_TIMEOUT}, - { "tls-cipher", 1, 0, OPT_TLS_CIPHER}, + { "use-tls", 0, 0, OPT_USE_TLS}, + { "tls-ca-file",1, 0, OPT_TLS_CA_FILE}, + { "tls-cert-file",1,0, OPT_TLS_CERT_FILE}, + { "tls-privkey-file",1,0, OPT_TLS_PRIV_FILE}, + { "tls-password",1,0, OPT_TLS_PASSWORD}, + { "tls-verify-server", 0, 0, OPT_TLS_VERIFY_SERVER}, + { "tls-verify-client", 0, 0, OPT_TLS_VERIFY_CLIENT}, + { "tls-neg-timeout", 1, 0, OPT_TLS_NEG_TIMEOUT}, + { "tls-cipher", 1, 0, OPT_TLS_CIPHER}, #endif - { "capture-dev", 1, 0, OPT_CAPTURE_DEV}, - { "playback-dev", 1, 0, OPT_PLAYBACK_DEV}, - { "capture-lat", 1, 0, OPT_CAPTURE_LAT}, - { "playback-lat", 1, 0, OPT_PLAYBACK_LAT}, - { "stdout-refresh", 1, 0, OPT_STDOUT_REFRESH}, - { "stdout-refresh-text", 1, 0, OPT_STDOUT_REFRESH_TEXT}, + { "capture-dev", 1, 0, OPT_CAPTURE_DEV}, + { "playback-dev", 1, 0, OPT_PLAYBACK_DEV}, + { "capture-lat", 1, 0, OPT_CAPTURE_LAT}, + { "playback-lat", 1, 0, OPT_PLAYBACK_LAT}, + { "stdout-refresh", 1, 0, OPT_STDOUT_REFRESH}, + { "stdout-refresh-text", 1, 0, OPT_STDOUT_REFRESH_TEXT}, #ifdef _IONBF - { "stdout-no-buf", 0, 0, OPT_STDOUT_NO_BUF }, + { "stdout-no-buf", 0, 0, OPT_STDOUT_NO_BUF }, #endif - { "snd-auto-close", 1, 0, OPT_SND_AUTO_CLOSE}, - { "no-tones", 0, 0, OPT_NO_TONES}, - { "jb-max-size", 1, 0, OPT_JB_MAX_SIZE}, + { "snd-auto-close", 1, 0, OPT_SND_AUTO_CLOSE}, + { "no-tones", 0, 0, OPT_NO_TONES}, + { "jb-max-size", 1, 0, OPT_JB_MAX_SIZE}, #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6 - { "ipv6", 0, 0, OPT_IPV6}, + { "ipv6", 0, 0, OPT_IPV6}, #endif - { "set-qos", 0, 0, OPT_QOS}, - { "use-timer", 1, 0, OPT_TIMER}, - { "timer-se", 1, 0, OPT_TIMER_SE}, - { "timer-min-se", 1, 0, OPT_TIMER_MIN_SE}, - { "outb-rid", 1, 0, OPT_OUTB_RID}, - { "video", 0, 0, OPT_VIDEO}, - { "extra-audio",0, 0, OPT_EXTRA_AUDIO}, - { "vcapture-dev", 1, 0, OPT_VCAPTURE_DEV}, - { "vrender-dev", 1, 0, OPT_VRENDER_DEV}, - { "play-avi", 1, 0, OPT_PLAY_AVI}, - { "auto-play-avi", 0, 0, OPT_AUTO_PLAY_AVI}, - { "use-cli", 0, 0, OPT_USE_CLI}, - { "cli-telnet-port", 1, 0, OPT_CLI_TELNET_PORT}, - { "no-cli-console", 0, 0, OPT_DISABLE_CLI_CONSOLE}, - { NULL, 0, 0, 0} + { "set-qos", 0, 0, OPT_QOS}, + { "use-timer", 1, 0, OPT_TIMER}, + { "timer-se", 1, 0, OPT_TIMER_SE}, + { "timer-min-se", 1, 0, OPT_TIMER_MIN_SE}, + { "outb-rid", 1, 0, OPT_OUTB_RID}, + { "video", 0, 0, OPT_VIDEO}, + { "extra-audio",0, 0, OPT_EXTRA_AUDIO}, + { "vcapture-dev", 1, 0, OPT_VCAPTURE_DEV}, + { "vrender-dev", 1, 0, OPT_VRENDER_DEV}, + { "play-avi", 1, 0, OPT_PLAY_AVI}, + { "auto-play-avi", 0, 0, OPT_AUTO_PLAY_AVI}, + { "use-cli", 0, 0, OPT_USE_CLI}, + { "cli-telnet-port", 1, 0, OPT_CLI_TELNET_PORT}, + { "no-cli-console", 0, 0, OPT_DISABLE_CLI_CONSOLE}, + { NULL, 0, 0, 0} }; pj_status_t status; pjsua_acc_config *cur_acc; @@ -557,21 +556,21 @@ static pj_status_t parse_args(int argc, char *argv[], /* Run pj_getopt once to see if user specifies config file to read. */ pj_optind = 0; while ((c=pj_getopt_long(argc, argv, "", long_options, - &option_index)) != -1) + &option_index)) != -1) { - switch (c) { - case OPT_CONFIG_FILE: - config_file = pj_optarg; - break; - } - if (config_file) - break; + switch (c) { + case OPT_CONFIG_FILE: + config_file = pj_optarg; + break; + } + if (config_file) + break; } if (config_file) { - status = read_config_file(cfg->pool, config_file, &argc, &argv); - if (status != 0) - return status; + status = read_config_file(cfg->pool, config_file, &argc, &argv); + if (status != 0) + return status; } cfg->acc_cnt = 0; @@ -583,1013 +582,1013 @@ static pj_status_t parse_args(int argc, char *argv[], */ pj_optind = 0; while((c=pj_getopt_long(argc,argv, "", long_options,&option_index))!=-1) { - pj_str_t tmp; - long lval; - - switch (c) { - - case OPT_CONFIG_FILE: - /* Ignore as this has been processed before */ - break; - - case OPT_LOG_FILE: - cfg->log_cfg.log_filename = pj_str(pj_optarg); - break; - - case OPT_LOG_LEVEL: - c = (int)pj_strtoul(pj_cstr(&tmp, pj_optarg)); - if (c < 0 || c > 6) { - PJ_LOG(1,(THIS_FILE, - "Error: expecting integer value 0-6 " - "for --log-level")); - return PJ_EINVAL; - } - cfg->log_cfg.level = c; - pj_log_set_level( c ); - break; - - case OPT_APP_LOG_LEVEL: - cfg->log_cfg.console_level = (unsigned)pj_strtoul(pj_cstr(&tmp, pj_optarg)); - if (cfg->log_cfg.console_level > 6) { - PJ_LOG(1,(THIS_FILE, - "Error: expecting integer value 0-6 " - "for --app-log-level")); - return PJ_EINVAL; - } - break; - - case OPT_LOG_APPEND: - cfg->log_cfg.log_file_flags |= PJ_O_APPEND; - break; - - case OPT_COLOR: - cfg->log_cfg.decor |= PJ_LOG_HAS_COLOR; - break; - - case OPT_NO_COLOR: - cfg->log_cfg.decor &= ~PJ_LOG_HAS_COLOR; - break; - - case OPT_LIGHT_BG: - pj_log_set_color(1, PJ_TERM_COLOR_R); - pj_log_set_color(2, PJ_TERM_COLOR_R | PJ_TERM_COLOR_G); - pj_log_set_color(3, PJ_TERM_COLOR_B | PJ_TERM_COLOR_G); - pj_log_set_color(4, 0); - pj_log_set_color(5, 0); - pj_log_set_color(77, 0); - break; - - case OPT_NO_STDERR: + pj_str_t tmp; + long lval; + + switch (c) { + + case OPT_CONFIG_FILE: + /* Ignore as this has been processed before */ + break; + + case OPT_LOG_FILE: + cfg->log_cfg.log_filename = pj_str(pj_optarg); + break; + + case OPT_LOG_LEVEL: + c = (int)pj_strtoul(pj_cstr(&tmp, pj_optarg)); + if (c < 0 || c > 6) { + PJ_LOG(1,(THIS_FILE, + "Error: expecting integer value 0-6 " + "for --log-level")); + return PJ_EINVAL; + } + cfg->log_cfg.level = c; + pj_log_set_level( c ); + break; + + case OPT_APP_LOG_LEVEL: + cfg->log_cfg.console_level = (unsigned)pj_strtoul(pj_cstr(&tmp, pj_optarg)); + if (cfg->log_cfg.console_level > 6) { + PJ_LOG(1,(THIS_FILE, + "Error: expecting integer value 0-6 " + "for --app-log-level")); + return PJ_EINVAL; + } + break; + + case OPT_LOG_APPEND: + cfg->log_cfg.log_file_flags |= PJ_O_APPEND; + break; + + case OPT_COLOR: + cfg->log_cfg.decor |= PJ_LOG_HAS_COLOR; + break; + + case OPT_NO_COLOR: + cfg->log_cfg.decor &= ~PJ_LOG_HAS_COLOR; + break; + + case OPT_LIGHT_BG: + pj_log_set_color(1, PJ_TERM_COLOR_R); + pj_log_set_color(2, PJ_TERM_COLOR_R | PJ_TERM_COLOR_G); + pj_log_set_color(3, PJ_TERM_COLOR_B | PJ_TERM_COLOR_G); + pj_log_set_color(4, 0); + pj_log_set_color(5, 0); + pj_log_set_color(77, 0); + break; + + case OPT_NO_STDERR: #if !defined(PJ_WIN32_WINCE) || PJ_WIN32_WINCE==0 - if (!freopen("/dev/null", "w", stderr)) { - PJ_LOG(4,(THIS_FILE, "Failed reopening dev/null")); - } + if (!freopen("/dev/null", "w", stderr)) { + PJ_LOG(4,(THIS_FILE, "Failed reopening dev/null")); + } #endif - break; - - case OPT_HELP: - usage(); - return PJ_EINVAL; - - case OPT_VERSION: /* version */ - if (pj_log_get_level() < 3) - pj_log_set_level(3); - pj_dump_config(); - return PJ_EINVAL; - - case OPT_NULL_AUDIO: - cfg->null_audio = PJ_TRUE; - break; - - case OPT_CLOCK_RATE: - lval = pj_strtoul(pj_cstr(&tmp, pj_optarg)); - if (lval < 8000 || lval > 192000) { - PJ_LOG(1,(THIS_FILE, "Error: expecting value between " - "8000-192000 for conference clock rate")); - return PJ_EINVAL; - } - cfg->media_cfg.clock_rate = (unsigned)lval; - break; - - case OPT_SND_CLOCK_RATE: - lval = pj_strtoul(pj_cstr(&tmp, pj_optarg)); - if (lval < 8000 || lval > 192000) { - PJ_LOG(1,(THIS_FILE, "Error: expecting value between " - "8000-192000 for sound device clock rate")); - return PJ_EINVAL; - } - cfg->media_cfg.snd_clock_rate = (unsigned)lval; - break; - - case OPT_STEREO: - cfg->media_cfg.channel_count = 2; - break; - - case OPT_LOCAL_PORT: /* local-port */ - lval = pj_strtoul(pj_cstr(&tmp, pj_optarg)); - if (lval < 0 || lval > 65535) { - PJ_LOG(1,(THIS_FILE, - "Error: expecting integer value for " - "--local-port")); - return PJ_EINVAL; - } - cfg->udp_cfg.port = (pj_uint16_t)lval; - break; - - case OPT_IP_ADDR: /* ip-addr */ - cfg->udp_cfg.public_addr = pj_str(pj_optarg); - cfg->rtp_cfg.public_addr = pj_str(pj_optarg); - break; - - case OPT_BOUND_ADDR: /* bound-addr */ - cfg->udp_cfg.bound_addr = pj_str(pj_optarg); - cfg->rtp_cfg.bound_addr = pj_str(pj_optarg); - break; - - case OPT_NO_UDP: /* no-udp */ - if (cfg->no_tcp && !cfg->use_tls) { - PJ_LOG(1,(THIS_FILE,"Error: cannot disable both TCP and UDP")); - return PJ_EINVAL; - } - - cfg->no_udp = PJ_TRUE; - break; - - case OPT_NOREFERSUB: /* norefersub */ - cfg->no_refersub = PJ_TRUE; - break; - - case OPT_NO_TCP: /* no-tcp */ - if (cfg->no_udp && !cfg->use_tls) { - PJ_LOG(1,(THIS_FILE,"Error: cannot disable both TCP and UDP")); - return PJ_EINVAL; - } - - cfg->no_tcp = PJ_TRUE; - break; - - case OPT_PROXY: /* proxy */ - if (pjsua_verify_sip_url(pj_optarg) != 0) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid SIP URL '%s' " - "in proxy argument", pj_optarg)); - return PJ_EINVAL; - } - cur_acc->proxy[cur_acc->proxy_cnt++] = pj_str(pj_optarg); - break; - - case OPT_OUTBOUND_PROXY: /* outbound proxy */ - if (pjsua_verify_sip_url(pj_optarg) != 0) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid SIP URL '%s' " - "in outbound proxy argument", pj_optarg)); - return PJ_EINVAL; - } - cfg->cfg.outbound_proxy[cfg->cfg.outbound_proxy_cnt++] = pj_str(pj_optarg); - break; - - case OPT_REGISTRAR: /* registrar */ - if (pjsua_verify_sip_url(pj_optarg) != 0) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid SIP URL '%s' in " - "registrar argument", pj_optarg)); - return PJ_EINVAL; - } - cur_acc->reg_uri = pj_str(pj_optarg); - break; - - case OPT_REG_TIMEOUT: /* reg-timeout */ - cur_acc->reg_timeout = (unsigned)pj_strtoul(pj_cstr(&tmp,pj_optarg)); - if (cur_acc->reg_timeout < 1 || cur_acc->reg_timeout > 3600) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid value for --reg-timeout " - "(expecting 1-3600)")); - return PJ_EINVAL; - } - break; - - case OPT_PUBLISH: /* publish */ - cur_acc->publish_enabled = PJ_TRUE; - break; - - case OPT_MWI: /* mwi */ - cur_acc->mwi_enabled = PJ_TRUE; - break; - - case OPT_100REL: /** 100rel */ - cur_acc->require_100rel = PJSUA_100REL_MANDATORY; - cfg->cfg.require_100rel = PJSUA_100REL_MANDATORY; - break; - - case OPT_TIMER: /** session timer */ - lval = pj_strtoul(pj_cstr(&tmp, pj_optarg)); - if (lval < 0 || lval > 3) { - PJ_LOG(1,(THIS_FILE, - "Error: expecting integer value 0-3 for --use-timer")); - return PJ_EINVAL; - } - cur_acc->use_timer = (pjsua_sip_timer_use)lval; - cfg->cfg.use_timer = (pjsua_sip_timer_use)lval; - break; - - case OPT_TIMER_SE: /** session timer session expiration */ - cur_acc->timer_setting.sess_expires = (unsigned)pj_strtoul(pj_cstr(&tmp, pj_optarg)); - if (cur_acc->timer_setting.sess_expires < 90) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid value for --timer-se " - "(expecting higher than 90)")); - return PJ_EINVAL; - } - cfg->cfg.timer_setting.sess_expires = cur_acc->timer_setting.sess_expires; - break; - - case OPT_TIMER_MIN_SE: /** session timer minimum session expiration */ - cur_acc->timer_setting.min_se = (unsigned)pj_strtoul(pj_cstr(&tmp, pj_optarg)); - if (cur_acc->timer_setting.min_se < 90) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid value for --timer-min-se " - "(expecting higher than 90)")); - return PJ_EINVAL; - } - cfg->cfg.timer_setting.min_se = cur_acc->timer_setting.min_se; - break; - - case OPT_OUTB_RID: /* Outbound reg-id */ - cur_acc->rfc5626_reg_id = pj_str(pj_optarg); - break; - - case OPT_USE_IMS: /* Activate IMS settings */ - cur_acc->auth_pref.initial_auth = PJ_TRUE; - break; - - case OPT_ID: /* id */ - if (pjsua_verify_url(pj_optarg) != 0) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid SIP URL '%s' " - "in local id argument", pj_optarg)); - return PJ_EINVAL; - } - cur_acc->id = pj_str(pj_optarg); - break; - - case OPT_CONTACT: /* contact */ - if (pjsua_verify_sip_url(pj_optarg) != 0) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid SIP URL '%s' " - "in contact argument", pj_optarg)); - return PJ_EINVAL; - } - cur_acc->force_contact = pj_str(pj_optarg); - break; - - case OPT_CONTACT_PARAMS: - cur_acc->contact_params = pj_str(pj_optarg); - break; - - case OPT_CONTACT_URI_PARAMS: - cur_acc->contact_uri_params = pj_str(pj_optarg); - break; - - case OPT_AUTO_UPDATE_NAT: /* OPT_AUTO_UPDATE_NAT */ + break; + + case OPT_HELP: + usage(); + return PJ_EINVAL; + + case OPT_VERSION: /* version */ + if (pj_log_get_level() < 3) + pj_log_set_level(3); + pj_dump_config(); + return PJ_EINVAL; + + case OPT_NULL_AUDIO: + cfg->null_audio = PJ_TRUE; + break; + + case OPT_CLOCK_RATE: + lval = pj_strtoul(pj_cstr(&tmp, pj_optarg)); + if (lval < 8000 || lval > 192000) { + PJ_LOG(1,(THIS_FILE, "Error: expecting value between " + "8000-192000 for conference clock rate")); + return PJ_EINVAL; + } + cfg->media_cfg.clock_rate = (unsigned)lval; + break; + + case OPT_SND_CLOCK_RATE: + lval = pj_strtoul(pj_cstr(&tmp, pj_optarg)); + if (lval < 8000 || lval > 192000) { + PJ_LOG(1,(THIS_FILE, "Error: expecting value between " + "8000-192000 for sound device clock rate")); + return PJ_EINVAL; + } + cfg->media_cfg.snd_clock_rate = (unsigned)lval; + break; + + case OPT_STEREO: + cfg->media_cfg.channel_count = 2; + break; + + case OPT_LOCAL_PORT: /* local-port */ + lval = pj_strtoul(pj_cstr(&tmp, pj_optarg)); + if (lval < 0 || lval > 65535) { + PJ_LOG(1,(THIS_FILE, + "Error: expecting integer value for " + "--local-port")); + return PJ_EINVAL; + } + cfg->udp_cfg.port = (pj_uint16_t)lval; + break; + + case OPT_IP_ADDR: /* ip-addr */ + cfg->udp_cfg.public_addr = pj_str(pj_optarg); + cfg->rtp_cfg.public_addr = pj_str(pj_optarg); + break; + + case OPT_BOUND_ADDR: /* bound-addr */ + cfg->udp_cfg.bound_addr = pj_str(pj_optarg); + cfg->rtp_cfg.bound_addr = pj_str(pj_optarg); + break; + + case OPT_NO_UDP: /* no-udp */ + if (cfg->no_tcp && !cfg->use_tls) { + PJ_LOG(1,(THIS_FILE,"Error: cannot disable both TCP and UDP")); + return PJ_EINVAL; + } + + cfg->no_udp = PJ_TRUE; + break; + + case OPT_NOREFERSUB: /* norefersub */ + cfg->no_refersub = PJ_TRUE; + break; + + case OPT_NO_TCP: /* no-tcp */ + if (cfg->no_udp && !cfg->use_tls) { + PJ_LOG(1,(THIS_FILE,"Error: cannot disable both TCP and UDP")); + return PJ_EINVAL; + } + + cfg->no_tcp = PJ_TRUE; + break; + + case OPT_PROXY: /* proxy */ + if (pjsua_verify_sip_url(pj_optarg) != 0) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid SIP URL '%s' " + "in proxy argument", pj_optarg)); + return PJ_EINVAL; + } + cur_acc->proxy[cur_acc->proxy_cnt++] = pj_str(pj_optarg); + break; + + case OPT_OUTBOUND_PROXY: /* outbound proxy */ + if (pjsua_verify_sip_url(pj_optarg) != 0) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid SIP URL '%s' " + "in outbound proxy argument", pj_optarg)); + return PJ_EINVAL; + } + cfg->cfg.outbound_proxy[cfg->cfg.outbound_proxy_cnt++] = pj_str(pj_optarg); + break; + + case OPT_REGISTRAR: /* registrar */ + if (pjsua_verify_sip_url(pj_optarg) != 0) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid SIP URL '%s' in " + "registrar argument", pj_optarg)); + return PJ_EINVAL; + } + cur_acc->reg_uri = pj_str(pj_optarg); + break; + + case OPT_REG_TIMEOUT: /* reg-timeout */ + cur_acc->reg_timeout = (unsigned)pj_strtoul(pj_cstr(&tmp,pj_optarg)); + if (cur_acc->reg_timeout < 1 || cur_acc->reg_timeout > 3600) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid value for --reg-timeout " + "(expecting 1-3600)")); + return PJ_EINVAL; + } + break; + + case OPT_PUBLISH: /* publish */ + cur_acc->publish_enabled = PJ_TRUE; + break; + + case OPT_MWI: /* mwi */ + cur_acc->mwi_enabled = PJ_TRUE; + break; + + case OPT_100REL: /** 100rel */ + cur_acc->require_100rel = PJSUA_100REL_MANDATORY; + cfg->cfg.require_100rel = PJSUA_100REL_MANDATORY; + break; + + case OPT_TIMER: /** session timer */ + lval = pj_strtoul(pj_cstr(&tmp, pj_optarg)); + if (lval < 0 || lval > 3) { + PJ_LOG(1,(THIS_FILE, + "Error: expecting integer value 0-3 for --use-timer")); + return PJ_EINVAL; + } + cur_acc->use_timer = (pjsua_sip_timer_use)lval; + cfg->cfg.use_timer = (pjsua_sip_timer_use)lval; + break; + + case OPT_TIMER_SE: /** session timer session expiration */ + cur_acc->timer_setting.sess_expires = (unsigned)pj_strtoul(pj_cstr(&tmp, pj_optarg)); + if (cur_acc->timer_setting.sess_expires < 90) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid value for --timer-se " + "(expecting higher than 90)")); + return PJ_EINVAL; + } + cfg->cfg.timer_setting.sess_expires = cur_acc->timer_setting.sess_expires; + break; + + case OPT_TIMER_MIN_SE: /** session timer minimum session expiration */ + cur_acc->timer_setting.min_se = (unsigned)pj_strtoul(pj_cstr(&tmp, pj_optarg)); + if (cur_acc->timer_setting.min_se < 90) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid value for --timer-min-se " + "(expecting higher than 90)")); + return PJ_EINVAL; + } + cfg->cfg.timer_setting.min_se = cur_acc->timer_setting.min_se; + break; + + case OPT_OUTB_RID: /* Outbound reg-id */ + cur_acc->rfc5626_reg_id = pj_str(pj_optarg); + break; + + case OPT_USE_IMS: /* Activate IMS settings */ + cur_acc->auth_pref.initial_auth = PJ_TRUE; + break; + + case OPT_ID: /* id */ + if (pjsua_verify_url(pj_optarg) != 0) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid SIP URL '%s' " + "in local id argument", pj_optarg)); + return PJ_EINVAL; + } + cur_acc->id = pj_str(pj_optarg); + break; + + case OPT_CONTACT: /* contact */ + if (pjsua_verify_sip_url(pj_optarg) != 0) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid SIP URL '%s' " + "in contact argument", pj_optarg)); + return PJ_EINVAL; + } + cur_acc->force_contact = pj_str(pj_optarg); + break; + + case OPT_CONTACT_PARAMS: + cur_acc->contact_params = pj_str(pj_optarg); + break; + + case OPT_CONTACT_URI_PARAMS: + cur_acc->contact_uri_params = pj_str(pj_optarg); + break; + + case OPT_AUTO_UPDATE_NAT: /* OPT_AUTO_UPDATE_NAT */ cur_acc->allow_contact_rewrite = (pj_bool_t)pj_strtoul(pj_cstr(&tmp, pj_optarg)); - break; + break; - case OPT_DISABLE_STUN: - cur_acc->sip_stun_use = PJSUA_STUN_USE_DISABLED; - cur_acc->media_stun_use = PJSUA_STUN_USE_DISABLED; - break; + case OPT_DISABLE_STUN: + cur_acc->sip_stun_use = PJSUA_STUN_USE_DISABLED; + cur_acc->media_stun_use = PJSUA_STUN_USE_DISABLED; + break; - case OPT_USE_COMPACT_FORM: - /* enable compact form - from Ticket #342 */ + case OPT_USE_COMPACT_FORM: + /* enable compact form - from Ticket #342 */ { - extern pj_bool_t pjsip_include_allow_hdr_in_dlg; - extern pj_bool_t pjmedia_add_rtpmap_for_static_pt; - - pjsip_cfg()->endpt.use_compact_form = PJ_TRUE; - /* do not transmit Allow header */ - pjsip_include_allow_hdr_in_dlg = PJ_FALSE; - /* Do not include rtpmap for static payload types (<96) */ - pjmedia_add_rtpmap_for_static_pt = PJ_FALSE; + extern pj_bool_t pjsip_include_allow_hdr_in_dlg; + extern pj_bool_t pjmedia_add_rtpmap_for_static_pt; + + pjsip_cfg()->endpt.use_compact_form = PJ_TRUE; + /* do not transmit Allow header */ + pjsip_include_allow_hdr_in_dlg = PJ_FALSE; + /* Do not include rtpmap for static payload types (<96) */ + pjmedia_add_rtpmap_for_static_pt = PJ_FALSE; } - break; - - case OPT_ACCEPT_REDIRECT: - cfg->redir_op = my_atoi(pj_optarg); - if (cfg->redir_op>PJSIP_REDIRECT_STOP) { - PJ_LOG(1,(THIS_FILE, - "Error: accept-redirect value '%s' ", pj_optarg)); - return PJ_EINVAL; - } - break; - - case OPT_NO_FORCE_LR: - cfg->cfg.force_lr = PJ_FALSE; - break; - - case OPT_NEXT_ACCOUNT: /* Add more account. */ - cfg->acc_cnt++; - cur_acc = &cfg->acc_cfg[cfg->acc_cnt]; - break; - - case OPT_USERNAME: /* Default authentication user */ - cur_acc->cred_info[cur_acc->cred_count].username = pj_str(pj_optarg); - cur_acc->cred_info[cur_acc->cred_count].scheme = pjsip_DIGEST_STR; - break; - - case OPT_REALM: /* Default authentication realm. */ - cur_acc->cred_info[cur_acc->cred_count].realm = pj_str(pj_optarg); - break; - - case OPT_PASSWORD: /* authentication password */ - cur_acc->cred_info[cur_acc->cred_count].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; - cur_acc->cred_info[cur_acc->cred_count].data = pj_str(pj_optarg); + break; + + case OPT_ACCEPT_REDIRECT: + cfg->redir_op = my_atoi(pj_optarg); + if (cfg->redir_op>PJSIP_REDIRECT_STOP) { + PJ_LOG(1,(THIS_FILE, + "Error: accept-redirect value '%s' ", pj_optarg)); + return PJ_EINVAL; + } + break; + + case OPT_NO_FORCE_LR: + cfg->cfg.force_lr = PJ_FALSE; + break; + + case OPT_NEXT_ACCOUNT: /* Add more account. */ + cfg->acc_cnt++; + cur_acc = &cfg->acc_cfg[cfg->acc_cnt]; + break; + + case OPT_USERNAME: /* Default authentication user */ + cur_acc->cred_info[cur_acc->cred_count].username = pj_str(pj_optarg); + cur_acc->cred_info[cur_acc->cred_count].scheme = pjsip_DIGEST_STR; + break; + + case OPT_REALM: /* Default authentication realm. */ + cur_acc->cred_info[cur_acc->cred_count].realm = pj_str(pj_optarg); + break; + + case OPT_PASSWORD: /* authentication password */ + cur_acc->cred_info[cur_acc->cred_count].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; + cur_acc->cred_info[cur_acc->cred_count].data = pj_str(pj_optarg); #if PJSIP_HAS_DIGEST_AKA_AUTH - cur_acc->cred_info[cur_acc->cred_count].data_type |= PJSIP_CRED_DATA_EXT_AKA; - cur_acc->cred_info[cur_acc->cred_count].ext.aka.k = pj_str(pj_optarg); - cur_acc->cred_info[cur_acc->cred_count].ext.aka.cb = &pjsip_auth_create_aka_response; + cur_acc->cred_info[cur_acc->cred_count].data_type |= PJSIP_CRED_DATA_EXT_AKA; + cur_acc->cred_info[cur_acc->cred_count].ext.aka.k = pj_str(pj_optarg); + cur_acc->cred_info[cur_acc->cred_count].ext.aka.cb = &pjsip_auth_create_aka_response; #endif - break; - - case OPT_REG_RETRY_INTERVAL: - cur_acc->reg_retry_interval = (unsigned)pj_strtoul(pj_cstr(&tmp, pj_optarg)); - break; - - case OPT_REG_USE_PROXY: - cur_acc->reg_use_proxy = (unsigned)pj_strtoul(pj_cstr(&tmp, pj_optarg)); - if (cur_acc->reg_use_proxy > 3) { - PJ_LOG(1,(THIS_FILE, "Error: invalid --reg-use-proxy value '%s'", - pj_optarg)); - return PJ_EINVAL; - } - break; - - case OPT_NEXT_CRED: /* next credential */ - cur_acc->cred_count++; - break; - - case OPT_NAMESERVER: /* nameserver */ - cfg->cfg.nameserver[cfg->cfg.nameserver_count++] = pj_str(pj_optarg); - if (cfg->cfg.nameserver_count > PJ_ARRAY_SIZE(cfg->cfg.nameserver)) { - PJ_LOG(1,(THIS_FILE, "Error: too many nameservers")); - return PJ_ETOOMANY; - } - break; - - case OPT_STUN_SRV: /* STUN server */ - cfg->cfg.stun_host = pj_str(pj_optarg); - if (cfg->cfg.stun_srv_cnt==PJ_ARRAY_SIZE(cfg->cfg.stun_srv)) { - PJ_LOG(1,(THIS_FILE, "Error: too many STUN servers")); - return PJ_ETOOMANY; - } - cfg->cfg.stun_srv[cfg->cfg.stun_srv_cnt++] = pj_str(pj_optarg); - break; - - case OPT_UPNP: /* UPnP */ - cfg->cfg.enable_upnp = PJ_TRUE; - cfg->cfg.upnp_if_name = pj_str(pj_optarg); - break; - - case OPT_ADD_BUDDY: /* Add to buddy list. */ - if (pjsua_verify_url(pj_optarg) != 0) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid URL '%s' in " - "--add-buddy option", pj_optarg)); - return -1; - } - if (cfg->buddy_cnt == PJ_ARRAY_SIZE(cfg->buddy_cfg)) { - PJ_LOG(1,(THIS_FILE, - "Error: too many buddies in buddy list.")); - return -1; - } - cfg->buddy_cfg[cfg->buddy_cnt].uri = pj_str(pj_optarg); - cfg->buddy_cnt++; - break; - - case OPT_AUTO_PLAY: - cfg->auto_play = 1; - break; - - case OPT_AUTO_PLAY_HANGUP: - cfg->auto_play_hangup = 1; - break; - - case OPT_AUTO_REC: - cfg->auto_rec = 1; - break; - - case OPT_AUTO_LOOP: - cfg->auto_loop = 1; - break; - - case OPT_AUTO_CONF: - cfg->auto_conf = 1; - break; - - case OPT_PLAY_FILE: - cfg->wav_files[cfg->wav_count++] = pj_str(pj_optarg); - break; - - case OPT_PLAY_TONE: - { - int f1, f2, on, off; - int n; - - n = sscanf(pj_optarg, "%d,%d,%d,%d", &f1, &f2, &on, &off); - if (n != 4) { - puts("Expecting f1,f2,on,off in --play-tone"); - return -1; - } - - cfg->tones[cfg->tone_count].freq1 = (short)f1; - cfg->tones[cfg->tone_count].freq2 = (short)f2; - cfg->tones[cfg->tone_count].on_msec = (short)on; - cfg->tones[cfg->tone_count].off_msec = (short)off; - ++cfg->tone_count; - } - break; - - case OPT_REC_FILE: - cfg->rec_file = pj_str(pj_optarg); - break; - - case OPT_USE_ICE: - cfg->media_cfg.enable_ice = - cur_acc->ice_cfg.enable_ice = PJ_TRUE; - break; - - case OPT_ICE_REGULAR: - cfg->media_cfg.ice_opt.aggressive = - cur_acc->ice_cfg.ice_opt.aggressive = PJ_FALSE; - break; - - case OPT_ICE_TRICKLE: - cfg->media_cfg.ice_opt.trickle = - cur_acc->ice_cfg.ice_opt.trickle = my_atoi(pj_optarg); - - if (!pj_isdigit(*pj_optarg) || cfg->media_cfg.ice_opt.trickle>2) { - PJ_LOG(1,(THIS_FILE, "Invalid value for --ice-trickle option")); - return -1; - } - - /* Automatically disable ICE aggressive mode */ - if (cfg->media_cfg.ice_opt.trickle > 0) { - cfg->media_cfg.ice_opt.aggressive = - cur_acc->ice_cfg.ice_opt.aggressive = PJ_FALSE; - } - break; - - case OPT_USE_TURN: - cfg->media_cfg.enable_turn = - cur_acc->turn_cfg.enable_turn = PJ_TRUE; - break; - - case OPT_ICE_MAX_HOSTS: - cfg->media_cfg.ice_max_host_cands = - cur_acc->ice_cfg.ice_max_host_cands = my_atoi(pj_optarg); - break; - - case OPT_ICE_NO_RTCP: - cfg->media_cfg.ice_no_rtcp = - cur_acc->ice_cfg.ice_no_rtcp = PJ_TRUE; - break; - - case OPT_TURN_SRV: - cfg->media_cfg.turn_server = - cur_acc->turn_cfg.turn_server = pj_str(pj_optarg); - break; - - case OPT_TURN_TCP: - cfg->media_cfg.turn_conn_type = - cur_acc->turn_cfg.turn_conn_type = PJ_TURN_TP_TCP; - break; + break; + + case OPT_REG_RETRY_INTERVAL: + cur_acc->reg_retry_interval = (unsigned)pj_strtoul(pj_cstr(&tmp, pj_optarg)); + break; + + case OPT_REG_USE_PROXY: + cur_acc->reg_use_proxy = (unsigned)pj_strtoul(pj_cstr(&tmp, pj_optarg)); + if (cur_acc->reg_use_proxy > 3) { + PJ_LOG(1,(THIS_FILE, "Error: invalid --reg-use-proxy value '%s'", + pj_optarg)); + return PJ_EINVAL; + } + break; + + case OPT_NEXT_CRED: /* next credential */ + cur_acc->cred_count++; + break; + + case OPT_NAMESERVER: /* nameserver */ + cfg->cfg.nameserver[cfg->cfg.nameserver_count++] = pj_str(pj_optarg); + if (cfg->cfg.nameserver_count > PJ_ARRAY_SIZE(cfg->cfg.nameserver)) { + PJ_LOG(1,(THIS_FILE, "Error: too many nameservers")); + return PJ_ETOOMANY; + } + break; + + case OPT_STUN_SRV: /* STUN server */ + cfg->cfg.stun_host = pj_str(pj_optarg); + if (cfg->cfg.stun_srv_cnt==PJ_ARRAY_SIZE(cfg->cfg.stun_srv)) { + PJ_LOG(1,(THIS_FILE, "Error: too many STUN servers")); + return PJ_ETOOMANY; + } + cfg->cfg.stun_srv[cfg->cfg.stun_srv_cnt++] = pj_str(pj_optarg); + break; + + case OPT_UPNP: /* UPnP */ + cfg->cfg.enable_upnp = PJ_TRUE; + cfg->cfg.upnp_if_name = pj_str(pj_optarg); + break; + + case OPT_ADD_BUDDY: /* Add to buddy list. */ + if (pjsua_verify_url(pj_optarg) != 0) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid URL '%s' in " + "--add-buddy option", pj_optarg)); + return -1; + } + if (cfg->buddy_cnt == PJ_ARRAY_SIZE(cfg->buddy_cfg)) { + PJ_LOG(1,(THIS_FILE, + "Error: too many buddies in buddy list.")); + return -1; + } + cfg->buddy_cfg[cfg->buddy_cnt].uri = pj_str(pj_optarg); + cfg->buddy_cnt++; + break; + + case OPT_AUTO_PLAY: + cfg->auto_play = 1; + break; + + case OPT_AUTO_PLAY_HANGUP: + cfg->auto_play_hangup = 1; + break; + + case OPT_AUTO_REC: + cfg->auto_rec = 1; + break; + + case OPT_AUTO_LOOP: + cfg->auto_loop = 1; + break; + + case OPT_AUTO_CONF: + cfg->auto_conf = 1; + break; + + case OPT_PLAY_FILE: + cfg->wav_files[cfg->wav_count++] = pj_str(pj_optarg); + break; + + case OPT_PLAY_TONE: + { + int f1, f2, on, off; + int n; + + n = sscanf(pj_optarg, "%d,%d,%d,%d", &f1, &f2, &on, &off); + if (n != 4) { + puts("Expecting f1,f2,on,off in --play-tone"); + return -1; + } + + cfg->tones[cfg->tone_count].freq1 = (short)f1; + cfg->tones[cfg->tone_count].freq2 = (short)f2; + cfg->tones[cfg->tone_count].on_msec = (short)on; + cfg->tones[cfg->tone_count].off_msec = (short)off; + ++cfg->tone_count; + } + break; + + case OPT_REC_FILE: + cfg->rec_file = pj_str(pj_optarg); + break; + + case OPT_USE_ICE: + cfg->media_cfg.enable_ice = + cur_acc->ice_cfg.enable_ice = PJ_TRUE; + break; + + case OPT_ICE_REGULAR: + cfg->media_cfg.ice_opt.aggressive = + cur_acc->ice_cfg.ice_opt.aggressive = PJ_FALSE; + break; + + case OPT_ICE_TRICKLE: + cfg->media_cfg.ice_opt.trickle = + cur_acc->ice_cfg.ice_opt.trickle = my_atoi(pj_optarg); + + if (!pj_isdigit(*pj_optarg) || cfg->media_cfg.ice_opt.trickle>2) { + PJ_LOG(1,(THIS_FILE, "Invalid value for --ice-trickle option")); + return -1; + } + + /* Automatically disable ICE aggressive mode */ + if (cfg->media_cfg.ice_opt.trickle > 0) { + cfg->media_cfg.ice_opt.aggressive = + cur_acc->ice_cfg.ice_opt.aggressive = PJ_FALSE; + } + break; + + case OPT_USE_TURN: + cfg->media_cfg.enable_turn = + cur_acc->turn_cfg.enable_turn = PJ_TRUE; + break; + + case OPT_ICE_MAX_HOSTS: + cfg->media_cfg.ice_max_host_cands = + cur_acc->ice_cfg.ice_max_host_cands = my_atoi(pj_optarg); + break; + + case OPT_ICE_NO_RTCP: + cfg->media_cfg.ice_no_rtcp = + cur_acc->ice_cfg.ice_no_rtcp = PJ_TRUE; + break; + + case OPT_TURN_SRV: + cfg->media_cfg.turn_server = + cur_acc->turn_cfg.turn_server = pj_str(pj_optarg); + break; + + case OPT_TURN_TCP: + cfg->media_cfg.turn_conn_type = + cur_acc->turn_cfg.turn_conn_type = PJ_TURN_TP_TCP; + break; #if PJ_HAS_SSL_SOCK - case OPT_TURN_TLS: - cfg->media_cfg.turn_conn_type = - cur_acc->turn_cfg.turn_conn_type = PJ_TURN_TP_TLS; - break; - case OPT_TURN_TLS_CA_FILE: - cfg->media_cfg.turn_tls_setting.ca_list_file = - cur_acc->turn_cfg.turn_tls_setting.ca_list_file = - pj_str(pj_optarg); - break; - - case OPT_TURN_TLS_CERT_FILE: - cfg->media_cfg.turn_tls_setting.cert_file = - cur_acc->turn_cfg.turn_tls_setting.cert_file = - pj_str(pj_optarg); - break; - - case OPT_TURN_TLS_PRIV_FILE: - cfg->media_cfg.turn_tls_setting.privkey_file = - cur_acc->turn_cfg.turn_tls_setting.privkey_file = - pj_str(pj_optarg); - break; - - case OPT_TURN_TLS_PASSWORD: - cfg->media_cfg.turn_tls_setting.password = - cur_acc->turn_cfg.turn_tls_setting.password = - pj_str(pj_optarg); - break; - - case OPT_TURN_TLS_NEG_TIMEOUT: - cfg->media_cfg.turn_tls_setting.ssock_param.timeout.sec = - cur_acc->turn_cfg.turn_tls_setting.ssock_param.timeout.sec = - atoi(pj_optarg); - break; - - case OPT_TURN_TLS_CIPHER: - { - pj_ssl_cipher cipher; - - if (pj_ansi_strnicmp(pj_optarg, "0x", 2) == 0) { - pj_str_t cipher_st = pj_str(pj_optarg + 2); - cipher = (pj_ssl_cipher)pj_strtoul2(&cipher_st, NULL, 16); - } else { - cipher = atoi(pj_optarg); - } - - if (pj_ssl_cipher_is_supported(cipher)) { - static pj_ssl_cipher tls_ciphers[PJ_SSL_SOCK_MAX_CIPHERS]; - pj_ssl_sock_param *ssock_param = - &cfg->media_cfg.turn_tls_setting.ssock_param; - - tls_ciphers[ssock_param->ciphers_num++] = cipher; - ssock_param->ciphers = - cur_acc->turn_cfg.turn_tls_setting.ssock_param.ciphers = - tls_ciphers; - } else { - pj_ssl_cipher ciphers[PJ_SSL_SOCK_MAX_CIPHERS]; - unsigned j, ciphers_cnt; - - ciphers_cnt = PJ_ARRAY_SIZE(ciphers); - pj_ssl_cipher_get_availables(ciphers, &ciphers_cnt); - - PJ_LOG(1,(THIS_FILE, "Cipher \"%s\" is not supported by " - "TLS/SSL backend.", pj_optarg)); - printf("Available TLS/SSL ciphers (%d):\n", ciphers_cnt); - for (j=0; jmedia_cfg.turn_conn_type = + cur_acc->turn_cfg.turn_conn_type = PJ_TURN_TP_TLS; + break; + case OPT_TURN_TLS_CA_FILE: + cfg->media_cfg.turn_tls_setting.ca_list_file = + cur_acc->turn_cfg.turn_tls_setting.ca_list_file = + pj_str(pj_optarg); + break; + + case OPT_TURN_TLS_CERT_FILE: + cfg->media_cfg.turn_tls_setting.cert_file = + cur_acc->turn_cfg.turn_tls_setting.cert_file = + pj_str(pj_optarg); + break; + + case OPT_TURN_TLS_PRIV_FILE: + cfg->media_cfg.turn_tls_setting.privkey_file = + cur_acc->turn_cfg.turn_tls_setting.privkey_file = + pj_str(pj_optarg); + break; + + case OPT_TURN_TLS_PASSWORD: + cfg->media_cfg.turn_tls_setting.password = + cur_acc->turn_cfg.turn_tls_setting.password = + pj_str(pj_optarg); + break; + + case OPT_TURN_TLS_NEG_TIMEOUT: + cfg->media_cfg.turn_tls_setting.ssock_param.timeout.sec = + cur_acc->turn_cfg.turn_tls_setting.ssock_param.timeout.sec = + atoi(pj_optarg); + break; + + case OPT_TURN_TLS_CIPHER: + { + pj_ssl_cipher cipher; + + if (pj_ansi_strnicmp(pj_optarg, "0x", 2) == 0) { + pj_str_t cipher_st = pj_str(pj_optarg + 2); + cipher = (pj_ssl_cipher)pj_strtoul2(&cipher_st, NULL, 16); + } else { + cipher = atoi(pj_optarg); + } + + if (pj_ssl_cipher_is_supported(cipher)) { + static pj_ssl_cipher tls_ciphers[PJ_SSL_SOCK_MAX_CIPHERS]; + pj_ssl_sock_param *ssock_param = + &cfg->media_cfg.turn_tls_setting.ssock_param; + + tls_ciphers[ssock_param->ciphers_num++] = cipher; + ssock_param->ciphers = + cur_acc->turn_cfg.turn_tls_setting.ssock_param.ciphers = + tls_ciphers; + } else { + pj_ssl_cipher ciphers[PJ_SSL_SOCK_MAX_CIPHERS]; + unsigned j, ciphers_cnt; + + ciphers_cnt = PJ_ARRAY_SIZE(ciphers); + pj_ssl_cipher_get_availables(ciphers, &ciphers_cnt); + + PJ_LOG(1,(THIS_FILE, "Cipher \"%s\" is not supported by " + "TLS/SSL backend.", pj_optarg)); + printf("Available TLS/SSL ciphers (%d):\n", ciphers_cnt); + for (j=0; jmedia_cfg.turn_auth_cred.type = - cur_acc->turn_cfg.turn_auth_cred.type = PJ_STUN_AUTH_CRED_STATIC; - cfg->media_cfg.turn_auth_cred.data.static_cred.realm = - cur_acc->turn_cfg.turn_auth_cred.data.static_cred.realm = pj_str("*"); - cfg->media_cfg.turn_auth_cred.data.static_cred.username = - cur_acc->turn_cfg.turn_auth_cred.data.static_cred.username = pj_str(pj_optarg); - break; - - case OPT_TURN_PASSWD: - cfg->media_cfg.turn_auth_cred.data.static_cred.data_type = - cur_acc->turn_cfg.turn_auth_cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN; - cfg->media_cfg.turn_auth_cred.data.static_cred.data = - cur_acc->turn_cfg.turn_auth_cred.data.static_cred.data = pj_str(pj_optarg); - break; - - case OPT_RTCP_MUX: - cur_acc->enable_rtcp_mux = PJ_TRUE; - break; + case OPT_TURN_USER: + cfg->media_cfg.turn_auth_cred.type = + cur_acc->turn_cfg.turn_auth_cred.type = PJ_STUN_AUTH_CRED_STATIC; + cfg->media_cfg.turn_auth_cred.data.static_cred.realm = + cur_acc->turn_cfg.turn_auth_cred.data.static_cred.realm = pj_str("*"); + cfg->media_cfg.turn_auth_cred.data.static_cred.username = + cur_acc->turn_cfg.turn_auth_cred.data.static_cred.username = pj_str(pj_optarg); + break; + + case OPT_TURN_PASSWD: + cfg->media_cfg.turn_auth_cred.data.static_cred.data_type = + cur_acc->turn_cfg.turn_auth_cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN; + cfg->media_cfg.turn_auth_cred.data.static_cred.data = + cur_acc->turn_cfg.turn_auth_cred.data.static_cred.data = pj_str(pj_optarg); + break; + + case OPT_RTCP_MUX: + cur_acc->enable_rtcp_mux = PJ_TRUE; + break; #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - case OPT_USE_SRTP: - app_config.cfg.use_srtp = my_atoi(pj_optarg); - if (!pj_isdigit(*pj_optarg) || app_config.cfg.use_srtp > 3) { - PJ_LOG(1,(THIS_FILE, "Invalid value for --use-srtp option")); - return -1; - } - if ((int)app_config.cfg.use_srtp == 3) { - /* SRTP optional mode with duplicated media offer */ - app_config.cfg.use_srtp = PJMEDIA_SRTP_OPTIONAL; - app_config.cfg.srtp_optional_dup_offer = PJ_TRUE; - cur_acc->srtp_optional_dup_offer = PJ_TRUE; - } - cur_acc->use_srtp = app_config.cfg.use_srtp; - break; - case OPT_SRTP_SECURE: - app_config.cfg.srtp_secure_signaling = my_atoi(pj_optarg); - if (!pj_isdigit(*pj_optarg) || - app_config.cfg.srtp_secure_signaling > 2) - { - PJ_LOG(1,(THIS_FILE, "Invalid value for --srtp-secure option")); - return -1; - } - cur_acc->srtp_secure_signaling = app_config.cfg.srtp_secure_signaling; - break; - case OPT_SRTP_KEYING: - app_config.srtp_keying = my_atoi(pj_optarg); - if (!pj_isdigit(*pj_optarg) || app_config.srtp_keying < 0 || - app_config.srtp_keying > 1) - { - PJ_LOG(1,(THIS_FILE, "Invalid value for --srtp-keying option")); - return -1; - } - /* Set SRTP keying to use DTLS over SDES */ - if (app_config.srtp_keying == 1) { - pjsua_srtp_opt *srtp_opt = &app_config.cfg.srtp_opt; - srtp_opt->keying_count = 2; - srtp_opt->keying[0] = PJMEDIA_SRTP_KEYING_DTLS_SRTP; - srtp_opt->keying[1] = PJMEDIA_SRTP_KEYING_SDES; - - cur_acc->srtp_opt.keying_count = 2; - cur_acc->srtp_opt.keying[0] = PJMEDIA_SRTP_KEYING_DTLS_SRTP; - cur_acc->srtp_opt.keying[1] = PJMEDIA_SRTP_KEYING_SDES; - } - break; + case OPT_USE_SRTP: + app_config.cfg.use_srtp = my_atoi(pj_optarg); + if (!pj_isdigit(*pj_optarg) || app_config.cfg.use_srtp > 3) { + PJ_LOG(1,(THIS_FILE, "Invalid value for --use-srtp option")); + return -1; + } + if ((int)app_config.cfg.use_srtp == 3) { + /* SRTP optional mode with duplicated media offer */ + app_config.cfg.use_srtp = PJMEDIA_SRTP_OPTIONAL; + app_config.cfg.srtp_optional_dup_offer = PJ_TRUE; + cur_acc->srtp_optional_dup_offer = PJ_TRUE; + } + cur_acc->use_srtp = app_config.cfg.use_srtp; + break; + case OPT_SRTP_SECURE: + app_config.cfg.srtp_secure_signaling = my_atoi(pj_optarg); + if (!pj_isdigit(*pj_optarg) || + app_config.cfg.srtp_secure_signaling > 2) + { + PJ_LOG(1,(THIS_FILE, "Invalid value for --srtp-secure option")); + return -1; + } + cur_acc->srtp_secure_signaling = app_config.cfg.srtp_secure_signaling; + break; + case OPT_SRTP_KEYING: + app_config.srtp_keying = my_atoi(pj_optarg); + if (!pj_isdigit(*pj_optarg) || app_config.srtp_keying < 0 || + app_config.srtp_keying > 1) + { + PJ_LOG(1,(THIS_FILE, "Invalid value for --srtp-keying option")); + return -1; + } + /* Set SRTP keying to use DTLS over SDES */ + if (app_config.srtp_keying == 1) { + pjsua_srtp_opt *srtp_opt = &app_config.cfg.srtp_opt; + srtp_opt->keying_count = 2; + srtp_opt->keying[0] = PJMEDIA_SRTP_KEYING_DTLS_SRTP; + srtp_opt->keying[1] = PJMEDIA_SRTP_KEYING_SDES; + + cur_acc->srtp_opt.keying_count = 2; + cur_acc->srtp_opt.keying[0] = PJMEDIA_SRTP_KEYING_DTLS_SRTP; + cur_acc->srtp_opt.keying[1] = PJMEDIA_SRTP_KEYING_SDES; + } + break; #endif - case OPT_RTP_PORT: - cfg->rtp_cfg.port = my_atoi(pj_optarg); - if (cfg->rtp_cfg.port == 0) { - enum { START_PORT=4000 }; - unsigned range; - - range = (65535-START_PORT-PJSUA_MAX_CALLS*2); - cfg->rtp_cfg.port = START_PORT + - ((pj_rand() % range) & 0xFFFE); - } - - if (cfg->rtp_cfg.port < 1 || cfg->rtp_cfg.port > 65535) { - PJ_LOG(1,(THIS_FILE, - "Error: rtp-port argument value " - "(expecting 1-65535")); - return -1; - } - break; - - case OPT_DIS_CODEC: + case OPT_RTP_PORT: + cfg->rtp_cfg.port = my_atoi(pj_optarg); + if (cfg->rtp_cfg.port == 0) { + enum { START_PORT=4000 }; + unsigned range; + + range = (65535-START_PORT-PJSUA_MAX_CALLS*2); + cfg->rtp_cfg.port = START_PORT + + ((pj_rand() % range) & 0xFFFE); + } + + if (cfg->rtp_cfg.port < 1 || cfg->rtp_cfg.port > 65535) { + PJ_LOG(1,(THIS_FILE, + "Error: rtp-port argument value " + "(expecting 1-65535")); + return -1; + } + break; + + case OPT_DIS_CODEC: cfg->codec_dis[cfg->codec_dis_cnt++] = pj_str(pj_optarg); - break; - - case OPT_ADD_CODEC: - cfg->codec_arg[cfg->codec_cnt++] = pj_str(pj_optarg); - break; - - /* These options were no longer valid after new pjsua */ - /* - case OPT_COMPLEXITY: - cfg->complexity = my_atoi(pj_optarg); - if (cfg->complexity < 0 || cfg->complexity > 10) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid --complexity (expecting 0-10")); - return -1; - } - break; - */ - - case OPT_DURATION: - cfg->duration = my_atoi(pj_optarg); - break; - - case OPT_THREAD_CNT: - cfg->cfg.thread_cnt = my_atoi(pj_optarg); - if (cfg->cfg.thread_cnt > 128) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid --thread-cnt option")); - return -1; - } - break; - - case OPT_PTIME: - cfg->media_cfg.ptime = my_atoi(pj_optarg); - if (cfg->media_cfg.ptime < 10 || cfg->media_cfg.ptime > 1000) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid --ptime option")); - return -1; - } - break; - - case OPT_NO_VAD: - cfg->media_cfg.no_vad = PJ_TRUE; - break; - - case OPT_EC_TAIL: - cfg->media_cfg.ec_tail_len = my_atoi(pj_optarg); - if (cfg->media_cfg.ec_tail_len > 1000) { - PJ_LOG(1,(THIS_FILE, "I think the ec-tail length setting " - "is too big")); - return -1; - } - break; - - case OPT_EC_OPT: - cfg->media_cfg.ec_options = my_atoi(pj_optarg); - if (cfg->media_cfg.ec_options > 0) - cfg->media_cfg.ec_options |= PJMEDIA_ECHO_USE_SW_ECHO; - break; - - case OPT_QUALITY: - cfg->media_cfg.quality = my_atoi(pj_optarg); - if (cfg->media_cfg.quality > 10) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid --quality (expecting 0-10")); - return -1; - } - break; - - case OPT_ILBC_MODE: - cfg->media_cfg.ilbc_mode = my_atoi(pj_optarg); - if (cfg->media_cfg.ilbc_mode!=20 && cfg->media_cfg.ilbc_mode!=30) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid --ilbc-mode (expecting 20 or 30")); - return -1; - } - break; - - case OPT_RX_DROP_PCT: - cfg->media_cfg.rx_drop_pct = my_atoi(pj_optarg); - if (cfg->media_cfg.rx_drop_pct > 100) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid --rx-drop-pct (expecting <= 100")); - return -1; - } - break; - - case OPT_TX_DROP_PCT: - cfg->media_cfg.tx_drop_pct = my_atoi(pj_optarg); - if (cfg->media_cfg.tx_drop_pct > 100) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid --tx-drop-pct (expecting <= 100")); - return -1; - } - break; - - case OPT_AUTO_ANSWER: - cfg->auto_answer = my_atoi(pj_optarg); - if (cfg->auto_answer < 100 || cfg->auto_answer > 699) { - PJ_LOG(1,(THIS_FILE, - "Error: invalid code in --auto-answer " - "(expecting 100-699")); - return -1; - } - break; - - case OPT_MAX_CALLS: - cfg->cfg.max_calls = my_atoi(pj_optarg); - if (cfg->cfg.max_calls < 1 || cfg->cfg.max_calls > PJSUA_MAX_CALLS) { - PJ_LOG(1,(THIS_FILE,"Error: maximum call setting exceeds " - "compile time limit (PJSUA_MAX_CALLS=%d)", - PJSUA_MAX_CALLS)); - return -1; - } - break; + break; + + case OPT_ADD_CODEC: + cfg->codec_arg[cfg->codec_cnt++] = pj_str(pj_optarg); + break; + + /* These options were no longer valid after new pjsua */ + /* + case OPT_COMPLEXITY: + cfg->complexity = my_atoi(pj_optarg); + if (cfg->complexity < 0 || cfg->complexity > 10) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid --complexity (expecting 0-10")); + return -1; + } + break; + */ + + case OPT_DURATION: + cfg->duration = my_atoi(pj_optarg); + break; + + case OPT_THREAD_CNT: + cfg->cfg.thread_cnt = my_atoi(pj_optarg); + if (cfg->cfg.thread_cnt > 128) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid --thread-cnt option")); + return -1; + } + break; + + case OPT_PTIME: + cfg->media_cfg.ptime = my_atoi(pj_optarg); + if (cfg->media_cfg.ptime < 10 || cfg->media_cfg.ptime > 1000) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid --ptime option")); + return -1; + } + break; + + case OPT_NO_VAD: + cfg->media_cfg.no_vad = PJ_TRUE; + break; + + case OPT_EC_TAIL: + cfg->media_cfg.ec_tail_len = my_atoi(pj_optarg); + if (cfg->media_cfg.ec_tail_len > 1000) { + PJ_LOG(1,(THIS_FILE, "I think the ec-tail length setting " + "is too big")); + return -1; + } + break; + + case OPT_EC_OPT: + cfg->media_cfg.ec_options = my_atoi(pj_optarg); + if (cfg->media_cfg.ec_options > 0) + cfg->media_cfg.ec_options |= PJMEDIA_ECHO_USE_SW_ECHO; + break; + + case OPT_QUALITY: + cfg->media_cfg.quality = my_atoi(pj_optarg); + if (cfg->media_cfg.quality > 10) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid --quality (expecting 0-10")); + return -1; + } + break; + + case OPT_ILBC_MODE: + cfg->media_cfg.ilbc_mode = my_atoi(pj_optarg); + if (cfg->media_cfg.ilbc_mode!=20 && cfg->media_cfg.ilbc_mode!=30) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid --ilbc-mode (expecting 20 or 30")); + return -1; + } + break; + + case OPT_RX_DROP_PCT: + cfg->media_cfg.rx_drop_pct = my_atoi(pj_optarg); + if (cfg->media_cfg.rx_drop_pct > 100) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid --rx-drop-pct (expecting <= 100")); + return -1; + } + break; + + case OPT_TX_DROP_PCT: + cfg->media_cfg.tx_drop_pct = my_atoi(pj_optarg); + if (cfg->media_cfg.tx_drop_pct > 100) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid --tx-drop-pct (expecting <= 100")); + return -1; + } + break; + + case OPT_AUTO_ANSWER: + cfg->auto_answer = my_atoi(pj_optarg); + if (cfg->auto_answer < 100 || cfg->auto_answer > 699) { + PJ_LOG(1,(THIS_FILE, + "Error: invalid code in --auto-answer " + "(expecting 100-699")); + return -1; + } + break; + + case OPT_MAX_CALLS: + cfg->cfg.max_calls = my_atoi(pj_optarg); + if (cfg->cfg.max_calls < 1 || cfg->cfg.max_calls > PJSUA_MAX_CALLS) { + PJ_LOG(1,(THIS_FILE,"Error: maximum call setting exceeds " + "compile time limit (PJSUA_MAX_CALLS=%d)", + PJSUA_MAX_CALLS)); + return -1; + } + break; #if defined(PJSIP_HAS_TLS_TRANSPORT) && (PJSIP_HAS_TLS_TRANSPORT != 0) - case OPT_USE_TLS: - cfg->use_tls = PJ_TRUE; - break; - - case OPT_TLS_CA_FILE: - cfg->udp_cfg.tls_setting.ca_list_file = pj_str(pj_optarg); - break; - - case OPT_TLS_CERT_FILE: - cfg->udp_cfg.tls_setting.cert_file = pj_str(pj_optarg); - break; - - case OPT_TLS_PRIV_FILE: - cfg->udp_cfg.tls_setting.privkey_file = pj_str(pj_optarg); - break; - - case OPT_TLS_PASSWORD: - cfg->udp_cfg.tls_setting.password = pj_str(pj_optarg); - break; - - case OPT_TLS_VERIFY_SERVER: - cfg->udp_cfg.tls_setting.verify_server = PJ_TRUE; - break; - - case OPT_TLS_VERIFY_CLIENT: - cfg->udp_cfg.tls_setting.verify_client = PJ_TRUE; - cfg->udp_cfg.tls_setting.require_client_cert = PJ_TRUE; - break; - - case OPT_TLS_NEG_TIMEOUT: - cfg->udp_cfg.tls_setting.timeout.sec = atoi(pj_optarg); - break; - - case OPT_TLS_CIPHER: - { - pj_ssl_cipher cipher; - - if (pj_ansi_strnicmp(pj_optarg, "0x", 2) == 0) { - pj_str_t cipher_st = pj_str(pj_optarg + 2); - cipher = (pj_ssl_cipher)pj_strtoul2(&cipher_st, NULL, 16); - } else { - cipher = atoi(pj_optarg); - } - - if (pj_ssl_cipher_is_supported(cipher)) { - static pj_ssl_cipher tls_ciphers[PJ_SSL_SOCK_MAX_CIPHERS]; - - tls_ciphers[cfg->udp_cfg.tls_setting.ciphers_num++] = cipher; - cfg->udp_cfg.tls_setting.ciphers = tls_ciphers; - } else { - pj_ssl_cipher ciphers[PJ_SSL_SOCK_MAX_CIPHERS]; - unsigned j, ciphers_cnt; - - ciphers_cnt = PJ_ARRAY_SIZE(ciphers); - pj_ssl_cipher_get_availables(ciphers, &ciphers_cnt); - - PJ_LOG(1,(THIS_FILE, "Cipher \"%s\" is not supported by " - "TLS/SSL backend.", pj_optarg)); - printf("Available TLS/SSL ciphers (%d):\n", ciphers_cnt); - for (j=0; juse_tls = PJ_TRUE; + break; + + case OPT_TLS_CA_FILE: + cfg->udp_cfg.tls_setting.ca_list_file = pj_str(pj_optarg); + break; + + case OPT_TLS_CERT_FILE: + cfg->udp_cfg.tls_setting.cert_file = pj_str(pj_optarg); + break; + + case OPT_TLS_PRIV_FILE: + cfg->udp_cfg.tls_setting.privkey_file = pj_str(pj_optarg); + break; + + case OPT_TLS_PASSWORD: + cfg->udp_cfg.tls_setting.password = pj_str(pj_optarg); + break; + + case OPT_TLS_VERIFY_SERVER: + cfg->udp_cfg.tls_setting.verify_server = PJ_TRUE; + break; + + case OPT_TLS_VERIFY_CLIENT: + cfg->udp_cfg.tls_setting.verify_client = PJ_TRUE; + cfg->udp_cfg.tls_setting.require_client_cert = PJ_TRUE; + break; + + case OPT_TLS_NEG_TIMEOUT: + cfg->udp_cfg.tls_setting.timeout.sec = atoi(pj_optarg); + break; + + case OPT_TLS_CIPHER: + { + pj_ssl_cipher cipher; + + if (pj_ansi_strnicmp(pj_optarg, "0x", 2) == 0) { + pj_str_t cipher_st = pj_str(pj_optarg + 2); + cipher = (pj_ssl_cipher)pj_strtoul2(&cipher_st, NULL, 16); + } else { + cipher = atoi(pj_optarg); + } + + if (pj_ssl_cipher_is_supported(cipher)) { + static pj_ssl_cipher tls_ciphers[PJ_SSL_SOCK_MAX_CIPHERS]; + + tls_ciphers[cfg->udp_cfg.tls_setting.ciphers_num++] = cipher; + cfg->udp_cfg.tls_setting.ciphers = tls_ciphers; + } else { + pj_ssl_cipher ciphers[PJ_SSL_SOCK_MAX_CIPHERS]; + unsigned j, ciphers_cnt; + + ciphers_cnt = PJ_ARRAY_SIZE(ciphers); + pj_ssl_cipher_get_availables(ciphers, &ciphers_cnt); + + PJ_LOG(1,(THIS_FILE, "Cipher \"%s\" is not supported by " + "TLS/SSL backend.", pj_optarg)); + printf("Available TLS/SSL ciphers (%d):\n", ciphers_cnt); + for (j=0; jcapture_dev = atoi(pj_optarg); - break; + case OPT_CAPTURE_DEV: + cfg->capture_dev = atoi(pj_optarg); + break; - case OPT_PLAYBACK_DEV: - cfg->playback_dev = atoi(pj_optarg); - break; + case OPT_PLAYBACK_DEV: + cfg->playback_dev = atoi(pj_optarg); + break; - case OPT_STDOUT_REFRESH: - stdout_refresh = atoi(pj_optarg); - break; + case OPT_STDOUT_REFRESH: + stdout_refresh = atoi(pj_optarg); + break; - case OPT_STDOUT_REFRESH_TEXT: - stdout_refresh_text = pj_optarg; - break; + case OPT_STDOUT_REFRESH_TEXT: + stdout_refresh_text = pj_optarg; + break; #ifdef _IONBF - case OPT_STDOUT_NO_BUF: - setvbuf(stdout, NULL, _IONBF, 0); - cfg->log_cfg.cb = &log_writer_nobuf; - break; + case OPT_STDOUT_NO_BUF: + setvbuf(stdout, NULL, _IONBF, 0); + cfg->log_cfg.cb = &log_writer_nobuf; + break; #endif - case OPT_CAPTURE_LAT: - cfg->capture_lat = atoi(pj_optarg); - break; + case OPT_CAPTURE_LAT: + cfg->capture_lat = atoi(pj_optarg); + break; - case OPT_PLAYBACK_LAT: - cfg->playback_lat = atoi(pj_optarg); - break; + case OPT_PLAYBACK_LAT: + cfg->playback_lat = atoi(pj_optarg); + break; - case OPT_SND_AUTO_CLOSE: - cfg->media_cfg.snd_auto_close_time = atoi(pj_optarg); - break; + case OPT_SND_AUTO_CLOSE: + cfg->media_cfg.snd_auto_close_time = atoi(pj_optarg); + break; - case OPT_NO_TONES: - cfg->no_tones = PJ_TRUE; - break; + case OPT_NO_TONES: + cfg->no_tones = PJ_TRUE; + break; - case OPT_JB_MAX_SIZE: - cfg->media_cfg.jb_max = atoi(pj_optarg); - break; + case OPT_JB_MAX_SIZE: + cfg->media_cfg.jb_max = atoi(pj_optarg); + break; #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6 - case OPT_IPV6: - cfg->ipv6 = PJ_TRUE; - break; + case OPT_IPV6: + cfg->ipv6 = PJ_TRUE; + break; #endif - case OPT_QOS: - cfg->enable_qos = PJ_TRUE; - /* Set RTP traffic type to Voice */ - cfg->rtp_cfg.qos_type = PJ_QOS_TYPE_VOICE; - /* Directly apply DSCP value to SIP traffic. Say lets - * set it to CS3 (DSCP 011000). Note that this will not - * work on all platforms. - */ - cfg->udp_cfg.qos_params.flags = PJ_QOS_PARAM_HAS_DSCP; - cfg->udp_cfg.qos_params.dscp_val = 0x18; - break; - case OPT_VIDEO: - cfg->vid.vid_cnt = 1; - cfg->vid.in_auto_show = PJ_TRUE; - cfg->vid.out_auto_transmit = PJ_TRUE; - break; - case OPT_EXTRA_AUDIO: - cfg->aud_cnt++; - break; - - case OPT_VCAPTURE_DEV: - cfg->vid.vcapture_dev = atoi(pj_optarg); - cur_acc->vid_cap_dev = cfg->vid.vcapture_dev; - break; - - case OPT_VRENDER_DEV: - cfg->vid.vrender_dev = atoi(pj_optarg); - cur_acc->vid_rend_dev = cfg->vid.vrender_dev; - break; - - case OPT_PLAY_AVI: - if (app_config.avi_cnt >= PJSUA_APP_MAX_AVI) { - PJ_LOG(1,(THIS_FILE, "Too many AVIs")); - return -1; - } - app_config.avi[app_config.avi_cnt++].path = pj_str(pj_optarg); - break; - - case OPT_AUTO_PLAY_AVI: - app_config.avi_auto_play = PJ_TRUE; - break; - - case OPT_USE_CLI: - cfg->use_cli = PJ_TRUE; - break; - - case OPT_CLI_TELNET_PORT: - cfg->cli_cfg.telnet_cfg.port = (pj_uint16_t)atoi(pj_optarg); - cfg->cli_cfg.cli_fe |= CLI_FE_TELNET; - break; - - case OPT_DISABLE_CLI_CONSOLE: - cfg->cli_cfg.cli_fe &= (~CLI_FE_CONSOLE); - break; - - default: - PJ_LOG(1,(THIS_FILE, - "Argument \"%s\" is not valid. Use --help to see help", - argv[pj_optind-1])); - return -1; - } + case OPT_QOS: + cfg->enable_qos = PJ_TRUE; + /* Set RTP traffic type to Voice */ + cfg->rtp_cfg.qos_type = PJ_QOS_TYPE_VOICE; + /* Directly apply DSCP value to SIP traffic. Say lets + * set it to CS3 (DSCP 011000). Note that this will not + * work on all platforms. + */ + cfg->udp_cfg.qos_params.flags = PJ_QOS_PARAM_HAS_DSCP; + cfg->udp_cfg.qos_params.dscp_val = 0x18; + break; + case OPT_VIDEO: + cfg->vid.vid_cnt = 1; + cfg->vid.in_auto_show = PJ_TRUE; + cfg->vid.out_auto_transmit = PJ_TRUE; + break; + case OPT_EXTRA_AUDIO: + cfg->aud_cnt++; + break; + + case OPT_VCAPTURE_DEV: + cfg->vid.vcapture_dev = atoi(pj_optarg); + cur_acc->vid_cap_dev = cfg->vid.vcapture_dev; + break; + + case OPT_VRENDER_DEV: + cfg->vid.vrender_dev = atoi(pj_optarg); + cur_acc->vid_rend_dev = cfg->vid.vrender_dev; + break; + + case OPT_PLAY_AVI: + if (app_config.avi_cnt >= PJSUA_APP_MAX_AVI) { + PJ_LOG(1,(THIS_FILE, "Too many AVIs")); + return -1; + } + app_config.avi[app_config.avi_cnt++].path = pj_str(pj_optarg); + break; + + case OPT_AUTO_PLAY_AVI: + app_config.avi_auto_play = PJ_TRUE; + break; + + case OPT_USE_CLI: + cfg->use_cli = PJ_TRUE; + break; + + case OPT_CLI_TELNET_PORT: + cfg->cli_cfg.telnet_cfg.port = (pj_uint16_t)atoi(pj_optarg); + cfg->cli_cfg.cli_fe |= CLI_FE_TELNET; + break; + + case OPT_DISABLE_CLI_CONSOLE: + cfg->cli_cfg.cli_fe &= (~CLI_FE_CONSOLE); + break; + + default: + PJ_LOG(1,(THIS_FILE, + "Argument \"%s\" is not valid. Use --help to see help", + argv[pj_optind-1])); + return -1; + } } if (pj_optind != argc) { - pj_str_t uri_arg; - - if (pjsua_verify_url(argv[pj_optind]) != PJ_SUCCESS) { - PJ_LOG(1,(THIS_FILE, "Invalid SIP URI %s", argv[pj_optind])); - return -1; - } - uri_arg = pj_str(argv[pj_optind]); - if (uri_to_call) - *uri_to_call = uri_arg; - pj_optind++; - - /* Add URI to call to buddy list if it's not already there */ - for (i=0; ibuddy_cnt; ++i) { - if (pj_stricmp(&cfg->buddy_cfg[i].uri, &uri_arg)==0) - break; - } - if (i == cfg->buddy_cnt && cfg->buddy_cnt < PJSUA_MAX_BUDDIES) { - cfg->buddy_cfg[cfg->buddy_cnt++].uri = uri_arg; - } + pj_str_t uri_arg; + + if (pjsua_verify_url(argv[pj_optind]) != PJ_SUCCESS) { + PJ_LOG(1,(THIS_FILE, "Invalid SIP URI %s", argv[pj_optind])); + return -1; + } + uri_arg = pj_str(argv[pj_optind]); + if (uri_to_call) + *uri_to_call = uri_arg; + pj_optind++; + + /* Add URI to call to buddy list if it's not already there */ + for (i=0; ibuddy_cnt; ++i) { + if (pj_stricmp(&cfg->buddy_cfg[i].uri, &uri_arg)==0) + break; + } + if (i == cfg->buddy_cnt && cfg->buddy_cnt < PJSUA_MAX_BUDDIES) { + cfg->buddy_cfg[cfg->buddy_cnt++].uri = uri_arg; + } } else { - if (uri_to_call) - uri_to_call->slen = 0; + if (uri_to_call) + uri_to_call->slen = 0; } if (pj_optind != argc) { - PJ_LOG(1,(THIS_FILE, "Error: unknown options %s", argv[pj_optind])); - return PJ_EINVAL; + PJ_LOG(1,(THIS_FILE, "Error: unknown options %s", argv[pj_optind])); + return PJ_EINVAL; } if (cfg->acc_cfg[cfg->acc_cnt].id.slen) - cfg->acc_cnt++; + cfg->acc_cnt++; for (i=0; iacc_cnt; ++i) { - pjsua_acc_config *acfg = &cfg->acc_cfg[i]; - - if (acfg->cred_info[acfg->cred_count].username.slen) - { - acfg->cred_count++; - } - - if (acfg->ice_cfg.enable_ice) { - acfg->ice_cfg_use = PJSUA_ICE_CONFIG_USE_CUSTOM; - } - if (acfg->turn_cfg.enable_turn) { - acfg->turn_cfg_use = PJSUA_TURN_CONFIG_USE_CUSTOM; - } - - /* When IMS mode is enabled for the account, verify that settings - * are okay. - */ - /* For now we check if IMS mode is activated by looking if - * initial_auth is set. - */ - if (acfg->auth_pref.initial_auth && acfg->cred_count) { - /* Realm must point to the real domain */ - if (*acfg->cred_info[0].realm.ptr=='*') { - PJ_LOG(1,(THIS_FILE, - "Error: cannot use '*' as realm with IMS")); - return PJ_EINVAL; - } - - /* Username for authentication must be in a@b format */ - if (strchr(acfg->cred_info[0].username.ptr, '@')==0) { - PJ_LOG(1,(THIS_FILE, - "Error: Username for authentication must " - "be in user@domain format with IMS")); - return PJ_EINVAL; - } - } + pjsua_acc_config *acfg = &cfg->acc_cfg[i]; + + if (acfg->cred_info[acfg->cred_count].username.slen) + { + acfg->cred_count++; + } + + if (acfg->ice_cfg.enable_ice) { + acfg->ice_cfg_use = PJSUA_ICE_CONFIG_USE_CUSTOM; + } + if (acfg->turn_cfg.enable_turn) { + acfg->turn_cfg_use = PJSUA_TURN_CONFIG_USE_CUSTOM; + } + + /* When IMS mode is enabled for the account, verify that settings + * are okay. + */ + /* For now we check if IMS mode is activated by looking if + * initial_auth is set. + */ + if (acfg->auth_pref.initial_auth && acfg->cred_count) { + /* Realm must point to the real domain */ + if (*acfg->cred_info[0].realm.ptr=='*') { + PJ_LOG(1,(THIS_FILE, + "Error: cannot use '*' as realm with IMS")); + return PJ_EINVAL; + } + + /* Username for authentication must be in a@b format */ + if (strchr(acfg->cred_info[0].username.ptr, '@')==0) { + PJ_LOG(1,(THIS_FILE, + "Error: Username for authentication must " + "be in user@domain format with IMS")); + return PJ_EINVAL; + } + } } return PJ_SUCCESS; } @@ -1603,7 +1602,7 @@ static void default_config() pjsua_config_default(&cfg->cfg); pj_ansi_sprintf(tmp, "PJSUA v%s %s", pj_get_version(), - pj_get_sys_info()->info.ptr); + pj_get_sys_info()->info.ptr); pj_strdup2_with_null(app_config.pool, &cfg->cfg.user_agent, tmp); pjsua_logging_config_default(&cfg->log_cfg); @@ -1627,10 +1626,10 @@ static void default_config() cfg->ring_slot = PJSUA_INVALID_ID; for (i=0; iacc_cfg); ++i) - pjsua_acc_config_default(&cfg->acc_cfg[i]); + pjsua_acc_config_default(&cfg->acc_cfg[i]); for (i=0; ibuddy_cfg); ++i) - pjsua_buddy_config_default(&cfg->buddy_cfg[i]); + pjsua_buddy_config_default(&cfg->buddy_cfg[i]); cfg->vid.vcapture_dev = PJMEDIA_VID_DEFAULT_CAPTURE_DEV; cfg->vid.vrender_dev = PJMEDIA_VID_DEFAULT_RENDER_DEV; @@ -1656,8 +1655,8 @@ static pj_status_t parse_config(int argc, char *argv[], pj_str_t *uri_arg) } pj_status_t load_config(int argc, - char **argv, - pj_str_t *uri_arg) + char **argv, + pj_str_t *uri_arg) { pj_status_t status; pj_bool_t use_cli = PJ_FALSE; @@ -1666,19 +1665,19 @@ pj_status_t load_config(int argc, /** CLI options are not changable **/ if (app_running) { - use_cli = app_config.use_cli; - cli_fe = app_config.cli_cfg.cli_fe; - cli_telnet_port = app_config.cli_cfg.telnet_cfg.port; + use_cli = app_config.use_cli; + cli_fe = app_config.cli_cfg.cli_fe; + cli_telnet_port = app_config.cli_cfg.telnet_cfg.port; } status = parse_config(argc, argv, uri_arg); if (status != PJ_SUCCESS) - return status; + return status; if (app_running) { - app_config.use_cli = use_cli; - app_config.cli_cfg.cli_fe = cli_fe; - app_config.cli_cfg.telnet_cfg.port = cli_telnet_port; + app_config.use_cli = use_cli; + app_config.cli_cfg.cli_fe = cli_fe; + app_config.cli_cfg.telnet_cfg.port = cli_telnet_port; } return status; @@ -1700,213 +1699,213 @@ static void write_account_settings(int acc_index, pj_str_t *result) /* Identity */ if (acc_cfg->id.slen) { - pj_ansi_sprintf(line, "--id %.*s\n", - (int)acc_cfg->id.slen, - acc_cfg->id.ptr); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--id %.*s\n", + (int)acc_cfg->id.slen, + acc_cfg->id.ptr); + pj_strcat2(result, line); } /* Registrar server */ if (acc_cfg->reg_uri.slen) { - pj_ansi_sprintf(line, "--registrar %.*s\n", - (int)acc_cfg->reg_uri.slen, - acc_cfg->reg_uri.ptr); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--registrar %.*s\n", + (int)acc_cfg->reg_uri.slen, + acc_cfg->reg_uri.ptr); + pj_strcat2(result, line); - pj_ansi_sprintf(line, "--reg-timeout %u\n", - acc_cfg->reg_timeout); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--reg-timeout %u\n", + acc_cfg->reg_timeout); + pj_strcat2(result, line); } /* Contact */ if (acc_cfg->force_contact.slen) { - pj_ansi_sprintf(line, "--contact %.*s\n", - (int)acc_cfg->force_contact.slen, - acc_cfg->force_contact.ptr); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--contact %.*s\n", + (int)acc_cfg->force_contact.slen, + acc_cfg->force_contact.ptr); + pj_strcat2(result, line); } /* Contact header parameters */ if (acc_cfg->contact_params.slen) { - pj_ansi_sprintf(line, "--contact-params %.*s\n", - (int)acc_cfg->contact_params.slen, - acc_cfg->contact_params.ptr); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--contact-params %.*s\n", + (int)acc_cfg->contact_params.slen, + acc_cfg->contact_params.ptr); + pj_strcat2(result, line); } /* Contact URI parameters */ if (acc_cfg->contact_uri_params.slen) { - pj_ansi_sprintf(line, "--contact-uri-params %.*s\n", - (int)acc_cfg->contact_uri_params.slen, - acc_cfg->contact_uri_params.ptr); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--contact-uri-params %.*s\n", + (int)acc_cfg->contact_uri_params.slen, + acc_cfg->contact_uri_params.ptr); + pj_strcat2(result, line); } /* */ if (acc_cfg->allow_contact_rewrite!=1) { - pj_ansi_sprintf(line, "--auto-update-nat %i\n", - (int)acc_cfg->allow_contact_rewrite); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--auto-update-nat %i\n", + (int)acc_cfg->allow_contact_rewrite); + pj_strcat2(result, line); } #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) /* SRTP */ if (acc_cfg->use_srtp) { - int use_srtp = (int)acc_cfg->use_srtp; - if (use_srtp == PJMEDIA_SRTP_OPTIONAL && - acc_cfg->srtp_optional_dup_offer) - { - use_srtp = 3; - } - pj_ansi_sprintf(line, "--use-srtp %i\n", use_srtp); - pj_strcat2(result, line); + int use_srtp = (int)acc_cfg->use_srtp; + if (use_srtp == PJMEDIA_SRTP_OPTIONAL && + acc_cfg->srtp_optional_dup_offer) + { + use_srtp = 3; + } + pj_ansi_sprintf(line, "--use-srtp %i\n", use_srtp); + pj_strcat2(result, line); } if (acc_cfg->srtp_secure_signaling != - PJSUA_DEFAULT_SRTP_SECURE_SIGNALING) + PJSUA_DEFAULT_SRTP_SECURE_SIGNALING) { - pj_ansi_sprintf(line, "--srtp-secure %d\n", - acc_cfg->srtp_secure_signaling); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--srtp-secure %d\n", + acc_cfg->srtp_secure_signaling); + pj_strcat2(result, line); } #endif /* Proxy */ for (i=0; iproxy_cnt; ++i) { - pj_ansi_sprintf(line, "--proxy %.*s\n", - (int)acc_cfg->proxy[i].slen, - acc_cfg->proxy[i].ptr); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--proxy %.*s\n", + (int)acc_cfg->proxy[i].slen, + acc_cfg->proxy[i].ptr); + pj_strcat2(result, line); } /* Credentials */ for (i=0; icred_count; ++i) { - if (acc_cfg->cred_info[i].realm.slen) { - pj_ansi_sprintf(line, "--realm %.*s\n", - (int)acc_cfg->cred_info[i].realm.slen, - acc_cfg->cred_info[i].realm.ptr); - pj_strcat2(result, line); - } - - if (acc_cfg->cred_info[i].username.slen) { - pj_ansi_sprintf(line, "--username %.*s\n", - (int)acc_cfg->cred_info[i].username.slen, - acc_cfg->cred_info[i].username.ptr); - pj_strcat2(result, line); - } - - if (acc_cfg->cred_info[i].data.slen) { - pj_ansi_sprintf(line, "--password %.*s\n", - (int)acc_cfg->cred_info[i].data.slen, - acc_cfg->cred_info[i].data.ptr); - pj_strcat2(result, line); - } - - if (i != acc_cfg->cred_count - 1) - pj_strcat2(result, "--next-cred\n"); + if (acc_cfg->cred_info[i].realm.slen) { + pj_ansi_sprintf(line, "--realm %.*s\n", + (int)acc_cfg->cred_info[i].realm.slen, + acc_cfg->cred_info[i].realm.ptr); + pj_strcat2(result, line); + } + + if (acc_cfg->cred_info[i].username.slen) { + pj_ansi_sprintf(line, "--username %.*s\n", + (int)acc_cfg->cred_info[i].username.slen, + acc_cfg->cred_info[i].username.ptr); + pj_strcat2(result, line); + } + + if (acc_cfg->cred_info[i].data.slen) { + pj_ansi_sprintf(line, "--password %.*s\n", + (int)acc_cfg->cred_info[i].data.slen, + acc_cfg->cred_info[i].data.ptr); + pj_strcat2(result, line); + } + + if (i != acc_cfg->cred_count - 1) + pj_strcat2(result, "--next-cred\n"); } /* reg-use-proxy */ if (acc_cfg->reg_use_proxy != 3) { - pj_ansi_sprintf(line, "--reg-use-proxy %d\n", - acc_cfg->reg_use_proxy); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--reg-use-proxy %d\n", + acc_cfg->reg_use_proxy); + pj_strcat2(result, line); } /* rereg-delay */ if (acc_cfg->reg_retry_interval != PJSUA_REG_RETRY_INTERVAL) { - pj_ansi_sprintf(line, "--rereg-delay %d\n", - acc_cfg->reg_retry_interval); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--rereg-delay %d\n", + acc_cfg->reg_retry_interval); + pj_strcat2(result, line); } /* 100rel extension */ if (acc_cfg->require_100rel == PJSUA_100REL_MANDATORY) { - pj_strcat2(result, "--use-100rel\n"); + pj_strcat2(result, "--use-100rel\n"); } /* Session Timer extension */ if (acc_cfg->use_timer) { - pj_ansi_sprintf(line, "--use-timer %d\n", - acc_cfg->use_timer); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--use-timer %d\n", + acc_cfg->use_timer); + pj_strcat2(result, line); } if (acc_cfg->timer_setting.min_se != 90) { - pj_ansi_sprintf(line, "--timer-min-se %d\n", - acc_cfg->timer_setting.min_se); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--timer-min-se %d\n", + acc_cfg->timer_setting.min_se); + pj_strcat2(result, line); } if (acc_cfg->timer_setting.sess_expires != PJSIP_SESS_TIMER_DEF_SE) { - pj_ansi_sprintf(line, "--timer-se %d\n", - acc_cfg->timer_setting.sess_expires); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--timer-se %d\n", + acc_cfg->timer_setting.sess_expires); + pj_strcat2(result, line); } /* Publish */ if (acc_cfg->publish_enabled) - pj_strcat2(result, "--publish\n"); + pj_strcat2(result, "--publish\n"); /* MWI */ if (acc_cfg->mwi_enabled) - pj_strcat2(result, "--mwi\n"); + pj_strcat2(result, "--mwi\n"); if (acc_cfg->sip_stun_use != PJSUA_STUN_USE_DEFAULT || - acc_cfg->media_stun_use != PJSUA_STUN_USE_DEFAULT) + acc_cfg->media_stun_use != PJSUA_STUN_USE_DEFAULT) { - pj_strcat2(result, "--disable-stun\n"); + pj_strcat2(result, "--disable-stun\n"); } /* Media Transport*/ if (acc_cfg->ice_cfg.enable_ice) - pj_strcat2(result, "--use-ice\n"); + pj_strcat2(result, "--use-ice\n"); if (acc_cfg->ice_cfg.ice_opt.aggressive == PJ_FALSE) - pj_strcat2(result, "--ice-regular\n"); + pj_strcat2(result, "--ice-regular\n"); if (acc_cfg->ice_cfg.ice_opt.trickle > 0) { - pj_ansi_sprintf(line, "--ice-trickle %d\n", - acc_cfg->ice_cfg.ice_opt.trickle); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--ice-trickle %d\n", + acc_cfg->ice_cfg.ice_opt.trickle); + pj_strcat2(result, line); } if (acc_cfg->turn_cfg.enable_turn) - pj_strcat2(result, "--use-turn\n"); + pj_strcat2(result, "--use-turn\n"); if (acc_cfg->ice_cfg.ice_max_host_cands >= 0) { - pj_ansi_sprintf(line, "--ice_max_host_cands %d\n", - acc_cfg->ice_cfg.ice_max_host_cands); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--ice_max_host_cands %d\n", + acc_cfg->ice_cfg.ice_max_host_cands); + pj_strcat2(result, line); } if (acc_cfg->ice_cfg.ice_no_rtcp) - pj_strcat2(result, "--ice-no-rtcp\n"); + pj_strcat2(result, "--ice-no-rtcp\n"); if (acc_cfg->turn_cfg.turn_server.slen) { - pj_ansi_sprintf(line, "--turn-srv %.*s\n", - (int)acc_cfg->turn_cfg.turn_server.slen, - acc_cfg->turn_cfg.turn_server.ptr); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--turn-srv %.*s\n", + (int)acc_cfg->turn_cfg.turn_server.slen, + acc_cfg->turn_cfg.turn_server.ptr); + pj_strcat2(result, line); } if (acc_cfg->turn_cfg.turn_conn_type == PJ_TURN_TP_TCP) - pj_strcat2(result, "--turn-tcp\n"); + pj_strcat2(result, "--turn-tcp\n"); if (acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.username.slen) { - pj_ansi_sprintf(line, "--turn-user %.*s\n", - (int)acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.username.slen, - acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.username.ptr); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--turn-user %.*s\n", + (int)acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.username.slen, + acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.username.ptr); + pj_strcat2(result, line); } if (acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.data.slen) { - pj_ansi_sprintf(line, "--turn-passwd %.*s\n", - (int)acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.data.slen, - acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.data.ptr); - pj_strcat2(result, line); + pj_ansi_sprintf(line, "--turn-passwd %.*s\n", + (int)acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.data.slen, + acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.data.ptr); + pj_strcat2(result, line); } if (acc_cfg->enable_rtcp_mux) - pj_strcat2(result, "--rtcp-mux\n"); + pj_strcat2(result, "--rtcp-mux\n"); } /* @@ -1927,57 +1926,57 @@ int write_settings(pjsua_app_config *config, char *buf, pj_size_t max) /* Logging. */ pj_strcat2(&cfg, "#\n# Logging options:\n#\n"); pj_ansi_sprintf(line, "--log-level %d\n", - config->log_cfg.level); + config->log_cfg.level); pj_strcat2(&cfg, line); pj_ansi_sprintf(line, "--app-log-level %d\n", - config->log_cfg.console_level); + config->log_cfg.console_level); pj_strcat2(&cfg, line); if (config->log_cfg.log_filename.slen) { - pj_ansi_sprintf(line, "--log-file %.*s\n", - (int)config->log_cfg.log_filename.slen, - config->log_cfg.log_filename.ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--log-file %.*s\n", + (int)config->log_cfg.log_filename.slen, + config->log_cfg.log_filename.ptr); + pj_strcat2(&cfg, line); } if (config->log_cfg.log_file_flags & PJ_O_APPEND) { - pj_strcat2(&cfg, "--log-append\n"); + pj_strcat2(&cfg, "--log-append\n"); } /* Save account settings. */ for (acc_index=0; acc_index < config->acc_cnt; ++acc_index) { - write_account_settings(acc_index, &cfg); + write_account_settings(acc_index, &cfg); - if (acc_index < config->acc_cnt-1) - pj_strcat2(&cfg, "--next-account\n"); + if (acc_index < config->acc_cnt-1) + pj_strcat2(&cfg, "--next-account\n"); } pj_strcat2(&cfg, "\n#\n# Network settings:\n#\n"); /* Nameservers */ for (i=0; icfg.nameserver_count; ++i) { - pj_ansi_sprintf(line, "--nameserver %.*s\n", - (int)config->cfg.nameserver[i].slen, - config->cfg.nameserver[i].ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--nameserver %.*s\n", + (int)config->cfg.nameserver[i].slen, + config->cfg.nameserver[i].ptr); + pj_strcat2(&cfg, line); } /* Outbound proxy */ for (i=0; icfg.outbound_proxy_cnt; ++i) { - pj_ansi_sprintf(line, "--outbound %.*s\n", - (int)config->cfg.outbound_proxy[i].slen, - config->cfg.outbound_proxy[i].ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--outbound %.*s\n", + (int)config->cfg.outbound_proxy[i].slen, + config->cfg.outbound_proxy[i].ptr); + pj_strcat2(&cfg, line); } /* Transport options */ if (config->ipv6) { - pj_strcat2(&cfg, "--ipv6\n"); + pj_strcat2(&cfg, "--ipv6\n"); } if (config->enable_qos) { - pj_strcat2(&cfg, "--set-qos\n"); + pj_strcat2(&cfg, "--set-qos\n"); } /* UDP Transport. */ @@ -1986,85 +1985,85 @@ int write_settings(pjsua_app_config *config, char *buf, pj_size_t max) /* IP address, if any. */ if (config->udp_cfg.public_addr.slen) { - pj_ansi_sprintf(line, "--ip-addr %.*s\n", - (int)config->udp_cfg.public_addr.slen, - config->udp_cfg.public_addr.ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--ip-addr %.*s\n", + (int)config->udp_cfg.public_addr.slen, + config->udp_cfg.public_addr.ptr); + pj_strcat2(&cfg, line); } /* Bound IP address, if any. */ if (config->udp_cfg.bound_addr.slen) { - pj_ansi_sprintf(line, "--bound-addr %.*s\n", - (int)config->udp_cfg.bound_addr.slen, - config->udp_cfg.bound_addr.ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--bound-addr %.*s\n", + (int)config->udp_cfg.bound_addr.slen, + config->udp_cfg.bound_addr.ptr); + pj_strcat2(&cfg, line); } /* No TCP ? */ if (config->no_tcp) { - pj_strcat2(&cfg, "--no-tcp\n"); + pj_strcat2(&cfg, "--no-tcp\n"); } /* No UDP ? */ if (config->no_udp) { - pj_strcat2(&cfg, "--no-udp\n"); + pj_strcat2(&cfg, "--no-udp\n"); } /* STUN */ for (i=0; icfg.stun_srv_cnt; ++i) { - pj_ansi_sprintf(line, "--stun-srv %.*s\n", - (int)config->cfg.stun_srv[i].slen, - config->cfg.stun_srv[i].ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--stun-srv %.*s\n", + (int)config->cfg.stun_srv[i].slen, + config->cfg.stun_srv[i].ptr); + pj_strcat2(&cfg, line); } #if defined(PJSIP_HAS_TLS_TRANSPORT) && (PJSIP_HAS_TLS_TRANSPORT != 0) /* TLS */ if (config->use_tls) - pj_strcat2(&cfg, "--use-tls\n"); + pj_strcat2(&cfg, "--use-tls\n"); if (config->udp_cfg.tls_setting.ca_list_file.slen) { - pj_ansi_sprintf(line, "--tls-ca-file %.*s\n", - (int)config->udp_cfg.tls_setting.ca_list_file.slen, - config->udp_cfg.tls_setting.ca_list_file.ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--tls-ca-file %.*s\n", + (int)config->udp_cfg.tls_setting.ca_list_file.slen, + config->udp_cfg.tls_setting.ca_list_file.ptr); + pj_strcat2(&cfg, line); } if (config->udp_cfg.tls_setting.cert_file.slen) { - pj_ansi_sprintf(line, "--tls-cert-file %.*s\n", - (int)config->udp_cfg.tls_setting.cert_file.slen, - config->udp_cfg.tls_setting.cert_file.ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--tls-cert-file %.*s\n", + (int)config->udp_cfg.tls_setting.cert_file.slen, + config->udp_cfg.tls_setting.cert_file.ptr); + pj_strcat2(&cfg, line); } if (config->udp_cfg.tls_setting.privkey_file.slen) { - pj_ansi_sprintf(line, "--tls-privkey-file %.*s\n", - (int)config->udp_cfg.tls_setting.privkey_file.slen, - config->udp_cfg.tls_setting.privkey_file.ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--tls-privkey-file %.*s\n", + (int)config->udp_cfg.tls_setting.privkey_file.slen, + config->udp_cfg.tls_setting.privkey_file.ptr); + pj_strcat2(&cfg, line); } if (config->udp_cfg.tls_setting.password.slen) { - pj_ansi_sprintf(line, "--tls-password %.*s\n", - (int)config->udp_cfg.tls_setting.password.slen, - config->udp_cfg.tls_setting.password.ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--tls-password %.*s\n", + (int)config->udp_cfg.tls_setting.password.slen, + config->udp_cfg.tls_setting.password.ptr); + pj_strcat2(&cfg, line); } if (config->udp_cfg.tls_setting.verify_server) - pj_strcat2(&cfg, "--tls-verify-server\n"); + pj_strcat2(&cfg, "--tls-verify-server\n"); if (config->udp_cfg.tls_setting.verify_client) - pj_strcat2(&cfg, "--tls-verify-client\n"); + pj_strcat2(&cfg, "--tls-verify-client\n"); if (config->udp_cfg.tls_setting.timeout.sec) { - pj_ansi_sprintf(line, "--tls-neg-timeout %d\n", - (int)config->udp_cfg.tls_setting.timeout.sec); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--tls-neg-timeout %d\n", + (int)config->udp_cfg.tls_setting.timeout.sec); + pj_strcat2(&cfg, line); } for (i=0; iudp_cfg.tls_setting.ciphers_num; ++i) { - pj_ansi_sprintf(line, "--tls-cipher 0x%06X # %s\n", - config->udp_cfg.tls_setting.ciphers[i], - pj_ssl_cipher_name(config->udp_cfg.tls_setting.ciphers[i])); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--tls-cipher 0x%06X # %s\n", + config->udp_cfg.tls_setting.ciphers[i], + pj_ssl_cipher_name(config->udp_cfg.tls_setting.ciphers[i])); + pj_strcat2(&cfg, line); } #endif @@ -2072,297 +2071,297 @@ int write_settings(pjsua_app_config *config, char *buf, pj_size_t max) /* Video & extra audio */ for (i=0; ivid.vid_cnt; ++i) { - pj_strcat2(&cfg, "--video\n"); + pj_strcat2(&cfg, "--video\n"); } for (i=1; iaud_cnt; ++i) { - pj_strcat2(&cfg, "--extra-audio\n"); + pj_strcat2(&cfg, "--extra-audio\n"); } /* SRTP */ #if PJMEDIA_HAS_SRTP if (app_config.cfg.use_srtp != PJSUA_DEFAULT_USE_SRTP) { - int use_srtp = (int)app_config.cfg.use_srtp; - if (use_srtp == PJMEDIA_SRTP_OPTIONAL && - app_config.cfg.srtp_optional_dup_offer) - { - use_srtp = 3; - } - pj_ansi_sprintf(line, "--use-srtp %d\n", use_srtp); - pj_strcat2(&cfg, line); + int use_srtp = (int)app_config.cfg.use_srtp; + if (use_srtp == PJMEDIA_SRTP_OPTIONAL && + app_config.cfg.srtp_optional_dup_offer) + { + use_srtp = 3; + } + pj_ansi_sprintf(line, "--use-srtp %d\n", use_srtp); + pj_strcat2(&cfg, line); } if (app_config.cfg.srtp_secure_signaling != - PJSUA_DEFAULT_SRTP_SECURE_SIGNALING) + PJSUA_DEFAULT_SRTP_SECURE_SIGNALING) { - pj_ansi_sprintf(line, "--srtp-secure %d\n", - app_config.cfg.srtp_secure_signaling); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--srtp-secure %d\n", + app_config.cfg.srtp_secure_signaling); + pj_strcat2(&cfg, line); } if (app_config.srtp_keying >= 0 && app_config.srtp_keying <= 1) { - pj_ansi_sprintf(line, "--srtp-keying %d\n", - app_config.srtp_keying); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--srtp-keying %d\n", + app_config.srtp_keying); + pj_strcat2(&cfg, line); } #endif /* Media */ if (config->null_audio) - pj_strcat2(&cfg, "--null-audio\n"); + pj_strcat2(&cfg, "--null-audio\n"); if (config->auto_play) - pj_strcat2(&cfg, "--auto-play\n"); + pj_strcat2(&cfg, "--auto-play\n"); if (config->auto_loop) - pj_strcat2(&cfg, "--auto-loop\n"); + pj_strcat2(&cfg, "--auto-loop\n"); if (config->auto_conf) - pj_strcat2(&cfg, "--auto-conf\n"); + pj_strcat2(&cfg, "--auto-conf\n"); for (i=0; iwav_count; ++i) { - pj_ansi_sprintf(line, "--play-file %s\n", - config->wav_files[i].ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--play-file %s\n", + config->wav_files[i].ptr); + pj_strcat2(&cfg, line); } for (i=0; itone_count; ++i) { - pj_ansi_sprintf(line, "--play-tone %d,%d,%d,%d\n", - config->tones[i].freq1, config->tones[i].freq2, - config->tones[i].on_msec, config->tones[i].off_msec); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--play-tone %d,%d,%d,%d\n", + config->tones[i].freq1, config->tones[i].freq2, + config->tones[i].on_msec, config->tones[i].off_msec); + pj_strcat2(&cfg, line); } if (config->rec_file.slen) { - pj_ansi_sprintf(line, "--rec-file %s\n", - config->rec_file.ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--rec-file %s\n", + config->rec_file.ptr); + pj_strcat2(&cfg, line); } if (config->auto_rec) - pj_strcat2(&cfg, "--auto-rec\n"); + pj_strcat2(&cfg, "--auto-rec\n"); if (config->capture_dev != PJSUA_INVALID_ID) { - pj_ansi_sprintf(line, "--capture-dev %d\n", config->capture_dev); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--capture-dev %d\n", config->capture_dev); + pj_strcat2(&cfg, line); } if (config->playback_dev != PJSUA_INVALID_ID) { - pj_ansi_sprintf(line, "--playback-dev %d\n", config->playback_dev); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--playback-dev %d\n", config->playback_dev); + pj_strcat2(&cfg, line); } if (config->media_cfg.snd_auto_close_time != -1) { - pj_ansi_sprintf(line, "--snd-auto-close %d\n", - config->media_cfg.snd_auto_close_time); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--snd-auto-close %d\n", + config->media_cfg.snd_auto_close_time); + pj_strcat2(&cfg, line); } if (config->no_tones) { - pj_strcat2(&cfg, "--no-tones\n"); + pj_strcat2(&cfg, "--no-tones\n"); } if (config->media_cfg.jb_max != -1) { - pj_ansi_sprintf(line, "--jb-max-size %d\n", - config->media_cfg.jb_max); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--jb-max-size %d\n", + config->media_cfg.jb_max); + pj_strcat2(&cfg, line); } /* Sound device latency */ if (config->capture_lat != PJMEDIA_SND_DEFAULT_REC_LATENCY) { - pj_ansi_sprintf(line, "--capture-lat %d\n", config->capture_lat); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--capture-lat %d\n", config->capture_lat); + pj_strcat2(&cfg, line); } if (config->playback_lat != PJMEDIA_SND_DEFAULT_PLAY_LATENCY) { - pj_ansi_sprintf(line, "--playback-lat %d\n", config->playback_lat); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--playback-lat %d\n", config->playback_lat); + pj_strcat2(&cfg, line); } /* Media clock rate. */ if (config->media_cfg.clock_rate != PJSUA_DEFAULT_CLOCK_RATE) { - pj_ansi_sprintf(line, "--clock-rate %d\n", - config->media_cfg.clock_rate); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--clock-rate %d\n", + config->media_cfg.clock_rate); + pj_strcat2(&cfg, line); } else { - pj_ansi_sprintf(line, "#using default --clock-rate %d\n", - config->media_cfg.clock_rate); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "#using default --clock-rate %d\n", + config->media_cfg.clock_rate); + pj_strcat2(&cfg, line); } if (config->media_cfg.snd_clock_rate && - config->media_cfg.snd_clock_rate != config->media_cfg.clock_rate) + config->media_cfg.snd_clock_rate != config->media_cfg.clock_rate) { - pj_ansi_sprintf(line, "--snd-clock-rate %d\n", - config->media_cfg.snd_clock_rate); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--snd-clock-rate %d\n", + config->media_cfg.snd_clock_rate); + pj_strcat2(&cfg, line); } /* Stereo mode. */ if (config->media_cfg.channel_count == 2) { - pj_ansi_sprintf(line, "--stereo\n"); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--stereo\n"); + pj_strcat2(&cfg, line); } /* quality */ if (config->media_cfg.quality != PJSUA_DEFAULT_CODEC_QUALITY) { - pj_ansi_sprintf(line, "--quality %d\n", - config->media_cfg.quality); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--quality %d\n", + config->media_cfg.quality); + pj_strcat2(&cfg, line); } else { - pj_ansi_sprintf(line, "#using default --quality %d\n", - config->media_cfg.quality); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "#using default --quality %d\n", + config->media_cfg.quality); + pj_strcat2(&cfg, line); } if (config->vid.vcapture_dev != PJMEDIA_VID_DEFAULT_CAPTURE_DEV) { - pj_ansi_sprintf(line, "--vcapture-dev %d\n", config->vid.vcapture_dev); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--vcapture-dev %d\n", config->vid.vcapture_dev); + pj_strcat2(&cfg, line); } if (config->vid.vrender_dev != PJMEDIA_VID_DEFAULT_RENDER_DEV) { - pj_ansi_sprintf(line, "--vrender-dev %d\n", config->vid.vrender_dev); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--vrender-dev %d\n", config->vid.vrender_dev); + pj_strcat2(&cfg, line); } for (i=0; iavi_cnt; ++i) { - pj_ansi_sprintf(line, "--play-avi %s\n", config->avi[i].path.ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--play-avi %s\n", config->avi[i].path.ptr); + pj_strcat2(&cfg, line); } if (config->avi_auto_play) { - pj_ansi_sprintf(line, "--auto-play-avi\n"); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--auto-play-avi\n"); + pj_strcat2(&cfg, line); } /* ptime */ if (config->media_cfg.ptime) { - pj_ansi_sprintf(line, "--ptime %d\n", - config->media_cfg.ptime); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--ptime %d\n", + config->media_cfg.ptime); + pj_strcat2(&cfg, line); } /* no-vad */ if (config->media_cfg.no_vad) { - pj_strcat2(&cfg, "--no-vad\n"); + pj_strcat2(&cfg, "--no-vad\n"); } /* ec-tail */ if (config->media_cfg.ec_tail_len != PJSUA_DEFAULT_EC_TAIL_LEN) { - pj_ansi_sprintf(line, "--ec-tail %d\n", - config->media_cfg.ec_tail_len); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--ec-tail %d\n", + config->media_cfg.ec_tail_len); + pj_strcat2(&cfg, line); } else { - pj_ansi_sprintf(line, "#using default --ec-tail %d\n", - config->media_cfg.ec_tail_len); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "#using default --ec-tail %d\n", + config->media_cfg.ec_tail_len); + pj_strcat2(&cfg, line); } /* ec-opt */ if (config->media_cfg.ec_options != 0) { - pj_ansi_sprintf(line, "--ec-opt %d\n", - config->media_cfg.ec_options); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--ec-opt %d\n", + config->media_cfg.ec_options); + pj_strcat2(&cfg, line); } /* ilbc-mode */ if (config->media_cfg.ilbc_mode != PJSUA_DEFAULT_ILBC_MODE) { - pj_ansi_sprintf(line, "--ilbc-mode %d\n", - config->media_cfg.ilbc_mode); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--ilbc-mode %d\n", + config->media_cfg.ilbc_mode); + pj_strcat2(&cfg, line); } else { - pj_ansi_sprintf(line, "#using default --ilbc-mode %d\n", - config->media_cfg.ilbc_mode); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "#using default --ilbc-mode %d\n", + config->media_cfg.ilbc_mode); + pj_strcat2(&cfg, line); } /* RTP drop */ if (config->media_cfg.tx_drop_pct) { - pj_ansi_sprintf(line, "--tx-drop-pct %d\n", - config->media_cfg.tx_drop_pct); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--tx-drop-pct %d\n", + config->media_cfg.tx_drop_pct); + pj_strcat2(&cfg, line); } if (config->media_cfg.rx_drop_pct) { - pj_ansi_sprintf(line, "--rx-drop-pct %d\n", - config->media_cfg.rx_drop_pct); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--rx-drop-pct %d\n", + config->media_cfg.rx_drop_pct); + pj_strcat2(&cfg, line); } /* Start RTP port. */ pj_ansi_sprintf(line, "--rtp-port %d\n", - config->rtp_cfg.port); + config->rtp_cfg.port); pj_strcat2(&cfg, line); /* Disable codec */ for (i=0; icodec_dis_cnt; ++i) { - pj_ansi_sprintf(line, "--dis-codec %s\n", - config->codec_dis[i].ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--dis-codec %s\n", + config->codec_dis[i].ptr); + pj_strcat2(&cfg, line); } /* Add codec. */ for (i=0; icodec_cnt; ++i) { - pj_ansi_sprintf(line, "--add-codec %s\n", - config->codec_arg[i].ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--add-codec %s\n", + config->codec_arg[i].ptr); + pj_strcat2(&cfg, line); } pj_strcat2(&cfg, "\n#\n# User agent:\n#\n"); /* Auto-answer. */ if (config->auto_answer != 0) { - pj_ansi_sprintf(line, "--auto-answer %d\n", - config->auto_answer); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--auto-answer %d\n", + config->auto_answer); + pj_strcat2(&cfg, line); } /* accept-redirect */ if (config->redir_op != PJSIP_REDIRECT_ACCEPT_REPLACE) { - pj_ansi_sprintf(line, "--accept-redirect %d\n", - config->redir_op); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--accept-redirect %d\n", + config->redir_op); + pj_strcat2(&cfg, line); } /* Max calls. */ pj_ansi_sprintf(line, "--max-calls %d\n", - config->cfg.max_calls); + config->cfg.max_calls); pj_strcat2(&cfg, line); /* Uas-duration. */ if (config->duration != PJSUA_APP_NO_LIMIT_DURATION) { - pj_ansi_sprintf(line, "--duration %d\n", - config->duration); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--duration %d\n", + config->duration); + pj_strcat2(&cfg, line); } /* norefersub ? */ if (config->no_refersub) { - pj_strcat2(&cfg, "--norefersub\n"); + pj_strcat2(&cfg, "--norefersub\n"); } if (pjsip_cfg()->endpt.use_compact_form) { - pj_strcat2(&cfg, "--use-compact-form\n"); + pj_strcat2(&cfg, "--use-compact-form\n"); } if (!config->cfg.force_lr) { - pj_strcat2(&cfg, "--no-force-lr\n"); + pj_strcat2(&cfg, "--no-force-lr\n"); } pj_strcat2(&cfg, "\n#\n# Buddies:\n#\n"); /* Add buddies. */ for (i=0; ibuddy_cnt; ++i) { - pj_ansi_sprintf(line, "--add-buddy %.*s\n", - (int)config->buddy_cfg[i].uri.slen, - config->buddy_cfg[i].uri.ptr); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--add-buddy %.*s\n", + (int)config->buddy_cfg[i].uri.slen, + config->buddy_cfg[i].uri.ptr); + pj_strcat2(&cfg, line); } /* SIP extensions. */ pj_strcat2(&cfg, "\n#\n# SIP extensions:\n#\n"); /* 100rel extension */ if (config->cfg.require_100rel == PJSUA_100REL_MANDATORY) { - pj_strcat2(&cfg, "--use-100rel\n"); + pj_strcat2(&cfg, "--use-100rel\n"); } /* Session Timer extension */ if (config->cfg.use_timer) { - pj_ansi_sprintf(line, "--use-timer %d\n", - config->cfg.use_timer); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--use-timer %d\n", + config->cfg.use_timer); + pj_strcat2(&cfg, line); } if (config->cfg.timer_setting.min_se != 90) { - pj_ansi_sprintf(line, "--timer-min-se %d\n", - config->cfg.timer_setting.min_se); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--timer-min-se %d\n", + config->cfg.timer_setting.min_se); + pj_strcat2(&cfg, line); } if (config->cfg.timer_setting.sess_expires != PJSIP_SESS_TIMER_DEF_SE) { - pj_ansi_sprintf(line, "--timer-se %d\n", - config->cfg.timer_setting.sess_expires); - pj_strcat2(&cfg, line); + pj_ansi_sprintf(line, "--timer-se %d\n", + config->cfg.timer_setting.sess_expires); + pj_strcat2(&cfg, line); } *(cfg.ptr + cfg.slen) = '\0'; diff --git a/pjsip-apps/src/pjsua/pjsua_app_config.h b/pjsip-apps/src/pjsua/pjsua_app_config.h index a010c8b532..2e65b2c7c7 100644 --- a/pjsip-apps/src/pjsua/pjsua_app_config.h +++ b/pjsip-apps/src/pjsua/pjsua_app_config.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2013 Teluu Inc. (http://www.teluu.com) * @@ -27,25 +26,25 @@ * your source file. */ const char *pjsua_app_def_argv[] = { "pjsua", - "--use-cli", - "--no-cli-console", - "--quality=4", + "--use-cli", + "--no-cli-console", + "--quality=4", #if defined(PJMEDIA_HAS_VIDEO) && PJMEDIA_HAS_VIDEO - "--video", + "--video", #endif #if defined(PJ_SYMBIAN) && PJ_SYMBIAN - /* Can't reuse address on E52 */ - "--cli-telnet-port=0", + /* Can't reuse address on E52 */ + "--cli-telnet-port=0", #else - "--cli-telnet-port=2323", + "--cli-telnet-port=2323", #endif #if defined(PJ_CONFIG_BB10) && PJ_CONFIG_BB10 - "--add-buddy=sip:169.254.0.2", + "--add-buddy=sip:169.254.0.2", #endif - NULL }; + NULL }; #define pjsua_app_def_argc (PJ_ARRAY_SIZE(pjsua_app_def_argv)-1) -#endif /* __PJSUA_APP_CONFIG_H__ */ +#endif /* __PJSUA_APP_CONFIG_H__ */ diff --git a/pjsip-apps/src/pjsua/pjsua_app_legacy.c b/pjsip-apps/src/pjsua/pjsua_app_legacy.c index 04e21889e0..8907e1472a 100644 --- a/pjsip-apps/src/pjsua/pjsua_app_legacy.c +++ b/pjsip-apps/src/pjsua/pjsua_app_legacy.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,7 +20,7 @@ #include #include "pjsua_app_common.h" -#define THIS_FILE "pjsua_app_legacy.c" +#define THIS_FILE "pjsua_app_legacy.c" /* An attempt to avoid stdout buffering for python tests: @@ -37,7 +36,7 @@ #endif -static pj_bool_t cmd_echo; +static pj_bool_t cmd_echo; /* * Print buddy list. @@ -53,21 +52,21 @@ static void print_buddy_list() pjsua_enum_buddies(ids, &count); if (count == 0) { - puts(" -none-"); + puts(" -none-"); } else { - for (i=0; i<(int)count; ++i) { - pjsua_buddy_info info; - - if (pjsua_buddy_get_info(ids[i], &info) != PJ_SUCCESS) - continue; - - printf(" [%2d] <%.*s> %.*s\n", - ids[i]+1, - (int)info.status_text.slen, - info.status_text.ptr, - (int)info.uri.slen, - info.uri.ptr); - } + for (i=0; i<(int)count; ++i) { + pjsua_buddy_info info; + + if (pjsua_buddy_get_info(ids[i], &info) != PJ_SUCCESS) + continue; + + printf(" [%2d] <%.*s> %.*s\n", + ids[i]+1, + (int)info.status_text.slen, + info.status_text.ptr, + (int)info.uri.slen, + info.uri.ptr); + } } puts(""); } @@ -76,7 +75,7 @@ static void print_buddy_list() * Input URL. */ static void ui_input_url(const char *title, char *buf, pj_size_t len, - input_result *result) + input_result *result) { result->nb_result = PJSUA_APP_NO_NB; result->uri_result = NULL; @@ -84,71 +83,71 @@ static void ui_input_url(const char *title, char *buf, pj_size_t len, print_buddy_list(); printf("Choices:\n" - " 0 For current dialog.\n" - " -1 All %d buddies in buddy list\n" - " [1 -%2d] Select from buddy list\n" - " URL An URL\n" - " Empty input (or 'q') to cancel\n" - , pjsua_get_buddy_count(), pjsua_get_buddy_count()); + " 0 For current dialog.\n" + " -1 All %d buddies in buddy list\n" + " [1 -%2d] Select from buddy list\n" + " URL An URL\n" + " Empty input (or 'q') to cancel\n" + , pjsua_get_buddy_count(), pjsua_get_buddy_count()); printf("%s: ", title); fflush(stdout); if (fgets(buf, (int)len, stdin) == NULL) - return; + return; len = strlen(buf); /* Left trim */ while (pj_isspace(*buf)) { - ++buf; - --len; + ++buf; + --len; } /* Remove trailing newlines */ while (len && (buf[len-1] == '\r' || buf[len-1] == '\n')) - buf[--len] = '\0'; + buf[--len] = '\0'; if (len == 0 || buf[0]=='q') - return; + return; if (pj_isdigit(*buf) || *buf=='-') { - unsigned i; + unsigned i; - if (*buf=='-') - i = 1; - else - i = 0; + if (*buf=='-') + i = 1; + else + i = 0; - for (; inb_result = my_atoi(buf); + result->nb_result = my_atoi(buf); - if (result->nb_result >= 0 && - result->nb_result <= (int)pjsua_get_buddy_count()) - { - return; - } - if (result->nb_result == -1) - return; + if (result->nb_result >= 0 && + result->nb_result <= (int)pjsua_get_buddy_count()) + { + return; + } + if (result->nb_result == -1) + return; - puts("Invalid input"); - result->nb_result = PJSUA_APP_NO_NB; - return; + puts("Invalid input"); + result->nb_result = PJSUA_APP_NO_NB; + return; } else { - pj_status_t status; + pj_status_t status; - if ((status=pjsua_verify_url(buf)) != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Invalid URL", status); - return; - } + if ((status=pjsua_verify_url(buf)) != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Invalid URL", status); + return; + } - result->uri_result = buf; + result->uri_result = buf; } } @@ -158,16 +157,16 @@ static pj_bool_t simple_input(const char *title, char *buf, pj_size_t len) printf("%s (empty to cancel): ", title); fflush(stdout); if (fgets(buf, (int)len, stdin) == NULL) - return PJ_FALSE; + return PJ_FALSE; /* Remove trailing newlines. */ for (p=buf; ; ++p) { - if (*p=='\r' || *p=='\n') *p='\0'; - else if (!*p) break; + if (*p=='\r' || *p=='\n') *p='\0'; + else if (!*p) break; } if (!*buf) - return PJ_FALSE; + return PJ_FALSE; return PJ_TRUE; } @@ -183,25 +182,25 @@ static void print_acc_status(int acc_id) pjsua_acc_get_info(acc_id, &info); if (!info.has_registration) { - pj_ansi_snprintf(buf, sizeof(buf), "%.*s", - (int)info.status_text.slen, - info.status_text.ptr); + pj_ansi_snprintf(buf, sizeof(buf), "%.*s", + (int)info.status_text.slen, + info.status_text.ptr); } else { - pj_ansi_snprintf(buf, sizeof(buf), - "%d/%.*s (expires=%d)", - info.status, - (int)info.status_text.slen, - info.status_text.ptr, - info.expires); + pj_ansi_snprintf(buf, sizeof(buf), + "%d/%.*s (expires=%d)", + info.status, + (int)info.status_text.slen, + info.status_text.ptr, + info.expires); } printf(" %c[%2d] %.*s: %s\n", (acc_id==current_acc?'*':' '), - acc_id, (int)info.acc_uri.slen, info.acc_uri.ptr, buf); + acc_id, (int)info.acc_uri.slen, info.acc_uri.ptr, buf); printf(" Online status: %.*s\n", - (int)info.online_status_text.slen, - info.online_status_text.ptr); + (int)info.online_status_text.slen, + info.online_status_text.ptr); } /* @@ -219,7 +218,7 @@ static void keystroke_help() printf("Account list:\n"); for (i=0; i<(int)count; ++i) - print_acc_status(acc_ids[i]); + print_acc_status(acc_ids[i]); print_buddy_list(); @@ -255,11 +254,11 @@ static void keystroke_help() printf("You have %d active call%s\n", i, (i>1?"s":"")); if (current_call != PJSUA_INVALID_ID) { - pjsua_call_info ci; - if (pjsua_call_get_info(current_call, &ci)==PJ_SUCCESS) - printf("Current call id=%d to %.*s [%.*s]\n", current_call, - (int)ci.remote_info.slen, ci.remote_info.ptr, - (int)ci.state_text.slen, ci.state_text.ptr); + pjsua_call_info ci; + if (pjsua_call_get_info(current_call, &ci)==PJ_SUCCESS) + printf("Current call id=%d to %.*s [%.*s]\n", current_call, + (int)ci.remote_info.slen, ci.remote_info.ptr, + (int)ci.state_text.slen, ci.state_text.ptr); } } @@ -297,13 +296,13 @@ static void vid_show_help() puts("| vid win show|hide ID Show/hide the specified video window ID |"); puts("| vid win move ID X Y Move window ID to position X,Y |"); puts("| vid win resize ID w h Resize window ID to the specified width, height |"); - puts("| vid win full off|on|dt ID Set fullscreen off/on/desktop for window ID |"); + puts("| vid win full off|on|dt ID Set fullscreen off/on/desktop for window ID |"); puts("| vid conf list List all video ports in video conference bridge |"); puts("| vid conf cc P Q Connect port P to Q in the video conf bridge |"); puts("| vid conf cd P Q Disconnect port P to Q in the video conf bridge |"); puts("+=============================================================================+"); printf("| Video will be %s in the next offer/answer %s |\n", - (vid_enabled? "enabled" : "disabled"), (vid_enabled? " " : "")); + (vid_enabled? "enabled" : "disabled"), (vid_enabled? " " : "")); puts("+=============================================================================+"); } @@ -315,372 +314,372 @@ static void vid_handle_menu(char *menuin) /* Tokenize */ argv[argc] = strtok(menuin, " \t\r\n"); while (argv[argc] && *argv[argc]) { - argc++; - argv[argc] = strtok(NULL, " \t\r\n"); + argc++; + argv[argc] = strtok(NULL, " \t\r\n"); } if (argc == 1 || strcmp(argv[1], "help")==0) { - vid_show_help(); + vid_show_help(); } else if (argc == 2 && (strcmp(argv[1], "enable")==0 || - strcmp(argv[1], "disable")==0)) + strcmp(argv[1], "disable")==0)) { - pj_bool_t enabled = (strcmp(argv[1], "enable")==0); - app_config.vid.vid_cnt = (enabled ? 1 : 0); - PJ_LOG(3,(THIS_FILE, "Video will be %s in next offer/answer", - (enabled?"enabled":"disabled"))); + pj_bool_t enabled = (strcmp(argv[1], "enable")==0); + app_config.vid.vid_cnt = (enabled ? 1 : 0); + PJ_LOG(3,(THIS_FILE, "Video will be %s in next offer/answer", + (enabled?"enabled":"disabled"))); } else if (strcmp(argv[1], "acc")==0) { - pjsua_acc_config acc_cfg; - pj_bool_t changed = PJ_FALSE; - pj_pool_t *tmp_pool = pjsua_pool_create("tmp-pjsua", 1000, 1000); - - pjsua_acc_get_config(current_acc, tmp_pool, &acc_cfg); - - if (argc == 3 && strcmp(argv[2], "show")==0) { - app_config_show_video(current_acc, &acc_cfg); - } else if (argc == 4 && strcmp(argv[2], "autorx")==0) { - int on = (strcmp(argv[3], "on")==0); - acc_cfg.vid_in_auto_show = on; - changed = PJ_TRUE; - } else if (argc == 4 && strcmp(argv[2], "autotx")==0) { - int on = (strcmp(argv[3], "on")==0); - acc_cfg.vid_out_auto_transmit = on; - changed = PJ_TRUE; - } else if (argc == 4 && strcmp(argv[2], "cap")==0) { - int dev = atoi(argv[3]); - acc_cfg.vid_cap_dev = dev; - changed = PJ_TRUE; - } else if (argc == 4 && strcmp(argv[2], "rend")==0) { - int dev = atoi(argv[3]); - acc_cfg.vid_rend_dev = dev; - changed = PJ_TRUE; - } else { - pj_pool_release(tmp_pool); - goto on_error; - } - - if (changed) { - pj_status_t status = pjsua_acc_modify(current_acc, &acc_cfg); - if (status != PJ_SUCCESS) - PJ_PERROR(1,(THIS_FILE, status, "Error modifying account %d", - current_acc)); - } - pj_pool_release(tmp_pool); + pjsua_acc_config acc_cfg; + pj_bool_t changed = PJ_FALSE; + pj_pool_t *tmp_pool = pjsua_pool_create("tmp-pjsua", 1000, 1000); + + pjsua_acc_get_config(current_acc, tmp_pool, &acc_cfg); + + if (argc == 3 && strcmp(argv[2], "show")==0) { + app_config_show_video(current_acc, &acc_cfg); + } else if (argc == 4 && strcmp(argv[2], "autorx")==0) { + int on = (strcmp(argv[3], "on")==0); + acc_cfg.vid_in_auto_show = on; + changed = PJ_TRUE; + } else if (argc == 4 && strcmp(argv[2], "autotx")==0) { + int on = (strcmp(argv[3], "on")==0); + acc_cfg.vid_out_auto_transmit = on; + changed = PJ_TRUE; + } else if (argc == 4 && strcmp(argv[2], "cap")==0) { + int dev = atoi(argv[3]); + acc_cfg.vid_cap_dev = dev; + changed = PJ_TRUE; + } else if (argc == 4 && strcmp(argv[2], "rend")==0) { + int dev = atoi(argv[3]); + acc_cfg.vid_rend_dev = dev; + changed = PJ_TRUE; + } else { + pj_pool_release(tmp_pool); + goto on_error; + } + + if (changed) { + pj_status_t status = pjsua_acc_modify(current_acc, &acc_cfg); + if (status != PJ_SUCCESS) + PJ_PERROR(1,(THIS_FILE, status, "Error modifying account %d", + current_acc)); + } + pj_pool_release(tmp_pool); } else if (strcmp(argv[1], "call")==0) { - pjsua_call_vid_strm_op_param param; - pj_status_t status = PJ_SUCCESS; - - pjsua_call_vid_strm_op_param_default(¶m); - - if (argc == 5 && strcmp(argv[2], "rx")==0) { - pjsua_stream_info si; - pj_bool_t on = (strcmp(argv[3], "on") == 0); - - param.med_idx = atoi(argv[4]); - if (pjsua_call_get_stream_info(current_call, param.med_idx, &si) || - si.type != PJMEDIA_TYPE_VIDEO) - { - PJ_PERROR(1,(THIS_FILE, PJ_EINVAL, "Invalid stream")); - return; - } - - if (on) param.dir = (si.info.vid.dir | PJMEDIA_DIR_DECODING); - else param.dir = (si.info.vid.dir & PJMEDIA_DIR_ENCODING); - - status = pjsua_call_set_vid_strm(current_call, - PJSUA_CALL_VID_STRM_CHANGE_DIR, - ¶m); - } - else if (argc == 5 && strcmp(argv[2], "tx")==0) { - pj_bool_t on = (strcmp(argv[3], "on") == 0); - pjsua_call_vid_strm_op op = on? PJSUA_CALL_VID_STRM_START_TRANSMIT : - PJSUA_CALL_VID_STRM_STOP_TRANSMIT; - - param.med_idx = atoi(argv[4]); - - status = pjsua_call_set_vid_strm(current_call, op, ¶m); - } - else if (argc == 3 && strcmp(argv[2], "add")==0) { - status = pjsua_call_set_vid_strm(current_call, - PJSUA_CALL_VID_STRM_ADD, NULL); - } - else if (argc >= 3 && - (strcmp(argv[2], "disable")==0 || strcmp(argv[2], "enable")==0)) - { - pj_bool_t enable = (strcmp(argv[2], "enable") == 0); - pjsua_call_vid_strm_op op = enable? PJSUA_CALL_VID_STRM_CHANGE_DIR : - PJSUA_CALL_VID_STRM_REMOVE; - - param.med_idx = argc >= 4? atoi(argv[3]) : -1; - param.dir = PJMEDIA_DIR_ENCODING_DECODING; - status = pjsua_call_set_vid_strm(current_call, op, ¶m); - } - else if (argc >= 3 && strcmp(argv[2], "cap")==0) { - param.med_idx = argc >= 4? atoi(argv[3]) : -1; - param.cap_dev = argc >= 5? atoi(argv[4]) : PJMEDIA_VID_DEFAULT_CAPTURE_DEV; - status = pjsua_call_set_vid_strm(current_call, - PJSUA_CALL_VID_STRM_CHANGE_CAP_DEV, - ¶m); - } else - goto on_error; - - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "Error modifying video stream")); - } + pjsua_call_vid_strm_op_param param; + pj_status_t status = PJ_SUCCESS; + + pjsua_call_vid_strm_op_param_default(¶m); + + if (argc == 5 && strcmp(argv[2], "rx")==0) { + pjsua_stream_info si; + pj_bool_t on = (strcmp(argv[3], "on") == 0); + + param.med_idx = atoi(argv[4]); + if (pjsua_call_get_stream_info(current_call, param.med_idx, &si) || + si.type != PJMEDIA_TYPE_VIDEO) + { + PJ_PERROR(1,(THIS_FILE, PJ_EINVAL, "Invalid stream")); + return; + } + + if (on) param.dir = (si.info.vid.dir | PJMEDIA_DIR_DECODING); + else param.dir = (si.info.vid.dir & PJMEDIA_DIR_ENCODING); + + status = pjsua_call_set_vid_strm(current_call, + PJSUA_CALL_VID_STRM_CHANGE_DIR, + ¶m); + } + else if (argc == 5 && strcmp(argv[2], "tx")==0) { + pj_bool_t on = (strcmp(argv[3], "on") == 0); + pjsua_call_vid_strm_op op = on? PJSUA_CALL_VID_STRM_START_TRANSMIT : + PJSUA_CALL_VID_STRM_STOP_TRANSMIT; + + param.med_idx = atoi(argv[4]); + + status = pjsua_call_set_vid_strm(current_call, op, ¶m); + } + else if (argc == 3 && strcmp(argv[2], "add")==0) { + status = pjsua_call_set_vid_strm(current_call, + PJSUA_CALL_VID_STRM_ADD, NULL); + } + else if (argc >= 3 && + (strcmp(argv[2], "disable")==0 || strcmp(argv[2], "enable")==0)) + { + pj_bool_t enable = (strcmp(argv[2], "enable") == 0); + pjsua_call_vid_strm_op op = enable? PJSUA_CALL_VID_STRM_CHANGE_DIR : + PJSUA_CALL_VID_STRM_REMOVE; + + param.med_idx = argc >= 4? atoi(argv[3]) : -1; + param.dir = PJMEDIA_DIR_ENCODING_DECODING; + status = pjsua_call_set_vid_strm(current_call, op, ¶m); + } + else if (argc >= 3 && strcmp(argv[2], "cap")==0) { + param.med_idx = argc >= 4? atoi(argv[3]) : -1; + param.cap_dev = argc >= 5? atoi(argv[4]) : PJMEDIA_VID_DEFAULT_CAPTURE_DEV; + status = pjsua_call_set_vid_strm(current_call, + PJSUA_CALL_VID_STRM_CHANGE_CAP_DEV, + ¶m); + } else + goto on_error; + + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, "Error modifying video stream")); + } } else if (argc >= 3 && strcmp(argv[1], "dev")==0) { - if (strcmp(argv[2], "list")==0) { - vid_list_devs(); - } else if (strcmp(argv[2], "refresh")==0) { - pjmedia_vid_dev_refresh(); - } else if (strcmp(argv[2], "prev")==0) { - if (argc != 5) { - goto on_error; - } else { - pj_bool_t on = (strcmp(argv[3], "on") == 0); - int dev_id = atoi(argv[4]); - if (on) { + if (strcmp(argv[2], "list")==0) { + vid_list_devs(); + } else if (strcmp(argv[2], "refresh")==0) { + pjmedia_vid_dev_refresh(); + } else if (strcmp(argv[2], "prev")==0) { + if (argc != 5) { + goto on_error; + } else { + pj_bool_t on = (strcmp(argv[3], "on") == 0); + int dev_id = atoi(argv[4]); + if (on) { pjsua_vid_preview_param param; pjsua_vid_preview_param_default(¶m); param.wnd_flags = PJMEDIA_VID_DEV_WND_BORDER | PJMEDIA_VID_DEV_WND_RESIZABLE; - pjsua_vid_preview_start(dev_id, ¶m); - arrange_window(pjsua_vid_preview_get_win(dev_id)); - } else { - pjsua_vid_win_id wid; - wid = pjsua_vid_preview_get_win(dev_id); - if (wid != PJSUA_INVALID_ID) { - /* Preview window hiding once it is stopped is - * responsibility of app */ - pjsua_vid_win_set_show(wid, PJ_FALSE); - pjsua_vid_preview_stop(dev_id); - } - } - } - } else - goto on_error; + pjsua_vid_preview_start(dev_id, ¶m); + arrange_window(pjsua_vid_preview_get_win(dev_id)); + } else { + pjsua_vid_win_id wid; + wid = pjsua_vid_preview_get_win(dev_id); + if (wid != PJSUA_INVALID_ID) { + /* Preview window hiding once it is stopped is + * responsibility of app */ + pjsua_vid_win_set_show(wid, PJ_FALSE); + pjsua_vid_preview_stop(dev_id); + } + } + } + } else + goto on_error; } else if (strcmp(argv[1], "win")==0) { - pj_status_t status = PJ_SUCCESS; - - if (argc==3 && strcmp(argv[2], "list")==0) { - pjsua_vid_win_id wids[PJSUA_MAX_VID_WINS]; - unsigned i, cnt = PJ_ARRAY_SIZE(wids); - - pjsua_vid_enum_wins(wids, &cnt); - - PJ_LOG(3,(THIS_FILE, "Found %d video windows:", cnt)); - PJ_LOG(3,(THIS_FILE, "WID show pos size")); - PJ_LOG(3,(THIS_FILE, "------------------------------")); - for (i = 0; i < cnt; ++i) { - pjsua_vid_win_info wi; - pjsua_vid_win_get_info(wids[i], &wi); - PJ_LOG(3,(THIS_FILE, "%3d %c (%d,%d) %dx%d", - wids[i], (wi.show?'Y':'N'), wi.pos.x, wi.pos.y, - wi.size.w, wi.size.h)); - } - } else if (argc==4 && (strcmp(argv[2], "show")==0 || - strcmp(argv[2], "hide")==0)) - { - pj_bool_t show = (strcmp(argv[2], "show")==0); - pjsua_vid_win_id wid = atoi(argv[3]); - status = pjsua_vid_win_set_show(wid, show); - } else if (argc==6 && strcmp(argv[2], "move")==0) { - pjsua_vid_win_id wid = atoi(argv[3]); - pjmedia_coord pos; - - pos.x = atoi(argv[4]); - pos.y = atoi(argv[5]); - status = pjsua_vid_win_set_pos(wid, &pos); - } else if (argc==6 && strcmp(argv[2], "resize")==0) { - pjsua_vid_win_id wid = atoi(argv[3]); - pjmedia_rect_size size; - - size.w = atoi(argv[4]); - size.h = atoi(argv[5]); - status = pjsua_vid_win_set_size(wid, &size); - } else if (argc==3 && strcmp(argv[2], "arrange")==0) { - arrange_window(PJSUA_INVALID_ID); - } else if (argc==5 && (strcmp(argv[2], "full")==0)) - { - pjsua_vid_win_id wid = atoi(argv[4]); - pjmedia_vid_dev_fullscreen_flag mode = PJMEDIA_VID_DEV_WINDOWED; - if (strcmp(argv[3], "on")==0) - mode = PJMEDIA_VID_DEV_FULLSCREEN; - else if (strcmp(argv[3], "dt")==0) - mode = PJMEDIA_VID_DEV_FULLSCREEN_DESKTOP; - status = pjsua_vid_win_set_fullscreen(wid, mode); - } else - goto on_error; - - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "Window operation error")); - } + pj_status_t status = PJ_SUCCESS; + + if (argc==3 && strcmp(argv[2], "list")==0) { + pjsua_vid_win_id wids[PJSUA_MAX_VID_WINS]; + unsigned i, cnt = PJ_ARRAY_SIZE(wids); + + pjsua_vid_enum_wins(wids, &cnt); + + PJ_LOG(3,(THIS_FILE, "Found %d video windows:", cnt)); + PJ_LOG(3,(THIS_FILE, "WID show pos size")); + PJ_LOG(3,(THIS_FILE, "------------------------------")); + for (i = 0; i < cnt; ++i) { + pjsua_vid_win_info wi; + pjsua_vid_win_get_info(wids[i], &wi); + PJ_LOG(3,(THIS_FILE, "%3d %c (%d,%d) %dx%d", + wids[i], (wi.show?'Y':'N'), wi.pos.x, wi.pos.y, + wi.size.w, wi.size.h)); + } + } else if (argc==4 && (strcmp(argv[2], "show")==0 || + strcmp(argv[2], "hide")==0)) + { + pj_bool_t show = (strcmp(argv[2], "show")==0); + pjsua_vid_win_id wid = atoi(argv[3]); + status = pjsua_vid_win_set_show(wid, show); + } else if (argc==6 && strcmp(argv[2], "move")==0) { + pjsua_vid_win_id wid = atoi(argv[3]); + pjmedia_coord pos; + + pos.x = atoi(argv[4]); + pos.y = atoi(argv[5]); + status = pjsua_vid_win_set_pos(wid, &pos); + } else if (argc==6 && strcmp(argv[2], "resize")==0) { + pjsua_vid_win_id wid = atoi(argv[3]); + pjmedia_rect_size size; + + size.w = atoi(argv[4]); + size.h = atoi(argv[5]); + status = pjsua_vid_win_set_size(wid, &size); + } else if (argc==3 && strcmp(argv[2], "arrange")==0) { + arrange_window(PJSUA_INVALID_ID); + } else if (argc==5 && (strcmp(argv[2], "full")==0)) + { + pjsua_vid_win_id wid = atoi(argv[4]); + pjmedia_vid_dev_fullscreen_flag mode = PJMEDIA_VID_DEV_WINDOWED; + if (strcmp(argv[3], "on")==0) + mode = PJMEDIA_VID_DEV_FULLSCREEN; + else if (strcmp(argv[3], "dt")==0) + mode = PJMEDIA_VID_DEV_FULLSCREEN_DESKTOP; + status = pjsua_vid_win_set_fullscreen(wid, mode); + } else + goto on_error; + + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, "Window operation error")); + } } else if (strcmp(argv[1], "codec")==0) { - pjsua_codec_info ci[PJMEDIA_CODEC_MGR_MAX_CODECS]; - unsigned count = PJ_ARRAY_SIZE(ci); - pj_status_t status; - - if (argc==3 && strcmp(argv[2], "list")==0) { - status = pjsua_vid_enum_codecs(ci, &count); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "Error enumerating codecs")); - } else { - unsigned i; - PJ_LOG(3,(THIS_FILE, "Found %d video codecs:", count)); - PJ_LOG(3,(THIS_FILE, "codec id prio fps bw(kbps) size")); - PJ_LOG(3,(THIS_FILE, "------------------------------------------")); - for (i=0; ifps.num*1.0/vfd->fps.denum), - vfd->avg_bps/1000, vfd->max_bps/1000, - vfd->size.w, vfd->size.h)); - } - } - } else if (argc==5 && strcmp(argv[2], "prio")==0) { - pj_str_t cid; - int prio; - cid = pj_str(argv[3]); - prio = atoi(argv[4]); - status = pjsua_vid_codec_set_priority(&cid, (pj_uint8_t)prio); - if (status != PJ_SUCCESS) - PJ_PERROR(1,(THIS_FILE, status, "Set codec priority error")); - } else if (argc==6 && strcmp(argv[2], "fps")==0) { - pjmedia_vid_codec_param cp; - pj_str_t cid; - int M, N; - cid = pj_str(argv[3]); - M = atoi(argv[4]); - N = atoi(argv[5]); - status = pjsua_vid_codec_get_param(&cid, &cp); - if (status == PJ_SUCCESS) { - cp.enc_fmt.det.vid.fps.num = M; - cp.enc_fmt.det.vid.fps.denum = N; - status = pjsua_vid_codec_set_param(&cid, &cp); - } - if (status != PJ_SUCCESS) - PJ_PERROR(1,(THIS_FILE, status, "Set codec framerate error")); - } else if (argc==6 && strcmp(argv[2], "bw")==0) { - pjmedia_vid_codec_param cp; - pj_str_t cid; - int M, N; - cid = pj_str(argv[3]); - M = atoi(argv[4]); - N = atoi(argv[5]); - status = pjsua_vid_codec_get_param(&cid, &cp); - if (status == PJ_SUCCESS) { - cp.enc_fmt.det.vid.avg_bps = M * 1000; - cp.enc_fmt.det.vid.max_bps = N * 1000; - status = pjsua_vid_codec_set_param(&cid, &cp); - } - if (status != PJ_SUCCESS) - PJ_PERROR(1,(THIS_FILE, status, "Set codec bitrate error")); - } else if (argc==6 && strcmp(argv[2], "size")==0) { - pjmedia_vid_codec_param cp; - pj_str_t cid; - int M, N; - cid = pj_str(argv[3]); - M = atoi(argv[4]); - N = atoi(argv[5]); - status = pjsua_vid_codec_get_param(&cid, &cp); - if (status == PJ_SUCCESS) { - cp.enc_fmt.det.vid.size.w = M; - cp.enc_fmt.det.vid.size.h = N; - status = pjsua_vid_codec_set_param(&cid, &cp); - } - if (status != PJ_SUCCESS) - PJ_PERROR(1,(THIS_FILE, status, "Set codec size error")); - } else - goto on_error; + pjsua_codec_info ci[PJMEDIA_CODEC_MGR_MAX_CODECS]; + unsigned count = PJ_ARRAY_SIZE(ci); + pj_status_t status; + + if (argc==3 && strcmp(argv[2], "list")==0) { + status = pjsua_vid_enum_codecs(ci, &count); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, "Error enumerating codecs")); + } else { + unsigned i; + PJ_LOG(3,(THIS_FILE, "Found %d video codecs:", count)); + PJ_LOG(3,(THIS_FILE, "codec id prio fps bw(kbps) size")); + PJ_LOG(3,(THIS_FILE, "------------------------------------------")); + for (i=0; ifps.num*1.0/vfd->fps.denum), + vfd->avg_bps/1000, vfd->max_bps/1000, + vfd->size.w, vfd->size.h)); + } + } + } else if (argc==5 && strcmp(argv[2], "prio")==0) { + pj_str_t cid; + int prio; + cid = pj_str(argv[3]); + prio = atoi(argv[4]); + status = pjsua_vid_codec_set_priority(&cid, (pj_uint8_t)prio); + if (status != PJ_SUCCESS) + PJ_PERROR(1,(THIS_FILE, status, "Set codec priority error")); + } else if (argc==6 && strcmp(argv[2], "fps")==0) { + pjmedia_vid_codec_param cp; + pj_str_t cid; + int M, N; + cid = pj_str(argv[3]); + M = atoi(argv[4]); + N = atoi(argv[5]); + status = pjsua_vid_codec_get_param(&cid, &cp); + if (status == PJ_SUCCESS) { + cp.enc_fmt.det.vid.fps.num = M; + cp.enc_fmt.det.vid.fps.denum = N; + status = pjsua_vid_codec_set_param(&cid, &cp); + } + if (status != PJ_SUCCESS) + PJ_PERROR(1,(THIS_FILE, status, "Set codec framerate error")); + } else if (argc==6 && strcmp(argv[2], "bw")==0) { + pjmedia_vid_codec_param cp; + pj_str_t cid; + int M, N; + cid = pj_str(argv[3]); + M = atoi(argv[4]); + N = atoi(argv[5]); + status = pjsua_vid_codec_get_param(&cid, &cp); + if (status == PJ_SUCCESS) { + cp.enc_fmt.det.vid.avg_bps = M * 1000; + cp.enc_fmt.det.vid.max_bps = N * 1000; + status = pjsua_vid_codec_set_param(&cid, &cp); + } + if (status != PJ_SUCCESS) + PJ_PERROR(1,(THIS_FILE, status, "Set codec bitrate error")); + } else if (argc==6 && strcmp(argv[2], "size")==0) { + pjmedia_vid_codec_param cp; + pj_str_t cid; + int M, N; + cid = pj_str(argv[3]); + M = atoi(argv[4]); + N = atoi(argv[5]); + status = pjsua_vid_codec_get_param(&cid, &cp); + if (status == PJ_SUCCESS) { + cp.enc_fmt.det.vid.size.w = M; + cp.enc_fmt.det.vid.size.h = N; + status = pjsua_vid_codec_set_param(&cid, &cp); + } + if (status != PJ_SUCCESS) + PJ_PERROR(1,(THIS_FILE, status, "Set codec size error")); + } else + goto on_error; } else if (strcmp(argv[1], "conf")==0) { - pj_status_t status; - - if (argc==3 && strcmp(argv[2], "list")==0) { - pjsua_conf_port_id id[100]; - unsigned count = PJ_ARRAY_SIZE(id); - - status = pjsua_vid_conf_enum_ports(id, &count); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "Failed enumerating video conf bridge ports")); - } else { - unsigned i; - printf(" Video conference has %d ports:\n", count); - printf(" id name format rx-from tx-to \n"); - printf(" ------------------------------------------------------------------\n"); - for (i=0; iw, size->h, - (float)(fps->num*1.0/fps->denum)); - printf("%3d %.*s%.*s %s%.*s %s%.*s %s\n", - id[i], - (int)info.name.slen, info.name.ptr, - 22-(int)info.name.slen, " ", - s, - 20-(int)pj_ansi_strlen(s), " ", - tr_list, - 12-(int)pj_ansi_strlen(tr_list), " ", - li_list); - } - } - } else if (argc==5 && strcmp(argv[2], "cc")==0) { - int P, Q; - P = atoi(argv[3]); - Q = atoi(argv[4]); - pjsua_vid_conf_connect(P, Q, NULL); - } else if (argc==5 && strcmp(argv[2], "cd")==0) { - int P, Q; - P = atoi(argv[3]); - Q = atoi(argv[4]); - pjsua_vid_conf_disconnect(P, Q); - } else { - goto on_error; - } + pj_status_t status; + + if (argc==3 && strcmp(argv[2], "list")==0) { + pjsua_conf_port_id id[100]; + unsigned count = PJ_ARRAY_SIZE(id); + + status = pjsua_vid_conf_enum_ports(id, &count); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "Failed enumerating video conf bridge ports")); + } else { + unsigned i; + printf(" Video conference has %d ports:\n", count); + printf(" id name format rx-from tx-to \n"); + printf(" ------------------------------------------------------------------\n"); + for (i=0; iw, size->h, + (float)(fps->num*1.0/fps->denum)); + printf("%3d %.*s%.*s %s%.*s %s%.*s %s\n", + id[i], + (int)info.name.slen, info.name.ptr, + 22-(int)info.name.slen, " ", + s, + 20-(int)pj_ansi_strlen(s), " ", + tr_list, + 12-(int)pj_ansi_strlen(tr_list), " ", + li_list); + } + } + } else if (argc==5 && strcmp(argv[2], "cc")==0) { + int P, Q; + P = atoi(argv[3]); + Q = atoi(argv[4]); + pjsua_vid_conf_connect(P, Q, NULL); + } else if (argc==5 && strcmp(argv[2], "cd")==0) { + int P, Q; + P = atoi(argv[3]); + Q = atoi(argv[4]); + pjsua_vid_conf_disconnect(P, Q); + } else { + goto on_error; + } } else - goto on_error; + goto on_error; return; @@ -703,26 +702,26 @@ static void ui_make_new_call() ui_input_url("Make call", buf, sizeof(buf), &result); if (result.nb_result != PJSUA_APP_NO_NB) { - if (result.nb_result == -1 || result.nb_result == 0) { - puts("You can't do that with make call!"); - return; - } else { - pjsua_buddy_info binfo; - pjsua_buddy_get_info(result.nb_result-1, &binfo); - tmp.ptr = buf; - pj_strncpy(&tmp, &binfo.uri, sizeof(buf)); - } + if (result.nb_result == -1 || result.nb_result == 0) { + puts("You can't do that with make call!"); + return; + } else { + pjsua_buddy_info binfo; + pjsua_buddy_get_info(result.nb_result-1, &binfo); + tmp.ptr = buf; + pj_strncpy(&tmp, &binfo.uri, sizeof(buf)); + } } else if (result.uri_result) { - tmp = pj_str(result.uri_result); + tmp = pj_str(result.uri_result); } else { - tmp.slen = 0; + tmp.slen = 0; } pjsua_msg_data_init(&msg_data_); TEST_MULTIPART(&msg_data_); pjsua_call_make_call(current_acc, &tmp, &call_opt, NULL, - &msg_data_, ¤t_call); + &msg_data_, ¤t_call); } static void ui_make_multi_call() @@ -737,33 +736,33 @@ static void ui_make_multi_call() printf("(You currently have %d calls)\n", pjsua_call_get_count()); if (!simple_input("Number of calls", menuin, sizeof(menuin))) - return; + return; count = my_atoi(menuin); if (count < 1) - return; + return; ui_input_url("Make call", buf, sizeof(buf), &result); if (result.nb_result != PJSUA_APP_NO_NB) { - pjsua_buddy_info binfo; - if (result.nb_result == -1 || result.nb_result == 0) { - puts("You can't do that with make call!"); - return; - } - pjsua_buddy_get_info(result.nb_result-1, &binfo); - tmp.ptr = buf; - pj_strncpy(&tmp, &binfo.uri, sizeof(buf)); + pjsua_buddy_info binfo; + if (result.nb_result == -1 || result.nb_result == 0) { + puts("You can't do that with make call!"); + return; + } + pjsua_buddy_get_info(result.nb_result-1, &binfo); + tmp.ptr = buf; + pj_strncpy(&tmp, &binfo.uri, sizeof(buf)); } else { - tmp = pj_str(result.uri_result); + tmp = pj_str(result.uri_result); } for (i=0; i= PJSIP_INV_STATE_CONNECTING) + call_info.role != PJSIP_ROLE_UAS || + call_info.state >= PJSIP_INV_STATE_CONNECTING) { - puts("No pending incoming call"); - fflush(stdout); - return; + puts("No pending incoming call"); + fflush(stdout); + return; } else { - int st_code; - char contact[120]; - pj_str_t hname = { "Contact", 7 }; - pj_str_t hvalue; - pjsip_generic_string_hdr hcontact; - - if (!simple_input("Answer with code (100-699)", buf, sizeof(buf))) - return; - - st_code = my_atoi(buf); - if (st_code < 100) - return; - - pjsua_msg_data_init(&msg_data_); - - if (st_code/100 == 3) { - if (!simple_input("Enter URL to be put in Contact", - contact, sizeof(contact))) - return; - hvalue = pj_str(contact); - pjsip_generic_string_hdr_init2(&hcontact, &hname, &hvalue); - - pj_list_push_back(&msg_data_.hdr_list, &hcontact); - } - - /* - * Must check again! - * Call may have been disconnected while we're waiting for - * keyboard input. - */ - if (current_call == -1) { - puts("Call has been disconnected"); - fflush(stdout); - return; - } - - pjsua_call_answer2(current_call, &call_opt, st_code, NULL, &msg_data_); + int st_code; + char contact[120]; + pj_str_t hname = { "Contact", 7 }; + pj_str_t hvalue; + pjsip_generic_string_hdr hcontact; + + if (!simple_input("Answer with code (100-699)", buf, sizeof(buf))) + return; + + st_code = my_atoi(buf); + if (st_code < 100) + return; + + pjsua_msg_data_init(&msg_data_); + + if (st_code/100 == 3) { + if (!simple_input("Enter URL to be put in Contact", + contact, sizeof(contact))) + return; + hvalue = pj_str(contact); + pjsip_generic_string_hdr_init2(&hcontact, &hname, &hvalue); + + pj_list_push_back(&msg_data_.hdr_list, &hcontact); + } + + /* + * Must check again! + * Call may have been disconnected while we're waiting for + * keyboard input. + */ + if (current_call == -1) { + puts("Call has been disconnected"); + fflush(stdout); + return; + } + + pjsua_call_answer2(current_call, &call_opt, st_code, NULL, &msg_data_); } } static void ui_hangup_call(char menuin[]) { if (current_call == -1) { - puts("No current call"); - fflush(stdout); - return; + puts("No current call"); + fflush(stdout); + return; } else if (menuin[1] == 'a') { - /* Hangup all calls */ - pjsua_call_hangup_all(); + /* Hangup all calls */ + pjsua_call_hangup_all(); } else { - /* Hangup current calls */ - pjsua_call_hangup(current_call, 0, NULL, NULL); + /* Hangup current calls */ + pjsua_call_hangup(current_call, 0, NULL, NULL); } } static void ui_cycle_dialog(char menuin[]) { if (menuin[0] == ']') { - find_next_call(); + find_next_call(); } else { - find_prev_call(); + find_prev_call(); } if (current_call != -1) { - pjsua_call_info call_info; + pjsua_call_info call_info; - pjsua_call_get_info(current_call, &call_info); - PJ_LOG(3,(THIS_FILE,"Current dialog: %.*s", - (int)call_info.remote_info.slen, - call_info.remote_info.ptr)); + pjsua_call_get_info(current_call, &call_info); + PJ_LOG(3,(THIS_FILE,"Current dialog: %.*s", + (int)call_info.remote_info.slen, + call_info.remote_info.ptr)); } else { - PJ_LOG(3,(THIS_FILE,"No current dialog")); + PJ_LOG(3,(THIS_FILE,"No current dialog")); } } @@ -948,14 +947,14 @@ static void ui_cycle_account() char buf[128]; if (!simple_input("Enter account ID to select", buf, sizeof(buf))) - return; + return; i = my_atoi(buf); if (pjsua_acc_is_valid(i)) { - pjsua_acc_set_default(i); - PJ_LOG(3,(THIS_FILE, "Current account changed to %d", i)); + pjsua_acc_set_default(i); + PJ_LOG(3,(THIS_FILE, "Current account changed to %d", i)); } else { - PJ_LOG(3,(THIS_FILE, "Invalid account id %d", i)); + PJ_LOG(3,(THIS_FILE, "Invalid account id %d", i)); } } @@ -967,11 +966,11 @@ static void ui_add_buddy() pj_status_t status; if (!simple_input("Enter buddy's URI:", buf, sizeof(buf))) - return; + return; if (pjsua_verify_url(buf) != PJ_SUCCESS) { - printf("Invalid URI '%s'\n", buf); - return; + printf("Invalid URI '%s'\n", buf); + return; } pj_bzero(&buddy_cfg, sizeof(pjsua_buddy_config)); @@ -981,8 +980,8 @@ static void ui_add_buddy() status = pjsua_buddy_add(&buddy_cfg, &buddy_id); if (status == PJ_SUCCESS) { - printf("New buddy '%s' added at index %d\n", - buf, buddy_id+1); + printf("New buddy '%s' added at index %d\n", + buf, buddy_id+1); } } @@ -993,15 +992,15 @@ static void ui_add_account(pjsua_transport_config *rtp_cfg) pj_status_t status; if (!simple_input("Your SIP URL:", id, sizeof(id))) - return; + return; if (!simple_input("URL of the registrar:", registrar, sizeof(registrar))) - return; + return; if (!simple_input("Auth Realm:", realm, sizeof(realm))) - return; + return; if (!simple_input("Auth Username:", uname, sizeof(uname))) - return; + return; if (!simple_input("Auth Password:", passwd, sizeof(passwd))) - return; + return; pjsua_acc_config_default(&acc_cfg); acc_cfg.id = pj_str(id); @@ -1018,7 +1017,7 @@ static void ui_add_account(pjsua_transport_config *rtp_cfg) status = pjsua_acc_add(&acc_cfg, PJ_TRUE, NULL); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error adding new account", status); + pjsua_perror(THIS_FILE, "Error adding new account", status); } } @@ -1028,15 +1027,15 @@ static void ui_delete_buddy() int i; if (!simple_input("Enter buddy ID to delete", buf, sizeof(buf))) - return; + return; i = my_atoi(buf) - 1; if (!pjsua_buddy_is_valid(i)) { - printf("Invalid buddy id %d\n", i); + printf("Invalid buddy id %d\n", i); } else { - pjsua_buddy_del(i); - printf("Buddy %d deleted\n", i); + pjsua_buddy_del(i); + printf("Buddy %d deleted\n", i); } } @@ -1046,24 +1045,24 @@ static void ui_delete_account() int i; if (!simple_input("Enter account ID to delete", buf, sizeof(buf))) - return; + return; i = my_atoi(buf); if (!pjsua_acc_is_valid(i)) { - printf("Invalid account id %d\n", i); + printf("Invalid account id %d\n", i); } else { - pjsua_acc_del(i); - printf("Account %d deleted\n", i); + pjsua_acc_del(i); + printf("Account %d deleted\n", i); } } static void ui_call_hold() { if (current_call != -1) { - pjsua_call_set_hold(current_call, NULL); + pjsua_call_set_hold(current_call, NULL); } else { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } } @@ -1076,9 +1075,9 @@ static void ui_call_reinvite() static void ui_send_update() { if (current_call != -1) { - pjsua_call_update2(current_call, &call_opt, NULL); + pjsua_call_update2(current_call, &call_opt, NULL); } else { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } } @@ -1098,8 +1097,8 @@ static void ui_manage_codec_prio() printf("List of audio codecs:\n"); pjsua_enum_codecs(c, &count); for (i=0; i PJMEDIA_CODEC_PRIO_HIGHEST) - new_prio = PJMEDIA_CODEC_PRIO_HIGHEST; + new_prio = PJMEDIA_CODEC_PRIO_HIGHEST; status = pjsua_codec_set_priority(pj_cstr(&id, codec), - (pj_uint8_t)new_prio); + (pj_uint8_t)new_prio); #if PJSUA_HAS_VIDEO if (status != PJ_SUCCESS) { - status = pjsua_vid_codec_set_priority(pj_cstr(&id, codec), - (pj_uint8_t)new_prio); + status = pjsua_vid_codec_set_priority(pj_cstr(&id, codec), + (pj_uint8_t)new_prio); } #endif if (status != PJ_SUCCESS) - pjsua_perror(THIS_FILE, "Error setting codec priority", status); + pjsua_perror(THIS_FILE, "Error setting codec priority", status); } static void ui_call_transfer(pj_bool_t no_refersub) { if (current_call == -1) { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } else { - int call = current_call; - char buf[128]; - pjsip_generic_string_hdr refer_sub; - pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 }; - pj_str_t STR_FALSE = { "false", 5 }; - pjsua_call_info ci; - input_result result; - pjsua_msg_data msg_data_; - - pjsua_call_get_info(current_call, &ci); - printf("Transferring current call [%d] %.*s\n", current_call, - (int)ci.remote_info.slen, ci.remote_info.ptr); - - ui_input_url("Transfer to URL", buf, sizeof(buf), &result); - - /* Check if call is still there. */ - - if (call != current_call) { - puts("Call has been disconnected"); - return; - } - - pjsua_msg_data_init(&msg_data_); - if (no_refersub) { - /* Add Refer-Sub: false in outgoing REFER request */ - pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB, - &STR_FALSE); - pj_list_push_back(&msg_data_.hdr_list, &refer_sub); - } - if (result.nb_result != PJSUA_APP_NO_NB) { - if (result.nb_result == -1 || result.nb_result == 0) { - puts("You can't do that with transfer call!"); - } else { - pjsua_buddy_info binfo; - pjsua_buddy_get_info(result.nb_result-1, &binfo); - pjsua_call_xfer( current_call, &binfo.uri, &msg_data_); - } - - } else if (result.uri_result) { - pj_str_t tmp; - tmp = pj_str(result.uri_result); - pjsua_call_xfer( current_call, &tmp, &msg_data_); - } + int call = current_call; + char buf[128]; + pjsip_generic_string_hdr refer_sub; + pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 }; + pj_str_t STR_FALSE = { "false", 5 }; + pjsua_call_info ci; + input_result result; + pjsua_msg_data msg_data_; + + pjsua_call_get_info(current_call, &ci); + printf("Transferring current call [%d] %.*s\n", current_call, + (int)ci.remote_info.slen, ci.remote_info.ptr); + + ui_input_url("Transfer to URL", buf, sizeof(buf), &result); + + /* Check if call is still there. */ + + if (call != current_call) { + puts("Call has been disconnected"); + return; + } + + pjsua_msg_data_init(&msg_data_); + if (no_refersub) { + /* Add Refer-Sub: false in outgoing REFER request */ + pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB, + &STR_FALSE); + pj_list_push_back(&msg_data_.hdr_list, &refer_sub); + } + if (result.nb_result != PJSUA_APP_NO_NB) { + if (result.nb_result == -1 || result.nb_result == 0) { + puts("You can't do that with transfer call!"); + } else { + pjsua_buddy_info binfo; + pjsua_buddy_get_info(result.nb_result-1, &binfo); + pjsua_call_xfer( current_call, &binfo.uri, &msg_data_); + } + + } else if (result.uri_result) { + pj_str_t tmp; + tmp = pj_str(result.uri_result); + pjsua_call_xfer( current_call, &tmp, &msg_data_); + } } } static void ui_call_transfer_replaces(pj_bool_t no_refersub) { if (current_call == -1) { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } else { - int call = current_call; - int dst_call; - pjsip_generic_string_hdr refer_sub; - pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 }; - pj_str_t STR_FALSE = { "false", 5 }; - pjsua_call_id ids[PJSUA_MAX_CALLS]; - pjsua_call_info ci; - pjsua_msg_data msg_data_; - char buf[128]; - unsigned i, count; - - count = PJ_ARRAY_SIZE(ids); - pjsua_enum_calls(ids, &count); - - if (count <= 1) { - puts("There are no other calls"); - return; - } - - pjsua_call_get_info(current_call, &ci); - printf("Transfer call [%d] %.*s to one of the following:\n", - current_call, - (int)ci.remote_info.slen, ci.remote_info.ptr); - - for (i=0; i= PJSUA_MAX_CALLS) { - puts("Invalid destination call number"); - return; - } - if (!pjsua_call_is_active(dst_call)) { - puts("Invalid destination call number"); - return; - } - - pjsua_msg_data_init(&msg_data_); - if (no_refersub) { - /* Add Refer-Sub: false in outgoing REFER request */ - pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB, - &STR_FALSE); - pj_list_push_back(&msg_data_.hdr_list, &refer_sub); - } - - pjsua_call_xfer_replaces(call, dst_call, - PJSUA_XFER_NO_REQUIRE_REPLACES, - &msg_data_); + int call = current_call; + int dst_call; + pjsip_generic_string_hdr refer_sub; + pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 }; + pj_str_t STR_FALSE = { "false", 5 }; + pjsua_call_id ids[PJSUA_MAX_CALLS]; + pjsua_call_info ci; + pjsua_msg_data msg_data_; + char buf[128]; + unsigned i, count; + + count = PJ_ARRAY_SIZE(ids); + pjsua_enum_calls(ids, &count); + + if (count <= 1) { + puts("There are no other calls"); + return; + } + + pjsua_call_get_info(current_call, &ci); + printf("Transfer call [%d] %.*s to one of the following:\n", + current_call, + (int)ci.remote_info.slen, ci.remote_info.ptr); + + for (i=0; i= PJSUA_MAX_CALLS) { + puts("Invalid destination call number"); + return; + } + if (!pjsua_call_is_active(dst_call)) { + puts("Invalid destination call number"); + return; + } + + pjsua_msg_data_init(&msg_data_); + if (no_refersub) { + /* Add Refer-Sub: false in outgoing REFER request */ + pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB, + &STR_FALSE); + pj_list_push_back(&msg_data_.hdr_list, &refer_sub); + } + + pjsua_call_xfer_replaces(call, dst_call, + PJSUA_XFER_NO_REQUIRE_REPLACES, + &msg_data_); } } static void ui_send_dtmf_2833() { if (current_call == -1) { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } else if (!pjsua_call_has_media(current_call)) { - PJ_LOG(3,(THIS_FILE, "Media is not established yet!")); + PJ_LOG(3,(THIS_FILE, "Media is not established yet!")); } else { - pj_str_t digits; - int call = current_call; - pj_status_t status; - char buf[128]; - -#if defined(PJMEDIA_HAS_DTMF_FLASH) && PJMEDIA_HAS_DTMF_FLASH!= 0 - if (!simple_input("DTMF strings to send (0-9*R#A-B)", buf, - sizeof(buf))) + pj_str_t digits; + int call = current_call; + pj_status_t status; + char buf[128]; + +#if defined(PJMEDIA_HAS_DTMF_FLASH) && PJMEDIA_HAS_DTMF_FLASH!= 0 + if (!simple_input("DTMF strings to send (0-9*R#A-B)", buf, + sizeof(buf))) #else - if (!simple_input("DTMF strings to send (0-9*#A-B)", buf, - sizeof(buf))) + if (!simple_input("DTMF strings to send (0-9*#A-B)", buf, + sizeof(buf))) #endif - { - return; - } - - if (call != current_call) { - puts("Call has been disconnected"); - return; - } - - digits = pj_str(buf); - status = pjsua_call_dial_dtmf(current_call, &digits); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send DTMF", status); - } else { - puts("DTMF digits enqueued for transmission"); - } + { + return; + } + + if (call != current_call) { + puts("Call has been disconnected"); + return; + } + + digits = pj_str(buf); + status = pjsua_call_dial_dtmf(current_call, &digits); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to send DTMF", status); + } else { + puts("DTMF digits enqueued for transmission"); + } } } static void ui_send_dtmf_info() { if (current_call == -1) { - PJ_LOG(3,(THIS_FILE, "No current call")); + PJ_LOG(3,(THIS_FILE, "No current call")); } else { - int call = current_call; - pj_status_t status; - char buf[128]; - pjsua_call_send_dtmf_param param; - - if (!simple_input("DTMF strings to send (0-9*#A-B)", buf, - sizeof(buf))) - { - return; - } - - if (call != current_call) { - puts("Call has been disconnected"); - return; - } - pjsua_call_send_dtmf_param_default(¶m); - param.digits = pj_str(buf); - param.method = PJSUA_DTMF_METHOD_SIP_INFO; - status = pjsua_call_send_dtmf(current_call, ¶m); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error sending DTMF", status); - } + int call = current_call; + pj_status_t status; + char buf[128]; + pjsua_call_send_dtmf_param param; + + if (!simple_input("DTMF strings to send (0-9*#A-B)", buf, + sizeof(buf))) + { + return; + } + + if (call != current_call) { + puts("Call has been disconnected"); + return; + } + pjsua_call_send_dtmf_param_default(¶m); + param.digits = pj_str(buf); + param.method = PJSUA_DTMF_METHOD_SIP_INFO; + status = pjsua_call_send_dtmf(current_call, ¶m); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error sending DTMF", status); + } } } @@ -1368,91 +1367,91 @@ static void ui_send_arbitrary_request() pj_str_t tmp; if (pjsua_acc_get_count() == 0) { - puts("Sorry, need at least one account configured"); - return; + puts("Sorry, need at least one account configured"); + return; } puts("Send arbitrary request to remote host"); /* Input METHOD */ if (!simple_input("Request method:",text,sizeof(text))) - return; + return; /* Input destination URI */ uri = NULL; ui_input_url("Destination URI", buf, sizeof(buf), &result); if (result.nb_result != PJSUA_APP_NO_NB) { - if (result.nb_result == -1) { - puts("Sorry you can't do that!"); - return; - } else if (result.nb_result == 0) { - uri = NULL; - if (current_call == PJSUA_INVALID_ID) { - puts("No current call"); - return; - } - } else { - pjsua_buddy_info binfo; - pjsua_buddy_get_info(result.nb_result-1, &binfo); - tmp.ptr = buf; - pj_strncpy_with_null(&tmp, &binfo.uri, sizeof(buf)); - uri = buf; - } + if (result.nb_result == -1) { + puts("Sorry you can't do that!"); + return; + } else if (result.nb_result == 0) { + uri = NULL; + if (current_call == PJSUA_INVALID_ID) { + puts("No current call"); + return; + } + } else { + pjsua_buddy_info binfo; + pjsua_buddy_get_info(result.nb_result-1, &binfo); + tmp.ptr = buf; + pj_strncpy_with_null(&tmp, &binfo.uri, sizeof(buf)); + uri = buf; + } } else if (result.uri_result) { - uri = result.uri_result; + uri = result.uri_result; } else { - return; + return; } if (uri) { - tmp = pj_str(uri); - send_request(text, &tmp); + tmp = pj_str(uri); + send_request(text, &tmp); } else { - /* If you send call control request using this method - * (such requests includes BYE, CANCEL, etc.), it will - * not go well with the call state, so don't do it - * unless it's for testing. - */ - pj_str_t method = pj_str(text); - pjsua_call_send_request(current_call, &method, NULL); + /* If you send call control request using this method + * (such requests includes BYE, CANCEL, etc.), it will + * not go well with the call state, so don't do it + * unless it's for testing. + */ + pj_str_t method = pj_str(text); + pjsua_call_send_request(current_call, &method, NULL); } } static void ui_echo(char menuin[]) { if (pj_ansi_strnicmp(menuin, "echo", 4)==0) { - pj_str_t tmp; + pj_str_t tmp; - tmp.ptr = menuin+5; - tmp.slen = pj_ansi_strlen(menuin)-6; + tmp.ptr = menuin+5; + tmp.slen = pj_ansi_strlen(menuin)-6; - if (tmp.slen < 1) { - puts("Usage: echo [0|1]"); - return; - } - cmd_echo = *tmp.ptr != '0' || tmp.slen!=1; + if (tmp.slen < 1) { + puts("Usage: echo [0|1]"); + return; + } + cmd_echo = *tmp.ptr != '0' || tmp.slen!=1; } } static void ui_sleep(char menuin[]) { if (pj_ansi_strnicmp(menuin, "sleep", 5)==0) { - pj_str_t tmp; - int delay; + pj_str_t tmp; + int delay; - tmp.ptr = menuin+6; - tmp.slen = pj_ansi_strlen(menuin)-7; + tmp.ptr = menuin+6; + tmp.slen = pj_ansi_strlen(menuin)-7; - if (tmp.slen < 1) { - puts("Usage: sleep MSEC"); - return; - } + if (tmp.slen < 1) { + puts("Usage: sleep MSEC"); + return; + } - delay = (int)pj_strtoul(&tmp); - if (delay < 0) delay = 0; - pj_thread_sleep(delay); + delay = (int)pj_strtoul(&tmp); + if (delay < 0) delay = 0; + pj_thread_sleep(delay); } } @@ -1463,21 +1462,21 @@ static void ui_subscribe(char menuin[]) ui_input_url("(un)Subscribe presence of", buf, sizeof(buf), &result); if (result.nb_result != PJSUA_APP_NO_NB) { - if (result.nb_result == -1) { - int i, count; - count = pjsua_get_buddy_count(); - for (i=0; i= OPT_MAX) { - puts("Invalid selection"); - return; + puts("Invalid selection"); + return; } pj_bzero(&elem, sizeof(elem)); @@ -1561,30 +1560,30 @@ static void ui_change_online_status() switch (choice) { case AVAILABLE: - break; + break; case BUSY: - elem.activity = PJRPID_ACTIVITY_BUSY; - elem.note = pj_str("Busy"); - break; + elem.activity = PJRPID_ACTIVITY_BUSY; + elem.note = pj_str("Busy"); + break; case OTP: - elem.activity = PJRPID_ACTIVITY_BUSY; - elem.note = pj_str("On the phone"); - break; + elem.activity = PJRPID_ACTIVITY_BUSY; + elem.note = pj_str("On the phone"); + break; case IDLE: - elem.activity = PJRPID_ACTIVITY_UNKNOWN; - elem.note = pj_str("Idle"); - break; + elem.activity = PJRPID_ACTIVITY_UNKNOWN; + elem.note = pj_str("Idle"); + break; case AWAY: - elem.activity = PJRPID_ACTIVITY_AWAY; - elem.note = pj_str("Away"); - break; + elem.activity = PJRPID_ACTIVITY_AWAY; + elem.note = pj_str("Away"); + break; case BRB: - elem.activity = PJRPID_ACTIVITY_UNKNOWN; - elem.note = pj_str("Be right back"); - break; + elem.activity = PJRPID_ACTIVITY_UNKNOWN; + elem.note = pj_str("Be right back"); + break; case OFFLINE: - online_status = PJ_FALSE; - break; + online_status = PJ_FALSE; + break; } pjsua_acc_set_online_status2(current_acc, online_status, &elem); @@ -1604,26 +1603,26 @@ static void ui_conf_list() pjsua_enum_conf_ports(id, &count); for (i=0; i>> "); - fflush(stdout); + printf(">>> "); + fflush(stdout); - if (fgets(menuin, sizeof(menuin), stdin) == NULL) { - /* - * Be friendly to users who redirect commands into - * program, when file ends, resume with kbd. - * If exit is desired end script with q for quit - */ - /* Reopen stdin/stdout/stderr to /dev/console */ + if (fgets(menuin, sizeof(menuin), stdin) == NULL) { + /* + * Be friendly to users who redirect commands into + * program, when file ends, resume with kbd. + * If exit is desired end script with q for quit + */ + /* Reopen stdin/stdout/stderr to /dev/console */ #if ((defined(PJ_WIN32) && PJ_WIN32!=0) || \ (defined(PJ_WIN64) && PJ_WIN64!=0)) && \ (!defined(PJ_WIN32_WINCE) || PJ_WIN32_WINCE==0) - if (freopen ("CONIN$", "r", stdin) == NULL) { + if (freopen ("CONIN$", "r", stdin) == NULL) { #else - if (1) { + if (1) { #endif - puts("Cannot switch back to console from file redirection"); - menuin[0] = 'q'; - menuin[1] = '\0'; - } else { - puts("Switched back to console from file redirection"); - continue; - } - } - - if (cmd_echo) { - printf("%s", menuin); - } - - /* Update call setting */ - pjsua_call_setting_default(&call_opt); - call_opt.aud_cnt = app_config.aud_cnt; - call_opt.vid_cnt = app_config.vid.vid_cnt; - - switch (menuin[0]) { - - case 'm': - /* Make call! : */ - ui_make_new_call(); - break; - - case 'M': - /* Make multiple calls! : */ - ui_make_multi_call(); - break; - - case 'n': - ui_detect_nat_type(); - break; - - case 'i': - /* Send instant messaeg */ - ui_send_instant_message(); - break; - - case 'a': - ui_answer_call(); - break; - - case 'h': - ui_hangup_call(menuin); - break; - - case ']': - case '[': - /* - * Cycle next/prev dialog. - */ - ui_cycle_dialog(menuin); - break; - - case '>': - case '<': - ui_cycle_account(); - break; - - case '+': - if (menuin[1] == 'b') { - ui_add_buddy(); - } else if (menuin[1] == 'a') { - ui_add_account(&app_config.rtp_cfg); - } else { - printf("Invalid input %s\n", menuin); - } - break; - - case '-': - if (menuin[1] == 'b') { - ui_delete_buddy(); - } else if (menuin[1] == 'a') { - ui_delete_account(); - } else { - printf("Invalid input %s\n", menuin); - } - break; - - case 'H': - /* - * Hold call. - */ - ui_call_hold(); - break; - - case 'v': + puts("Cannot switch back to console from file redirection"); + menuin[0] = 'q'; + menuin[1] = '\0'; + } else { + puts("Switched back to console from file redirection"); + continue; + } + } + + if (cmd_echo) { + printf("%s", menuin); + } + + /* Update call setting */ + pjsua_call_setting_default(&call_opt); + call_opt.aud_cnt = app_config.aud_cnt; + call_opt.vid_cnt = app_config.vid.vid_cnt; + + switch (menuin[0]) { + + case 'm': + /* Make call! : */ + ui_make_new_call(); + break; + + case 'M': + /* Make multiple calls! : */ + ui_make_multi_call(); + break; + + case 'n': + ui_detect_nat_type(); + break; + + case 'i': + /* Send instant messaeg */ + ui_send_instant_message(); + break; + + case 'a': + ui_answer_call(); + break; + + case 'h': + ui_hangup_call(menuin); + break; + + case ']': + case '[': + /* + * Cycle next/prev dialog. + */ + ui_cycle_dialog(menuin); + break; + + case '>': + case '<': + ui_cycle_account(); + break; + + case '+': + if (menuin[1] == 'b') { + ui_add_buddy(); + } else if (menuin[1] == 'a') { + ui_add_account(&app_config.rtp_cfg); + } else { + printf("Invalid input %s\n", menuin); + } + break; + + case '-': + if (menuin[1] == 'b') { + ui_delete_buddy(); + } else if (menuin[1] == 'a') { + ui_delete_account(); + } else { + printf("Invalid input %s\n", menuin); + } + break; + + case 'H': + /* + * Hold call. + */ + ui_call_hold(); + break; + + case 'v': #if PJSUA_HAS_VIDEO - if (menuin[1]=='i' && menuin[2]=='d' && menuin[3]==' ') { - vid_handle_menu(menuin); - } else + if (menuin[1]=='i' && menuin[2]=='d' && menuin[3]==' ') { + vid_handle_menu(menuin); + } else #endif - if (current_call != -1) { - /* - * re-INVITE - */ - ui_call_reinvite(); - } else { - PJ_LOG(3,(THIS_FILE, "No current call")); - } - break; - - case 'U': - /* - * Send UPDATE - */ - ui_send_update(); - break; - - case 'C': - if (menuin[1] == 'p') { - ui_manage_codec_prio(); - } - break; - - case 'x': - /* - * Transfer call. - */ - ui_call_transfer(app_config.no_refersub); - break; - - case 'X': - /* - * Transfer call with replaces. - */ - ui_call_transfer_replaces(app_config.no_refersub); - break; - - case '#': - /* - * Send DTMF strings. - */ - ui_send_dtmf_2833(); - break; - - case '*': - /* Send DTMF with INFO */ - ui_send_dtmf_info(); - break; - - case 'S': - /* - * Send arbitrary request - */ - ui_send_arbitrary_request(); - break; - - case 'e': - ui_echo(menuin); - break; - - case 's': - if (pj_ansi_strnicmp(menuin, "sleep", 5)==0) { - ui_sleep(menuin); - break; - } - /* Continue below */ - - case 'u': - /* - * Subscribe/unsubscribe presence. - */ - ui_subscribe(menuin); - break; - - case 'r': - ui_register(menuin); - break; - - case 't': - ui_toggle_state(); - break; - - case 'T': - ui_change_online_status(); - break; - - case 'c': - switch (menuin[1]) { - case 'l': - ui_conf_list(); - break; - case 'c': - case 'd': - ui_conf_connect(menuin); - break; - } - break; - - case 'V': - /* Adjust audio volume */ - ui_adjust_volume(); - break; - - case 'd': - if (menuin[1] == 'c') { - ui_dump_configuration(); - } else if (menuin[1] == 'q') { - ui_dump_call_quality(); - } else { - ui_app_dump(menuin[1]=='d'); - } - break; - - case 'f': - if (simple_input("Enter output filename", buf, sizeof(buf))) { - ui_write_settings(buf); - } - break; - - case 'L': /* Restart */ - case 'q': - legacy_on_stopped(menuin[0]=='L'); - goto on_exit; - - case 'R': - ui_call_redirect(menuin); - break; - - case 'I': /* Handle IP change. */ - ui_handle_ip_change(); - break; - - default: - if (menuin[0] != '\n' && menuin[0] != '\r') { - printf("Invalid input %s", menuin); - } - keystroke_help(); - break; - } + if (current_call != -1) { + /* + * re-INVITE + */ + ui_call_reinvite(); + } else { + PJ_LOG(3,(THIS_FILE, "No current call")); + } + break; + + case 'U': + /* + * Send UPDATE + */ + ui_send_update(); + break; + + case 'C': + if (menuin[1] == 'p') { + ui_manage_codec_prio(); + } + break; + + case 'x': + /* + * Transfer call. + */ + ui_call_transfer(app_config.no_refersub); + break; + + case 'X': + /* + * Transfer call with replaces. + */ + ui_call_transfer_replaces(app_config.no_refersub); + break; + + case '#': + /* + * Send DTMF strings. + */ + ui_send_dtmf_2833(); + break; + + case '*': + /* Send DTMF with INFO */ + ui_send_dtmf_info(); + break; + + case 'S': + /* + * Send arbitrary request + */ + ui_send_arbitrary_request(); + break; + + case 'e': + ui_echo(menuin); + break; + + case 's': + if (pj_ansi_strnicmp(menuin, "sleep", 5)==0) { + ui_sleep(menuin); + break; + } + /* Continue below */ + + case 'u': + /* + * Subscribe/unsubscribe presence. + */ + ui_subscribe(menuin); + break; + + case 'r': + ui_register(menuin); + break; + + case 't': + ui_toggle_state(); + break; + + case 'T': + ui_change_online_status(); + break; + + case 'c': + switch (menuin[1]) { + case 'l': + ui_conf_list(); + break; + case 'c': + case 'd': + ui_conf_connect(menuin); + break; + } + break; + + case 'V': + /* Adjust audio volume */ + ui_adjust_volume(); + break; + + case 'd': + if (menuin[1] == 'c') { + ui_dump_configuration(); + } else if (menuin[1] == 'q') { + ui_dump_call_quality(); + } else { + ui_app_dump(menuin[1]=='d'); + } + break; + + case 'f': + if (simple_input("Enter output filename", buf, sizeof(buf))) { + ui_write_settings(buf); + } + break; + + case 'L': /* Restart */ + case 'q': + legacy_on_stopped(menuin[0]=='L'); + goto on_exit; + + case 'R': + ui_call_redirect(menuin); + break; + + case 'I': /* Handle IP change. */ + ui_handle_ip_change(); + break; + + default: + if (menuin[0] != '\n' && menuin[0] != '\r') { + printf("Invalid input %s", menuin); + } + keystroke_help(); + break; + } } on_exit: diff --git a/pjsip-apps/src/pjsua/symbian/inc/PjsuaContainerView.h b/pjsip-apps/src/pjsua/symbian/inc/PjsuaContainerView.h index 22b3ed8b3f..a77ceaadf7 100644 --- a/pjsip-apps/src/pjsua/symbian/inc/PjsuaContainerView.h +++ b/pjsip-apps/src/pjsua/symbian/inc/PjsuaContainerView.h @@ -27,68 +27,68 @@ class CPjsuaContainer; /** * Avkon view class for pjsuaContainerView. It is register with the view server * by the AppUi. It owns the container control. - * @class CpjsuaContainerView pjsuaContainerView.h - */ - + * @class CpjsuaContainerView pjsuaContainerView.h + */ + class CpjsuaContainerView : public CAknView - { - - - // [[[ begin [Public Section] + { + + + // [[[ begin [Public Section] public: - // constructors and destructor - CpjsuaContainerView(); - static CpjsuaContainerView* NewL(); - static CpjsuaContainerView* NewLC(); - void ConstructL(); - virtual ~CpjsuaContainerView(); - - // from base class CAknView - TUid Id() const; - void HandleCommandL( TInt aCommand ); - - // [[[ begin generated region: do not modify [Generated Methods] - CPjsuaContainer* CreateContainerL(); - // ]]] end generated region [Generated Methods] - - // ]]] end [Public Section] - - void PutMessage( const char *msg ); - - // [[[ begin [Protected Section] + // constructors and destructor + CpjsuaContainerView(); + static CpjsuaContainerView* NewL(); + static CpjsuaContainerView* NewLC(); + void ConstructL(); + virtual ~CpjsuaContainerView(); + + // from base class CAknView + TUid Id() const; + void HandleCommandL( TInt aCommand ); + + // [[[ begin generated region: do not modify [Generated Methods] + CPjsuaContainer* CreateContainerL(); + // ]]] end generated region [Generated Methods] + + // ]]] end [Public Section] + + void PutMessage( const char *msg ); + + // [[[ begin [Protected Section] protected: - // from base class CAknView - void DoActivateL( - const TVwsViewId& aPrevViewId, - TUid aCustomMessageId, - const TDesC8& aCustomMessage ); - void DoDeactivate(); - void HandleStatusPaneSizeChange(); - - // [[[ begin generated region: do not modify [Overridden Methods] - // ]]] end generated region [Overridden Methods] - - - // [[[ begin [User Handlers] - // ]]] end [User Handlers] - - // ]]] end [Protected Section] - - - // [[[ begin [Private Section] + // from base class CAknView + void DoActivateL( + const TVwsViewId& aPrevViewId, + TUid aCustomMessageId, + const TDesC8& aCustomMessage ); + void DoDeactivate(); + void HandleStatusPaneSizeChange(); + + // [[[ begin generated region: do not modify [Overridden Methods] + // ]]] end generated region [Overridden Methods] + + + // [[[ begin [User Handlers] + // ]]] end [User Handlers] + + // ]]] end [Protected Section] + + + // [[[ begin [Private Section] private: - void SetupStatusPaneL(); - void CleanupStatusPane(); - - // [[[ begin generated region: do not modify [Generated Instance Variables] - CPjsuaContainer* iPjsuaContainer; - // ]]] end generated region [Generated Instance Variables] - - // [[[ begin generated region: do not modify [Generated Methods] - // ]]] end generated region [Generated Methods] - - // ]]] end [Private Section] - - }; + void SetupStatusPaneL(); + void CleanupStatusPane(); + + // [[[ begin generated region: do not modify [Generated Instance Variables] + CPjsuaContainer* iPjsuaContainer; + // ]]] end generated region [Generated Instance Variables] + + // [[[ begin generated region: do not modify [Generated Methods] + // ]]] end generated region [Generated Methods] + + // ]]] end [Private Section] + + }; #endif // PJSUACONTAINERVIEW_H diff --git a/pjsip-apps/src/pjsua/symbian/inc/pjsuaAppUi.h b/pjsip-apps/src/pjsua/symbian/inc/pjsuaAppUi.h index 8bfd24421f..b8570e619b 100644 --- a/pjsip-apps/src/pjsua/symbian/inc/pjsuaAppUi.h +++ b/pjsip-apps/src/pjsua/symbian/inc/pjsuaAppUi.h @@ -19,52 +19,52 @@ class CpjsuaContainerView; // ]]] end generated region [Generated Forward Declarations] /** - * @class CpjsuaAppUi pjsuaAppUi.h + * @class CpjsuaAppUi pjsuaAppUi.h * @brief The AppUi class handles application-wide aspects of the user interface, including * view management and the default menu, control pane, and status pane. */ class CpjsuaAppUi : public CAknViewAppUi - { + { public: - // constructor and destructor - CpjsuaAppUi(); - virtual ~CpjsuaAppUi(); - void ConstructL(); + // constructor and destructor + CpjsuaAppUi(); + virtual ~CpjsuaAppUi(); + void ConstructL(); public: - // from CCoeAppUi - TKeyResponse HandleKeyEventL( - const TKeyEvent& aKeyEvent, - TEventCode aType ); + // from CCoeAppUi + TKeyResponse HandleKeyEventL( + const TKeyEvent& aKeyEvent, + TEventCode aType ); - // from CEikAppUi - void HandleCommandL( TInt aCommand ); - void HandleResourceChangeL( TInt aType ); + // from CEikAppUi + void HandleCommandL( TInt aCommand ); + void HandleResourceChangeL( TInt aType ); - // from CAknAppUi - void HandleViewDeactivation( - const TVwsViewId& aViewIdToBeDeactivated, - const TVwsViewId& aNewlyActivatedViewId ); + // from CAknAppUi + void HandleViewDeactivation( + const TVwsViewId& aViewIdToBeDeactivated, + const TVwsViewId& aNewlyActivatedViewId ); private: - void InitializeContainersL(); - // [[[ begin generated region: do not modify [Generated Methods] + void InitializeContainersL(); + // [[[ begin generated region: do not modify [Generated Methods] public: - // ]]] end generated region [Generated Methods] - - void PutMsg(const char *msg); - - // [[[ begin generated region: do not modify [Generated Instance Variables] + // ]]] end generated region [Generated Methods] + + void PutMsg(const char *msg); + + // [[[ begin generated region: do not modify [Generated Instance Variables] private: - CpjsuaContainerView* iPjsuaContainerView; - // ]]] end generated region [Generated Instance Variables] - - - // [[[ begin [User Handlers] + CpjsuaContainerView* iPjsuaContainerView; + // ]]] end generated region [Generated Instance Variables] + + + // [[[ begin [User Handlers] protected: - // ]]] end [User Handlers] - void PrepareToExit(); + // ]]] end [User Handlers] + void PrepareToExit(); - }; + }; -#endif // PJSUAAPPUI_H +#endif // PJSUAAPPUI_H diff --git a/pjsip-apps/src/pjsua/symbian/inc/pjsuaApplication.h b/pjsip-apps/src/pjsua/symbian/inc/pjsuaApplication.h index eef6e3fe6a..b5615e3fe5 100644 --- a/pjsip-apps/src/pjsua/symbian/inc/pjsuaApplication.h +++ b/pjsip-apps/src/pjsua/symbian/inc/pjsuaApplication.h @@ -19,17 +19,17 @@ const TUid KUidpjsuaApplication = { 0xE44C2D02 }; /** * - * @class CpjsuaApplication pjsuaApplication.h - * @brief A CAknApplication-derived class is required by the S60 application + * @class CpjsuaApplication pjsuaApplication.h + * @brief A CAknApplication-derived class is required by the S60 application * framework. It is subclassed to create the application's document * object. */ class CpjsuaApplication : public CAknApplication - { + { private: - TUid AppDllUid() const; - CApaDocument* CreateDocumentL(); - - }; - -#endif // PJSUAAPPLICATION_H + TUid AppDllUid() const; + CApaDocument* CreateDocumentL(); + + }; + +#endif // PJSUAAPPLICATION_H diff --git a/pjsip-apps/src/pjsua/symbian/inc/pjsuaContainer.h b/pjsip-apps/src/pjsua/symbian/inc/pjsuaContainer.h index 2ee14758a6..0c069eb5c5 100644 --- a/pjsip-apps/src/pjsua/symbian/inc/pjsuaContainer.h +++ b/pjsip-apps/src/pjsua/symbian/inc/pjsuaContainer.h @@ -10,7 +10,7 @@ #define PJSUACONTAINER_H // [[[ begin generated region: do not modify [Generated Includes] -#include +#include // ]]] end generated region [Generated Includes] @@ -18,7 +18,7 @@ // ]]] end [Event Handler Includes] // [[[ begin generated region: do not modify [Generated Forward Declarations] -class MEikCommandObserver; +class MEikCommandObserver; class CEikImage; class CEikLabel; // ]]] end generated region [Generated Forward Declarations] @@ -26,87 +26,87 @@ class CEikLabel; /** * Container class for pjsuaContainer * - * @class CPjsuaContainer pjsuaContainer.h + * @class CPjsuaContainer pjsuaContainer.h */ class CPjsuaContainer : public CCoeControl - { + { public: - // constructors and destructor - CPjsuaContainer(); - static CPjsuaContainer* NewL( - const TRect& aRect, - const CCoeControl* aParent, - MEikCommandObserver* aCommandObserver ); - static CPjsuaContainer* NewLC( - const TRect& aRect, - const CCoeControl* aParent, - MEikCommandObserver* aCommandObserver ); - void ConstructL( - const TRect& aRect, - const CCoeControl* aParent, - MEikCommandObserver* aCommandObserver ); - virtual ~CPjsuaContainer(); + // constructors and destructor + CPjsuaContainer(); + static CPjsuaContainer* NewL( + const TRect& aRect, + const CCoeControl* aParent, + MEikCommandObserver* aCommandObserver ); + static CPjsuaContainer* NewLC( + const TRect& aRect, + const CCoeControl* aParent, + MEikCommandObserver* aCommandObserver ); + void ConstructL( + const TRect& aRect, + const CCoeControl* aParent, + MEikCommandObserver* aCommandObserver ); + virtual ~CPjsuaContainer(); public: - // from base class CCoeControl - TInt CountComponentControls() const; - CCoeControl* ComponentControl( TInt aIndex ) const; - TKeyResponse OfferKeyEventL( - const TKeyEvent& aKeyEvent, - TEventCode aType ); - void HandleResourceChange( TInt aType ); - + // from base class CCoeControl + TInt CountComponentControls() const; + CCoeControl* ComponentControl( TInt aIndex ) const; + TKeyResponse OfferKeyEventL( + const TKeyEvent& aKeyEvent, + TEventCode aType ); + void HandleResourceChange( TInt aType ); + protected: - // from base class CCoeControl - void SizeChanged(); + // from base class CCoeControl + void SizeChanged(); private: - // from base class CCoeControl - void Draw( const TRect& aRect ) const; + // from base class CCoeControl + void Draw( const TRect& aRect ) const; private: - void InitializeControlsL(); - void LayoutControls(); - CCoeControl* iFocusControl; - MEikCommandObserver* iCommandObserver; - // [[[ begin generated region: do not modify [Generated Methods] + void InitializeControlsL(); + void LayoutControls(); + CCoeControl* iFocusControl; + MEikCommandObserver* iCommandObserver; + // [[[ begin generated region: do not modify [Generated Methods] public: - // ]]] end generated region [Generated Methods] - - void PutMessageL( const char* msg ); - // [[[ begin generated region: do not modify [Generated Type Declarations] + // ]]] end generated region [Generated Methods] + + void PutMessageL( const char* msg ); + // [[[ begin generated region: do not modify [Generated Type Declarations] public: - // ]]] end generated region [Generated Type Declarations] - - // [[[ begin generated region: do not modify [Generated Instance Variables] + // ]]] end generated region [Generated Type Declarations] + + // [[[ begin generated region: do not modify [Generated Instance Variables] private: - CEikImage* iImage1; - CEikLabel* iLabel1; - // ]]] end generated region [Generated Instance Variables] - - - // [[[ begin [Overridden Methods] + CEikImage* iImage1; + CEikLabel* iLabel1; + // ]]] end generated region [Generated Instance Variables] + + + // [[[ begin [Overridden Methods] protected: - // ]]] end [Overridden Methods] - - - // [[[ begin [User Handlers] + // ]]] end [Overridden Methods] + + + // [[[ begin [User Handlers] protected: - // ]]] end [User Handlers] - + // ]]] end [User Handlers] + public: - enum TControls - { - // [[[ begin generated region: do not modify [Generated Contents] - EImage1, - ELabel1, - - // ]]] end generated region [Generated Contents] - - // add any user-defined entries here... - - ELastControl - }; - }; - + enum TControls + { + // [[[ begin generated region: do not modify [Generated Contents] + EImage1, + ELabel1, + + // ]]] end generated region [Generated Contents] + + // add any user-defined entries here... + + ELastControl + }; + }; + #endif // PJSUACONTAINER_H diff --git a/pjsip-apps/src/pjsua/symbian/inc/pjsuaDocument.h b/pjsip-apps/src/pjsua/symbian/inc/pjsuaDocument.h index be5deff378..f0fd7f036b 100644 --- a/pjsip-apps/src/pjsua/symbian/inc/pjsuaDocument.h +++ b/pjsip-apps/src/pjsua/symbian/inc/pjsuaDocument.h @@ -10,27 +10,27 @@ #define PJSUADOCUMENT_H #include - + class CEikAppUi; /** -* @class CpjsuaDocument pjsuaDocument.h -* @brief A CAknDocument-derived class is required by the S60 application +* @class CpjsuaDocument pjsuaDocument.h +* @brief A CAknDocument-derived class is required by the S60 application * framework. It is responsible for creating the AppUi object. */ class CpjsuaDocument : public CAknDocument - { + { public: - // constructor - static CpjsuaDocument* NewL( CEikApplication& aApp ); + // constructor + static CpjsuaDocument* NewL( CEikApplication& aApp ); private: - // constructors - CpjsuaDocument( CEikApplication& aApp ); - void ConstructL(); - + // constructors + CpjsuaDocument( CEikApplication& aApp ); + void ConstructL(); + public: - // from base class CEikDocument - CEikAppUi* CreateAppUiL(); - }; + // from base class CEikDocument + CEikAppUi* CreateAppUiL(); + }; #endif // PJSUADOCUMENT_H diff --git a/pjsip-apps/src/pjsua/symbian/src/PjsuaContainerView.cpp b/pjsip-apps/src/pjsua/symbian/src/PjsuaContainerView.cpp index 8595260fcb..47d7fe1908 100644 --- a/pjsip-apps/src/pjsua/symbian/src/PjsuaContainerView.cpp +++ b/pjsip-apps/src/pjsua/symbian/src/PjsuaContainerView.cpp @@ -36,25 +36,25 @@ * code that could leave. */ CpjsuaContainerView::CpjsuaContainerView() - { - // [[[ begin generated region: do not modify [Generated Contents] - iPjsuaContainer = NULL; - // ]]] end generated region [Generated Contents] - - } + { + // [[[ begin generated region: do not modify [Generated Contents] + iPjsuaContainer = NULL; + // ]]] end generated region [Generated Contents] + + } /** * The view's destructor removes the container from the control * stack and destroys it. */ CpjsuaContainerView::~CpjsuaContainerView() - { - // [[[ begin generated region: do not modify [Generated Contents] - delete iPjsuaContainer; - iPjsuaContainer = NULL; - // ]]] end generated region [Generated Contents] - - } + { + // [[[ begin generated region: do not modify [Generated Contents] + delete iPjsuaContainer; + iPjsuaContainer = NULL; + // ]]] end generated region [Generated Contents] + + } /** * Symbian two-phase constructor. @@ -63,11 +63,11 @@ CpjsuaContainerView::~CpjsuaContainerView() * @return new instance of CpjsuaContainerView */ CpjsuaContainerView* CpjsuaContainerView::NewL() - { - CpjsuaContainerView* self = CpjsuaContainerView::NewLC(); - CleanupStack::Pop( self ); - return self; - } + { + CpjsuaContainerView* self = CpjsuaContainerView::NewLC(); + CleanupStack::Pop( self ); + return self; + } /** * Symbian two-phase constructor. @@ -76,12 +76,12 @@ CpjsuaContainerView* CpjsuaContainerView::NewL() * @return new instance of CpjsuaContainerView */ CpjsuaContainerView* CpjsuaContainerView::NewLC() - { - CpjsuaContainerView* self = new ( ELeave ) CpjsuaContainerView(); - CleanupStack::PushL( self ); - self->ConstructL(); - return self; - } + { + CpjsuaContainerView* self = new ( ELeave ) CpjsuaContainerView(); + CleanupStack::PushL( self ); + self->ConstructL(); + return self; + } /** @@ -89,173 +89,173 @@ CpjsuaContainerView* CpjsuaContainerView::NewLC() * Initialize contents from resource. */ void CpjsuaContainerView::ConstructL() - { - // [[[ begin generated region: do not modify [Generated Code] - BaseConstructL( R_PJSUA_CONTAINER_PJSUA_CONTAINER_VIEW ); - - // ]]] end generated region [Generated Code] - - // add your own initialization code here - } + { + // [[[ begin generated region: do not modify [Generated Code] + BaseConstructL( R_PJSUA_CONTAINER_PJSUA_CONTAINER_VIEW ); + + // ]]] end generated region [Generated Code] + + // add your own initialization code here + } /** * @return The UID for this view */ TUid CpjsuaContainerView::Id() const - { - return TUid::Uid( EPjsuaContainerViewId ); - } + { + return TUid::Uid( EPjsuaContainerViewId ); + } /** * Handle a command for this view (override) * @param aCommand command id to be handled */ void CpjsuaContainerView::HandleCommandL( TInt aCommand ) - { - // [[[ begin generated region: do not modify [Generated Code] - TBool commandHandled = EFalse; - switch ( aCommand ) - { // code to dispatch to the AknView's menu and CBA commands is generated here - default: - break; - } - - - if ( !commandHandled ) - { - - if ( aCommand == EAknSoftkeyBack ) - { - AppUi()->HandleCommandL( EEikCmdExit ); - } - - } - // ]]] end generated region [Generated Code] - - } + { + // [[[ begin generated region: do not modify [Generated Code] + TBool commandHandled = EFalse; + switch ( aCommand ) + { // code to dispatch to the AknView's menu and CBA commands is generated here + default: + break; + } + + + if ( !commandHandled ) + { + + if ( aCommand == EAknSoftkeyBack ) + { + AppUi()->HandleCommandL( EEikCmdExit ); + } + + } + // ]]] end generated region [Generated Code] + + } /** - * Handles user actions during activation of the view, - * such as initializing the content. + * Handles user actions during activation of the view, + * such as initializing the content. */ void CpjsuaContainerView::DoActivateL( - const TVwsViewId& /*aPrevViewId*/, - TUid /*aCustomMessageId*/, - const TDesC8& /*aCustomMessage*/ ) - { - // [[[ begin generated region: do not modify [Generated Contents] - SetupStatusPaneL(); - - - - - if ( iPjsuaContainer == NULL ) - { - iPjsuaContainer = CreateContainerL(); - iPjsuaContainer->SetMopParent( this ); - AppUi()->AddToStackL( *this, iPjsuaContainer ); - } - // ]]] end generated region [Generated Contents] - - } + const TVwsViewId& /*aPrevViewId*/, + TUid /*aCustomMessageId*/, + const TDesC8& /*aCustomMessage*/ ) + { + // [[[ begin generated region: do not modify [Generated Contents] + SetupStatusPaneL(); + + + + + if ( iPjsuaContainer == NULL ) + { + iPjsuaContainer = CreateContainerL(); + iPjsuaContainer->SetMopParent( this ); + AppUi()->AddToStackL( *this, iPjsuaContainer ); + } + // ]]] end generated region [Generated Contents] + + } /** */ void CpjsuaContainerView::DoDeactivate() - { - // [[[ begin generated region: do not modify [Generated Contents] - CleanupStatusPane(); - - if ( iPjsuaContainer != NULL ) - { - AppUi()->RemoveFromViewStack( *this, iPjsuaContainer ); - delete iPjsuaContainer; - iPjsuaContainer = NULL; - } - // ]]] end generated region [Generated Contents] - - } + { + // [[[ begin generated region: do not modify [Generated Contents] + CleanupStatusPane(); + + if ( iPjsuaContainer != NULL ) + { + AppUi()->RemoveFromViewStack( *this, iPjsuaContainer ); + delete iPjsuaContainer; + iPjsuaContainer = NULL; + } + // ]]] end generated region [Generated Contents] + + } /** * Handle status pane size change for this view (override) */ void CpjsuaContainerView::HandleStatusPaneSizeChange() - { - CAknView::HandleStatusPaneSizeChange(); - - // this may fail, but we're not able to propagate exceptions here - TVwsViewId view; - AppUi()->GetActiveViewId( view ); - if ( view.iViewUid == Id() ) - { - TInt result; - TRAP( result, SetupStatusPaneL() ); - } + { + CAknView::HandleStatusPaneSizeChange(); + + // this may fail, but we're not able to propagate exceptions here + TVwsViewId view; + AppUi()->GetActiveViewId( view ); + if ( view.iViewUid == Id() ) + { + TInt result; + TRAP( result, SetupStatusPaneL() ); + } - // Hide menu - Cba()->MakeVisible(EFalse); - - //PutMessage("HandleStatusPaneSizeChange()"); - - // [[[ begin generated region: do not modify [Generated Code] - // ]]] end generated region [Generated Code] - - } + // Hide menu + Cba()->MakeVisible(EFalse); + + //PutMessage("HandleStatusPaneSizeChange()"); + + // [[[ begin generated region: do not modify [Generated Code] + // ]]] end generated region [Generated Code] + + } // [[[ begin generated function: do not modify void CpjsuaContainerView::SetupStatusPaneL() - { - // reset the context pane - TUid contextPaneUid = TUid::Uid( EEikStatusPaneUidContext ); - CEikStatusPaneBase::TPaneCapabilities subPaneContext = - StatusPane()->PaneCapabilities( contextPaneUid ); - if ( subPaneContext.IsPresent() && subPaneContext.IsAppOwned() ) - { - CAknContextPane* context = static_cast< CAknContextPane* > ( - StatusPane()->ControlL( contextPaneUid ) ); - context->SetPictureToDefaultL(); - } - - // setup the title pane - TUid titlePaneUid = TUid::Uid( EEikStatusPaneUidTitle ); - CEikStatusPaneBase::TPaneCapabilities subPaneTitle = - StatusPane()->PaneCapabilities( titlePaneUid ); - if ( subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned() ) - { - CAknTitlePane* title = static_cast< CAknTitlePane* >( - StatusPane()->ControlL( titlePaneUid ) ); - TResourceReader reader; - iEikonEnv->CreateResourceReaderLC( reader, R_PJSUA_CONTAINER_TITLE_RESOURCE ); - title->SetFromResourceL( reader ); - CleanupStack::PopAndDestroy(); // reader internal state - } - - } + { + // reset the context pane + TUid contextPaneUid = TUid::Uid( EEikStatusPaneUidContext ); + CEikStatusPaneBase::TPaneCapabilities subPaneContext = + StatusPane()->PaneCapabilities( contextPaneUid ); + if ( subPaneContext.IsPresent() && subPaneContext.IsAppOwned() ) + { + CAknContextPane* context = static_cast< CAknContextPane* > ( + StatusPane()->ControlL( contextPaneUid ) ); + context->SetPictureToDefaultL(); + } + + // setup the title pane + TUid titlePaneUid = TUid::Uid( EEikStatusPaneUidTitle ); + CEikStatusPaneBase::TPaneCapabilities subPaneTitle = + StatusPane()->PaneCapabilities( titlePaneUid ); + if ( subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned() ) + { + CAknTitlePane* title = static_cast< CAknTitlePane* >( + StatusPane()->ControlL( titlePaneUid ) ); + TResourceReader reader; + iEikonEnv->CreateResourceReaderLC( reader, R_PJSUA_CONTAINER_TITLE_RESOURCE ); + title->SetFromResourceL( reader ); + CleanupStack::PopAndDestroy(); // reader internal state + } + + } // ]]] end generated function // [[[ begin generated function: do not modify void CpjsuaContainerView::CleanupStatusPane() - { - } + { + } // ]]] end generated function /** - * Creates the top-level container for the view. You may modify this method's - * contents and the CPjsuaContainer::NewL() signature as needed to initialize the - * container, but the signature for this method is fixed. - * @return new initialized instance of CPjsuaContainer + * Creates the top-level container for the view. You may modify this method's + * contents and the CPjsuaContainer::NewL() signature as needed to initialize the + * container, but the signature for this method is fixed. + * @return new initialized instance of CPjsuaContainer */ CPjsuaContainer* CpjsuaContainerView::CreateContainerL() - { - return CPjsuaContainer::NewL( ClientRect(), NULL, this ); - } + { + return CPjsuaContainer::NewL( ClientRect(), NULL, this ); + } void CpjsuaContainerView::PutMessage( const char *msg ) { - if (!iPjsuaContainer) - return; + if (!iPjsuaContainer) + return; - TRAPD(result, iPjsuaContainer->PutMessageL(msg)); + TRAPD(result, iPjsuaContainer->PutMessageL(msg)); } diff --git a/pjsip-apps/src/pjsua/symbian/src/pjsuaAppUi.cpp b/pjsip-apps/src/pjsua/symbian/src/pjsuaAppUi.cpp index 74b8c42f10..287c17f318 100644 --- a/pjsip-apps/src/pjsua/symbian/src/pjsuaAppUi.cpp +++ b/pjsip-apps/src/pjsua/symbian/src/pjsuaAppUi.cpp @@ -51,31 +51,31 @@ class MyTimer : public CActive public: static MyTimer* NewL(int ms, timer_func f) { - MyTimer *self = new MyTimer(f); - CleanupStack::PushL(self); - self->ConstructL(ms); - CleanupStack::Pop(self); - return self; + MyTimer *self = new MyTimer(f); + CleanupStack::PushL(self); + self->ConstructL(ms); + CleanupStack::Pop(self); + return self; } MyTimer(timer_func f) : CActive(EPriorityStandard), func(f) {} ~MyTimer() { - Cancel(); - rtimer.Close(); + Cancel(); + rtimer.Close(); } virtual void RunL() { (*func)(); delete this; } virtual void DoCancel() { rtimer.Cancel(); } -private: +private: RTimer rtimer; timer_func func; void ConstructL(int ms) { - rtimer.CreateLocal(); - CActiveScheduler::Add(this); - rtimer.After(iStatus, ms * 1000); - SetActive(); + rtimer.CreateLocal(); + CActiveScheduler::Add(this); + rtimer.After(iStatus, ms * 1000); + SetActive(); } }; @@ -83,30 +83,30 @@ class MyTimer : public CActive * Construct the CpjsuaAppUi instance */ CpjsuaAppUi::CpjsuaAppUi() - { - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - } + { + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + + } /** * The appui's destructor removes the container from the control * stack and destroys it. */ CpjsuaAppUi::~CpjsuaAppUi() - { - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - } + { + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + + } // [[[ begin generated function: do not modify void CpjsuaAppUi::InitializeContainersL() - { - iPjsuaContainerView = CpjsuaContainerView::NewL(); - AddViewL( iPjsuaContainerView ); - SetDefaultViewL( *iPjsuaContainerView ); - } + { + iPjsuaContainerView = CpjsuaContainerView::NewL(); + AddViewL( iPjsuaContainerView ); + SetDefaultViewL( *iPjsuaContainerView ); + } // ]]] end generated function /** @@ -114,38 +114,38 @@ void CpjsuaAppUi::InitializeContainersL() * @param aCommand command id to be handled */ void CpjsuaAppUi::HandleCommandL( TInt aCommand ) - { - // [[[ begin generated region: do not modify [Generated Code] - TBool commandHandled = EFalse; - switch ( aCommand ) - { // code to dispatch to the AppUi's menu and CBA commands is generated here - default: - break; - } - - - if ( !commandHandled ) - { - if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit ) - { - Exit(); - } - } - // ]]] end generated region [Generated Code] - - } + { + // [[[ begin generated region: do not modify [Generated Code] + TBool commandHandled = EFalse; + switch ( aCommand ) + { // code to dispatch to the AppUi's menu and CBA commands is generated here + default: + break; + } + + + if ( !commandHandled ) + { + if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit ) + { + Exit(); + } + } + // ]]] end generated region [Generated Code] + + } /** * Override of the HandleResourceChangeL virtual function */ void CpjsuaAppUi::HandleResourceChangeL( TInt aType ) - { - CAknViewAppUi::HandleResourceChangeL( aType ); - // [[[ begin generated region: do not modify [Generated Code] - // ]]] end generated region [Generated Code] - - } - + { + CAknViewAppUi::HandleResourceChangeL( aType ); + // [[[ begin generated region: do not modify [Generated Code] + // ]]] end generated region [Generated Code] + + } + /** * Override of the HandleKeyEventL virtual function * @return EKeyWasConsumed if event was handled, EKeyWasNotConsumed if not @@ -153,25 +153,25 @@ void CpjsuaAppUi::HandleResourceChangeL( TInt aType ) * @param aType */ TKeyResponse CpjsuaAppUi::HandleKeyEventL( - const TKeyEvent& aKeyEvent, - TEventCode aType ) - { - // The inherited HandleKeyEventL is private and cannot be called - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - // Left or right softkey pressed - if (aType==EEventKeyDown && - (aKeyEvent.iScanCode == EStdKeyDevice0 || - aKeyEvent.iScanCode == EStdKeyDevice1)) - { - Cba()->MakeVisible(ETrue); - } else { - Cba()->MakeVisible(EFalse); - } - - return EKeyWasNotConsumed; - } + const TKeyEvent& aKeyEvent, + TEventCode aType ) + { + // The inherited HandleKeyEventL is private and cannot be called + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + + // Left or right softkey pressed + if (aType==EEventKeyDown && + (aKeyEvent.iScanCode == EStdKeyDevice0 || + aKeyEvent.iScanCode == EStdKeyDevice1)) + { + Cba()->MakeVisible(ETrue); + } else { + Cba()->MakeVisible(EFalse); + } + + return EKeyWasNotConsumed; + } /** * Override of the HandleViewDeactivation virtual function @@ -180,48 +180,48 @@ TKeyResponse CpjsuaAppUi::HandleKeyEventL( * @param aNewlyActivatedViewId */ void CpjsuaAppUi::HandleViewDeactivation( - const TVwsViewId& aViewIdToBeDeactivated, - const TVwsViewId& aNewlyActivatedViewId ) - { - CAknViewAppUi::HandleViewDeactivation( - aViewIdToBeDeactivated, - aNewlyActivatedViewId ); - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - } + const TVwsViewId& aViewIdToBeDeactivated, + const TVwsViewId& aNewlyActivatedViewId ) + { + CAknViewAppUi::HandleViewDeactivation( + aViewIdToBeDeactivated, + aNewlyActivatedViewId ); + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + + } /** * @brief Completes the second phase of Symbian object construction. * Put initialization code that could leave here. */ void CpjsuaAppUi::ConstructL() - { - // [[[ begin generated region: do not modify [Generated Contents] - - BaseConstructL( EAknEnableSkin | - EAknEnableMSK ); - InitializeContainersL(); - // ]]] end generated region [Generated Contents] - - // Save pointer to this AppUi - appui = this; - - // Full screen - StatusPane()->MakeVisible(EFalse); - Cba()->MakeVisible(EFalse); - - if (InitSymbSocket() != PJ_SUCCESS) { - PutMsg("Failed to initialize Symbian network param."); - } else { - start_argc = pjsua_app_def_argc; - start_argv = (char**)pjsua_app_def_argv; - - // Schedule Lib Init - MyTimer::NewL(100, &PjsuaInitL); - } - - } + { + // [[[ begin generated region: do not modify [Generated Contents] + + BaseConstructL( EAknEnableSkin | + EAknEnableMSK ); + InitializeContainersL(); + // ]]] end generated region [Generated Contents] + + // Save pointer to this AppUi + appui = this; + + // Full screen + StatusPane()->MakeVisible(EFalse); + Cba()->MakeVisible(EFalse); + + if (InitSymbSocket() != PJ_SUCCESS) { + PutMsg("Failed to initialize Symbian network param."); + } else { + start_argc = pjsua_app_def_argc; + start_argv = (char**)pjsua_app_def_argv; + + // Schedule Lib Init + MyTimer::NewL(100, &PjsuaInitL); + } + + } /* Called by Symbian GUI framework when app is about to exit */ void CpjsuaAppUi::PrepareToExit() @@ -249,11 +249,11 @@ void PjsuaOnStarted(pj_status_t status, const char* title) char err_msg[128]; if (status != PJ_SUCCESS || title == NULL) { - char err_str[PJ_ERR_MSG_SIZE]; - pj_strerror(status, err_str, sizeof(err_str)); - pj_ansi_snprintf(err_msg, sizeof(err_msg), "%s: %s", - (title?title:"App start error"), err_str); - title = err_msg; + char err_str[PJ_ERR_MSG_SIZE]; + pj_strerror(status, err_str, sizeof(err_str)); + pj_ansi_snprintf(err_msg, sizeof(err_msg), "%s: %s", + (title?title:"App start error"), err_str); + title = err_msg; } appui->PutMsg(title); @@ -263,14 +263,14 @@ void PjsuaOnStarted(pj_status_t status, const char* title) void PjsuaOnStopped(pj_bool_t restart, int argc, char** argv) { if (restart) { - start_argc = argc; - start_argv = argv; + start_argc = argc; + start_argv = argv; - // Schedule Lib Init - MyTimer::NewL(100, &PjsuaInitL); + // Schedule Lib Init + MyTimer::NewL(100, &PjsuaInitL); } else { - /* Destroy & quit GUI, e.g: clean up window, resources */ - appui->Exit(); + /* Destroy & quit GUI, e.g: clean up window, resources */ + appui->Exit(); } } @@ -287,7 +287,7 @@ void PjsuaOnConfig(pjsua_app_config *cfg) /* Create ioqueue for telnet CLI */ if (app_ioqueue == NULL) { - pj_ioqueue_create(cfg->pool, 0, &app_ioqueue); + pj_ioqueue_create(cfg->pool, 0, &app_ioqueue); } cfg->cli_cfg.telnet_cfg.ioqueue = app_ioqueue; } @@ -301,18 +301,18 @@ pj_status_t InitSymbSocket() // Initialize RSocketServ if ((err=aSocketServer.Connect(32)) != KErrNone) { - return PJ_STATUS_FROM_OS(err); + return PJ_STATUS_FROM_OS(err); } // Open up a connection if ((err=aConn.Open(aSocketServer)) != KErrNone) { - aSocketServer.Close(); - return PJ_STATUS_FROM_OS(err); + aSocketServer.Close(); + return PJ_STATUS_FROM_OS(err); } if ((err=aConn.Start()) != KErrNone) { - aConn.Close(); - aSocketServer.Close(); - return PJ_STATUS_FROM_OS(err); + aConn.Close(); + aSocketServer.Close(); + return PJ_STATUS_FROM_OS(err); } pj_bzero(&sym_params, sizeof(sym_params)); @@ -348,23 +348,23 @@ void PjsuaInitL() appui->PutMsg("Initializing.."); status = pjsua_app_init(&app_cfg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; appui->PutMsg("Starting.."); status = pjsua_app_run(PJ_FALSE); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; on_return: if (status != PJ_SUCCESS) - appui->PutMsg("Initialization failed"); + appui->PutMsg("Initialization failed"); } void PjsuaDestroyL() { if (app_ioqueue) { - pj_ioqueue_destroy(app_ioqueue); - app_ioqueue = NULL; + pj_ioqueue_destroy(app_ioqueue); + app_ioqueue = NULL; } pjsua_app_destroy(); } diff --git a/pjsip-apps/src/pjsua/symbian/src/pjsuaApplication.cpp b/pjsip-apps/src/pjsua/symbian/src/pjsuaApplication.cpp index 9196b9f9af..a0050eeb00 100644 --- a/pjsip-apps/src/pjsua/symbian/src/pjsuaApplication.cpp +++ b/pjsip-apps/src/pjsua/symbian/src/pjsuaApplication.cpp @@ -22,57 +22,57 @@ * @return UID for this application (KUidpjsuaApplication) */ TUid CpjsuaApplication::AppDllUid() const - { - return KUidpjsuaApplication; - } + { + return KUidpjsuaApplication; + } /** * @brief Creates the application's document (override from CApaApplication::CreateDocumentL()) * @return Pointer to the created document object (CpjsuaDocument) */ CApaDocument* CpjsuaApplication::CreateDocumentL() - { - return CpjsuaDocument::NewL( *this ); - } + { + return CpjsuaDocument::NewL( *this ); + } #ifdef EKA2 /** - * @brief Called by the application framework to construct the application object + * @brief Called by the application framework to construct the application object * @return The application (CpjsuaApplication) - */ + */ LOCAL_C CApaApplication* NewApplication() - { - return new CpjsuaApplication; - } + { + return new CpjsuaApplication; + } /** * @brief This standard export is the entry point for all Series 60 applications * @return error code - */ + */ GLDEF_C TInt E32Main() - { - return EikStart::RunApplication( NewApplication ); - } - -#else // Series 60 2.x main DLL program code + { + return EikStart::RunApplication( NewApplication ); + } + +#else // Series 60 2.x main DLL program code /** * @brief This standard export constructs the application object. * @return The application (CpjsuaApplication) */ EXPORT_C CApaApplication* NewApplication() - { - return new CpjsuaApplication; - } + { + return new CpjsuaApplication; + } /** * @brief This standard export is the entry point for all Series 60 applications * @return error code */ GLDEF_C TInt E32Dll(TDllReason /*reason*/) - { - return KErrNone; - } + { + return KErrNone; + } #endif // EKA2 diff --git a/pjsip-apps/src/pjsua/symbian/src/pjsuaContainer.cpp b/pjsip-apps/src/pjsua/symbian/src/pjsuaContainer.cpp index 5dec51f28d..1040d04f31 100644 --- a/pjsip-apps/src/pjsua/symbian/src/pjsuaContainer.cpp +++ b/pjsip-apps/src/pjsua/symbian/src/pjsuaContainer.cpp @@ -36,27 +36,27 @@ _LIT( KpjsuaFile, "\\resource\\apps\\pjsua.mbm" ); * contain any code that could leave. */ CPjsuaContainer::CPjsuaContainer() - { - // [[[ begin generated region: do not modify [Generated Contents] - iImage1 = NULL; - iLabel1 = NULL; - // ]]] end generated region [Generated Contents] - - } + { + // [[[ begin generated region: do not modify [Generated Contents] + iImage1 = NULL; + iLabel1 = NULL; + // ]]] end generated region [Generated Contents] + + } /** * Destroy child controls. */ CPjsuaContainer::~CPjsuaContainer() - { - // [[[ begin generated region: do not modify [Generated Contents] - delete iImage1; - iImage1 = NULL; - delete iLabel1; - iLabel1 = NULL; - // ]]] end generated region [Generated Contents] - - } - + { + // [[[ begin generated region: do not modify [Generated Contents] + delete iImage1; + iImage1 = NULL; + delete iLabel1; + iLabel1 = NULL; + // ]]] end generated region [Generated Contents] + + } + /** * Construct the control (first phase). * Creates an instance and initializes it. @@ -67,17 +67,17 @@ CPjsuaContainer::~CPjsuaContainer() * @return initialized instance of CPjsuaContainer */ CPjsuaContainer* CPjsuaContainer::NewL( - const TRect& aRect, - const CCoeControl* aParent, - MEikCommandObserver* aCommandObserver ) - { - CPjsuaContainer* self = CPjsuaContainer::NewLC( - aRect, - aParent, - aCommandObserver ); - CleanupStack::Pop( self ); - return self; - } + const TRect& aRect, + const CCoeControl* aParent, + MEikCommandObserver* aCommandObserver ) + { + CPjsuaContainer* self = CPjsuaContainer::NewLC( + aRect, + aParent, + aCommandObserver ); + CleanupStack::Pop( self ); + return self; + } /** * Construct the control (first phase). @@ -89,16 +89,16 @@ CPjsuaContainer* CPjsuaContainer::NewL( * @return new instance of CPjsuaContainer */ CPjsuaContainer* CPjsuaContainer::NewLC( - const TRect& aRect, - const CCoeControl* aParent, - MEikCommandObserver* aCommandObserver ) - { - CPjsuaContainer* self = new ( ELeave ) CPjsuaContainer(); - CleanupStack::PushL( self ); - self->ConstructL( aRect, aParent, aCommandObserver ); - return self; - } - + const TRect& aRect, + const CCoeControl* aParent, + MEikCommandObserver* aCommandObserver ) + { + CPjsuaContainer* self = new ( ELeave ) CPjsuaContainer(); + CleanupStack::PushL( self ); + self->ConstructL( aRect, aParent, aCommandObserver ); + return self; + } + /** * Construct the control (second phase). * Creates a window to contain the controls and activates it. @@ -107,199 +107,199 @@ CPjsuaContainer* CPjsuaContainer::NewLC( * @param aParent owning parent, or NULL */ void CPjsuaContainer::ConstructL( - const TRect& aRect, - const CCoeControl* aParent, - MEikCommandObserver* aCommandObserver ) - { - if ( aParent == NULL ) - { - CreateWindowL(); - } - else - { - SetContainerWindowL( *aParent ); - } - iFocusControl = NULL; - iCommandObserver = aCommandObserver; - InitializeControlsL(); - SetRect( aRect ); + const TRect& aRect, + const CCoeControl* aParent, + MEikCommandObserver* aCommandObserver ) + { + if ( aParent == NULL ) + { + CreateWindowL(); + } + else + { + SetContainerWindowL( *aParent ); + } + iFocusControl = NULL; + iCommandObserver = aCommandObserver; + InitializeControlsL(); + SetRect( aRect ); - // Full screen - SetExtentToWholeScreen(); - - // Set label color - //iLabel1->OverrideColorL( EColorLabelText, KRgbWhite ); - //iLabel1->OverrideColorL(EColorControlBackground, KRgbBlack ) - iLabel1->SetEmphasis( CEikLabel::EFullEmphasis); - iLabel1->OverrideColorL( EColorLabelHighlightFullEmphasis, KRgbBlack ); - iLabel1->OverrideColorL( EColorLabelTextEmphasis, KRgbWhite ); + // Full screen + SetExtentToWholeScreen(); + + // Set label color + //iLabel1->OverrideColorL( EColorLabelText, KRgbWhite ); + //iLabel1->OverrideColorL(EColorControlBackground, KRgbBlack ) + iLabel1->SetEmphasis( CEikLabel::EFullEmphasis); + iLabel1->OverrideColorL( EColorLabelHighlightFullEmphasis, KRgbBlack ); + iLabel1->OverrideColorL( EColorLabelTextEmphasis, KRgbWhite ); - // Set label font - CFont* fontUsed; - _LIT(f,"Arial"); - TFontSpec* fontSpec = new TFontSpec(f, 105); - TFontStyle* fontStyle = new TFontStyle(); - fontStyle->SetPosture(EPostureUpright); - fontStyle->SetStrokeWeight(EStrokeWeightNormal); - fontSpec->iFontStyle = *fontStyle; - fontUsed = iCoeEnv->CreateScreenFontL(*fontSpec); - iLabel1->SetFont(fontUsed); - iLabel1->SetAlignment( EHCenterVCenter ); - - ActivateL(); - // [[[ begin generated region: do not modify [Post-ActivateL initializations] - // ]]] end generated region [Post-ActivateL initializations] - - } - + // Set label font + CFont* fontUsed; + _LIT(f,"Arial"); + TFontSpec* fontSpec = new TFontSpec(f, 105); + TFontStyle* fontStyle = new TFontStyle(); + fontStyle->SetPosture(EPostureUpright); + fontStyle->SetStrokeWeight(EStrokeWeightNormal); + fontSpec->iFontStyle = *fontStyle; + fontUsed = iCoeEnv->CreateScreenFontL(*fontSpec); + iLabel1->SetFont(fontUsed); + iLabel1->SetAlignment( EHCenterVCenter ); + + ActivateL(); + // [[[ begin generated region: do not modify [Post-ActivateL initializations] + // ]]] end generated region [Post-ActivateL initializations] + + } + /** * Return the number of controls in the container (override) * @return count */ TInt CPjsuaContainer::CountComponentControls() const - { - return ( int ) ELastControl; - } - + { + return ( int ) ELastControl; + } + /** * Get the control with the given index (override) * @param aIndex Control index [0...n) (limited by #CountComponentControls) * @return Pointer to control */ CCoeControl* CPjsuaContainer::ComponentControl( TInt aIndex ) const - { - // [[[ begin generated region: do not modify [Generated Contents] - switch ( aIndex ) - { - case EImage1: - return iImage1; - case ELabel1: - return iLabel1; - } - // ]]] end generated region [Generated Contents] - - // handle any user controls here... - - return NULL; - } - + { + // [[[ begin generated region: do not modify [Generated Contents] + switch ( aIndex ) + { + case EImage1: + return iImage1; + case ELabel1: + return iLabel1; + } + // ]]] end generated region [Generated Contents] + + // handle any user controls here... + + return NULL; + } + /** - * Handle resizing of the container. This implementation will lay out + * Handle resizing of the container. This implementation will lay out * full-sized controls like list boxes for any screen size, and will layout * labels, editors, etc. to the size they were given in the UI designer. * This code will need to be modified to adjust arbitrary controls to * any screen size. - */ + */ void CPjsuaContainer::SizeChanged() - { - CCoeControl::SizeChanged(); - LayoutControls(); + { + CCoeControl::SizeChanged(); + LayoutControls(); - // Align the image - int x = (Size().iWidth - iImage1->Size().iWidth) / 2; - int y = (Size().iHeight - iImage1->Size().iHeight) / 2; - iImage1->SetPosition(TPoint(x, y)); - - // Align the label - iLabel1->SetExtent(TPoint(0, Size().iHeight - iLabel1->Size().iHeight), - TSize(Size().iWidth, iLabel1->Size().iHeight)); - - // [[[ begin generated region: do not modify [Generated Contents] - - // ]]] end generated region [Generated Contents] - - } - + // Align the image + int x = (Size().iWidth - iImage1->Size().iWidth) / 2; + int y = (Size().iHeight - iImage1->Size().iHeight) / 2; + iImage1->SetPosition(TPoint(x, y)); + + // Align the label + iLabel1->SetExtent(TPoint(0, Size().iHeight - iLabel1->Size().iHeight), + TSize(Size().iWidth, iLabel1->Size().iHeight)); + + // [[[ begin generated region: do not modify [Generated Contents] + + // ]]] end generated region [Generated Contents] + + } + // [[[ begin generated function: do not modify /** * Layout components as specified in the UI Designer */ void CPjsuaContainer::LayoutControls() - { - iImage1->SetExtent( TPoint( 0, 0 ), TSize( 99, 111 ) ); - iLabel1->SetExtent( TPoint( 0, 196 ), TSize( 241, 27 ) ); - } + { + iImage1->SetExtent( TPoint( 0, 0 ), TSize( 99, 111 ) ); + iLabel1->SetExtent( TPoint( 0, 196 ), TSize( 241, 27 ) ); + } // ]]] end generated function /** - * Handle key events. - */ + * Handle key events. + */ TKeyResponse CPjsuaContainer::OfferKeyEventL( - const TKeyEvent& aKeyEvent, - TEventCode aType ) - { - // [[[ begin generated region: do not modify [Generated Contents] - - // ]]] end generated region [Generated Contents] - - if ( iFocusControl != NULL - && iFocusControl->OfferKeyEventL( aKeyEvent, aType ) == EKeyWasConsumed ) - { - return EKeyWasConsumed; - } - return CCoeControl::OfferKeyEventL( aKeyEvent, aType ); - } - + const TKeyEvent& aKeyEvent, + TEventCode aType ) + { + // [[[ begin generated region: do not modify [Generated Contents] + + // ]]] end generated region [Generated Contents] + + if ( iFocusControl != NULL + && iFocusControl->OfferKeyEventL( aKeyEvent, aType ) == EKeyWasConsumed ) + { + return EKeyWasConsumed; + } + return CCoeControl::OfferKeyEventL( aKeyEvent, aType ); + } + // [[[ begin generated function: do not modify /** - * Initialize each control upon creation. - */ + * Initialize each control upon creation. + */ void CPjsuaContainer::InitializeControlsL() - { - iImage1 = new ( ELeave ) CEikImage; - { - CFbsBitmap *bitmap, *mask; - AknIconUtils::CreateIconL( bitmap, mask, - KpjsuaFile, EMbmPjsuaPjsua, -1 ); - AknIconUtils::SetSize( bitmap, TSize( 99, 111 ), EAspectRatioPreserved ); - iImage1->SetPicture( bitmap ); - } - iImage1->SetAlignment( EHCenterVTop ); - iLabel1 = new ( ELeave ) CEikLabel; - iLabel1->SetContainerWindowL( *this ); - { - TResourceReader reader; - iEikonEnv->CreateResourceReaderLC( reader, R_PJSUA_CONTAINER_LABEL1 ); - iLabel1->ConstructFromResourceL( reader ); - CleanupStack::PopAndDestroy(); // reader internal state - } - - } + { + iImage1 = new ( ELeave ) CEikImage; + { + CFbsBitmap *bitmap, *mask; + AknIconUtils::CreateIconL( bitmap, mask, + KpjsuaFile, EMbmPjsuaPjsua, -1 ); + AknIconUtils::SetSize( bitmap, TSize( 99, 111 ), EAspectRatioPreserved ); + iImage1->SetPicture( bitmap ); + } + iImage1->SetAlignment( EHCenterVTop ); + iLabel1 = new ( ELeave ) CEikLabel; + iLabel1->SetContainerWindowL( *this ); + { + TResourceReader reader; + iEikonEnv->CreateResourceReaderLC( reader, R_PJSUA_CONTAINER_LABEL1 ); + iLabel1->ConstructFromResourceL( reader ); + CleanupStack::PopAndDestroy(); // reader internal state + } + + } // ]]] end generated function /** * Handle global resource changes, such as scalable UI or skin events (override) */ void CPjsuaContainer::HandleResourceChange( TInt aType ) - { - CCoeControl::HandleResourceChange( aType ); - SetRect( iAvkonViewAppUi->View( TUid::Uid( EPjsuaContainerViewId ) )->ClientRect() ); - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - } - + { + CCoeControl::HandleResourceChange( aType ); + SetRect( iAvkonViewAppUi->View( TUid::Uid( EPjsuaContainerViewId ) )->ClientRect() ); + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + + } + /** - * Draw container contents. - */ + * Draw container contents. + */ void CPjsuaContainer::Draw( const TRect& aRect ) const - { - // [[[ begin generated region: do not modify [Generated Contents] - CWindowGc& gc = SystemGc(); - gc.SetPenStyle( CGraphicsContext::ENullPen ); - TRgb backColor( 0,0,0 ); - gc.SetBrushColor( backColor ); - gc.SetBrushStyle( CGraphicsContext::ESolidBrush ); - gc.DrawRect( aRect ); - - // ]]] end generated region [Generated Contents] - - } + { + // [[[ begin generated region: do not modify [Generated Contents] + CWindowGc& gc = SystemGc(); + gc.SetPenStyle( CGraphicsContext::ENullPen ); + TRgb backColor( 0,0,0 ); + gc.SetBrushColor( backColor ); + gc.SetBrushStyle( CGraphicsContext::ESolidBrush ); + gc.DrawRect( aRect ); + + // ]]] end generated region [Generated Contents] + + } void CPjsuaContainer::PutMessageL( const char * msg ) { if (!iLabel1) - return; + return; TPtrC8 ptr(reinterpret_cast(msg)); HBufC* buffer = HBufC::NewLC(ptr.Length()); diff --git a/pjsip-apps/src/pjsua/symbian/src/pjsuaDocument.cpp b/pjsip-apps/src/pjsua/symbian/src/pjsuaDocument.cpp index f349c6e82d..d7bf24dcc7 100644 --- a/pjsip-apps/src/pjsua/symbian/src/pjsuaDocument.cpp +++ b/pjsip-apps/src/pjsua/symbian/src/pjsuaDocument.cpp @@ -16,18 +16,18 @@ * @param anApplication the application instance */ CpjsuaDocument::CpjsuaDocument( CEikApplication& anApplication ) - : CAknDocument( anApplication ) - { - } + : CAknDocument( anApplication ) + { + } /** * @brief Completes the second phase of Symbian object construction. * Put initialization code that could leave here. */ void CpjsuaDocument::ConstructL() - { - } - + { + } + /** * Symbian OS two-phase constructor. * @@ -38,20 +38,20 @@ void CpjsuaDocument::ConstructL() * @return the new CpjsuaDocument */ CpjsuaDocument* CpjsuaDocument::NewL( CEikApplication& aApp ) - { - CpjsuaDocument* self = new ( ELeave ) CpjsuaDocument( aApp ); - CleanupStack::PushL( self ); - self->ConstructL(); - CleanupStack::Pop( self ); - return self; - } + { + CpjsuaDocument* self = new ( ELeave ) CpjsuaDocument( aApp ); + CleanupStack::PushL( self ); + self->ConstructL(); + CleanupStack::Pop( self ); + return self; + } /** * @brief Creates the application UI object for this document. * @return the new instance - */ + */ CEikAppUi* CpjsuaDocument::CreateAppUiL() - { - return new ( ELeave ) CpjsuaAppUi; - } - + { + return new ( ELeave ) CpjsuaAppUi; + } + diff --git a/pjsip-apps/src/pjsua/winrt/cli/comp/src/Globals.cpp b/pjsip-apps/src/pjsua/winrt/cli/comp/src/Globals.cpp index 4037f77300..30e1203134 100644 --- a/pjsip-apps/src/pjsua/winrt/cli/comp/src/Globals.cpp +++ b/pjsip-apps/src/pjsua/winrt/cli/comp/src/Globals.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -26,7 +25,7 @@ using namespace PjsuaCLI::BackEnd; using namespace Platform; -#define THIS_FILE "Globals.cpp" +#define THIS_FILE "Globals.cpp" #if defined (PJ_WIN32_WINPHONE8) && (PJ_WIN32_WINPHONE8 != 0) @@ -42,27 +41,27 @@ void on_cli_started(pj_status_t status, const char *msg) { char errmsg[PJ_ERR_MSG_SIZE]; if (Globals::Instance->PjsuaCallback) { - static wchar_t msgBuff[ PJ_ERR_MSG_SIZE ]; - Platform::String ^outMsg = nullptr; - if ((status != PJ_SUCCESS) && (!msg || !*msg)) { - pj_strerror(status, errmsg, sizeof(errmsg)); - msg = errmsg; - } - mbstowcs(msgBuff, msg, PJ_ERR_MSG_SIZE); - outMsg = ref new Platform::String(msgBuff); - Globals::Instance->PjsuaCallback->OnStarted(outMsg); + static wchar_t msgBuff[ PJ_ERR_MSG_SIZE ]; + Platform::String ^outMsg = nullptr; + if ((status != PJ_SUCCESS) && (!msg || !*msg)) { + pj_strerror(status, errmsg, sizeof(errmsg)); + msg = errmsg; + } + mbstowcs(msgBuff, msg, PJ_ERR_MSG_SIZE); + outMsg = ref new Platform::String(msgBuff); + Globals::Instance->PjsuaCallback->OnStarted(outMsg); } } void on_cli_stopped(pj_bool_t restart, int argc, char **argv) { if (restart) { - restart_argc = argc; - restart_argv = argv; + restart_argc = argc; + restart_argv = argv; } if (Globals::Instance->PjsuaCallback) { - Globals::Instance->PjsuaCallback->OnStopped(restart); + Globals::Instance->PjsuaCallback->OnStopped(restart); } } @@ -81,9 +80,9 @@ static int initMain(int argc, char **argv) status = pjsua_app_init(&wp_app_config); if (status == PJ_SUCCESS) { - status = pjsua_app_run(PJ_FALSE); + status = pjsua_app_run(PJ_FALSE); } else { - pjsua_app_destroy(); + pjsua_app_destroy(); } return status; @@ -135,9 +134,9 @@ PjsuaCallback^ Globals::PjsuaCallback::get() { if (this->callback == nullptr) { - if (this->callback == nullptr) + if (this->callback == nullptr) { - this->callback = ref new PjsuaCLI::BackEnd::PjsuaCallback(); + this->callback = ref new PjsuaCLI::BackEnd::PjsuaCallback(); } } diff --git a/pjsip-apps/src/pjsua/winrt/cli/comp/src/Globals.h b/pjsip-apps/src/pjsua/winrt/cli/comp/src/Globals.h index 9d202e5eda..4cae587d66 100644 --- a/pjsip-apps/src/pjsua/winrt/cli/comp/src/Globals.h +++ b/pjsip-apps/src/pjsua/winrt/cli/comp/src/Globals.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -23,9 +22,9 @@ namespace PjsuaCLI { namespace BackEnd { - ref class PjsuaCallback; + ref class PjsuaCallback; - public ref class Globals sealed + public ref class Globals sealed { public: // Get the single instance of this class @@ -33,17 +32,17 @@ namespace PjsuaCLI { Globals^ get(); } - + // Get the callback singleton object - property PjsuaCLI::BackEnd::PjsuaCallback^ PjsuaCallback + property PjsuaCLI::BackEnd::PjsuaCallback^ PjsuaCallback { - PjsuaCLI::BackEnd::PjsuaCallback^ get(); + PjsuaCLI::BackEnd::PjsuaCallback^ get(); } - /* pjsua method */ - int pjsuaStart(); - void pjsuaDestroy(); - int pjsuaRestart(); + /* pjsua method */ + int pjsuaStart(); + void pjsuaDestroy(); + int pjsuaRestart(); private: // Default constructor @@ -52,9 +51,9 @@ namespace PjsuaCLI // Destructor ~Globals(); - static Globals^ singleton; + static Globals^ singleton; - PjsuaCLI::BackEnd::PjsuaCallback^ callback; + PjsuaCLI::BackEnd::PjsuaCallback^ callback; }; } } diff --git a/pjsip-apps/src/pjsua/winrt/cli/comp/src/IPjsuaCallback.h b/pjsip-apps/src/pjsua/winrt/cli/comp/src/IPjsuaCallback.h index 6237d10fc0..3f187aa08b 100644 --- a/pjsip-apps/src/pjsua/winrt/cli/comp/src/IPjsuaCallback.h +++ b/pjsip-apps/src/pjsua/winrt/cli/comp/src/IPjsuaCallback.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -23,10 +22,10 @@ namespace PjsuaCLI { namespace BackEnd { - public interface class IPjsuaCallback - { - void OnPjsuaStarted(Platform::String ^outStr); - void OnPjsuaStopped(int restart); - }; + public interface class IPjsuaCallback + { + void OnPjsuaStarted(Platform::String ^outStr); + void OnPjsuaStopped(int restart); + }; } } \ No newline at end of file diff --git a/pjsip-apps/src/pjsua/winrt/cli/comp/src/PjsuaCallback.cpp b/pjsip-apps/src/pjsua/winrt/cli/comp/src/PjsuaCallback.cpp index 985e79c3e3..bf5feb0633 100644 --- a/pjsip-apps/src/pjsua/winrt/cli/comp/src/PjsuaCallback.cpp +++ b/pjsip-apps/src/pjsua/winrt/cli/comp/src/PjsuaCallback.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,7 +23,7 @@ using namespace PjsuaCLI::BackEnd; using namespace Platform; using namespace Windows::Foundation; -#define THIS_FILE "PjsuaCallback.cpp" +#define THIS_FILE "PjsuaCallback.cpp" void PjsuaCallback::SetCallback(IPjsuaCallback^ cb) { @@ -34,14 +33,14 @@ void PjsuaCallback::SetCallback(IPjsuaCallback^ cb) void PjsuaCallback::OnStarted(Platform::String ^outStr) { if (callback) { - callback->OnPjsuaStarted(outStr); + callback->OnPjsuaStarted(outStr); } } void PjsuaCallback::OnStopped(int restart) { if (callback) { - callback->OnPjsuaStopped(restart); + callback->OnPjsuaStopped(restart); } } diff --git a/pjsip-apps/src/pjsua/winrt/cli/comp/src/PjsuaCallback.h b/pjsip-apps/src/pjsua/winrt/cli/comp/src/PjsuaCallback.h index 84757160c1..a3c96fa907 100644 --- a/pjsip-apps/src/pjsua/winrt/cli/comp/src/PjsuaCallback.h +++ b/pjsip-apps/src/pjsua/winrt/cli/comp/src/PjsuaCallback.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -28,20 +27,20 @@ namespace PjsuaCLI // Forward declaration ref class Globals; - public ref class PjsuaCallback sealed - { - public: - void SetCallback(IPjsuaCallback^ cb); + public ref class PjsuaCallback sealed + { + public: + void SetCallback(IPjsuaCallback^ cb); - void OnStarted(Platform::String ^outStr); - void OnStopped(int restart); - private: - friend ref class PjsuaCLI::BackEnd::Globals; + void OnStarted(Platform::String ^outStr); + void OnStopped(int restart); + private: + friend ref class PjsuaCLI::BackEnd::Globals; - PjsuaCallback(); - ~PjsuaCallback(); + PjsuaCallback(); + ~PjsuaCallback(); - IPjsuaCallback^ callback; - }; + IPjsuaCallback^ callback; + }; } } \ No newline at end of file diff --git a/pjsip-apps/src/pjsua/winrt/gui/uwp/VoipBackEnd/MyApp.cpp b/pjsip-apps/src/pjsua/winrt/gui/uwp/VoipBackEnd/MyApp.cpp index f547cf036e..4de59b112a 100644 --- a/pjsip-apps/src/pjsua/winrt/gui/uwp/VoipBackEnd/MyApp.cpp +++ b/pjsip-apps/src/pjsua/winrt/gui/uwp/VoipBackEnd/MyApp.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2016 Teluu Inc. (http://www.teluu.com) * @@ -38,29 +37,29 @@ MyAppRT^ MyAppRT::singleton = nullptr; delete inPtr; #define CHECK_EXCEPTION(expr) \ - do { \ - try { \ - (expr); \ - } catch (pj::Error e) { \ - Platform::Exception^ exp = ref new Platform::COMException( \ - GenHresultFromITF(e.status)); \ - } \ - } while (0) + do { \ + try { \ + (expr); \ + } catch (pj::Error e) { \ + Platform::Exception^ exp = ref new Platform::COMException( \ + GenHresultFromITF(e.status)); \ + } \ + } while (0) /////////////////////////////////////////////////////////////////////////////// std::string make_string(const std::wstring& wstring) { auto wideData = wstring.c_str(); int bufferSize = WideCharToMultiByte(CP_UTF8, 0, wideData, - -1, nullptr, 0, NULL, NULL); + -1, nullptr, 0, NULL, NULL); std::unique_ptr utf8; utf8.reset(new char[bufferSize]); if (WideCharToMultiByte(CP_UTF8, 0, wideData, -1, - utf8.get(), bufferSize, NULL, NULL) == 0) - { - return std::string(); + utf8.get(), bufferSize, NULL, NULL) == 0) + { + return std::string(); } return std::string(utf8.get()); @@ -75,10 +74,10 @@ std::wstring make_wstring(const std::string& string) wide.reset(new wchar_t[bufferSize]); if (MultiByteToWideChar(CP_UTF8, 0, utf8Data, -1, - wide.get(), bufferSize) == 0) - { - return std::wstring(); - } + wide.get(), bufferSize) == 0) + { + return std::wstring(); + } return std::wstring(wide.get());; } @@ -147,11 +146,11 @@ void ImpAccount::setCallback(IntAccount^ callback) void ImpAccount::onIncomingCall(pj::OnIncomingCallParam& prm) { if (cb) { - if (MyAppRT::Instance->handleIncomingCall(prm.callId)) { - CallInfoRT^ info = MyAppRT::Instance->getCallInfo(); - if (info != nullptr) - cb->onIncomingCall(info); - } + if (MyAppRT::Instance->handleIncomingCall(prm.callId)) { + CallInfoRT^ info = MyAppRT::Instance->getCallInfo(); + if (info != nullptr) + cb->onIncomingCall(info); + } } } @@ -159,7 +158,7 @@ void ImpAccount::onIncomingCall(pj::OnIncomingCallParam& prm) void ImpAccount::onRegState(pj::OnRegStateParam& prm) { if (cb) - cb->onRegState(ref new OnRegStateParamRT(prm)); + cb->onRegState(ref new OnRegStateParamRT(prm)); } /////////////////////////////////////////////////////////////////////////////// @@ -245,8 +244,8 @@ void ImpCall::setCallback(IntCall^ callback) void ImpCall::onCallState(pj::OnCallStateParam& prm) { if (cb) { - pj::CallInfo info = getInfo(); - cb->onCallState(ref new CallInfoRT(info)); + pj::CallInfo info = getInfo(); + cb->onCallState(ref new CallInfoRT(info)); } }; @@ -254,33 +253,33 @@ void ImpCall::onCallMediaState(pj::OnCallMediaStateParam& prm) { pj::CallInfo info; try { - info = getInfo(); + info = getInfo(); } catch (pj::Error& e) { - MyAppRT::Instance->writeLog(2, to_platform_str(e.info())); - return; + MyAppRT::Instance->writeLog(2, to_platform_str(e.info())); + return; } for (unsigned i = 0; i < info.media.size(); i++) { - pj::CallMediaInfo med_info = info.media[i]; - if ((med_info.type == PJMEDIA_TYPE_AUDIO) && - ((med_info.status == PJSUA_CALL_MEDIA_ACTIVE) || - (med_info.status == PJSUA_CALL_MEDIA_REMOTE_HOLD)) - ) - { - pj::Media* m = getMedia(i); - pj::AudioMedia *am = pj::AudioMedia::typecastFromMedia(m); - pj::AudDevManager& aud_mgr = - pj::Endpoint::instance().audDevManager(); - - try { - aud_mgr.getCaptureDevMedia().startTransmit(*am); - am->startTransmit(aud_mgr.getPlaybackDevMedia()); - - } catch (pj::Error& e) { - MyAppRT::Instance->writeLog(2, to_platform_str(e.info())); - continue; - } - } + pj::CallMediaInfo med_info = info.media[i]; + if ((med_info.type == PJMEDIA_TYPE_AUDIO) && + ((med_info.status == PJSUA_CALL_MEDIA_ACTIVE) || + (med_info.status == PJSUA_CALL_MEDIA_REMOTE_HOLD)) + ) + { + pj::Media* m = getMedia(i); + pj::AudioMedia *am = pj::AudioMedia::typecastFromMedia(m); + pj::AudDevManager& aud_mgr = + pj::Endpoint::instance().audDevManager(); + + try { + aud_mgr.getCaptureDevMedia().startTransmit(*am); + am->startTransmit(aud_mgr.getPlaybackDevMedia()); + + } catch (pj::Error& e) { + MyAppRT::Instance->writeLog(2, to_platform_str(e.info())); + continue; + } + } } }; /////////////////////////////////////////////////////////////////////////////// @@ -298,29 +297,29 @@ Platform::String^ AccountInfo::registrar::get() { Platform::String^ AccountInfo::proxy::get() { if (!cfg->sipConfig.proxies.empty()) { - return to_platform_str(cfg->sipConfig.proxies[0]); + return to_platform_str(cfg->sipConfig.proxies[0]); } else { - return ref new Platform::String(L""); + return ref new Platform::String(L""); } } Platform::String^ AccountInfo::username::get() { if (!cfg->sipConfig.authCreds.empty()) { - pj::AuthCredInfo& info = cfg->sipConfig.authCreds[0]; + pj::AuthCredInfo& info = cfg->sipConfig.authCreds[0]; - return to_platform_str(info.username); + return to_platform_str(info.username); } else { - return ref new Platform::String(L""); + return ref new Platform::String(L""); } } Platform::String^ AccountInfo::password::get() { if (!cfg->sipConfig.authCreds.empty()) { - pj::AuthCredInfo& info = cfg->sipConfig.authCreds[0]; + pj::AuthCredInfo& info = cfg->sipConfig.authCreds[0]; - return to_platform_str(info.data); + return to_platform_str(info.data); } else { - return ref new Platform::String(L""); + return ref new Platform::String(L""); } } @@ -338,16 +337,16 @@ MyAppRT::~MyAppRT() { delete logWriter; if (account) - delete account; + delete account; if (epConfig) - delete epConfig; + delete epConfig; if (accConfig) - delete accConfig; + delete accConfig; if (sipTpConfig) - delete sipTpConfig; + delete sipTpConfig; } void MyAppRT::loadConfig() @@ -357,24 +356,24 @@ void MyAppRT::loadConfig() std::string configPath = appDir + "/" + CONFIG_NAME; try { - /* Load file */ - json->loadFile(configPath); - pj::ContainerNode root = json->getRootContainer(); + /* Load file */ + json->loadFile(configPath); + pj::ContainerNode root = json->getRootContainer(); - /* Read endpoint config */ - epConfig->readObject(root); + /* Read endpoint config */ + epConfig->readObject(root); - /* Read transport config */ - pj::ContainerNode tp_node = root.readContainer("SipTransport"); - sipTpConfig->readObject(tp_node); + /* Read transport config */ + pj::ContainerNode tp_node = root.readContainer("SipTransport"); + sipTpConfig->readObject(tp_node); - /* Read account configs */ - pj::ContainerNode acc_node = root.readContainer("Account"); - accConfig->readObject(acc_node); + /* Read account configs */ + pj::ContainerNode acc_node = root.readContainer("Account"); + accConfig->readObject(acc_node); } catch (pj::Error) { - ep.utilLogWrite(2, "loadConfig", "Failed loading config"); + ep.utilLogWrite(2, "loadConfig", "Failed loading config"); - sipTpConfig->port = SIP_PORT; + sipTpConfig->port = SIP_PORT; } delete json; @@ -387,23 +386,23 @@ void MyAppRT::saveConfig() std::string configPath = appDir + "/" + CONFIG_NAME; try { - /* Write endpoint config */ - json->writeObject(*epConfig); + /* Write endpoint config */ + json->writeObject(*epConfig); - /* Write transport config */ - pj::ContainerNode tp_node = json->writeNewContainer("SipTransport"); - sipTpConfig->writeObject(tp_node); + /* Write transport config */ + pj::ContainerNode tp_node = json->writeNewContainer("SipTransport"); + sipTpConfig->writeObject(tp_node); - /* Write account configs */ - pj::ContainerNode acc_node = json->writeNewContainer("Account"); - accConfig->writeObject(acc_node); + /* Write account configs */ + pj::ContainerNode acc_node = json->writeNewContainer("Account"); + accConfig->writeObject(acc_node); - /* Save file */ - json->saveFile(configPath); + /* Save file */ + json->saveFile(configPath); } catch (pj::Error) { - ep.utilLogWrite(2, "saveConfig", "Failed saving config"); + ep.utilLogWrite(2, "saveConfig", "Failed saving config"); - sipTpConfig->port = SIP_PORT; + sipTpConfig->port = SIP_PORT; } delete json; @@ -413,10 +412,10 @@ MyAppRT^ MyAppRT::Instance::get() { if (MyAppRT::singleton == nullptr) { - if (MyAppRT::singleton == nullptr) - { - MyAppRT::singleton = ref new MyAppRT(); - } + if (MyAppRT::singleton == nullptr) + { + MyAppRT::singleton = ref new MyAppRT(); + } } return MyAppRT::singleton; @@ -426,9 +425,9 @@ void MyAppRT::init(IntAccount^ iAcc, IntCall^ iCall) { /* Create endpoint */ try { - ep.libCreate(); + ep.libCreate(); } catch (pj::Error e) { - return; + return; } intAcc = iAcc; @@ -449,8 +448,8 @@ void MyAppRT::init(IntAccount^ iAcc, IntCall^ iCall) pj::LogConfig *log_cfg = &epConfig->logConfig; log_cfg->writer = logWriter; log_cfg->decor = log_cfg->decor & - ~(::pj_log_decoration::PJ_LOG_HAS_CR | - ::pj_log_decoration::PJ_LOG_HAS_NEWLINE); + ~(::pj_log_decoration::PJ_LOG_HAS_CR | + ::pj_log_decoration::PJ_LOG_HAS_NEWLINE); /* Set ua config. */ pj::UaConfig* ua_cfg = &epConfig->uaConfig; @@ -460,36 +459,36 @@ void MyAppRT::init(IntAccount^ iAcc, IntCall^ iCall) /* Init endpoint */ try { - ep.libInit(*epConfig); + ep.libInit(*epConfig); } catch (pj::Error& e) { - ep.utilLogWrite(2,THIS_FILE,e.info()); - return; + ep.utilLogWrite(2,THIS_FILE,e.info()); + return; } /* Create transports. */ try { - sipTpConfig->port = 5060; - ep.transportCreate(::pjsip_transport_type_e::PJSIP_TRANSPORT_TCP, - *sipTpConfig); + sipTpConfig->port = 5060; + ep.transportCreate(::pjsip_transport_type_e::PJSIP_TRANSPORT_TCP, + *sipTpConfig); } catch (pj::Error& e) { - ep.utilLogWrite(2,THIS_FILE,e.info()); + ep.utilLogWrite(2,THIS_FILE,e.info()); } try { - ep.transportCreate(::pjsip_transport_type_e::PJSIP_TRANSPORT_UDP, - *sipTpConfig); + ep.transportCreate(::pjsip_transport_type_e::PJSIP_TRANSPORT_UDP, + *sipTpConfig); } catch (pj::Error& e) { - ep.utilLogWrite(2,THIS_FILE,e.info()); + ep.utilLogWrite(2,THIS_FILE,e.info()); } /* Create accounts. */ account = new ImpAccount(); if (accConfig->idUri.length() == 0) { - accConfig->idUri = "sip:localhost"; + accConfig->idUri = "sip:localhost"; } else { - ua_cfg->stunServer.push_back("stun.pjsip.org"); + ua_cfg->stunServer.push_back("stun.pjsip.org"); } //accConfig->natConfig.iceEnabled = true; account->create(*accConfig); @@ -497,10 +496,10 @@ void MyAppRT::init(IntAccount^ iAcc, IntCall^ iCall) /* Start. */ try { - ep.libStart(); + ep.libStart(); } catch (pj::Error& e) { - ep.utilLogWrite(2,THIS_FILE,e.info()); - return; + ep.utilLogWrite(2,THIS_FILE,e.info()); + return; } } @@ -509,7 +508,7 @@ void MyAppRT::deInit() saveConfig(); try { - ep.libDestroy(); + ep.libDestroy(); } catch (pj::Error) {} } @@ -522,13 +521,13 @@ void MyAppRT::writeLog(int level, Platform::String^ message) void MyAppRT::hangupCall() { if (activeCall) { - if (!isThreadRegistered()) - { - registerThread("hangupCall"); - } - - delete activeCall; - activeCall = NULL; + if (!isThreadRegistered()) + { + registerThread("hangupCall"); + } + + delete activeCall; + activeCall = NULL; } }; @@ -536,7 +535,7 @@ void MyAppRT::answerCall(CallOpParamRT^ prm) { if (!isThreadRegistered()) { - registerThread("answerCall"); + registerThread("answerCall"); } CHECK_EXCEPTION(activeCall->answer(*prm->getPtr())); }; @@ -545,7 +544,7 @@ void MyAppRT::makeCall(Platform::String^ dst_uri) { if (!isThreadRegistered()) { - registerThread("makeCall"); + registerThread("makeCall"); } CallOpParamRT^ param = ref new CallOpParamRT; activeCall = new ImpCall(*account, -1); @@ -557,8 +556,8 @@ void MyAppRT::makeCall(Platform::String^ dst_uri) CallInfoRT^ MyAppRT::getCallInfo() { if (activeCall) { - pj::CallInfo info = activeCall->getInfo(); - return ref new CallInfoRT(info); + pj::CallInfo info = activeCall->getInfo(); + return ref new CallInfoRT(info); } return nullptr; @@ -567,7 +566,7 @@ CallInfoRT^ MyAppRT::getCallInfo() pj_bool_t MyAppRT::handleIncomingCall(int callId) { if (activeCall) { - return PJ_FALSE; + return PJ_FALSE; } activeCall = new ImpCall(*account, callId); @@ -595,34 +594,34 @@ AccountInfo^ MyAppRT::getAccountInfo() } void MyAppRT::modifyAccount(Platform::String^ id, - Platform::String^ registrar, - Platform::String^ proxy, - Platform::String^ username, - Platform::String^ password) + Platform::String^ registrar, + Platform::String^ proxy, + Platform::String^ username, + Platform::String^ password) { if (id->IsEmpty()) { - accConfig->idUri = "sip:localhost"; - accConfig->regConfig.registrarUri = ""; - accConfig->sipConfig.authCreds.clear(); - accConfig->sipConfig.proxies.clear(); + accConfig->idUri = "sip:localhost"; + accConfig->regConfig.registrarUri = ""; + accConfig->sipConfig.authCreds.clear(); + accConfig->sipConfig.proxies.clear(); } else { - pj::AuthCredInfo info = pj::AuthCredInfo("Digest", "*", - to_std_str(username), 0, - to_std_str(password)); + pj::AuthCredInfo info = pj::AuthCredInfo("Digest", "*", + to_std_str(username), 0, + to_std_str(password)); - accConfig->idUri = to_std_str(id); - accConfig->regConfig.registrarUri = to_std_str(registrar); + accConfig->idUri = to_std_str(id); + accConfig->regConfig.registrarUri = to_std_str(registrar); - accConfig->sipConfig.authCreds.clear(); - accConfig->sipConfig.authCreds.push_back(info); + accConfig->sipConfig.authCreds.clear(); + accConfig->sipConfig.authCreds.push_back(info); - accConfig->sipConfig.proxies.clear(); - accConfig->sipConfig.proxies.push_back(to_std_str(proxy)); + accConfig->sipConfig.proxies.clear(); + accConfig->sipConfig.proxies.push_back(to_std_str(proxy)); } if (!isThreadRegistered()) { - registerThread("registerAccount"); + registerThread("registerAccount"); } account->modify(*accConfig); diff --git a/pjsip-apps/src/pjsua/winrt/gui/uwp/VoipBackEnd/MyApp.h b/pjsip-apps/src/pjsua/winrt/gui/uwp/VoipBackEnd/MyApp.h index 9f60680cfb..4d64d3516b 100644 --- a/pjsip-apps/src/pjsua/winrt/gui/uwp/VoipBackEnd/MyApp.h +++ b/pjsip-apps/src/pjsua/winrt/gui/uwp/VoipBackEnd/MyApp.h @@ -27,245 +27,245 @@ namespace VoipBackEnd typedef Platform::Collections::Vector StringVector; typedef Windows::Foundation::Collections::IVector - IStringVector; + IStringVector; typedef public enum class INV_STATE { - PJSIP_INV_STATE_NULL, /**< Before INVITE is sent or received */ - PJSIP_INV_STATE_CALLING, /**< After INVITE is sent */ - PJSIP_INV_STATE_INCOMING, /**< After INVITE is received. */ - PJSIP_INV_STATE_EARLY, /**< After response with To tag. */ - PJSIP_INV_STATE_CONNECTING, /**< After 2xx is sent/received. */ - PJSIP_INV_STATE_CONFIRMED, /**< After ACK is sent/received. */ - PJSIP_INV_STATE_DISCONNECTED, /**< Session is terminated. */ + PJSIP_INV_STATE_NULL, /**< Before INVITE is sent or received */ + PJSIP_INV_STATE_CALLING, /**< After INVITE is sent */ + PJSIP_INV_STATE_INCOMING, /**< After INVITE is received. */ + PJSIP_INV_STATE_EARLY, /**< After response with To tag. */ + PJSIP_INV_STATE_CONNECTING, /**< After 2xx is sent/received. */ + PJSIP_INV_STATE_CONFIRMED, /**< After ACK is sent/received. */ + PJSIP_INV_STATE_DISCONNECTED, /**< Session is terminated. */ } INV_STATE; class ImpLogWriter : public pj::LogWriter { public: - virtual void write(const pj::LogEntry &entry); + virtual void write(const pj::LogEntry &entry); }; /* Account related data type. */ public ref struct OnRegStateParamRT sealed { - OnRegStateParamRT(); + OnRegStateParamRT(); - property pj_status_t status - { - pj_status_t get(); - }; + property pj_status_t status + { + pj_status_t get(); + }; - property unsigned code - { - unsigned get(); - }; + property unsigned code + { + unsigned get(); + }; - property Platform::String^ reason - { - Platform::String^ get(); - }; + property Platform::String^ reason + { + Platform::String^ get(); + }; - property int expiration - { - int get(); - }; + property int expiration + { + int get(); + }; internal: - OnRegStateParamRT(const pj::OnRegStateParam& param); + OnRegStateParamRT(const pj::OnRegStateParam& param); private: - pj::OnRegStateParam* inPtr; + pj::OnRegStateParam* inPtr; - ~OnRegStateParamRT(); + ~OnRegStateParamRT(); }; public ref struct CallInfoRT sealed - { - property Platform::String^ localUri - { - Platform::String^ get(); - } - - property Platform::String^ localContact - { - Platform::String^ get(); - } - - property Platform::String^ remoteUri - { - Platform::String^ get(); - } - - property Platform::String^ remoteContact - { - Platform::String^ get(); - } - - property INV_STATE state - { - INV_STATE get(); - }; + { + property Platform::String^ localUri + { + Platform::String^ get(); + } + + property Platform::String^ localContact + { + Platform::String^ get(); + } + + property Platform::String^ remoteUri + { + Platform::String^ get(); + } + + property Platform::String^ remoteContact + { + Platform::String^ get(); + } + + property INV_STATE state + { + INV_STATE get(); + }; internal: - CallInfoRT(const pj::CallInfo& info); + CallInfoRT(const pj::CallInfo& info); private: - pj::CallInfo* inPtr; + pj::CallInfo* inPtr; - ~CallInfoRT(); + ~CallInfoRT(); }; public interface class IntAccount { public: - virtual void onRegState(OnRegStateParamRT^ prm); - virtual void onIncomingCall(CallInfoRT^ info); + virtual void onRegState(OnRegStateParamRT^ prm); + virtual void onIncomingCall(CallInfoRT^ info); }; class ImpAccount : public pj::Account { public: - void setCallback(IntAccount^ callback); + void setCallback(IntAccount^ callback); - virtual void onIncomingCall(pj::OnIncomingCallParam& prm); - virtual void onRegState(pj::OnRegStateParam& prm); + virtual void onIncomingCall(pj::OnIncomingCallParam& prm); + virtual void onRegState(pj::OnRegStateParam& prm); - ~ImpAccount() {}; + ~ImpAccount() {}; private: - IntAccount^ cb; + IntAccount^ cb; }; /* Call related data type. */ public ref class CallOpParamRT sealed { public: - CallOpParamRT(); + CallOpParamRT(); - property unsigned statusCode - { - unsigned get(); - void set(unsigned val); - } + property unsigned statusCode + { + unsigned get(); + void set(unsigned val); + } - property Platform::String^ reason { - Platform::String^ get(); - void set(Platform::String^ val); - } + property Platform::String^ reason { + Platform::String^ get(); + void set(Platform::String^ val); + } internal: - pj::CallOpParam* getPtr(); + pj::CallOpParam* getPtr(); private: - pj::CallOpParam* inPtr; + pj::CallOpParam* inPtr; - ~CallOpParamRT(); + ~CallOpParamRT(); }; public interface class IntCall { public: - virtual void onCallState(CallInfoRT^ info); + virtual void onCallState(CallInfoRT^ info); }; class ImpCall : public pj::Call - { - public: - ImpCall(pj::Account& account, int call_id); - virtual ~ImpCall() {}; + { + public: + ImpCall(pj::Account& account, int call_id); + virtual ~ImpCall() {}; - void setCallback(IntCall^ callback); + void setCallback(IntCall^ callback); - virtual void onCallState(pj::OnCallStateParam& prm); - virtual void onCallMediaState(pj::OnCallMediaStateParam& prm); + virtual void onCallState(pj::OnCallStateParam& prm); + virtual void onCallMediaState(pj::OnCallMediaStateParam& prm); private: - IntCall^ cb; + IntCall^ cb; }; public ref class AccountInfo sealed { public: - property Platform::String^ id { - Platform::String^ get(); - } - property Platform::String^ registrar { - Platform::String^ get(); - } - property Platform::String^ proxy { - Platform::String^ get(); - } - property Platform::String^ username { - Platform::String^ get(); - } - property Platform::String^ password { - Platform::String^ get(); - } + property Platform::String^ id { + Platform::String^ get(); + } + property Platform::String^ registrar { + Platform::String^ get(); + } + property Platform::String^ proxy { + Platform::String^ get(); + } + property Platform::String^ username { + Platform::String^ get(); + } + property Platform::String^ password { + Platform::String^ get(); + } internal: - AccountInfo(pj::AccountConfig* accConfig); + AccountInfo(pj::AccountConfig* accConfig); private: - pj::AccountConfig* cfg; + pj::AccountConfig* cfg; }; /* App class. */ public ref class MyAppRT sealed { public: - static property MyAppRT^ Instance { - MyAppRT^ get(); - } + static property MyAppRT^ Instance { + MyAppRT^ get(); + } - void init(IntAccount^ iAcc, IntCall^ iCall); - void deInit(); + void init(IntAccount^ iAcc, IntCall^ iCall); + void deInit(); - /* Util */ - void writeLog(int level, Platform::String^ message); + /* Util */ + void writeLog(int level, Platform::String^ message); - /* Call handling. */ - void hangupCall(); - void answerCall(CallOpParamRT^ prm); - void makeCall(Platform::String^ dst_uri); - CallInfoRT^ getCallInfo(); + /* Call handling. */ + void hangupCall(); + void answerCall(CallOpParamRT^ prm); + void makeCall(Platform::String^ dst_uri); + CallInfoRT^ getCallInfo(); - /* Thread handling. */ - void registerThread(Platform::String^ name); - bool isThreadRegistered(); + /* Thread handling. */ + void registerThread(Platform::String^ name); + bool isThreadRegistered(); - /* Account handling. */ - AccountInfo^ getAccountInfo(); + /* Account handling. */ + AccountInfo^ getAccountInfo(); - void modifyAccount(Platform::String^ id, Platform::String^ registrar, - Platform::String^ proxy, Platform::String^ username, - Platform::String^ password); + void modifyAccount(Platform::String^ id, Platform::String^ registrar, + Platform::String^ proxy, Platform::String^ username, + Platform::String^ password); internal: - pj_bool_t handleIncomingCall(int callId); + pj_bool_t handleIncomingCall(int callId); private: - MyAppRT(); - ~MyAppRT(); + MyAppRT(); + ~MyAppRT(); - void loadConfig(); - void saveConfig(); + void loadConfig(); + void saveConfig(); - static MyAppRT^ singleton; + static MyAppRT^ singleton; - ImpLogWriter* logWriter; - pj::Endpoint ep; + ImpLogWriter* logWriter; + pj::Endpoint ep; - /* Configs */ - pj::EpConfig* epConfig; - pj::AccountConfig* accConfig; - pj::TransportConfig* sipTpConfig; + /* Configs */ + pj::EpConfig* epConfig; + pj::AccountConfig* accConfig; + pj::TransportConfig* sipTpConfig; - std::string appDir; - ImpAccount* account; - ImpCall* activeCall; + std::string appDir; + ImpAccount* account; + ImpCall* activeCall; - IntAccount^ intAcc; - IntCall^ intCall; + IntAccount^ intAcc; + IntCall^ intCall; }; } \ No newline at end of file diff --git a/pjsip-apps/src/pjsua/wm/main_wm.c b/pjsip-apps/src/pjsua/wm/main_wm.c index 311ca77dbc..0bf9c518e6 100644 --- a/pjsip-apps/src/pjsua/wm/main_wm.c +++ b/pjsip-apps/src/pjsua/wm/main_wm.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -25,19 +24,19 @@ #define MAINWINDOWTITLE TEXT("PJSUA") #define LOGO_PATH TEXT("\\Program Files\\pjsua\\pjsua.bmp") -#define WM_APP_INIT WM_USER + 1 -#define WM_APP_DESTROY WM_USER + 2 -#define WM_APP_RESTART WM_USER + 3 +#define WM_APP_INIT WM_USER + 1 +#define WM_APP_DESTROY WM_USER + 2 +#define WM_APP_RESTART WM_USER + 3 -static HINSTANCE g_hInst; -static HWND g_hWndMenuBar; -static HWND g_hWndMain; -static HWND g_hWndLbl; -static HWND g_hWndImg; -static HBITMAP g_hBmp; +static HINSTANCE g_hInst; +static HWND g_hWndMenuBar; +static HWND g_hWndMain; +static HWND g_hWndLbl; +static HWND g_hWndImg; +static HBITMAP g_hBmp; -static int start_argc; -static char **start_argv; +static int start_argc; +static char **start_argv; /* Helper funtions to init/destroy the pjsua */ static void PjsuaInit(); @@ -49,48 +48,48 @@ static void PjsuaOnStopped(pj_bool_t restart, int argc, char** argv); static void PjsuaOnConfig(pjsua_app_config *cfg); LRESULT CALLBACK DialogProc(const HWND hWnd, - const UINT Msg, - const WPARAM wParam, - const LPARAM lParam) + const UINT Msg, + const WPARAM wParam, + const LPARAM lParam) { LRESULT res = 0; switch (Msg) { case WM_CREATE: - g_hWndMain = hWnd; - break; + g_hWndMain = hWnd; + break; case WM_COMMAND: /* Exit menu */ case WM_CLOSE: - PostQuitMessage(0); - break; + PostQuitMessage(0); + break; case WM_HOTKEY: - /* Exit app when back is pressed. */ - if (VK_TBACK == HIWORD(lParam) && (0 != (MOD_KEYUP & LOWORD(lParam)))) { - PostQuitMessage(0); - } else { - return DefWindowProc(hWnd, Msg, wParam, lParam); - } - break; + /* Exit app when back is pressed. */ + if (VK_TBACK == HIWORD(lParam) && (0 != (MOD_KEYUP & LOWORD(lParam)))) { + PostQuitMessage(0); + } else { + return DefWindowProc(hWnd, Msg, wParam, lParam); + } + break; case WM_CTLCOLORSTATIC: - /* Set text and background color for static windows */ - SetTextColor((HDC)wParam, RGB(255, 255, 255)); - SetBkColor((HDC)wParam, RGB(0, 0, 0)); - return (LRESULT)GetStockObject(BLACK_BRUSH); + /* Set text and background color for static windows */ + SetTextColor((HDC)wParam, RGB(255, 255, 255)); + SetBkColor((HDC)wParam, RGB(0, 0, 0)); + return (LRESULT)GetStockObject(BLACK_BRUSH); case WM_APP_INIT: case WM_APP_RESTART: - PjsuaInit(); - break; + PjsuaInit(); + break; case WM_APP_DESTROY: - PostQuitMessage(0); - break; + PostQuitMessage(0); + break; default: - return DefWindowProc(hWnd, Msg, wParam, lParam); + return DefWindowProc(hWnd, Msg, wParam, lParam); } return res; @@ -102,7 +101,7 @@ LRESULT CALLBACK DialogProc(const HWND hWnd, pj_status_t GuiInit() { WNDCLASS wc; - HWND hWnd = NULL; + HWND hWnd = NULL; RECT r; DWORD dwStyle; enum { LABEL_HEIGHT = 30 }; @@ -117,8 +116,8 @@ pj_status_t GuiInit() hWnd = FindWindow(MAINWINDOWCLASS, MAINWINDOWTITLE); if (NULL != hWnd) { - SetForegroundWindow(hWnd); - return status; + SetForegroundWindow(hWnd); + return status; } wc.style = CS_HREDRAW | CS_VREDRAW; @@ -129,22 +128,22 @@ pj_status_t GuiInit() wc.hIcon = 0; wc.hCursor = 0; wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); - wc.lpszMenuName = 0; + wc.lpszMenuName = 0; wc.lpszClassName = MAINWINDOWCLASS; if (!RegisterClass(&wc) != 0) { - DWORD err = GetLastError(); - return PJ_RETURN_OS_ERROR(err); + DWORD err = GetLastError(); + return PJ_RETURN_OS_ERROR(err); } /* Create the app. window */ g_hWndMain = CreateWindow(MAINWINDOWCLASS, MAINWINDOWTITLE, - WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, - CW_USEDEFAULT, CW_USEDEFAULT, - (HWND)NULL, NULL, g_hInst, (LPSTR)NULL); + WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, + CW_USEDEFAULT, CW_USEDEFAULT, + (HWND)NULL, NULL, g_hInst, (LPSTR)NULL); if (g_hWndMain == NULL) { - DWORD err = GetLastError(); - return PJ_RETURN_OS_ERROR(err); + DWORD err = GetLastError(); + return PJ_RETURN_OS_ERROR(err); } /* Create exit menu */ @@ -155,12 +154,12 @@ pj_status_t GuiInit() ZeroMemory(&mbi, sizeof(SHMENUBARINFO)); mbi.cbSize = sizeof(SHMENUBARINFO); mbi.hwndParent = g_hWndMain; - mbi.dwFlags = SHCMBF_HIDESIPBUTTON|SHCMBF_HMENU; + mbi.dwFlags = SHCMBF_HIDESIPBUTTON|SHCMBF_HMENU; mbi.nToolBarId = (UINT)hRootMenu; mbi.hInstRes = g_hInst; if (FALSE == SHCreateMenuBar(&mbi)) { - DWORD err = GetLastError(); + DWORD err = GetLastError(); return PJ_RETURN_OS_ERROR(err); } @@ -173,8 +172,8 @@ pj_status_t GuiInit() /* Override back button */ SendMessage(g_hWndMenuBar, SHCMBM_OVERRIDEKEY, VK_TBACK, - MAKELPARAM(SHMBOF_NODEFAULT | SHMBOF_NOTIFY, - SHMBOF_NODEFAULT | SHMBOF_NOTIFY)); + MAKELPARAM(SHMBOF_NODEFAULT | SHMBOF_NOTIFY, + SHMBOF_NODEFAULT | SHMBOF_NOTIFY)); /* Get main window size */ GetClientRect(g_hWndMain, &r); @@ -186,32 +185,32 @@ pj_status_t GuiInit() /* Create logo */ g_hBmp = SHLoadDIBitmap(LOGO_PATH); /* for jpeg, uses SHLoadImageFile() */ if (g_hBmp == NULL) { - DWORD err = GetLastError(); - return PJ_RETURN_OS_ERROR(err); + DWORD err = GetLastError(); + return PJ_RETURN_OS_ERROR(err); } GetObject(g_hBmp, sizeof(bmp), &bmp); dwStyle = SS_CENTERIMAGE | SS_REALSIZEIMAGE | SS_BITMAP | - WS_CHILD | WS_VISIBLE; + WS_CHILD | WS_VISIBLE; g_hWndImg = CreateWindow(TEXT("STATIC"), NULL, dwStyle, - (r.right-r.left-bmp.bmWidth)/2, - (r.bottom-r.top-bmp.bmHeight)/2, - bmp.bmWidth, bmp.bmHeight, - g_hWndMain, (HMENU)0, g_hInst, NULL); + (r.right-r.left-bmp.bmWidth)/2, + (r.bottom-r.top-bmp.bmHeight)/2, + bmp.bmWidth, bmp.bmHeight, + g_hWndMain, (HMENU)0, g_hInst, NULL); if (g_hWndImg == NULL) { - DWORD err = GetLastError(); - return PJ_RETURN_OS_ERROR(err); + DWORD err = GetLastError(); + return PJ_RETURN_OS_ERROR(err); } SendMessage(g_hWndImg, STM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)g_hBmp); /* Create label */ dwStyle = WS_CHILD | WS_VISIBLE | ES_CENTER; g_hWndLbl = CreateWindow(TEXT("STATIC"), NULL, dwStyle, - 0, r.bottom-LABEL_HEIGHT, r.right-r.left, LABEL_HEIGHT, + 0, r.bottom-LABEL_HEIGHT, r.right-r.left, LABEL_HEIGHT, g_hWndMain, (HMENU)0, g_hInst, NULL); if (g_hWndLbl == NULL) { - DWORD err = GetLastError(); - return PJ_RETURN_OS_ERROR(err); + DWORD err = GetLastError(); + return PJ_RETURN_OS_ERROR(err); } SetWindowText(g_hWndLbl, _T("Please wait..")); @@ -233,24 +232,24 @@ pj_status_t GuiStart() void GuiDestroy(void) { if (g_hWndMain) { - DestroyWindow(g_hWndMain); - g_hWndMain = NULL; + DestroyWindow(g_hWndMain); + g_hWndMain = NULL; } if (g_hWndMenuBar) { - DestroyWindow(g_hWndMenuBar); - g_hWndMenuBar = NULL; + DestroyWindow(g_hWndMenuBar); + g_hWndMenuBar = NULL; } if (g_hWndLbl) { - DestroyWindow(g_hWndLbl); - g_hWndLbl = NULL; + DestroyWindow(g_hWndLbl); + g_hWndLbl = NULL; } if (g_hWndImg) { - DestroyWindow(g_hWndImg); - g_hWndImg = NULL; + DestroyWindow(g_hWndImg); + g_hWndImg = NULL; } if (g_hBmp) { - DeleteObject(g_hBmp); - g_hBmp = NULL; + DeleteObject(g_hBmp); + g_hBmp = NULL; } UnregisterClass(MAINWINDOWCLASS, g_hInst); } @@ -264,11 +263,11 @@ void PjsuaOnStarted(pj_status_t status, const char* title) char err_msg[128]; if (status != PJ_SUCCESS || title == NULL) { - char err_str[PJ_ERR_MSG_SIZE]; - pj_strerror(status, err_str, sizeof(err_str)); - pj_ansi_snprintf(err_msg, sizeof(err_msg), "%s: %s", - (title?title:"App start error"), err_str); - title = err_msg; + char err_str[PJ_ERR_MSG_SIZE]; + pj_strerror(status, err_str, sizeof(err_str)); + pj_ansi_snprintf(err_msg, sizeof(err_msg), "%s: %s", + (title?title:"App start error"), err_str); + title = err_msg; } pj_ansi_to_unicode(title, strlen(title), wtitle, PJ_ARRAY_SIZE(wtitle)); @@ -279,14 +278,14 @@ void PjsuaOnStarted(pj_status_t status, const char* title) void PjsuaOnStopped(pj_bool_t restart, int argc, char** argv) { if (restart) { - start_argc = argc; - start_argv = argv; + start_argc = argc; + start_argv = argv; - // Schedule Lib Restart - PostMessage(g_hWndMain, WM_APP_RESTART, 0, 0); + // Schedule Lib Restart + PostMessage(g_hWndMain, WM_APP_RESTART, 0, 0); } else { - /* Destroy & quit GUI, e.g: clean up window, resources */ - PostMessage(g_hWndMain, WM_APP_DESTROY, 0, 0); + /* Destroy & quit GUI, e.g: clean up window, resources */ + PostMessage(g_hWndMain, WM_APP_DESTROY, 0, 0); } } @@ -315,16 +314,16 @@ void PjsuaInit() SetWindowText(g_hWndLbl, _T("Initializing..")); status = pjsua_app_init(&app_cfg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; SetWindowText(g_hWndLbl, _T("Starting..")); status = pjsua_app_run(PJ_FALSE); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; on_return: if (status != PJ_SUCCESS) - SetWindowText(g_hWndLbl, _T("Initialization failed")); + SetWindowText(g_hWndLbl, _T("Initialization failed")); } void PjsuaDestroy() @@ -353,7 +352,7 @@ int WINAPI WinMain( // Start GUI status = GuiInit(); if (status != 0) - goto on_return; + goto on_return; // Setup args and start pjsua start_argc = pjsua_app_def_argc; @@ -361,7 +360,7 @@ int WINAPI WinMain( PostMessage(g_hWndMain, WM_APP_INIT, 0, 0); status = GuiStart(); - + on_return: PjsuaDestroy(); GuiDestroy(); diff --git a/pjsip-apps/src/pjsystest/gui.h b/pjsip-apps/src/pjsystest/gui.h index 5d3631d882..079f96c7c3 100644 --- a/pjsip-apps/src/pjsystest/gui.h +++ b/pjsip-apps/src/pjsystest/gui.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -29,10 +28,10 @@ typedef void (*gui_menu_handler) (void); typedef struct gui_menu { - gui_title title; - gui_menu_handler handler; - unsigned submenu_cnt; - struct gui_menu *submenus[16]; + gui_title title; + gui_menu_handler handler; + unsigned submenu_cnt; + struct gui_menu *submenus[16]; } gui_menu; enum gui_flag @@ -69,4 +68,4 @@ void gui_sleep(unsigned sec); PJ_END_DECL -#endif /* __GUI_H__ */ +#endif /* __GUI_H__ */ diff --git a/pjsip-apps/src/pjsystest/main_console.c b/pjsip-apps/src/pjsystest/main_console.c index e2c3302137..eb5114ee1d 100644 --- a/pjsip-apps/src/pjsystest/main_console.c +++ b/pjsip-apps/src/pjsystest/main_console.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -29,22 +28,22 @@ enum gui_key gui_msgbox(const char *title, const char *message, enum gui_flag fl puts(message); for (;;) { - char input[10], *ret; - - if (flag == WITH_YESNO) - printf("%c:Yes %c:No ", KEY_YES, KEY_NO); - else if (flag == WITH_OK) - printf("%c:OK ", KEY_OK); - else if (flag == WITH_OKCANCEL) - printf("%c:OK %c:Cancel ", KEY_OK, KEY_CANCEL); - puts(""); - - ret = fgets(input, sizeof(input), stdin); - if (!ret) - return KEY_CANCEL; - - if (input[0]==KEY_NO || input[0]==KEY_YES || input[0]==KEY_CANCEL) - return (enum gui_key)input[0]; + char input[10], *ret; + + if (flag == WITH_YESNO) + printf("%c:Yes %c:No ", KEY_YES, KEY_NO); + else if (flag == WITH_OK) + printf("%c:OK ", KEY_OK); + else if (flag == WITH_OKCANCEL) + printf("%c:OK %c:Cancel ", KEY_OK, KEY_CANCEL); + puts(""); + + ret = fgets(input, sizeof(input), stdin); + if (!ret) + return KEY_CANCEL; + + if (input[0]==KEY_NO || input[0]==KEY_YES || input[0]==KEY_CANCEL) + return (enum gui_key)input[0]; } } @@ -64,58 +63,58 @@ static void print_menu(const char *indent, char *menu_id, gui_menu *menu) printf("%s%s: %s\n", indent, menu_id, menu->title); for (i=0; isubmenu_cnt; ++i) { - char child_id[10]; + char child_id[10]; - pj_ansi_sprintf(child_id, "%s%u", menu_id, i); + pj_ansi_sprintf(child_id, "%s%u", menu_id, i); - if (!menu->submenus[i]) - puts(""); - else - print_menu(child_indent, child_id, menu->submenus[i]); + if (!menu->submenus[i]) + puts(""); + else + print_menu(child_indent, child_id, menu->submenus[i]); } } pj_status_t gui_start(gui_menu *menu) { while (!console_quit) { - unsigned i; - char input[10], *p; - gui_menu *choice; - - puts("M E N U :"); - puts("---------"); - for (i=0; isubmenu_cnt; ++i) { - char menu_id[11]; - pj_ansi_sprintf(menu_id, "%u", i); - print_menu("", menu_id, menu->submenus[i]); - } - puts(""); - printf("Enter the menu number: "); - - if (!fgets(input, sizeof(input), stdin)) - break; - - p = input; - choice = menu; - while (*p && *p!='\r' && *p!='\n') { - unsigned d = (*p - '0'); - if (d >= choice->submenu_cnt) { - puts("Invalid selection"); - choice = NULL; - break; - } - - choice = choice->submenus[d]; - ++p; - } - - if (choice && *p!='\r' && *p!='\n') { - puts("Invalid characters entered"); - continue; - } - - if (choice && choice->handler) - (*choice->handler)(); + unsigned i; + char input[10], *p; + gui_menu *choice; + + puts("M E N U :"); + puts("---------"); + for (i=0; isubmenu_cnt; ++i) { + char menu_id[11]; + pj_ansi_sprintf(menu_id, "%u", i); + print_menu("", menu_id, menu->submenus[i]); + } + puts(""); + printf("Enter the menu number: "); + + if (!fgets(input, sizeof(input), stdin)) + break; + + p = input; + choice = menu; + while (*p && *p!='\r' && *p!='\n') { + unsigned d = (*p - '0'); + if (d >= choice->submenu_cnt) { + puts("Invalid selection"); + choice = NULL; + break; + } + + choice = choice->submenus[d]; + ++p; + } + + if (choice && *p!='\r' && *p!='\n') { + puts("Invalid characters entered"); + continue; + } + + if (choice && choice->handler) + (*choice->handler)(); } return PJ_SUCCESS; @@ -136,7 +135,7 @@ int main() pj_log_set_level(1); if (systest_init() != PJ_SUCCESS) - return 1; + return 1; systest_run(); systest_deinit(); diff --git a/pjsip-apps/src/pjsystest/main_wm.c b/pjsip-apps/src/pjsystest/main_wm.c index debe8dd30c..09fff0a219 100644 --- a/pjsip-apps/src/pjsystest/main_wm.c +++ b/pjsip-apps/src/pjsystest/main_wm.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -31,20 +30,20 @@ #define MAINWINDOWTITLE TEXT("PJSYSTEST") typedef struct menu_handler_t { - UINT id; - gui_menu_handler handler; + UINT id; + gui_menu_handler handler; } menu_handler_t; -static HINSTANCE g_hInst; -static HWND g_hWndMenuBar; -static HWND g_hWndMain; -static HWND g_hWndLog; -static pj_thread_t *g_log_thread; -static gui_menu *g_menu; -static unsigned g_menu_handler_cnt; -static menu_handler_t g_menu_handlers[64]; +static HINSTANCE g_hInst; +static HWND g_hWndMenuBar; +static HWND g_hWndMain; +static HWND g_hWndLog; +static pj_thread_t *g_log_thread; +static gui_menu *g_menu; +static unsigned g_menu_handler_cnt; +static menu_handler_t g_menu_handlers[64]; -static pj_log_func *g_log_writer_orig; +static pj_log_func *g_log_writer_orig; static pj_status_t gui_update_menu(gui_menu *menu); @@ -58,18 +57,18 @@ static void log_writer(int level, const char *buffer, int len) pj_ansi_to_unicode(buffer, len, buf, 512); if (!g_hWndLog) - return; + return; /* For now, ignore log messages from other thread to avoid deadlock */ if (g_log_thread == pj_thread_this()) { - cur_len = (int)SendMessage(g_hWndLog, WM_GETTEXTLENGTH, 0, 0); - SendMessage(g_hWndLog, EM_SETSEL, (WPARAM)cur_len, (LPARAM)cur_len); - SendMessage(g_hWndLog, EM_REPLACESEL, (WPARAM)0, (LPARAM)buf); + cur_len = (int)SendMessage(g_hWndLog, WM_GETTEXTLENGTH, 0, 0); + SendMessage(g_hWndLog, EM_SETSEL, (WPARAM)cur_len, (LPARAM)cur_len); + SendMessage(g_hWndLog, EM_REPLACESEL, (WPARAM)0, (LPARAM)buf); } //uncomment to forward to the original log writer if (g_log_writer_orig) - (*g_log_writer_orig)(level, buffer, len); + (*g_log_writer_orig)(level, buffer, len); } /* execute menu handler for id menu specified, return FALSE if menu handler @@ -80,11 +79,11 @@ static BOOL handle_menu(UINT id) unsigned i; for (i = 0; i < g_menu_handler_cnt; ++i) { - if (g_menu_handlers[i].id == id) { - /* menu handler found, execute it */ - (*g_menu_handlers[i].handler)(); - return TRUE; - } + if (g_menu_handlers[i].id == id) { + /* menu handler found, execute it */ + (*g_menu_handlers[i].handler)(); + return TRUE; + } } return FALSE; @@ -97,50 +96,50 @@ static UINT generate_submenu(HMENU parent, UINT id_start, gui_menu *menu) UINT id = id_start; if (!menu) - return id; + return id; /* generate submenu */ for (i = 0; i < menu->submenu_cnt; ++i) { - if (menu->submenus[i] == NULL) { - - /* add separator */ - AppendMenu(parent, MF_SEPARATOR, 0, 0); - - } else if (menu->submenus[i]->submenu_cnt != 0) { - - /* this submenu item has children, generate popup menu */ - HMENU hMenu; - wchar_t buf[64]; - - pj_ansi_to_unicode(menu->submenus[i]->title, - pj_ansi_strlen(menu->submenus[i]->title), - buf, 64); - - hMenu = CreatePopupMenu(); - AppendMenu(parent, MF_STRING|MF_ENABLED|MF_POPUP, (UINT)hMenu, buf); - id = generate_submenu(hMenu, id, menu->submenus[i]); - - } else { - - /* this submenu item is leaf, register the handler */ - wchar_t buf[64]; - - pj_ansi_to_unicode(menu->submenus[i]->title, - pj_ansi_strlen(menu->submenus[i]->title), - buf, 64); - - AppendMenu(parent, MF_STRING, id, buf); - - if (menu->submenus[i]->handler) { - g_menu_handlers[g_menu_handler_cnt].id = id; - g_menu_handlers[g_menu_handler_cnt].handler = - menu->submenus[i]->handler; - ++g_menu_handler_cnt; - } - - ++id; - } + if (menu->submenus[i] == NULL) { + + /* add separator */ + AppendMenu(parent, MF_SEPARATOR, 0, 0); + + } else if (menu->submenus[i]->submenu_cnt != 0) { + + /* this submenu item has children, generate popup menu */ + HMENU hMenu; + wchar_t buf[64]; + + pj_ansi_to_unicode(menu->submenus[i]->title, + pj_ansi_strlen(menu->submenus[i]->title), + buf, 64); + + hMenu = CreatePopupMenu(); + AppendMenu(parent, MF_STRING|MF_ENABLED|MF_POPUP, (UINT)hMenu, buf); + id = generate_submenu(hMenu, id, menu->submenus[i]); + + } else { + + /* this submenu item is leaf, register the handler */ + wchar_t buf[64]; + + pj_ansi_to_unicode(menu->submenus[i]->title, + pj_ansi_strlen(menu->submenus[i]->title), + buf, 64); + + AppendMenu(parent, MF_STRING, id, buf); + + if (menu->submenus[i]->handler) { + g_menu_handlers[g_menu_handler_cnt].id = id; + g_menu_handlers[g_menu_handler_cnt].handler = + menu->submenus[i]->handler; + ++g_menu_handler_cnt; + } + + ++id; + } } return id; @@ -150,53 +149,53 @@ BOOL InitDialog() { /* update menu */ if (gui_update_menu(g_menu) != PJ_SUCCESS) - return FALSE; + return FALSE; return TRUE; } LRESULT CALLBACK DialogProc(const HWND hWnd, - const UINT Msg, - const WPARAM wParam, - const LPARAM lParam) + const UINT Msg, + const WPARAM wParam, + const LPARAM lParam) { LRESULT res = 0; switch (Msg) { case WM_CREATE: - g_hWndMain = hWnd; - if (FALSE == InitDialog()){ - DestroyWindow(g_hWndMain); - } - break; + g_hWndMain = hWnd; + if (FALSE == InitDialog()){ + DestroyWindow(g_hWndMain); + } + break; case WM_CLOSE: - DestroyWindow(g_hWndMain); - break; + DestroyWindow(g_hWndMain); + break; case WM_DESTROY: - if (g_hWndMenuBar) - DestroyWindow(g_hWndMenuBar); - g_hWndMenuBar = NULL; - g_hWndMain = NULL; + if (g_hWndMenuBar) + DestroyWindow(g_hWndMenuBar); + g_hWndMenuBar = NULL; + g_hWndMain = NULL; PostQuitMessage(0); break; case WM_HOTKEY: - /* Exit app when back is pressed. */ - if (VK_TBACK == HIWORD(lParam) && (0 != (MOD_KEYUP & LOWORD(lParam)))) { - DestroyWindow(g_hWndMain); - } else { - return DefWindowProc(hWnd, Msg, wParam, lParam); - } - break; + /* Exit app when back is pressed. */ + if (VK_TBACK == HIWORD(lParam) && (0 != (MOD_KEYUP & LOWORD(lParam)))) { + DestroyWindow(g_hWndMain); + } else { + return DefWindowProc(hWnd, Msg, wParam, lParam); + } + break; case WM_COMMAND: - res = handle_menu(LOWORD(wParam)); - break; + res = handle_menu(LOWORD(wParam)); + break; default: - return DefWindowProc(hWnd, Msg, wParam, lParam); + return DefWindowProc(hWnd, Msg, wParam, lParam); } return res; @@ -208,7 +207,7 @@ LRESULT CALLBACK DialogProc(const HWND hWnd, pj_status_t gui_init(gui_menu *menu) { WNDCLASS wc; - HWND hWnd = NULL; + HWND hWnd = NULL; RECT r; DWORD dwStyle; @@ -218,8 +217,8 @@ pj_status_t gui_init(gui_menu *menu) hWnd = FindWindow(MAINWINDOWCLASS, MAINWINDOWTITLE); if (NULL != hWnd) { - SetForegroundWindow(hWnd); - return status; + SetForegroundWindow(hWnd); + return status; } g_menu = menu; @@ -232,50 +231,50 @@ pj_status_t gui_init(gui_menu *menu) wc.hIcon = 0; wc.hCursor = 0; wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); - wc.lpszMenuName = 0; + wc.lpszMenuName = 0; wc.lpszClassName = MAINWINDOWCLASS; if (!RegisterClass(&wc) != 0) { - DWORD err = GetLastError(); - return PJ_RETURN_OS_ERROR(err); + DWORD err = GetLastError(); + return PJ_RETURN_OS_ERROR(err); } /* Create the app. window */ g_hWndMain = CreateWindow(MAINWINDOWCLASS, MAINWINDOWTITLE, - WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, - CW_USEDEFAULT, CW_USEDEFAULT, - (HWND)NULL, NULL, g_hInst, (LPSTR)NULL); + WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, + CW_USEDEFAULT, CW_USEDEFAULT, + (HWND)NULL, NULL, g_hInst, (LPSTR)NULL); /* Create edit control to print log */ GetClientRect(g_hWndMain, &r); dwStyle = WS_CHILD | WS_VISIBLE | WS_VSCROLL | - ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | ES_LEFT; + ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | ES_LEFT; g_hWndLog = CreateWindow( TEXT("EDIT"), // Class name NULL, // Window text dwStyle, // Window style - 0, // x-coordinate of the upper-left corner + 0, // x-coordinate of the upper-left corner 0, // y-coordinate of the upper-left corner - r.right-r.left, // Width of the window for the edit + r.right-r.left, // Width of the window for the edit // control - r.bottom-r.top, // Height of the window for the edit + r.bottom-r.top, // Height of the window for the edit // control g_hWndMain, // Window handle to the parent window - (HMENU) 0, // Control identifier + (HMENU) 0, // Control identifier g_hInst, // Instance handle NULL); // Specify NULL for this parameter when // you create a control /* Resize the log */ if (g_hWndMenuBar) { - RECT r_menu = {0}; - - GetWindowRect(g_hWndLog, &r); - GetWindowRect(g_hWndMenuBar, &r_menu); - if (r.bottom > r_menu.top) { - MoveWindow(g_hWndLog, 0, 0, r.right-r.left, - (r.bottom-r.top)-(r_menu.bottom-r_menu.top), TRUE); - } + RECT r_menu = {0}; + + GetWindowRect(g_hWndLog, &r); + GetWindowRect(g_hWndMenuBar, &r_menu); + if (r.bottom > r_menu.top) { + MoveWindow(g_hWndLog, 0, 0, r.right-r.left, + (r.bottom-r.top)-(r_menu.bottom-r_menu.top), TRUE); + } } /* Focus it, so SP user can scroll the log */ @@ -305,8 +304,8 @@ static pj_status_t gui_update_menu(gui_menu *menu) /* delete existing menu */ if (g_hWndMenuBar) { - DestroyWindow(g_hWndMenuBar); - g_hWndMenuBar = NULL; + DestroyWindow(g_hWndMenuBar); + g_hWndMenuBar = NULL; } /* delete menu handler map */ @@ -323,12 +322,12 @@ static pj_status_t gui_update_menu(gui_menu *menu) ZeroMemory(&mbi, sizeof(SHMENUBARINFO)); mbi.cbSize = sizeof(SHMENUBARINFO); mbi.hwndParent = g_hWndMain; - mbi.dwFlags = SHCMBF_HIDESIPBUTTON|SHCMBF_HMENU; + mbi.dwFlags = SHCMBF_HIDESIPBUTTON|SHCMBF_HMENU; mbi.nToolBarId = (UINT)hRootMenu; mbi.hInstRes = g_hInst; if (FALSE == SHCreateMenuBar(&mbi)) { - DWORD err = GetLastError(); + DWORD err = GetLastError(); return PJ_RETURN_OS_ERROR(err); } @@ -344,8 +343,8 @@ static pj_status_t gui_update_menu(gui_menu *menu) /* override back button */ SendMessage(g_hWndMenuBar, SHCMBM_OVERRIDEKEY, VK_TBACK, - MAKELPARAM(SHMBOF_NODEFAULT | SHMBOF_NOTIFY, - SHMBOF_NODEFAULT | SHMBOF_NOTIFY)); + MAKELPARAM(SHMBOF_NODEFAULT | SHMBOF_NOTIFY, + SHMBOF_NODEFAULT | SHMBOF_NOTIFY)); return PJ_SUCCESS; @@ -363,27 +362,27 @@ enum gui_key gui_msgbox(const char *title, const char *message, enum gui_flag fl switch (flag) { case WITH_OK: - wflag = MB_OK; - break; + wflag = MB_OK; + break; case WITH_YESNO: - wflag = MB_YESNO; - break; + wflag = MB_YESNO; + break; case WITH_OKCANCEL: - wflag = MB_OKCANCEL; - break; + wflag = MB_OKCANCEL; + break; } retcode = MessageBox(g_hWndMain, buf_msg, buf_title, wflag); switch (retcode) { case IDOK: - return KEY_OK; + return KEY_OK; case IDYES: - return KEY_YES; + return KEY_YES; case IDNO: - return KEY_NO; + return KEY_NO; default: - return KEY_CANCEL; + return KEY_CANCEL; } } @@ -409,8 +408,8 @@ pj_status_t gui_start(gui_menu *menu) void gui_destroy(void) { if (g_hWndMain) { - DestroyWindow(g_hWndMain); - g_hWndMain = NULL; + DestroyWindow(g_hWndMain); + g_hWndMain = NULL; } } @@ -433,10 +432,10 @@ int WINAPI WinMain( status = systest_init(); if (status != 0) - goto on_return; + goto on_return; status = systest_run(); - + on_return: systest_deinit(); diff --git a/pjsip-apps/src/pjsystest/systest.c b/pjsip-apps/src/pjsystest/systest.c index 07ed7a7f9e..82590a8a4c 100644 --- a/pjsip-apps/src/pjsystest/systest.c +++ b/pjsip-apps/src/pjsystest/systest.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -23,9 +22,9 @@ unsigned test_item_count; test_item_t test_items[SYSTEST_MAX_TEST]; -char doc_path[PATH_LENGTH] = {0}; -char res_path[PATH_LENGTH] = {0}; -char fpath[PATH_LENGTH]; +char doc_path[PATH_LENGTH] = {0}; +char res_path[PATH_LENGTH] = {0}; +char fpath[PATH_LENGTH]; #define USER_ERROR "User used said not okay" @@ -60,16 +59,16 @@ static gui_menu menu_tests = { "Tests", NULL, 10, { - &menu_wizard, - &menu_audtest, - &menu_playtn, - &menu_playwv1, - &menu_playwv2, - &menu_recaud, - &menu_calclat, - &menu_sndaec, - NULL, - &menu_exit + &menu_wizard, + &menu_audtest, + &menu_playtn, + &menu_playwv1, + &menu_playwv2, + &menu_recaud, + &menu_calclat, + &menu_sndaec, + NULL, + &menu_exit } }; @@ -77,8 +76,8 @@ static gui_menu menu_options = { "Options", NULL, 2, { - &menu_listdev, - &menu_getsets, + &menu_listdev, + &menu_getsets, } }; @@ -111,8 +110,8 @@ static void exit_app(void) typedef struct systest_t { - pjsua_config ua_cfg; - pjsua_media_config media_cfg; + pjsua_config ua_cfg; + pjsua_media_config media_cfg; pjmedia_aud_dev_index rec_id; pjmedia_aud_dev_index play_id; } systest_t; @@ -130,9 +129,9 @@ static void systest_perror(const char *title, pj_status_t status) char themsg[PJ_ERR_MSG_SIZE + 100]; if (status != PJ_SUCCESS) - pj_strerror(status, errmsg, sizeof(errmsg)); + pj_strerror(status, errmsg, sizeof(errmsg)); else - errmsg[0] = '\0'; + errmsg[0] = '\0'; strcpy(themsg, title); strncat(themsg, errmsg, sizeof(themsg)-1); @@ -146,8 +145,8 @@ test_item_t *systest_alloc_test_item(const char *title) test_item_t *ti; if (test_item_count == SYSTEST_MAX_TEST) { - gui_msgbox("Error", "You have done too many tests", WITH_OK); - return NULL; + gui_msgbox("Error", "You have done too many tests", WITH_OK); + return NULL; } ti = &test_items[test_item_count++]; @@ -163,12 +162,12 @@ test_item_t *systest_alloc_test_item(const char *title) static void systest_play_tone(void) { /* Ringtones */ - #define RINGBACK_FREQ1 440 /* 400 */ - #define RINGBACK_FREQ2 480 /* 450 */ - #define RINGBACK_ON 3000 /* 400 */ - #define RINGBACK_OFF 4000 /* 200 */ - #define RINGBACK_CNT 1 /* 2 */ - #define RINGBACK_INTERVAL 4000 /* 2000 */ + #define RINGBACK_FREQ1 440 /* 400 */ + #define RINGBACK_FREQ2 480 /* 450 */ + #define RINGBACK_ON 3000 /* 400 */ + #define RINGBACK_OFF 4000 /* 200 */ + #define RINGBACK_CNT 1 /* 2 */ + #define RINGBACK_INTERVAL 4000 /* 2000 */ unsigned i, samples_per_frame; pjmedia_tone_desc tone[RINGBACK_CNT]; @@ -183,85 +182,85 @@ static void systest_play_tone(void) ti = systest_alloc_test_item(title); if (!ti) - return; + return; key = gui_msgbox(title, - "This test will play simple ringback tone to " - "the speaker. Please listen carefully for audio " - "impairments such as stutter. You may need " - "to let this test running for a while to " - "make sure that everything is okay. Press " - "OK to start, CANCEL to skip", - WITH_OKCANCEL); + "This test will play simple ringback tone to " + "the speaker. Please listen carefully for audio " + "impairments such as stutter. You may need " + "to let this test running for a while to " + "make sure that everything is okay. Press " + "OK to start, CANCEL to skip", + WITH_OKCANCEL); if (key != KEY_OK) { - ti->skipped = PJ_TRUE; - return; + ti->skipped = PJ_TRUE; + return; } PJ_LOG(3,(THIS_FILE, "Running %s", title)); pool = pjsua_pool_create("ringback", 512, 512); samples_per_frame = systest.media_cfg.audio_frame_ptime * - systest.media_cfg.clock_rate * - systest.media_cfg.channel_count / 1000; + systest.media_cfg.clock_rate * + systest.media_cfg.channel_count / 1000; /* Ringback tone (call is ringing) */ name = pj_str("ringback"); status = pjmedia_tonegen_create2(pool, &name, - systest.media_cfg.clock_rate, - systest.media_cfg.channel_count, - samples_per_frame, - 16, PJMEDIA_TONEGEN_LOOP, - &ringback_port); + systest.media_cfg.clock_rate, + systest.media_cfg.channel_count, + samples_per_frame, + 16, PJMEDIA_TONEGEN_LOOP, + &ringback_port); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; pj_bzero(&tone, sizeof(tone)); for (i=0; isuccess = PJ_FALSE; - pj_strerror(status, ti->reason, sizeof(ti->reason)); + systest_perror("Sorry we encounter error when initializing " + "the tone generator: ", status); + ti->success = PJ_FALSE; + pj_strerror(status, ti->reason, sizeof(ti->reason)); } else { - key = gui_msgbox(title, "Is the audio okay?", WITH_YESNO); - ti->success = (key == KEY_YES); - if (!ti->success) - pj_ansi_strcpy(ti->reason, USER_ERROR); + key = gui_msgbox(title, "Is the audio okay?", WITH_YESNO); + ti->success = (key == KEY_YES); + if (!ti->success) + pj_ansi_strcpy(ti->reason, USER_ERROR); } return; } @@ -270,16 +269,16 @@ static void systest_play_tone(void) * the file. */ static pj_status_t create_player(unsigned path_cnt, const char *paths[], - pjsua_player_id *p_id) + pjsua_player_id *p_id) { pj_str_t name; pj_status_t status = PJ_ENOTFOUND; unsigned i; for (i=0; iskipped = PJ_TRUE; - return; + ti->skipped = PJ_TRUE; + return; } PJ_LOG(3,(THIS_FILE, "Running %s", title)); @@ -319,31 +318,31 @@ static void systest_play_wav(unsigned path_cnt, const char *paths[]) /* WAV port */ status = create_player(path_cnt, paths, &play_id); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; status = pjsua_conf_connect(pjsua_player_get_conf_port(play_id), 0); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; key = gui_msgbox(title, - "WAV file should be playing now in the " - "speaker. Press OK to stop. ", WITH_OK); + "WAV file should be playing now in the " + "speaker. Press OK to stop. ", WITH_OK); status = PJ_SUCCESS; on_return: if (play_id != -1) - pjsua_player_destroy(play_id); + pjsua_player_destroy(play_id); if (status != PJ_SUCCESS) { - systest_perror("Sorry we've encountered error", status); - ti->success = PJ_FALSE; - pj_strerror(status, ti->reason, sizeof(ti->reason)); + systest_perror("Sorry we've encountered error", status); + ti->success = PJ_FALSE; + pj_strerror(status, ti->reason, sizeof(ti->reason)); } else { - key = gui_msgbox(title, "Is the audio okay?", WITH_YESNO); - ti->success = (key == KEY_YES); - if (!ti->success) - pj_ansi_strcpy(ti->reason, USER_ERROR); + key = gui_msgbox(title, "Is the audio okay?", WITH_YESNO); + ti->success = (key == KEY_YES); + if (!ti->success) + pj_ansi_strcpy(ti->reason, USER_ERROR); } return; } @@ -351,14 +350,14 @@ static void systest_play_wav(unsigned path_cnt, const char *paths[]) static void systest_play_wav1(void) { const char *paths[] = { add_path(res_path, WAV_PLAYBACK_PATH), - ALT_PATH1 WAV_PLAYBACK_PATH }; + ALT_PATH1 WAV_PLAYBACK_PATH }; systest_play_wav(PJ_ARRAY_SIZE(paths), paths); } static void systest_play_wav2(void) { const char *paths[] = { add_path(res_path, WAV_TOCK8_PATH), - ALT_PATH1 WAV_TOCK8_PATH}; + ALT_PATH1 WAV_TOCK8_PATH}; systest_play_wav(PJ_ARRAY_SIZE(paths), paths); } @@ -381,17 +380,17 @@ static void systest_rec_audio(void) ti = systest_alloc_test_item(title); if (!ti) - return; + return; key = gui_msgbox(title, - "This test will allow you to record audio " - "from the microphone, and playback the " - "audio to the speaker. Press OK to start recording, " - "CANCEL to skip.", - WITH_OKCANCEL); + "This test will allow you to record audio " + "from the microphone, and playback the " + "audio to the speaker. Press OK to start recording, " + "CANCEL to skip.", + WITH_OKCANCEL); if (key != KEY_OK) { - ti->skipped = PJ_TRUE; - return; + ti->skipped = PJ_TRUE; + return; } PJ_LOG(3,(THIS_FILE, "Running %s", title)); @@ -400,18 +399,18 @@ static void systest_rec_audio(void) status = pjsua_recorder_create(&filename, 0, NULL, -1, 0, &rec_id); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; rec_slot = pjsua_recorder_get_conf_port(rec_id); status = pjsua_conf_connect(0, rec_slot); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; key = gui_msgbox(title, - "Recording is in progress now, please say " - "something in the microphone. Press OK " - "to stop recording", WITH_OK); + "Recording is in progress now, please say " + "something in the microphone. Press OK " + "to stop recording", WITH_OK); pjsua_conf_disconnect(0, rec_slot); rec_slot = PJSUA_INVALID_ID; @@ -420,50 +419,50 @@ static void systest_rec_audio(void) status = pjsua_player_create(&filename, 0, &play_id); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; play_slot = pjsua_player_get_conf_port(play_id); status = pjsua_conf_connect(play_slot, 0); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; key = gui_msgbox(title, - "Recording has been stopped. " - "The recorded audio is being played now to " - "the speaker device, in a loop. Listen for " - "any audio impairments. Press OK to stop.", - WITH_OK); + "Recording has been stopped. " + "The recorded audio is being played now to " + "the speaker device, in a loop. Listen for " + "any audio impairments. Press OK to stop.", + WITH_OK); on_return: if (rec_slot != PJSUA_INVALID_ID) - pjsua_conf_disconnect(0, rec_slot); + pjsua_conf_disconnect(0, rec_slot); if (rec_id != PJSUA_INVALID_ID) - pjsua_recorder_destroy(rec_id); + pjsua_recorder_destroy(rec_id); if (play_slot != PJSUA_INVALID_ID) - pjsua_conf_disconnect(play_slot, 0); + pjsua_conf_disconnect(play_slot, 0); if (play_id != PJSUA_INVALID_ID) - pjsua_player_destroy(play_id); + pjsua_player_destroy(play_id); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); if (status != PJ_SUCCESS) { - systest_perror("Sorry we encountered an error: ", status); - ti->success = PJ_FALSE; - pj_strerror(status, ti->reason, sizeof(ti->reason)); + systest_perror("Sorry we encountered an error: ", status); + ti->success = PJ_FALSE; + pj_strerror(status, ti->reason, sizeof(ti->reason)); } else { - key = gui_msgbox(title, "Is the audio okay?", WITH_YESNO); - ti->success = (key == KEY_YES); - if (!ti->success) { - pj_ansi_snprintf(textbuf, sizeof(textbuf), - "You will probably need to copy the recorded " - "WAV file %s to a desktop computer and analyze " - "it, to find out whether it's a recording " - "or playback problem.", - WAV_REC_OUT_PATH); - gui_msgbox(title, textbuf, WITH_OK); - pj_ansi_strcpy(ti->reason, USER_ERROR); - } + key = gui_msgbox(title, "Is the audio okay?", WITH_YESNO); + ti->success = (key == KEY_YES); + if (!ti->success) { + pj_ansi_snprintf(textbuf, sizeof(textbuf), + "You will probably need to copy the recorded " + "WAV file %s to a desktop computer and analyze " + "it, to find out whether it's a recording " + "or playback problem.", + WAV_REC_OUT_PATH); + gui_msgbox(title, textbuf, WITH_OK); + pj_ansi_strcpy(ti->reason, USER_ERROR); + } } } @@ -474,7 +473,7 @@ static void systest_rec_audio(void) static void systest_audio_test(void) { enum { - GOOD_MAX_INTERVAL = 5, + GOOD_MAX_INTERVAL = 5, }; const pjmedia_dir dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; pjmedia_aud_param param; @@ -490,18 +489,18 @@ static void systest_audio_test(void) ti = systest_alloc_test_item(title); if (!ti) - return; + return; key = gui_msgbox(title, - "This will run an automated test for about " - "ten seconds or so, and display some " - "statistics about your sound device. " - "Please don't do anything until the test completes. " - "Press OK to start, or CANCEL to skip this test.", - WITH_OKCANCEL); + "This will run an automated test for about " + "ten seconds or so, and display some " + "statistics about your sound device. " + "Please don't do anything until the test completes. " + "Press OK to start, or CANCEL to skip this test.", + WITH_OKCANCEL); if (key != KEY_OK) { - ti->skipped = PJ_TRUE; - return; + ti->skipped = PJ_TRUE; + return; } PJ_LOG(3,(THIS_FILE, "Running %s", title)); @@ -512,12 +511,12 @@ static void systest_audio_test(void) /* Setup parameters */ status = pjmedia_aud_dev_default_param(systest.play_id, ¶m); if (status != PJ_SUCCESS) { - systest_perror("Sorry we had error in pjmedia_aud_dev_default_param()", status); - pjsua_set_snd_dev(systest.rec_id, systest.play_id); - ti->success = PJ_FALSE; - pj_strerror(status, ti->reason, sizeof(ti->reason)); - ti->reason[sizeof(ti->reason)-1] = '\0'; - return; + systest_perror("Sorry we had error in pjmedia_aud_dev_default_param()", status); + pjsua_set_snd_dev(systest.rec_id, systest.play_id); + ti->success = PJ_FALSE; + pj_strerror(status, ti->reason, sizeof(ti->reason)); + ti->reason[sizeof(ti->reason)-1] = '\0'; + return; } param.dir = dir; @@ -526,23 +525,23 @@ static void systest_audio_test(void) param.clock_rate = systest.media_cfg.snd_clock_rate; param.channel_count = systest.media_cfg.channel_count; param.samples_per_frame = param.clock_rate * param.channel_count * - systest.media_cfg.audio_frame_ptime / 1000; + systest.media_cfg.audio_frame_ptime / 1000; /* Latency settings */ param.flags |= (PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY); + PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY); param.input_latency_ms = systest.media_cfg.snd_rec_latency; param.output_latency_ms = systest.media_cfg.snd_play_latency; /* Run the test */ status = pjmedia_aud_test(¶m, &result); if (status != PJ_SUCCESS) { - systest_perror("Sorry we encountered error with the test", status); - pjsua_set_snd_dev(systest.rec_id, systest.play_id); - ti->success = PJ_FALSE; - pj_strerror(status, ti->reason, sizeof(ti->reason)); - ti->reason[sizeof(ti->reason)-1] = '\0'; - return; + systest_perror("Sorry we encountered error with the test", status); + pjsua_set_snd_dev(systest.rec_id, systest.play_id); + ti->success = PJ_FALSE; + pj_strerror(status, ti->reason, sizeof(ti->reason)); + ti->reason[sizeof(ti->reason)-1] = '\0'; + return; } /* Restore pjsua sound device */ @@ -553,90 +552,90 @@ static void systest_audio_test(void) textbufpos = strlen(textbuf); if (result.rec.frame_cnt==0) { - problems[problem_count++] = - "No audio frames were captured from the microphone. " - "This means the audio device is not working properly."; + problems[problem_count++] = + "No audio frames were captured from the microphone. " + "This means the audio device is not working properly."; } else { - pj_ansi_snprintf(textbuf+textbufpos, - sizeof(textbuf)-textbufpos, - "Rec : interval (min/max/avg/dev)=\r\n" - " %u/%u/%u/%u (ms)\r\n" - " max burst=%u\r\n", - result.rec.min_interval, - result.rec.max_interval, - result.rec.avg_interval, - result.rec.dev_interval, - result.rec.max_burst); - textbufpos = strlen(textbuf); - - if (result.rec.max_burst > GOOD_MAX_INTERVAL) { - problems[problem_count++] = - "Recording max burst is quite high"; - } + pj_ansi_snprintf(textbuf+textbufpos, + sizeof(textbuf)-textbufpos, + "Rec : interval (min/max/avg/dev)=\r\n" + " %u/%u/%u/%u (ms)\r\n" + " max burst=%u\r\n", + result.rec.min_interval, + result.rec.max_interval, + result.rec.avg_interval, + result.rec.dev_interval, + result.rec.max_burst); + textbufpos = strlen(textbuf); + + if (result.rec.max_burst > GOOD_MAX_INTERVAL) { + problems[problem_count++] = + "Recording max burst is quite high"; + } } if (result.play.frame_cnt==0) { - problems[problem_count++] = - "No audio frames were played to the speaker. " - "This means the audio device is not working properly."; + problems[problem_count++] = + "No audio frames were played to the speaker. " + "This means the audio device is not working properly."; } else { - pj_ansi_snprintf(textbuf+textbufpos, - sizeof(textbuf)-textbufpos, - "Play: interval (min/max/avg/dev)=\r\n" - " %u/%u/%u/%u (ms)\r\n" - " burst=%u\r\n", - result.play.min_interval, - result.play.max_interval, - result.play.avg_interval, - result.play.dev_interval, - result.play.max_burst); - textbufpos = strlen(textbuf); - - if (result.play.max_burst > GOOD_MAX_INTERVAL) { - problems[problem_count++] = - "Playback max burst is quite high"; - } + pj_ansi_snprintf(textbuf+textbufpos, + sizeof(textbuf)-textbufpos, + "Play: interval (min/max/avg/dev)=\r\n" + " %u/%u/%u/%u (ms)\r\n" + " burst=%u\r\n", + result.play.min_interval, + result.play.max_interval, + result.play.avg_interval, + result.play.dev_interval, + result.play.max_burst); + textbufpos = strlen(textbuf); + + if (result.play.max_burst > GOOD_MAX_INTERVAL) { + problems[problem_count++] = + "Playback max burst is quite high"; + } } if (result.rec_drift_per_sec) { - const char *which = result.rec_drift_per_sec>=0 ? "faster" : "slower"; - unsigned drift = result.rec_drift_per_sec>=0 ? - result.rec_drift_per_sec : - -result.rec_drift_per_sec; - - pj_ansi_snprintf(drifttext, sizeof(drifttext), - "Clock drifts detected. Capture " - "is %d samples/sec %s " - "than the playback device", - drift, which); - problems[problem_count++] = drifttext; + const char *which = result.rec_drift_per_sec>=0 ? "faster" : "slower"; + unsigned drift = result.rec_drift_per_sec>=0 ? + result.rec_drift_per_sec : + -result.rec_drift_per_sec; + + pj_ansi_snprintf(drifttext, sizeof(drifttext), + "Clock drifts detected. Capture " + "is %d samples/sec %s " + "than the playback device", + drift, which); + problems[problem_count++] = drifttext; } if (problem_count == 0) { - pj_ansi_snprintf(textbuf+textbufpos, - sizeof(textbuf)-textbufpos, - "\r\nThe sound device seems to be okay!"); - textbufpos = strlen(textbuf); + pj_ansi_snprintf(textbuf+textbufpos, + sizeof(textbuf)-textbufpos, + "\r\nThe sound device seems to be okay!"); + textbufpos = strlen(textbuf); - key = gui_msgbox("Audio Device Test", textbuf, WITH_OK); + key = gui_msgbox("Audio Device Test", textbuf, WITH_OK); } else { - unsigned i; - - pj_ansi_snprintf(textbuf+textbufpos, - sizeof(textbuf)-textbufpos, - "There could be %d problem(s) with the " - "sound device:\r\n", - problem_count); - textbufpos = strlen(textbuf); - - for (i=0; isuccess = PJ_TRUE; @@ -649,8 +648,8 @@ static void systest_audio_test(void) * sound latency test */ static int calculate_latency(pj_pool_t *pool, pjmedia_port *wav, - unsigned *lat_sum, unsigned *lat_cnt, - unsigned *lat_min, unsigned *lat_max) + unsigned *lat_sum, unsigned *lat_cnt, + unsigned *lat_min, unsigned *lat_max) { pjmedia_frame frm; short *buf; @@ -675,17 +674,17 @@ static int calculate_latency(pj_pool_t *pool, pjmedia_port *wav, /* Read the whole file */ read = 0; while (read < len/2) { - status = pjmedia_port_get_frame(wav, &frm); - if (status != PJ_SUCCESS) - break; + status = pjmedia_port_get_frame(wav, &frm); + if (status != PJ_SUCCESS) + break; - pjmedia_copy_samples(buf+read, (short*)frm.buf, samples_per_frame); - read += samples_per_frame; + pjmedia_copy_samples(buf+read, (short*)frm.buf, samples_per_frame); + read += samples_per_frame; } if (read < 2 * clock_rate) { - systest_perror("The WAV file is too short", PJ_SUCCESS); - return -1; + systest_perror("The WAV file is too short", PJ_SUCCESS); + return -1; } /* Zero the first 500ms to remove loud click noises @@ -697,56 +696,56 @@ static int calculate_latency(pj_pool_t *pool, pjmedia_port *wav, start_pos = 0; first = PJ_TRUE; while (start_pos < len/2 - clock_rate) { - int max_signal = 0; - unsigned max_signal_pos = start_pos; - unsigned max_echo_pos = 0; - unsigned pos; - unsigned lat; - - /* Get the largest signal in the next 0.7s */ - for (i=start_pos; i max_signal) { - max_signal = abs(buf[i]); - max_signal_pos = i; - } - } - - /* Advance 10ms from max_signal_pos */ - pos = max_signal_pos + 10 * clock_rate / 1000; - - /* Get the largest signal in the next 800ms */ - max_signal = 0; - max_echo_pos = pos; - for (i=pos; i max_signal) { - max_signal = abs(buf[i]); - max_echo_pos = i; - } - } - - lat = (max_echo_pos - max_signal_pos) * 1000 / clock_rate; + int max_signal = 0; + unsigned max_signal_pos = start_pos; + unsigned max_echo_pos = 0; + unsigned pos; + unsigned lat; + + /* Get the largest signal in the next 0.7s */ + for (i=start_pos; i max_signal) { + max_signal = abs(buf[i]); + max_signal_pos = i; + } + } + + /* Advance 10ms from max_signal_pos */ + pos = max_signal_pos + 10 * clock_rate / 1000; + + /* Get the largest signal in the next 800ms */ + max_signal = 0; + max_echo_pos = pos; + for (i=pos; i max_signal) { + max_signal = abs(buf[i]); + max_echo_pos = i; + } + } + + lat = (max_echo_pos - max_signal_pos) * 1000 / clock_rate; #if 0 - PJ_LOG(4,(THIS_FILE, "Signal at %dms, echo at %d ms, latency %d ms", - max_signal_pos * 1000 / clock_rate, - max_echo_pos * 1000 / clock_rate, - lat)); + PJ_LOG(4,(THIS_FILE, "Signal at %dms, echo at %d ms, latency %d ms", + max_signal_pos * 1000 / clock_rate, + max_echo_pos * 1000 / clock_rate, + lat)); #endif - *lat_sum += lat; - (*lat_cnt)++; - if (lat < *lat_min) - *lat_min = lat; - if (lat > *lat_max) - *lat_max = lat; - - /* Advance next loop */ - if (first) { - start_pos = max_signal_pos + clock_rate * 9 / 10; - first = PJ_FALSE; - } else { - start_pos += clock_rate; - } + *lat_sum += lat; + (*lat_cnt)++; + if (lat < *lat_min) + *lat_min = lat; + if (lat > *lat_max) + *lat_max = lat; + + /* Advance next loop */ + if (first) { + start_pos = max_signal_pos + clock_rate * 9 / 10; + first = PJ_FALSE; + } else { + start_pos += clock_rate; + } } return 0; @@ -771,43 +770,43 @@ static void systest_latency_test(void) ti = systest_alloc_test_item(title); if (!ti) - return; + return; key = gui_msgbox(title, - "This test will try to find the audio device's " - "latency. We will play a special WAV file to the " - "speaker for ten seconds, then at the end " - "calculate the latency. Please don't do anything " - "until the test is done.", WITH_OKCANCEL); + "This test will try to find the audio device's " + "latency. We will play a special WAV file to the " + "speaker for ten seconds, then at the end " + "calculate the latency. Please don't do anything " + "until the test is done.", WITH_OKCANCEL); if (key != KEY_OK) { - ti->skipped = PJ_TRUE; - return; + ti->skipped = PJ_TRUE; + return; } key = gui_msgbox(title, - "For this test to work, we must be able to capture " - "the audio played in the speaker (the echo), and only" - " that audio (i.e. you must be in relatively quiet " - "place to run this test). " - "Press OK to start, or CANCEL to skip.", - WITH_OKCANCEL); + "For this test to work, we must be able to capture " + "the audio played in the speaker (the echo), and only" + " that audio (i.e. you must be in relatively quiet " + "place to run this test). " + "Press OK to start, or CANCEL to skip.", + WITH_OKCANCEL); if (key != KEY_OK) { - ti->skipped = PJ_TRUE; - return; + ti->skipped = PJ_TRUE; + return; } PJ_LOG(3,(THIS_FILE, "Running %s", title)); status = create_player(PJ_ARRAY_SIZE(ref_wav_paths), ref_wav_paths, - &play_id); + &play_id); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; play_slot = pjsua_player_get_conf_port(play_id); rec_wav_file = pj_str(add_path(doc_path, WAV_LATENCY_OUT_PATH)); status = pjsua_recorder_create(&rec_wav_file, 0, NULL, -1, 0, &rec_id); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; rec_slot = pjsua_recorder_get_conf_port(rec_id); @@ -836,88 +835,88 @@ static void systest_latency_test(void) /* Confirm that echo is heard */ gui_msgbox(title, - "Test is done. Now we need to confirm that we indeed " - "captured the echo. We will play the captured audio " - "and please confirm that you can hear the 'tock' echo.", - WITH_OK); + "Test is done. Now we need to confirm that we indeed " + "captured the echo. We will play the captured audio " + "and please confirm that you can hear the 'tock' echo.", + WITH_OK); status = pjsua_player_create(&rec_wav_file, 0, &play_id); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; play_slot = pjsua_player_get_conf_port(play_id); status = pjsua_conf_connect(play_slot, 0); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; key = gui_msgbox(title, - "The captured audio is being played back now. " - "Can you hear the 'tock' echo?", - WITH_YESNO); + "The captured audio is being played back now. " + "Can you hear the 'tock' echo?", + WITH_YESNO); pjsua_player_destroy(play_id); play_id = PJSUA_INVALID_ID; if (key != KEY_YES) - goto on_return; + goto on_return; /* Now analyze the latency */ pool = pjsua_pool_create("latency", 512, 512); status = pjmedia_wav_player_port_create(pool, rec_wav_file.ptr, 0, 0, 0, &wav_port); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; status = calculate_latency(pool, wav_port, &lat_sum, &lat_cnt, - &lat_min, &lat_max); + &lat_min, &lat_max); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; on_return: if (wav_port) - pjmedia_port_destroy(wav_port); + pjmedia_port_destroy(wav_port); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); if (play_id != PJSUA_INVALID_ID) - pjsua_player_destroy(play_id); + pjsua_player_destroy(play_id); if (rec_id != PJSUA_INVALID_ID) - pjsua_recorder_destroy(rec_id); + pjsua_recorder_destroy(rec_id); if (status != PJ_SUCCESS) { - systest_perror("Sorry we encountered an error: ", status); - ti->success = PJ_FALSE; - pj_strerror(status, ti->reason, sizeof(ti->reason)); + systest_perror("Sorry we encountered an error: ", status); + ti->success = PJ_FALSE; + pj_strerror(status, ti->reason, sizeof(ti->reason)); } else if (key != KEY_YES) { - ti->success = PJ_FALSE; - if (!ti->success) { - pj_ansi_strcpy(ti->reason, USER_ERROR); - } + ti->success = PJ_FALSE; + if (!ti->success) { + pj_ansi_strcpy(ti->reason, USER_ERROR); + } } else { - char msg[200]; - pj_size_t msglen; - - pj_ansi_snprintf(msg, sizeof(msg), - "The sound device latency:\r\n" - " Min=%u, Max=%u, Avg=%u\r\n", - lat_min, lat_max, lat_sum/lat_cnt); - msglen = strlen(msg); - - if (lat_sum/lat_cnt > 500) { - pj_ansi_snprintf(msg+msglen, sizeof(msg)-msglen, - "The latency is huge!\r\n"); - msglen = strlen(msg); - } else if (lat_sum/lat_cnt > 200) { - pj_ansi_snprintf(msg+msglen, sizeof(msg)-msglen, - "The latency is quite high\r\n"); - msglen = strlen(msg); - } - - key = gui_msgbox(title, msg, WITH_OK); - - ti->success = PJ_TRUE; - pj_ansi_strncpy(ti->reason, msg, sizeof(ti->reason)); - ti->reason[sizeof(ti->reason)-1] = '\0'; + char msg[200]; + pj_size_t msglen; + + pj_ansi_snprintf(msg, sizeof(msg), + "The sound device latency:\r\n" + " Min=%u, Max=%u, Avg=%u\r\n", + lat_min, lat_max, lat_sum/lat_cnt); + msglen = strlen(msg); + + if (lat_sum/lat_cnt > 500) { + pj_ansi_snprintf(msg+msglen, sizeof(msg)-msglen, + "The latency is huge!\r\n"); + msglen = strlen(msg); + } else if (lat_sum/lat_cnt > 200) { + pj_ansi_snprintf(msg+msglen, sizeof(msg)-msglen, + "The latency is quite high\r\n"); + msglen = strlen(msg); + } + + key = gui_msgbox(title, msg, WITH_OK); + + ti->success = PJ_TRUE; + pj_ansi_strncpy(ti->reason, msg, sizeof(ti->reason)); + ti->reason[sizeof(ti->reason)-1] = '\0'; } } @@ -925,7 +924,7 @@ static void systest_latency_test(void) static void systest_aec_test(void) { const char *ref_wav_paths[] = { add_path(res_path, WAV_PLAYBACK_PATH), - ALT_PATH1 WAV_PLAYBACK_PATH }; + ALT_PATH1 WAV_PLAYBACK_PATH }; pjsua_player_id player_id = PJSUA_INVALID_ID; pjsua_recorder_id writer_id = PJSUA_INVALID_ID; enum gui_key key; @@ -937,48 +936,48 @@ static void systest_aec_test(void) ti = systest_alloc_test_item(title); if (!ti) - return; + return; key = gui_msgbox(title, - "This test will try to find whether the AEC/AES " - "works good on this system. Test will play a file " - "while recording from mic. The recording will be " - "played back later so you can check if echo is there. " - "Press OK to start.", - WITH_OKCANCEL); + "This test will try to find whether the AEC/AES " + "works good on this system. Test will play a file " + "while recording from mic. The recording will be " + "played back later so you can check if echo is there. " + "Press OK to start.", + WITH_OKCANCEL); if (key != KEY_OK) { - ti->skipped = PJ_TRUE; - return; + ti->skipped = PJ_TRUE; + return; } /* Save current EC tail */ status = pjsua_get_ec_tail(&last_ec_tail); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Set EC tail setting to default */ status = pjsua_set_ec(PJSUA_DEFAULT_EC_TAIL_LEN, 0); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* * Create player and recorder */ status = create_player(PJ_ARRAY_SIZE(ref_wav_paths), ref_wav_paths, - &player_id); + &player_id); if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "Error opening WAV file %s", - WAV_PLAYBACK_PATH)); - goto on_return; + PJ_PERROR(1,(THIS_FILE, status, "Error opening WAV file %s", + WAV_PLAYBACK_PATH)); + goto on_return; } status = pjsua_recorder_create( pj_cstr(&tmp, add_path(doc_path, AEC_REC_PATH)), 0, 0, -1, 0, &writer_id); if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "Error writing WAV file %s", - AEC_REC_PATH)); - goto on_return; + PJ_PERROR(1,(THIS_FILE, status, "Error writing WAV file %s", + AEC_REC_PATH)); + goto on_return; } /* @@ -990,7 +989,7 @@ static void systest_aec_test(void) /* Wait user signal */ gui_msgbox(title, "AEC/AES test is running. Press OK to stop this test.", - WITH_OK); + WITH_OK); /* * Stop and close playback and recorder @@ -1009,55 +1008,55 @@ static void systest_aec_test(void) pj_cstr(&tmp, add_path(doc_path, AEC_REC_PATH)), 0, &player_id); if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "Error opening WAV file %s", AEC_REC_PATH)); - goto on_return; + PJ_PERROR(1,(THIS_FILE, status, "Error opening WAV file %s", AEC_REC_PATH)); + goto on_return; } pjsua_conf_connect(pjsua_player_get_conf_port(player_id), 0); /* Wait user signal */ gui_msgbox(title, "We are now playing the captured audio from the mic. " - "Check if echo (of the audio played back previously) is " - "present in the audio. The recording is stored in " - AEC_REC_PATH " for offline analysis. " - "Press OK to stop.", - WITH_OK); + "Check if echo (of the audio played back previously) is " + "present in the audio. The recording is stored in " + AEC_REC_PATH " for offline analysis. " + "Press OK to stop.", + WITH_OK); pjsua_conf_disconnect(pjsua_player_get_conf_port(player_id), 0); key = gui_msgbox(title, - "Did you notice any echo in the recording?", - WITH_YESNO); + "Did you notice any echo in the recording?", + WITH_YESNO); on_return: if (player_id != PJSUA_INVALID_ID) - pjsua_player_destroy(player_id); + pjsua_player_destroy(player_id); if (writer_id != PJSUA_INVALID_ID) - pjsua_recorder_destroy(writer_id); + pjsua_recorder_destroy(writer_id); /* Wait until sound device closed before restoring back EC tail setting */ while (pjsua_snd_is_active()) - pj_thread_sleep(10); + pj_thread_sleep(10); pjsua_set_ec(last_ec_tail, 0); if (status != PJ_SUCCESS) { - systest_perror("Sorry we encountered an error: ", status); - ti->success = PJ_FALSE; - pj_strerror(status, ti->reason, sizeof(ti->reason)); + systest_perror("Sorry we encountered an error: ", status); + ti->success = PJ_FALSE; + pj_strerror(status, ti->reason, sizeof(ti->reason)); } else if (key == KEY_YES) { - ti->success = PJ_FALSE; - if (!ti->success) { - pj_ansi_strcpy(ti->reason, USER_ERROR); - } + ti->success = PJ_FALSE; + if (!ti->success) { + pj_ansi_strcpy(ti->reason, USER_ERROR); + } } else { - char msg[200]; + char msg[200]; - pj_ansi_snprintf(msg, sizeof(msg), "Test succeeded.\r\n"); + pj_ansi_snprintf(msg, sizeof(msg), "Test succeeded.\r\n"); - ti->success = PJ_TRUE; - pj_ansi_strncpy(ti->reason, msg, sizeof(ti->reason)); - ti->reason[sizeof(ti->reason)-1] = '\0'; + ti->success = PJ_TRUE; + pj_ansi_strncpy(ti->reason, msg, sizeof(ti->reason)); + ti->reason[sizeof(ti->reason)-1] = '\0'; } } @@ -1076,39 +1075,39 @@ static void systest_list_audio_devs() ti = systest_alloc_test_item(title); if (!ti) - return; + return; PJ_LOG(3,(THIS_FILE, "Running %s", title)); dev_count = pjmedia_aud_dev_count(); if (dev_count == 0) { - key = gui_msgbox(title, - "No audio devices are found", WITH_OK); - ti->success = PJ_FALSE; - pj_ansi_strcpy(ti->reason, "No device found"); - return; + key = gui_msgbox(title, + "No audio devices are found", WITH_OK); + ti->success = PJ_FALSE; + pj_ansi_strcpy(ti->reason, "No device found"); + return; } pj_ansi_snprintf(ti->reason+len, sizeof(ti->reason)-len, - "Found %u devices\r\n", dev_count); + "Found %u devices\r\n", dev_count); len = strlen(ti->reason); for (i=0; isuccess = PJ_FALSE; - pj_strerror(status, ti->reason, sizeof(ti->reason)); - return; - } - - pj_ansi_snprintf(ti->reason+len, sizeof(ti->reason)-len, - " %2d: %s [%s] (%d/%d)\r\n", - i, info.driver, info.name, - info.input_count, info.output_count); - len = strlen(ti->reason); + pjmedia_aud_dev_info info; + + status = pjmedia_aud_dev_get_info(i, &info); + if (status != PJ_SUCCESS) { + systest_perror("Error retrieving device info: ", status); + ti->success = PJ_FALSE; + pj_strerror(status, ti->reason, sizeof(ti->reason)); + return; + } + + pj_ansi_snprintf(ti->reason+len, sizeof(ti->reason)-len, + " %2d: %s [%s] (%d/%d)\r\n", + i, info.driver, info.name, + info.input_count, info.output_count); + len = strlen(ti->reason); } ti->reason[len] = '\0'; @@ -1129,76 +1128,76 @@ static void systest_display_settings(void) ti = systest_alloc_test_item(title); if (!ti) - return; + return; PJ_LOG(3,(THIS_FILE, "Running %s", title)); pj_ansi_snprintf(textbuf+len, sizeof(textbuf)-len, "Version: %s\r\n", - pj_get_version()); + pj_get_version()); len = strlen(textbuf); pj_ansi_snprintf(textbuf+len, sizeof(textbuf)-len, "Test clock rate: %d\r\n", - systest.media_cfg.clock_rate); + systest.media_cfg.clock_rate); len = strlen(textbuf); pj_ansi_snprintf(textbuf+len, sizeof(textbuf)-len, "Device clock rate: %d\r\n", - systest.media_cfg.snd_clock_rate); + systest.media_cfg.snd_clock_rate); len = strlen(textbuf); pj_ansi_snprintf(textbuf+len, sizeof(textbuf)-len, "Aud frame ptime: %d\r\n", - systest.media_cfg.audio_frame_ptime); + systest.media_cfg.audio_frame_ptime); len = strlen(textbuf); pj_ansi_snprintf(textbuf+len, sizeof(textbuf)-len, "Channel count: %d\r\n", - systest.media_cfg.channel_count); + systest.media_cfg.channel_count); len = strlen(textbuf); pj_ansi_snprintf(textbuf+len, sizeof(textbuf)-len, "Audio switching: %s\r\n", - (PJMEDIA_CONF_USE_SWITCH_BOARD ? "Switchboard" : "Conf bridge")); + (PJMEDIA_CONF_USE_SWITCH_BOARD ? "Switchboard" : "Conf bridge")); len = strlen(textbuf); pj_ansi_snprintf(textbuf+len, sizeof(textbuf)-len, "Snd buff count: %d\r\n", - PJMEDIA_SOUND_BUFFER_COUNT); + PJMEDIA_SOUND_BUFFER_COUNT); len = strlen(textbuf); /* Capture device */ status = pjmedia_aud_dev_get_info(systest.rec_id, &di); if (status != PJ_SUCCESS) { - systest_perror("Error querying device info", status); - ti->success = PJ_FALSE; - pj_strerror(status, ti->reason, sizeof(ti->reason)); - return; + systest_perror("Error querying device info", status); + ti->success = PJ_FALSE; + pj_strerror(status, ti->reason, sizeof(ti->reason)); + return; } pj_ansi_snprintf(textbuf+len, sizeof(textbuf)-len, - "Rec dev : %d (%s) [%s]\r\n", - systest.rec_id, - di.name, - di.driver); + "Rec dev : %d (%s) [%s]\r\n", + systest.rec_id, + di.name, + di.driver); len = strlen(textbuf); pj_ansi_snprintf(textbuf+len, sizeof(textbuf)-len, - "Rec buf : %d msec\r\n", - systest.media_cfg.snd_rec_latency); + "Rec buf : %d msec\r\n", + systest.media_cfg.snd_rec_latency); len = strlen(textbuf); /* Playback device */ status = pjmedia_aud_dev_get_info(systest.play_id, &di); if (status != PJ_SUCCESS) { - systest_perror("Error querying device info", status); - return; + systest_perror("Error querying device info", status); + return; } pj_ansi_snprintf(textbuf+len, sizeof(textbuf)-len, - "Play dev: %d (%s) [%s]\r\n", - systest.play_id, - di.name, - di.driver); + "Play dev: %d (%s) [%s]\r\n", + systest.play_id, + di.name, + di.driver); len = strlen(textbuf); pj_ansi_snprintf(textbuf+len, sizeof(textbuf)-len, - "Play buf: %d msec\r\n", - systest.media_cfg.snd_play_latency); + "Play buf: %d msec\r\n", + systest.media_cfg.snd_play_latency); len = strlen(textbuf); ti->success = PJ_TRUE; @@ -1217,8 +1216,8 @@ int systest_init(void) status = pjsua_create(); if (status != PJ_SUCCESS) { - systest_perror("Sorry we've had error in pjsua_create(): ", status); - return status; + systest_perror("Sorry we've had error in pjsua_create(): ", status); + return status; } pjsua_logging_config_default(&log_cfg); @@ -1229,7 +1228,7 @@ int systest_init(void) systest.media_cfg.clock_rate = TEST_CLOCK_RATE; systest.media_cfg.snd_clock_rate = DEV_CLOCK_RATE; if (OVERRIDE_AUD_FRAME_PTIME) - systest.media_cfg.audio_frame_ptime = OVERRIDE_AUD_FRAME_PTIME; + systest.media_cfg.audio_frame_ptime = OVERRIDE_AUD_FRAME_PTIME; systest.media_cfg.channel_count = CHANNEL_COUNT; systest.rec_id = REC_DEV_ID; systest.play_id = PLAY_DEV_ID; @@ -1246,21 +1245,21 @@ int systest_init(void) status = pjsua_init(&systest.ua_cfg, &log_cfg, &systest.media_cfg); if (status != PJ_SUCCESS) { - pjsua_destroy(); - systest_perror("Sorry we've had error in pjsua_init(): ", status); - return status; + pjsua_destroy(); + systest_perror("Sorry we've had error in pjsua_init(): ", status); + return status; } status = pjsua_start(); if (status != PJ_SUCCESS) { - pjsua_destroy(); - systest_perror("Sorry we've had error in pjsua_start(): ", status); - return status; + pjsua_destroy(); + systest_perror("Sorry we've had error in pjsua_start(): ", status); + return status; } status = gui_init(&root_menu); if (status != 0) - goto on_return; + goto on_return; return 0; @@ -1310,11 +1309,11 @@ void systest_save_result(const char *filename) status = pj_file_open(NULL, filename, PJ_O_WRONLY | PJ_O_APPEND, &fd); if (status != PJ_SUCCESS) { - pj_ansi_snprintf(textbuf, sizeof(textbuf), - "Error opening file %s", - filename); - systest_perror(textbuf, status); - return; + pj_ansi_snprintf(textbuf, sizeof(textbuf), + "Error opening file %s", + filename); + systest_perror(textbuf, status); + return; } text = "\r\n\r\nPJSYSTEST Report\r\n"; @@ -1324,46 +1323,46 @@ void systest_save_result(const char *filename) /* Put timestamp */ pj_gettimeofday(&tv); if (pj_time_decode(&tv, &pt) == PJ_SUCCESS) { - pj_ansi_snprintf(textbuf, sizeof(textbuf), - "Time: %04d/%02d/%02d %02d:%02d:%02d\r\n", - pt.year, pt.mon+1, pt.day, - pt.hour, pt.min, pt.sec); - size = strlen(textbuf); - pj_file_write(fd, textbuf, &size); + pj_ansi_snprintf(textbuf, sizeof(textbuf), + "Time: %04d/%02d/%02d %02d:%02d:%02d\r\n", + pt.year, pt.mon+1, pt.day, + pt.hour, pt.min, pt.sec); + size = strlen(textbuf); + pj_file_write(fd, textbuf, &size); } pj_ansi_snprintf(textbuf, sizeof(textbuf), - "Tests invoked: %u\r\n" - "-----------------------------------------------\r\n", - test_item_count); + "Tests invoked: %u\r\n" + "-----------------------------------------------\r\n", + test_item_count); size = strlen(textbuf); pj_file_write(fd, textbuf, &size); for (i=0; ititle, - (ti->skipped? "Skipped" : (ti->success ? "Success" : "Failed"))); - PJ_CHECK_TRUNC_STR(len, textbuf, sizeof(textbuf)); - size = strlen(textbuf); - pj_file_write(fd, textbuf, &size); + len = pj_ansi_snprintf(textbuf, sizeof(textbuf), + "\r\nTEST %d: %s %s\r\n", + i, ti->title, + (ti->skipped? "Skipped" : (ti->success ? "Success" : "Failed"))); + PJ_CHECK_TRUNC_STR(len, textbuf, sizeof(textbuf)); + size = strlen(textbuf); + pj_file_write(fd, textbuf, &size); - size = strlen(ti->reason); - pj_file_write(fd, ti->reason, &size); + size = strlen(ti->reason); + pj_file_write(fd, ti->reason, &size); - size = 2; - pj_file_write(fd, "\r\n", &size); + size = 2; + pj_file_write(fd, "\r\n", &size); } pj_file_close(fd); pj_ansi_snprintf(textbuf, sizeof(textbuf), - "Test result successfully appended to file %s", - filename); + "Test result successfully appended to file %s", + filename); gui_msgbox("Test result saved", textbuf, WITH_OK); } diff --git a/pjsip-apps/src/pjsystest/systest.h b/pjsip-apps/src/pjsystest/systest.h index 5fe792adb6..002acb28dc 100644 --- a/pjsip-apps/src/pjsystest/systest.h +++ b/pjsip-apps/src/pjsystest/systest.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -24,46 +23,46 @@ /* * Overrideable parameters */ -#define REC_DEV_ID systest_cap_dev_id -#define PLAY_DEV_ID systest_play_dev_id -//#define REC_DEV_ID 5 -//#define PLAY_DEV_ID 5 -#define OVERRIDE_AUDDEV_REC_LAT 0 -#define OVERRIDE_AUDDEV_PLAY_LAT 0 -#define OVERRIDE_AUD_FRAME_PTIME 0 +#define REC_DEV_ID systest_cap_dev_id +#define PLAY_DEV_ID systest_play_dev_id +//#define REC_DEV_ID 5 +//#define PLAY_DEV_ID 5 +#define OVERRIDE_AUDDEV_REC_LAT 0 +#define OVERRIDE_AUDDEV_PLAY_LAT 0 +#define OVERRIDE_AUD_FRAME_PTIME 0 /* Don't change this */ -#define CHANNEL_COUNT 1 +#define CHANNEL_COUNT 1 /* If you change CLOCK_RATE then the input WAV files need to be * changed, so normally don't need to change this. */ -#define TEST_CLOCK_RATE 8000 +#define TEST_CLOCK_RATE 8000 /* You may change sound device's clock rate as long as resampling * is enabled. */ -#define DEV_CLOCK_RATE 8000 +#define DEV_CLOCK_RATE 8000 #if defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE - #define LOG_OUT_PATH "\\PJSYSTEST.TXT" - #define RESULT_OUT_PATH "\\PJSYSTEST_RESULT.TXT" - #define WAV_PLAYBACK_PATH "\\Program Files\\pjsystest\\input.8.wav" - #define WAV_REC_OUT_PATH "\\PJSYSTEST_TESTREC.WAV" - #define WAV_TOCK8_PATH "\\Program Files\\pjsystest\\tock8.WAV" - #define WAV_LATENCY_OUT_PATH "\\PJSYSTEST_LATREC.WAV" - #define ALT_PATH1 "" - #define AEC_REC_PATH "\\PJSYSTEST_AECREC.WAV" + #define LOG_OUT_PATH "\\PJSYSTEST.TXT" + #define RESULT_OUT_PATH "\\PJSYSTEST_RESULT.TXT" + #define WAV_PLAYBACK_PATH "\\Program Files\\pjsystest\\input.8.wav" + #define WAV_REC_OUT_PATH "\\PJSYSTEST_TESTREC.WAV" + #define WAV_TOCK8_PATH "\\Program Files\\pjsystest\\tock8.WAV" + #define WAV_LATENCY_OUT_PATH "\\PJSYSTEST_LATREC.WAV" + #define ALT_PATH1 "" + #define AEC_REC_PATH "\\PJSYSTEST_AECREC.WAV" #else - #define LOG_OUT_PATH "PJSYSTEST.TXT" - #define RESULT_OUT_PATH "PJSYSTEST_RESULT.TXT" - #define WAV_PLAYBACK_PATH "input.8.wav" - #define WAV_REC_OUT_PATH "PJSYSTEST_TESTREC.WAV" - #define WAV_TOCK8_PATH "tock8.wav" - #define WAV_LATENCY_OUT_PATH "PJSYSTEST_LATREC.WAV" - #define ALT_PATH1 "../../tests/pjsua/wavs/" - #define AEC_REC_PATH "PJSYSTEST_AECREC.WAV" + #define LOG_OUT_PATH "PJSYSTEST.TXT" + #define RESULT_OUT_PATH "PJSYSTEST_RESULT.TXT" + #define WAV_PLAYBACK_PATH "input.8.wav" + #define WAV_REC_OUT_PATH "PJSYSTEST_TESTREC.WAV" + #define WAV_TOCK8_PATH "tock8.wav" + #define WAV_LATENCY_OUT_PATH "PJSYSTEST_LATREC.WAV" + #define ALT_PATH1 "../../tests/pjsua/wavs/" + #define AEC_REC_PATH "PJSYSTEST_AECREC.WAV" #endif #ifdef __cplusplus @@ -71,11 +70,11 @@ extern "C" { #endif /* API, to be called by main() */ -int systest_init(void); -int systest_set_dev(int cap_dev, int play_dev); -int systest_run(void); -void systest_save_result(const char *filename); -void systest_deinit(void); +int systest_init(void); +int systest_set_dev(int cap_dev, int play_dev); +int systest_run(void); +void systest_save_result(const char *filename); +void systest_deinit(void); /* Device ID to test */ extern int systest_cap_dev_id; @@ -84,18 +83,18 @@ extern int systest_play_dev_id; /* Test item is used to record the test result */ typedef struct test_item_t { - char title[80]; - pj_bool_t skipped; - pj_bool_t success; - char reason[1024]; + char title[80]; + pj_bool_t skipped; + pj_bool_t success; + char reason[1024]; } test_item_t; #define SYSTEST_MAX_TEST 32 -extern unsigned test_item_count; +extern unsigned test_item_count; extern test_item_t test_items[SYSTEST_MAX_TEST]; -#define PATH_LENGTH PJ_MAXPATH -extern char doc_path[PATH_LENGTH]; -extern char res_path[PATH_LENGTH]; +#define PATH_LENGTH PJ_MAXPATH +extern char doc_path[PATH_LENGTH]; +extern char res_path[PATH_LENGTH]; test_item_t *systest_alloc_test_item(const char *title); @@ -103,4 +102,4 @@ test_item_t *systest_alloc_test_item(const char *title); } #endif -#endif /* __SYSTEST_H__ */ +#endif /* __SYSTEST_H__ */ diff --git a/pjsip-apps/src/py_pjsua/pjsua_app.py b/pjsip-apps/src/py_pjsua/pjsua_app.py index d8e208a933..ec6cb3f6f2 100644 --- a/pjsip-apps/src/py_pjsua/pjsua_app.py +++ b/pjsip-apps/src/py_pjsua/pjsua_app.py @@ -1,4 +1,3 @@ -# $Id$ # # Sample and simple Python script to make and receive calls, and do # presence and instant messaging/IM using PJSUA-API binding for Python. diff --git a/pjsip-apps/src/py_pjsua/py_pjsua.c b/pjsip-apps/src/py_pjsua/py_pjsua.c index 7ef55d8212..00cc9eeb01 100644 --- a/pjsip-apps/src/py_pjsua/py_pjsua.c +++ b/pjsip-apps/src/py_pjsua/py_pjsua.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,8 +28,8 @@ static PyObject* obj_log_cb; static long thread_id; -#define ENTER_PYTHON() PyGILState_STATE state = PyGILState_Ensure() -#define LEAVE_PYTHON() PyGILState_Release(state) +#define ENTER_PYTHON() PyGILState_STATE state = PyGILState_Ensure() +#define LEAVE_PYTHON() PyGILState_Release(state) /* * cb_log_cb @@ -38,23 +37,23 @@ static long thread_id; */ static void cb_log_cb(int level, const char *data, int len) { - + /* Ignore if this callback is called from alien thread context, * or otherwise it will crash Python. */ if (pj_thread_local_get(thread_id) == 0) - return; + return; if (PyCallable_Check(obj_log_cb)) { - ENTER_PYTHON(); + ENTER_PYTHON(); PyObject_CallFunctionObjArgs( obj_log_cb, Py_BuildValue("i",level), PyString_FromString(data), Py_BuildValue("i",len), NULL ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -73,24 +72,24 @@ static PyObj_pjsua_callback * g_obj_callback; static void cb_on_call_state(pjsua_call_id call_id, pjsip_event *e) { if (PyCallable_Check(g_obj_callback->on_call_state)) - { + { PyObj_pjsip_event * obj; - ENTER_PYTHON(); + ENTER_PYTHON(); - obj = (PyObj_pjsip_event *)PyType_GenericNew(&PyTyp_pjsip_event, - NULL, NULL); - - obj->event = e; - + obj = (PyObj_pjsip_event *)PyType_GenericNew(&PyTyp_pjsip_event, + NULL, NULL); + + obj->event = e; + PyObject_CallFunctionObjArgs( g_obj_callback->on_call_state, - Py_BuildValue("i",call_id), - obj, - NULL + Py_BuildValue("i",call_id), + obj, + NULL ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -104,23 +103,23 @@ static void cb_on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, { if (PyCallable_Check(g_obj_callback->on_incoming_call)) { - PyObj_pjsip_rx_data * obj; + PyObj_pjsip_rx_data * obj; - ENTER_PYTHON(); + ENTER_PYTHON(); - obj = (PyObj_pjsip_rx_data *)PyType_GenericNew(&PyTyp_pjsip_rx_data, - NULL, NULL); - obj->rdata = rdata; + obj = (PyObj_pjsip_rx_data *)PyType_GenericNew(&PyTyp_pjsip_rx_data, + NULL, NULL); + obj->rdata = rdata; PyObject_CallFunctionObjArgs( g_obj_callback->on_incoming_call, - Py_BuildValue("i",acc_id), + Py_BuildValue("i",acc_id), Py_BuildValue("i",call_id), - obj, - NULL + obj, + NULL ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -133,16 +132,16 @@ static void cb_on_call_media_state(pjsua_call_id call_id) { if (PyCallable_Check(g_obj_callback->on_call_media_state)) { - ENTER_PYTHON(); + ENTER_PYTHON(); PyObject_CallFunction( - g_obj_callback->on_call_media_state, - "i", - call_id, - NULL - ); + g_obj_callback->on_call_media_state, + "i", + call_id, + NULL + ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -155,20 +154,20 @@ static void cb_on_dtmf_digit(pjsua_call_id call_id, int digit) { if (PyCallable_Check(g_obj_callback->on_dtmf_digit)) { - char digit_str[10]; + char digit_str[10]; - ENTER_PYTHON(); + ENTER_PYTHON(); - pj_ansi_snprintf(digit_str, sizeof(digit_str), "%c", digit); + pj_ansi_snprintf(digit_str, sizeof(digit_str), "%c", digit); PyObject_CallFunctionObjArgs( - g_obj_callback->on_dtmf_digit, - Py_BuildValue("i",call_id), - PyString_FromString(digit_str), - NULL - ); + g_obj_callback->on_dtmf_digit, + Py_BuildValue("i",call_id), + PyString_FromString(digit_str), + NULL + ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -178,32 +177,32 @@ static void cb_on_dtmf_digit(pjsua_call_id call_id, int digit) * !modified @061206 */ static void cb_on_call_transfer_request(pjsua_call_id call_id, - const pj_str_t *dst, - pjsip_status_code *code) + const pj_str_t *dst, + pjsip_status_code *code) { if (PyCallable_Check(g_obj_callback->on_call_transfer_request)) { - PyObject * ret; - int cd; + PyObject * ret; + int cd; - ENTER_PYTHON(); + ENTER_PYTHON(); ret = PyObject_CallFunctionObjArgs( g_obj_callback->on_call_transfer_request, - Py_BuildValue("i",call_id), + Py_BuildValue("i",call_id), PyString_FromStringAndSize(dst->ptr, dst->slen), Py_BuildValue("i",*code), - NULL + NULL ); - if (ret != NULL) { - if (ret != Py_None) { - if (PyArg_Parse(ret,"i",&cd)) { - *code = cd; - } - } - } - - LEAVE_PYTHON(); + if (ret != NULL) { + if (ret != Py_None) { + if (PyArg_Parse(ret,"i",&cd)) { + *code = cd; + } + } + } + + LEAVE_PYTHON(); } } @@ -216,36 +215,36 @@ static void cb_on_call_transfer_request(pjsua_call_id call_id, * !modified @061206 */ static void cb_on_call_transfer_status( pjsua_call_id call_id, - int status_code, - const pj_str_t *status_text, - pj_bool_t final, - pj_bool_t *p_cont) + int status_code, + const pj_str_t *status_text, + pj_bool_t final, + pj_bool_t *p_cont) { if (PyCallable_Check(g_obj_callback->on_call_transfer_status)) { - PyObject * ret; - int cnt; + PyObject * ret; + int cnt; - ENTER_PYTHON(); + ENTER_PYTHON(); ret = PyObject_CallFunctionObjArgs( g_obj_callback->on_call_transfer_status, - Py_BuildValue("i",call_id), - Py_BuildValue("i",status_code), + Py_BuildValue("i",call_id), + Py_BuildValue("i",status_code), PyString_FromStringAndSize(status_text->ptr, status_text->slen), - Py_BuildValue("i",final), + Py_BuildValue("i",final), Py_BuildValue("i",*p_cont), - NULL + NULL ); - if (ret != NULL) { - if (ret != Py_None) { - if (PyArg_Parse(ret,"i",&cnt)) { - *p_cont = cnt; - } - } - } - - LEAVE_PYTHON(); + if (ret != NULL) { + if (ret != Py_None) { + if (PyArg_Parse(ret,"i",&cnt)) { + *p_cont = cnt; + } + } + } + + LEAVE_PYTHON(); } } @@ -256,42 +255,42 @@ static void cb_on_call_transfer_status( pjsua_call_id call_id, * !modified @061206 */ static void cb_on_call_replace_request( pjsua_call_id call_id, - pjsip_rx_data *rdata, - int *st_code, - pj_str_t *st_text) + pjsip_rx_data *rdata, + int *st_code, + pj_str_t *st_text) { if (PyCallable_Check(g_obj_callback->on_call_replace_request)) { - PyObject * ret; - PyObject * txt; - int cd; + PyObject * ret; + PyObject * txt; + int cd; PyObj_pjsip_rx_data * obj; - ENTER_PYTHON(); + ENTER_PYTHON(); - obj = (PyObj_pjsip_rx_data *)PyType_GenericNew(&PyTyp_pjsip_rx_data, - NULL, NULL); + obj = (PyObj_pjsip_rx_data *)PyType_GenericNew(&PyTyp_pjsip_rx_data, + NULL, NULL); obj->rdata = rdata; ret = PyObject_CallFunctionObjArgs( g_obj_callback->on_call_replace_request, - Py_BuildValue("i",call_id), - obj, - Py_BuildValue("i",*st_code), + Py_BuildValue("i",call_id), + obj, + Py_BuildValue("i",*st_code), PyString_FromStringAndSize(st_text->ptr, st_text->slen), - NULL + NULL ); - if (ret != NULL) { - if (ret != Py_None) { - if (PyArg_ParseTuple(ret,"iO",&cd, &txt)) { - *st_code = cd; - st_text->ptr = PyString_AsString(txt); - st_text->slen = strlen(PyString_AsString(txt)); - } - } - } - - LEAVE_PYTHON(); + if (ret != NULL) { + if (ret != Py_None) { + if (PyArg_ParseTuple(ret,"iO",&cd, &txt)) { + *st_code = cd; + st_text->ptr = PyString_AsString(txt); + st_text->slen = strlen(PyString_AsString(txt)); + } + } + } + + LEAVE_PYTHON(); } } @@ -302,20 +301,20 @@ static void cb_on_call_replace_request( pjsua_call_id call_id, * request with Replaces header. */ static void cb_on_call_replaced(pjsua_call_id old_call_id, - pjsua_call_id new_call_id) + pjsua_call_id new_call_id) { if (PyCallable_Check(g_obj_callback->on_call_replaced)) { - ENTER_PYTHON(); + ENTER_PYTHON(); PyObject_CallFunctionObjArgs( g_obj_callback->on_call_replaced, - Py_BuildValue("i",old_call_id), - Py_BuildValue("i",new_call_id), - NULL + Py_BuildValue("i",old_call_id), + Py_BuildValue("i",new_call_id), + NULL ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -328,16 +327,16 @@ static void cb_on_reg_state(pjsua_acc_id acc_id) { if (PyCallable_Check(g_obj_callback->on_reg_state)) { - ENTER_PYTHON(); + ENTER_PYTHON(); PyObject_CallFunction( - g_obj_callback->on_reg_state, - "i", - acc_id, - NULL - ); + g_obj_callback->on_reg_state, + "i", + acc_id, + NULL + ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -350,16 +349,16 @@ static void cb_on_buddy_state(pjsua_buddy_id buddy_id) { if (PyCallable_Check(g_obj_callback->on_buddy_state)) { - ENTER_PYTHON(); + ENTER_PYTHON(); PyObject_CallFunction( - g_obj_callback->on_buddy_state, - "i", - buddy_id, - NULL - ); + g_obj_callback->on_buddy_state, + "i", + buddy_id, + NULL + ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -373,7 +372,7 @@ static void cb_on_pager(pjsua_call_id call_id, const pj_str_t *from, { if (PyCallable_Check(g_obj_callback->on_pager)) { - ENTER_PYTHON(); + ENTER_PYTHON(); PyObject_CallFunctionObjArgs( g_obj_callback->on_pager,Py_BuildValue("i",call_id), @@ -382,10 +381,10 @@ static void cb_on_pager(pjsua_call_id call_id, const pj_str_t *from, PyString_FromStringAndSize(contact->ptr, contact->slen), PyString_FromStringAndSize(mime_type->ptr, mime_type->slen), PyString_FromStringAndSize(body->ptr, body->slen), - NULL + NULL ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -401,24 +400,24 @@ static void cb_on_pager_status(pjsua_call_id call_id, const pj_str_t *to, { if (PyCallable_Check(g_obj_callback->on_pager)) { - PyObject * obj_user_data; + PyObject * obj_user_data; - ENTER_PYTHON(); + ENTER_PYTHON(); - obj_user_data = Py_BuildValue("i", user_data); + obj_user_data = Py_BuildValue("i", user_data); PyObject_CallFunctionObjArgs( g_obj_callback->on_pager_status, - Py_BuildValue("i",call_id), + Py_BuildValue("i",call_id), PyString_FromStringAndSize(to->ptr, to->slen), PyString_FromStringAndSize(body->ptr, body->slen), - obj_user_data, + obj_user_data, Py_BuildValue("i",status), - PyString_FromStringAndSize(reason->ptr,reason->slen), - NULL + PyString_FromStringAndSize(reason->ptr,reason->slen), + NULL ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -433,7 +432,7 @@ static void cb_on_typing(pjsua_call_id call_id, const pj_str_t *from, { if (PyCallable_Check(g_obj_callback->on_typing)) { - ENTER_PYTHON(); + ENTER_PYTHON(); PyObject_CallFunctionObjArgs( g_obj_callback->on_typing,Py_BuildValue("i",call_id), @@ -441,10 +440,10 @@ static void cb_on_typing(pjsua_call_id call_id, const pj_str_t *from, PyString_FromStringAndSize(to->ptr, to->slen), PyString_FromStringAndSize(contact->ptr, contact->slen), Py_BuildValue("i",is_typing), - NULL + NULL ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -460,31 +459,31 @@ void translate_hdr(pj_pool_t *pool, pjsip_hdr *hdr, PyObject *py_hdr_list) pj_list_init(hdr); if (PyList_Check(py_hdr_list)) { - int i; + int i; for (i = 0; i < PyList_Size(py_hdr_list); i++) - { + { pj_str_t hname, hvalue; - pjsip_generic_string_hdr * new_hdr; + pjsip_generic_string_hdr * new_hdr; PyObject * tuple = PyList_GetItem(py_hdr_list, i); if (PyTuple_Check(tuple)) - { + { hname.ptr = PyString_AsString(PyTuple_GetItem(tuple,0)); hname.slen = strlen(PyString_AsString - (PyTuple_GetItem(tuple,0))); + (PyTuple_GetItem(tuple,0))); hvalue.ptr = PyString_AsString(PyTuple_GetItem(tuple,1)); hvalue.slen = strlen(PyString_AsString - (PyTuple_GetItem(tuple,1))); + (PyTuple_GetItem(tuple,1))); } else { - hname.ptr = ""; - hname.slen = 0; - hvalue.ptr = ""; - hvalue.slen = 0; + hname.ptr = ""; + hname.slen = 0; + hvalue.ptr = ""; + hvalue.slen = 0; } new_hdr = pjsip_generic_string_hdr_create(pool, &hname, &hvalue); pj_list_push_back((pj_list_type *)hdr, (pj_list_type *)new_hdr); - } + } } } @@ -509,20 +508,20 @@ void translate_hdr_rev(pjsip_generic_string_hdr *hdr, PyObject *py_hdr_list) py_hdr_list = PyList_New(len); for (i = 0; i < len && p_hdr != NULL; i++) - { + { PyObject * tuple; PyObject * str; tuple = PyTuple_New(2); - + str = PyString_FromStringAndSize(p_hdr->name.ptr, p_hdr->name.slen); PyTuple_SetItem(tuple, 0, str); str = PyString_FromStringAndSize - (hdr->hvalue.ptr, p_hdr->hvalue.slen); + (hdr->hvalue.ptr, p_hdr->hvalue.slen); PyTuple_SetItem(tuple, 1, str); PyList_SetItem(py_hdr_list, i, tuple); p_hdr = p_hdr->next; - } + } } @@ -534,8 +533,8 @@ void translate_hdr_rev(pjsip_generic_string_hdr *hdr, PyObject *py_hdr_list) */ static PyObject *py_pjsua_thread_register(PyObject *pSelf, PyObject *pArgs) { - - pj_status_t status; + + pj_status_t status; const char *name; PyObject *py_desc; pj_thread_t *thread; @@ -557,10 +556,10 @@ static PyObject *py_pjsua_thread_register(PyObject *pSelf, PyObject *pArgs) td = (int *)malloc(size * sizeof(int)); for (i = 0; i < size; i++) { - if (!PyArg_Parse(PyList_GetItem(py_desc,i),"i", td[i])) - { - return NULL; - } + if (!PyArg_Parse(PyList_GetItem(py_desc,i),"i", td[i])) + { + return NULL; + } } thread_desc = td; #else @@ -569,7 +568,7 @@ static PyObject *py_pjsua_thread_register(PyObject *pSelf, PyObject *pArgs) status = pj_thread_register(name, thread_desc, &thread); if (status == PJ_SUCCESS) - status = pj_thread_local_set(thread_id, (void*)1); + status = pj_thread_local_set(thread_id, (void*)1); return Py_BuildValue("i",status); } @@ -580,7 +579,7 @@ static PyObject *py_pjsua_thread_register(PyObject *pSelf, PyObject *pArgs) static PyObject *py_pjsua_logging_config_default(PyObject *pSelf, PyObject *pArgs) { - PyObj_pjsua_logging_config *obj; + PyObj_pjsua_logging_config *obj; pjsua_logging_config cfg; PJ_UNUSED_ARG(pSelf); @@ -592,7 +591,7 @@ static PyObject *py_pjsua_logging_config_default(PyObject *pSelf, pjsua_logging_config_default(&cfg); obj = (PyObj_pjsua_logging_config *) PyObj_pjsua_logging_config_new - (&PyTyp_pjsua_logging_config,NULL,NULL); + (&PyTyp_pjsua_logging_config,NULL,NULL); PyObj_pjsua_logging_config_import(obj, &cfg); return (PyObject *)obj; @@ -640,7 +639,7 @@ static PyObject * py_pjsua_media_config_default(PyObject *pSelf, } pjsua_media_config_default(&cfg); obj = (PyObj_pjsua_media_config *) - PyType_GenericNew(&PyTyp_pjsua_media_config, NULL, NULL); + PyType_GenericNew(&PyTyp_pjsua_media_config, NULL, NULL); PyObj_pjsua_media_config_import(obj, &cfg); return (PyObject *)obj; } @@ -825,7 +824,7 @@ static PyObject *py_pjsua_perror(PyObject *pSelf, PyObject *pArgs) { return NULL; } - + pjsua_perror(sender, title, status); Py_INCREF(Py_None); return Py_None; @@ -849,9 +848,9 @@ static PyObject *py_pjsua_create(PyObject *pSelf, PyObject *pArgs) if (status == PJ_SUCCESS) { - status = pj_thread_local_alloc(&thread_id); - if (status == PJ_SUCCESS) - status = pj_thread_local_set(thread_id, (void*)1); + status = pj_thread_local_alloc(&thread_id); + if (status == PJ_SUCCESS) + status = pj_thread_local_set(thread_id, (void*)1); } return Py_BuildValue("i",status); @@ -882,26 +881,26 @@ static PyObject *py_pjsua_init(PyObject *pSelf, PyObject *pArgs) if (o_ua_cfg != Py_None) { - PyObj_pjsua_config *obj_ua_cfg = (PyObj_pjsua_config*)o_ua_cfg; + PyObj_pjsua_config *obj_ua_cfg = (PyObj_pjsua_config*)o_ua_cfg; - PyObj_pjsua_config_export(&cfg_ua, obj_ua_cfg); + PyObj_pjsua_config_export(&cfg_ua, obj_ua_cfg); - g_obj_callback = obj_ua_cfg->cb; - Py_INCREF(g_obj_callback); + g_obj_callback = obj_ua_cfg->cb; + Py_INCREF(g_obj_callback); - cfg_ua.cb.on_call_state = &cb_on_call_state; - cfg_ua.cb.on_incoming_call = &cb_on_incoming_call; - cfg_ua.cb.on_call_media_state = &cb_on_call_media_state; - cfg_ua.cb.on_dtmf_digit = &cb_on_dtmf_digit; - cfg_ua.cb.on_call_transfer_request = &cb_on_call_transfer_request; - cfg_ua.cb.on_call_transfer_status = &cb_on_call_transfer_status; - cfg_ua.cb.on_call_replace_request = &cb_on_call_replace_request; - cfg_ua.cb.on_call_replaced = &cb_on_call_replaced; - cfg_ua.cb.on_reg_state = &cb_on_reg_state; - cfg_ua.cb.on_buddy_state = &cb_on_buddy_state; - cfg_ua.cb.on_pager = &cb_on_pager; - cfg_ua.cb.on_pager_status = &cb_on_pager_status; - cfg_ua.cb.on_typing = &cb_on_typing; + cfg_ua.cb.on_call_state = &cb_on_call_state; + cfg_ua.cb.on_incoming_call = &cb_on_incoming_call; + cfg_ua.cb.on_call_media_state = &cb_on_call_media_state; + cfg_ua.cb.on_dtmf_digit = &cb_on_dtmf_digit; + cfg_ua.cb.on_call_transfer_request = &cb_on_call_transfer_request; + cfg_ua.cb.on_call_transfer_status = &cb_on_call_transfer_status; + cfg_ua.cb.on_call_replace_request = &cb_on_call_replace_request; + cfg_ua.cb.on_call_replaced = &cb_on_call_replaced; + cfg_ua.cb.on_reg_state = &cb_on_reg_state; + cfg_ua.cb.on_buddy_state = &cb_on_buddy_state; + cfg_ua.cb.on_pager = &cb_on_pager; + cfg_ua.cb.on_pager_status = &cb_on_pager_status; + cfg_ua.cb.on_typing = &cb_on_typing; p_cfg_ua = &cfg_ua; @@ -911,7 +910,7 @@ static PyObject *py_pjsua_init(PyObject *pSelf, PyObject *pArgs) if (o_log_cfg != Py_None) { - PyObj_pjsua_logging_config * obj_log; + PyObj_pjsua_logging_config * obj_log; obj_log = (PyObj_pjsua_logging_config *)o_log_cfg; @@ -930,9 +929,9 @@ static PyObject *py_pjsua_init(PyObject *pSelf, PyObject *pArgs) if (o_media_cfg != Py_None) { - PyObj_pjsua_media_config_export(&cfg_media, - (PyObj_pjsua_media_config*)o_media_cfg); - p_cfg_media = &cfg_media; + PyObj_pjsua_media_config_export(&cfg_media, + (PyObj_pjsua_media_config*)o_media_cfg); + p_cfg_media = &cfg_media; } else { p_cfg_media = NULL; @@ -1142,7 +1141,7 @@ static char pjsua_msg_data_init_doc[] = * !modified @ 051206 */ static PyObject *py_pjsua_transport_config_default(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { PyObj_pjsua_transport_config *obj; pjsua_transport_config cfg; @@ -1155,8 +1154,8 @@ static PyObject *py_pjsua_transport_config_default(PyObject *pSelf, pjsua_transport_config_default(&cfg); obj = (PyObj_pjsua_transport_config*) - PyObj_pjsua_transport_config_new(&PyTyp_pjsua_transport_config, - NULL, NULL); + PyObj_pjsua_transport_config_new(&PyTyp_pjsua_transport_config, + NULL, NULL); PyObj_pjsua_transport_config_import(obj, &cfg); return (PyObject *)obj; @@ -1181,9 +1180,9 @@ static PyObject *py_pjsua_transport_create(PyObject *pSelf, PyObject *pArgs) } if (tmpObj != Py_None) { - PyObj_pjsua_transport_config *obj; + PyObj_pjsua_transport_config *obj; obj = (PyObj_pjsua_transport_config*)tmpObj; - PyObj_pjsua_transport_config_export(&cfg, obj); + PyObj_pjsua_transport_config_export(&cfg, obj); status = pjsua_transport_create(type, &cfg, &id); } else { status = pjsua_transport_create(type, NULL, &id); @@ -1210,7 +1209,7 @@ static PyObject *py_pjsua_enum_transports(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } c = PJ_ARRAY_SIZE(id); status = pjsua_enum_transports(id, &c); @@ -1242,15 +1241,15 @@ static PyObject *py_pjsua_transport_get_info(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "i", &id)) { return NULL; - } + } - status = pjsua_transport_get_info(id, &info); + status = pjsua_transport_get_info(id, &info); if (status == PJ_SUCCESS) { - PyObj_pjsua_transport_info *obj; + PyObj_pjsua_transport_info *obj; obj = (PyObj_pjsua_transport_info *) - PyObj_pjsua_transport_info_new(&PyTyp_pjsua_transport_info, - NULL, NULL); - PyObj_pjsua_transport_info_import(obj, &info); + PyObj_pjsua_transport_info_new(&PyTyp_pjsua_transport_info, + NULL, NULL); + PyObj_pjsua_transport_info_import(obj, &info); return Py_BuildValue("O", obj); } else { Py_INCREF(Py_None); @@ -1273,8 +1272,8 @@ static PyObject *py_pjsua_transport_set_enable if (!PyArg_ParseTuple(pArgs, "ii", &id, &enabled)) { return NULL; - } - status = pjsua_transport_set_enable(id, enabled); + } + status = pjsua_transport_set_enable(id, enabled); return Py_BuildValue("i",status); } @@ -1293,8 +1292,8 @@ static PyObject *py_pjsua_transport_close(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "ii", &id, &force)) { return NULL; - } - status = pjsua_transport_close(id, force); + } + status = pjsua_transport_close(id, force); return Py_BuildValue("i",status); } @@ -1352,8 +1351,8 @@ static PyObject *py_pjsua_acc_config_default(PyObject *pSelf, PyObject *pArgs) pjsua_acc_config_default(&cfg); obj = (PyObj_pjsua_acc_config *) - PyObj_pjsua_acc_config_new(&PyTyp_pjsua_acc_config, - NULL, NULL); + PyObj_pjsua_acc_config_new(&PyTyp_pjsua_acc_config, + NULL, NULL); PyObj_pjsua_acc_config_import(obj, &cfg); return (PyObject *)obj; } @@ -1389,7 +1388,7 @@ static PyObject *py_pjsua_acc_is_valid(PyObject *pSelf, PyObject *pArgs) return NULL; } - is_valid = pjsua_acc_is_valid(id); + is_valid = pjsua_acc_is_valid(id); return Py_BuildValue("i", is_valid); } @@ -1407,7 +1406,7 @@ static PyObject *py_pjsua_acc_set_default(PyObject *pSelf, PyObject *pArgs) return NULL; } status = pjsua_acc_set_default(id); - + return Py_BuildValue("i", status); } @@ -1417,7 +1416,7 @@ static PyObject *py_pjsua_acc_set_default(PyObject *pSelf, PyObject *pArgs) static PyObject *py_pjsua_acc_get_default(PyObject *pSelf, PyObject *pArgs) { int id; - + PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "")) { @@ -1425,7 +1424,7 @@ static PyObject *py_pjsua_acc_get_default(PyObject *pSelf, PyObject *pArgs) } id = pjsua_acc_get_default(); - + return Py_BuildValue("i", id); } @@ -1448,15 +1447,15 @@ static PyObject *py_pjsua_acc_add(PyObject *pSelf, PyObject *pArgs) } if (acObj != Py_None) { - pjsua_acc_config cfg; + pjsua_acc_config cfg; - pjsua_acc_config_default(&cfg); + pjsua_acc_config_default(&cfg); ac = (PyObj_pjsua_acc_config *)acObj; PyObj_pjsua_acc_config_export(&cfg, ac); status = pjsua_acc_add(&cfg, is_default, &acc_id); } else { status = PJ_EINVAL; - acc_id = PJSUA_INVALID_ID; + acc_id = PJSUA_INVALID_ID; } return Py_BuildValue("ii", status, acc_id); @@ -1472,13 +1471,13 @@ static PyObject *py_pjsua_acc_add_local(PyObject *pSelf, PyObject *pArgs) int tid; int p_acc_id; int status; - + PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &tid, &is_default)) { return NULL; } - + status = pjsua_acc_add_local(tid, is_default, &p_acc_id); @@ -1499,9 +1498,9 @@ static PyObject *py_pjsua_acc_del(PyObject *pSelf, PyObject *pArgs) { return NULL; } - - - status = pjsua_acc_del(acc_id); + + + status = pjsua_acc_del(acc_id); return Py_BuildValue("i", status); } @@ -1509,7 +1508,7 @@ static PyObject *py_pjsua_acc_del(PyObject *pSelf, PyObject *pArgs) * py_pjsua_acc_modify */ static PyObject *py_pjsua_acc_modify(PyObject *pSelf, PyObject *pArgs) -{ +{ PyObject * acObj; PyObj_pjsua_acc_config * ac; int acc_id; @@ -1522,9 +1521,9 @@ static PyObject *py_pjsua_acc_modify(PyObject *pSelf, PyObject *pArgs) } if (acObj != Py_None) { - pjsua_acc_config cfg; + pjsua_acc_config cfg; - pjsua_acc_config_default(&cfg); + pjsua_acc_config_default(&cfg); ac = (PyObj_pjsua_acc_config *)acObj; PyObj_pjsua_acc_config_export(&cfg, ac); @@ -1539,20 +1538,20 @@ static PyObject *py_pjsua_acc_modify(PyObject *pSelf, PyObject *pArgs) * py_pjsua_acc_set_online_status */ static PyObject *py_pjsua_acc_set_online_status(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { - int is_online; + int is_online; int acc_id; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &acc_id, &is_online)) { return NULL; } - + status = pjsua_acc_set_online_status(acc_id, is_online); - + return Py_BuildValue("i", status); } @@ -1560,19 +1559,19 @@ static PyObject *py_pjsua_acc_set_online_status(PyObject *pSelf, * py_pjsua_acc_set_online_status2 */ static PyObject *py_pjsua_acc_set_online_status2(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { - int is_online; + int is_online; int acc_id; int activity_id; const char *activity_text; pjrpid_element rpid; - pj_status_t status; + pj_status_t status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "iiis", &acc_id, &is_online, - &activity_id, &activity_text)) { + &activity_id, &activity_text)) { return NULL; } @@ -1589,20 +1588,20 @@ static PyObject *py_pjsua_acc_set_online_status2(PyObject *pSelf, * py_pjsua_acc_set_registration */ static PyObject *py_pjsua_acc_set_registration(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { - int renew; + int renew; int acc_id; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &acc_id, &renew)) { return NULL; } - + status = pjsua_acc_set_registration(acc_id, renew); - + return Py_BuildValue("i", status); } @@ -1611,11 +1610,11 @@ static PyObject *py_pjsua_acc_set_registration(PyObject *pSelf, * !modified @ 051206 */ static PyObject *py_pjsua_acc_get_info(PyObject *pSelf, PyObject *pArgs) -{ +{ int acc_id; PyObj_pjsua_acc_info * obj; pjsua_acc_info info; - int status; + int status; PJ_UNUSED_ARG(pSelf); @@ -1625,13 +1624,13 @@ static PyObject *py_pjsua_acc_get_info(PyObject *pSelf, PyObject *pArgs) status = pjsua_acc_get_info(acc_id, &info); if (status == PJ_SUCCESS) { - obj = (PyObj_pjsua_acc_info *) - PyObj_pjsua_acc_info_new(&PyTyp_pjsua_acc_info,NULL, NULL); - PyObj_pjsua_acc_info_import(obj, &info); + obj = (PyObj_pjsua_acc_info *) + PyObj_pjsua_acc_info_new(&PyTyp_pjsua_acc_info,NULL, NULL); + PyObj_pjsua_acc_info_import(obj, &info); return Py_BuildValue("O", obj); } else { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } } @@ -1652,7 +1651,7 @@ static PyObject *py_pjsua_enum_accs(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } c = PJ_ARRAY_SIZE(id); status = pjsua_enum_accs(id, &c); @@ -1662,7 +1661,7 @@ static PyObject *py_pjsua_enum_accs(PyObject *pSelf, PyObject *pArgs) { int ret = PyList_SetItem(list, i, Py_BuildValue("i", id[i])); if (ret == -1) - { + { return NULL; } } @@ -1685,7 +1684,7 @@ static PyObject *py_pjsua_acc_enum_info(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } c = PJ_ARRAY_SIZE(info); status = pjsua_acc_enum_info(info, &c); @@ -1694,9 +1693,9 @@ static PyObject *py_pjsua_acc_enum_info(PyObject *pSelf, PyObject *pArgs) for (i = 0; i < c; i++) { PyObj_pjsua_acc_info *obj; obj = (PyObj_pjsua_acc_info *) - PyObj_pjsua_acc_info_new(&PyTyp_pjsua_acc_info, NULL, NULL); + PyObj_pjsua_acc_info_new(&PyTyp_pjsua_acc_info, NULL, NULL); - PyObj_pjsua_acc_info_import(obj, &info[i]); + PyObj_pjsua_acc_info_import(obj, &info[i]); PyList_SetItem(list, i, (PyObject *)obj); } @@ -1708,9 +1707,9 @@ static PyObject *py_pjsua_acc_enum_info(PyObject *pSelf, PyObject *pArgs) * py_pjsua_acc_find_for_outgoing */ static PyObject *py_pjsua_acc_find_for_outgoing(PyObject *pSelf, - PyObject *pArgs) -{ - int acc_id; + PyObject *pArgs) +{ + int acc_id; PyObject * url; pj_str_t str; @@ -1722,9 +1721,9 @@ static PyObject *py_pjsua_acc_find_for_outgoing(PyObject *pSelf, } str.ptr = PyString_AsString(url); str.slen = strlen(PyString_AsString(url)); - + acc_id = pjsua_acc_find_for_outgoing(&str); - + return Py_BuildValue("i", acc_id); } @@ -1732,9 +1731,9 @@ static PyObject *py_pjsua_acc_find_for_outgoing(PyObject *pSelf, * py_pjsua_acc_find_for_incoming */ static PyObject *py_pjsua_acc_find_for_incoming(PyObject *pSelf, - PyObject *pArgs) -{ - int acc_id; + PyObject *pArgs) +{ + int acc_id; PyObject * tmpObj; PyObj_pjsip_rx_data * obj; pjsip_rx_data * rdata; @@ -1761,8 +1760,8 @@ static PyObject *py_pjsua_acc_find_for_incoming(PyObject *pSelf, * !modified @ 061206 */ static PyObject *py_pjsua_acc_create_uac_contact(PyObject *pSelf, - PyObject *pArgs) -{ + PyObject *pArgs) +{ int status; int acc_id; PyObject * pObj; @@ -1790,7 +1789,7 @@ static PyObject *py_pjsua_acc_create_uac_contact(PyObject *pSelf, status = pjsua_acc_create_uac_contact(NULL, &contact, acc_id, &uri); } strc = PyString_FromStringAndSize(contact.ptr, contact.slen); - + return Py_BuildValue("O", strc); } @@ -1799,10 +1798,10 @@ static PyObject *py_pjsua_acc_create_uac_contact(PyObject *pSelf, * !modified @ 061206 */ static PyObject *py_pjsua_acc_create_uas_contact(PyObject *pSelf, - PyObject *pArgs) -{ + PyObject *pArgs) +{ int status; - int acc_id; + int acc_id; PyObject * pObj; PyObj_pj_pool * p; pj_pool_t * pool; @@ -1823,7 +1822,7 @@ static PyObject *py_pjsua_acc_create_uas_contact(PyObject *pSelf, p = (PyObj_pj_pool *)pObj; pool = p->pool; } else { - pool = NULL; + pool = NULL; } if (rObj != Py_None) { @@ -1834,7 +1833,7 @@ static PyObject *py_pjsua_acc_create_uas_contact(PyObject *pSelf, } status = pjsua_acc_create_uas_contact(pool, &contact, acc_id, rdata); strc = PyString_FromStringAndSize(contact.ptr, contact.slen); - + return Py_BuildValue("O", strc); } @@ -1921,9 +1920,9 @@ static char pjsua_acc_create_uas_contact_doc[] = * py_pjsua_buddy_config_default */ static PyObject *py_pjsua_buddy_config_default(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { - PyObj_pjsua_buddy_config *obj; + PyObj_pjsua_buddy_config *obj; pjsua_buddy_config cfg; PJ_UNUSED_ARG(pSelf); @@ -1934,7 +1933,7 @@ static PyObject *py_pjsua_buddy_config_default(PyObject *pSelf, pjsua_buddy_config_default(&cfg); obj = (PyObj_pjsua_buddy_config *) - PyObj_pjsua_buddy_config_new(&PyTyp_pjsua_buddy_config, NULL, NULL); + PyObj_pjsua_buddy_config_new(&PyTyp_pjsua_buddy_config, NULL, NULL); PyObj_pjsua_buddy_config_import(obj, &cfg); return (PyObject *)obj; @@ -1953,7 +1952,7 @@ static PyObject *py_pjsua_get_buddy_count(PyObject *pSelf, PyObject *pArgs) return NULL; } ret = pjsua_get_buddy_count(); - + return Py_BuildValue("i", ret); } @@ -1971,7 +1970,7 @@ static PyObject *py_pjsua_buddy_is_valid(PyObject *pSelf, PyObject *pArgs) return NULL; } is_valid = pjsua_buddy_is_valid(id); - + return Py_BuildValue("i", is_valid); } @@ -1991,7 +1990,7 @@ static PyObject *py_pjsua_enum_buddies(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } c = PJ_ARRAY_SIZE(id); status = pjsua_enum_buddies(id, &c); list = PyList_New(c); @@ -2007,11 +2006,11 @@ static PyObject *py_pjsua_enum_buddies(PyObject *pSelf, PyObject *pArgs) * !modified @ 071206 */ static PyObject *py_pjsua_buddy_get_info(PyObject *pSelf, PyObject *pArgs) -{ +{ int buddy_id; PyObj_pjsua_buddy_info * obj; pjsua_buddy_info info; - int status; + int status; PJ_UNUSED_ARG(pSelf); @@ -2021,13 +2020,13 @@ static PyObject *py_pjsua_buddy_get_info(PyObject *pSelf, PyObject *pArgs) status = pjsua_buddy_get_info(buddy_id, &info); if (status == PJ_SUCCESS) { - obj = (PyObj_pjsua_buddy_info *) - PyObj_pjsua_buddy_config_new(&PyTyp_pjsua_buddy_info,NULL,NULL); - PyObj_pjsua_buddy_info_import(obj, &info); + obj = (PyObj_pjsua_buddy_info *) + PyObj_pjsua_buddy_config_new(&PyTyp_pjsua_buddy_info,NULL,NULL); + PyObj_pjsua_buddy_info_import(obj, &info); return Py_BuildValue("O", obj); } else { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } } @@ -2048,18 +2047,18 @@ static PyObject *py_pjsua_buddy_add(PyObject *pSelf, PyObject *pArgs) } if (bcObj != Py_None) { - pjsua_buddy_config cfg; - PyObj_pjsua_buddy_config * bc; + pjsua_buddy_config cfg; + PyObj_pjsua_buddy_config * bc; bc = (PyObj_pjsua_buddy_config *)bcObj; - pjsua_buddy_config_default(&cfg); + pjsua_buddy_config_default(&cfg); PyObj_pjsua_buddy_config_export(&cfg, bc); status = pjsua_buddy_add(&cfg, &buddy_id); } else { status = PJ_EINVAL; - buddy_id = PJSUA_INVALID_ID; + buddy_id = PJSUA_INVALID_ID; } return Py_BuildValue("ii", status, buddy_id); } @@ -2077,9 +2076,9 @@ static PyObject *py_pjsua_buddy_del(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "i", &buddy_id)) { return NULL; } - - - status = pjsua_buddy_del(buddy_id); + + + status = pjsua_buddy_del(buddy_id); return Py_BuildValue("i", status); } @@ -2097,9 +2096,9 @@ static PyObject *py_pjsua_buddy_subscribe_pres(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "ii", &buddy_id, &subscribe)) { return NULL; } - - - status = pjsua_buddy_subscribe_pres(buddy_id, subscribe); + + + status = pjsua_buddy_subscribe_pres(buddy_id, subscribe); return Py_BuildValue("i", status); } @@ -2115,9 +2114,9 @@ static PyObject *py_pjsua_pres_dump(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "i", &verbose)) { return NULL; } - - - pjsua_pres_dump(verbose); + + + pjsua_pres_dump(verbose); Py_INCREF(Py_None); return Py_None; } @@ -2145,13 +2144,13 @@ static PyObject *py_pjsua_im_send(PyObject *pSelf, PyObject *pArgs) PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "iOOOOi", &acc_id, - &st, &smt, &sc, &omdObj, &user_data)) + &st, &smt, &sc, &omdObj, &user_data)) { return NULL; } if (smt != Py_None) { mime_type = &tmp_mime_type; - tmp_mime_type = PyString_to_pj_str(smt); + tmp_mime_type = PyString_to_pj_str(smt); } else { mime_type = NULL; } @@ -2159,20 +2158,20 @@ static PyObject *py_pjsua_im_send(PyObject *pSelf, PyObject *pArgs) content = PyString_to_pj_str(sc); if (omdObj != Py_None) { - + omd = (PyObj_pjsua_msg_data *)omdObj; - msg_data.content_type = PyString_to_pj_str(omd->content_type); - msg_data.msg_body = PyString_to_pj_str(omd->msg_body); + msg_data.content_type = PyString_to_pj_str(omd->content_type); + msg_data.msg_body = PyString_to_pj_str(omd->msg_body); pool = pjsua_pool_create("pjsua", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); status = pjsua_im_send(acc_id, &to, mime_type, - &content, &msg_data, (void *)user_data); + &content, &msg_data, (void *)user_data); pj_pool_release(pool); } else { - + status = pjsua_im_send(acc_id, &to, mime_type, - &content, NULL, NULL); + &content, NULL, NULL); } return Py_BuildValue("i",status); @@ -2198,17 +2197,17 @@ static PyObject *py_pjsua_im_typing(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "iOiO", &acc_id, &st, &is_typing, &omdObj)) { return NULL; } - + to = PyString_to_pj_str(st); if (omdObj != Py_None) { omd = (PyObj_pjsua_msg_data *)omdObj; - msg_data.content_type = PyString_to_pj_str(omd->content_type); - msg_data.msg_body = PyString_to_pj_str(omd->msg_body); + msg_data.content_type = PyString_to_pj_str(omd->content_type); + msg_data.msg_body = PyString_to_pj_str(omd->msg_body); pool = pjsua_pool_create("pjsua", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); - status = pjsua_im_typing(acc_id, &to, is_typing, &msg_data); + status = pjsua_im_typing(acc_id, &to, is_typing, &msg_data); pj_pool_release(pool); } else { status = pjsua_im_typing(acc_id, &to, is_typing, NULL); @@ -2306,11 +2305,11 @@ static PyObject * codec_info_new(PyTypeObject *type, PyObject *args, { self->codec_id = PyString_FromString(""); if (self->codec_id == NULL) - { + { Py_DECREF(self); return NULL; } - + } return (PyObject *)self; @@ -2438,14 +2437,14 @@ static PyObject * conf_port_info_new(PyTypeObject *type, PyObject *args, { self->name = PyString_FromString(""); if (self->name == NULL) - { + { Py_DECREF(self); return NULL; } - - self->listeners = (PyListObject *)PyList_New(0); + + self->listeners = (PyListObject *)PyList_New(0); if (self->listeners == NULL) - { + { Py_DECREF(self); return NULL; } @@ -2492,7 +2491,7 @@ static PyMemberDef conf_port_info_members[] = "listeners", T_OBJECT_EX, offsetof(PyObj_pjsua_conf_port_info, listeners), 0, "Array of listeners (in other words, ports where this port " - "is transmitting to" + "is transmitting to" }, {NULL} /* Sentinel */ @@ -2635,11 +2634,11 @@ static PyObject * pjmedia_snd_dev_info_new(PyTypeObject *type, PyObject *args, { self->name = PyString_FromString(""); if (self->name == NULL) - { + { Py_DECREF(self); return NULL; } - + } return (PyObject *)self; } @@ -2739,7 +2738,7 @@ typedef struct pj_uint32_t avg_bps; pj_uint16_t frm_ptime; pj_uint8_t pcm_bits_per_sample; - pj_uint8_t pt; + pj_uint8_t pt; } PyObj_pjmedia_codec_param_info; @@ -2983,16 +2982,16 @@ static PyObject * pjmedia_codec_param_new(PyTypeObject *type, PyObject *args, if (self != NULL) { self->info = (PyObj_pjmedia_codec_param_info *) - PyType_GenericNew(&PyTyp_pjmedia_codec_param_info, NULL, NULL); + PyType_GenericNew(&PyTyp_pjmedia_codec_param_info, NULL, NULL); if (self->info == NULL) - { + { Py_DECREF(self); return NULL; } - self->setting = (PyObj_pjmedia_codec_param_setting *) - PyType_GenericNew(&PyTyp_pjmedia_codec_param_setting, NULL, NULL); + self->setting = (PyObj_pjmedia_codec_param_setting *) + PyType_GenericNew(&PyTyp_pjmedia_codec_param_setting, NULL, NULL); if (self->setting == NULL) - { + { Py_DECREF(self); return NULL; } @@ -3093,7 +3092,7 @@ static PyObject *py_pjsua_conf_get_max_ports return NULL; } ret = pjsua_conf_get_max_ports(); - + return Py_BuildValue("i", ret); } @@ -3112,7 +3111,7 @@ static PyObject *py_pjsua_conf_get_active_ports return NULL; } ret = pjsua_conf_get_active_ports(); - + return Py_BuildValue("i", ret); } @@ -3133,7 +3132,7 @@ static PyObject *py_pjsua_enum_conf_ports(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } c = PJ_ARRAY_SIZE(id); status = pjsua_enum_conf_ports(id, &c); @@ -3143,9 +3142,9 @@ static PyObject *py_pjsua_enum_conf_ports(PyObject *pSelf, PyObject *pArgs) { int ret = PyList_SetItem(list, i, Py_BuildValue("i", id[i])); if (ret == -1) - { + { return NULL; - } + } } return Py_BuildValue("O",list); @@ -3156,11 +3155,11 @@ static PyObject *py_pjsua_enum_conf_ports(PyObject *pSelf, PyObject *pArgs) */ static PyObject *py_pjsua_conf_get_port_info (PyObject *pSelf, PyObject *pArgs) -{ +{ int id; PyObj_pjsua_conf_port_info * obj; pjsua_conf_port_info info; - int status; + int status; unsigned i; PJ_UNUSED_ARG(pSelf); @@ -3169,11 +3168,11 @@ static PyObject *py_pjsua_conf_get_port_info { return NULL; } - + status = pjsua_conf_get_port_info(id, &info); obj = (PyObj_pjsua_conf_port_info *)conf_port_info_new - (&PyTyp_pjsua_conf_port_info,NULL,NULL); + (&PyTyp_pjsua_conf_port_info,NULL,NULL); obj->bits_per_sample = info.bits_per_sample; obj->channel_count = info.bits_per_sample; obj->clock_rate = info.clock_rate; @@ -3183,8 +3182,8 @@ static PyObject *py_pjsua_conf_get_port_info obj->listeners = (PyListObject *)PyList_New(info.listener_cnt); for (i = 0; i < info.listener_cnt; i++) { - PyObject * item = Py_BuildValue("i",info.listeners[i]); - PyList_SetItem((PyObject *)obj->listeners, i, item); + PyObject * item = Py_BuildValue("i",info.listeners[i]); + PyList_SetItem((PyObject *)obj->listeners, i, item); } return Py_BuildValue("O", obj); } @@ -3194,7 +3193,7 @@ static PyObject *py_pjsua_conf_get_port_info */ static PyObject *py_pjsua_conf_add_port (PyObject *pSelf, PyObject *pArgs) -{ +{ int p_id; PyObject * oportObj; PyObj_pjmedia_port * oport; @@ -3203,7 +3202,7 @@ static PyObject *py_pjsua_conf_add_port PyObj_pj_pool * opool; pj_pool_t * pool; - int status; + int status; PJ_UNUSED_ARG(pSelf); @@ -3214,7 +3213,7 @@ static PyObject *py_pjsua_conf_add_port if (opoolObj != Py_None) { opool = (PyObj_pj_pool *)opoolObj; - pool = opool->pool; + pool = opool->pool; } else { opool = NULL; pool = NULL; @@ -3222,7 +3221,7 @@ static PyObject *py_pjsua_conf_add_port if (oportObj != Py_None) { oport = (PyObj_pjmedia_port *)oportObj; - port = oport->port; + port = oport->port; } else { oport = NULL; port = NULL; @@ -3239,16 +3238,16 @@ static PyObject *py_pjsua_conf_add_port */ static PyObject *py_pjsua_conf_remove_port (PyObject *pSelf, PyObject *pArgs) -{ +{ int id; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "i", &id)) { return NULL; - } + } status = pjsua_conf_remove_port(id); @@ -3261,16 +3260,16 @@ static PyObject *py_pjsua_conf_remove_port */ static PyObject *py_pjsua_conf_connect (PyObject *pSelf, PyObject *pArgs) -{ +{ int source, sink; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &source, &sink)) { return NULL; - } + } status = pjsua_conf_connect(source, sink); @@ -3283,16 +3282,16 @@ static PyObject *py_pjsua_conf_connect */ static PyObject *py_pjsua_conf_disconnect (PyObject *pSelf, PyObject *pArgs) -{ +{ int source, sink; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &source, &sink)) { return NULL; - } + } status = pjsua_conf_disconnect(source, sink); @@ -3305,19 +3304,19 @@ static PyObject *py_pjsua_conf_disconnect */ static PyObject *py_pjsua_player_create (PyObject *pSelf, PyObject *pArgs) -{ +{ int id; int options; PyObject * filename; pj_str_t str; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "Oi", &filename, &options)) { return NULL; - } + } str.ptr = PyString_AsString(filename); str.slen = strlen(PyString_AsString(filename)); status = pjsua_player_create(&str, options, &id); @@ -3330,16 +3329,16 @@ static PyObject *py_pjsua_player_create */ static PyObject *py_pjsua_player_get_conf_port (PyObject *pSelf, PyObject *pArgs) -{ +{ - int id, port_id; + int id, port_id; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "i", &id)) { return NULL; - } + } port_id = pjsua_player_get_conf_port(id); @@ -3352,17 +3351,17 @@ static PyObject *py_pjsua_player_get_conf_port */ static PyObject *py_pjsua_player_set_pos (PyObject *pSelf, PyObject *pArgs) -{ +{ int id; pj_uint32_t samples; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "iI", &id, &samples)) { return NULL; - } + } status = pjsua_player_set_pos(id, samples); @@ -3375,16 +3374,16 @@ static PyObject *py_pjsua_player_set_pos */ static PyObject *py_pjsua_player_destroy (PyObject *pSelf, PyObject *pArgs) -{ +{ int id; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "i", &id)) { return NULL; - } + } status = pjsua_player_destroy(id); @@ -3398,7 +3397,7 @@ static PyObject *py_pjsua_player_destroy */ static PyObject *py_pjsua_recorder_create (PyObject *pSelf, PyObject *pArgs) -{ +{ int p_id; int options; int max_size; @@ -3408,15 +3407,15 @@ static PyObject *py_pjsua_recorder_create pj_str_t strparam; int enc_type; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "OiOii", &filename, - &enc_type, &enc_param, &max_size, &options)) + &enc_type, &enc_param, &max_size, &options)) { return NULL; - } + } str.ptr = PyString_AsString(filename); str.slen = strlen(PyString_AsString(filename)); if (enc_param != Py_None) @@ -3424,10 +3423,10 @@ static PyObject *py_pjsua_recorder_create strparam.ptr = PyString_AsString(enc_param); strparam.slen = strlen(PyString_AsString(enc_param)); status = pjsua_recorder_create - (&str, enc_type, NULL, max_size, options, &p_id); + (&str, enc_type, NULL, max_size, options, &p_id); } else { status = pjsua_recorder_create - (&str, enc_type, NULL, max_size, options, &p_id); + (&str, enc_type, NULL, max_size, options, &p_id); } return Py_BuildValue("ii", status, p_id); } @@ -3437,16 +3436,16 @@ static PyObject *py_pjsua_recorder_create */ static PyObject *py_pjsua_recorder_get_conf_port (PyObject *pSelf, PyObject *pArgs) -{ +{ - int id, port_id; + int id, port_id; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "i", &id)) { return NULL; - } + } port_id = pjsua_recorder_get_conf_port(id); @@ -3459,16 +3458,16 @@ static PyObject *py_pjsua_recorder_get_conf_port */ static PyObject *py_pjsua_recorder_destroy (PyObject *pSelf, PyObject *pArgs) -{ +{ int id; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "i", &id)) { return NULL; - } + } status = pjsua_recorder_destroy(id); @@ -3492,7 +3491,7 @@ static PyObject *py_pjsua_enum_snd_devs(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } c = PJ_ARRAY_SIZE(info); status = pjsua_enum_snd_devs(info, &c); @@ -3503,26 +3502,26 @@ static PyObject *py_pjsua_enum_snd_devs(PyObject *pSelf, PyObject *pArgs) int ret; int j; char * str; - + PyObj_pjmedia_snd_dev_info * obj; obj = (PyObj_pjmedia_snd_dev_info *)pjmedia_snd_dev_info_new - (&PyTyp_pjmedia_snd_dev_info, NULL, NULL); + (&PyTyp_pjmedia_snd_dev_info, NULL, NULL); obj->default_samples_per_sec = info[i].default_samples_per_sec; obj->input_count = info[i].input_count; obj->output_count = info[i].output_count; str = (char *)malloc(SND_NAME_LEN * sizeof(char)); memset(str, 0, SND_NAME_LEN); for (j = 0; j < SND_NAME_LEN; j++) - { + { str[j] = info[i].name[j]; - } + } obj->name = PyString_FromStringAndSize(str, SND_NAME_LEN); free(str); ret = PyList_SetItem(list, i, (PyObject *)obj); if (ret == -1) - { + { return NULL; - } + } } return Py_BuildValue("O",list); @@ -3533,16 +3532,16 @@ static PyObject *py_pjsua_enum_snd_devs(PyObject *pSelf, PyObject *pArgs) */ static PyObject *py_pjsua_get_snd_dev (PyObject *pSelf, PyObject *pArgs) -{ +{ int capture_dev, playback_dev; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } status = pjsua_get_snd_dev(&capture_dev, &playback_dev); @@ -3555,16 +3554,16 @@ static PyObject *py_pjsua_get_snd_dev */ static PyObject *py_pjsua_set_snd_dev (PyObject *pSelf, PyObject *pArgs) -{ +{ int capture_dev, playback_dev; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &capture_dev, &playback_dev)) { return NULL; - } + } status = pjsua_set_snd_dev(capture_dev, playback_dev); @@ -3577,16 +3576,16 @@ static PyObject *py_pjsua_set_snd_dev */ static PyObject *py_pjsua_set_null_snd_dev (PyObject *pSelf, PyObject *pArgs) -{ +{ - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } status = pjsua_set_null_snd_dev(); @@ -3599,19 +3598,19 @@ static PyObject *py_pjsua_set_null_snd_dev */ static PyObject *py_pjsua_set_no_snd_dev (PyObject *pSelf, PyObject *pArgs) -{ +{ - PyObj_pjmedia_port * obj; + PyObj_pjmedia_port * obj; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } obj = (PyObj_pjmedia_port *)PyType_GenericNew - (&PyTyp_pjmedia_port, NULL, NULL); + (&PyTyp_pjmedia_port, NULL, NULL); obj->port = pjsua_set_no_snd_dev(); return Py_BuildValue("O", obj); } @@ -3621,17 +3620,17 @@ static PyObject *py_pjsua_set_no_snd_dev */ static PyObject *py_pjsua_set_ec (PyObject *pSelf, PyObject *pArgs) -{ +{ int options; int tail_ms; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &tail_ms, &options)) { return NULL; - } + } status = pjsua_set_ec(tail_ms, options); @@ -3644,9 +3643,9 @@ static PyObject *py_pjsua_set_ec */ static PyObject *py_pjsua_get_ec_tail (PyObject *pSelf, PyObject *pArgs) -{ +{ - int status; + int status; unsigned p_tail_ms; PJ_UNUSED_ARG(pSelf); @@ -3654,7 +3653,7 @@ static PyObject *py_pjsua_get_ec_tail if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } status = pjsua_get_ec_tail(&p_tail_ms); @@ -3679,7 +3678,7 @@ static PyObject *py_pjsua_enum_codecs(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } c = PJ_ARRAY_SIZE(info); status = pjsua_enum_codecs(info, &c); @@ -3691,18 +3690,18 @@ static PyObject *py_pjsua_enum_codecs(PyObject *pSelf, PyObject *pArgs) int j; PyObj_pjsua_codec_info * obj; obj = (PyObj_pjsua_codec_info *)codec_info_new - (&PyTyp_pjsua_codec_info, NULL, NULL); + (&PyTyp_pjsua_codec_info, NULL, NULL); obj->codec_id = PyString_FromStringAndSize - (info[i].codec_id.ptr, info[i].codec_id.slen); + (info[i].codec_id.ptr, info[i].codec_id.slen); obj->priority = info[i].priority; for (j = 0; j < 32; j++) - { + { obj->buf_[j] = info[i].buf_[j]; - } + } ret = PyList_SetItem(list, i, (PyObject *)obj); if (ret == -1) { return NULL; - } + } } @@ -3714,9 +3713,9 @@ static PyObject *py_pjsua_enum_codecs(PyObject *pSelf, PyObject *pArgs) */ static PyObject *py_pjsua_codec_set_priority (PyObject *pSelf, PyObject *pArgs) -{ +{ - int status; + int status; PyObject * id; pj_str_t str; pj_uint8_t priority; @@ -3726,7 +3725,7 @@ static PyObject *py_pjsua_codec_set_priority if (!PyArg_ParseTuple(pArgs, "OB", &id, &priority)) { return NULL; - } + } str.ptr = PyString_AsString(id); str.slen = strlen(PyString_AsString(id)); status = pjsua_codec_set_priority(&str, priority); @@ -3740,9 +3739,9 @@ static PyObject *py_pjsua_codec_set_priority */ static PyObject *py_pjsua_codec_get_param (PyObject *pSelf, PyObject *pArgs) -{ +{ - int status; + int status; PyObject * id; pj_str_t str; pjmedia_codec_param param; @@ -3753,12 +3752,12 @@ static PyObject *py_pjsua_codec_get_param if (!PyArg_ParseTuple(pArgs, "O", &id)) { return NULL; - } + } str.ptr = PyString_AsString(id); str.slen = strlen(PyString_AsString(id)); status = pjsua_codec_get_param(&str, ¶m); obj = (PyObj_pjmedia_codec_param *)pjmedia_codec_param_new - (&PyTyp_pjmedia_codec_param, NULL, NULL); + (&PyTyp_pjmedia_codec_param, NULL, NULL); obj->info->avg_bps = param.info.avg_bps; obj->info->channel_cnt = param.info.channel_cnt; obj->info->clock_rate = param.info.clock_rate; @@ -3782,9 +3781,9 @@ static PyObject *py_pjsua_codec_get_param */ static PyObject *py_pjsua_codec_set_param (PyObject *pSelf, PyObject *pArgs) -{ +{ - int status; + int status; PyObject * id; pj_str_t str; pjmedia_codec_param param; @@ -3796,7 +3795,7 @@ static PyObject *py_pjsua_codec_set_param if (!PyArg_ParseTuple(pArgs, "OO", &id, &tmpObj)) { return NULL; - } + } str.ptr = PyString_AsString(id); str.slen = strlen(PyString_AsString(id)); @@ -3810,7 +3809,7 @@ static PyObject *py_pjsua_codec_set_param param.info.pcm_bits_per_sample = obj->info->pcm_bits_per_sample; param.info.pt = obj->info->pt; param.setting.cng = obj->setting->cng; - //Deprecated: + //Deprecated: //param.setting.dec_fmtp_mode = obj->setting->dec_fmtp_mode; //param.setting.enc_fmtp_mode = obj->setting->enc_fmtp_mode; param.setting.frm_per_pkt = obj->setting->frm_per_pkt; @@ -4043,12 +4042,12 @@ typedef struct PyObj_pj_time_val * connect_duration; PyObj_pj_time_val * total_duration; struct { - char local_info[128]; - char local_contact[128]; - char remote_info[128]; - char remote_contact[128]; - char call_id[128]; - char last_status_text[128]; + char local_info[128]; + char local_contact[128]; + char remote_info[128]; + char remote_contact[128]; + char call_id[128]; + char last_status_text[128]; } buf_; } PyObj_pjsua_call_info; @@ -4090,57 +4089,57 @@ static PyObject * call_info_new(PyTypeObject *type, PyObject *args, { self->local_info = PyString_FromString(""); if (self->local_info == NULL) - { + { Py_DECREF(self); return NULL; } - self->local_contact = PyString_FromString(""); + self->local_contact = PyString_FromString(""); if (self->local_contact == NULL) - { + { Py_DECREF(self); return NULL; } - self->remote_info = PyString_FromString(""); + self->remote_info = PyString_FromString(""); if (self->remote_info == NULL) - { + { Py_DECREF(self); return NULL; } - self->remote_contact = PyString_FromString(""); + self->remote_contact = PyString_FromString(""); if (self->remote_contact == NULL) - { + { Py_DECREF(self); return NULL; } - self->call_id = PyString_FromString(""); + self->call_id = PyString_FromString(""); if (self->call_id == NULL) - { + { Py_DECREF(self); return NULL; } - self->state_text = PyString_FromString(""); + self->state_text = PyString_FromString(""); if (self->state_text == NULL) - { + { Py_DECREF(self); return NULL; } - self->last_status_text = PyString_FromString(""); + self->last_status_text = PyString_FromString(""); if (self->last_status_text == NULL) - { + { Py_DECREF(self); return NULL; } - self->connect_duration = (PyObj_pj_time_val *)PyType_GenericNew - (&PyTyp_pj_time_val,NULL,NULL); + self->connect_duration = (PyObj_pj_time_val *)PyType_GenericNew + (&PyTyp_pj_time_val,NULL,NULL); if (self->connect_duration == NULL) - { + { Py_DECREF(self); return NULL; } - self->total_duration = (PyObj_pj_time_val *)PyType_GenericNew - (&PyTyp_pj_time_val,NULL,NULL); + self->total_duration = (PyObj_pj_time_val *)PyType_GenericNew + (&PyTyp_pj_time_val,NULL,NULL); if (self->total_duration == NULL) - { + { Py_DECREF(self); return NULL; } @@ -4297,7 +4296,7 @@ static PyTypeObject PyTyp_pjsua_call_info = */ static PyObject *py_pjsua_call_get_max_count (PyObject *pSelf, PyObject *pArgs) -{ +{ int count; PJ_UNUSED_ARG(pSelf); @@ -4305,7 +4304,7 @@ static PyObject *py_pjsua_call_get_max_count if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } count = pjsua_call_get_max_count(); @@ -4318,16 +4317,16 @@ static PyObject *py_pjsua_call_get_max_count */ static PyObject *py_pjsua_call_get_count (PyObject *pSelf, PyObject *pArgs) -{ +{ - int count; + int count; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } count = pjsua_call_get_count(); @@ -4351,7 +4350,7 @@ static PyObject *py_pjsua_enum_calls(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } c = PJ_ARRAY_SIZE(id); status = pjsua_enum_calls(id, &c); @@ -4390,11 +4389,11 @@ static PyObject *py_pjsua_call_make_call PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple - (pArgs, "iOIiO", &acc_id, &sd, &options, &user_data, &omdObj)) + (pArgs, "iOIiO", &acc_id, &sd, &options, &user_data, &omdObj)) { return NULL; } - + dst_uri.ptr = PyString_AsString(sd); dst_uri.slen = strlen(PyString_AsString(sd)); if (omdObj != Py_None) @@ -4402,22 +4401,22 @@ static PyObject *py_pjsua_call_make_call omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type.ptr = PyString_AsString(omd->content_type); msg_data.content_type.slen = strlen - (PyString_AsString(omd->content_type)); + (PyString_AsString(omd->content_type)); msg_data.msg_body.ptr = PyString_AsString(omd->msg_body); msg_data.msg_body.slen = strlen(PyString_AsString(omd->msg_body)); pool = pjsua_pool_create("pjsua", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); status = pjsua_call_make_call(acc_id, &dst_uri, - options, (void*)user_data, &msg_data, &call_id); + options, (void*)user_data, &msg_data, &call_id); pj_pool_release(pool); } else { - + status = pjsua_call_make_call(acc_id, &dst_uri, - options, (void*)user_data, NULL, &call_id); + options, (void*)user_data, NULL, &call_id); } - + return Py_BuildValue("ii",status, call_id); - + } /* @@ -4425,16 +4424,16 @@ static PyObject *py_pjsua_call_make_call */ static PyObject *py_pjsua_call_is_active (PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; - int isActive; + int isActive; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "i", &call_id)) { return NULL; - } + } isActive = pjsua_call_is_active(call_id); @@ -4447,16 +4446,16 @@ static PyObject *py_pjsua_call_is_active */ static PyObject *py_pjsua_call_has_media (PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; - int hasMedia; + int hasMedia; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "i", &call_id)) { return NULL; - } + } hasMedia = pjsua_call_has_media(call_id); @@ -4469,16 +4468,16 @@ static PyObject *py_pjsua_call_has_media */ static PyObject *py_pjsua_call_get_conf_port (PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; - int port_id; + int port_id; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "i", &call_id)) { return NULL; - } + } port_id = pjsua_call_get_conf_port(call_id); @@ -4491,7 +4490,7 @@ static PyObject *py_pjsua_call_get_conf_port */ static PyObject *py_pjsua_call_get_info (PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; int status; PyObj_pjsua_call_info * oi; @@ -4502,7 +4501,7 @@ static PyObject *py_pjsua_call_get_info if (!PyArg_ParseTuple(pArgs, "i", &call_id)) { return NULL; - } + } status = pjsua_call_get_info(call_id, &info); @@ -4511,22 +4510,22 @@ static PyObject *py_pjsua_call_get_info oi = (PyObj_pjsua_call_info *)call_info_new(&PyTyp_pjsua_call_info, NULL, NULL); oi->acc_id = info.acc_id; pj_ansi_snprintf(oi->buf_.call_id, sizeof(oi->buf_.call_id), - "%.*s", (int)info.call_id.slen, info.call_id.ptr); + "%.*s", (int)info.call_id.slen, info.call_id.ptr); pj_ansi_snprintf(oi->buf_.last_status_text, - sizeof(oi->buf_.last_status_text), - "%.*s", (int)info.last_status_text.slen, info.last_status_text.ptr); + sizeof(oi->buf_.last_status_text), + "%.*s", (int)info.last_status_text.slen, info.last_status_text.ptr); pj_ansi_snprintf(oi->buf_.local_contact, sizeof(oi->buf_.local_contact), - "%.*s", (int)info.local_contact.slen, info.local_contact.ptr); + "%.*s", (int)info.local_contact.slen, info.local_contact.ptr); pj_ansi_snprintf(oi->buf_.local_info, sizeof(oi->buf_.local_info), - "%.*s", (int)info.local_info.slen, info.local_info.ptr); + "%.*s", (int)info.local_info.slen, info.local_info.ptr); pj_ansi_snprintf(oi->buf_.remote_contact, - sizeof(oi->buf_.remote_contact), - "%.*s", (int)info.remote_contact.slen, info.remote_contact.ptr); + sizeof(oi->buf_.remote_contact), + "%.*s", (int)info.remote_contact.slen, info.remote_contact.ptr); pj_ansi_snprintf(oi->buf_.remote_info, sizeof(oi->buf_.remote_info), - "%.*s", (int)info.remote_info.slen, info.remote_info.ptr); + "%.*s", (int)info.remote_info.slen, info.remote_info.ptr); oi->call_id = PyString_FromStringAndSize(info.call_id.ptr, - info.call_id.slen); + info.call_id.slen); oi->conf_slot = info.conf_slot; oi->connect_duration->sec = info.connect_duration.sec; oi->connect_duration->msec = info.connect_duration.msec; @@ -4535,26 +4534,26 @@ static PyObject *py_pjsua_call_get_info oi->id = info.id; oi->last_status = info.last_status; oi->last_status_text = PyString_FromStringAndSize( - info.last_status_text.ptr, info.last_status_text.slen); + info.last_status_text.ptr, info.last_status_text.slen); oi->local_contact = PyString_FromStringAndSize( - info.local_contact.ptr, info.local_contact.slen); + info.local_contact.ptr, info.local_contact.slen); oi->local_info = PyString_FromStringAndSize( - info.local_info.ptr, info.local_info.slen); + info.local_info.ptr, info.local_info.slen); oi->remote_contact = PyString_FromStringAndSize( - info.remote_contact.ptr, info.remote_contact.slen); + info.remote_contact.ptr, info.remote_contact.slen); oi->remote_info = PyString_FromStringAndSize( - info.remote_info.ptr, info.remote_info.slen); + info.remote_info.ptr, info.remote_info.slen); oi->media_dir = info.media_dir; oi->media_status = info.media_status; oi->role = info.role; oi->state = info.state; oi->state_text = PyString_FromStringAndSize( - info.state_text.ptr, info.state_text.slen); + info.state_text.ptr, info.state_text.slen); - return Py_BuildValue("O", oi); + return Py_BuildValue("O", oi); } else { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } } @@ -4563,9 +4562,9 @@ static PyObject *py_pjsua_call_get_info */ static PyObject *py_pjsua_call_set_user_data (PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; - int user_data; + int user_data; int status; PJ_UNUSED_ARG(pSelf); @@ -4573,7 +4572,7 @@ static PyObject *py_pjsua_call_set_user_data if (!PyArg_ParseTuple(pArgs, "ii", &call_id, &user_data)) { return NULL; - } + } status = pjsua_call_set_user_data(call_id, (void*)user_data); @@ -4586,16 +4585,16 @@ static PyObject *py_pjsua_call_set_user_data */ static PyObject *py_pjsua_call_get_user_data (PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; - void * user_data; + void * user_data; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "i", &call_id)) { return NULL; - } + } user_data = pjsua_call_get_user_data(call_id); @@ -4629,7 +4628,7 @@ static PyObject *py_pjsua_call_answer { reason = NULL; } else { - reason = &tmp_reason; + reason = &tmp_reason; tmp_reason.ptr = PyString_AsString(sr); tmp_reason.slen = strlen(PyString_AsString(sr)); } @@ -4638,19 +4637,19 @@ static PyObject *py_pjsua_call_answer omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type.ptr = PyString_AsString(omd->content_type); msg_data.content_type.slen = strlen - (PyString_AsString(omd->content_type)); + (PyString_AsString(omd->content_type)); msg_data.msg_body.ptr = PyString_AsString(omd->msg_body); msg_data.msg_body.slen = strlen(PyString_AsString(omd->msg_body)); pool = pjsua_pool_create("pjsua", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); - - status = pjsua_call_answer(call_id, code, reason, &msg_data); + + status = pjsua_call_answer(call_id, code, reason, &msg_data); pj_pool_release(pool); } else { - + status = pjsua_call_answer(call_id, code, reason, NULL); - + } return Py_BuildValue("i",status); @@ -4691,15 +4690,15 @@ static PyObject *py_pjsua_call_hangup omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type.ptr = PyString_AsString(omd->content_type); msg_data.content_type.slen = strlen - (PyString_AsString(omd->content_type)); + (PyString_AsString(omd->content_type)); msg_data.msg_body.ptr = PyString_AsString(omd->msg_body); msg_data.msg_body.slen = strlen(PyString_AsString(omd->msg_body)); pool = pjsua_pool_create("pjsua", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); - status = pjsua_call_hangup(call_id, code, reason, &msg_data); + status = pjsua_call_hangup(call_id, code, reason, &msg_data); pj_pool_release(pool); } else { - status = pjsua_call_hangup(call_id, code, reason, NULL); + status = pjsua_call_hangup(call_id, code, reason, NULL); } return Py_BuildValue("i",status); @@ -4730,15 +4729,15 @@ static PyObject *py_pjsua_call_set_hold omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type.ptr = PyString_AsString(omd->content_type); msg_data.content_type.slen = strlen - (PyString_AsString(omd->content_type)); + (PyString_AsString(omd->content_type)); msg_data.msg_body.ptr = PyString_AsString(omd->msg_body); msg_data.msg_body.slen = strlen(PyString_AsString(omd->msg_body)); pool = pjsua_pool_create("pjsua", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); - status = pjsua_call_set_hold(call_id, &msg_data); + status = pjsua_call_set_hold(call_id, &msg_data); pj_pool_release(pool); } else { - status = pjsua_call_set_hold(call_id, NULL); + status = pjsua_call_set_hold(call_id, NULL); } return Py_BuildValue("i",status); } @@ -4769,12 +4768,12 @@ static PyObject *py_pjsua_call_reinvite omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type.ptr = PyString_AsString(omd->content_type); msg_data.content_type.slen = strlen - (PyString_AsString(omd->content_type)); + (PyString_AsString(omd->content_type)); msg_data.msg_body.ptr = PyString_AsString(omd->msg_body); msg_data.msg_body.slen = strlen(PyString_AsString(omd->msg_body)); pool = pjsua_pool_create("pjsua", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); - status = pjsua_call_reinvite(call_id, unhold, &msg_data); + status = pjsua_call_reinvite(call_id, unhold, &msg_data); pj_pool_release(pool); } else { status = pjsua_call_reinvite(call_id, unhold, NULL); @@ -4803,7 +4802,7 @@ static PyObject *py_pjsua_call_xfer { return NULL; } - + dest.ptr = PyString_AsString(sd); dest.slen = strlen(PyString_AsString(sd)); @@ -4812,15 +4811,15 @@ static PyObject *py_pjsua_call_xfer omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type.ptr = PyString_AsString(omd->content_type); msg_data.content_type.slen = strlen - (PyString_AsString(omd->content_type)); + (PyString_AsString(omd->content_type)); msg_data.msg_body.ptr = PyString_AsString(omd->msg_body); msg_data.msg_body.slen = strlen(PyString_AsString(omd->msg_body)); pool = pjsua_pool_create("pjsua", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); - status = pjsua_call_xfer(call_id, &dest, &msg_data); + status = pjsua_call_xfer(call_id, &dest, &msg_data); pj_pool_release(pool); } else { - status = pjsua_call_xfer(call_id, &dest, NULL); + status = pjsua_call_xfer(call_id, &dest, NULL); } return Py_BuildValue("i",status); } @@ -4843,26 +4842,26 @@ static PyObject *py_pjsua_call_xfer_replaces PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple - (pArgs, "iiIO", &call_id, &dest_call_id, &options, &omdObj)) + (pArgs, "iiIO", &call_id, &dest_call_id, &options, &omdObj)) { return NULL; } - + if (omdObj != Py_None) { omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type.ptr = PyString_AsString(omd->content_type); msg_data.content_type.slen = strlen - (PyString_AsString(omd->content_type)); + (PyString_AsString(omd->content_type)); msg_data.msg_body.ptr = PyString_AsString(omd->msg_body); msg_data.msg_body.slen = strlen(PyString_AsString(omd->msg_body)); pool = pjsua_pool_create("pjsua", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); status = pjsua_call_xfer_replaces - (call_id, dest_call_id, options, &msg_data); + (call_id, dest_call_id, options, &msg_data); pj_pool_release(pool); } else { - status = pjsua_call_xfer_replaces(call_id, dest_call_id,options, NULL); + status = pjsua_call_xfer_replaces(call_id, dest_call_id,options, NULL); } return Py_BuildValue("i",status); } @@ -4872,7 +4871,7 @@ static PyObject *py_pjsua_call_xfer_replaces */ static PyObject *py_pjsua_call_dial_dtmf (PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; PyObject * sd; pj_str_t digits; @@ -4883,7 +4882,7 @@ static PyObject *py_pjsua_call_dial_dtmf if (!PyArg_ParseTuple(pArgs, "iO", &call_id, &sd)) { return NULL; - } + } digits.ptr = PyString_AsString(sd); digits.slen = strlen(PyString_AsString(sd)); status = pjsua_call_dial_dtmf(call_id, &digits); @@ -4912,7 +4911,7 @@ static PyObject *py_pjsua_call_send_im PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple - (pArgs, "iOOOi", &call_id, &sm, &sc, &omdObj, &user_data)) + (pArgs, "iOOOi", &call_id, &sm, &sc, &omdObj, &user_data)) { return NULL; } @@ -4932,17 +4931,17 @@ static PyObject *py_pjsua_call_send_im omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type.ptr = PyString_AsString(omd->content_type); msg_data.content_type.slen = strlen - (PyString_AsString(omd->content_type)); + (PyString_AsString(omd->content_type)); msg_data.msg_body.ptr = PyString_AsString(omd->msg_body); msg_data.msg_body.slen = strlen(PyString_AsString(omd->msg_body)); pool = pjsua_pool_create("pjsua", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); status = pjsua_call_send_im - (call_id, mime_type, &content, &msg_data, (void *)user_data); + (call_id, mime_type, &content, &msg_data, (void *)user_data); pj_pool_release(pool); } else { status = pjsua_call_send_im - (call_id, mime_type, &content, NULL, (void *)user_data); + (call_id, mime_type, &content, NULL, (void *)user_data); } return Py_BuildValue("i",status); @@ -4968,21 +4967,21 @@ static PyObject *py_pjsua_call_send_typing_ind { return NULL; } - + if (omdObj != Py_None) { omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type.ptr = PyString_AsString(omd->content_type); msg_data.content_type.slen = strlen - (PyString_AsString(omd->content_type)); + (PyString_AsString(omd->content_type)); msg_data.msg_body.ptr = PyString_AsString(omd->msg_body); msg_data.msg_body.slen = strlen(PyString_AsString(omd->msg_body)); pool = pjsua_pool_create("pjsua", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); - status = pjsua_call_send_typing_ind(call_id, is_typing, &msg_data); + status = pjsua_call_send_typing_ind(call_id, is_typing, &msg_data); pj_pool_release(pool); } else { - status = pjsua_call_send_typing_ind(call_id, is_typing, NULL); + status = pjsua_call_send_typing_ind(call_id, is_typing, NULL); } return Py_BuildValue("i",status); } @@ -4992,14 +4991,14 @@ static PyObject *py_pjsua_call_send_typing_ind */ static PyObject *py_pjsua_call_hangup_all (PyObject *pSelf, PyObject *pArgs) -{ +{ PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } pjsua_call_hangup_all(); @@ -5012,7 +5011,7 @@ static PyObject *py_pjsua_call_hangup_all */ static PyObject *py_pjsua_call_dump (PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; int with_media; PyObject * sb; @@ -5027,7 +5026,7 @@ static PyObject *py_pjsua_call_dump if (!PyArg_ParseTuple(pArgs, "iiIO", &call_id, &with_media, &maxlen, &si)) { return NULL; - } + } buffer = (char *) malloc (maxlen * sizeof(char)); indent = PyString_AsString(si); @@ -5053,7 +5052,7 @@ static PyObject *py_pjsua_dump(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "i", &detail)) { return NULL; - } + } PJ_LOG(3,(THIS_FILE, "Start dumping application states:")); @@ -5061,7 +5060,7 @@ static PyObject *py_pjsua_dump(PyObject *pSelf, PyObject *pArgs) pj_log_set_decor(old_decor & (PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_CR)); if (detail) - pj_dump_config(); + pj_dump_config(); pjsip_endpt_dump(pjsua_get_pjsip_endpt(), detail); pjmedia_endpt_dump(pjsua_get_pjmedia_endpt()); @@ -5074,18 +5073,18 @@ static PyObject *py_pjsua_dump(PyObject *pSelf, PyObject *pArgs) if (pjsua_call_get_count() == 0) { - PJ_LOG(3,(THIS_FILE, " - no sessions -")); + PJ_LOG(3,(THIS_FILE, " - no sessions -")); } else { - unsigned i, max; - - max = pjsua_call_get_max_count(); - for (i=0; i @@ -32,11 +31,11 @@ PJ_INLINE(pj_str_t) PyString_to_pj_str(const PyObject *obj) pj_str_t str; if (obj) { - str.ptr = PyString_AS_STRING(obj); - str.slen = PyString_GET_SIZE(obj); + str.ptr = PyString_AS_STRING(obj); + str.slen = PyString_GET_SIZE(obj); } else { - str.ptr = NULL; - str.slen = 0; + str.ptr = NULL; + str.slen = 0; } return str; @@ -227,7 +226,7 @@ typedef struct PyObject *realm; PyObject *scheme; PyObject *username; - int data_type; + int data_type; PyObject *data; } PyObj_pjsip_cred_info; @@ -247,7 +246,7 @@ static void PyObj_pjsip_cred_info_delete(PyObj_pjsip_cred_info* self) static void PyObj_pjsip_cred_info_import(PyObj_pjsip_cred_info *obj, - const pjsip_cred_info *cfg) + const pjsip_cred_info *cfg) { Py_XDECREF(obj->realm); obj->realm = PyString_FromStringAndSize(cfg->realm.ptr, cfg->realm.slen); @@ -261,13 +260,13 @@ static void PyObj_pjsip_cred_info_import(PyObj_pjsip_cred_info *obj, } static void PyObj_pjsip_cred_info_export(pjsip_cred_info *cfg, - PyObj_pjsip_cred_info *obj) + PyObj_pjsip_cred_info *obj) { - cfg->realm = PyString_to_pj_str(obj->realm); - cfg->scheme = PyString_to_pj_str(obj->scheme); + cfg->realm = PyString_to_pj_str(obj->realm); + cfg->scheme = PyString_to_pj_str(obj->scheme); cfg->username = PyString_to_pj_str(obj->username); cfg->data_type = obj->data_type; - cfg->data = PyString_to_pj_str(obj->data); + cfg->data = PyString_to_pj_str(obj->data); } @@ -276,8 +275,8 @@ static void PyObj_pjsip_cred_info_export(pjsip_cred_info *cfg, * constructor for cred_info object */ static PyObject * PyObj_pjsip_cred_info_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsip_cred_info *self; @@ -289,26 +288,26 @@ static PyObject * PyObj_pjsip_cred_info_new(PyTypeObject *type, { self->realm = PyString_FromString(""); if (self->realm == NULL) - { + { Py_DECREF(self); return NULL; } self->scheme = PyString_FromString(""); if (self->scheme == NULL) - { + { Py_DECREF(self); return NULL; } self->username = PyString_FromString(""); if (self->username == NULL) - { + { Py_DECREF(self); return NULL; } - self->data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; + self->data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; self->data = PyString_FromString(""); if (self->data == NULL) - { + { Py_DECREF(self); return NULL; } @@ -342,11 +341,11 @@ static PyMemberDef PyObj_pjsip_cred_info_members[] = "data", T_OBJECT_EX, offsetof(PyObj_pjsip_cred_info, data), 0, "The data, which can be a plaintext password or a hashed digest, " - "depending on the value of data_type" + "depending on the value of data_type" }, { "data_type", T_INT, - offsetof(PyObj_pjsip_cred_info, data_type), 0, + offsetof(PyObj_pjsip_cred_info, data_type), 0, "Type of data" }, @@ -543,8 +542,8 @@ static void PyObj_pjsua_callback_delete(PyObj_pjsua_callback* self) * * declares constructor for callback struct */ static PyObject * PyObj_pjsua_callback_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_callback *self; @@ -557,91 +556,91 @@ static PyObject * PyObj_pjsua_callback_new(PyTypeObject *type, Py_INCREF(Py_None); self->on_call_state = Py_None; if (self->on_call_state == NULL) - { + { Py_DECREF(Py_None); return NULL; } Py_INCREF(Py_None); self->on_incoming_call = Py_None; if (self->on_incoming_call == NULL) - { + { Py_DECREF(Py_None); return NULL; } Py_INCREF(Py_None); self->on_call_media_state = Py_None; if (self->on_call_media_state == NULL) - { + { Py_DECREF(Py_None); return NULL; } Py_INCREF(Py_None); self->on_dtmf_digit = Py_None; if (self->on_dtmf_digit == NULL) - { + { Py_DECREF(Py_None); return NULL; } Py_INCREF(Py_None); self->on_call_transfer_request = Py_None; if (self->on_call_transfer_request == NULL) - { + { Py_DECREF(Py_None); return NULL; } Py_INCREF(Py_None); self->on_call_transfer_status = Py_None; if (self->on_call_transfer_status == NULL) - { + { Py_DECREF(Py_None); return NULL; } Py_INCREF(Py_None); self->on_call_replace_request = Py_None; if (self->on_call_replace_request == NULL) - { + { Py_DECREF(Py_None); return NULL; } Py_INCREF(Py_None); self->on_call_replaced = Py_None; if (self->on_call_replaced == NULL) - { + { Py_DECREF(Py_None); return NULL; } Py_INCREF(Py_None); self->on_reg_state = Py_None; if (self->on_reg_state == NULL) - { + { Py_DECREF(Py_None); return NULL; } Py_INCREF(Py_None); self->on_buddy_state = Py_None; if (self->on_buddy_state == NULL) - { + { Py_DECREF(Py_None); return NULL; } Py_INCREF(Py_None); self->on_pager = Py_None; if (self->on_pager == NULL) - { + { Py_DECREF(Py_None); return NULL; } Py_INCREF(Py_None); self->on_pager_status = Py_None; if (self->on_pager_status == NULL) - { + { Py_DECREF(Py_None); return NULL; } Py_INCREF(Py_None); self->on_typing = Py_None; if (self->on_typing == NULL) - { + { Py_DECREF(Py_None); return NULL; } @@ -659,8 +658,8 @@ static PyMemberDef PyObj_pjsua_callback_members[] = { { "on_call_state", T_OBJECT_EX, - offsetof(PyObj_pjsua_callback, on_call_state), 0, - "Notify application when invite state has changed. Application may " + offsetof(PyObj_pjsua_callback, on_call_state), 0, + "Notify application when invite state has changed. Application may " "then query the call info to get the detail call states." }, { @@ -676,18 +675,18 @@ static PyMemberDef PyObj_pjsua_callback_members[] = "the call's media to sound device." }, { - "on_dtmf_digit", T_OBJECT_EX, - offsetof(PyObj_pjsua_callback, on_dtmf_digit), 0, - "Notify application upon receiving incoming DTMF digit." + "on_dtmf_digit", T_OBJECT_EX, + offsetof(PyObj_pjsua_callback, on_dtmf_digit), 0, + "Notify application upon receiving incoming DTMF digit." }, { "on_call_transfer_request", T_OBJECT_EX, offsetof(PyObj_pjsua_callback, on_call_transfer_request), 0, "Notify application on call being transfered. " - "Application can decide to accept/reject transfer request " - "by setting the code (default is 200). When this callback " - "is not defined, the default behavior is to accept the " - "transfer." + "Application can decide to accept/reject transfer request " + "by setting the code (default is 200). When this callback " + "is not defined, the default behavior is to accept the " + "transfer." }, { "on_call_transfer_status", T_OBJECT_EX, @@ -706,12 +705,12 @@ static PyMemberDef PyObj_pjsua_callback_members[] = { "on_call_replaced", T_OBJECT_EX, offsetof(PyObj_pjsua_callback, on_call_replaced), 0, - "Notify application that an existing call has been replaced with " - "a new call. This happens when PJSUA-API receives incoming INVITE " - "request with Replaces header." - " " - "After this callback is called, normally PJSUA-API will disconnect " - "old_call_id and establish new_call_id." + "Notify application that an existing call has been replaced with " + "a new call. This happens when PJSUA-API receives incoming INVITE " + "request with Replaces header." + " " + "After this callback is called, normally PJSUA-API will disconnect " + "old_call_id and establish new_call_id." }, { "on_reg_state", T_OBJECT_EX, @@ -727,7 +726,7 @@ static PyMemberDef PyObj_pjsua_callback_members[] = }, { "on_pager", T_OBJECT_EX, - offsetof(PyObj_pjsua_callback, on_pager), 0, + offsetof(PyObj_pjsua_callback, on_pager), 0, "Notify application on incoming pager (i.e. MESSAGE request). " "Argument call_id will be -1 if MESSAGE request is not related to an " "existing call." @@ -740,7 +739,7 @@ static PyMemberDef PyObj_pjsua_callback_members[] = }, { "on_typing", T_OBJECT_EX, - offsetof(PyObj_pjsua_callback, on_typing), 0, + offsetof(PyObj_pjsua_callback, on_typing), 0, "Notify application about typing indication." }, {NULL} /* Sentinel */ @@ -754,45 +753,45 @@ static PyMemberDef PyObj_pjsua_callback_members[] = static PyTypeObject PyTyp_pjsua_callback = { PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ - "py_pjsua.Callback", /*tp_name*/ - sizeof(PyObj_pjsua_callback), /*tp_basicsize*/ - 0, /*tp_itemsize*/ + 0, /*ob_size*/ + "py_pjsua.Callback", /*tp_name*/ + sizeof(PyObj_pjsua_callback), /*tp_basicsize*/ + 0, /*tp_itemsize*/ (destructor)PyObj_pjsua_callback_delete, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ "This structure describes application callback " "to receive various event notifications from " - "PJSUA-API", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ + "PJSUA-API", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ PyObj_pjsua_callback_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ PyObj_pjsua_callback_new, /* tp_new */ }; @@ -809,11 +808,11 @@ typedef struct /* Type-specific fields go here. */ unsigned clock_rate; unsigned max_media_ports; - int has_ioqueue; + int has_ioqueue; unsigned thread_cnt; unsigned quality; unsigned ptime; - int no_vad; + int no_vad; unsigned ilbc_mode; unsigned tx_drop_pct; unsigned rx_drop_pct; @@ -830,7 +829,7 @@ static PyMemberDef PyObj_pjsua_media_config_members[] = { { "clock_rate", T_INT, - offsetof(PyObj_pjsua_media_config, clock_rate), 0, + offsetof(PyObj_pjsua_media_config, clock_rate), 0, "Clock rate to be applied to the conference bridge. If value is zero, " "default clock rate will be used (16KHz)." }, @@ -845,7 +844,7 @@ static PyMemberDef PyObj_pjsua_media_config_members[] = }, { "has_ioqueue", T_INT, - offsetof(PyObj_pjsua_media_config, has_ioqueue), 0, + offsetof(PyObj_pjsua_media_config, has_ioqueue), 0, "Specify whether the media manager should manage its own ioqueue for " "the RTP/RTCP sockets. If yes, ioqueue will be created and at least " "one worker thread will be created too. If no, the RTP/RTCP sockets " @@ -854,50 +853,50 @@ static PyMemberDef PyObj_pjsua_media_config_members[] = }, { "thread_cnt", T_INT, - offsetof(PyObj_pjsua_media_config, thread_cnt), 0, + offsetof(PyObj_pjsua_media_config, thread_cnt), 0, "Specify the number of worker threads to handle incoming RTP packets. " "A value of one is recommended for most applications." }, { "quality", T_INT, - offsetof(PyObj_pjsua_media_config, quality), 0, + offsetof(PyObj_pjsua_media_config, quality), 0, "The media quality also sets speex codec quality/complexity to the " "number." }, { "ptime", T_INT, - offsetof(PyObj_pjsua_media_config, ptime), 0, + offsetof(PyObj_pjsua_media_config, ptime), 0, "Specify default ptime." }, { "no_vad", T_INT, - offsetof(PyObj_pjsua_media_config, no_vad), 0, + offsetof(PyObj_pjsua_media_config, no_vad), 0, "Disable VAD?" }, { "ilbc_mode", T_INT, - offsetof(PyObj_pjsua_media_config, ilbc_mode), 0, + offsetof(PyObj_pjsua_media_config, ilbc_mode), 0, "iLBC mode (20 or 30)." }, { "tx_drop_pct", T_INT, - offsetof(PyObj_pjsua_media_config, tx_drop_pct), 0, + offsetof(PyObj_pjsua_media_config, tx_drop_pct), 0, "Percentage of RTP packet to drop in TX direction (to simulate packet " "lost)." }, { "rx_drop_pct", T_INT, - offsetof(PyObj_pjsua_media_config, rx_drop_pct), 0, + offsetof(PyObj_pjsua_media_config, rx_drop_pct), 0, "Percentage of RTP packet to drop in RX direction (to simulate packet " "lost)."}, { "ec_options", T_INT, - offsetof(PyObj_pjsua_media_config, ec_options), 0, + offsetof(PyObj_pjsua_media_config, ec_options), 0, "Echo canceller options (see pjmedia_echo_create())" }, { "ec_tail_len", T_INT, - offsetof(PyObj_pjsua_media_config, ec_tail_len), 0, + offsetof(PyObj_pjsua_media_config, ec_tail_len), 0, "Echo canceller tail length, in miliseconds." }, {NULL} /* Sentinel */ @@ -944,37 +943,37 @@ static PyTypeObject PyTyp_pjsua_media_config = static void PyObj_pjsua_media_config_import(PyObj_pjsua_media_config *obj, - const pjsua_media_config *cfg) + const pjsua_media_config *cfg) { - obj->clock_rate = cfg->clock_rate; + obj->clock_rate = cfg->clock_rate; obj->max_media_ports = cfg->max_media_ports; - obj->has_ioqueue = cfg->has_ioqueue; - obj->thread_cnt = cfg->thread_cnt; - obj->quality = cfg->quality; - obj->ptime = cfg->ptime; - obj->no_vad = cfg->no_vad; - obj->ilbc_mode = cfg->ilbc_mode; - obj->tx_drop_pct = cfg->tx_drop_pct; - obj->rx_drop_pct = cfg->rx_drop_pct; - obj->ec_options = cfg->ec_options; - obj->ec_tail_len = cfg->ec_tail_len; + obj->has_ioqueue = cfg->has_ioqueue; + obj->thread_cnt = cfg->thread_cnt; + obj->quality = cfg->quality; + obj->ptime = cfg->ptime; + obj->no_vad = cfg->no_vad; + obj->ilbc_mode = cfg->ilbc_mode; + obj->tx_drop_pct = cfg->tx_drop_pct; + obj->rx_drop_pct = cfg->rx_drop_pct; + obj->ec_options = cfg->ec_options; + obj->ec_tail_len = cfg->ec_tail_len; } static void PyObj_pjsua_media_config_export(pjsua_media_config *cfg, - const PyObj_pjsua_media_config *obj) + const PyObj_pjsua_media_config *obj) { - cfg->clock_rate = obj->clock_rate; + cfg->clock_rate = obj->clock_rate; cfg->max_media_ports = obj->max_media_ports; - cfg->has_ioqueue = obj->has_ioqueue; - cfg->thread_cnt = obj->thread_cnt; - cfg->quality = obj->quality; - cfg->ptime = obj->ptime; - cfg->no_vad = obj->no_vad; - cfg->ilbc_mode = obj->ilbc_mode; - cfg->tx_drop_pct = obj->tx_drop_pct; - cfg->rx_drop_pct = obj->rx_drop_pct; - cfg->ec_options = obj->ec_options; - cfg->ec_tail_len = obj->ec_tail_len; + cfg->has_ioqueue = obj->has_ioqueue; + cfg->thread_cnt = obj->thread_cnt; + cfg->quality = obj->quality; + cfg->ptime = obj->ptime; + cfg->no_vad = obj->no_vad; + cfg->ilbc_mode = obj->ilbc_mode; + cfg->tx_drop_pct = obj->tx_drop_pct; + cfg->rx_drop_pct = obj->rx_drop_pct; + cfg->ec_options = obj->ec_options; + cfg->ec_tail_len = obj->ec_tail_len; } ////////////////////////////////////////////////////////////////////////////// @@ -986,14 +985,14 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - unsigned max_calls; - unsigned thread_cnt; - PyObject *outbound_proxy; - PyObject *stun_domain; - PyObject *stun_host; - PyObject *stun_relay_host; + unsigned max_calls; + unsigned thread_cnt; + PyObject *outbound_proxy; + PyObject *stun_domain; + PyObject *stun_host; + PyObject *stun_relay_host; PyObj_pjsua_callback *cb; - PyObject *user_agent; + PyObject *user_agent; } PyObj_pjsua_config; @@ -1010,50 +1009,50 @@ static void PyObj_pjsua_config_delete(PyObj_pjsua_config* self) static void PyObj_pjsua_config_import(PyObj_pjsua_config *obj, - const pjsua_config *cfg) + const pjsua_config *cfg) { - obj->max_calls = cfg->max_calls; - obj->thread_cnt = cfg->thread_cnt; + obj->max_calls = cfg->max_calls; + obj->thread_cnt = cfg->thread_cnt; Py_XDECREF(obj->outbound_proxy); obj->outbound_proxy = PyString_FromStringAndSize(cfg->outbound_proxy[0].ptr, - cfg->outbound_proxy[0].slen); + cfg->outbound_proxy[0].slen); Py_XDECREF(obj->stun_domain); - obj->stun_domain = PyString_FromStringAndSize(cfg->stun_domain.ptr, - cfg->stun_domain.slen); + obj->stun_domain = PyString_FromStringAndSize(cfg->stun_domain.ptr, + cfg->stun_domain.slen); Py_XDECREF(obj->stun_host); - obj->stun_host = PyString_FromStringAndSize(cfg->stun_host.ptr, - cfg->stun_host.slen); + obj->stun_host = PyString_FromStringAndSize(cfg->stun_host.ptr, + cfg->stun_host.slen); Py_XDECREF(obj->stun_relay_host); obj->stun_relay_host= PyString_FromStringAndSize(cfg->stun_host.ptr, - cfg->stun_host.slen); + cfg->stun_host.slen); Py_XDECREF(obj->user_agent); - obj->user_agent = PyString_FromStringAndSize(cfg->user_agent.ptr, - cfg->user_agent.slen); + obj->user_agent = PyString_FromStringAndSize(cfg->user_agent.ptr, + cfg->user_agent.slen); } static void PyObj_pjsua_config_export(pjsua_config *cfg, - PyObj_pjsua_config *obj) + PyObj_pjsua_config *obj) { - cfg->max_calls = obj->max_calls; - cfg->thread_cnt = obj->thread_cnt; + cfg->max_calls = obj->max_calls; + cfg->thread_cnt = obj->thread_cnt; if (PyString_Size(obj->outbound_proxy) > 0) { - cfg->outbound_proxy_cnt = 1; - cfg->outbound_proxy[0] = PyString_to_pj_str(obj->outbound_proxy); + cfg->outbound_proxy_cnt = 1; + cfg->outbound_proxy[0] = PyString_to_pj_str(obj->outbound_proxy); } else { - cfg->outbound_proxy_cnt = 0; + cfg->outbound_proxy_cnt = 0; } - cfg->stun_domain = PyString_to_pj_str(obj->stun_domain); - cfg->stun_host = PyString_to_pj_str(obj->stun_host); + cfg->stun_domain = PyString_to_pj_str(obj->stun_domain); + cfg->stun_host = PyString_to_pj_str(obj->stun_host); //cfg->stun_relay_host= PyString_to_pj_str(obj->stun_host); - cfg->user_agent = PyString_to_pj_str(obj->user_agent); + cfg->user_agent = PyString_to_pj_str(obj->user_agent); } static PyObject *PyObj_pjsua_config_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_config *self; @@ -1065,20 +1064,20 @@ static PyObject *PyObj_pjsua_config_new(PyTypeObject *type, { self->user_agent = PyString_FromString(""); if (self->user_agent == NULL) - { + { Py_DECREF(self); return NULL; } self->outbound_proxy = PyString_FromString(""); if (self->outbound_proxy == NULL) - { + { Py_DECREF(self); return NULL; } self->cb = (PyObj_pjsua_callback *) - PyType_GenericNew(&PyTyp_pjsua_callback, NULL, NULL); + PyType_GenericNew(&PyTyp_pjsua_callback, NULL, NULL); if (self->cb == NULL) - { + { Py_DECREF(Py_None); return NULL; } @@ -1094,49 +1093,49 @@ static PyObject *PyObj_pjsua_config_new(PyTypeObject *type, static PyMemberDef PyObj_pjsua_config_members[] = { { - "max_calls", T_INT, - offsetof(PyObj_pjsua_config, max_calls), 0, - "Maximum calls to support (default: 4) " + "max_calls", T_INT, + offsetof(PyObj_pjsua_config, max_calls), 0, + "Maximum calls to support (default: 4) " }, { - "thread_cnt", T_INT, - offsetof(PyObj_pjsua_config, thread_cnt), 0, - "Number of worker threads. Normally application will want to have at " - "least one worker thread, unless when it wants to poll the library " - "periodically, which in this case the worker thread can be set to " - "zero." + "thread_cnt", T_INT, + offsetof(PyObj_pjsua_config, thread_cnt), 0, + "Number of worker threads. Normally application will want to have at " + "least one worker thread, unless when it wants to poll the library " + "periodically, which in this case the worker thread can be set to " + "zero." }, { - "outbound_proxy", T_OBJECT_EX, - offsetof(PyObj_pjsua_config, outbound_proxy), 0, - "SIP URL of the outbound proxy (optional)" + "outbound_proxy", T_OBJECT_EX, + offsetof(PyObj_pjsua_config, outbound_proxy), 0, + "SIP URL of the outbound proxy (optional)" }, { - "stun_domain", T_OBJECT_EX, - offsetof(PyObj_pjsua_config, stun_domain), 0, - "Domain of the STUN server (optional). STUN server will be resolved " - "using DNS SRV resolution only when nameserver is configured. " - "Alternatively, if DNS SRV resolution for STUN is not desired, " - "application can specify the STUN server hostname or IP address " - "in stun_host attribute." + "stun_domain", T_OBJECT_EX, + offsetof(PyObj_pjsua_config, stun_domain), 0, + "Domain of the STUN server (optional). STUN server will be resolved " + "using DNS SRV resolution only when nameserver is configured. " + "Alternatively, if DNS SRV resolution for STUN is not desired, " + "application can specify the STUN server hostname or IP address " + "in stun_host attribute." }, { - "stun_host", T_OBJECT_EX, - offsetof(PyObj_pjsua_config, stun_host), 0, - "Hostname or IP address of the STUN server (optional)." + "stun_host", T_OBJECT_EX, + offsetof(PyObj_pjsua_config, stun_host), 0, + "Hostname or IP address of the STUN server (optional)." }, { - "stun_relay_host", T_OBJECT_EX, - offsetof(PyObj_pjsua_config, stun_relay_host), 0, - "Hostname or IP address of the TURN server (optional)." + "stun_relay_host", T_OBJECT_EX, + offsetof(PyObj_pjsua_config, stun_relay_host), 0, + "Hostname or IP address of the TURN server (optional)." }, { - "cb", T_OBJECT_EX, offsetof(PyObj_pjsua_config, cb), 0, - "Application callback." + "cb", T_OBJECT_EX, offsetof(PyObj_pjsua_config, cb), 0, + "Application callback." }, { - "user_agent", T_OBJECT_EX, offsetof(PyObj_pjsua_config, user_agent), 0, - "User agent string (default empty)" + "user_agent", T_OBJECT_EX, offsetof(PyObj_pjsua_config, user_agent), 0, + "User agent string (default empty)" }, {NULL} /* Sentinel */ }; @@ -1199,12 +1198,12 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - int msg_logging; - unsigned level; - unsigned console_level; - unsigned decor; - PyObject *log_filename; - PyObject *cb; + int msg_logging; + unsigned level; + unsigned console_level; + unsigned decor; + PyObject *log_filename; + PyObject *cb; } PyObj_pjsua_logging_config; @@ -1221,22 +1220,22 @@ static void PyObj_pjsua_logging_config_delete(PyObj_pjsua_logging_config* self) static void PyObj_pjsua_logging_config_import(PyObj_pjsua_logging_config *obj, - const pjsua_logging_config *cfg) + const pjsua_logging_config *cfg) { - obj->msg_logging = cfg->msg_logging; - obj->level = cfg->level; - obj->console_level = cfg->console_level; - obj->decor = cfg->decor; + obj->msg_logging = cfg->msg_logging; + obj->level = cfg->level; + obj->console_level = cfg->console_level; + obj->decor = cfg->decor; } static void PyObj_pjsua_logging_config_export(pjsua_logging_config *cfg, - PyObj_pjsua_logging_config *obj) + PyObj_pjsua_logging_config *obj) { - cfg->msg_logging = obj->msg_logging; - cfg->level = obj->level; - cfg->console_level = obj->console_level; - cfg->decor = obj->decor; - cfg->log_filename = PyString_to_pj_str(obj->log_filename); + cfg->msg_logging = obj->msg_logging; + cfg->level = obj->level; + cfg->console_level = obj->console_level; + cfg->decor = obj->decor; + cfg->log_filename = PyString_to_pj_str(obj->log_filename); } @@ -1245,8 +1244,8 @@ static void PyObj_pjsua_logging_config_export(pjsua_logging_config *cfg, * constructor for logging_config object */ static PyObject * PyObj_pjsua_logging_config_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_logging_config *self; @@ -1258,14 +1257,14 @@ static PyObject * PyObj_pjsua_logging_config_new(PyTypeObject *type, { self->log_filename = PyString_FromString(""); if (self->log_filename == NULL) - { + { Py_DECREF(self); return NULL; } Py_INCREF(Py_None); self->cb = Py_None; if (self->cb == NULL) - { + { Py_DECREF(Py_None); return NULL; } @@ -1281,36 +1280,36 @@ static PyObject * PyObj_pjsua_logging_config_new(PyTypeObject *type, static PyMemberDef PyObj_pjsua_logging_config_members[] = { { - "msg_logging", T_INT, - offsetof(PyObj_pjsua_logging_config, msg_logging), 0, - "Log incoming and outgoing SIP message? Yes!" + "msg_logging", T_INT, + offsetof(PyObj_pjsua_logging_config, msg_logging), 0, + "Log incoming and outgoing SIP message? Yes!" }, { - "level", T_INT, - offsetof(PyObj_pjsua_logging_config, level), 0, - "Input verbosity level. Value 5 is reasonable." + "level", T_INT, + offsetof(PyObj_pjsua_logging_config, level), 0, + "Input verbosity level. Value 5 is reasonable." }, { - "console_level", T_INT, - offsetof(PyObj_pjsua_logging_config, console_level), - 0, "Verbosity level for console. Value 4 is reasonable." + "console_level", T_INT, + offsetof(PyObj_pjsua_logging_config, console_level), + 0, "Verbosity level for console. Value 4 is reasonable." }, { - "decor", T_INT, - offsetof(PyObj_pjsua_logging_config, decor), 0, - "Log decoration" + "decor", T_INT, + offsetof(PyObj_pjsua_logging_config, decor), 0, + "Log decoration" }, { - "log_filename", T_OBJECT_EX, - offsetof(PyObj_pjsua_logging_config, log_filename), 0, - "Optional log filename" + "log_filename", T_OBJECT_EX, + offsetof(PyObj_pjsua_logging_config, log_filename), 0, + "Optional log filename" }, { - "cb", T_OBJECT_EX, - offsetof(PyObj_pjsua_logging_config, cb), 0, - "Optional callback function to be called to write log to application " - "specific device. This function will be called forlog messages on " - "input verbosity level." + "cb", T_OBJECT_EX, + offsetof(PyObj_pjsua_logging_config, cb), 0, + "Optional callback function to be called to write log to application " + "specific device. This function will be called forlog messages on " + "input verbosity level." }, {NULL} /* Sentinel */ }; @@ -1402,8 +1401,8 @@ static void PyObj_pjsua_msg_data_delete(PyObj_pjsua_msg_data* self) * !modified @ 061206 */ static PyObject * PyObj_pjsua_msg_data_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_msg_data *self; @@ -1443,18 +1442,18 @@ static PyMemberDef PyObj_pjsua_msg_data_members[] = { { "hdr_list", T_OBJECT_EX, - offsetof(PyObj_pjsua_msg_data, hdr_list), 0, - "Additional message headers as linked list of strings." + offsetof(PyObj_pjsua_msg_data, hdr_list), 0, + "Additional message headers as linked list of strings." }, { - "content_type", T_OBJECT_EX, - offsetof(PyObj_pjsua_msg_data, content_type), 0, - "MIME type of optional message body." + "content_type", T_OBJECT_EX, + offsetof(PyObj_pjsua_msg_data, content_type), 0, + "MIME type of optional message body." }, { - "msg_body", T_OBJECT_EX, - offsetof(PyObj_pjsua_msg_data, msg_body), 0, - "Optional message body." + "msg_body", T_OBJECT_EX, + offsetof(PyObj_pjsua_msg_data, msg_body), 0, + "Optional message body." }, {NULL} /* Sentinel */ }; @@ -1518,7 +1517,7 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - unsigned port; + unsigned port; PyObject *public_addr; PyObject *bound_addr; } PyObj_pjsua_transport_config; @@ -1537,24 +1536,24 @@ static void PyObj_pjsua_transport_config_delete(PyObj_pjsua_transport_config* se static void PyObj_pjsua_transport_config_export(pjsua_transport_config *cfg, - PyObj_pjsua_transport_config *obj) + PyObj_pjsua_transport_config *obj) { - cfg->public_addr = PyString_to_pj_str(obj->public_addr); - cfg->bound_addr = PyString_to_pj_str(obj->bound_addr); - cfg->port = obj->port; + cfg->public_addr = PyString_to_pj_str(obj->public_addr); + cfg->bound_addr = PyString_to_pj_str(obj->bound_addr); + cfg->port = obj->port; } static void PyObj_pjsua_transport_config_import(PyObj_pjsua_transport_config *obj, - const pjsua_transport_config *cfg) + const pjsua_transport_config *cfg) { Py_XDECREF(obj->public_addr); obj->public_addr = PyString_FromStringAndSize(cfg->public_addr.ptr, - cfg->public_addr.slen); + cfg->public_addr.slen); Py_XDECREF(obj->bound_addr); obj->bound_addr = PyString_FromStringAndSize(cfg->bound_addr.ptr, - cfg->bound_addr.slen); + cfg->bound_addr.slen); obj->port = cfg->port; } @@ -1565,8 +1564,8 @@ static void PyObj_pjsua_transport_config_import(PyObj_pjsua_transport_config *ob * constructor for transport_config object */ static PyObject * PyObj_pjsua_transport_config_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_transport_config *self; @@ -1580,7 +1579,7 @@ static PyObject * PyObj_pjsua_transport_config_new(PyTypeObject *type, Py_DECREF(self); return NULL; } - self->bound_addr = PyString_FromString(""); + self->bound_addr = PyString_FromString(""); if (self->bound_addr == NULL) { Py_DECREF(self); return NULL; @@ -1598,7 +1597,7 @@ static PyMemberDef PyObj_pjsua_transport_config_members[] = { { "port", T_INT, - offsetof(PyObj_pjsua_transport_config, port), 0, + offsetof(PyObj_pjsua_transport_config, port), 0, "UDP port number to bind locally. This setting MUST be specified " "even when default port is desired. If the value is zero, the " "transport will be bound to any available port, and application " @@ -1606,12 +1605,12 @@ static PyMemberDef PyObj_pjsua_transport_config_members[] = }, { "public_addr", T_OBJECT_EX, - offsetof(PyObj_pjsua_transport_config, public_addr), 0, + offsetof(PyObj_pjsua_transport_config, public_addr), 0, "Optional address to advertise as the address of this transport. " "Application can specify any address or hostname for this field, " "for example it can point to one of the interface address in the " "system, or it can point to the public address of a NAT router " - "where port mappings have been configured for the application." + "where port mappings have been configured for the application." }, { "bound_addr", T_OBJECT_EX, @@ -1620,7 +1619,7 @@ static PyMemberDef PyObj_pjsua_transport_config_members[] = "SHOULD only be used to selectively bind the socket to particular " "interface (instead of 0.0.0.0), and SHOULD NOT be used to set the " "published address of a transport (the public_addr field should be " - "used for that purpose)." + "used for that purpose)." }, {NULL} /* Sentinel */ }; @@ -1654,7 +1653,7 @@ static PyTypeObject PyTyp_pjsua_transport_config = 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "Transport setting", /* tp_doc */ + "Transport setting", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ @@ -1684,14 +1683,14 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - int id; - int type; - PyObject *type_name; - PyObject *info; - unsigned flag; - PyObject *addr; - unsigned port; - unsigned usage_count; + int id; + int type; + PyObject *type_name; + PyObject *info; + unsigned flag; + PyObject *addr; + unsigned port; + unsigned usage_count; } PyObj_pjsua_transport_info; @@ -1709,18 +1708,18 @@ static void PyObj_pjsua_transport_info_delete(PyObj_pjsua_transport_info* self) static void PyObj_pjsua_transport_info_import(PyObj_pjsua_transport_info *obj, - const pjsua_transport_info *info) + const pjsua_transport_info *info) { - obj->id = info->id; - obj->type = info->type; + obj->id = info->id; + obj->type = info->type; obj->type_name = PyString_FromStringAndSize(info->type_name.ptr, - info->type_name.slen); - obj->info = PyString_FromStringAndSize(info->info.ptr, - info->info.slen); - obj->flag = info->flag; - obj->addr = PyString_FromStringAndSize(info->local_name.host.ptr, - info->local_name.host.slen); - obj->port = info->local_name.port; + info->type_name.slen); + obj->info = PyString_FromStringAndSize(info->info.ptr, + info->info.slen); + obj->flag = info->flag; + obj->addr = PyString_FromStringAndSize(info->local_name.host.ptr, + info->local_name.host.slen); + obj->port = info->local_name.port; obj->usage_count= info->usage_count; } @@ -1729,8 +1728,8 @@ static void PyObj_pjsua_transport_info_import(PyObj_pjsua_transport_info *obj, * constructor for transport_info object */ static PyObject * PyObj_pjsua_transport_info_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_transport_info *self; @@ -1768,12 +1767,12 @@ static PyMemberDef PyObj_pjsua_transport_info_members[] = { { "id", T_INT, - offsetof(PyObj_pjsua_transport_info, id), 0, + offsetof(PyObj_pjsua_transport_info, id), 0, "PJSUA transport identification." }, { "type", T_INT, - offsetof(PyObj_pjsua_transport_info, id), 0, + offsetof(PyObj_pjsua_transport_info, id), 0, "Transport type." }, { @@ -1788,7 +1787,7 @@ static PyMemberDef PyObj_pjsua_transport_info_members[] = }, { "flag", T_INT, - offsetof(PyObj_pjsua_transport_info, flag), 0, + offsetof(PyObj_pjsua_transport_info, flag), 0, "Transport flag (see ##pjsip_transport_flags_e)." }, { @@ -1803,7 +1802,7 @@ static PyMemberDef PyObj_pjsua_transport_info_members[] = }, { "usage_count", T_INT, - offsetof(PyObj_pjsua_transport_info, usage_count), 0, + offsetof(PyObj_pjsua_transport_info, usage_count), 0, "Current number of objects currently referencing this transport." }, {NULL} /* Sentinel */ @@ -1868,17 +1867,17 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - int priority; - PyObject *id; - PyObject *reg_uri; - int publish_enabled; - PyObject *force_contact; + int priority; + PyObject *id; + PyObject *reg_uri; + int publish_enabled; + PyObject *force_contact; /*pj_str_t proxy[8];*/ PyListObject *proxy; - unsigned reg_timeout; + unsigned reg_timeout; /*pjsip_cred_info cred_info[8];*/ PyListObject *cred_info; - int transport_id; + int transport_id; } PyObj_pjsua_acc_config; @@ -1890,7 +1889,7 @@ static void PyObj_pjsua_acc_config_delete(PyObj_pjsua_acc_config* self) { Py_XDECREF(self->id); Py_XDECREF(self->reg_uri); - Py_XDECREF(self->force_contact); + Py_XDECREF(self->force_contact); Py_XDECREF(self->proxy); Py_XDECREF(self->cred_info); self->ob_type->tp_free((PyObject*)self); @@ -1898,27 +1897,27 @@ static void PyObj_pjsua_acc_config_delete(PyObj_pjsua_acc_config* self) static void PyObj_pjsua_acc_config_import(PyObj_pjsua_acc_config *obj, - const pjsua_acc_config *cfg) + const pjsua_acc_config *cfg) { unsigned i; obj->priority = cfg->priority; Py_XDECREF(obj->id); - obj->id = PyString_FromStringAndSize(cfg->id.ptr, cfg->id.slen); + obj->id = PyString_FromStringAndSize(cfg->id.ptr, cfg->id.slen); Py_XDECREF(obj->reg_uri); obj->reg_uri = PyString_FromStringAndSize(cfg->reg_uri.ptr, - cfg->reg_uri.slen); + cfg->reg_uri.slen); obj->publish_enabled = cfg->publish_enabled; Py_XDECREF(obj->force_contact); obj->force_contact = PyString_FromStringAndSize(cfg->force_contact.ptr, - cfg->force_contact.slen); + cfg->force_contact.slen); Py_XDECREF(obj->proxy); obj->proxy = (PyListObject *)PyList_New(0); for (i=0; iproxy_cnt; ++i) { - PyObject * str; - str = PyString_FromStringAndSize(cfg->proxy[i].ptr, - cfg->proxy[i].slen); - PyList_Append((PyObject *)obj->proxy, str); + PyObject * str; + str = PyString_FromStringAndSize(cfg->proxy[i].ptr, + cfg->proxy[i].slen); + PyList_Append((PyObject *)obj->proxy, str); } obj->reg_timeout = cfg->reg_timeout; @@ -1926,24 +1925,24 @@ static void PyObj_pjsua_acc_config_import(PyObj_pjsua_acc_config *obj, Py_XDECREF(obj->cred_info); obj->cred_info = (PyListObject *)PyList_New(0); for (i=0; icred_count; ++i) { - PyObj_pjsip_cred_info * ci; - - ci = (PyObj_pjsip_cred_info *) - PyObj_pjsip_cred_info_new(&PyTyp_pjsip_cred_info,NULL,NULL); - PyObj_pjsip_cred_info_import(ci, &cfg->cred_info[i]); - PyList_Append((PyObject *)obj->cred_info, (PyObject *)ci); + PyObj_pjsip_cred_info * ci; + + ci = (PyObj_pjsip_cred_info *) + PyObj_pjsip_cred_info_new(&PyTyp_pjsip_cred_info,NULL,NULL); + PyObj_pjsip_cred_info_import(ci, &cfg->cred_info[i]); + PyList_Append((PyObject *)obj->cred_info, (PyObject *)ci); } obj->transport_id = cfg->transport_id; } static void PyObj_pjsua_acc_config_export(pjsua_acc_config *cfg, - PyObj_pjsua_acc_config *obj) + PyObj_pjsua_acc_config *obj) { unsigned i; cfg->priority = obj->priority; - cfg->id = PyString_to_pj_str(obj->id); + cfg->id = PyString_to_pj_str(obj->id); cfg->reg_uri = PyString_to_pj_str(obj->reg_uri); cfg->publish_enabled = obj->publish_enabled; cfg->force_contact = PyString_to_pj_str(obj->force_contact); @@ -1960,9 +1959,9 @@ static void PyObj_pjsua_acc_config_export(pjsua_acc_config *cfg, for (i = 0; i < cfg->cred_count; i++) { /*cfg.cred_info[i] = ac->cred_info[i];*/ PyObj_pjsip_cred_info *ci; - ci = (PyObj_pjsip_cred_info*) - PyList_GetItem((PyObject *)obj->cred_info,i); - PyObj_pjsip_cred_info_export(&cfg->cred_info[i], ci); + ci = (PyObj_pjsip_cred_info*) + PyList_GetItem((PyObject *)obj->cred_info,i); + PyObj_pjsip_cred_info_export(&cfg->cred_info[i], ci); } cfg->transport_id = obj->transport_id; @@ -1974,8 +1973,8 @@ static void PyObj_pjsua_acc_config_export(pjsua_acc_config *cfg, * constructor for acc_config object */ static PyObject * PyObj_pjsua_acc_config_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_acc_config *self; @@ -1999,16 +1998,16 @@ static PyObject * PyObj_pjsua_acc_config_new(PyTypeObject *type, Py_DECREF(self); return NULL; } - self->proxy = (PyListObject *)PyList_New(0); - if (self->proxy == NULL) { - Py_DECREF(self); - return NULL; - } - self->cred_info = (PyListObject *)PyList_New(0); - if (self->cred_info == NULL) { - Py_DECREF(self); - return NULL; - } + self->proxy = (PyListObject *)PyList_New(0); + if (self->proxy == NULL) { + Py_DECREF(self); + return NULL; + } + self->cred_info = (PyListObject *)PyList_New(0); + if (self->cred_info == NULL) { + Py_DECREF(self); + return NULL; + } } return (PyObject *)self; @@ -2060,10 +2059,10 @@ static PyMemberDef PyObj_pjsua_acc_config_members[] = "proxy", T_OBJECT_EX, offsetof(PyObj_pjsua_acc_config, proxy), 0, "Optional URI of the proxies to be visited for all outgoing requests " - "that are using this account (REGISTER, INVITE, etc). Application need " - "to specify these proxies if the service provider requires " - "that requests destined towards its network should go through certain " - "proxies first (for example, border controllers)." + "that are using this account (REGISTER, INVITE, etc). Application need " + "to specify these proxies if the service provider requires " + "that requests destined towards its network should go through certain " + "proxies first (for example, border controllers)." }, { "reg_timeout", T_INT, offsetof(PyObj_pjsua_acc_config, reg_timeout), 0, @@ -2075,19 +2074,19 @@ static PyMemberDef PyObj_pjsua_acc_config_members[] = "cred_info", T_OBJECT_EX, offsetof(PyObj_pjsua_acc_config, cred_info), 0, "Array of credentials. If registration is desired, normally there " - "should be at least one credential specified, to successfully " - "authenticate against the service provider. More credentials can " - "be specified, for example when the requests are expected to be " - "challenged by the proxies in the route set." + "should be at least one credential specified, to successfully " + "authenticate against the service provider. More credentials can " + "be specified, for example when the requests are expected to be " + "challenged by the proxies in the route set." }, { - "transport_id", T_INT, - offsetof(PyObj_pjsua_acc_config, transport_id), 0, - "Optionally bind this account to specific transport. This normally is" - " not a good idea, as account should be able to send requests using" - " any available transports according to the destination. But some" - " application may want to have explicit control over the transport to" - " use, so in that case it can set this field." + "transport_id", T_INT, + offsetof(PyObj_pjsua_acc_config, transport_id), 0, + "Optionally bind this account to specific transport. This normally is" + " not a good idea, as account should be able to send requests using" + " any available transports according to the destination. But some" + " application may want to have explicit control over the transport to" + " use, so in that case it can set this field." }, {NULL} /* Sentinel */ }; @@ -2152,15 +2151,15 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - int id; - int is_default; - PyObject *acc_uri; - int has_registration; - int expires; - int status; - PyObject *status_text; - int online_status; - PyObject *online_status_text; + int id; + int is_default; + PyObject *acc_uri; + int has_registration; + int expires; + int status; + PyObject *status_text; + int online_status; + PyObject *online_status_text; } PyObj_pjsua_acc_info; @@ -2178,20 +2177,20 @@ static void PyObj_pjsua_acc_info_delete(PyObj_pjsua_acc_info* self) static void PyObj_pjsua_acc_info_import(PyObj_pjsua_acc_info *obj, - const pjsua_acc_info *info) + const pjsua_acc_info *info) { - obj->id = info->id; + obj->id = info->id; obj->is_default = info->is_default; obj->acc_uri = PyString_FromStringAndSize(info->acc_uri.ptr, - info->acc_uri.slen); + info->acc_uri.slen); obj->has_registration = info->has_registration; obj->expires = info->expires; - obj->status = info->status; + obj->status = info->status; obj->status_text= PyString_FromStringAndSize(info->status_text.ptr, - info->status_text.slen); + info->status_text.slen); obj->online_status = info->online_status; obj->online_status_text = PyString_FromStringAndSize(info->online_status_text.ptr, - info->online_status_text.slen); + info->online_status_text.slen); } @@ -2200,8 +2199,8 @@ static void PyObj_pjsua_acc_info_import(PyObj_pjsua_acc_info *obj, * constructor for acc_info object */ static PyObject * PyObj_pjsua_acc_info_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_acc_info *self; @@ -2215,12 +2214,12 @@ static PyObject * PyObj_pjsua_acc_info_new(PyTypeObject *type, Py_DECREF(self); return NULL; } - self->status_text = PyString_FromString(""); + self->status_text = PyString_FromString(""); if (self->status_text == NULL) { Py_DECREF(self); return NULL; } - self->online_status_text = PyString_FromString(""); + self->online_status_text = PyString_FromString(""); if (self->online_status_text == NULL) { Py_DECREF(self); return NULL; @@ -2237,12 +2236,12 @@ static PyMemberDef acc_info_members[] = { { "id", T_INT, - offsetof(PyObj_pjsua_acc_info, id), 0, + offsetof(PyObj_pjsua_acc_info, id), 0, "The account ID." }, { "is_default", T_INT, - offsetof(PyObj_pjsua_acc_info, is_default), 0, + offsetof(PyObj_pjsua_acc_info, is_default), 0, "Flag to indicate whether this is the default account. " }, { @@ -2252,18 +2251,18 @@ static PyMemberDef acc_info_members[] = }, { "has_registration", T_INT, - offsetof(PyObj_pjsua_acc_info, has_registration), 0, + offsetof(PyObj_pjsua_acc_info, has_registration), 0, "Flag to tell whether this account has registration setting " "(reg_uri is not empty)." }, { "expires", T_INT, - offsetof(PyObj_pjsua_acc_info, expires), 0, + offsetof(PyObj_pjsua_acc_info, expires), 0, "An up to date expiration interval for account registration session." }, { "status", T_INT, - offsetof(PyObj_pjsua_acc_info, status), 0, + offsetof(PyObj_pjsua_acc_info, status), 0, "Last registration status code. If status code is zero, " "the account is currently not registered. Any other value indicates " "the SIP status code of the registration. " @@ -2275,12 +2274,12 @@ static PyMemberDef acc_info_members[] = }, { "online_status", T_INT, - offsetof(PyObj_pjsua_acc_info, online_status), 0, + offsetof(PyObj_pjsua_acc_info, online_status), 0, "Presence online status for this account. " }, { "online_status_text", T_OBJECT_EX, - offsetof(PyObj_pjsua_acc_info, online_status_text), 0, + offsetof(PyObj_pjsua_acc_info, online_status_text), 0, "Presence online status text." }, {NULL} /* Sentinel */ @@ -2323,7 +2322,7 @@ static PyTypeObject PyTyp_pjsua_acc_info = 0, /* tp_iter */ 0, /* tp_iternext */ NULL, /* tp_methods */ - acc_info_members, /* tp_members */ + acc_info_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ @@ -2347,8 +2346,8 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - PyObject *uri; - int subscribe; + PyObject *uri; + int subscribe; } PyObj_pjsua_buddy_config; @@ -2364,7 +2363,7 @@ static void PyObj_pjsua_buddy_config_delete(PyObj_pjsua_buddy_config* self) static void PyObj_pjsua_buddy_config_import(PyObj_pjsua_buddy_config *obj, - const pjsua_buddy_config *cfg) + const pjsua_buddy_config *cfg) { Py_XDECREF(obj->uri); obj->uri = PyString_FromStringAndSize(cfg->uri.ptr, cfg->uri.slen); @@ -2373,7 +2372,7 @@ static void PyObj_pjsua_buddy_config_import(PyObj_pjsua_buddy_config *obj, static void PyObj_pjsua_buddy_config_export(pjsua_buddy_config *cfg, - PyObj_pjsua_buddy_config *obj) + PyObj_pjsua_buddy_config *obj) { cfg->uri = PyString_to_pj_str(obj->uri); cfg->subscribe = obj->subscribe; @@ -2386,8 +2385,8 @@ static void PyObj_pjsua_buddy_config_export(pjsua_buddy_config *cfg, * constructor for buddy_config object */ static PyObject *PyObj_pjsua_buddy_config_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_buddy_config *self; @@ -2485,12 +2484,12 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - int id; - PyObject *uri; - PyObject *contact; - int status; - PyObject *status_text; - int monitor_pres; + int id; + PyObject *uri; + PyObject *contact; + int status; + PyObject *status_text; + int monitor_pres; } PyObj_pjsua_buddy_info; @@ -2510,7 +2509,7 @@ static void PyObj_pjsua_buddy_info_delete(PyObj_pjsua_buddy_info* self) static void PyObj_pjsua_buddy_info_import(PyObj_pjsua_buddy_info *obj, - const pjsua_buddy_info *info) + const pjsua_buddy_info *info) { obj->id = info->id; Py_XDECREF(obj->uri); @@ -2520,7 +2519,7 @@ static void PyObj_pjsua_buddy_info_import(PyObj_pjsua_buddy_info *obj, obj->status = info->status; Py_XDECREF(obj->status_text); obj->status_text = PyString_FromStringAndSize(info->status_text.ptr, - info->status_text.slen); + info->status_text.slen); obj->monitor_pres = info->monitor_pres; } @@ -2531,8 +2530,8 @@ static void PyObj_pjsua_buddy_info_import(PyObj_pjsua_buddy_info *obj, * !modified @ 071206 */ static PyObject * PyObj_pjsua_buddy_info_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_buddy_info *self; @@ -2546,17 +2545,17 @@ static PyObject * PyObj_pjsua_buddy_info_new(PyTypeObject *type, Py_DECREF(self); return NULL; } - self->contact = PyString_FromString(""); + self->contact = PyString_FromString(""); if (self->contact == NULL) { Py_DECREF(self); return NULL; } - self->status_text = PyString_FromString(""); + self->status_text = PyString_FromString(""); if (self->status_text == NULL) { Py_DECREF(self); return NULL; } - + } return (PyObject *)self; } @@ -2658,5 +2657,5 @@ static PyTypeObject PyTyp_pjsua_buddy_info = -#endif /* __PY_PJSUA_H__ */ +#endif /* __PY_PJSUA_H__ */ diff --git a/pjsip-apps/src/pygui/account.py b/pjsip-apps/src/pygui/account.py index 5e67a65159..82048439ca 100644 --- a/pjsip-apps/src/pygui/account.py +++ b/pjsip-apps/src/pygui/account.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua Python GUI Demo # diff --git a/pjsip-apps/src/pygui/accountsetting.py b/pjsip-apps/src/pygui/accountsetting.py index 652f4f4b8f..5bc7fe96a7 100644 --- a/pjsip-apps/src/pygui/accountsetting.py +++ b/pjsip-apps/src/pygui/accountsetting.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua Python GUI Demo # diff --git a/pjsip-apps/src/pygui/application.py b/pjsip-apps/src/pygui/application.py index e3b5341731..ed28890f98 100644 --- a/pjsip-apps/src/pygui/application.py +++ b/pjsip-apps/src/pygui/application.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua Python GUI Demo # diff --git a/pjsip-apps/src/pygui/buddy.py b/pjsip-apps/src/pygui/buddy.py index 591cce36a2..706ff553f8 100644 --- a/pjsip-apps/src/pygui/buddy.py +++ b/pjsip-apps/src/pygui/buddy.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua Python GUI Demo # diff --git a/pjsip-apps/src/pygui/call.py b/pjsip-apps/src/pygui/call.py index ff1a5a49b4..afd15ae569 100644 --- a/pjsip-apps/src/pygui/call.py +++ b/pjsip-apps/src/pygui/call.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua Python GUI Demo # diff --git a/pjsip-apps/src/pygui/chat.py b/pjsip-apps/src/pygui/chat.py index 1a014fa660..00b8e47c46 100644 --- a/pjsip-apps/src/pygui/chat.py +++ b/pjsip-apps/src/pygui/chat.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua Python GUI Demo # diff --git a/pjsip-apps/src/pygui/chatgui.py b/pjsip-apps/src/pygui/chatgui.py index 326c555f48..2fa4a974d7 100644 --- a/pjsip-apps/src/pygui/chatgui.py +++ b/pjsip-apps/src/pygui/chatgui.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua Python GUI Demo # diff --git a/pjsip-apps/src/pygui/endpoint.py b/pjsip-apps/src/pygui/endpoint.py index b26fea5a62..f04b3b9c79 100644 --- a/pjsip-apps/src/pygui/endpoint.py +++ b/pjsip-apps/src/pygui/endpoint.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua Python GUI Demo # diff --git a/pjsip-apps/src/pygui/log.py b/pjsip-apps/src/pygui/log.py index 3900671474..566353541b 100644 --- a/pjsip-apps/src/pygui/log.py +++ b/pjsip-apps/src/pygui/log.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua Python GUI Demo # diff --git a/pjsip-apps/src/pygui/settings.py b/pjsip-apps/src/pygui/settings.py index 25f053e220..a9805efa4a 100644 --- a/pjsip-apps/src/pygui/settings.py +++ b/pjsip-apps/src/pygui/settings.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua Python GUI Demo # diff --git a/pjsip-apps/src/python/_pjsua.c b/pjsip-apps/src/python/_pjsua.c index 3e1503001c..e138bdb503 100644 --- a/pjsip-apps/src/python/_pjsua.c +++ b/pjsip-apps/src/python/_pjsua.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,7 +30,7 @@ static long g_thread_id; static struct py_thread_desc { struct py_thread_desc *next; - pj_thread_desc desc; + pj_thread_desc desc; } *py_thread_desc; /* @@ -54,9 +53,9 @@ static PyObj_pjsua_callback * g_obj_callback; static void clear_py_thread_desc(void) { while (py_thread_desc) { - struct py_thread_desc *next = py_thread_desc->next; - free(py_thread_desc); - py_thread_desc = next; + struct py_thread_desc *next = py_thread_desc->next; + free(py_thread_desc); + py_thread_desc = next; } } @@ -67,32 +66,32 @@ static void clear_py_thread_desc(void) */ static void cb_log_cb(int level, const char *data, int len) { - + /* Ignore if this callback is called from alien thread context, * or otherwise it will crash Python. */ if (pj_thread_local_get(g_thread_id) == 0) - return; + return; if (PyCallable_Check(g_obj_log_cb)) { - PyObject *param_data; + PyObject *param_data; - ENTER_PYTHON(); + ENTER_PYTHON(); - param_data = PyString_FromStringAndSize(data, len); + param_data = PyString_FromStringAndSize(data, len); PyObject_CallFunction( g_obj_log_cb, - "iOi", - level, + "iOi", + level, param_data, - len, - NULL + len, + NULL ); - Py_DECREF(param_data); + Py_DECREF(param_data); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -104,24 +103,24 @@ static void cb_on_call_state(pjsua_call_id call_id, pjsip_event *e) { PJ_UNUSED_ARG(e); - if (PyCallable_Check(g_obj_callback->on_call_state)) { + if (PyCallable_Check(g_obj_callback->on_call_state)) { PyObject * obj; - ENTER_PYTHON(); + ENTER_PYTHON(); - obj = Py_BuildValue(""); - + obj = Py_BuildValue(""); + PyObject_CallFunction( g_obj_callback->on_call_state, - "iO", - call_id, - obj, - NULL + "iO", + call_id, + obj, + NULL ); - Py_DECREF(obj); + Py_DECREF(obj); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -131,30 +130,30 @@ static void cb_on_call_state(pjsua_call_id call_id, pjsip_event *e) * declares method on_incoming_call for callback struct */ static void cb_on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, - pjsip_rx_data *rdata) + pjsip_rx_data *rdata) { if (PyCallable_Check(g_obj_callback->on_incoming_call)) { - PyObj_pjsip_rx_data *obj; - - ENTER_PYTHON(); - - obj = (PyObj_pjsip_rx_data*) - PyObj_pjsip_rx_data_new(&PyTyp_pjsip_rx_data, - NULL, NULL); - PyObj_pjsip_rx_data_import(obj, rdata); - - PyObject_CallFunction( - g_obj_callback->on_incoming_call, - "iiO", - acc_id, - call_id, - obj, - NULL - ); - - Py_DECREF(obj); - - LEAVE_PYTHON(); + PyObj_pjsip_rx_data *obj; + + ENTER_PYTHON(); + + obj = (PyObj_pjsip_rx_data*) + PyObj_pjsip_rx_data_new(&PyTyp_pjsip_rx_data, + NULL, NULL); + PyObj_pjsip_rx_data_import(obj, rdata); + + PyObject_CallFunction( + g_obj_callback->on_incoming_call, + "iiO", + acc_id, + call_id, + obj, + NULL + ); + + Py_DECREF(obj); + + LEAVE_PYTHON(); } } @@ -167,16 +166,16 @@ static void cb_on_call_media_state(pjsua_call_id call_id) { if (PyCallable_Check(g_obj_callback->on_call_media_state)) { - ENTER_PYTHON(); + ENTER_PYTHON(); PyObject_CallFunction( - g_obj_callback->on_call_media_state, - "i", - call_id, - NULL - ); + g_obj_callback->on_call_media_state, + "i", + call_id, + NULL + ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -188,21 +187,21 @@ static void cb_on_call_media_state(pjsua_call_id call_id) static void cb_on_dtmf_digit(pjsua_call_id call_id, int digit) { if (PyCallable_Check(g_obj_callback->on_dtmf_digit)) { - char digit_str[10]; + char digit_str[10]; - PyGILState_STATE state = PyGILState_Ensure(); + PyGILState_STATE state = PyGILState_Ensure(); - pj_ansi_snprintf(digit_str, sizeof(digit_str), "%c", digit); + pj_ansi_snprintf(digit_str, sizeof(digit_str), "%c", digit); PyObject_CallFunction( - g_obj_callback->on_dtmf_digit, - "is", - call_id, - digit_str, - NULL - ); - - PyGILState_Release(state); + g_obj_callback->on_dtmf_digit, + "is", + call_id, + digit_str, + NULL + ); + + PyGILState_Release(state); } } @@ -212,38 +211,38 @@ static void cb_on_dtmf_digit(pjsua_call_id call_id, int digit) * !modified @061206 */ static void cb_on_call_transfer_request(pjsua_call_id call_id, - const pj_str_t *dst, - pjsip_status_code *code) + const pj_str_t *dst, + pjsip_status_code *code) { if (PyCallable_Check(g_obj_callback->on_call_transfer_request)) { - PyObject *ret, *param_dst; - int cd; + PyObject *ret, *param_dst; + int cd; - ENTER_PYTHON(); + ENTER_PYTHON(); - param_dst = PyString_FromPJ(dst); + param_dst = PyString_FromPJ(dst); ret = PyObject_CallFunction( - g_obj_callback->on_call_transfer_request, - "iOi", - call_id, - param_dst, - *code, - NULL - ); - - Py_DECREF(param_dst); - - if (ret != NULL) { - if (ret != Py_None) { - if (PyArg_Parse(ret,"i",&cd)) { - *code = cd; - } - } - Py_DECREF(ret); - } - - LEAVE_PYTHON(); + g_obj_callback->on_call_transfer_request, + "iOi", + call_id, + param_dst, + *code, + NULL + ); + + Py_DECREF(param_dst); + + if (ret != NULL) { + if (ret != Py_None) { + if (PyArg_Parse(ret,"i",&cd)) { + *code = cd; + } + } + Py_DECREF(ret); + } + + LEAVE_PYTHON(); } } @@ -256,42 +255,42 @@ static void cb_on_call_transfer_request(pjsua_call_id call_id, * !modified @061206 */ static void cb_on_call_transfer_status( pjsua_call_id call_id, - int status_code, - const pj_str_t *status_text, - pj_bool_t final, - pj_bool_t *p_cont) + int status_code, + const pj_str_t *status_text, + pj_bool_t final, + pj_bool_t *p_cont) { if (PyCallable_Check(g_obj_callback->on_call_transfer_status)) { - PyObject *ret, *param_reason; + PyObject *ret, *param_reason; - ENTER_PYTHON(); + ENTER_PYTHON(); - param_reason = PyString_FromPJ(status_text); + param_reason = PyString_FromPJ(status_text); ret = PyObject_CallFunction( - g_obj_callback->on_call_transfer_status, - "iiOii", - call_id, - status_code, - param_reason, - final, - *p_cont, - NULL - ); - - Py_DECREF(param_reason); - - if (ret != NULL) { - if (ret != Py_None) { - int cnt; - if (PyArg_Parse(ret,"i",&cnt)) { - *p_cont = cnt; - } - } - Py_DECREF(ret); - } - - LEAVE_PYTHON(); + g_obj_callback->on_call_transfer_status, + "iiOii", + call_id, + status_code, + param_reason, + final, + *p_cont, + NULL + ); + + Py_DECREF(param_reason); + + if (ret != NULL) { + if (ret != Py_None) { + int cnt; + if (PyArg_Parse(ret,"i",&cnt)) { + *p_cont = cnt; + } + } + Py_DECREF(ret); + } + + LEAVE_PYTHON(); } } @@ -302,46 +301,46 @@ static void cb_on_call_transfer_status( pjsua_call_id call_id, * !modified @061206 */ static void cb_on_call_replace_request( pjsua_call_id call_id, - pjsip_rx_data *rdata, - int *st_code, - pj_str_t *st_text) + pjsip_rx_data *rdata, + int *st_code, + pj_str_t *st_text) { PJ_UNUSED_ARG(rdata); if (PyCallable_Check(g_obj_callback->on_call_replace_request)) { - PyObject *ret, *param_reason, *param_rdata; - int cd; + PyObject *ret, *param_reason, *param_rdata; + int cd; - ENTER_PYTHON(); + ENTER_PYTHON(); - param_reason = PyString_FromPJ(st_text); - param_rdata = Py_BuildValue(""); + param_reason = PyString_FromPJ(st_text); + param_rdata = Py_BuildValue(""); ret = PyObject_CallFunction( - g_obj_callback->on_call_replace_request, - "iOiO", - call_id, - param_rdata, - *st_code, - param_reason, - NULL - ); - - Py_DECREF(param_rdata); - Py_DECREF(param_reason); - - if (ret != NULL) { - if (ret != Py_None) { - PyObject * txt; - if (PyArg_ParseTuple(ret,"iO",&cd, &txt)) { - *st_code = cd; - *st_text = PyString_ToPJ(txt); - } - } - Py_DECREF(ret); - } - - LEAVE_PYTHON(); + g_obj_callback->on_call_replace_request, + "iOiO", + call_id, + param_rdata, + *st_code, + param_reason, + NULL + ); + + Py_DECREF(param_rdata); + Py_DECREF(param_reason); + + if (ret != NULL) { + if (ret != Py_None) { + PyObject * txt; + if (PyArg_ParseTuple(ret,"iO",&cd, &txt)) { + *st_code = cd; + *st_text = PyString_ToPJ(txt); + } + } + Py_DECREF(ret); + } + + LEAVE_PYTHON(); } } @@ -352,20 +351,20 @@ static void cb_on_call_replace_request( pjsua_call_id call_id, * request with Replaces header. */ static void cb_on_call_replaced(pjsua_call_id old_call_id, - pjsua_call_id new_call_id) + pjsua_call_id new_call_id) { if (PyCallable_Check(g_obj_callback->on_call_replaced)) { - ENTER_PYTHON(); + ENTER_PYTHON(); PyObject_CallFunction( g_obj_callback->on_call_replaced, - "ii", - old_call_id, - new_call_id, - NULL + "ii", + old_call_id, + new_call_id, + NULL ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -377,16 +376,16 @@ static void cb_on_call_replaced(pjsua_call_id old_call_id, static void cb_on_reg_state(pjsua_acc_id acc_id) { if (PyCallable_Check(g_obj_callback->on_reg_state)) { - ENTER_PYTHON(); + ENTER_PYTHON(); PyObject_CallFunction( - g_obj_callback->on_reg_state, - "i", - acc_id, - NULL - ); + g_obj_callback->on_reg_state, + "i", + acc_id, + NULL + ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -394,13 +393,13 @@ static void cb_on_reg_state(pjsua_acc_id acc_id) * cb_on_incoming_subscribe */ static void cb_on_incoming_subscribe( pjsua_acc_id acc_id, - pjsua_srv_pres *srv_pres, - pjsua_buddy_id buddy_id, - const pj_str_t *from, - pjsip_rx_data *rdata, - pjsip_status_code *code, - pj_str_t *reason, - pjsua_msg_data *msg_data) + pjsua_srv_pres *srv_pres, + pjsua_buddy_id buddy_id, + const pj_str_t *from, + pjsip_rx_data *rdata, + pjsip_status_code *code, + pj_str_t *reason, + pjsua_msg_data *msg_data) { static char reason_buf[64]; @@ -408,72 +407,72 @@ static void cb_on_incoming_subscribe( pjsua_acc_id acc_id, PJ_UNUSED_ARG(msg_data); if (PyCallable_Check(g_obj_callback->on_incoming_subscribe)) { - PyObject *ret, *param_from, *param_contact, *param_srv_pres; - pjsip_contact_hdr *contact_hdr; - pj_pool_t *pool = NULL; - - ENTER_PYTHON(); - - param_from = PyString_FromPJ(from); - param_srv_pres = PyLong_FromLong((long)srv_pres); - - contact_hdr = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, - NULL); - if (contact_hdr) { - char *contact; - int len; - - pool = pjsua_pool_create("pytmp", 512, 512); - contact = (char*) pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE+1); - len = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, contact_hdr->uri, - contact, PJSIP_MAX_URL_SIZE); - if (len < 1) - len = 0; - contact[len] = '\0'; - - param_contact = PyString_FromStringAndSize(contact, len); - } else { - param_contact = Py_BuildValue(""); - } + PyObject *ret, *param_from, *param_contact, *param_srv_pres; + pjsip_contact_hdr *contact_hdr; + pj_pool_t *pool = NULL; + + ENTER_PYTHON(); + + param_from = PyString_FromPJ(from); + param_srv_pres = PyLong_FromLong((long)srv_pres); + + contact_hdr = (pjsip_contact_hdr*) + pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, + NULL); + if (contact_hdr) { + char *contact; + int len; + + pool = pjsua_pool_create("pytmp", 512, 512); + contact = (char*) pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE+1); + len = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, contact_hdr->uri, + contact, PJSIP_MAX_URL_SIZE); + if (len < 1) + len = 0; + contact[len] = '\0'; + + param_contact = PyString_FromStringAndSize(contact, len); + } else { + param_contact = Py_BuildValue(""); + } ret = PyObject_CallFunction( - g_obj_callback->on_incoming_subscribe, - "iiOOO", - acc_id, - buddy_id, - param_from, - param_contact, - param_srv_pres, - NULL - ); - - if (pool) - pj_pool_release(pool); - - Py_DECREF(param_from); - Py_DECREF(param_contact); - Py_DECREF(param_srv_pres); - - if (ret && PyTuple_Check(ret)) { - if (PyTuple_Size(ret) >= 1) - *code = (int)PyInt_AsLong(PyTuple_GetItem(ret, 0)); - if (PyTuple_Size(ret) >= 2) { - if (PyTuple_GetItem(ret, 1) != Py_None) { - pj_str_t tmp; - tmp = PyString_ToPJ(PyTuple_GetItem(ret, 1)); - reason->ptr = reason_buf; - pj_strncpy(reason, &tmp, sizeof(reason_buf)); - } else { - reason->slen = 0; - } - } - Py_XDECREF(ret); - } else if (ret) { - Py_XDECREF(ret); - } - - LEAVE_PYTHON(); + g_obj_callback->on_incoming_subscribe, + "iiOOO", + acc_id, + buddy_id, + param_from, + param_contact, + param_srv_pres, + NULL + ); + + if (pool) + pj_pool_release(pool); + + Py_DECREF(param_from); + Py_DECREF(param_contact); + Py_DECREF(param_srv_pres); + + if (ret && PyTuple_Check(ret)) { + if (PyTuple_Size(ret) >= 1) + *code = (int)PyInt_AsLong(PyTuple_GetItem(ret, 0)); + if (PyTuple_Size(ret) >= 2) { + if (PyTuple_GetItem(ret, 1) != Py_None) { + pj_str_t tmp; + tmp = PyString_ToPJ(PyTuple_GetItem(ret, 1)); + reason->ptr = reason_buf; + pj_strncpy(reason, &tmp, sizeof(reason_buf)); + } else { + reason->slen = 0; + } + } + Py_XDECREF(ret); + } else if (ret) { + Py_XDECREF(ret); + } + + LEAVE_PYTHON(); } } @@ -484,16 +483,16 @@ static void cb_on_incoming_subscribe( pjsua_acc_id acc_id, static void cb_on_buddy_state(pjsua_buddy_id buddy_id) { if (PyCallable_Check(g_obj_callback->on_buddy_state)) { - ENTER_PYTHON(); + ENTER_PYTHON(); PyObject_CallFunction( - g_obj_callback->on_buddy_state, - "i", - buddy_id, - NULL - ); + g_obj_callback->on_buddy_state, + "i", + buddy_id, + NULL + ); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -504,42 +503,42 @@ static void cb_on_buddy_state(pjsua_buddy_id buddy_id) static void cb_on_pager(pjsua_call_id call_id, const pj_str_t *from, const pj_str_t *to, const pj_str_t *contact, const pj_str_t *mime_type, const pj_str_t *body, - pjsip_rx_data *rdata, pjsua_acc_id acc_id) + pjsip_rx_data *rdata, pjsua_acc_id acc_id) { PJ_UNUSED_ARG(rdata); if (PyCallable_Check(g_obj_callback->on_pager)) { - PyObject *param_from, *param_to, *param_contact, *param_mime_type, - *param_body; + PyObject *param_from, *param_to, *param_contact, *param_mime_type, + *param_body; - ENTER_PYTHON(); + ENTER_PYTHON(); - param_from = PyString_FromPJ(from); - param_to = PyString_FromPJ(to); - param_contact = PyString_FromPJ(contact); - param_mime_type = PyString_FromPJ(mime_type); - param_body = PyString_FromPJ(body); + param_from = PyString_FromPJ(from); + param_to = PyString_FromPJ(to); + param_contact = PyString_FromPJ(contact); + param_mime_type = PyString_FromPJ(mime_type); + param_body = PyString_FromPJ(body); PyObject_CallFunction( - g_obj_callback->on_pager, - "iOOOOOi", - call_id, - param_from, - param_to, - param_contact, - param_mime_type, - param_body, - acc_id, - NULL - ); - - Py_DECREF(param_body); - Py_DECREF(param_mime_type); - Py_DECREF(param_contact); - Py_DECREF(param_to); - Py_DECREF(param_from); - - LEAVE_PYTHON(); + g_obj_callback->on_pager, + "iOOOOOi", + call_id, + param_from, + param_to, + param_contact, + param_mime_type, + param_body, + acc_id, + NULL + ); + + Py_DECREF(param_body); + Py_DECREF(param_mime_type); + Py_DECREF(param_contact); + Py_DECREF(param_to); + Py_DECREF(param_from); + + LEAVE_PYTHON(); } } @@ -552,41 +551,41 @@ static void cb_on_pager_status(pjsua_call_id call_id, const pj_str_t *to, const pj_str_t *body, void *user_data, pjsip_status_code status, const pj_str_t *reason, - pjsip_tx_data *tdata, - pjsip_rx_data *rdata, - pjsua_acc_id acc_id) + pjsip_tx_data *tdata, + pjsip_rx_data *rdata, + pjsua_acc_id acc_id) { if (PyCallable_Check(g_obj_callback->on_pager)) { - PyObject *param_call_id, *param_to, *param_body, - *param_user_data, *param_status, *param_reason, - *param_acc_id; + PyObject *param_call_id, *param_to, *param_body, + *param_user_data, *param_status, *param_reason, + *param_acc_id; - ENTER_PYTHON(); + ENTER_PYTHON(); - PJ_UNUSED_ARG(tdata); - PJ_UNUSED_ARG(rdata); + PJ_UNUSED_ARG(tdata); + PJ_UNUSED_ARG(rdata); PyObject_CallFunctionObjArgs( - g_obj_callback->on_pager_status, - param_call_id = Py_BuildValue("i",call_id), - param_to = PyString_FromPJ(to), - param_body = PyString_FromPJ(body), - param_user_data = Py_BuildValue("i", user_data), - param_status = Py_BuildValue("i",status), - param_reason = PyString_FromPJ(reason), - param_acc_id = Py_BuildValue("i",acc_id), - NULL - ); - - Py_DECREF(param_call_id); - Py_DECREF(param_to); - Py_DECREF(param_body); - Py_DECREF(param_user_data); - Py_DECREF(param_status); - Py_DECREF(param_reason); - Py_DECREF(param_acc_id); - - LEAVE_PYTHON(); + g_obj_callback->on_pager_status, + param_call_id = Py_BuildValue("i",call_id), + param_to = PyString_FromPJ(to), + param_body = PyString_FromPJ(body), + param_user_data = Py_BuildValue("i", user_data), + param_status = Py_BuildValue("i",status), + param_reason = PyString_FromPJ(reason), + param_acc_id = Py_BuildValue("i",acc_id), + NULL + ); + + Py_DECREF(param_call_id); + Py_DECREF(param_to); + Py_DECREF(param_body); + Py_DECREF(param_user_data); + Py_DECREF(param_status); + Py_DECREF(param_reason); + Py_DECREF(param_acc_id); + + LEAVE_PYTHON(); } } @@ -598,35 +597,35 @@ static void cb_on_pager_status(pjsua_call_id call_id, const pj_str_t *to, static void cb_on_typing(pjsua_call_id call_id, const pj_str_t *from, const pj_str_t *to, const pj_str_t *contact, pj_bool_t is_typing, pjsip_rx_data *rdata, - pjsua_acc_id acc_id) + pjsua_acc_id acc_id) { if (PyCallable_Check(g_obj_callback->on_typing)) { - PyObject *param_call_id, *param_from, *param_to, *param_contact, - *param_is_typing, *param_acc_id; + PyObject *param_call_id, *param_from, *param_to, *param_contact, + *param_is_typing, *param_acc_id; - ENTER_PYTHON(); + ENTER_PYTHON(); - PJ_UNUSED_ARG(rdata); + PJ_UNUSED_ARG(rdata); PyObject_CallFunctionObjArgs( - g_obj_callback->on_typing, - param_call_id = Py_BuildValue("i",call_id), - param_from = PyString_FromPJ(from), - param_to = PyString_FromPJ(to), - param_contact = PyString_FromPJ(contact), - param_is_typing = Py_BuildValue("i",is_typing), - param_acc_id = Py_BuildValue("i",acc_id), - NULL - ); - - Py_DECREF(param_call_id); - Py_DECREF(param_from); - Py_DECREF(param_to); - Py_DECREF(param_contact); - Py_DECREF(param_is_typing); - Py_DECREF(param_acc_id); - - LEAVE_PYTHON(); + g_obj_callback->on_typing, + param_call_id = Py_BuildValue("i",call_id), + param_from = PyString_FromPJ(from), + param_to = PyString_FromPJ(to), + param_contact = PyString_FromPJ(contact), + param_is_typing = Py_BuildValue("i",is_typing), + param_acc_id = Py_BuildValue("i",acc_id), + NULL + ); + + Py_DECREF(param_call_id); + Py_DECREF(param_from); + Py_DECREF(param_to); + Py_DECREF(param_contact); + Py_DECREF(param_is_typing); + Py_DECREF(param_acc_id); + + LEAVE_PYTHON(); } } @@ -637,25 +636,25 @@ static void cb_on_typing(pjsua_call_id call_id, const pj_str_t *from, static void cb_on_mwi_info(pjsua_acc_id acc_id, pjsua_mwi_info *mwi_info) { if (PyCallable_Check(g_obj_callback->on_mwi_info)) { - PyObject *param_acc_id, *param_body; - pj_str_t body; + PyObject *param_acc_id, *param_body; + pj_str_t body; - ENTER_PYTHON(); + ENTER_PYTHON(); - body.ptr = mwi_info->rdata->msg_info.msg->body->data; - body.slen = mwi_info->rdata->msg_info.msg->body->len; + body.ptr = mwi_info->rdata->msg_info.msg->body->data; + body.slen = mwi_info->rdata->msg_info.msg->body->len; PyObject_CallFunctionObjArgs( - g_obj_callback->on_mwi_info, - param_acc_id = Py_BuildValue("i",acc_id), - param_body = PyString_FromPJ(&body), - NULL - ); + g_obj_callback->on_mwi_info, + param_acc_id = Py_BuildValue("i",acc_id), + param_body = PyString_FromPJ(&body), + NULL + ); - Py_DECREF(param_acc_id); - Py_DECREF(param_body); + Py_DECREF(param_acc_id); + Py_DECREF(param_body); - LEAVE_PYTHON(); + LEAVE_PYTHON(); } } @@ -669,31 +668,31 @@ void translate_hdr(pj_pool_t *pool, pjsip_hdr *hdr, PyObject *py_hdr_list) pj_list_init(hdr); if (PyList_Check(py_hdr_list)) { - int i; + int i; for (i=0; i= 1) - hname = PyString_ToPJ(PyTuple_GetItem(tuple,0)); - else - hname.slen = 0; - if (PyTuple_Size(tuple) >= 2) - hvalue = PyString_ToPJ(PyTuple_GetItem(tuple,1)); - else - hvalue.slen = 0; + if (PyTuple_Size(tuple) >= 1) + hname = PyString_ToPJ(PyTuple_GetItem(tuple,0)); + else + hname.slen = 0; + if (PyTuple_Size(tuple) >= 2) + hvalue = PyString_ToPJ(PyTuple_GetItem(tuple,1)); + else + hvalue.slen = 0; } else { - hname.ptr = ""; - hname.slen = 0; - hvalue.ptr = ""; - hvalue.slen = 0; + hname.ptr = ""; + hname.slen = 0; + hvalue.ptr = ""; + hvalue.slen = 0; } new_hdr = pjsip_generic_string_hdr_create(pool, &hname, &hvalue); pj_list_push_back((pj_list_type *)hdr, (pj_list_type *)new_hdr); - } + } } } @@ -702,7 +701,7 @@ void translate_hdr(pj_pool_t *pool, pjsip_hdr *hdr, PyObject *py_hdr_list) */ static PyObject *py_pjsua_thread_register(PyObject *pSelf, PyObject *pArgs) { - pj_status_t status; + pj_status_t status; const char *name; PyObject *py_desc; pj_thread_t *thread; @@ -714,14 +713,14 @@ static PyObject *py_pjsua_thread_register(PyObject *pSelf, PyObject *pArgs) return NULL; } thread_desc = (struct py_thread_desc*) - malloc(sizeof(struct py_thread_desc)); + malloc(sizeof(struct py_thread_desc)); thread_desc->next = py_thread_desc; py_thread_desc = thread_desc; status = pj_thread_register(name, thread_desc->desc, &thread); if (status == PJ_SUCCESS) - status = pj_thread_local_set(g_thread_id, (void*)1); + status = pj_thread_local_set(g_thread_id, (void*)1); return Py_BuildValue("i",status); } @@ -732,7 +731,7 @@ static PyObject *py_pjsua_thread_register(PyObject *pSelf, PyObject *pArgs) static PyObject *py_pjsua_logging_config_default(PyObject *pSelf, PyObject *pArgs) { - PyObj_pjsua_logging_config *obj; + PyObj_pjsua_logging_config *obj; pjsua_logging_config cfg; PJ_UNUSED_ARG(pSelf); @@ -740,8 +739,8 @@ static PyObject *py_pjsua_logging_config_default(PyObject *pSelf, pjsua_logging_config_default(&cfg); obj = (PyObj_pjsua_logging_config*) - PyObj_pjsua_logging_config_new(&PyTyp_pjsua_logging_config, - NULL, NULL); + PyObj_pjsua_logging_config_new(&PyTyp_pjsua_logging_config, + NULL, NULL); PyObj_pjsua_logging_config_import(obj, &cfg); return (PyObject*)obj; @@ -761,7 +760,7 @@ static PyObject *py_pjsua_config_default(PyObject *pSelf, PyObject *pArgs) pjsua_config_default(&cfg); obj = (PyObj_pjsua_config *) PyObj_pjsua_config_new(&PyTyp_pjsua_config, - NULL, NULL); + NULL, NULL); PyObj_pjsua_config_import(obj, &cfg); return (PyObject*)obj; @@ -782,7 +781,7 @@ static PyObject * py_pjsua_media_config_default(PyObject *pSelf, pjsua_media_config_default(&cfg); obj = (PyObj_pjsua_media_config *) - PyType_GenericNew(&PyTyp_pjsua_media_config, NULL, NULL); + PyType_GenericNew(&PyTyp_pjsua_media_config, NULL, NULL); PyObj_pjsua_media_config_import(obj, &cfg); return (PyObject *)obj; @@ -798,7 +797,7 @@ static PyObject *py_pjsua_msg_data_init(PyObject *pSelf, PyObject *pArgs) PJ_UNUSED_ARG(pArgs); return (PyObject *)PyObj_pjsua_msg_data_new(&PyTyp_pjsua_msg_data, - NULL, NULL); + NULL, NULL); } @@ -806,7 +805,7 @@ static PyObject *py_pjsua_msg_data_init(PyObject *pSelf, PyObject *pArgs) * py_pjsua_reconfigure_logging */ static PyObject *py_pjsua_reconfigure_logging(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { PyObject *logObj; pj_status_t status; @@ -818,8 +817,8 @@ static PyObject *py_pjsua_reconfigure_logging(PyObject *pSelf, } if (logObj != Py_None) { - PyObj_pjsua_logging_config *log; - pjsua_logging_config cfg; + PyObj_pjsua_logging_config *log; + pjsua_logging_config cfg; log = (PyObj_pjsua_logging_config*)logObj; cfg.msg_logging = log->msg_logging; @@ -854,7 +853,7 @@ static PyObject *py_pjsua_perror(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "ssi", &sender, &title, &status)) { return NULL; } - + pjsua_perror(sender, title, status); return Py_BuildValue(""); @@ -874,11 +873,11 @@ static PyObject *py_pjsua_create(PyObject *pSelf, PyObject *pArgs) status = pjsua_create(); if (status == PJ_SUCCESS) { - status = pj_thread_local_alloc(&g_thread_id); - if (status == PJ_SUCCESS) - status = pj_thread_local_set(g_thread_id, (void*)1); + status = pj_thread_local_alloc(&g_thread_id); + if (status == PJ_SUCCESS) + status = pj_thread_local_set(g_thread_id, (void*)1); - pj_atexit(&clear_py_thread_desc); + pj_atexit(&clear_py_thread_desc); } return Py_BuildValue("i",status); @@ -907,29 +906,29 @@ static PyObject *py_pjsua_init(PyObject *pSelf, PyObject *pArgs) pjsua_media_config_default(&cfg_media); if (o_ua_cfg != Py_None) { - PyObj_pjsua_config *obj_ua_cfg = (PyObj_pjsua_config*)o_ua_cfg; - - PyObj_pjsua_config_export(&cfg_ua, obj_ua_cfg); - - Py_XDECREF(g_obj_callback); - g_obj_callback = obj_ua_cfg->cb; - Py_INCREF(g_obj_callback); - - cfg_ua.cb.on_call_state = &cb_on_call_state; - cfg_ua.cb.on_incoming_call = &cb_on_incoming_call; - cfg_ua.cb.on_call_media_state = &cb_on_call_media_state; - cfg_ua.cb.on_dtmf_digit = &cb_on_dtmf_digit; - cfg_ua.cb.on_call_transfer_request = &cb_on_call_transfer_request; - cfg_ua.cb.on_call_transfer_status = &cb_on_call_transfer_status; - cfg_ua.cb.on_call_replace_request = &cb_on_call_replace_request; - cfg_ua.cb.on_call_replaced = &cb_on_call_replaced; - cfg_ua.cb.on_reg_state = &cb_on_reg_state; - cfg_ua.cb.on_incoming_subscribe = &cb_on_incoming_subscribe; - cfg_ua.cb.on_buddy_state = &cb_on_buddy_state; - cfg_ua.cb.on_pager2 = &cb_on_pager; - cfg_ua.cb.on_pager_status2 = &cb_on_pager_status; - cfg_ua.cb.on_typing2 = &cb_on_typing; - cfg_ua.cb.on_mwi_info = &cb_on_mwi_info; + PyObj_pjsua_config *obj_ua_cfg = (PyObj_pjsua_config*)o_ua_cfg; + + PyObj_pjsua_config_export(&cfg_ua, obj_ua_cfg); + + Py_XDECREF(g_obj_callback); + g_obj_callback = obj_ua_cfg->cb; + Py_INCREF(g_obj_callback); + + cfg_ua.cb.on_call_state = &cb_on_call_state; + cfg_ua.cb.on_incoming_call = &cb_on_incoming_call; + cfg_ua.cb.on_call_media_state = &cb_on_call_media_state; + cfg_ua.cb.on_dtmf_digit = &cb_on_dtmf_digit; + cfg_ua.cb.on_call_transfer_request = &cb_on_call_transfer_request; + cfg_ua.cb.on_call_transfer_status = &cb_on_call_transfer_status; + cfg_ua.cb.on_call_replace_request = &cb_on_call_replace_request; + cfg_ua.cb.on_call_replaced = &cb_on_call_replaced; + cfg_ua.cb.on_reg_state = &cb_on_reg_state; + cfg_ua.cb.on_incoming_subscribe = &cb_on_incoming_subscribe; + cfg_ua.cb.on_buddy_state = &cb_on_buddy_state; + cfg_ua.cb.on_pager2 = &cb_on_pager; + cfg_ua.cb.on_pager_status2 = &cb_on_pager_status; + cfg_ua.cb.on_typing2 = &cb_on_typing; + cfg_ua.cb.on_mwi_info = &cb_on_mwi_info; p_cfg_ua = &cfg_ua; @@ -938,7 +937,7 @@ static PyObject *py_pjsua_init(PyObject *pSelf, PyObject *pArgs) } if (o_log_cfg != Py_None) { - PyObj_pjsua_logging_config * obj_log; + PyObj_pjsua_logging_config * obj_log; obj_log = (PyObj_pjsua_logging_config *)o_log_cfg; @@ -956,9 +955,9 @@ static PyObject *py_pjsua_init(PyObject *pSelf, PyObject *pArgs) } if (o_media_cfg != Py_None) { - PyObj_pjsua_media_config_export(&cfg_media, - (PyObj_pjsua_media_config*)o_media_cfg); - p_cfg_media = &cfg_media; + PyObj_pjsua_media_config_export(&cfg_media, + (PyObj_pjsua_media_config*)o_media_cfg); + p_cfg_media = &cfg_media; } else { p_cfg_media = NULL; @@ -1017,7 +1016,7 @@ static PyObject *py_pjsua_handle_events(PyObject *pSelf, PyObject *pArgs) } if (msec < 0) - msec = 0; + msec = 0; #if !NO_PJSIP_THREAD /* Since handle_events() will block, we must wrap it with ALLOW_THREADS @@ -1146,7 +1145,7 @@ static char pjsua_msg_data_init_doc[] = * py_pjsua_transport_config_default */ static PyObject *py_pjsua_transport_config_default(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { PyObj_pjsua_transport_config *obj; pjsua_transport_config cfg; @@ -1156,8 +1155,8 @@ static PyObject *py_pjsua_transport_config_default(PyObject *pSelf, pjsua_transport_config_default(&cfg); obj = (PyObj_pjsua_transport_config*) - PyObj_pjsua_transport_config_new(&PyTyp_pjsua_transport_config, - NULL, NULL); + PyObj_pjsua_transport_config_new(&PyTyp_pjsua_transport_config, + NULL, NULL); PyObj_pjsua_transport_config_import(obj, &cfg); return (PyObject *)obj; @@ -1181,10 +1180,10 @@ static PyObject *py_pjsua_transport_create(PyObject *pSelf, PyObject *pArgs) } if (pCfg != Py_None) { - PyObj_pjsua_transport_config *obj; + PyObj_pjsua_transport_config *obj; obj = (PyObj_pjsua_transport_config*)pCfg; - PyObj_pjsua_transport_config_export(&cfg, obj); + PyObj_pjsua_transport_config_export(&cfg, obj); status = pjsua_transport_create(type, &cfg, &id); } else { status = pjsua_transport_create(type, NULL, &id); @@ -1231,15 +1230,15 @@ static PyObject *py_pjsua_transport_get_info(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "i", &id)) { return NULL; - } + } - status = pjsua_transport_get_info(id, &info); + status = pjsua_transport_get_info(id, &info); if (status == PJ_SUCCESS) { - PyObj_pjsua_transport_info *obj; + PyObj_pjsua_transport_info *obj; obj = (PyObj_pjsua_transport_info *) - PyObj_pjsua_transport_info_new(&PyTyp_pjsua_transport_info, - NULL, NULL); - PyObj_pjsua_transport_info_import(obj, &info); + PyObj_pjsua_transport_info_new(&PyTyp_pjsua_transport_info, + NULL, NULL); + PyObj_pjsua_transport_info_import(obj, &info); return (PyObject*)obj; } else { return Py_BuildValue(""); @@ -1250,7 +1249,7 @@ static PyObject *py_pjsua_transport_get_info(PyObject *pSelf, PyObject *pArgs) * py_pjsua_transport_set_enable */ static PyObject *py_pjsua_transport_set_enable(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { pj_status_t status; int id; @@ -1279,8 +1278,8 @@ static PyObject *py_pjsua_transport_close(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "ii", &id, &force)) { return NULL; - } - status = pjsua_transport_close(id, force); + } + status = pjsua_transport_close(id, force); return Py_BuildValue("i", status); } @@ -1338,8 +1337,8 @@ static PyObject *py_pjsua_acc_config_default(PyObject *pSelf, PyObject *pArgs) pjsua_acc_config_default(&cfg); obj = (PyObj_pjsua_acc_config *) - PyObj_pjsua_acc_config_new(&PyTyp_pjsua_acc_config, - NULL, NULL); + PyObj_pjsua_acc_config_new(&PyTyp_pjsua_acc_config, + NULL, NULL); PyObj_pjsua_acc_config_import(obj, &cfg); return (PyObject *)obj; } @@ -1372,7 +1371,7 @@ static PyObject *py_pjsua_acc_is_valid(PyObject *pSelf, PyObject *pArgs) return NULL; } - is_valid = pjsua_acc_is_valid(id); + is_valid = pjsua_acc_is_valid(id); return Py_BuildValue("i", is_valid); } @@ -1390,7 +1389,7 @@ static PyObject *py_pjsua_acc_set_default(PyObject *pSelf, PyObject *pArgs) return NULL; } status = pjsua_acc_set_default(id); - + return Py_BuildValue("i", status); } @@ -1400,12 +1399,12 @@ static PyObject *py_pjsua_acc_set_default(PyObject *pSelf, PyObject *pArgs) static PyObject *py_pjsua_acc_get_default(PyObject *pSelf, PyObject *pArgs) { int id; - + PJ_UNUSED_ARG(pSelf); PJ_UNUSED_ARG(pArgs); id = pjsua_acc_get_default(); - + return Py_BuildValue("i", id); } @@ -1426,16 +1425,16 @@ static PyObject *py_pjsua_acc_add(PyObject *pSelf, PyObject *pArgs) } if (pCfg != Py_None) { - pjsua_acc_config cfg; - PyObj_pjsua_acc_config *ac; + pjsua_acc_config cfg; + PyObj_pjsua_acc_config *ac; - pjsua_acc_config_default(&cfg); + pjsua_acc_config_default(&cfg); ac = (PyObj_pjsua_acc_config *)pCfg; PyObj_pjsua_acc_config_export(&cfg, ac); status = pjsua_acc_add(&cfg, is_default, &acc_id); } else { status = PJ_EINVAL; - acc_id = PJSUA_INVALID_ID; + acc_id = PJSUA_INVALID_ID; } return Py_BuildValue("ii", status, acc_id); @@ -1450,13 +1449,13 @@ static PyObject *py_pjsua_acc_add_local(PyObject *pSelf, PyObject *pArgs) int tid; int acc_id; int status; - + PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &tid, &is_default)) { return NULL; } - + status = pjsua_acc_add_local(tid, is_default, &acc_id); return Py_BuildValue("ii", status, acc_id); @@ -1482,8 +1481,8 @@ static PyObject *py_pjsua_acc_set_user_data(PyObject *pSelf, PyObject *pArgs) status = pjsua_acc_set_user_data(acc_id, (void*)pUserData); if (status == PJ_SUCCESS) { - Py_XINCREF(pUserData); - Py_XDECREF(old_user_data); + Py_XINCREF(pUserData); + Py_XDECREF(old_user_data); } return Py_BuildValue("i", status); @@ -1535,7 +1534,7 @@ static PyObject *py_pjsua_acc_del(PyObject *pSelf, PyObject *pArgs) * py_pjsua_acc_modify */ static PyObject *py_pjsua_acc_modify(PyObject *pSelf, PyObject *pArgs) -{ +{ PyObject *pCfg; PyObj_pjsua_acc_config * ac; int acc_id; @@ -1548,9 +1547,9 @@ static PyObject *py_pjsua_acc_modify(PyObject *pSelf, PyObject *pArgs) } if (pCfg != Py_None) { - pjsua_acc_config cfg; + pjsua_acc_config cfg; - pjsua_acc_config_default(&cfg); + pjsua_acc_config_default(&cfg); ac = (PyObj_pjsua_acc_config*)pCfg; PyObj_pjsua_acc_config_export(&cfg, ac); @@ -1565,20 +1564,20 @@ static PyObject *py_pjsua_acc_modify(PyObject *pSelf, PyObject *pArgs) * py_pjsua_acc_set_online_status */ static PyObject *py_pjsua_acc_set_online_status(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { - int is_online; + int is_online; int acc_id; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &acc_id, &is_online)) { return NULL; } - + status = pjsua_acc_set_online_status(acc_id, is_online); - + return Py_BuildValue("i", status); } @@ -1586,20 +1585,20 @@ static PyObject *py_pjsua_acc_set_online_status(PyObject *pSelf, * py_pjsua_acc_set_online_status2 */ static PyObject *py_pjsua_acc_set_online_status2(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { - int is_online; + int is_online; int acc_id; int activity_id; const char *activity_text = NULL; const char *rpid_id = NULL; pjrpid_element rpid; - pj_status_t status; + pj_status_t status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "iiiss", &acc_id, &is_online, - &activity_id, &activity_text, &rpid_id)) + &activity_id, &activity_text, &rpid_id)) { return NULL; } @@ -1608,10 +1607,10 @@ static PyObject *py_pjsua_acc_set_online_status2(PyObject *pSelf, rpid.type = PJRPID_ELEMENT_TYPE_PERSON; rpid.activity = activity_id; if (activity_text) - rpid.note = pj_str((char*)activity_text); + rpid.note = pj_str((char*)activity_text); if (rpid_id) - rpid.id = pj_str((char*)rpid_id); + rpid.id = pj_str((char*)rpid_id); status = pjsua_acc_set_online_status2(acc_id, is_online, &rpid); @@ -1622,20 +1621,20 @@ static PyObject *py_pjsua_acc_set_online_status2(PyObject *pSelf, * py_pjsua_acc_set_registration */ static PyObject *py_pjsua_acc_set_registration(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { - int renew; + int renew; int acc_id; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &acc_id, &renew)) { return NULL; } - + status = pjsua_acc_set_registration(acc_id, renew); - + return Py_BuildValue("i", status); } @@ -1643,11 +1642,11 @@ static PyObject *py_pjsua_acc_set_registration(PyObject *pSelf, * py_pjsua_acc_get_info */ static PyObject *py_pjsua_acc_get_info(PyObject *pSelf, PyObject *pArgs) -{ +{ int acc_id; PyObj_pjsua_acc_info * obj; pjsua_acc_info info; - int status; + int status; PJ_UNUSED_ARG(pSelf); @@ -1657,12 +1656,12 @@ static PyObject *py_pjsua_acc_get_info(PyObject *pSelf, PyObject *pArgs) status = pjsua_acc_get_info(acc_id, &info); if (status == PJ_SUCCESS) { - obj = (PyObj_pjsua_acc_info*) - PyObj_pjsua_acc_info_new(&PyTyp_pjsua_acc_info, NULL, NULL); - PyObj_pjsua_acc_info_import(obj, &info); + obj = (PyObj_pjsua_acc_info*) + PyObj_pjsua_acc_info_new(&PyTyp_pjsua_acc_info, NULL, NULL); + PyObj_pjsua_acc_info_import(obj, &info); return (PyObject*)obj; } else { - return Py_BuildValue(""); + return Py_BuildValue(""); } } @@ -1682,7 +1681,7 @@ static PyObject *py_pjsua_enum_accs(PyObject *pSelf, PyObject *pArgs) c = PJ_ARRAY_SIZE(id); status = pjsua_enum_accs(id, &c); if (status != PJ_SUCCESS) - c = 0; + c = 0; list = PyList_New(c); for (i = 0; i < c; i++) { @@ -1707,20 +1706,20 @@ static PyObject *py_pjsua_acc_enum_info(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "")) { return NULL; - } + } c = PJ_ARRAY_SIZE(info); status = pjsua_acc_enum_info(info, &c); if (status != PJ_SUCCESS) - c = 0; + c = 0; list = PyList_New(c); for (i = 0; i < c; i++) { PyObj_pjsua_acc_info *obj; obj = (PyObj_pjsua_acc_info *) - PyObj_pjsua_acc_info_new(&PyTyp_pjsua_acc_info, NULL, NULL); + PyObj_pjsua_acc_info_new(&PyTyp_pjsua_acc_info, NULL, NULL); - PyObj_pjsua_acc_info_import(obj, &info[i]); + PyObj_pjsua_acc_info_import(obj, &info[i]); PyList_SetItem(list, i, (PyObject*)obj); } @@ -1732,15 +1731,15 @@ static PyObject *py_pjsua_acc_enum_info(PyObject *pSelf, PyObject *pArgs) * py_pjsua_acc_set_transport */ static PyObject *py_pjsua_acc_set_transport(PyObject *pSelf, PyObject *pArgs) -{ +{ int acc_id, transport_id; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &acc_id, &transport_id)) { return NULL; - } + } status = pjsua_acc_set_transport(acc_id, transport_id); @@ -1753,7 +1752,7 @@ static PyObject *py_pjsua_acc_set_transport(PyObject *pSelf, PyObject *pArgs) * py_pjsua_acc_pres_notify */ static PyObject *py_pjsua_acc_pres_notify(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { int acc_id, state; PyObject *arg_pres, *arg_msg_data, *arg_reason; @@ -1762,23 +1761,23 @@ static PyObject *py_pjsua_acc_pres_notify(PyObject *pSelf, pj_str_t reason; pj_bool_t with_body; pj_pool_t *pool = NULL; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "iOiOO", &acc_id, &arg_pres, - &state, &arg_reason, &arg_msg_data)) + &state, &arg_reason, &arg_msg_data)) { return NULL; - } + } srv_pres = (void*) PyLong_AsLong(arg_pres); with_body = (state != PJSIP_EVSUB_STATE_TERMINATED); if (arg_reason && PyString_Check(arg_reason)) { - reason = PyString_ToPJ(arg_reason); + reason = PyString_ToPJ(arg_reason); } else { - reason = pj_str(""); + reason = pj_str(""); } pjsua_msg_data_init(&msg_data); @@ -1791,11 +1790,11 @@ static PyObject *py_pjsua_acc_pres_notify(PyObject *pSelf, } status = pjsua_pres_notify(acc_id, (pjsua_srv_pres*)srv_pres, - (pjsip_evsub_state)state, NULL, - &reason, with_body, &msg_data); + (pjsip_evsub_state)state, NULL, + &reason, with_body, &msg_data); if (pool) { - pj_pool_release(pool); + pj_pool_release(pool); } return Py_BuildValue("i", status); @@ -1866,9 +1865,9 @@ static char pjsua_acc_enum_info_doc[] = * py_pjsua_buddy_config_default */ static PyObject *py_pjsua_buddy_config_default(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { - PyObj_pjsua_buddy_config *obj; + PyObj_pjsua_buddy_config *obj; pjsua_buddy_config cfg; PJ_UNUSED_ARG(pSelf); @@ -1876,7 +1875,7 @@ static PyObject *py_pjsua_buddy_config_default(PyObject *pSelf, pjsua_buddy_config_default(&cfg); obj = (PyObj_pjsua_buddy_config *) - PyObj_pjsua_buddy_config_new(&PyTyp_pjsua_buddy_config, NULL, NULL); + PyObj_pjsua_buddy_config_new(&PyTyp_pjsua_buddy_config, NULL, NULL); PyObj_pjsua_buddy_config_import(obj, &cfg); return (PyObject *)obj; @@ -1907,7 +1906,7 @@ static PyObject *py_pjsua_buddy_is_valid(PyObject *pSelf, PyObject *pArgs) return NULL; } is_valid = pjsua_buddy_is_valid(id); - + return Py_BuildValue("i", is_valid); } @@ -1927,7 +1926,7 @@ static PyObject *py_pjsua_enum_buddies(PyObject *pSelf, PyObject *pArgs) c = PJ_ARRAY_SIZE(id); status = pjsua_enum_buddies(id, &c); if (status != PJ_SUCCESS) - c = 0; + c = 0; list = PyList_New(c); for (i = 0; i < c; i++) { @@ -1953,7 +1952,7 @@ static PyObject *py_pjsua_buddy_find(PyObject *pSelf, PyObject *pArgs) } if (!PyString_Check(pURI)) - return Py_BuildValue("i", PJSUA_INVALID_ID); + return Py_BuildValue("i", PJSUA_INVALID_ID); uri = PyString_ToPJ(pURI); buddy_id = pjsua_buddy_find(&uri); @@ -1965,10 +1964,10 @@ static PyObject *py_pjsua_buddy_find(PyObject *pSelf, PyObject *pArgs) * py_pjsua_buddy_get_info */ static PyObject *py_pjsua_buddy_get_info(PyObject *pSelf, PyObject *pArgs) -{ +{ int buddy_id; pjsua_buddy_info info; - int status; + int status; PJ_UNUSED_ARG(pSelf); @@ -1978,15 +1977,15 @@ static PyObject *py_pjsua_buddy_get_info(PyObject *pSelf, PyObject *pArgs) status = pjsua_buddy_get_info(buddy_id, &info); if (status == PJ_SUCCESS) { - PyObj_pjsua_buddy_info *obj; + PyObj_pjsua_buddy_info *obj; - obj = (PyObj_pjsua_buddy_info *) - PyObj_pjsua_buddy_config_new(&PyTyp_pjsua_buddy_info, - NULL, NULL); - PyObj_pjsua_buddy_info_import(obj, &info); + obj = (PyObj_pjsua_buddy_info *) + PyObj_pjsua_buddy_config_new(&PyTyp_pjsua_buddy_info, + NULL, NULL); + PyObj_pjsua_buddy_info_import(obj, &info); return (PyObject*)obj; } else { - return Py_BuildValue(""); + return Py_BuildValue(""); } } @@ -2006,19 +2005,19 @@ static PyObject *py_pjsua_buddy_add(PyObject *pSelf, PyObject *pArgs) } if (pCfg != Py_None) { - pjsua_buddy_config cfg; - PyObj_pjsua_buddy_config *bc; + pjsua_buddy_config cfg; + PyObj_pjsua_buddy_config *bc; bc = (PyObj_pjsua_buddy_config *)pCfg; - pjsua_buddy_config_default(&cfg); + pjsua_buddy_config_default(&cfg); PyObj_pjsua_buddy_config_export(&cfg, bc); status = pjsua_buddy_add(&cfg, &buddy_id); } else { status = PJ_EINVAL; - buddy_id = PJSUA_INVALID_ID; + buddy_id = PJSUA_INVALID_ID; } return Py_BuildValue("ii", status, buddy_id); } @@ -2062,7 +2061,7 @@ static PyObject *py_pjsua_buddy_set_user_data(PyObject *pSelf, PyObject *pArgs) } if (!pjsua_buddy_is_valid(buddy_id)) { - return Py_BuildValue("i", 0); + return Py_BuildValue("i", 0); } old_user_data = (PyObject*) pjsua_buddy_get_user_data(buddy_id); @@ -2070,8 +2069,8 @@ static PyObject *py_pjsua_buddy_set_user_data(PyObject *pSelf, PyObject *pArgs) status = pjsua_buddy_set_user_data(buddy_id, (void*)user_data); if (status == PJ_SUCCESS) { - Py_XINCREF(user_data); - Py_XDECREF(old_user_data); + Py_XINCREF(user_data); + Py_XDECREF(old_user_data); } return Py_BuildValue("i", status); @@ -2100,7 +2099,7 @@ static PyObject *py_pjsua_buddy_get_user_data(PyObject *pSelf, PyObject *pArgs) * py_pjsua_buddy_subscribe_pres */ static PyObject *py_pjsua_buddy_subscribe_pres(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { int buddy_id; int status; @@ -2130,7 +2129,7 @@ static PyObject *py_pjsua_pres_dump(PyObject *pSelf, PyObject *pArgs) return NULL; } - pjsua_pres_dump(verbose); + pjsua_pres_dump(verbose); return Py_BuildValue(""); } @@ -2155,14 +2154,14 @@ static PyObject *py_pjsua_im_send(PyObject *pSelf, PyObject *pArgs) PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "iOOOOi", &acc_id, - &pTo, &pMimeType, &pContent, &pMsgData, &user_data)) + &pTo, &pMimeType, &pContent, &pMsgData, &user_data)) { return NULL; } if (pMimeType != Py_None) { mime_type = &tmp_mime_type; - tmp_mime_type = PyString_ToPJ(pMimeType); + tmp_mime_type = PyString_ToPJ(pMimeType); } else { mime_type = NULL; } @@ -2173,19 +2172,19 @@ static PyObject *py_pjsua_im_send(PyObject *pSelf, PyObject *pArgs) pjsua_msg_data_init(&msg_data); if (pMsgData != Py_None) { - PyObj_pjsua_msg_data *omd; + PyObj_pjsua_msg_data *omd; omd = (PyObj_pjsua_msg_data *)pMsgData; - msg_data.content_type = PyString_ToPJ(omd->content_type); - msg_data.msg_body = PyString_ToPJ(omd->msg_body); + msg_data.content_type = PyString_ToPJ(omd->content_type); + msg_data.msg_body = PyString_ToPJ(omd->msg_body); pool = pjsua_pool_create("pytmp", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); } status = pjsua_im_send(acc_id, &to, mime_type, &content, - &msg_data, (void*)(long)user_data); + &msg_data, (void*)(long)user_data); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return Py_BuildValue("i",status); } @@ -2207,21 +2206,21 @@ static PyObject *py_pjsua_im_typing(PyObject *pSelf, PyObject *pArgs) PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "iOiO", &acc_id, &pTo, &is_typing, - &pMsgData)) + &pMsgData)) { return NULL; } - + to = PyString_ToPJ(pTo); pjsua_msg_data_init(&msg_data); if (pMsgData != Py_None) { - PyObj_pjsua_msg_data *omd; + PyObj_pjsua_msg_data *omd; omd = (PyObj_pjsua_msg_data *)pMsgData; - msg_data.content_type = PyString_ToPJ(omd->content_type); - msg_data.msg_body = PyString_ToPJ(omd->msg_body); + msg_data.content_type = PyString_ToPJ(omd->content_type); + msg_data.msg_body = PyString_ToPJ(omd->msg_body); pool = pjsua_pool_create("pytmp", POOL_SIZE, POOL_SIZE); translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); @@ -2230,7 +2229,7 @@ static PyObject *py_pjsua_im_typing(PyObject *pSelf, PyObject *pArgs) status = pjsua_im_typing(acc_id, &to, is_typing, &msg_data); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return Py_BuildValue("i", status); } @@ -2292,7 +2291,7 @@ static PyObject *py_pjsua_conf_get_max_ports(PyObject *pSelf, PyObject *pArgs) * py_pjsua_conf_get_active_ports */ static PyObject *py_pjsua_conf_get_active_ports(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { PJ_UNUSED_ARG(pSelf); PJ_UNUSED_ARG(pArgs); @@ -2316,7 +2315,7 @@ static PyObject *py_pjsua_enum_conf_ports(PyObject *pSelf, PyObject *pArgs) c = PJ_ARRAY_SIZE(id); status = pjsua_enum_conf_ports(id, &c); if (status != PJ_SUCCESS) - c = 0; + c = 0; list = PyList_New(c); for (i = 0; i < c; i++) { @@ -2330,7 +2329,7 @@ static PyObject *py_pjsua_enum_conf_ports(PyObject *pSelf, PyObject *pArgs) * py_pjsua_conf_get_port_info */ static PyObject *py_pjsua_conf_get_port_info(PyObject *pSelf, PyObject *pArgs) -{ +{ int id; PyObj_pjsua_conf_port_info *ret; pjsua_conf_port_info info; @@ -2344,7 +2343,7 @@ static PyObject *py_pjsua_conf_get_port_info(PyObject *pSelf, PyObject *pArgs) pjsua_conf_get_port_info(id, &info); ret = (PyObj_pjsua_conf_port_info *) - conf_port_info_new(&PyTyp_pjsua_conf_port_info, NULL, NULL); + conf_port_info_new(&PyTyp_pjsua_conf_port_info, NULL, NULL); ret->bits_per_sample = info.bits_per_sample; ret->channel_count = info.channel_count; ret->clock_rate = info.clock_rate; @@ -2354,8 +2353,8 @@ static PyObject *py_pjsua_conf_get_port_info(PyObject *pSelf, PyObject *pArgs) Py_XDECREF(ret->listeners); ret->listeners = PyList_New(info.listener_cnt); for (i = 0; i < info.listener_cnt; i++) { - PyObject *item = Py_BuildValue("i",info.listeners[i]); - PyList_SetItem(ret->listeners, i, item); + PyObject *item = Py_BuildValue("i",info.listeners[i]); + PyList_SetItem(ret->listeners, i, item); } return (PyObject*)ret; } @@ -2364,15 +2363,15 @@ static PyObject *py_pjsua_conf_get_port_info(PyObject *pSelf, PyObject *pArgs) * py_pjsua_conf_remove_port */ static PyObject *py_pjsua_conf_remove_port(PyObject *pSelf, PyObject *pArgs) -{ +{ int id; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "i", &id)) { return NULL; - } + } status = pjsua_conf_remove_port(id); @@ -2383,15 +2382,15 @@ static PyObject *py_pjsua_conf_remove_port(PyObject *pSelf, PyObject *pArgs) * py_pjsua_conf_connect */ static PyObject *py_pjsua_conf_connect(PyObject *pSelf, PyObject *pArgs) -{ +{ int source, sink; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &source, &sink)) { return NULL; - } + } status = pjsua_conf_connect(source, sink); @@ -2402,15 +2401,15 @@ static PyObject *py_pjsua_conf_connect(PyObject *pSelf, PyObject *pArgs) * py_pjsua_conf_disconnect */ static PyObject *py_pjsua_conf_disconnect(PyObject *pSelf, PyObject *pArgs) -{ +{ int source, sink; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &source, &sink)) { return NULL; - } + } status = pjsua_conf_disconnect(source, sink); @@ -2421,16 +2420,16 @@ static PyObject *py_pjsua_conf_disconnect(PyObject *pSelf, PyObject *pArgs) * py_pjsua_conf_set_tx_level */ static PyObject *py_pjsua_conf_set_tx_level(PyObject *pSelf, PyObject *pArgs) -{ +{ int slot; float level; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "if", &slot, &level)) { return NULL; - } + } status = pjsua_conf_adjust_tx_level(slot, level); @@ -2441,16 +2440,16 @@ static PyObject *py_pjsua_conf_set_tx_level(PyObject *pSelf, PyObject *pArgs) * py_pjsua_conf_set_rx_level */ static PyObject *py_pjsua_conf_set_rx_level(PyObject *pSelf, PyObject *pArgs) -{ +{ int slot; float level; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "if", &slot, &level)) { return NULL; - } + } status = pjsua_conf_adjust_rx_level(slot, level); @@ -2461,34 +2460,34 @@ static PyObject *py_pjsua_conf_set_rx_level(PyObject *pSelf, PyObject *pArgs) * py_pjsua_conf_get_signal_level */ static PyObject *py_pjsua_conf_get_signal_level(PyObject *pSelf, - PyObject *pArgs) -{ + PyObject *pArgs) +{ int slot; unsigned tx_level, rx_level; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "i", &slot)) { return NULL; - } + } status = pjsua_conf_get_signal_level(slot, &tx_level, &rx_level); return Py_BuildValue("iff", status, (float)(tx_level/255.0), - (float)(rx_level/255.0)); + (float)(rx_level/255.0)); } /* * py_pjsua_player_create */ static PyObject *py_pjsua_player_create(PyObject *pSelf, PyObject *pArgs) -{ +{ int id; int options; PyObject *pFilename; pj_str_t filename; - int status; + int status; PJ_UNUSED_ARG(pSelf); @@ -2506,14 +2505,14 @@ static PyObject *py_pjsua_player_create(PyObject *pSelf, PyObject *pArgs) * py_pjsua_playlist_create */ static PyObject *py_pjsua_playlist_create(PyObject *pSelf, PyObject *pArgs) -{ +{ int id; int options; PyObject *pLabel, *pFileList; pj_str_t label; int count; pj_str_t files[64]; - int status; + int status; PJ_UNUSED_ARG(pSelf); @@ -2523,13 +2522,13 @@ static PyObject *py_pjsua_playlist_create(PyObject *pSelf, PyObject *pArgs) label = PyString_ToPJ(pLabel); if (!PyList_Check(pFileList)) - return Py_BuildValue("ii", PJ_EINVAL, PJSUA_INVALID_ID); + return Py_BuildValue("ii", PJ_EINVAL, PJSUA_INVALID_ID); count = 0; for (count=0; countdefault_samples_per_sec = info[i].default_samples_per_sec; obj->input_count = info[i].input_count; obj->output_count = info[i].output_count; @@ -2707,7 +2706,7 @@ static PyObject *py_pjsua_enum_snd_devs(PyObject *pSelf, PyObject *pArgs) * py_pjsua_get_snd_dev */ static PyObject *py_pjsua_get_snd_dev(PyObject *pSelf, PyObject *pArgs) -{ +{ int capture_dev, playback_dev; PJ_UNUSED_ARG(pSelf); @@ -2722,15 +2721,15 @@ static PyObject *py_pjsua_get_snd_dev(PyObject *pSelf, PyObject *pArgs) * py_pjsua_set_snd_dev */ static PyObject *py_pjsua_set_snd_dev(PyObject *pSelf, PyObject *pArgs) -{ +{ int capture_dev, playback_dev; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &capture_dev, &playback_dev)) { return NULL; - } + } status = pjsua_set_snd_dev(capture_dev, playback_dev); @@ -2741,8 +2740,8 @@ static PyObject *py_pjsua_set_snd_dev(PyObject *pSelf, PyObject *pArgs) * py_pjsua_set_null_snd_dev */ static PyObject *py_pjsua_set_null_snd_dev(PyObject *pSelf, PyObject *pArgs) -{ - int status; +{ + int status; PJ_UNUSED_ARG(pSelf); PJ_UNUSED_ARG(pArgs); @@ -2756,16 +2755,16 @@ static PyObject *py_pjsua_set_null_snd_dev(PyObject *pSelf, PyObject *pArgs) * py_pjsua_set_ec */ static PyObject *py_pjsua_set_ec(PyObject *pSelf, PyObject *pArgs) -{ +{ int options; int tail_ms; - int status; + int status; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "ii", &tail_ms, &options)) { return NULL; - } + } status = pjsua_set_ec(tail_ms, options); @@ -2776,8 +2775,8 @@ static PyObject *py_pjsua_set_ec(PyObject *pSelf, PyObject *pArgs) * py_pjsua_get_ec_tail */ static PyObject *py_pjsua_get_ec_tail(PyObject *pSelf, PyObject *pArgs) -{ - int status; +{ + int status; unsigned tail_ms; PJ_UNUSED_ARG(pSelf); @@ -2785,7 +2784,7 @@ static PyObject *py_pjsua_get_ec_tail(PyObject *pSelf, PyObject *pArgs) status = pjsua_get_ec_tail(&tail_ms); if (status != PJ_SUCCESS) - tail_ms = 0; + tail_ms = 0; return Py_BuildValue("i", tail_ms); } @@ -2806,13 +2805,13 @@ static PyObject *py_pjsua_enum_codecs(PyObject *pSelf, PyObject *pArgs) c = PJ_ARRAY_SIZE(info); status = pjsua_enum_codecs(info, &c); if (status != PJ_SUCCESS) - c = 0; + c = 0; ret = PyList_New(c); for (i = 0; i < c; i++) { PyObj_pjsua_codec_info * obj; obj = (PyObj_pjsua_codec_info *) - codec_info_new(&PyTyp_pjsua_codec_info, NULL, NULL); + codec_info_new(&PyTyp_pjsua_codec_info, NULL, NULL); obj->codec_id = PyString_FromPJ(&info[i].codec_id); obj->priority = info[i].priority; @@ -2826,8 +2825,8 @@ static PyObject *py_pjsua_enum_codecs(PyObject *pSelf, PyObject *pArgs) * py_pjsua_codec_set_priority */ static PyObject *py_pjsua_codec_set_priority(PyObject *pSelf, PyObject *pArgs) -{ - int status; +{ + int status; PyObject *pCodecId; pj_str_t codec_id; int priority; @@ -2840,9 +2839,9 @@ static PyObject *py_pjsua_codec_set_priority(PyObject *pSelf, PyObject *pArgs) codec_id = PyString_ToPJ(pCodecId); if (priority < 0) - priority = 0; + priority = 0; if (priority > 255) - priority = 255; + priority = 255; status = pjsua_codec_set_priority(&codec_id, (pj_uint8_t)priority); @@ -2853,8 +2852,8 @@ static PyObject *py_pjsua_codec_set_priority(PyObject *pSelf, PyObject *pArgs) * py_pjsua_codec_get_param */ static PyObject *py_pjsua_codec_get_param(PyObject *pSelf, PyObject *pArgs) -{ - int status; +{ + int status; PyObject *pCodecId; pj_str_t codec_id; pjmedia_codec_param param; @@ -2864,16 +2863,16 @@ static PyObject *py_pjsua_codec_get_param(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "O", &pCodecId)) { return NULL; - } + } codec_id = PyString_ToPJ(pCodecId); status = pjsua_codec_get_param(&codec_id, ¶m); if (status != PJ_SUCCESS) - return Py_BuildValue(""); + return Py_BuildValue(""); ret = (PyObj_pjmedia_codec_param *) - pjmedia_codec_param_new(&PyTyp_pjmedia_codec_param, NULL, NULL); + pjmedia_codec_param_new(&PyTyp_pjmedia_codec_param, NULL, NULL); ret->info->avg_bps = param.info.avg_bps; ret->info->channel_cnt = param.info.channel_cnt; @@ -2897,8 +2896,8 @@ static PyObject *py_pjsua_codec_get_param(PyObject *pSelf, PyObject *pArgs) * py_pjsua_codec_set_param */ static PyObject *py_pjsua_codec_set_param(PyObject *pSelf, PyObject *pArgs) -{ - int status; +{ + int status; PyObject *pCodecId, *pCodecParam; pj_str_t codec_id; pjmedia_codec_param param; @@ -2907,12 +2906,12 @@ static PyObject *py_pjsua_codec_set_param(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "OO", &pCodecId, &pCodecParam)) { return NULL; - } + } codec_id = PyString_ToPJ(pCodecId); if (pCodecParam != Py_None) { - PyObj_pjmedia_codec_param *obj; + PyObj_pjmedia_codec_param *obj; obj = (PyObj_pjmedia_codec_param *)pCodecParam; @@ -3042,7 +3041,7 @@ static char pjsua_codec_set_param_doc[] = * py_pjsua_call_get_max_count */ static PyObject *py_pjsua_call_get_max_count(PyObject *pSelf, PyObject *pArgs) -{ +{ int count; PJ_UNUSED_ARG(pSelf); @@ -3057,8 +3056,8 @@ static PyObject *py_pjsua_call_get_max_count(PyObject *pSelf, PyObject *pArgs) * py_pjsua_call_get_count */ static PyObject *py_pjsua_call_get_count(PyObject *pSelf, PyObject *pArgs) -{ - int count; +{ + int count; PJ_UNUSED_ARG(pSelf); PJ_UNUSED_ARG(pArgs); @@ -3084,7 +3083,7 @@ static PyObject *py_pjsua_enum_calls(PyObject *pSelf, PyObject *pArgs) c = PJ_ARRAY_SIZE(id); status = pjsua_enum_calls(id, &c); if (status != PJ_SUCCESS) - c = 0; + c = 0; ret = PyList_New(c); for (i = 0; i < c; i++) { @@ -3103,25 +3102,25 @@ static PyObject *py_pjsua_call_make_call(PyObject *pSelf, PyObject *pArgs) int acc_id; pj_str_t dst_uri; PyObject *pDstUri, *pMsgData, *pUserData; - pjsua_call_setting option; + pjsua_call_setting option; pjsua_msg_data msg_data; int call_id; pj_pool_t *pool = NULL; PJ_UNUSED_ARG(pSelf); - pjsua_call_setting_default(&option); - if (!PyArg_ParseTuple(pArgs, "iOIOO", &acc_id, &pDstUri, &option.flag, - &pUserData, &pMsgData)) + pjsua_call_setting_default(&option); + if (!PyArg_ParseTuple(pArgs, "iOIOO", &acc_id, &pDstUri, &option.flag, + &pUserData, &pMsgData)) { return NULL; } - + dst_uri = PyString_ToPJ(pDstUri); pjsua_msg_data_init(&msg_data); if (pMsgData != Py_None) { - PyObj_pjsua_msg_data * omd; + PyObj_pjsua_msg_data * omd; omd = (PyObj_pjsua_msg_data *)pMsgData; @@ -3134,23 +3133,23 @@ static PyObject *py_pjsua_call_make_call(PyObject *pSelf, PyObject *pArgs) Py_XINCREF(pUserData); status = pjsua_call_make_call(acc_id, &dst_uri, - &option, (void*)pUserData, - &msg_data, &call_id); + &option, (void*)pUserData, + &msg_data, &call_id); if (pool != NULL) - pj_pool_release(pool); + pj_pool_release(pool); if (status != PJ_SUCCESS) { - Py_XDECREF(pUserData); + Py_XDECREF(pUserData); } - return Py_BuildValue("ii", status, call_id); + return Py_BuildValue("ii", status, call_id); } /* * py_pjsua_call_is_active */ static PyObject *py_pjsua_call_is_active(PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; int is_active; @@ -3158,7 +3157,7 @@ static PyObject *py_pjsua_call_is_active(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "i", &call_id)) { return NULL; - } + } is_active = pjsua_call_is_active(call_id); @@ -3169,7 +3168,7 @@ static PyObject *py_pjsua_call_is_active(PyObject *pSelf, PyObject *pArgs) * py_pjsua_call_has_media */ static PyObject *py_pjsua_call_has_media(PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; int has_media; @@ -3177,7 +3176,7 @@ static PyObject *py_pjsua_call_has_media(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "i", &call_id)) { return NULL; - } + } has_media = pjsua_call_has_media(call_id); @@ -3188,7 +3187,7 @@ static PyObject *py_pjsua_call_has_media(PyObject *pSelf, PyObject *pArgs) * py_pjsua_call_get_conf_port */ static PyObject* py_pjsua_call_get_conf_port(PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; int port_id; @@ -3207,7 +3206,7 @@ static PyObject* py_pjsua_call_get_conf_port(PyObject *pSelf, PyObject *pArgs) * py_pjsua_call_get_info */ static PyObject* py_pjsua_call_get_info(PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; int status; PyObj_pjsua_call_info *ret; @@ -3217,22 +3216,22 @@ static PyObject* py_pjsua_call_get_info(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "i", &call_id)) { return NULL; - } + } status = pjsua_call_get_info(call_id, &info); if (status != PJ_SUCCESS) - return Py_BuildValue(""); + return Py_BuildValue(""); ret = (PyObj_pjsua_call_info *)call_info_new(&PyTyp_pjsua_call_info, - NULL, NULL); + NULL, NULL); ret->acc_id = info.acc_id; Py_XDECREF(ret->call_id); ret->call_id = PyString_FromPJ(&info.call_id); ret->conf_slot = info.conf_slot; ret->connect_duration = info.connect_duration.sec * 1000 + - info.connect_duration.msec; + info.connect_duration.msec; ret->total_duration = info.total_duration.sec * 1000 + - info.total_duration.msec; + info.total_duration.msec; ret->id = info.id; ret->last_status = info.last_status; Py_XDECREF(ret->last_status_text); @@ -3259,7 +3258,7 @@ static PyObject* py_pjsua_call_get_info(PyObject *pSelf, PyObject *pArgs) * py_pjsua_call_set_user_data */ static PyObject *py_pjsua_call_set_user_data(PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; PyObject *pUserData, *old_user_data; int status; @@ -3273,7 +3272,7 @@ static PyObject *py_pjsua_call_set_user_data(PyObject *pSelf, PyObject *pArgs) old_user_data = (PyObject*) pjsua_call_get_user_data(call_id); if (old_user_data == pUserData) { - return Py_BuildValue("i", PJ_SUCCESS); + return Py_BuildValue("i", PJ_SUCCESS); } Py_XINCREF(pUserData); @@ -3282,7 +3281,7 @@ static PyObject *py_pjsua_call_set_user_data(PyObject *pSelf, PyObject *pArgs) status = pjsua_call_set_user_data(call_id, (void*)pUserData); if (status != PJ_SUCCESS) { - Py_XDECREF(pUserData); + Py_XDECREF(pUserData); } return Py_BuildValue("i", status); @@ -3292,15 +3291,15 @@ static PyObject *py_pjsua_call_set_user_data(PyObject *pSelf, PyObject *pArgs) * py_pjsua_call_get_user_data */ static PyObject *py_pjsua_call_get_user_data(PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; - PyObject *user_data; + PyObject *user_data; PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "i", &call_id)) { return NULL; - } + } user_data = (PyObject*)pjsua_call_get_user_data(call_id); return user_data ? Py_BuildValue("O", user_data) : Py_BuildValue(""); @@ -3329,13 +3328,13 @@ static PyObject *py_pjsua_call_answer(PyObject *pSelf, PyObject *pArgs) if (pReason == Py_None) { reason = NULL; } else { - reason = &tmp_reason; + reason = &tmp_reason; tmp_reason = PyString_ToPJ(pReason); } pjsua_msg_data_init(&msg_data); if (omdObj != Py_None) { - PyObj_pjsua_msg_data *omd; + PyObj_pjsua_msg_data *omd; omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type = PyString_ToPJ(omd->content_type); @@ -3344,10 +3343,10 @@ static PyObject *py_pjsua_call_answer(PyObject *pSelf, PyObject *pArgs) translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); } - status = pjsua_call_answer(call_id, code, reason, &msg_data); + status = pjsua_call_answer(call_id, code, reason, &msg_data); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return Py_BuildValue("i", status); } @@ -3369,7 +3368,7 @@ static PyObject *py_pjsua_call_hangup(PyObject *pSelf, PyObject *pArgs) PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "iIOO", &call_id, &code, &pReason, - &omdObj)) + &omdObj)) { return NULL; } @@ -3383,7 +3382,7 @@ static PyObject *py_pjsua_call_hangup(PyObject *pSelf, PyObject *pArgs) pjsua_msg_data_init(&msg_data); if (omdObj != Py_None) { - PyObj_pjsua_msg_data *omd; + PyObj_pjsua_msg_data *omd; omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type = PyString_ToPJ(omd->content_type); @@ -3394,7 +3393,7 @@ static PyObject *py_pjsua_call_hangup(PyObject *pSelf, PyObject *pArgs) status = pjsua_call_hangup(call_id, code, reason, &msg_data); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return Py_BuildValue("i", status); } @@ -3418,7 +3417,7 @@ static PyObject *py_pjsua_call_set_hold(PyObject *pSelf, PyObject *pArgs) pjsua_msg_data_init(&msg_data); if (omdObj != Py_None) { - PyObj_pjsua_msg_data *omd; + PyObj_pjsua_msg_data *omd; omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type = PyString_ToPJ(omd->content_type); @@ -3455,7 +3454,7 @@ static PyObject *py_pjsua_call_reinvite(PyObject *pSelf, PyObject *pArgs) pjsua_msg_data_init(&msg_data); if (omdObj != Py_None) { - PyObj_pjsua_msg_data *omd; + PyObj_pjsua_msg_data *omd; omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type = PyString_ToPJ(omd->content_type); @@ -3492,7 +3491,7 @@ static PyObject *py_pjsua_call_update(PyObject *pSelf, PyObject *pArgs) pjsua_msg_data_init(&msg_data); if (omdObj != Py_None) { - PyObj_pjsua_msg_data *omd; + PyObj_pjsua_msg_data *omd; omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type = PyString_ToPJ(omd->content_type); @@ -3501,7 +3500,7 @@ static PyObject *py_pjsua_call_update(PyObject *pSelf, PyObject *pArgs) translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); } - status = pjsua_call_update(call_id, option, &msg_data); + status = pjsua_call_update(call_id, option, &msg_data); if (pool) pj_pool_release(pool); @@ -3529,14 +3528,14 @@ static PyObject *py_pjsua_call_send_request(PyObject *pSelf, PyObject *pArgs) } if (!PyString_Check(pMethod)) { - return NULL; + return NULL; } method = PyString_ToPJ(pMethod); pjsua_msg_data_init(&msg_data); if (omdObj != Py_None) { - PyObj_pjsua_msg_data *omd; + PyObj_pjsua_msg_data *omd; omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type = PyString_ToPJ(omd->content_type); @@ -3545,7 +3544,7 @@ static PyObject *py_pjsua_call_send_request(PyObject *pSelf, PyObject *pArgs) translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); } - status = pjsua_call_send_request(call_id, &method, &msg_data); + status = pjsua_call_send_request(call_id, &method, &msg_data); if (pool) pj_pool_release(pool); @@ -3573,13 +3572,13 @@ static PyObject *py_pjsua_call_xfer(PyObject *pSelf, PyObject *pArgs) } if (!PyString_Check(pDstUri)) - return NULL; + return NULL; dest = PyString_ToPJ(pDstUri); pjsua_msg_data_init(&msg_data); if (omdObj != Py_None) { - PyObj_pjsua_msg_data *omd; + PyObj_pjsua_msg_data *omd; omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type = PyString_ToPJ(omd->content_type); @@ -3612,7 +3611,7 @@ static PyObject *py_pjsua_call_xfer_replaces(PyObject *pSelf, PyObject *pArgs) PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "iiIO", &call_id, &dest_call_id, - &options, &omdObj)) + &options, &omdObj)) { return NULL; } @@ -3620,7 +3619,7 @@ static PyObject *py_pjsua_call_xfer_replaces(PyObject *pSelf, PyObject *pArgs) pjsua_msg_data_init(&msg_data); if (omdObj != Py_None) { - PyObj_pjsua_msg_data *omd; + PyObj_pjsua_msg_data *omd; omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type = PyString_ToPJ(omd->content_type); @@ -3630,10 +3629,10 @@ static PyObject *py_pjsua_call_xfer_replaces(PyObject *pSelf, PyObject *pArgs) } status = pjsua_call_xfer_replaces(call_id, dest_call_id, options, - &msg_data); + &msg_data); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return Py_BuildValue("i", status); } @@ -3642,7 +3641,7 @@ static PyObject *py_pjsua_call_xfer_replaces(PyObject *pSelf, PyObject *pArgs) * py_pjsua_call_dial_dtmf */ static PyObject *py_pjsua_call_dial_dtmf(PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; PyObject *pDigits; pj_str_t digits; @@ -3655,7 +3654,7 @@ static PyObject *py_pjsua_call_dial_dtmf(PyObject *pSelf, PyObject *pArgs) } if (!PyString_Check(pDigits)) - return Py_BuildValue("i", PJ_EINVAL); + return Py_BuildValue("i", PJ_EINVAL); digits = PyString_ToPJ(pDigits); status = pjsua_call_dial_dtmf(call_id, &digits); @@ -3680,13 +3679,13 @@ static PyObject *py_pjsua_call_send_im(PyObject *pSelf, PyObject *pArgs) PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "iOOOi", &call_id, &pMimeType, &pContent, - &omdObj, &user_data)) + &omdObj, &user_data)) { return NULL; } if (!PyString_Check(pContent)) - return Py_BuildValue("i", PJ_EINVAL); + return Py_BuildValue("i", PJ_EINVAL); content = PyString_ToPJ(pContent); @@ -3694,12 +3693,12 @@ static PyObject *py_pjsua_call_send_im(PyObject *pSelf, PyObject *pArgs) mime_type = &tmp_mime_type; tmp_mime_type = PyString_ToPJ(pMimeType); } else { - mime_type = NULL; + mime_type = NULL; } pjsua_msg_data_init(&msg_data); if (omdObj != Py_None) { - PyObj_pjsua_msg_data * omd; + PyObj_pjsua_msg_data * omd; omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type = PyString_ToPJ(omd->content_type); @@ -3709,7 +3708,7 @@ static PyObject *py_pjsua_call_send_im(PyObject *pSelf, PyObject *pArgs) } status = pjsua_call_send_im(call_id, mime_type, &content, - &msg_data, (void*)(long)user_data); + &msg_data, (void*)(long)user_data); if (pool) pj_pool_release(pool); @@ -3721,7 +3720,7 @@ static PyObject *py_pjsua_call_send_im(PyObject *pSelf, PyObject *pArgs) * py_pjsua_call_send_typing_ind */ static PyObject *py_pjsua_call_send_typing_ind(PyObject *pSelf, - PyObject *pArgs) + PyObject *pArgs) { int status; int call_id; @@ -3735,10 +3734,10 @@ static PyObject *py_pjsua_call_send_typing_ind(PyObject *pSelf, if (!PyArg_ParseTuple(pArgs, "iiO", &call_id, &is_typing, &omdObj)) { return NULL; } - + pjsua_msg_data_init(&msg_data); if (omdObj != Py_None) { - PyObj_pjsua_msg_data *omd; + PyObj_pjsua_msg_data *omd; omd = (PyObj_pjsua_msg_data *)omdObj; msg_data.content_type = PyString_ToPJ(omd->content_type); @@ -3747,7 +3746,7 @@ static PyObject *py_pjsua_call_send_typing_ind(PyObject *pSelf, translate_hdr(pool, &msg_data.hdr_list, omd->hdr_list); } - status = pjsua_call_send_typing_ind(call_id, is_typing, &msg_data); + status = pjsua_call_send_typing_ind(call_id, is_typing, &msg_data); if (pool) pj_pool_release(pool); @@ -3759,7 +3758,7 @@ static PyObject *py_pjsua_call_send_typing_ind(PyObject *pSelf, * py_pjsua_call_hangup_all */ static PyObject *py_pjsua_call_hangup_all(PyObject *pSelf, PyObject *pArgs) -{ +{ PJ_UNUSED_ARG(pSelf); PJ_UNUSED_ARG(pArgs); @@ -3772,7 +3771,7 @@ static PyObject *py_pjsua_call_hangup_all(PyObject *pSelf, PyObject *pArgs) * py_pjsua_call_dump */ static PyObject *py_pjsua_call_dump(PyObject *pSelf, PyObject *pArgs) -{ +{ int call_id; int with_media; PyObject *ret; @@ -3785,18 +3784,18 @@ static PyObject *py_pjsua_call_dump(PyObject *pSelf, PyObject *pArgs) PJ_UNUSED_ARG(pSelf); if (!PyArg_ParseTuple(pArgs, "iiIO", &call_id, &with_media, - &maxlen, &pIndent)) + &maxlen, &pIndent)) { return NULL; - } + } buffer = (char*) malloc(maxlen * sizeof(char)); indent = PyString_AsString(pIndent); status = pjsua_call_dump(call_id, with_media, buffer, maxlen, indent); if (status != PJ_SUCCESS) { - free(buffer); - return PyString_FromString(""); + free(buffer); + return PyString_FromString(""); } ret = PyString_FromString(buffer); @@ -3817,7 +3816,7 @@ static PyObject *py_pjsua_dump(PyObject *pSelf, PyObject *pArgs) if (!PyArg_ParseTuple(pArgs, "i", &detail)) { return NULL; - } + } pjsua_dump(detail); @@ -3871,9 +3870,9 @@ static PyObject *py_pj_parse_simple_sip(PyObject *pSelf, PyObject *pArgs) uri = pjsip_parse_uri(pool, tmp, strlen(tmp), 0); if (uri == NULL || (!PJSIP_URI_SCHEME_IS_SIP(uri) && - !PJSIP_URI_SCHEME_IS_SIPS(uri))) { - pj_pool_release(pool); - return Py_BuildValue(""); + !PJSIP_URI_SCHEME_IS_SIPS(uri))) { + pj_pool_release(pool); + return Py_BuildValue(""); } ret = PyTuple_New(5); @@ -3893,15 +3892,15 @@ static PyObject *py_pj_parse_simple_sip(PyObject *pSelf, PyObject *pArgs) /* Port */ if (sip_uri->port == 5060) { - sip_uri->port = 0; + sip_uri->port = 0; } item = Py_BuildValue("i", sip_uri->port); PyTuple_SetItem(ret, 3, item); /* Transport */ if (pj_stricmp2(&sip_uri->transport_param, "udp")) { - sip_uri->transport_param.ptr = ""; - sip_uri->transport_param.slen = 0; + sip_uri->transport_param.ptr = ""; + sip_uri->transport_param.slen = 0; } item = PyString_FromPJ(&sip_uri->transport_param); PyTuple_SetItem(ret, 4, item); @@ -4003,49 +4002,49 @@ static PyMethodDef py_pjsua_methods[] = pjsua_thread_register_doc }, { - "perror", py_pjsua_perror, METH_VARARGS, pjsua_perror_doc + "perror", py_pjsua_perror, METH_VARARGS, pjsua_perror_doc }, { - "create", py_pjsua_create, METH_VARARGS, pjsua_create_doc + "create", py_pjsua_create, METH_VARARGS, pjsua_create_doc }, { - "init", py_pjsua_init, METH_VARARGS, pjsua_init_doc + "init", py_pjsua_init, METH_VARARGS, pjsua_init_doc }, { - "start", py_pjsua_start, METH_VARARGS, pjsua_start_doc + "start", py_pjsua_start, METH_VARARGS, pjsua_start_doc }, { - "destroy", py_pjsua_destroy, METH_VARARGS, pjsua_destroy_doc + "destroy", py_pjsua_destroy, METH_VARARGS, pjsua_destroy_doc }, { - "handle_events", py_pjsua_handle_events, METH_VARARGS, - pjsua_handle_events_doc + "handle_events", py_pjsua_handle_events, METH_VARARGS, + pjsua_handle_events_doc }, { - "verify_sip_url", py_pjsua_verify_sip_url, METH_VARARGS, - pjsua_verify_sip_url_doc + "verify_sip_url", py_pjsua_verify_sip_url, METH_VARARGS, + pjsua_verify_sip_url_doc }, { - "reconfigure_logging", py_pjsua_reconfigure_logging, METH_VARARGS, - pjsua_reconfigure_logging_doc + "reconfigure_logging", py_pjsua_reconfigure_logging, METH_VARARGS, + pjsua_reconfigure_logging_doc }, { - "logging_config_default", py_pjsua_logging_config_default, - METH_VARARGS, pjsua_logging_config_default_doc + "logging_config_default", py_pjsua_logging_config_default, + METH_VARARGS, pjsua_logging_config_default_doc }, { - "config_default", py_pjsua_config_default, METH_VARARGS, - pjsua_config_default_doc + "config_default", py_pjsua_config_default, METH_VARARGS, + pjsua_config_default_doc }, { - "media_config_default", py_pjsua_media_config_default, METH_VARARGS, - pjsua_media_config_default_doc + "media_config_default", py_pjsua_media_config_default, METH_VARARGS, + pjsua_media_config_default_doc }, { - "msg_data_init", py_pjsua_msg_data_init, METH_VARARGS, - pjsua_msg_data_init_doc + "msg_data_init", py_pjsua_msg_data_init, METH_VARARGS, + pjsua_msg_data_init_doc }, { "transport_config_default", py_pjsua_transport_config_default, @@ -4132,8 +4131,8 @@ static PyMethodDef py_pjsua_methods[] = pjsua_acc_get_info_doc }, { - "acc_pres_notify", py_pjsua_acc_pres_notify, METH_VARARGS, - "Accept or reject subscription request" + "acc_pres_notify", py_pjsua_acc_pres_notify, METH_VARARGS, + "Accept or reject subscription request" }, { "enum_accs", py_pjsua_enum_accs, METH_VARARGS, @@ -4232,18 +4231,18 @@ static PyMethodDef py_pjsua_methods[] = pjsua_conf_disconnect_doc }, { - "conf_set_tx_level", py_pjsua_conf_set_tx_level, METH_VARARGS, - "Adjust the signal level to be transmitted from the bridge to the" - " specified port by making it louder or quieter" + "conf_set_tx_level", py_pjsua_conf_set_tx_level, METH_VARARGS, + "Adjust the signal level to be transmitted from the bridge to the" + " specified port by making it louder or quieter" }, { - "conf_set_rx_level", py_pjsua_conf_set_rx_level, METH_VARARGS, - "Adjust the signal level to be received from the specified port (to" - " the bridge) by making it louder or quieter" + "conf_set_rx_level", py_pjsua_conf_set_rx_level, METH_VARARGS, + "Adjust the signal level to be received from the specified port (to" + " the bridge) by making it louder or quieter" }, { - "conf_get_signal_level", py_pjsua_conf_get_signal_level, METH_VARARGS, - "Get last signal level transmitted to or received from the specified port" + "conf_get_signal_level", py_pjsua_conf_get_signal_level, METH_VARARGS, + "Get last signal level transmitted to or received from the specified port" }, { "player_create", py_pjsua_player_create, METH_VARARGS, @@ -4410,13 +4409,13 @@ static PyMethodDef py_pjsua_methods[] = "Send arbitrary request" }, { - "dump", py_pjsua_dump, METH_VARARGS, "Dump application state" + "dump", py_pjsua_dump, METH_VARARGS, "Dump application state" }, { - "strerror", py_pj_strerror, METH_VARARGS, "Get error message" + "strerror", py_pj_strerror, METH_VARARGS, "Get error message" }, { - "parse_simple_uri", py_pj_parse_simple_sip, METH_VARARGS, "Parse URI" + "parse_simple_uri", py_pj_parse_simple_sip, METH_VARARGS, "Parse URI" }, @@ -4432,7 +4431,7 @@ DL_EXPORT(void) init_pjsua(void) { PyObject* m = NULL; -#define ADD_CONSTANT(mod,name) PyModule_AddIntConstant(mod,#name,name) +#define ADD_CONSTANT(mod,name) PyModule_AddIntConstant(mod,#name,name) pj_log_set_level(1); @@ -4583,16 +4582,16 @@ init_pjsua(void) PyModule_AddObject(m, "Conf_Port_Info", (PyObject *)&PyTyp_pjsua_conf_port_info); Py_INCREF(&PyTyp_pjmedia_snd_dev_info); PyModule_AddObject(m, "PJMedia_Snd_Dev_Info", - (PyObject *)&PyTyp_pjmedia_snd_dev_info); + (PyObject *)&PyTyp_pjmedia_snd_dev_info); Py_INCREF(&PyTyp_pjmedia_codec_param_info); PyModule_AddObject(m, "PJMedia_Codec_Param_Info", - (PyObject *)&PyTyp_pjmedia_codec_param_info); + (PyObject *)&PyTyp_pjmedia_codec_param_info); Py_INCREF(&PyTyp_pjmedia_codec_param_setting); PyModule_AddObject(m, "PJMedia_Codec_Param_Setting", - (PyObject *)&PyTyp_pjmedia_codec_param_setting); + (PyObject *)&PyTyp_pjmedia_codec_param_setting); Py_INCREF(&PyTyp_pjmedia_codec_param); PyModule_AddObject(m, "PJMedia_Codec_Param", - (PyObject *)&PyTyp_pjmedia_codec_param); + (PyObject *)&PyTyp_pjmedia_codec_param); /* END OF LIB MEDIA */ diff --git a/pjsip-apps/src/python/_pjsua.h b/pjsip-apps/src/python/_pjsua.h index 2ea0e436f6..d0e2e0b525 100644 --- a/pjsip-apps/src/python/_pjsua.h +++ b/pjsip-apps/src/python/_pjsua.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,11 +31,11 @@ PJ_INLINE(pj_str_t) PyString_ToPJ(const PyObject *obj) pj_str_t str; if (obj && PyString_Check(obj)) { - str.ptr = PyString_AS_STRING(obj); - str.slen = PyString_GET_SIZE(obj); + str.ptr = PyString_AS_STRING(obj); + str.slen = PyString_GET_SIZE(obj); } else { - str.ptr = NULL; - str.slen = 0; + str.ptr = NULL; + str.slen = 0; } return str; @@ -59,7 +58,7 @@ typedef struct PyObject *realm; PyObject *scheme; PyObject *username; - int data_type; + int data_type; PyObject *data; } PyObj_pjsip_cred_info; @@ -79,7 +78,7 @@ static void PyObj_pjsip_cred_info_delete(PyObj_pjsip_cred_info* self) static void PyObj_pjsip_cred_info_import(PyObj_pjsip_cred_info *obj, - const pjsip_cred_info *cfg) + const pjsip_cred_info *cfg) { Py_XDECREF(obj->realm); obj->realm = PyString_FromPJ(&cfg->realm); @@ -93,13 +92,13 @@ static void PyObj_pjsip_cred_info_import(PyObj_pjsip_cred_info *obj, } static void PyObj_pjsip_cred_info_export(pjsip_cred_info *cfg, - PyObj_pjsip_cred_info *obj) + PyObj_pjsip_cred_info *obj) { - cfg->realm = PyString_ToPJ(obj->realm); - cfg->scheme = PyString_ToPJ(obj->scheme); + cfg->realm = PyString_ToPJ(obj->realm); + cfg->scheme = PyString_ToPJ(obj->scheme); cfg->username = PyString_ToPJ(obj->username); cfg->data_type = obj->data_type; - cfg->data = PyString_ToPJ(obj->data); + cfg->data = PyString_ToPJ(obj->data); } @@ -108,8 +107,8 @@ static void PyObj_pjsip_cred_info_export(pjsip_cred_info *cfg, * constructor for cred_info object */ static PyObject * PyObj_pjsip_cred_info_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsip_cred_info *self; @@ -121,7 +120,7 @@ static PyObject * PyObj_pjsip_cred_info_new(PyTypeObject *type, self->realm = PyString_FromString(""); self->scheme = PyString_FromString(""); self->username = PyString_FromString(""); - self->data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; + self->data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; self->data = PyString_FromString(""); } @@ -153,11 +152,11 @@ static PyMemberDef PyObj_pjsip_cred_info_members[] = "data", T_OBJECT_EX, offsetof(PyObj_pjsip_cred_info, data), 0, "The data, which can be a plaintext password or a hashed digest, " - "depending on the value of data_type" + "depending on the value of data_type" }, { "data_type", T_INT, - offsetof(PyObj_pjsip_cred_info, data_type), 0, + offsetof(PyObj_pjsip_cred_info, data_type), 0, "Type of data" }, @@ -269,8 +268,8 @@ static void PyObj_pjsua_callback_delete(PyObj_pjsua_callback* self) * * declares constructor for callback struct */ static PyObject * PyObj_pjsua_callback_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_callback *self; @@ -293,7 +292,7 @@ static PyObject * PyObj_pjsua_callback_new(PyTypeObject *type, self->on_pager = Py_BuildValue(""); self->on_pager_status = Py_BuildValue(""); self->on_typing = Py_BuildValue(""); - self->on_mwi_info = Py_BuildValue(""); + self->on_mwi_info = Py_BuildValue(""); } return (PyObject *)self; @@ -308,8 +307,8 @@ static PyMemberDef PyObj_pjsua_callback_members[] = { { "on_call_state", T_OBJECT_EX, - offsetof(PyObj_pjsua_callback, on_call_state), 0, - "Notify application when invite state has changed. Application may " + offsetof(PyObj_pjsua_callback, on_call_state), 0, + "Notify application when invite state has changed. Application may " "then query the call info to get the detail call states." }, { @@ -325,18 +324,18 @@ static PyMemberDef PyObj_pjsua_callback_members[] = "the call's media to sound device." }, { - "on_dtmf_digit", T_OBJECT_EX, - offsetof(PyObj_pjsua_callback, on_dtmf_digit), 0, - "Notify application upon receiving incoming DTMF digit." + "on_dtmf_digit", T_OBJECT_EX, + offsetof(PyObj_pjsua_callback, on_dtmf_digit), 0, + "Notify application upon receiving incoming DTMF digit." }, { "on_call_transfer_request", T_OBJECT_EX, offsetof(PyObj_pjsua_callback, on_call_transfer_request), 0, "Notify application on call being transferred. " - "Application can decide to accept/reject transfer request " - "by setting the code (default is 200). When this callback " - "is not defined, the default behavior is to accept the " - "transfer." + "Application can decide to accept/reject transfer request " + "by setting the code (default is 200). When this callback " + "is not defined, the default behavior is to accept the " + "transfer." }, { "on_call_transfer_status", T_OBJECT_EX, @@ -355,12 +354,12 @@ static PyMemberDef PyObj_pjsua_callback_members[] = { "on_call_replaced", T_OBJECT_EX, offsetof(PyObj_pjsua_callback, on_call_replaced), 0, - "Notify application that an existing call has been replaced with " - "a new call. This happens when PJSUA-API receives incoming INVITE " - "request with Replaces header." - " " - "After this callback is called, normally PJSUA-API will disconnect " - "old_call_id and establish new_call_id." + "Notify application that an existing call has been replaced with " + "a new call. This happens when PJSUA-API receives incoming INVITE " + "request with Replaces header." + " " + "After this callback is called, normally PJSUA-API will disconnect " + "old_call_id and establish new_call_id." }, { "on_reg_state", T_OBJECT_EX, @@ -381,7 +380,7 @@ static PyMemberDef PyObj_pjsua_callback_members[] = }, { "on_pager", T_OBJECT_EX, - offsetof(PyObj_pjsua_callback, on_pager), 0, + offsetof(PyObj_pjsua_callback, on_pager), 0, "Notify application on incoming pager (i.e. MESSAGE request). " "Argument call_id will be -1 if MESSAGE request is not related to an " "existing call." @@ -394,12 +393,12 @@ static PyMemberDef PyObj_pjsua_callback_members[] = }, { "on_typing", T_OBJECT_EX, - offsetof(PyObj_pjsua_callback, on_typing), 0, + offsetof(PyObj_pjsua_callback, on_typing), 0, "Notify application about typing indication." }, { "on_mwi_info", T_OBJECT_EX, - offsetof(PyObj_pjsua_callback, on_mwi_info), 0, + offsetof(PyObj_pjsua_callback, on_mwi_info), 0, "Notify application about MWI indication." }, {NULL} /* Sentinel */ @@ -413,45 +412,45 @@ static PyMemberDef PyObj_pjsua_callback_members[] = static PyTypeObject PyTyp_pjsua_callback = { PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ - "_pjsua.Callback", /*tp_name*/ - sizeof(PyObj_pjsua_callback), /*tp_basicsize*/ - 0, /*tp_itemsize*/ + 0, /*ob_size*/ + "_pjsua.Callback", /*tp_name*/ + sizeof(PyObj_pjsua_callback), /*tp_basicsize*/ + 0, /*tp_itemsize*/ (destructor)PyObj_pjsua_callback_delete, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ "This structure describes application callback " "to receive various event notifications from " - "PJSUA-API", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ + "PJSUA-API", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ PyObj_pjsua_callback_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ PyObj_pjsua_callback_new, /* tp_new */ }; @@ -470,27 +469,27 @@ typedef struct unsigned snd_clock_rate; unsigned channel_count; unsigned audio_frame_ptime; - int snd_auto_close_time; + int snd_auto_close_time; unsigned max_media_ports; - int has_ioqueue; + int has_ioqueue; unsigned thread_cnt; unsigned quality; unsigned ptime; - int no_vad; + int no_vad; unsigned ilbc_mode; unsigned tx_drop_pct; unsigned rx_drop_pct; unsigned ec_options; unsigned ec_tail_len; - int jb_min; - int jb_max; - int enable_ice; - int enable_turn; + int jb_min; + int jb_max; + int enable_ice; + int enable_turn; PyObject *turn_server; - int turn_conn_type; + int turn_conn_type; PyObject *turn_realm; PyObject *turn_username; - int turn_passwd_type; + int turn_passwd_type; PyObject *turn_passwd; } PyObj_pjsua_media_config; @@ -503,28 +502,28 @@ static PyMemberDef PyObj_pjsua_media_config_members[] = { { "clock_rate", T_INT, - offsetof(PyObj_pjsua_media_config, clock_rate), 0, + offsetof(PyObj_pjsua_media_config, clock_rate), 0, "Clock rate to be applied to the conference bridge. If value is zero, " "default clock rate will be used (16KHz)." }, { "snd_clock_rate", T_INT, - offsetof(PyObj_pjsua_media_config, snd_clock_rate), 0, + offsetof(PyObj_pjsua_media_config, snd_clock_rate), 0, "Specify different clock rate of sound device, otherwise 0." }, { "channel_count", T_INT, - offsetof(PyObj_pjsua_media_config, channel_count), 0, + offsetof(PyObj_pjsua_media_config, channel_count), 0, "Specify channel count (default 1)." }, { "audio_frame_ptime", T_INT, - offsetof(PyObj_pjsua_media_config, audio_frame_ptime), 0, + offsetof(PyObj_pjsua_media_config, audio_frame_ptime), 0, "Audio frame length in milliseconds." }, { "snd_auto_close_time", T_INT, - offsetof(PyObj_pjsua_media_config, snd_auto_close_time), 0, + offsetof(PyObj_pjsua_media_config, snd_auto_close_time), 0, "Sound idle time before it's closed." }, { @@ -538,7 +537,7 @@ static PyMemberDef PyObj_pjsua_media_config_members[] = }, { "has_ioqueue", T_INT, - offsetof(PyObj_pjsua_media_config, has_ioqueue), 0, + offsetof(PyObj_pjsua_media_config, has_ioqueue), 0, "Specify whether the media manager should manage its own ioqueue for " "the RTP/RTCP sockets. If yes, ioqueue will be created and at least " "one worker thread will be created too. If no, the RTP/RTCP sockets " @@ -547,101 +546,101 @@ static PyMemberDef PyObj_pjsua_media_config_members[] = }, { "thread_cnt", T_INT, - offsetof(PyObj_pjsua_media_config, thread_cnt), 0, + offsetof(PyObj_pjsua_media_config, thread_cnt), 0, "Specify the number of worker threads to handle incoming RTP packets. " "A value of one is recommended for most applications." }, { "quality", T_INT, - offsetof(PyObj_pjsua_media_config, quality), 0, + offsetof(PyObj_pjsua_media_config, quality), 0, "The media quality also sets speex codec quality/complexity to the " "number." }, { "ptime", T_INT, - offsetof(PyObj_pjsua_media_config, ptime), 0, + offsetof(PyObj_pjsua_media_config, ptime), 0, "Specify default ptime." }, { "no_vad", T_INT, - offsetof(PyObj_pjsua_media_config, no_vad), 0, + offsetof(PyObj_pjsua_media_config, no_vad), 0, "Disable VAD?" }, { "ilbc_mode", T_INT, - offsetof(PyObj_pjsua_media_config, ilbc_mode), 0, + offsetof(PyObj_pjsua_media_config, ilbc_mode), 0, "iLBC mode (20 or 30)." }, { "tx_drop_pct", T_INT, - offsetof(PyObj_pjsua_media_config, tx_drop_pct), 0, + offsetof(PyObj_pjsua_media_config, tx_drop_pct), 0, "Percentage of RTP packet to drop in TX direction (to simulate packet " "lost)." }, { "rx_drop_pct", T_INT, - offsetof(PyObj_pjsua_media_config, rx_drop_pct), 0, + offsetof(PyObj_pjsua_media_config, rx_drop_pct), 0, "Percentage of RTP packet to drop in RX direction (to simulate packet " "lost)."}, { "ec_options", T_INT, - offsetof(PyObj_pjsua_media_config, ec_options), 0, + offsetof(PyObj_pjsua_media_config, ec_options), 0, "Echo canceller options (see pjmedia_echo_create())" }, { "ec_tail_len", T_INT, - offsetof(PyObj_pjsua_media_config, ec_tail_len), 0, + offsetof(PyObj_pjsua_media_config, ec_tail_len), 0, "Echo canceller tail length, in miliseconds." }, { "jb_min", T_INT, - offsetof(PyObj_pjsua_media_config, jb_min), 0, + offsetof(PyObj_pjsua_media_config, jb_min), 0, "Jitter buffer minimum size in milliseconds." }, { "jb_max", T_INT, - offsetof(PyObj_pjsua_media_config, jb_max), 0, + offsetof(PyObj_pjsua_media_config, jb_max), 0, "Jitter buffer maximum size in milliseconds." }, { - "enable_ice", T_INT, - offsetof(PyObj_pjsua_media_config, enable_ice), 0, + "enable_ice", T_INT, + offsetof(PyObj_pjsua_media_config, enable_ice), 0, "Enable ICE." }, { - "enable_turn", T_INT, - offsetof(PyObj_pjsua_media_config, enable_turn), 0, + "enable_turn", T_INT, + offsetof(PyObj_pjsua_media_config, enable_turn), 0, "Enable TURN." }, { - "turn_server", T_OBJECT_EX, - offsetof(PyObj_pjsua_media_config, turn_server), 0, - "Specify the TURN server." + "turn_server", T_OBJECT_EX, + offsetof(PyObj_pjsua_media_config, turn_server), 0, + "Specify the TURN server." }, { - "turn_conn_type", T_INT, - offsetof(PyObj_pjsua_media_config, turn_conn_type), 0, + "turn_conn_type", T_INT, + offsetof(PyObj_pjsua_media_config, turn_conn_type), 0, "Specify TURN connection type." }, { - "turn_realm", T_OBJECT_EX, - offsetof(PyObj_pjsua_media_config, turn_realm), 0, - "Specify the TURN realm." + "turn_realm", T_OBJECT_EX, + offsetof(PyObj_pjsua_media_config, turn_realm), 0, + "Specify the TURN realm." }, { - "turn_username", T_OBJECT_EX, - offsetof(PyObj_pjsua_media_config, turn_username), 0, - "Specify the TURN username." + "turn_username", T_OBJECT_EX, + offsetof(PyObj_pjsua_media_config, turn_username), 0, + "Specify the TURN username." }, { - "turn_passwd_type", T_INT, - offsetof(PyObj_pjsua_media_config, turn_passwd_type), 0, + "turn_passwd_type", T_INT, + offsetof(PyObj_pjsua_media_config, turn_passwd_type), 0, "Specify TURN password type." }, { - "turn_passwd", T_OBJECT_EX, - offsetof(PyObj_pjsua_media_config, turn_passwd), 0, - "Specify the TURN password." + "turn_passwd", T_OBJECT_EX, + offsetof(PyObj_pjsua_media_config, turn_passwd), 0, + "Specify the TURN password." }, {NULL} /* Sentinel */ @@ -649,8 +648,8 @@ static PyMemberDef PyObj_pjsua_media_config_members[] = static PyObject *PyObj_pjsua_media_config_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_media_config *self; @@ -659,10 +658,10 @@ static PyObject *PyObj_pjsua_media_config_new(PyTypeObject *type, self = (PyObj_pjsua_media_config*)type->tp_alloc(type, 0); if (self != NULL) { - self->turn_server = PyString_FromString(""); - self->turn_realm = PyString_FromString(""); - self->turn_username = PyString_FromString(""); - self->turn_passwd = PyString_FromString(""); + self->turn_server = PyString_FromString(""); + self->turn_realm = PyString_FromString(""); + self->turn_username = PyString_FromString(""); + self->turn_passwd = PyString_FromString(""); } return (PyObject *)self; @@ -678,84 +677,84 @@ static void PyObj_pjsua_media_config_delete(PyObj_pjsua_media_config * self) } static void PyObj_pjsua_media_config_import(PyObj_pjsua_media_config *obj, - const pjsua_media_config *cfg) + const pjsua_media_config *cfg) { - obj->clock_rate = cfg->clock_rate; - obj->snd_clock_rate = cfg->snd_clock_rate; - obj->channel_count = cfg->channel_count; + obj->clock_rate = cfg->clock_rate; + obj->snd_clock_rate = cfg->snd_clock_rate; + obj->channel_count = cfg->channel_count; obj->audio_frame_ptime = cfg->audio_frame_ptime; obj->snd_auto_close_time= cfg->snd_auto_close_time; obj->max_media_ports = cfg->max_media_ports; - obj->has_ioqueue = cfg->has_ioqueue; - obj->thread_cnt = cfg->thread_cnt; - obj->quality = cfg->quality; - obj->ptime = cfg->ptime; - obj->no_vad = cfg->no_vad; - obj->ilbc_mode = cfg->ilbc_mode; - obj->jb_min = cfg->jb_min_pre; - obj->jb_max = cfg->jb_max; - obj->tx_drop_pct = cfg->tx_drop_pct; - obj->rx_drop_pct = cfg->rx_drop_pct; - obj->ec_options = cfg->ec_options; - obj->ec_tail_len = cfg->ec_tail_len; - obj->enable_ice = cfg->enable_ice; - obj->enable_turn = cfg->enable_turn; + obj->has_ioqueue = cfg->has_ioqueue; + obj->thread_cnt = cfg->thread_cnt; + obj->quality = cfg->quality; + obj->ptime = cfg->ptime; + obj->no_vad = cfg->no_vad; + obj->ilbc_mode = cfg->ilbc_mode; + obj->jb_min = cfg->jb_min_pre; + obj->jb_max = cfg->jb_max; + obj->tx_drop_pct = cfg->tx_drop_pct; + obj->rx_drop_pct = cfg->rx_drop_pct; + obj->ec_options = cfg->ec_options; + obj->ec_tail_len = cfg->ec_tail_len; + obj->enable_ice = cfg->enable_ice; + obj->enable_turn = cfg->enable_turn; Py_XDECREF(obj->turn_server); - obj->turn_server = PyString_FromPJ(&cfg->turn_server); - obj->turn_conn_type = cfg->turn_conn_type; + obj->turn_server = PyString_FromPJ(&cfg->turn_server); + obj->turn_conn_type = cfg->turn_conn_type; if (cfg->turn_auth_cred.type == PJ_STUN_AUTH_CRED_STATIC) { - const pj_stun_auth_cred *cred = &cfg->turn_auth_cred; - - Py_XDECREF(obj->turn_realm); - obj->turn_realm = PyString_FromPJ(&cred->data.static_cred.realm); - Py_XDECREF(obj->turn_username); - obj->turn_username = PyString_FromPJ(&cred->data.static_cred.username); - obj->turn_passwd_type = cred->data.static_cred.data_type; - Py_XDECREF(obj->turn_passwd); - obj->turn_passwd = PyString_FromPJ(&cred->data.static_cred.data); + const pj_stun_auth_cred *cred = &cfg->turn_auth_cred; + + Py_XDECREF(obj->turn_realm); + obj->turn_realm = PyString_FromPJ(&cred->data.static_cred.realm); + Py_XDECREF(obj->turn_username); + obj->turn_username = PyString_FromPJ(&cred->data.static_cred.username); + obj->turn_passwd_type = cred->data.static_cred.data_type; + Py_XDECREF(obj->turn_passwd); + obj->turn_passwd = PyString_FromPJ(&cred->data.static_cred.data); } else { - Py_XDECREF(obj->turn_realm); - obj->turn_realm = PyString_FromString(""); - Py_XDECREF(obj->turn_username); - obj->turn_username = PyString_FromString(""); - obj->turn_passwd_type = 0; - Py_XDECREF(obj->turn_passwd); - obj->turn_passwd = PyString_FromString(""); + Py_XDECREF(obj->turn_realm); + obj->turn_realm = PyString_FromString(""); + Py_XDECREF(obj->turn_username); + obj->turn_username = PyString_FromString(""); + obj->turn_passwd_type = 0; + Py_XDECREF(obj->turn_passwd); + obj->turn_passwd = PyString_FromString(""); } } static void PyObj_pjsua_media_config_export(pjsua_media_config *cfg, - const PyObj_pjsua_media_config *obj) + const PyObj_pjsua_media_config *obj) { - cfg->clock_rate = obj->clock_rate; - cfg->snd_clock_rate = obj->snd_clock_rate; - cfg->channel_count = obj->channel_count; + cfg->clock_rate = obj->clock_rate; + cfg->snd_clock_rate = obj->snd_clock_rate; + cfg->channel_count = obj->channel_count; cfg->audio_frame_ptime = obj->audio_frame_ptime; cfg->snd_auto_close_time=obj->snd_auto_close_time; cfg->max_media_ports = obj->max_media_ports; - cfg->has_ioqueue = obj->has_ioqueue; - cfg->thread_cnt = obj->thread_cnt; - cfg->quality = obj->quality; - cfg->ptime = obj->ptime; - cfg->no_vad = obj->no_vad; - cfg->jb_min_pre = obj->jb_min; - cfg->jb_max = obj->jb_max; - cfg->ilbc_mode = obj->ilbc_mode; - cfg->tx_drop_pct = obj->tx_drop_pct; - cfg->rx_drop_pct = obj->rx_drop_pct; - cfg->ec_options = obj->ec_options; - cfg->ec_tail_len = obj->ec_tail_len; - cfg->enable_ice = obj->enable_ice; - cfg->enable_turn = obj->enable_turn; + cfg->has_ioqueue = obj->has_ioqueue; + cfg->thread_cnt = obj->thread_cnt; + cfg->quality = obj->quality; + cfg->ptime = obj->ptime; + cfg->no_vad = obj->no_vad; + cfg->jb_min_pre = obj->jb_min; + cfg->jb_max = obj->jb_max; + cfg->ilbc_mode = obj->ilbc_mode; + cfg->tx_drop_pct = obj->tx_drop_pct; + cfg->rx_drop_pct = obj->rx_drop_pct; + cfg->ec_options = obj->ec_options; + cfg->ec_tail_len = obj->ec_tail_len; + cfg->enable_ice = obj->enable_ice; + cfg->enable_turn = obj->enable_turn; if (cfg->enable_turn) { - cfg->turn_server = PyString_ToPJ(obj->turn_server); - cfg->turn_conn_type = obj->turn_conn_type; - cfg->turn_auth_cred.type = PJ_STUN_AUTH_CRED_STATIC; - cfg->turn_auth_cred.data.static_cred.realm = PyString_ToPJ(obj->turn_realm); - cfg->turn_auth_cred.data.static_cred.username = PyString_ToPJ(obj->turn_username); - cfg->turn_auth_cred.data.static_cred.data_type= obj->turn_passwd_type; - cfg->turn_auth_cred.data.static_cred.data = PyString_ToPJ(obj->turn_passwd); + cfg->turn_server = PyString_ToPJ(obj->turn_server); + cfg->turn_conn_type = obj->turn_conn_type; + cfg->turn_auth_cred.type = PJ_STUN_AUTH_CRED_STATIC; + cfg->turn_auth_cred.data.static_cred.realm = PyString_ToPJ(obj->turn_realm); + cfg->turn_auth_cred.data.static_cred.username = PyString_ToPJ(obj->turn_username); + cfg->turn_auth_cred.data.static_cred.data_type= obj->turn_passwd_type; + cfg->turn_auth_cred.data.static_cred.data = PyString_ToPJ(obj->turn_passwd); } } @@ -816,14 +815,14 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - unsigned max_calls; - unsigned thread_cnt; - PyObject *outbound_proxy; - PyObject *stun_domain; - PyObject *stun_host; - PyListObject *nameserver; + unsigned max_calls; + unsigned thread_cnt; + PyObject *outbound_proxy; + PyObject *stun_domain; + PyObject *stun_host; + PyListObject *nameserver; PyObj_pjsua_callback *cb; - PyObject *user_agent; + PyObject *user_agent; } PyObj_pjsua_config; @@ -840,64 +839,64 @@ static void PyObj_pjsua_config_delete(PyObj_pjsua_config* self) static void PyObj_pjsua_config_import(PyObj_pjsua_config *obj, - const pjsua_config *cfg) + const pjsua_config *cfg) { unsigned i; - obj->max_calls = cfg->max_calls; - obj->thread_cnt = cfg->thread_cnt; + obj->max_calls = cfg->max_calls; + obj->thread_cnt = cfg->thread_cnt; Py_XDECREF(obj->outbound_proxy); if (cfg->outbound_proxy_cnt) - obj->outbound_proxy = PyString_FromPJ(&cfg->outbound_proxy[0]); + obj->outbound_proxy = PyString_FromPJ(&cfg->outbound_proxy[0]); else - obj->outbound_proxy = PyString_FromString(""); + obj->outbound_proxy = PyString_FromString(""); Py_XDECREF(obj->stun_domain); - obj->stun_domain = PyString_FromPJ(&cfg->stun_domain); + obj->stun_domain = PyString_FromPJ(&cfg->stun_domain); Py_XDECREF(obj->stun_host); - obj->stun_host = PyString_FromPJ(&cfg->stun_host); + obj->stun_host = PyString_FromPJ(&cfg->stun_host); Py_XDECREF(obj->nameserver); obj->nameserver = (PyListObject *)PyList_New(0); for (i=0; inameserver_count; ++i) { - PyObject * str; - str = PyString_FromPJ(&cfg->nameserver[i]); - PyList_Append((PyObject *)obj->nameserver, str); + PyObject * str; + str = PyString_FromPJ(&cfg->nameserver[i]); + PyList_Append((PyObject *)obj->nameserver, str); } Py_XDECREF(obj->user_agent); - obj->user_agent = PyString_FromPJ(&cfg->user_agent); + obj->user_agent = PyString_FromPJ(&cfg->user_agent); } static void PyObj_pjsua_config_export(pjsua_config *cfg, - PyObj_pjsua_config *obj) + PyObj_pjsua_config *obj) { unsigned i; - cfg->max_calls = obj->max_calls; - cfg->thread_cnt = obj->thread_cnt; + cfg->max_calls = obj->max_calls; + cfg->thread_cnt = obj->thread_cnt; if (PyString_Size(obj->outbound_proxy) > 0) { - cfg->outbound_proxy_cnt = 1; - cfg->outbound_proxy[0] = PyString_ToPJ(obj->outbound_proxy); + cfg->outbound_proxy_cnt = 1; + cfg->outbound_proxy[0] = PyString_ToPJ(obj->outbound_proxy); } else { - cfg->outbound_proxy_cnt = 0; + cfg->outbound_proxy_cnt = 0; } cfg->nameserver_count = PyList_Size((PyObject*)obj->nameserver); if (cfg->nameserver_count > PJ_ARRAY_SIZE(cfg->nameserver)) - cfg->nameserver_count = PJ_ARRAY_SIZE(cfg->nameserver); + cfg->nameserver_count = PJ_ARRAY_SIZE(cfg->nameserver); for (i = 0; i < cfg->nameserver_count; i++) { - PyObject *item = PyList_GetItem((PyObject *)obj->nameserver,i); + PyObject *item = PyList_GetItem((PyObject *)obj->nameserver,i); cfg->nameserver[i] = PyString_ToPJ(item); } - cfg->stun_domain = PyString_ToPJ(obj->stun_domain); - cfg->stun_host = PyString_ToPJ(obj->stun_host); - cfg->user_agent = PyString_ToPJ(obj->user_agent); + cfg->stun_domain = PyString_ToPJ(obj->stun_domain); + cfg->stun_host = PyString_ToPJ(obj->stun_host); + cfg->user_agent = PyString_ToPJ(obj->user_agent); } static PyObject *PyObj_pjsua_config_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_config *self; @@ -908,10 +907,10 @@ static PyObject *PyObj_pjsua_config_new(PyTypeObject *type, if (self != NULL) { self->user_agent = PyString_FromString(""); self->outbound_proxy = PyString_FromString(""); - self->stun_domain = PyString_FromString(""); - self->stun_host = PyString_FromString(""); + self->stun_domain = PyString_FromString(""); + self->stun_host = PyString_FromString(""); self->cb = (PyObj_pjsua_callback *) - PyType_GenericNew(&PyTyp_pjsua_callback, NULL, NULL); + PyType_GenericNew(&PyTyp_pjsua_callback, NULL, NULL); } return (PyObject *)self; } @@ -924,49 +923,49 @@ static PyObject *PyObj_pjsua_config_new(PyTypeObject *type, static PyMemberDef PyObj_pjsua_config_members[] = { { - "max_calls", T_INT, - offsetof(PyObj_pjsua_config, max_calls), 0, - "Maximum calls to support (default: 4) " + "max_calls", T_INT, + offsetof(PyObj_pjsua_config, max_calls), 0, + "Maximum calls to support (default: 4) " }, { - "thread_cnt", T_INT, - offsetof(PyObj_pjsua_config, thread_cnt), 0, - "Number of worker threads. Normally application will want to have at " - "least one worker thread, unless when it wants to poll the library " - "periodically, which in this case the worker thread can be set to " - "zero." + "thread_cnt", T_INT, + offsetof(PyObj_pjsua_config, thread_cnt), 0, + "Number of worker threads. Normally application will want to have at " + "least one worker thread, unless when it wants to poll the library " + "periodically, which in this case the worker thread can be set to " + "zero." }, { - "outbound_proxy", T_OBJECT_EX, - offsetof(PyObj_pjsua_config, outbound_proxy), 0, - "SIP URL of the outbound proxy (optional)" + "outbound_proxy", T_OBJECT_EX, + offsetof(PyObj_pjsua_config, outbound_proxy), 0, + "SIP URL of the outbound proxy (optional)" }, { - "stun_domain", T_OBJECT_EX, - offsetof(PyObj_pjsua_config, stun_domain), 0, - "Domain of the STUN server (optional). STUN server will be resolved " - "using DNS SRV resolution only when nameserver is configured. " - "Alternatively, if DNS SRV resolution for STUN is not desired, " - "application can specify the STUN server hostname or IP address " - "in stun_host attribute." + "stun_domain", T_OBJECT_EX, + offsetof(PyObj_pjsua_config, stun_domain), 0, + "Domain of the STUN server (optional). STUN server will be resolved " + "using DNS SRV resolution only when nameserver is configured. " + "Alternatively, if DNS SRV resolution for STUN is not desired, " + "application can specify the STUN server hostname or IP address " + "in stun_host attribute." }, { - "stun_host", T_OBJECT_EX, - offsetof(PyObj_pjsua_config, stun_host), 0, - "Hostname or IP address of the STUN server (optional)." + "stun_host", T_OBJECT_EX, + offsetof(PyObj_pjsua_config, stun_host), 0, + "Hostname or IP address of the STUN server (optional)." }, { - "nameserver", T_OBJECT_EX, - offsetof(PyObj_pjsua_config, nameserver), 0, - "IP address of the nameserver." + "nameserver", T_OBJECT_EX, + offsetof(PyObj_pjsua_config, nameserver), 0, + "IP address of the nameserver." }, { - "cb", T_OBJECT_EX, offsetof(PyObj_pjsua_config, cb), 0, - "Application callback." + "cb", T_OBJECT_EX, offsetof(PyObj_pjsua_config, cb), 0, + "Application callback." }, { - "user_agent", T_OBJECT_EX, offsetof(PyObj_pjsua_config, user_agent), 0, - "User agent string (default empty)" + "user_agent", T_OBJECT_EX, offsetof(PyObj_pjsua_config, user_agent), 0, + "User agent string (default empty)" }, {NULL} /* Sentinel */ }; @@ -1029,12 +1028,12 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - int msg_logging; - unsigned level; - unsigned console_level; - unsigned decor; - PyObject *log_filename; - PyObject *cb; + int msg_logging; + unsigned level; + unsigned console_level; + unsigned decor; + PyObject *log_filename; + PyObject *cb; } PyObj_pjsua_logging_config; @@ -1051,24 +1050,24 @@ static void PyObj_pjsua_logging_config_delete(PyObj_pjsua_logging_config* self) static void PyObj_pjsua_logging_config_import(PyObj_pjsua_logging_config *obj, - const pjsua_logging_config *cfg) + const pjsua_logging_config *cfg) { - obj->msg_logging = cfg->msg_logging; - obj->level = cfg->level; - obj->console_level = cfg->console_level; - obj->decor = cfg->decor; + obj->msg_logging = cfg->msg_logging; + obj->level = cfg->level; + obj->console_level = cfg->console_level; + obj->decor = cfg->decor; Py_XDECREF(obj->log_filename); obj->log_filename = PyString_FromPJ(&cfg->log_filename); } static void PyObj_pjsua_logging_config_export(pjsua_logging_config *cfg, - PyObj_pjsua_logging_config *obj) + PyObj_pjsua_logging_config *obj) { - cfg->msg_logging = obj->msg_logging; - cfg->level = obj->level; - cfg->console_level = obj->console_level; - cfg->decor = obj->decor; - cfg->log_filename = PyString_ToPJ(obj->log_filename); + cfg->msg_logging = obj->msg_logging; + cfg->level = obj->level; + cfg->console_level = obj->console_level; + cfg->decor = obj->decor; + cfg->log_filename = PyString_ToPJ(obj->log_filename); } @@ -1077,8 +1076,8 @@ static void PyObj_pjsua_logging_config_export(pjsua_logging_config *cfg, * constructor for logging_config object */ static PyObject * PyObj_pjsua_logging_config_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_logging_config *self; @@ -1101,36 +1100,36 @@ static PyObject * PyObj_pjsua_logging_config_new(PyTypeObject *type, static PyMemberDef PyObj_pjsua_logging_config_members[] = { { - "msg_logging", T_INT, - offsetof(PyObj_pjsua_logging_config, msg_logging), 0, - "Log incoming and outgoing SIP message? Yes!" + "msg_logging", T_INT, + offsetof(PyObj_pjsua_logging_config, msg_logging), 0, + "Log incoming and outgoing SIP message? Yes!" }, { - "level", T_INT, - offsetof(PyObj_pjsua_logging_config, level), 0, - "Input verbosity level. Value 5 is reasonable." + "level", T_INT, + offsetof(PyObj_pjsua_logging_config, level), 0, + "Input verbosity level. Value 5 is reasonable." }, { - "console_level", T_INT, - offsetof(PyObj_pjsua_logging_config, console_level), - 0, "Verbosity level for console. Value 4 is reasonable." + "console_level", T_INT, + offsetof(PyObj_pjsua_logging_config, console_level), + 0, "Verbosity level for console. Value 4 is reasonable." }, { - "decor", T_INT, - offsetof(PyObj_pjsua_logging_config, decor), 0, - "Log decoration" + "decor", T_INT, + offsetof(PyObj_pjsua_logging_config, decor), 0, + "Log decoration" }, { - "log_filename", T_OBJECT_EX, - offsetof(PyObj_pjsua_logging_config, log_filename), 0, - "Optional log filename" + "log_filename", T_OBJECT_EX, + offsetof(PyObj_pjsua_logging_config, log_filename), 0, + "Optional log filename" }, { - "cb", T_OBJECT_EX, - offsetof(PyObj_pjsua_logging_config, cb), 0, - "Optional callback function to be called to write log to application " - "specific device. This function will be called forlog messages on " - "input verbosity level." + "cb", T_OBJECT_EX, + offsetof(PyObj_pjsua_logging_config, cb), 0, + "Optional callback function to be called to write log to application " + "specific device. This function will be called forlog messages on " + "input verbosity level." }, {NULL} /* Sentinel */ }; @@ -1222,8 +1221,8 @@ static void PyObj_pjsua_msg_data_delete(PyObj_pjsua_msg_data* self) * !modified @ 061206 */ static PyObject * PyObj_pjsua_msg_data_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_msg_data *self; @@ -1249,18 +1248,18 @@ static PyMemberDef PyObj_pjsua_msg_data_members[] = { { "hdr_list", T_OBJECT_EX, - offsetof(PyObj_pjsua_msg_data, hdr_list), 0, - "Additional message headers as linked list of strings." + offsetof(PyObj_pjsua_msg_data, hdr_list), 0, + "Additional message headers as linked list of strings." }, { - "content_type", T_OBJECT_EX, - offsetof(PyObj_pjsua_msg_data, content_type), 0, - "MIME type of optional message body." + "content_type", T_OBJECT_EX, + offsetof(PyObj_pjsua_msg_data, content_type), 0, + "MIME type of optional message body." }, { - "msg_body", T_OBJECT_EX, - offsetof(PyObj_pjsua_msg_data, msg_body), 0, - "Optional message body." + "msg_body", T_OBJECT_EX, + offsetof(PyObj_pjsua_msg_data, msg_body), 0, + "Optional message body." }, {NULL} /* Sentinel */ }; @@ -1324,7 +1323,7 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - unsigned port; + unsigned port; PyObject *public_addr; PyObject *bound_addr; pj_qos_type qos_type; @@ -1349,21 +1348,21 @@ static void PyObj_pjsua_transport_config_delete(PyObj_pjsua_transport_config* se static void PyObj_pjsua_transport_config_export(pjsua_transport_config *cfg, - PyObj_pjsua_transport_config *obj) + PyObj_pjsua_transport_config *obj) { pjsua_transport_config_default(cfg); - cfg->public_addr = PyString_ToPJ(obj->public_addr); - cfg->bound_addr = PyString_ToPJ(obj->bound_addr); - cfg->port = obj->port; - cfg->qos_type = obj->qos_type; - cfg->qos_params.flags = obj->qos_params_flags; - cfg->qos_params.dscp_val = obj->qos_params_dscp_val; - cfg->qos_params.so_prio = obj->qos_params_so_prio; - cfg->qos_params.wmm_prio = obj->qos_params_wmm_prio; + cfg->public_addr = PyString_ToPJ(obj->public_addr); + cfg->bound_addr = PyString_ToPJ(obj->bound_addr); + cfg->port = obj->port; + cfg->qos_type = obj->qos_type; + cfg->qos_params.flags = obj->qos_params_flags; + cfg->qos_params.dscp_val = obj->qos_params_dscp_val; + cfg->qos_params.so_prio = obj->qos_params_so_prio; + cfg->qos_params.wmm_prio = obj->qos_params_wmm_prio; } static void PyObj_pjsua_transport_config_import(PyObj_pjsua_transport_config *obj, - const pjsua_transport_config *cfg) + const pjsua_transport_config *cfg) { Py_XDECREF(obj->public_addr); obj->public_addr = PyString_FromPJ(&cfg->public_addr); @@ -1371,12 +1370,12 @@ static void PyObj_pjsua_transport_config_import(PyObj_pjsua_transport_config *ob Py_XDECREF(obj->bound_addr); obj->bound_addr = PyString_FromPJ(&cfg->bound_addr); - obj->port = cfg->port; - obj->qos_type = cfg->qos_type; - obj->qos_params_flags = cfg->qos_params.flags; - obj->qos_params_dscp_val = cfg->qos_params.dscp_val; - obj->qos_params_so_prio = cfg->qos_params.so_prio; - obj->qos_params_wmm_prio = cfg->qos_params.wmm_prio; + obj->port = cfg->port; + obj->qos_type = cfg->qos_type; + obj->qos_params_flags = cfg->qos_params.flags; + obj->qos_params_dscp_val = cfg->qos_params.dscp_val; + obj->qos_params_so_prio = cfg->qos_params.so_prio; + obj->qos_params_wmm_prio = cfg->qos_params.wmm_prio; } @@ -1386,8 +1385,8 @@ static void PyObj_pjsua_transport_config_import(PyObj_pjsua_transport_config *ob * constructor for transport_config object */ static PyObject * PyObj_pjsua_transport_config_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_transport_config *self; @@ -1411,7 +1410,7 @@ static PyMemberDef PyObj_pjsua_transport_config_members[] = { { "port", T_INT, - offsetof(PyObj_pjsua_transport_config, port), 0, + offsetof(PyObj_pjsua_transport_config, port), 0, "UDP port number to bind locally. This setting MUST be specified " "even when default port is desired. If the value is zero, the " "transport will be bound to any available port, and application " @@ -1419,12 +1418,12 @@ static PyMemberDef PyObj_pjsua_transport_config_members[] = }, { "public_addr", T_OBJECT_EX, - offsetof(PyObj_pjsua_transport_config, public_addr), 0, + offsetof(PyObj_pjsua_transport_config, public_addr), 0, "Optional address to advertise as the address of this transport. " "Application can specify any address or hostname for this field, " "for example it can point to one of the interface address in the " "system, or it can point to the public address of a NAT router " - "where port mappings have been configured for the application." + "where port mappings have been configured for the application." }, { "bound_addr", T_OBJECT_EX, @@ -1433,7 +1432,7 @@ static PyMemberDef PyObj_pjsua_transport_config_members[] = "SHOULD only be used to selectively bind the socket to particular " "interface (instead of 0.0.0.0), and SHOULD NOT be used to set the " "published address of a transport (the public_addr field should be " - "used for that purpose)." + "used for that purpose)." }, { "qos_type", T_INT, @@ -1519,7 +1518,7 @@ static PyTypeObject PyTyp_pjsua_transport_config = 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "Transport setting", /* tp_doc */ + "Transport setting", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ @@ -1549,14 +1548,14 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - int id; - int type; - PyObject *type_name; - PyObject *info; - unsigned flag; - PyObject *addr; - unsigned port; - unsigned usage_count; + int id; + int type; + PyObject *type_name; + PyObject *info; + unsigned flag; + PyObject *addr; + unsigned port; + unsigned usage_count; } PyObj_pjsua_transport_info; @@ -1574,15 +1573,15 @@ static void PyObj_pjsua_transport_info_delete(PyObj_pjsua_transport_info* self) static void PyObj_pjsua_transport_info_import(PyObj_pjsua_transport_info *obj, - const pjsua_transport_info *info) + const pjsua_transport_info *info) { - obj->id = info->id; - obj->type = info->type; + obj->id = info->id; + obj->type = info->type; obj->type_name = PyString_FromPJ(&info->type_name); - obj->info = PyString_FromPJ(&info->info); - obj->flag = info->flag; - obj->addr = PyString_FromPJ(&info->local_name.host); - obj->port = info->local_name.port; + obj->info = PyString_FromPJ(&info->info); + obj->flag = info->flag; + obj->addr = PyString_FromPJ(&info->local_name.host); + obj->port = info->local_name.port; obj->usage_count= info->usage_count; } @@ -1591,8 +1590,8 @@ static void PyObj_pjsua_transport_info_import(PyObj_pjsua_transport_info *obj, * constructor for transport_info object */ static PyObject * PyObj_pjsua_transport_info_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_transport_info *self; @@ -1618,12 +1617,12 @@ static PyMemberDef PyObj_pjsua_transport_info_members[] = { { "id", T_INT, - offsetof(PyObj_pjsua_transport_info, id), 0, + offsetof(PyObj_pjsua_transport_info, id), 0, "PJSUA transport identification." }, { "type", T_INT, - offsetof(PyObj_pjsua_transport_info, type), 0, + offsetof(PyObj_pjsua_transport_info, type), 0, "Transport type." }, { @@ -1638,7 +1637,7 @@ static PyMemberDef PyObj_pjsua_transport_info_members[] = }, { "flag", T_INT, - offsetof(PyObj_pjsua_transport_info, flag), 0, + offsetof(PyObj_pjsua_transport_info, flag), 0, "Transport flag (see ##pjsip_transport_flags_e)." }, { @@ -1653,7 +1652,7 @@ static PyMemberDef PyObj_pjsua_transport_info_members[] = }, { "usage_count", T_INT, - offsetof(PyObj_pjsua_transport_info, usage_count), 0, + offsetof(PyObj_pjsua_transport_info, usage_count), 0, "Current number of objects currently referencing this transport." }, {NULL} /* Sentinel */ @@ -1718,32 +1717,32 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - int priority; - PyObject *id; - PyObject *reg_uri; - int publish_enabled; - int mwi_enabled; - PyObject *force_contact; + int priority; + PyObject *id; + PyObject *reg_uri; + int publish_enabled; + int mwi_enabled; + PyObject *force_contact; PyListObject *proxy; - unsigned reg_timeout; - unsigned reg_delay_before_refresh; + unsigned reg_timeout; + unsigned reg_delay_before_refresh; PyListObject *cred_info; - int transport_id; - int auth_initial_send; - PyObject *auth_initial_algorithm; - PyObject *pidf_tuple_id; - PyObject *contact_params; - PyObject *contact_uri_params; - int require_100rel; - int use_timer; - unsigned timer_se; - unsigned timer_min_se; - int allow_contact_rewrite; - int ka_interval; - PyObject *ka_data; - unsigned use_srtp; - unsigned srtp_secure_signaling; - PyObject *rtp_transport_cfg; + int transport_id; + int auth_initial_send; + PyObject *auth_initial_algorithm; + PyObject *pidf_tuple_id; + PyObject *contact_params; + PyObject *contact_uri_params; + int require_100rel; + int use_timer; + unsigned timer_se; + unsigned timer_min_se; + int allow_contact_rewrite; + int ka_interval; + PyObject *ka_data; + unsigned use_srtp; + unsigned srtp_secure_signaling; + PyObject *rtp_transport_cfg; } PyObj_pjsua_acc_config; @@ -1755,7 +1754,7 @@ static void PyObj_pjsua_acc_config_delete(PyObj_pjsua_acc_config* self) { Py_XDECREF(self->id); Py_XDECREF(self->reg_uri); - Py_XDECREF(self->force_contact); + Py_XDECREF(self->force_contact); Py_XDECREF(self->proxy); Py_XDECREF(self->cred_info); Py_XDECREF(self->auth_initial_algorithm); @@ -1769,14 +1768,14 @@ static void PyObj_pjsua_acc_config_delete(PyObj_pjsua_acc_config* self) static void PyObj_pjsua_acc_config_import(PyObj_pjsua_acc_config *obj, - const pjsua_acc_config *cfg) + const pjsua_acc_config *cfg) { PyObj_pjsua_transport_config *tconf; unsigned i; obj->priority = cfg->priority; Py_XDECREF(obj->id); - obj->id = PyString_FromPJ(&cfg->id); + obj->id = PyString_FromPJ(&cfg->id); Py_XDECREF(obj->reg_uri); obj->reg_uri = PyString_FromPJ(&cfg->reg_uri); obj->publish_enabled = cfg->publish_enabled; @@ -1786,9 +1785,9 @@ static void PyObj_pjsua_acc_config_import(PyObj_pjsua_acc_config *obj, Py_XDECREF(obj->proxy); obj->proxy = (PyListObject *)PyList_New(0); for (i=0; iproxy_cnt; ++i) { - PyObject * str; - str = PyString_FromPJ(&cfg->proxy[i]); - PyList_Append((PyObject *)obj->proxy, str); + PyObject * str; + str = PyString_FromPJ(&cfg->proxy[i]); + PyList_Append((PyObject *)obj->proxy, str); } obj->reg_timeout = cfg->reg_timeout; @@ -1797,12 +1796,12 @@ static void PyObj_pjsua_acc_config_import(PyObj_pjsua_acc_config *obj, Py_XDECREF(obj->cred_info); obj->cred_info = (PyListObject *)PyList_New(0); for (i=0; icred_count; ++i) { - PyObj_pjsip_cred_info * ci; + PyObj_pjsip_cred_info * ci; - ci = (PyObj_pjsip_cred_info *) - PyObj_pjsip_cred_info_new(&PyTyp_pjsip_cred_info,NULL,NULL); - PyObj_pjsip_cred_info_import(ci, &cfg->cred_info[i]); - PyList_Append((PyObject *)obj->cred_info, (PyObject *)ci); + ci = (PyObj_pjsip_cred_info *) + PyObj_pjsip_cred_info_new(&PyTyp_pjsip_cred_info,NULL,NULL); + PyObj_pjsip_cred_info_import(ci, &cfg->cred_info[i]); + PyList_Append((PyObject *)obj->cred_info, (PyObject *)ci); } obj->transport_id = cfg->transport_id; @@ -1829,20 +1828,20 @@ static void PyObj_pjsua_acc_config_import(PyObj_pjsua_acc_config *obj, Py_XDECREF(obj->rtp_transport_cfg); tconf = (PyObj_pjsua_transport_config*) - PyObj_pjsua_transport_config_new(&PyTyp_pjsua_transport_config, - NULL, NULL); + PyObj_pjsua_transport_config_new(&PyTyp_pjsua_transport_config, + NULL, NULL); PyObj_pjsua_transport_config_import(tconf, &cfg->rtp_cfg); obj->rtp_transport_cfg = (PyObject *) tconf; } static void PyObj_pjsua_acc_config_export(pjsua_acc_config *cfg, - PyObj_pjsua_acc_config *obj) + PyObj_pjsua_acc_config *obj) { PyObj_pjsua_transport_config *tconf; unsigned i; cfg->priority = obj->priority; - cfg->id = PyString_ToPJ(obj->id); + cfg->id = PyString_ToPJ(obj->id); cfg->reg_uri = PyString_ToPJ(obj->reg_uri); cfg->publish_enabled = obj->publish_enabled; cfg->mwi_enabled = obj->mwi_enabled; @@ -1850,9 +1849,9 @@ static void PyObj_pjsua_acc_config_export(pjsua_acc_config *cfg, cfg->proxy_cnt = PyList_Size((PyObject*)obj->proxy); if (cfg->proxy_cnt > PJ_ARRAY_SIZE(cfg->proxy)) - cfg->proxy_cnt = PJ_ARRAY_SIZE(cfg->proxy); + cfg->proxy_cnt = PJ_ARRAY_SIZE(cfg->proxy); for (i = 0; i < cfg->proxy_cnt; i++) { - PyObject *item = PyList_GetItem((PyObject *)obj->proxy, i); + PyObject *item = PyList_GetItem((PyObject *)obj->proxy, i); cfg->proxy[i] = PyString_ToPJ(item); } @@ -1861,12 +1860,12 @@ static void PyObj_pjsua_acc_config_export(pjsua_acc_config *cfg, cfg->cred_count = PyList_Size((PyObject*)obj->cred_info); if (cfg->cred_count > PJ_ARRAY_SIZE(cfg->cred_info)) - cfg->cred_count = PJ_ARRAY_SIZE(cfg->cred_info); + cfg->cred_count = PJ_ARRAY_SIZE(cfg->cred_info); for (i = 0; i < cfg->cred_count; i++) { - PyObj_pjsip_cred_info *ci; - ci = (PyObj_pjsip_cred_info*) - PyList_GetItem((PyObject *)obj->cred_info, i); - PyObj_pjsip_cred_info_export(&cfg->cred_info[i], ci); + PyObj_pjsip_cred_info *ci; + ci = (PyObj_pjsip_cred_info*) + PyList_GetItem((PyObject *)obj->cred_info, i); + PyObj_pjsip_cred_info_export(&cfg->cred_info[i], ci); } cfg->transport_id = obj->transport_id; @@ -1895,8 +1894,8 @@ static void PyObj_pjsua_acc_config_export(pjsua_acc_config *cfg, * constructor for acc_config object */ static PyObject * PyObj_pjsua_acc_config_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_acc_config *self; @@ -1908,13 +1907,13 @@ static PyObject * PyObj_pjsua_acc_config_new(PyTypeObject *type, self->id = PyString_FromString(""); self->reg_uri = PyString_FromString(""); self->force_contact = PyString_FromString(""); - self->proxy = (PyListObject *)PyList_New(0); - self->cred_info = (PyListObject *)PyList_New(0); - self->auth_initial_algorithm = PyString_FromString(""); - self->pidf_tuple_id = PyString_FromString(""); - self->contact_params = PyString_FromString(""); - self->contact_uri_params = PyString_FromString(""); - self->ka_data = PyString_FromString(""); + self->proxy = (PyListObject *)PyList_New(0); + self->cred_info = (PyListObject *)PyList_New(0); + self->auth_initial_algorithm = PyString_FromString(""); + self->pidf_tuple_id = PyString_FromString(""); + self->contact_params = PyString_FromString(""); + self->contact_uri_params = PyString_FromString(""); + self->ka_data = PyString_FromString(""); } return (PyObject *)self; @@ -1971,21 +1970,21 @@ static PyMemberDef PyObj_pjsua_acc_config_members[] = "proxy", T_OBJECT_EX, offsetof(PyObj_pjsua_acc_config, proxy), 0, "Optional URI of the proxies to be visited for all outgoing requests " - "that are using this account (REGISTER, INVITE, etc). Application need " - "to specify these proxies if the service provider requires " - "that requests destined towards its network should go through certain " - "proxies first (for example, border controllers)." + "that are using this account (REGISTER, INVITE, etc). Application need " + "to specify these proxies if the service provider requires " + "that requests destined towards its network should go through certain " + "proxies first (for example, border controllers)." }, { "reg_timeout", T_INT, - offsetof(PyObj_pjsua_acc_config, reg_timeout), 0, + offsetof(PyObj_pjsua_acc_config, reg_timeout), 0, "Optional interval for registration, in seconds. " "If the value is zero, default interval will be used " "(PJSUA_REG_INTERVAL, 55 seconds). " }, { "reg_delay_before_refresh", T_INT, - offsetof(PyObj_pjsua_acc_config, reg_delay_before_refresh), 0, + offsetof(PyObj_pjsua_acc_config, reg_delay_before_refresh), 0, "Specify the number of seconds to refresh the client registration" "before the registration expires." "(PJSIP_REGISTER_CLIENT_DELAY_BEFORE_REFRESH, 5 seconds). " @@ -1994,95 +1993,95 @@ static PyMemberDef PyObj_pjsua_acc_config_members[] = "cred_info", T_OBJECT_EX, offsetof(PyObj_pjsua_acc_config, cred_info), 0, "Array of credentials. If registration is desired, normally there " - "should be at least one credential specified, to successfully " - "authenticate against the service provider. More credentials can " - "be specified, for example when the requests are expected to be " - "challenged by the proxies in the route set." + "should be at least one credential specified, to successfully " + "authenticate against the service provider. More credentials can " + "be specified, for example when the requests are expected to be " + "challenged by the proxies in the route set." }, { - "transport_id", T_INT, - offsetof(PyObj_pjsua_acc_config, transport_id), 0, - "Optionally bind this account to specific transport. This normally is" - " not a good idea, as account should be able to send requests using" - " any available transports according to the destination. But some" - " application may want to have explicit control over the transport to" - " use, so in that case it can set this field." + "transport_id", T_INT, + offsetof(PyObj_pjsua_acc_config, transport_id), 0, + "Optionally bind this account to specific transport. This normally is" + " not a good idea, as account should be able to send requests using" + " any available transports according to the destination. But some" + " application may want to have explicit control over the transport to" + " use, so in that case it can set this field." }, { - "auth_initial_send", T_INT, - offsetof(PyObj_pjsua_acc_config, auth_initial_send), 0, - "Send empty initial authorization header." + "auth_initial_send", T_INT, + offsetof(PyObj_pjsua_acc_config, auth_initial_send), 0, + "Send empty initial authorization header." }, { - "auth_initial_algorithm", T_OBJECT_EX, - offsetof(PyObj_pjsua_acc_config, auth_initial_algorithm), 0, - "Specify algorithm in empty initial authorization header." + "auth_initial_algorithm", T_OBJECT_EX, + offsetof(PyObj_pjsua_acc_config, auth_initial_algorithm), 0, + "Specify algorithm in empty initial authorization header." }, { - "pidf_tuple_id", T_OBJECT_EX, - offsetof(PyObj_pjsua_acc_config, pidf_tuple_id), 0, - "PIDF tuple id." + "pidf_tuple_id", T_OBJECT_EX, + offsetof(PyObj_pjsua_acc_config, pidf_tuple_id), 0, + "PIDF tuple id." }, { - "contact_params", T_OBJECT_EX, - offsetof(PyObj_pjsua_acc_config, contact_params), 0, - "Additional parameters for Contact header." + "contact_params", T_OBJECT_EX, + offsetof(PyObj_pjsua_acc_config, contact_params), 0, + "Additional parameters for Contact header." }, { - "contact_uri_params", T_OBJECT_EX, - offsetof(PyObj_pjsua_acc_config, contact_uri_params), 0, - "Additional parameters for Contact URI." + "contact_uri_params", T_OBJECT_EX, + offsetof(PyObj_pjsua_acc_config, contact_uri_params), 0, + "Additional parameters for Contact URI." }, { - "require_100rel", T_INT, - offsetof(PyObj_pjsua_acc_config, require_100rel), 0, - "Require reliable provisional response." + "require_100rel", T_INT, + offsetof(PyObj_pjsua_acc_config, require_100rel), 0, + "Require reliable provisional response." }, { - "use_timer", T_INT, - offsetof(PyObj_pjsua_acc_config, use_timer), 0, - "Use SIP session timers? (default=1)" - "0:inactive, 1:optional, 2:mandatory, 3:always" + "use_timer", T_INT, + offsetof(PyObj_pjsua_acc_config, use_timer), 0, + "Use SIP session timers? (default=1)" + "0:inactive, 1:optional, 2:mandatory, 3:always" }, { - "timer_se", T_INT, - offsetof(PyObj_pjsua_acc_config, timer_se), 0, - "Session timer expiration period, in seconds." + "timer_se", T_INT, + offsetof(PyObj_pjsua_acc_config, timer_se), 0, + "Session timer expiration period, in seconds." }, { - "timer_min_se", T_INT, - offsetof(PyObj_pjsua_acc_config, timer_min_se), 0, - "Session timer minimum expiration period, in seconds." + "timer_min_se", T_INT, + offsetof(PyObj_pjsua_acc_config, timer_min_se), 0, + "Session timer minimum expiration period, in seconds." }, { - "allow_contact_rewrite", T_INT, - offsetof(PyObj_pjsua_acc_config, allow_contact_rewrite), 0, - "Re-REGISTER if behind symmetric NAT." + "allow_contact_rewrite", T_INT, + offsetof(PyObj_pjsua_acc_config, allow_contact_rewrite), 0, + "Re-REGISTER if behind symmetric NAT." }, { - "ka_interval", T_INT, - offsetof(PyObj_pjsua_acc_config, ka_interval), 0, - "Keep-alive interval." + "ka_interval", T_INT, + offsetof(PyObj_pjsua_acc_config, ka_interval), 0, + "Keep-alive interval." }, { - "ka_data", T_OBJECT_EX, - offsetof(PyObj_pjsua_acc_config, ka_data), 0, - "Keep-alive data." + "ka_data", T_OBJECT_EX, + offsetof(PyObj_pjsua_acc_config, ka_data), 0, + "Keep-alive data." }, { - "use_srtp", T_INT, - offsetof(PyObj_pjsua_acc_config, use_srtp), 0, - "Specify SRTP usage." + "use_srtp", T_INT, + offsetof(PyObj_pjsua_acc_config, use_srtp), 0, + "Specify SRTP usage." }, { - "srtp_secure_signaling", T_INT, - offsetof(PyObj_pjsua_acc_config, srtp_secure_signaling), 0, - "Specify if SRTP requires secure signaling to be used." + "srtp_secure_signaling", T_INT, + offsetof(PyObj_pjsua_acc_config, srtp_secure_signaling), 0, + "Specify if SRTP requires secure signaling to be used." }, { - "rtp_transport_cfg", T_OBJECT_EX, - offsetof(PyObj_pjsua_acc_config, rtp_transport_cfg), 0, - "Transport configuration for RTP." + "rtp_transport_cfg", T_OBJECT_EX, + offsetof(PyObj_pjsua_acc_config, rtp_transport_cfg), 0, + "Transport configuration for RTP." }, {NULL} /* Sentinel */ @@ -2098,7 +2097,7 @@ static PyTypeObject PyTyp_pjsua_acc_config = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "_pjsua.Acc_Config", /*tp_name*/ + "_pjsua.Acc_Config", /*tp_name*/ sizeof(PyObj_pjsua_acc_config), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)PyObj_pjsua_acc_config_delete,/*tp_dealloc*/ @@ -2117,7 +2116,7 @@ static PyTypeObject PyTyp_pjsua_acc_config = 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "Account settings", /* tp_doc */ + "Account settings", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ @@ -2148,15 +2147,15 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - int id; - int is_default; - PyObject *acc_uri; - int has_registration; - int expires; - int status; - PyObject *status_text; - int online_status; - PyObject *online_status_text; + int id; + int is_default; + PyObject *acc_uri; + int has_registration; + int expires; + int status; + PyObject *status_text; + int online_status; + PyObject *online_status_text; } PyObj_pjsua_acc_info; @@ -2174,15 +2173,15 @@ static void PyObj_pjsua_acc_info_delete(PyObj_pjsua_acc_info* self) static void PyObj_pjsua_acc_info_import(PyObj_pjsua_acc_info *obj, - const pjsua_acc_info *info) + const pjsua_acc_info *info) { - obj->id = info->id; + obj->id = info->id; obj->is_default = info->is_default; Py_XDECREF(obj->acc_uri); obj->acc_uri = PyString_FromPJ(&info->acc_uri); obj->has_registration = info->has_registration; obj->expires = info->expires; - obj->status = info->status; + obj->status = info->status; Py_XDECREF(obj->status_text); obj->status_text= PyString_FromPJ(&info->status_text); obj->online_status = info->online_status; @@ -2196,8 +2195,8 @@ static void PyObj_pjsua_acc_info_import(PyObj_pjsua_acc_info *obj, * constructor for acc_info object */ static PyObject * PyObj_pjsua_acc_info_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_acc_info *self; @@ -2207,8 +2206,8 @@ static PyObject * PyObj_pjsua_acc_info_new(PyTypeObject *type, self = (PyObj_pjsua_acc_info *)type->tp_alloc(type, 0); if (self != NULL) { self->acc_uri = PyString_FromString(""); - self->status_text = PyString_FromString(""); - self->online_status_text = PyString_FromString(""); + self->status_text = PyString_FromString(""); + self->online_status_text = PyString_FromString(""); } return (PyObject *)self; @@ -2221,12 +2220,12 @@ static PyMemberDef acc_info_members[] = { { "id", T_INT, - offsetof(PyObj_pjsua_acc_info, id), 0, + offsetof(PyObj_pjsua_acc_info, id), 0, "The account ID." }, { "is_default", T_INT, - offsetof(PyObj_pjsua_acc_info, is_default), 0, + offsetof(PyObj_pjsua_acc_info, is_default), 0, "Flag to indicate whether this is the default account. " }, { @@ -2236,18 +2235,18 @@ static PyMemberDef acc_info_members[] = }, { "has_registration", T_INT, - offsetof(PyObj_pjsua_acc_info, has_registration), 0, + offsetof(PyObj_pjsua_acc_info, has_registration), 0, "Flag to tell whether this account has registration setting " "(reg_uri is not empty)." }, { "expires", T_INT, - offsetof(PyObj_pjsua_acc_info, expires), 0, + offsetof(PyObj_pjsua_acc_info, expires), 0, "An up to date expiration interval for account registration session." }, { "status", T_INT, - offsetof(PyObj_pjsua_acc_info, status), 0, + offsetof(PyObj_pjsua_acc_info, status), 0, "Last registration status code. If status code is zero, " "the account is currently not registered. Any other value indicates " "the SIP status code of the registration. " @@ -2259,12 +2258,12 @@ static PyMemberDef acc_info_members[] = }, { "online_status", T_INT, - offsetof(PyObj_pjsua_acc_info, online_status), 0, + offsetof(PyObj_pjsua_acc_info, online_status), 0, "Presence online status for this account. " }, { "online_status_text", T_OBJECT_EX, - offsetof(PyObj_pjsua_acc_info, online_status_text), 0, + offsetof(PyObj_pjsua_acc_info, online_status_text), 0, "Presence online status text." }, {NULL} /* Sentinel */ @@ -2280,7 +2279,7 @@ static PyTypeObject PyTyp_pjsua_acc_info = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "_pjsua.Acc_Info", /*tp_name*/ + "_pjsua.Acc_Info", /*tp_name*/ sizeof(PyObj_pjsua_acc_info), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)PyObj_pjsua_acc_info_delete,/*tp_dealloc*/ @@ -2299,7 +2298,7 @@ static PyTypeObject PyTyp_pjsua_acc_info = 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "Account info", /* tp_doc */ + "Account info", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ @@ -2307,7 +2306,7 @@ static PyTypeObject PyTyp_pjsua_acc_info = 0, /* tp_iter */ 0, /* tp_iternext */ NULL, /* tp_methods */ - acc_info_members, /* tp_members */ + acc_info_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ @@ -2331,8 +2330,8 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - PyObject *uri; - int subscribe; + PyObject *uri; + int subscribe; } PyObj_pjsua_buddy_config; @@ -2348,7 +2347,7 @@ static void PyObj_pjsua_buddy_config_delete(PyObj_pjsua_buddy_config* self) static void PyObj_pjsua_buddy_config_import(PyObj_pjsua_buddy_config *obj, - const pjsua_buddy_config *cfg) + const pjsua_buddy_config *cfg) { Py_XDECREF(obj->uri); obj->uri = PyString_FromPJ(&cfg->uri); @@ -2357,7 +2356,7 @@ static void PyObj_pjsua_buddy_config_import(PyObj_pjsua_buddy_config *obj, static void PyObj_pjsua_buddy_config_export(pjsua_buddy_config *cfg, - PyObj_pjsua_buddy_config *obj) + PyObj_pjsua_buddy_config *obj) { cfg->uri = PyString_ToPJ(obj->uri); cfg->subscribe = obj->subscribe; @@ -2370,8 +2369,8 @@ static void PyObj_pjsua_buddy_config_export(pjsua_buddy_config *cfg, * constructor for buddy_config object */ static PyObject *PyObj_pjsua_buddy_config_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_buddy_config *self; @@ -2435,7 +2434,7 @@ static PyTypeObject PyTyp_pjsua_buddy_config = 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "Buddy config", /* tp_doc */ + "Buddy config", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ @@ -2465,15 +2464,15 @@ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ - int id; - PyObject *uri; - PyObject *contact; - int status; - PyObject *status_text; - int monitor_pres; - int activity; - int sub_state; - PyObject *sub_term_reason; + int id; + PyObject *uri; + PyObject *contact; + int status; + PyObject *status_text; + int monitor_pres; + int activity; + int sub_state; + PyObject *sub_term_reason; } PyObj_pjsua_buddy_info; @@ -2494,7 +2493,7 @@ static void PyObj_pjsua_buddy_info_delete(PyObj_pjsua_buddy_info* self) static void PyObj_pjsua_buddy_info_import(PyObj_pjsua_buddy_info *obj, - const pjsua_buddy_info *info) + const pjsua_buddy_info *info) { obj->id = info->id; Py_XDECREF(obj->uri); @@ -2518,8 +2517,8 @@ static void PyObj_pjsua_buddy_info_import(PyObj_pjsua_buddy_info *obj, * !modified @ 071206 */ static PyObject * PyObj_pjsua_buddy_info_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjsua_buddy_info *self; @@ -2529,9 +2528,9 @@ static PyObject * PyObj_pjsua_buddy_info_new(PyTypeObject *type, self = (PyObj_pjsua_buddy_info *)type->tp_alloc(type, 0); if (self != NULL) { self->uri = PyString_FromString(""); - self->contact = PyString_FromString(""); - self->status_text = PyString_FromString(""); - self->sub_term_reason = PyString_FromString(""); + self->contact = PyString_FromString(""); + self->status_text = PyString_FromString(""); + self->sub_term_reason = PyString_FromString(""); } return (PyObject *)self; } @@ -2604,7 +2603,7 @@ static PyTypeObject PyTyp_pjsua_buddy_info = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "_pjsua.Buddy_Info", /*tp_name*/ + "_pjsua.Buddy_Info", /*tp_name*/ sizeof(PyObj_pjsua_buddy_info), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)PyObj_pjsua_buddy_info_delete,/*tp_dealloc*/ @@ -2623,7 +2622,7 @@ static PyTypeObject PyTyp_pjsua_buddy_info = 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "Buddy Info object", /* tp_doc */ + "Buddy Info object", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ @@ -2718,7 +2717,7 @@ static PyTypeObject PyTyp_pjsua_codec_info = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "_pjsua.Codec_Info", /*tp_name*/ + "_pjsua.Codec_Info", /*tp_name*/ sizeof(PyObj_pjsua_codec_info), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)codec_info_dealloc, /*tp_dealloc*/ @@ -2737,7 +2736,7 @@ static PyTypeObject PyTyp_pjsua_codec_info = 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "Codec Info", /* tp_doc */ + "Codec Info", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ @@ -2745,7 +2744,7 @@ static PyTypeObject PyTyp_pjsua_codec_info = 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ - codec_info_members, /* tp_members */ + codec_info_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ @@ -2754,7 +2753,7 @@ static PyTypeObject PyTyp_pjsua_codec_info = 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ - codec_info_new, /* tp_new */ + codec_info_new, /* tp_new */ }; @@ -2770,13 +2769,13 @@ typedef struct PyObject_HEAD /* Type-specific fields go here. */ - int slot_id; - PyObject *name; - unsigned clock_rate; - unsigned channel_count; - unsigned samples_per_frame; - unsigned bits_per_sample; - PyObject *listeners; + int slot_id; + PyObject *name; + unsigned clock_rate; + unsigned channel_count; + unsigned samples_per_frame; + unsigned bits_per_sample; + PyObject *listeners; } PyObj_pjsua_conf_port_info; @@ -2808,7 +2807,7 @@ static PyObject * conf_port_info_new(PyTypeObject *type, PyObject *args, self = (PyObj_pjsua_conf_port_info *)type->tp_alloc(type, 0); if (self != NULL) { self->name = PyString_FromString(""); - self->listeners = PyList_New(0); + self->listeners = PyList_New(0); } return (PyObject *)self; } @@ -2852,7 +2851,7 @@ static PyMemberDef conf_port_info_members[] = "listeners", T_OBJECT_EX, offsetof(PyObj_pjsua_conf_port_info, listeners), 0, "Array of listeners (in other words, ports where this port " - "is transmitting to" + "is transmitting to" }, {NULL} /* Sentinel */ @@ -2868,7 +2867,7 @@ static PyTypeObject PyTyp_pjsua_conf_port_info = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "_pjsua.Conf_Port_Info", /*tp_name*/ + "_pjsua.Conf_Port_Info", /*tp_name*/ sizeof(PyObj_pjsua_conf_port_info), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)conf_port_info_dealloc,/*tp_dealloc*/ @@ -2941,8 +2940,8 @@ static void pjmedia_snd_dev_info_dealloc(PyObj_pjmedia_snd_dev_info* self) * constructor for pjmedia_snd_dev_info object */ static PyObject * pjmedia_snd_dev_info_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjmedia_snd_dev_info *self; @@ -2951,7 +2950,7 @@ static PyObject * pjmedia_snd_dev_info_new(PyTypeObject *type, self = (PyObj_pjmedia_snd_dev_info *)type->tp_alloc(type, 0); if (self != NULL) { - self->name = PyString_FromString(""); + self->name = PyString_FromString(""); } return (PyObject *)self; } @@ -3044,12 +3043,12 @@ typedef struct PyObject_HEAD /* Type-specific fields go here. */ - unsigned clock_rate; - unsigned channel_cnt; + unsigned clock_rate; + unsigned channel_cnt; pj_uint32_t avg_bps; pj_uint16_t frm_ptime; pj_uint8_t pcm_bits_per_sample; - pj_uint8_t pt; + pj_uint8_t pt; } PyObj_pjmedia_codec_param_info; @@ -3105,7 +3104,7 @@ static PyTypeObject PyTyp_pjmedia_codec_param_info = "_pjsua.PJMedia_Codec_Param_Info", /*tp_name*/ sizeof(PyObj_pjmedia_codec_param_info), /*tp_basicsize*/ 0, /*tp_itemsize*/ - 0, /*tp_dealloc*/ + 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -3187,7 +3186,7 @@ static PyMemberDef pjmedia_codec_param_setting_members[] = offsetof(PyObj_pjmedia_codec_param_setting, plc), 0, "Packet loss concealment" }, -#if 0 // no longer valid with latest modification in codec +#if 0 // no longer valid with latest modification in codec { "enc_fmtp_mode", T_INT, offsetof(PyObj_pjmedia_codec_param_setting, enc_fmtp_mode), 0, @@ -3214,7 +3213,7 @@ static PyTypeObject PyTyp_pjmedia_codec_param_setting = "_pjsua.PJMedia_Codec_Param_Setting",/*tp_name*/ sizeof(PyObj_pjmedia_codec_param_setting), /*tp_basicsize*/ 0, /*tp_itemsize*/ - 0, /*tp_dealloc*/ + 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -3274,8 +3273,8 @@ static void pjmedia_codec_param_dealloc(PyObj_pjmedia_codec_param* self) * constructor for pjmedia_codec_param object */ static PyObject * pjmedia_codec_param_new(PyTypeObject *type, - PyObject *args, - PyObject *kwds) + PyObject *args, + PyObject *kwds) { PyObj_pjmedia_codec_param *self; @@ -3285,11 +3284,11 @@ static PyObject * pjmedia_codec_param_new(PyTypeObject *type, self = (PyObj_pjmedia_codec_param *)type->tp_alloc(type, 0); if (self != NULL) { self->info = (PyObj_pjmedia_codec_param_info *) - PyType_GenericNew(&PyTyp_pjmedia_codec_param_info, - NULL, NULL); - self->setting = (PyObj_pjmedia_codec_param_setting *) - PyType_GenericNew(&PyTyp_pjmedia_codec_param_setting, - NULL, NULL); + PyType_GenericNew(&PyTyp_pjmedia_codec_param_info, + NULL, NULL); + self->setting = (PyObj_pjmedia_codec_param_setting *) + PyType_GenericNew(&PyTyp_pjmedia_codec_param_setting, + NULL, NULL); } return (PyObject *)self; } @@ -3348,7 +3347,7 @@ static PyTypeObject PyTyp_pjmedia_codec_param = 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "PJMedia Codec Param", /* tp_doc */ + "PJMedia Codec Param", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ @@ -3380,23 +3379,23 @@ typedef struct PyObject_HEAD /* Type-specific fields go here. */ - int id; - int role; - int acc_id; - PyObject *local_info; - PyObject *local_contact; - PyObject *remote_info; - PyObject *remote_contact; - PyObject *call_id; - int state; - PyObject *state_text; - int last_status; - PyObject *last_status_text; - int media_status; - int media_dir; - int conf_slot; - int connect_duration; - int total_duration; + int id; + int role; + int acc_id; + PyObject *local_info; + PyObject *local_contact; + PyObject *remote_info; + PyObject *remote_contact; + PyObject *call_id; + int state; + PyObject *state_text; + int last_status; + PyObject *last_status_text; + int media_status; + int media_dir; + int conf_slot; + int connect_duration; + int total_duration; } PyObj_pjsua_call_info; @@ -3433,12 +3432,12 @@ static PyObject * call_info_new(PyTypeObject *type, PyObject *args, self = (PyObj_pjsua_call_info *)type->tp_alloc(type, 0); if (self != NULL) { self->local_info = PyString_FromString(""); - self->local_contact = PyString_FromString(""); - self->remote_info = PyString_FromString(""); - self->remote_contact = PyString_FromString(""); - self->call_id = PyString_FromString(""); - self->state_text = PyString_FromString(""); - self->last_status_text = PyString_FromString(""); + self->local_contact = PyString_FromString(""); + self->remote_info = PyString_FromString(""); + self->remote_contact = PyString_FromString(""); + self->call_id = PyString_FromString(""); + self->state_text = PyString_FromString(""); + self->last_status_text = PyString_FromString(""); } return (PyObject *)self; } @@ -3547,7 +3546,7 @@ static PyTypeObject PyTyp_pjsua_call_info = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "_pjsua.Call_Info", /*tp_name*/ + "_pjsua.Call_Info", /*tp_name*/ sizeof(PyObj_pjsua_call_info), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)call_info_dealloc, /*tp_dealloc*/ @@ -3566,7 +3565,7 @@ static PyTypeObject PyTyp_pjsua_call_info = 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "Call Info", /* tp_doc */ + "Call Info", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ @@ -3574,7 +3573,7 @@ static PyTypeObject PyTyp_pjsua_call_info = 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ - call_info_members, /* tp_members */ + call_info_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ @@ -3583,7 +3582,7 @@ static PyTypeObject PyTyp_pjsua_call_info = 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ - call_info_new, /* tp_new */ + call_info_new, /* tp_new */ }; @@ -3598,7 +3597,7 @@ typedef struct /* Type-specific fields go here. */ PyObject *msg_info_buffer; // string - PyObject *msg_info_info; // string + PyObject *msg_info_info; // string } PyObj_pjsip_rx_data; @@ -3630,7 +3629,7 @@ static void PyObj_pjsip_rx_data_import(PyObj_pjsip_rx_data *obj, pjsip_rx_data * */ static PyObject * PyObj_pjsip_rx_data_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObj_pjsip_rx_data *self; + PyObj_pjsip_rx_data *self; PJ_UNUSED_ARG(args); PJ_UNUSED_ARG(kwds); @@ -3672,7 +3671,7 @@ static PyTypeObject PyTyp_pjsip_rx_data = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "_pjsua.Pjsip_Rx_Data", /*tp_name*/ + "_pjsua.Pjsip_Rx_Data", /*tp_name*/ sizeof(PyObj_pjsip_rx_data), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)PyObj_pjsip_rx_data_delete,/*tp_dealloc*/ @@ -3716,5 +3715,5 @@ static PyTypeObject PyTyp_pjsip_rx_data = ////////////////////////////////////////////////////////////////////////////// -#endif /* __PY_PJSUA_H__ */ +#endif /* __PY_PJSUA_H__ */ diff --git a/pjsip-apps/src/python/pjsua.py b/pjsip-apps/src/python/pjsua.py index 13391b288a..dcb3b0dcd2 100644 --- a/pjsip-apps/src/python/pjsua.py +++ b/pjsip-apps/src/python/pjsua.py @@ -1,4 +1,3 @@ -# $Id$ # # Object oriented PJSUA wrapper. # diff --git a/pjsip-apps/src/python/samples/call.py b/pjsip-apps/src/python/samples/call.py index 89cbb1c067..6a6637c460 100644 --- a/pjsip-apps/src/python/samples/call.py +++ b/pjsip-apps/src/python/samples/call.py @@ -1,4 +1,3 @@ -# $Id$ # # SIP call sample. # diff --git a/pjsip-apps/src/python/samples/presence.py b/pjsip-apps/src/python/samples/presence.py index a9ee8dd1f3..6236cae155 100644 --- a/pjsip-apps/src/python/samples/presence.py +++ b/pjsip-apps/src/python/samples/presence.py @@ -1,4 +1,3 @@ -# $Id$ # # Presence and instant messaging # diff --git a/pjsip-apps/src/python/samples/registration.py b/pjsip-apps/src/python/samples/registration.py index 6c07e967d3..f40d767f7f 100644 --- a/pjsip-apps/src/python/samples/registration.py +++ b/pjsip-apps/src/python/samples/registration.py @@ -1,4 +1,3 @@ -# $Id$ # # SIP account and registration sample. In this sample, the program # will block to wait until registration is complete diff --git a/pjsip-apps/src/python/samples/simplecall.py b/pjsip-apps/src/python/samples/simplecall.py index 4b5cd71ea3..ca9808c75f 100644 --- a/pjsip-apps/src/python/samples/simplecall.py +++ b/pjsip-apps/src/python/samples/simplecall.py @@ -1,4 +1,3 @@ -# $Id$ # # SIP account and registration sample. In this sample, the program # will block to wait until registration is complete diff --git a/pjsip-apps/src/python/setup-vc.py b/pjsip-apps/src/python/setup-vc.py index 82c5475ad3..f3c6f94d2c 100644 --- a/pjsip-apps/src/python/setup-vc.py +++ b/pjsip-apps/src/python/setup-vc.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua Setup script for Visual Studio # diff --git a/pjsip-apps/src/python/setup.py b/pjsip-apps/src/python/setup.py index 9d10eab3f9..0acf5127f4 100644 --- a/pjsip-apps/src/python/setup.py +++ b/pjsip-apps/src/python/setup.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua Setup script. # diff --git a/pjsip-apps/src/samples/aectest.c b/pjsip-apps/src/samples/aectest.c index a86ab9f45d..394b6f0ff8 100644 --- a/pjsip-apps/src/samples/aectest.c +++ b/pjsip-apps/src/samples/aectest.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,37 +29,37 @@ * \includelineno aectest.c */ #include -#include /* pj_getopt */ +#include /* pj_getopt */ #include #define THIS_FILE "aectest.c" -#define PTIME 20 +#define PTIME 20 #define TAIL_LENGTH 200 static const char *desc = -" FILE \n" -" \n" -" aectest.c \n" -" \n" -" PURPOSE \n" -" \n" -" Test the AEC effectiveness. \n" -" \n" -" USAGE \n" -" \n" -" aectest [options] \n" -" \n" -" is the signal played to the speaker. \n" -" is the signal captured from the microphone. \n" -" is the output file to store the test result \n" +" FILE \n" +" \n" +" aectest.c \n" +" \n" +" PURPOSE \n" +" \n" +" Test the AEC effectiveness. \n" +" \n" +" USAGE \n" +" \n" +" aectest [options] \n" +" \n" +" is the signal played to the speaker. \n" +" is the signal captured from the microphone. \n" +" is the output file to store the test result \n" "\n" " options:\n" " -d The delay between playback and capture in ms, at least 25 ms.\n" " Default is 25 ms. See note below. \n" -" -l Set the echo tail length in ms. Default is 200 ms \n" +" -l Set the echo tail length in ms. Default is 200 ms \n" " -r Set repeat count (default=1) \n" -" -a Algorithm: 0=default, 1=speex, 2=echo suppress, 3=WebRtc \n" -" -i Interactive \n" +" -a Algorithm: 0=default, 1=speex, 2=echo suppress, 3=WebRtc \n" +" -i Interactive \n" "\n" " Note that for the AEC internal buffering mechanism, it is required\n" " that the echoed signal (in REC.WAV) is delayed from the \n" @@ -91,7 +90,7 @@ int main(int argc, char *argv[]) { pj_caching_pool cp; pjmedia_endpt *med_endpt; - pj_pool_t *pool; + pj_pool_t *pool; pjmedia_port *wav_play; pjmedia_port *wav_rec; pjmedia_port *wav_out; @@ -106,58 +105,58 @@ int main(int argc, char *argv[]) pj_optind = 0; while ((c=pj_getopt(argc, argv, "d:l:a:r:i")) !=-1) { - switch (c) { - case 'd': - latency_ms = atoi(pj_optarg); - if (latency_ms < 25) { - puts("Invalid delay"); - puts(desc); - } - break; - case 'l': - tail_ms = atoi(pj_optarg); - break; - case 'a': - { - int alg = atoi(pj_optarg); - switch (alg) { - case 0: - opt = 0; - break; - case 1: - opt = PJMEDIA_ECHO_SPEEX; - break; - case 2: - opt = PJMEDIA_ECHO_SIMPLE; - break; - case 3: - opt = PJMEDIA_ECHO_WEBRTC; - break; - default: - puts("Invalid algorithm"); - puts(desc); - return 1; - } - } - break; - case 'r': - repeat = atoi(pj_optarg); - if (repeat < 1) { - puts("Invalid repeat count"); - puts(desc); - return 1; - } - break; - case 'i': - interactive = 1; - break; - } + switch (c) { + case 'd': + latency_ms = atoi(pj_optarg); + if (latency_ms < 25) { + puts("Invalid delay"); + puts(desc); + } + break; + case 'l': + tail_ms = atoi(pj_optarg); + break; + case 'a': + { + int alg = atoi(pj_optarg); + switch (alg) { + case 0: + opt = 0; + break; + case 1: + opt = PJMEDIA_ECHO_SPEEX; + break; + case 2: + opt = PJMEDIA_ECHO_SIMPLE; + break; + case 3: + opt = PJMEDIA_ECHO_WEBRTC; + break; + default: + puts("Invalid algorithm"); + puts(desc); + return 1; + } + } + break; + case 'r': + repeat = atoi(pj_optarg); + if (repeat < 1) { + puts("Invalid repeat count"); + puts(desc); + return 1; + } + break; + case 'i': + interactive = 1; + break; + } } if (argc - pj_optind != 3) { - puts("Error: missing argument(s)"); - puts(desc); - return 1; + puts("Error: missing argument(s)"); + puts(desc); + return 1; } /* Must init PJLIB first: */ @@ -175,64 +174,64 @@ int main(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool for our file player */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "wav", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "wav", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); /* Open wav_play */ status = pjmedia_wav_player_port_create(pool, argv[pj_optind], PTIME, - PJMEDIA_FILE_NO_LOOP, 0, - &wav_play); + PJMEDIA_FILE_NO_LOOP, 0, + &wav_play); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error opening playback WAV file", status); - return 1; + app_perror(THIS_FILE, "Error opening playback WAV file", status); + return 1; } /* Open recorded wav */ status = pjmedia_wav_player_port_create(pool, argv[pj_optind+1], PTIME, - PJMEDIA_FILE_NO_LOOP, 0, - &wav_rec); + PJMEDIA_FILE_NO_LOOP, 0, + &wav_rec); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error opening recorded WAV file", status); - return 1; + app_perror(THIS_FILE, "Error opening recorded WAV file", status); + return 1; } /* play and rec WAVs must have the same clock rate */ if (PJMEDIA_PIA_SRATE(&wav_play->info) != PJMEDIA_PIA_SRATE(&wav_rec->info)) { - puts("Error: clock rate mismatch in the WAV files"); - return 1; + puts("Error: clock rate mismatch in the WAV files"); + return 1; } /* .. and channel count */ if (PJMEDIA_PIA_CCNT(&wav_play->info) != PJMEDIA_PIA_CCNT(&wav_rec->info)) { - puts("Error: clock rate mismatch in the WAV files"); - return 1; + puts("Error: clock rate mismatch in the WAV files"); + return 1; } /* Create output wav */ status = pjmedia_wav_writer_port_create(pool, argv[pj_optind+2], - PJMEDIA_PIA_SRATE(&wav_play->info), - PJMEDIA_PIA_CCNT(&wav_play->info), - PJMEDIA_PIA_SPF(&wav_play->info), - PJMEDIA_PIA_BITS(&wav_play->info), - 0, 0, &wav_out); + PJMEDIA_PIA_SRATE(&wav_play->info), + PJMEDIA_PIA_CCNT(&wav_play->info), + PJMEDIA_PIA_SPF(&wav_play->info), + PJMEDIA_PIA_BITS(&wav_play->info), + 0, 0, &wav_out); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error opening output WAV file", status); - return 1; + app_perror(THIS_FILE, "Error opening output WAV file", status); + return 1; } /* Create echo canceller */ status = pjmedia_echo_create2(pool, PJMEDIA_PIA_SRATE(&wav_play->info), - PJMEDIA_PIA_CCNT(&wav_play->info), - PJMEDIA_PIA_SPF(&wav_play->info), - tail_ms, latency_ms, - opt, &ec); + PJMEDIA_PIA_CCNT(&wav_play->info), + PJMEDIA_PIA_SPF(&wav_play->info), + tail_ms, latency_ms, + opt, &ec); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error creating EC", status); - return 1; + app_perror(THIS_FILE, "Error creating EC", status); + return 1; } @@ -241,36 +240,36 @@ int main(int argc, char *argv[]) rec_frame.buf = pj_pool_alloc(pool, PJMEDIA_PIA_SPF(&wav_play->info)<<1); pj_get_timestamp(&t0); for (i=0; i < repeat; ++i) { - for (;;) { - play_frame.size = PJMEDIA_PIA_SPF(&wav_play->info) << 1; - status = pjmedia_port_get_frame(wav_play, &play_frame); - if (status != PJ_SUCCESS) - break; + for (;;) { + play_frame.size = PJMEDIA_PIA_SPF(&wav_play->info) << 1; + status = pjmedia_port_get_frame(wav_play, &play_frame); + if (status != PJ_SUCCESS) + break; - status = pjmedia_echo_playback(ec, (short*)play_frame.buf); + status = pjmedia_echo_playback(ec, (short*)play_frame.buf); - rec_frame.size = PJMEDIA_PIA_SPF(&wav_play->info) << 1; - status = pjmedia_port_get_frame(wav_rec, &rec_frame); - if (status != PJ_SUCCESS) - break; + rec_frame.size = PJMEDIA_PIA_SPF(&wav_play->info) << 1; + status = pjmedia_port_get_frame(wav_rec, &rec_frame); + if (status != PJ_SUCCESS) + break; - status = pjmedia_echo_capture(ec, (short*)rec_frame.buf, 0); + status = pjmedia_echo_capture(ec, (short*)rec_frame.buf, 0); - //status = pjmedia_echo_cancel(ec, (short*)rec_frame.buf, - // (short*)play_frame.buf, 0, NULL); + //status = pjmedia_echo_cancel(ec, (short*)rec_frame.buf, + // (short*)play_frame.buf, 0, NULL); - pjmedia_port_put_frame(wav_out, &rec_frame); - } + pjmedia_port_put_frame(wav_out, &rec_frame); + } - pjmedia_wav_player_port_set_pos(wav_play, 0); - pjmedia_wav_player_port_set_pos(wav_rec, 0); + pjmedia_wav_player_port_set_pos(wav_play, 0); + pjmedia_wav_player_port_set_pos(wav_rec, 0); } pj_get_timestamp(&t1); i = (int)pjmedia_wav_writer_port_get_pos(wav_out) / sizeof(pj_int16_t) * 1000 / - (PJMEDIA_PIA_SRATE(&wav_out->info) * PJMEDIA_PIA_CCNT(&wav_out->info)); + (PJMEDIA_PIA_SRATE(&wav_out->info) * PJMEDIA_PIA_CCNT(&wav_out->info)); PJ_LOG(3,(THIS_FILE, "Processed %3d.%03ds audio", - i / 1000, i % 1000)); + i / 1000, i % 1000)); PJ_LOG(3,(THIS_FILE, "Completed in %u msec\n", pj_elapsed_msec(&t0, &t1))); /* Destroy file port(s) */ @@ -297,10 +296,10 @@ int main(int argc, char *argv[]) pj_shutdown(); if (interactive) { - char s[10], *dummy; - puts("ENTER to quit"); - dummy = fgets(s, sizeof(s), stdin); - PJ_UNUSED_ARG(dummy); + char s[10], *dummy; + puts("ENTER to quit"); + dummy = fgets(s, sizeof(s), stdin); + PJ_UNUSED_ARG(dummy); } /* Done. */ diff --git a/pjsip-apps/src/samples/auddemo.c b/pjsip-apps/src/samples/auddemo.c index c91ac9cbaf..91f41d3f60 100644 --- a/pjsip-apps/src/samples/auddemo.c +++ b/pjsip-apps/src/samples/auddemo.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -23,9 +22,9 @@ #include #include -#define THIS_FILE "auddemo.c" -#define MAX_DEVICES 64 -#define WAV_FILE "auddemo.wav" +#define THIS_FILE "auddemo.c" +#define MAX_DEVICES 64 +#define WAV_FILE "auddemo.wav" static unsigned dev_count; @@ -36,9 +35,9 @@ static void app_perror(const char *title, pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); + pj_strerror(status, errmsg, sizeof(errmsg)); printf( "%s: %s (err=%d)\n", - title, errmsg, status); + title, errmsg, status); } static void list_devices(void) @@ -48,21 +47,21 @@ static void list_devices(void) dev_count = pjmedia_aud_dev_count(); if (dev_count == 0) { - PJ_LOG(3,(THIS_FILE, "No devices found")); - return; + PJ_LOG(3,(THIS_FILE, "No devices found")); + return; } PJ_LOG(3,(THIS_FILE, "Found %d devices:", dev_count)); for (i=0; i= dev_count) { - PJ_LOG(1,(THIS_FILE, "Error: invalid index %u", index)); - return; + PJ_LOG(1,(THIS_FILE, "Error: invalid index %u", index)); + return; } status = pjmedia_aud_dev_get_info(index, &info); if (status != PJ_SUCCESS) { - app_perror("pjmedia_aud_dev_get_info() error", status); - return; + app_perror("pjmedia_aud_dev_get_info() error", status); + return; } PJ_LOG(3, (THIS_FILE, "Device at index %u:", index)); @@ -116,38 +115,38 @@ static void show_dev_info(unsigned index) formats[0] = '\0'; if (info.caps & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT) { - unsigned i; - - for (i=0; i=0 ? "faster" : "slower"; - unsigned drift = result.rec_drift_per_sec>=0 ? - result.rec_drift_per_sec : - -result.rec_drift_per_sec; - - PJ_LOG(3,(THIS_FILE, " Clock drifts detected. Capture device " - "is running %d samples per second %s " - "than the playback device", - drift, which)); - } + if (result.rec_drift_per_sec == 0) { + PJ_LOG(3,(THIS_FILE, " No clock drift detected")); + } else { + const char *which = result.rec_drift_per_sec>=0 ? "faster" : "slower"; + unsigned drift = result.rec_drift_per_sec>=0 ? + result.rec_drift_per_sec : + -result.rec_drift_per_sec; + + PJ_LOG(3,(THIS_FILE, " Clock drifts detected. Capture device " + "is running %d samples per second %s " + "than the playback device", + drift, which)); + } } } @@ -257,22 +256,22 @@ static void record(unsigned rec_index, const char *filename) pj_status_t status; if (filename == NULL) - filename = WAV_FILE; + filename = WAV_FILE; pool = pj_pool_create(pjmedia_aud_subsys_get_pool_factory(), "wav", - 1000, 1000, NULL); + 1000, 1000, NULL); status = pjmedia_wav_writer_port_create(pool, filename, 16000, - 1, 320, 16, 0, 0, &wav); + 1, 320, 16, 0, 0, &wav); if (status != PJ_SUCCESS) { - app_perror("Error creating WAV file", status); - goto on_return; + app_perror("Error creating WAV file", status); + goto on_return; } status = pjmedia_aud_dev_default_param(rec_index, ¶m); if (status != PJ_SUCCESS) { - app_perror("pjmedia_aud_dev_default_param()", status); - goto on_return; + app_perror("pjmedia_aud_dev_default_param()", status); + goto on_return; } param.dir = PJMEDIA_DIR_CAPTURE; @@ -282,16 +281,16 @@ static void record(unsigned rec_index, const char *filename) param.bits_per_sample = PJMEDIA_PIA_BITS(&wav->info); status = pjmedia_aud_stream_create(¶m, &wav_rec_cb, NULL, wav, - &strm); + &strm); if (status != PJ_SUCCESS) { - app_perror("Error opening the sound device", status); - goto on_return; + app_perror("Error opening the sound device", status); + goto on_return; } status = pjmedia_aud_stream_start(strm); if (status != PJ_SUCCESS) { - app_perror("Error starting the sound device", status); - goto on_return; + app_perror("Error starting the sound device", status); + goto on_return; } PJ_LOG(3,(THIS_FILE, "Recording started, press ENTER to stop")); @@ -300,13 +299,13 @@ static void record(unsigned rec_index, const char *filename) on_return: if (strm) { - pjmedia_aud_stream_stop(strm); - pjmedia_aud_stream_destroy(strm); + pjmedia_aud_stream_stop(strm); + pjmedia_aud_stream_destroy(strm); } if (wav) - pjmedia_port_destroy(wav); + pjmedia_port_destroy(wav); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); } @@ -326,21 +325,21 @@ static void play_file(unsigned play_index, const char *filename) pj_status_t status; if (filename == NULL) - filename = WAV_FILE; + filename = WAV_FILE; pool = pj_pool_create(pjmedia_aud_subsys_get_pool_factory(), "wav", - 1000, 1000, NULL); + 1000, 1000, NULL); status = pjmedia_wav_player_port_create(pool, filename, 20, 0, 0, &wav); if (status != PJ_SUCCESS) { - app_perror("Error opening WAV file", status); - goto on_return; + app_perror("Error opening WAV file", status); + goto on_return; } status = pjmedia_aud_dev_default_param(play_index, ¶m); if (status != PJ_SUCCESS) { - app_perror("pjmedia_aud_dev_default_param()", status); - goto on_return; + app_perror("pjmedia_aud_dev_default_param()", status); + goto on_return; } param.dir = PJMEDIA_DIR_PLAYBACK; @@ -350,16 +349,16 @@ static void play_file(unsigned play_index, const char *filename) param.bits_per_sample = PJMEDIA_PIA_BITS(&wav->info); status = pjmedia_aud_stream_create(¶m, NULL, &wav_play_cb, wav, - &strm); + &strm); if (status != PJ_SUCCESS) { - app_perror("Error opening the sound device", status); - goto on_return; + app_perror("Error opening the sound device", status); + goto on_return; } status = pjmedia_aud_stream_start(strm); if (status != PJ_SUCCESS) { - app_perror("Error starting the sound device", status); - goto on_return; + app_perror("Error starting the sound device", status); + goto on_return; } PJ_LOG(3,(THIS_FILE, "Playback started, press ENTER to stop")); @@ -368,13 +367,13 @@ static void play_file(unsigned play_index, const char *filename) on_return: if (strm) { - pjmedia_aud_stream_stop(strm); - pjmedia_aud_stream_destroy(strm); + pjmedia_aud_stream_stop(strm); + pjmedia_aud_stream_destroy(strm); } if (wav) - pjmedia_port_destroy(wav); + pjmedia_port_destroy(wav); if (pool) - pj_pool_release(pool); + pj_pool_release(pool); } @@ -422,158 +421,158 @@ int main() status = pjmedia_aud_subsys_init(&cp.factory); if (status != PJ_SUCCESS) { - app_perror("pjmedia_aud_subsys_init()", status); - pj_caching_pool_destroy(&cp); - pj_shutdown(); - return 1; + app_perror("pjmedia_aud_subsys_init()", status); + pj_caching_pool_destroy(&cp); + pj_shutdown(); + return 1; } list_devices(); while (!done) { - char line[80]; - - print_menu(); - - if (fgets(line, sizeof(line), stdin)==NULL) - break; - - switch (line[0]) { - case 'l': - list_devices(); - break; - - case 'R': - pjmedia_aud_dev_refresh(); - puts("Audio device list refreshed."); - break; - - case 'i': - { - unsigned dev_index; - if (sscanf(line+2, "%u", &dev_index) != 1) { - puts("error: device ID required"); - break; - } - show_dev_info(dev_index); - } - break; - - case 't': - { - pjmedia_dir dir; - int rec_id, play_id; - unsigned clock_rate, ptime, chnum; - int cnt; - - cnt = sscanf(line+2, "%d %d %u %u %u", &rec_id, &play_id, - &clock_rate, &ptime, &chnum); - if (cnt < 4) { - puts("error: not enough parameters"); - break; - } - if (clock_rate < 8000 || clock_rate > 128000) { - puts("error: invalid clock rate"); - break; - } - if (ptime < 10 || ptime > 500) { - puts("error: invalid ptime"); - break; - } - if (cnt==5) { - if (chnum < 1 || chnum > 4) { - puts("error: invalid number of channels"); - break; - } - } else { - chnum = 1; - } - - if (rec_id >= 0 && rec_id < (int)dev_count) { - if (play_id >= 0 && play_id < (int)dev_count) - dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; - else - dir = PJMEDIA_DIR_CAPTURE; - } else if (play_id >= 0 && play_id < (int)dev_count) { - dir = PJMEDIA_DIR_PLAYBACK; - } else { - puts("error: at least one valid device index required"); - break; - } - - test_device(dir, rec_id, play_id, clock_rate, ptime, chnum); - - } - break; - - case 'r': - /* record */ - { - int index; - char filename[80]; - int count; - - count = sscanf(line+2, "%d %s", &index, filename); - if (count==1) - record(index, NULL); - else if (count==2) - record(index, filename); - else - puts("error: invalid command syntax"); - } - break; - - case 'p': - /* playback */ - { - int index; - char filename[80]; - int count; - - count = sscanf(line+2, "%d %s", &index, filename); - if (count==1) - play_file(index, NULL); - else if (count==2) - play_file(index, filename); - else - puts("error: invalid command syntax"); - } - break; - - case 'd': - /* latencies */ - { - int rec_lat, play_lat; - - if (sscanf(line+2, "%d %d", &rec_lat, &play_lat) == 2) { - capture_lat = (unsigned) - (rec_lat>=0? rec_lat:PJMEDIA_SND_DEFAULT_REC_LATENCY); - playback_lat = (unsigned) - (play_lat >= 0? play_lat : PJMEDIA_SND_DEFAULT_PLAY_LATENCY); - printf("Recording latency=%ums, playback latency=%ums", - capture_lat, playback_lat); - } else { - printf("Current latencies: record=%ums, playback=%ums", - capture_lat, playback_lat); - } - puts(""); - } - break; - - case 'v': - if (pj_log_get_level() <= 3) { - pj_log_set_level(5); - puts("Logging set to detail"); - } else { - pj_log_set_level(3); - puts("Logging set to quiet"); - } - break; - - case 'q': - done = PJ_TRUE; - break; - } + char line[80]; + + print_menu(); + + if (fgets(line, sizeof(line), stdin)==NULL) + break; + + switch (line[0]) { + case 'l': + list_devices(); + break; + + case 'R': + pjmedia_aud_dev_refresh(); + puts("Audio device list refreshed."); + break; + + case 'i': + { + unsigned dev_index; + if (sscanf(line+2, "%u", &dev_index) != 1) { + puts("error: device ID required"); + break; + } + show_dev_info(dev_index); + } + break; + + case 't': + { + pjmedia_dir dir; + int rec_id, play_id; + unsigned clock_rate, ptime, chnum; + int cnt; + + cnt = sscanf(line+2, "%d %d %u %u %u", &rec_id, &play_id, + &clock_rate, &ptime, &chnum); + if (cnt < 4) { + puts("error: not enough parameters"); + break; + } + if (clock_rate < 8000 || clock_rate > 128000) { + puts("error: invalid clock rate"); + break; + } + if (ptime < 10 || ptime > 500) { + puts("error: invalid ptime"); + break; + } + if (cnt==5) { + if (chnum < 1 || chnum > 4) { + puts("error: invalid number of channels"); + break; + } + } else { + chnum = 1; + } + + if (rec_id >= 0 && rec_id < (int)dev_count) { + if (play_id >= 0 && play_id < (int)dev_count) + dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; + else + dir = PJMEDIA_DIR_CAPTURE; + } else if (play_id >= 0 && play_id < (int)dev_count) { + dir = PJMEDIA_DIR_PLAYBACK; + } else { + puts("error: at least one valid device index required"); + break; + } + + test_device(dir, rec_id, play_id, clock_rate, ptime, chnum); + + } + break; + + case 'r': + /* record */ + { + int index; + char filename[80]; + int count; + + count = sscanf(line+2, "%d %s", &index, filename); + if (count==1) + record(index, NULL); + else if (count==2) + record(index, filename); + else + puts("error: invalid command syntax"); + } + break; + + case 'p': + /* playback */ + { + int index; + char filename[80]; + int count; + + count = sscanf(line+2, "%d %s", &index, filename); + if (count==1) + play_file(index, NULL); + else if (count==2) + play_file(index, filename); + else + puts("error: invalid command syntax"); + } + break; + + case 'd': + /* latencies */ + { + int rec_lat, play_lat; + + if (sscanf(line+2, "%d %d", &rec_lat, &play_lat) == 2) { + capture_lat = (unsigned) + (rec_lat>=0? rec_lat:PJMEDIA_SND_DEFAULT_REC_LATENCY); + playback_lat = (unsigned) + (play_lat >= 0? play_lat : PJMEDIA_SND_DEFAULT_PLAY_LATENCY); + printf("Recording latency=%ums, playback latency=%ums", + capture_lat, playback_lat); + } else { + printf("Current latencies: record=%ums, playback=%ums", + capture_lat, playback_lat); + } + puts(""); + } + break; + + case 'v': + if (pj_log_get_level() <= 3) { + pj_log_set_level(5); + puts("Logging set to detail"); + } else { + pj_log_set_level(3); + puts("Logging set to quiet"); + } + break; + + case 'q': + done = PJ_TRUE; + break; + } } pj_caching_pool_destroy(&cp); diff --git a/pjsip-apps/src/samples/aviplay.c b/pjsip-apps/src/samples/aviplay.c index 28d80bb6a3..a05c56740d 100644 --- a/pjsip-apps/src/samples/aviplay.c +++ b/pjsip-apps/src/samples/aviplay.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com) * @@ -64,17 +63,17 @@ #define THIS_FILE "aviplay.c" static const char *desc = -" FILE \n" -" \n" -" aviplay.c \n" -" \n" -" PURPOSE \n" -" \n" -" Demonstrate how to play a AVI file. \n" -" \n" -" USAGE \n" -" \n" -" aviplay FILE.AVI \n"; +" FILE \n" +" \n" +" aviplay.c \n" +" \n" +" PURPOSE \n" +" \n" +" Demonstrate how to play a AVI file. \n" +" \n" +" USAGE \n" +" \n" +" aviplay FILE.AVI \n"; struct codec_fmt { pj_uint32_t pjmedia_id; @@ -141,7 +140,7 @@ static pj_status_t avi_event_cb(pjmedia_event *event, } static pj_status_t codec_get_frame(pjmedia_port *port, - pjmedia_frame *frame) + pjmedia_frame *frame) { codec_port_data_t *port_data = (codec_port_data_t*)port->port_data.pdata; pjmedia_vid_codec *codec = port_data->codec; @@ -153,18 +152,18 @@ static pj_status_t codec_get_frame(pjmedia_port *port, if (port_data->conv) { pj_size_t frame_size = frame->size; - + status = pjmedia_port_get_frame(port_data->src_port, frame); if (status != PJ_SUCCESS) goto on_error; - + status = pjmedia_vid_codec_decode(codec, 1, frame, (unsigned)frame->size, &enc_frame); if (status != PJ_SUCCESS) goto on_error; - + frame->size = frame_size; status = pjmedia_converter_convert(port_data->conv, &enc_frame, frame); if (status != PJ_SUCCESS) goto on_error; - + return PJ_SUCCESS; } @@ -209,11 +208,11 @@ static int aviplay(pj_pool_t *pool, const char *fname) if (vid_port) { pjmedia_vid_port_param_default(¶m); - + CHECK( pjmedia_vid_dev_default_param(pool, PJMEDIA_VID_DEFAULT_RENDER_DEV, ¶m.vidparam) ); - + /* Create renderer, set it to active */ param.active = PJ_TRUE; param.vidparam.dir = PJMEDIA_DIR_RENDER; @@ -225,7 +224,7 @@ static int aviplay(pj_pool_t *pool, const char *fname) vid_port->info.fmt.id, vfd->size.w, vfd->size.h, vfd->fps.num, vfd->fps.denum); - + vfi = pjmedia_get_video_format_info( pjmedia_video_format_mgr_instance(), vid_port->info.fmt.id); @@ -242,7 +241,7 @@ static int aviplay(pj_pool_t *pool, const char *fname) pjmedia_port codec_port; pjmedia_vid_codec_param codec_param; struct codec_fmt *codecp = NULL; - + /* Lookup codec */ for (i = 0; i < sizeof(codec_fmts)/sizeof(codec_fmts[0]); i++) { if (vid_port->info.fmt.id == codec_fmts[i].pjmedia_id) { @@ -262,7 +261,7 @@ static int aviplay(pj_pool_t *pool, const char *fname) CHECK( pjmedia_vid_codec_mgr_get_default_param(NULL, codec_info, &codec_param) ); - + pjmedia_format_copy(&codec_param.enc_fmt, ¶m.vidparam.fmt); pjmedia_vid_dev_get_info(param.vidparam.rend_id, &rdr_info); @@ -276,29 +275,29 @@ static int aviplay(pj_pool_t *pool, const char *fname) } } } - + /* Open codec */ CHECK( pjmedia_vid_codec_mgr_alloc_codec(NULL, codec_info, &codec)); - + CHECK( pjmedia_vid_codec_init(codec, pool) ); - + pjmedia_format_copy(&codec_param.dec_fmt, ¶m.vidparam.fmt); codec_param.dir = PJMEDIA_DIR_DECODING; codec_param.packing = PJMEDIA_VID_PACKING_WHOLE; CHECK( pjmedia_vid_codec_open(codec, &codec_param) ); - + /* Alloc encoding buffer */ enc_buf_size = codec_param.dec_fmt.det.vid.size.w * - codec_param.dec_fmt.det.vid.size.h * 4; + codec_param.dec_fmt.det.vid.size.h * 4; enc_buf = pj_pool_alloc(pool, enc_buf_size + - 128 /*< padding, required for vid codecs - such as ffmpeg. Must be >= - AV_INPUT_BUFFER_PADDING_SIZE. - And must not be included in - the enc_buf_size calculation - above. */); - + 128 /*< padding, required for vid codecs + such as ffmpeg. Must be >= + AV_INPUT_BUFFER_PADDING_SIZE. + And must not be included in + the enc_buf_size calculation + above. */); + /* Init codec port */ pj_bzero(&codec_port, sizeof(codec_port)); CHECK( pjmedia_port_info_init2(&codec_port.info, &port_name, @@ -311,35 +310,35 @@ static int aviplay(pj_pool_t *pool, const char *fname) codec_port_data.src_port = vid_port; codec_port_data.enc_buf = enc_buf; codec_port_data.enc_buf_size = enc_buf_size; - + codec_port.get_frame = &codec_get_frame; codec_port.port_data.pdata = &codec_port_data; - + /* Check whether we need to convert the decoded frame */ if (codecp->need_conversion) { pjmedia_conversion_param conv_param; - + pjmedia_format_copy(&conv_param.src, ¶m.vidparam.fmt); pjmedia_format_copy(&conv_param.dst, ¶m.vidparam.fmt); conv_param.dst.id = codecp->dst_fmt; param.vidparam.fmt.id = conv_param.dst.id; - + CHECK( pjmedia_converter_create(NULL, pool, &conv_param, &codec_port_data.conv)); } - + CHECK( pjmedia_vid_port_create(pool, ¶m, &renderer) ); - + CHECK( pjmedia_vid_port_connect(renderer, &codec_port, PJ_FALSE) ); } else { CHECK( pjmedia_vid_port_create(pool, ¶m, &renderer) ); - + /* Connect avi port to renderer */ CHECK( pjmedia_vid_port_connect(renderer, vid_port, PJ_FALSE) ); } - + } aud_stream = pjmedia_avi_streams_get_stream_by_media(avi_streams, @@ -350,16 +349,16 @@ static int aviplay(pj_pool_t *pool, const char *fname) if (aud_port) { /* Create sound player port. */ CHECK( pjmedia_snd_port_create_player( - pool, /* pool */ - -1, /* use default dev. */ - PJMEDIA_PIA_SRATE(&aud_port->info),/* clock rate. */ - PJMEDIA_PIA_CCNT(&aud_port->info), /* # of channels. */ - PJMEDIA_PIA_SPF(&aud_port->info), /* samples per frame. */ - PJMEDIA_PIA_BITS(&aud_port->info), /* bits per sample. */ - 0, /* options */ - &snd_port /* returned port */ - )); - + pool, /* pool */ + -1, /* use default dev. */ + PJMEDIA_PIA_SRATE(&aud_port->info),/* clock rate. */ + PJMEDIA_PIA_CCNT(&aud_port->info), /* # of channels. */ + PJMEDIA_PIA_SPF(&aud_port->info), /* samples per frame. */ + PJMEDIA_PIA_BITS(&aud_port->info), /* bits per sample. */ + 0, /* options */ + &snd_port /* returned port */ + )); + /* Connect file port to the sound player. * Stream playing will commence immediately. */ @@ -368,7 +367,7 @@ static int aviplay(pj_pool_t *pool, const char *fname) if (vid_port) { pjmedia_vid_dev_cb cb; - + pj_bzero(&cb, sizeof(cb)); avi_port.snd_port = snd_port; avi_port.vid_port = renderer; @@ -387,7 +386,7 @@ static int aviplay(pj_pool_t *pool, const char *fname) snd_port, PJMEDIA_DIR_PLAYBACK)); } - + /* Start video streaming.. */ CHECK( pjmedia_vid_port_start(renderer) ); } @@ -445,9 +444,9 @@ static int main_func(int argc, char *argv[]) pj_status_t status = PJ_SUCCESS; if (argc != 2) { - puts("Error: filename required"); - puts(desc); - return 110; + puts("Error: filename required"); + puts(desc); + return 110; } #ifndef _MSC_VER @@ -463,12 +462,12 @@ static int main_func(int argc, char *argv[]) pj_caching_pool_init(&cp, &pj_pool_factory_default_policy, 0); /* Create memory pool for our file player */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "AVI", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "AVI", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); pjmedia_video_format_mgr_create(pool, 64, 0, NULL); pjmedia_converter_mgr_create(pool, NULL); @@ -478,29 +477,29 @@ static int main_func(int argc, char *argv[]) status = pjmedia_vid_dev_subsys_init(&cp.factory); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "Video init failed", status); - rc = 130; + rc = 130; goto on_return; } status = pjmedia_aud_subsys_init(&cp.factory); if (status != PJ_SUCCESS) { - rc = 140; + rc = 140; goto on_return; } #if defined(PJMEDIA_HAS_OPENH264_CODEC) && PJMEDIA_HAS_OPENH264_CODEC != 0 status = pjmedia_codec_openh264_vid_init(NULL, &cp.factory); if (status != PJ_SUCCESS) { - rc = 150; - goto on_return; + rc = 150; + goto on_return; } #endif #if PJMEDIA_HAS_FFMPEG_VID_CODEC status = pjmedia_codec_ffmpeg_vid_init(NULL, &cp.factory); if (status != PJ_SUCCESS) { - rc = 160; - goto on_return; + rc = 160; + goto on_return; } #endif diff --git a/pjsip-apps/src/samples/clidemo.c b/pjsip-apps/src/samples/clidemo.c index ccaa8219d6..73dc55cb0a 100644 --- a/pjsip-apps/src/samples/clidemo.c +++ b/pjsip-apps/src/samples/clidemo.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) * @@ -27,7 +26,7 @@ #include #include -#define THIS_FILE "clidemo.c" +#define THIS_FILE "clidemo.c" /* Set this to 1 if you want to let the system assign a port * for the CLI telnet daemon. @@ -92,11 +91,11 @@ static pj_status_t quit_app(pj_cli_cmd_val *cval) static void get_codec_list(pj_cli_dyn_choice_param *param) { if (param->arg_id == 3) { - param->cnt = 2; - pj_strdup2(param->pool, ¶m->choice[0].value, "iLbc"); - pj_strdup2(param->pool, ¶m->choice[0].desc, "iLbc Codec"); - pj_strdup2(param->pool, ¶m->choice[1].value, "g729"); - pj_strdup2(param->pool, ¶m->choice[1].desc, "g729 Codec"); + param->cnt = 2; + pj_strdup2(param->pool, ¶m->choice[0].value, "iLbc"); + pj_strdup2(param->pool, ¶m->choice[0].desc, "iLbc Codec"); + pj_strdup2(param->pool, ¶m->choice[1].value, "g729"); + pj_strdup2(param->pool, ¶m->choice[1].desc, "g729 Codec"); } } @@ -128,10 +127,10 @@ static struct cmd_xml_t cmd_xmls[] = { "", NULL}, {"" - " " - " " - " " - " " + " " + " " + " " + " " "", NULL}, {"" @@ -168,21 +167,21 @@ int main() status = pj_cli_create(&cli_cfg, &cli); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* * Register some commands. */ for (i = 0; i < sizeof(cmd_xmls)/sizeof(cmd_xmls[0]); i++) { - xml = pj_str(cmd_xmls[i].xml); + xml = pj_str(cmd_xmls[i].xml); status = pj_cli_add_cmd_from_xml(cli, NULL, &xml, - cmd_xmls[i].handler, NULL, - get_codec_list); + cmd_xmls[i].handler, NULL, + get_codec_list); if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "Failed adding command from XML #%d", i)); - goto on_return; - } + PJ_PERROR(1,(THIS_FILE, status, + "Failed adding command from XML #%d", i)); + goto on_return; + } } /* @@ -198,7 +197,7 @@ int main() tcfg.prompt_str = pj_str("CoolWater% "); status = pj_cli_telnet_create(cli, &tcfg, NULL); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* * Run the system specific main loop. @@ -237,7 +236,7 @@ pj_status_t app_main(pj_cli_t *c) */ status = pj_cli_console_create(c, &console_cfg, &sess, NULL); if (status != PJ_SUCCESS) - return status; + return status; pj_log_set_log_func(&log_writer); @@ -245,20 +244,20 @@ pj_status_t app_main(pj_cli_t *c) * Main loop. */ for (;;) { - char cmdline[PJ_CLI_MAX_CMDBUF]; + char cmdline[PJ_CLI_MAX_CMDBUF]; status = pj_cli_console_process(sess, &cmdline[0], sizeof(cmdline)); - if (status != PJ_SUCCESS) - break; - - //pj_ansi_strcpy(cmdline, "sayhello {Teluu Inc.}"); - if (status == PJ_CLI_EEXIT) { - /* exit is called */ - break; - } else if (status != PJ_SUCCESS) { - /* Something wrong with the cmdline */ - PJ_PERROR(1,(THIS_FILE, status, "Exec error")); - } + if (status != PJ_SUCCESS) + break; + + //pj_ansi_strcpy(cmdline, "sayhello {Teluu Inc.}"); + if (status == PJ_CLI_EEXIT) { + /* exit is called */ + break; + } else if (status != PJ_SUCCESS) { + /* Something wrong with the cmdline */ + PJ_PERROR(1,(THIS_FILE, status, "Exec error")); + } } return PJ_SUCCESS; diff --git a/pjsip-apps/src/samples/confbench.c b/pjsip-apps/src/samples/confbench.c index 84305f6cb2..efcf5a1980 100644 --- a/pjsip-apps/src/samples/confbench.c +++ b/pjsip-apps/src/samples/confbench.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,9 +31,9 @@ #include -#include /* pj_getopt */ +#include /* pj_getopt */ #include -#include /* atoi() */ +#include /* atoi() */ #include #include @@ -47,28 +46,28 @@ * HAS_RESAMPLE will activate resampling on about half * the port. */ -#define TEST_SET LARGE_SET -#define HAS_RESAMPLE 0 +#define TEST_SET LARGE_SET +#define HAS_RESAMPLE 0 -#define SMALL_SET 16 -#define LARGE_SET 100 +#define SMALL_SET 16 +#define LARGE_SET 100 -#define PORT_COUNT 254 -#define CLOCK_RATE 16000 +#define PORT_COUNT 254 +#define CLOCK_RATE 16000 #define SAMPLES_PER_FRAME (CLOCK_RATE/100) #if HAS_RESAMPLE -# define SINE_CLOCK 32000 +# define SINE_CLOCK 32000 #else -# define SINE_CLOCK CLOCK_RATE +# define SINE_CLOCK CLOCK_RATE #endif -#define SINE_PTIME 20 -#define DURATION 10 +#define SINE_PTIME 20 +#define DURATION 10 -#define SINE_COUNT TEST_SET -#define NULL_COUNT TEST_SET -#define IDLE_COUNT 32 +#define SINE_COUNT TEST_SET +#define NULL_COUNT TEST_SET +#define IDLE_COUNT 32 static void app_perror(const char *sender, const char *title, pj_status_t status) @@ -82,9 +81,9 @@ static void app_perror(const char *sender, const char *title, pj_status_t status struct Times { - FILETIME kernel_time; + FILETIME kernel_time; ULARGE_INTEGER u_kernel_time; - FILETIME user_time; + FILETIME user_time; ULARGE_INTEGER u_user_time; ULARGE_INTEGER u_total; }; @@ -110,13 +109,13 @@ static void benchmark(void) ts = GetTickCount(); rc = GetProcessTimes(GetCurrentProcess(), &creation_time, &exit_time, - &start.kernel_time, &start.user_time); + &start.kernel_time, &start.user_time); for (i=DURATION; i>0; --i) { - printf("\r%d ", i); fflush(stdout); - pj_thread_sleep(1000); + printf("\r%d ", i); fflush(stdout); + pj_thread_sleep(1000); } rc = GetProcessTimes(GetCurrentProcess(), &creation_time, &exit_time, - &end.kernel_time, &end.user_time); + &end.kernel_time, &end.user_time); te = GetTickCount(); process(&start); @@ -134,13 +133,13 @@ static void benchmark(void) /* Struct attached to sine generator */ typedef struct { - pj_int16_t *samples; /* Sine samples. */ + pj_int16_t *samples; /* Sine samples. */ } port_data; /* This callback is called to feed more samples */ static pj_status_t sine_get_frame( pjmedia_port *port, - pjmedia_frame *frame) + pjmedia_frame *frame) { port_data *sine = port->port_data.pdata; pj_int16_t *samples = frame->buf; @@ -154,15 +153,15 @@ static pj_status_t sine_get_frame( pjmedia_port *port, right = 0; for (i=0; isamples[left]; - ++left; - - if (PJMEDIA_PIA_CCNT(&port->info) == 2) { - *samples++ = sine->samples[right]; - right += 2; /* higher pitch so we can distinguish left and right. */ - if (right >= count) - right = 0; - } + *samples++ = sine->samples[left]; + ++left; + + if (PJMEDIA_PIA_CCNT(&port->info) == 2) { + *samples++ = sine->samples[right]; + right += 2; /* higher pitch so we can distinguish left and right. */ + if (right >= count) + right = 0; + } } /* Must set frame->type correctly, otherwise the sound device @@ -181,9 +180,9 @@ static pj_status_t sine_get_frame( pjmedia_port *port, * Create a media port to generate sine wave samples. */ static pj_status_t create_sine_port(pj_pool_t *pool, - unsigned sampling_rate, - unsigned channel_count, - pjmedia_port **p_port) + unsigned sampling_rate, + unsigned channel_count, + pjmedia_port **p_port) { pjmedia_port *port; unsigned i; @@ -192,7 +191,7 @@ static pj_status_t create_sine_port(pj_pool_t *pool, port_data *sine; PJ_ASSERT_RETURN(pool && channel_count > 0 && channel_count <= 2, - PJ_EINVAL); + PJ_EINVAL); port = pj_pool_zalloc(pool, sizeof(pjmedia_port)); PJ_ASSERT_RETURN(port != NULL, PJ_ENOMEM); @@ -200,8 +199,8 @@ static pj_status_t create_sine_port(pj_pool_t *pool, /* Fill in port info. */ port_name = pj_str("sine generator"); pjmedia_port_info_init(&port->info, &port_name, - 12345, sampling_rate, channel_count, 16, - sampling_rate * SINE_PTIME / 1000 * channel_count); + 12345, sampling_rate, channel_count, 16, + sampling_rate * SINE_PTIME / 1000 * channel_count); /* Set the function to feed frame */ port->get_frame = &sine_get_frame; @@ -218,7 +217,7 @@ static pj_status_t create_sine_port(pj_pool_t *pool, for( i=0; isamples[i] = (pj_int16_t) (10000.0 * - sin(((double)i/(double)count) * M_PI * 8.) ); + sin(((double)i/(double)count) * M_PI * 8.) ); } *p_port = port; @@ -246,12 +245,12 @@ int main() PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); pj_caching_pool_init(&cp, &pj_pool_factory_default_policy, 0); - pool = pj_pool_create( &cp.factory, /* pool factory */ - "wav", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "wav", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); status = pjmedia_endpt_create(&cp.factory, NULL, 1, &med_endpt); PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); @@ -259,14 +258,14 @@ int main() status = pjmedia_conf_create( pool, - PORT_COUNT, - CLOCK_RATE, - 1, SAMPLES_PER_FRAME, 16, - PJMEDIA_CONF_NO_DEVICE, - &conf); + PORT_COUNT, + CLOCK_RATE, + 1, SAMPLES_PER_FRAME, 16, + PJMEDIA_CONF_NO_DEVICE, + &conf); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create conference bridge", status); - return 1; + app_perror(THIS_FILE, "Unable to create conference bridge", status); + return 1; } printf("Resampling is %s\n", (HAS_RESAMPLE?"active":"disabled")); @@ -274,56 +273,56 @@ int main() /* Create Null ports */ printf("Creating %d null ports..\n", NULL_COUNT); for (i=0; i @@ -19,10 +18,10 @@ */ #include -#include /* pj_getopt */ +#include /* pj_getopt */ #include -#include /* atoi() */ +#include /* atoi() */ #include #include "util.h" @@ -48,30 +47,30 @@ static const char *desc = - " FILE: \n" - " \n" - " confsample.c \n" - " \n" - " PURPOSE: \n" - " \n" - " Demonstrate how to use conference bridge. \n" - " \n" - " USAGE: \n" - " \n" - " confsample [options] [file1.wav] [file2.wav] ... \n" - " \n" - " options: \n" + " FILE: \n" + " \n" + " confsample.c \n" + " \n" + " PURPOSE: \n" + " \n" + " Demonstrate how to use conference bridge. \n" + " \n" + " USAGE: \n" + " \n" + " confsample [options] [file1.wav] [file2.wav] ... \n" + " \n" + " options: \n" SND_USAGE - " \n" + " \n" " fileN.wav are optional WAV files to be connected to the conference \n" " bridge. The WAV files MUST have single channel (mono) and 16 bit PCM \n" - " samples. It can have arbitrary sampling rate. \n" - " \n" - " DESCRIPTION: \n" - " \n" + " samples. It can have arbitrary sampling rate. \n" + " \n" + " DESCRIPTION: \n" + " \n" " Here we create a conference bridge, with at least one port (port zero \n" - " is always created for the sound device). \n" - " \n" + " is always created for the sound device). \n" + " \n" " If WAV files are specified, the WAV file player ports will be connected \n" " to slot starting from number one in the bridge. The WAV files can have \n" " arbitrary sampling rate; the bridge will convert it to its clock rate. \n" @@ -106,16 +105,16 @@ static pj_bool_t input(const char *title, char *buf, pj_size_t len) printf("%s (empty to cancel): ", title); fflush(stdout); if (fgets(buf, (int)len, stdin) == NULL) - return PJ_FALSE; + return PJ_FALSE; /* Remove trailing newlines. */ for (p=buf; ; ++p) { - if (*p=='\r' || *p=='\n') *p='\0'; - else if (!*p) break; + if (*p=='\r' || *p=='\n') *p='\0'; + else if (!*p) break; } if (!*buf) - return PJ_FALSE; + return PJ_FALSE; return PJ_TRUE; } @@ -138,7 +137,7 @@ int main(int argc, char *argv[]) pjmedia_conf *conf; int i, port_count, file_count; - pjmedia_port **file_port; /* Array of file ports */ + pjmedia_port **file_port; /* Array of file ports */ pjmedia_port *rec_port = NULL; /* Wav writer port */ char tmp[10]; @@ -151,10 +150,10 @@ int main(int argc, char *argv[]) /* Get command line options. */ if (get_snd_options(THIS_FILE, argc, argv, &dev_id, &clock_rate, - &channel_count, &samples_per_frame, &bits_per_sample)) + &channel_count, &samples_per_frame, &bits_per_sample)) { - usage(); - return 1; + usage(); + return 1; } /* Must create a pool factory before we can allocate any memory. */ @@ -168,12 +167,12 @@ int main(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool to allocate memory */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "wav", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "wav", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); file_count = argc - pj_optind; @@ -183,29 +182,29 @@ int main(int argc, char *argv[]) * With default options (zero), the bridge will create an instance of * sound capture and playback device and connect them to slot zero. */ - status = pjmedia_conf_create( pool, /* pool to use */ - port_count,/* number of ports */ - clock_rate, - channel_count, - samples_per_frame, - bits_per_sample, - 0, /* options */ - &conf /* result */ - ); + status = pjmedia_conf_create( pool, /* pool to use */ + port_count,/* number of ports */ + clock_rate, + channel_count, + samples_per_frame, + bits_per_sample, + 0, /* options */ + &conf /* result */ + ); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create conference bridge", status); - return 1; + app_perror(THIS_FILE, "Unable to create conference bridge", status); + return 1; } #if RECORDER status = pjmedia_wav_writer_port_create( pool, "confrecord.wav", - clock_rate, channel_count, - samples_per_frame, - bits_per_sample, 0, 0, - &rec_port); + clock_rate, channel_count, + samples_per_frame, + bits_per_sample, 0, 0, + &rec_port); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create WAV writer", status); - return 1; + app_perror(THIS_FILE, "Unable to create WAV writer", status); + return 1; } pjmedia_conf_add_port(conf, pool, rec_port, NULL, NULL); @@ -217,34 +216,34 @@ int main(int argc, char *argv[]) for (i=0; i= port_count) { - puts("Invalid slot number"); - continue; - } - - if (!input("Enter destination port number", tmp2, sizeof(tmp2)) ) - continue; - dst = strtol(tmp2, &err, 10); - if (*err || dst < 0 || dst >= port_count) { - puts("Invalid slot number"); - continue; - } - - status = pjmedia_conf_connect_port(conf, src, dst, 0); - if (status != PJ_SUCCESS) - app_perror(THIS_FILE, "Error connecting port", status); - - break; - - case 'd': - puts(""); - puts("Disconnect port connection"); - if (!input("Enter source port number", tmp1, sizeof(tmp1)) ) - continue; - src = strtol(tmp1, &err, 10); - if (*err || src < 0 || src >= port_count) { - puts("Invalid slot number"); - continue; - } - - if (!input("Enter destination port number", tmp2, sizeof(tmp2)) ) - continue; - dst = strtol(tmp2, &err, 10); - if (*err || dst < 0 || dst >= port_count) { - puts("Invalid slot number"); - continue; - } - - status = pjmedia_conf_disconnect_port(conf, src, dst); - if (status != PJ_SUCCESS) - app_perror(THIS_FILE, "Error connecting port", status); - - - break; - - case 't': - puts(""); - puts("Adjust transmit level of a port"); - if (!input("Enter port number", tmp1, sizeof(tmp1)) ) - continue; - src = strtol(tmp1, &err, 10); - if (*err || src < 0 || src >= port_count) { - puts("Invalid slot number"); - continue; - } - - if (!input("Enter level (-128 to >127, 0 for normal)", - tmp2, sizeof(tmp2)) ) - continue; - level = strtol(tmp2, &err, 10); - if (*err || level < -128) { - puts("Invalid level"); - continue; - } - - status = pjmedia_conf_adjust_tx_level( conf, src, level); - if (status != PJ_SUCCESS) - app_perror(THIS_FILE, "Error adjusting level", status); - break; - - - case 'r': - puts(""); - puts("Adjust receive level of a port"); - if (!input("Enter port number", tmp1, sizeof(tmp1)) ) - continue; - src = strtol(tmp1, &err, 10); - if (*err || src < 0 || src >= port_count) { - puts("Invalid slot number"); - continue; - } - - if (!input("Enter level (-128 to >127, 0 for normal)", - tmp2, sizeof(tmp2)) ) - continue; - level = strtol(tmp2, &err, 10); - if (*err || level < -128) { - puts("Invalid level"); - continue; - } - - status = pjmedia_conf_adjust_rx_level( conf, src, level); - if (status != PJ_SUCCESS) - app_perror(THIS_FILE, "Error adjusting level", status); - break; - - case 'v': - puts(""); - puts("Display VU meter"); - if (!input("Enter port number to monitor", tmp1, sizeof(tmp1)) ) - continue; - src = strtol(tmp1, &err, 10); - if (*err || src < 0 || src >= port_count) { - puts("Invalid slot number"); - continue; - } - - if (!input("Enter r for rx level or t for tx level", tmp2, sizeof(tmp2))) - continue; - if (tmp2[0] != 'r' && tmp2[0] != 't') { - puts("Invalid option"); - continue; - } - - if (!input("Duration to monitor (in seconds)", tmp1, sizeof(tmp1)) ) - continue; - dur = strtol(tmp1, &err, 10); - if (*err) { - puts("Invalid duration number"); - continue; - } - - monitor_level(conf, src, tmp2[0], dur); - break; - - case 'q': - goto on_quit; - - default: - printf("Invalid input character '%c'\n", tmp[0]); - break; - } + char tmp1[10]; + char tmp2[10]; + char *err; + int src, dst, level, dur; + + puts(""); + conf_list(conf, 0); + puts(""); + puts("Menu:"); + puts(" s Show ports details"); + puts(" c Connect one port to another"); + puts(" d Disconnect port connection"); + puts(" t Adjust signal level transmitted (tx) to a port"); + puts(" r Adjust signal level received (rx) from a port"); + puts(" v Display VU meter for a particular port"); + puts(" q Quit"); + puts(""); + + printf("Enter selection: "); fflush(stdout); + + if (fgets(tmp, sizeof(tmp), stdin) == NULL) + break; + + switch (tmp[0]) { + case 's': + puts(""); + conf_list(conf, 1); + break; + + case 'c': + puts(""); + puts("Connect source port to destination port"); + if (!input("Enter source port number", tmp1, sizeof(tmp1)) ) + continue; + src = strtol(tmp1, &err, 10); + if (*err || src < 0 || src >= port_count) { + puts("Invalid slot number"); + continue; + } + + if (!input("Enter destination port number", tmp2, sizeof(tmp2)) ) + continue; + dst = strtol(tmp2, &err, 10); + if (*err || dst < 0 || dst >= port_count) { + puts("Invalid slot number"); + continue; + } + + status = pjmedia_conf_connect_port(conf, src, dst, 0); + if (status != PJ_SUCCESS) + app_perror(THIS_FILE, "Error connecting port", status); + + break; + + case 'd': + puts(""); + puts("Disconnect port connection"); + if (!input("Enter source port number", tmp1, sizeof(tmp1)) ) + continue; + src = strtol(tmp1, &err, 10); + if (*err || src < 0 || src >= port_count) { + puts("Invalid slot number"); + continue; + } + + if (!input("Enter destination port number", tmp2, sizeof(tmp2)) ) + continue; + dst = strtol(tmp2, &err, 10); + if (*err || dst < 0 || dst >= port_count) { + puts("Invalid slot number"); + continue; + } + + status = pjmedia_conf_disconnect_port(conf, src, dst); + if (status != PJ_SUCCESS) + app_perror(THIS_FILE, "Error connecting port", status); + + + break; + + case 't': + puts(""); + puts("Adjust transmit level of a port"); + if (!input("Enter port number", tmp1, sizeof(tmp1)) ) + continue; + src = strtol(tmp1, &err, 10); + if (*err || src < 0 || src >= port_count) { + puts("Invalid slot number"); + continue; + } + + if (!input("Enter level (-128 to >127, 0 for normal)", + tmp2, sizeof(tmp2)) ) + continue; + level = strtol(tmp2, &err, 10); + if (*err || level < -128) { + puts("Invalid level"); + continue; + } + + status = pjmedia_conf_adjust_tx_level( conf, src, level); + if (status != PJ_SUCCESS) + app_perror(THIS_FILE, "Error adjusting level", status); + break; + + + case 'r': + puts(""); + puts("Adjust receive level of a port"); + if (!input("Enter port number", tmp1, sizeof(tmp1)) ) + continue; + src = strtol(tmp1, &err, 10); + if (*err || src < 0 || src >= port_count) { + puts("Invalid slot number"); + continue; + } + + if (!input("Enter level (-128 to >127, 0 for normal)", + tmp2, sizeof(tmp2)) ) + continue; + level = strtol(tmp2, &err, 10); + if (*err || level < -128) { + puts("Invalid level"); + continue; + } + + status = pjmedia_conf_adjust_rx_level( conf, src, level); + if (status != PJ_SUCCESS) + app_perror(THIS_FILE, "Error adjusting level", status); + break; + + case 'v': + puts(""); + puts("Display VU meter"); + if (!input("Enter port number to monitor", tmp1, sizeof(tmp1)) ) + continue; + src = strtol(tmp1, &err, 10); + if (*err || src < 0 || src >= port_count) { + puts("Invalid slot number"); + continue; + } + + if (!input("Enter r for rx level or t for tx level", tmp2, sizeof(tmp2))) + continue; + if (tmp2[0] != 'r' && tmp2[0] != 't') { + puts("Invalid option"); + continue; + } + + if (!input("Duration to monitor (in seconds)", tmp1, sizeof(tmp1)) ) + continue; + dur = strtol(tmp1, &err, 10); + if (*err) { + puts("Invalid duration number"); + continue; + } + + monitor_level(conf, src, tmp2[0], dur); + break; + + case 'q': + goto on_quit; + + default: + printf("Invalid input character '%c'\n", tmp[0]); + break; + } } on_quit: @@ -446,13 +445,13 @@ int main(int argc, char *argv[]) /* Destroy file ports */ for (i=0; ilistener_cnt; ++j) { - char s[10]; - pj_ansi_sprintf(s, "#%d ", port_info->listener_slots[j]); - pj_ansi_strcat(txlist, s); - - } - - if (txlist[0] == '\0') { - txlist[0] = '-'; - txlist[1] = '\0'; - } - - if (!detail) { - printf("Port #%02d %-25.*s transmitting to: %s\n", - port_info->slot, - (int)port_info->name.slen, - port_info->name.ptr, - txlist); - } else { - unsigned tx_level, rx_level; - - pjmedia_conf_get_signal_level(conf, port_info->slot, - &tx_level, &rx_level); - - printf("Port #%02d:\n" - " Name : %.*s\n" - " Sampling rate : %d Hz\n" - " Samples per frame : %d\n" - " Frame time : %d ms\n" - " Signal level adjustment : tx=%d, rx=%d\n" - " Current signal level : tx=%u, rx=%u\n" - " Transmitting to ports : %s\n\n", - port_info->slot, - (int)port_info->name.slen, - port_info->name.ptr, - port_info->clock_rate, - port_info->samples_per_frame, - port_info->samples_per_frame*1000/port_info->clock_rate, - port_info->tx_adj_level, - port_info->rx_adj_level, - tx_level, - rx_level, - txlist); - } + char txlist[4*MAX_PORTS]; + unsigned j; + pjmedia_conf_port_info *port_info = &info[i]; + + txlist[0] = '\0'; + for (j=0; jlistener_cnt; ++j) { + char s[10]; + pj_ansi_sprintf(s, "#%d ", port_info->listener_slots[j]); + pj_ansi_strcat(txlist, s); + + } + + if (txlist[0] == '\0') { + txlist[0] = '-'; + txlist[1] = '\0'; + } + + if (!detail) { + printf("Port #%02d %-25.*s transmitting to: %s\n", + port_info->slot, + (int)port_info->name.slen, + port_info->name.ptr, + txlist); + } else { + unsigned tx_level, rx_level; + + pjmedia_conf_get_signal_level(conf, port_info->slot, + &tx_level, &rx_level); + + printf("Port #%02d:\n" + " Name : %.*s\n" + " Sampling rate : %d Hz\n" + " Samples per frame : %d\n" + " Frame time : %d ms\n" + " Signal level adjustment : tx=%d, rx=%d\n" + " Current signal level : tx=%u, rx=%u\n" + " Transmitting to ports : %s\n\n", + port_info->slot, + (int)port_info->name.slen, + port_info->name.ptr, + port_info->clock_rate, + port_info->samples_per_frame, + port_info->samples_per_frame*1000/port_info->clock_rate, + port_info->tx_adj_level, + port_info->rx_adj_level, + tx_level, + rx_level, + txlist); + } } puts(""); @@ -554,7 +553,7 @@ static void monitor_level(pjmedia_conf *conf, int slot, int dir, int dur) puts(""); printf("Displaying VU meter for port %d for about %d seconds\n", - slot, dur); + slot, dur); total_count = dur * 1000 / SLEEP; @@ -562,46 +561,46 @@ static void monitor_level(pjmedia_conf *conf, int slot, int dir, int dur) samp_cnt = 0; for (i=0; i diff --git a/pjsip-apps/src/samples/encdec.c b/pjsip-apps/src/samples/encdec.c index 17f50f2555..2851003cf3 100644 --- a/pjsip-apps/src/samples/encdec.c +++ b/pjsip-apps/src/samples/encdec.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,13 +34,13 @@ #define THIS_FILE "encdec.c" static const char *desc = - " encdec \n" - " \n" - " PURPOSE: \n" + " encdec \n" + " \n" + " PURPOSE: \n" " Encode input WAV with a codec, and decode the result to another WAV \n" "\n" "\n" - " USAGE: \n" + " USAGE: \n" " encdec codec input.wav output.wav \n" "\n" "\n" @@ -57,11 +56,11 @@ static const char *desc = //#define PJ_TRACE 1 #ifndef PJ_TRACE -# define PJ_TRACE 0 +# define PJ_TRACE 0 #endif #if PJ_TRACE -# define TRACE_(expr) PJ_LOG(4,expr) +# define TRACE_(expr) PJ_LOG(4,expr) #else # define TRACE_(expr) #endif @@ -75,20 +74,20 @@ static void err(const char *op, pj_status_t status) } #define CHECK(op) do { \ - status = op; \ - if (status != PJ_SUCCESS) { \ - err(#op, status); \ - return status; \ - } \ - } \ - while (0) + status = op; \ + if (status != PJ_SUCCESS) { \ + err(#op, status); \ + return status; \ + } \ + } \ + while (0) static pjmedia_endpt *mept; static unsigned file_msec_duration; static pj_status_t enc_dec_test(const char *codec_id, - const char *filein, - const char *fileout) + const char *filein, + const char *fileout) { pj_pool_t *pool; pjmedia_codec_mgr *cm; @@ -116,7 +115,7 @@ static pj_status_t enc_dec_test(const char *codec_id, cnt = 1; CHECK( pjmedia_codec_mgr_find_codecs_by_id(cm, pj_cstr(&tmp, codec_id), - &cnt, &pci, NULL) ); + &cnt, &pci, NULL) ); CHECK( pjmedia_codec_mgr_get_default_param(cm, pci, ¶m) ); samples_per_frame = param.info.clock_rate * param.info.frm_ptime / 1000; @@ -126,15 +125,15 @@ static pj_status_t enc_dec_test(const char *codec_id, /* Open wav for reading */ CHECK( pjmedia_wav_player_port_create(pool, filein, - param.info.frm_ptime, - PJMEDIA_FILE_NO_LOOP, 0, &wavin) ); + param.info.frm_ptime, + PJMEDIA_FILE_NO_LOOP, 0, &wavin) ); /* Open wav for writing */ CHECK( pjmedia_wav_writer_port_create(pool, fileout, - param.info.clock_rate, - param.info.channel_cnt, - samples_per_frame, - 16, 0, 0, &wavout) ); + param.info.clock_rate, + param.info.channel_cnt, + samples_per_frame, + 16, 0, 0, &wavout) ); /* Alloc codec */ CHECK( pjmedia_codec_mgr_alloc_codec(cm, pci, &codec) ); @@ -142,71 +141,71 @@ static pj_status_t enc_dec_test(const char *codec_id, CHECK( pjmedia_codec_open(codec, ¶m) ); for (;;) { - pjmedia_frame frm_pcm, frm_bit, out_frm, frames[4]; - pj_int16_t pcmbuf[2048]; - pj_timestamp ts; - pj_uint8_t bitstream[2048]; - - frm_pcm.buf = (char*)pcmbuf; - frm_pcm.size = samples_per_frame * 2; - - /* Read from WAV */ - if (pjmedia_port_get_frame(wavin, &frm_pcm) != PJ_SUCCESS) - break; - if (frm_pcm.type != PJMEDIA_FRAME_TYPE_AUDIO) - break;; - - /* Update duration */ - file_msec_duration += samples_per_frame * 1000 / - param.info.clock_rate; - - /* Encode */ - frm_bit.buf = bitstream; - frm_bit.size = sizeof(bitstream); - CHECK(pjmedia_codec_encode(codec, &frm_pcm, sizeof(bitstream), - &frm_bit)); - - /* On DTX, write zero frame to wavout to maintain duration */ - if (frm_bit.size == 0 || frm_bit.type != PJMEDIA_FRAME_TYPE_AUDIO) { - out_frm.buf = (char*)pcmbuf; - out_frm.size = 160; - CHECK( pjmedia_port_put_frame(wavout, &out_frm) ); - TRACE_((THIS_FILE, "%d.%03d read: %u, enc: %u", - T, frm_pcm.size, frm_bit.size)); - continue; - } - - bitstream_size += (unsigned)frm_bit.size; - - /* Parse the bitstream (not really necessary for this case - * since we always decode 1 frame, but it's still good - * for testing) - */ - ts.u64 = 0; - cnt = PJ_ARRAY_SIZE(frames); - CHECK( pjmedia_codec_parse(codec, bitstream, frm_bit.size, &ts, &cnt, - frames) ); - CHECK( (cnt==1 ? PJ_SUCCESS : -1) ); - - /* Decode or simulate packet loss */ - out_frm.buf = (char*)pcmbuf; - out_frm.size = sizeof(pcmbuf); - - if ((pj_rand() % 100) < (int)lost_pct) { - /* Simulate loss */ - CHECK( pjmedia_codec_recover(codec, sizeof(pcmbuf), &out_frm) ); - TRACE_((THIS_FILE, "%d.%03d Packet lost", T)); - } else { - /* Decode */ - CHECK( pjmedia_codec_decode(codec, &frames[0], sizeof(pcmbuf), - &out_frm) ); - } - - /* Write to WAV */ - CHECK( pjmedia_port_put_frame(wavout, &out_frm) ); - - TRACE_((THIS_FILE, "%d.%03d read: %u, enc: %u, dec/write: %u", - T, frm_pcm.size, frm_bit.size, out_frm.size)); + pjmedia_frame frm_pcm, frm_bit, out_frm, frames[4]; + pj_int16_t pcmbuf[2048]; + pj_timestamp ts; + pj_uint8_t bitstream[2048]; + + frm_pcm.buf = (char*)pcmbuf; + frm_pcm.size = samples_per_frame * 2; + + /* Read from WAV */ + if (pjmedia_port_get_frame(wavin, &frm_pcm) != PJ_SUCCESS) + break; + if (frm_pcm.type != PJMEDIA_FRAME_TYPE_AUDIO) + break;; + + /* Update duration */ + file_msec_duration += samples_per_frame * 1000 / + param.info.clock_rate; + + /* Encode */ + frm_bit.buf = bitstream; + frm_bit.size = sizeof(bitstream); + CHECK(pjmedia_codec_encode(codec, &frm_pcm, sizeof(bitstream), + &frm_bit)); + + /* On DTX, write zero frame to wavout to maintain duration */ + if (frm_bit.size == 0 || frm_bit.type != PJMEDIA_FRAME_TYPE_AUDIO) { + out_frm.buf = (char*)pcmbuf; + out_frm.size = 160; + CHECK( pjmedia_port_put_frame(wavout, &out_frm) ); + TRACE_((THIS_FILE, "%d.%03d read: %u, enc: %u", + T, frm_pcm.size, frm_bit.size)); + continue; + } + + bitstream_size += (unsigned)frm_bit.size; + + /* Parse the bitstream (not really necessary for this case + * since we always decode 1 frame, but it's still good + * for testing) + */ + ts.u64 = 0; + cnt = PJ_ARRAY_SIZE(frames); + CHECK( pjmedia_codec_parse(codec, bitstream, frm_bit.size, &ts, &cnt, + frames) ); + CHECK( (cnt==1 ? PJ_SUCCESS : -1) ); + + /* Decode or simulate packet loss */ + out_frm.buf = (char*)pcmbuf; + out_frm.size = sizeof(pcmbuf); + + if ((pj_rand() % 100) < (int)lost_pct) { + /* Simulate loss */ + CHECK( pjmedia_codec_recover(codec, sizeof(pcmbuf), &out_frm) ); + TRACE_((THIS_FILE, "%d.%03d Packet lost", T)); + } else { + /* Decode */ + CHECK( pjmedia_codec_decode(codec, &frames[0], sizeof(pcmbuf), + &out_frm) ); + } + + /* Write to WAV */ + CHECK( pjmedia_port_put_frame(wavout, &out_frm) ); + + TRACE_((THIS_FILE, "%d.%03d read: %u, enc: %u, dec/write: %u", + T, frm_pcm.size, frm_bit.size, out_frm.size)); } /* Close wavs */ @@ -233,8 +232,8 @@ int main(int argc, char *argv[]) pj_status_t status; if (argc != 4) { - puts(desc); - return 1; + puts(desc); + return 1; } CHECK( pj_init() ); @@ -256,11 +255,11 @@ int main(int argc, char *argv[]) pj_shutdown(); if (status == PJ_SUCCESS) { - puts(""); - puts("Success"); - printf("Duration: %ds.%03d\n", file_msec_duration/1000, - file_msec_duration%1000); - printf("Time: %lds.%03ld\n", t1.sec, t1.msec); + puts(""); + puts("Success"); + printf("Duration: %ds.%03d\n", file_msec_duration/1000, + file_msec_duration%1000); + printf("Time: %lds.%03ld\n", t1.sec, t1.msec); } return 0; diff --git a/pjsip-apps/src/samples/footprint.c b/pjsip-apps/src/samples/footprint.c index 16dbb536cc..6fa4425ddb 100644 --- a/pjsip-apps/src/samples/footprint.c +++ b/pjsip-apps/src/samples/footprint.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -277,9 +276,9 @@ int dummy_function() #ifdef HAS_PJSIP_CORE_MSG_UTIL pjsip_endpt_create_request(NULL, NULL, NULL, NULL, NULL, NULL, NULL, - -1, NULL, NULL); + -1, NULL, NULL); pjsip_endpt_create_request_from_hdr(NULL, NULL, NULL, NULL, NULL, NULL, - NULL, -1, NULL, NULL); + NULL, -1, NULL, NULL); pjsip_endpt_create_response(NULL, NULL, -1, NULL, NULL); pjsip_endpt_create_ack(NULL, NULL, NULL, NULL); pjsip_endpt_create_cancel(NULL, NULL, NULL); diff --git a/pjsip-apps/src/samples/httpdemo.c b/pjsip-apps/src/samples/httpdemo.c index ec49a0f939..6a81b20ed8 100644 --- a/pjsip-apps/src/samples/httpdemo.c +++ b/pjsip-apps/src/samples/httpdemo.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -41,7 +40,7 @@ static pj_pool_factory *mem; static FILE *f = NULL; //#define VERBOSE -#define THIS_FILE "http_demo" +#define THIS_FILE "http_demo" static void on_response(pj_http_req *req, const pj_http_resp *resp) { @@ -49,27 +48,27 @@ static void on_response(pj_http_req *req, const pj_http_resp *resp) PJ_UNUSED_ARG(req); PJ_LOG(3,(THIS_FILE, "%.*s %d %.*s", (int)resp->version.slen, resp->version.ptr, - resp->status_code, - (int)resp->reason.slen, resp->reason.ptr)); + resp->status_code, + (int)resp->reason.slen, resp->reason.ptr)); for (i=0; iheaders.count; ++i) { - const pj_http_header_elmt *h = &resp->headers.header[i]; - - if (!pj_stricmp2(&h->name, "Content-Length") || - !pj_stricmp2(&h->name, "Content-Type")) - { - PJ_LOG(3,(THIS_FILE, "%.*s: %.*s", - (int)h->name.slen, h->name.ptr, - (int)h->value.slen, h->value.ptr)); - } + const pj_http_header_elmt *h = &resp->headers.header[i]; + + if (!pj_stricmp2(&h->name, "Content-Length") || + !pj_stricmp2(&h->name, "Content-Type")) + { + PJ_LOG(3,(THIS_FILE, "%.*s: %.*s", + (int)h->name.slen, h->name.ptr, + (int)h->value.slen, h->value.ptr)); + } } } static void on_send_data(pj_http_req *req, void **data, pj_size_t *size) { - PJ_UNUSED_ARG(req); - PJ_UNUSED_ARG(size); - PJ_UNUSED_ARG(data); + PJ_UNUSED_ARG(req); + PJ_UNUSED_ARG(size); + PJ_UNUSED_ARG(data); } static void on_data_read(pj_http_req *hreq, void *data, pj_size_t size) @@ -133,8 +132,8 @@ pj_status_t getURL(const char *curl) while (pj_http_req_is_running(http_req)) { pj_time_val delay = {0, 50}; - pj_ioqueue_poll(ioqueue, &delay); - pj_timer_heap_poll(timer_heap, NULL); + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer_heap, NULL); } pj_http_req_destroy(http_req); @@ -153,8 +152,8 @@ int main(int argc, char *argv[]) pj_status_t status; if (argc < 2 || argc > 3) { - puts("Usage: httpdemo URL [output-filename]"); - return 1; + puts("Usage: httpdemo URL [output-filename]"); + return 1; } pj_log_set_level(5); @@ -165,9 +164,9 @@ int main(int argc, char *argv[]) pjlib_util_init(); if (argc > 2) - f = fopen(argv[2], "wb"); + f = fopen(argv[2], "wb"); else - f = stdout; + f = stdout; status = getURL(argv[1]); if (status != PJ_SUCCESS) { @@ -175,7 +174,7 @@ int main(int argc, char *argv[]) } if (f != stdout) - fclose(f); + fclose(f); pj_caching_pool_destroy(&cp); pj_shutdown(); diff --git a/pjsip-apps/src/samples/icedemo.c b/pjsip-apps/src/samples/icedemo.c index 07ccc31f0b..5d9143fe6f 100644 --- a/pjsip-apps/src/samples/icedemo.c +++ b/pjsip-apps/src/samples/icedemo.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -37,37 +36,37 @@ static struct app_t /* Command line options are stored here */ struct options { - unsigned comp_cnt; - pj_str_t ns; - int max_host; - pj_bool_t regular; - pj_str_t stun_srv; - pj_str_t turn_srv; - pj_bool_t turn_tcp; - pj_str_t turn_username; - pj_str_t turn_password; - pj_bool_t turn_fingerprint; - const char *log_file; + unsigned comp_cnt; + pj_str_t ns; + int max_host; + pj_bool_t regular; + pj_str_t stun_srv; + pj_str_t turn_srv; + pj_bool_t turn_tcp; + pj_str_t turn_username; + pj_str_t turn_password; + pj_bool_t turn_fingerprint; + const char *log_file; } opt; /* Our global variables */ - pj_caching_pool cp; - pj_pool_t *pool; - pj_thread_t *thread; - pj_bool_t thread_quit_flag; - pj_ice_strans_cfg ice_cfg; - pj_ice_strans *icest; - FILE *log_fhnd; + pj_caching_pool cp; + pj_pool_t *pool; + pj_thread_t *thread; + pj_bool_t thread_quit_flag; + pj_ice_strans_cfg ice_cfg; + pj_ice_strans *icest; + FILE *log_fhnd; /* Variables to store parsed remote ICE info */ struct rem_info { - char ufrag[80]; - char pwd[80]; - unsigned comp_cnt; - pj_sockaddr def_addr[PJ_ICE_MAX_COMP]; - unsigned cand_cnt; - pj_ice_sess_cand cand[PJ_ICE_ST_MAX_CAND]; + char ufrag[80]; + char pwd[80]; + unsigned comp_cnt; + pj_sockaddr def_addr[PJ_ICE_MAX_COMP]; + unsigned cand_cnt; + pj_ice_sess_cand cand[PJ_ICE_ST_MAX_CAND]; } rem; } icedemo; @@ -87,43 +86,43 @@ static void icedemo_perror(const char *title, pj_status_t status) static void err_exit(const char *title, pj_status_t status) { if (status != PJ_SUCCESS) { - icedemo_perror(title, status); + icedemo_perror(title, status); } PJ_LOG(3,(THIS_FILE, "Shutting down..")); if (icedemo.icest) - pj_ice_strans_destroy(icedemo.icest); + pj_ice_strans_destroy(icedemo.icest); pj_thread_sleep(500); icedemo.thread_quit_flag = PJ_TRUE; if (icedemo.thread) { - pj_thread_join(icedemo.thread); - pj_thread_destroy(icedemo.thread); + pj_thread_join(icedemo.thread); + pj_thread_destroy(icedemo.thread); } if (icedemo.ice_cfg.stun_cfg.ioqueue) - pj_ioqueue_destroy(icedemo.ice_cfg.stun_cfg.ioqueue); + pj_ioqueue_destroy(icedemo.ice_cfg.stun_cfg.ioqueue); if (icedemo.ice_cfg.stun_cfg.timer_heap) - pj_timer_heap_destroy(icedemo.ice_cfg.stun_cfg.timer_heap); + pj_timer_heap_destroy(icedemo.ice_cfg.stun_cfg.timer_heap); pj_caching_pool_destroy(&icedemo.cp); pj_shutdown(); if (icedemo.log_fhnd) { - fclose(icedemo.log_fhnd); - icedemo.log_fhnd = NULL; + fclose(icedemo.log_fhnd); + icedemo.log_fhnd = NULL; } exit(status != PJ_SUCCESS); } -#define CHECK(expr) status=expr; \ - if (status!=PJ_SUCCESS) { \ - err_exit(#expr, status); \ - } +#define CHECK(expr) status=expr; \ + if (status!=PJ_SUCCESS) { \ + err_exit(#expr, status); \ + } /* * This function checks for events from both timer and ioqueue (for @@ -143,7 +142,7 @@ static pj_status_t handle_events(unsigned max_msec, unsigned *p_count) timeout.sec = timeout.msec = 0; c = pj_timer_heap_poll( icedemo.ice_cfg.stun_cfg.timer_heap, &timeout ); if (c > 0) - count += c; + count += c; /* timer_heap_poll should never ever returns negative value, or otherwise * ioqueue_poll() will block forever! @@ -155,7 +154,7 @@ static pj_status_t handle_events(unsigned max_msec, unsigned *p_count) * minimum value. */ if (PJ_TIME_VAL_GT(timeout, max_timeout)) - timeout = max_timeout; + timeout = max_timeout; /* Poll ioqueue. * Repeat polling the ioqueue while we have immediate events, because @@ -169,24 +168,24 @@ static pj_status_t handle_events(unsigned max_msec, unsigned *p_count) * reported in timely manner. */ do { - c = pj_ioqueue_poll( icedemo.ice_cfg.stun_cfg.ioqueue, &timeout); - if (c < 0) { - pj_status_t err = pj_get_netos_error(); - pj_thread_sleep(PJ_TIME_VAL_MSEC(timeout)); - if (p_count) - *p_count = count; - return err; - } else if (c == 0) { - break; - } else { - net_event_count += c; - timeout.sec = timeout.msec = 0; - } + c = pj_ioqueue_poll( icedemo.ice_cfg.stun_cfg.ioqueue, &timeout); + if (c < 0) { + pj_status_t err = pj_get_netos_error(); + pj_thread_sleep(PJ_TIME_VAL_MSEC(timeout)); + if (p_count) + *p_count = count; + return err; + } else if (c == 0) { + break; + } else { + net_event_count += c; + timeout.sec = timeout.msec = 0; + } } while (c > 0 && net_event_count < MAX_NET_EVENTS); count += net_event_count; if (p_count) - *p_count = count; + *p_count = count; return PJ_SUCCESS; @@ -200,7 +199,7 @@ static int icedemo_worker_thread(void *unused) PJ_UNUSED_ARG(unused); while (!icedemo.thread_quit_flag) { - handle_events(500, NULL); + handle_events(500, NULL); } return 0; @@ -213,10 +212,10 @@ static int icedemo_worker_thread(void *unused) * as STUN connectivity checks or TURN signaling). */ static void cb_on_rx_data(pj_ice_strans *ice_st, - unsigned comp_id, - void *pkt, pj_size_t size, - const pj_sockaddr_t *src_addr, - unsigned src_addr_len) + unsigned comp_id, + void *pkt, pj_size_t size, + const pj_sockaddr_t *src_addr, + unsigned src_addr_len) { char ipstr[PJ_INET6_ADDRSTRLEN+10]; @@ -228,10 +227,10 @@ static void cb_on_rx_data(pj_ice_strans *ice_st, //((char*)pkt)[size] = '\0'; PJ_LOG(3,(THIS_FILE, "Component %d: received %d bytes data from %s: \"%.*s\"", - comp_id, size, - pj_sockaddr_print(src_addr, ipstr, sizeof(ipstr), 3), - (unsigned)size, - (char*)pkt)); + comp_id, size, + pj_sockaddr_print(src_addr, ipstr, sizeof(ipstr), 3), + (unsigned)size, + (char*)pkt)); } /* @@ -239,22 +238,22 @@ static void cb_on_rx_data(pj_ice_strans *ice_st, * receive notification about ICE state progression. */ static void cb_on_ice_complete(pj_ice_strans *ice_st, - pj_ice_strans_op op, - pj_status_t status) + pj_ice_strans_op op, + pj_status_t status) { const char *opname = - (op==PJ_ICE_STRANS_OP_INIT? "initialization" : - (op==PJ_ICE_STRANS_OP_NEGOTIATION ? "negotiation" : "unknown_op")); + (op==PJ_ICE_STRANS_OP_INIT? "initialization" : + (op==PJ_ICE_STRANS_OP_NEGOTIATION ? "negotiation" : "unknown_op")); if (status == PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, "ICE %s successful", opname)); + PJ_LOG(3,(THIS_FILE, "ICE %s successful", opname)); } else { - char errmsg[PJ_ERR_MSG_SIZE]; + char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(1,(THIS_FILE, "ICE %s failed: %s", opname, errmsg)); - pj_ice_strans_destroy(ice_st); - icedemo.icest = NULL; + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(1,(THIS_FILE, "ICE %s failed: %s", opname, errmsg)); + pj_ice_strans_destroy(ice_st); + icedemo.icest = NULL; } } @@ -263,8 +262,8 @@ static void log_func(int level, const char *data, int len) { pj_log_write(level, data, len); if (icedemo.log_fhnd) { - if (fwrite(data, len, 1, icedemo.log_fhnd) != 1) - return; + if (fwrite(data, len, 1, icedemo.log_fhnd) != 1) + return; } } @@ -278,8 +277,8 @@ static pj_status_t icedemo_init(void) pj_status_t status; if (icedemo.opt.log_file) { - icedemo.log_fhnd = fopen(icedemo.opt.log_file, "a"); - pj_log_set_log_func(&log_func); + icedemo.log_fhnd = fopen(icedemo.opt.log_file, "a"); + pj_log_set_log_func(&log_func); } /* Initialize the libraries before anything else */ @@ -297,102 +296,102 @@ static pj_status_t icedemo_init(void) /* Create application memory pool */ icedemo.pool = pj_pool_create(&icedemo.cp.factory, "icedemo", - 512, 512, NULL); + 512, 512, NULL); /* Create timer heap for timer stuff */ CHECK( pj_timer_heap_create(icedemo.pool, 100, - &icedemo.ice_cfg.stun_cfg.timer_heap) ); + &icedemo.ice_cfg.stun_cfg.timer_heap) ); /* and create ioqueue for network I/O stuff */ CHECK( pj_ioqueue_create(icedemo.pool, 16, - &icedemo.ice_cfg.stun_cfg.ioqueue) ); + &icedemo.ice_cfg.stun_cfg.ioqueue) ); /* something must poll the timer heap and ioqueue, * unless we're on Symbian where the timer heap and ioqueue run * on themselves. */ CHECK( pj_thread_create(icedemo.pool, "icedemo", &icedemo_worker_thread, - NULL, 0, 0, &icedemo.thread) ); + NULL, 0, 0, &icedemo.thread) ); icedemo.ice_cfg.af = pj_AF_INET(); /* Create DNS resolver if nameserver is set */ if (icedemo.opt.ns.slen) { - CHECK( pj_dns_resolver_create(&icedemo.cp.factory, - "resolver", - 0, - icedemo.ice_cfg.stun_cfg.timer_heap, - icedemo.ice_cfg.stun_cfg.ioqueue, - &icedemo.ice_cfg.resolver) ); - - CHECK( pj_dns_resolver_set_ns(icedemo.ice_cfg.resolver, 1, - &icedemo.opt.ns, NULL) ); + CHECK( pj_dns_resolver_create(&icedemo.cp.factory, + "resolver", + 0, + icedemo.ice_cfg.stun_cfg.timer_heap, + icedemo.ice_cfg.stun_cfg.ioqueue, + &icedemo.ice_cfg.resolver) ); + + CHECK( pj_dns_resolver_set_ns(icedemo.ice_cfg.resolver, 1, + &icedemo.opt.ns, NULL) ); } /* -= Start initializing ICE stream transport config =- */ /* Maximum number of host candidates */ if (icedemo.opt.max_host != -1) - icedemo.ice_cfg.stun.max_host_cands = icedemo.opt.max_host; + icedemo.ice_cfg.stun.max_host_cands = icedemo.opt.max_host; /* Nomination strategy */ if (icedemo.opt.regular) - icedemo.ice_cfg.opt.aggressive = PJ_FALSE; + icedemo.ice_cfg.opt.aggressive = PJ_FALSE; else - icedemo.ice_cfg.opt.aggressive = PJ_TRUE; + icedemo.ice_cfg.opt.aggressive = PJ_TRUE; /* Configure STUN/srflx candidate resolution */ if (icedemo.opt.stun_srv.slen) { - char *pos; - - /* Command line option may contain port number */ - if ((pos=pj_strchr(&icedemo.opt.stun_srv, ':')) != NULL) { - icedemo.ice_cfg.stun.server.ptr = icedemo.opt.stun_srv.ptr; - icedemo.ice_cfg.stun.server.slen = (pos - icedemo.opt.stun_srv.ptr); - - icedemo.ice_cfg.stun.port = (pj_uint16_t)atoi(pos+1); - } else { - icedemo.ice_cfg.stun.server = icedemo.opt.stun_srv; - icedemo.ice_cfg.stun.port = PJ_STUN_PORT; - } - - /* For this demo app, configure longer STUN keep-alive time - * so that it does't clutter the screen output. - */ - icedemo.ice_cfg.stun.cfg.ka_interval = KA_INTERVAL; + char *pos; + + /* Command line option may contain port number */ + if ((pos=pj_strchr(&icedemo.opt.stun_srv, ':')) != NULL) { + icedemo.ice_cfg.stun.server.ptr = icedemo.opt.stun_srv.ptr; + icedemo.ice_cfg.stun.server.slen = (pos - icedemo.opt.stun_srv.ptr); + + icedemo.ice_cfg.stun.port = (pj_uint16_t)atoi(pos+1); + } else { + icedemo.ice_cfg.stun.server = icedemo.opt.stun_srv; + icedemo.ice_cfg.stun.port = PJ_STUN_PORT; + } + + /* For this demo app, configure longer STUN keep-alive time + * so that it does't clutter the screen output. + */ + icedemo.ice_cfg.stun.cfg.ka_interval = KA_INTERVAL; } /* Configure TURN candidate */ if (icedemo.opt.turn_srv.slen) { - char *pos; - - /* Command line option may contain port number */ - if ((pos=pj_strchr(&icedemo.opt.turn_srv, ':')) != NULL) { - icedemo.ice_cfg.turn.server.ptr = icedemo.opt.turn_srv.ptr; - icedemo.ice_cfg.turn.server.slen = (pos - icedemo.opt.turn_srv.ptr); - - icedemo.ice_cfg.turn.port = (pj_uint16_t)atoi(pos+1); - } else { - icedemo.ice_cfg.turn.server = icedemo.opt.turn_srv; - icedemo.ice_cfg.turn.port = PJ_STUN_PORT; - } - - /* TURN credential */ - icedemo.ice_cfg.turn.auth_cred.type = PJ_STUN_AUTH_CRED_STATIC; - icedemo.ice_cfg.turn.auth_cred.data.static_cred.username = icedemo.opt.turn_username; - icedemo.ice_cfg.turn.auth_cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN; - icedemo.ice_cfg.turn.auth_cred.data.static_cred.data = icedemo.opt.turn_password; - - /* Connection type to TURN server */ - if (icedemo.opt.turn_tcp) - icedemo.ice_cfg.turn.conn_type = PJ_TURN_TP_TCP; - else - icedemo.ice_cfg.turn.conn_type = PJ_TURN_TP_UDP; - - /* For this demo app, configure longer keep-alive time - * so that it does't clutter the screen output. - */ - icedemo.ice_cfg.turn.alloc_param.ka_interval = KA_INTERVAL; + char *pos; + + /* Command line option may contain port number */ + if ((pos=pj_strchr(&icedemo.opt.turn_srv, ':')) != NULL) { + icedemo.ice_cfg.turn.server.ptr = icedemo.opt.turn_srv.ptr; + icedemo.ice_cfg.turn.server.slen = (pos - icedemo.opt.turn_srv.ptr); + + icedemo.ice_cfg.turn.port = (pj_uint16_t)atoi(pos+1); + } else { + icedemo.ice_cfg.turn.server = icedemo.opt.turn_srv; + icedemo.ice_cfg.turn.port = PJ_STUN_PORT; + } + + /* TURN credential */ + icedemo.ice_cfg.turn.auth_cred.type = PJ_STUN_AUTH_CRED_STATIC; + icedemo.ice_cfg.turn.auth_cred.data.static_cred.username = icedemo.opt.turn_username; + icedemo.ice_cfg.turn.auth_cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN; + icedemo.ice_cfg.turn.auth_cred.data.static_cred.data = icedemo.opt.turn_password; + + /* Connection type to TURN server */ + if (icedemo.opt.turn_tcp) + icedemo.ice_cfg.turn.conn_type = PJ_TURN_TP_TCP; + else + icedemo.ice_cfg.turn.conn_type = PJ_TURN_TP_UDP; + + /* For this demo app, configure longer keep-alive time + * so that it does't clutter the screen output. + */ + icedemo.ice_cfg.turn.alloc_param.ka_interval = KA_INTERVAL; } /* -= That's it for now, initialization is complete =- */ @@ -409,8 +408,8 @@ static void icedemo_create_instance(void) pj_status_t status; if (icedemo.icest != NULL) { - puts("ICE instance already created, destroy it first"); - return; + puts("ICE instance already created, destroy it first"); + return; } /* init the callback */ @@ -419,17 +418,17 @@ static void icedemo_create_instance(void) icecb.on_ice_complete = cb_on_ice_complete; /* create the instance */ - status = pj_ice_strans_create("icedemo", /* object name */ - &icedemo.ice_cfg, /* settings */ - icedemo.opt.comp_cnt, /* comp_cnt */ - NULL, /* user data */ - &icecb, /* callback */ - &icedemo.icest) /* instance ptr */ - ; + status = pj_ice_strans_create("icedemo", /* object name */ + &icedemo.ice_cfg, /* settings */ + icedemo.opt.comp_cnt, /* comp_cnt */ + NULL, /* user data */ + &icecb, /* callback */ + &icedemo.icest) /* instance ptr */ + ; if (status != PJ_SUCCESS) - icedemo_perror("error creating ice", status); + icedemo_perror("error creating ice", status); else - PJ_LOG(3,(THIS_FILE, "ICE instance successfully created")); + PJ_LOG(3,(THIS_FILE, "ICE instance successfully created")); } /* Utility to nullify parsed remote info */ @@ -445,8 +444,8 @@ static void reset_rem_info(void) static void icedemo_destroy_instance(void) { if (icedemo.icest == NULL) { - PJ_LOG(1,(THIS_FILE, "Error: No ICE instance, create it first")); - return; + PJ_LOG(1,(THIS_FILE, "Error: No ICE instance, create it first")); + return; } pj_ice_strans_destroy(icedemo.icest); @@ -464,25 +463,25 @@ static void icedemo_destroy_instance(void) static void icedemo_init_session(unsigned rolechar) { pj_ice_sess_role role = (pj_tolower((pj_uint8_t)rolechar)=='o' ? - PJ_ICE_SESS_ROLE_CONTROLLING : - PJ_ICE_SESS_ROLE_CONTROLLED); + PJ_ICE_SESS_ROLE_CONTROLLING : + PJ_ICE_SESS_ROLE_CONTROLLED); pj_status_t status; if (icedemo.icest == NULL) { - PJ_LOG(1,(THIS_FILE, "Error: No ICE instance, create it first")); - return; + PJ_LOG(1,(THIS_FILE, "Error: No ICE instance, create it first")); + return; } if (pj_ice_strans_has_sess(icedemo.icest)) { - PJ_LOG(1,(THIS_FILE, "Error: Session already created")); - return; + PJ_LOG(1,(THIS_FILE, "Error: Session already created")); + return; } status = pj_ice_strans_init_ice(icedemo.icest, role, NULL, NULL); if (status != PJ_SUCCESS) - icedemo_perror("error creating session", status); + icedemo_perror("error creating session", status); else - PJ_LOG(3,(THIS_FILE, "ICE session created")); + PJ_LOG(3,(THIS_FILE, "ICE session created")); reset_rem_info(); } @@ -496,54 +495,54 @@ static void icedemo_stop_session(void) pj_status_t status; if (icedemo.icest == NULL) { - PJ_LOG(1,(THIS_FILE, "Error: No ICE instance, create it first")); - return; + PJ_LOG(1,(THIS_FILE, "Error: No ICE instance, create it first")); + return; } if (!pj_ice_strans_has_sess(icedemo.icest)) { - PJ_LOG(1,(THIS_FILE, "Error: No ICE session, initialize first")); - return; + PJ_LOG(1,(THIS_FILE, "Error: No ICE session, initialize first")); + return; } status = pj_ice_strans_stop_ice(icedemo.icest); if (status != PJ_SUCCESS) - icedemo_perror("error stopping session", status); + icedemo_perror("error stopping session", status); else - PJ_LOG(3,(THIS_FILE, "ICE session stopped")); + PJ_LOG(3,(THIS_FILE, "ICE session stopped")); reset_rem_info(); } -#define PRINT(...) \ - printed = pj_ansi_snprintf(p, maxlen - (p-buffer), \ - __VA_ARGS__); \ - if (printed <= 0 || printed >= (int)(maxlen - (p-buffer))) \ - return -PJ_ETOOSMALL; \ - p += printed +#define PRINT(...) \ + printed = pj_ansi_snprintf(p, maxlen - (p-buffer), \ + __VA_ARGS__); \ + if (printed <= 0 || printed >= (int)(maxlen - (p-buffer))) \ + return -PJ_ETOOSMALL; \ + p += printed /* Utility to create a=candidate SDP attribute */ static int print_cand(char buffer[], unsigned maxlen, - const pj_ice_sess_cand *cand) + const pj_ice_sess_cand *cand) { char ipaddr[PJ_INET6_ADDRSTRLEN]; char *p = buffer; int printed; PRINT("a=candidate:%.*s %u UDP %u %s %u typ ", - (int)cand->foundation.slen, - cand->foundation.ptr, - (unsigned)cand->comp_id, - cand->prio, - pj_sockaddr_print(&cand->addr, ipaddr, - sizeof(ipaddr), 0), - (unsigned)pj_sockaddr_get_port(&cand->addr)); + (int)cand->foundation.slen, + cand->foundation.ptr, + (unsigned)cand->comp_id, + cand->prio, + pj_sockaddr_print(&cand->addr, ipaddr, + sizeof(ipaddr), 0), + (unsigned)pj_sockaddr_get_port(&cand->addr)); PRINT("%s\n", - pj_ice_get_cand_type_name(cand->type)); + pj_ice_get_cand_type_name(cand->type)); if (p == buffer+maxlen) - return -PJ_ETOOSMALL; + return -PJ_ETOOSMALL; *p = '\0'; @@ -566,66 +565,66 @@ static int encode_session(char buffer[], unsigned maxlen) /* Get ufrag and pwd from current session */ pj_ice_strans_get_ufrag_pwd(icedemo.icest, &local_ufrag, &local_pwd, - NULL, NULL); + NULL, NULL); /* Write the a=ice-ufrag and a=ice-pwd attributes */ PRINT("a=ice-ufrag:%.*s\na=ice-pwd:%.*s\n", - (int)local_ufrag.slen, - local_ufrag.ptr, - (int)local_pwd.slen, - local_pwd.ptr); + (int)local_ufrag.slen, + local_ufrag.ptr, + (int)local_pwd.slen, + local_pwd.ptr); /* Write each component */ for (comp=0; comp"); - if (stdout) fflush(stdout); - - if (fgets(linebuf, sizeof(linebuf), stdin)==NULL) - break; - - len = strlen(linebuf); - while (len && (linebuf[len-1] == '\r' || linebuf[len-1] == '\n')) - linebuf[--len] = '\0'; - - line = linebuf; - while (len && pj_isspace(*line)) - ++line, --len; - - if (len==0) - break; - - /* Ignore subsequent media descriptors */ - if (media_cnt > 1) - continue; - - switch (line[0]) { - case 'm': - { - int cnt; - char media[32], portstr[32]; - - ++media_cnt; - if (media_cnt > 1) { - puts("Media line ignored"); - break; - } - - cnt = sscanf(line+2, "%s %s RTP/", media, portstr); - if (cnt != 2) { - PJ_LOG(1,(THIS_FILE, "Error parsing media line")); - goto on_error; - } - - comp0_port = atoi(portstr); - - } - break; - case 'c': - { - int cnt; - char c[32], net[32], ip[80]; - - cnt = sscanf(line+2, "%s %s %s", c, net, ip); - if (cnt != 3) { - PJ_LOG(1,(THIS_FILE, "Error parsing connection line")); - goto on_error; - } - - strcpy(comp0_addr, ip); - } - break; - case 'a': - { - char *attr = strtok(line+2, ": \t\r\n"); - if (strcmp(attr, "ice-ufrag")==0) { - strcpy(icedemo.rem.ufrag, attr+strlen(attr)+1); - } else if (strcmp(attr, "ice-pwd")==0) { - strcpy(icedemo.rem.pwd, attr+strlen(attr)+1); - } else if (strcmp(attr, "rtcp")==0) { - char *val = attr+strlen(attr)+1; - int af, cnt; - int port; - char net[32], ip[64]; - pj_str_t tmp_addr; - pj_status_t status; - - cnt = sscanf(val, "%d IN %s %s", &port, net, ip); - if (cnt != 3) { - PJ_LOG(1,(THIS_FILE, "Error parsing rtcp attribute")); - goto on_error; - } - - if (strchr(ip, ':')) - af = pj_AF_INET6(); - else - af = pj_AF_INET(); - - pj_sockaddr_init(af, &icedemo.rem.def_addr[1], NULL, 0); - tmp_addr = pj_str(ip); - status = pj_sockaddr_set_str_addr(af, &icedemo.rem.def_addr[1], - &tmp_addr); - if (status != PJ_SUCCESS) { - PJ_LOG(1,(THIS_FILE, "Invalid IP address")); - goto on_error; - } - pj_sockaddr_set_port(&icedemo.rem.def_addr[1], (pj_uint16_t)port); - - } else if (strcmp(attr, "candidate")==0) { - char *sdpcand = attr+strlen(attr)+1; - int af, cnt; - char foundation[32], transport[12], ipaddr[80], type[32]; - pj_str_t tmpaddr; - int comp_id, prio, port; - pj_ice_sess_cand *cand; - pj_status_t status; - - cnt = sscanf(sdpcand, "%s %d %s %d %s %d typ %s", - foundation, - &comp_id, - transport, - &prio, - ipaddr, - &port, - type); - if (cnt != 7) { - PJ_LOG(1, (THIS_FILE, "error: Invalid ICE candidate line")); - goto on_error; - } - - cand = &icedemo.rem.cand[icedemo.rem.cand_cnt]; - pj_bzero(cand, sizeof(*cand)); - - if (strcmp(type, "host")==0) - cand->type = PJ_ICE_CAND_TYPE_HOST; - else if (strcmp(type, "srflx")==0) - cand->type = PJ_ICE_CAND_TYPE_SRFLX; - else if (strcmp(type, "relay")==0) - cand->type = PJ_ICE_CAND_TYPE_RELAYED; - else { - PJ_LOG(1, (THIS_FILE, "Error: invalid candidate type '%s'", - type)); - goto on_error; - } - - cand->comp_id = (pj_uint8_t)comp_id; - pj_strdup2(icedemo.pool, &cand->foundation, foundation); - cand->prio = prio; - - if (strchr(ipaddr, ':')) - af = pj_AF_INET6(); - else - af = pj_AF_INET(); - - tmpaddr = pj_str(ipaddr); - pj_sockaddr_init(af, &cand->addr, NULL, 0); - status = pj_sockaddr_set_str_addr(af, &cand->addr, &tmpaddr); - if (status != PJ_SUCCESS) { - PJ_LOG(1,(THIS_FILE, "Error: invalid IP address '%s'", - ipaddr)); - goto on_error; - } - - pj_sockaddr_set_port(&cand->addr, (pj_uint16_t)port); - - ++icedemo.rem.cand_cnt; - - if (cand->comp_id > icedemo.rem.comp_cnt) - icedemo.rem.comp_cnt = cand->comp_id; - } - } - break; - } + pj_size_t len; + char *line; + + printf(">"); + if (stdout) fflush(stdout); + + if (fgets(linebuf, sizeof(linebuf), stdin)==NULL) + break; + + len = strlen(linebuf); + while (len && (linebuf[len-1] == '\r' || linebuf[len-1] == '\n')) + linebuf[--len] = '\0'; + + line = linebuf; + while (len && pj_isspace(*line)) + ++line, --len; + + if (len==0) + break; + + /* Ignore subsequent media descriptors */ + if (media_cnt > 1) + continue; + + switch (line[0]) { + case 'm': + { + int cnt; + char media[32], portstr[32]; + + ++media_cnt; + if (media_cnt > 1) { + puts("Media line ignored"); + break; + } + + cnt = sscanf(line+2, "%s %s RTP/", media, portstr); + if (cnt != 2) { + PJ_LOG(1,(THIS_FILE, "Error parsing media line")); + goto on_error; + } + + comp0_port = atoi(portstr); + + } + break; + case 'c': + { + int cnt; + char c[32], net[32], ip[80]; + + cnt = sscanf(line+2, "%s %s %s", c, net, ip); + if (cnt != 3) { + PJ_LOG(1,(THIS_FILE, "Error parsing connection line")); + goto on_error; + } + + strcpy(comp0_addr, ip); + } + break; + case 'a': + { + char *attr = strtok(line+2, ": \t\r\n"); + if (strcmp(attr, "ice-ufrag")==0) { + strcpy(icedemo.rem.ufrag, attr+strlen(attr)+1); + } else if (strcmp(attr, "ice-pwd")==0) { + strcpy(icedemo.rem.pwd, attr+strlen(attr)+1); + } else if (strcmp(attr, "rtcp")==0) { + char *val = attr+strlen(attr)+1; + int af, cnt; + int port; + char net[32], ip[64]; + pj_str_t tmp_addr; + pj_status_t status; + + cnt = sscanf(val, "%d IN %s %s", &port, net, ip); + if (cnt != 3) { + PJ_LOG(1,(THIS_FILE, "Error parsing rtcp attribute")); + goto on_error; + } + + if (strchr(ip, ':')) + af = pj_AF_INET6(); + else + af = pj_AF_INET(); + + pj_sockaddr_init(af, &icedemo.rem.def_addr[1], NULL, 0); + tmp_addr = pj_str(ip); + status = pj_sockaddr_set_str_addr(af, &icedemo.rem.def_addr[1], + &tmp_addr); + if (status != PJ_SUCCESS) { + PJ_LOG(1,(THIS_FILE, "Invalid IP address")); + goto on_error; + } + pj_sockaddr_set_port(&icedemo.rem.def_addr[1], (pj_uint16_t)port); + + } else if (strcmp(attr, "candidate")==0) { + char *sdpcand = attr+strlen(attr)+1; + int af, cnt; + char foundation[32], transport[12], ipaddr[80], type[32]; + pj_str_t tmpaddr; + int comp_id, prio, port; + pj_ice_sess_cand *cand; + pj_status_t status; + + cnt = sscanf(sdpcand, "%s %d %s %d %s %d typ %s", + foundation, + &comp_id, + transport, + &prio, + ipaddr, + &port, + type); + if (cnt != 7) { + PJ_LOG(1, (THIS_FILE, "error: Invalid ICE candidate line")); + goto on_error; + } + + cand = &icedemo.rem.cand[icedemo.rem.cand_cnt]; + pj_bzero(cand, sizeof(*cand)); + + if (strcmp(type, "host")==0) + cand->type = PJ_ICE_CAND_TYPE_HOST; + else if (strcmp(type, "srflx")==0) + cand->type = PJ_ICE_CAND_TYPE_SRFLX; + else if (strcmp(type, "relay")==0) + cand->type = PJ_ICE_CAND_TYPE_RELAYED; + else { + PJ_LOG(1, (THIS_FILE, "Error: invalid candidate type '%s'", + type)); + goto on_error; + } + + cand->comp_id = (pj_uint8_t)comp_id; + pj_strdup2(icedemo.pool, &cand->foundation, foundation); + cand->prio = prio; + + if (strchr(ipaddr, ':')) + af = pj_AF_INET6(); + else + af = pj_AF_INET(); + + tmpaddr = pj_str(ipaddr); + pj_sockaddr_init(af, &cand->addr, NULL, 0); + status = pj_sockaddr_set_str_addr(af, &cand->addr, &tmpaddr); + if (status != PJ_SUCCESS) { + PJ_LOG(1,(THIS_FILE, "Error: invalid IP address '%s'", + ipaddr)); + goto on_error; + } + + pj_sockaddr_set_port(&cand->addr, (pj_uint16_t)port); + + ++icedemo.rem.cand_cnt; + + if (cand->comp_id > icedemo.rem.comp_cnt) + icedemo.rem.comp_cnt = cand->comp_id; + } + } + break; + } } if (icedemo.rem.cand_cnt==0 || - icedemo.rem.ufrag[0]==0 || - icedemo.rem.pwd[0]==0 || - icedemo.rem.comp_cnt == 0) + icedemo.rem.ufrag[0]==0 || + icedemo.rem.pwd[0]==0 || + icedemo.rem.comp_cnt == 0) { - PJ_LOG(1, (THIS_FILE, "Error: not enough info")); - goto on_error; + PJ_LOG(1, (THIS_FILE, "Error: not enough info")); + goto on_error; } if (comp0_port==0 || comp0_addr[0]=='\0') { - PJ_LOG(1, (THIS_FILE, "Error: default address for component 0 not found")); - goto on_error; + PJ_LOG(1, (THIS_FILE, "Error: default address for component 0 not found")); + goto on_error; } else { - int af; - pj_str_t tmp_addr; - pj_status_t status; - - if (strchr(comp0_addr, ':')) - af = pj_AF_INET6(); - else - af = pj_AF_INET(); - - pj_sockaddr_init(af, &icedemo.rem.def_addr[0], NULL, 0); - tmp_addr = pj_str(comp0_addr); - status = pj_sockaddr_set_str_addr(af, &icedemo.rem.def_addr[0], - &tmp_addr); - if (status != PJ_SUCCESS) { - PJ_LOG(1,(THIS_FILE, "Invalid IP address in c= line")); - goto on_error; - } - pj_sockaddr_set_port(&icedemo.rem.def_addr[0], (pj_uint16_t)comp0_port); + int af; + pj_str_t tmp_addr; + pj_status_t status; + + if (strchr(comp0_addr, ':')) + af = pj_AF_INET6(); + else + af = pj_AF_INET(); + + pj_sockaddr_init(af, &icedemo.rem.def_addr[0], NULL, 0); + tmp_addr = pj_str(comp0_addr); + status = pj_sockaddr_set_str_addr(af, &icedemo.rem.def_addr[0], + &tmp_addr); + if (status != PJ_SUCCESS) { + PJ_LOG(1,(THIS_FILE, "Invalid IP address in c= line")); + goto on_error; + } + pj_sockaddr_set_port(&icedemo.rem.def_addr[0], (pj_uint16_t)comp0_port); } PJ_LOG(3, (THIS_FILE, "Done, %d remote candidate(s) added", - icedemo.rem.cand_cnt)); + icedemo.rem.cand_cnt)); return; on_error: @@ -936,31 +935,31 @@ static void icedemo_start_nego(void) pj_status_t status; if (icedemo.icest == NULL) { - PJ_LOG(1,(THIS_FILE, "Error: No ICE instance, create it first")); - return; + PJ_LOG(1,(THIS_FILE, "Error: No ICE instance, create it first")); + return; } if (!pj_ice_strans_has_sess(icedemo.icest)) { - PJ_LOG(1,(THIS_FILE, "Error: No ICE session, initialize first")); - return; + PJ_LOG(1,(THIS_FILE, "Error: No ICE session, initialize first")); + return; } if (icedemo.rem.cand_cnt == 0) { - PJ_LOG(1,(THIS_FILE, "Error: No remote info, input remote info first")); - return; + PJ_LOG(1,(THIS_FILE, "Error: No remote info, input remote info first")); + return; } PJ_LOG(3,(THIS_FILE, "Starting ICE negotiation..")); status = pj_ice_strans_start_ice(icedemo.icest, - pj_cstr(&rufrag, icedemo.rem.ufrag), - pj_cstr(&rpwd, icedemo.rem.pwd), - icedemo.rem.cand_cnt, - icedemo.rem.cand); + pj_cstr(&rufrag, icedemo.rem.ufrag), + pj_cstr(&rpwd, icedemo.rem.pwd), + icedemo.rem.cand_cnt, + icedemo.rem.cand); if (status != PJ_SUCCESS) - icedemo_perror("Error starting ICE", status); + icedemo_perror("Error starting ICE", status); else - PJ_LOG(3,(THIS_FILE, "ICE negotiation started")); + PJ_LOG(3,(THIS_FILE, "ICE negotiation started")); } @@ -972,34 +971,34 @@ static void icedemo_send_data(unsigned comp_id, const char *data) pj_status_t status; if (icedemo.icest == NULL) { - PJ_LOG(1,(THIS_FILE, "Error: No ICE instance, create it first")); - return; + PJ_LOG(1,(THIS_FILE, "Error: No ICE instance, create it first")); + return; } if (!pj_ice_strans_has_sess(icedemo.icest)) { - PJ_LOG(1,(THIS_FILE, "Error: No ICE session, initialize first")); - return; + PJ_LOG(1,(THIS_FILE, "Error: No ICE session, initialize first")); + return; } /* if (!pj_ice_strans_sess_is_complete(icedemo.icest)) { - PJ_LOG(1,(THIS_FILE, "Error: ICE negotiation has not been started or is in progress")); - return; + PJ_LOG(1,(THIS_FILE, "Error: ICE negotiation has not been started or is in progress")); + return; } */ if (comp_id<1||comp_id>pj_ice_strans_get_running_comp_cnt(icedemo.icest)) { - PJ_LOG(1,(THIS_FILE, "Error: invalid component ID")); - return; + PJ_LOG(1,(THIS_FILE, "Error: invalid component ID")); + return; } status = pj_ice_strans_sendto2(icedemo.icest, comp_id, data, strlen(data), - &icedemo.rem.def_addr[comp_id-1], - pj_sockaddr_get_len(&icedemo.rem.def_addr[comp_id-1])); + &icedemo.rem.def_addr[comp_id-1], + pj_sockaddr_get_len(&icedemo.rem.def_addr[comp_id-1])); if (status != PJ_SUCCESS && status != PJ_EPENDING) - icedemo_perror("Error sending data", status); + icedemo_perror("Error sending data", status); else - PJ_LOG(3,(THIS_FILE, "Data sent/will be sent")); + PJ_LOG(3,(THIS_FILE, "Data sent/will be sent")); } @@ -1012,25 +1011,25 @@ static void icedemo_help_menu(void) puts("-= Help on using ICE and this icedemo program =-"); puts(""); puts("This application demonstrates how to use ICE in pjnath without having\n" - "to use the SIP protocol. To use this application, you will need to run\n" - "two instances of this application, to simulate two ICE agents.\n"); + "to use the SIP protocol. To use this application, you will need to run\n" + "two instances of this application, to simulate two ICE agents.\n"); puts("Basic ICE flow:\n" - " create instance [menu \"c\"]\n" - " repeat these steps as wanted:\n" - " - init session as offerer or answerer [menu \"i\"]\n" - " - display our SDP [menu \"s\"]\n" - " - \"send\" our SDP from the \"show\" output above to remote, by\n" - " copy-pasting the SDP to the other icedemo application\n" - " - parse remote SDP, by pasting SDP generated by the other icedemo\n" - " instance [menu \"r\"]\n" - " - begin ICE negotiation in our end [menu \"b\"], and \n" - " - immediately begin ICE negotiation in the other icedemo instance\n" - " - ICE negotiation will run, and result will be printed to screen\n" - " - send application data to remote [menu \"x\"]\n" - " - end/stop ICE session [menu \"e\"]\n" - " destroy instance [menu \"d\"]\n" - ""); + " create instance [menu \"c\"]\n" + " repeat these steps as wanted:\n" + " - init session as offerer or answerer [menu \"i\"]\n" + " - display our SDP [menu \"s\"]\n" + " - \"send\" our SDP from the \"show\" output above to remote, by\n" + " copy-pasting the SDP to the other icedemo application\n" + " - parse remote SDP, by pasting SDP generated by the other icedemo\n" + " instance [menu \"r\"]\n" + " - begin ICE negotiation in our end [menu \"b\"], and \n" + " - immediately begin ICE negotiation in the other icedemo instance\n" + " - ICE negotiation will run, and result will be printed to screen\n" + " - send application data to remote [menu \"x\"]\n" + " - end/stop ICE session [menu \"e\"]\n" + " destroy instance [menu \"d\"]\n" + ""); puts(""); puts("This concludes the help screen."); @@ -1070,85 +1069,85 @@ static void icedemo_console(void) pj_bool_t app_quit = PJ_FALSE; while (!app_quit) { - char input[80], *cmd; - const char *SEP = " \t\r\n"; - pj_size_t len; + char input[80], *cmd; + const char *SEP = " \t\r\n"; + pj_size_t len; - icedemo_print_menu(); + icedemo_print_menu(); - printf("Input: "); - if (stdout) fflush(stdout); + printf("Input: "); + if (stdout) fflush(stdout); - pj_bzero(input, sizeof(input)); - if (fgets(input, sizeof(input), stdin) == NULL) - break; + pj_bzero(input, sizeof(input)); + if (fgets(input, sizeof(input), stdin) == NULL) + break; - len = strlen(input); - while (len && (input[len-1]=='\r' || input[len-1]=='\n')) - input[--len] = '\0'; + len = strlen(input); + while (len && (input[len-1]=='\r' || input[len-1]=='\n')) + input[--len] = '\0'; - cmd = strtok(input, SEP); - if (!cmd) - continue; + cmd = strtok(input, SEP); + if (!cmd) + continue; - if (strcmp(cmd, "create")==0 || strcmp(cmd, "c")==0) { + if (strcmp(cmd, "create")==0 || strcmp(cmd, "c")==0) { - icedemo_create_instance(); + icedemo_create_instance(); - } else if (strcmp(cmd, "destroy")==0 || strcmp(cmd, "d")==0) { + } else if (strcmp(cmd, "destroy")==0 || strcmp(cmd, "d")==0) { - icedemo_destroy_instance(); + icedemo_destroy_instance(); - } else if (strcmp(cmd, "init")==0 || strcmp(cmd, "i")==0) { + } else if (strcmp(cmd, "init")==0 || strcmp(cmd, "i")==0) { - char *role = strtok(NULL, SEP); - if (role) - icedemo_init_session(*role); - else - puts("error: Role required"); + char *role = strtok(NULL, SEP); + if (role) + icedemo_init_session(*role); + else + puts("error: Role required"); - } else if (strcmp(cmd, "stop")==0 || strcmp(cmd, "e")==0) { + } else if (strcmp(cmd, "stop")==0 || strcmp(cmd, "e")==0) { - icedemo_stop_session(); + icedemo_stop_session(); - } else if (strcmp(cmd, "show")==0 || strcmp(cmd, "s")==0) { + } else if (strcmp(cmd, "show")==0 || strcmp(cmd, "s")==0) { - icedemo_show_ice(); + icedemo_show_ice(); - } else if (strcmp(cmd, "remote")==0 || strcmp(cmd, "r")==0) { + } else if (strcmp(cmd, "remote")==0 || strcmp(cmd, "r")==0) { - icedemo_input_remote(); + icedemo_input_remote(); - } else if (strcmp(cmd, "start")==0 || strcmp(cmd, "b")==0) { + } else if (strcmp(cmd, "start")==0 || strcmp(cmd, "b")==0) { - icedemo_start_nego(); + icedemo_start_nego(); - } else if (strcmp(cmd, "send")==0 || strcmp(cmd, "x")==0) { + } else if (strcmp(cmd, "send")==0 || strcmp(cmd, "x")==0) { - char *comp = strtok(NULL, SEP); + char *comp = strtok(NULL, SEP); - if (!comp) { - PJ_LOG(1,(THIS_FILE, "Error: component ID required")); - } else { - char *data = comp + strlen(comp) + 1; - if (!data) - data = ""; - icedemo_send_data(atoi(comp), data); - } + if (!comp) { + PJ_LOG(1,(THIS_FILE, "Error: component ID required")); + } else { + char *data = comp + strlen(comp) + 1; + if (!data) + data = ""; + icedemo_send_data(atoi(comp), data); + } - } else if (strcmp(cmd, "help")==0 || strcmp(cmd, "h")==0) { + } else if (strcmp(cmd, "help")==0 || strcmp(cmd, "h")==0) { - icedemo_help_menu(); + icedemo_help_menu(); - } else if (strcmp(cmd, "quit")==0 || strcmp(cmd, "q")==0) { + } else if (strcmp(cmd, "quit")==0 || strcmp(cmd, "q")==0) { - app_quit = PJ_TRUE; + app_quit = PJ_TRUE; - } else { + } else { - printf("Invalid command '%s'\n", cmd); + printf("Invalid command '%s'\n", cmd); - } + } } } @@ -1193,18 +1192,18 @@ static void icedemo_usage() int main(int argc, char *argv[]) { struct pj_getopt_option long_options[] = { - { "comp-cnt", 1, 0, 'c'}, - { "nameserver", 1, 0, 'n'}, - { "max-host", 1, 0, 'H'}, - { "help", 0, 0, 'h'}, - { "stun-srv", 1, 0, 's'}, - { "turn-srv", 1, 0, 't'}, - { "turn-tcp", 0, 0, 'T'}, - { "turn-username", 1, 0, 'u'}, - { "turn-password", 1, 0, 'p'}, - { "turn-fingerprint", 0, 0, 'F'}, - { "regular", 0, 0, 'R'}, - { "log-file", 1, 0, 'L'}, + { "comp-cnt", 1, 0, 'c'}, + { "nameserver", 1, 0, 'n'}, + { "max-host", 1, 0, 'H'}, + { "help", 0, 0, 'h'}, + { "stun-srv", 1, 0, 's'}, + { "turn-srv", 1, 0, 't'}, + { "turn-tcp", 0, 0, 'T'}, + { "turn-username", 1, 0, 'u'}, + { "turn-password", 1, 0, 'p'}, + { "turn-fingerprint", 0, 0, 'F'}, + { "regular", 0, 0, 'R'}, + { "log-file", 1, 0, 'L'}, }; int c, opt_id; pj_status_t status; @@ -1213,57 +1212,57 @@ int main(int argc, char *argv[]) icedemo.opt.max_host = -1; while((c=pj_getopt_long(argc,argv, "c:n:s:t:u:p:H:L:hTFR", long_options, &opt_id))!=-1) { - switch (c) { - case 'c': - icedemo.opt.comp_cnt = atoi(pj_optarg); - if (icedemo.opt.comp_cnt < 1 || icedemo.opt.comp_cnt >= PJ_ICE_MAX_COMP) { - puts("Invalid component count value"); - return 1; - } - break; - case 'n': - icedemo.opt.ns = pj_str(pj_optarg); - break; - case 'H': - icedemo.opt.max_host = atoi(pj_optarg); - break; - case 'h': - icedemo_usage(); - return 0; - case 's': - icedemo.opt.stun_srv = pj_str(pj_optarg); - break; - case 't': - icedemo.opt.turn_srv = pj_str(pj_optarg); - break; - case 'T': - icedemo.opt.turn_tcp = PJ_TRUE; - break; - case 'u': - icedemo.opt.turn_username = pj_str(pj_optarg); - break; - case 'p': - icedemo.opt.turn_password = pj_str(pj_optarg); - break; - case 'F': - icedemo.opt.turn_fingerprint = PJ_TRUE; - break; - case 'R': - icedemo.opt.regular = PJ_TRUE; - break; - case 'L': - icedemo.opt.log_file = pj_optarg; - break; - default: - printf("Argument \"%s\" is not valid. Use -h to see help", - argv[pj_optind]); - return 1; - } + switch (c) { + case 'c': + icedemo.opt.comp_cnt = atoi(pj_optarg); + if (icedemo.opt.comp_cnt < 1 || icedemo.opt.comp_cnt >= PJ_ICE_MAX_COMP) { + puts("Invalid component count value"); + return 1; + } + break; + case 'n': + icedemo.opt.ns = pj_str(pj_optarg); + break; + case 'H': + icedemo.opt.max_host = atoi(pj_optarg); + break; + case 'h': + icedemo_usage(); + return 0; + case 's': + icedemo.opt.stun_srv = pj_str(pj_optarg); + break; + case 't': + icedemo.opt.turn_srv = pj_str(pj_optarg); + break; + case 'T': + icedemo.opt.turn_tcp = PJ_TRUE; + break; + case 'u': + icedemo.opt.turn_username = pj_str(pj_optarg); + break; + case 'p': + icedemo.opt.turn_password = pj_str(pj_optarg); + break; + case 'F': + icedemo.opt.turn_fingerprint = PJ_TRUE; + break; + case 'R': + icedemo.opt.regular = PJ_TRUE; + break; + case 'L': + icedemo.opt.log_file = pj_optarg; + break; + default: + printf("Argument \"%s\" is not valid. Use -h to see help", + argv[pj_optind]); + return 1; + } } status = icedemo_init(); if (status != PJ_SUCCESS) - return 1; + return 1; icedemo_console(); diff --git a/pjsip-apps/src/samples/invtester.c b/pjsip-apps/src/samples/invtester.c index f1f5a2033e..6cac892cf4 100644 --- a/pjsip-apps/src/samples/invtester.c +++ b/pjsip-apps/src/samples/invtester.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,12 +29,12 @@ #include #include -#define THIS_FILE "invtester.c" +#define THIS_FILE "invtester.c" -#define PORT 50060 -#define PORT_STR ":50060" -#define SAME_BRANCH 0 -#define ACK_HAS_SDP 1 +#define PORT 50060 +#define PORT_STR ":50060" +#define SAME_BRANCH 0 +#define ACK_HAS_SDP 1 static pjsip_endpoint *sip_endpt; static pj_bool_t quit_flag; @@ -47,19 +46,19 @@ static void on_tsx_state(pjsip_transaction *tsx, pjsip_event *event); static pjsip_module mod_app = { - NULL, NULL, /* prev, next. */ - { "mod-app", 7 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - NULL, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - &on_tsx_state /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-app", 7 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + &on_tsx_state /* on_tsx_state() */ }; @@ -69,8 +68,8 @@ static int worker_thread(void *arg) PJ_UNUSED_ARG(arg); while (!quit_flag) { - pj_time_val timeout = {0, 500}; - pjsip_endpt_handle_events(sip_endpt, &timeout); + pj_time_val timeout = {0, 500}; + pjsip_endpt_handle_events(sip_endpt, &timeout); } return 0; @@ -78,25 +77,25 @@ static int worker_thread(void *arg) /* Send request */ static void send_request(const pjsip_method *method, - int cseq, - const pj_str_t *branch, - pj_bool_t with_offer) + int cseq, + const pj_str_t *branch, + pj_bool_t with_offer) { pjsip_tx_data *tdata; pj_str_t dummy_sdp_str = { - "v=0\r\n" - "o=- 3360842071 3360842071 IN IP4 192.168.0.68\r\n" - "s=pjmedia\r\n" - "c=IN IP4 192.168.0.68\r\n" - "t=0 0\r\n" - "m=audio 4000 RTP/AVP 0 101\r\n" - "a=rtcp:4001 IN IP4 192.168.0.68\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "a=sendrecv\r\n" - "a=rtpmap:101 telephone-event/8000\r\n" - "a=fmtp:101 0-15\r\n", - 0 + "v=0\r\n" + "o=- 3360842071 3360842071 IN IP4 192.168.0.68\r\n" + "s=pjmedia\r\n" + "c=IN IP4 192.168.0.68\r\n" + "t=0 0\r\n" + "m=audio 4000 RTP/AVP 0 101\r\n" + "a=rtcp:4001 IN IP4 192.168.0.68\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=sendrecv\r\n" + "a=rtpmap:101 telephone-event/8000\r\n" + "a=fmtp:101 0-15\r\n", + 0 }; pj_status_t status; @@ -104,23 +103,23 @@ static void send_request(const pjsip_method *method, pj_assert(status == PJ_SUCCESS); if (branch) { - pjsip_via_hdr *via; + pjsip_via_hdr *via; - via = (pjsip_via_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); - pj_strdup(tdata->pool, &via->branch_param, branch); + via = (pjsip_via_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); + pj_strdup(tdata->pool, &via->branch_param, branch); } if (with_offer) { - pjsip_msg_body *body; - pj_str_t mime_application = { "application", 11}; - pj_str_t mime_sdp = {"sdp", 3}; + pjsip_msg_body *body; + pj_str_t mime_application = { "application", 11}; + pj_str_t mime_sdp = {"sdp", 3}; - dummy_sdp_str.slen = pj_ansi_strlen(dummy_sdp_str.ptr); - body = pjsip_msg_body_create(tdata->pool, - &mime_application, &mime_sdp, - &dummy_sdp_str); - tdata->msg->body = body; + dummy_sdp_str.slen = pj_ansi_strlen(dummy_sdp_str.ptr); + body = pjsip_msg_body_create(tdata->pool, + &mime_application, &mime_sdp, + &dummy_sdp_str); + tdata->msg->body = body; } status = pjsip_dlg_send_request(dlg, tdata, -1, NULL); @@ -131,22 +130,22 @@ static void send_request(const pjsip_method *method, static void on_tsx_state(pjsip_transaction *tsx, pjsip_event *event) { if (tsx->role == PJSIP_ROLE_UAC) { - if (tsx->method.id == PJSIP_INVITE_METHOD && tsx->state == PJSIP_TSX_STATE_TERMINATED) { + if (tsx->method.id == PJSIP_INVITE_METHOD && tsx->state == PJSIP_TSX_STATE_TERMINATED) { #if SAME_BRANCH - send_request(&pjsip_ack_method, tsx->cseq, &tsx->branch, ACK_HAS_SDP); + send_request(&pjsip_ack_method, tsx->cseq, &tsx->branch, ACK_HAS_SDP); #else - send_request(&pjsip_ack_method, tsx->cseq, NULL, ACK_HAS_SDP); + send_request(&pjsip_ack_method, tsx->cseq, NULL, ACK_HAS_SDP); #endif - } + } } else { - if (event->type == PJSIP_EVENT_RX_MSG && tsx->state == PJSIP_TSX_STATE_TRYING) { - pjsip_tx_data *tdata; + if (event->type == PJSIP_EVENT_RX_MSG && tsx->state == PJSIP_TSX_STATE_TRYING) { + pjsip_tx_data *tdata; - pjsip_dlg_create_response(dlg, event->body.tsx_state.src.rdata, - 200, NULL, &tdata); - pjsip_dlg_send_response(dlg, tsx, tdata); - } + pjsip_dlg_create_response(dlg, event->body.tsx_state.src.rdata, + 200, NULL, &tdata); + pjsip_dlg_send_response(dlg, tsx, tdata); + } } } @@ -158,7 +157,7 @@ void make_call(char *uri, pj_bool_t with_offer) pj_status_t status; status = pjsip_dlg_create_uac(pjsip_ua_instance(), - &local, &local, &remote, &remote, &dlg); + &local, &local, &remote, &remote, &dlg); pj_assert(status == PJ_SUCCESS); pjsip_dlg_inc_lock(dlg); @@ -198,8 +197,8 @@ int main(int argc, char *argv[]) pj_status_t status; if (argc != 2) { - puts("Error: destination URL needed"); - return 0; + puts("Error: destination URL needed"); + return 0; } /* Must init PJLIB first: */ @@ -217,25 +216,25 @@ int main(int argc, char *argv[]) /* Create the endpoint: */ status = pjsip_endpt_create(&cp.factory, "sipstateless", - &sip_endpt); + &sip_endpt); PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* * Add UDP transport, with hard-coded port */ { - pj_sockaddr_in addr; - - addr.sin_family = pj_AF_INET(); - addr.sin_addr.s_addr = 0; - addr.sin_port = pj_htons(PORT); - - status = pjsip_udp_transport_start( sip_endpt, &addr, NULL, 1, NULL); - if (status != PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, - "Error starting UDP transport (port in use?)")); - return 1; - } + pj_sockaddr_in addr; + + addr.sin_family = pj_AF_INET(); + addr.sin_addr.s_addr = 0; + addr.sin_port = pj_htons(PORT); + + status = pjsip_udp_transport_start( sip_endpt, &addr, NULL, 1, NULL); + if (status != PJ_SUCCESS) { + PJ_LOG(3,(THIS_FILE, + "Error starting UDP transport (port in use?)")); + return 1; + } } status = pjsip_tsx_layer_init_module(sip_endpt); @@ -258,29 +257,29 @@ int main(int argc, char *argv[]) printf("Destination URL: %s\n", argv[1]); for (;;) { - char line[10]; - - fgets(line, sizeof(line), stdin); - - switch (line[0]) { - case 'm': - make_call(argv[1], PJ_FALSE); - break; - case 'M': - make_call(argv[1], PJ_TRUE); - break; - case 'r': - reinvite(PJ_FALSE); - break; - case 'R': - reinvite(PJ_TRUE); - break; - case 'h': - hangup(); - break; - case 'q': - goto on_quit; - } + char line[10]; + + fgets(line, sizeof(line), stdin); + + switch (line[0]) { + case 'm': + make_call(argv[1], PJ_FALSE); + break; + case 'M': + make_call(argv[1], PJ_TRUE); + break; + case 'r': + reinvite(PJ_FALSE); + break; + case 'R': + reinvite(PJ_TRUE); + break; + case 'h': + hangup(); + break; + case 'q': + goto on_quit; + } } on_quit: diff --git a/pjsip-apps/src/samples/jbsim.c b/pjsip-apps/src/samples/jbsim.c index bd91f45847..95413e528e 100644 --- a/pjsip-apps/src/samples/jbsim.c +++ b/pjsip-apps/src/samples/jbsim.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -36,21 +35,21 @@ #define THIS_FILE "jbsim.c" /* Timer resolution in ms (must be NONZERO!) */ -#define WALL_CLOCK_TICK 1 +#define WALL_CLOCK_TICK 1 /* Defaults settings */ -#define CODEC "PCMU" -#define LOG_FILE "jbsim.csv" -#define WAV_REF "../../tests/pjsua/wavs/input.8.wav" -#define WAV_OUT "jbsim.wav" -#define DURATION 60 -#define DTX PJ_TRUE -#define PLC PJ_TRUE -#define MIN_LOST_BURST 0 -#define MAX_LOST_BURST 20 -#define LOSS_CORR 0 -#define LOSS_EXTRA 2 -#define SILENT 1 +#define CODEC "PCMU" +#define LOG_FILE "jbsim.csv" +#define WAV_REF "../../tests/pjsua/wavs/input.8.wav" +#define WAV_OUT "jbsim.wav" +#define DURATION 60 +#define DTX PJ_TRUE +#define PLC PJ_TRUE +#define MIN_LOST_BURST 0 +#define MAX_LOST_BURST 20 +#define LOSS_CORR 0 +#define LOSS_EXTRA 2 +#define SILENT 1 /* Test setup: @@ -61,39 +60,39 @@ /* Stream settings */ struct stream_cfg { - const char *name; /* for logging purposes */ - pjmedia_dir dir; /* stream direction */ - pj_str_t codec; /* codec name */ - unsigned ptime; /* zero for default */ - pj_bool_t dtx; /* DTX enabled? */ - pj_bool_t plc; /* PLC enabled? */ + const char *name; /* for logging purposes */ + pjmedia_dir dir; /* stream direction */ + pj_str_t codec; /* codec name */ + unsigned ptime; /* zero for default */ + pj_bool_t dtx; /* DTX enabled? */ + pj_bool_t plc; /* PLC enabled? */ }; /* Stream instance. We will instantiate two streams, TX and RX */ struct stream { - pj_pool_t *pool; - pjmedia_stream *strm; - pjmedia_port *port; + pj_pool_t *pool; + pjmedia_stream *strm; + pjmedia_port *port; /* * Running states: */ union { - /* TX stream state */ - struct { - pj_time_val next_schedule; /* Time to send next packet */ - unsigned total_tx; /* # of TX packets so far */ - int total_lost; /* # of dropped pkts so far */ - unsigned cur_lost_burst; /* current # of lost bursts */ - unsigned drop_prob; /* drop probability value */ - - } tx; - - /* RX stream state */ - struct { - pj_time_val next_schedule; /* Time to fetch next pkt */ - } rx; + /* TX stream state */ + struct { + pj_time_val next_schedule; /* Time to send next packet */ + unsigned total_tx; /* # of TX packets so far */ + int total_lost; /* # of dropped pkts so far */ + unsigned cur_lost_burst; /* current # of lost bursts */ + unsigned drop_prob; /* drop probability value */ + + } tx; + + /* RX stream state */ + struct { + pj_time_val next_schedule; /* Time to fetch next pkt */ + } rx; } state; }; @@ -102,54 +101,54 @@ struct stream */ /* Events names */ -#define EVENT_LOG "" -#define EVENT_TX "TX/PUT" -#define EVENT_TX_DROP "*** LOSS ***" -#define EVENT_GET_PRE "GET (pre)" -#define EVENT_GET_POST "GET (post)" +#define EVENT_LOG "" +#define EVENT_TX "TX/PUT" +#define EVENT_TX_DROP "*** LOSS ***" +#define EVENT_GET_PRE "GET (pre)" +#define EVENT_GET_POST "GET (post)" /* Logging entry */ struct log_entry { - pj_time_val wall_clock; /* Wall clock time */ - const char *event; /* Event name */ - pjmedia_jb_state *jb_state; /* JB state, optional */ - pjmedia_rtcp_stat *stat; /* Stream stat, optional */ - const char *log; /* Log message, optional */ + pj_time_val wall_clock; /* Wall clock time */ + const char *event; /* Event name */ + pjmedia_jb_state *jb_state; /* JB state, optional */ + pjmedia_rtcp_stat *stat; /* Stream stat, optional */ + const char *log; /* Log message, optional */ }; /* Test settings, taken from command line */ struct test_cfg { /* General options */ - pj_bool_t silent; /* Write little to stdout */ - const char *log_file; /* The output log file */ + pj_bool_t silent; /* Write little to stdout */ + const char *log_file; /* The output log file */ /* Test settings */ - pj_str_t codec; /* Codec to be used */ - unsigned duration_msec; /* Test duration */ + pj_str_t codec; /* Codec to be used */ + unsigned duration_msec; /* Test duration */ /* Transmitter setting */ - const char *tx_wav_in; /* Input/reference WAV */ - unsigned tx_ptime; /* TX stream ptime */ - unsigned tx_min_jitter; /* Minimum jitter in ms */ - unsigned tx_max_jitter; /* Max jitter in ms */ - unsigned tx_dtx; /* DTX enabled? */ - unsigned tx_pct_avg_lost; /* Average loss in percent */ - unsigned tx_min_lost_burst; /* Min lost burst in #pkt */ - unsigned tx_max_lost_burst; /* Max lost burst in #pkt */ - unsigned tx_pct_loss_corr; /* Loss correlation in pct */ + const char *tx_wav_in; /* Input/reference WAV */ + unsigned tx_ptime; /* TX stream ptime */ + unsigned tx_min_jitter; /* Minimum jitter in ms */ + unsigned tx_max_jitter; /* Max jitter in ms */ + unsigned tx_dtx; /* DTX enabled? */ + unsigned tx_pct_avg_lost; /* Average loss in percent */ + unsigned tx_min_lost_burst; /* Min lost burst in #pkt */ + unsigned tx_max_lost_burst; /* Max lost burst in #pkt */ + unsigned tx_pct_loss_corr; /* Loss correlation in pct */ /* Receiver setting */ - const char *rx_wav_out; /* Output WAV file */ - unsigned rx_ptime; /* RX stream ptime */ - unsigned rx_snd_burst; /* RX sound burst */ - pj_bool_t rx_plc; /* RX PLC enabled? */ - int rx_jb_init; /* if > 0 will enable prefetch (ms) */ - int rx_jb_min_pre; /* JB minimum prefetch (ms) */ - int rx_jb_max_pre; /* JB maximum prefetch (ms) */ - int rx_jb_max; /* JB maximum size (ms) */ + const char *rx_wav_out; /* Output WAV file */ + unsigned rx_ptime; /* RX stream ptime */ + unsigned rx_snd_burst; /* RX sound burst */ + pj_bool_t rx_plc; /* RX PLC enabled? */ + int rx_jb_init; /* if > 0 will enable prefetch (ms) */ + int rx_jb_min_pre; /* JB minimum prefetch (ms) */ + int rx_jb_max_pre; /* JB maximum prefetch (ms) */ + int rx_jb_max; /* JB maximum size (ms) */ }; /* @@ -157,34 +156,34 @@ struct test_cfg */ struct global_app { - pj_caching_pool cp; - pj_pool_t *pool; - pj_int16_t *framebuf; - pjmedia_endpt *endpt; - pjmedia_transport *loop; + pj_caching_pool cp; + pj_pool_t *pool; + pj_int16_t *framebuf; + pjmedia_endpt *endpt; + pjmedia_transport *loop; - pj_oshandle_t log_fd; + pj_oshandle_t log_fd; - struct test_cfg cfg; + struct test_cfg cfg; - struct stream *tx; - pjmedia_port *tx_wav; + struct stream *tx; + pjmedia_port *tx_wav; - struct stream *rx; - pjmedia_port *rx_wav; + struct stream *rx; + pjmedia_port *rx_wav; - pj_time_val wall_clock; + pj_time_val wall_clock; }; static struct global_app g_app; #ifndef MAX -# define MAX(a,b) (ajb_state) { - sprintf(s_jbprefetch, "%d", entry->jb_state->prefetch); - sprintf(s_jbsize, "%d", entry->jb_state->size); - sprintf(s_jbdiscard, "%d", entry->jb_state->discard); - sprintf(s_jbempty, "%d", entry->jb_state->empty); + sprintf(s_jbprefetch, "%d", entry->jb_state->prefetch); + sprintf(s_jbsize, "%d", entry->jb_state->size); + sprintf(s_jbdiscard, "%d", entry->jb_state->discard); + sprintf(s_jbempty, "%d", entry->jb_state->empty); } else { - strcpy(s_jbprefetch, ""); - strcpy(s_jbsize, ""); - strcpy(s_jbdiscard, ""); - strcpy(s_jbempty, ""); + strcpy(s_jbprefetch, ""); + strcpy(s_jbsize, ""); + strcpy(s_jbdiscard, ""); + strcpy(s_jbempty, ""); } if (entry->stat) { - sprintf(s_rxpkt, "%d", entry->stat->rx.pkt); - sprintf(s_losspkt, "%d", entry->stat->rx.loss); + sprintf(s_rxpkt, "%d", entry->stat->rx.pkt); + sprintf(s_losspkt, "%d", entry->stat->rx.loss); } else { - strcpy(s_rxpkt, ""); - strcpy(s_losspkt, ""); + strcpy(s_rxpkt, ""); + strcpy(s_losspkt, ""); } if (entry->log == NULL) - entry->log = ""; + entry->log = ""; pj_ansi_snprintf(log, sizeof(log), - "'%d.%03d;" /* time */ - "%s;" /* event */ - "%s;" /* rxpkt */ - "%s;" /* jb prefetch */ - "%s;" /* jbsize */ - "%s;" /* losspkt */ - "%s;" /* jbdiscard */ - "%s;" /* jbempty */ - "%s\n" /* logmsg */, - - (int)entry->wall_clock.sec, (int)entry->wall_clock.msec, /* time */ - entry->event, - s_rxpkt, - s_losspkt, - s_jbprefetch, - s_jbsize, - s_jbdiscard, - s_jbempty, - entry->log - ); + "'%d.%03d;" /* time */ + "%s;" /* event */ + "%s;" /* rxpkt */ + "%s;" /* jb prefetch */ + "%s;" /* jbsize */ + "%s;" /* losspkt */ + "%s;" /* jbdiscard */ + "%s;" /* jbempty */ + "%s\n" /* logmsg */, + + (int)entry->wall_clock.sec, (int)entry->wall_clock.msec, /* time */ + entry->event, + s_rxpkt, + s_losspkt, + s_jbprefetch, + s_jbsize, + s_jbdiscard, + s_jbempty, + entry->log + ); if (g_app.log_fd != NULL) { - pj_ssize_t size = strlen(log); - pj_file_write(g_app.log_fd, log, &size); + pj_ssize_t size = strlen(log); + pj_file_write(g_app.log_fd, log, &size); } if (to_stdout && !g_app.cfg.silent) - printf("%s", log); + printf("%s", log); } static void log_cb(int level, const char *data, int len) @@ -300,9 +299,9 @@ static void jbsim_perror(const char *title, pj_status_t status) static void stream_destroy(struct stream *stream) { if (stream->strm) - pjmedia_stream_destroy(stream->strm); + pjmedia_stream_destroy(stream->strm); if (stream->pool) - pj_pool_release(stream->pool); + pj_pool_release(stream->pool); } static pj_status_t stream_init(const struct stream_cfg *cfg, struct stream **p_stream) @@ -325,15 +324,15 @@ static pj_status_t stream_init(const struct stream_cfg *cfg, struct stream **p_s si.type = PJMEDIA_TYPE_AUDIO; si.proto = PJMEDIA_TP_PROTO_RTP_AVP; si.dir = cfg->dir; - pj_sockaddr_in_init(&si.rem_addr.ipv4, NULL, 4000); /* dummy */ - pj_sockaddr_in_init(&si.rem_rtcp.ipv4, NULL, 4001); /* dummy */ + pj_sockaddr_in_init(&si.rem_addr.ipv4, NULL, 4000); /* dummy */ + pj_sockaddr_in_init(&si.rem_rtcp.ipv4, NULL, 4001); /* dummy */ /* Apply JB settings if this is RX direction */ if (cfg->dir == PJMEDIA_DIR_DECODING) { - si.jb_init = g_app.cfg.rx_jb_init; - si.jb_min_pre = g_app.cfg.rx_jb_min_pre; - si.jb_max_pre = g_app.cfg.rx_jb_max_pre; - si.jb_max = g_app.cfg.rx_jb_max; + si.jb_init = g_app.cfg.rx_jb_init; + si.jb_min_pre = g_app.cfg.rx_jb_min_pre; + si.jb_max_pre = g_app.cfg.rx_jb_max_pre; + si.jb_max = g_app.cfg.rx_jb_max; si.jb_discard_algo = PJMEDIA_JB_DISCARD_PROGRESSIVE; } @@ -342,8 +341,8 @@ static pj_status_t stream_init(const struct stream_cfg *cfg, struct stream **p_s count = 1; status = pjmedia_codec_mgr_find_codecs_by_id(cm, &cfg->codec, &count, &ci, NULL); if (status != PJ_SUCCESS) { - jbsim_perror("Unable to find codec", status); - goto on_error; + jbsim_perror("Unable to find codec", status); + goto on_error; } pj_memcpy(&si.fmt, ci, sizeof(*ci)); @@ -351,17 +350,17 @@ static pj_status_t stream_init(const struct stream_cfg *cfg, struct stream **p_s si.param = PJ_POOL_ALLOC_T(pool, struct pjmedia_codec_param); status = pjmedia_codec_mgr_get_default_param(cm, &si.fmt, si.param); if (status != PJ_SUCCESS) { - jbsim_perror("Unable to get codec defaults", status); - goto on_error; + jbsim_perror("Unable to get codec defaults", status); + goto on_error; } si.tx_pt = si.fmt.pt; /* Apply ptime setting */ if (cfg->ptime) { - si.param->setting.frm_per_pkt = (pj_uint8_t) - ((cfg->ptime + si.param->info.frm_ptime - 1) / - si.param->info.frm_ptime); + si.param->setting.frm_per_pkt = (pj_uint8_t) + ((cfg->ptime + si.param->info.frm_ptime - 1) / + si.param->info.frm_ptime); } /* Apply DTX setting */ si.param->setting.vad = cfg->dtx; @@ -372,21 +371,21 @@ static pj_status_t stream_init(const struct stream_cfg *cfg, struct stream **p_s /* Create stream */ status = pjmedia_stream_create(g_app.endpt, pool, &si, g_app.loop, NULL, &stream->strm); if (status != PJ_SUCCESS) { - jbsim_perror("Error creating stream", status); - goto on_error; + jbsim_perror("Error creating stream", status); + goto on_error; } status = pjmedia_stream_get_port(stream->strm, &stream->port); if (status != PJ_SUCCESS) { - jbsim_perror("Error retrieving stream", status); - goto on_error; + jbsim_perror("Error retrieving stream", status); + goto on_error; } /* Start stream */ status = pjmedia_stream_start(stream->strm); if (status != PJ_SUCCESS) { - jbsim_perror("Error starting stream", status); - goto on_error; + jbsim_perror("Error starting stream", status); + goto on_error; } /* Done */ @@ -395,10 +394,10 @@ static pj_status_t stream_init(const struct stream_cfg *cfg, struct stream **p_s on_error: if (stream) { - stream_destroy(stream); + stream_destroy(stream); } else { - if (pool) - pj_pool_release(pool); + if (pool) + pj_pool_release(pool); } return status; } @@ -410,25 +409,25 @@ static pj_status_t stream_init(const struct stream_cfg *cfg, struct stream **p_s static void test_destroy(void) { if (g_app.tx) - stream_destroy(g_app.tx); + stream_destroy(g_app.tx); if (g_app.tx_wav) - pjmedia_port_destroy(g_app.tx_wav); + pjmedia_port_destroy(g_app.tx_wav); if (g_app.rx) - stream_destroy(g_app.rx); + stream_destroy(g_app.rx); if (g_app.rx_wav) - pjmedia_port_destroy(g_app.rx_wav); + pjmedia_port_destroy(g_app.rx_wav); if (g_app.loop) - pjmedia_transport_close(g_app.loop); + pjmedia_transport_close(g_app.loop); if (g_app.endpt) - pjmedia_endpt_destroy( g_app.endpt ); + pjmedia_endpt_destroy( g_app.endpt ); if (g_app.log_fd) { - pj_log_set_log_func(&pj_log_write); - pj_log_set_decor(pj_log_get_decor() | PJ_LOG_HAS_NEWLINE); - pj_file_close(g_app.log_fd); - g_app.log_fd = NULL; + pj_log_set_log_func(&pj_log_write); + pj_log_set_decor(pj_log_get_decor() | PJ_LOG_HAS_NEWLINE); + pj_file_close(g_app.log_fd); + g_app.log_fd = NULL; } if (g_app.pool) - pj_pool_release(g_app.pool); + pj_pool_release(g_app.pool); pjmedia_event_mgr_destroy(NULL); pj_caching_pool_destroy( &g_app.cp ); pj_shutdown(); @@ -452,16 +451,16 @@ static pj_status_t test_init(void) /* Log file */ if (g_app.cfg.log_file) { - status = pj_file_open(g_app.pool, g_app.cfg.log_file, - PJ_O_WRONLY, - &g_app.log_fd); - if (status != PJ_SUCCESS) { - jbsim_perror("Error writing output file", status); - goto on_error; - } - - pj_log_set_decor(PJ_LOG_HAS_SENDER | PJ_LOG_HAS_COLOR | PJ_LOG_HAS_LEVEL_TEXT); - pj_log_set_log_func(&log_cb); + status = pj_file_open(g_app.pool, g_app.cfg.log_file, + PJ_O_WRONLY, + &g_app.log_fd); + if (status != PJ_SUCCESS) { + jbsim_perror("Error writing output file", status); + goto on_error; + } + + pj_log_set_decor(PJ_LOG_HAS_SENDER | PJ_LOG_HAS_COLOR | PJ_LOG_HAS_LEVEL_TEXT); + pj_log_set_log_func(&log_cb); } /* @@ -470,8 +469,8 @@ static pj_status_t test_init(void) */ status = pjmedia_endpt_create(&g_app.cp.factory, NULL, 0, &g_app.endpt); if (status != PJ_SUCCESS) { - jbsim_perror("Error creating media endpoint", status); - goto on_error; + jbsim_perror("Error creating media endpoint", status); + goto on_error; } /* Register codecs */ @@ -480,15 +479,15 @@ static pj_status_t test_init(void) /* Create the loop transport */ status = pjmedia_transport_loop_create(g_app.endpt, &g_app.loop); if (status != PJ_SUCCESS) { - jbsim_perror("Error creating loop transport", status); - goto on_error; + jbsim_perror("Error creating loop transport", status); + goto on_error; } /* Create event manager */ status = pjmedia_event_mgr_create(g_app.pool, 0, NULL); if (status != PJ_SUCCESS) { - jbsim_perror("Error creating event manager", status); - goto on_error; + jbsim_perror("Error creating event manager", status); + goto on_error; } /* Create transmitter stream */ @@ -501,27 +500,27 @@ static pj_status_t test_init(void) strm_cfg.plc = PJ_TRUE; status = stream_init(&strm_cfg, &g_app.tx); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create transmitter WAV */ status = pjmedia_wav_player_port_create(g_app.pool, - g_app.cfg.tx_wav_in, - g_app.cfg.tx_ptime, - 0, - 0, - &g_app.tx_wav); + g_app.cfg.tx_wav_in, + g_app.cfg.tx_ptime, + 0, + 0, + &g_app.tx_wav); if (status != PJ_SUCCESS) { - jbsim_perror("Error reading input WAV file", status); - goto on_error; + jbsim_perror("Error reading input WAV file", status); + goto on_error; } /* Make sure stream and WAV parameters match */ if (PJMEDIA_PIA_SRATE(&g_app.tx_wav->info) != PJMEDIA_PIA_SRATE(&g_app.tx->port->info) || - PJMEDIA_PIA_CCNT(&g_app.tx_wav->info) != PJMEDIA_PIA_CCNT(&g_app.tx->port->info)) + PJMEDIA_PIA_CCNT(&g_app.tx_wav->info) != PJMEDIA_PIA_CCNT(&g_app.tx->port->info)) { - jbsim_perror("Error: Input WAV file has different clock rate " - "or number of channels than the codec", PJ_SUCCESS); - goto on_error; + jbsim_perror("Error: Input WAV file has different clock rate " + "or number of channels than the codec", PJ_SUCCESS); + goto on_error; } @@ -535,29 +534,29 @@ static pj_status_t test_init(void) strm_cfg.plc = g_app.cfg.rx_plc; status = stream_init(&strm_cfg, &g_app.rx); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create receiver WAV */ status = pjmedia_wav_writer_port_create(g_app.pool, - g_app.cfg.rx_wav_out, - PJMEDIA_PIA_SRATE(&g_app.rx->port->info), - PJMEDIA_PIA_CCNT(&g_app.rx->port->info), - PJMEDIA_PIA_SPF(&g_app.rx->port->info), - PJMEDIA_PIA_BITS(&g_app.rx->port->info), - 0, - 0, - &g_app.rx_wav); + g_app.cfg.rx_wav_out, + PJMEDIA_PIA_SRATE(&g_app.rx->port->info), + PJMEDIA_PIA_CCNT(&g_app.rx->port->info), + PJMEDIA_PIA_SPF(&g_app.rx->port->info), + PJMEDIA_PIA_BITS(&g_app.rx->port->info), + 0, + 0, + &g_app.rx_wav); if (status != PJ_SUCCESS) { - jbsim_perror("Error creating output WAV file", status); - goto on_error; + jbsim_perror("Error creating output WAV file", status); + goto on_error; } /* Frame buffer */ g_app.framebuf = (pj_int16_t*) - pj_pool_alloc(g_app.pool, - MAX(PJMEDIA_PIA_SPF(&g_app.rx->port->info), - PJMEDIA_PIA_SPF(&g_app.tx->port->info)) * sizeof(pj_int16_t)); + pj_pool_alloc(g_app.pool, + MAX(PJMEDIA_PIA_SPF(&g_app.rx->port->info), + PJMEDIA_PIA_SPF(&g_app.tx->port->info)) * sizeof(pj_int16_t)); /* Set the receiver in the loop transport */ @@ -572,7 +571,7 @@ static pj_status_t test_init(void) } static void run_one_frame(pjmedia_port *src, pjmedia_port *dst, - pj_bool_t *has_frame) + pj_bool_t *has_frame) { pjmedia_frame frame; pj_status_t status; @@ -586,14 +585,14 @@ static void run_one_frame(pjmedia_port *src, pjmedia_port *dst, pj_assert(status == PJ_SUCCESS); if (status!= PJ_SUCCESS || frame.type != PJMEDIA_FRAME_TYPE_AUDIO) { - frame.buf = g_app.framebuf; - pjmedia_zero_samples(g_app.framebuf, PJMEDIA_PIA_SPF(&src->info)); - frame.size = PJMEDIA_PIA_SPF(&src->info) * 2; - if (has_frame) - *has_frame = PJ_FALSE; + frame.buf = g_app.framebuf; + pjmedia_zero_samples(g_app.framebuf, PJMEDIA_PIA_SPF(&src->info)); + frame.size = PJMEDIA_PIA_SPF(&src->info) * 2; + if (has_frame) + *has_frame = PJ_FALSE; } else { - if (has_frame) - *has_frame = PJ_TRUE; + if (has_frame) + *has_frame = PJ_TRUE; } @@ -615,139 +614,139 @@ static void tx_tick(const pj_time_val *t) /* packet interval, without jitter */ pkt_interval = PJMEDIA_PIA_SPF(&port->info) * 1000 / - PJMEDIA_PIA_SRATE(&port->info); + PJMEDIA_PIA_SRATE(&port->info); while (PJ_TIME_VAL_GTE(*t, strm->state.tx.next_schedule)) { - struct log_entry entry; - pj_bool_t drop_this_pkt = PJ_FALSE; - int jitter; - - /* Init log entry */ - pj_bzero(&entry, sizeof(entry)); - entry.wall_clock = *t; - - /* - * Determine whether to drop this packet - */ - if (strm->state.tx.cur_lost_burst) { - /* We are currently dropping packet */ - - /* Make it comply to minimum lost burst */ - if (strm->state.tx.cur_lost_burst < g_app.cfg.tx_min_lost_burst) { - drop_this_pkt = PJ_TRUE; - } - - /* Correlate the next packet loss */ - if (!drop_this_pkt && - strm->state.tx.cur_lost_burst < g_app.cfg.tx_max_lost_burst && - MAX(strm->state.tx.total_lost-LOSS_EXTRA,0) * 100 / MAX(strm->state.tx.total_tx,1) < g_app.cfg.tx_pct_avg_lost - ) - { - strm->state.tx.drop_prob = ((g_app.cfg.tx_pct_loss_corr * strm->state.tx.drop_prob) + - ((100-g_app.cfg.tx_pct_loss_corr) * (pj_rand()%100)) - ) / 100; - if (strm->state.tx.drop_prob >= 100) - strm->state.tx.drop_prob = 99; - - if (strm->state.tx.drop_prob >= 100 - g_app.cfg.tx_pct_avg_lost) - drop_this_pkt = PJ_TRUE; - } - } - - /* If we're not dropping packet then use randomly distributed loss */ - if (!drop_this_pkt && - MAX(strm->state.tx.total_lost-LOSS_EXTRA,0) * 100 / MAX(strm->state.tx.total_tx,1) < g_app.cfg.tx_pct_avg_lost) - { - strm->state.tx.drop_prob = pj_rand() % 100; - - if (strm->state.tx.drop_prob >= 100 - g_app.cfg.tx_pct_avg_lost) - drop_this_pkt = PJ_TRUE; - } - - if (drop_this_pkt) { - /* Drop the frame */ - pjmedia_transport_simulate_lost(g_app.loop, PJMEDIA_DIR_ENCODING, 100); - run_one_frame(g_app.tx_wav, g_app.tx->port, NULL); - pjmedia_transport_simulate_lost(g_app.loop, PJMEDIA_DIR_ENCODING, 0); - - entry.event = EVENT_TX_DROP; - entry.log = "** This packet was lost **"; - - ++strm->state.tx.total_lost; - ++strm->state.tx.cur_lost_burst; - - } else { - pjmedia_rtcp_stat stat; - pjmedia_jb_state jstate; - unsigned last_discard; - - pjmedia_stream_get_stat_jbuf(g_app.rx->strm, &jstate); - last_discard = jstate.discard; - - run_one_frame(g_app.tx_wav, g_app.tx->port, NULL); - - pjmedia_stream_get_stat(g_app.rx->strm, &stat); - pjmedia_stream_get_stat_jbuf(g_app.rx->strm, &jstate); - - entry.event = EVENT_TX; - entry.jb_state = &jstate; - entry.stat = &stat; - entry.log = log_msg; - - if (jstate.discard > last_discard) - strcat(log_msg, "** Note: packet was discarded by jitter buffer **"); - - strm->state.tx.cur_lost_burst = 0; - } - - write_log(&entry, PJ_TRUE); - - ++strm->state.tx.total_tx; - - /* Calculate next schedule */ - strm->state.tx.next_schedule.sec = 0; - strm->state.tx.next_schedule.msec = (strm->state.tx.total_tx + 1) * pkt_interval; - - /* Apply jitter */ - if (g_app.cfg.tx_max_jitter || g_app.cfg.tx_min_jitter) { - - if (g_app.cfg.tx_max_jitter == g_app.cfg.tx_min_jitter) { - /* Fixed jitter */ - switch (pj_rand() % 3) { - case 0: - jitter = 0 - g_app.cfg.tx_min_jitter; - break; - case 2: - jitter = g_app.cfg.tx_min_jitter; - break; - default: - jitter = 0; - break; - } - } else { - int jitter_range; - jitter_range = (g_app.cfg.tx_max_jitter-g_app.cfg.tx_min_jitter)*2; - jitter = pj_rand() % jitter_range; - if (jitter < jitter_range/2) { - jitter = 0 - g_app.cfg.tx_min_jitter - (jitter/2); - } else { - jitter = g_app.cfg.tx_min_jitter + (jitter/2); - } - } - - } else { - jitter = 0; - } - - pj_time_val_normalize(&strm->state.tx.next_schedule); - - sprintf(log_msg, "** Packet #%u tick is at %d.%03d, %d ms jitter applied **", - strm->state.tx.total_tx+1, - (int)strm->state.tx.next_schedule.sec, (int)strm->state.tx.next_schedule.msec, - jitter); - - strm->state.tx.next_schedule.msec += jitter; - pj_time_val_normalize(&strm->state.tx.next_schedule); + struct log_entry entry; + pj_bool_t drop_this_pkt = PJ_FALSE; + int jitter; + + /* Init log entry */ + pj_bzero(&entry, sizeof(entry)); + entry.wall_clock = *t; + + /* + * Determine whether to drop this packet + */ + if (strm->state.tx.cur_lost_burst) { + /* We are currently dropping packet */ + + /* Make it comply to minimum lost burst */ + if (strm->state.tx.cur_lost_burst < g_app.cfg.tx_min_lost_burst) { + drop_this_pkt = PJ_TRUE; + } + + /* Correlate the next packet loss */ + if (!drop_this_pkt && + strm->state.tx.cur_lost_burst < g_app.cfg.tx_max_lost_burst && + MAX(strm->state.tx.total_lost-LOSS_EXTRA,0) * 100 / MAX(strm->state.tx.total_tx,1) < g_app.cfg.tx_pct_avg_lost + ) + { + strm->state.tx.drop_prob = ((g_app.cfg.tx_pct_loss_corr * strm->state.tx.drop_prob) + + ((100-g_app.cfg.tx_pct_loss_corr) * (pj_rand()%100)) + ) / 100; + if (strm->state.tx.drop_prob >= 100) + strm->state.tx.drop_prob = 99; + + if (strm->state.tx.drop_prob >= 100 - g_app.cfg.tx_pct_avg_lost) + drop_this_pkt = PJ_TRUE; + } + } + + /* If we're not dropping packet then use randomly distributed loss */ + if (!drop_this_pkt && + MAX(strm->state.tx.total_lost-LOSS_EXTRA,0) * 100 / MAX(strm->state.tx.total_tx,1) < g_app.cfg.tx_pct_avg_lost) + { + strm->state.tx.drop_prob = pj_rand() % 100; + + if (strm->state.tx.drop_prob >= 100 - g_app.cfg.tx_pct_avg_lost) + drop_this_pkt = PJ_TRUE; + } + + if (drop_this_pkt) { + /* Drop the frame */ + pjmedia_transport_simulate_lost(g_app.loop, PJMEDIA_DIR_ENCODING, 100); + run_one_frame(g_app.tx_wav, g_app.tx->port, NULL); + pjmedia_transport_simulate_lost(g_app.loop, PJMEDIA_DIR_ENCODING, 0); + + entry.event = EVENT_TX_DROP; + entry.log = "** This packet was lost **"; + + ++strm->state.tx.total_lost; + ++strm->state.tx.cur_lost_burst; + + } else { + pjmedia_rtcp_stat stat; + pjmedia_jb_state jstate; + unsigned last_discard; + + pjmedia_stream_get_stat_jbuf(g_app.rx->strm, &jstate); + last_discard = jstate.discard; + + run_one_frame(g_app.tx_wav, g_app.tx->port, NULL); + + pjmedia_stream_get_stat(g_app.rx->strm, &stat); + pjmedia_stream_get_stat_jbuf(g_app.rx->strm, &jstate); + + entry.event = EVENT_TX; + entry.jb_state = &jstate; + entry.stat = &stat; + entry.log = log_msg; + + if (jstate.discard > last_discard) + strcat(log_msg, "** Note: packet was discarded by jitter buffer **"); + + strm->state.tx.cur_lost_burst = 0; + } + + write_log(&entry, PJ_TRUE); + + ++strm->state.tx.total_tx; + + /* Calculate next schedule */ + strm->state.tx.next_schedule.sec = 0; + strm->state.tx.next_schedule.msec = (strm->state.tx.total_tx + 1) * pkt_interval; + + /* Apply jitter */ + if (g_app.cfg.tx_max_jitter || g_app.cfg.tx_min_jitter) { + + if (g_app.cfg.tx_max_jitter == g_app.cfg.tx_min_jitter) { + /* Fixed jitter */ + switch (pj_rand() % 3) { + case 0: + jitter = 0 - g_app.cfg.tx_min_jitter; + break; + case 2: + jitter = g_app.cfg.tx_min_jitter; + break; + default: + jitter = 0; + break; + } + } else { + int jitter_range; + jitter_range = (g_app.cfg.tx_max_jitter-g_app.cfg.tx_min_jitter)*2; + jitter = pj_rand() % jitter_range; + if (jitter < jitter_range/2) { + jitter = 0 - g_app.cfg.tx_min_jitter - (jitter/2); + } else { + jitter = g_app.cfg.tx_min_jitter + (jitter/2); + } + } + + } else { + jitter = 0; + } + + pj_time_val_normalize(&strm->state.tx.next_schedule); + + sprintf(log_msg, "** Packet #%u tick is at %d.%03d, %d ms jitter applied **", + strm->state.tx.total_tx+1, + (int)strm->state.tx.next_schedule.sec, (int)strm->state.tx.next_schedule.msec, + jitter); + + strm->state.tx.next_schedule.msec += jitter; + pj_time_val_normalize(&strm->state.tx.next_schedule); } /* while */ } @@ -764,62 +763,62 @@ static void rx_tick(const pj_time_val *t) long pkt_interval; pkt_interval = PJMEDIA_PIA_SPF(&port->info) * 1000 / - PJMEDIA_PIA_SRATE(&port->info) * - (long)g_app.cfg.rx_snd_burst; + PJMEDIA_PIA_SRATE(&port->info) * + (long)g_app.cfg.rx_snd_burst; if (PJ_TIME_VAL_GTE(*t, strm->state.rx.next_schedule)) { - unsigned i; - for (i=0; istrm, &stat); - pjmedia_stream_get_stat_jbuf(g_app.rx->strm, &jstate); - last_empty = jstate.empty; + pjmedia_stream_get_stat(g_app.rx->strm, &stat); + pjmedia_stream_get_stat_jbuf(g_app.rx->strm, &jstate); + last_empty = jstate.empty; - /* Pre GET event */ - pj_bzero(&entry, sizeof(entry)); - entry.event = EVENT_GET_PRE; - entry.wall_clock = *t; - entry.stat = &stat; - entry.jb_state = &jstate; + /* Pre GET event */ + pj_bzero(&entry, sizeof(entry)); + entry.event = EVENT_GET_PRE; + entry.wall_clock = *t; + entry.stat = &stat; + entry.jb_state = &jstate; - write_log(&entry, PJ_TRUE); + write_log(&entry, PJ_TRUE); - /* GET */ - run_one_frame(g_app.rx->port, g_app.rx_wav, &has_frame); + /* GET */ + run_one_frame(g_app.rx->port, g_app.rx_wav, &has_frame); - /* Post GET event */ - pjmedia_stream_get_stat(g_app.rx->strm, &stat); - pjmedia_stream_get_stat_jbuf(g_app.rx->strm, &jstate); + /* Post GET event */ + pjmedia_stream_get_stat(g_app.rx->strm, &stat); + pjmedia_stream_get_stat_jbuf(g_app.rx->strm, &jstate); - pj_bzero(&entry, sizeof(entry)); - entry.event = EVENT_GET_POST; - entry.wall_clock = *t; - entry.stat = &stat; - entry.jb_state = &jstate; + pj_bzero(&entry, sizeof(entry)); + entry.event = EVENT_GET_POST; + entry.wall_clock = *t; + entry.stat = &stat; + entry.jb_state = &jstate; - msg[0] = '\0'; - entry.log = msg; + msg[0] = '\0'; + entry.log = msg; - if (jstate.empty > last_empty) - strcat(msg, "** JBUF was empty **"); - if (!has_frame) - strcat(msg, "** NULL frame was returned **"); + if (jstate.empty > last_empty) + strcat(msg, "** JBUF was empty **"); + if (!has_frame) + strcat(msg, "** NULL frame was returned **"); - write_log(&entry, PJ_TRUE); + write_log(&entry, PJ_TRUE); - } + } - strm->state.rx.next_schedule.msec += pkt_interval; - pj_time_val_normalize(&strm->state.rx.next_schedule); + strm->state.rx.next_schedule.msec += pkt_interval; + pj_time_val_normalize(&strm->state.rx.next_schedule); } - + } static void test_loop(long duration) @@ -829,15 +828,15 @@ static void test_loop(long duration) while (PJ_TIME_VAL_MSEC(g_app.wall_clock) <= duration) { - /* Run TX tick */ - tx_tick(&g_app.wall_clock); + /* Run TX tick */ + tx_tick(&g_app.wall_clock); - /* Run RX tick */ - rx_tick(&g_app.wall_clock); + /* Run RX tick */ + rx_tick(&g_app.wall_clock); - /* Increment tick */ - g_app.wall_clock.msec += WALL_CLOCK_TICK; - pj_time_val_normalize(&g_app.wall_clock); + /* Increment tick */ + g_app.wall_clock.msec += WALL_CLOCK_TICK; + pj_time_val_normalize(&g_app.wall_clock); } } @@ -846,24 +845,24 @@ static void test_loop(long duration) * usage() */ enum { - OPT_CODEC = 'c', - OPT_INPUT = 'i', - OPT_OUTPUT = 'o', + OPT_CODEC = 'c', + OPT_INPUT = 'i', + OPT_OUTPUT = 'o', OPT_DURATION = 'd', OPT_LOG_FILE = 'l', - OPT_LOSS = 'x', + OPT_LOSS = 'x', OPT_MIN_JITTER = 'j', OPT_MAX_JITTER = 'J', OPT_SND_BURST = 'b', OPT_TX_PTIME = 't', OPT_RX_PTIME = 'r', - OPT_NO_VAD = 'U', - OPT_NO_PLC = 'p', + OPT_NO_VAD = 'U', + OPT_NO_PLC = 'p', OPT_JB_PREFETCH = 'P', OPT_JB_MIN_PRE = 'm', OPT_JB_MAX_PRE = 'M', - OPT_JB_MAX = 'X', - OPT_HELP = 'h', + OPT_JB_MAX = 'X', + OPT_HELP = 'h', OPT_MIN_LOST_BURST = 1, OPT_MAX_LOST_BURST, OPT_LOSS_CORR, @@ -926,28 +925,28 @@ static void usage(void) static int init_options(int argc, char *argv[]) { struct pj_getopt_option long_options[] = { - { "codec", 1, 0, OPT_CODEC }, - { "input", 1, 0, OPT_INPUT }, - { "output", 1, 0, OPT_OUTPUT }, - { "duration", 1, 0, OPT_DURATION }, - { "log-file", 1, 0, OPT_LOG_FILE}, - { "loss", 1, 0, OPT_LOSS }, - { "min-lost-burst", 1, 0, OPT_MIN_LOST_BURST}, - { "max-lost-burst", 1, 0, OPT_MAX_LOST_BURST}, - { "loss-corr", 1, 0, OPT_LOSS_CORR}, - { "min-jitter", 1, 0, OPT_MIN_JITTER }, - { "max-jitter", 1, 0, OPT_MAX_JITTER }, - { "snd-burst", 1, 0, OPT_SND_BURST }, - { "tx-ptime", 1, 0, OPT_TX_PTIME }, - { "rx-ptime", 1, 0, OPT_RX_PTIME }, - { "no-vad", 0, 0, OPT_NO_VAD }, - { "no-plc", 0, 0, OPT_NO_PLC }, - { "jb-prefetch", 0, 0, OPT_JB_PREFETCH }, - { "jb-min-pre", 1, 0, OPT_JB_MIN_PRE }, - { "jb-max-pre", 1, 0, OPT_JB_MAX_PRE }, - { "jb-max", 1, 0, OPT_JB_MAX }, - { "help", 0, 0, OPT_HELP}, - { NULL, 0, 0, 0 }, + { "codec", 1, 0, OPT_CODEC }, + { "input", 1, 0, OPT_INPUT }, + { "output", 1, 0, OPT_OUTPUT }, + { "duration", 1, 0, OPT_DURATION }, + { "log-file", 1, 0, OPT_LOG_FILE}, + { "loss", 1, 0, OPT_LOSS }, + { "min-lost-burst", 1, 0, OPT_MIN_LOST_BURST}, + { "max-lost-burst", 1, 0, OPT_MAX_LOST_BURST}, + { "loss-corr", 1, 0, OPT_LOSS_CORR}, + { "min-jitter", 1, 0, OPT_MIN_JITTER }, + { "max-jitter", 1, 0, OPT_MAX_JITTER }, + { "snd-burst", 1, 0, OPT_SND_BURST }, + { "tx-ptime", 1, 0, OPT_TX_PTIME }, + { "rx-ptime", 1, 0, OPT_RX_PTIME }, + { "no-vad", 0, 0, OPT_NO_VAD }, + { "no-plc", 0, 0, OPT_NO_PLC }, + { "jb-prefetch", 0, 0, OPT_JB_PREFETCH }, + { "jb-min-pre", 1, 0, OPT_JB_MIN_PRE }, + { "jb-max-pre", 1, 0, OPT_JB_MAX_PRE }, + { "jb-max", 1, 0, OPT_JB_MAX }, + { "help", 0, 0, OPT_HELP}, + { NULL, 0, 0, 0 }, }; int c; int option_index; @@ -980,117 +979,117 @@ static int init_options(int argc, char *argv[]) /* Build format */ format[0] = '\0'; for (c=0; c 100) { - puts("Error: Invalid loss value?"); - return 1; - } - break; - case OPT_MIN_LOST_BURST: - g_app.cfg.tx_min_lost_burst = atoi(pj_optarg); - break; - case OPT_MAX_LOST_BURST: - g_app.cfg.tx_max_lost_burst = atoi(pj_optarg); - break; - case OPT_LOSS_CORR: - g_app.cfg.tx_pct_loss_corr = atoi(pj_optarg); - if (g_app.cfg.tx_pct_avg_lost > 100) { - puts("Error: Loss correlation is in percentage, value is not valid?"); - return 1; - } - break; - case OPT_MIN_JITTER: - g_app.cfg.tx_min_jitter = atoi(pj_optarg); - break; - case OPT_MAX_JITTER: - g_app.cfg.tx_max_jitter = atoi(pj_optarg); - break; - case OPT_SND_BURST: - g_app.cfg.rx_snd_burst = atoi(pj_optarg); - break; - case OPT_TX_PTIME: - g_app.cfg.tx_ptime = atoi(pj_optarg); - break; - case OPT_RX_PTIME: - g_app.cfg.rx_ptime = atoi(pj_optarg); - break; - case OPT_NO_VAD: - g_app.cfg.tx_dtx = PJ_FALSE; - break; - case OPT_NO_PLC: - g_app.cfg.rx_plc = PJ_FALSE; - break; - case OPT_JB_PREFETCH: - g_app.cfg.rx_jb_init = 1; - break; - case OPT_JB_MIN_PRE: - g_app.cfg.rx_jb_min_pre = atoi(pj_optarg); - break; - case OPT_JB_MAX_PRE: - g_app.cfg.rx_jb_max_pre = atoi(pj_optarg); - break; - case OPT_JB_MAX: - g_app.cfg.rx_jb_max = atoi(pj_optarg); - break; - case OPT_HELP: - usage(); - return 1; - default: - usage(); - return 1; - } + switch (c) { + case OPT_CODEC: + g_app.cfg.codec = pj_str(pj_optarg); + break; + case OPT_INPUT: + g_app.cfg.tx_wav_in = pj_optarg; + break; + case OPT_OUTPUT: + g_app.cfg.rx_wav_out = pj_optarg; + break; + case OPT_DURATION: + g_app.cfg.duration_msec = atoi(pj_optarg) * 1000; + break; + case OPT_LOG_FILE: + g_app.cfg.log_file = pj_optarg; + break; + case OPT_LOSS: + g_app.cfg.tx_pct_avg_lost = atoi(pj_optarg); + if (g_app.cfg.tx_pct_avg_lost > 100) { + puts("Error: Invalid loss value?"); + return 1; + } + break; + case OPT_MIN_LOST_BURST: + g_app.cfg.tx_min_lost_burst = atoi(pj_optarg); + break; + case OPT_MAX_LOST_BURST: + g_app.cfg.tx_max_lost_burst = atoi(pj_optarg); + break; + case OPT_LOSS_CORR: + g_app.cfg.tx_pct_loss_corr = atoi(pj_optarg); + if (g_app.cfg.tx_pct_avg_lost > 100) { + puts("Error: Loss correlation is in percentage, value is not valid?"); + return 1; + } + break; + case OPT_MIN_JITTER: + g_app.cfg.tx_min_jitter = atoi(pj_optarg); + break; + case OPT_MAX_JITTER: + g_app.cfg.tx_max_jitter = atoi(pj_optarg); + break; + case OPT_SND_BURST: + g_app.cfg.rx_snd_burst = atoi(pj_optarg); + break; + case OPT_TX_PTIME: + g_app.cfg.tx_ptime = atoi(pj_optarg); + break; + case OPT_RX_PTIME: + g_app.cfg.rx_ptime = atoi(pj_optarg); + break; + case OPT_NO_VAD: + g_app.cfg.tx_dtx = PJ_FALSE; + break; + case OPT_NO_PLC: + g_app.cfg.rx_plc = PJ_FALSE; + break; + case OPT_JB_PREFETCH: + g_app.cfg.rx_jb_init = 1; + break; + case OPT_JB_MIN_PRE: + g_app.cfg.rx_jb_min_pre = atoi(pj_optarg); + break; + case OPT_JB_MAX_PRE: + g_app.cfg.rx_jb_max_pre = atoi(pj_optarg); + break; + case OPT_JB_MAX: + g_app.cfg.rx_jb_max = atoi(pj_optarg); + break; + case OPT_HELP: + usage(); + return 1; + default: + usage(); + return 1; + } } /* Check for orphaned params */ if (pj_optind < argc) { - usage(); - return 1; + usage(); + return 1; } /* Normalize options */ if (g_app.cfg.rx_jb_init < g_app.cfg.rx_jb_min_pre) - g_app.cfg.rx_jb_init = g_app.cfg.rx_jb_min_pre; + g_app.cfg.rx_jb_init = g_app.cfg.rx_jb_min_pre; else if (g_app.cfg.rx_jb_init > g_app.cfg.rx_jb_max_pre) - g_app.cfg.rx_jb_init = g_app.cfg.rx_jb_max_pre; + g_app.cfg.rx_jb_init = g_app.cfg.rx_jb_max_pre; if (g_app.cfg.tx_max_jitter < g_app.cfg.tx_min_jitter) - g_app.cfg.tx_max_jitter = g_app.cfg.tx_min_jitter; + g_app.cfg.tx_max_jitter = g_app.cfg.tx_min_jitter; return 0; } @@ -1102,37 +1101,37 @@ int main(int argc, char *argv[]) pj_status_t status; if (init_options(argc, argv) != 0) - return 1; + return 1; /* Init */ status = test_init(); if (status != PJ_SUCCESS) - return 1; + return 1; /* Print parameters */ PJ_LOG(3,(THIS_FILE, "Starting simulation. Parameters: ")); PJ_LOG(3,(THIS_FILE, " Codec=%.*s, tx_ptime=%d, rx_ptime=%d", - (int)g_app.cfg.codec.slen, - g_app.cfg.codec.ptr, - g_app.cfg.tx_ptime, - g_app.cfg.rx_ptime)); + (int)g_app.cfg.codec.slen, + g_app.cfg.codec.ptr, + g_app.cfg.tx_ptime, + g_app.cfg.rx_ptime)); PJ_LOG(3,(THIS_FILE, " Loss avg=%d%%, min_burst=%d, max_burst=%d", - g_app.cfg.tx_pct_avg_lost, - g_app.cfg.tx_min_lost_burst, - g_app.cfg.tx_max_lost_burst)); + g_app.cfg.tx_pct_avg_lost, + g_app.cfg.tx_min_lost_burst, + g_app.cfg.tx_max_lost_burst)); PJ_LOG(3,(THIS_FILE, " TX jitter min=%dms, max=%dms", - g_app.cfg.tx_min_jitter, - g_app.cfg.tx_max_jitter)); + g_app.cfg.tx_min_jitter, + g_app.cfg.tx_max_jitter)); PJ_LOG(3,(THIS_FILE, " RX jb init:%dms, min_pre=%dms, max_pre=%dms, max=%dms", - g_app.cfg.rx_jb_init, - g_app.cfg.rx_jb_min_pre, - g_app.cfg.rx_jb_max_pre, - g_app.cfg.rx_jb_max)); + g_app.cfg.rx_jb_init, + g_app.cfg.rx_jb_min_pre, + g_app.cfg.rx_jb_max_pre, + g_app.cfg.rx_jb_max)); PJ_LOG(3,(THIS_FILE, " RX sound burst:%d frames", - g_app.cfg.rx_snd_burst)); + g_app.cfg.rx_snd_burst)); PJ_LOG(3,(THIS_FILE, " DTX=%d, PLC=%d", - g_app.cfg.tx_dtx, g_app.cfg.rx_plc)); + g_app.cfg.tx_dtx, g_app.cfg.rx_plc)); /* Run test loop */ test_loop(g_app.cfg.duration_msec); @@ -1140,9 +1139,9 @@ int main(int argc, char *argv[]) /* Print statistics */ PJ_LOG(3,(THIS_FILE, "Simulation done")); PJ_LOG(3,(THIS_FILE, " TX packets=%u, dropped=%u/%5.1f%%", - g_app.tx->state.tx.total_tx, - g_app.tx->state.tx.total_lost, - (float)(g_app.tx->state.tx.total_lost * 100.0 / g_app.tx->state.tx.total_tx))); + g_app.tx->state.tx.total_tx, + g_app.tx->state.tx.total_lost, + (float)(g_app.tx->state.tx.total_lost * 100.0 / g_app.tx->state.tx.total_tx))); /* Done */ test_destroy(); diff --git a/pjsip-apps/src/samples/latency.c b/pjsip-apps/src/samples/latency.c index c9192b52f3..dc5bd92c7c 100644 --- a/pjsip-apps/src/samples/latency.c +++ b/pjsip-apps/src/samples/latency.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,7 +31,7 @@ /* Util to display the error message for the specified error code */ static int app_perror( const char *sender, const char *title, - pj_status_t status) + pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; @@ -57,9 +56,9 @@ static int calculate_latency(pj_pool_t *pool, pjmedia_port *wav) pj_status_t status; unsigned lat_sum = 0, - lat_cnt = 0, - lat_min = 10000, - lat_max = 0; + lat_cnt = 0, + lat_min = 10000, + lat_max = 0; samples_per_frame = PJMEDIA_PIA_SPF(&wav->info); frm.buf = pj_pool_alloc(pool, samples_per_frame * 2); @@ -69,63 +68,63 @@ static int calculate_latency(pj_pool_t *pool, pjmedia_port *wav) read = 0; while (read < len/2) { - status = pjmedia_port_get_frame(wav, &frm); - if (status != PJ_SUCCESS) - break; + status = pjmedia_port_get_frame(wav, &frm); + if (status != PJ_SUCCESS) + break; - pjmedia_copy_samples(buf+read, (short*)frm.buf, samples_per_frame); - read += samples_per_frame; + pjmedia_copy_samples(buf+read, (short*)frm.buf, samples_per_frame); + read += samples_per_frame; } if (read < 2 * PJMEDIA_PIA_SRATE(&wav->info)) { - puts("Error: too short"); - return -1; + puts("Error: too short"); + return -1; } start_pos = 0; while (start_pos < len/2 - PJMEDIA_PIA_SRATE(&wav->info)) { - int max_signal = 0; - unsigned max_signal_pos = start_pos; - unsigned max_echo_pos = 0; - unsigned pos; - unsigned lat; - - /* Get the largest signal in the next 0.7s */ - for (i=start_pos; iinfo) * 700 / 1000; ++i) { - if (abs(buf[i]) > max_signal) { - max_signal = abs(buf[i]); - max_signal_pos = i; - } - } - - /* Advance 10ms from max_signal_pos */ - pos = max_signal_pos + 10 * PJMEDIA_PIA_SRATE(&wav->info) / 1000; - - /* Get the largest signal in the next 500ms */ - max_signal = 0; - max_echo_pos = pos; - for (i=pos; iinfo)/2; ++i) { - if (abs(buf[i]) > max_signal) { - max_signal = abs(buf[i]); - max_echo_pos = i; - } - } - - lat = (max_echo_pos - max_signal_pos) * 1000 / PJMEDIA_PIA_SRATE(&wav->info); - + int max_signal = 0; + unsigned max_signal_pos = start_pos; + unsigned max_echo_pos = 0; + unsigned pos; + unsigned lat; + + /* Get the largest signal in the next 0.7s */ + for (i=start_pos; iinfo) * 700 / 1000; ++i) { + if (abs(buf[i]) > max_signal) { + max_signal = abs(buf[i]); + max_signal_pos = i; + } + } + + /* Advance 10ms from max_signal_pos */ + pos = max_signal_pos + 10 * PJMEDIA_PIA_SRATE(&wav->info) / 1000; + + /* Get the largest signal in the next 500ms */ + max_signal = 0; + max_echo_pos = pos; + for (i=pos; iinfo)/2; ++i) { + if (abs(buf[i]) > max_signal) { + max_signal = abs(buf[i]); + max_echo_pos = i; + } + } + + lat = (max_echo_pos - max_signal_pos) * 1000 / PJMEDIA_PIA_SRATE(&wav->info); + #if 0 - printf("Latency = %u\n", lat); + printf("Latency = %u\n", lat); #endif - lat_sum += lat; - lat_cnt++; - if (lat < lat_min) - lat_min = lat; - if (lat > lat_max) - lat_max = lat; + lat_sum += lat; + lat_cnt++; + if (lat < lat_min) + lat_min = lat; + if (lat > lat_max) + lat_max = lat; - /* Advance next loop */ - start_pos += PJMEDIA_PIA_SRATE(&wav->info); + /* Advance next loop */ + start_pos += PJMEDIA_PIA_SRATE(&wav->info); } printf("Latency average = %u\n", lat_sum / lat_cnt); @@ -150,9 +149,9 @@ int main(int argc, char *argv[]) /* Verify cmd line arguments. */ if (argc != 2) { - puts("Error: missing argument(s)"); - puts("Usage: latency REV.WAV"); - return 1; + puts("Error: missing argument(s)"); + puts("Usage: latency REV.WAV"); + return 1; } pj_log_set_level(0); @@ -162,33 +161,33 @@ int main(int argc, char *argv[]) pj_caching_pool_init(&cp, &pj_pool_factory_default_policy, 0); - pool = pj_pool_create( &cp.factory, /* pool factory */ - "wav", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "wav", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); status = pj_register_strerror(PJMEDIA_ERRNO_START, PJ_ERRNO_SPACE_SIZE, - &pjmedia_strerror); + &pjmedia_strerror); pj_assert(status == PJ_SUCCESS); /* Wav */ - status = pjmedia_wav_player_port_create( pool, /* memory pool */ - argv[1], /* file to play */ - 0, /* use default ptime*/ - 0, /* flags */ - 0, /* default buffer */ - &wav /* returned port */ - ); + status = pjmedia_wav_player_port_create( pool, /* memory pool */ + argv[1], /* file to play */ + 0, /* use default ptime*/ + 0, /* flags */ + 0, /* default buffer */ + &wav /* returned port */ + ); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, argv[1], status); - return 1; + app_perror(THIS_FILE, argv[1], status); + return 1; } status = calculate_latency(pool, wav); if (status != PJ_SUCCESS) - return 1; + return 1; status = pjmedia_port_destroy( wav ); PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); diff --git a/pjsip-apps/src/samples/level.c b/pjsip-apps/src/samples/level.c index 6bba3fe1b8..d58da84f34 100644 --- a/pjsip-apps/src/samples/level.c +++ b/pjsip-apps/src/samples/level.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,17 +31,17 @@ static const char *desc = - " FILE: \n" - " level.c \n" - " \n" - " PURPOSE: \n" + " FILE: \n" + " level.c \n" + " \n" + " PURPOSE: \n" " Read PCM WAV file and display the audio level the first 100 frames. \n" - " Each frame is assumed to have 160 samples. \n" - " \n" - " USAGE: \n" - " level file.wav \n" - " \n" - " The WAV file SHOULD have a 16bit mono samples. "; + " Each frame is assumed to have 160 samples. \n" + " \n" + " USAGE: \n" + " level file.wav \n" + " \n" + " The WAV file SHOULD have a 16bit mono samples. "; #include #include @@ -55,7 +54,7 @@ static const char *desc = /* Util to display the error message for the specified error code */ static int app_perror( const char *sender, const char *title, - pj_status_t status) + pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; @@ -84,9 +83,9 @@ int main(int argc, char *argv[]) /* Verify cmd line arguments. */ if (argc != 2) { - puts(""); - puts(desc); - return 1; + puts(""); + puts(desc); + return 1; } /* Must init PJLIB first: */ @@ -104,54 +103,54 @@ int main(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool for our file player */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "wav", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "wav", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); /* Create file media port from the WAV file */ - status = pjmedia_wav_player_port_create( pool, /* memory pool */ - argv[1], /* file to play */ - 0, /* use default ptime*/ - 0, /* flags */ - 0, /* default buffer */ - &file_port/* returned port */ - ); + status = pjmedia_wav_player_port_create( pool, /* memory pool */ + argv[1], /* file to play */ + 0, /* use default ptime*/ + 0, /* flags */ + 0, /* default buffer */ + &file_port/* returned port */ + ); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to use WAV file", status); - return 1; + app_perror(THIS_FILE, "Unable to use WAV file", status); + return 1; } if (PJMEDIA_PIA_SPF(&file_port->info) > NSAMPLES) { - app_perror(THIS_FILE, "WAV clock rate is too big", PJ_EINVAL); - return 1; + app_perror(THIS_FILE, "WAV clock rate is too big", PJ_EINVAL); + return 1; } puts("Time\tPCMU\tLinear"); puts("------------------------"); for (i=0; iinfo)); - level = pjmedia_linear2ulaw(level32) ^ 0xFF; - - ms = i * 1000 * PJMEDIA_PIA_SPF(&file_port->info) / - PJMEDIA_PIA_SRATE(&file_port->info); - printf("%03d.%03d\t%7d\t%7d\n", - ms/1000, ms%1000, level, level32); + pj_int16_t framebuf[NSAMPLES]; + pjmedia_frame frm; + pj_int32_t level32; + unsigned ms; + int level; + + frm.buf = framebuf; + frm.size = sizeof(framebuf); + + pjmedia_port_get_frame(file_port, &frm); + + level32 = pjmedia_calc_avg_signal(framebuf, + PJMEDIA_PIA_SPF(&file_port->info)); + level = pjmedia_linear2ulaw(level32) ^ 0xFF; + + ms = i * 1000 * PJMEDIA_PIA_SPF(&file_port->info) / + PJMEDIA_PIA_SRATE(&file_port->info); + printf("%03d.%03d\t%7d\t%7d\n", + ms/1000, ms%1000, level, level32); } puts(""); diff --git a/pjsip-apps/src/samples/mix.c b/pjsip-apps/src/samples/mix.c index da2dd6d8e5..51956cd122 100644 --- a/pjsip-apps/src/samples/mix.c +++ b/pjsip-apps/src/samples/mix.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -53,15 +52,15 @@ static const char *desc = " -f Force write (overwrite output without warning\n" ; -#define MAX_WAV 16 -#define PTIME 20 -#define APPEND 1000 +#define MAX_WAV 16 +#define PTIME 20 +#define APPEND 1000 struct wav_input { - const char *fname; + const char *fname; pjmedia_port *port; - unsigned slot; + unsigned slot; }; static int err_ret(const char *title, pj_status_t status) @@ -93,65 +92,65 @@ int main(int argc, char *argv[]) pj_status_t status; #define CHECK(op) do { \ - status = op; \ - if (status != PJ_SUCCESS) \ - return err_ret(#op, status); \ - } while (0) + status = op; \ + if (status != PJ_SUCCESS) \ + return err_ret(#op, status); \ + } while (0) /* Parse arguments */ while ((c=pj_getopt(argc, argv, "c:f")) != -1) { - switch (c) { - case 'c': - clock_rate = atoi(pj_optarg); - if (clock_rate < 1000) { - puts("Error: invalid clock rate"); - usage(); - return -1; - } - break; - case 'f': - force = 1; - break; - } + switch (c) { + case 'c': + clock_rate = atoi(pj_optarg); + if (clock_rate < 1000) { + puts("Error: invalid clock rate"); + usage(); + return -1; + } + break; + case 'f': + force = 1; + break; + } } /* Get output WAV name */ if (pj_optind == argc) { - puts("Error: no WAV output is specified"); - usage(); - return 1; + puts("Error: no WAV output is specified"); + usage(); + return 1; } out_fname = argv[pj_optind++]; if (force==0 && pj_file_exists(out_fname)) { - char in[8]; - - printf("File %s exists, overwrite? [Y/N] ", out_fname); - fflush(stdout); - if (fgets(in, sizeof(in), stdin) == NULL) - return 1; - if (pj_tolower(in[0]) != 'y') - return 1; + char in[8]; + + printf("File %s exists, overwrite? [Y/N] ", out_fname); + fflush(stdout); + if (fgets(in, sizeof(in), stdin) == NULL) + return 1; + if (pj_tolower(in[0]) != 'y') + return 1; } /* Scan input file names */ for (input_cnt=0 ; pj_optindinfo)); - if (len > (pj_ssize_t)longest) - longest = len; + CHECK( pjmedia_wav_player_port_create(pool, wav_input[i].fname, 20, + PJMEDIA_FILE_NO_LOOP, 0, + &wav_input[i].port) ); + len = pjmedia_wav_player_get_len(wav_input[i].port); + len = (pj_ssize_t)(len * 1.0 * clock_rate / + PJMEDIA_PIA_SRATE(&wav_input[i].port->info)); + if (len > (pj_ssize_t)longest) + longest = len; - CHECK( pjmedia_conf_add_port(conf, pool, wav_input[i].port, - NULL, &wav_input[i].slot)); + CHECK( pjmedia_conf_add_port(conf, pool, wav_input[i].port, + NULL, &wav_input[i].slot)); - CHECK( pjmedia_conf_connect_port(conf, wav_input[i].slot, 0, 0) ); + CHECK( pjmedia_conf_connect_port(conf, wav_input[i].slot, 0, 0) ); } /* Loop reading frame from the bridge and write it to WAV */ processed = 0; while (processed < longest + clock_rate * APPEND * 2 / 1000) { - pj_int16_t framebuf[PTIME * 48000 / 1000]; - pjmedia_port *mp = pjmedia_conf_get_master_port(conf); - pjmedia_frame frame; + pj_int16_t framebuf[PTIME * 48000 / 1000]; + pjmedia_port *mp = pjmedia_conf_get_master_port(conf); + pjmedia_frame frame; - frame.buf = framebuf; - frame.size = PJMEDIA_PIA_SPF(&mp->info) * 2; - pj_assert(frame.size <= sizeof(framebuf)); - - CHECK( pjmedia_port_get_frame(mp, &frame) ); + frame.buf = framebuf; + frame.size = PJMEDIA_PIA_SPF(&mp->info) * 2; + pj_assert(frame.size <= sizeof(framebuf)); + + CHECK( pjmedia_port_get_frame(mp, &frame) ); - if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) { - pj_bzero(frame.buf, frame.size); - frame.type = PJMEDIA_FRAME_TYPE_AUDIO; - } + if (frame.type != PJMEDIA_FRAME_TYPE_AUDIO) { + pj_bzero(frame.buf, frame.size); + frame.type = PJMEDIA_FRAME_TYPE_AUDIO; + } - CHECK( pjmedia_port_put_frame(wavout, &frame)); + CHECK( pjmedia_port_put_frame(wavout, &frame)); - processed += frame.size; + processed += frame.size; } PJ_LOG(3,(THIS_FILE, "Done. Output duration: %d.%03d", - (processed >> 2)/clock_rate, - ((processed >> 2)*1000/clock_rate) % 1000)); + (processed >> 2)/clock_rate, + ((processed >> 2)*1000/clock_rate) % 1000)); /* Shutdown everything */ CHECK( pjmedia_port_destroy(wavout) ); for (i=0; i @@ -44,7 +43,7 @@ static const char *USAGE = "\n" "Options for RTP packet processing:\n" "" -" --codec=codec_id The codec ID formatted \"name/clock-rate/channel-count\"\n" +" --codec=codec_id The codec ID formatted \"name/clock-rate/channel-count\"\n" " must be specified for codec with dynamic PT,\n" " e.g: \"Speex/8000\"\n" " --srtp-crypto=TAG, -c Set crypto to be used to decrypt SRTP packets. Valid\n" @@ -67,17 +66,17 @@ static const char *USAGE = static struct app { - pj_caching_pool cp; - pj_pool_t *pool; - pjmedia_endpt *mept; - pj_pcap_file *pcap; - pjmedia_port *wav; - pjmedia_codec *codec; + pj_caching_pool cp; + pj_pool_t *pool; + pjmedia_endpt *mept; + pj_pcap_file *pcap; + pjmedia_port *wav; + pjmedia_codec *codec; pjmedia_aud_stream *aud_strm; - unsigned pt; - pjmedia_transport *srtp; - pjmedia_rtp_session rtp_sess; - pj_bool_t rtp_sess_init; + unsigned pt; + pjmedia_transport *srtp; + pjmedia_rtp_session rtp_sess; + pj_bool_t rtp_sess_init; } app; @@ -94,18 +93,18 @@ static void cleanup() (msec / 1000) % 60, msec % 1000); } - pjmedia_port_destroy(app.wav); + pjmedia_port_destroy(app.wav); } if (app.pcap) pj_pcap_close(app.pcap); if (app.codec) { - pjmedia_codec_mgr *cmgr; - pjmedia_codec_close(app.codec); - cmgr = pjmedia_endpt_get_codec_mgr(app.mept); - pjmedia_codec_mgr_dealloc_codec(cmgr, app.codec); + pjmedia_codec_mgr *cmgr; + pjmedia_codec_close(app.codec); + cmgr = pjmedia_endpt_get_codec_mgr(app.mept); + pjmedia_codec_mgr_dealloc_codec(cmgr, app.codec); } if (app.aud_strm) { - pjmedia_aud_stream_stop(app.aud_strm); - pjmedia_aud_stream_destroy(app.aud_strm); + pjmedia_aud_stream_stop(app.aud_strm); + pjmedia_aud_stream_destroy(app.aud_strm); } if (app.mept) pjmedia_endpt_destroy(app.mept); if (app.pool) pj_pool_release(app.pool); @@ -116,115 +115,115 @@ static void cleanup() static void err_exit(const char *title, pj_status_t status) { if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - printf("Error: %s: %s\n", title, errmsg); + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + printf("Error: %s: %s\n", title, errmsg); } else { - printf("Error: %s\n", title); + printf("Error: %s\n", title); } cleanup(); exit(1); } -#define T(op) do { \ - status = op; \ - if (status != PJ_SUCCESS) \ - err_exit(#op, status); \ - } while (0) +#define T(op) do { \ + status = op; \ + if (status != PJ_SUCCESS) \ + err_exit(#op, status); \ + } while (0) static void read_rtp(pj_uint8_t *buf, pj_size_t bufsize, - pjmedia_rtp_hdr **rtp, - pj_uint8_t **payload, - unsigned *payload_size, - pj_bool_t check_pt) + pjmedia_rtp_hdr **rtp, + pj_uint8_t **payload, + unsigned *payload_size, + pj_bool_t check_pt) { pj_status_t status; /* Init RTP session */ if (!app.rtp_sess_init) { - T(pjmedia_rtp_session_init(&app.rtp_sess, 0, 0)); - app.rtp_sess_init = PJ_TRUE; + T(pjmedia_rtp_session_init(&app.rtp_sess, 0, 0)); + app.rtp_sess_init = PJ_TRUE; } /* Loop reading until we have a good RTP packet */ for (;;) { - pj_size_t sz = bufsize; - const pjmedia_rtp_hdr *r; - const void *p; - pjmedia_rtp_status seq_st; - - status = pj_pcap_read_udp(app.pcap, NULL, buf, &sz); - if (status != PJ_SUCCESS) - err_exit("Error reading PCAP file", status); - - /* Decode RTP packet to make sure that this is an RTP packet. - * We will decode it again to get the payload after we do - * SRTP decoding - */ - status = pjmedia_rtp_decode_rtp(&app.rtp_sess, buf, (int)sz, &r, - &p, payload_size); - if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - printf("Not RTP packet, skipping packet: %s\n", errmsg); - continue; - } - - /* Decrypt SRTP */ + pj_size_t sz = bufsize; + const pjmedia_rtp_hdr *r; + const void *p; + pjmedia_rtp_status seq_st; + + status = pj_pcap_read_udp(app.pcap, NULL, buf, &sz); + if (status != PJ_SUCCESS) + err_exit("Error reading PCAP file", status); + + /* Decode RTP packet to make sure that this is an RTP packet. + * We will decode it again to get the payload after we do + * SRTP decoding + */ + status = pjmedia_rtp_decode_rtp(&app.rtp_sess, buf, (int)sz, &r, + &p, payload_size); + if (status != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + printf("Not RTP packet, skipping packet: %s\n", errmsg); + continue; + } + + /* Decrypt SRTP */ #if PJMEDIA_HAS_SRTP - if (app.srtp) { - int len = (int)sz; - status = pjmedia_transport_srtp_decrypt_pkt(app.srtp, PJ_TRUE, - buf, &len); - if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - printf("SRTP packet decryption failed, skipping packet: %s\n", - errmsg); - continue; - } - sz = len; - - /* Decode RTP packet again */ - status = pjmedia_rtp_decode_rtp(&app.rtp_sess, buf, (int)sz, &r, - &p, payload_size); - if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - printf("Not RTP packet, skipping packet: %s\n", errmsg); - continue; - } - } + if (app.srtp) { + int len = (int)sz; + status = pjmedia_transport_srtp_decrypt_pkt(app.srtp, PJ_TRUE, + buf, &len); + if (status != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + printf("SRTP packet decryption failed, skipping packet: %s\n", + errmsg); + continue; + } + sz = len; + + /* Decode RTP packet again */ + status = pjmedia_rtp_decode_rtp(&app.rtp_sess, buf, (int)sz, &r, + &p, payload_size); + if (status != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + printf("Not RTP packet, skipping packet: %s\n", errmsg); + continue; + } + } #endif - /* Update RTP session */ - pjmedia_rtp_session_update2(&app.rtp_sess, r, &seq_st, PJ_FALSE); + /* Update RTP session */ + pjmedia_rtp_session_update2(&app.rtp_sess, r, &seq_st, PJ_FALSE); - /* Skip out-of-order packet */ - if (seq_st.diff == 0) { - printf("Skipping out of order packet\n"); - continue; - } + /* Skip out-of-order packet */ + if (seq_st.diff == 0) { + printf("Skipping out of order packet\n"); + continue; + } - /* Skip if payload type is different */ - if (check_pt && r->pt != app.pt) { - printf("Skipping RTP packet with bad payload type\n"); - continue; - } + /* Skip if payload type is different */ + if (check_pt && r->pt != app.pt) { + printf("Skipping RTP packet with bad payload type\n"); + continue; + } - /* Skip bad packet */ - if (seq_st.status.flag.bad) { - printf("Skipping bad RTP\n"); - continue; - } + /* Skip bad packet */ + if (seq_st.status.flag.bad) { + printf("Skipping bad RTP\n"); + continue; + } - *rtp = (pjmedia_rtp_hdr*)r; - *payload = (pj_uint8_t*)p; + *rtp = (pjmedia_rtp_hdr*)r; + *payload = (pj_uint8_t*)p; - /* We have good packet */ - break; + /* We have good packet */ + break; } } @@ -237,7 +236,7 @@ static pj_status_t wait_play(pjmedia_frame *f) play_frm = *f; play_frm_ready = PJ_TRUE; while (!play_frm_copied) { - pj_thread_sleep(1); + pj_thread_sleep(1); } play_frm_ready = PJ_FALSE; @@ -249,8 +248,8 @@ static pj_status_t play_cb(void *user_data, pjmedia_frame *f) PJ_UNUSED_ARG(user_data); if (!play_frm_ready) { - PJ_LOG(3, ("play_cb()", "Warning! Play frame not ready")); - return PJ_SUCCESS; + PJ_LOG(3, ("play_cb()", "Warning! Play frame not ready")); + return PJ_SUCCESS; } pj_memcpy(f->buf, play_frm.buf, play_frm.size); @@ -261,18 +260,18 @@ static pj_status_t play_cb(void *user_data, pjmedia_frame *f) } static void pcap2wav(const pj_str_t *codec, - const pj_str_t *wav_filename, - pjmedia_aud_dev_index dev_id, - const pj_str_t *srtp_crypto, - const pj_str_t *srtp_key) + const pj_str_t *wav_filename, + pjmedia_aud_dev_index dev_id, + const pj_str_t *srtp_crypto, + const pj_str_t *srtp_key) { const pj_str_t WAV = {".wav", 4}; struct pkt { - pj_uint8_t buffer[PJMEDIA_MAX_MTU]; - pjmedia_rtp_hdr *rtp; - pj_uint8_t *payload; - unsigned payload_len; + pj_uint8_t buffer[PJMEDIA_MAX_MTU]; + pjmedia_rtp_hdr *rtp; + pj_uint8_t *payload; + unsigned payload_len; } pkt0; pjmedia_codec_mgr *cmgr; const pjmedia_codec_info *ci; @@ -286,15 +285,15 @@ static void pcap2wav(const pj_str_t *codec, /* Create SRTP transport is needed */ #if PJMEDIA_HAS_SRTP if (srtp_crypto->slen) { - pjmedia_srtp_crypto crypto; - pjmedia_transport *tp; - - pj_bzero(&crypto, sizeof(crypto)); - crypto.key = *srtp_key; - crypto.name = *srtp_crypto; - T( pjmedia_transport_loop_create(app.mept, &tp) ); - T( pjmedia_transport_srtp_create(app.mept, tp, NULL, &app.srtp) ); - T( pjmedia_transport_srtp_start(app.srtp, &crypto, &crypto) ); + pjmedia_srtp_crypto crypto; + pjmedia_transport *tp; + + pj_bzero(&crypto, sizeof(crypto)); + crypto.key = *srtp_key; + crypto.name = *srtp_crypto; + T( pjmedia_transport_loop_create(app.mept, &tp) ); + T( pjmedia_transport_srtp_create(app.mept, tp, NULL, &app.srtp) ); + T( pjmedia_transport_srtp_start(app.srtp, &crypto, &crypto) ); } #else PJ_UNUSED_ARG(srtp_crypto); @@ -303,23 +302,23 @@ static void pcap2wav(const pj_str_t *codec, /* Read first packet */ read_rtp(pkt0.buffer, sizeof(pkt0.buffer), &pkt0.rtp, - &pkt0.payload, &pkt0.payload_len, PJ_FALSE); + &pkt0.payload, &pkt0.payload_len, PJ_FALSE); cmgr = pjmedia_endpt_get_codec_mgr(app.mept); /* Get codec info and param for the specified payload type */ app.pt = pkt0.rtp->pt; if (app.pt < 96) { - T( pjmedia_codec_mgr_get_codec_info(cmgr, pkt0.rtp->pt, &ci) ); + T( pjmedia_codec_mgr_get_codec_info(cmgr, pkt0.rtp->pt, &ci) ); } else { - unsigned cnt = 2; - const pjmedia_codec_info *info[2]; - T( pjmedia_codec_mgr_find_codecs_by_id(cmgr, codec, &cnt, - info, NULL) ); - if (cnt != 1) - err_exit("Codec ID must be specified and unique!", 0); - - ci = info[0]; + unsigned cnt = 2; + const pjmedia_codec_info *info[2]; + T( pjmedia_codec_mgr_find_codecs_by_id(cmgr, codec, &cnt, + info, NULL) ); + if (cnt != 1) + err_exit("Codec ID must be specified and unique!", 0); + + ci = info[0]; } T( pjmedia_codec_mgr_get_default_param(cmgr, ci, ¶m) ); @@ -331,94 +330,94 @@ static void pcap2wav(const pj_str_t *codec, /* Init audio device or WAV file */ samples_per_frame = ci->clock_rate * param.info.frm_ptime / 1000; if (pj_strcmp2(wav_filename, "-") == 0) { - pjmedia_aud_param aud_param; - - /* Open audio device */ - T( pjmedia_aud_dev_default_param(dev_id, &aud_param) ); - aud_param.dir = PJMEDIA_DIR_PLAYBACK; - aud_param.channel_count = ci->channel_cnt; - aud_param.clock_rate = ci->clock_rate; - aud_param.samples_per_frame = samples_per_frame; - T( pjmedia_aud_stream_create(&aud_param, NULL, &play_cb, - NULL, &app.aud_strm) ); - T( pjmedia_aud_stream_start(app.aud_strm) ); + pjmedia_aud_param aud_param; + + /* Open audio device */ + T( pjmedia_aud_dev_default_param(dev_id, &aud_param) ); + aud_param.dir = PJMEDIA_DIR_PLAYBACK; + aud_param.channel_count = ci->channel_cnt; + aud_param.clock_rate = ci->clock_rate; + aud_param.samples_per_frame = samples_per_frame; + T( pjmedia_aud_stream_create(&aud_param, NULL, &play_cb, + NULL, &app.aud_strm) ); + T( pjmedia_aud_stream_start(app.aud_strm) ); } else if (pj_stristr(wav_filename, &WAV)) { - /* Open WAV file */ - T( pjmedia_wav_writer_port_create(app.pool, wav_filename->ptr, - ci->clock_rate, ci->channel_cnt, - samples_per_frame, - param.info.pcm_bits_per_sample, 0, 0, - &app.wav) ); + /* Open WAV file */ + T( pjmedia_wav_writer_port_create(app.pool, wav_filename->ptr, + ci->clock_rate, ci->channel_cnt, + samples_per_frame, + param.info.pcm_bits_per_sample, 0, 0, + &app.wav) ); } else { - err_exit("invalid output file", PJ_EINVAL); + err_exit("invalid output file", PJ_EINVAL); } /* Loop reading PCAP and writing WAV file */ for (;;) { - struct pkt pkt1; - pj_timestamp ts; - pjmedia_frame frames[16], pcm_frame; - short pcm[PJMEDIA_MAX_MTU]; - unsigned i, frame_cnt; - long samples_cnt, ts_gap; - - pj_assert(sizeof(pcm) >= samples_per_frame); - - /* Parse first packet */ - ts.u64 = 0; - frame_cnt = PJ_ARRAY_SIZE(frames); - T( pjmedia_codec_parse(app.codec, pkt0.payload, pkt0.payload_len, - &ts, &frame_cnt, frames) ); - - /* Decode and write to WAV file */ - samples_cnt = 0; - for (i=0; its) - pj_ntohl(pkt0.rtp->ts) - - samples_cnt; - while (ts_gap >= (long)samples_per_frame) { - - pcm_frame.buf = pcm; - pcm_frame.size = samples_per_frame * 2; - - if (app.codec->op->recover) { - T( pjmedia_codec_recover(app.codec, (unsigned)pcm_frame.size, - &pcm_frame) ); - } else { - pj_bzero(pcm_frame.buf, pcm_frame.size); - } - - if (app.wav) { - T( pjmedia_port_put_frame(app.wav, &pcm_frame) ); - } - if (app.aud_strm) { - T( wait_play(&pcm_frame) ); - } - ts_gap -= samples_per_frame; - } - - /* Next */ - pkt0 = pkt1; - pkt0.rtp = (pjmedia_rtp_hdr*)pkt0.buffer; - pkt0.payload = pkt0.buffer + (pkt1.payload - pkt1.buffer); + struct pkt pkt1; + pj_timestamp ts; + pjmedia_frame frames[16], pcm_frame; + short pcm[PJMEDIA_MAX_MTU]; + unsigned i, frame_cnt; + long samples_cnt, ts_gap; + + pj_assert(sizeof(pcm) >= samples_per_frame); + + /* Parse first packet */ + ts.u64 = 0; + frame_cnt = PJ_ARRAY_SIZE(frames); + T( pjmedia_codec_parse(app.codec, pkt0.payload, pkt0.payload_len, + &ts, &frame_cnt, frames) ); + + /* Decode and write to WAV file */ + samples_cnt = 0; + for (i=0; its) - pj_ntohl(pkt0.rtp->ts) - + samples_cnt; + while (ts_gap >= (long)samples_per_frame) { + + pcm_frame.buf = pcm; + pcm_frame.size = samples_per_frame * 2; + + if (app.codec->op->recover) { + T( pjmedia_codec_recover(app.codec, (unsigned)pcm_frame.size, + &pcm_frame) ); + } else { + pj_bzero(pcm_frame.buf, pcm_frame.size); + } + + if (app.wav) { + T( pjmedia_port_put_frame(app.wav, &pcm_frame) ); + } + if (app.aud_strm) { + T( wait_play(&pcm_frame) ); + } + ts_gap -= samples_per_frame; + } + + /* Next */ + pkt0 = pkt1; + pkt0.rtp = (pjmedia_rtp_hdr*)pkt0.buffer; + pkt0.payload = pkt0.buffer + (pkt1.payload - pkt1.buffer); } } @@ -431,19 +430,19 @@ int main(int argc, char *argv[]) pj_status_t status; enum { - OPT_SRC_IP = 1, OPT_DST_IP, OPT_SRC_PORT, OPT_DST_PORT, - OPT_CODEC, OPT_PLAY_DEV_ID + OPT_SRC_IP = 1, OPT_DST_IP, OPT_SRC_PORT, OPT_DST_PORT, + OPT_CODEC, OPT_PLAY_DEV_ID }; struct pj_getopt_option long_options[] = { - { "srtp-crypto", 1, 0, 'c' }, - { "srtp-key", 1, 0, 'k' }, - { "src-ip", 1, 0, OPT_SRC_IP }, - { "dst-ip", 1, 0, OPT_DST_IP }, - { "src-port", 1, 0, OPT_SRC_PORT }, - { "dst-port", 1, 0, OPT_DST_PORT }, - { "codec", 1, 0, OPT_CODEC }, - { "play-dev-id", 1, 0, OPT_PLAY_DEV_ID }, - { NULL, 0, 0, 0} + { "srtp-crypto", 1, 0, 'c' }, + { "srtp-key", 1, 0, 'k' }, + { "src-ip", 1, 0, OPT_SRC_IP }, + { "dst-ip", 1, 0, OPT_DST_IP }, + { "src-port", 1, 0, OPT_SRC_PORT }, + { "dst-port", 1, 0, OPT_DST_PORT }, + { "codec", 1, 0, OPT_CODEC }, + { "play-dev-id", 1, 0, OPT_PLAY_DEV_ID }, + { NULL, 0, 0, 0} }; int c; int option_index; @@ -459,63 +458,63 @@ int main(int argc, char *argv[]) /* Parse arguments */ pj_optind = 0; while((c=pj_getopt_long(argc,argv, "c:k:", long_options, &option_index))!=-1) { - switch (c) { - case 'c': - srtp_crypto = pj_str(pj_optarg); - break; - case 'k': - { - int key_len = sizeof(key_bin); - srtp_key = pj_str(pj_optarg); - if (pj_base64_decode(&srtp_key, (pj_uint8_t*)key_bin, &key_len)) { - puts("Error: invalid key"); - return 1; - } - srtp_key.ptr = key_bin; - srtp_key.slen = key_len; - } - break; - case OPT_SRC_IP: - { - pj_str_t t = pj_str(pj_optarg); - pj_in_addr a = pj_inet_addr(&t); - filter.ip_src = a.s_addr; - } - break; - case OPT_DST_IP: - { - pj_str_t t = pj_str(pj_optarg); - pj_in_addr a = pj_inet_addr(&t); - filter.ip_dst = a.s_addr; - } - break; - case OPT_SRC_PORT: - filter.src_port = pj_htons((pj_uint16_t)atoi(pj_optarg)); - break; - case OPT_DST_PORT: - filter.dst_port = pj_htons((pj_uint16_t)atoi(pj_optarg)); - break; - case OPT_CODEC: - codec = pj_str(pj_optarg); - break; - case OPT_PLAY_DEV_ID: - dev_id = atoi(pj_optarg); - break; - default: - puts("Error: invalid option"); - return 1; - } + switch (c) { + case 'c': + srtp_crypto = pj_str(pj_optarg); + break; + case 'k': + { + int key_len = sizeof(key_bin); + srtp_key = pj_str(pj_optarg); + if (pj_base64_decode(&srtp_key, (pj_uint8_t*)key_bin, &key_len)) { + puts("Error: invalid key"); + return 1; + } + srtp_key.ptr = key_bin; + srtp_key.slen = key_len; + } + break; + case OPT_SRC_IP: + { + pj_str_t t = pj_str(pj_optarg); + pj_in_addr a = pj_inet_addr(&t); + filter.ip_src = a.s_addr; + } + break; + case OPT_DST_IP: + { + pj_str_t t = pj_str(pj_optarg); + pj_in_addr a = pj_inet_addr(&t); + filter.ip_dst = a.s_addr; + } + break; + case OPT_SRC_PORT: + filter.src_port = pj_htons((pj_uint16_t)atoi(pj_optarg)); + break; + case OPT_DST_PORT: + filter.dst_port = pj_htons((pj_uint16_t)atoi(pj_optarg)); + break; + case OPT_CODEC: + codec = pj_str(pj_optarg); + break; + case OPT_PLAY_DEV_ID: + dev_id = atoi(pj_optarg); + break; + default: + puts("Error: invalid option"); + return 1; + } } if (pj_optind != argc - 2) { - puts(USAGE); - return 1; + puts(USAGE); + return 1; } if (!(srtp_crypto.slen) != !(srtp_key.slen)) { - puts("Error: both SRTP crypto and key must be specified"); - puts(USAGE); - return 1; + puts("Error: both SRTP crypto and key must be specified"); + puts(USAGE); + return 1; } input = pj_str(argv[pj_optind]); diff --git a/pjsip-apps/src/samples/pjsip-perf.c b/pjsip-apps/src/samples/pjsip-perf.c index c957a152de..e13d593900 100644 --- a/pjsip-apps/src/samples/pjsip-perf.c +++ b/pjsip-apps/src/samples/pjsip-perf.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -71,9 +70,9 @@ # include #endif -#define THIS_FILE "pjsip-perf.c" -#define DEFAULT_COUNT (pjsip_cfg()->tsx.max_count/2>10000?10000:pjsip_cfg()->tsx.max_count/2) -#define JOB_WINDOW 1000 +#define THIS_FILE "pjsip-perf.c" +#define DEFAULT_COUNT (pjsip_cfg()->tsx.max_count/2>10000?10000:pjsip_cfg()->tsx.max_count/2) +#define JOB_WINDOW 1000 #define TERMINATE_TSX(x,c) @@ -112,58 +111,58 @@ static pj_str_t mime_sdp = {"sdp", 3}; struct srv_state { - unsigned stateless_cnt; - unsigned stateful_cnt; - unsigned call_cnt; + unsigned stateless_cnt; + unsigned stateful_cnt; + unsigned call_cnt; }; struct app { - pj_caching_pool cp; - pj_pool_t *pool; - pj_bool_t use_tcp; - pj_str_t local_addr; - int local_port; - pjsip_endpoint *sip_endpt; - pjmedia_endpt *med_endpt; - pj_str_t local_uri; - pj_str_t local_contact; - unsigned skinfo_cnt; - pjmedia_sock_info skinfo[8]; - - pj_bool_t thread_quit; - unsigned thread_count; - pj_thread_t *thread[16]; - - pj_bool_t real_sdp; + pj_caching_pool cp; + pj_pool_t *pool; + pj_bool_t use_tcp; + pj_str_t local_addr; + int local_port; + pjsip_endpoint *sip_endpt; + pjmedia_endpt *med_endpt; + pj_str_t local_uri; + pj_str_t local_contact; + unsigned skinfo_cnt; + pjmedia_sock_info skinfo[8]; + + pj_bool_t thread_quit; + unsigned thread_count; + pj_thread_t *thread[16]; + + pj_bool_t real_sdp; pjmedia_sdp_session *dummy_sdp; - int log_level; + int log_level; struct { - pjsip_method method; - pj_str_t dst_uri; - pj_bool_t stateless; - unsigned timeout; - unsigned job_count, - job_submitted, - job_finished, - job_window; - unsigned stat_max_window; - pj_time_val first_request; - pj_time_val requests_sent; - pj_time_val last_completion; - unsigned total_responses; - unsigned response_codes[800]; + pjsip_method method; + pj_str_t dst_uri; + pj_bool_t stateless; + unsigned timeout; + unsigned job_count, + job_submitted, + job_finished, + job_window; + unsigned stat_max_window; + pj_time_val first_request; + pj_time_val requests_sent; + pj_time_val last_completion; + unsigned total_responses; + unsigned response_codes[800]; } client; struct { - pj_bool_t send_trying; - pj_bool_t send_ringing; - unsigned delay; - struct srv_state prev_state; - struct srv_state cur_state; + pj_bool_t send_trying; + pj_bool_t send_ringing; + unsigned delay; + struct srv_state prev_state; + struct srv_state cur_state; } server; @@ -171,13 +170,13 @@ struct app struct call { - pjsip_inv_session *inv; - pj_timer_entry ans_timer; + pjsip_inv_session *inv; + pj_timer_entry ans_timer; }; static void app_perror(const char *sender, const char *title, - pj_status_t status) + pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; @@ -195,19 +194,19 @@ static pj_bool_t mod_stateless_on_rx_request(pjsip_rx_data *rdata); */ static pjsip_module mod_stateless_server = { - NULL, NULL, /* prev, next. */ - { "mod-stateless-server", 20 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &mod_stateless_on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-stateless-server", 20 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &mod_stateless_on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -221,13 +220,13 @@ static pj_bool_t mod_stateless_on_rx_request(pjsip_rx_data *rdata) /* Only want to receive SIP/SIPS scheme */ if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri)) - return PJ_FALSE; + return PJ_FALSE; sip_uri = (pjsip_sip_uri*) uri; /* Check for matching user part */ if (pj_strcmp(&sip_uri->user, &stateless_user)!=0) - return PJ_FALSE; + return PJ_FALSE; /* * Yes, this is for us. @@ -235,13 +234,13 @@ static pj_bool_t mod_stateless_on_rx_request(pjsip_rx_data *rdata) /* Ignore ACK request */ if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) - return PJ_TRUE; + return PJ_TRUE; /* * Respond statelessly with 200/OK. */ pjsip_endpt_respond_stateless(app.sip_endpt, rdata, 200, NULL, - NULL, NULL); + NULL, NULL); app.server.cur_state.stateless_cnt++; return PJ_TRUE; } @@ -256,19 +255,19 @@ static pj_bool_t mod_stateful_on_rx_request(pjsip_rx_data *rdata); */ static pjsip_module mod_stateful_server = { - NULL, NULL, /* prev, next. */ - { "mod-stateful-server", 19 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &mod_stateful_on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-stateful-server", 19 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &mod_stateful_on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -282,13 +281,13 @@ static pj_bool_t mod_stateful_on_rx_request(pjsip_rx_data *rdata) /* Only want to receive SIP/SIPS scheme */ if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri)) - return PJ_FALSE; + return PJ_FALSE; sip_uri = (pjsip_sip_uri*) uri; /* Check for matching user part */ if (pj_strcmp(&sip_uri->user, &stateful_user)!=0) - return PJ_FALSE; + return PJ_FALSE; /* * Yes, this is for us. @@ -296,25 +295,25 @@ static pj_bool_t mod_stateful_on_rx_request(pjsip_rx_data *rdata) */ switch (rdata->msg_info.msg->line.req.method.id) { case PJSIP_INVITE_METHOD: - { - pjsip_msg_body *body; - - if (dummy_sdp_str.slen == 0) - dummy_sdp_str.slen = pj_ansi_strlen(dummy_sdp_str.ptr); - - body = pjsip_msg_body_create(rdata->tp_info.pool, - &mime_application, &mime_sdp, - &dummy_sdp_str); - pjsip_endpt_respond(app.sip_endpt, &mod_stateful_server, rdata, - 200, NULL, NULL, body, NULL); - } - break; + { + pjsip_msg_body *body; + + if (dummy_sdp_str.slen == 0) + dummy_sdp_str.slen = pj_ansi_strlen(dummy_sdp_str.ptr); + + body = pjsip_msg_body_create(rdata->tp_info.pool, + &mime_application, &mime_sdp, + &dummy_sdp_str); + pjsip_endpt_respond(app.sip_endpt, &mod_stateful_server, rdata, + 200, NULL, NULL, body, NULL); + } + break; case PJSIP_ACK_METHOD: - return PJ_TRUE; + return PJ_TRUE; default: - pjsip_endpt_respond(app.sip_endpt, &mod_stateful_server, rdata, - 200, NULL, NULL, NULL, NULL); - break; + pjsip_endpt_respond(app.sip_endpt, &mod_stateful_server, rdata, + 200, NULL, NULL, NULL, NULL); + break; } app.server.cur_state.stateful_cnt++; @@ -331,62 +330,62 @@ static pj_bool_t mod_call_on_rx_request(pjsip_rx_data *rdata); */ static pjsip_module mod_call_server = { - NULL, NULL, /* prev, next. */ - { "mod-call-server", 15 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &mod_call_on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-call-server", 15 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &mod_call_on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; static pj_status_t send_response(pjsip_inv_session *inv, - pjsip_rx_data *rdata, - int code, - pj_bool_t *has_initial) + pjsip_rx_data *rdata, + int code, + pj_bool_t *has_initial) { pjsip_tx_data *tdata; pj_status_t status; if (*has_initial) { - status = pjsip_inv_answer(inv, code, NULL, NULL, &tdata); + status = pjsip_inv_answer(inv, code, NULL, NULL, &tdata); } else { - status = pjsip_inv_initial_answer(inv, rdata, code, - NULL, NULL, &tdata); + status = pjsip_inv_initial_answer(inv, rdata, code, + NULL, NULL, &tdata); } if (status != PJ_SUCCESS) { - if (*has_initial) { - status = pjsip_inv_answer(inv, PJSIP_SC_NOT_ACCEPTABLE, - NULL, NULL, &tdata); - } else { - status = pjsip_inv_initial_answer(inv, rdata, - PJSIP_SC_NOT_ACCEPTABLE, - NULL, NULL, &tdata); - } - - if (status == PJ_SUCCESS) { - *has_initial = PJ_TRUE; - pjsip_inv_send_msg(inv, tdata); - } else { - pjsip_inv_terminate(inv, 500, PJ_FALSE); - return -1; - } + if (*has_initial) { + status = pjsip_inv_answer(inv, PJSIP_SC_NOT_ACCEPTABLE, + NULL, NULL, &tdata); + } else { + status = pjsip_inv_initial_answer(inv, rdata, + PJSIP_SC_NOT_ACCEPTABLE, + NULL, NULL, &tdata); + } + + if (status == PJ_SUCCESS) { + *has_initial = PJ_TRUE; + pjsip_inv_send_msg(inv, tdata); + } else { + pjsip_inv_terminate(inv, 500, PJ_FALSE); + return -1; + } } else { - *has_initial = PJ_TRUE; + *has_initial = PJ_TRUE; - status = pjsip_inv_send_msg(inv, tdata); - if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - return status; - } + status = pjsip_inv_send_msg(inv, tdata); + if (status != PJ_SUCCESS) { + pjsip_tx_data_dec_ref(tdata); + return status; + } } return status; @@ -419,69 +418,69 @@ static pj_bool_t mod_call_on_rx_request(pjsip_rx_data *rdata) /* Only want to receive SIP/SIPS scheme */ if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri)) - return PJ_FALSE; + return PJ_FALSE; sip_uri = (pjsip_sip_uri*) uri; /* Only want to handle INVITE requests. */ if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD) { - return PJ_FALSE; + return PJ_FALSE; } /* Check for matching user part. Incoming requests will be handled * call-statefully if: - * - user part is "2", or + * - user part is "2", or * - user part is not "0" nor "1" and method is INVITE. */ if (pj_strcmp(&sip_uri->user, &call_user) == 0 || - sip_uri->user.slen != 1 || - (*sip_uri->user.ptr != '0' && *sip_uri->user.ptr != '1')) + sip_uri->user.slen != 1 || + (*sip_uri->user.ptr != '0' && *sip_uri->user.ptr != '1')) { - /* Match */ + /* Match */ } else { - return PJ_FALSE; + return PJ_FALSE; } /* Verify that we can handle the request. */ if (app.real_sdp) { - unsigned options = 0; - status = pjsip_inv_verify_request(rdata, &options, NULL, NULL, - app.sip_endpt, &tdata); - if (status != PJ_SUCCESS) { - - /* - * No we can't handle the incoming INVITE request. - */ - - if (tdata) { - pjsip_response_addr res_addr; - - pjsip_get_response_addr(tdata->pool, rdata, &res_addr); - status = pjsip_endpt_send_response(app.sip_endpt, &res_addr, tdata, - NULL, NULL); - if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(tdata); - } else { - /* Respond with 500 (Internal Server Error) */ - pjsip_endpt_respond_stateless(app.sip_endpt, rdata, 500, NULL, - NULL, NULL); - } - - return PJ_TRUE; - } + unsigned options = 0; + status = pjsip_inv_verify_request(rdata, &options, NULL, NULL, + app.sip_endpt, &tdata); + if (status != PJ_SUCCESS) { + + /* + * No we can't handle the incoming INVITE request. + */ + + if (tdata) { + pjsip_response_addr res_addr; + + pjsip_get_response_addr(tdata->pool, rdata, &res_addr); + status = pjsip_endpt_send_response(app.sip_endpt, &res_addr, tdata, + NULL, NULL); + if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(tdata); + } else { + /* Respond with 500 (Internal Server Error) */ + pjsip_endpt_respond_stateless(app.sip_endpt, rdata, 500, NULL, + NULL, NULL); + } + + return PJ_TRUE; + } } /* Create UAS dialog */ status = pjsip_dlg_create_uas_and_inc_lock( pjsip_ua_instance(), rdata, - &app.local_contact, &dlg); + &app.local_contact, &dlg); if (status != PJ_SUCCESS) { - const pj_str_t reason = pj_str("Unable to create dialog"); - pjsip_endpt_respond_stateless( app.sip_endpt, rdata, - 500, &reason, - NULL, NULL); - return PJ_TRUE; + const pj_str_t reason = pj_str("Unable to create dialog"); + pjsip_endpt_respond_stateless( app.sip_endpt, rdata, + 500, &reason, + NULL, NULL); + return PJ_TRUE; } /* Alloc call structure. */ @@ -489,20 +488,20 @@ static pj_bool_t mod_call_on_rx_request(pjsip_rx_data *rdata) /* Create SDP from PJMEDIA */ if (app.real_sdp) { - status = pjmedia_endpt_create_sdp(app.med_endpt, rdata->tp_info.pool, - app.skinfo_cnt, app.skinfo, - &sdp); + status = pjmedia_endpt_create_sdp(app.med_endpt, rdata->tp_info.pool, + app.skinfo_cnt, app.skinfo, + &sdp); } else { - sdp = app.dummy_sdp; + sdp = app.dummy_sdp; } /* Create UAS invite session */ status = pjsip_inv_create_uas( dlg, rdata, sdp, 0, &call->inv); if (status != PJ_SUCCESS) { - pjsip_dlg_create_response(dlg, rdata, 500, NULL, &tdata); - pjsip_dlg_send_response(dlg, pjsip_rdata_get_tsx(rdata), tdata); - pjsip_dlg_dec_lock(dlg); - return PJ_TRUE; + pjsip_dlg_create_response(dlg, rdata, 500, NULL, &tdata); + pjsip_dlg_send_response(dlg, pjsip_rdata_get_tsx(rdata), tdata); + pjsip_dlg_dec_lock(dlg); + return PJ_TRUE; } /* Invite session has been created, decrement & release dialog lock. */ @@ -510,36 +509,36 @@ static pj_bool_t mod_call_on_rx_request(pjsip_rx_data *rdata) /* Send 100/Trying if needed */ if (app.server.send_trying) { - status = send_response(call->inv, rdata, 100, &has_initial); - if (status != PJ_SUCCESS) - return PJ_TRUE; + status = send_response(call->inv, rdata, 100, &has_initial); + if (status != PJ_SUCCESS) + return PJ_TRUE; } /* Send 180/Ringing if needed */ if (app.server.send_ringing) { - status = send_response(call->inv, rdata, 180, &has_initial); - if (status != PJ_SUCCESS) - return PJ_TRUE; + status = send_response(call->inv, rdata, 180, &has_initial); + if (status != PJ_SUCCESS) + return PJ_TRUE; } /* Simulate call processing delay */ if (app.server.delay) { - pj_time_val delay; + pj_time_val delay; - call->ans_timer.id = 1; - call->ans_timer.user_data = call; - call->ans_timer.cb = &answer_timer_cb; - - delay.sec = 0; - delay.msec = app.server.delay; - pj_time_val_normalize(&delay); + call->ans_timer.id = 1; + call->ans_timer.user_data = call; + call->ans_timer.cb = &answer_timer_cb; + + delay.sec = 0; + delay.msec = app.server.delay; + pj_time_val_normalize(&delay); - pjsip_endpt_schedule_timer(app.sip_endpt, &call->ans_timer, &delay); + pjsip_endpt_schedule_timer(app.sip_endpt, &call->ans_timer, &delay); } else { - /* Send the 200 response immediately . */ - status = send_response(call->inv, rdata, 200, &has_initial); - PJ_ASSERT_ON_FAIL(status == PJ_SUCCESS, return PJ_TRUE); + /* Send the 200 response immediately . */ + status = send_response(call->inv, rdata, 200, &has_initial); + PJ_ASSERT_ON_FAIL(status == PJ_SUCCESS, return PJ_TRUE); } /* Done */ @@ -560,19 +559,19 @@ static pj_bool_t mod_responder_on_rx_request(pjsip_rx_data *rdata); */ static pjsip_module mod_responder = { - NULL, NULL, /* prev, next. */ - { "mod-responder", 13 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION+1, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &mod_responder_on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-responder", 13 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION+1, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &mod_responder_on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -584,8 +583,8 @@ static pj_bool_t mod_responder_on_rx_request(pjsip_rx_data *rdata) * Respond any requests (except ACK!) with 500. */ if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { - pjsip_endpt_respond_stateless(app.sip_endpt, rdata, 500, &reason, - NULL, NULL); + pjsip_endpt_respond_stateless(app.sip_endpt, rdata, 500, &reason, + NULL, NULL); } return PJ_TRUE; @@ -602,15 +601,15 @@ static pj_bool_t mod_responder_on_rx_request(pjsip_rx_data *rdata) static pj_bool_t logger_on_rx_msg(pjsip_rx_data *rdata) { PJ_LOG(3,(THIS_FILE, "RX %d bytes %s from %s %s:%d:\n" - "%.*s\n" - "--end msg--", - rdata->msg_info.len, - pjsip_rx_data_get_info(rdata), - rdata->tp_info.transport->type_name, - rdata->pkt_info.src_name, - rdata->pkt_info.src_port, - (int)rdata->msg_info.len, - rdata->msg_info.msg_buf)); + "%.*s\n" + "--end msg--", + rdata->msg_info.len, + pjsip_rx_data_get_info(rdata), + rdata->tp_info.transport->type_name, + rdata->pkt_info.src_name, + rdata->pkt_info.src_port, + (int)rdata->msg_info.len, + rdata->msg_info.msg_buf)); /* Always return false, otherwise messages will not get processed! */ return PJ_FALSE; @@ -621,21 +620,21 @@ static pj_status_t logger_on_tx_msg(pjsip_tx_data *tdata) { /* Important note: - * tp_info field is only valid after outgoing messages has passed - * transport layer. So don't try to access tp_info when the module - * has lower priority than transport layer. + * tp_info field is only valid after outgoing messages has passed + * transport layer. So don't try to access tp_info when the module + * has lower priority than transport layer. */ PJ_LOG(3,(THIS_FILE, "TX %d bytes %s to %s %s:%d:\n" - "%.*s\n" - "--end msg--", - (tdata->buf.cur - tdata->buf.start), - pjsip_tx_data_get_info(tdata), - tdata->tp_info.transport->type_name, - tdata->tp_info.dst_name, - tdata->tp_info.dst_port, - (int)(tdata->buf.cur - tdata->buf.start), - tdata->buf.start)); + "%.*s\n" + "--end msg--", + (tdata->buf.cur - tdata->buf.start), + pjsip_tx_data_get_info(tdata), + tdata->tp_info.transport->type_name, + tdata->tp_info.dst_name, + tdata->tp_info.dst_port, + (int)(tdata->buf.cur - tdata->buf.start), + tdata->buf.start)); /* Always return success, otherwise message will not get sent! */ return PJ_SUCCESS; @@ -644,19 +643,19 @@ static pj_status_t logger_on_tx_msg(pjsip_tx_data *tdata) /* The module instance. */ static pjsip_module msg_logger = { - NULL, NULL, /* prev, next. */ - { "mod-siprtp-log", 14 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &logger_on_rx_msg, /* on_rx_request() */ - &logger_on_rx_msg, /* on_rx_response() */ - &logger_on_tx_msg, /* on_tx_request. */ - &logger_on_tx_msg, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-siprtp-log", 14 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &logger_on_rx_msg, /* on_rx_request() */ + &logger_on_rx_msg, /* on_rx_response() */ + &logger_on_tx_msg, /* on_tx_request. */ + &logger_on_tx_msg, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -669,9 +668,9 @@ static pjsip_module msg_logger = static pj_bool_t mod_test_on_rx_response(pjsip_rx_data *rdata); static void call_on_media_update( pjsip_inv_session *inv, - pj_status_t status); + pj_status_t status); static void call_on_state_changed( pjsip_inv_session *inv, - pjsip_event *e); + pjsip_event *e); static void call_on_forked(pjsip_inv_session *inv, pjsip_event *e); @@ -679,19 +678,19 @@ static void call_on_forked(pjsip_inv_session *inv, pjsip_event *e); */ static pjsip_module mod_test = { - NULL, NULL, /* prev, next. */ - { "mod-test", 8 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - NULL, /* on_rx_request() */ - &mod_test_on_rx_response, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-test", 8 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + &mod_test_on_rx_response, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -699,7 +698,7 @@ static void report_completion(int status_code) { app.client.job_finished++; if (status_code >= 200 && status_code < 800) - app.client.response_codes[status_code]++; + app.client.response_codes[status_code]++; app.client.total_responses++; pj_gettimeofday(&app.client.last_completion); } @@ -709,7 +708,7 @@ static void report_completion(int status_code) static pj_bool_t mod_test_on_rx_response(pjsip_rx_data *rdata) { if (pjsip_rdata_get_tsx(rdata) == NULL) { - report_completion(rdata->msg_info.msg->line.status.code); + report_completion(rdata->msg_info.msg->line.status.code); } return PJ_TRUE; @@ -725,8 +724,8 @@ static pj_status_t create_app(void) status = pj_init(); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error initializing pjlib", status); - return status; + app_perror(THIS_FILE, "Error initializing pjlib", status); + return status; } /* init PJLIB-UTIL: */ @@ -735,14 +734,14 @@ static pj_status_t create_app(void) /* Must create a pool factory before we can allocate any memory. */ pj_caching_pool_init(&app.cp, &pj_pool_factory_default_policy, - CACHING_POOL_SIZE); + CACHING_POOL_SIZE); /* Create application pool for misc. */ app.pool = pj_pool_create(&app.cp.factory, "app", 1000, 1000, NULL); /* Create the endpoint: */ status = pjsip_endpt_create(&app.cp.factory, pj_gethostname()->ptr, - &app.sip_endpt); + &app.sip_endpt); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); @@ -759,64 +758,64 @@ static pj_status_t init_sip() /* Add UDP/TCP transport. */ { - pj_sockaddr_in addr; - pjsip_host_port addrname; - const char *transport_type = NULL; - - pj_bzero(&addr, sizeof(addr)); - addr.sin_family = pj_AF_INET(); - addr.sin_addr.s_addr = 0; - addr.sin_port = pj_htons((pj_uint16_t)app.local_port); - - if (app.local_addr.slen) { - addrname.host = app.local_addr; - addrname.port = 5060; - } - if (app.local_port != 0) - addrname.port = app.local_port; - - if (0) { + pj_sockaddr_in addr; + pjsip_host_port addrname; + const char *transport_type = NULL; + + pj_bzero(&addr, sizeof(addr)); + addr.sin_family = pj_AF_INET(); + addr.sin_addr.s_addr = 0; + addr.sin_port = pj_htons((pj_uint16_t)app.local_port); + + if (app.local_addr.slen) { + addrname.host = app.local_addr; + addrname.port = 5060; + } + if (app.local_port != 0) + addrname.port = app.local_port; + + if (0) { #if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0 - } else if (app.use_tcp) { - pj_sockaddr_in local_addr; - pjsip_tpfactory *tpfactory; - - transport_type = "tcp"; - pj_sockaddr_in_init(&local_addr, 0, (pj_uint16_t)app.local_port); - status = pjsip_tcp_transport_start(app.sip_endpt, &local_addr, - app.thread_count, &tpfactory); - if (status == PJ_SUCCESS) { - app.local_addr = tpfactory->addr_name.host; - app.local_port = tpfactory->addr_name.port; - } + } else if (app.use_tcp) { + pj_sockaddr_in local_addr; + pjsip_tpfactory *tpfactory; + + transport_type = "tcp"; + pj_sockaddr_in_init(&local_addr, 0, (pj_uint16_t)app.local_port); + status = pjsip_tcp_transport_start(app.sip_endpt, &local_addr, + app.thread_count, &tpfactory); + if (status == PJ_SUCCESS) { + app.local_addr = tpfactory->addr_name.host; + app.local_port = tpfactory->addr_name.port; + } #endif - } else { - pjsip_transport *tp; - - transport_type = "udp"; - status = pjsip_udp_transport_start(app.sip_endpt, &addr, - (app.local_addr.slen ? &addrname:NULL), - app.thread_count, &tp); - if (status == PJ_SUCCESS) { - app.local_addr = tp->local_name.host; - app.local_port = tp->local_name.port; - } - - } - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to start transport", status); - return status; - } - - app.local_uri.ptr = pj_pool_alloc(app.pool, 128); - app.local_uri.slen = pj_ansi_sprintf(app.local_uri.ptr, - "", - (int)app.local_addr.slen, - app.local_addr.ptr, - app.local_port, - transport_type); - - app.local_contact = app.local_uri; + } else { + pjsip_transport *tp; + + transport_type = "udp"; + status = pjsip_udp_transport_start(app.sip_endpt, &addr, + (app.local_addr.slen ? &addrname:NULL), + app.thread_count, &tp); + if (status == PJ_SUCCESS) { + app.local_addr = tp->local_name.host; + app.local_port = tp->local_name.port; + } + + } + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to start transport", status); + return status; + } + + app.local_uri.ptr = pj_pool_alloc(app.pool, 128); + app.local_uri.slen = pj_ansi_sprintf(app.local_uri.ptr, + "", + (int)app.local_addr.slen, + app.local_addr.ptr, + app.local_port, + transport_type); + + app.local_contact = app.local_uri; } /* @@ -836,17 +835,17 @@ static pj_status_t init_sip() /* Init invite session module. */ { - pjsip_inv_callback inv_cb; + pjsip_inv_callback inv_cb; - /* Init the callback for INVITE session: */ - pj_bzero(&inv_cb, sizeof(inv_cb)); - inv_cb.on_state_changed = &call_on_state_changed; - inv_cb.on_new_session = &call_on_forked; - inv_cb.on_media_update = &call_on_media_update; + /* Init the callback for INVITE session: */ + pj_bzero(&inv_cb, sizeof(inv_cb)); + inv_cb.on_state_changed = &call_on_state_changed; + inv_cb.on_new_session = &call_on_forked; + inv_cb.on_media_update = &call_on_media_update; - /* Initialize invite session module: */ - status = pjsip_inv_usage_init(app.sip_endpt, &inv_cb); - PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); + /* Initialize invite session module: */ + status = pjsip_inv_usage_init(app.sip_endpt, &inv_cb); + PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); } /* Register our module to receive incoming requests. */ @@ -886,24 +885,24 @@ static void destroy_app() app.thread_quit = 1; for (i=0; irtp_addr_name.ipv4, &app.local_addr, - (pj_uint16_t)rtp_port); - pj_sockaddr_in_init(&skinfo->rtp_addr_name.ipv4, &app.local_addr, - (pj_uint16_t)(rtp_port+1)); - app.skinfo_cnt++; + pjmedia_sock_info *skinfo; + + skinfo = &app.skinfo[i]; + + pj_sockaddr_in_init(&skinfo->rtp_addr_name.ipv4, &app.local_addr, + (pj_uint16_t)rtp_port); + pj_sockaddr_in_init(&skinfo->rtp_addr_name.ipv4, &app.local_addr, + (pj_uint16_t)(rtp_port+1)); + app.skinfo_cnt++; } /* Generate dummy SDP */ dummy_sdp_str.slen = pj_ansi_strlen(dummy_sdp_str.ptr); status = pjmedia_sdp_parse(app.pool, dummy_sdp_str.ptr, dummy_sdp_str.slen, - &app.dummy_sdp); + &app.dummy_sdp); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error parsing dummy SDP", status); - return status; + app_perror(THIS_FILE, "Error parsing dummy SDP", status); + return status; } @@ -966,16 +965,16 @@ static pj_status_t init_media() * status. This is called for client calls only. */ static void call_on_media_update( pjsip_inv_session *inv, - pj_status_t status) + pj_status_t status) { if (status != PJ_SUCCESS) { - pjsip_tx_data *tdata; - pj_status_t status2; + pjsip_tx_data *tdata; + pj_status_t status2; - status2 = pjsip_inv_end_session(inv, PJSIP_SC_UNSUPPORTED_MEDIA_TYPE, - NULL, &tdata); - if (status2 == PJ_SUCCESS && tdata) - status2 = pjsip_inv_send_msg(inv, tdata); + status2 = pjsip_inv_end_session(inv, PJSIP_SC_UNSUPPORTED_MEDIA_TYPE, + NULL, &tdata); + if (status2 == PJ_SUCCESS && tdata) + status2 = pjsip_inv_send_msg(inv, tdata); } } @@ -984,32 +983,32 @@ static void call_on_media_update( pjsip_inv_session *inv, * This is called for client calls only. */ static void call_on_state_changed( pjsip_inv_session *inv, - pjsip_event *e) + pjsip_event *e) { PJ_UNUSED_ARG(e); /* Bail out if the session has been counted before */ if (inv->mod_data[mod_test.id] != NULL) - return; + return; /* Bail out if this is not an outgoing call */ if (inv->role != PJSIP_UAC_ROLE) - return; + return; if (inv->state == PJSIP_INV_STATE_CONFIRMED) { - pjsip_tx_data *tdata; - pj_status_t status; + pjsip_tx_data *tdata; + pj_status_t status; - //report_completion(200); - //inv->mod_data[mod_test.id] = (void*)1; + //report_completion(200); + //inv->mod_data[mod_test.id] = (void*)1; - status = pjsip_inv_end_session(inv, PJSIP_SC_OK, NULL, &tdata); - if (status == PJ_SUCCESS && tdata) - status = pjsip_inv_send_msg(inv, tdata); + status = pjsip_inv_end_session(inv, PJSIP_SC_OK, NULL, &tdata); + if (status == PJ_SUCCESS && tdata) + status = pjsip_inv_send_msg(inv, tdata); } else if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { - report_completion(inv->cause); - inv->mod_data[mod_test.id] = (void*)(pj_ssize_t)1; + report_completion(inv->cause); + inv->mod_data[mod_test.id] = (void*)(pj_ssize_t)1; } } @@ -1037,13 +1036,13 @@ static pj_status_t make_call(const pj_str_t *dst_uri) /* Create UAC dialog */ status = pjsip_dlg_create_uac( pjsip_ua_instance(), - &app.local_uri, /* local URI */ - &app.local_contact, /* local Contact */ - dst_uri, /* remote URI */ - dst_uri, /* remote target */ - &dlg); /* dialog */ + &app.local_uri, /* local URI */ + &app.local_contact, /* local Contact */ + dst_uri, /* remote URI */ + dst_uri, /* remote target */ + &dlg); /* dialog */ if (status != PJ_SUCCESS) { - return status; + return status; } /* Create call */ @@ -1051,20 +1050,20 @@ static pj_status_t make_call(const pj_str_t *dst_uri) /* Create SDP */ if (app.real_sdp) { - status = pjmedia_endpt_create_sdp(app.med_endpt, dlg->pool, 1, - app.skinfo, &sdp); - if (status != PJ_SUCCESS) { - pjsip_dlg_terminate(dlg); - return status; - } + status = pjmedia_endpt_create_sdp(app.med_endpt, dlg->pool, 1, + app.skinfo, &sdp); + if (status != PJ_SUCCESS) { + pjsip_dlg_terminate(dlg); + return status; + } } else - sdp = app.dummy_sdp; + sdp = app.dummy_sdp; /* Create the INVITE session. */ status = pjsip_inv_create_uac( dlg, sdp, 0, &call->inv); if (status != PJ_SUCCESS) { - pjsip_dlg_terminate(dlg); - return status; + pjsip_dlg_terminate(dlg); + return status; } @@ -1109,7 +1108,7 @@ static pj_status_t verify_sip_url(const char *c_url) p = pjsip_parse_uri(pool, url, len, 0); if (!p || pj_stricmp2(pjsip_uri_get_scheme(p), "sip") != 0) - p = NULL; + p = NULL; pj_pool_release(pool); return p ? 0 : -1; @@ -1119,46 +1118,46 @@ static pj_status_t verify_sip_url(const char *c_url) static void usage(void) { printf( - "Usage:\n" - " pjsip-perf [OPTIONS] -- to start as server\n" - " pjsip-perf [OPTIONS] URL -- to call server (possibly itself)\n" - "\n" - "where:\n" - " URL The SIP URL to be contacted.\n" - "\n" - "Client options:\n" - " --method=METHOD, -m Set test method (set to INVITE for call benchmark)\n" + "Usage:\n" + " pjsip-perf [OPTIONS] -- to start as server\n" + " pjsip-perf [OPTIONS] URL -- to call server (possibly itself)\n" + "\n" + "where:\n" + " URL The SIP URL to be contacted.\n" + "\n" + "Client options:\n" + " --method=METHOD, -m Set test method (set to INVITE for call benchmark)\n" " [default: OPTIONS]\n" - " --count=N, -n Set total number of requests to initiate\n" - " [default=%d]\n" - " --stateless, -s Set to operate in stateless mode\n" - " [default: stateful]\n" - " --timeout=SEC, -t Set client timeout [default=60 sec]\n" - " --window=COUNT, -w Set maximum outstanding job [default: %d]\n" - "\n" - "SDP options (client and server):\n" - " --real-sdp Generate real SDP from pjmedia, and also perform\n" - " proper SDP negotiation [default: dummy]\n" - "\n" - "Client and Server options:\n" - " --local-port=PORT, -p Set local port [default: 5060]\n" - " --use-tcp, -T Use TCP instead of UDP. Note that when started as\n" - " client, you must add ;transport=tcp parameter to URL\n" - " [default: no]\n" - " --thread-count=N Set number of worker threads [default=1]\n" - " --trying Send 100/Trying response (server, default no)\n" - " --ringing Send 180/Ringing response (server, default no)\n" - " --delay=MS, -d Delay answering call by MS (server, default no)\n" - "\n" - "Misc options:\n" - " --help, -h Display this screen\n" - " --verbose, -v Verbose logging (put more than once for even more)\n" - "\n" - "When started as server, pjsip-perf can be contacted on the following URIs:\n" - " - sip:0@server-addr To handle requests statelessly.\n" - " - sip:1@server-addr To handle requests statefully.\n" - " - sip:2@server-addr To handle INVITE call.\n", - DEFAULT_COUNT, JOB_WINDOW); + " --count=N, -n Set total number of requests to initiate\n" + " [default=%d]\n" + " --stateless, -s Set to operate in stateless mode\n" + " [default: stateful]\n" + " --timeout=SEC, -t Set client timeout [default=60 sec]\n" + " --window=COUNT, -w Set maximum outstanding job [default: %d]\n" + "\n" + "SDP options (client and server):\n" + " --real-sdp Generate real SDP from pjmedia, and also perform\n" + " proper SDP negotiation [default: dummy]\n" + "\n" + "Client and Server options:\n" + " --local-port=PORT, -p Set local port [default: 5060]\n" + " --use-tcp, -T Use TCP instead of UDP. Note that when started as\n" + " client, you must add ;transport=tcp parameter to URL\n" + " [default: no]\n" + " --thread-count=N Set number of worker threads [default=1]\n" + " --trying Send 100/Trying response (server, default no)\n" + " --ringing Send 180/Ringing response (server, default no)\n" + " --delay=MS, -d Delay answering call by MS (server, default no)\n" + "\n" + "Misc options:\n" + " --help, -h Display this screen\n" + " --verbose, -v Verbose logging (put more than once for even more)\n" + "\n" + "When started as server, pjsip-perf can be contacted on the following URIs:\n" + " - sip:0@server-addr To handle requests statelessly.\n" + " - sip:1@server-addr To handle requests statefully.\n" + " - sip:2@server-addr To handle INVITE call.\n", + DEFAULT_COUNT, JOB_WINDOW); } @@ -1173,21 +1172,21 @@ static pj_status_t init_options(int argc, char *argv[]) { enum { OPT_THREAD_COUNT = 1, OPT_REAL_SDP, OPT_TRYING, OPT_RINGING }; struct pj_getopt_option long_options[] = { - { "local-port", 1, 0, 'p' }, - { "count", 1, 0, 'c' }, - { "thread-count", 1, 0, OPT_THREAD_COUNT }, - { "method", 1, 0, 'm' }, - { "help", 0, 0, 'h' }, - { "stateless", 0, 0, 's' }, - { "timeout", 1, 0, 't' }, - { "real-sdp", 0, 0, OPT_REAL_SDP }, - { "verbose", 0, 0, 'v' }, - { "use-tcp", 0, 0, 'T' }, - { "window", 1, 0, 'w' }, - { "delay", 1, 0, 'd' }, - { "trying", 0, 0, OPT_TRYING}, - { "ringing", 0, 0, OPT_RINGING}, - { NULL, 0, 0, 0 }, + { "local-port", 1, 0, 'p' }, + { "count", 1, 0, 'c' }, + { "thread-count", 1, 0, OPT_THREAD_COUNT }, + { "method", 1, 0, 'm' }, + { "help", 0, 0, 'h' }, + { "stateless", 0, 0, 's' }, + { "timeout", 1, 0, 't' }, + { "real-sdp", 0, 0, OPT_REAL_SDP }, + { "verbose", 0, 0, 'v' }, + { "use-tcp", 0, 0, 'T' }, + { "window", 1, 0, 'w' }, + { "delay", 1, 0, 'd' }, + { "trying", 0, 0, OPT_TRYING}, + { "ringing", 0, 0, OPT_RINGING}, + { NULL, 0, 0, 0 }, }; int c; int option_index; @@ -1205,116 +1204,116 @@ static pj_status_t init_options(int argc, char *argv[]) /* Parse options */ pj_optind = 0; while((c=pj_getopt_long(argc,argv, "p:c:m:t:w:d:hsv", - long_options, &option_index))!=-1) + long_options, &option_index))!=-1) { - switch (c) { - case 'p': - app.local_port = my_atoi(pj_optarg); - if (app.local_port < 0 || app.local_port > 65535) { - PJ_LOG(3,(THIS_FILE, "Invalid --local-port %s", pj_optarg)); - return -1; - } - break; - - case 'c': - app.client.job_count = my_atoi(pj_optarg); - if (app.client.job_count > pjsip_cfg()->tsx.max_count) - PJ_LOG(3,(THIS_FILE, - "Warning: --count value (%d) exceeds maximum " - "transaction count (%d)", app.client.job_count, - pjsip_cfg()->tsx.max_count)); - break; - - case OPT_THREAD_COUNT: - app.thread_count = my_atoi(pj_optarg); - if (app.thread_count < 1 || app.thread_count > 16) { - PJ_LOG(3,(THIS_FILE, "Invalid --thread-count %s", pj_optarg)); - return -1; - } - break; - - case 'm': - { - pj_str_t temp = pj_str((char*)pj_optarg); - pjsip_method_init_np(&app.client.method, &temp); - } - break; - - case 'h': - usage(); - return -1; - - case 's': - app.client.stateless = PJ_TRUE; - break; - - case OPT_REAL_SDP: - app.real_sdp = 1; - break; - - case 'v': - app.log_level++; - break; - - case 't': - app.client.timeout = my_atoi(pj_optarg); - if (app.client.timeout > 600) { - PJ_LOG(3,(THIS_FILE, "Invalid --timeout %s", pj_optarg)); - return -1; - } - break; - - case 'w': - app.client.job_window = my_atoi(pj_optarg); - if (app.client.job_window <= 0) { - PJ_LOG(3,(THIS_FILE, "Invalid --window %s", pj_optarg)); - return -1; - } - break; - - case 'T': - app.use_tcp = PJ_TRUE; - break; - - case 'd': - app.server.delay = my_atoi(pj_optarg); - if (app.server.delay > 3600) { - PJ_LOG(3,(THIS_FILE, "I think --delay %s is too long", - pj_optarg)); - return -1; - } - break; - - case OPT_TRYING: - app.server.send_trying = 1; - break; - - case OPT_RINGING: - app.server.send_ringing = 1; - break; - - default: - PJ_LOG(1,(THIS_FILE, - "Invalid argument. Use --help to see help")); - return -1; - } + switch (c) { + case 'p': + app.local_port = my_atoi(pj_optarg); + if (app.local_port < 0 || app.local_port > 65535) { + PJ_LOG(3,(THIS_FILE, "Invalid --local-port %s", pj_optarg)); + return -1; + } + break; + + case 'c': + app.client.job_count = my_atoi(pj_optarg); + if (app.client.job_count > pjsip_cfg()->tsx.max_count) + PJ_LOG(3,(THIS_FILE, + "Warning: --count value (%d) exceeds maximum " + "transaction count (%d)", app.client.job_count, + pjsip_cfg()->tsx.max_count)); + break; + + case OPT_THREAD_COUNT: + app.thread_count = my_atoi(pj_optarg); + if (app.thread_count < 1 || app.thread_count > 16) { + PJ_LOG(3,(THIS_FILE, "Invalid --thread-count %s", pj_optarg)); + return -1; + } + break; + + case 'm': + { + pj_str_t temp = pj_str((char*)pj_optarg); + pjsip_method_init_np(&app.client.method, &temp); + } + break; + + case 'h': + usage(); + return -1; + + case 's': + app.client.stateless = PJ_TRUE; + break; + + case OPT_REAL_SDP: + app.real_sdp = 1; + break; + + case 'v': + app.log_level++; + break; + + case 't': + app.client.timeout = my_atoi(pj_optarg); + if (app.client.timeout > 600) { + PJ_LOG(3,(THIS_FILE, "Invalid --timeout %s", pj_optarg)); + return -1; + } + break; + + case 'w': + app.client.job_window = my_atoi(pj_optarg); + if (app.client.job_window <= 0) { + PJ_LOG(3,(THIS_FILE, "Invalid --window %s", pj_optarg)); + return -1; + } + break; + + case 'T': + app.use_tcp = PJ_TRUE; + break; + + case 'd': + app.server.delay = my_atoi(pj_optarg); + if (app.server.delay > 3600) { + PJ_LOG(3,(THIS_FILE, "I think --delay %s is too long", + pj_optarg)); + return -1; + } + break; + + case OPT_TRYING: + app.server.send_trying = 1; + break; + + case OPT_RINGING: + app.server.send_ringing = 1; + break; + + default: + PJ_LOG(1,(THIS_FILE, + "Invalid argument. Use --help to see help")); + return -1; + } } if (pj_optind != argc) { - if (verify_sip_url(argv[pj_optind]) != PJ_SUCCESS) { - PJ_LOG(1,(THIS_FILE, "Invalid SIP URI %s", argv[pj_optind])); - return -1; - } - app.client.dst_uri = pj_str(argv[pj_optind]); - - pj_optind++; + if (verify_sip_url(argv[pj_optind]) != PJ_SUCCESS) { + PJ_LOG(1,(THIS_FILE, "Invalid SIP URI %s", argv[pj_optind])); + return -1; + } + app.client.dst_uri = pj_str(argv[pj_optind]); + + pj_optind++; } if (pj_optind != argc) { - PJ_LOG(1,(THIS_FILE, "Error: unknown options %s", argv[pj_optind])); - return -1; + PJ_LOG(1,(THIS_FILE, "Error: unknown options %s", argv[pj_optind])); + return -1; } return 0; @@ -1328,22 +1327,22 @@ static pj_status_t submit_stateless_job(void) pj_status_t status; status = pjsip_endpt_create_request(app.sip_endpt, &app.client.method, - &app.client.dst_uri, &app.local_uri, - &app.client.dst_uri, &app.local_contact, - NULL, -1, NULL, &tdata); + &app.client.dst_uri, &app.local_uri, + &app.client.dst_uri, &app.local_contact, + NULL, -1, NULL, &tdata); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error creating request", status); - report_completion(701); - return status; + app_perror(THIS_FILE, "Error creating request", status); + report_completion(701); + return status; } status = pjsip_endpt_send_request_stateless(app.sip_endpt, tdata, NULL, - NULL); + NULL); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - app_perror(THIS_FILE, "Error sending stateless request", status); - report_completion(701); - return status; + pjsip_tx_data_dec_ref(tdata); + app_perror(THIS_FILE, "Error sending stateless request", status); + report_completion(701); + return status; } return PJ_SUCCESS; @@ -1358,31 +1357,31 @@ static void tsx_completion_cb(void *token, pjsip_event *event) PJ_UNUSED_ARG(token); if (event->type != PJSIP_EVENT_TSX_STATE) - return; + return; tsx = event->body.tsx_state.tsx; if (tsx->mod_data[mod_test.id] != NULL) { - /* This transaction has been calculated before */ - return; + /* This transaction has been calculated before */ + return; } if (tsx->state==PJSIP_TSX_STATE_TERMINATED) { - report_completion(tsx->status_code); - tsx->mod_data[mod_test.id] = (void*)(pj_ssize_t)1; + report_completion(tsx->status_code); + tsx->mod_data[mod_test.id] = (void*)(pj_ssize_t)1; } else if (tsx->method.id == PJSIP_INVITE_METHOD && - tsx->state == PJSIP_TSX_STATE_CONFIRMED) { + tsx->state == PJSIP_TSX_STATE_CONFIRMED) { - report_completion(tsx->status_code); - tsx->mod_data[mod_test.id] = (void*)(pj_ssize_t)1; - + report_completion(tsx->status_code); + tsx->mod_data[mod_test.id] = (void*)(pj_ssize_t)1; + } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { - report_completion(tsx->status_code); - tsx->mod_data[mod_test.id] = (void*)(pj_ssize_t)1; + report_completion(tsx->status_code); + tsx->mod_data[mod_test.id] = (void*)(pj_ssize_t)1; - TERMINATE_TSX(tsx, tsx->status_code); + TERMINATE_TSX(tsx, tsx->status_code); } } @@ -1394,23 +1393,23 @@ static pj_status_t submit_job(void) pj_status_t status; status = pjsip_endpt_create_request(app.sip_endpt, &app.client.method, - &app.client.dst_uri, &app.local_uri, - &app.client.dst_uri, &app.local_contact, - NULL, -1, NULL, &tdata); + &app.client.dst_uri, &app.local_uri, + &app.client.dst_uri, &app.local_contact, + NULL, -1, NULL, &tdata); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error creating request", status); - report_completion(701); - return status; + app_perror(THIS_FILE, "Error creating request", status); + report_completion(701); + return status; } status = pjsip_endpt_send_request(app.sip_endpt, tdata, -1, NULL, - &tsx_completion_cb); + &tsx_completion_cb); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error sending stateful request", status); - //should have been reported by tsx_completion_cb(). - //report_completion(701); - //No longer necessary (r777) - //pjsip_tx_data_dec_ref(tdata); + app_perror(THIS_FILE, "Error sending stateful request", status); + //should have been reported by tsx_completion_cb(). + //report_completion(701); + //No longer necessary (r777) + //pjsip_tx_data_dec_ref(tdata); } return status; } @@ -1431,106 +1430,106 @@ static int client_thread(void *arg) pj_gettimeofday(&last_report); if (app.client.first_request.sec == 0) { - pj_gettimeofday(&app.client.first_request); + pj_gettimeofday(&app.client.first_request); } /* Submit all jobs */ while (app.client.job_submitted < app.client.job_count && !app.thread_quit){ - pj_time_val timeout = { 0, 1 }; - unsigned i; - int outstanding; - pj_status_t status; - - /* Calculate current outstanding job */ - outstanding = app.client.job_submitted - app.client.job_finished; - - /* Update stats on max outstanding jobs */ - if (outstanding > (int)app.client.stat_max_window) - app.client.stat_max_window = outstanding; - - /* Wait if there are more pending jobs than allowed in the - * window. But spawn a new job anyway if no events are happening - * after we wait for some time. - */ - for (i=0; outstanding > (int)app.client.job_window && i<1000; ++i) { - pj_time_val wait = { 0, 500 }; - unsigned count = 0; - - pjsip_endpt_handle_events2(app.sip_endpt, &wait, &count); - outstanding = app.client.job_submitted - app.client.job_finished; - - if (count == 0) - break; - - ++cycle; - } - - - /* Submit one job */ - if (app.client.method.id == PJSIP_INVITE_METHOD) { - status = make_call(&app.client.dst_uri); - } else if (app.client.stateless) { - status = submit_stateless_job(); - } else { - status = submit_job(); - } - PJ_UNUSED_ARG(status); - - ++app.client.job_submitted; - ++cycle; - - /* Handle event */ - pjsip_endpt_handle_events2(app.sip_endpt, &timeout, NULL); - - /* Check for time out, also print report */ - if (cycle - last_cycle >= 500) { - pj_gettimeofday(&now); - if (PJ_TIME_VAL_GTE(now, end_time)) { - break; - } - last_cycle = cycle; - - - if (thread_index == 0 && now.sec-last_report.sec >= 2) { - printf("\r%d jobs started, %d completed... ", - app.client.job_submitted, app.client.job_finished); - fflush(stdout); - last_report = now; - } - } + pj_time_val timeout = { 0, 1 }; + unsigned i; + int outstanding; + pj_status_t status; + + /* Calculate current outstanding job */ + outstanding = app.client.job_submitted - app.client.job_finished; + + /* Update stats on max outstanding jobs */ + if (outstanding > (int)app.client.stat_max_window) + app.client.stat_max_window = outstanding; + + /* Wait if there are more pending jobs than allowed in the + * window. But spawn a new job anyway if no events are happening + * after we wait for some time. + */ + for (i=0; outstanding > (int)app.client.job_window && i<1000; ++i) { + pj_time_val wait = { 0, 500 }; + unsigned count = 0; + + pjsip_endpt_handle_events2(app.sip_endpt, &wait, &count); + outstanding = app.client.job_submitted - app.client.job_finished; + + if (count == 0) + break; + + ++cycle; + } + + + /* Submit one job */ + if (app.client.method.id == PJSIP_INVITE_METHOD) { + status = make_call(&app.client.dst_uri); + } else if (app.client.stateless) { + status = submit_stateless_job(); + } else { + status = submit_job(); + } + PJ_UNUSED_ARG(status); + + ++app.client.job_submitted; + ++cycle; + + /* Handle event */ + pjsip_endpt_handle_events2(app.sip_endpt, &timeout, NULL); + + /* Check for time out, also print report */ + if (cycle - last_cycle >= 500) { + pj_gettimeofday(&now); + if (PJ_TIME_VAL_GTE(now, end_time)) { + break; + } + last_cycle = cycle; + + + if (thread_index == 0 && now.sec-last_report.sec >= 2) { + printf("\r%d jobs started, %d completed... ", + app.client.job_submitted, app.client.job_finished); + fflush(stdout); + last_report = now; + } + } } if (app.client.requests_sent.sec == 0) { - pj_gettimeofday(&app.client.requests_sent); + pj_gettimeofday(&app.client.requests_sent); } if (thread_index == 0) { - printf("\r%d jobs started, %d completed%s\n", - app.client.job_submitted, app.client.job_finished, - (app.client.job_submitted!=app.client.job_finished ? - ", waiting..." : ".") ); - fflush(stdout); + printf("\r%d jobs started, %d completed%s\n", + app.client.job_submitted, app.client.job_finished, + (app.client.job_submitted!=app.client.job_finished ? + ", waiting..." : ".") ); + fflush(stdout); } /* Wait until all jobs completes, or timed out */ pj_gettimeofday(&now); while (PJ_TIME_VAL_LT(now, end_time) && - app.client.job_finished < app.client.job_count && - !app.thread_quit) + app.client.job_finished < app.client.job_count && + !app.thread_quit) { - pj_time_val timeout = { 0, 1 }; - unsigned i; - - for (i=0; i<1000; ++i) { - unsigned count; - count = 0; - pjsip_endpt_handle_events2(app.sip_endpt, &timeout, &count); - if (count == 0) - break; - } - - pj_gettimeofday(&now); + pj_time_val timeout = { 0, 1 }; + unsigned i; + + for (i=0; i<1000; ++i) { + unsigned count; + count = 0; + pjsip_endpt_handle_events2(app.sip_endpt, &timeout, &count); + if (count == 0) + break; + } + + pj_gettimeofday(&now); } /* Wait couple of seconds to let jobs completes (e.g. ACKs to be sent) */ @@ -1539,18 +1538,18 @@ static int client_thread(void *arg) end_time.sec += 2; while (PJ_TIME_VAL_LT(now, end_time)) { - pj_time_val timeout = { 0, 1 }; - unsigned i; - - for (i=0; i<1000; ++i) { - unsigned count; - count = 0; - pjsip_endpt_handle_events2(app.sip_endpt, &timeout, &count); - if (count == 0) - break; - } - - pj_gettimeofday(&now); + pj_time_val timeout = { 0, 1 }; + unsigned i; + + for (i=0; i<1000; ++i) { + unsigned count; + count = 0; + pjsip_endpt_handle_events2(app.sip_endpt, &timeout, &count); + if (count == 0) + break; + } + + pj_gettimeofday(&now); } return 0; @@ -1560,15 +1559,15 @@ static int client_thread(void *arg) static const char *good_number(char *buf, pj_int32_t val) { if (val < 1000) { - pj_ansi_sprintf(buf, "%d", val); + pj_ansi_sprintf(buf, "%d", val); } else if (val < 1000000) { - pj_ansi_sprintf(buf, "%d.%dK", - val / 1000, - (val % 1000) / 100); + pj_ansi_sprintf(buf, "%d.%dK", + val / 1000, + (val % 1000) / 100); } else { - pj_ansi_sprintf(buf, "%d.%02dM", - val / 1000000, - (val % 1000000) / 10000); + pj_ansi_sprintf(buf, "%d.%02dM", + val / 1000000, + (val % 1000000) / 10000); } return buf; @@ -1586,50 +1585,50 @@ static int server_thread(void *arg) next_report.sec++; while (!app.thread_quit) { - pj_time_val now; - unsigned i; - - for (i=0; i<100; ++i) { - unsigned count = 0; - pjsip_endpt_handle_events2(app.sip_endpt, &timeout, &count); - if (count == 0) - break; - } - - if (thread_index == 0) { - pj_gettimeofday(&now); - - if (PJ_TIME_VAL_GTE(now, next_report)) { - pj_time_val tmp; - unsigned msec; - unsigned stateless, stateful, call; - char str_stateless[32], str_stateful[32], str_call[32]; - - tmp = now; - PJ_TIME_VAL_SUB(tmp, last_report); - msec = PJ_TIME_VAL_MSEC(tmp); - - last_report = now; - next_report = last_report; - next_report.sec++; - - stateless = app.server.cur_state.stateless_cnt - app.server.prev_state.stateless_cnt; - stateful = app.server.cur_state.stateful_cnt - app.server.prev_state.stateful_cnt; - call = app.server.cur_state.call_cnt - app.server.prev_state.call_cnt; - - good_number(str_stateless, app.server.cur_state.stateless_cnt); - good_number(str_stateful, app.server.cur_state.stateful_cnt); - good_number(str_call, app.server.cur_state.call_cnt); - - printf("Total(rate): stateless:%s (%d/s), statefull:%s (%d/s), call:%s (%d/s) \r", - str_stateless, stateless*1000/msec, - str_stateful, stateful*1000/msec, - str_call, call*1000/msec); - fflush(stdout); - - app.server.prev_state = app.server.cur_state; - } - } + pj_time_val now; + unsigned i; + + for (i=0; i<100; ++i) { + unsigned count = 0; + pjsip_endpt_handle_events2(app.sip_endpt, &timeout, &count); + if (count == 0) + break; + } + + if (thread_index == 0) { + pj_gettimeofday(&now); + + if (PJ_TIME_VAL_GTE(now, next_report)) { + pj_time_val tmp; + unsigned msec; + unsigned stateless, stateful, call; + char str_stateless[32], str_stateful[32], str_call[32]; + + tmp = now; + PJ_TIME_VAL_SUB(tmp, last_report); + msec = PJ_TIME_VAL_MSEC(tmp); + + last_report = now; + next_report = last_report; + next_report.sec++; + + stateless = app.server.cur_state.stateless_cnt - app.server.prev_state.stateless_cnt; + stateful = app.server.cur_state.stateful_cnt - app.server.prev_state.stateful_cnt; + call = app.server.cur_state.call_cnt - app.server.prev_state.call_cnt; + + good_number(str_stateless, app.server.cur_state.stateless_cnt); + good_number(str_stateful, app.server.cur_state.stateful_cnt); + good_number(str_call, app.server.cur_state.call_cnt); + + printf("Total(rate): stateless:%s (%d/s), statefull:%s (%d/s), call:%s (%d/s) \r", + str_stateless, stateless*1000/msec, + str_stateful, stateful*1000/msec, + str_call, call*1000/msec); + fflush(stdout); + + app.server.prev_state = app.server.cur_state; + } + } } return 0; @@ -1652,199 +1651,199 @@ int main(int argc, char *argv[]) printf("PJSIP Performance Measurement Tool v%s\n" "(c)2006 pjsip.org\n\n", - PJ_VERSION); + PJ_VERSION); if (create_app() != 0) - return 1; + return 1; if (init_options(argc, argv) != 0) - return 1; + return 1; if (init_sip() != 0) - return 1; + return 1; if (init_media() != 0) - return 1; + return 1; pj_log_set_level(app.log_level); if (app.log_level > 4) { - pjsip_endpt_register_module(app.sip_endpt, &msg_logger); + pjsip_endpt_register_module(app.sip_endpt, &msg_logger); } /* Misc infos */ if (app.client.dst_uri.slen != 0) { - if (app.client.method.id == PJSIP_INVITE_METHOD) { - if (app.client.stateless) { - PJ_LOG(3,(THIS_FILE, - "Info: --stateless option makes no sense for INVITE," - " ignored.")); - } - } + if (app.client.method.id == PJSIP_INVITE_METHOD) { + if (app.client.stateless) { + PJ_LOG(3,(THIS_FILE, + "Info: --stateless option makes no sense for INVITE," + " ignored.")); + } + } } if (app.client.dst_uri.slen) { - /* Client mode */ - pj_status_t status; - char test_type[64]; - unsigned msec_req, msec_res; - unsigned i; - - /* Get the job name */ - if (app.client.method.id == PJSIP_INVITE_METHOD) { - pj_ansi_strcpy(test_type, "INVITE calls"); - } else if (app.client.stateless) { - pj_ansi_sprintf(test_type, "stateless %.*s requests", - (int)app.client.method.name.slen, - app.client.method.name.ptr); - } else { - pj_ansi_sprintf(test_type, "stateful %.*s requests", - (int)app.client.method.name.slen, - app.client.method.name.ptr); - } - - - printf("Sending %d %s to '%.*s' with %d maximum outstanding jobs, please wait..\n", - app.client.job_count, test_type, - (int)app.client.dst_uri.slen, app.client.dst_uri.ptr, - app.client.job_window); - - for (i=0; islen, reason->ptr); - write_report(report); - } - - /* Total responses and rate */ - pj_ansi_snprintf( report, sizeof(report), - " ------\n" - " TOTAL responses: %7d (rate=%d/sec)\n", - app.client.total_responses, - app.client.total_responses*1000/msec_res); - - write_report(report); - - pj_ansi_sprintf(report, "Maximum outstanding job: %d", - app.client.stat_max_window); - write_report(report); + /* Client mode */ + pj_status_t status; + char test_type[64]; + unsigned msec_req, msec_res; + unsigned i; + + /* Get the job name */ + if (app.client.method.id == PJSIP_INVITE_METHOD) { + pj_ansi_strcpy(test_type, "INVITE calls"); + } else if (app.client.stateless) { + pj_ansi_sprintf(test_type, "stateless %.*s requests", + (int)app.client.method.name.slen, + app.client.method.name.ptr); + } else { + pj_ansi_sprintf(test_type, "stateful %.*s requests", + (int)app.client.method.name.slen, + app.client.method.name.ptr); + } + + + printf("Sending %d %s to '%.*s' with %d maximum outstanding jobs, please wait..\n", + app.client.job_count, test_type, + (int)app.client.dst_uri.slen, app.client.dst_uri.ptr, + app.client.job_window); + + for (i=0; islen, reason->ptr); + write_report(report); + } + + /* Total responses and rate */ + pj_ansi_snprintf( report, sizeof(report), + " ------\n" + " TOTAL responses: %7d (rate=%d/sec)\n", + app.client.total_responses, + app.client.total_responses*1000/msec_res); + + write_report(report); + + pj_ansi_sprintf(report, "Maximum outstanding job: %d", + app.client.stat_max_window); + write_report(report); } else { - /* Server mode */ - char s[10], *unused; - pj_status_t status; - unsigned i; - - puts("pjsip-perf started in server-mode"); - - printf("Receiving requests on the following URIs:\n" - " sip:0@%.*s:%d%s for stateless handling\n" - " sip:1@%.*s:%d%s for stateful handling\n" - " sip:2@%.*s:%d%s for call handling\n", - (int)app.local_addr.slen, - app.local_addr.ptr, - app.local_port, - (app.use_tcp ? ";transport=tcp" : ""), - (int)app.local_addr.slen, - app.local_addr.ptr, - app.local_port, - (app.use_tcp ? ";transport=tcp" : ""), - (int)app.local_addr.slen, - app.local_addr.ptr, - app.local_port, - (app.use_tcp ? ";transport=tcp" : "")); - printf("INVITE with non-matching user part will be handled call-statefully\n"); - - for (i=0; i to quit\n"); - fflush(stdout); - unused = fgets(s, sizeof(s), stdin); - PJ_UNUSED_ARG(unused); - - app.thread_quit = PJ_TRUE; - for (i=0; i to quit\n"); + fflush(stdout); + unused = fgets(s, sizeof(s), stdin); + PJ_UNUSED_ARG(unused); + + app.thread_quit = PJ_TRUE; + for (i=0; i #include -#define THIS_FILE "pjsua2_demo.cpp" +#define THIS_FILE "pjsua2_demo.cpp" using namespace pj; @@ -60,14 +59,14 @@ class MyCall : public Call MyCall(Account &acc, int call_id = PJSUA_INVALID_ID) : Call(acc, call_id) { - wav_player = NULL; + wav_player = NULL; myAcc = (MyAccount *)&acc; } ~MyCall() { - if (wav_player) - delete wav_player; + if (wav_player) + delete wav_player; } virtual void onCallState(OnCallStateParam &prm); @@ -90,11 +89,11 @@ class MyAccount : public Account std::cout << "*** Account is being deleted: No of calls=" << calls.size() << std::endl; - for (std::vector::iterator it = calls.begin(); + for (std::vector::iterator it = calls.begin(); it != calls.end(); ) { - delete (*it); - it = calls.erase(it); + delete (*it); + it = calls.erase(it); } } @@ -112,9 +111,9 @@ class MyAccount : public Account virtual void onRegState(OnRegStateParam &prm) { - AccountInfo ai = getInfo(); - std::cout << (ai.regIsActive? "*** Register: code=" : "*** Unregister: code=") - << prm.code << std::endl; + AccountInfo ai = getInfo(); + std::cout << (ai.regIsActive? "*** Register: code=" : "*** Unregister: code=") + << prm.code << std::endl; } virtual void onIncomingCall(OnIncomingCallParam &iprm) @@ -154,31 +153,31 @@ void MyCall::onCallMediaState(OnCallMediaStateParam &prm) CallInfo ci = getInfo(); AudioMedia aud_med; AudioMedia& play_dev_med = - MyEndpoint::instance().audDevManager().getPlaybackDevMedia(); + MyEndpoint::instance().audDevManager().getPlaybackDevMedia(); try { - // Get the first audio media - aud_med = getAudioMedia(-1); + // Get the first audio media + aud_med = getAudioMedia(-1); } catch(...) { - std::cout << "Failed to get audio media" << std::endl; - return; + std::cout << "Failed to get audio media" << std::endl; + return; } if (!wav_player) { - wav_player = new AudioMediaPlayer(); - try { - wav_player->createPlayer( - "../../../../tests/pjsua/wavs/input.16.wav", 0); - } catch (...) { - std::cout << "Failed opening wav file" << std::endl; - delete wav_player; - wav_player = NULL; - } + wav_player = new AudioMediaPlayer(); + try { + wav_player->createPlayer( + "../../../../tests/pjsua/wavs/input.16.wav", 0); + } catch (...) { + std::cout << "Failed opening wav file" << std::endl; + delete wav_player; + wav_player = NULL; + } } // This will connect the wav file to the call audio media if (wav_player) - wav_player->startTransmit(aud_med); + wav_player->startTransmit(aud_med); // And this will connect the call audio media to the sound device/speaker aud_med.startTransmit(play_dev_med); @@ -229,9 +228,9 @@ static void mainProg1(MyEndpoint &ep) acc_cfg.sipConfig.authCreds.push_back(aci); MyAccount *acc(new MyAccount); try { - acc->create(acc_cfg); + acc->create(acc_cfg); } catch (...) { - std::cout << "Adding account failed" << std::endl; + std::cout << "Adding account failed" << std::endl; } pj_thread_sleep(2000); @@ -261,44 +260,44 @@ static void mainProg2() { string json_str; { - EpConfig epCfg; - JsonDocument jDoc; - - epCfg.uaConfig.maxCalls = 61; - epCfg.uaConfig.userAgent = "Just JSON Test"; - epCfg.uaConfig.stunServer.push_back("stun1.pjsip.org"); - epCfg.uaConfig.stunServer.push_back("stun2.pjsip.org"); - epCfg.logConfig.filename = "THE.LOG"; - - jDoc.writeObject(epCfg); - json_str = jDoc.saveString(); - std::cout << json_str << std::endl << std::endl; + EpConfig epCfg; + JsonDocument jDoc; + + epCfg.uaConfig.maxCalls = 61; + epCfg.uaConfig.userAgent = "Just JSON Test"; + epCfg.uaConfig.stunServer.push_back("stun1.pjsip.org"); + epCfg.uaConfig.stunServer.push_back("stun2.pjsip.org"); + epCfg.logConfig.filename = "THE.LOG"; + + jDoc.writeObject(epCfg); + json_str = jDoc.saveString(); + std::cout << json_str << std::endl << std::endl; } { - EpConfig epCfg; - JsonDocument rDoc; - string output; + EpConfig epCfg; + JsonDocument rDoc; + string output; - rDoc.loadString(json_str); - rDoc.readObject(epCfg); + rDoc.loadString(json_str); + rDoc.readObject(epCfg); - JsonDocument wDoc; + JsonDocument wDoc; - wDoc.writeObject(epCfg); - json_str = wDoc.saveString(); - std::cout << json_str << std::endl << std::endl; + wDoc.writeObject(epCfg); + json_str = wDoc.saveString(); + std::cout << json_str << std::endl << std::endl; - wDoc.saveFile("jsontest.js"); + wDoc.saveFile("jsontest.js"); } { - EpConfig epCfg; - JsonDocument rDoc; + EpConfig epCfg; + JsonDocument rDoc; - rDoc.loadFile("jsontest.js"); - rDoc.readObject(epCfg); - pj_file_delete("jsontest.js"); + rDoc.loadFile("jsontest.js"); + rDoc.readObject(epCfg); + pj_file_delete("jsontest.js"); } } #endif @@ -308,8 +307,8 @@ static void mainProg2() static void mainProg3(MyEndpoint &ep) { const char *paths[] = { "../../../../tests/pjsua/wavs/input.16.wav", - "../../tests/pjsua/wavs/input.16.wav", - "input.16.wav"}; + "../../tests/pjsua/wavs/input.16.wav", + "input.16.wav"}; unsigned i; const char *filename = NULL; @@ -325,8 +324,8 @@ static void mainProg3(MyEndpoint &ep) } if (!filename) { - PJSUA2_RAISE_ERROR3(PJ_ENOTFOUND, "mainProg3()", - "Could not locate input.16.wav"); + PJSUA2_RAISE_ERROR3(PJ_ENOTFOUND, "mainProg3()", + "Could not locate input.16.wav"); } // Start library @@ -342,24 +341,24 @@ static void mainProg3(MyEndpoint &ep) /* And install sound device using Extra Audio Device */ ExtraAudioDevice auddev2(-1, -1); try { - auddev2.open(); + auddev2.open(); } catch (...) { - std::cout << "Extra sound device failed" << std::endl; + std::cout << "Extra sound device failed" << std::endl; } // Create player and recorder { - AudioMediaPlayer amp; - amp.createPlayer(filename); + AudioMediaPlayer amp; + amp.createPlayer(filename); - AudioMediaRecorder amr; - amr.createRecorder("recorder_test_output.wav"); + AudioMediaRecorder amr; + amr.createRecorder("recorder_test_output.wav"); - amp.startTransmit(amr); - if (auddev2.isOpened()) - amp.startTransmit(auddev2); + amp.startTransmit(amr); + if (auddev2.isOpened()) + amp.startTransmit(auddev2); - pj_thread_sleep(5000); + pj_thread_sleep(5000); } } #endif @@ -371,54 +370,54 @@ static void mainProg(MyEndpoint &) string json_str; { - JsonDocument jdoc; - AccountConfig accCfg; - - accCfg.idUri = "\"Just Test\" "; - accCfg.regConfig.registrarUri = "sip:sip.pjsip.org"; - SipHeader h; - h.hName = "X-Header"; - h.hValue = "User header"; - accCfg.regConfig.headers.push_back(h); - - accCfg.sipConfig.proxies.push_back(""); - accCfg.sipConfig.proxies.push_back(""); - - accCfg.mediaConfig.transportConfig.tlsConfig.ciphers.push_back(1); - accCfg.mediaConfig.transportConfig.tlsConfig.ciphers.push_back(2); - accCfg.mediaConfig.transportConfig.tlsConfig.ciphers.push_back(3); - - AuthCredInfo aci; - aci.scheme = "digest"; - aci.username = "test"; - aci.data = "passwd"; - aci.realm = "*"; - aci.dataType = PJSIP_CRED_DATA_PLAIN_PASSWD; + JsonDocument jdoc; + AccountConfig accCfg; + + accCfg.idUri = "\"Just Test\" "; + accCfg.regConfig.registrarUri = "sip:sip.pjsip.org"; + SipHeader h; + h.hName = "X-Header"; + h.hValue = "User header"; + accCfg.regConfig.headers.push_back(h); + + accCfg.sipConfig.proxies.push_back(""); + accCfg.sipConfig.proxies.push_back(""); + + accCfg.mediaConfig.transportConfig.tlsConfig.ciphers.push_back(1); + accCfg.mediaConfig.transportConfig.tlsConfig.ciphers.push_back(2); + accCfg.mediaConfig.transportConfig.tlsConfig.ciphers.push_back(3); + + AuthCredInfo aci; + aci.scheme = "digest"; + aci.username = "test"; + aci.data = "passwd"; + aci.realm = "*"; + aci.dataType = PJSIP_CRED_DATA_PLAIN_PASSWD; #if PJSIP_HAS_DIGEST_AKA_AUTH - aci.dataType |= PJSIP_CRED_DATA_EXT_AKA; - aci.akaK = "key"; + aci.dataType |= PJSIP_CRED_DATA_EXT_AKA; + aci.akaK = "key"; #endif - accCfg.sipConfig.authCreds.push_back(aci); + accCfg.sipConfig.authCreds.push_back(aci); - jdoc.writeObject(accCfg); - json_str = jdoc.saveString(); - std::cout << "Original:" << std::endl; - std::cout << json_str << std::endl << std::endl; + jdoc.writeObject(accCfg); + json_str = jdoc.saveString(); + std::cout << "Original:" << std::endl; + std::cout << json_str << std::endl << std::endl; } { - JsonDocument rdoc; + JsonDocument rdoc; - rdoc.loadString(json_str); - AccountConfig accCfg; - rdoc.readObject(accCfg); + rdoc.loadString(json_str); + AccountConfig accCfg; + rdoc.readObject(accCfg); - JsonDocument wdoc; - wdoc.writeObject(accCfg); - json_str = wdoc.saveString(); + JsonDocument wdoc; + wdoc.writeObject(accCfg); + json_str = wdoc.saveString(); - std::cout << "Parsed:" << std::endl; - std::cout << json_str << std::endl << std::endl; + std::cout << "Parsed:" << std::endl; + std::cout << json_str << std::endl << std::endl; } } #endif @@ -463,41 +462,41 @@ int main() MyEndpoint ep; try { - ep.libCreate(); + ep.libCreate(); #if USE_TEST == 0 - mainProg(ep); + mainProg(ep); #endif #if USE_TEST == 1 - mainProg1(ep); + mainProg1(ep); #endif #if USE_TEST == 2 - mainProg2(ep); + mainProg2(ep); #endif #if USE_TEST == 3 - mainProg3(ep); + mainProg3(ep); #endif #if USE_TEST == 4 - mainProg4(ep); + mainProg4(ep); #endif - ret = PJ_SUCCESS; + ret = PJ_SUCCESS; } catch (Error & err) { - std::cout << "Exception: " << err.info() << std::endl; - ret = 1; + std::cout << "Exception: " << err.info() << std::endl; + ret = 1; } try { - ep.libDestroy(); + ep.libDestroy(); } catch(Error &err) { - std::cout << "Exception: " << err.info() << std::endl; - ret = 1; + std::cout << "Exception: " << err.info() << std::endl; + ret = 1; } if (ret == PJ_SUCCESS) { - std::cout << "Success" << std::endl; + std::cout << "Success" << std::endl; } else { - std::cout << "Error Found" << std::endl; + std::cout << "Error Found" << std::endl; } return ret; diff --git a/pjsip-apps/src/samples/playfile.c b/pjsip-apps/src/samples/playfile.c index 10116ffaba..242846659c 100644 --- a/pjsip-apps/src/samples/playfile.c +++ b/pjsip-apps/src/samples/playfile.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -63,18 +62,18 @@ static const char *desc = -" FILE \n" -" \n" -" playfile.c \n" -" \n" -" PURPOSE \n" -" \n" -" Demonstrate how to play a WAV file. \n" -" \n" -" USAGE \n" -" \n" -" playfile FILE.WAV \n" -" \n" +" FILE \n" +" \n" +" playfile.c \n" +" \n" +" PURPOSE \n" +" \n" +" Demonstrate how to play a WAV file. \n" +" \n" +" USAGE \n" +" \n" +" playfile FILE.WAV \n" +" \n" " The WAV file could have mono or stereo channels with arbitrary \n" " sampling rate, but MUST contain uncompressed (i.e. 16bit) PCM. \n"; @@ -94,9 +93,9 @@ int main(int argc, char *argv[]) if (argc != 2) { - puts("Error: filename required"); - puts(desc); - return 1; + puts("Error: filename required"); + puts(desc); + return 1; } @@ -115,40 +114,40 @@ int main(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool for our file player */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "wav", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "wav", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); /* Create file media port from the WAV file */ - status = pjmedia_wav_player_port_create( pool, /* memory pool */ - argv[1], /* file to play */ - 20, /* ptime. */ - 0, /* flags */ - 0, /* default buffer */ - &file_port/* returned port */ - ); + status = pjmedia_wav_player_port_create( pool, /* memory pool */ + argv[1], /* file to play */ + 20, /* ptime. */ + 0, /* flags */ + 0, /* default buffer */ + &file_port/* returned port */ + ); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to use WAV file", status); - return 1; + app_perror(THIS_FILE, "Unable to use WAV file", status); + return 1; } /* Create sound player port. */ status = pjmedia_snd_port_create_player( - pool, /* pool */ - -1, /* use default dev. */ - PJMEDIA_PIA_SRATE(&file_port->info),/* clock rate. */ - PJMEDIA_PIA_CCNT(&file_port->info),/* # of channels. */ - PJMEDIA_PIA_SPF(&file_port->info), /* samples per frame. */ - PJMEDIA_PIA_BITS(&file_port->info),/* bits per sample. */ - 0, /* options */ - &snd_port /* returned port */ - ); + pool, /* pool */ + -1, /* use default dev. */ + PJMEDIA_PIA_SRATE(&file_port->info),/* clock rate. */ + PJMEDIA_PIA_CCNT(&file_port->info),/* # of channels. */ + PJMEDIA_PIA_SPF(&file_port->info), /* samples per frame. */ + PJMEDIA_PIA_BITS(&file_port->info),/* bits per sample. */ + 0, /* options */ + &snd_port /* returned port */ + ); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to open sound device", status); - return 1; + app_perror(THIS_FILE, "Unable to open sound device", status); + return 1; } /* Connect file port to the sound player. @@ -173,7 +172,7 @@ int main(int argc, char *argv[]) puts("Press to stop playing and quit"); if (fgets(tmp, sizeof(tmp), stdin) == NULL) { - puts("EOF while reading stdin, will quit now.."); + puts("EOF while reading stdin, will quit now.."); } diff --git a/pjsip-apps/src/samples/playsine.c b/pjsip-apps/src/samples/playsine.c index 92491f1a83..412ab0540b 100644 --- a/pjsip-apps/src/samples/playsine.c +++ b/pjsip-apps/src/samples/playsine.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -47,9 +46,9 @@ #include #include -#include /* atoi() */ +#include /* atoi() */ #include -#include /* sin() */ +#include /* sin() */ /* For logging purpose. */ #define THIS_FILE "playsine.c" @@ -57,7 +56,7 @@ /* Util to display the error message for the specified error code */ static int app_perror( const char *sender, const char *title, - pj_status_t status) + pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; @@ -73,13 +72,13 @@ static int app_perror( const char *sender, const char *title, /* Struct attached to sine generator */ typedef struct { - pj_int16_t *samples; /* Sine samples. */ + pj_int16_t *samples; /* Sine samples. */ } port_data; /* This callback is called to feed more samples */ static pj_status_t sine_get_frame( pjmedia_port *port, - pjmedia_frame *frame) + pjmedia_frame *frame) { port_data *sine = port->port_data.pdata; pj_int16_t *samples = frame->buf; @@ -93,15 +92,15 @@ static pj_status_t sine_get_frame( pjmedia_port *port, right = 0; for (i=0; isamples[left]; - ++left; - - if (PJMEDIA_PIA_CCNT(&port->info) == 2) { - *samples++ = sine->samples[right]; - right += 2; /* higher pitch so we can distinguish left and right. */ - if (right >= count) - right = 0; - } + *samples++ = sine->samples[left]; + ++left; + + if (PJMEDIA_PIA_CCNT(&port->info) == 2) { + *samples++ = sine->samples[right]; + right += 2; /* higher pitch so we can distinguish left and right. */ + if (right >= count) + right = 0; + } } /* Must set frame->type correctly, otherwise the sound device @@ -120,9 +119,9 @@ static pj_status_t sine_get_frame( pjmedia_port *port, * Create a media port to generate sine wave samples. */ static pj_status_t create_sine_port(pj_pool_t *pool, - unsigned sampling_rate, - unsigned channel_count, - pjmedia_port **p_port) + unsigned sampling_rate, + unsigned channel_count, + pjmedia_port **p_port) { pjmedia_port *port; unsigned i; @@ -131,7 +130,7 @@ static pj_status_t create_sine_port(pj_pool_t *pool, port_data *sine; PJ_ASSERT_RETURN(pool && channel_count > 0 && channel_count <= 2, - PJ_EINVAL); + PJ_EINVAL); port = pj_pool_zalloc(pool, sizeof(pjmedia_port)); PJ_ASSERT_RETURN(port != NULL, PJ_ENOMEM); @@ -140,9 +139,9 @@ static pj_status_t create_sine_port(pj_pool_t *pool, name = pj_str("sine generator"); pjmedia_port_info_init(&port->info, &name, PJMEDIA_SIG_CLASS_PORT_AUD('s', 'i'), - sampling_rate, - channel_count, - 16, sampling_rate * 20 / 1000 * channel_count); + sampling_rate, + channel_count, + 16, sampling_rate * 20 / 1000 * channel_count); /* Set the function to feed frame */ port->get_frame = &sine_get_frame; @@ -159,7 +158,7 @@ static pj_status_t create_sine_port(pj_pool_t *pool, for( i=0; isamples[i] = (pj_int16_t) (10000.0 * - sin(((double)i/(double)count) * M_PI * 8.) ); + sin(((double)i/(double)count) * M_PI * 8.) ); } *p_port = port; @@ -196,12 +195,12 @@ int main(int argc, char *argv[]) pj_status_t status; if (argc == 2) { - channel_count = atoi(argv[1]); - if (channel_count < 1 || channel_count > 2) { - puts("Error: invalid arguments"); - usage(); - return 1; - } + channel_count = atoi(argv[1]); + if (channel_count < 1 || channel_count > 2) { + puts("Error: invalid arguments"); + usage(); + return 1; + } } /* Must init PJLIB first: */ @@ -219,38 +218,38 @@ int main(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool for our sine generator */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "wav", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "wav", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); /* Create a media port to generate sine wave samples. */ - status = create_sine_port( pool, /* memory pool */ - 11025, /* sampling rate */ - channel_count,/* # of channels */ - &sine_port /* returned port */ - ); + status = create_sine_port( pool, /* memory pool */ + 11025, /* sampling rate */ + channel_count,/* # of channels */ + &sine_port /* returned port */ + ); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create sine port", status); - return 1; + app_perror(THIS_FILE, "Unable to create sine port", status); + return 1; } /* Create sound player port. */ status = pjmedia_snd_port_create_player( - pool, /* pool */ - -1, /* use default dev. */ - PJMEDIA_PIA_SRATE(&sine_port->info),/* clock rate. */ - PJMEDIA_PIA_CCNT(&sine_port->info),/* # of channels. */ - PJMEDIA_PIA_SPF(&sine_port->info), /* samples per frame. */ - PJMEDIA_PIA_BITS(&sine_port->info),/* bits per sample. */ - 0, /* options */ - &snd_port /* returned port */ - ); + pool, /* pool */ + -1, /* use default dev. */ + PJMEDIA_PIA_SRATE(&sine_port->info),/* clock rate. */ + PJMEDIA_PIA_CCNT(&sine_port->info),/* # of channels. */ + PJMEDIA_PIA_SPF(&sine_port->info), /* samples per frame. */ + PJMEDIA_PIA_BITS(&sine_port->info),/* bits per sample. */ + 0, /* options */ + &snd_port /* returned port */ + ); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to open sound device", status); - return 1; + app_perror(THIS_FILE, "Unable to open sound device", status); + return 1; } /* Connect sine generator port to the sound player @@ -275,7 +274,7 @@ int main(int argc, char *argv[]) puts("Press to stop playing and quit"); if (fgets(tmp, sizeof(tmp), stdin) == NULL) { - puts("EOF while reading stdin, will quit now.."); + puts("EOF while reading stdin, will quit now.."); } diff --git a/pjsip-apps/src/samples/proxy.h b/pjsip-apps/src/samples/proxy.h index cf9631759a..ba808383e6 100644 --- a/pjsip-apps/src/samples/proxy.h +++ b/pjsip-apps/src/samples/proxy.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,18 +24,18 @@ /* Options */ static struct global_struct { - pj_caching_pool cp; - pjsip_endpoint *endpt; - int port; - pj_pool_t *pool; + pj_caching_pool cp; + pjsip_endpoint *endpt; + int port; + pj_pool_t *pool; - pj_thread_t *thread; - pj_bool_t quit_flag; + pj_thread_t *thread; + pj_bool_t quit_flag; - pj_bool_t record_route; + pj_bool_t record_route; - unsigned name_cnt; - pjsip_host_port name[16]; + unsigned name_cnt; + pjsip_host_port name[16]; } global; @@ -53,52 +52,52 @@ static void app_perror(const char *msg, pj_status_t status) static void usage(void) { puts("Options:\n" - "\n" - " -p, --port N Set local listener port to N\n" - " -R, --rr Perform record routing\n" - " -L, --log-level N Set log level to N (default: 4)\n" - " -h, --help Show this help screen\n" - ); + "\n" + " -p, --port N Set local listener port to N\n" + " -R, --rr Perform record routing\n" + " -L, --log-level N Set log level to N (default: 4)\n" + " -h, --help Show this help screen\n" + ); } static pj_status_t init_options(int argc, char *argv[]) { struct pj_getopt_option long_opt[] = { - { "port", 1, 0, 'p'}, - { "rr", 0, 0, 'R'}, - { "log-level", 1, 0, 'L'}, - { "help", 0, 0, 'h'}, - { NULL, 0, 0, 0} + { "port", 1, 0, 'p'}, + { "rr", 0, 0, 'R'}, + { "log-level", 1, 0, 'L'}, + { "help", 0, 0, 'h'}, + { NULL, 0, 0, 0} }; int c; int opt_ind; pj_optind = 0; while((c=pj_getopt_long(argc, argv, "p:L:Rh", long_opt, &opt_ind))!=-1) { - switch (c) { - case 'p': - global.port = atoi(pj_optarg); - printf("Port is set to %d\n", global.port); - break; - - case 'R': - global.record_route = PJ_TRUE; - printf("Using record route mode\n"); - break; - - case 'L': - pj_log_set_level(atoi(pj_optarg)); - break; - - case 'h': - usage(); - return -1; - - default: - puts("Unknown option. Run with --help for help."); - return -1; - } + switch (c) { + case 'p': + global.port = atoi(pj_optarg); + printf("Port is set to %d\n", global.port); + break; + + case 'R': + global.record_route = PJ_TRUE; + printf("Using record route mode\n"); + break; + + case 'L': + pj_log_set_level(atoi(pj_optarg)); + break; + + case 'h': + usage(); + return -1; + + default: + puts("Unknown option. Run with --help for help."); + return -1; + } } return PJ_SUCCESS; @@ -123,15 +122,15 @@ static pj_status_t init_options(int argc, char *argv[]) static pj_bool_t logging_on_rx_msg(pjsip_rx_data *rdata) { PJ_LOG(5,(THIS_FILE, "RX %d bytes %s from %s %s:%d:\n" - "%.*s\n" - "--end msg--", - rdata->msg_info.len, - pjsip_rx_data_get_info(rdata), - rdata->tp_info.transport->type_name, - rdata->pkt_info.src_name, - rdata->pkt_info.src_port, - (int)rdata->msg_info.len, - rdata->msg_info.msg_buf)); + "%.*s\n" + "--end msg--", + rdata->msg_info.len, + pjsip_rx_data_get_info(rdata), + rdata->tp_info.transport->type_name, + rdata->pkt_info.src_name, + rdata->pkt_info.src_port, + (int)rdata->msg_info.len, + rdata->msg_info.msg_buf)); /* Always return false, otherwise messages will not get processed! */ return PJ_FALSE; @@ -142,21 +141,21 @@ static pj_status_t logging_on_tx_msg(pjsip_tx_data *tdata) { /* Important note: - * tp_info field is only valid after outgoing messages has passed - * transport layer. So don't try to access tp_info when the module - * has lower priority than transport layer. + * tp_info field is only valid after outgoing messages has passed + * transport layer. So don't try to access tp_info when the module + * has lower priority than transport layer. */ PJ_LOG(5,(THIS_FILE, "TX %d bytes %s to %s %s:%d:\n" - "%.*s\n" - "--end msg--", - (tdata->buf.cur - tdata->buf.start), - pjsip_tx_data_get_info(tdata), - tdata->tp_info.transport->type_name, - tdata->tp_info.dst_name, - tdata->tp_info.dst_port, - (int)(tdata->buf.cur - tdata->buf.start), - tdata->buf.start)); + "%.*s\n" + "--end msg--", + (tdata->buf.cur - tdata->buf.start), + pjsip_tx_data_get_info(tdata), + tdata->tp_info.transport->type_name, + tdata->tp_info.dst_name, + tdata->tp_info.dst_port, + (int)(tdata->buf.cur - tdata->buf.start), + tdata->buf.start)); /* Always return success, otherwise message will not get sent! */ return PJ_SUCCESS; @@ -165,19 +164,19 @@ static pj_status_t logging_on_tx_msg(pjsip_tx_data *tdata) /* The module instance. */ static pjsip_module mod_msg_logger = { - NULL, NULL, /* prev, next. */ - { "mod-msg-logger", 14 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &logging_on_rx_msg, /* on_rx_request() */ - &logging_on_rx_msg, /* on_rx_response() */ - &logging_on_tx_msg, /* on_tx_request. */ - &logging_on_tx_msg, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-msg-logger", 14 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &logging_on_rx_msg, /* on_rx_request() */ + &logging_on_rx_msg, /* on_rx_response() */ + &logging_on_tx_msg, /* on_tx_request. */ + &logging_on_tx_msg, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -211,21 +210,21 @@ static pj_status_t init_stack(void) /* Create listening transport */ { - pj_sockaddr_in addr; + pj_sockaddr_in addr; - addr.sin_family = pj_AF_INET(); - addr.sin_addr.s_addr = 0; - addr.sin_port = pj_htons((pj_uint16_t)global.port); + addr.sin_family = pj_AF_INET(); + addr.sin_addr.s_addr = 0; + addr.sin_port = pj_htons((pj_uint16_t)global.port); - status = pjsip_udp_transport_start( global.endpt, &addr, - NULL, 1, NULL); - if (status != PJ_SUCCESS) - return status; + status = pjsip_udp_transport_start( global.endpt, &addr, + NULL, 1, NULL); + if (status != PJ_SUCCESS) + return status; } /* Create pool for the application */ global.pool = pj_pool_create(&global.cp.factory, "proxyapp", - 4000, 4000, NULL); + 4000, 4000, NULL); /* Register the logger module */ pjsip_endpt_register_module(global.endpt, &mod_msg_logger); @@ -252,30 +251,30 @@ static pj_status_t init_proxy(void) * to be added in Record-Route. */ if (pj_gethostip(pj_AF_INET(), &pri_addr)==PJ_SUCCESS) { - char addr[PJ_INET_ADDRSTRLEN]; - pj_inet_ntop(pj_AF_INET(), &pri_addr.ipv4.sin_addr, addr, - sizeof(addr)); - pj_strdup2(global.pool, &global.name[global.name_cnt].host, addr); - global.name[global.name_cnt].port = global.port; - global.name_cnt++; + char addr[PJ_INET_ADDRSTRLEN]; + pj_inet_ntop(pj_AF_INET(), &pri_addr.ipv4.sin_addr, addr, + sizeof(addr)); + pj_strdup2(global.pool, &global.name[global.name_cnt].host, addr); + global.name[global.name_cnt].port = global.port; + global.name_cnt++; } /* Get the rest of IP interfaces */ if (pj_enum_ip_interface(pj_AF_INET(), &addr_cnt, addr_list) == PJ_SUCCESS) { - for (i=0; iport == global.name[i].port || - (uri->port==0 && global.name[i].port==5060)) && - pj_stricmp(&uri->host, &global.name[i].host)==0) - { - /* Match */ - return PJ_TRUE; - } + if ((uri->port == global.name[i].port || + (uri->port==0 && global.name[i].port==5060)) && + pj_stricmp(&uri->host, &global.name[i].host)==0) + { + /* Match */ + return PJ_TRUE; + } } /* Doesn't match */ @@ -373,22 +372,22 @@ static pj_status_t proxy_verify_request(pjsip_rx_data *rdata) * We only want to support "sip:"/"sips:" URI scheme for this simple proxy. */ if (!PJSIP_URI_SCHEME_IS_SIP(rdata->msg_info.msg->line.req.uri) && - !PJSIP_URI_SCHEME_IS_SIPS(rdata->msg_info.msg->line.req.uri)) + !PJSIP_URI_SCHEME_IS_SIPS(rdata->msg_info.msg->line.req.uri)) { - pjsip_endpt_respond_stateless(global.endpt, rdata, - PJSIP_SC_UNSUPPORTED_URI_SCHEME, NULL, - NULL, NULL); - return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_UNSUPPORTED_URI_SCHEME); + pjsip_endpt_respond_stateless(global.endpt, rdata, + PJSIP_SC_UNSUPPORTED_URI_SCHEME, NULL, + NULL, NULL); + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_UNSUPPORTED_URI_SCHEME); } /* 3. Max-Forwards. * Send error if Max-Forwards is 1 or lower. */ if (rdata->msg_info.max_fwd && rdata->msg_info.max_fwd->ivalue <= 1) { - pjsip_endpt_respond_stateless(global.endpt, rdata, - PJSIP_SC_TOO_MANY_HOPS, NULL, - NULL, NULL); - return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_TOO_MANY_HOPS); + pjsip_endpt_respond_stateless(global.endpt, rdata, + PJSIP_SC_TOO_MANY_HOPS, NULL, + NULL, NULL); + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_TOO_MANY_HOPS); } /* 4. (Optional) Loop Detection. @@ -397,12 +396,12 @@ static pj_status_t proxy_verify_request(pjsip_rx_data *rdata) /* 5. Proxy-Require */ if (pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_PROXY_REQUIRE, - NULL) != NULL) + NULL) != NULL) { - pjsip_endpt_respond_stateless(global.endpt, rdata, - PJSIP_SC_BAD_EXTENSION, NULL, - NULL, NULL); - return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_EXTENSION); + pjsip_endpt_respond_stateless(global.endpt, rdata, + PJSIP_SC_BAD_EXTENSION, NULL, + NULL, NULL); + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_EXTENSION); } /* 6. Proxy-Authorization. @@ -432,44 +431,44 @@ static pj_status_t proxy_process_routing(pjsip_tx_data *tdata) * this modified request. */ if (is_uri_local(target)) { - pjsip_route_hdr *r; - pjsip_sip_uri *uri; - - /* Find the first Route header */ - r = hroute = (pjsip_route_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, NULL); - if (r == NULL) { - /* No Route header. This request is destined for this proxy. */ - return PJ_SUCCESS; - } - - /* Find the last Route header */ - while ( (r=(pjsip_route_hdr*)pjsip_msg_find_hdr(tdata->msg, - PJSIP_H_ROUTE, - r->next)) != NULL ) - { - hroute = r; - } - - /* If the last Route header doesn't have ";lr" parameter, then - * this is a strict-routed request indeed, and we follow the steps - * in processing strict-route requests above. - * - * But if it does contain ";lr" parameter, skip the strict-route - * processing. - */ - uri = (pjsip_sip_uri*) - pjsip_uri_get_uri(&hroute->name_addr); - if (uri->lr_param == 0) { - /* Yes this is strict route, so: - * - replace req URI with the URI in Route header, - * - remove the Route header, - * - proceed as if it received this modified request. - */ - tdata->msg->line.req.uri = hroute->name_addr.uri; - target = (pjsip_sip_uri*) tdata->msg->line.req.uri; - pj_list_erase(hroute); - } + pjsip_route_hdr *r; + pjsip_sip_uri *uri; + + /* Find the first Route header */ + r = hroute = (pjsip_route_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, NULL); + if (r == NULL) { + /* No Route header. This request is destined for this proxy. */ + return PJ_SUCCESS; + } + + /* Find the last Route header */ + while ( (r=(pjsip_route_hdr*)pjsip_msg_find_hdr(tdata->msg, + PJSIP_H_ROUTE, + r->next)) != NULL ) + { + hroute = r; + } + + /* If the last Route header doesn't have ";lr" parameter, then + * this is a strict-routed request indeed, and we follow the steps + * in processing strict-route requests above. + * + * But if it does contain ";lr" parameter, skip the strict-route + * processing. + */ + uri = (pjsip_sip_uri*) + pjsip_uri_get_uri(&hroute->name_addr); + if (uri->lr_param == 0) { + /* Yes this is strict route, so: + * - replace req URI with the URI in Route header, + * - remove the Route header, + * - proceed as if it received this modified request. + */ + tdata->msg->line.req.uri = hroute->name_addr.uri; + target = (pjsip_sip_uri*) tdata->msg->line.req.uri; + pj_list_erase(hroute); + } } /* If the Request-URI contains a maddr parameter, the proxy MUST check @@ -482,25 +481,25 @@ static pj_status_t proxy_process_routing(pjsip_tx_data *tdata) * those values had not been present in the request. */ if (target->maddr_param.slen != 0) { - pjsip_sip_uri maddr_uri; + pjsip_sip_uri maddr_uri; - maddr_uri.host = target->maddr_param; - maddr_uri.port = global.port; + maddr_uri.host = target->maddr_param; + maddr_uri.port = global.port; - if (is_uri_local(&maddr_uri)) { - target->maddr_param.slen = 0; - target->port = 0; - target->transport_param.slen = 0; - } + if (is_uri_local(&maddr_uri)) { + target->maddr_param.slen = 0; + target->port = 0; + target->transport_param.slen = 0; + } } /* If the first value in the Route header field indicates this proxy, * the proxy MUST remove that value from the request. */ hroute = (pjsip_route_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, NULL); + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, NULL); if (hroute && is_uri_local((pjsip_sip_uri*)hroute->name_addr.uri)) { - pj_list_erase(hroute); + pj_list_erase(hroute); } return PJ_SUCCESS; @@ -512,26 +511,26 @@ static void proxy_postprocess(pjsip_tx_data *tdata) { /* Optionally record-route */ if (global.record_route) { - char uribuf[128]; - pj_str_t uri; - const pj_str_t H_RR = { "Record-Route", 12 }; - pjsip_generic_string_hdr *rr; - - pj_ansi_snprintf(uribuf, sizeof(uribuf), "", - (int)global.name[0].host.slen, - global.name[0].host.ptr, - global.name[0].port); - uri = pj_str(uribuf); - rr = pjsip_generic_string_hdr_create(tdata->pool, - &H_RR, &uri); - pjsip_msg_insert_first_hdr(tdata->msg, (pjsip_hdr*)rr); + char uribuf[128]; + pj_str_t uri; + const pj_str_t H_RR = { "Record-Route", 12 }; + pjsip_generic_string_hdr *rr; + + pj_ansi_snprintf(uribuf, sizeof(uribuf), "", + (int)global.name[0].host.slen, + global.name[0].host.ptr, + global.name[0].port); + uri = pj_str(uribuf); + rr = pjsip_generic_string_hdr_create(tdata->pool, + &H_RR, &uri); + pjsip_msg_insert_first_hdr(tdata->msg, (pjsip_hdr*)rr); } } /* Calculate new target for the request */ static pj_status_t proxy_calculate_target(pjsip_rx_data *rdata, - pjsip_tx_data *tdata) + pjsip_tx_data *tdata) { pjsip_sip_uri *target; @@ -544,8 +543,8 @@ static pj_status_t proxy_calculate_target(pjsip_rx_data *rdata, * URI, and the proxy MUST proceed to Section 16.6. */ if (target->maddr_param.slen) { - proxy_postprocess(tdata); - return PJ_SUCCESS; + proxy_postprocess(tdata); + return PJ_SUCCESS; } @@ -555,8 +554,8 @@ static pj_status_t proxy_calculate_target(pjsip_rx_data *rdata, * Request Forwarding (Section 16.6). */ if (!is_uri_local(target)) { - proxy_postprocess(tdata); - return PJ_SUCCESS; + proxy_postprocess(tdata); + return PJ_SUCCESS; } /* If the target set for the request has not been predetermined as @@ -569,9 +568,9 @@ static pj_status_t proxy_calculate_target(pjsip_rx_data *rdata, * respond with 404/Not Found (only if request is not ACK!). */ if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { - pjsip_endpt_respond_stateless(global.endpt, rdata, - PJSIP_SC_NOT_FOUND, NULL, - NULL, NULL); + pjsip_endpt_respond_stateless(global.endpt, rdata, + PJSIP_SC_NOT_FOUND, NULL, + NULL, NULL); } /* Delete the request since we're not forwarding it */ diff --git a/pjsip-apps/src/samples/recfile.c b/pjsip-apps/src/samples/recfile.c index 60ca4e4f9c..463157b7b7 100644 --- a/pjsip-apps/src/samples/recfile.c +++ b/pjsip-apps/src/samples/recfile.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -41,27 +40,27 @@ /* Configs */ -#define CLOCK_RATE 44100 -#define NCHANNELS 2 +#define CLOCK_RATE 44100 +#define NCHANNELS 2 #define SAMPLES_PER_FRAME (NCHANNELS * (CLOCK_RATE * 10 / 1000)) -#define BITS_PER_SAMPLE 16 +#define BITS_PER_SAMPLE 16 static const char *desc = - " FILE \n" - " recfile.c \n" - " \n" - " PURPOSE: \n" - " Record microphone to WAVE file. \n" - " \n" - " USAGE: \n" - " recfile FILE.WAV \n" + " FILE \n" + " recfile.c \n" + " \n" + " PURPOSE: \n" + " Record microphone to WAVE file. \n" + " \n" + " USAGE: \n" + " recfile FILE.WAV \n" ""; /* Util to display the error message for the specified error code */ static int app_perror( const char *sender, const char *title, - pj_status_t status) + pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; @@ -90,9 +89,9 @@ int main(int argc, char *argv[]) /* Verify cmd line arguments. */ if (argc != 2) { - puts(""); - puts(desc); - return 0; + puts(""); + puts(desc); + return 0; } /* Must init PJLIB first: */ @@ -110,40 +109,40 @@ int main(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool for our file player */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "app", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "app", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); /* Create WAVE file writer port. */ status = pjmedia_wav_writer_port_create( pool, argv[1], - CLOCK_RATE, - NCHANNELS, - SAMPLES_PER_FRAME, - BITS_PER_SAMPLE, - 0, 0, - &file_port); + CLOCK_RATE, + NCHANNELS, + SAMPLES_PER_FRAME, + BITS_PER_SAMPLE, + 0, 0, + &file_port); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to open WAV file for writing", status); - return 1; + app_perror(THIS_FILE, "Unable to open WAV file for writing", status); + return 1; } /* Create sound player port. */ status = pjmedia_snd_port_create_rec( - pool, /* pool */ - -1, /* use default dev. */ - PJMEDIA_PIA_SRATE(&file_port->info),/* clock rate. */ - PJMEDIA_PIA_CCNT(&file_port->info),/* # of channels. */ - PJMEDIA_PIA_SPF(&file_port->info), /* samples per frame. */ - PJMEDIA_PIA_BITS(&file_port->info),/* bits per sample. */ - 0, /* options */ - &snd_port /* returned port */ - ); + pool, /* pool */ + -1, /* use default dev. */ + PJMEDIA_PIA_SRATE(&file_port->info),/* clock rate. */ + PJMEDIA_PIA_CCNT(&file_port->info),/* # of channels. */ + PJMEDIA_PIA_SPF(&file_port->info), /* samples per frame. */ + PJMEDIA_PIA_BITS(&file_port->info),/* bits per sample. */ + 0, /* options */ + &snd_port /* returned port */ + ); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to open sound device", status); - return 1; + app_perror(THIS_FILE, "Unable to open sound device", status); + return 1; } /* Connect file port to the sound player. @@ -168,7 +167,7 @@ int main(int argc, char *argv[]) puts("Press to stop recording and quit"); if (fgets(tmp, sizeof(tmp), stdin) == NULL) { - puts("EOF while reading stdin, will quit now.."); + puts("EOF while reading stdin, will quit now.."); } diff --git a/pjsip-apps/src/samples/resampleplay.c b/pjsip-apps/src/samples/resampleplay.c index 5a40e3083d..56ebd1756a 100644 --- a/pjsip-apps/src/samples/resampleplay.c +++ b/pjsip-apps/src/samples/resampleplay.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -43,22 +42,22 @@ static const char *desc = -" FILE \n" -" \n" -" resampleplay.c \n" -" \n" -" PURPOSE \n" -" \n" +" FILE \n" +" \n" +" resampleplay.c \n" +" \n" +" PURPOSE \n" +" \n" " Demonstrate how use resample port to play a WAV file to sound \n" -" device using different sampling rate. \n" -" \n" -" USAGE \n" -" \n" -" resampleplay [options] FILE.WAV \n" -" \n" -" where options: \n" +" device using different sampling rate. \n" +" \n" +" USAGE \n" +" \n" +" resampleplay [options] FILE.WAV \n" +" \n" +" where options: \n" SND_USAGE -" \n" +" \n" " The WAV file could have mono or stereo channels with arbitrary \n" " sampling rate, but MUST contain uncompressed (i.e. 16bit) PCM. \n"; @@ -89,17 +88,17 @@ int main(int argc, char *argv[]) /* Get options */ if (get_snd_options(THIS_FILE, argc, argv, &dev_id, &sampling_rate, - &channel_count, &samples_per_frame, &bits_per_sample)) + &channel_count, &samples_per_frame, &bits_per_sample)) { - puts(""); - puts(desc); - return 1; + puts(""); + puts(desc); + return 1; } if (!argv[pj_optind]) { - puts("Error: no file is specified"); - puts(desc); - return 1; + puts("Error: no file is specified"); + puts(desc); + return 1; } /* Must create a pool factory before we can allocate any memory. */ @@ -113,27 +112,27 @@ int main(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool for our file player */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "app", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "app", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); /* Create the file port. */ status = pjmedia_wav_player_port_create( pool, argv[pj_optind], 0, 0, - 0, &file_port); + 0, &file_port); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to open file", status); - return 1; + app_perror(THIS_FILE, "Unable to open file", status); + return 1; } /* File must have same number of channels. */ if (PJMEDIA_PIA_CCNT(&file_port->info) != (unsigned)channel_count) { - PJ_LOG(3,(THIS_FILE, "Error: file has different number of channels. " - "Perhaps you'd need -c option?")); - pjmedia_port_destroy(file_port); - return 1; + PJ_LOG(3,(THIS_FILE, "Error: file has different number of channels. " + "Perhaps you'd need -c option?")); + pjmedia_port_destroy(file_port); + return 1; } /* Calculate number of samples per frame to be taken from file port */ @@ -141,35 +140,35 @@ int main(int argc, char *argv[]) /* Create the resample port. */ status = pjmedia_resample_port_create( pool, file_port, - sampling_rate, 0, - &resample_port); + sampling_rate, 0, + &resample_port); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create resample port", status); - return 1; + app_perror(THIS_FILE, "Unable to create resample port", status); + return 1; } /* Create sound player port. */ status = pjmedia_snd_port_create( - pool, /* pool */ - dev_id, /* device */ - dev_id, /* device */ - sampling_rate, /* clock rate. */ - channel_count, /* # of channels. */ - samples_per_frame, /* samples per frame. */ - bits_per_sample, /* bits per sample. */ - 0, /* options */ - &snd_port /* returned port */ - ); + pool, /* pool */ + dev_id, /* device */ + dev_id, /* device */ + sampling_rate, /* clock rate. */ + channel_count, /* # of channels. */ + samples_per_frame, /* samples per frame. */ + bits_per_sample, /* bits per sample. */ + 0, /* options */ + &snd_port /* returned port */ + ); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to open sound device", status); - return 1; + app_perror(THIS_FILE, "Unable to open sound device", status); + return 1; } /* Connect resample port to sound device */ status = pjmedia_snd_port_connect( snd_port, resample_port); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error connecting sound ports", status); - return 1; + app_perror(THIS_FILE, "Error connecting sound ports", status); + return 1; } @@ -186,13 +185,13 @@ int main(int argc, char *argv[]) printf("Playing %s at sampling rate %d (original file sampling rate=%d)\n", - argv[pj_optind], sampling_rate, - PJMEDIA_PIA_SRATE(&file_port->info)); + argv[pj_optind], sampling_rate, + PJMEDIA_PIA_SRATE(&file_port->info)); puts(""); puts("Press to stop playing and quit"); if (fgets(tmp, sizeof(tmp), stdin) == NULL) { - puts("EOF while reading stdin, will quit now.."); + puts("EOF while reading stdin, will quit now.."); } /* Start deinitialization: */ diff --git a/pjsip-apps/src/samples/simple_pjsua.c b/pjsip-apps/src/samples/simple_pjsua.c index 5cd0ce1f7f..7d5c320991 100644 --- a/pjsip-apps/src/samples/simple_pjsua.c +++ b/pjsip-apps/src/samples/simple_pjsua.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,7 +30,7 @@ * - To make outgoing call, start simple_pjsua with the URL of remote * destination to contact. * E.g.: - * simpleua sip:user@remote + * simpleua sip:user@remote * * - Incoming calls will automatically be answered with 200. * @@ -40,16 +39,16 @@ #include -#define THIS_FILE "APP" +#define THIS_FILE "APP" -#define SIP_DOMAIN "example.com" -#define SIP_USER "alice" -#define SIP_PASSWD "secret" +#define SIP_DOMAIN "example.com" +#define SIP_USER "alice" +#define SIP_PASSWD "secret" /* Callback called by the library upon receiving incoming call */ static void on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, - pjsip_rx_data *rdata) + pjsip_rx_data *rdata) { pjsua_call_info ci; @@ -59,8 +58,8 @@ static void on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, pjsua_call_get_info(call_id, &ci); PJ_LOG(3,(THIS_FILE, "Incoming call from %.*s!!", - (int)ci.remote_info.slen, - ci.remote_info.ptr)); + (int)ci.remote_info.slen, + ci.remote_info.ptr)); /* Automatically answer incoming calls with 200/OK */ pjsua_call_answer(call_id, 200, NULL, NULL); @@ -75,8 +74,8 @@ static void on_call_state(pjsua_call_id call_id, pjsip_event *e) pjsua_call_get_info(call_id, &ci); PJ_LOG(3,(THIS_FILE, "Call %d state=%.*s", call_id, - (int)ci.state_text.slen, - ci.state_text.ptr)); + (int)ci.state_text.slen, + ci.state_text.ptr)); } /* Callback called by the library when call's media state has changed */ @@ -87,9 +86,9 @@ static void on_call_media_state(pjsua_call_id call_id) pjsua_call_get_info(call_id, &ci); if (ci.media_status == PJSUA_CALL_MEDIA_ACTIVE) { - // When media is active, connect call to sound device. - pjsua_conf_connect(ci.conf_slot, 0); - pjsua_conf_connect(0, ci.conf_slot); + // When media is active, connect call to sound device. + pjsua_conf_connect(ci.conf_slot, 0); + pjsua_conf_connect(0, ci.conf_slot); } } @@ -117,35 +116,35 @@ int main(int argc, char *argv[]) /* If argument is specified, it's got to be a valid SIP URL */ if (argc > 1) { - status = pjsua_verify_url(argv[1]); - if (status != PJ_SUCCESS) error_exit("Invalid URL in argv", status); + status = pjsua_verify_url(argv[1]); + if (status != PJ_SUCCESS) error_exit("Invalid URL in argv", status); } /* Init pjsua */ { - pjsua_config cfg; - pjsua_logging_config log_cfg; + pjsua_config cfg; + pjsua_logging_config log_cfg; - pjsua_config_default(&cfg); - cfg.cb.on_incoming_call = &on_incoming_call; - cfg.cb.on_call_media_state = &on_call_media_state; - cfg.cb.on_call_state = &on_call_state; + pjsua_config_default(&cfg); + cfg.cb.on_incoming_call = &on_incoming_call; + cfg.cb.on_call_media_state = &on_call_media_state; + cfg.cb.on_call_state = &on_call_state; - pjsua_logging_config_default(&log_cfg); - log_cfg.console_level = 4; + pjsua_logging_config_default(&log_cfg); + log_cfg.console_level = 4; - status = pjsua_init(&cfg, &log_cfg, NULL); - if (status != PJ_SUCCESS) error_exit("Error in pjsua_init()", status); + status = pjsua_init(&cfg, &log_cfg, NULL); + if (status != PJ_SUCCESS) error_exit("Error in pjsua_init()", status); } /* Add UDP transport. */ { - pjsua_transport_config cfg; + pjsua_transport_config cfg; - pjsua_transport_config_default(&cfg); - cfg.port = 5060; - status = pjsua_transport_create(PJSIP_TRANSPORT_UDP, &cfg, NULL); - if (status != PJ_SUCCESS) error_exit("Error creating transport", status); + pjsua_transport_config_default(&cfg); + cfg.port = 5060; + status = pjsua_transport_create(PJSIP_TRANSPORT_UDP, &cfg, NULL); + if (status != PJ_SUCCESS) error_exit("Error creating transport", status); } /* Initialization is done, now start pjsua */ @@ -154,44 +153,44 @@ int main(int argc, char *argv[]) /* Register to SIP server by creating SIP account. */ { - pjsua_acc_config cfg; - - pjsua_acc_config_default(&cfg); - cfg.id = pj_str("sip:" SIP_USER "@" SIP_DOMAIN); - cfg.reg_uri = pj_str("sip:" SIP_DOMAIN); - cfg.cred_count = 1; - cfg.cred_info[0].realm = pj_str(SIP_DOMAIN); - cfg.cred_info[0].scheme = pj_str("digest"); - cfg.cred_info[0].username = pj_str(SIP_USER); - cfg.cred_info[0].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; - cfg.cred_info[0].data = pj_str(SIP_PASSWD); - - status = pjsua_acc_add(&cfg, PJ_TRUE, &acc_id); - if (status != PJ_SUCCESS) error_exit("Error adding account", status); + pjsua_acc_config cfg; + + pjsua_acc_config_default(&cfg); + cfg.id = pj_str("sip:" SIP_USER "@" SIP_DOMAIN); + cfg.reg_uri = pj_str("sip:" SIP_DOMAIN); + cfg.cred_count = 1; + cfg.cred_info[0].realm = pj_str(SIP_DOMAIN); + cfg.cred_info[0].scheme = pj_str("digest"); + cfg.cred_info[0].username = pj_str(SIP_USER); + cfg.cred_info[0].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; + cfg.cred_info[0].data = pj_str(SIP_PASSWD); + + status = pjsua_acc_add(&cfg, PJ_TRUE, &acc_id); + if (status != PJ_SUCCESS) error_exit("Error adding account", status); } /* If URL is specified, make call to the URL. */ if (argc > 1) { - pj_str_t uri = pj_str(argv[1]); - status = pjsua_call_make_call(acc_id, &uri, 0, NULL, NULL, NULL); - if (status != PJ_SUCCESS) error_exit("Error making call", status); + pj_str_t uri = pj_str(argv[1]); + status = pjsua_call_make_call(acc_id, &uri, 0, NULL, NULL, NULL); + if (status != PJ_SUCCESS) error_exit("Error making call", status); } /* Wait until user press "q" to quit. */ for (;;) { - char option[10]; + char option[10]; - puts("Press 'h' to hangup all calls, 'q' to quit"); - if (fgets(option, sizeof(option), stdin) == NULL) { - puts("EOF while reading stdin, will quit now.."); - break; - } + puts("Press 'h' to hangup all calls, 'q' to quit"); + if (fgets(option, sizeof(option), stdin) == NULL) { + puts("EOF while reading stdin, will quit now.."); + break; + } - if (option[0] == 'q') - break; + if (option[0] == 'q') + break; - if (option[0] == 'h') - pjsua_call_hangup_all(); + if (option[0] == 'h') + pjsua_call_hangup_all(); } /* Destroy pjsua */ diff --git a/pjsip-apps/src/samples/simpleua.c b/pjsip-apps/src/samples/simpleua.c index 9964b1e3ca..bac4ee7ff8 100644 --- a/pjsip-apps/src/samples/simpleua.c +++ b/pjsip-apps/src/samples/simpleua.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -42,7 +41,7 @@ * - To make outgoing call, start simpleua with the URL of remote * destination to contact. * E.g.: - * simpleua sip:user@remote + * simpleua sip:user@remote * * - Incoming calls will automatically be answered with 180, then 200. * @@ -67,47 +66,47 @@ /* Settings */ -#define AF pj_AF_INET() /* Change to pj_AF_INET6() for IPv6. - * PJ_HAS_IPV6 must be enabled and - * your system must support IPv6. */ +#define AF pj_AF_INET() /* Change to pj_AF_INET6() for IPv6. + * PJ_HAS_IPV6 must be enabled and + * your system must support IPv6. */ #if 0 -#define SIP_PORT 5080 /* Listening SIP port */ -#define RTP_PORT 5000 /* RTP port */ +#define SIP_PORT 5080 /* Listening SIP port */ +#define RTP_PORT 5000 /* RTP port */ #else -#define SIP_PORT 5060 /* Listening SIP port */ -#define RTP_PORT 4000 /* RTP port */ +#define SIP_PORT 5060 /* Listening SIP port */ +#define RTP_PORT 4000 /* RTP port */ #endif -#define MAX_MEDIA_CNT 2 /* Media count, set to 1 for audio - * only or 2 for audio and video */ +#define MAX_MEDIA_CNT 2 /* Media count, set to 1 for audio + * only or 2 for audio and video */ /* * Static variables. */ -static pj_bool_t g_complete; /* Quit flag. */ -static pjsip_endpoint *g_endpt; /* SIP endpoint. */ -static pj_caching_pool cp; /* Global pool factory. */ +static pj_bool_t g_complete; /* Quit flag. */ +static pjsip_endpoint *g_endpt; /* SIP endpoint. */ +static pj_caching_pool cp; /* Global pool factory. */ -static pjmedia_endpt *g_med_endpt; /* Media endpoint. */ +static pjmedia_endpt *g_med_endpt; /* Media endpoint. */ static pjmedia_transport_info g_med_tpinfo[MAX_MEDIA_CNT]; - /* Socket info for media */ + /* Socket info for media */ static pjmedia_transport *g_med_transport[MAX_MEDIA_CNT]; - /* Media stream transport */ + /* Media stream transport */ static pjmedia_sock_info g_sock_info[MAX_MEDIA_CNT]; - /* Socket info array */ + /* Socket info array */ /* Call variables: */ -static pjsip_inv_session *g_inv; /* Current invite session. */ -static pjmedia_stream *g_med_stream; /* Call's audio stream. */ -static pjmedia_snd_port *g_snd_port; /* Sound device. */ +static pjsip_inv_session *g_inv; /* Current invite session. */ +static pjmedia_stream *g_med_stream; /* Call's audio stream. */ +static pjmedia_snd_port *g_snd_port; /* Sound device. */ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -static pjmedia_vid_stream *g_med_vstream; /* Call's video stream. */ -static pjmedia_vid_port *g_vid_capturer;/* Call's video capturer. */ -static pjmedia_vid_port *g_vid_renderer;/* Call's video renderer. */ -#endif /* PJMEDIA_HAS_VIDEO */ +static pjmedia_vid_stream *g_med_vstream; /* Call's video stream. */ +static pjmedia_vid_port *g_vid_capturer;/* Call's video capturer. */ +static pjmedia_vid_port *g_vid_renderer;/* Call's video renderer. */ +#endif /* PJMEDIA_HAS_VIDEO */ /* * Prototypes: @@ -115,11 +114,11 @@ static pjmedia_vid_port *g_vid_renderer;/* Call's video renderer. */ /* Callback to be called when SDP negotiation is done in the call: */ static void call_on_media_update( pjsip_inv_session *inv, - pj_status_t status); + pj_status_t status); /* Callback to be called when invite session's state has changed: */ static void call_on_state_changed( pjsip_inv_session *inv, - pjsip_event *e); + pjsip_event *e); /* Callback to be called when dialog has forked: */ static void call_on_forked(pjsip_inv_session *inv, pjsip_event *e); @@ -137,19 +136,19 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ); */ static pjsip_module mod_simpleua = { - NULL, NULL, /* prev, next. */ - { "mod-simpleua", 12 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-simpleua", 12 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -157,15 +156,15 @@ static pjsip_module mod_simpleua = static pj_bool_t logging_on_rx_msg(pjsip_rx_data *rdata) { PJ_LOG(4,(THIS_FILE, "RX %d bytes %s from %s %s:%d:\n" - "%.*s\n" - "--end msg--", - rdata->msg_info.len, - pjsip_rx_data_get_info(rdata), - rdata->tp_info.transport->type_name, - rdata->pkt_info.src_name, - rdata->pkt_info.src_port, - (int)rdata->msg_info.len, - rdata->msg_info.msg_buf)); + "%.*s\n" + "--end msg--", + rdata->msg_info.len, + pjsip_rx_data_get_info(rdata), + rdata->tp_info.transport->type_name, + rdata->pkt_info.src_name, + rdata->pkt_info.src_port, + (int)rdata->msg_info.len, + rdata->msg_info.msg_buf)); /* Always return false, otherwise messages will not get processed! */ return PJ_FALSE; @@ -176,21 +175,21 @@ static pj_status_t logging_on_tx_msg(pjsip_tx_data *tdata) { /* Important note: - * tp_info field is only valid after outgoing messages has passed - * transport layer. So don't try to access tp_info when the module - * has lower priority than transport layer. + * tp_info field is only valid after outgoing messages has passed + * transport layer. So don't try to access tp_info when the module + * has lower priority than transport layer. */ PJ_LOG(4,(THIS_FILE, "TX %d bytes %s to %s %s:%d:\n" - "%.*s\n" - "--end msg--", - (tdata->buf.cur - tdata->buf.start), - pjsip_tx_data_get_info(tdata), - tdata->tp_info.transport->type_name, - tdata->tp_info.dst_name, - tdata->tp_info.dst_port, - (int)(tdata->buf.cur - tdata->buf.start), - tdata->buf.start)); + "%.*s\n" + "--end msg--", + (tdata->buf.cur - tdata->buf.start), + pjsip_tx_data_get_info(tdata), + tdata->tp_info.transport->type_name, + tdata->tp_info.dst_name, + tdata->tp_info.dst_port, + (int)(tdata->buf.cur - tdata->buf.start), + tdata->buf.start)); /* Always return success, otherwise message will not get sent! */ return PJ_SUCCESS; @@ -199,19 +198,19 @@ static pj_status_t logging_on_tx_msg(pjsip_tx_data *tdata) /* The module instance. */ static pjsip_module msg_logger = { - NULL, NULL, /* prev, next. */ - { "mod-msg-log", 13 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &logging_on_rx_msg, /* on_rx_request() */ - &logging_on_rx_msg, /* on_rx_response() */ - &logging_on_tx_msg, /* on_tx_request. */ - &logging_on_tx_msg, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-msg-log", 13 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &logging_on_rx_msg, /* on_rx_request() */ + &logging_on_rx_msg, /* on_rx_response() */ + &logging_on_tx_msg, /* on_tx_request. */ + &logging_on_tx_msg, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -245,22 +244,22 @@ int main(int argc, char *argv[]) /* Create global endpoint: */ { - const pj_str_t *hostname; - const char *endpt_name; + const pj_str_t *hostname; + const char *endpt_name; - /* Endpoint MUST be assigned a globally unique name. - * The name will be used as the hostname in Warning header. - */ + /* Endpoint MUST be assigned a globally unique name. + * The name will be used as the hostname in Warning header. + */ - /* For this implementation, we'll use hostname for simplicity */ - hostname = pj_gethostname(); - endpt_name = hostname->ptr; + /* For this implementation, we'll use hostname for simplicity */ + hostname = pj_gethostname(); + endpt_name = hostname->ptr; - /* Create the endpoint: */ + /* Create the endpoint: */ - status = pjsip_endpt_create(&cp.factory, endpt_name, - &g_endpt); - PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); + status = pjsip_endpt_create(&cp.factory, endpt_name, + &g_endpt); + PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); } @@ -271,25 +270,25 @@ int main(int argc, char *argv[]) * resolves the address with STUN). */ { - pj_sockaddr addr; - int af = AF; - - pj_sockaddr_init(af, &addr, NULL, (pj_uint16_t)SIP_PORT); - - if (af == pj_AF_INET()) { - status = pjsip_udp_transport_start( g_endpt, &addr.ipv4, NULL, - 1, NULL); - } else if (af == pj_AF_INET6()) { - status = pjsip_udp_transport_start6(g_endpt, &addr.ipv6, NULL, - 1, NULL); - } else { - status = PJ_EAFNOTSUP; - } - - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to start UDP transport", status); - return 1; - } + pj_sockaddr addr; + int af = AF; + + pj_sockaddr_init(af, &addr, NULL, (pj_uint16_t)SIP_PORT); + + if (af == pj_AF_INET()) { + status = pjsip_udp_transport_start( g_endpt, &addr.ipv4, NULL, + 1, NULL); + } else if (af == pj_AF_INET6()) { + status = pjsip_udp_transport_start6(g_endpt, &addr.ipv6, NULL, + 1, NULL); + } else { + status = PJ_EAFNOTSUP; + } + + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to start UDP transport", status); + return 1; + } } @@ -322,17 +321,17 @@ int main(int argc, char *argv[]) * media transmission. */ { - pjsip_inv_callback inv_cb; + pjsip_inv_callback inv_cb; - /* Init the callback for INVITE session: */ - pj_bzero(&inv_cb, sizeof(inv_cb)); - inv_cb.on_state_changed = &call_on_state_changed; - inv_cb.on_new_session = &call_on_forked; - inv_cb.on_media_update = &call_on_media_update; + /* Init the callback for INVITE session: */ + pj_bzero(&inv_cb, sizeof(inv_cb)); + inv_cb.on_state_changed = &call_on_state_changed; + inv_cb.on_new_session = &call_on_forked; + inv_cb.on_media_update = &call_on_media_update; - /* Initialize invite session module: */ - status = pjsip_inv_usage_init(g_endpt, &inv_cb); - PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); + /* Initialize invite session module: */ + status = pjsip_inv_usage_init(g_endpt, &inv_cb); + PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); } /* Initialize 100rel support */ @@ -360,13 +359,13 @@ int main(int argc, char *argv[]) status = pjmedia_endpt_create(&cp.factory, NULL, 1, &g_med_endpt); #else status = pjmedia_endpt_create(&cp.factory, - pjsip_endpt_get_ioqueue(g_endpt), - 0, &g_med_endpt); + pjsip_endpt_get_ioqueue(g_endpt), + 0, &g_med_endpt); #endif PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create pool. */ - pool = pjmedia_endpt_create_pool(g_med_endpt, "Media pool", 512, 512); + pool = pjmedia_endpt_create_pool(g_med_endpt, "Media pool", 512, 512); /* * Add PCMA/PCMU codec to the media endpoint. @@ -409,7 +408,7 @@ int main(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); # endif /* PJMEDIA_HAS_FFMPEG_VID_CODEC */ -#endif /* PJMEDIA_HAS_VIDEO */ +#endif /* PJMEDIA_HAS_VIDEO */ /* Create event manager */ status = pjmedia_event_mgr_create(pool, 0, NULL); @@ -421,152 +420,152 @@ int main(int argc, char *argv[]) * opt to re-use the same media transport for subsequent calls. */ for (i = 0; i < PJ_ARRAY_SIZE(g_med_transport); ++i) { - status = pjmedia_transport_udp_create3(g_med_endpt, AF, NULL, NULL, - RTP_PORT + i*2, 0, - &g_med_transport[i]); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create media transport", status); - return 1; - } - - /* - * Get socket info (address, port) of the media transport. We will - * need this info to create SDP (i.e. the address and port info in - * the SDP). - */ - pjmedia_transport_info_init(&g_med_tpinfo[i]); - pjmedia_transport_get_info(g_med_transport[i], &g_med_tpinfo[i]); - - pj_memcpy(&g_sock_info[i], &g_med_tpinfo[i].sock_info, - sizeof(pjmedia_sock_info)); + status = pjmedia_transport_udp_create3(g_med_endpt, AF, NULL, NULL, + RTP_PORT + i*2, 0, + &g_med_transport[i]); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to create media transport", status); + return 1; + } + + /* + * Get socket info (address, port) of the media transport. We will + * need this info to create SDP (i.e. the address and port info in + * the SDP). + */ + pjmedia_transport_info_init(&g_med_tpinfo[i]); + pjmedia_transport_get_info(g_med_transport[i], &g_med_tpinfo[i]); + + pj_memcpy(&g_sock_info[i], &g_med_tpinfo[i].sock_info, + sizeof(pjmedia_sock_info)); } /* * If URL is specified, then make call immediately. */ if (argc > 1) { - pj_sockaddr hostaddr; - char hostip[PJ_INET6_ADDRSTRLEN+2]; - char temp[80]; - pj_str_t dst_uri = pj_str(argv[1]); - pj_str_t local_uri; - pjsip_dialog *dlg; - pjmedia_sdp_session *local_sdp; - pjsip_tx_data *tdata; - - if (pj_gethostip(AF, &hostaddr) != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to retrieve local host IP", status); - return 1; - } - pj_sockaddr_print(&hostaddr, hostip, sizeof(hostip), 2); - - pj_ansi_sprintf(temp, "", - hostip, SIP_PORT); - local_uri = pj_str(temp); - - /* Create UAC dialog */ - status = pjsip_dlg_create_uac( pjsip_ua_instance(), - &local_uri, /* local URI */ - &local_uri, /* local Contact */ - &dst_uri, /* remote URI */ - &dst_uri, /* remote target */ - &dlg); /* dialog */ - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create UAC dialog", status); - return 1; - } - - /* If we expect the outgoing INVITE to be challenged, then we should - * put the credentials in the dialog here, with something like this: - * - { - pjsip_cred_info cred[1]; - - cred[0].realm = pj_str("sip.server.realm"); - cred[0].scheme = pj_str("digest"); - cred[0].username = pj_str("theuser"); - cred[0].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; - cred[0].data = pj_str("thepassword"); - - pjsip_auth_clt_set_credentials( &dlg->auth_sess, 1, cred); - } - * - */ - - - /* Get the SDP body to be put in the outgoing INVITE, by asking - * media endpoint to create one for us. - */ - status = pjmedia_endpt_create_sdp( g_med_endpt, /* the media endpt */ - dlg->pool, /* pool. */ - MAX_MEDIA_CNT, /* # of streams */ - g_sock_info, /* RTP sock info */ - &local_sdp); /* the SDP result */ - PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); - - - - /* Create the INVITE session, and pass the SDP returned earlier - * as the session's initial capability. - */ - status = pjsip_inv_create_uac( dlg, local_sdp, 0, &g_inv); - PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); - - /* If we want the initial INVITE to travel to specific SIP proxies, - * then we should put the initial dialog's route set here. The final - * route set will be updated once a dialog has been established. - * To set the dialog's initial route set, we do it with something - * like this: - * - { - pjsip_route_hdr route_set; - pjsip_route_hdr *route; - const pj_str_t hname = { "Route", 5 }; - char *uri = "sip:proxy.server;lr"; - - pj_list_init(&route_set); - - route = pjsip_parse_hdr( dlg->pool, &hname, - uri, strlen(uri), - NULL); - PJ_ASSERT_RETURN(route != NULL, 1); - pj_list_push_back(&route_set, route); - - pjsip_dlg_set_route_set(dlg, &route_set); - } - * - * Note that Route URI SHOULD have an ";lr" parameter! - */ - - /* Create initial INVITE request. - * This INVITE request will contain a perfectly good request and - * an SDP body as well. - */ - status = pjsip_inv_invite(g_inv, &tdata); - PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); - - - - /* Send initial INVITE request. - * From now on, the invite session's state will be reported to us - * via the invite session callbacks. - */ - status = pjsip_inv_send_msg(g_inv, tdata); - PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); + pj_sockaddr hostaddr; + char hostip[PJ_INET6_ADDRSTRLEN+2]; + char temp[80]; + pj_str_t dst_uri = pj_str(argv[1]); + pj_str_t local_uri; + pjsip_dialog *dlg; + pjmedia_sdp_session *local_sdp; + pjsip_tx_data *tdata; + + if (pj_gethostip(AF, &hostaddr) != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to retrieve local host IP", status); + return 1; + } + pj_sockaddr_print(&hostaddr, hostip, sizeof(hostip), 2); + + pj_ansi_sprintf(temp, "", + hostip, SIP_PORT); + local_uri = pj_str(temp); + + /* Create UAC dialog */ + status = pjsip_dlg_create_uac( pjsip_ua_instance(), + &local_uri, /* local URI */ + &local_uri, /* local Contact */ + &dst_uri, /* remote URI */ + &dst_uri, /* remote target */ + &dlg); /* dialog */ + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to create UAC dialog", status); + return 1; + } + + /* If we expect the outgoing INVITE to be challenged, then we should + * put the credentials in the dialog here, with something like this: + * + { + pjsip_cred_info cred[1]; + + cred[0].realm = pj_str("sip.server.realm"); + cred[0].scheme = pj_str("digest"); + cred[0].username = pj_str("theuser"); + cred[0].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; + cred[0].data = pj_str("thepassword"); + + pjsip_auth_clt_set_credentials( &dlg->auth_sess, 1, cred); + } + * + */ + + + /* Get the SDP body to be put in the outgoing INVITE, by asking + * media endpoint to create one for us. + */ + status = pjmedia_endpt_create_sdp( g_med_endpt, /* the media endpt */ + dlg->pool, /* pool. */ + MAX_MEDIA_CNT, /* # of streams */ + g_sock_info, /* RTP sock info */ + &local_sdp); /* the SDP result */ + PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); + + + + /* Create the INVITE session, and pass the SDP returned earlier + * as the session's initial capability. + */ + status = pjsip_inv_create_uac( dlg, local_sdp, 0, &g_inv); + PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); + + /* If we want the initial INVITE to travel to specific SIP proxies, + * then we should put the initial dialog's route set here. The final + * route set will be updated once a dialog has been established. + * To set the dialog's initial route set, we do it with something + * like this: + * + { + pjsip_route_hdr route_set; + pjsip_route_hdr *route; + const pj_str_t hname = { "Route", 5 }; + char *uri = "sip:proxy.server;lr"; + + pj_list_init(&route_set); + + route = pjsip_parse_hdr( dlg->pool, &hname, + uri, strlen(uri), + NULL); + PJ_ASSERT_RETURN(route != NULL, 1); + pj_list_push_back(&route_set, route); + + pjsip_dlg_set_route_set(dlg, &route_set); + } + * + * Note that Route URI SHOULD have an ";lr" parameter! + */ + + /* Create initial INVITE request. + * This INVITE request will contain a perfectly good request and + * an SDP body as well. + */ + status = pjsip_inv_invite(g_inv, &tdata); + PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); + + + + /* Send initial INVITE request. + * From now on, the invite session's state will be reported to us + * via the invite session callbacks. + */ + status = pjsip_inv_send_msg(g_inv, tdata); + PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); } else { - /* No URL to make call to */ + /* No URL to make call to */ - PJ_LOG(3,(THIS_FILE, "Ready to accept incoming calls...")); + PJ_LOG(3,(THIS_FILE, "Ready to accept incoming calls...")); } /* Loop until one call is completed */ for (;!g_complete;) { - pj_time_val timeout = {0, 10}; - pjsip_endpt_handle_events(g_endpt, &timeout); + pj_time_val timeout = {0, 10}; + pjsip_endpt_handle_events(g_endpt, &timeout); } /* On exit, dump current memory usage: */ @@ -577,22 +576,22 @@ int main(int argc, char *argv[]) * that get/put frames to the stream. */ if (g_snd_port) - pjmedia_snd_port_destroy(g_snd_port); + pjmedia_snd_port_destroy(g_snd_port); #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) /* Destroy video ports */ if (g_vid_capturer) - pjmedia_vid_port_destroy(g_vid_capturer); + pjmedia_vid_port_destroy(g_vid_capturer); if (g_vid_renderer) - pjmedia_vid_port_destroy(g_vid_renderer); + pjmedia_vid_port_destroy(g_vid_renderer); #endif /* Destroy streams */ if (g_med_stream) - pjmedia_stream_destroy(g_med_stream); + pjmedia_stream_destroy(g_med_stream); #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) if (g_med_vstream) - pjmedia_vid_stream_destroy(g_med_vstream); + pjmedia_vid_stream_destroy(g_med_vstream); /* Deinit ffmpeg codec */ # if defined(PJMEDIA_HAS_FFMPEG_VID_CODEC) && PJMEDIA_HAS_FFMPEG_VID_CODEC!=0 @@ -612,8 +611,8 @@ int main(int argc, char *argv[]) /* Destroy media transports */ for (i = 0; i < MAX_MEDIA_CNT; ++i) { - if (g_med_transport[i]) - pjmedia_transport_close(g_med_transport[i]); + if (g_med_transport[i]) + pjmedia_transport_close(g_med_transport[i]); } /* Destroy event manager */ @@ -621,15 +620,15 @@ int main(int argc, char *argv[]) /* Deinit pjmedia endpoint */ if (g_med_endpt) - pjmedia_endpt_destroy(g_med_endpt); + pjmedia_endpt_destroy(g_med_endpt); /* Deinit pjsip endpoint */ if (g_endpt) - pjsip_endpt_destroy(g_endpt); + pjsip_endpt_destroy(g_endpt); /* Release pool */ if (pool) - pj_pool_release(pool); + pj_pool_release(pool); return 0; } @@ -643,23 +642,23 @@ int main(int argc, char *argv[]) * so that we can quit the application. */ static void call_on_state_changed( pjsip_inv_session *inv, - pjsip_event *e) + pjsip_event *e) { PJ_UNUSED_ARG(e); if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { - PJ_LOG(3,(THIS_FILE, "Call DISCONNECTED [reason=%d (%s)]", - inv->cause, - pjsip_get_status_text(inv->cause)->ptr)); + PJ_LOG(3,(THIS_FILE, "Call DISCONNECTED [reason=%d (%s)]", + inv->cause, + pjsip_get_status_text(inv->cause)->ptr)); - PJ_LOG(3,(THIS_FILE, "One call completed, application quitting...")); - g_complete = 1; + PJ_LOG(3,(THIS_FILE, "One call completed, application quitting...")); + g_complete = 1; } else { - PJ_LOG(3,(THIS_FILE, "Call state changed to %s", - pjsip_inv_state_name(inv->state))); + PJ_LOG(3,(THIS_FILE, "Call state changed to %s", + pjsip_inv_state_name(inv->state))); } } @@ -696,15 +695,15 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) */ if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD) { - if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { - pj_str_t reason = pj_str("Simple UA unable to handle " - "this request"); + if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { + pj_str_t reason = pj_str("Simple UA unable to handle " + "this request"); - pjsip_endpt_respond_stateless( g_endpt, rdata, - 500, &reason, - NULL, NULL); - } - return PJ_TRUE; + pjsip_endpt_respond_stateless( g_endpt, rdata, + 500, &reason, + NULL, NULL); + } + return PJ_TRUE; } @@ -713,52 +712,52 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) */ if (g_inv) { - pj_str_t reason = pj_str("Another call is in progress"); + pj_str_t reason = pj_str("Another call is in progress"); - pjsip_endpt_respond_stateless( g_endpt, rdata, - 500, &reason, - NULL, NULL); - return PJ_TRUE; + pjsip_endpt_respond_stateless( g_endpt, rdata, + 500, &reason, + NULL, NULL); + return PJ_TRUE; } /* Verify that we can handle the request. */ status = pjsip_inv_verify_request(rdata, &options, NULL, NULL, - g_endpt, NULL); + g_endpt, NULL); if (status != PJ_SUCCESS) { - pj_str_t reason = pj_str("Sorry Simple UA can not handle this INVITE"); + pj_str_t reason = pj_str("Sorry Simple UA can not handle this INVITE"); - pjsip_endpt_respond_stateless( g_endpt, rdata, - 500, &reason, - NULL, NULL); - return PJ_TRUE; + pjsip_endpt_respond_stateless( g_endpt, rdata, + 500, &reason, + NULL, NULL); + return PJ_TRUE; } /* * Generate Contact URI */ if (pj_gethostip(AF, &hostaddr) != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to retrieve local host IP", status); - return PJ_TRUE; + app_perror(THIS_FILE, "Unable to retrieve local host IP", status); + return PJ_TRUE; } pj_sockaddr_print(&hostaddr, hostip, sizeof(hostip), 2); pj_ansi_sprintf(temp, "", - hostip, SIP_PORT); + hostip, SIP_PORT); local_uri = pj_str(temp); /* * Create UAS dialog. */ status = pjsip_dlg_create_uas_and_inc_lock( pjsip_ua_instance(), - rdata, - &local_uri, /* contact */ - &dlg); + rdata, + &local_uri, /* contact */ + &dlg); if (status != PJ_SUCCESS) { - pjsip_endpt_respond_stateless(g_endpt, rdata, 500, NULL, - NULL, NULL); - return PJ_TRUE; + pjsip_endpt_respond_stateless(g_endpt, rdata, 500, NULL, + NULL, NULL); + return PJ_TRUE; } /* @@ -766,11 +765,11 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) */ status = pjmedia_endpt_create_sdp( g_med_endpt, rdata->tp_info.pool, - MAX_MEDIA_CNT, g_sock_info, &local_sdp); + MAX_MEDIA_CNT, g_sock_info, &local_sdp); pj_assert(status == PJ_SUCCESS); if (status != PJ_SUCCESS) { - pjsip_dlg_dec_lock(dlg); - return PJ_TRUE; + pjsip_dlg_dec_lock(dlg); + return PJ_TRUE; } @@ -781,8 +780,8 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) status = pjsip_inv_create_uas( dlg, rdata, local_sdp, 0, &g_inv); pj_assert(status == PJ_SUCCESS); if (status != PJ_SUCCESS) { - pjsip_dlg_dec_lock(dlg); - return PJ_TRUE; + pjsip_dlg_dec_lock(dlg); + return PJ_TRUE; } /* @@ -799,8 +798,8 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) * transaction MUST use pjsip_inv_answer(). */ status = pjsip_inv_initial_answer(g_inv, rdata, - 180, - NULL, NULL, &tdata); + 180, + NULL, NULL, &tdata); PJ_ASSERT_RETURN(status == PJ_SUCCESS, PJ_TRUE); @@ -813,9 +812,9 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) * Now create 200 response. */ status = pjsip_inv_answer( g_inv, - 200, NULL, /* st_code and st_text */ - NULL, /* SDP already specified */ - &tdata); + 200, NULL, /* st_code and st_text */ + NULL, /* SDP already specified */ + &tdata); PJ_ASSERT_RETURN(status == PJ_SUCCESS, PJ_TRUE); /* @@ -840,7 +839,7 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) * as soon as SDP negotiation is completed. */ static void call_on_media_update( pjsip_inv_session *inv, - pj_status_t status) + pj_status_t status) { pjmedia_stream_info stream_info; const pjmedia_sdp_session *local_sdp; @@ -849,12 +848,12 @@ static void call_on_media_update( pjsip_inv_session *inv, if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "SDP negotiation has failed", status); + app_perror(THIS_FILE, "SDP negotiation has failed", status); - /* Here we should disconnect call if we're not in the middle - * of initializing an UAS dialog and if this is not a re-INVITE. - */ - return; + /* Here we should disconnect call if we're not in the middle + * of initializing an UAS dialog and if this is not a re-INVITE. + */ + return; } /* Get local and remote SDP. @@ -867,11 +866,11 @@ static void call_on_media_update( pjsip_inv_session *inv, /* Create stream info based on the media audio SDP. */ status = pjmedia_stream_info_from_sdp(&stream_info, inv->dlg->pool, - g_med_endpt, - local_sdp, remote_sdp, 0); + g_med_endpt, + local_sdp, remote_sdp, 0); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE,"Unable to create audio stream info",status); - return; + app_perror(THIS_FILE,"Unable to create audio stream info",status); + return; } /* If required, we can also change some settings in the stream info, @@ -883,17 +882,17 @@ static void call_on_media_update( pjsip_inv_session *inv, * media socket that we created earlier. */ status = pjmedia_stream_create(g_med_endpt, inv->dlg->pool, &stream_info, - g_med_transport[0], NULL, &g_med_stream); + g_med_transport[0], NULL, &g_med_stream); if (status != PJ_SUCCESS) { - app_perror( THIS_FILE, "Unable to create audio stream", status); - return; + app_perror( THIS_FILE, "Unable to create audio stream", status); + return; } /* Start the audio stream */ status = pjmedia_stream_start(g_med_stream); if (status != PJ_SUCCESS) { - app_perror( THIS_FILE, "Unable to start audio stream", status); - return; + app_perror( THIS_FILE, "Unable to start audio stream", status); + return; } /* Start the UDP media transport */ @@ -911,7 +910,7 @@ static void call_on_media_update( pjsip_inv_session *inv, pjmedia_snd_port_create(inv->pool, PJMEDIA_AUD_DEFAULT_CAPTURE_DEV, PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV, - PJMEDIA_PIA_SRATE(&media_port->info),/* clock rate */ + PJMEDIA_PIA_SRATE(&media_port->info),/* clock rate */ PJMEDIA_PIA_CCNT(&media_port->info),/* channel count */ PJMEDIA_PIA_SPF(&media_port->info), /* samples per frame*/ PJMEDIA_PIA_BITS(&media_port->info),/* bits per sample */ @@ -919,14 +918,14 @@ static void call_on_media_update( pjsip_inv_session *inv, &g_snd_port); if (status != PJ_SUCCESS) { - app_perror( THIS_FILE, "Unable to create sound port", status); - PJ_LOG(3,(THIS_FILE, "%d %d %d %d", - PJMEDIA_PIA_SRATE(&media_port->info),/* clock rate */ - PJMEDIA_PIA_CCNT(&media_port->info),/* channel count */ - PJMEDIA_PIA_SPF(&media_port->info), /* samples per frame*/ - PJMEDIA_PIA_BITS(&media_port->info) /* bits per sample */ - )); - return; + app_perror( THIS_FILE, "Unable to create sound port", status); + PJ_LOG(3,(THIS_FILE, "%d %d %d %d", + PJMEDIA_PIA_SRATE(&media_port->info),/* clock rate */ + PJMEDIA_PIA_CCNT(&media_port->info),/* channel count */ + PJMEDIA_PIA_SPF(&media_port->info), /* samples per frame*/ + PJMEDIA_PIA_BITS(&media_port->info) /* bits per sample */ + )); + return; } status = pjmedia_snd_port_connect(g_snd_port, media_port); @@ -938,144 +937,144 @@ static void call_on_media_update( pjsip_inv_session *inv, */ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) if (local_sdp->media_count > 1) { - pjmedia_vid_stream_info vstream_info; - pjmedia_vid_port_param vport_param; - - pjmedia_vid_port_param_default(&vport_param); - - /* Create stream info based on the media video SDP. */ - status = pjmedia_vid_stream_info_from_sdp(&vstream_info, - inv->dlg->pool, g_med_endpt, - local_sdp, remote_sdp, 1); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE,"Unable to create video stream info",status); - return; - } - - /* If required, we can also change some settings in the stream info, - * (such as jitter buffer settings, codec settings, etc) before we - * create the video stream. - */ - - /* Create new video media stream, passing the stream info, and also the - * media socket that we created earlier. - */ - status = pjmedia_vid_stream_create(g_med_endpt, NULL, &vstream_info, - g_med_transport[1], NULL, - &g_med_vstream); - if (status != PJ_SUCCESS) { - app_perror( THIS_FILE, "Unable to create video stream", status); - return; - } - - /* Start the video stream */ - status = pjmedia_vid_stream_start(g_med_vstream); - if (status != PJ_SUCCESS) { - app_perror( THIS_FILE, "Unable to start video stream", status); - return; - } - - /* Start the UDP media transport */ - pjmedia_transport_media_start(g_med_transport[1], 0, 0, 0, 0); - - if (vstream_info.dir & PJMEDIA_DIR_DECODING) { - status = pjmedia_vid_dev_default_param( - inv->pool, PJMEDIA_VID_DEFAULT_RENDER_DEV, - &vport_param.vidparam); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to get default param of video " - "renderer device", status); - return; - } - - /* Get video stream port for decoding direction */ - pjmedia_vid_stream_get_port(g_med_vstream, PJMEDIA_DIR_DECODING, - &media_port); - - /* Set format */ - pjmedia_format_copy(&vport_param.vidparam.fmt, - &media_port->info.fmt); - vport_param.vidparam.dir = PJMEDIA_DIR_RENDER; - vport_param.active = PJ_TRUE; - - /* Create renderer */ - status = pjmedia_vid_port_create(inv->pool, &vport_param, - &g_vid_renderer); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create video renderer device", - status); - return; - } - - /* Connect renderer to media_port */ - status = pjmedia_vid_port_connect(g_vid_renderer, media_port, - PJ_FALSE); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to connect renderer to stream", - status); - return; - } - } - - /* Create capturer */ - if (vstream_info.dir & PJMEDIA_DIR_ENCODING) { - status = pjmedia_vid_dev_default_param( - inv->pool, PJMEDIA_VID_DEFAULT_CAPTURE_DEV, - &vport_param.vidparam); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to get default param of video " - "capture device", status); - return; - } - - /* Get video stream port for decoding direction */ - pjmedia_vid_stream_get_port(g_med_vstream, PJMEDIA_DIR_ENCODING, - &media_port); - - /* Get capturer format from stream info */ - pjmedia_format_copy(&vport_param.vidparam.fmt, - &media_port->info.fmt); - vport_param.vidparam.dir = PJMEDIA_DIR_CAPTURE; - vport_param.active = PJ_TRUE; - - /* Create capturer */ - status = pjmedia_vid_port_create(inv->pool, &vport_param, - &g_vid_capturer); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create video capture device", - status); - return; - } - - /* Connect capturer to media_port */ - status = pjmedia_vid_port_connect(g_vid_capturer, media_port, - PJ_FALSE); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to connect capturer to stream", - status); - return; - } - } - - /* Start streaming */ - if (g_vid_renderer) { - status = pjmedia_vid_port_start(g_vid_renderer); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to start video renderer", - status); - return; - } - } - if (g_vid_capturer) { - status = pjmedia_vid_port_start(g_vid_capturer); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to start video capturer", - status); - return; - } - } + pjmedia_vid_stream_info vstream_info; + pjmedia_vid_port_param vport_param; + + pjmedia_vid_port_param_default(&vport_param); + + /* Create stream info based on the media video SDP. */ + status = pjmedia_vid_stream_info_from_sdp(&vstream_info, + inv->dlg->pool, g_med_endpt, + local_sdp, remote_sdp, 1); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE,"Unable to create video stream info",status); + return; + } + + /* If required, we can also change some settings in the stream info, + * (such as jitter buffer settings, codec settings, etc) before we + * create the video stream. + */ + + /* Create new video media stream, passing the stream info, and also the + * media socket that we created earlier. + */ + status = pjmedia_vid_stream_create(g_med_endpt, NULL, &vstream_info, + g_med_transport[1], NULL, + &g_med_vstream); + if (status != PJ_SUCCESS) { + app_perror( THIS_FILE, "Unable to create video stream", status); + return; + } + + /* Start the video stream */ + status = pjmedia_vid_stream_start(g_med_vstream); + if (status != PJ_SUCCESS) { + app_perror( THIS_FILE, "Unable to start video stream", status); + return; + } + + /* Start the UDP media transport */ + pjmedia_transport_media_start(g_med_transport[1], 0, 0, 0, 0); + + if (vstream_info.dir & PJMEDIA_DIR_DECODING) { + status = pjmedia_vid_dev_default_param( + inv->pool, PJMEDIA_VID_DEFAULT_RENDER_DEV, + &vport_param.vidparam); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to get default param of video " + "renderer device", status); + return; + } + + /* Get video stream port for decoding direction */ + pjmedia_vid_stream_get_port(g_med_vstream, PJMEDIA_DIR_DECODING, + &media_port); + + /* Set format */ + pjmedia_format_copy(&vport_param.vidparam.fmt, + &media_port->info.fmt); + vport_param.vidparam.dir = PJMEDIA_DIR_RENDER; + vport_param.active = PJ_TRUE; + + /* Create renderer */ + status = pjmedia_vid_port_create(inv->pool, &vport_param, + &g_vid_renderer); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to create video renderer device", + status); + return; + } + + /* Connect renderer to media_port */ + status = pjmedia_vid_port_connect(g_vid_renderer, media_port, + PJ_FALSE); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to connect renderer to stream", + status); + return; + } + } + + /* Create capturer */ + if (vstream_info.dir & PJMEDIA_DIR_ENCODING) { + status = pjmedia_vid_dev_default_param( + inv->pool, PJMEDIA_VID_DEFAULT_CAPTURE_DEV, + &vport_param.vidparam); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to get default param of video " + "capture device", status); + return; + } + + /* Get video stream port for decoding direction */ + pjmedia_vid_stream_get_port(g_med_vstream, PJMEDIA_DIR_ENCODING, + &media_port); + + /* Get capturer format from stream info */ + pjmedia_format_copy(&vport_param.vidparam.fmt, + &media_port->info.fmt); + vport_param.vidparam.dir = PJMEDIA_DIR_CAPTURE; + vport_param.active = PJ_TRUE; + + /* Create capturer */ + status = pjmedia_vid_port_create(inv->pool, &vport_param, + &g_vid_capturer); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to create video capture device", + status); + return; + } + + /* Connect capturer to media_port */ + status = pjmedia_vid_port_connect(g_vid_capturer, media_port, + PJ_FALSE); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to connect capturer to stream", + status); + return; + } + } + + /* Start streaming */ + if (g_vid_renderer) { + status = pjmedia_vid_port_start(g_vid_renderer); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to start video renderer", + status); + return; + } + } + if (g_vid_capturer) { + status = pjmedia_vid_port_start(g_vid_capturer); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to start video capturer", + status); + return; + } + } } -#endif /* PJMEDIA_HAS_VIDEO */ +#endif /* PJMEDIA_HAS_VIDEO */ /* Done with media. */ } diff --git a/pjsip-apps/src/samples/sipecho.c b/pjsip-apps/src/samples/sipecho.c index ada7c5d528..3450a1a942 100644 --- a/pjsip-apps/src/samples/sipecho.c +++ b/pjsip-apps/src/samples/sipecho.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -41,27 +40,27 @@ /* Settings */ -#define MAX_CALLS 8 +#define MAX_CALLS 8 typedef struct call_t { - pjsip_inv_session *inv; + pjsip_inv_session *inv; } call_t; static struct app_t { - pj_caching_pool cp; - pj_pool_t *pool; + pj_caching_pool cp; + pj_pool_t *pool; - pjsip_endpoint *sip_endpt; - //pjmedia_endpt *med_endpt; + pjsip_endpoint *sip_endpt; + //pjmedia_endpt *med_endpt; - call_t call[MAX_CALLS]; + call_t call[MAX_CALLS]; - pj_bool_t quit; - pj_thread_t *worker_thread; + pj_bool_t quit; + pj_thread_t *worker_thread; - pj_bool_t enable_msg_logging; + pj_bool_t enable_msg_logging; } app; /* @@ -86,37 +85,37 @@ static pj_bool_t sip_tcp; */ static pjsip_module mod_sipecho = { - NULL, NULL, /* prev, next. */ - { "mod-sipecho", 11 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-sipecho", 11 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; /* Notification on incoming messages */ static pj_bool_t logging_on_rx_msg(pjsip_rx_data *rdata) { if (!app.enable_msg_logging) - return PJ_FALSE; + return PJ_FALSE; PJ_LOG(3,(THIS_FILE, "RX %d bytes %s from %s %s:%d:\n" - "%.*s\n" - "--end msg--", - rdata->msg_info.len, - pjsip_rx_data_get_info(rdata), - rdata->tp_info.transport->type_name, - rdata->pkt_info.src_name, - rdata->pkt_info.src_port, - (int)rdata->msg_info.len, - rdata->msg_info.msg_buf)); + "%.*s\n" + "--end msg--", + rdata->msg_info.len, + pjsip_rx_data_get_info(rdata), + rdata->tp_info.transport->type_name, + rdata->pkt_info.src_name, + rdata->pkt_info.src_port, + (int)rdata->msg_info.len, + rdata->msg_info.msg_buf)); return PJ_FALSE; } @@ -124,37 +123,37 @@ static pj_bool_t logging_on_rx_msg(pjsip_rx_data *rdata) static pj_status_t logging_on_tx_msg(pjsip_tx_data *tdata) { if (!app.enable_msg_logging) - return PJ_SUCCESS; + return PJ_SUCCESS; PJ_LOG(3,(THIS_FILE, "TX %d bytes %s to %s %s:%d:\n" - "%.*s\n" - "--end msg--", - (tdata->buf.cur - tdata->buf.start), - pjsip_tx_data_get_info(tdata), - tdata->tp_info.transport->type_name, - tdata->tp_info.dst_name, - tdata->tp_info.dst_port, - (int)(tdata->buf.cur - tdata->buf.start), - tdata->buf.start)); + "%.*s\n" + "--end msg--", + (tdata->buf.cur - tdata->buf.start), + pjsip_tx_data_get_info(tdata), + tdata->tp_info.transport->type_name, + tdata->tp_info.dst_name, + tdata->tp_info.dst_port, + (int)(tdata->buf.cur - tdata->buf.start), + tdata->buf.start)); return PJ_SUCCESS; } /* The module instance. */ static pjsip_module msg_logger = { - NULL, NULL, /* prev, next. */ - { "mod-msg-log", 13 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &logging_on_rx_msg, /* on_rx_request() */ - &logging_on_rx_msg, /* on_rx_response() */ - &logging_on_tx_msg, /* on_tx_request. */ - &logging_on_tx_msg, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-msg-log", 13 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &logging_on_rx_msg, /* on_rx_request() */ + &logging_on_rx_msg, /* on_rx_response() */ + &logging_on_tx_msg, /* on_tx_request. */ + &logging_on_tx_msg, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -163,8 +162,8 @@ static int worker_proc(void *arg) PJ_UNUSED_ARG(arg); while (!app.quit) { - pj_time_val interval = { 0, 20 }; - pjsip_endpt_handle_events(app.sip_endpt, &interval); + pj_time_val interval = { 0, 20 }; + pjsip_endpt_handle_events(app.sip_endpt, &interval); } return 0; @@ -174,16 +173,16 @@ static void hangup_all(void) { unsigned i; for (i=0; iinv && call->inv->state <= PJSIP_INV_STATE_CONFIRMED) { - pj_status_t status; - pjsip_tx_data *tdata; + if (call->inv && call->inv->state <= PJSIP_INV_STATE_CONFIRMED) { + pj_status_t status; + pjsip_tx_data *tdata; - status = pjsip_inv_end_session(call->inv, PJSIP_SC_BUSY_HERE, NULL, &tdata); - if (status==PJ_SUCCESS && tdata) - pjsip_inv_send_msg(call->inv, tdata); - } + status = pjsip_inv_end_session(call->inv, PJSIP_SC_BUSY_HERE, NULL, &tdata); + if (status==PJ_SUCCESS && tdata) + pjsip_inv_send_msg(call->inv, tdata); + } } } @@ -197,34 +196,34 @@ static void destroy_stack(void) /* Wait until all clear */ hangup_all(); for (i=0; iinv && call->inv->state <= PJSIP_INV_STATE_CONFIRMED) - break; - } + for (j=0; jinv && call->inv->state <= PJSIP_INV_STATE_CONFIRMED) + break; + } - if (j==MAX_CALLS) - return; + if (j==MAX_CALLS) + return; - pj_thread_sleep(WAIT_INTERVAL); + pj_thread_sleep(WAIT_INTERVAL); } app.quit = PJ_TRUE; if (app.worker_thread) { - pj_thread_join(app.worker_thread); - app.worker_thread = NULL; + pj_thread_join(app.worker_thread); + app.worker_thread = NULL; } //if (app.med_endpt) - //pjmedia_endpt_destroy(app.med_endpt); + //pjmedia_endpt_destroy(app.med_endpt); if (app.sip_endpt) - pjsip_endpt_destroy(app.sip_endpt); + pjsip_endpt_destroy(app.sip_endpt); if (app.pool) - pj_pool_release(app.pool); + pj_pool_release(app.pool); dump_pool_usage(THIS_FILE, &app.cp); pj_caching_pool_destroy(&app.cp); @@ -249,16 +248,16 @@ static pj_status_t init_stack() pj_log_set_level(4); pj_sockaddr_init((pj_uint16_t)sip_af, &addr, NULL, (pj_uint16_t)sip_port); if (sip_af == pj_AF_INET()) { - if (sip_tcp) { - CHECK( pjsip_tcp_transport_start( app.sip_endpt, &addr.ipv4, 1, - NULL) ); - } else { - CHECK( pjsip_udp_transport_start( app.sip_endpt, &addr.ipv4, - NULL, 1, NULL) ); - } + if (sip_tcp) { + CHECK( pjsip_tcp_transport_start( app.sip_endpt, &addr.ipv4, 1, + NULL) ); + } else { + CHECK( pjsip_udp_transport_start( app.sip_endpt, &addr.ipv4, + NULL, 1, NULL) ); + } } else if (sip_af == pj_AF_INET6()) { - CHECK( pjsip_udp_transport_start6(app.sip_endpt, &addr.ipv6, - NULL, 1, NULL) ); + CHECK( pjsip_udp_transport_start6(app.sip_endpt, &addr.ipv6, + NULL, 1, NULL) ); } else { CHECK( PJ_EAFNOTSUP ); } @@ -266,7 +265,7 @@ static pj_status_t init_stack() pj_log_set_level(3); status = pjsip_tsx_layer_init_module(app.sip_endpt) || - pjsip_ua_init_module( app.sip_endpt, NULL ); + pjsip_ua_init_module( app.sip_endpt, NULL ); CHECK( status ); pj_bzero(&inv_cb, sizeof(inv_cb)); @@ -276,12 +275,12 @@ static pj_status_t init_stack() inv_cb.on_rx_offer = &call_on_rx_offer; status = pjsip_inv_usage_init(app.sip_endpt, &inv_cb) || - pjsip_100rel_init_module(app.sip_endpt) || - pjsip_endpt_register_module( app.sip_endpt, &mod_sipecho) || - pjsip_endpt_register_module( app.sip_endpt, &msg_logger) || - //pjmedia_endpt_create(&app.cp.factory, - // pjsip_endpt_get_ioqueue(app.sip_endpt), - // 0, &app.med_endpt) || + pjsip_100rel_init_module(app.sip_endpt) || + pjsip_endpt_register_module( app.sip_endpt, &mod_sipecho) || + pjsip_endpt_register_module( app.sip_endpt, &msg_logger) || + //pjmedia_endpt_create(&app.cp.factory, + // pjsip_endpt_get_ioqueue(app.sip_endpt), + // 0, &app.med_endpt) || pj_thread_create(app.pool, "sipecho", &worker_proc, NULL, 0, 0, &app.worker_thread); CHECK( status ); @@ -306,16 +305,16 @@ static pjmedia_sdp_attr * find_remove_sdp_attrs(unsigned *cnt, int i; for (i=0; i<(int)*cnt; ++i) { - unsigned j; - for (j=0; jname, attr_to_remove[j])==0) { - if (!found_attr) found_attr = attr[i]; - pj_array_erase(attr, sizeof(attr[0]), *cnt, i); - --(*cnt); - --i; - break; - } - } + unsigned j; + for (j=0; jname, attr_to_remove[j])==0) { + if (!found_attr) found_attr = attr[i]; + pj_array_erase(attr, sizeof(attr[0]), *cnt, i); + --(*cnt); + --i; + break; + } + } } return found_attr; @@ -338,63 +337,63 @@ static pjmedia_sdp_session *create_answer(int call_num, pj_pool_t *pool, dir_attrs); for (mi=0; mimedia_count; ++mi) { - pjmedia_sdp_media *m = answer->media[mi]; - pjmedia_sdp_attr *m_dir_attr; - pjmedia_sdp_attr *dir_attr; - const char *our_dir = NULL; - pjmedia_sdp_conn *c; - - /* Match direction */ - m_dir_attr = find_remove_sdp_attrs(&m->attr_count, m->attr, - PJ_ARRAY_SIZE(dir_attrs), - dir_attrs); - dir_attr = m_dir_attr ? m_dir_attr : sess_dir_attr; - - if (dir_attr) { - if (pj_strcmp2(&dir_attr->name, "sendonly")==0) - our_dir = "recvonly"; - else if (pj_strcmp2(&dir_attr->name, "inactive")==0) - our_dir = "inactive"; - else if (pj_strcmp2(&dir_attr->name, "recvonly")==0) - our_dir = "inactive"; - - if (our_dir) { - dir_attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); - dir_attr->name = pj_str((char*)our_dir); - m->attr[m->attr_count++] = dir_attr; - } - } - - /* Remove ICE attributes */ - find_remove_sdp_attrs(&m->attr_count, m->attr, PJ_ARRAY_SIZE(ice_attrs), ice_attrs); - - /* Done */ - c = m->conn ? m->conn : answer->conn; - PJ_LOG(3,(THIS_FILE, " Media %d, %.*s: %s <--> %.*s:%d", - mi, (int)m->desc.media.slen, m->desc.media.ptr, - (our_dir ? our_dir : "sendrecv"), - (int)c->addr.slen, c->addr.ptr, m->desc.port)); + pjmedia_sdp_media *m = answer->media[mi]; + pjmedia_sdp_attr *m_dir_attr; + pjmedia_sdp_attr *dir_attr; + const char *our_dir = NULL; + pjmedia_sdp_conn *c; + + /* Match direction */ + m_dir_attr = find_remove_sdp_attrs(&m->attr_count, m->attr, + PJ_ARRAY_SIZE(dir_attrs), + dir_attrs); + dir_attr = m_dir_attr ? m_dir_attr : sess_dir_attr; + + if (dir_attr) { + if (pj_strcmp2(&dir_attr->name, "sendonly")==0) + our_dir = "recvonly"; + else if (pj_strcmp2(&dir_attr->name, "inactive")==0) + our_dir = "inactive"; + else if (pj_strcmp2(&dir_attr->name, "recvonly")==0) + our_dir = "inactive"; + + if (our_dir) { + dir_attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr); + dir_attr->name = pj_str((char*)our_dir); + m->attr[m->attr_count++] = dir_attr; + } + } + + /* Remove ICE attributes */ + find_remove_sdp_attrs(&m->attr_count, m->attr, PJ_ARRAY_SIZE(ice_attrs), ice_attrs); + + /* Done */ + c = m->conn ? m->conn : answer->conn; + PJ_LOG(3,(THIS_FILE, " Media %d, %.*s: %s <--> %.*s:%d", + mi, (int)m->desc.media.slen, m->desc.media.ptr, + (our_dir ? our_dir : "sendrecv"), + (int)c->addr.slen, c->addr.ptr, m->desc.port)); } return answer; } static void call_on_state_changed( pjsip_inv_session *inv, - pjsip_event *e) + pjsip_event *e) { call_t *call = (call_t*)inv->mod_data[mod_sipecho.id]; if (!call) - return; + return; PJ_UNUSED_ARG(e); if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { - PJ_LOG(3,(THIS_FILE, "Call %d: DISCONNECTED [reason=%d (%s)]", - call - app.call, inv->cause, - pjsip_get_status_text(inv->cause)->ptr)); - destroy_call(call); + PJ_LOG(3,(THIS_FILE, "Call %d: DISCONNECTED [reason=%d (%s)]", + call - app.call, inv->cause, + pjsip_get_status_text(inv->cause)->ptr)); + destroy_call(call); } else { - PJ_LOG(3,(THIS_FILE, "Call %d: state changed to %s", - call - app.call, pjsip_inv_state_name(inv->state))); + PJ_LOG(3,(THIS_FILE, "Call %d: state changed to %s", + call - app.call, pjsip_inv_state_name(inv->state))); } } @@ -402,7 +401,7 @@ static void call_on_rx_offer(pjsip_inv_session *inv, const pjmedia_sdp_session * { call_t *call = (call_t*) inv->mod_data[mod_sipecho.id]; pjsip_inv_set_sdp_answer(inv, create_answer((int)(call - app.call), - inv->pool_prov, offer)); + inv->pool_prov, offer)); } static void call_on_forked(pjsip_inv_session *inv, pjsip_event *e) @@ -425,121 +424,121 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) pj_status_t status; PJ_LOG(3,(THIS_FILE, "RX %.*s from %s", - (int)rdata->msg_info.msg->line.req.method.name.slen, - rdata->msg_info.msg->line.req.method.name.ptr, - rdata->pkt_info.src_name)); + (int)rdata->msg_info.msg->line.req.method.name.slen, + rdata->msg_info.msg->line.req.method.name.ptr, + rdata->pkt_info.src_name)); if (rdata->msg_info.msg->line.req.method.id == PJSIP_REGISTER_METHOD) { - /* Let me be a registrar! */ - pjsip_hdr hdr_list, *h; - pjsip_msg *msg; - unsigned expires = PJSIP_EXPIRES_NOT_SPECIFIED; - - pj_list_init(&hdr_list); - msg = rdata->msg_info.msg; - h = (pjsip_hdr*)pjsip_msg_find_hdr(msg, PJSIP_H_EXPIRES, NULL); - if (h) { - expires = ((pjsip_expires_hdr*)h)->ivalue; - pj_list_push_back(&hdr_list, pjsip_hdr_clone(rdata->tp_info.pool, h)); - PJ_LOG(3,(THIS_FILE, " Expires=%d", expires)); - } - if (expires != 0 && expires != PJSIP_EXPIRES_NOT_SPECIFIED) { - h = (pjsip_hdr*)pjsip_msg_find_hdr(msg, PJSIP_H_CONTACT, NULL); - if (h) - pj_list_push_back(&hdr_list, pjsip_hdr_clone(rdata->tp_info.pool, h)); - } - - pjsip_endpt_respond(app.sip_endpt, &mod_sipecho, rdata, 200, NULL, - &hdr_list, NULL, NULL); - return PJ_TRUE; + /* Let me be a registrar! */ + pjsip_hdr hdr_list, *h; + pjsip_msg *msg; + unsigned expires = PJSIP_EXPIRES_NOT_SPECIFIED; + + pj_list_init(&hdr_list); + msg = rdata->msg_info.msg; + h = (pjsip_hdr*)pjsip_msg_find_hdr(msg, PJSIP_H_EXPIRES, NULL); + if (h) { + expires = ((pjsip_expires_hdr*)h)->ivalue; + pj_list_push_back(&hdr_list, pjsip_hdr_clone(rdata->tp_info.pool, h)); + PJ_LOG(3,(THIS_FILE, " Expires=%d", expires)); + } + if (expires != 0 && expires != PJSIP_EXPIRES_NOT_SPECIFIED) { + h = (pjsip_hdr*)pjsip_msg_find_hdr(msg, PJSIP_H_CONTACT, NULL); + if (h) + pj_list_push_back(&hdr_list, pjsip_hdr_clone(rdata->tp_info.pool, h)); + } + + pjsip_endpt_respond(app.sip_endpt, &mod_sipecho, rdata, 200, NULL, + &hdr_list, NULL, NULL); + return PJ_TRUE; } if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD) { - if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { - pj_str_t reason = pj_str("Go away"); - pjsip_endpt_respond_stateless( app.sip_endpt, rdata, - 400, &reason, - NULL, NULL); - } - return PJ_TRUE; + if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { + pj_str_t reason = pj_str("Go away"); + pjsip_endpt_respond_stateless( app.sip_endpt, rdata, + 400, &reason, + NULL, NULL); + } + return PJ_TRUE; } sdp_info = pjsip_rdata_get_sdp_info(rdata); if (!sdp_info || !sdp_info->sdp) { - pj_str_t reason = pj_str("Require valid offer"); - pjsip_endpt_respond_stateless( app.sip_endpt, rdata, - 400, &reason, - NULL, NULL); + pj_str_t reason = pj_str("Require valid offer"); + pjsip_endpt_respond_stateless( app.sip_endpt, rdata, + 400, &reason, + NULL, NULL); } for (i=0; i", hostip, sip_port); local_uri = pj_str(temp); status = pjsip_dlg_create_uas_and_inc_lock( pjsip_ua_instance(), rdata, - &local_uri, &dlg); + &local_uri, &dlg); if (status == PJ_SUCCESS) - answer = create_answer((int)(call-app.call), dlg->pool, sdp_info->sdp); + answer = create_answer((int)(call-app.call), dlg->pool, sdp_info->sdp); if (status == PJ_SUCCESS) - status = pjsip_inv_create_uas( dlg, rdata, answer, 0, &call->inv); + status = pjsip_inv_create_uas( dlg, rdata, answer, 0, &call->inv); if (dlg) - pjsip_dlg_dec_lock(dlg); + pjsip_dlg_dec_lock(dlg); if (status == PJ_SUCCESS) - status = pjsip_inv_initial_answer(call->inv, rdata, 100, - NULL, NULL, &tdata); + status = pjsip_inv_initial_answer(call->inv, rdata, 100, + NULL, NULL, &tdata); if (status == PJ_SUCCESS) - status = pjsip_inv_send_msg(call->inv, tdata); + status = pjsip_inv_send_msg(call->inv, tdata); if (status == PJ_SUCCESS) - status = pjsip_inv_answer(call->inv, 180, NULL, - NULL, &tdata); + status = pjsip_inv_answer(call->inv, 180, NULL, + NULL, &tdata); if (status == PJ_SUCCESS) - status = pjsip_inv_send_msg(call->inv, tdata); + status = pjsip_inv_send_msg(call->inv, tdata); if (status == PJ_SUCCESS) - status = pjsip_inv_answer(call->inv, 200, NULL, - NULL, &tdata); + status = pjsip_inv_answer(call->inv, 200, NULL, + NULL, &tdata); if (status == PJ_SUCCESS) - status = pjsip_inv_send_msg(call->inv, tdata); + status = pjsip_inv_send_msg(call->inv, tdata); if (status != PJ_SUCCESS) { - pjsip_endpt_respond_stateless( app.sip_endpt, rdata, - 500, NULL, NULL, NULL); - destroy_call(call); + pjsip_endpt_respond_stateless( app.sip_endpt, rdata, + 500, NULL, NULL, NULL); + destroy_call(call); } else { - call->inv->mod_data[mod_sipecho.id] = call; + call->inv->mod_data[mod_sipecho.id] = call; } return PJ_TRUE; } static void call_on_media_update( pjsip_inv_session *inv, - pj_status_t status) + pj_status_t status) { PJ_UNUSED_ARG(inv); PJ_UNUSED_ARG(status); @@ -565,10 +564,10 @@ static void usage() int main(int argc, char *argv[]) { struct pj_getopt_option long_options[] = { - { "local-port", 1, 0, 'p' }, - { "tcp", 0, 0, 't' }, - { "ipv6", 0, 0, '6' }, - { "help", 0, 0, 'h' } + { "local-port", 1, 0, 'p' }, + { "tcp", 0, 0, 't' }, + { "ipv6", 0, 0, '6' }, + { "help", 0, 0, 'h' } }; int c, option_index; pj_status_t status; @@ -584,94 +583,94 @@ int main(int argc, char *argv[]) while ((c = pj_getopt_long(argc, argv, "p:t6h", long_options, &option_index)) != -1) { - switch (c) { - case 'p': - sip_port = atoi(pj_optarg); - break; - case 't': - sip_tcp = PJ_TRUE; - break; - case 'h': - usage(); - return 0; - case '6': - sip_af = pj_AF_INET6(); - break; - default: - PJ_LOG(1,(THIS_FILE, - "Argument \"%s\" is not valid. Use --help to see help", - argv[pj_optind-1])); - return -1; - } + switch (c) { + case 'p': + sip_port = atoi(pj_optarg); + break; + case 't': + sip_tcp = PJ_TRUE; + break; + case 'h': + usage(); + return 0; + case '6': + sip_af = pj_AF_INET6(); + break; + default: + PJ_LOG(1,(THIS_FILE, + "Argument \"%s\" is not valid. Use --help to see help", + argv[pj_optind-1])); + return -1; + } } if ((status=init_stack()) != PJ_SUCCESS) - goto on_error; + goto on_error; /* If URL is specified, then make call immediately. */ if (pj_optind != argc) { - pj_sockaddr hostaddr; - char hostip[PJ_INET6_ADDRSTRLEN+2]; - char temp[80]; - call_t *call; - pj_str_t dst_uri = pj_str(argv[pj_optind]); - pj_str_t local_uri; - pjsip_dialog *dlg; - pjsip_tx_data *tdata; + pj_sockaddr hostaddr; + char hostip[PJ_INET6_ADDRSTRLEN+2]; + char temp[80]; + call_t *call; + pj_str_t dst_uri = pj_str(argv[pj_optind]); + pj_str_t local_uri; + pjsip_dialog *dlg; + pjsip_tx_data *tdata; - CHECK( pj_gethostip(sip_af, &hostaddr) ); - pj_sockaddr_print(&hostaddr, hostip, sizeof(hostip), 2); + CHECK( pj_gethostip(sip_af, &hostaddr) ); + pj_sockaddr_print(&hostaddr, hostip, sizeof(hostip), 2); - pj_ansi_sprintf(temp, "", - hostip, sip_port); - local_uri = pj_str(temp); + pj_ansi_sprintf(temp, "", + hostip, sip_port); + local_uri = pj_str(temp); - call = &app.call[0]; + call = &app.call[0]; - CHECK( pjsip_dlg_create_uac( pjsip_ua_instance(), - &local_uri, /* local URI */ - &local_uri, /* local Contact */ - &dst_uri, /* remote URI */ - &dst_uri, /* remote target */ - &dlg) ); /* dialog */ + CHECK( pjsip_dlg_create_uac( pjsip_ua_instance(), + &local_uri, /* local URI */ + &local_uri, /* local Contact */ + &dst_uri, /* remote URI */ + &dst_uri, /* remote target */ + &dlg) ); /* dialog */ - CHECK( pjsip_inv_create_uac( dlg, NULL, 0, &call->inv) ); + CHECK( pjsip_inv_create_uac( dlg, NULL, 0, &call->inv) ); - call->inv->mod_data[mod_sipecho.id] = call; + call->inv->mod_data[mod_sipecho.id] = call; - CHECK( pjsip_inv_invite(call->inv, &tdata) ); - if (status != PJ_SUCCESS) goto on_error; + CHECK( pjsip_inv_invite(call->inv, &tdata) ); + if (status != PJ_SUCCESS) goto on_error; - CHECK( pjsip_inv_send_msg(call->inv, tdata) ); - if (status != PJ_SUCCESS) goto on_error; + CHECK( pjsip_inv_send_msg(call->inv, tdata) ); + if (status != PJ_SUCCESS) goto on_error; - puts("Press ENTER to quit..."); + puts("Press ENTER to quit..."); } else { - puts("Ready for incoming calls. Press ENTER to quit..."); + puts("Ready for incoming calls. Press ENTER to quit..."); } for (;;) { - char s[10]; - - printf("\nMenu:\n" - " h Hangup all calls\n" - " l %s message logging\n" - " q Quit\n", - (app.enable_msg_logging? "Disable" : "Enable")); - - if (fgets(s, sizeof(s), stdin) == NULL) - continue; - - if (s[0]=='q') - break; - switch (s[0]) { - case 'l': - app.enable_msg_logging = !app.enable_msg_logging; - break; - case 'h': - hangup_all(); - break; - } + char s[10]; + + printf("\nMenu:\n" + " h Hangup all calls\n" + " l %s message logging\n" + " q Quit\n", + (app.enable_msg_logging? "Disable" : "Enable")); + + if (fgets(s, sizeof(s), stdin) == NULL) + continue; + + if (s[0]=='q') + break; + switch (s[0]) { + case 'l': + app.enable_msg_logging = !app.enable_msg_logging; + break; + case 'h': + hangup_all(); + break; + } } destroy_stack(); diff --git a/pjsip-apps/src/samples/siprtp.c b/pjsip-apps/src/samples/siprtp.c index 4fb7f6705a..d55ede0748 100644 --- a/pjsip-apps/src/samples/siprtp.c +++ b/pjsip-apps/src/samples/siprtp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,10 +23,10 @@ /* Usage */ static const char *USAGE = -" PURPOSE: \n" +" PURPOSE: \n" " This program establishes SIP INVITE session and media, and calculate \n" -" the media quality (packet lost, jitter, rtt, etc.). Unlike normal \n" -" pjmedia applications, this program bypasses all pjmedia stream \n" +" the media quality (packet lost, jitter, rtt, etc.). Unlike normal \n" +" pjmedia applications, this program bypasses all pjmedia stream \n" " framework and transmit encoded RTP packets manually using own thread. \n" "\n" " USAGE:\n" @@ -92,20 +91,20 @@ static const char *USAGE = # error "High resolution timer is needed for this sample" #endif -#define THIS_FILE "siprtp.c" -#define MAX_CALLS 1024 -#define RTP_START_PORT 4000 +#define THIS_FILE "siprtp.c" +#define MAX_CALLS 1024 +#define RTP_START_PORT 4000 /* Codec descriptor: */ struct codec { - unsigned pt; - char* name; - unsigned clock_rate; - unsigned bit_rate; - unsigned ptime; - char* description; + unsigned pt; + char* name; + unsigned clock_rate; + unsigned bit_rate; + unsigned ptime; + char* description; }; @@ -113,31 +112,31 @@ struct codec struct media_stream { /* Static: */ - unsigned call_index; /* Call owner. */ - unsigned media_index; /* Media index in call. */ - pjmedia_transport *transport; /* To send/recv RTP/RTCP */ + unsigned call_index; /* Call owner. */ + unsigned media_index; /* Media index in call. */ + pjmedia_transport *transport; /* To send/recv RTP/RTCP */ /* Active? */ - pj_bool_t active; /* Non-zero if is in call. */ + pj_bool_t active; /* Non-zero if is in call. */ /* Current stream info: */ - pjmedia_stream_info si; /* Current stream info. */ + pjmedia_stream_info si; /* Current stream info. */ /* More info: */ - unsigned clock_rate; /* clock rate */ - unsigned samples_per_frame; /* samples per frame */ - unsigned bytes_per_frame; /* frame size. */ + unsigned clock_rate; /* clock rate */ + unsigned samples_per_frame; /* samples per frame */ + unsigned bytes_per_frame; /* frame size. */ /* RTP session: */ - pjmedia_rtp_session out_sess; /* outgoing RTP session */ - pjmedia_rtp_session in_sess; /* incoming RTP session */ + pjmedia_rtp_session out_sess; /* outgoing RTP session */ + pjmedia_rtp_session in_sess; /* incoming RTP session */ /* RTCP stats: */ - pjmedia_rtcp_session rtcp; /* incoming RTCP session. */ + pjmedia_rtcp_session rtcp; /* incoming RTCP session. */ /* Thread: */ - pj_bool_t thread_quit_flag; /* Stop media thread. */ - pj_thread_t *thread; /* Media thread. */ + pj_bool_t thread_quit_flag; /* Stop media thread. */ + pj_thread_t *thread; /* Media thread. */ }; @@ -146,52 +145,52 @@ struct media_stream */ struct call { - unsigned index; - pjsip_inv_session *inv; - unsigned media_count; - struct media_stream media[1]; - pj_time_val start_time; - pj_time_val response_time; - pj_time_val connect_time; - - pj_timer_entry d_timer; /**< Disconnect timer. */ + unsigned index; + pjsip_inv_session *inv; + unsigned media_count; + struct media_stream media[1]; + pj_time_val start_time; + pj_time_val response_time; + pj_time_val connect_time; + + pj_timer_entry d_timer; /**< Disconnect timer. */ }; /* Application's global variables */ static struct app { - unsigned max_calls; - unsigned call_gap; - pj_bool_t call_report; - unsigned uac_calls; - unsigned duration; - pj_bool_t auto_quit; - unsigned thread_count; - int sip_port; - int rtp_start_port; - pj_str_t local_addr; - pj_str_t local_uri; - pj_str_t local_contact; + unsigned max_calls; + unsigned call_gap; + pj_bool_t call_report; + unsigned uac_calls; + unsigned duration; + pj_bool_t auto_quit; + unsigned thread_count; + int sip_port; + int rtp_start_port; + pj_str_t local_addr; + pj_str_t local_uri; + pj_str_t local_contact; - int app_log_level; - int log_level; - char *log_filename; - char *report_filename; + int app_log_level; + int log_level; + char *log_filename; + char *report_filename; - struct codec audio_codec; + struct codec audio_codec; - pj_str_t uri_to_call; + pj_str_t uri_to_call; - pj_caching_pool cp; - pj_pool_t *pool; + pj_caching_pool cp; + pj_pool_t *pool; - pjsip_endpoint *sip_endpt; - pj_bool_t thread_quit; - pj_thread_t *sip_thread[1]; + pjsip_endpoint *sip_endpt; + pj_bool_t thread_quit; + pj_thread_t *sip_thread[1]; - pjmedia_endpt *med_endpt; - struct call call[MAX_CALLS]; + pjmedia_endpt *med_endpt; + struct call call[MAX_CALLS]; } app; @@ -202,11 +201,11 @@ static struct app /* Callback to be called when SDP negotiation is done in the call: */ static void call_on_media_update( pjsip_inv_session *inv, - pj_status_t status); + pj_status_t status); /* Callback to be called when invite session's state has changed: */ static void call_on_state_changed( pjsip_inv_session *inv, - pjsip_event *e); + pjsip_event *e); /* Callback to be called when dialog has forked: */ static void call_on_forked(pjsip_inv_session *inv, pjsip_event *e); @@ -219,8 +218,8 @@ static int sip_worker_thread(void *arg); /* Create SDP for call */ static pj_status_t create_sdp( pj_pool_t *pool, - struct call *call, - pjmedia_sdp_session **p_sdp); + struct call *call, + pjmedia_sdp_session **p_sdp); /* Hangup call */ static void hangup_call(unsigned index); @@ -239,7 +238,7 @@ static void on_rx_rtcp(void *user_data, void *pkt, pj_ssize_t size); /* Display error */ static void app_perror(const char *sender, const char *title, - pj_status_t status); + pj_status_t status); /* Print call */ static void print_call(int call_index); @@ -252,19 +251,19 @@ static void print_call(int call_index); */ static pjsip_module mod_siprtp = { - NULL, NULL, /* prev, next. */ - { "mod-siprtpapp", 13 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-siprtpapp", 13 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -299,45 +298,45 @@ static pj_status_t init_sip() /* Create the endpoint: */ status = pjsip_endpt_create(&app.cp.factory, pj_gethostname()->ptr, - &app.sip_endpt); + &app.sip_endpt); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); /* Add UDP transport. */ { - pj_sockaddr_in addr; - pjsip_host_port addrname; - pjsip_transport *tp; - - pj_bzero(&addr, sizeof(addr)); - addr.sin_family = pj_AF_INET(); - addr.sin_addr.s_addr = 0; - addr.sin_port = pj_htons((pj_uint16_t)app.sip_port); - - if (app.local_addr.slen) { - - addrname.host = app.local_addr; - addrname.port = app.sip_port; - - status = pj_sockaddr_in_init(&addr, &app.local_addr, - (pj_uint16_t)app.sip_port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to resolve IP interface", status); - return status; - } - } - - status = pjsip_udp_transport_start( app.sip_endpt, &addr, - (app.local_addr.slen ? &addrname:NULL), - 1, &tp); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to start UDP transport", status); - return status; - } - - PJ_LOG(3,(THIS_FILE, "SIP UDP listening on %.*s:%d", - (int)tp->local_name.host.slen, tp->local_name.host.ptr, - tp->local_name.port)); + pj_sockaddr_in addr; + pjsip_host_port addrname; + pjsip_transport *tp; + + pj_bzero(&addr, sizeof(addr)); + addr.sin_family = pj_AF_INET(); + addr.sin_addr.s_addr = 0; + addr.sin_port = pj_htons((pj_uint16_t)app.sip_port); + + if (app.local_addr.slen) { + + addrname.host = app.local_addr; + addrname.port = app.sip_port; + + status = pj_sockaddr_in_init(&addr, &app.local_addr, + (pj_uint16_t)app.sip_port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to resolve IP interface", status); + return status; + } + } + + status = pjsip_udp_transport_start( app.sip_endpt, &addr, + (app.local_addr.slen ? &addrname:NULL), + 1, &tp); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to start UDP transport", status); + return status; + } + + PJ_LOG(3,(THIS_FILE, "SIP UDP listening on %.*s:%d", + (int)tp->local_name.host.slen, tp->local_name.host.ptr, + tp->local_name.port)); } /* @@ -357,17 +356,17 @@ static pj_status_t init_sip() /* Init invite session module. */ { - pjsip_inv_callback inv_cb; + pjsip_inv_callback inv_cb; - /* Init the callback for INVITE session: */ - pj_bzero(&inv_cb, sizeof(inv_cb)); - inv_cb.on_state_changed = &call_on_state_changed; - inv_cb.on_new_session = &call_on_forked; - inv_cb.on_media_update = &call_on_media_update; + /* Init the callback for INVITE session: */ + pj_bzero(&inv_cb, sizeof(inv_cb)); + inv_cb.on_state_changed = &call_on_state_changed; + inv_cb.on_new_session = &call_on_forked; + inv_cb.on_media_update = &call_on_media_update; - /* Initialize invite session module: */ - status = pjsip_inv_usage_init(app.sip_endpt, &inv_cb); - PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); + /* Initialize invite session module: */ + status = pjsip_inv_usage_init(app.sip_endpt, &inv_cb); + PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); } /* Register our module to receive incoming requests. */ @@ -376,7 +375,7 @@ static pj_status_t init_sip() /* Init calls */ for (i=0; itransport); - if (status == PJ_SUCCESS) { - rtp_port += 2; - break; - } - } - } - - if (status != PJ_SUCCESS) - goto on_error; + unsigned j; + + /* Create transport for each media in the call */ + for (j=0; jtransport); + if (status == PJ_SUCCESS) { + rtp_port += 2; + break; + } + } + } + + if (status != PJ_SUCCESS) + goto on_error; } /* Done */ @@ -490,20 +489,20 @@ static void destroy_media() unsigned i; for (i=0; itransport) { - pjmedia_transport_close(m->transport); - m->transport = NULL; - } - } + unsigned j; + for (j=0; jtransport) { + pjmedia_transport_close(m->transport); + m->transport = NULL; + } + } } if (app.med_endpt) { - pjmedia_endpt_destroy(app.med_endpt); - app.med_endpt = NULL; + pjmedia_endpt_destroy(app.med_endpt); + app.med_endpt = NULL; } } @@ -523,25 +522,25 @@ static pj_status_t make_call(const pj_str_t *dst_uri) /* Find unused call slot */ for (i=0; iinv); if (status != PJ_SUCCESS) { - pjsip_dlg_terminate(dlg); - ++app.uac_calls; - return status; + pjsip_dlg_terminate(dlg); + ++app.uac_calls; + return status; } @@ -597,16 +596,16 @@ static void process_incoming_call(pjsip_rx_data *rdata) /* Find free call slot */ for (i=0; ipool, rdata, &res_addr); - status = pjsip_endpt_send_response(app.sip_endpt, &res_addr, tdata, - NULL, NULL); - if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(tdata); - - } else { - - /* Respond with 500 (Internal Server Error) */ - pjsip_endpt_respond_stateless(app.sip_endpt, rdata, 500, NULL, - NULL, NULL); - } - - return; + /* + * No we can't handle the incoming INVITE request. + */ + if (tdata) { + pjsip_response_addr res_addr; + + pjsip_get_response_addr(tdata->pool, rdata, &res_addr); + status = pjsip_endpt_send_response(app.sip_endpt, &res_addr, tdata, + NULL, NULL); + if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(tdata); + + } else { + + /* Respond with 500 (Internal Server Error) */ + pjsip_endpt_respond_stateless(app.sip_endpt, rdata, 500, NULL, + NULL, NULL); + } + + return; } /* Create UAS dialog */ status = pjsip_dlg_create_uas_and_inc_lock( pjsip_ua_instance(), rdata, - &app.local_contact, &dlg); + &app.local_contact, &dlg); if (status != PJ_SUCCESS) { - const pj_str_t reason = pj_str("Unable to create dialog"); - pjsip_endpt_respond_stateless( app.sip_endpt, rdata, - 500, &reason, - NULL, NULL); - return; + const pj_str_t reason = pj_str("Unable to create dialog"); + pjsip_endpt_respond_stateless( app.sip_endpt, rdata, + 500, &reason, + NULL, NULL); + return; } /* Create SDP */ @@ -654,10 +653,10 @@ static void process_incoming_call(pjsip_rx_data *rdata) /* Create UAS invite session */ status = pjsip_inv_create_uas( dlg, rdata, sdp, 0, &call->inv); if (status != PJ_SUCCESS) { - pjsip_dlg_create_response(dlg, rdata, 500, NULL, &tdata); - pjsip_dlg_send_response(dlg, pjsip_rdata_get_tsx(rdata), tdata); - pjsip_dlg_dec_lock(dlg); - return; + pjsip_dlg_create_response(dlg, rdata, 500, NULL, &tdata); + pjsip_dlg_send_response(dlg, pjsip_rdata_get_tsx(rdata), tdata); + pjsip_dlg_dec_lock(dlg); + return; } /* Invite session has been created, decrement & release dialog lock */ @@ -673,16 +672,16 @@ static void process_incoming_call(pjsip_rx_data *rdata) /* Create 200 response .*/ status = pjsip_inv_initial_answer(call->inv, rdata, 200, - NULL, NULL, &tdata); + NULL, NULL, &tdata); if (status != PJ_SUCCESS) { - status = pjsip_inv_initial_answer(call->inv, rdata, - PJSIP_SC_NOT_ACCEPTABLE, - NULL, NULL, &tdata); - if (status == PJ_SUCCESS) - pjsip_inv_send_msg(call->inv, tdata); - else - pjsip_inv_terminate(call->inv, 500, PJ_FALSE); - return; + status = pjsip_inv_initial_answer(call->inv, rdata, + PJSIP_SC_NOT_ACCEPTABLE, + NULL, NULL, &tdata); + if (status == PJ_SUCCESS) + pjsip_inv_send_msg(call->inv, tdata); + else + pjsip_inv_terminate(call->inv, 500, PJ_FALSE); + return; } @@ -710,15 +709,15 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) { /* Ignore strandled ACKs (must not send respone */ if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) - return PJ_FALSE; + return PJ_FALSE; /* Respond (statelessly) any non-INVITE requests with 500 */ if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD) { - pj_str_t reason = pj_str("Unsupported Operation"); - pjsip_endpt_respond_stateless( app.sip_endpt, rdata, - 500, &reason, - NULL, NULL); - return PJ_TRUE; + pj_str_t reason = pj_str("Unsupported Operation"); + pjsip_endpt_respond_stateless( app.sip_endpt, rdata, + 500, &reason, + NULL, NULL); + return PJ_TRUE; } /* Handle incoming INVITE */ @@ -731,7 +730,7 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) /* Callback timer to disconnect call (limiting call duration) */ static void timer_disconnect_call( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { struct call *call = (struct call *)(entry->user_data); @@ -744,77 +743,77 @@ static void timer_disconnect_call( pj_timer_heap_t *timer_heap, /* Callback to be called when invite session's state has changed: */ static void call_on_state_changed( pjsip_inv_session *inv, - pjsip_event *e) + pjsip_event *e) { struct call *call = (struct call *)inv->mod_data[mod_siprtp.id]; PJ_UNUSED_ARG(e); if (!call) - return; + return; if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { - - pj_time_val null_time = {0, 0}; + + pj_time_val null_time = {0, 0}; - if (call->d_timer.id != 0) { - pjsip_endpt_cancel_timer(app.sip_endpt, &call->d_timer); - call->d_timer.id = 0; - } + if (call->d_timer.id != 0) { + pjsip_endpt_cancel_timer(app.sip_endpt, &call->d_timer); + call->d_timer.id = 0; + } - PJ_LOG(3,(THIS_FILE, "Call #%d disconnected. Reason=%d (%.*s)", - call->index, - inv->cause, - (int)inv->cause_text.slen, - inv->cause_text.ptr)); + PJ_LOG(3,(THIS_FILE, "Call #%d disconnected. Reason=%d (%.*s)", + call->index, + inv->cause, + (int)inv->cause_text.slen, + inv->cause_text.ptr)); - if (app.call_report) { - PJ_LOG(3,(THIS_FILE, "Call #%d statistics:", call->index)); - print_call(call->index); - } + if (app.call_report) { + PJ_LOG(3,(THIS_FILE, "Call #%d statistics:", call->index)); + print_call(call->index); + } - call->inv = NULL; - inv->mod_data[mod_siprtp.id] = NULL; + call->inv = NULL; + inv->mod_data[mod_siprtp.id] = NULL; - destroy_call_media(call->index); + destroy_call_media(call->index); - call->start_time = null_time; - call->response_time = null_time; - call->connect_time = null_time; + call->start_time = null_time; + call->response_time = null_time; + call->connect_time = null_time; - ++app.uac_calls; + ++app.uac_calls; } else if (inv->state == PJSIP_INV_STATE_CONFIRMED) { - pj_time_val t; + pj_time_val t; - pj_gettimeofday(&call->connect_time); - if (call->response_time.sec == 0) - call->response_time = call->connect_time; + pj_gettimeofday(&call->connect_time); + if (call->response_time.sec == 0) + call->response_time = call->connect_time; - t = call->connect_time; - PJ_TIME_VAL_SUB(t, call->start_time); + t = call->connect_time; + PJ_TIME_VAL_SUB(t, call->start_time); - PJ_LOG(3,(THIS_FILE, "Call #%d connected in %d ms", call->index, - PJ_TIME_VAL_MSEC(t))); + PJ_LOG(3,(THIS_FILE, "Call #%d connected in %d ms", call->index, + PJ_TIME_VAL_MSEC(t))); - if (app.duration != 0) { - call->d_timer.id = 1; - call->d_timer.user_data = call; - call->d_timer.cb = &timer_disconnect_call; + if (app.duration != 0) { + call->d_timer.id = 1; + call->d_timer.user_data = call; + call->d_timer.cb = &timer_disconnect_call; - t.sec = app.duration; - t.msec = 0; + t.sec = app.duration; + t.msec = 0; - pjsip_endpt_schedule_timer(app.sip_endpt, &call->d_timer, &t); - } + pjsip_endpt_schedule_timer(app.sip_endpt, &call->d_timer, &t); + } - } else if ( inv->state == PJSIP_INV_STATE_EARLY || - inv->state == PJSIP_INV_STATE_CONNECTING) { + } else if ( inv->state == PJSIP_INV_STATE_EARLY || + inv->state == PJSIP_INV_STATE_CONNECTING) { - if (call->response_time.sec == 0) - pj_gettimeofday(&call->response_time); + if (call->response_time.sec == 0) + pj_gettimeofday(&call->response_time); } } @@ -822,7 +821,7 @@ static void call_on_state_changed( pjsip_inv_session *inv, /* Utility */ static void app_perror(const char *sender, const char *title, - pj_status_t status) + pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; @@ -837,8 +836,8 @@ static int sip_worker_thread(void *arg) PJ_UNUSED_ARG(arg); while (!app.thread_quit) { - pj_time_val timeout = {0, 10}; - pjsip_endpt_handle_events(app.sip_endpt, &timeout); + pj_time_val timeout = {0, 10}; + pjsip_endpt_handle_events(app.sip_endpt, &timeout); } return 0; @@ -852,48 +851,48 @@ static pj_status_t init_options(int argc, char *argv[]) static char local_uri[64]; enum { OPT_START, - OPT_APP_LOG_LEVEL, OPT_LOG_FILE, - OPT_A_PT, OPT_A_NAME, OPT_A_CLOCK, OPT_A_BITRATE, OPT_A_PTIME, - OPT_REPORT_FILE }; + OPT_APP_LOG_LEVEL, OPT_LOG_FILE, + OPT_A_PT, OPT_A_NAME, OPT_A_CLOCK, OPT_A_BITRATE, OPT_A_PTIME, + OPT_REPORT_FILE }; struct pj_getopt_option long_options[] = { - { "count", 1, 0, 'c' }, - { "gap", 1, 0, 'g' }, - { "call-report", 0, 0, 'R' }, - { "duration", 1, 0, 'd' }, - { "auto-quit", 0, 0, 'q' }, - { "local-port", 1, 0, 'p' }, - { "rtp-port", 1, 0, 'r' }, - { "ip-addr", 1, 0, 'i' }, - - { "log-level", 1, 0, 'l' }, - { "app-log-level", 1, 0, OPT_APP_LOG_LEVEL }, - { "log-file", 1, 0, OPT_LOG_FILE }, - - { "report-file", 1, 0, OPT_REPORT_FILE }, - - /* Don't support this anymore, see comments in USAGE above. - { "a-pt", 1, 0, OPT_A_PT }, - { "a-name", 1, 0, OPT_A_NAME }, - { "a-clock", 1, 0, OPT_A_CLOCK }, - { "a-bitrate", 1, 0, OPT_A_BITRATE }, - { "a-ptime", 1, 0, OPT_A_PTIME }, - */ - - { NULL, 0, 0, 0 }, + { "count", 1, 0, 'c' }, + { "gap", 1, 0, 'g' }, + { "call-report", 0, 0, 'R' }, + { "duration", 1, 0, 'd' }, + { "auto-quit", 0, 0, 'q' }, + { "local-port", 1, 0, 'p' }, + { "rtp-port", 1, 0, 'r' }, + { "ip-addr", 1, 0, 'i' }, + + { "log-level", 1, 0, 'l' }, + { "app-log-level", 1, 0, OPT_APP_LOG_LEVEL }, + { "log-file", 1, 0, OPT_LOG_FILE }, + + { "report-file", 1, 0, OPT_REPORT_FILE }, + + /* Don't support this anymore, see comments in USAGE above. + { "a-pt", 1, 0, OPT_A_PT }, + { "a-name", 1, 0, OPT_A_NAME }, + { "a-clock", 1, 0, OPT_A_CLOCK }, + { "a-bitrate", 1, 0, OPT_A_BITRATE }, + { "a-ptime", 1, 0, OPT_A_PTIME }, + */ + + { NULL, 0, 0, 0 }, }; int c; int option_index; /* Get local IP address for the default IP address */ { - const pj_str_t *hostname; - pj_sockaddr_in tmp_addr; + const pj_str_t *hostname; + pj_sockaddr_in tmp_addr; - hostname = pj_gethostname(); - pj_sockaddr_in_init(&tmp_addr, hostname, 0); - pj_inet_ntop(pj_AF_INET(), &tmp_addr.sin_addr, ip_addr, - sizeof(ip_addr)); + hostname = pj_gethostname(); + pj_sockaddr_in_init(&tmp_addr, hostname, 0); + pj_inet_ntop(pj_AF_INET(), &tmp_addr.sin_addr, ip_addr, + sizeof(ip_addr)); } /* Init defaults */ @@ -912,78 +911,78 @@ static pj_status_t init_options(int argc, char *argv[]) /* Parse options */ pj_optind = 0; while((c=pj_getopt_long(argc,argv, "c:d:p:r:i:l:g:qR", - long_options, &option_index))!=-1) + long_options, &option_index))!=-1) { - switch (c) { - case 'c': - app.max_calls = atoi(pj_optarg); - if (app.max_calls > MAX_CALLS) { - PJ_LOG(3,(THIS_FILE,"Invalid max calls value %s " - "(must be <= %d)", pj_optarg, MAX_CALLS)); - return 1; - } - break; - case 'g': - app.call_gap = atoi(pj_optarg); - break; - case 'R': - app.call_report = PJ_TRUE; - break; - case 'd': - app.duration = atoi(pj_optarg); - break; - case 'q': - app.auto_quit = 1; - break; - - case 'p': - app.sip_port = atoi(pj_optarg); - break; - case 'r': - app.rtp_start_port = atoi(pj_optarg); - break; - case 'i': - app.local_addr = pj_str(pj_optarg); - break; - - case 'l': - app.log_level = atoi(pj_optarg); - break; - case OPT_APP_LOG_LEVEL: - app.app_log_level = atoi(pj_optarg); - break; - case OPT_LOG_FILE: - app.log_filename = pj_optarg; - break; - - case OPT_A_PT: - app.audio_codec.pt = atoi(pj_optarg); - break; - case OPT_A_NAME: - app.audio_codec.name = pj_optarg; - break; - case OPT_A_CLOCK: - app.audio_codec.clock_rate = atoi(pj_optarg); - break; - case OPT_A_BITRATE: - app.audio_codec.bit_rate = atoi(pj_optarg); - break; - case OPT_A_PTIME: - app.audio_codec.ptime = atoi(pj_optarg); - break; - case OPT_REPORT_FILE: - app.report_filename = pj_optarg; - break; - - default: - puts(USAGE); - return 1; - } + switch (c) { + case 'c': + app.max_calls = atoi(pj_optarg); + if (app.max_calls > MAX_CALLS) { + PJ_LOG(3,(THIS_FILE,"Invalid max calls value %s " + "(must be <= %d)", pj_optarg, MAX_CALLS)); + return 1; + } + break; + case 'g': + app.call_gap = atoi(pj_optarg); + break; + case 'R': + app.call_report = PJ_TRUE; + break; + case 'd': + app.duration = atoi(pj_optarg); + break; + case 'q': + app.auto_quit = 1; + break; + + case 'p': + app.sip_port = atoi(pj_optarg); + break; + case 'r': + app.rtp_start_port = atoi(pj_optarg); + break; + case 'i': + app.local_addr = pj_str(pj_optarg); + break; + + case 'l': + app.log_level = atoi(pj_optarg); + break; + case OPT_APP_LOG_LEVEL: + app.app_log_level = atoi(pj_optarg); + break; + case OPT_LOG_FILE: + app.log_filename = pj_optarg; + break; + + case OPT_A_PT: + app.audio_codec.pt = atoi(pj_optarg); + break; + case OPT_A_NAME: + app.audio_codec.name = pj_optarg; + break; + case OPT_A_CLOCK: + app.audio_codec.clock_rate = atoi(pj_optarg); + break; + case OPT_A_BITRATE: + app.audio_codec.bit_rate = atoi(pj_optarg); + break; + case OPT_A_PTIME: + app.audio_codec.ptime = atoi(pj_optarg); + break; + case OPT_REPORT_FILE: + app.report_filename = pj_optarg; + break; + + default: + puts(USAGE); + return 1; + } } /* Check if URL is specified */ if (pj_optind < argc) - app.uri_to_call = pj_str(argv[pj_optind]); + app.uri_to_call = pj_str(argv[pj_optind]); /* Build local URI and contact */ pj_ansi_sprintf( local_uri, "sip:%s:%d", app.local_addr.ptr, app.sip_port); @@ -1003,8 +1002,8 @@ static pj_status_t init_options(int argc, char *argv[]) * Create SDP session for a call. */ static pj_status_t create_sdp( pj_pool_t *pool, - struct call *call, - pjmedia_sdp_session **p_sdp) + struct call *call, + pjmedia_sdp_session **p_sdp) { pj_time_val tv; pjmedia_sdp_session *sdp; @@ -1061,18 +1060,18 @@ static pj_status_t create_sdp( pj_pool_t *pool, m->attr_count = 0; { - pjmedia_sdp_rtpmap rtpmap; - char ptstr[10]; - - sprintf(ptstr, "%d", app.audio_codec.pt); - pj_strdup2(pool, &m->desc.fmt[0], ptstr); - rtpmap.pt = m->desc.fmt[0]; - rtpmap.clock_rate = app.audio_codec.clock_rate; - rtpmap.enc_name = pj_str(app.audio_codec.name); - rtpmap.param.slen = 0; - - pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr); - m->attr[m->attr_count++] = attr; + pjmedia_sdp_rtpmap rtpmap; + char ptstr[10]; + + sprintf(ptstr, "%d", app.audio_codec.pt); + pj_strdup2(pool, &m->desc.fmt[0], ptstr); + rtpmap.pt = m->desc.fmt[0]; + rtpmap.clock_rate = app.audio_codec.clock_rate; + rtpmap.enc_name = pj_str(app.audio_codec.name); + rtpmap.param.slen = 0; + + pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr); + m->attr[m->attr_count++] = attr; } /* Add sendrecv attribute. */ @@ -1116,62 +1115,62 @@ static void boost_priority(void) #include static void boost_priority(void) { -#define POLICY SCHED_FIFO +#define POLICY SCHED_FIFO struct sched_param tp; int max_prio; int policy; int rc; if (sched_get_priority_min(POLICY) < sched_get_priority_max(POLICY)) - max_prio = sched_get_priority_max(POLICY)-1; + max_prio = sched_get_priority_max(POLICY)-1; else - max_prio = sched_get_priority_max(POLICY)+1; + max_prio = sched_get_priority_max(POLICY)+1; /* * Adjust process scheduling algorithm and priority */ rc = sched_getparam(0, &tp); if (rc != 0) { - app_perror( THIS_FILE, "sched_getparam error", - PJ_RETURN_OS_ERROR(rc)); - return; + app_perror( THIS_FILE, "sched_getparam error", + PJ_RETURN_OS_ERROR(rc)); + return; } tp.sched_priority = max_prio; rc = sched_setscheduler(0, POLICY, &tp); if (rc != 0) { - app_perror( THIS_FILE, "sched_setscheduler error", - PJ_RETURN_OS_ERROR(rc)); + app_perror( THIS_FILE, "sched_setscheduler error", + PJ_RETURN_OS_ERROR(rc)); } PJ_LOG(4, (THIS_FILE, "New process policy=%d, priority=%d", - policy, tp.sched_priority)); + policy, tp.sched_priority)); /* * Adjust thread scheduling algorithm and priority */ rc = pthread_getschedparam(pthread_self(), &policy, &tp); if (rc != 0) { - app_perror( THIS_FILE, "pthread_getschedparam error", - PJ_RETURN_OS_ERROR(rc)); - return; + app_perror( THIS_FILE, "pthread_getschedparam error", + PJ_RETURN_OS_ERROR(rc)); + return; } PJ_LOG(4, (THIS_FILE, "Old thread policy=%d, priority=%d", - policy, tp.sched_priority)); + policy, tp.sched_priority)); policy = POLICY; tp.sched_priority = max_prio; rc = pthread_setschedparam(pthread_self(), policy, &tp); if (rc != 0) { - app_perror( THIS_FILE, "pthread_setschedparam error", - PJ_RETURN_OS_ERROR(rc)); - return; + app_perror( THIS_FILE, "pthread_setschedparam error", + PJ_RETURN_OS_ERROR(rc)); + return; } PJ_LOG(4, (THIS_FILE, "New thread policy=%d, priority=%d", - policy, tp.sched_priority)); + policy, tp.sched_priority)); } #else @@ -1194,28 +1193,28 @@ static void on_rx_rtp(void *user_data, void *pkt, pj_ssize_t size) /* Discard packet if media is inactive */ if (!strm->active) - return; + return; /* Check for errors */ if (size < 0) { - app_perror(THIS_FILE, "RTP recv() error", (pj_status_t)-size); - return; + app_perror(THIS_FILE, "RTP recv() error", (pj_status_t)-size); + return; } /* Decode RTP packet. */ status = pjmedia_rtp_decode_rtp(&strm->in_sess, - pkt, (int)size, - &hdr, &payload, &payload_len); + pkt, (int)size, + &hdr, &payload, &payload_len); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "RTP decode error", status); - return; + app_perror(THIS_FILE, "RTP decode error", status); + return; } //PJ_LOG(4,(THIS_FILE, "Rx seq=%d", pj_ntohs(hdr->seq))); /* Update the RTCP session. */ pjmedia_rtcp_rx_rtp(&strm->rtcp, pj_ntohs(hdr->seq), - pj_ntohl(hdr->ts), payload_len); + pj_ntohl(hdr->ts), payload_len); /* Update RTP session */ pjmedia_rtp_session_update(&strm->in_sess, hdr, NULL); @@ -1233,12 +1232,12 @@ static void on_rx_rtcp(void *user_data, void *pkt, pj_ssize_t size) /* Discard packet if media is inactive */ if (!strm->active) - return; + return; /* Check for errors */ if (size < 0) { - app_perror(THIS_FILE, "Error receiving RTCP packet",(pj_status_t)-size); - return; + app_perror(THIS_FILE, "Error receiving RTCP packet",(pj_status_t)-size); + return; } /* Update RTCP session */ @@ -1277,116 +1276,116 @@ static int media_thread(void *arg) while (!strm->thread_quit_flag) { - pj_timestamp now, lesser; - pj_time_val timeout; - pj_bool_t send_rtp, send_rtcp; - - send_rtp = send_rtcp = PJ_FALSE; - - /* Determine how long to sleep */ - if (next_rtp.u64 < next_rtcp.u64) { - lesser = next_rtp; - send_rtp = PJ_TRUE; - } else { - lesser = next_rtcp; - send_rtcp = PJ_TRUE; - } - - pj_get_timestamp(&now); - if (lesser.u64 <= now.u64) { - timeout.sec = timeout.msec = 0; - //printf("immediate "); fflush(stdout); - } else { - pj_uint64_t tick_delay; - tick_delay = lesser.u64 - now.u64; - timeout.sec = 0; - timeout.msec = (pj_uint32_t)(tick_delay * 1000 / freq.u64); - pj_time_val_normalize(&timeout); - - //printf("%d:%03d ", timeout.sec, timeout.msec); fflush(stdout); - } - - /* Wait for next interval */ - //if (timeout.sec!=0 && timeout.msec!=0) { - pj_thread_sleep(PJ_TIME_VAL_MSEC(timeout)); - if (strm->thread_quit_flag) - break; - //} - - pj_get_timestamp(&now); - - if (send_rtp || next_rtp.u64 <= now.u64) { - /* - * Time to send RTP packet. - */ - pj_status_t status; - const void *p_hdr; - const pjmedia_rtp_hdr *hdr; - pj_ssize_t size; - int hdrlen; - - /* Format RTP header */ - status = pjmedia_rtp_encode_rtp( &strm->out_sess, strm->si.tx_pt, - 0, /* marker bit */ - strm->bytes_per_frame, - strm->samples_per_frame, - &p_hdr, &hdrlen); - if (status == PJ_SUCCESS) { - - //PJ_LOG(4,(THIS_FILE, "\t\tTx seq=%d", pj_ntohs(hdr->seq))); - - hdr = (const pjmedia_rtp_hdr*) p_hdr; - - /* Copy RTP header to packet */ - pj_memcpy(packet, hdr, hdrlen); - - /* Zero the payload */ - pj_bzero(packet+hdrlen, strm->bytes_per_frame); - - /* Send RTP packet */ - size = hdrlen + strm->bytes_per_frame; - status = pjmedia_transport_send_rtp(strm->transport, - packet, size); - if (status != PJ_SUCCESS) - app_perror(THIS_FILE, "Error sending RTP packet", status); - - } else { - pj_assert(!"RTP encode() error"); - } - - /* Update RTCP SR */ - pjmedia_rtcp_tx_rtp( &strm->rtcp, (pj_uint16_t)strm->bytes_per_frame); - - /* Schedule next send */ - next_rtp.u64 += (msec_interval * freq.u64 / 1000); - } - - - if (send_rtcp || next_rtcp.u64 <= now.u64) { - /* - * Time to send RTCP packet. - */ - void *rtcp_pkt; - int rtcp_len; - pj_ssize_t size; - pj_status_t status; - - /* Build RTCP packet */ - pjmedia_rtcp_build_rtcp(&strm->rtcp, &rtcp_pkt, &rtcp_len); + pj_timestamp now, lesser; + pj_time_val timeout; + pj_bool_t send_rtp, send_rtcp; + + send_rtp = send_rtcp = PJ_FALSE; + + /* Determine how long to sleep */ + if (next_rtp.u64 < next_rtcp.u64) { + lesser = next_rtp; + send_rtp = PJ_TRUE; + } else { + lesser = next_rtcp; + send_rtcp = PJ_TRUE; + } + + pj_get_timestamp(&now); + if (lesser.u64 <= now.u64) { + timeout.sec = timeout.msec = 0; + //printf("immediate "); fflush(stdout); + } else { + pj_uint64_t tick_delay; + tick_delay = lesser.u64 - now.u64; + timeout.sec = 0; + timeout.msec = (pj_uint32_t)(tick_delay * 1000 / freq.u64); + pj_time_val_normalize(&timeout); + + //printf("%d:%03d ", timeout.sec, timeout.msec); fflush(stdout); + } + + /* Wait for next interval */ + //if (timeout.sec!=0 && timeout.msec!=0) { + pj_thread_sleep(PJ_TIME_VAL_MSEC(timeout)); + if (strm->thread_quit_flag) + break; + //} + + pj_get_timestamp(&now); + + if (send_rtp || next_rtp.u64 <= now.u64) { + /* + * Time to send RTP packet. + */ + pj_status_t status; + const void *p_hdr; + const pjmedia_rtp_hdr *hdr; + pj_ssize_t size; + int hdrlen; + + /* Format RTP header */ + status = pjmedia_rtp_encode_rtp( &strm->out_sess, strm->si.tx_pt, + 0, /* marker bit */ + strm->bytes_per_frame, + strm->samples_per_frame, + &p_hdr, &hdrlen); + if (status == PJ_SUCCESS) { + + //PJ_LOG(4,(THIS_FILE, "\t\tTx seq=%d", pj_ntohs(hdr->seq))); + + hdr = (const pjmedia_rtp_hdr*) p_hdr; + + /* Copy RTP header to packet */ + pj_memcpy(packet, hdr, hdrlen); + + /* Zero the payload */ + pj_bzero(packet+hdrlen, strm->bytes_per_frame); + + /* Send RTP packet */ + size = hdrlen + strm->bytes_per_frame; + status = pjmedia_transport_send_rtp(strm->transport, + packet, size); + if (status != PJ_SUCCESS) + app_perror(THIS_FILE, "Error sending RTP packet", status); + + } else { + pj_assert(!"RTP encode() error"); + } + + /* Update RTCP SR */ + pjmedia_rtcp_tx_rtp( &strm->rtcp, (pj_uint16_t)strm->bytes_per_frame); + + /* Schedule next send */ + next_rtp.u64 += (msec_interval * freq.u64 / 1000); + } + + + if (send_rtcp || next_rtcp.u64 <= now.u64) { + /* + * Time to send RTCP packet. + */ + void *rtcp_pkt; + int rtcp_len; + pj_ssize_t size; + pj_status_t status; + + /* Build RTCP packet */ + pjmedia_rtcp_build_rtcp(&strm->rtcp, &rtcp_pkt, &rtcp_len); - /* Send packet */ - size = rtcp_len; - status = pjmedia_transport_send_rtcp(strm->transport, - rtcp_pkt, size); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error sending RTCP packet", status); - } - - /* Schedule next send */ - next_rtcp.u64 += (freq.u64 * (RTCP_INTERVAL+(pj_rand()%RTCP_RAND)) / - 1000); - } + /* Send packet */ + size = rtcp_len; + status = pjmedia_transport_send_rtcp(strm->transport, + rtcp_pkt, size); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Error sending RTCP packet", status); + } + + /* Schedule next send */ + next_rtcp.u64 += (freq.u64 * (RTCP_INTERVAL+(pj_rand()%RTCP_RAND)) / + 1000); + } } return 0; @@ -1395,7 +1394,7 @@ static int media_thread(void *arg) /* Callback to be called when SDP negotiation is done in the call: */ static void call_on_media_update( pjsip_inv_session *inv, - pj_status_t status) + pj_status_t status) { struct call *call; struct media_stream *audio; @@ -1408,13 +1407,13 @@ static void call_on_media_update( pjsip_inv_session *inv, /* If this is a mid-call media update, then destroy existing media */ if (audio->thread != NULL) - destroy_call_media(call->index); + destroy_call_media(call->index); /* Do nothing if media negotiation has failed */ if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "SDP negotiation failed", status); - return; + app_perror(THIS_FILE, "SDP negotiation failed", status); + return; } @@ -1423,28 +1422,28 @@ static void call_on_media_update( pjsip_inv_session *inv, pjmedia_sdp_neg_get_active_remote(inv->neg, &remote_sdp); status = pjmedia_stream_info_from_sdp(&audio->si, inv->pool, app.med_endpt, - local_sdp, remote_sdp, 0); + local_sdp, remote_sdp, 0); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error creating stream info from SDP", status); - return; + app_perror(THIS_FILE, "Error creating stream info from SDP", status); + return; } /* Get the remainder of codec information from codec descriptor */ if (audio->si.fmt.pt == app.audio_codec.pt) - codec_desc = &app.audio_codec; + codec_desc = &app.audio_codec; else { - /* Find the codec description in codec array */ - for (i=0; isi.fmt.pt) { - codec_desc = &audio_codecs[i]; - break; - } - } - - if (codec_desc == NULL) { - PJ_LOG(3, (THIS_FILE, "Error: Invalid codec payload type")); - return; - } + /* Find the codec description in codec array */ + for (i=0; isi.fmt.pt) { + codec_desc = &audio_codecs[i]; + break; + } + } + + if (codec_desc == NULL) { + PJ_LOG(3, (THIS_FILE, "Error: Invalid codec payload type")); + return; + } } audio->clock_rate = audio->si.fmt.clock_rate; @@ -1453,22 +1452,22 @@ static void call_on_media_update( pjsip_inv_session *inv, pjmedia_rtp_session_init(&audio->out_sess, audio->si.tx_pt, - pj_rand()); + pj_rand()); pjmedia_rtp_session_init(&audio->in_sess, audio->si.fmt.pt, 0); pjmedia_rtcp_init(&audio->rtcp, "rtcp", audio->clock_rate, - audio->samples_per_frame, 0); + audio->samples_per_frame, 0); /* Attach media to transport */ status = pjmedia_transport_attach(audio->transport, audio, - &audio->si.rem_addr, - &audio->si.rem_rtcp, - sizeof(pj_sockaddr_in), - &on_rx_rtp, - &on_rx_rtcp); + &audio->si.rem_addr, + &audio->si.rem_rtcp, + sizeof(pj_sockaddr_in), + &on_rx_rtp, + &on_rx_rtcp); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error on pjmedia_transport_attach()", status); - return; + app_perror(THIS_FILE, "Error on pjmedia_transport_attach()", status); + return; } /* Start media transport */ @@ -1478,10 +1477,10 @@ static void call_on_media_update( pjsip_inv_session *inv, audio->thread_quit_flag = 0; #if PJ_HAS_THREADS status = pj_thread_create( inv->pool, "media", &media_thread, audio, - 0, 0, &audio->thread); + 0, 0, &audio->thread); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error creating media thread", status); - return; + app_perror(THIS_FILE, "Error creating media thread", status); + return; } #endif @@ -1497,17 +1496,17 @@ static void destroy_call_media(unsigned call_index) struct media_stream *audio = &app.call[call_index].media[0]; if (audio) { - audio->active = PJ_FALSE; + audio->active = PJ_FALSE; - if (audio->thread) { - audio->thread_quit_flag = 1; - pj_thread_join(audio->thread); - pj_thread_destroy(audio->thread); - audio->thread = NULL; - audio->thread_quit_flag = 0; - } + if (audio->thread) { + audio->thread_quit_flag = 1; + pj_thread_join(audio->thread); + pj_thread_destroy(audio->thread); + audio->thread = NULL; + audio->thread_quit_flag = 0; + } - pjmedia_transport_detach(audio->transport, audio); + pjmedia_transport_detach(audio->transport, audio); } } @@ -1524,16 +1523,16 @@ static void call_get_duration(int call_index, pj_time_val *dur) dur->sec = dur->msec = 0; if (!call) - return; + return; inv = call->inv; if (!inv) - return; + return; if (inv->state >= PJSIP_INV_STATE_CONFIRMED && call->connect_time.sec) { - pj_gettimeofday(dur); - PJ_TIME_VAL_SUB((*dur), call->connect_time); + pj_gettimeofday(dur); + PJ_TIME_VAL_SUB((*dur), call->connect_time); } } @@ -1541,15 +1540,15 @@ static void call_get_duration(int call_index, pj_time_val *dur) static const char *good_number(char *buf, pj_int32_t val) { if (val < 1000) { - pj_ansi_sprintf(buf, "%d", val); + pj_ansi_sprintf(buf, "%d", val); } else if (val < 1000000) { - pj_ansi_sprintf(buf, "%d.%02dK", - val / 1000, - (val % 1000) / 100); + pj_ansi_sprintf(buf, "%d.%02dK", + val / 1000, + (val % 1000) / 100); } else { - pj_ansi_sprintf(buf, "%d.%02dM", - val / 1000000, - (val % 1000000) / 10000); + pj_ansi_sprintf(buf, "%d.%02dM", + val / 1000000, + (val % 1000000) / 10000); } return buf; @@ -1559,13 +1558,13 @@ static const char *good_number(char *buf, pj_int32_t val) static void print_avg_stat(void) { -#define MIN_(var,val) if ((int)val < (int)var) var = val -#define MAX_(var,val) if ((int)val > (int)var) var = val -#define AVG_(var,val) var = ( ((var * count) + val) / (count+1) ) -#define BIGVAL 0x7FFFFFFFL +#define MIN_(var,val) if ((int)val < (int)var) var = val +#define MAX_(var,val) if ((int)val > (int)var) var = val +#define AVG_(var,val) var = ( ((var * count) + val) / (count+1) ) +#define BIGVAL 0x7FFFFFFFL struct stat_entry { - int min, avg, max; + int min, avg, max; }; struct stat_entry call_dur, call_pdd; @@ -1600,219 +1599,219 @@ static void print_avg_stat(void) for (i=0, count=0; imedia[0]; - pj_time_val dur; - unsigned msec_dur; - - if (call->inv == NULL || - call->inv->state < PJSIP_INV_STATE_CONFIRMED || - call->connect_time.sec == 0) - { - continue; - } - - /* Duration */ - call_get_duration(i, &dur); - msec_dur = PJ_TIME_VAL_MSEC(dur); - - MIN_(call_dur.min, msec_dur); - MAX_(call_dur.max, msec_dur); - AVG_(call_dur.avg, msec_dur); - - /* Connect delay */ - if (call->connect_time.sec) { - pj_time_val t = call->connect_time; - PJ_TIME_VAL_SUB(t, call->start_time); - msec_dur = PJ_TIME_VAL_MSEC(t); - } else { - msec_dur = 10; - } - - MIN_(call_pdd.min, msec_dur); - MAX_(call_pdd.max, msec_dur); - AVG_(call_pdd.avg, msec_dur); - - /* RX Statistisc: */ - - /* Packets */ - MIN_(min_stat.rx.pkt, audio->rtcp.stat.rx.pkt); - MAX_(max_stat.rx.pkt, audio->rtcp.stat.rx.pkt); - AVG_(avg_stat.rx.pkt, audio->rtcp.stat.rx.pkt); - - /* Bytes */ - MIN_(min_stat.rx.bytes, audio->rtcp.stat.rx.bytes); - MAX_(max_stat.rx.bytes, audio->rtcp.stat.rx.bytes); - AVG_(avg_stat.rx.bytes, audio->rtcp.stat.rx.bytes); - - - /* Packet loss */ - MIN_(min_stat.rx.loss, audio->rtcp.stat.rx.loss); - MAX_(max_stat.rx.loss, audio->rtcp.stat.rx.loss); - AVG_(avg_stat.rx.loss, audio->rtcp.stat.rx.loss); - - /* Packet dup */ - MIN_(min_stat.rx.dup, audio->rtcp.stat.rx.dup); - MAX_(max_stat.rx.dup, audio->rtcp.stat.rx.dup); - AVG_(avg_stat.rx.dup, audio->rtcp.stat.rx.dup); - - /* Packet reorder */ - MIN_(min_stat.rx.reorder, audio->rtcp.stat.rx.reorder); - MAX_(max_stat.rx.reorder, audio->rtcp.stat.rx.reorder); - AVG_(avg_stat.rx.reorder, audio->rtcp.stat.rx.reorder); - - /* Jitter */ - MIN_(min_stat.rx.jitter.min, audio->rtcp.stat.rx.jitter.min); - MAX_(max_stat.rx.jitter.max, audio->rtcp.stat.rx.jitter.max); - AVG_(avg_stat.rx.jitter.mean, audio->rtcp.stat.rx.jitter.mean); - - - /* TX Statistisc: */ - - /* Packets */ - MIN_(min_stat.tx.pkt, audio->rtcp.stat.tx.pkt); - MAX_(max_stat.tx.pkt, audio->rtcp.stat.tx.pkt); - AVG_(avg_stat.tx.pkt, audio->rtcp.stat.tx.pkt); - - /* Bytes */ - MIN_(min_stat.tx.bytes, audio->rtcp.stat.tx.bytes); - MAX_(max_stat.tx.bytes, audio->rtcp.stat.tx.bytes); - AVG_(avg_stat.tx.bytes, audio->rtcp.stat.tx.bytes); - - /* Packet loss */ - MIN_(min_stat.tx.loss, audio->rtcp.stat.tx.loss); - MAX_(max_stat.tx.loss, audio->rtcp.stat.tx.loss); - AVG_(avg_stat.tx.loss, audio->rtcp.stat.tx.loss); - - /* Packet dup */ - MIN_(min_stat.tx.dup, audio->rtcp.stat.tx.dup); - MAX_(max_stat.tx.dup, audio->rtcp.stat.tx.dup); - AVG_(avg_stat.tx.dup, audio->rtcp.stat.tx.dup); - - /* Packet reorder */ - MIN_(min_stat.tx.reorder, audio->rtcp.stat.tx.reorder); - MAX_(max_stat.tx.reorder, audio->rtcp.stat.tx.reorder); - AVG_(avg_stat.tx.reorder, audio->rtcp.stat.tx.reorder); - - /* Jitter */ - MIN_(min_stat.tx.jitter.min, audio->rtcp.stat.tx.jitter.min); - MAX_(max_stat.tx.jitter.max, audio->rtcp.stat.tx.jitter.max); - AVG_(avg_stat.tx.jitter.mean, audio->rtcp.stat.tx.jitter.mean); - - - /* RTT */ - MIN_(min_stat.rtt.min, audio->rtcp.stat.rtt.min); - MAX_(max_stat.rtt.max, audio->rtcp.stat.rtt.max); - AVG_(avg_stat.rtt.mean, audio->rtcp.stat.rtt.mean); - - ++count; + struct call *call = &app.call[i]; + struct media_stream *audio = &call->media[0]; + pj_time_val dur; + unsigned msec_dur; + + if (call->inv == NULL || + call->inv->state < PJSIP_INV_STATE_CONFIRMED || + call->connect_time.sec == 0) + { + continue; + } + + /* Duration */ + call_get_duration(i, &dur); + msec_dur = PJ_TIME_VAL_MSEC(dur); + + MIN_(call_dur.min, msec_dur); + MAX_(call_dur.max, msec_dur); + AVG_(call_dur.avg, msec_dur); + + /* Connect delay */ + if (call->connect_time.sec) { + pj_time_val t = call->connect_time; + PJ_TIME_VAL_SUB(t, call->start_time); + msec_dur = PJ_TIME_VAL_MSEC(t); + } else { + msec_dur = 10; + } + + MIN_(call_pdd.min, msec_dur); + MAX_(call_pdd.max, msec_dur); + AVG_(call_pdd.avg, msec_dur); + + /* RX Statistisc: */ + + /* Packets */ + MIN_(min_stat.rx.pkt, audio->rtcp.stat.rx.pkt); + MAX_(max_stat.rx.pkt, audio->rtcp.stat.rx.pkt); + AVG_(avg_stat.rx.pkt, audio->rtcp.stat.rx.pkt); + + /* Bytes */ + MIN_(min_stat.rx.bytes, audio->rtcp.stat.rx.bytes); + MAX_(max_stat.rx.bytes, audio->rtcp.stat.rx.bytes); + AVG_(avg_stat.rx.bytes, audio->rtcp.stat.rx.bytes); + + + /* Packet loss */ + MIN_(min_stat.rx.loss, audio->rtcp.stat.rx.loss); + MAX_(max_stat.rx.loss, audio->rtcp.stat.rx.loss); + AVG_(avg_stat.rx.loss, audio->rtcp.stat.rx.loss); + + /* Packet dup */ + MIN_(min_stat.rx.dup, audio->rtcp.stat.rx.dup); + MAX_(max_stat.rx.dup, audio->rtcp.stat.rx.dup); + AVG_(avg_stat.rx.dup, audio->rtcp.stat.rx.dup); + + /* Packet reorder */ + MIN_(min_stat.rx.reorder, audio->rtcp.stat.rx.reorder); + MAX_(max_stat.rx.reorder, audio->rtcp.stat.rx.reorder); + AVG_(avg_stat.rx.reorder, audio->rtcp.stat.rx.reorder); + + /* Jitter */ + MIN_(min_stat.rx.jitter.min, audio->rtcp.stat.rx.jitter.min); + MAX_(max_stat.rx.jitter.max, audio->rtcp.stat.rx.jitter.max); + AVG_(avg_stat.rx.jitter.mean, audio->rtcp.stat.rx.jitter.mean); + + + /* TX Statistisc: */ + + /* Packets */ + MIN_(min_stat.tx.pkt, audio->rtcp.stat.tx.pkt); + MAX_(max_stat.tx.pkt, audio->rtcp.stat.tx.pkt); + AVG_(avg_stat.tx.pkt, audio->rtcp.stat.tx.pkt); + + /* Bytes */ + MIN_(min_stat.tx.bytes, audio->rtcp.stat.tx.bytes); + MAX_(max_stat.tx.bytes, audio->rtcp.stat.tx.bytes); + AVG_(avg_stat.tx.bytes, audio->rtcp.stat.tx.bytes); + + /* Packet loss */ + MIN_(min_stat.tx.loss, audio->rtcp.stat.tx.loss); + MAX_(max_stat.tx.loss, audio->rtcp.stat.tx.loss); + AVG_(avg_stat.tx.loss, audio->rtcp.stat.tx.loss); + + /* Packet dup */ + MIN_(min_stat.tx.dup, audio->rtcp.stat.tx.dup); + MAX_(max_stat.tx.dup, audio->rtcp.stat.tx.dup); + AVG_(avg_stat.tx.dup, audio->rtcp.stat.tx.dup); + + /* Packet reorder */ + MIN_(min_stat.tx.reorder, audio->rtcp.stat.tx.reorder); + MAX_(max_stat.tx.reorder, audio->rtcp.stat.tx.reorder); + AVG_(avg_stat.tx.reorder, audio->rtcp.stat.tx.reorder); + + /* Jitter */ + MIN_(min_stat.tx.jitter.min, audio->rtcp.stat.tx.jitter.min); + MAX_(max_stat.tx.jitter.max, audio->rtcp.stat.tx.jitter.max); + AVG_(avg_stat.tx.jitter.mean, audio->rtcp.stat.tx.jitter.mean); + + + /* RTT */ + MIN_(min_stat.rtt.min, audio->rtcp.stat.rtt.min); + MAX_(max_stat.rtt.max, audio->rtcp.stat.rtt.max); + AVG_(avg_stat.rtt.mean, audio->rtcp.stat.rtt.mean); + + ++count; } if (count == 0) { - puts("No active calls"); - return; + puts("No active calls"); + return; } printf("Total %d call(s) active.\n" - " Average Statistics\n" - " min avg max \n" - " -----------------------\n" - " call duration: %7d %7d %7d %s\n" - " connect delay: %7d %7d %7d %s\n" - " RX stat:\n" - " packets: %7s %7s %7s %s\n" - " payload: %7s %7s %7s %s\n" - " loss: %7d %7d %7d %s\n" - " percent loss: %7.3f %7.3f %7.3f %s\n" - " dup: %7d %7d %7d %s\n" - " reorder: %7d %7d %7d %s\n" - " jitter: %7.3f %7.3f %7.3f %s\n" - " TX stat:\n" - " packets: %7s %7s %7s %s\n" - " payload: %7s %7s %7s %s\n" - " loss: %7d %7d %7d %s\n" - " percent loss: %7.3f %7.3f %7.3f %s\n" - " dup: %7d %7d %7d %s\n" - " reorder: %7d %7d %7d %s\n" - " jitter: %7.3f %7.3f %7.3f %s\n" - " RTT : %7.3f %7.3f %7.3f %s\n" - , - count, - call_dur.min/1000, call_dur.avg/1000, call_dur.max/1000, - "seconds", - - call_pdd.min, call_pdd.avg, call_pdd.max, - "ms", - - /* rx */ - - good_number(srx_min, min_stat.rx.pkt), - good_number(srx_avg, avg_stat.rx.pkt), - good_number(srx_max, max_stat.rx.pkt), - "packets", - - good_number(brx_min, min_stat.rx.bytes), - good_number(brx_avg, avg_stat.rx.bytes), - good_number(brx_max, max_stat.rx.bytes), - "bytes", - - min_stat.rx.loss, avg_stat.rx.loss, max_stat.rx.loss, - "packets", - - min_stat.rx.loss*100.0/(min_stat.rx.pkt+min_stat.rx.loss), - avg_stat.rx.loss*100.0/(avg_stat.rx.pkt+avg_stat.rx.loss), - max_stat.rx.loss*100.0/(max_stat.rx.pkt+max_stat.rx.loss), - "%", - - - min_stat.rx.dup, avg_stat.rx.dup, max_stat.rx.dup, - "packets", - - min_stat.rx.reorder, avg_stat.rx.reorder, max_stat.rx.reorder, - "packets", - - min_stat.rx.jitter.min/1000.0, - avg_stat.rx.jitter.mean/1000.0, - max_stat.rx.jitter.max/1000.0, - "ms", - - /* tx */ - - good_number(stx_min, min_stat.tx.pkt), - good_number(stx_avg, avg_stat.tx.pkt), - good_number(stx_max, max_stat.tx.pkt), - "packets", - - good_number(btx_min, min_stat.tx.bytes), - good_number(btx_avg, avg_stat.tx.bytes), - good_number(btx_max, max_stat.tx.bytes), - "bytes", - - min_stat.tx.loss, avg_stat.tx.loss, max_stat.tx.loss, - "packets", - - min_stat.tx.loss*100.0/(min_stat.tx.pkt+min_stat.tx.loss), - avg_stat.tx.loss*100.0/(avg_stat.tx.pkt+avg_stat.tx.loss), - max_stat.tx.loss*100.0/(max_stat.tx.pkt+max_stat.tx.loss), - "%", - - min_stat.tx.dup, avg_stat.tx.dup, max_stat.tx.dup, - "packets", - - min_stat.tx.reorder, avg_stat.tx.reorder, max_stat.tx.reorder, - "packets", - - min_stat.tx.jitter.min/1000.0, - avg_stat.tx.jitter.mean/1000.0, - max_stat.tx.jitter.max/1000.0, - "ms", - - /* rtt */ - min_stat.rtt.min/1000.0, - avg_stat.rtt.mean/1000.0, - max_stat.rtt.max/1000.0, - "ms" - ); + " Average Statistics\n" + " min avg max \n" + " -----------------------\n" + " call duration: %7d %7d %7d %s\n" + " connect delay: %7d %7d %7d %s\n" + " RX stat:\n" + " packets: %7s %7s %7s %s\n" + " payload: %7s %7s %7s %s\n" + " loss: %7d %7d %7d %s\n" + " percent loss: %7.3f %7.3f %7.3f %s\n" + " dup: %7d %7d %7d %s\n" + " reorder: %7d %7d %7d %s\n" + " jitter: %7.3f %7.3f %7.3f %s\n" + " TX stat:\n" + " packets: %7s %7s %7s %s\n" + " payload: %7s %7s %7s %s\n" + " loss: %7d %7d %7d %s\n" + " percent loss: %7.3f %7.3f %7.3f %s\n" + " dup: %7d %7d %7d %s\n" + " reorder: %7d %7d %7d %s\n" + " jitter: %7.3f %7.3f %7.3f %s\n" + " RTT : %7.3f %7.3f %7.3f %s\n" + , + count, + call_dur.min/1000, call_dur.avg/1000, call_dur.max/1000, + "seconds", + + call_pdd.min, call_pdd.avg, call_pdd.max, + "ms", + + /* rx */ + + good_number(srx_min, min_stat.rx.pkt), + good_number(srx_avg, avg_stat.rx.pkt), + good_number(srx_max, max_stat.rx.pkt), + "packets", + + good_number(brx_min, min_stat.rx.bytes), + good_number(brx_avg, avg_stat.rx.bytes), + good_number(brx_max, max_stat.rx.bytes), + "bytes", + + min_stat.rx.loss, avg_stat.rx.loss, max_stat.rx.loss, + "packets", + + min_stat.rx.loss*100.0/(min_stat.rx.pkt+min_stat.rx.loss), + avg_stat.rx.loss*100.0/(avg_stat.rx.pkt+avg_stat.rx.loss), + max_stat.rx.loss*100.0/(max_stat.rx.pkt+max_stat.rx.loss), + "%", + + + min_stat.rx.dup, avg_stat.rx.dup, max_stat.rx.dup, + "packets", + + min_stat.rx.reorder, avg_stat.rx.reorder, max_stat.rx.reorder, + "packets", + + min_stat.rx.jitter.min/1000.0, + avg_stat.rx.jitter.mean/1000.0, + max_stat.rx.jitter.max/1000.0, + "ms", + + /* tx */ + + good_number(stx_min, min_stat.tx.pkt), + good_number(stx_avg, avg_stat.tx.pkt), + good_number(stx_max, max_stat.tx.pkt), + "packets", + + good_number(btx_min, min_stat.tx.bytes), + good_number(btx_avg, avg_stat.tx.bytes), + good_number(btx_max, max_stat.tx.bytes), + "bytes", + + min_stat.tx.loss, avg_stat.tx.loss, max_stat.tx.loss, + "packets", + + min_stat.tx.loss*100.0/(min_stat.tx.pkt+min_stat.tx.loss), + avg_stat.tx.loss*100.0/(avg_stat.tx.pkt+avg_stat.tx.loss), + max_stat.tx.loss*100.0/(max_stat.tx.pkt+max_stat.tx.loss), + "%", + + min_stat.tx.dup, avg_stat.tx.dup, max_stat.tx.dup, + "packets", + + min_stat.tx.reorder, avg_stat.tx.reorder, max_stat.tx.reorder, + "packets", + + min_stat.tx.jitter.min/1000.0, + avg_stat.tx.jitter.mean/1000.0, + max_stat.tx.jitter.max/1000.0, + "ms", + + /* rtt */ + min_stat.rtt.min/1000.0, + avg_stat.rtt.mean/1000.0, + max_stat.rtt.max/1000.0, + "ms" + ); } @@ -1825,9 +1824,9 @@ static void list_calls() unsigned i; puts("List all calls:"); for (i=0; i>> "); fflush(stdout); - if (fgets(input1, sizeof(input1), stdin) == NULL) { - puts("EOF while reading stdin, will quit now.."); - break; - } + printf(">>> "); fflush(stdout); + if (fgets(input1, sizeof(input1), stdin) == NULL) { + puts("EOF while reading stdin, will quit now.."); + break; + } - switch (input1[0]) { + switch (input1[0]) { - case 's': - print_avg_stat(); - break; + case 's': + print_avg_stat(); + break; - case 'l': - list_calls(); - break; + case 'l': + list_calls(); + break; - case 'h': - if (!simple_input("Call number to hangup", input1, sizeof(input1))) - break; + case 'h': + if (!simple_input("Call number to hangup", input1, sizeof(input1))) + break; - i = atoi(input1); - hangup_call(i); - break; + i = atoi(input1); + hangup_call(i); + break; - case 'H': - hangup_all_calls(); - break; + case 'H': + hangup_all_calls(); + break; - case 'q': - goto on_exit; + case 'q': + goto on_exit; - default: - puts("Invalid command"); - printf("%s", MENU); - break; - } + default: + puts("Invalid command"); + printf("%s", MENU); + break; + } - fflush(stdout); + fflush(stdout); } on_exit: @@ -1956,13 +1955,13 @@ static void console_main() static pj_bool_t logger_on_rx_msg(pjsip_rx_data *rdata) { PJ_LOG(4,(THIS_FILE, "RX %d bytes %s from %s:%d:\n" - "%s\n" - "--end msg--", - rdata->msg_info.len, - pjsip_rx_data_get_info(rdata), - rdata->pkt_info.src_name, - rdata->pkt_info.src_port, - rdata->msg_info.msg_buf)); + "%s\n" + "--end msg--", + rdata->msg_info.len, + pjsip_rx_data_get_info(rdata), + rdata->pkt_info.src_name, + rdata->pkt_info.src_port, + rdata->msg_info.msg_buf)); /* Always return false, otherwise messages will not get processed! */ return PJ_FALSE; @@ -1973,19 +1972,19 @@ static pj_status_t logger_on_tx_msg(pjsip_tx_data *tdata) { /* Important note: - * tp_info field is only valid after outgoing messages has passed - * transport layer. So don't try to access tp_info when the module - * has lower priority than transport layer. + * tp_info field is only valid after outgoing messages has passed + * transport layer. So don't try to access tp_info when the module + * has lower priority than transport layer. */ PJ_LOG(4,(THIS_FILE, "TX %d bytes %s to %s:%d:\n" - "%s\n" - "--end msg--", - (tdata->buf.cur - tdata->buf.start), - pjsip_tx_data_get_info(tdata), - tdata->tp_info.dst_name, - tdata->tp_info.dst_port, - tdata->buf.start)); + "%s\n" + "--end msg--", + (tdata->buf.cur - tdata->buf.start), + pjsip_tx_data_get_info(tdata), + tdata->tp_info.dst_name, + tdata->tp_info.dst_port, + tdata->buf.start)); /* Always return success, otherwise message will not get sent! */ return PJ_SUCCESS; @@ -1994,19 +1993,19 @@ static pj_status_t logger_on_tx_msg(pjsip_tx_data *tdata) /* The module instance. */ static pjsip_module msg_logger = { - NULL, NULL, /* prev, next. */ - { "mod-siprtp-log", 14 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &logger_on_rx_msg, /* on_rx_request() */ - &logger_on_rx_msg, /* on_rx_response() */ - &logger_on_tx_msg, /* on_tx_request. */ - &logger_on_tx_msg, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-siprtp-log", 14 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &logger_on_rx_msg, /* on_rx_request() */ + &logger_on_rx_msg, /* on_rx_response() */ + &logger_on_tx_msg, /* on_tx_request. */ + &logger_on_tx_msg, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -2025,12 +2024,12 @@ static void app_log_writer(int level, const char *buffer, int len) /* Write to both stdout and file. */ if (level <= app.app_log_level) - pj_log_write(level, buffer, len); + pj_log_write(level, buffer, len); if (log_file) { - pj_size_t count = fwrite(buffer, len, 1, log_file); - PJ_UNUSED_ARG(count); - fflush(log_file); + pj_size_t count = fwrite(buffer, len, 1, log_file); + PJ_UNUSED_ARG(count); + fflush(log_file); } } @@ -2044,12 +2043,12 @@ pj_status_t app_logging_init(void) /* If output log file is desired, create the file: */ if (app.log_filename) { - log_file = fopen(app.log_filename, "wt"); - if (log_file == NULL) { - PJ_LOG(1,(THIS_FILE, "Unable to open log file %s", - app.log_filename)); - return -1; - } + log_file = fopen(app.log_filename, "wt"); + if (log_file == NULL) { + PJ_LOG(1,(THIS_FILE, "Unable to open log file %s", + app.log_filename)); + return -1; + } } return PJ_SUCCESS; @@ -2061,8 +2060,8 @@ void app_logging_shutdown(void) /* Close logging file, if any: */ if (log_file) { - fclose(log_file); - log_file = NULL; + fclose(log_file); + log_file = NULL; } } @@ -2078,33 +2077,33 @@ int main(int argc, char *argv[]) /* Must init PJLIB first */ status = pj_init(); if (status != PJ_SUCCESS) - return 1; + return 1; /* Get command line options */ status = init_options(argc, argv); if (status != PJ_SUCCESS) - return 1; + return 1; /* Verify options: */ /* Auto-quit can not be specified for UAS */ if (app.auto_quit && app.uri_to_call.slen == 0) { - printf("Error: --auto-quit option only valid for outgoing " - "mode (UAC) only\n"); - return 1; + printf("Error: --auto-quit option only valid for outgoing " + "mode (UAC) only\n"); + return 1; } /* Init logging */ status = app_logging_init(); if (status != PJ_SUCCESS) - return 1; + return 1; /* Init SIP etc */ status = init_sip(); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Initialization has failed", status); - destroy_sip(); - return 1; + app_perror(THIS_FILE, "Initialization has failed", status); + destroy_sip(); + return 1; } /* Register module to log incoming/outgoing messages */ @@ -2113,61 +2112,61 @@ int main(int argc, char *argv[]) /* Init media */ status = init_media(); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Media initialization failed", status); - destroy_sip(); - return 1; + app_perror(THIS_FILE, "Media initialization failed", status); + destroy_sip(); + return 1; } /* Start worker threads */ #if PJ_HAS_THREADS for (i=0; i @@ -48,183 +47,183 @@ static void print_call(int call_index) pj_gettimeofday(&now); if (app.report_filename) - puts(app.report_filename); + puts(app.report_filename); /* Print duration */ if (inv->state >= PJSIP_INV_STATE_CONFIRMED && call->connect_time.sec) { - PJ_TIME_VAL_SUB(now, call->connect_time); + PJ_TIME_VAL_SUB(now, call->connect_time); - sprintf(duration, " [duration: %02ld:%02ld:%02ld.%03ld]", - now.sec / 3600, - (now.sec % 3600) / 60, - (now.sec % 60), - now.msec); + sprintf(duration, " [duration: %02ld:%02ld:%02ld.%03ld]", + now.sec / 3600, + (now.sec % 3600) / 60, + (now.sec % 60), + now.msec); } else { - duration[0] = '\0'; + duration[0] = '\0'; } /* Call number and state */ PJ_LOG(3, (THIS_FILE, - "Call #%d: %s%s", - call_index, pjsip_inv_state_name(inv->state), - duration)); + "Call #%d: %s%s", + call_index, pjsip_inv_state_name(inv->state), + duration)); /* Call identification */ len = pjsip_hdr_print_on(dlg->remote.info, userinfo, sizeof(userinfo)); if (len < 0) - pj_ansi_strcpy(userinfo, "<--uri too long-->"); + pj_ansi_strcpy(userinfo, "<--uri too long-->"); else - userinfo[len] = '\0'; + userinfo[len] = '\0'; PJ_LOG(3, (THIS_FILE, " %s", userinfo)); if (call->inv == NULL || call->inv->state < PJSIP_INV_STATE_CONFIRMED || - call->connect_time.sec == 0) + call->connect_time.sec == 0) { - pj_log_set_decor(decor); - return; + pj_log_set_decor(decor); + return; } /* Signaling quality */ { - char pdd[64], connectdelay[64]; - pj_time_val t; - - if (call->response_time.sec) { - t = call->response_time; - PJ_TIME_VAL_SUB(t, call->start_time); - sprintf(pdd, "got 1st response in %ld ms", PJ_TIME_VAL_MSEC(t)); - } else { - pdd[0] = '\0'; - } - - if (call->connect_time.sec) { - t = call->connect_time; - PJ_TIME_VAL_SUB(t, call->start_time); - sprintf(connectdelay, ", connected after: %ld ms", - PJ_TIME_VAL_MSEC(t)); - } else { - connectdelay[0] = '\0'; - } - - PJ_LOG(3, (THIS_FILE, - " Signaling quality: %s%s", pdd, connectdelay)); + char pdd[64], connectdelay[64]; + pj_time_val t; + + if (call->response_time.sec) { + t = call->response_time; + PJ_TIME_VAL_SUB(t, call->start_time); + sprintf(pdd, "got 1st response in %ld ms", PJ_TIME_VAL_MSEC(t)); + } else { + pdd[0] = '\0'; + } + + if (call->connect_time.sec) { + t = call->connect_time; + PJ_TIME_VAL_SUB(t, call->start_time); + sprintf(connectdelay, ", connected after: %ld ms", + PJ_TIME_VAL_MSEC(t)); + } else { + connectdelay[0] = '\0'; + } + + PJ_LOG(3, (THIS_FILE, + " Signaling quality: %s%s", pdd, connectdelay)); } PJ_LOG(3, (THIS_FILE, - " Stream #0: audio %.*s@%dHz, %dms/frame, %sB/s (%sB/s +IP hdr)", - (int)audio->si.fmt.encoding_name.slen, - audio->si.fmt.encoding_name.ptr, - audio->clock_rate, - audio->samples_per_frame * 1000 / audio->clock_rate, - good_number(bps, audio->bytes_per_frame * audio->clock_rate / audio->samples_per_frame), - good_number(ipbps, (audio->bytes_per_frame+32) * audio->clock_rate / audio->samples_per_frame))); + " Stream #0: audio %.*s@%dHz, %dms/frame, %sB/s (%sB/s +IP hdr)", + (int)audio->si.fmt.encoding_name.slen, + audio->si.fmt.encoding_name.ptr, + audio->clock_rate, + audio->samples_per_frame * 1000 / audio->clock_rate, + good_number(bps, audio->bytes_per_frame * audio->clock_rate / audio->samples_per_frame), + good_number(ipbps, (audio->bytes_per_frame+32) * audio->clock_rate / audio->samples_per_frame))); if (audio->rtcp.stat.rx.update_cnt == 0) - strcpy(last_update, "never"); + strcpy(last_update, "never"); else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, audio->rtcp.stat.rx.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, audio->rtcp.stat.rx.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); } PJ_LOG(3, (THIS_FILE, - " RX stat last update: %s\n" - " total %s packets %sB received (%sB +IP hdr)%s\n" - " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" - " (msec) min avg max last\n" - " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" - " jitter : %7.3f %7.3f %7.3f %7.3f%s", - last_update, - good_number(packets, audio->rtcp.stat.rx.pkt), - good_number(bytes, audio->rtcp.stat.rx.bytes), - good_number(ipbytes, audio->rtcp.stat.rx.bytes + audio->rtcp.stat.rx.pkt * 32), - "", - audio->rtcp.stat.rx.loss, - audio->rtcp.stat.rx.loss * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), - audio->rtcp.stat.rx.dup, - audio->rtcp.stat.rx.dup * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), - audio->rtcp.stat.rx.reorder, - audio->rtcp.stat.rx.reorder * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), - "", - audio->rtcp.stat.rx.loss_period.min / 1000.0, - audio->rtcp.stat.rx.loss_period.mean / 1000.0, - audio->rtcp.stat.rx.loss_period.max / 1000.0, - audio->rtcp.stat.rx.loss_period.last / 1000.0, - "", - audio->rtcp.stat.rx.jitter.min / 1000.0, - audio->rtcp.stat.rx.jitter.mean / 1000.0, - audio->rtcp.stat.rx.jitter.max / 1000.0, - audio->rtcp.stat.rx.jitter.last / 1000.0, - "" - )); + " RX stat last update: %s\n" + " total %s packets %sB received (%sB +IP hdr)%s\n" + " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" + " (msec) min avg max last\n" + " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" + " jitter : %7.3f %7.3f %7.3f %7.3f%s", + last_update, + good_number(packets, audio->rtcp.stat.rx.pkt), + good_number(bytes, audio->rtcp.stat.rx.bytes), + good_number(ipbytes, audio->rtcp.stat.rx.bytes + audio->rtcp.stat.rx.pkt * 32), + "", + audio->rtcp.stat.rx.loss, + audio->rtcp.stat.rx.loss * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), + audio->rtcp.stat.rx.dup, + audio->rtcp.stat.rx.dup * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), + audio->rtcp.stat.rx.reorder, + audio->rtcp.stat.rx.reorder * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), + "", + audio->rtcp.stat.rx.loss_period.min / 1000.0, + audio->rtcp.stat.rx.loss_period.mean / 1000.0, + audio->rtcp.stat.rx.loss_period.max / 1000.0, + audio->rtcp.stat.rx.loss_period.last / 1000.0, + "", + audio->rtcp.stat.rx.jitter.min / 1000.0, + audio->rtcp.stat.rx.jitter.mean / 1000.0, + audio->rtcp.stat.rx.jitter.max / 1000.0, + audio->rtcp.stat.rx.jitter.last / 1000.0, + "" + )); if (audio->rtcp.stat.tx.update_cnt == 0) - strcpy(last_update, "never"); + strcpy(last_update, "never"); else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, audio->rtcp.stat.tx.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, audio->rtcp.stat.tx.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); } PJ_LOG(3, (THIS_FILE, - " TX stat last update: %s\n" - " total %s packets %sB sent (%sB +IP hdr)%s\n" - " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" - " (msec) min avg max last\n" - " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" - " jitter : %7.3f %7.3f %7.3f %7.3f%s", - last_update, - good_number(packets, audio->rtcp.stat.tx.pkt), - good_number(bytes, audio->rtcp.stat.tx.bytes), - good_number(ipbytes, audio->rtcp.stat.tx.bytes + audio->rtcp.stat.tx.pkt * 32), - "", - audio->rtcp.stat.tx.loss, - audio->rtcp.stat.tx.loss * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), - audio->rtcp.stat.tx.dup, - audio->rtcp.stat.tx.dup * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), - audio->rtcp.stat.tx.reorder, - audio->rtcp.stat.tx.reorder * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), - "", - audio->rtcp.stat.tx.loss_period.min / 1000.0, - audio->rtcp.stat.tx.loss_period.mean / 1000.0, - audio->rtcp.stat.tx.loss_period.max / 1000.0, - audio->rtcp.stat.tx.loss_period.last / 1000.0, - "", - audio->rtcp.stat.tx.jitter.min / 1000.0, - audio->rtcp.stat.tx.jitter.mean / 1000.0, - audio->rtcp.stat.tx.jitter.max / 1000.0, - audio->rtcp.stat.tx.jitter.last / 1000.0, - "" - )); + " TX stat last update: %s\n" + " total %s packets %sB sent (%sB +IP hdr)%s\n" + " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" + " (msec) min avg max last\n" + " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" + " jitter : %7.3f %7.3f %7.3f %7.3f%s", + last_update, + good_number(packets, audio->rtcp.stat.tx.pkt), + good_number(bytes, audio->rtcp.stat.tx.bytes), + good_number(ipbytes, audio->rtcp.stat.tx.bytes + audio->rtcp.stat.tx.pkt * 32), + "", + audio->rtcp.stat.tx.loss, + audio->rtcp.stat.tx.loss * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), + audio->rtcp.stat.tx.dup, + audio->rtcp.stat.tx.dup * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), + audio->rtcp.stat.tx.reorder, + audio->rtcp.stat.tx.reorder * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), + "", + audio->rtcp.stat.tx.loss_period.min / 1000.0, + audio->rtcp.stat.tx.loss_period.mean / 1000.0, + audio->rtcp.stat.tx.loss_period.max / 1000.0, + audio->rtcp.stat.tx.loss_period.last / 1000.0, + "", + audio->rtcp.stat.tx.jitter.min / 1000.0, + audio->rtcp.stat.tx.jitter.mean / 1000.0, + audio->rtcp.stat.tx.jitter.max / 1000.0, + audio->rtcp.stat.tx.jitter.last / 1000.0, + "" + )); PJ_LOG(3, (THIS_FILE, - " RTT delay : %7.3f %7.3f %7.3f %7.3f%s\n", - audio->rtcp.stat.rtt.min / 1000.0, - audio->rtcp.stat.rtt.mean / 1000.0, - audio->rtcp.stat.rtt.max / 1000.0, - audio->rtcp.stat.rtt.last / 1000.0, - "" - )); + " RTT delay : %7.3f %7.3f %7.3f %7.3f%s\n", + audio->rtcp.stat.rtt.min / 1000.0, + audio->rtcp.stat.rtt.mean / 1000.0, + audio->rtcp.stat.rtt.max / 1000.0, + audio->rtcp.stat.rtt.last / 1000.0, + "" + )); pj_log_set_decor(decor); } diff --git a/pjsip-apps/src/samples/sipstateless.c b/pjsip-apps/src/samples/sipstateless.c index 5e939ab4b9..38d62d0d45 100644 --- a/pjsip-apps/src/samples/sipstateless.c +++ b/pjsip-apps/src/samples/sipstateless.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -40,7 +39,7 @@ #define HAS_TCP_TRANSPORT (1 && PJ_HAS_TCP) /* Log identification */ -#define THIS_FILE "sipstateless.c" +#define THIS_FILE "sipstateless.c" /* Global SIP endpoint */ @@ -74,9 +73,9 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) * with 501 (Not Implemented) */ if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { - pjsip_endpt_respond_stateless( sip_endpt, rdata, - code, NULL, - &hdr_list, NULL); + pjsip_endpt_respond_stateless( sip_endpt, rdata, + code, NULL, + &hdr_list, NULL); } return PJ_TRUE; } @@ -93,19 +92,19 @@ int main(int argc, char *argv[]) pj_pool_t *pool = NULL; pjsip_module mod_app = { - NULL, NULL, /* prev, next. */ - { "mod-app", 7 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-app", 7 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; int c; pj_status_t status; @@ -124,64 +123,64 @@ int main(int argc, char *argv[]) /* Create global endpoint: */ { - /* Endpoint MUST be assigned a globally unique name. - * Ideally we should put hostname or public IP address, but - * we'll just use an arbitrary name here. - */ - - /* Create the endpoint: */ - status = pjsip_endpt_create(&cp.factory, "sipstateless", - &sip_endpt); - PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); + /* Endpoint MUST be assigned a globally unique name. + * Ideally we should put hostname or public IP address, but + * we'll just use an arbitrary name here. + */ + + /* Create the endpoint: */ + status = pjsip_endpt_create(&cp.factory, "sipstateless", + &sip_endpt); + PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); } /* Parse arguments */ pj_optind = 0; pj_list_init(&hdr_list); while ((c=pj_getopt(argc, argv , "H:")) != -1) { - switch (c) { - case 'H': - if (pool == NULL) { - pool = pj_pool_create(&cp.factory, "sipstateless", 1000, - 1000, NULL); - } - - if (pool) { - char *name; - name = strtok(pj_optarg, ":"); - if (name == NULL) { - puts("Error: invalid header format"); - return 1; - } else { - char *val = strtok(NULL, "\r\n"); - pjsip_generic_string_hdr *h; - pj_str_t hname, hvalue; - - hname = pj_str(name); - hvalue = pj_str(val); - - h = pjsip_generic_string_hdr_create(pool, &hname, &hvalue); - - pj_list_push_back(&hdr_list, h); - - PJ_LOG(4,(THIS_FILE, "Header %s: %s added", name, val)); - } - } - break; - default: - puts("Error: invalid argument"); - usage(); - return 1; - } + switch (c) { + case 'H': + if (pool == NULL) { + pool = pj_pool_create(&cp.factory, "sipstateless", 1000, + 1000, NULL); + } + + if (pool) { + char *name; + name = strtok(pj_optarg, ":"); + if (name == NULL) { + puts("Error: invalid header format"); + return 1; + } else { + char *val = strtok(NULL, "\r\n"); + pjsip_generic_string_hdr *h; + pj_str_t hname, hvalue; + + hname = pj_str(name); + hvalue = pj_str(val); + + h = pjsip_generic_string_hdr_create(pool, &hname, &hvalue); + + pj_list_push_back(&hdr_list, h); + + PJ_LOG(4,(THIS_FILE, "Header %s: %s added", name, val)); + } + } + break; + default: + puts("Error: invalid argument"); + usage(); + return 1; + } } if (pj_optind != argc) { - code = atoi(argv[pj_optind]); - if (code < 200 || code > 699) { - puts("Error: invalid status code"); - usage(); - return 1; - } + code = atoi(argv[pj_optind]); + if (code < 200 || code > 699) { + puts("Error: invalid status code"); + usage(); + return 1; + } } PJ_LOG(4,(THIS_FILE, "Returning %d to incoming requests", code)); @@ -192,18 +191,18 @@ int main(int argc, char *argv[]) */ #ifdef HAS_UDP_TRANSPORT { - pj_sockaddr_in addr; - - addr.sin_family = pj_AF_INET(); - addr.sin_addr.s_addr = 0; - addr.sin_port = pj_htons(5060); - - status = pjsip_udp_transport_start( sip_endpt, &addr, NULL, 1, NULL); - if (status != PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, - "Error starting UDP transport (port in use?)")); - return 1; - } + pj_sockaddr_in addr; + + addr.sin_family = pj_AF_INET(); + addr.sin_addr.s_addr = 0; + addr.sin_port = pj_htons(5060); + + status = pjsip_udp_transport_start( sip_endpt, &addr, NULL, 1, NULL); + if (status != PJ_SUCCESS) { + PJ_LOG(3,(THIS_FILE, + "Error starting UDP transport (port in use?)")); + return 1; + } } #endif @@ -212,18 +211,18 @@ int main(int argc, char *argv[]) * Add UDP transport, with hard-coded port */ { - pj_sockaddr_in addr; - - addr.sin_family = pj_AF_INET(); - addr.sin_addr.s_addr = 0; - addr.sin_port = pj_htons(5060); - - status = pjsip_tcp_transport_start(sip_endpt, &addr, 1, NULL); - if (status != PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, - "Error starting TCP transport (port in use?)")); - return 1; - } + pj_sockaddr_in addr; + + addr.sin_family = pj_AF_INET(); + addr.sin_addr.s_addr = 0; + addr.sin_port = pj_htons(5060); + + status = pjsip_tcp_transport_start(sip_endpt, &addr, 1, NULL); + if (status != PJ_SUCCESS) { + PJ_LOG(3,(THIS_FILE, + "Error starting TCP transport (port in use?)")); + return 1; + } } #endif @@ -238,6 +237,6 @@ int main(int argc, char *argv[]) PJ_LOG(3,(THIS_FILE, "Press Ctrl-C to quit..")); for (;;) { - pjsip_endpt_handle_events(sip_endpt, NULL); + pjsip_endpt_handle_events(sip_endpt, NULL); } } diff --git a/pjsip-apps/src/samples/stateful_proxy.c b/pjsip-apps/src/samples/stateful_proxy.c index 9dfb9f192d..d1d0ac29ee 100644 --- a/pjsip-apps/src/samples/stateful_proxy.c +++ b/pjsip-apps/src/samples/stateful_proxy.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -33,19 +32,19 @@ static pj_bool_t proxy_on_rx_response(pjsip_rx_data *rdata ); static pjsip_module mod_stateful_proxy = { - NULL, NULL, /* prev, next. */ - { "mod-stateful-proxy", 18 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_UA_PROXY_LAYER, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &proxy_on_rx_request, /* on_rx_request() */ - &proxy_on_rx_response, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-stateful-proxy", 18 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_UA_PROXY_LAYER, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &proxy_on_rx_request, /* on_rx_request() */ + &proxy_on_rx_response, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -57,34 +56,34 @@ static void tu_on_tsx_state(pjsip_transaction *tsx, pjsip_event *event); static pjsip_module mod_tu = { - NULL, NULL, /* prev, next. */ - { "mod-transaction-user", 20 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - NULL, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - &tu_on_tsx_state, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-transaction-user", 20 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + &tu_on_tsx_state, /* on_tsx_state() */ }; /* This is the data that is attached to the UAC transaction */ struct uac_data { - pjsip_transaction *uas_tsx; - pj_timer_entry timer; + pjsip_transaction *uas_tsx; + pj_timer_entry timer; }; /* This is the data that is attached to the UAS transaction */ struct uas_data { - pjsip_transaction *uac_tsx; + pjsip_transaction *uac_tsx; }; @@ -114,176 +113,176 @@ static pj_bool_t proxy_on_rx_request( pjsip_rx_data *rdata ) if (rdata->msg_info.msg->line.req.method.id != PJSIP_CANCEL_METHOD) { - /* Verify incoming request */ - status = proxy_verify_request(rdata); - if (status != PJ_SUCCESS) { - app_perror("RX invalid request", status); - return PJ_TRUE; - } - - /* - * Request looks sane, next clone the request to create transmit data. - */ - status = pjsip_endpt_create_request_fwd(global.endpt, rdata, NULL, - NULL, 0, &tdata); - if (status != PJ_SUCCESS) { - pjsip_endpt_respond_stateless(global.endpt, rdata, - PJSIP_SC_INTERNAL_SERVER_ERROR, - NULL, NULL, NULL); - return PJ_TRUE; - } - - - /* Process routing */ - status = proxy_process_routing(tdata); - if (status != PJ_SUCCESS) { - app_perror("Error processing route", status); - return PJ_TRUE; - } - - /* Calculate target */ - status = proxy_calculate_target(rdata, tdata); - if (status != PJ_SUCCESS) { - app_perror("Error calculating target", status); - return PJ_TRUE; - } - - /* Everything is set to forward the request. */ - - /* If this is an ACK request, forward statelessly. - * This happens if the proxy records route and this ACK - * is sent for 2xx response. An ACK that is sent for non-2xx - * final response will be absorbed by transaction layer, and - * it will not be received by on_rx_request() callback. - */ - if (tdata->msg->line.req.method.id == PJSIP_ACK_METHOD) { - status = pjsip_endpt_send_request_stateless(global.endpt, tdata, - NULL, NULL); - if (status != PJ_SUCCESS) { - app_perror("Error forwarding request", status); - return PJ_TRUE; - } - - return PJ_TRUE; - } - - /* Create UAC transaction for forwarding the request. - * Set our module as the transaction user to receive further - * events from this transaction. - */ - status = pjsip_tsx_create_uac(&mod_tu, tdata, &uac_tsx); - if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - pjsip_endpt_respond_stateless(global.endpt, rdata, - PJSIP_SC_INTERNAL_SERVER_ERROR, - NULL, NULL, NULL); - return PJ_TRUE; - } - - /* Create UAS transaction to handle incoming request */ - status = pjsip_tsx_create_uas(&mod_tu, rdata, &uas_tsx); - if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - pjsip_endpt_respond_stateless(global.endpt, rdata, - PJSIP_SC_INTERNAL_SERVER_ERROR, - NULL, NULL, NULL); - pjsip_tsx_terminate(uac_tsx, PJSIP_SC_INTERNAL_SERVER_ERROR); - return PJ_TRUE; - } - - /* Feed the request to the UAS transaction to drive it's state - * out of NULL state. - */ - pjsip_tsx_recv_msg(uas_tsx, rdata); - - /* Attach a data to the UAC transaction, to be used to find the - * UAS transaction when we receive response in the UAC side. - */ - uac_data = (struct uac_data*) - pj_pool_alloc(uac_tsx->pool, sizeof(struct uac_data)); - uac_data->uas_tsx = uas_tsx; - uac_tsx->mod_data[mod_tu.id] = (void*)uac_data; - - /* Attach data to the UAS transaction, to find the UAC transaction - * when cancelling INVITE request. - */ - uas_data = (struct uas_data*) - pj_pool_alloc(uas_tsx->pool, sizeof(struct uas_data)); - uas_data->uac_tsx = uac_tsx; - uas_tsx->mod_data[mod_tu.id] = (void*)uas_data; - - /* Everything is setup, forward the request */ - status = pjsip_tsx_send_msg(uac_tsx, tdata); - if (status != PJ_SUCCESS) { - pjsip_tx_data *err_res; - - /* Fail to send request, for some reason */ - - /* Destroy transmit data */ - pjsip_tx_data_dec_ref(tdata); - - /* I think UAC transaction should have been destroyed when - * it fails to send request, so no need to destroy it. - pjsip_tsx_terminate(uac_tsx, PJSIP_SC_INTERNAL_SERVER_ERROR); - */ - - /* Send 500/Internal Server Error to UAS transaction */ - pjsip_endpt_create_response(global.endpt, rdata, - 500, NULL, &err_res); - pjsip_tsx_send_msg(uas_tsx, err_res); - - return PJ_TRUE; - } - - /* Send 100/Trying if this is an INVITE */ - if (rdata->msg_info.msg->line.req.method.id == PJSIP_INVITE_METHOD) { - pjsip_tx_data *res100; - - pjsip_endpt_create_response(global.endpt, rdata, 100, NULL, - &res100); - pjsip_tsx_send_msg(uas_tsx, res100); - } + /* Verify incoming request */ + status = proxy_verify_request(rdata); + if (status != PJ_SUCCESS) { + app_perror("RX invalid request", status); + return PJ_TRUE; + } + + /* + * Request looks sane, next clone the request to create transmit data. + */ + status = pjsip_endpt_create_request_fwd(global.endpt, rdata, NULL, + NULL, 0, &tdata); + if (status != PJ_SUCCESS) { + pjsip_endpt_respond_stateless(global.endpt, rdata, + PJSIP_SC_INTERNAL_SERVER_ERROR, + NULL, NULL, NULL); + return PJ_TRUE; + } + + + /* Process routing */ + status = proxy_process_routing(tdata); + if (status != PJ_SUCCESS) { + app_perror("Error processing route", status); + return PJ_TRUE; + } + + /* Calculate target */ + status = proxy_calculate_target(rdata, tdata); + if (status != PJ_SUCCESS) { + app_perror("Error calculating target", status); + return PJ_TRUE; + } + + /* Everything is set to forward the request. */ + + /* If this is an ACK request, forward statelessly. + * This happens if the proxy records route and this ACK + * is sent for 2xx response. An ACK that is sent for non-2xx + * final response will be absorbed by transaction layer, and + * it will not be received by on_rx_request() callback. + */ + if (tdata->msg->line.req.method.id == PJSIP_ACK_METHOD) { + status = pjsip_endpt_send_request_stateless(global.endpt, tdata, + NULL, NULL); + if (status != PJ_SUCCESS) { + app_perror("Error forwarding request", status); + return PJ_TRUE; + } + + return PJ_TRUE; + } + + /* Create UAC transaction for forwarding the request. + * Set our module as the transaction user to receive further + * events from this transaction. + */ + status = pjsip_tsx_create_uac(&mod_tu, tdata, &uac_tsx); + if (status != PJ_SUCCESS) { + pjsip_tx_data_dec_ref(tdata); + pjsip_endpt_respond_stateless(global.endpt, rdata, + PJSIP_SC_INTERNAL_SERVER_ERROR, + NULL, NULL, NULL); + return PJ_TRUE; + } + + /* Create UAS transaction to handle incoming request */ + status = pjsip_tsx_create_uas(&mod_tu, rdata, &uas_tsx); + if (status != PJ_SUCCESS) { + pjsip_tx_data_dec_ref(tdata); + pjsip_endpt_respond_stateless(global.endpt, rdata, + PJSIP_SC_INTERNAL_SERVER_ERROR, + NULL, NULL, NULL); + pjsip_tsx_terminate(uac_tsx, PJSIP_SC_INTERNAL_SERVER_ERROR); + return PJ_TRUE; + } + + /* Feed the request to the UAS transaction to drive it's state + * out of NULL state. + */ + pjsip_tsx_recv_msg(uas_tsx, rdata); + + /* Attach a data to the UAC transaction, to be used to find the + * UAS transaction when we receive response in the UAC side. + */ + uac_data = (struct uac_data*) + pj_pool_alloc(uac_tsx->pool, sizeof(struct uac_data)); + uac_data->uas_tsx = uas_tsx; + uac_tsx->mod_data[mod_tu.id] = (void*)uac_data; + + /* Attach data to the UAS transaction, to find the UAC transaction + * when cancelling INVITE request. + */ + uas_data = (struct uas_data*) + pj_pool_alloc(uas_tsx->pool, sizeof(struct uas_data)); + uas_data->uac_tsx = uac_tsx; + uas_tsx->mod_data[mod_tu.id] = (void*)uas_data; + + /* Everything is setup, forward the request */ + status = pjsip_tsx_send_msg(uac_tsx, tdata); + if (status != PJ_SUCCESS) { + pjsip_tx_data *err_res; + + /* Fail to send request, for some reason */ + + /* Destroy transmit data */ + pjsip_tx_data_dec_ref(tdata); + + /* I think UAC transaction should have been destroyed when + * it fails to send request, so no need to destroy it. + pjsip_tsx_terminate(uac_tsx, PJSIP_SC_INTERNAL_SERVER_ERROR); + */ + + /* Send 500/Internal Server Error to UAS transaction */ + pjsip_endpt_create_response(global.endpt, rdata, + 500, NULL, &err_res); + pjsip_tsx_send_msg(uas_tsx, err_res); + + return PJ_TRUE; + } + + /* Send 100/Trying if this is an INVITE */ + if (rdata->msg_info.msg->line.req.method.id == PJSIP_INVITE_METHOD) { + pjsip_tx_data *res100; + + pjsip_endpt_create_response(global.endpt, rdata, 100, NULL, + &res100); + pjsip_tsx_send_msg(uas_tsx, res100); + } } else { - /* This is CANCEL request */ - pjsip_transaction *invite_uas; - struct uas_data *uas_data2; - pj_str_t key; - - /* Find the UAS INVITE transaction */ - pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_UAS_ROLE, - pjsip_get_invite_method(), rdata); - invite_uas = pjsip_tsx_layer_find_tsx(&key, PJ_TRUE); - if (!invite_uas) { - /* Invite transaction not found, respond CANCEL with 481 */ - pjsip_endpt_respond_stateless(global.endpt, rdata, 481, NULL, - NULL, NULL); - return PJ_TRUE; - } - - /* Respond 200 OK to CANCEL */ - pjsip_endpt_respond(global.endpt, NULL, rdata, 200, NULL, NULL, - NULL, NULL); - - /* Send CANCEL to cancel the UAC transaction. - * The UAS INVITE transaction will get final response when - * we receive final response from the UAC INVITE transaction. - */ - uas_data2 = (struct uas_data*) invite_uas->mod_data[mod_tu.id]; - if (uas_data2->uac_tsx && uas_data2->uac_tsx->status_code < 200) { - pjsip_tx_data *cancel; - - pj_grp_lock_acquire(uas_data2->uac_tsx->grp_lock); - - pjsip_endpt_create_cancel(global.endpt, uas_data2->uac_tsx->last_tx, - &cancel); - pjsip_endpt_send_request(global.endpt, cancel, -1, NULL, NULL); - - pj_grp_lock_release(uas_data2->uac_tsx->grp_lock); - } - - /* Unlock UAS tsx because it is locked in find_tsx() */ - pj_grp_lock_release(invite_uas->grp_lock); + /* This is CANCEL request */ + pjsip_transaction *invite_uas; + struct uas_data *uas_data2; + pj_str_t key; + + /* Find the UAS INVITE transaction */ + pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_UAS_ROLE, + pjsip_get_invite_method(), rdata); + invite_uas = pjsip_tsx_layer_find_tsx(&key, PJ_TRUE); + if (!invite_uas) { + /* Invite transaction not found, respond CANCEL with 481 */ + pjsip_endpt_respond_stateless(global.endpt, rdata, 481, NULL, + NULL, NULL); + return PJ_TRUE; + } + + /* Respond 200 OK to CANCEL */ + pjsip_endpt_respond(global.endpt, NULL, rdata, 200, NULL, NULL, + NULL, NULL); + + /* Send CANCEL to cancel the UAC transaction. + * The UAS INVITE transaction will get final response when + * we receive final response from the UAC INVITE transaction. + */ + uas_data2 = (struct uas_data*) invite_uas->mod_data[mod_tu.id]; + if (uas_data2->uac_tsx && uas_data2->uac_tsx->status_code < 200) { + pjsip_tx_data *cancel; + + pj_grp_lock_acquire(uas_data2->uac_tsx->grp_lock); + + pjsip_endpt_create_cancel(global.endpt, uas_data2->uac_tsx->last_tx, + &cancel); + pjsip_endpt_send_request(global.endpt, cancel, -1, NULL, NULL); + + pj_grp_lock_release(uas_data2->uac_tsx->grp_lock); + } + + /* Unlock UAS tsx because it is locked in find_tsx() */ + pj_grp_lock_release(invite_uas->grp_lock); } return PJ_TRUE; @@ -306,49 +305,49 @@ static pj_bool_t proxy_on_rx_response( pjsip_rx_data *rdata ) /* Create response to be forwarded upstream (Via will be stripped here) */ status = pjsip_endpt_create_response_fwd(global.endpt, rdata, 0, &tdata); if (status != PJ_SUCCESS) { - app_perror("Error creating response", status); - return PJ_TRUE; + app_perror("Error creating response", status); + return PJ_TRUE; } /* Get topmost Via header */ hvia = (pjsip_via_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); if (hvia == NULL) { - /* Invalid response! Just drop it */ - pjsip_tx_data_dec_ref(tdata); - return PJ_TRUE; + /* Invalid response! Just drop it */ + pjsip_tx_data_dec_ref(tdata); + return PJ_TRUE; } /* Calculate the address to forward the response */ pj_bzero(&res_addr, sizeof(res_addr)); res_addr.dst_host.type = PJSIP_TRANSPORT_UDP; res_addr.dst_host.flag = - pjsip_transport_get_flag_from_type(PJSIP_TRANSPORT_UDP); + pjsip_transport_get_flag_from_type(PJSIP_TRANSPORT_UDP); /* Destination address is Via's received param */ res_addr.dst_host.addr.host = hvia->recvd_param; if (res_addr.dst_host.addr.host.slen == 0) { - /* Someone has messed up our Via header! */ - res_addr.dst_host.addr.host = hvia->sent_by.host; + /* Someone has messed up our Via header! */ + res_addr.dst_host.addr.host = hvia->sent_by.host; } /* Destination port is the rport */ if (hvia->rport_param != 0 && hvia->rport_param != -1) - res_addr.dst_host.addr.port = hvia->rport_param; + res_addr.dst_host.addr.port = hvia->rport_param; if (res_addr.dst_host.addr.port == 0) { - /* Ugh, original sender didn't put rport! - * At best, can only send the response to the port in Via. - */ - res_addr.dst_host.addr.port = hvia->sent_by.port; + /* Ugh, original sender didn't put rport! + * At best, can only send the response to the port in Via. + */ + res_addr.dst_host.addr.port = hvia->sent_by.port; } /* Forward response */ status = pjsip_endpt_send_response(global.endpt, &res_addr, tdata, - NULL, NULL); + NULL, NULL); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - app_perror("Error forwarding response", status); - return PJ_TRUE; + pjsip_tx_data_dec_ref(tdata); + app_perror("Error forwarding response", status); + return PJ_TRUE; } return PJ_TRUE; @@ -362,18 +361,18 @@ static void tu_on_tsx_state(pjsip_transaction *tsx, pjsip_event *event) pj_status_t status; if (tsx->role == PJSIP_ROLE_UAS) { - if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - struct uas_data *uas_data; - - uas_data = (struct uas_data*) tsx->mod_data[mod_tu.id]; - if (uas_data->uac_tsx) { - uac_data = (struct uac_data*) - uas_data->uac_tsx->mod_data[mod_tu.id]; - uac_data->uas_tsx = NULL; - } - - } - return; + if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + struct uas_data *uas_data; + + uas_data = (struct uas_data*) tsx->mod_data[mod_tu.id]; + if (uas_data->uac_tsx) { + uac_data = (struct uac_data*) + uas_data->uac_tsx->mod_data[mod_tu.id]; + uac_data->uas_tsx = NULL; + } + + } + return; } /* Get the data that we attached to the UAC transaction previously */ @@ -383,123 +382,123 @@ static void tu_on_tsx_state(pjsip_transaction *tsx, pjsip_event *event) /* Handle incoming response */ if (event->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - pjsip_rx_data *rdata; - pjsip_response_addr res_addr; + pjsip_rx_data *rdata; + pjsip_response_addr res_addr; pjsip_via_hdr *hvia; - pjsip_tx_data *tdata; - - rdata = event->body.tsx_state.src.rdata; - - /* Do not forward 100 response for INVITE (we already responded - * INVITE with 100) - */ - if (tsx->method.id == PJSIP_INVITE_METHOD && - rdata->msg_info.msg->line.status.code == 100) - { - return; - } - - /* Create response to be forwarded upstream - * (Via will be stripped here) - */ - status = pjsip_endpt_create_response_fwd(global.endpt, rdata, 0, - &tdata); - if (status != PJ_SUCCESS) { - app_perror("Error creating response", status); - return; - } - - /* Get topmost Via header of the new response */ - hvia = (pjsip_via_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, - NULL); - if (hvia == NULL) { - /* Invalid response! Just drop it */ - pjsip_tx_data_dec_ref(tdata); - return; - } - - /* Calculate the address to forward the response */ - pj_bzero(&res_addr, sizeof(res_addr)); - res_addr.dst_host.type = PJSIP_TRANSPORT_UDP; - res_addr.dst_host.flag = - pjsip_transport_get_flag_from_type(PJSIP_TRANSPORT_UDP); - - /* Destination address is Via's received param */ - res_addr.dst_host.addr.host = hvia->recvd_param; - if (res_addr.dst_host.addr.host.slen == 0) { - /* Someone has messed up our Via header! */ - res_addr.dst_host.addr.host = hvia->sent_by.host; - } - - /* Destination port is the rport */ - if (hvia->rport_param != 0 && hvia->rport_param != -1) - res_addr.dst_host.addr.port = hvia->rport_param; - - if (res_addr.dst_host.addr.port == 0) { - /* Ugh, original sender didn't put rport! - * At best, can only send the response to the port in Via. - */ - res_addr.dst_host.addr.port = hvia->sent_by.port; - } - - /* Forward response with the UAS transaction */ - pjsip_tsx_send_msg(uac_data->uas_tsx, tdata); + pjsip_tx_data *tdata; + + rdata = event->body.tsx_state.src.rdata; + + /* Do not forward 100 response for INVITE (we already responded + * INVITE with 100) + */ + if (tsx->method.id == PJSIP_INVITE_METHOD && + rdata->msg_info.msg->line.status.code == 100) + { + return; + } + + /* Create response to be forwarded upstream + * (Via will be stripped here) + */ + status = pjsip_endpt_create_response_fwd(global.endpt, rdata, 0, + &tdata); + if (status != PJ_SUCCESS) { + app_perror("Error creating response", status); + return; + } + + /* Get topmost Via header of the new response */ + hvia = (pjsip_via_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, + NULL); + if (hvia == NULL) { + /* Invalid response! Just drop it */ + pjsip_tx_data_dec_ref(tdata); + return; + } + + /* Calculate the address to forward the response */ + pj_bzero(&res_addr, sizeof(res_addr)); + res_addr.dst_host.type = PJSIP_TRANSPORT_UDP; + res_addr.dst_host.flag = + pjsip_transport_get_flag_from_type(PJSIP_TRANSPORT_UDP); + + /* Destination address is Via's received param */ + res_addr.dst_host.addr.host = hvia->recvd_param; + if (res_addr.dst_host.addr.host.slen == 0) { + /* Someone has messed up our Via header! */ + res_addr.dst_host.addr.host = hvia->sent_by.host; + } + + /* Destination port is the rport */ + if (hvia->rport_param != 0 && hvia->rport_param != -1) + res_addr.dst_host.addr.port = hvia->rport_param; + + if (res_addr.dst_host.addr.port == 0) { + /* Ugh, original sender didn't put rport! + * At best, can only send the response to the port in Via. + */ + res_addr.dst_host.addr.port = hvia->sent_by.port; + } + + /* Forward response with the UAS transaction */ + pjsip_tsx_send_msg(uac_data->uas_tsx, tdata); } /* If UAC transaction is terminated, terminate the UAS as well. * This could happen because of: - * - timeout on the UAC side + * - timeout on the UAC side * - receipt of 2xx response to INVITE */ if (tsx->state == PJSIP_TSX_STATE_TERMINATED && uac_data && - uac_data->uas_tsx) + uac_data->uas_tsx) { - pjsip_transaction *uas_tsx; - struct uas_data *uas_data; + pjsip_transaction *uas_tsx; + struct uas_data *uas_data; - uas_tsx = uac_data->uas_tsx; - uas_data = (struct uas_data*) uas_tsx->mod_data[mod_tu.id]; - uas_data->uac_tsx = NULL; + uas_tsx = uac_data->uas_tsx; + uas_data = (struct uas_data*) uas_tsx->mod_data[mod_tu.id]; + uas_data->uac_tsx = NULL; - if (event->body.tsx_state.type == PJSIP_EVENT_TIMER) { + if (event->body.tsx_state.type == PJSIP_EVENT_TIMER) { - /* Send 408/Timeout if this is an INVITE transaction, since - * we must have sent provisional response before. For non - * INVITE transaction, just destroy it. - */ - if (tsx->method.id == PJSIP_INVITE_METHOD) { + /* Send 408/Timeout if this is an INVITE transaction, since + * we must have sent provisional response before. For non + * INVITE transaction, just destroy it. + */ + if (tsx->method.id == PJSIP_INVITE_METHOD) { - pjsip_tx_data *tdata = uas_tsx->last_tx; + pjsip_tx_data *tdata = uas_tsx->last_tx; - tdata->msg->line.status.code = PJSIP_SC_REQUEST_TIMEOUT; - tdata->msg->line.status.reason = pj_str("Request timed out"); - tdata->msg->body = NULL; + tdata->msg->line.status.code = PJSIP_SC_REQUEST_TIMEOUT; + tdata->msg->line.status.reason = pj_str("Request timed out"); + tdata->msg->body = NULL; - pjsip_tx_data_add_ref(tdata); - pjsip_tx_data_invalidate_msg(tdata); + pjsip_tx_data_add_ref(tdata); + pjsip_tx_data_invalidate_msg(tdata); - pjsip_tsx_send_msg(uas_tsx, tdata); + pjsip_tsx_send_msg(uas_tsx, tdata); - } else { - /* For non-INVITE, just destroy the UAS transaction */ - pjsip_tsx_terminate(uas_tsx, PJSIP_SC_REQUEST_TIMEOUT); - } + } else { + /* For non-INVITE, just destroy the UAS transaction */ + pjsip_tsx_terminate(uas_tsx, PJSIP_SC_REQUEST_TIMEOUT); + } - } else if (event->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { + } else if (event->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - if (uas_tsx->state < PJSIP_TSX_STATE_TERMINATED) { - pjsip_msg *msg; - int code; + if (uas_tsx->state < PJSIP_TSX_STATE_TERMINATED) { + pjsip_msg *msg; + int code; - msg = event->body.tsx_state.src.rdata->msg_info.msg; - code = msg->line.status.code; + msg = event->body.tsx_state.src.rdata->msg_info.msg; + code = msg->line.status.code; - uac_data->uas_tsx = NULL; - pjsip_tsx_terminate(uas_tsx, code); - } - } + uac_data->uas_tsx = NULL; + pjsip_tsx_terminate(uas_tsx, code); + } + } } } @@ -518,57 +517,57 @@ int main(int argc, char *argv[]) status = init_options(argc, argv); if (status != PJ_SUCCESS) - return 1; + return 1; status = init_stack(); if (status != PJ_SUCCESS) { - app_perror("Error initializing stack", status); - return 1; + app_perror("Error initializing stack", status); + return 1; } status = init_proxy(); if (status != PJ_SUCCESS) { - app_perror("Error initializing proxy", status); - return 1; + app_perror("Error initializing proxy", status); + return 1; } status = init_stateful_proxy(); if (status != PJ_SUCCESS) { - app_perror("Error initializing stateful proxy", status); - return 1; + app_perror("Error initializing stateful proxy", status); + return 1; } #if PJ_HAS_THREADS status = pj_thread_create(global.pool, "sproxy", &worker_thread, - NULL, 0, 0, &global.thread); + NULL, 0, 0, &global.thread); if (status != PJ_SUCCESS) { - app_perror("Error creating thread", status); - return 1; + app_perror("Error creating thread", status); + return 1; } while (!global.quit_flag) { - char line[10]; - - puts("\n" - "Menu:\n" - " q quit\n" - " d dump status\n" - " dd dump detailed status\n" - ""); - - if (fgets(line, sizeof(line), stdin) == NULL) { - puts("EOF while reading stdin, will quit now.."); - global.quit_flag = PJ_TRUE; - break; - } - - if (line[0] == 'q') { - global.quit_flag = PJ_TRUE; - } else if (line[0] == 'd') { - pj_bool_t detail = (line[1] == 'd'); - pjsip_endpt_dump(global.endpt, detail); - pjsip_tsx_layer_dump(detail); - } + char line[10]; + + puts("\n" + "Menu:\n" + " q quit\n" + " d dump status\n" + " dd dump detailed status\n" + ""); + + if (fgets(line, sizeof(line), stdin) == NULL) { + puts("EOF while reading stdin, will quit now.."); + global.quit_flag = PJ_TRUE; + break; + } + + if (line[0] == 'q') { + global.quit_flag = PJ_TRUE; + } else if (line[0] == 'd') { + pj_bool_t detail = (line[1] == 'd'); + pjsip_endpt_dump(global.endpt, detail); + pjsip_tsx_layer_dump(detail); + } } pj_thread_join(global.thread); @@ -576,8 +575,8 @@ int main(int argc, char *argv[]) #else puts("\nPress Ctrl-C to quit\n"); for (;;) { - pj_time_val delay = {0, 0}; - pjsip_endpt_handle_events(global.endpt, &delay); + pj_time_val delay = {0, 0}; + pjsip_endpt_handle_events(global.endpt, &delay); } #endif diff --git a/pjsip-apps/src/samples/stateless_proxy.c b/pjsip-apps/src/samples/stateless_proxy.c index afd45cd917..c0198ac1d3 100644 --- a/pjsip-apps/src/samples/stateless_proxy.c +++ b/pjsip-apps/src/samples/stateless_proxy.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,19 +34,19 @@ static pj_status_t init_stateless_proxy(void) { static pjsip_module mod_stateless_proxy = { - NULL, NULL, /* prev, next. */ - { "mod-stateless-proxy", 19 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_UA_PROXY_LAYER, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &on_rx_request, /* on_rx_request() */ - &on_rx_response, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-stateless-proxy", 19 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_UA_PROXY_LAYER, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &on_rx_request, /* on_rx_request() */ + &on_rx_response, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; pj_status_t status; @@ -70,43 +69,43 @@ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) /* Verify incoming request */ status = proxy_verify_request(rdata); if (status != PJ_SUCCESS) { - app_perror("RX invalid request", status); - return PJ_TRUE; + app_perror("RX invalid request", status); + return PJ_TRUE; } /* * Request looks sane, next clone the request to create transmit data. */ status = pjsip_endpt_create_request_fwd(global.endpt, rdata, NULL, - NULL, 0, &tdata); + NULL, 0, &tdata); if (status != PJ_SUCCESS) { - pjsip_endpt_respond_stateless(global.endpt, rdata, - PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, - NULL, NULL); - return PJ_TRUE; + pjsip_endpt_respond_stateless(global.endpt, rdata, + PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, + NULL, NULL); + return PJ_TRUE; } /* Process routing */ status = proxy_process_routing(tdata); if (status != PJ_SUCCESS) { - app_perror("Error processing route", status); - return PJ_TRUE; + app_perror("Error processing route", status); + return PJ_TRUE; } /* Calculate target */ status = proxy_calculate_target(rdata, tdata); if (status != PJ_SUCCESS) { - app_perror("Error calculating target", status); - return PJ_TRUE; + app_perror("Error calculating target", status); + return PJ_TRUE; } /* Target is set, forward the request */ status = pjsip_endpt_send_request_stateless(global.endpt, tdata, - NULL, NULL); + NULL, NULL); if (status != PJ_SUCCESS) { - app_perror("Error forwarding request", status); - return PJ_TRUE; + app_perror("Error forwarding request", status); + return PJ_TRUE; } return PJ_TRUE; @@ -124,16 +123,16 @@ static pj_bool_t on_rx_response( pjsip_rx_data *rdata ) /* Create response to be forwarded upstream (Via will be stripped here) */ status = pjsip_endpt_create_response_fwd(global.endpt, rdata, 0, &tdata); if (status != PJ_SUCCESS) { - app_perror("Error creating response", status); - return PJ_TRUE; + app_perror("Error creating response", status); + return PJ_TRUE; } /* Get topmost Via header */ hvia = (pjsip_via_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); if (hvia == NULL) { - /* Invalid response! Just drop it */ - pjsip_tx_data_dec_ref(tdata); - return PJ_TRUE; + /* Invalid response! Just drop it */ + pjsip_tx_data_dec_ref(tdata); + return PJ_TRUE; } /* Calculate the address to forward the response */ @@ -144,28 +143,28 @@ static pj_bool_t on_rx_response( pjsip_rx_data *rdata ) /* Destination address is Via's received param */ res_addr.dst_host.addr.host = hvia->recvd_param; if (res_addr.dst_host.addr.host.slen == 0) { - /* Someone has messed up our Via header! */ - res_addr.dst_host.addr.host = hvia->sent_by.host; + /* Someone has messed up our Via header! */ + res_addr.dst_host.addr.host = hvia->sent_by.host; } /* Destination port is the rpot */ if (hvia->rport_param != 0 && hvia->rport_param != -1) - res_addr.dst_host.addr.port = hvia->rport_param; + res_addr.dst_host.addr.port = hvia->rport_param; if (res_addr.dst_host.addr.port == 0) { - /* Ugh, original sender didn't put rport! - * At best, can only send the response to the port in Via. - */ - res_addr.dst_host.addr.port = hvia->sent_by.port; + /* Ugh, original sender didn't put rport! + * At best, can only send the response to the port in Via. + */ + res_addr.dst_host.addr.port = hvia->sent_by.port; } /* Forward response */ status = pjsip_endpt_send_response(global.endpt, &res_addr, tdata, - NULL, NULL); + NULL, NULL); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - app_perror("Error forwarding response", status); - return PJ_TRUE; + pjsip_tx_data_dec_ref(tdata); + app_perror("Error forwarding response", status); + return PJ_TRUE; } return PJ_TRUE; @@ -184,59 +183,59 @@ int main(int argc, char *argv[]) status = init_options(argc, argv); if (status != PJ_SUCCESS) - return 1; + return 1; status = init_stack(); if (status != PJ_SUCCESS) { - app_perror("Error initializing stack", status); - return 1; + app_perror("Error initializing stack", status); + return 1; } status = init_proxy(); if (status != PJ_SUCCESS) { - app_perror("Error initializing proxy", status); - return 1; + app_perror("Error initializing proxy", status); + return 1; } status = init_stateless_proxy(); if (status != PJ_SUCCESS) { - app_perror("Error initializing stateless proxy", status); - return 1; + app_perror("Error initializing stateless proxy", status); + return 1; } #if PJ_HAS_THREADS status = pj_thread_create(global.pool, "sproxy", &worker_thread, - NULL, 0, 0, &global.thread); + NULL, 0, 0, &global.thread); if (status != PJ_SUCCESS) { - app_perror("Error creating thread", status); - return 1; + app_perror("Error creating thread", status); + return 1; } while (!global.quit_flag) { - char line[10]; - - puts("\n" - "Menu:\n" - " q quit\n" - " d dump status\n" - " dd dump detailed status\n" - ""); - - if (fgets(line, sizeof(line), stdin) == NULL) { - puts("EOF while reading stdin, will quit now.."); - global.quit_flag = PJ_TRUE; - break; - } - - if (line[0] == 'q') { - global.quit_flag = PJ_TRUE; - } else if (line[0] == 'd') { - pj_bool_t detail = (line[1] == 'd'); - pjsip_endpt_dump(global.endpt, detail); + char line[10]; + + puts("\n" + "Menu:\n" + " q quit\n" + " d dump status\n" + " dd dump detailed status\n" + ""); + + if (fgets(line, sizeof(line), stdin) == NULL) { + puts("EOF while reading stdin, will quit now.."); + global.quit_flag = PJ_TRUE; + break; + } + + if (line[0] == 'q') { + global.quit_flag = PJ_TRUE; + } else if (line[0] == 'd') { + pj_bool_t detail = (line[1] == 'd'); + pjsip_endpt_dump(global.endpt, detail); #if STATEFUL - pjsip_tsx_layer_dump(detail); + pjsip_tsx_layer_dump(detail); #endif - } + } } pj_thread_join(global.thread); @@ -244,8 +243,8 @@ int main(int argc, char *argv[]) #else puts("\nPress Ctrl-C to quit\n"); for (;;) { - pj_time_val delay = {0, 0}; - pjsip_endpt_handle_events(global.endpt, &delay); + pj_time_val delay = {0, 0}; + pjsip_endpt_handle_events(global.endpt, &delay); } #endif diff --git a/pjsip-apps/src/samples/stereotest.c b/pjsip-apps/src/samples/stereotest.c index d61c1d212d..d00de76049 100644 --- a/pjsip-apps/src/samples/stereotest.c +++ b/pjsip-apps/src/samples/stereotest.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -38,11 +37,11 @@ #include "util.h" -#define REC_CLOCK_RATE 16000 -#define PTIME 20 +#define REC_CLOCK_RATE 16000 +#define PTIME 20 -#define MODE_PLAY 1 -#define MODE_RECORD 2 +#define MODE_PLAY 1 +#define MODE_RECORD 2 /* For logging purpose. */ @@ -50,25 +49,25 @@ static const char *desc = -" FILE \n" -" \n" -" stereotest.c \n" -" \n" -" PURPOSE \n" -" \n" -" Demonstrate how use stereo port to play a WAV file to sound \n" +" FILE \n" +" \n" +" stereotest.c \n" +" \n" +" PURPOSE \n" +" \n" +" Demonstrate how use stereo port to play a WAV file to sound \n" " device or record to a WAV file from sound device with different \n" -" channel count. \n" -" \n" -" USAGE \n" -" \n" -" stereotest [options] WAV \n" -" \n" -" Options: \n" +" channel count. \n" +" \n" +" USAGE \n" +" \n" +" stereotest [options] WAV \n" +" \n" +" Options: \n" " -m, --mode=N Operation mode: 1 = playing, 2 = recording.\n" -" -C, --rec-ch-cnt=N Number of channel for recording file. \n" +" -C, --rec-ch-cnt=N Number of channel for recording file. \n" " -c, --snd-ch-cnt=N Number of channel for opening sound device.\n" -" \n"; +" \n"; int main(int argc, char *argv[]) { @@ -90,16 +89,16 @@ int main(int argc, char *argv[]) unsigned snd_ch_cnt = 2; enum { - OPT_MODE = 'm', - OPT_REC_CHANNEL = 'C', - OPT_SND_CHANNEL = 'c', + OPT_MODE = 'm', + OPT_REC_CHANNEL = 'C', + OPT_SND_CHANNEL = 'c', }; struct pj_getopt_option long_options[] = { - { "mode", 1, 0, OPT_MODE }, - { "rec-ch-cnt", 1, 0, OPT_REC_CHANNEL }, - { "snd-ch-cnt", 1, 0, OPT_SND_CHANNEL }, - { NULL, 0, 0, 0 }, + { "mode", 1, 0, OPT_MODE }, + { "rec-ch-cnt", 1, 0, OPT_REC_CHANNEL }, + { "snd-ch-cnt", 1, 0, OPT_SND_CHANNEL }, + { NULL, 0, 0, 0 }, }; int c; @@ -113,29 +112,29 @@ int main(int argc, char *argv[]) pj_optind = 0; while((c=pj_getopt_long(argc,argv, "m:C:c:", long_options, &option_index))!=-1) { - switch (c) { - case OPT_MODE: - if (mode) { - app_perror(THIS_FILE, "Cannot record and play at once!", - PJ_EINVAL); - return 1; - } - mode = atoi(pj_optarg); - break; - - case OPT_REC_CHANNEL: - rec_ch_cnt = atoi(pj_optarg); - break; - - case OPT_SND_CHANNEL: - snd_ch_cnt = atoi(pj_optarg); - break; - - default: - printf("Invalid options %s\n", argv[pj_optind]); - puts(desc); - return 1; - } + switch (c) { + case OPT_MODE: + if (mode) { + app_perror(THIS_FILE, "Cannot record and play at once!", + PJ_EINVAL); + return 1; + } + mode = atoi(pj_optarg); + break; + + case OPT_REC_CHANNEL: + rec_ch_cnt = atoi(pj_optarg); + break; + + case OPT_SND_CHANNEL: + snd_ch_cnt = atoi(pj_optarg); + break; + + default: + printf("Invalid options %s\n", argv[pj_optind]); + puts(desc); + return 1; + } } @@ -143,19 +142,19 @@ int main(int argc, char *argv[]) /* Verify arguments. */ if (!wav_file) { - app_perror(THIS_FILE, "WAV file not specified!", PJ_EINVAL); - puts(desc); - return 1; + app_perror(THIS_FILE, "WAV file not specified!", PJ_EINVAL); + puts(desc); + return 1; } if (!snd_ch_cnt || !rec_ch_cnt || rec_ch_cnt > 6) { - app_perror(THIS_FILE, "Invalid or too many channel count!", PJ_EINVAL); - puts(desc); - return 1; + app_perror(THIS_FILE, "Invalid or too many channel count!", PJ_EINVAL); + puts(desc); + return 1; } if (mode != MODE_RECORD && mode != MODE_PLAY) { - app_perror(THIS_FILE, "Invalid operation mode!", PJ_EINVAL); - puts(desc); - return 1; + app_perror(THIS_FILE, "Invalid operation mode!", PJ_EINVAL); + puts(desc); + return 1; } /* Must create a pool factory before we can allocate any memory. */ @@ -169,112 +168,112 @@ int main(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool for our file player */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "app", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "app", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); if (mode == MODE_PLAY) { - /* Create WAVE file player port. */ - status = pjmedia_wav_player_port_create( pool, wav_file, PTIME, 0, - 0, &file_port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to open file", status); - return 1; - } - - /* Create sound player port. */ - status = pjmedia_snd_port_create_player( - pool, /* pool */ - dev_id, /* device id. */ - PJMEDIA_PIA_SRATE(&file_port->info),/* clock rate. */ - snd_ch_cnt, /* # of channels. */ - snd_ch_cnt * PTIME * /* samples per frame. */ - PJMEDIA_PIA_SRATE(&file_port->info) / 1000, - PJMEDIA_PIA_BITS(&file_port->info),/* bits per sample. */ - 0, /* options */ - &snd_port /* returned port */ - ); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to open sound device", status); - return 1; - } - - if (snd_ch_cnt != PJMEDIA_PIA_CCNT(&file_port->info)) { - status = pjmedia_stereo_port_create( pool, - file_port, - snd_ch_cnt, - 0, - &stereo_port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create stereo port", status); - return 1; - } - - status = pjmedia_snd_port_connect(snd_port, stereo_port); - } else { - status = pjmedia_snd_port_connect(snd_port, file_port); - } - - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to connect sound port", status); - return 1; - } + /* Create WAVE file player port. */ + status = pjmedia_wav_player_port_create( pool, wav_file, PTIME, 0, + 0, &file_port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to open file", status); + return 1; + } + + /* Create sound player port. */ + status = pjmedia_snd_port_create_player( + pool, /* pool */ + dev_id, /* device id. */ + PJMEDIA_PIA_SRATE(&file_port->info),/* clock rate. */ + snd_ch_cnt, /* # of channels. */ + snd_ch_cnt * PTIME * /* samples per frame. */ + PJMEDIA_PIA_SRATE(&file_port->info) / 1000, + PJMEDIA_PIA_BITS(&file_port->info),/* bits per sample. */ + 0, /* options */ + &snd_port /* returned port */ + ); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to open sound device", status); + return 1; + } + + if (snd_ch_cnt != PJMEDIA_PIA_CCNT(&file_port->info)) { + status = pjmedia_stereo_port_create( pool, + file_port, + snd_ch_cnt, + 0, + &stereo_port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to create stereo port", status); + return 1; + } + + status = pjmedia_snd_port_connect(snd_port, stereo_port); + } else { + status = pjmedia_snd_port_connect(snd_port, file_port); + } + + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to connect sound port", status); + return 1; + } } else { - /* Create WAVE file writer port. */ - status = pjmedia_wav_writer_port_create(pool, wav_file, - REC_CLOCK_RATE, - rec_ch_cnt, - rec_ch_cnt * PTIME * - REC_CLOCK_RATE / 1000, - NBITS, - 0, 0, - &file_port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to open file", status); - return 1; - } - - /* Create sound player port. */ - status = pjmedia_snd_port_create_rec( - pool, /* pool */ - dev_id, /* device id. */ - REC_CLOCK_RATE, /* clock rate. */ - snd_ch_cnt, /* # of channels. */ - snd_ch_cnt * PTIME * - REC_CLOCK_RATE / 1000, /* samples per frame. */ - NBITS, /* bits per sample. */ - 0, /* options */ - &snd_port /* returned port */ - ); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to open sound device", status); - return 1; - } - - if (rec_ch_cnt != snd_ch_cnt) { - status = pjmedia_stereo_port_create( pool, - file_port, - snd_ch_cnt, - 0, - &stereo_port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create stereo port", status); - return 1; - } - - status = pjmedia_snd_port_connect(snd_port, stereo_port); - } else { - status = pjmedia_snd_port_connect(snd_port, file_port); - } - - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to connect sound port", status); - return 1; - } + /* Create WAVE file writer port. */ + status = pjmedia_wav_writer_port_create(pool, wav_file, + REC_CLOCK_RATE, + rec_ch_cnt, + rec_ch_cnt * PTIME * + REC_CLOCK_RATE / 1000, + NBITS, + 0, 0, + &file_port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to open file", status); + return 1; + } + + /* Create sound player port. */ + status = pjmedia_snd_port_create_rec( + pool, /* pool */ + dev_id, /* device id. */ + REC_CLOCK_RATE, /* clock rate. */ + snd_ch_cnt, /* # of channels. */ + snd_ch_cnt * PTIME * + REC_CLOCK_RATE / 1000, /* samples per frame. */ + NBITS, /* bits per sample. */ + 0, /* options */ + &snd_port /* returned port */ + ); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to open sound device", status); + return 1; + } + + if (rec_ch_cnt != snd_ch_cnt) { + status = pjmedia_stereo_port_create( pool, + file_port, + snd_ch_cnt, + 0, + &stereo_port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to create stereo port", status); + return 1; + } + + status = pjmedia_snd_port_connect(snd_port, stereo_port); + } else { + status = pjmedia_snd_port_connect(snd_port, file_port); + } + + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to connect sound port", status); + return 1; + } } /* Dump memory usage */ @@ -291,12 +290,12 @@ int main(int argc, char *argv[]) printf("Mode = %s\n", (mode == MODE_PLAY? "playing" : "recording") ); printf("File port channel count = %d\n", PJMEDIA_PIA_CCNT(&file_port->info)); printf("Sound port channel count = %d\n", - PJMEDIA_PIA_CCNT(&pjmedia_snd_port_get_port(snd_port)->info)); + PJMEDIA_PIA_CCNT(&pjmedia_snd_port_get_port(snd_port)->info)); puts(""); puts("Press to stop and quit"); if (fgets(tmp, sizeof(tmp), stdin) == NULL) { - puts("EOF while reading stdin, will quit now.."); + puts("EOF while reading stdin, will quit now.."); } /* Start deinitialization: */ diff --git a/pjsip-apps/src/samples/streamutil.c b/pjsip-apps/src/samples/streamutil.c index 3bba4aba8e..eabb28b15e 100644 --- a/pjsip-apps/src/samples/streamutil.c +++ b/pjsip-apps/src/samples/streamutil.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,7 +35,7 @@ #include #include -#include /* atoi() */ +#include /* atoi() */ #include #include "util.h" @@ -48,38 +47,38 @@ #define HAVE_MULTICAST 1 static const char *desc = - " streamutil \n" - " \n" - " PURPOSE: \n" + " streamutil \n" + " \n" + " PURPOSE: \n" " Demonstrate how to use pjmedia stream component to transmit/receive \n" - " RTP packets to/from sound device. \n" + " RTP packets to/from sound device. \n" "\n" "\n" - " USAGE: \n" + " USAGE: \n" " streamutil [options] \n" "\n" "\n" " Options:\n" " --codec=CODEC Set the codec name. \n" - " --local-port=PORT Set local RTP port (default=4000) \n" - " --remote=IP:PORT Set the remote peer. If this option is set, \n" - " the program will transmit RTP audio to the \n" - " specified address. (default: recv only) \n" + " --local-port=PORT Set local RTP port (default=4000) \n" + " --remote=IP:PORT Set the remote peer. If this option is set, \n" + " the program will transmit RTP audio to the \n" + " specified address. (default: recv only) \n" #if HAVE_MULTICAST - " --mcast-add=IP Joins the multicast group as specified by \n" - " the address. Sample usage: \n" - " Sender: \n" - " streamutil --remote=[multicast_addr]:[port] \n" - " Receivers: \n" - " streamutil --local-port=[port] \n" - " --mcast-add=[multicast_addr] \n" + " --mcast-add=IP Joins the multicast group as specified by \n" + " the address. Sample usage: \n" + " Sender: \n" + " streamutil --remote=[multicast_addr]:[port] \n" + " Receivers: \n" + " streamutil --local-port=[port] \n" + " --mcast-add=[multicast_addr] \n" #endif - " --play-file=WAV Send audio from the WAV file instead of from \n" - " the sound device. \n" - " --record-file=WAV Record incoming audio to WAV file instead of \n" - " playing it to sound device. \n" + " --play-file=WAV Send audio from the WAV file instead of from \n" + " the sound device. \n" + " --record-file=WAV Record incoming audio to WAV file instead of \n" + " playing it to sound device. \n" " --send-recv Set stream direction to bidirectional. \n" - " --send-only Set stream direction to send only \n" + " --send-only Set stream direction to send only \n" " --recv-only Set stream direction to recv only (default) \n" #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) @@ -100,25 +99,25 @@ static const char *desc = -#define THIS_FILE "stream.c" +#define THIS_FILE "stream.c" /* Prototype */ static void print_stream_stat(pjmedia_stream *stream, - const pjmedia_codec_param *codec_param); + const pjmedia_codec_param *codec_param); /* Hexa string to octet array */ int my_hex_string_to_octet_string(char *raw, char *hex, int len) { int i; for (i = 0; i < len; i+=2) { - int tmp; - if (i+1 >= len || !pj_isxdigit(hex[i]) || !pj_isxdigit(hex[i+1])) - return i; - tmp = pj_hex_digit_to_val((unsigned char)hex[i]) << 4; - tmp |= pj_hex_digit_to_val((unsigned char)hex[i+1]); - raw[i/2] = (char)(tmp & 0xFF); + int tmp; + if (i+1 >= len || !pj_isxdigit(hex[i]) || !pj_isxdigit(hex[i+1])) + return i; + tmp = pj_hex_digit_to_val((unsigned char)hex[i]) << 4; + tmp |= pj_hex_digit_to_val((unsigned char)hex[i+1]); + raw[i/2] = (char)(tmp & 0xFF); } return len; } @@ -136,22 +135,22 @@ static pj_status_t init_codecs(pjmedia_endpt *med_endpt) * Create stream based on the codec, dir, remote address, etc. */ static pj_status_t create_stream( pj_pool_t *pool, - pjmedia_endpt *med_endpt, - const pjmedia_codec_info *codec_info, - pjmedia_dir dir, - pj_uint16_t local_port, - const pj_sockaddr_in *rem_addr, - pj_bool_t mcast, - const pj_sockaddr_in *mcast_addr, + pjmedia_endpt *med_endpt, + const pjmedia_codec_info *codec_info, + pjmedia_dir dir, + pj_uint16_t local_port, + const pj_sockaddr_in *rem_addr, + pj_bool_t mcast, + const pj_sockaddr_in *mcast_addr, #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - pj_bool_t use_srtp, - const pj_str_t *crypto_suite, - const pj_str_t *srtp_tx_key, - const pj_str_t *srtp_rx_key, - pj_bool_t is_dtls_client, - pj_bool_t is_dtls_server, + pj_bool_t use_srtp, + const pj_str_t *crypto_suite, + const pj_str_t *srtp_tx_key, + const pj_str_t *srtp_rx_key, + pj_bool_t is_dtls_client, + pj_bool_t is_dtls_server, #endif - pjmedia_stream **p_stream ) + pjmedia_stream **p_stream ) { pjmedia_stream_info info; pjmedia_transport *transport = NULL; @@ -185,149 +184,149 @@ static pj_status_t create_stream( pj_pool_t *pool, * (otherwise stream will assert). */ if (info.rem_addr.addr.sa_family == 0) { - const pj_str_t addr = pj_str("127.0.0.1"); - pj_sockaddr_in_init(&info.rem_addr.ipv4, &addr, 0); + const pj_str_t addr = pj_str("127.0.0.1"); + pj_sockaddr_in_init(&info.rem_addr.ipv4, &addr, 0); } pj_sockaddr_cp(&info.rem_rtcp, &info.rem_addr); pj_sockaddr_set_port(&info.rem_rtcp, - pj_sockaddr_get_port(&info.rem_rtcp)+1); + pj_sockaddr_get_port(&info.rem_rtcp)+1); if (mcast) { - pjmedia_sock_info si; - int reuse = 1; - - pj_bzero(&si, sizeof(pjmedia_sock_info)); - si.rtp_sock = si.rtcp_sock = PJ_INVALID_SOCKET; - - /* Create RTP socket */ - status = pj_sock_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, - &si.rtp_sock); - if (status != PJ_SUCCESS) - return status; - - status = pj_sock_setsockopt(si.rtp_sock, pj_SOL_SOCKET(), - pj_SO_REUSEADDR(), &reuse, sizeof(reuse)); - if (status != PJ_SUCCESS) - return status; - - /* Bind RTP socket */ - status = pj_sockaddr_init(pj_AF_INET(), &si.rtp_addr_name, - NULL, local_port); - if (status != PJ_SUCCESS) - return status; + pjmedia_sock_info si; + int reuse = 1; + + pj_bzero(&si, sizeof(pjmedia_sock_info)); + si.rtp_sock = si.rtcp_sock = PJ_INVALID_SOCKET; + + /* Create RTP socket */ + status = pj_sock_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, + &si.rtp_sock); + if (status != PJ_SUCCESS) + return status; + + status = pj_sock_setsockopt(si.rtp_sock, pj_SOL_SOCKET(), + pj_SO_REUSEADDR(), &reuse, sizeof(reuse)); + if (status != PJ_SUCCESS) + return status; + + /* Bind RTP socket */ + status = pj_sockaddr_init(pj_AF_INET(), &si.rtp_addr_name, + NULL, local_port); + if (status != PJ_SUCCESS) + return status; status = pj_sock_bind(si.rtp_sock, &si.rtp_addr_name, - pj_sockaddr_get_len(&si.rtp_addr_name)); - if (status != PJ_SUCCESS) - return status; - - /* Create RTCP socket */ - status = pj_sock_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, - &si.rtcp_sock); - if (status != PJ_SUCCESS) - return status; - - status = pj_sock_setsockopt(si.rtcp_sock, pj_SOL_SOCKET(), - pj_SO_REUSEADDR(), &reuse, sizeof(reuse)); - if (status != PJ_SUCCESS) - return status; - - /* Bind RTCP socket */ - status = pj_sockaddr_init(pj_AF_INET(), &si.rtcp_addr_name, - NULL, local_port+1); - if (status != PJ_SUCCESS) - return status; + pj_sockaddr_get_len(&si.rtp_addr_name)); + if (status != PJ_SUCCESS) + return status; + + /* Create RTCP socket */ + status = pj_sock_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, + &si.rtcp_sock); + if (status != PJ_SUCCESS) + return status; + + status = pj_sock_setsockopt(si.rtcp_sock, pj_SOL_SOCKET(), + pj_SO_REUSEADDR(), &reuse, sizeof(reuse)); + if (status != PJ_SUCCESS) + return status; + + /* Bind RTCP socket */ + status = pj_sockaddr_init(pj_AF_INET(), &si.rtcp_addr_name, + NULL, local_port+1); + if (status != PJ_SUCCESS) + return status; - status = pj_sock_bind(si.rtcp_sock, &si.rtcp_addr_name, + status = pj_sock_bind(si.rtcp_sock, &si.rtcp_addr_name, pj_sockaddr_get_len(&si.rtcp_addr_name)); - if (status != PJ_SUCCESS) - return status; + if (status != PJ_SUCCESS) + return status; #ifdef HAVE_MULTICAST - { - unsigned char loop; - struct pj_ip_mreq imr; - - pj_memset(&imr, 0, sizeof(struct pj_ip_mreq)); - imr.imr_multiaddr.s_addr = mcast_addr->sin_addr.s_addr; - imr.imr_interface.s_addr = pj_htonl(PJ_INADDR_ANY); - status = pj_sock_setsockopt(si.rtp_sock, pj_SOL_IP(), - pj_IP_ADD_MEMBERSHIP(), - &imr, sizeof(struct pj_ip_mreq)); - if (status != PJ_SUCCESS) - return status; - - status = pj_sock_setsockopt(si.rtcp_sock, pj_SOL_IP(), - pj_IP_ADD_MEMBERSHIP(), - &imr, sizeof(struct pj_ip_mreq)); - if (status != PJ_SUCCESS) - return status; - - /* Disable local reception of local sent packets */ - loop = 0; - pj_sock_setsockopt(si.rtp_sock, pj_SOL_IP(), - pj_IP_MULTICAST_LOOP(), &loop, sizeof(loop)); - pj_sock_setsockopt(si.rtcp_sock, pj_SOL_IP(), - pj_IP_MULTICAST_LOOP(), &loop, sizeof(loop)); - } + { + unsigned char loop; + struct pj_ip_mreq imr; + + pj_memset(&imr, 0, sizeof(struct pj_ip_mreq)); + imr.imr_multiaddr.s_addr = mcast_addr->sin_addr.s_addr; + imr.imr_interface.s_addr = pj_htonl(PJ_INADDR_ANY); + status = pj_sock_setsockopt(si.rtp_sock, pj_SOL_IP(), + pj_IP_ADD_MEMBERSHIP(), + &imr, sizeof(struct pj_ip_mreq)); + if (status != PJ_SUCCESS) + return status; + + status = pj_sock_setsockopt(si.rtcp_sock, pj_SOL_IP(), + pj_IP_ADD_MEMBERSHIP(), + &imr, sizeof(struct pj_ip_mreq)); + if (status != PJ_SUCCESS) + return status; + + /* Disable local reception of local sent packets */ + loop = 0; + pj_sock_setsockopt(si.rtp_sock, pj_SOL_IP(), + pj_IP_MULTICAST_LOOP(), &loop, sizeof(loop)); + pj_sock_setsockopt(si.rtcp_sock, pj_SOL_IP(), + pj_IP_MULTICAST_LOOP(), &loop, sizeof(loop)); + } #endif - - /* Create media transport from existing sockets */ - status = pjmedia_transport_udp_attach( med_endpt, NULL, &si, - PJMEDIA_UDP_NO_SRC_ADDR_CHECKING, &transport); - if (status != PJ_SUCCESS) - return status; - + + /* Create media transport from existing sockets */ + status = pjmedia_transport_udp_attach( med_endpt, NULL, &si, + PJMEDIA_UDP_NO_SRC_ADDR_CHECKING, &transport); + if (status != PJ_SUCCESS) + return status; + } else { /* Create media transport */ status = pjmedia_transport_udp_create(med_endpt, NULL, local_port, - 0, &transport); + 0, &transport); if (status != PJ_SUCCESS) - return status; + return status; } #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) /* Check if SRTP enabled */ if (use_srtp) { - status = pjmedia_transport_srtp_create(med_endpt, transport, - NULL, &srtp_tp); - if (status != PJ_SUCCESS) - return status; - - if (is_dtls_client || is_dtls_server) { - char fp[128]; - pj_size_t fp_len = sizeof(fp); - pjmedia_srtp_dtls_nego_param dtls_param; - - pjmedia_transport_srtp_dtls_get_fingerprint(srtp_tp, "SHA-256", fp, &fp_len); - PJ_LOG(3, (THIS_FILE, "Local cert fingerprint: %s", fp)); - - pj_bzero(&dtls_param, sizeof(dtls_param)); - pj_sockaddr_cp(&dtls_param.rem_addr, rem_addr); - pj_sockaddr_cp(&dtls_param.rem_rtcp, rem_addr); - dtls_param.is_role_active = is_dtls_client; - - status = pjmedia_transport_srtp_dtls_start_nego(srtp_tp, &dtls_param); - if (status != PJ_SUCCESS) - return status; - } else { - pjmedia_srtp_crypto tx_plc, rx_plc; - - pj_bzero(&tx_plc, sizeof(pjmedia_srtp_crypto)); - pj_bzero(&rx_plc, sizeof(pjmedia_srtp_crypto)); - - tx_plc.key = *srtp_tx_key; - tx_plc.name = *crypto_suite; - rx_plc.key = *srtp_rx_key; - rx_plc.name = *crypto_suite; - - status = pjmedia_transport_srtp_start(srtp_tp, &tx_plc, &rx_plc); - if (status != PJ_SUCCESS) - return status; - } - - transport = srtp_tp; + status = pjmedia_transport_srtp_create(med_endpt, transport, + NULL, &srtp_tp); + if (status != PJ_SUCCESS) + return status; + + if (is_dtls_client || is_dtls_server) { + char fp[128]; + pj_size_t fp_len = sizeof(fp); + pjmedia_srtp_dtls_nego_param dtls_param; + + pjmedia_transport_srtp_dtls_get_fingerprint(srtp_tp, "SHA-256", fp, &fp_len); + PJ_LOG(3, (THIS_FILE, "Local cert fingerprint: %s", fp)); + + pj_bzero(&dtls_param, sizeof(dtls_param)); + pj_sockaddr_cp(&dtls_param.rem_addr, rem_addr); + pj_sockaddr_cp(&dtls_param.rem_rtcp, rem_addr); + dtls_param.is_role_active = is_dtls_client; + + status = pjmedia_transport_srtp_dtls_start_nego(srtp_tp, &dtls_param); + if (status != PJ_SUCCESS) + return status; + } else { + pjmedia_srtp_crypto tx_plc, rx_plc; + + pj_bzero(&tx_plc, sizeof(pjmedia_srtp_crypto)); + pj_bzero(&rx_plc, sizeof(pjmedia_srtp_crypto)); + + tx_plc.key = *srtp_tx_key; + tx_plc.name = *crypto_suite; + rx_plc.key = *srtp_rx_key; + rx_plc.name = *crypto_suite; + + status = pjmedia_transport_srtp_start(srtp_tp, &tx_plc, &rx_plc); + if (status != PJ_SUCCESS) + return status; + } + + transport = srtp_tp; } #endif @@ -336,13 +335,13 @@ static pj_status_t create_stream( pj_pool_t *pool, */ status = pjmedia_stream_create( med_endpt, pool, &info, - transport, - NULL, p_stream); + transport, + NULL, p_stream); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error creating stream", status); - pjmedia_transport_close(transport); - return status; + app_perror(THIS_FILE, "Error creating stream", status); + pjmedia_transport_close(transport); + return status; } /* Start media transport */ @@ -388,7 +387,7 @@ int main(int argc, char *argv[]) pj_str_t srtp_crypto_suite = {NULL, 0}; pj_bool_t is_dtls_client = PJ_FALSE; pj_bool_t is_dtls_server = PJ_FALSE; - int tmp_key_len; + int tmp_key_len; #endif /* Default values */ @@ -404,44 +403,44 @@ int main(int argc, char *argv[]) int mcast = 0; enum { - OPT_CODEC = 'c', - OPT_LOCAL_PORT = 'p', - OPT_REMOTE = 'r', - OPT_MCAST = 'm', - OPT_PLAY_FILE = 'w', - OPT_RECORD_FILE = 'R', - OPT_SEND_RECV = 'b', - OPT_SEND_ONLY = 's', - OPT_RECV_ONLY = 'i', + OPT_CODEC = 'c', + OPT_LOCAL_PORT = 'p', + OPT_REMOTE = 'r', + OPT_MCAST = 'm', + OPT_PLAY_FILE = 'w', + OPT_RECORD_FILE = 'R', + OPT_SEND_RECV = 'b', + OPT_SEND_ONLY = 's', + OPT_RECV_ONLY = 'i', #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - OPT_USE_SRTP = 'S', + OPT_USE_SRTP = 'S', #endif - OPT_SRTP_TX_KEY = 'x', - OPT_SRTP_RX_KEY = 'y', - OPT_SRTP_DTLS_CLIENT = 'd', - OPT_SRTP_DTLS_SERVER = 'D', - OPT_HELP = 'h', + OPT_SRTP_TX_KEY = 'x', + OPT_SRTP_RX_KEY = 'y', + OPT_SRTP_DTLS_CLIENT = 'd', + OPT_SRTP_DTLS_SERVER = 'D', + OPT_HELP = 'h', }; struct pj_getopt_option long_options[] = { - { "codec", 1, 0, OPT_CODEC }, - { "local-port", 1, 0, OPT_LOCAL_PORT }, - { "remote", 1, 0, OPT_REMOTE }, - { "mcast-add", 1, 0, OPT_MCAST }, - { "play-file", 1, 0, OPT_PLAY_FILE }, - { "record-file", 1, 0, OPT_RECORD_FILE }, - { "send-recv", 0, 0, OPT_SEND_RECV }, - { "send-only", 0, 0, OPT_SEND_ONLY }, - { "recv-only", 0, 0, OPT_RECV_ONLY }, + { "codec", 1, 0, OPT_CODEC }, + { "local-port", 1, 0, OPT_LOCAL_PORT }, + { "remote", 1, 0, OPT_REMOTE }, + { "mcast-add", 1, 0, OPT_MCAST }, + { "play-file", 1, 0, OPT_PLAY_FILE }, + { "record-file", 1, 0, OPT_RECORD_FILE }, + { "send-recv", 0, 0, OPT_SEND_RECV }, + { "send-only", 0, 0, OPT_SEND_ONLY }, + { "recv-only", 0, 0, OPT_RECV_ONLY }, #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - { "use-srtp", 2, 0, OPT_USE_SRTP }, - { "srtp-tx-key", 1, 0, OPT_SRTP_TX_KEY }, - { "srtp-rx-key", 1, 0, OPT_SRTP_RX_KEY }, - { "srtp-dtls-client", 0, 0, OPT_SRTP_DTLS_CLIENT }, - { "srtp-dtls-server", 0, 0, OPT_SRTP_DTLS_SERVER }, + { "use-srtp", 2, 0, OPT_USE_SRTP }, + { "srtp-tx-key", 1, 0, OPT_SRTP_TX_KEY }, + { "srtp-rx-key", 1, 0, OPT_SRTP_RX_KEY }, + { "srtp-dtls-client", 0, 0, OPT_SRTP_DTLS_CLIENT }, + { "srtp-dtls-server", 0, 0, OPT_SRTP_DTLS_SERVER }, #endif - { "help", 0, 0, OPT_HELP }, - { NULL, 0, 0, 0 }, + { "help", 0, 0, OPT_HELP }, + { NULL, 0, 0, 0 }, }; int c; @@ -460,110 +459,110 @@ int main(int argc, char *argv[]) pj_optind = 0; while((c=pj_getopt_long(argc,argv, "h", long_options, &option_index))!=-1) { - switch (c) { - case OPT_CODEC: - codec_id = pj_optarg; - break; - - case OPT_LOCAL_PORT: - local_port = (pj_uint16_t) atoi(pj_optarg); - if (local_port < 1) { - printf("Error: invalid local port %s\n", pj_optarg); - return 1; - } - break; - - case OPT_REMOTE: - { - pj_str_t ip = pj_str(strtok(pj_optarg, ":")); - pj_uint16_t port = (pj_uint16_t) atoi(strtok(NULL, ":")); - - status = pj_sockaddr_in_init(&remote_addr, &ip, port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Invalid remote address", status); - return 1; - } - } - break; - - case OPT_MCAST: - { - pj_str_t ip = pj_str(pj_optarg); - - mcast = 1; - status = pj_sockaddr_in_init(&mcast_addr, &ip, 0); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Invalid mcast address", status); - return 1; - } - } - break; - - case OPT_PLAY_FILE: - play_file = pj_optarg; - break; - - case OPT_RECORD_FILE: - rec_file = pj_optarg; - break; - - case OPT_SEND_RECV: - dir = PJMEDIA_DIR_ENCODING_DECODING; - break; - - case OPT_SEND_ONLY: - dir = PJMEDIA_DIR_ENCODING; - break; - - case OPT_RECV_ONLY: - dir = PJMEDIA_DIR_DECODING; - break; + switch (c) { + case OPT_CODEC: + codec_id = pj_optarg; + break; + + case OPT_LOCAL_PORT: + local_port = (pj_uint16_t) atoi(pj_optarg); + if (local_port < 1) { + printf("Error: invalid local port %s\n", pj_optarg); + return 1; + } + break; + + case OPT_REMOTE: + { + pj_str_t ip = pj_str(strtok(pj_optarg, ":")); + pj_uint16_t port = (pj_uint16_t) atoi(strtok(NULL, ":")); + + status = pj_sockaddr_in_init(&remote_addr, &ip, port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Invalid remote address", status); + return 1; + } + } + break; + + case OPT_MCAST: + { + pj_str_t ip = pj_str(pj_optarg); + + mcast = 1; + status = pj_sockaddr_in_init(&mcast_addr, &ip, 0); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Invalid mcast address", status); + return 1; + } + } + break; + + case OPT_PLAY_FILE: + play_file = pj_optarg; + break; + + case OPT_RECORD_FILE: + rec_file = pj_optarg; + break; + + case OPT_SEND_RECV: + dir = PJMEDIA_DIR_ENCODING_DECODING; + break; + + case OPT_SEND_ONLY: + dir = PJMEDIA_DIR_ENCODING; + break; + + case OPT_RECV_ONLY: + dir = PJMEDIA_DIR_DECODING; + break; #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - case OPT_USE_SRTP: - use_srtp = PJ_TRUE; - if (pj_optarg) { - pj_strset(&srtp_crypto_suite, pj_optarg, strlen(pj_optarg)); - } else { - srtp_crypto_suite = pj_str("AES_CM_128_HMAC_SHA1_80"); - } - break; - - case OPT_SRTP_TX_KEY: - tmp_key_len = my_hex_string_to_octet_string(tmp_tx_key, pj_optarg, - (int)strlen(pj_optarg)); - pj_strset(&srtp_tx_key, tmp_tx_key, tmp_key_len/2); - break; - - case OPT_SRTP_RX_KEY: - tmp_key_len = my_hex_string_to_octet_string(tmp_rx_key, pj_optarg, - (int)strlen(pj_optarg)); - pj_strset(&srtp_rx_key, tmp_rx_key, tmp_key_len/2); - break; - case OPT_SRTP_DTLS_CLIENT: - is_dtls_client = PJ_TRUE; - if (is_dtls_server) { - printf("Error: Cannot be as both DTLS server & client\n"); - return 1; - } - break; - case OPT_SRTP_DTLS_SERVER: - is_dtls_server = PJ_TRUE; - if (is_dtls_client) { - printf("Error: Cannot be as both DTLS server & client\n"); - return 1; - } - break; + case OPT_USE_SRTP: + use_srtp = PJ_TRUE; + if (pj_optarg) { + pj_strset(&srtp_crypto_suite, pj_optarg, strlen(pj_optarg)); + } else { + srtp_crypto_suite = pj_str("AES_CM_128_HMAC_SHA1_80"); + } + break; + + case OPT_SRTP_TX_KEY: + tmp_key_len = my_hex_string_to_octet_string(tmp_tx_key, pj_optarg, + (int)strlen(pj_optarg)); + pj_strset(&srtp_tx_key, tmp_tx_key, tmp_key_len/2); + break; + + case OPT_SRTP_RX_KEY: + tmp_key_len = my_hex_string_to_octet_string(tmp_rx_key, pj_optarg, + (int)strlen(pj_optarg)); + pj_strset(&srtp_rx_key, tmp_rx_key, tmp_key_len/2); + break; + case OPT_SRTP_DTLS_CLIENT: + is_dtls_client = PJ_TRUE; + if (is_dtls_server) { + printf("Error: Cannot be as both DTLS server & client\n"); + return 1; + } + break; + case OPT_SRTP_DTLS_SERVER: + is_dtls_server = PJ_TRUE; + if (is_dtls_client) { + printf("Error: Cannot be as both DTLS server & client\n"); + return 1; + } + break; #endif - case OPT_HELP: - usage(); - return 1; + case OPT_HELP: + usage(); + return 1; - default: - printf("Invalid options %s\n", argv[pj_optind]); - return 1; - } + default: + printf("Invalid options %s\n", argv[pj_optind]); + return 1; + } } @@ -574,26 +573,26 @@ int main(int argc, char *argv[]) || is_dtls_client || is_dtls_server #endif ) { - if (remote_addr.sin_addr.s_addr == 0) { - printf("Error: remote address must be set\n"); - return 1; - } + if (remote_addr.sin_addr.s_addr == 0) { + printf("Error: remote address must be set\n"); + return 1; + } } if (play_file != NULL && dir != PJMEDIA_DIR_ENCODING) { - printf("Direction is set to --send-only because of --play-file\n"); - dir = PJMEDIA_DIR_ENCODING; + printf("Direction is set to --send-only because of --play-file\n"); + dir = PJMEDIA_DIR_ENCODING; } #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) /* SRTP validation */ if (use_srtp) { - if (!is_dtls_client && !is_dtls_server && - (!srtp_tx_key.slen || !srtp_rx_key.slen)) - { - printf("Error: Key for each SRTP stream direction must be set\n"); - return 1; - } + if (!is_dtls_client && !is_dtls_server && + (!srtp_tx_key.slen || !srtp_rx_key.slen)) + { + printf("Error: Key for each SRTP stream direction must be set\n"); + return 1; + } } #endif @@ -608,12 +607,12 @@ int main(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool for application purpose */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "app", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "app", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); /* Register all supported codecs */ @@ -623,44 +622,44 @@ int main(int argc, char *argv[]) /* Find which codec to use. */ if (codec_id) { - unsigned count = 1; - pj_str_t str_codec_id = pj_str(codec_id); - pjmedia_codec_mgr *codec_mgr = pjmedia_endpt_get_codec_mgr(med_endpt); - status = pjmedia_codec_mgr_find_codecs_by_id( codec_mgr, - &str_codec_id, &count, - &codec_info, NULL); - if (status != PJ_SUCCESS) { - printf("Error: unable to find codec %s\n", codec_id); - return 1; - } + unsigned count = 1; + pj_str_t str_codec_id = pj_str(codec_id); + pjmedia_codec_mgr *codec_mgr = pjmedia_endpt_get_codec_mgr(med_endpt); + status = pjmedia_codec_mgr_find_codecs_by_id( codec_mgr, + &str_codec_id, &count, + &codec_info, NULL); + if (status != PJ_SUCCESS) { + printf("Error: unable to find codec %s\n", codec_id); + return 1; + } } else { - /* Default to pcmu */ - pjmedia_codec_mgr_get_codec_info( pjmedia_endpt_get_codec_mgr(med_endpt), - 0, &codec_info); + /* Default to pcmu */ + pjmedia_codec_mgr_get_codec_info( pjmedia_endpt_get_codec_mgr(med_endpt), + 0, &codec_info); } /* Create event manager */ status = pjmedia_event_mgr_create(pool, 0, NULL); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; /* Create stream based on program arguments */ status = create_stream(pool, med_endpt, codec_info, dir, local_port, - &remote_addr, mcast, &mcast_addr, + &remote_addr, mcast, &mcast_addr, #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - use_srtp, &srtp_crypto_suite, - &srtp_tx_key, &srtp_rx_key, - is_dtls_client, is_dtls_server, + use_srtp, &srtp_crypto_suite, + &srtp_tx_key, &srtp_rx_key, + is_dtls_client, is_dtls_server, #endif - &stream); + &stream); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; /* Get codec default param for info */ status = pjmedia_codec_mgr_get_default_param( - pjmedia_endpt_get_codec_mgr(med_endpt), - codec_info, - &codec_param); + pjmedia_endpt_get_codec_mgr(med_endpt), + codec_info, + &codec_param); /* Should be ok, as create_stream() above succeeded */ pj_assert(status == PJ_SUCCESS); @@ -670,93 +669,93 @@ int main(int argc, char *argv[]) if (play_file) { - unsigned wav_ptime; - - wav_ptime = PJMEDIA_PIA_PTIME(&stream_port->info); - status = pjmedia_wav_player_port_create(pool, play_file, wav_ptime, - 0, -1, &play_file_port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to use file", status); - goto on_exit; - } - - status = pjmedia_master_port_create(pool, play_file_port, stream_port, - 0, &master_port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create master port", status); - goto on_exit; - } - - status = pjmedia_master_port_start(master_port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error starting master port", status); - goto on_exit; - } - - printf("Playing from WAV file %s..\n", play_file); + unsigned wav_ptime; + + wav_ptime = PJMEDIA_PIA_PTIME(&stream_port->info); + status = pjmedia_wav_player_port_create(pool, play_file, wav_ptime, + 0, -1, &play_file_port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to use file", status); + goto on_exit; + } + + status = pjmedia_master_port_create(pool, play_file_port, stream_port, + 0, &master_port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to create master port", status); + goto on_exit; + } + + status = pjmedia_master_port_start(master_port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Error starting master port", status); + goto on_exit; + } + + printf("Playing from WAV file %s..\n", play_file); } else if (rec_file) { - status = pjmedia_wav_writer_port_create(pool, rec_file, - PJMEDIA_PIA_SRATE(&stream_port->info), - PJMEDIA_PIA_CCNT(&stream_port->info), - PJMEDIA_PIA_SPF(&stream_port->info), - PJMEDIA_PIA_BITS(&stream_port->info), - 0, 0, &rec_file_port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to use file", status); - goto on_exit; - } - - status = pjmedia_master_port_create(pool, stream_port, rec_file_port, - 0, &master_port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create master port", status); - goto on_exit; - } - - status = pjmedia_master_port_start(master_port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error starting master port", status); - goto on_exit; - } - - printf("Recording to WAV file %s..\n", rec_file); - + status = pjmedia_wav_writer_port_create(pool, rec_file, + PJMEDIA_PIA_SRATE(&stream_port->info), + PJMEDIA_PIA_CCNT(&stream_port->info), + PJMEDIA_PIA_SPF(&stream_port->info), + PJMEDIA_PIA_BITS(&stream_port->info), + 0, 0, &rec_file_port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to use file", status); + goto on_exit; + } + + status = pjmedia_master_port_create(pool, stream_port, rec_file_port, + 0, &master_port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to create master port", status); + goto on_exit; + } + + status = pjmedia_master_port_start(master_port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Error starting master port", status); + goto on_exit; + } + + printf("Recording to WAV file %s..\n", rec_file); + } else { - /* Create sound device port. */ - if (dir == PJMEDIA_DIR_ENCODING_DECODING) - status = pjmedia_snd_port_create(pool, -1, -1, - PJMEDIA_PIA_SRATE(&stream_port->info), - PJMEDIA_PIA_CCNT(&stream_port->info), - PJMEDIA_PIA_SPF(&stream_port->info), - PJMEDIA_PIA_BITS(&stream_port->info), - 0, &snd_port); - else if (dir == PJMEDIA_DIR_ENCODING) - status = pjmedia_snd_port_create_rec(pool, -1, - PJMEDIA_PIA_SRATE(&stream_port->info), - PJMEDIA_PIA_CCNT(&stream_port->info), - PJMEDIA_PIA_SPF(&stream_port->info), - PJMEDIA_PIA_BITS(&stream_port->info), - 0, &snd_port); - else - status = pjmedia_snd_port_create_player(pool, -1, - PJMEDIA_PIA_SRATE(&stream_port->info), - PJMEDIA_PIA_CCNT(&stream_port->info), - PJMEDIA_PIA_SPF(&stream_port->info), - PJMEDIA_PIA_BITS(&stream_port->info), - 0, &snd_port); - - - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to create sound port", status); - goto on_exit; - } - - /* Connect sound port to stream */ - status = pjmedia_snd_port_connect( snd_port, stream_port ); - PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); + /* Create sound device port. */ + if (dir == PJMEDIA_DIR_ENCODING_DECODING) + status = pjmedia_snd_port_create(pool, -1, -1, + PJMEDIA_PIA_SRATE(&stream_port->info), + PJMEDIA_PIA_CCNT(&stream_port->info), + PJMEDIA_PIA_SPF(&stream_port->info), + PJMEDIA_PIA_BITS(&stream_port->info), + 0, &snd_port); + else if (dir == PJMEDIA_DIR_ENCODING) + status = pjmedia_snd_port_create_rec(pool, -1, + PJMEDIA_PIA_SRATE(&stream_port->info), + PJMEDIA_PIA_CCNT(&stream_port->info), + PJMEDIA_PIA_SPF(&stream_port->info), + PJMEDIA_PIA_BITS(&stream_port->info), + 0, &snd_port); + else + status = pjmedia_snd_port_create_player(pool, -1, + PJMEDIA_PIA_SRATE(&stream_port->info), + PJMEDIA_PIA_CCNT(&stream_port->info), + PJMEDIA_PIA_SPF(&stream_port->info), + PJMEDIA_PIA_BITS(&stream_port->info), + 0, &snd_port); + + + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Unable to create sound port", status); + goto on_exit; + } + + /* Connect sound port to stream */ + status = pjmedia_snd_port_connect( snd_port, stream_port ); + PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); } @@ -767,41 +766,41 @@ int main(int argc, char *argv[]) /* Done */ if (dir == PJMEDIA_DIR_DECODING) - printf("Stream is active, dir is recv-only, local port is %d\n", - local_port); + printf("Stream is active, dir is recv-only, local port is %d\n", + local_port); else if (dir == PJMEDIA_DIR_ENCODING) - printf("Stream is active, dir is send-only, sending to %s:%d\n", - pj_inet_ntop2(pj_AF_INET(), &remote_addr.sin_addr, addr, - sizeof(addr)), - pj_ntohs(remote_addr.sin_port)); + printf("Stream is active, dir is send-only, sending to %s:%d\n", + pj_inet_ntop2(pj_AF_INET(), &remote_addr.sin_addr, addr, + sizeof(addr)), + pj_ntohs(remote_addr.sin_port)); else - printf("Stream is active, send/recv, local port is %d, " - "sending to %s:%d\n", - local_port, - pj_inet_ntop2(pj_AF_INET(), &remote_addr.sin_addr, addr, - sizeof(addr)), - pj_ntohs(remote_addr.sin_port)); + printf("Stream is active, send/recv, local port is %d, " + "sending to %s:%d\n", + local_port, + pj_inet_ntop2(pj_AF_INET(), &remote_addr.sin_addr, addr, + sizeof(addr)), + pj_ntohs(remote_addr.sin_port)); for (;;) { - puts(""); - puts("Commands:"); - puts(" s Display media statistics"); - puts(" q Quit"); - puts(""); + puts(""); + puts("Commands:"); + puts(" s Display media statistics"); + puts(" q Quit"); + puts(""); - printf("Command: "); fflush(stdout); + printf("Command: "); fflush(stdout); - if (fgets(tmp, sizeof(tmp), stdin) == NULL) { - puts("EOF while reading stdin, will quit now.."); - break; - } + if (fgets(tmp, sizeof(tmp), stdin) == NULL) { + puts("EOF while reading stdin, will quit now.."); + break; + } - if (tmp[0] == 's') - print_stream_stat(stream, &codec_param); - else if (tmp[0] == 'q') - break; + if (tmp[0] == 's') + print_stream_stat(stream, &codec_param); + else if (tmp[0] == 'q') + break; } @@ -812,8 +811,8 @@ int main(int argc, char *argv[]) /* Destroy sound device */ if (snd_port) { - pjmedia_snd_port_destroy( snd_port ); - PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); + pjmedia_snd_port_destroy( snd_port ); + PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); } /* If there is master port, then we just need to destroy master port @@ -821,27 +820,27 @@ int main(int argc, char *argv[]) * in this case are file_port and stream_port). */ if (master_port) { - pjmedia_master_port_destroy(master_port, PJ_TRUE); - play_file_port = NULL; - stream = NULL; + pjmedia_master_port_destroy(master_port, PJ_TRUE); + play_file_port = NULL; + stream = NULL; } /* Destroy stream */ if (stream) { - pjmedia_transport *tp; + pjmedia_transport *tp; - tp = pjmedia_stream_get_transport(stream); - pjmedia_stream_destroy(stream); - - pjmedia_transport_media_stop(tp); - pjmedia_transport_close(tp); + tp = pjmedia_stream_get_transport(stream); + pjmedia_stream_destroy(stream); + + pjmedia_transport_media_stop(tp); + pjmedia_transport_close(tp); } /* Destroy file ports */ if (play_file_port) - pjmedia_port_destroy( play_file_port ); + pjmedia_port_destroy( play_file_port ); if (rec_file_port) - pjmedia_port_destroy( rec_file_port ); + pjmedia_port_destroy( rec_file_port ); /* Destroy event manager */ pjmedia_event_mgr_destroy(NULL); @@ -868,15 +867,15 @@ int main(int argc, char *argv[]) static const char *good_number(char *buf, pj_int32_t val) { if (val < 1000) { - pj_ansi_sprintf(buf, "%d", val); + pj_ansi_sprintf(buf, "%d", val); } else if (val < 1000000) { - pj_ansi_sprintf(buf, "%d.%dK", - val / 1000, - (val % 1000) / 100); + pj_ansi_sprintf(buf, "%d.%dK", + val / 1000, + (val % 1000) / 100); } else { - pj_ansi_sprintf(buf, "%d.%02dM", - val / 1000000, - (val % 1000000) / 10000); + pj_ansi_sprintf(buf, "%d.%02dM", + val / 1000000, + (val % 1000000) / 10000); } return buf; @@ -885,26 +884,26 @@ static const char *good_number(char *buf, pj_int32_t val) #define SAMPLES_TO_USEC(usec, samples, clock_rate) \ do { \ - if (samples <= 4294) \ - usec = samples * 1000000 / clock_rate; \ - else { \ - usec = samples * 1000 / clock_rate; \ - usec *= 1000; \ - } \ + if (samples <= 4294) \ + usec = samples * 1000000 / clock_rate; \ + else { \ + usec = samples * 1000 / clock_rate; \ + usec *= 1000; \ + } \ } while(0) #define PRINT_VOIP_MTC_VAL(s, v) \ if (v == 127) \ - sprintf(s, "(na)"); \ + sprintf(s, "(na)"); \ else \ - sprintf(s, "%d", v) + sprintf(s, "%d", v) /* * Print stream statistics */ static void print_stream_stat(pjmedia_stream *stream, - const pjmedia_codec_param *codec_param) + const pjmedia_codec_param *codec_param) { char duration[80], last_update[80]; char bps[16], ipbps[16], packets[16], bytes[16], ipbytes[16]; @@ -922,453 +921,453 @@ static void print_stream_stat(pjmedia_stream *stream, /* Print duration */ PJ_TIME_VAL_SUB(now, stat.start); sprintf(duration, " Duration: %02ld:%02ld:%02ld.%03ld", - now.sec / 3600, - (now.sec % 3600) / 60, - (now.sec % 60), - now.msec); + now.sec / 3600, + (now.sec % 3600) / 60, + (now.sec % 60), + now.msec); printf(" Info: audio %dHz, %dms/frame, %sB/s (%sB/s +IP hdr)\n", - PJMEDIA_PIA_SRATE(&port->info), - PJMEDIA_PIA_PTIME(&port->info), - good_number(bps, (codec_param->info.avg_bps+7)/8), - good_number(ipbps, ((codec_param->info.avg_bps+7)/8) + - (40 * 1000 / - codec_param->setting.frm_per_pkt / - codec_param->info.frm_ptime))); + PJMEDIA_PIA_SRATE(&port->info), + PJMEDIA_PIA_PTIME(&port->info), + good_number(bps, (codec_param->info.avg_bps+7)/8), + good_number(ipbps, ((codec_param->info.avg_bps+7)/8) + + (40 * 1000 / + codec_param->setting.frm_per_pkt / + codec_param->info.frm_ptime))); if (stat.rx.update_cnt == 0) - strcpy(last_update, "never"); + strcpy(last_update, "never"); else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, stat.rx.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, stat.rx.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); } printf(" RX stat last update: %s\n" - " total %s packets %sB received (%sB +IP hdr)%s\n" - " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" - " (msec) min avg max last dev\n" - " loss period: %7.3f %7.3f %7.3f %7.3f %7.3f%s\n" - " jitter : %7.3f %7.3f %7.3f %7.3f %7.3f%s\n", - last_update, - good_number(packets, stat.rx.pkt), - good_number(bytes, stat.rx.bytes), - good_number(ipbytes, stat.rx.bytes + stat.rx.pkt * 32), - "", - stat.rx.loss, - stat.rx.loss * 100.0 / (stat.rx.pkt + stat.rx.loss), - stat.rx.dup, - stat.rx.dup * 100.0 / (stat.rx.pkt + stat.rx.loss), - stat.rx.reorder, - stat.rx.reorder * 100.0 / (stat.rx.pkt + stat.rx.loss), - "", - stat.rx.loss_period.min / 1000.0, - stat.rx.loss_period.mean / 1000.0, - stat.rx.loss_period.max / 1000.0, - stat.rx.loss_period.last / 1000.0, - pj_math_stat_get_stddev(&stat.rx.loss_period) / 1000.0, - "", - stat.rx.jitter.min / 1000.0, - stat.rx.jitter.mean / 1000.0, - stat.rx.jitter.max / 1000.0, - stat.rx.jitter.last / 1000.0, - pj_math_stat_get_stddev(&stat.rx.jitter) / 1000.0, - "" - ); + " total %s packets %sB received (%sB +IP hdr)%s\n" + " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" + " (msec) min avg max last dev\n" + " loss period: %7.3f %7.3f %7.3f %7.3f %7.3f%s\n" + " jitter : %7.3f %7.3f %7.3f %7.3f %7.3f%s\n", + last_update, + good_number(packets, stat.rx.pkt), + good_number(bytes, stat.rx.bytes), + good_number(ipbytes, stat.rx.bytes + stat.rx.pkt * 32), + "", + stat.rx.loss, + stat.rx.loss * 100.0 / (stat.rx.pkt + stat.rx.loss), + stat.rx.dup, + stat.rx.dup * 100.0 / (stat.rx.pkt + stat.rx.loss), + stat.rx.reorder, + stat.rx.reorder * 100.0 / (stat.rx.pkt + stat.rx.loss), + "", + stat.rx.loss_period.min / 1000.0, + stat.rx.loss_period.mean / 1000.0, + stat.rx.loss_period.max / 1000.0, + stat.rx.loss_period.last / 1000.0, + pj_math_stat_get_stddev(&stat.rx.loss_period) / 1000.0, + "", + stat.rx.jitter.min / 1000.0, + stat.rx.jitter.mean / 1000.0, + stat.rx.jitter.max / 1000.0, + stat.rx.jitter.last / 1000.0, + pj_math_stat_get_stddev(&stat.rx.jitter) / 1000.0, + "" + ); if (stat.tx.update_cnt == 0) - strcpy(last_update, "never"); + strcpy(last_update, "never"); else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, stat.tx.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, stat.tx.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); } printf(" TX stat last update: %s\n" - " total %s packets %sB sent (%sB +IP hdr)%s\n" - " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" - " (msec) min avg max last dev\n" - " loss period: %7.3f %7.3f %7.3f %7.3f %7.3f%s\n" - " jitter : %7.3f %7.3f %7.3f %7.3f %7.3f%s\n", - last_update, - good_number(packets, stat.tx.pkt), - good_number(bytes, stat.tx.bytes), - good_number(ipbytes, stat.tx.bytes + stat.tx.pkt * 32), - "", - stat.tx.loss, - stat.tx.loss * 100.0 / (stat.tx.pkt + stat.tx.loss), - stat.tx.dup, - stat.tx.dup * 100.0 / (stat.tx.pkt + stat.tx.loss), - stat.tx.reorder, - stat.tx.reorder * 100.0 / (stat.tx.pkt + stat.tx.loss), - "", - stat.tx.loss_period.min / 1000.0, - stat.tx.loss_period.mean / 1000.0, - stat.tx.loss_period.max / 1000.0, - stat.tx.loss_period.last / 1000.0, - pj_math_stat_get_stddev(&stat.tx.loss_period) / 1000.0, - "", - stat.tx.jitter.min / 1000.0, - stat.tx.jitter.mean / 1000.0, - stat.tx.jitter.max / 1000.0, - stat.tx.jitter.last / 1000.0, - pj_math_stat_get_stddev(&stat.tx.jitter) / 1000.0, - "" - ); + " total %s packets %sB sent (%sB +IP hdr)%s\n" + " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" + " (msec) min avg max last dev\n" + " loss period: %7.3f %7.3f %7.3f %7.3f %7.3f%s\n" + " jitter : %7.3f %7.3f %7.3f %7.3f %7.3f%s\n", + last_update, + good_number(packets, stat.tx.pkt), + good_number(bytes, stat.tx.bytes), + good_number(ipbytes, stat.tx.bytes + stat.tx.pkt * 32), + "", + stat.tx.loss, + stat.tx.loss * 100.0 / (stat.tx.pkt + stat.tx.loss), + stat.tx.dup, + stat.tx.dup * 100.0 / (stat.tx.pkt + stat.tx.loss), + stat.tx.reorder, + stat.tx.reorder * 100.0 / (stat.tx.pkt + stat.tx.loss), + "", + stat.tx.loss_period.min / 1000.0, + stat.tx.loss_period.mean / 1000.0, + stat.tx.loss_period.max / 1000.0, + stat.tx.loss_period.last / 1000.0, + pj_math_stat_get_stddev(&stat.tx.loss_period) / 1000.0, + "", + stat.tx.jitter.min / 1000.0, + stat.tx.jitter.mean / 1000.0, + stat.tx.jitter.max / 1000.0, + stat.tx.jitter.last / 1000.0, + pj_math_stat_get_stddev(&stat.tx.jitter) / 1000.0, + "" + ); printf(" RTT delay : %7.3f %7.3f %7.3f %7.3f %7.3f%s\n", - stat.rtt.min / 1000.0, - stat.rtt.mean / 1000.0, - stat.rtt.max / 1000.0, - stat.rtt.last / 1000.0, - pj_math_stat_get_stddev(&stat.rtt) / 1000.0, - "" - ); + stat.rtt.min / 1000.0, + stat.rtt.mean / 1000.0, + stat.rtt.max / 1000.0, + stat.rtt.last / 1000.0, + pj_math_stat_get_stddev(&stat.rtt) / 1000.0, + "" + ); #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) /* RTCP XR Reports */ do { - char loss[16], dup[16]; - char jitter[80]; - char toh[80]; - char plc[16], jba[16], jbr[16]; - char signal_lvl[16], noise_lvl[16], rerl[16]; - char r_factor[16], ext_r_factor[16], mos_lq[16], mos_cq[16]; - pjmedia_rtcp_xr_stat xr_stat; - - if (pjmedia_stream_get_stat_xr(stream, &xr_stat) != PJ_SUCCESS) - break; - - puts("\nExtended reports:"); - - /* Statistics Summary */ - puts(" Statistics Summary"); - - if (xr_stat.rx.stat_sum.l) - sprintf(loss, "%d", xr_stat.rx.stat_sum.lost); - else - sprintf(loss, "(na)"); - - if (xr_stat.rx.stat_sum.d) - sprintf(dup, "%d", xr_stat.rx.stat_sum.dup); - else - sprintf(dup, "(na)"); - - if (xr_stat.rx.stat_sum.j) { - unsigned jmin, jmax, jmean, jdev; - - SAMPLES_TO_USEC(jmin, xr_stat.rx.stat_sum.jitter.min, - port->info.fmt.det.aud.clock_rate); - SAMPLES_TO_USEC(jmax, xr_stat.rx.stat_sum.jitter.max, - port->info.fmt.det.aud.clock_rate); - SAMPLES_TO_USEC(jmean, xr_stat.rx.stat_sum.jitter.mean, - port->info.fmt.det.aud.clock_rate); - SAMPLES_TO_USEC(jdev, - pj_math_stat_get_stddev(&xr_stat.rx.stat_sum.jitter), - port->info.fmt.det.aud.clock_rate); - sprintf(jitter, "%7.3f %7.3f %7.3f %7.3f", - jmin/1000.0, jmean/1000.0, jmax/1000.0, jdev/1000.0); - } else - sprintf(jitter, "(report not available)"); - - if (xr_stat.rx.stat_sum.t) { - sprintf(toh, "%11d %11d %11d %11d", - xr_stat.rx.stat_sum.toh.min, - xr_stat.rx.stat_sum.toh.mean, - xr_stat.rx.stat_sum.toh.max, - pj_math_stat_get_stddev(&xr_stat.rx.stat_sum.toh)); - } else - sprintf(toh, "(report not available)"); - - if (xr_stat.rx.stat_sum.update.sec == 0) - strcpy(last_update, "never"); - else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, xr_stat.rx.stat_sum.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); - } - - printf(" RX last update: %s\n" - " begin seq=%d, end seq=%d%s\n" - " pkt loss=%s, dup=%s%s\n" - " (msec) min avg max dev\n" - " jitter : %s\n" - " toh : %s\n", - last_update, - xr_stat.rx.stat_sum.begin_seq, xr_stat.rx.stat_sum.end_seq, - "", - loss, dup, - "", - jitter, - toh - ); - - if (xr_stat.tx.stat_sum.l) - sprintf(loss, "%d", xr_stat.tx.stat_sum.lost); - else - sprintf(loss, "(na)"); - - if (xr_stat.tx.stat_sum.d) - sprintf(dup, "%d", xr_stat.tx.stat_sum.dup); - else - sprintf(dup, "(na)"); - - if (xr_stat.tx.stat_sum.j) { - unsigned jmin, jmax, jmean, jdev; - - SAMPLES_TO_USEC(jmin, xr_stat.tx.stat_sum.jitter.min, - port->info.fmt.det.aud.clock_rate); - SAMPLES_TO_USEC(jmax, xr_stat.tx.stat_sum.jitter.max, - port->info.fmt.det.aud.clock_rate); - SAMPLES_TO_USEC(jmean, xr_stat.tx.stat_sum.jitter.mean, - port->info.fmt.det.aud.clock_rate); - SAMPLES_TO_USEC(jdev, - pj_math_stat_get_stddev(&xr_stat.tx.stat_sum.jitter), - port->info.fmt.det.aud.clock_rate); - sprintf(jitter, "%7.3f %7.3f %7.3f %7.3f", - jmin/1000.0, jmean/1000.0, jmax/1000.0, jdev/1000.0); - } else - sprintf(jitter, "(report not available)"); - - if (xr_stat.tx.stat_sum.t) { - sprintf(toh, "%11d %11d %11d %11d", - xr_stat.tx.stat_sum.toh.min, - xr_stat.tx.stat_sum.toh.mean, - xr_stat.tx.stat_sum.toh.max, - pj_math_stat_get_stddev(&xr_stat.rx.stat_sum.toh)); - } else - sprintf(toh, "(report not available)"); - - if (xr_stat.tx.stat_sum.update.sec == 0) - strcpy(last_update, "never"); - else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, xr_stat.tx.stat_sum.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); - } - - printf(" TX last update: %s\n" - " begin seq=%d, end seq=%d%s\n" - " pkt loss=%s, dup=%s%s\n" - " (msec) min avg max dev\n" - " jitter : %s\n" - " toh : %s\n", - last_update, - xr_stat.tx.stat_sum.begin_seq, xr_stat.tx.stat_sum.end_seq, - "", - loss, dup, - "", - jitter, - toh - ); - - /* VoIP Metrics */ - puts(" VoIP Metrics"); - - PRINT_VOIP_MTC_VAL(signal_lvl, xr_stat.rx.voip_mtc.signal_lvl); - PRINT_VOIP_MTC_VAL(noise_lvl, xr_stat.rx.voip_mtc.noise_lvl); - PRINT_VOIP_MTC_VAL(rerl, xr_stat.rx.voip_mtc.rerl); - PRINT_VOIP_MTC_VAL(r_factor, xr_stat.rx.voip_mtc.r_factor); - PRINT_VOIP_MTC_VAL(ext_r_factor, xr_stat.rx.voip_mtc.ext_r_factor); - PRINT_VOIP_MTC_VAL(mos_lq, xr_stat.rx.voip_mtc.mos_lq); - PRINT_VOIP_MTC_VAL(mos_cq, xr_stat.rx.voip_mtc.mos_cq); - - switch ((xr_stat.rx.voip_mtc.rx_config>>6) & 3) { - case PJMEDIA_RTCP_XR_PLC_DIS: - sprintf(plc, "DISABLED"); - break; - case PJMEDIA_RTCP_XR_PLC_ENH: - sprintf(plc, "ENHANCED"); - break; - case PJMEDIA_RTCP_XR_PLC_STD: - sprintf(plc, "STANDARD"); - break; - case PJMEDIA_RTCP_XR_PLC_UNK: - default: - sprintf(plc, "UNKNOWN"); - break; - } - - switch ((xr_stat.rx.voip_mtc.rx_config>>4) & 3) { - case PJMEDIA_RTCP_XR_JB_FIXED: - sprintf(jba, "FIXED"); - break; - case PJMEDIA_RTCP_XR_JB_ADAPTIVE: - sprintf(jba, "ADAPTIVE"); - break; - default: - sprintf(jba, "UNKNOWN"); - break; - } - - sprintf(jbr, "%d", xr_stat.rx.voip_mtc.rx_config & 0x0F); - - if (xr_stat.rx.voip_mtc.update.sec == 0) - strcpy(last_update, "never"); - else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, xr_stat.rx.voip_mtc.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); - } - - printf(" RX last update: %s\n" - " packets : loss rate=%d (%.2f%%), discard rate=%d (%.2f%%)\n" - " burst : density=%d (%.2f%%), duration=%d%s\n" - " gap : density=%d (%.2f%%), duration=%d%s\n" - " delay : round trip=%d%s, end system=%d%s\n" - " level : signal=%s%s, noise=%s%s, RERL=%s%s\n" - " quality : R factor=%s, ext R factor=%s\n" - " MOS LQ=%s, MOS CQ=%s\n" - " config : PLC=%s, JB=%s, JB rate=%s, Gmin=%d\n" - " JB delay : cur=%d%s, max=%d%s, abs max=%d%s\n", - last_update, - /* pakcets */ - xr_stat.rx.voip_mtc.loss_rate, xr_stat.rx.voip_mtc.loss_rate*100.0/256, - xr_stat.rx.voip_mtc.discard_rate, xr_stat.rx.voip_mtc.discard_rate*100.0/256, - /* burst */ - xr_stat.rx.voip_mtc.burst_den, xr_stat.rx.voip_mtc.burst_den*100.0/256, - xr_stat.rx.voip_mtc.burst_dur, "ms", - /* gap */ - xr_stat.rx.voip_mtc.gap_den, xr_stat.rx.voip_mtc.gap_den*100.0/256, - xr_stat.rx.voip_mtc.gap_dur, "ms", - /* delay */ - xr_stat.rx.voip_mtc.rnd_trip_delay, "ms", - xr_stat.rx.voip_mtc.end_sys_delay, "ms", - /* level */ - signal_lvl, "dB", - noise_lvl, "dB", - rerl, "", - /* quality */ - r_factor, ext_r_factor, mos_lq, mos_cq, - /* config */ - plc, jba, jbr, xr_stat.rx.voip_mtc.gmin, - /* JB delay */ - xr_stat.rx.voip_mtc.jb_nom, "ms", - xr_stat.rx.voip_mtc.jb_max, "ms", - xr_stat.rx.voip_mtc.jb_abs_max, "ms" - ); - - PRINT_VOIP_MTC_VAL(signal_lvl, xr_stat.tx.voip_mtc.signal_lvl); - PRINT_VOIP_MTC_VAL(noise_lvl, xr_stat.tx.voip_mtc.noise_lvl); - PRINT_VOIP_MTC_VAL(rerl, xr_stat.tx.voip_mtc.rerl); - PRINT_VOIP_MTC_VAL(r_factor, xr_stat.tx.voip_mtc.r_factor); - PRINT_VOIP_MTC_VAL(ext_r_factor, xr_stat.tx.voip_mtc.ext_r_factor); - PRINT_VOIP_MTC_VAL(mos_lq, xr_stat.tx.voip_mtc.mos_lq); - PRINT_VOIP_MTC_VAL(mos_cq, xr_stat.tx.voip_mtc.mos_cq); - - switch ((xr_stat.tx.voip_mtc.rx_config>>6) & 3) { - case PJMEDIA_RTCP_XR_PLC_DIS: - sprintf(plc, "DISABLED"); - break; - case PJMEDIA_RTCP_XR_PLC_ENH: - sprintf(plc, "ENHANCED"); - break; - case PJMEDIA_RTCP_XR_PLC_STD: - sprintf(plc, "STANDARD"); - break; - case PJMEDIA_RTCP_XR_PLC_UNK: - default: - sprintf(plc, "unknown"); - break; - } - - switch ((xr_stat.tx.voip_mtc.rx_config>>4) & 3) { - case PJMEDIA_RTCP_XR_JB_FIXED: - sprintf(jba, "FIXED"); - break; - case PJMEDIA_RTCP_XR_JB_ADAPTIVE: - sprintf(jba, "ADAPTIVE"); - break; - default: - sprintf(jba, "unknown"); - break; - } - - sprintf(jbr, "%d", xr_stat.tx.voip_mtc.rx_config & 0x0F); - - if (xr_stat.tx.voip_mtc.update.sec == 0) - strcpy(last_update, "never"); - else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, xr_stat.tx.voip_mtc.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); - } - - printf(" TX last update: %s\n" - " packets : loss rate=%d (%.2f%%), discard rate=%d (%.2f%%)\n" - " burst : density=%d (%.2f%%), duration=%d%s\n" - " gap : density=%d (%.2f%%), duration=%d%s\n" - " delay : round trip=%d%s, end system=%d%s\n" - " level : signal=%s%s, noise=%s%s, RERL=%s%s\n" - " quality : R factor=%s, ext R factor=%s\n" - " MOS LQ=%s, MOS CQ=%s\n" - " config : PLC=%s, JB=%s, JB rate=%s, Gmin=%d\n" - " JB delay : cur=%d%s, max=%d%s, abs max=%d%s\n", - last_update, - /* pakcets */ - xr_stat.tx.voip_mtc.loss_rate, xr_stat.tx.voip_mtc.loss_rate*100.0/256, - xr_stat.tx.voip_mtc.discard_rate, xr_stat.tx.voip_mtc.discard_rate*100.0/256, - /* burst */ - xr_stat.tx.voip_mtc.burst_den, xr_stat.tx.voip_mtc.burst_den*100.0/256, - xr_stat.tx.voip_mtc.burst_dur, "ms", - /* gap */ - xr_stat.tx.voip_mtc.gap_den, xr_stat.tx.voip_mtc.gap_den*100.0/256, - xr_stat.tx.voip_mtc.gap_dur, "ms", - /* delay */ - xr_stat.tx.voip_mtc.rnd_trip_delay, "ms", - xr_stat.tx.voip_mtc.end_sys_delay, "ms", - /* level */ - signal_lvl, "dB", - noise_lvl, "dB", - rerl, "", - /* quality */ - r_factor, ext_r_factor, mos_lq, mos_cq, - /* config */ - plc, jba, jbr, xr_stat.tx.voip_mtc.gmin, - /* JB delay */ - xr_stat.tx.voip_mtc.jb_nom, "ms", - xr_stat.tx.voip_mtc.jb_max, "ms", - xr_stat.tx.voip_mtc.jb_abs_max, "ms" - ); - - - /* RTT delay (by receiver side) */ - printf(" (msec) min avg max last dev\n"); - printf(" RTT delay : %7.3f %7.3f %7.3f %7.3f %7.3f%s\n", - xr_stat.rtt.min / 1000.0, - xr_stat.rtt.mean / 1000.0, - xr_stat.rtt.max / 1000.0, - xr_stat.rtt.last / 1000.0, - pj_math_stat_get_stddev(&xr_stat.rtt) / 1000.0, - "" - ); + char loss[16], dup[16]; + char jitter[80]; + char toh[80]; + char plc[16], jba[16], jbr[16]; + char signal_lvl[16], noise_lvl[16], rerl[16]; + char r_factor[16], ext_r_factor[16], mos_lq[16], mos_cq[16]; + pjmedia_rtcp_xr_stat xr_stat; + + if (pjmedia_stream_get_stat_xr(stream, &xr_stat) != PJ_SUCCESS) + break; + + puts("\nExtended reports:"); + + /* Statistics Summary */ + puts(" Statistics Summary"); + + if (xr_stat.rx.stat_sum.l) + sprintf(loss, "%d", xr_stat.rx.stat_sum.lost); + else + sprintf(loss, "(na)"); + + if (xr_stat.rx.stat_sum.d) + sprintf(dup, "%d", xr_stat.rx.stat_sum.dup); + else + sprintf(dup, "(na)"); + + if (xr_stat.rx.stat_sum.j) { + unsigned jmin, jmax, jmean, jdev; + + SAMPLES_TO_USEC(jmin, xr_stat.rx.stat_sum.jitter.min, + port->info.fmt.det.aud.clock_rate); + SAMPLES_TO_USEC(jmax, xr_stat.rx.stat_sum.jitter.max, + port->info.fmt.det.aud.clock_rate); + SAMPLES_TO_USEC(jmean, xr_stat.rx.stat_sum.jitter.mean, + port->info.fmt.det.aud.clock_rate); + SAMPLES_TO_USEC(jdev, + pj_math_stat_get_stddev(&xr_stat.rx.stat_sum.jitter), + port->info.fmt.det.aud.clock_rate); + sprintf(jitter, "%7.3f %7.3f %7.3f %7.3f", + jmin/1000.0, jmean/1000.0, jmax/1000.0, jdev/1000.0); + } else + sprintf(jitter, "(report not available)"); + + if (xr_stat.rx.stat_sum.t) { + sprintf(toh, "%11d %11d %11d %11d", + xr_stat.rx.stat_sum.toh.min, + xr_stat.rx.stat_sum.toh.mean, + xr_stat.rx.stat_sum.toh.max, + pj_math_stat_get_stddev(&xr_stat.rx.stat_sum.toh)); + } else + sprintf(toh, "(report not available)"); + + if (xr_stat.rx.stat_sum.update.sec == 0) + strcpy(last_update, "never"); + else { + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, xr_stat.rx.stat_sum.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); + } + + printf(" RX last update: %s\n" + " begin seq=%d, end seq=%d%s\n" + " pkt loss=%s, dup=%s%s\n" + " (msec) min avg max dev\n" + " jitter : %s\n" + " toh : %s\n", + last_update, + xr_stat.rx.stat_sum.begin_seq, xr_stat.rx.stat_sum.end_seq, + "", + loss, dup, + "", + jitter, + toh + ); + + if (xr_stat.tx.stat_sum.l) + sprintf(loss, "%d", xr_stat.tx.stat_sum.lost); + else + sprintf(loss, "(na)"); + + if (xr_stat.tx.stat_sum.d) + sprintf(dup, "%d", xr_stat.tx.stat_sum.dup); + else + sprintf(dup, "(na)"); + + if (xr_stat.tx.stat_sum.j) { + unsigned jmin, jmax, jmean, jdev; + + SAMPLES_TO_USEC(jmin, xr_stat.tx.stat_sum.jitter.min, + port->info.fmt.det.aud.clock_rate); + SAMPLES_TO_USEC(jmax, xr_stat.tx.stat_sum.jitter.max, + port->info.fmt.det.aud.clock_rate); + SAMPLES_TO_USEC(jmean, xr_stat.tx.stat_sum.jitter.mean, + port->info.fmt.det.aud.clock_rate); + SAMPLES_TO_USEC(jdev, + pj_math_stat_get_stddev(&xr_stat.tx.stat_sum.jitter), + port->info.fmt.det.aud.clock_rate); + sprintf(jitter, "%7.3f %7.3f %7.3f %7.3f", + jmin/1000.0, jmean/1000.0, jmax/1000.0, jdev/1000.0); + } else + sprintf(jitter, "(report not available)"); + + if (xr_stat.tx.stat_sum.t) { + sprintf(toh, "%11d %11d %11d %11d", + xr_stat.tx.stat_sum.toh.min, + xr_stat.tx.stat_sum.toh.mean, + xr_stat.tx.stat_sum.toh.max, + pj_math_stat_get_stddev(&xr_stat.rx.stat_sum.toh)); + } else + sprintf(toh, "(report not available)"); + + if (xr_stat.tx.stat_sum.update.sec == 0) + strcpy(last_update, "never"); + else { + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, xr_stat.tx.stat_sum.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); + } + + printf(" TX last update: %s\n" + " begin seq=%d, end seq=%d%s\n" + " pkt loss=%s, dup=%s%s\n" + " (msec) min avg max dev\n" + " jitter : %s\n" + " toh : %s\n", + last_update, + xr_stat.tx.stat_sum.begin_seq, xr_stat.tx.stat_sum.end_seq, + "", + loss, dup, + "", + jitter, + toh + ); + + /* VoIP Metrics */ + puts(" VoIP Metrics"); + + PRINT_VOIP_MTC_VAL(signal_lvl, xr_stat.rx.voip_mtc.signal_lvl); + PRINT_VOIP_MTC_VAL(noise_lvl, xr_stat.rx.voip_mtc.noise_lvl); + PRINT_VOIP_MTC_VAL(rerl, xr_stat.rx.voip_mtc.rerl); + PRINT_VOIP_MTC_VAL(r_factor, xr_stat.rx.voip_mtc.r_factor); + PRINT_VOIP_MTC_VAL(ext_r_factor, xr_stat.rx.voip_mtc.ext_r_factor); + PRINT_VOIP_MTC_VAL(mos_lq, xr_stat.rx.voip_mtc.mos_lq); + PRINT_VOIP_MTC_VAL(mos_cq, xr_stat.rx.voip_mtc.mos_cq); + + switch ((xr_stat.rx.voip_mtc.rx_config>>6) & 3) { + case PJMEDIA_RTCP_XR_PLC_DIS: + sprintf(plc, "DISABLED"); + break; + case PJMEDIA_RTCP_XR_PLC_ENH: + sprintf(plc, "ENHANCED"); + break; + case PJMEDIA_RTCP_XR_PLC_STD: + sprintf(plc, "STANDARD"); + break; + case PJMEDIA_RTCP_XR_PLC_UNK: + default: + sprintf(plc, "UNKNOWN"); + break; + } + + switch ((xr_stat.rx.voip_mtc.rx_config>>4) & 3) { + case PJMEDIA_RTCP_XR_JB_FIXED: + sprintf(jba, "FIXED"); + break; + case PJMEDIA_RTCP_XR_JB_ADAPTIVE: + sprintf(jba, "ADAPTIVE"); + break; + default: + sprintf(jba, "UNKNOWN"); + break; + } + + sprintf(jbr, "%d", xr_stat.rx.voip_mtc.rx_config & 0x0F); + + if (xr_stat.rx.voip_mtc.update.sec == 0) + strcpy(last_update, "never"); + else { + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, xr_stat.rx.voip_mtc.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); + } + + printf(" RX last update: %s\n" + " packets : loss rate=%d (%.2f%%), discard rate=%d (%.2f%%)\n" + " burst : density=%d (%.2f%%), duration=%d%s\n" + " gap : density=%d (%.2f%%), duration=%d%s\n" + " delay : round trip=%d%s, end system=%d%s\n" + " level : signal=%s%s, noise=%s%s, RERL=%s%s\n" + " quality : R factor=%s, ext R factor=%s\n" + " MOS LQ=%s, MOS CQ=%s\n" + " config : PLC=%s, JB=%s, JB rate=%s, Gmin=%d\n" + " JB delay : cur=%d%s, max=%d%s, abs max=%d%s\n", + last_update, + /* pakcets */ + xr_stat.rx.voip_mtc.loss_rate, xr_stat.rx.voip_mtc.loss_rate*100.0/256, + xr_stat.rx.voip_mtc.discard_rate, xr_stat.rx.voip_mtc.discard_rate*100.0/256, + /* burst */ + xr_stat.rx.voip_mtc.burst_den, xr_stat.rx.voip_mtc.burst_den*100.0/256, + xr_stat.rx.voip_mtc.burst_dur, "ms", + /* gap */ + xr_stat.rx.voip_mtc.gap_den, xr_stat.rx.voip_mtc.gap_den*100.0/256, + xr_stat.rx.voip_mtc.gap_dur, "ms", + /* delay */ + xr_stat.rx.voip_mtc.rnd_trip_delay, "ms", + xr_stat.rx.voip_mtc.end_sys_delay, "ms", + /* level */ + signal_lvl, "dB", + noise_lvl, "dB", + rerl, "", + /* quality */ + r_factor, ext_r_factor, mos_lq, mos_cq, + /* config */ + plc, jba, jbr, xr_stat.rx.voip_mtc.gmin, + /* JB delay */ + xr_stat.rx.voip_mtc.jb_nom, "ms", + xr_stat.rx.voip_mtc.jb_max, "ms", + xr_stat.rx.voip_mtc.jb_abs_max, "ms" + ); + + PRINT_VOIP_MTC_VAL(signal_lvl, xr_stat.tx.voip_mtc.signal_lvl); + PRINT_VOIP_MTC_VAL(noise_lvl, xr_stat.tx.voip_mtc.noise_lvl); + PRINT_VOIP_MTC_VAL(rerl, xr_stat.tx.voip_mtc.rerl); + PRINT_VOIP_MTC_VAL(r_factor, xr_stat.tx.voip_mtc.r_factor); + PRINT_VOIP_MTC_VAL(ext_r_factor, xr_stat.tx.voip_mtc.ext_r_factor); + PRINT_VOIP_MTC_VAL(mos_lq, xr_stat.tx.voip_mtc.mos_lq); + PRINT_VOIP_MTC_VAL(mos_cq, xr_stat.tx.voip_mtc.mos_cq); + + switch ((xr_stat.tx.voip_mtc.rx_config>>6) & 3) { + case PJMEDIA_RTCP_XR_PLC_DIS: + sprintf(plc, "DISABLED"); + break; + case PJMEDIA_RTCP_XR_PLC_ENH: + sprintf(plc, "ENHANCED"); + break; + case PJMEDIA_RTCP_XR_PLC_STD: + sprintf(plc, "STANDARD"); + break; + case PJMEDIA_RTCP_XR_PLC_UNK: + default: + sprintf(plc, "unknown"); + break; + } + + switch ((xr_stat.tx.voip_mtc.rx_config>>4) & 3) { + case PJMEDIA_RTCP_XR_JB_FIXED: + sprintf(jba, "FIXED"); + break; + case PJMEDIA_RTCP_XR_JB_ADAPTIVE: + sprintf(jba, "ADAPTIVE"); + break; + default: + sprintf(jba, "unknown"); + break; + } + + sprintf(jbr, "%d", xr_stat.tx.voip_mtc.rx_config & 0x0F); + + if (xr_stat.tx.voip_mtc.update.sec == 0) + strcpy(last_update, "never"); + else { + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, xr_stat.tx.voip_mtc.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); + } + + printf(" TX last update: %s\n" + " packets : loss rate=%d (%.2f%%), discard rate=%d (%.2f%%)\n" + " burst : density=%d (%.2f%%), duration=%d%s\n" + " gap : density=%d (%.2f%%), duration=%d%s\n" + " delay : round trip=%d%s, end system=%d%s\n" + " level : signal=%s%s, noise=%s%s, RERL=%s%s\n" + " quality : R factor=%s, ext R factor=%s\n" + " MOS LQ=%s, MOS CQ=%s\n" + " config : PLC=%s, JB=%s, JB rate=%s, Gmin=%d\n" + " JB delay : cur=%d%s, max=%d%s, abs max=%d%s\n", + last_update, + /* pakcets */ + xr_stat.tx.voip_mtc.loss_rate, xr_stat.tx.voip_mtc.loss_rate*100.0/256, + xr_stat.tx.voip_mtc.discard_rate, xr_stat.tx.voip_mtc.discard_rate*100.0/256, + /* burst */ + xr_stat.tx.voip_mtc.burst_den, xr_stat.tx.voip_mtc.burst_den*100.0/256, + xr_stat.tx.voip_mtc.burst_dur, "ms", + /* gap */ + xr_stat.tx.voip_mtc.gap_den, xr_stat.tx.voip_mtc.gap_den*100.0/256, + xr_stat.tx.voip_mtc.gap_dur, "ms", + /* delay */ + xr_stat.tx.voip_mtc.rnd_trip_delay, "ms", + xr_stat.tx.voip_mtc.end_sys_delay, "ms", + /* level */ + signal_lvl, "dB", + noise_lvl, "dB", + rerl, "", + /* quality */ + r_factor, ext_r_factor, mos_lq, mos_cq, + /* config */ + plc, jba, jbr, xr_stat.tx.voip_mtc.gmin, + /* JB delay */ + xr_stat.tx.voip_mtc.jb_nom, "ms", + xr_stat.tx.voip_mtc.jb_max, "ms", + xr_stat.tx.voip_mtc.jb_abs_max, "ms" + ); + + + /* RTT delay (by receiver side) */ + printf(" (msec) min avg max last dev\n"); + printf(" RTT delay : %7.3f %7.3f %7.3f %7.3f %7.3f%s\n", + xr_stat.rtt.min / 1000.0, + xr_stat.rtt.mean / 1000.0, + xr_stat.rtt.max / 1000.0, + xr_stat.rtt.last / 1000.0, + pj_math_stat_get_stddev(&xr_stat.rtt) / 1000.0, + "" + ); } while (0); #endif /* PJMEDIA_HAS_RTCP_XR */ diff --git a/pjsip-apps/src/samples/strerror.c b/pjsip-apps/src/samples/strerror.c index e6d94f175a..63a8266c2b 100644 --- a/pjsip-apps/src/samples/strerror.c +++ b/pjsip-apps/src/samples/strerror.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,8 +45,8 @@ int main(int argc, char *argv[]) pj_status_t code; if (argc != 2) { - puts("Usage: strerror ERRNUM"); - return 1; + puts("Usage: strerror ERRNUM"); + return 1; } pj_log_set_level(3); diff --git a/pjsip-apps/src/samples/tonegen.c b/pjsip-apps/src/samples/tonegen.c index efd4a31821..dfc9f6a44b 100644 --- a/pjsip-apps/src/samples/tonegen.c +++ b/pjsip-apps/src/samples/tonegen.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,8 +35,8 @@ #include #define SAMPLES_PER_FRAME 64 -#define ON_DURATION 100 -#define OFF_DURATION 100 +#define ON_DURATION 100 +#define OFF_DURATION 100 /* @@ -68,74 +67,74 @@ int main() PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool for our file player */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "app", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "app", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); status = pjmedia_tonegen_create(pool, 8000, 1, SAMPLES_PER_FRAME, 16, 0, &port); if (status != PJ_SUCCESS) - return 1; + return 1; { - pjmedia_tone_desc tones[3]; + pjmedia_tone_desc tones[3]; - tones[0].freq1 = 200; - tones[0].freq2 = 0; - tones[0].on_msec = ON_DURATION; - tones[0].off_msec = OFF_DURATION; + tones[0].freq1 = 200; + tones[0].freq2 = 0; + tones[0].on_msec = ON_DURATION; + tones[0].off_msec = OFF_DURATION; - tones[1].freq1 = 400; - tones[1].freq2 = 0; - tones[1].on_msec = ON_DURATION; - tones[1].off_msec = OFF_DURATION; + tones[1].freq1 = 400; + tones[1].freq2 = 0; + tones[1].on_msec = ON_DURATION; + tones[1].off_msec = OFF_DURATION; - tones[2].freq1 = 800; - tones[2].freq2 = 0; - tones[2].on_msec = ON_DURATION; - tones[2].off_msec = OFF_DURATION; + tones[2].freq1 = 800; + tones[2].freq2 = 0; + tones[2].on_msec = ON_DURATION; + tones[2].off_msec = OFF_DURATION; - status = pjmedia_tonegen_play(port, 3, tones, 0); - PJ_ASSERT_RETURN(status==PJ_SUCCESS, 1); + status = pjmedia_tonegen_play(port, 3, tones, 0); + PJ_ASSERT_RETURN(status==PJ_SUCCESS, 1); } { - pjmedia_tone_digit digits[2]; + pjmedia_tone_digit digits[2]; - digits[0].digit = '0'; - digits[0].on_msec = ON_DURATION; - digits[0].off_msec = OFF_DURATION; + digits[0].digit = '0'; + digits[0].on_msec = ON_DURATION; + digits[0].off_msec = OFF_DURATION; - digits[1].digit = '0'; - digits[1].on_msec = ON_DURATION; - digits[1].off_msec = OFF_DURATION; + digits[1].digit = '0'; + digits[1].on_msec = ON_DURATION; + digits[1].off_msec = OFF_DURATION; - status = pjmedia_tonegen_play_digits(port, 2, digits, 0); - PJ_ASSERT_RETURN(status==PJ_SUCCESS, 1); + status = pjmedia_tonegen_play_digits(port, 2, digits, 0); + PJ_ASSERT_RETURN(status==PJ_SUCCESS, 1); } { - pjmedia_frame frm; - FILE *f; - void *buf; + pjmedia_frame frm; + FILE *f; + void *buf; - buf = pj_pool_alloc(pool, 2*8000); - frm.buf = buf; + buf = pj_pool_alloc(pool, 2*8000); + frm.buf = buf; - f = fopen("tonegen.pcm", "wb"); + f = fopen("tonegen.pcm", "wb"); - for (i=0; i<8000/SAMPLES_PER_FRAME; ++i) { - pj_size_t count; - pjmedia_port_get_frame(port, &frm); - count = fwrite(buf, SAMPLES_PER_FRAME, 2, f); - if (count != 2) - break; - } + for (i=0; i<8000/SAMPLES_PER_FRAME; ++i) { + pj_size_t count; + pjmedia_port_get_frame(port, &frm); + count = fwrite(buf, SAMPLES_PER_FRAME, 2, f); + if (count != 2) + break; + } - pj_assert(pjmedia_tonegen_is_busy(port) == 0); - fclose(f); + pj_assert(pjmedia_tonegen_is_busy(port) == 0); + fclose(f); } /* Delete port */ diff --git a/pjsip-apps/src/samples/util.h b/pjsip-apps/src/samples/util.h index 30b10b2d67..c9b9f28e49 100644 --- a/pjsip-apps/src/samples/util.h +++ b/pjsip-apps/src/samples/util.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -17,11 +16,11 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -#include /* strtol() */ +#include /* strtol() */ /* Util to display the error message for the specified error code */ static int app_perror( const char *sender, const char *title, - pj_status_t status) + pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; @@ -33,30 +32,30 @@ static int app_perror( const char *sender, const char *title, #define STRLIT_(expr) #expr #define STRLIT(expr) STRLIT_(expr) -#define CHECK(expr) do { \ - status = expr; \ - if (status!=PJ_SUCCESS && status!=PJ_EPENDING) { \ - PJ_PERROR(1,(THIS_FILE, status, \ - "In " __FILE__ ":" STRLIT(__LINE__))); \ - goto on_error; \ - } \ - } while (0) +#define CHECK(expr) do { \ + status = expr; \ + if (status!=PJ_SUCCESS && status!=PJ_EPENDING) { \ + PJ_PERROR(1,(THIS_FILE, status, \ + "In " __FILE__ ":" STRLIT(__LINE__))); \ + goto on_error; \ + } \ + } while (0) /* Constants */ -#define CLOCK_RATE 44100 -#define NSAMPLES (CLOCK_RATE * 20 / 1000) -#define NCHANNELS 1 -#define NBITS 16 +#define CLOCK_RATE 44100 +#define NSAMPLES (CLOCK_RATE * 20 / 1000) +#define NCHANNELS 1 +#define NBITS 16 /* * Common sound options. */ #define SND_USAGE \ -" -d, --dev=NUM Sound device use device id NUM (default=-1) \n"\ +" -d, --dev=NUM Sound device use device id NUM (default=-1) \n"\ " -r, --rate=HZ Set clock rate in samples per sec (default=44100)\n"\ -" -c, --channel=NUM Set # of channels (default=1 for mono). \n"\ +" -c, --channel=NUM Set # of channels (default=1 for mono). \n"\ " -f, --frame=NUM Set # of samples per frame (default equival 20ms)\n"\ -" -b, --bit=NUM Set # of bits per sample (default=16) \n" +" -b, --bit=NUM Set # of bits per sample (default=16) \n" /* @@ -64,21 +63,21 @@ static int app_perror( const char *sender, const char *title, * common sound options. */ pj_status_t get_snd_options(const char *app_name, - int argc, - char *argv[], - int *dev_id, - int *clock_rate, - int *channel_count, - int *samples_per_frame, - int *bits_per_sample) + int argc, + char *argv[], + int *dev_id, + int *clock_rate, + int *channel_count, + int *samples_per_frame, + int *bits_per_sample) { struct pj_getopt_option long_options[] = { - { "dev", 1, 0, 'd' }, - { "rate", 1, 0, 'r' }, - { "channel", 1, 0, 'c' }, - { "frame", 1, 0, 'f' }, - { "bit", 1, 0, 'b' }, - { NULL, 0, 0, 0 }, + { "dev", 1, 0, 'd' }, + { "rate", 1, 0, 'r' }, + { "channel", 1, 0, 'c' }, + { "frame", 1, 0, 'f' }, + { "bit", 1, 0, 'b' }, + { NULL, 0, 0, 0 }, }; int c; int option_index; @@ -89,70 +88,70 @@ pj_status_t get_snd_options(const char *app_name, pj_optind = 0; while((c=pj_getopt_long(argc,argv, "d:r:c:f:b:", - long_options, &option_index))!=-1) + long_options, &option_index))!=-1) { - switch (c) { - case 'd': - /* device */ - val = strtol(pj_optarg, &err, 10); - if (*err) { - PJ_LOG(3,(app_name, "Error: invalid value for device id")); - return PJ_EINVAL; - } - *dev_id = val; - break; - - case 'r': - /* rate */ - val = strtol(pj_optarg, &err, 10); - if (*err) { - PJ_LOG(3,(app_name, "Error: invalid value for clock rate")); - return PJ_EINVAL; - } - *clock_rate = val; - break; - - case 'c': - /* channel count */ - val = strtol(pj_optarg, &err, 10); - if (*err) { - PJ_LOG(3,(app_name, "Error: invalid channel count")); - return PJ_EINVAL; - } - *channel_count = val; - break; - - case 'f': - /* frame count/samples per frame */ - val = strtol(pj_optarg, &err, 10); - if (*err) { - PJ_LOG(3,(app_name, "Error: invalid samples per frame")); - return PJ_EINVAL; - } - *samples_per_frame = val; - break; - - case 'b': - /* bit per sample */ - val = strtol(pj_optarg, &err, 10); - if (*err) { - PJ_LOG(3,(app_name, "Error: invalid samples bits per sample")); - return PJ_EINVAL; - } - *bits_per_sample = val; - break; - - default: - /* Unknown options */ - PJ_LOG(3,(app_name, "Error: unknown options '%c'", pj_optopt)); - return PJ_EINVAL; - } + switch (c) { + case 'd': + /* device */ + val = strtol(pj_optarg, &err, 10); + if (*err) { + PJ_LOG(3,(app_name, "Error: invalid value for device id")); + return PJ_EINVAL; + } + *dev_id = val; + break; + + case 'r': + /* rate */ + val = strtol(pj_optarg, &err, 10); + if (*err) { + PJ_LOG(3,(app_name, "Error: invalid value for clock rate")); + return PJ_EINVAL; + } + *clock_rate = val; + break; + + case 'c': + /* channel count */ + val = strtol(pj_optarg, &err, 10); + if (*err) { + PJ_LOG(3,(app_name, "Error: invalid channel count")); + return PJ_EINVAL; + } + *channel_count = val; + break; + + case 'f': + /* frame count/samples per frame */ + val = strtol(pj_optarg, &err, 10); + if (*err) { + PJ_LOG(3,(app_name, "Error: invalid samples per frame")); + return PJ_EINVAL; + } + *samples_per_frame = val; + break; + + case 'b': + /* bit per sample */ + val = strtol(pj_optarg, &err, 10); + if (*err) { + PJ_LOG(3,(app_name, "Error: invalid samples bits per sample")); + return PJ_EINVAL; + } + *bits_per_sample = val; + break; + + default: + /* Unknown options */ + PJ_LOG(3,(app_name, "Error: unknown options '%c'", pj_optopt)); + return PJ_EINVAL; + } } if (*samples_per_frame == 0) { - *samples_per_frame = *clock_rate * *channel_count * 20 / 1000; + *samples_per_frame = *clock_rate * *channel_count * 20 / 1000; } return 0; @@ -170,13 +169,13 @@ void dump_pool_usage( const char *app_name, pj_caching_pool *cp ) /* Accumulate memory usage in active list. */ p = (pj_pool_t*)cp->used_list.next; while (p != (pj_pool_t*) &cp->used_list) { - total_alloc += pj_pool_get_capacity(p); - total_used += pj_pool_get_used_size(p); - p = p->next; + total_alloc += pj_pool_get_capacity(p); + total_used += pj_pool_get_used_size(p); + p = p->next; } PJ_LOG(3, (app_name, "Total pool memory allocated=%d KB, used=%d KB", - total_alloc / 1000, - total_used / 1000)); + total_alloc / 1000, + total_used / 1000)); #endif } diff --git a/pjsip-apps/src/samples/vid_codec_test.c b/pjsip-apps/src/samples/vid_codec_test.c index 978555d76a..2738c41d96 100644 --- a/pjsip-apps/src/samples/vid_codec_test.c +++ b/pjsip-apps/src/samples/vid_codec_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2014 Teluu Inc. (http://www.teluu.com) * @@ -37,13 +36,13 @@ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -#include /* atoi() */ +#include /* atoi() */ #include #include "util.h" -#define THIS_FILE "vid_vodec_test.c" +#define THIS_FILE "vid_vodec_test.c" /* If set, local renderer will be created to play original file */ @@ -53,8 +52,8 @@ /* Default width and height for the renderer, better be set to maximum * acceptable size. */ -#define DEF_RENDERER_WIDTH 640 -#define DEF_RENDERER_HEIGHT 480 +#define DEF_RENDERER_WIDTH 640 +#define DEF_RENDERER_HEIGHT 480 /* Prototype for LIBSRTP utility in file datatypes.c */ @@ -123,30 +122,30 @@ static void show_diff(const pj_uint8_t *buf1, const pj_uint8_t *buf2, unsigned size) { enum { - STEP = 50 + STEP = 50 }; unsigned i=0; for (; i 0) - { - break; - } - } - nal_len[0] = i; - for (i = 0; i < size[1]; i++) { - if (memcmp(buf[1] + pos[1] + i, start_nal, - sizeof(start_nal)) == 0 && i > 0) - { - break; - } - } - nal_len[1] = i; - - if (nal_len[0] != nal_len[1]) { - printf("Different size in frame %d (%d vs %d)\n", - frame_cnt, nal_len[0], nal_len[1]); - } - - if (memcmp(buf[0]+pos[0], buf[1]+pos[1], nal_len[0]) != 0) { - printf("Mismatch in frame %d\n", frame_cnt); - show_diff(buf[0]+pos[0], buf[1]+pos[1], nal_len[0]); - puts(""); - ++mismatch_cnt; - } - - pos[0] += nal_len[0]; - pos[1] += nal_len[1]; - - if (pos[0] >= size[0]) - break; + unsigned nal_len[2]; + for (i = 0; i < size[0]; i++) { + if (memcmp(buf[0] + pos[0] + i, start_nal, + sizeof(start_nal)) == 0 && i > 0) + { + break; + } + } + nal_len[0] = i; + for (i = 0; i < size[1]; i++) { + if (memcmp(buf[1] + pos[1] + i, start_nal, + sizeof(start_nal)) == 0 && i > 0) + { + break; + } + } + nal_len[1] = i; + + if (nal_len[0] != nal_len[1]) { + printf("Different size in frame %d (%d vs %d)\n", + frame_cnt, nal_len[0], nal_len[1]); + } + + if (memcmp(buf[0]+pos[0], buf[1]+pos[1], nal_len[0]) != 0) { + printf("Mismatch in frame %d\n", frame_cnt); + show_diff(buf[0]+pos[0], buf[1]+pos[1], nal_len[0]); + puts(""); + ++mismatch_cnt; + } + + pos[0] += nal_len[0]; + pos[1] += nal_len[1]; + + if (pos[0] >= size[0]) + break; } free(buf[0]); free(buf[1]); if (!mismatch_cnt) - puts("Files the same!"); + puts("Files the same!"); else - printf("%d mismatches\n", mismatch_cnt); + printf("%d mismatches\n", mismatch_cnt); } /* @@ -261,19 +260,19 @@ int main(int argc, char *argv[]) pjmedia_vid_codec *codec = NULL; //const char *save_filename = - // "/home/bennylp/Desktop/opt/src/openh264-svn/testbin/test.264"; + // "/home/bennylp/Desktop/opt/src/openh264-svn/testbin/test.264"; const char *save_filename = NULL; /* File */ enum { - WIDTH = 320, - HEIGHT = 192, - FPS = 12, - YUV_SIZE = WIDTH * HEIGHT * 3 >> 1, - YUV_BUF_SIZE = YUV_SIZE + WIDTH, - MAX_FRAMES = 32, - MTU = 1500 + WIDTH = 320, + HEIGHT = 192, + FPS = 12, + YUV_SIZE = WIDTH * HEIGHT * 3 >> 1, + YUV_BUF_SIZE = YUV_SIZE + WIDTH, + MAX_FRAMES = 32, + MTU = 1500 }; FILE *fyuv = NULL; FILE *f264 = NULL; @@ -281,13 +280,13 @@ int main(int argc, char *argv[]) pj_uint8_t yuv_frame[YUV_BUF_SIZE]; enc_buf_type enc_buf[MAX_FRAMES]; unsigned read_cnt = 0, - pkt_cnt = 0, - dec_cnt = 0, - enc_cnt; + pkt_cnt = 0, + dec_cnt = 0, + enc_cnt; if (0) { - diff_file(); - return 1; + diff_file(); + return 1; } /* init PJLIB : */ @@ -302,12 +301,12 @@ int main(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool for application purpose */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "app", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "app", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); /* Init video format manager */ pjmedia_video_format_mgr_create(pool, 64, 0, NULL); @@ -328,47 +327,47 @@ int main(int argc, char *argv[]) /* Open YUV file */ fyuv = fopen("pjsip-apps/bin/CiscoVT2people_320x192_12fps.yuv", "rb"); if (!fyuv) { - puts("Unable to open ../CiscoVT2people_320x192_12fps.yuv"); - status = -1; - goto on_exit; + puts("Unable to open ../CiscoVT2people_320x192_12fps.yuv"); + status = -1; + goto on_exit; } /* Write 264 file if wanted */ if (save_filename) { - f264 = fopen(save_filename, "wb"); + f264 = fopen(save_filename, "wb"); } /* Find which codec to use. */ if (codec_id) { - unsigned count = 1; - pj_str_t str_codec_id = pj_str(codec_id); + unsigned count = 1; + pj_str_t str_codec_id = pj_str(codec_id); status = pjmedia_vid_codec_mgr_find_codecs_by_id(NULL, - &str_codec_id, &count, - &codec_info, NULL); - if (status != PJ_SUCCESS) { - printf("Error: unable to find codec %s\n", codec_id); - goto on_exit; - } + &str_codec_id, &count, + &codec_info, NULL); + if (status != PJ_SUCCESS) { + printf("Error: unable to find codec %s\n", codec_id); + goto on_exit; + } } else { static pjmedia_vid_codec_info info[1]; unsigned count = PJ_ARRAY_SIZE(info); - /* Default to first codec */ - pjmedia_vid_codec_mgr_enum_codecs(NULL, &count, info, NULL); + /* Default to first codec */ + pjmedia_vid_codec_mgr_enum_codecs(NULL, &count, info, NULL); codec_info = &info[0]; } /* Get codec default param for info */ status = pjmedia_vid_codec_mgr_get_default_param(NULL, codec_info, - &codec_param); + &codec_param); pj_assert(status == PJ_SUCCESS); /* Alloc encoder */ status = pjmedia_vid_codec_mgr_alloc_codec(NULL, codec_info, &codec); if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, "Error allocating codec")); - goto on_exit; + PJ_PERROR(3,(THIS_FILE, status, "Error allocating codec")); + goto on_exit; } codec_param.dir = PJMEDIA_DIR_ENCODING_DECODING; @@ -381,116 +380,116 @@ int main(int argc, char *argv[]) status = pjmedia_vid_codec_init(codec, pool); if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, "Error initializing codec")); - goto on_exit; + PJ_PERROR(3,(THIS_FILE, status, "Error initializing codec")); + goto on_exit; } status = pjmedia_vid_codec_open(codec, &codec_param); if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, "Error opening codec")); - goto on_exit; + PJ_PERROR(3,(THIS_FILE, status, "Error opening codec")); + goto on_exit; } while (fread(yuv_frame, 1, YUV_SIZE, fyuv) == YUV_SIZE) { - pjmedia_frame frm_yuv, frm_enc[MAX_FRAMES]; - pj_bool_t has_more = PJ_FALSE; - const pj_uint8_t start_nal[] = { 0, 0, 1 }; - - ++ read_cnt; - - pj_bzero(&frm_enc, sizeof(frm_enc)); - pj_bzero(&frm_yuv, sizeof(frm_yuv)); - - frm_yuv.buf = yuv_frame; - frm_yuv.size = YUV_SIZE; - - enc_cnt = 0; - frm_enc[enc_cnt].buf = enc_buf[enc_cnt]; - frm_enc[enc_cnt].size = MTU; - - status = pjmedia_vid_codec_encode_begin(codec, NULL, &frm_yuv, - MTU, &frm_enc[enc_cnt], - &has_more); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, "Codec encode error")); - goto on_exit; - } - if (frm_enc[enc_cnt].size) { - if (f264) { - fwrite(start_nal, 1, sizeof(start_nal), f264); - fwrite(frm_enc[enc_cnt].buf, 1, frm_enc[enc_cnt].size, f264); - } - ++pkt_cnt; - ++enc_cnt; - } - - while (has_more) { - - if (enc_cnt >= MAX_FRAMES) { - status = -1; - puts("Error: too many encoded frames"); - goto on_exit; - } - - has_more = PJ_FALSE; - frm_enc[enc_cnt].buf = enc_buf[enc_cnt]; - frm_enc[enc_cnt].size = MTU; - - status = pjmedia_vid_codec_encode_more(codec, MTU, - &frm_enc[enc_cnt], - &has_more); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, "Codec encode error")); - goto on_exit; - } - - if (frm_enc[enc_cnt].size) { - if (f264) { - fwrite(start_nal, 1, sizeof(start_nal), f264); - fwrite(frm_enc[enc_cnt].buf, 1, frm_enc[enc_cnt].size, - f264); - } - ++pkt_cnt; - ++enc_cnt; - } - } - - if (enc_cnt) { - frm_yuv.buf = yuv_frame; - frm_yuv.size = YUV_BUF_SIZE; - status = pjmedia_vid_codec_decode(codec, enc_cnt, - frm_enc, - YUV_BUF_SIZE, - &frm_yuv); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, "Codec decode error")); - goto on_exit; - } - - if (frm_yuv.size != 0) { - ++dec_cnt; - } - } + pjmedia_frame frm_yuv, frm_enc[MAX_FRAMES]; + pj_bool_t has_more = PJ_FALSE; + const pj_uint8_t start_nal[] = { 0, 0, 1 }; + + ++ read_cnt; + + pj_bzero(&frm_enc, sizeof(frm_enc)); + pj_bzero(&frm_yuv, sizeof(frm_yuv)); + + frm_yuv.buf = yuv_frame; + frm_yuv.size = YUV_SIZE; + + enc_cnt = 0; + frm_enc[enc_cnt].buf = enc_buf[enc_cnt]; + frm_enc[enc_cnt].size = MTU; + + status = pjmedia_vid_codec_encode_begin(codec, NULL, &frm_yuv, + MTU, &frm_enc[enc_cnt], + &has_more); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(THIS_FILE, status, "Codec encode error")); + goto on_exit; + } + if (frm_enc[enc_cnt].size) { + if (f264) { + fwrite(start_nal, 1, sizeof(start_nal), f264); + fwrite(frm_enc[enc_cnt].buf, 1, frm_enc[enc_cnt].size, f264); + } + ++pkt_cnt; + ++enc_cnt; + } + + while (has_more) { + + if (enc_cnt >= MAX_FRAMES) { + status = -1; + puts("Error: too many encoded frames"); + goto on_exit; + } + + has_more = PJ_FALSE; + frm_enc[enc_cnt].buf = enc_buf[enc_cnt]; + frm_enc[enc_cnt].size = MTU; + + status = pjmedia_vid_codec_encode_more(codec, MTU, + &frm_enc[enc_cnt], + &has_more); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(THIS_FILE, status, "Codec encode error")); + goto on_exit; + } + + if (frm_enc[enc_cnt].size) { + if (f264) { + fwrite(start_nal, 1, sizeof(start_nal), f264); + fwrite(frm_enc[enc_cnt].buf, 1, frm_enc[enc_cnt].size, + f264); + } + ++pkt_cnt; + ++enc_cnt; + } + } + + if (enc_cnt) { + frm_yuv.buf = yuv_frame; + frm_yuv.size = YUV_BUF_SIZE; + status = pjmedia_vid_codec_decode(codec, enc_cnt, + frm_enc, + YUV_BUF_SIZE, + &frm_yuv); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(THIS_FILE, status, "Codec decode error")); + goto on_exit; + } + + if (frm_yuv.size != 0) { + ++dec_cnt; + } + } } printf("Done.\n" - " Read YUV frames: %d\n" - " Encoded packets: %d\n" - " Decoded YUV frames: %d\n", - read_cnt, pkt_cnt, dec_cnt); + " Read YUV frames: %d\n" + " Encoded packets: %d\n" + " Decoded YUV frames: %d\n", + read_cnt, pkt_cnt, dec_cnt); /* Start deinitialization: */ on_exit: if (codec) { - pjmedia_vid_codec_close(codec); - pjmedia_vid_codec_mgr_dealloc_codec(NULL, codec); + pjmedia_vid_codec_close(codec); + pjmedia_vid_codec_mgr_dealloc_codec(NULL, codec); } if (f264) - fclose(f264); + fclose(f264); if (fyuv) - fclose(fyuv); + fclose(fyuv); /* Deinit codecs */ deinit_codecs(); @@ -524,7 +523,7 @@ int main(int argc, char *argv[]) PJ_UNUSED_ARG(argc); PJ_UNUSED_ARG(argv); puts("Error: this sample requires video capability " - "(PJMEDIA_HAS_VIDEO == 1)"); + "(PJMEDIA_HAS_VIDEO == 1)"); return -1; } diff --git a/pjsip-apps/src/samples/vid_streamutil.c b/pjsip-apps/src/samples/vid_streamutil.c index 06959ee8a9..e01c1c7769 100644 --- a/pjsip-apps/src/samples/vid_streamutil.c +++ b/pjsip-apps/src/samples/vid_streamutil.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011 Teluu Inc. (http://www.teluu.com) * @@ -39,7 +38,7 @@ #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) -#include /* atoi() */ +#include /* atoi() */ #include #include "util.h" @@ -49,8 +48,8 @@ static const char *desc = " vid_streamutil \n" "\n" " PURPOSE: \n" - " Demonstrate how to use pjmedia video stream component to \n" - " transmit/receive RTP packets to/from video device/file. \n" + " Demonstrate how to use pjmedia video stream component to \n" + " transmit/receive RTP packets to/from video device/file. \n" "\n" "\n" " USAGE: \n" @@ -90,7 +89,7 @@ static const char *desc = "\n" ; -#define THIS_FILE "vid_streamutil.c" +#define THIS_FILE "vid_streamutil.c" /* If set, local renderer will be created to play original file */ @@ -100,8 +99,8 @@ static const char *desc = /* Default width and height for the renderer, better be set to maximum * acceptable size. */ -#define DEF_RENDERER_WIDTH 640 -#define DEF_RENDERER_HEIGHT 480 +#define DEF_RENDERER_WIDTH 640 +#define DEF_RENDERER_HEIGHT 480 /* Hexa string to octet array */ @@ -109,12 +108,12 @@ int my_hex_string_to_octet_string(char *raw, char *hex, int len) { int i; for (i = 0; i < len; i+=2) { - int tmp; - if (i+1 >= len || !pj_isxdigit(hex[i]) || !pj_isxdigit(hex[i+1])) - return i; - tmp = pj_hex_digit_to_val((unsigned char)hex[i]) << 4; - tmp |= pj_hex_digit_to_val((unsigned char)hex[i+1]); - raw[i/2] = (char)(tmp & 0xFF); + int tmp; + if (i+1 >= len || !pj_isxdigit(hex[i]) || !pj_isxdigit(hex[i+1])) + return i; + tmp = pj_hex_digit_to_val((unsigned char)hex[i]) << 4; + tmp |= pj_hex_digit_to_val((unsigned char)hex[i+1]); + raw[i/2] = (char)(tmp & 0xFF); } return len; } @@ -128,7 +127,7 @@ static pj_status_t init_codecs(pj_pool_factory *pf) /* To suppress warning about unused var when all codecs are disabled */ PJ_UNUSED_ARG(status); - PJ_UNUSED_ARG(pf); + PJ_UNUSED_ARG(pf); #if defined(PJMEDIA_HAS_OPENH264_CODEC) && PJMEDIA_HAS_OPENH264_CODEC != 0 status = pjmedia_codec_openh264_vid_init(NULL, pf); @@ -179,8 +178,8 @@ static void deinit_codecs() } static pj_status_t create_file_player( pj_pool_t *pool, - const char *file_name, - pjmedia_port **p_play_port) + const char *file_name, + pjmedia_port **p_play_port) { pjmedia_avi_streams *avi_streams; pjmedia_avi_stream *vid_stream; @@ -189,13 +188,13 @@ static pj_status_t create_file_player( pj_pool_t *pool, status = pjmedia_avi_player_create_streams(pool, file_name, 0, &avi_streams); if (status != PJ_SUCCESS) - return status; + return status; vid_stream = pjmedia_avi_streams_get_stream_by_media(avi_streams, 0, PJMEDIA_TYPE_VIDEO); if (!vid_stream) - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; play_port = pjmedia_avi_stream_get_port(vid_stream); pj_assert(play_port); @@ -209,21 +208,21 @@ static pj_status_t create_file_player( pj_pool_t *pool, * Create stream based on the codec, dir, remote address, etc. */ static pj_status_t create_stream( pj_pool_t *pool, - pjmedia_endpt *med_endpt, - const pjmedia_vid_codec_info *codec_info, + pjmedia_endpt *med_endpt, + const pjmedia_vid_codec_info *codec_info, pjmedia_vid_codec_param *codec_param, - pjmedia_dir dir, - pj_int8_t rx_pt, - pj_int8_t tx_pt, - pj_uint16_t local_port, - const pj_sockaddr_in *rem_addr, + pjmedia_dir dir, + pj_int8_t rx_pt, + pj_int8_t tx_pt, + pj_uint16_t local_port, + const pj_sockaddr_in *rem_addr, #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - pj_bool_t use_srtp, - const pj_str_t *crypto_suite, - const pj_str_t *srtp_tx_key, - const pj_str_t *srtp_rx_key, + pj_bool_t use_srtp, + const pj_str_t *crypto_suite, + const pj_str_t *srtp_tx_key, + const pj_str_t *srtp_rx_key, #endif - pjmedia_vid_stream **p_stream ) + pjmedia_vid_stream **p_stream ) { pjmedia_vid_stream_info info; pjmedia_transport *transport = NULL; @@ -252,39 +251,39 @@ static pj_status_t create_stream( pj_pool_t *pool, * (otherwise stream will assert). */ if (info.rem_addr.addr.sa_family == 0) { - const pj_str_t addr = pj_str("127.0.0.1"); - pj_sockaddr_in_init(&info.rem_addr.ipv4, &addr, 0); + const pj_str_t addr = pj_str("127.0.0.1"); + pj_sockaddr_in_init(&info.rem_addr.ipv4, &addr, 0); } /* Create media transport */ status = pjmedia_transport_udp_create(med_endpt, NULL, local_port, - 0, &transport); + 0, &transport); if (status != PJ_SUCCESS) - return status; + return status; #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) /* Check if SRTP enabled */ if (use_srtp) { - pjmedia_srtp_crypto tx_plc, rx_plc; - - status = pjmedia_transport_srtp_create(med_endpt, transport, - NULL, &srtp_tp); - if (status != PJ_SUCCESS) - return status; - - pj_bzero(&tx_plc, sizeof(pjmedia_srtp_crypto)); - pj_bzero(&rx_plc, sizeof(pjmedia_srtp_crypto)); - - tx_plc.key = *srtp_tx_key; - tx_plc.name = *crypto_suite; - rx_plc.key = *srtp_rx_key; - rx_plc.name = *crypto_suite; - - status = pjmedia_transport_srtp_start(srtp_tp, &tx_plc, &rx_plc); - if (status != PJ_SUCCESS) - return status; - - transport = srtp_tp; + pjmedia_srtp_crypto tx_plc, rx_plc; + + status = pjmedia_transport_srtp_create(med_endpt, transport, + NULL, &srtp_tp); + if (status != PJ_SUCCESS) + return status; + + pj_bzero(&tx_plc, sizeof(pjmedia_srtp_crypto)); + pj_bzero(&rx_plc, sizeof(pjmedia_srtp_crypto)); + + tx_plc.key = *srtp_tx_key; + tx_plc.name = *crypto_suite; + rx_plc.key = *srtp_rx_key; + rx_plc.name = *crypto_suite; + + status = pjmedia_transport_srtp_start(srtp_tp, &tx_plc, &rx_plc); + if (status != PJ_SUCCESS) + return status; + + transport = srtp_tp; } #endif @@ -293,13 +292,13 @@ static pj_status_t create_stream( pj_pool_t *pool, */ status = pjmedia_vid_stream_create( med_endpt, pool, &info, - transport, - NULL, p_stream); + transport, + NULL, p_stream); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error creating stream", status); - pjmedia_transport_close(transport); - return status; + app_perror(THIS_FILE, "Error creating stream", status); + pjmedia_transport_close(transport); + return status; } /* Start media transport */ @@ -338,22 +337,22 @@ static void clock_cb(const pj_timestamp *ts, void *user_data) /* Decode frame, if needed */ if (play_file->decoder) { - pjmedia_vid_codec *decoder = play_file->decoder; - - write_frame.buf = play_file->dec_buf; - write_frame.size = play_file->dec_buf_size; - status = pjmedia_vid_codec_decode(decoder, 1, &read_frame, - (unsigned)write_frame.size, - &write_frame); - if (status != PJ_SUCCESS) - return; + pjmedia_vid_codec *decoder = play_file->decoder; + + write_frame.buf = play_file->dec_buf; + write_frame.size = play_file->dec_buf_size; + status = pjmedia_vid_codec_decode(decoder, 1, &read_frame, + (unsigned)write_frame.size, + &write_frame); + if (status != PJ_SUCCESS) + return; } else { - write_frame = read_frame; + write_frame = read_frame; } /* Display frame locally */ if (play_file->renderer) - pjmedia_port_put_frame(play_file->renderer, &write_frame); + pjmedia_port_put_frame(play_file->renderer, &write_frame); /* Send frame */ pjmedia_port_put_frame(play_file->stream_port, &write_frame); @@ -392,7 +391,7 @@ static int main_func(int argc, char *argv[]) pj_str_t srtp_tx_key = {NULL, 0}; pj_str_t srtp_rx_key = {NULL, 0}; pj_str_t srtp_crypto_suite = {NULL, 0}; - int tmp_key_len; + int tmp_key_len; #endif /* Default values */ @@ -411,44 +410,44 @@ static int main_func(int argc, char *argv[]) pjmedia_clock *play_clock = NULL; enum { - OPT_CODEC = 'c', - OPT_LOCAL_PORT = 'p', - OPT_REMOTE = 'r', - OPT_PLAY_FILE = 'f', - OPT_SEND_RECV = 'b', - OPT_SEND_ONLY = 's', - OPT_RECV_ONLY = 'i', - OPT_SEND_WIDTH = 'W', - OPT_SEND_HEIGHT = 'H', - OPT_RECV_PT = 't', - OPT_SEND_PT = 'T', + OPT_CODEC = 'c', + OPT_LOCAL_PORT = 'p', + OPT_REMOTE = 'r', + OPT_PLAY_FILE = 'f', + OPT_SEND_RECV = 'b', + OPT_SEND_ONLY = 's', + OPT_RECV_ONLY = 'i', + OPT_SEND_WIDTH = 'W', + OPT_SEND_HEIGHT = 'H', + OPT_RECV_PT = 't', + OPT_SEND_PT = 'T', #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - OPT_USE_SRTP = 'S', + OPT_USE_SRTP = 'S', #endif - OPT_SRTP_TX_KEY = 'x', - OPT_SRTP_RX_KEY = 'y', - OPT_HELP = 'h', + OPT_SRTP_TX_KEY = 'x', + OPT_SRTP_RX_KEY = 'y', + OPT_HELP = 'h', }; struct pj_getopt_option long_options[] = { - { "codec", 1, 0, OPT_CODEC }, - { "local-port", 1, 0, OPT_LOCAL_PORT }, - { "remote", 1, 0, OPT_REMOTE }, - { "play-file", 1, 0, OPT_PLAY_FILE }, - { "send-recv", 0, 0, OPT_SEND_RECV }, - { "send-only", 0, 0, OPT_SEND_ONLY }, - { "recv-only", 0, 0, OPT_RECV_ONLY }, - { "send-width", 1, 0, OPT_SEND_WIDTH }, - { "send-height", 1, 0, OPT_SEND_HEIGHT }, - { "recv-pt", 1, 0, OPT_RECV_PT }, - { "send-pt", 1, 0, OPT_SEND_PT }, + { "codec", 1, 0, OPT_CODEC }, + { "local-port", 1, 0, OPT_LOCAL_PORT }, + { "remote", 1, 0, OPT_REMOTE }, + { "play-file", 1, 0, OPT_PLAY_FILE }, + { "send-recv", 0, 0, OPT_SEND_RECV }, + { "send-only", 0, 0, OPT_SEND_ONLY }, + { "recv-only", 0, 0, OPT_RECV_ONLY }, + { "send-width", 1, 0, OPT_SEND_WIDTH }, + { "send-height", 1, 0, OPT_SEND_HEIGHT }, + { "recv-pt", 1, 0, OPT_RECV_PT }, + { "send-pt", 1, 0, OPT_SEND_PT }, #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - { "use-srtp", 2, 0, OPT_USE_SRTP }, - { "srtp-tx-key", 1, 0, OPT_SRTP_TX_KEY }, - { "srtp-rx-key", 1, 0, OPT_SRTP_RX_KEY }, + { "use-srtp", 2, 0, OPT_USE_SRTP }, + { "srtp-tx-key", 1, 0, OPT_SRTP_TX_KEY }, + { "srtp-rx-key", 1, 0, OPT_SRTP_RX_KEY }, #endif - { "help", 0, 0, OPT_HELP }, - { NULL, 0, 0, 0 }, + { "help", 0, 0, OPT_HELP }, + { NULL, 0, 0, 0 }, }; int c; @@ -467,120 +466,120 @@ static int main_func(int argc, char *argv[]) pj_optind = 0; while((c=pj_getopt_long(argc,argv, "h", long_options, &option_index))!=-1) { - switch (c) { - case OPT_CODEC: - codec_id = pj_optarg; - break; - - case OPT_LOCAL_PORT: - local_port = (pj_uint16_t) atoi(pj_optarg); - if (local_port < 1) { - printf("Error: invalid local port %s\n", pj_optarg); - return 1; - } - break; - - case OPT_REMOTE: - { - pj_str_t ip = pj_str(strtok(pj_optarg, ":")); - pj_uint16_t port = (pj_uint16_t) atoi(strtok(NULL, ":")); - - status = pj_sockaddr_in_init(&remote_addr, &ip, port); - if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Invalid remote address", status); - return 1; - } - } - break; - - case OPT_PLAY_FILE: - play_file.file_name = pj_optarg; - break; - - case OPT_SEND_RECV: - dir = PJMEDIA_DIR_ENCODING_DECODING; - break; - - case OPT_SEND_ONLY: - dir = PJMEDIA_DIR_ENCODING; - break; - - case OPT_RECV_ONLY: - dir = PJMEDIA_DIR_DECODING; - break; - - case OPT_SEND_WIDTH: - tx_size.w = (unsigned)atoi(pj_optarg); - break; - - case OPT_SEND_HEIGHT: - tx_size.h = (unsigned)atoi(pj_optarg); - break; - - case OPT_RECV_PT: - rx_pt = (pj_int8_t)atoi(pj_optarg); - break; - - case OPT_SEND_PT: - tx_pt = (pj_int8_t)atoi(pj_optarg); - break; + switch (c) { + case OPT_CODEC: + codec_id = pj_optarg; + break; + + case OPT_LOCAL_PORT: + local_port = (pj_uint16_t) atoi(pj_optarg); + if (local_port < 1) { + printf("Error: invalid local port %s\n", pj_optarg); + return 1; + } + break; + + case OPT_REMOTE: + { + pj_str_t ip = pj_str(strtok(pj_optarg, ":")); + pj_uint16_t port = (pj_uint16_t) atoi(strtok(NULL, ":")); + + status = pj_sockaddr_in_init(&remote_addr, &ip, port); + if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Invalid remote address", status); + return 1; + } + } + break; + + case OPT_PLAY_FILE: + play_file.file_name = pj_optarg; + break; + + case OPT_SEND_RECV: + dir = PJMEDIA_DIR_ENCODING_DECODING; + break; + + case OPT_SEND_ONLY: + dir = PJMEDIA_DIR_ENCODING; + break; + + case OPT_RECV_ONLY: + dir = PJMEDIA_DIR_DECODING; + break; + + case OPT_SEND_WIDTH: + tx_size.w = (unsigned)atoi(pj_optarg); + break; + + case OPT_SEND_HEIGHT: + tx_size.h = (unsigned)atoi(pj_optarg); + break; + + case OPT_RECV_PT: + rx_pt = (pj_int8_t)atoi(pj_optarg); + break; + + case OPT_SEND_PT: + tx_pt = (pj_int8_t)atoi(pj_optarg); + break; #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - case OPT_USE_SRTP: - use_srtp = PJ_TRUE; - if (pj_optarg) { - pj_strset(&srtp_crypto_suite, pj_optarg, strlen(pj_optarg)); - } else { - srtp_crypto_suite = pj_str("AES_CM_128_HMAC_SHA1_80"); - } - break; - - case OPT_SRTP_TX_KEY: - tmp_key_len = my_hex_string_to_octet_string(tmp_tx_key, pj_optarg, - (int)strlen(pj_optarg)); - pj_strset(&srtp_tx_key, tmp_tx_key, tmp_key_len/2); - break; - - case OPT_SRTP_RX_KEY: - tmp_key_len = my_hex_string_to_octet_string(tmp_rx_key, pj_optarg, - (int)strlen(pj_optarg)); - pj_strset(&srtp_rx_key, tmp_rx_key, tmp_key_len/2); - break; + case OPT_USE_SRTP: + use_srtp = PJ_TRUE; + if (pj_optarg) { + pj_strset(&srtp_crypto_suite, pj_optarg, strlen(pj_optarg)); + } else { + srtp_crypto_suite = pj_str("AES_CM_128_HMAC_SHA1_80"); + } + break; + + case OPT_SRTP_TX_KEY: + tmp_key_len = my_hex_string_to_octet_string(tmp_tx_key, pj_optarg, + (int)strlen(pj_optarg)); + pj_strset(&srtp_tx_key, tmp_tx_key, tmp_key_len/2); + break; + + case OPT_SRTP_RX_KEY: + tmp_key_len = my_hex_string_to_octet_string(tmp_rx_key, pj_optarg, + (int)strlen(pj_optarg)); + pj_strset(&srtp_rx_key, tmp_rx_key, tmp_key_len/2); + break; #endif - case OPT_HELP: - usage(); - return 1; + case OPT_HELP: + usage(); + return 1; - default: - printf("Invalid options %s\n", argv[pj_optind]); - return 1; - } + default: + printf("Invalid options %s\n", argv[pj_optind]); + return 1; + } } /* Verify arguments. */ if (dir & PJMEDIA_DIR_ENCODING) { - if (remote_addr.sin_addr.s_addr == 0) { - printf("Error: remote address must be set\n"); - return 1; - } + if (remote_addr.sin_addr.s_addr == 0) { + printf("Error: remote address must be set\n"); + return 1; + } } if (play_file.file_name != NULL && dir != PJMEDIA_DIR_ENCODING) { - printf("Direction is set to --send-only because of --play-file\n"); - dir = PJMEDIA_DIR_ENCODING; + printf("Direction is set to --send-only because of --play-file\n"); + dir = PJMEDIA_DIR_ENCODING; } #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) /* SRTP validation */ if (use_srtp) { - if (!srtp_tx_key.slen || !srtp_rx_key.slen) - { - printf("Error: Key for each SRTP stream direction must be set\n"); - return 1; - } + if (!srtp_tx_key.slen || !srtp_rx_key.slen) + { + printf("Error: Key for each SRTP stream direction must be set\n"); + return 1; + } } #endif @@ -595,12 +594,12 @@ static int main_func(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool for application purpose */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "app", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "app", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); /* Init video format manager */ pjmedia_video_format_mgr_create(pool, 64, 0, NULL); @@ -624,28 +623,28 @@ static int main_func(int argc, char *argv[]) /* Find which codec to use. */ if (codec_id) { - unsigned count = 1; - pj_str_t str_codec_id = pj_str(codec_id); + unsigned count = 1; + pj_str_t str_codec_id = pj_str(codec_id); status = pjmedia_vid_codec_mgr_find_codecs_by_id(NULL, - &str_codec_id, &count, - &codec_info, NULL); - if (status != PJ_SUCCESS) { - printf("Error: unable to find codec %s\n", codec_id); - return 1; - } + &str_codec_id, &count, + &codec_info, NULL); + if (status != PJ_SUCCESS) { + printf("Error: unable to find codec %s\n", codec_id); + return 1; + } } else { static pjmedia_vid_codec_info info[1]; unsigned count = PJ_ARRAY_SIZE(info); - /* Default to first codec */ - pjmedia_vid_codec_mgr_enum_codecs(NULL, &count, info, NULL); + /* Default to first codec */ + pjmedia_vid_codec_mgr_enum_codecs(NULL, &count, info, NULL); codec_info = &info[0]; } /* Get codec default param for info */ status = pjmedia_vid_codec_mgr_get_default_param(NULL, codec_info, - &codec_param); + &codec_param); pj_assert(status == PJ_SUCCESS); /* Set outgoing video size */ @@ -655,95 +654,95 @@ static int main_func(int argc, char *argv[]) #if DEF_RENDERER_WIDTH && DEF_RENDERER_HEIGHT /* Set incoming video size */ if (DEF_RENDERER_WIDTH > codec_param.dec_fmt.det.vid.size.w) - codec_param.dec_fmt.det.vid.size.w = DEF_RENDERER_WIDTH; + codec_param.dec_fmt.det.vid.size.w = DEF_RENDERER_WIDTH; if (DEF_RENDERER_HEIGHT > codec_param.dec_fmt.det.vid.size.h) - codec_param.dec_fmt.det.vid.size.h = DEF_RENDERER_HEIGHT; + codec_param.dec_fmt.det.vid.size.h = DEF_RENDERER_HEIGHT; #endif if (play_file.file_name) { - pjmedia_video_format_detail *file_vfd; + pjmedia_video_format_detail *file_vfd; pjmedia_clock_param clock_param; char fmt_name[5]; - /* Create file player */ - status = create_file_player(pool, play_file.file_name, &play_port); - if (status != PJ_SUCCESS) - goto on_exit; - - /* Collect format info */ - file_vfd = pjmedia_format_get_video_format_detail(&play_port->info.fmt, - PJ_TRUE); - PJ_LOG(2, (THIS_FILE, "Reading video stream %dx%d %s @%.2ffps", - file_vfd->size.w, file_vfd->size.h, - pjmedia_fourcc_name(play_port->info.fmt.id, fmt_name), - (1.0*file_vfd->fps.num/file_vfd->fps.denum))); - - /* Allocate file read buffer */ - play_file.read_buf_size = PJMEDIA_MAX_VIDEO_ENC_FRAME_SIZE; - play_file.read_buf = pj_pool_zalloc(pool, play_file.read_buf_size); - - /* Create decoder, if the file and the stream uses different codec */ - if (codec_info->fmt_id != (pjmedia_format_id)play_port->info.fmt.id) { - const pjmedia_video_format_info *dec_vfi; - pjmedia_video_apply_fmt_param dec_vafp = {0}; - const pjmedia_vid_codec_info *codec_info2; - pjmedia_vid_codec_param codec_param2; - - /* Find decoder */ - status = pjmedia_vid_codec_mgr_get_codec_info2(NULL, - play_port->info.fmt.id, - &codec_info2); - if (status != PJ_SUCCESS) - goto on_exit; - - /* Init decoder */ - status = pjmedia_vid_codec_mgr_alloc_codec(NULL, codec_info2, - &play_decoder); - if (status != PJ_SUCCESS) - goto on_exit; - - status = play_decoder->op->init(play_decoder, pool); - if (status != PJ_SUCCESS) - goto on_exit; - - /* Open decoder */ - status = pjmedia_vid_codec_mgr_get_default_param(NULL, codec_info2, - &codec_param2); - if (status != PJ_SUCCESS) - goto on_exit; - - codec_param2.dir = PJMEDIA_DIR_DECODING; - status = play_decoder->op->open(play_decoder, &codec_param2); - if (status != PJ_SUCCESS) - goto on_exit; - - /* Get decoder format info and apply param */ - dec_vfi = pjmedia_get_video_format_info(NULL, - codec_info2->dec_fmt_id[0]); - if (!dec_vfi || !dec_vfi->apply_fmt) { - status = PJ_ENOTSUP; - goto on_exit; - } - dec_vafp.size = file_vfd->size; - (*dec_vfi->apply_fmt)(dec_vfi, &dec_vafp); - - /* Allocate buffer to receive decoder output */ - play_file.dec_buf_size = dec_vafp.framebytes; - play_file.dec_buf = pj_pool_zalloc(pool, play_file.dec_buf_size); - } - - /* Create player clock */ + /* Create file player */ + status = create_file_player(pool, play_file.file_name, &play_port); + if (status != PJ_SUCCESS) + goto on_exit; + + /* Collect format info */ + file_vfd = pjmedia_format_get_video_format_detail(&play_port->info.fmt, + PJ_TRUE); + PJ_LOG(2, (THIS_FILE, "Reading video stream %dx%d %s @%.2ffps", + file_vfd->size.w, file_vfd->size.h, + pjmedia_fourcc_name(play_port->info.fmt.id, fmt_name), + (1.0*file_vfd->fps.num/file_vfd->fps.denum))); + + /* Allocate file read buffer */ + play_file.read_buf_size = PJMEDIA_MAX_VIDEO_ENC_FRAME_SIZE; + play_file.read_buf = pj_pool_zalloc(pool, play_file.read_buf_size); + + /* Create decoder, if the file and the stream uses different codec */ + if (codec_info->fmt_id != (pjmedia_format_id)play_port->info.fmt.id) { + const pjmedia_video_format_info *dec_vfi; + pjmedia_video_apply_fmt_param dec_vafp = {0}; + const pjmedia_vid_codec_info *codec_info2; + pjmedia_vid_codec_param codec_param2; + + /* Find decoder */ + status = pjmedia_vid_codec_mgr_get_codec_info2(NULL, + play_port->info.fmt.id, + &codec_info2); + if (status != PJ_SUCCESS) + goto on_exit; + + /* Init decoder */ + status = pjmedia_vid_codec_mgr_alloc_codec(NULL, codec_info2, + &play_decoder); + if (status != PJ_SUCCESS) + goto on_exit; + + status = play_decoder->op->init(play_decoder, pool); + if (status != PJ_SUCCESS) + goto on_exit; + + /* Open decoder */ + status = pjmedia_vid_codec_mgr_get_default_param(NULL, codec_info2, + &codec_param2); + if (status != PJ_SUCCESS) + goto on_exit; + + codec_param2.dir = PJMEDIA_DIR_DECODING; + status = play_decoder->op->open(play_decoder, &codec_param2); + if (status != PJ_SUCCESS) + goto on_exit; + + /* Get decoder format info and apply param */ + dec_vfi = pjmedia_get_video_format_info(NULL, + codec_info2->dec_fmt_id[0]); + if (!dec_vfi || !dec_vfi->apply_fmt) { + status = PJ_ENOTSUP; + goto on_exit; + } + dec_vafp.size = file_vfd->size; + (*dec_vfi->apply_fmt)(dec_vfi, &dec_vafp); + + /* Allocate buffer to receive decoder output */ + play_file.dec_buf_size = dec_vafp.framebytes; + play_file.dec_buf = pj_pool_zalloc(pool, play_file.dec_buf_size); + } + + /* Create player clock */ clock_param.usec_interval = PJMEDIA_PTIME(&file_vfd->fps); clock_param.clock_rate = codec_info->clock_rate; - status = pjmedia_clock_create2(pool, &clock_param, - PJMEDIA_CLOCK_NO_HIGHEST_PRIO, - &clock_cb, &play_file, &play_clock); - if (status != PJ_SUCCESS) - goto on_exit; + status = pjmedia_clock_create2(pool, &clock_param, + PJMEDIA_CLOCK_NO_HIGHEST_PRIO, + &clock_cb, &play_file, &play_clock); + if (status != PJ_SUCCESS) + goto on_exit; - /* Override stream codec param for encoding direction */ - codec_param.enc_fmt.det.vid.size = file_vfd->size; - codec_param.enc_fmt.det.vid.fps = file_vfd->fps; + /* Override stream codec param for encoding direction */ + codec_param.enc_fmt.det.vid.size = file_vfd->size; + codec_param.enc_fmt.det.vid.fps = file_vfd->fps; } else { pjmedia_vid_port_param_default(&vpp); @@ -751,44 +750,44 @@ static int main_func(int argc, char *argv[]) /* Set as active for all video devices */ vpp.active = PJ_TRUE; - /* Create video device port. */ + /* Create video device port. */ if (dir & PJMEDIA_DIR_ENCODING) { /* Create capture */ status = pjmedia_vid_dev_default_param( - pool, - PJMEDIA_VID_DEFAULT_CAPTURE_DEV, - &vpp.vidparam); + pool, + PJMEDIA_VID_DEFAULT_CAPTURE_DEV, + &vpp.vidparam); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; pjmedia_format_copy(&vpp.vidparam.fmt, &codec_param.enc_fmt); - vpp.vidparam.fmt.id = codec_param.dec_fmt.id; + vpp.vidparam.fmt.id = codec_param.dec_fmt.id; vpp.vidparam.dir = PJMEDIA_DIR_CAPTURE; status = pjmedia_vid_port_create(pool, &vpp, &capture); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; } - + if (dir & PJMEDIA_DIR_DECODING) { /* Create renderer */ status = pjmedia_vid_dev_default_param( - pool, - PJMEDIA_VID_DEFAULT_RENDER_DEV, - &vpp.vidparam); + pool, + PJMEDIA_VID_DEFAULT_RENDER_DEV, + &vpp.vidparam); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; pjmedia_format_copy(&vpp.vidparam.fmt, &codec_param.dec_fmt); vpp.vidparam.dir = PJMEDIA_DIR_RENDER; vpp.vidparam.disp_size = vpp.vidparam.fmt.det.vid.size; - vpp.vidparam.flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS; - vpp.vidparam.window_flags = PJMEDIA_VID_DEV_WND_BORDER | - PJMEDIA_VID_DEV_WND_RESIZABLE; + vpp.vidparam.flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS; + vpp.vidparam.window_flags = PJMEDIA_VID_DEV_WND_BORDER | + PJMEDIA_VID_DEV_WND_RESIZABLE; status = pjmedia_vid_port_create(pool, &vpp, &renderer); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; } } @@ -799,20 +798,20 @@ static int main_func(int argc, char *argv[]) status = create_stream(pool, med_endpt, codec_info, &codec_param, dir, rx_pt, tx_pt, local_port, &remote_addr, #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - use_srtp, &srtp_crypto_suite, - &srtp_tx_key, &srtp_rx_key, + use_srtp, &srtp_crypto_suite, + &srtp_tx_key, &srtp_rx_key, #endif - &stream); + &stream); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; /* Get the port interface of the stream */ status = pjmedia_vid_stream_get_port(stream, PJMEDIA_DIR_ENCODING, - &enc_port); + &enc_port); PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); status = pjmedia_vid_stream_get_port(stream, PJMEDIA_DIR_DECODING, - &dec_port); + &dec_port); PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Start streaming */ @@ -824,7 +823,7 @@ static int main_func(int argc, char *argv[]) if (renderer) { status = pjmedia_vid_port_connect(renderer, dec_port, PJ_FALSE); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; status = pjmedia_vid_port_start(renderer); if (status != PJ_SUCCESS) goto on_exit; @@ -834,7 +833,7 @@ static int main_func(int argc, char *argv[]) if (capture) { status = pjmedia_vid_port_connect(capture, enc_port, PJ_FALSE); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; status = pjmedia_vid_port_start(capture); if (status != PJ_SUCCESS) goto on_exit; @@ -848,86 +847,86 @@ static int main_func(int argc, char *argv[]) pjmedia_vid_port_param_default(&vpp); vpp.active = PJ_FALSE; status = pjmedia_vid_dev_default_param( - pool, - PJMEDIA_VID_DEFAULT_RENDER_DEV, - &vpp.vidparam); + pool, + PJMEDIA_VID_DEFAULT_RENDER_DEV, + &vpp.vidparam); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; vpp.vidparam.dir = PJMEDIA_DIR_RENDER; pjmedia_format_copy(&vpp.vidparam.fmt, &codec_param.dec_fmt); - vpp.vidparam.fmt.det.vid.size = play_port->info.fmt.det.vid.size; - vpp.vidparam.fmt.det.vid.fps = play_port->info.fmt.det.vid.fps; + vpp.vidparam.fmt.det.vid.size = play_port->info.fmt.det.vid.size; + vpp.vidparam.fmt.det.vid.fps = play_port->info.fmt.det.vid.fps; vpp.vidparam.disp_size = vpp.vidparam.fmt.det.vid.size; - vpp.vidparam.flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS; - vpp.vidparam.window_flags = PJMEDIA_VID_DEV_WND_BORDER | - PJMEDIA_VID_DEV_WND_RESIZABLE; + vpp.vidparam.flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS; + vpp.vidparam.window_flags = PJMEDIA_VID_DEV_WND_BORDER | + PJMEDIA_VID_DEV_WND_RESIZABLE; - status = pjmedia_vid_port_create(pool, &vpp, &renderer); + status = pjmedia_vid_port_create(pool, &vpp, &renderer); if (status != PJ_SUCCESS) - goto on_exit; + goto on_exit; status = pjmedia_vid_port_start(renderer); if (status != PJ_SUCCESS) goto on_exit; #endif - /* Init play file data */ - play_file.play_port = play_port; - play_file.stream_port = enc_port; - play_file.decoder = play_decoder; - if (renderer) { - play_file.renderer = pjmedia_vid_port_get_passive_port(renderer); - } - - status = pjmedia_clock_start(play_clock); - if (status != PJ_SUCCESS) - goto on_exit; + /* Init play file data */ + play_file.play_port = play_port; + play_file.stream_port = enc_port; + play_file.decoder = play_decoder; + if (renderer) { + play_file.renderer = pjmedia_vid_port_get_passive_port(renderer); + } + + status = pjmedia_clock_start(play_clock); + if (status != PJ_SUCCESS) + goto on_exit; } /* Done */ if (dir == PJMEDIA_DIR_DECODING) - printf("Stream is active, dir is recv-only, local port is %d\n", - local_port); + printf("Stream is active, dir is recv-only, local port is %d\n", + local_port); else if (dir == PJMEDIA_DIR_ENCODING) - printf("Stream is active, dir is send-only, sending to %s:%d\n", + printf("Stream is active, dir is send-only, sending to %s:%d\n", pj_inet_ntop2(pj_AF_INET(), &remote_addr.sin_addr, addr, - sizeof(addr)), - pj_ntohs(remote_addr.sin_port)); + sizeof(addr)), + pj_ntohs(remote_addr.sin_port)); else - printf("Stream is active, send/recv, local port is %d, " - "sending to %s:%d\n", - local_port, - pj_inet_ntop2(pj_AF_INET(), &remote_addr.sin_addr, addr, - sizeof(addr)), - pj_ntohs(remote_addr.sin_port)); + printf("Stream is active, send/recv, local port is %d, " + "sending to %s:%d\n", + local_port, + pj_inet_ntop2(pj_AF_INET(), &remote_addr.sin_addr, addr, + sizeof(addr)), + pj_ntohs(remote_addr.sin_port)); if (dir & PJMEDIA_DIR_ENCODING) - PJ_LOG(2, (THIS_FILE, "Sending %dx%d %.*s @%.2ffps", - codec_param.enc_fmt.det.vid.size.w, - codec_param.enc_fmt.det.vid.size.h, - codec_info->encoding_name.slen, - codec_info->encoding_name.ptr, - (1.0*codec_param.enc_fmt.det.vid.fps.num/ - codec_param.enc_fmt.det.vid.fps.denum))); + PJ_LOG(2, (THIS_FILE, "Sending %dx%d %.*s @%.2ffps", + codec_param.enc_fmt.det.vid.size.w, + codec_param.enc_fmt.det.vid.size.h, + codec_info->encoding_name.slen, + codec_info->encoding_name.ptr, + (1.0*codec_param.enc_fmt.det.vid.fps.num/ + codec_param.enc_fmt.det.vid.fps.denum))); for (;;) { - char tmp[10]; + char tmp[10]; - puts(""); - puts("Commands:"); - puts(" q Quit"); - puts(""); + puts(""); + puts("Commands:"); + puts(" q Quit"); + puts(""); - printf("Command: "); fflush(stdout); + printf("Command: "); fflush(stdout); - if (fgets(tmp, sizeof(tmp), stdin) == NULL) { - puts("EOF while reading stdin, will quit now.."); - break; - } + if (fgets(tmp, sizeof(tmp), stdin) == NULL) { + puts("EOF while reading stdin, will quit now.."); + break; + } - if (tmp[0] == 'q') - break; + if (tmp[0] == 'q') + break; } @@ -944,35 +943,35 @@ static int main_func(int argc, char *argv[]) /* Stop and destroy file clock */ if (play_clock) { - pjmedia_clock_stop(play_clock); - pjmedia_clock_destroy(play_clock); + pjmedia_clock_stop(play_clock); + pjmedia_clock_destroy(play_clock); } /* Destroy file reader/player */ if (play_port) - pjmedia_port_destroy(play_port); + pjmedia_port_destroy(play_port); /* Destroy file decoder */ if (play_decoder) { - play_decoder->op->close(play_decoder); - pjmedia_vid_codec_mgr_dealloc_codec(NULL, play_decoder); + play_decoder->op->close(play_decoder); + pjmedia_vid_codec_mgr_dealloc_codec(NULL, play_decoder); } /* Destroy video devices */ if (capture) - pjmedia_vid_port_destroy(capture); + pjmedia_vid_port_destroy(capture); if (renderer) - pjmedia_vid_port_destroy(renderer); + pjmedia_vid_port_destroy(renderer); /* Destroy stream */ if (stream) { - pjmedia_transport *tp; + pjmedia_transport *tp; - tp = pjmedia_vid_stream_get_transport(stream); - pjmedia_vid_stream_destroy(stream); - - pjmedia_transport_media_stop(tp); - pjmedia_transport_close(tp); + tp = pjmedia_vid_stream_get_transport(stream); + pjmedia_vid_stream_destroy(stream); + + pjmedia_transport_media_stop(tp); + pjmedia_transport_close(tp); } /* Deinit codecs */ diff --git a/pjsip-apps/src/swig/importsym.py b/pjsip-apps/src/swig/importsym.py index c64ed471ec..6f549b6bcb 100644 --- a/pjsip-apps/src/swig/importsym.py +++ b/pjsip-apps/src/swig/importsym.py @@ -1,4 +1,3 @@ -# $Id$ # # importsym.py: Import C symbol decls (structs, enums, etc) and write them # to another file diff --git a/pjsip-apps/src/swig/java/android/app/src/main/java/org/pjsip/pjsua2/app/CallActivity.java b/pjsip-apps/src/swig/java/android/app/src/main/java/org/pjsip/pjsua2/app/CallActivity.java index e8a666d4f3..4ac476011a 100644 --- a/pjsip-apps/src/swig/java/android/app/src/main/java/org/pjsip/pjsua2/app/CallActivity.java +++ b/pjsip-apps/src/swig/java/android/app/src/main/java/org/pjsip/pjsua2/app/CallActivity.java @@ -41,60 +41,60 @@ class VideoPreviewHandler implements SurfaceHolder.Callback public void updateVideoPreview(SurfaceHolder holder) { - if (MainActivity.currentCall != null && - MainActivity.currentCall.vidWin != null && - MainActivity.currentCall.vidPrev != null) - { - if (videoPreviewActive) { - VideoWindowHandle vidWH = new VideoWindowHandle(); - vidWH.getHandle().setWindow(holder.getSurface()); - VideoPreviewOpParam vidPrevParam = new VideoPreviewOpParam(); - vidPrevParam.setWindow(vidWH); - try { - MainActivity.currentCall.vidPrev.start(vidPrevParam); - } catch (Exception e) { - System.out.println(e); - } - } else { - try { - MainActivity.currentCall.vidPrev.stop(); - } catch (Exception e) { - System.out.println(e); - } - } - } + if (MainActivity.currentCall != null && + MainActivity.currentCall.vidWin != null && + MainActivity.currentCall.vidPrev != null) + { + if (videoPreviewActive) { + VideoWindowHandle vidWH = new VideoWindowHandle(); + vidWH.getHandle().setWindow(holder.getSurface()); + VideoPreviewOpParam vidPrevParam = new VideoPreviewOpParam(); + vidPrevParam.setWindow(vidWH); + try { + MainActivity.currentCall.vidPrev.start(vidPrevParam); + } catch (Exception e) { + System.out.println(e); + } + } else { + try { + MainActivity.currentCall.vidPrev.stop(); + } catch (Exception e) { + System.out.println(e); + } + } + } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { - updateVideoPreview(holder); + updateVideoPreview(holder); } @Override public void surfaceCreated(SurfaceHolder holder) { - + } @Override public void surfaceDestroyed(SurfaceHolder holder) { - try { - MainActivity.currentCall.vidPrev.stop(); - } catch (Exception e) { - System.out.println(e); - } + try { + MainActivity.currentCall.vidPrev.stop(); + } catch (Exception e) { + System.out.println(e); + } } } public class CallActivity extends Activity - implements Handler.Callback, SurfaceHolder.Callback + implements Handler.Callback, SurfaceHolder.Callback { public static Handler handler_; private static VideoPreviewHandler previewHandler = - new VideoPreviewHandler(); + new VideoPreviewHandler(); private final Handler handler = new Handler(this); private static CallInfo lastCallInfo; @@ -102,37 +102,37 @@ public class CallActivity extends Activity @Override protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_call); - - SurfaceView surfaceInVideo = (SurfaceView) - findViewById(R.id.surfaceIncomingVideo); - SurfaceView surfacePreview = (SurfaceView) - findViewById(R.id.surfacePreviewCapture); - Button buttonShowPreview = (Button) - findViewById(R.id.buttonShowPreview); - - if (MainActivity.currentCall == null || - MainActivity.currentCall.vidWin == null) - { - surfaceInVideo.setVisibility(View.GONE); - buttonShowPreview.setVisibility(View.GONE); - } - setupVideoPreview(surfacePreview, buttonShowPreview); - surfaceInVideo.getHolder().addCallback(this); - surfacePreview.getHolder().addCallback(previewHandler); - - handler_ = handler; - if (MainActivity.currentCall != null) { - try { - lastCallInfo = MainActivity.currentCall.getInfo(); - updateCallState(lastCallInfo); - } catch (Exception e) { - System.out.println(e); - } - } else { - updateCallState(lastCallInfo); - } + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_call); + + SurfaceView surfaceInVideo = (SurfaceView) + findViewById(R.id.surfaceIncomingVideo); + SurfaceView surfacePreview = (SurfaceView) + findViewById(R.id.surfacePreviewCapture); + Button buttonShowPreview = (Button) + findViewById(R.id.buttonShowPreview); + + if (MainActivity.currentCall == null || + MainActivity.currentCall.vidWin == null) + { + surfaceInVideo.setVisibility(View.GONE); + buttonShowPreview.setVisibility(View.GONE); + } + setupVideoPreview(surfacePreview, buttonShowPreview); + surfaceInVideo.getHolder().addCallback(this); + surfacePreview.getHolder().addCallback(previewHandler); + + handler_ = handler; + if (MainActivity.currentCall != null) { + try { + lastCallInfo = MainActivity.currentCall.getInfo(); + updateCallState(lastCallInfo); + } catch (Exception e) { + System.out.println(e); + } + } else { + updateCallState(lastCallInfo); + } } @Override @@ -168,12 +168,12 @@ public void onConfigurationChanged(Configuration newConfig) { if (MyApp.ep != null && MainActivity.account != null) { try { - AccountConfig cfg = MainActivity.account.cfg; - int cap_dev = cfg.getVideoConfig().getDefaultCaptureDevice(); - MyApp.ep.vidDevManager().setCaptureOrient(cap_dev, orient, - true); + AccountConfig cfg = MainActivity.account.cfg; + int cap_dev = cfg.getVideoConfig().getDefaultCaptureDevice(); + MyApp.ep.vidDevManager().setCaptureOrient(cap_dev, orient, + true); } catch (Exception e) { - System.out.println(e); + System.out.println(e); } } } @@ -181,37 +181,37 @@ public void onConfigurationChanged(Configuration newConfig) { @Override protected void onDestroy() { - super.onDestroy(); - handler_ = null; + super.onDestroy(); + handler_ = null; } private void updateVideoWindow(boolean show) { - if (MainActivity.currentCall != null && - MainActivity.currentCall.vidWin != null && - MainActivity.currentCall.vidPrev != null) - { - SurfaceView surfaceInVideo = (SurfaceView) - findViewById(R.id.surfaceIncomingVideo); - - VideoWindowHandle vidWH = new VideoWindowHandle(); - if (show) { - vidWH.getHandle().setWindow( - surfaceInVideo.getHolder().getSurface()); - } else { - vidWH.getHandle().setWindow(null); - } - try { - MainActivity.currentCall.vidWin.setWindow(vidWH); - } catch (Exception e) { - System.out.println(e); - } - } + if (MainActivity.currentCall != null && + MainActivity.currentCall.vidWin != null && + MainActivity.currentCall.vidPrev != null) + { + SurfaceView surfaceInVideo = (SurfaceView) + findViewById(R.id.surfaceIncomingVideo); + + VideoWindowHandle vidWH = new VideoWindowHandle(); + if (show) { + vidWH.getHandle().setWindow( + surfaceInVideo.getHolder().getSurface()); + } else { + vidWH.getHandle().setWindow(null); + } + try { + MainActivity.currentCall.vidWin.setWindow(vidWH); + } catch (Exception e) { + System.out.println(e); + } + } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { - updateVideoWindow(true); + updateVideoWindow(true); } public void surfaceCreated(SurfaceHolder holder) @@ -220,152 +220,152 @@ public void surfaceCreated(SurfaceHolder holder) public void surfaceDestroyed(SurfaceHolder holder) { - updateVideoWindow(false); + updateVideoWindow(false); } public void acceptCall(View view) { - CallOpParam prm = new CallOpParam(); - prm.setStatusCode(pjsip_status_code.PJSIP_SC_OK); - try { - MainActivity.currentCall.answer(prm); - } catch (Exception e) { - System.out.println(e); - } - - view.setVisibility(View.GONE); + CallOpParam prm = new CallOpParam(); + prm.setStatusCode(pjsip_status_code.PJSIP_SC_OK); + try { + MainActivity.currentCall.answer(prm); + } catch (Exception e) { + System.out.println(e); + } + + view.setVisibility(View.GONE); } public void hangupCall(View view) { - handler_ = null; - finish(); - - if (MainActivity.currentCall != null) { - CallOpParam prm = new CallOpParam(); - prm.setStatusCode(pjsip_status_code.PJSIP_SC_DECLINE); - try { - MainActivity.currentCall.hangup(prm); - } catch (Exception e) { - System.out.println(e); - } - } + handler_ = null; + finish(); + + if (MainActivity.currentCall != null) { + CallOpParam prm = new CallOpParam(); + prm.setStatusCode(pjsip_status_code.PJSIP_SC_DECLINE); + try { + MainActivity.currentCall.hangup(prm); + } catch (Exception e) { + System.out.println(e); + } + } } public void setupVideoPreview(SurfaceView surfacePreview, - Button buttonShowPreview) + Button buttonShowPreview) { - surfacePreview.setVisibility(previewHandler.videoPreviewActive? - View.VISIBLE:View.GONE); - - buttonShowPreview.setText(previewHandler.videoPreviewActive? - getString(R.string.hide_preview): - getString(R.string.show_preview)); + surfacePreview.setVisibility(previewHandler.videoPreviewActive? + View.VISIBLE:View.GONE); + + buttonShowPreview.setText(previewHandler.videoPreviewActive? + getString(R.string.hide_preview): + getString(R.string.show_preview)); } public void showPreview(View view) { - SurfaceView surfacePreview = (SurfaceView) - findViewById(R.id.surfacePreviewCapture); - - Button buttonShowPreview = (Button) - findViewById(R.id.buttonShowPreview); - - - previewHandler.videoPreviewActive = !previewHandler.videoPreviewActive; - - setupVideoPreview(surfacePreview, buttonShowPreview); - - previewHandler.updateVideoPreview(surfacePreview.getHolder()); + SurfaceView surfacePreview = (SurfaceView) + findViewById(R.id.surfacePreviewCapture); + + Button buttonShowPreview = (Button) + findViewById(R.id.buttonShowPreview); + + + previewHandler.videoPreviewActive = !previewHandler.videoPreviewActive; + + setupVideoPreview(surfacePreview, buttonShowPreview); + + previewHandler.updateVideoPreview(surfacePreview.getHolder()); } private void setupVideoSurface() { - SurfaceView surfaceInVideo = (SurfaceView) - findViewById(R.id.surfaceIncomingVideo); - SurfaceView surfacePreview = (SurfaceView) - findViewById(R.id.surfacePreviewCapture); - Button buttonShowPreview = (Button) - findViewById(R.id.buttonShowPreview); - surfaceInVideo.setVisibility(View.VISIBLE); - buttonShowPreview.setVisibility(View.VISIBLE); - surfacePreview.setVisibility(View.GONE); + SurfaceView surfaceInVideo = (SurfaceView) + findViewById(R.id.surfaceIncomingVideo); + SurfaceView surfacePreview = (SurfaceView) + findViewById(R.id.surfacePreviewCapture); + Button buttonShowPreview = (Button) + findViewById(R.id.buttonShowPreview); + surfaceInVideo.setVisibility(View.VISIBLE); + buttonShowPreview.setVisibility(View.VISIBLE); + surfacePreview.setVisibility(View.GONE); } @Override public boolean handleMessage(Message m) { - if (m.what == MainActivity.MSG_TYPE.CALL_STATE) { + if (m.what == MainActivity.MSG_TYPE.CALL_STATE) { - lastCallInfo = (CallInfo) m.obj; - updateCallState(lastCallInfo); + lastCallInfo = (CallInfo) m.obj; + updateCallState(lastCallInfo); - } else if (m.what == MainActivity.MSG_TYPE.CALL_MEDIA_STATE) { + } else if (m.what == MainActivity.MSG_TYPE.CALL_MEDIA_STATE) { - if (MainActivity.currentCall.vidWin != null) { - /* Set capture orientation according to current - * device orientation. - */ - onConfigurationChanged(getResources().getConfiguration()); - /* If there's incoming video, display it. */ - setupVideoSurface(); - } + if (MainActivity.currentCall.vidWin != null) { + /* Set capture orientation according to current + * device orientation. + */ + onConfigurationChanged(getResources().getConfiguration()); + /* If there's incoming video, display it. */ + setupVideoSurface(); + } - } else { + } else { - /* Message not handled */ - return false; + /* Message not handled */ + return false; - } + } - return true; + return true; } private void updateCallState(CallInfo ci) { - TextView tvPeer = (TextView) findViewById(R.id.textViewPeer); - TextView tvState = (TextView) findViewById(R.id.textViewCallState); - Button buttonHangup = (Button) findViewById(R.id.buttonHangup); - Button buttonAccept = (Button) findViewById(R.id.buttonAccept); - String call_state = ""; + TextView tvPeer = (TextView) findViewById(R.id.textViewPeer); + TextView tvState = (TextView) findViewById(R.id.textViewCallState); + Button buttonHangup = (Button) findViewById(R.id.buttonHangup); + Button buttonAccept = (Button) findViewById(R.id.buttonAccept); + String call_state = ""; if (ci == null) { - buttonAccept.setVisibility(View.GONE); - buttonHangup.setText("OK"); - tvState.setText("Call disconnected"); - return; - } - - if (ci.getRole() == pjsip_role_e.PJSIP_ROLE_UAC) { - buttonAccept.setVisibility(View.GONE); - } - - if (ci.getState() < - pjsip_inv_state.PJSIP_INV_STATE_CONFIRMED) - { - if (ci.getRole() == pjsip_role_e.PJSIP_ROLE_UAS) { - call_state = "Incoming call.."; - /* Default button texts are already 'Accept' & 'Reject' */ - } else { - buttonHangup.setText("Cancel"); - call_state = ci.getStateText(); - } - } - else if (ci.getState() >= - pjsip_inv_state.PJSIP_INV_STATE_CONFIRMED) - { - buttonAccept.setVisibility(View.GONE); - call_state = ci.getStateText(); - if (ci.getState() == pjsip_inv_state.PJSIP_INV_STATE_CONFIRMED) { - buttonHangup.setText("Hangup"); - } else if (ci.getState() == - pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED) - { - buttonHangup.setText("OK"); - call_state = "Call disconnected: " + ci.getLastReason(); - } - } - - tvPeer.setText(ci.getRemoteUri()); - tvState.setText(call_state); + buttonAccept.setVisibility(View.GONE); + buttonHangup.setText("OK"); + tvState.setText("Call disconnected"); + return; + } + + if (ci.getRole() == pjsip_role_e.PJSIP_ROLE_UAC) { + buttonAccept.setVisibility(View.GONE); + } + + if (ci.getState() < + pjsip_inv_state.PJSIP_INV_STATE_CONFIRMED) + { + if (ci.getRole() == pjsip_role_e.PJSIP_ROLE_UAS) { + call_state = "Incoming call.."; + /* Default button texts are already 'Accept' & 'Reject' */ + } else { + buttonHangup.setText("Cancel"); + call_state = ci.getStateText(); + } + } + else if (ci.getState() >= + pjsip_inv_state.PJSIP_INV_STATE_CONFIRMED) + { + buttonAccept.setVisibility(View.GONE); + call_state = ci.getStateText(); + if (ci.getState() == pjsip_inv_state.PJSIP_INV_STATE_CONFIRMED) { + buttonHangup.setText("Hangup"); + } else if (ci.getState() == + pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED) + { + buttonHangup.setText("OK"); + call_state = "Call disconnected: " + ci.getLastReason(); + } + } + + tvPeer.setText(ci.getRemoteUri()); + tvState.setText(call_state); } } diff --git a/pjsip-apps/src/swig/java/android/app/src/main/java/org/pjsip/pjsua2/app/MainActivity.java b/pjsip-apps/src/swig/java/android/app/src/main/java/org/pjsip/pjsua2/app/MainActivity.java index 19fee09d6a..beef292c04 100644 --- a/pjsip-apps/src/swig/java/android/app/src/main/java/org/pjsip/pjsua2/app/MainActivity.java +++ b/pjsip-apps/src/swig/java/android/app/src/main/java/org/pjsip/pjsua2/app/MainActivity.java @@ -51,7 +51,7 @@ import org.pjsip.pjsua2.*; public class MainActivity extends Activity - implements Handler.Callback, MyAppObserver + implements Handler.Callback, MyAppObserver { public static MyApp app = null; public static MyCall currentCall = null; @@ -69,508 +69,508 @@ public class MainActivity extends Activity private final Handler handler = new Handler(this); public class MSG_TYPE { - public final static int INCOMING_CALL = 1; - public final static int CALL_STATE = 2; - public final static int REG_STATE = 3; - public final static int BUDDY_STATE = 4; - public final static int CALL_MEDIA_STATE = 5; - public final static int CHANGE_NETWORK = 6; + public final static int INCOMING_CALL = 1; + public final static int CALL_STATE = 2; + public final static int REG_STATE = 3; + public final static int BUDDY_STATE = 4; + public final static int CALL_MEDIA_STATE = 5; + public final static int CHANGE_NETWORK = 6; } private class MyBroadcastReceiver extends BroadcastReceiver { - private String conn_name = ""; - - @Override - public void onReceive(Context context, Intent intent) { - if (isNetworkChange(context)) - notifyChangeNetwork(); - } - - private boolean isNetworkChange(Context context) { - boolean network_changed = false; - ConnectivityManager connectivity_mgr = - ((ConnectivityManager)context.getSystemService( - Context.CONNECTIVITY_SERVICE)); - - NetworkInfo net_info = connectivity_mgr.getActiveNetworkInfo(); - if(net_info != null && net_info.isConnectedOrConnecting() && - !conn_name.equalsIgnoreCase("")) - { - String new_con = net_info.getExtraInfo(); - if (new_con != null && !new_con.equalsIgnoreCase(conn_name)) - network_changed = true; - - conn_name = (new_con == null)?"":new_con; - } else { - if (conn_name.equalsIgnoreCase("")) - conn_name = net_info.getExtraInfo(); - } - return network_changed; - } + private String conn_name = ""; + + @Override + public void onReceive(Context context, Intent intent) { + if (isNetworkChange(context)) + notifyChangeNetwork(); + } + + private boolean isNetworkChange(Context context) { + boolean network_changed = false; + ConnectivityManager connectivity_mgr = + ((ConnectivityManager)context.getSystemService( + Context.CONNECTIVITY_SERVICE)); + + NetworkInfo net_info = connectivity_mgr.getActiveNetworkInfo(); + if(net_info != null && net_info.isConnectedOrConnecting() && + !conn_name.equalsIgnoreCase("")) + { + String new_con = net_info.getExtraInfo(); + if (new_con != null && !new_con.equalsIgnoreCase(conn_name)) + network_changed = true; + + conn_name = (new_con == null)?"":new_con; + } else { + if (conn_name.equalsIgnoreCase("")) + conn_name = net_info.getExtraInfo(); + } + return network_changed; + } } private HashMap putData(String uri, String status) { - HashMap item = new HashMap(); - item.put("uri", uri); - item.put("status", status); - return item; + HashMap item = new HashMap(); + item.put("uri", uri); + item.put("status", status); + return item; } private void showCallActivity() { - Intent intent = new Intent(this, CallActivity.class); - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivity(intent); + Intent intent = new Intent(this, CallActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - CameraManager cm = (CameraManager)getSystemService(Context.CAMERA_SERVICE); - PjCameraInfo2.SetCameraManager(cm); - - if (app == null) { - app = new MyApp(); - // Wait for GDB to init, for native debugging only - if (false && - (getApplicationInfo().flags & - ApplicationInfo.FLAG_DEBUGGABLE) != 0) - { - try { - Thread.sleep(5000); - } catch (InterruptedException e) {} - } - - app.init(this, getFilesDir().getAbsolutePath()); - } - - if (app.accList.size() == 0) { - accCfg = new AccountConfig(); - accCfg.setIdUri("sip:localhost"); - accCfg.getNatConfig().setIceEnabled(true); - accCfg.getVideoConfig().setAutoTransmitOutgoing(true); - accCfg.getVideoConfig().setAutoShowIncoming(true); - account = app.addAcc(accCfg); - } else { - account = app.accList.get(0); - accCfg = account.cfg; - } - - buddyList = new ArrayList>(); - for (int i = 0; i < account.buddyList.size(); i++) { - buddyList.add(putData(account.buddyList.get(i).cfg.getUri(), - account.buddyList.get(i).getStatusText())); - } - - String[] from = { "uri", "status" }; - int[] to = { android.R.id.text1, android.R.id.text2 }; - buddyListAdapter = new SimpleAdapter( - this, buddyList, - android.R.layout.simple_list_item_2, - from, to); - - buddyListView = (ListView) findViewById(R.id.listViewBuddy);; - buddyListView.setAdapter(buddyListAdapter); - buddyListView.setOnItemClickListener( - new AdapterView.OnItemClickListener() - { - @Override - public void onItemClick(AdapterView parent, - final View view, - int position, long id) - { - view.setSelected(true); - buddyListSelectedIdx = position; - } - } - ); - if (receiver == null) { - receiver = new MyBroadcastReceiver(); - intentFilter = new IntentFilter( - ConnectivityManager.CONNECTIVITY_ACTION); - registerReceiver(receiver, intentFilter); - } + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + CameraManager cm = (CameraManager)getSystemService(Context.CAMERA_SERVICE); + PjCameraInfo2.SetCameraManager(cm); + + if (app == null) { + app = new MyApp(); + // Wait for GDB to init, for native debugging only + if (false && + (getApplicationInfo().flags & + ApplicationInfo.FLAG_DEBUGGABLE) != 0) + { + try { + Thread.sleep(5000); + } catch (InterruptedException e) {} + } + + app.init(this, getFilesDir().getAbsolutePath()); + } + + if (app.accList.size() == 0) { + accCfg = new AccountConfig(); + accCfg.setIdUri("sip:localhost"); + accCfg.getNatConfig().setIceEnabled(true); + accCfg.getVideoConfig().setAutoTransmitOutgoing(true); + accCfg.getVideoConfig().setAutoShowIncoming(true); + account = app.addAcc(accCfg); + } else { + account = app.accList.get(0); + accCfg = account.cfg; + } + + buddyList = new ArrayList>(); + for (int i = 0; i < account.buddyList.size(); i++) { + buddyList.add(putData(account.buddyList.get(i).cfg.getUri(), + account.buddyList.get(i).getStatusText())); + } + + String[] from = { "uri", "status" }; + int[] to = { android.R.id.text1, android.R.id.text2 }; + buddyListAdapter = new SimpleAdapter( + this, buddyList, + android.R.layout.simple_list_item_2, + from, to); + + buddyListView = (ListView) findViewById(R.id.listViewBuddy);; + buddyListView.setAdapter(buddyListAdapter); + buddyListView.setOnItemClickListener( + new AdapterView.OnItemClickListener() + { + @Override + public void onItemClick(AdapterView parent, + final View view, + int position, long id) + { + view.setSelected(true); + buddyListSelectedIdx = position; + } + } + ); + if (receiver == null) { + receiver = new MyBroadcastReceiver(); + intentFilter = new IntentFilter( + ConnectivityManager.CONNECTIVITY_ACTION); + registerReceiver(receiver, intentFilter); + } } @Override public boolean onCreateOptionsMenu(Menu menu) { - // Inflate the menu; this adds items to the action bar - // if it is present. - getMenuInflater().inflate(R.menu.main, menu); - return true; + // Inflate the menu; this adds items to the action bar + // if it is present. + getMenuInflater().inflate(R.menu.main, menu); + return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.action_acc_config: - dlgAccountSetting(); - break; + switch (item.getItemId()) { + case R.id.action_acc_config: + dlgAccountSetting(); + break; - case R.id.action_quit: - Message m = Message.obtain(handler, 0); - m.sendToTarget(); - break; + case R.id.action_quit: + Message m = Message.obtain(handler, 0); + m.sendToTarget(); + break; - default: - break; - } + default: + break; + } - return true; - } + return true; + } @Override public boolean handleMessage(Message m) { - if (m.what == 0) { - - app.deinit(); - finish(); - Runtime.getRuntime().gc(); - android.os.Process.killProcess(android.os.Process.myPid()); - - } else if (m.what == MSG_TYPE.CALL_STATE) { - - CallInfo ci = (CallInfo) m.obj; - - if (currentCall == null || ci == null || ci.getId() != currentCall.getId()) { - System.out.println("Call state event received, but call info is invalid"); - return true; - } - - /* Forward the call info to CallActivity */ - if (CallActivity.handler_ != null) { - Message m2 = Message.obtain(CallActivity.handler_, MSG_TYPE.CALL_STATE, ci); - m2.sendToTarget(); - } - - if (ci.getState() == pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED) - { - currentCall.delete(); - currentCall = null; - } - - } else if (m.what == MSG_TYPE.CALL_MEDIA_STATE) { - - /* Forward the message to CallActivity */ - if (CallActivity.handler_ != null) { - Message m2 = Message.obtain(CallActivity.handler_, - MSG_TYPE.CALL_MEDIA_STATE, - null); - m2.sendToTarget(); - } - - } else if (m.what == MSG_TYPE.BUDDY_STATE) { - - MyBuddy buddy = (MyBuddy) m.obj; - int idx = account.buddyList.indexOf(buddy); - - /* Update buddy status text, if buddy is valid and - * the buddy lists in account and UI are sync-ed. - */ - if (idx >= 0 && account.buddyList.size() == buddyList.size()) - { - buddyList.get(idx).put("status", buddy.getStatusText()); - buddyListAdapter.notifyDataSetChanged(); - // TODO: selection color/mark is gone after this, - // dont know how to return it back. - //buddyListView.setSelection(buddyListSelectedIdx); - //buddyListView.performItemClick(buddyListView, - // buddyListSelectedIdx, - // buddyListView. - // getItemIdAtPosition(buddyListSelectedIdx)); - - /* Return back Call activity */ - notifyCallState(currentCall); - } - - } else if (m.what == MSG_TYPE.REG_STATE) { - - String msg_str = (String) m.obj; - lastRegStatus = msg_str; - - } else if (m.what == MSG_TYPE.INCOMING_CALL) { - - /* Incoming call */ - final MyCall call = (MyCall) m.obj; - CallOpParam prm = new CallOpParam(); - - /* Only one call at anytime */ - if (currentCall != null) { - /* - prm.setStatusCode(pjsip_status_code.PJSIP_SC_BUSY_HERE); - try { - call.hangup(prm); - } catch (Exception e) {} - */ - // TODO: set status code - call.delete(); - return true; - } - - /* Answer with ringing */ - prm.setStatusCode(pjsip_status_code.PJSIP_SC_RINGING); - try { - call.answer(prm); - } catch (Exception e) {} - - currentCall = call; - showCallActivity(); - - } else if (m.what == MSG_TYPE.CHANGE_NETWORK) { - app.handleNetworkChange(); - } else { - - /* Message not handled */ - return false; - - } - - return true; + if (m.what == 0) { + + app.deinit(); + finish(); + Runtime.getRuntime().gc(); + android.os.Process.killProcess(android.os.Process.myPid()); + + } else if (m.what == MSG_TYPE.CALL_STATE) { + + CallInfo ci = (CallInfo) m.obj; + + if (currentCall == null || ci == null || ci.getId() != currentCall.getId()) { + System.out.println("Call state event received, but call info is invalid"); + return true; + } + + /* Forward the call info to CallActivity */ + if (CallActivity.handler_ != null) { + Message m2 = Message.obtain(CallActivity.handler_, MSG_TYPE.CALL_STATE, ci); + m2.sendToTarget(); + } + + if (ci.getState() == pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED) + { + currentCall.delete(); + currentCall = null; + } + + } else if (m.what == MSG_TYPE.CALL_MEDIA_STATE) { + + /* Forward the message to CallActivity */ + if (CallActivity.handler_ != null) { + Message m2 = Message.obtain(CallActivity.handler_, + MSG_TYPE.CALL_MEDIA_STATE, + null); + m2.sendToTarget(); + } + + } else if (m.what == MSG_TYPE.BUDDY_STATE) { + + MyBuddy buddy = (MyBuddy) m.obj; + int idx = account.buddyList.indexOf(buddy); + + /* Update buddy status text, if buddy is valid and + * the buddy lists in account and UI are sync-ed. + */ + if (idx >= 0 && account.buddyList.size() == buddyList.size()) + { + buddyList.get(idx).put("status", buddy.getStatusText()); + buddyListAdapter.notifyDataSetChanged(); + // TODO: selection color/mark is gone after this, + // dont know how to return it back. + //buddyListView.setSelection(buddyListSelectedIdx); + //buddyListView.performItemClick(buddyListView, + // buddyListSelectedIdx, + // buddyListView. + // getItemIdAtPosition(buddyListSelectedIdx)); + + /* Return back Call activity */ + notifyCallState(currentCall); + } + + } else if (m.what == MSG_TYPE.REG_STATE) { + + String msg_str = (String) m.obj; + lastRegStatus = msg_str; + + } else if (m.what == MSG_TYPE.INCOMING_CALL) { + + /* Incoming call */ + final MyCall call = (MyCall) m.obj; + CallOpParam prm = new CallOpParam(); + + /* Only one call at anytime */ + if (currentCall != null) { + /* + prm.setStatusCode(pjsip_status_code.PJSIP_SC_BUSY_HERE); + try { + call.hangup(prm); + } catch (Exception e) {} + */ + // TODO: set status code + call.delete(); + return true; + } + + /* Answer with ringing */ + prm.setStatusCode(pjsip_status_code.PJSIP_SC_RINGING); + try { + call.answer(prm); + } catch (Exception e) {} + + currentCall = call; + showCallActivity(); + + } else if (m.what == MSG_TYPE.CHANGE_NETWORK) { + app.handleNetworkChange(); + } else { + + /* Message not handled */ + return false; + + } + + return true; } private void dlgAccountSetting() { - LayoutInflater li = LayoutInflater.from(this); - View view = li.inflate(R.layout.dlg_account_config, null); - - if (lastRegStatus.length()!=0) { - TextView tvInfo = (TextView)view.findViewById(R.id.textViewInfo); - tvInfo.setText("Last status: " + lastRegStatus); - } - - AlertDialog.Builder adb = new AlertDialog.Builder(this); - adb.setView(view); - adb.setTitle("Account Settings"); - - final EditText etId = (EditText)view.findViewById(R.id.editTextId); - final EditText etReg = (EditText)view.findViewById(R.id.editTextRegistrar); - final EditText etProxy = (EditText)view.findViewById(R.id.editTextProxy); - final EditText etUser = (EditText)view.findViewById(R.id.editTextUsername); - final EditText etPass = (EditText)view.findViewById(R.id.editTextPassword); - - etId. setText(accCfg.getIdUri()); - etReg. setText(accCfg.getRegConfig().getRegistrarUri()); - StringVector proxies = accCfg.getSipConfig().getProxies(); - if (proxies.size() > 0) - etProxy.setText(proxies.get(0)); - else - etProxy.setText(""); - AuthCredInfoVector creds = accCfg.getSipConfig().getAuthCreds(); - if (creds.size() > 0) { - etUser. setText(creds.get(0).getUsername()); - etPass. setText(creds.get(0).getData()); - } else { - etUser. setText(""); - etPass. setText(""); - } - - adb.setCancelable(false); - adb.setPositiveButton("OK", - new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog,int id) - { - String acc_id = etId.getText().toString(); - String registrar = etReg.getText().toString(); - String proxy = etProxy.getText().toString(); - String username = etUser.getText().toString(); - String password = etPass.getText().toString(); - - accCfg.setIdUri(acc_id); - accCfg.getRegConfig().setRegistrarUri(registrar); - AuthCredInfoVector creds = accCfg.getSipConfig(). - getAuthCreds(); - creds.clear(); - if (username.length() != 0) { - creds.add(new AuthCredInfo("Digest", "*", username, 0, - password)); - } - StringVector proxies = accCfg.getSipConfig().getProxies(); - proxies.clear(); - if (proxy.length() != 0) { - proxies.add(proxy); - } - - /* Enable ICE */ - accCfg.getNatConfig().setIceEnabled(true); - - /* Finally */ - lastRegStatus = ""; - try { - account.modify(accCfg); - } catch (Exception e) {} - } - } - ); - adb.setNegativeButton("Cancel", - new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog,int id) - { - dialog.cancel(); - } - } - ); - - AlertDialog ad = adb.create(); - ad.show(); + LayoutInflater li = LayoutInflater.from(this); + View view = li.inflate(R.layout.dlg_account_config, null); + + if (lastRegStatus.length()!=0) { + TextView tvInfo = (TextView)view.findViewById(R.id.textViewInfo); + tvInfo.setText("Last status: " + lastRegStatus); + } + + AlertDialog.Builder adb = new AlertDialog.Builder(this); + adb.setView(view); + adb.setTitle("Account Settings"); + + final EditText etId = (EditText)view.findViewById(R.id.editTextId); + final EditText etReg = (EditText)view.findViewById(R.id.editTextRegistrar); + final EditText etProxy = (EditText)view.findViewById(R.id.editTextProxy); + final EditText etUser = (EditText)view.findViewById(R.id.editTextUsername); + final EditText etPass = (EditText)view.findViewById(R.id.editTextPassword); + + etId. setText(accCfg.getIdUri()); + etReg. setText(accCfg.getRegConfig().getRegistrarUri()); + StringVector proxies = accCfg.getSipConfig().getProxies(); + if (proxies.size() > 0) + etProxy.setText(proxies.get(0)); + else + etProxy.setText(""); + AuthCredInfoVector creds = accCfg.getSipConfig().getAuthCreds(); + if (creds.size() > 0) { + etUser. setText(creds.get(0).getUsername()); + etPass. setText(creds.get(0).getData()); + } else { + etUser. setText(""); + etPass. setText(""); + } + + adb.setCancelable(false); + adb.setPositiveButton("OK", + new DialogInterface.OnClickListener() + { + public void onClick(DialogInterface dialog,int id) + { + String acc_id = etId.getText().toString(); + String registrar = etReg.getText().toString(); + String proxy = etProxy.getText().toString(); + String username = etUser.getText().toString(); + String password = etPass.getText().toString(); + + accCfg.setIdUri(acc_id); + accCfg.getRegConfig().setRegistrarUri(registrar); + AuthCredInfoVector creds = accCfg.getSipConfig(). + getAuthCreds(); + creds.clear(); + if (username.length() != 0) { + creds.add(new AuthCredInfo("Digest", "*", username, 0, + password)); + } + StringVector proxies = accCfg.getSipConfig().getProxies(); + proxies.clear(); + if (proxy.length() != 0) { + proxies.add(proxy); + } + + /* Enable ICE */ + accCfg.getNatConfig().setIceEnabled(true); + + /* Finally */ + lastRegStatus = ""; + try { + account.modify(accCfg); + } catch (Exception e) {} + } + } + ); + adb.setNegativeButton("Cancel", + new DialogInterface.OnClickListener() + { + public void onClick(DialogInterface dialog,int id) + { + dialog.cancel(); + } + } + ); + + AlertDialog ad = adb.create(); + ad.show(); } public void makeCall(View view) { - if (buddyListSelectedIdx == -1) - return; - - /* Only one call at anytime */ - if (currentCall != null) { - return; - } - - HashMap item = (HashMap) buddyListView. - getItemAtPosition(buddyListSelectedIdx); - String buddy_uri = item.get("uri"); - - MyCall call = new MyCall(account, -1); - CallOpParam prm = new CallOpParam(true); - - try { - call.makeCall(buddy_uri, prm); - } catch (Exception e) { - call.delete(); - return; - } - - currentCall = call; - showCallActivity(); + if (buddyListSelectedIdx == -1) + return; + + /* Only one call at anytime */ + if (currentCall != null) { + return; + } + + HashMap item = (HashMap) buddyListView. + getItemAtPosition(buddyListSelectedIdx); + String buddy_uri = item.get("uri"); + + MyCall call = new MyCall(account, -1); + CallOpParam prm = new CallOpParam(true); + + try { + call.makeCall(buddy_uri, prm); + } catch (Exception e) { + call.delete(); + return; + } + + currentCall = call; + showCallActivity(); } private void dlgAddEditBuddy(BuddyConfig initial) { - final BuddyConfig cfg = new BuddyConfig(); - final BuddyConfig old_cfg = initial; - final boolean is_add = initial == null; - - LayoutInflater li = LayoutInflater.from(this); - View view = li.inflate(R.layout.dlg_add_buddy, null); - - AlertDialog.Builder adb = new AlertDialog.Builder(this); - adb.setView(view); - - final EditText etUri = (EditText)view.findViewById(R.id.editTextUri); - final CheckBox cbSubs = (CheckBox)view.findViewById(R.id.checkBoxSubscribe); - - if (is_add) { - adb.setTitle("Add Buddy"); - } else { - adb.setTitle("Edit Buddy"); - etUri. setText(initial.getUri()); - cbSubs.setChecked(initial.getSubscribe()); - } - - adb.setCancelable(false); - adb.setPositiveButton("OK", - new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog,int id) - { - cfg.setUri(etUri.getText().toString()); - cfg.setSubscribe(cbSubs.isChecked()); - - if (is_add) { - account.addBuddy(cfg); - buddyList.add(putData(cfg.getUri(), "")); - buddyListAdapter.notifyDataSetChanged(); - buddyListSelectedIdx = -1; - } else { - if (!old_cfg.getUri().equals(cfg.getUri())) { - account.delBuddy(buddyListSelectedIdx); - account.addBuddy(cfg); - buddyList.remove(buddyListSelectedIdx); - buddyList.add(putData(cfg.getUri(), "")); - buddyListAdapter.notifyDataSetChanged(); - buddyListSelectedIdx = -1; - } else if (old_cfg.getSubscribe() != - cfg.getSubscribe()) - { - MyBuddy bud = account.buddyList.get( - buddyListSelectedIdx); - try { - bud.subscribePresence(cfg.getSubscribe()); - } catch (Exception e) {} - } - } - } - } - ); - adb.setNegativeButton("Cancel", - new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog,int id) { - dialog.cancel(); - } - } - ); - - AlertDialog ad = adb.create(); - ad.show(); + final BuddyConfig cfg = new BuddyConfig(); + final BuddyConfig old_cfg = initial; + final boolean is_add = initial == null; + + LayoutInflater li = LayoutInflater.from(this); + View view = li.inflate(R.layout.dlg_add_buddy, null); + + AlertDialog.Builder adb = new AlertDialog.Builder(this); + adb.setView(view); + + final EditText etUri = (EditText)view.findViewById(R.id.editTextUri); + final CheckBox cbSubs = (CheckBox)view.findViewById(R.id.checkBoxSubscribe); + + if (is_add) { + adb.setTitle("Add Buddy"); + } else { + adb.setTitle("Edit Buddy"); + etUri. setText(initial.getUri()); + cbSubs.setChecked(initial.getSubscribe()); + } + + adb.setCancelable(false); + adb.setPositiveButton("OK", + new DialogInterface.OnClickListener() + { + public void onClick(DialogInterface dialog,int id) + { + cfg.setUri(etUri.getText().toString()); + cfg.setSubscribe(cbSubs.isChecked()); + + if (is_add) { + account.addBuddy(cfg); + buddyList.add(putData(cfg.getUri(), "")); + buddyListAdapter.notifyDataSetChanged(); + buddyListSelectedIdx = -1; + } else { + if (!old_cfg.getUri().equals(cfg.getUri())) { + account.delBuddy(buddyListSelectedIdx); + account.addBuddy(cfg); + buddyList.remove(buddyListSelectedIdx); + buddyList.add(putData(cfg.getUri(), "")); + buddyListAdapter.notifyDataSetChanged(); + buddyListSelectedIdx = -1; + } else if (old_cfg.getSubscribe() != + cfg.getSubscribe()) + { + MyBuddy bud = account.buddyList.get( + buddyListSelectedIdx); + try { + bud.subscribePresence(cfg.getSubscribe()); + } catch (Exception e) {} + } + } + } + } + ); + adb.setNegativeButton("Cancel", + new DialogInterface.OnClickListener() + { + public void onClick(DialogInterface dialog,int id) { + dialog.cancel(); + } + } + ); + + AlertDialog ad = adb.create(); + ad.show(); } public void addBuddy(View view) { - dlgAddEditBuddy(null); + dlgAddEditBuddy(null); } public void editBuddy(View view) { - if (buddyListSelectedIdx == -1) - return; + if (buddyListSelectedIdx == -1) + return; - BuddyConfig old_cfg = account.buddyList.get(buddyListSelectedIdx).cfg; - dlgAddEditBuddy(old_cfg); + BuddyConfig old_cfg = account.buddyList.get(buddyListSelectedIdx).cfg; + dlgAddEditBuddy(old_cfg); } public void delBuddy(View view) { - if (buddyListSelectedIdx == -1) - return; - - final HashMap item = (HashMap) - buddyListView.getItemAtPosition(buddyListSelectedIdx); - String buddy_uri = item.get("uri"); - - DialogInterface.OnClickListener ocl = - new DialogInterface.OnClickListener() - { - @Override - public void onClick(DialogInterface dialog, int which) - { - switch (which) { - case DialogInterface.BUTTON_POSITIVE: - account.delBuddy(buddyListSelectedIdx); - buddyList.remove(item); - buddyListAdapter.notifyDataSetChanged(); - buddyListSelectedIdx = -1; - break; - case DialogInterface.BUTTON_NEGATIVE: - break; - } - } - }; - - AlertDialog.Builder adb = new AlertDialog.Builder(this); - adb.setTitle(buddy_uri); - adb.setMessage("\nDelete this buddy?\n"); - adb.setPositiveButton("Yes", ocl); - adb.setNegativeButton("No", ocl); - adb.show(); + if (buddyListSelectedIdx == -1) + return; + + final HashMap item = (HashMap) + buddyListView.getItemAtPosition(buddyListSelectedIdx); + String buddy_uri = item.get("uri"); + + DialogInterface.OnClickListener ocl = + new DialogInterface.OnClickListener() + { + @Override + public void onClick(DialogInterface dialog, int which) + { + switch (which) { + case DialogInterface.BUTTON_POSITIVE: + account.delBuddy(buddyListSelectedIdx); + buddyList.remove(item); + buddyListAdapter.notifyDataSetChanged(); + buddyListSelectedIdx = -1; + break; + case DialogInterface.BUTTON_NEGATIVE: + break; + } + } + }; + + AlertDialog.Builder adb = new AlertDialog.Builder(this); + adb.setTitle(buddy_uri); + adb.setMessage("\nDelete this buddy?\n"); + adb.setPositiveButton("Yes", ocl); + adb.setNegativeButton("No", ocl); + adb.show(); } @@ -583,61 +583,61 @@ public void onClick(DialogInterface dialog, int which) public void notifyIncomingCall(MyCall call) { - Message m = Message.obtain(handler, MSG_TYPE.INCOMING_CALL, call); - m.sendToTarget(); + Message m = Message.obtain(handler, MSG_TYPE.INCOMING_CALL, call); + m.sendToTarget(); } public void notifyRegState(int code, String reason, - long expiration) + long expiration) { - String msg_str = ""; - if (expiration == 0) - msg_str += "Unregistration"; - else - msg_str += "Registration"; - - if (code/100 == 2) - msg_str += " successful"; - else - msg_str += " failed: " + reason; - - Message m = Message.obtain(handler, MSG_TYPE.REG_STATE, msg_str); - m.sendToTarget(); + String msg_str = ""; + if (expiration == 0) + msg_str += "Unregistration"; + else + msg_str += "Registration"; + + if (code/100 == 2) + msg_str += " successful"; + else + msg_str += " failed: " + reason; + + Message m = Message.obtain(handler, MSG_TYPE.REG_STATE, msg_str); + m.sendToTarget(); } public void notifyCallState(MyCall call) { - if (currentCall == null || call.getId() != currentCall.getId()) - return; + if (currentCall == null || call.getId() != currentCall.getId()) + return; - CallInfo ci = null; - try { - ci = call.getInfo(); - } catch (Exception e) {} + CallInfo ci = null; + try { + ci = call.getInfo(); + } catch (Exception e) {} - if (ci == null) - return; + if (ci == null) + return; - Message m = Message.obtain(handler, MSG_TYPE.CALL_STATE, ci); - m.sendToTarget(); + Message m = Message.obtain(handler, MSG_TYPE.CALL_STATE, ci); + m.sendToTarget(); } public void notifyCallMediaState(MyCall call) { - Message m = Message.obtain(handler, MSG_TYPE.CALL_MEDIA_STATE, null); - m.sendToTarget(); + Message m = Message.obtain(handler, MSG_TYPE.CALL_MEDIA_STATE, null); + m.sendToTarget(); } public void notifyBuddyState(MyBuddy buddy) { - Message m = Message.obtain(handler, MSG_TYPE.BUDDY_STATE, buddy); - m.sendToTarget(); + Message m = Message.obtain(handler, MSG_TYPE.BUDDY_STATE, buddy); + m.sendToTarget(); } public void notifyChangeNetwork() { - Message m = Message.obtain(handler, MSG_TYPE.CHANGE_NETWORK, null); - m.sendToTarget(); + Message m = Message.obtain(handler, MSG_TYPE.CHANGE_NETWORK, null); + m.sendToTarget(); } /* === end of MyAppObserver ==== */ diff --git a/pjsip-apps/src/swig/java/android/app/src/main/java/org/pjsip/pjsua2/app/MyApp.java b/pjsip-apps/src/swig/java/android/app/src/main/java/org/pjsip/pjsua2/app/MyApp.java index e4ff2e3fb1..11e5220c7e 100644 --- a/pjsip-apps/src/swig/java/android/app/src/main/java/org/pjsip/pjsua2/app/MyApp.java +++ b/pjsip-apps/src/swig/java/android/app/src/main/java/org/pjsip/pjsua2/app/MyApp.java @@ -41,7 +41,7 @@ class MyLogWriter extends LogWriter @Override public void write(LogEntry entry) { - System.out.println(entry.getMsg()); + System.out.println(entry.getMsg()); } } @@ -53,72 +53,72 @@ class MyCall extends Call MyCall(MyAccount acc, int call_id) { - super(acc, call_id); - vidWin = null; + super(acc, call_id); + vidWin = null; } @Override public void onCallState(OnCallStateParam prm) { - try { - CallInfo ci = getInfo(); - if (ci.getState() == - pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED) - { - MyApp.ep.utilLogWrite(3, "MyCall", this.dump(true, "")); - } - } catch (Exception e) { - } - - // Should not delete this call instance (self) in this context, - // so the observer should manage this call instance deletion - // out of this callback context. - MyApp.observer.notifyCallState(this); + try { + CallInfo ci = getInfo(); + if (ci.getState() == + pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED) + { + MyApp.ep.utilLogWrite(3, "MyCall", this.dump(true, "")); + } + } catch (Exception e) { + } + + // Should not delete this call instance (self) in this context, + // so the observer should manage this call instance deletion + // out of this callback context. + MyApp.observer.notifyCallState(this); } @Override public void onCallMediaState(OnCallMediaStateParam prm) { - CallInfo ci; - try { - ci = getInfo(); - } catch (Exception e) { - return; - } - - CallMediaInfoVector cmiv = ci.getMedia(); - - for (int i = 0; i < cmiv.size(); i++) { - CallMediaInfo cmi = cmiv.get(i); - if (cmi.getType() == pjmedia_type.PJMEDIA_TYPE_AUDIO && - (cmi.getStatus() == - pjsua_call_media_status.PJSUA_CALL_MEDIA_ACTIVE || - cmi.getStatus() == - pjsua_call_media_status.PJSUA_CALL_MEDIA_REMOTE_HOLD)) - { - // connect ports - try { - AudioMedia am = getAudioMedia(i); - MyApp.ep.audDevManager().getCaptureDevMedia(). - startTransmit(am); - am.startTransmit(MyApp.ep.audDevManager(). - getPlaybackDevMedia()); - } catch (Exception e) { - System.out.println("Failed connecting media ports" + - e.getMessage()); - continue; - } - } else if (cmi.getType() == pjmedia_type.PJMEDIA_TYPE_VIDEO && - cmi.getStatus() == - pjsua_call_media_status.PJSUA_CALL_MEDIA_ACTIVE && - cmi.getVideoIncomingWindowId() != pjsua2.INVALID_ID) - { - vidWin = new VideoWindow(cmi.getVideoIncomingWindowId()); - vidPrev = new VideoPreview(cmi.getVideoCapDev()); - } - } - - MyApp.observer.notifyCallMediaState(this); + CallInfo ci; + try { + ci = getInfo(); + } catch (Exception e) { + return; + } + + CallMediaInfoVector cmiv = ci.getMedia(); + + for (int i = 0; i < cmiv.size(); i++) { + CallMediaInfo cmi = cmiv.get(i); + if (cmi.getType() == pjmedia_type.PJMEDIA_TYPE_AUDIO && + (cmi.getStatus() == + pjsua_call_media_status.PJSUA_CALL_MEDIA_ACTIVE || + cmi.getStatus() == + pjsua_call_media_status.PJSUA_CALL_MEDIA_REMOTE_HOLD)) + { + // connect ports + try { + AudioMedia am = getAudioMedia(i); + MyApp.ep.audDevManager().getCaptureDevMedia(). + startTransmit(am); + am.startTransmit(MyApp.ep.audDevManager(). + getPlaybackDevMedia()); + } catch (Exception e) { + System.out.println("Failed connecting media ports" + + e.getMessage()); + continue; + } + } else if (cmi.getType() == pjmedia_type.PJMEDIA_TYPE_VIDEO && + cmi.getStatus() == + pjsua_call_media_status.PJSUA_CALL_MEDIA_ACTIVE && + cmi.getVideoIncomingWindowId() != pjsua2.INVALID_ID) + { + vidWin = new VideoWindow(cmi.getVideoIncomingWindowId()); + vidPrev = new VideoPreview(cmi.getVideoCapDev()); + } + } + + MyApp.observer.notifyCallMediaState(this); } } @@ -130,69 +130,69 @@ class MyAccount extends Account MyAccount(AccountConfig config) { - super(); - cfg = config; + super(); + cfg = config; } public MyBuddy addBuddy(BuddyConfig bud_cfg) { - /* Create Buddy */ - MyBuddy bud = new MyBuddy(bud_cfg); - try { - bud.create(this, bud_cfg); - } catch (Exception e) { - bud.delete(); - bud = null; - } - - if (bud != null) { - buddyList.add(bud); - if (bud_cfg.getSubscribe()) - try { - bud.subscribePresence(true); - } catch (Exception e) {} - } - - return bud; + /* Create Buddy */ + MyBuddy bud = new MyBuddy(bud_cfg); + try { + bud.create(this, bud_cfg); + } catch (Exception e) { + bud.delete(); + bud = null; + } + + if (bud != null) { + buddyList.add(bud); + if (bud_cfg.getSubscribe()) + try { + bud.subscribePresence(true); + } catch (Exception e) {} + } + + return bud; } public void delBuddy(MyBuddy buddy) { - buddyList.remove(buddy); - buddy.delete(); + buddyList.remove(buddy); + buddy.delete(); } public void delBuddy(int index) { - MyBuddy bud = buddyList.get(index); - buddyList.remove(index); - bud.delete(); + MyBuddy bud = buddyList.get(index); + buddyList.remove(index); + bud.delete(); } @Override public void onRegState(OnRegStateParam prm) { MyApp.observer.notifyRegState(prm.getCode(), prm.getReason(), - prm.getExpiration()); + prm.getExpiration()); } @Override public void onIncomingCall(OnIncomingCallParam prm) { - System.out.println("======== Incoming call ======== "); - MyCall call = new MyCall(this, prm.getCallId()); - MyApp.observer.notifyIncomingCall(call); + System.out.println("======== Incoming call ======== "); + MyCall call = new MyCall(this, prm.getCallId()); + MyApp.observer.notifyIncomingCall(call); } @Override public void onInstantMessage(OnInstantMessageParam prm) { - System.out.println("======== Incoming pager ======== "); - System.out.println("From : " + prm.getFromUri()); - System.out.println("To : " + prm.getToUri()); - System.out.println("Contact : " + prm.getContactUri()); - System.out.println("Mimetype : " + prm.getContentType()); - System.out.println("Body : " + prm.getMsgBody()); + System.out.println("======== Incoming pager ======== "); + System.out.println("From : " + prm.getFromUri()); + System.out.println("To : " + prm.getToUri()); + System.out.println("Contact : " + prm.getContactUri()); + System.out.println("Mimetype : " + prm.getContentType()); + System.out.println("Body : " + prm.getMsgBody()); } } @@ -203,44 +203,44 @@ class MyBuddy extends Buddy MyBuddy(BuddyConfig config) { - super(); - cfg = config; + super(); + cfg = config; } String getStatusText() { - BuddyInfo bi; - - try { - bi = getInfo(); - } catch (Exception e) { - return "?"; - } - - String status = ""; - if (bi.getSubState() == pjsip_evsub_state.PJSIP_EVSUB_STATE_ACTIVE) { - if (bi.getPresStatus().getStatus() == - pjsua_buddy_status.PJSUA_BUDDY_STATUS_ONLINE) - { - status = bi.getPresStatus().getStatusText(); - if (status == null || status.length()==0) { - status = "Online"; - } - } else if (bi.getPresStatus().getStatus() == - pjsua_buddy_status.PJSUA_BUDDY_STATUS_OFFLINE) - { - status = "Offline"; - } else { - status = "Unknown"; - } - } - return status; + BuddyInfo bi; + + try { + bi = getInfo(); + } catch (Exception e) { + return "?"; + } + + String status = ""; + if (bi.getSubState() == pjsip_evsub_state.PJSIP_EVSUB_STATE_ACTIVE) { + if (bi.getPresStatus().getStatus() == + pjsua_buddy_status.PJSUA_BUDDY_STATUS_ONLINE) + { + status = bi.getPresStatus().getStatusText(); + if (status == null || status.length()==0) { + status = "Online"; + } + } else if (bi.getPresStatus().getStatus() == + pjsua_buddy_status.PJSUA_BUDDY_STATUS_OFFLINE) + { + status = "Offline"; + } else { + status = "Unknown"; + } + } + return status; } @Override public void onBuddyState() { - MyApp.observer.notifyBuddyState(this); + MyApp.observer.notifyBuddyState(this); } } @@ -253,29 +253,29 @@ class MyAccountConfig public void readObject(ContainerNode node) { - try { - ContainerNode acc_node = node.readContainer("Account"); - accCfg.readObject(acc_node); - ContainerNode buddies_node = acc_node.readArray("buddies"); - buddyCfgs.clear(); - while (buddies_node.hasUnread()) { - BuddyConfig bud_cfg = new BuddyConfig(); - bud_cfg.readObject(buddies_node); - buddyCfgs.add(bud_cfg); - } - } catch (Exception e) {} + try { + ContainerNode acc_node = node.readContainer("Account"); + accCfg.readObject(acc_node); + ContainerNode buddies_node = acc_node.readArray("buddies"); + buddyCfgs.clear(); + while (buddies_node.hasUnread()) { + BuddyConfig bud_cfg = new BuddyConfig(); + bud_cfg.readObject(buddies_node); + buddyCfgs.add(bud_cfg); + } + } catch (Exception e) {} } public void writeObject(ContainerNode node) { - try { - ContainerNode acc_node = node.writeNewContainer("Account"); - accCfg.writeObject(acc_node); - ContainerNode buddies_node = acc_node.writeNewArray("buddies"); - for (int j = 0; j < buddyCfgs.size(); j++) { - buddyCfgs.get(j).writeObject(buddies_node); - } - } catch (Exception e) {} + try { + ContainerNode acc_node = node.writeNewContainer("Account"); + accCfg.writeObject(acc_node); + ContainerNode buddies_node = acc_node.writeNewArray("buddies"); + for (int j = 0; j < buddyCfgs.size(); j++) { + buddyCfgs.get(j).writeObject(buddies_node); + } + } catch (Exception e) {} } } @@ -286,7 +286,7 @@ class MyApp extends pjsua2 { public ArrayList accList = new ArrayList(); private ArrayList accCfgs = - new ArrayList(); + new ArrayList(); private EpConfig epConfig = new EpConfig(); private TransportConfig sipTpConfig = new TransportConfig(); private String appDir; @@ -300,263 +300,263 @@ class MyApp extends pjsua2 { public void init(MyAppObserver obs, String app_dir) { - init(obs, app_dir, false); + init(obs, app_dir, false); } public void init(MyAppObserver obs, String app_dir, - boolean own_worker_thread) + boolean own_worker_thread) { - observer = obs; - appDir = app_dir; - - /* Create endpoint */ - try { - ep.libCreate(); - } catch (Exception e) { - return; - } - - - /* Load config */ - String configPath = appDir + "/" + configName; - File f = new File(configPath); - if (f.exists()) { - loadConfig(configPath); - } else { - /* Set 'default' values */ - sipTpConfig.setPort(SIP_PORT); - } - - /* Override log level setting */ - epConfig.getLogConfig().setLevel(LOG_LEVEL); - epConfig.getLogConfig().setConsoleLevel(LOG_LEVEL); - - /* Set log config. */ - LogConfig log_cfg = epConfig.getLogConfig(); - logWriter = new MyLogWriter(); - log_cfg.setWriter(logWriter); - log_cfg.setDecor(log_cfg.getDecor() & - ~(pj_log_decoration.PJ_LOG_HAS_CR | - pj_log_decoration.PJ_LOG_HAS_NEWLINE)); - - /* Write log to file (just uncomment whenever needed) */ - //String log_path = android.os.Environment.getExternalStorageDirectory().toString(); - //log_cfg.setFilename(log_path + "/pjsip.log"); - - /* Set ua config. */ - UaConfig ua_cfg = epConfig.getUaConfig(); - ua_cfg.setUserAgent("Pjsua2 Android " + ep.libVersion().getFull()); - - /* STUN server. */ - //StringVector stun_servers = new StringVector(); - //stun_servers.add("stun.pjsip.org"); - //ua_cfg.setStunServer(stun_servers); - - /* No worker thread */ - if (own_worker_thread) { - ua_cfg.setThreadCnt(0); - ua_cfg.setMainThreadOnly(true); - } - - /* Init endpoint */ - try { - ep.libInit(epConfig); - } catch (Exception e) { - return; - } - - /* Create transports. */ - try { - ep.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_UDP, - sipTpConfig); - } catch (Exception e) { - System.out.println(e); - } - - try { - ep.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_TCP, - sipTpConfig); - } catch (Exception e) { - System.out.println(e); - } - - try { - sipTpConfig.setPort(SIP_PORT+1); - ep.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_TLS, - sipTpConfig); - } catch (Exception e) { - System.out.println(e); - } + observer = obs; + appDir = app_dir; + + /* Create endpoint */ + try { + ep.libCreate(); + } catch (Exception e) { + return; + } + + + /* Load config */ + String configPath = appDir + "/" + configName; + File f = new File(configPath); + if (f.exists()) { + loadConfig(configPath); + } else { + /* Set 'default' values */ + sipTpConfig.setPort(SIP_PORT); + } + + /* Override log level setting */ + epConfig.getLogConfig().setLevel(LOG_LEVEL); + epConfig.getLogConfig().setConsoleLevel(LOG_LEVEL); + + /* Set log config. */ + LogConfig log_cfg = epConfig.getLogConfig(); + logWriter = new MyLogWriter(); + log_cfg.setWriter(logWriter); + log_cfg.setDecor(log_cfg.getDecor() & + ~(pj_log_decoration.PJ_LOG_HAS_CR | + pj_log_decoration.PJ_LOG_HAS_NEWLINE)); + + /* Write log to file (just uncomment whenever needed) */ + //String log_path = android.os.Environment.getExternalStorageDirectory().toString(); + //log_cfg.setFilename(log_path + "/pjsip.log"); + + /* Set ua config. */ + UaConfig ua_cfg = epConfig.getUaConfig(); + ua_cfg.setUserAgent("Pjsua2 Android " + ep.libVersion().getFull()); + + /* STUN server. */ + //StringVector stun_servers = new StringVector(); + //stun_servers.add("stun.pjsip.org"); + //ua_cfg.setStunServer(stun_servers); + + /* No worker thread */ + if (own_worker_thread) { + ua_cfg.setThreadCnt(0); + ua_cfg.setMainThreadOnly(true); + } + + /* Init endpoint */ + try { + ep.libInit(epConfig); + } catch (Exception e) { + return; + } + + /* Create transports. */ + try { + ep.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_UDP, + sipTpConfig); + } catch (Exception e) { + System.out.println(e); + } + + try { + ep.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_TCP, + sipTpConfig); + } catch (Exception e) { + System.out.println(e); + } + + try { + sipTpConfig.setPort(SIP_PORT+1); + ep.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_TLS, + sipTpConfig); + } catch (Exception e) { + System.out.println(e); + } /* Set SIP port back to default for JSON saved config */ sipTpConfig.setPort(SIP_PORT); - /* Create accounts. */ - for (int i = 0; i < accCfgs.size(); i++) { - MyAccountConfig my_cfg = accCfgs.get(i); - - /* Customize account config */ - my_cfg.accCfg.getNatConfig().setIceEnabled(true); - my_cfg.accCfg.getVideoConfig().setAutoTransmitOutgoing(true); - my_cfg.accCfg.getVideoConfig().setAutoShowIncoming(true); - - /* Enable SRTP optional mode and without requiring SIP TLS transport */ - my_cfg.accCfg.getMediaConfig().setSrtpUse(pjmedia_srtp_use.PJMEDIA_SRTP_OPTIONAL); - my_cfg.accCfg.getMediaConfig().setSrtpSecureSignaling(0); - - MyAccount acc = addAcc(my_cfg.accCfg); - if (acc == null) - continue; - - /* Add Buddies */ - for (int j = 0; j < my_cfg.buddyCfgs.size(); j++) { - BuddyConfig bud_cfg = my_cfg.buddyCfgs.get(j); - acc.addBuddy(bud_cfg); - } - } - - /* Start. */ - try { - ep.libStart(); - } catch (Exception e) { - return; - } + /* Create accounts. */ + for (int i = 0; i < accCfgs.size(); i++) { + MyAccountConfig my_cfg = accCfgs.get(i); + + /* Customize account config */ + my_cfg.accCfg.getNatConfig().setIceEnabled(true); + my_cfg.accCfg.getVideoConfig().setAutoTransmitOutgoing(true); + my_cfg.accCfg.getVideoConfig().setAutoShowIncoming(true); + + /* Enable SRTP optional mode and without requiring SIP TLS transport */ + my_cfg.accCfg.getMediaConfig().setSrtpUse(pjmedia_srtp_use.PJMEDIA_SRTP_OPTIONAL); + my_cfg.accCfg.getMediaConfig().setSrtpSecureSignaling(0); + + MyAccount acc = addAcc(my_cfg.accCfg); + if (acc == null) + continue; + + /* Add Buddies */ + for (int j = 0; j < my_cfg.buddyCfgs.size(); j++) { + BuddyConfig bud_cfg = my_cfg.buddyCfgs.get(j); + acc.addBuddy(bud_cfg); + } + } + + /* Start. */ + try { + ep.libStart(); + } catch (Exception e) { + return; + } } public MyAccount addAcc(AccountConfig cfg) { - MyAccount acc = new MyAccount(cfg); - try { - acc.create(cfg); - } catch (Exception e) { - System.out.println(e); - acc = null; - return null; - } - - accList.add(acc); - return acc; + MyAccount acc = new MyAccount(cfg); + try { + acc.create(cfg); + } catch (Exception e) { + System.out.println(e); + acc = null; + return null; + } + + accList.add(acc); + return acc; } public void delAcc(MyAccount acc) { - accList.remove(acc); + accList.remove(acc); } private void loadConfig(String filename) { - JsonDocument json = new JsonDocument(); - - try { - /* Load file */ - json.loadFile(filename); - ContainerNode root = json.getRootContainer(); - - /* Read endpoint config */ - epConfig.readObject(root); - - /* Read transport config */ - ContainerNode tp_node = root.readContainer("SipTransport"); - sipTpConfig.readObject(tp_node); - - /* Read account configs */ - accCfgs.clear(); - ContainerNode accs_node = root.readArray("accounts"); - while (accs_node.hasUnread()) { - MyAccountConfig acc_cfg = new MyAccountConfig(); - acc_cfg.readObject(accs_node); - accCfgs.add(acc_cfg); - } - } catch (Exception e) { - System.out.println(e); - } - - /* Force delete json now, as I found that Java somehow destroys it - * after lib has been destroyed and from non-registered thread. - */ - json.delete(); + JsonDocument json = new JsonDocument(); + + try { + /* Load file */ + json.loadFile(filename); + ContainerNode root = json.getRootContainer(); + + /* Read endpoint config */ + epConfig.readObject(root); + + /* Read transport config */ + ContainerNode tp_node = root.readContainer("SipTransport"); + sipTpConfig.readObject(tp_node); + + /* Read account configs */ + accCfgs.clear(); + ContainerNode accs_node = root.readArray("accounts"); + while (accs_node.hasUnread()) { + MyAccountConfig acc_cfg = new MyAccountConfig(); + acc_cfg.readObject(accs_node); + accCfgs.add(acc_cfg); + } + } catch (Exception e) { + System.out.println(e); + } + + /* Force delete json now, as I found that Java somehow destroys it + * after lib has been destroyed and from non-registered thread. + */ + json.delete(); } private void buildAccConfigs() { - /* Sync accCfgs from accList */ - accCfgs.clear(); - for (int i = 0; i < accList.size(); i++) { - MyAccount acc = accList.get(i); - MyAccountConfig my_acc_cfg = new MyAccountConfig(); - my_acc_cfg.accCfg = acc.cfg; - - my_acc_cfg.buddyCfgs.clear(); - for (int j = 0; j < acc.buddyList.size(); j++) { - MyBuddy bud = acc.buddyList.get(j); - my_acc_cfg.buddyCfgs.add(bud.cfg); - } - - accCfgs.add(my_acc_cfg); - } + /* Sync accCfgs from accList */ + accCfgs.clear(); + for (int i = 0; i < accList.size(); i++) { + MyAccount acc = accList.get(i); + MyAccountConfig my_acc_cfg = new MyAccountConfig(); + my_acc_cfg.accCfg = acc.cfg; + + my_acc_cfg.buddyCfgs.clear(); + for (int j = 0; j < acc.buddyList.size(); j++) { + MyBuddy bud = acc.buddyList.get(j); + my_acc_cfg.buddyCfgs.add(bud.cfg); + } + + accCfgs.add(my_acc_cfg); + } } private void saveConfig(String filename) { - JsonDocument json = new JsonDocument(); - - try { - /* Write endpoint config */ - json.writeObject(epConfig); - - /* Write transport config */ - ContainerNode tp_node = json.writeNewContainer("SipTransport"); - sipTpConfig.writeObject(tp_node); - - /* Write account configs */ - buildAccConfigs(); - ContainerNode accs_node = json.writeNewArray("accounts"); - for (int i = 0; i < accCfgs.size(); i++) { - accCfgs.get(i).writeObject(accs_node); - } - - /* Save file */ - json.saveFile(filename); - } catch (Exception e) {} - - /* Force delete json now, as I found that Java somehow destroys it - * after lib has been destroyed and from non-registered thread. - */ - json.delete(); + JsonDocument json = new JsonDocument(); + + try { + /* Write endpoint config */ + json.writeObject(epConfig); + + /* Write transport config */ + ContainerNode tp_node = json.writeNewContainer("SipTransport"); + sipTpConfig.writeObject(tp_node); + + /* Write account configs */ + buildAccConfigs(); + ContainerNode accs_node = json.writeNewArray("accounts"); + for (int i = 0; i < accCfgs.size(); i++) { + accCfgs.get(i).writeObject(accs_node); + } + + /* Save file */ + json.saveFile(filename); + } catch (Exception e) {} + + /* Force delete json now, as I found that Java somehow destroys it + * after lib has been destroyed and from non-registered thread. + */ + json.delete(); } public void handleNetworkChange() { - try{ - System.out.println("Network change detected"); - IpChangeParam changeParam = new IpChangeParam(); - ep.handleIpChange(changeParam); - } catch (Exception e) { - System.out.println(e); - } + try{ + System.out.println("Network change detected"); + IpChangeParam changeParam = new IpChangeParam(); + ep.handleIpChange(changeParam); + } catch (Exception e) { + System.out.println(e); + } } public void deinit() { - String configPath = appDir + "/" + configName; - saveConfig(configPath); - - /* Try force GC to avoid late destroy of PJ objects as they should be - * deleted before lib is destroyed. - */ - Runtime.getRuntime().gc(); - - /* Shutdown pjsua. Note that Endpoint destructor will also invoke - * libDestroy(), so this will be a test of double libDestroy(). - */ - try { - ep.libDestroy(); - } catch (Exception e) {} - - /* Force delete Endpoint here, to avoid deletion from a non- - * registered thread (by GC?). - */ - ep.delete(); - ep = null; + String configPath = appDir + "/" + configName; + saveConfig(configPath); + + /* Try force GC to avoid late destroy of PJ objects as they should be + * deleted before lib is destroyed. + */ + Runtime.getRuntime().gc(); + + /* Shutdown pjsua. Note that Endpoint destructor will also invoke + * libDestroy(), so this will be a test of double libDestroy(). + */ + try { + ep.libDestroy(); + } catch (Exception e) {} + + /* Force delete Endpoint here, to avoid deletion from a non- + * registered thread (by GC?). + */ + ep.delete(); + ep = null; } } diff --git a/pjsip-apps/src/swig/java/sample.java b/pjsip-apps/src/swig/java/sample.java index f03a6ac69e..444f259474 100644 --- a/pjsip-apps/src/swig/java/sample.java +++ b/pjsip-apps/src/swig/java/sample.java @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -24,156 +23,156 @@ import org.pjsip.pjsua2.app.*; class MyObserver implements MyAppObserver { - private static MyCall currentCall = null; - private boolean del_call_scheduled = false; - - public void check_call_deletion() - { - if (del_call_scheduled && currentCall != null) { - currentCall.delete(); - currentCall = null; - del_call_scheduled = false; - } - } - - @Override - public void notifyRegState(int code, String reason, long expiration) {} - - @Override - public void notifyIncomingCall(MyCall call) { - /* Auto answer. */ - CallOpParam call_param = new CallOpParam(); - call_param.setStatusCode(pjsip_status_code.PJSIP_SC_OK); - try { - currentCall = call; - currentCall.answer(call_param); - } catch (Exception e) { - System.out.println(e); - return; - } - } - - @Override - public void notifyCallMediaState(MyCall call) { - } + private static MyCall currentCall = null; + private boolean del_call_scheduled = false; + + public void check_call_deletion() + { + if (del_call_scheduled && currentCall != null) { + currentCall.delete(); + currentCall = null; + del_call_scheduled = false; + } + } + + @Override + public void notifyRegState(int code, String reason, long expiration) {} + + @Override + public void notifyIncomingCall(MyCall call) { + /* Auto answer. */ + CallOpParam call_param = new CallOpParam(); + call_param.setStatusCode(pjsip_status_code.PJSIP_SC_OK); + try { + currentCall = call; + currentCall.answer(call_param); + } catch (Exception e) { + System.out.println(e); + return; + } + } + + @Override + public void notifyCallMediaState(MyCall call) { + } - public void notifyCallState(MyCall call) { - if (currentCall == null || call.getId() != currentCall.getId()) - return; - - CallInfo ci; - try { - ci = call.getInfo(); - } catch (Exception e) { - ci = null; - } - if (ci.getState() == pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED) { - // Should not delete call instance in this context, - // so let's just schedule it, the call will be deleted - // in our main worker thread context. - del_call_scheduled = true; - } - - } - - @Override - public void notifyBuddyState(MyBuddy buddy) {} + public void notifyCallState(MyCall call) { + if (currentCall == null || call.getId() != currentCall.getId()) + return; + + CallInfo ci; + try { + ci = call.getInfo(); + } catch (Exception e) { + ci = null; + } + if (ci.getState() == pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED) { + // Should not delete call instance in this context, + // so let's just schedule it, the call will be deleted + // in our main worker thread context. + del_call_scheduled = true; + } + + } + + @Override + public void notifyBuddyState(MyBuddy buddy) {} - @Override - public void notifyChangeNetwork() {} + @Override + public void notifyChangeNetwork() {} } class MyShutdownHook extends Thread { - Thread thread; - MyShutdownHook(Thread thr) { - thread = thr; - } - public void run() { - thread.interrupt(); - try { - thread.join(); - } catch (Exception e) { - ; - } - } -} + Thread thread; + MyShutdownHook(Thread thr) { + thread = thr; + } + public void run() { + thread.interrupt(); + try { + thread.join(); + } catch (Exception e) { + ; + } + } +} public class sample { - private static MyApp app = new MyApp(); - private static MyObserver observer = new MyObserver(); - private static MyAccount account = null; - private static AccountConfig accCfg = null; + private static MyApp app = new MyApp(); + private static MyObserver observer = new MyObserver(); + private static MyAccount account = null; + private static AccountConfig accCfg = null; // Snippet code to set native window to output video /* private void setOutputVidWin() {} - VideoWindowHandle vidWH = new VideoWindowHandle(); + VideoWindowHandle vidWH = new VideoWindowHandle(); vidWH.getHandle().setWindow(getNativeWindow()); try { - currentCall.vidWin.setWindow(vidWH); + currentCall.vidWin.setWindow(vidWH); } catch (Exception e) { System.out.println(e); } } */ - private static void runWorker() { - try { - app.init(observer, ".", true); - } catch (Exception e) { - System.out.println(e); - app.deinit(); - System.exit(-1); - } + private static void runWorker() { + try { + app.init(observer, ".", true); + } catch (Exception e) { + System.out.println(e); + app.deinit(); + System.exit(-1); + } - if (app.accList.size() == 0) { - accCfg = new AccountConfig(); - accCfg.setIdUri("sip:localhost"); - account = app.addAcc(accCfg); + if (app.accList.size() == 0) { + accCfg = new AccountConfig(); + accCfg.setIdUri("sip:localhost"); + account = app.addAcc(accCfg); - accCfg.setIdUri("sip:test@pjsip.org"); - AccountSipConfig sipCfg = accCfg.getSipConfig(); - AuthCredInfoVector ciVec = sipCfg.getAuthCreds(); - ciVec.add(new AuthCredInfo("Digest", - "*", - "test", - 0, - "passwd")); + accCfg.setIdUri("sip:test@pjsip.org"); + AccountSipConfig sipCfg = accCfg.getSipConfig(); + AuthCredInfoVector ciVec = sipCfg.getAuthCreds(); + ciVec.add(new AuthCredInfo("Digest", + "*", + "test", + 0, + "passwd")); - StringVector proxy = sipCfg.getProxies(); - proxy.add("sip:pjsip.org;transport=tcp"); + StringVector proxy = sipCfg.getProxies(); + proxy.add("sip:pjsip.org;transport=tcp"); - AccountRegConfig regCfg = accCfg.getRegConfig(); - regCfg.setRegistrarUri("sip:pjsip.org"); - account = app.addAcc(accCfg); - } else { - account = app.accList.get(0); - accCfg = account.cfg; - } + AccountRegConfig regCfg = accCfg.getRegConfig(); + regCfg.setRegistrarUri("sip:pjsip.org"); + account = app.addAcc(accCfg); + } else { + account = app.accList.get(0); + accCfg = account.cfg; + } - try { - account.modify(accCfg); - } catch (Exception e) {} + try { + account.modify(accCfg); + } catch (Exception e) {} - while (!Thread.currentThread().isInterrupted()) { - // Handle events - MyApp.ep.libHandleEvents(10); - - // Check if any call instance need to be deleted - observer.check_call_deletion(); - - try { - Thread.currentThread().sleep(50); - } catch (InterruptedException ie) { - break; - } - } - app.deinit(); - } - - public static void main(String argv[]) { - Runtime.getRuntime().addShutdownHook(new MyShutdownHook(Thread.currentThread())); + while (!Thread.currentThread().isInterrupted()) { + // Handle events + MyApp.ep.libHandleEvents(10); + + // Check if any call instance need to be deleted + observer.check_call_deletion(); + + try { + Thread.currentThread().sleep(50); + } catch (InterruptedException ie) { + break; + } + } + app.deinit(); + } + + public static void main(String argv[]) { + Runtime.getRuntime().addShutdownHook(new MyShutdownHook(Thread.currentThread())); - runWorker(); + runWorker(); } } diff --git a/pjsip-apps/src/swig/java/sample2.java b/pjsip-apps/src/swig/java/sample2.java index 045dc7dfe0..30c1f50346 100644 --- a/pjsip-apps/src/swig/java/sample2.java +++ b/pjsip-apps/src/swig/java/sample2.java @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -32,172 +31,172 @@ import java.lang.reflect.Method; class MyObserver implements MyAppObserver { - private static MyCall currentCall = null; - private static boolean del_call_scheduled = false; - - public void check_call_deletion() - { - if (del_call_scheduled && currentCall != null) { - currentCall.delete(); - currentCall = null; - del_call_scheduled = false; - } - } - - @Override - public void notifyRegState(int code, String reason, long expiration) {} - - @Override - public void notifyIncomingCall(MyCall call) { - /* Auto answer. */ - CallOpParam call_param = new CallOpParam(); - call_param.setStatusCode(pjsip_status_code.PJSIP_SC_OK); - try { - currentCall = call; - currentCall.answer(call_param); - } catch (Exception e) { - System.out.println(e); - return; - } - } - - @Override - public void notifyCallMediaState(MyCall call) { - } - - public void notifyCallState(MyCall call) { - if (currentCall == null || call.getId() != currentCall.getId()) - return; - - CallInfo ci; - try { - ci = call.getInfo(); - } catch (Exception e) { - ci = null; - } - if (ci.getState() == pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED) { - // Should not delete call instance here, so let's schedule it. - // The call will be deleted by our main worker thread. - del_call_scheduled = true; - } else if (ci.getState() == pjsip_inv_state.PJSIP_INV_STATE_CONFIRMED) { - if (ci.getSetting().getVideoCount() != 0) { - System.out.println("Changing video window using " + sample2.hwnd); - // Change window - VideoWindowHandle vidWH = new VideoWindowHandle(); - vidWH.getHandle().setWindow(sample2.hwnd); - try { - currentCall.vidWin.setWindow(vidWH); - } catch (Exception e) { - System.out.println(e); - } - } - } - } - - @Override - public void notifyBuddyState(MyBuddy buddy) {} - - @Override - public void notifyChangeNetwork() {} + private static MyCall currentCall = null; + private static boolean del_call_scheduled = false; + + public void check_call_deletion() + { + if (del_call_scheduled && currentCall != null) { + currentCall.delete(); + currentCall = null; + del_call_scheduled = false; + } + } + + @Override + public void notifyRegState(int code, String reason, long expiration) {} + + @Override + public void notifyIncomingCall(MyCall call) { + /* Auto answer. */ + CallOpParam call_param = new CallOpParam(); + call_param.setStatusCode(pjsip_status_code.PJSIP_SC_OK); + try { + currentCall = call; + currentCall.answer(call_param); + } catch (Exception e) { + System.out.println(e); + return; + } + } + + @Override + public void notifyCallMediaState(MyCall call) { + } + + public void notifyCallState(MyCall call) { + if (currentCall == null || call.getId() != currentCall.getId()) + return; + + CallInfo ci; + try { + ci = call.getInfo(); + } catch (Exception e) { + ci = null; + } + if (ci.getState() == pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED) { + // Should not delete call instance here, so let's schedule it. + // The call will be deleted by our main worker thread. + del_call_scheduled = true; + } else if (ci.getState() == pjsip_inv_state.PJSIP_INV_STATE_CONFIRMED) { + if (ci.getSetting().getVideoCount() != 0) { + System.out.println("Changing video window using " + sample2.hwnd); + // Change window + VideoWindowHandle vidWH = new VideoWindowHandle(); + vidWH.getHandle().setWindow(sample2.hwnd); + try { + currentCall.vidWin.setWindow(vidWH); + } catch (Exception e) { + System.out.println(e); + } + } + } + } + + @Override + public void notifyBuddyState(MyBuddy buddy) {} + + @Override + public void notifyChangeNetwork() {} } class MyThread extends Thread { - private static MyApp app = new MyApp(); - private static MyObserver observer = new MyObserver(); - private static MyAccount account = null; - private static AccountConfig accCfg = null; - - public void run() { - try { - app.init(observer, ".", true); - } catch (Exception e) { - System.out.println(e); - app.deinit(); - System.exit(-1); - } - - if (app.accList.size() == 0) { - accCfg = new AccountConfig(); - accCfg.setIdUri("sip:localhost"); - account = app.addAcc(accCfg); - - accCfg.setIdUri("sip:test1@pjsip.org"); - AccountSipConfig sipCfg = accCfg.getSipConfig(); - AuthCredInfoVector ciVec = sipCfg.getAuthCreds(); - ciVec.add(new AuthCredInfo("Digest", - "*", - "test1", - 0, - "test1")); - - StringVector proxy = sipCfg.getProxies(); - proxy.add("sip:sip.pjsip.org;transport=tcp"); - - AccountRegConfig regCfg = accCfg.getRegConfig(); - regCfg.setRegistrarUri("sip:pjsip.org"); - - accCfg.getVideoConfig().setAutoTransmitOutgoing(true); - accCfg.getVideoConfig().setAutoShowIncoming(true); - account = app.addAcc(accCfg); - } else { - account = app.accList.get(0); - accCfg = account.cfg; - } - - try { - account.modify(accCfg); - } catch (Exception e) {} - - while (!Thread.currentThread().isInterrupted()) { - // Handle events - MyApp.ep.libHandleEvents(10); - - // Check if any call instance need to be deleted - observer.check_call_deletion(); - try { - Thread.sleep(50); - } catch (InterruptedException ie) { - break; - } - } + private static MyApp app = new MyApp(); + private static MyObserver observer = new MyObserver(); + private static MyAccount account = null; + private static AccountConfig accCfg = null; + + public void run() { + try { + app.init(observer, ".", true); + } catch (Exception e) { + System.out.println(e); + app.deinit(); + System.exit(-1); + } + + if (app.accList.size() == 0) { + accCfg = new AccountConfig(); + accCfg.setIdUri("sip:localhost"); + account = app.addAcc(accCfg); + + accCfg.setIdUri("sip:test1@pjsip.org"); + AccountSipConfig sipCfg = accCfg.getSipConfig(); + AuthCredInfoVector ciVec = sipCfg.getAuthCreds(); + ciVec.add(new AuthCredInfo("Digest", + "*", + "test1", + 0, + "test1")); + + StringVector proxy = sipCfg.getProxies(); + proxy.add("sip:sip.pjsip.org;transport=tcp"); + + AccountRegConfig regCfg = accCfg.getRegConfig(); + regCfg.setRegistrarUri("sip:pjsip.org"); + + accCfg.getVideoConfig().setAutoTransmitOutgoing(true); + accCfg.getVideoConfig().setAutoShowIncoming(true); + account = app.addAcc(accCfg); + } else { + account = app.accList.get(0); + accCfg = account.cfg; + } + + try { + account.modify(accCfg); + } catch (Exception e) {} + + while (!Thread.currentThread().isInterrupted()) { + // Handle events + MyApp.ep.libHandleEvents(10); + + // Check if any call instance need to be deleted + observer.check_call_deletion(); + try { + Thread.sleep(50); + } catch (InterruptedException ie) { + break; + } + } app.deinit(); - } + } } public class sample2 extends Application { - public static long hwnd; - private static Thread myThread = new MyThread(); - - private static long getWindowPointer(Stage stage) { - try { - TKStage tkStage = stage.impl_getPeer(); - Method getPlatformWindow = tkStage.getClass().getDeclaredMethod("getPlatformWindow" ); - getPlatformWindow.setAccessible(true); - Object platformWindow = getPlatformWindow.invoke(tkStage); - Method getNativeHandle = platformWindow.getClass().getMethod( "getNativeHandle" ); - getNativeHandle.setAccessible(true); - return (long)getNativeHandle.invoke(platformWindow); + public static long hwnd; + private static Thread myThread = new MyThread(); + + private static long getWindowPointer(Stage stage) { + try { + TKStage tkStage = stage.impl_getPeer(); + Method getPlatformWindow = tkStage.getClass().getDeclaredMethod("getPlatformWindow" ); + getPlatformWindow.setAccessible(true); + Object platformWindow = getPlatformWindow.invoke(tkStage); + Method getNativeHandle = platformWindow.getClass().getMethod( "getNativeHandle" ); + getNativeHandle.setAccessible(true); + return (long)getNativeHandle.invoke(platformWindow); } catch (Throwable e) { - System.err.println("Error getting Window Pointer"); - return 0; + System.err.println("Error getting Window Pointer"); + return 0; } - } + } - @Override - public void start(Stage primaryStage) { - primaryStage.setTitle("Pjsua2 javafx sample"); - StackPane root = new StackPane(); - primaryStage.setScene(new Scene(root, 300, 250)); - primaryStage.show(); - hwnd = getWindowPointer(primaryStage); - myThread.start(); - } - @Override - public void stop() throws Exception { - myThread.interrupt(); - myThread.join(); - } - public static void main(String argv[]) { - launch(argv); - } + @Override + public void start(Stage primaryStage) { + primaryStage.setTitle("Pjsua2 javafx sample"); + StackPane root = new StackPane(); + primaryStage.setScene(new Scene(root, 300, 250)); + primaryStage.show(); + hwnd = getWindowPointer(primaryStage); + myThread.start(); + } + @Override + public void stop() throws Exception { + myThread.interrupt(); + myThread.join(); + } + public static void main(String argv[]) { + launch(argv); + } } \ No newline at end of file diff --git a/pjsip-apps/src/swig/java/test.java b/pjsip-apps/src/swig/java/test.java index f616460d2d..b66dc9c4e9 100644 --- a/pjsip-apps/src/swig/java/test.java +++ b/pjsip-apps/src/swig/java/test.java @@ -8,10 +8,10 @@ public class test { public static void main(String argv[]) { - AuthCredInfo cred = new AuthCredInfo(); + AuthCredInfo cred = new AuthCredInfo(); - cred.setRealm("Hello world"); + cred.setRealm("Hello world"); - System.out.println(cred.getRealm()); + System.out.println(cred.getRealm()); } } diff --git a/pjsip-apps/src/swig/python/cc_mingw.c b/pjsip-apps/src/swig/python/cc_mingw.c index adbcf8a471..8beef4da9f 100644 --- a/pjsip-apps/src/swig/python/cc_mingw.c +++ b/pjsip-apps/src/swig/python/cc_mingw.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2014 Teluu Inc. (http://www.teluu.com) * @@ -38,32 +37,32 @@ const char* find_gcc(const char *gcc_exe) p = getenv("PATH"); if (strlen(p) >= sizeof(spath)) { - printf("Error: find_gcc() not enough buffer 1\n"); - return NULL; + printf("Error: find_gcc() not enough buffer 1\n"); + return NULL; } strncpy(spath, p, sizeof(spath)); p = strtok(spath, ";"); while (p) { - int len; - - /* Skip current dir */ - if (strcmp(p, ".") == 0) { - p = strtok(NULL, ";"); - continue; - } - - len = snprintf(fname, sizeof(fname), "%s\\%s", p, gcc_exe); - if (len < 0 || len >= sizeof(fname)) { - printf("Error: find_gcc() not enough buffer 2\n"); - return NULL; - } - - if (access(fname, F_OK | X_OK) != -1) { - return fname; - } - - p = strtok(NULL, ";"); + int len; + + /* Skip current dir */ + if (strcmp(p, ".") == 0) { + p = strtok(NULL, ";"); + continue; + } + + len = snprintf(fname, sizeof(fname), "%s\\%s", p, gcc_exe); + if (len < 0 || len >= sizeof(fname)) { + printf("Error: find_gcc() not enough buffer 2\n"); + return NULL; + } + + if (access(fname, F_OK | X_OK) != -1) { + return fname; + } + + p = strtok(NULL, ";"); } return NULL; @@ -79,13 +78,13 @@ int check_gcc_reject_mno_cygwin(const char *gcc_path) snprintf(tmp, sizeof(tmp), "%s -mno-cygwin 2>&1", gcc_path); fp = popen(tmp, "r"); if (fp == NULL) { - printf("Error: failed to run gcc\n" ); - return -1; + printf("Error: failed to run gcc\n" ); + return -1; } while (fgets(tmp, sizeof(tmp), fp) != NULL) { - if (strstr(tmp, "unrecognized") && strstr(tmp, "-mno-cygwin")) - return 1; + if (strstr(tmp, "unrecognized") && strstr(tmp, "-mno-cygwin")) + return 1; } pclose(fp); @@ -102,48 +101,48 @@ int main(int argc, const char const **argv) int remove_mno_cygwin; if (strstr(argv[0], "gcc") || strstr(argv[0], "GCC")) { - gcc_exe = "gcc.exe"; + gcc_exe = "gcc.exe"; } else if (strstr(argv[0], "g++") || strstr(argv[0], "G++")) { - gcc_exe = "g++.exe"; + gcc_exe = "g++.exe"; } else { - printf("Error: app name not gcc/g++\n"); - return -10; + printf("Error: app name not gcc/g++\n"); + return -10; } /* Resolve GCC path from PATH env var */ gcc_exe = find_gcc(gcc_exe); if (!gcc_exe) { - printf("Error: real gcc/g++ not found\n"); - return -20; + printf("Error: real gcc/g++ not found\n"); + return -20; } /* Check if GCC rejects '-mno-cygwin' option */ remove_mno_cygwin = check_gcc_reject_mno_cygwin(gcc_exe); if (remove_mno_cygwin < 0) - return -30; + return -30; len = snprintf(cmd, sizeof(cmd), "%s", gcc_exe); p = cmd + len; sz = sizeof(cmd) - len; for (i = 1; i < argc && sz > 0; ++i) { - if (remove_mno_cygwin && strcmp(argv[i], "-mno-cygwin") == 0) { - printf("Removed option '-mno-cygwin'.\n"); - continue; - } - - len = snprintf(p, sz, " %s", argv[i]); - if (len < 0 || len >= sz) { - ret = E2BIG; - break; - } - p += len; - sz -= len; + if (remove_mno_cygwin && strcmp(argv[i], "-mno-cygwin") == 0) { + printf("Removed option '-mno-cygwin'.\n"); + continue; + } + + len = snprintf(p, sz, " %s", argv[i]); + if (len < 0 || len >= sz) { + ret = E2BIG; + break; + } + p += len; + sz -= len; } if (!ret) { - //printf("cmd = %s\n", cmd); - ret = system(cmd); + //printf("cmd = %s\n", cmd); + ret = system(cmd); } if (ret) { diff --git a/pjsip-apps/src/swig/python/setup.py b/pjsip-apps/src/swig/python/setup.py index 2285a7c0e2..d06a7e82ca 100644 --- a/pjsip-apps/src/swig/python/setup.py +++ b/pjsip-apps/src/swig/python/setup.py @@ -1,4 +1,3 @@ -# $Id$ # # pjsua2 Setup script. # diff --git a/pjsip-apps/src/symsndtest/app_main.cpp b/pjsip-apps/src/symsndtest/app_main.cpp index aaa9512b1b..da04f4f34b 100644 --- a/pjsip-apps/src/symsndtest/app_main.cpp +++ b/pjsip-apps/src/symsndtest/app_main.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,12 +26,12 @@ #include #include -#define THIS_FILE "app_main.cpp" -#define CLOCK_RATE 8000 -#define CHANNEL_COUNT 1 -#define PTIME 20 -#define SAMPLES_PER_FRAME (CLOCK_RATE*PTIME/1000) -#define BITS_PER_SAMPLE 16 +#define THIS_FILE "app_main.cpp" +#define CLOCK_RATE 8000 +#define CHANNEL_COUNT 1 +#define PTIME 20 +#define SAMPLES_PER_FRAME (CLOCK_RATE*PTIME/1000) +#define BITS_PER_SAMPLE 16 extern CConsoleBase* console; @@ -50,15 +49,15 @@ static void copy_frame_ext(pjmedia_frame_ext *f_dst, { pj_bzero(f_dst, sizeof(*f_dst)); if (f_src->subframe_cnt) { - f_dst->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - for (unsigned i = 0; i < f_src->subframe_cnt; ++i) { - pjmedia_frame_ext_subframe *sf; - sf = pjmedia_frame_ext_get_subframe(f_src, i); - pjmedia_frame_ext_append_subframe(f_dst, sf->data, sf->bitlen, - param.samples_per_frame); - } + f_dst->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + for (unsigned i = 0; i < f_src->subframe_cnt; ++i) { + pjmedia_frame_ext_subframe *sf; + sf = pjmedia_frame_ext_get_subframe(f_src, i); + pjmedia_frame_ext_append_subframe(f_dst, sf->data, sf->bitlen, + param.samples_per_frame); + } } else { - f_dst->base.type = PJMEDIA_FRAME_TYPE_NONE; + f_dst->base.type = PJMEDIA_FRAME_TYPE_NONE; } } @@ -97,8 +96,8 @@ static pj_status_t app_init() /* Init pjlib */ status = pj_init(); if (status != PJ_SUCCESS) { - app_perror("pj_init()", status); - return status; + app_perror("pj_init()", status); + return status; } pj_caching_pool_init(&cp, NULL, 0); @@ -106,76 +105,76 @@ static pj_status_t app_init() /* Init sound subsystem */ status = pjmedia_aud_subsys_init(&cp.factory); if (status != PJ_SUCCESS) { - app_perror("pjmedia_snd_init()", status); + app_perror("pjmedia_snd_init()", status); pj_caching_pool_destroy(&cp); - pj_shutdown(); - return status; + pj_shutdown(); + return status; } count = pjmedia_aud_dev_count(); PJ_LOG(3,(THIS_FILE, "Device count: %d", count)); for (i=0; ibuf); + pjmedia_delay_buf_put(delaybuf, (pj_int16_t*)frame->buf); - if (frame->size != SAMPLES_PER_FRAME*2) { - PJ_LOG(3, (THIS_FILE, "Size captured = %u", - frame->size)); - } + if (frame->size != SAMPLES_PER_FRAME*2) { + PJ_LOG(3, (THIS_FILE, "Size captured = %u", + frame->size)); + } } else { - pjmedia_frame_ext *f_src = (pjmedia_frame_ext*)frame; - pjmedia_frame_ext *f_dst = (pjmedia_frame_ext*)frame_buf; - - copy_frame_ext(f_dst, f_src); + pjmedia_frame_ext *f_src = (pjmedia_frame_ext*)frame; + pjmedia_frame_ext *f_dst = (pjmedia_frame_ext*)frame_buf; + + copy_frame_ext(f_dst, f_src); } ++rec_cnt; @@ -208,19 +207,19 @@ static pj_status_t rec_cb(void *user_data, /* Play cb */ static pj_status_t play_cb(void *user_data, - pjmedia_frame *frame) + pjmedia_frame *frame) { PJ_UNUSED_ARG(user_data); if (param.ext_fmt.id == PJMEDIA_FORMAT_PCM) { - pjmedia_delay_buf_get(delaybuf, (pj_int16_t*)frame->buf); - frame->size = SAMPLES_PER_FRAME*2; - frame->type = PJMEDIA_FRAME_TYPE_AUDIO; + pjmedia_delay_buf_get(delaybuf, (pj_int16_t*)frame->buf); + frame->size = SAMPLES_PER_FRAME*2; + frame->type = PJMEDIA_FRAME_TYPE_AUDIO; } else { - pjmedia_frame_ext *f_src = (pjmedia_frame_ext*)frame_buf; - pjmedia_frame_ext *f_dst = (pjmedia_frame_ext*)frame; + pjmedia_frame_ext *f_src = (pjmedia_frame_ext*)frame_buf; + pjmedia_frame_ext *f_dst = (pjmedia_frame_ext*)frame; - copy_frame_ext(f_dst, f_src); + copy_frame_ext(f_dst, f_src); } ++play_cnt; @@ -233,8 +232,8 @@ static pj_status_t snd_start(unsigned flag) pj_status_t status; if (strm != NULL) { - app_perror("snd already open", PJ_EINVALIDOP); - return PJ_EINVALIDOP; + app_perror("snd already open", PJ_EINVALIDOP); + return PJ_EINVALIDOP; } pjmedia_aud_dev_default_param(0, ¶m); @@ -248,8 +247,8 @@ static pj_status_t snd_start(unsigned flag) status = pjmedia_aud_stream_create(¶m, &rec_cb, &play_cb, NULL, &strm); if (status != PJ_SUCCESS) { - app_perror("snd open", status); - return status; + app_perror("snd open", status); + return status; } rec_cnt = play_cnt = 0; @@ -259,10 +258,10 @@ static pj_status_t snd_start(unsigned flag) status = pjmedia_aud_stream_start(strm); if (status != PJ_SUCCESS) { - app_perror("snd start", status); - pjmedia_aud_stream_destroy(strm); - strm = NULL; - return status; + app_perror("snd start", status); + pjmedia_aud_stream_destroy(strm); + strm = NULL; + return status; } return PJ_SUCCESS; @@ -275,13 +274,13 @@ static pj_status_t snd_stop() pj_status_t status; if (strm == NULL) { - app_perror("snd not open", PJ_EINVALIDOP); - return PJ_EINVALIDOP; + app_perror("snd not open", PJ_EINVALIDOP); + return PJ_EINVALIDOP; } status = pjmedia_aud_stream_stop(strm); if (status != PJ_SUCCESS) { - app_perror("snd failed to stop", status); + app_perror("snd failed to stop", status); } status = pjmedia_aud_stream_destroy(strm); strm = NULL; @@ -300,7 +299,7 @@ static pj_status_t snd_stop() static void app_fini() { if (strm) - snd_stop(); + snd_stop(); pjmedia_aud_subsys_shutdown(); pjmedia_delay_buf_destroy(delaybuf); @@ -367,12 +366,12 @@ void ConsoleUI::DoCancel() static void PrintMenu() { PJ_LOG(3, (THIS_FILE, "\n\n" - "Menu:\n" - " a Start bidir sound\n" - " t Start recorder\n" - " p Start player\n" - " d Stop & close sound\n" - " w Quit\n")); + "Menu:\n" + " a Start bidir sound\n" + " t Start recorder\n" + " p Start player\n" + " d Stop & close sound\n" + " w Quit\n")); } // Implementation: called when read has completed. @@ -383,32 +382,32 @@ void ConsoleUI::RunL() switch (kc) { case 'w': - snd_stop(); - CActiveScheduler::Stop(); - reschedule = PJ_FALSE; - break; + snd_stop(); + CActiveScheduler::Stop(); + reschedule = PJ_FALSE; + break; case 'a': - snd_start(PJMEDIA_DIR_CAPTURE_PLAYBACK); - break; + snd_start(PJMEDIA_DIR_CAPTURE_PLAYBACK); + break; case 't': - snd_start(PJMEDIA_DIR_CAPTURE); - break; + snd_start(PJMEDIA_DIR_CAPTURE); + break; case 'p': - snd_start(PJMEDIA_DIR_PLAYBACK); + snd_start(PJMEDIA_DIR_PLAYBACK); break; case 'd': - snd_stop(); - break; + snd_stop(); + break; default: - PJ_LOG(3,(THIS_FILE, "Keycode '%c' (%d) is pressed", - kc, kc)); - break; + PJ_LOG(3,(THIS_FILE, "Keycode '%c' (%d) is pressed", + kc, kc)); + break; } PrintMenu(); if (reschedule) - Run(); + Run(); } diff --git a/pjsip-apps/src/symsndtest/main_symbian.cpp b/pjsip-apps/src/symsndtest/main_symbian.cpp index 6f29915f85..6c05d53fd9 100644 --- a/pjsip-apps/src/symsndtest/main_symbian.cpp +++ b/pjsip-apps/src/symsndtest/main_symbian.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjsip-apps/src/vidgui/vidgui.cpp b/pjsip-apps/src/vidgui/vidgui.cpp index a2e8326e3d..54b3e7ac5c 100644 --- a/pjsip-apps/src/vidgui/vidgui.cpp +++ b/pjsip-apps/src/vidgui/vidgui.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011-2011 Teluu Inc. (http://www.teluu.com) * @@ -27,8 +26,8 @@ #include #include -#define LOG_FILE "vidgui.log" -#define THIS_FILE "vidgui.cpp" +#define LOG_FILE "vidgui.log" +#define THIS_FILE "vidgui.cpp" /////////////////////////////////////////////////////////////////////////// // @@ -38,26 +37,26 @@ // // These configure SIP registration // -#define USE_REGISTRATION 0 -#define SIP_DOMAIN "pjsip.org" -#define SIP_USERNAME "vidgui" -#define SIP_PASSWORD "secret" -#define SIP_PORT 5080 -#define SIP_TCP 1 +#define USE_REGISTRATION 0 +#define SIP_DOMAIN "pjsip.org" +#define SIP_USERNAME "vidgui" +#define SIP_PASSWORD "secret" +#define SIP_PORT 5080 +#define SIP_TCP 1 // // NAT helper settings // -#define USE_ICE 1 -#define USE_STUN 0 -#define STUN_SRV "stun.pjsip.org" +#define USE_ICE 1 +#define USE_STUN 0 +#define STUN_SRV "stun.pjsip.org" // // Devices settings // -#define DEFAULT_CAP_DEV PJMEDIA_VID_DEFAULT_CAPTURE_DEV -//#define DEFAULT_CAP_DEV 1 -#define DEFAULT_REND_DEV PJMEDIA_VID_DEFAULT_RENDER_DEV +#define DEFAULT_CAP_DEV PJMEDIA_VID_DEFAULT_CAPTURE_DEV +//#define DEFAULT_CAP_DEV 1 +#define DEFAULT_REND_DEV PJMEDIA_VID_DEFAULT_RENDER_DEV // @@ -137,13 +136,13 @@ void MainWin::initLayout() // UI updates must be done in the UI thread! connect(this, SIGNAL(signalNewCall(int, bool)), - this, SLOT(onNewCall(int, bool))); + this, SLOT(onNewCall(int, bool))); connect(this, SIGNAL(signalCallReleased()), - this, SLOT(onCallReleased())); + this, SLOT(onCallReleased())); connect(this, SIGNAL(signalInitVideoWindow()), - this, SLOT(initVideoWindow())); + this, SLOT(initVideoWindow())); connect(this, SIGNAL(signalShowStatus(const QString&)), - this, SLOT(doShowStatus(const QString&))); + this, SLOT(doShowStatus(const QString&))); } void MainWin::quit() @@ -186,7 +185,7 @@ void MainWin::onVidEnabledChanged(int state) pjsua_call_setting call_setting; if (currentCall_ == -1) - return; + return; pjsua_call_setting_default(&call_setting); call_setting.vid_cnt = (state == Qt::Checked); @@ -207,10 +206,10 @@ void MainWin::onNewCall(int cid, bool incoming) hangupButton_->setEnabled(true); if (incoming) { - callButton_->setText(tr("Answer")); - callButton_->setEnabled(true); + callButton_->setText(tr("Answer")); + callButton_->setEnabled(true); } else { - callButton_->setEnabled(false); + callButton_->setEnabled(false); } //video_->setText(ci.remote_contact.ptr); @@ -232,44 +231,44 @@ void MainWin::onCallReleased() void MainWin::preview() { if (preview_on) { - delete video_prev_; - video_prev_ = NULL; + delete video_prev_; + video_prev_ = NULL; - pjsua_vid_preview_stop(DEFAULT_CAP_DEV); + pjsua_vid_preview_stop(DEFAULT_CAP_DEV); - showStatus("Preview stopped"); - previewButton_->setText(tr("Start &Preview")); + showStatus("Preview stopped"); + previewButton_->setText(tr("Start &Preview")); } else { - pjsua_vid_win_id wid; - pjsua_vid_win_info wi; - pjsua_vid_preview_param pre_param; - pj_status_t status; - - pjsua_vid_preview_param_default(&pre_param); - pre_param.rend_id = DEFAULT_REND_DEV; - pre_param.show = PJ_FALSE; - - status = pjsua_vid_preview_start(DEFAULT_CAP_DEV, &pre_param); - if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - QMessageBox::critical(0, "Error creating preview", errmsg); - return; - } - wid = pjsua_vid_preview_get_win(DEFAULT_CAP_DEV); - pjsua_vid_win_get_info(wid, &wi); - - video_prev_ = new VidWin(&wi.hwnd); + pjsua_vid_win_id wid; + pjsua_vid_win_info wi; + pjsua_vid_preview_param pre_param; + pj_status_t status; + + pjsua_vid_preview_param_default(&pre_param); + pre_param.rend_id = DEFAULT_REND_DEV; + pre_param.show = PJ_FALSE; + + status = pjsua_vid_preview_start(DEFAULT_CAP_DEV, &pre_param); + if (status != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + QMessageBox::critical(0, "Error creating preview", errmsg); + return; + } + wid = pjsua_vid_preview_get_win(DEFAULT_CAP_DEV); + pjsua_vid_win_get_info(wid, &wi); + + video_prev_ = new VidWin(&wi.hwnd); video_prev_->putIntoLayout(vbox_left); - //Using this will cause SDL window to display blank - //screen sometimes, probably because it's using different - //X11 Display - //status = pjsua_vid_win_set_show(wid, PJ_TRUE); - //This is handled by VidWin now - //video_prev_->show_sdl(); - showStatus("Preview started"); - - previewButton_->setText(tr("Stop &Preview")); + //Using this will cause SDL window to display blank + //screen sometimes, probably because it's using different + //X11 Display + //status = pjsua_vid_win_set_show(wid, PJ_TRUE); + //This is handled by VidWin now + //video_prev_->show_sdl(); + showStatus("Preview started"); + + previewButton_->setText(tr("Stop &Preview")); } preview_on = !preview_on; } @@ -278,35 +277,35 @@ void MainWin::preview() void MainWin::call() { if (callButton_->text() == "Answer") { - pjsua_call_setting call_setting; + pjsua_call_setting call_setting; - pj_assert(currentCall_ != -1); + pj_assert(currentCall_ != -1); - pjsua_call_setting_default(&call_setting); - call_setting.vid_cnt = (vidEnabled_->checkState()==Qt::Checked); + pjsua_call_setting_default(&call_setting); + call_setting.vid_cnt = (vidEnabled_->checkState()==Qt::Checked); - pjsua_call_answer2(currentCall_, &call_setting, 200, NULL, NULL); - callButton_->setEnabled(false); + pjsua_call_answer2(currentCall_, &call_setting, 200, NULL, NULL); + callButton_->setEnabled(false); } else { - pj_status_t status; - QString dst = url_->text(); - char uri[256]; - pjsua_call_setting call_setting; + pj_status_t status; + QString dst = url_->text(); + char uri[256]; + pjsua_call_setting call_setting; - pj_ansi_strncpy(uri, dst.toUtf8().data(), sizeof(uri)); - pj_str_t uri2 = pj_str((char*)uri); + pj_ansi_strncpy(uri, dst.toUtf8().data(), sizeof(uri)); + pj_str_t uri2 = pj_str((char*)uri); - pj_assert(currentCall_ == -1); + pj_assert(currentCall_ == -1); - pjsua_call_setting_default(&call_setting); - call_setting.vid_cnt = (vidEnabled_->checkState()==Qt::Checked); + pjsua_call_setting_default(&call_setting); + call_setting.vid_cnt = (vidEnabled_->checkState()==Qt::Checked); - status = pjsua_call_make_call(accountId_, &uri2, &call_setting, - NULL, NULL, ¤tCall_); - if (status != PJ_SUCCESS) { - showError("make call", status); - return; - } + status = pjsua_call_make_call(accountId_, &uri2, &call_setting, + NULL, NULL, ¤tCall_); + if (status != PJ_SUCCESS) { + showError("make call", status); + return; + } } } @@ -325,24 +324,24 @@ void MainWin::initVideoWindow() unsigned i; if (currentCall_ == -1) - return; + return; delete video_; video_ = NULL; pjsua_call_get_info(currentCall_, &ci); for (i = 0; i < ci.media_cnt; ++i) { - if ((ci.media[i].type == PJMEDIA_TYPE_VIDEO) && - (ci.media[i].dir & PJMEDIA_DIR_DECODING)) - { - pjsua_vid_win_info wi; - pjsua_vid_win_get_info(ci.media[i].stream.vid.win_in, &wi); + if ((ci.media[i].type == PJMEDIA_TYPE_VIDEO) && + (ci.media[i].dir & PJMEDIA_DIR_DECODING)) + { + pjsua_vid_win_info wi; + pjsua_vid_win_get_info(ci.media[i].stream.vid.win_in, &wi); - video_= new VidWin(&wi.hwnd); + video_= new VidWin(&wi.hwnd); video_->putIntoLayout(vbox_left); - break; - } + break; + } } } @@ -356,24 +355,24 @@ void MainWin::on_reg_state(pjsua_acc_id acc_id) char status[120]; if (!info.has_registration) { - pj_ansi_snprintf(reg_status, sizeof(reg_status), "%.*s", - (int)info.status_text.slen, - info.status_text.ptr); + pj_ansi_snprintf(reg_status, sizeof(reg_status), "%.*s", + (int)info.status_text.slen, + info.status_text.ptr); } else { - pj_ansi_snprintf(reg_status, sizeof(reg_status), - "%d/%.*s (expires=%d)", - info.status, - (int)info.status_text.slen, - info.status_text.ptr, - info.expires); + pj_ansi_snprintf(reg_status, sizeof(reg_status), + "%d/%.*s (expires=%d)", + info.status, + (int)info.status_text.slen, + info.status_text.ptr, + info.expires); } snprintf(status, sizeof(status), - "%.*s: %s\n", - (int)info.acc_uri.slen, info.acc_uri.ptr, - reg_status); + "%.*s: %s\n", + (int)info.acc_uri.slen, info.acc_uri.ptr, + reg_status); showStatus(status); } @@ -386,21 +385,21 @@ void MainWin::on_call_state(pjsua_call_id call_id, pjsip_event *e) pjsua_call_get_info(call_id, &ci); if (currentCall_ == -1 && ci.state < PJSIP_INV_STATE_DISCONNECTED && - ci.role == PJSIP_ROLE_UAC) + ci.role == PJSIP_ROLE_UAC) { - emit signalNewCall(call_id, false); + emit signalNewCall(call_id, false); } char status[80]; if (ci.state == PJSIP_INV_STATE_DISCONNECTED) { - snprintf(status, sizeof(status), "Call is %s (%s)", - ci.state_text.ptr, - ci.last_status_text.ptr); - showStatus(status); - emit signalCallReleased(); + snprintf(status, sizeof(status), "Call is %s (%s)", + ci.state_text.ptr, + ci.last_status_text.ptr); + showStatus(status); + emit signalCallReleased(); } else { - snprintf(status, sizeof(status), "Call is %s", pjsip_inv_state_name(ci.state)); - showStatus(status); + snprintf(status, sizeof(status), "Call is %s", pjsip_inv_state_name(ci.state)); + showStatus(status); } } @@ -411,8 +410,8 @@ void MainWin::on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, PJ_UNUSED_ARG(rdata); if (currentCall_ != -1) { - pjsua_call_answer(call_id, PJSIP_SC_BUSY_HERE, NULL, NULL); - return; + pjsua_call_answer(call_id, PJSIP_SC_BUSY_HERE, NULL, NULL); + return; } emit signalNewCall(call_id, true); @@ -433,18 +432,18 @@ void MainWin::on_call_media_state(pjsua_call_id call_id) pjsua_call_get_info(call_id, &ci); for (unsigned i=0; isetText(acc_cfg.id.ptr); @@ -597,8 +596,8 @@ bool MainWin::initStack() showStatus("Starting stack.."); status = pjsua_start(); if (status != PJ_SUCCESS) { - showError("pjsua_start", status); - goto on_error; + showError("pjsua_start", status); + goto on_error; } showStatus("Ready"); @@ -623,35 +622,35 @@ static void simple_registrar(pjsip_rx_data *rdata) pj_status_t status; status = pjsip_endpt_create_response(pjsua_get_pjsip_endpt(), - rdata, 200, NULL, &tdata); + rdata, 200, NULL, &tdata); if (status != PJ_SUCCESS) - return; + return; exp = (pjsip_expires_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL); + pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL); h = rdata->msg_info.msg->hdr.next; while (h != &rdata->msg_info.msg->hdr) { - if (h->type == PJSIP_H_CONTACT) { - const pjsip_contact_hdr *c = (const pjsip_contact_hdr*)h; - int e = c->expires; - - if (e < 0) { - if (exp) - e = exp->ivalue; - else - e = 3600; - } - - if (e > 0) { - pjsip_contact_hdr *nc = (pjsip_contact_hdr*) - pjsip_hdr_clone(tdata->pool, h); - nc->expires = e; - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)nc); - ++cnt; - } - } - h = h->next; + if (h->type == PJSIP_H_CONTACT) { + const pjsip_contact_hdr *c = (const pjsip_contact_hdr*)h; + int e = c->expires; + + if (e < 0) { + if (exp) + e = exp->ivalue; + else + e = 3600; + } + + if (e > 0) { + pjsip_contact_hdr *nc = (pjsip_contact_hdr*) + pjsip_hdr_clone(tdata->pool, h); + nc->expires = e; + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)nc); + ++cnt; + } + } + h = h->next; } srv = pjsip_generic_string_hdr_create(tdata->pool, NULL, NULL); @@ -671,8 +670,8 @@ static pj_bool_t default_mod_on_rx_request(pjsip_rx_data *rdata) if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_register_method) == 0) { - simple_registrar(rdata); - return PJ_TRUE; + simple_registrar(rdata); + return PJ_TRUE; } return PJ_FALSE; @@ -681,19 +680,19 @@ static pj_bool_t default_mod_on_rx_request(pjsip_rx_data *rdata) /* The module instance. */ static pjsip_module mod_default_handler = { - NULL, NULL, /* prev, next. */ - { (char*)"mod-default-handler", 19 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION+99, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &default_mod_on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { (char*)"mod-default-handler", 19 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION+99, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &default_mod_on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -703,12 +702,12 @@ int main(int argc, char *argv[]) * creating/initializing QApplication, otherwise we'll segfault miserably * in SDL_CreateWindow(). Here's a stack trace if you're interested: - Thread [7] (Suspended: Signal 'SIGSEGV' received. Description: Segmentation fault.) - 13 XCreateIC() - 12 SetupWindowData() - 11 X11_CreateWindow() - 10 SDL_CreateWindow() - .. + Thread [7] (Suspended: Signal 'SIGSEGV' received. Description: Segmentation fault.) + 13 XCreateIC() + 12 SetupWindowData() + 11 X11_CreateWindow() + 10 SDL_CreateWindow() + .. */ if ( SDL_InitSubSystem(SDL_INIT_VIDEO) < 0 ) { printf("Unable to init SDL: %s\n", SDL_GetError()); @@ -721,14 +720,14 @@ int main(int argc, char *argv[]) win.show(); if (!win.initStack()) { - win.quit(); - return 1; + win.quit(); + return 1; } /* We want to be registrar too! */ if (pjsua_get_pjsip_endpt()) { - pjsip_endpt_register_module(pjsua_get_pjsip_endpt(), - &mod_default_handler); + pjsip_endpt_register_module(pjsua_get_pjsip_endpt(), + &mod_default_handler); } return app.exec(); diff --git a/pjsip-apps/src/vidgui/vidgui.h b/pjsip-apps/src/vidgui/vidgui.h index 1cc27462f0..b192107123 100644 --- a/pjsip-apps/src/vidgui/vidgui.h +++ b/pjsip-apps/src/vidgui/vidgui.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011-2011 Teluu Inc. (http://www.teluu.com) * @@ -81,9 +80,9 @@ public slots: private: QPushButton *callButton_, - *hangupButton_, - *quitButton_, - *previewButton_; + *hangupButton_, + *quitButton_, + *previewButton_; QCheckBox *vidEnabled_; QLineEdit *url_; VidWin *video_; diff --git a/pjsip-apps/src/vidgui/vidwin.cpp b/pjsip-apps/src/vidgui/vidwin.cpp index 6f36e744dd..44d0fbd723 100644 --- a/pjsip-apps/src/vidgui/vidwin.cpp +++ b/pjsip-apps/src/vidgui/vidwin.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011 Teluu Inc. (http://www.teluu.com) * @@ -19,12 +18,12 @@ #include "vidwin.h" #include -#define THIS_FILE "vidwin.cpp" -#define TRACE_(...) PJ_LOG(4,(THIS_FILE, __VA_ARGS__)) +#define THIS_FILE "vidwin.cpp" +#define TRACE_(...) PJ_LOG(4,(THIS_FILE, __VA_ARGS__)) VidWin::VidWin(const pjmedia_vid_dev_hwnd *hwnd_, - QWidget* parent, - Qt::WindowFlags f) : + QWidget* parent, + Qt::WindowFlags f) : QWidget(parent, f), orig_parent(NULL), size_hint(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX) { @@ -40,7 +39,7 @@ VidWin::VidWin(const pjmedia_vid_dev_hwnd *hwnd_, pj_bzero(&hwnd, sizeof(hwnd)); if (hwnd_) { - hwnd = *hwnd_; + hwnd = *hwnd_; } } @@ -63,34 +62,34 @@ bool VidWin::event(QEvent *e) switch(e->type()) { case QEvent::Resize: - set_size(); - break; + set_size(); + break; case QEvent::ParentChange: - get_size(); - if (0) { - QRect qr = rect(); - if (qr.width() > size_hint.width()) - size_hint.setWidth(qr.width()); - if (qr.height() > size_hint.height()) - size_hint.setWidth(qr.height()); - } - setFixedSize(size_hint); - attach(); - break; + get_size(); + if (0) { + QRect qr = rect(); + if (qr.width() > size_hint.width()) + size_hint.setWidth(qr.width()); + if (qr.height() > size_hint.height()) + size_hint.setWidth(qr.height()); + } + setFixedSize(size_hint); + attach(); + break; case QEvent::Show: - show_sdl(true); - // revert to default size hint, make it resizable - setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); - break; + show_sdl(true); + // revert to default size hint, make it resizable + setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); + break; case QEvent::Hide: - show_sdl(false); - break; + show_sdl(false); + break; default: - break; + break; } return QWidget::event(e); @@ -142,7 +141,7 @@ void VidWin::get_size() HWND w = (HWND)hwnd.info.win.hwnd; RECT r; if (GetWindowRect(w, &r)) - size_hint = QSize(r.right-r.left+1, r.bottom-r.top+1); + size_hint = QSize(r.right-r.left+1, r.bottom-r.top+1); TRACE_("%p size = %dx%d", w, size_hint.width(), size_hint.height()); } @@ -237,8 +236,8 @@ void VidWin::show_sdl(bool visible) #include #include -#define GET_DISPLAY() QX11Info::display() -//#define GET_DISPLAY() (Display*)hwnd.info.x11.display +#define GET_DISPLAY() QX11Info::display() +//#define GET_DISPLAY() (Display*)hwnd.info.x11.display void VidWin::attach() { @@ -254,7 +253,7 @@ void VidWin::attach() Window parent = (Window)this->winId(); int err = XReparentWindow(d, w, parent, 0, 0); TRACE_("%p new parent handle = %p, err = %d", - (void*)w,(void*)parent, err); + (void*)w,(void*)parent, err); } @@ -274,7 +273,7 @@ void VidWin::set_size() int err = XResizeWindow(d, w, qr.width(), qr.height()); TRACE_("[%p,%p] new size = %dx%d, err = %d", - (void*)d, (void*)w, qr.width(), qr.height(), err); + (void*)d, (void*)w, qr.width(), qr.height(), err); } void VidWin::get_size() @@ -298,9 +297,9 @@ void VidWin::show_sdl(bool visible) Window w = (Window)hwnd.info.x11.window; if (visible) { - XMapRaised(d, w); + XMapRaised(d, w); } else { - XUnmapWindow(d, w); + XUnmapWindow(d, w); } XFlush(d); diff --git a/pjsip-apps/src/vidgui/vidwin.h b/pjsip-apps/src/vidgui/vidwin.h index 8ab4a76d09..abb221c2b8 100644 --- a/pjsip-apps/src/vidgui/vidwin.h +++ b/pjsip-apps/src/vidgui/vidwin.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011 Teluu Inc. (http://www.teluu.com) * @@ -29,8 +28,8 @@ class VidWin : public QWidget public: VidWin(const pjmedia_vid_dev_hwnd *hwnd, - QWidget* parent = 0, - Qt::WindowFlags f = 0); + QWidget* parent = 0, + Qt::WindowFlags f = 0); virtual ~VidWin(); QSize sizeHint() const { return size_hint; } diff --git a/pjsip/docs/doxygen.h b/pjsip/docs/doxygen.h index 7ce01bfdc2..236d13d7e5 100644 --- a/pjsip/docs/doxygen.h +++ b/pjsip/docs/doxygen.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,7 +24,7 @@ /*////////////////////////////////////////////////////////////////////////// */ /* - INTRODUCTION PAGE + INTRODUCTION PAGE */ /** diff --git a/pjsip/include/pjsip-simple/errno.h b/pjsip/include/pjsip-simple/errno.h index 62927ca94e..938f7c336b 100644 --- a/pjsip/include/pjsip-simple/errno.h +++ b/pjsip/include/pjsip-simple/errno.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -37,12 +36,12 @@ PJ_BEGIN_DECL * @hideinitializer * No event package with the specified name. */ -#define PJSIP_SIMPLE_ENOPKG (PJSIP_SIMPLE_ERRNO_START+1) /*270001*/ +#define PJSIP_SIMPLE_ENOPKG (PJSIP_SIMPLE_ERRNO_START+1) /*270001*/ /** * @hideinitializer * Event package already exists. */ -#define PJSIP_SIMPLE_EPKGEXISTS (PJSIP_SIMPLE_ERRNO_START+2) /*270002*/ +#define PJSIP_SIMPLE_EPKGEXISTS (PJSIP_SIMPLE_ERRNO_START+2) /*270002*/ /************************************************************ @@ -72,17 +71,17 @@ PJ_BEGIN_DECL * @hideinitializer * Bad PIDF Message */ -#define PJSIP_SIMPLE_EBADPIDF (PJSIP_SIMPLE_ERRNO_START+24) /*270024*/ +#define PJSIP_SIMPLE_EBADPIDF (PJSIP_SIMPLE_ERRNO_START+24) /*270024*/ /** * @hideinitializer * Bad XPIDF Message */ -#define PJSIP_SIMPLE_EBADXPIDF (PJSIP_SIMPLE_ERRNO_START+25) /*270025*/ +#define PJSIP_SIMPLE_EBADXPIDF (PJSIP_SIMPLE_ERRNO_START+25) /*270025*/ /** * @hideinitializer * Bad RPID Message */ -#define PJSIP_SIMPLE_EBADRPID (PJSIP_SIMPLE_ERRNO_START+26) /*270026*/ +#define PJSIP_SIMPLE_EBADRPID (PJSIP_SIMPLE_ERRNO_START+26) /*270026*/ /************************************************************ @@ -105,14 +104,14 @@ PJ_BEGIN_DECL * @param buffer The buffer where to put the error message. * @param bufsize Size of the buffer. * - * @return The error message as NULL terminated string, + * @return The error message as NULL terminated string, * wrapped with pj_str_t. */ PJ_DECL(pj_str_t) pjsipsimple_strerror(pj_status_t status, - char *buffer, pj_size_t bufsize); + char *buffer, pj_size_t bufsize); PJ_END_DECL -#endif /* __PJSIP_SIMPLE_ERRNO_H__ */ +#endif /* __PJSIP_SIMPLE_ERRNO_H__ */ diff --git a/pjsip/include/pjsip-simple/evsub.h b/pjsip/include/pjsip-simple/evsub.h index 5be9eaa9bb..6c30f03ab6 100644 --- a/pjsip/include/pjsip-simple/evsub.h +++ b/pjsip/include/pjsip-simple/evsub.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -60,16 +59,16 @@ typedef struct pjsip_evsub pjsip_evsub; */ typedef enum pjsip_evsub_state { - PJSIP_EVSUB_STATE_NULL, /**< State is NULL. */ - PJSIP_EVSUB_STATE_SENT, /**< Client has sent SUBSCRIBE request. */ - PJSIP_EVSUB_STATE_ACCEPTED, /**< 2xx response to SUBSCRIBE has been - sent/received. */ - PJSIP_EVSUB_STATE_PENDING, /**< Subscription is pending. */ - PJSIP_EVSUB_STATE_ACTIVE, /**< Subscription is active. */ - PJSIP_EVSUB_STATE_TERMINATED,/**< Subscription is terminated. */ - PJSIP_EVSUB_STATE_UNKNOWN, /**< Subscription state can not be determined. - Application can query the state by - calling #pjsip_evsub_get_state_name().*/ + PJSIP_EVSUB_STATE_NULL, /**< State is NULL. */ + PJSIP_EVSUB_STATE_SENT, /**< Client has sent SUBSCRIBE request. */ + PJSIP_EVSUB_STATE_ACCEPTED, /**< 2xx response to SUBSCRIBE has been + sent/received. */ + PJSIP_EVSUB_STATE_PENDING, /**< Subscription is pending. */ + PJSIP_EVSUB_STATE_ACTIVE, /**< Subscription is active. */ + PJSIP_EVSUB_STATE_TERMINATED,/**< Subscription is terminated. */ + PJSIP_EVSUB_STATE_UNKNOWN, /**< Subscription state can not be determined. + Application can query the state by + calling #pjsip_evsub_get_state_name().*/ } pjsip_evsub_state; @@ -100,22 +99,22 @@ struct pjsip_evsub_user * * This callback is OPTIONAL. * - * @param sub The subscription instance. - * @param event The event that has caused the state to change, - * which may be NULL or may have type other than - * PJSIP_EVENT_TSX_STATE. + * @param sub The subscription instance. + * @param event The event that has caused the state to change, + * which may be NULL or may have type other than + * PJSIP_EVENT_TSX_STATE. */ void (*on_evsub_state)( pjsip_evsub *sub, pjsip_event *event); /** * This callback is called when transaction state has changed. * - * @param sub The subscription instance. - * @param tsx Transaction. - * @param event The event. + * @param sub The subscription instance. + * @param tsx Transaction. + * @param event The event. */ void (*on_tsx_state)(pjsip_evsub *sub, pjsip_transaction *tsx, - pjsip_event *event); + pjsip_event *event); /** * This callback is called when incoming SUBSCRIBE (or any method that @@ -131,25 +130,25 @@ struct pjsip_evsub_user * since this function takes care about unsubscription request and * calculates the appropriate expiration interval. * - * @param sub The subscription instance. - * @param rdata The received SUBSCRIBE request. - * @param p_st_code Application MUST set the value of this argument with - * final status code (200-699) upon returning from the - * callback. Only applicable for refresh request. For - * unsubscription, the library will always reply with - * 200. - * @param p_st_text Custom status text, if any. - * @param res_hdr Upon return, application can put additional headers - * to be sent in the response in this list. - * @param p_body Application MAY specify message body to be sent in - * the response. + * @param sub The subscription instance. + * @param rdata The received SUBSCRIBE request. + * @param p_st_code Application MUST set the value of this argument with + * final status code (200-699) upon returning from the + * callback. Only applicable for refresh request. For + * unsubscription, the library will always reply with + * 200. + * @param p_st_text Custom status text, if any. + * @param res_hdr Upon return, application can put additional headers + * to be sent in the response in this list. + * @param p_body Application MAY specify message body to be sent in + * the response. */ void (*on_rx_refresh)( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body); + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body); /** * This callback is called when client/subscriber received incoming @@ -160,23 +159,23 @@ struct pjsip_evsub_user * This callback is OPTIONAL. When it is not implemented, the default * behavior is to respond incoming NOTIFY request with 200 (OK). * - * @param sub The subscription instance. - * @param rdata The received NOTIFY request. - * @param p_st_code Application MUST set the value of this argument with - * final status code (200-699) upon returning from the - * callback. - * @param p_st_text Custom status text, if any. - * @param res_hdr Upon return, application can put additional headers - * to be sent in the response in this list. - * @param p_body Application MAY specify message body to be sent in - * the response. + * @param sub The subscription instance. + * @param rdata The received NOTIFY request. + * @param p_st_code Application MUST set the value of this argument with + * final status code (200-699) upon returning from the + * callback. + * @param p_st_text Custom status text, if any. + * @param res_hdr Upon return, application can put additional headers + * to be sent in the response in this list. + * @param p_body Application MAY specify message body to be sent in + * the response. */ void (*on_rx_notify)(pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body); + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body); /** * This callback is called when it is time for the client to refresh @@ -186,7 +185,7 @@ struct pjsip_evsub_user * refer is used; the event package will refresh subscription by sending * SUBSCRIBE with the interval set to current/last interval. * - * @param sub The subscription instance. + * @param sub The subscription instance. */ void (*on_client_refresh)(pjsip_evsub *sub); @@ -234,10 +233,10 @@ PJ_DECL(const pjsip_method*) pjsip_get_notify_method(void); * Initialize the event subscription module and register the module to the * specified endpoint. * - * @param endpt The endpoint instance. + * @param endpt The endpoint instance. * - * @return PJ_SUCCESS if module can be created and registered - * successfully. + * @return PJ_SUCCESS if module can be created and registered + * successfully. */ PJ_DECL(pj_status_t) pjsip_evsub_init_module(pjsip_endpoint *endpt); @@ -246,7 +245,7 @@ PJ_DECL(pj_status_t) pjsip_evsub_init_module(pjsip_endpoint *endpt); * Get the event subscription module instance that was previously created * and registered to endpoint. * - * @return The event subscription module instance. + * @return The event subscription module instance. */ PJ_DECL(pjsip_module*) pjsip_evsub_instance(void); @@ -254,70 +253,70 @@ PJ_DECL(pjsip_module*) pjsip_evsub_instance(void); /** * Register event package to the event subscription framework. * - * @param pkg_mod The module that implements the event package being - * registered. - * @param event_name Event package identification. - * @param expires Default subscription expiration time, in seconds. - * @param accept_cnt Number of strings in Accept array. The value must - * not be greater than PJSIP_GENERIC_ARRAY_MAX_COUNT. - * @param accept Array of Accept value. + * @param pkg_mod The module that implements the event package being + * registered. + * @param event_name Event package identification. + * @param expires Default subscription expiration time, in seconds. + * @param accept_cnt Number of strings in Accept array. The value must + * not be greater than PJSIP_GENERIC_ARRAY_MAX_COUNT. + * @param accept Array of Accept value. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_evsub_register_pkg( pjsip_module *pkg_mod, - const pj_str_t *event_name, - unsigned expires, - unsigned accept_cnt, - const pj_str_t accept[]); + const pj_str_t *event_name, + unsigned expires, + unsigned accept_cnt, + const pj_str_t accept[]); /** * Get the Allow-Events header. This header is built based on the packages * that are registered to the evsub module. * - * @param m Pointer to event subscription module instance, or - * NULL to use default instance (equal to - * #pjsip_evsub_instance()). + * @param m Pointer to event subscription module instance, or + * NULL to use default instance (equal to + * #pjsip_evsub_instance()). * - * @return The Allow-Events header. + * @return The Allow-Events header. */ PJ_DECL(const pjsip_hdr*) pjsip_evsub_get_allow_events_hdr( - const pjsip_module *m); + const pjsip_module *m); /** * Create client subscription session. * - * @param dlg The underlying dialog to use. - * @param user_cb Callback to receive event subscription notifications. - * @param event Event name. - * @param option Bitmask of options. - * @param p_evsub Pointer to receive event subscription instance. + * @param dlg The underlying dialog to use. + * @param user_cb Callback to receive event subscription notifications. + * @param event Event name. + * @param option Bitmask of options. + * @param p_evsub Pointer to receive event subscription instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_evsub_create_uac( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - const pj_str_t *event, - unsigned option, - pjsip_evsub **p_evsub); + const pjsip_evsub_user *user_cb, + const pj_str_t *event, + unsigned option, + pjsip_evsub **p_evsub); /** * Create server subscription session. * - * @param dlg The underlying dialog to use. - * @param user_cb Callback to receive event subscription notifications. - * @param rdata The incoming request that creates the event - * subscription, such as SUBSCRIBE or REFER. - * @param option Bitmask of options. - * @param p_evsub Pointer to receive event subscription instance. + * @param dlg The underlying dialog to use. + * @param user_cb Callback to receive event subscription notifications. + * @param rdata The incoming request that creates the event + * subscription, such as SUBSCRIBE or REFER. + * @param option Bitmask of options. + * @param p_evsub Pointer to receive event subscription instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_evsub_create_uas( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - pjsip_rx_data *rdata, - unsigned option, - pjsip_evsub **p_evsub); + const pjsip_evsub_user *user_cb, + pjsip_rx_data *rdata, + unsigned option, + pjsip_evsub **p_evsub); /** * Forcefully destroy the subscription session. This function should only @@ -325,22 +324,22 @@ PJ_DECL(pj_status_t) pjsip_evsub_create_uas( pjsip_dialog *dlg, * initialization has failed. For other conditions, application MUST terminate * the subscription by sending the appropriate un(SUBSCRIBE) or NOTIFY. * - * @param sub The event subscription. - * @param notify Specify whether the state notification callback - * should be called. + * @param sub The event subscription. + * @param notify Specify whether the state notification callback + * should be called. * - * @return PJ_SUCCESS if subscription session has been destroyed. + * @return PJ_SUCCESS if subscription session has been destroyed. */ PJ_DECL(pj_status_t) pjsip_evsub_terminate( pjsip_evsub *sub, - pj_bool_t notify ); + pj_bool_t notify ); /** * Get subscription state. * - * @param sub Event subscription instance. + * @param sub Event subscription instance. * - * @return Subscription state. + * @return Subscription state. */ PJ_DECL(pjsip_evsub_state) pjsip_evsub_get_state(const pjsip_evsub *sub); @@ -348,9 +347,9 @@ PJ_DECL(pjsip_evsub_state) pjsip_evsub_get_state(const pjsip_evsub *sub); /** * Get the string representation of the subscription state. * - * @param sub Event subscription instance. + * @param sub Event subscription instance. * - * @return NULL terminated string. + * @return NULL terminated string. */ PJ_DECL(const char*) pjsip_evsub_get_state_name(const pjsip_evsub *sub); @@ -359,20 +358,20 @@ PJ_DECL(const char*) pjsip_evsub_get_state_name(const pjsip_evsub *sub); * Get subscription termination reason, if any. If remote did not * send termination reason, this function will return empty string. * - * @param sub Event subscription instance. + * @param sub Event subscription instance. * - * @return NULL terminated string. + * @return NULL terminated string. */ PJ_DECL(const pj_str_t*) pjsip_evsub_get_termination_reason( - const pjsip_evsub *sub); + const pjsip_evsub *sub); /** * Get subscription expiration time. * - * @param sub Event subscription instance. + * @param sub Event subscription instance. * - * @return Subscription expiration time, in seconds. + * @return Subscription expiration time, in seconds. */ PJ_DECL(pj_uint32_t) pjsip_evsub_get_expires(const pjsip_evsub *sub); @@ -381,87 +380,87 @@ PJ_DECL(pj_uint32_t) pjsip_evsub_get_expires(const pjsip_evsub *sub); * Call this function to create request to initiate subscription, to * refresh subcription, or to request subscription termination. * - * @param sub Client subscription instance. - * @param method The method that establishes the subscription, such as - * SUBSCRIBE or REFER. If this argument is NULL, then - * SUBSCRIBE will be used. - * @param expires Subscription expiration. If the value is set to zero, - * this will request unsubscription. If the value is - * PJSIP_EXPIRES_NOT_SPECIFIED, default expiration - * as defined by the package will be used. - * @param p_tdata Pointer to receive the request. + * @param sub Client subscription instance. + * @param method The method that establishes the subscription, such as + * SUBSCRIBE or REFER. If this argument is NULL, then + * SUBSCRIBE will be used. + * @param expires Subscription expiration. If the value is set to zero, + * this will request unsubscription. If the value is + * PJSIP_EXPIRES_NOT_SPECIFIED, default expiration + * as defined by the package will be used. + * @param p_tdata Pointer to receive the request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_evsub_initiate( pjsip_evsub *sub, - const pjsip_method *method, - pj_uint32_t expires, - pjsip_tx_data **p_tdata); + const pjsip_method *method, + pj_uint32_t expires, + pjsip_tx_data **p_tdata); /** * Add a list of headers to the subscription instance. The list of headers * will be added to outgoing presence subscription requests. * - * @param sub Subscription instance. - * @param hdr_list List of headers to be added. + * @param sub Subscription instance. + * @param hdr_list List of headers to be added. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_evsub_add_header( pjsip_evsub *sub, - const pjsip_hdr *hdr_list ); + const pjsip_hdr *hdr_list ); /** * Accept the incoming subscription request by sending 2xx response to * incoming SUBSCRIBE request. * - * @param sub Server subscription instance. - * @param rdata The incoming subscription request message. - * @param st_code Status code, which MUST be final response. - * @param hdr_list Optional list of headers to be added in the response. + * @param sub Server subscription instance. + * @param rdata The incoming subscription request message. + * @param st_code Status code, which MUST be final response. + * @param hdr_list Optional list of headers to be added in the response. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_evsub_accept( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int st_code, - const pjsip_hdr *hdr_list ); + pjsip_rx_data *rdata, + int st_code, + const pjsip_hdr *hdr_list ); /** * For notifier, create NOTIFY request to subscriber, and set the state * of the subscription. * - * @param sub The server subscription (notifier) instance. - * @param state New state to set. - * @param state_str The state string name, if state contains value other - * than active, pending, or terminated. Otherwise this - * argument is ignored. - * @param reason Specify reason if new state is terminated, otherwise - * put NULL. - * @param p_tdata Pointer to receive request message. + * @param sub The server subscription (notifier) instance. + * @param state New state to set. + * @param state_str The state string name, if state contains value other + * than active, pending, or terminated. Otherwise this + * argument is ignored. + * @param reason Specify reason if new state is terminated, otherwise + * put NULL. + * @param p_tdata Pointer to receive request message. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_evsub_notify( pjsip_evsub *sub, - pjsip_evsub_state state, - const pj_str_t *state_str, - const pj_str_t *reason, - pjsip_tx_data **p_tdata); + pjsip_evsub_state state, + const pj_str_t *state_str, + const pj_str_t *reason, + pjsip_tx_data **p_tdata); /** * For notifier, create a NOTIFY request that reflects current subscription * status. * - * @param sub The server subscription instance. - * @param p_tdata Pointer to receive the request messge. + * @param sub The server subscription instance. + * @param p_tdata Pointer to receive the request messge. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_evsub_current_notify( pjsip_evsub *sub, - pjsip_tx_data **p_tdata ); + pjsip_tx_data **p_tdata ); @@ -471,13 +470,13 @@ PJ_DECL(pj_status_t) pjsip_evsub_current_notify( pjsip_evsub *sub, * functions, e.g. authentication. But the request MUST be either request * that creates/refresh subscription or NOTIFY request. * - * @param sub The event subscription object. - * @param tdata Request message to be send. + * @param sub The event subscription object. + * @param tdata Request message to be send. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_evsub_send_request( pjsip_evsub *sub, - pjsip_tx_data *tdata); + pjsip_tx_data *tdata); @@ -485,10 +484,10 @@ PJ_DECL(pj_status_t) pjsip_evsub_send_request( pjsip_evsub *sub, * Get the event subscription instance associated with the specified * transaction. * - * @param tsx The transaction. + * @param tsx The transaction. * - * @return The event subscription instance registered in the - * transaction, if any. + * @return The event subscription instance registered in the + * transaction, if any. */ PJ_DECL(pjsip_evsub*) pjsip_tsx_get_evsub(const pjsip_transaction *tsx); @@ -496,32 +495,32 @@ PJ_DECL(pjsip_evsub*) pjsip_tsx_get_evsub(const pjsip_transaction *tsx); /** * Set event subscription's module data. * - * @param sub The event subscription. - * @param mod_id The module id. - * @param data Arbitrary data. + * @param sub The event subscription. + * @param mod_id The module id. + * @param data Arbitrary data. */ PJ_DECL(void) pjsip_evsub_set_mod_data( pjsip_evsub *sub, unsigned mod_id, - void *data ); + void *data ); /** * Get event subscription's module data. * - * @param sub The event subscription. - * @param mod_id The module id. + * @param sub The event subscription. + * @param mod_id The module id. * - * @return Data previously set at the specified id. + * @return Data previously set at the specified id. */ PJ_DECL(void*) pjsip_evsub_get_mod_data( const pjsip_evsub *sub, - unsigned mod_id ); + unsigned mod_id ); /** * Increment the event subscription's group lock. * - * @param sub The server subscription instance. + * @param sub The server subscription instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DEF(pj_status_t) pjsip_evsub_add_ref(pjsip_evsub *sub); @@ -529,9 +528,9 @@ PJ_DEF(pj_status_t) pjsip_evsub_add_ref(pjsip_evsub *sub); /** * Decrement the event subscription's group lock. * - * @param sub The server subscription instance. + * @param sub The server subscription instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DEF(pj_status_t) pjsip_evsub_dec_ref(pjsip_evsub *sub); @@ -550,7 +549,7 @@ PJ_DEF(pj_status_t) pjsip_evsub_dec_ref(pjsip_evsub *sub); * @param seconds The new timeout. */ PJ_DEF(void) pjsip_evsub_uas_set_timeout(pjsip_evsub *sub, - pj_uint32_t seconds); + pj_uint32_t seconds); PJ_END_DECL @@ -559,4 +558,4 @@ PJ_END_DECL * @} */ -#endif /* __PJSIP_SIMPLE_EVSUB_H__ */ +#endif /* __PJSIP_SIMPLE_EVSUB_H__ */ diff --git a/pjsip/include/pjsip-simple/evsub_msg.h b/pjsip/include/pjsip-simple/evsub_msg.h index f6f8aa62f5..9aec582688 100644 --- a/pjsip/include/pjsip-simple/evsub_msg.h +++ b/pjsip/include/pjsip-simple/evsub_msg.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,7 +35,7 @@ PJ_BEGIN_DECL /** Max events in Allow-Events header. */ -#define PJSIP_MAX_ALLOW_EVENTS 16 +#define PJSIP_MAX_ALLOW_EVENTS 16 /** * This structure describes Event header. @@ -46,17 +45,17 @@ typedef struct pjsip_event_hdr /** Standard header fields. */ PJSIP_DECL_HDR_MEMBER(struct pjsip_event_hdr); - pj_str_t event_type; /**< Event name. */ - pj_str_t id_param; /**< Optional event ID parameter. */ - pjsip_param other_param; /**< Other parameter. */ + pj_str_t event_type; /**< Event name. */ + pj_str_t id_param; /**< Optional event ID parameter. */ + pjsip_param other_param; /**< Other parameter. */ } pjsip_event_hdr; /** * Create an Event header. * - * @param pool The pool. + * @param pool The pool. * - * @return New Event header instance. + * @return New Event header instance. */ PJ_DECL(pjsip_event_hdr*) pjsip_event_hdr_create(pj_pool_t *pool); @@ -70,9 +69,9 @@ typedef pjsip_generic_array_hdr pjsip_allow_events_hdr; /** * Create a new Allow-Events header. * - * @param pool The pool. + * @param pool The pool. * - * @return Allow-Events header. + * @return Allow-Events header. */ PJ_DECL(pjsip_allow_events_hdr*) pjsip_allow_events_hdr_create(pj_pool_t *pool); @@ -86,20 +85,20 @@ typedef struct pjsip_sub_state_hdr /** Standard header fields. */ PJSIP_DECL_HDR_MEMBER(struct pjsip_sub_state_hdr); - pj_str_t sub_state; /**< Subscription state. */ - pj_str_t reason_param; /**< Optional termination reason. */ - unsigned expires_param; /**< Expires param, or - PJSIP_EXPIRES_NOT_SPECIFIED. */ - int retry_after; /**< Retry after param, or -1. */ - pjsip_param other_param; /**< Other parameters. */ + pj_str_t sub_state; /**< Subscription state. */ + pj_str_t reason_param; /**< Optional termination reason. */ + unsigned expires_param; /**< Expires param, or + PJSIP_EXPIRES_NOT_SPECIFIED. */ + int retry_after; /**< Retry after param, or -1. */ + pjsip_param other_param; /**< Other parameters. */ } pjsip_sub_state_hdr; /** * Create new Subscription-State header. * - * @param pool The pool. + * @param pool The pool. * - * @return Subscription-State header. + * @return Subscription-State header. */ PJ_DECL(pjsip_sub_state_hdr*) pjsip_sub_state_hdr_create(pj_pool_t *pool); @@ -116,5 +115,5 @@ PJ_END_DECL * @} */ -#endif /* __PJSIP_SIMPLE_EVENT_NOTIFY_MSG_H__ */ +#endif /* __PJSIP_SIMPLE_EVENT_NOTIFY_MSG_H__ */ diff --git a/pjsip/include/pjsip-simple/iscomposing.h b/pjsip/include/pjsip-simple/iscomposing.h index 54ca2e3e5c..b5479344b0 100644 --- a/pjsip/include/pjsip-simple/iscomposing.h +++ b/pjsip/include/pjsip-simple/iscomposing.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,60 +43,60 @@ PJ_BEGIN_DECL * Create XML message with MIME type "application/im-iscomposing+xml" * to indicate the message composition status. * - * @param pool Pool to allocate memory. - * @param is_composing Message composition indication status. Set to - * PJ_TRUE (or non-zero) to indicate that application - * is currently composing an instant message. - * @param lst_actv Optional attribute to indicate time of last - * activity. If none is to be specified, the value - * MUST be set to NULL. - * @param content_tp Optional attribute to indicate the content type of - * message being composed. If none is to be specified, - * the value MUST be set to NULL. - * @param refresh Optional attribute to indicate the interval when - * next indication will be sent, only when - * is_composing is non-zero. If none is to be - * specified, the value MUST be set to -1. + * @param pool Pool to allocate memory. + * @param is_composing Message composition indication status. Set to + * PJ_TRUE (or non-zero) to indicate that application + * is currently composing an instant message. + * @param lst_actv Optional attribute to indicate time of last + * activity. If none is to be specified, the value + * MUST be set to NULL. + * @param content_tp Optional attribute to indicate the content type of + * message being composed. If none is to be specified, + * the value MUST be set to NULL. + * @param refresh Optional attribute to indicate the interval when + * next indication will be sent, only when + * is_composing is non-zero. If none is to be + * specified, the value MUST be set to -1. * - * @return An XML message containing the message indication. - * NULL will be returned when there's not enough - * memory to allocate the message. + * @return An XML message containing the message indication. + * NULL will be returned when there's not enough + * memory to allocate the message. */ PJ_DECL(pj_xml_node*) pjsip_iscomposing_create_xml(pj_pool_t *pool, - pj_bool_t is_composing, - const pj_time_val *lst_actv, - const pj_str_t *content_tp, - int refresh); + pj_bool_t is_composing, + const pj_time_val *lst_actv, + const pj_str_t *content_tp, + int refresh); /** * Create message body with Content-Type "application/im-iscomposing+xml" * to indicate the message composition status. * - * @param pool Pool to allocate memory. - * @param is_composing Message composition indication status. Set to - * PJ_TRUE (or non-zero) to indicate that application - * is currently composing an instant message. - * @param lst_actv Optional attribute to indicate time of last - * activity. If none is to be specified, the value - * MUST be set to NULL. - * @param content_tp Optional attribute to indicate the content type of - * message being composed. If none is to be specified, - * the value MUST be set to NULL. - * @param refresh Optional attribute to indicate the interval when - * next indication will be sent, only when - * is_composing is non-zero. If none is to be - * specified, the value MUST be set to -1. + * @param pool Pool to allocate memory. + * @param is_composing Message composition indication status. Set to + * PJ_TRUE (or non-zero) to indicate that application + * is currently composing an instant message. + * @param lst_actv Optional attribute to indicate time of last + * activity. If none is to be specified, the value + * MUST be set to NULL. + * @param content_tp Optional attribute to indicate the content type of + * message being composed. If none is to be specified, + * the value MUST be set to NULL. + * @param refresh Optional attribute to indicate the interval when + * next indication will be sent, only when + * is_composing is non-zero. If none is to be + * specified, the value MUST be set to -1. * - * @return The SIP message body containing XML message - * indication. NULL will be returned when there's not - * enough memory to allocate the message. + * @return The SIP message body containing XML message + * indication. NULL will be returned when there's not + * enough memory to allocate the message. */ PJ_DECL(pjsip_msg_body*) pjsip_iscomposing_create_body( pj_pool_t *pool, - pj_bool_t is_composing, - const pj_time_val *lst_actv, - const pj_str_t *content_tp, - int refresh); + pj_bool_t is_composing, + const pj_time_val *lst_actv, + const pj_str_t *content_tp, + int refresh); /** @@ -107,23 +106,23 @@ PJ_DECL(pjsip_msg_body*) pjsip_iscomposing_create_body( pj_pool_t *pool, * Note that the input string buffer MUST be NULL terminated and have * length at least len+1 (len MUST NOT include the NULL terminator). * - * @param pool Pool to allocate memory for the parsing process. - * @param msg The message to be parsed, MUST be NULL terminated. - * @param len Length of the message, excluding NULL terminator. + * @param pool Pool to allocate memory for the parsing process. + * @param msg The message to be parsed, MUST be NULL terminated. + * @param len Length of the message, excluding NULL terminator. * @param p_is_composing Optional pointer to receive iscomposing status. - * @param p_last_active Optional pointer to receive last active attribute. + * @param p_last_active Optional pointer to receive last active attribute. * @param p_content_type Optional pointer to receive content type attribute. - * @param p_refresh Optional pointer to receive refresh time. + * @param p_refresh Optional pointer to receive refresh time. * - * @return PJ_SUCCESS if message can be successfully parsed. + * @return PJ_SUCCESS if message can be successfully parsed. */ PJ_DECL(pj_status_t) pjsip_iscomposing_parse( pj_pool_t *pool, - char *msg, - pj_size_t len, - pj_bool_t *p_is_composing, - pj_str_t **p_last_active, - pj_str_t **p_content_type, - int *p_refresh ); + char *msg, + pj_size_t len, + pj_bool_t *p_is_composing, + pj_str_t **p_last_active, + pj_str_t **p_content_type, + int *p_refresh ); /** @@ -134,5 +133,5 @@ PJ_DECL(pj_status_t) pjsip_iscomposing_parse( pj_pool_t *pool, PJ_END_DECL -#endif /* __PJSIP_SIMPLE_ISCOMPOSING_H__ */ +#endif /* __PJSIP_SIMPLE_ISCOMPOSING_H__ */ diff --git a/pjsip/include/pjsip-simple/mwi.h b/pjsip/include/pjsip-simple/mwi.h index 97fc909a06..7975b2943b 100644 --- a/pjsip/include/pjsip-simple/mwi.h +++ b/pjsip/include/pjsip-simple/mwi.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -47,58 +46,58 @@ PJ_BEGIN_DECL * Initialize the MWI module and register it as endpoint module and * package to the event subscription module. * - * @param endpt The endpoint instance. - * @param mod_evsub The event subscription module instance. + * @param endpt The endpoint instance. + * @param mod_evsub The event subscription module instance. * - * @return PJ_SUCCESS if the module is successfully - * initialized and registered to both endpoint - * and the event subscription module. + * @return PJ_SUCCESS if the module is successfully + * initialized and registered to both endpoint + * and the event subscription module. */ PJ_DECL(pj_status_t) pjsip_mwi_init_module(pjsip_endpoint *endpt, - pjsip_module *mod_evsub); + pjsip_module *mod_evsub); /** * Get the MWI module instance. * - * @return The MWI module instance. + * @return The MWI module instance. */ PJ_DECL(pjsip_module*) pjsip_mwi_instance(void); /** * Create MWI client subscription session. * - * @param dlg The underlying dialog to use. - * @param user_cb Pointer to callbacks to receive MWI subscription - * events. - * @param options Option flags. Currently only PJSIP_EVSUB_NO_EVENT_ID - * is recognized. - * @param p_evsub Pointer to receive the MWI subscription - * session. + * @param dlg The underlying dialog to use. + * @param user_cb Pointer to callbacks to receive MWI subscription + * events. + * @param options Option flags. Currently only PJSIP_EVSUB_NO_EVENT_ID + * is recognized. + * @param p_evsub Pointer to receive the MWI subscription + * session. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_mwi_create_uac( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - unsigned options, - pjsip_evsub **p_evsub ); + const pjsip_evsub_user *user_cb, + unsigned options, + pjsip_evsub **p_evsub ); /** * Create MWI server subscription session. * - * @param dlg The underlying dialog to use. - * @param user_cb Pointer to callbacks to receive MWI subscription - * events. - * @param rdata The incoming SUBSCRIBE request that creates the event - * subscription. - * @param p_evsub Pointer to receive the MWI subscription - * session. + * @param dlg The underlying dialog to use. + * @param user_cb Pointer to callbacks to receive MWI subscription + * events. + * @param rdata The incoming SUBSCRIBE request that creates the event + * subscription. + * @param p_evsub Pointer to receive the MWI subscription + * session. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_mwi_create_uas( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - pjsip_rx_data *rdata, - pjsip_evsub **p_evsub ); + const pjsip_evsub_user *user_cb, + pjsip_rx_data *rdata, + pjsip_evsub **p_evsub ); /** * Forcefully destroy the MWI subscription. This function should only @@ -106,84 +105,84 @@ PJ_DECL(pj_status_t) pjsip_mwi_create_uas( pjsip_dialog *dlg, * initialization has failed. For other conditions, application MUST terminate * the subscription by sending the appropriate un(SUBSCRIBE) or NOTIFY. * - * @param sub The MWI subscription. - * @param notify Specify whether the state notification callback - * should be called. + * @param sub The MWI subscription. + * @param notify Specify whether the state notification callback + * should be called. * - * @return PJ_SUCCESS if subscription session has been destroyed. + * @return PJ_SUCCESS if subscription session has been destroyed. */ PJ_DECL(pj_status_t) pjsip_mwi_terminate( pjsip_evsub *sub, - pj_bool_t notify ); + pj_bool_t notify ); /** * Call this function to create request to initiate MWI subscription, to * refresh subcription, or to request subscription termination. * - * @param sub Client subscription instance. - * @param expires Subscription expiration. If the value is set to zero, - * this will request unsubscription. If the value is - * PJSIP_EXPIRES_NOT_SPECIFIED, default expiration - * as defined by the package will be used. - * @param p_tdata Pointer to receive the request. + * @param sub Client subscription instance. + * @param expires Subscription expiration. If the value is set to zero, + * this will request unsubscription. If the value is + * PJSIP_EXPIRES_NOT_SPECIFIED, default expiration + * as defined by the package will be used. + * @param p_tdata Pointer to receive the request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_mwi_initiate( pjsip_evsub *sub, - pj_uint32_t expires, - pjsip_tx_data **p_tdata); + pj_uint32_t expires, + pjsip_tx_data **p_tdata); /** * Accept the incoming subscription request by sending 2xx response to * incoming SUBSCRIBE request. * - * @param sub Server subscription instance. - * @param rdata The incoming subscription request message. - * @param st_code Status code, which MUST be final response. - * @param hdr_list Optional list of headers to be added in the response. + * @param sub Server subscription instance. + * @param rdata The incoming subscription request message. + * @param st_code Status code, which MUST be final response. + * @param hdr_list Optional list of headers to be added in the response. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_mwi_accept( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int st_code, - const pjsip_hdr *hdr_list ); + pjsip_rx_data *rdata, + int st_code, + const pjsip_hdr *hdr_list ); /** * For notifier, create NOTIFY request to subscriber, and set the state * of the subscription. * - * @param sub The server subscription (notifier) instance. - * @param state New state to set. - * @param state_str The state string name, if state contains value other - * than active, pending, or terminated. Otherwise this - * argument is ignored. - * @param reason Specify reason if new state is terminated, otherwise - * put NULL. - * @param mime_type MIME type/content type of the message body. - * @param body Message body to be included in the NOTIFY request. - * @param p_tdata Pointer to receive the request. - * - * @return PJ_SUCCESS on success. + * @param sub The server subscription (notifier) instance. + * @param state New state to set. + * @param state_str The state string name, if state contains value other + * than active, pending, or terminated. Otherwise this + * argument is ignored. + * @param reason Specify reason if new state is terminated, otherwise + * put NULL. + * @param mime_type MIME type/content type of the message body. + * @param body Message body to be included in the NOTIFY request. + * @param p_tdata Pointer to receive the request. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_mwi_notify( pjsip_evsub *sub, - pjsip_evsub_state state, - const pj_str_t *state_str, - const pj_str_t *reason, - const pjsip_media_type *mime_type, - const pj_str_t *body, - pjsip_tx_data **p_tdata); + pjsip_evsub_state state, + const pj_str_t *state_str, + const pj_str_t *reason, + const pjsip_media_type *mime_type, + const pj_str_t *body, + pjsip_tx_data **p_tdata); /** * Create NOTIFY request containing message body from the last NOITFY * message created. * - * @param sub Server subscription object. - * @param p_tdata Pointer to receive request. + * @param sub Server subscription object. + * @param p_tdata Pointer to receive request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_mwi_current_notify( pjsip_evsub *sub, - pjsip_tx_data **p_tdata ); + pjsip_tx_data **p_tdata ); /** @@ -192,13 +191,13 @@ PJ_DECL(pj_status_t) pjsip_mwi_current_notify( pjsip_evsub *sub, * functions, e.g. authentication. But the request MUST be either request * that creates/refresh subscription or NOTIFY request. * - * @param sub The subscription object. - * @param tdata Request message to be sent. + * @param sub The subscription object. + * @param tdata Request message to be sent. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_mwi_send_request( pjsip_evsub *sub, - pjsip_tx_data *tdata ); + pjsip_tx_data *tdata ); /** * @} @@ -207,4 +206,4 @@ PJ_DECL(pj_status_t) pjsip_mwi_send_request( pjsip_evsub *sub, PJ_END_DECL -#endif /* __PJSIP_SIMPLE_MWI_H__ */ +#endif /* __PJSIP_SIMPLE_MWI_H__ */ diff --git a/pjsip/include/pjsip-simple/pidf.h b/pjsip/include/pjsip-simple/pidf.h index 98828da439..9181d99870 100644 --- a/pjsip/include/pjsip-simple/pidf.h +++ b/pjsip/include/pjsip-simple/pidf.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -46,23 +45,23 @@ typedef struct pj_xml_node pjpidf_note; typedef struct pjpidf_status_op { - void (*construct)(pj_pool_t*, pjpidf_status*); - pj_bool_t (*is_basic_open)(const pjpidf_status*); - void (*set_basic_open)(pjpidf_status*, pj_bool_t); + void (*construct)(pj_pool_t*, pjpidf_status*); + pj_bool_t (*is_basic_open)(const pjpidf_status*); + void (*set_basic_open)(pjpidf_status*, pj_bool_t); } pjpidf_status_op; typedef struct pjpidf_tuple_op { - void (*construct)(pj_pool_t*, pjpidf_tuple*, const pj_str_t*); + void (*construct)(pj_pool_t*, pjpidf_tuple*, const pj_str_t*); const pj_str_t* (*get_id)(const pjpidf_tuple* ); - void (*set_id)(pj_pool_t*, pjpidf_tuple *, const pj_str_t*); + void (*set_id)(pj_pool_t*, pjpidf_tuple *, const pj_str_t*); pjpidf_status* (*get_status)(pjpidf_tuple* ); const pj_str_t* (*get_contact)(const pjpidf_tuple*); - void (*set_contact)(pj_pool_t*, pjpidf_tuple*, const pj_str_t*); - void (*set_contact_prio)(pj_pool_t*, pjpidf_tuple*, const pj_str_t*); + void (*set_contact)(pj_pool_t*, pjpidf_tuple*, const pj_str_t*); + void (*set_contact_prio)(pj_pool_t*, pjpidf_tuple*, const pj_str_t*); const pj_str_t* (*get_contact_prio)(const pjpidf_tuple*); pjpidf_note* (*add_note)(pj_pool_t*, pjpidf_tuple*, const pj_str_t*); @@ -70,20 +69,20 @@ typedef struct pjpidf_tuple_op pjpidf_note* (*get_next_note)(pjpidf_tuple*, pjpidf_note*); const pj_str_t* (*get_timestamp)(const pjpidf_tuple*); - void (*set_timestamp)(pj_pool_t*, pjpidf_tuple*, const pj_str_t*); - void (*set_timestamp_np)(pj_pool_t*,pjpidf_tuple*, pj_str_t*); + void (*set_timestamp)(pj_pool_t*, pjpidf_tuple*, const pj_str_t*); + void (*set_timestamp_np)(pj_pool_t*,pjpidf_tuple*, pj_str_t*); } pjpidf_tuple_op; typedef struct pjpidf_pres_op { - void (*construct)(pj_pool_t*, pjpidf_pres*, const pj_str_t*); + void (*construct)(pj_pool_t*, pjpidf_pres*, const pj_str_t*); pjpidf_tuple* (*add_tuple)(pj_pool_t*, pjpidf_pres*, const pj_str_t*); pjpidf_tuple* (*get_first_tuple)(pjpidf_pres*); pjpidf_tuple* (*get_next_tuple)(pjpidf_pres*, pjpidf_tuple*); pjpidf_tuple* (*find_tuple)(pjpidf_pres*, const pj_str_t*); - void (*remove_tuple)(pjpidf_pres*, pjpidf_tuple*); + void (*remove_tuple)(pjpidf_pres*, pjpidf_tuple*); pjpidf_note* (*add_note)(pj_pool_t*, pjpidf_pres*, const pj_str_t*); pjpidf_note* (*get_first_note)(pjpidf_pres*); @@ -94,9 +93,9 @@ typedef struct pjpidf_pres_op extern struct pjpidf_op_desc { - pjpidf_pres_op pres; - pjpidf_tuple_op tuple; - pjpidf_status_op status; + pjpidf_pres_op pres; + pjpidf_tuple_op tuple; + pjpidf_status_op status; } pjpidf_op; @@ -104,67 +103,67 @@ extern struct pjpidf_op_desc * Top level API for managing presence document. *****************************************************************************/ PJ_DECL(pjpidf_pres*) pjpidf_create(pj_pool_t *pool, const pj_str_t *entity); -PJ_DECL(pjpidf_pres*) pjpidf_parse(pj_pool_t *pool, char *text, int len); -PJ_DECL(int) pjpidf_print(const pjpidf_pres* pres, char *buf, int len); +PJ_DECL(pjpidf_pres*) pjpidf_parse(pj_pool_t *pool, char *text, int len); +PJ_DECL(int) pjpidf_print(const pjpidf_pres* pres, char *buf, int len); /****************************************************************************** * API for managing Presence node. *****************************************************************************/ -PJ_DECL(void) pjpidf_pres_construct(pj_pool_t *pool, pjpidf_pres *pres, - const pj_str_t *entity); -PJ_DECL(pjpidf_tuple*) pjpidf_pres_add_tuple(pj_pool_t *pool, pjpidf_pres *pres, - const pj_str_t *id); -PJ_DECL(pjpidf_tuple*) pjpidf_pres_get_first_tuple(pjpidf_pres *pres); -PJ_DECL(pjpidf_tuple*) pjpidf_pres_get_next_tuple(pjpidf_pres *pres, - pjpidf_tuple *t); -PJ_DECL(pjpidf_tuple*) pjpidf_pres_find_tuple(pjpidf_pres *pres, - const pj_str_t *id); -PJ_DECL(void) pjpidf_pres_remove_tuple(pjpidf_pres *pres, - pjpidf_tuple*); - -PJ_DECL(pjpidf_note*) pjpidf_pres_add_note(pj_pool_t *pool, pjpidf_pres *pres, - const pj_str_t *text); -PJ_DECL(pjpidf_note*) pjpidf_pres_get_first_note(pjpidf_pres *pres); -PJ_DECL(pjpidf_note*) pjpidf_pres_get_next_note(pjpidf_pres*, pjpidf_note*); +PJ_DECL(void) pjpidf_pres_construct(pj_pool_t *pool, pjpidf_pres *pres, + const pj_str_t *entity); +PJ_DECL(pjpidf_tuple*) pjpidf_pres_add_tuple(pj_pool_t *pool, pjpidf_pres *pres, + const pj_str_t *id); +PJ_DECL(pjpidf_tuple*) pjpidf_pres_get_first_tuple(pjpidf_pres *pres); +PJ_DECL(pjpidf_tuple*) pjpidf_pres_get_next_tuple(pjpidf_pres *pres, + pjpidf_tuple *t); +PJ_DECL(pjpidf_tuple*) pjpidf_pres_find_tuple(pjpidf_pres *pres, + const pj_str_t *id); +PJ_DECL(void) pjpidf_pres_remove_tuple(pjpidf_pres *pres, + pjpidf_tuple*); + +PJ_DECL(pjpidf_note*) pjpidf_pres_add_note(pj_pool_t *pool, pjpidf_pres *pres, + const pj_str_t *text); +PJ_DECL(pjpidf_note*) pjpidf_pres_get_first_note(pjpidf_pres *pres); +PJ_DECL(pjpidf_note*) pjpidf_pres_get_next_note(pjpidf_pres*, pjpidf_note*); /****************************************************************************** * API for managing Tuple node. *****************************************************************************/ -PJ_DECL(void) pjpidf_tuple_construct(pj_pool_t *pool, pjpidf_tuple *t, - const pj_str_t *id); +PJ_DECL(void) pjpidf_tuple_construct(pj_pool_t *pool, pjpidf_tuple *t, + const pj_str_t *id); PJ_DECL(const pj_str_t*) pjpidf_tuple_get_id(const pjpidf_tuple *t ); -PJ_DECL(void) pjpidf_tuple_set_id(pj_pool_t *pool, pjpidf_tuple *t, - const pj_str_t *id); +PJ_DECL(void) pjpidf_tuple_set_id(pj_pool_t *pool, pjpidf_tuple *t, + const pj_str_t *id); PJ_DECL(pjpidf_status*) pjpidf_tuple_get_status(pjpidf_tuple *t); PJ_DECL(const pj_str_t*) pjpidf_tuple_get_contact(const pjpidf_tuple *t); -PJ_DECL(void) pjpidf_tuple_set_contact(pj_pool_t *pool, pjpidf_tuple *t, - const pj_str_t *contact); -PJ_DECL(void) pjpidf_tuple_set_contact_prio(pj_pool_t *pool, pjpidf_tuple *t, - const pj_str_t *prio); +PJ_DECL(void) pjpidf_tuple_set_contact(pj_pool_t *pool, pjpidf_tuple *t, + const pj_str_t *contact); +PJ_DECL(void) pjpidf_tuple_set_contact_prio(pj_pool_t *pool, pjpidf_tuple *t, + const pj_str_t *prio); PJ_DECL(const pj_str_t*) pjpidf_tuple_get_contact_prio(const pjpidf_tuple *t); -PJ_DECL(pjpidf_note*) pjpidf_tuple_add_note(pj_pool_t *pool, pjpidf_tuple *t, - const pj_str_t *text); -PJ_DECL(pjpidf_note*) pjpidf_tuple_get_first_note(pjpidf_tuple *t); -PJ_DECL(pjpidf_note*) pjpidf_tuple_get_next_note(pjpidf_tuple *t, pjpidf_note *n); +PJ_DECL(pjpidf_note*) pjpidf_tuple_add_note(pj_pool_t *pool, pjpidf_tuple *t, + const pj_str_t *text); +PJ_DECL(pjpidf_note*) pjpidf_tuple_get_first_note(pjpidf_tuple *t); +PJ_DECL(pjpidf_note*) pjpidf_tuple_get_next_note(pjpidf_tuple *t, pjpidf_note *n); PJ_DECL(const pj_str_t*) pjpidf_tuple_get_timestamp(const pjpidf_tuple *t); -PJ_DECL(void) pjpidf_tuple_set_timestamp(pj_pool_t *pool, pjpidf_tuple *t, - const pj_str_t *ts); -PJ_DECL(void) pjpidf_tuple_set_timestamp_np( pj_pool_t*, pjpidf_tuple *t, - pj_str_t *ts); +PJ_DECL(void) pjpidf_tuple_set_timestamp(pj_pool_t *pool, pjpidf_tuple *t, + const pj_str_t *ts); +PJ_DECL(void) pjpidf_tuple_set_timestamp_np( pj_pool_t*, pjpidf_tuple *t, + pj_str_t *ts); /****************************************************************************** * API for managing Status node. *****************************************************************************/ -PJ_DECL(void) pjpidf_status_construct(pj_pool_t*, pjpidf_status*); -PJ_DECL(pj_bool_t) pjpidf_status_is_basic_open(const pjpidf_status*); -PJ_DECL(void) pjpidf_status_set_basic_open(pjpidf_status*, pj_bool_t); +PJ_DECL(void) pjpidf_status_construct(pj_pool_t*, pjpidf_status*); +PJ_DECL(pj_bool_t) pjpidf_status_is_basic_open(const pjpidf_status*); +PJ_DECL(void) pjpidf_status_set_basic_open(pjpidf_status*, pj_bool_t); /** @@ -175,4 +174,4 @@ PJ_DECL(void) pjpidf_status_set_basic_open(pjpidf_status*, pj_bool_t); PJ_END_DECL -#endif /* __PJSIP_SIMPLE_PIDF_H__ */ +#endif /* __PJSIP_SIMPLE_PIDF_H__ */ diff --git a/pjsip/include/pjsip-simple/presence.h b/pjsip/include/pjsip-simple/presence.h index 74ad6bf8e9..d6e271b49a 100644 --- a/pjsip/include/pjsip-simple/presence.h +++ b/pjsip/include/pjsip-simple/presence.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -51,21 +50,21 @@ PJ_BEGIN_DECL * Initialize the presence module and register it as endpoint module and * package to the event subscription module. * - * @param endpt The endpoint instance. - * @param mod_evsub The event subscription module instance. + * @param endpt The endpoint instance. + * @param mod_evsub The event subscription module instance. * - * @return PJ_SUCCESS if the module is successfully - * initialized and registered to both endpoint - * and the event subscription module. + * @return PJ_SUCCESS if the module is successfully + * initialized and registered to both endpoint + * and the event subscription module. */ PJ_DECL(pj_status_t) pjsip_pres_init_module(pjsip_endpoint *endpt, - pjsip_module *mod_evsub); + pjsip_module *mod_evsub); /** * Get the presence module instance. * - * @return The presence module instance. + * @return The presence module instance. */ PJ_DECL(pjsip_module*) pjsip_pres_instance(void); @@ -81,26 +80,26 @@ PJ_DECL(pjsip_module*) pjsip_pres_instance(void); */ struct pjsip_pres_status { - unsigned info_cnt; /**< Number of info in the status. */ + unsigned info_cnt; /**< Number of info in the status. */ struct { - pj_bool_t basic_open; /**< Basic status/availability. */ - pjrpid_element rpid; /**< Optional RPID info. */ + pj_bool_t basic_open; /**< Basic status/availability. */ + pjrpid_element rpid; /**< Optional RPID info. */ - pj_str_t id; /**< Tuple id. */ - pj_str_t contact; /**< Optional contact address. */ + pj_str_t id; /**< Tuple id. */ + pj_str_t contact; /**< Optional contact address. */ - pj_xml_node *tuple_node; /**< Pointer to tuple XML node of - parsed PIDF body received from - remote agent. Only valid for - client subscription. If the - last received NOTIFY request - does not contain any PIDF body, - this valud will be set to NULL */ + pj_xml_node *tuple_node; /**< Pointer to tuple XML node of + parsed PIDF body received from + remote agent. Only valid for + client subscription. If the + last received NOTIFY request + does not contain any PIDF body, + this valud will be set to NULL */ - } info[PJSIP_PRES_STATUS_MAX_INFO]; /**< Array of info. */ + } info[PJSIP_PRES_STATUS_MAX_INFO]; /**< Array of info. */ - pj_bool_t _is_valid; /**< Internal flag. */ + pj_bool_t _is_valid; /**< Internal flag. */ }; @@ -113,39 +112,39 @@ typedef struct pjsip_pres_status pjsip_pres_status; /** * Create presence client subscription session. * - * @param dlg The underlying dialog to use. - * @param user_cb Pointer to callbacks to receive presence subscription - * events. - * @param options Option flags. Currently only PJSIP_EVSUB_NO_EVENT_ID - * is recognized. - * @param p_evsub Pointer to receive the presence subscription - * session. + * @param dlg The underlying dialog to use. + * @param user_cb Pointer to callbacks to receive presence subscription + * events. + * @param options Option flags. Currently only PJSIP_EVSUB_NO_EVENT_ID + * is recognized. + * @param p_evsub Pointer to receive the presence subscription + * session. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_pres_create_uac( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - unsigned options, - pjsip_evsub **p_evsub ); + const pjsip_evsub_user *user_cb, + unsigned options, + pjsip_evsub **p_evsub ); /** * Create presence server subscription session. * - * @param dlg The underlying dialog to use. - * @param user_cb Pointer to callbacks to receive presence subscription - * events. - * @param rdata The incoming SUBSCRIBE request that creates the event - * subscription. - * @param p_evsub Pointer to receive the presence subscription - * session. + * @param dlg The underlying dialog to use. + * @param user_cb Pointer to callbacks to receive presence subscription + * events. + * @param rdata The incoming SUBSCRIBE request that creates the event + * subscription. + * @param p_evsub Pointer to receive the presence subscription + * session. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_pres_create_uas( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - pjsip_rx_data *rdata, - pjsip_evsub **p_evsub ); + const pjsip_evsub_user *user_cb, + pjsip_rx_data *rdata, + pjsip_evsub **p_evsub ); /** @@ -154,14 +153,14 @@ PJ_DECL(pj_status_t) pjsip_pres_create_uas( pjsip_dialog *dlg, * initialization has failed. For other conditions, application MUST terminate * the subscription by sending the appropriate un(SUBSCRIBE) or NOTIFY. * - * @param sub The presence subscription. - * @param notify Specify whether the state notification callback - * should be called. + * @param sub The presence subscription. + * @param notify Specify whether the state notification callback + * should be called. * - * @return PJ_SUCCESS if subscription session has been destroyed. + * @return PJ_SUCCESS if subscription session has been destroyed. */ PJ_DECL(pj_status_t) pjsip_pres_terminate( pjsip_evsub *sub, - pj_bool_t notify ); + pj_bool_t notify ); @@ -169,48 +168,48 @@ PJ_DECL(pj_status_t) pjsip_pres_terminate( pjsip_evsub *sub, * Call this function to create request to initiate presence subscription, to * refresh subcription, or to request subscription termination. * - * @param sub Client subscription instance. - * @param expires Subscription expiration. If the value is set to zero, - * this will request unsubscription. If the value is - * PJSIP_EXPIRES_NOT_SPECIFIED, default expiration - * as defined by the package will be used. - * @param p_tdata Pointer to receive the request. + * @param sub Client subscription instance. + * @param expires Subscription expiration. If the value is set to zero, + * this will request unsubscription. If the value is + * PJSIP_EXPIRES_NOT_SPECIFIED, default expiration + * as defined by the package will be used. + * @param p_tdata Pointer to receive the request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_pres_initiate( pjsip_evsub *sub, - pj_uint32_t expires, - pjsip_tx_data **p_tdata); + pj_uint32_t expires, + pjsip_tx_data **p_tdata); /** * Add a list of headers to the subscription instance. The list of headers * will be added to outgoing presence subscription requests. * - * @param sub Subscription instance. - * @param hdr_list List of headers to be added. + * @param sub Subscription instance. + * @param hdr_list List of headers to be added. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_pres_add_header( pjsip_evsub *sub, - const pjsip_hdr *hdr_list ); + const pjsip_hdr *hdr_list ); /** * Accept the incoming subscription request by sending 2xx response to * incoming SUBSCRIBE request. * - * @param sub Server subscription instance. - * @param rdata The incoming subscription request message. - * @param st_code Status code, which MUST be final response. - * @param hdr_list Optional list of headers to be added in the response. + * @param sub Server subscription instance. + * @param rdata The incoming subscription request message. + * @param st_code Status code, which MUST be final response. + * @param hdr_list Optional list of headers to be added in the response. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_pres_accept( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int st_code, - const pjsip_hdr *hdr_list ); + pjsip_rx_data *rdata, + int st_code, + const pjsip_hdr *hdr_list ); @@ -221,34 +220,34 @@ PJ_DECL(pj_status_t) pjsip_pres_accept( pjsip_evsub *sub, * appropriate state (by calling #pjsip_pres_set_status()) before calling * this function. * - * @param sub The server subscription (notifier) instance. - * @param state New state to set. - * @param state_str The state string name, if state contains value other - * than active, pending, or terminated. Otherwise this - * argument is ignored. - * @param reason Specify reason if new state is terminated, otherwise - * put NULL. - * @param p_tdata Pointer to receive the request. + * @param sub The server subscription (notifier) instance. + * @param state New state to set. + * @param state_str The state string name, if state contains value other + * than active, pending, or terminated. Otherwise this + * argument is ignored. + * @param reason Specify reason if new state is terminated, otherwise + * put NULL. + * @param p_tdata Pointer to receive the request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_pres_notify( pjsip_evsub *sub, - pjsip_evsub_state state, - const pj_str_t *state_str, - const pj_str_t *reason, - pjsip_tx_data **p_tdata); + pjsip_evsub_state state, + const pj_str_t *state_str, + const pj_str_t *reason, + pjsip_tx_data **p_tdata); /** * Create NOTIFY request to reflect current subscription status. * - * @param sub Server subscription object. - * @param p_tdata Pointer to receive request. + * @param sub Server subscription object. + * @param p_tdata Pointer to receive request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_pres_current_notify( pjsip_evsub *sub, - pjsip_tx_data **p_tdata ); + pjsip_tx_data **p_tdata ); @@ -258,26 +257,26 @@ PJ_DECL(pj_status_t) pjsip_pres_current_notify( pjsip_evsub *sub, * functions, e.g. authentication. But the request MUST be either request * that creates/refresh subscription or NOTIFY request. * - * @param sub The subscription object. - * @param tdata Request message to be sent. + * @param sub The subscription object. + * @param tdata Request message to be sent. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_pres_send_request( pjsip_evsub *sub, - pjsip_tx_data *tdata ); + pjsip_tx_data *tdata ); /** * Get the presence status. Client normally would call this function * after receiving NOTIFY request from server. * - * @param sub The client or server subscription. - * @param status The structure to receive presence status. + * @param sub The client or server subscription. + * @param status The structure to receive presence status. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_pres_get_status( pjsip_evsub *sub, - pjsip_pres_status *status ); + pjsip_pres_status *status ); /** @@ -285,125 +284,125 @@ PJ_DECL(pj_status_t) pjsip_pres_get_status( pjsip_evsub *sub, * subscription. After calling this function, application would need to * send NOTIFY request to client. * - * @param sub The server subscription. - * @param status Status to be set. + * @param sub The server subscription. + * @param status Status to be set. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_pres_set_status( pjsip_evsub *sub, - const pjsip_pres_status *status ); + const pjsip_pres_status *status ); /** * This is a utility function to create PIDF message body from PJSIP * presence status (pjsip_pres_status). * - * @param pool The pool to allocate memory for the message body. - * @param status Presence status to be converted into PIDF message - * body. - * @param entity The entity ID, which normally is equal to the - * presentity ID publishing this presence info. - * @param p_body Pointer to receive the SIP message body. + * @param pool The pool to allocate memory for the message body. + * @param status Presence status to be converted into PIDF message + * body. + * @param entity The entity ID, which normally is equal to the + * presentity ID publishing this presence info. + * @param p_body Pointer to receive the SIP message body. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_pres_create_pidf( pj_pool_t *pool, - const pjsip_pres_status *status, - const pj_str_t *entity, - pjsip_msg_body **p_body ); + const pjsip_pres_status *status, + const pj_str_t *entity, + pjsip_msg_body **p_body ); /** * This is a utility function to create X-PIDF message body from PJSIP * presence status (pjsip_pres_status). * - * @param pool The pool to allocate memory for the message body. - * @param status Presence status to be converted into X-PIDF message - * body. - * @param entity The entity ID, which normally is equal to the - * presentity ID publishing this presence info. - * @param p_body Pointer to receive the SIP message body. + * @param pool The pool to allocate memory for the message body. + * @param status Presence status to be converted into X-PIDF message + * body. + * @param entity The entity ID, which normally is equal to the + * presentity ID publishing this presence info. + * @param p_body Pointer to receive the SIP message body. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_pres_create_xpidf(pj_pool_t *pool, - const pjsip_pres_status *status, - const pj_str_t *entity, - pjsip_msg_body **p_body ); + const pjsip_pres_status *status, + const pj_str_t *entity, + pjsip_msg_body **p_body ); /** * This is a utility function to parse PIDF body into PJSIP presence status. * - * @param rdata The incoming SIP message containing the PIDF body. - * @param pool Pool to allocate memory to copy the strings into - * the presence status structure. - * @param status The presence status to be initialized. + * @param rdata The incoming SIP message containing the PIDF body. + * @param pool Pool to allocate memory to copy the strings into + * the presence status structure. + * @param status The presence status to be initialized. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. * * @see pjsip_pres_parse_pidf2() */ PJ_DECL(pj_status_t) pjsip_pres_parse_pidf(pjsip_rx_data *rdata, - pj_pool_t *pool, - pjsip_pres_status *status); + pj_pool_t *pool, + pjsip_pres_status *status); /** * This is a utility function to parse PIDF body into PJSIP presence status. * - * @param body Text body, with one extra space at the end to place - * NULL character temporarily during parsing. - * @param body_len Length of the body, not including the NULL termination - * character. - * @param pool Pool to allocate memory to copy the strings into - * the presence status structure. - * @param status The presence status to be initialized. + * @param body Text body, with one extra space at the end to place + * NULL character temporarily during parsing. + * @param body_len Length of the body, not including the NULL termination + * character. + * @param pool Pool to allocate memory to copy the strings into + * the presence status structure. + * @param status The presence status to be initialized. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. * * @see pjsip_pres_parse_pidf() */ PJ_DECL(pj_status_t) pjsip_pres_parse_pidf2(char *body, unsigned body_len, - pj_pool_t *pool, - pjsip_pres_status *status); + pj_pool_t *pool, + pjsip_pres_status *status); /** * This is a utility function to parse X-PIDF body into PJSIP presence status. * - * @param rdata The incoming SIP message containing the X-PIDF body. - * @param pool Pool to allocate memory to copy the strings into - * the presence status structure. - * @param status The presence status to be initialized. + * @param rdata The incoming SIP message containing the X-PIDF body. + * @param pool Pool to allocate memory to copy the strings into + * the presence status structure. + * @param status The presence status to be initialized. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. * * @see pjsip_pres_parse_xpidf2() */ PJ_DECL(pj_status_t) pjsip_pres_parse_xpidf(pjsip_rx_data *rdata, - pj_pool_t *pool, - pjsip_pres_status *status); + pj_pool_t *pool, + pjsip_pres_status *status); /** * This is a utility function to parse X-PIDF body into PJSIP presence status. * - * @param body Text body, with one extra space at the end to place - * NULL character temporarily during parsing. - * @param body_len Length of the body, not including the NULL termination - * character. - * @param pool Pool to allocate memory to copy the strings into - * the presence status structure. - * @param status The presence status to be initialized. + * @param body Text body, with one extra space at the end to place + * NULL character temporarily during parsing. + * @param body_len Length of the body, not including the NULL termination + * character. + * @param pool Pool to allocate memory to copy the strings into + * the presence status structure. + * @param status The presence status to be initialized. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. * * @see pjsip_pres_parse_xpidf() */ PJ_DECL(pj_status_t) pjsip_pres_parse_xpidf2(char *body, unsigned body_len, - pj_pool_t *pool, - pjsip_pres_status *status); + pj_pool_t *pool, + pjsip_pres_status *status); @@ -414,4 +413,4 @@ PJ_DECL(pj_status_t) pjsip_pres_parse_xpidf2(char *body, unsigned body_len, PJ_END_DECL -#endif /* __PJSIP_SIMPLE_PRESENCE_H__ */ +#endif /* __PJSIP_SIMPLE_PRESENCE_H__ */ diff --git a/pjsip/include/pjsip-simple/publish.h b/pjsip/include/pjsip-simple/publish.h index 9e2f95f1d7..5696dc366c 100644 --- a/pjsip/include/pjsip-simple/publish.h +++ b/pjsip/include/pjsip-simple/publish.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -57,7 +56,7 @@ extern const pjsip_method pjsip_publish_method; /** Expiration not specified. */ -#define PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED ((pj_uint32_t)0xFFFFFFFFUL) +#define PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED ((pj_uint32_t)0xFFFFFFFFUL) /** * Opaque declaration for client side event publication session. @@ -80,7 +79,7 @@ typedef struct pjsip_publishc_opt * * Default: PJSIP_PUBLISHC_QUEUE_REQUEST */ - pj_bool_t queue_request; + pj_bool_t queue_request; } pjsip_publishc_opt; @@ -91,17 +90,17 @@ typedef struct pjsip_publishc_opt */ struct pjsip_publishc_cbparam { - pjsip_publishc *pubc; /**< Client publication structure. */ - void *token; /**< Arbitrary token. */ - pj_status_t status; /**< Error status. */ - int code; /**< SIP status code received. */ - pj_str_t reason; /**< SIP reason phrase received. */ - pjsip_rx_data *rdata; /**< The complete received response. */ - unsigned expiration;/**< Next expiration interval. If the - value is - PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED, - it means the session will not renew - itself. */ + pjsip_publishc *pubc; /**< Client publication structure. */ + void *token; /**< Arbitrary token. */ + pj_status_t status; /**< Error status. */ + int code; /**< SIP status code received. */ + pj_str_t reason; /**< SIP reason phrase received. */ + pjsip_rx_data *rdata; /**< The complete received response. */ + unsigned expiration;/**< Next expiration interval. If the + value is + PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED, + it means the session will not renew + itself. */ }; @@ -112,7 +111,7 @@ typedef void pjsip_publishc_cb(struct pjsip_publishc_cbparam *param); /** * Initialize client publication session option with default values. * - * @param opt The option. + * @param opt The option. */ PJ_DECL(void) pjsip_publishc_opt_default(pjsip_publishc_opt *opt); @@ -120,9 +119,9 @@ PJ_DECL(void) pjsip_publishc_opt_default(pjsip_publishc_opt *opt); /** * Initialize client publication module. * - * @param endpt SIP endpoint. + * @param endpt SIP endpoint. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_publishc_init_module(pjsip_endpoint *endpt); @@ -130,19 +129,19 @@ PJ_DECL(pj_status_t) pjsip_publishc_init_module(pjsip_endpoint *endpt); /** * Create client publication structure. * - * @param endpt Endpoint, used to allocate pool from. - * @param opt Options, or NULL to specify default options. - * @param token Opaque data to be associated with the client publication. - * @param cb Pointer to callback function to receive publication status. + * @param endpt Endpoint, used to allocate pool from. + * @param opt Options, or NULL to specify default options. + * @param token Opaque data to be associated with the client publication. + * @param cb Pointer to callback function to receive publication status. * @param p_pubc Pointer to receive client publication structure. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_publishc_create( pjsip_endpoint *endpt, - const pjsip_publishc_opt *opt, - void *token, - pjsip_publishc_cb *cb, - pjsip_publishc **p_pubc); + const pjsip_publishc_opt *opt, + void *token, + pjsip_publishc_cb *cb, + pjsip_publishc **p_pubc); /** @@ -150,9 +149,9 @@ PJ_DECL(pj_status_t) pjsip_publishc_create( pjsip_endpoint *endpt, * in progress, then the structure will be deleted only after a final response * has been received, and in this case, the callback won't be called. * - * @param pubc The client publication structure. + * @param pubc The client publication structure. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_publishc_destroy(pjsip_publishc *pubc); @@ -161,8 +160,8 @@ PJ_DECL(pj_status_t) pjsip_publishc_destroy(pjsip_publishc *pubc); /** * Get the memory pool associated with a publication client session. * - * @param pubc The client publication structure. - * @return pool handle. + * @param pubc The client publication structure. + * @return pool handle. */ PJ_DECL(pj_pool_t*) pjsip_publishc_get_pool(pjsip_publishc *pubc); @@ -171,52 +170,52 @@ PJ_DECL(pj_pool_t*) pjsip_publishc_get_pool(pjsip_publishc *pubc); * Initialize client publication structure with various information needed to * perform the publication. * - * @param pubc The client publication structure. - * @param event The Event identification (e.g. "presence"). - * @param target_uri The URI of the presentity which the which the status - * is being published. - * @param from_uri The URI of the endpoint who sends the event - * publication. Normally the value would be the same as - * target_uri. - * @param to_uri The URI to be put in To header. Normally the value - * would be the same as target_uri. - * @param expires The default expiration of the event publication. - * If the value PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED is - * given, then no default expiration will be applied. - * - * @return PJ_SUCCESS on success. + * @param pubc The client publication structure. + * @param event The Event identification (e.g. "presence"). + * @param target_uri The URI of the presentity which the which the status + * is being published. + * @param from_uri The URI of the endpoint who sends the event + * publication. Normally the value would be the same as + * target_uri. + * @param to_uri The URI to be put in To header. Normally the value + * would be the same as target_uri. + * @param expires The default expiration of the event publication. + * If the value PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED is + * given, then no default expiration will be applied. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_publishc_init(pjsip_publishc *pubc, - const pj_str_t *event, - const pj_str_t *target_uri, - const pj_str_t *from_uri, - const pj_str_t *to_uri, - pj_uint32_t expires); + const pj_str_t *event, + const pj_str_t *target_uri, + const pj_str_t *from_uri, + const pj_str_t *to_uri, + pj_uint32_t expires); /** * Set authentication credentials to use by this publication. * - * @param pubc The publication structure. - * @param count Number of credentials in the array. - * @param c Array of credentials. + * @param pubc The publication structure. + * @param count Number of credentials in the array. + * @param c Array of credentials. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_publishc_set_credentials(pjsip_publishc *pubc, - int count, - const pjsip_cred_info c[]); + int count, + const pjsip_cred_info c[]); /** * Set route set to be used for outgoing requests. * - * @param pubc The client publication structure. - * @param rs List containing Route headers. + * @param pubc The client publication structure. + * @param rs List containing Route headers. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_publishc_set_route_set(pjsip_publishc *pubc, - const pjsip_route_hdr *rs); + const pjsip_route_hdr *rs); /** @@ -230,27 +229,27 @@ PJ_DECL(pj_status_t) pjsip_publishc_set_route_set(pjsip_publishc *pubc, * Note that calling this function will clear the previously added list * of headers. * - * @param pubc The client publication structure. + * @param pubc The client publication structure. * @param hdr_list The list of headers. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_publishc_set_headers(pjsip_publishc *pubc, - const pjsip_hdr *hdr_list); + const pjsip_hdr *hdr_list); /** * Set the "sent-by" field of the Via header for outgoing requests. * - * @param pubc The client publication structure. + * @param pubc The client publication structure. * @param via_addr Set via_addr to use for the Via header or NULL to use * the transport's published name. * @param via_tp via_addr will only be used if we are using via_tp * transport. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_publishc_set_via_sent_by(pjsip_publishc *pubc, - pjsip_host_port *via_addr, + pjsip_host_port *via_addr, pjsip_transport *via_tp); @@ -267,30 +266,30 @@ PJ_DECL(pj_status_t) pjsip_publishc_set_via_sent_by(pjsip_publishc *pubc, * (as long as auto_refresh argument below is non-zero), and application * should not use this function to perform publication refresh. * - * @param pubc The client publication session. - * @param auto_refresh If non zero, the library will automatically - * refresh the next publication until application - * unpublish. - * @param p_tdata Pointer to receive the PUBLISH request. Note that - * the request DOES NOT have a message body. + * @param pubc The client publication session. + * @param auto_refresh If non zero, the library will automatically + * refresh the next publication until application + * unpublish. + * @param p_tdata Pointer to receive the PUBLISH request. Note that + * the request DOES NOT have a message body. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_publishc_publish(pjsip_publishc *pubc, - pj_bool_t auto_refresh, - pjsip_tx_data **p_tdata); + pj_bool_t auto_refresh, + pjsip_tx_data **p_tdata); /** * Create PUBLISH request to unpublish the current client publication. * - * @param pubc The client publication structure. + * @param pubc The client publication structure. * @param p_tdata Pointer to receive the PUBLISH request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_publishc_unpublish(pjsip_publishc *pubc, - pjsip_tx_data **p_tdata); + pjsip_tx_data **p_tdata); /** @@ -299,13 +298,13 @@ PJ_DECL(pj_status_t) pjsip_publishc_unpublish(pjsip_publishc *pubc, * session. If application wants to do this, then it must construct a * PUBLISH request and send it to the server. * - * @param pubc The client publication structure. + * @param pubc The client publication structure. * @param expires The new expires value. * - * @return PU_SUCCESS on successfull. + * @return PU_SUCCESS on successfull. */ PJ_DECL(pj_status_t) pjsip_publishc_update_expires(pjsip_publishc *pubc, - pj_uint32_t expires ); + pj_uint32_t expires ); /** @@ -322,17 +321,17 @@ PJ_DECL(pj_status_t) pjsip_publishc_update_expires(pjsip_publishc *pubc, * request will be sent automatically. If request queueing is disabled, the * function will reject the request and return PJ_EBUSY. * - * @param pubc The client publication structure. - * @param tdata Transmit data. + * @param pubc The client publication structure. + * @param tdata Transmit data. * - * @return - PJ_SUCCESS on success, or - * - PJ_EPENDING if request is queued, or - * - PJ_EBUSY if request is rejected because another PUBLISH - * request is in progress, or - * - other status code to indicate the error. + * @return - PJ_SUCCESS on success, or + * - PJ_EPENDING if request is queued, or + * - PJ_EBUSY if request is rejected because another PUBLISH + * request is in progress, or + * - other status code to indicate the error. */ PJ_DECL(pj_status_t) pjsip_publishc_send(pjsip_publishc *pubc, - pjsip_tx_data *tdata); + pjsip_tx_data *tdata); @@ -347,5 +346,5 @@ PJ_DECL(pj_status_t) pjsip_publishc_send(pjsip_publishc *pubc, PJ_END_DECL -#endif /* __PJSIP_SIMPLE_PUBLISH_H__ */ +#endif /* __PJSIP_SIMPLE_PUBLISH_H__ */ diff --git a/pjsip/include/pjsip-simple/rpid.h b/pjsip/include/pjsip-simple/rpid.h index 1aad3d9854..dbc48d5d82 100644 --- a/pjsip/include/pjsip-simple/rpid.h +++ b/pjsip/include/pjsip-simple/rpid.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -78,16 +77,16 @@ typedef enum pjrpid_element_type typedef struct pjrpid_element { /** Element type. */ - pjrpid_element_type type; + pjrpid_element_type type; /** Optional id to set on the element. */ - pj_str_t id; + pj_str_t id; /** Activity type. */ - pjrpid_activity activity; + pjrpid_activity activity; /** Optional text describing the person/element. */ - pj_str_t note; + pj_str_t note; } pjrpid_element; @@ -95,12 +94,12 @@ typedef struct pjrpid_element /** * Duplicate RPID element. * - * @param pool Pool. - * @param dst Destination structure. - * @param src Source structure. + * @param pool Pool. + * @param dst Destination structure. + * @param src Source structure. */ PJ_DECL(void) pjrpid_element_dup(pj_pool_t *pool, pjrpid_element *dst, - const pjrpid_element *src); + const pjrpid_element *src); /** @@ -110,32 +109,32 @@ PJ_DECL(void) pjrpid_element_dup(pj_pool_t *pool, pjrpid_element *dst, * to the first element of the PIDF document, if a element * is not present. * - * @param pres The PIDF presence document. - * @param pool Pool. + * @param pres The PIDF presence document. + * @param pool Pool. * @param options Currently unused, and must be zero. - * @param elem RPID element information to be added into the PIDF - * document. + * @param elem RPID element information to be added into the PIDF + * document. * * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjrpid_add_element(pjpidf_pres *pres, - pj_pool_t *pool, - unsigned options, - const pjrpid_element *elem); + pj_pool_t *pool, + unsigned options, + const pjrpid_element *elem); /** * Get RPID element information from PIDF document, if any. * - * @param pres The PIDF document containing RPID elements. - * @param pool Pool to duplicate the information. - * @param elem Structure to receive the element information. + * @param pres The PIDF document containing RPID elements. + * @param pool Pool to duplicate the information. + * @param elem Structure to receive the element information. * - * @return PJ_SUCCESS if the document does contain RPID element - * and the information has been parsed successfully. + * @return PJ_SUCCESS if the document does contain RPID element + * and the information has been parsed successfully. */ PJ_DECL(pj_status_t) pjrpid_get_element(const pjpidf_pres *pres, - pj_pool_t *pool, - pjrpid_element *elem); + pj_pool_t *pool, + pjrpid_element *elem); /** @@ -146,5 +145,5 @@ PJ_DECL(pj_status_t) pjrpid_get_element(const pjpidf_pres *pres, PJ_END_DECL -#endif /* __PJSIP_SIMPLE_RPID_H__ */ +#endif /* __PJSIP_SIMPLE_RPID_H__ */ diff --git a/pjsip/include/pjsip-simple/types.h b/pjsip/include/pjsip-simple/types.h index f8c7f77e02..648cd5e862 100644 --- a/pjsip/include/pjsip-simple/types.h +++ b/pjsip/include/pjsip-simple/types.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -23,9 +22,9 @@ #include -#define PJSIP_EVSUB_POOL_LEN 4000 -#define PJSIP_EVSUB_POOL_INC 4000 +#define PJSIP_EVSUB_POOL_LEN 4000 +#define PJSIP_EVSUB_POOL_INC 4000 -#endif /* __PJSIP_SIMPLE_TYPES_H__ */ +#endif /* __PJSIP_SIMPLE_TYPES_H__ */ diff --git a/pjsip/include/pjsip-simple/xpidf.h b/pjsip/include/pjsip-simple/xpidf.h index 2044646c90..32257aa0e7 100644 --- a/pjsip/include/pjsip-simple/xpidf.h +++ b/pjsip/include/pjsip-simple/xpidf.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -49,10 +48,10 @@ typedef pj_xml_node pjxpidf_pres; /** * Create a new XPIDF document. * - * @param pool Pool. - * @param uri URI to set in the XPIDF document. + * @param pool Pool. + * @param uri URI to set in the XPIDF document. * - * @return XPIDF document. + * @return XPIDF document. */ PJ_DECL(pjxpidf_pres*) pjxpidf_create(pj_pool_t *pool, const pj_str_t *uri); @@ -63,11 +62,11 @@ PJ_DECL(pjxpidf_pres*) pjxpidf_create(pj_pool_t *pool, const pj_str_t *uri); * Note that the input text buffer MUST be NULL terminated and have * length at least len+1 (len MUST NOT include the NULL terminator). * - * @param pool Pool. - * @param text Input text, MUST be NULL terminated. - * @param len Length of input text, NOT including the NULL terminator. + * @param pool Pool. + * @param text Input text, MUST be NULL terminated. + * @param len Length of input text, NOT including the NULL terminator. * - * @return XPIDF document. + * @return XPIDF document. */ PJ_DECL(pjxpidf_pres*) pjxpidf_parse(pj_pool_t *pool, char *text, pj_size_t len); @@ -75,11 +74,11 @@ PJ_DECL(pjxpidf_pres*) pjxpidf_parse(pj_pool_t *pool, char *text, pj_size_t len) /** * Print XPIDF document. * - * @param pres The XPIDF document to print. - * @param text Buffer to place the output. - * @param len Length of the buffer. + * @param pres The XPIDF document to print. + * @param text Buffer to place the output. + * @param len Length of the buffer. * - * @return The length printed. + * @return The length printed. */ PJ_DECL(int) pjxpidf_print( pjxpidf_pres *pres, char *text, pj_size_t len); @@ -87,9 +86,9 @@ PJ_DECL(int) pjxpidf_print( pjxpidf_pres *pres, char *text, pj_size_t len); /** * Get URI in the XPIDF document * - * @param pres XPIDF document + * @param pres XPIDF document * - * @return The URI, or an empty string. + * @return The URI, or an empty string. */ PJ_DECL(pj_str_t*) pjxpidf_get_uri(pjxpidf_pres *pres); @@ -97,22 +96,22 @@ PJ_DECL(pj_str_t*) pjxpidf_get_uri(pjxpidf_pres *pres); /** * Set the URI of the XPIDF document. * - * @param pool Pool. - * @param pres The XPIDF document. - * @param uri URI to set in the XPIDF document. + * @param pool Pool. + * @param pres The XPIDF document. + * @param uri URI to set in the XPIDF document. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pjxpidf_set_uri(pj_pool_t *pool, pjxpidf_pres *pres, - const pj_str_t *uri); + const pj_str_t *uri); /** * Get presence status in the XPIDF document. * - * @param pres XPIDF document. + * @param pres XPIDF document. * - * @return True to indicate the contact is online. + * @return True to indicate the contact is online. */ PJ_DECL(pj_bool_t) pjxpidf_get_status(pjxpidf_pres *pres); @@ -120,10 +119,10 @@ PJ_DECL(pj_bool_t) pjxpidf_get_status(pjxpidf_pres *pres); /** * Set presence status in the XPIDF document. * - * @param pres XPIDF document. + * @param pres XPIDF document. * @param status Status to set, True for online, False for offline. * - * @return Zero on success. + * @return Zero on success. */ PJ_DECL(pj_status_t) pjxpidf_set_status(pjxpidf_pres *pres, pj_bool_t status); @@ -135,4 +134,4 @@ PJ_DECL(pj_status_t) pjxpidf_set_status(pjxpidf_pres *pres, pj_bool_t status); PJ_END_DECL -#endif /* __PJSIP_SIMPLE_XPIDF_H__ */ +#endif /* __PJSIP_SIMPLE_XPIDF_H__ */ diff --git a/pjsip/include/pjsip-ua/sip_100rel.h b/pjsip/include/pjsip-ua/sip_100rel.h index d44b0f67c3..089ab91fd0 100644 --- a/pjsip/include/pjsip-ua/sip_100rel.h +++ b/pjsip/include/pjsip-ua/sip_100rel.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -85,12 +84,12 @@ options |= PJSIP_INV_SUPPORT_100REL; status = pjsip_inv_verify_request(rdata, &options, answer, NULL, - endpt, &resp); + endpt, &resp); if (status != PJ_SUCCESS) { - // INVITE request cannot be handled. - // Reject the request with the response in resp. - ... - return; + // INVITE request cannot be handled. + // Reject the request with the response in resp. + ... + return; } // Create UAS dialog, populate Contact header, etc. @@ -141,9 +140,9 @@ PJ_DECL(const pjsip_method*) pjsip_get_prack_method(void); * Initialize 100rel module. This function must be called once during * application initialization, to register 100rel module to SIP endpoint. * - * @param endpt The SIP endpoint instance. + * @param endpt The SIP endpoint instance. * - * @return PJ_SUCCESS if module is successfully initialized. + * @return PJ_SUCCESS if module is successfully initialized. */ PJ_DECL(pj_status_t) pjsip_100rel_init_module(pjsip_endpoint *endpt); @@ -153,9 +152,9 @@ PJ_DECL(pj_status_t) pjsip_100rel_init_module(pjsip_endpoint *endpt); * be called internally by the invite session if it detects that the * session needs 100rel support. * - * @param inv The invite session. + * @param inv The invite session. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_100rel_attach(pjsip_inv_session *inv); @@ -163,9 +162,9 @@ PJ_DECL(pj_status_t) pjsip_100rel_attach(pjsip_inv_session *inv); /** * Check if incoming response has reliable provisional response feature. * - * @param rdata Receive data buffer containing the response. + * @param rdata Receive data buffer containing the response. * - * @return PJ_TRUE if the provisional response is reliable. + * @return PJ_TRUE if the provisional response is reliable. */ PJ_DECL(pj_bool_t) pjsip_100rel_is_reliable(pjsip_rx_data *rdata); @@ -174,39 +173,39 @@ PJ_DECL(pj_bool_t) pjsip_100rel_is_reliable(pjsip_rx_data *rdata); * Create PRACK request for the incoming reliable provisional response. * Note that PRACK request MUST be sent using #pjsip_100rel_send_prack(). * - * @param inv The invite session. - * @param rdata The incoming reliable provisional response. - * @param p_tdata Upon return, it will be initialized with the - * PRACK request. + * @param inv The invite session. + * @param rdata The incoming reliable provisional response. + * @param p_tdata Upon return, it will be initialized with the + * PRACK request. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_100rel_create_prack(pjsip_inv_session *inv, - pjsip_rx_data *rdata, - pjsip_tx_data **p_tdata); + pjsip_rx_data *rdata, + pjsip_tx_data **p_tdata); /** * Send PRACK request. * - * @param inv The invite session. - * @param tdata The PRACK request. + * @param inv The invite session. + * @param tdata The PRACK request. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_100rel_send_prack(pjsip_inv_session *inv, - pjsip_tx_data *tdata); + pjsip_tx_data *tdata); /** * Handle incoming PRACK request. * - * @param inv The invite session. - * @param rdata Incoming PRACK request. + * @param inv The invite session. + * @param rdata Incoming PRACK request. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_100rel_on_rx_prack(pjsip_inv_session *inv, - pjsip_rx_data *rdata); + pjsip_rx_data *rdata); /** @@ -216,21 +215,21 @@ PJ_DECL(pj_status_t) pjsip_100rel_on_rx_prack(pjsip_inv_session *inv, * reliable response processing. This function will be called internally * by invite session. * - * @param inv The invite session. - * @param tdata The INVITE response. + * @param inv The invite session. + * @param tdata The INVITE response. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_100rel_tx_response(pjsip_inv_session *inv, - pjsip_tx_data *tdata); + pjsip_tx_data *tdata); /** * Notify 100rel module that the invite session has been disconnected. * - * @param inv The invite session. + * @param inv The invite session. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_100rel_end_session(pjsip_inv_session *inv); @@ -242,4 +241,4 @@ PJ_END_DECL */ -#endif /* __SIP_100REL_H__ */ +#endif /* __SIP_100REL_H__ */ diff --git a/pjsip/include/pjsip-ua/sip_inv.h b/pjsip/include/pjsip-ua/sip_inv.h index 43d5c344e3..bdaa509523 100644 --- a/pjsip/include/pjsip-ua/sip_inv.h +++ b/pjsip/include/pjsip-ua/sip_inv.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -87,13 +86,13 @@ typedef struct pjsip_inv_session pjsip_inv_session; */ typedef enum pjsip_inv_state { - PJSIP_INV_STATE_NULL, /**< Before INVITE is sent or received */ - PJSIP_INV_STATE_CALLING, /**< After INVITE is sent */ - PJSIP_INV_STATE_INCOMING, /**< After INVITE is received. */ - PJSIP_INV_STATE_EARLY, /**< After response with To tag. */ - PJSIP_INV_STATE_CONNECTING, /**< After 2xx is sent/received. */ - PJSIP_INV_STATE_CONFIRMED, /**< After ACK is sent/received. */ - PJSIP_INV_STATE_DISCONNECTED, /**< Session is terminated. */ + PJSIP_INV_STATE_NULL, /**< Before INVITE is sent or received */ + PJSIP_INV_STATE_CALLING, /**< After INVITE is sent */ + PJSIP_INV_STATE_INCOMING, /**< After INVITE is received. */ + PJSIP_INV_STATE_EARLY, /**< After response with To tag. */ + PJSIP_INV_STATE_CONNECTING, /**< After 2xx is sent/received. */ + PJSIP_INV_STATE_CONFIRMED, /**< After ACK is sent/received. */ + PJSIP_INV_STATE_DISCONNECTED, /**< Session is terminated. */ } pjsip_inv_state; /** @@ -102,8 +101,8 @@ typedef enum pjsip_inv_state */ struct pjsip_inv_on_rx_offer_cb_param { - const pjmedia_sdp_session *offer; /**< Remote offer. */ - const pjsip_rx_data *rdata; /**< The received request. */ + const pjmedia_sdp_session *offer; /**< Remote offer. */ + const pjsip_rx_data *rdata; /**< The received request. */ }; @@ -121,9 +120,9 @@ typedef struct pjsip_inv_callback * * This callback is mandatory. * - * @param inv The invite session. - * @param e The event which has caused the invite session's - * state to change. + * @param inv The invite session. + * @param e The event which has caused the invite session's + * state to change. */ void (*on_state_changed)(pjsip_inv_session *inv, pjsip_event *e); @@ -134,10 +133,10 @@ typedef struct pjsip_inv_callback * Currently the invite session does not create a new dialog in * forking scenario, so this callback will never be invoked. * - * @param inv The new invite session. - * @param e The event which has caused the dialog to fork. - * The type of this event can be either - * PJSIP_EVENT_RX_MSG or PJSIP_EVENT_RX_200_MSG. + * @param inv The new invite session. + * @param e The event which has caused the dialog to fork. + * The type of this event can be either + * PJSIP_EVENT_RX_MSG or PJSIP_EVENT_RX_200_MSG. */ void (*on_new_session)(pjsip_inv_session *inv, pjsip_event *e); @@ -149,14 +148,14 @@ typedef struct pjsip_inv_callback * * This callback is optional. * - * @param inv The invite session. - * @param tsx The transaction, which state has changed. - * @param e The event which has caused the transation state's - * to change. + * @param inv The invite session. + * @param tsx The transaction, which state has changed. + * @param e The event which has caused the transation state's + * to change. */ void (*on_tsx_state_changed)(pjsip_inv_session *inv, - pjsip_transaction *tsx, - pjsip_event *e); + pjsip_transaction *tsx, + pjsip_event *e); /** * This callback is called when the invite session has received @@ -169,8 +168,8 @@ typedef struct pjsip_inv_callback * Note: if callback #on_rx_offer2() is implemented, this callback will * not be called. * - * @param inv The invite session. - * @param offer Remote offer. + * @param inv The invite session. + * @param offer Remote offer. */ void (*on_rx_offer)(pjsip_inv_session *inv, const pjmedia_sdp_session *offer); @@ -179,8 +178,8 @@ typedef struct pjsip_inv_callback * This callback is called when the invite session has received * new offer from peer. Variant of #on_rx_offer() callback. * - * @param inv The invite session. - * @param param The callback parameters. + * @param inv The invite session. + * @param param The callback parameters. */ void (*on_rx_offer2)(pjsip_inv_session *inv, struct pjsip_inv_on_rx_offer_cb_param *param); @@ -201,17 +200,17 @@ typedef struct pjsip_inv_callback * callback to check whether the re-INVITE is already answered * automatically with 487 due to being cancelled. * - * @param inv The invite session. - * @param offer Remote offer. + * @param inv The invite session. + * @param offer Remote offer. * @param rdata The received re-INVITE request. * - * @return - PJ_SUCCESS: application will answer the re-INVITE + * @return - PJ_SUCCESS: application will answer the re-INVITE * manually * - non-PJ_SUCCESS: answer the re-INVITE automatically * using the SDP set via #pjsip_inv_set_sdp_answer() */ pj_status_t (*on_rx_reinvite)(pjsip_inv_session *inv, - const pjmedia_sdp_session *offer, + const pjmedia_sdp_session *offer, pjsip_rx_data *rdata); /** @@ -223,12 +222,12 @@ typedef struct pjsip_inv_callback * If application doesn't implement this callback, the invite session * will send the currently active SDP as the offer. * - * @param inv The invite session. - * @param p_offer Pointer to receive the SDP offer created by - * application. + * @param inv The invite session. + * @param p_offer Pointer to receive the SDP offer created by + * application. */ void (*on_create_offer)(pjsip_inv_session *inv, - pjmedia_sdp_session **p_offer); + pjmedia_sdp_session **p_offer); /** * This callback is called after SDP offer/answer session has completed. @@ -238,11 +237,11 @@ typedef struct pjsip_inv_callback * This callback is optional (from the point of view of the framework), * but all useful applications normally need to implement this callback. * - * @param inv The invite session. - * @param status The negotiation status. + * @param inv The invite session. + * @param status The negotiation status. */ void (*on_media_update)(pjsip_inv_session *inv_ses, - pj_status_t status); + pj_status_t status); /** * This callback is called when the framework needs to send @@ -287,40 +286,40 @@ typedef struct pjsip_inv_callback * This callback is optional. If this callback is not implemented, * the default behavior is to NOT follow the redirection response. * - * @param inv The invite session. - * @param target The current target to be tried. - * @param e The event that caused this callback to be called. - * This could be the receipt of 3xx response, or - * 4xx/5xx response received for the INVITE sent to - * subsequent targets, or NULL if this callback is - * called from within #pjsip_inv_process_redirect() - * context. + * @param inv The invite session. + * @param target The current target to be tried. + * @param e The event that caused this callback to be called. + * This could be the receipt of 3xx response, or + * 4xx/5xx response received for the INVITE sent to + * subsequent targets, or NULL if this callback is + * called from within #pjsip_inv_process_redirect() + * context. * - * @return Action to be performed for the target. Set this - * parameter to one of the value below: - * - PJSIP_REDIRECT_ACCEPT: immediately accept the - * redirection to this target. When set, the - * session will immediately resend INVITE request - * to the target after this callback returns. - * - PJSIP_REDIRECT_REJECT: immediately reject this - * target. The session will continue retrying with - * next target if present, or disconnect the call - * if there is no more target to try. - * - PJSIP_REDIRECT_STOP: stop the whole redirection - * process and immediately disconnect the call. The - * on_state_changed() callback will be called with - * PJSIP_INV_STATE_DISCONNECTED state immediately - * after this callback returns. - * - PJSIP_REDIRECT_PENDING: set to this value if - * no decision can be made immediately (for example - * to request confirmation from user). Application - * then MUST call #pjsip_inv_process_redirect() - * to either accept or reject the redirection upon - * getting user decision. + * @return Action to be performed for the target. Set this + * parameter to one of the value below: + * - PJSIP_REDIRECT_ACCEPT: immediately accept the + * redirection to this target. When set, the + * session will immediately resend INVITE request + * to the target after this callback returns. + * - PJSIP_REDIRECT_REJECT: immediately reject this + * target. The session will continue retrying with + * next target if present, or disconnect the call + * if there is no more target to try. + * - PJSIP_REDIRECT_STOP: stop the whole redirection + * process and immediately disconnect the call. The + * on_state_changed() callback will be called with + * PJSIP_INV_STATE_DISCONNECTED state immediately + * after this callback returns. + * - PJSIP_REDIRECT_PENDING: set to this value if + * no decision can be made immediately (for example + * to request confirmation from user). Application + * then MUST call #pjsip_inv_process_redirect() + * to either accept or reject the redirection upon + * getting user decision. */ pjsip_redirect_op (*on_redirected)(pjsip_inv_session *inv, - const pjsip_uri *target, - const pjsip_event *e); + const pjsip_uri *target, + const pjsip_event *e); } pjsip_inv_callback; @@ -334,16 +333,16 @@ typedef struct pjsip_inv_callback * common in both endpoints. */ enum pjsip_inv_option -{ +{ /** * Indicate support for reliable provisional response extension */ - PJSIP_INV_SUPPORT_100REL = 1, + PJSIP_INV_SUPPORT_100REL = 1, /** * Indicate support for session timer extension. */ - PJSIP_INV_SUPPORT_TIMER = 2, + PJSIP_INV_SUPPORT_TIMER = 2, /** * Indicate support for UPDATE method. This is automatically implied @@ -351,33 +350,33 @@ enum pjsip_inv_option * the options member of #pjsip_inv_session shows whether peer supports * this method as well. */ - PJSIP_INV_SUPPORT_UPDATE = 4, + PJSIP_INV_SUPPORT_UPDATE = 4, /** * Indicate support for ICE */ - PJSIP_INV_SUPPORT_ICE = 8, + PJSIP_INV_SUPPORT_ICE = 8, /** * Require ICE support. */ - PJSIP_INV_REQUIRE_ICE = 16, + PJSIP_INV_REQUIRE_ICE = 16, /** * Require reliable provisional response extension. */ - PJSIP_INV_REQUIRE_100REL = 32, + PJSIP_INV_REQUIRE_100REL = 32, /** * Require session timer extension. */ - PJSIP_INV_REQUIRE_TIMER = 64, + PJSIP_INV_REQUIRE_TIMER = 64, /** * Session timer extension will always be used even when peer doesn't * support/want session timer. */ - PJSIP_INV_ALWAYS_USE_TIMER = 128, + PJSIP_INV_ALWAYS_USE_TIMER = 128, /** * Indicate support for trickle ICE @@ -430,37 +429,37 @@ struct pjsip_timer; */ struct pjsip_inv_session { - char obj_name[PJ_MAX_OBJ_NAME]; /**< Log identification */ - pj_pool_t *pool; /**< Long term pool. */ - pj_pool_t *pool_prov; /**< Provisional pool */ - pj_pool_t *pool_active; /**< Active/current pool*/ - pjsip_inv_state state; /**< Invite sess state. */ - pj_bool_t cancelling; /**< CANCEL requested */ - pj_bool_t pending_cancel; /**< Wait to send CANCEL*/ - pjsip_tx_data *pending_bye; /**< BYE to send later */ - pjsip_status_code cause; /**< Disconnect cause. */ - pj_str_t cause_text; /**< Cause text. */ - pj_bool_t notify; /**< Internal. */ - pj_bool_t sdp_done_early_rel; /**< Nego done in early - med was reliable? */ - unsigned cb_called; /**< Cb has been called */ - pjsip_dialog *dlg; /**< Underlying dialog. */ - pjsip_role_e role; /**< Invite role. */ - unsigned options; /**< Options in use. */ - pjmedia_sdp_neg *neg; /**< Negotiator. */ + char obj_name[PJ_MAX_OBJ_NAME]; /**< Log identification */ + pj_pool_t *pool; /**< Long term pool. */ + pj_pool_t *pool_prov; /**< Provisional pool */ + pj_pool_t *pool_active; /**< Active/current pool*/ + pjsip_inv_state state; /**< Invite sess state. */ + pj_bool_t cancelling; /**< CANCEL requested */ + pj_bool_t pending_cancel; /**< Wait to send CANCEL*/ + pjsip_tx_data *pending_bye; /**< BYE to send later */ + pjsip_status_code cause; /**< Disconnect cause. */ + pj_str_t cause_text; /**< Cause text. */ + pj_bool_t notify; /**< Internal. */ + pj_bool_t sdp_done_early_rel; /**< Nego done in early + med was reliable? */ + unsigned cb_called; /**< Cb has been called */ + pjsip_dialog *dlg; /**< Underlying dialog. */ + pjsip_role_e role; /**< Invite role. */ + unsigned options; /**< Options in use. */ + pjmedia_sdp_neg *neg; /**< Negotiator. */ unsigned sdp_neg_flags; /**< SDP neg flags. */ - pjsip_transaction *invite_tsx; /**< 1st invite tsx. */ - pjsip_tx_data *invite_req; /**< Saved invite req */ - pjsip_tx_data *last_answer; /**< Last INVITE resp. */ - pjsip_tx_data *last_ack; /**< Last ACK request */ - pj_int32_t last_ack_cseq; /**< CSeq of last ACK */ - void *mod_data[PJSIP_MAX_MODULE];/**< Modules data. */ - struct pjsip_timer *timer; /**< Session Timers. */ - pj_bool_t following_fork; /**< Internal, following - forked media? */ - pj_atomic_t *ref_cnt; /**< Reference counter. */ + pjsip_transaction *invite_tsx; /**< 1st invite tsx. */ + pjsip_tx_data *invite_req; /**< Saved invite req */ + pjsip_tx_data *last_answer; /**< Last INVITE resp. */ + pjsip_tx_data *last_ack; /**< Last ACK request */ + pj_int32_t last_ack_cseq; /**< CSeq of last ACK */ + void *mod_data[PJSIP_MAX_MODULE];/**< Modules data. */ + struct pjsip_timer *timer; /**< Session Timers. */ + pj_bool_t following_fork; /**< Internal, following + forked media? */ + pj_atomic_t *ref_cnt; /**< Reference counter. */ pj_bool_t updated_sdp_answer; /**< SDP answer just been - updated? */ + updated? */ }; @@ -476,13 +475,13 @@ typedef struct pjsip_sdp_info * the pointer is NULL, it means the message does not contain SDP * body. */ - pj_str_t body; + pj_str_t body; /** * This will contain non-zero if an invalid SDP body is found in the * message. */ - pj_status_t sdp_err; + pj_status_t sdp_err; /** * A parsed and validated SDP body. @@ -511,18 +510,18 @@ typedef pjsip_sdp_info pjsip_tdata_sdp_info; * The callback argument contains pointer to functions to be called on * occurences of events in invite sessions. * - * @param endpt The endpoint instance. - * @param cb Callback structure. + * @param endpt The endpoint instance. + * @param cb Callback structure. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_inv_usage_init(pjsip_endpoint *endpt, - const pjsip_inv_callback *cb); + const pjsip_inv_callback *cb); /** * Get the INVITE usage module instance. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pjsip_module*) pjsip_inv_usage_instance(void); @@ -536,23 +535,23 @@ PJ_DECL(void) pjsip_inv_usage_dump(void); /** * Create UAC invite session for the specified dialog in dlg. * - * @param dlg The dialog which will be used by this invite session. - * @param local_sdp If application has determined its media capability, - * it can specify the SDP here. Otherwise it can leave - * this to NULL, to let remote UAS specifies an offer. - * @param options The options argument is bitmask combination of SIP - * features in pjsip_inv_option enumeration. - * @param p_inv On successful return, the invite session will be put - * in this argument. - * - * @return The function will return PJ_SUCCESS if it can create - * the session. Otherwise the appropriate error status - * will be returned on failure. + * @param dlg The dialog which will be used by this invite session. + * @param local_sdp If application has determined its media capability, + * it can specify the SDP here. Otherwise it can leave + * this to NULL, to let remote UAS specifies an offer. + * @param options The options argument is bitmask combination of SIP + * features in pjsip_inv_option enumeration. + * @param p_inv On successful return, the invite session will be put + * in this argument. + * + * @return The function will return PJ_SUCCESS if it can create + * the session. Otherwise the appropriate error status + * will be returned on failure. */ PJ_DECL(pj_status_t) pjsip_inv_create_uac(pjsip_dialog *dlg, - const pjmedia_sdp_session *local_sdp, - unsigned options, - pjsip_inv_session **p_inv); + const pjmedia_sdp_session *local_sdp, + unsigned options, + pjsip_inv_session **p_inv); /** @@ -563,68 +562,68 @@ PJ_DECL(pj_status_t) pjsip_inv_create_uac(pjsip_dialog *dlg, * SIP extensions in the request (i.e. Require header) and also the media, * if media description is present in the request. * - * @param rdata The incoming INVITE request. - * - * @param options Upon calling this function, the options argument - * MUST contain the desired SIP extensions to be - * applied to the session. Upon return, this argument - * will contain the SIP extension that will be applied - * to the session, after considering the Supported, - * Require, and Allow headers in the request. - * - * @param sdp If local media capability has been determined, - * and if application wishes to verify that it can - * handle the media offer in the incoming INVITE - * request, it SHOULD specify its local media capability - * in this argument. - * If it is not specified, media verification will not - * be performed by this function. - * - * @param dlg If tdata is not NULL, application needs to specify - * how to create the response. Either dlg or endpt - * argument MUST be specified, with dlg argument takes - * precedence when both are specified. - * - * If a dialog has been created prior to calling this - * function, then it MUST be specified in dlg argument. - * Otherwise application MUST specify the endpt argument - * (this is useful e.g. when application wants to send - * the response statelessly). - * - * @param endpt If tdata is not NULL, application needs to specify - * how to create the response. Either dlg or endpt - * argument MUST be specified, with dlg argument takes - * precedence when both are specified. - * - * @param tdata If this argument is not NULL, this function will - * create the appropriate non-2xx final response message - * when the verification fails. - * - * @return If everything has been negotiated successfully, - * the function will return PJ_SUCCESS. Otherwise it - * will return the reason of the failure as the return - * code. - * - * This function is capable to create the appropriate - * response message when the verification has failed. - * If tdata is specified, then a non-2xx final response - * will be created and put in this argument upon return, - * when the verification has failed. - * - * If a dialog has been created prior to calling this - * function, then it MUST be specified in dlg argument. - * Otherwise application MUST specify the endpt argument - * (this is useful e.g. when application wants to send - * the response statelessly). + * @param rdata The incoming INVITE request. + * + * @param options Upon calling this function, the options argument + * MUST contain the desired SIP extensions to be + * applied to the session. Upon return, this argument + * will contain the SIP extension that will be applied + * to the session, after considering the Supported, + * Require, and Allow headers in the request. + * + * @param sdp If local media capability has been determined, + * and if application wishes to verify that it can + * handle the media offer in the incoming INVITE + * request, it SHOULD specify its local media capability + * in this argument. + * If it is not specified, media verification will not + * be performed by this function. + * + * @param dlg If tdata is not NULL, application needs to specify + * how to create the response. Either dlg or endpt + * argument MUST be specified, with dlg argument takes + * precedence when both are specified. + * + * If a dialog has been created prior to calling this + * function, then it MUST be specified in dlg argument. + * Otherwise application MUST specify the endpt argument + * (this is useful e.g. when application wants to send + * the response statelessly). + * + * @param endpt If tdata is not NULL, application needs to specify + * how to create the response. Either dlg or endpt + * argument MUST be specified, with dlg argument takes + * precedence when both are specified. + * + * @param tdata If this argument is not NULL, this function will + * create the appropriate non-2xx final response message + * when the verification fails. + * + * @return If everything has been negotiated successfully, + * the function will return PJ_SUCCESS. Otherwise it + * will return the reason of the failure as the return + * code. + * + * This function is capable to create the appropriate + * response message when the verification has failed. + * If tdata is specified, then a non-2xx final response + * will be created and put in this argument upon return, + * when the verification has failed. + * + * If a dialog has been created prior to calling this + * function, then it MUST be specified in dlg argument. + * Otherwise application MUST specify the endpt argument + * (this is useful e.g. when application wants to send + * the response statelessly). * * @see pjsip_inv_verify_request2() */ -PJ_DECL(pj_status_t) pjsip_inv_verify_request( pjsip_rx_data *rdata, - unsigned *options, - const pjmedia_sdp_session *sdp, - pjsip_dialog *dlg, - pjsip_endpoint *endpt, - pjsip_tx_data **tdata); +PJ_DECL(pj_status_t) pjsip_inv_verify_request( pjsip_rx_data *rdata, + unsigned *options, + const pjmedia_sdp_session *sdp, + pjsip_dialog *dlg, + pjsip_endpoint *endpt, + pjsip_tx_data **tdata); /** * Variant of #pjsip_inv_verify_request() which allows application to specify @@ -634,12 +633,12 @@ PJ_DECL(pj_status_t) pjsip_inv_verify_request( pjsip_rx_data *rdata, * @see pjsip_inv_verify_request() */ PJ_DECL(pj_status_t) pjsip_inv_verify_request2( pjsip_rx_data *rdata, - unsigned *options, - const pjmedia_sdp_session *offer, - const pjmedia_sdp_session *answer, - pjsip_dialog *dlg, - pjsip_endpoint *endpt, - pjsip_tx_data **tdata); + unsigned *options, + const pjmedia_sdp_session *offer, + const pjmedia_sdp_session *answer, + pjsip_dialog *dlg, + pjsip_endpoint *endpt, + pjsip_tx_data **tdata); /** * Variant of #pjsip_inv_verify_request() which allows application not to @@ -652,12 +651,12 @@ PJ_DECL(pj_status_t) pjsip_inv_verify_request2( pjsip_rx_data *rdata, */ PJ_DECL(pj_status_t) pjsip_inv_verify_request3( pjsip_rx_data *rdata, pj_pool_t *tmp_pool, - unsigned *options, - const pjmedia_sdp_session *offer, - const pjmedia_sdp_session *answer, - pjsip_dialog *dlg, - pjsip_endpoint *endpt, - pjsip_tx_data **tdata); + unsigned *options, + const pjmedia_sdp_session *offer, + const pjmedia_sdp_session *answer, + pjsip_dialog *dlg, + pjsip_endpoint *endpt, + pjsip_tx_data **tdata); /** @@ -665,32 +664,32 @@ PJ_DECL(pj_status_t) pjsip_inv_verify_request3( pjsip_rx_data *rdata, * SHOULD call the verification function before calling this function, * to ensure that it can create the session successfully. * - * @param dlg The dialog to be used. - * @param rdata Application MUST specify the received INVITE request - * in rdata. The invite session needs to inspect the - * received request to see if the request contains - * features that it supports. - * @param local_sdp If application has determined its media capability, - * it can specify this capability in this argument. - * If SDP is received in the initial INVITE, the UAS - * capability specified in this argument doesn't have to - * match the received offer; the SDP negotiator is able - * to rearrange the media lines in the answer so that it - * matches the offer. - * @param options The options argument is bitmask combination of SIP - * features in pjsip_inv_option enumeration. - * @param p_inv Pointer to receive the newly created invite session. - * - * @return On successful, the invite session will be put in - * p_inv argument and the function will return PJ_SUCCESS. - * Otherwise the appropriate error status will be returned - * on failure. + * @param dlg The dialog to be used. + * @param rdata Application MUST specify the received INVITE request + * in rdata. The invite session needs to inspect the + * received request to see if the request contains + * features that it supports. + * @param local_sdp If application has determined its media capability, + * it can specify this capability in this argument. + * If SDP is received in the initial INVITE, the UAS + * capability specified in this argument doesn't have to + * match the received offer; the SDP negotiator is able + * to rearrange the media lines in the answer so that it + * matches the offer. + * @param options The options argument is bitmask combination of SIP + * features in pjsip_inv_option enumeration. + * @param p_inv Pointer to receive the newly created invite session. + * + * @return On successful, the invite session will be put in + * p_inv argument and the function will return PJ_SUCCESS. + * Otherwise the appropriate error status will be returned + * on failure. */ PJ_DECL(pj_status_t) pjsip_inv_create_uas(pjsip_dialog *dlg, - pjsip_rx_data *rdata, - const pjmedia_sdp_session *local_sdp, - unsigned options, - pjsip_inv_session **p_inv); + pjsip_rx_data *rdata, + const pjmedia_sdp_session *local_sdp, + unsigned options, + pjsip_inv_session **p_inv); /** @@ -727,17 +726,17 @@ PJ_DECL(pj_status_t) pjsip_inv_dec_ref( pjsip_inv_session *inv ); * Note also that this function may terminate the underlying dialog, if * there are no other sessions in the dialog. * - * @param inv The invite session. - * @param st_code Status code for the reason of the termination. - * @param notify If set to non-zero, then on_state_changed() - * callback will be called. + * @param inv The invite session. + * @param st_code Status code for the reason of the termination. + * @param notify If set to non-zero, then on_state_changed() + * callback will be called. * - * @return PJ_SUCCESS if the INVITE session has been - * terminated. + * @return PJ_SUCCESS if the INVITE session has been + * terminated. */ PJ_DECL(pj_status_t) pjsip_inv_terminate( pjsip_inv_session *inv, - int st_code, - pj_bool_t notify ); + int st_code, + pj_bool_t notify ); /** @@ -748,14 +747,14 @@ PJ_DECL(pj_status_t) pjsip_inv_terminate( pjsip_inv_session *inv, * the session is restarted, application may create and send a new INVITE * request. * - * @param inv The invite session. - * @param new_offer Should be set to PJ_TRUE since the application will - * restart the session. + * @param inv The invite session. + * @param new_offer Should be set to PJ_TRUE since the application will + * restart the session. * - * @return PJ_SUCCESS on successful operation. + * @return PJ_SUCCESS on successful operation. */ PJ_DECL(pj_status_t) pjsip_inv_uac_restart(pjsip_inv_session *inv, - pj_bool_t new_offer); + pj_bool_t new_offer); /** @@ -773,18 +772,18 @@ PJ_DECL(pj_status_t) pjsip_inv_uac_restart(pjsip_inv_session *inv, * may also be called before this function returns if there is another target * to try. * - * @param inv The invite session. - * @param cmd Redirection operation. The semantic of this argument - * is similar to the description in the \a on_redirected() - * callback, except that the PJSIP_REDIRECT_PENDING is - * not accepted here. - * @param e Should be set to NULL. + * @param inv The invite session. + * @param cmd Redirection operation. The semantic of this argument + * is similar to the description in the \a on_redirected() + * callback, except that the PJSIP_REDIRECT_PENDING is + * not accepted here. + * @param e Should be set to NULL. * - * @return PJ_SUCCESS on successful operation. + * @return PJ_SUCCESS on successful operation. */ PJ_DECL(pj_status_t) pjsip_inv_process_redirect(pjsip_inv_session *inv, - pjsip_redirect_op cmd, - pjsip_event *e); + pjsip_redirect_op cmd, + pjsip_event *e); /** @@ -794,14 +793,14 @@ PJ_DECL(pj_status_t) pjsip_inv_process_redirect(pjsip_inv_session *inv, * in the outgoing INVITE request. Otherwise the outgoing request will not * contain SDP body. * - * @param inv The UAC invite session. - * @param p_tdata The initial INVITE request will be put in this - * argument if it can be created successfully. + * @param inv The UAC invite session. + * @param p_tdata The initial INVITE request will be put in this + * argument if it can be created successfully. * - * @return PJ_SUCCESS if the INVITE request can be created. + * @return PJ_SUCCESS if the INVITE request can be created. */ PJ_DECL(pj_status_t) pjsip_inv_invite( pjsip_inv_session *inv, - pjsip_tx_data **p_tdata ); + pjsip_tx_data **p_tdata ); /** @@ -809,73 +808,73 @@ PJ_DECL(pj_status_t) pjsip_inv_invite( pjsip_inv_session *inv, * rdata with status code st_code and optional status text st_text. Use * #pjsip_inv_answer() to create subsequent response message. */ -PJ_DECL(pj_status_t) pjsip_inv_initial_answer( pjsip_inv_session *inv, - pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - const pjmedia_sdp_session *sdp, - pjsip_tx_data **p_tdata); +PJ_DECL(pj_status_t) pjsip_inv_initial_answer( pjsip_inv_session *inv, + pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + const pjmedia_sdp_session *sdp, + pjsip_tx_data **p_tdata); /** * Create a response message to an INVITE request. * - * @param inv The UAS invite session. - * @param st_code The st_code contains the status code to be sent, - * which may be a provisional or final response. - * @param st_text If custom status text is desired, application can - * specify the text in st_text; otherwise if this - * argument is NULL, default status text will be used. - * @param local_sdp If application has specified its media capability - * during creation of UAS invite session, the local_sdp - * argument MUST be NULL. This is because application - * can not perform more than one SDP offer/answer session - * in a single INVITE transaction. - * If application has not specified its media capability - * during creation of UAS invite session, it MAY or MUST - * specify its capability in local_sdp argument, - * depending whether st_code indicates a 2xx final - * response. - * @param p_tdata Pointer to receive the response message created by - * this function. - * - * @return PJ_SUCCESS if response message was created - * successfully. + * @param inv The UAS invite session. + * @param st_code The st_code contains the status code to be sent, + * which may be a provisional or final response. + * @param st_text If custom status text is desired, application can + * specify the text in st_text; otherwise if this + * argument is NULL, default status text will be used. + * @param local_sdp If application has specified its media capability + * during creation of UAS invite session, the local_sdp + * argument MUST be NULL. This is because application + * can not perform more than one SDP offer/answer session + * in a single INVITE transaction. + * If application has not specified its media capability + * during creation of UAS invite session, it MAY or MUST + * specify its capability in local_sdp argument, + * depending whether st_code indicates a 2xx final + * response. + * @param p_tdata Pointer to receive the response message created by + * this function. + * + * @return PJ_SUCCESS if response message was created + * successfully. */ -PJ_DECL(pj_status_t) pjsip_inv_answer( pjsip_inv_session *inv, - int st_code, - const pj_str_t *st_text, - const pjmedia_sdp_session *local_sdp, - pjsip_tx_data **p_tdata ); +PJ_DECL(pj_status_t) pjsip_inv_answer( pjsip_inv_session *inv, + int st_code, + const pj_str_t *st_text, + const pjmedia_sdp_session *local_sdp, + pjsip_tx_data **p_tdata ); /** * Set local offer or answer depending on negotiator state (it may also * create a negotiator if it doesn't exist yet). * - * @param inv The invite session. - * @param sdp The SDP description which will be set as - * an offer/answer to remote. + * @param inv The invite session. + * @param sdp The SDP description which will be set as + * an offer/answer to remote. * - * @return PJ_SUCCESS if local offer/answer can be accepted by - * SDP negotiator. + * @return PJ_SUCCESS if local offer/answer can be accepted by + * SDP negotiator. */ PJ_DECL(pj_status_t) pjsip_inv_set_local_sdp(pjsip_inv_session *inv, - const pjmedia_sdp_session *sdp ); + const pjmedia_sdp_session *sdp ); /** * Set local answer to respond to remote SDP offer, to be carried by * subsequent response (or request). * - * @param inv The invite session. - * @param sdp The SDP description which will be set as answer - * to remote. + * @param inv The invite session. + * @param sdp The SDP description which will be set as answer + * to remote. * - * @return PJ_SUCCESS if local answer can be accepted by - * SDP negotiator. + * @return PJ_SUCCESS if local answer can be accepted by + * SDP negotiator. */ PJ_DECL(pj_status_t) pjsip_inv_set_sdp_answer(pjsip_inv_session *inv, - const pjmedia_sdp_session *sdp ); + const pjmedia_sdp_session *sdp ); /** @@ -899,19 +898,19 @@ PJ_DECL(pj_status_t) pjsip_inv_set_sdp_answer(pjsip_inv_session *inv, * For both UAC and UAS, if the INVITE session has been answered with final * response, a BYE request will be created. * - * @param inv The invite session. - * @param st_code Status code to be used for terminating the session. - * @param st_text Optional status text. - * @param p_tdata Pointer to receive the message to be created. Note - * that it's possible to receive NULL here while the - * function returns PJ_SUCCESS, see the description. + * @param inv The invite session. + * @param st_code Status code to be used for terminating the session. + * @param st_text Optional status text. + * @param p_tdata Pointer to receive the message to be created. Note + * that it's possible to receive NULL here while the + * function returns PJ_SUCCESS, see the description. * - * @return PJ_SUCCESS if termination is initiated. + * @return PJ_SUCCESS if termination is initiated. */ PJ_DECL(pj_status_t) pjsip_inv_end_session( pjsip_inv_session *inv, - int st_code, - const pj_str_t *st_text, - pjsip_tx_data **p_tdata ); + int st_code, + const pj_str_t *st_text, + pjsip_tx_data **p_tdata ); /** @@ -922,67 +921,67 @@ PJ_DECL(pj_status_t) pjsip_inv_end_session( pjsip_inv_session *inv, * provisional response. If then a provisional response is received, * the invite session will send CANCEL automatically. * - * @param inv The invite session. - * @param p_tdata Pointer to receive the message to be created. Note - * that it's possible to receive NULL here while the - * function returns PJ_SUCCESS, see the description. + * @param inv The invite session. + * @param p_tdata Pointer to receive the message to be created. Note + * that it's possible to receive NULL here while the + * function returns PJ_SUCCESS, see the description. * - * @return PJ_SUCCESS if termination is initiated. + * @return PJ_SUCCESS if termination is initiated. */ PJ_DECL(pj_status_t) pjsip_inv_cancel_reinvite( pjsip_inv_session *inv, - pjsip_tx_data **p_tdata ); + pjsip_tx_data **p_tdata ); /** * Create a re-INVITE request. * - * @param inv The invite session. - * @param new_contact If application wants to update its local contact and - * inform peer to perform target refresh with a new - * contact, it can specify the new contact in this - * argument; otherwise this argument must be NULL. - * @param new_offer Application MAY initiate a new SDP offer/answer - * session in the request when there is no pending - * answer to be sent or received. It can detect this - * condition by observing the state of the SDP - * negotiator of the invite session. If new offer - * should be sent to remote, the offer must be specified - * in this argument, otherwise it must be NULL. - * @param p_tdata Pointer to receive the re-INVITE request message to - * be created. - * - * @return PJ_SUCCESS if a re-INVITE request with the specified - * characteristics (e.g. to contain new offer) can be - * created. + * @param inv The invite session. + * @param new_contact If application wants to update its local contact and + * inform peer to perform target refresh with a new + * contact, it can specify the new contact in this + * argument; otherwise this argument must be NULL. + * @param new_offer Application MAY initiate a new SDP offer/answer + * session in the request when there is no pending + * answer to be sent or received. It can detect this + * condition by observing the state of the SDP + * negotiator of the invite session. If new offer + * should be sent to remote, the offer must be specified + * in this argument, otherwise it must be NULL. + * @param p_tdata Pointer to receive the re-INVITE request message to + * be created. + * + * @return PJ_SUCCESS if a re-INVITE request with the specified + * characteristics (e.g. to contain new offer) can be + * created. */ PJ_DECL(pj_status_t) pjsip_inv_reinvite(pjsip_inv_session *inv, - const pj_str_t *new_contact, - const pjmedia_sdp_session *new_offer, - pjsip_tx_data **p_tdata ); + const pj_str_t *new_contact, + const pjmedia_sdp_session *new_offer, + pjsip_tx_data **p_tdata ); /** * Create an UPDATE request to initiate new SDP offer. * - * @param inv The invite session. - * @param new_contact If application wants to update its local contact - * and inform peer to perform target refresh with a new - * contact, it can specify the new contact in this - * argument; otherwise this argument must be NULL. - * @param offer Offer to be sent to remote. This argument is - * mandatory. - * @param p_tdata Pointer to receive the UPDATE request message to - * be created. - * - * @return PJ_SUCCESS if a UPDATE request with the specified - * characteristics (e.g. to contain new offer) can be - * created. + * @param inv The invite session. + * @param new_contact If application wants to update its local contact + * and inform peer to perform target refresh with a new + * contact, it can specify the new contact in this + * argument; otherwise this argument must be NULL. + * @param offer Offer to be sent to remote. This argument is + * mandatory. + * @param p_tdata Pointer to receive the UPDATE request message to + * be created. + * + * @return PJ_SUCCESS if a UPDATE request with the specified + * characteristics (e.g. to contain new offer) can be + * created. */ -PJ_DECL(pj_status_t) pjsip_inv_update ( pjsip_inv_session *inv, - const pj_str_t *new_contact, - const pjmedia_sdp_session *offer, - pjsip_tx_data **p_tdata ); +PJ_DECL(pj_status_t) pjsip_inv_update ( pjsip_inv_session *inv, + const pj_str_t *new_contact, + const pjmedia_sdp_session *offer, + pjsip_tx_data **p_tdata ); /** @@ -997,54 +996,54 @@ PJ_DECL(pj_status_t) pjsip_inv_update ( pjsip_inv_session *inv, * prior to creating the ACK request. In this case, the ACK request * will be added with SDP message body. * - * @param inv The invite session. - * @param cseq Mandatory argument to specify the CSeq of the - * ACK request. This value MUST match the value - * of the INVITE transaction to be acknowledged. - * @param p_tdata Pointer to receive the ACK request message to - * be created. + * @param inv The invite session. + * @param cseq Mandatory argument to specify the CSeq of the + * ACK request. This value MUST match the value + * of the INVITE transaction to be acknowledged. + * @param p_tdata Pointer to receive the ACK request message to + * be created. * - * @return PJ_SUCCESS if ACK request has been created. + * @return PJ_SUCCESS if ACK request has been created. */ PJ_DECL(pj_status_t) pjsip_inv_create_ack(pjsip_inv_session *inv, - int cseq, - pjsip_tx_data **p_tdata); + int cseq, + pjsip_tx_data **p_tdata); /** * Send request or response message in tdata. * - * @param inv The invite session. - * @param tdata The message to be sent. + * @param inv The invite session. + * @param tdata The message to be sent. * - * @return PJ_SUCCESS if transaction can be initiated - * successfully to send this message. Note that the - * actual final state of the transaction itself will - * be reported later, in on_tsx_state_changed() - * callback. + * @return PJ_SUCCESS if transaction can be initiated + * successfully to send this message. Note that the + * actual final state of the transaction itself will + * be reported later, in on_tsx_state_changed() + * callback. */ PJ_DECL(pj_status_t) pjsip_inv_send_msg(pjsip_inv_session *inv, - pjsip_tx_data *tdata); + pjsip_tx_data *tdata); /** * Get the invite session for the dialog, if any. * - * @param dlg The dialog which invite session is being queried. + * @param dlg The dialog which invite session is being queried. * - * @return The invite session instance which has been - * associated with this dialog, or NULL. + * @return The invite session instance which has been + * associated with this dialog, or NULL. */ PJ_DECL(pjsip_inv_session*) pjsip_dlg_get_inv_session(pjsip_dialog *dlg); /** * Get the invite session instance associated with transaction tsx, if any. * - * @param tsx The transaction, which invite session is being - * queried. + * @param tsx The transaction, which invite session is being + * queried. * - * @return The invite session instance which has been - * associated with this transaction, or NULL. + * @return The invite session instance which has been + * associated with this transaction, or NULL. */ PJ_DECL(pjsip_inv_session*) pjsip_tsx_get_inv_session(pjsip_transaction *tsx); @@ -1052,9 +1051,9 @@ PJ_DECL(pjsip_inv_session*) pjsip_tsx_get_inv_session(pjsip_transaction *tsx); /** * Get state names for INVITE session state. * - * @param state The invite state. + * @param state The invite state. * - * @return String describing the state. + * @return String describing the state. */ PJ_DECL(const char *) pjsip_inv_state_name(pjsip_inv_state state); @@ -1062,27 +1061,27 @@ PJ_DECL(const char *) pjsip_inv_state_name(pjsip_inv_state state); /** * This is a utility function to create SIP body for SDP content. * - * @param pool Pool to allocate memory. - * @param sdp SDP session to be put in the SIP message body. - * @param p_body Pointer to receive SIP message body containing - * the SDP session. + * @param pool Pool to allocate memory. + * @param sdp SDP session to be put in the SIP message body. + * @param p_body Pointer to receive SIP message body containing + * the SDP session. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_create_sdp_body(pj_pool_t *pool, - pjmedia_sdp_session *sdp, - pjsip_msg_body **p_body); + pjmedia_sdp_session *sdp, + pjsip_msg_body **p_body); /** * This is a utility function to create a multipart body with the * SIP body as the first part. * - * @param pool Pool to allocate memory. - * @param sdp SDP session to be put in the SIP message body. - * @param p_body Pointer to receive SIP message body containing - * the SDP session. + * @param pool Pool to allocate memory. + * @param sdp SDP session to be put in the SIP message body. + * @param p_body Pointer to receive SIP message body containing + * the SDP session. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_create_multipart_sdp_body( pj_pool_t *pool, pjmedia_sdp_session *sdp, @@ -1107,9 +1106,9 @@ PJ_DECL(pj_status_t) pjsip_create_multipart_sdp_body( pj_pool_t *pool, * @return The SDP info. */ PJ_DECL(pjsip_sdp_info*) pjsip_get_sdp_info(pj_pool_t *pool, - pjsip_msg_body *body, - pjsip_media_type *msg_media_type, - const pjsip_media_type *search_media_type); + pjsip_msg_body *body, + pjsip_media_type *msg_media_type, + const pjsip_media_type *search_media_type); /** * Retrieve SDP information from an incoming message. Application should @@ -1120,9 +1119,9 @@ PJ_DECL(pjsip_sdp_info*) pjsip_get_sdp_info(pj_pool_t *pool, * on the same message. Subsequent call on the same message will just pick * up the already parsed SDP from the message. * - * @param rdata The incoming message. + * @param rdata The incoming message. * - * @return The SDP info. + * @return The SDP info. */ PJ_DECL(pjsip_rdata_sdp_info*) pjsip_rdata_get_sdp_info(pjsip_rx_data *rdata); @@ -1143,8 +1142,8 @@ PJ_DECL(pjsip_rdata_sdp_info*) pjsip_rdata_get_sdp_info(pjsip_rx_data *rdata); * @return The SDP info. */ PJ_DECL(pjsip_rdata_sdp_info*) pjsip_rdata_get_sdp_info2( - pjsip_rx_data *rdata, - const pjsip_media_type *search_media_type); + pjsip_rx_data *rdata, + const pjsip_media_type *search_media_type); /** * Retrieve SDP information from an outgoing message. Application should @@ -1177,8 +1176,8 @@ PJ_DECL(pjsip_tdata_sdp_info*) pjsip_tdata_get_sdp_info(pjsip_tx_data *tdata); * @return The SDP info. */ PJ_DECL(pjsip_tdata_sdp_info*) pjsip_tdata_get_sdp_info2( - pjsip_tx_data *tdata, - const pjsip_media_type *search_media_type); + pjsip_tx_data *tdata, + const pjsip_media_type *search_media_type); PJ_END_DECL @@ -1188,4 +1187,4 @@ PJ_END_DECL */ -#endif /* __SIP_INVITE_SESSION_H__ */ +#endif /* __SIP_INVITE_SESSION_H__ */ diff --git a/pjsip/include/pjsip-ua/sip_regc.h b/pjsip/include/pjsip-ua/sip_regc.h index 03d18c371e..df97a6011d 100644 --- a/pjsip/include/pjsip-ua/sip_regc.h +++ b/pjsip/include/pjsip-ua/sip_regc.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -48,13 +47,13 @@ PJ_BEGIN_DECL typedef struct pjsip_regc pjsip_regc; /** Maximum contacts in registration. */ -#define PJSIP_REGC_MAX_CONTACT 10 +#define PJSIP_REGC_MAX_CONTACT 10 /** Expiration not specified. */ -#define PJSIP_REGC_EXPIRATION_NOT_SPECIFIED PJSIP_EXPIRES_NOT_SPECIFIED +#define PJSIP_REGC_EXPIRATION_NOT_SPECIFIED PJSIP_EXPIRES_NOT_SPECIFIED /** Buffer to hold all contacts. */ -#define PJSIP_REGC_CONTACT_BUF_SIZE 512 +#define PJSIP_REGC_CONTACT_BUF_SIZE 512 /** Structure to hold parameters when calling application's callback. * The application's callback is called when the client registration process @@ -62,24 +61,24 @@ typedef struct pjsip_regc pjsip_regc; */ struct pjsip_regc_cbparam { - pjsip_regc *regc; /**< Client registration structure. */ - void *token; /**< Arbitrary token set by application */ + pjsip_regc *regc; /**< Client registration structure. */ + void *token; /**< Arbitrary token set by application */ /** Error status. If this value is non-PJ_SUCCESS, some error has occured. * Note that even when this contains PJ_SUCCESS the registration might * have failed; in this case the \a code field will contain non * successful (non-2xx status class) code */ - pj_status_t status; - int code; /**< SIP status code received. */ - pj_str_t reason; /**< SIP reason phrase received. */ - pjsip_rx_data *rdata; /**< The complete received response. */ - unsigned expiration;/**< Next expiration interval, - PJSIP_REGC_EXPIRATION_NOT_SPECIFIED - if not specified. */ - int contact_cnt;/**". If no "<" and ">" are - * present, all parameters after the URI are header - * parameters, not URI parameters. The display name - * can be tokens, or a quoted string, if a larger - * character set is desired. + * as described in RFC 3261 Section 20.10: + * When the header field value contains a display + * name, the URI including all URI parameters is + * enclosed in "<" and ">". If no "<" and ">" are + * present, all parameters after the URI are header + * parameters, not URI parameters. The display name + * can be tokens, or a quoted string, if a larger + * character set is desired. * @param expires Default expiration interval (in seconds) to be applied for - * contact URL that doesn't have expiration settings. If the - * value PJSIP_REGC_EXPIRATION_NOT_SPECIFIED is given, then - * no default expiration will be applied. - * @return zero on success. + * contact URL that doesn't have expiration settings. If the + * value PJSIP_REGC_EXPIRATION_NOT_SPECIFIED is given, then + * no default expiration will be applied. + * @return zero on success. */ PJ_DECL(pj_status_t) pjsip_regc_init(pjsip_regc *regc, - const pj_str_t *srv_url, - const pj_str_t *from_url, - const pj_str_t *to_url, - int ccnt, - const pj_str_t contact[], - pj_uint32_t expires); + const pj_str_t *srv_url, + const pj_str_t *from_url, + const pj_str_t *to_url, + int ccnt, + const pj_str_t contact[], + pj_uint32_t expires); /** * Increment busy counter temporarily, to prevent client registration * structure from being destroyed. * - * @param regc The client registration structure. + * @param regc The client registration structure. */ PJ_DECL(void) pjsip_regc_add_ref( pjsip_regc *regc ); @@ -247,10 +246,10 @@ PJ_DECL(void) pjsip_regc_add_ref( pjsip_regc *regc ); * is called, client registration structure may have been destroyed * if there's a pending destroy. * - * @param regc The client registration structure. + * @param regc The client registration structure. * - * @return PJ_SUCCESS on success. PJ_EGONE if the registration - * structure has been destroyed inside the function. + * @return PJ_SUCCESS on success. PJ_EGONE if the registration + * structure has been destroyed inside the function. */ PJ_DECL(pj_status_t) pjsip_regc_dec_ref( pjsip_regc *regc ); @@ -262,78 +261,78 @@ PJ_DECL(pj_status_t) pjsip_regc_dec_ref( pjsip_regc *regc ); * (including 401/407/423) and before any subsequent requests are sent. * In case of unregistration, this callback will not be called. * - * @param regc The client registration structure. + * @param regc The client registration structure. * @param tsx_cb Pointer to callback function to receive registration status. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_regc_set_reg_tsx_cb(pjsip_regc *regc, - pjsip_regc_tsx_cb *tsx_cb); + pjsip_regc_tsx_cb *tsx_cb); /** * Set the "sent-by" field of the Via header for outgoing requests. * - * @param regc The client registration structure. + * @param regc The client registration structure. * @param via_addr Set via_addr to use for the Via header or NULL to use * the transport's published name. * @param via_tp via_addr will only be used if we are using via_tp * transport. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_regc_set_via_sent_by(pjsip_regc *regc, - pjsip_host_port *via_addr, + pjsip_host_port *via_addr, pjsip_transport *via_tp); /** * Set the number of seconds to refresh the client registration before * the registration expires. * - * @param regc The registration structure. + * @param regc The registration structure. * @param delay The number of seconds to refresh the client * registration before the registration expires. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_regc_set_delay_before_refresh( pjsip_regc *regc, - pj_uint32_t delay ); + pj_uint32_t delay ); /** * Set authentication credentials to use by this registration. * - * @param regc The registration structure. - * @param count Number of credentials in the array. - * @param cred Array of credentials. + * @param regc The registration structure. + * @param count Number of credentials in the array. + * @param cred Array of credentials. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_regc_set_credentials( pjsip_regc *regc, - int count, - const pjsip_cred_info cred[] ); + int count, + const pjsip_cred_info cred[] ); /** * Set authentication preference. * - * @param regc The registration structure. - * @param pref Authentication preference. + * @param regc The registration structure. + * @param pref Authentication preference. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_regc_set_prefs( pjsip_regc *regc, - const pjsip_auth_clt_pref *pref); + const pjsip_auth_clt_pref *pref); /** * Set route set to be used for outgoing requests. * - * @param regc The client registration structure. + * @param regc The client registration structure. * @param route_set List containing Route headers. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_regc_set_route_set(pjsip_regc *regc, - const pjsip_route_hdr*route_set); + const pjsip_route_hdr*route_set); /** @@ -350,15 +349,15 @@ PJ_DECL(pj_status_t) pjsip_regc_set_route_set(pjsip_regc *regc, * necessary, to adjust the address according to the transport being * selected. * - * @param regc The client registration instance. - * @param sel Transport selector containing the specification of - * transport or listener to be used by this session - * to send requests. + * @param regc The client registration instance. + * @param sel Transport selector containing the specification of + * transport or listener to be used by this session + * to send requests. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_regc_set_transport(pjsip_regc *regc, - const pjsip_tpselector *sel); + const pjsip_tpselector *sel); /** * Release the reference to current transport being used by the regc, if any. @@ -368,23 +367,23 @@ PJ_DECL(pj_status_t) pjsip_regc_set_transport(pjsip_regc *regc, * regc to release this reference so that the transport can be destroyed. * See https://github.com/pjsip/pjproject/issues/1481 for background info. * - * @param regc The client registration instance. + * @param regc The client registration instance. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_regc_release_transport(pjsip_regc *regc); /** * Add headers to be added to outgoing REGISTER requests. * - * @param regc The client registration structure. + * @param regc The client registration structure. * @param hdr_list List containing SIP headers to be added for all outgoing - * REGISTER requests. + * REGISTER requests. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_regc_add_headers(pjsip_regc *regc, - const pjsip_hdr *hdr_list); + const pjsip_hdr *hdr_list); /** @@ -394,28 +393,28 @@ PJ_DECL(pj_status_t) pjsip_regc_add_headers(pjsip_regc *regc, * the client registration structure to list what contacts are associaciated * with the address of record being targeted in the registration. * - * @param regc The client registration structure. + * @param regc The client registration structure. * @param autoreg If non zero, the library will automatically refresh the - * next registration until application unregister. + * next registration until application unregister. * @param p_tdata Pointer to receive the REGISTER request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_regc_register(pjsip_regc *regc, pj_bool_t autoreg, - pjsip_tx_data **p_tdata); + pjsip_tx_data **p_tdata); /** * Create REGISTER request to unregister the contacts that were previously * registered by this client registration. * - * @param regc The client registration structure. + * @param regc The client registration structure. * @param p_tdata Pointer to receive the REGISTER request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_regc_unregister(pjsip_regc *regc, - pjsip_tx_data **p_tdata); + pjsip_tx_data **p_tdata); /** * Create REGISTER request to unregister all contacts from server records. @@ -424,13 +423,13 @@ PJ_DECL(pj_status_t) pjsip_regc_unregister(pjsip_regc *regc, * contact registered by this client registration instance, use * #pjsip_regc_unregister() instead. * - * @param regc The client registration structure. + * @param regc The client registration structure. * @param p_tdata Pointer to receive the REGISTER request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_regc_unregister_all(pjsip_regc *regc, - pjsip_tx_data **p_tdata); + pjsip_tx_data **p_tdata); /** * Update Contact details in the client registration structure. For each @@ -446,43 +445,43 @@ PJ_DECL(pj_status_t) pjsip_regc_unregister_all(pjsip_regc *regc, * old contacts will have it's expires parameter set to zero to instruct * the registrar to remove the bindings. * - * @param regc The client registration structure. - * @param ccnt Number of contacts. + * @param regc The client registration structure. + * @param ccnt Number of contacts. * @param contact Array of contacts, each contact item must be formatted - * as described in RFC 3261 Section 20.10: - * When the header field value contains a display - * name, the URI including all URI parameters is - * enclosed in "<" and ">". If no "<" and ">" are - * present, all parameters after the URI are header - * parameters, not URI parameters. The display name - * can be tokens, or a quoted string, if a larger - * character set is desired. - * @return PJ_SUCCESS if sucessfull. + * as described in RFC 3261 Section 20.10: + * When the header field value contains a display + * name, the URI including all URI parameters is + * enclosed in "<" and ">". If no "<" and ">" are + * present, all parameters after the URI are header + * parameters, not URI parameters. The display name + * can be tokens, or a quoted string, if a larger + * character set is desired. + * @return PJ_SUCCESS if sucessfull. */ PJ_DECL(pj_status_t) pjsip_regc_update_contact( pjsip_regc *regc, - int ccnt, - const pj_str_t contact[] ); + int ccnt, + const pj_str_t contact[] ); /** * Update the expires value. The next REGISTER request will contain * new expires value for the registration. * - * @param regc The client registration structure. + * @param regc The client registration structure. * @param expires The new expires value. - * @return zero on successfull. + * @return zero on successfull. */ PJ_DECL(pj_status_t) pjsip_regc_update_expires( pjsip_regc *regc, - pj_uint32_t expires ); + pj_uint32_t expires ); /** * Sends outgoing REGISTER request. * The process will complete asynchronously, and application * will be notified via the callback when the process completes. * - * @param regc The client registration structure. - * @param tdata Transmit data. + * @param regc The client registration structure. + * @param tdata Transmit data. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_regc_send(pjsip_regc *regc, pjsip_tx_data *tdata); @@ -493,4 +492,4 @@ PJ_END_DECL * @} */ -#endif /* __PJSIP_REG_H__ */ +#endif /* __PJSIP_REG_H__ */ diff --git a/pjsip/include/pjsip-ua/sip_replaces.h b/pjsip/include/pjsip-ua/sip_replaces.h index a5196e4e76..cfe2038a22 100644 --- a/pjsip/include/pjsip-ua/sip_replaces.h +++ b/pjsip/include/pjsip-ua/sip_replaces.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -126,17 +125,17 @@ // status = pjsip_replaces_verify_request(rdata, &replaced_dlg, PJ_FALSE, &response); if (status != PJ_SUCCESS) { - // Something wrong with Replaces request. - // - pj_status_t status; - if (response) { - status = pjsip_endpt_send_response(endpt, rdata, response, NULL, NULL); - if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(tdata); - } else { - // Respond with 500 (Internal Server Error) - status = pjsip_endpt_respond_stateless(endpt, rdata, 500, NULL, NULL, NULL); - if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(tdata); - } + // Something wrong with Replaces request. + // + pj_status_t status; + if (response) { + status = pjsip_endpt_send_response(endpt, rdata, response, NULL, NULL); + if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(tdata); + } else { + // Respond with 500 (Internal Server Error) + status = pjsip_endpt_respond_stateless(endpt, rdata, 500, NULL, NULL, NULL); + if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(tdata); + } } // Create UAS Invite session as usual. @@ -149,43 +148,43 @@ // status = pjsip_inv_initial_answer(inv, rdata, 100, ..., &response); if (status == PJ_SUCCESS) - pjsip_inv_send_msg(inv, response); + pjsip_inv_send_msg(inv, response); // This is where processing is different between normal call // (without Replaces) and call with Replaces. // if (replaced_dlg) { - pjsip_inv_session *replaced_inv; + pjsip_inv_session *replaced_inv; - // Always answer the new INVITE with 200, regardless whether - // the replaced call is in early or confirmed state. - // - status = pjsip_inv_answer(inv, 200, NULL, NULL, &response); - if (status == PJ_SUCCESS) - pjsip_inv_send_msg(inv, response); + // Always answer the new INVITE with 200, regardless whether + // the replaced call is in early or confirmed state. + // + status = pjsip_inv_answer(inv, 200, NULL, NULL, &response); + if (status == PJ_SUCCESS) + pjsip_inv_send_msg(inv, response); - // Get the INVITE session associated with the replaced dialog. - // - replaced_inv = pjsip_dlg_get_inv_session(replaced_dlg); + // Get the INVITE session associated with the replaced dialog. + // + replaced_inv = pjsip_dlg_get_inv_session(replaced_dlg); - // Disconnect the "replaced" INVITE session. - // - status = pjsip_inv_end_session(replaced_inv, PJSIP_SC_GONE, NULL, &tdata); - if (status == PJ_SUCCESS && tdata) - status = pjsip_inv_send_msg(replaced_inv, tdata); + // Disconnect the "replaced" INVITE session. + // + status = pjsip_inv_end_session(replaced_inv, PJSIP_SC_GONE, NULL, &tdata); + if (status == PJ_SUCCESS && tdata) + status = pjsip_inv_send_msg(replaced_inv, tdata); - // It's up to application to associate the new INVITE session - // with the old (now terminated) session. For example, application - // may assign the same User Interface object for the new INVITE - // session. + // It's up to application to associate the new INVITE session + // with the old (now terminated) session. For example, application + // may assign the same User Interface object for the new INVITE + // session. } else { - // Process normal INVITE without Replaces. - ... + // Process normal INVITE without Replaces. + ... } } @@ -216,19 +215,19 @@ typedef struct pjsip_replaces_hdr PJSIP_DECL_HDR_MEMBER(struct pjsip_replaces_hdr); /** Call-Id */ - pj_str_t call_id; + pj_str_t call_id; /** to-tag */ - pj_str_t to_tag; + pj_str_t to_tag; /** from-tag */ - pj_str_t from_tag; + pj_str_t from_tag; /** early-only? */ - pj_bool_t early_only; + pj_bool_t early_only; /** Other parameters */ - pjsip_param other_param; + pjsip_param other_param; } pjsip_replaces_hdr; @@ -238,9 +237,9 @@ typedef struct pjsip_replaces_hdr * Initialize Replaces support in PJSIP. This would, among other things, * register the header parser for Replaces header. * - * @param endpt The endpoint instance. + * @param endpt The endpoint instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_replaces_init_module(pjsip_endpoint *endpt); @@ -248,9 +247,9 @@ PJ_DECL(pj_status_t) pjsip_replaces_init_module(pjsip_endpoint *endpt); /** * Create Replaces header. * - * @param pool Pool to allocate the header instance from. + * @param pool Pool to allocate the header instance from. * - * @return An empty Replaces header instance. + * @return An empty Replaces header instance. */ PJ_DECL(pjsip_replaces_hdr*) pjsip_replaces_hdr_create(pj_pool_t *pool); @@ -260,35 +259,35 @@ PJ_DECL(pjsip_replaces_hdr*) pjsip_replaces_hdr_create(pj_pool_t *pool); * This function will perform all necessary checks according to RFC 3891 * Section 3 "User Agent Server Behavior: Receiving a Replaces Header". * - * @param rdata The incoming request to be verified. - * @param p_dlg On return, it will be filled with the matching - * dialog. + * @param rdata The incoming request to be verified. + * @param p_dlg On return, it will be filled with the matching + * dialog. * @param lock_dlg Specifies whether this function should acquire lock - * to the matching dialog. If yes (and should be yes!), - * then application will need to release the dialog's - * lock with #pjsip_dlg_dec_lock() when the function - * returns PJ_SUCCESS and the \a p_dlg parameter is filled - * with the dialog instance. + * to the matching dialog. If yes (and should be yes!), + * then application will need to release the dialog's + * lock with #pjsip_dlg_dec_lock() when the function + * returns PJ_SUCCESS and the \a p_dlg parameter is filled + * with the dialog instance. * @param p_tdata Upon error, it will be filled with the final response - * to be sent to the request sender. - * - * @return The function returns the following: - * - If the request doesn't contain Replaces header, the - * function returns PJ_SUCCESS and \a p_dlg parameter - * will be set to NULL. - * - If the request contains Replaces header and a valid, - * matching dialog is found, the function returns - * PJ_SUCCESS and \a p_dlg parameter will be set to the - * matching dialog instance. - * - Upon error condition (as described by RFC 3891), the - * function returns non-PJ_SUCCESS, and \a p_tdata - * parameter SHOULD be set with a final response message - * to be sent to the sender of the request. + * to be sent to the request sender. + * + * @return The function returns the following: + * - If the request doesn't contain Replaces header, the + * function returns PJ_SUCCESS and \a p_dlg parameter + * will be set to NULL. + * - If the request contains Replaces header and a valid, + * matching dialog is found, the function returns + * PJ_SUCCESS and \a p_dlg parameter will be set to the + * matching dialog instance. + * - Upon error condition (as described by RFC 3891), the + * function returns non-PJ_SUCCESS, and \a p_tdata + * parameter SHOULD be set with a final response message + * to be sent to the sender of the request. */ PJ_DECL(pj_status_t) pjsip_replaces_verify_request(pjsip_rx_data *rdata, - pjsip_dialog **p_dlg, - pj_bool_t lock_dlg, - pjsip_tx_data **p_tdata); + pjsip_dialog **p_dlg, + pj_bool_t lock_dlg, + pjsip_tx_data **p_tdata); @@ -300,5 +299,5 @@ PJ_END_DECL */ -#endif /* __PJSIP_REPLACES_H__ */ +#endif /* __PJSIP_REPLACES_H__ */ diff --git a/pjsip/include/pjsip-ua/sip_timer.h b/pjsip/include/pjsip-ua/sip_timer.h index 9460423b8d..19d8ce8d85 100644 --- a/pjsip/include/pjsip-ua/sip_timer.h +++ b/pjsip/include/pjsip-ua/sip_timer.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * @@ -58,13 +57,13 @@ typedef struct pjsip_timer_setting * Specify minimum session expiration period, in seconds. Must not be * lower than 90. Default is 90. */ - unsigned min_se; + unsigned min_se; /** * Specify session expiration period, in seconds. Must not be lower than * #min_se. Default is 1800. */ - unsigned sess_expires; + unsigned sess_expires; } pjsip_timer_setting; @@ -78,13 +77,13 @@ typedef struct pjsip_sess_expires_hdr PJSIP_DECL_HDR_MEMBER(struct pjsip_sess_expires_hdr); /** Session expiration period */ - unsigned sess_expires; + unsigned sess_expires; /** Refresher */ - pj_str_t refresher; + pj_str_t refresher; /** Other parameters */ - pjsip_param other_param; + pjsip_param other_param; } pjsip_sess_expires_hdr; @@ -98,10 +97,10 @@ typedef struct pjsip_min_se_hdr PJSIP_DECL_HDR_MEMBER(struct pjsip_min_se_hdr); /** Minimum session expiration period */ - unsigned min_se; + unsigned min_se; /** Other parameters */ - pjsip_param other_param; + pjsip_param other_param; } pjsip_min_se_hdr; @@ -111,9 +110,9 @@ typedef struct pjsip_min_se_hdr * Initialize Session Timers module. This function must be called once during * application initialization, to register this module to SIP endpoint. * - * @param endpt The SIP endpoint instance. + * @param endpt The SIP endpoint instance. * - * @return PJ_SUCCESS if module is successfully initialized. + * @return PJ_SUCCESS if module is successfully initialized. */ PJ_DECL(pj_status_t) pjsip_timer_init_module(pjsip_endpoint *endpt); @@ -121,9 +120,9 @@ PJ_DECL(pj_status_t) pjsip_timer_init_module(pjsip_endpoint *endpt); /** * Initialize Session Timers setting with default values. * - * @param setting Session Timers setting to be initialized. + * @param setting Session Timers setting to be initialized. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_timer_setting_default(pjsip_timer_setting *setting); @@ -133,34 +132,34 @@ PJ_DECL(pj_status_t) pjsip_timer_setting_default(pjsip_timer_setting *setting); * called by application to apply Session Timers setting, otherwise invite * session will apply default setting to the Session Timers. * - * @param inv The invite session. - * @param setting Session Timers setting, see pjsip_timer_setting. - * If setting is NULL, default setting will be applied. + * @param inv The invite session. + * @param setting Session Timers setting, see pjsip_timer_setting. + * If setting is NULL, default setting will be applied. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_timer_init_session( - pjsip_inv_session *inv, - const pjsip_timer_setting *setting); + pjsip_inv_session *inv, + const pjsip_timer_setting *setting); /** * Create Session-Expires header. * - * @param pool Pool to allocate the header instance from. + * @param pool Pool to allocate the header instance from. * - * @return An empty Session-Expires header instance. + * @return An empty Session-Expires header instance. */ PJ_DECL(pjsip_sess_expires_hdr*) pjsip_sess_expires_hdr_create( - pj_pool_t *pool); + pj_pool_t *pool); /** * Create Min-SE header. * - * @param pool Pool to allocate the header instance from. + * @param pool Pool to allocate the header instance from. * - * @return An empty Min-SE header instance. + * @return An empty Min-SE header instance. */ PJ_DECL(pjsip_min_se_hdr*) pjsip_min_se_hdr_create(pj_pool_t *pool); @@ -172,13 +171,13 @@ PJ_DECL(pjsip_min_se_hdr*) pjsip_min_se_hdr_create(pj_pool_t *pool); * This function will be called internally by the invite session if it * detects that the session needs Session Timers support. * - * @param inv The invite session. - * @param tdata Outgoing INVITE or UPDATE request. + * @param inv The invite session. + * @param tdata Outgoing INVITE or UPDATE request. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_timer_update_req(pjsip_inv_session *inv, - pjsip_tx_data *tdata); + pjsip_tx_data *tdata); /** @@ -189,30 +188,30 @@ PJ_DECL(pj_status_t) pjsip_timer_update_req(pjsip_inv_session *inv, * This function will be called internally by the invite session if it * detects that the session needs Session Timers support. * - * @param inv The invite session. - * @param rdata Incoming response data. - * @param st_code Output buffer to store corresponding SIP status code - * when function returning non-PJ_SUCCESS. + * @param inv The invite session. + * @param rdata Incoming response data. + * @param st_code Output buffer to store corresponding SIP status code + * when function returning non-PJ_SUCCESS. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_timer_process_resp(pjsip_inv_session *inv, - const pjsip_rx_data *rdata, - pjsip_status_code *st_code); + const pjsip_rx_data *rdata, + pjsip_status_code *st_code); /** * Process Session Timers refresh error, this function will process * error from refresh request. The error will be handle according the * error code, i.e : BYE will be sent after error 503 (Transport Error). * - * @param inv The invite session. - * @param event The event that trigger the error. + * @param inv The invite session. + * @param event The event that trigger the error. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_timer_handle_refresh_error( - pjsip_inv_session *inv, - pjsip_event *event); + pjsip_inv_session *inv, + pjsip_event *event); /** * Process Session Timers headers in incoming request, this function @@ -221,16 +220,16 @@ PJ_DECL(pj_status_t) pjsip_timer_handle_refresh_error( * This function will be called internally by the invite session if it * detects that the session needs Session Timers support. * - * @param inv The invite session. - * @param rdata Incoming INVITE or UPDATE request. - * @param st_code Output buffer to store corresponding SIP status code - * when function returning non-PJ_SUCCESS. + * @param inv The invite session. + * @param rdata Incoming INVITE or UPDATE request. + * @param st_code Output buffer to store corresponding SIP status code + * when function returning non-PJ_SUCCESS. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_timer_process_req(pjsip_inv_session *inv, - const pjsip_rx_data *rdata, - pjsip_status_code *st_code); + const pjsip_rx_data *rdata, + pjsip_status_code *st_code); /** @@ -242,13 +241,13 @@ PJ_DECL(pj_status_t) pjsip_timer_process_req(pjsip_inv_session *inv, * This function will be called internally by the invite session if it * detects that the session needs Session Timers support. * - * @param inv The invite session. - * @param tdata Outgoing 422/2xx response. + * @param inv The invite session. + * @param tdata Outgoing 422/2xx response. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_timer_update_resp(pjsip_inv_session *inv, - pjsip_tx_data *tdata); + pjsip_tx_data *tdata); /** * End Session Timers in an invite session. @@ -256,9 +255,9 @@ PJ_DECL(pj_status_t) pjsip_timer_update_resp(pjsip_inv_session *inv, * This function will be called internally by the invite session if it * detects that the session needs Session Timers support. * - * @param inv The invite session. + * @param inv The invite session. * - * @return PJ_SUCCESS on successful. + * @return PJ_SUCCESS on successful. */ PJ_DECL(pj_status_t) pjsip_timer_end_session(pjsip_inv_session *inv); @@ -272,4 +271,4 @@ PJ_END_DECL */ -#endif /* __PJSIP_TIMER_H__ */ +#endif /* __PJSIP_TIMER_H__ */ diff --git a/pjsip/include/pjsip-ua/sip_xfer.h b/pjsip/include/pjsip-ua/sip_xfer.h index b8d8126383..d8502873eb 100644 --- a/pjsip/include/pjsip-ua/sip_xfer.h +++ b/pjsip/include/pjsip-ua/sip_xfer.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -80,90 +79,90 @@ PJ_DECL(pj_status_t) pjsip_xfer_init_module(pjsip_endpoint *endpt); /** * Create transferer (sender of REFER request). * - * @param dlg The underlying dialog to use. - * @param user_cb Pointer to callbacks to receive presence subscription - * events. - * @param p_evsub Pointer to receive the presence subscription - * session. + * @param dlg The underlying dialog to use. + * @param user_cb Pointer to callbacks to receive presence subscription + * events. + * @param p_evsub Pointer to receive the presence subscription + * session. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_xfer_create_uac( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - pjsip_evsub **p_evsub ); + const pjsip_evsub_user *user_cb, + pjsip_evsub **p_evsub ); /** * Create transferee (receiver of REFER request). * - * @param dlg The underlying dialog to use. - * @param user_cb Pointer to callbacks to receive presence subscription - * events. - * @param rdata The incoming SUBSCRIBE request that creates the event - * subscription. - * @param p_evsub Pointer to receive the presence subscription - * session. + * @param dlg The underlying dialog to use. + * @param user_cb Pointer to callbacks to receive presence subscription + * events. + * @param rdata The incoming SUBSCRIBE request that creates the event + * subscription. + * @param p_evsub Pointer to receive the presence subscription + * session. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_xfer_create_uas( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - pjsip_rx_data *rdata, - pjsip_evsub **p_evsub ); + const pjsip_evsub_user *user_cb, + pjsip_rx_data *rdata, + pjsip_evsub **p_evsub ); /** * Call this function to create request to initiate REFER subscription, * to refresh subscription, or to unsubscribe. For request other than * the initial REFER request, "refer_to_uri" argument may be NULL. * - * @param sub Client subscription instance. - * @param refer_to_uri URI to be put to the Refer-To header. This argument - * may be NULL for subsequent REFER requests. - * @param p_tdata Pointer to receive the request. + * @param sub Client subscription instance. + * @param refer_to_uri URI to be put to the Refer-To header. This argument + * may be NULL for subsequent REFER requests. + * @param p_tdata Pointer to receive the request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_xfer_initiate( pjsip_evsub *sub, - const pj_str_t *refer_to_uri, - pjsip_tx_data **p_tdata); + const pj_str_t *refer_to_uri, + pjsip_tx_data **p_tdata); /** * Accept the incoming REFER request by sending 2xx response. * - * @param sub Server subscription instance. - * @param rdata The incoming subscription request message. - * @param st_code Status code, which MUST be 2xx. - * @param hdr_list Optional list of headers to be added in the response. + * @param sub Server subscription instance. + * @param rdata The incoming subscription request message. + * @param st_code Status code, which MUST be 2xx. + * @param hdr_list Optional list of headers to be added in the response. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_xfer_accept( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int st_code, - const pjsip_hdr *hdr_list ); + pjsip_rx_data *rdata, + int st_code, + const pjsip_hdr *hdr_list ); /** * For notifier, create NOTIFY request to subscriber, and set the state * of the subscription. * - * @param sub The server subscription (notifier) instance. - * @param state New state to set. - * @param xfer_st_code The call status code to be reported with the NOTIFY - * request. - * @param xfer_st_text Optional call status text to be reported with the - * NOTIFY request. If the value is NULL, default - * status text will be used. - * @param p_tdata Pointer to receive the request. + * @param sub The server subscription (notifier) instance. + * @param state New state to set. + * @param xfer_st_code The call status code to be reported with the NOTIFY + * request. + * @param xfer_st_text Optional call status text to be reported with the + * NOTIFY request. If the value is NULL, default + * status text will be used. + * @param p_tdata Pointer to receive the request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_xfer_notify( pjsip_evsub *sub, - pjsip_evsub_state state, - int xfer_st_code, - const pj_str_t *xfer_st_text, - pjsip_tx_data **p_tdata); + pjsip_evsub_state state, + int xfer_st_code, + const pj_str_t *xfer_st_text, + pjsip_tx_data **p_tdata); /** @@ -172,13 +171,13 @@ PJ_DECL(pj_status_t) pjsip_xfer_notify( pjsip_evsub *sub, * This will also re-send the last "message/sipfrag" body that was sent * in the previous NOTIFY. * - * @param sub Server subscription object. - * @param p_tdata Pointer to receive request. + * @param sub Server subscription object. + * @param p_tdata Pointer to receive request. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_xfer_current_notify( pjsip_evsub *sub, - pjsip_tx_data **p_tdata ); + pjsip_tx_data **p_tdata ); @@ -189,13 +188,13 @@ PJ_DECL(pj_status_t) pjsip_xfer_current_notify( pjsip_evsub *sub, * that creates/refresh subscription or NOTIFY request. * * - * @param sub The event subscription object. - * @param tdata Request message to be send. + * @param sub The event subscription object. + * @param tdata Request message to be send. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_xfer_send_request( pjsip_evsub *sub, - pjsip_tx_data *tdata); + pjsip_tx_data *tdata); PJ_END_DECL @@ -204,5 +203,5 @@ PJ_END_DECL * @} */ -#endif /* __PJSIP_XFER_H__ */ +#endif /* __PJSIP_XFER_H__ */ diff --git a/pjsip/include/pjsip.h b/pjsip/include/pjsip.h index 0074d03a3d..f29bf4a9f9 100644 --- a/pjsip/include/pjsip.h +++ b/pjsip/include/pjsip.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -58,5 +57,5 @@ #include -#endif /* __PJSIP_H__ */ +#endif /* __PJSIP_H__ */ diff --git a/pjsip/include/pjsip/print_util.h b/pjsip/include/pjsip/print_util.h index bd5d6f6b96..8dd36e0591 100644 --- a/pjsip/include/pjsip/print_util.h +++ b/pjsip/include/pjsip/print_util.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,115 +20,115 @@ #define __PJSIP_PRINT_H__ #define copy_advance_char_check(buf,chr) \ - do { \ - if (1 >= (endbuf-buf)) return -1; \ - *buf++ = chr; \ - } while (0) + do { \ + if (1 >= (endbuf-buf)) return -1; \ + *buf++ = chr; \ + } while (0) #define copy_advance_check(buf,str) \ - do { \ - if ((str).slen >= (endbuf-buf)) return -1; \ - if ((str).slen) { \ - pj_memcpy(buf, (str).ptr, (str).slen); \ - buf += (str).slen; \ - } \ - } while (0) + do { \ + if ((str).slen >= (endbuf-buf)) return -1; \ + if ((str).slen) { \ + pj_memcpy(buf, (str).ptr, (str).slen); \ + buf += (str).slen; \ + } \ + } while (0) #define copy_advance_pair_check(buf,str1,len1,str2) \ - do { \ - if (str2.slen) { \ - printed = len1+(int)str2.slen; \ - if (printed >= (endbuf-buf)) return -1; \ - pj_memcpy(buf,str1,len1); \ - pj_memcpy(buf+len1, str2.ptr, str2.slen); \ - buf += printed; \ - } \ - } while (0) + do { \ + if (str2.slen) { \ + printed = len1+(int)str2.slen; \ + if (printed >= (endbuf-buf)) return -1; \ + pj_memcpy(buf,str1,len1); \ + pj_memcpy(buf+len1, str2.ptr, str2.slen); \ + buf += printed; \ + } \ + } while (0) #define copy_advance_pair_quote_check(buf,str1,len1,str2,quotebegin,quoteend) \ - do { \ - if (str2.slen) { \ - printed = len1+str2.slen+2; \ - if (printed >= (endbuf-buf)) return -1; \ - pj_memcpy(buf,str1,len1); \ - *(buf+len1)=quotebegin; \ - pj_memcpy(buf+len1+1, str2.ptr, str2.slen); \ - *(buf+printed-1) = quoteend; \ - buf += printed; \ - } \ - } while (0) + do { \ + if (str2.slen) { \ + printed = len1+str2.slen+2; \ + if (printed >= (endbuf-buf)) return -1; \ + pj_memcpy(buf,str1,len1); \ + *(buf+len1)=quotebegin; \ + pj_memcpy(buf+len1+1, str2.ptr, str2.slen); \ + *(buf+printed-1) = quoteend; \ + buf += printed; \ + } \ + } while (0) #define copy_advance_pair_quote(buf,str1,len1,str2,quotebegin,quoteend) \ - do { \ - printed = len1+(int)str2.slen+2; \ - if (printed >= (endbuf-buf)) return -1; \ - pj_memcpy(buf,str1,len1); \ - *(buf+len1)=quotebegin; \ - pj_memcpy(buf+len1+1, str2.ptr, str2.slen); \ - *(buf+printed-1) = quoteend; \ - buf += printed; \ - } while (0) - -#define copy_advance_pair_escape(buf,str1,len1,str2,unres) \ - do { \ - if (str2.slen) { \ - if (len1+str2.slen >= (endbuf-buf)) return -1; \ - pj_memcpy(buf,str1,len1); \ - printed=(int)pj_strncpy2_escape(buf+len1,&str2,(endbuf-buf-len1), \ - &unres);\ - if (printed < 0) return -1; \ - buf += (printed+len1); \ - } \ - } while (0) + do { \ + printed = len1+(int)str2.slen+2; \ + if (printed >= (endbuf-buf)) return -1; \ + pj_memcpy(buf,str1,len1); \ + *(buf+len1)=quotebegin; \ + pj_memcpy(buf+len1+1, str2.ptr, str2.slen); \ + *(buf+printed-1) = quoteend; \ + buf += printed; \ + } while (0) + +#define copy_advance_pair_escape(buf,str1,len1,str2,unres) \ + do { \ + if (str2.slen) { \ + if (len1+str2.slen >= (endbuf-buf)) return -1; \ + pj_memcpy(buf,str1,len1); \ + printed=(int)pj_strncpy2_escape(buf+len1,&str2,(endbuf-buf-len1), \ + &unres);\ + if (printed < 0) return -1; \ + buf += (printed+len1); \ + } \ + } while (0) #define copy_advance_no_check(buf,str) \ - do { \ - pj_memcpy(buf, (str).ptr, (str).slen); \ - buf += (str).slen; \ - } while (0) + do { \ + pj_memcpy(buf, (str).ptr, (str).slen); \ + buf += (str).slen; \ + } while (0) #define copy_advance_escape(buf,str,unres) \ - do { \ - printed = \ - (int)pj_strncpy2_escape(buf, &(str), (endbuf-buf), &(unres)); \ - if (printed < 0) return -1; \ - buf += printed; \ - } while (0) + do { \ + printed = \ + (int)pj_strncpy2_escape(buf, &(str), (endbuf-buf), &(unres)); \ + if (printed < 0) return -1; \ + buf += printed; \ + } while (0) #define copy_advance_pair_no_check(buf,str1,len1,str2) \ - if (str2.slen) { \ - pj_memcpy(buf,str1,len1); \ - pj_memcpy(buf+len1, str2.ptr, str2.slen); \ - buf += len1+str2.slen; \ - } + if (str2.slen) { \ + pj_memcpy(buf,str1,len1); \ + pj_memcpy(buf+len1, str2.ptr, str2.slen); \ + buf += len1+str2.slen; \ + } -#define copy_advance copy_advance_check -#define copy_advance_pair copy_advance_pair_check +#define copy_advance copy_advance_check +#define copy_advance_pair copy_advance_pair_check /* * Append str1 and quoted str2 and copy to buf. * No string is copied if str2 is empty. */ #define copy_advance_pair_quote_cond(buf,str1,len1,str2,quotebegin,quoteend) \ - do { \ - if (str2.slen && *str2.ptr!=quotebegin) \ - copy_advance_pair_quote(buf,str1,len1,str2,quotebegin,quoteend); \ - else \ - copy_advance_pair(buf,str1,len1,str2); \ - } while (0) + do { \ + if (str2.slen && *str2.ptr!=quotebegin) \ + copy_advance_pair_quote(buf,str1,len1,str2,quotebegin,quoteend); \ + else \ + copy_advance_pair(buf,str1,len1,str2); \ + } while (0) /* * Append str1 and quoted str2 and copy to buf. * In case str2 is empty, str1 will be appended with empty quote. */ #define copy_advance_pair_quote_cond_always(buf,str1,len1,str2,quotebegin, \ - quoteend)\ - do { \ + quoteend)\ + do { \ if (!str2.slen) \ copy_advance_pair_quote(buf,str1,len1,str2,quotebegin,quoteend); \ else \ - copy_advance_pair_quote_cond(buf,str1,len1,str2,quotebegin,quoteend);\ + copy_advance_pair_quote_cond(buf,str1,len1,str2,quotebegin,quoteend);\ } while (0) /* @@ -140,9 +139,9 @@ typedef int (*pjsip_hdr_print_fptr)(void *hdr, char *buf, pj_size_t len); typedef struct pjsip_hdr_name_info_t { - char *name; - unsigned name_len; - char *sname; + char *name; + unsigned name_len; + char *sname; } pjsip_hdr_name_info_t; extern const pjsip_hdr_name_info_t pjsip_hdr_names[]; @@ -154,14 +153,14 @@ PJ_INLINE(void) init_hdr(void *hptr, pjsip_hdr_e htype, void *vptr) hdr->name.ptr = pjsip_hdr_names[htype].name; hdr->name.slen = pjsip_hdr_names[htype].name_len; if (pjsip_hdr_names[htype].sname) { - hdr->sname.ptr = pjsip_hdr_names[htype].sname; - hdr->sname.slen = 1; + hdr->sname.ptr = pjsip_hdr_names[htype].sname; + hdr->sname.slen = 1; } else { - hdr->sname = hdr->name; + hdr->sname = hdr->name; } hdr->vptr = (pjsip_hdr_vptr*) vptr; pj_list_init(hdr); } -#endif /* __PJSIP_PRINT_H__ */ +#endif /* __PJSIP_PRINT_H__ */ diff --git a/pjsip/include/pjsip/sip_auth.h b/pjsip/include/pjsip/sip_auth.h index a880232df3..fa55830fd7 100644 --- a/pjsip/include/pjsip/sip_auth.h +++ b/pjsip/include/pjsip/sip_auth.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -44,29 +43,29 @@ PJ_BEGIN_DECL */ /** Length of digest MD5 string. */ -#define PJSIP_MD5STRLEN 32 +#define PJSIP_MD5STRLEN 32 /** Length of digest SHA256 string. */ -#define PJSIP_SHA256STRLEN 64 +#define PJSIP_SHA256STRLEN 64 /** Type of data in the credential information in #pjsip_cred_info. */ typedef enum pjsip_cred_data_type { - PJSIP_CRED_DATA_PLAIN_PASSWD=0, /**< Plain text password. */ - PJSIP_CRED_DATA_DIGEST =1, /**< Hashed digest. */ + PJSIP_CRED_DATA_PLAIN_PASSWD=0, /**< Plain text password. */ + PJSIP_CRED_DATA_DIGEST =1, /**< Hashed digest. */ - PJSIP_CRED_DATA_EXT_AKA =16 /**< Extended AKA info is available */ + PJSIP_CRED_DATA_EXT_AKA =16 /**< Extended AKA info is available */ } pjsip_cred_data_type; /** Authentication's quality of protection (qop) type. */ typedef enum pjsip_auth_qop_type { - PJSIP_AUTH_QOP_NONE, /**< No quality of protection. */ - PJSIP_AUTH_QOP_AUTH, /**< Authentication. */ - PJSIP_AUTH_QOP_AUTH_INT, /**< Authentication with integrity protection. */ - PJSIP_AUTH_QOP_UNKNOWN /**< Unknown protection. */ + PJSIP_AUTH_QOP_NONE, /**< No quality of protection. */ + PJSIP_AUTH_QOP_AUTH, /**< Authentication. */ + PJSIP_AUTH_QOP_AUTH_INT, /**< Authentication with integrity protection. */ + PJSIP_AUTH_QOP_UNKNOWN /**< Unknown protection. */ } pjsip_auth_qop_type; @@ -79,25 +78,25 @@ typedef enum pjsip_auth_qop_type * Application normally should just need to calculate the response digest * of the authentication response. * - * @param pool Pool to allocate memory from if application needs to. - * @param chal The authentication challenge sent by server in 401 - * or 401 response, in either Proxy-Authenticate or - * WWW-Authenticate header. - * @param cred The credential that has been selected by the framework - * to authenticate against the challenge. - * @param auth The authentication response which application needs to - * calculate the response digest. + * @param pool Pool to allocate memory from if application needs to. + * @param chal The authentication challenge sent by server in 401 + * or 401 response, in either Proxy-Authenticate or + * WWW-Authenticate header. + * @param cred The credential that has been selected by the framework + * to authenticate against the challenge. + * @param auth The authentication response which application needs to + * calculate the response digest. * - * @return Application may return non-PJ_SUCCESS to abort the - * authentication process. When this happens, the - * framework will return failure to the original function - * that requested authentication. + * @return Application may return non-PJ_SUCCESS to abort the + * authentication process. When this happens, the + * framework will return failure to the original function + * that requested authentication. */ typedef pj_status_t (*pjsip_cred_cb)(pj_pool_t *pool, - const pjsip_digest_challenge *chal, - const pjsip_cred_info *cred, - const pj_str_t *method, - pjsip_digest_credential *auth); + const pjsip_digest_challenge *chal, + const pjsip_cred_info *cred, + const pj_str_t *method, + pjsip_digest_credential *auth); /** @@ -111,28 +110,28 @@ typedef pj_status_t (*pjsip_cred_cb)(pj_pool_t *pool, */ struct pjsip_cred_info { - pj_str_t realm; /**< Realm. Use "*" to make a credential that - can be used to authenticate against any - challenges. */ - pj_str_t scheme; /**< Scheme (e.g. "digest"). */ - pj_str_t username; /**< User name. */ - int data_type; /**< Type of data (0 for plaintext passwd). */ - pj_str_t data; /**< The data, which can be a plaintext - password or a hashed digest. */ + pj_str_t realm; /**< Realm. Use "*" to make a credential that + can be used to authenticate against any + challenges. */ + pj_str_t scheme; /**< Scheme (e.g. "digest"). */ + pj_str_t username; /**< User name. */ + int data_type; /**< Type of data (0 for plaintext passwd). */ + pj_str_t data; /**< The data, which can be a plaintext + password or a hashed digest. */ /** Extended data */ union { - /** Digest AKA credential information. Note that when AKA credential - * is being used, the \a data field of this #pjsip_cred_info is - * not used, but it still must be initialized to an empty string. - * Please see \ref PJSIP_AUTH_AKA_API for more information. - */ - struct { - pj_str_t k; /**< Permanent subscriber key. */ - pj_str_t op; /**< Operator variant key. */ - pj_str_t amf; /**< Authentication Management Field */ - pjsip_cred_cb cb; /**< Callback to create AKA digest. */ - } aka; + /** Digest AKA credential information. Note that when AKA credential + * is being used, the \a data field of this #pjsip_cred_info is + * not used, but it still must be initialized to an empty string. + * Please see \ref PJSIP_AUTH_AKA_API for more information. + */ + struct { + pj_str_t k; /**< Permanent subscriber key. */ + pj_str_t op; /**< Operator variant key. */ + pj_str_t amf; /**< Authentication Management Field */ + pjsip_cred_cb cb; /**< Callback to create AKA digest. */ + } aka; } ext; }; @@ -148,8 +147,8 @@ typedef struct pjsip_cached_auth_hdr /** Standard list member */ PJ_DECL_LIST_MEMBER(struct pjsip_cached_auth_hdr); - pjsip_method method; /**< To quickly see the method. */ - pjsip_authorization_hdr *hdr; /**< The cached header. */ + pjsip_method method; /**< To quickly see the method. */ + pjsip_authorization_hdr *hdr; /**< The cached header. */ } pjsip_cached_auth_hdr; @@ -169,19 +168,19 @@ typedef struct pjsip_cached_auth /** Standard list member */ PJ_DECL_LIST_MEMBER(struct pjsip_cached_auth); - pj_pool_t *pool; /**< Pool for cached auth */ - pj_str_t realm; /**< Realm. */ - pj_bool_t is_proxy; /**< Server type (401/407) */ - pjsip_auth_qop_type qop_value; /**< qop required by server. */ - unsigned stale_cnt; /**< Number of stale retry. */ + pj_pool_t *pool; /**< Pool for cached auth */ + pj_str_t realm; /**< Realm. */ + pj_bool_t is_proxy; /**< Server type (401/407) */ + pjsip_auth_qop_type qop_value; /**< qop required by server. */ + unsigned stale_cnt; /**< Number of stale retry. */ #if PJSIP_AUTH_QOP_SUPPORT - pj_uint32_t nc; /**< Nonce count. */ - pj_str_t cnonce; /**< Cnonce value. */ + pj_uint32_t nc; /**< Nonce count. */ + pj_str_t cnonce; /**< Cnonce value. */ #endif - pjsip_www_authenticate_hdr *last_chal; /**< Last challenge seen. */ + pjsip_www_authenticate_hdr *last_chal; /**< Last challenge seen. */ #if PJSIP_AUTH_HEADER_CACHING - pjsip_cached_auth_hdr cached_hdr;/**< List of cached header for - each method. */ + pjsip_cached_auth_hdr cached_hdr;/**< List of cached header for + each method. */ #endif } pjsip_cached_auth; @@ -198,13 +197,13 @@ typedef struct pjsip_auth_clt_pref * send an empty Authorization header in each initial request. * Default is no. */ - pj_bool_t initial_auth; + pj_bool_t initial_auth; /** * Specify the algorithm to use when empty Authorization header * is to be sent for each initial request (see above) */ - pj_str_t algorithm; + pj_str_t algorithm; } pjsip_auth_clt_pref; @@ -212,13 +211,13 @@ typedef struct pjsip_auth_clt_pref /** * Duplicate a client authentication preference setting. * - * @param pool The memory pool. - * @param dst Destination client authentication preference. - * @param src Source client authentication preference. + * @param pool The memory pool. + * @param dst Destination client authentication preference. + * @param src Source client authentication preference. */ PJ_DECL(void) pjsip_auth_clt_pref_dup(pj_pool_t *pool, - pjsip_auth_clt_pref *dst, - const pjsip_auth_clt_pref *src); + pjsip_auth_clt_pref *dst, + const pjsip_auth_clt_pref *src); /** @@ -228,12 +227,12 @@ PJ_DECL(void) pjsip_auth_clt_pref_dup(pj_pool_t *pool, */ typedef struct pjsip_auth_clt_sess { - pj_pool_t *pool; /**< Pool to use. */ - pjsip_endpoint *endpt; /**< Endpoint where this belongs. */ - pjsip_auth_clt_pref pref; /**< Preference/options. */ - unsigned cred_cnt; /**< Number of credentials. */ - pjsip_cred_info *cred_info; /**< Array of credential information*/ - pjsip_cached_auth cached_auth; /**< Cached authorization info. */ + pj_pool_t *pool; /**< Pool to use. */ + pjsip_endpoint *endpt; /**< Endpoint where this belongs. */ + pjsip_auth_clt_pref pref; /**< Preference/options. */ + unsigned cred_cnt; /**< Number of credentials. */ + pjsip_cred_info *cred_info; /**< Array of credential information*/ + pjsip_cached_auth cached_auth; /**< Cached authorization info. */ } pjsip_auth_clt_sess; @@ -241,43 +240,43 @@ typedef struct pjsip_auth_clt_sess /** * Duplicate a credential info. * - * @param pool The memory pool. - * @param dst Destination credential. - * @param src Source credential. + * @param pool The memory pool. + * @param dst Destination credential. + * @param src Source credential. */ PJ_DECL(void) pjsip_cred_info_dup(pj_pool_t *pool, - pjsip_cred_info *dst, - const pjsip_cred_info *src); + pjsip_cred_info *dst, + const pjsip_cred_info *src); /** * Compare two credential infos. * - * @param cred1 The credential info to compare. - * @param cred2 The credential info to compare. + * @param cred1 The credential info to compare. + * @param cred2 The credential info to compare. * - * @return 0 if both credentials are equal. + * @return 0 if both credentials are equal. */ PJ_DECL(int) pjsip_cred_info_cmp(const pjsip_cred_info *cred1, - const pjsip_cred_info *cred2); + const pjsip_cred_info *cred2); /** * Type of function to lookup credential for the specified name. * - * @param pool Pool to initialize the credential info. - * @param realm Realm to find the account. - * @param acc_name Account name to look for. - * @param cred_info The structure to put the credential when it's found. + * @param pool Pool to initialize the credential info. + * @param realm Realm to find the account. + * @param acc_name Account name to look for. + * @param cred_info The structure to put the credential when it's found. * - * @return The function MUST return PJ_SUCCESS when it found - * a correct credential for the specified account and - * realm. Otherwise it may return PJSIP_EAUTHACCNOTFOUND - * or PJSIP_EAUTHACCDISABLED. + * @return The function MUST return PJ_SUCCESS when it found + * a correct credential for the specified account and + * realm. Otherwise it may return PJSIP_EAUTHACCNOTFOUND + * or PJSIP_EAUTHACCDISABLED. */ typedef pj_status_t pjsip_auth_lookup_cred( pj_pool_t *pool, - const pj_str_t *realm, - const pj_str_t *acc_name, - pjsip_cred_info *cred_info ); + const pj_str_t *realm, + const pj_str_t *acc_name, + pjsip_cred_info *cred_info ); /** @@ -285,9 +284,9 @@ typedef pj_status_t pjsip_auth_lookup_cred( pj_pool_t *pool, */ typedef struct pjsip_auth_lookup_cred_param { - pj_str_t realm; /**< Realm to find the account. */ - pj_str_t acc_name; /**< Account name to look for. */ - pjsip_rx_data *rdata; /**< Incoming request to be authenticated. */ + pj_str_t realm; /**< Realm to find the account. */ + pj_str_t acc_name; /**< Account name to look for. */ + pjsip_rx_data *rdata; /**< Incoming request to be authenticated. */ } pjsip_auth_lookup_cred_param; @@ -295,34 +294,34 @@ typedef struct pjsip_auth_lookup_cred_param /** * Type of function to lookup credential for the specified name. * - * @param pool Pool to initialize the credential info. - * @param param The input param for credential lookup. - * @param cred_info The structure to put the credential when it's found. + * @param pool Pool to initialize the credential info. + * @param param The input param for credential lookup. + * @param cred_info The structure to put the credential when it's found. * - * @return The function MUST return PJ_SUCCESS when it found - * a correct credential for the specified account and - * realm. Otherwise it may return PJSIP_EAUTHACCNOTFOUND - * or PJSIP_EAUTHACCDISABLED. + * @return The function MUST return PJ_SUCCESS when it found + * a correct credential for the specified account and + * realm. Otherwise it may return PJSIP_EAUTHACCNOTFOUND + * or PJSIP_EAUTHACCDISABLED. */ typedef pj_status_t pjsip_auth_lookup_cred2( - pj_pool_t *pool, - const pjsip_auth_lookup_cred_param *param, - pjsip_cred_info *cred_info ); + pj_pool_t *pool, + const pjsip_auth_lookup_cred_param *param, + pjsip_cred_info *cred_info ); /** Flag to specify that server is a proxy. */ -#define PJSIP_AUTH_SRV_IS_PROXY 1 +#define PJSIP_AUTH_SRV_IS_PROXY 1 /** * This structure describes server authentication information. */ typedef struct pjsip_auth_srv { - pj_str_t realm; /**< Realm to serve. */ - pj_bool_t is_proxy; /**< Will issue 407 instead of 401 */ - pjsip_auth_lookup_cred *lookup; /**< Lookup function. */ - pjsip_auth_lookup_cred2 *lookup2; /**< Lookup function with additional - info in its input param. */ + pj_str_t realm; /**< Realm to serve. */ + pj_bool_t is_proxy; /**< Will issue 407 instead of 401 */ + pjsip_auth_lookup_cred *lookup; /**< Lookup function. */ + pjsip_auth_lookup_cred2 *lookup2; /**< Lookup function with additional + info in its input param. */ } pjsip_auth_srv; @@ -331,25 +330,25 @@ typedef struct pjsip_auth_srv * session to use pool for its subsequent memory allocation. The argument * options should be set to zero for this PJSIP version. * - * @param sess The client authentication session. - * @param endpt Endpoint where this session belongs. - * @param pool Pool to use. - * @param options Must be zero. + * @param sess The client authentication session. + * @param endpt Endpoint where this session belongs. + * @param pool Pool to use. + * @param options Must be zero. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_auth_clt_init( pjsip_auth_clt_sess *sess, - pjsip_endpoint *endpt, - pj_pool_t *pool, - unsigned options); + pjsip_endpoint *endpt, + pj_pool_t *pool, + unsigned options); /** * Deinitialize client authentication session data structure. * - * @param sess The client authentication session. + * @param sess The client authentication session. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_auth_clt_deinit( pjsip_auth_clt_sess *sess); @@ -357,53 +356,53 @@ PJ_DECL(pj_status_t) pjsip_auth_clt_deinit( pjsip_auth_clt_sess *sess); /** * Clone client initialization session. * - * @param pool Pool to use. - * @param sess Structure to put the duplicated session. - * @param rhs The client session to be cloned. + * @param pool Pool to use. + * @param sess Structure to put the duplicated session. + * @param rhs The client session to be cloned. * - * @return PJ_SUCCESS on success; + * @return PJ_SUCCESS on success; */ PJ_DECL(pj_status_t) pjsip_auth_clt_clone( pj_pool_t *pool, - pjsip_auth_clt_sess *sess, - const pjsip_auth_clt_sess *rhs); + pjsip_auth_clt_sess *sess, + const pjsip_auth_clt_sess *rhs); /** * Set the credentials to be used during the session. This will duplicate * the specified credentials using client authentication's pool. * - * @param sess The client authentication session. - * @param cred_cnt Number of credentials. - * @param c Array of credentials. + * @param sess The client authentication session. + * @param cred_cnt Number of credentials. + * @param c Array of credentials. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_auth_clt_set_credentials( pjsip_auth_clt_sess *sess, - int cred_cnt, - const pjsip_cred_info *c); + int cred_cnt, + const pjsip_cred_info *c); /** * Set the preference for the client authentication session. * - * @param sess The client authentication session. - * @param p Preference. + * @param sess The client authentication session. + * @param p Preference. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_auth_clt_set_prefs(pjsip_auth_clt_sess *sess, - const pjsip_auth_clt_pref *p); + const pjsip_auth_clt_pref *p); /** * Get the preference for the client authentication session. * - * @param sess The client authentication session. - * @param p Pointer to receive the preference. + * @param sess The client authentication session. + * @param p Pointer to receive the preference. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_auth_clt_get_prefs(pjsip_auth_clt_sess *sess, - pjsip_auth_clt_pref *p); + pjsip_auth_clt_pref *p); /** * Initialize new request message with authorization headers. @@ -421,13 +420,13 @@ PJ_DECL(pj_status_t) pjsip_auth_clt_get_prefs(pjsip_auth_clt_sess *sess, * are not set, this function will do nothing. The stack then will only send * Authorization/Proxy-Authorization to respond 401/407 response. * - * @param sess The client authentication session. - * @param tdata The request message to be initialized. + * @param sess The client authentication session. + * @param tdata The request message to be initialized. * - * @return PJ_SUCCESS if successfull. + * @return PJ_SUCCESS if successfull. */ PJ_DECL(pj_status_t) pjsip_auth_clt_init_req( pjsip_auth_clt_sess *sess, - pjsip_tx_data *tdata ); + pjsip_tx_data *tdata ); /** @@ -439,44 +438,44 @@ PJ_DECL(pj_status_t) pjsip_auth_clt_init_req( pjsip_auth_clt_sess *sess, * Note that upon return the reference counter of the new transmit data * will be set to 1. * - * @param sess The client authentication session. - * @param rdata The response message containing 401/407 status. - * @param old_request The original request message, which will be re- - * created with authorization info. - * @param new_request Pointer to receive new request message which - * will contain all required authorization headers. + * @param sess The client authentication session. + * @param rdata The response message containing 401/407 status. + * @param old_request The original request message, which will be re- + * created with authorization info. + * @param new_request Pointer to receive new request message which + * will contain all required authorization headers. * - * @return PJ_SUCCESS if new request can be successfully - * created to respond all the authentication - * challenges. + * @return PJ_SUCCESS if new request can be successfully + * created to respond all the authentication + * challenges. */ -PJ_DECL(pj_status_t) pjsip_auth_clt_reinit_req( pjsip_auth_clt_sess *sess, - const pjsip_rx_data *rdata, - pjsip_tx_data *old_request, - pjsip_tx_data **new_request ); +PJ_DECL(pj_status_t) pjsip_auth_clt_reinit_req( pjsip_auth_clt_sess *sess, + const pjsip_rx_data *rdata, + pjsip_tx_data *old_request, + pjsip_tx_data **new_request ); /** * Initialize server authorization session data structure to serve the * specified realm and to use lookup_func function to look for the credential * info. * - * @param pool Pool used to initialize the authentication server. - * @param auth_srv The authentication server structure. - * @param realm Realm to be served by the server. - * @param lookup Account lookup function. - * @param options Options, bitmask of: - * - PJSIP_AUTH_SRV_IS_PROXY: to specify that the server - * will authorize clients as a proxy server (instead of - * as UAS), which means that Proxy-Authenticate will - * be used instead of WWW-Authenticate. + * @param pool Pool used to initialize the authentication server. + * @param auth_srv The authentication server structure. + * @param realm Realm to be served by the server. + * @param lookup Account lookup function. + * @param options Options, bitmask of: + * - PJSIP_AUTH_SRV_IS_PROXY: to specify that the server + * will authorize clients as a proxy server (instead of + * as UAS), which means that Proxy-Authenticate will + * be used instead of WWW-Authenticate. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_auth_srv_init( pj_pool_t *pool, - pjsip_auth_srv *auth_srv, - const pj_str_t *realm, - pjsip_auth_lookup_cred *lookup, - unsigned options ); + pjsip_auth_srv *auth_srv, + const pj_str_t *realm, + pjsip_auth_lookup_cred *lookup, + unsigned options ); /** @@ -488,12 +487,12 @@ typedef struct pjsip_auth_srv_init_param /** * Realm to be served by the server. */ - const pj_str_t *realm; + const pj_str_t *realm; /** * Account lookup function. */ - pjsip_auth_lookup_cred2 *lookup2; + pjsip_auth_lookup_cred2 *lookup2; /** * Options, bitmask of: @@ -501,7 +500,7 @@ typedef struct pjsip_auth_srv_init_param * clients as a proxy server (instead of as UAS), which means that * Proxy-Authenticate will be used instead of WWW-Authenticate. */ - unsigned options; + unsigned options; } pjsip_auth_srv_init_param; @@ -511,39 +510,39 @@ typedef struct pjsip_auth_srv_init_param * specified realm and to use lookup_func function to look for the credential * info. * - * @param pool Pool used to initialize the authentication server. - * @param auth_srv The authentication server structure. - * @param param The initialization param. + * @param pool Pool used to initialize the authentication server. + * @param auth_srv The authentication server structure. + * @param param The initialization param. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_auth_srv_init2( - pj_pool_t *pool, - pjsip_auth_srv *auth_srv, - const pjsip_auth_srv_init_param *param); + pj_pool_t *pool, + pjsip_auth_srv *auth_srv, + const pjsip_auth_srv_init_param *param); /** * Request the authorization server framework to verify the authorization * information in the specified request in rdata. * - * @param auth_srv The server authentication structure. - * @param rdata Incoming request to be authenticated. - * @param status_code When not null, it will be filled with suitable - * status code to be sent to the client. - * - * @return PJ_SUCCESS if request is successfully authenticated. - * Otherwise the function may return one of the - * following error codes: - * - PJSIP_EAUTHNOAUTH - * - PJSIP_EINVALIDAUTHSCHEME - * - PJSIP_EAUTHACCNOTFOUND - * - PJSIP_EAUTHACCDISABLED - * - PJSIP_EAUTHINVALIDREALM - * - PJSIP_EAUTHINVALIDDIGEST + * @param auth_srv The server authentication structure. + * @param rdata Incoming request to be authenticated. + * @param status_code When not null, it will be filled with suitable + * status code to be sent to the client. + * + * @return PJ_SUCCESS if request is successfully authenticated. + * Otherwise the function may return one of the + * following error codes: + * - PJSIP_EAUTHNOAUTH + * - PJSIP_EINVALIDAUTHSCHEME + * - PJSIP_EAUTHACCNOTFOUND + * - PJSIP_EAUTHACCDISABLED + * - PJSIP_EAUTHINVALIDREALM + * - PJSIP_EAUTHINVALIDDIGEST */ PJ_DECL(pj_status_t) pjsip_auth_srv_verify( pjsip_auth_srv *auth_srv, - pjsip_rx_data *rdata, - int *status_code ); + pjsip_rx_data *rdata, + int *status_code ); /** @@ -552,78 +551,78 @@ PJ_DECL(pj_status_t) pjsip_auth_srv_verify( pjsip_auth_srv *auth_srv, * or can leave the value to NULL to make the function fills them in with * random characters. * - * @param auth_srv The server authentication structure. - * @param qop Optional qop value. - * @param nonce Optional nonce value. - * @param opaque Optional opaque value. - * @param stale Stale indication. - * @param tdata The outgoing response message. The response must have - * 401 or 407 response code. + * @param auth_srv The server authentication structure. + * @param qop Optional qop value. + * @param nonce Optional nonce value. + * @param opaque Optional opaque value. + * @param stale Stale indication. + * @param tdata The outgoing response message. The response must have + * 401 or 407 response code. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_auth_srv_challenge( pjsip_auth_srv *auth_srv, - const pj_str_t *qop, - const pj_str_t *nonce, - const pj_str_t *opaque, - pj_bool_t stale, - pjsip_tx_data *tdata); + const pj_str_t *qop, + const pj_str_t *nonce, + const pj_str_t *opaque, + pj_bool_t stale, + pjsip_tx_data *tdata); /** * Helper function to create MD5 digest out of the specified * parameters. * - * @param result String to store the response digest. This string - * must have been preallocated by caller with the - * buffer at least PJSIP_MD5STRLEN (32 bytes) in size. - * @param nonce Optional nonce. - * @param nc Nonce count. - * @param cnonce Optional cnonce. - * @param qop Optional qop. - * @param uri URI. - * @param realm Realm. - * @param cred_info Credential info. - * @param method SIP method. + * @param result String to store the response digest. This string + * must have been preallocated by caller with the + * buffer at least PJSIP_MD5STRLEN (32 bytes) in size. + * @param nonce Optional nonce. + * @param nc Nonce count. + * @param cnonce Optional cnonce. + * @param qop Optional qop. + * @param uri URI. + * @param realm Realm. + * @param cred_info Credential info. + * @param method SIP method. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_auth_create_digest(pj_str_t *result, - const pj_str_t *nonce, - const pj_str_t *nc, - const pj_str_t *cnonce, - const pj_str_t *qop, - const pj_str_t *uri, - const pj_str_t *realm, - const pjsip_cred_info *cred_info, - const pj_str_t *method); + const pj_str_t *nonce, + const pj_str_t *nc, + const pj_str_t *cnonce, + const pj_str_t *qop, + const pj_str_t *uri, + const pj_str_t *realm, + const pjsip_cred_info *cred_info, + const pj_str_t *method); /** * Helper function to create SHA-256 digest out of the specified * parameters. * - * @param result String to store the response digest. This string - * must have been preallocated by caller with the - * buffer at least PJSIP_SHA256STRLEN (64 bytes) in size. - * @param nonce Optional nonce. - * @param nc Nonce count. - * @param cnonce Optional cnonce. - * @param qop Optional qop. - * @param uri URI. - * @param realm Realm. - * @param cred_info Credential info. - * @param method SIP method. + * @param result String to store the response digest. This string + * must have been preallocated by caller with the + * buffer at least PJSIP_SHA256STRLEN (64 bytes) in size. + * @param nonce Optional nonce. + * @param nc Nonce count. + * @param cnonce Optional cnonce. + * @param qop Optional qop. + * @param uri URI. + * @param realm Realm. + * @param cred_info Credential info. + * @param method SIP method. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DEF(pj_status_t) pjsip_auth_create_digestSHA256(pj_str_t* result, - const pj_str_t* nonce, - const pj_str_t* nc, - const pj_str_t* cnonce, - const pj_str_t* qop, - const pj_str_t* uri, - const pj_str_t* realm, - const pjsip_cred_info* cred_info, - const pj_str_t* method); + const pj_str_t* nonce, + const pj_str_t* nc, + const pj_str_t* cnonce, + const pj_str_t* qop, + const pj_str_t* uri, + const pj_str_t* realm, + const pjsip_cred_info* cred_info, + const pj_str_t* method); /** * @} @@ -634,5 +633,5 @@ PJ_DEF(pj_status_t) pjsip_auth_create_digestSHA256(pj_str_t* result, PJ_END_DECL -#endif /* __PJSIP_AUTH_SIP_AUTH_H__ */ +#endif /* __PJSIP_AUTH_SIP_AUTH_H__ */ diff --git a/pjsip/include/pjsip/sip_auth_aka.h b/pjsip/include/pjsip/sip_auth_aka.h index 291e2b07d3..41b77e7764 100644 --- a/pjsip/include/pjsip/sip_auth_aka.h +++ b/pjsip/include/pjsip/sip_auth_aka.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -112,57 +111,57 @@ PJ_BEGIN_DECL /** * Length of Authentication Key (AK) in bytes. */ -#define PJSIP_AKA_AKLEN 6 +#define PJSIP_AKA_AKLEN 6 /** * Length of Authentication Management Field (AMF) in bytes. */ -#define PJSIP_AKA_AMFLEN 2 +#define PJSIP_AKA_AMFLEN 2 /** * Length of AUTN in bytes. */ -#define PJSIP_AKA_AUTNLEN 16 +#define PJSIP_AKA_AUTNLEN 16 /** * Length of Confidentiality Key (CK) in bytes. */ -#define PJSIP_AKA_CKLEN 16 +#define PJSIP_AKA_CKLEN 16 /** * Length of Integrity Key (AK) in bytes. */ -#define PJSIP_AKA_IKLEN 16 +#define PJSIP_AKA_IKLEN 16 /** * Length of permanent/subscriber Key (K) in bytes. */ -#define PJSIP_AKA_KLEN 16 +#define PJSIP_AKA_KLEN 16 /** * Length of AKA authentication code in bytes. */ -#define PJSIP_AKA_MACLEN 8 +#define PJSIP_AKA_MACLEN 8 /** * Length of operator key in bytes. */ -#define PJSIP_AKA_OPLEN 16 +#define PJSIP_AKA_OPLEN 16 /** * Length of random challenge (RAND) in bytes. */ -#define PJSIP_AKA_RANDLEN 16 +#define PJSIP_AKA_RANDLEN 16 /** * Length of response digest in bytes. */ -#define PJSIP_AKA_RESLEN 8 +#define PJSIP_AKA_RESLEN 8 /** * Length of sequence number (SQN) in bytes. */ -#define PJSIP_AKA_SQNLEN 6 +#define PJSIP_AKA_SQNLEN 6 /** * This function creates MD5, AKAv1-MD5, or AKAv2-MD5 response for @@ -177,27 +176,27 @@ PJ_BEGIN_DECL * the credential, and fills up other AKA specific information in * the credential. * - * @param pool Pool to allocate memory. - * @param chal The authentication challenge sent by server in 401 - * or 401 response, as either Proxy-Authenticate or - * WWW-Authenticate header. - * @param cred The credential to be used. + * @param pool Pool to allocate memory. + * @param chal The authentication challenge sent by server in 401 + * or 401 response, as either Proxy-Authenticate or + * WWW-Authenticate header. + * @param cred The credential to be used. * @param method The request method. - * @param auth The digest credential where the digest response - * will be placed to. Upon calling this function, the - * nonce, nc, cnonce, qop, uri, and realm fields of - * this structure must have been set by caller. Upon - * return, the \a response field will be initialized - * by this function. + * @param auth The digest credential where the digest response + * will be placed to. Upon calling this function, the + * nonce, nc, cnonce, qop, uri, and realm fields of + * this structure must have been set by caller. Upon + * return, the \a response field will be initialized + * by this function. * - * @return PJ_SUCCESS if response has been created successfully. + * @return PJ_SUCCESS if response has been created successfully. */ PJ_DECL(pj_status_t) pjsip_auth_create_aka_response( - pj_pool_t *pool, - const pjsip_digest_challenge*chal, - const pjsip_cred_info *cred, - const pj_str_t *method, - pjsip_digest_credential *auth); + pj_pool_t *pool, + const pjsip_digest_challenge*chal, + const pjsip_cred_info *cred, + const pj_str_t *method, + pjsip_digest_credential *auth); /** @@ -209,5 +208,5 @@ PJ_DECL(pj_status_t) pjsip_auth_create_aka_response( PJ_END_DECL -#endif /* __PJSIP_AUTH_SIP_AUTH_AKA_H__ */ +#endif /* __PJSIP_AUTH_SIP_AUTH_AKA_H__ */ diff --git a/pjsip/include/pjsip/sip_auth_msg.h b/pjsip/include/pjsip/sip_auth_msg.h index 01285e9730..6eb933f4ff 100644 --- a/pjsip/include/pjsip/sip_auth_msg.h +++ b/pjsip/include/pjsip/sip_auth_msg.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,8 +34,8 @@ PJ_BEGIN_DECL */ struct pjsip_common_credential { - pj_str_t realm; /**< Credential's realm. */ - pjsip_param other_param; /**< Other parameters. */ + pj_str_t realm; /**< Credential's realm. */ + pjsip_param other_param; /**< Other parameters. */ }; /** @@ -51,17 +50,17 @@ typedef struct pjsip_common_credential pjsip_common_credential; */ struct pjsip_digest_credential { - pj_str_t realm; /**< Realm of the credential */ - pjsip_param other_param; /**< Other parameters. */ - pj_str_t username; /**< Username parameter. */ - pj_str_t nonce; /**< Nonce parameter. */ - pj_str_t uri; /**< URI parameter. */ - pj_str_t response; /**< Response digest. */ - pj_str_t algorithm; /**< Algorithm. */ - pj_str_t cnonce; /**< Cnonce. */ - pj_str_t opaque; /**< Opaque value. */ - pj_str_t qop; /**< Quality of protection. */ - pj_str_t nc; /**< Nonce count. */ + pj_str_t realm; /**< Realm of the credential */ + pjsip_param other_param; /**< Other parameters. */ + pj_str_t username; /**< Username parameter. */ + pj_str_t nonce; /**< Nonce parameter. */ + pj_str_t uri; /**< URI parameter. */ + pj_str_t response; /**< Response digest. */ + pj_str_t algorithm; /**< Algorithm. */ + pj_str_t cnonce; /**< Cnonce. */ + pj_str_t opaque; /**< Opaque value. */ + pj_str_t qop; /**< Quality of protection. */ + pj_str_t nc; /**< Nonce count. */ }; /** @@ -75,12 +74,12 @@ typedef struct pjsip_digest_credential pjsip_digest_credential; */ struct pjsip_pgp_credential { - pj_str_t realm; /**< Realm. */ - pjsip_param other_param; /**< Other parameters. */ - pj_str_t version; /**< Version parameter. */ - pj_str_t signature; /**< Signature parameter. */ - pj_str_t signed_by; /**< Signed by parameter. */ - pj_str_t nonce; /**< Nonce parameter. */ + pj_str_t realm; /**< Realm. */ + pjsip_param other_param; /**< Other parameters. */ + pj_str_t version; /**< Version parameter. */ + pj_str_t signature; /**< Signature parameter. */ + pj_str_t signed_by; /**< Signed by parameter. */ + pj_str_t nonce; /**< Nonce parameter. */ }; /** @@ -120,10 +119,10 @@ struct pjsip_authorization_hdr /** Type of credentials, depending on the scheme. */ union { - pjsip_common_credential common; /**< Common fields. */ - pjsip_digest_credential digest; /**< Digest credentials. */ - pjsip_pgp_credential pgp; /**< PGP credentials. */ - pjsip_oauth_credential oauth; /**< OAuth credentials. */ + pjsip_common_credential common; /**< Common fields. */ + pjsip_digest_credential digest; /**< Digest credentials. */ + pjsip_pgp_credential pgp; /**< PGP credentials. */ + pjsip_oauth_credential oauth; /**< OAuth credentials. */ } credential; }; @@ -139,16 +138,16 @@ typedef struct pjsip_authorization_hdr pjsip_proxy_authorization_hdr; /** * Create SIP Authorization header. - * @param pool Pool where memory will be allocated from. - * @return SIP Authorization header. + * @param pool Pool where memory will be allocated from. + * @return SIP Authorization header. */ PJ_DECL(pjsip_authorization_hdr*) pjsip_authorization_hdr_create(pj_pool_t *pool); /** * Create SIP Proxy-Authorization header. - * @param pool Pool where memory will be allocated from. - * @return SIP Proxy-Authorization header. + * @param pool Pool where memory will be allocated from. + * @return SIP Proxy-Authorization header. */ PJ_DECL(pjsip_proxy_authorization_hdr*) pjsip_proxy_authorization_hdr_create(pj_pool_t *pool); @@ -160,8 +159,8 @@ pjsip_proxy_authorization_hdr_create(pj_pool_t *pool); */ struct pjsip_common_challenge { - pj_str_t realm; /**< Realm for the challenge. */ - pjsip_param other_param; /**< Other parameters. */ + pj_str_t realm; /**< Realm for the challenge. */ + pjsip_param other_param; /**< Other parameters. */ }; /** @@ -175,14 +174,14 @@ typedef struct pjsip_common_challenge pjsip_common_challenge; */ struct pjsip_digest_challenge { - pj_str_t realm; /**< Realm for the challenge. */ - pjsip_param other_param; /**< Other parameters. */ - pj_str_t domain; /**< Domain. */ - pj_str_t nonce; /**< Nonce challenge. */ - pj_str_t opaque; /**< Opaque value. */ - int stale; /**< Stale parameter. */ - pj_str_t algorithm; /**< Algorithm parameter. */ - pj_str_t qop; /**< Quality of protection. */ + pj_str_t realm; /**< Realm for the challenge. */ + pjsip_param other_param; /**< Other parameters. */ + pj_str_t domain; /**< Domain. */ + pj_str_t nonce; /**< Nonce challenge. */ + pj_str_t opaque; /**< Opaque value. */ + int stale; /**< Stale parameter. */ + pj_str_t algorithm; /**< Algorithm parameter. */ + pj_str_t qop; /**< Quality of protection. */ }; /** @@ -196,12 +195,12 @@ typedef struct pjsip_digest_challenge pjsip_digest_challenge; */ struct pjsip_pgp_challenge { - pj_str_t realm; /**< Realm for the challenge. */ - pjsip_param other_param; /**< Other parameters. */ - pj_str_t version; /**< PGP version. */ - pj_str_t micalgorithm; /**< micalgorithm parameter. */ - pj_str_t pubalgorithm; /**< pubalgorithm parameter. */ - pj_str_t nonce; /**< Nonce challenge. */ + pj_str_t realm; /**< Realm for the challenge. */ + pjsip_param other_param; /**< Other parameters. */ + pj_str_t version; /**< PGP version. */ + pj_str_t micalgorithm; /**< micalgorithm parameter. */ + pj_str_t pubalgorithm; /**< pubalgorithm parameter. */ + pj_str_t nonce; /**< Nonce challenge. */ }; /** @@ -219,16 +218,16 @@ struct pjsip_www_authenticate_hdr PJSIP_DECL_HDR_MEMBER(struct pjsip_www_authenticate_hdr); /** Authentication scheme */ - pj_str_t scheme; + pj_str_t scheme; /** This union contains structures that are only relevant depending on the value of the scheme being used. */ union { - pjsip_common_challenge common; /**< Common fields. */ - pjsip_digest_challenge digest; /**< Digest challenge. */ - pjsip_pgp_challenge pgp; /**< PGP challenge. */ + pjsip_common_challenge common; /**< Common fields. */ + pjsip_digest_challenge digest; /**< Digest challenge. */ + pjsip_pgp_challenge pgp; /**< PGP challenge. */ } challenge; }; @@ -246,8 +245,8 @@ typedef struct pjsip_www_authenticate_hdr pjsip_proxy_authenticate_hdr; /** * Create SIP WWW-Authenticate header. * - * @param pool Pool where memory will be allocated from. - * @return SIP WWW-Authenticate header. + * @param pool Pool where memory will be allocated from. + * @return SIP WWW-Authenticate header. */ PJ_DECL(pjsip_www_authenticate_hdr*) pjsip_www_authenticate_hdr_create(pj_pool_t *pool); @@ -255,8 +254,8 @@ pjsip_www_authenticate_hdr_create(pj_pool_t *pool); /** * Create SIP Proxy-Authenticate header. * - * @param pool Pool where memory will be allocated from. - * @return SIP Proxy-Authenticate header. + * @param pool Pool where memory will be allocated from. + * @return SIP Proxy-Authenticate header. */ PJ_DECL(pjsip_proxy_authenticate_hdr*) pjsip_proxy_authenticate_hdr_create(pj_pool_t *pool); @@ -267,4 +266,4 @@ pjsip_proxy_authenticate_hdr_create(pj_pool_t *pool); PJ_END_DECL -#endif /* __PJSIP_AUTH_SIP_AUTH_MSG_H__ */ +#endif /* __PJSIP_AUTH_SIP_AUTH_MSG_H__ */ diff --git a/pjsip/include/pjsip/sip_auth_parser.h b/pjsip/include/pjsip/sip_auth_parser.h index 7012a04293..f7faefbfb9 100644 --- a/pjsip/include/pjsip/sip_auth_parser.h +++ b/pjsip/include/pjsip/sip_auth_parser.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -48,28 +47,28 @@ PJ_DECL(void) pjsip_auth_deinit_parser(void); -extern const pj_str_t pjsip_USERNAME_STR, /**< "username" string const. */ - pjsip_REALM_STR, /**< "realm" string const. */ - pjsip_NONCE_STR, /**< "nonce" string const. */ - pjsip_URI_STR, /**< "uri" string const. */ - pjsip_RESPONSE_STR, /**< "response" string const. */ - pjsip_ALGORITHM_STR,/**< "algorithm" string const. */ - pjsip_DOMAIN_STR, /**< "domain" string const. */ - pjsip_STALE_STR, /**< "stale" string const. */ - pjsip_QOP_STR, /**< "qop" string const. */ - pjsip_CNONCE_STR, /**< "cnonce" string const. */ - pjsip_OPAQUE_STR, /**< "opaque" string const. */ - pjsip_NC_STR, /**< "nc" string const. */ - pjsip_TRUE_STR, /**< "true" string const. */ - pjsip_FALSE_STR, /**< "false" string const. */ - pjsip_DIGEST_STR, /**< "digest" string const. */ - pjsip_PGP_STR, /**< "pgp" string const. */ - pjsip_BEARER_STR, /**< "bearer" string const. */ - pjsip_MD5_STR, /**< "MD5" string const. */ - pjsip_SHA256_STR, /**< "SHA-256" string const. */ - pjsip_AUTH_STR; /**< "auth" string const. */ +extern const pj_str_t pjsip_USERNAME_STR, /**< "username" string const. */ + pjsip_REALM_STR, /**< "realm" string const. */ + pjsip_NONCE_STR, /**< "nonce" string const. */ + pjsip_URI_STR, /**< "uri" string const. */ + pjsip_RESPONSE_STR, /**< "response" string const. */ + pjsip_ALGORITHM_STR,/**< "algorithm" string const. */ + pjsip_DOMAIN_STR, /**< "domain" string const. */ + pjsip_STALE_STR, /**< "stale" string const. */ + pjsip_QOP_STR, /**< "qop" string const. */ + pjsip_CNONCE_STR, /**< "cnonce" string const. */ + pjsip_OPAQUE_STR, /**< "opaque" string const. */ + pjsip_NC_STR, /**< "nc" string const. */ + pjsip_TRUE_STR, /**< "true" string const. */ + pjsip_FALSE_STR, /**< "false" string const. */ + pjsip_DIGEST_STR, /**< "digest" string const. */ + pjsip_PGP_STR, /**< "pgp" string const. */ + pjsip_BEARER_STR, /**< "bearer" string const. */ + pjsip_MD5_STR, /**< "MD5" string const. */ + pjsip_SHA256_STR, /**< "SHA-256" string const. */ + pjsip_AUTH_STR; /**< "auth" string const. */ PJ_END_DECL -#endif /* __PJSIP_AUTH_SIP_AUTH_PARSER_H__ */ +#endif /* __PJSIP_AUTH_SIP_AUTH_PARSER_H__ */ diff --git a/pjsip/include/pjsip/sip_autoconf.h.in b/pjsip/include/pjsip/sip_autoconf.h.in index 38eda08d4d..8081ba94ea 100644 --- a/pjsip/include/pjsip/sip_autoconf.h.in +++ b/pjsip/include/pjsip/sip_autoconf.h.in @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,5 +34,5 @@ //#undef PJSIP_HAS_TLS_TRANSPORT //#endif -#endif /* __PJSIP_SIP_AUTOCONF_H__ */ +#endif /* __PJSIP_SIP_AUTOCONF_H__ */ diff --git a/pjsip/include/pjsip/sip_config.h b/pjsip/include/pjsip/sip_config.h index 697d2c569d..b03a19d69b 100644 --- a/pjsip/include/pjsip/sip_config.h +++ b/pjsip/include/pjsip/sip_config.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -70,105 +69,105 @@ typedef struct pjsip_cfg_t { /** Global settings. */ struct { - /** - * Specify port number should be allowed to appear in To and From - * header. Note that RFC 3261 disallow this, see Table 1 in section - * 19.1.1 of the RFC. - * - * Default is PJSIP_ALLOW_PORT_IN_FROMTO_HDR. - */ - pj_bool_t allow_port_in_fromto_hdr; - - /** - * Accept call replace in early state when invite is not initiated - * by the user agent. RFC 3891 Section 3 disallows this, however, - * for better interoperability reason, this might be ignored. - * - * Default is PJSIP_ACCEPT_REPLACE_IN_EARLY_STATE. - */ - pj_bool_t accept_replace_in_early_state; - - /** - * Allow hash character ('#') to appear in outgoing URIs. See - * https://github.com/pjsip/pjproject/issues/1569. - * - * Default is PJ_FALSE. - */ - pj_bool_t allow_tx_hash_in_uri; - - /** - * Disable rport in request. - * - * Default is PJ_FALSE. - */ - pj_bool_t disable_rport; - - /** - * Disable automatic switching from UDP to TCP if outgoing request - * is greater than 1300 bytes. - * - * Default is PJSIP_DONT_SWITCH_TO_TCP. - */ - pj_bool_t disable_tcp_switch; - - /** - * Disable automatic switching to TLS if target-URI does not use - * "sips" scheme nor TLS transport, even when request-URI uses - * "sips" scheme. - * - * Default is PJSIP_DONT_SWITCH_TO_TLS. - */ - pj_bool_t disable_tls_switch; - - /** - * Enable call media session to always be updated to the latest - * received early media SDP when receiving forked early media - * (multiple 183 responses with different To tag). - * - * Default is PJSIP_FOLLOW_EARLY_MEDIA_FORK. - */ - pj_bool_t follow_early_media_fork; - - /** - * Specify whether "alias" param should be added to the Via header - * in any outgoing request with connection oriented transport. - * - * Default is PJSIP_REQ_HAS_VIA_ALIAS. - */ - pj_bool_t req_has_via_alias; - - /** - * Resolve hostname when trying to get the network interface to be put - * in Via or Contact header. - * - * Default is PJSIP_RESOLVE_HOSTNAME_TO_GET_INTERFACE. - */ - pj_bool_t resolve_hostname_to_get_interface; - - /** - * Disable security check on incoming messages in a secure dialog. - * A secure dialog is created when the request that creates the dialog - * uses "sips" scheme in its request URI. Contact URI should use "sips" - * scheme and the top-most Record-Route URI, if any, should use either - * "sips" scheme or "transport=tls" param. See also - * https://github.com/pjsip/pjproject/issues/1735. - * - * Default is PJ_FALSE. - */ - pj_bool_t disable_secure_dlg_check; - - /** - * Encode SIP headers in their short forms to reduce size. By default, - * SIP headers in outgoing messages will be encoded in their full names. - * If this option is enabled, then SIP headers for outgoing messages - * will be encoded in their short forms, to reduce message size. - * Note that this does not affect the ability of PJSIP to parse incoming - * SIP messages, as the parser always supports parsing both the long - * and short version of the headers. - * - * Default is PJSIP_ENCODE_SHORT_HNAME - */ - pj_bool_t use_compact_form; + /** + * Specify port number should be allowed to appear in To and From + * header. Note that RFC 3261 disallow this, see Table 1 in section + * 19.1.1 of the RFC. + * + * Default is PJSIP_ALLOW_PORT_IN_FROMTO_HDR. + */ + pj_bool_t allow_port_in_fromto_hdr; + + /** + * Accept call replace in early state when invite is not initiated + * by the user agent. RFC 3891 Section 3 disallows this, however, + * for better interoperability reason, this might be ignored. + * + * Default is PJSIP_ACCEPT_REPLACE_IN_EARLY_STATE. + */ + pj_bool_t accept_replace_in_early_state; + + /** + * Allow hash character ('#') to appear in outgoing URIs. See + * https://github.com/pjsip/pjproject/issues/1569. + * + * Default is PJ_FALSE. + */ + pj_bool_t allow_tx_hash_in_uri; + + /** + * Disable rport in request. + * + * Default is PJ_FALSE. + */ + pj_bool_t disable_rport; + + /** + * Disable automatic switching from UDP to TCP if outgoing request + * is greater than 1300 bytes. + * + * Default is PJSIP_DONT_SWITCH_TO_TCP. + */ + pj_bool_t disable_tcp_switch; + + /** + * Disable automatic switching to TLS if target-URI does not use + * "sips" scheme nor TLS transport, even when request-URI uses + * "sips" scheme. + * + * Default is PJSIP_DONT_SWITCH_TO_TLS. + */ + pj_bool_t disable_tls_switch; + + /** + * Enable call media session to always be updated to the latest + * received early media SDP when receiving forked early media + * (multiple 183 responses with different To tag). + * + * Default is PJSIP_FOLLOW_EARLY_MEDIA_FORK. + */ + pj_bool_t follow_early_media_fork; + + /** + * Specify whether "alias" param should be added to the Via header + * in any outgoing request with connection oriented transport. + * + * Default is PJSIP_REQ_HAS_VIA_ALIAS. + */ + pj_bool_t req_has_via_alias; + + /** + * Resolve hostname when trying to get the network interface to be put + * in Via or Contact header. + * + * Default is PJSIP_RESOLVE_HOSTNAME_TO_GET_INTERFACE. + */ + pj_bool_t resolve_hostname_to_get_interface; + + /** + * Disable security check on incoming messages in a secure dialog. + * A secure dialog is created when the request that creates the dialog + * uses "sips" scheme in its request URI. Contact URI should use "sips" + * scheme and the top-most Record-Route URI, if any, should use either + * "sips" scheme or "transport=tls" param. See also + * https://github.com/pjsip/pjproject/issues/1735. + * + * Default is PJ_FALSE. + */ + pj_bool_t disable_secure_dlg_check; + + /** + * Encode SIP headers in their short forms to reduce size. By default, + * SIP headers in outgoing messages will be encoded in their full names. + * If this option is enabled, then SIP headers for outgoing messages + * will be encoded in their short forms, to reduce message size. + * Note that this does not affect the ability of PJSIP to parse incoming + * SIP messages, as the parser always supports parsing both the long + * and short version of the headers. + * + * Default is PJSIP_ENCODE_SHORT_HNAME + */ + pj_bool_t use_compact_form; /** * Accept multiple SDP answers on non-reliable 18X responses and the 2XX @@ -181,46 +180,46 @@ typedef struct pjsip_cfg_t */ pj_bool_t accept_multiple_sdp_answers; - /** - * Don't disconnect the INVITE session after an outgoing request - * gets timed out or responded with 408 (request timeout). - * - * Default is PJ_FALSE. - */ - pj_bool_t keep_inv_after_tsx_timeout; + /** + * Don't disconnect the INVITE session after an outgoing request + * gets timed out or responded with 408 (request timeout). + * + * Default is PJ_FALSE. + */ + pj_bool_t keep_inv_after_tsx_timeout; } endpt; /** Transaction layer settings. */ struct { - /** Maximum number of transactions. The value is initialized with - * PJSIP_MAX_TSX_COUNT - */ - unsigned max_count; + /** Maximum number of transactions. The value is initialized with + * PJSIP_MAX_TSX_COUNT + */ + unsigned max_count; - /* Timeout values: */ + /* Timeout values: */ - /** Transaction T1 timeout, in msec. Default value is PJSIP_T1_TIMEOUT - */ - unsigned t1; + /** Transaction T1 timeout, in msec. Default value is PJSIP_T1_TIMEOUT + */ + unsigned t1; - /** Transaction T2 timeout, in msec. Default value is PJSIP_T2_TIMEOUT - */ - unsigned t2; + /** Transaction T2 timeout, in msec. Default value is PJSIP_T2_TIMEOUT + */ + unsigned t2; - /** Transaction completed timer for non-INVITE, in msec. Default value - * is PJSIP_T4_TIMEOUT - */ - unsigned t4; + /** Transaction completed timer for non-INVITE, in msec. Default value + * is PJSIP_T4_TIMEOUT + */ + unsigned t4; - /** Transaction completed timer for INVITE, in msec. Default value is - * PJSIP_TD_TIMEOUT. - * - * This setting is also used for transaction timeout timer for both - * INVITE and non-INVITE. - */ - unsigned td; + /** Transaction completed timer for INVITE, in msec. Default value is + * PJSIP_TD_TIMEOUT. + * + * This setting is also used for transaction timeout timer for both + * INVITE and non-INVITE. + */ + unsigned td; } tsx; @@ -228,27 +227,27 @@ typedef struct pjsip_cfg_t /** Client registration settings. */ struct { - /** - * Specify whether client registration should check for its - * registered contact in Contact header of successful REGISTER - * response to determine whether registration has been successful. - * This setting may be disabled if non-compliant registrar is unable - * to return correct Contact header. - * - * Default is PJSIP_REGISTER_CLIENT_CHECK_CONTACT - */ - pj_bool_t check_contact; - - /** - * Specify whether client registration should add "x-uid" extension - * parameter in all Contact URIs that it registers to assist the - * matching of Contact URIs in the 200/OK REGISTER response, in - * case the registrar is unable to return exact Contact URI in the - * 200/OK response. - * - * Default is PJSIP_REGISTER_CLIENT_ADD_XUID_PARAM. - */ - pj_bool_t add_xuid_param; + /** + * Specify whether client registration should check for its + * registered contact in Contact header of successful REGISTER + * response to determine whether registration has been successful. + * This setting may be disabled if non-compliant registrar is unable + * to return correct Contact header. + * + * Default is PJSIP_REGISTER_CLIENT_CHECK_CONTACT + */ + pj_bool_t check_contact; + + /** + * Specify whether client registration should add "x-uid" extension + * parameter in all Contact URIs that it registers to assist the + * matching of Contact URIs in the 200/OK REGISTER response, in + * case the registrar is unable to return exact Contact URI in the + * 200/OK response. + * + * Default is PJSIP_REGISTER_CLIENT_ADD_XUID_PARAM. + */ + pj_bool_t add_xuid_param; } regc; @@ -288,7 +287,7 @@ typedef struct pjsip_cfg_t */ PJ_DECL(pjsip_cfg_t*) pjsip_cfg(void); -#else /* PJ_DLL */ +#else /* PJ_DLL */ extern pjsip_cfg_t pjsip_sip_cfg_var; @@ -303,7 +302,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) return &pjsip_sip_cfg_var; } -#endif /* PJ_DLL */ +#endif /* PJ_DLL */ /** @@ -314,7 +313,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default value is 1023 */ #ifndef PJSIP_MAX_TSX_COUNT -# define PJSIP_MAX_TSX_COUNT (1024-1) +# define PJSIP_MAX_TSX_COUNT (1024-1) #endif /** @@ -325,7 +324,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default value is 511. */ #ifndef PJSIP_MAX_DIALOG_COUNT -# define PJSIP_MAX_DIALOG_COUNT (512-1) +# define PJSIP_MAX_DIALOG_COUNT (512-1) #endif @@ -335,7 +334,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * See also PJSIP_TPMGR_HTABLE_SIZE. */ #ifndef PJSIP_MAX_TRANSPORTS -# define PJSIP_MAX_TRANSPORTS (PJ_IOQUEUE_MAX_HANDLES) +# define PJSIP_MAX_TRANSPORTS (PJ_IOQUEUE_MAX_HANDLES) #endif @@ -344,7 +343,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * See also PJSIP_MAX_TRANSPORTS */ #ifndef PJSIP_TPMGR_HTABLE_SIZE -# define PJSIP_TPMGR_HTABLE_SIZE 31 +# define PJSIP_TPMGR_HTABLE_SIZE 31 #endif @@ -352,7 +351,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Specify maximum URL size. */ #ifndef PJSIP_MAX_URL_SIZE -# define PJSIP_MAX_URL_SIZE 256 +# define PJSIP_MAX_URL_SIZE 256 #endif @@ -361,7 +360,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * This mainly affects the size of mod_data array in various components. */ #ifndef PJSIP_MAX_MODULE -# define PJSIP_MAX_MODULE 32 +# define PJSIP_MAX_MODULE 32 #endif @@ -370,7 +369,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * containing presence information can be quite large (>1500). */ #ifndef PJSIP_MAX_PKT_LEN -# define PJSIP_MAX_PKT_LEN 4000 +# define PJSIP_MAX_PKT_LEN 4000 #endif @@ -390,7 +389,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is 0 (no). */ #ifndef PJSIP_DONT_SWITCH_TO_TCP -# define PJSIP_DONT_SWITCH_TO_TCP 0 +# define PJSIP_DONT_SWITCH_TO_TCP 0 #endif @@ -408,7 +407,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is 0 (no). */ #ifndef PJSIP_DONT_SWITCH_TO_TLS -# define PJSIP_DONT_SWITCH_TO_TLS 0 +# define PJSIP_DONT_SWITCH_TO_TLS 0 #endif /** @@ -419,7 +418,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) */ #ifndef PJSIP_HANDLE_EVENTS_HAS_SLEEP_ON_ERR -# define PJSIP_HANDLE_EVENTS_HAS_SLEEP_ON_ERR 1 +# define PJSIP_HANDLE_EVENTS_HAS_SLEEP_ON_ERR 1 #endif /** @@ -433,7 +432,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is PJ_TRUE. */ #ifndef PJSIP_FOLLOW_EARLY_MEDIA_FORK -# define PJSIP_FOLLOW_EARLY_MEDIA_FORK PJ_TRUE +# define PJSIP_FOLLOW_EARLY_MEDIA_FORK PJ_TRUE #endif @@ -461,7 +460,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is PJ_TRUE. */ #ifndef PJSIP_REQ_HAS_VIA_ALIAS -# define PJSIP_REQ_HAS_VIA_ALIAS PJ_TRUE +# define PJSIP_REQ_HAS_VIA_ALIAS PJ_TRUE #endif /** @@ -488,7 +487,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is 0 (no). */ #ifndef PJSIP_ACCEPT_REPLACE_IN_EARLY_STATE -# define PJSIP_ACCEPT_REPLACE_IN_EARLY_STATE 0 +# define PJSIP_ACCEPT_REPLACE_IN_EARLY_STATE 0 #endif @@ -500,7 +499,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is 1300 bytes. */ #ifndef PJSIP_UDP_SIZE_THRESHOLD -# define PJSIP_UDP_SIZE_THRESHOLD 1300 +# define PJSIP_UDP_SIZE_THRESHOLD 1300 #endif @@ -519,7 +518,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is 0 (no) */ #ifndef PJSIP_ENCODE_SHORT_HNAME -# define PJSIP_ENCODE_SHORT_HNAME 0 +# define PJSIP_ENCODE_SHORT_HNAME 0 #endif @@ -545,7 +544,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is 1 (Yes) */ #ifndef PJSIP_INCLUDE_ALLOW_HDR_IN_DLG -# define PJSIP_INCLUDE_ALLOW_HDR_IN_DLG 1 +# define PJSIP_INCLUDE_ALLOW_HDR_IN_DLG 1 #endif @@ -555,7 +554,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * access module. */ #ifndef PJSIP_SAFE_MODULE -# define PJSIP_SAFE_MODULE 1 +# define PJSIP_SAFE_MODULE 1 #endif @@ -582,7 +581,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * https://github.com/pjsip/pjproject/issues/1412 */ #ifndef PJSIP_CHECK_VIA_SENT_BY -# define PJSIP_CHECK_VIA_SENT_BY 0 +# define PJSIP_CHECK_VIA_SENT_BY 0 #endif @@ -599,7 +598,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 0 */ #ifndef PJSIP_UNESCAPE_IN_PLACE -# define PJSIP_UNESCAPE_IN_PLACE 0 +# define PJSIP_UNESCAPE_IN_PLACE 0 #endif @@ -613,7 +612,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 0 */ #ifndef PJSIP_ALLOW_PORT_IN_FROMTO_HDR -# define PJSIP_ALLOW_PORT_IN_FROMTO_HDR 0 +# define PJSIP_ALLOW_PORT_IN_FROMTO_HDR 0 #endif /** @@ -630,7 +629,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 1 */ #ifndef PJSIP_MAX_NET_EVENTS -# define PJSIP_MAX_NET_EVENTS 1 +# define PJSIP_MAX_NET_EVENTS 1 #endif @@ -640,7 +639,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 10 */ #ifndef PJSIP_MAX_TIMED_OUT_ENTRIES -# define PJSIP_MAX_TIMED_OUT_ENTRIES 10 +# define PJSIP_MAX_TIMED_OUT_ENTRIES 10 #endif @@ -656,7 +655,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 33 */ #ifndef PJSIP_TRANSPORT_IDLE_TIME -# define PJSIP_TRANSPORT_IDLE_TIME 33 +# define PJSIP_TRANSPORT_IDLE_TIME 33 #endif @@ -669,7 +668,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 600 */ #ifndef PJSIP_TRANSPORT_SERVER_IDLE_TIME -# define PJSIP_TRANSPORT_SERVER_IDLE_TIME 600 +# define PJSIP_TRANSPORT_SERVER_IDLE_TIME 600 #endif @@ -682,7 +681,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: -1 */ #ifndef PJSIP_MAX_TRANSPORT_USAGE -# define PJSIP_MAX_TRANSPORT_USAGE ((unsigned)-1) +# define PJSIP_MAX_TRANSPORT_USAGE ((unsigned)-1) #endif @@ -694,7 +693,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * @see PJSIP_TLS_TRANSPORT_BACKLOG */ #ifndef PJSIP_TCP_TRANSPORT_BACKLOG -# define PJSIP_TCP_TRANSPORT_BACKLOG 5 +# define PJSIP_TCP_TRANSPORT_BACKLOG 5 #endif @@ -709,9 +708,9 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) */ #ifndef PJSIP_TCP_TRANSPORT_REUSEADDR # if (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64) -# define PJSIP_TCP_TRANSPORT_REUSEADDR 0 +# define PJSIP_TCP_TRANSPORT_REUSEADDR 0 # else -# define PJSIP_TCP_TRANSPORT_REUSEADDR 1 +# define PJSIP_TCP_TRANSPORT_REUSEADDR 1 # endif #endif @@ -778,7 +777,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: CRLF */ #ifndef PJSIP_TCP_KEEP_ALIVE_DATA -# define PJSIP_TCP_KEEP_ALIVE_DATA { "\r\n\r\n", 4 } +# define PJSIP_TCP_KEEP_ALIVE_DATA { "\r\n\r\n", 4 } #endif @@ -794,7 +793,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 0 (disabled) */ #ifndef PJSIP_TCP_INITIAL_TIMEOUT -# define PJSIP_TCP_INITIAL_TIMEOUT 0 +# define PJSIP_TCP_INITIAL_TIMEOUT 0 #endif /** @@ -819,7 +818,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: CRLF */ #ifndef PJSIP_TLS_KEEP_ALIVE_DATA -# define PJSIP_TLS_KEEP_ALIVE_DATA { "\r\n\r\n", 4 } +# define PJSIP_TLS_KEEP_ALIVE_DATA { "\r\n\r\n", 4 } #endif @@ -844,7 +843,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * @see PJSIP_MAX_RESOLVED_ADDRESSES */ #ifndef PJSIP_HAS_RESOLVER -# define PJSIP_HAS_RESOLVER 1 +# define PJSIP_HAS_RESOLVER 1 #endif @@ -859,9 +858,9 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) */ #ifndef PJSIP_MAX_RESOLVED_ADDRESSES # if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6 -# define PJSIP_MAX_RESOLVED_ADDRESSES 32 +# define PJSIP_MAX_RESOLVED_ADDRESSES 32 # else -# define PJSIP_MAX_RESOLVED_ADDRESSES 16 +# define PJSIP_MAX_RESOLVED_ADDRESSES 16 # endif #endif @@ -885,7 +884,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * @see PJSIP_TCP_TRANSPORT_BACKLOG */ #ifndef PJSIP_TLS_TRANSPORT_BACKLOG -# define PJSIP_TLS_TRANSPORT_BACKLOG 5 +# define PJSIP_TLS_TRANSPORT_BACKLOG 5 #endif @@ -898,9 +897,9 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) */ #ifndef PJSIP_TLS_TRANSPORT_REUSEADDR # if (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64) -# define PJSIP_TLS_TRANSPORT_REUSEADDR 0 +# define PJSIP_TLS_TRANSPORT_REUSEADDR 0 # else -# define PJSIP_TLS_TRANSPORT_REUSEADDR 1 +# define PJSIP_TLS_TRANSPORT_REUSEADDR 1 # endif #endif @@ -913,22 +912,22 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: (2*pjsip_cfg()->tsx.max_count) + (2*PJSIP_MAX_DIALOG_COUNT) */ #ifndef PJSIP_MAX_TIMER_COUNT -# define PJSIP_MAX_TIMER_COUNT (2*pjsip_cfg()->tsx.max_count + \ - 2*PJSIP_MAX_DIALOG_COUNT) +# define PJSIP_MAX_TIMER_COUNT (2*pjsip_cfg()->tsx.max_count + \ + 2*PJSIP_MAX_DIALOG_COUNT) #endif /** * Initial memory block for the endpoint. */ #ifndef PJSIP_POOL_LEN_ENDPT -# define PJSIP_POOL_LEN_ENDPT (4000) +# define PJSIP_POOL_LEN_ENDPT (4000) #endif /** * Memory increment for endpoint. */ #ifndef PJSIP_POOL_INC_ENDPT -# define PJSIP_POOL_INC_ENDPT (4000) +# define PJSIP_POOL_INC_ENDPT (4000) #endif @@ -938,86 +937,86 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Initial memory block for rdata. */ #ifndef PJSIP_POOL_RDATA_LEN -# define PJSIP_POOL_RDATA_LEN 4000 +# define PJSIP_POOL_RDATA_LEN 4000 #endif /** * Memory increment for rdata. */ #ifndef PJSIP_POOL_RDATA_INC -# define PJSIP_POOL_RDATA_INC 4000 +# define PJSIP_POOL_RDATA_INC 4000 #endif /** * Initial memory block for SIP transport. */ #ifndef PJSIP_POOL_LEN_TRANSPORT -# define PJSIP_POOL_LEN_TRANSPORT 512 +# define PJSIP_POOL_LEN_TRANSPORT 512 #endif /** * Memory increment for SIP transport. */ #ifndef PJSIP_POOL_INC_TRANSPORT -# define PJSIP_POOL_INC_TRANSPORT 512 +# define PJSIP_POOL_INC_TRANSPORT 512 #endif /** * Initial memory block size for tdata. */ #ifndef PJSIP_POOL_LEN_TDATA -# define PJSIP_POOL_LEN_TDATA 4000 +# define PJSIP_POOL_LEN_TDATA 4000 #endif /** * Memory increment for tdata. */ #ifndef PJSIP_POOL_INC_TDATA -# define PJSIP_POOL_INC_TDATA 4000 +# define PJSIP_POOL_INC_TDATA 4000 #endif /** * Initial memory size for UA layer */ #ifndef PJSIP_POOL_LEN_UA -# define PJSIP_POOL_LEN_UA 512 +# define PJSIP_POOL_LEN_UA 512 #endif /** * Memory increment for UA layer. */ #ifndef PJSIP_POOL_INC_UA -# define PJSIP_POOL_INC_UA 512 +# define PJSIP_POOL_INC_UA 512 #endif /** * Initial memory block for event subscription module. */ #ifndef PJSIP_POOL_EVSUB_LEN -# define PJSIP_POOL_EVSUB_LEN 512 +# define PJSIP_POOL_EVSUB_LEN 512 #endif /** * Memory increment for event subscription module. */ #ifndef PJSIP_POOL_EVSUB_INC -# define PJSIP_POOL_EVSUB_INC 512 +# define PJSIP_POOL_EVSUB_INC 512 #endif /** * Default value for Max-Forwards header */ -#define PJSIP_MAX_FORWARDS_VALUE 70 +#define PJSIP_MAX_FORWARDS_VALUE 70 /** * Via branch parameter prefix */ -#define PJSIP_RFC3261_BRANCH_ID "z9hG4bK" +#define PJSIP_RFC3261_BRANCH_ID "z9hG4bK" /** * Length of PJSIP_RFC3261_BRANCH_ID */ -#define PJSIP_RFC3261_BRANCH_LEN 7 +#define PJSIP_RFC3261_BRANCH_LEN 7 /* Transaction related constants. */ @@ -1028,7 +1027,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * fragmentation and the memory will most likely be wasted. */ #ifndef PJSIP_POOL_TSX_LAYER_LEN -# define PJSIP_POOL_TSX_LAYER_LEN 512 +# define PJSIP_POOL_TSX_LAYER_LEN 512 #endif /** @@ -1038,21 +1037,21 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * fragmentation and the memory will most likely be wasted. */ #ifndef PJSIP_POOL_TSX_LAYER_INC -# define PJSIP_POOL_TSX_LAYER_INC 512 +# define PJSIP_POOL_TSX_LAYER_INC 512 #endif /** * Initial memory size for a SIP transaction object. */ #ifndef PJSIP_POOL_TSX_LEN -# define PJSIP_POOL_TSX_LEN 1536 /* 768 */ +# define PJSIP_POOL_TSX_LEN 1536 /* 768 */ #endif /** * Memory increment for transaction object. */ #ifndef PJSIP_POOL_TSX_INC -# define PJSIP_POOL_TSX_INC 256 +# define PJSIP_POOL_TSX_INC 256 #endif /** @@ -1062,7 +1061,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 60 seconds */ #ifndef PJSIP_TSX_1XX_RETRANS_DELAY -# define PJSIP_TSX_1XX_RETRANS_DELAY 60 +# define PJSIP_TSX_1XX_RETRANS_DELAY 60 #endif /** @@ -1078,32 +1077,32 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) # define PJSIP_TSX_UAS_CONTINUE_ON_TP_ERROR 1 #endif -#define PJSIP_MAX_TSX_KEY_LEN (PJSIP_MAX_URL_SIZE*2) +#define PJSIP_MAX_TSX_KEY_LEN (PJSIP_MAX_URL_SIZE*2) /* User agent's pool setting. */ -#define PJSIP_POOL_LEN_USER_AGENT 1024 +#define PJSIP_POOL_LEN_USER_AGENT 1024 /* User agent's pool setting. */ -#define PJSIP_POOL_INC_USER_AGENT 1024 +#define PJSIP_POOL_INC_USER_AGENT 1024 /** Message/URL related constants. */ -#define PJSIP_MAX_CALL_ID_LEN pj_GUID_STRING_LENGTH() +#define PJSIP_MAX_CALL_ID_LEN pj_GUID_STRING_LENGTH() /** Message/URL related constants. */ -#define PJSIP_MAX_TAG_LEN pj_GUID_STRING_LENGTH() +#define PJSIP_MAX_TAG_LEN pj_GUID_STRING_LENGTH() /** Message/URL related constants. */ -#define PJSIP_MAX_BRANCH_LEN (PJSIP_RFC3261_BRANCH_LEN + pj_GUID_STRING_LENGTH() + 2) +#define PJSIP_MAX_BRANCH_LEN (PJSIP_RFC3261_BRANCH_LEN + pj_GUID_STRING_LENGTH() + 2) /** Message/URL related constants. */ -#define PJSIP_MAX_HNAME_LEN 64 +#define PJSIP_MAX_HNAME_LEN 64 /** Dialog's pool setting. */ -#define PJSIP_POOL_LEN_DIALOG 1200 +#define PJSIP_POOL_LEN_DIALOG 1200 /** Dialog's pool setting. */ -#define PJSIP_POOL_INC_DIALOG 512 +#define PJSIP_POOL_INC_DIALOG 512 /** Maximum header types. */ -#define PJSIP_MAX_HEADER_TYPES 72 +#define PJSIP_MAX_HEADER_TYPES 72 /** Maximum URI types. */ -#define PJSIP_MAX_URI_TYPES 4 +#define PJSIP_MAX_URI_TYPES 4 /***************************************************************************** * Default timeout settings, in miliseconds. @@ -1111,17 +1110,17 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) /** Transaction T1 timeout value. */ #if !defined(PJSIP_T1_TIMEOUT) -# define PJSIP_T1_TIMEOUT 500 +# define PJSIP_T1_TIMEOUT 500 #endif /** Transaction T2 timeout value. */ #if !defined(PJSIP_T2_TIMEOUT) -# define PJSIP_T2_TIMEOUT 4000 +# define PJSIP_T2_TIMEOUT 4000 #endif /** Transaction completed timer for non-INVITE */ #if !defined(PJSIP_T4_TIMEOUT) -# define PJSIP_T4_TIMEOUT 5000 +# define PJSIP_T4_TIMEOUT 5000 #endif /** @@ -1131,7 +1130,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * INVITE and non-INVITE. */ #if !defined(PJSIP_TD_TIMEOUT) -# define PJSIP_TD_TIMEOUT 32000 +# define PJSIP_TD_TIMEOUT 32000 #endif @@ -1152,7 +1151,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 0 */ #if !defined(PJSIP_AUTH_HEADER_CACHING) -# define PJSIP_AUTH_HEADER_CACHING 0 +# define PJSIP_AUTH_HEADER_CACHING 0 #endif /** @@ -1173,7 +1172,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 0 */ #if !defined(PJSIP_AUTH_AUTO_SEND_NEXT) -# define PJSIP_AUTH_AUTO_SEND_NEXT 0 +# define PJSIP_AUTH_AUTO_SEND_NEXT 0 #endif /** @@ -1184,7 +1183,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 1 */ #if !defined(PJSIP_AUTH_QOP_SUPPORT) -# define PJSIP_AUTH_QOP_SUPPORT 1 +# define PJSIP_AUTH_QOP_SUPPORT 1 #endif @@ -1195,7 +1194,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 3 */ #ifndef PJSIP_MAX_STALE_COUNT -# define PJSIP_MAX_STALE_COUNT 3 +# define PJSIP_MAX_STALE_COUNT 3 #endif @@ -1209,7 +1208,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 0 (for now) */ #ifndef PJSIP_HAS_DIGEST_AKA_AUTH -# define PJSIP_HAS_DIGEST_AKA_AUTH 0 +# define PJSIP_HAS_DIGEST_AKA_AUTH 0 #endif @@ -1236,7 +1235,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is 1 */ #ifndef PJSIP_REGISTER_CLIENT_CHECK_CONTACT -# define PJSIP_REGISTER_CLIENT_CHECK_CONTACT 1 +# define PJSIP_REGISTER_CLIENT_CHECK_CONTACT 1 #endif @@ -1253,7 +1252,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is 0. */ #ifndef PJSIP_REGISTER_CLIENT_ADD_XUID_PARAM -# define PJSIP_REGISTER_CLIENT_ADD_XUID_PARAM 0 +# define PJSIP_REGISTER_CLIENT_ADD_XUID_PARAM 0 #endif @@ -1265,7 +1264,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is 1. */ #ifndef PJSIP_REGISTER_ALLOW_EXP_REFRESH -# define PJSIP_REGISTER_ALLOW_EXP_REFRESH 1 +# define PJSIP_REGISTER_ALLOW_EXP_REFRESH 1 #endif @@ -1277,7 +1276,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is 20 kB */ #ifndef PJSIP_AUTH_CACHED_POOL_MAX_SIZE -# define PJSIP_AUTH_CACHED_POOL_MAX_SIZE (20 * 1024) +# define PJSIP_AUTH_CACHED_POOL_MAX_SIZE (20 * 1024) #endif @@ -1291,7 +1290,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default is 1 (cnonce will not contain any hyphen characters). */ #ifndef PJSIP_AUTH_CNONCE_USE_DIGITS_ONLY -# define PJSIP_AUTH_CNONCE_USE_DIGITS_ONLY 1 +# define PJSIP_AUTH_CNONCE_USE_DIGITS_ONLY 1 #endif /** @@ -1317,7 +1316,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 5 seconds */ #ifndef PJSIP_EVSUB_TIME_UAC_REFRESH -# define PJSIP_EVSUB_TIME_UAC_REFRESH 5 +# define PJSIP_EVSUB_TIME_UAC_REFRESH 5 #endif @@ -1328,7 +1327,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 5 seconds */ #ifndef PJSIP_PUBLISHC_DELAY_BEFORE_REFRESH -# define PJSIP_PUBLISHC_DELAY_BEFORE_REFRESH 5 +# define PJSIP_PUBLISHC_DELAY_BEFORE_REFRESH 5 #endif @@ -1339,7 +1338,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 5 seconds */ #ifndef PJSIP_EVSUB_TIME_UAC_TERMINATE -# define PJSIP_EVSUB_TIME_UAC_TERMINATE 5 +# define PJSIP_EVSUB_TIME_UAC_TERMINATE 5 #endif @@ -1352,7 +1351,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 5 seconds */ #ifndef PJSIP_EVSUB_TIME_UAC_WAIT_NOTIFY -# define PJSIP_EVSUB_TIME_UAC_WAIT_NOTIFY 5 +# define PJSIP_EVSUB_TIME_UAC_WAIT_NOTIFY 5 #endif @@ -1368,7 +1367,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 600 seconds (10 minutes) */ #ifndef PJSIP_PRES_DEFAULT_EXPIRES -# define PJSIP_PRES_DEFAULT_EXPIRES 600 +# define PJSIP_PRES_DEFAULT_EXPIRES 600 #endif @@ -1386,7 +1385,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 488 (Not Acceptable Here) */ #ifndef PJSIP_PRES_BAD_CONTENT_RESPONSE -# define PJSIP_PRES_BAD_CONTENT_RESPONSE 488 +# define PJSIP_PRES_BAD_CONTENT_RESPONSE 488 #endif @@ -1397,7 +1396,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 1 (yes) */ #ifndef PJSIP_PRES_PIDF_ADD_TIMESTAMP -# define PJSIP_PRES_PIDF_ADD_TIMESTAMP 1 +# define PJSIP_PRES_PIDF_ADD_TIMESTAMP 1 #endif @@ -1410,7 +1409,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 1800 seconds */ #ifndef PJSIP_SESS_TIMER_DEF_SE -# define PJSIP_SESS_TIMER_DEF_SE 1800 +# define PJSIP_SESS_TIMER_DEF_SE 1800 #endif @@ -1422,7 +1421,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 10 seconds */ #ifndef PJSIP_SESS_TIMER_RETRY_DELAY -# define PJSIP_SESS_TIMER_RETRY_DELAY 10 +# define PJSIP_SESS_TIMER_RETRY_DELAY 10 #endif @@ -1436,7 +1435,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 1 (yes) */ #ifndef PJSIP_PUBLISHC_QUEUE_REQUEST -# define PJSIP_PUBLISHC_QUEUE_REQUEST 1 +# define PJSIP_PUBLISHC_QUEUE_REQUEST 1 #endif @@ -1453,7 +1452,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 3600 seconds */ #ifndef PJSIP_MWI_DEFAULT_EXPIRES -# define PJSIP_MWI_DEFAULT_EXPIRES 3600 +# define PJSIP_MWI_DEFAULT_EXPIRES 3600 #endif @@ -1468,7 +1467,7 @@ PJ_INLINE(pjsip_cfg_t*) pjsip_cfg(void) * Default: 0 (no) */ #ifndef PJSIP_HAS_TX_DATA_LIST -# define PJSIP_HAS_TX_DATA_LIST 0 +# define PJSIP_HAS_TX_DATA_LIST 0 #endif /** @@ -1513,5 +1512,5 @@ PJ_END_DECL #include -#endif /* __PJSIP_SIP_CONFIG_H__ */ +#endif /* __PJSIP_SIP_CONFIG_H__ */ diff --git a/pjsip/include/pjsip/sip_dialog.h b/pjsip/include/pjsip/sip_dialog.h index 623d8fae91..49853ce478 100644 --- a/pjsip/include/pjsip/sip_dialog.h +++ b/pjsip/include/pjsip/sip_dialog.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -76,12 +75,12 @@ PJ_BEGIN_DECL */ typedef struct pjsip_dlg_party { - pjsip_fromto_hdr *info; /**< From/To header, inc tag. */ - pj_str_t info_str; /**< String rep of info header. */ - pj_uint32_t tag_hval; /**< Hashed value of the tag. */ - pjsip_contact_hdr *contact; /**< Contact header. */ - pj_int32_t first_cseq;/**< First CSeq seen. */ - pj_int32_t cseq; /**< Next sequence number. */ + pjsip_fromto_hdr *info; /**< From/To header, inc tag. */ + pj_str_t info_str; /**< String rep of info header. */ + pj_uint32_t tag_hval; /**< Hashed value of the tag. */ + pjsip_contact_hdr *contact; /**< Contact header. */ + pj_int32_t first_cseq;/**< First CSeq seen. */ + pj_int32_t cseq; /**< Next sequence number. */ } pjsip_dlg_party; @@ -107,14 +106,14 @@ typedef enum pjsip_dialog_cap_status PJSIP_DIALOG_CAP_UNSUPPORTED = 0, /** Capability is supported */ - PJSIP_DIALOG_CAP_SUPPORTED = 1, + PJSIP_DIALOG_CAP_SUPPORTED = 1, /** * Unknown capability status. This is usually because we lack the * capability info which is retrieved from capability header specified * in the dialog messages. */ - PJSIP_DIALOG_CAP_UNKNOWN = 2 + PJSIP_DIALOG_CAP_UNKNOWN = 2 } pjsip_dialog_cap_status; @@ -139,58 +138,58 @@ struct pjsip_dialog PJ_DECL_LIST_MEMBER(pjsip_dialog); /* Dialog's system properties. */ - char obj_name[PJ_MAX_OBJ_NAME]; /**< Standard id. */ - pj_pool_t *pool; /**< Dialog's pool. */ - pjsip_user_agent *ua; /**< User agent instance. */ - pjsip_endpoint *endpt; /**< Endpoint instance. */ + char obj_name[PJ_MAX_OBJ_NAME]; /**< Standard id. */ + pj_pool_t *pool; /**< Dialog's pool. */ + pjsip_user_agent *ua; /**< User agent instance. */ + pjsip_endpoint *endpt; /**< Endpoint instance. */ pj_grp_lock_t *grp_lock_; /**< Dialog's grp lock. Do not call!! - Use pjsip_dlg_inc_lock() instead! */ + Use pjsip_dlg_inc_lock() instead! */ /** The dialog set which this dialog belongs (opaque type). */ - void *dlg_set; + void *dlg_set; /* Dialog's session properties. */ - pjsip_dialog_state state; /**< Dialog state. */ - pjsip_uri *target; /**< Current target. */ - pjsip_target_set target_set; /**< Target set, for UAC only. */ - pjsip_hdr inv_hdr; /**< Headers from hparam in dest URL */ - pjsip_dlg_party local; /**< Local party info. */ - pjsip_dlg_party remote; /**< Remote party info. */ - pjsip_hdr rem_cap_hdr;/**< List of remote capability header. */ - pjsip_role_e role; /**< Initial role. */ - pj_bool_t uac_has_2xx;/**< UAC has received 2xx response? */ - pj_bool_t secure; /**< Use secure transport? */ - pj_bool_t add_allow; /**< Add Allow header in requests? */ - pjsip_cid_hdr *call_id; /**< Call-ID header. */ - pjsip_route_hdr route_set; /**< Route set. */ - pj_bool_t route_set_frozen; /**< Route set has been set. */ - pjsip_auth_clt_sess auth_sess; /**< Client authentication session. */ - pj_str_t initial_dest;/**< Initial destination host. */ + pjsip_dialog_state state; /**< Dialog state. */ + pjsip_uri *target; /**< Current target. */ + pjsip_target_set target_set; /**< Target set, for UAC only. */ + pjsip_hdr inv_hdr; /**< Headers from hparam in dest URL */ + pjsip_dlg_party local; /**< Local party info. */ + pjsip_dlg_party remote; /**< Remote party info. */ + pjsip_hdr rem_cap_hdr;/**< List of remote capability header. */ + pjsip_role_e role; /**< Initial role. */ + pj_bool_t uac_has_2xx;/**< UAC has received 2xx response? */ + pj_bool_t secure; /**< Use secure transport? */ + pj_bool_t add_allow; /**< Add Allow header in requests? */ + pjsip_cid_hdr *call_id; /**< Call-ID header. */ + pjsip_route_hdr route_set; /**< Route set. */ + pj_bool_t route_set_frozen; /**< Route set has been set. */ + pjsip_auth_clt_sess auth_sess; /**< Client authentication session. */ + pj_str_t initial_dest;/**< Initial destination host. */ /** Session counter. */ - int sess_count; /**< Number of sessions. */ + int sess_count; /**< Number of sessions. */ /** Transaction counter. */ - int tsx_count; /**< Number of pending transactions. */ + int tsx_count; /**< Number of pending transactions. */ /** Transport selector. */ - pjsip_tpselector tp_sel; + pjsip_tpselector tp_sel; /* Dialog usages. */ - unsigned usage_cnt; /**< Number of registered usages. */ + unsigned usage_cnt; /**< Number of registered usages. */ pjsip_module *usage[PJSIP_MAX_MODULE]; /**< Array of usages, - priority sorted */ + priority sorted */ /** Module specific data. */ - void *mod_data[PJSIP_MAX_MODULE]; /**< Module data. */ + void *mod_data[PJSIP_MAX_MODULE]; /**< Module data. */ /** * If via_addr is set, it will be used as the "sent-by" field of the * Via header for outgoing requests as long as the request uses via_tp * transport. Normally application should not use or access these fields. */ - pjsip_host_port via_addr; /**< Via address. */ - const void *via_tp; /**< Via transport. */ + pjsip_host_port via_addr; /**< Via address. */ + const void *via_tp; /**< Via transport. */ }; /** @@ -244,9 +243,9 @@ typedef struct pjsip_dlg_create_uac_param { * dialog creating request. This method property is used to determine * whether Contact header should be included in outgoing request. * - * @param m The SIP method. + * @param m The SIP method. * - * @return PJ_TRUE if the method creates a dialog. + * @return PJ_TRUE if the method creates a dialog. */ PJ_DECL(pj_bool_t) pjsip_method_creates_dialog(const pjsip_method *m); @@ -265,34 +264,34 @@ PJ_DECL(pj_bool_t) pjsip_method_creates_dialog(const pjsip_method *m); * Note that initially, the session count in the dialog will be initialized * to zero. * - * @param ua The user agent module instance. - * @param local_uri Dialog local URI (i.e. From header). - * @param local_contact Optional dialog local Contact to be put as Contact - * header value, hence the format must follow - * RFC 3261 Section 20.10: - * When the header field value contains a display - * name, the URI including all URI parameters is - * enclosed in "<" and ">". If no "<" and ">" are - * present, all parameters after the URI are header - * parameters, not URI parameters. The display name - * can be tokens, or a quoted string, if a larger - * character set is desired. - * If this argument is NULL, the Contact will be taken - * from the local URI. - * @param remote_uri Dialog remote URI (i.e. To header). - * @param target Optional initial remote target. If this argument - * is NULL, the initial target will be set to - * remote URI. - * @param p_dlg Pointer to receive the dialog. - * - * @return PJ_SUCCESS on success. + * @param ua The user agent module instance. + * @param local_uri Dialog local URI (i.e. From header). + * @param local_contact Optional dialog local Contact to be put as Contact + * header value, hence the format must follow + * RFC 3261 Section 20.10: + * When the header field value contains a display + * name, the URI including all URI parameters is + * enclosed in "<" and ">". If no "<" and ">" are + * present, all parameters after the URI are header + * parameters, not URI parameters. The display name + * can be tokens, or a quoted string, if a larger + * character set is desired. + * If this argument is NULL, the Contact will be taken + * from the local URI. + * @param remote_uri Dialog remote URI (i.e. To header). + * @param target Optional initial remote target. If this argument + * is NULL, the initial target will be set to + * remote URI. + * @param p_dlg Pointer to receive the dialog. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_dlg_create_uac( pjsip_user_agent *ua, - const pj_str_t *local_uri, - const pj_str_t *local_contact, - const pj_str_t *remote_uri, - const pj_str_t *target, - pjsip_dialog **p_dlg); + const pj_str_t *local_uri, + const pj_str_t *local_contact, + const pj_str_t *remote_uri, + const pj_str_t *target, + pjsip_dialog **p_dlg); /** * Variant of pjsip_dlg_create_uac() with additional parameter to specify @@ -302,15 +301,15 @@ PJ_DECL(pj_status_t) pjsip_dlg_create_uac( pjsip_user_agent *ua, * * See \a pjsip_dlg_create_uac() for general info about this function. * - * @param create_param The parameter, refer to - * \a pjsip_dlg_create_uac_param - * @param p_dlg Pointer to receive the dialog. + * @param create_param The parameter, refer to + * \a pjsip_dlg_create_uac_param + * @param p_dlg Pointer to receive the dialog. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_dlg_create_uac2( - const pjsip_dlg_create_uac_param *create_param, - pjsip_dialog **p_dlg); + const pjsip_dlg_create_uac_param *create_param, + pjsip_dialog **p_dlg); #if !DEPRECATED_FOR_TICKET_1902 @@ -329,30 +328,30 @@ PJ_DECL(pj_status_t) pjsip_dlg_create_uac2( * to zero. * * - * @param ua The user agent module instance. - * @param rdata The incoming request that creates the dialog, - * such as INVITE, SUBSCRIBE, or REFER. - * @param contact Optional dialog local Contact to be put as Contact - * header value, hence the format must follow - * RFC 3261 Section 20.10: - * When the header field value contains a display - * name, the URI including all URI parameters is - * enclosed in "<" and ">". If no "<" and ">" are - * present, all parameters after the URI are header - * parameters, not URI parameters. The display name - * can be tokens, or a quoted string, if a larger - * character set is desired. - * If this argument is NULL, the local contact will be - * initialized from the value of To header in the - * request. - * @param p_dlg Pointer to receive the dialog. - * - * @return PJ_SUCCESS on success. + * @param ua The user agent module instance. + * @param rdata The incoming request that creates the dialog, + * such as INVITE, SUBSCRIBE, or REFER. + * @param contact Optional dialog local Contact to be put as Contact + * header value, hence the format must follow + * RFC 3261 Section 20.10: + * When the header field value contains a display + * name, the URI including all URI parameters is + * enclosed in "<" and ">". If no "<" and ">" are + * present, all parameters after the URI are header + * parameters, not URI parameters. The display name + * can be tokens, or a quoted string, if a larger + * character set is desired. + * If this argument is NULL, the local contact will be + * initialized from the value of To header in the + * request. + * @param p_dlg Pointer to receive the dialog. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_dlg_create_uas( pjsip_user_agent *ua, - pjsip_rx_data *rdata, - const pj_str_t *contact, - pjsip_dialog **p_dlg); + pjsip_rx_data *rdata, + const pj_str_t *contact, + pjsip_dialog **p_dlg); #endif @@ -372,31 +371,31 @@ PJ_DECL(pj_status_t) pjsip_dlg_create_uas( pjsip_user_agent *ua, * #pjsip_dlg_dec_lock() to release the lock and decrease the session count. * * - * @param ua The user agent module instance. - * @param rdata The incoming request that creates the dialog, - * such as INVITE, SUBSCRIBE, or REFER. - * @param contact Optional dialog local Contact to be put as Contact - * header value, hence the format must follow - * RFC 3261 Section 20.10: - * When the header field value contains a display - * name, the URI including all URI parameters is - * enclosed in "<" and ">". If no "<" and ">" are - * present, all parameters after the URI are header - * parameters, not URI parameters. The display name - * can be tokens, or a quoted string, if a larger - * character set is desired. - * If this argument is NULL, the local contact will be - * initialized from the value of To header in the - * request. - * @param p_dlg Pointer to receive the dialog. - * - * @return PJ_SUCCESS on success. + * @param ua The user agent module instance. + * @param rdata The incoming request that creates the dialog, + * such as INVITE, SUBSCRIBE, or REFER. + * @param contact Optional dialog local Contact to be put as Contact + * header value, hence the format must follow + * RFC 3261 Section 20.10: + * When the header field value contains a display + * name, the URI including all URI parameters is + * enclosed in "<" and ">". If no "<" and ">" are + * present, all parameters after the URI are header + * parameters, not URI parameters. The display name + * can be tokens, or a quoted string, if a larger + * character set is desired. + * If this argument is NULL, the local contact will be + * initialized from the value of To header in the + * request. + * @param p_dlg Pointer to receive the dialog. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_dlg_create_uas_and_inc_lock( pjsip_user_agent *ua, - pjsip_rx_data *rdata, - const pj_str_t *contact, - pjsip_dialog **p_dlg); + pjsip_rx_data *rdata, + const pj_str_t *contact, + pjsip_dialog **p_dlg); /** @@ -412,30 +411,30 @@ pjsip_dlg_create_uas_and_inc_lock( pjsip_user_agent *ua, * necessary, to adjust the address according to the transport being * selected. * - * @param dlg The dialog instance. - * @param sel Transport selector containing the specification of - * transport or listener to be used by this dialog - * to send requests. + * @param dlg The dialog instance. + * @param sel Transport selector containing the specification of + * transport or listener to be used by this dialog + * to send requests. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_dlg_set_transport(pjsip_dialog *dlg, - const pjsip_tpselector *sel); + const pjsip_tpselector *sel); /** * Set the "sent-by" field of the Via header for outgoing requests. * - * @param dlg The dialog instance. + * @param dlg The dialog instance. * @param via_addr Set via_addr to use for the Via header or NULL to use * the transport's published name. * @param via_tp via_addr will only be used if we are using via_tp * transport. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_dlg_set_via_sent_by(pjsip_dialog *dlg, - pjsip_host_port *via_addr, + pjsip_host_port *via_addr, pjsip_transport *via_tp); @@ -449,15 +448,15 @@ PJ_DECL(pj_status_t) pjsip_dlg_set_via_sent_by(pjsip_dialog *dlg, * Note that initially, the session count in the dialog will be initialized * to zero. * - * @param original_dlg The original UAC dialog. - * @param rdata The incoming forked response message. - * @param new_dlg Pointer to receive the new dialog. + * @param original_dlg The original UAC dialog. + * @param rdata The incoming forked response message. + * @param new_dlg Pointer to receive the new dialog. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_dlg_fork(const pjsip_dialog *original_dlg, - const pjsip_rx_data *rdata, - pjsip_dialog **new_dlg ); + const pjsip_rx_data *rdata, + pjsip_dialog **new_dlg ); /** * Forcefully terminate the dialog. Application can only call this function @@ -467,9 +466,9 @@ PJ_DECL(pj_status_t) pjsip_dlg_fork(const pjsip_dialog *original_dlg, * for each dialog session (e.g. #pjsip_inv_terminate() to terminate INVITE * session). * - * @param dlg The dialog. + * @param dlg The dialog. * - * @return PJ_SUCCESS if dialog has been terminated. + * @return PJ_SUCCESS if dialog has been terminated. */ PJ_DECL(pj_status_t) pjsip_dlg_terminate( pjsip_dialog *dlg ); @@ -486,25 +485,25 @@ PJ_DECL(pj_status_t) pjsip_dlg_terminate( pjsip_dialog *dlg ); * The route_set argument is standard list of Route headers (i.e. with * sentinel). * - * @param dlg The UAC dialog. - * @param route_set List of Route header. + * @param dlg The UAC dialog. + * @param route_set List of Route header. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_dlg_set_route_set( pjsip_dialog *dlg, - const pjsip_route_hdr *route_set ); + const pjsip_route_hdr *route_set ); /** * Increment the number of sessions in the dialog. Note that initially * (after created) the dialog has the session counter set to zero. * - * @param dlg The dialog. - * @param mod The module that increments the session counter. + * @param dlg The dialog. + * @param mod The module that increments the session counter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_dlg_inc_session( pjsip_dialog *dlg, - pjsip_module *mod); + pjsip_module *mod); /** @@ -513,74 +512,74 @@ PJ_DECL(pj_status_t) pjsip_dlg_inc_session( pjsip_dialog *dlg, * destroyed. Note that this function may destroy the dialog immediately * if there is no pending transaction when this function is called. * - * @param dlg The dialog. - * @param mod The module that decrements the session counter. + * @param dlg The dialog. + * @param mod The module that decrements the session counter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_dlg_dec_session( pjsip_dialog *dlg, - pjsip_module *mod); + pjsip_module *mod); /** * Add a module as dialog usage, and optionally set the module specific data. * - * @param dlg The dialog. - * @param module The module to be registered as dialog usage. - * @param mod_data Optional arbitrary data to be attached to dialog's - * mod_data array at the module's index. + * @param dlg The dialog. + * @param module The module to be registered as dialog usage. + * @param mod_data Optional arbitrary data to be attached to dialog's + * mod_data array at the module's index. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_dlg_add_usage( pjsip_dialog *dlg, - pjsip_module *module, - void *mod_data ); + pjsip_module *module, + void *mod_data ); /** * Check if the specified module has been registered as usage to the dialog. * - * @param dlg The dialog. - * @param module The module. + * @param dlg The dialog. + * @param module The module. * - * @return PJ_TRUE if the specified module is currently - * registered as a usage to the dialog. + * @return PJ_TRUE if the specified module is currently + * registered as a usage to the dialog. */ PJ_DECL(pj_bool_t) pjsip_dlg_has_usage(pjsip_dialog *dlg, - pjsip_module *module); + pjsip_module *module); /** * Attach module specific data to the dialog. Application can also set * the value directly by accessing dlg->mod_data[module_id]. * - * @param dlg The dialog - * @param mod_id The ID of the module from which the data is to be - * set to the dialog. - * @param data Arbitrary data. + * @param dlg The dialog + * @param mod_id The ID of the module from which the data is to be + * set to the dialog. + * @param data Arbitrary data. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_dlg_set_mod_data( pjsip_dialog *dlg, - int mod_id, - void *data ); + int mod_id, + void *data ); /** * Get module specific data previously attached to the dialog. Application * can also get value directly by accessing dlg->mod_data[module_id]. * - * @param dlg The dialog - * @param mod_id The ID of the module from which the data is to be - * retrieved from the dialog. + * @param dlg The dialog + * @param mod_id The ID of the module from which the data is to be + * retrieved from the dialog. * - * @return The data that was previously set, or NULL. + * @return The data that was previously set, or NULL. */ PJ_DECL(void*) pjsip_dlg_get_mod_data( pjsip_dialog *dlg, - int mod_id); + int mod_id); /** * Lock dialog and increment session counter termporarily, to prevent it * from being destroyed. * - * @param dlg The dialog. + * @param dlg The dialog. */ PJ_DECL(void) pjsip_dlg_inc_lock( pjsip_dialog *dlg ); @@ -588,9 +587,9 @@ PJ_DECL(void) pjsip_dlg_inc_lock( pjsip_dialog *dlg ); * Try to acquire dialog's lock, but return immediately if lock can not * be acquired. * - * @param dlg The dialog. + * @param dlg The dialog. * - * @return PJ_SUCCESS if lock has been acquired. + * @return PJ_SUCCESS if lock has been acquired. */ PJ_DECL(pj_status_t) pjsip_dlg_try_inc_lock( pjsip_dialog *dlg ); @@ -598,7 +597,7 @@ PJ_DECL(pj_status_t) pjsip_dlg_try_inc_lock( pjsip_dialog *dlg ); * Unlock dialog and decrement temporary session counter. After this function * is called, dialog may be destroyed. * - * @param dlg The dialog. + * @param dlg The dialog. */ PJ_DECL(void) pjsip_dlg_dec_lock( pjsip_dialog *dlg ); @@ -607,9 +606,9 @@ PJ_DECL(void) pjsip_dlg_dec_lock( pjsip_dialog *dlg ); * method, it is recommended to hold reference to the dialog * (e.g: call #pjsip_dlg_inc_session() or #pjsip_dlg_inc_lock()). * - * @param dlg The dialog. + * @param dlg The dialog. * - * @return The group lock. + * @return The group lock. */ PJ_DECL(pj_grp_lock_t *) pjsip_dlg_get_lock( pjsip_dialog *dlg ); @@ -625,9 +624,9 @@ PJ_DECL(pj_grp_lock_t *) pjsip_dlg_get_lock( pjsip_dialog *dlg ); * only call this function in the context of module that runs in priority * number higher than PJSIP_MOD_PRIORITY_UA_PROXY_LAYER. * - * @param rdata Incoming message buffer. + * @param rdata Incoming message buffer. * - * @return The dialog instance that "owns" the message. + * @return The dialog instance that "owns" the message. */ PJ_DECL(pjsip_dialog*) pjsip_rdata_get_dlg( pjsip_rx_data *rdata ); @@ -635,20 +634,20 @@ PJ_DECL(pjsip_dialog*) pjsip_rdata_get_dlg( pjsip_rx_data *rdata ); * Get the dialog instance for the outgoing tdata. Returns NULL if the message * wasn't sent from a dialog. * - * @param tdata Outgoing message buffer. + * @param tdata Outgoing message buffer. * - * @return The dialog instance that "owns" the message. + * @return The dialog instance that "owns" the message. */ PJ_DECL(pjsip_dialog*) pjsip_tdata_get_dlg( pjsip_tx_data *tdata ); /** * Get the associated dialog for the specified transaction, if any. * - * @param tsx The transaction. + * @param tsx The transaction. * - * @return The dialog instance which has been registered - * to the transaction as transaction user, or - * NULL if the transaction is outside any dialogs. + * @return The dialog instance which has been registered + * to the transaction as transaction user, or + * NULL if the transaction is outside any dialogs. */ PJ_DECL(pjsip_dialog*) pjsip_tsx_get_dlg( pjsip_transaction *tsx ); @@ -662,20 +661,20 @@ PJ_DECL(pjsip_dialog*) pjsip_tsx_get_dlg( pjsip_transaction *tsx ); * * This function will also put Contact header where appropriate. * - * @param dlg The dialog instance. - * @param method The method of the request. - * @param cseq Optional CSeq, which only needs to be specified - * when creating ACK and CANCEL. For other requests, - * specify -1 to use dialog's internal counter. - * @param tdata Pointer to receive the request's transmit - * data buffer. + * @param dlg The dialog instance. + * @param method The method of the request. + * @param cseq Optional CSeq, which only needs to be specified + * when creating ACK and CANCEL. For other requests, + * specify -1 to use dialog's internal counter. + * @param tdata Pointer to receive the request's transmit + * data buffer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ -PJ_DECL(pj_status_t) pjsip_dlg_create_request( pjsip_dialog *dlg, - const pjsip_method *method, - int cseq, - pjsip_tx_data **tdata); +PJ_DECL(pj_status_t) pjsip_dlg_create_request( pjsip_dialog *dlg, + const pjsip_method *method, + int cseq, + pjsip_tx_data **tdata); /** @@ -693,20 +692,20 @@ PJ_DECL(pj_status_t) pjsip_dlg_create_request( pjsip_dialog *dlg, * This function will decrement the transmit data's reference counter * regardless the status of the operation. * - * @param dlg The dialog. - * @param tdata The request message to be sent. - * @param mod_data_id Optional module data index to put an optional data - * into the transaction. If no module data is to be - * attached, this value should be -1. - * @param mod_data Optional module data to be attached to the - * transaction at mod_data_id index. + * @param dlg The dialog. + * @param tdata The request message to be sent. + * @param mod_data_id Optional module data index to put an optional data + * into the transaction. If no module data is to be + * attached, this value should be -1. + * @param mod_data Optional module data to be attached to the + * transaction at mod_data_id index. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ -PJ_DECL(pj_status_t) pjsip_dlg_send_request ( pjsip_dialog *dlg, - pjsip_tx_data *tdata, - int mod_data_id, - void *mod_data); +PJ_DECL(pj_status_t) pjsip_dlg_send_request ( pjsip_dialog *dlg, + pjsip_tx_data *tdata, + int mod_data_id, + void *mod_data); /** @@ -716,39 +715,39 @@ PJ_DECL(pj_status_t) pjsip_dlg_send_request ( pjsip_dialog *dlg, * function adds Contact header and Record-Routes headers in the response * where appropriate. * - * @param dlg The dialog. - * @param rdata The incoming request message for which the - * response will be created. - * @param st_code Status code. - * @param st_text Optional string for custom status reason text. - * @param tdata Pointer to receive the response message transmit - * data buffer. + * @param dlg The dialog. + * @param rdata The incoming request message for which the + * response will be created. + * @param st_code Status code. + * @param st_text Optional string for custom status reason text. + * @param tdata Pointer to receive the response message transmit + * data buffer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ -PJ_DECL(pj_status_t) pjsip_dlg_create_response( pjsip_dialog *dlg, - pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - pjsip_tx_data **tdata); +PJ_DECL(pj_status_t) pjsip_dlg_create_response( pjsip_dialog *dlg, + pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + pjsip_tx_data **tdata); /** * Modify previously sent response with other status code. Contact header * will be added when appropriate. * - * @param dlg The dialog. - * @param tdata The transmit data buffer containing response - * message to be modified. - * @param st_code New status code to be set. - * @param st_text Optional string for custom status reason text. + * @param dlg The dialog. + * @param tdata The transmit data buffer containing response + * message to be modified. + * @param st_code New status code to be set. + * @param st_text Optional string for custom status reason text. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ -PJ_DECL(pj_status_t) pjsip_dlg_modify_response( pjsip_dialog *dlg, - pjsip_tx_data *tdata, - int st_code, - const pj_str_t *st_text); +PJ_DECL(pj_status_t) pjsip_dlg_modify_response( pjsip_dialog *dlg, + pjsip_tx_data *tdata, + int st_code, + const pj_str_t *st_text); /** @@ -758,42 +757,42 @@ PJ_DECL(pj_status_t) pjsip_dlg_modify_response( pjsip_dialog *dlg, * This function decrements the transmit data's reference counter regardless * the status of the operation. * - * @param dlg The dialog. - * @param tsx The UAS transaction associated with the incoming - * request. If the request is within a dialog, or - * a dialog has been created for the request that - * creates the dialog, application can get the - * transaction instance for the request by calling - * #pjsip_rdata_get_tsx(). - * @param tdata Response message to be sent. + * @param dlg The dialog. + * @param tsx The UAS transaction associated with the incoming + * request. If the request is within a dialog, or + * a dialog has been created for the request that + * creates the dialog, application can get the + * transaction instance for the request by calling + * #pjsip_rdata_get_tsx(). + * @param tdata Response message to be sent. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ -PJ_DECL(pj_status_t) pjsip_dlg_send_response( pjsip_dialog *dlg, - pjsip_transaction *tsx, - pjsip_tx_data *tdata); +PJ_DECL(pj_status_t) pjsip_dlg_send_response( pjsip_dialog *dlg, + pjsip_transaction *tsx, + pjsip_tx_data *tdata); /** * This composite function sends response message statefully to an incoming * request message inside dialog. * - * @param dlg The endpoint instance. - * @param rdata The incoming request message. + * @param dlg The endpoint instance. + * @param rdata The incoming request message. * @param st_code Status code of the response. * @param st_text Optional status text of the response. * @param hdr_list Optional header list to be added to the response. - * @param body Optional message body to be added to the response. + * @param body Optional message body to be added to the response. * - * @return PJ_SUCCESS if response message has successfully been - * sent. + * @return PJ_SUCCESS if response message has successfully been + * sent. */ PJ_DECL(pj_status_t) pjsip_dlg_respond( pjsip_dialog *dlg, - pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - const pjsip_hdr *hdr_list, - const pjsip_msg_body *body ); + pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + const pjsip_hdr *hdr_list, + const pjsip_msg_body *body ); /** @@ -805,101 +804,101 @@ PJ_DECL(pj_status_t) pjsip_dlg_respond( pjsip_dialog *dlg, * case-sensitive, for example: "text/html" will not match * "text / html" (notice the spaces). * - * @param dlg The dialog. - * @param htype The header type to be checked, which value may be: - * - PJSIP_H_ACCEPT - * - PJSIP_H_ALLOW - * - PJSIP_H_SUPPORTED - * @param hname If htype specifies PJSIP_H_OTHER, then the header name - * must be supplied in this argument. Otherwise the value - * must be set to NULL. - * @param token The capability token to check. For example, if \a htype - * is PJSIP_H_ALLOW, then \a token specifies the method - * names; if \a htype is PJSIP_H_SUPPORTED, then \a token - * specifies the extension names such as "100rel". - * - * @return PJSIP_DIALOG_CAP_SUPPORTED if the specified capability - * is explicitly supported, see pjsip_dialog_cap_status - * for more info. + * @param dlg The dialog. + * @param htype The header type to be checked, which value may be: + * - PJSIP_H_ACCEPT + * - PJSIP_H_ALLOW + * - PJSIP_H_SUPPORTED + * @param hname If htype specifies PJSIP_H_OTHER, then the header name + * must be supplied in this argument. Otherwise the value + * must be set to NULL. + * @param token The capability token to check. For example, if \a htype + * is PJSIP_H_ALLOW, then \a token specifies the method + * names; if \a htype is PJSIP_H_SUPPORTED, then \a token + * specifies the extension names such as "100rel". + * + * @return PJSIP_DIALOG_CAP_SUPPORTED if the specified capability + * is explicitly supported, see pjsip_dialog_cap_status + * for more info. */ PJ_DECL(pjsip_dialog_cap_status) pjsip_dlg_remote_has_cap( - pjsip_dialog *dlg, - int htype, - const pj_str_t *hname, - const pj_str_t *token); + pjsip_dialog *dlg, + int htype, + const pj_str_t *hname, + const pj_str_t *token); /** * Get the specified capability header from the remote capability headers * stored in the dialog. * - * @param dlg The dialog. - * @param htype The header type to be retrieved, which value may be: - * - PJSIP_H_ACCEPT - * - PJSIP_H_ALLOW - * - PJSIP_H_SUPPORTED - * @param hname If htype specifies PJSIP_H_OTHER, then the header name - * must be supplied in this argument. Otherwise the value - * must be set to NULL. + * @param dlg The dialog. + * @param htype The header type to be retrieved, which value may be: + * - PJSIP_H_ACCEPT + * - PJSIP_H_ALLOW + * - PJSIP_H_SUPPORTED + * @param hname If htype specifies PJSIP_H_OTHER, then the header name + * must be supplied in this argument. Otherwise the value + * must be set to NULL. * - * @return The appropriate header, or NULL if the header is not - * available. + * @return The appropriate header, or NULL if the header is not + * available. */ PJ_DECL(const pjsip_hdr*) pjsip_dlg_get_remote_cap_hdr(pjsip_dialog *dlg, - int htype, - const pj_str_t *hname); + int htype, + const pj_str_t *hname); /** * Set remote capability from a SIP header containing array of capability * tags/values. * - * @param dlg The dialog. + * @param dlg The dialog. * @param cap_hdr The SIP header. * - * @return PJ_SUCCESS when successful, otherwise the appropriate - * error code will be returned. + * @return PJ_SUCCESS when successful, otherwise the appropriate + * error code will be returned. */ PJ_DECL(pj_status_t) pjsip_dlg_set_remote_cap_hdr( - pjsip_dialog *dlg, - const pjsip_generic_array_hdr *cap_hdr); + pjsip_dialog *dlg, + const pjsip_generic_array_hdr *cap_hdr); /** * Remove a remote capability header. * - * @param dlg The dialog. - * @param htype The header type to be removed, which value may be: - * - PJSIP_H_ACCEPT - * - PJSIP_H_ALLOW - * - PJSIP_H_SUPPORTED - * @param hname If htype specifies PJSIP_H_OTHER, then the header name - * must be supplied in this argument. Otherwise the value - * must be set to NULL. + * @param dlg The dialog. + * @param htype The header type to be removed, which value may be: + * - PJSIP_H_ACCEPT + * - PJSIP_H_ALLOW + * - PJSIP_H_SUPPORTED + * @param hname If htype specifies PJSIP_H_OTHER, then the header name + * must be supplied in this argument. Otherwise the value + * must be set to NULL. * - * @return PJ_SUCCESS when successful, otherwise the appropriate - * error code will be returned. + * @return PJ_SUCCESS when successful, otherwise the appropriate + * error code will be returned. */ PJ_DECL(pj_status_t) pjsip_dlg_remove_remote_cap_hdr(pjsip_dialog *dlg, - int htype, - const pj_str_t *hname); + int htype, + const pj_str_t *hname); /** * Update remote capabilities from a received message. The header types * to be updated from the message will only be \a PJSIP_H_ACCEPT, * \a PJSIP_H_ALLOW, and \a PJSIP_H_SUPPORTED. * - * @param dlg The dialog. - * @param msg The received message. + * @param dlg The dialog. + * @param msg The received message. * @param strict If this is set to PJ_TRUE, any header types missing - * from the message will cause removal of existing - * header types in the capability list. Otherwise, the - * capability list will not be modified when any header + * from the message will cause removal of existing + * header types in the capability list. Otherwise, the + * capability list will not be modified when any header * type is missing. * - * @return PJ_SUCCESS when successful, otherwise the appropriate - * error code will be returned. + * @return PJ_SUCCESS when successful, otherwise the appropriate + * error code will be returned. */ PJ_DECL(pj_status_t) pjsip_dlg_update_remote_cap(pjsip_dialog *dlg, - const pjsip_msg *msg, - pj_bool_t strict); + const pjsip_msg *msg, + pj_bool_t strict); @@ -913,21 +912,21 @@ PJ_DECL(pj_status_t) pjsip_dlg_update_remote_cap(pjsip_dialog *dlg, /** Internal: receives transaction event (called by user_agent module) */ void pjsip_dlg_on_tsx_state( pjsip_dialog *dlg, - pjsip_transaction *tsx, - pjsip_event *e ); + pjsip_transaction *tsx, + pjsip_event *e ); /** Internal */ void pjsip_dlg_on_rx_request( pjsip_dialog *dlg, - pjsip_rx_data *rdata ); + pjsip_rx_data *rdata ); /** Internal */ void pjsip_dlg_on_rx_response( pjsip_dialog *dlg, - pjsip_rx_data *rdata ); + pjsip_rx_data *rdata ); PJ_END_DECL -#endif /* __PJSIP_SIP_DIALOG_H__ */ +#endif /* __PJSIP_SIP_DIALOG_H__ */ diff --git a/pjsip/include/pjsip/sip_endpoint.h b/pjsip/include/pjsip/sip_endpoint.h index bd439dff66..620b23ee85 100644 --- a/pjsip/include/pjsip/sip_endpoint.h +++ b/pjsip/include/pjsip/sip_endpoint.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -75,7 +74,7 @@ typedef void (*pjsip_endpt_exit_callback)(pjsip_endpoint *endpt); * future memory allocations by SIP components will be taken from the same * pool factory. * - * @param pf Pool factory that will be used for the lifetime of + * @param pf Pool factory that will be used for the lifetime of * endpoint. * @param name Optional name to be specified for the endpoint. * If this parameter is NULL, then the name will use @@ -85,7 +84,7 @@ typedef void (*pjsip_endpt_exit_callback)(pjsip_endpoint *endpt); * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_endpt_create(pj_pool_factory *pf, - const char *name, + const char *name, pjsip_endpoint **endpt); /** @@ -93,7 +92,7 @@ PJ_DECL(pj_status_t) pjsip_endpt_create(pj_pool_factory *pf, * transactions have been terminated properly, because this function does not * check for the presence of pending transactions. * - * @param endpt The SIP endpoint to be destroyed. + * @param endpt The SIP endpoint to be destroyed. */ PJ_DECL(void) pjsip_endpt_destroy(pjsip_endpoint *endpt); @@ -113,31 +112,31 @@ PJ_DECL(const pj_str_t*) pjsip_endpt_name(const pjsip_endpoint *endpt); * manner. This function, like all other endpoint functions, is thread safe, * and application may have more than one thread concurrently calling this function. * - * @param endpt The endpoint. - * @param max_timeout Maximum time to wait for events, or NULL to wait forever - * until event is received. + * @param endpt The endpoint. + * @param max_timeout Maximum time to wait for events, or NULL to wait forever + * until event is received. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_endpt_handle_events( pjsip_endpoint *endpt, - const pj_time_val *max_timeout); + const pj_time_val *max_timeout); /** * Handle events with additional info about number of events that * have been handled. * - * @param endpt The endpoint. - * @param max_timeout Maximum time to wait for events, or NULL to wait forever - * until event is received. - * @param count Optional argument to receive the number of events that - * have been handled by the function. + * @param endpt The endpoint. + * @param max_timeout Maximum time to wait for events, or NULL to wait forever + * until event is received. + * @param count Optional argument to receive the number of events that + * have been handled by the function. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_endpt_handle_events2(pjsip_endpoint *endpt, - const pj_time_val *max_timeout, - unsigned *count); + const pj_time_val *max_timeout, + unsigned *count); /** * Schedule timer to endpoint's timer heap. Application must poll the endpoint @@ -146,25 +145,25 @@ PJ_DECL(pj_status_t) pjsip_endpt_handle_events2(pjsip_endpoint *endpt, * has elapsed, the callback specified in the entry argument will be called. * This function, like all other endpoint functions, is thread safe. * - * @param endpt The endpoint. - * @param entry The timer entry. - * @param delay The relative delay of the timer. - * @return PJ_OK (zero) if successfull. + * @param endpt The endpoint. + * @param entry The timer entry. + * @param delay The relative delay of the timer. + * @return PJ_OK (zero) if successfull. */ #if PJ_TIMER_DEBUG #define pjsip_endpt_schedule_timer(ept,ent,d) \ - pjsip_endpt_schedule_timer_dbg(ept, ent, d, \ - __FILE__, __LINE__) + pjsip_endpt_schedule_timer_dbg(ept, ent, d, \ + __FILE__, __LINE__) PJ_DECL(pj_status_t) pjsip_endpt_schedule_timer_dbg(pjsip_endpoint *endpt, - pj_timer_entry *entry, - const pj_time_val *delay, - const char *src_file, - int src_line); + pj_timer_entry *entry, + const pj_time_val *delay, + const char *src_file, + int src_line); #else PJ_DECL(pj_status_t) pjsip_endpt_schedule_timer( pjsip_endpoint *endpt, - pj_timer_entry *entry, - const pj_time_val *delay ); + pj_timer_entry *entry, + const pj_time_val *delay ); #endif /** @@ -175,52 +174,52 @@ PJ_DECL(pj_status_t) pjsip_endpt_schedule_timer( pjsip_endpoint *endpt, * argument will be called. This function, like all other endpoint functions, * is thread safe. * - * @param endpt The endpoint. - * @param entry The timer entry. - * @param delay The relative delay of the timer. + * @param endpt The endpoint. + * @param entry The timer entry. + * @param delay The relative delay of the timer. * @param id_val The value to be set to the "id" field of the timer entry - * once the timer is scheduled. + * once the timer is scheduled. * @param grp_lock The group lock. - * @return PJ_OK (zero) if successfull. + * @return PJ_OK (zero) if successfull. */ #if PJ_TIMER_DEBUG #define pjsip_endpt_schedule_timer_w_grp_lock(ept,ent,d,id,gl) \ - pjsip_endpt_schedule_timer_w_grp_lock_dbg(ept,ent,d,id,gl,\ - __FILE__, __LINE__) + pjsip_endpt_schedule_timer_w_grp_lock_dbg(ept,ent,d,id,gl,\ + __FILE__, __LINE__) PJ_DECL(pj_status_t) pjsip_endpt_schedule_timer_w_grp_lock_dbg( - pjsip_endpoint *endpt, - pj_timer_entry *entry, - const pj_time_val *delay, - int id_val, - pj_grp_lock_t *grp_lock, - const char *src_file, - int src_line); + pjsip_endpoint *endpt, + pj_timer_entry *entry, + const pj_time_val *delay, + int id_val, + pj_grp_lock_t *grp_lock, + const char *src_file, + int src_line); #else PJ_DECL(pj_status_t) pjsip_endpt_schedule_timer_w_grp_lock( - pjsip_endpoint *endpt, - pj_timer_entry *entry, - const pj_time_val *delay, - int id_val, - pj_grp_lock_t *grp_lock ); + pjsip_endpoint *endpt, + pj_timer_entry *entry, + const pj_time_val *delay, + int id_val, + pj_grp_lock_t *grp_lock ); #endif /** * Cancel the previously registered timer. * This function, like all other endpoint functions, is thread safe. * - * @param endpt The endpoint. - * @param entry The timer entry previously registered. + * @param endpt The endpoint. + * @param entry The timer entry previously registered. */ PJ_DECL(void) pjsip_endpt_cancel_timer( pjsip_endpoint *endpt, - pj_timer_entry *entry ); + pj_timer_entry *entry ); /** * Get the timer heap instance of the SIP endpoint. * - * @param endpt The endpoint. + * @param endpt The endpoint. * - * @return The timer heap instance. + * @return The timer heap instance. */ PJ_DECL(pj_timer_heap_t*) pjsip_endpt_get_timer_heap(pjsip_endpoint *endpt); @@ -231,26 +230,26 @@ PJ_DECL(pj_timer_heap_t*) pjsip_endpt_get_timer_heap(pjsip_endpoint *endpt); * properly initialize the module, and assign a unique module ID for the * module. * - * @param endpt The endpoint. - * @param module The module to be registered. + * @param endpt The endpoint. + * @param module The module to be registered. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_endpt_register_module( pjsip_endpoint *endpt, - pjsip_module *module ); + pjsip_module *module ); /** * Unregister a module from the endpoint. * The endpoint will then call the stop and unload function in the module to * properly shutdown the module. * - * @param endpt The endpoint. - * @param module The module to be registered. + * @param endpt The endpoint. + * @param module The module to be registered. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_endpt_unregister_module( pjsip_endpoint *endpt, - pjsip_module *module ); + pjsip_module *module ); /** * This describes additional parameters to pjsip_endpt_process_rx_data() @@ -292,7 +291,7 @@ typedef struct pjsip_process_rdata_param /** * Initialize with default. * - * @param p The param. + * @param p The param. */ PJ_DECL(void) pjsip_process_rdata_param_default(pjsip_process_rdata_param *p); @@ -309,15 +308,15 @@ PJ_DECL(void) pjsip_process_rdata_param_default(pjsip_process_rdata_param *p); * long operation, it resumes pjsip's module processing by calling this * function, and then free the cloned rdata. * - * @param endpt The endpoint instance. - * @param rdata The rdata to be distributed. - * @param p Optional pointer to param to specify from which module - * the processing should start. - * @param p_handled Optional pointer to receive last return value of - * module's \a on_rx_request() or \a on_rx_response() - * callback. + * @param endpt The endpoint instance. + * @param rdata The rdata to be distributed. + * @param p Optional pointer to param to specify from which module + * the processing should start. + * @param p_handled Optional pointer to receive last return value of + * module's \a on_rx_request() or \a on_rx_response() + * callback. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_endpt_process_rx_data(pjsip_endpoint *endpt, pjsip_rx_data *rdata, @@ -330,73 +329,73 @@ PJ_DECL(pj_status_t) pjsip_endpt_process_rx_data(pjsip_endpoint *endpt, * allocated from the same pool factory. This function, like all other endpoint * functions, is thread safe. * - * @param endpt The SIP endpoint. - * @param pool_name Name to be assigned to the pool. - * @param initial The initial size of the pool. - * @param increment The resize size. - * @return Memory pool, or NULL on failure. + * @param endpt The SIP endpoint. + * @param pool_name Name to be assigned to the pool. + * @param initial The initial size of the pool. + * @param increment The resize size. + * @return Memory pool, or NULL on failure. * * @see pj_pool_create */ PJ_DECL(pj_pool_t*) pjsip_endpt_create_pool( pjsip_endpoint *endpt, - const char *pool_name, - pj_size_t initial, - pj_size_t increment ); + const char *pool_name, + pj_size_t initial, + pj_size_t increment ); /** * Return back pool to endpoint to be released back to the pool factory. * This function, like all other endpoint functions, is thread safe. * - * @param endpt The endpoint. - * @param pool The pool to be destroyed. + * @param endpt The endpoint. + * @param pool The pool to be destroyed. */ PJ_DECL(void) pjsip_endpt_release_pool( pjsip_endpoint *endpt, - pj_pool_t *pool ); + pj_pool_t *pool ); /** * Find transaction in endpoint's transaction table by the transaction's key. * This function normally is only used by modules. The key for a transaction * can be created by calling #pjsip_tsx_create_key. * - * @param endpt The endpoint instance. - * @param key Transaction key, as created with #pjsip_tsx_create_key. + * @param endpt The endpoint instance. + * @param key Transaction key, as created with #pjsip_tsx_create_key. * - * @return The transaction, or NULL if it's not found. + * @return The transaction, or NULL if it's not found. */ PJ_DECL(pjsip_transaction*) pjsip_endpt_find_tsx( pjsip_endpoint *endpt, - const pj_str_t *key ); + const pj_str_t *key ); /** * Register the transaction to the endpoint's transaction table. * This function should only be used internally by the stack. * - * @param endpt The SIP endpoint. - * @param tsx The transaction. + * @param endpt The SIP endpoint. + * @param tsx The transaction. */ PJ_DECL(void) pjsip_endpt_register_tsx( pjsip_endpoint *endpt, - pjsip_transaction *tsx); + pjsip_transaction *tsx); /** * Forcefull destroy the transaction. This function should only be used * internally by the stack. * - * @param endpt The endpoint. - * @param tsx The transaction to destroy. + * @param endpt The endpoint. + * @param tsx The transaction to destroy. */ PJ_DECL(void) pjsip_endpt_destroy_tsx( pjsip_endpoint *endpt, - pjsip_transaction *tsx); + pjsip_transaction *tsx); /** * Create a new transmit data buffer. * This function, like all other endpoint functions, is thread safe. * - * @param endpt The endpoint. + * @param endpt The endpoint. * @param p_tdata Pointer to receive transmit data buffer. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_endpt_create_tdata( pjsip_endpoint *endpt, - pjsip_tx_data **p_tdata); + pjsip_tx_data **p_tdata); /** * Create the DNS resolver instance. Application creates the DNS @@ -404,14 +403,14 @@ PJ_DECL(pj_status_t) pjsip_endpt_create_tdata( pjsip_endpoint *endpt, * resolver, then set the DNS resolver to be used by the endpoint * by calling #pjsip_endpt_set_resolver(). * - * @param endpt The SIP endpoint instance. - * @param p_resv Pointer to receive the DNS resolver instance. + * @param endpt The SIP endpoint instance. + * @param p_resv Pointer to receive the DNS resolver instance. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjsip_endpt_create_resolver(pjsip_endpoint *endpt, - pj_dns_resolver **p_resv); + pj_dns_resolver **p_resv); /** * Set DNS resolver to be used by the SIP resolver. Application can set @@ -419,15 +418,15 @@ PJ_DECL(pj_status_t) pjsip_endpt_create_resolver(pjsip_endpoint *endpt, * temporarily). When DNS resolver is disabled, the endpoint will resolve * hostnames with the normal pj_gethostbyname() function. * - * @param endpt The SIP endpoint instance. - * @param resv The resolver instance to be used by the SIP - * endpoint. + * @param endpt The SIP endpoint instance. + * @param resv The resolver instance to be used by the SIP + * endpoint. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjsip_endpt_set_resolver(pjsip_endpoint *endpt, - pj_dns_resolver *resv); + pj_dns_resolver *resv); /** * Set the DNS external resolver implementation to use in the SIP resolver. @@ -439,21 +438,21 @@ PJ_DECL(pj_status_t) pjsip_endpt_set_resolver(pjsip_endpoint *endpt, * * @param endpt The SIP resolver engine. * @param ext_res The external resolver implementation callback. This argument - * can be NULL to reset the whole external implementation. - * However, it is prohibited to reset individual callback. + * can be NULL to reset the whole external implementation. + * However, it is prohibited to reset individual callback. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_endpt_set_ext_resolver(pjsip_endpoint *endpt, - pjsip_ext_resolver *ext_res); + pjsip_ext_resolver *ext_res); /** * Get the DNS resolver being used by the SIP resolver. * - * @param endpt The SIP endpoint instance. + * @param endpt The SIP endpoint instance. * - * @return The DNS resolver instance currently being used - * by the SIP endpoint. + * @return The DNS resolver instance currently being used + * by the SIP endpoint. */ PJ_DECL(pj_dns_resolver*) pjsip_endpt_get_resolver(pjsip_endpoint *endpt); @@ -462,33 +461,33 @@ PJ_DECL(pj_dns_resolver*) pjsip_endpt_get_resolver(pjsip_endpoint *endpt); * specified in RFC 3263 (Locating SIP Servers). When the resolving operation * has completed, the callback will be called. * - * @param endpt The endpoint instance. - * @param pool The pool to allocate resolver job. + * @param endpt The endpoint instance. + * @param pool The pool to allocate resolver job. * @param target The target specification to be resolved. - * @param token A user defined token to be passed back to callback function. - * @param cb The callback function. + * @param token A user defined token to be passed back to callback function. + * @param cb The callback function. */ PJ_DECL(void) pjsip_endpt_resolve( pjsip_endpoint *endpt, - pj_pool_t *pool, - pjsip_host_info *target, - void *token, - pjsip_resolver_callback *cb); + pj_pool_t *pool, + pjsip_host_info *target, + void *token, + pjsip_resolver_callback *cb); /** * Get transport manager instance. * - * @param endpt The endpoint. + * @param endpt The endpoint. * - * @return Transport manager instance. + * @return Transport manager instance. */ PJ_DECL(pjsip_tpmgr*) pjsip_endpt_get_tpmgr(pjsip_endpoint *endpt); /** * Get ioqueue instance. * - * @param endpt The endpoint. + * @param endpt The endpoint. * - * @return The ioqueue. + * @return The ioqueue. */ PJ_DECL(pj_ioqueue_t*) pjsip_endpt_get_ioqueue(pjsip_endpoint *endpt); @@ -500,23 +499,23 @@ PJ_DECL(pj_ioqueue_t*) pjsip_endpt_get_ioqueue(pjsip_endpoint *endpt); * * @see pjsip_tpmgr_acquire_transport * - * @param endpt The SIP endpoint instance. - * @param type The type of transport to be acquired. + * @param endpt The SIP endpoint instance. + * @param type The type of transport to be acquired. * @param remote The remote address to send message to. * @param addr_len Length of the remote address. - * @param sel Optional pointer to transport selector instance which is - * used to find explicit transport, if required. - * @param p_tp Pointer to receive the transport instance, if one is found. + * @param sel Optional pointer to transport selector instance which is + * used to find explicit transport, if required. + * @param p_tp Pointer to receive the transport instance, if one is found. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_endpt_acquire_transport( pjsip_endpoint *endpt, - pjsip_transport_type_e type, - const pj_sockaddr_t *remote, - int addr_len, - const pjsip_tpselector *sel, - pjsip_transport **p_tp); + pjsip_transport_type_e type, + const pj_sockaddr_t *remote, + int addr_len, + const pjsip_tpselector *sel, + pjsip_transport **p_tp); /** @@ -527,25 +526,25 @@ pjsip_endpt_acquire_transport( pjsip_endpoint *endpt, * * @see pjsip_tpmgr_acquire_transport * - * @param endpt The SIP endpoint instance. - * @param type The type of transport to be acquired. + * @param endpt The SIP endpoint instance. + * @param type The type of transport to be acquired. * @param remote The remote address to send message to. * @param addr_len Length of the remote address. - * @param sel Optional pointer to transport selector instance which is - * used to find explicit transport, if required. - * @param tdata Optional pointer to SIP message data to be sent. - * @param p_tp Pointer to receive the transport instance, if one is found. + * @param sel Optional pointer to transport selector instance which is + * used to find explicit transport, if required. + * @param tdata Optional pointer to SIP message data to be sent. + * @param p_tp Pointer to receive the transport instance, if one is found. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_endpt_acquire_transport2(pjsip_endpoint *endpt, - pjsip_transport_type_e type, - const pj_sockaddr_t *remote, - int addr_len, - const pjsip_tpselector *sel, - pjsip_tx_data *tdata, - pjsip_transport **p_tp); + pjsip_transport_type_e type, + const pj_sockaddr_t *remote, + int addr_len, + const pjsip_tpselector *sel, + pjsip_tx_data *tdata, + pjsip_transport **p_tp); /***************************************************************************** @@ -567,82 +566,82 @@ pjsip_endpt_acquire_transport2(pjsip_endpoint *endpt, /** * Get the value of the specified capability header field. * - * @param endpt The endpoint. - * @param htype The header type to be retrieved, which value may be: - * - PJSIP_H_ACCEPT - * - PJSIP_H_ALLOW - * - PJSIP_H_SUPPORTED - * @param hname If htype specifies PJSIP_H_OTHER, then the header name - * must be supplied in this argument. Otherwise the value - * must be set to NULL. + * @param endpt The endpoint. + * @param htype The header type to be retrieved, which value may be: + * - PJSIP_H_ACCEPT + * - PJSIP_H_ALLOW + * - PJSIP_H_SUPPORTED + * @param hname If htype specifies PJSIP_H_OTHER, then the header name + * must be supplied in this argument. Otherwise the value + * must be set to NULL. * - * @return The appropriate header, or NULL if the header is not - * available. + * @return The appropriate header, or NULL if the header is not + * available. */ PJ_DECL(const pjsip_hdr*) pjsip_endpt_get_capability( pjsip_endpoint *endpt, - int htype, - const pj_str_t *hname); + int htype, + const pj_str_t *hname); /** * Check if we have the specified capability. * - * @param endpt The endpoint. - * @param htype The header type to be retrieved, which value may be: - * - PJSIP_H_ACCEPT - * - PJSIP_H_ALLOW - * - PJSIP_H_SUPPORTED - * @param hname If htype specifies PJSIP_H_OTHER, then the header name - * must be supplied in this argument. Otherwise the value - * must be set to NULL. - * @param token The capability token to check. For example, if \a htype - * is PJSIP_H_ALLOW, then \a token specifies the method - * names; if \a htype is PJSIP_H_SUPPORTED, then \a token - * specifies the extension names such as "100rel". - * - * @return PJ_TRUE if the specified capability is supported, - * otherwise PJ_FALSE.. + * @param endpt The endpoint. + * @param htype The header type to be retrieved, which value may be: + * - PJSIP_H_ACCEPT + * - PJSIP_H_ALLOW + * - PJSIP_H_SUPPORTED + * @param hname If htype specifies PJSIP_H_OTHER, then the header name + * must be supplied in this argument. Otherwise the value + * must be set to NULL. + * @param token The capability token to check. For example, if \a htype + * is PJSIP_H_ALLOW, then \a token specifies the method + * names; if \a htype is PJSIP_H_SUPPORTED, then \a token + * specifies the extension names such as "100rel". + * + * @return PJ_TRUE if the specified capability is supported, + * otherwise PJ_FALSE.. */ PJ_DECL(pj_bool_t) pjsip_endpt_has_capability( pjsip_endpoint *endpt, - int htype, - const pj_str_t *hname, - const pj_str_t *token); + int htype, + const pj_str_t *hname, + const pj_str_t *token); /** * Add or register new capabilities as indicated by the tags to the * appropriate header fields in the endpoint. * - * @param endpt The endpoint. - * @param mod The module which registers the capability. - * @param htype The header type to be set, which value may be: - * - PJSIP_H_ACCEPT - * - PJSIP_H_ALLOW - * - PJSIP_H_SUPPORTED - * @param hname If htype specifies PJSIP_H_OTHER, then the header name - * must be supplied in this argument. Otherwise the value - * must be set to NULL. - * @param count The number of tags in the array. The value must not - * be greater than PJSIP_GENERIC_ARRAY_MAX_COUNT. - * @param tags Array of tags describing the capabilities or extensions - * to be added to the appropriate header. - * - * @return PJ_SUCCESS on success. + * @param endpt The endpoint. + * @param mod The module which registers the capability. + * @param htype The header type to be set, which value may be: + * - PJSIP_H_ACCEPT + * - PJSIP_H_ALLOW + * - PJSIP_H_SUPPORTED + * @param hname If htype specifies PJSIP_H_OTHER, then the header name + * must be supplied in this argument. Otherwise the value + * must be set to NULL. + * @param count The number of tags in the array. The value must not + * be greater than PJSIP_GENERIC_ARRAY_MAX_COUNT. + * @param tags Array of tags describing the capabilities or extensions + * to be added to the appropriate header. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_endpt_add_capability( pjsip_endpoint *endpt, - pjsip_module *mod, - int htype, - const pj_str_t *hname, - unsigned count, - const pj_str_t tags[]); + pjsip_module *mod, + int htype, + const pj_str_t *hname, + unsigned count, + const pj_str_t tags[]); /** * Get list of additional headers to be put in outgoing request message. * Currently only Max-Forwards are defined. * - * @param e The endpoint. + * @param e The endpoint. * - * @return List of headers. + * @return List of headers. */ PJ_DECL(const pjsip_hdr*) pjsip_endpt_get_request_headers(pjsip_endpoint *e); @@ -651,10 +650,10 @@ PJ_DECL(const pjsip_hdr*) pjsip_endpt_get_request_headers(pjsip_endpoint *e); * Dump endpoint status to the log. This will print the status to the log * with log level 3. * - * @param endpt The endpoint. - * @param detail If non zero, then it will dump a detailed output. - * BEWARE that this option may crash the system because - * it tries to access all memory pools. + * @param endpt The endpoint. + * @param detail If non zero, then it will dump a detailed output. + * BEWARE that this option may crash the system because + * it tries to access all memory pools. */ PJ_DECL(void) pjsip_endpt_dump( pjsip_endpoint *endpt, pj_bool_t detail ); @@ -666,13 +665,13 @@ PJ_DECL(void) pjsip_endpt_dump( pjsip_endpoint *endpt, pj_bool_t detail ); * from within the callback as such resource may have been released when * the callback function is invoked. * - * @param endpt The SIP endpoint. - * @param func The function to be registered. + * @param endpt The SIP endpoint. + * @param func The function to be registered. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_endpt_atexit(pjsip_endpoint *endpt, - pjsip_endpt_exit_callback func); + pjsip_endpt_exit_callback func); /** @@ -684,7 +683,7 @@ PJ_DECL(pj_status_t) pjsip_endpt_atexit(pjsip_endpoint *endpt, * Log an error. */ PJ_DECL(void) pjsip_endpt_log_error( pjsip_endpoint *endpt, - const char *sender, + const char *sender, pj_status_t error_code, const char *format, ... ); @@ -711,5 +710,5 @@ void pjsip_endpt_send_tsx_event( pjsip_endpoint *endpt, pjsip_event *evt ); PJ_END_DECL -#endif /* __PJSIP_SIP_ENDPOINT_H__ */ +#endif /* __PJSIP_SIP_ENDPOINT_H__ */ diff --git a/pjsip/include/pjsip/sip_errno.h b/pjsip/include/pjsip/sip_errno.h index afcecc4b05..5053bb04fa 100644 --- a/pjsip/include/pjsip/sip_errno.h +++ b/pjsip/include/pjsip/sip_errno.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -80,27 +79,27 @@ PJ_BEGIN_DECL * @hideinitializer * SIP object is busy. */ -#define PJSIP_EBUSY (PJSIP_ERRNO_START_PJSIP + 1) /* 171001 */ +#define PJSIP_EBUSY (PJSIP_ERRNO_START_PJSIP + 1) /* 171001 */ /** * @hideinitializer * SIP object with the same type already exists. */ -#define PJSIP_ETYPEEXISTS (PJSIP_ERRNO_START_PJSIP + 2) /* 171002 */ +#define PJSIP_ETYPEEXISTS (PJSIP_ERRNO_START_PJSIP + 2) /* 171002 */ /** * @hideinitializer * SIP stack is shutting down. */ -#define PJSIP_ESHUTDOWN (PJSIP_ERRNO_START_PJSIP + 3) /* 171003 */ +#define PJSIP_ESHUTDOWN (PJSIP_ERRNO_START_PJSIP + 3) /* 171003 */ /** * @hideinitializer * SIP object is not initialized. */ -#define PJSIP_ENOTINITIALIZED (PJSIP_ERRNO_START_PJSIP + 4) /* 171004 */ +#define PJSIP_ENOTINITIALIZED (PJSIP_ERRNO_START_PJSIP + 4) /* 171004 */ /** * @hideinitializer * Missing route set (for tel: URI) */ -#define PJSIP_ENOROUTESET (PJSIP_ERRNO_START_PJSIP + 5) /* 171005 */ +#define PJSIP_ENOROUTESET (PJSIP_ERRNO_START_PJSIP + 5) /* 171005 */ /************************************************************ @@ -110,90 +109,90 @@ PJ_BEGIN_DECL * @hideinitializer * General invalid message error (e.g. syntax error) */ -#define PJSIP_EINVALIDMSG (PJSIP_ERRNO_START_PJSIP + 20) /* 171020 */ +#define PJSIP_EINVALIDMSG (PJSIP_ERRNO_START_PJSIP + 20) /* 171020 */ /** * @hideinitializer * Expecting request message. */ -#define PJSIP_ENOTREQUESTMSG (PJSIP_ERRNO_START_PJSIP + 21) /* 171021 */ +#define PJSIP_ENOTREQUESTMSG (PJSIP_ERRNO_START_PJSIP + 21) /* 171021 */ /** * @hideinitializer * Expecting response message. */ -#define PJSIP_ENOTRESPONSEMSG (PJSIP_ERRNO_START_PJSIP + 22) /* 171022 */ +#define PJSIP_ENOTRESPONSEMSG (PJSIP_ERRNO_START_PJSIP + 22) /* 171022 */ /** * @hideinitializer * Message too long. See also PJSIP_ERXOVERFLOW. */ -#define PJSIP_EMSGTOOLONG (PJSIP_ERRNO_START_PJSIP + 23) /* 171023 */ +#define PJSIP_EMSGTOOLONG (PJSIP_ERRNO_START_PJSIP + 23) /* 171023 */ /** * @hideinitializer * Message not completely received. */ -#define PJSIP_EPARTIALMSG (PJSIP_ERRNO_START_PJSIP + 24) /* 171024 */ +#define PJSIP_EPARTIALMSG (PJSIP_ERRNO_START_PJSIP + 24) /* 171024 */ /** * @hideinitializer * Status code is invalid. */ -#define PJSIP_EINVALIDSTATUS (PJSIP_ERRNO_START_PJSIP + 30) /* 171030 */ +#define PJSIP_EINVALIDSTATUS (PJSIP_ERRNO_START_PJSIP + 30) /* 171030 */ /** * @hideinitializer * General Invalid URI error. */ -#define PJSIP_EINVALIDURI (PJSIP_ERRNO_START_PJSIP + 39) /* 171039 */ +#define PJSIP_EINVALIDURI (PJSIP_ERRNO_START_PJSIP + 39) /* 171039 */ /** * @hideinitializer * Unsupported URL scheme. */ -#define PJSIP_EINVALIDSCHEME (PJSIP_ERRNO_START_PJSIP + 40) /* 171040 */ +#define PJSIP_EINVALIDSCHEME (PJSIP_ERRNO_START_PJSIP + 40) /* 171040 */ /** * @hideinitializer * Missing Request-URI. */ -#define PJSIP_EMISSINGREQURI (PJSIP_ERRNO_START_PJSIP + 41) /* 171041 */ +#define PJSIP_EMISSINGREQURI (PJSIP_ERRNO_START_PJSIP + 41) /* 171041 */ /** * @hideinitializer * Invalid request URI. */ -#define PJSIP_EINVALIDREQURI (PJSIP_ERRNO_START_PJSIP + 42) /* 171042 */ +#define PJSIP_EINVALIDREQURI (PJSIP_ERRNO_START_PJSIP + 42) /* 171042 */ /** * @hideinitializer * URI is too long. */ -#define PJSIP_EURITOOLONG (PJSIP_ERRNO_START_PJSIP + 43) /* 171043 */ +#define PJSIP_EURITOOLONG (PJSIP_ERRNO_START_PJSIP + 43) /* 171043 */ /** * @hideinitializer * Missing required header(s). */ -#define PJSIP_EMISSINGHDR (PJSIP_ERRNO_START_PJSIP + 50) /* 171050 */ +#define PJSIP_EMISSINGHDR (PJSIP_ERRNO_START_PJSIP + 50) /* 171050 */ /** * @hideinitializer * Invalid header field. */ -#define PJSIP_EINVALIDHDR (PJSIP_ERRNO_START_PJSIP + 51) /* 171051 */ +#define PJSIP_EINVALIDHDR (PJSIP_ERRNO_START_PJSIP + 51) /* 171051 */ /** * @hideinitializer * Invalid Via header in response (sent-by, etc). */ -#define PJSIP_EINVALIDVIA (PJSIP_ERRNO_START_PJSIP + 52) /* 171052 */ +#define PJSIP_EINVALIDVIA (PJSIP_ERRNO_START_PJSIP + 52) /* 171052 */ /** * @hideinitializer * Multiple Via headers in response. */ -#define PJSIP_EMULTIPLEVIA (PJSIP_ERRNO_START_PJSIP + 53) /* 171053 */ +#define PJSIP_EMULTIPLEVIA (PJSIP_ERRNO_START_PJSIP + 53) /* 171053 */ /** * @hideinitializer * Missing message body. */ -#define PJSIP_EMISSINGBODY (PJSIP_ERRNO_START_PJSIP + 54) /* 171054 */ +#define PJSIP_EMISSINGBODY (PJSIP_ERRNO_START_PJSIP + 54) /* 171054 */ /** * @hideinitializer * Invalid/unexpected method. */ -#define PJSIP_EINVALIDMETHOD (PJSIP_ERRNO_START_PJSIP + 55) /* 171055 */ +#define PJSIP_EINVALIDMETHOD (PJSIP_ERRNO_START_PJSIP + 55) /* 171055 */ /************************************************************ @@ -203,23 +202,23 @@ PJ_BEGIN_DECL * @hideinitializer * Unsupported transport type. */ -#define PJSIP_EUNSUPTRANSPORT (PJSIP_ERRNO_START_PJSIP + 60) /* 171060 */ +#define PJSIP_EUNSUPTRANSPORT (PJSIP_ERRNO_START_PJSIP + 60) /* 171060 */ /** * @hideinitializer * Buffer is being sent, operation still pending. */ -#define PJSIP_EPENDINGTX (PJSIP_ERRNO_START_PJSIP + 61) /* 171061 */ +#define PJSIP_EPENDINGTX (PJSIP_ERRNO_START_PJSIP + 61) /* 171061 */ /** * @hideinitializer * Rx buffer overflow. See also PJSIP_EMSGTOOLONG. */ -#define PJSIP_ERXOVERFLOW (PJSIP_ERRNO_START_PJSIP + 62) /* 171062 */ +#define PJSIP_ERXOVERFLOW (PJSIP_ERRNO_START_PJSIP + 62) /* 171062 */ /** * @hideinitializer * This is not really an error, it just informs application that * transmit data has been deleted on return of pjsip_tx_data_dec_ref(). */ -#define PJSIP_EBUFDESTROYED (PJSIP_ERRNO_START_PJSIP + 63) /* 171063 */ +#define PJSIP_EBUFDESTROYED (PJSIP_ERRNO_START_PJSIP + 63) /* 171063 */ /** * @hideinitializer * Unsuitable transport selected. This error occurs when application @@ -227,14 +226,14 @@ PJ_BEGIN_DECL * but the selected transport is not suitable to send request to * the specified destination. */ -#define PJSIP_ETPNOTSUITABLE (PJSIP_ERRNO_START_PJSIP + 64) /* 171064 */ +#define PJSIP_ETPNOTSUITABLE (PJSIP_ERRNO_START_PJSIP + 64) /* 171064 */ /** * @hideinitializer * Transport not available. This error occurs for example when the SIP stack * is trying to use a SIP transport while the transport is being paused by * application. */ -#define PJSIP_ETPNOTAVAIL (PJSIP_ERRNO_START_PJSIP + 65) /* 171065 */ +#define PJSIP_ETPNOTAVAIL (PJSIP_ERRNO_START_PJSIP + 65) /* 171065 */ /************************************************************ * TRANSACTION ERRORS @@ -243,12 +242,12 @@ PJ_BEGIN_DECL * @hideinitializer * Transaction has just been destroyed. */ -#define PJSIP_ETSXDESTROYED (PJSIP_ERRNO_START_PJSIP + 70) /* 171070 */ +#define PJSIP_ETSXDESTROYED (PJSIP_ERRNO_START_PJSIP + 70) /* 171070 */ /** * @hideinitializer * No transaction. */ -#define PJSIP_ENOTSX (PJSIP_ERRNO_START_PJSIP + 71) /* 171071 */ +#define PJSIP_ENOTSX (PJSIP_ERRNO_START_PJSIP + 71) /* 171071 */ /************************************************************ @@ -258,62 +257,62 @@ PJ_BEGIN_DECL * @hideinitializer * Scheme mismatch. */ -#define PJSIP_ECMPSCHEME (PJSIP_ERRNO_START_PJSIP + 80) /* 171080 */ +#define PJSIP_ECMPSCHEME (PJSIP_ERRNO_START_PJSIP + 80) /* 171080 */ /** * @hideinitializer * User part mismatch. */ -#define PJSIP_ECMPUSER (PJSIP_ERRNO_START_PJSIP + 81) /* 171081 */ +#define PJSIP_ECMPUSER (PJSIP_ERRNO_START_PJSIP + 81) /* 171081 */ /** * @hideinitializer * Password part mismatch. */ -#define PJSIP_ECMPPASSWD (PJSIP_ERRNO_START_PJSIP + 82) /* 171082 */ +#define PJSIP_ECMPPASSWD (PJSIP_ERRNO_START_PJSIP + 82) /* 171082 */ /** * @hideinitializer * Host part mismatch. */ -#define PJSIP_ECMPHOST (PJSIP_ERRNO_START_PJSIP + 83) /* 171083 */ +#define PJSIP_ECMPHOST (PJSIP_ERRNO_START_PJSIP + 83) /* 171083 */ /** * @hideinitializer * Port part mismatch. */ -#define PJSIP_ECMPPORT (PJSIP_ERRNO_START_PJSIP + 84) /* 171084 */ +#define PJSIP_ECMPPORT (PJSIP_ERRNO_START_PJSIP + 84) /* 171084 */ /** * @hideinitializer * Transport parameter part mismatch. */ -#define PJSIP_ECMPTRANSPORTPRM (PJSIP_ERRNO_START_PJSIP + 85) /* 171085 */ +#define PJSIP_ECMPTRANSPORTPRM (PJSIP_ERRNO_START_PJSIP + 85) /* 171085 */ /** * @hideinitializer * TTL parameter part mismatch. */ -#define PJSIP_ECMPTTLPARAM (PJSIP_ERRNO_START_PJSIP + 86) /* 171086 */ +#define PJSIP_ECMPTTLPARAM (PJSIP_ERRNO_START_PJSIP + 86) /* 171086 */ /** * @hideinitializer * User parameter part mismatch. */ -#define PJSIP_ECMPUSERPARAM (PJSIP_ERRNO_START_PJSIP + 87) /* 171087 */ +#define PJSIP_ECMPUSERPARAM (PJSIP_ERRNO_START_PJSIP + 87) /* 171087 */ /** * @hideinitializer * Method parameter part mismatch. */ -#define PJSIP_ECMPMETHODPARAM (PJSIP_ERRNO_START_PJSIP + 88) /* 171088 */ +#define PJSIP_ECMPMETHODPARAM (PJSIP_ERRNO_START_PJSIP + 88) /* 171088 */ /** * @hideinitializer * Maddr parameter part mismatch. */ -#define PJSIP_ECMPMADDRPARAM (PJSIP_ERRNO_START_PJSIP + 89) /* 171089 */ +#define PJSIP_ECMPMADDRPARAM (PJSIP_ERRNO_START_PJSIP + 89) /* 171089 */ /** * @hideinitializer * Parameter part in other_param mismatch. */ -#define PJSIP_ECMPOTHERPARAM (PJSIP_ERRNO_START_PJSIP + 90) /* 171090 */ +#define PJSIP_ECMPOTHERPARAM (PJSIP_ERRNO_START_PJSIP + 90) /* 171090 */ /** * @hideinitializer * Parameter part in header_param mismatch. */ -#define PJSIP_ECMPHEADERPARAM (PJSIP_ERRNO_START_PJSIP + 91) /* 171091 */ +#define PJSIP_ECMPHEADERPARAM (PJSIP_ERRNO_START_PJSIP + 91) /* 171091 */ /************************************************************ @@ -327,7 +326,7 @@ PJ_BEGIN_DECL * (either with no stale parameter or with "stale=false" parameter). In most * cases, this indicates that the username/password combination is incorrect. */ -#define PJSIP_EFAILEDCREDENTIAL (PJSIP_ERRNO_START_PJSIP + 100) /* 171100 */ +#define PJSIP_EFAILEDCREDENTIAL (PJSIP_ERRNO_START_PJSIP + 100) /* 171100 */ /** * @hideinitializer * No suitable credential is found to authenticate the request against @@ -335,17 +334,17 @@ PJ_BEGIN_DECL * is caused by different realm supplied in the credential than the realm * found in the challenge. */ -#define PJSIP_ENOCREDENTIAL (PJSIP_ERRNO_START_PJSIP + 101) /* 171101 */ +#define PJSIP_ENOCREDENTIAL (PJSIP_ERRNO_START_PJSIP + 101) /* 171101 */ /** * @hideinitializer * Invalid/unsupported algorithm. */ -#define PJSIP_EINVALIDALGORITHM (PJSIP_ERRNO_START_PJSIP + 102) /* 171102 */ +#define PJSIP_EINVALIDALGORITHM (PJSIP_ERRNO_START_PJSIP + 102) /* 171102 */ /** * @hideinitializer * Invalid/unsupported qop. */ -#define PJSIP_EINVALIDQOP (PJSIP_ERRNO_START_PJSIP + 103) /* 171103 */ +#define PJSIP_EINVALIDQOP (PJSIP_ERRNO_START_PJSIP + 103) /* 171103 */ /** * @hideinitializer * Invalid/unsupported authentication scheme. @@ -355,52 +354,52 @@ PJ_BEGIN_DECL * @hideinitializer * No previous challenge. */ -#define PJSIP_EAUTHNOPREVCHAL (PJSIP_ERRNO_START_PJSIP + 105) /* 171105 */ +#define PJSIP_EAUTHNOPREVCHAL (PJSIP_ERRNO_START_PJSIP + 105) /* 171105 */ /** * @hideinitializer * No authorization is found. */ -#define PJSIP_EAUTHNOAUTH (PJSIP_ERRNO_START_PJSIP + 106) /* 171106 */ +#define PJSIP_EAUTHNOAUTH (PJSIP_ERRNO_START_PJSIP + 106) /* 171106 */ /** * @hideinitializer * Account not found. */ -#define PJSIP_EAUTHACCNOTFOUND (PJSIP_ERRNO_START_PJSIP + 107) /* 171107 */ +#define PJSIP_EAUTHACCNOTFOUND (PJSIP_ERRNO_START_PJSIP + 107) /* 171107 */ /** * @hideinitializer * Account is disabled. */ -#define PJSIP_EAUTHACCDISABLED (PJSIP_ERRNO_START_PJSIP + 108) /* 171108 */ +#define PJSIP_EAUTHACCDISABLED (PJSIP_ERRNO_START_PJSIP + 108) /* 171108 */ /** * @hideinitializer * Invalid realm. */ -#define PJSIP_EAUTHINVALIDREALM (PJSIP_ERRNO_START_PJSIP + 109) /* 171109 */ +#define PJSIP_EAUTHINVALIDREALM (PJSIP_ERRNO_START_PJSIP + 109) /* 171109 */ /** * @hideinitializer * Invalid digest. */ -#define PJSIP_EAUTHINVALIDDIGEST (PJSIP_ERRNO_START_PJSIP+110) /* 171110 */ +#define PJSIP_EAUTHINVALIDDIGEST (PJSIP_ERRNO_START_PJSIP+110) /* 171110 */ /** * @hideinitializer * Maximum number of stale retries exceeded. This happens when server * keeps rejecting our authorization request with stale=true. */ -#define PJSIP_EAUTHSTALECOUNT (PJSIP_ERRNO_START_PJSIP + 111) /* 171111 */ +#define PJSIP_EAUTHSTALECOUNT (PJSIP_ERRNO_START_PJSIP + 111) /* 171111 */ /** * @hideinitializer * Invalid nonce value in the challenge. */ -#define PJSIP_EAUTHINNONCE (PJSIP_ERRNO_START_PJSIP + 112) /* 171112 */ +#define PJSIP_EAUTHINNONCE (PJSIP_ERRNO_START_PJSIP + 112) /* 171112 */ /** * @hideinitializer * Invalid AKA credential. */ -#define PJSIP_EAUTHINAKACRED (PJSIP_ERRNO_START_PJSIP + 113) /* 171113 */ +#define PJSIP_EAUTHINAKACRED (PJSIP_ERRNO_START_PJSIP + 113) /* 171113 */ /** * No challenge is found in the challenge. */ -#define PJSIP_EAUTHNOCHAL (PJSIP_ERRNO_START_PJSIP + 114) /* 171114 */ +#define PJSIP_EAUTHNOCHAL (PJSIP_ERRNO_START_PJSIP + 114) /* 171114 */ /************************************************************ * UA AND DIALOG ERRORS @@ -409,17 +408,17 @@ PJ_BEGIN_DECL * @hideinitializer * Missing From/To tag. */ -#define PJSIP_EMISSINGTAG (PJSIP_ERRNO_START_PJSIP+120) /* 171120 */ +#define PJSIP_EMISSINGTAG (PJSIP_ERRNO_START_PJSIP+120) /* 171120 */ /** * @hideinitializer * Expecting REFER method */ -#define PJSIP_ENOTREFER (PJSIP_ERRNO_START_PJSIP+121) /* 171121 */ +#define PJSIP_ENOTREFER (PJSIP_ERRNO_START_PJSIP+121) /* 171121 */ /** * @hideinitializer * Not associated with REFER subscription */ -#define PJSIP_ENOREFERSESSION (PJSIP_ERRNO_START_PJSIP+122) /* 171122 */ +#define PJSIP_ENOREFERSESSION (PJSIP_ERRNO_START_PJSIP+122) /* 171122 */ /************************************************************ * INVITE SESSIONS ERRORS @@ -428,18 +427,18 @@ PJ_BEGIN_DECL * @hideinitializer * Session already terminated. */ -#define PJSIP_ESESSIONTERMINATED (PJSIP_ERRNO_START_PJSIP+140) /* 171140 */ +#define PJSIP_ESESSIONTERMINATED (PJSIP_ERRNO_START_PJSIP+140) /* 171140 */ /** * @hideinitializer * Invalid session state for the specified operation. */ -#define PJSIP_ESESSIONSTATE (PJSIP_ERRNO_START_PJSIP+141) /* 171141 */ +#define PJSIP_ESESSIONSTATE (PJSIP_ERRNO_START_PJSIP+141) /* 171141 */ /** * @hideinitializer * The feature being requested requires the use of secure session or * transport. */ -#define PJSIP_ESESSIONINSECURE (PJSIP_ERRNO_START_PJSIP+142) /* 171142 */ +#define PJSIP_ESESSIONINSECURE (PJSIP_ERRNO_START_PJSIP+142) /* 171142 */ /************************************************************ * TLS TRANSPORT ERRORS @@ -448,72 +447,72 @@ PJ_BEGIN_DECL * @hideinitializer * Unknown TLS error */ -#define PJSIP_TLS_EUNKNOWN (PJSIP_ERRNO_START_PJSIP+160) /* 171160 */ +#define PJSIP_TLS_EUNKNOWN (PJSIP_ERRNO_START_PJSIP+160) /* 171160 */ /** * @hideinitializer * Invalid SSL protocol method. */ -#define PJSIP_TLS_EINVMETHOD (PJSIP_ERRNO_START_PJSIP+161) /* 171161 */ +#define PJSIP_TLS_EINVMETHOD (PJSIP_ERRNO_START_PJSIP+161) /* 171161 */ /** * @hideinitializer * Error loading/verifying SSL CA list file. */ -#define PJSIP_TLS_ECACERT (PJSIP_ERRNO_START_PJSIP+162) /* 171162 */ +#define PJSIP_TLS_ECACERT (PJSIP_ERRNO_START_PJSIP+162) /* 171162 */ /** * @hideinitializer * Error loading SSL certificate chain file. */ -#define PJSIP_TLS_ECERTFILE (PJSIP_ERRNO_START_PJSIP+163) /* 171163 */ +#define PJSIP_TLS_ECERTFILE (PJSIP_ERRNO_START_PJSIP+163) /* 171163 */ /** * @hideinitializer * Error adding private key from SSL certificate file. */ -#define PJSIP_TLS_EKEYFILE (PJSIP_ERRNO_START_PJSIP+164) /* 171164 */ +#define PJSIP_TLS_EKEYFILE (PJSIP_ERRNO_START_PJSIP+164) /* 171164 */ /** * @hideinitializer * Error setting SSL cipher list. */ -#define PJSIP_TLS_ECIPHER (PJSIP_ERRNO_START_PJSIP+165) /* 171165 */ +#define PJSIP_TLS_ECIPHER (PJSIP_ERRNO_START_PJSIP+165) /* 171165 */ /** * @hideinitializer * Error creating SSL context. */ -#define PJSIP_TLS_ECTX (PJSIP_ERRNO_START_PJSIP+166) /* 171166 */ +#define PJSIP_TLS_ECTX (PJSIP_ERRNO_START_PJSIP+166) /* 171166 */ /** * @hideinitializer * Error creating SSL connection object. */ -#define PJSIP_TLS_ESSLCONN (PJSIP_ERRNO_START_PJSIP+167) /* 171167 */ +#define PJSIP_TLS_ESSLCONN (PJSIP_ERRNO_START_PJSIP+167) /* 171167 */ /** * @hideinitializer * Unknown error when performing SSL connect(). */ -#define PJSIP_TLS_ECONNECT (PJSIP_ERRNO_START_PJSIP+168) /* 171168 */ +#define PJSIP_TLS_ECONNECT (PJSIP_ERRNO_START_PJSIP+168) /* 171168 */ /** * @hideinitializer * Unknown error when performing SSL accept(). */ -#define PJSIP_TLS_EACCEPT (PJSIP_ERRNO_START_PJSIP+169) /* 171169 */ +#define PJSIP_TLS_EACCEPT (PJSIP_ERRNO_START_PJSIP+169) /* 171169 */ /** * @hideinitializer * Unknown error when sending SSL data */ -#define PJSIP_TLS_ESEND (PJSIP_ERRNO_START_PJSIP+170) /* 171170 */ +#define PJSIP_TLS_ESEND (PJSIP_ERRNO_START_PJSIP+170) /* 171170 */ /** * @hideinitializer * Unknown error when reading SSL data */ -#define PJSIP_TLS_EREAD (PJSIP_ERRNO_START_PJSIP+171) /* 171171 */ +#define PJSIP_TLS_EREAD (PJSIP_ERRNO_START_PJSIP+171) /* 171171 */ /** * @hideinitializer * SSL negotiation has exceeded the maximum configured timeout. */ -#define PJSIP_TLS_ETIMEDOUT (PJSIP_ERRNO_START_PJSIP+172) /* 171172 */ +#define PJSIP_TLS_ETIMEDOUT (PJSIP_ERRNO_START_PJSIP+172) /* 171172 */ /** * @hideinitializer * SSL certificate verification error. */ -#define PJSIP_TLS_ECERTVERIF (PJSIP_ERRNO_START_PJSIP+173) /* 171173 */ +#define PJSIP_TLS_ECERTVERIF (PJSIP_ERRNO_START_PJSIP+173) /* 171173 */ /** @@ -527,11 +526,11 @@ PJ_BEGIN_DECL * @param buffer The buffer where to put the error message. * @param bufsize Size of the buffer. * - * @return The error message as NULL terminated string, + * @return The error message as NULL terminated string, * wrapped with pj_str_t. */ PJ_DECL(pj_str_t) pjsip_strerror(pj_status_t status, - char *buffer, pj_size_t bufsize); + char *buffer, pj_size_t bufsize); PJ_END_DECL @@ -541,5 +540,5 @@ PJ_END_DECL * @} */ -#endif /* __PJSIP_SIP_ERRNO_H__ */ +#endif /* __PJSIP_SIP_ERRNO_H__ */ diff --git a/pjsip/include/pjsip/sip_event.h b/pjsip/include/pjsip/sip_event.h index 4e002bc185..5b51a4d0ef 100644 --- a/pjsip/include/pjsip/sip_event.h +++ b/pjsip/include/pjsip/sip_event.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -112,7 +111,7 @@ struct pjsip_event void *data; /**< Generic data. */ } src; pjsip_transaction *tsx; /**< The transaction. */ - int prev_state; /**< Previous state. */ + int prev_state; /**< Previous state. */ pjsip_event_id_e type; /**< Type of event source: * - PJSIP_EVENT_TX_MSG * - PJSIP_EVENT_RX_MSG, @@ -169,28 +168,28 @@ struct pjsip_event #define PJSIP_EVENT_INIT_TSX_STATE(event,ptsx,ptype,pdata,prev) \ do { \ (event).type = PJSIP_EVENT_TSX_STATE; \ - (event).body.tsx_state.tsx = ptsx; \ + (event).body.tsx_state.tsx = ptsx; \ (event).body.tsx_state.type = ptype; \ (event).body.tsx_state.src.data = pdata; \ - (event).body.tsx_state.prev_state = prev; \ + (event).body.tsx_state.prev_state = prev; \ } while (0) /** * Init tx msg event. */ -#define PJSIP_EVENT_INIT_TX_MSG(event,ptdata) \ +#define PJSIP_EVENT_INIT_TX_MSG(event,ptdata) \ do { \ (event).type = PJSIP_EVENT_TX_MSG; \ - (event).body.tx_msg.tdata = ptdata; \ + (event).body.tx_msg.tdata = ptdata; \ } while (0) /** * Init rx msg event. */ -#define PJSIP_EVENT_INIT_RX_MSG(event,prdata) \ +#define PJSIP_EVENT_INIT_RX_MSG(event,prdata) \ do { \ - (event).type = PJSIP_EVENT_RX_MSG; \ - (event).body.rx_msg.rdata = prdata; \ + (event).type = PJSIP_EVENT_RX_MSG; \ + (event).body.rx_msg.rdata = prdata; \ } while (0) /** @@ -199,8 +198,8 @@ struct pjsip_event #define PJSIP_EVENT_INIT_TRANSPORT_ERROR(event,ptsx,ptdata) \ do { \ (event).type = PJSIP_EVENT_TRANSPORT_ERROR; \ - (event).body.tx_error.tsx = ptsx; \ - (event).body.tx_error.tdata = ptdata; \ + (event).body.tx_error.tsx = ptsx; \ + (event).body.tx_error.tdata = ptdata; \ } while (0) /** @@ -228,4 +227,4 @@ PJ_DECL(const char *) pjsip_event_str(pjsip_event_id_e e); PJ_END_DECL -#endif /* __PJSIP_SIP_EVENT_H__ */ +#endif /* __PJSIP_SIP_EVENT_H__ */ diff --git a/pjsip/include/pjsip/sip_module.h b/pjsip/include/pjsip/sip_module.h index cc44fef319..79d3291caf 100644 --- a/pjsip/include/pjsip/sip_module.h +++ b/pjsip/include/pjsip/sip_module.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -84,8 +83,8 @@ struct pjsip_module * will be called by endpoint during module registration. If the value * is NULL, then it's equal to returning PJ_SUCCESS. * - * @param endpt The endpoint instance. - * @return Module should return PJ_SUCCESS to indicate success. + * @param endpt The endpoint instance. + * @return Module should return PJ_SUCCESS to indicate success. */ pj_status_t (*load)(pjsip_endpoint *endpt); @@ -94,7 +93,7 @@ struct pjsip_module * will be called by endpoint during module registration. If the value * is NULL, then it's equal to returning PJ_SUCCESS. * - * @return Module should return zero to indicate success. + * @return Module should return zero to indicate success. */ pj_status_t (*start)(void); @@ -104,7 +103,7 @@ struct pjsip_module * module unregistration. If the value is NULL, then it's equal to * returning PJ_SUCCESS. * - * @return Module should return PJ_SUCCESS to indicate success. + * @return Module should return PJ_SUCCESS to indicate success. */ pj_status_t (*stop)(void); @@ -114,31 +113,31 @@ struct pjsip_module * module unregistration. If the value is NULL, then it's equal to * returning PJ_SUCCESS. * - * @param mod The module. + * @param mod The module. * - * @return Module should return PJ_SUCCESS to indicate success. + * @return Module should return PJ_SUCCESS to indicate success. */ pj_status_t (*unload)(void); /** * Optional function to be called to process incoming request message. * - * @param rdata The incoming message. + * @param rdata The incoming message. * - * @return Module should return PJ_TRUE if it handles the request, - * or otherwise it should return PJ_FALSE to allow other - * modules to handle the request. + * @return Module should return PJ_TRUE if it handles the request, + * or otherwise it should return PJ_FALSE to allow other + * modules to handle the request. */ pj_bool_t (*on_rx_request)(pjsip_rx_data *rdata); /** * Optional function to be called to process incoming response message. * - * @param rdata The incoming message. + * @param rdata The incoming message. * - * @return Module should return PJ_TRUE if it handles the - * response, or otherwise it should return PJ_FALSE to - * allow other modules to handle the response. + * @return Module should return PJ_TRUE if it handles the + * response, or otherwise it should return PJ_FALSE to + * allow other modules to handle the response. */ pj_bool_t (*on_rx_response)(pjsip_rx_data *rdata); @@ -146,11 +145,11 @@ struct pjsip_module * Optional function to be called when transport layer is about to * transmit outgoing request message. * - * @param tdata The outgoing request message. + * @param tdata The outgoing request message. * - * @return Module should return PJ_SUCCESS in all cases. - * If non-zero (or PJ_FALSE) is returned, the message - * will not be sent. + * @return Module should return PJ_SUCCESS in all cases. + * If non-zero (or PJ_FALSE) is returned, the message + * will not be sent. */ pj_status_t (*on_tx_request)(pjsip_tx_data *tdata); @@ -158,11 +157,11 @@ struct pjsip_module * Optional function to be called when transport layer is about to * transmit outgoing response message. * - * @param tdata The outgoing response message. + * @param tdata The outgoing response message. * - * @return Module should return PJ_SUCCESS in all cases. - * If non-zero (or PJ_FALSE) is returned, the message - * will not be sent. + * @return Module should return PJ_SUCCESS in all cases. + * If non-zero (or PJ_FALSE) is returned, the message + * will not be sent. */ pj_status_t (*on_tx_response)(pjsip_tx_data *tdata); @@ -171,9 +170,9 @@ struct pjsip_module * transaction user for the specified transaction, when the * transaction's state has changed. * - * @param tsx The transaction. - * @param event The event which has caused the transaction state - * to change. + * @param tsx The transaction. + * @param event The event which has caused the transaction state + * to change. */ void (*on_tsx_state)(pjsip_transaction *tsx, pjsip_event *event); @@ -188,27 +187,27 @@ enum pjsip_module_priority /** * This is the priority used by transport layer. */ - PJSIP_MOD_PRIORITY_TRANSPORT_LAYER = 8, + PJSIP_MOD_PRIORITY_TRANSPORT_LAYER = 8, /** * This is the priority used by transaction layer. */ - PJSIP_MOD_PRIORITY_TSX_LAYER = 16, + PJSIP_MOD_PRIORITY_TSX_LAYER = 16, /** * This is the priority used by the user agent and proxy layer. */ - PJSIP_MOD_PRIORITY_UA_PROXY_LAYER = 32, + PJSIP_MOD_PRIORITY_UA_PROXY_LAYER = 32, /** * This is the priority used by the dialog usages. */ - PJSIP_MOD_PRIORITY_DIALOG_USAGE = 48, + PJSIP_MOD_PRIORITY_DIALOG_USAGE = 48, /** * This is the recommended priority to be used by applications. */ - PJSIP_MOD_PRIORITY_APPLICATION = 64 + PJSIP_MOD_PRIORITY_APPLICATION = 64 }; @@ -218,5 +217,5 @@ enum pjsip_module_priority PJ_END_DECL -#endif /* __PJSIP_SIP_MODULE_H__ */ +#endif /* __PJSIP_SIP_MODULE_H__ */ diff --git a/pjsip/include/pjsip/sip_msg.h b/pjsip/include/pjsip/sip_msg.h index e3502e94e0..abf37c866b 100644 --- a/pjsip/include/pjsip/sip_msg.h +++ b/pjsip/include/pjsip/sip_msg.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -55,13 +54,13 @@ PJ_BEGIN_DECL typedef enum pjsip_method_e { PJSIP_INVITE_METHOD, /**< INVITE method, for establishing dialogs. */ - PJSIP_CANCEL_METHOD, /**< CANCEL method, for cancelling request. */ - PJSIP_ACK_METHOD, /**< ACK method. */ - PJSIP_BYE_METHOD, /**< BYE method, for terminating dialog. */ - PJSIP_REGISTER_METHOD, /**< REGISTER method. */ - PJSIP_OPTIONS_METHOD, /**< OPTIONS method. */ + PJSIP_CANCEL_METHOD, /**< CANCEL method, for cancelling request. */ + PJSIP_ACK_METHOD, /**< ACK method. */ + PJSIP_BYE_METHOD, /**< BYE method, for terminating dialog. */ + PJSIP_REGISTER_METHOD, /**< REGISTER method. */ + PJSIP_OPTIONS_METHOD, /**< OPTIONS method. */ - PJSIP_OTHER_METHOD /**< Other method. */ + PJSIP_OTHER_METHOD /**< Other method. */ } pjsip_method_e; @@ -76,9 +75,9 @@ typedef enum pjsip_method_e */ struct pjsip_method { - pjsip_method_e id; /**< Method ID, from \a pjsip_method_e. */ - pj_str_t name; /**< Method name, which will always contain the - method string. */ + pjsip_method_e id; /**< Method ID, from \a pjsip_method_e. */ + pj_str_t name; /**< Method name, which will always contain the + method string. */ }; @@ -129,31 +128,31 @@ PJ_DECL(const pjsip_method*) pjsip_get_options_method(void); * This function will check whether the method is a known method then set * both the id and name accordingly. * - * @param m The method to initialize. - * @param pool Pool where memory allocation will be allocated from, if required. - * @param str The method string. + * @param m The method to initialize. + * @param pool Pool where memory allocation will be allocated from, if required. + * @param str The method string. */ PJ_DECL(void) pjsip_method_init( pjsip_method *m, - pj_pool_t *pool, - const pj_str_t *str); + pj_pool_t *pool, + const pj_str_t *str); /** * Initialize the method structure from a string, without cloning the string. * See #pjsip_method_init. * - * @param m The method structure to be initialized. - * @param str The method string. + * @param m The method structure to be initialized. + * @param str The method string. */ PJ_DECL(void) pjsip_method_init_np( pjsip_method *m, - pj_str_t *str); + pj_str_t *str); /** * Set the method with the predefined method ID. * This function will also set the name member of the structure to the correct * string according to the method. * - * @param m The method structure. - * @param id The method ID. + * @param m The method structure. + * @param id The method ID. */ PJ_DECL(void) pjsip_method_set( pjsip_method *m, pjsip_method_e id ); @@ -162,22 +161,22 @@ PJ_DECL(void) pjsip_method_set( pjsip_method *m, pjsip_method_e id ); * Copy one method structure to another. If the method is of the known methods, * then memory allocation is not required. * - * @param pool Pool to allocate memory from, if required. + * @param pool Pool to allocate memory from, if required. * @param method The destination method to copy to. - * @param rhs The source method to copy from. + * @param rhs The source method to copy from. */ PJ_DECL(void) pjsip_method_copy( pj_pool_t *pool, - pjsip_method *method, - const pjsip_method *rhs ); + pjsip_method *method, + const pjsip_method *rhs ); /** * Compare one method with another, and conveniently determine whether the * first method is equal, less than, or greater than the second method. * - * @param m1 The first method. - * @param m2 The second method. + * @param m1 The first method. + * @param m2 The second method. * - * @return Zero if equal, otherwise will return -1 if less or +1 if greater. + * @return Zero if equal, otherwise will return -1 if less or +1 if greater. */ PJ_DECL(int) pjsip_method_cmp( const pjsip_method *m1, const pjsip_method *m2); @@ -206,48 +205,48 @@ typedef enum pjsip_hdr_e * DO NOT CHANGE THE VALUE/ORDER OF THE HEADER IDs!!!. */ PJSIP_H_ACCEPT, - PJSIP_H_ACCEPT_ENCODING_UNIMP, /* N/A, use pjsip_generic_string_hdr */ - PJSIP_H_ACCEPT_LANGUAGE_UNIMP, /* N/A, use pjsip_generic_string_hdr */ - PJSIP_H_ALERT_INFO_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_ACCEPT_ENCODING_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_ACCEPT_LANGUAGE_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_ALERT_INFO_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_ALLOW, - PJSIP_H_AUTHENTICATION_INFO_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_AUTHENTICATION_INFO_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_AUTHORIZATION, PJSIP_H_CALL_ID, - PJSIP_H_CALL_INFO_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_CALL_INFO_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_CONTACT, - PJSIP_H_CONTENT_DISPOSITION_UNIMP, /* N/A, use pjsip_generic_string_hdr */ - PJSIP_H_CONTENT_ENCODING_UNIMP, /* N/A, use pjsip_generic_string_hdr */ - PJSIP_H_CONTENT_LANGUAGE_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_CONTENT_DISPOSITION_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_CONTENT_ENCODING_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_CONTENT_LANGUAGE_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_CONTENT_LENGTH, PJSIP_H_CONTENT_TYPE, PJSIP_H_CSEQ, - PJSIP_H_DATE_UNIMP, /* N/A, use pjsip_generic_string_hdr */ - PJSIP_H_ERROR_INFO_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_DATE_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_ERROR_INFO_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_EXPIRES, PJSIP_H_FROM, - PJSIP_H_IN_REPLY_TO_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_IN_REPLY_TO_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_MAX_FORWARDS, - PJSIP_H_MIME_VERSION_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_MIME_VERSION_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_MIN_EXPIRES, - PJSIP_H_ORGANIZATION_UNIMP, /* N/A, use pjsip_generic_string_hdr */ - PJSIP_H_PRIORITY_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_ORGANIZATION_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_PRIORITY_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_PROXY_AUTHENTICATE, PJSIP_H_PROXY_AUTHORIZATION, - PJSIP_H_PROXY_REQUIRE_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_PROXY_REQUIRE_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_RECORD_ROUTE, - PJSIP_H_REPLY_TO_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_REPLY_TO_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_REQUIRE, PJSIP_H_RETRY_AFTER, PJSIP_H_ROUTE, - PJSIP_H_SERVER_UNIMP, /* N/A, use pjsip_generic_string_hdr */ - PJSIP_H_SUBJECT_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_SERVER_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_SUBJECT_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_SUPPORTED, - PJSIP_H_TIMESTAMP_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_TIMESTAMP_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_TO, PJSIP_H_UNSUPPORTED, - PJSIP_H_USER_AGENT_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_USER_AGENT_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_VIA, - PJSIP_H_WARNING_UNIMP, /* N/A, use pjsip_generic_string_hdr */ + PJSIP_H_WARNING_UNIMP, /* N/A, use pjsip_generic_string_hdr */ PJSIP_H_WWW_AUTHENTICATE, PJSIP_H_OTHER @@ -285,14 +284,14 @@ typedef struct pjsip_hdr_vptr void *(*shallow_clone)(pj_pool_t *pool, const void *hdr); /** Pointer to function to print the header to the specified buffer. - * Returns the length of string written, or -1 if the remaining buffer - * is not enough to hold the header. + * Returns the length of string written, or -1 if the remaining buffer + * is not enough to hold the header. * * @param hdr The header to print. * @param buf The buffer. * @param len The size of the buffer. * - * @return The size copied to buffer, or -1 if there's not enough space. + * @return The size copied to buffer, or -1 if there's not enough space. */ int (*print_on)(void *hdr, char *buf, pj_size_t len); @@ -305,15 +304,15 @@ typedef struct pjsip_hdr_vptr * the storage. This behaves like C++ inheritance actually. */ #define PJSIP_DECL_HDR_MEMBER(hdr) \ - /** List members. */ \ - PJ_DECL_LIST_MEMBER(hdr); \ - /** Header type */ \ - pjsip_hdr_e type; \ - /** Header name. */ \ - pj_str_t name; \ - /** Header short name version. */ \ - pj_str_t sname; \ - /** Virtual function table. */ \ + /** List members. */ \ + PJ_DECL_LIST_MEMBER(hdr); \ + /** Header type */ \ + pjsip_hdr_e type; \ + /** Header name. */ \ + pj_str_t name; \ + /** Header short name version. */ \ + pj_str_t sname; \ + /** Virtual function table. */ \ pjsip_hdr_vptr *vptr @@ -331,10 +330,10 @@ struct pjsip_hdr * This generic function will clone any header, by calling "clone" function * in header's virtual function table. * - * @param pool The pool to allocate memory from. - * @param hdr The header to clone. + * @param pool The pool to allocate memory from. + * @param hdr The header to clone. * - * @return A new instance copied from the original header. + * @return A new instance copied from the original header. */ PJ_DECL(void*) pjsip_hdr_clone( pj_pool_t *pool, const void *hdr ); @@ -343,10 +342,10 @@ PJ_DECL(void*) pjsip_hdr_clone( pj_pool_t *pool, const void *hdr ); * This generic function will clone any header, by calling "shallow_clone" * function in header's virtual function table. * - * @param pool The pool to allocate memory from. - * @param hdr The header to clone. + * @param pool The pool to allocate memory from. + * @param hdr The header to clone. * - * @return A new instance copied from the original header. + * @return A new instance copied from the original header. */ PJ_DECL(void*) pjsip_hdr_shallow_clone( pj_pool_t *pool, const void *hdr ); @@ -358,7 +357,7 @@ PJ_DECL(void*) pjsip_hdr_shallow_clone( pj_pool_t *pool, const void *hdr ); * @param buf The buffer. * @param len The size of the buffer. * - * @return The size copied to buffer, or -1 if there's not enough space. + * @return The size copied to buffer, or -1 if there's not enough space. */ PJ_DECL(int) pjsip_hdr_print_on( void *hdr, char *buf, pj_size_t len); @@ -376,8 +375,8 @@ PJ_DECL(int) pjsip_hdr_print_on( void *hdr, char *buf, pj_size_t len); * type is found. */ PJ_DECL(void*) pjsip_hdr_find( const void *hdr_list, - pjsip_hdr_e type, - const void *start); + pjsip_hdr_e type, + const void *start); /** * Find a header in a header list by its name. @@ -393,8 +392,8 @@ PJ_DECL(void*) pjsip_hdr_find( const void *hdr_list, * type is found. */ PJ_DECL(void*) pjsip_hdr_find_by_name( const void *hdr_list, - const pj_str_t *name, - const void *start); + const pj_str_t *name, + const void *start); /** * Find a header in a header list by its name and short name version. @@ -407,13 +406,13 @@ PJ_DECL(void*) pjsip_hdr_find_by_name( const void *hdr_list, * first header, otherwise the search will begin at the * specified header. * - * @return The header field, or NULL if no header with the specified - * type is found. + * @return The header field, or NULL if no header with the specified + * type is found. */ PJ_DECL(void*) pjsip_hdr_find_by_names( const void *hdr_list, - const pj_str_t *name, - const pj_str_t *sname, - const void *start); + const pj_str_t *name, + const pj_str_t *sname, + const void *start); /** * @} @@ -442,8 +441,8 @@ typedef struct pjsip_request_line */ typedef struct pjsip_status_line { - int code; /**< Status code. */ - pj_str_t reason; /**< Reason string. */ + int code; /**< Status code. */ + pj_str_t reason; /**< Reason string. */ } pjsip_status_line; @@ -556,9 +555,9 @@ typedef enum pjsip_status_code /** * Get the default status text for the status code. * - * @param status_code SIP Status Code + * @param status_code SIP Status Code * - * @return textual message for the status code. + * @return textual message for the status code. */ PJ_DECL(const pj_str_t*) pjsip_get_status_text(int status_code); @@ -566,11 +565,11 @@ PJ_DECL(const pj_str_t*) pjsip_get_status_text(int status_code); * This macro returns non-zero (TRUE) if the specified status_code is * in the same class as the code_class. * - * @param status_code The status code. - * @param code_class The status code in the class (for example 100, 200). + * @param status_code The status code. + * @param code_class The status code in the class (for example 100, 200). */ #define PJSIP_IS_STATUS_IN_CLASS(status_code, code_class) \ - (status_code/100 == code_class/100) + (status_code/100 == code_class/100) /** * @} @@ -590,75 +589,75 @@ PJ_DECL(const pj_str_t*) pjsip_get_status_text(int status_code); */ typedef struct pjsip_media_type { - pj_str_t type; /**< Media type. */ - pj_str_t subtype; /**< Media subtype. */ - pjsip_param param; /**< Media type parameters */ + pj_str_t type; /**< Media type. */ + pj_str_t subtype; /**< Media subtype. */ + pjsip_param param; /**< Media type parameters */ } pjsip_media_type; /** * Initialize the media type with the specified type and subtype string. * - * @param mt The media type. - * @param type Optionally specify the media type. - * @param subtype Optionally specify the media subtype. + * @param mt The media type. + * @param type Optionally specify the media type. + * @param subtype Optionally specify the media subtype. */ PJ_DECL(void) pjsip_media_type_init(pjsip_media_type *mt, - pj_str_t *type, - pj_str_t *subtype); + pj_str_t *type, + pj_str_t *subtype); /** * Initialize the media type with the specified type and subtype string. * - * @param mt The media type. - * @param type Optionally specify the media type. - * @param subtype Optionally specify the media subtype. + * @param mt The media type. + * @param type Optionally specify the media type. + * @param subtype Optionally specify the media subtype. */ PJ_DECL(void) pjsip_media_type_init2(pjsip_media_type *mt, - char *type, - char *subtype); + char *type, + char *subtype); /** * Compare two media types. * - * @param mt1 The first media type. - * @param mt2 The second media type. - * @param cmp_param Specify how to compare the media type parameters: - * - 0: do not compare parameters - * - 1: compare parameters but ignore parameters that - * only appear in one of the media type. - * - 2: compare the parameters. + * @param mt1 The first media type. + * @param mt2 The second media type. + * @param cmp_param Specify how to compare the media type parameters: + * - 0: do not compare parameters + * - 1: compare parameters but ignore parameters that + * only appear in one of the media type. + * - 2: compare the parameters. * - * @return Zero if both media types are equal, -1 if mt1 < mt2, - * 1 if mt1 > mt2. + * @return Zero if both media types are equal, -1 if mt1 < mt2, + * 1 if mt1 > mt2. */ PJ_DECL(int) pjsip_media_type_cmp(const pjsip_media_type *mt1, - const pjsip_media_type *mt2, - int cmp_param); + const pjsip_media_type *mt2, + int cmp_param); /** * Copy SIP media type to another. * - * @param pool Pool to duplicate strings. - * @param dst Destination structure. - * @param src Source structure. + * @param pool Pool to duplicate strings. + * @param dst Destination structure. + * @param src Source structure. */ PJ_DECL(void) pjsip_media_type_cp(pj_pool_t *pool, - pjsip_media_type *dst, - const pjsip_media_type *src); + pjsip_media_type *dst, + const pjsip_media_type *src); /** * Print media type to the specified buffer. * - * @param buf Destination buffer. - * @param len Length of the buffer. - * @param mt The media type to be printed. + * @param buf Destination buffer. + * @param len Length of the buffer. + * @param mt The media type to be printed. * - * @return The number of characters printed to the buffer, or -1 - * if there's not enough space in the buffer. + * @return The number of characters printed to the buffer, or -1 + * if there's not enough space in the buffer. */ PJ_DECL(int) pjsip_media_type_print(char *buf, unsigned len, - const pjsip_media_type *mt); + const pjsip_media_type *mt); /** * @} @@ -723,27 +722,27 @@ struct pjsip_msg_body * Application must set a proper function here when sending outgoing * message. * - * @param msg_body This structure itself. - * @param buf The buffer. - * @param size The buffer size. + * @param msg_body This structure itself. + * @param buf The buffer. + * @param size The buffer size. * - * @return The length of the string printed, or -1 if there is - * not enough space in the buffer to print the whole - * message body. + * @return The length of the string printed, or -1 if there is + * not enough space in the buffer to print the whole + * message body. */ int (*print_body)(struct pjsip_msg_body *msg_body, - char *buf, pj_size_t size); + char *buf, pj_size_t size); /** Clone the data part only of this message body. Note that this only * duplicates the data part of the body instead of the whole message * body. If application wants to duplicate the entire message body * structure, it must call #pjsip_msg_body_clone(). * - * @param pool Pool used to clone the data. - * @param data The data inside message body, to be cloned. - * @param len The length of the data. + * @param pool Pool used to clone the data. + * @param data The data inside message body, to be cloned. + * @param len The length of the data. * - * @return New data duplicated from the original data. + * @return New data duplicated from the original data. */ void* (*clone_data)(pj_pool_t *pool, const void *data, unsigned len); @@ -756,14 +755,14 @@ struct pjsip_msg_body * body is not a textual body, then application must supply a custom function * to print that body. * - * @param msg_body The message body. - * @param buf Buffer to copy the message body to. - * @param size The size of the buffer. + * @param msg_body The message body. + * @param buf Buffer to copy the message body to. + * @param size The size of the buffer. * - * @return The length copied to the buffer, or -1. + * @return The length copied to the buffer, or -1. */ PJ_DECL(int) pjsip_print_text_body( pjsip_msg_body *msg_body, - char *buf, pj_size_t size); + char *buf, pj_size_t size); /** * General purpose function to clone textual data in a SIP body. Attach this @@ -771,14 +770,14 @@ PJ_DECL(int) pjsip_print_text_body( pjsip_msg_body *msg_body, * is a text (i.e. C string, not pj_str_t), and the length indicates the * length of the text. * - * @param pool Pool used to clone the data. - * @param data Textual data. - * @param len The length of the string. + * @param pool Pool used to clone the data. + * @param data Textual data. + * @param len The length of the string. * - * @return New text duplicated from the original text. + * @return New text duplicated from the original text. */ PJ_DECL(void*) pjsip_clone_text_data( pj_pool_t *pool, const void *data, - unsigned len); + unsigned len); /** @@ -786,29 +785,29 @@ PJ_DECL(void*) pjsip_clone_text_data( pj_pool_t *pool, const void *data, * the contents of the message body using the \a clone_data member of the * source message body. * - * @param pool Pool to use to duplicate the message body. - * @param dst_body Destination message body. - * @param src_body Source message body to duplicate. + * @param pool Pool to use to duplicate the message body. + * @param dst_body Destination message body. + * @param src_body Source message body to duplicate. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_msg_body_copy( pj_pool_t *pool, - pjsip_msg_body *dst_body, - const pjsip_msg_body *src_body ); - + pjsip_msg_body *dst_body, + const pjsip_msg_body *src_body ); + /** * Create cloned message body. This will duplicate the contents of the message * body using the \a clone_data member of the source message body. * - * @param pool Pool to use to duplicate the message body. - * @param body Source message body to duplicate. + * @param pool Pool to use to duplicate the message body. + * @param body Source message body to duplicate. * - * @return The cloned message body on successfull. + * @return The cloned message body on successfull. */ PJ_DECL(pjsip_msg_body*) pjsip_msg_body_clone( pj_pool_t *pool, - const pjsip_msg_body *body ); - + const pjsip_msg_body *body ); + /** * Create a text message body. Use this function to create message body when @@ -816,18 +815,18 @@ PJ_DECL(pjsip_msg_body*) pjsip_msg_body_clone( pj_pool_t *pool, * pjmedia_sdp_session or pj_xml_node), application must construct the message * manually. * - * @param pool Pool to allocate message body and its contents. - * @param type MIME type (e.g. "text"). - * @param subtype MIME subtype (e.g. "plain"). - * @param text The text content to be put in the message body. + * @param pool Pool to allocate message body and its contents. + * @param type MIME type (e.g. "text"). + * @param subtype MIME subtype (e.g. "plain"). + * @param text The text content to be put in the message body. * - * @return A new message body with the specified Content-Type and - * text. + * @return A new message body with the specified Content-Type and + * text. */ PJ_DECL(pjsip_msg_body*) pjsip_msg_body_create( pj_pool_t *pool, - const pj_str_t *type, - const pj_str_t *subtype, - const pj_str_t *text ); + const pj_str_t *type, + const pj_str_t *subtype, + const pj_str_t *text ); /** * @} @@ -846,8 +845,8 @@ PJ_DECL(pjsip_msg_body*) pjsip_msg_body_create( pj_pool_t *pool, */ typedef enum pjsip_msg_type_e { - PJSIP_REQUEST_MSG, /**< Indicates request message. */ - PJSIP_RESPONSE_MSG /**< Indicates response message. */ + PJSIP_REQUEST_MSG, /**< Indicates request message. */ + PJSIP_RESPONSE_MSG /**< Indicates response message. */ } pjsip_msg_type_e; @@ -860,23 +859,23 @@ struct pjsip_msg pjsip_msg_type_e type; /** The first line of the message can be either request line for request - * messages, or status line for response messages. It is represented here + * messages, or status line for response messages. It is represented here * as a union. */ union { - /** Request Line. */ - struct pjsip_request_line req; + /** Request Line. */ + struct pjsip_request_line req; - /** Status Line. */ - struct pjsip_status_line status; + /** Status Line. */ + struct pjsip_status_line status; } line; /** List of message headers. */ pjsip_hdr hdr; /** Pointer to message body, or NULL if no message body is attached to - * this mesage. + * this mesage. */ pjsip_msg_body *body; }; @@ -885,9 +884,9 @@ struct pjsip_msg /** * Create new request or response message. * - * @param pool The pool. - * @param type Message type. - * @return New message, or THROW exception if failed. + * @param pool The pool. + * @param type Message type. + * @return New message, or THROW exception if failed. */ PJ_DECL(pjsip_msg*) pjsip_msg_create( pj_pool_t *pool, pjsip_msg_type_e type); @@ -895,11 +894,11 @@ PJ_DECL(pjsip_msg*) pjsip_msg_create( pj_pool_t *pool, pjsip_msg_type_e type); /** * Perform a deep clone of a SIP message. * - * @param pool The pool for creating the new message. - * @param msg The message to be duplicated. + * @param pool The pool for creating the new message. + * @param msg The message to be duplicated. * - * @return New message, which is duplicated from the original - * message. + * @return New message, which is duplicated from the original + * message. */ PJ_DECL(pjsip_msg*) pjsip_msg_clone( pj_pool_t *pool, const pjsip_msg *msg); @@ -907,73 +906,73 @@ PJ_DECL(pjsip_msg*) pjsip_msg_clone( pj_pool_t *pool, const pjsip_msg *msg); /** * Find a header in the message by the header type. * - * @param msg The message. - * @param type The header type to find. - * @param start The first header field where the search should begin. - * If NULL is specified, then the search will begin from the - * first header, otherwise the search will begin at the - * specified header. + * @param msg The message. + * @param type The header type to find. + * @param start The first header field where the search should begin. + * If NULL is specified, then the search will begin from the + * first header, otherwise the search will begin at the + * specified header. * - * @return The header field, or NULL if no header with the specified - * type is found. + * @return The header field, or NULL if no header with the specified + * type is found. */ PJ_DECL(void*) pjsip_msg_find_hdr( const pjsip_msg *msg, - pjsip_hdr_e type, const void *start); + pjsip_hdr_e type, const void *start); /** * Find a header in the message by its name. * - * @param msg The message. - * @param name The header name to find. - * @param start The first header field where the search should begin. - * If NULL is specified, then the search will begin from the - * first header, otherwise the search will begin at the - * specified header. + * @param msg The message. + * @param name The header name to find. + * @param start The first header field where the search should begin. + * If NULL is specified, then the search will begin from the + * first header, otherwise the search will begin at the + * specified header. * - * @return The header field, or NULL if no header with the specified - * type is found. + * @return The header field, or NULL if no header with the specified + * type is found. */ PJ_DECL(void*) pjsip_msg_find_hdr_by_name( const pjsip_msg *msg, - const pj_str_t *name, - const void *start); + const pj_str_t *name, + const void *start); /** * Find a header in the message by its name and short name version. * - * @param msg The message. - * @param name The header name to find. - * @param sname The short name version of the header name. - * @param start The first header field where the search should begin. - * If NULL is specified, then the search will begin from the - * first header, otherwise the search will begin at the - * specified header. + * @param msg The message. + * @param name The header name to find. + * @param sname The short name version of the header name. + * @param start The first header field where the search should begin. + * If NULL is specified, then the search will begin from the + * first header, otherwise the search will begin at the + * specified header. * - * @return The header field, or NULL if no header with the specified - * type is found. + * @return The header field, or NULL if no header with the specified + * type is found. */ PJ_DECL(void*) pjsip_msg_find_hdr_by_names(const pjsip_msg *msg, - const pj_str_t *name, - const pj_str_t *sname, - const void *start); + const pj_str_t *name, + const pj_str_t *sname, + const void *start); /** * Find and remove a header in the message. * - * @param msg The message. - * @param hdr The header type to find. - * @param start The first header field where the search should begin, - * or NULL to search from the first header in the message. + * @param msg The message. + * @param hdr The header type to find. + * @param start The first header field where the search should begin, + * or NULL to search from the first header in the message. * - * @return The header field, or NULL if not found. + * @return The header field, or NULL if not found. */ PJ_DECL(void*) pjsip_msg_find_remove_hdr( pjsip_msg *msg, - pjsip_hdr_e hdr, void *start); + pjsip_hdr_e hdr, void *start); /** * Add a header to the message, putting it last in the header list. * - * @param msg The message. - * @param hdr The header to add. + * @param msg The message. + * @param hdr The header to add. * * @bug Once the header is put in a list (or message), it can not be put in * other list (or message). Otherwise Real Bad Thing will happen. @@ -986,8 +985,8 @@ PJ_INLINE(void) pjsip_msg_add_hdr( pjsip_msg *msg, pjsip_hdr *hdr ) /** * Add header field to the message, putting it in the front of the header list. * - * @param msg The message. - * @param hdr The header to add. + * @param msg The message. + * @param hdr The header to add. * * @bug Once the header is put in a list (or message), it can not be put in * other list (or message). Otherwise Real Bad Thing will happen. @@ -1000,15 +999,15 @@ PJ_INLINE(void) pjsip_msg_insert_first_hdr( pjsip_msg *msg, pjsip_hdr *hdr ) /** * Print the message to the specified buffer. * - * @param msg The message to print. - * @param buf The buffer - * @param size The size of the buffer. + * @param msg The message to print. + * @param buf The buffer + * @param size The size of the buffer. * - * @return The length of the printed characters (in bytes), or NEGATIVE - * value if the message is too large for the specified buffer. + * @return The length of the printed characters (in bytes), or NEGATIVE + * value if the message is too large for the specified buffer. */ PJ_DECL(pj_ssize_t) pjsip_msg_print(const pjsip_msg *msg, - char *buf, pj_size_t size); + char *buf, pj_size_t size); /* @@ -1019,38 +1018,38 @@ PJ_DECL(pj_ssize_t) pjsip_msg_print(const pjsip_msg *msg, /** * Find Call-ID header. * - * @param msg The message. - * @return Call-ID header instance. + * @param msg The message. + * @return Call-ID header instance. */ #define PJSIP_MSG_CID_HDR(msg) \ - ((pjsip_cid_hdr*)pjsip_msg_find_hdr(msg, PJSIP_H_CALL_ID, NULL)) + ((pjsip_cid_hdr*)pjsip_msg_find_hdr(msg, PJSIP_H_CALL_ID, NULL)) /** * Find CSeq header. * - * @param msg The message. - * @return CSeq header instance. + * @param msg The message. + * @return CSeq header instance. */ #define PJSIP_MSG_CSEQ_HDR(msg) \ - ((pjsip_cseq_hdr*)pjsip_msg_find_hdr(msg, PJSIP_H_CSEQ, NULL)) + ((pjsip_cseq_hdr*)pjsip_msg_find_hdr(msg, PJSIP_H_CSEQ, NULL)) /** * Find From header. * - * @param msg The message. - * @return From header instance. + * @param msg The message. + * @return From header instance. */ #define PJSIP_MSG_FROM_HDR(msg) \ - ((pjsip_from_hdr*)pjsip_msg_find_hdr(msg, PJSIP_H_FROM, NULL)) + ((pjsip_from_hdr*)pjsip_msg_find_hdr(msg, PJSIP_H_FROM, NULL)) /** * Find To header. * - * @param msg The message. - * @return To header instance. + * @param msg The message. + * @return To header instance. */ #define PJSIP_MSG_TO_HDR(msg) \ - ((pjsip_to_hdr*)pjsip_msg_find_hdr(msg, PJSIP_H_TO, NULL)) + ((pjsip_to_hdr*)pjsip_msg_find_hdr(msg, PJSIP_H_TO, NULL)) /** @@ -1080,17 +1079,17 @@ typedef struct pjsip_generic_string_hdr * Create a new instance of generic header. A generic header can have an * arbitrary header name. * - * @param pool The pool. - * @param hname The header name to be assigned to the header, or NULL to - * assign the header name with some string. + * @param pool The pool. + * @param hname The header name to be assigned to the header, or NULL to + * assign the header name with some string. * @param hvalue Optional string to be assigned as the value. * - * @return The header, or THROW exception. + * @return The header, or THROW exception. */ PJ_DECL(pjsip_generic_string_hdr*) pjsip_generic_string_hdr_create( pj_pool_t *pool, - const pj_str_t *hname, - const pj_str_t *hvalue); + const pj_str_t *hname, + const pj_str_t *hvalue); /** @@ -1101,20 +1100,20 @@ pjsip_generic_string_hdr_create( pj_pool_t *pool, * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. - * @param hname The header name to be assigned to the header, or NULL to - * assign the header name with some string later. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. + * @param hname The header name to be assigned to the header, or NULL to + * assign the header name with some string later. * @param hvalue Optional string to be assigned as the value. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_generic_string_hdr*) pjsip_generic_string_hdr_init( pj_pool_t *pool, - void *mem, - const pj_str_t *hname, - const pj_str_t *hvalue); + void *mem, + const pj_str_t *hname, + const pj_str_t *hvalue); /** @@ -1123,15 +1122,15 @@ pjsip_generic_string_hdr_init( pj_pool_t *pool, * very short (for example, creating the header in the stack to be passed * as argument to a function which will copy the header). * - * @param h The header to be initialized. - * @param hname The header name to be assigned to the header, or NULL to - * assign the header name with some string. + * @param h The header to be initialized. + * @param hname The header name to be assigned to the header, or NULL to + * assign the header name with some string. * @param hvalue Optional string to be assigned as the value. * */ PJ_DECL(void) pjsip_generic_string_hdr_init2(pjsip_generic_string_hdr *h, - pj_str_t *hname, - pj_str_t *hvalue); + pj_str_t *hname, + pj_str_t *hvalue); /* **************************************************************************/ @@ -1152,16 +1151,16 @@ typedef struct pjsip_generic_int_hdr * Create a new instance of generic header. A generic header can have an * arbitrary header name. * - * @param pool The pool. - * @param hname The header name to be assigned to the header, or NULL to - * assign the header name with some string. + * @param pool The pool. + * @param hname The header name to be assigned to the header, or NULL to + * assign the header name with some string. * @param hvalue The value to be assigned to the header. * - * @return The header, or THROW exception. + * @return The header, or THROW exception. */ PJ_DECL(pjsip_generic_int_hdr*) pjsip_generic_int_hdr_create( pj_pool_t *pool, - const pj_str_t *hname, - unsigned hvalue ); + const pj_str_t *hname, + unsigned hvalue ); /** @@ -1172,24 +1171,24 @@ PJ_DECL(pjsip_generic_int_hdr*) pjsip_generic_int_hdr_create( pj_pool_t *pool, * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. - * @param hname The header name to be assigned to the header, or NULL to - * assign the header name with some string later. - * @param value Value to be assigned to the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. + * @param hname The header name to be assigned to the header, or NULL to + * assign the header name with some string later. + * @param value Value to be assigned to the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_generic_int_hdr*) pjsip_generic_int_hdr_init( pj_pool_t *pool, - void *mem, - const pj_str_t *hname, - unsigned value ); + void *mem, + const pj_str_t *hname, + unsigned value ); /* **************************************************************************/ /** Maximum elements in the header array. */ -#define PJSIP_GENERIC_ARRAY_MAX_COUNT 32 +#define PJSIP_GENERIC_ARRAY_MAX_COUNT 32 /** * Generic array of string header. @@ -1200,23 +1199,23 @@ typedef struct pjsip_generic_array_hdr PJSIP_DECL_HDR_MEMBER(struct pjsip_generic_array_hdr); /** Number of tags/elements. */ - unsigned count; + unsigned count; /** Tags/elements. */ - pj_str_t values[PJSIP_GENERIC_ARRAY_MAX_COUNT]; + pj_str_t values[PJSIP_GENERIC_ARRAY_MAX_COUNT]; } pjsip_generic_array_hdr; /** * Create generic array header. * - * @param pool Pool to allocate memory from. - * @param hname Header name. + * @param pool Pool to allocate memory from. + * @param hname Header name. * - * @return New generic array header. + * @return New generic array header. */ PJ_DECL(pjsip_generic_array_hdr*) pjsip_generic_array_hdr_create(pj_pool_t *pool, - const pj_str_t *hname); + const pj_str_t *hname); /** * Initialize a preallocated memory with the header structure. This function @@ -1226,17 +1225,17 @@ PJ_DECL(pjsip_generic_array_hdr*) pjsip_generic_array_hdr_create(pj_pool_t *pool * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. - * @param hname The header name to be assigned to the header, or NULL to - * assign the header name with some string later. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. + * @param hname The header name to be assigned to the header, or NULL to + * assign the header name with some string later. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_generic_array_hdr*) pjsip_generic_array_hdr_init(pj_pool_t *pool, - void *mem, - const pj_str_t *hname); + void *mem, + const pj_str_t *hname); /* **************************************************************************/ @@ -1245,14 +1244,14 @@ PJ_DECL(pjsip_generic_array_hdr*) pjsip_generic_array_hdr_init(pj_pool_t *pool, typedef pjsip_generic_array_hdr pjsip_accept_hdr; /** Maximum fields in Accept header. */ -#define PJSIP_MAX_ACCEPT_COUNT PJSIP_GENERIC_ARRAY_MAX_COUNT +#define PJSIP_MAX_ACCEPT_COUNT PJSIP_GENERIC_ARRAY_MAX_COUNT /** * Create new Accept header instance. * - * @param pool The pool. + * @param pool The pool. * - * @return New Accept header instance. + * @return New Accept header instance. */ PJ_DECL(pjsip_accept_hdr*) pjsip_accept_hdr_create(pj_pool_t *pool); @@ -1264,14 +1263,14 @@ PJ_DECL(pjsip_accept_hdr*) pjsip_accept_hdr_create(pj_pool_t *pool); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_accept_hdr*) pjsip_accept_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /* **************************************************************************/ @@ -1284,9 +1283,9 @@ typedef pjsip_generic_array_hdr pjsip_allow_hdr; /** * Create new Allow header instance. * - * @param pool The pool. + * @param pool The pool. * - * @return New Allow header instance. + * @return New Allow header instance. */ PJ_DECL(pjsip_allow_hdr*) pjsip_allow_hdr_create(pj_pool_t *pool); @@ -1300,14 +1299,14 @@ PJ_DECL(pjsip_allow_hdr*) pjsip_allow_hdr_create(pj_pool_t *pool); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_allow_hdr*) pjsip_allow_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /* **************************************************************************/ @@ -1317,16 +1316,16 @@ PJ_DECL(pjsip_allow_hdr*) pjsip_allow_hdr_init( pj_pool_t *pool, typedef struct pjsip_cid_hdr { PJSIP_DECL_HDR_MEMBER(struct pjsip_cid_hdr); - pj_str_t id; /**< Call-ID string. */ + pj_str_t id; /**< Call-ID string. */ } pjsip_cid_hdr; /** * Create new Call-ID header. * - * @param pool The pool. + * @param pool The pool. * - * @return new Call-ID header. + * @return new Call-ID header. */ PJ_DECL(pjsip_cid_hdr*) pjsip_cid_hdr_create( pj_pool_t *pool ); @@ -1339,14 +1338,14 @@ PJ_DECL(pjsip_cid_hdr*) pjsip_cid_hdr_create( pj_pool_t *pool ); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_cid_hdr*) pjsip_cid_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); @@ -1357,14 +1356,14 @@ PJ_DECL(pjsip_cid_hdr*) pjsip_cid_hdr_init( pj_pool_t *pool, typedef struct pjsip_clen_hdr { PJSIP_DECL_HDR_MEMBER(struct pjsip_clen_hdr); - int len; /**< Content length. */ + int len; /**< Content length. */ } pjsip_clen_hdr; /** * Create new Content-Length header. * - * @param pool the pool. - * @return A new Content-Length header instance. + * @param pool the pool. + * @return A new Content-Length header instance. */ PJ_DECL(pjsip_clen_hdr*) pjsip_clen_hdr_create( pj_pool_t *pool ); @@ -1376,14 +1375,14 @@ PJ_DECL(pjsip_clen_hdr*) pjsip_clen_hdr_create( pj_pool_t *pool ); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_clen_hdr*) pjsip_clen_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /* **************************************************************************/ @@ -1393,14 +1392,14 @@ PJ_DECL(pjsip_clen_hdr*) pjsip_clen_hdr_init( pj_pool_t *pool, typedef struct pjsip_cseq_hdr { PJSIP_DECL_HDR_MEMBER(struct pjsip_cseq_hdr); - pj_int32_t cseq; /**< CSeq number. */ - pjsip_method method; /**< CSeq method. */ + pj_int32_t cseq; /**< CSeq number. */ + pjsip_method method; /**< CSeq method. */ } pjsip_cseq_hdr; /** Create new CSeq header. * - * @param pool The pool. + * @param pool The pool. * @return A new CSeq header instance. */ PJ_DECL(pjsip_cseq_hdr*) pjsip_cseq_hdr_create( pj_pool_t *pool ); @@ -1413,19 +1412,19 @@ PJ_DECL(pjsip_cseq_hdr*) pjsip_cseq_hdr_create( pj_pool_t *pool ); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_cseq_hdr*) pjsip_cseq_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /* **************************************************************************/ /** Expires not specified. */ -#define PJSIP_EXPIRES_NOT_SPECIFIED ((pj_uint32_t)0xFFFFFFFFUL) +#define PJSIP_EXPIRES_NOT_SPECIFIED ((pj_uint32_t)0xFFFFFFFFUL) /** * Contact header. @@ -1436,24 +1435,24 @@ PJ_DECL(pjsip_cseq_hdr*) pjsip_cseq_hdr_init( pj_pool_t *pool, typedef struct pjsip_contact_hdr { PJSIP_DECL_HDR_MEMBER(struct pjsip_contact_hdr); - int star; /**< The contact contains only a '*' - character */ - pjsip_uri *uri; /**< URI in the contact. */ - int q1000; /**< The "q" value times 1000 - (to avoid float) */ - pj_uint32_t expires; /**< Expires parameter, otherwise - PJSIP_EXPIRES_NOT_SPECIFIED - if not present. */ - pjsip_param other_param; /**< Other parameters, concatenated in - a single string. */ + int star; /**< The contact contains only a '*' + character */ + pjsip_uri *uri; /**< URI in the contact. */ + int q1000; /**< The "q" value times 1000 + (to avoid float) */ + pj_uint32_t expires; /**< Expires parameter, otherwise + PJSIP_EXPIRES_NOT_SPECIFIED + if not present. */ + pjsip_param other_param; /**< Other parameters, concatenated in + a single string. */ } pjsip_contact_hdr; /** * Create a new Contact header. * - * @param pool The pool. - * @return A new instance of Contact header. + * @param pool The pool. + * @return A new instance of Contact header. */ PJ_DECL(pjsip_contact_hdr*) pjsip_contact_hdr_create( pj_pool_t *pool ); @@ -1465,14 +1464,14 @@ PJ_DECL(pjsip_contact_hdr*) pjsip_contact_hdr_create( pj_pool_t *pool ); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_contact_hdr*) pjsip_contact_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /* **************************************************************************/ @@ -1489,8 +1488,8 @@ typedef struct pjsip_ctype_hdr /** * Create a nwe Content Type header. * - * @param pool The pool. - * @return A new Content-Type header. + * @param pool The pool. + * @return A new Content-Type header. */ PJ_DECL(pjsip_ctype_hdr*) pjsip_ctype_hdr_create( pj_pool_t *pool ); @@ -1502,14 +1501,14 @@ PJ_DECL(pjsip_ctype_hdr*) pjsip_ctype_hdr_create( pj_pool_t *pool ); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_ctype_hdr*) pjsip_ctype_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /* **************************************************************************/ /** Expires header. */ @@ -1518,13 +1517,13 @@ typedef pjsip_generic_int_hdr pjsip_expires_hdr; /** * Create a new Expires header. * - * @param pool The pool. - * @param value The expiration value. + * @param pool The pool. + * @param value The expiration value. * - * @return A new Expires header. + * @return A new Expires header. */ PJ_DECL(pjsip_expires_hdr*) pjsip_expires_hdr_create( pj_pool_t *pool, - unsigned value); + unsigned value); /** * Initialize a preallocated memory with the header structure. This function @@ -1534,16 +1533,16 @@ PJ_DECL(pjsip_expires_hdr*) pjsip_expires_hdr_create( pj_pool_t *pool, * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. - * @param value The expiration value. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. + * @param value The expiration value. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_expires_hdr*) pjsip_expires_hdr_init( pj_pool_t *pool, - void *mem, - unsigned value ); + void *mem, + unsigned value ); @@ -1554,9 +1553,9 @@ PJ_DECL(pjsip_expires_hdr*) pjsip_expires_hdr_init( pj_pool_t *pool, typedef struct pjsip_fromto_hdr { PJSIP_DECL_HDR_MEMBER(struct pjsip_fromto_hdr); - pjsip_uri *uri; /**< URI in From/To header. */ - pj_str_t tag; /**< Header "tag" parameter. */ - pjsip_param other_param; /**< Other params, concatenated as a single string. */ + pjsip_uri *uri; /**< URI in From/To header. */ + pj_str_t tag; /**< Header "tag" parameter. */ + pjsip_param other_param; /**< Other params, concatenated as a single string. */ } pjsip_fromto_hdr; /** Alias for From header. */ @@ -1568,8 +1567,8 @@ typedef pjsip_fromto_hdr pjsip_to_hdr; /** * Create a From header. * - * @param pool The pool. - * @return New instance of From header. + * @param pool The pool. + * @return New instance of From header. */ PJ_DECL(pjsip_from_hdr*) pjsip_from_hdr_create( pj_pool_t *pool ); @@ -1581,20 +1580,20 @@ PJ_DECL(pjsip_from_hdr*) pjsip_from_hdr_create( pj_pool_t *pool ); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_from_hdr*) pjsip_from_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /** * Create a To header. * - * @param pool The pool. - * @return New instance of To header. + * @param pool The pool. + * @return New instance of To header. */ PJ_DECL(pjsip_to_hdr*) pjsip_to_hdr_create( pj_pool_t *pool ); @@ -1606,28 +1605,28 @@ PJ_DECL(pjsip_to_hdr*) pjsip_to_hdr_create( pj_pool_t *pool ); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_to_hdr*) pjsip_to_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /** * Convert the header to a From header. * - * @param hdr The generic from/to header. - * @return "From" header. + * @param hdr The generic from/to header. + * @return "From" header. */ PJ_DECL(pjsip_from_hdr*) pjsip_fromto_hdr_set_from( pjsip_fromto_hdr *hdr ); /** * Convert the header to a To header. * - * @param hdr The generic from/to header. - * @return "To" header. + * @param hdr The generic from/to header. + * @return "To" header. */ PJ_DECL(pjsip_to_hdr*) pjsip_fromto_hdr_set_to( pjsip_fromto_hdr *hdr ); @@ -1641,10 +1640,10 @@ typedef pjsip_generic_int_hdr pjsip_max_fwd_hdr; /** * Create new Max-Forwards header instance. * - * @param pool The pool. - * @param value The Max-Forwards value. + * @param pool The pool. + * @param value The Max-Forwards value. * - * @return New Max-Forwards header instance. + * @return New Max-Forwards header instance. */ PJ_DECL(pjsip_max_fwd_hdr*) pjsip_max_fwd_hdr_create(pj_pool_t *pool, unsigned value); @@ -1658,12 +1657,12 @@ pjsip_max_fwd_hdr_create(pj_pool_t *pool, unsigned value); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. - * @param value The Max-Forwards value. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. + * @param value The Max-Forwards value. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_max_fwd_hdr*) pjsip_max_fwd_hdr_init( pj_pool_t *pool, void *mem, unsigned value ); @@ -1678,13 +1677,13 @@ typedef pjsip_generic_int_hdr pjsip_min_expires_hdr; /** * Create new Min-Expires header instance. * - * @param pool The pool. - * @param value The Min-Expires value. + * @param pool The pool. + * @param value The Min-Expires value. * - * @return New Min-Expires header instance. + * @return New Min-Expires header instance. */ PJ_DECL(pjsip_min_expires_hdr*) pjsip_min_expires_hdr_create(pj_pool_t *pool, - unsigned value); + unsigned value); /** @@ -1695,16 +1694,16 @@ PJ_DECL(pjsip_min_expires_hdr*) pjsip_min_expires_hdr_create(pj_pool_t *pool, * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. - * @param value The Min-Expires value. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. + * @param value The Min-Expires value. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_min_expires_hdr*) pjsip_min_expires_hdr_init( pj_pool_t *pool, - void *mem, - unsigned value ); + void *mem, + unsigned value ); /* **************************************************************************/ @@ -1714,8 +1713,8 @@ PJ_DECL(pjsip_min_expires_hdr*) pjsip_min_expires_hdr_init( pj_pool_t *pool, typedef struct pjsip_routing_hdr { PJSIP_DECL_HDR_MEMBER(struct pjsip_routing_hdr); /**< Generic header fields. */ - pjsip_name_addr name_addr; /**< The URL in the Route/Record-Route header. */ - pjsip_param other_param; /**< Other parameter. */ + pjsip_name_addr name_addr; /**< The URL in the Route/Record-Route header. */ + pjsip_param other_param; /**< Other parameter. */ } pjsip_routing_hdr; /** Alias for Record-Route header. */ @@ -1728,10 +1727,10 @@ typedef pjsip_routing_hdr pjsip_route_hdr; /** * Create new Record-Route header from the pool. * - * @param pool The pool. - * @return A new instance of Record-Route header. + * @param pool The pool. + * @return A new instance of Record-Route header. */ -PJ_DECL(pjsip_rr_hdr*) pjsip_rr_hdr_create( pj_pool_t *pool ); +PJ_DECL(pjsip_rr_hdr*) pjsip_rr_hdr_create( pj_pool_t *pool ); /** * Initialize a preallocated memory with the header structure. This function @@ -1741,20 +1740,20 @@ PJ_DECL(pjsip_rr_hdr*) pjsip_rr_hdr_create( pj_pool_t *pool ); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_rr_hdr*) pjsip_rr_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /** * Create new Route header from the pool. * - * @param pool The pool. - * @return A new instance of "Route" header. + * @param pool The pool. + * @return A new instance of "Route" header. */ PJ_DECL(pjsip_route_hdr*) pjsip_route_hdr_create( pj_pool_t *pool ); @@ -1766,28 +1765,28 @@ PJ_DECL(pjsip_route_hdr*) pjsip_route_hdr_create( pj_pool_t *pool ); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_route_hdr*) pjsip_route_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /** * Convert generic routing header to Record-Route header. * - * @param r The generic routing header, or a "Routing" header. - * @return Record-Route header. + * @param r The generic routing header, or a "Routing" header. + * @return Record-Route header. */ -PJ_DECL(pjsip_rr_hdr*) pjsip_routing_hdr_set_rr( pjsip_routing_hdr *r ); +PJ_DECL(pjsip_rr_hdr*) pjsip_routing_hdr_set_rr( pjsip_routing_hdr *r ); /** * Convert generic routing header to "Route" header. * - * @param r The generic routing header, or a "Record-Route" header. - * @return "Route" header. + * @param r The generic routing header, or a "Record-Route" header. + * @return "Route" header. */ PJ_DECL(pjsip_route_hdr*) pjsip_routing_hdr_set_route( pjsip_routing_hdr *r ); @@ -1800,9 +1799,9 @@ typedef pjsip_generic_array_hdr pjsip_require_hdr; /** * Create new Require header instance. * - * @param pool The pool. + * @param pool The pool. * - * @return New Require header instance. + * @return New Require header instance. */ PJ_DECL(pjsip_require_hdr*) pjsip_require_hdr_create(pj_pool_t *pool); @@ -1814,14 +1813,14 @@ PJ_DECL(pjsip_require_hdr*) pjsip_require_hdr_create(pj_pool_t *pool); * For normal applications, they should use pjsip_xxx_hdr_create() instead, * which allocates memory and initialize it in one go. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_require_hdr*) pjsip_require_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /* **************************************************************************/ @@ -1832,36 +1831,36 @@ typedef struct pjsip_retry_after_hdr { /** Standard header field. */ PJSIP_DECL_HDR_MEMBER(struct pjsip_retry_after_hdr); - pj_int32_t ivalue; /**< Retry-After value */ - pjsip_param param; /**< Optional parameters */ - pj_str_t comment; /**< Optional comments. */ + pj_int32_t ivalue; /**< Retry-After value */ + pjsip_param param; /**< Optional parameters */ + pj_str_t comment; /**< Optional comments. */ } pjsip_retry_after_hdr; /** * Create new Retry-After header instance. * - * @param pool The pool. - * @param value The Retry-After value. + * @param pool The pool. + * @param value The Retry-After value. * - * @return New Retry-After header instance. + * @return New Retry-After header instance. */ PJ_DECL(pjsip_retry_after_hdr*) pjsip_retry_after_hdr_create(pj_pool_t *pool, - int value); + int value); /** * Initialize a preallocated memory with the header structure. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. - * @param value The Retry-After value. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. + * @param value The Retry-After value. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_retry_after_hdr*) pjsip_retry_after_hdr_init( pj_pool_t *pool, - void *mem, - int value ); + void *mem, + int value ); /* **************************************************************************/ @@ -1873,23 +1872,23 @@ typedef pjsip_generic_array_hdr pjsip_supported_hdr; /** * Create new Supported header instance. * - * @param pool The pool. + * @param pool The pool. * - * @return New Supported header instance. + * @return New Supported header instance. */ PJ_DECL(pjsip_supported_hdr*) pjsip_supported_hdr_create(pj_pool_t *pool); /** * Initialize a preallocated memory with the header structure. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_supported_hdr*) pjsip_supported_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /* **************************************************************************/ /** @@ -1900,23 +1899,23 @@ typedef pjsip_generic_array_hdr pjsip_unsupported_hdr; /** * Create new Unsupported header instance. * - * @param pool The pool. + * @param pool The pool. * - * @return New Unsupported header instance. + * @return New Unsupported header instance. */ PJ_DECL(pjsip_unsupported_hdr*) pjsip_unsupported_hdr_create(pj_pool_t *pool); /** * Initialize a preallocated memory with the header structure. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_unsupported_hdr*) pjsip_unsupported_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /* **************************************************************************/ /** @@ -1928,37 +1927,37 @@ PJ_DECL(pjsip_unsupported_hdr*) pjsip_unsupported_hdr_init( pj_pool_t *pool, typedef struct pjsip_via_hdr { PJSIP_DECL_HDR_MEMBER(struct pjsip_via_hdr); - pj_str_t transport; /**< Transport type. */ - pjsip_host_port sent_by; /**< Host and optional port */ - int ttl_param; /**< TTL parameter, or -1 if it's not specified. */ - int rport_param; /**< "rport" parameter, 0 to specify without - port number, -1 means doesn't exist. */ - pj_str_t maddr_param; /**< "maddr" parameter. */ - pj_str_t recvd_param; /**< "received" parameter. */ - pj_str_t branch_param; /**< "branch" parameter. */ - pjsip_param other_param; /**< Other parameters, concatenated as single string. */ - pj_str_t comment; /**< Comment. */ + pj_str_t transport; /**< Transport type. */ + pjsip_host_port sent_by; /**< Host and optional port */ + int ttl_param; /**< TTL parameter, or -1 if it's not specified. */ + int rport_param; /**< "rport" parameter, 0 to specify without + port number, -1 means doesn't exist. */ + pj_str_t maddr_param; /**< "maddr" parameter. */ + pj_str_t recvd_param; /**< "received" parameter. */ + pj_str_t branch_param; /**< "branch" parameter. */ + pjsip_param other_param; /**< Other parameters, concatenated as single string. */ + pj_str_t comment; /**< Comment. */ } pjsip_via_hdr; /** * Create a new Via header. * - * @param pool The pool. - * @return A new "Via" header instance. + * @param pool The pool. + * @return A new "Via" header instance. */ PJ_DECL(pjsip_via_hdr*) pjsip_via_hdr_create( pj_pool_t *pool ); /** * Initialize a preallocated memory with the header structure. * - * @param pool Pool for additional memory allocation if required. - * @param mem Pre-allocated memory to be initialized as the header. + * @param pool Pool for additional memory allocation if required. + * @param mem Pre-allocated memory to be initialized as the header. * - * @return The header instance, which points to the same memory - * location as the mem argument. + * @return The header instance, which points to the same memory + * location as the mem argument. */ PJ_DECL(pjsip_via_hdr*) pjsip_via_hdr_init( pj_pool_t *pool, - void *mem ); + void *mem ); /* **************************************************************************/ /** @@ -1971,35 +1970,35 @@ typedef pjsip_generic_string_hdr pjsip_warning_hdr; /** * Create a warning header with the specified contents. * - * @param pool Pool to allocate memory from. - * @param code Warning code, 300-399. - * @param host The host portion of the Warning header. - * @param text The warning text, which MUST not be quoted with - * double quote. + * @param pool Pool to allocate memory from. + * @param code Warning code, 300-399. + * @param host The host portion of the Warning header. + * @param text The warning text, which MUST not be quoted with + * double quote. * - * @return The Warning header field. + * @return The Warning header field. */ PJ_DECL(pjsip_warning_hdr*) pjsip_warning_hdr_create( pj_pool_t *pool, - int code, - const pj_str_t *host, - const pj_str_t *text); + int code, + const pj_str_t *host, + const pj_str_t *text); /** * Create a warning header and initialize the contents from the error * message for the specified status code. The warning code will be * set to 399. * - * @param pool Pool to allocate memory from. - * @param host The host portion of the Warning header. + * @param pool Pool to allocate memory from. + * @param host The host portion of the Warning header. * @param status The error status code, which error text will be - * put in as the Warning text. + * put in as the Warning text. * - * @return The Warning header field. + * @return The Warning header field. */ PJ_DECL(pjsip_warning_hdr*) pjsip_warning_hdr_create_from_status( pj_pool_t *pool, - const pj_str_t *host, - pj_status_t status); + const pj_str_t *host, + pj_status_t status); /* **************************************************************************/ /** Accept-Encoding header. */ @@ -2131,5 +2130,5 @@ typedef pjsip_generic_string_hdr pjsip_user_agent_hdr; PJ_END_DECL -#endif /* __PJSIP_SIP_MSG_H__ */ +#endif /* __PJSIP_SIP_MSG_H__ */ diff --git a/pjsip/include/pjsip/sip_multipart.h b/pjsip/include/pjsip/sip_multipart.h index f9a5271fc0..c4256bec48 100644 --- a/pjsip/include/pjsip/sip_multipart.h +++ b/pjsip/include/pjsip/sip_multipart.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -50,39 +49,39 @@ typedef struct pjsip_multipart_part /** * Optional message headers. */ - pjsip_hdr hdr; + pjsip_hdr hdr; /** * Pointer to the message body. */ - pjsip_msg_body *body; + pjsip_msg_body *body; } pjsip_multipart_part; /** * Create an empty multipart body. * - * @param pool Memory pool to allocate memory from. - * @param ctype Optional MIME media type of the multipart - * bodies. If not specified, "multipart/mixed" - * will be used. - * @param boundary Optional string to be set as part boundary. - * The boundary string excludes the leading - * hyphens. If this parameter is NULL or empty, - * a random boundary will be generated. + * @param pool Memory pool to allocate memory from. + * @param ctype Optional MIME media type of the multipart + * bodies. If not specified, "multipart/mixed" + * will be used. + * @param boundary Optional string to be set as part boundary. + * The boundary string excludes the leading + * hyphens. If this parameter is NULL or empty, + * a random boundary will be generated. * - * @return Multipart body instance with no part. + * @return Multipart body instance with no part. */ PJ_DECL(pjsip_msg_body*) pjsip_multipart_create(pj_pool_t *pool, - const pjsip_media_type *ctype, - const pj_str_t *boundary); + const pjsip_media_type *ctype, + const pj_str_t *boundary); /** * Create an empty multipart part. * - * @param pool The memory pool. + * @param pool The memory pool. * - * @return The multipart part. + * @return The multipart part. */ PJ_DECL(pjsip_multipart_part*) pjsip_multipart_create_part(pj_pool_t *pool); @@ -90,35 +89,35 @@ PJ_DECL(pjsip_multipart_part*) pjsip_multipart_create_part(pj_pool_t *pool); /** * Perform a deep clone to a multipart part. * - * @param pool The memory pool. - * @param part The part to be duplicated. + * @param pool The memory pool. + * @param part The part to be duplicated. * - * @return Copy of the multipart part. + * @return Copy of the multipart part. */ PJ_DECL(pjsip_multipart_part*) pjsip_multipart_clone_part(pj_pool_t *pool, - const pjsip_multipart_part *part); + const pjsip_multipart_part *part); /** * Add a part into multipart bodies. * - * @param pool The memory pool. - * @param mp The multipart bodies. - * @param part The part to be added into the bodies. + * @param pool The memory pool. + * @param mp The multipart bodies. + * @param part The part to be added into the bodies. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_multipart_add_part(pj_pool_t *pool, - pjsip_msg_body *mp, - pjsip_multipart_part *part); + pjsip_msg_body *mp, + pjsip_multipart_part *part); /** * Get the first part of multipart bodies. * - * @param mp The multipart bodies. + * @param mp The multipart bodies. * - * @return The first part, or NULL if the multipart - * bodies currently doesn't hold any elements. + * @return The first part, or NULL if the multipart + * bodies currently doesn't hold any elements. */ PJ_DECL(pjsip_multipart_part*) pjsip_multipart_get_first_part(const pjsip_msg_body *mp); @@ -126,75 +125,75 @@ pjsip_multipart_get_first_part(const pjsip_msg_body *mp); /** * Get the next part after the specified part. * - * @param mp The multipart bodies. - * @param part The part. + * @param mp The multipart bodies. + * @param part The part. * - * @return The next part, or NULL if there is no other part after - * the part. + * @return The next part, or NULL if there is no other part after + * the part. */ PJ_DECL(pjsip_multipart_part*) pjsip_multipart_get_next_part(const pjsip_msg_body *mp, - pjsip_multipart_part *part); + pjsip_multipart_part *part); /** * Find a body inside multipart bodies which has the specified content type. * - * @param mp The multipart body. - * @param content_type Content type to find. - * @param start If specified, the search will begin at - * start->next. Otherwise it will begin at - * the first part in the multipart bodies. + * @param mp The multipart body. + * @param content_type Content type to find. + * @param start If specified, the search will begin at + * start->next. Otherwise it will begin at + * the first part in the multipart bodies. * - * @return The first part with the specified content type - * if found, or NULL. + * @return The first part with the specified content type + * if found, or NULL. */ PJ_DECL(pjsip_multipart_part*) pjsip_multipart_find_part( const pjsip_msg_body *mp, - const pjsip_media_type *content_type, - const pjsip_multipart_part *start); + const pjsip_media_type *content_type, + const pjsip_multipart_part *start); /** * Find a body inside multipart bodies which has a header matching the * supplied one. Most useful for finding a part with a specific Content-ID. * - * @param pool Memory pool to use for temp space. - * @param mp The multipart body. - * @param search_hdr Header to search for. - * @param start If specified, the search will begin at - * start->next part. Otherwise it will begin at - * the first part in the multipart bodies. + * @param pool Memory pool to use for temp space. + * @param mp The multipart body. + * @param search_hdr Header to search for. + * @param start If specified, the search will begin at + * start->next part. Otherwise it will begin at + * the first part in the multipart bodies. * - * @return The first part which has a header matching the - * specified one, or NULL if not found. + * @return The first part which has a header matching the + * specified one, or NULL if not found. */ PJ_DECL(pjsip_multipart_part*) pjsip_multipart_find_part_by_header(pj_pool_t *pool, - const pjsip_msg_body *mp, - void *search_hdr, - const pjsip_multipart_part *start); + const pjsip_msg_body *mp, + void *search_hdr, + const pjsip_multipart_part *start); /** * Find a body inside multipart bodies which has a header matching the * supplied name and value. Most useful for finding a part with a specific * Content-ID. * - * @param pool Memory pool to use for temp space. - * @param mp The multipart body. - * @param hdr_name Header name to search for. - * @param hdr_value Header value search for. - * @param start If specified, the search will begin at - * start->next part. Otherwise it will begin at - * the first part in the multipart bodies. + * @param pool Memory pool to use for temp space. + * @param mp The multipart body. + * @param hdr_name Header name to search for. + * @param hdr_value Header value search for. + * @param start If specified, the search will begin at + * start->next part. Otherwise it will begin at + * the first part in the multipart bodies. * - * @return The first part which has a header matching the - * specified one, or NULL if not found. + * @return The first part which has a header matching the + * specified one, or NULL if not found. */ PJ_DECL(pjsip_multipart_part*) pjsip_multipart_find_part_by_header_str(pj_pool_t *pool, - const pjsip_msg_body *mp, - const pj_str_t *hdr_name, - const pj_str_t *hdr_value, - const pjsip_multipart_part *start); + const pjsip_msg_body *mp, + const pj_str_t *hdr_name, + const pj_str_t *hdr_value, + const pjsip_multipart_part *start); @@ -206,17 +205,17 @@ pjsip_multipart_find_part_by_header_str(pj_pool_t *pool, * * @see RFC2392 Content-ID and Message-ID Uniform Resource Locators * - * @param pool Memory pool to use for temp space. - * @param mp The multipart body. - * @param cid The "cid" URI to search for in pj_str form. + * @param pool Memory pool to use for temp space. + * @param mp The multipart body. + * @param cid The "cid" URI to search for in pj_str form. * - * @return The first part which has a Content-ID header matching the - * specified "cid" URI. or NULL if not found. + * @return The first part which has a Content-ID header matching the + * specified "cid" URI. or NULL if not found. */ PJ_DECL(pjsip_multipart_part*) pjsip_multipart_find_part_by_cid_str(pj_pool_t *pool, - const pjsip_msg_body *mp, - pj_str_t *cid); + const pjsip_msg_body *mp, + pj_str_t *cid); /** * Find a body inside multipart bodies which has a Content-ID value matching the @@ -224,48 +223,48 @@ pjsip_multipart_find_part_by_cid_str(pj_pool_t *pool, * * @see RFC2392 Content-ID and Message-ID Uniform Resource Locators * - * @param pool Memory pool to use for temp space. - * @param mp The multipart body. - * @param cid The "cid" URI to search for. + * @param pool Memory pool to use for temp space. + * @param mp The multipart body. + * @param cid The "cid" URI to search for. * - * @return The first part which had a Content-ID header matching the - * specified "cid" URI. or NULL if not found. + * @return The first part which had a Content-ID header matching the + * specified "cid" URI. or NULL if not found. */ PJ_DECL(pjsip_multipart_part*) pjsip_multipart_find_part_by_cid_uri(pj_pool_t *pool, - const pjsip_msg_body *mp, - pjsip_other_uri *cid); + const pjsip_msg_body *mp, + pjsip_other_uri *cid); /** * Parse multipart message. * - * @param pool Memory pool. - * @param buf Input buffer. - * @param len The buffer length. - * @param ctype Content type of the multipart body. - * @param options Parsing options, must be zero for now. + * @param pool Memory pool. + * @param buf Input buffer. + * @param len The buffer length. + * @param ctype Content type of the multipart body. + * @param options Parsing options, must be zero for now. * - * @return Multipart message body. + * @return Multipart message body. */ PJ_DECL(pjsip_msg_body*) pjsip_multipart_parse(pj_pool_t *pool, - char *buf, pj_size_t len, - const pjsip_media_type *ctype, - unsigned options); + char *buf, pj_size_t len, + const pjsip_media_type *ctype, + unsigned options); /** * Get the boundary string and the raw message body of the specified * multipart message body. Note that raw message body will only be available * if the multipart message body is generated by pjsip_multipart_parse(). * - * @param mp The multipart message body. - * @param boundary Optional parameter to receive the boundary string. - * @param raw_data Optional parameter to receive the raw message body. + * @param mp The multipart message body. + * @param boundary Optional parameter to receive the boundary string. + * @param raw_data Optional parameter to receive the raw message body. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_multipart_get_raw(pjsip_msg_body *mp, - pj_str_t *boundary, - pj_str_t *raw_data); + pj_str_t *boundary, + pj_str_t *raw_data); /** * @} PJSIP_MULTIPART @@ -274,4 +273,4 @@ PJ_DECL(pj_status_t) pjsip_multipart_get_raw(pjsip_msg_body *mp, PJ_END_DECL -#endif /* __PJSIP_SIP_MULTIPART_H__ */ +#endif /* __PJSIP_SIP_MULTIPART_H__ */ diff --git a/pjsip/include/pjsip/sip_parser.h b/pjsip/include/pjsip/sip_parser.h index 3efd9376f9..e1c6a5694b 100644 --- a/pjsip/include/pjsip/sip_parser.h +++ b/pjsip/include/pjsip/sip_parser.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -41,22 +40,22 @@ PJ_BEGIN_DECL /** * Contants for limit checks */ -#define PJSIP_MIN_CONTENT_LENGTH 0 /**< For limit checks */ +#define PJSIP_MIN_CONTENT_LENGTH 0 /**< For limit checks */ #define PJSIP_MAX_CONTENT_LENGTH PJ_MAXINT32 /**< For limit checks */ -#define PJSIP_MIN_PORT 0 /**< For limit checks */ -#define PJSIP_MAX_PORT PJ_MAXUINT16/**< For limit checks */ -#define PJSIP_MIN_TTL 0 /**< For limit checks */ -#define PJSIP_MAX_TTL PJ_MAXUINT8 /**< For limit checks */ -#define PJSIP_MIN_STATUS_CODE 100 /**< For limit checks */ -#define PJSIP_MAX_STATUS_CODE 999 /**< For limit checks */ -#define PJSIP_MIN_Q1000 0 /**< For limit checks */ -#define PJSIP_MAX_Q1000 PJ_MAXINT32 / 1000/**< For limit checks */ -#define PJSIP_MIN_EXPIRES 0 /**< For limit checks */ -#define PJSIP_MAX_EXPIRES ((pj_uint32_t)0xFFFFFFFFUL)/**< for chk */ -#define PJSIP_MIN_CSEQ 0 /**< For limit checks */ -#define PJSIP_MAX_CSEQ PJ_MAXINT32 /**< For limit checks */ -#define PJSIP_MIN_RETRY_AFTER 0 /**< For limit checks */ -#define PJSIP_MAX_RETRY_AFTER PJ_MAXINT32 /**< For limit checks */ +#define PJSIP_MIN_PORT 0 /**< For limit checks */ +#define PJSIP_MAX_PORT PJ_MAXUINT16/**< For limit checks */ +#define PJSIP_MIN_TTL 0 /**< For limit checks */ +#define PJSIP_MAX_TTL PJ_MAXUINT8 /**< For limit checks */ +#define PJSIP_MIN_STATUS_CODE 100 /**< For limit checks */ +#define PJSIP_MAX_STATUS_CODE 999 /**< For limit checks */ +#define PJSIP_MIN_Q1000 0 /**< For limit checks */ +#define PJSIP_MAX_Q1000 PJ_MAXINT32 / 1000/**< For limit checks */ +#define PJSIP_MIN_EXPIRES 0 /**< For limit checks */ +#define PJSIP_MAX_EXPIRES ((pj_uint32_t)0xFFFFFFFFUL)/**< for chk */ +#define PJSIP_MIN_CSEQ 0 /**< For limit checks */ +#define PJSIP_MAX_CSEQ PJ_MAXINT32 /**< For limit checks */ +#define PJSIP_MIN_RETRY_AFTER 0 /**< For limit checks */ +#define PJSIP_MAX_RETRY_AFTER PJ_MAXINT32 /**< For limit checks */ /** * URI Parsing options. @@ -95,10 +94,10 @@ typedef struct pjsip_parser_err_report { /** Standard header fields. */ PJ_DECL_LIST_MEMBER(struct pjsip_parser_err_report); - int except_code; /**< Error exception (e.g. PJSIP_SYN_ERR_EXCEPTION) */ - int line; /**< Line number. */ - int col; /**< Column number. */ - pj_str_t hname; /**< Header name, if any. */ + int except_code; /**< Error exception (e.g. PJSIP_SYN_ERR_EXCEPTION) */ + int line; /**< Line number. */ + int col; /**< Column number. */ + pj_str_t hname; /**< Header name, if any. */ } pjsip_parser_err_report; @@ -125,9 +124,9 @@ typedef struct pjsip_parse_ctx * - It must read the header separator after finished reading the header * body. The separator types are described below, and if they don't exist, * exception must be thrown. Header separator can be a: - * - newline, such as when the header is part of a SIP message. - * - ampersand, such as when the header is part of an URI. - * - for the last header, these separator is optional since parsing + * - newline, such as when the header is part of a SIP message. + * - ampersand, such as when the header is part of an URI. + * - for the last header, these separator is optional since parsing * can be terminated when seeing EOF. */ typedef pjsip_hdr* (pjsip_parse_hdr_func)(pjsip_parse_ctx *context); @@ -138,97 +137,97 @@ typedef pjsip_hdr* (pjsip_parse_hdr_func)(pjsip_parse_ctx *context); * also applies here (except the separator part). */ typedef void* (pjsip_parse_uri_func)(pj_scanner *scanner, pj_pool_t *pool, - pj_bool_t parse_params); + pj_bool_t parse_params); /** * Register header parser handler. The parser handler MUST follow the * specification of header parser handler function. New registration * overwrites previous registration with the same name. * - * @param hname The header name. - * @param hshortname The short header name or NULL. - * @param fptr The pointer to function to parser the header. + * @param hname The header name. + * @param hshortname The short header name or NULL. + * @param fptr The pointer to function to parser the header. * - * @return PJ_SUCCESS if success, or the appropriate error code. + * @return PJ_SUCCESS if success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_register_hdr_parser( const char *hname, - const char *hshortname, - pjsip_parse_hdr_func *fptr); + const char *hshortname, + pjsip_parse_hdr_func *fptr); /** * Unregister previously registered header parser handler. * All the arguments MUST exactly equal to the value specified upon * registration of the handler. * - * @param hname The header name registered. - * @param hshortname The short header name registered, or NULL. - * @param fptr Previously registered function to parse the header. + * @param hname The header name registered. + * @param hshortname The short header name registered, or NULL. + * @param fptr Previously registered function to parse the header. * - * @return zero if unregistration was successfull. + * @return zero if unregistration was successfull. */ PJ_DECL(pj_status_t) pjsip_unregister_hdr_parser( const char *hname, - const char *hshortname, - pjsip_parse_hdr_func *fptr); + const char *hshortname, + pjsip_parse_hdr_func *fptr); /** * Register URI scheme parser handler. * - * @param scheme The URI scheme registered. - * @param func The URI parser function. + * @param scheme The URI scheme registered. + * @param func The URI parser function. * - * @return zero on success. + * @return zero on success. */ PJ_DECL(pj_status_t) pjsip_register_uri_parser( char *scheme, - pjsip_parse_uri_func *func); + pjsip_parse_uri_func *func); /** * Unregister URI scheme parser handler. * All the arguments MUST exactly equal to the value specified upon * registration of the handler. * - * @param scheme The URI scheme as registered previously. - * @param func The function handler as registered previously. + * @param scheme The URI scheme as registered previously. + * @param func The function handler as registered previously. * - * @return zero if the registration was successfull. + * @return zero if the registration was successfull. */ PJ_DECL(pj_status_t) pjsip_unregister_uri_parser( const char *scheme, - pjsip_parse_uri_func *func); + pjsip_parse_uri_func *func); /** * Parse an URI in the input and return the correct instance of URI. * Note that the input string buffer MUST be NULL terminated and have * length at least size+1 (size MUST NOT include the NULL terminator). * - * @param pool The pool to get memory allocations. - * @param buf The input buffer, which MUST be NULL terminated. - * @param size The length of the string (not counting NULL terminator). - * @param options If no options are given (value is zero), the object - * returned is dependent on the syntax of the URI, - * eg. basic SIP URL, TEL URL, or name address. - * If option PJSIP_PARSE_URI_AS_NAMEADDR is given, - * then the returned object is always name address object, - * with the relevant URI object contained in the name - * address object. - * @return The URI or NULL when failed. No exception is thrown by - * this function (or any public parser functions). + * @param pool The pool to get memory allocations. + * @param buf The input buffer, which MUST be NULL terminated. + * @param size The length of the string (not counting NULL terminator). + * @param options If no options are given (value is zero), the object + * returned is dependent on the syntax of the URI, + * eg. basic SIP URL, TEL URL, or name address. + * If option PJSIP_PARSE_URI_AS_NAMEADDR is given, + * then the returned object is always name address object, + * with the relevant URI object contained in the name + * address object. + * @return The URI or NULL when failed. No exception is thrown by + * this function (or any public parser functions). */ PJ_DECL(pjsip_uri*) pjsip_parse_uri( pj_pool_t *pool, - char *buf, pj_size_t size, - unsigned options); + char *buf, pj_size_t size, + unsigned options); /** * Parse SIP status line. * Note that the input string buffer MUST be NULL terminated and have * length at least size+1 (size MUST NOT include the NULL terminator). * - * @param buf Text buffer to parse, which MUST be NULL terminated. - * @param size The size of the buffer, excluding the NULL character. - * @param status_line Structure to receive the parsed elements. + * @param buf Text buffer to parse, which MUST be NULL terminated. + * @param size The size of the buffer, excluding the NULL character. + * @param status_line Structure to receive the parsed elements. * - * @return PJ_SUCCESS if a status line is parsed successfully. + * @return PJ_SUCCESS if a status line is parsed successfully. */ PJ_DECL(pj_status_t) pjsip_parse_status_line(char *buf, pj_size_t size, - pjsip_status_line *status_line); + pjsip_status_line *status_line); /** @@ -241,18 +240,18 @@ PJ_DECL(pj_status_t) pjsip_parse_status_line(char *buf, pj_size_t size, * Note that the input string buffer MUST be NULL terminated and have * length at least size+1 (size MUST NOT include the NULL terminator). * - * @param pool The pool to allocate memory. - * @param buf The input buffer, which MUST be NULL terminated. - * @param size The length of the string (not counting NULL terminator). - * @param err_list If this parameter is not NULL, then the parser will - * put error messages during parsing in this list. + * @param pool The pool to allocate memory. + * @param buf The input buffer, which MUST be NULL terminated. + * @param size The length of the string (not counting NULL terminator). + * @param err_list If this parameter is not NULL, then the parser will + * put error messages during parsing in this list. * - * @return The message or NULL when failed. No exception is thrown - * by this function (or any public parser functions). + * @return The message or NULL when failed. No exception is thrown + * by this function (or any public parser functions). */ PJ_DECL(pjsip_msg *) pjsip_parse_msg( pj_pool_t *pool, - char *buf, pj_size_t size, - pjsip_parser_err_report *err_list); + char *buf, pj_size_t size, + pjsip_parser_err_report *err_list); /** @@ -266,8 +265,8 @@ PJ_DECL(pjsip_msg *) pjsip_parse_msg( pj_pool_t *pool, * Note that the input string buffer MUST be NULL terminated and have * length at least size+1 (size MUST NOT include the NULL terminator). * - * @param buf The input buffer, which MUST be NULL terminated. - * @param size The length of the string (not counting NULL terminator). + * @param buf The input buffer, which MUST be NULL terminated. + * @param size The length of the string (not counting NULL terminator). * @param rdata The receive data buffer to store the message and * its elements. * @@ -282,17 +281,17 @@ PJ_DECL(pjsip_msg *) pjsip_parse_rdata( char *buf, pj_size_t size, * Note that the input string buffer MUST be NULL terminated and have * length at least size+1 (size MUST NOT include the NULL terminator). * - * @param buf The input buffer, which must be NULL terminated. - * @param size The length of the string (not counting NULL terminator). - * @param is_datagram Put non-zero if transport is datagram oriented. - * @param msg_size [out] If message is valid, this parameter will contain - * the size of the SIP message (including body, if any). + * @param buf The input buffer, which must be NULL terminated. + * @param size The length of the string (not counting NULL terminator). + * @param is_datagram Put non-zero if transport is datagram oriented. + * @param msg_size [out] If message is valid, this parameter will contain + * the size of the SIP message (including body, if any). * - * @return PJ_SUCCESS if a message is found, or an error code. + * @return PJ_SUCCESS if a message is found, or an error code. */ PJ_DECL(pj_status_t) pjsip_find_msg(const char *buf, pj_size_t size, - pj_bool_t is_datagram, + pj_bool_t is_datagram, pj_size_t *msg_size); /** @@ -303,25 +302,25 @@ PJ_DECL(pj_status_t) pjsip_find_msg(const char *buf, * Note that the input string buffer MUST be NULL terminated and have * length at least size+1 (size MUST NOT include the NULL terminator). * - * @param pool Pool to allocate memory for the header. - * @param hname Header name which is used to find the correct function - * to parse the header. - * @param line Header content, which must be NULL terminated. - * @param size The length of the string (not counting NULL terminator, - * if any). - * @param parsed_len If the value is not NULL, then upon return the function - * will fill the pointer with the length of the string - * that has been parsed. This is usefull for two purposes, - * one is when the string may contain more than one header - * lines, and two when an error happen the value can - * pinpoint the location of the error in the buffer. + * @param pool Pool to allocate memory for the header. + * @param hname Header name which is used to find the correct function + * to parse the header. + * @param line Header content, which must be NULL terminated. + * @param size The length of the string (not counting NULL terminator, + * if any). + * @param parsed_len If the value is not NULL, then upon return the function + * will fill the pointer with the length of the string + * that has been parsed. This is usefull for two purposes, + * one is when the string may contain more than one header + * lines, and two when an error happen the value can + * pinpoint the location of the error in the buffer. * - * @return The instance of the header if parsing was successful, - * or otherwise a NULL pointer will be returned. + * @return The instance of the header if parsing was successful, + * or otherwise a NULL pointer will be returned. */ PJ_DECL(void*) pjsip_parse_hdr( pj_pool_t *pool, const pj_str_t *hname, - char *line, pj_size_t size, - int *parsed_len); + char *line, pj_size_t size, + int *parsed_len); /** * Parse header line(s). Multiple headers can be parsed by this function. @@ -332,23 +331,23 @@ PJ_DECL(void*) pjsip_parse_hdr( pj_pool_t *pool, const pj_str_t *hname, * Note that the input string buffer MUST be NULL terminated and have * length at least size+1 (size MUST NOT include the NULL terminator). * - * @param pool The pool. - * @param input The input text to parse, which must be NULL terminated. - * @param size The text length (not counting NULL terminator). - * @param hlist The header list to store the parsed headers. - * This list must have been initialized before calling - * this function. - * @param options Specify 1 here to make parsing stop when error is - * encountered when parsing the header. Otherwise the - * error is silently ignored and parsing resumes to the - * next line. - * @return zero if successfull, or -1 if error is encountered. - * Upon error, the \a hlist argument MAY contain - * successfully parsed headers. + * @param pool The pool. + * @param input The input text to parse, which must be NULL terminated. + * @param size The text length (not counting NULL terminator). + * @param hlist The header list to store the parsed headers. + * This list must have been initialized before calling + * this function. + * @param options Specify 1 here to make parsing stop when error is + * encountered when parsing the header. Otherwise the + * error is silently ignored and parsing resumes to the + * next line. + * @return zero if successfull, or -1 if error is encountered. + * Upon error, the \a hlist argument MAY contain + * successfully parsed headers. */ PJ_DECL(pj_status_t) pjsip_parse_headers( pj_pool_t *pool, char *input, - pj_size_t size, pjsip_hdr *hlist, - unsigned options); + pj_size_t size, pjsip_hdr *hlist, + unsigned options); /** @@ -368,55 +367,55 @@ PJ_DECL(pj_status_t) pjsip_parse_headers( pj_pool_t *pool, char *input, */ typedef struct pjsip_parser_const_t { - const pj_str_t pjsip_USER_STR; /**< "user" string constant. */ - const pj_str_t pjsip_METHOD_STR; /**< "method" string constant */ - const pj_str_t pjsip_TRANSPORT_STR; /**< "transport" string const. */ - const pj_str_t pjsip_MADDR_STR; /**< "maddr" string const. */ - const pj_str_t pjsip_LR_STR; /**< "lr" string const. */ - const pj_str_t pjsip_SIP_STR; /**< "sip" string constant. */ - const pj_str_t pjsip_SIPS_STR; /**< "sips" string constant. */ - const pj_str_t pjsip_TEL_STR; /**< "tel" string constant. */ - const pj_str_t pjsip_BRANCH_STR; /**< "branch" string constant. */ - const pj_str_t pjsip_TTL_STR; /**< "ttl" string constant. */ - const pj_str_t pjsip_RECEIVED_STR; /**< "received" string const. */ - const pj_str_t pjsip_Q_STR; /**< "q" string constant. */ - const pj_str_t pjsip_EXPIRES_STR; /**< "expires" string constant. */ - const pj_str_t pjsip_TAG_STR; /**< "tag" string constant. */ - const pj_str_t pjsip_RPORT_STR; /**< "rport" string const. */ - - pj_cis_t pjsip_HOST_SPEC; /**< For scanning host part. */ - pj_cis_t pjsip_DIGIT_SPEC; /**< Decimal digits */ - pj_cis_t pjsip_ALPHA_SPEC; /**< Alpha (A-Z, a-z) */ - pj_cis_t pjsip_ALNUM_SPEC; /**< Decimal + Alpha. */ - pj_cis_t pjsip_TOKEN_SPEC; /**< Token. */ - pj_cis_t pjsip_TOKEN_SPEC_ESC; /**< Token without '%' character */ - pj_cis_t pjsip_VIA_PARAM_SPEC; /**< Via param is token + ":" for - IPv6. */ - pj_cis_t pjsip_VIA_PARAM_SPEC_ESC; /**< .. as above without '%' */ - pj_cis_t pjsip_HEX_SPEC; /**< Hexadecimal digits. */ - pj_cis_t pjsip_PARAM_CHAR_SPEC; /**< For scanning pname (or pvalue - when it's not quoted.) in URI */ - pj_cis_t pjsip_PARAM_CHAR_SPEC_ESC; /**< Variant without the escape ('%') - char */ - pj_cis_t pjsip_HDR_CHAR_SPEC; /**< Chars in hname/havalue in URL. */ - pj_cis_t pjsip_HDR_CHAR_SPEC_ESC; /**< Variant without the escape ('%') - char */ - pj_cis_t pjsip_PROBE_USER_HOST_SPEC;/**< Hostname characters. */ - pj_cis_t pjsip_PASSWD_SPEC; /**< Password. */ - pj_cis_t pjsip_PASSWD_SPEC_ESC; /**< Variant without the escape ('%') - char */ - pj_cis_t pjsip_USER_SPEC; /**< User */ - pj_cis_t pjsip_USER_SPEC_ESC; /**< Variant without the escape ('%') - char */ - pj_cis_t pjsip_USER_SPEC_LENIENT; /**< User, with additional '#' char */ + const pj_str_t pjsip_USER_STR; /**< "user" string constant. */ + const pj_str_t pjsip_METHOD_STR; /**< "method" string constant */ + const pj_str_t pjsip_TRANSPORT_STR; /**< "transport" string const. */ + const pj_str_t pjsip_MADDR_STR; /**< "maddr" string const. */ + const pj_str_t pjsip_LR_STR; /**< "lr" string const. */ + const pj_str_t pjsip_SIP_STR; /**< "sip" string constant. */ + const pj_str_t pjsip_SIPS_STR; /**< "sips" string constant. */ + const pj_str_t pjsip_TEL_STR; /**< "tel" string constant. */ + const pj_str_t pjsip_BRANCH_STR; /**< "branch" string constant. */ + const pj_str_t pjsip_TTL_STR; /**< "ttl" string constant. */ + const pj_str_t pjsip_RECEIVED_STR; /**< "received" string const. */ + const pj_str_t pjsip_Q_STR; /**< "q" string constant. */ + const pj_str_t pjsip_EXPIRES_STR; /**< "expires" string constant. */ + const pj_str_t pjsip_TAG_STR; /**< "tag" string constant. */ + const pj_str_t pjsip_RPORT_STR; /**< "rport" string const. */ + + pj_cis_t pjsip_HOST_SPEC; /**< For scanning host part. */ + pj_cis_t pjsip_DIGIT_SPEC; /**< Decimal digits */ + pj_cis_t pjsip_ALPHA_SPEC; /**< Alpha (A-Z, a-z) */ + pj_cis_t pjsip_ALNUM_SPEC; /**< Decimal + Alpha. */ + pj_cis_t pjsip_TOKEN_SPEC; /**< Token. */ + pj_cis_t pjsip_TOKEN_SPEC_ESC; /**< Token without '%' character */ + pj_cis_t pjsip_VIA_PARAM_SPEC; /**< Via param is token + ":" for + IPv6. */ + pj_cis_t pjsip_VIA_PARAM_SPEC_ESC; /**< .. as above without '%' */ + pj_cis_t pjsip_HEX_SPEC; /**< Hexadecimal digits. */ + pj_cis_t pjsip_PARAM_CHAR_SPEC; /**< For scanning pname (or pvalue + when it's not quoted.) in URI */ + pj_cis_t pjsip_PARAM_CHAR_SPEC_ESC; /**< Variant without the escape ('%') + char */ + pj_cis_t pjsip_HDR_CHAR_SPEC; /**< Chars in hname/havalue in URL. */ + pj_cis_t pjsip_HDR_CHAR_SPEC_ESC; /**< Variant without the escape ('%') + char */ + pj_cis_t pjsip_PROBE_USER_HOST_SPEC;/**< Hostname characters. */ + pj_cis_t pjsip_PASSWD_SPEC; /**< Password. */ + pj_cis_t pjsip_PASSWD_SPEC_ESC; /**< Variant without the escape ('%') + char */ + pj_cis_t pjsip_USER_SPEC; /**< User */ + pj_cis_t pjsip_USER_SPEC_ESC; /**< Variant without the escape ('%') + char */ + pj_cis_t pjsip_USER_SPEC_LENIENT; /**< User, with additional '#' char */ pj_cis_t pjsip_USER_SPEC_LENIENT_ESC;/**< pjsip_USER_SPEC_ESC with '#' */ - pj_cis_t pjsip_NOT_NEWLINE; /**< For eating up header, basically - any chars except newlines or - zero. */ - pj_cis_t pjsip_NOT_COMMA_OR_NEWLINE;/**< Array elements. */ - pj_cis_t pjsip_DISPLAY_SPEC; /**< Used when searching for display - name. */ - pj_cis_t pjsip_OTHER_URI_CONTENT; /**< Generic URI content. */ + pj_cis_t pjsip_NOT_NEWLINE; /**< For eating up header, basically + any chars except newlines or + zero. */ + pj_cis_t pjsip_NOT_COMMA_OR_NEWLINE;/**< Array elements. */ + pj_cis_t pjsip_DISPLAY_SPEC; /**< Used when searching for display + name. */ + pj_cis_t pjsip_OTHER_URI_CONTENT; /**< Generic URI content. */ } pjsip_parser_const_t; @@ -441,26 +440,26 @@ enum /** Internal: parse parameter in header (matching the character as token) */ PJ_DECL(void) pjsip_parse_param_imp(pj_scanner *scanner, pj_pool_t *pool, - pj_str_t *pname, pj_str_t *pvalue, - unsigned opt); + pj_str_t *pname, pj_str_t *pvalue, + unsigned opt); /** Internal: parse parameter in URL (matching the character as paramchar) */ PJ_DECL(void) pjsip_parse_uri_param_imp(pj_scanner *scanner, pj_pool_t *pool, - pj_str_t *pname, pj_str_t *pvalue, - unsigned opt); + pj_str_t *pname, pj_str_t *pvalue, + unsigned opt); /** Internal: concatenate parameter */ PJ_DECL(void) pjsip_concat_param_imp(pj_str_t *param, pj_pool_t *pool, - const pj_str_t *pname, - const pj_str_t *pvalue, - int sepchar); + const pj_str_t *pname, + const pj_str_t *pvalue, + int sepchar); /** Internal */ PJ_DECL(void) pjsip_parse_end_hdr_imp ( pj_scanner *scanner ); /** Parse generic array header */ PJ_DECL(void) pjsip_parse_generic_array_hdr_imp(pjsip_generic_array_hdr *hdr, - pj_scanner *scanner); + pj_scanner *scanner); PJ_END_DECL -#endif /* __PJSIP_SIP_PARSER_H__ */ +#endif /* __PJSIP_SIP_PARSER_H__ */ diff --git a/pjsip/include/pjsip/sip_private.h b/pjsip/include/pjsip/sip_private.h index 621ca8fcde..0261b8992f 100644 --- a/pjsip/include/pjsip/sip_private.h +++ b/pjsip/include/pjsip/sip_private.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjsip/include/pjsip/sip_resolve.h b/pjsip/include/pjsip/sip_resolve.h index 188cd315f3..29a690cfce 100644 --- a/pjsip/include/pjsip/sip_resolve.h +++ b/pjsip/include/pjsip/sip_resolve.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -178,25 +177,25 @@ PJ_BEGIN_DECL typedef struct pjsip_server_addresses { /** Number of address records. */ - unsigned count; + unsigned count; /** Address records. */ struct { - /** Preferable transport to be used to contact this address. */ - pjsip_transport_type_e type; + /** Preferable transport to be used to contact this address. */ + pjsip_transport_type_e type; - /** Server priority (the lower the higher the priority). */ - unsigned priority; + /** Server priority (the lower the higher the priority). */ + unsigned priority; - /** Server weight (the higher the more load it can handle). */ - unsigned weight; + /** Server weight (the higher the more load it can handle). */ + unsigned weight; - /** The server's address. */ - pj_sockaddr addr; + /** The server's address. */ + pj_sockaddr addr; - /** Address length. */ - int addr_len; + /** Address length. */ + int addr_len; } entry[PJSIP_MAX_RESOLVED_ADDRESSES]; @@ -207,13 +206,13 @@ typedef struct pjsip_server_addresses * The type of callback function to be called when resolver finishes the job. * * @param status The status of the operation, which is zero on success. - * @param token The token that was associated with the job when application - * call the resolve function. - * @param addr The addresses resolved by the operation. + * @param token The token that was associated with the job when application + * call the resolve function. + * @param addr The addresses resolved by the operation. */ typedef void pjsip_resolver_callback(pj_status_t status, - void *token, - const struct pjsip_server_addresses *addr); + void *token, + const struct pjsip_server_addresses *addr); /** * This structure describes application callback to receive various event from @@ -243,13 +242,13 @@ typedef struct pjsip_ext_resolver * Create SIP resolver engine. Note that this function is normally called * internally by pjsip_endpoint instance. * - * @param pool Pool to allocate memory from. - * @param p_res Pointer to receive SIP resolver instance. + * @param pool Pool to allocate memory from. + * @param p_res Pointer to receive SIP resolver instance. * - * @return PJ_SUCCESS when resolver can be successfully created. + * @return PJ_SUCCESS when resolver can be successfully created. */ PJ_DECL(pj_status_t) pjsip_resolver_create(pj_pool_t *pool, - pjsip_resolver_t **p_res); + pjsip_resolver_t **p_res); /** * Set the DNS resolver instance of the SIP resolver engine. Before the @@ -259,15 +258,15 @@ PJ_DECL(pj_status_t) pjsip_resolver_create(pj_pool_t *pool, * Note that application normally will use #pjsip_endpt_set_resolver() instead * since it does not normally have access to the SIP resolver instance. * - * @param res The SIP resolver engine. + * @param res The SIP resolver engine. * @param dns_res The DNS resolver instance to be used by the SIP resolver. - * This argument can be NULL to reset the internal DNS - * instance. + * This argument can be NULL to reset the internal DNS + * instance. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_resolver_set_resolver(pjsip_resolver_t *res, - pj_dns_resolver *dns_res); + pj_dns_resolver *dns_res); /** @@ -283,14 +282,14 @@ PJ_DECL(pj_status_t) pjsip_resolver_set_resolver(pjsip_resolver_t *res, * * @param res The SIP resolver engine. * @param ext_res The external resolver implementation callback. This argument - * can be NULL to reset the whole external implementation. - * However, it is prohibited to reset individual callback. + * can be NULL to reset the whole external implementation. + * However, it is prohibited to reset individual callback. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_resolver_set_ext_resolver( - pjsip_resolver_t *res, - pjsip_ext_resolver *ext_res); + pjsip_resolver_t *res, + pjsip_ext_resolver *ext_res); /** * Get the DNS resolver instance of the SIP resolver engine. @@ -298,9 +297,9 @@ PJ_DECL(pj_status_t) pjsip_resolver_set_ext_resolver( * Note that application normally will use #pjsip_endpt_get_resolver() instead * since it does not normally have access to the SIP resolver instance. * - * @param res The SIP resolver engine. + * @param res The SIP resolver engine. * - * @return The DNS resolver instance (may be NULL) + * @return The DNS resolver instance (may be NULL) */ PJ_DECL(pj_dns_resolver*) pjsip_resolver_get_resolver(pjsip_resolver_t *res); @@ -325,17 +324,17 @@ PJ_DECL(void) pjsip_resolver_destroy(pjsip_resolver_t *resolver); * Note that application normally will use #pjsip_endpt_resolve() instead * since it does not normally have access to the SIP resolver instance. * - * @param resolver The resolver engine. - * @param pool The pool to allocate resolver job. - * @param target The target specification to be resolved. - * @param token A user defined token to be passed back to callback function. - * @param cb The callback function. + * @param resolver The resolver engine. + * @param pool The pool to allocate resolver job. + * @param target The target specification to be resolved. + * @param token A user defined token to be passed back to callback function. + * @param cb The callback function. */ PJ_DECL(void) pjsip_resolve( pjsip_resolver_t *resolver, - pj_pool_t *pool, - const pjsip_host_info *target, - void *token, - pjsip_resolver_callback *cb); + pj_pool_t *pool, + const pjsip_host_info *target, + void *token, + pjsip_resolver_callback *cb); /** * @} @@ -343,4 +342,4 @@ PJ_DECL(void) pjsip_resolve( pjsip_resolver_t *resolver, PJ_END_DECL -#endif /* __PJSIP_SIP_RESOLVE_H__ */ +#endif /* __PJSIP_SIP_RESOLVE_H__ */ diff --git a/pjsip/include/pjsip/sip_tel_uri.h b/pjsip/include/pjsip/sip_tel_uri.h index 15766e83a5..ac8e2615e1 100644 --- a/pjsip/include/pjsip/sip_tel_uri.h +++ b/pjsip/include/pjsip/sip_tel_uri.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -42,21 +41,21 @@ PJ_BEGIN_DECL */ typedef struct pjsip_tel_uri { - pjsip_uri_vptr *vptr; /**< Pointer to virtual function table. */ - pj_str_t number; /**< Global or local phone number */ - pj_str_t context; /**< Phone context (for local number). */ - pj_str_t ext_param; /**< Extension param. */ - pj_str_t isub_param; /**< ISDN sub-address param. */ - pjsip_param other_param;/**< Other parameter. */ + pjsip_uri_vptr *vptr; /**< Pointer to virtual function table. */ + pj_str_t number; /**< Global or local phone number */ + pj_str_t context; /**< Phone context (for local number). */ + pj_str_t ext_param; /**< Extension param. */ + pj_str_t isub_param; /**< ISDN sub-address param. */ + pjsip_param other_param;/**< Other parameter. */ } pjsip_tel_uri; /** * Create a new tel: URI. * - * @param pool The pool. + * @param pool The pool. * - * @return New instance of tel: URI. + * @return New instance of tel: URI. */ PJ_DECL(pjsip_tel_uri*) pjsip_tel_uri_create(pj_pool_t *pool); @@ -64,11 +63,11 @@ PJ_DECL(pjsip_tel_uri*) pjsip_tel_uri_create(pj_pool_t *pool); * This function compares two numbers for equality, according to rules as * specified in RFC 3966. * - * @param nb1 The first number. - * @param nb2 The second number. + * @param nb1 The first number. + * @param nb2 The second number. * - * @return Zero if equal, -1 if nb1 is less than nb2, or +1 if - * nb1 is greater than nb2. + * @return Zero if equal, -1 if nb1 is less than nb2, or +1 if + * nb1 is greater than nb2. */ PJ_DECL(int) pjsip_tel_nb_cmp(const pj_str_t *nb1, const pj_str_t *nb2); @@ -81,4 +80,4 @@ PJ_END_DECL */ -#endif /* __PJSIP_TEL_URI_H__ */ +#endif /* __PJSIP_TEL_URI_H__ */ diff --git a/pjsip/include/pjsip/sip_transaction.h b/pjsip/include/pjsip/sip_transaction.h index 754b6ea0ac..9f7fee6cae 100644 --- a/pjsip/include/pjsip/sip_transaction.h +++ b/pjsip/include/pjsip/sip_transaction.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -61,15 +60,15 @@ PJ_BEGIN_DECL */ typedef enum pjsip_tsx_state_e { - PJSIP_TSX_STATE_NULL, /**< For UAC, before any message is sent. */ - PJSIP_TSX_STATE_CALLING, /**< For UAC, just after request is sent. */ - PJSIP_TSX_STATE_TRYING, /**< For UAS, just after request is received.*/ - PJSIP_TSX_STATE_PROCEEDING, /**< For UAS/UAC, after provisional response.*/ - PJSIP_TSX_STATE_COMPLETED, /**< For UAS/UAC, after final response. */ - PJSIP_TSX_STATE_CONFIRMED, /**< For UAS, after ACK is received. */ - PJSIP_TSX_STATE_TERMINATED, /**< For UAS/UAC, before it's destroyed. */ - PJSIP_TSX_STATE_DESTROYED, /**< For UAS/UAC, will be destroyed now. */ - PJSIP_TSX_STATE_MAX /**< Number of states. */ + PJSIP_TSX_STATE_NULL, /**< For UAC, before any message is sent. */ + PJSIP_TSX_STATE_CALLING, /**< For UAC, just after request is sent. */ + PJSIP_TSX_STATE_TRYING, /**< For UAS, just after request is received.*/ + PJSIP_TSX_STATE_PROCEEDING, /**< For UAS/UAC, after provisional response.*/ + PJSIP_TSX_STATE_COMPLETED, /**< For UAS/UAC, after final response. */ + PJSIP_TSX_STATE_CONFIRMED, /**< For UAS, after ACK is received. */ + PJSIP_TSX_STATE_TERMINATED, /**< For UAS/UAC, before it's destroyed. */ + PJSIP_TSX_STATE_DESTROYED, /**< For UAS/UAC, will be destroyed now. */ + PJSIP_TSX_STATE_MAX /**< Number of states. */ } pjsip_tsx_state_e; @@ -82,33 +81,33 @@ struct pjsip_transaction /* * Administrivia */ - pj_pool_t *pool; /**< Pool owned by the tsx. */ - pjsip_module *tsx_user; /**< Transaction user. */ - pjsip_endpoint *endpt; /**< Endpoint instance. */ - pj_bool_t terminating; /**< terminate() was called */ - pj_grp_lock_t *grp_lock; /**< Transaction grp lock. */ - pj_mutex_t *mutex_b; /**< Second mutex to avoid - deadlock. It is used to - protect timer. */ + pj_pool_t *pool; /**< Pool owned by the tsx. */ + pjsip_module *tsx_user; /**< Transaction user. */ + pjsip_endpoint *endpt; /**< Endpoint instance. */ + pj_bool_t terminating; /**< terminate() was called */ + pj_grp_lock_t *grp_lock; /**< Transaction grp lock. */ + pj_mutex_t *mutex_b; /**< Second mutex to avoid + deadlock. It is used to + protect timer. */ /* * Transaction identification. */ - char obj_name[PJ_MAX_OBJ_NAME]; /**< Log info. */ - pjsip_role_e role; /**< Role (UAS or UAC) */ - pjsip_method method; /**< The method. */ - pj_int32_t cseq; /**< The CSeq */ - pj_str_t transaction_key;/**< Hash table key. */ - pj_uint32_t hashed_key; /**< Key's hashed value. */ - pj_str_t branch; /**< The branch Id. */ + char obj_name[PJ_MAX_OBJ_NAME]; /**< Log info. */ + pjsip_role_e role; /**< Role (UAS or UAC) */ + pjsip_method method; /**< The method. */ + pj_int32_t cseq; /**< The CSeq */ + pj_str_t transaction_key;/**< Hash table key. */ + pj_uint32_t hashed_key; /**< Key's hashed value. */ + pj_str_t branch; /**< The branch Id. */ /* * State and status. */ - int status_code; /**< Last status code seen. */ - pj_str_t status_text; /**< Last reason phrase. */ - pjsip_tsx_state_e state; /**< State. */ - int handle_200resp; /**< UAS 200/INVITE retrsm.*/ + int status_code; /**< Last status code seen. */ + pj_str_t status_text; /**< Last reason phrase. */ + pjsip_tsx_state_e state; /**< State. */ + int handle_200resp; /**< UAS 200/INVITE retrsm.*/ int tracing; /**< Tracing enabled? */ /** Handler according to current state. */ @@ -117,53 +116,53 @@ struct pjsip_transaction /* * Transport. */ - pjsip_transport *transport; /**< Transport to use. */ - pj_bool_t is_reliable; /**< Transport is reliable. */ - pj_sockaddr addr; /**< Destination address. */ - int addr_len; /**< Address length. */ - pjsip_response_addr res_addr; /**< Response address. */ - unsigned transport_flag; /**< Miscelaneous flag. */ - pj_status_t transport_err; /**< Internal error code. */ - pjsip_tpselector tp_sel; /**< Transport selector. */ - pjsip_tx_data *pending_tx; /**< Tdata which caused - pending transport flag - to be set on tsx. */ + pjsip_transport *transport; /**< Transport to use. */ + pj_bool_t is_reliable; /**< Transport is reliable. */ + pj_sockaddr addr; /**< Destination address. */ + int addr_len; /**< Address length. */ + pjsip_response_addr res_addr; /**< Response address. */ + unsigned transport_flag; /**< Miscelaneous flag. */ + pj_status_t transport_err; /**< Internal error code. */ + pjsip_tpselector tp_sel; /**< Transport selector. */ + pjsip_tx_data *pending_tx; /**< Tdata which caused + pending transport flag + to be set on tsx. */ pjsip_tp_state_listener_key *tp_st_key; /**< Transport state listener - key. */ + key. */ /* * Messages and timer. */ - pjsip_tx_data *last_tx; /**< Msg kept for retrans. */ - int retransmit_count;/**< Retransmission count. */ - pj_timer_entry retransmit_timer;/**< Retransmit timer. */ - pj_timer_entry timeout_timer; /**< Timeout timer. */ + pjsip_tx_data *last_tx; /**< Msg kept for retrans. */ + int retransmit_count;/**< Retransmission count. */ + pj_timer_entry retransmit_timer;/**< Retransmit timer. */ + pj_timer_entry timeout_timer; /**< Timeout timer. */ /** Module specific data. */ - void *mod_data[PJSIP_MAX_MODULE]; + void *mod_data[PJSIP_MAX_MODULE]; }; /** * Create and register transaction layer module to the specified endpoint. * - * @param endpt The endpoint instance. + * @param endpt The endpoint instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_tsx_layer_init_module(pjsip_endpoint *endpt); /** * Get the instance of the transaction layer module. * - * @return The transaction layer module. + * @return The transaction layer module. */ PJ_DECL(pjsip_module*) pjsip_tsx_layer_instance(void); /** * Unregister and destroy transaction layer module. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_tsx_layer_destroy(void); @@ -171,7 +170,7 @@ PJ_DECL(pj_status_t) pjsip_tsx_layer_destroy(void); * Retrieve the current number of transactions currently registered * in the hash table. * - * @return Number of transactions. + * @return Number of transactions. */ PJ_DECL(unsigned) pjsip_tsx_layer_get_tsx_count(void); @@ -183,31 +182,31 @@ PJ_DECL(unsigned) pjsip_tsx_layer_get_tsx_count(void); * #pjsip_tsx_layer_find_tsx2() instead which only adds a reference to * the transaction instead of locking it. * - * @param key The key string to find the transaction. - * @param lock If non-zero, transaction will be locked before the - * function returns, to make sure that it's not deleted - * by other threads. + * @param key The key string to find the transaction. + * @param lock If non-zero, transaction will be locked before the + * function returns, to make sure that it's not deleted + * by other threads. * - * @return The matching transaction instance, or NULL if transaction - * can not be found. + * @return The matching transaction instance, or NULL if transaction + * can not be found. */ PJ_DECL(pjsip_transaction*) pjsip_tsx_layer_find_tsx( const pj_str_t *key, - pj_bool_t lock ); + pj_bool_t lock ); /** * Find a transaction with the specified key. The transaction key normally * is created by calling #pjsip_tsx_create_key() from an incoming message. * - * @param key The key string to find the transaction. + * @param key The key string to find the transaction. * @param add_ref If non-zero, transaction's reference will be added - * by one before the function returns, to make sure that - * it's not deleted by other threads. + * by one before the function returns, to make sure that + * it's not deleted by other threads. * - * @return The matching transaction instance, or NULL if transaction - * can not be found. + * @return The matching transaction instance, or NULL if transaction + * can not be found. */ PJ_DECL(pjsip_transaction*) pjsip_tsx_layer_find_tsx2( const pj_str_t *key, - pj_bool_t add_ref ); + pj_bool_t add_ref ); /** * Create, initialize, and register a new transaction as UAC from the @@ -221,16 +220,16 @@ PJ_DECL(pjsip_transaction*) pjsip_tsx_layer_find_tsx2( const pj_str_t *key, * will be created. * * @param tsx_user Module to be registered as transaction user of the new - * transaction, which will receive notification from the - * transaction via on_tsx_state() callback. + * transaction, which will receive notification from the + * transaction via on_tsx_state() callback. * @param tdata The outgoing request message. - * @param p_tsx On return will contain the new transaction instance. + * @param p_tsx On return will contain the new transaction instance. * * @return PJ_SUCCESS if successfull. */ PJ_DECL(pj_status_t) pjsip_tsx_create_uac( pjsip_module *tsx_user, - pjsip_tx_data *tdata, - pjsip_transaction **p_tsx); + pjsip_tx_data *tdata, + pjsip_transaction **p_tsx); /** * Variant of pjsip_tsx_create_uac() with additional parameter to specify @@ -241,20 +240,20 @@ PJ_DECL(pj_status_t) pjsip_tsx_create_uac( pjsip_module *tsx_user, * See pjsip_tsx_create_uac() for general info about this function. * * @param tsx_user Module to be registered as transaction user of the new - * transaction, which will receive notification from the - * transaction via on_tsx_state() callback. + * transaction, which will receive notification from the + * transaction via on_tsx_state() callback. * @param tdata The outgoing request message. * @param grp_lock Optional group lock to use by this transaction. If - * the value is NULL, the transaction will create its - * own group lock. - * @param p_tsx On return will contain the new transaction instance. + * the value is NULL, the transaction will create its + * own group lock. + * @param p_tsx On return will contain the new transaction instance. * * @return PJ_SUCCESS if successfull. */ PJ_DECL(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user, - pjsip_tx_data *tdata, - pj_grp_lock_t *grp_lock, - pjsip_transaction **p_tsx); + pjsip_tx_data *tdata, + pj_grp_lock_t *grp_lock, + pjsip_transaction **p_tsx); /** * Create, initialize, and register a new transaction as UAS from the @@ -263,16 +262,16 @@ PJ_DECL(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user, * moves from state NULL. * * @param tsx_user Module to be registered as transaction user of the new - * transaction, which will receive notification from the - * transaction via on_tsx_state() callback. + * transaction, which will receive notification from the + * transaction via on_tsx_state() callback. * @param rdata The received incoming request. - * @param p_tsx On return will contain the new transaction instance. + * @param p_tsx On return will contain the new transaction instance. * - * @return PJ_SUCCESS if successfull. + * @return PJ_SUCCESS if successfull. */ PJ_DECL(pj_status_t) pjsip_tsx_create_uas( pjsip_module *tsx_user, - pjsip_rx_data *rdata, - pjsip_transaction **p_tsx ); + pjsip_rx_data *rdata, + pjsip_transaction **p_tsx ); /** * Variant of pjsip_tsx_create_uas() with additional parameter to specify @@ -283,35 +282,35 @@ PJ_DECL(pj_status_t) pjsip_tsx_create_uas( pjsip_module *tsx_user, * See pjsip_tsx_create_uas() for general info about this function. * * @param tsx_user Module to be registered as transaction user of the new - * transaction, which will receive notification from the - * transaction via on_tsx_state() callback. + * transaction, which will receive notification from the + * transaction via on_tsx_state() callback. * @param rdata The received incoming request. * @param grp_lock Optional group lock to use by this transaction. If - * the value is NULL, the transaction will create its - * own group lock. - * @param p_tsx On return will contain the new transaction instance. + * the value is NULL, the transaction will create its + * own group lock. + * @param p_tsx On return will contain the new transaction instance. * - * @return PJ_SUCCESS if successfull. + * @return PJ_SUCCESS if successfull. */ PJ_DECL(pj_status_t) pjsip_tsx_create_uas2(pjsip_module *tsx_user, - pjsip_rx_data *rdata, - pj_grp_lock_t *grp_lock, - pjsip_transaction **p_tsx ); + pjsip_rx_data *rdata, + pj_grp_lock_t *grp_lock, + pjsip_transaction **p_tsx ); /** * Lock/bind transaction to a specific transport/listener. This is optional, * as normally transport will be selected automatically based on the * destination of the message upon resolver completion. * - * @param tsx The transaction. - * @param sel Transport selector containing the specification of - * transport or listener to be used by this transaction - * to send requests. + * @param tsx The transaction. + * @param sel Transport selector containing the specification of + * transport or listener to be used by this transaction + * to send requests. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tsx_set_transport(pjsip_transaction *tsx, - const pjsip_tpselector *sel); + const pjsip_tpselector *sel); /** * Call this function to manually feed a message to the transaction. @@ -324,11 +323,11 @@ PJ_DECL(pj_status_t) pjsip_tsx_set_transport(pjsip_transaction *tsx, * is passed to this function, then on_rx_response() will also be called * before on_tsx_state(). * - * @param tsx The transaction. - * @param rdata The message. + * @param tsx The transaction. + * @param rdata The message. */ PJ_DECL(void) pjsip_tsx_recv_msg( pjsip_transaction *tsx, - pjsip_rx_data *rdata); + pjsip_rx_data *rdata); /** * Transmit message in tdata with this transaction. It is possible to @@ -341,13 +340,13 @@ PJ_DECL(void) pjsip_tsx_recv_msg( pjsip_transaction *tsx, * * @param tsx The transaction. * @param tdata The outgoing message. If NULL is specified, then the - * last message transmitted (or the message specified - * in UAC initialization) will be sent. + * last message transmitted (or the message specified + * in UAC initialization) will be sent. * - * @return PJ_SUCCESS if successfull. + * @return PJ_SUCCESS if successfull. */ PJ_DECL(pj_status_t) pjsip_tsx_send_msg( pjsip_transaction *tsx, - pjsip_tx_data *tdata); + pjsip_tx_data *tdata); /** @@ -356,16 +355,16 @@ PJ_DECL(pj_status_t) pjsip_tsx_send_msg( pjsip_transaction *tsx, * TU wants to maintain the retransmision by itself (for example, * retransmitting reliable provisional response). * - * @param tsx The transaction. + * @param tsx The transaction. * @param tdata The outgoing message. If NULL is specified, then the - * last message transmitted (or the message specified - * in UAC initialization) will be sent. + * last message transmitted (or the message specified + * in UAC initialization) will be sent. * * - * @return PJ_SUCCESS if successful. + * @return PJ_SUCCESS if successful. */ PJ_DECL(pj_status_t) pjsip_tsx_retransmit_no_state(pjsip_transaction *tsx, - pjsip_tx_data *tdata); + pjsip_tx_data *tdata); /** @@ -381,10 +380,10 @@ PJ_DECL(pj_status_t) pjsip_tsx_retransmit_no_state(pjsip_transaction *tsx, * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tsx_create_key( pj_pool_t *pool, - pj_str_t *key, - pjsip_role_e role, - const pjsip_method *method, - const pjsip_rx_data *rdata ); + pj_str_t *key, + pjsip_role_e role, + const pjsip_method *method, + const pjsip_rx_data *rdata ); /** * Force terminate transaction. @@ -393,7 +392,7 @@ PJ_DECL(pj_status_t) pjsip_tsx_create_key( pj_pool_t *pool, * @param code The status code to report. */ PJ_DECL(pj_status_t) pjsip_tsx_terminate( pjsip_transaction *tsx, - int code ); + int code ); /** @@ -433,7 +432,7 @@ PJ_DECL(pj_status_t) pjsip_tsx_stop_retransmit(pjsip_transaction *tsx); * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tsx_set_timeout(pjsip_transaction *tsx, - unsigned millisec); + unsigned millisec); /** * Change timer values used by transaction layer. Currently scheduled @@ -457,10 +456,10 @@ PJ_DECL(void) pjsip_tsx_initialize_timer_values(void); * has a corresponding transaction, this function will return non NULL * value. * - * @param rdata The incoming message buffer. + * @param rdata The incoming message buffer. * - * @return The transaction instance associated with this message, - * or NULL if the message doesn't match any transactions. + * @return The transaction instance associated with this message, + * or NULL if the message doesn't match any transactions. */ PJ_DECL(pjsip_transaction*) pjsip_rdata_get_tsx( pjsip_rx_data *rdata ); @@ -480,18 +479,18 @@ PJ_DECL(void) pjsip_tsx_layer_dump(pj_bool_t detail); /** * Get the string name for the state. - * @param state State + * @param state State */ PJ_DECL(const char *) pjsip_tsx_state_str(pjsip_tsx_state_e state); /** * Get the role name. - * @param role Role. + * @param role Role. */ PJ_DECL(const char *) pjsip_role_name(pjsip_role_e role); PJ_END_DECL -#endif /* __PJSIP_TRANSACT_H__ */ +#endif /* __PJSIP_TRANSACT_H__ */ diff --git a/pjsip/include/pjsip/sip_transport.h b/pjsip/include/pjsip/sip_transport.h index 6d2a4cb8f7..87f982c8e9 100644 --- a/pjsip/include/pjsip/sip_transport.h +++ b/pjsip/include/pjsip/sip_transport.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -69,24 +68,24 @@ typedef struct pjsip_tpfactory pjsip_tpfactory; */ enum pjsip_transport_flags_e { - PJSIP_TRANSPORT_RELIABLE = 1, /**< Transport is reliable. */ - PJSIP_TRANSPORT_SECURE = 2, /**< Transport is secure. */ - PJSIP_TRANSPORT_DATAGRAM = 4 /**< Datagram based transport. - (it's also assumed to be - connectionless) */ + PJSIP_TRANSPORT_RELIABLE = 1, /**< Transport is reliable. */ + PJSIP_TRANSPORT_SECURE = 2, /**< Transport is secure. */ + PJSIP_TRANSPORT_DATAGRAM = 4 /**< Datagram based transport. + (it's also assumed to be + connectionless) */ }; /** * Check if transport tp is reliable. */ -#define PJSIP_TRANSPORT_IS_RELIABLE(tp) \ - ((tp)->flag & PJSIP_TRANSPORT_RELIABLE) +#define PJSIP_TRANSPORT_IS_RELIABLE(tp) \ + ((tp)->flag & PJSIP_TRANSPORT_RELIABLE) /** * Check if transport tp is secure. */ -#define PJSIP_TRANSPORT_IS_SECURE(tp) \ - ((tp)->flag & PJSIP_TRANSPORT_SECURE) +#define PJSIP_TRANSPORT_IS_SECURE(tp) \ + ((tp)->flag & PJSIP_TRANSPORT_SECURE) /** * Register new transport type to PJSIP. The PJSIP transport framework @@ -96,30 +95,30 @@ enum pjsip_transport_flags_e * about the new transport type to PJSIP by calling this function. * * @param tp_flag The flags describing characteristics of this - * transport type. + * transport type. * @param tp_name Transport type name. * @param def_port Default port to be used for the transport. * @param p_tp_type On successful registration, it will be filled with - * the registered type. This argument is optional. + * the registered type. This argument is optional. * - * @return PJ_SUCCESS if registration is successful, or - * PJSIP_ETYPEEXISTS if the same transport type has - * already been registered. + * @return PJ_SUCCESS if registration is successful, or + * PJSIP_ETYPEEXISTS if the same transport type has + * already been registered. */ PJ_DECL(pj_status_t) pjsip_transport_register_type(unsigned tp_flag, - const char *tp_name, - int def_port, - int *p_tp_type); + const char *tp_name, + int def_port, + int *p_tp_type); /** * Get the transport type from the transport name. * - * @param name Transport name, such as "TCP", or "UDP". + * @param name Transport name, such as "TCP", or "UDP". * - * @return The transport type, or PJSIP_TRANSPORT_UNSPECIFIED if - * the name is not recognized as the name of supported - * transport. + * @return The transport type, or PJSIP_TRANSPORT_UNSPECIFIED if + * the name is not recognized as the name of supported + * transport. */ PJ_DECL(pjsip_transport_type_e) pjsip_transport_get_type_from_name(const pj_str_t *name); @@ -127,9 +126,9 @@ pjsip_transport_get_type_from_name(const pj_str_t *name); /** * Get the transport type for the specified flags. * - * @param flag The transport flag. + * @param flag The transport flag. * - * @return Transport type. + * @return Transport type. */ PJ_DECL(pjsip_transport_type_e) pjsip_transport_get_type_from_flag(unsigned flag); @@ -137,18 +136,18 @@ pjsip_transport_get_type_from_flag(unsigned flag); /** * Get the socket address family of a given transport type. * - * @param type Transport type. + * @param type Transport type. * - * @return Transport type. + * @return Transport type. */ PJ_DECL(int) pjsip_transport_type_get_af(pjsip_transport_type_e type); /** * Get transport flag from type. * - * @param type Transport type. + * @param type Transport type. * - * @return Transport flags. + * @return Transport flags. */ PJ_DECL(unsigned) pjsip_transport_get_flag_from_type( pjsip_transport_type_e type ); @@ -156,10 +155,10 @@ pjsip_transport_get_flag_from_type( pjsip_transport_type_e type ); /** * Get the default SIP port number for the specified type. * - * @param type Transport type. + * @param type Transport type. * - * @return The port number, which is the default SIP port number for - * the specified type. + * @return The port number, which is the default SIP port number for + * the specified type. */ PJ_DECL(int) pjsip_transport_get_default_port_for_type(pjsip_transport_type_e type); @@ -167,18 +166,18 @@ pjsip_transport_get_default_port_for_type(pjsip_transport_type_e type); /** * Get transport type name. * - * @param t Transport type. + * @param t Transport type. * - * @return Transport name. + * @return Transport name. */ PJ_DECL(const char*) pjsip_transport_get_type_name(pjsip_transport_type_e t); /** * Get longer description for the specified transport type. * - * @param t Transport type. + * @param t Transport type. * - * @return Transport description. + * @return Transport description. */ PJ_DECL(const char*) pjsip_transport_get_type_desc(pjsip_transport_type_e t); @@ -243,9 +242,9 @@ typedef struct pjsip_tpselector /** Union representing the transport/listener criteria to be used. */ union { - pjsip_transport *transport; - pjsip_tpfactory *listener; - void *ptr; + pjsip_transport *transport; + pjsip_tpfactory *listener; + void *ptr; } u; } pjsip_tpselector; @@ -256,14 +255,14 @@ typedef struct pjsip_tpselector * transport/listener from being destroyed while application still has * reference to it. * - * @param sel The transport selector. + * @param sel The transport selector. */ PJ_DECL(void) pjsip_tpselector_add_ref(pjsip_tpselector *sel); /** * Decrement transport/listener reference in the selector. - * @param sel The transport selector + * @param sel The transport selector */ PJ_DECL(void) pjsip_tpselector_dec_ref(pjsip_tpselector *sel); @@ -280,8 +279,8 @@ PJ_DECL(void) pjsip_tpselector_dec_ref(pjsip_tpselector *sel); */ typedef struct pjsip_rx_data_op_key { - pj_ioqueue_op_key_t op_key; /**< ioqueue op_key. */ - pjsip_rx_data *rdata; /**< rdata associated with this */ + pj_ioqueue_op_key_t op_key; /**< ioqueue op_key. */ + pjsip_rx_data *rdata; /**< rdata associated with this */ } pjsip_rx_data_op_key; @@ -301,17 +300,17 @@ struct pjsip_rx_data */ struct { - /** Memory pool for this buffer. */ - pj_pool_t *pool; + /** Memory pool for this buffer. */ + pj_pool_t *pool; - /** The transport object which received this packet. */ - pjsip_transport *transport; + /** The transport object which received this packet. */ + pjsip_transport *transport; - /** Other transport specific data to be attached to this buffer. */ - void *tp_data; + /** Other transport specific data to be attached to this buffer. */ + void *tp_data; - /** Ioqueue key. */ - pjsip_rx_data_op_key op_key; + /** Ioqueue key. */ + pjsip_rx_data_op_key op_key; } tp_info; @@ -322,29 +321,29 @@ struct pjsip_rx_data */ struct { - /** Time when the message was received. */ - pj_time_val timestamp; + /** Time when the message was received. */ + pj_time_val timestamp; - /** Pointer to the original packet. */ - char packet[PJSIP_MAX_PKT_LEN]; + /** Pointer to the original packet. */ + char packet[PJSIP_MAX_PKT_LEN]; - /** Zero termination for the packet. */ - pj_uint32_t zero; + /** Zero termination for the packet. */ + pj_uint32_t zero; - /** The length of the packet received. */ - pj_ssize_t len; + /** The length of the packet received. */ + pj_ssize_t len; - /** The source address from which the packet was received. */ - pj_sockaddr src_addr; + /** The source address from which the packet was received. */ + pj_sockaddr src_addr; - /** The length of the source address. */ - int src_addr_len; + /** The length of the source address. */ + int src_addr_len; - /** The IP source address string (NULL terminated). */ - char src_name[PJ_INET6_ADDRSTRLEN]; + /** The IP source address string (NULL terminated). */ + char src_name[PJ_INET6_ADDRSTRLEN]; - /** The IP source port number. */ - int src_port; + /** The IP source port number. */ + int src_port; } pkt_info; @@ -355,64 +354,64 @@ struct pjsip_rx_data */ struct { - /** Start of msg buffer. */ - char *msg_buf; + /** Start of msg buffer. */ + char *msg_buf; - /** Length fo message. */ - int len; + /** Length fo message. */ + int len; - /** The parsed message, if any. */ - pjsip_msg *msg; + /** The parsed message, if any. */ + pjsip_msg *msg; - /** Short description about the message. - * Application should use #pjsip_rx_data_get_info() instead. - */ - char *info; + /** Short description about the message. + * Application should use #pjsip_rx_data_get_info() instead. + */ + char *info; - /** The Call-ID header as found in the message. */ - pjsip_cid_hdr *cid; + /** The Call-ID header as found in the message. */ + pjsip_cid_hdr *cid; - /** The From header as found in the message. */ - pjsip_from_hdr *from; + /** The From header as found in the message. */ + pjsip_from_hdr *from; - /** The To header as found in the message. */ - pjsip_to_hdr *to; + /** The To header as found in the message. */ + pjsip_to_hdr *to; - /** The topmost Via header as found in the message. */ - pjsip_via_hdr *via; + /** The topmost Via header as found in the message. */ + pjsip_via_hdr *via; - /** The CSeq header as found in the message. */ - pjsip_cseq_hdr *cseq; + /** The CSeq header as found in the message. */ + pjsip_cseq_hdr *cseq; - /** Max forwards header. */ - pjsip_max_fwd_hdr *max_fwd; + /** Max forwards header. */ + pjsip_max_fwd_hdr *max_fwd; - /** The first route header. */ - pjsip_route_hdr *route; + /** The first route header. */ + pjsip_route_hdr *route; - /** The first record-route header. */ - pjsip_rr_hdr *record_route; + /** The first record-route header. */ + pjsip_rr_hdr *record_route; - /** Content-type header. */ - pjsip_ctype_hdr *ctype; + /** Content-type header. */ + pjsip_ctype_hdr *ctype; - /** Content-length header. */ - pjsip_clen_hdr *clen; + /** Content-length header. */ + pjsip_clen_hdr *clen; - /** "Require" header containing aggregates of all Require - * headers found in the message, or NULL. - */ - pjsip_require_hdr *require; + /** "Require" header containing aggregates of all Require + * headers found in the message, or NULL. + */ + pjsip_require_hdr *require; - /** "Supported" header containing aggregates of all Supported - * headers found in the message, or NULL. - */ - pjsip_supported_hdr *supported; + /** "Supported" header containing aggregates of all Supported + * headers found in the message, or NULL. + */ + pjsip_supported_hdr *supported; - /** The list of error generated by the parser when parsing - this message. - */ - pjsip_parser_err_report parse_err; + /** The list of error generated by the parser when parsing + this message. + */ + pjsip_parser_err_report parse_err; } msg_info; @@ -423,10 +422,10 @@ struct pjsip_rx_data */ struct { - /** - * Data attached by modules to this message. - */ - void *mod_data[PJSIP_MAX_MODULE]; + /** + * Data attached by modules to this message. + */ + void *mod_data[PJSIP_MAX_MODULE]; } endpt_info; @@ -435,9 +434,9 @@ struct pjsip_rx_data /** * Get printable information about the message in the rdata. * - * @param rdata The receive data buffer. + * @param rdata The receive data buffer. * - * @return Printable information. + * @return Printable information. */ PJ_DECL(char*) pjsip_rx_data_get_info(pjsip_rx_data *rdata); @@ -452,11 +451,11 @@ PJ_DECL(char*) pjsip_rx_data_get_info(pjsip_rx_data *rdata); * perform deep clone of the \a msg_info parts of the rdata, and * fills the \a endpt_info (i.e. the \a mod_data) with zeros. * - * @param src The source to be cloned. - * @param flags Optional flags. Must be zero for now. + * @param src The source to be cloned. + * @param flags Optional flags. Must be zero for now. * @param p_rdata Pointer to receive the cloned rdata. * - * @return PJ_SUCCESS on success or the appropriate error. + * @return PJ_SUCCESS on success or the appropriate error. */ PJ_DECL(pj_status_t) pjsip_rx_data_clone(const pjsip_rx_data *src, unsigned flags, @@ -471,9 +470,9 @@ PJ_DECL(pj_status_t) pjsip_rx_data_clone(const pjsip_rx_data *src, * This function will free the memory used by the pjsip_rx_data and * decrement the transport reference counter. * - * @param rdata The receive data buffer. + * @param rdata The receive data buffer. * - * @return PJ_SUCCESS on success or the appropriate error. + * @return PJ_SUCCESS on success or the appropriate error. */ PJ_DECL(pj_status_t) pjsip_rx_data_free_cloned(pjsip_rx_data *rdata); @@ -490,18 +489,18 @@ PJ_DECL(pj_status_t) pjsip_rx_data_free_cloned(pjsip_rx_data *rdata); typedef struct pjsip_tx_data_op_key { /** ioqueue pending operation key. */ - pj_ioqueue_op_key_t key; + pj_ioqueue_op_key_t key; /** Transmit data associated with this key. */ - pjsip_tx_data *tdata; + pjsip_tx_data *tdata; /** Arbitrary token (attached by transport) */ - void *token; + void *token; /** Callback to be called when pending transmit operation has completed. */ - void (*callback)(pjsip_transport*,void*,pj_ssize_t); + void (*callback)(pjsip_transport*,void*,pj_ssize_t); } pjsip_tx_data_op_key; @@ -525,40 +524,40 @@ struct pjsip_tx_data PJ_DECL_LIST_MEMBER(struct pjsip_tx_data); /** Memory pool for this buffer. */ - pj_pool_t *pool; + pj_pool_t *pool; /** A name to identify this buffer. */ - char obj_name[PJ_MAX_OBJ_NAME]; + char obj_name[PJ_MAX_OBJ_NAME]; /** Short information describing this buffer and the message in it. * Application should use #pjsip_tx_data_get_info() instead of * directly accessing this member. */ - char *info; + char *info; /** For response message, this contains the reference to timestamp when * the original request message was received. The value of this field * is set when application creates response message to a request by * calling #pjsip_endpt_create_response. */ - pj_time_val rx_timestamp; + pj_time_val rx_timestamp; /** The transport manager for this buffer. */ - pjsip_tpmgr *mgr; + pjsip_tpmgr *mgr; /** Ioqueue asynchronous operation key. */ pjsip_tx_data_op_key op_key; /** Lock object. */ - pj_lock_t *lock; + pj_lock_t *lock; /** The message in this buffer. */ - pjsip_msg *msg; + pjsip_msg *msg; /** Strict route header saved by #pjsip_process_route_set(), to be * restored by #pjsip_restore_strict_route_set(). */ - pjsip_route_hdr *saved_strict_route; + pjsip_route_hdr *saved_strict_route; /** Buffer to the printed text representation of the message. When the * content of this buffer is set, then the transport will send the content @@ -566,19 +565,19 @@ struct pjsip_tx_data * message structure has changed, then application must invalidate this * buffer by calling #pjsip_tx_data_invalidate_msg. */ - pjsip_buffer buf; + pjsip_buffer buf; /** Reference counter. */ - pj_atomic_t *ref_cnt; + pj_atomic_t *ref_cnt; /** Being processed by transport? */ - int is_pending; + int is_pending; /** Transport manager internal. */ - void *token; + void *token; - /** Callback to be called when this tx_data has been transmitted. */ - void (*cb)(void*, pjsip_tx_data*, pj_ssize_t); + /** Callback to be called when this tx_data has been transmitted. */ + void (*cb)(void*, pjsip_tx_data*, pj_ssize_t); /** Destination information, to be used to determine the network address * of the message. For a request, this information is initialized when @@ -590,17 +589,17 @@ struct pjsip_tx_data */ struct { - /** Server name. - */ - pj_str_t name; + /** Server name. + */ + pj_str_t name; - /** Server addresses resolved. - */ - pjsip_server_addresses addr; + /** Server addresses resolved. + */ + pjsip_server_addresses addr; - /** Current server address being tried. - */ - unsigned cur_addr; + /** Current server address being tried. + */ + unsigned cur_addr; } dest_info; @@ -609,11 +608,11 @@ struct pjsip_tx_data */ struct { - pjsip_transport *transport; /**< Transport being used. */ - pj_sockaddr dst_addr; /**< Destination address. */ - int dst_addr_len; /**< Length of address. */ - char dst_name[PJ_INET6_ADDRSTRLEN]; /**< Destination address. */ - int dst_port; /**< Destination port. */ + pjsip_transport *transport; /**< Transport being used. */ + pj_sockaddr dst_addr; /**< Destination address. */ + int dst_addr_len; /**< Length of address. */ + char dst_name[PJ_INET6_ADDRSTRLEN]; /**< Destination address. */ + int dst_port; /**< Destination port. */ } tp_info; /** @@ -621,27 +620,27 @@ struct pjsip_tx_data * The value here must be set with pjsip_tx_data_set_transport(), * to allow reference counter to be set properly. */ - pjsip_tpselector tp_sel; + pjsip_tpselector tp_sel; /** * Special flag to indicate that this transmit data is a request that has * been updated with proper authentication response and is ready to be * sent for retry. */ - pj_bool_t auth_retry; + pj_bool_t auth_retry; /** * Arbitrary data attached by PJSIP modules. */ - void *mod_data[PJSIP_MAX_MODULE]; + void *mod_data[PJSIP_MAX_MODULE]; /** * If via_addr is set, it will be used as the "sent-by" field of the * Via header for outgoing requests as long as the request uses via_tp * transport. Normally application should not use or access these fields. */ - pjsip_host_port via_addr; /**< Via address. */ - const void *via_tp; /**< Via transport. */ + pjsip_host_port via_addr; /**< Via address. */ + const void *via_tp; /**< Via transport. */ }; @@ -649,22 +648,22 @@ struct pjsip_tx_data * Create a new, blank transmit buffer. The reference count is initialized * to zero. * - * @param mgr The transport manager. - * @param tdata Pointer to receive transmit data. + * @param mgr The transport manager. + * @param tdata Pointer to receive transmit data. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. * * @see pjsip_endpt_create_tdata */ PJ_DECL(pj_status_t) pjsip_tx_data_create( pjsip_tpmgr *mgr, - pjsip_tx_data **tdata ); + pjsip_tx_data **tdata ); /** * Add reference counter to the transmit buffer. The reference counter controls * the life time of the buffer, ie. when the counter reaches zero, then it * will be destroyed. * - * @param tdata The transmit buffer. + * @param tdata The transmit buffer. */ PJ_DECL(void) pjsip_tx_data_add_ref( pjsip_tx_data *tdata ); @@ -673,10 +672,10 @@ PJ_DECL(void) pjsip_tx_data_add_ref( pjsip_tx_data *tdata ); * When the transmit buffer is no longer used, it will be destroyed and * caller is informed with PJSIP_EBUFDESTROYED return status. * - * @param tdata The transmit buffer data. - * @return This function will always succeeded eventhough the return - * status is non-zero. A status PJSIP_EBUFDESTROYED will be - * returned to inform that buffer is destroyed. + * @param tdata The transmit buffer data. + * @return This function will always succeeded eventhough the return + * status is non-zero. A status PJSIP_EBUFDESTROYED will be + * returned to inform that buffer is destroyed. */ PJ_DECL(pj_status_t) pjsip_tx_data_dec_ref( pjsip_tx_data *tdata ); @@ -685,17 +684,17 @@ PJ_DECL(pj_status_t) pjsip_tx_data_dec_ref( pjsip_tx_data *tdata ); * may allocate memory for the buffer, if the buffer has not been allocated * yet, and encode the SIP message to that buffer. * - * @param tdata The transmit buffer. + * @param tdata The transmit buffer. * - * @return PJ_SUCCESS on success of the appropriate error code. + * @return PJ_SUCCESS on success of the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tx_data_encode(pjsip_tx_data *tdata); /** * Check if transmit data buffer contains a valid message. * - * @param tdata The transmit buffer. - * @return Non-zero (PJ_TRUE) if buffer contains a valid message. + * @param tdata The transmit buffer. + * @return Non-zero (PJ_TRUE) if buffer contains a valid message. */ PJ_DECL(pj_bool_t) pjsip_tx_data_is_valid( pjsip_tx_data *tdata ); @@ -707,7 +706,7 @@ PJ_DECL(pj_bool_t) pjsip_tx_data_is_valid( pjsip_tx_data *tdata ); * the message to be re-printed, unless application invalidates the buffer * by calling this function. * - * @param tdata The transmit buffer. + * @param tdata The transmit buffer. */ PJ_DECL(void) pjsip_tx_data_invalidate_msg( pjsip_tx_data *tdata ); @@ -715,9 +714,9 @@ PJ_DECL(void) pjsip_tx_data_invalidate_msg( pjsip_tx_data *tdata ); * Get short printable info about the transmit data. This will normally return * short information about the message. * - * @param tdata The transmit buffer. + * @param tdata The transmit buffer. * - * @return Null terminated info string. + * @return Null terminated info string. */ PJ_DECL(char*) pjsip_tx_data_get_info( pjsip_tx_data *tdata ); @@ -727,13 +726,13 @@ PJ_DECL(char*) pjsip_tx_data_get_info( pjsip_tx_data *tdata ); * pjsip_tsx_set_transport() and pjsip_dlg_set_transport() instead (which * will call this function). * - * @param tdata The transmit buffer. - * @param sel Transport selector. + * @param tdata The transmit buffer. + * @param sel Transport selector. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_tx_data_set_transport(pjsip_tx_data *tdata, - const pjsip_tpselector *sel); + const pjsip_tpselector *sel); /** * Clone pjsip_tx_data. This will duplicate the message contents of @@ -742,11 +741,11 @@ PJ_DECL(pj_status_t) pjsip_tx_data_set_transport(pjsip_tx_data *tdata, * it must release it by calling #pjsip_tx_data_dec_ref(). * Currently, this will only clone response message. * - * @param src The source to be cloned. - * @param flags Optional flags. Must be zero for now. + * @param src The source to be cloned. + * @param flags Optional flags. Must be zero for now. * @param p_rdata Pointer to receive the cloned tdata. * - * @return PJ_SUCCESS on success or the appropriate error. + * @return PJ_SUCCESS on success or the appropriate error. */ PJ_DECL(pj_status_t) pjsip_tx_data_clone(const pjsip_tx_data *src, unsigned flags, @@ -771,12 +770,12 @@ typedef struct pjsip_transport_key /** * Transport type. */ - long type; + long type; /** * Destination address. */ - pj_sockaddr rem_addr; + pj_sockaddr rem_addr; } pjsip_transport_key; @@ -786,15 +785,15 @@ typedef struct pjsip_transport_key */ typedef enum pjsip_transport_dir { - PJSIP_TP_DIR_NONE, /**< Direction not set, normally used by - connectionless transports such as - UDP transport. */ - PJSIP_TP_DIR_OUTGOING, /**< Outgoing connection or client mode, - this is only for connection-oriented - transports. */ - PJSIP_TP_DIR_INCOMING, /**< Incoming connection or server mode, - this is only for connection-oriented - transports. */ + PJSIP_TP_DIR_NONE, /**< Direction not set, normally used by + connectionless transports such as + UDP transport. */ + PJSIP_TP_DIR_OUTGOING, /**< Outgoing connection or client mode, + this is only for connection-oriented + transports. */ + PJSIP_TP_DIR_INCOMING, /**< Incoming connection or server mode, + this is only for connection-oriented + transports. */ } pjsip_transport_dir; @@ -805,73 +804,73 @@ typedef enum pjsip_transport_dir */ struct pjsip_transport { - char obj_name[PJ_MAX_OBJ_NAME]; /**< Name. */ + char obj_name[PJ_MAX_OBJ_NAME]; /**< Name. */ - pj_pool_t *pool; /**< Pool used by transport. */ - pj_atomic_t *ref_cnt; /**< Reference counter. */ - pj_lock_t *lock; /**< Lock object. */ - pj_grp_lock_t *grp_lock; /**< Group lock for sync with - ioqueue and timer. */ - pj_bool_t tracing; /**< Tracing enabled? */ - pj_bool_t is_shutdown; /**< Being shutdown? */ - pj_bool_t is_destroying; /**< Destroy in progress? */ + pj_pool_t *pool; /**< Pool used by transport. */ + pj_atomic_t *ref_cnt; /**< Reference counter. */ + pj_lock_t *lock; /**< Lock object. */ + pj_grp_lock_t *grp_lock; /**< Group lock for sync with + ioqueue and timer. */ + pj_bool_t tracing; /**< Tracing enabled? */ + pj_bool_t is_shutdown; /**< Being shutdown? */ + pj_bool_t is_destroying; /**< Destroy in progress? */ /** Key for indexing this transport in hash table. */ - pjsip_transport_key key; + pjsip_transport_key key; - char *type_name; /**< Type name. */ - unsigned flag; /**< #pjsip_transport_flags_e */ - char *info; /**< Transport info/description.*/ + char *type_name; /**< Type name. */ + unsigned flag; /**< #pjsip_transport_flags_e */ + char *info; /**< Transport info/description.*/ - int addr_len; /**< Length of addresses. */ - pj_sockaddr local_addr; /**< Bound address. */ - pjsip_host_port local_name; /**< Published name (eg. STUN). */ - pjsip_host_port remote_name; /**< Remote address name. */ - pjsip_transport_dir dir; /**< Connection direction. */ + int addr_len; /**< Length of addresses. */ + pj_sockaddr local_addr; /**< Bound address. */ + pjsip_host_port local_name; /**< Published name (eg. STUN). */ + pjsip_host_port remote_name; /**< Remote address name. */ + pjsip_transport_dir dir; /**< Connection direction. */ - pjsip_endpoint *endpt; /**< Endpoint instance. */ - pjsip_tpmgr *tpmgr; /**< Transport manager. */ - pjsip_tpfactory *factory; /**< Factory instance. Note: it - may be invalid/shutdown. */ - pj_timer_entry idle_timer; /**< Timer when ref cnt is zero.*/ + pjsip_endpoint *endpt; /**< Endpoint instance. */ + pjsip_tpmgr *tpmgr; /**< Transport manager. */ + pjsip_tpfactory *factory; /**< Factory instance. Note: it + may be invalid/shutdown. */ + pj_timer_entry idle_timer; /**< Timer when ref cnt is zero.*/ - pj_timestamp last_recv_ts; /**< Last time receiving data. */ - pj_size_t last_recv_len; /**< Last received data length. */ + pj_timestamp last_recv_ts; /**< Last time receiving data. */ + pj_size_t last_recv_len; /**< Last received data length. */ - void *data; /**< Internal transport data. */ + void *data; /**< Internal transport data. */ /** * Function to be called by transport manager to send SIP message. * - * @param transport The transport to send the message. - * @param packet The buffer to send. - * @param length The length of the buffer to send. - * @param op_key Completion token, which will be supplied to - * caller when pending send operation completes. - * @param rem_addr The remote destination address. - * @param addr_len Size of remote address. - * @param callback If supplied, the callback will be called - * once a pending transmission has completed. If - * the function completes immediately (i.e. return - * code is not PJ_EPENDING), the callback will not - * be called. + * @param transport The transport to send the message. + * @param packet The buffer to send. + * @param length The length of the buffer to send. + * @param op_key Completion token, which will be supplied to + * caller when pending send operation completes. + * @param rem_addr The remote destination address. + * @param addr_len Size of remote address. + * @param callback If supplied, the callback will be called + * once a pending transmission has completed. If + * the function completes immediately (i.e. return + * code is not PJ_EPENDING), the callback will not + * be called. * - * @return Should return PJ_SUCCESS only if data has been - * succesfully queued to operating system for - * transmission. Otherwise it may return PJ_EPENDING - * if the underlying transport can not send the - * data immediately and will send it later, which in - * this case caller doesn't have to do anything - * except wait the calback to be called, if it - * supplies one. - * Other return values indicate the error code. + * @return Should return PJ_SUCCESS only if data has been + * succesfully queued to operating system for + * transmission. Otherwise it may return PJ_EPENDING + * if the underlying transport can not send the + * data immediately and will send it later, which in + * this case caller doesn't have to do anything + * except wait the calback to be called, if it + * supplies one. + * Other return values indicate the error code. */ pj_status_t (*send_msg)(pjsip_transport *transport, - pjsip_tx_data *tdata, - const pj_sockaddr_t *rem_addr, - int addr_len, - void *token, - pjsip_transport_callback callback); + pjsip_tx_data *tdata, + const pj_sockaddr_t *rem_addr, + int addr_len, + void *token, + pjsip_transport_callback callback); /** * Instruct the transport to initiate graceful shutdown procedure. @@ -880,9 +879,9 @@ struct pjsip_transport * * Note that application MUST use #pjsip_transport_shutdown() instead. * - * @param transport The transport. + * @param transport The transport. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ pj_status_t (*do_shutdown)(pjsip_transport *transport); @@ -893,9 +892,9 @@ struct pjsip_transport * transport itself) who know what they're doing. Application should use * #pjsip_transport_shutdown() instead. * - * @param transport The transport. + * @param transport The transport. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ pj_status_t (*destroy)(pjsip_transport *transport); @@ -910,13 +909,13 @@ struct pjsip_transport * is normally called by the transport instance when it is created * by application. * - * @param mgr The transport manager. - * @param tp The new transport to be registered. + * @param mgr The transport manager. + * @param tp The new transport to be registered. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_transport_register( pjsip_tpmgr *mgr, - pjsip_transport *tp ); + pjsip_transport *tp ); /** @@ -928,9 +927,9 @@ PJ_DECL(pj_status_t) pjsip_transport_register( pjsip_tpmgr *mgr, * After all objects release their reference to this transport, * the transport will be destroyed immediately. * - * @param tp The transport. + * @param tp The transport. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_transport_shutdown(pjsip_transport *tp); @@ -942,14 +941,14 @@ PJ_DECL(pj_status_t) pjsip_transport_shutdown(pjsip_transport *tp); * use the transport anymore. In either case, transport will * only be destroyed after all objects release their references. * - * @param tp The transport. - * @param force Force transport to immediately send - * disconnection state notification. + * @param tp The transport. + * @param force Force transport to immediately send + * disconnection state notification. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_transport_shutdown2(pjsip_transport *tp, - pj_bool_t force); + pj_bool_t force); /** * Destroy a transport when there is no object currently uses the transport. @@ -957,11 +956,11 @@ PJ_DECL(pj_status_t) pjsip_transport_shutdown2(pjsip_transport *tp, * transport itself. Application should use #pjsip_transport_shutdown() * instead. * - * @param tp The transport instance. + * @param tp The transport instance. * - * @return PJ_SUCCESS on success or the appropriate error code. - * Some of possible errors are PJSIP_EBUSY if the - * transport's reference counter is not zero. + * @return PJ_SUCCESS on success or the appropriate error code. + * Some of possible errors are PJSIP_EBUSY if the + * transport's reference counter is not zero. */ PJ_DECL(pj_status_t) pjsip_transport_destroy( pjsip_transport *tp); @@ -970,9 +969,9 @@ PJ_DECL(pj_status_t) pjsip_transport_destroy( pjsip_transport *tp); * to keep the reference of the transport MUST increment the transport's * reference counter to prevent it from being destroyed. * - * @param tp The transport instance. + * @param tp The transport instance. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_transport_add_ref( pjsip_transport *tp ); @@ -984,9 +983,9 @@ PJ_DECL(pj_status_t) pjsip_transport_add_ref( pjsip_transport *tp ); * transport if no objects acquire the reference counter during the idle * interval. * - * @param tp The transport instance. + * @param tp The transport instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_transport_dec_ref( pjsip_transport *tp ); @@ -997,22 +996,22 @@ PJ_DECL(pj_status_t) pjsip_transport_dec_ref( pjsip_transport *tp ); * parse all SIP messages in the packet, and for each parsed SIP message, it * would report the message to the SIP endpoint (#pjsip_endpoint). * - * @param mgr The transport manager instance. - * @param rdata The receive data buffer containing the packet. The - * transport MUST fully initialize tp_info and pkt_info - * member of the rdata. + * @param mgr The transport manager instance. + * @param rdata The receive data buffer containing the packet. The + * transport MUST fully initialize tp_info and pkt_info + * member of the rdata. * - * @return The number of bytes successfully processed from the - * packet. If the transport is datagram oriented, the - * value will be equal to the size of the packet. For - * stream oriented transport (e.g. TCP, TLS), the value - * returned may be less than the packet size, if - * partial message is received. The transport then MUST - * keep the remainder part and report it again to - * this function once more data/packet is received. + * @return The number of bytes successfully processed from the + * packet. If the transport is datagram oriented, the + * value will be equal to the size of the packet. For + * stream oriented transport (e.g. TCP, TLS), the value + * returned may be less than the packet size, if + * partial message is received. The transport then MUST + * keep the remainder part and report it again to + * this function once more data/packet is received. */ PJ_DECL(pj_ssize_t) pjsip_tpmgr_receive_packet(pjsip_tpmgr *mgr, - pjsip_rx_data *rdata); + pjsip_rx_data *rdata); /***************************************************************************** @@ -1035,18 +1034,18 @@ struct pjsip_tpfactory /** This list is managed by transport manager. */ PJ_DECL_LIST_MEMBER(struct pjsip_tpfactory); - char obj_name[PJ_MAX_OBJ_NAME]; /**< Name. */ + char obj_name[PJ_MAX_OBJ_NAME]; /**< Name. */ - pj_pool_t *pool; /**< Owned memory pool. */ - pj_lock_t *lock; /**< Lock object. */ + pj_pool_t *pool; /**< Owned memory pool. */ + pj_lock_t *lock; /**< Lock object. */ - pjsip_transport_type_e type; /**< Transport type. */ - char *type_name; /**< Type string name. */ - unsigned flag; /**< Transport flag. */ - char *info; /**< Transport info/description.*/ + pjsip_transport_type_e type; /**< Transport type. */ + char *type_name; /**< Type string name. */ + unsigned flag; /**< Transport flag. */ + char *info; /**< Transport info/description.*/ - pj_sockaddr local_addr; /**< Bound address. */ - pjsip_host_port addr_name; /**< Published name. */ + pj_sockaddr local_addr; /**< Bound address. */ + pjsip_host_port addr_name; /**< Published name. */ /** * Create new outbound connection suitable for sending SIP message @@ -1055,11 +1054,11 @@ struct pjsip_tpfactory * transport and registering it to the transport manager. */ pj_status_t (*create_transport)(pjsip_tpfactory *factory, - pjsip_tpmgr *mgr, - pjsip_endpoint *endpt, - const pj_sockaddr *rem_addr, - int addr_len, - pjsip_transport **transport); + pjsip_tpmgr *mgr, + pjsip_endpoint *endpt, + const pj_sockaddr *rem_addr, + int addr_len, + pjsip_transport **transport); /** * Create new outbound connection suitable for sending SIP message @@ -1069,12 +1068,12 @@ struct pjsip_tpfactory * transport and registering it to the transport manager. */ pj_status_t (*create_transport2)(pjsip_tpfactory *factory, - pjsip_tpmgr *mgr, - pjsip_endpoint *endpt, - const pj_sockaddr *rem_addr, - int addr_len, - pjsip_tx_data *tdata, - pjsip_transport **transport); + pjsip_tpmgr *mgr, + pjsip_endpoint *endpt, + const pj_sockaddr *rem_addr, + int addr_len, + pjsip_tx_data *tdata, + pjsip_transport **transport); /** * Destroy the listener. @@ -1091,24 +1090,24 @@ struct pjsip_tpfactory /** * Register a transport factory. * - * @param mgr The transport manager. - * @param tpf Transport factory. + * @param mgr The transport manager. + * @param tpf Transport factory. * - * @return PJ_SUCCESS if listener was successfully created. + * @return PJ_SUCCESS if listener was successfully created. */ PJ_DECL(pj_status_t) pjsip_tpmgr_register_tpfactory(pjsip_tpmgr *mgr, - pjsip_tpfactory *tpf); + pjsip_tpfactory *tpf); /** * Unregister factory. * - * @param mgr The transport manager. - * @param tpf Transport factory. + * @param mgr The transport manager. + * @param tpf Transport factory. * - * @return PJ_SUCCESS is sucessfully unregistered. + * @return PJ_SUCCESS is sucessfully unregistered. */ PJ_DECL(pj_status_t) pjsip_tpmgr_unregister_tpfactory(pjsip_tpmgr *mgr, - pjsip_tpfactory *tpf); + pjsip_tpfactory *tpf); /***************************************************************************** @@ -1121,19 +1120,19 @@ PJ_DECL(pj_status_t) pjsip_tpmgr_unregister_tpfactory(pjsip_tpmgr *mgr, * Type of callback to be called when transport manager receives incoming * SIP message. * - * @param ep Endpoint. + * @param ep Endpoint. * @param status Receiption status. - * @param rd Received packet. + * @param rd Received packet. */ typedef void (*pjsip_rx_callback)(pjsip_endpoint *ep, pj_status_t status, - pjsip_rx_data *rd); + pjsip_rx_data *rd); /** * Type of callback to be called before transport manager is about * to transmit SIP message. * - * @param ep Endpoint. - * @param td Transmit data. + * @param ep Endpoint. + * @param td Transmit data. */ typedef pj_status_t (*pjsip_tx_callback)(pjsip_endpoint *ep, pjsip_tx_data*td); @@ -1142,20 +1141,20 @@ typedef pj_status_t (*pjsip_tx_callback)(pjsip_endpoint *ep, pjsip_tx_data*td); * this function directly, since a transport manager will be created and * destroyed automatically by the SIP endpoint. * - * @param pool Pool. - * @param endpt Endpoint instance. - * @param rx_cb Callback to receive incoming message. - * @param tx_cb Callback to be called before transport manager is sending - * outgoing message. - * @param p_mgr Pointer to receive the new transport manager. + * @param pool Pool. + * @param endpt Endpoint instance. + * @param rx_cb Callback to receive incoming message. + * @param tx_cb Callback to be called before transport manager is sending + * outgoing message. + * @param p_mgr Pointer to receive the new transport manager. * - * @return PJ_SUCCESS or the appropriate error code on error. + * @return PJ_SUCCESS or the appropriate error code on error. */ PJ_DECL(pj_status_t) pjsip_tpmgr_create( pj_pool_t *pool, - pjsip_endpoint * endpt, - pjsip_rx_callback rx_cb, - pjsip_tx_callback tx_cb, - pjsip_tpmgr **p_mgr); + pjsip_endpoint * endpt, + pjsip_rx_callback rx_cb, + pjsip_tx_callback tx_cb, + pjsip_tpmgr **p_mgr); /** @@ -1169,21 +1168,21 @@ PJ_DECL(pj_status_t) pjsip_tpmgr_create( pj_pool_t *pool, * * @see pjsip_tpmgr_find_local_addr2() * - * @param tpmgr The transport manager. - * @param pool Pool to allocate memory for the IP address. - * @param type Destination address to contact. - * @param sel Optional pointer to prefered transport, if any. + * @param tpmgr The transport manager. + * @param pool Pool to allocate memory for the IP address. + * @param type Destination address to contact. + * @param sel Optional pointer to prefered transport, if any. * @param ip_addr Pointer to receive the IP address. - * @param port Pointer to receive the port number. + * @param port Pointer to receive the port number. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tpmgr_find_local_addr( pjsip_tpmgr *tpmgr, - pj_pool_t *pool, - pjsip_transport_type_e type, - const pjsip_tpselector *sel, - pj_str_t *ip_addr, - int *port); + pj_pool_t *pool, + pjsip_transport_type_e type, + const pjsip_tpselector *sel, + pj_str_t *ip_addr, + int *port); /** * Parameter for pjsip_tpmgr_find_local_addr2() function. @@ -1193,47 +1192,47 @@ typedef struct pjsip_tpmgr_fla2_param /** * Specify transport type to use. This must be set. */ - pjsip_transport_type_e tp_type; + pjsip_transport_type_e tp_type; /** * Optional pointer to preferred transport, if any. */ - const pjsip_tpselector *tp_sel; + const pjsip_tpselector *tp_sel; /** * Destination host, if known. The destination host is needed * if \a local_if field below is set. */ - pj_str_t dst_host; + pj_str_t dst_host; /** * Specify if the function should return which local interface * to use for the specified destination in \a dst_host. By definition, * the returned address will always be local interface address. */ - pj_bool_t local_if; + pj_bool_t local_if; /** * The returned address. */ - pj_str_t ret_addr; + pj_str_t ret_addr; /** * The returned port. */ - pj_uint16_t ret_port; + pj_uint16_t ret_port; /** * Returned pointer to the transport. Only set if local_if is set. */ - const void *ret_tp; + const void *ret_tp; } pjsip_tpmgr_fla2_param; /** * Initialize with default values. * - * @param prm The parameter to be initialized. + * @param prm The parameter to be initialized. */ PJ_DECL(void) pjsip_tpmgr_fla2_param_default(pjsip_tpmgr_fla2_param *prm); @@ -1245,11 +1244,11 @@ PJ_DECL(void) pjsip_tpmgr_fla2_param_default(pjsip_tpmgr_fla2_param *prm); * * @see pjsip_tpmgr_find_local_addr() * - * @param tpmgr The transport manager. - * @param pool Pool to allocate memory for the IP address. - * @param prm Function input and output parameters. + * @param tpmgr The transport manager. + * @param pool Pool to allocate memory for the IP address. + * @param prm Function input and output parameters. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tpmgr_find_local_addr2(pjsip_tpmgr *tpmgr, pj_pool_t *pool, @@ -1259,9 +1258,9 @@ PJ_DECL(pj_status_t) pjsip_tpmgr_find_local_addr2(pjsip_tpmgr *tpmgr, * Return number of transports currently registered to the transport * manager. * - * @param mgr The transport manager. + * @param mgr The transport manager. * - * @return Number of transports. + * @return Number of transports. */ PJ_DECL(unsigned) pjsip_tpmgr_get_transport_count(pjsip_tpmgr *mgr); @@ -1271,9 +1270,9 @@ PJ_DECL(unsigned) pjsip_tpmgr_get_transport_count(pjsip_tpmgr *mgr); * this function directly, since a transport manager will be created and * destroyed automatically by the SIP endpoint. * - * @param mgr The transport manager. + * @param mgr The transport manager. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_tpmgr_destroy(pjsip_tpmgr *mgr); @@ -1281,7 +1280,7 @@ PJ_DECL(pj_status_t) pjsip_tpmgr_destroy(pjsip_tpmgr *mgr); /** * Dump transport info and status to log. * - * @param mgr The transport manager. + * @param mgr The transport manager. */ PJ_DECL(void) pjsip_tpmgr_dump_transports(pjsip_tpmgr *mgr); @@ -1301,22 +1300,22 @@ PJ_DECL(void) pjsip_tpmgr_dump_transports(pjsip_tpmgr *mgr); * to transport manager. Application should use pjsip_endpt_acquire_transport() * instead. * - * @param mgr The transport manager instance. - * @param type The type of transport to be acquired. + * @param mgr The transport manager instance. + * @param type The type of transport to be acquired. * @param remote The remote address to send message to. * @param addr_len Length of the remote address. - * @param sel Optional pointer to transport selector instance which is - * used to find explicit transport, if required. - * @param tp Pointer to receive the transport instance, if one is found. + * @param sel Optional pointer to transport selector instance which is + * used to find explicit transport, if required. + * @param tp Pointer to receive the transport instance, if one is found. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tpmgr_acquire_transport(pjsip_tpmgr *mgr, - pjsip_transport_type_e type, - const pj_sockaddr_t *remote, - int addr_len, - const pjsip_tpselector *sel, - pjsip_transport **tp); + pjsip_transport_type_e type, + const pj_sockaddr_t *remote, + int addr_len, + const pjsip_tpselector *sel, + pjsip_transport **tp); /** * Find suitable transport for sending SIP message to specified remote @@ -1327,68 +1326,68 @@ PJ_DECL(pj_status_t) pjsip_tpmgr_acquire_transport(pjsip_tpmgr *mgr, * to transport manager. Application should use pjsip_endpt_acquire_transport2() * instead. * - * @param mgr The transport manager instance. - * @param type The type of transport to be acquired. + * @param mgr The transport manager instance. + * @param type The type of transport to be acquired. * @param remote The remote address to send message to. * @param addr_len Length of the remote address. - * @param sel Optional pointer to transport selector instance which is - * used to find explicit transport, if required. - * @param tdata Optional pointer to data to be sent. - * @param tp Pointer to receive the transport instance, if one is found. + * @param sel Optional pointer to transport selector instance which is + * used to find explicit transport, if required. + * @param tdata Optional pointer to data to be sent. + * @param tp Pointer to receive the transport instance, if one is found. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tpmgr_acquire_transport2(pjsip_tpmgr *mgr, - pjsip_transport_type_e type, - const pj_sockaddr_t *remote, - int addr_len, - const pjsip_tpselector *sel, - pjsip_tx_data *tdata, - pjsip_transport **tp); + pjsip_transport_type_e type, + const pj_sockaddr_t *remote, + int addr_len, + const pjsip_tpselector *sel, + pjsip_tx_data *tdata, + pjsip_transport **tp); /** * Type of callback to receive notification when message or raw data * has been sent. * - * @param token The token that was given when calling the function - * to send message or raw data. - * @param tdata The transmit buffer used to send the message. - * @param bytes_sent Number of bytes sent. On success, the value will be - * positive number indicating the number of bytes sent. - * On failure, the value will be a negative number of - * the error code (i.e. bytes_sent = -status). + * @param token The token that was given when calling the function + * to send message or raw data. + * @param tdata The transmit buffer used to send the message. + * @param bytes_sent Number of bytes sent. On success, the value will be + * positive number indicating the number of bytes sent. + * On failure, the value will be a negative number of + * the error code (i.e. bytes_sent = -status). */ typedef void (*pjsip_tp_send_callback)(void *token, pjsip_tx_data *tdata, - pj_ssize_t bytes_sent); + pj_ssize_t bytes_sent); /** * This is a low-level function to send a SIP message using the specified * transport to the specified destination. * - * @param tr The SIP transport to be used. - * @param tdata Transmit data buffer containing SIP message. - * @param addr Destination address. + * @param tr The SIP transport to be used. + * @param tdata Transmit data buffer containing SIP message. + * @param addr Destination address. * @param addr_len Length of destination address. - * @param token Arbitrary token to be returned back to callback. - * @param cb Optional callback to be called to notify caller about - * the completion status of the pending send operation. - * - * @return If the message has been sent successfully, this function - * will return PJ_SUCCESS and the callback will not be - * called. If message cannot be sent immediately, this - * function will return PJ_EPENDING, and application will - * be notified later about the completion via the callback. - * Any statuses other than PJ_SUCCESS or PJ_EPENDING - * indicates immediate failure, and in this case the - * callback will not be called. + * @param token Arbitrary token to be returned back to callback. + * @param cb Optional callback to be called to notify caller about + * the completion status of the pending send operation. + * + * @return If the message has been sent successfully, this function + * will return PJ_SUCCESS and the callback will not be + * called. If message cannot be sent immediately, this + * function will return PJ_EPENDING, and application will + * be notified later about the completion via the callback. + * Any statuses other than PJ_SUCCESS or PJ_EPENDING + * indicates immediate failure, and in this case the + * callback will not be called. */ PJ_DECL(pj_status_t) pjsip_transport_send( pjsip_transport *tr, - pjsip_tx_data *tdata, - const pj_sockaddr_t *addr, - int addr_len, - void *token, - pjsip_tp_send_callback cb); + pjsip_tx_data *tdata, + const pj_sockaddr_t *addr, + int addr_len, + void *token, + pjsip_tp_send_callback cb); /** @@ -1396,43 +1395,43 @@ PJ_DECL(pj_status_t) pjsip_transport_send( pjsip_transport *tr, * * See also #pjsip_endpt_send_raw() and #pjsip_endpt_send_raw_to_uri(). * - * @param mgr Transport manager. + * @param mgr Transport manager. * @param tp_type Transport type. - * @param sel Optional pointer to transport selector instance if - * application wants to use a specific transport instance - * rather then letting transport manager finds the suitable - * transport. - * @param tdata Optional transmit data buffer to be used. If this value - * is NULL, this function will create one internally. If - * tdata is specified, this function will decrement the - * reference counter upon completion. + * @param sel Optional pointer to transport selector instance if + * application wants to use a specific transport instance + * rather then letting transport manager finds the suitable + * transport. + * @param tdata Optional transmit data buffer to be used. If this value + * is NULL, this function will create one internally. If + * tdata is specified, this function will decrement the + * reference counter upon completion. * @param raw_data The data to be sent. * @param data_len The length of the data. - * @param addr Destination address. + * @param addr Destination address. * @param addr_len Length of destination address. - * @param token Arbitrary token to be returned back to callback. - * @param cb Optional callback to be called to notify caller about - * the completion status of the pending send operation. - * - * @return If the message has been sent successfully, this function - * will return PJ_SUCCESS and the callback will not be - * called. If message cannot be sent immediately, this - * function will return PJ_EPENDING, and application will - * be notified later about the completion via the callback. - * Any statuses other than PJ_SUCCESS or PJ_EPENDING - * indicates immediate failure, and in this case the - * callback will not be called. + * @param token Arbitrary token to be returned back to callback. + * @param cb Optional callback to be called to notify caller about + * the completion status of the pending send operation. + * + * @return If the message has been sent successfully, this function + * will return PJ_SUCCESS and the callback will not be + * called. If message cannot be sent immediately, this + * function will return PJ_EPENDING, and application will + * be notified later about the completion via the callback. + * Any statuses other than PJ_SUCCESS or PJ_EPENDING + * indicates immediate failure, and in this case the + * callback will not be called. */ PJ_DECL(pj_status_t) pjsip_tpmgr_send_raw(pjsip_tpmgr *mgr, - pjsip_transport_type_e tp_type, - const pjsip_tpselector *sel, - pjsip_tx_data *tdata, - const void *raw_data, - pj_size_t data_len, - const pj_sockaddr_t *addr, - int addr_len, - void *token, - pjsip_tp_send_callback cb); + pjsip_transport_type_e tp_type, + const pjsip_tpselector *sel, + pjsip_tx_data *tdata, + const void *raw_data, + pj_size_t data_len, + const pj_sockaddr_t *addr, + int addr_len, + void *token, + pjsip_tp_send_callback cb); /** @@ -1440,12 +1439,12 @@ PJ_DECL(pj_status_t) pjsip_tpmgr_send_raw(pjsip_tpmgr *mgr, */ typedef enum pjsip_transport_state { - PJSIP_TP_STATE_CONNECTED, /**< Transport connected, applicable only - to connection-oriented transports - such as TCP and TLS. */ + PJSIP_TP_STATE_CONNECTED, /**< Transport connected, applicable only + to connection-oriented transports + such as TCP and TLS. */ PJSIP_TP_STATE_DISCONNECTED, /**< Transport disconnected, applicable - only to connection-oriented - transports such as TCP and TLS. */ + only to connection-oriented + transports such as TCP and TLS. */ PJSIP_TP_STATE_SHUTDOWN, /**< Transport shutdown, either due to TCP/TLS disconnect error from the network, or when shutdown @@ -1467,18 +1466,18 @@ typedef struct pjsip_transport_state_info { /** * The last error code related to the transport state. */ - pj_status_t status; + pj_status_t status; /** * Optional extended info, the content is specific for each transport type. */ - void *ext_info; + void *ext_info; /** * Optional user data. In global transport state notification, this will * always be NULL. */ - void *user_data; + void *user_data; } pjsip_transport_state_info; @@ -1488,14 +1487,14 @@ typedef struct pjsip_transport_state_info { * transport connected/disconnected. Application may shutdown the transport * in this callback. * - * @param tp The transport instance. - * @param state The transport state. - * @param info The transport state info. + * @param tp The transport instance. + * @param state The transport state. + * @param info The transport state info. */ typedef void (*pjsip_tp_state_callback)( - pjsip_transport *tp, - pjsip_transport_state state, - const pjsip_transport_state_info *info); + pjsip_transport *tp, + pjsip_transport_state state, + const pjsip_transport_state_info *info); /** @@ -1509,59 +1508,59 @@ typedef void (*pjsip_tp_state_callback)( * concerns about the transport state will no longer receive transport state * events. * - * @param mgr Transport manager. - * @param cb Callback to be called to notify caller about transport - * state changing. + * @param mgr Transport manager. + * @param cb Callback to be called to notify caller about transport + * state changing. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tpmgr_set_state_cb(pjsip_tpmgr *mgr, - pjsip_tp_state_callback cb); + pjsip_tp_state_callback cb); /** * Get the callback of global transport state notification. * - * @param mgr Transport manager. + * @param mgr Transport manager. * - * @return The transport state callback or NULL if it is not set. + * @return The transport state callback or NULL if it is not set. */ PJ_DECL(pjsip_tp_state_callback) pjsip_tpmgr_get_state_cb( - const pjsip_tpmgr *mgr); + const pjsip_tpmgr *mgr); /** * Add a listener to the specified transport for transport state notification. * - * @param tp The transport. - * @param cb Callback to be called to notify listener about transport - * state changing. + * @param tp The transport. + * @param cb Callback to be called to notify listener about transport + * state changing. * @param user_data The user data. - * @param key Output key, used to remove this listener. + * @param key Output key, used to remove this listener. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_transport_add_state_listener ( - pjsip_transport *tp, - pjsip_tp_state_callback cb, - void *user_data, - pjsip_tp_state_listener_key **key); + pjsip_transport *tp, + pjsip_tp_state_callback cb, + void *user_data, + pjsip_tp_state_listener_key **key); /** * Remove a listener from the specified transport for transport state * notification. * - * @param tp The transport. - * @param key The listener key. + * @param tp The transport. + * @param key The listener key. * @param user_data The user data, for validation purpose. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_transport_remove_state_listener ( - pjsip_transport *tp, - pjsip_tp_state_listener_key *key, - const void *user_data); + pjsip_transport *tp, + pjsip_tp_state_listener_key *key, + const void *user_data); /** @@ -1577,7 +1576,7 @@ typedef struct pjsip_tp_dropped_data /** * The data. */ - void *data; + void *data; /** * The data length. @@ -1588,7 +1587,7 @@ typedef struct pjsip_tp_dropped_data * wishes to use the same transport for SIP signalling and non-SIP * purposes (such as SIP outbound using STUN message). */ - pj_size_t len; + pj_size_t len; /** * The status or reason of drop. For example, a leading newlines (common @@ -1596,7 +1595,7 @@ typedef struct pjsip_tp_dropped_data * SIP message will have status PJSIP_EINVALIDMSG, a SIP message overflow * will have status PJSIP_ERXOVERFLOW. */ - pj_status_t status; + pj_status_t status; } pjsip_tp_dropped_data; @@ -1604,7 +1603,7 @@ typedef struct pjsip_tp_dropped_data /** * Type of callback to data dropping notifications. * - * @param data The dropped data. + * @param data The dropped data. */ typedef void (*pjsip_tp_on_rx_dropped_cb)(pjsip_tp_dropped_data *data); @@ -1616,13 +1615,13 @@ typedef void (*pjsip_tp_on_rx_dropped_cb)(pjsip_tp_dropped_data *data); * for example, to implement custom keep-alive mechanism or connection * availability detection. * - * @param mgr Transport manager. - * @param cb The callback function, set to NULL to reset the callback. + * @param mgr Transport manager. + * @param cb The callback function, set to NULL to reset the callback. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tpmgr_set_drop_data_cb(pjsip_tpmgr *mgr, - pjsip_tp_on_rx_dropped_cb cb); + pjsip_tp_on_rx_dropped_cb cb); /** @@ -1632,5 +1631,5 @@ PJ_DECL(pj_status_t) pjsip_tpmgr_set_drop_data_cb(pjsip_tpmgr *mgr, PJ_END_DECL -#endif /* __PJSIP_SIP_TRANSPORT_H__ */ +#endif /* __PJSIP_SIP_TRANSPORT_H__ */ diff --git a/pjsip/include/pjsip/sip_transport_loop.h b/pjsip/include/pjsip/sip_transport_loop.h index 9bb760b890..6568cd3f82 100644 --- a/pjsip/include/pjsip/sip_transport_loop.h +++ b/pjsip/include/pjsip/sip_transport_loop.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -45,29 +44,29 @@ PJ_BEGIN_DECL /** * Create and start datagram loop transport. * - * @param endpt The endpoint instance. - * @param transport Pointer to receive the transport instance. + * @param endpt The endpoint instance. + * @param transport Pointer to receive the transport instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_loop_start( pjsip_endpoint *endpt, - pjsip_transport **transport); + pjsip_transport **transport); /** * Enable/disable flag to discard any packets sent using the specified * loop transport. * - * @param tp The loop transport. - * @param discard If non-zero, any outgoing packets will be discarded. - * @param prev_value Optional argument to receive previous value of - * the discard flag. + * @param tp The loop transport. + * @param discard If non-zero, any outgoing packets will be discarded. + * @param prev_value Optional argument to receive previous value of + * the discard flag. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_loop_set_discard( pjsip_transport *tp, - pj_bool_t discard, - pj_bool_t *prev_value ); + pj_bool_t discard, + pj_bool_t *prev_value ); /** @@ -76,20 +75,20 @@ PJ_DECL(pj_status_t) pjsip_loop_set_discard( pjsip_transport *tp, * callback. If error is to be notified via callback, then the notification * will occur after some delay, which is controlled by #pjsip_loop_set_delay(). * - * @param tp The loop transport. - * @param fail_flag If set to 1, the transport will return fail to deliver - * the message. If delay is zero, failure will occur - * immediately; otherwise it will be reported in callback. - * If set to zero, the transport will successfully deliver - * the packet. - * @param prev_value Optional argument to receive previous value of - * the failure flag. + * @param tp The loop transport. + * @param fail_flag If set to 1, the transport will return fail to deliver + * the message. If delay is zero, failure will occur + * immediately; otherwise it will be reported in callback. + * If set to zero, the transport will successfully deliver + * the packet. + * @param prev_value Optional argument to receive previous value of + * the failure flag. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_loop_set_failure( pjsip_transport *tp, - int fail_flag, - int *prev_value ); + int fail_flag, + int *prev_value ); /** @@ -97,44 +96,44 @@ PJ_DECL(pj_status_t) pjsip_loop_set_failure( pjsip_transport *tp, * of the loop transport. This will also * control the delay for error notification callback. * - * @param tp The loop transport. - * @param delay Delay, in miliseconds. - * @param prev_value Optional argument to receive previous value of the - * delay. + * @param tp The loop transport. + * @param delay Delay, in miliseconds. + * @param prev_value Optional argument to receive previous value of the + * delay. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_loop_set_recv_delay( pjsip_transport *tp, - unsigned delay, - unsigned *prev_value); + unsigned delay, + unsigned *prev_value); /** * Set delay (in miliseconds) before send notification is delivered to sender. * This will also control the delay for error notification callback. * - * @param tp The loop transport. - * @param delay Delay, in miliseconds. - * @param prev_value Optional argument to receive previous value of the - * delay. + * @param tp The loop transport. + * @param delay Delay, in miliseconds. + * @param prev_value Optional argument to receive previous value of the + * delay. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_loop_set_send_callback_delay( pjsip_transport *tp, - unsigned delay, - unsigned *prev_value); + unsigned delay, + unsigned *prev_value); /** * Set both receive and send notification delay. * - * @param tp The loop transport. - * @param delay Delay, in miliseconds. + * @param tp The loop transport. + * @param delay Delay, in miliseconds. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_loop_set_delay( pjsip_transport *tp, - unsigned delay ); + unsigned delay ); PJ_END_DECL @@ -143,5 +142,5 @@ PJ_END_DECL * @} */ -#endif /* __PJSIP_TRANSPORT_LOOP_H__ */ +#endif /* __PJSIP_TRANSPORT_LOOP_H__ */ diff --git a/pjsip/include/pjsip/sip_transport_tcp.h b/pjsip/include/pjsip/sip_transport_tcp.h index c0c133f86d..9cd396dc00 100644 --- a/pjsip/include/pjsip/sip_transport_tcp.h +++ b/pjsip/include/pjsip/sip_transport_tcp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -55,26 +54,26 @@ typedef struct pjsip_tcp_transport_cfg * Address family to use. Valid values are pj_AF_INET() and * pj_AF_INET6(). Default is pj_AF_INET(). */ - int af; + int af; /** * Optional address to bind the socket to. Default is to bind to * PJ_INADDR_ANY and to any available port. */ - pj_sockaddr bind_addr; + pj_sockaddr bind_addr; /** * Should SO_REUSEADDR be used for the listener socket. * Default value is PJSIP_TCP_TRANSPORT_REUSEADDR. */ - pj_bool_t reuse_addr; + pj_bool_t reuse_addr; /** * Optional published address, which is the address to be * advertised as the address of this SIP transport. * By default the bound address will be used as the published address. */ - pjsip_host_port addr_name; + pjsip_host_port addr_name; /** * Number of simultaneous asynchronous accept() operations to be @@ -84,7 +83,7 @@ typedef struct pjsip_tcp_transport_cfg * * Default: 1 */ - unsigned async_cnt; + unsigned async_cnt; /** * QoS traffic type to be set on this transport. When application wants @@ -93,7 +92,7 @@ typedef struct pjsip_tcp_transport_cfg * * Default is QoS not set. */ - pj_qos_type qos_type; + pj_qos_type qos_type; /** * Set the low level QoS parameters to the transport. This is a lower @@ -102,7 +101,7 @@ typedef struct pjsip_tcp_transport_cfg * * Default is QoS not set. */ - pj_qos_params qos_params; + pj_qos_params qos_params; /** * Specify options to be set on the transport. @@ -110,7 +109,7 @@ typedef struct pjsip_tcp_transport_cfg * By default there is no options. * */ - pj_sockopt_params sockopt_params; + pj_sockopt_params sockopt_params; /** @@ -119,7 +118,7 @@ typedef struct pjsip_tcp_transport_cfg * * Default: PJSIP_TCP_INITIAL_TIMEOUT */ - unsigned initial_timeout; + unsigned initial_timeout; } pjsip_tcp_transport_cfg; @@ -128,11 +127,11 @@ typedef struct pjsip_tcp_transport_cfg * Initialize pjsip_tcp_transport_cfg structure with default values for * the specifed address family. * - * @param cfg The structure to initialize. - * @param af Address family to be used. + * @param cfg The structure to initialize. + * @param af Address family to be used. */ PJ_DECL(void) pjsip_tcp_transport_cfg_default(pjsip_tcp_transport_cfg *cfg, - int af); + int af); /** @@ -141,30 +140,30 @@ PJ_DECL(void) pjsip_tcp_transport_cfg_default(pjsip_tcp_transport_cfg *cfg, * instance of SIP TCP transport factory and register it to the * transport manager. * - * @param endpt The SIP endpoint. - * @param local Optional local address to bind, or specify the - * address to bind the server socket to. Both IP - * interface address and port fields are optional. - * If IP interface address is not specified, socket - * will be bound to PJ_INADDR_ANY. If port is not - * specified, socket will be bound to any port - * selected by the operating system. - * @param async_cnt Number of simultaneous asynchronous accept() - * operations to be supported. It is recommended that - * the number here corresponds to the number of - * processors in the system (or the number of SIP - * worker threads). - * @param p_factory Optional pointer to receive the instance of the - * SIP TCP transport factory just created. + * @param endpt The SIP endpoint. + * @param local Optional local address to bind, or specify the + * address to bind the server socket to. Both IP + * interface address and port fields are optional. + * If IP interface address is not specified, socket + * will be bound to PJ_INADDR_ANY. If port is not + * specified, socket will be bound to any port + * selected by the operating system. + * @param async_cnt Number of simultaneous asynchronous accept() + * operations to be supported. It is recommended that + * the number here corresponds to the number of + * processors in the system (or the number of SIP + * worker threads). + * @param p_factory Optional pointer to receive the instance of the + * SIP TCP transport factory just created. * - * @return PJ_SUCCESS when the transport has been successfully - * started and registered to transport manager, or - * the appropriate error code. + * @return PJ_SUCCESS when the transport has been successfully + * started and registered to transport manager, or + * the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tcp_transport_start(pjsip_endpoint *endpt, - const pj_sockaddr_in *local, - unsigned async_cnt, - pjsip_tpfactory **p_factory); + const pj_sockaddr_in *local, + unsigned async_cnt, + pjsip_tpfactory **p_factory); @@ -172,54 +171,54 @@ PJ_DECL(pj_status_t) pjsip_tcp_transport_start(pjsip_endpoint *endpt, * A newer variant of #pjsip_tcp_transport_start(), which allows specifying * the published/public address of the TCP transport. * - * @param endpt The SIP endpoint. - * @param local Optional local address to bind, or specify the - * address to bind the server socket to. Both IP - * interface address and port fields are optional. - * If IP interface address is not specified, socket - * will be bound to PJ_INADDR_ANY. If port is not - * specified, socket will be bound to any port - * selected by the operating system. - * @param a_name Optional published address, which is the address to be - * advertised as the address of this SIP transport. - * If this argument is NULL, then the bound address - * will be used as the published address. - * @param async_cnt Number of simultaneous asynchronous accept() - * operations to be supported. It is recommended that - * the number here corresponds to the number of - * processors in the system (or the number of SIP - * worker threads). - * @param p_factory Optional pointer to receive the instance of the - * SIP TCP transport factory just created. + * @param endpt The SIP endpoint. + * @param local Optional local address to bind, or specify the + * address to bind the server socket to. Both IP + * interface address and port fields are optional. + * If IP interface address is not specified, socket + * will be bound to PJ_INADDR_ANY. If port is not + * specified, socket will be bound to any port + * selected by the operating system. + * @param a_name Optional published address, which is the address to be + * advertised as the address of this SIP transport. + * If this argument is NULL, then the bound address + * will be used as the published address. + * @param async_cnt Number of simultaneous asynchronous accept() + * operations to be supported. It is recommended that + * the number here corresponds to the number of + * processors in the system (or the number of SIP + * worker threads). + * @param p_factory Optional pointer to receive the instance of the + * SIP TCP transport factory just created. * - * @return PJ_SUCCESS when the transport has been successfully - * started and registered to transport manager, or - * the appropriate error code. + * @return PJ_SUCCESS when the transport has been successfully + * started and registered to transport manager, or + * the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tcp_transport_start2(pjsip_endpoint *endpt, - const pj_sockaddr_in *local, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_tpfactory **p_factory); + const pj_sockaddr_in *local, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_tpfactory **p_factory); /** * Another variant of #pjsip_tcp_transport_start(). * - * @param endpt The SIP endpoint. - * @param cfg TCP transport settings. Application should initialize - * this setting with #pjsip_tcp_transport_cfg_default(). - * @param p_factory Optional pointer to receive the instance of the - * SIP TCP transport factory just created. + * @param endpt The SIP endpoint. + * @param cfg TCP transport settings. Application should initialize + * this setting with #pjsip_tcp_transport_cfg_default(). + * @param p_factory Optional pointer to receive the instance of the + * SIP TCP transport factory just created. * - * @return PJ_SUCCESS when the transport has been successfully - * started and registered to transport manager, or - * the appropriate error code. + * @return PJ_SUCCESS when the transport has been successfully + * started and registered to transport manager, or + * the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tcp_transport_start3( - pjsip_endpoint *endpt, - const pjsip_tcp_transport_cfg *cfg, - pjsip_tpfactory **p_factory - ); + pjsip_endpoint *endpt, + const pjsip_tcp_transport_cfg *cfg, + pjsip_tpfactory **p_factory + ); /** * Retrieve the internal socket handle used by the TCP transport. Note @@ -227,10 +226,10 @@ PJ_DECL(pj_status_t) pjsip_tcp_transport_start3( * needs to take care not to perform operation that disrupts ioqueue * operation. * - * @param transport The TCP transport. + * @param transport The TCP transport. * - * @return The socket handle, or PJ_INVALID_SOCKET if no socket - * is currently being used. + * @return The socket handle, or PJ_INVALID_SOCKET if no socket + * is currently being used. */ PJ_DECL(pj_sock_t) pjsip_tcp_transport_get_socket(pjsip_transport *transport); @@ -239,50 +238,50 @@ PJ_DECL(pj_sock_t) pjsip_tcp_transport_get_socket(pjsip_transport *transport); * to start the listener manually, if listener was not started when * PJSIP_TCP_TRANSPORT_DONT_CREATE_LISTENER is set to 0. * - * @param factory The SIP TCP transport factory. + * @param factory The SIP TCP transport factory. * - * @param local The address where the listener should be bound to. - * Both IP interface address and port fields are optional. - * If IP interface address is not specified, socket - * will be bound to PJ_INADDR_ANY. If port is not - * specified, socket will be bound to any port - * selected by the operating system. + * @param local The address where the listener should be bound to. + * Both IP interface address and port fields are optional. + * If IP interface address is not specified, socket + * will be bound to PJ_INADDR_ANY. If port is not + * specified, socket will be bound to any port + * selected by the operating system. * - * @param a_name The published address for the listener. - * If this argument is NULL, then the bound address will - * be used as the published address. + * @param a_name The published address for the listener. + * If this argument is NULL, then the bound address will + * be used as the published address. * - * @return PJ_SUCCESS when the listener has been successfully - * started. + * @return PJ_SUCCESS when the listener has been successfully + * started. */ PJ_DECL(pj_status_t) pjsip_tcp_transport_lis_start(pjsip_tpfactory *factory, - const pj_sockaddr *local, - const pjsip_host_port *a_name); + const pj_sockaddr *local, + const pjsip_host_port *a_name); /** * Restart the TCP listener. This will close the listener socket and recreate * the socket based on the config used when starting the transport. * - * @param factory The SIP TCP transport factory. + * @param factory The SIP TCP transport factory. * - * @param local The address where the listener should be bound to. - * Both IP interface address and port fields are optional. - * If IP interface address is not specified, socket - * will be bound to PJ_INADDR_ANY. If port is not - * specified, socket will be bound to any port - * selected by the operating system. + * @param local The address where the listener should be bound to. + * Both IP interface address and port fields are optional. + * If IP interface address is not specified, socket + * will be bound to PJ_INADDR_ANY. If port is not + * specified, socket will be bound to any port + * selected by the operating system. * - * @param a_name The published address for the listener. - * If this argument is NULL, then the bound address will - * be used as the published address. + * @param a_name The published address for the listener. + * If this argument is NULL, then the bound address will + * be used as the published address. * - * @return PJ_SUCCESS when the listener has been successfully - * restarted. + * @return PJ_SUCCESS when the listener has been successfully + * restarted. * */ PJ_DECL(pj_status_t) pjsip_tcp_transport_restart(pjsip_tpfactory *factory, - const pj_sockaddr *local, - const pjsip_host_port *a_name); + const pj_sockaddr *local, + const pjsip_host_port *a_name); PJ_END_DECL @@ -291,6 +290,6 @@ PJ_END_DECL * @} */ -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ -#endif /* __PJSIP_TRANSPORT_TCP_H__ */ +#endif /* __PJSIP_TRANSPORT_TCP_H__ */ diff --git a/pjsip/include/pjsip/sip_transport_tls.h b/pjsip/include/pjsip/sip_transport_tls.h index 2d58ae8c5c..a5fba6d675 100644 --- a/pjsip/include/pjsip/sip_transport_tls.h +++ b/pjsip/include/pjsip/sip_transport_tls.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -48,21 +47,21 @@ PJ_BEGIN_DECL * Default is PJSIP_TLSV1_METHOD */ #ifndef PJSIP_SSL_DEFAULT_METHOD -# define PJSIP_SSL_DEFAULT_METHOD PJSIP_TLSV1_METHOD +# define PJSIP_SSL_DEFAULT_METHOD PJSIP_TLSV1_METHOD #endif /** SSL protocol method constants. */ typedef enum pjsip_ssl_method { - PJSIP_SSL_UNSPECIFIED_METHOD = 0, /**< Default protocol method. */ - PJSIP_SSLV2_METHOD = 20, /**< Use SSLv2 method. */ - PJSIP_SSLV3_METHOD = 30, /**< Use SSLv3 method. */ - PJSIP_TLSV1_METHOD = 31, /**< Use TLSv1 method. */ - PJSIP_TLSV1_1_METHOD = 32, /**< Use TLSv1_1 method. */ - PJSIP_TLSV1_2_METHOD = 33, /**< Use TLSv1_2 method. */ - PJSIP_TLSV1_3_METHOD = 34, /**< Use TLSv1_3 method. */ - PJSIP_SSLV23_METHOD = 23, /**< Use SSLv23 method. */ + PJSIP_SSL_UNSPECIFIED_METHOD = 0, /**< Default protocol method. */ + PJSIP_SSLV2_METHOD = 20, /**< Use SSLv2 method. */ + PJSIP_SSLV3_METHOD = 30, /**< Use SSLv3 method. */ + PJSIP_TLSV1_METHOD = 31, /**< Use TLSv1 method. */ + PJSIP_TLSV1_1_METHOD = 32, /**< Use TLSv1_1 method. */ + PJSIP_TLSV1_2_METHOD = 33, /**< Use TLSv1_2 method. */ + PJSIP_TLSV1_3_METHOD = 34, /**< Use TLSv1_3 method. */ + PJSIP_SSLV23_METHOD = 23, /**< Use SSLv23 method. */ } pjsip_ssl_method; /** @@ -71,8 +70,8 @@ typedef enum pjsip_ssl_method */ #ifndef PJSIP_SSL_DEFAULT_PROTO # define PJSIP_SSL_DEFAULT_PROTO (PJ_SSL_SOCK_PROTO_TLS1 | \ - PJ_SSL_SOCK_PROTO_TLS1_1 | \ - PJ_SSL_SOCK_PROTO_TLS1_2) + PJ_SSL_SOCK_PROTO_TLS1_1 | \ + PJ_SSL_SOCK_PROTO_TLS1_2) #endif @@ -144,24 +143,24 @@ typedef struct pjsip_tls_setting /** * Certificate of Authority (CA) list file. */ - pj_str_t ca_list_file; + pj_str_t ca_list_file; /** * Certificate of Authority (CA) list directory path. */ - pj_str_t ca_list_path; + pj_str_t ca_list_path; /** * Public endpoint certificate file, which will be used as client- * side certificate for outgoing TLS connection, and server-side * certificate for incoming TLS connection. */ - pj_str_t cert_file; + pj_str_t cert_file; /** * Optional private key of the endpoint certificate to be used. */ - pj_str_t privkey_file; + pj_str_t privkey_file; /** * Certificate of Authority (CA) buffer. If ca_list_file, ca_list_path, @@ -187,7 +186,7 @@ typedef struct pjsip_tls_setting /** * Password to open private key. */ - pj_str_t password; + pj_str_t password; /** * TLS protocol method from #pjsip_ssl_method. In the future, this field @@ -197,7 +196,7 @@ typedef struct pjsip_tls_setting * Default is PJSIP_SSL_UNSPECIFIED_METHOD (0), which in turn will * use PJSIP_SSL_DEFAULT_METHOD, which default value is PJSIP_TLSV1_METHOD. */ - pjsip_ssl_method method; + pjsip_ssl_method method; /** * TLS protocol type from #pj_ssl_sock_proto. Use this field to enable @@ -206,7 +205,7 @@ typedef struct pjsip_tls_setting * * Default is PJSIP_SSL_DEFAULT_PROTO. */ - pj_uint32_t proto; + pj_uint32_t proto; /** * Number of ciphers contained in the specified cipher preference. @@ -246,7 +245,7 @@ typedef struct pjsip_tls_setting * Algorithms are: "MD5", "SHA1", "SHA224", "SHA256", "SHA384", "SHA512" * Example: "ECDSA+SHA256:RSA+SHA256" */ - pj_str_t sigalgs; + pj_str_t sigalgs; /** * Reseed random number generator. @@ -257,7 +256,7 @@ typedef struct pjsip_tls_setting * * Default value is PJ_SSL_ENTROPY_NONE. */ - pj_ssl_entropy_t entropy_type; + pj_ssl_entropy_t entropy_type; /** * When using a file/socket for entropy #PJ_SSL_ENTROPY_EGD or @@ -266,7 +265,7 @@ typedef struct pjsip_tls_setting * * Default value is an empty string. */ - pj_str_t entropy_path; + pj_str_t entropy_path; /** * Specifies TLS transport behavior on the server TLS certificate @@ -284,7 +283,7 @@ typedef struct pjsip_tls_setting * * Default value is PJ_FALSE. */ - pj_bool_t verify_server; + pj_bool_t verify_server; /** * Specifies TLS transport behavior on the client TLS certificate @@ -302,7 +301,7 @@ typedef struct pjsip_tls_setting * * Default value is PJ_FALSE. */ - pj_bool_t verify_client; + pj_bool_t verify_client; /** * When acting as server (incoming TLS connections), reject inocming @@ -311,14 +310,14 @@ typedef struct pjsip_tls_setting * This setting corresponds to SSL_VERIFY_FAIL_IF_NO_PEER_CERT flag. * Default value is PJ_FALSE. */ - pj_bool_t require_client_cert; + pj_bool_t require_client_cert; /** * TLS negotiation timeout to be applied for both outgoing and * incoming connection. If both sec and msec member is set to zero, * the SSL negotiation doesn't have a timeout. */ - pj_time_val timeout; + pj_time_val timeout; /** * Should SO_REUSEADDR be used for the listener socket. @@ -383,8 +382,8 @@ typedef struct pjsip_tls_setting * @param param The parameter to the callback. * * @return Return PJ_TRUE if succesfully verified. - * If verification failed, connection will be dropped - * immediately. + * If verification failed, connection will be dropped + * immediately. * */ pj_bool_t(*on_verify_cb)(const pjsip_tls_on_verify_param *param); @@ -402,7 +401,7 @@ typedef struct pjsip_tls_state_info /** * SSL socket info. */ - pj_ssl_sock_info *ssl_sock_info; + pj_ssl_sock_info *ssl_sock_info; } pjsip_tls_state_info; @@ -426,13 +425,13 @@ PJ_INLINE(void) pjsip_tls_setting_default(pjsip_tls_setting *tls_opt) /** * Copy TLS setting. * - * @param pool The pool to duplicate strings etc. - * @param dst Destination structure. - * @param src Source structure. + * @param pool The pool to duplicate strings etc. + * @param dst Destination structure. + * @param src Source structure. */ PJ_INLINE(void) pjsip_tls_setting_copy(pj_pool_t *pool, - pjsip_tls_setting *dst, - const pjsip_tls_setting *src) + pjsip_tls_setting *dst, + const pjsip_tls_setting *src) { pj_memcpy(dst, src, sizeof(*dst)); pj_strdup_with_null(pool, &dst->ca_list_file, &src->ca_list_file); @@ -448,19 +447,19 @@ PJ_INLINE(void) pjsip_tls_setting_copy(pj_pool_t *pool, pj_strdup(pool, &dst->privkey_buf, &src->privkey_buf); if (src->ciphers_num) { - unsigned i; - dst->ciphers = (pj_ssl_cipher*) pj_pool_calloc(pool, src->ciphers_num, - sizeof(pj_ssl_cipher)); - for (i=0; iciphers_num; ++i) - dst->ciphers[i] = src->ciphers[i]; + unsigned i; + dst->ciphers = (pj_ssl_cipher*) pj_pool_calloc(pool, src->ciphers_num, + sizeof(pj_ssl_cipher)); + for (i=0; iciphers_num; ++i) + dst->ciphers[i] = src->ciphers[i]; } if (src->curves_num) { - unsigned i; - dst->curves = (pj_ssl_curve*) pj_pool_calloc(pool, src->curves_num, - sizeof(pj_ssl_curve)); - for (i=0; icurves_num; ++i) - dst->curves[i] = src->curves[i]; + unsigned i; + dst->curves = (pj_ssl_curve*) pj_pool_calloc(pool, src->curves_num, + sizeof(pj_ssl_curve)); + for (i=0; icurves_num; ++i) + dst->curves[i] = src->curves[i]; } } @@ -468,7 +467,7 @@ PJ_INLINE(void) pjsip_tls_setting_copy(pj_pool_t *pool, /** * Wipe out certificates and keys in the TLS setting buffer. * - * @param opt TLS setting. + * @param opt TLS setting. */ PJ_DECL(void) pjsip_tls_setting_wipe_keys(pjsip_tls_setting *opt); @@ -481,37 +480,37 @@ PJ_DECL(void) pjsip_tls_setting_wipe_keys(pjsip_tls_setting *opt); * * See also #pjsip_tls_transport_start2() which supports IPv6. * - * @param endpt The SIP endpoint. - * @param opt Optional TLS settings. - * @param local Optional local address to bind, or specify the - * address to bind the server socket to. Both IP - * interface address and port fields are optional. - * If IP interface address is not specified, socket - * will be bound to PJ_INADDR_ANY. If port is not - * specified, socket will be bound to any port - * selected by the operating system. - * @param a_name Optional published address, which is the address to be - * advertised as the address of this SIP transport. - * If this argument is NULL, then the bound address - * will be used as the published address. - * @param async_cnt Number of simultaneous asynchronous accept() - * operations to be supported. It is recommended that - * the number here corresponds to the number of - * processors in the system (or the number of SIP - * worker threads). - * @param p_factory Optional pointer to receive the instance of the - * SIP TLS transport factory just created. + * @param endpt The SIP endpoint. + * @param opt Optional TLS settings. + * @param local Optional local address to bind, or specify the + * address to bind the server socket to. Both IP + * interface address and port fields are optional. + * If IP interface address is not specified, socket + * will be bound to PJ_INADDR_ANY. If port is not + * specified, socket will be bound to any port + * selected by the operating system. + * @param a_name Optional published address, which is the address to be + * advertised as the address of this SIP transport. + * If this argument is NULL, then the bound address + * will be used as the published address. + * @param async_cnt Number of simultaneous asynchronous accept() + * operations to be supported. It is recommended that + * the number here corresponds to the number of + * processors in the system (or the number of SIP + * worker threads). + * @param p_factory Optional pointer to receive the instance of the + * SIP TLS transport factory just created. * - * @return PJ_SUCCESS when the transport has been successfully - * started and registered to transport manager, or - * the appropriate error code. + * @return PJ_SUCCESS when the transport has been successfully + * started and registered to transport manager, or + * the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tls_transport_start(pjsip_endpoint *endpt, - const pjsip_tls_setting *opt, - const pj_sockaddr_in *local, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_tpfactory **p_factory); + const pjsip_tls_setting *opt, + const pj_sockaddr_in *local, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_tpfactory **p_factory); /** * Variant of #pjsip_tls_transport_start() that supports IPv6. To instantiate @@ -519,88 +518,88 @@ PJ_DECL(pj_status_t) pjsip_tls_transport_start(pjsip_endpoint *endpt, * (the host and port part may be left unspecified if not desired, i.e. by * filling them with zeroes). * - * @param endpt The SIP endpoint. - * @param opt Optional TLS settings. - * @param local Optional local address to bind, or specify the - * address to bind the server socket to. Both IP - * interface address and port fields are optional. - * If IP interface address is not specified, socket - * will be bound to any address. If port is not - * specified, socket will be bound to any port - * selected by the operating system. - * @param a_name Optional published address, which is the address to be - * advertised as the address of this SIP transport. - * If this argument is NULL, then the bound address - * will be used as the published address. - * @param async_cnt Number of simultaneous asynchronous accept() - * operations to be supported. It is recommended that - * the number here corresponds to the number of - * processors in the system (or the number of SIP - * worker threads). - * @param p_factory Optional pointer to receive the instance of the - * SIP TLS transport factory just created. + * @param endpt The SIP endpoint. + * @param opt Optional TLS settings. + * @param local Optional local address to bind, or specify the + * address to bind the server socket to. Both IP + * interface address and port fields are optional. + * If IP interface address is not specified, socket + * will be bound to any address. If port is not + * specified, socket will be bound to any port + * selected by the operating system. + * @param a_name Optional published address, which is the address to be + * advertised as the address of this SIP transport. + * If this argument is NULL, then the bound address + * will be used as the published address. + * @param async_cnt Number of simultaneous asynchronous accept() + * operations to be supported. It is recommended that + * the number here corresponds to the number of + * processors in the system (or the number of SIP + * worker threads). + * @param p_factory Optional pointer to receive the instance of the + * SIP TLS transport factory just created. * - * @return PJ_SUCCESS when the transport has been successfully - * started and registered to transport manager, or - * the appropriate error code. + * @return PJ_SUCCESS when the transport has been successfully + * started and registered to transport manager, or + * the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_tls_transport_start2(pjsip_endpoint *endpt, - const pjsip_tls_setting *opt, - const pj_sockaddr *local, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_tpfactory **p_factory); + const pjsip_tls_setting *opt, + const pj_sockaddr *local, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_tpfactory **p_factory); /** * Start the TLS listener, if the listener is not started yet. This is useful * to start the listener manually, if listener was not started when * PJSIP_TLS_TRANSPORT_DONT_CREATE_LISTENER is set to 0. * - * @param factory The SIP TLS transport factory. + * @param factory The SIP TLS transport factory. * - * @param local The address where the listener should be bound to. - * Both IP interface address and port fields are optional. - * If IP interface address is not specified, socket - * will be bound to PJ_INADDR_ANY. If port is not - * specified, socket will be bound to any port - * selected by the operating system. + * @param local The address where the listener should be bound to. + * Both IP interface address and port fields are optional. + * If IP interface address is not specified, socket + * will be bound to PJ_INADDR_ANY. If port is not + * specified, socket will be bound to any port + * selected by the operating system. * - * @param a_name The published address for the listener. - * If this argument is NULL, then the bound address will - * be used as the published address. + * @param a_name The published address for the listener. + * If this argument is NULL, then the bound address will + * be used as the published address. * - * @return PJ_SUCCESS when the listener has been successfully - * started. + * @return PJ_SUCCESS when the listener has been successfully + * started. */ PJ_DECL(pj_status_t) pjsip_tls_transport_lis_start(pjsip_tpfactory *factory, - const pj_sockaddr *local, - const pjsip_host_port *a_name); + const pj_sockaddr *local, + const pjsip_host_port *a_name); /** * Restart the TLS listener. This will close the listener socket and recreate * the socket based on the config used when starting the transport. * - * @param factory The SIP TLS transport factory. + * @param factory The SIP TLS transport factory. * - * @param local The address where the listener should be bound to. - * Both IP interface address and port fields are optional. - * If IP interface address is not specified, socket - * will be bound to PJ_INADDR_ANY. If port is not - * specified, socket will be bound to any port - * selected by the operating system. + * @param local The address where the listener should be bound to. + * Both IP interface address and port fields are optional. + * If IP interface address is not specified, socket + * will be bound to PJ_INADDR_ANY. If port is not + * specified, socket will be bound to any port + * selected by the operating system. * - * @param a_name The published address for the listener. - * If this argument is NULL, then the bound address will - * be used as the published address. + * @param a_name The published address for the listener. + * If this argument is NULL, then the bound address will + * be used as the published address. * - * @return PJ_SUCCESS when the listener has been successfully - * restarted. + * @return PJ_SUCCESS when the listener has been successfully + * restarted. * */ PJ_DECL(pj_status_t) pjsip_tls_transport_restart(pjsip_tpfactory *factory, - const pj_sockaddr *local, - const pjsip_host_port *a_name); + const pj_sockaddr *local, + const pjsip_host_port *a_name); PJ_END_DECL @@ -608,4 +607,4 @@ PJ_END_DECL * @} */ -#endif /* __PJSIP_TRANSPORT_TLS_H__ */ +#endif /* __PJSIP_TRANSPORT_TLS_H__ */ diff --git a/pjsip/include/pjsip/sip_transport_udp.h b/pjsip/include/pjsip/sip_transport_udp.h index 0946463e13..dfb93101bf 100644 --- a/pjsip/include/pjsip/sip_transport_udp.h +++ b/pjsip/include/pjsip/sip_transport_udp.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -49,14 +48,14 @@ enum * This flag tells the transport to keep the existing/internal socket * handle. */ - PJSIP_UDP_TRANSPORT_KEEP_SOCKET = 1, + PJSIP_UDP_TRANSPORT_KEEP_SOCKET = 1, /** * This flag tells the transport to destroy the existing/internal socket * handle. Naturally this flag and PJSIP_UDP_TRANSPORT_KEEP_SOCKET are * mutually exclusive. */ - PJSIP_UDP_TRANSPORT_DESTROY_SOCKET = 2 + PJSIP_UDP_TRANSPORT_DESTROY_SOCKET = 2 }; @@ -71,19 +70,19 @@ typedef struct pjsip_udp_transport_cfg * Address family to use. Valid values are pj_AF_INET() and * pj_AF_INET6(). Default is pj_AF_INET(). */ - int af; + int af; /** * Address to bind the socket to. */ - pj_sockaddr bind_addr; + pj_sockaddr bind_addr; /** * Optional published address, which is the address to be * advertised as the address of this SIP transport. * By default the bound address will be used as the published address. */ - pjsip_host_port addr_name; + pjsip_host_port addr_name; /** * Number of simultaneous asynchronous accept() operations to be @@ -93,7 +92,7 @@ typedef struct pjsip_udp_transport_cfg * * Default: 1 */ - unsigned async_cnt; + unsigned async_cnt; /** * QoS traffic type to be set on this transport. When application wants @@ -102,7 +101,7 @@ typedef struct pjsip_udp_transport_cfg * * Default is QoS not set. */ - pj_qos_type qos_type; + pj_qos_type qos_type; /** * Set the low level QoS parameters to the transport. This is a lower @@ -111,7 +110,7 @@ typedef struct pjsip_udp_transport_cfg * * Default is QoS not set. */ - pj_qos_params qos_params; + pj_qos_params qos_params; /** * Specify options to be set on the transport. @@ -119,7 +118,7 @@ typedef struct pjsip_udp_transport_cfg * By default there is no options. * */ - pj_sockopt_params sockopt_params; + pj_sockopt_params sockopt_params; } pjsip_udp_transport_cfg; @@ -128,107 +127,107 @@ typedef struct pjsip_udp_transport_cfg * Initialize pjsip_udp_transport_cfg structure with default values for * the specifed address family. * - * @param cfg The structure to initialize. - * @param af Address family to be used. + * @param cfg The structure to initialize. + * @param af Address family to be used. */ PJ_DECL(void) pjsip_udp_transport_cfg_default(pjsip_udp_transport_cfg *cfg, - int af); + int af); /** * Start UDP IPv4/IPv6 transport. * - * @param endpt The SIP endpoint. - * @param cfg UDP transport settings. Application should initialize - * this setting with #pjsip_udp_transport_cfg_default(). - * @param p_transport Pointer to receive the transport. + * @param endpt The SIP endpoint. + * @param cfg UDP transport settings. Application should initialize + * this setting with #pjsip_udp_transport_cfg_default(). + * @param p_transport Pointer to receive the transport. * - * @return PJ_SUCCESS when the transport has been successfully - * started and registered to transport manager, or - * the appropriate error code. + * @return PJ_SUCCESS when the transport has been successfully + * started and registered to transport manager, or + * the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_udp_transport_start2( - pjsip_endpoint *endpt, - const pjsip_udp_transport_cfg *cfg, - pjsip_transport **p_transport); + pjsip_endpoint *endpt, + const pjsip_udp_transport_cfg *cfg, + pjsip_transport **p_transport); /** * Start UDP transport. * - * @param endpt The SIP endpoint. - * @param local Optional local address to bind. If this argument - * is NULL, the UDP transport will be bound to arbitrary - * UDP port. - * @param a_name Published address (only the host and port portion is - * used). If this argument is NULL, then the bound address - * will be used as the published address. - * @param async_cnt Number of simultaneous async operations. - * @param p_transport Pointer to receive the transport. + * @param endpt The SIP endpoint. + * @param local Optional local address to bind. If this argument + * is NULL, the UDP transport will be bound to arbitrary + * UDP port. + * @param a_name Published address (only the host and port portion is + * used). If this argument is NULL, then the bound address + * will be used as the published address. + * @param async_cnt Number of simultaneous async operations. + * @param p_transport Pointer to receive the transport. * - * @return PJ_SUCCESS when the transport has been successfully - * started and registered to transport manager, or - * the appropriate error code. + * @return PJ_SUCCESS when the transport has been successfully + * started and registered to transport manager, or + * the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_udp_transport_start(pjsip_endpoint *endpt, - const pj_sockaddr_in *local, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_transport **p_transport); + const pj_sockaddr_in *local, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_transport **p_transport); /** * Start IPv6 UDP transport. */ PJ_DECL(pj_status_t) pjsip_udp_transport_start6(pjsip_endpoint *endpt, - const pj_sockaddr_in6 *local, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_transport **p_transport); + const pj_sockaddr_in6 *local, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_transport **p_transport); /** * Attach IPv4 UDP socket as a new transport and start the transport. * - * @param endpt The SIP endpoint. - * @param sock UDP socket to use. - * @param a_name Published address (only the host and port portion is - * used). - * @param async_cnt Number of simultaneous async operations. - * @param p_transport Pointer to receive the transport. + * @param endpt The SIP endpoint. + * @param sock UDP socket to use. + * @param a_name Published address (only the host and port portion is + * used). + * @param async_cnt Number of simultaneous async operations. + * @param p_transport Pointer to receive the transport. * - * @return PJ_SUCCESS when the transport has been successfully - * started and registered to transport manager, or - * the appropriate error code. + * @return PJ_SUCCESS when the transport has been successfully + * started and registered to transport manager, or + * the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_udp_transport_attach(pjsip_endpoint *endpt, - pj_sock_t sock, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_transport **p_transport); + pj_sock_t sock, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_transport **p_transport); /** * Attach IPv4 or IPv6 UDP socket as a new transport and start the transport. * - * @param endpt The SIP endpoint. - * @param type Transport type, which is PJSIP_TRANSPORT_UDP for IPv4 - * or PJSIP_TRANSPORT_UDP6 for IPv6 socket. - * @param sock UDP socket to use. - * @param a_name Published address (only the host and port portion is - * used). - * @param async_cnt Number of simultaneous async operations. - * @param p_transport Pointer to receive the transport. + * @param endpt The SIP endpoint. + * @param type Transport type, which is PJSIP_TRANSPORT_UDP for IPv4 + * or PJSIP_TRANSPORT_UDP6 for IPv6 socket. + * @param sock UDP socket to use. + * @param a_name Published address (only the host and port portion is + * used). + * @param async_cnt Number of simultaneous async operations. + * @param p_transport Pointer to receive the transport. * - * @return PJ_SUCCESS when the transport has been successfully - * started and registered to transport manager, or - * the appropriate error code. + * @return PJ_SUCCESS when the transport has been successfully + * started and registered to transport manager, or + * the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_udp_transport_attach2(pjsip_endpoint *endpt, - pjsip_transport_type_e type, - pj_sock_t sock, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_transport **p_transport); + pjsip_transport_type_e type, + pj_sock_t sock, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_transport **p_transport); /** * Retrieve the internal socket handle used by the UDP transport. Note @@ -236,11 +235,11 @@ PJ_DECL(pj_status_t) pjsip_udp_transport_attach2(pjsip_endpoint *endpt, * wants to make use of this socket, it should temporarily pause the * transport. * - * @param transport The UDP transport. + * @param transport The UDP transport. * - * @return The socket handle, or PJ_INVALID_SOCKET if no socket - * is currently being used (for example, when transport - * is being paused). + * @return The socket handle, or PJ_INVALID_SOCKET if no socket + * is currently being used (for example, when transport + * is being paused). */ PJ_DECL(pj_sock_t) pjsip_udp_transport_get_socket(pjsip_transport *transport); @@ -266,14 +265,14 @@ PJ_DECL(pj_sock_t) pjsip_udp_transport_get_socket(pjsip_transport *transport); * flag when calling this function, and specify a new socket when * calling #pjsip_udp_transport_restart(). * - * @param transport The UDP transport. - * @param option Pause option. + * @param transport The UDP transport. + * @param option Pause option. * - * @return PJ_SUCCESS if transport is paused successfully, - * or the appropriate error code. + * @return PJ_SUCCESS if transport is paused successfully, + * or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_udp_transport_pause(pjsip_transport *transport, - unsigned option); + unsigned option); /** * Restart the transport. Several operations are supported by this function: @@ -303,29 +302,29 @@ PJ_DECL(pj_status_t) pjsip_udp_transport_pause(pjsip_transport *transport, * this method. * Please see https://github.com/pjsip/pjproject/pull/2731 for more details. * - * @param transport The UDP transport. - * @param option Restart option. - * @param sock Optional socket to be used by the transport. - * @param local The address where the socket should be bound to. - * If this argument is NULL, socket will be bound - * to any available port. - * @param a_name Optionally specify the published address for - * this transport. If the socket is not replaced - * (PJSIP_UDP_TRANSPORT_KEEP_SOCKET flag is - * specified), then if this argument is NULL, the - * previous value will be used. If the socket is - * replaced and this argument is NULL, the bound - * address will be used as the published address - * of the transport. + * @param transport The UDP transport. + * @param option Restart option. + * @param sock Optional socket to be used by the transport. + * @param local The address where the socket should be bound to. + * If this argument is NULL, socket will be bound + * to any available port. + * @param a_name Optionally specify the published address for + * this transport. If the socket is not replaced + * (PJSIP_UDP_TRANSPORT_KEEP_SOCKET flag is + * specified), then if this argument is NULL, the + * previous value will be used. If the socket is + * replaced and this argument is NULL, the bound + * address will be used as the published address + * of the transport. * - * @return PJ_SUCCESS if transport can be restarted, or - * the appropriate error code. + * @return PJ_SUCCESS if transport can be restarted, or + * the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_udp_transport_restart(pjsip_transport *transport, - unsigned option, - pj_sock_t sock, - const pj_sockaddr_in *local, - const pjsip_host_port *a_name); + unsigned option, + pj_sock_t sock, + const pj_sockaddr_in *local, + const pjsip_host_port *a_name); /** * Restart the transport. Several operations are supported by this function: @@ -356,29 +355,29 @@ PJ_DECL(pj_status_t) pjsip_udp_transport_restart(pjsip_transport *transport, * this method. * Please see https://github.com/pjsip/pjproject/pull/2731 for more details. * - * @param transport The UDP transport. - * @param option Restart option. - * @param sock Optional socket to be used by the transport. - * @param local The address where the socket should be bound to. - * If this argument is NULL, socket will be bound - * to any available port. - * @param a_name Optionally specify the published address for - * this transport. If the socket is not replaced - * (PJSIP_UDP_TRANSPORT_KEEP_SOCKET flag is - * specified), then if this argument is NULL, the - * previous value will be used. If the socket is - * replaced and this argument is NULL, the bound - * address will be used as the published address - * of the transport. + * @param transport The UDP transport. + * @param option Restart option. + * @param sock Optional socket to be used by the transport. + * @param local The address where the socket should be bound to. + * If this argument is NULL, socket will be bound + * to any available port. + * @param a_name Optionally specify the published address for + * this transport. If the socket is not replaced + * (PJSIP_UDP_TRANSPORT_KEEP_SOCKET flag is + * specified), then if this argument is NULL, the + * previous value will be used. If the socket is + * replaced and this argument is NULL, the bound + * address will be used as the published address + * of the transport. * - * @return PJ_SUCCESS if transport can be restarted, or - * the appropriate error code. + * @return PJ_SUCCESS if transport can be restarted, or + * the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_udp_transport_restart2(pjsip_transport *transport, - unsigned option, - pj_sock_t sock, - const pj_sockaddr *local, - const pjsip_host_port *a_name); + unsigned option, + pj_sock_t sock, + const pj_sockaddr *local, + const pjsip_host_port *a_name); PJ_END_DECL @@ -387,4 +386,4 @@ PJ_END_DECL * @} */ -#endif /* __PJSIP_TRANSPORT_UDP_H__ */ +#endif /* __PJSIP_TRANSPORT_UDP_H__ */ diff --git a/pjsip/include/pjsip/sip_types.h b/pjsip/include/pjsip/sip_types.h index aa49da8a81..840d548bfd 100644 --- a/pjsip/include/pjsip/sip_types.h +++ b/pjsip/include/pjsip/sip_types.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -188,13 +187,13 @@ typedef struct pjsip_dialog pjsip_dialog; */ typedef enum pjsip_role_e { - PJSIP_ROLE_UAC, /**< Role is UAC. */ - PJSIP_ROLE_UAS, /**< Role is UAS. */ + PJSIP_ROLE_UAC, /**< Role is UAC. */ + PJSIP_ROLE_UAS, /**< Role is UAS. */ /* Alias: */ - PJSIP_UAC_ROLE = PJSIP_ROLE_UAC, /**< Role is UAC. */ - PJSIP_UAS_ROLE = PJSIP_ROLE_UAS /**< Role is UAS. */ + PJSIP_UAC_ROLE = PJSIP_ROLE_UAC, /**< Role is UAC. */ + PJSIP_UAS_ROLE = PJSIP_ROLE_UAS /**< Role is UAS. */ } pjsip_role_e; @@ -223,8 +222,8 @@ typedef struct pjsip_buffer */ typedef struct pjsip_host_port { - pj_str_t host; /**< Host part or IP address. */ - int port; /**< Port number. */ + pj_str_t host; /**< Host part or IP address. */ + int port; /**< Port number. */ } pjsip_host_port; /** @@ -232,9 +231,9 @@ typedef struct pjsip_host_port */ typedef struct pjsip_host_info { - unsigned flag; /**< Flags of pjsip_transport_flags_e. */ + unsigned flag; /**< Flags of pjsip_transport_flags_e. */ pjsip_transport_type_e type; /**< Transport type. */ - pjsip_host_port addr; /**< Address information. */ + pjsip_host_port addr; /**< Address information. */ } pjsip_host_info; @@ -262,5 +261,5 @@ PJ_DECL(pj_status_t) pjsip_exception_to_status(int exception_id); * @} */ -#endif /* __PJSIP_SIP_TYPES_H__ */ +#endif /* __PJSIP_SIP_TYPES_H__ */ diff --git a/pjsip/include/pjsip/sip_ua_layer.h b/pjsip/include/pjsip/sip_ua_layer.h index f32430e68f..af3797eaa5 100644 --- a/pjsip/include/pjsip/sip_ua_layer.h +++ b/pjsip/include/pjsip/sip_ua_layer.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -63,19 +62,19 @@ typedef struct pjsip_ua_init_param /** * Initialize user agent layer and register it to the specified endpoint. * - * @param endpt The endpoint where the user agent will be - * registered. - * @param prm UA initialization parameter. + * @param endpt The endpoint where the user agent will be + * registered. + * @param prm UA initialization parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_ua_init_module(pjsip_endpoint *endpt, - const pjsip_ua_init_param *prm); + const pjsip_ua_init_param *prm); /** * Get the instance of the user agent. * - * @return The user agent module instance. + * @return The user agent module instance. */ PJ_DECL(pjsip_user_agent*) pjsip_ua_instance(void); @@ -88,7 +87,7 @@ PJ_DECL(pjsip_user_agent*) pjsip_ua_instance(void); * no forking occurs, the number of dialog sets will be equal to * the number of dialogs. * - * @return Number of dialog sets. + * @return Number of dialog sets. */ PJ_DECL(pj_uint32_t) pjsip_ua_get_dlg_set_count(void); @@ -98,44 +97,44 @@ PJ_DECL(pj_uint32_t) pjsip_ua_get_dlg_set_count(void); * function may optionally lock the matching dialog instance before * returning it back to the caller. * - * @param call_id The call ID to be matched. - * @param local_tag The local tag to be matched. - * @param remote_tag The remote tag to be matched. - * @param lock_dialog If non-zero, instruct the function to lock the - * matching dialog with #pjsip_dlg_inc_lock(). - * Application is responsible to release the dialog's - * lock after it has finished manipulating the dialog, - * by calling #pjsip_dlg_dec_lock(). + * @param call_id The call ID to be matched. + * @param local_tag The local tag to be matched. + * @param remote_tag The remote tag to be matched. + * @param lock_dialog If non-zero, instruct the function to lock the + * matching dialog with #pjsip_dlg_inc_lock(). + * Application is responsible to release the dialog's + * lock after it has finished manipulating the dialog, + * by calling #pjsip_dlg_dec_lock(). * - * @return The matching dialog instance, or NULL if no matching - * dialog is found. + * @return The matching dialog instance, or NULL if no matching + * dialog is found. */ PJ_DECL(pjsip_dialog*) pjsip_ua_find_dialog(const pj_str_t *call_id, - const pj_str_t *local_tag, - const pj_str_t *remote_tag, - pj_bool_t lock_dialog); + const pj_str_t *local_tag, + const pj_str_t *remote_tag, + pj_bool_t lock_dialog); /** * Destroy the user agent layer. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_ua_destroy(void); /** * Dump user agent contents (e.g. all dialogs). * - * @param detail If non-zero, list of dialogs will be printed. + * @param detail If non-zero, list of dialogs will be printed. */ PJ_DECL(void) pjsip_ua_dump(pj_bool_t detail); /** * Get the endpoint instance of a user agent module. * - * @param ua The user agent instance. + * @param ua The user agent instance. * - * @return The endpoint instance where the user agent is - * registered. + * @return The endpoint instance where the user agent is + * registered. */ PJ_DECL(pjsip_endpoint*) pjsip_ua_get_endpt(pjsip_user_agent *ua); @@ -147,14 +146,14 @@ PJ_DECL(pjsip_endpoint*) pjsip_ua_get_endpt(pjsip_user_agent *ua); /** Internal (called by sip_dialog.c). */ PJ_DECL(pj_status_t) pjsip_ua_register_dlg( pjsip_user_agent *ua, - pjsip_dialog *dlg ); + pjsip_dialog *dlg ); /** Internal (called by sip_dialog.c). */ PJ_DECL(pj_status_t) pjsip_ua_unregister_dlg(pjsip_user_agent *ua, - pjsip_dialog *dlg ); + pjsip_dialog *dlg ); PJ_END_DECL -#endif /* __PJSIP_SIP_UA_LAYER_H__ */ +#endif /* __PJSIP_SIP_UA_LAYER_H__ */ diff --git a/pjsip/include/pjsip/sip_uri.h b/pjsip/include/pjsip/sip_uri.h index 40254dea2a..2459bf5fd0 100644 --- a/pjsip/include/pjsip/sip_uri.h +++ b/pjsip/include/pjsip/sip_uri.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -52,9 +51,9 @@ PJ_BEGIN_DECL */ typedef struct pjsip_param { - PJ_DECL_LIST_MEMBER(struct pjsip_param); /**< Generic list member. */ - pj_str_t name; /**< Param/header name. */ - pj_str_t value; /**< Param/header value. */ + PJ_DECL_LIST_MEMBER(struct pjsip_param); /**< Generic list member. */ + pj_str_t name; /**< Param/header name. */ + pj_str_t value; /**< Param/header value. */ } pjsip_param; @@ -62,20 +61,20 @@ typedef struct pjsip_param * Find the specified parameter name in the list. The name will be compared * in case-insensitive comparison. * - * @param param_list List of parameters to find. - * @param name Parameter/header name to find. + * @param param_list List of parameters to find. + * @param name Parameter/header name to find. * - * @return The parameter if found, or NULL. + * @return The parameter if found, or NULL. */ PJ_DECL(pjsip_param*) pjsip_param_find( const pjsip_param *param_list, - const pj_str_t *name ); + const pj_str_t *name ); /** * Alias for pjsip_param_find() */ PJ_INLINE(pjsip_param*) pjsip_param_cfind(const pjsip_param *param_list, - const pj_str_t *name) + const pj_str_t *name) { return pjsip_param_find(param_list, name); } @@ -83,59 +82,59 @@ PJ_INLINE(pjsip_param*) pjsip_param_cfind(const pjsip_param *param_list, /** * Compare two parameter lists. * - * @param param_list1 First parameter list. - * @param param_list2 Second parameter list. - * @param ig_nf If set to 1, do not compare parameters that only - * appear in one of the list. + * @param param_list1 First parameter list. + * @param param_list2 Second parameter list. + * @param ig_nf If set to 1, do not compare parameters that only + * appear in one of the list. * - * @return Zero if the parameter list are equal, non-zero - * otherwise. + * @return Zero if the parameter list are equal, non-zero + * otherwise. */ PJ_DECL(int) pjsip_param_cmp(const pjsip_param *param_list1, - const pjsip_param *param_list2, - pj_bool_t ig_nf); + const pjsip_param *param_list2, + pj_bool_t ig_nf); /** * Duplicate the parameters. * - * @param pool Pool to allocate memory from. - * @param dst_list Destination list. - * @param src_list Source list. + * @param pool Pool to allocate memory from. + * @param dst_list Destination list. + * @param src_list Source list. */ PJ_DECL(void) pjsip_param_clone(pj_pool_t *pool, pjsip_param *dst_list, - const pjsip_param *src_list); + const pjsip_param *src_list); /** * Duplicate the parameters. * - * @param pool Pool to allocate memory from. - * @param dst_list Destination list. - * @param src_list Source list. + * @param pool Pool to allocate memory from. + * @param dst_list Destination list. + * @param src_list Source list. */ PJ_DECL(void) pjsip_param_shallow_clone(pj_pool_t *pool, - pjsip_param *dst_list, - const pjsip_param *src_list); + pjsip_param *dst_list, + const pjsip_param *src_list); /** * Print parameters. * - * @param param_list The parameter list. - * @param buf Buffer. - * @param size Size of buffer. - * @param pname_unres Specification of allowed characters in pname. - * @param pvalue_unres Specification of allowed characters in pvalue. - * @param sep Separator character (either ';', ',', or '?'). - * When separator is set to '?', this function will - * automatically adjust the separator character to - * '&' after the first parameter is printed. + * @param param_list The parameter list. + * @param buf Buffer. + * @param size Size of buffer. + * @param pname_unres Specification of allowed characters in pname. + * @param pvalue_unres Specification of allowed characters in pvalue. + * @param sep Separator character (either ';', ',', or '?'). + * When separator is set to '?', this function will + * automatically adjust the separator character to + * '&' after the first parameter is printed. * - * @return The number of bytes printed, or -1 on errr. + * @return The number of bytes printed, or -1 on errr. */ PJ_DECL(pj_ssize_t) pjsip_param_print_on(const pjsip_param *param_list, - char *buf, pj_size_t size, - const pj_cis_t *pname_unres, - const pj_cis_t *pvalue_unres, - int sep); + char *buf, pj_size_t size, + const pj_cis_t *pname_unres, + const pj_cis_t *pvalue_unres, + int sep); /** * @} @@ -153,11 +152,11 @@ PJ_DECL(pj_ssize_t) pjsip_param_print_on(const pjsip_param *param_list, */ typedef enum pjsip_uri_context_e { - PJSIP_URI_IN_REQ_URI, /**< The URI is in Request URI. */ - PJSIP_URI_IN_FROMTO_HDR, /**< The URI is in From/To header. */ - PJSIP_URI_IN_CONTACT_HDR, /**< The URI is in Contact header. */ - PJSIP_URI_IN_ROUTING_HDR, /**< The URI is in Route/Record-Route header. */ - PJSIP_URI_IN_OTHER /**< Other context (web page, business card, etc.) */ + PJSIP_URI_IN_REQ_URI, /**< The URI is in Request URI. */ + PJSIP_URI_IN_FROMTO_HDR, /**< The URI is in From/To header. */ + PJSIP_URI_IN_CONTACT_HDR, /**< The URI is in Contact header. */ + PJSIP_URI_IN_ROUTING_HDR, /**< The URI is in Route/Record-Route header. */ + PJSIP_URI_IN_OTHER /**< Other context (web page, business card, etc.) */ } pjsip_uri_context_e; /** @@ -192,8 +191,8 @@ typedef struct pjsip_uri_vptr * @return the length printed. */ pj_ssize_t (*p_print)(pjsip_uri_context_e context, - const void *uri, - char *buf, pj_size_t size); + const void *uri, + char *buf, pj_size_t size); /** * Compare two URIs according to the context. @@ -201,10 +200,10 @@ typedef struct pjsip_uri_vptr * @param uri1 the first URI (self). * @param uri2 the second URI. * @return PJ_SUCCESS if equal, or otherwise the error status which - * should point to the mismatch part. + * should point to the mismatch part. */ - pj_status_t (*p_compare)(pjsip_uri_context_e context, - const void *uri1, const void *uri2); + pj_status_t (*p_compare)(pjsip_uri_context_e context, + const void *uri1, const void *uri2); /** * Clone URI. @@ -231,7 +230,7 @@ struct pjsip_uri * @param url The URL (pointer to) * @return non-zero if TRUE. */ -#define PJSIP_URI_SCHEME_IS_SIP(url) \ +#define PJSIP_URI_SCHEME_IS_SIP(url) \ (pj_stricmp2(pjsip_uri_get_scheme(url), "sip")==0) /** @@ -239,7 +238,7 @@ struct pjsip_uri * @param url The URL (pointer to) * @return non-zero if TRUE. */ -#define PJSIP_URI_SCHEME_IS_SIPS(url) \ +#define PJSIP_URI_SCHEME_IS_SIPS(url) \ (pj_stricmp2(pjsip_uri_get_scheme(url), "sips")==0) /** @@ -247,14 +246,14 @@ struct pjsip_uri * @param url The URL (pointer to) * @return non-zero if TRUE. */ -#define PJSIP_URI_SCHEME_IS_TEL(url) \ +#define PJSIP_URI_SCHEME_IS_TEL(url) \ (pj_stricmp2(pjsip_uri_get_scheme(url), "tel")==0) /** * Generic function to get the URI scheme. - * @param uri the URI object. - * @return the URI scheme. + * @param uri the URI object. + * @return the URI scheme. */ PJ_INLINE(const pj_str_t*) pjsip_uri_get_scheme(const void *uri) { @@ -265,8 +264,8 @@ PJ_INLINE(const pj_str_t*) pjsip_uri_get_scheme(const void *uri) * Generic function to get the URI object contained by this URI, or the URI * itself if it doesn't contain another URI. * - * @param uri the URI. - * @return the URI. + * @param uri the URI. + * @return the URI. */ PJ_INLINE(void*) pjsip_uri_get_uri(const void *uri) { @@ -278,13 +277,13 @@ PJ_INLINE(void*) pjsip_uri_get_uri(const void *uri) * Generic function to compare two URIs. * * @param context Comparison context. - * @param uri1 The first URI. - * @param uri2 The second URI. - * @return PJ_SUCCESS if equal, or otherwise the error status which - * should point to the mismatch part. + * @param uri1 The first URI. + * @param uri2 The second URI. + * @return PJ_SUCCESS if equal, or otherwise the error status which + * should point to the mismatch part. */ PJ_INLINE(pj_status_t) pjsip_uri_cmp(pjsip_uri_context_e context, - const void *uri1, const void *uri2) + const void *uri1, const void *uri2) { return (*((const pjsip_uri*)uri1)->vptr->p_compare)(context, uri1, uri2); } @@ -293,25 +292,25 @@ PJ_INLINE(pj_status_t) pjsip_uri_cmp(pjsip_uri_context_e context, * Generic function to print an URI object. * * @param context Print context. - * @param uri The URI to print. - * @param buf The buffer. - * @param size Size of the buffer. - * @return Length printed if successful, negative value if failed. + * @param uri The URI to print. + * @param buf The buffer. + * @param size Size of the buffer. + * @return Length printed if successful, negative value if failed. */ PJ_INLINE(int) pjsip_uri_print(pjsip_uri_context_e context, - const void *uri, - char *buf, pj_size_t size) + const void *uri, + char *buf, pj_size_t size) { return (int)(*((const pjsip_uri*)uri)->vptr->p_print)(context, uri, - buf, size); + buf, size); } /** * Generic function to clone an URI object. * - * @param pool Pool. - * @param uri URI to clone. - * @return New URI. + * @param pool Pool. + * @param uri URI to clone. + * @return New URI. */ PJ_INLINE(void*) pjsip_uri_clone( pj_pool_t *pool, const void *uri ) { @@ -337,19 +336,19 @@ PJ_INLINE(void*) pjsip_uri_clone( pj_pool_t *pool, const void *uri ) */ typedef struct pjsip_sip_uri { - pjsip_uri_vptr *vptr; /**< Pointer to virtual function table.*/ - pj_str_t user; /**< Optional user part. */ - pj_str_t passwd; /**< Optional password part. */ - pj_str_t host; /**< Host part, always exists. */ - int port; /**< Optional port number, or zero. */ - pj_str_t user_param; /**< Optional user parameter */ - pj_str_t method_param; /**< Optional method parameter. */ - pj_str_t transport_param; /**< Optional transport parameter. */ - int ttl_param; /**< Optional TTL param, or -1. */ - int lr_param; /**< Optional loose routing param, or zero */ - pj_str_t maddr_param; /**< Optional maddr param */ - pjsip_param other_param; /**< Other parameters grouped together. */ - pjsip_param header_param; /**< Optional header parameter. */ + pjsip_uri_vptr *vptr; /**< Pointer to virtual function table.*/ + pj_str_t user; /**< Optional user part. */ + pj_str_t passwd; /**< Optional password part. */ + pj_str_t host; /**< Host part, always exists. */ + int port; /**< Optional port number, or zero. */ + pj_str_t user_param; /**< Optional user parameter */ + pj_str_t method_param; /**< Optional method parameter. */ + pj_str_t transport_param; /**< Optional transport parameter. */ + int ttl_param; /**< Optional TTL param, or -1. */ + int lr_param; /**< Optional loose routing param, or zero */ + pj_str_t maddr_param; /**< Optional maddr param */ + pjsip_param other_param; /**< Other parameters grouped together. */ + pjsip_param header_param; /**< Optional header parameter. */ } pjsip_sip_uri; @@ -363,53 +362,53 @@ typedef struct pjsip_name_addr pjsip_uri_vptr *vptr; /** Optional display name. */ - pj_str_t display; + pj_str_t display; /** URI part. */ - pjsip_uri *uri; + pjsip_uri *uri; } pjsip_name_addr; /** * Create new SIP URL and initialize all fields with zero or NULL. - * @param pool The pool. + * @param pool The pool. * @param secure Flag to indicate whether secure transport should be used. * @return SIP URL. */ PJ_DECL(pjsip_sip_uri*) pjsip_sip_uri_create( pj_pool_t *pool, - pj_bool_t secure ); + pj_bool_t secure ); /** * Change the SIP URI scheme to sip or sips based on the secure flag. * This would not change anything except the scheme. - * @param uri The URI + * @param uri The URI * @param secure Non-zero if sips is wanted. */ PJ_DECL(void) pjsip_sip_uri_set_secure( pjsip_sip_uri *uri, - pj_bool_t secure ); + pj_bool_t secure ); /** * Initialize SIP URL (all fields are set to NULL or zero). - * @param url The URL. + * @param url The URL. * @param secure Create sips URI? */ PJ_DECL(void) pjsip_sip_uri_init(pjsip_sip_uri *url, pj_bool_t secure); /** * Perform full assignment to the SIP URL. - * @param pool The pool. - * @param url Destination URL. - * @param rhs The source URL. + * @param pool The pool. + * @param url Destination URL. + * @param rhs The source URL. */ PJ_DECL(void) pjsip_sip_uri_assign(pj_pool_t *pool, pjsip_sip_uri *url, - const pjsip_sip_uri *rhs); + const pjsip_sip_uri *rhs); /** * Create new instance of name address and initialize all fields with zero or * NULL. - * @param pool The pool. - * @return New SIP name address. + * @param pool The pool. + * @return New SIP name address. */ PJ_DECL(pjsip_name_addr*) pjsip_name_addr_create(pj_pool_t *pool); @@ -421,13 +420,13 @@ PJ_DECL(void) pjsip_name_addr_init(pjsip_name_addr *name_addr); /** * Perform full assignment to the name address. - * @param pool The pool. - * @param addr The destination name address. - * @param rhs The source name address. + * @param pool The pool. + * @param addr The destination name address. + * @param rhs The source name address. */ PJ_DECL(void) pjsip_name_addr_assign(pj_pool_t *pool, - pjsip_name_addr *addr, - const pjsip_name_addr *rhs); + pjsip_name_addr *addr, + const pjsip_name_addr *rhs); /** * @} @@ -445,18 +444,18 @@ PJ_DECL(void) pjsip_name_addr_assign(pj_pool_t *pool, */ typedef struct pjsip_other_uri { - pjsip_uri_vptr *vptr; /**< Pointer to virtual function table. */ - pj_str_t scheme; /**< The URI scheme (e.g. "mailto") */ - pj_str_t content; /**< The whole URI content */ + pjsip_uri_vptr *vptr; /**< Pointer to virtual function table. */ + pj_str_t scheme; /**< The URI scheme (e.g. "mailto") */ + pj_str_t content; /**< The whole URI content */ } pjsip_other_uri; /** * Create a generic URI object. * - * @param pool The pool to allocate memory from. + * @param pool The pool to allocate memory from. * - * @return The URI instance. + * @return The URI instance. */ PJ_DECL(pjsip_other_uri*) pjsip_other_uri_create(pj_pool_t *pool); @@ -467,5 +466,5 @@ PJ_DECL(pjsip_other_uri*) pjsip_other_uri_create(pj_pool_t *pool); PJ_END_DECL -#endif /* __PJSIP_URL_H__ */ +#endif /* __PJSIP_URL_H__ */ diff --git a/pjsip/include/pjsip/sip_util.h b/pjsip/include/pjsip/sip_util.h index 3e7ff135b8..bba120fc74 100644 --- a/pjsip/include/pjsip/sip_util.h +++ b/pjsip/include/pjsip/sip_util.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -55,10 +54,10 @@ PJ_BEGIN_DECL typedef struct pjsip_target { PJ_DECL_LIST_MEMBER(struct pjsip_target);/**< Standard list element */ - pjsip_uri *uri; /**< The target URI */ - int q1000; /**< q-value multiplied by 1000 */ - pjsip_status_code code; /**< Last status code received */ - pj_str_t reason; /**< Last reason phrase received */ + pjsip_uri *uri; /**< The target URI */ + int q1000; /**< q-value multiplied by 1000 */ + pjsip_status_code code; /**< Last status code received */ + pj_str_t reason; /**< Last reason phrase received */ } pjsip_target; @@ -68,8 +67,8 @@ typedef struct pjsip_target */ typedef struct pjsip_target_set { - pjsip_target head; /**< Target linked-list head */ - pjsip_target *current; /**< Current target. */ + pjsip_target head; /**< Target linked-list head */ + pjsip_target *current; /**< Current target. */ } pjsip_target_set; @@ -117,7 +116,7 @@ typedef enum pjsip_redirect_op * Initialize target set. This will empty the list of targets in the * target set. * - * @param tset The target set. + * @param tset The target set. */ PJ_INLINE(void) pjsip_target_set_init(pjsip_target_set *tset) { @@ -136,40 +135,40 @@ PJ_INLINE(void) pjsip_target_set_init(pjsip_target_set *tset) * The first URI added to the target set will also be made current target * by this function. * - * @param tset The target set. - * @param pool The memory pool to be used to duplicate the URI. - * @param uri The URI to be checked and added. - * @param q1000 The q-value multiplied by 1000. + * @param tset The target set. + * @param pool The memory pool to be used to duplicate the URI. + * @param uri The URI to be checked and added. + * @param q1000 The q-value multiplied by 1000. * - * @return PJ_SUCCESS if the URI was added to the target set, - * or PJ_EEXISTS if the URI already exists in the target - * set, or other error codes. + * @return PJ_SUCCESS if the URI was added to the target set, + * or PJ_EEXISTS if the URI already exists in the target + * set, or other error codes. */ PJ_DECL(pj_status_t) pjsip_target_set_add_uri(pjsip_target_set *tset, - pj_pool_t *pool, - const pjsip_uri *uri, - int q1000); + pj_pool_t *pool, + const pjsip_uri *uri, + int q1000); /** * Extract URI's in the Contact headers of the specified (response) message * and add them to the target set. This function will also check if the * URI's already exist in the target set before adding them to the list. * - * @param tset The target set. - * @param pool The memory pool to be used to duplicate the URI's. - * @param msg SIP message from which the Contact headers will be - * scanned and the URI's to be extracted, checked, and - * added to the target set. + * @param tset The target set. + * @param pool The memory pool to be used to duplicate the URI's. + * @param msg SIP message from which the Contact headers will be + * scanned and the URI's to be extracted, checked, and + * added to the target set. * - * @return PJ_SUCCESS if at least one URI was added to the - * target set, or PJ_EEXISTS if all URI's in the message - * already exists in the target set or if the message - * doesn't contain usable Contact headers, or other error - * codes. + * @return PJ_SUCCESS if at least one URI was added to the + * target set, or PJ_EEXISTS if all URI's in the message + * already exists in the target set or if the message + * doesn't contain usable Contact headers, or other error + * codes. */ PJ_DECL(pj_status_t) pjsip_target_set_add_from_msg(pjsip_target_set *tset, - pj_pool_t *pool, - const pjsip_msg *msg); + pj_pool_t *pool, + const pjsip_msg *msg); /** * Get the next target to be retried. This function will scan the target set @@ -178,11 +177,11 @@ PJ_DECL(pj_status_t) pjsip_target_set_add_from_msg(pjsip_target_set *tset, * if there is one target with 2xx or 6xx code or if all targets have been * tried. * - * @param tset The target set. + * @param tset The target set. * - * @return The next target to be tried, or NULL if all targets have - * been tried or at least one target returns 2xx or 6xx - * response. + * @return The next target to be tried, or NULL if all targets have + * been tried or at least one target returns 2xx or 6xx + * response. */ PJ_DECL(pjsip_target*) pjsip_target_set_get_next(const pjsip_target_set *tset); @@ -193,30 +192,30 @@ pjsip_target_set_get_next(const pjsip_target_set *tset); * current target may be used by application to keep track on which target * is currently being operated on. * - * @param tset The target set. + * @param tset The target set. * @param target The target to be set as current target. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_target_set_set_current(pjsip_target_set *tset, - pjsip_target *target); + pjsip_target *target); /** * Set the status code and reason phrase of the specified target. * * @param target The target. - * @param pool The memory pool to be used to duplicate the reason phrase. - * @param status_code The SIP status code to be set to the target. + * @param pool The memory pool to be used to duplicate the reason phrase. + * @param status_code The SIP status code to be set to the target. * @param reason The reason phrase to be set to the target. * - * @return PJ_SUCCESS on successful operation or the appropriate - * error code. + * @return PJ_SUCCESS on successful operation or the appropriate + * error code. */ PJ_DECL(pj_status_t) pjsip_target_assign_status(pjsip_target *target, - pj_pool_t *pool, - int status_code, - const pj_str_t *reason); + pj_pool_t *pool, + int status_code, + const pj_str_t *reason); /** * @} @@ -245,37 +244,37 @@ PJ_DECL(pj_status_t) pjsip_target_assign_status(pjsip_target *target, * * Once a transmit data is created, the reference counter is initialized to 1. * - * @param endpt Endpoint instance. + * @param endpt Endpoint instance. * @param method SIP Method. * @param target Target URI. - * @param from URL to put in From header. - * @param to URL to put in To header. + * @param from URL to put in From header. + * @param to URL to put in To header. * @param contact Contact to be put as Contact header value, hence - * the format must follow RFC 3261 Section 20.10: - * When the header field value contains a display - * name, the URI including all URI parameters is - * enclosed in "<" and ">". If no "<" and ">" are - * present, all parameters after the URI are header - * parameters, not URI parameters. The display name - * can be tokens, or a quoted string, if a larger - * character set is desired. + * the format must follow RFC 3261 Section 20.10: + * When the header field value contains a display + * name, the URI including all URI parameters is + * enclosed in "<" and ">". If no "<" and ">" are + * present, all parameters after the URI are header + * parameters, not URI parameters. The display name + * can be tokens, or a quoted string, if a larger + * character set is desired. * @param call_id Optional Call-ID (put NULL to generate unique Call-ID). - * @param cseq Optional CSeq (put -1 to generate random CSeq). - * @param text Optional text body (put NULL to omit body). + * @param cseq Optional CSeq (put -1 to generate random CSeq). + * @param text Optional text body (put NULL to omit body). * @param p_tdata Pointer to receive the transmit data. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_endpt_create_request( pjsip_endpoint *endpt, - const pjsip_method *method, - const pj_str_t *target, - const pj_str_t *from, - const pj_str_t *to, - const pj_str_t *contact, - const pj_str_t *call_id, - int cseq, - const pj_str_t *text, - pjsip_tx_data **p_tdata); + const pjsip_method *method, + const pj_str_t *target, + const pj_str_t *from, + const pj_str_t *to, + const pj_str_t *contact, + const pj_str_t *call_id, + int cseq, + const pj_str_t *text, + pjsip_tx_data **p_tdata); /** * Create an independent request message from the specified headers. This @@ -292,30 +291,30 @@ PJ_DECL(pj_status_t) pjsip_endpt_create_request( pjsip_endpoint *endpt, * * Once a transmit data is created, the reference counter is initialized to 1. * - * @param endpt Endpoint instance. + * @param endpt Endpoint instance. * @param method SIP Method. * @param target Target URI. - * @param from From header. - * @param to To header. + * @param from From header. + * @param to To header. * @param contact Contact header. * @param call_id Optional Call-ID (put NULL to generate unique Call-ID). - * @param cseq Optional CSeq (put -1 to generate random CSeq). - * @param text Optional text body (put NULL to omit body). + * @param cseq Optional CSeq (put -1 to generate random CSeq). + * @param text Optional text body (put NULL to omit body). * @param p_tdata Pointer to receive the transmit data. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_endpt_create_request_from_hdr( pjsip_endpoint *endpt, - const pjsip_method *method, - const pjsip_uri *target, - const pjsip_from_hdr *from, - const pjsip_to_hdr *to, - const pjsip_contact_hdr *contact, - const pjsip_cid_hdr *call_id, - int cseq, - const pj_str_t *text, - pjsip_tx_data **p_tdata); + const pjsip_method *method, + const pjsip_uri *target, + const pjsip_from_hdr *from, + const pjsip_to_hdr *to, + const pjsip_contact_hdr *contact, + const pjsip_cid_hdr *call_id, + int cseq, + const pj_str_t *text, + pjsip_tx_data **p_tdata); /** * Construct a minimal response message for the received request. This function @@ -324,19 +323,19 @@ pjsip_endpt_create_request_from_hdr( pjsip_endpoint *endpt, * * Once a transmit data is created, the reference counter is initialized to 1. * - * @param endpt The endpoint. - * @param rdata The request receive data. + * @param endpt The endpoint. + * @param rdata The request receive data. * @param st_code Status code to be put in the response. * @param st_text Optional status text, or NULL to get the default text. * @param p_tdata Pointer to receive the transmit data. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_endpt_create_response( pjsip_endpoint *endpt, - const pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - pjsip_tx_data **p_tdata); + const pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + pjsip_tx_data **p_tdata); /** * Construct a full ACK request for the received non-2xx final response. @@ -347,17 +346,17 @@ PJ_DECL(pj_status_t) pjsip_endpt_create_response( pjsip_endpoint *endpt, * * Once a transmit data is created, the reference counter is initialized to 1. * - * @param endpt The endpoint. - * @param tdata This contains the original INVITE request - * @param rdata The final response. - * @param ack The ACK request created. + * @param endpt The endpoint. + * @param tdata This contains the original INVITE request + * @param rdata The final response. + * @param ack The ACK request created. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_endpt_create_ack( pjsip_endpoint *endpt, - const pjsip_tx_data *tdata, - const pjsip_rx_data *rdata, - pjsip_tx_data **ack); + const pjsip_tx_data *tdata, + const pjsip_rx_data *rdata, + pjsip_tx_data **ack); /** @@ -365,31 +364,31 @@ PJ_DECL(pj_status_t) pjsip_endpt_create_ack( pjsip_endpoint *endpt, * * Once a transmit data is created, the reference counter is initialized to 1. * - * @param endpt The endpoint. - * @param tdata The transmit buffer for the request being cancelled. + * @param endpt The endpoint. + * @param tdata The transmit buffer for the request being cancelled. * @param p_tdata Pointer to receive the transmit data. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_endpt_create_cancel( pjsip_endpoint *endpt, - const pjsip_tx_data *tdata, - pjsip_tx_data **p_tdata); + const pjsip_tx_data *tdata, + pjsip_tx_data **p_tdata); /** * Get destination address and port and transport type information for the * specified URI. * - * @param target_uri The destination URI. - * @param request_uri Optional request URI to be considered. May be NULL. - * @param pool Pool to allocate memory from. - * @param dest_info To be filled with destination info. + * @param target_uri The destination URI. + * @param request_uri Optional request URI to be considered. May be NULL. + * @param pool Pool to allocate memory from. + * @param dest_info To be filled with destination info. * - * @return PJ_SUCCESS or the appropriate error code. + * @return PJ_SUCCESS or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_get_dest_info(const pjsip_uri *target_uri, - const pjsip_uri *request_uri, - pj_pool_t *pool, - pjsip_host_info *dest_info); + const pjsip_uri *request_uri, + pj_pool_t *pool, + pjsip_host_info *dest_info); /** * Find which destination to be used to send the request message, based @@ -403,19 +402,19 @@ PJ_DECL(pj_status_t) pjsip_get_dest_info(const pjsip_uri *target_uri, * longer the case now, and this process is done in separate function * (see #pjsip_process_route_set()). * - * @param tdata The transmit data containing the request message. + * @param tdata The transmit data containing the request message. * @param dest_info On return, it contains information about destination - * host to contact, along with the preferable transport - * type, if any. Caller will then normally proceed with - * resolving this host with server resolution procedure - * described in RFC 3263. + * host to contact, along with the preferable transport + * type, if any. Caller will then normally proceed with + * resolving this host with server resolution procedure + * described in RFC 3263. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. * * @see pjsip_process_route_set */ PJ_DECL(pj_status_t) pjsip_get_request_dest(const pjsip_tx_data *tdata, - pjsip_host_info *dest_info ); + pjsip_host_info *dest_info ); /** @@ -430,19 +429,19 @@ PJ_DECL(pj_status_t) pjsip_get_request_dest(const pjsip_tx_data *tdata, * case, the target URI will be put as the request URI of the request and * current request URI will be put as the last entry of the Route headers. * - * @param tdata The transmit data containing the request message. + * @param tdata The transmit data containing the request message. * @param dest_info On return, it contains information about destination - * host to contact, along with the preferable transport - * type, if any. Caller will then normally proceed with - * resolving this host with server resolution procedure - * described in RFC 3263. + * host to contact, along with the preferable transport + * type, if any. Caller will then normally proceed with + * resolving this host with server resolution procedure + * described in RFC 3263. * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. * * @see pjsip_get_request_addr */ PJ_DECL(pj_status_t) pjsip_process_route_set(pjsip_tx_data *tdata, - pjsip_host_info *dest_info ); + pjsip_host_info *dest_info ); /** @@ -454,7 +453,7 @@ PJ_DECL(pj_status_t) pjsip_process_route_set(pjsip_tx_data *tdata, * This function should only used internally by PJSIP client authentication * module. * - * @param tdata Transmit data containing request message. + * @param tdata Transmit data containing request message. */ PJ_DECL(void) pjsip_restore_strict_route_set(pjsip_tx_data *tdata); @@ -485,8 +484,8 @@ typedef struct pjsip_send_state * #pjsip_endpt_send_request_stateless() was called. */ void (*app_cb)(struct pjsip_send_state*, - pj_ssize_t sent, - pj_bool_t *cont); + pj_ssize_t sent, + pj_bool_t *cont); } pjsip_send_state; @@ -495,13 +494,13 @@ typedef struct pjsip_send_state * #pjsip_endpt_send_request_stateless(), #pjsip_endpt_send_response(), or * #pjsip_endpt_send_response2(). * - * @param st Structure to keep transmission state. - * @param sent Number of bytes sent. - * @param cont When current transmission fails, specify whether - * the function should fallback to next destination. + * @param st Structure to keep transmission state. + * @param sent Number of bytes sent. + * @param cont When current transmission fails, specify whether + * the function should fallback to next destination. */ typedef void (*pjsip_send_callback)(pjsip_send_state *st, pj_ssize_t sent, - pj_bool_t *cont); + pj_bool_t *cont); /** * Send outgoing request statelessly The function will take care of which @@ -511,58 +510,58 @@ typedef void (*pjsip_send_callback)(pjsip_send_state *st, pj_ssize_t sent, * This function is different than #pjsip_transport_send() in that this * function adds/modify the Via header as necessary. * - * @param endpt The endpoint instance. - * @param tdata The transmit data to be sent. - * @param token Arbitrary token to be given back on the callback. - * @param cb Optional callback to notify transmission status (also - * gives chance for application to discontinue retrying - * sending to alternate address). + * @param endpt The endpoint instance. + * @param tdata The transmit data to be sent. + * @param token Arbitrary token to be given back on the callback. + * @param cb Optional callback to notify transmission status (also + * gives chance for application to discontinue retrying + * sending to alternate address). * - * @return PJ_SUCCESS, or the appropriate error code. + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_endpt_send_request_stateless( pjsip_endpoint *endpt, - pjsip_tx_data *tdata, - void *token, - pjsip_send_callback cb); + pjsip_tx_data *tdata, + void *token, + pjsip_send_callback cb); /** * This is a low-level function to send raw data to a destination. * * See also #pjsip_endpt_send_raw_to_uri(). * - * @param endpt The SIP endpoint instance. + * @param endpt The SIP endpoint instance. * @param tp_type Transport type. - * @param sel Optional pointer to transport selector instance if - * application wants to use a specific transport instance - * rather then letting transport manager finds the suitable - * transport.. + * @param sel Optional pointer to transport selector instance if + * application wants to use a specific transport instance + * rather then letting transport manager finds the suitable + * transport.. * @param raw_data The data to be sent. * @param data_len The length of the data. - * @param addr Destination address. + * @param addr Destination address. * @param addr_len Length of destination address. - * @param token Arbitrary token to be returned back to callback. - * @param cb Optional callback to be called to notify caller about - * the completion status of the pending send operation. - * - * @return If the message has been sent successfully, this function - * will return PJ_SUCCESS and the callback will not be - * called. If message cannot be sent immediately, this - * function will return PJ_EPENDING, and application will - * be notified later about the completion via the callback. - * Any statuses other than PJ_SUCCESS or PJ_EPENDING - * indicates immediate failure, and in this case the - * callback will not be called. + * @param token Arbitrary token to be returned back to callback. + * @param cb Optional callback to be called to notify caller about + * the completion status of the pending send operation. + * + * @return If the message has been sent successfully, this function + * will return PJ_SUCCESS and the callback will not be + * called. If message cannot be sent immediately, this + * function will return PJ_EPENDING, and application will + * be notified later about the completion via the callback. + * Any statuses other than PJ_SUCCESS or PJ_EPENDING + * indicates immediate failure, and in this case the + * callback will not be called. */ PJ_DECL(pj_status_t) pjsip_endpt_send_raw(pjsip_endpoint *endpt, - pjsip_transport_type_e tp_type, - const pjsip_tpselector *sel, - const void *raw_data, - pj_size_t data_len, - const pj_sockaddr_t *addr, - int addr_len, - void *token, - pjsip_tp_send_callback cb); + pjsip_transport_type_e tp_type, + const pjsip_tpselector *sel, + const void *raw_data, + pj_size_t data_len, + const pj_sockaddr_t *addr, + int addr_len, + void *token, + pjsip_tp_send_callback cb); /** * Send raw data to the specified destination URI. The actual destination @@ -571,34 +570,34 @@ PJ_DECL(pj_status_t) pjsip_endpt_send_raw(pjsip_endpoint *endpt, * * See also #pjsip_endpt_send_raw(). * - * @param endpt The SIP endpoint instance. + * @param endpt The SIP endpoint instance. * @param dst_uri Destination address URI. - * @param sel Optional pointer to transport selector instance if - * application wants to use a specific transport instance - * rather then letting transport manager finds the suitable - * transport.. + * @param sel Optional pointer to transport selector instance if + * application wants to use a specific transport instance + * rather then letting transport manager finds the suitable + * transport.. * @param raw_data The data to be sent. * @param data_len The length of the data. - * @param token Arbitrary token to be returned back to callback. - * @param cb Optional callback to be called to notify caller about - * the completion status of the pending send operation. - * - * @return If the message has been sent successfully, this function - * will return PJ_SUCCESS and the callback will not be - * called. If message cannot be sent immediately, this - * function will return PJ_EPENDING, and application will - * be notified later about the completion via the callback. - * Any statuses other than PJ_SUCCESS or PJ_EPENDING - * indicates immediate failure, and in this case the - * callback will not be called. + * @param token Arbitrary token to be returned back to callback. + * @param cb Optional callback to be called to notify caller about + * the completion status of the pending send operation. + * + * @return If the message has been sent successfully, this function + * will return PJ_SUCCESS and the callback will not be + * called. If message cannot be sent immediately, this + * function will return PJ_EPENDING, and application will + * be notified later about the completion via the callback. + * Any statuses other than PJ_SUCCESS or PJ_EPENDING + * indicates immediate failure, and in this case the + * callback will not be called. */ PJ_DECL(pj_status_t) pjsip_endpt_send_raw_to_uri(pjsip_endpoint *endpt, - const pj_str_t *dst_uri, - const pjsip_tpselector *sel, - const void *raw_data, - pj_size_t data_len, - void *token, - pjsip_tp_send_callback cb); + const pj_str_t *dst_uri, + const pjsip_tpselector *sel, + const void *raw_data, + pj_size_t data_len, + void *token, + pjsip_tp_send_callback cb); /** * This structure describes destination information to send response. @@ -616,10 +615,10 @@ PJ_DECL(pj_status_t) pjsip_endpt_send_raw_to_uri(pjsip_endpoint *endpt, */ typedef struct pjsip_response_addr { - pjsip_transport *transport; /**< Immediate transport to be used. */ - pj_sockaddr addr; /**< Immediate address to send to. */ - int addr_len; /**< Address length. */ - pjsip_host_info dst_host; /**< Destination host to contact. */ + pjsip_transport *transport; /**< Immediate transport to be used. */ + pj_sockaddr addr; /**< Immediate address to send to. */ + int addr_len; /**< Address length. */ + pjsip_host_info dst_host; /**< Destination host to contact. */ } pjsip_response_addr; /** @@ -631,16 +630,16 @@ typedef struct pjsip_response_addr * The information about destination to send the response will be returned * in res_addr argument. Please see #pjsip_response_addr for more info. * - * @param pool The pool. - * @param rdata The incoming request received by the server. + * @param pool The pool. + * @param rdata The incoming request received by the server. * @param res_addr On return, it will be initialized with information about - * destination address and transport to send the response. + * destination address and transport to send the response. * - * @return zero (PJ_OK) if successfull. + * @return zero (PJ_OK) if successfull. */ PJ_DECL(pj_status_t) pjsip_get_response_addr(pj_pool_t *pool, - pjsip_rx_data *rdata, - pjsip_response_addr *res_addr); + pjsip_rx_data *rdata, + pjsip_response_addr *res_addr); /** * Send response in tdata statelessly. The function will take care of which @@ -655,72 +654,72 @@ PJ_DECL(pj_status_t) pjsip_get_response_addr(pj_pool_t *pool, * The behavior of this function complies with section 18.2.2 of RFC 3261 * and RFC 3581. * - * @param endpt The endpoint instance. + * @param endpt The endpoint instance. * @param res_addr The information about the address and transport to send - * the response to. Application can get this information - * by calling #pjsip_get_response_addr(). - * @param tdata The response message to be sent. - * @param token Token to be passed back when the callback is called. - * @param cb Optional callback to notify the transmission status - * to application, and to inform whether next address or - * transport will be tried. + * the response to. Application can get this information + * by calling #pjsip_get_response_addr(). + * @param tdata The response message to be sent. + * @param token Token to be passed back when the callback is called. + * @param cb Optional callback to notify the transmission status + * to application, and to inform whether next address or + * transport will be tried. * - * @return PJ_SUCCESS if response has been successfully created and - * sent to transport layer, or a non-zero error code. - * However, even when it returns PJ_SUCCESS, there is no - * guarantee that the response has been successfully sent. + * @return PJ_SUCCESS if response has been successfully created and + * sent to transport layer, or a non-zero error code. + * However, even when it returns PJ_SUCCESS, there is no + * guarantee that the response has been successfully sent. */ PJ_DECL(pj_status_t) pjsip_endpt_send_response( pjsip_endpoint *endpt, - pjsip_response_addr *res_addr, - pjsip_tx_data *tdata, - void *token, - pjsip_send_callback cb); + pjsip_response_addr *res_addr, + pjsip_tx_data *tdata, + void *token, + pjsip_send_callback cb); /** * This is a convenient function which wraps #pjsip_get_response_addr() and * #pjsip_endpt_send_response() in a single function. * - * @param endpt The endpoint instance. - * @param rdata The original request to be responded. - * @param tdata The response message to be sent. - * @param token Token to be passed back when the callback is called. - * @param cb Optional callback to notify the transmission status - * to application, and to inform whether next address or - * transport will be tried. + * @param endpt The endpoint instance. + * @param rdata The original request to be responded. + * @param tdata The response message to be sent. + * @param token Token to be passed back when the callback is called. + * @param cb Optional callback to notify the transmission status + * to application, and to inform whether next address or + * transport will be tried. * - * @return PJ_SUCCESS if response has been successfully created and - * sent to transport layer, or a non-zero error code. - * However, even when it returns PJ_SUCCESS, there is no - * guarantee that the response has been successfully sent. + * @return PJ_SUCCESS if response has been successfully created and + * sent to transport layer, or a non-zero error code. + * However, even when it returns PJ_SUCCESS, there is no + * guarantee that the response has been successfully sent. */ PJ_DECL(pj_status_t) pjsip_endpt_send_response2(pjsip_endpoint *endpt, - pjsip_rx_data *rdata, - pjsip_tx_data *tdata, - void *token, - pjsip_send_callback cb); + pjsip_rx_data *rdata, + pjsip_tx_data *tdata, + void *token, + pjsip_send_callback cb); /** * This composite function sends response message statelessly to an incoming * request message. Internally it calls #pjsip_endpt_create_response() and * #pjsip_endpt_send_response(). * - * @param endpt The endpoint instance. - * @param rdata The incoming request message. + * @param endpt The endpoint instance. + * @param rdata The incoming request message. * @param st_code Status code of the response. * @param st_text Optional status text of the response. * @param hdr_list Optional header list to be added to the response. - * @param body Optional message body to be added to the response. + * @param body Optional message body to be added to the response. * - * @return PJ_SUCCESS if response message has successfully been - * sent. + * @return PJ_SUCCESS if response message has successfully been + * sent. */ PJ_DECL(pj_status_t) pjsip_endpt_respond_stateless(pjsip_endpoint *endpt, - pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - const pjsip_hdr *hdr_list, - const pjsip_msg_body *body); - + pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + const pjsip_hdr *hdr_list, + const pjsip_msg_body *body); + /** * @} */ @@ -736,33 +735,33 @@ PJ_DECL(pj_status_t) pjsip_endpt_respond_stateless(pjsip_endpoint *endpt, * This composite function creates and sends response statefully for the * incoming request. * - * @param endpt The endpoint instance. + * @param endpt The endpoint instance. * @param tsx_user The module to be registered as transaction user. - * @param rdata The incoming request message. + * @param rdata The incoming request message. * @param st_code Status code of the response. * @param st_text Optional status text of the response. * @param hdr_list Optional header list to be added to the response. - * @param body Optional message body to be added to the response. - * @param p_tsx Optional pointer to receive the transaction which was - * created to send the response. + * @param body Optional message body to be added to the response. + * @param p_tsx Optional pointer to receive the transaction which was + * created to send the response. * - * @return PJ_SUCCESS if response message has successfully been - * created. + * @return PJ_SUCCESS if response message has successfully been + * created. */ PJ_DECL(pj_status_t) pjsip_endpt_respond( pjsip_endpoint *endpt, - pjsip_module *tsx_user, - pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - const pjsip_hdr *hdr_list, - const pjsip_msg_body *body, - pjsip_transaction **p_tsx ); + pjsip_module *tsx_user, + pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + const pjsip_hdr *hdr_list, + const pjsip_msg_body *body, + pjsip_transaction **p_tsx ); /** * Type of callback to be specified in #pjsip_endpt_send_request(). * - * @param token The token that was given in #pjsip_endpt_send_request() - * @param e Completion event. + * @param token The token that was given in #pjsip_endpt_send_request() + * @param e Completion event. */ typedef void (*pjsip_endpt_send_callback)(void *token, pjsip_event *e); @@ -772,27 +771,27 @@ typedef void (*pjsip_endpt_send_callback)(void *token, pjsip_event *e); * requests outside a dialog. To send a request within a dialog, application * should use #pjsip_dlg_send_request instead. * - * @param endpt The endpoint instance. - * @param tdata The transmit data to be sent. + * @param endpt The endpoint instance. + * @param tdata The transmit data to be sent. * @param timeout Optional timeout for final response to be received, or -1 - * if the transaction should not have a timeout restriction. - * The value is in miliseconds. Note that this is not - * implemented yet, so application needs to use its own timer - * to handle timeout. - * @param token Optional token to be associated with the transaction, and - * to be passed to the callback. - * @param cb Optional callback to be called when the transaction has - * received a final response. The callback will be called with - * the previously registered token and the event that triggers - * the completion of the transaction. - * - * @return PJ_SUCCESS, or the appropriate error code. + * if the transaction should not have a timeout restriction. + * The value is in miliseconds. Note that this is not + * implemented yet, so application needs to use its own timer + * to handle timeout. + * @param token Optional token to be associated with the transaction, and + * to be passed to the callback. + * @param cb Optional callback to be called when the transaction has + * received a final response. The callback will be called with + * the previously registered token and the event that triggers + * the completion of the transaction. + * + * @return PJ_SUCCESS, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsip_endpt_send_request( pjsip_endpoint *endpt, - pjsip_tx_data *tdata, - pj_int32_t timeout, - void *token, - pjsip_endpt_send_callback cb); + pjsip_tx_data *tdata, + pj_int32_t timeout, + void *token, + pjsip_endpt_send_callback cb); /** * @} @@ -812,29 +811,29 @@ PJ_DECL(pj_status_t) pjsip_endpt_send_request( pjsip_endpoint *endpt, * the Via header. If it is NULL, then a unique branch parameter will be used. * * Note: this function DOES NOT perform Route information preprocessing as - * described in RFC 3261 Section 16.4. Application must take care of - * removing/updating the Route headers according of the rules as - * described in that section. + * described in RFC 3261 Section 16.4. Application must take care of + * removing/updating the Route headers according of the rules as + * described in that section. * - * @param endpt The endpoint instance. - * @param rdata The incoming request message. - * @param uri The URI where the request will be forwarded to. + * @param endpt The endpoint instance. + * @param rdata The incoming request message. + * @param uri The URI where the request will be forwarded to. * @param branch Optional branch parameter. Application may specify its - * own branch, for example if it wishes to perform loop - * detection. If the branch parameter is not specified, - * this function will generate its own by calling - * #pjsip_calculate_branch_id() function. + * own branch, for example if it wishes to perform loop + * detection. If the branch parameter is not specified, + * this function will generate its own by calling + * #pjsip_calculate_branch_id() function. * @param options Optional option flags when duplicating the message. - * @param tdata The result. + * @param tdata The result. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_endpt_create_request_fwd(pjsip_endpoint *endpt, - pjsip_rx_data *rdata, - const pjsip_uri *uri, - const pj_str_t *branch, - unsigned options, - pjsip_tx_data **tdata); + pjsip_rx_data *rdata, + const pjsip_uri *uri, + const pj_str_t *branch, + unsigned options, + pjsip_tx_data **tdata); @@ -846,17 +845,17 @@ PJ_DECL(pj_status_t) pjsip_endpt_create_request_fwd(pjsip_endpoint *endpt, * full/deep clone of the response, unless other copy mechanism is used in * the options. * - * @param endpt The endpoint instance. - * @param rdata The incoming response message. + * @param endpt The endpoint instance. + * @param rdata The incoming response message. * @param options Optional option flags when duplicate the message. - * @param tdata The result + * @param tdata The result * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsip_endpt_create_response_fwd( pjsip_endpoint *endpt, - pjsip_rx_data *rdata, - unsigned options, - pjsip_tx_data **tdata); + pjsip_rx_data *rdata, + unsigned options, + pjsip_tx_data **tdata); @@ -872,9 +871,9 @@ PJ_DECL(pj_status_t) pjsip_endpt_create_response_fwd( pjsip_endpoint *endpt, * * Note that the returned string was allocated from rdata's pool. * - * @param rdata The incoming request message. + * @param rdata The incoming request message. * - * @return Unique branch-ID string. + * @return Unique branch-ID string. */ PJ_DECL(pj_str_t) pjsip_calculate_branch_id( pjsip_rx_data *rdata ); @@ -885,5 +884,5 @@ PJ_DECL(pj_str_t) pjsip_calculate_branch_id( pjsip_rx_data *rdata ); PJ_END_DECL -#endif /* __PJSIP_SIP_MISC_H__ */ +#endif /* __PJSIP_SIP_MISC_H__ */ diff --git a/pjsip/include/pjsip_auth.h b/pjsip/include/pjsip_auth.h index 7adf26bb5b..60d10abad5 100644 --- a/pjsip/include/pjsip_auth.h +++ b/pjsip/include/pjsip_auth.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,5 +33,5 @@ #include #include -#endif /* __PJSIP_AUTH_H__ */ +#endif /* __PJSIP_AUTH_H__ */ diff --git a/pjsip/include/pjsip_simple.h b/pjsip/include/pjsip_simple.h index b60ce4c279..95b1cea91d 100644 --- a/pjsip/include/pjsip_simple.h +++ b/pjsip/include/pjsip_simple.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -43,4 +42,4 @@ #include #include -#endif /* __PJSIP_SIMPLE_H__ */ +#endif /* __PJSIP_SIMPLE_H__ */ diff --git a/pjsip/include/pjsip_ua.h b/pjsip/include/pjsip_ua.h index 2f5da2ee25..234983a117 100644 --- a/pjsip/include/pjsip_ua.h +++ b/pjsip/include/pjsip_ua.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,5 +27,5 @@ #include -#endif /* __PJSIP_UA_H__ */ +#endif /* __PJSIP_UA_H__ */ diff --git a/pjsip/include/pjsua-lib/pjsua.h b/pjsip/include/pjsua-lib/pjsua.h index 5f1b489938..2a88aefa89 100644 --- a/pjsip/include/pjsua-lib/pjsua.h +++ b/pjsip/include/pjsua-lib/pjsua.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -152,7 +151,7 @@ PJ_BEGIN_DECL static pj_status_t app_init(void) { - pjsua_config ua_cfg; + pjsua_config ua_cfg; pjsua_logging_config log_cfg; pjsua_media_config media_cfg; pj_status_t status; @@ -160,8 +159,8 @@ PJ_BEGIN_DECL // Must create pjsua before anything else! status = pjsua_create(); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error initializing pjsua", status); - return status; + pjsua_perror(THIS_FILE, "Error initializing pjsua", status); + return status; } // Initialize configs with default settings. @@ -183,7 +182,7 @@ PJ_BEGIN_DECL status = pjsua_init(&ua_cfg, &log_cfg, &media_cfg); if (status != PJ_SUCCESS) { pjsua_perror(THIS_FILE, "Error initializing pjsua", status); - return status; + return status; } . ... @@ -232,18 +231,18 @@ PJ_BEGIN_DECL // Start pjsua status = pjsua_start(); if (status != PJ_SUCCESS) { - pjsua_destroy(); - pjsua_perror(THIS_FILE, "Error starting pjsua", status); - return status; + pjsua_destroy(); + pjsua_perror(THIS_FILE, "Error starting pjsua", status); + return status; } // Run application loop while (1) { - char choice[10]; - - printf("Select menu: "); - fgets(choice, sizeof(choice), stdin); - ... + char choice[10]; + + printf("Select menu: "); + fgets(choice, sizeof(choice), stdin); + ... } } \endcode @@ -257,7 +256,7 @@ enum pjsua_invalid_id_const_ }; /** Disabled features temporarily for media reorganization */ -#define DISABLED_FOR_TICKET_1185 0 +#define DISABLED_FOR_TICKET_1185 0 /** Call identification */ typedef int pjsua_call_id; @@ -290,28 +289,28 @@ typedef struct pj_stun_resolve_result pj_stun_resolve_result; * Initial memory block for PJSUA. */ #ifndef PJSUA_POOL_LEN -# define PJSUA_POOL_LEN 1000 +# define PJSUA_POOL_LEN 1000 #endif /** * Memory increment for PJSUA. */ #ifndef PJSUA_POOL_INC -# define PJSUA_POOL_INC 1000 +# define PJSUA_POOL_INC 1000 #endif /** * Initial memory block for PJSUA account. */ #ifndef PJSUA_POOL_LEN_ACC -# define PJSUA_POOL_LEN_ACC 512 +# define PJSUA_POOL_LEN_ACC 512 #endif /** * Memory increment for PJSUA account. */ #ifndef PJSUA_POOL_INC_ACC -# define PJSUA_POOL_INC_ACC 256 +# define PJSUA_POOL_INC_ACC 256 #endif /** @@ -332,9 +331,9 @@ typedef struct pj_stun_resolve_result pj_stun_resolve_result; /** * Default value of secure signaling requirement for SRTP. * Valid values are: - * 0: SRTP does not require secure signaling - * 1: SRTP requires secure transport such as TLS - * 2: SRTP requires secure end-to-end transport (SIPS) + * 0: SRTP does not require secure signaling + * 1: SRTP requires secure transport such as TLS + * 2: SRTP requires secure end-to-end transport (SIPS) */ #ifndef PJSUA_DEFAULT_SRTP_SECURE_SIGNALING #define PJSUA_DEFAULT_SRTP_SECURE_SIGNALING 1 @@ -348,7 +347,7 @@ typedef struct pj_stun_resolve_result pj_stun_resolve_result; * Default: 1 */ #ifndef PJSUA_ADD_ICE_TAGS -# define PJSUA_ADD_ICE_TAGS 1 +# define PJSUA_ADD_ICE_TAGS 1 #endif /** @@ -364,7 +363,7 @@ typedef struct pj_stun_resolve_result pj_stun_resolve_result; * Is video enabled. */ #ifndef PJSUA_HAS_VIDEO -# define PJSUA_HAS_VIDEO PJMEDIA_HAS_VIDEO +# define PJSUA_HAS_VIDEO PJMEDIA_HAS_VIDEO #endif @@ -374,7 +373,7 @@ typedef struct pj_stun_resolve_result pj_stun_resolve_result; * Default: 3000 ms */ #ifndef PJSUA_VID_REQ_KEYFRAME_INTERVAL -# define PJSUA_VID_REQ_KEYFRAME_INTERVAL 3000 +# define PJSUA_VID_REQ_KEYFRAME_INTERVAL 3000 #endif @@ -390,7 +389,7 @@ typedef struct pj_stun_resolve_result pj_stun_resolve_result; * Default: 0 (disabled) */ #ifndef PJSUA_SEPARATE_WORKER_FOR_TIMER -# define PJSUA_SEPARATE_WORKER_FOR_TIMER 0 +# define PJSUA_SEPARATE_WORKER_FOR_TIMER 0 #endif @@ -402,7 +401,7 @@ typedef struct pj_stun_resolve_result pj_stun_resolve_result; * Default: 0 (automatic sending enabled) */ #ifndef PJSUA_DISABLE_AUTO_SEND_100 -# define PJSUA_DISABLE_AUTO_SEND_100 0 +# define PJSUA_DISABLE_AUTO_SEND_100 0 #endif @@ -411,7 +410,7 @@ typedef struct pj_stun_resolve_result pj_stun_resolve_result; * See #pjmedia_transport_ice_options. */ #ifndef PJSUA_ICE_TRANSPORT_OPTION -# define PJSUA_ICE_TRANSPORT_OPTION 0 +# define PJSUA_ICE_TRANSPORT_OPTION 0 #endif /** @@ -424,7 +423,7 @@ typedef struct pj_stun_resolve_result pj_stun_resolve_result; * Default: 100 ms */ #ifndef PJSUA_TRICKLE_ICE_NEW_CAND_CHECK_INTERVAL -# define PJSUA_TRICKLE_ICE_NEW_CAND_CHECK_INTERVAL 100 +# define PJSUA_TRICKLE_ICE_NEW_CAND_CHECK_INTERVAL 100 #endif @@ -476,27 +475,27 @@ typedef struct pjsua_logging_config /** * Log incoming and outgoing SIP message? Yes! */ - pj_bool_t msg_logging; + pj_bool_t msg_logging; /** * Input verbosity level. Value 5 is reasonable. */ - unsigned level; + unsigned level; /** * Verbosity level for console. Value 4 is reasonable. */ - unsigned console_level; + unsigned console_level; /** * Log decoration. */ - unsigned decor; + unsigned decor; /** * Optional log filename. */ - pj_str_t log_filename; + pj_str_t log_filename; /** * Additional flags to be given to #pj_file_open() when opening @@ -506,7 +505,7 @@ typedef struct pjsua_logging_config * * Default is 0. */ - unsigned log_file_flags; + unsigned log_file_flags; /** * Optional callback function to be called to write log to @@ -522,7 +521,7 @@ typedef struct pjsua_logging_config /** * Use this function to initialize logging config. * - * @param cfg The logging config to be initialized. + * @param cfg The logging config to be initialized. */ PJ_DECL(void) pjsua_logging_config_default(pjsua_logging_config *cfg); @@ -530,13 +529,13 @@ PJ_DECL(void) pjsua_logging_config_default(pjsua_logging_config *cfg); /** * Use this function to duplicate logging config. * - * @param pool Pool to use. - * @param dst Destination config. - * @param src Source config. + * @param pool Pool to use. + * @param dst Destination config. + * @param src Source config. */ PJ_DECL(void) pjsua_logging_config_dup(pj_pool_t *pool, - pjsua_logging_config *dst, - const pjsua_logging_config *src); + pjsua_logging_config *dst, + const pjsua_logging_config *src); /** @@ -544,9 +543,9 @@ PJ_DECL(void) pjsua_logging_config_dup(pj_pool_t *pool, */ typedef struct pjsua_mwi_info { - pjsip_evsub *evsub; /**< Event subscription session, for - reference. */ - pjsip_rx_data *rdata; /**< The received NOTIFY request. */ + pjsip_evsub *evsub; /**< Event subscription session, for + reference. */ + pjsip_rx_data *rdata; /**< The received NOTIFY request. */ } pjsua_mwi_info; @@ -555,12 +554,12 @@ typedef struct pjsua_mwi_info */ typedef struct pjsua_reg_info { - struct pjsip_regc_cbparam *cbparam; /**< Parameters returned by - registration callback. */ - pjsip_regc *regc; /**< Client registration - structure. */ - pj_bool_t renew; /**< Non-zero for registration and - zero for unregistration. */ + struct pjsip_regc_cbparam *cbparam; /**< Parameters returned by + registration callback. */ + pjsip_regc *regc; /**< Client registration + structure. */ + pj_bool_t renew; /**< Non-zero for registration and + zero for unregistration. */ } pjsua_reg_info; @@ -574,11 +573,11 @@ typedef struct pjsua_stream_info /** Stream info (union). */ union { - /** Audio stream info */ - pjmedia_stream_info aud; + /** Audio stream info */ + pjmedia_stream_info aud; - /** Video stream info */ - pjmedia_vid_stream_info vid; + /** Video stream info */ + pjmedia_vid_stream_info vid; } info; } pjsua_stream_info; @@ -590,10 +589,10 @@ typedef struct pjsua_stream_info typedef struct pjsua_stream_stat { /** RTCP statistic. */ - pjmedia_rtcp_stat rtcp; + pjmedia_rtcp_stat rtcp; /** Jitter buffer statistic. */ - pjmedia_jb_state jbuf; + pjmedia_jb_state jbuf; } pjsua_stream_stat; @@ -625,12 +624,12 @@ typedef struct pjsua_on_stream_created_param /** * The audio media stream, read-only. */ - pjmedia_stream *stream; + pjmedia_stream *stream; /** * Stream index in the audio media session, read-only. */ - unsigned stream_idx; + unsigned stream_idx; /** * Specify if PJSUA should take ownership of the port returned in @@ -640,7 +639,7 @@ typedef struct pjsua_on_stream_created_param * * Default: PJ_FALSE */ - pj_bool_t destroy_port; + pj_bool_t destroy_port; /** * On input, it specifies the audio media port of the stream. Application @@ -699,17 +698,17 @@ typedef struct pjsua_med_tp_state_info /** * The last error code related to the media transport state. */ - pj_status_t status; + pj_status_t status; /** * Optional SIP error code. */ - int sip_err_code; + int sip_err_code; /** * Optional extended info, the content is specific for each transport type. */ - void *ext_info; + void *ext_info; } pjsua_med_tp_state_info; @@ -717,10 +716,10 @@ typedef struct pjsua_med_tp_state_info /** * Type of callback to be called when media transport state is changed. * - * @param call_id The call ID. + * @param call_id The call ID. * @param info The media transport state info. * - * @return The callback must return PJ_SUCCESS at the moment. + * @return The callback must return PJ_SUCCESS at the moment. */ typedef pj_status_t (*pjsua_med_tp_state_cb)(pjsua_call_id call_id, @@ -762,7 +761,7 @@ typedef struct pjsua_srtp_opt * * Default is zero. */ - unsigned crypto_count; + unsigned crypto_count; /** * Specify individual crypto suite setting and its priority order. @@ -772,7 +771,7 @@ typedef struct pjsua_srtp_opt * AES_CM_128_HMAC_SHA1_32, AEAD_AES_256_GCM, and AEAD_AES_128_GCM. * - SRTP key is not configurable. */ - pjmedia_srtp_crypto crypto[PJMEDIA_SRTP_MAX_CRYPTOS]; + pjmedia_srtp_crypto crypto[PJMEDIA_SRTP_MAX_CRYPTOS]; /** * Specify the number of enabled keying methods. If set to zero, all @@ -783,7 +782,7 @@ typedef struct pjsua_srtp_opt * Default is zero (all keyings are enabled with priority order: * SDES, DTLS-SRTP). */ - unsigned keying_count; + unsigned keying_count; /** * Specify enabled keying methods and its priority order. Keying method @@ -791,7 +790,7 @@ typedef struct pjsua_srtp_opt * for example as currently only one keying is supported in the SDP offer, * keying with first priority will be likely used in the SDP offer. */ - pjmedia_srtp_keying_method keying[PJMEDIA_SRTP_KEYINGS_COUNT]; + pjmedia_srtp_keying_method keying[PJMEDIA_SRTP_KEYINGS_COUNT]; } pjsua_srtp_opt; @@ -879,39 +878,39 @@ typedef union pjsua_ip_change_op_info { * The information from listener restart operation. */ struct { - int transport_id; + int transport_id; } lis_restart; /** * The information from shutdown transport. */ struct { - int acc_id; + int acc_id; } acc_shutdown_tp; /** * The information from updating contact. */ struct { - pjsua_acc_id acc_id; - pj_bool_t is_register; /**< SIP Register if PJ_TRUE. */ - int code; /**< SIP status code received. */ + pjsua_acc_id acc_id; + pj_bool_t is_register; /**< SIP Register if PJ_TRUE. */ + int code; /**< SIP status code received. */ } acc_update_contact; /** * The information from hanging up call operation. */ struct { - pjsua_acc_id acc_id; - pjsua_call_id call_id; + pjsua_acc_id acc_id; + pjsua_call_id call_id; } acc_hangup_calls; /** * The information from re-Invite call operation. */ struct { - pjsua_acc_id acc_id; - pjsua_call_id call_id; + pjsua_acc_id acc_id; + pjsua_call_id call_id; } acc_reinvite_calls; } pjsua_ip_change_op_info; @@ -1028,16 +1027,16 @@ typedef struct pjsua_call_setting * * Default: PJSUA_CALL_INCLUDE_DISABLED_MEDIA */ - unsigned flag; + unsigned flag; /** * This flag controls what methods to request keyframe are allowed on * the call. Value is bitmask of #pjsua_vid_req_keyframe_method. * * Default: (PJSUA_VID_REQ_KEYFRAME_SIP_INFO | - * PJSUA_VID_REQ_KEYFRAME_RTCP_PLI) + * PJSUA_VID_REQ_KEYFRAME_RTCP_PLI) */ - unsigned req_keyframe_method; + unsigned req_keyframe_method; /** * Number of simultaneous active audio streams for this call. Setting @@ -1076,7 +1075,7 @@ typedef struct pjsua_call_setting * * Default: PJMEDIA_DIR_ENCODING_DECODING */ - pjmedia_dir media_dir[PJMEDIA_MAX_SDP_MEDIA]; + pjmedia_dir media_dir[PJMEDIA_MAX_SDP_MEDIA]; } pjsua_call_setting; @@ -1094,21 +1093,21 @@ typedef struct pjsua_callback * Application may then query the call info to get the * detail call states by calling pjsua_call_get_info() function. * - * @param call_id The call index. - * @param e Event which causes the call state to change. + * @param call_id The call index. + * @param e Event which causes the call state to change. */ void (*on_call_state)(pjsua_call_id call_id, pjsip_event *e); /** * Notify application on incoming call. * - * @param acc_id The account which match the incoming call. - * @param call_id The call id that has just been created for - * the call. - * @param rdata The incoming INVITE request. + * @param acc_id The account which match the incoming call. + * @param call_id The call id that has just been created for + * the call. + * @param rdata The incoming INVITE request. */ void (*on_incoming_call)(pjsua_acc_id acc_id, pjsua_call_id call_id, - pjsip_rx_data *rdata); + pjsip_rx_data *rdata); /** * This is a general notification callback which is called whenever @@ -1117,13 +1116,13 @@ typedef struct pjsua_callback * outgoing requests, or to answer unhandled incoming requests * (such as INFO) with a final response. * - * @param call_id Call identification. - * @param tsx The transaction which has changed state. - * @param e Transaction event that caused the state change. + * @param call_id Call identification. + * @param tsx The transaction which has changed state. + * @param e Transaction event that caused the state change. */ void (*on_call_tsx_state)(pjsua_call_id call_id, - pjsip_transaction *tsx, - pjsip_event *e); + pjsip_transaction *tsx, + pjsip_event *e); /** * Notify application when media state in the call has changed. @@ -1133,7 +1132,7 @@ typedef struct pjsua_callback * failure. When DTLS-SRTP is used, this callback will also be called * to report DTLS negotiation failure. * - * @param call_id The call index. + * @param call_id The call index. */ void (*on_call_media_state)(pjsua_call_id call_id); @@ -1145,16 +1144,16 @@ typedef struct pjsua_callback * negotiated with remote SDP, for example to apply per account/call * basis codecs priority or to add custom/proprietary SDP attributes. * - * @param call_id The call index. - * @param sdp The SDP has just been created. - * @param pool The pool instance, application should use this pool - * to modify the SDP. - * @param rem_sdp The remote SDP, will be NULL if local is SDP offerer. + * @param call_id The call index. + * @param sdp The SDP has just been created. + * @param pool The pool instance, application should use this pool + * to modify the SDP. + * @param rem_sdp The remote SDP, will be NULL if local is SDP offerer. */ void (*on_call_sdp_created)(pjsua_call_id call_id, - pjmedia_sdp_session *sdp, - pj_pool_t *pool, - const pjmedia_sdp_session *rem_sdp); + pjmedia_sdp_session *sdp, + pj_pool_t *pool, + const pjmedia_sdp_session *rem_sdp); /** * Notify application when an audio media session is about to be created @@ -1179,18 +1178,18 @@ typedef struct pjsua_callback * Note: if implemented, on_stream_created2() callback will be called * instead of this one. * - * @param call_id Call identification. - * @param strm Audio media stream. + * @param call_id Call identification. + * @param strm Audio media stream. * @param stream_idx Stream index in the audio media session. - * @param p_port On input, it specifies the audio media port of the - * stream. Application may modify this pointer to - * point to different media port to be registered - * to the conference bridge. + * @param p_port On input, it specifies the audio media port of the + * stream. Application may modify this pointer to + * point to different media port to be registered + * to the conference bridge. */ void (*on_stream_created)(pjsua_call_id call_id, - pjmedia_stream *strm, + pjmedia_stream *strm, unsigned stream_idx, - pjmedia_port **p_port); + pjmedia_port **p_port); /** * Notify application when audio media session is created and before it is @@ -1198,31 +1197,31 @@ typedef struct pjsua_callback * audio media port if it has added media processing port to the stream. * This media port then will be added to the conference bridge instead. * - * @param call_id Call identification. - * @param param The on stream created callback parameter. + * @param call_id Call identification. + * @param param The on stream created callback parameter. */ void (*on_stream_created2)(pjsua_call_id call_id, - pjsua_on_stream_created_param *param); + pjsua_on_stream_created_param *param); /** * Notify application when audio media session has been unregistered from * the conference bridge and about to be destroyed. * - * @param call_id Call identification. - * @param strm Audio media stream. + * @param call_id Call identification. + * @param strm Audio media stream. * @param stream_idx Stream index in the audio media session. */ void (*on_stream_destroyed)(pjsua_call_id call_id, pjmedia_stream *strm, - unsigned stream_idx); + unsigned stream_idx); /** * Notify application upon incoming DTMF digits using RFC 2833 payload * formats. This callback will not be called if app implements \a * on_dtmf_digit2() or \a on_dtmf_event(). * - * @param call_id The call index. - * @param digit DTMF ASCII digit. + * @param call_id The call index. + * @param digit DTMF ASCII digit. */ void (*on_dtmf_digit)(pjsua_call_id call_id, int digit); @@ -1231,8 +1230,8 @@ typedef struct pjsua_callback * in \a pjsua_dtmf_method. This callback will not be called if app * implements \a on_dtmf_event(). * - * @param call_id The call index. - * @param info The DTMF info. + * @param call_id The call index. + * @param info The DTMF info. */ void (*on_dtmf_digit2)(pjsua_call_id call_id, const pjsua_dtmf_info *info); @@ -1241,8 +1240,8 @@ typedef struct pjsua_callback * in \a pjsua_dtmf_method. Includes additional information about events * received via RTP. * - * @param call_id The call index. - * @param event The DTMF event. + * @param call_id The call index. + * @param event The DTMF event. */ void (*on_dtmf_event)(pjsua_call_id call_id, const pjsua_dtmf_event *event); @@ -1255,15 +1254,15 @@ typedef struct pjsua_callback * transfer. See also on_call_transfer_request2() callback for * the version with \a pjsua_call_setting in the argument list. * - * @param call_id The call index. - * @param dst The destination where the call will be - * transferred to. - * @param code Status code to be returned for the call transfer - * request. On input, it contains status code 202. + * @param call_id The call index. + * @param dst The destination where the call will be + * transferred to. + * @param code Status code to be returned for the call transfer + * request. On input, it contains status code 202. */ void (*on_call_transfer_request)(pjsua_call_id call_id, - const pj_str_t *dst, - pjsip_status_code *code); + const pj_str_t *dst, + pjsip_status_code *code); /** * Notify application on call being transferred (i.e. REFER is received). @@ -1272,18 +1271,18 @@ typedef struct pjsua_callback * is not defined, the default behavior is to accept the * transfer. * - * @param call_id The call index. - * @param dst The destination where the call will be - * transferred to. - * @param code Status code to be returned for the call transfer - * request. On input, it contains status code 202. - * @param opt The current call setting, application can update - * this setting for the call being transferred. + * @param call_id The call index. + * @param dst The destination where the call will be + * transferred to. + * @param code Status code to be returned for the call transfer + * request. On input, it contains status code 202. + * @param opt The current call setting, application can update + * this setting for the call being transferred. */ void (*on_call_transfer_request2)(pjsua_call_id call_id, - const pj_str_t *dst, - pjsip_status_code *code, - pjsua_call_setting *opt); + const pj_str_t *dst, + pjsip_status_code *code, + pjsua_call_setting *opt); /** * Notify application of the status of previously sent call @@ -1291,22 +1290,22 @@ typedef struct pjsua_callback * call transfer request, for example to decide whether to * terminate existing call. * - * @param call_id Call ID. - * @param st_code Status progress of the transfer request. - * @param st_text Status progress text. - * @param final If non-zero, no further notification will - * be reported. The st_code specified in - * this callback is the final status. - * @param p_cont Initially will be set to non-zero, application - * can set this to FALSE if it no longer wants - * to receie further notification (for example, - * after it hangs up the call). + * @param call_id Call ID. + * @param st_code Status progress of the transfer request. + * @param st_text Status progress text. + * @param final If non-zero, no further notification will + * be reported. The st_code specified in + * this callback is the final status. + * @param p_cont Initially will be set to non-zero, application + * can set this to FALSE if it no longer wants + * to receie further notification (for example, + * after it hangs up the call). */ void (*on_call_transfer_status)(pjsua_call_id call_id, - int st_code, - const pj_str_t *st_text, - pj_bool_t final, - pj_bool_t *p_cont); + int st_code, + const pj_str_t *st_text, + pj_bool_t final, + pj_bool_t *p_cont); /** * Notify application about incoming INVITE with Replaces header. @@ -1314,34 +1313,34 @@ typedef struct pjsua_callback * See also on_call_replace_request2() callback for the version * with \a pjsua_call_setting in the argument list. * - * @param call_id The call ID to be replaced. - * @param rdata The incoming INVITE request to replace the call. - * @param st_code Status code to be set by application. Application - * should only return a final status (200-699). - * @param st_text Optional status text to be set by application. + * @param call_id The call ID to be replaced. + * @param rdata The incoming INVITE request to replace the call. + * @param st_code Status code to be set by application. Application + * should only return a final status (200-699). + * @param st_text Optional status text to be set by application. */ void (*on_call_replace_request)(pjsua_call_id call_id, - pjsip_rx_data *rdata, - int *st_code, - pj_str_t *st_text); + pjsip_rx_data *rdata, + int *st_code, + pj_str_t *st_text); /** * Notify application about incoming INVITE with Replaces header. * Application may reject the request by setting non-2xx code. * - * @param call_id The call ID to be replaced. - * @param rdata The incoming INVITE request to replace the call. - * @param st_code Status code to be set by application. Application - * should only return a final status (200-699). - * @param st_text Optional status text to be set by application. - * @param opt The current call setting, application can update - * this setting for the call being replaced. + * @param call_id The call ID to be replaced. + * @param rdata The incoming INVITE request to replace the call. + * @param st_code Status code to be set by application. Application + * should only return a final status (200-699). + * @param st_text Optional status text to be set by application. + * @param opt The current call setting, application can update + * this setting for the call being replaced. */ void (*on_call_replace_request2)(pjsua_call_id call_id, - pjsip_rx_data *rdata, - int *st_code, - pj_str_t *st_text, - pjsua_call_setting *opt); + pjsip_rx_data *rdata, + int *st_code, + pj_str_t *st_text, + pjsua_call_setting *opt); /** * Notify application that an existing call has been replaced with @@ -1352,12 +1351,12 @@ typedef struct pjsua_callback * \a old_call_id and establish \a new_call_id. * * @param old_call_id Existing call which to be replaced with the - * new call. + * new call. * @param new_call_id The new call. - * @param rdata The incoming INVITE with Replaces request. + * @param rdata The incoming INVITE with Replaces request. */ void (*on_call_replaced)(pjsua_call_id old_call_id, - pjsua_call_id new_call_id); + pjsua_call_id new_call_id); /** @@ -1374,20 +1373,20 @@ typedef struct pjsua_callback * Note: this callback may not be called if \a on_call_rx_reinvite() * is implemented. * - * @param call_id The call index. - * @param offer The new offer received. - * @param reserved Reserved param, currently not used. - * @param code Status code to be returned for answering the - * offer. On input, it contains status code 200. - * Currently, valid values are only 200 and 488. - * @param opt The current call setting, application can update - * this setting for answering the offer. + * @param call_id The call index. + * @param offer The new offer received. + * @param reserved Reserved param, currently not used. + * @param code Status code to be returned for answering the + * offer. On input, it contains status code 200. + * Currently, valid values are only 200 and 488. + * @param opt The current call setting, application can update + * this setting for answering the offer. */ void (*on_call_rx_offer)(pjsua_call_id call_id, - const pjmedia_sdp_session *offer, - void *reserved, - pjsip_status_code *code, - pjsua_call_setting *opt); + const pjmedia_sdp_session *offer, + void *reserved, + pjsip_status_code *code, + pjsua_call_setting *opt); /** @@ -1410,25 +1409,25 @@ typedef struct pjsua_callback * Note: on_call_rx_offer() will still be called after this callback, * but only if async is PJ_FALSE and code is 200. * - * @param call_id The call index. - * @param offer Remote offer. + * @param call_id The call index. + * @param offer Remote offer. * @param rdata The received re-INVITE request. - * @param reserved Reserved param, currently not used. - * @param async On input, it is PJ_FALSE. Set to PJ_TRUE if - * app wants to manually answer the re-INVITE. - * @param code Status code to be returned for answering the - * offer. On input, it contains status code 200. - * Currently, valid values are only 200 and 488. - * @param opt The current call setting, application can update - * this setting for answering the offer. + * @param reserved Reserved param, currently not used. + * @param async On input, it is PJ_FALSE. Set to PJ_TRUE if + * app wants to manually answer the re-INVITE. + * @param code Status code to be returned for answering the + * offer. On input, it contains status code 200. + * Currently, valid values are only 200 and 488. + * @param opt The current call setting, application can update + * this setting for answering the offer. */ void (*on_call_rx_reinvite)(pjsua_call_id call_id, - const pjmedia_sdp_session *offer, + const pjmedia_sdp_session *offer, pjsip_rx_data *rdata, - void *reserved, - pj_bool_t *async, - pjsip_status_code *code, - pjsua_call_setting *opt); + void *reserved, + pj_bool_t *async, + pjsip_status_code *code, + pjsua_call_setting *opt); /** @@ -1445,14 +1444,14 @@ typedef struct pjsua_callback * SDP offer using current active media session (with all enabled codecs * on each media type). * - * @param call_id The call index. - * @param reserved Reserved param, currently not used. - * @param opt The current call setting, application can update - * this setting for generating the offer. + * @param call_id The call index. + * @param reserved Reserved param, currently not used. + * @param opt The current call setting, application can update + * this setting for generating the offer. */ void (*on_call_tx_offer)(pjsua_call_id call_id, - void *reserved, - pjsua_call_setting *opt); + void *reserved, + pjsua_call_setting *opt); /** @@ -1461,9 +1460,9 @@ typedef struct pjsua_callback * and unregistration. Once registration session is active, subsequent * refresh will not cause this callback to be called. * - * @param acc_id The account ID. - * @param renew Non-zero for registration and zero for - * unregistration. + * @param acc_id The account ID. + * @param renew Non-zero for registration and zero for + * unregistration. */ void (*on_reg_started)(pjsua_acc_id acc_id, pj_bool_t renew); @@ -1471,18 +1470,18 @@ typedef struct pjsua_callback * This is the alternative version of the \a on_reg_started() callback with * \a pjsua_reg_info argument. * - * @param acc_id The account ID. - * @param info The registration info. + * @param acc_id The account ID. + * @param info The registration info. */ void (*on_reg_started2)(pjsua_acc_id acc_id, - pjsua_reg_info *info); + pjsua_reg_info *info); /** * Notify application when registration status has changed. * Application may then query the account info to get the * registration details. * - * @param acc_id The account ID. + * @param acc_id The account ID. */ void (*on_reg_state)(pjsua_acc_id acc_id); @@ -1491,8 +1490,8 @@ typedef struct pjsua_callback * Application may inspect the registration info to get the * registration status details. * - * @param acc_id The account ID. - * @param info The registration info. + * @param acc_id The account ID. + * @param info The registration info. */ void (*on_reg_state2)(pjsua_acc_id acc_id, pjsua_reg_info *info); @@ -1506,16 +1505,16 @@ typedef struct pjsua_callback * * If this callback is implemented, application has several choices on * what to do with the incoming request: - * - it may reject the request immediately by specifying non-200 class + * - it may reject the request immediately by specifying non-200 class * final response in the \a code argument. - * - it may immediately accept the request by specifying 200 as the - * \a code argument. This is the default value if application doesn't - * set any value to the \a code argument. In this case, the library - * will automatically send NOTIFY request upon returning from this - * callback. + * - it may immediately accept the request by specifying 200 as the + * \a code argument. This is the default value if application doesn't + * set any value to the \a code argument. In this case, the library + * will automatically send NOTIFY request upon returning from this + * callback. * - it may delay the processing of the request, for example to request * user permission whether to accept or reject the request. In this - * case, the application MUST set the \a code argument to 202, then + * case, the application MUST set the \a code argument to 202, then * IMMEDIATELY calls #pjsua_pres_notify() with state * PJSIP_EVSUB_STATE_PENDING and later calls #pjsua_pres_notify() * again to accept or reject the subscription request. @@ -1525,56 +1524,56 @@ typedef struct pjsua_callback * Application MUST return from this callback immediately (e.g. it must * not block in this callback while waiting for user confirmation). * - * @param srv_pres Server presence subscription instance. If - * application delays the acceptance of the request, - * it will need to specify this object when calling - * #pjsua_pres_notify(). - * @param acc_id Account ID most appropriate for this request. - * @param buddy_id ID of the buddy matching the sender of the - * request, if any, or PJSUA_INVALID_ID if no - * matching buddy is found. - * @param from The From URI of the request. - * @param rdata The incoming request. - * @param code The status code to respond to the request. The - * default value is 200. Application may set this - * to other final status code to accept or reject - * the request. - * @param reason The reason phrase to respond to the request. - * @param msg_data If the application wants to send additional - * headers in the response, it can put it in this - * parameter. + * @param srv_pres Server presence subscription instance. If + * application delays the acceptance of the request, + * it will need to specify this object when calling + * #pjsua_pres_notify(). + * @param acc_id Account ID most appropriate for this request. + * @param buddy_id ID of the buddy matching the sender of the + * request, if any, or PJSUA_INVALID_ID if no + * matching buddy is found. + * @param from The From URI of the request. + * @param rdata The incoming request. + * @param code The status code to respond to the request. The + * default value is 200. Application may set this + * to other final status code to accept or reject + * the request. + * @param reason The reason phrase to respond to the request. + * @param msg_data If the application wants to send additional + * headers in the response, it can put it in this + * parameter. */ void (*on_incoming_subscribe)(pjsua_acc_id acc_id, - pjsua_srv_pres *srv_pres, - pjsua_buddy_id buddy_id, - const pj_str_t *from, - pjsip_rx_data *rdata, - pjsip_status_code *code, - pj_str_t *reason, - pjsua_msg_data *msg_data); + pjsua_srv_pres *srv_pres, + pjsua_buddy_id buddy_id, + const pj_str_t *from, + pjsip_rx_data *rdata, + pjsip_status_code *code, + pj_str_t *reason, + pjsua_msg_data *msg_data); /** * Notification when server side subscription state has changed. * This callback is optional as application normally does not need * to do anything to maintain server side presence subscription. * - * @param acc_id The account ID. - * @param srv_pres Server presence subscription object. + * @param acc_id The account ID. + * @param srv_pres Server presence subscription object. * @param remote_uri Remote URI string. - * @param state New subscription state. - * @param event PJSIP event that triggers the state change. + * @param state New subscription state. + * @param event PJSIP event that triggers the state change. */ void (*on_srv_subscribe_state)(pjsua_acc_id acc_id, - pjsua_srv_pres *srv_pres, - const pj_str_t *remote_uri, - pjsip_evsub_state state, - pjsip_event *event); + pjsua_srv_pres *srv_pres, + const pj_str_t *remote_uri, + pjsip_evsub_state state, + pjsip_event *event); /** * Notify application when the buddy state has changed. * Application may then query the buddy into to get the details. * - * @param buddy_id The buddy id. + * @param buddy_id The buddy id. */ void (*on_buddy_state)(pjsua_buddy_id buddy_id); @@ -1585,13 +1584,13 @@ typedef struct pjsua_callback * callback to retrieve more detailed information about the state * changed event. * - * @param buddy_id The buddy id. - * @param sub Event subscription session. - * @param event The event which triggers state change event. + * @param buddy_id The buddy id. + * @param sub Event subscription session. + * @param event The event which triggers state change event. */ void (*on_buddy_evsub_state)(pjsua_buddy_id buddy_id, - pjsip_evsub *sub, - pjsip_event *event); + pjsip_evsub *sub, + pjsip_event *event); /** * Notify application on incoming pager (i.e. MESSAGE request). @@ -1601,131 +1600,131 @@ typedef struct pjsua_callback * See also \a on_pager2() callback for the version with \a pjsip_rx_data * passed as one of the argument. * - * @param call_id Containts the ID of the call where the IM was - * sent, or PJSUA_INVALID_ID if the IM was sent - * outside call context. - * @param from URI of the sender. - * @param to URI of the destination message. - * @param contact The Contact URI of the sender, if present. - * @param mime_type MIME type of the message. - * @param body The message content. + * @param call_id Containts the ID of the call where the IM was + * sent, or PJSUA_INVALID_ID if the IM was sent + * outside call context. + * @param from URI of the sender. + * @param to URI of the destination message. + * @param contact The Contact URI of the sender, if present. + * @param mime_type MIME type of the message. + * @param body The message content. */ void (*on_pager)(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - const pj_str_t *mime_type, const pj_str_t *body); + const pj_str_t *to, const pj_str_t *contact, + const pj_str_t *mime_type, const pj_str_t *body); /** * This is the alternative version of the \a on_pager() callback with * \a pjsip_rx_data argument. * - * @param call_id Containts the ID of the call where the IM was - * sent, or PJSUA_INVALID_ID if the IM was sent - * outside call context. - * @param from URI of the sender. - * @param to URI of the destination message. - * @param contact The Contact URI of the sender, if present. - * @param mime_type MIME type of the message. - * @param body The message content. - * @param rdata The incoming MESSAGE request. - * @param acc_id Account ID most suitable for this message. + * @param call_id Containts the ID of the call where the IM was + * sent, or PJSUA_INVALID_ID if the IM was sent + * outside call context. + * @param from URI of the sender. + * @param to URI of the destination message. + * @param contact The Contact URI of the sender, if present. + * @param mime_type MIME type of the message. + * @param body The message content. + * @param rdata The incoming MESSAGE request. + * @param acc_id Account ID most suitable for this message. */ void (*on_pager2)(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - const pj_str_t *mime_type, const pj_str_t *body, - pjsip_rx_data *rdata, pjsua_acc_id acc_id); + const pj_str_t *to, const pj_str_t *contact, + const pj_str_t *mime_type, const pj_str_t *body, + pjsip_rx_data *rdata, pjsua_acc_id acc_id); /** * Notify application about the delivery status of outgoing pager * request. See also on_pager_status2() callback for the version with * \a pjsip_rx_data in the argument list. * - * @param call_id Containts the ID of the call where the IM was - * sent, or PJSUA_INVALID_ID if the IM was sent - * outside call context. - * @param to Destination URI. - * @param body Message body. - * @param user_data Arbitrary data that was specified when sending - * IM message. - * @param status Delivery status. - * @param reason Delivery status reason. + * @param call_id Containts the ID of the call where the IM was + * sent, or PJSUA_INVALID_ID if the IM was sent + * outside call context. + * @param to Destination URI. + * @param body Message body. + * @param user_data Arbitrary data that was specified when sending + * IM message. + * @param status Delivery status. + * @param reason Delivery status reason. */ void (*on_pager_status)(pjsua_call_id call_id, - const pj_str_t *to, - const pj_str_t *body, - void *user_data, - pjsip_status_code status, - const pj_str_t *reason); + const pj_str_t *to, + const pj_str_t *body, + void *user_data, + pjsip_status_code status, + const pj_str_t *reason); /** * Notify application about the delivery status of outgoing pager * request. * - * @param call_id Containts the ID of the call where the IM was - * sent, or PJSUA_INVALID_ID if the IM was sent - * outside call context. - * @param to Destination URI. - * @param body Message body. - * @param user_data Arbitrary data that was specified when sending - * IM message. - * @param status Delivery status. - * @param reason Delivery status reason. - * @param tdata The original MESSAGE request. - * @param rdata The incoming MESSAGE response, or NULL if the - * message transaction fails because of time out - * or transport error. - * @param acc_id Account ID from this the instant message was - * send. + * @param call_id Containts the ID of the call where the IM was + * sent, or PJSUA_INVALID_ID if the IM was sent + * outside call context. + * @param to Destination URI. + * @param body Message body. + * @param user_data Arbitrary data that was specified when sending + * IM message. + * @param status Delivery status. + * @param reason Delivery status reason. + * @param tdata The original MESSAGE request. + * @param rdata The incoming MESSAGE response, or NULL if the + * message transaction fails because of time out + * or transport error. + * @param acc_id Account ID from this the instant message was + * send. */ void (*on_pager_status2)(pjsua_call_id call_id, - const pj_str_t *to, - const pj_str_t *body, - void *user_data, - pjsip_status_code status, - const pj_str_t *reason, - pjsip_tx_data *tdata, - pjsip_rx_data *rdata, - pjsua_acc_id acc_id); + const pj_str_t *to, + const pj_str_t *body, + void *user_data, + pjsip_status_code status, + const pj_str_t *reason, + pjsip_tx_data *tdata, + pjsip_rx_data *rdata, + pjsua_acc_id acc_id); /** * Notify application about typing indication. * - * @param call_id Containts the ID of the call where the IM was - * sent, or PJSUA_INVALID_ID if the IM was sent - * outside call context. - * @param from URI of the sender. - * @param to URI of the destination message. - * @param contact The Contact URI of the sender, if present. - * @param is_typing Non-zero if peer is typing, or zero if peer - * has stopped typing a message. + * @param call_id Containts the ID of the call where the IM was + * sent, or PJSUA_INVALID_ID if the IM was sent + * outside call context. + * @param from URI of the sender. + * @param to URI of the destination message. + * @param contact The Contact URI of the sender, if present. + * @param is_typing Non-zero if peer is typing, or zero if peer + * has stopped typing a message. */ void (*on_typing)(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - pj_bool_t is_typing); + const pj_str_t *to, const pj_str_t *contact, + pj_bool_t is_typing); /** * Notify application about typing indication. * - * @param call_id Containts the ID of the call where the IM was - * sent, or PJSUA_INVALID_ID if the IM was sent - * outside call context. - * @param from URI of the sender. - * @param to URI of the destination message. - * @param contact The Contact URI of the sender, if present. - * @param is_typing Non-zero if peer is typing, or zero if peer - * has stopped typing a message. - * @param rdata The received request. - * @param acc_id Account ID most suitable for this message. + * @param call_id Containts the ID of the call where the IM was + * sent, or PJSUA_INVALID_ID if the IM was sent + * outside call context. + * @param from URI of the sender. + * @param to URI of the destination message. + * @param contact The Contact URI of the sender, if present. + * @param is_typing Non-zero if peer is typing, or zero if peer + * has stopped typing a message. + * @param rdata The received request. + * @param acc_id Account ID most suitable for this message. */ void (*on_typing2)(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - pj_bool_t is_typing, pjsip_rx_data *rdata, - pjsua_acc_id acc_id); + const pj_str_t *to, const pj_str_t *contact, + pj_bool_t is_typing, pjsip_rx_data *rdata, + pjsua_acc_id acc_id); /** * Callback when the library has finished performing NAT type * detection. * - * @param res NAT detection result. + * @param res NAT detection result. */ void (*on_nat_detect)(const pj_stun_nat_detect_result *res); @@ -1743,51 +1742,51 @@ typedef struct pjsua_callback * This callback is optional. If this callback is not implemented, * the default behavior is to NOT follow the redirection response. * - * @param call_id The call ID. - * @param target The current target to be tried. - * @param e The event that caused this callback to be called. - * This could be the receipt of 3xx response, or - * 4xx/5xx response received for the INVITE sent to - * subsequent targets, or NULL if this callback is - * called from within #pjsua_call_process_redirect() - * context. - * - * @return Action to be performed for the target. Set this - * parameter to one of the value below: - * - PJSIP_REDIRECT_ACCEPT: immediately accept the - * redirection. When set, the call will immediately - * resend INVITE request to the target. - * - PJSIP_REDIRECT_ACCEPT_REPLACE: immediately accept - * the redirection and replace the To header with the - * current target. When set, the call will immediately - * resend INVITE request to the target. - * - PJSIP_REDIRECT_REJECT: immediately reject this - * target. The call will continue retrying with - * next target if present, or disconnect the call - * if there is no more target to try. - * - PJSIP_REDIRECT_STOP: stop the whole redirection - * process and immediately disconnect the call. The - * on_call_state() callback will be called with - * PJSIP_INV_STATE_DISCONNECTED state immediately - * after this callback returns. - * - PJSIP_REDIRECT_PENDING: set to this value if - * no decision can be made immediately (for example - * to request confirmation from user). Application - * then MUST call #pjsua_call_process_redirect() - * to either accept or reject the redirection upon - * getting user decision. + * @param call_id The call ID. + * @param target The current target to be tried. + * @param e The event that caused this callback to be called. + * This could be the receipt of 3xx response, or + * 4xx/5xx response received for the INVITE sent to + * subsequent targets, or NULL if this callback is + * called from within #pjsua_call_process_redirect() + * context. + * + * @return Action to be performed for the target. Set this + * parameter to one of the value below: + * - PJSIP_REDIRECT_ACCEPT: immediately accept the + * redirection. When set, the call will immediately + * resend INVITE request to the target. + * - PJSIP_REDIRECT_ACCEPT_REPLACE: immediately accept + * the redirection and replace the To header with the + * current target. When set, the call will immediately + * resend INVITE request to the target. + * - PJSIP_REDIRECT_REJECT: immediately reject this + * target. The call will continue retrying with + * next target if present, or disconnect the call + * if there is no more target to try. + * - PJSIP_REDIRECT_STOP: stop the whole redirection + * process and immediately disconnect the call. The + * on_call_state() callback will be called with + * PJSIP_INV_STATE_DISCONNECTED state immediately + * after this callback returns. + * - PJSIP_REDIRECT_PENDING: set to this value if + * no decision can be made immediately (for example + * to request confirmation from user). Application + * then MUST call #pjsua_call_process_redirect() + * to either accept or reject the redirection upon + * getting user decision. */ pjsip_redirect_op (*on_call_redirected)(pjsua_call_id call_id, - const pjsip_uri *target, - const pjsip_event *e); + const pjsip_uri *target, + const pjsip_event *e); /** * This callback is called when message waiting indication subscription * state has changed. Application can then query the subscription state * by calling #pjsip_evsub_get_state(). * - * @param acc_id The account ID. - * @param evsub The subscription instance. + * @param acc_id The account ID. + * @param evsub The subscription instance. */ void (*on_mwi_state)(pjsua_acc_id acc_id, pjsip_evsub *evsub); @@ -1795,10 +1794,10 @@ typedef struct pjsua_callback * This callback is called when a NOTIFY request for message summary / * message waiting indication is received. * - * @param acc_id The account ID. - * @param mwi_info Structure containing details of the event, - * including the received NOTIFY request in the - * \a rdata field. + * @param acc_id The account ID. + * @param mwi_info Structure containing details of the event, + * including the received NOTIFY request in the + * \a rdata field. */ void (*on_mwi_info)(pjsua_acc_id acc_id, pjsua_mwi_info *mwi_info); @@ -1818,14 +1817,14 @@ typedef struct pjsua_callback * This callback is called to report error in ICE media transport. * Currently it is used to report TURN Refresh error. * - * @param index Transport index. - * @param op Operation which trigger the failure. - * @param status Error status. - * @param param Additional info about the event. Currently this will - * always be set to NULL. + * @param index Transport index. + * @param op Operation which trigger the failure. + * @param status Error status. + * @param param Additional info about the event. Currently this will + * always be set to NULL. */ void (*on_ice_transport_error)(int index, pj_ice_strans_op op, - pj_status_t status, void *param); + pj_status_t status, void *param); /** * Callback when the sound device is about to be opened or closed. @@ -1839,10 +1838,10 @@ typedef struct pjsua_callback * the sound device by itself (i.e. with #pjsua_set_no_snd_dev()), * to get notified when it should open or close the sound device. * - * @param operation The value will be set to 0 to signal that sound - * device is about to be closed, and 1 to be opened. + * @param operation The value will be set to 0 to signal that sound + * device is about to be closed, and 1 to be opened. * - * @return The callback must return PJ_SUCCESS at the moment. + * @return The callback must return PJ_SUCCESS at the moment. */ pj_status_t (*on_snd_dev_operation)(int operation); @@ -1854,13 +1853,13 @@ typedef struct pjsua_callback * callback. If application needs to perform more complex tasks to * handle the event, it should post the task to another thread. * - * @param call_id The call id. - * @param med_idx The media stream index. - * @param event The media event. + * @param call_id The call id. + * @param med_idx The media stream index. + * @param event The media event. */ void (*on_call_media_event)(pjsua_call_id call_id, - unsigned med_idx, - pjmedia_event *event); + unsigned med_idx, + pjmedia_event *event); /** * This callback can be used by application to implement custom media @@ -1904,7 +1903,7 @@ typedef struct pjsua_callback * * @param call_id Call ID * @param media_idx The media index in the SDP for which this SRTP - * media transport will be used. + * media transport will be used. * @param srtp_opt The SRTP setting. Application can modify this. */ void (*on_create_media_transport_srtp)(pjsua_call_id call_id, @@ -1924,13 +1923,13 @@ typedef struct pjsua_callback * may be called before the callback of the SIP event itself, i.e: * incoming call, pager, subscription, or unsolicited-event. * - * @param rdata The incoming message. - * @param acc_id On input, initial account ID calculated automatically - * by the library. On output, the account ID prefered - * by application to handle the incoming message. + * @param rdata The incoming message. + * @param acc_id On input, initial account ID calculated automatically + * by the library. On output, the account ID prefered + * by application to handle the incoming message. */ void (*on_acc_find_for_incoming)(const pjsip_rx_data *rdata, - pjsua_acc_id* acc_id); + pjsua_acc_id* acc_id); /** * Calling #pjsua_init() will initiate an async process to resolve and @@ -1948,14 +1947,14 @@ typedef struct pjsua_callback * Calling #pjsua_handle_ip_change() may involve different operation. This * callback is called to report the progress of each enabled operation. * - * @param op The operation. - * @param status The status of operation. - * @param info The info from the operation + * @param op The operation. + * @param status The status of operation. + * @param info The info from the operation * */ void (*on_ip_change_progress)(pjsua_ip_change_op op, - pj_status_t status, - const pjsua_ip_change_op_info *info); + pj_status_t status, + const pjsua_ip_change_op_info *info); /** * Notification about media events such as video notifications. This @@ -1964,7 +1963,7 @@ typedef struct pjsua_callback * If application needs to perform more complex tasks to handle * the event, it should post the task to another thread. * - * @param event The media event. + * @param event The media event. */ void (*on_media_event)(pjmedia_event *event); @@ -2046,7 +2045,7 @@ typedef struct pjsua_config * PJSUA_MAX_CALLS. To increase this limit, the library must be * recompiled with new PJSUA_MAX_CALLS value. */ - unsigned max_calls; + unsigned max_calls; /** * Number of worker threads. Normally application will want to have at @@ -2054,21 +2053,21 @@ typedef struct pjsua_config * periodically, which in this case the worker thread can be set to * zero. */ - unsigned thread_cnt; + unsigned thread_cnt; /** * Number of nameservers. If no name server is configured, the SIP SRV * resolution would be disabled, and domain will be resolved with * standard pj_gethostbyname() function. */ - unsigned nameserver_count; + unsigned nameserver_count; /** * Array of nameservers to be used by the SIP resolver subsystem. * The order of the name server specifies the priority (first name * server will be used first, unless it is not reachable). */ - pj_str_t nameserver[4]; + pj_str_t nameserver[4]; /** * Force loose-route to be used in all route/proxy URIs (outbound_proxy @@ -2078,12 +2077,12 @@ typedef struct pjsua_config * * Default: 1 */ - pj_bool_t force_lr; + pj_bool_t force_lr; /** * Number of outbound proxies in the \a outbound_proxy array. */ - unsigned outbound_proxy_cnt; + unsigned outbound_proxy_cnt; /** * Specify the URL of outbound proxies to visit for all outgoing requests. @@ -2092,7 +2091,7 @@ typedef struct pjsua_config * route set for outgoing requests will consists of the outbound proxies * and the proxy configured in the account. */ - pj_str_t outbound_proxy[4]; + pj_str_t outbound_proxy[4]; /** * Warning: deprecated, please use \a stun_srv field instead. To maintain @@ -2106,7 +2105,7 @@ typedef struct pjsua_config * If DNS SRV resolution failed for this domain, then DNS A resolution * will be performed only if \a stun_host is specified. */ - pj_str_t stun_domain; + pj_str_t stun_domain; /** * Warning: deprecated, please use \a stun_srv field instead. To maintain @@ -2116,22 +2115,22 @@ typedef struct pjsua_config * Specify STUN server to be used, in "HOST[:PORT]" format. If port is * not specified, default port 3478 will be used. */ - pj_str_t stun_host; + pj_str_t stun_host; /** * Number of STUN server entries in \a stun_srv array. */ - unsigned stun_srv_cnt; + unsigned stun_srv_cnt; /** * Array of STUN servers to try. The library will try to resolve and * contact each of the STUN server entry until it finds one that is * usable. Each entry may be a domain name, host name, IP address, and * it may contain an optional port number. For example: - * - "pjsip.org" (domain name) - * - "sip.pjsip.org" (host name) - * - "pjsip.org:33478" (domain name and a non-standard port number) - * - "10.0.0.1:3478" (IP address and port number) + * - "pjsip.org" (domain name) + * - "sip.pjsip.org" (host name) + * - "pjsip.org:33478" (domain name and a non-standard port number) + * - "10.0.0.1:3478" (IP address and port number) * * When nameserver is configured in the \a pjsua_config.nameserver field, * if entry is not an IP address, it will be resolved with DNS SRV @@ -2143,7 +2142,7 @@ typedef struct pjsua_config * #pj_gethostbyname() if it's not an IP address. Port number may be * specified if the server is not listening in standard STUN port. */ - pj_str_t stun_srv[8]; + pj_str_t stun_srv[8]; /** * This specifies if the library should try to do an IPv6 resolution of @@ -2152,7 +2151,7 @@ typedef struct pjsua_config * * Default: PJ_FALSE */ - pj_bool_t stun_try_ipv6; + pj_bool_t stun_try_ipv6; /** * This specifies if the library should ignore failure with the @@ -2166,7 +2165,7 @@ typedef struct pjsua_config * * Default: PJ_TRUE */ - pj_bool_t stun_ignore_failure; + pj_bool_t stun_ignore_failure; /** * This specifies whether STUN requests for resolving socket mapped @@ -2175,18 +2174,18 @@ typedef struct pjsua_config * * Default: PJ_FALSE */ - pj_bool_t stun_map_use_stun2; + pj_bool_t stun_map_use_stun2; /** * Support for adding and parsing NAT type in the SDP to assist * troubleshooting. The valid values are: - * - 0: no information will be added in SDP, and parsing is disabled. - * - 1: only the NAT type number is added. - * - 2: add both NAT type number and name. + * - 0: no information will be added in SDP, and parsing is disabled. + * - 1: only the NAT type number is added. + * - 2: add both NAT type number and name. * * Default: 1 */ - int nat_type_in_sdp; + int nat_type_in_sdp; /** * Specify how the support for reliable provisional response (100rel/ @@ -2219,7 +2218,7 @@ typedef struct pjsua_config * Default: PJ_TRUE * */ - pj_bool_t enable_unsolicited_mwi; + pj_bool_t enable_unsolicited_mwi; /** * Specify Session Timer settings, see #pjsip_timer_setting. @@ -2231,7 +2230,7 @@ typedef struct pjsua_config /** * Number of credentials in the credential array. */ - unsigned cred_count; + unsigned cred_count; /** * Array of credentials. These credentials will be used by all accounts, @@ -2252,7 +2251,7 @@ typedef struct pjsua_config * Optional user agent string (default empty). If it's empty, no * User-Agent header will be sent with outgoing requests. */ - pj_str_t user_agent; + pj_str_t user_agent; /** * Specify default value of secure media transport usage. @@ -2264,28 +2263,28 @@ typedef struct pjsua_config * * Default: #PJSUA_DEFAULT_USE_SRTP */ - pjmedia_srtp_use use_srtp; + pjmedia_srtp_use use_srtp; /** * Specify whether SRTP requires secure signaling to be used. This option * is only used when \a use_srtp option above is non-zero. * * Valid values are: - * 0: SRTP does not require secure signaling - * 1: SRTP requires secure transport such as TLS - * 2: SRTP requires secure end-to-end transport (SIPS) + * 0: SRTP does not require secure signaling + * 1: SRTP requires secure transport such as TLS + * 2: SRTP requires secure end-to-end transport (SIPS) * * Note that this setting can be further customized in account * configuration (#pjsua_acc_config). * * Default: #PJSUA_DEFAULT_SRTP_SECURE_SIGNALING */ - int srtp_secure_signaling; + int srtp_secure_signaling; /** * This setting has been deprecated and will be ignored. */ - pj_bool_t srtp_optional_dup_offer; + pj_bool_t srtp_optional_dup_offer; /** * Specify SRTP transport setting. Application can initialize it with @@ -2305,7 +2304,7 @@ typedef struct pjsua_config * * Default: PJ_TRUE (only disable this setting for testing purposes). */ - pj_bool_t hangup_forked_call; + pj_bool_t hangup_forked_call; /** * Specify whether to enable UPnP. @@ -2356,32 +2355,32 @@ typedef enum pjsua_destroy_flag * shorthand for PJSUA_DESTROY_NO_RX_MSG + PJSUA_DESTROY_NO_TX_MSG. */ PJSUA_DESTROY_NO_NETWORK = PJSUA_DESTROY_NO_RX_MSG | - PJSUA_DESTROY_NO_TX_MSG + PJSUA_DESTROY_NO_TX_MSG } pjsua_destroy_flag; /** * Use this function to initialize pjsua config. * - * @param cfg pjsua config to be initialized. + * @param cfg pjsua config to be initialized. */ PJ_DECL(void) pjsua_config_default(pjsua_config *cfg); /** The implementation has been moved to sip_auth.h */ -#define pjsip_cred_dup pjsip_cred_info_dup +#define pjsip_cred_dup pjsip_cred_info_dup /** * Duplicate pjsua_config. * - * @param pool The pool to get memory from. - * @param dst Destination config. - * @param src Source config. + * @param pool The pool to get memory from. + * @param dst Destination config. + * @param src Source config. */ PJ_DECL(void) pjsua_config_dup(pj_pool_t *pool, - pjsua_config *dst, - const pjsua_config *src); + pjsua_config *dst, + const pjsua_config *src); /** @@ -2409,18 +2408,18 @@ struct pjsua_msg_data * or from temporary local variable, and add the header using * linked list operation. See pjsua_app.c for some sample codes. */ - pjsip_hdr hdr_list; + pjsip_hdr hdr_list; /** * MIME type of optional message body. */ - pj_str_t content_type; + pj_str_t content_type; /** * Optional message body to be added to the message, only when the * message doesn't have a body. */ - pj_str_t msg_body; + pj_str_t msg_body; /** * Content type of the multipart body. If application wants to send @@ -2451,7 +2450,7 @@ PJ_DECL(void) pjsua_msg_data_init(pjsua_msg_data *msg_data); /** * Clone message data. * - * @param pool Pool to allocate memory for the new message data. + * @param pool Pool to allocate memory for the new message data. * @param rhs Message data to be cloned. * * @return The new message data. @@ -2466,7 +2465,7 @@ PJ_DECL(pjsua_msg_data*) pjsua_msg_data_clone(pj_pool_t *pool, * are properly initialized. Once this function has returned success, * application must call pjsua_destroy() before quitting. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_create(void); @@ -2482,15 +2481,15 @@ typedef struct pjsua_media_config pjsua_media_config; * * Note that #pjsua_create() MUST be called before calling this function. * - * @param ua_cfg User agent configuration. - * @param log_cfg Optional logging configuration. - * @param media_cfg Optional media configuration. + * @param ua_cfg User agent configuration. + * @param log_cfg Optional logging configuration. + * @param media_cfg Optional media configuration. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_init(const pjsua_config *ua_cfg, - const pjsua_logging_config *log_cfg, - const pjsua_media_config *media_cfg); + const pjsua_logging_config *log_cfg, + const pjsua_media_config *media_cfg); /** @@ -2500,7 +2499,7 @@ PJ_DECL(pj_status_t) pjsua_init(const pjsua_config *ua_cfg, * * Application may call this function anytime after #pjsua_init(). * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_start(void); @@ -2518,7 +2517,7 @@ PJ_DECL(pj_status_t) pjsua_start(void); * * @see pjsua_destroy2() * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_destroy(void); @@ -2526,7 +2525,7 @@ PJ_DECL(pj_status_t) pjsua_destroy(void); /** * Retrieve pjsua state. * - * @return pjsua state. + * @return pjsua state. */ PJ_DECL(pjsua_state) pjsua_get_state(void); @@ -2534,9 +2533,9 @@ PJ_DECL(pjsua_state) pjsua_get_state(void); /** * Variant of destroy with additional flags. * - * @param flags Combination of pjsua_destroy_flag enumeration. + * @param flags Combination of pjsua_destroy_flag enumeration. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_destroy2(unsigned flags); @@ -2549,11 +2548,11 @@ PJ_DECL(pj_status_t) pjsua_destroy2(unsigned flags); * configured worker thread (\a thread_cnt field) in pjsua_config structure, * because polling then will be done by these worker threads instead. * - * @param msec_timeout Maximum time to wait, in miliseconds. + * @param msec_timeout Maximum time to wait, in miliseconds. * * @return The number of events that have been handled during the - * poll. Negative value indicates error, and application - * can retrieve the error as (status = -return_value). + * poll. Negative value indicates error, and application + * can retrieve the error as (status = -return_value). */ PJ_DECL(int) pjsua_handle_events(unsigned msec_timeout); @@ -2569,23 +2568,23 @@ PJ_DECL(void) pjsua_stop_worker_threads(void); * Create memory pool to be used by the application. Once application * finished using the pool, it must be released with pj_pool_release(). * - * @param name Optional pool name. - * @param init_size Initial size of the pool. - * @param increment Increment size. + * @param name Optional pool name. + * @param init_size Initial size of the pool. + * @param increment Increment size. * - * @return The pool, or NULL when there's no memory. + * @return The pool, or NULL when there's no memory. */ PJ_DECL(pj_pool_t*) pjsua_pool_create(const char *name, pj_size_t init_size, - pj_size_t increment); + pj_size_t increment); /** * Application can call this function at any time (after pjsua_create(), of * course) to change logging settings. * - * @param c Logging configuration. + * @param c Logging configuration. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_reconfigure_logging(const pjsua_logging_config *c); @@ -2595,7 +2594,7 @@ PJ_DECL(pj_status_t) pjsua_reconfigure_logging(const pjsua_logging_config *c); * needed for example to register module, create transports, etc. * Only valid after #pjsua_init() is called. * - * @return SIP endpoint instance. + * @return SIP endpoint instance. */ PJ_DECL(pjsip_endpoint*) pjsua_get_pjsip_endpt(void); @@ -2603,7 +2602,7 @@ PJ_DECL(pjsip_endpoint*) pjsua_get_pjsip_endpt(void); * Internal function to get media endpoint instance. * Only valid after #pjsua_init() is called. * - * @return Media endpoint instance. + * @return Media endpoint instance. */ PJ_DECL(pjmedia_endpt*) pjsua_get_pjmedia_endpt(void); @@ -2611,7 +2610,7 @@ PJ_DECL(pjmedia_endpt*) pjsua_get_pjmedia_endpt(void); * Internal function to get PJSUA pool factory. * Only valid after #pjsua_create() is called. * - * @return Pool factory currently used by PJSUA. + * @return Pool factory currently used by PJSUA. */ PJ_DECL(pj_pool_factory*) pjsua_get_pool_factory(void); @@ -2633,31 +2632,31 @@ struct pj_stun_resolve_result * Arbitrary data that was passed to #pjsua_resolve_stun_servers() * function. */ - void *token; + void *token; /** * This will contain PJ_SUCCESS if at least one usable STUN server * is found, otherwise it will contain the last error code during * the operation. */ - pj_status_t status; + pj_status_t status; /** * The server name that yields successful result. This will only * contain value if status is successful. */ - pj_str_t name; + pj_str_t name; /** * The server IP address. This will only contain value if status * is successful. */ - pj_sockaddr addr; + pj_sockaddr addr; /** * The index of the usable STUN server. */ - unsigned index; + unsigned index; }; @@ -2671,7 +2670,7 @@ typedef struct pjsua_ip_change_param * * Default : PJ_TRUE */ - pj_bool_t restart_listener; + pj_bool_t restart_listener; /** * If \a restart listener is set to PJ_TRUE, some delay might be needed @@ -2679,7 +2678,7 @@ typedef struct pjsua_ip_change_param * * Default : PJSUA_TRANSPORT_RESTART_DELAY_TIME */ - unsigned restart_lis_delay; + unsigned restart_lis_delay; } pjsua_ip_change_param; @@ -2697,7 +2696,7 @@ typedef struct pjsua_ip_change_acc_cfg * * Default: PJ_TRUE */ - pj_bool_t shutdown_tp; + pj_bool_t shutdown_tp; /** * Hangup active calls associated with the account. If this is set to @@ -2705,7 +2704,7 @@ typedef struct pjsua_ip_change_acc_cfg * * Default: PJ_FALSE */ - pj_bool_t hangup_calls; + pj_bool_t hangup_calls; /** * Specify the call flags used in the re-INVITE when \a hangup_calls is set @@ -2715,7 +2714,7 @@ typedef struct pjsua_ip_change_acc_cfg * Default: PJSUA_CALL_REINIT_MEDIA | PJSUA_CALL_UPDATE_CONTACT | * PJSUA_CALL_UPDATE_VIA */ - unsigned reinvite_flags; + unsigned reinvite_flags; /** * For refreshing the call, use SIP UPDATE, instead of re-INVITE, if @@ -2726,7 +2725,7 @@ typedef struct pjsua_ip_change_acc_cfg * * Default: PJ_FALSE (using re-INVITE). */ - pj_bool_t reinv_use_update; + pj_bool_t reinv_use_update; } pjsua_ip_change_acc_cfg; @@ -2735,7 +2734,7 @@ typedef struct pjsua_ip_change_acc_cfg * Call this function to initialize \a pjsua_ip_change_param with default * values. * - * @param param The IP change param to be initialized. + * @param param The IP change param to be initialized. */ PJ_DECL(void) pjsua_ip_change_param_default(pjsua_ip_change_param *param); @@ -2753,7 +2752,7 @@ PJ_DECL(void) pjsua_ip_change_param_default(pjsua_ip_change_param *param); * * Note that STUN must be enabled to run this function successfully. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_detect_nat_type(void); @@ -2763,15 +2762,15 @@ PJ_DECL(pj_status_t) pjsua_detect_nat_type(void); * This function will only return useful NAT type after #pjsua_detect_nat_type() * has completed successfully and \a on_nat_detect() callback has been called. * - * @param type NAT type. + * @param type NAT type. * - * @return When detection is in progress, this function will - * return PJ_EPENDING and \a type will be set to - * PJ_STUN_NAT_TYPE_UNKNOWN. After NAT type has been - * detected successfully, this function will return - * PJ_SUCCESS and \a type will be set to the correct - * value. Other return values indicate error and - * \a type will be set to PJ_STUN_NAT_TYPE_ERR_UNKNOWN. + * @return When detection is in progress, this function will + * return PJ_EPENDING and \a type will be set to + * PJ_STUN_NAT_TYPE_UNKNOWN. After NAT type has been + * detected successfully, this function will return + * PJ_SUCCESS and \a type will be set to the correct + * value. Other return values indicate error and + * \a type will be set to PJ_STUN_NAT_TYPE_ERR_UNKNOWN. * * @see pjsua_call_get_rem_nat_type() */ @@ -2782,24 +2781,24 @@ PJ_DECL(pj_status_t) pjsua_get_nat_type(pj_stun_nat_type *type); * Update the STUN servers list. The #pjsua_init() must have been called * before calling this function. * - * @param count Number of STUN server entries. - * @param srv Array of STUN server entries to try. Please see - * the \a stun_srv field in the #pjsua_config - * documentation about the format of this entry. - * @param wait Specify non-zero to make the function block until - * it gets the result. In this case, the function - * will block while the resolution is being done, - * and the callback will be called before this function - * returns. - * - * @return If \a wait parameter is non-zero, this will return - * PJ_SUCCESS if one usable STUN server is found. - * Otherwise it will always return PJ_SUCCESS, and - * application will be notified about the result in - * the callback on_stun_resolution_complete(). + * @param count Number of STUN server entries. + * @param srv Array of STUN server entries to try. Please see + * the \a stun_srv field in the #pjsua_config + * documentation about the format of this entry. + * @param wait Specify non-zero to make the function block until + * it gets the result. In this case, the function + * will block while the resolution is being done, + * and the callback will be called before this function + * returns. + * + * @return If \a wait parameter is non-zero, this will return + * PJ_SUCCESS if one usable STUN server is found. + * Otherwise it will always return PJ_SUCCESS, and + * application will be notified about the result in + * the callback on_stun_resolution_complete(). */ PJ_DECL(pj_status_t) pjsua_update_stun_servers(unsigned count, pj_str_t srv[], - pj_bool_t wait); + pj_bool_t wait); /** @@ -2807,57 +2806,57 @@ PJ_DECL(pj_status_t) pjsua_update_stun_servers(unsigned count, pj_str_t srv[], * entries (sequentially) to find which is usable. The #pjsua_init() must * have been called before calling this function. * - * @param count Number of STUN server entries to try. - * @param srv Array of STUN server entries to try. Please see - * the \a stun_srv field in the #pjsua_config - * documentation about the format of this entry. - * @param wait Specify non-zero to make the function block until - * it gets the result. In this case, the function - * will block while the resolution is being done, - * and the callback will be called before this function - * returns. - * @param token Arbitrary token to be passed back to application - * in the callback. - * @param cb Callback to be called to notify the result of - * the function. - * - * @return If \a wait parameter is non-zero, this will return - * PJ_SUCCESS if one usable STUN server is found. - * Otherwise it will always return PJ_SUCCESS, and - * application will be notified about the result in - * the callback. + * @param count Number of STUN server entries to try. + * @param srv Array of STUN server entries to try. Please see + * the \a stun_srv field in the #pjsua_config + * documentation about the format of this entry. + * @param wait Specify non-zero to make the function block until + * it gets the result. In this case, the function + * will block while the resolution is being done, + * and the callback will be called before this function + * returns. + * @param token Arbitrary token to be passed back to application + * in the callback. + * @param cb Callback to be called to notify the result of + * the function. + * + * @return If \a wait parameter is non-zero, this will return + * PJ_SUCCESS if one usable STUN server is found. + * Otherwise it will always return PJ_SUCCESS, and + * application will be notified about the result in + * the callback. */ PJ_DECL(pj_status_t) pjsua_resolve_stun_servers(unsigned count, - pj_str_t srv[], - pj_bool_t wait, - void *token, - pj_stun_resolve_cb cb); + pj_str_t srv[], + pj_bool_t wait, + void *token, + pj_stun_resolve_cb cb); /** * Cancel pending STUN resolution which match the specified token. * - * @param token The token to match. This token was given to - * #pjsua_resolve_stun_servers() - * @param notify_cb Boolean to control whether the callback should - * be called for cancelled resolutions. When the - * callback is called, the status in the result - * will be set as PJ_ECANCELLED. + * @param token The token to match. This token was given to + * #pjsua_resolve_stun_servers() + * @param notify_cb Boolean to control whether the callback should + * be called for cancelled resolutions. When the + * callback is called, the status in the result + * will be set as PJ_ECANCELLED. * - * @return PJ_SUCCESS if there is at least one pending STUN - * resolution cancelled, or PJ_ENOTFOUND if there is - * no matching one, or other error. + * @return PJ_SUCCESS if there is at least one pending STUN + * resolution cancelled, or PJ_ENOTFOUND if there is + * no matching one, or other error. */ PJ_DECL(pj_status_t) pjsua_cancel_stun_resolution(void *token, - pj_bool_t notify_cb); + pj_bool_t notify_cb); /** * This is a utility function to verify that valid SIP url is given. If the * URL is a valid SIP/SIPS scheme, PJ_SUCCESS will be returned. * - * @param url The URL, as NULL terminated string. + * @param url The URL, as NULL terminated string. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. * * @see pjsua_verify_url() */ @@ -2869,9 +2868,9 @@ PJ_DECL(pj_status_t) pjsua_verify_sip_url(const char *url); * pjsua_verify_sip_url(), this function will return PJ_SUCCESS if tel: URI * is given. * - * @param url The URL, as NULL terminated string. + * @param url The URL, as NULL terminated string. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. * * @see pjsua_verify_sip_url() */ @@ -2883,10 +2882,10 @@ PJ_DECL(pj_status_t) pjsua_verify_url(const char *url); * by different thread, depending on whether worker thread is enabled or * not. * - * @param entry Timer heap entry. + * @param entry Timer heap entry. * @param delay The interval to expire. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. * * @see pjsip_endpt_schedule_timer() */ @@ -2900,7 +2899,7 @@ PJ_DECL(pj_status_t) pjsua_schedule_timer_dbg(pj_timer_entry *entry, int src_line); #else PJ_DECL(pj_status_t) pjsua_schedule_timer(pj_timer_entry *entry, - const pj_time_val *delay); + const pj_time_val *delay); #endif /** @@ -2908,15 +2907,15 @@ PJ_DECL(pj_status_t) pjsua_schedule_timer(pj_timer_entry *entry, * Note that the callback may be executed by different thread, depending on * whether worker thread is enabled or not. * - * @param cb The callback function. + * @param cb The callback function. * @param user_data The user data. * @param msec_delay The time interval in msec. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ #if PJ_TIMER_DEBUG #define pjsua_schedule_timer2(cb,u,d) \ - pjsua_schedule_timer2_dbg(cb,u,d,__FILE__,__LINE__) + pjsua_schedule_timer2_dbg(cb,u,d,__FILE__,__LINE__) PJ_DECL(pj_status_t) pjsua_schedule_timer2_dbg(void (*cb)(void *user_data), void *user_data, @@ -2932,7 +2931,7 @@ PJ_DECL(pj_status_t) pjsua_schedule_timer2(void (*cb)(void *user_data), /** * Cancel the previously scheduled timer. * - * @param entry Timer heap entry. + * @param entry Timer heap entry. * * @see pjsip_endpt_cancel_timer() */ @@ -2943,20 +2942,20 @@ PJ_DECL(void) pjsua_cancel_timer(pj_timer_entry *entry); * This is a utility function to display error message for the specified * error code. The error message will be sent to the log. * - * @param sender The log sender field. - * @param title Message title for the error. - * @param status Status code. + * @param sender The log sender field. + * @param title Message title for the error. + * @param status Status code. */ PJ_DECL(void) pjsua_perror(const char *sender, const char *title, - pj_status_t status); + pj_status_t status); /** * This is a utility function to dump the stack states to log, using * verbosity level 3. * - * @param detail Will print detailed output (such as list of - * SIP transactions) when non-zero. + * @param detail Will print detailed output (such as list of + * SIP transactions) when non-zero. */ PJ_DECL(void) pjsua_dump(pj_bool_t detail); @@ -2976,13 +2975,13 @@ PJ_DECL(void) pjsua_dump(pj_bool_t detail); * continue the call by sending re-INVITE * (configurable via \a pjsua_acc_config.ip_change_cfg.reinvite_flags). * - * @param param The IP change parameter, have a look at - * #pjsua_ip_change_param. + * @param param The IP change parameter, have a look at + * #pjsua_ip_change_param. * - * @return PJ_SUCCESS on success, other on error. + * @return PJ_SUCCESS on success, other on error. */ PJ_DECL(pj_status_t) pjsua_handle_ip_change( - const pjsua_ip_change_param *param); + const pjsua_ip_change_param *param); /** @@ -3026,7 +3025,7 @@ typedef struct pjsua_transport_config * transport will be bound to any available port, and application * can query the port by querying the transport info. */ - unsigned port; + unsigned port; /** * Specify the port range for socket binding, relative to the start @@ -3040,7 +3039,7 @@ typedef struct pjsua_transport_config * * Default value is zero. */ - unsigned port_range; + unsigned port_range; /** * Specify whether to randomly pick the starting port number from @@ -3050,7 +3049,7 @@ typedef struct pjsua_transport_config * * Default is PJ_FALSE. */ - pj_bool_t randomize_port; + pj_bool_t randomize_port; /** * Optional address to advertise as the address of this transport. @@ -3061,7 +3060,7 @@ typedef struct pjsua_transport_config * * Note: this option can be used for both UDP and TCP as well! */ - pj_str_t public_addr; + pj_str_t public_addr; /** * Optional address where the socket should be bound to. This option @@ -3074,14 +3073,14 @@ typedef struct pjsua_transport_config * MUST correspond to the actual interface address in the host, since * this address will be specified as bind() argument. */ - pj_str_t bound_addr; + pj_str_t bound_addr; /** * This specifies TLS settings for TLS transport. It is only be used * when this transport config is being used to create a SIP TLS * transport. */ - pjsip_tls_setting tls_setting; + pjsip_tls_setting tls_setting; /** * QoS traffic type to be set on this transport. When application wants @@ -3090,7 +3089,7 @@ typedef struct pjsua_transport_config * * Default is QoS not set. */ - pj_qos_type qos_type; + pj_qos_type qos_type; /** * Set the low level QoS parameters to the transport. This is a lower @@ -3099,7 +3098,7 @@ typedef struct pjsua_transport_config * * Default is QoS not set. */ - pj_qos_params qos_params; + pj_qos_params qos_params; /** * Specify options to be set on the transport. @@ -3107,7 +3106,7 @@ typedef struct pjsua_transport_config * By default there is no options. * */ - pj_sockopt_params sockopt_params; + pj_sockopt_params sockopt_params; } pjsua_transport_config; @@ -3115,7 +3114,7 @@ typedef struct pjsua_transport_config /** * Call this function to initialize UDP config with default values. * - * @param cfg The UDP config to be initialized. + * @param cfg The UDP config to be initialized. */ PJ_DECL(void) pjsua_transport_config_default(pjsua_transport_config *cfg); @@ -3123,13 +3122,13 @@ PJ_DECL(void) pjsua_transport_config_default(pjsua_transport_config *cfg); /** * Duplicate transport config. * - * @param pool The pool. - * @param dst The destination config. - * @param src The source config. + * @param pool The pool. + * @param dst The destination config. + * @param src The source config. */ PJ_DECL(void) pjsua_transport_config_dup(pj_pool_t *pool, - pjsua_transport_config *dst, - const pjsua_transport_config *src); + pjsua_transport_config *dst, + const pjsua_transport_config *src); /** @@ -3141,7 +3140,7 @@ typedef struct pjsua_transport_info /** * PJSUA transport identification. */ - pjsua_transport_id id; + pjsua_transport_id id; /** * Transport type. @@ -3151,37 +3150,37 @@ typedef struct pjsua_transport_info /** * Transport type name. */ - pj_str_t type_name; + pj_str_t type_name; /** * Transport string info/description. */ - pj_str_t info; + pj_str_t info; /** * Transport flag (see ##pjsip_transport_flags_e). */ - unsigned flag; + unsigned flag; /** * Local address length. */ - unsigned addr_len; + unsigned addr_len; /** * Local/bound address. */ - pj_sockaddr local_addr; + pj_sockaddr local_addr; /** * Published address (or transport address name). */ - pjsip_host_port local_name; + pjsip_host_port local_name; /** * Current number of objects currently referencing this transport. */ - unsigned usage_count; + unsigned usage_count; } pjsua_transport_info; @@ -3191,28 +3190,28 @@ typedef struct pjsua_transport_info * Create and start a new SIP transport according to the specified * settings. * - * @param type Transport type. - * @param cfg Transport configuration. - * @param p_id Optional pointer to receive transport ID. + * @param type Transport type. + * @param cfg Transport configuration. + * @param p_id Optional pointer to receive transport ID. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_transport_create(pjsip_transport_type_e type, - const pjsua_transport_config *cfg, - pjsua_transport_id *p_id); + const pjsua_transport_config *cfg, + pjsua_transport_id *p_id); /** * Register transport that has been created by application. This function * is useful if application wants to implement custom SIP transport and use * it with pjsua. * - * @param tp Transport instance. - * @param p_id Optional pointer to receive transport ID. + * @param tp Transport instance. + * @param p_id Optional pointer to receive transport ID. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_transport_register(pjsip_transport *tp, - pjsua_transport_id *p_id); + pjsua_transport_id *p_id); /** @@ -3220,13 +3219,13 @@ PJ_DECL(pj_status_t) pjsua_transport_register(pjsip_transport *tp, * This function is useful if application wants to implement custom SIP * transport and use it with pjsua. * - * @param tf Transport factory instance. - * @param p_id Optional pointer to receive transport ID. + * @param tf Transport factory instance. + * @param p_id Optional pointer to receive transport ID. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_tpfactory_register( pjsip_tpfactory *tf, - pjsua_transport_id *p_id); + pjsua_transport_id *p_id); /** * Enumerate all transports currently created in the system. This function @@ -3234,26 +3233,26 @@ PJ_DECL(pj_status_t) pjsua_tpfactory_register( pjsip_tpfactory *tf, * #pjsua_transport_get_info() function to retrieve detailed information * about the transport. * - * @param id Array to receive transport ids. - * @param count In input, specifies the maximum number of elements. - * On return, it contains the actual number of elements. + * @param id Array to receive transport ids. + * @param count In input, specifies the maximum number of elements. + * On return, it contains the actual number of elements. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_enum_transports( pjsua_transport_id id[], - unsigned *count ); + unsigned *count ); /** * Get information about transports. * - * @param id Transport ID. - * @param info Pointer to receive transport info. + * @param id Transport ID. + * @param info Pointer to receive transport info. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_transport_get_info(pjsua_transport_id id, - pjsua_transport_info *info); + pjsua_transport_info *info); /** @@ -3262,13 +3261,13 @@ PJ_DECL(pj_status_t) pjsua_transport_get_info(pjsua_transport_id id, * close the socket, it will only discard incoming messages and prevent * the transport from being used to send outgoing messages. * - * @param id Transport ID. - * @param enabled Non-zero to enable, zero to disable. + * @param id Transport ID. + * @param enabled Non-zero to enable, zero to disable. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_transport_set_enable(pjsua_transport_id id, - pj_bool_t enabled); + pj_bool_t enabled); /** @@ -3282,28 +3281,28 @@ PJ_DECL(pj_status_t) pjsua_transport_set_enable(pjsua_transport_id id, * close the transport for the purpose of restarting it should use * #pjsua_handle_ip_change() instead. * - * @param id Transport ID. - * @param force Must be PJ_FALSE. force = PJ_TRUE is deprecated. + * @param id Transport ID. + * @param force Must be PJ_FALSE. force = PJ_TRUE is deprecated. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_transport_close( pjsua_transport_id id, - pj_bool_t force ); + pj_bool_t force ); /** * Start the listener of the transport. This is useful when listener is not * automatically started when creating the transport. * - * @param id Transport ID. - * @param cfg The new transport config used by the listener. - * Only port, public_addr and bound_addr are used at the - * moment. + * @param id Transport ID. + * @param cfg The new transport config used by the listener. + * Only port, public_addr and bound_addr are used at the + * moment. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_transport_lis_start( pjsua_transport_id id, - const pjsua_transport_config *cfg); + const pjsua_transport_config *cfg); /** @@ -3361,7 +3360,7 @@ PJ_DECL(pj_status_t) pjsua_transport_lis_start( pjsua_transport_id id, * Maximum accounts. */ #ifndef PJSUA_MAX_ACC -# define PJSUA_MAX_ACC 8 +# define PJSUA_MAX_ACC 8 #endif @@ -3369,7 +3368,7 @@ PJ_DECL(pj_status_t) pjsua_transport_lis_start( pjsua_transport_id id, * Default registration interval. */ #ifndef PJSUA_REG_INTERVAL -# define PJSUA_REG_INTERVAL 300 +# define PJSUA_REG_INTERVAL 300 #endif @@ -3380,7 +3379,7 @@ PJ_DECL(pj_status_t) pjsua_transport_lis_start( pjsua_transport_id id, * Default: 4000 (4 seconds) */ #ifndef PJSUA_UNREG_TIMEOUT -# define PJSUA_UNREG_TIMEOUT 4000 +# define PJSUA_UNREG_TIMEOUT 4000 #endif @@ -3396,7 +3395,7 @@ PJ_DECL(pj_status_t) pjsua_transport_lis_start( pjsua_transport_id id, * Default account priority. */ #ifndef PJSUA_DEFAULT_ACC_PRIORITY -# define PJSUA_DEFAULT_ACC_PRIORITY 0 +# define PJSUA_DEFAULT_ACC_PRIORITY 0 #endif @@ -3412,7 +3411,7 @@ PJ_DECL(pj_status_t) pjsua_transport_lis_start( pjsua_transport_id id, * Default: 2000 (2 seconds) */ #ifndef PJSUA_UNPUBLISH_MAX_WAIT_TIME_MSEC -# define PJSUA_UNPUBLISH_MAX_WAIT_TIME_MSEC 2000 +# define PJSUA_UNPUBLISH_MAX_WAIT_TIME_MSEC 2000 #endif @@ -3424,7 +3423,7 @@ PJ_DECL(pj_status_t) pjsua_transport_lis_start( pjsua_transport_id id, * Default: 300 (5 minutes) */ #ifndef PJSUA_REG_RETRY_INTERVAL -# define PJSUA_REG_RETRY_INTERVAL 300 +# define PJSUA_REG_RETRY_INTERVAL 300 #endif /** @@ -3453,7 +3452,7 @@ PJ_DECL(pj_status_t) pjsua_transport_lis_start( pjsua_transport_id id, * PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE(4) */ #ifndef PJSUA_CONTACT_REWRITE_METHOD -# define PJSUA_CONTACT_REWRITE_METHOD (PJSUA_CONTACT_REWRITE_NO_UNREG | \ +# define PJSUA_CONTACT_REWRITE_METHOD (PJSUA_CONTACT_REWRITE_NO_UNREG | \ PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE) #endif @@ -3462,14 +3461,14 @@ PJ_DECL(pj_status_t) pjsua_transport_lis_start( pjsua_transport_id id, * Bit value used in pjsua_acc_config.reg_use_proxy field to indicate that * the global outbound proxy list should be added to the REGISTER request. */ -#define PJSUA_REG_USE_OUTBOUND_PROXY 1 +#define PJSUA_REG_USE_OUTBOUND_PROXY 1 /** * Bit value used in pjsua_acc_config.reg_use_proxy field to indicate that * the account proxy list should be added to the REGISTER request. */ -#define PJSUA_REG_USE_ACC_PROXY 2 +#define PJSUA_REG_USE_ACC_PROXY 2 /** @@ -3507,7 +3506,7 @@ typedef enum pjsua_call_hold_type * this except if you're communicating with an old/non-standard peer. */ #ifndef PJSUA_CALL_HOLD_TYPE_DEFAULT -# define PJSUA_CALL_HOLD_TYPE_DEFAULT PJSUA_CALL_HOLD_TYPE_RFC3264 +# define PJSUA_CALL_HOLD_TYPE_DEFAULT PJSUA_CALL_HOLD_TYPE_RFC3264 #endif /** @@ -3596,26 +3595,26 @@ typedef struct pjsua_ice_config /** * Enable ICE. */ - pj_bool_t enable_ice; + pj_bool_t enable_ice; /** * Set the maximum number of host candidates. * * Default: -1 (maximum not set) */ - int ice_max_host_cands; + int ice_max_host_cands; /** * ICE session options. */ - pj_ice_sess_options ice_opt; + pj_ice_sess_options ice_opt; /** * Disable RTCP component. * * Default: no */ - pj_bool_t ice_no_rtcp; + pj_bool_t ice_no_rtcp; /** * Send re-INVITE/UPDATE every after ICE connectivity check regardless @@ -3625,7 +3624,7 @@ typedef struct pjsua_ice_config * * Default: yes */ - pj_bool_t ice_always_update; + pj_bool_t ice_always_update; } pjsua_ice_config; @@ -3637,13 +3636,13 @@ typedef struct pjsua_turn_config /** * Enable TURN candidate in ICE. */ - pj_bool_t enable_turn; + pj_bool_t enable_turn; /** * Specify TURN domain name or host name, in in "DOMAIN:PORT" or * "HOST:PORT" format. */ - pj_str_t turn_server; + pj_str_t turn_server; /** * Specify the connection type to be used to the TURN server. Valid @@ -3651,12 +3650,12 @@ typedef struct pjsua_turn_config * * Default: PJ_TURN_TP_UDP */ - pj_turn_tp_type turn_conn_type; + pj_turn_tp_type turn_conn_type; /** * Specify the credential to authenticate with the TURN server. */ - pj_stun_auth_cred turn_auth_cred; + pj_stun_auth_cred turn_auth_cred; /** * This specifies TLS settings for TURN TLS. It is only be used @@ -3713,14 +3712,14 @@ typedef struct pjsua_acc_config * Application may set this later with #pjsua_acc_set_user_data() and * retrieve it with #pjsua_acc_get_user_data(). */ - void *user_data; + void *user_data; /** * Account priority, which is used to control the order of matching * incoming/outgoing requests. The higher the number means the higher * the priority is, and the account will be matched first. */ - int priority; + int priority; /** * The full SIP URL for the account. The value can take name address or @@ -3729,7 +3728,7 @@ typedef struct pjsua_acc_config * * This field is mandatory. */ - pj_str_t id; + pj_str_t id; /** * This is the URL to be put in the request URI for the registration, @@ -3738,13 +3737,13 @@ typedef struct pjsua_acc_config * This field should be specified if registration is desired. If the * value is empty, no account registration will be performed. */ - pj_str_t reg_uri; + pj_str_t reg_uri; /** * The optional custom SIP headers to be put in the registration * request. */ - pjsip_hdr reg_hdr_list; + pjsip_hdr reg_hdr_list; /** * Additional parameters that will be appended in the Contact header @@ -3753,9 +3752,9 @@ typedef struct pjsua_acc_config * * The parameters should be preceeded by semicolon, and all strings must * be properly escaped. Example: - * ";my-param=X;another-param=Hi%20there" + * ";my-param=X;another-param=Hi%20there" */ - pj_str_t reg_contact_params; + pj_str_t reg_contact_params; /** * Additional URI parameters that will be appended in the Contact URI @@ -3764,15 +3763,15 @@ typedef struct pjsua_acc_config * * The parameters should be preceeded by semicolon, and all strings must * be properly escaped. Example: - * ";my-param=X;another-param=Hi%20there" + * ";my-param=X;another-param=Hi%20there" */ - pj_str_t reg_contact_uri_params; + pj_str_t reg_contact_uri_params; /** * The optional custom SIP headers to be put in the presence * subscription request. */ - pjsip_hdr sub_hdr_list; + pjsip_hdr sub_hdr_list; /** * Subscribe to message waiting indication events (RFC 3842). @@ -3781,7 +3780,7 @@ typedef struct pjsua_acc_config * * Default: no */ - pj_bool_t mwi_enabled; + pj_bool_t mwi_enabled; /** * Specify the default expiration time for Message Waiting Indication @@ -3789,7 +3788,7 @@ typedef struct pjsua_acc_config * * Default: PJSIP_MWI_DEFAULT_EXPIRES */ - unsigned mwi_expires; + unsigned mwi_expires; /** * If this flag is set, the presence information of this account will @@ -3797,12 +3796,12 @@ typedef struct pjsua_acc_config * * Default: PJ_FALSE */ - pj_bool_t publish_enabled; + pj_bool_t publish_enabled; /** * Event publication options. */ - pjsip_publishc_opt publish_opt; + pjsip_publishc_opt publish_opt; /** * Maximum time to wait for unpublication transaction(s) to complete @@ -3815,7 +3814,7 @@ typedef struct pjsua_acc_config * * Default: PJSUA_UNPUBLISH_MAX_WAIT_TIME_MSEC */ - unsigned unpublish_max_wait_time_msec; + unsigned unpublish_max_wait_time_msec; /** * Authentication preference. @@ -3826,14 +3825,14 @@ typedef struct pjsua_acc_config * Optional PIDF tuple ID for outgoing PUBLISH and NOTIFY. If this value * is not specified, a random string will be used. */ - pj_str_t pidf_tuple_id; + pj_str_t pidf_tuple_id; /** * Optional URI to be put as Contact for this account. It is recommended * that this field is left empty, so that the value will be calculated * automatically based on the transport address. */ - pj_str_t force_contact; + pj_str_t force_contact; /** * Additional parameters that will be appended in the Contact header @@ -3843,9 +3842,9 @@ typedef struct pjsua_acc_config * * The parameters should be preceeded by semicolon, and all strings must * be properly escaped. Example: - * ";my-param=X;another-param=Hi%20there" + * ";my-param=X;another-param=Hi%20there" */ - pj_str_t contact_params; + pj_str_t contact_params; /** * Additional URI parameters that will be appended in the Contact URI @@ -3855,9 +3854,9 @@ typedef struct pjsua_acc_config * * The parameters should be preceeded by semicolon, and all strings must * be properly escaped. Example: - * ";my-param=X;another-param=Hi%20there" + * ";my-param=X;another-param=Hi%20there" */ - pj_str_t contact_uri_params; + pj_str_t contact_uri_params; /** * Specify how support for reliable provisional response (100rel/ @@ -3885,7 +3884,7 @@ typedef struct pjsua_acc_config /** * Number of proxies in the proxy array below. */ - unsigned proxy_cnt; + unsigned proxy_cnt; /** * Optional URI of the proxies to be visited for all outgoing requests @@ -3900,7 +3899,7 @@ typedef struct pjsua_acc_config * then these account proxies will be placed after the global outbound * proxies in the routeset. */ - pj_str_t proxy[PJSUA_ACC_MAX_PROXIES]; + pj_str_t proxy[PJSUA_ACC_MAX_PROXIES]; /** * If remote sends SDP answer containing more than one format or codec in @@ -3909,13 +3908,13 @@ typedef struct pjsua_acc_config * * Default: 1 (Yes). Set to zero to disable. */ - unsigned lock_codec; + unsigned lock_codec; /** * Optional interval for registration, in seconds. If the value is zero, * default interval will be used (PJSUA_REG_INTERVAL, 300 seconds). */ - unsigned reg_timeout; + unsigned reg_timeout; /** * Specify the number of seconds to refresh the client registration @@ -3923,7 +3922,7 @@ typedef struct pjsua_acc_config * * Default: PJSIP_REGISTER_CLIENT_DELAY_BEFORE_REFRESH, 5 seconds */ - unsigned reg_delay_before_refresh; + unsigned reg_delay_before_refresh; /** * Specify the maximum time to wait for unregistration requests to @@ -3931,12 +3930,12 @@ typedef struct pjsua_acc_config * * Default: PJSUA_UNREG_TIMEOUT */ - unsigned unreg_timeout; + unsigned unreg_timeout; /** * Number of credentials in the credential array. */ - unsigned cred_count; + unsigned cred_count; /** * Array of credentials. If registration is desired, normally there should @@ -3986,7 +3985,7 @@ typedef struct pjsua_acc_config * Default value: PJSUA_CONTACT_REWRITE_METHOD * (PJSUA_CONTACT_REWRITE_NO_UNREG | PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE) */ - int contact_rewrite_method; + int contact_rewrite_method; /** * Specify if source TCP port should be used as the initial Contact @@ -3999,7 +3998,7 @@ typedef struct pjsua_acc_config * * Default: PJ_TRUE (yes). */ - pj_bool_t contact_use_src_port; + pj_bool_t contact_use_src_port; /** * This option is used to overwrite the "sent-by" field of the Via header @@ -4036,7 +4035,7 @@ typedef struct pjsua_acc_config * * Default: PJ_TRUE */ - unsigned use_rfc5626; + unsigned use_rfc5626; /** * Specify SIP outbound (RFC 5626) instance ID to be used by this @@ -4047,7 +4046,7 @@ typedef struct pjsua_acc_config * * Default: empty */ - pj_str_t rfc5626_instance_id; + pj_str_t rfc5626_instance_id; /** * Specify SIP outbound (RFC 5626) registration ID. The default value @@ -4056,7 +4055,7 @@ typedef struct pjsua_acc_config * * Default: empty */ - pj_str_t rfc5626_reg_id; + pj_str_t rfc5626_reg_id; /** * Set the interval for periodic keep-alive transmission for this account. @@ -4066,14 +4065,14 @@ typedef struct pjsua_acc_config * * Default: 15 (seconds) */ - unsigned ka_interval; + unsigned ka_interval; /** * Specify the data to be transmitted as keep-alive packets. * * Default: CR-LF */ - pj_str_t ka_data; + pj_str_t ka_data; /** * Specify whether incoming video should be shown to screen by default. @@ -4160,40 +4159,40 @@ typedef struct pjsua_acc_config * * Default: PJSUA_NAT64_DISABLED */ - pjsua_nat64_opt nat64_opt; + pjsua_nat64_opt nat64_opt; /** * Specify whether IPv6 should be used on media. */ - pjsua_ipv6_use ipv6_media_use; + pjsua_ipv6_use ipv6_media_use; /** * Control the use of STUN for the SIP signaling. * * Default: PJSUA_STUN_USE_DEFAULT */ - pjsua_stun_use sip_stun_use; + pjsua_stun_use sip_stun_use; /** * Control the use of STUN for the media transports. * * Default: PJSUA_STUN_RETRY_ON_FAILURE */ - pjsua_stun_use media_stun_use; + pjsua_stun_use media_stun_use; /** * Control the use of UPnP for the SIP signaling. * * Default: PJSUA_UPNP_USE_DEFAULT */ - pjsua_upnp_use sip_upnp_use; + pjsua_upnp_use sip_upnp_use; /** * Control the use of UPnP for the media transports. * * Default: PJSUA_UPNP_USE_DEFAULT */ - pjsua_upnp_use media_upnp_use; + pjsua_upnp_use media_upnp_use; /** * Use loopback media transport. This may be useful if application @@ -4202,7 +4201,7 @@ typedef struct pjsua_acc_config * * Default: PJ_FALSE */ - pj_bool_t use_loop_med_tp; + pj_bool_t use_loop_med_tp; /** * Enable local loopback when loop_med_tp_use is set to PJ_TRUE. @@ -4211,7 +4210,7 @@ typedef struct pjsua_acc_config * * Default: PJ_FALSE */ - pj_bool_t enable_loopback; + pj_bool_t enable_loopback; /** * Control the use of ICE in the account. By default, the settings in the @@ -4219,13 +4218,13 @@ typedef struct pjsua_acc_config * * Default: PJSUA_ICE_CONFIG_USE_DEFAULT */ - pjsua_ice_config_use ice_cfg_use; + pjsua_ice_config_use ice_cfg_use; /** * The custom ICE setting for this account. This setting will only be * used if \a ice_cfg_use is set to PJSUA_ICE_CONFIG_USE_CUSTOM */ - pjsua_ice_config ice_cfg; + pjsua_ice_config ice_cfg; /** * Control the use of TURN in the account. By default, the settings in the @@ -4233,13 +4232,13 @@ typedef struct pjsua_acc_config * * Default: PJSUA_TURN_CONFIG_USE_DEFAULT */ - pjsua_turn_config_use turn_cfg_use; + pjsua_turn_config_use turn_cfg_use; /** * The custom TURN setting for this account. This setting will only be * used if \a turn_cfg_use is set to PJSUA_TURN_CONFIG_USE_CUSTOM */ - pjsua_turn_config turn_cfg; + pjsua_turn_config turn_cfg; /** * Specify whether secure media transport should be used for this account. @@ -4248,25 +4247,25 @@ typedef struct pjsua_acc_config * * Default: #PJSUA_DEFAULT_USE_SRTP */ - pjmedia_srtp_use use_srtp; + pjmedia_srtp_use use_srtp; /** * Specify whether SRTP requires secure signaling to be used. This option * is only used when \a use_srtp option above is non-zero. * * Valid values are: - * 0: SRTP does not require secure signaling - * 1: SRTP requires secure transport such as TLS - * 2: SRTP requires secure end-to-end transport (SIPS) + * 0: SRTP does not require secure signaling + * 1: SRTP requires secure transport such as TLS + * 2: SRTP requires secure end-to-end transport (SIPS) * * Default: #PJSUA_DEFAULT_SRTP_SECURE_SIGNALING */ - int srtp_secure_signaling; + int srtp_secure_signaling; /** * This setting has been deprecated and will be ignored. */ - pj_bool_t srtp_optional_dup_offer; + pj_bool_t srtp_optional_dup_offer; /** * Specify SRTP transport setting. Application can initialize it with @@ -4293,7 +4292,7 @@ typedef struct pjsua_acc_config * * Default: #PJSUA_REG_RETRY_INTERVAL */ - unsigned reg_retry_interval; + unsigned reg_retry_interval; /** * This specifies the interval for the first registration retry. The @@ -4304,7 +4303,7 @@ typedef struct pjsua_acc_config * * Default: 0 */ - unsigned reg_first_retry_interval; + unsigned reg_first_retry_interval; /** * This specifies maximum randomized value to be added/substracted @@ -4317,7 +4316,7 @@ typedef struct pjsua_acc_config * * Default: 10 */ - unsigned reg_retry_random_interval; + unsigned reg_retry_random_interval; /** * Specify whether calls of the configured account should be dropped @@ -4326,7 +4325,7 @@ typedef struct pjsua_acc_config * * Default: PJ_FALSE (disabled) */ - pj_bool_t drop_calls_on_reg_fail; + pj_bool_t drop_calls_on_reg_fail; /** * Specify how the registration uses the outbound and account proxy @@ -4338,7 +4337,7 @@ typedef struct pjsua_acc_config * * Default: 3 (PJSUA_REG_USE_OUTBOUND_PROXY | PJSUA_REG_USE_ACC_PROXY) */ - unsigned reg_use_proxy; + unsigned reg_use_proxy; #if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0) /** @@ -4348,7 +4347,7 @@ typedef struct pjsua_acc_config * * Default: PJ_FALSE (disabled) */ - pj_bool_t use_stream_ka; + pj_bool_t use_stream_ka; /** * Specify the keepalive configuration for stream. @@ -4374,7 +4373,7 @@ typedef struct pjsua_acc_config * * Default: PJ_TRUE */ - pj_bool_t register_on_acc_add; + pj_bool_t register_on_acc_add; /** * Specify account configuration specific to IP address change used when @@ -4385,7 +4384,7 @@ typedef struct pjsua_acc_config /** * Enable RTP and RTCP multiplexing. */ - pj_bool_t enable_rtcp_mux; + pj_bool_t enable_rtcp_mux; /** * RTCP Feedback configuration. @@ -4397,7 +4396,7 @@ typedef struct pjsua_acc_config * * Default: PJMEDIA_STREAM_ENABLE_XR */ - pj_bool_t enable_rtcp_xr; + pj_bool_t enable_rtcp_xr; } pjsua_acc_config; @@ -4406,9 +4405,9 @@ typedef struct pjsua_acc_config * Initialize ICE config from a media config. If the \a pool argument * is NULL, a simple memcpy() will be used. * - * @param pool Memory to duplicate strings. - * @param dst Destination config. - * @param src Source config. + * @param pool Memory to duplicate strings. + * @param dst Destination config. + * @param src Source config. */ PJ_DECL(void) pjsua_ice_config_from_media_config(pj_pool_t *pool, pjsua_ice_config *dst, @@ -4417,9 +4416,9 @@ PJ_DECL(void) pjsua_ice_config_from_media_config(pj_pool_t *pool, /** * Clone. If the \a pool argument is NULL, a simple memcpy() will be used. * - * @param pool Memory to duplicate strings. - * @param dst Destination config. - * @param src Source config. + * @param pool Memory to duplicate strings. + * @param dst Destination config. + * @param src Source config. */ PJ_DECL(void) pjsua_ice_config_dup( pj_pool_t *pool, pjsua_ice_config *dst, @@ -4429,9 +4428,9 @@ PJ_DECL(void) pjsua_ice_config_dup( pj_pool_t *pool, * Initialize TURN config from a media config. If the \a pool argument * is NULL, a simple memcpy() will be used. * - * @param pool Memory to duplicate strings. - * @param dst Destination config. - * @param src Source config. + * @param pool Memory to duplicate strings. + * @param dst Destination config. + * @param src Source config. */ PJ_DECL(void) pjsua_turn_config_from_media_config(pj_pool_t *pool, pjsua_turn_config *dst, @@ -4440,9 +4439,9 @@ PJ_DECL(void) pjsua_turn_config_from_media_config(pj_pool_t *pool, /** * Clone. If the \a pool argument is NULL, a simple memcpy() will be used. * - * @param pool Memory to duplicate strings. - * @param dst Destination config. - * @param src Source config. + * @param pool Memory to duplicate strings. + * @param dst Destination config. + * @param src Source config. */ PJ_DECL(void) pjsua_turn_config_dup(pj_pool_t *pool, pjsua_turn_config *dst, @@ -4452,7 +4451,7 @@ PJ_DECL(void) pjsua_turn_config_dup(pj_pool_t *pool, /** * Call this function to initialize SRTP config with default values. * - * @param cfg The SRTP config to be initialized. + * @param cfg The SRTP config to be initialized. */ PJ_DECL(void) pjsua_srtp_opt_default(pjsua_srtp_opt *cfg); @@ -4461,13 +4460,13 @@ PJ_DECL(void) pjsua_srtp_opt_default(pjsua_srtp_opt *cfg); * Duplicate SRTP transport setting. If the \a pool argument is NULL, * a simple memcpy() will be used. * - * @param pool Memory to duplicate strings. - * @param dst Destination setting. - * @param src Source setting. + * @param pool Memory to duplicate strings. + * @param dst Destination setting. + * @param src Source setting. * @param check_str If set to TRUE, the function will check if strings - * are identical before copying. Identical strings - * will not be duplicated. - * If set to FALSE, all strings will be duplicated. + * are identical before copying. Identical strings + * will not be duplicated. + * If set to FALSE, all strings will be duplicated. */ PJ_DECL(void) pjsua_srtp_opt_dup(pj_pool_t *pool, pjsua_srtp_opt *dst, const pjsua_srtp_opt *src, @@ -4477,7 +4476,7 @@ PJ_DECL(void) pjsua_srtp_opt_dup(pj_pool_t *pool, pjsua_srtp_opt *dst, /** * Call this function to initialize account config with default values. * - * @param cfg The account config to be initialized. + * @param cfg The account config to be initialized. */ PJ_DECL(void) pjsua_acc_config_default(pjsua_acc_config *cfg); @@ -4485,13 +4484,13 @@ PJ_DECL(void) pjsua_acc_config_default(pjsua_acc_config *cfg); /** * Duplicate account config. * - * @param pool Pool to be used for duplicating the config. - * @param dst Destination configuration. - * @param src Source configuration. + * @param pool Pool to be used for duplicating the config. + * @param dst Destination configuration. + * @param src Source configuration. */ PJ_DECL(void) pjsua_acc_config_dup(pj_pool_t *pool, - pjsua_acc_config *dst, - const pjsua_acc_config *src); + pjsua_acc_config *dst, + const pjsua_acc_config *src); /** @@ -4503,36 +4502,36 @@ typedef struct pjsua_acc_info /** * The account ID. */ - pjsua_acc_id id; + pjsua_acc_id id; /** * Flag to indicate whether this is the default account. */ - pj_bool_t is_default; + pj_bool_t is_default; /** * Account URI */ - pj_str_t acc_uri; + pj_str_t acc_uri; /** * Flag to tell whether this account has registration setting * (reg_uri is not empty). */ - pj_bool_t has_registration; + pj_bool_t has_registration; /** * An up to date expiration interval for account registration session, * PJSIP_EXPIRES_NOT_SPECIFIED if the account doesn't have reg session. */ - unsigned expires; + unsigned expires; /** * Last registration status code. If status code is zero, the account * is currently not registered. Any other value indicates the SIP * status code of the registration. */ - pjsip_status_code status; + pjsip_status_code status; /** * Last registration error code. When the status field contains a SIP @@ -4540,32 +4539,32 @@ typedef struct pjsua_acc_info * error code contains the error code that causes the failure. In any * other case, its value is zero. */ - pj_status_t reg_last_err; + pj_status_t reg_last_err; /** * String describing the registration status. */ - pj_str_t status_text; + pj_str_t status_text; /** * Presence online status for this account. */ - pj_bool_t online_status; + pj_bool_t online_status; /** * Presence online status text. */ - pj_str_t online_status_text; + pj_str_t online_status_text; /** * Extended RPID online status information. */ - pjrpid_element rpid; + pjrpid_element rpid; /** * Buffer that is used internally to store the status text. */ - char buf_[PJ_ERR_MSG_SIZE]; + char buf_[PJ_ERR_MSG_SIZE]; } pjsua_acc_info; @@ -4574,7 +4573,7 @@ typedef struct pjsua_acc_info /** * Get number of current accounts. * - * @return Current number of accounts. + * @return Current number of accounts. */ PJ_DECL(unsigned) pjsua_acc_get_count(void); @@ -4582,9 +4581,9 @@ PJ_DECL(unsigned) pjsua_acc_get_count(void); /** * Check if the specified account ID is valid. * - * @param acc_id Account ID to check. + * @param acc_id Account ID to check. * - * @return Non-zero if account ID is valid. + * @return Non-zero if account ID is valid. */ PJ_DECL(pj_bool_t) pjsua_acc_is_valid(pjsua_acc_id acc_id); @@ -4593,9 +4592,9 @@ PJ_DECL(pj_bool_t) pjsua_acc_is_valid(pjsua_acc_id acc_id); * Set default account to be used when incoming and outgoing * requests doesn't match any accounts. * - * @param acc_id The account ID to be used as default. + * @param acc_id The account ID to be used as default. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsua_acc_set_default(pjsua_acc_id acc_id); @@ -4605,8 +4604,8 @@ PJ_DECL(pj_status_t) pjsua_acc_set_default(pjsua_acc_id acc_id); * when the destination of the incoming call doesn't match any other * accounts. * - * @return The default account ID, or PJSUA_INVALID_ID if no - * default account is configured. + * @return The default account ID, or PJSUA_INVALID_ID if no + * default account is configured. */ PJ_DECL(pjsua_acc_id) pjsua_acc_get_default(void); @@ -4620,20 +4619,20 @@ PJ_DECL(pjsua_acc_id) pjsua_acc_get_default(void); * need to do anything to maintain the registration session. * * - * @param acc_cfg Account configuration. - * @param is_default If non-zero, this account will be set as the default - * account. The default account will be used when sending - * outgoing requests (e.g. making call) when no account is - * specified, and when receiving incoming requests when the - * request does not match any accounts. It is recommended - * that default account is set to local/LAN account. - * @param p_acc_id Pointer to receive account ID of the new account. + * @param acc_cfg Account configuration. + * @param is_default If non-zero, this account will be set as the default + * account. The default account will be used when sending + * outgoing requests (e.g. making call) when no account is + * specified, and when receiving incoming requests when the + * request does not match any accounts. It is recommended + * that default account is set to local/LAN account. + * @param p_acc_id Pointer to receive account ID of the new account. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_acc_add(const pjsua_acc_config *acc_cfg, - pj_bool_t is_default, - pjsua_acc_id *p_acc_id); + pj_bool_t is_default, + pjsua_acc_id *p_acc_id); /** @@ -4641,40 +4640,40 @@ PJ_DECL(pj_status_t) pjsua_acc_add(const pjsua_acc_config *acc_cfg, * instead of a specific user, and for this reason, a transport ID is needed * to obtain the local address information. * - * @param tid Transport ID to generate account address. - * @param is_default If non-zero, this account will be set as the default - * account. The default account will be used when sending - * outgoing requests (e.g. making call) when no account is - * specified, and when receiving incoming requests when the - * request does not match any accounts. It is recommended - * that default account is set to local/LAN account. - * @param p_acc_id Pointer to receive account ID of the new account. + * @param tid Transport ID to generate account address. + * @param is_default If non-zero, this account will be set as the default + * account. The default account will be used when sending + * outgoing requests (e.g. making call) when no account is + * specified, and when receiving incoming requests when the + * request does not match any accounts. It is recommended + * that default account is set to local/LAN account. + * @param p_acc_id Pointer to receive account ID of the new account. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_acc_add_local(pjsua_transport_id tid, - pj_bool_t is_default, - pjsua_acc_id *p_acc_id); + pj_bool_t is_default, + pjsua_acc_id *p_acc_id); /** * Set arbitrary data to be associated with the account. * - * @param acc_id The account ID. - * @param user_data User/application data. + * @param acc_id The account ID. + * @param user_data User/application data. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_acc_set_user_data(pjsua_acc_id acc_id, - void *user_data); + void *user_data); /** * Retrieve arbitrary data associated with the account. * - * @param acc_id The account ID. + * @param acc_id The account ID. * - * @return The user data. In the case where the account ID is - * not valid, NULL is returned. + * @return The user data. In the case where the account ID is + * not valid, NULL is returned. */ PJ_DECL(void*) pjsua_acc_get_user_data(pjsua_acc_id acc_id); @@ -4684,9 +4683,9 @@ PJ_DECL(void*) pjsua_acc_get_user_data(pjsua_acc_id acc_id); * if necessary, and terminate server side presence subscriptions associated * with this account. * - * @param acc_id Id of the account to be deleted. + * @param acc_id Id of the account to be deleted. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_acc_del(pjsua_acc_id acc_id); @@ -4698,11 +4697,11 @@ PJ_DECL(pj_status_t) pjsua_acc_del(pjsua_acc_id acc_id); * modify the values in any way. Application must also take care that these * data is only valid until the account is destroyed. * - * @param acc_id The account ID. - * @param pool Pool to duplicate the config. - * @param acc_cfg Structure to receive the settings. + * @param acc_id The account ID. + * @param pool Pool to duplicate the config. + * @param acc_cfg Structure to receive the settings. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_acc_get_config(pjsua_acc_id acc_id, pj_pool_t *pool, @@ -4725,13 +4724,13 @@ PJ_DECL(pj_status_t) pjsua_acc_get_config(pjsua_acc_id acc_id, * fails, the account setting will not be reverted back to the old setting * and the account will be in unregistered state. * - * @param acc_id Id of the account to be modified. - * @param acc_cfg New account configuration. + * @param acc_id Id of the account to be modified. + * @param acc_cfg New account configuration. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_acc_modify(pjsua_acc_id acc_id, - const pjsua_acc_config *acc_cfg); + const pjsua_acc_config *acc_cfg); /** @@ -4742,13 +4741,13 @@ PJ_DECL(pj_status_t) pjsua_acc_modify(pjsua_acc_id acc_id, * * @see pjsua_acc_set_online_status2() * - * @param acc_id The account ID. - * @param is_online True of false. + * @param acc_id The account ID. + * @param is_online True of false. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_acc_set_online_status(pjsua_acc_id acc_id, - pj_bool_t is_online); + pj_bool_t is_online); /** * Modify account's presence status to be advertised to remote/presence @@ -4758,16 +4757,16 @@ PJ_DECL(pj_status_t) pjsua_acc_set_online_status(pjsua_acc_id acc_id, * * @see pjsua_acc_set_online_status() * - * @param acc_id The account ID. - * @param is_online True of false. - * @param pr Extended information in subset of RPID format - * which allows setting custom presence text. + * @param acc_id The account ID. + * @param is_online True of false. + * @param pr Extended information in subset of RPID format + * which allows setting custom presence text. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_acc_set_online_status2(pjsua_acc_id acc_id, - pj_bool_t is_online, - const pjrpid_element *pr); + pj_bool_t is_online, + const pjrpid_element *pr); /** * Update registration or perform unregistration. If registration is @@ -4776,25 +4775,25 @@ PJ_DECL(pj_status_t) pjsua_acc_set_online_status2(pjsua_acc_id acc_id, * only need to call this function if it wants to manually update the * registration or to unregister from the server. * - * @param acc_id The account ID. - * @param renew If renew argument is zero, this will start - * unregistration process. + * @param acc_id The account ID. + * @param renew If renew argument is zero, this will start + * unregistration process. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_acc_set_registration(pjsua_acc_id acc_id, - pj_bool_t renew); + pj_bool_t renew); /** * Get information about the specified account. * - * @param acc_id Account identification. - * @param info Pointer to receive account information. + * @param acc_id Account identification. + * @param info Pointer to receive account information. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_acc_get_info(pjsua_acc_id acc_id, - pjsua_acc_info *info); + pjsua_acc_info *info); /** @@ -4804,36 +4803,36 @@ PJ_DECL(pj_status_t) pjsua_acc_get_info(pjsua_acc_id acc_id, * * @see pjsua_acc_enum_info(). * - * @param ids Array of account IDs to be initialized. - * @param count In input, specifies the maximum number of elements. - * On return, it contains the actual number of elements. + * @param ids Array of account IDs to be initialized. + * @param count In input, specifies the maximum number of elements. + * On return, it contains the actual number of elements. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_enum_accs(pjsua_acc_id ids[], - unsigned *count ); + unsigned *count ); /** * Enumerate account informations. * - * @param info Array of account infos to be initialized. - * @param count In input, specifies the maximum number of elements. - * On return, it contains the actual number of elements. + * @param info Array of account infos to be initialized. + * @param count In input, specifies the maximum number of elements. + * On return, it contains the actual number of elements. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_acc_enum_info( pjsua_acc_info info[], - unsigned *count ); + unsigned *count ); /** * This is an internal function to find the most appropriate account to * used to reach to the specified URL. * - * @param url The remote URL to reach. + * @param url The remote URL to reach. * - * @return Account id. + * @return Account id. */ PJ_DECL(pjsua_acc_id) pjsua_acc_find_for_outgoing(const pj_str_t *url); @@ -4842,9 +4841,9 @@ PJ_DECL(pjsua_acc_id) pjsua_acc_find_for_outgoing(const pj_str_t *url); * This is an internal function to find the most appropriate account to be * used to handle incoming calls. * - * @param rdata The incoming request message. + * @param rdata The incoming request message. * - * @return Account id. + * @return Account id. */ PJ_DECL(pjsua_acc_id) pjsua_acc_find_for_incoming(pjsip_rx_data *rdata); @@ -4855,53 +4854,53 @@ PJ_DECL(pjsua_acc_id) pjsua_acc_find_for_incoming(pjsip_rx_data *rdata); * OPTIONS, and use the call or presence API to create dialog related * requests. * - * @param acc_id The account ID. - * @param method The SIP method of the request. - * @param target Target URI. - * @param p_tdata Pointer to receive the request. + * @param acc_id The account ID. + * @param method The SIP method of the request. + * @param target Target URI. + * @param p_tdata Pointer to receive the request. * - * @return PJ_SUCCESS or the error code. + * @return PJ_SUCCESS or the error code. */ PJ_DECL(pj_status_t) pjsua_acc_create_request(pjsua_acc_id acc_id, - const pjsip_method *method, - const pj_str_t *target, - pjsip_tx_data **p_tdata); + const pjsip_method *method, + const pj_str_t *target, + pjsip_tx_data **p_tdata); /** * Create a suitable Contact header value, based on the specified target URI * for the specified account. * - * @param pool Pool to allocate memory for the string. - * @param contact The string where the Contact will be stored. - * @param acc_id Account ID. - * @param uri Destination URI of the request. + * @param pool Pool to allocate memory for the string. + * @param contact The string where the Contact will be stored. + * @param acc_id Account ID. + * @param uri Destination URI of the request. * - * @return PJ_SUCCESS on success, other on error. + * @return PJ_SUCCESS on success, other on error. */ PJ_DECL(pj_status_t) pjsua_acc_create_uac_contact( pj_pool_t *pool, - pj_str_t *contact, - pjsua_acc_id acc_id, - const pj_str_t *uri); - + pj_str_t *contact, + pjsua_acc_id acc_id, + const pj_str_t *uri); + /** * Create a suitable Contact header value, based on the information in the * incoming request. * - * @param pool Pool to allocate memory for the string. - * @param contact The string where the Contact will be stored. - * @param acc_id Account ID. - * @param rdata Incoming request. + * @param pool Pool to allocate memory for the string. + * @param contact The string where the Contact will be stored. + * @param acc_id Account ID. + * @param rdata Incoming request. * - * @return PJ_SUCCESS on success, other on error. + * @return PJ_SUCCESS on success, other on error. */ PJ_DECL(pj_status_t) pjsua_acc_create_uas_contact( pj_pool_t *pool, - pj_str_t *contact, - pjsua_acc_id acc_id, - pjsip_rx_data *rdata ); - + pj_str_t *contact, + pjsua_acc_id acc_id, + pjsip_rx_data *rdata ); + /** * Lock/bind this account to a specific transport/listener. Normally @@ -4915,13 +4914,13 @@ PJ_DECL(pj_status_t) pjsua_acc_create_uas_contact( pj_pool_t *pool, * * Note that transport_id may be specified in pjsua_acc_config too. * - * @param acc_id The account ID. - * @param tp_id The transport ID. + * @param acc_id The account ID. + * @param tp_id The transport ID. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsua_acc_set_transport(pjsua_acc_id acc_id, - pjsua_transport_id tp_id); + pjsua_transport_id tp_id); /** @@ -4945,14 +4944,14 @@ PJ_DECL(pj_status_t) pjsua_acc_set_transport(pjsua_acc_id acc_id, * Maximum simultaneous calls. */ #ifndef PJSUA_MAX_CALLS -# define PJSUA_MAX_CALLS 4 +# define PJSUA_MAX_CALLS 4 #endif /** * Maximum active video windows */ #ifndef PJSUA_MAX_VID_WINS -# define PJSUA_MAX_VID_WINS 16 +# define PJSUA_MAX_VID_WINS 16 #endif @@ -4969,7 +4968,7 @@ PJ_DECL(pj_status_t) pjsua_acc_set_transport(pjsua_acc_id acc_id, * while re-INVITE needs to wait until the dialog is confirmed. */ #ifndef PJSUA_LOCK_CODEC_DONT_USE_UPDATE -# define PJSUA_LOCK_CODEC_DONT_USE_UPDATE 0 +# define PJSUA_LOCK_CODEC_DONT_USE_UPDATE 0 #endif @@ -5024,12 +5023,12 @@ typedef enum pjsua_vid_req_keyframe_method * Requesting keyframe via SIP INFO message. Note that incoming keyframe * request via SIP INFO will always be handled even if this flag is unset. */ - PJSUA_VID_REQ_KEYFRAME_SIP_INFO = 1, + PJSUA_VID_REQ_KEYFRAME_SIP_INFO = 1, /** * Requesting keyframe via Picture Loss Indication of RTCP feedback. */ - PJSUA_VID_REQ_KEYFRAME_RTCP_PLI = 2 + PJSUA_VID_REQ_KEYFRAME_RTCP_PLI = 2 } pjsua_vid_req_keyframe_method; @@ -5040,52 +5039,52 @@ typedef enum pjsua_vid_req_keyframe_method typedef struct pjsua_call_media_info { /** Media index in SDP. */ - unsigned index; + unsigned index; /** Media type. */ - pjmedia_type type; + pjmedia_type type; /** Media direction. */ - pjmedia_dir dir; + pjmedia_dir dir; /** Call media status. */ pjsua_call_media_status status; /** The specific media stream info. */ union { - /** Audio stream */ - struct { - /** The conference port number for the call. */ - pjsua_conf_port_id conf_slot; - } aud; - - /** Video stream */ - struct { - /** - * The window id for incoming video, if any, or - * PJSUA_INVALID_ID. - */ - pjsua_vid_win_id win_in; - - /** - * The video conference port number for the call in decoding - * direction. - */ - pjsua_conf_port_id dec_slot; - - /** - * The video conference port number for the call in encoding - * direction. - */ - pjsua_conf_port_id enc_slot; - - /** - * The video capture device for outgoing transmission, - * if any, or PJMEDIA_VID_INVALID_DEV - */ - pjmedia_vid_dev_index cap_dev; - - } vid; + /** Audio stream */ + struct { + /** The conference port number for the call. */ + pjsua_conf_port_id conf_slot; + } aud; + + /** Video stream */ + struct { + /** + * The window id for incoming video, if any, or + * PJSUA_INVALID_ID. + */ + pjsua_vid_win_id win_in; + + /** + * The video conference port number for the call in decoding + * direction. + */ + pjsua_conf_port_id dec_slot; + + /** + * The video conference port number for the call in encoding + * direction. + */ + pjsua_conf_port_id enc_slot; + + /** + * The video capture device for outgoing transmission, + * if any, or PJMEDIA_VID_INVALID_DEV + */ + pjmedia_vid_dev_index cap_dev; + + } vid; } stream; } pjsua_call_media_info; @@ -5097,43 +5096,43 @@ typedef struct pjsua_call_media_info typedef struct pjsua_call_info { /** Call identification. */ - pjsua_call_id id; + pjsua_call_id id; /** Initial call role (UAC == caller) */ - pjsip_role_e role; + pjsip_role_e role; /** The account ID where this call belongs. */ - pjsua_acc_id acc_id; + pjsua_acc_id acc_id; /** Local URI */ - pj_str_t local_info; + pj_str_t local_info; /** Local Contact */ - pj_str_t local_contact; + pj_str_t local_contact; /** Remote URI */ - pj_str_t remote_info; + pj_str_t remote_info; /** Remote contact */ - pj_str_t remote_contact; + pj_str_t remote_contact; /** Dialog Call-ID string. */ - pj_str_t call_id; + pj_str_t call_id; /** Call setting */ - pjsua_call_setting setting; + pjsua_call_setting setting; /** Call state */ - pjsip_inv_state state; + pjsip_inv_state state; /** Text describing the state */ - pj_str_t state_text; + pj_str_t state_text; /** Last status code heard, which can be used as cause code */ - pjsip_status_code last_status; + pjsip_status_code last_status; /** The reason phrase describing the status. */ - pj_str_t last_status_text; + pj_str_t last_status_text; /** Media status of the default audio stream. Default audio stream * is chosen according to this priority: @@ -5148,21 +5147,21 @@ typedef struct pjsua_call_info /** Media direction of the default audio stream. * See \a media_status above on how the default is chosen. */ - pjmedia_dir media_dir; + pjmedia_dir media_dir; /** The conference port number for the default audio stream. * See \a media_status above on how the default is chosen. */ - pjsua_conf_port_id conf_slot; + pjsua_conf_port_id conf_slot; /** Number of active media info in this call. */ - unsigned media_cnt; + unsigned media_cnt; /** Array of active media information. */ pjsua_call_media_info media[PJMEDIA_MAX_SDP_MEDIA]; /** Number of provisional media info in this call. */ - unsigned prov_media_cnt; + unsigned prov_media_cnt; /** Array of provisional media information. This contains the media info * in the provisioning state, that is when the media session is being @@ -5173,28 +5172,28 @@ typedef struct pjsua_call_info /** Up-to-date call connected duration (zero when call is not * established) */ - pj_time_val connect_duration; + pj_time_val connect_duration; /** Total call duration, including set-up time */ - pj_time_val total_duration; + pj_time_val total_duration; /** Flag if remote was SDP offerer */ - pj_bool_t rem_offerer; + pj_bool_t rem_offerer; /** Number of audio streams offered by remote */ - unsigned rem_aud_cnt; + unsigned rem_aud_cnt; /** Number of video streams offered by remote */ - unsigned rem_vid_cnt; + unsigned rem_vid_cnt; /** Internal */ struct { - char local_info[PJSIP_MAX_URL_SIZE]; - char local_contact[PJSIP_MAX_URL_SIZE]; - char remote_info[PJSIP_MAX_URL_SIZE]; - char remote_contact[PJSIP_MAX_URL_SIZE]; - char call_id[128]; - char last_status_text[128]; + char local_info[PJSIP_MAX_URL_SIZE]; + char local_contact[PJSIP_MAX_URL_SIZE]; + char remote_info[PJSIP_MAX_URL_SIZE]; + char remote_contact[PJSIP_MAX_URL_SIZE]; + char call_id[128]; + char last_status_text[128]; } buf_; } pjsua_call_info; @@ -5434,7 +5433,7 @@ typedef struct pjsua_call_send_dtmf_param /** * Initialize call settings. * - * @param opt The call setting to be initialized. + * @param opt The call setting to be initialized. */ PJ_DECL(void) pjsua_call_setting_default(pjsua_call_setting *opt); @@ -5442,7 +5441,7 @@ PJ_DECL(void) pjsua_call_setting_default(pjsua_call_setting *opt); /** * Initialize video stream operation param with default values. * - * @param param The video stream operation param to be initialized. + * @param param The video stream operation param to be initialized. */ PJ_DECL(void) pjsua_call_vid_strm_op_param_default(pjsua_call_vid_strm_op_param *param); @@ -5451,7 +5450,7 @@ pjsua_call_vid_strm_op_param_default(pjsua_call_vid_strm_op_param *param); /** * Initialize send DTMF param with default values. * - * @param param The send DTMF param to be initialized. + * @param param The send DTMF param to be initialized. */ PJ_DECL(void) pjsua_call_send_dtmf_param_default(pjsua_call_send_dtmf_param *param); @@ -5460,7 +5459,7 @@ pjsua_call_send_dtmf_param_default(pjsua_call_send_dtmf_param *param); /** * Get maximum number of calls configured in pjsua. * - * @return Maximum number of calls configured. + * @return Maximum number of calls configured. */ PJ_DECL(unsigned) pjsua_call_get_max_count(void); @@ -5469,7 +5468,7 @@ PJ_DECL(unsigned) pjsua_call_get_max_count(void); * (pjsua_call_is_active(call_id) == PJ_TRUE), as well as calls that * are no longer active but still in the process of hanging up. * - * @return Number of current calls. + * @return Number of current calls. */ PJ_DECL(unsigned) pjsua_call_get_count(void); @@ -5477,47 +5476,47 @@ PJ_DECL(unsigned) pjsua_call_get_count(void); * Enumerate all active calls. Application may then query the information and * state of each call by calling #pjsua_call_get_info(). * - * @param ids Array of account IDs to be initialized. - * @param count In input, specifies the maximum number of elements. - * On return, it contains the actual number of elements. + * @param ids Array of account IDs to be initialized. + * @param count In input, specifies the maximum number of elements. + * On return, it contains the actual number of elements. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_enum_calls(pjsua_call_id ids[], - unsigned *count); + unsigned *count); /** * Make outgoing call to the specified URI using the specified account. * - * @param acc_id The account to be used. - * @param dst_uri URI to be put in the To header (normally is the same - * as the target URI). - * @param opt Optional call setting. This should be initialized - * using #pjsua_call_setting_default(). - * @param user_data Arbitrary user data to be attached to the call, and - * can be retrieved later. - * @param msg_data Optional headers etc to be added to outgoing INVITE - * request, or NULL if no custom header is desired. - * @param p_call_id Pointer to receive call identification. + * @param acc_id The account to be used. + * @param dst_uri URI to be put in the To header (normally is the same + * as the target URI). + * @param opt Optional call setting. This should be initialized + * using #pjsua_call_setting_default(). + * @param user_data Arbitrary user data to be attached to the call, and + * can be retrieved later. + * @param msg_data Optional headers etc to be added to outgoing INVITE + * request, or NULL if no custom header is desired. + * @param p_call_id Pointer to receive call identification. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_make_call(pjsua_acc_id acc_id, - const pj_str_t *dst_uri, - const pjsua_call_setting *opt, - void *user_data, - const pjsua_msg_data *msg_data, - pjsua_call_id *p_call_id); + const pj_str_t *dst_uri, + const pjsua_call_setting *opt, + void *user_data, + const pjsua_msg_data *msg_data, + pjsua_call_id *p_call_id); /** * Check if the specified call has active INVITE session and the INVITE * session has not been disconnected. * - * @param call_id Call identification. + * @param call_id Call identification. * - * @return Non-zero if call is active. + * @return Non-zero if call is active. */ PJ_DECL(pj_bool_t) pjsua_call_is_active(pjsua_call_id call_id); @@ -5525,9 +5524,9 @@ PJ_DECL(pj_bool_t) pjsua_call_is_active(pjsua_call_id call_id); /** * Check if call has an active media session. * - * @param call_id Call identification. + * @param call_id Call identification. * - * @return Non-zero if yes. + * @return Non-zero if yes. */ PJ_DECL(pj_bool_t) pjsua_call_has_media(pjsua_call_id call_id); @@ -5535,10 +5534,10 @@ PJ_DECL(pj_bool_t) pjsua_call_has_media(pjsua_call_id call_id); /** * Get the conference port identification associated with the call. * - * @param call_id Call identification. + * @param call_id Call identification. * - * @return Conference port ID, or PJSUA_INVALID_ID when the - * media has not been established or is not active. + * @return Conference port ID, or PJSUA_INVALID_ID when the + * media has not been established or is not active. */ PJ_DECL(pjsua_conf_port_id) pjsua_call_get_conf_port(pjsua_call_id call_id); @@ -5548,10 +5547,10 @@ PJ_DECL(pjsua_conf_port_id) pjsua_call_get_conf_port(pjsua_call_id call_id); * will only evaluate the first video stream in the call, to query any other * video stream, use pjsua_call_get_info(). * - * @param call_id Call identification. + * @param call_id Call identification. * - * @return Video window, or PJSUA_INVALID_ID when the - * media has not been established or is not active. + * @return Video window, or PJSUA_INVALID_ID when the + * media has not been established or is not active. */ PJ_DECL(pjsua_vid_win_id) pjsua_call_get_vid_win(pjsua_call_id call_id); @@ -5561,75 +5560,75 @@ PJ_DECL(pjsua_vid_win_id) pjsua_call_get_vid_win(pjsua_call_id call_id); * Note that this function will only evaluate the first video stream in * the call, to query any other video stream, use pjsua_call_get_info(). * - * @param call_id Call identification. - * @param dir Port direction to be queried. Valid values are - * PJMEDIA_DIR_ENCODING and PJMEDIA_DIR_DECODING only. + * @param call_id Call identification. + * @param dir Port direction to be queried. Valid values are + * PJMEDIA_DIR_ENCODING and PJMEDIA_DIR_DECODING only. * - * @return Conference port ID, or PJSUA_INVALID_ID when the - * media has not been established or is not active. + * @return Conference port ID, or PJSUA_INVALID_ID when the + * media has not been established or is not active. */ PJ_DECL(pjsua_conf_port_id) pjsua_call_get_vid_conf_port( - pjsua_call_id call_id, - pjmedia_dir dir); + pjsua_call_id call_id, + pjmedia_dir dir); /** * Obtain detail information about the specified call. * - * @param call_id Call identification. - * @param info Call info to be initialized. + * @param call_id Call identification. + * @param info Call info to be initialized. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_get_info(pjsua_call_id call_id, - pjsua_call_info *info); + pjsua_call_info *info); /** * Check if remote peer support the specified capability. * - * @param call_id Call identification. - * @param htype The header type to be checked, which value may be: - * - PJSIP_H_ACCEPT - * - PJSIP_H_ALLOW - * - PJSIP_H_SUPPORTED - * @param hname If htype specifies PJSIP_H_OTHER, then the header - * name must be supplied in this argument. Otherwise the - * value must be set to NULL. - * @param token The capability token to check. For example, if \a - * htype is PJSIP_H_ALLOW, then \a token specifies the - * method names; if \a htype is PJSIP_H_SUPPORTED, then - * \a token specifies the extension names such as - * "100rel". - * - * @return PJSIP_DIALOG_CAP_SUPPORTED if the specified capability - * is explicitly supported, see pjsip_dialog_cap_status - * for more info. + * @param call_id Call identification. + * @param htype The header type to be checked, which value may be: + * - PJSIP_H_ACCEPT + * - PJSIP_H_ALLOW + * - PJSIP_H_SUPPORTED + * @param hname If htype specifies PJSIP_H_OTHER, then the header + * name must be supplied in this argument. Otherwise the + * value must be set to NULL. + * @param token The capability token to check. For example, if \a + * htype is PJSIP_H_ALLOW, then \a token specifies the + * method names; if \a htype is PJSIP_H_SUPPORTED, then + * \a token specifies the extension names such as + * "100rel". + * + * @return PJSIP_DIALOG_CAP_SUPPORTED if the specified capability + * is explicitly supported, see pjsip_dialog_cap_status + * for more info. */ PJ_DECL(pjsip_dialog_cap_status) pjsua_call_remote_has_cap( - pjsua_call_id call_id, - int htype, - const pj_str_t *hname, - const pj_str_t *token); + pjsua_call_id call_id, + int htype, + const pj_str_t *hname, + const pj_str_t *token); /** * Attach application specific data to the call. Application can then * inspect this data by calling #pjsua_call_get_user_data(). * - * @param call_id Call identification. - * @param user_data Arbitrary data to be attached to the call. + * @param call_id Call identification. + * @param user_data Arbitrary data to be attached to the call. * - * @return The user data. + * @return The user data. */ PJ_DECL(pj_status_t) pjsua_call_set_user_data(pjsua_call_id call_id, - void *user_data); + void *user_data); /** * Get user data attached to the call, which has been previously set with * #pjsua_call_set_user_data(). * - * @param call_id Call identification. + * @param call_id Call identification. * - * @return The user data. + * @return The user data. */ PJ_DECL(void*) pjsua_call_get_user_data(pjsua_call_id call_id); @@ -5646,17 +5645,17 @@ PJ_DECL(void*) pjsua_call_get_user_data(pjsua_call_id call_id); * 200/OK response to INVITE). As a general case, application should call * this function after or in \a on_call_media_state() callback. * - * @param call_id Call identification. - * @param p_type Pointer to store the NAT type. Application can then - * retrieve the string description of the NAT type - * by calling pj_stun_get_nat_name(). + * @param call_id Call identification. + * @param p_type Pointer to store the NAT type. Application can then + * retrieve the string description of the NAT type + * by calling pj_stun_get_nat_name(). * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. * * @see pjsua_get_nat_type(), nat_type_in_sdp */ PJ_DECL(pj_status_t) pjsua_call_get_rem_nat_type(pjsua_call_id call_id, - pj_stun_nat_type *p_type); + pj_stun_nat_type *p_type); /** * Send response to incoming INVITE request. Depending on the status @@ -5664,21 +5663,21 @@ PJ_DECL(pj_status_t) pjsua_call_get_rem_nat_type(pjsua_call_id call_id, * response, establish the call, or terminate the call. See also * #pjsua_call_answer2(). * - * @param call_id Incoming call identification. - * @param code Status code, (100-699). - * @param reason Optional reason phrase. If NULL, default text - * will be used. - * @param msg_data Optional list of headers etc to be added to outgoing - * response message. Note that this message data will - * be persistent in all next answers/responses for this - * INVITE request. + * @param call_id Incoming call identification. + * @param code Status code, (100-699). + * @param reason Optional reason phrase. If NULL, default text + * will be used. + * @param msg_data Optional list of headers etc to be added to outgoing + * response message. Note that this message data will + * be persistent in all next answers/responses for this + * INVITE request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_answer(pjsua_call_id call_id, - unsigned code, - const pj_str_t *reason, - const pjsua_msg_data *msg_data); + unsigned code, + const pj_str_t *reason, + const pjsua_msg_data *msg_data); /** @@ -5694,49 +5693,49 @@ PJ_DECL(pj_status_t) pjsua_call_answer(pjsua_call_id call_id, * with status code 183 or 2xx, the default call setting will be used, * check #pjsua_call_setting for its default values. * - * @param call_id Incoming call identification. - * @param opt Optional call setting. - * @param code Status code, (100-699). - * @param reason Optional reason phrase. If NULL, default text - * will be used. - * @param msg_data Optional list of headers etc to be added to outgoing - * response message. Note that this message data will - * be persistent in all next answers/responses for this - * INVITE request. + * @param call_id Incoming call identification. + * @param opt Optional call setting. + * @param code Status code, (100-699). + * @param reason Optional reason phrase. If NULL, default text + * will be used. + * @param msg_data Optional list of headers etc to be added to outgoing + * response message. Note that this message data will + * be persistent in all next answers/responses for this + * INVITE request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_answer2(pjsua_call_id call_id, - const pjsua_call_setting *opt, - unsigned code, - const pj_str_t *reason, - const pjsua_msg_data *msg_data); + const pjsua_call_setting *opt, + unsigned code, + const pj_str_t *reason, + const pjsua_msg_data *msg_data); /** * Same as #pjsua_call_answer2() but this function will set the SDP * answer first before sending the response. * - * @param call_id Incoming call identification. - * @param sdp SDP answer. - * @param opt Optional call setting. - * @param code Status code, (100-699). - * @param reason Optional reason phrase. If NULL, default text - * will be used. - * @param msg_data Optional list of headers etc to be added to outgoing - * response message. Note that this message data will - * be persistent in all next answers/responses for this - * INVITE request. + * @param call_id Incoming call identification. + * @param sdp SDP answer. + * @param opt Optional call setting. + * @param code Status code, (100-699). + * @param reason Optional reason phrase. If NULL, default text + * will be used. + * @param msg_data Optional list of headers etc to be added to outgoing + * response message. Note that this message data will + * be persistent in all next answers/responses for this + * INVITE request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_answer_with_sdp(pjsua_call_id call_id, - const pjmedia_sdp_session *sdp, - const pjsua_call_setting *opt, - unsigned code, - const pj_str_t *reason, - const pjsua_msg_data *msg_data); + const pjmedia_sdp_session *sdp, + const pjsua_call_setting *opt, + unsigned code, + const pj_str_t *reason, + const pjsua_msg_data *msg_data); /** @@ -5760,21 +5759,21 @@ pjsua_call_answer_with_sdp(pjsua_call_id call_id, * * Note that on_call_tsx_state() will not be called when using this API. * - * @param call_id Call identification. - * @param code Optional status code to be sent when we're rejecting - * incoming call. If the value is zero, "603/Decline" - * will be sent. - * @param reason Optional reason phrase to be sent when we're rejecting - * incoming call. If NULL, default text will be used. - * @param msg_data Optional list of headers etc to be added to outgoing - * request/response message. + * @param call_id Call identification. + * @param code Optional status code to be sent when we're rejecting + * incoming call. If the value is zero, "603/Decline" + * will be sent. + * @param reason Optional reason phrase to be sent when we're rejecting + * incoming call. If NULL, default text will be used. + * @param msg_data Optional list of headers etc to be added to outgoing + * request/response message. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_hangup(pjsua_call_id call_id, - unsigned code, - const pj_str_t *reason, - const pjsua_msg_data *msg_data); + unsigned code, + const pj_str_t *reason, + const pjsua_msg_data *msg_data); /** * Accept or reject redirection response. Application MUST call this function @@ -5791,17 +5790,17 @@ PJ_DECL(pj_status_t) pjsua_call_hangup(pjsua_call_id call_id, * callback may also be called before this function returns if there is * another target to try. * - * @param call_id The call ID. - * @param cmd Redirection operation to be applied to the current - * target. The semantic of this argument is similar - * to the description in the \a on_call_redirected() - * callback, except that the PJSIP_REDIRECT_PENDING is - * not accepted here. + * @param call_id The call ID. + * @param cmd Redirection operation to be applied to the current + * target. The semantic of this argument is similar + * to the description in the \a on_call_redirected() + * callback, except that the PJSIP_REDIRECT_PENDING is + * not accepted here. * - * @return PJ_SUCCESS on successful operation. + * @return PJ_SUCCESS on successful operation. */ PJ_DECL(pj_status_t) pjsua_call_process_redirect(pjsua_call_id call_id, - pjsip_redirect_op cmd); + pjsip_redirect_op cmd); /** * Put the specified call on hold. This will send re-INVITE with the @@ -5810,14 +5809,14 @@ PJ_DECL(pj_status_t) pjsua_call_process_redirect(pjsua_call_id call_id, * \a on_call_media_state() callback, which inform the application that * the media state of the call has changed. * - * @param call_id Call identification. - * @param msg_data Optional message components to be sent with - * the request. + * @param call_id Call identification. + * @param msg_data Optional message components to be sent with + * the request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_set_hold(pjsua_call_id call_id, - const pjsua_msg_data *msg_data); + const pjsua_msg_data *msg_data); /** * Put the specified call on hold. This will send re-INVITE with the @@ -5826,17 +5825,17 @@ PJ_DECL(pj_status_t) pjsua_call_set_hold(pjsua_call_id call_id, * \a on_call_media_state() callback, which inform the application that * the media state of the call has changed. * - * @param call_id Call identification. - * @param options Bitmask of pjsua_call_flag constants. Currently, only + * @param call_id Call identification. + * @param options Bitmask of pjsua_call_flag constants. Currently, only * the flag PJSUA_CALL_UPDATE_CONTACT can be used. - * @param msg_data Optional message components to be sent with - * the request. + * @param msg_data Optional message components to be sent with + * the request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_set_hold2(pjsua_call_id call_id, unsigned options, - const pjsua_msg_data *msg_data); + const pjsua_msg_data *msg_data); /** * Send re-INVITE request or release hold. @@ -5844,18 +5843,18 @@ PJ_DECL(pj_status_t) pjsua_call_set_hold2(pjsua_call_id call_id, * \a on_call_media_state() callback, which inform the application that * the media state of the call has changed. * - * @param call_id Call identification. - * @param options Bitmask of pjsua_call_flag constants. Note that - * for compatibility, specifying PJ_TRUE here is - * equal to specifying PJSUA_CALL_UNHOLD flag. - * @param msg_data Optional message components to be sent with - * the request. + * @param call_id Call identification. + * @param options Bitmask of pjsua_call_flag constants. Note that + * for compatibility, specifying PJ_TRUE here is + * equal to specifying PJSUA_CALL_UNHOLD flag. + * @param msg_data Optional message components to be sent with + * the request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_reinvite(pjsua_call_id call_id, - unsigned options, - const pjsua_msg_data *msg_data); + unsigned options, + const pjsua_msg_data *msg_data); /** @@ -5864,56 +5863,56 @@ PJ_DECL(pj_status_t) pjsua_call_reinvite(pjsua_call_id call_id, * \a on_call_media_state() callback, which inform the application that * the media state of the call has changed. * - * @param call_id Call identification. - * @param opt Optional call setting, if NULL, the current call - * setting will be used. Note that to release hold - * or update contact or omit SDP offer, this parameter - * cannot be NULL and it must specify appropriate flags, - * e.g: PJSUA_CALL_UNHOLD, PJSUA_CALL_UPDATE_CONTACT, - * PJSUA_CALL_NO_SDP_OFFER. - * @param msg_data Optional message components to be sent with - * the request. + * @param call_id Call identification. + * @param opt Optional call setting, if NULL, the current call + * setting will be used. Note that to release hold + * or update contact or omit SDP offer, this parameter + * cannot be NULL and it must specify appropriate flags, + * e.g: PJSUA_CALL_UNHOLD, PJSUA_CALL_UPDATE_CONTACT, + * PJSUA_CALL_NO_SDP_OFFER. + * @param msg_data Optional message components to be sent with + * the request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_reinvite2(pjsua_call_id call_id, - const pjsua_call_setting *opt, - const pjsua_msg_data *msg_data); + const pjsua_call_setting *opt, + const pjsua_msg_data *msg_data); /** * Send UPDATE request. * - * @param call_id Call identification. - * @param options Bitmask of pjsua_call_flag constants. - * @param msg_data Optional message components to be sent with - * the request. + * @param call_id Call identification. + * @param options Bitmask of pjsua_call_flag constants. + * @param msg_data Optional message components to be sent with + * the request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_update(pjsua_call_id call_id, - unsigned options, - const pjsua_msg_data *msg_data); + unsigned options, + const pjsua_msg_data *msg_data); /** * Send UPDATE request. * - * @param call_id Call identification. - * @param opt Optional call setting, if NULL, the current call - * setting will be used. Note that to release hold - * or update contact or omit SDP offer, this parameter - * cannot be NULL and it must specify appropriate flags, - * e.g: PJSUA_CALL_UNHOLD, PJSUA_CALL_UPDATE_CONTACT, - * PJSUA_CALL_NO_SDP_OFFER. - * @param msg_data Optional message components to be sent with - * the request. + * @param call_id Call identification. + * @param opt Optional call setting, if NULL, the current call + * setting will be used. Note that to release hold + * or update contact or omit SDP offer, this parameter + * cannot be NULL and it must specify appropriate flags, + * e.g: PJSUA_CALL_UNHOLD, PJSUA_CALL_UPDATE_CONTACT, + * PJSUA_CALL_NO_SDP_OFFER. + * @param msg_data Optional message components to be sent with + * the request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_update2(pjsua_call_id call_id, - const pjsua_call_setting *opt, - const pjsua_msg_data *msg_data); + const pjsua_call_setting *opt, + const pjsua_msg_data *msg_data); /** @@ -5926,24 +5925,24 @@ PJ_DECL(pj_status_t) pjsua_call_update2(pjsua_call_id call_id, * \a on_call_transfer_status() callback which will report the progress * of the call transfer request. * - * @param call_id The call id to be transferred. - * @param dest URI of new target to be contacted. The URI may be - * in name address or addr-spec format. - * @param msg_data Optional message components to be sent with - * the request. + * @param call_id The call id to be transferred. + * @param dest URI of new target to be contacted. The URI may be + * in name address or addr-spec format. + * @param msg_data Optional message components to be sent with + * the request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_xfer(pjsua_call_id call_id, - const pj_str_t *dest, - const pjsua_msg_data *msg_data); + const pj_str_t *dest, + const pjsua_msg_data *msg_data); /** * Flag to indicate that "Require: replaces" should not be put in the * outgoing INVITE request caused by REFER request created by * #pjsua_call_xfer_replaces(). */ -#define PJSUA_XFER_NO_REQUIRE_REPLACES 1 +#define PJSUA_XFER_NO_REQUIRE_REPLACES 1 /** * Initiate attended call transfer. This function will send REFER request @@ -5951,21 +5950,21 @@ PJ_DECL(pj_status_t) pjsua_call_xfer(pjsua_call_id call_id, * of \a dest_call_id. The party at \a dest_call_id then should "replace" * the call with us with the new call from the REFER recipient. * - * @param call_id The call id to be transferred. - * @param dest_call_id The call id to be replaced. - * @param options Application may specify PJSUA_XFER_NO_REQUIRE_REPLACES - * to suppress the inclusion of "Require: replaces" in - * the outgoing INVITE request created by the REFER - * request. - * @param msg_data Optional message components to be sent with - * the request. + * @param call_id The call id to be transferred. + * @param dest_call_id The call id to be replaced. + * @param options Application may specify PJSUA_XFER_NO_REQUIRE_REPLACES + * to suppress the inclusion of "Require: replaces" in + * the outgoing INVITE request created by the REFER + * request. + * @param msg_data Optional message components to be sent with + * the request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_xfer_replaces(pjsua_call_id call_id, - pjsua_call_id dest_call_id, - unsigned options, - const pjsua_msg_data *msg_data); + pjsua_call_id dest_call_id, + unsigned options, + const pjsua_msg_data *msg_data); /** * Send DTMF digits to remote using RFC 2833 payload formats. Use @@ -5973,16 +5972,16 @@ PJ_DECL(pj_status_t) pjsua_call_xfer_replaces(pjsua_call_id call_id, * \a pjsua_dtmf_method. App can use \a on_dtmf_digit() or \a on_dtmf_digit2() * callback to monitor incoming DTMF. * - * @param call_id Call identification. - * @param digits DTMF string digits to be sent as described on RFC 2833 - * section 3.10. If PJMEDIA_HAS_DTMF_FLASH is enabled, - * character 'R' is used to represent the - * event type 16 (flash) as stated in RFC 4730. + * @param call_id Call identification. + * @param digits DTMF string digits to be sent as described on RFC 2833 + * section 3.10. If PJMEDIA_HAS_DTMF_FLASH is enabled, + * character 'R' is used to represent the + * event type 16 (flash) as stated in RFC 4730. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_dial_dtmf(pjsua_call_id call_id, - const pj_str_t *digits); + const pj_str_t *digits); /** * Send DTMF digits to remote. Use this method to send DTMF using the method in @@ -5993,51 +5992,51 @@ PJ_DECL(pj_status_t) pjsua_call_dial_dtmf(pjsua_call_id call_id, * \a pjsua_dtmf_method. Note that \a on_dtmf_digit() will not be called once * \a on_dtmf_digit2() is implemented. * - * @param call_id Call identification. - * @param param The send DTMF parameter. + * @param call_id Call identification. + * @param param The send DTMF parameter. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_send_dtmf(pjsua_call_id call_id, - const pjsua_call_send_dtmf_param *param); + const pjsua_call_send_dtmf_param *param); /** * Send instant messaging inside INVITE session. * - * @param call_id Call identification. - * @param mime_type Optional MIME type. If NULL, then "text/plain" is - * assumed. - * @param content The message content. Can be NULL if msg_data specifies - * body and/or multipart. - * @param msg_data Optional list of headers etc to be included in outgoing - * request. The body descriptor in the msg_data is - * ignored if parameter 'content' is set. - * @param user_data Optional user data, which will be given back when - * the IM callback is called. + * @param call_id Call identification. + * @param mime_type Optional MIME type. If NULL, then "text/plain" is + * assumed. + * @param content The message content. Can be NULL if msg_data specifies + * body and/or multipart. + * @param msg_data Optional list of headers etc to be included in outgoing + * request. The body descriptor in the msg_data is + * ignored if parameter 'content' is set. + * @param user_data Optional user data, which will be given back when + * the IM callback is called. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_send_im( pjsua_call_id call_id, - const pj_str_t *mime_type, - const pj_str_t *content, - const pjsua_msg_data *msg_data, - void *user_data); + const pj_str_t *mime_type, + const pj_str_t *content, + const pjsua_msg_data *msg_data, + void *user_data); /** * Send IM typing indication inside INVITE session. * - * @param call_id Call identification. - * @param is_typing Non-zero to indicate to remote that local person is - * currently typing an IM. - * @param msg_data Optional list of headers etc to be included in outgoing - * request. + * @param call_id Call identification. + * @param is_typing Non-zero to indicate to remote that local person is + * currently typing an IM. + * @param msg_data Optional list of headers etc to be included in outgoing + * request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_send_typing_ind(pjsua_call_id call_id, - pj_bool_t is_typing, - const pjsua_msg_data*msg_data); + pj_bool_t is_typing, + const pjsua_msg_data*msg_data); /** * Send arbitrary request with the call. This is useful for example to send @@ -6045,16 +6044,16 @@ PJ_DECL(pj_status_t) pjsua_call_send_typing_ind(pjsua_call_id call_id, * requests which would change the invite session's state, such as re-INVITE, * UPDATE, PRACK, and BYE. * - * @param call_id Call identification. - * @param method SIP method of the request. - * @param msg_data Optional message body and/or list of headers to be - * included in outgoing request. + * @param call_id Call identification. + * @param method SIP method of the request. + * @param msg_data Optional message body and/or list of headers to be + * included in outgoing request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_call_send_request(pjsua_call_id call_id, - const pj_str_t *method, - const pjsua_msg_data *msg_data); + const pj_str_t *method, + const pjsua_msg_data *msg_data); /** @@ -6067,19 +6066,19 @@ PJ_DECL(void) pjsua_call_hangup_all(void); /** * Dump call and media statistics to string. * - * @param call_id Call identification. - * @param with_media Non-zero to include media information too. - * @param buffer Buffer where the statistics are to be written to. - * @param maxlen Maximum length of buffer. - * @param indent Spaces for left indentation. + * @param call_id Call identification. + * @param with_media Non-zero to include media information too. + * @param buffer Buffer where the statistics are to be written to. + * @param maxlen Maximum length of buffer. + * @param indent Spaces for left indentation. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsua_call_dump(pjsua_call_id call_id, - pj_bool_t with_media, - char *buffer, - unsigned maxlen, - const char *indent); + pj_bool_t with_media, + char *buffer, + unsigned maxlen, + const char *indent); /** * Get the media stream index of the default video stream in the call. @@ -6087,10 +6086,10 @@ PJ_DECL(pj_status_t) pjsua_call_dump(pjsua_call_id call_id, * activated video stream in the call. If none is active, it will return * the first inactive video stream. * - * @param call_id Call identification. + * @param call_id Call identification. * - * @return The media stream index or -1 if no video stream - * is present in the call. + * @return The media stream index or -1 if no video stream + * is present in the call. */ PJ_DECL(int) pjsua_call_get_vid_stream_idx(pjsua_call_id call_id); @@ -6100,13 +6099,13 @@ PJ_DECL(int) pjsua_call_get_vid_stream_idx(pjsua_call_id call_id); * (i.e. has been created, started, and not being paused) for the specified * direction. * - * @param call_id Call identification. - * @param med_idx Media stream index, or -1 to specify default video - * media. - * @param dir The direction to be checked. + * @param call_id Call identification. + * @param med_idx Media stream index, or -1 to specify default video + * media. + * @param dir The direction to be checked. * - * @return PJ_TRUE if stream is currently running for the - * specified direction. + * @return PJ_TRUE if stream is currently running for the + * specified direction. */ PJ_DECL(pj_bool_t) pjsua_call_vid_stream_is_running(pjsua_call_id call_id, int med_idx, @@ -6117,19 +6116,19 @@ PJ_DECL(pj_bool_t) pjsua_call_vid_stream_is_running(pjsua_call_id call_id, * specified call. This may trigger a re-INVITE or UPDATE to be sent * for the call. * - * @param call_id Call identification. - * @param op The video stream operation to be performed, - * possible values are #pjsua_call_vid_strm_op. - * @param param The parameters for the video stream operation, - * or NULL for the default parameter values - * (see #pjsua_call_vid_strm_op_param). + * @param call_id Call identification. + * @param op The video stream operation to be performed, + * possible values are #pjsua_call_vid_strm_op. + * @param param The parameters for the video stream operation, + * or NULL for the default parameter values + * (see #pjsua_call_vid_strm_op_param). * - * @return PJ_SUCCESS on success or the appropriate error. + * @return PJ_SUCCESS on success or the appropriate error. */ PJ_DECL(pj_status_t) pjsua_call_set_vid_strm ( - pjsua_call_id call_id, - pjsua_call_vid_strm_op op, - const pjsua_call_vid_strm_op_param *param); + pjsua_call_id call_id, + pjsua_call_vid_strm_op op, + const pjsua_call_vid_strm_op_param *param); /** * Modify the audio stream's codec parameter after the codec is opened. @@ -6138,26 +6137,26 @@ PJ_DECL(pj_status_t) pjsua_call_set_vid_strm ( * such as bitrate and bandwidth, while other codecs may only be able to * modify minor settings such as VAD or PLC. * - * @param call_id Call identification. - * @param med_idx Media stream index, or -1 to specify default audio - * media. - * @param param The new codec parameter. + * @param call_id Call identification. + * @param med_idx Media stream index, or -1 to specify default audio + * media. + * @param param The new codec parameter. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsua_call_aud_stream_modify_codec_param(pjsua_call_id call_id, int med_idx, - const pjmedia_codec_param *param); + const pjmedia_codec_param *param); /** * Get media stream info for the specified media index. * - * @param call_id The call identification. - * @param med_idx Media stream index. - * @param psi To be filled with the stream info. + * @param call_id The call identification. + * @param med_idx Media stream index. + * @param psi To be filled with the stream info. * - * @return PJ_SUCCESS on success or the appropriate error. + * @return PJ_SUCCESS on success or the appropriate error. */ PJ_DECL(pj_status_t) pjsua_call_get_stream_info(pjsua_call_id call_id, unsigned med_idx, @@ -6166,11 +6165,11 @@ PJ_DECL(pj_status_t) pjsua_call_get_stream_info(pjsua_call_id call_id, /** * Get media stream statistic for the specified media index. * - * @param call_id The call identification. - * @param med_idx Media stream index. - * @param stat To be filled with the stream statistic. + * @param call_id The call identification. + * @param med_idx Media stream index. + * @param stat To be filled with the stream statistic. * - * @return PJ_SUCCESS on success or the appropriate error. + * @return PJ_SUCCESS on success or the appropriate error. */ PJ_DECL(pj_status_t) pjsua_call_get_stream_stat(pjsua_call_id call_id, unsigned med_idx, @@ -6179,11 +6178,11 @@ PJ_DECL(pj_status_t) pjsua_call_get_stream_stat(pjsua_call_id call_id, /** * Get media transport info for the specified media index. * - * @param call_id The call identification. - * @param med_idx Media stream index. - * @param t To be filled with the transport info. + * @param call_id The call identification. + * @param med_idx Media stream index. + * @param t To be filled with the transport info. * - * @return PJ_SUCCESS on success or the appropriate error. + * @return PJ_SUCCESS on success or the appropriate error. */ PJ_DECL(pj_status_t) pjsua_call_get_med_transport_info(pjsua_call_id call_id, @@ -6216,7 +6215,7 @@ pjsua_call_get_med_transport_info(pjsua_call_id call_id, * Max buddies in buddy list. */ #ifndef PJSUA_MAX_BUDDIES -# define PJSUA_MAX_BUDDIES 256 +# define PJSUA_MAX_BUDDIES 256 #endif @@ -6231,7 +6230,7 @@ pjsua_call_get_med_transport_info(pjsua_call_id call_id, * Default: 300 seconds */ #ifndef PJSUA_PRES_TIMER -# define PJSUA_PRES_TIMER 300 +# define PJSUA_PRES_TIMER 300 #endif @@ -6246,12 +6245,12 @@ typedef struct pjsua_buddy_config /** * Buddy URL or name address. */ - pj_str_t uri; + pj_str_t uri; /** * Specify whether presence subscription should start immediately. */ - pj_bool_t subscribe; + pj_bool_t subscribe; /** * Specify arbitrary application data to be associated with with @@ -6296,34 +6295,34 @@ typedef struct pjsua_buddy_info /** * The buddy ID. */ - pjsua_buddy_id id; + pjsua_buddy_id id; /** * The full URI of the buddy, as specified in the configuration. */ - pj_str_t uri; + pj_str_t uri; /** * Buddy's Contact, only available when presence subscription has * been established to the buddy. */ - pj_str_t contact; + pj_str_t contact; /** * Buddy's online status. */ - pjsua_buddy_status status; + pjsua_buddy_status status; /** * Text to describe buddy's online status. */ - pj_str_t status_text; + pj_str_t status_text; /** * Flag to indicate that we should monitor the presence information for * this buddy (normally yes, unless explicitly disabled). */ - pj_bool_t monitor_pres; + pj_bool_t monitor_pres; /** * If \a monitor_pres is enabled, this specifies the last state of the @@ -6333,12 +6332,12 @@ typedef struct pjsua_buddy_info * PJSIP_EVSUB_STATE_TERMINATED, and the termination reason will be * specified in \a sub_term_reason. */ - pjsip_evsub_state sub_state; + pjsip_evsub_state sub_state; /** * String representation of subscription state. */ - const char *sub_state_name; + const char *sub_state_name; /** * Specifies the last presence subscription termination code. This would @@ -6347,28 +6346,28 @@ typedef struct pjsua_buddy_info * 200, and subscription termination reason will be given in the * \a sub_term_reason field. */ - unsigned sub_term_code; + unsigned sub_term_code; /** * Specifies the last presence subscription termination reason. If * presence subscription is currently active, the value will be empty. */ - pj_str_t sub_term_reason; + pj_str_t sub_term_reason; /** * Extended RPID information about the person. */ - pjrpid_element rpid; + pjrpid_element rpid; /** * Extended presence info. */ - pjsip_pres_status pres_status; + pjsip_pres_status pres_status; /** * Internal buffer. */ - char buf_[512]; + char buf_[512]; } pjsua_buddy_info; @@ -6382,7 +6381,7 @@ PJ_DECL(void) pjsua_buddy_config_default(pjsua_buddy_config *cfg); /** * Get total number of buddies. * - * @return Number of buddies. + * @return Number of buddies. */ PJ_DECL(unsigned) pjsua_get_buddy_count(void); @@ -6390,9 +6389,9 @@ PJ_DECL(unsigned) pjsua_get_buddy_count(void); /** * Check if buddy ID is valid. * - * @param buddy_id Buddy ID to check. + * @param buddy_id Buddy ID to check. * - * @return Non-zero if buddy ID is valid. + * @return Non-zero if buddy ID is valid. */ PJ_DECL(pj_bool_t) pjsua_buddy_is_valid(pjsua_buddy_id buddy_id); @@ -6402,22 +6401,22 @@ PJ_DECL(pj_bool_t) pjsua_buddy_is_valid(pjsua_buddy_id buddy_id); * #pjsua_buddy_get_info() to get the detail information for each buddy * id. * - * @param ids Array of ids to be initialized. - * @param count On input, specifies max elements in the array. - * On return, it contains actual number of elements - * that have been initialized. + * @param ids Array of ids to be initialized. + * @param count On input, specifies max elements in the array. + * On return, it contains actual number of elements + * that have been initialized. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_enum_buddies(pjsua_buddy_id ids[], - unsigned *count); + unsigned *count); /** * Find the buddy ID with the specified URI. * - * @param uri The buddy URI. + * @param uri The buddy URI. * - * @return The buddy ID, or PJSUA_INVALID_ID if not found. + * @return The buddy ID, or PJSUA_INVALID_ID if not found. */ PJ_DECL(pjsua_buddy_id) pjsua_buddy_find(const pj_str_t *uri); @@ -6425,33 +6424,33 @@ PJ_DECL(pjsua_buddy_id) pjsua_buddy_find(const pj_str_t *uri); /** * Get detailed buddy info. * - * @param buddy_id The buddy identification. - * @param info Pointer to receive information about buddy. + * @param buddy_id The buddy identification. + * @param info Pointer to receive information about buddy. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_buddy_get_info(pjsua_buddy_id buddy_id, - pjsua_buddy_info *info); + pjsua_buddy_info *info); /** * Set the user data associated with the buddy object. * - * @param buddy_id The buddy identification. - * @param user_data Arbitrary application data to be associated with - * the buddy object. + * @param buddy_id The buddy identification. + * @param user_data Arbitrary application data to be associated with + * the buddy object. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_buddy_set_user_data(pjsua_buddy_id buddy_id, - void *user_data); + void *user_data); /** * Get the user data associated with the budy object. * - * @param buddy_id The buddy identification. + * @param buddy_id The buddy identification. * - * @return The application data. + * @return The application data. */ PJ_DECL(void*) pjsua_buddy_get_user_data(pjsua_buddy_id buddy_id); @@ -6461,22 +6460,22 @@ PJ_DECL(void*) pjsua_buddy_get_user_data(pjsua_buddy_id buddy_id); * for this buddy, this function will also start the presence subscription * session immediately. * - * @param buddy_cfg Buddy configuration. - * @param p_buddy_id Pointer to receive buddy ID. + * @param buddy_cfg Buddy configuration. + * @param p_buddy_id Pointer to receive buddy ID. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_buddy_add(const pjsua_buddy_config *buddy_cfg, - pjsua_buddy_id *p_buddy_id); + pjsua_buddy_id *p_buddy_id); /** * Delete the specified buddy from the buddy list. Any presence subscription * to this buddy will be terminated. * - * @param buddy_id Buddy identification. + * @param buddy_id Buddy identification. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_buddy_del(pjsua_buddy_id buddy_id); @@ -6486,14 +6485,14 @@ PJ_DECL(pj_status_t) pjsua_buddy_del(pjsua_buddy_id buddy_id); * subscribed, application will be informed about buddy's presence status * changed via \a on_buddy_state() callback. * - * @param buddy_id Buddy identification. - * @param subscribe Specify non-zero to activate presence subscription to - * the specified buddy. + * @param buddy_id Buddy identification. + * @param subscribe Specify non-zero to activate presence subscription to + * the specified buddy. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_buddy_subscribe_pres(pjsua_buddy_id buddy_id, - pj_bool_t subscribe); + pj_bool_t subscribe); /** @@ -6512,9 +6511,9 @@ PJ_DECL(pj_status_t) pjsua_buddy_subscribe_pres(pjsua_buddy_id buddy_id, * application will be notified about the buddy's presence status in the * on_buddy_state() callback. * - * @param buddy_id Buddy identification. + * @param buddy_id Buddy identification. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_buddy_update_pres(pjsua_buddy_id buddy_id); @@ -6524,34 +6523,34 @@ PJ_DECL(pj_status_t) pjsua_buddy_update_pres(pjsua_buddy_id buddy_id); * side presence subscription. If application wants to reject the incoming * request, it should set the \a state to PJSIP_EVSUB_STATE_TERMINATED. * - * @param acc_id Account ID. - * @param srv_pres Server presence subscription instance. - * @param state New state to set. - * @param state_str Optionally specify the state string name, if state - * is not "active", "pending", or "terminated". - * @param reason If the new state is PJSIP_EVSUB_STATE_TERMINATED, - * optionally specify the termination reason. - * @param with_body If the new state is PJSIP_EVSUB_STATE_TERMINATED, - * this specifies whether the NOTIFY request should - * contain message body containing account's presence - * information. - * @param msg_data Optional list of headers to be sent with the NOTIFY - * request. - * - * @return PJ_SUCCESS on success. + * @param acc_id Account ID. + * @param srv_pres Server presence subscription instance. + * @param state New state to set. + * @param state_str Optionally specify the state string name, if state + * is not "active", "pending", or "terminated". + * @param reason If the new state is PJSIP_EVSUB_STATE_TERMINATED, + * optionally specify the termination reason. + * @param with_body If the new state is PJSIP_EVSUB_STATE_TERMINATED, + * this specifies whether the NOTIFY request should + * contain message body containing account's presence + * information. + * @param msg_data Optional list of headers to be sent with the NOTIFY + * request. + * + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsua_pres_notify(pjsua_acc_id acc_id, - pjsua_srv_pres *srv_pres, - pjsip_evsub_state state, - const pj_str_t *state_str, - const pj_str_t *reason, - pj_bool_t with_body, - const pjsua_msg_data *msg_data); + pjsua_srv_pres *srv_pres, + pjsip_evsub_state state, + const pj_str_t *state_str, + const pj_str_t *reason, + pj_bool_t with_body, + const pjsua_msg_data *msg_data); /** * Dump presence subscriptions to log. * - * @param verbose Yes or no. + * @param verbose Yes or no. */ PJ_DECL(void) pjsua_pres_dump(pj_bool_t verbose); @@ -6572,44 +6571,44 @@ extern const pjsip_method pjsip_info_method; * Send instant messaging outside dialog, using the specified account for * route set and authentication. * - * @param acc_id Account ID to be used to send the request. - * @param to Remote URI. - * @param mime_type Optional MIME type. If NULL, then "text/plain" is - * assumed. - * @param content The message content. Can be NULL if msg_data specifies - * body and/or multipart. - * @param msg_data Optional list of headers etc to be included in outgoing - * request. The body descriptor in the msg_data is - * ignored if parameter 'content' is set. - * @param user_data Optional user data, which will be given back when - * the IM callback is called. + * @param acc_id Account ID to be used to send the request. + * @param to Remote URI. + * @param mime_type Optional MIME type. If NULL, then "text/plain" is + * assumed. + * @param content The message content. Can be NULL if msg_data specifies + * body and/or multipart. + * @param msg_data Optional list of headers etc to be included in outgoing + * request. The body descriptor in the msg_data is + * ignored if parameter 'content' is set. + * @param user_data Optional user data, which will be given back when + * the IM callback is called. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_im_send(pjsua_acc_id acc_id, - const pj_str_t *to, - const pj_str_t *mime_type, - const pj_str_t *content, - const pjsua_msg_data *msg_data, - void *user_data); + const pj_str_t *to, + const pj_str_t *mime_type, + const pj_str_t *content, + const pjsua_msg_data *msg_data, + void *user_data); /** * Send typing indication outside dialog. * - * @param acc_id Account ID to be used to send the request. - * @param to Remote URI. - * @param is_typing If non-zero, it tells remote person that local person - * is currently composing an IM. - * @param msg_data Optional list of headers etc to be added to outgoing - * request. + * @param acc_id Account ID to be used to send the request. + * @param to Remote URI. + * @param is_typing If non-zero, it tells remote person that local person + * is currently composing an IM. + * @param msg_data Optional list of headers etc to be added to outgoing + * request. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_im_typing(pjsua_acc_id acc_id, - const pj_str_t *to, - pj_bool_t is_typing, - const pjsua_msg_data *msg_data); + const pj_str_t *to, + pj_bool_t is_typing, + const pjsua_msg_data *msg_data); @@ -6663,7 +6662,7 @@ PJ_DECL(pj_status_t) pjsua_im_typing(pjsua_acc_id acc_id, return status; status = pjsua_conf_connect( pjsua_player_get_conf_port(), - pjsua_call_get_conf_port() ); + pjsua_call_get_conf_port() ); } \endcode * @@ -6690,8 +6689,8 @@ PJ_DECL(pj_status_t) pjsua_im_typing(pjsua_acc_id acc_id, * stack. */ #ifndef PJSUA_MEDIA_HAS_PJMEDIA -# define PJSUA_MEDIA_HAS_PJMEDIA 1 -#endif /* PJSUA_MEDIA_HAS_PJMEDIA */ +# define PJSUA_MEDIA_HAS_PJMEDIA 1 +#endif /* PJSUA_MEDIA_HAS_PJMEDIA */ /** @@ -6721,7 +6720,7 @@ PJ_DECL(pj_status_t) pjsua_im_typing(pjsua_acc_id acc_id, * for pjsua_media_config.max_media_ports. */ #ifndef PJSUA_MAX_CONF_PORTS -# define PJSUA_MAX_CONF_PORTS 254 +# define PJSUA_MAX_CONF_PORTS 254 #endif /** @@ -6729,7 +6728,7 @@ PJ_DECL(pj_status_t) pjsua_im_typing(pjsua_acc_id acc_id, * is the default value for pjsua_media_config.clock_rate. */ #ifndef PJSUA_DEFAULT_CLOCK_RATE -# define PJSUA_DEFAULT_CLOCK_RATE 16000 +# define PJSUA_DEFAULT_CLOCK_RATE 16000 #endif /** @@ -6746,7 +6745,7 @@ PJ_DECL(pj_status_t) pjsua_im_typing(pjsua_acc_id acc_id, * for pjsua_media_config.quality. */ #ifndef PJSUA_DEFAULT_CODEC_QUALITY -# define PJSUA_DEFAULT_CODEC_QUALITY 8 +# define PJSUA_DEFAULT_CODEC_QUALITY 8 #endif /** @@ -6754,7 +6753,7 @@ PJ_DECL(pj_status_t) pjsua_im_typing(pjsua_acc_id acc_id, * pjsua_media_config.ilbc_mode. */ #ifndef PJSUA_DEFAULT_ILBC_MODE -# define PJSUA_DEFAULT_ILBC_MODE 30 +# define PJSUA_DEFAULT_ILBC_MODE 30 #endif /** @@ -6762,7 +6761,7 @@ PJ_DECL(pj_status_t) pjsua_im_typing(pjsua_acc_id acc_id, * is the default value for pjsua_media_config.ec_tail_len. */ #ifndef PJSUA_DEFAULT_EC_TAIL_LEN -# define PJSUA_DEFAULT_EC_TAIL_LEN 200 +# define PJSUA_DEFAULT_EC_TAIL_LEN 200 #endif @@ -6770,7 +6769,7 @@ PJ_DECL(pj_status_t) pjsua_im_typing(pjsua_acc_id acc_id, * The maximum file player. */ #ifndef PJSUA_MAX_PLAYERS -# define PJSUA_MAX_PLAYERS 32 +# define PJSUA_MAX_PLAYERS 32 #endif @@ -6778,7 +6777,7 @@ PJ_DECL(pj_status_t) pjsua_im_typing(pjsua_acc_id acc_id, * The maximum file player. */ #ifndef PJSUA_MAX_RECORDERS -# define PJSUA_MAX_RECORDERS 32 +# define PJSUA_MAX_RECORDERS 32 #endif @@ -6786,7 +6785,7 @@ PJ_DECL(pj_status_t) pjsua_im_typing(pjsua_acc_id acc_id, * Enable/disable "c=" line in SDP session level. Set to zero to disable it. */ #ifndef PJSUA_SDP_SESS_HAS_CONN -# define PJSUA_SDP_SESS_HAS_CONN 0 +# define PJSUA_SDP_SESS_HAS_CONN 0 #endif @@ -6795,7 +6794,7 @@ PJ_DECL(pj_status_t) pjsua_im_typing(pjsua_acc_id acc_id, * e.g: 10 msec on Linux or Android, and 0 on the other platforms. */ #ifndef PJSUA_TRANSPORT_RESTART_DELAY_TIME -# define PJSUA_TRANSPORT_RESTART_DELAY_TIME 10 +# define PJSUA_TRANSPORT_RESTART_DELAY_TIME 10 #endif @@ -6811,19 +6810,19 @@ struct pjsua_media_config * If value is zero, default clock rate will be used * (PJSUA_DEFAULT_CLOCK_RATE, which by default is 16KHz). */ - unsigned clock_rate; + unsigned clock_rate; /** * Clock rate to be applied when opening the sound device. * If value is zero, conference bridge clock rate will be used. */ - unsigned snd_clock_rate; + unsigned snd_clock_rate; /** * Channel count be applied when opening the sound device and * conference bridge. */ - unsigned channel_count; + unsigned channel_count; /** * Specify audio frame ptime. The value here will affect the @@ -6833,7 +6832,7 @@ struct pjsua_media_config * * Default value: PJSUA_DEFAULT_AUDIO_FRAME_PTIME */ - unsigned audio_frame_ptime; + unsigned audio_frame_ptime; /** * Specify maximum number of media ports to be created in the @@ -6844,7 +6843,7 @@ struct pjsua_media_config * * Default value: PJSUA_MAX_CONF_PORTS */ - unsigned max_media_ports; + unsigned max_media_ports; /** * Specify whether the media manager should manage its own @@ -6856,13 +6855,13 @@ struct pjsua_media_config * Normally application would say yes here, unless it wants to * run everything from a single thread. */ - pj_bool_t has_ioqueue; + pj_bool_t has_ioqueue; /** * Specify the number of worker threads to handle incoming RTP * packets. A value of one is recommended for most applications. */ - unsigned thread_cnt; + unsigned thread_cnt; /** * Media quality, 0-10, according to this table: @@ -6874,28 +6873,28 @@ struct pjsua_media_config * * Default: PJSUA_DEFAULT_CODEC_QUALITY. */ - unsigned quality; + unsigned quality; /** * Specify default codec ptime. * * Default: 0 (codec specific) */ - unsigned ptime; + unsigned ptime; /** * Disable VAD? * * Default: 0 (codec specific) */ - pj_bool_t no_vad; + pj_bool_t no_vad; /** * iLBC mode (20 or 30). * * Default: 30 (PJSUA_DEFAULT_ILBC_MODE) */ - unsigned ilbc_mode; + unsigned ilbc_mode; /** * Percentage of RTP packet to drop in TX direction @@ -6903,7 +6902,7 @@ struct pjsua_media_config * * Default: 0 */ - unsigned tx_drop_pct; + unsigned tx_drop_pct; /** * Percentage of RTP packet to drop in RX direction @@ -6911,7 +6910,7 @@ struct pjsua_media_config * * Default: 0 */ - unsigned rx_drop_pct; + unsigned rx_drop_pct; /** * Echo canceller options (see #pjmedia_echo_create()). @@ -6920,28 +6919,28 @@ struct pjsua_media_config * * Default: 0. */ - unsigned ec_options; + unsigned ec_options; /** * Echo canceller tail length, in miliseconds. * * Default: PJSUA_DEFAULT_EC_TAIL_LEN */ - unsigned ec_tail_len; + unsigned ec_tail_len; /** * Audio capture buffer length, in milliseconds. * * Default: PJMEDIA_SND_DEFAULT_REC_LATENCY */ - unsigned snd_rec_latency; + unsigned snd_rec_latency; /** * Audio playback buffer length, in milliseconds. * * Default: PJMEDIA_SND_DEFAULT_PLAY_LATENCY */ - unsigned snd_play_latency; + unsigned snd_play_latency; /** * Jitter buffer initial prefetch delay in msec. The value must be @@ -6950,28 +6949,28 @@ struct pjsua_media_config * * Default: -1 (to use default stream settings, currently 0) */ - int jb_init; + int jb_init; /** * Jitter buffer minimum prefetch delay in msec. * * Default: -1 (to use default stream settings, currently codec ptime) */ - int jb_min_pre; + int jb_min_pre; /** * Jitter buffer maximum prefetch delay in msec. * * Default: -1 (to use default stream settings, currently 80% of jb_max) */ - int jb_max_pre; + int jb_max_pre; /** * Set maximum delay that can be accomodated by the jitter buffer msec. * * Default: -1 (to use default stream settings, currently 500 msec) */ - int jb_max; + int jb_max; /** * Set the algorithm the jitter buffer uses to discard frames in order to @@ -6984,26 +6983,26 @@ struct pjsua_media_config /** * Enable ICE */ - pj_bool_t enable_ice; + pj_bool_t enable_ice; /** * Set the maximum number of host candidates. * * Default: -1 (maximum not set) */ - int ice_max_host_cands; + int ice_max_host_cands; /** * ICE session options. */ - pj_ice_sess_options ice_opt; + pj_ice_sess_options ice_opt; /** * Disable RTCP component. * * Default: no */ - pj_bool_t ice_no_rtcp; + pj_bool_t ice_no_rtcp; /** * Send re-INVITE/UPDATE every after ICE connectivity check regardless @@ -7013,18 +7012,18 @@ struct pjsua_media_config * * Default: yes */ - pj_bool_t ice_always_update; + pj_bool_t ice_always_update; /** * Enable TURN relay candidate in ICE. */ - pj_bool_t enable_turn; + pj_bool_t enable_turn; /** * Specify TURN domain name or host name, in in "DOMAIN:PORT" or * "HOST:PORT" format. */ - pj_str_t turn_server; + pj_str_t turn_server; /** * Specify the connection type to be used to the TURN server. Valid @@ -7032,12 +7031,12 @@ struct pjsua_media_config * * Default: PJ_TURN_TP_UDP */ - pj_turn_tp_type turn_conn_type; + pj_turn_tp_type turn_conn_type; /** * Specify the credential to authenticate with the TURN server. */ - pj_stun_auth_cred turn_auth_cred; + pj_stun_auth_cred turn_auth_cred; /** * This specifies TLS settings for TLS transport. It is only be used @@ -7052,7 +7051,7 @@ struct pjsua_media_config * * Default : 1 */ - int snd_auto_close_time; + int snd_auto_close_time; /** * Specify whether built-in/native preview should be used if available. @@ -7121,7 +7120,7 @@ struct pjsua_media_config /** * Use this function to initialize media config. * - * @param cfg The media config to be initialized. + * @param cfg The media config to be initialized. */ PJ_DECL(void) pjsua_media_config_default(pjsua_media_config *cfg); @@ -7135,22 +7134,22 @@ typedef struct pjsua_codec_info /** * Codec unique identification. */ - pj_str_t codec_id; + pj_str_t codec_id; /** * Codec priority (integer 0-255). */ - pj_uint8_t priority; + pj_uint8_t priority; /** * Codec description. */ - pj_str_t desc; + pj_str_t desc; /** * Internal buffer. */ - char buf_[64]; + char buf_[64]; } pjsua_codec_info; @@ -7163,39 +7162,39 @@ typedef struct pjsua_codec_info typedef struct pjsua_conf_port_info { /** Conference port number. */ - pjsua_conf_port_id slot_id; + pjsua_conf_port_id slot_id; /** Port name. */ - pj_str_t name; + pj_str_t name; /** Format. */ - pjmedia_format format; + pjmedia_format format; /** Clock rate. */ - unsigned clock_rate; + unsigned clock_rate; /** Number of channels. */ - unsigned channel_count; + unsigned channel_count; /** Samples per frame */ - unsigned samples_per_frame; + unsigned samples_per_frame; /** Bits per sample */ - unsigned bits_per_sample; + unsigned bits_per_sample; /** Tx level adjustment. */ - float tx_level_adj; + float tx_level_adj; /** Rx level adjustment. */ - float rx_level_adj; + float rx_level_adj; /** Number of listeners in the array. */ - unsigned listener_cnt; + unsigned listener_cnt; /** Array of listeners (in other words, ports where this port is * transmitting to). */ - pjsua_conf_port_id listeners[PJSUA_MAX_CONF_PORTS]; + pjsua_conf_port_id listeners[PJSUA_MAX_CONF_PORTS]; } pjsua_conf_port_info; @@ -7210,12 +7209,12 @@ typedef struct pjsua_media_transport * Media socket information containing the address information * of the RTP and RTCP socket. */ - pjmedia_sock_info skinfo; + pjmedia_sock_info skinfo; /** * The media transport instance. */ - pjmedia_transport *transport; + pjmedia_transport *transport; } pjsua_media_transport; @@ -7277,21 +7276,21 @@ typedef struct pjsua_snd_dev_param * * Default: PJMEDIA_AUD_DEFAULT_CAPTURE_DEV */ - int capture_dev; + int capture_dev; /** * Playback dev id. * * Default: PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV */ - int playback_dev; + int playback_dev; /** * Sound device mode, refer to #pjsua_snd_dev_mode. * * Default: 0 */ - unsigned mode; + unsigned mode; /* * The library will maintain the global sound device settings set when @@ -7307,7 +7306,7 @@ typedef struct pjsua_snd_dev_param * * Default: PJ_FALSE */ - pj_bool_t use_default_settings; + pj_bool_t use_default_settings; } pjsua_snd_dev_param; @@ -7315,7 +7314,7 @@ typedef struct pjsua_snd_dev_param /** * Initialize pjsua_snd_dev_param with default values. * - * @param prm The parameter. + * @param prm The parameter. */ PJ_DECL(void) pjsua_snd_dev_param_default(pjsua_snd_dev_param *prm); @@ -7334,7 +7333,7 @@ typedef struct pjsua_conf_connect_param * * Default: 1.0 */ - float level; + float level; } pjsua_conf_connect_param; @@ -7342,7 +7341,7 @@ typedef struct pjsua_conf_connect_param /** * Initialize pjsua_conf_connect_param with default values. * - * @param prm The parameter. + * @param prm The parameter. */ PJ_DECL(void) pjsua_conf_connect_param_default(pjsua_conf_connect_param *prm); @@ -7350,7 +7349,7 @@ PJ_DECL(void) pjsua_conf_connect_param_default(pjsua_conf_connect_param *prm); /** * Get maxinum number of conference ports. * - * @return Maximum number of ports in the conference bridge. + * @return Maximum number of ports in the conference bridge. */ PJ_DECL(unsigned) pjsua_conf_get_max_ports(void); @@ -7358,7 +7357,7 @@ PJ_DECL(unsigned) pjsua_conf_get_max_ports(void); /** * Get current number of active ports in the bridge. * - * @return The number. + * @return The number. */ PJ_DECL(unsigned) pjsua_conf_get_active_ports(void); @@ -7366,27 +7365,27 @@ PJ_DECL(unsigned) pjsua_conf_get_active_ports(void); /** * Enumerate all conference ports. * - * @param id Array of conference port ID to be initialized. - * @param count On input, specifies max elements in the array. - * On return, it contains actual number of elements - * that have been initialized. + * @param id Array of conference port ID to be initialized. + * @param count On input, specifies max elements in the array. + * On return, it contains actual number of elements + * that have been initialized. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_enum_conf_ports(pjsua_conf_port_id id[], - unsigned *count); + unsigned *count); /** * Get information about the specified conference port * - * @param port_id Port identification. - * @param info Pointer to store the port info. + * @param port_id Port identification. + * @param info Pointer to store the port info. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_conf_get_port_info( pjsua_conf_port_id port_id, - pjsua_conf_port_info *info); + pjsua_conf_port_info *info); /** @@ -7396,16 +7395,16 @@ PJ_DECL(pj_status_t) pjsua_conf_get_port_info( pjsua_conf_port_id port_id, * or file recorder), PJSUA-LIB will automatically add the port to * the bridge. * - * @param pool Pool to use. - * @param port Media port to be added to the bridge. - * @param p_id Optional pointer to receive the conference - * slot id. + * @param pool Pool to use. + * @param port Media port to be added to the bridge. + * @param p_id Optional pointer to receive the conference + * slot id. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_conf_add_port(pj_pool_t *pool, - pjmedia_port *port, - pjsua_conf_port_id *p_id); + pjmedia_port *port, + pjsua_conf_port_id *p_id); /** @@ -7413,9 +7412,9 @@ PJ_DECL(pj_status_t) pjsua_conf_add_port(pj_pool_t *pool, * call this function if it registered the port manually with previous call * to #pjsua_conf_add_port(). * - * @param port_id The slot id of the port to be removed. + * @param port_id The slot id of the port to be removed. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_conf_remove_port(pjsua_conf_port_id port_id); @@ -7431,13 +7430,13 @@ PJ_DECL(pj_status_t) pjsua_conf_remove_port(pjsua_conf_port_id port_id); * this function twice, with the second one having the arguments * reversed. * - * @param source Port ID of the source media/transmitter. - * @param sink Port ID of the destination media/received. + * @param source Port ID of the source media/transmitter. + * @param sink Port ID of the destination media/received. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_conf_connect(pjsua_conf_port_id source, - pjsua_conf_port_id sink); + pjsua_conf_port_id sink); /** * Establish unidirectional media flow from source to sink. One source @@ -7462,74 +7461,74 @@ PJ_DECL(pj_status_t) pjsua_conf_connect(pjsua_conf_port_id source, * this function twice, with the second one having the arguments * reversed. * - * @param source Port ID of the source media/transmitter. - * @param sink Port ID of the destination media/received. - * @param prm Conference port connection param. If set to - * NULL, default values will be used. + * @param source Port ID of the source media/transmitter. + * @param sink Port ID of the destination media/received. + * @param prm Conference port connection param. If set to + * NULL, default values will be used. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_conf_connect2(pjsua_conf_port_id source, - pjsua_conf_port_id sink, - const pjsua_conf_connect_param *prm); + pjsua_conf_port_id sink, + const pjsua_conf_connect_param *prm); /** * Disconnect media flow from the source to destination port. * - * @param source Port ID of the source media/transmitter. - * @param sink Port ID of the destination media/received. + * @param source Port ID of the source media/transmitter. + * @param sink Port ID of the destination media/received. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_conf_disconnect(pjsua_conf_port_id source, - pjsua_conf_port_id sink); + pjsua_conf_port_id sink); /** * Adjust the signal level to be transmitted from the bridge to the * specified port by making it louder or quieter. * - * @param slot The conference bridge slot number. - * @param level Signal level adjustment. Value 1.0 means no level - * adjustment, while value 0 means to mute the port. + * @param slot The conference bridge slot number. + * @param level Signal level adjustment. Value 1.0 means no level + * adjustment, while value 0 means to mute the port. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_conf_adjust_tx_level(pjsua_conf_port_id slot, - float level); + float level); /** * Adjust the signal level to be received from the specified port (to * the bridge) by making it louder or quieter. * - * @param slot The conference bridge slot number. - * @param level Signal level adjustment. Value 1.0 means no level - * adjustment, while value 0 means to mute the port. + * @param slot The conference bridge slot number. + * @param level Signal level adjustment. Value 1.0 means no level + * adjustment, while value 0 means to mute the port. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_conf_adjust_rx_level(pjsua_conf_port_id slot, - float level); + float level); /** * Get last signal level transmitted to or received from the specified port. * The signal level is an integer value in zero to 255, with zero indicates * no signal, and 255 indicates the loudest signal level. * - * @param slot The conference bridge slot number. - * @param tx_level Optional argument to receive the level of signal - * transmitted to the specified port (i.e. the direction - * is from the bridge to the port). - * @param rx_level Optional argument to receive the level of signal - * received from the port (i.e. the direction is from the - * port to the bridge). + * @param slot The conference bridge slot number. + * @param tx_level Optional argument to receive the level of signal + * transmitted to the specified port (i.e. the direction + * is from the bridge to the port). + * @param rx_level Optional argument to receive the level of signal + * received from the port (i.e. the direction is from the + * port to the bridge). * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsua_conf_get_signal_level(pjsua_conf_port_id slot, - unsigned *tx_level, - unsigned *rx_level); + unsigned *tx_level, + unsigned *rx_level); /***************************************************************************** @@ -7540,51 +7539,51 @@ PJ_DECL(pj_status_t) pjsua_conf_get_signal_level(pjsua_conf_port_id slot, * Create a file player, and automatically add this player to * the conference bridge. * - * @param filename The filename to be played. Currently only - * WAV files are supported, and the WAV file MUST be - * formatted as 16bit PCM mono/single channel (any - * clock rate is supported). - * Filename's length must be smaller than PJ_MAXPATH. - * @param options Optional option flag. Application may specify - * PJMEDIA_FILE_NO_LOOP to prevent playback loop. - * @param p_id Pointer to receive player ID. + * @param filename The filename to be played. Currently only + * WAV files are supported, and the WAV file MUST be + * formatted as 16bit PCM mono/single channel (any + * clock rate is supported). + * Filename's length must be smaller than PJ_MAXPATH. + * @param options Optional option flag. Application may specify + * PJMEDIA_FILE_NO_LOOP to prevent playback loop. + * @param p_id Pointer to receive player ID. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_player_create(const pj_str_t *filename, - unsigned options, - pjsua_player_id *p_id); + unsigned options, + pjsua_player_id *p_id); /** * Create a file playlist media port, and automatically add the port * to the conference bridge. * - * @param file_names Array of file names to be added to the play list. - * Note that the files must have the same clock rate, - * number of channels, and number of bits per sample. - * Each filename's length must be smaller than - * PJ_MAXPATH. - * @param file_count Number of files in the array. - * @param label Optional label to be set for the media port. - * @param options Optional option flag. Application may specify - * PJMEDIA_FILE_NO_LOOP to prevent looping. - * @param p_id Optional pointer to receive player ID. + * @param file_names Array of file names to be added to the play list. + * Note that the files must have the same clock rate, + * number of channels, and number of bits per sample. + * Each filename's length must be smaller than + * PJ_MAXPATH. + * @param file_count Number of files in the array. + * @param label Optional label to be set for the media port. + * @param options Optional option flag. Application may specify + * PJMEDIA_FILE_NO_LOOP to prevent looping. + * @param p_id Optional pointer to receive player ID. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_playlist_create(const pj_str_t file_names[], - unsigned file_count, - const pj_str_t *label, - unsigned options, - pjsua_player_id *p_id); + unsigned file_count, + const pj_str_t *label, + unsigned options, + pjsua_player_id *p_id); /** * Get conference port ID associated with player or playlist. * - * @param id The file player ID. + * @param id The file player ID. * - * @return Conference port ID associated with this player. + * @return Conference port ID associated with this player. */ PJ_DECL(pjsua_conf_port_id) pjsua_player_get_conf_port(pjsua_player_id id); @@ -7592,22 +7591,22 @@ PJ_DECL(pjsua_conf_port_id) pjsua_player_get_conf_port(pjsua_player_id id); /** * Get the media port for the player or playlist. * - * @param id The player ID. - * @param p_port The media port associated with the player. + * @param id The player ID. + * @param p_port The media port associated with the player. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsua_player_get_port(pjsua_player_id id, - pjmedia_port **p_port); + pjmedia_port **p_port); /** * Get additional info about the file player. This operation is not valid * for playlist. * - * @param id The file player ID. - * @param info The info. + * @param id The file player ID. + * @param info The info. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_player_get_info(pjsua_player_id id, pjmedia_wav_player_info *info); @@ -7616,32 +7615,32 @@ PJ_DECL(pj_status_t) pjsua_player_get_info(pjsua_player_id id, /** * Get playback position. This operation is not valid for playlist. * - * @param id The file player ID. + * @param id The file player ID. * - * @return The current playback position, in samples. On error, - * return the error code as negative value. + * @return The current playback position, in samples. On error, + * return the error code as negative value. */ PJ_DECL(pj_ssize_t) pjsua_player_get_pos(pjsua_player_id id); /** * Set playback position. This operation is not valid for playlist. * - * @param id The file player ID. - * @param samples The playback position, in samples. Application can - * specify zero to re-start the playback. + * @param id The file player ID. + * @param samples The playback position, in samples. Application can + * specify zero to re-start the playback. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_player_set_pos(pjsua_player_id id, - pj_uint32_t samples); + pj_uint32_t samples); /** * Close the file of playlist, remove the player from the bridge, and free * resources associated with the file player or playlist. * - * @param id The file player ID. + * @param id The file player ID. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_player_destroy(pjsua_player_id id); @@ -7656,37 +7655,37 @@ PJ_DECL(pj_status_t) pjsua_player_destroy(pjsua_player_id id); * The type of the recorder to use is determined by the extension of the file * (e.g. ".wav"). * - * @param filename Output file name. The function will determine the - * default format to be used based on the file extension. - * Currently ".wav" is supported on all platforms. - * Filename's length must be smaller than PJ_MAXPATH. - * @param enc_type Optionally specify the type of encoder to be used to - * compress the media, if the file can support different - * encodings. This value must be zero for now. - * @param enc_param Optionally specify codec specific parameter to be - * passed to the file writer. - * For .WAV recorder, this value must be NULL. - * @param max_size Maximum file size. Specify zero or -1 to remove size - * limitation. This value must be zero or -1 for now. - * @param options Optional options. - * @param p_id Pointer to receive the recorder instance. - * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @param filename Output file name. The function will determine the + * default format to be used based on the file extension. + * Currently ".wav" is supported on all platforms. + * Filename's length must be smaller than PJ_MAXPATH. + * @param enc_type Optionally specify the type of encoder to be used to + * compress the media, if the file can support different + * encodings. This value must be zero for now. + * @param enc_param Optionally specify codec specific parameter to be + * passed to the file writer. + * For .WAV recorder, this value must be NULL. + * @param max_size Maximum file size. Specify zero or -1 to remove size + * limitation. This value must be zero or -1 for now. + * @param options Optional options. + * @param p_id Pointer to receive the recorder instance. + * + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_recorder_create(const pj_str_t *filename, - unsigned enc_type, - void *enc_param, - pj_ssize_t max_size, - unsigned options, - pjsua_recorder_id *p_id); + unsigned enc_type, + void *enc_param, + pj_ssize_t max_size, + unsigned options, + pjsua_recorder_id *p_id); /** * Get conference port associated with recorder. * - * @param id The recorder ID. + * @param id The recorder ID. * - * @return Conference port ID associated with this recorder. + * @return Conference port ID associated with this recorder. */ PJ_DECL(pjsua_conf_port_id) pjsua_recorder_get_conf_port(pjsua_recorder_id id); @@ -7694,21 +7693,21 @@ PJ_DECL(pjsua_conf_port_id) pjsua_recorder_get_conf_port(pjsua_recorder_id id); /** * Get the media port for the recorder. * - * @param id The recorder ID. - * @param p_port The media port associated with the recorder. + * @param id The recorder ID. + * @param p_port The media port associated with the recorder. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsua_recorder_get_port(pjsua_recorder_id id, - pjmedia_port **p_port); + pjmedia_port **p_port); /** * Destroy recorder (this will complete recording). * - * @param id The recorder ID. + * @param id The recorder ID. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_recorder_destroy(pjsua_recorder_id id); @@ -7720,28 +7719,28 @@ PJ_DECL(pj_status_t) pjsua_recorder_destroy(pjsua_recorder_id id); /** * Enum all audio devices installed in the system. * - * @param info Array of info to be initialized. - * @param count On input, specifies max elements in the array. - * On return, it contains actual number of elements - * that have been initialized. + * @param info Array of info to be initialized. + * @param count On input, specifies max elements in the array. + * On return, it contains actual number of elements + * that have been initialized. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_enum_aud_devs(pjmedia_aud_dev_info info[], - unsigned *count); + unsigned *count); /** * Enum all sound devices installed in the system (old API). * - * @param info Array of info to be initialized. - * @param count On input, specifies max elements in the array. - * On return, it contains actual number of elements - * that have been initialized. + * @param info Array of info to be initialized. + * @param count On input, specifies max elements in the array. + * On return, it contains actual number of elements + * that have been initialized. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_enum_snd_devs(pjmedia_snd_dev_info info[], - unsigned *count); + unsigned *count); /** * Get currently active sound devices. If sound devices has not been created @@ -7750,14 +7749,14 @@ PJ_DECL(pj_status_t) pjsua_enum_snd_devs(pjmedia_snd_dev_info info[], * See also #pjsua_snd_dev_id constants. * * @param capture_dev On return it will be filled with device ID of the - * capture device. - * @param playback_dev On return it will be filled with device ID of the - * device ID of the playback device. + * capture device. + * @param playback_dev On return it will be filled with device ID of the + * device ID of the playback device. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_get_snd_dev(int *capture_dev, - int *playback_dev); + int *playback_dev); /** @@ -7769,19 +7768,19 @@ PJ_DECL(pj_status_t) pjsua_get_snd_dev(int *capture_dev, * with PJSUA_SND_DEV_NO_IMMEDIATE_OPEN flag. * * @param capture_dev Device ID of the capture device. - * @param playback_dev Device ID of the playback device. + * @param playback_dev Device ID of the playback device. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_set_snd_dev(int capture_dev, - int playback_dev); + int playback_dev); /** * Get sound device parameters such as playback & capture device IDs and mode. * - * @param snd_param On return, it is set with sound device param. + * @param snd_param On return, it is set with sound device param. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_get_snd_dev2(pjsua_snd_dev_param *snd_param); @@ -7789,9 +7788,9 @@ PJ_DECL(pj_status_t) pjsua_get_snd_dev2(pjsua_snd_dev_param *snd_param); /** * Select or change sound device according to the specified param. * - * @param snd_param Sound device param. + * @param snd_param Sound device param. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_set_snd_dev2(const pjsua_snd_dev_param *snd_param); @@ -7801,7 +7800,7 @@ PJ_DECL(pj_status_t) pjsua_set_snd_dev2(const pjsua_snd_dev_param *snd_param); * the timing needed by the conference bridge, and will not interract with * any hardware. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_set_null_snd_dev(void); @@ -7810,9 +7809,9 @@ PJ_DECL(pj_status_t) pjsua_set_null_snd_dev(void); * Disconnect the main conference bridge from any sound devices, and let * application connect the bridge to it's own sound device/master port. * - * @return The port interface of the conference bridge, - * so that application can connect this to it's own - * sound device or master port. + * @return The port interface of the conference bridge, + * so that application can connect this to it's own + * sound device or master port. */ PJ_DECL(pjmedia_port*) pjsua_set_no_snd_dev(void); @@ -7835,12 +7834,12 @@ PJ_DECL(pjmedia_port*) pjsua_set_no_snd_dev(void); * default AEC settings and the setting will be applied next time the * sound device is opened. * - * @param tail_ms The tail length, in miliseconds. Set to zero to - * disable AEC. - * @param options Options to be passed to pjmedia_echo_create(). - * Normally the value should be zero. + * @param tail_ms The tail length, in miliseconds. Set to zero to + * disable AEC. + * @param options Options to be passed to pjmedia_echo_create(). + * Normally the value should be zero. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsua_set_ec(unsigned tail_ms, unsigned options); @@ -7848,10 +7847,10 @@ PJ_DECL(pj_status_t) pjsua_set_ec(unsigned tail_ms, unsigned options); /** * Get current echo canceller tail length. * - * @param p_tail_ms Pointer to receive the tail length, in miliseconds. - * If AEC is disabled, the value will be zero. + * @param p_tail_ms Pointer to receive the tail length, in miliseconds. + * If AEC is disabled, the value will be zero. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjsua_get_ec_tail(unsigned *p_tail_ms); @@ -7859,10 +7858,10 @@ PJ_DECL(pj_status_t) pjsua_get_ec_tail(unsigned *p_tail_ms); /** * Get echo canceller statistics. * - * @param p_stat Pointer to receive the stat. + * @param p_stat Pointer to receive the stat. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjsua_get_ec_stat(pjmedia_echo_stat *p_stat); @@ -7898,18 +7897,18 @@ PJ_DECL(pj_bool_t) pjsua_snd_is_active(void); * See also #pjmedia_aud_stream_set_cap() for more information about setting * an audio device capability. * - * @param cap The sound device setting to change. - * @param pval Pointer to value. Please see #pjmedia_aud_dev_cap - * documentation about the type of value to be - * supplied for each setting. - * @param keep Specify whether the setting is to be kept for future - * use. + * @param cap The sound device setting to change. + * @param pval Pointer to value. Please see #pjmedia_aud_dev_cap + * documentation about the type of value to be + * supplied for each setting. + * @param keep Specify whether the setting is to be kept for future + * use. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_snd_set_setting(pjmedia_aud_dev_cap cap, - const void *pval, - pj_bool_t keep); + const void *pval, + pj_bool_t keep); /** * Retrieve a sound device setting. If sound device is currently active, @@ -7921,15 +7920,15 @@ PJ_DECL(pj_status_t) pjsua_snd_set_setting(pjmedia_aud_dev_cap cap, * Note that echo cancellation settings should be retrieved with * #pjsua_get_ec_tail() API instead. * - * @param cap The sound device setting to retrieve. - * @param pval Pointer to receive the value. - * Please see #pjmedia_aud_dev_cap documentation about - * the type of value to be supplied for each setting. + * @param cap The sound device setting to retrieve. + * @param pval Pointer to receive the value. + * Please see #pjmedia_aud_dev_cap documentation about + * the type of value to be supplied for each setting. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_snd_get_setting(pjmedia_aud_dev_cap cap, - void *pval); + void *pval); /** @@ -7957,22 +7956,22 @@ typedef struct pjsua_ext_snd_dev pjsua_ext_snd_dev; /** * Create an extra sound device and register it to conference bridge. * - * @param param Sound device port param. Currently this only supports - * mono channel, so channel count must be set to 1. - * @param p_snd The extra sound device instance. + * @param param Sound device port param. Currently this only supports + * mono channel, so channel count must be set to 1. + * @param p_snd The extra sound device instance. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_ext_snd_dev_create(pjmedia_snd_port_param *param, - pjsua_ext_snd_dev **p_snd); + pjsua_ext_snd_dev **p_snd); /** * Destroy an extra sound device and unregister it from conference bridge. * - * @param snd The extra sound device instance. + * @param snd The extra sound device instance. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_ext_snd_dev_destroy(pjsua_ext_snd_dev *snd); @@ -7980,22 +7979,22 @@ PJ_DECL(pj_status_t) pjsua_ext_snd_dev_destroy(pjsua_ext_snd_dev *snd); /** * Get sound port instance of an extra sound device. * - * @param snd The extra sound device instance. + * @param snd The extra sound device instance. * - * @return The sound port instance. + * @return The sound port instance. */ PJ_DECL(pjmedia_snd_port*) pjsua_ext_snd_dev_get_snd_port( - pjsua_ext_snd_dev *snd); + pjsua_ext_snd_dev *snd); /** * Get conference port ID of an extra sound device. * - * @param snd The extra sound device instance. + * @param snd The extra sound device instance. * - * @return The conference port ID. + * @return The conference port ID. */ PJ_DECL(pjsua_conf_port_id) pjsua_ext_snd_dev_get_conf_port( - pjsua_ext_snd_dev *snd); + pjsua_ext_snd_dev *snd); /***************************************************************************** @@ -8005,55 +8004,55 @@ PJ_DECL(pjsua_conf_port_id) pjsua_ext_snd_dev_get_conf_port( /** * Enum all supported codecs in the system. * - * @param id Array of ID to be initialized. - * @param count On input, specifies max elements in the array. - * On return, it contains actual number of elements - * that have been initialized. + * @param id Array of ID to be initialized. + * @param count On input, specifies max elements in the array. + * On return, it contains actual number of elements + * that have been initialized. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_enum_codecs( pjsua_codec_info id[], - unsigned *count ); + unsigned *count ); /** * Change codec priority. * - * @param codec_id Codec ID, which is a string that uniquely identify - * the codec (such as "speex/8000"). Please see pjsua - * manual or pjmedia codec reference for details. - * @param priority Codec priority, 0-255, where zero means to disable - * the codec. + * @param codec_id Codec ID, which is a string that uniquely identify + * the codec (such as "speex/8000"). Please see pjsua + * manual or pjmedia codec reference for details. + * @param priority Codec priority, 0-255, where zero means to disable + * the codec. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_codec_set_priority( const pj_str_t *codec_id, - pj_uint8_t priority ); + pj_uint8_t priority ); /** * Get codec parameters. * - * @param codec_id Codec ID. - * @param param Structure to receive codec parameters. + * @param codec_id Codec ID. + * @param param Structure to receive codec parameters. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_codec_get_param( const pj_str_t *codec_id, - pjmedia_codec_param *param ); + pjmedia_codec_param *param ); /** * Set codec parameters. * - * @param codec_id Codec ID. - * @param param Codec parameter to set. Set to NULL to reset - * codec parameter to library default settings. + * @param codec_id Codec ID. + * @param param Codec parameter to set. Set to NULL to reset + * codec parameter to library default settings. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_codec_set_param( const pj_str_t *codec_id, - const pjmedia_codec_param *param); + const pjmedia_codec_param *param); #if DISABLED_FOR_TICKET_1185 @@ -8061,11 +8060,11 @@ PJ_DECL(pj_status_t) pjsua_codec_set_param( const pj_str_t *codec_id, * Create UDP media transports for all the calls. This function creates * one UDP media transport for each call. * - * @param cfg Media transport configuration. The "port" field in the - * configuration is used as the start port to bind the - * sockets. + * @param cfg Media transport configuration. The "port" field in the + * configuration is used as the start port to bind the + * sockets. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_media_transports_create(const pjsua_transport_config *cfg); @@ -8075,19 +8074,19 @@ pjsua_media_transports_create(const pjsua_transport_config *cfg); * Register custom media transports to be used by calls. There must * enough media transports for all calls. * - * @param tp The media transport array. - * @param count Number of elements in the array. This number MUST - * match the number of maximum calls configured when - * pjsua is created. - * @param auto_delete Flag to indicate whether the transports should be - * destroyed when pjsua is shutdown. + * @param tp The media transport array. + * @param count Number of elements in the array. This number MUST + * match the number of maximum calls configured when + * pjsua is created. + * @param auto_delete Flag to indicate whether the transports should be + * destroyed when pjsua is shutdown. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_media_transports_attach( pjsua_media_transport tp[], - unsigned count, - pj_bool_t auto_delete); + unsigned count, + pj_bool_t auto_delete); #endif @@ -8134,24 +8133,24 @@ pjsua_media_transports_attach( pjsua_media_transport tp[], * Default: 0 (no) */ #ifndef PJSUA_DONT_INIT_VID_DEV_SUBSYS -# define PJSUA_DONT_INIT_VID_DEV_SUBSYS 0 +# define PJSUA_DONT_INIT_VID_DEV_SUBSYS 0 #endif /** * Get the number of video devices installed in the system. * - * @return The number of devices. + * @return The number of devices. */ PJ_DECL(unsigned) pjsua_vid_dev_count(void); /** * Retrieve the video device info for the specified device index. * - * @param id The device index. - * @param vdi Device info to be initialized. + * @param id The device index. + * @param vdi Device info to be initialized. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_dev_get_info(pjmedia_vid_dev_index id, pjmedia_vid_dev_info *vdi); @@ -8161,9 +8160,9 @@ PJ_DECL(pj_status_t) pjsua_vid_dev_get_info(pjmedia_vid_dev_index id, * a video preview has been started or there is a video call using * the device. This function will return PJ_FALSE for video renderer device. * - * @param id The video device index. + * @param id The video device index. * - * @return PJ_TRUE if active, PJ_FALSE otherwise. + * @return PJ_TRUE if active, PJ_FALSE otherwise. */ PJ_DECL(pj_bool_t) pjsua_vid_dev_is_active(pjmedia_vid_dev_index id); @@ -8189,19 +8188,19 @@ PJ_DECL(pj_bool_t) pjsua_vid_dev_is_active(pjmedia_vid_dev_index id); * See also pjmedia_vid_stream_set_cap() for more information about setting * a video device capability. * - * @param id The video device index. - * @param cap The video device capability to change. - * @param pval Pointer to value. Please see #pjmedia_vid_dev_cap - * documentation about the type of value to be - * supplied for each setting. + * @param id The video device index. + * @param cap The video device capability to change. + * @param pval Pointer to value. Please see #pjmedia_vid_dev_cap + * documentation about the type of value to be + * supplied for each setting. * @param keep (see description) * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_dev_set_setting(pjmedia_vid_dev_index id, - pjmedia_vid_dev_cap cap, - const void *pval, - pj_bool_t keep); + pjmedia_vid_dev_cap cap, + const void *pval, + pj_bool_t keep); /** * Retrieve the value of a video capture device setting. If the device is @@ -8213,30 +8212,30 @@ PJ_DECL(pj_status_t) pjsua_vid_dev_set_setting(pjmedia_vid_dev_index id, * error. * The function only works for video capture device. * - * @param id The video device index. - * @param cap The video device capability to retrieve. - * @param pval Pointer to receive the value. - * Please see #pjmedia_vid_dev_cap documentation about - * the type of value to be supplied for each setting. + * @param id The video device index. + * @param cap The video device capability to retrieve. + * @param pval Pointer to receive the value. + * Please see #pjmedia_vid_dev_cap documentation about + * the type of value to be supplied for each setting. * - * @return PJ_SUCCESS on success or the appropriate error code. + * @return PJ_SUCCESS on success or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_dev_get_setting(pjmedia_vid_dev_index id, - pjmedia_vid_dev_cap cap, - void *pval); + pjmedia_vid_dev_cap cap, + void *pval); /** * Enum all video devices installed in the system. * - * @param info Array of info to be initialized. - * @param count On input, specifies max elements in the array. - * On return, it contains actual number of elements - * that have been initialized. + * @param info Array of info to be initialized. + * @param count On input, specifies max elements in the array. + * On return, it contains actual number of elements + * that have been initialized. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_enum_devs(pjmedia_vid_dev_info info[], - unsigned *count); + unsigned *count); /* @@ -8257,14 +8256,14 @@ typedef struct pjsua_vid_preview_param * * Default: PJMEDIA_VID_DEFAULT_RENDER_DEV */ - pjmedia_vid_dev_index rend_id; + pjmedia_vid_dev_index rend_id; /** * Show window initially. * * Default: PJ_TRUE. */ - pj_bool_t show; + pj_bool_t show; /** * Window flags. The value is a bitmask combination of @@ -8272,7 +8271,7 @@ typedef struct pjsua_vid_preview_param * * Default: 0. */ - unsigned wnd_flags; + unsigned wnd_flags; /** * Media format. Initialize this with #pjmedia_format_init_video(). @@ -8286,7 +8285,7 @@ typedef struct pjsua_vid_preview_param * PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW capability and the capability * is not read-only. */ - pjmedia_vid_dev_hwnd wnd; + pjmedia_vid_dev_hwnd wnd; } pjsua_vid_preview_param; @@ -8294,7 +8293,7 @@ typedef struct pjsua_vid_preview_param /** * Initialize pjsua_vid_preview_param * - * @param p The parameter to be initialized. + * @param p The parameter to be initialized. */ PJ_DECL(void) pjsua_vid_preview_param_default(pjsua_vid_preview_param *p); @@ -8304,21 +8303,21 @@ PJ_DECL(void) pjsua_vid_preview_param_default(pjsua_vid_preview_param *p); * querying device's capability for PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW * capability. * - * @param id The capture device ID. + * @param id The capture device ID. * - * @return PJ_TRUE if it has. + * @return PJ_TRUE if it has. */ PJ_DECL(pj_bool_t) pjsua_vid_preview_has_native(pjmedia_vid_dev_index id); /** * Start video preview window for the specified capture device. * - * @param id The capture device ID where its preview will be - * started. - * @param p Optional video preview parameters. Specify NULL - * to use default values. + * @param id The capture device ID where its preview will be + * started. + * @param p Optional video preview parameters. Specify NULL + * to use default values. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_preview_start(pjmedia_vid_dev_index id, const pjsua_vid_preview_param *p); @@ -8326,32 +8325,32 @@ PJ_DECL(pj_status_t) pjsua_vid_preview_start(pjmedia_vid_dev_index id, /** * Get the preview window handle associated with the capture device, if any. * - * @param id The capture device ID. + * @param id The capture device ID. * - * @return The window ID of the preview window for the - * specified capture device ID, or PJSUA_INVALID_ID if - * preview has not been started for the device. + * @return The window ID of the preview window for the + * specified capture device ID, or PJSUA_INVALID_ID if + * preview has not been started for the device. */ PJ_DECL(pjsua_vid_win_id) pjsua_vid_preview_get_win(pjmedia_vid_dev_index id); /** * Get video conference slot ID of the specified capture device, if any. * - * @param id The capture device ID. + * @param id The capture device ID. * - * @return The video conference slot ID of the specified capture - * device ID, or PJSUA_INVALID_ID if preview has not been - * started for the device. + * @return The video conference slot ID of the specified capture + * device ID, or PJSUA_INVALID_ID if preview has not been + * started for the device. */ PJ_DECL(pjsua_conf_port_id) pjsua_vid_preview_get_vid_conf_port( - pjmedia_vid_dev_index id); + pjmedia_vid_dev_index id); /** * Stop video preview. * - * @param id The capture device ID. + * @param id The capture device ID. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_preview_stop(pjmedia_vid_dev_index id); @@ -8391,7 +8390,7 @@ typedef struct pjsua_vid_win_info /** * Window show status. The window is hidden if false. */ - pj_bool_t show; + pj_bool_t show; /** * Window position. @@ -8409,24 +8408,24 @@ typedef struct pjsua_vid_win_info /** * Enumerates all video windows. * - * @param wids Array of window ID to be initialized. - * @param count On input, specifies max elements in the array. - * On return, it contains actual number of elements - * that have been initialized. + * @param wids Array of window ID to be initialized. + * @param count On input, specifies max elements in the array. + * On return, it contains actual number of elements + * that have been initialized. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_enum_wins(pjsua_vid_win_id wids[], - unsigned *count); + unsigned *count); /** * Get window info. * - * @param wid The video window ID. - * @param wi The video window info to be initialized. + * @param wid The video window ID. + * @param wi The video window info to be initialized. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_win_get_info(pjsua_vid_win_id wid, pjsua_vid_win_info *wi); @@ -8436,11 +8435,11 @@ PJ_DECL(pj_status_t) pjsua_vid_win_get_info(pjsua_vid_win_id wid, * (pjsua_vid_win_info.is_native=PJ_TRUE), on which native windowing API * must be used instead. * - * @param wid The video window ID. - * @param show Set to PJ_TRUE to show the window, PJ_FALSE to - * hide the window. + * @param wid The video window ID. + * @param show Set to PJ_TRUE to show the window, PJ_FALSE to + * hide the window. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_win_set_show(pjsua_vid_win_id wid, pj_bool_t show); @@ -8450,10 +8449,10 @@ PJ_DECL(pj_status_t) pjsua_vid_win_set_show(pjsua_vid_win_id wid, * (pjsua_vid_win_info.is_native=PJ_TRUE), on which native windowing API * must be used instead. * - * @param wid The video window ID. - * @param pos The window position. + * @param wid The video window ID. + * @param pos The window position. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_win_set_pos(pjsua_vid_win_id wid, const pjmedia_coord *pos); @@ -8463,10 +8462,10 @@ PJ_DECL(pj_status_t) pjsua_vid_win_set_pos(pjsua_vid_win_id wid, * (pjsua_vid_win_info.is_native=PJ_TRUE), on which native windowing API * must be used instead. * - * @param wid The video window ID. - * @param size The new window size. + * @param wid The video window ID. + * @param size The new window size. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_win_set_size(pjsua_vid_win_id wid, const pjmedia_rect_size *size); @@ -8477,10 +8476,10 @@ PJ_DECL(pj_status_t) pjsua_vid_win_set_size(pjsua_vid_win_id wid, * allows the output window to be changed on-the-fly. Currently it is only * supported on Android. * - * @param wid The video window ID. - * @param win The new output window. + * @param wid The video window ID. + * @param win The new output window. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_win_set_win(pjsua_vid_win_id wid, const pjmedia_vid_dev_hwnd *win); @@ -8491,15 +8490,15 @@ PJ_DECL(pj_status_t) pjsua_vid_win_set_win(pjsua_vid_win_id wid, * This operation is not valid for native windows (pjsua_vid_win_info.is_native * =PJ_TRUE), on which native windowing API must be used instead. * - * @param wid The video window ID. - * @param angle The rotation angle in degrees, must be multiple of 90. - * Specify positive value for clockwise rotation or - * negative value for counter-clockwise rotation. + * @param wid The video window ID. + * @param angle The rotation angle in degrees, must be multiple of 90. + * Specify positive value for clockwise rotation or + * negative value for counter-clockwise rotation. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_win_rotate(pjsua_vid_win_id wid, - int angle); + int angle); /** @@ -8507,14 +8506,14 @@ PJ_DECL(pj_status_t) pjsua_vid_win_rotate(pjsua_vid_win_id wid, * underlying video device supports PJMEDIA_VID_DEV_CAP_OUTPUT_FULLSCREEN * capability. Currently it is only supported on SDL backend. * - * @param wid The video window ID. - * @param mode Fullscreen mode, see pjmedia_vid_dev_fullscreen_flag. + * @param wid The video window ID. + * @param mode Fullscreen mode, see pjmedia_vid_dev_fullscreen_flag. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_win_set_fullscreen( - pjsua_vid_win_id wid, - pjmedia_vid_dev_fullscreen_flag mode); + pjsua_vid_win_id wid, + pjmedia_vid_dev_fullscreen_flag mode); /* @@ -8524,57 +8523,57 @@ PJ_DECL(pj_status_t) pjsua_vid_win_set_fullscreen( /** * Enum all supported video codecs in the system. * - * @param id Array of ID to be initialized. - * @param count On input, specifies max elements in the array. - * On return, it contains actual number of elements - * that have been initialized. + * @param id Array of ID to be initialized. + * @param count On input, specifies max elements in the array. + * On return, it contains actual number of elements + * that have been initialized. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_enum_codecs( pjsua_codec_info id[], - unsigned *count ); + unsigned *count ); /** * Change video codec priority. * - * @param codec_id Codec ID, which is a string that uniquely identify - * the codec (such as "H263/90000"). Please see pjsua - * manual or pjmedia codec reference for details. - * @param priority Codec priority, 0-255, where zero means to disable - * the codec. + * @param codec_id Codec ID, which is a string that uniquely identify + * the codec (such as "H263/90000"). Please see pjsua + * manual or pjmedia codec reference for details. + * @param priority Codec priority, 0-255, where zero means to disable + * the codec. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_codec_set_priority( const pj_str_t *codec_id, - pj_uint8_t priority ); + pj_uint8_t priority ); /** * Get video codec parameters. * - * @param codec_id Codec ID. - * @param param Structure to receive video codec parameters. + * @param codec_id Codec ID. + * @param param Structure to receive video codec parameters. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_codec_get_param( - const pj_str_t *codec_id, - pjmedia_vid_codec_param *param); + const pj_str_t *codec_id, + pjmedia_vid_codec_param *param); /** * Set video codec parameters. * - * @param codec_id Codec ID. - * @param param Codec parameter to set. Set to NULL to reset - * codec parameter to library default settings. + * @param codec_id Codec ID. + * @param param Codec parameter to set. Set to NULL to reset + * codec parameter to library default settings. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_codec_set_param( - const pj_str_t *codec_id, - const pjmedia_vid_codec_param *param); + const pj_str_t *codec_id, + const pjmedia_vid_codec_param *param); /* @@ -8589,29 +8588,29 @@ PJ_DECL(pj_status_t) pjsua_vid_codec_set_param( typedef struct pjsua_vid_conf_port_info { /** Conference port number. */ - pjsua_conf_port_id slot_id; + pjsua_conf_port_id slot_id; /** Port name. */ - pj_str_t name; + pj_str_t name; /** Format. */ - pjmedia_format format; + pjmedia_format format; /** Number of listeners in the array. */ - unsigned listener_cnt; + unsigned listener_cnt; /** Array of listeners (in other words, ports where this port is * transmitting to). */ - pjsua_conf_port_id listeners[PJSUA_MAX_CONF_PORTS]; + pjsua_conf_port_id listeners[PJSUA_MAX_CONF_PORTS]; /** Number of transmitters in the array. */ - unsigned transmitter_cnt; + unsigned transmitter_cnt; /** Array of transmitters (in other words, ports where this port is * receiving from). */ - pjsua_conf_port_id transmitters[PJSUA_MAX_CONF_PORTS]; + pjsua_conf_port_id transmitters[PJSUA_MAX_CONF_PORTS]; } pjsua_vid_conf_port_info; @@ -8619,7 +8618,7 @@ typedef struct pjsua_vid_conf_port_info /** * Get current number of active ports in the bridge. * - * @return The number. + * @return The number. */ PJ_DECL(unsigned) pjsua_vid_conf_get_active_ports(void); @@ -8627,28 +8626,28 @@ PJ_DECL(unsigned) pjsua_vid_conf_get_active_ports(void); /** * Enumerate all video conference ports. * - * @param id Array of conference port ID to be initialized. - * @param count On input, specifies max elements in the array. - * On return, it contains actual number of elements - * that have been initialized. + * @param id Array of conference port ID to be initialized. + * @param count On input, specifies max elements in the array. + * On return, it contains actual number of elements + * that have been initialized. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_conf_enum_ports(pjsua_conf_port_id id[], - unsigned *count); + unsigned *count); /** * Get information about the specified video conference port * - * @param port_id Port identification. - * @param info Pointer to store the port info. + * @param port_id Port identification. + * @param info Pointer to store the port info. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_conf_get_port_info( - pjsua_conf_port_id port_id, - pjsua_vid_conf_port_info *info); + pjsua_conf_port_id port_id, + pjsua_vid_conf_port_info *info); /** @@ -8657,18 +8656,18 @@ PJ_DECL(pj_status_t) pjsua_vid_conf_get_port_info( * For media ports that are created by PJSUA-LIB (such as calls, AVI player), * PJSUA-LIB will automatically add the port to the bridge. * - * @param pool Pool to use. - * @param port Media port to be added to the bridge. - * @param param Currently this is not used and must be set to NULL. - * @param p_id Optional pointer to receive the conference - * slot id. + * @param pool Pool to use. + * @param port Media port to be added to the bridge. + * @param param Currently this is not used and must be set to NULL. + * @param p_id Optional pointer to receive the conference + * slot id. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_conf_add_port(pj_pool_t *pool, - pjmedia_port *port, - const void *param, - pjsua_conf_port_id *p_id); + pjmedia_port *port, + const void *param, + pjsua_conf_port_id *p_id); /** @@ -8676,9 +8675,9 @@ PJ_DECL(pj_status_t) pjsua_vid_conf_add_port(pj_pool_t *pool, * only call this function if it registered the port manually with previous * call to #pjsua_vid_conf_add_port(). * - * @param port_id The slot id of the port to be removed. + * @param port_id The slot id of the port to be removed. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_conf_remove_port(pjsua_conf_port_id port_id); @@ -8695,27 +8694,27 @@ PJ_DECL(pj_status_t) pjsua_vid_conf_remove_port(pjsua_conf_port_id port_id); * this function twice, with the second one having the arguments * reversed. * - * @param source Port ID of the source media/transmitter. - * @param sink Port ID of the destination media/received. - * @param param Currently this is not used and must be set to NULL. + * @param source Port ID of the source media/transmitter. + * @param sink Port ID of the destination media/received. + * @param param Currently this is not used and must be set to NULL. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_conf_connect(pjsua_conf_port_id source, - pjsua_conf_port_id sink, - const void *param); + pjsua_conf_port_id sink, + const void *param); /** * Disconnect video flow from the source to destination port. * - * @param source Port ID of the source media/transmitter. - * @param sink Port ID of the destination media/received. + * @param source Port ID of the source media/transmitter. + * @param sink Port ID of the destination media/received. * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DECL(pj_status_t) pjsua_vid_conf_disconnect(pjsua_conf_port_id source, - pjsua_conf_port_id sink); + pjsua_conf_port_id sink); /** @@ -8725,10 +8724,10 @@ PJ_DECL(pj_status_t) pjsua_vid_conf_disconnect(pjsua_conf_port_id source, * has changed, video conference needs to be informed to update its * internal states. * - * @param port_id The slot id of the port to be updated. + * @param port_id The slot id of the port to be updated. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. */ PJ_DECL(pj_status_t) pjsua_vid_conf_update_port(pjsua_conf_port_id port_id); @@ -8746,4 +8745,4 @@ PJ_DECL(pj_status_t) pjsua_vid_conf_update_port(pjsua_conf_port_id port_id); PJ_END_DECL -#endif /* __PJSUA_H__ */ +#endif /* __PJSUA_H__ */ diff --git a/pjsip/include/pjsua-lib/pjsua_internal.h b/pjsip/include/pjsua-lib/pjsua_internal.h index 8d35121d04..2e849b45d2 100644 --- a/pjsip/include/pjsua-lib/pjsua_internal.h +++ b/pjsip/include/pjsua-lib/pjsua_internal.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,71 +38,71 @@ typedef struct pjsua_call_media pjsua_call_media; */ struct pjsua_call_media { - pjsua_call *call; /**< Parent call. */ - pjmedia_type type; /**< Media type. */ - unsigned idx; /**< This media index in parent call. */ - pj_str_t rem_mid; /**< Remote SDP "a=mid" attribute. */ - pjsua_call_media_status state; /**< Media state. */ + pjsua_call *call; /**< Parent call. */ + pjmedia_type type; /**< Media type. */ + unsigned idx; /**< This media index in parent call. */ + pj_str_t rem_mid; /**< Remote SDP "a=mid" attribute. */ + pjsua_call_media_status state; /**< Media state. */ pjsua_call_media_status prev_state;/**< Previous media state. */ - pjmedia_dir def_dir; /**< Default media direction. */ - pjmedia_dir dir; /**< Current media direction. */ + pjmedia_dir def_dir; /**< Default media direction. */ + pjmedia_dir dir; /**< Current media direction. */ /** The stream */ struct { - /** Audio stream */ - struct { - pjmedia_stream *stream; /**< The audio stream. */ - pjmedia_port *media_port;/**< The media port. */ - pj_bool_t destroy_port;/**< Destroy the media port? */ - int conf_slot; /**< Slot # in conference bridge. */ - } a; - - /** Video stream */ - struct { - pjmedia_vid_stream *stream; /**< The video stream. */ - pjsua_conf_port_id strm_enc_slot; /**< Stream encode slot */ - pjsua_conf_port_id strm_dec_slot; /**< Stream decode slot */ - pjsua_vid_win_id cap_win_id;/**< The video capture window */ - pjsua_vid_win_id rdr_win_id;/**< The video render window */ - pjmedia_vid_dev_index cap_dev; /**< The video capture device */ - pjmedia_vid_dev_index rdr_dev; /**< The video-in render device */ - } v; + /** Audio stream */ + struct { + pjmedia_stream *stream; /**< The audio stream. */ + pjmedia_port *media_port;/**< The media port. */ + pj_bool_t destroy_port;/**< Destroy the media port? */ + int conf_slot; /**< Slot # in conference bridge. */ + } a; + + /** Video stream */ + struct { + pjmedia_vid_stream *stream; /**< The video stream. */ + pjsua_conf_port_id strm_enc_slot; /**< Stream encode slot */ + pjsua_conf_port_id strm_dec_slot; /**< Stream decode slot */ + pjsua_vid_win_id cap_win_id;/**< The video capture window */ + pjsua_vid_win_id rdr_win_id;/**< The video render window */ + pjmedia_vid_dev_index cap_dev; /**< The video capture device */ + pjmedia_vid_dev_index rdr_dev; /**< The video-in render device */ + } v; } strm; - pj_uint32_t ssrc; /**< RTP SSRC */ - pj_uint32_t rtp_tx_ts; /**< Initial RTP timestamp for sender. */ - pj_uint16_t rtp_tx_seq;/**< Initial RTP sequence for sender. */ - pj_uint8_t rtp_tx_seq_ts_set; - /**< Bitmask flags if initial RTP sequence - and/or timestamp for sender are set. - bit 0/LSB : sequence flag - bit 1 : timestamp flag */ - - pjmedia_type prev_type; /**< Previous media type */ - pjmedia_stream_info prev_aud_si; /**< Prev audio stream info */ - pjmedia_vid_stream_info prev_vid_si; /**< Prev video stream info */ - pj_bool_t prev_srtp_use; /**< Prev SRTP use */ - pjmedia_srtp_info prev_srtp_info;/**< Prev SRTP transport info*/ - pj_bool_t prev_ice_use; /**< Prev ICE use */ - pjmedia_ice_transport_info prev_ice_info; /**< Prev ICE transport info */ - - pjmedia_transport *tp; /**< Current media transport (can be 0) */ - pj_status_t tp_ready; /**< Media transport status. */ - pj_status_t tp_result; /**< Media transport creation result. */ - pjmedia_transport *tp_orig; /**< Original media transport */ - pj_bool_t tp_auto_del; /**< May delete media transport */ - pjsua_med_tp_st tp_st; /**< Media transport state */ + pj_uint32_t ssrc; /**< RTP SSRC */ + pj_uint32_t rtp_tx_ts; /**< Initial RTP timestamp for sender. */ + pj_uint16_t rtp_tx_seq;/**< Initial RTP sequence for sender. */ + pj_uint8_t rtp_tx_seq_ts_set; + /**< Bitmask flags if initial RTP sequence + and/or timestamp for sender are set. + bit 0/LSB : sequence flag + bit 1 : timestamp flag */ + + pjmedia_type prev_type; /**< Previous media type */ + pjmedia_stream_info prev_aud_si; /**< Prev audio stream info */ + pjmedia_vid_stream_info prev_vid_si; /**< Prev video stream info */ + pj_bool_t prev_srtp_use; /**< Prev SRTP use */ + pjmedia_srtp_info prev_srtp_info;/**< Prev SRTP transport info*/ + pj_bool_t prev_ice_use; /**< Prev ICE use */ + pjmedia_ice_transport_info prev_ice_info; /**< Prev ICE transport info */ + + pjmedia_transport *tp; /**< Current media transport (can be 0) */ + pj_status_t tp_ready; /**< Media transport status. */ + pj_status_t tp_result; /**< Media transport creation result. */ + pjmedia_transport *tp_orig; /**< Original media transport */ + pj_bool_t tp_auto_del; /**< May delete media transport */ + pjsua_med_tp_st tp_st; /**< Media transport state */ pj_bool_t use_custom_med_tp;/**< Use custom media transport? */ - pj_bool_t enable_rtcp_mux;/**< Enable RTP& RTCP multiplexing?*/ - pj_sockaddr rtp_addr; /**< Current RTP source address - (used to update ICE default - address) */ - pjmedia_srtp_use rem_srtp_use; /**< Remote's SRTP usage policy. */ - pj_timestamp last_req_keyframe;/**< Last TX keyframe request. */ + pj_bool_t enable_rtcp_mux;/**< Enable RTP& RTCP multiplexing?*/ + pj_sockaddr rtp_addr; /**< Current RTP source address + (used to update ICE default + address) */ + pjmedia_srtp_use rem_srtp_use; /**< Remote's SRTP usage policy. */ + pj_timestamp last_req_keyframe;/**< Last TX keyframe request. */ - pj_bool_t use_upnp; /**< Use UPnP? */ - pj_sockaddr mapped_addr[2]; /* UPnP mapped address. */ + pj_bool_t use_upnp; /**< Use UPnP? */ + pj_sockaddr mapped_addr[2]; /* UPnP mapped address. */ pjsua_med_tp_state_cb med_init_cb;/**< Media transport initialization callback. */ @@ -117,7 +116,7 @@ struct pjsua_call_media /** * Maximum number of SDP "m=" lines to be supported. */ -#define PJSUA_MAX_CALL_MEDIA PJMEDIA_MAX_SDP_MEDIA +#define PJSUA_MAX_CALL_MEDIA PJMEDIA_MAX_SDP_MEDIA /* Call answer's list. */ typedef struct call_answer @@ -126,7 +125,7 @@ typedef struct call_answer pjsua_msg_data *msg_data; /**< Answer's headers list. */ pj_str_t *reason; /**< Answer's reason phrase. */ unsigned code; /**< Answer's status code. */ - pjsua_call_setting *opt; /**< Answer's call setting. */ + pjsua_call_setting *opt; /**< Answer's call setting. */ } call_answer; @@ -145,50 +144,50 @@ typedef enum pjsua_op_state { */ struct pjsua_call { - unsigned index; /**< Index in pjsua array. */ - pjsua_call_setting opt; /**< Call setting. */ - pj_bool_t opt_inited;/**< Initial call setting has been set, - to avoid different opt in answer. */ - pjsip_inv_session *inv; /**< The invite session. */ - void *user_data; /**< User/application data. */ - pjsip_status_code last_code; /**< Last status code seen. */ - pj_str_t last_text; /**< Last status text seen. */ - pj_time_val start_time;/**< First INVITE sent/received. */ - pj_time_val res_time; /**< First response sent/received. */ - pj_time_val conn_time; /**< Connected/confirmed time. */ - pj_time_val dis_time; /**< Disconnect time. */ - pjsua_acc_id acc_id; /**< Account index being used. */ - int secure_level;/**< Signaling security level. */ - pjsua_call_hold_type call_hold_type; /**< How to do call hold. */ - pj_bool_t local_hold;/**< Flag for call-hold by local. */ - void *hold_msg; /**< Outgoing hold tx_data. */ - pj_str_t cname; /**< RTCP CNAME. */ - char cname_buf[16];/**< cname buffer. */ - - unsigned med_cnt; /**< Number of media in SDP. */ + unsigned index; /**< Index in pjsua array. */ + pjsua_call_setting opt; /**< Call setting. */ + pj_bool_t opt_inited;/**< Initial call setting has been set, + to avoid different opt in answer. */ + pjsip_inv_session *inv; /**< The invite session. */ + void *user_data; /**< User/application data. */ + pjsip_status_code last_code; /**< Last status code seen. */ + pj_str_t last_text; /**< Last status text seen. */ + pj_time_val start_time;/**< First INVITE sent/received. */ + pj_time_val res_time; /**< First response sent/received. */ + pj_time_val conn_time; /**< Connected/confirmed time. */ + pj_time_val dis_time; /**< Disconnect time. */ + pjsua_acc_id acc_id; /**< Account index being used. */ + int secure_level;/**< Signaling security level. */ + pjsua_call_hold_type call_hold_type; /**< How to do call hold. */ + pj_bool_t local_hold;/**< Flag for call-hold by local. */ + void *hold_msg; /**< Outgoing hold tx_data. */ + pj_str_t cname; /**< RTCP CNAME. */ + char cname_buf[16];/**< cname buffer. */ + + unsigned med_cnt; /**< Number of media in SDP. */ pjsua_call_media media[PJSUA_MAX_CALL_MEDIA]; /**< Array of media */ - unsigned med_prov_cnt;/**< Number of provisional media. */ - pjsua_call_media media_prov[PJSUA_MAX_CALL_MEDIA]; - /**< Array of provisional media. */ - pj_bool_t med_update_success; - /**< Is media update successful? */ - pj_bool_t hanging_up;/**< Is call in the process of hangup? */ - - int audio_idx; /**< First active audio media. */ + unsigned med_prov_cnt;/**< Number of provisional media. */ + pjsua_call_media media_prov[PJSUA_MAX_CALL_MEDIA]; + /**< Array of provisional media. */ + pj_bool_t med_update_success; + /**< Is media update successful? */ + pj_bool_t hanging_up;/**< Is call in the process of hangup? */ + + int audio_idx; /**< First active audio media. */ pj_mutex_t *med_ch_mutex;/**< Media channel callback's mutex. */ - pjsua_med_tp_state_cb med_ch_cb;/**< Media channel callback. */ + pjsua_med_tp_state_cb med_ch_cb;/**< Media channel callback. */ pjsua_med_tp_state_info med_ch_info;/**< Media channel info. */ - pjsip_evsub *xfer_sub; /**< Xfer server subscription, if this - call was triggered by xfer. */ - pj_stun_nat_type rem_nat_type; /**< NAT type of remote endpoint. */ + pjsip_evsub *xfer_sub; /**< Xfer server subscription, if this + call was triggered by xfer. */ + pj_stun_nat_type rem_nat_type; /**< NAT type of remote endpoint. */ - char last_text_buf_[128]; /**< Buffer for last_text. */ + char last_text_buf_[128]; /**< Buffer for last_text. */ struct { - int retry_cnt; /**< Retry count. */ - } lock_codec; /**< Data for codec locking when answer - contains multiple codecs. */ + int retry_cnt; /**< Retry count. */ + } lock_codec; /**< Data for codec locking when answer + contains multiple codecs. */ struct { pjsip_dialog *dlg; /**< Call dialog. */ @@ -200,48 +199,48 @@ struct pjsua_call pjsua_msg_data *msg_data;/**< Headers for outgoing INVITE. */ pj_bool_t hangup; /**< Call is hangup? */ } out_call; - struct { + struct { call_answer answers;/**< A list of call answers. */ - pj_bool_t hangup;/**< Call is hangup? */ - pjsip_dialog *replaced_dlg; /**< Replaced dialog. */ + pj_bool_t hangup;/**< Call is hangup? */ + pjsip_dialog *replaced_dlg; /**< Replaced dialog. */ } inc_call; } call_var; } async_call; /**< Temporary storage for async outgoing/incoming call. */ - pj_bool_t rem_offerer; /**< Was remote SDP offerer? */ - unsigned rem_aud_cnt; /**< No of active audio in last remote - offer. */ - unsigned rem_vid_cnt; /**< No of active video in last remote - offer. */ + pj_bool_t rem_offerer; /**< Was remote SDP offerer? */ + unsigned rem_aud_cnt; /**< No of active audio in last remote + offer. */ + unsigned rem_vid_cnt; /**< No of active video in last remote + offer. */ - pj_bool_t rx_reinv_async;/**< on_call_rx_reinvite() async. */ - pj_timer_entry reinv_timer; /**< Reinvite retry timer. */ - pj_bool_t reinv_pending;/**< Pending until CONFIRMED state. */ - pj_bool_t reinv_ice_sent;/**< Has reinvite for ICE upd sent? */ - pjsip_rx_data *incoming_data;/**< Cloned incoming call rdata. - On pjsua2, when handling incoming - call, onCreateMediaTransport() will - not be called since the call isn't - created yet. This temporary - variable is used to handle such - case, see ticket #1916. */ + pj_bool_t rx_reinv_async;/**< on_call_rx_reinvite() async. */ + pj_timer_entry reinv_timer; /**< Reinvite retry timer. */ + pj_bool_t reinv_pending;/**< Pending until CONFIRMED state. */ + pj_bool_t reinv_ice_sent;/**< Has reinvite for ICE upd sent? */ + pjsip_rx_data *incoming_data;/**< Cloned incoming call rdata. + On pjsua2, when handling incoming + call, onCreateMediaTransport() will + not be called since the call isn't + created yet. This temporary + variable is used to handle such + case, see ticket #1916. */ struct { - pj_bool_t enabled; - pj_bool_t remote_sup; - pj_bool_t remote_dlg_est; - pjsua_op_state trickling; - int retrans18x_count; - pj_bool_t pending_info; - pj_timer_entry timer; + pj_bool_t enabled; + pj_bool_t remote_sup; + pj_bool_t remote_dlg_est; + pjsua_op_state trickling; + int retrans18x_count; + pj_bool_t pending_info; + pj_timer_entry timer; } trickle_ice; - pj_timer_entry hangup_timer; /**< Hangup retry timer. */ - unsigned hangup_retry; /**< Number of hangup retries. */ - unsigned hangup_code; /**< Hangup code. */ - pj_str_t hangup_reason; /**< Hangup reason. */ - pjsua_msg_data *hangup_msg_data;/**< Hangup message data. */ + pj_timer_entry hangup_timer; /**< Hangup retry timer. */ + unsigned hangup_retry; /**< Number of hangup retries. */ + unsigned hangup_code; /**< Hangup code. */ + pj_str_t hangup_reason; /**< Hangup reason. */ + pjsua_msg_data *hangup_msg_data;/**< Hangup message data. */ }; @@ -251,13 +250,13 @@ struct pjsua_call struct pjsua_srv_pres { PJ_DECL_LIST_MEMBER(struct pjsua_srv_pres); - pjsip_evsub *sub; /**< The evsub. */ - char *remote; /**< Remote URI. */ - int acc_id; /**< Account ID. */ - pjsip_dialog *dlg; /**< Dialog. */ - unsigned expires; /**< "expires" value in the request, - PJSIP_EXPIRES_NOT_SPECIFIED - if not present. */ + pjsip_evsub *sub; /**< The evsub. */ + char *remote; /**< Remote URI. */ + int acc_id; /**< Account ID. */ + pjsip_dialog *dlg; /**< Dialog. */ + unsigned expires; /**< "expires" value in the request, + PJSIP_EXPIRES_NOT_SPECIFIED + if not present. */ }; /** @@ -265,75 +264,75 @@ struct pjsua_srv_pres */ typedef struct pjsua_acc { - pj_pool_t *pool; /**< Pool for this account. */ - pjsua_acc_config cfg; /**< Account configuration. */ - pj_bool_t valid; /**< Is this account valid? */ - - int index; /**< Index in accounts array. */ - pj_str_t display; /**< Display name, if any. */ - pj_str_t user_part; /**< User part of local URI. */ - pj_bool_t is_sips; /**< Local URI uses "sips"? */ - pj_str_t contact; /**< Our Contact header. */ + pj_pool_t *pool; /**< Pool for this account. */ + pjsua_acc_config cfg; /**< Account configuration. */ + pj_bool_t valid; /**< Is this account valid? */ + + int index; /**< Index in accounts array. */ + pj_str_t display; /**< Display name, if any. */ + pj_str_t user_part; /**< User part of local URI. */ + pj_bool_t is_sips; /**< Local URI uses "sips"? */ + pj_str_t contact; /**< Our Contact header. */ pj_str_t reg_contact; /**< Contact header for REGISTER. - It may be different than acc - contact if outbound is used */ - pj_bool_t contact_rewritten; - /**< Contact rewrite has been done? */ + It may be different than acc + contact if outbound is used */ + pj_bool_t contact_rewritten; + /**< Contact rewrite has been done? */ pjsip_host_port via_addr; /**< Address for Via header */ pjsip_transport *via_tp; /**< Transport associated with the Via address */ - pj_str_t srv_domain; /**< Host part of reg server. */ - int srv_port; /**< Port number of reg server. */ + pj_str_t srv_domain; /**< Host part of reg server. */ + int srv_port; /**< Port number of reg server. */ - pjsip_regc *regc; /**< Client registration session. */ - pj_status_t reg_last_err; /**< Last registration error. */ - int reg_last_code; /**< Last status last register. */ + pjsip_regc *regc; /**< Client registration session. */ + pj_status_t reg_last_err; /**< Last registration error. */ + int reg_last_code; /**< Last status last register. */ pj_str_t reg_mapped_addr;/**< Our addr as seen by reg srv. Only if allow_sdp_nat_rewrite is set */ struct { - pj_bool_t active; /**< Flag of reregister status. */ - pj_timer_entry timer; /**< Timer for reregistration. */ - void *reg_tp; /**< Transport for registration. */ - unsigned attempt_cnt; /**< Attempt counter. */ - } auto_rereg; /**< Reregister/reconnect data. */ + pj_bool_t active; /**< Flag of reregister status. */ + pj_timer_entry timer; /**< Timer for reregistration. */ + void *reg_tp; /**< Transport for registration. */ + unsigned attempt_cnt; /**< Attempt counter. */ + } auto_rereg; /**< Reregister/reconnect data. */ - pj_timer_entry ka_timer; /**< Keep-alive timer for UDP. */ - pjsip_transport *ka_transport; /**< Transport for keep-alive. */ - pj_sockaddr ka_target; /**< Destination address for K-A */ - unsigned ka_target_len; /**< Length of ka_target. */ + pj_timer_entry ka_timer; /**< Keep-alive timer for UDP. */ + pjsip_transport *ka_transport; /**< Transport for keep-alive. */ + pj_sockaddr ka_target; /**< Destination address for K-A */ + unsigned ka_target_len; /**< Length of ka_target. */ - pjsip_route_hdr route_set; /**< Complete route set inc. outbnd.*/ - pj_uint32_t global_route_crc; /** CRC of global route setting. */ - pj_uint32_t local_route_crc; /** CRC of account route setting.*/ + pjsip_route_hdr route_set; /**< Complete route set inc. outbnd.*/ + pj_uint32_t global_route_crc; /** CRC of global route setting. */ + pj_uint32_t local_route_crc; /** CRC of account route setting.*/ unsigned rfc5626_status;/**< SIP outbound status: 0: not used 1: requested 2: acknowledged by servers */ - pj_str_t rfc5626_instprm;/**< SIP outbound instance param. */ + pj_str_t rfc5626_instprm;/**< SIP outbound instance param. */ pj_str_t rfc5626_regprm;/**< SIP outbound reg param. */ unsigned rfc5626_flowtmr;/**< SIP outbound flow timer. */ - unsigned cred_cnt; /**< Number of credentials. */ - pjsip_cred_info cred[PJSUA_ACC_MAX_PROXIES]; /**< Complete creds. */ + unsigned cred_cnt; /**< Number of credentials. */ + pjsip_cred_info cred[PJSUA_ACC_MAX_PROXIES]; /**< Complete creds. */ - pj_bool_t online_status; /**< Our online status. */ - pjrpid_element rpid; /**< RPID element information. */ - pjsua_srv_pres pres_srv_list; /**< Server subscription list. */ - pjsip_publishc *publish_sess; /**< Client publication session. */ - pj_bool_t publish_state; /**< Last published online status */ + pj_bool_t online_status; /**< Our online status. */ + pjrpid_element rpid; /**< RPID element information. */ + pjsua_srv_pres pres_srv_list; /**< Server subscription list. */ + pjsip_publishc *publish_sess; /**< Client publication session. */ + pj_bool_t publish_state; /**< Last published online status */ - pjsip_evsub *mwi_sub; /**< MWI client subscription */ - pjsip_dialog *mwi_dlg; /**< Dialog for MWI sub. */ + pjsip_evsub *mwi_sub; /**< MWI client subscription */ + pjsip_dialog *mwi_dlg; /**< Dialog for MWI sub. */ pj_uint16_t next_rtp_port; /**< Next RTP port to be used. */ pjsip_transport_type_e tp_type; /**< Transport type (for local acc or - transport binding) */ - pjsua_ip_change_op ip_change_op;/**< IP change process progress. */ + transport binding) */ + pjsua_ip_change_op ip_change_op;/**< IP change process progress. */ } pjsua_acc; @@ -342,47 +341,47 @@ typedef struct pjsua_acc */ typedef struct pjsua_transport_data { - int index; + int index; pjsip_transport_type_e type; - pjsip_host_port local_name; - pj_sockaddr pub_addr; + pjsip_host_port local_name; + pj_sockaddr pub_addr; union { - pjsip_transport *tp; - pjsip_tpfactory *factory; - void *ptr; + pjsip_transport *tp; + pjsip_tpfactory *factory; + void *ptr; } data; - pj_bool_t is_restarting; - pj_status_t restart_status; - pj_bool_t has_bound_addr; + pj_bool_t is_restarting; + pj_status_t restart_status; + pj_bool_t has_bound_addr; } pjsua_transport_data; /** Maximum length of subscription termination reason. */ -#define PJSUA_BUDDY_SUB_TERM_REASON_LEN 32 +#define PJSUA_BUDDY_SUB_TERM_REASON_LEN 32 /** * Buddy data. */ typedef struct pjsua_buddy { - pj_pool_t *pool; /**< Pool for this buddy. */ - unsigned index; /**< Buddy index. */ - void *user_data; /**< Application data. */ - pj_str_t uri; /**< Buddy URI. */ - pj_str_t contact; /**< Contact learned from subscrp. */ - pj_str_t name; /**< Buddy name. */ - pj_str_t display; /**< Buddy display name. */ - pj_str_t host; /**< Buddy host. */ - unsigned port; /**< Buddy port. */ - pj_bool_t monitor; /**< Should we monitor? */ - pjsip_dialog *dlg; /**< The underlying dialog. */ - pjsip_evsub *sub; /**< Buddy presence subscription */ - unsigned term_code; /**< Subscription termination code */ - pj_str_t term_reason;/**< Subscription termination reason */ - pjsip_pres_status status; /**< Buddy presence status. */ - pj_timer_entry timer; /**< Resubscription timer */ + pj_pool_t *pool; /**< Pool for this buddy. */ + unsigned index; /**< Buddy index. */ + void *user_data; /**< Application data. */ + pj_str_t uri; /**< Buddy URI. */ + pj_str_t contact; /**< Contact learned from subscrp. */ + pj_str_t name; /**< Buddy name. */ + pj_str_t display; /**< Buddy display name. */ + pj_str_t host; /**< Buddy host. */ + unsigned port; /**< Buddy port. */ + pj_bool_t monitor; /**< Should we monitor? */ + pjsip_dialog *dlg; /**< The underlying dialog. */ + pjsip_evsub *sub; /**< Buddy presence subscription */ + unsigned term_code; /**< Subscription termination code */ + pj_str_t term_reason;/**< Subscription termination reason */ + pjsip_pres_status status; /**< Buddy presence status. */ + pj_timer_entry timer; /**< Resubscription timer */ } pjsua_buddy; @@ -391,10 +390,10 @@ typedef struct pjsua_buddy */ typedef struct pjsua_file_data { - pj_bool_t type; /* 0=player, 1=playlist */ + pj_bool_t type; /* 0=player, 1=playlist */ pjmedia_port *port; - pj_pool_t *pool; - unsigned slot; + pj_pool_t *pool; + unsigned slot; } pjsua_file_data; @@ -403,33 +402,33 @@ typedef struct pjsua_file_data */ typedef struct pjsua_conf_setting { - unsigned channel_count; - unsigned samples_per_frame; - unsigned bits_per_sample; + unsigned channel_count; + unsigned samples_per_frame; + unsigned bits_per_sample; } pjsua_conf_setting; typedef struct pjsua_stun_resolve { PJ_DECL_LIST_MEMBER(struct pjsua_stun_resolve); - pj_pool_t *pool; /**< Pool */ - int ref_cnt; /**< Reference count */ - pj_bool_t destroy_flag; /**< To be destroyed */ - pj_bool_t has_result; - unsigned count; /**< # of entries */ - pj_str_t *srv; /**< Array of entries */ - unsigned idx; /**< Current index */ - void *token; /**< App token */ - pj_stun_resolve_cb cb; /**< App callback */ - pj_bool_t blocking; /**< Blocking? */ - pj_thread_t *waiter; /**< Waiting thread */ - pj_timer_entry timer; /**< Destroy timer */ - pj_status_t status; /**< Session status */ - pj_sockaddr addr; /**< Result */ - pj_stun_sock *stun_sock; /**< Testing STUN sock */ - int af; /**< Address family */ - pj_bool_t async_wait;/**< Async resolution - of STUN entry */ + pj_pool_t *pool; /**< Pool */ + int ref_cnt; /**< Reference count */ + pj_bool_t destroy_flag; /**< To be destroyed */ + pj_bool_t has_result; + unsigned count; /**< # of entries */ + pj_str_t *srv; /**< Array of entries */ + unsigned idx; /**< Current index */ + void *token; /**< App token */ + pj_stun_resolve_cb cb; /**< App callback */ + pj_bool_t blocking; /**< Blocking? */ + pj_thread_t *waiter; /**< Waiting thread */ + pj_timer_entry timer; /**< Destroy timer */ + pj_status_t status; /**< Session status */ + pj_sockaddr addr; /**< Result */ + pj_stun_sock *stun_sock; /**< Testing STUN sock */ + int af; /**< Address family */ + pj_bool_t async_wait;/**< Async resolution + of STUN entry */ } pjsua_stun_resolve; /* See also pjsua_vid_win_type_name() */ @@ -442,16 +441,16 @@ typedef enum pjsua_vid_win_type typedef struct pjsua_vid_win { - pjsua_vid_win_type type; /**< Type. */ - pj_pool_t *pool; /**< Own pool. */ - unsigned ref_cnt; /**< Reference counter. */ - pjmedia_vid_port *vp_cap; /**< Capture vidport. */ - pjmedia_vid_port *vp_rend; /**< Renderer vidport */ - pjsua_conf_port_id cap_slot; /**< Capturer conf slot */ - pjsua_conf_port_id rend_slot; /**< Renderer conf slot */ - pjmedia_vid_dev_index preview_cap_id;/**< Capture dev id */ - pj_bool_t preview_running;/**< Preview is started*/ - pj_bool_t is_native; /**< Preview is by dev */ + pjsua_vid_win_type type; /**< Type. */ + pj_pool_t *pool; /**< Own pool. */ + unsigned ref_cnt; /**< Reference counter. */ + pjmedia_vid_port *vp_cap; /**< Capture vidport. */ + pjmedia_vid_port *vp_rend; /**< Renderer vidport */ + pjsua_conf_port_id cap_slot; /**< Capturer conf slot */ + pjsua_conf_port_id rend_slot; /**< Renderer conf slot */ + pjmedia_vid_dev_index preview_cap_id;/**< Capture dev id */ + pj_bool_t preview_running;/**< Preview is started*/ + pj_bool_t is_native; /**< Preview is by dev */ } pjsua_vid_win; @@ -468,8 +467,8 @@ typedef struct pjsua_event_list { PJ_DECL_LIST_MEMBER(struct pjsua_event_list); pjmedia_event event; - pjsua_call_id call_id; - unsigned med_idx; + pjsua_call_id call_id; + unsigned med_idx; } pjsua_event_list; @@ -480,118 +479,118 @@ struct pjsua_data { /* Control: */ - pj_caching_pool cp; /**< Global pool factory. */ - pj_pool_t *pool; /**< pjsua's private pool. */ - pj_pool_t *timer_pool;/**< pjsua's timer pool. */ - pj_mutex_t *mutex; /**< Mutex protection for this data */ - unsigned mutex_nesting_level; /**< Mutex nesting level. */ - pj_thread_t *mutex_owner; /**< Mutex owner. */ - pjsua_state state; /**< Library state. */ + pj_caching_pool cp; /**< Global pool factory. */ + pj_pool_t *pool; /**< pjsua's private pool. */ + pj_pool_t *timer_pool;/**< pjsua's timer pool. */ + pj_mutex_t *mutex; /**< Mutex protection for this data */ + unsigned mutex_nesting_level; /**< Mutex nesting level. */ + pj_thread_t *mutex_owner; /**< Mutex owner. */ + pjsua_state state; /**< Library state. */ /* Logging: */ - pjsua_logging_config log_cfg; /**< Current logging config. */ - pj_oshandle_t log_file; /** medias; - pj_pool_t *sdp_pool; - Call *child; /* New outgoing call in call transfer. */ + pj_pool_t *sdp_pool; + Call *child; /* New outgoing call in call transfer. */ }; /** @@ -2203,5 +2202,5 @@ class Call } // namespace pj -#endif /* __PJSUA2_CALL_HPP__ */ +#endif /* __PJSUA2_CALL_HPP__ */ diff --git a/pjsip/include/pjsua2/config.hpp b/pjsip/include/pjsua2/config.hpp index 7ff9658c5d..2a29921cd6 100644 --- a/pjsip/include/pjsua2/config.hpp +++ b/pjsip/include/pjsua2/config.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -36,7 +35,7 @@ * file information. */ #ifndef PJSUA2_ERROR_HAS_EXTRA_INFO -# define PJSUA2_ERROR_HAS_EXTRA_INFO 1 +# define PJSUA2_ERROR_HAS_EXTRA_INFO 1 #endif /** @@ -44,7 +43,7 @@ * if the printed SDP is not needed. */ #ifndef PJSUA2_MAX_SDP_BUF_LEN -# define PJSUA2_MAX_SDP_BUF_LEN 1024 +# define PJSUA2_MAX_SDP_BUF_LEN 1024 #endif /** @@ -54,7 +53,7 @@ * See also https://github.com/pjsip/pjproject/issues/2232 */ #ifndef DEPRECATED_FOR_TICKET_2232 -# define DEPRECATED_FOR_TICKET_2232 1 +# define DEPRECATED_FOR_TICKET_2232 1 #endif /** @@ -70,4 +69,4 @@ * @} PJSUA2_CFG */ -#endif /* __PJSUA2_CONFIG_HPP__ */ +#endif /* __PJSUA2_CONFIG_HPP__ */ diff --git a/pjsip/include/pjsua2/doxygen.hpp b/pjsip/include/pjsua2/doxygen.hpp index 057e4de3c2..8811d47a3c 100644 --- a/pjsip/include/pjsua2/doxygen.hpp +++ b/pjsip/include/pjsua2/doxygen.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2012 Teluu Inc. (http://www.teluu.com) * @@ -46,4 +45,4 @@ see The PJSIP Book. -#endif /* __PJSUA2_DOXYGEN_HPP__ */ +#endif /* __PJSUA2_DOXYGEN_HPP__ */ diff --git a/pjsip/include/pjsua2/endpoint.hpp b/pjsip/include/pjsua2/endpoint.hpp index b1d3c2684d..c477b8cfba 100644 --- a/pjsip/include/pjsua2/endpoint.hpp +++ b/pjsip/include/pjsua2/endpoint.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -55,23 +54,23 @@ struct OnNatDetectionCompleteParam * the detection has failed and \a nat_type field will contain * PJ_STUN_NAT_TYPE_UNKNOWN. */ - pj_status_t status; + pj_status_t status; /** * The text describing the status, if the status is not PJ_SUCCESS. */ - string reason; + string reason; /** * This contains the NAT type as detected by the detection procedure. * This value is only valid when the \a status is PJ_SUCCESS. */ - pj_stun_nat_type natType; + pj_stun_nat_type natType; /** * Text describing that NAT type. */ - string natTypeName; + string natTypeName; }; @@ -84,26 +83,26 @@ struct OnNatCheckStunServersCompleteParam * Arbitrary user data that was passed to Endpoint::natCheckStunServers() * function. */ - Token userData; + Token userData; /** * This will contain PJ_SUCCESS if at least one usable STUN server * is found, otherwise it will contain the last error code during * the operation. */ - pj_status_t status; + pj_status_t status; /** * The server name that yields successful result. This will only * contain value if status is successful. */ - string name; + string name; /** * The server IP address and port in "IP:port" format. This will only * contain value if status is successful. */ - SocketAddress addr; + SocketAddress addr; }; /** @@ -115,12 +114,12 @@ struct OnTimerParam * Arbitrary user data that was passed to Endpoint::utilTimerSchedule() * function. */ - Token userData; + Token userData; /** * The interval of this timer, in miliseconds. */ - unsigned msecDelay; + unsigned msecDelay; }; /** @@ -128,8 +127,8 @@ struct OnTimerParam */ struct SslCertName { - pj_ssl_cert_name_type type; /**< Name type */ - string name; /**< The name */ + pj_ssl_cert_name_type type; /**< Name type */ + string name; /**< The name */ public: /** @@ -147,30 +146,30 @@ typedef std::vector SslCertNameVector; */ struct SslCertInfo { - unsigned version; /**< Certificate version */ - unsigned char serialNo[20]; /**< Serial number, array - of octets, first index - is MSB */ - string subjectCn; /**< Subject common name */ - string subjectInfo; /**< One line subject, fields - are separated by slash, e.g: - "CN=sample.org/OU=HRD" */ - - string issuerCn; /**< Issuer common name */ - string issuerInfo; /**< One line subject, fields - are separated by slash */ - - TimeVal validityStart; /**< Validity start */ - TimeVal validityEnd; /**< Validity end */ - bool validityGmt; /**< Flag if validity - date/time use GMT */ - - SslCertNameVector subjectAltName; /**< Subject alternative - name extension */ - - string raw; /**< Raw certificate in PEM - format, only available - for remote certificate */ + unsigned version; /**< Certificate version */ + unsigned char serialNo[20]; /**< Serial number, array + of octets, first index + is MSB */ + string subjectCn; /**< Subject common name */ + string subjectInfo; /**< One line subject, fields + are separated by slash, e.g: + "CN=sample.org/OU=HRD" */ + + string issuerCn; /**< Issuer common name */ + string issuerInfo; /**< One line subject, fields + are separated by slash */ + + TimeVal validityStart; /**< Validity start */ + TimeVal validityEnd; /**< Validity end */ + bool validityGmt; /**< Flag if validity + date/time use GMT */ + + SslCertNameVector subjectAltName; /**< Subject alternative + name extension */ + + string raw; /**< Raw certificate in PEM + format, only available + for remote certificate */ public: /** @@ -181,7 +180,7 @@ struct SslCertInfo /** * Check if the info is set with empty values. * - * @return True if the info is empty. + * @return True if the info is empty. */ bool isEmpty() const; @@ -203,58 +202,58 @@ struct TlsInfo * Describes whether secure socket connection is established, i.e: TLS/SSL * handshaking has been done successfully. */ - bool established; + bool established; /** * Describes secure socket protocol being used, see #pj_ssl_sock_proto. * Use bitwise OR operation to combine the protocol type. */ - unsigned protocol; + unsigned protocol; /** * Describes cipher suite being used, this will only be set when connection * is established. */ - pj_ssl_cipher cipher; + pj_ssl_cipher cipher; /** * Describes cipher name being used, this will only be set when connection * is established. */ - string cipherName; + string cipherName; /** * Describes local address. */ - SocketAddress localAddr; + SocketAddress localAddr; /** * Describes remote address. */ - SocketAddress remoteAddr; + SocketAddress remoteAddr; /** * Describes active local certificate info. Use SslCertInfo.isEmpty() * to check if the local cert info is available. */ - SslCertInfo localCertInfo; + SslCertInfo localCertInfo; /** * Describes active remote certificate info. Use SslCertInfo.isEmpty() * to check if the remote cert info is available. */ - SslCertInfo remoteCertInfo; + SslCertInfo remoteCertInfo; /** * Status of peer certificate verification. */ - unsigned verifyStatus; + unsigned verifyStatus; /** * Error messages (if any) of peer certificate verification, based on * the field verifyStatus above. */ - StringVector verifyMsgs; + StringVector verifyMsgs; public: /** @@ -265,7 +264,7 @@ struct TlsInfo /** * Check if the info is set with empty values. * - * @return True if the info is empty. + * @return True if the info is empty. */ bool isEmpty() const; @@ -286,12 +285,12 @@ struct OnTransportStateParam /** * The transport handle. */ - TransportHandle hnd; + TransportHandle hnd; /** * The transport type. */ - string type; + string type; /** * Transport current state. @@ -301,13 +300,13 @@ struct OnTransportStateParam /** * The last error code related to the transport state. */ - pj_status_t lastError; + pj_status_t lastError; /** * TLS transport info, only used if transport type is TLS. Use * TlsInfo.isEmpty() to check if this info is available. */ - TlsInfo tlsInfo; + TlsInfo tlsInfo; }; /** @@ -318,7 +317,7 @@ struct OnSelectAccountParam /** * The incoming request. */ - SipRxData rdata; + SipRxData rdata; /** * The account index to be used to handle the request. @@ -326,7 +325,7 @@ struct OnSelectAccountParam * chosen by the library. Application may change it to * another value to use another account. */ - int accountIndex; + int accountIndex; }; /** @@ -338,7 +337,7 @@ struct IpChangeParam { * * Default : PJ_TRUE */ - bool restartListener; + bool restartListener; /** * If \a restartListener is set to PJ_TRUE, some delay might be needed @@ -346,7 +345,7 @@ struct IpChangeParam { * * Default : PJSUA_TRANSPORT_RESTART_DELAY_TIME */ - unsigned restartLisDelay; + unsigned restartLisDelay; public: /** @@ -378,7 +377,7 @@ struct RegProgressParam /** * SIP status code received. */ - int code; + int code; }; /** @@ -389,18 +388,18 @@ struct OnIpChangeProgressParam /** * The IP change progress operation. */ - pjsua_ip_change_op op; + pjsua_ip_change_op op; /** * The operation progress status. */ - pj_status_t status; + pj_status_t status; /** * Information of the transport id. This is only available when the * operation is PJSUA_IP_CHANGE_OP_RESTART_LIS. */ - TransportId transportId; + TransportId transportId; /** * Information of the account id. This is only available when the @@ -410,20 +409,20 @@ struct OnIpChangeProgressParam * - PJSUA_IP_CHANGE_OP_ACC_HANGUP_CALLS * - PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS */ - int accId; + int accId; /** * Information of the call id. This is only available when the operation is * PJSUA_IP_CHANGE_OP_ACC_HANGUP_CALLS or * PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS */ - int callId; + int callId; /** * Registration information. This is only available when the operation is * PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT */ - RegProgressParam regInfo; + RegProgressParam regInfo; }; /** @@ -598,7 +597,7 @@ struct UaConfig : public PersistentObject * limit, the library must be recompiled with new PJSUA_MAX_CALLS * value. */ - unsigned maxCalls; + unsigned maxCalls; /** * Number of worker threads. Normally application will want to have at @@ -606,7 +605,7 @@ struct UaConfig : public PersistentObject * periodically, which in this case the worker thread can be set to * zero. */ - unsigned threadCnt; + unsigned threadCnt; /** * When this flag is non-zero, all callbacks that come from thread @@ -619,14 +618,14 @@ struct UaConfig : public PersistentObject * * Default: false */ - bool mainThreadOnly; + bool mainThreadOnly; /** * Array of nameservers to be used by the SIP resolver subsystem. * The order of the name server specifies the priority (first name * server will be used first, unless it is not reachable). */ - StringVector nameserver; + StringVector nameserver; /** * Specify the URL of outbound proxies to visit for all outgoing requests. @@ -635,23 +634,23 @@ struct UaConfig : public PersistentObject * route set for outgoing requests will consists of the outbound proxies * and the proxy configured in the account. */ - StringVector outboundProxies; + StringVector outboundProxies; /** * Optional user agent string (default empty). If it's empty, no * User-Agent header will be sent with outgoing requests. */ - string userAgent; + string userAgent; /** * Array of STUN servers to try. The library will try to resolve and * contact each of the STUN server entry until it finds one that is * usable. Each entry may be a domain name, host name, IP address, and * it may contain an optional port number. For example: - * - "pjsip.org" (domain name) - * - "sip.pjsip.org" (host name) - * - "pjsip.org:33478" (domain name and a non-standard port number) - * - "10.0.0.1:3478" (IP address and port number) + * - "pjsip.org" (domain name) + * - "sip.pjsip.org" (host name) + * - "pjsip.org:33478" (domain name and a non-standard port number) + * - "10.0.0.1:3478" (IP address and port number) * * When nameserver is configured in the \a pjsua_config.nameserver field, * if entry is not an IP address, it will be resolved with DNS SRV @@ -663,7 +662,7 @@ struct UaConfig : public PersistentObject * pj_gethostbyname() if it's not an IP address. Port number may be * specified if the server is not listening in standard STUN port. */ - StringVector stunServer; + StringVector stunServer; /** * This specifies if the library should try to do an IPv6 resolution of @@ -672,7 +671,7 @@ struct UaConfig : public PersistentObject * * Default: FALSE */ - bool stunTryIpv6; + bool stunTryIpv6; /** * This specifies if the library startup should ignore failure with the @@ -681,18 +680,18 @@ struct UaConfig : public PersistentObject * * Default: TRUE */ - bool stunIgnoreFailure; + bool stunIgnoreFailure; /** * Support for adding and parsing NAT type in the SDP to assist * troubleshooting. The valid values are: - * - 0: no information will be added in SDP, and parsing is disabled. - * - 1: only the NAT type number is added. - * - 2: add both NAT type number and name. + * - 0: no information will be added in SDP, and parsing is disabled. + * - 1: only the NAT type number is added. + * - 2: add both NAT type number and name. * * Default: 1 */ - int natTypeInSdp; + int natTypeInSdp; /** * Handle unsolicited NOTIFY requests containing message waiting @@ -706,7 +705,7 @@ struct UaConfig : public PersistentObject * * Default: PJ_TRUE */ - bool mwiUnsolicitedEnabled; + bool mwiUnsolicitedEnabled; /** * Specify whether to enable UPnP. @@ -716,7 +715,7 @@ struct UaConfig : public PersistentObject * * Default: FALSE */ - bool enableUpnp; + bool enableUpnp; /** * Specify which interface to use for UPnP. If empty, UPnP will use @@ -726,7 +725,7 @@ struct UaConfig : public PersistentObject * * Default: empty string */ - string upnpIfName; + string upnpIfName; public: /** @@ -747,14 +746,14 @@ struct UaConfig : public PersistentObject /** * Read this object from a container. * - * @param node Container to write values from. + * @param node Container to write values from. */ virtual void readObject(const ContainerNode &node) PJSUA2_THROW(Error); /** * Write this object to a container. * - * @param node Container to write values to. + * @param node Container to write values to. */ virtual void writeObject(ContainerNode &node) const PJSUA2_THROW(Error); @@ -767,16 +766,16 @@ struct UaConfig : public PersistentObject struct LogEntry { /** Log verbosity level of this message */ - int level; + int level; /** The log message */ - string msg; + string msg; /** ID of current thread */ - long threadId; + long threadId; /** The name of the thread that writes this log */ - string threadName; + string threadName; }; @@ -803,20 +802,20 @@ class LogWriter struct LogConfig : public PersistentObject { /** Log incoming and outgoing SIP message? Yes! */ - unsigned msgLogging; + unsigned msgLogging; /** Input verbosity level. Value 5 is reasonable. */ - unsigned level; + unsigned level; /** Verbosity level for console. Value 4 is reasonable. */ - unsigned consoleLevel; + unsigned consoleLevel; /** Log decoration. */ - unsigned decor; + unsigned decor; /** Optional log filename if app wishes the library to write to log file. */ - string filename; + string filename; /** * Additional flags to be given to pj_file_open() when opening @@ -826,13 +825,13 @@ struct LogConfig : public PersistentObject * * Default is 0. */ - unsigned fileFlags; + unsigned fileFlags; /** * Custom log writer, if required. This instance will be destroyed * by the endpoint when the endpoint is destroyed. */ - LogWriter *writer; + LogWriter *writer; public: /** Default constructor initialises with default values */ @@ -847,14 +846,14 @@ struct LogConfig : public PersistentObject /** * Read this object from a container. * - * @param node Container to write values from. + * @param node Container to write values from. */ virtual void readObject(const ContainerNode &node) PJSUA2_THROW(Error); /** * Write this object to a container. * - * @param node Container to write values to. + * @param node Container to write values to. */ virtual void writeObject(ContainerNode &node) const PJSUA2_THROW(Error); }; @@ -872,19 +871,19 @@ struct MediaConfig : public PersistentObject * If value is zero, default clock rate will be used * (PJSUA_DEFAULT_CLOCK_RATE, which by default is 16KHz). */ - unsigned clockRate; + unsigned clockRate; /** * Clock rate to be applied when opening the sound device. * If value is zero, conference bridge clock rate will be used. */ - unsigned sndClockRate; + unsigned sndClockRate; /** * Channel count be applied when opening the sound device and * conference bridge. */ - unsigned channelCount; + unsigned channelCount; /** * Specify audio frame ptime. The value here will affect the @@ -894,7 +893,7 @@ struct MediaConfig : public PersistentObject * * Default value: PJSUA_DEFAULT_AUDIO_FRAME_PTIME */ - unsigned audioFramePtime; + unsigned audioFramePtime; /** * Specify maximum number of media ports to be created in the @@ -905,7 +904,7 @@ struct MediaConfig : public PersistentObject * * Default value: PJSUA_MAX_CONF_PORTS */ - unsigned maxMediaPorts; + unsigned maxMediaPorts; /** * Specify whether the media manager should manage its own @@ -917,13 +916,13 @@ struct MediaConfig : public PersistentObject * Normally application would say yes here, unless it wants to * run everything from a single thread. */ - bool hasIoqueue; + bool hasIoqueue; /** * Specify the number of worker threads to handle incoming RTP * packets. A value of one is recommended for most applications. */ - unsigned threadCnt; + unsigned threadCnt; /** * Media quality, 0-10, according to this table: @@ -935,28 +934,28 @@ struct MediaConfig : public PersistentObject * * Default: PJSUA_DEFAULT_CODEC_QUALITY. */ - unsigned quality; + unsigned quality; /** * Specify default codec ptime. * * Default: 0 (codec specific) */ - unsigned ptime; + unsigned ptime; /** * Disable VAD? * * Default: 0 (codec specific) */ - bool noVad; + bool noVad; /** * iLBC mode (20 or 30). * * Default: 30 (PJSUA_DEFAULT_ILBC_MODE) */ - unsigned ilbcMode; + unsigned ilbcMode; /** * Percentage of RTP packet to drop in TX direction @@ -964,7 +963,7 @@ struct MediaConfig : public PersistentObject * * Default: 0 */ - unsigned txDropPct; + unsigned txDropPct; /** * Percentage of RTP packet to drop in RX direction @@ -972,7 +971,7 @@ struct MediaConfig : public PersistentObject * * Default: 0 */ - unsigned rxDropPct; + unsigned rxDropPct; /** * Echo canceller options (see pjmedia_echo_create()). @@ -981,7 +980,7 @@ struct MediaConfig : public PersistentObject * * Default: 0. */ - unsigned ecOptions; + unsigned ecOptions; /** * Echo canceller tail length, in miliseconds. Setting this to zero @@ -989,21 +988,21 @@ struct MediaConfig : public PersistentObject * * Default: PJSUA_DEFAULT_EC_TAIL_LEN */ - unsigned ecTailLen; + unsigned ecTailLen; /** * Audio capture buffer length, in milliseconds. * * Default: PJMEDIA_SND_DEFAULT_REC_LATENCY */ - unsigned sndRecLatency; + unsigned sndRecLatency; /** * Audio playback buffer length, in milliseconds. * * Default: PJMEDIA_SND_DEFAULT_PLAY_LATENCY */ - unsigned sndPlayLatency; + unsigned sndPlayLatency; /** * Jitter buffer initial prefetch delay in msec. The value must be @@ -1012,28 +1011,28 @@ struct MediaConfig : public PersistentObject * * Default: -1 (to use default stream settings, currently 0) */ - int jbInit; + int jbInit; /** * Jitter buffer minimum prefetch delay in msec. * * Default: -1 (to use default stream settings, currently codec ptime) */ - int jbMinPre; + int jbMinPre; /** * Jitter buffer maximum prefetch delay in msec. * * Default: -1 (to use default stream settings, currently 80% of jbMax) */ - int jbMaxPre; + int jbMaxPre; /** * Set maximum delay that can be accomodated by the jitter buffer msec. * * Default: -1 (to use default stream settings, currently 500 msec) */ - int jbMax; + int jbMax; /** * Set the algorithm the jitter buffer uses to discard frames in order to @@ -1050,7 +1049,7 @@ struct MediaConfig : public PersistentObject * * Default : 1 */ - int sndAutoCloseTime; + int sndAutoCloseTime; /** * Specify whether built-in/native preview should be used if available. @@ -1062,7 +1061,7 @@ struct MediaConfig : public PersistentObject * * Default: PJ_TRUE */ - bool vidPreviewEnableNative; + bool vidPreviewEnableNative; public: /** Default constructor initialises with default values */ @@ -1077,14 +1076,14 @@ struct MediaConfig : public PersistentObject /** * Read this object from a container. * - * @param node Container to write values from. + * @param node Container to write values from. */ virtual void readObject(const ContainerNode &node) PJSUA2_THROW(Error); /** * Write this object to a container. * - * @param node Container to write values to. + * @param node Container to write values to. */ virtual void writeObject(ContainerNode &node) const PJSUA2_THROW(Error); }; @@ -1096,25 +1095,25 @@ struct MediaConfig : public PersistentObject struct EpConfig : public PersistentObject { /** UA config */ - UaConfig uaConfig; + UaConfig uaConfig; /** Logging config */ - LogConfig logConfig; + LogConfig logConfig; /** Media config */ - MediaConfig medConfig; + MediaConfig medConfig; /** * Read this object from a container. * - * @param node Container to write values from. + * @param node Container to write values from. */ virtual void readObject(const ContainerNode &node) PJSUA2_THROW(Error); /** * Write this object to a container. * - * @param node Container to write values to. + * @param node Container to write values to. */ virtual void writeObject(ContainerNode &node) const PJSUA2_THROW(Error); @@ -1170,7 +1169,7 @@ class Endpoint /** * Get library state. * - * @return library state. + * @return library state. */ pjsua_state libGetState() const; @@ -1181,7 +1180,7 @@ class Endpoint * * Note that create() MUST be called before calling this function. * - * @param prmEpConfig Endpoint configurations + * @param prmEpConfig Endpoint configurations */ void libInit( const EpConfig &prmEpConfig) PJSUA2_THROW(Error); @@ -1198,7 +1197,7 @@ class Endpoint * some memory to store the thread description, which will only be freed * when the library is destroyed. * - * @param name The optional name to be assigned to the thread. + * @param name The optional name to be assigned to the thread. */ void libRegisterThread(const string &name) PJSUA2_THROW(Error); @@ -1230,9 +1229,9 @@ class Endpoint * * @param msec_timeout Maximum time to wait, in miliseconds. * - * @return The number of events that have been handled during the - * poll. Negative value indicates error, and application - * can retrieve the error as (status = -return_value). + * @return The number of events that have been handled during the + * poll. Negative value indicates error, and application + * can retrieve the error as (status = -return_value). */ int libHandleEvents(unsigned msec_timeout); @@ -1247,7 +1246,7 @@ class Endpoint * Application.may safely call this function more than once if it doesn't * keep track of it's state. * - * @param prmFlags Combination of pjsua_destroy_flag enumeration. + * @param prmFlags Combination of pjsua_destroy_flag enumeration. */ void libDestroy(unsigned prmFlags=0) PJSUA2_THROW(Error); @@ -1259,16 +1258,16 @@ class Endpoint /** * Retrieve the error string for the specified status code. * - * @param prmErr The error code. + * @param prmErr The error code. */ string utilStrError(pj_status_t prmErr); /** * Write a log message. * - * @param prmLevel Log verbosity level (1-5) - * @param prmSender The log sender. - * @param prmMsg The log message. + * @param prmLevel Log verbosity level (1-5) + * @param prmSender The log sender. + * @param prmMsg The log message. */ void utilLogWrite(int prmLevel, const string &prmSender, @@ -1282,7 +1281,7 @@ class Endpoint * logging functionality. For that, you should use * utilLogWrite(prmLevel, prmSender, prmMsg) above. * - * @param e The log entry. + * @param e The log entry. */ void utilLogWrite(LogEntry &e); @@ -1290,10 +1289,10 @@ class Endpoint * This is a utility function to verify that valid SIP url is given. If the * URL is a valid SIP/SIPS scheme, PJ_SUCCESS will be returned. * - * @param prmUri The URL string. + * @param prmUri The URL string. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. * * @see utilVerifyUri() */ @@ -1304,10 +1303,10 @@ class Endpoint * utilVerifySipUri(), this function will return PJ_SUCCESS if tel: URI * is given. * - * @param prmUri The URL string. + * @param prmUri The URL string. * - * @return PJ_SUCCESS on success, or the appropriate error - * code. + * @return PJ_SUCCESS on success, or the appropriate error + * code. * * @see pjsua_verify_sip_url() */ @@ -1319,12 +1318,12 @@ class Endpoint * called. Note that the callback may be executed by different thread, * depending on whether worker thread is enabled or not. * - * @param prmMsecDelay The time interval in msec. - * @param prmUserData Arbitrary user data, to be given back to - * application in the callback. + * @param prmMsecDelay The time interval in msec. + * @param prmUserData Arbitrary user data, to be given back to + * application in the callback. * - * @return Token to identify the timer, which could be - * given to utilTimerCancel(). + * @return Token to identify the timer, which could be + * given to utilTimerCancel(). */ Token utilTimerSchedule(unsigned prmMsecDelay, Token prmUserData) PJSUA2_THROW(Error); @@ -1332,8 +1331,8 @@ class Endpoint /** * Cancel previously scheduled timer with the specified timer token. * - * @param prmToken The timer token, which was returned from - * previous utilTimerSchedule() call. + * @param prmToken The timer token, which was returned from + * previous utilTimerSchedule() call. */ void utilTimerCancel(Token prmToken); @@ -1342,7 +1341,7 @@ class Endpoint * If EpConfig::UaConfig::mainThreadOnly is false, the job will be * executed immediately. * - * @param job The job class. + * @param job The job class. */ void utilAddPendingJob(PendingJob *job); @@ -1383,23 +1382,23 @@ class Endpoint * Update the STUN servers list. The libInit() must have been called * before calling this function. * - * @param prmServers Array of STUN servers to try. The endpoint - * will try to resolve and contact each of the - * STUN server entry until it finds one that is - * usable. Each entry may be a domain name, host - * name, IP address, and it may contain an - * optional port number. For example: - * - "pjsip.org" (domain name) - * - "sip.pjsip.org" (host name) - * - "pjsip.org:33478" (domain name and a non- - * standard port number) - * - "10.0.0.1:3478" (IP address and port number) - * @param prmWait Specify if the function should block until - * it gets the result. In this case, the - * function will block while the resolution - * is being done, and the callback - * onNatCheckStunServersComplete() will be called - * before this function returns. + * @param prmServers Array of STUN servers to try. The endpoint + * will try to resolve and contact each of the + * STUN server entry until it finds one that is + * usable. Each entry may be a domain name, host + * name, IP address, and it may contain an + * optional port number. For example: + * - "pjsip.org" (domain name) + * - "sip.pjsip.org" (host name) + * - "pjsip.org:33478" (domain name and a non- + * standard port number) + * - "10.0.0.1:3478" (IP address and port number) + * @param prmWait Specify if the function should block until + * it gets the result. In this case, the + * function will block while the resolution + * is being done, and the callback + * onNatCheckStunServersComplete() will be called + * before this function returns. * */ void natUpdateStunServers(const StringVector &prmServers, @@ -1410,24 +1409,24 @@ class Endpoint * entries (sequentially) to find which is usable. The libInit() must * have been called before calling this function. * - * @param prmServers Array of STUN servers to try. The endpoint - * will try to resolve and contact each of the - * STUN server entry until it finds one that is - * usable. Each entry may be a domain name, host - * name, IP address, and it may contain an - * optional port number. For example: - * - "pjsip.org" (domain name) - * - "sip.pjsip.org" (host name) - * - "pjsip.org:33478" (domain name and a non- - * standard port number) - * - "10.0.0.1:3478" (IP address and port number) - * @param prmWait Specify if the function should block until - * it gets the result. In this case, the function - * will block while the resolution is being done, - * and the callback will be called before this - * function returns. - * @param prmUserData Arbitrary user data to be passed back to - * application in the callback. + * @param prmServers Array of STUN servers to try. The endpoint + * will try to resolve and contact each of the + * STUN server entry until it finds one that is + * usable. Each entry may be a domain name, host + * name, IP address, and it may contain an + * optional port number. For example: + * - "pjsip.org" (domain name) + * - "sip.pjsip.org" (host name) + * - "pjsip.org:33478" (domain name and a non- + * standard port number) + * - "10.0.0.1:3478" (IP address and port number) + * @param prmWait Specify if the function should block until + * it gets the result. In this case, the function + * will block while the resolution is being done, + * and the callback will be called before this + * function returns. + * @param prmUserData Arbitrary user data to be passed back to + * application in the callback. * * @see natCancelCheckStunServers() */ @@ -1438,12 +1437,12 @@ class Endpoint /** * Cancel pending STUN resolution which match the specified token. * - * @param token The token to match. This token was given to - * natCheckStunServers() - * @param notify_cb Boolean to control whether the callback should - * be called for cancelled resolutions. When the - * callback is called, the status in the result - * will be set as PJ_ECANCELLED. + * @param token The token to match. This token was given to + * natCheckStunServers() + * @param notify_cb Boolean to control whether the callback should + * be called for cancelled resolutions. When the + * callback is called, the status in the result + * will be set as PJ_ECANCELLED. * * Exception: PJ_ENOTFOUND if there is no matching one, or other error. */ @@ -1458,10 +1457,10 @@ class Endpoint * Create and start a new SIP transport according to the specified * settings. * - * @param type Transport type. - * @param cfg Transport configuration. + * @param type Transport type. + * @param cfg Transport configuration. * - * @return The transport ID. + * @return The transport ID. */ TransportId transportCreate(pjsip_transport_type_e type, const TransportConfig &cfg) PJSUA2_THROW(Error); @@ -1472,16 +1471,16 @@ class Endpoint * call transportGetInfo() function to retrieve detailed information * about the transport. * - * @return Array of transport IDs. + * @return Array of transport IDs. */ IntVector transportEnum() const PJSUA2_THROW(Error); /** * Get information about transport. * - * @param id Transport ID. + * @param id Transport ID. * - * @return Transport info. + * @return Transport info. */ TransportInfo transportGetInfo(TransportId id) const PJSUA2_THROW(Error); @@ -1491,8 +1490,8 @@ class Endpoint * close the socket, it will only discard incoming messages and prevent * the transport from being used to send outgoing messages. * - * @param id Transport ID. - * @param enabled Enable or disable the transport. + * @param id Transport ID. + * @param enabled Enable or disable the transport. * */ void transportSetEnable(TransportId id, bool enabled) PJSUA2_THROW(Error); @@ -1502,7 +1501,7 @@ class Endpoint * closed while preventing new users from using the transport, and will * close the transport when its usage count reaches zero. * - * @param id Transport ID. + * @param id Transport ID. */ void transportClose(TransportId id) PJSUA2_THROW(Error); @@ -1517,7 +1516,7 @@ class Endpoint * Note: application normally uses this API after obtaining the handle * from onTransportState() callback. * - * @param tp The transport. + * @param tp The transport. */ void transportShutdown(TransportHandle tp) PJSUA2_THROW(Error); @@ -1538,37 +1537,37 @@ class Endpoint /** * Add media to the media list. * - * @param media media to be added. + * @param media media to be added. */ void mediaAdd(AudioMedia &media); /** * Remove media from the media list. * - * @param media media to be removed. + * @param media media to be removed. */ void mediaRemove(AudioMedia &media); /** * Check if media has been added to the media list. * - * @param media media to be check. + * @param media media to be check. * - * @return True if media has been added, false otherwise. + * @return True if media has been added, false otherwise. */ bool mediaExists(const AudioMedia &media) const; /** * Get maximum number of media port. * - * @return Maximum number of media port in the conference bridge. + * @return Maximum number of media port in the conference bridge. */ unsigned mediaMaxPorts() const; /** * Get current number of active media port in the bridge. * - * @return The number of active media port. + * @return The number of active media port. */ unsigned mediaActivePorts() const; @@ -1579,7 +1578,7 @@ class Endpoint * * Enumerate all media port. * - * @return The list of media port. + * @return The list of media port. */ const AudioMediaVector &mediaEnumPorts() const PJSUA2_THROW(Error); #endif @@ -1587,28 +1586,28 @@ class Endpoint /** * Enumerate all audio media port. * - * @return The list of audio media port. + * @return The list of audio media port. */ AudioMediaVector2 mediaEnumPorts2() const PJSUA2_THROW(Error); /** * Enumerate all video media port. * - * @return The list of video media port. + * @return The list of video media port. */ VideoMediaVector mediaEnumVidPorts() const PJSUA2_THROW(Error); /** * Get the instance of Audio Device Manager. * - * @return The Audio Device Manager. + * @return The Audio Device Manager. */ AudDevManager &audDevManager(); /** * Get the instance of Video Device Manager. * - * @return The Video Device Manager. + * @return The Video Device Manager. */ VidDevManager &vidDevManager(); @@ -1623,7 +1622,7 @@ class Endpoint * * Enum all supported codecs in the system. * - * @return Array of codec info. + * @return Array of codec info. */ const CodecInfoVector &codecEnum() PJSUA2_THROW(Error); #endif @@ -1631,29 +1630,29 @@ class Endpoint /** * Enum all supported codecs in the system. * - * @return Array of codec info. + * @return Array of codec info. */ CodecInfoVector2 codecEnum2() const PJSUA2_THROW(Error); /** * Change codec priority. * - * @param codec_id Codec ID, which is a string that uniquely identify - * the codec (such as "speex/8000"). - * @param priority Codec priority, 0-255, where zero means to disable - * the codec. + * @param codec_id Codec ID, which is a string that uniquely identify + * the codec (such as "speex/8000"). + * @param priority Codec priority, 0-255, where zero means to disable + * the codec. * */ void codecSetPriority(const string &codec_id, - pj_uint8_t priority) PJSUA2_THROW(Error); + pj_uint8_t priority) PJSUA2_THROW(Error); /** * Get codec parameters. * - * @param codec_id Codec ID. + * @param codec_id Codec ID. * - * @return Codec parameters. If codec is not found, Error - * will be thrown. + * @return Codec parameters. If codec is not found, Error + * will be thrown. * */ CodecParam codecGetParam(const string &codec_id) const PJSUA2_THROW(Error); @@ -1661,13 +1660,13 @@ class Endpoint /** * Set codec parameters. * - * @param codec_id Codec ID. - * @param param Codec parameter to set. Set to NULL to reset - * codec parameter to library default settings. + * @param codec_id Codec ID. + * @param param Codec parameter to set. Set to NULL to reset + * codec parameter to library default settings. * */ void codecSetParam(const string &codec_id, - const CodecParam param) PJSUA2_THROW(Error); + const CodecParam param) PJSUA2_THROW(Error); #if !DEPRECATED_FOR_TICKET_2232 /** @@ -1676,7 +1675,7 @@ class Endpoint * * Enum all supported video codecs in the system. * - * @return Array of video codec info. + * @return Array of video codec info. */ const CodecInfoVector &videoCodecEnum() PJSUA2_THROW(Error); #endif @@ -1684,49 +1683,49 @@ class Endpoint /** * Enum all supported video codecs in the system. * - * @return Array of video codec info. + * @return Array of video codec info. */ CodecInfoVector2 videoCodecEnum2() const PJSUA2_THROW(Error); /** * Change video codec priority. * - * @param codec_id Codec ID, which is a string that uniquely identify - * the codec (such as "H263/90000"). Please see pjsua - * manual or pjmedia codec reference for details. - * @param priority Codec priority, 0-255, where zero means to disable - * the codec. + * @param codec_id Codec ID, which is a string that uniquely identify + * the codec (such as "H263/90000"). Please see pjsua + * manual or pjmedia codec reference for details. + * @param priority Codec priority, 0-255, where zero means to disable + * the codec. * */ void videoCodecSetPriority(const string &codec_id, - pj_uint8_t priority) PJSUA2_THROW(Error); + pj_uint8_t priority) PJSUA2_THROW(Error); /** * Get video codec parameters. * - * @param codec_id Codec ID. + * @param codec_id Codec ID. * - * @return Codec parameters. If codec is not found, Error - * will be thrown. + * @return Codec parameters. If codec is not found, Error + * will be thrown. * */ VidCodecParam getVideoCodecParam(const string &codec_id) const - PJSUA2_THROW(Error); + PJSUA2_THROW(Error); /** * Set video codec parameters. * - * @param codec_id Codec ID. - * @param param Codec parameter to set. + * @param codec_id Codec ID. + * @param param Codec parameter to set. * */ void setVideoCodecParam(const string &codec_id, - const VidCodecParam ¶m) PJSUA2_THROW(Error); - + const VidCodecParam ¶m) PJSUA2_THROW(Error); + /** * Reset video codec parameters to library default settings. * - * @param codec_id Codec ID. + * @param codec_id Codec ID. * */ void resetVideoCodecParam(const string &codec_id) PJSUA2_THROW(Error); @@ -1741,17 +1740,17 @@ class Endpoint /** * Set codec Opus config. * - * @param opus_cfg Codec Opus configuration. + * @param opus_cfg Codec Opus configuration. * */ void setCodecOpusConfig(const CodecOpusConfig &opus_cfg) - PJSUA2_THROW(Error); + PJSUA2_THROW(Error); #endif /** * Enumerate all SRTP crypto-suite names. * - * @return The list of SRTP crypto-suite name. + * @return The list of SRTP crypto-suite name. */ StringVector srtpCryptoEnum() PJSUA2_THROW(Error); @@ -1774,7 +1773,7 @@ class Endpoint * continue the call by sending re-INVITE * (configurable via \a AccountConfig.ipChangeConfig.reinviteFlags). * - * @param param The IP change parameter, have a look at IpChangeParam. + * @param param The IP change parameter, have a look at IpChangeParam. */ void handleIpChange(const IpChangeParam ¶m) PJSUA2_THROW(Error); @@ -1787,11 +1786,11 @@ class Endpoint * Callback when the Endpoint has finished performing NAT type * detection that is initiated with natDetectType(). * - * @param prm Callback parameters containing the detection - * result. + * @param prm Callback parameters containing the detection + * result. */ virtual void onNatDetectionComplete( - const OnNatDetectionCompleteParam &prm) + const OnNatDetectionCompleteParam &prm) { PJ_UNUSED_ARG(prm); } /** @@ -1799,26 +1798,26 @@ class Endpoint * checking that is initiated when calling libInit(), or by * calling natCheckStunServers() or natUpdateStunServers(). * - * @param prm Callback parameters. + * @param prm Callback parameters. */ virtual void onNatCheckStunServersComplete( - const OnNatCheckStunServersCompleteParam &prm) + const OnNatCheckStunServersCompleteParam &prm) { PJ_UNUSED_ARG(prm); } /** * This callback is called when transport state has changed. * - * @param prm Callback parameters. + * @param prm Callback parameters. */ virtual void onTransportState( - const OnTransportStateParam &prm) + const OnTransportStateParam &prm) { PJ_UNUSED_ARG(prm); } /** * Callback when a timer has fired. The timer was scheduled by * utilTimerSchedule(). * - * @param prm Callback parameters. + * @param prm Callback parameters. */ virtual void onTimer(const OnTimerParam &prm) { PJ_UNUSED_ARG(prm); } @@ -1836,7 +1835,7 @@ class Endpoint * may be called before the callback of the SIP event itself, i.e: * incoming call, pager, subscription, or unsolicited-event. * - * @param prm Callback parameters. + * @param prm Callback parameters. */ virtual void onSelectAccount(OnSelectAccountParam &prm) { PJ_UNUSED_ARG(prm); } @@ -1845,7 +1844,7 @@ class Endpoint * Calling #handleIpChange() may involve different operation. This * callback is called to report the progress of each enabled operation. * - * @param prm Callback parameters. + * @param prm Callback parameters. * */ virtual void onIpChangeProgress(OnIpChangeProgressParam &prm) @@ -1858,7 +1857,7 @@ class Endpoint * If application needs to perform more complex tasks to handle the * event, it should post the task to another thread. * - * @param prm Callback parameter. + * @param prm Callback parameter. */ virtual void onMediaEvent(OnMediaEventParam &prm) { PJ_UNUSED_ARG(prm); } @@ -1879,44 +1878,44 @@ class Endpoint * \a third_party directory is linked, and this callback returns PJ_ENOTSUP, * then the default digest computation back-end is used. * - * @param prm.digestChallenge The authentication challenge sent by server in 401 - * or 401 response, as either Proxy-Authenticate or - * WWW-Authenticate header. - * @param prm.credentialInfo The credential to be used. + * @param prm.digestChallenge The authentication challenge sent by server in 401 + * or 401 response, as either Proxy-Authenticate or + * WWW-Authenticate header. + * @param prm.credentialInfo The credential to be used. * @param method The request method. - * @param prm.digestCredential The digest credential where the digest response - * will be placed to. Upon calling this function, the - * nonce, nc, cnonce, qop, uri, and realm fields of - * this structure must have been set by caller. Upon - * return, the \a response field will be initialized - * by this function. + * @param prm.digestCredential The digest credential where the digest response + * will be placed to. Upon calling this function, the + * nonce, nc, cnonce, qop, uri, and realm fields of + * this structure must have been set by caller. Upon + * return, the \a response field will be initialized + * by this function. * * @return PJ_ENOTSUP is the default. If you overload this callback, - * return PJ_SUCCESS on success. + * return PJ_SUCCESS on success. */ virtual pj_status_t onCredAuth(OnCredAuthParam &prm); private: - static Endpoint *instance_; // static instance - LogWriter *writer; // Custom writer, if any - AudDevManager audioDevMgr; - VidDevManager videoDevMgr; + static Endpoint *instance_; // static instance + LogWriter *writer; // Custom writer, if any + AudDevManager audioDevMgr; + VidDevManager videoDevMgr; #if !DEPRECATED_FOR_TICKET_2232 - CodecInfoVector codecInfoList; - CodecInfoVector videoCodecInfoList; + CodecInfoVector codecInfoList; + CodecInfoVector videoCodecInfoList; #endif std::map threadDescMap; - pj_mutex_t *threadDescMutex; + pj_mutex_t *threadDescMutex; #if !DEPRECATED_FOR_TICKET_2232 - AudioMediaVector mediaList; - pj_mutex_t *mediaListMutex; + AudioMediaVector mediaList; + pj_mutex_t *mediaListMutex; #endif /* Pending logging */ - bool mainThreadOnly; - void *mainThread; - unsigned pendingJobSize; - std::list pendingJobs; + bool mainThreadOnly; + void *mainThread; + unsigned pendingJobSize; + std::list pendingJobs; void performPendingJobs(); @@ -1924,18 +1923,18 @@ class Endpoint static void logFunc(int level, const char *data, int len); static void stun_resolve_cb(const pj_stun_resolve_result *result); static void on_timer(pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry); + struct pj_timer_entry *entry); static void on_nat_detect(const pj_stun_nat_detect_result *res); static void on_transport_state(pjsip_transport *tp, - pjsip_transport_state state, - const pjsip_transport_state_info *info); + pjsip_transport_state state, + const pjsip_transport_state_info *info); private: /* * Account & Call lookups */ - static Account *lookupAcc(int acc_id, const char *op); - static Call *lookupCall(int call_id, const char *op); + static Account *lookupAcc(int acc_id, const char *op); + static Call *lookupCall(int call_id, const char *op); /* static callbacks */ static void on_incoming_call(pjsua_acc_id acc_id, @@ -1946,13 +1945,13 @@ class Endpoint static void on_reg_state2(pjsua_acc_id acc_id, pjsua_reg_info *info); static void on_incoming_subscribe(pjsua_acc_id acc_id, - pjsua_srv_pres *srv_pres, - pjsua_buddy_id buddy_id, - const pj_str_t *from, - pjsip_rx_data *rdata, - pjsip_status_code *code, - pj_str_t *reason, - pjsua_msg_data *msg_data); + pjsua_srv_pres *srv_pres, + pjsua_buddy_id buddy_id, + const pj_str_t *from, + pjsip_rx_data *rdata, + pjsip_status_code *code, + pj_str_t *reason, + pjsua_msg_data *msg_data); static void on_pager2(pjsua_call_id call_id, const pj_str_t *from, const pj_str_t *to, @@ -1962,14 +1961,14 @@ class Endpoint pjsip_rx_data *rdata, pjsua_acc_id acc_id); static void on_pager_status2(pjsua_call_id call_id, - const pj_str_t *to, - const pj_str_t *body, - void *user_data, - pjsip_status_code status, - const pj_str_t *reason, - pjsip_tx_data *tdata, - pjsip_rx_data *rdata, - pjsua_acc_id acc_id); + const pj_str_t *to, + const pj_str_t *body, + void *user_data, + pjsip_status_code status, + const pj_str_t *reason, + pjsip_tx_data *tdata, + pjsip_rx_data *rdata, + pjsua_acc_id acc_id); static void on_typing2(pjsua_call_id call_id, const pj_str_t *from, const pj_str_t *to, @@ -1980,11 +1979,11 @@ class Endpoint static void on_mwi_info(pjsua_acc_id acc_id, pjsua_mwi_info *mwi_info); static void on_acc_find_for_incoming(const pjsip_rx_data *rdata, - pjsua_acc_id* acc_id); + pjsua_acc_id* acc_id); static void on_buddy_state(pjsua_buddy_id buddy_id); static void on_buddy_evsub_state(pjsua_buddy_id buddy_id, - pjsip_evsub *sub, - pjsip_event *event); + pjsip_evsub *sub, + pjsip_event *event); // Call callbacks static void on_call_state(pjsua_call_id call_id, pjsip_event *e); static void on_call_tsx_state(pjsua_call_id call_id, @@ -1998,13 +1997,13 @@ class Endpoint static void on_stream_precreate(pjsua_call_id call_id, pjsua_on_stream_precreate_param *param); static void on_stream_created2(pjsua_call_id call_id, - pjsua_on_stream_created_param *param); + pjsua_on_stream_created_param *param); static void on_stream_destroyed(pjsua_call_id call_id, pjmedia_stream *strm, unsigned stream_idx); static void on_dtmf_digit(pjsua_call_id call_id, int digit); static void on_dtmf_digit2(pjsua_call_id call_id, - const pjsua_dtmf_info *info); + const pjsua_dtmf_info *info); static void on_dtmf_event(pjsua_call_id call_id, const pjsua_dtmf_event *event); static void on_call_transfer_request(pjsua_call_id call_id, @@ -2043,8 +2042,8 @@ class Endpoint pjsip_status_code *code, pjsua_call_setting *opt); static void on_call_tx_offer(pjsua_call_id call_id, - void *reserved, - pjsua_call_setting *opt); + void *reserved, + pjsua_call_setting *opt); static pjsip_redirect_op on_call_redirected(pjsua_call_id call_id, const pjsip_uri *target, const pjsip_event *e); @@ -2067,22 +2066,22 @@ class Endpoint static void on_ip_change_progress(pjsua_ip_change_op op, - pj_status_t status, - const pjsua_ip_change_op_info *info); + pj_status_t status, + const pjsua_ip_change_op_info *info); static pj_status_t on_auth_create_aka_response_callback( - pj_pool_t *pool, - const pjsip_digest_challenge*chal, - const pjsip_cred_info *cred, - const pj_str_t *method, - pjsip_digest_credential *auth); + pj_pool_t *pool, + const pjsip_digest_challenge*chal, + const pjsip_cred_info *cred, + const pj_str_t *method, + pjsip_digest_credential *auth); friend class Account; private: void clearCodecInfoList(CodecInfoVector &codec_list); void updateCodecInfoList(pjsua_codec_info pj_codec[], unsigned count, - CodecInfoVector &codec_list); + CodecInfoVector &codec_list); }; @@ -2096,5 +2095,5 @@ class Endpoint /* End pj namespace */ -#endif /* __PJSUA2_UA_HPP__ */ +#endif /* __PJSUA2_UA_HPP__ */ diff --git a/pjsip/include/pjsua2/json.hpp b/pjsip/include/pjsua2/json.hpp index 9416f3bb85..37cfef22ca 100644 --- a/pjsip/include/pjsua2/json.hpp +++ b/pjsip/include/pjsua2/json.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -56,21 +55,21 @@ class JsonDocument : public PersistentDocument /** * Load this document from a file. * - * @param filename The file name. + * @param filename The file name. */ virtual void loadFile(const string &filename) PJSUA2_THROW(Error); /** * Load this document from string. * - * @param input The string. + * @param input The string. */ virtual void loadString(const string &input) PJSUA2_THROW(Error); /** * Write this document to a file. * - * @param filename The file name. + * @param filename The file name. */ virtual void saveFile(const string &filename) PJSUA2_THROW(Error); @@ -92,13 +91,13 @@ class JsonDocument : public PersistentDocument /** * An internal function to get the pool. */ - pj_pool_t* getPool(); + pj_pool_t* getPool(); private: - pj_caching_pool cp; + pj_caching_pool cp; mutable ContainerNode rootNode; mutable pj_json_elem *root; - mutable pj_pool_t *pool; + mutable pj_pool_t *pool; void initRoot() const; }; @@ -113,4 +112,4 @@ class JsonDocument : public PersistentDocument } // namespace pj -#endif /* __PJSUA2_JSON_HPP__ */ +#endif /* __PJSUA2_JSON_HPP__ */ diff --git a/pjsip/include/pjsua2/media.hpp b/pjsip/include/pjsua2/media.hpp index 2ac4f5a075..3282bf7ef6 100644 --- a/pjsip/include/pjsua2/media.hpp +++ b/pjsip/include/pjsua2/media.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -53,12 +52,12 @@ struct MediaFormat * * @see pjmedia_format_id */ - pj_uint32_t id; + pj_uint32_t id; /** * The top-most type of the media, as an information. */ - pjmedia_type type; + pjmedia_type type; public: /** @@ -73,12 +72,12 @@ struct MediaFormat */ struct MediaFormatAudio : public MediaFormat { - unsigned clockRate; /**< Audio clock rate in samples or Hz. */ - unsigned channelCount; /**< Number of channels. */ - unsigned frameTimeUsec; /**< Frame interval, in microseconds. */ - unsigned bitsPerSample; /**< Number of bits per sample. */ - pj_uint32_t avgBps; /**< Average bitrate */ - pj_uint32_t maxBps; /**< Maximum bitrate */ + unsigned clockRate; /**< Audio clock rate in samples or Hz. */ + unsigned channelCount; /**< Number of channels. */ + unsigned frameTimeUsec; /**< Frame interval, in microseconds. */ + unsigned bitsPerSample; /**< Number of bits per sample. */ + pj_uint32_t avgBps; /**< Average bitrate */ + pj_uint32_t maxBps; /**< Maximum bitrate */ /** * Construct from pjmedia_format. @@ -96,12 +95,12 @@ struct MediaFormatAudio : public MediaFormat */ struct MediaFormatVideo : public MediaFormat { - unsigned width; /**< Video width. */ - unsigned height; /**< Video height. */ - int fpsNum; /**< Frames per second numerator. */ - int fpsDenum; /**< Frames per second denumerator. */ - pj_uint32_t avgBps; /**< Average bitrate. */ - pj_uint32_t maxBps; /**< Maximum bitrate. */ + unsigned width; /**< Video width. */ + unsigned height; /**< Video height. */ + int fpsNum; /**< Frames per second numerator. */ + int fpsDenum; /**< Frames per second denumerator. */ + pj_uint32_t avgBps; /**< Average bitrate. */ + pj_uint32_t maxBps; /**< Maximum bitrate. */ /** * Construct from pjmedia_format. @@ -129,35 +128,35 @@ struct ConfPortInfo /** * Conference port number. */ - int portId; + int portId; /** * Port name. */ - string name; + string name; /** * Media audio format information */ - MediaFormatAudio format; + MediaFormatAudio format; /** * Tx level adjustment. Value 1.0 means no adjustment, value 0 means * the port is muted, value 2.0 means the level is amplified two times. */ - float txLevelAdj; + float txLevelAdj; /** * Rx level adjustment. Value 1.0 means no adjustment, value 0 means * the port is muted, value 2.0 means the level is amplified two times. */ - float rxLevelAdj; + float rxLevelAdj; /** * Array of listeners (in other words, ports where this port is * transmitting to). */ - IntVector listeners; + IntVector listeners; public: /** @@ -213,7 +212,7 @@ struct AudioMediaTransmitParam * * Default: 1.0 */ - float level; + float level; public: /** @@ -269,7 +268,7 @@ class AudioMedia : public Media * this method twice, with the second one called from the opposite source * media. * - * @param sink The destination Media. + * @param sink The destination Media. */ void startTransmit(const AudioMedia &sink) const PJSUA2_THROW(Error); @@ -295,17 +294,17 @@ class AudioMedia : public Media * this method twice, with the second one called from the opposite source * media. * - * @param sink The destination Media. - * @param param The parameter. + * @param sink The destination Media. + * @param param The parameter. */ void startTransmit2(const AudioMedia &sink, - const AudioMediaTransmitParam ¶m) const + const AudioMediaTransmitParam ¶m) const PJSUA2_THROW(Error); /** * Stop media flow to destination/sink port. * - * @param sink The destination media. + * @param sink The destination media. * */ void stopTransmit(const AudioMedia &sink) const PJSUA2_THROW(Error); @@ -314,9 +313,9 @@ class AudioMedia : public Media * Adjust the signal level to be transmitted from the bridge to this * media port by making it louder or quieter. * - * @param level Signal level adjustment. Value 1.0 means no - * level adjustment, while value 0 means to mute - * the port. + * @param level Signal level adjustment. Value 1.0 means no + * level adjustment, while value 0 means to mute + * the port. */ void adjustRxLevel(float level) PJSUA2_THROW(Error); @@ -324,23 +323,23 @@ class AudioMedia : public Media * Adjust the signal level to be received from this media port (to * the bridge) by making it louder or quieter. * - * @param level Signal level adjustment. Value 1.0 means no - * level adjustment, while value 0 means to mute - * the port. + * @param level Signal level adjustment. Value 1.0 means no + * level adjustment, while value 0 means to mute + * the port. */ void adjustTxLevel(float level) PJSUA2_THROW(Error); /** * Get the last received signal level. * - * @return Signal level in percent. + * @return Signal level in percent. */ unsigned getRxLevel() const PJSUA2_THROW(Error); /** * Get the last transmitted signal level. * - * @return Signal level in percent. + * @return Signal level in percent. */ unsigned getTxLevel() const PJSUA2_THROW(Error); @@ -350,9 +349,9 @@ class AudioMedia : public Media * Typecast from base class Media. This is useful for application written * in language that does not support downcasting such as Python. * - * @param media The object to be downcasted + * @param media The object to be downcasted * - * @return The object as AudioMedia instance + * @return The object as AudioMedia instance */ static AudioMedia* typecastFromMedia(Media *media); @@ -374,7 +373,7 @@ class AudioMedia : public Media /** * Conference port Id. */ - int id; + int id; protected: /** @@ -400,7 +399,7 @@ class AudioMedia : public Media * */ void registerMediaPort2(MediaPort port, pj_pool_t *pool) - PJSUA2_THROW(Error); + PJSUA2_THROW(Error); /** * This method needs to be called by descendants of this class to remove @@ -412,8 +411,8 @@ class AudioMedia : public Media private: /* Memory pool for deprecated registerMediaPort() */ - pj_caching_pool mediaCachingPool; - pj_pool_t *mediaPool; + pj_caching_pool mediaCachingPool; + pj_pool_t *mediaPool; }; /** @@ -435,23 +434,23 @@ struct AudioMediaPlayerInfo /** * Format ID of the payload. */ - pjmedia_format_id formatId; + pjmedia_format_id formatId; /** * The number of bits per sample of the file payload. For example, * the value is 16 for PCM WAV and 8 for Alaw/Ulas WAV files. */ - unsigned payloadBitsPerSample; + unsigned payloadBitsPerSample; /** * The WAV payload size in bytes. */ - pj_uint32_t sizeBytes; + pj_uint32_t sizeBytes; /** * The WAV payload size in samples. */ - pj_uint32_t sizeSamples; + pj_uint32_t sizeSamples; public: /** @@ -476,36 +475,36 @@ class AudioMediaPlayer : public AudioMedia * Create a file player, and automatically add this * player to the conference bridge. * - * @param file_name The filename to be played. Currently only - * WAV files are supported, and the WAV file MUST be - * formatted as 16bit PCM mono/single channel (any - * clock rate is supported). - * @param options Optional option flag. Application may specify - * PJMEDIA_FILE_NO_LOOP to prevent playback loop. + * @param file_name The filename to be played. Currently only + * WAV files are supported, and the WAV file MUST be + * formatted as 16bit PCM mono/single channel (any + * clock rate is supported). + * @param options Optional option flag. Application may specify + * PJMEDIA_FILE_NO_LOOP to prevent playback loop. */ void createPlayer(const string &file_name, - unsigned options=0) PJSUA2_THROW(Error); + unsigned options=0) PJSUA2_THROW(Error); /** * Create a file playlist media port, and automatically add the port * to the conference bridge. * * @param file_names Array of file names to be added to the play list. - * Note that the files must have the same clock rate, - * number of channels, and number of bits per sample. - * @param label Optional label to be set for the media port. - * @param options Optional option flag. Application may specify - * PJMEDIA_FILE_NO_LOOP to prevent looping. + * Note that the files must have the same clock rate, + * number of channels, and number of bits per sample. + * @param label Optional label to be set for the media port. + * @param options Optional option flag. Application may specify + * PJMEDIA_FILE_NO_LOOP to prevent looping. */ void createPlaylist(const StringVector &file_names, - const string &label="", - unsigned options=0) PJSUA2_THROW(Error); + const string &label="", + unsigned options=0) PJSUA2_THROW(Error); /** * Get additional info about the player. This operation is only valid * for player. For playlist, Error will be thrown. * - * @return the info. + * @return the info. */ AudioMediaPlayerInfo getInfo() const PJSUA2_THROW(Error); @@ -513,7 +512,7 @@ class AudioMediaPlayer : public AudioMedia * Get current playback position in samples. This operation is not valid * for playlist. * - * @return Current playback position, in samples. + * @return Current playback position, in samples. */ pj_uint32_t getPos() const PJSUA2_THROW(Error); @@ -521,7 +520,7 @@ class AudioMediaPlayer : public AudioMedia * Set playback position in samples. This operation is not valid for * playlist. * - * @param samples The desired playback position, in samples. + * @param samples The desired playback position, in samples. */ void setPos(pj_uint32_t samples) PJSUA2_THROW(Error); @@ -531,9 +530,9 @@ class AudioMediaPlayer : public AudioMedia * Typecast from base class AudioMedia. This is useful for application * written in language that does not support downcasting such as Python. * - * @param media The object to be downcasted + * @param media The object to be downcasted * - * @return The object as AudioMediaPlayer instance + * @return The object as AudioMediaPlayer instance */ static AudioMediaPlayer* typecastFromAudioMedia(AudioMedia *media); @@ -558,10 +557,10 @@ class AudioMediaPlayer : public AudioMedia * is set to play repeatedly, then the callback will be called multiple * times. * - * @return If the callback returns false, the playback - * will stop. Note that if application destroys - * the player in the callback, it must return - * false here. + * @return If the callback returns false, the playback + * will stop. Note that if application destroys + * the player in the callback, it must return + * false here. */ virtual bool onEof() { return true; } @@ -585,7 +584,7 @@ class AudioMediaPlayer : public AudioMedia /** * Player Id. */ - int playerId; + int playerId; /** * Low level PJMEDIA callback @@ -611,24 +610,24 @@ class AudioMediaRecorder : public AudioMedia * file. The type of the recorder to use is determined by the extension of * the file (e.g. ".wav"). * - * @param file_name Output file name. The function will determine the - * default format to be used based on the file extension. - * Currently ".wav" is supported on all platforms. - * @param enc_type Optionally specify the type of encoder to be used to - * compress the media, if the file can support different - * encodings. This value must be zero for now. - * @param max_size Maximum file size. Specify zero or -1 to remove size - * limitation. This value must be zero or -1 for now. - * @param options Optional options, which can be used to specify the - * recording file format. Supported options are - * PJMEDIA_FILE_WRITE_PCM, PJMEDIA_FILE_WRITE_ALAW, - * and PJMEDIA_FILE_WRITE_ULAW. Default is zero or - * PJMEDIA_FILE_WRITE_PCM. + * @param file_name Output file name. The function will determine the + * default format to be used based on the file extension. + * Currently ".wav" is supported on all platforms. + * @param enc_type Optionally specify the type of encoder to be used to + * compress the media, if the file can support different + * encodings. This value must be zero for now. + * @param max_size Maximum file size. Specify zero or -1 to remove size + * limitation. This value must be zero or -1 for now. + * @param options Optional options, which can be used to specify the + * recording file format. Supported options are + * PJMEDIA_FILE_WRITE_PCM, PJMEDIA_FILE_WRITE_ALAW, + * and PJMEDIA_FILE_WRITE_ULAW. Default is zero or + * PJMEDIA_FILE_WRITE_PCM. */ void createRecorder(const string &file_name, - unsigned enc_type=0, - long max_size=0, - unsigned options=0) PJSUA2_THROW(Error); + unsigned enc_type=0, + long max_size=0, + unsigned options=0) PJSUA2_THROW(Error); /** * Warning: deprecated and will be removed in future release. @@ -636,9 +635,9 @@ class AudioMediaRecorder : public AudioMedia * Typecast from base class AudioMedia. This is useful for application * written in language that does not support downcasting such as Python. * - * @param media The object to be downcasted + * @param media The object to be downcasted * - * @return The object as AudioMediaRecorder instance + * @return The object as AudioMediaRecorder instance */ static AudioMediaRecorder* typecastFromAudioMedia(AudioMedia *media); @@ -652,7 +651,7 @@ class AudioMediaRecorder : public AudioMedia /** * Recorder Id. */ - int recorderId; + int recorderId; }; /** @@ -663,7 +662,7 @@ class ToneDesc : public pjmedia_tone_desc public: ToneDesc() { - pj_bzero(this, sizeof(*this)); + pj_bzero(this, sizeof(*this)); } ~ToneDesc() {} }; @@ -681,7 +680,7 @@ class ToneDigit : public pjmedia_tone_digit public: ToneDigit() { - pj_bzero(this, sizeof(*this)); + pj_bzero(this, sizeof(*this)); } ~ToneDigit() {} }; @@ -697,9 +696,9 @@ typedef std::vector ToneDigitVector; struct ToneDigitMapDigit { public: - string digit; /**< the digit */ - int freq1; /**< first frequency */ - int freq2; /**< second frequency */ + string digit; /**< the digit */ + int freq1; /**< first frequency */ + int freq2; /**< second frequency */ }; /** @@ -728,11 +727,11 @@ class ToneGenerator : public AudioMedia * Create tone generator and register the port to the conference bridge. */ void createToneGenerator(unsigned clock_rate = 16000, - unsigned channel_count = 1) PJSUA2_THROW(Error); + unsigned channel_count = 1) PJSUA2_THROW(Error); /** * Check if the tone generator is still busy producing some tones. - * @return Non-zero if busy. + * @return Non-zero if busy. */ bool isBusy() const; @@ -754,8 +753,8 @@ class ToneGenerator : public AudioMedia * function. The playback will begin as soon as the tone generator is * connected to other media. * - * @param tones Array of tones to be played. - * @param loop Play the tone in a loop. + * @param tones Array of tones to be played. + * @param loop Play the tone in a loop. */ void play(const ToneDescVector &tones, bool loop=false) PJSUA2_THROW(Error); @@ -768,8 +767,8 @@ class ToneGenerator : public AudioMedia * stop() is called before calling this function. The playback will begin * as soon as the tone generator is connected to a sink media. * - * @param digits Array of MF digits. - * @param loop Play the tone in a loop. + * @param digits Array of MF digits. + * @param loop Play the tone in a loop. */ void playDigits(const ToneDigitVector &digits, bool loop=false) PJSUA2_THROW(Error); @@ -777,14 +776,14 @@ class ToneGenerator : public AudioMedia /** * Get the digit-map currently used by this tone generator. * - * @return The digitmap currently used by the tone generator + * @return The digitmap currently used by the tone generator */ ToneDigitMapVector getDigitMap() const PJSUA2_THROW(Error); /** * Set digit map to be used by the tone generator. * - * @param digit_map Digitmap to be used by the tone generator. + * @param digit_map Digitmap to be used by the tone generator. */ void setDigitMap(const ToneDigitMapVector &digit_map) PJSUA2_THROW(Error); @@ -881,14 +880,14 @@ class AudDevManager * Get currently active capture sound devices. If sound devices has not been * created, it is possible that the function returns -1 as device IDs. * - * @return Device ID of the capture device. + * @return Device ID of the capture device. */ int getCaptureDev() const PJSUA2_THROW(Error); /** * Get the AudioMedia of the capture audio device. * - * @return Audio media for the capture device. + * @return Audio media for the capture device. */ AudioMedia &getCaptureDevMedia() PJSUA2_THROW(Error); @@ -896,14 +895,14 @@ class AudDevManager * Get currently active playback sound devices. If sound devices has not * been created, it is possible that the function returns -1 as device IDs. * - * @return Device ID of the playback device. + * @return Device ID of the playback device. */ int getPlaybackDev() const PJSUA2_THROW(Error); /** * Get the AudioMedia of the speaker/playback audio device. * - * @return Audio media for the speaker/playback device. + * @return Audio media for the speaker/playback device. */ AudioMedia &getPlaybackDevMedia() PJSUA2_THROW(Error); @@ -912,7 +911,7 @@ class AudDevManager * function at any time to replace current sound device. Calling this * method will not change the state of the sound device (opened/closed). * - * @param capture_dev Device ID of the capture device. + * @param capture_dev Device ID of the capture device. */ void setCaptureDev(int capture_dev) const PJSUA2_THROW(Error); @@ -921,7 +920,7 @@ class AudDevManager * function at any time to replace current sound device. Calling this * method will not change the state of the sound device (opened/closed). * - * @param playback_dev Device ID of the playback device. + * @param playback_dev Device ID of the playback device. */ void setPlaybackDev(int playback_dev) const PJSUA2_THROW(Error); @@ -933,7 +932,7 @@ class AudDevManager * Enum all audio devices installed in the system. This function is not * safe in multithreaded environment. * - * @return The list of audio device info. + * @return The list of audio device info. */ const AudioDevInfoVector &enumDev() PJSUA2_THROW(Error); #endif @@ -941,7 +940,7 @@ class AudDevManager /** * Enum all audio devices installed in the system. * - * @return The list of audio device info. + * @return The list of audio device info. */ AudioDevInfoVector2 enumDev2() const PJSUA2_THROW(Error); @@ -957,9 +956,9 @@ class AudDevManager * Disconnect the main conference bridge from any sound devices, and let * application connect the bridge to it's own sound device/master port. * - * @return The port interface of the conference bridge, - * so that application can connect this to it's - * own sound device or master port. + * @return The port interface of the conference bridge, + * so that application can connect this to it's + * own sound device or master port. */ MediaPort *setNoDev(); @@ -970,8 +969,8 @@ class AudDevManager * active IDs set via setCaptureDev() or setPlaybackDev(), if the flag * PJSUA_SND_DEV_NO_IMMEDIATE_OPEN is not specified. * - * @param mode The sound device mode, as bitmask combination - * of #pjsua_snd_dev_mode + * @param mode The sound device mode, as bitmask combination + * of #pjsua_snd_dev_mode * */ void setSndDevMode(unsigned mode) const PJSUA2_THROW(Error); @@ -994,10 +993,10 @@ class AudDevManager * default AEC settings and the setting will be applied next time the * sound device is opened. * - * @param tail_msec The tail length, in miliseconds. Set to zero to - * disable AEC. - * @param options Options to be passed to pjmedia_echo_create(). - * Normally the value should be zero. + * @param tail_msec The tail length, in miliseconds. Set to zero to + * disable AEC. + * @param options Options to be passed to pjmedia_echo_create(). + * Normally the value should be zero. * */ void setEcOptions(unsigned tail_msec, unsigned options) PJSUA2_THROW(Error); @@ -1005,8 +1004,8 @@ class AudDevManager /** * Get current echo canceller tail length. * - * @return The EC tail length in milliseconds, - * If AEC is disabled, the value will be zero. + * @return The EC tail length in milliseconds, + * If AEC is disabled, the value will be zero. */ unsigned getEcTail() const PJSUA2_THROW(Error); @@ -1032,8 +1031,8 @@ class AudDevManager /** * Get the number of sound devices installed in the system. * - * @return The number of sound devices installed in the - * system. + * @return The number of sound devices installed in the + * system. * */ unsigned getDevCount() const; @@ -1041,31 +1040,31 @@ class AudDevManager /** * Get device information. * - * @param id The audio device ID. + * @param id The audio device ID. * - * @return The device information which will be filled in - * by this method once it returns successfully. + * @return The device information which will be filled in + * by this method once it returns successfully. */ AudioDevInfo getDevInfo(int id) const PJSUA2_THROW(Error); /** * Lookup device index based on the driver and device name. * - * @param drv_name The driver name. - * @param dev_name The device name. + * @param drv_name The driver name. + * @param dev_name The device name. * - * @return The device ID. If the device is not found, - * Error will be thrown. + * @return The device ID. If the device is not found, + * Error will be thrown. */ int lookupDev(const string &drv_name, - const string &dev_name) const PJSUA2_THROW(Error); + const string &dev_name) const PJSUA2_THROW(Error); /** * Get string info for the specified capability. * - * @param cap The capability ID. + * @param cap The capability ID. * - * @return Capability name. + * @return Capability name. */ string capName(pjmedia_aud_dev_cap cap) const; @@ -1083,13 +1082,13 @@ class AudDevManager * to any devices, even when application has changed the sound device to be * used. * - * @param format The audio format. - * @param keep Specify whether the setting is to be kept for - * future use. + * @param format The audio format. + * @param keep Specify whether the setting is to be kept for + * future use. * */ void setExtFormat(const MediaFormatAudio &format, bool keep=true) - PJSUA2_THROW(Error); + PJSUA2_THROW(Error); /** * Get the audio format capability (other than PCM) of the sound device @@ -1103,7 +1102,7 @@ class AudDevManager * PJMEDIA_AUD_DEV_CAP_EXT_FORMAT capability in AudioDevInfo.caps flags, * otherwise Error will be thrown. * - * @return The audio format. + * @return The audio format. * */ MediaFormatAudio getExtFormat() const PJSUA2_THROW(Error); @@ -1122,9 +1121,9 @@ class AudDevManager * to any devices, even when application has changed the sound device to be * used. * - * @param latency_msec The input latency. - * @param keep Specify whether the setting is to be kept - * for future use. + * @param latency_msec The input latency. + * @param keep Specify whether the setting is to be kept + * for future use. */ void setInputLatency(unsigned latency_msec, bool keep=true) PJSUA2_THROW(Error); @@ -1141,7 +1140,7 @@ class AudDevManager * PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY capability in AudioDevInfo.caps flags, * otherwise Error will be thrown. * - * @return The audio input latency. + * @return The audio input latency. * */ unsigned getInputLatency() const PJSUA2_THROW(Error); @@ -1160,9 +1159,9 @@ class AudDevManager * to any devices, even when application has changed the sound device to be * used. * - * @param latency_msec The output latency. - * @param keep Specify whether the setting is to be kept - * for future use. + * @param latency_msec The output latency. + * @param keep Specify whether the setting is to be kept + * for future use. * */ void @@ -1180,7 +1179,7 @@ class AudDevManager * PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY capability in AudioDevInfo.caps flags, * otherwise Error will be thrown. * - * @return The audio output latency. + * @return The audio output latency. * */ unsigned getOutputLatency() const PJSUA2_THROW(Error); @@ -1200,9 +1199,9 @@ class AudDevManager * to any devices, even when application has changed the sound device to be * used. * - * @param volume The input volume level, in percent. - * @param keep Specify whether the setting is to be kept for - * future use. + * @param volume The input volume level, in percent. + * @param keep Specify whether the setting is to be kept for + * future use. * */ void setInputVolume(unsigned volume, bool keep=true) PJSUA2_THROW(Error); @@ -1219,7 +1218,7 @@ class AudDevManager * PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING capability in AudioDevInfo.caps * flags, otherwise Error will be thrown. * - * @return The audio input volume level, in percent. + * @return The audio input volume level, in percent. * */ unsigned getInputVolume() const PJSUA2_THROW(Error); @@ -1238,9 +1237,9 @@ class AudDevManager * to any devices, even when application has changed the sound device to be * used. * - * @param volume The output volume level, in percent. - * @param keep Specify whether the setting is to be kept - * for future use. + * @param volume The output volume level, in percent. + * @param keep Specify whether the setting is to be kept + * for future use. * */ void setOutputVolume(unsigned volume, bool keep=true) PJSUA2_THROW(Error); @@ -1257,7 +1256,7 @@ class AudDevManager * PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING capability in AudioDevInfo.caps * flags, otherwise Error will be thrown. * - * @return The audio output volume level, in percent. + * @return The audio output volume level, in percent. * */ unsigned getOutputVolume() const PJSUA2_THROW(Error); @@ -1274,7 +1273,7 @@ class AudDevManager * PJMEDIA_AUD_DEV_CAP_INPUT_SIGNAL_METER capability in AudioDevInfo.caps * flags, otherwise Error will be thrown. * - * @return The audio input signal level, in percent. + * @return The audio input signal level, in percent. * */ unsigned getInputSignal() const PJSUA2_THROW(Error); @@ -1291,7 +1290,7 @@ class AudDevManager * PJMEDIA_AUD_DEV_CAP_OUTPUT_SIGNAL_METER capability in AudioDevInfo.caps * flags, otherwise Error will be thrown. * - * @return The audio output signal level, in percent. + * @return The audio output signal level, in percent. * */ unsigned getOutputSignal() const PJSUA2_THROW(Error); @@ -1310,13 +1309,13 @@ class AudDevManager * to any devices, even when application has changed the sound device to be * used. * - * @param route The audio input route. - * @param keep Specify whether the setting is to be kept - * for future use. + * @param route The audio input route. + * @param keep Specify whether the setting is to be kept + * for future use. * */ void setInputRoute(pjmedia_aud_dev_route route, bool keep=true) - PJSUA2_THROW(Error); + PJSUA2_THROW(Error); /** * Get the audio input route capability of the sound device being used. @@ -1330,7 +1329,7 @@ class AudDevManager * PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE capability in AudioDevInfo.caps * flags, otherwise Error will be thrown. * - * @return The audio input route. + * @return The audio input route. * */ pjmedia_aud_dev_route getInputRoute() const PJSUA2_THROW(Error); @@ -1349,13 +1348,13 @@ class AudDevManager * to any devices, even when application has changed the sound device to be * used. * - * @param route The audio output route. - * @param keep Specify whether the setting is to be kept - * for future use. + * @param route The audio output route. + * @param keep Specify whether the setting is to be kept + * for future use. * */ void setOutputRoute(pjmedia_aud_dev_route route, bool keep=true) - PJSUA2_THROW(Error); + PJSUA2_THROW(Error); /** * Get the audio output route capability of the sound device being used. @@ -1369,7 +1368,7 @@ class AudDevManager * PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE capability in AudioDevInfo.caps * flags, otherwise Error will be thrown. * - * @return The audio output route. + * @return The audio output route. * */ pjmedia_aud_dev_route getOutputRoute() const PJSUA2_THROW(Error); @@ -1387,10 +1386,10 @@ class AudDevManager * to any devices, even when application has changed the sound device to be * used. * - * @param enable Enable/disable voice activity detection - * feature. Set true to enable. - * @param keep Specify whether the setting is to be kept for - * future use. + * @param enable Enable/disable voice activity detection + * feature. Set true to enable. + * @param keep Specify whether the setting is to be kept for + * future use. * */ void setVad(bool enable, bool keep=true) PJSUA2_THROW(Error); @@ -1406,7 +1405,7 @@ class AudDevManager * This method is only valid if the device has PJMEDIA_AUD_DEV_CAP_VAD * capability in AudioDevInfo.caps flags, otherwise Error will be thrown. * - * @return The audio voice activity detection feature. + * @return The audio voice activity detection feature. * */ bool getVad() const PJSUA2_THROW(Error); @@ -1424,10 +1423,10 @@ class AudDevManager * to any devices, even when application has changed the sound device to be * used. * - * @param enable Enable/disable comfort noise generation - * feature. Set true to enable. - * @param keep Specify whether the setting is to be kept for - * future use. + * @param enable Enable/disable comfort noise generation + * feature. Set true to enable. + * @param keep Specify whether the setting is to be kept for + * future use. * */ void setCng(bool enable, bool keep=true) PJSUA2_THROW(Error); @@ -1443,7 +1442,7 @@ class AudDevManager * This method is only valid if the device has PJMEDIA_AUD_DEV_CAP_CNG * capability in AudioDevInfo.caps flags, otherwise Error will be thrown. * - * @return The audio comfort noise generation feature. + * @return The audio comfort noise generation feature. * */ bool getCng() const PJSUA2_THROW(Error); @@ -1461,10 +1460,10 @@ class AudDevManager * to any devices, even when application has changed the sound device to be * used. * - * @param enable Enable/disable packet loss concealment - * feature. Set true to enable. - * @param keep Specify whether the setting is to be kept for - * future use. + * @param enable Enable/disable packet loss concealment + * feature. Set true to enable. + * @param keep Specify whether the setting is to be kept for + * future use. * */ void setPlc(bool enable, bool keep=true) PJSUA2_THROW(Error); @@ -1480,16 +1479,16 @@ class AudDevManager * This method is only valid if the device has PJMEDIA_AUD_DEV_CAP_PLC * capability in AudioDevInfo.caps flags, otherwise Error will be thrown. * - * @return The audio packet loss concealment feature. + * @return The audio packet loss concealment feature. * */ bool getPlc() const PJSUA2_THROW(Error); private: #if !DEPRECATED_FOR_TICKET_2232 - AudioDevInfoVector audioDevList; + AudioDevInfoVector audioDevList; #endif - AudioMedia *devMedia; + AudioMedia *devMedia; /** * Constructor. @@ -1528,8 +1527,8 @@ class ExtraAudioDevice : public AudioMedia /** * Constructor. * - * @param playdev Playback device ID. - * @param recdev Record device ID. + * @param playdev Playback device ID. + * @param recdev Record device ID. */ ExtraAudioDevice(int playdev, int recdev); @@ -1555,7 +1554,7 @@ class ExtraAudioDevice : public AudioMedia /** * Is the extra audio device opened? * - * @return 'true' if it is opened. + * @return 'true' if it is opened. */ bool isOpened(); @@ -1575,8 +1574,8 @@ class ExtraAudioDevice : public AudioMedia */ struct MediaCoordinate { - int x; /**< X position of the coordinate */ - int y; /**< Y position of the coordinate */ + int x; /**< X position of the coordinate */ + int y; /**< Y position of the coordinate */ }; /** @@ -1584,8 +1583,8 @@ struct MediaCoordinate */ struct MediaSize { - unsigned w; /**< The width. */ - unsigned h; /**< The height. */ + unsigned w; /**< The width. */ + unsigned h; /**< The height. */ }; @@ -1598,29 +1597,29 @@ struct VidConfPortInfo /** * Conference port number. */ - int portId; + int portId; /** * Port name. */ - string name; + string name; /** * Media audio format information */ - MediaFormatVideo format; + MediaFormatVideo format; /** * Array of listeners (in other words, ports where this port is * transmitting to). */ - IntVector listeners; + IntVector listeners; /** * Array of listeners (in other words, ports where this port is * listening to). */ - IntVector transmitters; + IntVector transmitters; public: /** @@ -1668,17 +1667,17 @@ class VideoMedia : public Media * this method twice, with the second one called from the opposite source * media. * - * @param sink The destination Media. - * @param param The parameter. + * @param sink The destination Media. + * @param param The parameter. */ void startTransmit(const VideoMedia &sink, - const VideoMediaTransmitParam ¶m) const + const VideoMediaTransmitParam ¶m) const PJSUA2_THROW(Error); /** * Stop media flow to destination/sink port. * - * @param sink The destination media. + * @param sink The destination media. * */ void stopTransmit(const VideoMedia &sink) const PJSUA2_THROW(Error); @@ -1711,7 +1710,7 @@ class VideoMedia : public Media /** * Conference port Id. */ - int id; + int id; protected: /** @@ -1741,8 +1740,8 @@ typedef std::vector VideoMediaVector; * Window handle. */ typedef struct WindowHandle { - void *window; /**< Window */ - void *display; /**< Display */ + void *window; /**< Window */ + void *display; /**< Display */ } WindowHandle; /** @@ -1753,12 +1752,12 @@ struct VideoWindowHandle /** * The window handle type. */ - pjmedia_vid_dev_hwnd_type type; + pjmedia_vid_dev_hwnd_type type; /** * The window handle. */ - WindowHandle handle; + WindowHandle handle; }; /** @@ -1772,32 +1771,32 @@ typedef struct VideoWindowInfo * true, only the video window handle field of this * structure is valid. */ - bool isNative; + bool isNative; /** * Video window handle. */ - VideoWindowHandle winHandle; + VideoWindowHandle winHandle; /** * Renderer device ID. */ - int renderDeviceId; + int renderDeviceId; /** * Window show status. The window is hidden if false. */ - bool show; + bool show; /** * Window position. */ - MediaCoordinate pos; + MediaCoordinate pos; /** * Window size. */ - MediaSize size; + MediaSize size; } VideoWindowInfo; @@ -1815,7 +1814,7 @@ class VideoWindow /** * Get window info. * - * @return video window info. + * @return video window info. */ VideoWindowInfo getInfo() const PJSUA2_THROW(Error); @@ -1823,7 +1822,7 @@ class VideoWindow * Get video media or conference bridge port of the renderer of * this video window. * - * @return Video media of this renderer window. + * @return Video media of this renderer window. */ VideoMedia getVideoMedia() PJSUA2_THROW(Error); @@ -1832,8 +1831,8 @@ class VideoWindow * (VideoWindowInfo.isNative=true), on which native windowing API * must be used instead. * - * @param show Set to true to show the window, false to - * hide the window. + * @param show Set to true to show the window, false to + * hide the window. * */ void Show(bool show) PJSUA2_THROW(Error); @@ -1843,7 +1842,7 @@ class VideoWindow * (VideoWindowInfo.isNative=true), on which native windowing API * must be used instead. * - * @param pos The window position. + * @param pos The window position. * */ void setPos(const MediaCoordinate &pos) PJSUA2_THROW(Error); @@ -1853,7 +1852,7 @@ class VideoWindow * (VideoWindowInfo.isNative=true), on which native windowing API * must be used instead. * - * @param size The new window size. + * @param size The new window size. * */ void setSize(const MediaSize &size) PJSUA2_THROW(Error); @@ -1864,10 +1863,10 @@ class VideoWindow * This operation is not valid for native windows (VideoWindowInfo.isNative * =true), on which native windowing API must be used instead. * - * @param angle The rotation angle in degrees, must be - * multiple of 90. - * Specify positive value for clockwise rotation or - * negative value for counter-clockwise rotation. + * @param angle The rotation angle in degrees, must be + * multiple of 90. + * Specify positive value for clockwise rotation or + * negative value for counter-clockwise rotation. */ void rotate(int angle) PJSUA2_THROW(Error); @@ -1877,7 +1876,7 @@ class VideoWindow * allows the output window to be changed on-the-fly, otherwise Error will * be thrown. Currently it is only supported on Android. * - * @param win The new output window. + * @param win The new output window. */ void setWindow(const VideoWindowHandle &win) PJSUA2_THROW(Error); @@ -1886,8 +1885,8 @@ class VideoWindow * underlying video device supports PJMEDIA_VID_DEV_CAP_OUTPUT_FULLSCREEN * capability. Currently it is only supported on SDL backend. * - * @param enabled Set to true if full screen is desired, false - * otherwise. + * @param enabled Set to true if full screen is desired, false + * otherwise. */ void setFullScreen(bool enabled) PJSUA2_THROW(Error); @@ -1896,14 +1895,14 @@ class VideoWindow * underlying video device supports PJMEDIA_VID_DEV_CAP_OUTPUT_FULLSCREEN * capability. Currently it is only supported on SDL backend. * - * @param mode Fullscreen mode, see - * pjmedia_vid_dev_fullscreen_flag. + * @param mode Fullscreen mode, see + * pjmedia_vid_dev_fullscreen_flag. */ void setFullScreen2(pjmedia_vid_dev_fullscreen_flag mode) - PJSUA2_THROW(Error); + PJSUA2_THROW(Error); private: - pjsua_vid_win_id winId; + pjsua_vid_win_id winId; }; /** @@ -1924,7 +1923,7 @@ struct VideoPreviewOpParam { * * Default: PJ_TRUE. */ - bool show; + bool show; /** * Window flags. The value is a bitmask combination of @@ -1932,12 +1931,12 @@ struct VideoPreviewOpParam { * * Default: 0. */ - unsigned windowFlags; + unsigned windowFlags; /** * Media format. If left unitialized, this parameter will not be used. */ - MediaFormat format; + MediaFormat format; /** * Optional output window to be used to display the video preview. @@ -1945,7 +1944,7 @@ struct VideoPreviewOpParam { * PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW capability and the capability * is not read-only. */ - VideoWindowHandle window; + VideoWindowHandle window; public: /** @@ -1980,14 +1979,14 @@ class VideoPreview { * querying device's capability for PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW * capability. * - * @return true if it has. + * @return true if it has. */ bool hasNative(); /** * Start video preview window for the specified capture device. * - * @param param Video preview parameters. + * @param param Video preview parameters. */ void start(const VideoPreviewOpParam ¶m) PJSUA2_THROW(Error); @@ -2004,7 +2003,7 @@ class VideoPreview { /** * Get video media or conference bridge port of the video capture device. * - * @return Video media of the video capture device. + * @return Video media of the video capture device. */ VideoMedia getVideoMedia() PJSUA2_THROW(Error); @@ -2124,16 +2123,16 @@ class VidDevManager { /** * Get the number of video devices installed in the system. * - * @return The number of devices. + * @return The number of devices. */ unsigned getDevCount(); /** * Retrieve the video device info for the specified device index. * - * @param dev_id The video device id + * @param dev_id The video device id * - * @return The list of video device info + * @return The list of video device info */ VideoDevInfo getDevInfo(int dev_id) const PJSUA2_THROW(Error); @@ -2144,7 +2143,7 @@ class VidDevManager { * * Enum all video devices installed in the system. * - * @return The list of video device info + * @return The list of video device info */ const VideoDevInfoVector &enumDev() PJSUA2_THROW(Error); #endif @@ -2152,28 +2151,28 @@ class VidDevManager { /** * Enum all video devices installed in the system. * - * @return The list of video device info + * @return The list of video device info */ VideoDevInfoVector2 enumDev2() const PJSUA2_THROW(Error); /** * Lookup device index based on the driver and device name. * - * @param drv_name The driver name. - * @param dev_name The device name. + * @param drv_name The driver name. + * @param dev_name The device name. * - * @return The device ID. If the device is not found, - * Error will be thrown. + * @return The device ID. If the device is not found, + * Error will be thrown. */ int lookupDev(const string &drv_name, - const string &dev_name) const PJSUA2_THROW(Error); + const string &dev_name) const PJSUA2_THROW(Error); /** * Get string info for the specified capability. * - * @param cap The capability ID. + * @param cap The capability ID. * - * @return Capability name. + * @return Capability name. */ string capName(pjmedia_vid_dev_cap cap) const; @@ -2191,14 +2190,14 @@ class VidDevManager { * to any devices, even when application has changed the video device to be * used. * - * @param dev_id The video device id. - * @param format The video format. - * @param keep Specify whether the setting is to be kept for - * future use. + * @param dev_id The video device id. + * @param format The video format. + * @param keep Specify whether the setting is to be kept for + * future use. */ void setFormat(int dev_id, - const MediaFormatVideo &format, - bool keep) PJSUA2_THROW(Error); + const MediaFormatVideo &format, + bool keep) PJSUA2_THROW(Error); /** * Get the video format capability to the video device. @@ -2212,8 +2211,8 @@ class VidDevManager { * PJMEDIA_VID_DEV_CAP_FORMAT capability in VideoDevInfo.caps flags, * otherwise Error will be thrown. * - * @param dev_id The video device id. - * @return keep The video format. + * @param dev_id The video device id. + * @return keep The video format. */ MediaFormatVideo getFormat(int dev_id) const PJSUA2_THROW(Error); @@ -2231,14 +2230,14 @@ class VidDevManager { * to any devices, even when application has changed the video device to be * used. * - * @param dev_id The video device id. - * @param scale The video scale. - * @param keep Specify whether the setting is to be kept for - * future use. + * @param dev_id The video device id. + * @param scale The video scale. + * @param keep Specify whether the setting is to be kept for + * future use. */ void setInputScale(int dev_id, - const MediaSize &scale, - bool keep) PJSUA2_THROW(Error); + const MediaSize &scale, + bool keep) PJSUA2_THROW(Error); /** * Get the video input scale capability to the video device. @@ -2252,8 +2251,8 @@ class VidDevManager { * PJMEDIA_VID_DEV_CAP_FORMAT capability in VideoDevInfo.caps flags, * otherwise Error will be thrown. * - * @param dev_id The video device id. - * @return keep The video format. + * @param dev_id The video device id. + * @return keep The video format. */ MediaSize getInputScale(int dev_id) const PJSUA2_THROW(Error); @@ -2271,13 +2270,13 @@ class VidDevManager { * to any devices, even when application has changed the video device to be * used. * - * @param dev_id The video device id. - * @param flags The video window flag. - * @param keep Specify whether the setting is to be kept for - * future use. + * @param dev_id The video device id. + * @param flags The video window flag. + * @param keep Specify whether the setting is to be kept for + * future use. */ void setOutputWindowFlags(int dev_id, int flags, bool keep) - PJSUA2_THROW(Error); + PJSUA2_THROW(Error); /** * Get the window output flags capability to the video device. @@ -2291,8 +2290,8 @@ class VidDevManager { * PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS capability in VideoDevInfo.caps * flags, otherwise Error will be thrown. * - * @param dev_id The video device id. - * @return keep The video format. + * @param dev_id The video device id. + * @return keep The video format. */ int getOutputWindowFlags(int dev_id) PJSUA2_THROW(Error); @@ -2306,20 +2305,20 @@ class VidDevManager { * PJMEDIA_VID_DEV_CAP_SWITCH capability in VideoDevInfo.caps flags, * otherwise Error will be thrown. * - * @param dev_id The video device id. - * @param param The video switch param. + * @param dev_id The video device id. + * @param param The video switch param. */ void switchDev(int dev_id, - const VideoSwitchParam ¶m) PJSUA2_THROW(Error); + const VideoSwitchParam ¶m) PJSUA2_THROW(Error); /** * Check whether the video capture device is currently active, i.e. if * a video preview has been started or there is a video call using * the device. * - * @param dev_id The video device id + * @param dev_id The video device id * - * @return True if it's active. + * @return True if it's active. */ bool isCaptureActive(int dev_id) const; @@ -2335,15 +2334,15 @@ class VidDevManager { * currently inactive, and the "keep" argument is false, this method * will throw Error. * - * @param dev_id The video device id - * @param orient The video orientation. - * @param keep Specify whether the setting is to be kept for - * future use. + * @param dev_id The video device id + * @param orient The video orientation. + * @param keep Specify whether the setting is to be kept for + * future use. * */ void setCaptureOrient(pjmedia_vid_dev_index dev_id, - pjmedia_orient orient, - bool keep=true) PJSUA2_THROW(Error); + pjmedia_orient orient, + bool keep=true) PJSUA2_THROW(Error); private: #if !DEPRECATED_FOR_TICKET_2232 @@ -2378,17 +2377,17 @@ struct CodecInfo /** * Codec unique identification. */ - string codecId; + string codecId; /** * Codec priority (integer 0-255). */ - pj_uint8_t priority; + pj_uint8_t priority; /** * Codec description. */ - string desc; + string desc; /** * Construct from pjsua_codec_info. @@ -2425,19 +2424,19 @@ typedef std::vector CodecFmtpVector; */ struct CodecParamInfo { - unsigned clockRate; /**< Sampling rate in Hz */ - unsigned channelCnt; /**< Channel count. */ - unsigned avgBps; /**< Average bandwidth in bits/sec */ - unsigned maxBps; /**< Maximum bandwidth in bits/sec */ - unsigned maxRxFrameSize; /**< Maximum frame size */ - unsigned frameLen; /**< Decoder frame ptime in msec. */ - unsigned encFrameLen; /**< Encoder ptime, or zero if it's - equal to decoder ptime. */ - unsigned pcmBitsPerSample; /**< Bits/sample in the PCM side */ - unsigned pt; /**< Payload type. */ - pjmedia_format_id fmtId; /**< Source format, it's format of - encoder input and decoder - output. */ + unsigned clockRate; /**< Sampling rate in Hz */ + unsigned channelCnt; /**< Channel count. */ + unsigned avgBps; /**< Average bandwidth in bits/sec */ + unsigned maxBps; /**< Maximum bandwidth in bits/sec */ + unsigned maxRxFrameSize; /**< Maximum frame size */ + unsigned frameLen; /**< Decoder frame ptime in msec. */ + unsigned encFrameLen; /**< Encoder ptime, or zero if it's + equal to decoder ptime. */ + unsigned pcmBitsPerSample; /**< Bits/sample in the PCM side */ + unsigned pt; /**< Payload type. */ + pjmedia_format_id fmtId; /**< Source format, it's format of + encoder input and decoder + output. */ public: /** * Default constructor @@ -2451,17 +2450,17 @@ struct CodecParamInfo */ struct CodecParamSetting { - unsigned frmPerPkt; /**< Number of frames per packet. */ - bool vad; /**< Voice Activity Detector. */ - bool cng; /**< Comfort Noise Generator. */ - bool penh; /**< Perceptual Enhancement */ - bool plc; /**< Packet loss concealment */ - bool reserved; /**< Reserved, must be zero. */ - CodecFmtpVector encFmtp; /**< Encoder's fmtp params. */ - CodecFmtpVector decFmtp; /**< Decoder's fmtp params. */ - unsigned packetLoss; /**< Encoder's expected pkt loss %. */ - unsigned complexity; /**< Encoder complexity, 0-10(max). */ - bool cbr; /**< Constant bit rate? */ + unsigned frmPerPkt; /**< Number of frames per packet. */ + bool vad; /**< Voice Activity Detector. */ + bool cng; /**< Comfort Noise Generator. */ + bool penh; /**< Perceptual Enhancement */ + bool plc; /**< Packet loss concealment */ + bool reserved; /**< Reserved, must be zero. */ + CodecFmtpVector encFmtp; /**< Encoder's fmtp params. */ + CodecFmtpVector decFmtp; /**< Decoder's fmtp params. */ + unsigned packetLoss; /**< Encoder's expected pkt loss %. */ + unsigned complexity; /**< Encoder complexity, 0-10(max). */ + bool cbr; /**< Constant bit rate? */ }; /** @@ -2492,11 +2491,11 @@ struct CodecOpusConfig { unsigned sample_rate; /**< Sample rate in Hz. */ unsigned channel_cnt; /**< Number of channels. */ - unsigned frm_ptime; /**< Frame time in msec. */ - unsigned bit_rate; /**< Encoder bit rate in bps. */ - unsigned packet_loss; /**< Encoder's expected packet loss pct. */ + unsigned frm_ptime; /**< Frame time in msec. */ + unsigned bit_rate; /**< Encoder bit rate in bps. */ + unsigned packet_loss; /**< Encoder's expected packet loss pct. */ unsigned complexity; /**< Encoder complexity, 0-10(10 is highest)*/ - bool cbr; /**< Constant bit rate? */ + bool cbr; /**< Constant bit rate? */ pjmedia_codec_opus_config toPj() const; void fromPj(const pjmedia_codec_opus_config &config); @@ -2513,28 +2512,28 @@ struct CodecOpusConfig struct VidCodecParam { pjmedia_dir dir; /**< Direction */ - pjmedia_vid_packing packing; /**< Packetization strategy. */ + pjmedia_vid_packing packing; /**< Packetization strategy. */ struct - MediaFormatVideo encFmt; /**< Encoded format */ - CodecFmtpVector encFmtp; /**< Encoder fmtp params */ + MediaFormatVideo encFmt; /**< Encoded format */ + CodecFmtpVector encFmtp; /**< Encoder fmtp params */ unsigned encMtu; /**< MTU or max payload size setting*/ struct - MediaFormatVideo decFmt; /**< Decoded format */ - CodecFmtpVector decFmtp; /**< Decoder fmtp params */ + MediaFormatVideo decFmt; /**< Decoded format */ + CodecFmtpVector decFmtp; /**< Decoder fmtp params */ - bool ignoreFmtp; /**< Ignore fmtp params. If set to - true, the codec will apply - format settings specified in - encFmt and decFmt only. */ + bool ignoreFmtp; /**< Ignore fmtp params. If set to + true, the codec will apply + format settings specified in + encFmt and decFmt only. */ public: /** * Default constructor */ VidCodecParam() : dir(PJMEDIA_DIR_NONE), - packing(PJMEDIA_VID_PACKING_UNKNOWN) + packing(PJMEDIA_VID_PACKING_UNKNOWN) {} void fromPj(const pjmedia_vid_codec_param ¶m); @@ -2561,9 +2560,9 @@ struct MediaFmtChangedEvent */ struct AudDevErrorEvent { - pjmedia_dir dir; /**< The direction. */ - int id; /**< The audio device ID. */ - pj_status_t status; /**< The status code. */ + pjmedia_dir dir; /**< The direction. */ + int id; /**< The audio device ID. */ + pj_status_t status; /**< The status code. */ }; /** @@ -2578,13 +2577,13 @@ typedef union MediaEventData { /** * Audio device error event data. */ - AudDevErrorEvent audDevError; + AudDevErrorEvent audDevError; /** * Pointer to storage to user event data, if it's outside * this struct */ - GenericData ptr; + GenericData ptr; } MediaEventData; @@ -2630,4 +2629,4 @@ struct MediaEvent } // namespace pj -#endif /* __PJSUA2_MEDIA_HPP__ */ +#endif /* __PJSUA2_MEDIA_HPP__ */ diff --git a/pjsip/include/pjsua2/persistent.hpp b/pjsip/include/pjsua2/persistent.hpp index 858d22b4f0..494c95c2d2 100644 --- a/pjsip/include/pjsua2/persistent.hpp +++ b/pjsip/include/pjsua2/persistent.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -66,14 +65,14 @@ class PersistentObject /** * Read this object from a container node. * - * @param node Container to read values from. + * @param node Container to read values from. */ virtual void readObject(const ContainerNode &node) PJSUA2_THROW(Error) = 0; /** * Write this object to a container node. * - * @param node Container to write values to. + * @param node Container to write values to. */ virtual void writeObject(ContainerNode &node) const PJSUA2_THROW(Error) = 0; }; @@ -108,38 +107,38 @@ class PersistentDocument /** * Load this document from a file. * - * @param filename The file name. + * @param filename The file name. */ - virtual void loadFile(const string &filename) - PJSUA2_THROW(Error) = 0; + virtual void loadFile(const string &filename) + PJSUA2_THROW(Error) = 0; /** * Load this document from string. * - * @param input The string. + * @param input The string. */ - virtual void loadString(const string &input) - PJSUA2_THROW(Error) = 0; + virtual void loadString(const string &input) + PJSUA2_THROW(Error) = 0; /** * Write this document to a file. * - * @param filename The file name. + * @param filename The file name. */ - virtual void saveFile(const string &filename) - PJSUA2_THROW(Error) = 0; + virtual void saveFile(const string &filename) + PJSUA2_THROW(Error) = 0; /** * Write this document to string. * - * @return The string document. + * @return The string document. */ - virtual string saveString() PJSUA2_THROW(Error) = 0; + virtual string saveString() PJSUA2_THROW(Error) = 0; /** * Get the root container node for this document * - * @return The root node. + * @return The root node. */ virtual ContainerNode & getRootContainer() const = 0; @@ -153,201 +152,201 @@ class PersistentDocument * Determine if there is unread element. If yes, then app can use one of * the readXxx() functions to read it. * - * @return True if there is. + * @return True if there is. */ - bool hasUnread() const; + bool hasUnread() const; /** * Get the name of the next unread element. It will throw Error if there * is no more element to read. * - * @return The name of the next element . + * @return The name of the next element . */ - string unreadName() const PJSUA2_THROW(Error); + string unreadName() const PJSUA2_THROW(Error); /** * Read an integer value from the document and return the value. * This will throw Error if the current element is not a number. * The read position will be advanced to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return The value. + * @return The value. */ - int readInt(const string &name="") const - PJSUA2_THROW(Error); + int readInt(const string &name="") const + PJSUA2_THROW(Error); /** * Read a float value from the document and return the value. * This will throw Error if the current element is not a number. * The read position will be advanced to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return The value. + * @return The value. */ - float readNumber(const string &name="") const - PJSUA2_THROW(Error); + float readNumber(const string &name="") const + PJSUA2_THROW(Error); /** * Read a boolean value from the container and return the value. * This will throw Error if the current element is not a boolean. * The read position will be advanced to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return The value. + * @return The value. */ - bool readBool(const string &name="") const - PJSUA2_THROW(Error); + bool readBool(const string &name="") const + PJSUA2_THROW(Error); /** * Read a string value from the container and return the value. * This will throw Error if the current element is not a string. * The read position will be advanced to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return The value. + * @return The value. */ - string readString(const string &name="") const - PJSUA2_THROW(Error); + string readString(const string &name="") const + PJSUA2_THROW(Error); /** * Read a string array from the container. This will throw Error * if the current element is not a string array. The read position * will be advanced to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return The value. + * @return The value. */ - StringVector readStringVector(const string &name="") const - PJSUA2_THROW(Error); + StringVector readStringVector(const string &name="") const + PJSUA2_THROW(Error); /** * Read the specified object from the container. This is equal to * calling PersistentObject.readObject(ContainerNode); * - * @param obj The object to read. + * @param obj The object to read. */ - void readObject(PersistentObject &obj) const - PJSUA2_THROW(Error); + void readObject(PersistentObject &obj) const + PJSUA2_THROW(Error); /** * Read a container from the container. This will throw Error if the * current element is not an object. The read position will be advanced * to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return Container object. + * @return Container object. */ - ContainerNode readContainer(const string &name="") const - PJSUA2_THROW(Error); + ContainerNode readContainer(const string &name="") const + PJSUA2_THROW(Error); /** * Read array container from the container. This will throw Error if the * current element is not an array. The read position will be advanced * to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return Container object. + * @return Container object. */ - ContainerNode readArray(const string &name="") const - PJSUA2_THROW(Error); + ContainerNode readArray(const string &name="") const + PJSUA2_THROW(Error); /** * Write a number value to the container. * - * @param name The name for the value in the container. - * @param num The value to be written. + * @param name The name for the value in the container. + * @param num The value to be written. */ - void writeNumber(const string &name, - float num) PJSUA2_THROW(Error); + void writeNumber(const string &name, + float num) PJSUA2_THROW(Error); /** * Write a number value to the container. * - * @param name The name for the value in the container. - * @param num The value to be written. + * @param name The name for the value in the container. + * @param num The value to be written. */ - void writeInt(const string &name, - int num) PJSUA2_THROW(Error); + void writeInt(const string &name, + int num) PJSUA2_THROW(Error); /** * Write a boolean value to the container. * - * @param name The name for the value in the container. - * @param value The value to be written. + * @param name The name for the value in the container. + * @param value The value to be written. */ - void writeBool(const string &name, - bool value) PJSUA2_THROW(Error); + void writeBool(const string &name, + bool value) PJSUA2_THROW(Error); /** * Write a string value to the container. * - * @param name The name for the value in the container. - * @param value The value to be written. + * @param name The name for the value in the container. + * @param value The value to be written. */ - void writeString(const string &name, - const string &value) PJSUA2_THROW(Error); + void writeString(const string &name, + const string &value) PJSUA2_THROW(Error); /** * Write string vector to the container. * - * @param name The name for the value in the container. - * @param arr The vector to be written. + * @param name The name for the value in the container. + * @param arr The vector to be written. */ - void writeStringVector(const string &name, - const StringVector &arr) - PJSUA2_THROW(Error); + void writeStringVector(const string &name, + const StringVector &arr) + PJSUA2_THROW(Error); /** * Write an object to the container. This is equal to calling * PersistentObject.writeObject(ContainerNode); * - * @param obj The object to be written + * @param obj The object to be written */ - void writeObject(const PersistentObject &obj) - PJSUA2_THROW(Error); + void writeObject(const PersistentObject &obj) + PJSUA2_THROW(Error); /** * Create and write an empty Object node that can be used as parent * for subsequent write operations. * - * @param name The name for the new container in the container. + * @param name The name for the new container in the container. * - * @return A sub-container. + * @return A sub-container. */ - ContainerNode writeNewContainer(const string &name) - PJSUA2_THROW(Error); + ContainerNode writeNewContainer(const string &name) + PJSUA2_THROW(Error); /** * Create and write an empty array node that can be used as parent * for subsequent write operations. * - * @param name The name for the array. + * @param name The name for the array. * - * @return A sub-container. + * @return A sub-container. */ - ContainerNode writeNewArray(const string &name) - PJSUA2_THROW(Error); + ContainerNode writeNewArray(const string &name) + PJSUA2_THROW(Error); }; @@ -363,9 +362,9 @@ struct container_node_op; */ struct container_node_internal_data { - void *doc; /**< The document. */ - void *data1; /**< Internal data 1 */ - void *data2; /**< Internal data 2 */ + void *doc; /**< The document. */ + void *data1; /**< Internal data 1 */ + void *data2; /**< Internal data 2 */ }; /** @@ -380,22 +379,22 @@ struct container_node_internal_data * write data to it using the various write methods. Alternatively, it * may be more convenient to use the provided macros below to read and write * the data, because these macros set the name automatically: - * - NODE_READ_BOOL(node,item) - * - NODE_READ_UNSIGNED(node,item) - * - NODE_READ_INT(node,item) - * - NODE_READ_FLOAT(node,item) - * - NODE_READ_NUM_T(node,type,item) - * - NODE_READ_STRING(node,item) - * - NODE_READ_STRINGV(node,item) - * - NODE_READ_OBJ(node,item) - * - NODE_WRITE_BOOL(node,item) - * - NODE_WRITE_UNSIGNED(node,item) - * - NODE_WRITE_INT(node,item) - * - NODE_WRITE_FLOAT(node,item) - * - NODE_WRITE_NUM_T(node,type,item) - * - NODE_WRITE_STRING(node,item) - * - NODE_WRITE_STRINGV(node,item) - * - NODE_WRITE_OBJ(node,item) + * - NODE_READ_BOOL(node,item) + * - NODE_READ_UNSIGNED(node,item) + * - NODE_READ_INT(node,item) + * - NODE_READ_FLOAT(node,item) + * - NODE_READ_NUM_T(node,type,item) + * - NODE_READ_STRING(node,item) + * - NODE_READ_STRINGV(node,item) + * - NODE_READ_OBJ(node,item) + * - NODE_WRITE_BOOL(node,item) + * - NODE_WRITE_UNSIGNED(node,item) + * - NODE_WRITE_INT(node,item) + * - NODE_WRITE_FLOAT(node,item) + * - NODE_WRITE_NUM_T(node,type,item) + * - NODE_WRITE_STRING(node,item) + * - NODE_WRITE_STRINGV(node,item) + * - NODE_WRITE_OBJ(node,item) * * Implementation notes: * @@ -426,201 +425,201 @@ class ContainerNode * Determine if there is unread element. If yes, then app can use one of * the readXxx() functions to read it. */ - bool hasUnread() const; + bool hasUnread() const; /** * Get the name of the next unread element. */ - string unreadName() const PJSUA2_THROW(Error); + string unreadName() const PJSUA2_THROW(Error); /** * Read an integer value from the document and return the value. * This will throw Error if the current element is not a number. * The read position will be advanced to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return The value. + * @return The value. */ - int readInt(const string &name="") const - PJSUA2_THROW(Error); + int readInt(const string &name="") const + PJSUA2_THROW(Error); /** * Read a number value from the document and return the value. * This will throw Error if the current element is not a number. * The read position will be advanced to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return The value. + * @return The value. */ - float readNumber(const string &name="") const - PJSUA2_THROW(Error); + float readNumber(const string &name="") const + PJSUA2_THROW(Error); /** * Read a boolean value from the container and return the value. * This will throw Error if the current element is not a boolean. * The read position will be advanced to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return The value. + * @return The value. */ - bool readBool(const string &name="") const - PJSUA2_THROW(Error); + bool readBool(const string &name="") const + PJSUA2_THROW(Error); /** * Read a string value from the container and return the value. * This will throw Error if the current element is not a string. * The read position will be advanced to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return The value. + * @return The value. */ - string readString(const string &name="") const - PJSUA2_THROW(Error); + string readString(const string &name="") const + PJSUA2_THROW(Error); /** * Read a string array from the container. This will throw Error * if the current element is not a string array. The read position * will be advanced to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return The value. + * @return The value. */ - StringVector readStringVector(const string &name="") const - PJSUA2_THROW(Error); + StringVector readStringVector(const string &name="") const + PJSUA2_THROW(Error); /** * Read the specified object from the container. This is equal to * calling PersistentObject.readObject(ContainerNode); * - * @param obj The object to read. + * @param obj The object to read. */ - void readObject(PersistentObject &obj) const - PJSUA2_THROW(Error); + void readObject(PersistentObject &obj) const + PJSUA2_THROW(Error); /** * Read a container from the container. This will throw Error if the * current element is not a container. The read position will be advanced * to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return Container object. + * @return Container object. */ - ContainerNode readContainer(const string &name="") const - PJSUA2_THROW(Error); + ContainerNode readContainer(const string &name="") const + PJSUA2_THROW(Error); /** * Read array container from the container. This will throw Error if the * current element is not an array. The read position will be advanced * to the next element. * - * @param name If specified, then the function will check if the - * name of the next element matches the specified - * name and throw Error if it doesn't match. + * @param name If specified, then the function will check if the + * name of the next element matches the specified + * name and throw Error if it doesn't match. * - * @return Container object. + * @return Container object. */ - ContainerNode readArray(const string &name="") const - PJSUA2_THROW(Error); + ContainerNode readArray(const string &name="") const + PJSUA2_THROW(Error); /** * Write a number value to the container. * - * @param name The name for the value in the container. - * @param num The value to be written. + * @param name The name for the value in the container. + * @param num The value to be written. */ - void writeNumber(const string &name, - float num) PJSUA2_THROW(Error); + void writeNumber(const string &name, + float num) PJSUA2_THROW(Error); /** * Write a number value to the container. * - * @param name The name for the value in the container. - * @param num The value to be written. + * @param name The name for the value in the container. + * @param num The value to be written. */ - void writeInt(const string &name, - int num) PJSUA2_THROW(Error); + void writeInt(const string &name, + int num) PJSUA2_THROW(Error); /** * Write a boolean value to the container. * - * @param name The name for the value in the container. - * @param value The value to be written. + * @param name The name for the value in the container. + * @param value The value to be written. */ - void writeBool(const string &name, - bool value) PJSUA2_THROW(Error); + void writeBool(const string &name, + bool value) PJSUA2_THROW(Error); /** * Write a string value to the container. * - * @param name The name for the value in the container. - * @param value The value to be written. + * @param name The name for the value in the container. + * @param value The value to be written. */ - void writeString(const string &name, - const string &value) PJSUA2_THROW(Error); + void writeString(const string &name, + const string &value) PJSUA2_THROW(Error); /** * Write string vector to the container. * - * @param name The name for the value in the container. - * @param arr The vector to be written. + * @param name The name for the value in the container. + * @param arr The vector to be written. */ - void writeStringVector(const string &name, - const StringVector &arr) - PJSUA2_THROW(Error); + void writeStringVector(const string &name, + const StringVector &arr) + PJSUA2_THROW(Error); /** * Write an object to the container. This is equal to calling * PersistentObject.writeObject(ContainerNode); * - * @param obj The object to be written + * @param obj The object to be written */ - void writeObject(const PersistentObject &obj) - PJSUA2_THROW(Error); + void writeObject(const PersistentObject &obj) + PJSUA2_THROW(Error); /** * Create and write an empty Object node that can be used as parent * for subsequent write operations. * - * @param name The name for the new container in the container. + * @param name The name for the new container in the container. * - * @return A sub-container. + * @return A sub-container. */ - ContainerNode writeNewContainer(const string &name) - PJSUA2_THROW(Error); + ContainerNode writeNewContainer(const string &name) + PJSUA2_THROW(Error); /** * Create and write an empty array node that can be used as parent * for subsequent write operations. * - * @param name The name for the array. + * @param name The name for the array. * - * @return A sub-container. + * @return A sub-container. */ - ContainerNode writeNewArray(const string &name) - PJSUA2_THROW(Error); + ContainerNode writeNewArray(const string &name) + PJSUA2_THROW(Error); public: /* internal data */ - container_node_op *op; /**< Method table. */ - container_node_internal_data data; /**< Internal data */ + container_node_op *op; /**< Method table. */ + container_node_internal_data data; /**< Internal data */ }; @@ -631,71 +630,71 @@ class ContainerNode //! @cond Doxygen_Suppress struct container_node_op { - bool (*hasUnread)(const ContainerNode*); - string (*unreadName)(const ContainerNode*) - PJSUA2_THROW(Error); - float (*readNumber)(const ContainerNode*, - const string&) - PJSUA2_THROW(Error); - bool (*readBool)(const ContainerNode*, - const string&) - PJSUA2_THROW(Error); - string (*readString)(const ContainerNode*, - const string&) - PJSUA2_THROW(Error); - StringVector (*readStringVector)(const ContainerNode*, - const string&) - PJSUA2_THROW(Error); - ContainerNode (*readContainer)(const ContainerNode*, - const string &) - PJSUA2_THROW(Error); - ContainerNode (*readArray)(const ContainerNode*, - const string &) - PJSUA2_THROW(Error); - void (*writeNumber)(ContainerNode*, - const string &name, - float num) - PJSUA2_THROW(Error); - void (*writeBool)(ContainerNode*, - const string &name, - bool value) - PJSUA2_THROW(Error); - void (*writeString)(ContainerNode*, - const string &name, - const string &value) - PJSUA2_THROW(Error); - void (*writeStringVector)(ContainerNode*, - const string &name, - const StringVector &value) - PJSUA2_THROW(Error); - ContainerNode (*writeNewContainer)(ContainerNode*, - const string &name) - PJSUA2_THROW(Error); - ContainerNode (*writeNewArray)(ContainerNode*, - const string &name) - PJSUA2_THROW(Error); + bool (*hasUnread)(const ContainerNode*); + string (*unreadName)(const ContainerNode*) + PJSUA2_THROW(Error); + float (*readNumber)(const ContainerNode*, + const string&) + PJSUA2_THROW(Error); + bool (*readBool)(const ContainerNode*, + const string&) + PJSUA2_THROW(Error); + string (*readString)(const ContainerNode*, + const string&) + PJSUA2_THROW(Error); + StringVector (*readStringVector)(const ContainerNode*, + const string&) + PJSUA2_THROW(Error); + ContainerNode (*readContainer)(const ContainerNode*, + const string &) + PJSUA2_THROW(Error); + ContainerNode (*readArray)(const ContainerNode*, + const string &) + PJSUA2_THROW(Error); + void (*writeNumber)(ContainerNode*, + const string &name, + float num) + PJSUA2_THROW(Error); + void (*writeBool)(ContainerNode*, + const string &name, + bool value) + PJSUA2_THROW(Error); + void (*writeString)(ContainerNode*, + const string &name, + const string &value) + PJSUA2_THROW(Error); + void (*writeStringVector)(ContainerNode*, + const string &name, + const StringVector &value) + PJSUA2_THROW(Error); + ContainerNode (*writeNewContainer)(ContainerNode*, + const string &name) + PJSUA2_THROW(Error); + ContainerNode (*writeNewArray)(ContainerNode*, + const string &name) + PJSUA2_THROW(Error); }; /* * Convenient macros. */ -#define NODE_READ_BOOL(node,item) item = node.readBool(#item) -#define NODE_READ_UNSIGNED(node,item) item = (unsigned)node.readNumber(#item) -#define NODE_READ_INT(node,item) item = (int) node.readNumber(#item) -#define NODE_READ_FLOAT(node,item) item = node.readNumber(#item) -#define NODE_READ_NUM_T(node,T,item) item = (T)(int)node.readNumber(#item) -#define NODE_READ_STRING(node,item) item = node.readString(#item) -#define NODE_READ_STRINGV(node,item) item = node.readStringVector(#item) -#define NODE_READ_OBJ(node,item) node.readObject(item) - -#define NODE_WRITE_BOOL(node,item) node.writeBool(#item, item) -#define NODE_WRITE_UNSIGNED(node,item) node.writeNumber(#item, (float)item) -#define NODE_WRITE_INT(node,item) node.writeNumber(#item, (float)item) -#define NODE_WRITE_NUM_T(node,T,item) node.writeNumber(#item, (float)item) -#define NODE_WRITE_FLOAT(node,item) node.writeNumber(#item, item) -#define NODE_WRITE_STRING(node,item) node.writeString(#item, item) -#define NODE_WRITE_STRINGV(node,item) node.writeStringVector(#item, item) -#define NODE_WRITE_OBJ(node,item) node.writeObject(item) +#define NODE_READ_BOOL(node,item) item = node.readBool(#item) +#define NODE_READ_UNSIGNED(node,item) item = (unsigned)node.readNumber(#item) +#define NODE_READ_INT(node,item) item = (int) node.readNumber(#item) +#define NODE_READ_FLOAT(node,item) item = node.readNumber(#item) +#define NODE_READ_NUM_T(node,T,item) item = (T)(int)node.readNumber(#item) +#define NODE_READ_STRING(node,item) item = node.readString(#item) +#define NODE_READ_STRINGV(node,item) item = node.readStringVector(#item) +#define NODE_READ_OBJ(node,item) node.readObject(item) + +#define NODE_WRITE_BOOL(node,item) node.writeBool(#item, item) +#define NODE_WRITE_UNSIGNED(node,item) node.writeNumber(#item, (float)item) +#define NODE_WRITE_INT(node,item) node.writeNumber(#item, (float)item) +#define NODE_WRITE_NUM_T(node,T,item) node.writeNumber(#item, (float)item) +#define NODE_WRITE_FLOAT(node,item) node.writeNumber(#item, item) +#define NODE_WRITE_STRING(node,item) node.writeString(#item, item) +#define NODE_WRITE_STRINGV(node,item) node.writeStringVector(#item, item) +#define NODE_WRITE_OBJ(node,item) node.writeObject(item) //! @endcond @@ -707,4 +706,4 @@ struct container_node_op -#endif /* __PJSUA2_PERSISTENT_HPP__ */ +#endif /* __PJSUA2_PERSISTENT_HPP__ */ diff --git a/pjsip/include/pjsua2/presence.hpp b/pjsip/include/pjsua2/presence.hpp index 66110715d3..9450250f98 100644 --- a/pjsip/include/pjsua2/presence.hpp +++ b/pjsip/include/pjsua2/presence.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -48,27 +47,27 @@ struct PresenceStatus /** * Buddy's online status. */ - pjsua_buddy_status status; + pjsua_buddy_status status; /** * Text to describe buddy's online status. */ - string statusText; + string statusText; /** * Activity type. */ - pjrpid_activity activity; + pjrpid_activity activity; /** * Optional text describing the person/element. */ - string note; + string note; /** * Optional RPID ID string. */ - string rpidId; + string rpidId; public: /** @@ -87,25 +86,25 @@ struct BuddyConfig : public PersistentObject /** * Buddy URL or name address. */ - string uri; + string uri; /** * Specify whether presence subscription should start immediately. */ - bool subscribe; + bool subscribe; public: /** * Read this object from a container node. * - * @param node Container to read values from. + * @param node Container to read values from. */ virtual void readObject(const ContainerNode &node) PJSUA2_THROW(Error); /** * Write this object to a container node. * - * @param node Container to write values to. + * @param node Container to write values to. */ virtual void writeObject(ContainerNode &node) const PJSUA2_THROW(Error); }; @@ -120,19 +119,19 @@ struct BuddyInfo /** * The full URI of the buddy, as specified in the configuration. */ - string uri; + string uri; /** * Buddy's Contact, only available when presence subscription has * been established to the buddy. */ - string contact; + string contact; /** * Flag to indicate that we should monitor the presence information for * this buddy (normally yes, unless explicitly disabled). */ - bool presMonitorEnabled; + bool presMonitorEnabled; /** * If \a presMonitorEnabled is true, this specifies the last state of @@ -142,12 +141,12 @@ struct BuddyInfo * PJSIP_EVSUB_STATE_TERMINATED, and the termination reason will be * specified in \a subTermReason. */ - pjsip_evsub_state subState; + pjsip_evsub_state subState; /** * String representation of subscription state. */ - string subStateName; + string subStateName; /** * Specifies the last presence subscription termination code. This would @@ -156,27 +155,27 @@ struct BuddyInfo * 200, and subscription termination reason will be given in the * \a subTermReason field. */ - pjsip_status_code subTermCode; + pjsip_status_code subTermCode; /** * Specifies the last presence subscription termination reason. If * presence subscription is currently active, the value will be empty. */ - string subTermReason; + string subTermReason; /** * Presence status. */ - PresenceStatus presStatus; + PresenceStatus presStatus; public: /** * Default constructor */ BuddyInfo() : subState(PJSIP_EVSUB_STATE_UNKNOWN), - subTermCode(PJSIP_SC_NULL) + subTermCode(PJSIP_SC_NULL) {} - + /** Import from pjsip structure */ void fromPj(const pjsua_buddy_info &pbi); @@ -237,29 +236,29 @@ class Buddy * the instance that calls this create() method as it is only the original * instance destructor that will delete the underlying Buddy in PJSUA-LIB. * - * @param acc The account for this buddy. - * @param cfg The buddy config. + * @param acc The account for this buddy. + * @param cfg The buddy config. */ void create(Account &acc, const BuddyConfig &cfg) PJSUA2_THROW(Error); /** * Check if this buddy is valid. * - * @return True if it is. + * @return True if it is. */ bool isValid() const; /** * Get PJSUA-LIB buddy ID or index associated with this buddy. * - * @return Integer greater than or equal to zero. + * @return Integer greater than or equal to zero. */ int getId() const; /** * Get detailed buddy info. * - * @return Buddy info. + * @return Buddy info. */ BuddyInfo getInfo() const PJSUA2_THROW(Error); @@ -268,8 +267,8 @@ class Buddy * subscribed, application will be informed about buddy's presence status * changed via \a onBuddyState() callback. * - * @param subscribe Specify true to activate presence - * subscription. + * @param subscribe Specify true to activate presence + * subscription. */ void subscribePresence(bool subscribe) PJSUA2_THROW(Error); @@ -295,18 +294,18 @@ class Buddy * Send instant messaging outside dialog, using this buddy's specified * account for route set and authentication. * - * @param prm Sending instant message parameter. + * @param prm Sending instant message parameter. */ void sendInstantMessage(const SendInstantMessageParam &prm) - PJSUA2_THROW(Error); + PJSUA2_THROW(Error); /** * Send typing indication outside dialog. * - * @param prm Sending instant message parameter. + * @param prm Sending instant message parameter. */ void sendTypingIndication(const SendTypingIndicationParam &prm) - PJSUA2_THROW(Error); + PJSUA2_THROW(Error); public: /* @@ -326,7 +325,7 @@ class Buddy * callback to retrieve more detailed information about the state * changed event. * - * @param prm Callback parameter. + * @param prm Callback parameter. */ virtual void onBuddyEvSubState(OnBuddyEvSubStateParam &prm) { PJ_UNUSED_ARG(prm); } @@ -335,7 +334,7 @@ class Buddy /** * Buddy ID. */ - pjsua_buddy_id id; + pjsua_buddy_id id; private: friend class Endpoint; @@ -364,4 +363,4 @@ typedef std::vector BuddyVector2; } // namespace pj -#endif /* __PJSUA2_PRESENCE_HPP__ */ +#endif /* __PJSUA2_PRESENCE_HPP__ */ diff --git a/pjsip/include/pjsua2/siptypes.hpp b/pjsip/include/pjsua2/siptypes.hpp index 3010c2aaf5..7b5b150a04 100644 --- a/pjsip/include/pjsua2/siptypes.hpp +++ b/pjsip/include/pjsua2/siptypes.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2032 Teluu Inc. (http://www.teluu.com) * @@ -48,29 +47,29 @@ struct AuthCredInfo : public PersistentObject /** * The authentication scheme (e.g. "digest"). */ - string scheme; + string scheme; /** * Realm on which this credential is to be used. Use "*" to make * a credential that can be used to authenticate against any challenges. */ - string realm; + string realm; /** * Authentication user name. */ - string username; + string username; /** * Type of data that is contained in the "data" field. Use 0 if the data * contains plain text password. */ - int dataType; + int dataType; /** * The data, which can be a plain text password or a hashed digest. */ - string data; + string data; /* * Digest AKA credential information. Note that when AKA credential @@ -80,13 +79,13 @@ struct AuthCredInfo : public PersistentObject */ /** Permanent subscriber key. */ - string akaK; + string akaK; /** Operator variant key. */ - string akaOp; + string akaOp; - /** Authentication Management Field */ - string akaAmf; + /** Authentication Management Field */ + string akaAmf; public: /** Default constructor */ @@ -112,14 +111,14 @@ struct AuthCredInfo : public PersistentObject /** * Read this object from a container node. * - * @param node Container to read values from. + * @param node Container to read values from. */ virtual void readObject(const ContainerNode &node) PJSUA2_THROW(Error); /** * Write this object to a container node. * - * @param node Container to write values to. + * @param node Container to write values to. */ virtual void writeObject(ContainerNode &node) const PJSUA2_THROW(Error); }; @@ -135,30 +134,30 @@ struct TlsConfig : public PersistentObject /** * Certificate of Authority (CA) list file. */ - string CaListFile; + string CaListFile; /** * Public endpoint certificate file, which will be used as client- * side certificate for outgoing TLS connection, and server-side * certificate for incoming TLS connection. */ - string certFile; + string certFile; /** * Optional private key of the endpoint certificate to be used. */ - string privKeyFile; + string privKeyFile; /** * Password to open private key. */ - string password; + string password; /** * Certificate of Authority (CA) buffer. If CaListFile, certFile or * privKeyFile are set, this setting will be ignored. */ - string CaBuf; + string CaBuf; /** * Public endpoint certificate buffer, which will be used as client- @@ -166,14 +165,14 @@ struct TlsConfig : public PersistentObject * certificate for incoming TLS connection. If CaListFile, certFile or * privKeyFile are set, this setting will be ignored. */ - string certBuf; + string certBuf; /** * Optional private key buffer of the endpoint certificate to be used. * If CaListFile, certFile or privKeyFile are set, this setting will * be ignored. */ - string privKeyBuf; + string privKeyBuf; /** * TLS protocol method from #pjsip_ssl_method. In the future, this field @@ -183,7 +182,7 @@ struct TlsConfig : public PersistentObject * Default is PJSIP_SSL_UNSPECIFIED_METHOD (0), which in turn will * use PJSIP_SSL_DEFAULT_METHOD, which default value is PJSIP_TLSV1_METHOD. */ - pjsip_ssl_method method; + pjsip_ssl_method method; /** * TLS protocol type from #pj_ssl_sock_proto. Use this field to enable @@ -192,7 +191,7 @@ struct TlsConfig : public PersistentObject * * Default is PJSIP_SSL_DEFAULT_PROTO. */ - unsigned proto; + unsigned proto; /** * Ciphers and order preference. The Endpoint::utilSslGetAvailableCiphers() @@ -200,7 +199,7 @@ struct TlsConfig : public PersistentObject * If the array is empty, then default cipher list of the backend * will be used. */ - IntVector ciphers; + IntVector ciphers; /** * Specifies TLS transport behavior on the server TLS certificate @@ -218,7 +217,7 @@ struct TlsConfig : public PersistentObject * * Default value is false. */ - bool verifyServer; + bool verifyServer; /** * Specifies TLS transport behavior on the client TLS certificate @@ -236,7 +235,7 @@ struct TlsConfig : public PersistentObject * * Default value is PJ_FALSE. */ - bool verifyClient; + bool verifyClient; /** * When acting as server (incoming TLS connections), reject incoming @@ -245,7 +244,7 @@ struct TlsConfig : public PersistentObject * This setting corresponds to SSL_VERIFY_FAIL_IF_NO_PEER_CERT flag. * Default value is PJ_FALSE. */ - bool requireClientCert; + bool requireClientCert; /** * TLS negotiation timeout to be applied for both outgoing and incoming @@ -254,7 +253,7 @@ struct TlsConfig : public PersistentObject * * Default: zero */ - unsigned msecTimeout; + unsigned msecTimeout; /** * QoS traffic type to be set on this transport. When application wants @@ -263,7 +262,7 @@ struct TlsConfig : public PersistentObject * * Default value is PJ_QOS_TYPE_BEST_EFFORT. */ - pj_qos_type qosType; + pj_qos_type qosType; /** * Set the low level QoS parameters to the transport. This is a lower @@ -272,7 +271,7 @@ struct TlsConfig : public PersistentObject * * By default all settings in this structure are disabled. */ - pj_qos_params qosParams; + pj_qos_params qosParams; /** * Specify if the transport should ignore any errors when setting the QoS @@ -280,7 +279,7 @@ struct TlsConfig : public PersistentObject * * Default: PJ_TRUE */ - bool qosIgnoreError; + bool qosIgnoreError; public: /** Default constructor initialises with default values */ @@ -295,14 +294,14 @@ struct TlsConfig : public PersistentObject /** * Read this object from a container node. * - * @param node Container to read values from. + * @param node Container to read values from. */ virtual void readObject(const ContainerNode &node) PJSUA2_THROW(Error); /** * Write this object to a container node. * - * @param node Container to write values to. + * @param node Container to write values to. */ virtual void writeObject(ContainerNode &node) const PJSUA2_THROW(Error); }; @@ -319,7 +318,7 @@ struct TransportConfig : public PersistentObject * transport will be bound to any available port, and application * can query the port by querying the transport info. */ - unsigned port; + unsigned port; /** * Specify the port range for socket binding, relative to the start @@ -333,7 +332,7 @@ struct TransportConfig : public PersistentObject * * Default value is zero. */ - unsigned portRange; + unsigned portRange; /** * Specify whether to randomly pick the starting port number from @@ -343,7 +342,7 @@ struct TransportConfig : public PersistentObject * * Default is PJ_FALSE. */ - bool randomizePort; + bool randomizePort; /** * Optional address to advertise as the address of this transport. @@ -354,7 +353,7 @@ struct TransportConfig : public PersistentObject * * Note: this option can be used for both UDP and TCP as well! */ - string publicAddress; + string publicAddress; /** * Optional address where the socket should be bound to. This option @@ -367,14 +366,14 @@ struct TransportConfig : public PersistentObject * MUST correspond to the actual interface address in the host, since * this address will be specified as bind() argument. */ - string boundAddress; + string boundAddress; /** * This specifies TLS settings for TLS transport. It is only be used * when this transport config is being used to create a SIP TLS * transport. */ - TlsConfig tlsConfig; + TlsConfig tlsConfig; /** * QoS traffic type to be set on this transport. When application wants @@ -383,7 +382,7 @@ struct TransportConfig : public PersistentObject * * Default is QoS not set. */ - pj_qos_type qosType; + pj_qos_type qosType; /** * Set the low level QoS parameters to the transport. This is a lower @@ -392,7 +391,7 @@ struct TransportConfig : public PersistentObject * * Default is QoS not set. */ - pj_qos_params qosParams; + pj_qos_params qosParams; public: /** Default constructor initialises with default values */ @@ -407,14 +406,14 @@ struct TransportConfig : public PersistentObject /** * Read this object from a container node. * - * @param node Container to read values from. + * @param node Container to read values from. */ virtual void readObject(const ContainerNode &node) PJSUA2_THROW(Error); /** * Write this object to a container node. * - * @param node Container to write values to. + * @param node Container to write values to. */ virtual void writeObject(ContainerNode &node) const PJSUA2_THROW(Error); }; @@ -426,28 +425,28 @@ struct TransportConfig : public PersistentObject struct TransportInfo { /** PJSUA transport identification. */ - TransportId id; + TransportId id; /** Transport type. */ pjsip_transport_type_e type; /** Transport type name. */ - string typeName; + string typeName; /** Transport string info/description. */ - string info; + string info; /** Transport flags (see pjsip_transport_flags_e). */ - unsigned flags; + unsigned flags; /** Local/bound address. */ - SocketAddress localAddress; + SocketAddress localAddress; /** Published address (or transport address name). */ - SocketAddress localName; + SocketAddress localName; /** Current number of objects currently referencing this transport. */ - unsigned usageCount; + unsigned usageCount; public: /** @@ -471,13 +470,13 @@ struct SipRxData * A short info string describing the request, which normally contains * the request method and its CSeq. */ - string info; + string info; /** * The whole message data as a string, containing both the header section * and message body section. */ - string wholeMsg; + string wholeMsg; /** * Source address of the message. @@ -512,18 +511,18 @@ struct SipTxData * A short info string describing the request, which normally contains * the request method and its CSeq. */ - string info; + string info; /** * The whole message data as a string, containing both the header section * and message body section. */ - string wholeMsg; + string wholeMsg; /** * Destination address of the message. */ - SocketAddress dstAddress; + SocketAddress dstAddress; /** * Pointer to original pjsip_tx_data. Only valid when the struct @@ -554,9 +553,9 @@ struct SipTransaction string method; /**< The method. */ /* State and status. */ - int statusCode; /**< Last status code seen. */ - string statusText; /**< Last reason phrase. */ - pjsip_tsx_state_e state; /**< State. */ + int statusCode; /**< Last status code seen. */ + string statusText; /**< Last reason phrase. */ + pjsip_tsx_state_e state; /**< State. */ /* Messages and timer. */ SipTxData lastTx; /**< Msg kept for retrans. */ @@ -733,10 +732,10 @@ struct SipEvent struct SipMediaType { /** Media type. */ - string type; + string type; /** Media subtype. */ - string subType; + string subType; public: /** @@ -758,12 +757,12 @@ struct SipHeader /** * Header name. */ - string hName; + string hName; /** * Header value. */ - string hValue; + string hValue; public: /** @@ -778,7 +777,7 @@ struct SipHeader private: /** Interal buffer for conversion to PJSIP header */ - mutable pjsip_generic_string_hdr pjHdr; + mutable pjsip_generic_string_hdr pjHdr; }; @@ -793,17 +792,17 @@ struct SipMultipartPart /** * Optional headers to be put in this multipart part. */ - SipHeaderVector headers; + SipHeaderVector headers; /** * The MIME type of the body part of this multipart part. */ - SipMediaType contentType; + SipMediaType contentType; /** * The body part of tthis multipart part. */ - string body; + string body; public: /** @@ -818,8 +817,8 @@ struct SipMultipartPart private: /** Interal buffer for conversion to PJSIP pjsip_multipart_part */ - mutable pjsip_multipart_part pjMpp; - mutable pjsip_msg_body pjMsgBody; + mutable pjsip_multipart_part pjMpp; + mutable pjsip_msg_body pjMsgBody; }; /** Array of multipart parts */ @@ -982,4 +981,4 @@ void writeSipHeaders(ContainerNode &node, -#endif /* __PJSUA2_SIPTYPES_HPP__ */ +#endif /* __PJSUA2_SIPTYPES_HPP__ */ diff --git a/pjsip/include/pjsua2/types.hpp b/pjsip/include/pjsua2/types.hpp index 6676e7f4a6..79d4faea8e 100644 --- a/pjsip/include/pjsua2/types.hpp +++ b/pjsip/include/pjsua2/types.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -103,7 +102,7 @@ class Call; enum { /** Invalid ID, equal to PJSUA_INVALID_ID */ - INVALID_ID = -1, + INVALID_ID = -1, /** Success, equal to PJ_SUCCESS */ SUCCESS = 0 @@ -118,22 +117,22 @@ enum struct Error { /** The error code. */ - pj_status_t status; + pj_status_t status; /** The PJSUA API operation that throws the error. */ - string title; + string title; /** The error message */ - string reason; + string reason; /** The PJSUA source file that throws the error */ - string srcFile; + string srcFile; /** The line number of PJSUA source file that throws the error */ - int srcLine; + int srcLine; /** Build error string. */ - string info(bool multi_line=false) const; + string info(bool multi_line=false) const; /** Default constructor */ Error(); @@ -155,56 +154,56 @@ struct Error * Error utilities. */ #if PJSUA2_ERROR_HAS_EXTRA_INFO -# define PJSUA2_RAISE_ERROR(status) \ - PJSUA2_RAISE_ERROR2(status, __FUNCTION__) +# define PJSUA2_RAISE_ERROR(status) \ + PJSUA2_RAISE_ERROR2(status, __FUNCTION__) -# define PJSUA2_RAISE_ERROR2(status,op) \ - PJSUA2_RAISE_ERROR3(status, op, string()) +# define PJSUA2_RAISE_ERROR2(status,op) \ + PJSUA2_RAISE_ERROR3(status, op, string()) -# define PJSUA2_RAISE_ERROR3(status,op,txt) \ - do { \ - Error err_ = Error(status, op, txt, __FILE__, __LINE__); \ - PJ_LOG(1,(THIS_FILE, "%s", err_.info().c_str())); \ - throw err_; \ - } while (0) +# define PJSUA2_RAISE_ERROR3(status,op,txt) \ + do { \ + Error err_ = Error(status, op, txt, __FILE__, __LINE__); \ + PJ_LOG(1,(THIS_FILE, "%s", err_.info().c_str())); \ + throw err_; \ + } while (0) #else /** Raise Error exception */ -# define PJSUA2_RAISE_ERROR(status) \ - PJSUA2_RAISE_ERROR2(status, string()) +# define PJSUA2_RAISE_ERROR(status) \ + PJSUA2_RAISE_ERROR2(status, string()) /** Raise Error exception */ -# define PJSUA2_RAISE_ERROR2(status,op) \ - PJSUA2_RAISE_ERROR3(status, op, string()) +# define PJSUA2_RAISE_ERROR2(status,op) \ + PJSUA2_RAISE_ERROR3(status, op, string()) /** Raise Error exception */ -# define PJSUA2_RAISE_ERROR3(status,op,txt) \ - do { \ - Error err_ = Error(status, op, txt, string(), 0); \ - PJ_LOG(1,(THIS_FILE, "%s", err_.info().c_str())); \ - throw err_; \ - } while (0) +# define PJSUA2_RAISE_ERROR3(status,op,txt) \ + do { \ + Error err_ = Error(status, op, txt, string(), 0); \ + PJ_LOG(1,(THIS_FILE, "%s", err_.info().c_str())); \ + throw err_; \ + } while (0) #endif /** Raise Error exception if the expression fails */ -#define PJSUA2_CHECK_RAISE_ERROR2(status, op) \ - do { \ - if (status != PJ_SUCCESS) { \ - PJSUA2_RAISE_ERROR2(status, op); \ - } \ - } while (0) +#define PJSUA2_CHECK_RAISE_ERROR2(status, op) \ + do { \ + if (status != PJ_SUCCESS) { \ + PJSUA2_RAISE_ERROR2(status, op); \ + } \ + } while (0) /** Raise Error exception if the status fails */ -#define PJSUA2_CHECK_RAISE_ERROR(status) \ - PJSUA2_CHECK_RAISE_ERROR2(status, "") +#define PJSUA2_CHECK_RAISE_ERROR(status) \ + PJSUA2_CHECK_RAISE_ERROR2(status, "") /** Raise Error exception if the expression fails */ -#define PJSUA2_CHECK_EXPR(expr) \ - do { \ - pj_status_t the_status = expr; \ - PJSUA2_CHECK_RAISE_ERROR2(the_status, #expr); \ - } while (0) +#define PJSUA2_CHECK_EXPR(expr) \ + do { \ + pj_status_t the_status = expr; \ + PJSUA2_CHECK_RAISE_ERROR2(the_status, #expr); \ + } while (0) ////////////////////////////////////////////////////////////////////////////// /** @@ -213,26 +212,26 @@ struct Error struct Version { /** Major number */ - int major; + int major; /** Minor number */ - int minor; + int minor; /** Additional revision number */ - int rev; + int rev; /** Version suffix (e.g. "-svn") */ - string suffix; + string suffix; /** The full version info (e.g. "2.1.0-svn") */ - string full; + string full; /** * PJLIB version number as three bytes with the following format: * 0xMMIIRR00, where MM: major number, II: minor number, RR: revision * number, 00: always zero for now. */ - unsigned numeric; + unsigned numeric; }; ////////////////////////////////////////////////////////////////////////////// @@ -267,4 +266,4 @@ struct TimeVal -#endif /* __PJSUA2_TYPES_HPP__ */ +#endif /* __PJSUA2_TYPES_HPP__ */ diff --git a/pjsip/src/pjsip-simple/errno.c b/pjsip/src/pjsip-simple/errno.c index 3c8c7f8b03..ee3258273a 100644 --- a/pjsip/src/pjsip-simple/errno.c +++ b/pjsip/src/pjsip-simple/errno.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,84 +33,84 @@ static const struct } err_str[] = { /* Event errors */ - { PJSIP_SIMPLE_ENOPKG, "No SIP event package with the specified name" }, - { PJSIP_SIMPLE_EPKGEXISTS, "SIP event package already exist" }, + { PJSIP_SIMPLE_ENOPKG, "No SIP event package with the specified name" }, + { PJSIP_SIMPLE_EPKGEXISTS, "SIP event package already exist" }, /* Presence errors */ { PJSIP_SIMPLE_ENOTSUBSCRIBE, "Expecting SUBSCRIBE request" }, - { PJSIP_SIMPLE_ENOPRESENCE, "No presence associated with the subscription" }, + { PJSIP_SIMPLE_ENOPRESENCE, "No presence associated with the subscription" }, { PJSIP_SIMPLE_ENOPRESENCEINFO, "No presence info in the server subscription" }, - { PJSIP_SIMPLE_EBADCONTENT, "Bad Content-Type for presence" }, - { PJSIP_SIMPLE_EBADPIDF, "Bad PIDF content for presence" }, - { PJSIP_SIMPLE_EBADXPIDF, "Bad XPIDF content for presence" }, - { PJSIP_SIMPLE_EBADRPID, "Invalid or bad RPID document"}, + { PJSIP_SIMPLE_EBADCONTENT, "Bad Content-Type for presence" }, + { PJSIP_SIMPLE_EBADPIDF, "Bad PIDF content for presence" }, + { PJSIP_SIMPLE_EBADXPIDF, "Bad XPIDF content for presence" }, + { PJSIP_SIMPLE_EBADRPID, "Invalid or bad RPID document"}, /* isComposing errors. */ { PJSIP_SIMPLE_EBADISCOMPOSE, "Bad isComposing indication/XML message" }, }; -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ /* * pjsipsimple_strerror() */ PJ_DEF(pj_str_t) pjsipsimple_strerror( pj_status_t statcode, - char *buf, pj_size_t bufsize ) + char *buf, pj_size_t bufsize ) { pj_str_t errstr; #if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0) if (statcode >= PJSIP_SIMPLE_ERRNO_START && - statcode < PJSIP_SIMPLE_ERRNO_START + PJ_ERRNO_SPACE_SIZE) + statcode < PJSIP_SIMPLE_ERRNO_START + PJ_ERRNO_SPACE_SIZE) { - /* Find the error in the table. - * Use binary search! - */ - int first = 0; - int n = PJ_ARRAY_SIZE(err_str); - - while (n > 0) { - int half = n/2; - int mid = first + half; - - if (err_str[mid].code < statcode) { - first = mid+1; - n -= (half+1); - } else if (err_str[mid].code > statcode) { - n = half; - } else { - first = mid; - break; - } - } - - - if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { - pj_str_t msg; - - msg.ptr = (char*)err_str[first].msg; - msg.slen = pj_ansi_strlen(err_str[first].msg); - - errstr.ptr = buf; - pj_strncpy_with_null(&errstr, &msg, bufsize); - return errstr; - - } + /* Find the error in the table. + * Use binary search! + */ + int first = 0; + int n = PJ_ARRAY_SIZE(err_str); + + while (n > 0) { + int half = n/2; + int mid = first + half; + + if (err_str[mid].code < statcode) { + first = mid+1; + n -= (half+1); + } else if (err_str[mid].code > statcode) { + n = half; + } else { + first = mid; + break; + } + } + + + if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { + pj_str_t msg; + + msg.ptr = (char*)err_str[first].msg; + msg.slen = pj_ansi_strlen(err_str[first].msg); + + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, &msg, bufsize); + return errstr; + + } } -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ /* Error not found. */ errstr.ptr = buf; errstr.slen = pj_ansi_snprintf(buf, bufsize, - "Unknown pjsip-simple error %d", - statcode); + "Unknown pjsip-simple error %d", + statcode); if (errstr.slen < 1 || errstr.slen >= (pj_ssize_t)bufsize) - errstr.slen = bufsize - 1; + errstr.slen = bufsize - 1; return errstr; } diff --git a/pjsip/src/pjsip-simple/evsub.c b/pjsip/src/pjsip-simple/evsub.c index 8527056b29..870682db2a 100644 --- a/pjsip/src/pjsip-simple/evsub.c +++ b/pjsip/src/pjsip-simple/evsub.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,7 +35,7 @@ #include -#define THIS_FILE "evsub.c" +#define THIS_FILE "evsub.c" /* * Global constant @@ -83,7 +82,7 @@ PJ_DEF(const pjsip_method*) pjsip_get_notify_method() /* * Static prototypes. */ -static void mod_evsub_on_tsx_state(pjsip_transaction*, pjsip_event*); +static void mod_evsub_on_tsx_state(pjsip_transaction*, pjsip_event*); static pj_status_t mod_evsub_unload(void); @@ -92,11 +91,11 @@ static pj_status_t mod_evsub_unload(void); */ static pj_str_t evsub_state_names[] = { - { "NULL", 4}, - { "SENT", 4}, + { "NULL", 4}, + { "SENT", 4}, { "ACCEPTED", 8}, { "PENDING", 7}, - { "ACTIVE", 6}, + { "ACTIVE", 6}, { "TERMINATED", 10}, { "UNKNOWN", 7} }; @@ -106,16 +105,16 @@ static pj_str_t evsub_state_names[] = */ /* Number of seconds to send SUBSCRIBE before the actual expiration */ -#define TIME_UAC_REFRESH PJSIP_EVSUB_TIME_UAC_REFRESH +#define TIME_UAC_REFRESH PJSIP_EVSUB_TIME_UAC_REFRESH /* Time to wait for the final NOTIFY after sending unsubscription */ -#define TIME_UAC_TERMINATE PJSIP_EVSUB_TIME_UAC_TERMINATE +#define TIME_UAC_TERMINATE PJSIP_EVSUB_TIME_UAC_TERMINATE /* If client responds NOTIFY with non-2xx final response (such as 401), * wait for this seconds for further NOTIFY, otherwise client will * unsubscribe */ -#define TIME_UAC_WAIT_NOTIFY PJSIP_EVSUB_TIME_UAC_WAIT_NOTIFY +#define TIME_UAC_WAIT_NOTIFY PJSIP_EVSUB_TIME_UAC_WAIT_NOTIFY /* @@ -167,10 +166,10 @@ struct evpkg { PJ_DECL_LIST_MEMBER(struct evpkg); - pj_str_t pkg_name; - pjsip_module *pkg_mod; - unsigned pkg_expires; - pjsip_accept_hdr *pkg_accept; + pj_str_t pkg_name; + pjsip_module *pkg_mod; + unsigned pkg_expires; + pjsip_accept_hdr *pkg_accept; }; @@ -179,28 +178,28 @@ struct evpkg */ static struct mod_evsub { - pjsip_module mod; - pj_pool_t *pool; - pjsip_endpoint *endpt; - struct evpkg pkg_list; + pjsip_module mod; + pj_pool_t *pool; + pjsip_endpoint *endpt; + struct evpkg pkg_list; pjsip_allow_events_hdr *allow_events_hdr; } mod_evsub = { { - NULL, NULL, /* prev, next. */ - { "mod-evsub", 9 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_DIALOG_USAGE, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - &mod_evsub_unload, /* unload() */ - NULL, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - &mod_evsub_on_tsx_state, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-evsub", 9 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_DIALOG_USAGE, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + &mod_evsub_unload, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + &mod_evsub_on_tsx_state, /* on_tsx_state() */ } }; @@ -210,36 +209,36 @@ static struct mod_evsub */ struct pjsip_evsub { - char obj_name[PJ_MAX_OBJ_NAME]; /**< Name. */ - pj_pool_t *pool; /**< Pool. */ - pjsip_endpoint *endpt; /**< Endpoint instance. */ - pjsip_dialog *dlg; /**< Underlying dialog. */ - struct evpkg *pkg; /**< The event package. */ - unsigned option; /**< Options. */ - pjsip_evsub_user user; /**< Callback. */ - pj_bool_t call_cb; /**< Notify callback? */ - pjsip_role_e role; /**< UAC=subscriber, UAS=notifier */ - pjsip_evsub_state state; /**< Subscription state. */ - pj_str_t state_str; /**< String describing the state. */ - pjsip_evsub_state dst_state; /**< Pending state to be set. */ - pj_str_t dst_state_str;/**< Pending state to be set. */ - pj_str_t term_reason; /**< Termination reason. */ - pjsip_method method; /**< Method that established subscr.*/ - pjsip_event_hdr *event; /**< Event description. */ - pjsip_expires_hdr *expires; /**< Expires header */ - pjsip_accept_hdr *accept; /**< Local Accept header. */ + char obj_name[PJ_MAX_OBJ_NAME]; /**< Name. */ + pj_pool_t *pool; /**< Pool. */ + pjsip_endpoint *endpt; /**< Endpoint instance. */ + pjsip_dialog *dlg; /**< Underlying dialog. */ + struct evpkg *pkg; /**< The event package. */ + unsigned option; /**< Options. */ + pjsip_evsub_user user; /**< Callback. */ + pj_bool_t call_cb; /**< Notify callback? */ + pjsip_role_e role; /**< UAC=subscriber, UAS=notifier */ + pjsip_evsub_state state; /**< Subscription state. */ + pj_str_t state_str; /**< String describing the state. */ + pjsip_evsub_state dst_state; /**< Pending state to be set. */ + pj_str_t dst_state_str;/**< Pending state to be set. */ + pj_str_t term_reason; /**< Termination reason. */ + pjsip_method method; /**< Method that established subscr.*/ + pjsip_event_hdr *event; /**< Event description. */ + pjsip_expires_hdr *expires; /**< Expires header */ + pjsip_accept_hdr *accept; /**< Local Accept header. */ pjsip_hdr sub_hdr_list; /**< User-defined header. */ - pj_time_val refresh_time; /**< Time to refresh. */ - pj_timer_entry timer; /**< Internal timer. */ - int pending_tsx; /**< Number of pending transactions.*/ - pjsip_transaction *pending_sub; /**< Pending UAC SUBSCRIBE tsx. */ - pj_timer_entry *pending_sub_timer; /**< Stop pending sub timer. */ - pjsip_tx_data *pending_notify;/**< Pending NOTIFY to be sent. */ - pj_bool_t calling_on_rx_refresh;/**< Inside on_rx_refresh()?*/ - pj_grp_lock_t *grp_lock; /* Session group lock */ + pj_time_val refresh_time; /**< Time to refresh. */ + pj_timer_entry timer; /**< Internal timer. */ + int pending_tsx; /**< Number of pending transactions.*/ + pjsip_transaction *pending_sub; /**< Pending UAC SUBSCRIBE tsx. */ + pj_timer_entry *pending_sub_timer; /**< Stop pending sub timer. */ + pjsip_tx_data *pending_notify;/**< Pending NOTIFY to be sent. */ + pj_bool_t calling_on_rx_refresh;/**< Inside on_rx_refresh()?*/ + pj_grp_lock_t *grp_lock; /* Session group lock */ - void *mod_data[PJSIP_MAX_MODULE]; /**< Module data. */ + void *mod_data[PJSIP_MAX_MODULE]; /**< Module data. */ }; @@ -255,7 +254,7 @@ struct dlgsub /* Static vars. */ -static const pj_str_t STR_EVENT = { "Event", 5 }; +static const pj_str_t STR_EVENT = { "Event", 5 }; static const pj_str_t STR_EVENT_S = { "o", 1 }; static const pj_str_t STR_SUB_STATE = { "Subscription-State", 18 }; static const pj_str_t STR_TERMINATED = { "terminated", 10 }; @@ -280,7 +279,7 @@ static pj_status_t mod_evsub_unload(void) * Defined in errno.c */ PJ_DECL(pj_str_t) pjsipsimple_strerror( pj_status_t statcode, - char *buf, pj_size_t bufsize ); + char *buf, pj_size_t bufsize ); /* * Init and register module. @@ -289,13 +288,13 @@ PJ_DEF(pj_status_t) pjsip_evsub_init_module(pjsip_endpoint *endpt) { pj_status_t status; pj_str_t method_tags[] = { - { "SUBSCRIBE", 9}, - { "NOTIFY", 6} + { "SUBSCRIBE", 9}, + { "NOTIFY", 6} }; status = pj_register_strerror(PJSIP_SIMPLE_ERRNO_START, - PJ_ERRNO_SPACE_SIZE, - &pjsipsimple_strerror); + PJ_ERRNO_SPACE_SIZE, + &pjsipsimple_strerror); pj_assert(status == PJ_SUCCESS); PJ_ASSERT_RETURN(endpt != NULL, PJ_EINVAL); @@ -312,12 +311,12 @@ PJ_DEF(pj_status_t) pjsip_evsub_init_module(pjsip_endpoint *endpt) PJSIP_POOL_EVSUB_LEN, PJSIP_POOL_EVSUB_INC); if (!mod_evsub.pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Register module: */ status = pjsip_endpt_register_module(endpt, &mod_evsub.mod); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create Allow-Events header: */ mod_evsub.allow_events_hdr = pjsip_allow_events_hdr_create(mod_evsub.pool); @@ -327,15 +326,15 @@ PJ_DEF(pj_status_t) pjsip_evsub_init_module(pjsip_endpoint *endpt) /* Register new methods SUBSCRIBE and NOTIFY in Allow-ed header */ pjsip_endpt_add_capability(endpt, &mod_evsub.mod, PJSIP_H_ALLOW, NULL, - 2, method_tags); + 2, method_tags); /* Done. */ return PJ_SUCCESS; on_error: if (mod_evsub.pool) { - pjsip_endpt_release_pool(endpt, mod_evsub.pool); - mod_evsub.pool = NULL; + pjsip_endpt_release_pool(endpt, mod_evsub.pool); + mod_evsub.pool = NULL; } mod_evsub.endpt = NULL; return status; @@ -366,7 +365,7 @@ PJ_DEF(pjsip_evsub*) pjsip_tsx_get_evsub(const pjsip_transaction *tsx) * Set event subscription's module data. */ PJ_DEF(void) pjsip_evsub_set_mod_data( pjsip_evsub *sub, unsigned mod_id, - void *data ) + void *data ) { PJ_ASSERT_ON_FAIL(mod_id < PJSIP_MAX_MODULE, return); sub->mod_data[mod_id] = data; @@ -377,7 +376,7 @@ PJ_DEF(void) pjsip_evsub_set_mod_data( pjsip_evsub *sub, unsigned mod_id, * Get event subscription's module data. */ PJ_DEF(void*) pjsip_evsub_get_mod_data( const pjsip_evsub *sub, - unsigned mod_id ) + unsigned mod_id ) { PJ_ASSERT_RETURN(mod_id < PJSIP_MAX_MODULE, NULL); return sub->mod_data[mod_id]; @@ -394,11 +393,11 @@ static struct evpkg* find_pkg(const pj_str_t *event_name) pkg = mod_evsub.pkg_list.next; while (pkg != &mod_evsub.pkg_list) { - if (pj_stricmp(&pkg->pkg_name, event_name) == 0) { - return pkg; - } + if (pj_stricmp(&pkg->pkg_name, event_name) == 0) { + return pkg; + } - pkg = pkg->next; + pkg = pkg->next; } return NULL; @@ -408,10 +407,10 @@ static struct evpkg* find_pkg(const pj_str_t *event_name) * Register an event package */ PJ_DEF(pj_status_t) pjsip_evsub_register_pkg( pjsip_module *pkg_mod, - const pj_str_t *event_name, - unsigned expires, - unsigned accept_cnt, - const pj_str_t accept[]) + const pj_str_t *event_name, + unsigned expires, + unsigned accept_cnt, + const pj_str_t accept[]) { struct evpkg *pkg; unsigned i; @@ -420,7 +419,7 @@ PJ_DEF(pj_status_t) pjsip_evsub_register_pkg( pjsip_module *pkg_mod, /* Make sure accept_cnt < PJ_ARRAY_SIZE(pkg->pkg_accept->values) */ PJ_ASSERT_RETURN(accept_cnt <= PJSIP_GENERIC_ARRAY_MAX_COUNT, - PJ_ETOOMANY); + PJ_ETOOMANY); /* Make sure evsub module has been initialized */ PJ_ASSERT_RETURN(mod_evsub.mod.id != -1, PJ_EINVALIDOP); @@ -440,7 +439,7 @@ PJ_DEF(pj_status_t) pjsip_evsub_register_pkg( pjsip_module *pkg_mod, pkg->pkg_accept = pjsip_accept_hdr_create(mod_evsub.pool); pkg->pkg_accept->count = accept_cnt; for (i=0; ipkg_accept->values[i], &accept[i]); + pj_strdup(mod_evsub.pool, &pkg->pkg_accept->values[i], &accept[i]); } /* Add to package list: */ @@ -450,25 +449,25 @@ PJ_DEF(pj_status_t) pjsip_evsub_register_pkg( pjsip_module *pkg_mod, /* Add to Allow-Events header: */ if (mod_evsub.allow_events_hdr->count != - PJ_ARRAY_SIZE(mod_evsub.allow_events_hdr->values)) + PJ_ARRAY_SIZE(mod_evsub.allow_events_hdr->values)) { - mod_evsub.allow_events_hdr->values[mod_evsub.allow_events_hdr->count] = - pkg->pkg_name; - ++mod_evsub.allow_events_hdr->count; + mod_evsub.allow_events_hdr->values[mod_evsub.allow_events_hdr->count] = + pkg->pkg_name; + ++mod_evsub.allow_events_hdr->count; } /* Add to endpoint's Accept header */ pjsip_endpt_add_capability(mod_evsub.endpt, &mod_evsub.mod, - PJSIP_H_ACCEPT, NULL, - pkg->pkg_accept->count, - pkg->pkg_accept->values); + PJSIP_H_ACCEPT, NULL, + pkg->pkg_accept->count, + pkg->pkg_accept->values); /* Done */ PJ_LOG(5,(THIS_FILE, "Event pkg \"%.*s\" registered by %.*s", - (int)event_name->slen, event_name->ptr, - (int)pkg_mod->name.slen, pkg_mod->name.ptr)); + (int)event_name->slen, event_name->ptr, + (int)pkg_mod->name.slen, pkg_mod->name.ptr)); return PJ_SUCCESS; } @@ -478,12 +477,12 @@ PJ_DEF(pj_status_t) pjsip_evsub_register_pkg( pjsip_module *pkg_mod, * Retrieve Allow-Events header */ PJ_DEF(const pjsip_hdr*) pjsip_evsub_get_allow_events_hdr( - const pjsip_module *m) + const pjsip_module *m) { struct mod_evsub *mod; if (m == NULL) - m = pjsip_evsub_instance(); + m = pjsip_evsub_instance(); mod = (struct mod_evsub*)m; @@ -505,32 +504,32 @@ static void update_expires( pjsip_evsub *sub, pj_uint32_t interval ) * Schedule timer. */ static void set_timer( pjsip_evsub *sub, int timer_id, - pj_uint32_t seconds) + pj_uint32_t seconds) { if (sub->timer.id != TIMER_TYPE_NONE) { - PJ_LOG(5,(sub->obj_name, "%s %s timer", - (timer_id==sub->timer.id ? "Updating" : "Cancelling"), - timer_names[sub->timer.id])); - pjsip_endpt_cancel_timer(sub->endpt, &sub->timer); - sub->timer.id = TIMER_TYPE_NONE; + PJ_LOG(5,(sub->obj_name, "%s %s timer", + (timer_id==sub->timer.id ? "Updating" : "Cancelling"), + timer_names[sub->timer.id])); + pjsip_endpt_cancel_timer(sub->endpt, &sub->timer); + sub->timer.id = TIMER_TYPE_NONE; } if (timer_id != TIMER_TYPE_NONE && seconds != PJSIP_EXPIRES_NOT_SPECIFIED) { - pj_time_val timeout; + pj_time_val timeout; - PJ_ASSERT_ON_FAIL(timer_id>TIMER_TYPE_NONE && timer_idTIMER_TYPE_NONE && timer_idendpt), - &sub->timer, &timeout, timer_id, sub->grp_lock); + pj_timer_heap_schedule_w_grp_lock( + pjsip_endpt_get_timer_heap(sub->endpt), + &sub->timer, &timeout, timer_id, sub->grp_lock); - PJ_LOG(5,(sub->obj_name, "Timer %s scheduled in %d seconds", - timer_names[sub->timer.id], timeout.sec)); + PJ_LOG(5,(sub->obj_name, "Timer %s scheduled in %d seconds", + timer_names[sub->timer.id], timeout.sec)); } } @@ -570,22 +569,22 @@ static void evsub_destroy( pjsip_evsub *sub ) /* Kill timer for stopping pending sub (see ticket #1807) */ if (sub->pending_sub_timer && sub->pending_sub_timer->id == 1) { - pjsip_endpt_cancel_timer(sub->endpt, sub->pending_sub_timer); - sub->pending_sub_timer->id = 0; - sub->pending_sub_timer = NULL; + pjsip_endpt_cancel_timer(sub->endpt, sub->pending_sub_timer); + sub->pending_sub_timer->id = 0; + sub->pending_sub_timer = NULL; } /* Remove this session from dialog's list of subscription */ dlgsub_head = (struct dlgsub *) sub->dlg->mod_data[mod_evsub.mod.id]; dlgsub = dlgsub_head->next; while (dlgsub != dlgsub_head) { - - if (dlgsub->sub == sub) { - pj_list_erase(dlgsub); - break; - } + + if (dlgsub->sub == sub) { + pj_list_erase(dlgsub); + break; + } - dlgsub = dlgsub->next; + dlgsub = dlgsub->next; } pj_grp_lock_dec_ref(sub->grp_lock); @@ -595,8 +594,8 @@ static void evsub_destroy( pjsip_evsub *sub ) * Set subscription session state. */ static void set_state( pjsip_evsub *sub, pjsip_evsub_state state, - const pj_str_t *state_str, pjsip_event *event, - const pj_str_t *reason) + const pj_str_t *state_str, pjsip_event *event, + const pj_str_t *reason) { pjsip_evsub_state prev_state = sub->state; pj_str_t old_state_str = sub->state_str; @@ -605,40 +604,40 @@ static void set_state( pjsip_evsub *sub, pjsip_evsub_state state, sub->state = state; if (state_str && state_str->slen) - pj_strdup_with_null(sub->pool, &sub->state_str, state_str); + pj_strdup_with_null(sub->pool, &sub->state_str, state_str); else - sub->state_str = evsub_state_names[state]; + sub->state_str = evsub_state_names[state]; if (reason && sub->term_reason.slen==0) - pj_strdup(sub->pool, &sub->term_reason, reason); + pj_strdup(sub->pool, &sub->term_reason, reason); PJ_LOG(4,(sub->obj_name, - "Subscription state changed %.*s --> %.*s", - (int)old_state_str.slen, - old_state_str.ptr, - (int)sub->state_str.slen, - sub->state_str.ptr)); + "Subscription state changed %.*s --> %.*s", + (int)old_state_str.slen, + old_state_str.ptr, + (int)sub->state_str.slen, + sub->state_str.ptr)); pj_log_push_indent(); /* don't call the callback with NULL event, it may crash the app! */ if (!event) { - PJSIP_EVENT_INIT_USER(dummy_event, 0, 0, 0, 0); - event = &dummy_event; + PJSIP_EVENT_INIT_USER(dummy_event, 0, 0, 0, 0); + event = &dummy_event; } if (sub->user.on_evsub_state && sub->call_cb) - (*sub->user.on_evsub_state)(sub, event); + (*sub->user.on_evsub_state)(sub, event); if (state == PJSIP_EVSUB_STATE_TERMINATED && - prev_state != PJSIP_EVSUB_STATE_TERMINATED) + prev_state != PJSIP_EVSUB_STATE_TERMINATED) { - /* Kill any timer. */ - set_timer(sub, TIMER_TYPE_NONE, 0); + /* Kill any timer. */ + set_timer(sub, TIMER_TYPE_NONE, 0); - /* We must not destroy evsub if we're still calling the callback. */ - if (sub->pending_tsx == 0 && !sub->calling_on_rx_refresh) { - evsub_destroy(sub); - } + /* We must not destroy evsub if we're still calling the callback. */ + if (sub->pending_tsx == 0 && !sub->calling_on_rx_refresh) { + evsub_destroy(sub); + } } pj_log_pop_indent(); @@ -649,7 +648,7 @@ static void set_state( pjsip_evsub *sub, pjsip_evsub_state state, * Timer callback. */ static void on_timer( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { pjsip_evsub *sub; int timer_id; @@ -664,8 +663,8 @@ static void on_timer( pj_timer_heap_t *timer_heap, * while waiting for dialog mutex, just return (see #1885 scenario 1). */ if (pj_timer_entry_running(entry) || entry->id == TIMER_TYPE_NONE) { - pjsip_dlg_dec_lock(sub->dlg); - return; + pjsip_dlg_dec_lock(sub->dlg); + return; } timer_id = entry->id; @@ -674,78 +673,78 @@ static void on_timer( pj_timer_heap_t *timer_heap, switch (timer_id) { case TIMER_TYPE_UAC_REFRESH: - /* Time for UAC to refresh subscription */ - if (sub->user.on_client_refresh && sub->call_cb) { - (*sub->user.on_client_refresh)(sub); - } else { - pjsip_tx_data *tdata; - pj_status_t status; - - PJ_LOG(5,(sub->obj_name, "Refreshing subscription.")); - pj_log_push_indent(); - status = pjsip_evsub_initiate(sub, NULL, - sub->expires->ivalue, - &tdata); - if (status == PJ_SUCCESS) - pjsip_evsub_send_request(sub, tdata); - - pj_log_pop_indent(); - } - break; + /* Time for UAC to refresh subscription */ + if (sub->user.on_client_refresh && sub->call_cb) { + (*sub->user.on_client_refresh)(sub); + } else { + pjsip_tx_data *tdata; + pj_status_t status; + + PJ_LOG(5,(sub->obj_name, "Refreshing subscription.")); + pj_log_push_indent(); + status = pjsip_evsub_initiate(sub, NULL, + sub->expires->ivalue, + &tdata); + if (status == PJ_SUCCESS) + pjsip_evsub_send_request(sub, tdata); + + pj_log_pop_indent(); + } + break; case TIMER_TYPE_UAS_TIMEOUT: - /* Refresh from UAC has not been received */ - if (sub->user.on_server_timeout && sub->call_cb) { - (*sub->user.on_server_timeout)(sub); - } else { - pjsip_tx_data *tdata; - pj_status_t status; - - PJ_LOG(5,(sub->obj_name, "Timeout waiting for refresh. " - "Sending NOTIFY to terminate.")); - pj_log_push_indent(); - status = pjsip_evsub_notify( sub, PJSIP_EVSUB_STATE_TERMINATED, - NULL, &STR_TIMEOUT, &tdata); - if (status == PJ_SUCCESS) - pjsip_evsub_send_request(sub, tdata); - - pj_log_pop_indent(); - } - break; + /* Refresh from UAC has not been received */ + if (sub->user.on_server_timeout && sub->call_cb) { + (*sub->user.on_server_timeout)(sub); + } else { + pjsip_tx_data *tdata; + pj_status_t status; + + PJ_LOG(5,(sub->obj_name, "Timeout waiting for refresh. " + "Sending NOTIFY to terminate.")); + pj_log_push_indent(); + status = pjsip_evsub_notify( sub, PJSIP_EVSUB_STATE_TERMINATED, + NULL, &STR_TIMEOUT, &tdata); + if (status == PJ_SUCCESS) + pjsip_evsub_send_request(sub, tdata); + + pj_log_pop_indent(); + } + break; case TIMER_TYPE_UAC_TERMINATE: - { - pj_str_t timeout = {"timeout", 7}; - - PJ_LOG(5,(sub->obj_name, "Timeout waiting for final NOTIFY. " - "Terminating..")); - pj_log_push_indent(); - set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, NULL, NULL, - &timeout); - pj_log_pop_indent(); - } - break; + { + pj_str_t timeout = {"timeout", 7}; + + PJ_LOG(5,(sub->obj_name, "Timeout waiting for final NOTIFY. " + "Terminating..")); + pj_log_push_indent(); + set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, NULL, NULL, + &timeout); + pj_log_pop_indent(); + } + break; case TIMER_TYPE_UAC_WAIT_NOTIFY: - { - pjsip_tx_data *tdata; - pj_status_t status; - - PJ_LOG(5,(sub->obj_name, - "Timeout waiting for subsequent NOTIFY (we did " - "send non-2xx response for previous NOTIFY). " - "Unsubscribing..")); - pj_log_push_indent(); - status = pjsip_evsub_initiate( sub, NULL, 0, &tdata); - if (status == PJ_SUCCESS) - pjsip_evsub_send_request(sub, tdata); - - pj_log_pop_indent(); - } - break; + { + pjsip_tx_data *tdata; + pj_status_t status; + + PJ_LOG(5,(sub->obj_name, + "Timeout waiting for subsequent NOTIFY (we did " + "send non-2xx response for previous NOTIFY). " + "Unsubscribing..")); + pj_log_push_indent(); + status = pjsip_evsub_initiate( sub, NULL, 0, &tdata); + if (status == PJ_SUCCESS) + pjsip_evsub_send_request(sub, tdata); + + pj_log_pop_indent(); + } + break; default: - pj_assert(!"Invalid timer id"); + pj_assert(!"Invalid timer id"); } pjsip_dlg_dec_lock(sub->dlg); @@ -756,11 +755,11 @@ static void on_timer( pj_timer_heap_t *timer_heap, * Create subscription session, used for both client and notifier. */ static pj_status_t evsub_create( pjsip_dialog *dlg, - pjsip_role_e role, - const pjsip_evsub_user *user_cb, - const pj_str_t *event, - unsigned option, - pjsip_evsub **p_evsub ) + pjsip_role_e role, + const pjsip_evsub_user *user_cb, + const pj_str_t *event, + unsigned option, + pjsip_evsub **p_evsub ) { pjsip_evsub *sub; struct evpkg *pkg; @@ -771,7 +770,7 @@ static pj_status_t evsub_create( pjsip_dialog *dlg, pkg = find_pkg(event); if (pkg == NULL) - return PJSIP_SIMPLE_ENOPKG; + return PJSIP_SIMPLE_ENOPKG; /* Must lock dialog before using pool etc. */ @@ -791,7 +790,7 @@ static pj_status_t evsub_create( pjsip_dialog *dlg, sub->state_str = evsub_state_names[sub->state]; sub->expires = pjsip_expires_hdr_create(sub->pool, pkg->pkg_expires); sub->accept = (pjsip_accept_hdr*) - pjsip_hdr_clone(sub->pool, pkg->pkg_accept); + pjsip_hdr_clone(sub->pool, pkg->pkg_accept); pj_list_init(&sub->sub_hdr_list); sub->timer.user_data = sub; @@ -799,12 +798,12 @@ static pj_status_t evsub_create( pjsip_dialog *dlg, /* Set name. */ pj_ansi_snprintf(sub->obj_name, PJ_ARRAY_SIZE(sub->obj_name), - "evsub%p", sub); + "evsub%p", sub); /* Copy callback, if any: */ if (user_cb) - pj_memcpy(&sub->user, user_cb, sizeof(pjsip_evsub_user)); + pj_memcpy(&sub->user, user_cb, sizeof(pjsip_evsub_user)); /* Create Event header: */ @@ -817,31 +816,31 @@ static pj_status_t evsub_create( pjsip_dialog *dlg, * create and register a new subscription list. */ if (pjsip_dlg_has_usage(dlg, &mod_evsub.mod)) { - dlgsub_head = (struct dlgsub*) dlg->mod_data[mod_evsub.mod.id]; - dlgsub = PJ_POOL_ALLOC_T(sub->pool, struct dlgsub); - dlgsub->sub = sub; - pj_list_push_back(dlgsub_head, dlgsub); + dlgsub_head = (struct dlgsub*) dlg->mod_data[mod_evsub.mod.id]; + dlgsub = PJ_POOL_ALLOC_T(sub->pool, struct dlgsub); + dlgsub->sub = sub; + pj_list_push_back(dlgsub_head, dlgsub); } else { - dlgsub_head = PJ_POOL_ALLOC_T(sub->pool, struct dlgsub); - dlgsub = PJ_POOL_ALLOC_T(sub->pool, struct dlgsub); - dlgsub->sub = sub; + dlgsub_head = PJ_POOL_ALLOC_T(sub->pool, struct dlgsub); + dlgsub = PJ_POOL_ALLOC_T(sub->pool, struct dlgsub); + dlgsub->sub = sub; - pj_list_init(dlgsub_head); - pj_list_push_back(dlgsub_head, dlgsub); + pj_list_init(dlgsub_head); + pj_list_push_back(dlgsub_head, dlgsub); - /* Register as dialog usage: */ + /* Register as dialog usage: */ - status = pjsip_dlg_add_usage(dlg, &mod_evsub.mod, dlgsub_head); - if (status != PJ_SUCCESS) { - pjsip_dlg_dec_lock(dlg); - return status; - } + status = pjsip_dlg_add_usage(dlg, &mod_evsub.mod, dlgsub_head); + if (status != PJ_SUCCESS) { + pjsip_dlg_dec_lock(dlg); + return status; + } } PJ_LOG(5,(sub->obj_name, "%s subscription created, using dialog %s", - (role==PJSIP_ROLE_UAC ? "UAC" : "UAS"), - dlg->obj_name)); + (role==PJSIP_ROLE_UAC ? "UAC" : "UAS"), + dlg->obj_name)); *p_evsub = sub; pjsip_dlg_dec_lock(dlg); @@ -869,10 +868,10 @@ PJ_DEF(pj_status_t) pjsip_evsub_dec_ref(pjsip_evsub *sub) * Create client subscription session. */ PJ_DEF(pj_status_t) pjsip_evsub_create_uac( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - const pj_str_t *event, - unsigned option, - pjsip_evsub **p_evsub) + const pjsip_evsub_user *user_cb, + const pj_str_t *event, + unsigned option, + pjsip_evsub **p_evsub) { pjsip_evsub *sub; pj_status_t status; @@ -882,13 +881,13 @@ PJ_DEF(pj_status_t) pjsip_evsub_create_uac( pjsip_dialog *dlg, pjsip_dlg_inc_lock(dlg); status = evsub_create(dlg, PJSIP_UAC_ROLE, user_cb, event, option, &sub); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Add unique Id to Event header, only when PJSIP_EVSUB_NO_EVENT_ID * is not specified. */ if ((option & PJSIP_EVSUB_NO_EVENT_ID) == 0) { - pj_create_unique_string(sub->pool, &sub->event->id_param); + pj_create_unique_string(sub->pool, &sub->event->id_param); } /* Increment dlg session. */ @@ -897,8 +896,8 @@ PJ_DEF(pj_status_t) pjsip_evsub_create_uac( pjsip_dialog *dlg, /* Init group lock */ status = pj_grp_lock_create(dlg->pool, NULL, &sub->grp_lock); if (status != PJ_SUCCESS) { - pjsip_dlg_dec_session(sub->dlg, &mod_evsub.mod); - goto on_return; + pjsip_dlg_dec_session(sub->dlg, &mod_evsub.mod); + goto on_return; } pj_grp_lock_add_ref(sub->grp_lock); @@ -917,10 +916,10 @@ PJ_DEF(pj_status_t) pjsip_evsub_create_uac( pjsip_dialog *dlg, * Create server subscription session from incoming request. */ PJ_DEF(pj_status_t) pjsip_evsub_create_uas( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - pjsip_rx_data *rdata, - unsigned option, - pjsip_evsub **p_evsub) + const pjsip_evsub_user *user_cb, + pjsip_rx_data *rdata, + unsigned option, + pjsip_evsub **p_evsub) { pjsip_evsub *sub; pjsip_transaction *tsx; @@ -934,7 +933,7 @@ PJ_DEF(pj_status_t) pjsip_evsub_create_uas( pjsip_dialog *dlg, /* MUST be request message: */ PJ_ASSERT_RETURN(rdata->msg_info.msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); /* Transaction MUST have been created (in the dialog) */ tsx = pjsip_rdata_get_tsx(rdata); @@ -942,7 +941,7 @@ PJ_DEF(pj_status_t) pjsip_evsub_create_uas( pjsip_dialog *dlg, /* No subscription must have been attached to transaction */ PJ_ASSERT_RETURN(tsx->mod_data[mod_evsub.mod.id] == NULL, - PJSIP_ETYPEEXISTS); + PJSIP_ETYPEEXISTS); /* Package MUST implement on_rx_refresh */ PJ_ASSERT_RETURN(user_cb->on_rx_refresh, PJ_EINVALIDOP); @@ -951,10 +950,10 @@ PJ_DEF(pj_status_t) pjsip_evsub_create_uas( pjsip_dialog *dlg, * the package name (don't want to add more arguments in the function). */ event_hdr = (pjsip_event_hdr*) - pjsip_msg_find_hdr_by_names(rdata->msg_info.msg, &STR_EVENT, - &STR_EVENT_S, NULL); + pjsip_msg_find_hdr_by_names(rdata->msg_info.msg, &STR_EVENT, + &STR_EVENT_S, NULL); if (event_hdr == NULL) { - return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_REQUEST); + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_REQUEST); } /* Start locking the mutex: */ @@ -964,23 +963,23 @@ PJ_DEF(pj_status_t) pjsip_evsub_create_uas( pjsip_dialog *dlg, /* Create the session: */ status = evsub_create(dlg, PJSIP_UAS_ROLE, user_cb, - &event_hdr->event_type, option, &sub); + &event_hdr->event_type, option, &sub); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Just duplicate Event header from the request */ sub->event = (pjsip_event_hdr*) pjsip_hdr_clone(sub->pool, event_hdr); /* Set the method: */ pjsip_method_copy(sub->pool, &sub->method, - &rdata->msg_info.msg->line.req.method); + &rdata->msg_info.msg->line.req.method); /* Update expiration time according to client request: */ expires_hdr = (pjsip_expires_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL); + pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL); if (expires_hdr) { - sub->expires->ivalue = expires_hdr->ivalue; + sub->expires->ivalue = expires_hdr->ivalue; } /* Update time. */ @@ -989,9 +988,9 @@ PJ_DEF(pj_status_t) pjsip_evsub_create_uas( pjsip_dialog *dlg, /* Update Accept header: */ accept_hdr = (pjsip_accept_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_ACCEPT, NULL); + pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_ACCEPT, NULL); if (accept_hdr) - sub->accept = (pjsip_accept_hdr*)pjsip_hdr_clone(sub->pool,accept_hdr); + sub->accept = (pjsip_accept_hdr*)pjsip_hdr_clone(sub->pool,accept_hdr); /* Increment dlg session. */ pjsip_dlg_inc_session(dlg, &mod_evsub.mod); @@ -999,8 +998,8 @@ PJ_DEF(pj_status_t) pjsip_evsub_create_uas( pjsip_dialog *dlg, /* Init group lock */ status = pj_grp_lock_create(dlg->pool, NULL, &sub->grp_lock); if (status != PJ_SUCCESS) { - pjsip_dlg_dec_session(sub->dlg, &mod_evsub.mod); - goto on_return; + pjsip_dlg_dec_session(sub->dlg, &mod_evsub.mod); + goto on_return; } pj_grp_lock_add_ref(sub->grp_lock); @@ -1025,7 +1024,7 @@ PJ_DEF(pj_status_t) pjsip_evsub_create_uas( pjsip_dialog *dlg, * Forcefully destroy subscription. */ PJ_DEF(pj_status_t) pjsip_evsub_terminate( pjsip_evsub *sub, - pj_bool_t notify ) + pj_bool_t notify ) { PJ_ASSERT_RETURN(sub, PJ_EINVAL); @@ -1034,9 +1033,9 @@ PJ_DEF(pj_status_t) pjsip_evsub_terminate( pjsip_evsub *sub, /* I think it's pretty safe to disable this check. if (sub->pending_tsx) { - pj_assert(!"Unable to terminate when there's pending tsx"); - pjsip_dlg_dec_lock(sub->dlg); - return PJ_EINVALIDOP; + pj_assert(!"Unable to terminate when there's pending tsx"); + pjsip_dlg_dec_lock(sub->dlg); + return PJ_EINVALIDOP; } */ @@ -1067,7 +1066,7 @@ PJ_DEF(const char*) pjsip_evsub_get_state_name(const pjsip_evsub *sub) * Get termination reason. */ PJ_DEF(const pj_str_t*) pjsip_evsub_get_termination_reason( - const pjsip_evsub *sub) + const pjsip_evsub *sub) { return &sub->term_reason; } @@ -1084,9 +1083,9 @@ PJ_DEF(pj_uint32_t) pjsip_evsub_get_expires(const pjsip_evsub *sub) * Initiate client subscription */ PJ_DEF(pj_status_t) pjsip_evsub_initiate( pjsip_evsub *sub, - const pjsip_method *method, - pj_uint32_t expires, - pjsip_tx_data **p_tdata) + const pjsip_method *method, + pj_uint32_t expires, + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pj_status_t status; @@ -1095,61 +1094,61 @@ PJ_DEF(pj_status_t) pjsip_evsub_initiate( pjsip_evsub *sub, /* Use SUBSCRIBE if method is not specified */ if (method == NULL) - method = &pjsip_subscribe_method; + method = &pjsip_subscribe_method; pjsip_dlg_inc_lock(sub->dlg); /* Update method: */ if (sub->state == PJSIP_EVSUB_STATE_NULL) - pjsip_method_copy(sub->pool, &sub->method, method); + pjsip_method_copy(sub->pool, &sub->method, method); status = pjsip_dlg_create_request( sub->dlg, method, -1, &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Add Event header: */ pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, sub->event)); + pjsip_hdr_shallow_clone(tdata->pool, sub->event)); /* Update and add expires header: */ if (expires != PJSIP_EXPIRES_NOT_SPECIFIED) - sub->expires->ivalue = expires; + sub->expires->ivalue = expires; pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, sub->expires)); + pjsip_hdr_shallow_clone(tdata->pool, sub->expires)); /* Add Supported header (it's optional in RFC 3265, but some event package * RFC may bring this requirement to SHOULD strength - e.g. RFC 5373) */ { const pjsip_hdr *hdr = pjsip_endpt_get_capability(sub->endpt, - PJSIP_H_SUPPORTED, - NULL); + PJSIP_H_SUPPORTED, + NULL); if (hdr) { - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, hdr)); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, hdr)); } } /* Add Accept header: */ pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, sub->accept)); + pjsip_hdr_shallow_clone(tdata->pool, sub->accept)); /* Add Allow-Events header: */ pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, - mod_evsub.allow_events_hdr)); + pjsip_hdr_shallow_clone(tdata->pool, + mod_evsub.allow_events_hdr)); /* Add custom headers */ { - const pjsip_hdr *hdr = sub->sub_hdr_list.next; - while (hdr != &sub->sub_hdr_list) { - pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, hdr)); - hdr = hdr->next; - } + const pjsip_hdr *hdr = sub->sub_hdr_list.next; + while (hdr != &sub->sub_hdr_list) { + pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, hdr)); + hdr = hdr->next; + } } @@ -1167,7 +1166,7 @@ PJ_DEF(pj_status_t) pjsip_evsub_initiate( pjsip_evsub *sub, * Add custom headers. */ PJ_DEF(pj_status_t) pjsip_evsub_add_header( pjsip_evsub *sub, - const pjsip_hdr *hdr_list ) + const pjsip_hdr *hdr_list ) { const pjsip_hdr *hdr; @@ -1176,8 +1175,8 @@ PJ_DEF(pj_status_t) pjsip_evsub_add_header( pjsip_evsub *sub, hdr = hdr_list->next; while (hdr != hdr_list) { pj_list_push_back(&sub->sub_hdr_list, (pjsip_hdr*) - pjsip_hdr_clone(sub->pool, hdr)); - hdr = hdr->next; + pjsip_hdr_clone(sub->pool, hdr)); + hdr = hdr->next; } return PJ_SUCCESS; @@ -1188,9 +1187,9 @@ PJ_DEF(pj_status_t) pjsip_evsub_add_header( pjsip_evsub *sub, * Accept incoming subscription request. */ PJ_DEF(pj_status_t) pjsip_evsub_accept( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int st_code, - const pjsip_hdr *hdr_list ) + pjsip_rx_data *rdata, + int st_code, + const pjsip_hdr *hdr_list ) { pjsip_tx_data *tdata; pjsip_transaction *tsx; @@ -1211,44 +1210,44 @@ PJ_DEF(pj_status_t) pjsip_evsub_accept( pjsip_evsub *sub, */ tsx = pjsip_rdata_get_tsx(rdata); PJ_ASSERT_RETURN(tsx->mod_data[mod_evsub.mod.id] != NULL, - PJ_EINVALIDOP); + PJ_EINVALIDOP); /* Lock dialog */ pjsip_dlg_inc_lock(sub->dlg); /* Create response: */ status = pjsip_dlg_create_response( sub->dlg, rdata, st_code, NULL, - &tdata); + &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Add expires header: */ pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, sub->expires)); + pjsip_hdr_shallow_clone(tdata->pool, sub->expires)); /* Add additional header, if any. */ if (hdr_list) { - const pjsip_hdr *hdr = hdr_list->next; - while (hdr != hdr_list) { - pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) - pjsip_hdr_clone(tdata->pool, hdr)); - hdr = hdr->next; - } + const pjsip_hdr *hdr = hdr_list->next; + while (hdr != hdr_list) { + pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, hdr)); + hdr = hdr->next; + } } /* Send the response: */ status = pjsip_dlg_send_response( sub->dlg, tsx, tdata ); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Set UAS timeout timer, when status code is 2xx and state is not * terminated. */ if (st_code/100 == 2 && sub->state != PJSIP_EVSUB_STATE_TERMINATED) { - PJ_LOG(5,(sub->obj_name, "UAS timeout in %d seconds", - sub->expires->ivalue)); - set_timer(sub, TIMER_TYPE_UAS_TIMEOUT, sub->expires->ivalue); + PJ_LOG(5,(sub->obj_name, "UAS timeout in %d seconds", + sub->expires->ivalue)); + set_timer(sub, TIMER_TYPE_UAS_TIMEOUT, sub->expires->ivalue); } on_return: @@ -1263,10 +1262,10 @@ PJ_DEF(pj_status_t) pjsip_evsub_accept( pjsip_evsub *sub, * state. */ static pjsip_sub_state_hdr* sub_state_create( pj_pool_t *pool, - pjsip_evsub *sub, - pjsip_evsub_state state, - const pj_str_t *state_str, - const pj_str_t *reason ) + pjsip_evsub *sub, + pjsip_evsub_state state, + const pj_str_t *state_str, + const pj_str_t *reason ) { pjsip_sub_state_hdr *sub_state; pj_time_val now, delay; @@ -1283,30 +1282,30 @@ static pjsip_sub_state_hdr* sub_state_create( pj_pool_t *pool, switch (state) { case PJSIP_EVSUB_STATE_NULL: case PJSIP_EVSUB_STATE_SENT: - pj_assert(!"Invalid state!"); - /* Treat as pending */ + pj_assert(!"Invalid state!"); + /* Treat as pending */ case PJSIP_EVSUB_STATE_ACCEPTED: case PJSIP_EVSUB_STATE_PENDING: - sub_state->sub_state = STR_PENDING; - sub_state->expires_param = delay.sec; - break; + sub_state->sub_state = STR_PENDING; + sub_state->expires_param = delay.sec; + break; case PJSIP_EVSUB_STATE_ACTIVE: - sub_state->sub_state = STR_ACTIVE; - sub_state->expires_param = delay.sec; - break; + sub_state->sub_state = STR_ACTIVE; + sub_state->expires_param = delay.sec; + break; case PJSIP_EVSUB_STATE_TERMINATED: - sub_state->sub_state = STR_TERMINATED; - if (reason != NULL) - pj_strdup(pool, &sub_state->reason_param, reason); - break; + sub_state->sub_state = STR_TERMINATED; + if (reason != NULL) + pj_strdup(pool, &sub_state->reason_param, reason); + break; case PJSIP_EVSUB_STATE_UNKNOWN: - pj_assert(state_str != NULL); - pj_strdup(pool, &sub_state->sub_state, state_str); - break; + pj_assert(state_str != NULL); + pj_strdup(pool, &sub_state->sub_state, state_str); + break; } return sub_state; @@ -1316,10 +1315,10 @@ static pjsip_sub_state_hdr* sub_state_create( pj_pool_t *pool, * Create and send NOTIFY request. */ PJ_DEF(pj_status_t) pjsip_evsub_notify( pjsip_evsub *sub, - pjsip_evsub_state state, - const pj_str_t *state_str, - const pj_str_t *reason, - pjsip_tx_data **p_tdata) + pjsip_evsub_state state, + const pj_str_t *state_str, + const pj_str_t *reason, + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pjsip_sub_state_hdr *sub_state; @@ -1333,36 +1332,36 @@ PJ_DEF(pj_status_t) pjsip_evsub_notify( pjsip_evsub *sub, /* Create NOTIFY request */ status = pjsip_dlg_create_request( sub->dlg, pjsip_get_notify_method(), - -1, &tdata); + -1, &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Add Event header */ pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, sub->event)); + pjsip_hdr_shallow_clone(tdata->pool, sub->event)); /* Add Subscription-State header */ sub_state = sub_state_create(tdata->pool, sub, state, state_str, - reason); + reason); pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)sub_state); /* Add Allow-Events header */ pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, mod_evsub.allow_events_hdr)); + pjsip_hdr_shallow_clone(tdata->pool, mod_evsub.allow_events_hdr)); /* Add Authentication headers. */ pjsip_auth_clt_init_req( &sub->dlg->auth_sess, tdata ); /* Update reason */ if (reason) - pj_strdup(sub->dlg->pool, &sub->term_reason, reason); + pj_strdup(sub->dlg->pool, &sub->term_reason, reason); /* Save destination state. */ sub->dst_state = state; if (state_str) - pj_strdup(sub->pool, &sub->dst_state_str, state_str); + pj_strdup(sub->pool, &sub->dst_state_str, state_str); else - sub->dst_state_str.slen = 0; + sub->dst_state_str.slen = 0; *p_tdata = tdata; @@ -1378,10 +1377,10 @@ PJ_DEF(pj_status_t) pjsip_evsub_notify( pjsip_evsub *sub, * Create NOTIFY to reflect current status. */ PJ_DEF(pj_status_t) pjsip_evsub_current_notify( pjsip_evsub *sub, - pjsip_tx_data **p_tdata ) + pjsip_tx_data **p_tdata ) { return pjsip_evsub_notify( sub, sub->state, &sub->state_str, - NULL, p_tdata ); + NULL, p_tdata ); } @@ -1389,13 +1388,13 @@ PJ_DEF(pj_status_t) pjsip_evsub_current_notify( pjsip_evsub *sub, * Send request. */ PJ_DEF(pj_status_t) pjsip_evsub_send_request( pjsip_evsub *sub, - pjsip_tx_data *tdata) + pjsip_tx_data *tdata) { pj_status_t status = PJ_SUCCESS; /* Must be request message. */ PJ_ASSERT_RETURN(tdata->msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); /* Lock */ pjsip_dlg_inc_lock(sub->dlg); @@ -1406,16 +1405,16 @@ PJ_DEF(pj_status_t) pjsip_evsub_send_request( pjsip_evsub *sub, */ if (sub->calling_on_rx_refresh && pjsip_method_cmp(&tdata->msg->line.req.method, - &pjsip_notify_method)==0) + &pjsip_notify_method)==0) { - sub->pending_notify = tdata; - goto on_return; + sub->pending_notify = tdata; + goto on_return; } /* Send the request. */ status = pjsip_dlg_send_request(sub->dlg, tdata, -1, NULL); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Special case for NOTIFY: @@ -1423,17 +1422,17 @@ PJ_DEF(pj_status_t) pjsip_evsub_send_request( pjsip_evsub *sub, * new state now, when the request was actually sent. */ if (pjsip_method_cmp(&tdata->msg->line.req.method, - &pjsip_notify_method)==0) + &pjsip_notify_method)==0) { - PJ_ASSERT_ON_FAIL( sub->dst_state!=PJSIP_EVSUB_STATE_NULL, - {goto on_return;}); + PJ_ASSERT_ON_FAIL( sub->dst_state!=PJSIP_EVSUB_STATE_NULL, + {goto on_return;}); - set_state(sub, sub->dst_state, - (sub->dst_state_str.slen ? &sub->dst_state_str : NULL), - NULL, NULL); + set_state(sub, sub->dst_state, + (sub->dst_state_str.slen ? &sub->dst_state_str : NULL), + NULL, NULL); - sub->dst_state = PJSIP_EVSUB_STATE_NULL; - sub->dst_state_str.slen = 0; + sub->dst_state = PJSIP_EVSUB_STATE_NULL; + sub->dst_state_str.slen = 0; } @@ -1446,7 +1445,7 @@ PJ_DEF(pj_status_t) pjsip_evsub_send_request( pjsip_evsub *sub, /* Callback to be called to terminate transaction. */ static void terminate_timer_cb(pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { pj_str_t *key; pjsip_transaction *tsx; @@ -1460,7 +1459,7 @@ static void terminate_timer_cb(pj_timer_heap_t *timer_heap, tsx = pjsip_tsx_layer_find_tsx(key, PJ_FALSE); /* Chance of race condition here */ if (tsx) { - pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_UPDATED); + pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_UPDATED); } } @@ -1469,7 +1468,7 @@ static void terminate_timer_cb(pj_timer_heap_t *timer_heap, * Attach subscription session to newly created transaction, if appropriate. */ static pjsip_evsub *on_new_transaction( pjsip_transaction *tsx, - pjsip_event *event) + pjsip_event *event) { /* * Newly created transaction will not have subscription session @@ -1484,41 +1483,41 @@ static pjsip_evsub *on_new_transaction( pjsip_transaction *tsx, dlg = pjsip_tsx_get_dlg(tsx); if (!dlg) { - pj_assert(!"Transaction should have a dialog instance!"); - return NULL; + pj_assert(!"Transaction should have a dialog instance!"); + return NULL; } switch (event->body.tsx_state.type) { case PJSIP_EVENT_RX_MSG: - msg = event->body.tsx_state.src.rdata->msg_info.msg; - break; + msg = event->body.tsx_state.src.rdata->msg_info.msg; + break; case PJSIP_EVENT_TX_MSG: - msg = event->body.tsx_state.src.tdata->msg; - break; + msg = event->body.tsx_state.src.tdata->msg; + break; default: - if (tsx->role == PJSIP_ROLE_UAC) - msg = tsx->last_tx->msg; - else - msg = NULL; - break; + if (tsx->role == PJSIP_ROLE_UAC) + msg = tsx->last_tx->msg; + else + msg = NULL; + break; } if (!msg) { - //Note: - // this transaction can be other transaction in the dialog. - // The assertion below probably only valid for dialog that - // only has one event subscription usage. - //pj_assert(!"First transaction event is not TX or RX!"); - return NULL; + //Note: + // this transaction can be other transaction in the dialog. + // The assertion below probably only valid for dialog that + // only has one event subscription usage. + //pj_assert(!"First transaction event is not TX or RX!"); + return NULL; } event_hdr = (pjsip_event_hdr*) - pjsip_msg_find_hdr_by_names(msg, &STR_EVENT, - &STR_EVENT_S, NULL); + pjsip_msg_find_hdr_by_names(msg, &STR_EVENT, + &STR_EVENT_S, NULL); if (!event_hdr) { - /* Not subscription related message */ - return NULL; + /* Not subscription related message */ + return NULL; } /* Find the subscription in the dialog, based on the content @@ -1527,62 +1526,62 @@ static pjsip_evsub *on_new_transaction( pjsip_transaction *tsx, dlgsub_head = (struct dlgsub*) dlg->mod_data[mod_evsub.mod.id]; if (dlgsub_head == NULL) { - dlgsub_head = PJ_POOL_ALLOC_T(dlg->pool, struct dlgsub); - pj_list_init(dlgsub_head); - dlg->mod_data[mod_evsub.mod.id] = dlgsub_head; + dlgsub_head = PJ_POOL_ALLOC_T(dlg->pool, struct dlgsub); + pj_list_init(dlgsub_head); + dlg->mod_data[mod_evsub.mod.id] = dlgsub_head; } dlgsub = dlgsub_head->next; while (dlgsub != dlgsub_head) { - if (pj_stricmp(&dlgsub->sub->event->event_type, - &event_hdr->event_type)==0) - { - /* Event type matched. - * Check if event ID matched too. - */ - if (pj_strcmp(&dlgsub->sub->event->id_param, - &event_hdr->id_param)==0) - { - /* Skip this subscription if it has no event ID and has been - * terminated (see ticket #1647). - */ - if ((dlgsub->sub->option & PJSIP_EVSUB_NO_EVENT_ID) && - (pjsip_evsub_get_state(dlgsub->sub)== - PJSIP_EVSUB_STATE_TERMINATED)) - { - dlgsub = dlgsub->next; - continue; - } else { - break; - } - - } - /* - * Otherwise if it is an UAC subscription, AND - * PJSIP_EVSUB_NO_EVENT_ID flag is set, AND - * the session's event id is NULL, AND - * the incoming request is NOTIFY with event ID, then - * we consider it as a match, and update the - * session's event id. - */ - else if (dlgsub->sub->role == PJSIP_ROLE_UAC && - (dlgsub->sub->option & PJSIP_EVSUB_NO_EVENT_ID)!=0 && - dlgsub->sub->event->id_param.slen==0 && - !pjsip_method_cmp(&tsx->method, &pjsip_notify_method)) - { - /* Update session's event id. */ - pj_strdup(dlgsub->sub->pool, - &dlgsub->sub->event->id_param, - &event_hdr->id_param); - - break; - } - } - - - - dlgsub = dlgsub->next; + if (pj_stricmp(&dlgsub->sub->event->event_type, + &event_hdr->event_type)==0) + { + /* Event type matched. + * Check if event ID matched too. + */ + if (pj_strcmp(&dlgsub->sub->event->id_param, + &event_hdr->id_param)==0) + { + /* Skip this subscription if it has no event ID and has been + * terminated (see ticket #1647). + */ + if ((dlgsub->sub->option & PJSIP_EVSUB_NO_EVENT_ID) && + (pjsip_evsub_get_state(dlgsub->sub)== + PJSIP_EVSUB_STATE_TERMINATED)) + { + dlgsub = dlgsub->next; + continue; + } else { + break; + } + + } + /* + * Otherwise if it is an UAC subscription, AND + * PJSIP_EVSUB_NO_EVENT_ID flag is set, AND + * the session's event id is NULL, AND + * the incoming request is NOTIFY with event ID, then + * we consider it as a match, and update the + * session's event id. + */ + else if (dlgsub->sub->role == PJSIP_ROLE_UAC && + (dlgsub->sub->option & PJSIP_EVSUB_NO_EVENT_ID)!=0 && + dlgsub->sub->event->id_param.slen==0 && + !pjsip_method_cmp(&tsx->method, &pjsip_notify_method)) + { + /* Update session's event id. */ + pj_strdup(dlgsub->sub->pool, + &dlgsub->sub->event->id_param, + &event_hdr->id_param); + + break; + } + } + + + + dlgsub = dlgsub->next; } /* Note: @@ -1591,43 +1590,43 @@ static pjsip_evsub *on_new_transaction( pjsip_transaction *tsx, * such as final NOTIFY upon unsubscription. */ if (dlgsub == dlgsub_head || - (dlgsub->sub && - tsx->role == PJSIP_ROLE_UAS && - pjsip_evsub_get_state(dlgsub->sub)==PJSIP_EVSUB_STATE_TERMINATED)) + (dlgsub->sub && + tsx->role == PJSIP_ROLE_UAS && + pjsip_evsub_get_state(dlgsub->sub)==PJSIP_EVSUB_STATE_TERMINATED)) { - const char *reason_msg = - (dlgsub == dlgsub_head ? "Subscription Does Not Exist" : - "Subscription already terminated"); - - /* This could be incoming request to create new subscription */ - PJ_LOG(4,(THIS_FILE, - "%s for %.*s, event=%.*s;id=%.*s", - reason_msg, - (int)tsx->method.name.slen, - tsx->method.name.ptr, - (int)event_hdr->event_type.slen, - event_hdr->event_type.ptr, - (int)event_hdr->id_param.slen, - event_hdr->id_param.ptr)); - - /* If this is an incoming NOTIFY, reject with 481 */ - if (tsx->state == PJSIP_TSX_STATE_TRYING && - pjsip_method_cmp(&tsx->method, &pjsip_notify_method)==0) - { - pj_str_t reason; - pjsip_tx_data *tdata; - pj_status_t status; - - pj_cstr(&reason, reason_msg); - status = pjsip_dlg_create_response(dlg, - event->body.tsx_state.src.rdata, - 481, &reason, - &tdata); - if (status == PJ_SUCCESS) { - status = pjsip_dlg_send_response(dlg, tsx, tdata); - } - } - return NULL; + const char *reason_msg = + (dlgsub == dlgsub_head ? "Subscription Does Not Exist" : + "Subscription already terminated"); + + /* This could be incoming request to create new subscription */ + PJ_LOG(4,(THIS_FILE, + "%s for %.*s, event=%.*s;id=%.*s", + reason_msg, + (int)tsx->method.name.slen, + tsx->method.name.ptr, + (int)event_hdr->event_type.slen, + event_hdr->event_type.ptr, + (int)event_hdr->id_param.slen, + event_hdr->id_param.ptr)); + + /* If this is an incoming NOTIFY, reject with 481 */ + if (tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_notify_method)==0) + { + pj_str_t reason; + pjsip_tx_data *tdata; + pj_status_t status; + + pj_cstr(&reason, reason_msg); + status = pjsip_dlg_create_response(dlg, + event->body.tsx_state.src.rdata, + 481, &reason, + &tdata); + if (status == PJ_SUCCESS) { + status = pjsip_dlg_send_response(dlg, tsx, tdata); + } + } + return NULL; } /* Found! */ @@ -1643,50 +1642,50 @@ static pjsip_evsub *on_new_transaction( pjsip_transaction *tsx, * the older one. * * Sample scenario: - * - subscribe sent to destination that doesn't exist, transaction - * is still retransmitting request, then unsubscribe is sent. + * - subscribe sent to destination that doesn't exist, transaction + * is still retransmitting request, then unsubscribe is sent. */ if (tsx->role == PJSIP_ROLE_UAC && - tsx->state == PJSIP_TSX_STATE_CALLING && - (pjsip_method_cmp(&tsx->method, &sub->method) == 0 || - pjsip_method_cmp(&tsx->method, &pjsip_subscribe_method) == 0)) + tsx->state == PJSIP_TSX_STATE_CALLING && + (pjsip_method_cmp(&tsx->method, &sub->method) == 0 || + pjsip_method_cmp(&tsx->method, &pjsip_subscribe_method) == 0)) { - if (sub->pending_sub && - sub->pending_sub->state < PJSIP_TSX_STATE_COMPLETED) - { - pj_timer_entry *timer; - pj_str_t *key; - pj_time_val timeout = {0, 0}; - - PJ_LOG(4,(sub->obj_name, - "Cancelling pending subscription request")); - - /* By convention, we use 490 (Request Updated) status code. - * When transaction handler (below) see this status code, it - * will ignore the transaction. - */ - /* This unfortunately may cause deadlock, because at the moment - * we are holding dialog's mutex. If a response to this - * transaction is in progress in another thread, that thread - * will deadlock when trying to acquire dialog mutex, because - * it is holding the transaction mutex. - * - * So the solution is to register timer to kill this transaction. - */ - //pjsip_tsx_terminate(sub->pending_sub, PJSIP_SC_REQUEST_UPDATED); - timer = PJ_POOL_ZALLOC_T(dlg->pool, pj_timer_entry); - key = PJ_POOL_ALLOC_T(dlg->pool, pj_str_t); - pj_strdup(dlg->pool, key, &sub->pending_sub->transaction_key); - timer->cb = &terminate_timer_cb; - timer->user_data = key; - timer->id = 1; - sub->pending_sub_timer = timer; - - pjsip_endpt_schedule_timer(dlg->endpt, timer, &timeout); - } - - sub->pending_sub = tsx; + if (sub->pending_sub && + sub->pending_sub->state < PJSIP_TSX_STATE_COMPLETED) + { + pj_timer_entry *timer; + pj_str_t *key; + pj_time_val timeout = {0, 0}; + + PJ_LOG(4,(sub->obj_name, + "Cancelling pending subscription request")); + + /* By convention, we use 490 (Request Updated) status code. + * When transaction handler (below) see this status code, it + * will ignore the transaction. + */ + /* This unfortunately may cause deadlock, because at the moment + * we are holding dialog's mutex. If a response to this + * transaction is in progress in another thread, that thread + * will deadlock when trying to acquire dialog mutex, because + * it is holding the transaction mutex. + * + * So the solution is to register timer to kill this transaction. + */ + //pjsip_tsx_terminate(sub->pending_sub, PJSIP_SC_REQUEST_UPDATED); + timer = PJ_POOL_ZALLOC_T(dlg->pool, pj_timer_entry); + key = PJ_POOL_ALLOC_T(dlg->pool, pj_str_t); + pj_strdup(dlg->pool, key, &sub->pending_sub->transaction_key); + timer->cb = &terminate_timer_cb; + timer->user_data = key; + timer->id = 1; + sub->pending_sub_timer = timer; + + pjsip_endpt_schedule_timer(dlg->endpt, timer, &timeout); + } + + sub->pending_sub = tsx; } @@ -1698,42 +1697,42 @@ static pjsip_evsub *on_new_transaction( pjsip_transaction *tsx, * Create response, adding custome headers and msg body. */ static pj_status_t create_response( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - const pjsip_hdr *res_hdr, - const pjsip_msg_body *body, - pjsip_tx_data **p_tdata) + pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + const pjsip_hdr *res_hdr, + const pjsip_msg_body *body, + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pjsip_hdr *hdr; pj_status_t status; status = pjsip_dlg_create_response(sub->dlg, rdata, - st_code, st_text, &tdata); + st_code, st_text, &tdata); if (status != PJ_SUCCESS) - return status; + return status; *p_tdata = tdata; /* Add response headers. */ hdr = res_hdr->next; while (hdr != res_hdr) { - pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) - pjsip_hdr_clone(tdata->pool, hdr)); - hdr = hdr->next; + pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, hdr)); + hdr = hdr->next; } /* Add msg body, if any */ if (body) { - tdata->msg->body = pjsip_msg_body_clone(tdata->pool, body); - if (tdata->msg->body == NULL) { + tdata->msg->body = pjsip_msg_body_clone(tdata->pool, body); + if (tdata->msg->body == NULL) { - PJ_LOG(4,(THIS_FILE, "Error: unable to clone msg body")); + PJ_LOG(4,(THIS_FILE, "Error: unable to clone msg body")); - /* Ignore */ - return PJ_SUCCESS; - } + /* Ignore */ + return PJ_SUCCESS; + } } return PJ_SUCCESS; @@ -1743,28 +1742,28 @@ static pj_status_t create_response( pjsip_evsub *sub, * Get subscription state from the value of Subscription-State header. */ static void get_hdr_state( pjsip_sub_state_hdr *sub_state, - pjsip_evsub_state *state, - pj_str_t **state_str ) + pjsip_evsub_state *state, + pj_str_t **state_str ) { if (pj_stricmp(&sub_state->sub_state, &STR_TERMINATED)==0) { - *state = PJSIP_EVSUB_STATE_TERMINATED; - *state_str = NULL; + *state = PJSIP_EVSUB_STATE_TERMINATED; + *state_str = NULL; } else if (pj_stricmp(&sub_state->sub_state, &STR_ACTIVE)==0) { - *state = PJSIP_EVSUB_STATE_ACTIVE; - *state_str = NULL; + *state = PJSIP_EVSUB_STATE_ACTIVE; + *state_str = NULL; } else if (pj_stricmp(&sub_state->sub_state, &STR_PENDING)==0) { - *state = PJSIP_EVSUB_STATE_PENDING; - *state_str = NULL; + *state = PJSIP_EVSUB_STATE_PENDING; + *state_str = NULL; } else { - *state = PJSIP_EVSUB_STATE_UNKNOWN; - *state_str = &sub_state->sub_state; + *state = PJSIP_EVSUB_STATE_UNKNOWN; + *state_str = &sub_state->sub_state; } } @@ -1773,308 +1772,308 @@ static void get_hdr_state( pjsip_sub_state_hdr *sub_state, * Transaction event processing by UAC, after subscription is sent. */ static void on_tsx_state_uac( pjsip_evsub *sub, pjsip_transaction *tsx, - pjsip_event *event ) + pjsip_event *event ) { if (pjsip_method_cmp(&tsx->method, &sub->method)==0 || - pjsip_method_cmp(&tsx->method, &pjsip_subscribe_method)==0) + pjsip_method_cmp(&tsx->method, &pjsip_subscribe_method)==0) { - /* Received response to outgoing request that establishes/refresh - * subscription. - */ - - /* First time initial request is sent. */ - if (sub->state == PJSIP_EVSUB_STATE_NULL && - tsx->state == PJSIP_TSX_STATE_CALLING) - { - set_state(sub, PJSIP_EVSUB_STATE_SENT, NULL, event, NULL); - return; - } - - /* Only interested in final response */ - if (tsx->state != PJSIP_TSX_STATE_COMPLETED && - tsx->state != PJSIP_TSX_STATE_TERMINATED) - { - return; - } - - /* Clear pending subscription */ - if (tsx == sub->pending_sub) { - sub->pending_sub = NULL; - } else if (sub->pending_sub != NULL) { - /* This SUBSCRIBE transaction has been "renewed" with another - * SUBSCRIBE, so we can just ignore this. For example, user - * sent SUBSCRIBE followed immediately with UN-SUBSCRIBE. - */ - return; - } - - /* Handle authentication. */ - if (tsx->status_code==401 || tsx->status_code==407) { - pjsip_tx_data *tdata; - pj_status_t status; - - if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - /* Previously failed transaction has terminated */ - return; - } - - status = pjsip_auth_clt_reinit_req(&sub->dlg->auth_sess, - event->body.tsx_state.src.rdata, - tsx->last_tx, &tdata); - if (status == PJ_SUCCESS) - status = pjsip_dlg_send_request(sub->dlg, tdata, -1, NULL); - - if (status != PJ_SUCCESS) { - /* Authentication failed! */ - set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, - NULL, event, &tsx->status_text); - return; - } - - return; - } - - if (tsx->status_code/100 == 2) { - - /* Successfull SUBSCRIBE request! - * This could be: - * - response to initial SUBSCRIBE request - * - response to subsequent refresh - * - response to unsubscription - */ - - if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - /* Ignore; this transaction has been processed before */ - return; - } - - /* Update UAC refresh time, if response contains Expires header, - * only when we're not unsubscribing. - */ - if (sub->expires->ivalue != 0) { - pjsip_msg *msg; - pjsip_expires_hdr *expires; - - msg = event->body.tsx_state.src.rdata->msg_info.msg; - expires = (pjsip_expires_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_EXPIRES, NULL); - if (expires) { - sub->expires->ivalue = expires->ivalue; - } - } - - /* Update time */ - update_expires(sub, sub->expires->ivalue); - - /* Start UAC refresh timer, only when we're not unsubscribing */ - if (sub->expires->ivalue != 0) { - unsigned timeout = (sub->expires->ivalue > TIME_UAC_REFRESH) ? - sub->expires->ivalue - TIME_UAC_REFRESH : sub->expires->ivalue; - - /* Reduce timeout by about 1 - 10 secs (randomized) */ - if (timeout > 10) - timeout += -10 + (pj_rand() % 10); - - PJ_LOG(5,(sub->obj_name, "Will refresh in %d seconds", - timeout)); - set_timer(sub, TIMER_TYPE_UAC_REFRESH, timeout); - - } else { - /* Otherwise set timer to terminate client subscription when - * NOTIFY to end subscription is not received. - */ - set_timer(sub, TIMER_TYPE_UAC_TERMINATE, TIME_UAC_TERMINATE); - } - - /* Set state, if necessary */ - pj_assert(sub->state != PJSIP_EVSUB_STATE_NULL); - if (sub->state == PJSIP_EVSUB_STATE_SENT) { - set_state(sub, PJSIP_EVSUB_STATE_ACCEPTED, NULL, event, NULL); - } - - } else { - - /* Failed SUBSCRIBE request! - * - * The RFC 3265 says that if outgoing SUBSCRIBE fails with status - * other than 481, the subscription is still considered valid for - * the duration of the last Expires. - * - * Since we send refresh about 5 seconds (TIME_UAC_REFRESH) before - * expiration, theoritically the expiration is still valid for the - * next 5 seconds even when we receive non-481 failed response. - * - * Ah, what the heck! - * - * Just terminate now! - * - */ - - if (sub->state == PJSIP_EVSUB_STATE_TERMINATED) { - /* Ignore, has been handled before */ - return; - } - - /* Ignore 490 (Request Updated) status. - * This happens when application sends SUBSCRIBE/REFER while - * another one is still in progress. - */ - if (tsx->status_code == PJSIP_SC_REQUEST_UPDATED) { - return; - } - - /* Set state to TERMINATED */ - set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, - NULL, event, &tsx->status_text); - - } + /* Received response to outgoing request that establishes/refresh + * subscription. + */ + + /* First time initial request is sent. */ + if (sub->state == PJSIP_EVSUB_STATE_NULL && + tsx->state == PJSIP_TSX_STATE_CALLING) + { + set_state(sub, PJSIP_EVSUB_STATE_SENT, NULL, event, NULL); + return; + } + + /* Only interested in final response */ + if (tsx->state != PJSIP_TSX_STATE_COMPLETED && + tsx->state != PJSIP_TSX_STATE_TERMINATED) + { + return; + } + + /* Clear pending subscription */ + if (tsx == sub->pending_sub) { + sub->pending_sub = NULL; + } else if (sub->pending_sub != NULL) { + /* This SUBSCRIBE transaction has been "renewed" with another + * SUBSCRIBE, so we can just ignore this. For example, user + * sent SUBSCRIBE followed immediately with UN-SUBSCRIBE. + */ + return; + } + + /* Handle authentication. */ + if (tsx->status_code==401 || tsx->status_code==407) { + pjsip_tx_data *tdata; + pj_status_t status; + + if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + /* Previously failed transaction has terminated */ + return; + } + + status = pjsip_auth_clt_reinit_req(&sub->dlg->auth_sess, + event->body.tsx_state.src.rdata, + tsx->last_tx, &tdata); + if (status == PJ_SUCCESS) + status = pjsip_dlg_send_request(sub->dlg, tdata, -1, NULL); + + if (status != PJ_SUCCESS) { + /* Authentication failed! */ + set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, + NULL, event, &tsx->status_text); + return; + } + + return; + } + + if (tsx->status_code/100 == 2) { + + /* Successfull SUBSCRIBE request! + * This could be: + * - response to initial SUBSCRIBE request + * - response to subsequent refresh + * - response to unsubscription + */ + + if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + /* Ignore; this transaction has been processed before */ + return; + } + + /* Update UAC refresh time, if response contains Expires header, + * only when we're not unsubscribing. + */ + if (sub->expires->ivalue != 0) { + pjsip_msg *msg; + pjsip_expires_hdr *expires; + + msg = event->body.tsx_state.src.rdata->msg_info.msg; + expires = (pjsip_expires_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_EXPIRES, NULL); + if (expires) { + sub->expires->ivalue = expires->ivalue; + } + } + + /* Update time */ + update_expires(sub, sub->expires->ivalue); + + /* Start UAC refresh timer, only when we're not unsubscribing */ + if (sub->expires->ivalue != 0) { + unsigned timeout = (sub->expires->ivalue > TIME_UAC_REFRESH) ? + sub->expires->ivalue - TIME_UAC_REFRESH : sub->expires->ivalue; + + /* Reduce timeout by about 1 - 10 secs (randomized) */ + if (timeout > 10) + timeout += -10 + (pj_rand() % 10); + + PJ_LOG(5,(sub->obj_name, "Will refresh in %d seconds", + timeout)); + set_timer(sub, TIMER_TYPE_UAC_REFRESH, timeout); + + } else { + /* Otherwise set timer to terminate client subscription when + * NOTIFY to end subscription is not received. + */ + set_timer(sub, TIMER_TYPE_UAC_TERMINATE, TIME_UAC_TERMINATE); + } + + /* Set state, if necessary */ + pj_assert(sub->state != PJSIP_EVSUB_STATE_NULL); + if (sub->state == PJSIP_EVSUB_STATE_SENT) { + set_state(sub, PJSIP_EVSUB_STATE_ACCEPTED, NULL, event, NULL); + } + + } else { + + /* Failed SUBSCRIBE request! + * + * The RFC 3265 says that if outgoing SUBSCRIBE fails with status + * other than 481, the subscription is still considered valid for + * the duration of the last Expires. + * + * Since we send refresh about 5 seconds (TIME_UAC_REFRESH) before + * expiration, theoritically the expiration is still valid for the + * next 5 seconds even when we receive non-481 failed response. + * + * Ah, what the heck! + * + * Just terminate now! + * + */ + + if (sub->state == PJSIP_EVSUB_STATE_TERMINATED) { + /* Ignore, has been handled before */ + return; + } + + /* Ignore 490 (Request Updated) status. + * This happens when application sends SUBSCRIBE/REFER while + * another one is still in progress. + */ + if (tsx->status_code == PJSIP_SC_REQUEST_UPDATED) { + return; + } + + /* Set state to TERMINATED */ + set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, + NULL, event, &tsx->status_text); + + } } else if (pjsip_method_cmp(&tsx->method, &pjsip_notify_method) == 0) { - /* Incoming NOTIFY. - * This can be the result of: - * - Initial subscription response - * - UAS updating the resource info. - * - Unsubscription response. - */ - int st_code = 200; - pj_str_t *st_text = NULL; - pjsip_hdr res_hdr; - pjsip_msg_body *body = NULL; - - pjsip_rx_data *rdata; - pjsip_msg *msg; - pjsip_sub_state_hdr *sub_state; - - pjsip_evsub_state new_state; - pj_str_t *new_state_str; - - pjsip_tx_data *tdata; - pj_status_t status; - - /* Only want to handle initial NOTIFY receive event. */ - if (tsx->state != PJSIP_TSX_STATE_TRYING) - return; - - - rdata = event->body.tsx_state.src.rdata; - msg = rdata->msg_info.msg; - - pj_list_init(&res_hdr); - - /* Get subscription state header. */ - sub_state = (pjsip_sub_state_hdr*) - pjsip_msg_find_hdr_by_name(msg, &STR_SUB_STATE, NULL); - if (sub_state == NULL) { - - pjsip_warning_hdr *warn_hdr; - pj_str_t warn_text = { "Missing Subscription-State header", 33}; - - /* Bad request! Add warning header. */ - st_code = PJSIP_SC_BAD_REQUEST; - warn_hdr = pjsip_warning_hdr_create(rdata->tp_info.pool, 399, - pjsip_endpt_name(sub->endpt), - &warn_text); - pj_list_push_back(&res_hdr, warn_hdr); - } - - /* Call application registered callback to handle incoming NOTIFY, - * if any. - */ - if (st_code==200 && sub->user.on_rx_notify && sub->call_cb) { - (*sub->user.on_rx_notify)(sub, rdata, &st_code, &st_text, - &res_hdr, &body); - - /* Application MUST specify final response! */ - PJ_ASSERT_ON_FAIL(st_code >= 200, {st_code=200; }); - - /* Must be a valid status code */ - PJ_ASSERT_ON_FAIL(st_code <= 699, {st_code=500; }); - } - - - /* If non-2xx should be returned, then send the response. - * No need to update server subscription state. - */ - if (st_code >= 300) { - status = create_response(sub, rdata, st_code, st_text, &res_hdr, - body, &tdata); - if (status == PJ_SUCCESS) { - status = pjsip_dlg_send_response(sub->dlg, tsx, tdata); - } - - /* Start timer to terminate subscription, just in case server - * is not able to generate NOTIFY to our response. - */ - if (status == PJ_SUCCESS) { - unsigned timeout = TIME_UAC_WAIT_NOTIFY; - set_timer(sub, TIMER_TYPE_UAC_WAIT_NOTIFY, timeout); - } else { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_str_t reason; - - reason = pj_strerror(status, errmsg, sizeof(errmsg)); - set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, NULL, NULL, - &reason); - } - - return; - } - - /* Update expiration from the value of expires param in - * Subscription-State header, but ONLY when subscription state - * is "active" or "pending", AND the header contains expires param. - */ - if (sub->expires->ivalue != 0 && - sub_state->expires_param != PJSIP_EXPIRES_NOT_SPECIFIED && - (pj_stricmp(&sub_state->sub_state, &STR_ACTIVE)==0 || - pj_stricmp(&sub_state->sub_state, &STR_PENDING)==0)) - { - unsigned next_refresh = sub_state->expires_param; - unsigned timeout; - - update_expires(sub, next_refresh); - - /* Start UAC refresh timer, only when we're not unsubscribing */ - timeout = (next_refresh > TIME_UAC_REFRESH) ? - next_refresh - TIME_UAC_REFRESH : next_refresh; - - PJ_LOG(5,(sub->obj_name, "Will refresh in %d seconds", timeout)); - set_timer(sub, TIMER_TYPE_UAC_REFRESH, timeout); - } - - /* Find out the state */ - get_hdr_state(sub_state, &new_state, &new_state_str); - - /* Send response. */ - status = create_response(sub, rdata, st_code, st_text, &res_hdr, - body, &tdata); - if (status == PJ_SUCCESS) - status = pjsip_dlg_send_response(sub->dlg, tsx, tdata); - - /* Set the state */ - if (status == PJ_SUCCESS) { - set_state(sub, new_state, new_state_str, event, - &sub_state->reason_param); - } else { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_str_t reason; - - reason = pj_strerror(status, errmsg, sizeof(errmsg)); - set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, NULL, event, - &reason); - } + /* Incoming NOTIFY. + * This can be the result of: + * - Initial subscription response + * - UAS updating the resource info. + * - Unsubscription response. + */ + int st_code = 200; + pj_str_t *st_text = NULL; + pjsip_hdr res_hdr; + pjsip_msg_body *body = NULL; + + pjsip_rx_data *rdata; + pjsip_msg *msg; + pjsip_sub_state_hdr *sub_state; + + pjsip_evsub_state new_state; + pj_str_t *new_state_str; + + pjsip_tx_data *tdata; + pj_status_t status; + + /* Only want to handle initial NOTIFY receive event. */ + if (tsx->state != PJSIP_TSX_STATE_TRYING) + return; + + + rdata = event->body.tsx_state.src.rdata; + msg = rdata->msg_info.msg; + + pj_list_init(&res_hdr); + + /* Get subscription state header. */ + sub_state = (pjsip_sub_state_hdr*) + pjsip_msg_find_hdr_by_name(msg, &STR_SUB_STATE, NULL); + if (sub_state == NULL) { + + pjsip_warning_hdr *warn_hdr; + pj_str_t warn_text = { "Missing Subscription-State header", 33}; + + /* Bad request! Add warning header. */ + st_code = PJSIP_SC_BAD_REQUEST; + warn_hdr = pjsip_warning_hdr_create(rdata->tp_info.pool, 399, + pjsip_endpt_name(sub->endpt), + &warn_text); + pj_list_push_back(&res_hdr, warn_hdr); + } + + /* Call application registered callback to handle incoming NOTIFY, + * if any. + */ + if (st_code==200 && sub->user.on_rx_notify && sub->call_cb) { + (*sub->user.on_rx_notify)(sub, rdata, &st_code, &st_text, + &res_hdr, &body); + + /* Application MUST specify final response! */ + PJ_ASSERT_ON_FAIL(st_code >= 200, {st_code=200; }); + + /* Must be a valid status code */ + PJ_ASSERT_ON_FAIL(st_code <= 699, {st_code=500; }); + } + + + /* If non-2xx should be returned, then send the response. + * No need to update server subscription state. + */ + if (st_code >= 300) { + status = create_response(sub, rdata, st_code, st_text, &res_hdr, + body, &tdata); + if (status == PJ_SUCCESS) { + status = pjsip_dlg_send_response(sub->dlg, tsx, tdata); + } + + /* Start timer to terminate subscription, just in case server + * is not able to generate NOTIFY to our response. + */ + if (status == PJ_SUCCESS) { + unsigned timeout = TIME_UAC_WAIT_NOTIFY; + set_timer(sub, TIMER_TYPE_UAC_WAIT_NOTIFY, timeout); + } else { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_str_t reason; + + reason = pj_strerror(status, errmsg, sizeof(errmsg)); + set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, NULL, NULL, + &reason); + } + + return; + } + + /* Update expiration from the value of expires param in + * Subscription-State header, but ONLY when subscription state + * is "active" or "pending", AND the header contains expires param. + */ + if (sub->expires->ivalue != 0 && + sub_state->expires_param != PJSIP_EXPIRES_NOT_SPECIFIED && + (pj_stricmp(&sub_state->sub_state, &STR_ACTIVE)==0 || + pj_stricmp(&sub_state->sub_state, &STR_PENDING)==0)) + { + unsigned next_refresh = sub_state->expires_param; + unsigned timeout; + + update_expires(sub, next_refresh); + + /* Start UAC refresh timer, only when we're not unsubscribing */ + timeout = (next_refresh > TIME_UAC_REFRESH) ? + next_refresh - TIME_UAC_REFRESH : next_refresh; + + PJ_LOG(5,(sub->obj_name, "Will refresh in %d seconds", timeout)); + set_timer(sub, TIMER_TYPE_UAC_REFRESH, timeout); + } + + /* Find out the state */ + get_hdr_state(sub_state, &new_state, &new_state_str); + + /* Send response. */ + status = create_response(sub, rdata, st_code, st_text, &res_hdr, + body, &tdata); + if (status == PJ_SUCCESS) + status = pjsip_dlg_send_response(sub->dlg, tsx, tdata); + + /* Set the state */ + if (status == PJ_SUCCESS) { + set_state(sub, new_state, new_state_str, event, + &sub_state->reason_param); + } else { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_str_t reason; + + reason = pj_strerror(status, errmsg, sizeof(errmsg)); + set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, NULL, event, + &reason); + } } else { - /* - * Unexpected method! - */ - PJ_LOG(4,(sub->obj_name, "Unexpected transaction method %.*s", - (int)tsx->method.name.slen, tsx->method.name.ptr)); + /* + * Unexpected method! + */ + PJ_LOG(4,(sub->obj_name, "Unexpected transaction method %.*s", + (int)tsx->method.name.slen, tsx->method.name.ptr)); } } @@ -2083,225 +2082,225 @@ static void on_tsx_state_uac( pjsip_evsub *sub, pjsip_transaction *tsx, * Transaction event processing by UAS, after subscription is accepted. */ static void on_tsx_state_uas( pjsip_evsub *sub, pjsip_transaction *tsx, - pjsip_event *event) + pjsip_event *event) { if (pjsip_method_cmp(&tsx->method, &sub->method) == 0 || - pjsip_method_cmp(&tsx->method, &pjsip_subscribe_method) == 0) + pjsip_method_cmp(&tsx->method, &pjsip_subscribe_method) == 0) { - - /* - * Incoming request (e.g. SUBSCRIBE or REFER) to refresh subsciption. - * - */ - pjsip_rx_data *rdata; - pjsip_event_hdr *event_hdr; - pjsip_expires_hdr *expires; - pjsip_msg *msg; - pjsip_tx_data *tdata; - int st_code = 200; - pj_str_t *st_text = NULL; - pjsip_hdr res_hdr; - pjsip_msg_body *body = NULL; - pjsip_evsub_state old_state; - pj_str_t old_state_str; - pj_str_t reason = { NULL, 0 }; - pj_status_t status; - - - /* Only wants to handle the first event when the request is - * received. - */ - if (tsx->state != PJSIP_TSX_STATE_TRYING) - return; - - rdata = event->body.tsx_state.src.rdata; - msg = rdata->msg_info.msg; - - /* Set expiration time based on client request (in Expires header), - * or package default expiration time. - */ - event_hdr = (pjsip_event_hdr*) - pjsip_msg_find_hdr_by_names(msg, &STR_EVENT, - &STR_EVENT, NULL); - expires = (pjsip_expires_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_EXPIRES, NULL); - if (event_hdr && expires) { - struct evpkg *evpkg; - - evpkg = find_pkg(&event_hdr->event_type); - if (evpkg) { - if (expires->ivalue < evpkg->pkg_expires) - sub->expires->ivalue = expires->ivalue; - else - sub->expires->ivalue = evpkg->pkg_expires; - } - } - - /* Update time (before calling on_rx_refresh, since application - * will send NOTIFY. - */ - update_expires(sub, sub->expires->ivalue); - - - /* Save old state. - * If application respond with non-2xx, revert to old state. - * But if subscriber wants to unsubscribe, there is no - * turning back. - */ - old_state = sub->state; - old_state_str = sub->state_str; - - /* Must set this before calling set_state(), to prevent evsub - * from being destroyed. - */ - sub->calling_on_rx_refresh = PJ_TRUE; - - if (sub->expires->ivalue == 0) { - pj_str_t timeout = { "timeout", 7}; - - PJ_LOG(4,(sub->obj_name, "Receiving unsubscription request " - "(Expires=0).")); - set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, NULL, event, - &timeout); - } else if (sub->state == PJSIP_EVSUB_STATE_NULL) { - sub->state = PJSIP_EVSUB_STATE_ACCEPTED; - sub->state_str = evsub_state_names[sub->state]; - } - - /* Call application's on_rx_refresh, just in case it wants to send - * response other than 200 (OK) - */ - pj_list_init(&res_hdr); - - if (sub->user.on_rx_refresh && sub->call_cb) { - (*sub->user.on_rx_refresh)(sub, rdata, &st_code, &st_text, - &res_hdr, &body); - /* We shouldn't fail an unsubscription request, should we? */ - if (sub->expires->ivalue == 0) st_code = 200; - } - sub->calling_on_rx_refresh = PJ_FALSE; - - /* Application MUST specify final response! */ - PJ_ASSERT_ON_FAIL(st_code >= 200, {st_code=200; }); - - /* Must be a valid status code */ - PJ_ASSERT_ON_FAIL(st_code <= 699, {st_code=500; }); - - - /* Create and send response */ - status = create_response(sub, rdata, st_code, st_text, &res_hdr, - body, &tdata); - if (status == PJ_SUCCESS) { - /* Add expires header: */ - pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, - sub->expires)); - - /* Send */ - status = pjsip_dlg_send_response(sub->dlg, tsx, tdata); - } - - /* Update state or revert state */ - if (st_code/100==2) { - - if (sub->state == PJSIP_EVSUB_STATE_NULL) { - set_state(sub, sub->state, NULL, event, &reason); - } - - /* Set UAS timeout timer, when state is not terminated. */ - if (sub->state != PJSIP_EVSUB_STATE_TERMINATED) { - PJ_LOG(5,(sub->obj_name, "UAS timeout in %d seconds", - sub->expires->ivalue)); - set_timer(sub, TIMER_TYPE_UAS_TIMEOUT, - sub->expires->ivalue); - } - - } else { - sub->state = old_state; - sub->state_str = old_state_str; - } - - /* Send the pending NOTIFY sent by app from inside - * on_rx_refresh() callback. - */ - pj_assert(sub->pending_notify); - status = pjsip_evsub_send_request(sub, sub->pending_notify); - sub->pending_notify = NULL; + + /* + * Incoming request (e.g. SUBSCRIBE or REFER) to refresh subsciption. + * + */ + pjsip_rx_data *rdata; + pjsip_event_hdr *event_hdr; + pjsip_expires_hdr *expires; + pjsip_msg *msg; + pjsip_tx_data *tdata; + int st_code = 200; + pj_str_t *st_text = NULL; + pjsip_hdr res_hdr; + pjsip_msg_body *body = NULL; + pjsip_evsub_state old_state; + pj_str_t old_state_str; + pj_str_t reason = { NULL, 0 }; + pj_status_t status; + + + /* Only wants to handle the first event when the request is + * received. + */ + if (tsx->state != PJSIP_TSX_STATE_TRYING) + return; + + rdata = event->body.tsx_state.src.rdata; + msg = rdata->msg_info.msg; + + /* Set expiration time based on client request (in Expires header), + * or package default expiration time. + */ + event_hdr = (pjsip_event_hdr*) + pjsip_msg_find_hdr_by_names(msg, &STR_EVENT, + &STR_EVENT, NULL); + expires = (pjsip_expires_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_EXPIRES, NULL); + if (event_hdr && expires) { + struct evpkg *evpkg; + + evpkg = find_pkg(&event_hdr->event_type); + if (evpkg) { + if (expires->ivalue < evpkg->pkg_expires) + sub->expires->ivalue = expires->ivalue; + else + sub->expires->ivalue = evpkg->pkg_expires; + } + } + + /* Update time (before calling on_rx_refresh, since application + * will send NOTIFY. + */ + update_expires(sub, sub->expires->ivalue); + + + /* Save old state. + * If application respond with non-2xx, revert to old state. + * But if subscriber wants to unsubscribe, there is no + * turning back. + */ + old_state = sub->state; + old_state_str = sub->state_str; + + /* Must set this before calling set_state(), to prevent evsub + * from being destroyed. + */ + sub->calling_on_rx_refresh = PJ_TRUE; + + if (sub->expires->ivalue == 0) { + pj_str_t timeout = { "timeout", 7}; + + PJ_LOG(4,(sub->obj_name, "Receiving unsubscription request " + "(Expires=0).")); + set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, NULL, event, + &timeout); + } else if (sub->state == PJSIP_EVSUB_STATE_NULL) { + sub->state = PJSIP_EVSUB_STATE_ACCEPTED; + sub->state_str = evsub_state_names[sub->state]; + } + + /* Call application's on_rx_refresh, just in case it wants to send + * response other than 200 (OK) + */ + pj_list_init(&res_hdr); + + if (sub->user.on_rx_refresh && sub->call_cb) { + (*sub->user.on_rx_refresh)(sub, rdata, &st_code, &st_text, + &res_hdr, &body); + /* We shouldn't fail an unsubscription request, should we? */ + if (sub->expires->ivalue == 0) st_code = 200; + } + sub->calling_on_rx_refresh = PJ_FALSE; + + /* Application MUST specify final response! */ + PJ_ASSERT_ON_FAIL(st_code >= 200, {st_code=200; }); + + /* Must be a valid status code */ + PJ_ASSERT_ON_FAIL(st_code <= 699, {st_code=500; }); + + + /* Create and send response */ + status = create_response(sub, rdata, st_code, st_text, &res_hdr, + body, &tdata); + if (status == PJ_SUCCESS) { + /* Add expires header: */ + pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, + sub->expires)); + + /* Send */ + status = pjsip_dlg_send_response(sub->dlg, tsx, tdata); + } + + /* Update state or revert state */ + if (st_code/100==2) { + + if (sub->state == PJSIP_EVSUB_STATE_NULL) { + set_state(sub, sub->state, NULL, event, &reason); + } + + /* Set UAS timeout timer, when state is not terminated. */ + if (sub->state != PJSIP_EVSUB_STATE_TERMINATED) { + PJ_LOG(5,(sub->obj_name, "UAS timeout in %d seconds", + sub->expires->ivalue)); + set_timer(sub, TIMER_TYPE_UAS_TIMEOUT, + sub->expires->ivalue); + } + + } else { + sub->state = old_state; + sub->state_str = old_state_str; + } + + /* Send the pending NOTIFY sent by app from inside + * on_rx_refresh() callback. + */ + pj_assert(sub->pending_notify); + status = pjsip_evsub_send_request(sub, sub->pending_notify); + sub->pending_notify = NULL; } else if (pjsip_method_cmp(&tsx->method, &pjsip_notify_method)==0) { - /* Handle authentication */ - if (tsx->state == PJSIP_TSX_STATE_COMPLETED && - (tsx->status_code==401 || tsx->status_code==407)) - { - pjsip_tx_data *tdata; - pj_status_t status; - pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; - - /* Handled by other module already (e.g: invite module) */ - if (tsx->last_tx->auth_retry) - return; - - status = pjsip_auth_clt_reinit_req(&sub->dlg->auth_sess, rdata, - tsx->last_tx, &tdata); - if (status == PJ_SUCCESS) - status = pjsip_dlg_send_request(sub->dlg, tdata, -1, NULL); - - if (status != PJ_SUCCESS) { - /* Can't authenticate. Terminate session (?) */ - set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, NULL, NULL, - &tsx->status_text); - } - return; - - } - - if (sub->state == PJSIP_EVSUB_STATE_TERMINATED) - return; - - /* NOTIFY failure check */ - if (tsx->status_code/100 != 2) { - pj_bool_t should_terminate_sub = PJ_FALSE; - - if (event->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - if (tsx->status_code == 481) { - should_terminate_sub = PJ_TRUE; - } else { - pjsip_retry_after_hdr *retry_after; - pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; - pjsip_msg *msg = rdata->msg_info.msg; - - retry_after = (pjsip_retry_after_hdr*) - pjsip_msg_find_hdr_by_name(msg, &STR_RETRY_AFTER, NULL); - - if (!retry_after) { - should_terminate_sub = PJ_TRUE; - } - } - } else if (event->body.tsx_state.type == PJSIP_EVENT_TIMER) { - if (tsx->status_code == 408) { - should_terminate_sub = PJ_TRUE; - } - } - - /* - * Terminate event usage if we receive non 2xx without retry_after - * parameter, 481, 408 responses. - */ - if (should_terminate_sub) { - set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, NULL, event, - &tsx->status_text); - return; - } - } + /* Handle authentication */ + if (tsx->state == PJSIP_TSX_STATE_COMPLETED && + (tsx->status_code==401 || tsx->status_code==407)) + { + pjsip_tx_data *tdata; + pj_status_t status; + pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; + + /* Handled by other module already (e.g: invite module) */ + if (tsx->last_tx->auth_retry) + return; + + status = pjsip_auth_clt_reinit_req(&sub->dlg->auth_sess, rdata, + tsx->last_tx, &tdata); + if (status == PJ_SUCCESS) + status = pjsip_dlg_send_request(sub->dlg, tdata, -1, NULL); + + if (status != PJ_SUCCESS) { + /* Can't authenticate. Terminate session (?) */ + set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, NULL, NULL, + &tsx->status_text); + } + return; + + } + + if (sub->state == PJSIP_EVSUB_STATE_TERMINATED) + return; + + /* NOTIFY failure check */ + if (tsx->status_code/100 != 2) { + pj_bool_t should_terminate_sub = PJ_FALSE; + + if (event->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { + if (tsx->status_code == 481) { + should_terminate_sub = PJ_TRUE; + } else { + pjsip_retry_after_hdr *retry_after; + pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; + pjsip_msg *msg = rdata->msg_info.msg; + + retry_after = (pjsip_retry_after_hdr*) + pjsip_msg_find_hdr_by_name(msg, &STR_RETRY_AFTER, NULL); + + if (!retry_after) { + should_terminate_sub = PJ_TRUE; + } + } + } else if (event->body.tsx_state.type == PJSIP_EVENT_TIMER) { + if (tsx->status_code == 408) { + should_terminate_sub = PJ_TRUE; + } + } + + /* + * Terminate event usage if we receive non 2xx without retry_after + * parameter, 481, 408 responses. + */ + if (should_terminate_sub) { + set_state(sub, PJSIP_EVSUB_STATE_TERMINATED, NULL, event, + &tsx->status_text); + return; + } + } } else { - /* - * Unexpected method! - */ - PJ_LOG(4,(sub->obj_name, "Unexpected transaction method %.*s", - (int)tsx->method.name.slen, tsx->method.name.ptr)); + /* + * Unexpected method! + */ + PJ_LOG(4,(sub->obj_name, "Unexpected transaction method %.*s", + (int)tsx->method.name.slen, tsx->method.name.ptr)); } } @@ -2315,36 +2314,36 @@ static void mod_evsub_on_tsx_state(pjsip_transaction *tsx, pjsip_event *event) pjsip_evsub *sub = pjsip_tsx_get_evsub(tsx); if (sub == NULL) { - sub = on_new_transaction(tsx, event); - if (sub == NULL) - return; + sub = on_new_transaction(tsx, event); + if (sub == NULL) + return; } /* Call on_tsx_state callback, if any. */ if (sub->user.on_tsx_state && sub->call_cb) - (*sub->user.on_tsx_state)(sub, tsx, event); + (*sub->user.on_tsx_state)(sub, tsx, event); /* Process the event: */ if (sub->role == PJSIP_ROLE_UAC) { - on_tsx_state_uac(sub, tsx, event); + on_tsx_state_uac(sub, tsx, event); } else { - on_tsx_state_uas(sub, tsx, event); + on_tsx_state_uas(sub, tsx, event); } /* Check transaction TERMINATE event */ if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - --sub->pending_tsx; + --sub->pending_tsx; - if (sub->state == PJSIP_EVSUB_STATE_TERMINATED && - sub->pending_tsx == 0) - { - evsub_destroy(sub); - } + if (sub->state == PJSIP_EVSUB_STATE_TERMINATED && + sub->pending_tsx == 0) + { + evsub_destroy(sub); + } } } diff --git a/pjsip/src/pjsip-simple/evsub_msg.c b/pjsip/src/pjsip-simple/evsub_msg.c index cf8ed2f39a..b34ecae3b9 100644 --- a/pjsip/src/pjsip-simple/evsub_msg.c +++ b/pjsip/src/pjsip-simple/evsub_msg.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,11 +28,11 @@ * Event header. */ static int pjsip_event_hdr_print( pjsip_event_hdr *hdr, - char *buf, pj_size_t size); + char *buf, pj_size_t size); static pjsip_event_hdr* pjsip_event_hdr_clone( pj_pool_t *pool, - const pjsip_event_hdr *hdr); + const pjsip_event_hdr *hdr); static pjsip_event_hdr* pjsip_event_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_event_hdr*); + const pjsip_event_hdr*); static pjsip_hdr_vptr event_hdr_vptr = { @@ -58,7 +57,7 @@ PJ_DEF(pjsip_event_hdr*) pjsip_event_hdr_create(pj_pool_t *pool) } static int pjsip_event_hdr_print( pjsip_event_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { char *p = buf; char *endbuf = buf+size; @@ -73,17 +72,17 @@ static int pjsip_event_hdr_print( pjsip_event_hdr *hdr, copy_advance_pair(p, ";id=", 4, hdr->id_param); printed = pjsip_param_print_on(&hdr->other_param, p, endbuf-p, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, ';'); + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ';'); if (printed < 0) - return (int)printed; + return (int)printed; p += printed; return (int)(p - buf); } static pjsip_event_hdr* pjsip_event_hdr_clone( pj_pool_t *pool, - const pjsip_event_hdr *rhs) + const pjsip_event_hdr *rhs) { pjsip_event_hdr *hdr = pjsip_event_hdr_create(pool); pj_strdup(pool, &hdr->event_type, &rhs->event_type); @@ -94,7 +93,7 @@ static pjsip_event_hdr* pjsip_event_hdr_clone( pj_pool_t *pool, static pjsip_event_hdr* pjsip_event_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_event_hdr *rhs ) + const pjsip_event_hdr *rhs ) { pjsip_event_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_event_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -114,8 +113,8 @@ PJ_DEF(pjsip_allow_events_hdr*) pjsip_allow_events_hdr_create(pj_pool_t *pool) hdr = pjsip_generic_array_hdr_create(pool, &STR_ALLOW_EVENTS); if (hdr) { - hdr->sname.ptr = "u"; - hdr->sname.slen = 1; + hdr->sname.ptr = "u"; + hdr->sname.slen = 1; } return hdr; @@ -126,13 +125,13 @@ PJ_DEF(pjsip_allow_events_hdr*) pjsip_allow_events_hdr_create(pj_pool_t *pool) * Subscription-State header. */ static int pjsip_sub_state_hdr_print(pjsip_sub_state_hdr *hdr, - char *buf, pj_size_t size); + char *buf, pj_size_t size); static pjsip_sub_state_hdr* pjsip_sub_state_hdr_clone(pj_pool_t *pool, - const pjsip_sub_state_hdr *hdr); + const pjsip_sub_state_hdr *hdr); static pjsip_sub_state_hdr* pjsip_sub_state_hdr_shallow_clone(pj_pool_t *pool, - const pjsip_sub_state_hdr*); + const pjsip_sub_state_hdr*); static pjsip_hdr_vptr sub_state_hdr_vptr = { @@ -157,7 +156,7 @@ PJ_DEF(pjsip_sub_state_hdr*) pjsip_sub_state_hdr_create(pj_pool_t *pool) } static int pjsip_sub_state_hdr_print(pjsip_sub_state_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { char *p = buf; char *endbuf = buf+size; @@ -170,26 +169,26 @@ static int pjsip_sub_state_hdr_print(pjsip_sub_state_hdr *hdr, copy_advance_escape(p, hdr->sub_state, pc->pjsip_TOKEN_SPEC); copy_advance_pair_escape(p, ";reason=", 8, hdr->reason_param, - pc->pjsip_TOKEN_SPEC); + pc->pjsip_TOKEN_SPEC); if (hdr->expires_param != PJSIP_EXPIRES_NOT_SPECIFIED) { - pj_memcpy(p, ";expires=", 9); - p += 9; - printed = pj_utoa(hdr->expires_param, p); - p += printed; + pj_memcpy(p, ";expires=", 9); + p += 9; + printed = pj_utoa(hdr->expires_param, p); + p += printed; } if (hdr->retry_after >= 0) { - pj_memcpy(p, ";retry-after=", 13); - p += 13; - printed = pj_utoa(hdr->retry_after, p); - p += printed; + pj_memcpy(p, ";retry-after=", 13); + p += 13; + printed = pj_utoa(hdr->retry_after, p); + p += printed; } printed = pjsip_param_print_on( &hdr->other_param, p, endbuf-p, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, - ';'); + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, + ';'); if (printed < 0) - return (int)printed; + return (int)printed; p += printed; @@ -198,7 +197,7 @@ static int pjsip_sub_state_hdr_print(pjsip_sub_state_hdr *hdr, static pjsip_sub_state_hdr* pjsip_sub_state_hdr_clone(pj_pool_t *pool, - const pjsip_sub_state_hdr *rhs) + const pjsip_sub_state_hdr *rhs) { pjsip_sub_state_hdr *hdr = pjsip_sub_state_hdr_create(pool); pj_strdup(pool, &hdr->sub_state, &rhs->sub_state); @@ -211,7 +210,7 @@ pjsip_sub_state_hdr_clone(pj_pool_t *pool, static pjsip_sub_state_hdr* pjsip_sub_state_hdr_shallow_clone(pj_pool_t *pool, - const pjsip_sub_state_hdr *rhs) + const pjsip_sub_state_hdr *rhs) { pjsip_sub_state_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_sub_state_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -232,19 +231,19 @@ static pjsip_hdr *parse_hdr_event(pjsip_parse_ctx *ctx) pj_scan_get(ctx->scanner, &pc->pjsip_TOKEN_SPEC, &hdr->event_type); while (*ctx->scanner->curptr == ';') { - pj_str_t pname, pvalue; - - pj_scan_get_char(ctx->scanner); - pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); - - if (pj_stricmp(&pname, &id_param)==0) { - hdr->id_param = pvalue; - } else { - pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); - param->name = pname; - param->value = pvalue; - pj_list_push_back(&hdr->other_param, param); - } + pj_str_t pname, pvalue; + + pj_scan_get_char(ctx->scanner); + pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); + + if (pj_stricmp(&pname, &id_param)==0) { + hdr->id_param = pvalue; + } else { + pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); + param->name = pname; + param->value = pvalue; + pj_list_push_back(&hdr->other_param, param); + } } pjsip_parse_end_hdr_imp( ctx->scanner ); return (pjsip_hdr*)hdr; @@ -257,35 +256,35 @@ static pjsip_hdr* parse_hdr_sub_state( pjsip_parse_ctx *ctx ) { pjsip_sub_state_hdr *hdr = pjsip_sub_state_hdr_create(ctx->pool); const pj_str_t reason = { "reason", 6 }, - expires = { "expires", 7 }, - retry_after = { "retry-after", 11 }; + expires = { "expires", 7 }, + retry_after = { "retry-after", 11 }; const pjsip_parser_const_t *pc = pjsip_parser_const(); pj_scan_get(ctx->scanner, &pc->pjsip_TOKEN_SPEC, &hdr->sub_state); while (*ctx->scanner->curptr == ';') { - pj_str_t pname, pvalue; + pj_str_t pname, pvalue; - pj_scan_get_char(ctx->scanner); - pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); + pj_scan_get_char(ctx->scanner); + pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); - if (pj_stricmp(&pname, &reason) == 0) { - hdr->reason_param = pvalue; + if (pj_stricmp(&pname, &reason) == 0) { + hdr->reason_param = pvalue; - } else if (pj_stricmp(&pname, &expires) == 0) { - hdr->expires_param = pj_strtoul(&pvalue); - if (hdr->expires_param == PJSIP_EXPIRES_NOT_SPECIFIED) - hdr->expires_param--; + } else if (pj_stricmp(&pname, &expires) == 0) { + hdr->expires_param = pj_strtoul(&pvalue); + if (hdr->expires_param == PJSIP_EXPIRES_NOT_SPECIFIED) + hdr->expires_param--; - } else if (pj_stricmp(&pname, &retry_after) == 0) { - hdr->retry_after = pj_strtoul(&pvalue); + } else if (pj_stricmp(&pname, &retry_after) == 0) { + hdr->retry_after = pj_strtoul(&pvalue); - } else { - pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); - param->name = pname; - param->value = pvalue; - pj_list_push_back(&hdr->other_param, param); - } + } else { + pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); + param->name = pname; + param->value = pvalue; + pj_list_push_back(&hdr->other_param, param); + } } pjsip_parse_end_hdr_imp( ctx->scanner ); @@ -298,9 +297,9 @@ static pjsip_hdr* parse_hdr_sub_state( pjsip_parse_ctx *ctx ) PJ_DEF(void) pjsip_evsub_init_parser(void) { pjsip_register_hdr_parser( "Event", "o", - &parse_hdr_event); + &parse_hdr_event); pjsip_register_hdr_parser( "Subscription-State", NULL, - &parse_hdr_sub_state); + &parse_hdr_sub_state); } diff --git a/pjsip/src/pjsip-simple/iscomposing.c b/pjsip/src/pjsip-simple/iscomposing.c index 18fd1f5c0c..f3c4d058a1 100644 --- a/pjsip/src/pjsip-simple/iscomposing.c +++ b/pjsip/src/pjsip-simple/iscomposing.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,13 +30,13 @@ static const pj_str_t STR_MIME_SUBTYPE = { "im-iscomposing+xml", 18 }; /* XML node constants. */ -static const pj_str_t STR_ISCOMPOSING = { "isComposing", 11 }; -static const pj_str_t STR_STATE = { "state", 5 }; -static const pj_str_t STR_ACTIVE = { "active", 6 }; -static const pj_str_t STR_IDLE = { "idle", 4 }; -static const pj_str_t STR_LASTACTIVE = { "lastactive", 10 }; -static const pj_str_t STR_CONTENTTYPE = { "contenttype", 11 }; -static const pj_str_t STR_REFRESH = { "refresh", 7 }; +static const pj_str_t STR_ISCOMPOSING = { "isComposing", 11 }; +static const pj_str_t STR_STATE = { "state", 5 }; +static const pj_str_t STR_ACTIVE = { "active", 6 }; +static const pj_str_t STR_IDLE = { "idle", 4 }; +static const pj_str_t STR_LASTACTIVE = { "lastactive", 10 }; +static const pj_str_t STR_CONTENTTYPE = { "contenttype", 11 }; +static const pj_str_t STR_REFRESH = { "refresh", 7 }; /* XML attributes constants */ @@ -50,10 +49,10 @@ static const pj_str_t STR_XSI_SLOC_VAL = { "urn:ietf:params:xml:ns:im-composin PJ_DEF(pj_xml_node*) pjsip_iscomposing_create_xml( pj_pool_t *pool, - pj_bool_t is_composing, - const pj_time_val *lst_actv, - const pj_str_t *content_tp, - int refresh) + pj_bool_t is_composing, + const pj_time_val *lst_actv, + const pj_str_t *content_tp, + int refresh) { pj_xml_node *doc, *node; pj_xml_attr *attr; @@ -75,30 +74,30 @@ PJ_DEF(pj_xml_node*) pjsip_iscomposing_create_xml( pj_pool_t *pool, /* Add state. */ node = pj_xml_node_new(pool, &STR_STATE); if (is_composing) - node->content = STR_ACTIVE; + node->content = STR_ACTIVE; else - node->content = STR_IDLE; + node->content = STR_IDLE; pj_xml_add_node(doc, node); /* Add lastactive, if any. */ PJ_UNUSED_ARG(lst_actv); //if (!is_composing && lst_actv) { - // PJ_TODO(IMPLEMENT_LAST_ACTIVE_ATTRIBUTE); + // PJ_TODO(IMPLEMENT_LAST_ACTIVE_ATTRIBUTE); //} /* Add contenttype, if any. */ if (content_tp) { - node = pj_xml_node_new(pool, &STR_CONTENTTYPE); - pj_strdup(pool, &node->content, content_tp); - pj_xml_add_node(doc, node); + node = pj_xml_node_new(pool, &STR_CONTENTTYPE); + pj_strdup(pool, &node->content, content_tp); + pj_xml_add_node(doc, node); } /* Add refresh, if any. */ if (is_composing && refresh > 1 && refresh < 3601) { - node = pj_xml_node_new(pool, &STR_REFRESH); - node->content.ptr = (char*) pj_pool_alloc(pool, 10); - node->content.slen = pj_utoa(refresh, node->content.ptr); - pj_xml_add_node(doc, node); + node = pj_xml_node_new(pool, &STR_REFRESH); + node->content.ptr = (char*) pj_pool_alloc(pool, 10); + node->content.slen = pj_utoa(refresh, node->content.ptr); + pj_xml_add_node(doc, node); } /* Done! */ @@ -112,10 +111,10 @@ PJ_DEF(pj_xml_node*) pjsip_iscomposing_create_xml( pj_pool_t *pool, * Function to print XML message body. */ static int xml_print_body( struct pjsip_msg_body *msg_body, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { return pj_xml_print((const pj_xml_node*)msg_body->data, buf, size, - PJ_TRUE); + PJ_TRUE); } @@ -131,18 +130,18 @@ static void* xml_clone_data(pj_pool_t *pool, const void *data, unsigned len) PJ_DEF(pjsip_msg_body*) pjsip_iscomposing_create_body( pj_pool_t *pool, - pj_bool_t is_composing, - const pj_time_val *lst_actv, - const pj_str_t *content_tp, - int refresh) + pj_bool_t is_composing, + const pj_time_val *lst_actv, + const pj_str_t *content_tp, + int refresh) { pj_xml_node *doc; pjsip_msg_body *body; doc = pjsip_iscomposing_create_xml( pool, is_composing, lst_actv, - content_tp, refresh); + content_tp, refresh); if (doc == NULL) - return NULL; + return NULL; body = PJ_POOL_ZALLOC_T(pool, pjsip_msg_body); @@ -160,12 +159,12 @@ PJ_DEF(pjsip_msg_body*) pjsip_iscomposing_create_body( pj_pool_t *pool, PJ_DEF(pj_status_t) pjsip_iscomposing_parse( pj_pool_t *pool, - char *msg, - pj_size_t len, - pj_bool_t *p_is_composing, - pj_str_t **p_last_active, - pj_str_t **p_content_type, - int *p_refresh ) + char *msg, + pj_size_t len, + pj_bool_t *p_is_composing, + pj_str_t **p_last_active, + pj_str_t **p_content_type, + int *p_refresh ) { pj_xml_node *doc, *node; @@ -177,39 +176,39 @@ PJ_DEF(pj_status_t) pjsip_iscomposing_parse( pj_pool_t *pool, /* Parse XML */ doc = pj_xml_parse( pool, msg, len); if (!doc) - return PJLIB_UTIL_EINXML; + return PJLIB_UTIL_EINXML; /* Root document must be "isComposing" */ if (pj_stricmp(&doc->name, &STR_ISCOMPOSING) != 0) - return PJSIP_SIMPLE_EBADISCOMPOSE; + return PJSIP_SIMPLE_EBADISCOMPOSE; /* Get the status. */ if (p_is_composing) { - node = pj_xml_find_node(doc, &STR_STATE); - if (node == NULL) - return PJSIP_SIMPLE_EBADISCOMPOSE; - *p_is_composing = (pj_stricmp(&node->content, &STR_ACTIVE)==0); + node = pj_xml_find_node(doc, &STR_STATE); + if (node == NULL) + return PJSIP_SIMPLE_EBADISCOMPOSE; + *p_is_composing = (pj_stricmp(&node->content, &STR_ACTIVE)==0); } /* Get last active. */ if (p_last_active) { - node = pj_xml_find_node(doc, &STR_LASTACTIVE); - if (node) - *p_last_active = &node->content; + node = pj_xml_find_node(doc, &STR_LASTACTIVE); + if (node) + *p_last_active = &node->content; } /* Get content type */ if (p_content_type) { - node = pj_xml_find_node(doc, &STR_CONTENTTYPE); - if (node) - *p_content_type = &node->content; + node = pj_xml_find_node(doc, &STR_CONTENTTYPE); + if (node) + *p_content_type = &node->content; } /* Get refresh */ if (p_refresh) { - node = pj_xml_find_node(doc, &STR_REFRESH); - if (node) - *p_refresh = pj_strtoul(&node->content); + node = pj_xml_find_node(doc, &STR_REFRESH); + if (node) + *p_refresh = pj_strtoul(&node->content); } return PJ_SUCCESS; diff --git a/pjsip/src/pjsip-simple/mwi.c b/pjsip/src/pjsip-simple/mwi.c index 1799c296bc..8e4e62755d 100644 --- a/pjsip/src/pjsip-simple/mwi.c +++ b/pjsip/src/pjsip-simple/mwi.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,26 +30,26 @@ #include -#define THIS_FILE "mwi.c" +#define THIS_FILE "mwi.c" /* * MWI module (mod-mdi) */ static struct pjsip_module mod_mwi = { - NULL, NULL, /* prev, next. */ - { "mod-mwi", 7 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_DIALOG_USAGE,/* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - NULL, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-mwi", 7 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_DIALOG_USAGE,/* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -59,14 +58,14 @@ static struct pjsip_module mod_mwi = */ typedef struct pjsip_mwi { - pjsip_evsub *sub; /**< Event subscribtion record. */ - pjsip_dialog *dlg; /**< The dialog. */ - pjsip_evsub_user user_cb; /**< The user callback. */ + pjsip_evsub *sub; /**< Event subscribtion record. */ + pjsip_dialog *dlg; /**< The dialog. */ + pjsip_evsub_user user_cb; /**< The user callback. */ /* These are for server subscriptions */ - pj_pool_t *body_pool; /**< Pool to save message body */ - pjsip_media_type mime_type; /**< MIME type of last msg body */ - pj_str_t body; /**< Last sent message body */ + pj_pool_t *body_pool; /**< Pool to save message body */ + pjsip_media_type mime_type; /**< MIME type of last msg body */ + pj_str_t body; /**< Last sent message body */ } pjsip_mwi; @@ -75,19 +74,19 @@ typedef struct pjsip_mwi */ static void mwi_on_evsub_state( pjsip_evsub *sub, pjsip_event *event); static void mwi_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, - pjsip_event *event); + pjsip_event *event); static void mwi_on_evsub_rx_refresh( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body); + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body); static void mwi_on_evsub_rx_notify( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body); + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body); static void mwi_on_evsub_client_refresh(pjsip_evsub *sub); static void mwi_on_evsub_server_timeout(pjsip_evsub *sub); @@ -109,15 +108,15 @@ static pjsip_evsub_user mwi_user = /* * Some static constants. */ -static const pj_str_t STR_EVENT = { "Event", 5 }; -static const pj_str_t STR_MWI = { "message-summary", 15 }; +static const pj_str_t STR_EVENT = { "Event", 5 }; +static const pj_str_t STR_MWI = { "message-summary", 15 }; static const pj_str_t STR_APP_SIMPLE_SMS = { "application/simple-message-summary", 34}; /* * Init mwi module. */ PJ_DEF(pj_status_t) pjsip_mwi_init_module( pjsip_endpoint *endpt, - pjsip_module *mod_evsub) + pjsip_module *mod_evsub) { pj_status_t status; pj_str_t accept[1]; @@ -131,17 +130,17 @@ PJ_DEF(pj_status_t) pjsip_mwi_init_module( pjsip_endpoint *endpt, /* Register to endpoint */ status = pjsip_endpt_register_module(endpt, &mod_mwi); if (status != PJ_SUCCESS) - return status; + return status; accept[0] = STR_APP_SIMPLE_SMS; /* Register event package to event module. */ status = pjsip_evsub_register_pkg( &mod_mwi, &STR_MWI, - PJSIP_MWI_DEFAULT_EXPIRES, - PJ_ARRAY_SIZE(accept), accept); + PJSIP_MWI_DEFAULT_EXPIRES, + PJ_ARRAY_SIZE(accept), accept); if (status != PJ_SUCCESS) { - pjsip_endpt_unregister_module(endpt, &mod_mwi); - return status; + pjsip_endpt_unregister_module(endpt, &mod_mwi); + return status; } return PJ_SUCCESS; @@ -161,9 +160,9 @@ PJ_DEF(pjsip_module*) pjsip_mwi_instance(void) * Create client subscription. */ PJ_DEF(pj_status_t) pjsip_mwi_create_uac( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - unsigned options, - pjsip_evsub **p_evsub ) + const pjsip_evsub_user *user_cb, + unsigned options, + pjsip_evsub **p_evsub ) { pj_status_t status; pjsip_mwi *mwi; @@ -177,16 +176,16 @@ PJ_DEF(pj_status_t) pjsip_mwi_create_uac( pjsip_dialog *dlg, /* Create event subscription */ status = pjsip_evsub_create_uac( dlg, &mwi_user, &STR_MWI, - options, &sub); + options, &sub); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create mwi */ mwi = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_mwi); mwi->dlg = dlg; mwi->sub = sub; if (user_cb) - pj_memcpy(&mwi->user_cb, user_cb, sizeof(pjsip_evsub_user)); + pj_memcpy(&mwi->user_cb, user_cb, sizeof(pjsip_evsub_user)); /* Attach to evsub */ pjsip_evsub_set_mod_data(sub, mod_mwi.id, mwi); @@ -203,9 +202,9 @@ PJ_DEF(pj_status_t) pjsip_mwi_create_uac( pjsip_dialog *dlg, * Create server subscription. */ PJ_DEF(pj_status_t) pjsip_mwi_create_uas( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - pjsip_rx_data *rdata, - pjsip_evsub **p_evsub ) + const pjsip_evsub_user *user_cb, + pjsip_rx_data *rdata, + pjsip_evsub **p_evsub ) { pjsip_accept_hdr *accept; pjsip_event_hdr *event; @@ -219,43 +218,43 @@ PJ_DEF(pj_status_t) pjsip_mwi_create_uas( pjsip_dialog *dlg, /* Must be request message */ PJ_ASSERT_RETURN(rdata->msg_info.msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); /* Check that request is SUBSCRIBE */ PJ_ASSERT_RETURN(pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, - &pjsip_subscribe_method)==0, - PJSIP_SIMPLE_ENOTSUBSCRIBE); + &pjsip_subscribe_method)==0, + PJSIP_SIMPLE_ENOTSUBSCRIBE); /* Check that Event header contains "mwi" */ event = (pjsip_event_hdr*) - pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_EVENT, NULL); + pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_EVENT, NULL); if (!event) { - return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_REQUEST); + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_REQUEST); } if (pj_stricmp(&event->event_type, &STR_MWI) != 0) { - return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_EVENT); + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_EVENT); } /* Check that request contains compatible Accept header. */ accept = (pjsip_accept_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_ACCEPT, NULL); + pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_ACCEPT, NULL); if (accept) { - unsigned i; - for (i=0; icount; ++i) { - if (pj_stricmp(&accept->values[i], &STR_APP_SIMPLE_SMS)==0) { - break; - } - } - - if (i==accept->count) { - /* Nothing is acceptable */ - return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_NOT_ACCEPTABLE); - } + unsigned i; + for (i=0; icount; ++i) { + if (pj_stricmp(&accept->values[i], &STR_APP_SIMPLE_SMS)==0) { + break; + } + } + + if (i==accept->count) { + /* Nothing is acceptable */ + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_NOT_ACCEPTABLE); + } } else { - /* No Accept header. - * Assume client supports "application/simple-message-summary" - */ + /* No Accept header. + * Assume client supports "application/simple-message-summary" + */ } /* Lock dialog */ @@ -265,18 +264,18 @@ PJ_DEF(pj_status_t) pjsip_mwi_create_uas( pjsip_dialog *dlg, /* Create server subscription */ status = pjsip_evsub_create_uas( dlg, &mwi_user, rdata, 0, &sub); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create server mwi subscription */ mwi = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_mwi); mwi->dlg = dlg; mwi->sub = sub; if (user_cb) - pj_memcpy(&mwi->user_cb, user_cb, sizeof(pjsip_evsub_user)); + pj_memcpy(&mwi->user_cb, user_cb, sizeof(pjsip_evsub_user)); pj_ansi_snprintf(obj_name, PJ_MAX_OBJ_NAME, "mwibd%p", dlg->pool); mwi->body_pool = pj_pool_create(dlg->pool->factory, obj_name, - 512, 512, NULL); + 512, 512, NULL); /* Attach to evsub */ pjsip_evsub_set_mod_data(sub, mod_mwi.id, mwi); @@ -294,7 +293,7 @@ PJ_DEF(pj_status_t) pjsip_mwi_create_uas( pjsip_dialog *dlg, * Forcefully terminate mwi. */ PJ_DEF(pj_status_t) pjsip_mwi_terminate( pjsip_evsub *sub, - pj_bool_t notify ) + pj_bool_t notify ) { return pjsip_evsub_terminate(sub, notify); } @@ -303,11 +302,11 @@ PJ_DEF(pj_status_t) pjsip_mwi_terminate( pjsip_evsub *sub, * Create SUBSCRIBE */ PJ_DEF(pj_status_t) pjsip_mwi_initiate( pjsip_evsub *sub, - pj_uint32_t expires, - pjsip_tx_data **p_tdata) + pj_uint32_t expires, + pjsip_tx_data **p_tdata) { return pjsip_evsub_initiate(sub, &pjsip_subscribe_method, expires, - p_tdata); + p_tdata); } @@ -315,9 +314,9 @@ PJ_DEF(pj_status_t) pjsip_mwi_initiate( pjsip_evsub *sub, * Accept incoming subscription. */ PJ_DEF(pj_status_t) pjsip_mwi_accept( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int st_code, - const pjsip_hdr *hdr_list ) + pjsip_rx_data *rdata, + int st_code, + const pjsip_hdr *hdr_list ) { return pjsip_evsub_accept( sub, rdata, st_code, hdr_list ); } @@ -326,7 +325,7 @@ PJ_DEF(pj_status_t) pjsip_mwi_accept( pjsip_evsub *sub, * Create message body and attach it to the (NOTIFY) request. */ static pj_status_t mwi_create_msg_body( pjsip_mwi *mwi, - pjsip_tx_data *tdata) + pjsip_tx_data *tdata) { pjsip_msg_body *body; pj_str_t dup_text; @@ -355,12 +354,12 @@ static pj_status_t mwi_create_msg_body( pjsip_mwi *mwi, * Create NOTIFY */ PJ_DEF(pj_status_t) pjsip_mwi_notify( pjsip_evsub *sub, - pjsip_evsub_state state, - const pj_str_t *state_str, - const pj_str_t *reason, - const pjsip_media_type *mime_type, - const pj_str_t *body, - pjsip_tx_data **p_tdata) + pjsip_evsub_state state, + const pj_str_t *state_str, + const pj_str_t *reason, + const pjsip_media_type *mime_type, + const pj_str_t *body, + pjsip_tx_data **p_tdata) { pjsip_mwi *mwi; pjsip_tx_data *tdata; @@ -379,20 +378,20 @@ PJ_DEF(pj_status_t) pjsip_mwi_notify( pjsip_evsub *sub, /* Create the NOTIFY request. */ status = pjsip_evsub_notify( sub, state, state_str, reason, &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Update the cached message body */ if (mime_type || body) - pj_pool_reset(mwi->body_pool); + pj_pool_reset(mwi->body_pool); if (mime_type) - pjsip_media_type_cp(mwi->body_pool, &mwi->mime_type, mime_type); + pjsip_media_type_cp(mwi->body_pool, &mwi->mime_type, mime_type); if (body) - pj_strdup(mwi->body_pool, &mwi->body, body); + pj_strdup(mwi->body_pool, &mwi->body, body); /* Create message body */ status = mwi_create_msg_body( mwi, tdata ); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Done. */ *p_tdata = tdata; @@ -407,7 +406,7 @@ PJ_DEF(pj_status_t) pjsip_mwi_notify( pjsip_evsub *sub, * Create NOTIFY that reflect current state. */ PJ_DEF(pj_status_t) pjsip_mwi_current_notify( pjsip_evsub *sub, - pjsip_tx_data **p_tdata ) + pjsip_tx_data **p_tdata ) { pjsip_mwi *mwi; pjsip_tx_data *tdata; @@ -426,13 +425,13 @@ PJ_DEF(pj_status_t) pjsip_mwi_current_notify( pjsip_evsub *sub, /* Create the NOTIFY request. */ status = pjsip_evsub_current_notify( sub, &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create message body to reflect the mwi status. */ status = mwi_create_msg_body( mwi, tdata ); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Done. */ *p_tdata = tdata; @@ -447,7 +446,7 @@ PJ_DEF(pj_status_t) pjsip_mwi_current_notify( pjsip_evsub *sub, * Send request. */ PJ_DEF(pj_status_t) pjsip_mwi_send_request( pjsip_evsub *sub, - pjsip_tx_data *tdata ) + pjsip_tx_data *tdata ) { return pjsip_evsub_send_request(sub, tdata); } @@ -464,13 +463,13 @@ static void mwi_on_evsub_state( pjsip_evsub *sub, pjsip_event *event) PJ_ASSERT_ON_FAIL(mwi!=NULL, {return;}); if (mwi->user_cb.on_evsub_state) - (*mwi->user_cb.on_evsub_state)(sub, event); + (*mwi->user_cb.on_evsub_state)(sub, event); if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) { - if (mwi->body_pool) { - pj_pool_release(mwi->body_pool); - mwi->body_pool = NULL; - } + if (mwi->body_pool) { + pj_pool_release(mwi->body_pool); + mwi->body_pool = NULL; + } } } @@ -478,7 +477,7 @@ static void mwi_on_evsub_state( pjsip_evsub *sub, pjsip_event *event) * Called when transaction state has changed. */ static void mwi_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, - pjsip_event *event) + pjsip_event *event) { pjsip_mwi *mwi; @@ -486,7 +485,7 @@ static void mwi_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, PJ_ASSERT_ON_FAIL(mwi!=NULL, {return;}); if (mwi->user_cb.on_tsx_state) - (*mwi->user_cb.on_tsx_state)(sub, tsx, event); + (*mwi->user_cb.on_tsx_state)(sub, tsx, event); } @@ -494,11 +493,11 @@ static void mwi_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, * Called when SUBSCRIBE is received. */ static void mwi_on_evsub_rx_refresh( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body) + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body) { pjsip_mwi *mwi; @@ -506,24 +505,24 @@ static void mwi_on_evsub_rx_refresh( pjsip_evsub *sub, PJ_ASSERT_ON_FAIL(mwi!=NULL, {return;}); if (mwi->user_cb.on_rx_refresh) { - (*mwi->user_cb.on_rx_refresh)(sub, rdata, p_st_code, p_st_text, - res_hdr, p_body); + (*mwi->user_cb.on_rx_refresh)(sub, rdata, p_st_code, p_st_text, + res_hdr, p_body); } else { - /* Implementors MUST send NOTIFY if it implements on_rx_refresh */ - pjsip_tx_data *tdata; - pj_str_t timeout = { "timeout", 7}; - pj_status_t status; - - if (pjsip_evsub_get_state(sub)==PJSIP_EVSUB_STATE_TERMINATED) { - status = pjsip_mwi_notify( sub, PJSIP_EVSUB_STATE_TERMINATED, - NULL, &timeout, NULL, NULL, &tdata); - } else { - status = pjsip_mwi_current_notify(sub, &tdata); - } - - if (status == PJ_SUCCESS) - pjsip_mwi_send_request(sub, tdata); + /* Implementors MUST send NOTIFY if it implements on_rx_refresh */ + pjsip_tx_data *tdata; + pj_str_t timeout = { "timeout", 7}; + pj_status_t status; + + if (pjsip_evsub_get_state(sub)==PJSIP_EVSUB_STATE_TERMINATED) { + status = pjsip_mwi_notify( sub, PJSIP_EVSUB_STATE_TERMINATED, + NULL, &timeout, NULL, NULL, &tdata); + } else { + status = pjsip_mwi_current_notify(sub, &tdata); + } + + if (status == PJ_SUCCESS) + pjsip_mwi_send_request(sub, tdata); } } @@ -532,11 +531,11 @@ static void mwi_on_evsub_rx_refresh( pjsip_evsub *sub, * Called when NOTIFY is received. */ static void mwi_on_evsub_rx_notify( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body) + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body) { pjsip_mwi *mwi; @@ -545,8 +544,8 @@ static void mwi_on_evsub_rx_notify( pjsip_evsub *sub, /* Just notify application. */ if (mwi->user_cb.on_rx_notify) { - (*mwi->user_cb.on_rx_notify)(sub, rdata, p_st_code, p_st_text, - res_hdr, p_body); + (*mwi->user_cb.on_rx_notify)(sub, rdata, p_st_code, p_st_text, + res_hdr, p_body); } } @@ -561,14 +560,14 @@ static void mwi_on_evsub_client_refresh(pjsip_evsub *sub) PJ_ASSERT_ON_FAIL(mwi!=NULL, {return;}); if (mwi->user_cb.on_client_refresh) { - (*mwi->user_cb.on_client_refresh)(sub); + (*mwi->user_cb.on_client_refresh)(sub); } else { - pj_status_t status; - pjsip_tx_data *tdata; + pj_status_t status; + pjsip_tx_data *tdata; - status = pjsip_mwi_initiate(sub, PJSIP_EXPIRES_NOT_SPECIFIED, &tdata); - if (status == PJ_SUCCESS) - pjsip_mwi_send_request(sub, tdata); + status = pjsip_mwi_initiate(sub, PJSIP_EXPIRES_NOT_SPECIFIED, &tdata); + if (status == PJ_SUCCESS) + pjsip_mwi_send_request(sub, tdata); } } @@ -583,16 +582,16 @@ static void mwi_on_evsub_server_timeout(pjsip_evsub *sub) PJ_ASSERT_ON_FAIL(mwi!=NULL, {return;}); if (mwi->user_cb.on_server_timeout) { - (*mwi->user_cb.on_server_timeout)(sub); + (*mwi->user_cb.on_server_timeout)(sub); } else { - pj_status_t status; - pjsip_tx_data *tdata; - pj_str_t reason = { "timeout", 7 }; - - status = pjsip_mwi_notify(sub, PJSIP_EVSUB_STATE_TERMINATED, - NULL, &reason, NULL, NULL, &tdata); - if (status == PJ_SUCCESS) - pjsip_mwi_send_request(sub, tdata); + pj_status_t status; + pjsip_tx_data *tdata; + pj_str_t reason = { "timeout", 7 }; + + status = pjsip_mwi_notify(sub, PJSIP_EVSUB_STATE_TERMINATED, + NULL, &reason, NULL, NULL, &tdata); + if (status == PJ_SUCCESS) + pjsip_mwi_send_request(sub, tdata); } } diff --git a/pjsip/src/pjsip-simple/pidf.c b/pjsip/src/pjsip-simple/pidf.c index b90725d4e4..72a4a46f87 100644 --- a/pjsip/src/pjsip-simple/pidf.c +++ b/pjsip/src/pjsip-simple/pidf.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -26,42 +25,42 @@ struct pjpidf_op_desc pjpidf_op = { { - &pjpidf_pres_construct, - &pjpidf_pres_add_tuple, - &pjpidf_pres_get_first_tuple, - &pjpidf_pres_get_next_tuple, - &pjpidf_pres_find_tuple, - &pjpidf_pres_remove_tuple, - &pjpidf_pres_add_note, - &pjpidf_pres_get_first_note, - &pjpidf_pres_get_next_note + &pjpidf_pres_construct, + &pjpidf_pres_add_tuple, + &pjpidf_pres_get_first_tuple, + &pjpidf_pres_get_next_tuple, + &pjpidf_pres_find_tuple, + &pjpidf_pres_remove_tuple, + &pjpidf_pres_add_note, + &pjpidf_pres_get_first_note, + &pjpidf_pres_get_next_note }, { - &pjpidf_tuple_construct, - &pjpidf_tuple_get_id, - &pjpidf_tuple_set_id, - &pjpidf_tuple_get_status, - &pjpidf_tuple_get_contact, - &pjpidf_tuple_set_contact, - &pjpidf_tuple_set_contact_prio, - &pjpidf_tuple_get_contact_prio, - &pjpidf_tuple_add_note, - &pjpidf_tuple_get_first_note, - &pjpidf_tuple_get_next_note, - &pjpidf_tuple_get_timestamp, - &pjpidf_tuple_set_timestamp, - &pjpidf_tuple_set_timestamp_np + &pjpidf_tuple_construct, + &pjpidf_tuple_get_id, + &pjpidf_tuple_set_id, + &pjpidf_tuple_get_status, + &pjpidf_tuple_get_contact, + &pjpidf_tuple_set_contact, + &pjpidf_tuple_set_contact_prio, + &pjpidf_tuple_get_contact_prio, + &pjpidf_tuple_add_note, + &pjpidf_tuple_get_first_note, + &pjpidf_tuple_get_next_note, + &pjpidf_tuple_get_timestamp, + &pjpidf_tuple_set_timestamp, + &pjpidf_tuple_set_timestamp_np }, { - &pjpidf_status_construct, - &pjpidf_status_is_basic_open, - &pjpidf_status_set_basic_open + &pjpidf_status_construct, + &pjpidf_status_is_basic_open, + &pjpidf_status_set_basic_open } }; static pj_str_t PRESENCE = { "presence", 8 }; static pj_str_t ENTITY = { "entity", 6}; -static pj_str_t TUPLE = { "tuple", 5 }; +static pj_str_t TUPLE = { "tuple", 5 }; static pj_str_t ID = { "id", 2 }; static pj_str_t NOTE = { "note", 4 }; static pj_str_t STATUS = { "status", 6 }; @@ -77,7 +76,7 @@ static pj_str_t XMLNS = { "xmlns", 5 }; static pj_str_t PIDF_XMLNS = { "urn:ietf:params:xml:ns:pidf", 27 }; static void xml_init_node(pj_pool_t *pool, pj_xml_node *node, - pj_str_t *name, const pj_str_t *value) + pj_str_t *name, const pj_str_t *value) { pj_list_init(&node->attr_head); pj_list_init(&node->node_head); @@ -87,7 +86,7 @@ static void xml_init_node(pj_pool_t *pool, pj_xml_node *node, } static pj_xml_attr* xml_create_attr(pj_pool_t *pool, pj_str_t *name, - const pj_str_t *value) + const pj_str_t *value) { pj_xml_attr *attr = PJ_POOL_ALLOC_T(pool, pj_xml_attr); attr->name = *name; @@ -97,7 +96,7 @@ static pj_xml_attr* xml_create_attr(pj_pool_t *pool, pj_str_t *name, /* Presence */ PJ_DEF(void) pjpidf_pres_construct(pj_pool_t *pool, pjpidf_pres *pres, - const pj_str_t *entity) + const pj_str_t *entity) { pj_xml_attr *attr; @@ -109,7 +108,7 @@ PJ_DEF(void) pjpidf_pres_construct(pj_pool_t *pool, pjpidf_pres *pres, } PJ_DEF(pjpidf_tuple*) pjpidf_pres_add_tuple(pj_pool_t *pool, pjpidf_pres *pres, - const pj_str_t *id) + const pj_str_t *id) { pjpidf_tuple *t = PJ_POOL_ALLOC_T(pool, pjpidf_tuple); pjpidf_tuple_construct(pool, t, id); @@ -123,7 +122,7 @@ PJ_DEF(pjpidf_tuple*) pjpidf_pres_get_first_tuple(pjpidf_pres *pres) } PJ_DEF(pjpidf_tuple*) pjpidf_pres_get_next_tuple(pjpidf_pres *pres, - pjpidf_tuple *tuple) + pjpidf_tuple *tuple) { return pj_xml_find_next_node(pres, tuple, &TUPLE); } @@ -145,7 +144,7 @@ PJ_DEF(void) pjpidf_pres_remove_tuple(pjpidf_pres *pres, pjpidf_tuple *t) } PJ_DEF(pjpidf_note*) pjpidf_pres_add_note(pj_pool_t *pool, pjpidf_pres *pres, - const pj_str_t *text) + const pj_str_t *text) { pjpidf_note *note = PJ_POOL_ALLOC_T(pool, pjpidf_note); xml_init_node(pool, note, &NOTE, text); @@ -166,7 +165,7 @@ PJ_DEF(pjpidf_note*) pjpidf_pres_get_next_note(pjpidf_pres *t, pjpidf_note *note /* Tuple */ PJ_DEF(void) pjpidf_tuple_construct(pj_pool_t *pool, pjpidf_tuple *t, - const pj_str_t *id) + const pj_str_t *id) { pj_xml_attr *attr; pjpidf_status *st; @@ -206,40 +205,40 @@ PJ_DEF(const pj_str_t*) pjpidf_tuple_get_contact(const pjpidf_tuple *t) { pj_xml_node *node = pj_xml_find_node((pj_xml_node*)t, &CONTACT); if (!node) - return &EMPTY_STRING; + return &EMPTY_STRING; return &node->content; } PJ_DEF(void) pjpidf_tuple_set_contact(pj_pool_t *pool, pjpidf_tuple *t, - const pj_str_t *contact) + const pj_str_t *contact) { pj_xml_node *node = pj_xml_find_node(t, &CONTACT); if (!node) { - node = PJ_POOL_ALLOC_T(pool, pj_xml_node); - xml_init_node(pool, node, &CONTACT, contact); - pj_xml_add_node(t, node); + node = PJ_POOL_ALLOC_T(pool, pj_xml_node); + xml_init_node(pool, node, &CONTACT, contact); + pj_xml_add_node(t, node); } else { - pj_strdup(pool, &node->content, contact); + pj_strdup(pool, &node->content, contact); } } PJ_DEF(void) pjpidf_tuple_set_contact_prio(pj_pool_t *pool, pjpidf_tuple *t, - const pj_str_t *prio) + const pj_str_t *prio) { pj_xml_node *node = pj_xml_find_node(t, &CONTACT); pj_xml_attr *attr; if (!node) { - node = PJ_POOL_ALLOC_T(pool, pj_xml_node); - xml_init_node(pool, node, &CONTACT, NULL); - pj_xml_add_node(t, node); + node = PJ_POOL_ALLOC_T(pool, pj_xml_node); + xml_init_node(pool, node, &CONTACT, NULL); + pj_xml_add_node(t, node); } attr = pj_xml_find_attr(node, &PRIORITY, NULL); if (!attr) { - attr = xml_create_attr(pool, &PRIORITY, prio); - pj_xml_add_attr(node, attr); + attr = xml_create_attr(pool, &PRIORITY, prio); + pj_xml_add_attr(node, attr); } else { - pj_strdup(pool, &attr->value, prio); + pj_strdup(pool, &attr->value, prio); } } @@ -249,16 +248,16 @@ PJ_DEF(const pj_str_t*) pjpidf_tuple_get_contact_prio(const pjpidf_tuple *t) pj_xml_attr *attr; if (!node) - return &EMPTY_STRING; + return &EMPTY_STRING; attr = pj_xml_find_attr(node, &PRIORITY, NULL); if (!attr) - return &EMPTY_STRING; + return &EMPTY_STRING; return &attr->value; } PJ_DEF(pjpidf_note*) pjpidf_tuple_add_note(pj_pool_t *pool, pjpidf_tuple *t, - const pj_str_t *text) + const pj_str_t *text) { pjpidf_note *note = PJ_POOL_ALLOC_T(pool, pjpidf_note); xml_init_node(pool, note, &NOTE, text); @@ -284,28 +283,28 @@ PJ_DEF(const pj_str_t*) pjpidf_tuple_get_timestamp(const pjpidf_tuple *t) } PJ_DEF(void) pjpidf_tuple_set_timestamp(pj_pool_t *pool, pjpidf_tuple *t, - const pj_str_t *ts) + const pj_str_t *ts) { pj_xml_node *node = pj_xml_find_node(t, &TIMESTAMP); if (!node) { - node = PJ_POOL_ALLOC_T(pool, pj_xml_node); - xml_init_node(pool, node, &TIMESTAMP, ts); - pj_xml_add_node(t, node); + node = PJ_POOL_ALLOC_T(pool, pj_xml_node); + xml_init_node(pool, node, &TIMESTAMP, ts); + pj_xml_add_node(t, node); } else { - pj_strdup(pool, &node->content, ts); + pj_strdup(pool, &node->content, ts); } } PJ_DEF(void) pjpidf_tuple_set_timestamp_np(pj_pool_t *pool, pjpidf_tuple *t, - pj_str_t *ts) + pj_str_t *ts) { pj_xml_node *node = pj_xml_find_node(t, &TIMESTAMP); if (!node) { - node = PJ_POOL_ALLOC_T(pool, pj_xml_node); - xml_init_node(pool, node, &TIMESTAMP, ts); + node = PJ_POOL_ALLOC_T(pool, pj_xml_node); + xml_init_node(pool, node, &TIMESTAMP, ts); } else { - node->content = *ts; + node->content = *ts; } } @@ -325,7 +324,7 @@ PJ_DEF(pj_bool_t) pjpidf_status_is_basic_open(const pjpidf_status *st) { pj_xml_node *node = pj_xml_find_node((pj_xml_node*)st, &BASIC); if (!node) - return PJ_FALSE; + return PJ_FALSE; return pj_stricmp(&node->content, &OPEN)==0; } @@ -333,7 +332,7 @@ PJ_DEF(void) pjpidf_status_set_basic_open(pjpidf_status *st, pj_bool_t open) { pj_xml_node *node = pj_xml_find_node(st, &BASIC); if (node) - node->content = open ? OPEN : CLOSED; + node->content = open ? OPEN : CLOSED; } PJ_DEF(pjpidf_pres*) pjpidf_create(pj_pool_t *pool, const pj_str_t *entity) @@ -347,13 +346,13 @@ PJ_DEF(pjpidf_pres*) pjpidf_parse(pj_pool_t *pool, char *text, int len) { pjpidf_pres *pres = pj_xml_parse(pool, text, len); if (pres && pres->name.slen >= 8) { - pj_str_t name; + pj_str_t name; - name.ptr = pres->name.ptr + (pres->name.slen - 8); - name.slen = 8; + name.ptr = pres->name.ptr + (pres->name.slen - 8); + name.slen = 8; - if (pj_stricmp(&name, &PRESENCE) == 0) - return pres; + if (pj_stricmp(&name, &PRESENCE) == 0) + return pres; } return NULL; } diff --git a/pjsip/src/pjsip-simple/presence.c b/pjsip/src/pjsip-simple/presence.c index faba612965..abc2aee94a 100644 --- a/pjsip/src/pjsip-simple/presence.c +++ b/pjsip/src/pjsip-simple/presence.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,8 +31,8 @@ #include -#define THIS_FILE "presence.c" -#define PRES_DEFAULT_EXPIRES PJSIP_PRES_DEFAULT_EXPIRES +#define THIS_FILE "presence.c" +#define PRES_DEFAULT_EXPIRES PJSIP_PRES_DEFAULT_EXPIRES #if PJSIP_PRES_BAD_CONTENT_RESPONSE < 200 || \ PJSIP_PRES_BAD_CONTENT_RESPONSE > 699 || \ @@ -46,19 +45,19 @@ */ static struct pjsip_module mod_presence = { - NULL, NULL, /* prev, next. */ - { "mod-presence", 12 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_DIALOG_USAGE,/* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - NULL, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-presence", 12 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_DIALOG_USAGE,/* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -77,14 +76,14 @@ typedef enum content_type_e */ struct pjsip_pres { - pjsip_evsub *sub; /**< Event subscribtion record. */ - pjsip_dialog *dlg; /**< The dialog. */ - content_type_e content_type; /**< Content-Type. */ - pj_pool_t *status_pool; /**< Pool for pres_status */ - pjsip_pres_status status; /**< Presence status. */ - pj_pool_t *tmp_pool; /**< Pool for tmp_status */ - pjsip_pres_status tmp_status; /**< Temp, before NOTIFY is answred.*/ - pjsip_evsub_user user_cb; /**< The user callback. */ + pjsip_evsub *sub; /**< Event subscribtion record. */ + pjsip_dialog *dlg; /**< The dialog. */ + content_type_e content_type; /**< Content-Type. */ + pj_pool_t *status_pool; /**< Pool for pres_status */ + pjsip_pres_status status; /**< Presence status. */ + pj_pool_t *tmp_pool; /**< Pool for tmp_status */ + pjsip_pres_status tmp_status; /**< Temp, before NOTIFY is answred.*/ + pjsip_evsub_user user_cb; /**< The user callback. */ }; @@ -96,19 +95,19 @@ typedef struct pjsip_pres pjsip_pres; */ static void pres_on_evsub_state( pjsip_evsub *sub, pjsip_event *event); static void pres_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, - pjsip_event *event); + pjsip_event *event); static void pres_on_evsub_rx_refresh( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body); + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body); static void pres_on_evsub_rx_notify( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body); + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body); static void pres_on_evsub_client_refresh(pjsip_evsub *sub); static void pres_on_evsub_server_timeout(pjsip_evsub *sub); @@ -130,12 +129,12 @@ static pjsip_evsub_user pres_user = /* * Some static constants. */ -static const pj_str_t STR_EVENT = { "Event", 5 }; -static const pj_str_t STR_PRESENCE = { "presence", 8 }; -static const pj_str_t STR_APPLICATION = { "application", 11 }; -static const pj_str_t STR_PIDF_XML = { "pidf+xml", 8}; -static const pj_str_t STR_XPIDF_XML = { "xpidf+xml", 9}; -static const pj_str_t STR_APP_PIDF_XML = { "application/pidf+xml", 20 }; +static const pj_str_t STR_EVENT = { "Event", 5 }; +static const pj_str_t STR_PRESENCE = { "presence", 8 }; +static const pj_str_t STR_APPLICATION = { "application", 11 }; +static const pj_str_t STR_PIDF_XML = { "pidf+xml", 8}; +static const pj_str_t STR_XPIDF_XML = { "xpidf+xml", 9}; +static const pj_str_t STR_APP_PIDF_XML = { "application/pidf+xml", 20 }; static const pj_str_t STR_APP_XPIDF_XML = { "application/xpidf+xml", 21 }; @@ -143,7 +142,7 @@ static const pj_str_t STR_APP_XPIDF_XML = { "application/xpidf+xml", 21 }; * Init presence module. */ PJ_DEF(pj_status_t) pjsip_pres_init_module( pjsip_endpoint *endpt, - pjsip_module *mod_evsub) + pjsip_module *mod_evsub) { pj_status_t status; pj_str_t accept[2]; @@ -157,18 +156,18 @@ PJ_DEF(pj_status_t) pjsip_pres_init_module( pjsip_endpoint *endpt, /* Register to endpoint */ status = pjsip_endpt_register_module(endpt, &mod_presence); if (status != PJ_SUCCESS) - return status; + return status; accept[0] = STR_APP_PIDF_XML; accept[1] = STR_APP_XPIDF_XML; /* Register event package to event module. */ status = pjsip_evsub_register_pkg( &mod_presence, &STR_PRESENCE, - PRES_DEFAULT_EXPIRES, - PJ_ARRAY_SIZE(accept), accept); + PRES_DEFAULT_EXPIRES, + PJ_ARRAY_SIZE(accept), accept); if (status != PJ_SUCCESS) { - pjsip_endpt_unregister_module(endpt, &mod_presence); - return status; + pjsip_endpt_unregister_module(endpt, &mod_presence); + return status; } return PJ_SUCCESS; @@ -188,9 +187,9 @@ PJ_DEF(pjsip_module*) pjsip_pres_instance(void) * Create client subscription. */ PJ_DEF(pj_status_t) pjsip_pres_create_uac( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - unsigned options, - pjsip_evsub **p_evsub ) + const pjsip_evsub_user *user_cb, + unsigned options, + pjsip_evsub **p_evsub ) { pj_status_t status; pjsip_pres *pres; @@ -203,23 +202,23 @@ PJ_DEF(pj_status_t) pjsip_pres_create_uac( pjsip_dialog *dlg, /* Create event subscription */ status = pjsip_evsub_create_uac( dlg, &pres_user, &STR_PRESENCE, - options, &sub); + options, &sub); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create presence */ pres = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_pres); pres->dlg = dlg; pres->sub = sub; if (user_cb) - pj_memcpy(&pres->user_cb, user_cb, sizeof(pjsip_evsub_user)); + pj_memcpy(&pres->user_cb, user_cb, sizeof(pjsip_evsub_user)); pj_ansi_snprintf(obj_name, PJ_MAX_OBJ_NAME, "pres%p", dlg->pool); pres->status_pool = pj_pool_create(dlg->pool->factory, obj_name, - 512, 512, NULL); + 512, 512, NULL); pj_ansi_snprintf(obj_name, PJ_MAX_OBJ_NAME, "tmpres%p", dlg->pool); pres->tmp_pool = pj_pool_create(dlg->pool->factory, obj_name, - 512, 512, NULL); + 512, 512, NULL); /* Attach to evsub */ pjsip_evsub_set_mod_data(sub, mod_presence.id, pres); @@ -236,9 +235,9 @@ PJ_DEF(pj_status_t) pjsip_pres_create_uac( pjsip_dialog *dlg, * Create server subscription. */ PJ_DEF(pj_status_t) pjsip_pres_create_uas( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - pjsip_rx_data *rdata, - pjsip_evsub **p_evsub ) + const pjsip_evsub_user *user_cb, + pjsip_rx_data *rdata, + pjsip_evsub **p_evsub ) { pjsip_accept_hdr *accept; pjsip_event_hdr *event; @@ -253,49 +252,49 @@ PJ_DEF(pj_status_t) pjsip_pres_create_uas( pjsip_dialog *dlg, /* Must be request message */ PJ_ASSERT_RETURN(rdata->msg_info.msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); /* Check that request is SUBSCRIBE */ PJ_ASSERT_RETURN(pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, - &pjsip_subscribe_method)==0, - PJSIP_SIMPLE_ENOTSUBSCRIBE); + &pjsip_subscribe_method)==0, + PJSIP_SIMPLE_ENOTSUBSCRIBE); /* Check that Event header contains "presence" */ event = (pjsip_event_hdr*) - pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_EVENT, NULL); + pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_EVENT, NULL); if (!event) { - return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_REQUEST); + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_REQUEST); } if (pj_stricmp(&event->event_type, &STR_PRESENCE) != 0) { - return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_EVENT); + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_EVENT); } /* Check that request contains compatible Accept header. */ accept = (pjsip_accept_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_ACCEPT, NULL); + pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_ACCEPT, NULL); if (accept) { - unsigned i; - for (i=0; icount; ++i) { - if (pj_stricmp(&accept->values[i], &STR_APP_PIDF_XML)==0) { - content_type = CONTENT_TYPE_PIDF; - break; - } else - if (pj_stricmp(&accept->values[i], &STR_APP_XPIDF_XML)==0) { - content_type = CONTENT_TYPE_XPIDF; - break; - } - } - - if (i==accept->count) { - /* Nothing is acceptable */ - return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_NOT_ACCEPTABLE); - } + unsigned i; + for (i=0; icount; ++i) { + if (pj_stricmp(&accept->values[i], &STR_APP_PIDF_XML)==0) { + content_type = CONTENT_TYPE_PIDF; + break; + } else + if (pj_stricmp(&accept->values[i], &STR_APP_XPIDF_XML)==0) { + content_type = CONTENT_TYPE_XPIDF; + break; + } + } + + if (i==accept->count) { + /* Nothing is acceptable */ + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_NOT_ACCEPTABLE); + } } else { - /* No Accept header. - * Treat as "application/pidf+xml" - */ - content_type = CONTENT_TYPE_PIDF; + /* No Accept header. + * Treat as "application/pidf+xml" + */ + content_type = CONTENT_TYPE_PIDF; } /* Lock dialog */ @@ -305,7 +304,7 @@ PJ_DEF(pj_status_t) pjsip_pres_create_uas( pjsip_dialog *dlg, /* Create server subscription */ status = pjsip_evsub_create_uas( dlg, &pres_user, rdata, 0, &sub); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create server presence subscription */ pres = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_pres); @@ -313,14 +312,14 @@ PJ_DEF(pj_status_t) pjsip_pres_create_uas( pjsip_dialog *dlg, pres->sub = sub; pres->content_type = content_type; if (user_cb) - pj_memcpy(&pres->user_cb, user_cb, sizeof(pjsip_evsub_user)); + pj_memcpy(&pres->user_cb, user_cb, sizeof(pjsip_evsub_user)); pj_ansi_snprintf(obj_name, PJ_MAX_OBJ_NAME, "pres%p", dlg->pool); pres->status_pool = pj_pool_create(dlg->pool->factory, obj_name, - 512, 512, NULL); + 512, 512, NULL); pj_ansi_snprintf(obj_name, PJ_MAX_OBJ_NAME, "tmpres%p", dlg->pool); pres->tmp_pool = pj_pool_create(dlg->pool->factory, obj_name, - 512, 512, NULL); + 512, 512, NULL); /* Attach to evsub */ pjsip_evsub_set_mod_data(sub, mod_presence.id, pres); @@ -338,7 +337,7 @@ PJ_DEF(pj_status_t) pjsip_pres_create_uas( pjsip_dialog *dlg, * Forcefully terminate presence. */ PJ_DEF(pj_status_t) pjsip_pres_terminate( pjsip_evsub *sub, - pj_bool_t notify ) + pj_bool_t notify ) { return pjsip_evsub_terminate(sub, notify); } @@ -347,11 +346,11 @@ PJ_DEF(pj_status_t) pjsip_pres_terminate( pjsip_evsub *sub, * Create SUBSCRIBE */ PJ_DEF(pj_status_t) pjsip_pres_initiate( pjsip_evsub *sub, - pj_uint32_t expires, - pjsip_tx_data **p_tdata) + pj_uint32_t expires, + pjsip_tx_data **p_tdata) { return pjsip_evsub_initiate(sub, &pjsip_subscribe_method, expires, - p_tdata); + p_tdata); } @@ -359,7 +358,7 @@ PJ_DEF(pj_status_t) pjsip_pres_initiate( pjsip_evsub *sub, * Add custom headers. */ PJ_DEF(pj_status_t) pjsip_pres_add_header( pjsip_evsub *sub, - const pjsip_hdr *hdr_list ) + const pjsip_hdr *hdr_list ) { return pjsip_evsub_add_header( sub, hdr_list ); } @@ -369,9 +368,9 @@ PJ_DEF(pj_status_t) pjsip_pres_add_header( pjsip_evsub *sub, * Accept incoming subscription. */ PJ_DEF(pj_status_t) pjsip_pres_accept( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int st_code, - const pjsip_hdr *hdr_list ) + pjsip_rx_data *rdata, + int st_code, + const pjsip_hdr *hdr_list ) { return pjsip_evsub_accept( sub, rdata, st_code, hdr_list ); } @@ -381,7 +380,7 @@ PJ_DEF(pj_status_t) pjsip_pres_accept( pjsip_evsub *sub, * Get presence status. */ PJ_DEF(pj_status_t) pjsip_pres_get_status( pjsip_evsub *sub, - pjsip_pres_status *status ) + pjsip_pres_status *status ) { pjsip_pres *pres; @@ -391,11 +390,11 @@ PJ_DEF(pj_status_t) pjsip_pres_get_status( pjsip_evsub *sub, PJ_ASSERT_RETURN(pres!=NULL, PJSIP_SIMPLE_ENOPRESENCE); if (pres->tmp_status._is_valid) { - PJ_ASSERT_RETURN(pres->tmp_pool!=NULL, PJSIP_SIMPLE_ENOPRESENCE); - pj_memcpy(status, &pres->tmp_status, sizeof(pjsip_pres_status)); + PJ_ASSERT_RETURN(pres->tmp_pool!=NULL, PJSIP_SIMPLE_ENOPRESENCE); + pj_memcpy(status, &pres->tmp_status, sizeof(pjsip_pres_status)); } else { - PJ_ASSERT_RETURN(pres->status_pool!=NULL, PJSIP_SIMPLE_ENOPRESENCE); - pj_memcpy(status, &pres->status, sizeof(pjsip_pres_status)); + PJ_ASSERT_RETURN(pres->status_pool!=NULL, PJSIP_SIMPLE_ENOPRESENCE); + pj_memcpy(status, &pres->status, sizeof(pjsip_pres_status)); } return PJ_SUCCESS; @@ -406,7 +405,7 @@ PJ_DEF(pj_status_t) pjsip_pres_get_status( pjsip_evsub *sub, * Set presence status. */ PJ_DEF(pj_status_t) pjsip_pres_set_status( pjsip_evsub *sub, - const pjsip_pres_status *status ) + const pjsip_pres_status *status ) { unsigned i; pj_pool_t *tmp; @@ -418,30 +417,30 @@ PJ_DEF(pj_status_t) pjsip_pres_set_status( pjsip_evsub *sub, PJ_ASSERT_RETURN(pres!=NULL, PJSIP_SIMPLE_ENOPRESENCE); for (i=0; iinfo_cnt; ++i) { - pres->status.info[i].basic_open = status->info[i].basic_open; - if (pres->status.info[i].id.slen) { - /* Id already set */ - } else if (status->info[i].id.slen == 0) { - pj_create_unique_string(pres->dlg->pool, - &pres->status.info[i].id); - } else { - pj_strdup(pres->dlg->pool, - &pres->status.info[i].id, - &status->info[i].id); - } - pj_strdup(pres->tmp_pool, - &pres->status.info[i].contact, - &status->info[i].contact); - - /* Duplicate */ - pres->status.info[i].rpid.activity = - status->info[i].rpid.activity; - pj_strdup(pres->tmp_pool, - &pres->status.info[i].rpid.id, - &status->info[i].rpid.id); - pj_strdup(pres->tmp_pool, - &pres->status.info[i].rpid.note, - &status->info[i].rpid.note); + pres->status.info[i].basic_open = status->info[i].basic_open; + if (pres->status.info[i].id.slen) { + /* Id already set */ + } else if (status->info[i].id.slen == 0) { + pj_create_unique_string(pres->dlg->pool, + &pres->status.info[i].id); + } else { + pj_strdup(pres->dlg->pool, + &pres->status.info[i].id, + &status->info[i].id); + } + pj_strdup(pres->tmp_pool, + &pres->status.info[i].contact, + &status->info[i].contact); + + /* Duplicate */ + pres->status.info[i].rpid.activity = + status->info[i].rpid.activity; + pj_strdup(pres->tmp_pool, + &pres->status.info[i].rpid.id, + &status->info[i].rpid.id); + pj_strdup(pres->tmp_pool, + &pres->status.info[i].rpid.note, + &status->info[i].rpid.note); } @@ -461,30 +460,30 @@ PJ_DEF(pj_status_t) pjsip_pres_set_status( pjsip_evsub *sub, * Create message body. */ static pj_status_t pres_create_msg_body( pjsip_pres *pres, - pjsip_tx_data *tdata) + pjsip_tx_data *tdata) { pj_str_t entity; /* Get publisher URI */ entity.ptr = (char*) pj_pool_alloc(tdata->pool, PJSIP_MAX_URL_SIZE); entity.slen = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, - pres->dlg->local.info->uri, - entity.ptr, PJSIP_MAX_URL_SIZE); + pres->dlg->local.info->uri, + entity.ptr, PJSIP_MAX_URL_SIZE); if (entity.slen < 1) - return PJ_ENOMEM; + return PJ_ENOMEM; if (pres->content_type == CONTENT_TYPE_PIDF) { - return pjsip_pres_create_pidf(tdata->pool, &pres->status, - &entity, &tdata->msg->body); + return pjsip_pres_create_pidf(tdata->pool, &pres->status, + &entity, &tdata->msg->body); } else if (pres->content_type == CONTENT_TYPE_XPIDF) { - return pjsip_pres_create_xpidf(tdata->pool, &pres->status, - &entity, &tdata->msg->body); + return pjsip_pres_create_xpidf(tdata->pool, &pres->status, + &entity, &tdata->msg->body); } else { - return PJSIP_SIMPLE_EBADCONTENT; + return PJSIP_SIMPLE_EBADCONTENT; } } @@ -493,10 +492,10 @@ static pj_status_t pres_create_msg_body( pjsip_pres *pres, * Create NOTIFY */ PJ_DEF(pj_status_t) pjsip_pres_notify( pjsip_evsub *sub, - pjsip_evsub_state state, - const pj_str_t *state_str, - const pj_str_t *reason, - pjsip_tx_data **p_tdata) + pjsip_evsub_state state, + const pj_str_t *state_str, + const pj_str_t *reason, + pjsip_tx_data **p_tdata) { pjsip_pres *pres; pjsip_tx_data *tdata; @@ -515,7 +514,7 @@ PJ_DEF(pj_status_t) pjsip_pres_notify( pjsip_evsub *sub, * and remote cancels the subscription. */ PJ_ASSERT_RETURN(state==PJSIP_EVSUB_STATE_TERMINATED || - pres->status.info_cnt > 0, PJSIP_SIMPLE_ENOPRESENCEINFO); + pres->status.info_cnt > 0, PJSIP_SIMPLE_ENOPRESENCEINFO); /* Lock object. */ @@ -524,16 +523,16 @@ PJ_DEF(pj_status_t) pjsip_pres_notify( pjsip_evsub *sub, /* Create the NOTIFY request. */ status = pjsip_evsub_notify( sub, state, state_str, reason, &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create message body to reflect the presence status. * Only do this if we have presence status info to send (see above). */ if (pres->status.info_cnt > 0) { - status = pres_create_msg_body( pres, tdata ); - if (status != PJ_SUCCESS) - goto on_return; + status = pres_create_msg_body( pres, tdata ); + if (status != PJ_SUCCESS) + goto on_return; } /* Done. */ @@ -550,7 +549,7 @@ PJ_DEF(pj_status_t) pjsip_pres_notify( pjsip_evsub *sub, * Create NOTIFY that reflect current state. */ PJ_DEF(pj_status_t) pjsip_pres_current_notify( pjsip_evsub *sub, - pjsip_tx_data **p_tdata ) + pjsip_tx_data **p_tdata ) { pjsip_pres *pres; pjsip_tx_data *tdata; @@ -567,7 +566,7 @@ PJ_DEF(pj_status_t) pjsip_pres_current_notify( pjsip_evsub *sub, * to refresh subscription while we're waiting for user authorization. */ //PJ_ASSERT_RETURN(pres->status.info_cnt > 0, - // PJSIP_SIMPLE_ENOPRESENCEINFO); + // PJSIP_SIMPLE_ENOPRESENCEINFO); /* Lock object. */ @@ -576,14 +575,14 @@ PJ_DEF(pj_status_t) pjsip_pres_current_notify( pjsip_evsub *sub, /* Create the NOTIFY request. */ status = pjsip_evsub_current_notify( sub, &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create message body to reflect the presence status. */ if (pres->status.info_cnt > 0) { - status = pres_create_msg_body( pres, tdata ); - if (status != PJ_SUCCESS) - goto on_return; + status = pres_create_msg_body( pres, tdata ); + if (status != PJ_SUCCESS) + goto on_return; } /* Done. */ @@ -600,7 +599,7 @@ PJ_DEF(pj_status_t) pjsip_pres_current_notify( pjsip_evsub *sub, * Send request. */ PJ_DEF(pj_status_t) pjsip_pres_send_request( pjsip_evsub *sub, - pjsip_tx_data *tdata ) + pjsip_tx_data *tdata ) { return pjsip_evsub_send_request(sub, tdata); } @@ -618,17 +617,17 @@ static void pres_on_evsub_state( pjsip_evsub *sub, pjsip_event *event) PJ_ASSERT_ON_FAIL(pres!=NULL, {return;}); if (pres->user_cb.on_evsub_state) - (*pres->user_cb.on_evsub_state)(sub, event); + (*pres->user_cb.on_evsub_state)(sub, event); if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) { - if (pres->status_pool) { - pj_pool_release(pres->status_pool); - pres->status_pool = NULL; - } - if (pres->tmp_pool) { - pj_pool_release(pres->tmp_pool); - pres->tmp_pool = NULL; - } + if (pres->status_pool) { + pj_pool_release(pres->status_pool); + pres->status_pool = NULL; + } + if (pres->tmp_pool) { + pj_pool_release(pres->tmp_pool); + pres->tmp_pool = NULL; + } } } @@ -636,7 +635,7 @@ static void pres_on_evsub_state( pjsip_evsub *sub, pjsip_event *event) * Called when transaction state has changed. */ static void pres_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, - pjsip_event *event) + pjsip_event *event) { pjsip_pres *pres; @@ -644,7 +643,7 @@ static void pres_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, PJ_ASSERT_ON_FAIL(pres!=NULL, {return;}); if (pres->user_cb.on_tsx_state) - (*pres->user_cb.on_tsx_state)(sub, tsx, event); + (*pres->user_cb.on_tsx_state)(sub, tsx, event); } @@ -652,11 +651,11 @@ static void pres_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, * Called when SUBSCRIBE is received. */ static void pres_on_evsub_rx_refresh( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body) + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body) { pjsip_pres *pres; @@ -664,24 +663,24 @@ static void pres_on_evsub_rx_refresh( pjsip_evsub *sub, PJ_ASSERT_ON_FAIL(pres!=NULL, {return;}); if (pres->user_cb.on_rx_refresh) { - (*pres->user_cb.on_rx_refresh)(sub, rdata, p_st_code, p_st_text, - res_hdr, p_body); + (*pres->user_cb.on_rx_refresh)(sub, rdata, p_st_code, p_st_text, + res_hdr, p_body); } else { - /* Implementors MUST send NOTIFY if it implements on_rx_refresh */ - pjsip_tx_data *tdata; - pj_str_t timeout = { "timeout", 7}; - pj_status_t status; - - if (pjsip_evsub_get_state(sub)==PJSIP_EVSUB_STATE_TERMINATED) { - status = pjsip_pres_notify( sub, PJSIP_EVSUB_STATE_TERMINATED, - NULL, &timeout, &tdata); - } else { - status = pjsip_pres_current_notify(sub, &tdata); - } - - if (status == PJ_SUCCESS) - pjsip_pres_send_request(sub, tdata); + /* Implementors MUST send NOTIFY if it implements on_rx_refresh */ + pjsip_tx_data *tdata; + pj_str_t timeout = { "timeout", 7}; + pj_status_t status; + + if (pjsip_evsub_get_state(sub)==PJSIP_EVSUB_STATE_TERMINATED) { + status = pjsip_pres_notify( sub, PJSIP_EVSUB_STATE_TERMINATED, + NULL, &timeout, &tdata); + } else { + status = pjsip_pres_current_notify(sub, &tdata); + } + + if (status == PJ_SUCCESS) + pjsip_pres_send_request(sub, tdata); } } @@ -691,13 +690,13 @@ static void pres_on_evsub_rx_refresh( pjsip_evsub *sub, * status. * * return PJ_SUCCESS if incoming request is acceptable. If return value - * is not PJ_SUCCESS, res_hdr may be added with Warning header. + * is not PJ_SUCCESS, res_hdr may be added with Warning header. */ static pj_status_t pres_process_rx_notify( pjsip_pres *pres, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr) + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr) { const pj_str_t STR_MULTIPART = { "multipart", 9 }; pjsip_ctype_hdr *ctype_hdr; @@ -709,101 +708,101 @@ static pj_status_t pres_process_rx_notify( pjsip_pres *pres, ctype_hdr = rdata->msg_info.ctype; if (ctype_hdr==NULL || rdata->msg_info.msg->body==NULL) { - - pjsip_warning_hdr *warn_hdr; - pj_str_t warn_text; + + pjsip_warning_hdr *warn_hdr; + pj_str_t warn_text; - *p_st_code = PJSIP_SC_BAD_REQUEST; + *p_st_code = PJSIP_SC_BAD_REQUEST; - warn_text = pj_str("Message body is not present"); - warn_hdr = pjsip_warning_hdr_create(rdata->tp_info.pool, 399, - pjsip_endpt_name(pres->dlg->endpt), - &warn_text); - pj_list_push_back(res_hdr, warn_hdr); + warn_text = pj_str("Message body is not present"); + warn_hdr = pjsip_warning_hdr_create(rdata->tp_info.pool, 399, + pjsip_endpt_name(pres->dlg->endpt), + &warn_text); + pj_list_push_back(res_hdr, warn_hdr); - return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_REQUEST); + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_REQUEST); } /* Parse content. */ if (pj_stricmp(&ctype_hdr->media.type, &STR_MULTIPART)==0) { - pjsip_multipart_part *mpart; - pjsip_media_type ctype; - - pjsip_media_type_init(&ctype, (pj_str_t*)&STR_APPLICATION, - (pj_str_t*)&STR_PIDF_XML); - mpart = pjsip_multipart_find_part(rdata->msg_info.msg->body, - &ctype, NULL); - if (mpart) { - status = pjsip_pres_parse_pidf2((char*)mpart->body->data, - mpart->body->len, pres->tmp_pool, - &pres->tmp_status); - } - - if (mpart==NULL) { - pjsip_media_type_init(&ctype, (pj_str_t*)&STR_APPLICATION, - (pj_str_t*)&STR_XPIDF_XML); - mpart = pjsip_multipart_find_part(rdata->msg_info.msg->body, - &ctype, NULL); - if (mpart) { - status = pjsip_pres_parse_xpidf2((char*)mpart->body->data, - mpart->body->len, - pres->tmp_pool, - &pres->tmp_status); - } else { - status = PJSIP_SIMPLE_EBADCONTENT; - } - } + pjsip_multipart_part *mpart; + pjsip_media_type ctype; + + pjsip_media_type_init(&ctype, (pj_str_t*)&STR_APPLICATION, + (pj_str_t*)&STR_PIDF_XML); + mpart = pjsip_multipart_find_part(rdata->msg_info.msg->body, + &ctype, NULL); + if (mpart) { + status = pjsip_pres_parse_pidf2((char*)mpart->body->data, + mpart->body->len, pres->tmp_pool, + &pres->tmp_status); + } + + if (mpart==NULL) { + pjsip_media_type_init(&ctype, (pj_str_t*)&STR_APPLICATION, + (pj_str_t*)&STR_XPIDF_XML); + mpart = pjsip_multipart_find_part(rdata->msg_info.msg->body, + &ctype, NULL); + if (mpart) { + status = pjsip_pres_parse_xpidf2((char*)mpart->body->data, + mpart->body->len, + pres->tmp_pool, + &pres->tmp_status); + } else { + status = PJSIP_SIMPLE_EBADCONTENT; + } + } } else if (pj_stricmp(&ctype_hdr->media.type, &STR_APPLICATION)==0 && - pj_stricmp(&ctype_hdr->media.subtype, &STR_PIDF_XML)==0) + pj_stricmp(&ctype_hdr->media.subtype, &STR_PIDF_XML)==0) { - status = pjsip_pres_parse_pidf( rdata, pres->tmp_pool, - &pres->tmp_status); + status = pjsip_pres_parse_pidf( rdata, pres->tmp_pool, + &pres->tmp_status); } else if (pj_stricmp(&ctype_hdr->media.type, &STR_APPLICATION)==0 && - pj_stricmp(&ctype_hdr->media.subtype, &STR_XPIDF_XML)==0) + pj_stricmp(&ctype_hdr->media.subtype, &STR_XPIDF_XML)==0) { - status = pjsip_pres_parse_xpidf( rdata, pres->tmp_pool, - &pres->tmp_status); + status = pjsip_pres_parse_xpidf( rdata, pres->tmp_pool, + &pres->tmp_status); } else { - status = PJSIP_SIMPLE_EBADCONTENT; + status = PJSIP_SIMPLE_EBADCONTENT; } if (status != PJ_SUCCESS) { - /* Unsupported or bad Content-Type */ - if (PJSIP_PRES_BAD_CONTENT_RESPONSE >= 300) { - pjsip_accept_hdr *accept_hdr; - pjsip_warning_hdr *warn_hdr; - - *p_st_code = PJSIP_PRES_BAD_CONTENT_RESPONSE; - - /* Add Accept header */ - accept_hdr = pjsip_accept_hdr_create(rdata->tp_info.pool); - accept_hdr->values[accept_hdr->count++] = STR_APP_PIDF_XML; - accept_hdr->values[accept_hdr->count++] = STR_APP_XPIDF_XML; - pj_list_push_back(res_hdr, accept_hdr); - - /* Add Warning header */ - warn_hdr = pjsip_warning_hdr_create_from_status( - rdata->tp_info.pool, - pjsip_endpt_name(pres->dlg->endpt), - status); - pj_list_push_back(res_hdr, warn_hdr); - - return status; - } else { - pj_assert(PJSIP_PRES_BAD_CONTENT_RESPONSE/100 == 2); - PJ_PERROR(4,(THIS_FILE, status, - "Ignoring presence error due to " - "PJSIP_PRES_BAD_CONTENT_RESPONSE setting [%d]", - PJSIP_PRES_BAD_CONTENT_RESPONSE)); - *p_st_code = PJSIP_PRES_BAD_CONTENT_RESPONSE; - status = PJ_SUCCESS; - } + /* Unsupported or bad Content-Type */ + if (PJSIP_PRES_BAD_CONTENT_RESPONSE >= 300) { + pjsip_accept_hdr *accept_hdr; + pjsip_warning_hdr *warn_hdr; + + *p_st_code = PJSIP_PRES_BAD_CONTENT_RESPONSE; + + /* Add Accept header */ + accept_hdr = pjsip_accept_hdr_create(rdata->tp_info.pool); + accept_hdr->values[accept_hdr->count++] = STR_APP_PIDF_XML; + accept_hdr->values[accept_hdr->count++] = STR_APP_XPIDF_XML; + pj_list_push_back(res_hdr, accept_hdr); + + /* Add Warning header */ + warn_hdr = pjsip_warning_hdr_create_from_status( + rdata->tp_info.pool, + pjsip_endpt_name(pres->dlg->endpt), + status); + pj_list_push_back(res_hdr, warn_hdr); + + return status; + } else { + pj_assert(PJSIP_PRES_BAD_CONTENT_RESPONSE/100 == 2); + PJ_PERROR(4,(THIS_FILE, status, + "Ignoring presence error due to " + "PJSIP_PRES_BAD_CONTENT_RESPONSE setting [%d]", + PJSIP_PRES_BAD_CONTENT_RESPONSE)); + *p_st_code = PJSIP_PRES_BAD_CONTENT_RESPONSE; + status = PJ_SUCCESS; + } } /* If application calls pres_get_status(), redirect the call to @@ -819,11 +818,11 @@ static pj_status_t pres_process_rx_notify( pjsip_pres *pres, * Called when NOTIFY is received. */ static void pres_on_evsub_rx_notify( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body) + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body) { pjsip_pres *pres; pj_status_t status; @@ -832,44 +831,44 @@ static void pres_on_evsub_rx_notify( pjsip_evsub *sub, PJ_ASSERT_ON_FAIL(pres!=NULL, {return;}); if (rdata->msg_info.msg->body) { - status = pres_process_rx_notify( pres, rdata, p_st_code, p_st_text, - res_hdr ); - if (status != PJ_SUCCESS) - return; + status = pres_process_rx_notify( pres, rdata, p_st_code, p_st_text, + res_hdr ); + if (status != PJ_SUCCESS) + return; } else { #if 1 - /* This is the newest change, https://github.com/pjsip/pjproject/issues/873 - * Some app want to be notified about the empty NOTIFY, e.g. to - * decide whether it should consider the buddy as offline. - * In this case, leave the buddy state unchanged, but set the - * "tuple_node" in pjsip_pres_status to NULL. - */ - unsigned i; - for (i=0; istatus.info_cnt; ++i) { - pres->status.info[i].tuple_node = NULL; - } + /* This is the newest change, https://github.com/pjsip/pjproject/issues/873 + * Some app want to be notified about the empty NOTIFY, e.g. to + * decide whether it should consider the buddy as offline. + * In this case, leave the buddy state unchanged, but set the + * "tuple_node" in pjsip_pres_status to NULL. + */ + unsigned i; + for (i=0; istatus.info_cnt; ++i) { + pres->status.info[i].tuple_node = NULL; + } #elif 0 - /* This has just been changed. Previously, we treat incoming NOTIFY - * with no message body as having the presence subscription closed. - * Now we treat it as no change in presence status (ref: EyeBeam). - */ - *p_st_code = 200; - return; + /* This has just been changed. Previously, we treat incoming NOTIFY + * with no message body as having the presence subscription closed. + * Now we treat it as no change in presence status (ref: EyeBeam). + */ + *p_st_code = 200; + return; #else - unsigned i; - /* Subscription is terminated. Consider contact is offline */ - pres->tmp_status._is_valid = PJ_TRUE; - for (i=0; itmp_status.info_cnt; ++i) - pres->tmp_status.info[i].basic_open = PJ_FALSE; + unsigned i; + /* Subscription is terminated. Consider contact is offline */ + pres->tmp_status._is_valid = PJ_TRUE; + for (i=0; itmp_status.info_cnt; ++i) + pres->tmp_status.info[i].basic_open = PJ_FALSE; #endif } /* Notify application. */ if (pres->user_cb.on_rx_notify) { - (*pres->user_cb.on_rx_notify)(sub, rdata, p_st_code, p_st_text, - res_hdr, p_body); + (*pres->user_cb.on_rx_notify)(sub, rdata, p_st_code, p_st_text, + res_hdr, p_body); } @@ -877,14 +876,14 @@ static void pres_on_evsub_rx_notify( pjsip_evsub *sub, * to main status, and mark the temporary status as invalid. */ if ((*p_st_code)/100 == 2) { - pj_pool_t *tmp; + pj_pool_t *tmp; - pj_memcpy(&pres->status, &pres->tmp_status, sizeof(pjsip_pres_status)); + pj_memcpy(&pres->status, &pres->tmp_status, sizeof(pjsip_pres_status)); - /* Swap the pool */ - tmp = pres->tmp_pool; - pres->tmp_pool = pres->status_pool; - pres->status_pool = tmp; + /* Swap the pool */ + tmp = pres->tmp_pool; + pres->tmp_pool = pres->status_pool; + pres->status_pool = tmp; } pres->tmp_status._is_valid = PJ_FALSE; @@ -904,15 +903,15 @@ static void pres_on_evsub_client_refresh(pjsip_evsub *sub) PJ_ASSERT_ON_FAIL(pres!=NULL, {return;}); if (pres->user_cb.on_client_refresh) { - (*pres->user_cb.on_client_refresh)(sub); + (*pres->user_cb.on_client_refresh)(sub); } else { - pj_status_t status; - pjsip_tx_data *tdata; + pj_status_t status; + pjsip_tx_data *tdata; - status = pjsip_pres_initiate(sub, PJSIP_EXPIRES_NOT_SPECIFIED, - &tdata); - if (status == PJ_SUCCESS) - pjsip_pres_send_request(sub, tdata); + status = pjsip_pres_initiate(sub, PJSIP_EXPIRES_NOT_SPECIFIED, + &tdata); + if (status == PJ_SUCCESS) + pjsip_pres_send_request(sub, tdata); } } @@ -927,16 +926,16 @@ static void pres_on_evsub_server_timeout(pjsip_evsub *sub) PJ_ASSERT_ON_FAIL(pres!=NULL, {return;}); if (pres->user_cb.on_server_timeout) { - (*pres->user_cb.on_server_timeout)(sub); + (*pres->user_cb.on_server_timeout)(sub); } else { - pj_status_t status; - pjsip_tx_data *tdata; - pj_str_t reason = { "timeout", 7 }; - - status = pjsip_pres_notify(sub, PJSIP_EVSUB_STATE_TERMINATED, - NULL, &reason, &tdata); - if (status == PJ_SUCCESS) - pjsip_pres_send_request(sub, tdata); + pj_status_t status; + pjsip_tx_data *tdata; + pj_str_t reason = { "timeout", 7 }; + + status = pjsip_pres_notify(sub, PJSIP_EVSUB_STATE_TERMINATED, + NULL, &reason, &tdata); + if (status == PJ_SUCCESS) + pjsip_pres_send_request(sub, tdata); } } diff --git a/pjsip/src/pjsip-simple/presence_body.c b/pjsip/src/pjsip-simple/presence_body.c index 8c8475535f..d7a14b4eb7 100644 --- a/pjsip/src/pjsip-simple/presence_body.c +++ b/pjsip/src/pjsip-simple/presence_body.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -32,8 +31,8 @@ static const pj_str_t STR_APPLICATION = { "application", 11 }; -static const pj_str_t STR_PIDF_XML = { "pidf+xml", 8 }; -static const pj_str_t STR_XPIDF_XML = { "xpidf+xml", 9 }; +static const pj_str_t STR_PIDF_XML = { "pidf+xml", 8 }; +static const pj_str_t STR_XPIDF_XML = { "xpidf+xml", 9 }; @@ -42,10 +41,10 @@ static const pj_str_t STR_XPIDF_XML = { "xpidf+xml", 9 }; * Function to print XML message body. */ static int pres_print_body(struct pjsip_msg_body *msg_body, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { return pj_xml_print((const pj_xml_node*)msg_body->data, buf, size, - PJ_TRUE); + PJ_TRUE); } @@ -64,9 +63,9 @@ static void* xml_clone_data(pj_pool_t *pool, const void *data, unsigned len) * presence status (pjsip_pres_status). */ PJ_DEF(pj_status_t) pjsip_pres_create_pidf( pj_pool_t *pool, - const pjsip_pres_status *status, - const pj_str_t *entity, - pjsip_msg_body **p_body ) + const pjsip_pres_status *status, + const pj_str_t *entity, + pjsip_msg_body **p_body ) { pjpidf_pres *pidf; pjsip_msg_body *body; @@ -78,74 +77,74 @@ PJ_DEF(pj_status_t) pjsip_pres_create_pidf( pj_pool_t *pool, /* Create */ for (i=0; iinfo_cnt; ++i) { - pjpidf_tuple *pidf_tuple; - pjpidf_status *pidf_status; - pj_str_t id; - - /* Add tuple id. */ - if (status->info[i].id.slen == 0) { - /* xs:ID must start with letter */ - //pj_create_unique_string(pool, &id); - id.ptr = (char*)pj_pool_alloc(pool, pj_GUID_STRING_LENGTH()+2); - id.ptr += 2; - pj_generate_unique_string(&id); - id.ptr -= 2; - id.ptr[0] = 'p'; - id.ptr[1] = 'j'; - id.slen += 2; - } else { - id = status->info[i].id; - } - - pidf_tuple = pjpidf_pres_add_tuple(pool, pidf, &id); - - /* Set */ - if (status->info[i].contact.slen) - pjpidf_tuple_set_contact(pool, pidf_tuple, - &status->info[i].contact); - - - /* Set basic status */ - pidf_status = pjpidf_tuple_get_status(pidf_tuple); - pjpidf_status_set_basic_open(pidf_status, - status->info[i].basic_open); - - /* Add if configured */ + pjpidf_tuple *pidf_tuple; + pjpidf_status *pidf_status; + pj_str_t id; + + /* Add tuple id. */ + if (status->info[i].id.slen == 0) { + /* xs:ID must start with letter */ + //pj_create_unique_string(pool, &id); + id.ptr = (char*)pj_pool_alloc(pool, pj_GUID_STRING_LENGTH()+2); + id.ptr += 2; + pj_generate_unique_string(&id); + id.ptr -= 2; + id.ptr[0] = 'p'; + id.ptr[1] = 'j'; + id.slen += 2; + } else { + id = status->info[i].id; + } + + pidf_tuple = pjpidf_pres_add_tuple(pool, pidf, &id); + + /* Set */ + if (status->info[i].contact.slen) + pjpidf_tuple_set_contact(pool, pidf_tuple, + &status->info[i].contact); + + + /* Set basic status */ + pidf_status = pjpidf_tuple_get_status(pidf_tuple); + pjpidf_status_set_basic_open(pidf_status, + status->info[i].basic_open); + + /* Add if configured */ #if defined(PJSIP_PRES_PIDF_ADD_TIMESTAMP) && PJSIP_PRES_PIDF_ADD_TIMESTAMP - if (PJSIP_PRES_PIDF_ADD_TIMESTAMP) { - char buf[50]; - int tslen = 0; - pj_time_val tv; - pj_parsed_time pt; - pj_status_t s; - - pj_gettimeofday(&tv); - - /* Convert time to GMT (some platforms may not support it - * such as WinCE). - */ - s = pj_time_local_to_gmt(&tv); - if (s != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE,s, - "Warning: failed to convert PIDF time to GMT")); - } - pj_time_decode( &tv, &pt); - - tslen = pj_ansi_snprintf(buf, sizeof(buf), - "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", - pt.year, pt.mon+1, pt.day, - pt.hour, pt.min, pt.sec, pt.msec); - if (tslen > 0 && tslen < (int)sizeof(buf)) { - pj_str_t time = pj_str(buf); - pjpidf_tuple_set_timestamp(pool, pidf_tuple, &time); - } - } + if (PJSIP_PRES_PIDF_ADD_TIMESTAMP) { + char buf[50]; + int tslen = 0; + pj_time_val tv; + pj_parsed_time pt; + pj_status_t s; + + pj_gettimeofday(&tv); + + /* Convert time to GMT (some platforms may not support it + * such as WinCE). + */ + s = pj_time_local_to_gmt(&tv); + if (s != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE,s, + "Warning: failed to convert PIDF time to GMT")); + } + pj_time_decode( &tv, &pt); + + tslen = pj_ansi_snprintf(buf, sizeof(buf), + "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", + pt.year, pt.mon+1, pt.day, + pt.hour, pt.min, pt.sec, pt.msec); + if (tslen > 0 && tslen < (int)sizeof(buf)) { + pj_str_t time = pj_str(buf); + pjpidf_tuple_set_timestamp(pool, pidf_tuple, &time); + } + } #endif } /* Create (RPID) */ if (status->info_cnt) { - pjrpid_add_element(pidf, pool, 0, &status->info[0].rpid); + pjrpid_add_element(pidf, pool, 0, &status->info[0].rpid); } body = PJ_POOL_ZALLOC_T(pool, pjsip_msg_body); @@ -166,9 +165,9 @@ PJ_DEF(pj_status_t) pjsip_pres_create_pidf( pj_pool_t *pool, * presence status (pjsip_pres_status). */ PJ_DEF(pj_status_t) pjsip_pres_create_xpidf( pj_pool_t *pool, - const pjsip_pres_status *status, - const pj_str_t *entity, - pjsip_msg_body **p_body ) + const pjsip_pres_status *status, + const pj_str_t *entity, + pjsip_msg_body **p_body ) { /* Note: PJSIP implementation of XPIDF is not complete! */ @@ -176,16 +175,16 @@ PJ_DEF(pj_status_t) pjsip_pres_create_xpidf( pj_pool_t *pool, pjsip_msg_body *body; PJ_LOG(4,(THIS_FILE, "Warning: XPIDF format is not fully supported " - "by PJSIP")); + "by PJSIP")); /* Create XPIDF document. */ xpidf = pjxpidf_create(pool, entity); /* Set basic status. */ if (status->info_cnt > 0) - pjxpidf_set_status( xpidf, status->info[0].basic_open); + pjxpidf_set_status( xpidf, status->info[0].basic_open); else - pjxpidf_set_status( xpidf, PJ_FALSE); + pjxpidf_set_status( xpidf, PJ_FALSE); body = PJ_POOL_ZALLOC_T(pool, pjsip_msg_body); body->data = xpidf; @@ -205,52 +204,52 @@ PJ_DEF(pj_status_t) pjsip_pres_create_xpidf( pj_pool_t *pool, * This is a utility function to parse PIDF body into PJSIP presence status. */ PJ_DEF(pj_status_t) pjsip_pres_parse_pidf( pjsip_rx_data *rdata, - pj_pool_t *pool, - pjsip_pres_status *pres_status) + pj_pool_t *pool, + pjsip_pres_status *pres_status) { return pjsip_pres_parse_pidf2((char*)rdata->msg_info.msg->body->data, - rdata->msg_info.msg->body->len, - pool, pres_status); + rdata->msg_info.msg->body->len, + pool, pres_status); } PJ_DEF(pj_status_t) pjsip_pres_parse_pidf2(char *body, unsigned body_len, - pj_pool_t *pool, - pjsip_pres_status *pres_status) + pj_pool_t *pool, + pjsip_pres_status *pres_status) { pjpidf_pres *pidf; pjpidf_tuple *pidf_tuple; pidf = pjpidf_parse(pool, body, body_len); if (pidf == NULL) - return PJSIP_SIMPLE_EBADPIDF; + return PJSIP_SIMPLE_EBADPIDF; pres_status->info_cnt = 0; pidf_tuple = pjpidf_pres_get_first_tuple(pidf); while (pidf_tuple && pres_status->info_cnt < PJSIP_PRES_STATUS_MAX_INFO) { - pjpidf_status *pidf_status; + pjpidf_status *pidf_status; - pres_status->info[pres_status->info_cnt].tuple_node = - pj_xml_clone(pool, pidf_tuple); + pres_status->info[pres_status->info_cnt].tuple_node = + pj_xml_clone(pool, pidf_tuple); - pj_strdup(pool, - &pres_status->info[pres_status->info_cnt].id, - pjpidf_tuple_get_id(pidf_tuple)); + pj_strdup(pool, + &pres_status->info[pres_status->info_cnt].id, + pjpidf_tuple_get_id(pidf_tuple)); - pj_strdup(pool, - &pres_status->info[pres_status->info_cnt].contact, - pjpidf_tuple_get_contact(pidf_tuple)); + pj_strdup(pool, + &pres_status->info[pres_status->info_cnt].contact, + pjpidf_tuple_get_contact(pidf_tuple)); - pidf_status = pjpidf_tuple_get_status(pidf_tuple); - if (pidf_status) { - pres_status->info[pres_status->info_cnt].basic_open = - pjpidf_status_is_basic_open(pidf_status); - } else { - pres_status->info[pres_status->info_cnt].basic_open = PJ_FALSE; - } + pidf_status = pjpidf_tuple_get_status(pidf_tuple); + if (pidf_status) { + pres_status->info[pres_status->info_cnt].basic_open = + pjpidf_status_is_basic_open(pidf_status); + } else { + pres_status->info[pres_status->info_cnt].basic_open = PJ_FALSE; + } - pidf_tuple = pjpidf_pres_get_next_tuple( pidf, pidf_tuple ); - pres_status->info_cnt++; + pidf_tuple = pjpidf_pres_get_next_tuple( pidf, pidf_tuple ); + pres_status->info_cnt++; } /* Parse (RPID) */ @@ -264,29 +263,29 @@ PJ_DEF(pj_status_t) pjsip_pres_parse_pidf2(char *body, unsigned body_len, * This is a utility function to parse X-PIDF body into PJSIP presence status. */ PJ_DEF(pj_status_t) pjsip_pres_parse_xpidf(pjsip_rx_data *rdata, - pj_pool_t *pool, - pjsip_pres_status *pres_status) + pj_pool_t *pool, + pjsip_pres_status *pres_status) { return pjsip_pres_parse_xpidf2((char*)rdata->msg_info.msg->body->data, - rdata->msg_info.msg->body->len, - pool, pres_status); + rdata->msg_info.msg->body->len, + pool, pres_status); } PJ_DEF(pj_status_t) pjsip_pres_parse_xpidf2(char *body, unsigned body_len, - pj_pool_t *pool, - pjsip_pres_status *pres_status) + pj_pool_t *pool, + pjsip_pres_status *pres_status) { pjxpidf_pres *xpidf; xpidf = pjxpidf_parse(pool, body, body_len); if (xpidf == NULL) - return PJSIP_SIMPLE_EBADXPIDF; + return PJSIP_SIMPLE_EBADXPIDF; pres_status->info_cnt = 1; pj_strdup(pool, - &pres_status->info[0].contact, - pjxpidf_get_uri(xpidf)); + &pres_status->info[0].contact, + pjxpidf_get_uri(xpidf)); pres_status->info[0].basic_open = pjxpidf_get_status(xpidf); pres_status->info[0].id.slen = 0; pres_status->info[0].tuple_node = NULL; diff --git a/pjsip/src/pjsip-simple/publishc.c b/pjsip/src/pjsip-simple/publishc.c index 48554198e6..a18a32f9ae 100644 --- a/pjsip/src/pjsip-simple/publishc.c +++ b/pjsip/src/pjsip-simple/publishc.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,9 +35,9 @@ #include -#define REFRESH_TIMER 1 -#define DELAY_BEFORE_REFRESH PJSIP_PUBLISHC_DELAY_BEFORE_REFRESH -#define THIS_FILE "publishc.c" +#define REFRESH_TIMER 1 +#define DELAY_BEFORE_REFRESH PJSIP_PUBLISHC_DELAY_BEFORE_REFRESH +#define THIS_FILE "publishc.c" /* Let's define this enum, so that it'll trigger compilation error @@ -62,7 +61,7 @@ const pjsip_method pjsip_publish_method = typedef struct pending_publish { PJ_DECL_LIST_MEMBER(struct pending_publish); - pjsip_tx_data *tdata; + pjsip_tx_data *tdata; } pending_publish; @@ -71,45 +70,45 @@ typedef struct pending_publish */ struct pjsip_publishc { - pj_pool_t *pool; - pjsip_endpoint *endpt; - pj_bool_t _delete_flag; - int pending_tsx; - pj_bool_t in_callback; - pj_mutex_t *mutex; - - pjsip_publishc_opt opt; - void *token; - pjsip_publishc_cb *cb; - - pj_str_t event; - pj_str_t str_target_uri; - pjsip_uri *target_uri; - pjsip_cid_hdr *cid_hdr; - pjsip_cseq_hdr *cseq_hdr; - pj_str_t from_uri; - pjsip_from_hdr *from_hdr; - pjsip_to_hdr *to_hdr; - pj_str_t etag; - pjsip_expires_hdr *expires_hdr; - pj_uint32_t expires; - pjsip_route_hdr route_set; - pjsip_hdr usr_hdr; + pj_pool_t *pool; + pjsip_endpoint *endpt; + pj_bool_t _delete_flag; + int pending_tsx; + pj_bool_t in_callback; + pj_mutex_t *mutex; + + pjsip_publishc_opt opt; + void *token; + pjsip_publishc_cb *cb; + + pj_str_t event; + pj_str_t str_target_uri; + pjsip_uri *target_uri; + pjsip_cid_hdr *cid_hdr; + pjsip_cseq_hdr *cseq_hdr; + pj_str_t from_uri; + pjsip_from_hdr *from_hdr; + pjsip_to_hdr *to_hdr; + pj_str_t etag; + pjsip_expires_hdr *expires_hdr; + pj_uint32_t expires; + pjsip_route_hdr route_set; + pjsip_hdr usr_hdr; pjsip_host_port via_addr; const void *via_tp; /* Authorization sessions. */ - pjsip_auth_clt_sess auth_sess; + pjsip_auth_clt_sess auth_sess; /* Auto refresh publication. */ - pj_bool_t auto_refresh; - pj_time_val last_refresh; - pj_time_val next_refresh; - pj_timer_entry timer; + pj_bool_t auto_refresh; + pj_time_val last_refresh; + pj_time_val next_refresh; + pj_timer_entry timer; /* Pending PUBLISH request */ - pending_publish pending_reqs; - pending_publish pending_reqs_empty; + pending_publish pending_reqs; + pending_publish pending_reqs_empty; }; @@ -126,25 +125,25 @@ PJ_DEF(void) pjsip_publishc_opt_default(pjsip_publishc_opt *opt) PJ_DEF(pj_status_t) pjsip_publishc_init_module(pjsip_endpoint *endpt) { /* Note: - Commented out the capability registration below, since it's - wrong to include PUBLISH in Allow header of INVITE requests/ - responses. + Commented out the capability registration below, since it's + wrong to include PUBLISH in Allow header of INVITE requests/ + responses. - 13.2.1 Creating the Initial INVITE - An Allow header field (Section 20.5) SHOULD be present in the - INVITE. It indicates what methods can be invoked within a dialog + 13.2.1 Creating the Initial INVITE + An Allow header field (Section 20.5) SHOULD be present in the + INVITE. It indicates what methods can be invoked within a dialog - 20.5 Allow - The Allow header field lists the set of methods supported by the - UA generating the message. + 20.5 Allow + The Allow header field lists the set of methods supported by the + UA generating the message. - While the semantic of Allow header in non-dialog requests is unclear, - it's probably best not to include PUBLISH in Allow header for now - until we can find out how to customize the inclusion of methods in - Allow header for in-dialog vs out-dialog requests. + While the semantic of Allow header in non-dialog requests is unclear, + it's probably best not to include PUBLISH in Allow header for now + until we can find out how to customize the inclusion of methods in + Allow header for in-dialog vs out-dialog requests. return pjsip_endpt_add_capability( endpt, NULL, PJSIP_H_ALLOW, NULL, - 1, &pjsip_publish_method.name); + 1, &pjsip_publish_method.name); */ PJ_UNUSED_ARG(endpt); return PJ_SUCCESS; @@ -152,10 +151,10 @@ PJ_DEF(pj_status_t) pjsip_publishc_init_module(pjsip_endpoint *endpt) PJ_DEF(pj_status_t) pjsip_publishc_create( pjsip_endpoint *endpt, - const pjsip_publishc_opt *opt, - void *token, - pjsip_publishc_cb *cb, - pjsip_publishc **p_pubc) + const pjsip_publishc_opt *opt, + void *token, + pjsip_publishc_cb *cb, + pjsip_publishc **p_pubc) { pj_pool_t *pool; pjsip_publishc *pubc; @@ -177,8 +176,8 @@ PJ_DEF(pj_status_t) pjsip_publishc_create( pjsip_endpoint *endpt, pubc->expires = PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED; if (!opt) { - pjsip_publishc_opt_default(&default_opt); - opt = &default_opt; + pjsip_publishc_opt_default(&default_opt); + opt = &default_opt; } pj_memcpy(&pubc->opt, opt, sizeof(*opt)); pj_list_init(&pubc->pending_reqs); @@ -186,15 +185,15 @@ PJ_DEF(pj_status_t) pjsip_publishc_create( pjsip_endpoint *endpt, status = pj_mutex_create_recursive(pubc->pool, "pubc%p", &pubc->mutex); if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; + pj_pool_release(pool); + return status; } status = pjsip_auth_clt_init(&pubc->auth_sess, endpt, pubc->pool, 0); if (status != PJ_SUCCESS) { - pj_mutex_destroy(pubc->mutex); - pj_pool_release(pool); - return status; + pj_mutex_destroy(pubc->mutex); + pj_pool_release(pool); + return status; } pj_list_init(&pubc->route_set); @@ -211,20 +210,20 @@ PJ_DEF(pj_status_t) pjsip_publishc_destroy(pjsip_publishc *pubc) PJ_ASSERT_RETURN(pubc, PJ_EINVAL); if (pubc->pending_tsx || pubc->in_callback) { - pubc->_delete_flag = 1; - pubc->cb = NULL; + pubc->_delete_flag = 1; + pubc->cb = NULL; } else { - /* Cancel existing timer, if any */ - if (pubc->timer.id != 0) { - pjsip_endpt_cancel_timer(pubc->endpt, &pubc->timer); - pubc->timer.id = 0; - } + /* Cancel existing timer, if any */ + if (pubc->timer.id != 0) { + pjsip_endpt_cancel_timer(pubc->endpt, &pubc->timer); + pubc->timer.id = 0; + } - if (pubc->mutex) - pj_mutex_destroy(pubc->mutex); + if (pubc->mutex) + pj_mutex_destroy(pubc->mutex); - pjsip_auth_clt_deinit(&pubc->auth_sess); - pjsip_endpt_release_pool(pubc->endpt, pubc->pool); + pjsip_auth_clt_deinit(&pubc->auth_sess); + pjsip_endpt_release_pool(pubc->endpt, pubc->pool); } return PJ_SUCCESS; @@ -239,26 +238,26 @@ PJ_DEF(pj_pool_t*) pjsip_publishc_get_pool(pjsip_publishc *pubc) static void set_expires( pjsip_publishc *pubc, pj_uint32_t expires) { if (expires != pubc->expires && - expires != PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED) + expires != PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED) { - pubc->expires_hdr = pjsip_expires_hdr_create(pubc->pool, expires); + pubc->expires_hdr = pjsip_expires_hdr_create(pubc->pool, expires); } else { - pubc->expires_hdr = NULL; + pubc->expires_hdr = NULL; } } PJ_DEF(pj_status_t) pjsip_publishc_init(pjsip_publishc *pubc, - const pj_str_t *event, - const pj_str_t *target_uri, - const pj_str_t *from_uri, - const pj_str_t *to_uri, - pj_uint32_t expires) + const pj_str_t *event, + const pj_str_t *target_uri, + const pj_str_t *from_uri, + const pj_str_t *to_uri, + pj_uint32_t expires) { pj_str_t tmp; PJ_ASSERT_RETURN(pubc && event && target_uri && from_uri && to_uri && - expires, PJ_EINVAL); + expires, PJ_EINVAL); /* Copy event type */ pj_strdup_with_null(pubc->pool, &pubc->event, event); @@ -270,7 +269,7 @@ PJ_DEF(pj_status_t) pjsip_publishc_init(pjsip_publishc *pubc, tmp = pubc->str_target_uri; pubc->target_uri = pjsip_parse_uri( pubc->pool, tmp.ptr, tmp.slen, 0); if (pubc->target_uri == NULL) { - return PJSIP_EINVALIDURI; + return PJSIP_EINVALIDURI; } /* Set "From" header. */ @@ -278,18 +277,18 @@ PJ_DEF(pj_status_t) pjsip_publishc_init(pjsip_publishc *pubc, tmp = pubc->from_uri; pubc->from_hdr = pjsip_from_hdr_create(pubc->pool); pubc->from_hdr->uri = pjsip_parse_uri(pubc->pool, tmp.ptr, tmp.slen, - PJSIP_PARSE_URI_AS_NAMEADDR); + PJSIP_PARSE_URI_AS_NAMEADDR); if (!pubc->from_hdr->uri) { - return PJSIP_EINVALIDURI; + return PJSIP_EINVALIDURI; } /* Set "To" header. */ pj_strdup_with_null(pubc->pool, &tmp, to_uri); pubc->to_hdr = pjsip_to_hdr_create(pubc->pool); pubc->to_hdr->uri = pjsip_parse_uri(pubc->pool, tmp.ptr, tmp.slen, - PJSIP_PARSE_URI_AS_NAMEADDR); + PJSIP_PARSE_URI_AS_NAMEADDR); if (!pubc->to_hdr->uri) { - return PJSIP_EINVALIDURI; + return PJSIP_EINVALIDURI; } @@ -310,15 +309,15 @@ PJ_DEF(pj_status_t) pjsip_publishc_init(pjsip_publishc *pubc, } PJ_DEF(pj_status_t) pjsip_publishc_set_credentials( pjsip_publishc *pubc, - int count, - const pjsip_cred_info cred[] ) + int count, + const pjsip_cred_info cred[] ) { PJ_ASSERT_RETURN(pubc && count && cred, PJ_EINVAL); return pjsip_auth_clt_set_credentials(&pubc->auth_sess, count, cred); } PJ_DEF(pj_status_t) pjsip_publishc_set_route_set( pjsip_publishc *pubc, - const pjsip_route_hdr *route_set) + const pjsip_route_hdr *route_set) { const pjsip_route_hdr *chdr; @@ -328,15 +327,15 @@ PJ_DEF(pj_status_t) pjsip_publishc_set_route_set( pjsip_publishc *pubc, chdr = route_set->next; while (chdr != route_set) { - pj_list_push_back(&pubc->route_set, pjsip_hdr_clone(pubc->pool, chdr)); - chdr = chdr->next; + pj_list_push_back(&pubc->route_set, pjsip_hdr_clone(pubc->pool, chdr)); + chdr = chdr->next; } return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjsip_publishc_set_headers( pjsip_publishc *pubc, - const pjsip_hdr *hdr_list) + const pjsip_hdr *hdr_list) { const pjsip_hdr *h; @@ -345,15 +344,15 @@ PJ_DEF(pj_status_t) pjsip_publishc_set_headers( pjsip_publishc *pubc, pj_list_init(&pubc->usr_hdr); h = hdr_list->next; while (h != hdr_list) { - pj_list_push_back(&pubc->usr_hdr, pjsip_hdr_clone(pubc->pool, h)); - h = h->next; + pj_list_push_back(&pubc->usr_hdr, pjsip_hdr_clone(pubc->pool, h)); + h = h->next; } return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjsip_publishc_set_via_sent_by(pjsip_publishc *pubc, - pjsip_host_port *via_addr, + pjsip_host_port *via_addr, pjsip_transport *via_tp) { PJ_ASSERT_RETURN(pubc, PJ_EINVAL); @@ -371,7 +370,7 @@ PJ_DEF(pj_status_t) pjsip_publishc_set_via_sent_by(pjsip_publishc *pubc, } static pj_status_t create_request(pjsip_publishc *pubc, - pjsip_tx_data **p_tdata) + pjsip_tx_data **p_tdata) { const pj_str_t STR_EVENT = { "Event", 5 }; pj_status_t status; @@ -382,69 +381,69 @@ static pj_status_t create_request(pjsip_publishc *pubc, /* Create the request. */ status = pjsip_endpt_create_request_from_hdr( pubc->endpt, - &pjsip_publish_method, - pubc->target_uri, - pubc->from_hdr, - pubc->to_hdr, - NULL, - pubc->cid_hdr, - pubc->cseq_hdr->cseq, - NULL, - &tdata); + &pjsip_publish_method, + pubc->target_uri, + pubc->from_hdr, + pubc->to_hdr, + NULL, + pubc->cid_hdr, + pubc->cseq_hdr->cseq, + NULL, + &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Add cached authorization headers. */ pjsip_auth_clt_init_req( &pubc->auth_sess, tdata ); /* Add Route headers from route set, ideally after Via header */ if (!pj_list_empty(&pubc->route_set)) { - pjsip_hdr *route_pos; - const pjsip_route_hdr *route; - - route_pos = (pjsip_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); - if (!route_pos) - route_pos = &tdata->msg->hdr; - - route = pubc->route_set.next; - while (route != &pubc->route_set) { - pjsip_hdr *new_hdr = (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, route); - pj_list_insert_after(route_pos, new_hdr); - route_pos = new_hdr; - route = route->next; - } + pjsip_hdr *route_pos; + const pjsip_route_hdr *route; + + route_pos = (pjsip_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); + if (!route_pos) + route_pos = &tdata->msg->hdr; + + route = pubc->route_set.next; + while (route != &pubc->route_set) { + pjsip_hdr *new_hdr = (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, route); + pj_list_insert_after(route_pos, new_hdr); + route_pos = new_hdr; + route = route->next; + } } /* Add Event header */ hdr = pjsip_generic_string_hdr_create(tdata->pool, &STR_EVENT, - &pubc->event); + &pubc->event); if (hdr) - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hdr); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hdr); /* Add SIP-If-Match if we have etag */ if (pubc->etag.slen) { - const pj_str_t STR_HNAME = { "SIP-If-Match", 12 }; + const pj_str_t STR_HNAME = { "SIP-If-Match", 12 }; - hdr = pjsip_generic_string_hdr_create(tdata->pool, &STR_HNAME, - &pubc->etag); - if (hdr) - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hdr); + hdr = pjsip_generic_string_hdr_create(tdata->pool, &STR_HNAME, + &pubc->etag); + if (hdr) + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hdr); } /* Add user headers */ if (!pj_list_empty(&pubc->usr_hdr)) { - const pjsip_hdr *uhdr; - - uhdr = pubc->usr_hdr.next; - while (uhdr != &pubc->usr_hdr) { - pjsip_hdr *new_hdr = (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, uhdr); - pjsip_msg_add_hdr(tdata->msg, new_hdr); - uhdr = uhdr->next; - } + const pjsip_hdr *uhdr; + + uhdr = pubc->usr_hdr.next; + while (uhdr != &pubc->usr_hdr) { + pjsip_hdr *new_hdr = (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, uhdr); + pjsip_msg_add_hdr(tdata->msg, new_hdr); + uhdr = uhdr->next; + } } @@ -455,8 +454,8 @@ static pj_status_t create_request(pjsip_publishc *pubc, PJ_DEF(pj_status_t) pjsip_publishc_publish(pjsip_publishc *pubc, - pj_bool_t auto_refresh, - pjsip_tx_data **p_tdata) + pj_bool_t auto_refresh, + pjsip_tx_data **p_tdata) { pj_status_t status; pjsip_tx_data *tdata; @@ -465,22 +464,22 @@ PJ_DEF(pj_status_t) pjsip_publishc_publish(pjsip_publishc *pubc, status = create_request(pubc, &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Add Expires header */ if (pubc->expires_hdr) { - pjsip_hdr *dup; + pjsip_hdr *dup; - dup = (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, pubc->expires_hdr); - if (dup) - pjsip_msg_add_hdr(tdata->msg, dup); + dup = (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, pubc->expires_hdr); + if (dup) + pjsip_msg_add_hdr(tdata->msg, dup); } /* Cancel existing timer */ if (pubc->timer.id != 0) { - pjsip_endpt_cancel_timer(pubc->endpt, &pubc->timer); - pubc->timer.id = 0; + pjsip_endpt_cancel_timer(pubc->endpt, &pubc->timer); + pubc->timer.id = 0; } pubc->auto_refresh = auto_refresh; @@ -492,7 +491,7 @@ PJ_DEF(pj_status_t) pjsip_publishc_publish(pjsip_publishc *pubc, PJ_DEF(pj_status_t) pjsip_publishc_unpublish(pjsip_publishc *pubc, - pjsip_tx_data **p_tdata) + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pjsip_msg *msg; @@ -502,13 +501,13 @@ PJ_DEF(pj_status_t) pjsip_publishc_unpublish(pjsip_publishc *pubc, PJ_ASSERT_RETURN(pubc && p_tdata, PJ_EINVAL); if (pubc->timer.id != 0) { - pjsip_endpt_cancel_timer(pubc->endpt, &pubc->timer); - pubc->timer.id = 0; + pjsip_endpt_cancel_timer(pubc->endpt, &pubc->timer); + pubc->timer.id = 0; } status = create_request(pubc, &tdata); if (status != PJ_SUCCESS) - return status; + return status; msg = tdata->msg; @@ -522,7 +521,7 @@ PJ_DEF(pj_status_t) pjsip_publishc_unpublish(pjsip_publishc *pubc, PJ_DEF(pj_status_t) pjsip_publishc_update_expires( pjsip_publishc *pubc, - pj_uint32_t expires ) + pj_uint32_t expires ) { PJ_ASSERT_RETURN(pubc, PJ_EINVAL); set_expires( pubc, expires ); @@ -531,8 +530,8 @@ PJ_DEF(pj_status_t) pjsip_publishc_update_expires( pjsip_publishc *pubc, static void call_callback(pjsip_publishc *pubc, pj_status_t status, - int st_code, const pj_str_t *reason, - pjsip_rx_data *rdata, pj_uint32_t expiration) + int st_code, const pj_str_t *reason, + pjsip_rx_data *rdata, pj_uint32_t expiration) { struct pjsip_publishc_cbparam cbparam; @@ -549,7 +548,7 @@ static void call_callback(pjsip_publishc *pubc, pj_status_t status, } static void pubc_refresh_timer_cb( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { pjsip_publishc *pubc = (pjsip_publishc*) entry->user_data; pjsip_tx_data *tdata; @@ -560,11 +559,11 @@ static void pubc_refresh_timer_cb( pj_timer_heap_t *timer_heap, entry->id = 0; status = pjsip_publishc_publish(pubc, 1, &tdata); if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_str_t reason = pj_strerror(status, errmsg, sizeof(errmsg)); - call_callback(pubc, status, 400, &reason, NULL, - PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED); - return; + char errmsg[PJ_ERR_MSG_SIZE]; + pj_str_t reason = pj_strerror(status, errmsg, sizeof(errmsg)); + call_callback(pubc, status, 400, &reason, NULL, + PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED); + return; } status = pjsip_publishc_send(pubc, tdata); @@ -589,149 +588,149 @@ static void tsx_callback(void *token, pjsip_event *event) */ if (pubc->_delete_flag) { - /* Nothing to do */ - ; + /* Nothing to do */ + ; } else if (tsx->status_code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED || - tsx->status_code == PJSIP_SC_UNAUTHORIZED) + tsx->status_code == PJSIP_SC_UNAUTHORIZED) { - pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; - pjsip_tx_data *tdata; - - status = pjsip_auth_clt_reinit_req( &pubc->auth_sess, - rdata, - tsx->last_tx, - &tdata); - if (status != PJ_SUCCESS) { - call_callback(pubc, status, tsx->status_code, - &rdata->msg_info.msg->line.status.reason, - rdata, PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED); - } else { - status = pjsip_publishc_send(pubc, tdata); - } + pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; + pjsip_tx_data *tdata; + + status = pjsip_auth_clt_reinit_req( &pubc->auth_sess, + rdata, + tsx->last_tx, + &tdata); + if (status != PJ_SUCCESS) { + call_callback(pubc, status, tsx->status_code, + &rdata->msg_info.msg->line.status.reason, + rdata, PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED); + } else { + status = pjsip_publishc_send(pubc, tdata); + } } else { - pjsip_rx_data *rdata; - pj_uint32_t expiration = PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED; - - if (tsx->status_code/100 == 2) { - pjsip_msg *msg; - pjsip_expires_hdr *expires; - pjsip_generic_string_hdr *etag_hdr; - const pj_str_t STR_ETAG = { "SIP-ETag", 8 }; - - rdata = event->body.tsx_state.src.rdata; - msg = rdata->msg_info.msg; - - /* Save ETag value */ - etag_hdr = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(msg, &STR_ETAG, NULL); - if (etag_hdr) { - pj_strdup(pubc->pool, &pubc->etag, &etag_hdr->hvalue); - } else { - pubc->etag.slen = 0; - } - - /* Update expires value */ - expires = (pjsip_expires_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_EXPIRES, NULL); - - if (pubc->auto_refresh && expires) - expiration = expires->ivalue; - - if (pubc->auto_refresh && expiration!=0 && - expiration!=PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED) - { - pj_time_val delay = { 0, 0}; - - /* Cancel existing timer, if any */ - if (pubc->timer.id != 0) { - pjsip_endpt_cancel_timer(pubc->endpt, &pubc->timer); - pubc->timer.id = 0; - } - - delay.sec = expiration - DELAY_BEFORE_REFRESH; - if (pubc->expires != PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED && - delay.sec > (pj_int32_t)pubc->expires) - { - delay.sec = pubc->expires; - } - if (delay.sec < DELAY_BEFORE_REFRESH) - delay.sec = DELAY_BEFORE_REFRESH; - pubc->timer.cb = &pubc_refresh_timer_cb; - pubc->timer.id = REFRESH_TIMER; - pubc->timer.user_data = pubc; - pjsip_endpt_schedule_timer( pubc->endpt, &pubc->timer, &delay); - pj_gettimeofday(&pubc->last_refresh); - pubc->next_refresh = pubc->last_refresh; - pubc->next_refresh.sec += delay.sec; - } - - } else { - rdata = (event->body.tsx_state.type==PJSIP_EVENT_RX_MSG) ? - event->body.tsx_state.src.rdata : NULL; - } - - - /* Call callback. */ - // if (expiration == 0xFFFF) expiration = -1; - - /* Temporarily increment pending_tsx to prevent callback from - * destroying pubc. - */ - ++pubc->pending_tsx; - - call_callback(pubc, PJ_SUCCESS, tsx->status_code, - (rdata ? &rdata->msg_info.msg->line.status.reason - : pjsip_get_status_text(tsx->status_code)), - rdata, expiration); - - --pubc->pending_tsx; - - /* If we have pending request(s), send them now */ - pj_mutex_lock(pubc->mutex); - while (!pj_list_empty(&pubc->pending_reqs)) { - pending_publish *pp = pubc->pending_reqs.next; - pjsip_tx_data *tdata = pp->tdata; - - /* Remove the request from pending request list, - * and keep the unused entry into pending_reqs_empty pool. - */ - pj_list_erase(pp); - pj_list_push_back(&pubc->pending_reqs_empty, pp); - - /* Add SIP-If-Match if we have etag and the request doesn't have - * one (https://github.com/pjsip/pjproject/issues/996) - */ - if (pubc->etag.slen) { - const pj_str_t STR_HNAME = { "SIP-If-Match", 12 }; - pjsip_generic_string_hdr *sim_hdr; - - sim_hdr = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(tdata->msg, &STR_HNAME, NULL); - if (!sim_hdr) { - /* Create the header */ - sim_hdr = pjsip_generic_string_hdr_create(tdata->pool, - &STR_HNAME, - &pubc->etag); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)sim_hdr); - - } else { - /* Update */ - if (pj_strcmp(&pubc->etag, &sim_hdr->hvalue)) - pj_strdup(tdata->pool, &sim_hdr->hvalue, &pubc->etag); - } - } - - status = pjsip_publishc_send(pubc, tdata); - if (status == PJ_EPENDING) { - pj_assert(!"Not expected"); - pjsip_tx_data_dec_ref(tdata); - } else if (status == PJ_SUCCESS) { - break; - } - } - pj_mutex_unlock(pubc->mutex); + pjsip_rx_data *rdata; + pj_uint32_t expiration = PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED; + + if (tsx->status_code/100 == 2) { + pjsip_msg *msg; + pjsip_expires_hdr *expires; + pjsip_generic_string_hdr *etag_hdr; + const pj_str_t STR_ETAG = { "SIP-ETag", 8 }; + + rdata = event->body.tsx_state.src.rdata; + msg = rdata->msg_info.msg; + + /* Save ETag value */ + etag_hdr = (pjsip_generic_string_hdr*) + pjsip_msg_find_hdr_by_name(msg, &STR_ETAG, NULL); + if (etag_hdr) { + pj_strdup(pubc->pool, &pubc->etag, &etag_hdr->hvalue); + } else { + pubc->etag.slen = 0; + } + + /* Update expires value */ + expires = (pjsip_expires_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_EXPIRES, NULL); + + if (pubc->auto_refresh && expires) + expiration = expires->ivalue; + + if (pubc->auto_refresh && expiration!=0 && + expiration!=PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED) + { + pj_time_val delay = { 0, 0}; + + /* Cancel existing timer, if any */ + if (pubc->timer.id != 0) { + pjsip_endpt_cancel_timer(pubc->endpt, &pubc->timer); + pubc->timer.id = 0; + } + + delay.sec = expiration - DELAY_BEFORE_REFRESH; + if (pubc->expires != PJSIP_PUBC_EXPIRATION_NOT_SPECIFIED && + delay.sec > (pj_int32_t)pubc->expires) + { + delay.sec = pubc->expires; + } + if (delay.sec < DELAY_BEFORE_REFRESH) + delay.sec = DELAY_BEFORE_REFRESH; + pubc->timer.cb = &pubc_refresh_timer_cb; + pubc->timer.id = REFRESH_TIMER; + pubc->timer.user_data = pubc; + pjsip_endpt_schedule_timer( pubc->endpt, &pubc->timer, &delay); + pj_gettimeofday(&pubc->last_refresh); + pubc->next_refresh = pubc->last_refresh; + pubc->next_refresh.sec += delay.sec; + } + + } else { + rdata = (event->body.tsx_state.type==PJSIP_EVENT_RX_MSG) ? + event->body.tsx_state.src.rdata : NULL; + } + + + /* Call callback. */ + // if (expiration == 0xFFFF) expiration = -1; + + /* Temporarily increment pending_tsx to prevent callback from + * destroying pubc. + */ + ++pubc->pending_tsx; + + call_callback(pubc, PJ_SUCCESS, tsx->status_code, + (rdata ? &rdata->msg_info.msg->line.status.reason + : pjsip_get_status_text(tsx->status_code)), + rdata, expiration); + + --pubc->pending_tsx; + + /* If we have pending request(s), send them now */ + pj_mutex_lock(pubc->mutex); + while (!pj_list_empty(&pubc->pending_reqs)) { + pending_publish *pp = pubc->pending_reqs.next; + pjsip_tx_data *tdata = pp->tdata; + + /* Remove the request from pending request list, + * and keep the unused entry into pending_reqs_empty pool. + */ + pj_list_erase(pp); + pj_list_push_back(&pubc->pending_reqs_empty, pp); + + /* Add SIP-If-Match if we have etag and the request doesn't have + * one (https://github.com/pjsip/pjproject/issues/996) + */ + if (pubc->etag.slen) { + const pj_str_t STR_HNAME = { "SIP-If-Match", 12 }; + pjsip_generic_string_hdr *sim_hdr; + + sim_hdr = (pjsip_generic_string_hdr*) + pjsip_msg_find_hdr_by_name(tdata->msg, &STR_HNAME, NULL); + if (!sim_hdr) { + /* Create the header */ + sim_hdr = pjsip_generic_string_hdr_create(tdata->pool, + &STR_HNAME, + &pubc->etag); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)sim_hdr); + + } else { + /* Update */ + if (pj_strcmp(&pubc->etag, &sim_hdr->hvalue)) + pj_strdup(tdata->pool, &sim_hdr->hvalue, &pubc->etag); + } + } + + status = pjsip_publishc_send(pubc, tdata); + if (status == PJ_EPENDING) { + pj_assert(!"Not expected"); + pjsip_tx_data_dec_ref(tdata); + } else if (status == PJ_SUCCESS) { + break; + } + } + pj_mutex_unlock(pubc->mutex); } /* No longer in callback. */ @@ -739,13 +738,13 @@ static void tsx_callback(void *token, pjsip_event *event) /* Delete the record if user destroy pubc during the callback. */ if (pubc->_delete_flag && pubc->pending_tsx==0) { - pjsip_publishc_destroy(pubc); + pjsip_publishc_destroy(pubc); } } PJ_DEF(pj_status_t) pjsip_publishc_send(pjsip_publishc *pubc, - pjsip_tx_data *tdata) + pjsip_tx_data *tdata) { pj_status_t status; pjsip_cseq_hdr *cseq_hdr; @@ -756,27 +755,27 @@ PJ_DEF(pj_status_t) pjsip_publishc_send(pjsip_publishc *pubc, /* Make sure we don't have pending transaction. */ pj_mutex_lock(pubc->mutex); if (pubc->pending_tsx) { - if (pubc->opt.queue_request) { - pending_publish *pp = NULL; - if (pj_list_empty(&pubc->pending_reqs_empty)) { - pp = PJ_POOL_ZALLOC_T(pubc->pool, pending_publish); - } else { - pp = pubc->pending_reqs_empty.next; - pj_list_erase(pp); - } - pp->tdata = tdata; - pj_list_push_back(&pubc->pending_reqs, pp); - pj_mutex_unlock(pubc->mutex); - PJ_LOG(4,(THIS_FILE, "Request is queued, pubc has another " - "transaction pending")); - return PJ_EPENDING; - } else { - pjsip_tx_data_dec_ref(tdata); - pj_mutex_unlock(pubc->mutex); - PJ_LOG(4,(THIS_FILE, "Unable to send request, pubc has another " - "transaction pending")); - return PJ_EBUSY; - } + if (pubc->opt.queue_request) { + pending_publish *pp = NULL; + if (pj_list_empty(&pubc->pending_reqs_empty)) { + pp = PJ_POOL_ZALLOC_T(pubc->pool, pending_publish); + } else { + pp = pubc->pending_reqs_empty.next; + pj_list_erase(pp); + } + pp->tdata = tdata; + pj_list_push_back(&pubc->pending_reqs, pp); + pj_mutex_unlock(pubc->mutex); + PJ_LOG(4,(THIS_FILE, "Request is queued, pubc has another " + "transaction pending")); + return PJ_EPENDING; + } else { + pjsip_tx_data_dec_ref(tdata); + pj_mutex_unlock(pubc->mutex); + PJ_LOG(4,(THIS_FILE, "Unable to send request, pubc has another " + "transaction pending")); + return PJ_EBUSY; + } } pj_mutex_unlock(pubc->mutex); @@ -792,7 +791,7 @@ PJ_DEF(pj_status_t) pjsip_publishc_send(pjsip_publishc *pubc, /* Increment CSeq */ cseq = ++pubc->cseq_hdr->cseq; cseq_hdr = (pjsip_cseq_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL); + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL); cseq_hdr->cseq = cseq; /* Increment pending transaction first, since transaction callback @@ -800,13 +799,13 @@ PJ_DEF(pj_status_t) pjsip_publishc_send(pjsip_publishc *pubc, */ ++pubc->pending_tsx; status = pjsip_endpt_send_request(pubc->endpt, tdata, -1, pubc, - &tsx_callback); + &tsx_callback); if (status!=PJ_SUCCESS) { - // no need to decrement, callback has been called and it should - // already decremented pending_tsx. Decrementing this here may - // cause accessing freed memory location. - //--pubc->pending_tsx; - PJ_PERROR(4,(THIS_FILE, status, "Error sending request")); + // no need to decrement, callback has been called and it should + // already decremented pending_tsx. Decrementing this here may + // cause accessing freed memory location. + //--pubc->pending_tsx; + PJ_PERROR(4,(THIS_FILE, status, "Error sending request")); } return status; diff --git a/pjsip/src/pjsip-simple/rpid.c b/pjsip/src/pjsip-simple/rpid.c index 104af92d98..f65efd0269 100644 --- a/pjsip/src/pjsip-simple/rpid.c +++ b/pjsip/src/pjsip-simple/rpid.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -42,7 +41,7 @@ static const pj_str_t RPID_UNKNOWN = {"rpid:unknown", 12}; /* Duplicate RPID element */ PJ_DEF(void) pjrpid_element_dup(pj_pool_t *pool, pjrpid_element *dst, - const pjrpid_element *src) + const pjrpid_element *src) { pj_memcpy(dst, src, sizeof(pjrpid_element)); pj_strdup(pool, &dst->id, &src->id); @@ -52,11 +51,11 @@ PJ_DEF(void) pjrpid_element_dup(pj_pool_t *pool, pjrpid_element *dst, /* Update RPID namespaces. */ static void update_namespaces(pjpidf_pres *pres, - pj_pool_t *pool) + pj_pool_t *pool) { /* Check if namespace is already present. */ if (pj_xml_find_attr(pres, &DM_NAME, NULL) != NULL) - return; + return; pj_xml_add_attr(pres, pj_xml_attr_new(pool, &DM_NAME, &DM_VAL)); pj_xml_add_attr(pres, pj_xml_attr_new(pool, &RPID_NAME, &RPID_VAL)); @@ -65,16 +64,16 @@ static void update_namespaces(pjpidf_pres *pres, /* Comparison function to find node name substring */ static pj_bool_t substring_match(const pj_xml_node *node, - const char *part_name, - pj_ssize_t part_len) + const char *part_name, + pj_ssize_t part_len) { pj_str_t end_name; if (part_len < 1) - part_len = pj_ansi_strlen(part_name); + part_len = pj_ansi_strlen(part_name); if (node->name.slen < part_len) - return PJ_FALSE; + return PJ_FALSE; end_name.ptr = node->name.ptr + (node->name.slen - part_len); end_name.slen = part_len; @@ -84,17 +83,17 @@ static pj_bool_t substring_match(const pj_xml_node *node, /* Util to find child node with the specified substring */ static pj_xml_node *find_node(const pj_xml_node *parent, - const char *part_name) + const char *part_name) { const pj_xml_node *node = parent->node_head.next, - *head = (pj_xml_node*) &parent->node_head; + *head = (pj_xml_node*) &parent->node_head; pj_ssize_t part_len = pj_ansi_strlen(part_name); while (node != head) { - if (substring_match(node, part_name, part_len)) - return (pj_xml_node*) node; + if (substring_match(node, part_name, part_len)) + return (pj_xml_node*) node; - node = node->next; + node = node->next; } return NULL; @@ -104,9 +103,9 @@ static pj_xml_node *find_node(const pj_xml_node *parent, * Add RPID element into existing PIDF document. */ PJ_DEF(pj_status_t) pjrpid_add_element(pjpidf_pres *pres, - pj_pool_t *pool, - unsigned options, - const pjrpid_element *elem) + pj_pool_t *pool, + unsigned options, + const pjrpid_element *elem) { pj_xml_node *nd_person, *nd_activities, *nd_activity, *nd_note; pj_xml_attr *attr; @@ -117,24 +116,24 @@ PJ_DEF(pj_status_t) pjrpid_add_element(pjpidf_pres *pres, /* Add to , if none */ if (elem->note.slen != 0) { - pj_xml_node *nd_tuple; - - nd_tuple = find_node(pres, "tuple"); - nd_note = nd_tuple? find_node(nd_tuple, "note"):NULL; - if (!nd_note) { - nd_note = pj_xml_node_new(pool, &NOTE); - pj_strdup(pool, &nd_note->content, &elem->note); - pj_xml_add_node(nd_tuple, nd_note); - nd_note = NULL; - } + pj_xml_node *nd_tuple; + + nd_tuple = find_node(pres, "tuple"); + nd_note = nd_tuple? find_node(nd_tuple, "note"):NULL; + if (!nd_note) { + nd_note = pj_xml_node_new(pool, &NOTE); + pj_strdup(pool, &nd_note->content, &elem->note); + pj_xml_add_node(nd_tuple, nd_note); + nd_note = NULL; + } } /* Check if we need to add RPID information into the PIDF document. */ if (elem->id.slen==0 && - elem->activity==PJRPID_ACTIVITY_UNKNOWN) + elem->activity==PJRPID_ACTIVITY_UNKNOWN) { - /* No RPID information to be added. */ - return PJ_SUCCESS; + /* No RPID information to be added. */ + return PJ_SUCCESS; } /* Update namespace */ @@ -143,20 +142,20 @@ PJ_DEF(pj_status_t) pjrpid_add_element(pjpidf_pres *pres, /* Add */ nd_person = pj_xml_node_new(pool, &DM_PERSON); if (elem->id.slen != 0) { - attr = pj_xml_attr_new(pool, &ID, &elem->id); + attr = pj_xml_attr_new(pool, &ID, &elem->id); } else { - pj_str_t person_id; - /* xs:ID must start with letter */ - //pj_create_unique_string(pool, &person_id); - person_id.ptr = (char*)pj_pool_alloc(pool, pj_GUID_STRING_LENGTH()+2); - person_id.ptr += 2; - pj_generate_unique_string(&person_id); - person_id.ptr -= 2; - person_id.ptr[0] = 'p'; - person_id.ptr[1] = 'j'; - person_id.slen += 2; - - attr = pj_xml_attr_new(pool, &ID, &person_id); + pj_str_t person_id; + /* xs:ID must start with letter */ + //pj_create_unique_string(pool, &person_id); + person_id.ptr = (char*)pj_pool_alloc(pool, pj_GUID_STRING_LENGTH()+2); + person_id.ptr += 2; + pj_generate_unique_string(&person_id); + person_id.ptr -= 2; + person_id.ptr[0] = 'p'; + person_id.ptr[1] = 'j'; + person_id.slen += 2; + + attr = pj_xml_attr_new(pool, &ID, &person_id); } pj_xml_add_attr(nd_person, attr); pj_xml_add_node(pres, nd_person); @@ -168,23 +167,23 @@ PJ_DEF(pj_status_t) pjrpid_add_element(pjpidf_pres *pres, /* Add the activity */ switch (elem->activity) { case PJRPID_ACTIVITY_AWAY: - nd_activity = pj_xml_node_new(pool, &RPID_AWAY); - break; + nd_activity = pj_xml_node_new(pool, &RPID_AWAY); + break; case PJRPID_ACTIVITY_BUSY: - nd_activity = pj_xml_node_new(pool, &RPID_BUSY); - break; + nd_activity = pj_xml_node_new(pool, &RPID_BUSY); + break; case PJRPID_ACTIVITY_UNKNOWN: default: - nd_activity = pj_xml_node_new(pool, &RPID_UNKNOWN); - break; + nd_activity = pj_xml_node_new(pool, &RPID_UNKNOWN); + break; } pj_xml_add_node(nd_activities, nd_activity); /* Add custom text if required. */ if (elem->note.slen != 0) { - nd_note = pj_xml_node_new(pool, &DM_NOTE); - pj_strdup(pool, &nd_note->content, &elem->note); - pj_xml_add_node(nd_person, nd_note); + nd_note = pj_xml_node_new(pool, &DM_NOTE); + pj_strdup(pool, &nd_note->content, &elem->note); + pj_xml_add_node(nd_person, nd_note); } /* Done */ @@ -194,23 +193,23 @@ PJ_DEF(pj_status_t) pjrpid_add_element(pjpidf_pres *pres, /* Get element from PIDF element */ static pj_status_t get_tuple_note(const pjpidf_pres *pres, - pj_pool_t *pool, - pjrpid_element *elem) + pj_pool_t *pool, + pjrpid_element *elem) { const pj_xml_node *nd_tuple, *nd_note; nd_tuple = find_node(pres, "tuple"); if (!nd_tuple) - return PJSIP_SIMPLE_EBADRPID; + return PJSIP_SIMPLE_EBADRPID; nd_note = find_node(nd_tuple, "note"); /* If we cannot find inside , try to get it from root. */ if (!nd_note) - nd_note = find_node(pres, "note"); + nd_note = find_node(pres, "note"); if (nd_note) { - pj_strdup(pool, &elem->note, &nd_note->content); - return PJ_SUCCESS; + pj_strdup(pool, &elem->note, &nd_note->content); + return PJ_SUCCESS; } return PJSIP_SIMPLE_EBADRPID; @@ -220,8 +219,8 @@ static pj_status_t get_tuple_note(const pjpidf_pres *pres, * Get RPID element from PIDF document, if any. */ PJ_DEF(pj_status_t) pjrpid_get_element(const pjpidf_pres *pres, - pj_pool_t *pool, - pjrpid_element *elem) + pj_pool_t *pool, + pjrpid_element *elem) { const pj_xml_node *nd_person, *nd_activities, *nd_note = NULL; const pj_xml_attr *attr; @@ -233,47 +232,47 @@ PJ_DEF(pj_status_t) pjrpid_get_element(const pjpidf_pres *pres, /* Find */ nd_person = find_node(pres, "person"); if (!nd_person) { - /* not found, try to get from */ - return get_tuple_note(pres, pool, elem); + /* not found, try to get from */ + return get_tuple_note(pres, pool, elem); } /* Get element id attribute */ attr = pj_xml_find_attr((pj_xml_node*)nd_person, &ID, NULL); if (attr) - pj_strdup(pool, &elem->id, &attr->value); + pj_strdup(pool, &elem->id, &attr->value); /* Get */ nd_activities = find_node(nd_person, "activities"); if (nd_activities) { - const pj_xml_node *nd_activity; + const pj_xml_node *nd_activity; - /* Try to get from */ - nd_note = find_node(nd_activities, "note"); + /* Try to get from */ + nd_note = find_node(nd_activities, "note"); - /* Get the activity */ - nd_activity = nd_activities->node_head.next; - if (nd_activity == nd_note) - nd_activity = nd_activity->next; + /* Get the activity */ + nd_activity = nd_activities->node_head.next; + if (nd_activity == nd_note) + nd_activity = nd_activity->next; - if (nd_activity != (pj_xml_node*) &nd_activities->node_head) { - if (substring_match(nd_activity, "busy", -1)) - elem->activity = PJRPID_ACTIVITY_BUSY; - else if (substring_match(nd_activity, "away", -1)) - elem->activity = PJRPID_ACTIVITY_AWAY; - else - elem->activity = PJRPID_ACTIVITY_UNKNOWN; + if (nd_activity != (pj_xml_node*) &nd_activities->node_head) { + if (substring_match(nd_activity, "busy", -1)) + elem->activity = PJRPID_ACTIVITY_BUSY; + else if (substring_match(nd_activity, "away", -1)) + elem->activity = PJRPID_ACTIVITY_AWAY; + else + elem->activity = PJRPID_ACTIVITY_UNKNOWN; - } + } } /* If is not found, get from */ if (nd_note == NULL) - nd_note = find_node(nd_person, "note"); + nd_note = find_node(nd_person, "note"); if (nd_note) { - pj_strdup(pool, &elem->note, &nd_note->content); + pj_strdup(pool, &elem->note, &nd_note->content); } else { - get_tuple_note(pres, pool, elem); + get_tuple_note(pres, pool, elem); } return PJ_SUCCESS; diff --git a/pjsip/src/pjsip-simple/xpidf.c b/pjsip/src/pjsip-simple/xpidf.c index 4ca4b29165..daa42c0a0c 100644 --- a/pjsip/src/pjsip-simple/xpidf.c +++ b/pjsip/src/pjsip-simple/xpidf.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -37,7 +36,7 @@ static pj_str_t STR_PRESENTITY = { "presentity", 10 }; static pj_str_t STR_EMPTY_STRING = { NULL, 0 }; static pj_xml_node* xml_create_node(pj_pool_t *pool, - pj_str_t *name, const pj_str_t *value) + pj_str_t *name, const pj_str_t *value) { pj_xml_node *node; @@ -52,7 +51,7 @@ static pj_xml_node* xml_create_node(pj_pool_t *pool, } static pj_xml_attr* xml_create_attr(pj_pool_t *pool, pj_str_t *name, - const pj_str_t *value) + const pj_str_t *value) { pj_xml_attr *attr = PJ_POOL_ALLOC_T(pool, pj_xml_attr); attr->name = *name; @@ -81,7 +80,7 @@ PJ_DEF(pjxpidf_pres*) pjxpidf_create(pj_pool_t *pool, const pj_str_t *uri_cstr) /* uri attribute */ uri.ptr = (char*) pj_pool_alloc(pool, uri_cstr->slen + - STR_SUBSCRIBE_PARAM.slen); + STR_SUBSCRIBE_PARAM.slen); pj_strcpy( &uri, uri_cstr); pj_strcat( &uri, &STR_SUBSCRIBE_PARAM); attr = xml_create_attr(pool, &STR_URI, &uri); @@ -124,43 +123,43 @@ PJ_DEF(pjxpidf_pres*) pjxpidf_parse(pj_pool_t *pool, char *text, pj_size_t len) pres = pj_xml_parse(pool, text, len); if (!pres) - return NULL; + return NULL; /* Validate */ if (pj_stricmp(&pres->name, &STR_PRESENCE) != 0) - return NULL; + return NULL; /* Validate */ node = pj_xml_find_node(pres, &STR_PRESENTITY); if (node == NULL) - return NULL; + return NULL; if (pj_xml_find_attr(node, &STR_URI, NULL) == NULL) - return NULL; + return NULL; /* Validate */ node = pj_xml_find_node(pres, &STR_ATOM); if (node == NULL) - return NULL; + return NULL; if (pj_xml_find_attr(node, &STR_ATOMID, NULL) == NULL && - pj_xml_find_attr(node, &STR_ID, NULL) == NULL) + pj_xml_find_attr(node, &STR_ID, NULL) == NULL) { - return NULL; + return NULL; } /* Address */ node = pj_xml_find_node(node, &STR_ADDRESS); if (node == NULL) - return NULL; + return NULL; if (pj_xml_find_attr(node, &STR_URI, NULL) == NULL) - return NULL; + return NULL; /* Status */ node = pj_xml_find_node(node, &STR_STATUS); if (node == NULL) - return NULL; + return NULL; if (pj_xml_find_attr(node, &STR_STATUS, NULL) == NULL) - return NULL; + return NULL; return pres; } @@ -179,18 +178,18 @@ PJ_DEF(pj_str_t*) pjxpidf_get_uri(pjxpidf_pres *pres) presentity = pj_xml_find_node(pres, &STR_PRESENTITY); if (!presentity) - return &STR_EMPTY_STRING; + return &STR_EMPTY_STRING; attr = pj_xml_find_attr(presentity, &STR_URI, NULL); if (!attr) - return &STR_EMPTY_STRING; + return &STR_EMPTY_STRING; return &attr->value; } PJ_DEF(pj_status_t) pjxpidf_set_uri(pj_pool_t *pool, pjxpidf_pres *pres, - const pj_str_t *uri) + const pj_str_t *uri) { pj_xml_node *presentity; pj_xml_node *atom; @@ -200,25 +199,25 @@ PJ_DEF(pj_status_t) pjxpidf_set_uri(pj_pool_t *pool, pjxpidf_pres *pres, presentity = pj_xml_find_node(pres, &STR_PRESENTITY); if (!presentity) { - pj_assert(0); - return -1; + pj_assert(0); + return -1; } atom = pj_xml_find_node(pres, &STR_ATOM); if (!atom) { - pj_assert(0); - return -1; + pj_assert(0); + return -1; } addr = pj_xml_find_node(atom, &STR_ADDRESS); if (!addr) { - pj_assert(0); - return -1; + pj_assert(0); + return -1; } /* Set uri in presentity */ attr = pj_xml_find_attr(presentity, &STR_URI, NULL); if (!attr) { - pj_assert(0); - return -1; + pj_assert(0); + return -1; } pj_strdup(pool, &dup_uri, uri); attr->value = dup_uri; @@ -226,8 +225,8 @@ PJ_DEF(pj_status_t) pjxpidf_set_uri(pj_pool_t *pool, pjxpidf_pres *pres, /* Set uri in address. */ attr = pj_xml_find_attr(addr, &STR_URI, NULL); if (!attr) { - pj_assert(0); - return -1; + pj_assert(0); + return -1; } attr->value = dup_uri; @@ -244,23 +243,23 @@ PJ_DEF(pj_bool_t) pjxpidf_get_status(pjxpidf_pres *pres) atom = pj_xml_find_node(pres, &STR_ATOM); if (!atom) { - pj_assert(0); - return PJ_FALSE; + pj_assert(0); + return PJ_FALSE; } addr = pj_xml_find_node(atom, &STR_ADDRESS); if (!addr) { - pj_assert(0); - return PJ_FALSE; + pj_assert(0); + return PJ_FALSE; } status = pj_xml_find_node(addr, &STR_STATUS); if (!status) { - pj_assert(0); - return PJ_FALSE; + pj_assert(0); + return PJ_FALSE; } attr = pj_xml_find_attr(status, &STR_STATUS, NULL); if (!attr) { - pj_assert(0); - return PJ_FALSE; + pj_assert(0); + return PJ_FALSE; } return pj_stricmp(&attr->value, &STR_OPEN)==0 ? PJ_TRUE : PJ_FALSE; @@ -276,23 +275,23 @@ PJ_DEF(pj_status_t) pjxpidf_set_status(pjxpidf_pres *pres, pj_bool_t online_stat atom = pj_xml_find_node(pres, &STR_ATOM); if (!atom) { - pj_assert(0); - return -1; + pj_assert(0); + return -1; } addr = pj_xml_find_node(atom, &STR_ADDRESS); if (!addr) { - pj_assert(0); - return -1; + pj_assert(0); + return -1; } status = pj_xml_find_node(addr, &STR_STATUS); if (!status) { - pj_assert(0); - return -1; + pj_assert(0); + return -1; } attr = pj_xml_find_attr(status, &STR_STATUS, NULL); if (!attr) { - pj_assert(0); - return -1; + pj_assert(0); + return -1; } attr->value = ( online_status ? STR_OPEN : STR_CLOSED ); diff --git a/pjsip/src/pjsip-ua/sip_100rel.c b/pjsip/src/pjsip-ua/sip_100rel.c index fd45ada0d2..9fa1b9bfd2 100644 --- a/pjsip/src/pjsip-ua/sip_100rel.c +++ b/pjsip/src/pjsip-ua/sip_100rel.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,7 +29,7 @@ #include #include -#define THIS_FILE "sip_100rel.c" +#define THIS_FILE "sip_100rel.c" /* PRACK method */ PJ_DEF_DATA(const pjsip_method) pjsip_prack_method = @@ -47,7 +46,7 @@ typedef struct dlg_data dlg_data; static pj_status_t mod_100rel_load(pjsip_endpoint *endpt); static void on_retransmit(pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry); + struct pj_timer_entry *entry); static const pj_str_t tag_100rel = { "100rel", 6 }; @@ -58,24 +57,24 @@ static const pj_str_t RACK = { "RAck", 4 }; /* 100rel module */ static struct mod_100rel { - pjsip_module mod; - pjsip_endpoint *endpt; + pjsip_module mod; + pjsip_endpoint *endpt; } mod_100rel = { { - NULL, NULL, /* prev, next. */ - { "mod-100rel", 10 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_DIALOG_USAGE, /* Priority */ - &mod_100rel_load, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - NULL, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-100rel", 10 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_DIALOG_USAGE, /* Priority */ + &mod_100rel_load, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ } }; @@ -83,9 +82,9 @@ static struct mod_100rel /* List of pending transmission (may include the final response as well) */ typedef struct tx_data_list_t { - PJ_DECL_LIST_MEMBER(struct tx_data_list_t); - pj_uint32_t rseq; - pjsip_tx_data *tdata; + PJ_DECL_LIST_MEMBER(struct tx_data_list_t); + pj_uint32_t rseq; + pjsip_tx_data *tdata; } tx_data_list_t; @@ -94,30 +93,30 @@ typedef struct tx_data_list_t /* UAS state. */ typedef struct uas_state_t { - pj_int32_t cseq; - pj_uint32_t rseq; /* Initialized to -1 */ - tx_data_list_t tx_data_list; - unsigned retransmit_count; - pj_timer_entry retransmit_timer; + pj_int32_t cseq; + pj_uint32_t rseq; /* Initialized to -1 */ + tx_data_list_t tx_data_list; + unsigned retransmit_count; + pj_timer_entry retransmit_timer; } uas_state_t; /* UAC state */ typedef struct uac_state_t { - pj_str_t tag; /* To tag */ - pj_int32_t cseq; - pj_uint32_t rseq; /* Initialized to -1 */ - struct uac_state_t *next; /* next call leg */ + pj_str_t tag; /* To tag */ + pj_int32_t cseq; + pj_uint32_t rseq; /* Initialized to -1 */ + struct uac_state_t *next; /* next call leg */ } uac_state_t; /* State attached to each dialog. */ struct dlg_data { - pjsip_inv_session *inv; - uas_state_t *uas_state; - uac_state_t *uac_state_list; + pjsip_inv_session *inv; + uas_state_t *uas_state; + uac_state_t *uac_state_list; }; @@ -131,11 +130,11 @@ static pj_status_t mod_100rel_load(pjsip_endpoint *endpt) { mod_100rel.endpt = endpt; pjsip_endpt_add_capability(endpt, &mod_100rel.mod, - PJSIP_H_ALLOW, NULL, - 1, &pjsip_prack_method.name); + PJSIP_H_ALLOW, NULL, + 1, &pjsip_prack_method.name); pjsip_endpt_add_capability(endpt, &mod_100rel.mod, - PJSIP_H_SUPPORTED, NULL, - 1, &tag_100rel); + PJSIP_H_SUPPORTED, NULL, + 1, &tag_100rel); return PJ_SUCCESS; } @@ -145,21 +144,21 @@ static pjsip_require_hdr *find_req_hdr(pjsip_msg *msg) pjsip_require_hdr *hreq; hreq = (pjsip_require_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_REQUIRE, NULL); + pjsip_msg_find_hdr(msg, PJSIP_H_REQUIRE, NULL); while (hreq) { - unsigned i; - for (i=0; icount; ++i) { - if (!pj_stricmp(&hreq->values[i], &tag_100rel)) { - return hreq; - } - } + unsigned i; + for (i=0; icount; ++i) { + if (!pj_stricmp(&hreq->values[i], &tag_100rel)) { + return hreq; + } + } - if ((void*)hreq->next == (void*)&msg->hdr) - return NULL; + if ((void*)hreq->next == (void*)&msg->hdr) + return NULL; - hreq = (pjsip_require_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_REQUIRE, hreq->next); + hreq = (pjsip_require_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_REQUIRE, hreq->next); } @@ -182,7 +181,7 @@ PJ_DEF(const pjsip_method*) pjsip_get_prack_method(void) PJ_DEF(pj_status_t) pjsip_100rel_init_module(pjsip_endpoint *endpt) { if (mod_100rel.mod.id != -1) - return PJ_SUCCESS; + return PJ_SUCCESS; return pjsip_endpt_register_module(endpt, &mod_100rel.mod); } @@ -220,8 +219,8 @@ PJ_DEF(pj_bool_t) pjsip_100rel_is_reliable(pjsip_rx_data *rdata) PJ_ASSERT_RETURN(msg->type == PJSIP_RESPONSE_MSG, PJ_FALSE); return msg->line.status.code > 100 && msg->line.status.code < 200 && - rdata->msg_info.require != NULL && - find_req_hdr(msg) != NULL; + rdata->msg_info.require != NULL && + find_req_hdr(msg) != NULL; } @@ -229,8 +228,8 @@ PJ_DEF(pj_bool_t) pjsip_100rel_is_reliable(pjsip_rx_data *rdata) * Create PRACK request for the incoming reliable provisional response. */ PJ_DEF(pj_status_t) pjsip_100rel_create_prack( pjsip_inv_session *inv, - pjsip_rx_data *rdata, - pjsip_tx_data **p_tdata) + pjsip_rx_data *rdata, + pjsip_tx_data **p_tdata) { dlg_data *dd; uac_state_t *uac_state = NULL; @@ -255,57 +254,57 @@ PJ_DEF(pj_status_t) pjsip_100rel_create_prack( pjsip_inv_session *inv, /* Check our assumptions */ pj_assert( tsx->role == PJSIP_ROLE_UAC && - tsx->method.id == PJSIP_INVITE_METHOD && - msg->line.status.code > 100 && - msg->line.status.code < 200); + tsx->method.id == PJSIP_INVITE_METHOD && + msg->line.status.code > 100 && + msg->line.status.code < 200); /* Get the RSeq header */ rseq_hdr = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(msg, &RSEQ, NULL); + pjsip_msg_find_hdr_by_name(msg, &RSEQ, NULL); if (rseq_hdr == NULL) { - PJ_LOG(4,(dd->inv->dlg->obj_name, - "Ignoring 100rel response with no RSeq header")); - return PJSIP_EMISSINGHDR; + PJ_LOG(4,(dd->inv->dlg->obj_name, + "Ignoring 100rel response with no RSeq header")); + return PJSIP_EMISSINGHDR; } rseq = (pj_uint32_t) pj_strtoul(&rseq_hdr->hvalue); /* Find UAC state for the specified call leg */ uac_state = dd->uac_state_list; while (uac_state) { - if (pj_stricmp(&uac_state->tag, to_tag)==0) - break; - uac_state = uac_state->next; + if (pj_stricmp(&uac_state->tag, to_tag)==0) + break; + uac_state = uac_state->next; } /* Create new UAC state if we don't have one */ if (uac_state == NULL) { - uac_state = PJ_POOL_ZALLOC_T(dd->inv->dlg->pool, uac_state_t); - uac_state->cseq = rdata->msg_info.cseq->cseq; - uac_state->rseq = rseq - 1; - pj_strdup(dd->inv->dlg->pool, &uac_state->tag, to_tag); - uac_state->next = dd->uac_state_list; - dd->uac_state_list = uac_state; + uac_state = PJ_POOL_ZALLOC_T(dd->inv->dlg->pool, uac_state_t); + uac_state->cseq = rdata->msg_info.cseq->cseq; + uac_state->rseq = rseq - 1; + pj_strdup(dd->inv->dlg->pool, &uac_state->tag, to_tag); + uac_state->next = dd->uac_state_list; + dd->uac_state_list = uac_state; } /* If this is from new INVITE transaction, reset UAC state. */ if (rdata->msg_info.cseq->cseq != uac_state->cseq) { - uac_state->cseq = rdata->msg_info.cseq->cseq; - uac_state->rseq = rseq - 1; + uac_state->cseq = rdata->msg_info.cseq->cseq; + uac_state->rseq = rseq - 1; } /* Ignore provisional response retransmission */ if (rseq <= uac_state->rseq) { - /* This should have been handled before */ - return PJ_EIGNORED; + /* This should have been handled before */ + return PJ_EIGNORED; /* Ignore provisional response with out-of-order RSeq */ } else if (rseq != uac_state->rseq + 1) { - PJ_LOG(4,(dd->inv->dlg->obj_name, - "Ignoring 100rel response because RSeq jump " - "(expecting %u, got %u)", - uac_state->rseq+1, rseq)); - return PJ_EIGNORED; + PJ_LOG(4,(dd->inv->dlg->obj_name, + "Ignoring 100rel response because RSeq jump " + "(expecting %u, got %u)", + uac_state->rseq+1, rseq)); + return PJ_EIGNORED; } /* Update our RSeq */ @@ -313,39 +312,39 @@ PJ_DEF(pj_status_t) pjsip_100rel_create_prack( pjsip_inv_session *inv, /* Create PRACK */ status = pjsip_dlg_create_request(dd->inv->dlg, &pjsip_prack_method, - -1, &tdata); + -1, &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* If this response is a forked response from a different call-leg, * update the req URI (https://github.com/pjsip/pjproject/issues/1364) */ if (pj_stricmp(&uac_state->tag, &dd->inv->dlg->remote.info->tag)) { - const pjsip_contact_hdr *mhdr; - - mhdr = (const pjsip_contact_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, - PJSIP_H_CONTACT, NULL); - if (!mhdr || !mhdr->uri) { - PJ_LOG(4,(dd->inv->dlg->obj_name, - "Ignoring 100rel response with no or " - "invalid Contact header")); - pjsip_tx_data_dec_ref(tdata); - return PJ_EIGNORED; - } - tdata->msg->line.req.uri = (pjsip_uri*) - pjsip_uri_clone(tdata->pool, mhdr->uri); + const pjsip_contact_hdr *mhdr; + + mhdr = (const pjsip_contact_hdr*) + pjsip_msg_find_hdr(rdata->msg_info.msg, + PJSIP_H_CONTACT, NULL); + if (!mhdr || !mhdr->uri) { + PJ_LOG(4,(dd->inv->dlg->obj_name, + "Ignoring 100rel response with no or " + "invalid Contact header")); + pjsip_tx_data_dec_ref(tdata); + return PJ_EIGNORED; + } + tdata->msg->line.req.uri = (pjsip_uri*) + pjsip_uri_clone(tdata->pool, mhdr->uri); } /* Create RAck header */ rack.ptr = rack_buf; rack.slen = pj_ansi_snprintf(rack.ptr, sizeof(rack_buf), - "%u %u %.*s", - rseq, rdata->msg_info.cseq->cseq, - (int)tsx->method.name.slen, - tsx->method.name.ptr); + "%u %u %.*s", + rseq, rdata->msg_info.cseq->cseq, + (int)tsx->method.name.slen, + tsx->method.name.ptr); if (rack.slen < 1 || rack.slen >= (int)sizeof(rack_buf)) { - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; } rack_hdr = pjsip_generic_string_hdr_create(tdata->pool, &RACK, &rack); pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) rack_hdr); @@ -361,7 +360,7 @@ PJ_DEF(pj_status_t) pjsip_100rel_create_prack( pjsip_inv_session *inv, * Send PRACK request. */ PJ_DEF(pj_status_t) pjsip_100rel_send_prack( pjsip_inv_session *inv, - pjsip_tx_data *tdata) + pjsip_tx_data *tdata) { dlg_data *dd; @@ -370,7 +369,7 @@ PJ_DEF(pj_status_t) pjsip_100rel_send_prack( pjsip_inv_session *inv, {pjsip_tx_data_dec_ref(tdata); return PJSIP_ENOTINITIALIZED; }); return pjsip_dlg_send_request(inv->dlg, tdata, - mod_100rel.mod.id, (void*) dd); + mod_100rel.mod.id, (void*) dd); } @@ -382,8 +381,8 @@ static void clear_all_responses(dlg_data *dd) tl = dd->uas_state->tx_data_list.next; while (tl != &dd->uas_state->tx_data_list) { - pjsip_tx_data_dec_ref(tl->tdata); - tl = tl->next; + pjsip_tx_data_dec_ref(tl->tdata); + tl = tl->next; } pj_list_init(&dd->uas_state->tx_data_list); } @@ -397,20 +396,20 @@ PJ_DEF(pj_status_t) pjsip_100rel_end_session(pjsip_inv_session *inv) dd = (dlg_data*) inv->dlg->mod_data[mod_100rel.mod.id]; if (!dd) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Make sure we don't have pending transmission */ if (dd->uas_state) { /* Cancel the retransmit timer */ - if (dd->uas_state->retransmit_timer.id) { - pjsip_endpt_cancel_timer(dd->inv->dlg->endpt, - &dd->uas_state->retransmit_timer); - dd->uas_state->retransmit_timer.id = PJ_FALSE; - } - if (!pj_list_empty(&dd->uas_state->tx_data_list)) { - /* Clear all pending responses (drop 'em) */ - clear_all_responses(dd); - } + if (dd->uas_state->retransmit_timer.id) { + pjsip_endpt_cancel_timer(dd->inv->dlg->endpt, + &dd->uas_state->retransmit_timer); + dd->uas_state->retransmit_timer.id = PJ_FALSE; + } + if (!pj_list_empty(&dd->uas_state->tx_data_list)) { + /* Clear all pending responses (drop 'em) */ + clear_all_responses(dd); + } } return PJ_SUCCESS; @@ -418,32 +417,32 @@ PJ_DEF(pj_status_t) pjsip_100rel_end_session(pjsip_inv_session *inv) static void parse_rack(const pj_str_t *rack, - pj_uint32_t *p_rseq, pj_int32_t *p_seq, - pj_str_t *p_method) + pj_uint32_t *p_rseq, pj_int32_t *p_seq, + pj_str_t *p_method) { const char *p = rack->ptr, *end = p + rack->slen; pj_str_t token; token.ptr = (char*)p; while (p < end && pj_isdigit(*p)) - ++p; + ++p; token.slen = p - token.ptr; *p_rseq = pj_strtoul(&token); ++p; token.ptr = (char*)p; while (p < end && pj_isdigit(*p)) - ++p; + ++p; token.slen = p - token.ptr; *p_seq = pj_strtoul(&token); ++p; if (p < end) { - p_method->ptr = (char*)p; - p_method->slen = end - p; + p_method->ptr = (char*)p; + p_method->slen = end - p; } else { - p_method->ptr = NULL; - p_method->slen = 0; + p_method->ptr = NULL; + p_method->slen = 0; } } @@ -452,7 +451,7 @@ static void parse_rack(const pj_str_t *rack, * Handle incoming PRACK request. */ PJ_DEF(pj_status_t) pjsip_100rel_on_rx_prack( pjsip_inv_session *inv, - pjsip_rx_data *rdata) + pjsip_rx_data *rdata) { dlg_data *dd; pjsip_transaction *tsx; @@ -471,39 +470,39 @@ PJ_DEF(pj_status_t) pjsip_100rel_on_rx_prack( pjsip_inv_session *inv, dd = (dlg_data*) inv->dlg->mod_data[mod_100rel.mod.id]; if (dd == NULL) { - /* UAC sends us PRACK while we didn't send reliable provisional - * response. Respond with 400 (?) - */ - const pj_str_t reason = pj_str("Unexpected PRACK"); - - status = pjsip_dlg_create_response(inv->dlg, rdata, 400, - &reason, &tdata); - if (status == PJ_SUCCESS) { - status = pjsip_dlg_send_response(inv->dlg, tsx, tdata); - } - return PJSIP_ENOTINITIALIZED; + /* UAC sends us PRACK while we didn't send reliable provisional + * response. Respond with 400 (?) + */ + const pj_str_t reason = pj_str("Unexpected PRACK"); + + status = pjsip_dlg_create_response(inv->dlg, rdata, 400, + &reason, &tdata); + if (status == PJ_SUCCESS) { + status = pjsip_dlg_send_response(inv->dlg, tsx, tdata); + } + return PJSIP_ENOTINITIALIZED; } /* Always reply with 200/OK for PRACK */ status = pjsip_dlg_create_response(inv->dlg, rdata, 200, NULL, &tdata); if (status == PJ_SUCCESS) { - status = pjsip_dlg_send_response(inv->dlg, tsx, tdata); + status = pjsip_dlg_send_response(inv->dlg, tsx, tdata); } /* Ignore if we don't have pending transmission */ if (dd->uas_state == NULL || pj_list_empty(&dd->uas_state->tx_data_list)) { - PJ_LOG(4,(dd->inv->dlg->obj_name, - "PRACK ignored - no pending response")); - return PJ_EIGNORED; + PJ_LOG(4,(dd->inv->dlg->obj_name, + "PRACK ignored - no pending response")); + return PJ_EIGNORED; } /* Find RAck header */ rack_hdr = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(msg, &RACK, NULL); + pjsip_msg_find_hdr_by_name(msg, &RACK, NULL); if (!rack_hdr) { - /* RAck header not found */ - PJ_LOG(4,(dd->inv->dlg->obj_name, "No RAck header")); - return PJSIP_EMISSINGHDR; + /* RAck header not found */ + PJ_LOG(4,(dd->inv->dlg->obj_name, "No RAck header")); + return PJSIP_EMISSINGHDR; } /* Parse RAck header */ @@ -512,38 +511,38 @@ PJ_DEF(pj_status_t) pjsip_100rel_on_rx_prack( pjsip_inv_session *inv, /* Match RAck against outgoing transmission */ if (rseq == dd->uas_state->tx_data_list.next->rseq && - cseq == dd->uas_state->cseq) + cseq == dd->uas_state->cseq) { - /* - * Yes this PRACK matches outgoing transmission. - */ - tx_data_list_t *tl = dd->uas_state->tx_data_list.next; - - if (dd->uas_state->retransmit_timer.id) { - pjsip_endpt_cancel_timer(dd->inv->dlg->endpt, - &dd->uas_state->retransmit_timer); - dd->uas_state->retransmit_timer.id = PJ_FALSE; - } - - /* Remove from the list */ - if (tl != &dd->uas_state->tx_data_list) { - pj_list_erase(tl); - - /* Destroy the response */ - pjsip_tx_data_dec_ref(tl->tdata); - } - - /* Schedule next packet */ - dd->uas_state->retransmit_count = 0; - if (!pj_list_empty(&dd->uas_state->tx_data_list)) { - on_retransmit(NULL, &dd->uas_state->retransmit_timer); - } + /* + * Yes this PRACK matches outgoing transmission. + */ + tx_data_list_t *tl = dd->uas_state->tx_data_list.next; + + if (dd->uas_state->retransmit_timer.id) { + pjsip_endpt_cancel_timer(dd->inv->dlg->endpt, + &dd->uas_state->retransmit_timer); + dd->uas_state->retransmit_timer.id = PJ_FALSE; + } + + /* Remove from the list */ + if (tl != &dd->uas_state->tx_data_list) { + pj_list_erase(tl); + + /* Destroy the response */ + pjsip_tx_data_dec_ref(tl->tdata); + } + + /* Schedule next packet */ + dd->uas_state->retransmit_count = 0; + if (!pj_list_empty(&dd->uas_state->tx_data_list)) { + on_retransmit(NULL, &dd->uas_state->retransmit_timer); + } } else { - /* No it doesn't match */ - PJ_LOG(4,(dd->inv->dlg->obj_name, - "Rx PRACK with no matching reliable response")); - return PJ_EIGNORED; + /* No it doesn't match */ + PJ_LOG(4,(dd->inv->dlg->obj_name, + "Rx PRACK with no matching reliable response")); + return PJ_EIGNORED; } return PJ_SUCCESS; @@ -555,7 +554,7 @@ PJ_DEF(pj_status_t) pjsip_100rel_on_rx_prack( pjsip_inv_session *inv, * and subsequently when the retransmission time elapses. */ static void on_retransmit(pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { dlg_data *dd; tx_data_list_t *tl; @@ -571,25 +570,25 @@ static void on_retransmit(pj_timer_heap_t *timer_heap, ++dd->uas_state->retransmit_count; if (dd->uas_state->retransmit_count >= 7) { - /* If a reliable provisional response is retransmitted for - 64*T1 seconds without reception of a corresponding PRACK, - the UAS SHOULD reject the original request with a 5xx - response. - */ - pj_str_t reason = pj_str("Reliable response timed out"); - pj_status_t status; - - /* Clear all pending responses */ - clear_all_responses(dd); - - /* Send 500 response */ - status = pjsip_inv_end_session(dd->inv, 500, &reason, &tdata); - if (status == PJ_SUCCESS && tdata) { - pjsip_dlg_send_response(dd->inv->dlg, - dd->inv->invite_tsx, - tdata); - } - return; + /* If a reliable provisional response is retransmitted for + 64*T1 seconds without reception of a corresponding PRACK, + the UAS SHOULD reject the original request with a 5xx + response. + */ + pj_str_t reason = pj_str("Reliable response timed out"); + pj_status_t status; + + /* Clear all pending responses */ + clear_all_responses(dd); + + /* Send 500 response */ + status = pjsip_inv_end_session(dd->inv, 500, &reason, &tdata); + if (status == PJ_SUCCESS && tdata) { + pjsip_dlg_send_response(dd->inv->dlg, + dd->inv->invite_tsx, + tdata); + } + return; } pj_assert(!pj_list_empty(&dd->uas_state->tx_data_list)); @@ -600,42 +599,42 @@ static void on_retransmit(pj_timer_heap_t *timer_heap, final = tdata->msg->line.status.code >= 200; if (dd->uas_state->retransmit_count == 1) { - pj_status_t status; - - status = pjsip_tsx_send_msg(dd->inv->invite_tsx, tdata); - if (status != PJ_SUCCESS) { - PJ_PERROR(3, (THIS_FILE, status, - "Failed to send message")); - return; - } + pj_status_t status; + + status = pjsip_tsx_send_msg(dd->inv->invite_tsx, tdata); + if (status != PJ_SUCCESS) { + PJ_PERROR(3, (THIS_FILE, status, + "Failed to send message")); + return; + } } else { - pjsip_tsx_retransmit_no_state(dd->inv->invite_tsx, tdata); + pjsip_tsx_retransmit_no_state(dd->inv->invite_tsx, tdata); } if (final) { - /* This is final response, which will be retransmitted by - * UA layer. There's no more task to do, so clear the - * transmission list and bail out. - */ - clear_all_responses(dd); - return; + /* This is final response, which will be retransmitted by + * UA layer. There's no more task to do, so clear the + * transmission list and bail out. + */ + clear_all_responses(dd); + return; } /* Schedule next retransmission */ if (dd->uas_state->retransmit_count < 6) { - delay.sec = 0; - delay.msec = (1 << dd->uas_state->retransmit_count) * - (long)pjsip_cfg()->tsx.t1; - pj_time_val_normalize(&delay); + delay.sec = 0; + delay.msec = (1 << dd->uas_state->retransmit_count) * + (long)pjsip_cfg()->tsx.t1; + pj_time_val_normalize(&delay); } else { - delay.sec = 1; - delay.msec = 500; + delay.sec = 1; + delay.msec = 500; } pjsip_endpt_schedule_timer(dd->inv->dlg->endpt, - &dd->uas_state->retransmit_timer, - &delay); + &dd->uas_state->retransmit_timer, + &delay); entry->id = PJ_TRUE; } @@ -649,9 +648,9 @@ static pj_bool_t has_sdp(dlg_data *dd) tl = dd->uas_state->tx_data_list.next; while (tl != &dd->uas_state->tx_data_list) { - if (tl->tdata->msg->body) - return PJ_TRUE; - tl = tl->next; + if (tl->tdata->msg->body) + return PJ_TRUE; + tl = tl->next; } return PJ_FALSE; @@ -660,7 +659,7 @@ static pj_bool_t has_sdp(dlg_data *dd) /* Send response reliably */ PJ_DEF(pj_status_t) pjsip_100rel_tx_response(pjsip_inv_session *inv, - pjsip_tx_data *tdata) + pjsip_tx_data *tdata) { pjsip_cseq_hdr *cseq_hdr; pjsip_generic_string_hdr *rseq_hdr; @@ -671,13 +670,13 @@ PJ_DEF(pj_status_t) pjsip_100rel_tx_response(pjsip_inv_session *inv, pj_status_t status; PJ_ASSERT_RETURN(tdata->msg->type == PJSIP_RESPONSE_MSG, - PJSIP_ENOTRESPONSEMSG); + PJSIP_ENOTRESPONSEMSG); status_code = tdata->msg->line.status.code; /* 100 response doesn't need PRACK */ if (status_code == 100) - return pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata); + return pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata); /* Get the 100rel data attached to this dialog */ @@ -697,183 +696,183 @@ PJ_DEF(pj_status_t) pjsip_100rel_tx_response(pjsip_inv_session *inv, /* Get CSeq header, and make sure this is INVITE response */ cseq_hdr = (pjsip_cseq_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL); + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL); PJ_ASSERT_RETURN(cseq_hdr != NULL, PJ_EBUG); PJ_ASSERT_RETURN(cseq_hdr->method.id == PJSIP_INVITE_METHOD, - PJ_EINVALIDOP); + PJ_EINVALIDOP); /* Remove existing Require header */ req_hdr = find_req_hdr(tdata->msg); if (req_hdr) { - pj_list_erase(req_hdr); + pj_list_erase(req_hdr); } /* Remove existing RSeq header */ rseq_hdr = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(tdata->msg, &RSEQ, NULL); + pjsip_msg_find_hdr_by_name(tdata->msg, &RSEQ, NULL); if (rseq_hdr) - pj_list_erase(rseq_hdr); + pj_list_erase(rseq_hdr); /* Different treatment for provisional and final response */ if (status_code/100 == 2) { - - /* RFC 3262 Section 3: UAS Behavior: + + /* RFC 3262 Section 3: UAS Behavior: - The UAS MAY send a final response to the initial request - before having received PRACKs for all unacknowledged - reliable provisional responses, unless the final response - is 2xx and any of the unacknowledged reliable provisional - responses contained a session description. In that case, - it MUST NOT send a final response until those provisional - responses are acknowledged. - */ - - if (dd->uas_state && has_sdp(dd)) { - /* Yes we have transmitted 1xx with SDP reliably. - * In this case, must queue the 2xx response. - */ - tx_data_list_t *tl; - - tl = PJ_POOL_ZALLOC_T(tdata->pool, tx_data_list_t); - tl->tdata = tdata; - tl->rseq = (pj_uint32_t)-1; - pj_list_push_back(&dd->uas_state->tx_data_list, tl); - - /* Will send later */ - status = PJ_SUCCESS; - - PJ_LOG(4,(dd->inv->dlg->obj_name, - "2xx response will be sent after PRACK")); - - } else if (dd->uas_state) { - /* - RFC 3262 Section 3: UAS Behavior: - - If the UAS does send a final response when reliable - responses are still unacknowledged, it SHOULD NOT - continue to retransmit the unacknowledged reliable - provisional responses, but it MUST be prepared to - process PRACK requests for those outstanding - responses. - */ - - PJ_LOG(4,(dd->inv->dlg->obj_name, - "No SDP sent so far, sending 2xx now")); - - /* Cancel the retransmit timer */ - if (dd->uas_state->retransmit_timer.id) { - pjsip_endpt_cancel_timer(dd->inv->dlg->endpt, - &dd->uas_state->retransmit_timer); - dd->uas_state->retransmit_timer.id = PJ_FALSE; - } - - /* Clear all pending responses (drop 'em) */ - clear_all_responses(dd); - - /* And transmit the 2xx response */ - status=pjsip_dlg_send_response(inv->dlg, - inv->invite_tsx, tdata); - - } else { - /* We didn't send any reliable provisional response */ - - /* Transmit the 2xx response */ - status=pjsip_dlg_send_response(inv->dlg, - inv->invite_tsx, tdata); - } - + The UAS MAY send a final response to the initial request + before having received PRACKs for all unacknowledged + reliable provisional responses, unless the final response + is 2xx and any of the unacknowledged reliable provisional + responses contained a session description. In that case, + it MUST NOT send a final response until those provisional + responses are acknowledged. + */ + + if (dd->uas_state && has_sdp(dd)) { + /* Yes we have transmitted 1xx with SDP reliably. + * In this case, must queue the 2xx response. + */ + tx_data_list_t *tl; + + tl = PJ_POOL_ZALLOC_T(tdata->pool, tx_data_list_t); + tl->tdata = tdata; + tl->rseq = (pj_uint32_t)-1; + pj_list_push_back(&dd->uas_state->tx_data_list, tl); + + /* Will send later */ + status = PJ_SUCCESS; + + PJ_LOG(4,(dd->inv->dlg->obj_name, + "2xx response will be sent after PRACK")); + + } else if (dd->uas_state) { + /* + RFC 3262 Section 3: UAS Behavior: + + If the UAS does send a final response when reliable + responses are still unacknowledged, it SHOULD NOT + continue to retransmit the unacknowledged reliable + provisional responses, but it MUST be prepared to + process PRACK requests for those outstanding + responses. + */ + + PJ_LOG(4,(dd->inv->dlg->obj_name, + "No SDP sent so far, sending 2xx now")); + + /* Cancel the retransmit timer */ + if (dd->uas_state->retransmit_timer.id) { + pjsip_endpt_cancel_timer(dd->inv->dlg->endpt, + &dd->uas_state->retransmit_timer); + dd->uas_state->retransmit_timer.id = PJ_FALSE; + } + + /* Clear all pending responses (drop 'em) */ + clear_all_responses(dd); + + /* And transmit the 2xx response */ + status=pjsip_dlg_send_response(inv->dlg, + inv->invite_tsx, tdata); + + } else { + /* We didn't send any reliable provisional response */ + + /* Transmit the 2xx response */ + status=pjsip_dlg_send_response(inv->dlg, + inv->invite_tsx, tdata); + } + } else if (status_code >= 300) { - - /* - RFC 3262 Section 3: UAS Behavior: - - If the UAS does send a final response when reliable - responses are still unacknowledged, it SHOULD NOT - continue to retransmit the unacknowledged reliable - provisional responses, but it MUST be prepared to - process PRACK requests for those outstanding - responses. - */ - - /* Cancel the retransmit timer */ - if (dd->uas_state && dd->uas_state->retransmit_timer.id) { - pjsip_endpt_cancel_timer(dd->inv->dlg->endpt, - &dd->uas_state->retransmit_timer); - dd->uas_state->retransmit_timer.id = PJ_FALSE; - - /* Clear all pending responses (drop 'em) */ - clear_all_responses(dd); - } - - /* And transmit the 2xx response */ - status=pjsip_dlg_send_response(inv->dlg, - inv->invite_tsx, tdata); - + + /* + RFC 3262 Section 3: UAS Behavior: + + If the UAS does send a final response when reliable + responses are still unacknowledged, it SHOULD NOT + continue to retransmit the unacknowledged reliable + provisional responses, but it MUST be prepared to + process PRACK requests for those outstanding + responses. + */ + + /* Cancel the retransmit timer */ + if (dd->uas_state && dd->uas_state->retransmit_timer.id) { + pjsip_endpt_cancel_timer(dd->inv->dlg->endpt, + &dd->uas_state->retransmit_timer); + dd->uas_state->retransmit_timer.id = PJ_FALSE; + + /* Clear all pending responses (drop 'em) */ + clear_all_responses(dd); + } + + /* And transmit the 2xx response */ + status=pjsip_dlg_send_response(inv->dlg, + inv->invite_tsx, tdata); + } else { - /* - * This is provisional response. - */ - char rseq_str[32]; - pj_str_t rseq; - tx_data_list_t *tl; - - /* Create UAS state if we don't have one */ - if (dd->uas_state == NULL) { - dd->uas_state = PJ_POOL_ZALLOC_T(inv->dlg->pool, - uas_state_t); - dd->uas_state->cseq = cseq_hdr->cseq; - dd->uas_state->rseq = (pj_rand() % 0x7FFF) + 1; - pj_list_init(&dd->uas_state->tx_data_list); - dd->uas_state->retransmit_timer.user_data = dd; - dd->uas_state->retransmit_timer.cb = &on_retransmit; - } - - /* Check that CSeq match */ - PJ_ASSERT_RETURN(cseq_hdr->cseq == dd->uas_state->cseq, - PJ_EINVALIDOP); - - /* Add Require header */ - req_hdr = pjsip_require_hdr_create(tdata->pool); - req_hdr->count = 1; - req_hdr->values[0] = tag_100rel; - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)req_hdr); - - /* Add RSeq header */ - pj_ansi_snprintf(rseq_str, sizeof(rseq_str), "%u", - dd->uas_state->rseq); - rseq = pj_str(rseq_str); - rseq_hdr = pjsip_generic_string_hdr_create(tdata->pool, - &RSEQ, &rseq); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)rseq_hdr); - - /* Create list entry for this response */ - tl = PJ_POOL_ZALLOC_T(tdata->pool, tx_data_list_t); - tl->tdata = tdata; - tl->rseq = dd->uas_state->rseq++; - - /* Add to queue if there's pending response, otherwise - * transmit immediately. - */ - if (!pj_list_empty(&dd->uas_state->tx_data_list)) { - - int code = tdata->msg->line.status.code; - - /* Will send later */ - pj_list_push_back(&dd->uas_state->tx_data_list, tl); - status = PJ_SUCCESS; - - PJ_LOG(4,(dd->inv->dlg->obj_name, - "Reliable %d response enqueued (%d pending)", - code, pj_list_size(&dd->uas_state->tx_data_list))); - - } else { - pj_list_push_back(&dd->uas_state->tx_data_list, tl); - - dd->uas_state->retransmit_count = 0; - on_retransmit(NULL, &dd->uas_state->retransmit_timer); - status = PJ_SUCCESS; - } - + /* + * This is provisional response. + */ + char rseq_str[32]; + pj_str_t rseq; + tx_data_list_t *tl; + + /* Create UAS state if we don't have one */ + if (dd->uas_state == NULL) { + dd->uas_state = PJ_POOL_ZALLOC_T(inv->dlg->pool, + uas_state_t); + dd->uas_state->cseq = cseq_hdr->cseq; + dd->uas_state->rseq = (pj_rand() % 0x7FFF) + 1; + pj_list_init(&dd->uas_state->tx_data_list); + dd->uas_state->retransmit_timer.user_data = dd; + dd->uas_state->retransmit_timer.cb = &on_retransmit; + } + + /* Check that CSeq match */ + PJ_ASSERT_RETURN(cseq_hdr->cseq == dd->uas_state->cseq, + PJ_EINVALIDOP); + + /* Add Require header */ + req_hdr = pjsip_require_hdr_create(tdata->pool); + req_hdr->count = 1; + req_hdr->values[0] = tag_100rel; + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)req_hdr); + + /* Add RSeq header */ + pj_ansi_snprintf(rseq_str, sizeof(rseq_str), "%u", + dd->uas_state->rseq); + rseq = pj_str(rseq_str); + rseq_hdr = pjsip_generic_string_hdr_create(tdata->pool, + &RSEQ, &rseq); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)rseq_hdr); + + /* Create list entry for this response */ + tl = PJ_POOL_ZALLOC_T(tdata->pool, tx_data_list_t); + tl->tdata = tdata; + tl->rseq = dd->uas_state->rseq++; + + /* Add to queue if there's pending response, otherwise + * transmit immediately. + */ + if (!pj_list_empty(&dd->uas_state->tx_data_list)) { + + int code = tdata->msg->line.status.code; + + /* Will send later */ + pj_list_push_back(&dd->uas_state->tx_data_list, tl); + status = PJ_SUCCESS; + + PJ_LOG(4,(dd->inv->dlg->obj_name, + "Reliable %d response enqueued (%d pending)", + code, pj_list_size(&dd->uas_state->tx_data_list))); + + } else { + pj_list_push_back(&dd->uas_state->tx_data_list, tl); + + dd->uas_state->retransmit_count = 0; + on_retransmit(NULL, &dd->uas_state->retransmit_timer); + status = PJ_SUCCESS; + } + } return status; diff --git a/pjsip/src/pjsip-ua/sip_inv.c b/pjsip/src/pjsip-ua/sip_inv.c index 9240b11e36..9a71f70db0 100644 --- a/pjsip/src/pjsip-ua/sip_inv.c +++ b/pjsip/src/pjsip-ua/sip_inv.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -42,24 +41,24 @@ * The offer/answer framework in this implementation assumes the occurence * of SDP in a particular request/response according to this table: - offer answer Note: + offer answer Note: ======================================================================== - INVITE X INVITE may contain offer - 18x/INVITE X X Response may contain offer or answer - 2xx/INVITE X X Response may contain offer or answer - ACK X ACK may contain answer + INVITE X INVITE may contain offer + 18x/INVITE X X Response may contain offer or answer + 2xx/INVITE X X Response may contain offer or answer + ACK X ACK may contain answer - PRACK X PRACK can only contain answer - 2xx/PRACK Response may not have offer nor answer + PRACK X PRACK can only contain answer + 2xx/PRACK Response may not have offer nor answer - UPDATE X UPDATE may only contain offer - 2xx/UPDATE X Response may only contain answer + UPDATE X UPDATE may only contain offer + 2xx/UPDATE X Response may only contain answer ======================================================================== * */ -#define THIS_FILE "sip_inv.c" +#define THIS_FILE "sip_inv.c" static const char *inv_state_names[] = { @@ -80,8 +79,8 @@ static const pjsip_method pjsip_update_method = { "UPDATE", 6 } }; -#define POOL_INIT_SIZE 256 -#define POOL_INC_SIZE 256 +#define POOL_INIT_SIZE 256 +#define POOL_INC_SIZE 256 /* * Static prototypes. @@ -90,7 +89,7 @@ static pj_status_t mod_inv_load(pjsip_endpoint *endpt); static pj_status_t mod_inv_unload(void); static pj_bool_t mod_inv_on_rx_request(pjsip_rx_data *rdata); static pj_bool_t mod_inv_on_rx_response(pjsip_rx_data *rdata); -static void mod_inv_on_tsx_state(pjsip_transaction*, pjsip_event*); +static void mod_inv_on_tsx_state(pjsip_transaction*, pjsip_event*); static void inv_on_state_null( pjsip_inv_session *inv, pjsip_event *e); static void inv_on_state_calling( pjsip_inv_session *inv, pjsip_event *e); @@ -101,22 +100,22 @@ static void inv_on_state_confirmed( pjsip_inv_session *inv, pjsip_event *e); static void inv_on_state_disconnected( pjsip_inv_session *inv, pjsip_event *e); static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv, - pjsip_transaction *tsx, - pjsip_rx_data *rdata); + pjsip_transaction *tsx, + pjsip_rx_data *rdata); static pj_status_t inv_negotiate_sdp( pjsip_inv_session *inv ); static pjsip_msg_body *create_sdp_body(pj_pool_t *pool, - const pjmedia_sdp_session *c_sdp); + const pjmedia_sdp_session *c_sdp); static pj_status_t process_answer( pjsip_inv_session *inv, - int st_code, - pjsip_tx_data *tdata, - const pjmedia_sdp_session *local_sdp); + int st_code, + pjsip_tx_data *tdata, + const pjmedia_sdp_session *local_sdp); static pj_status_t handle_timer_response(pjsip_inv_session *inv, - const pjsip_rx_data *rdata, - pj_bool_t end_sess_on_failure); + const pjsip_rx_data *rdata, + pj_bool_t end_sess_on_failure); static pj_bool_t inv_check_secure_dlg(pjsip_inv_session *inv, - pjsip_event *e); + pjsip_event *e); static int print_sdp(pjsip_msg_body *body, char *buf, pj_size_t len); @@ -133,25 +132,25 @@ static void (*inv_state_handler[])( pjsip_inv_session *inv, pjsip_event *e) = static struct mod_inv { - pjsip_module mod; - pjsip_endpoint *endpt; - pjsip_inv_callback cb; + pjsip_module mod; + pjsip_endpoint *endpt; + pjsip_inv_callback cb; } mod_inv = { { - NULL, NULL, /* prev, next. */ - { "mod-invite", 10 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_DIALOG_USAGE, /* Priority */ - &mod_inv_load, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - &mod_inv_unload, /* unload() */ - &mod_inv_on_rx_request, /* on_rx_request() */ - &mod_inv_on_rx_response, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - &mod_inv_on_tsx_state, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-invite", 10 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_DIALOG_USAGE, /* Priority */ + &mod_inv_load, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + &mod_inv_unload, /* unload() */ + &mod_inv_on_rx_request, /* on_rx_request() */ + &mod_inv_on_rx_response, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + &mod_inv_on_tsx_state, /* on_tsx_state() */ } }; @@ -159,13 +158,13 @@ static struct mod_inv /* Invite session data to be attached to transaction. */ struct tsx_inv_data { - pjsip_inv_session *inv; /* The invite session */ - pj_bool_t sdp_done; /* SDP negotiation done for this tsx? */ - pj_bool_t retrying; /* Resend (e.g. due to 401/407) */ - pj_str_t done_tag; /* To tag in RX response with answer */ - pj_bool_t done_early;/* Negotiation was done for early med? */ - pj_bool_t done_early_rel;/* Early med was realiable? */ - pj_bool_t has_sdp; /* Message with SDP? */ + pjsip_inv_session *inv; /* The invite session */ + pj_bool_t sdp_done; /* SDP negotiation done for this tsx? */ + pj_bool_t retrying; /* Resend (e.g. due to 401/407) */ + pj_str_t done_tag; /* To tag in RX response with answer */ + pj_bool_t done_early;/* Negotiation was done for early med? */ + pj_bool_t done_early_rel;/* Early med was realiable? */ + pj_bool_t has_sdp; /* Message with SDP? */ }; /* @@ -174,16 +173,16 @@ struct tsx_inv_data static pj_status_t mod_inv_load(pjsip_endpoint *endpt) { pj_str_t allowed[] = {{"INVITE", 6}, {"ACK",3}, {"BYE",3}, {"CANCEL",6}, - { "UPDATE", 6}}; + { "UPDATE", 6}}; pj_str_t accepted = { "application/sdp", 15 }; /* Register supported methods: INVITE, ACK, BYE, CANCEL, UPDATE */ pjsip_endpt_add_capability(endpt, &mod_inv.mod, PJSIP_H_ALLOW, NULL, - PJ_ARRAY_SIZE(allowed), allowed); + PJ_ARRAY_SIZE(allowed), allowed); /* Register "application/sdp" in Accept header */ pjsip_endpt_add_capability(endpt, &mod_inv.mod, PJSIP_H_ACCEPT, NULL, - 1, &accepted); + 1, &accepted); return PJ_SUCCESS; } @@ -212,16 +211,16 @@ PJ_DEF(pj_status_t) pjsip_inv_add_ref( pjsip_inv_session *inv ) static void inv_session_destroy(pjsip_inv_session *inv) { if (inv->last_ack) { - pjsip_tx_data_dec_ref(inv->last_ack); - inv->last_ack = NULL; + pjsip_tx_data_dec_ref(inv->last_ack); + inv->last_ack = NULL; } if (inv->invite_req) { - pjsip_tx_data_dec_ref(inv->invite_req); - inv->invite_req = NULL; + pjsip_tx_data_dec_ref(inv->invite_req); + inv->invite_req = NULL; } if (inv->pending_bye) { - pjsip_tx_data_dec_ref(inv->pending_bye); - inv->pending_bye = NULL; + pjsip_tx_data_dec_ref(inv->pending_bye); + inv->pending_bye = NULL; } pjsip_100rel_end_session(inv); pjsip_timer_end_session(inv); @@ -260,7 +259,7 @@ PJ_DEF(pj_status_t) pjsip_inv_dec_ref( pjsip_inv_session *inv ) * Set session state. */ static void inv_set_state(pjsip_inv_session *inv, pjsip_inv_state state, - pjsip_event *e) + pjsip_event *e) { pjsip_inv_state prev_state = inv->state; pj_bool_t dont_notify = PJ_FALSE; @@ -271,38 +270,38 @@ static void inv_set_state(pjsip_inv_session *inv, pjsip_inv_state state, * https://github.com/pjsip/pjproject/issues/1318 */ if (state==PJSIP_INV_STATE_CALLING && - (inv->cb_called & (1 << PJSIP_INV_STATE_CALLING)) != 0) + (inv->cb_called & (1 << PJSIP_INV_STATE_CALLING)) != 0) { - dont_notify = PJ_TRUE; + dont_notify = PJ_TRUE; } /* If state is confirmed, check that SDP negotiation is done, * otherwise disconnect the session. */ if (state == PJSIP_INV_STATE_CONFIRMED) { - struct tsx_inv_data *tsx_inv_data = NULL; + struct tsx_inv_data *tsx_inv_data = NULL; - if (inv->invite_tsx) { - tsx_inv_data = (struct tsx_inv_data*) - inv->invite_tsx->mod_data[mod_inv.mod.id]; - } + if (inv->invite_tsx) { + tsx_inv_data = (struct tsx_inv_data*) + inv->invite_tsx->mod_data[mod_inv.mod.id]; + } - if ((tsx_inv_data && !tsx_inv_data->sdp_done) && - (!inv->neg || pjmedia_sdp_neg_get_state(inv->neg)!= - PJMEDIA_SDP_NEG_STATE_DONE)) - { - pjsip_tx_data *bye; + if ((tsx_inv_data && !tsx_inv_data->sdp_done) && + (!inv->neg || pjmedia_sdp_neg_get_state(inv->neg)!= + PJMEDIA_SDP_NEG_STATE_DONE)) + { + pjsip_tx_data *bye; - PJ_LOG(4,(inv->obj_name, "SDP offer/answer incomplete, ending the " - "session")); + PJ_LOG(4,(inv->obj_name, "SDP offer/answer incomplete, ending the " + "session")); - status = pjsip_inv_end_session(inv, PJSIP_SC_NOT_ACCEPTABLE, - NULL, &bye); - if (status == PJ_SUCCESS && bye) - status = pjsip_inv_send_msg(inv, bye); + status = pjsip_inv_end_session(inv, PJSIP_SC_NOT_ACCEPTABLE, + NULL, &bye); + if (status == PJ_SUCCESS && bye) + status = pjsip_inv_send_msg(inv, bye); - return; - } + return; + } } /* Set state. */ @@ -310,7 +309,7 @@ static void inv_set_state(pjsip_inv_session *inv, pjsip_inv_state state, /* If state is DISCONNECTED, cause code MUST have been set. */ pj_assert(inv->state != PJSIP_INV_STATE_DISCONNECTED || - inv->cause != 0); + inv->cause != 0); /* Mark the callback as called for this state */ inv->cb_called |= (1 << state); @@ -322,7 +321,7 @@ static void inv_set_state(pjsip_inv_session *inv, pjsip_inv_state state, */ pjsip_inv_add_ref(inv); if (mod_inv.cb.on_state_changed && inv->notify && !dont_notify) - (*mod_inv.cb.on_state_changed)(inv, e); + (*mod_inv.cb.on_state_changed)(inv, e); pjsip_inv_dec_ref(inv); /* The above callback may change the state, so we need to be careful here @@ -336,10 +335,10 @@ static void inv_set_state(pjsip_inv_session *inv, pjsip_inv_state state, * inv may have already been destroyed. */ if (state == PJSIP_INV_STATE_DISCONNECTED && - prev_state != PJSIP_INV_STATE_DISCONNECTED && - inv->state == PJSIP_INV_STATE_DISCONNECTED) + prev_state != PJSIP_INV_STATE_DISCONNECTED && + inv->state == PJSIP_INV_STATE_DISCONNECTED) { - pjsip_inv_dec_ref(inv); + pjsip_inv_dec_ref(inv); } } @@ -348,16 +347,16 @@ static void inv_set_state(pjsip_inv_session *inv, pjsip_inv_state state, * Set cause code. */ static void inv_set_cause(pjsip_inv_session *inv, int cause_code, - const pj_str_t *cause_text) + const pj_str_t *cause_text) { if ((cause_code > inv->cause) || inv->pending_bye) { - inv->cause = (pjsip_status_code) cause_code; - if (cause_text) - pj_strdup(inv->pool, &inv->cause_text, cause_text); - else if (cause_code/100 == 2) - inv->cause_text = pj_str("Normal call clearing"); - else - inv->cause_text = *pjsip_get_status_text(cause_code); + inv->cause = (pjsip_status_code) cause_code; + if (cause_text) + pj_strdup(inv->pool, &inv->cause_text, cause_text); + else if (cause_code/100 == 2) + inv->cause_text = pj_str("Normal call clearing"); + else + inv->cause_text = *pjsip_get_status_text(cause_code); } } @@ -367,7 +366,7 @@ static void inv_set_cause(pjsip_inv_session *inv, int cause_code, * This applies for both ACK and PRACK requests. */ static const pjmedia_sdp_session *inv_has_pending_answer(pjsip_inv_session *inv, - pjsip_transaction *tsx) + pjsip_transaction *tsx) { pjmedia_sdp_neg_state neg_state; const pjmedia_sdp_session *sdp = NULL; @@ -377,47 +376,47 @@ static const pjmedia_sdp_session *inv_has_pending_answer(pjsip_inv_session *inv, /* Start nego when appropriate. */ neg_state = inv->neg ? pjmedia_sdp_neg_get_state(inv->neg) : - PJMEDIA_SDP_NEG_STATE_NULL; + PJMEDIA_SDP_NEG_STATE_NULL; if (neg_state == PJMEDIA_SDP_NEG_STATE_DONE) { - /* Nothing to do */ + /* Nothing to do */ } else if (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO && - pjmedia_sdp_neg_has_local_answer(inv->neg) ) + pjmedia_sdp_neg_has_local_answer(inv->neg) ) { - struct tsx_inv_data *tsx_inv_data; - struct tsx_inv_data dummy; - - /* Get invite session's transaction data. - * Note that tsx may be NULL, for example when application sends - * delayed ACK request (at this time, the original INVITE - * transaction may have been destroyed. - */ - if (tsx) { - tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; - } else { - tsx_inv_data = &dummy; - pj_bzero(&dummy, sizeof(dummy)); - dummy.inv = inv; - } - - status = inv_negotiate_sdp(inv); - if (status != PJ_SUCCESS) - return NULL; - - /* Mark this transaction has having SDP offer/answer done. */ - tsx_inv_data->sdp_done = 1; - - status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp); + struct tsx_inv_data *tsx_inv_data; + struct tsx_inv_data dummy; + + /* Get invite session's transaction data. + * Note that tsx may be NULL, for example when application sends + * delayed ACK request (at this time, the original INVITE + * transaction may have been destroyed. + */ + if (tsx) { + tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; + } else { + tsx_inv_data = &dummy; + pj_bzero(&dummy, sizeof(dummy)); + dummy.inv = inv; + } + + status = inv_negotiate_sdp(inv); + if (status != PJ_SUCCESS) + return NULL; + + /* Mark this transaction has having SDP offer/answer done. */ + tsx_inv_data->sdp_done = 1; + + status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp); } else { - /* This remark is only valid for ACK. - PJ_LOG(4,(inv->dlg->obj_name, - "FYI, the SDP negotiator state (%s) is in a mess " - "when sending this ACK/PRACK request", - pjmedia_sdp_neg_state_str(neg_state))); - */ + /* This remark is only valid for ACK. + PJ_LOG(4,(inv->dlg->obj_name, + "FYI, the SDP negotiator state (%s) is in a mess " + "when sending this ACK/PRACK request", + pjmedia_sdp_neg_state_str(neg_state))); + */ } return sdp; @@ -429,18 +428,18 @@ static const pjmedia_sdp_session *inv_has_pending_answer(pjsip_inv_session *inv, static void inv_perform_pending_bye(pjsip_inv_session *inv) { if (inv->pending_bye) { - pjsip_tx_data *bye = inv->pending_bye; - pj_status_t status; + pjsip_tx_data *bye = inv->pending_bye; + pj_status_t status; - PJ_LOG(4,(inv->dlg->obj_name, "Sending pending BYE")); + PJ_LOG(4,(inv->dlg->obj_name, "Sending pending BYE")); - inv->pending_bye = NULL; - status = pjsip_inv_send_msg(inv, bye); + inv->pending_bye = NULL; + status = pjsip_inv_send_msg(inv, bye); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(inv->dlg->obj_name, status, - "Failed sending pending BYE")); - } + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(inv->dlg->obj_name, status, + "Failed sending pending BYE")); + } } } @@ -454,12 +453,12 @@ static pj_status_t inv_send_ack(pjsip_inv_session *inv, pjsip_event *e) pj_status_t status; if (e->type == PJSIP_EVENT_TSX_STATE) - rdata = e->body.tsx_state.src.rdata; + rdata = e->body.tsx_state.src.rdata; else if (e->type == PJSIP_EVENT_RX_MSG) - rdata = e->body.rx_msg.rdata; + rdata = e->body.rx_msg.rdata; else { - pj_assert(!"Unsupported event type"); - return PJ_EBUG; + pj_assert(!"Unsupported event type"); + return PJ_EBUG; } /* Note that with https://github.com/pjsip/pjproject/issues/1725, this @@ -468,33 +467,33 @@ static pj_status_t inv_send_ack(pjsip_inv_session *inv, pjsip_event *e) */ PJ_LOG(5,(inv->obj_name, "Received %s, sending ACK", - pjsip_rx_data_get_info(rdata))); + pjsip_rx_data_get_info(rdata))); /* Check if we have cached ACK request and if we have sent it. * Must not use the cached ACK if it's still marked as pending * by transport (#1011). */ if (inv->last_ack && rdata->msg_info.cseq->cseq == inv->last_ack_cseq && - inv->last_ack->tp_info.transport != NULL && - !inv->last_ack->is_pending) + inv->last_ack->tp_info.transport != NULL && + !inv->last_ack->is_pending) { - pjsip_tx_data_add_ref(inv->last_ack); + pjsip_tx_data_add_ref(inv->last_ack); } else if (mod_inv.cb.on_send_ack) { - /* If application handles ACK transmission manually, just notify the - * callback - */ - PJ_LOG(5,(inv->obj_name, "Received %s, notifying application callback", - pjsip_rx_data_get_info(rdata))); + /* If application handles ACK transmission manually, just notify the + * callback + */ + PJ_LOG(5,(inv->obj_name, "Received %s, notifying application callback", + pjsip_rx_data_get_info(rdata))); - (*mod_inv.cb.on_send_ack)(inv, rdata); - return PJ_SUCCESS; + (*mod_inv.cb.on_send_ack)(inv, rdata); + return PJ_SUCCESS; } else { - status = pjsip_inv_create_ack(inv, rdata->msg_info.cseq->cseq, - &inv->last_ack); - if (status != PJ_SUCCESS) - return status; + status = pjsip_inv_create_ack(inv, rdata->msg_info.cseq->cseq, + &inv->last_ack); + if (status != PJ_SUCCESS) + return status; } PJSIP_EVENT_INIT_TX_MSG(ack_e, inv->last_ack); @@ -502,9 +501,9 @@ static pj_status_t inv_send_ack(pjsip_inv_session *inv, pjsip_event *e) /* Send ACK */ status = pjsip_dlg_send_request(inv->dlg, inv->last_ack, -1, NULL); if (status != PJ_SUCCESS) { - /* Better luck next time */ - pj_assert(!"Unable to send ACK!"); - return status; + /* Better luck next time */ + pj_assert(!"Unable to send ACK!"); + return status; } @@ -513,7 +512,7 @@ static pj_status_t inv_send_ack(pjsip_inv_session *inv, pjsip_event *e) * (this may have been a late 200/OK response. */ if (inv->state < PJSIP_INV_STATE_CONFIRMED) { - inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &ack_e); + inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &ack_e); } else if (inv->state == PJSIP_INV_STATE_DISCONNECTED && inv->last_ack) { /* Avoid possible leaked tdata when invite session is already * destroyed. @@ -543,7 +542,7 @@ static pj_bool_t mod_inv_on_rx_request(pjsip_rx_data *rdata) /* Only wants to receive request from a dialog. */ dlg = pjsip_rdata_get_dlg(rdata); if (dlg == NULL) - return PJ_FALSE; + return PJ_FALSE; inv = (pjsip_inv_session*) dlg->mod_data[mod_inv.mod.id]; @@ -554,17 +553,17 @@ static pj_bool_t mod_inv_on_rx_request(pjsip_rx_data *rdata) method = &rdata->msg_info.msg->line.req.method; if (method->id == PJSIP_INVITE_METHOD) { - return PJ_TRUE; + return PJ_TRUE; } /* BYE and CANCEL must have existing invite session */ if (method->id == PJSIP_BYE_METHOD || - method->id == PJSIP_CANCEL_METHOD) + method->id == PJSIP_CANCEL_METHOD) { - if (inv == NULL) - return PJ_FALSE; + if (inv == NULL) + return PJ_FALSE; - return PJ_TRUE; + return PJ_TRUE; } /* On receipt ACK request, when state is CONNECTING, @@ -572,73 +571,73 @@ static pj_bool_t mod_inv_on_rx_request(pjsip_rx_data *rdata) */ if (method->id == PJSIP_ACK_METHOD && inv) { - /* Ignore if we don't have INVITE in progress */ - if (!inv->invite_tsx) { - return PJ_TRUE; - } - - /* Ignore ACK if pending INVITE transaction has not finished. */ - if (inv->invite_tsx->state < PJSIP_TSX_STATE_COMPLETED) { - return PJ_TRUE; - } - - /* Ignore ACK with different CSeq - * https://github.com/pjsip/pjproject/issues/1391 - */ - if (rdata->msg_info.cseq->cseq != inv->invite_tsx->cseq) { - return PJ_TRUE; - } - - /* Terminate INVITE transaction, if it's still present. */ - if (inv->invite_tsx->state <= PJSIP_TSX_STATE_COMPLETED) { - /* Before we terminate INVITE transaction, process the SDP - * in the ACK request, if any. - * Only do this when invite state is not already disconnected - * (https://github.com/pjsip/pjproject/issues/640). - */ - if (inv->state < PJSIP_INV_STATE_DISCONNECTED) { - inv_check_sdp_in_incoming_msg(inv, inv->invite_tsx, rdata); - - /* Check if local offer got no SDP answer and INVITE session - * is in CONFIRMED state. - */ - if (pjmedia_sdp_neg_get_state(inv->neg)== - PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER && - inv->state==PJSIP_INV_STATE_CONFIRMED) - { - pjmedia_sdp_neg_cancel_offer(inv->neg); - } - } - - /* Now we can terminate the INVITE transaction */ - pj_assert(inv->invite_tsx->status_code >= 200); - pjsip_tsx_terminate(inv->invite_tsx, - inv->invite_tsx->status_code); - inv->invite_tsx = NULL; - if (inv->last_answer) { - pjsip_tx_data_dec_ref(inv->last_answer); - inv->last_answer = NULL; - } - } - - /* On receipt of ACK, only set state to confirmed when state - * is CONNECTING (e.g. we don't want to set the state to confirmed - * when we receive ACK retransmission after sending non-2xx!) - */ - if (inv->state == PJSIP_INV_STATE_CONNECTING) { - pjsip_event event; - - PJSIP_EVENT_INIT_RX_MSG(event, rdata); - inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &event); - - /* Send pending BYE if any: - * https://github.com/pjsip/pjproject/issues/1712 - * Do this after setting the state to CONFIRMED, so that we - * have consistent CONFIRMED state between caller and callee. - */ - if (inv->pending_bye) - inv_perform_pending_bye(inv); - } + /* Ignore if we don't have INVITE in progress */ + if (!inv->invite_tsx) { + return PJ_TRUE; + } + + /* Ignore ACK if pending INVITE transaction has not finished. */ + if (inv->invite_tsx->state < PJSIP_TSX_STATE_COMPLETED) { + return PJ_TRUE; + } + + /* Ignore ACK with different CSeq + * https://github.com/pjsip/pjproject/issues/1391 + */ + if (rdata->msg_info.cseq->cseq != inv->invite_tsx->cseq) { + return PJ_TRUE; + } + + /* Terminate INVITE transaction, if it's still present. */ + if (inv->invite_tsx->state <= PJSIP_TSX_STATE_COMPLETED) { + /* Before we terminate INVITE transaction, process the SDP + * in the ACK request, if any. + * Only do this when invite state is not already disconnected + * (https://github.com/pjsip/pjproject/issues/640). + */ + if (inv->state < PJSIP_INV_STATE_DISCONNECTED) { + inv_check_sdp_in_incoming_msg(inv, inv->invite_tsx, rdata); + + /* Check if local offer got no SDP answer and INVITE session + * is in CONFIRMED state. + */ + if (pjmedia_sdp_neg_get_state(inv->neg)== + PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER && + inv->state==PJSIP_INV_STATE_CONFIRMED) + { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } + } + + /* Now we can terminate the INVITE transaction */ + pj_assert(inv->invite_tsx->status_code >= 200); + pjsip_tsx_terminate(inv->invite_tsx, + inv->invite_tsx->status_code); + inv->invite_tsx = NULL; + if (inv->last_answer) { + pjsip_tx_data_dec_ref(inv->last_answer); + inv->last_answer = NULL; + } + } + + /* On receipt of ACK, only set state to confirmed when state + * is CONNECTING (e.g. we don't want to set the state to confirmed + * when we receive ACK retransmission after sending non-2xx!) + */ + if (inv->state == PJSIP_INV_STATE_CONNECTING) { + pjsip_event event; + + PJSIP_EVENT_INIT_RX_MSG(event, rdata); + inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &event); + + /* Send pending BYE if any: + * https://github.com/pjsip/pjproject/issues/1712 + * Do this after setting the state to CONFIRMED, so that we + * have consistent CONFIRMED state between caller and callee. + */ + if (inv->pending_bye) + inv_perform_pending_bye(inv); + } } return PJ_FALSE; @@ -648,20 +647,20 @@ static pj_bool_t mod_inv_on_rx_request(pjsip_rx_data *rdata) * 2xx or 422 response of INVITE/UPDATE request. */ static pj_status_t handle_timer_response(pjsip_inv_session *inv, - const pjsip_rx_data *rdata, - pj_bool_t end_sess_on_failure) + const pjsip_rx_data *rdata, + pj_bool_t end_sess_on_failure) { pjsip_status_code st_code; pj_status_t status; status = pjsip_timer_process_resp(inv, rdata, &st_code); if (status != PJ_SUCCESS && end_sess_on_failure) { - pjsip_tx_data *tdata; - pj_status_t status2; + pjsip_tx_data *tdata; + pj_status_t status2; - status2 = pjsip_inv_end_session(inv, st_code, NULL, &tdata); - if (tdata && status2 == PJ_SUCCESS) - pjsip_inv_send_msg(inv, tdata); + status2 = pjsip_inv_end_session(inv, st_code, NULL, &tdata); + if (tdata && status2 == PJ_SUCCESS) + pjsip_inv_send_msg(inv, tdata); } return status; @@ -685,37 +684,37 @@ static pj_bool_t mod_inv_on_rx_response(pjsip_rx_data *rdata) /* Ignore responses outside dialog */ if (dlg == NULL) - return PJ_FALSE; + return PJ_FALSE; /* Ignore responses not belonging to invite session */ inv = pjsip_dlg_get_inv_session(dlg); if (inv == NULL) - return PJ_FALSE; + return PJ_FALSE; /* This MAY be retransmission of 2xx response to INVITE. * If it is, we need to send ACK. */ if (msg->type == PJSIP_RESPONSE_MSG && msg->line.status.code/100==2 && - rdata->msg_info.cseq->method.id == PJSIP_INVITE_METHOD) + rdata->msg_info.cseq->method.id == PJSIP_INVITE_METHOD) { - /* The code inside "if" is called the second time 200/OK - * retransmission is received. Also handle the situation - * when we have another re-INVITE on going and 200/OK - * retransmission is received. See: - * https://github.com/pjsip/pjproject/issues/1725. - * Also send ACK for 200/OK of pending re-INVITE after call is - * disconnected (see https://github.com/pjsip/pjproject/issues/1755). - */ - if (inv->invite_tsx == NULL || - inv->state == PJSIP_INV_STATE_DISCONNECTED || - (inv->last_ack && inv->last_ack_cseq==rdata->msg_info.cseq->cseq)) - { - pjsip_event e; - - PJSIP_EVENT_INIT_RX_MSG(e, rdata); - inv_send_ack(inv, &e); - return PJ_TRUE; - } + /* The code inside "if" is called the second time 200/OK + * retransmission is received. Also handle the situation + * when we have another re-INVITE on going and 200/OK + * retransmission is received. See: + * https://github.com/pjsip/pjproject/issues/1725. + * Also send ACK for 200/OK of pending re-INVITE after call is + * disconnected (see https://github.com/pjsip/pjproject/issues/1755). + */ + if (inv->invite_tsx == NULL || + inv->state == PJSIP_INV_STATE_DISCONNECTED || + (inv->last_ack && inv->last_ack_cseq==rdata->msg_info.cseq->cseq)) + { + pjsip_event e; + + PJSIP_EVENT_INIT_RX_MSG(e, rdata); + inv_send_ack(inv, &e); + return PJ_TRUE; + } } /* No other processing needs to be done here. */ @@ -735,11 +734,11 @@ static void mod_inv_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e) dlg = pjsip_tsx_get_dlg(tsx); if (dlg == NULL) - return; + return; inv = pjsip_dlg_get_inv_session(dlg); if (inv == NULL) - return; + return; /* Call state handler for the invite session. */ (*inv_state_handler[inv->state])(inv, e); @@ -749,12 +748,12 @@ static void mod_inv_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e) * after the transaction is terminated. */ if (tsx->state==PJSIP_TSX_STATE_TERMINATED && tsx == inv->invite_tsx) { - inv->invite_tsx = NULL; + inv->invite_tsx = NULL; - if (inv->last_answer) { - pjsip_tx_data_dec_ref(inv->last_answer); - inv->last_answer = NULL; - } + if (inv->last_answer) { + pjsip_tx_data_dec_ref(inv->last_answer); + inv->last_answer = NULL; + } } /* Call on_tsx_state. CANCEL request is a special case and has been @@ -764,7 +763,7 @@ static void mod_inv_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e) !(tsx->method.id==PJSIP_CANCEL_METHOD && e->body.tsx_state.type==PJSIP_EVENT_RX_MSG)) { - (*mod_inv.cb.on_tsx_state_changed)(inv, tsx, e); + (*mod_inv.cb.on_tsx_state_changed)(inv, tsx, e); } /* Clear invite transaction when tsx is confirmed. @@ -772,13 +771,13 @@ static void mod_inv_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e) * terminated, but this didn't work when ACK has the same Via branch * value as the INVITE (see https://github.com/pjsip/pjproject/issues/113) */ - if (tsx->state>=PJSIP_TSX_STATE_CONFIRMED && tsx == inv->invite_tsx) { - inv->invite_tsx = NULL; + if (tsx->state>=PJSIP_TSX_STATE_CONFIRMED && tsx == inv->invite_tsx) { + inv->invite_tsx = NULL; - if (inv->last_answer) { - pjsip_tx_data_dec_ref(inv->last_answer); - inv->last_answer = NULL; - } + if (inv->last_answer) { + pjsip_tx_data_dec_ref(inv->last_answer); + inv->last_answer = NULL; + } } } @@ -795,22 +794,22 @@ static pj_bool_t tx_data_has_sdp(const pjsip_tx_data *tdata) pjsip_media_type_init2(&app_sdp, "application", "sdp"); if (body && - pj_stricmp(&body->content_type.type, &app_sdp.type)==0 && - pj_stricmp(&body->content_type.subtype, &app_sdp.subtype)==0) + pj_stricmp(&body->content_type.type, &app_sdp.type)==0 && + pj_stricmp(&body->content_type.subtype, &app_sdp.subtype)==0) { - return PJ_TRUE; + return PJ_TRUE; } else if (body && - pj_stricmp2(&body->content_type.type, "multipart") && - (pj_stricmp2(&body->content_type.subtype, "mixed")==0 || - pj_stricmp2(&body->content_type.subtype, "alternative")==0)) + pj_stricmp2(&body->content_type.type, "multipart") && + (pj_stricmp2(&body->content_type.subtype, "mixed")==0 || + pj_stricmp2(&body->content_type.subtype, "alternative")==0)) { - pjsip_multipart_part *part; + pjsip_multipart_part *part; - part = pjsip_multipart_find_part(body, &app_sdp, NULL); - if (part) { - return PJ_TRUE; - } + part = pjsip_multipart_find_part(body, &app_sdp, NULL); + if (part) { + return PJ_TRUE; + } } return PJ_FALSE; @@ -821,7 +820,7 @@ static pj_bool_t tx_data_has_sdp(const pjsip_tx_data *tdata) * Initialize the invite module. */ PJ_DEF(pj_status_t) pjsip_inv_usage_init( pjsip_endpoint *endpt, - const pjsip_inv_callback *cb) + const pjsip_inv_callback *cb) { pj_status_t status; @@ -842,7 +841,7 @@ PJ_DEF(pj_status_t) pjsip_inv_usage_init( pjsip_endpoint *endpt, /* Register the module. */ status = pjsip_endpt_register_module(endpt, &mod_inv.mod); if (status != PJ_SUCCESS) - return status; + return status; return PJ_SUCCESS; } @@ -872,8 +871,8 @@ PJ_DEF(pjsip_inv_session*) pjsip_dlg_get_inv_session(pjsip_dialog *dlg) PJ_DEF(const char *) pjsip_inv_state_name(pjsip_inv_state state) { PJ_ASSERT_RETURN(state >= PJSIP_INV_STATE_NULL && - state <= PJSIP_INV_STATE_DISCONNECTED, - "??"); + state <= PJSIP_INV_STATE_DISCONNECTED, + "??"); return inv_state_names[state]; } @@ -882,9 +881,9 @@ PJ_DEF(const char *) pjsip_inv_state_name(pjsip_inv_state state) * Create UAC invite session. */ PJ_DEF(pj_status_t) pjsip_inv_create_uac( pjsip_dialog *dlg, - const pjmedia_sdp_session *local_sdp, - unsigned options, - pjsip_inv_session **p_inv) + const pjmedia_sdp_session *local_sdp, + unsigned options, + pjsip_inv_session **p_inv) { pjsip_inv_session *inv; pj_status_t status; @@ -897,11 +896,11 @@ PJ_DEF(pj_status_t) pjsip_inv_create_uac( pjsip_dialog *dlg, /* Normalize options */ if (options & PJSIP_INV_REQUIRE_100REL) - options |= PJSIP_INV_SUPPORT_100REL; + options |= PJSIP_INV_SUPPORT_100REL; if (options & PJSIP_INV_REQUIRE_TIMER) - options |= PJSIP_INV_SUPPORT_TIMER; + options |= PJSIP_INV_SUPPORT_TIMER; if (options & PJSIP_INV_REQUIRE_TRICKLE_ICE) - options |= PJSIP_INV_SUPPORT_TRICKLE_ICE; + options |= PJSIP_INV_SUPPORT_TRICKLE_ICE; /* Create the session */ inv = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_inv_session); @@ -909,8 +908,8 @@ PJ_DEF(pj_status_t) pjsip_inv_create_uac( pjsip_dialog *dlg, status = pj_atomic_create(dlg->pool, 0, &inv->ref_cnt); if (status != PJ_SUCCESS) { - pjsip_dlg_dec_lock(dlg); - return status; + pjsip_dlg_dec_lock(dlg); + return status; } inv->pool = dlg->pool; @@ -925,28 +924,28 @@ PJ_DEF(pj_status_t) pjsip_inv_create_uac( pjsip_dialog *dlg, /* (using inv->obj_name as temporary variable for pool names */ pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg->pool); inv->pool_prov = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name, - POOL_INIT_SIZE, POOL_INC_SIZE); + POOL_INIT_SIZE, POOL_INC_SIZE); inv->pool_active = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name, - POOL_INIT_SIZE, POOL_INC_SIZE); + POOL_INIT_SIZE, POOL_INC_SIZE); /* Object name will use the same dialog pointer. */ pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg); /* Create negotiator if local_sdp is specified. */ if (local_sdp) { - status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, - local_sdp, &inv->neg); - if (status != PJ_SUCCESS) { - pjsip_dlg_dec_lock(dlg); - return status; - } + status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, + local_sdp, &inv->neg); + if (status != PJ_SUCCESS) { + pjsip_dlg_dec_lock(dlg); + return status; + } } /* Register invite as dialog usage. */ status = pjsip_dlg_add_usage(dlg, &mod_inv.mod, inv); if (status != PJ_SUCCESS) { - pjsip_dlg_dec_lock(dlg); - return status; + pjsip_dlg_dec_lock(dlg); + return status; } /* Increment dialog session */ @@ -962,7 +961,7 @@ PJ_DEF(pj_status_t) pjsip_inv_create_uac( pjsip_dialog *dlg, pjsip_dlg_dec_lock(dlg); PJ_LOG(5,(inv->obj_name, "UAC invite session created for dialog %s", - dlg->obj_name)); + dlg->obj_name)); return PJ_SUCCESS; } @@ -989,12 +988,12 @@ PJ_DEF(pjsip_sdp_info*) pjsip_get_sdp_info(pj_pool_t *pool, } if (msg_media_type) { - msg_type = msg_media_type; + msg_type = msg_media_type; } else { - if (body->content_type.type.slen == 0) { - return sdp_info; - } - msg_type = &body->content_type; + if (body->content_type.type.slen == 0) { + return sdp_info; + } + msg_type = &body->content_type; } if (!search_media_type) { @@ -1008,12 +1007,12 @@ PJ_DEF(pjsip_sdp_info*) pjsip_get_sdp_info(pj_pool_t *pool, if (pjsip_media_type_cmp(msg_type, &search_type, PJ_FALSE) == 0) { - /* - * If the print_body function is print_sdp, we know that - * body->data is a pjmedia_sdp_session object and came from - * a tx_data. If not, it's the text representation of the - * sdp from an rx_data. - */ + /* + * If the print_body function is print_sdp, we know that + * body->data is a pjmedia_sdp_session object and came from + * a tx_data. If not, it's the text representation of the + * sdp from an rx_data. + */ if (body->print_body == print_sdp) { sdp_info->sdp = body->data; } else { @@ -1021,7 +1020,7 @@ PJ_DEF(pjsip_sdp_info*) pjsip_get_sdp_info(pj_pool_t *pool, sdp_info->body.slen = body->len; } } else if (pjsip_media_type_cmp(&multipart_mixed, msg_type, PJ_FALSE) == 0 || - pjsip_media_type_cmp(&multipart_alternative, msg_type, PJ_FALSE) == 0) + pjsip_media_type_cmp(&multipart_alternative, msg_type, PJ_FALSE) == 0) { pjsip_multipart_part *part; part = pjsip_multipart_find_part(body, &search_type, NULL); @@ -1041,7 +1040,7 @@ PJ_DEF(pjsip_sdp_info*) pjsip_get_sdp_info(pj_pool_t *pool, * of the sdp either, we can also just return. */ if (sdp_info->sdp || !sdp_info->body.ptr) { - return sdp_info; + return sdp_info; } /* @@ -1049,16 +1048,16 @@ PJ_DEF(pjsip_sdp_info*) pjsip_get_sdp_info(pj_pool_t *pool, * to parse it to create a pjmedia_sdp_session object. */ status = pjmedia_sdp_parse(pool, - sdp_info->body.ptr, - sdp_info->body.slen, - &sdp_info->sdp); + sdp_info->body.ptr, + sdp_info->body.slen, + &sdp_info->sdp); if (status == PJ_SUCCESS) - status = pjmedia_sdp_validate2(sdp_info->sdp, PJ_FALSE); + status = pjmedia_sdp_validate2(sdp_info->sdp, PJ_FALSE); if (status != PJ_SUCCESS) { - sdp_info->sdp = NULL; - PJ_PERROR(1, (THIS_FILE, status, - "Error parsing/validating SDP body")); + sdp_info->sdp = NULL; + PJ_PERROR(1, (THIS_FILE, status, + "Error parsing/validating SDP body")); } sdp_info->sdp_err = status; @@ -1074,7 +1073,7 @@ PJ_DEF(pjsip_rdata_sdp_info*) pjsip_rdata_get_sdp_info2( pjsip_rdata_sdp_info *sdp_info; if (rdata->endpt_info.mod_data[mod_inv.mod.id]) { - return (pjsip_rdata_sdp_info *)rdata->endpt_info.mod_data[mod_inv.mod.id]; + return (pjsip_rdata_sdp_info *)rdata->endpt_info.mod_data[mod_inv.mod.id]; } /* @@ -1082,12 +1081,12 @@ PJ_DEF(pjsip_rdata_sdp_info*) pjsip_rdata_get_sdp_info2( * make sure. */ if (rdata->msg_info.ctype) { - msg_media_type = &rdata->msg_info.ctype->media; + msg_media_type = &rdata->msg_info.ctype->media; } sdp_info = pjsip_get_sdp_info(rdata->tp_info.pool, - rdata->msg_info.msg->body, - msg_media_type, - search_media_type); + rdata->msg_info.msg->body, + msg_media_type, + search_media_type); rdata->endpt_info.mod_data[mod_inv.mod.id] = sdp_info; return sdp_info; @@ -1107,7 +1106,7 @@ PJ_DEF(pjsip_tdata_sdp_info*) pjsip_tdata_get_sdp_info2( pjsip_tdata_sdp_info *sdp_info; if (tdata->mod_data[mod_inv.mod.id]) { - return (pjsip_tdata_sdp_info *)tdata->mod_data[mod_inv.mod.id]; + return (pjsip_tdata_sdp_info *)tdata->mod_data[mod_inv.mod.id]; } /* * tdata won't usually have a Content-Type header at this point @@ -1115,13 +1114,13 @@ PJ_DEF(pjsip_tdata_sdp_info*) pjsip_tdata_get_sdp_info2( */ ctype_hdr = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTENT_TYPE, NULL); if (ctype_hdr) { - msg_media_type = &ctype_hdr->media; + msg_media_type = &ctype_hdr->media; } sdp_info = pjsip_get_sdp_info(tdata->pool, - tdata->msg->body, - msg_media_type, - search_media_type); + tdata->msg->body, + msg_media_type, + search_media_type); tdata->mod_data[mod_inv.mod.id] = sdp_info; return sdp_info; @@ -1137,12 +1136,12 @@ PJ_DEF(pjsip_tdata_sdp_info*) pjsip_tdata_get_sdp_info(pjsip_tx_data *tdata) */ PJ_DEF(pj_status_t) pjsip_inv_verify_request3(pjsip_rx_data *rdata, pj_pool_t *tmp_pool, - unsigned *options, - const pjmedia_sdp_session *r_sdp, - const pjmedia_sdp_session *l_sdp, - pjsip_dialog *dlg, - pjsip_endpoint *endpt, - pjsip_tx_data **p_tdata) + unsigned *options, + const pjmedia_sdp_session *r_sdp, + const pjmedia_sdp_session *l_sdp, + pjsip_dialog *dlg, + pjsip_endpoint *endpt, + pjsip_tx_data **p_tdata) { pjsip_msg *msg = NULL; pjsip_allow_hdr *allow = NULL; @@ -1163,13 +1162,13 @@ PJ_DEF(pj_status_t) pjsip_inv_verify_request3(pjsip_rx_data *rdata, /* Normalize options */ if (*options & PJSIP_INV_REQUIRE_100REL) - *options |= PJSIP_INV_SUPPORT_100REL; + *options |= PJSIP_INV_SUPPORT_100REL; if (*options & PJSIP_INV_REQUIRE_TIMER) - *options |= PJSIP_INV_SUPPORT_TIMER; + *options |= PJSIP_INV_SUPPORT_TIMER; if (*options & PJSIP_INV_REQUIRE_ICE) - *options |= PJSIP_INV_SUPPORT_ICE; + *options |= PJSIP_INV_SUPPORT_ICE; if (*options & PJSIP_INV_REQUIRE_TRICKLE_ICE) - *options |= PJSIP_INV_SUPPORT_TRICKLE_ICE; + *options |= PJSIP_INV_SUPPORT_TRICKLE_ICE; if (rdata) { /* Get the message in rdata */ @@ -1177,8 +1176,8 @@ PJ_DEF(pj_status_t) pjsip_inv_verify_request3(pjsip_rx_data *rdata, /* Must be INVITE request. */ PJ_ASSERT_RETURN(msg && msg->type == PJSIP_REQUEST_MSG && - msg->line.req.method.id == PJSIP_INVITE_METHOD, - PJ_EINVAL); + msg->line.req.method.id == PJSIP_INVITE_METHOD, + PJ_EINVAL); } /* If tdata is specified, then either dlg or endpt must be specified */ @@ -1193,173 +1192,173 @@ PJ_DEF(pj_status_t) pjsip_inv_verify_request3(pjsip_rx_data *rdata, /* Check the Contact header */ if (msg) { c_hdr = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_CONTACT, NULL); + pjsip_msg_find_hdr(msg, PJSIP_H_CONTACT, NULL); } if (msg && (!c_hdr || !c_hdr->uri)) { /* Missing Contact header or Contact contains "*" */ - pjsip_warning_hdr *w; - pj_str_t warn_text; - - warn_text = pj_str("Bad/missing Contact header"); - w = pjsip_warning_hdr_create(tmp_pool, 399, - pjsip_endpt_name(endpt), - &warn_text); - if (w) { - pj_list_push_back(&res_hdr_list, w); - } + pjsip_warning_hdr *w; + pj_str_t warn_text; + + warn_text = pj_str("Bad/missing Contact header"); + w = pjsip_warning_hdr_create(tmp_pool, 399, + pjsip_endpt_name(endpt), + &warn_text); + if (w) { + pj_list_push_back(&res_hdr_list, w); + } - code = PJSIP_SC_BAD_REQUEST; - status = PJSIP_ERRNO_FROM_SIP_STATUS(code); - goto on_return; + code = PJSIP_SC_BAD_REQUEST; + status = PJSIP_ERRNO_FROM_SIP_STATUS(code); + goto on_return; } /* Ticket #1735: Check Contact/Record-Route header in a secure dialog. */ if (pjsip_cfg()->endpt.disable_secure_dlg_check == PJ_FALSE && - msg && PJSIP_URI_SCHEME_IS_SIPS(msg->line.req.uri)) + msg && PJSIP_URI_SCHEME_IS_SIPS(msg->line.req.uri)) { - /* Check Contact header */ - if (!PJSIP_URI_SCHEME_IS_SIPS(c_hdr->uri)) - status = PJSIP_ESESSIONINSECURE; - - /* Check top Record-Route header */ - if (status == PJ_SUCCESS) { - pjsip_rr_hdr *r = (pjsip_rr_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_RECORD_ROUTE, - NULL); - if (r && !PJSIP_URI_SCHEME_IS_SIPS(&r->name_addr)) { - /* Not "sips", check if it is "sip" and has param - * "transport=tls". - */ - if (PJSIP_URI_SCHEME_IS_SIP(&r->name_addr)) { - pjsip_sip_uri *sip_uri = (pjsip_sip_uri*) - pjsip_uri_get_uri(r->name_addr.uri); - if (pj_stricmp2(&sip_uri->transport_param, "tls")!=0) - status = PJSIP_ESESSIONINSECURE; - } else { - /* Not "sips" nor "sip", treat it as insecure? */ - status = PJSIP_ESESSIONINSECURE; - } - } - } - - if (status != PJ_SUCCESS) { - pjsip_warning_hdr *w; - pj_str_t warn_text = pj_str("SIPS Required"); - w = pjsip_warning_hdr_create(tmp_pool, 381, - pjsip_endpt_name(endpt), - &warn_text); - if (w) { - pj_list_push_back(&res_hdr_list, w); - } - code = PJSIP_SC_TEMPORARILY_UNAVAILABLE; - goto on_return; - } + /* Check Contact header */ + if (!PJSIP_URI_SCHEME_IS_SIPS(c_hdr->uri)) + status = PJSIP_ESESSIONINSECURE; + + /* Check top Record-Route header */ + if (status == PJ_SUCCESS) { + pjsip_rr_hdr *r = (pjsip_rr_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_RECORD_ROUTE, + NULL); + if (r && !PJSIP_URI_SCHEME_IS_SIPS(&r->name_addr)) { + /* Not "sips", check if it is "sip" and has param + * "transport=tls". + */ + if (PJSIP_URI_SCHEME_IS_SIP(&r->name_addr)) { + pjsip_sip_uri *sip_uri = (pjsip_sip_uri*) + pjsip_uri_get_uri(r->name_addr.uri); + if (pj_stricmp2(&sip_uri->transport_param, "tls")!=0) + status = PJSIP_ESESSIONINSECURE; + } else { + /* Not "sips" nor "sip", treat it as insecure? */ + status = PJSIP_ESESSIONINSECURE; + } + } + } + + if (status != PJ_SUCCESS) { + pjsip_warning_hdr *w; + pj_str_t warn_text = pj_str("SIPS Required"); + w = pjsip_warning_hdr_create(tmp_pool, 381, + pjsip_endpt_name(endpt), + &warn_text); + if (w) { + pj_list_push_back(&res_hdr_list, w); + } + code = PJSIP_SC_TEMPORARILY_UNAVAILABLE; + goto on_return; + } } /* Check the request body, see if it's something that we support, * only when the body hasn't been parsed before. */ if (r_sdp == NULL && rdata) { - sdp_info = pjsip_rdata_get_sdp_info(rdata); + sdp_info = pjsip_rdata_get_sdp_info(rdata); } else { - sdp_info = NULL; + sdp_info = NULL; } if (r_sdp==NULL && msg && msg->body) { - /* Check if body really contains SDP. */ - if (sdp_info->body.ptr == NULL && !PJSIP_INV_ACCEPT_UNKNOWN_BODY) { - /* Couldn't find "application/sdp" */ - code = PJSIP_SC_UNSUPPORTED_MEDIA_TYPE; - status = PJSIP_ERRNO_FROM_SIP_STATUS(code); + /* Check if body really contains SDP. */ + if (sdp_info->body.ptr == NULL && !PJSIP_INV_ACCEPT_UNKNOWN_BODY) { + /* Couldn't find "application/sdp" */ + code = PJSIP_SC_UNSUPPORTED_MEDIA_TYPE; + status = PJSIP_ERRNO_FROM_SIP_STATUS(code); - if (p_tdata) { - /* Add Accept header to response */ - pjsip_accept_hdr *acc; + if (p_tdata) { + /* Add Accept header to response */ + pjsip_accept_hdr *acc; - acc = pjsip_accept_hdr_create(tmp_pool); - PJ_ASSERT_RETURN(acc, PJ_ENOMEM); - acc->values[acc->count++] = pj_str("application/sdp"); - pj_list_push_back(&res_hdr_list, acc); - } + acc = pjsip_accept_hdr_create(tmp_pool); + PJ_ASSERT_RETURN(acc, PJ_ENOMEM); + acc->values[acc->count++] = pj_str("application/sdp"); + pj_list_push_back(&res_hdr_list, acc); + } - goto on_return; - } + goto on_return; + } - if (sdp_info->sdp_err != PJ_SUCCESS) { - /* Unparseable or invalid SDP */ - code = PJSIP_SC_BAD_REQUEST; + if (sdp_info->sdp_err != PJ_SUCCESS) { + /* Unparseable or invalid SDP */ + code = PJSIP_SC_BAD_REQUEST; - if (p_tdata) { - /* Add Warning header. */ - pjsip_warning_hdr *w; + if (p_tdata) { + /* Add Warning header. */ + pjsip_warning_hdr *w; - w = pjsip_warning_hdr_create_from_status(tmp_pool, - pjsip_endpt_name(endpt), - sdp_info->sdp_err); - PJ_ASSERT_RETURN(w, PJ_ENOMEM); + w = pjsip_warning_hdr_create_from_status(tmp_pool, + pjsip_endpt_name(endpt), + sdp_info->sdp_err); + PJ_ASSERT_RETURN(w, PJ_ENOMEM); - pj_list_push_back(&res_hdr_list, w); - } + pj_list_push_back(&res_hdr_list, w); + } - goto on_return; - } + goto on_return; + } - r_sdp = sdp_info->sdp; + r_sdp = sdp_info->sdp; } if (r_sdp) { - /* Negotiate with local SDP */ - if (l_sdp) { - pjmedia_sdp_neg *neg; - - /* Local SDP must be valid! */ - status = pjmedia_sdp_validate(l_sdp); - if (status != PJ_SUCCESS) { - pj_assert(!"Invalid local SDP"); - code = PJSIP_SC_INTERNAL_SERVER_ERROR; - goto on_return; - } - - /* Create SDP negotiator */ - status = pjmedia_sdp_neg_create_w_remote_offer( - tmp_pool, l_sdp, r_sdp, &neg); - if (status != PJ_SUCCESS) { - pj_assert(!"Failed creating SDP negotiator"); - code = PJSIP_SC_INTERNAL_SERVER_ERROR; - goto on_return; - } - - /* Negotiate SDP */ - status = pjmedia_sdp_neg_negotiate(tmp_pool, neg, 0); - if (status != PJ_SUCCESS) { - - /* Incompatible media */ - code = PJSIP_SC_NOT_ACCEPTABLE_HERE; - - if (p_tdata) { - pjsip_accept_hdr *acc; - pjsip_warning_hdr *w; - - /* Add Warning header. */ - w = pjsip_warning_hdr_create_from_status( - tmp_pool, - pjsip_endpt_name(endpt), status); - PJ_ASSERT_RETURN(w, PJ_ENOMEM); - - pj_list_push_back(&res_hdr_list, w); - - /* Add Accept header to response */ - acc = pjsip_accept_hdr_create(tmp_pool); - PJ_ASSERT_RETURN(acc, PJ_ENOMEM); - acc->values[acc->count++] = pj_str("application/sdp"); - pj_list_push_back(&res_hdr_list, acc); - - } - - goto on_return; - } - } + /* Negotiate with local SDP */ + if (l_sdp) { + pjmedia_sdp_neg *neg; + + /* Local SDP must be valid! */ + status = pjmedia_sdp_validate(l_sdp); + if (status != PJ_SUCCESS) { + pj_assert(!"Invalid local SDP"); + code = PJSIP_SC_INTERNAL_SERVER_ERROR; + goto on_return; + } + + /* Create SDP negotiator */ + status = pjmedia_sdp_neg_create_w_remote_offer( + tmp_pool, l_sdp, r_sdp, &neg); + if (status != PJ_SUCCESS) { + pj_assert(!"Failed creating SDP negotiator"); + code = PJSIP_SC_INTERNAL_SERVER_ERROR; + goto on_return; + } + + /* Negotiate SDP */ + status = pjmedia_sdp_neg_negotiate(tmp_pool, neg, 0); + if (status != PJ_SUCCESS) { + + /* Incompatible media */ + code = PJSIP_SC_NOT_ACCEPTABLE_HERE; + + if (p_tdata) { + pjsip_accept_hdr *acc; + pjsip_warning_hdr *w; + + /* Add Warning header. */ + w = pjsip_warning_hdr_create_from_status( + tmp_pool, + pjsip_endpt_name(endpt), status); + PJ_ASSERT_RETURN(w, PJ_ENOMEM); + + pj_list_push_back(&res_hdr_list, w); + + /* Add Accept header to response */ + acc = pjsip_accept_hdr_create(tmp_pool); + PJ_ASSERT_RETURN(acc, PJ_ENOMEM); + acc->values[acc->count++] = pj_str("application/sdp"); + pj_list_push_back(&res_hdr_list, acc); + + } + + goto on_return; + } + } } /* Check supported methods, see if peer supports UPDATE. @@ -1371,129 +1370,129 @@ PJ_DEF(pj_status_t) pjsip_inv_verify_request3(pjsip_rx_data *rdata, NULL); } if (allow) { - unsigned i; - const pj_str_t STR_UPDATE = { "UPDATE", 6 }; + unsigned i; + const pj_str_t STR_UPDATE = { "UPDATE", 6 }; - for (i=0; icount; ++i) { - if (pj_stricmp(&allow->values[i], &STR_UPDATE)==0) - break; - } + for (i=0; icount; ++i) { + if (pj_stricmp(&allow->values[i], &STR_UPDATE)==0) + break; + } - if (i != allow->count) { - /* UPDATE is present in Allow */ - *options |= PJSIP_INV_SUPPORT_UPDATE; - } + if (i != allow->count) { + /* UPDATE is present in Allow */ + *options |= PJSIP_INV_SUPPORT_UPDATE; + } } /* Check Supported header */ if (msg) { sup_hdr = (pjsip_supported_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_SUPPORTED, NULL); + pjsip_msg_find_hdr(msg, PJSIP_H_SUPPORTED, NULL); } if (sup_hdr) { - unsigned i; - const pj_str_t STR_100REL = { "100rel", 6}; - const pj_str_t STR_TIMER = { "timer", 5}; - const pj_str_t STR_ICE = { "ice", 3 }; - const pj_str_t STR_TRICKLE_ICE = { "trickle-ice", 11 }; - - for (i=0; icount; ++i) { - if (pj_stricmp(&sup_hdr->values[i], &STR_100REL)==0) - rem_option |= PJSIP_INV_SUPPORT_100REL; - else if (pj_stricmp(&sup_hdr->values[i], &STR_TIMER)==0) - rem_option |= PJSIP_INV_SUPPORT_TIMER; - else if (pj_stricmp(&sup_hdr->values[i], &STR_ICE)==0) - rem_option |= PJSIP_INV_SUPPORT_ICE; - else if (pj_stricmp(&sup_hdr->values[i], &STR_TRICKLE_ICE)==0) - rem_option |= PJSIP_INV_SUPPORT_TRICKLE_ICE; - } + unsigned i; + const pj_str_t STR_100REL = { "100rel", 6}; + const pj_str_t STR_TIMER = { "timer", 5}; + const pj_str_t STR_ICE = { "ice", 3 }; + const pj_str_t STR_TRICKLE_ICE = { "trickle-ice", 11 }; + + for (i=0; icount; ++i) { + if (pj_stricmp(&sup_hdr->values[i], &STR_100REL)==0) + rem_option |= PJSIP_INV_SUPPORT_100REL; + else if (pj_stricmp(&sup_hdr->values[i], &STR_TIMER)==0) + rem_option |= PJSIP_INV_SUPPORT_TIMER; + else if (pj_stricmp(&sup_hdr->values[i], &STR_ICE)==0) + rem_option |= PJSIP_INV_SUPPORT_ICE; + else if (pj_stricmp(&sup_hdr->values[i], &STR_TRICKLE_ICE)==0) + rem_option |= PJSIP_INV_SUPPORT_TRICKLE_ICE; + } } /* Check Require header */ if (msg) { req_hdr = (pjsip_require_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_REQUIRE, NULL); + pjsip_msg_find_hdr(msg, PJSIP_H_REQUIRE, NULL); } if (req_hdr) { - unsigned i; - const pj_str_t STR_100REL = { "100rel", 6}; - const pj_str_t STR_REPLACES = { "replaces", 8 }; - const pj_str_t STR_TIMER = { "timer", 5 }; - const pj_str_t STR_ICE = { "ice", 3 }; - const pj_str_t STR_TRICKLE_ICE = { "trickle-ice", 11 }; - unsigned unsupp_cnt = 0; - pj_str_t unsupp_tags[PJSIP_GENERIC_ARRAY_MAX_COUNT]; - - for (i=0; icount; ++i) { - if ((*options & PJSIP_INV_SUPPORT_100REL) && - pj_stricmp(&req_hdr->values[i], &STR_100REL)==0) - { - rem_option |= PJSIP_INV_REQUIRE_100REL; - - } else if ((*options & PJSIP_INV_SUPPORT_TIMER) && - pj_stricmp(&req_hdr->values[i], &STR_TIMER)==0) - { - rem_option |= PJSIP_INV_REQUIRE_TIMER; - - } else if (pj_stricmp(&req_hdr->values[i], &STR_REPLACES)==0) { - pj_bool_t supp; - - supp = pjsip_endpt_has_capability(endpt, PJSIP_H_SUPPORTED, - NULL, &STR_REPLACES); - if (!supp) - unsupp_tags[unsupp_cnt++] = req_hdr->values[i]; - } else if ((*options & PJSIP_INV_SUPPORT_ICE) && - pj_stricmp(&req_hdr->values[i], &STR_ICE)==0) - { - rem_option |= PJSIP_INV_REQUIRE_ICE; - - } else if ((*options & PJSIP_INV_SUPPORT_TRICKLE_ICE) && - pj_stricmp(&req_hdr->values[i], &STR_TRICKLE_ICE)==0) - { - rem_option |= PJSIP_INV_REQUIRE_TRICKLE_ICE; - - } else if (!pjsip_endpt_has_capability(endpt, PJSIP_H_SUPPORTED, - NULL, &req_hdr->values[i])) - { - /* Unknown/unsupported extension tag! */ - unsupp_tags[unsupp_cnt++] = req_hdr->values[i]; - } - } - - /* Check if there are required tags that we don't support */ - if (unsupp_cnt) { - - code = PJSIP_SC_BAD_EXTENSION; - status = PJSIP_ERRNO_FROM_SIP_STATUS(code); - - if (p_tdata) { - pjsip_unsupported_hdr *unsupp_hdr; - const pjsip_hdr *h; - - /* Add Unsupported header. */ - unsupp_hdr = pjsip_unsupported_hdr_create(tmp_pool); - PJ_ASSERT_RETURN(unsupp_hdr != NULL, PJ_ENOMEM); - - unsupp_hdr->count = unsupp_cnt; - for (i=0; ivalues[i] = unsupp_tags[i]; - - pj_list_push_back(&res_hdr_list, unsupp_hdr); - - /* Add Supported header. */ - h = pjsip_endpt_get_capability(endpt, PJSIP_H_SUPPORTED, - NULL); - pj_assert(h); - if (h) { - sup_hdr = (pjsip_supported_hdr*) - pjsip_hdr_clone(tmp_pool, h); - pj_list_push_back(&res_hdr_list, sup_hdr); - } - } - - goto on_return; - } + unsigned i; + const pj_str_t STR_100REL = { "100rel", 6}; + const pj_str_t STR_REPLACES = { "replaces", 8 }; + const pj_str_t STR_TIMER = { "timer", 5 }; + const pj_str_t STR_ICE = { "ice", 3 }; + const pj_str_t STR_TRICKLE_ICE = { "trickle-ice", 11 }; + unsigned unsupp_cnt = 0; + pj_str_t unsupp_tags[PJSIP_GENERIC_ARRAY_MAX_COUNT]; + + for (i=0; icount; ++i) { + if ((*options & PJSIP_INV_SUPPORT_100REL) && + pj_stricmp(&req_hdr->values[i], &STR_100REL)==0) + { + rem_option |= PJSIP_INV_REQUIRE_100REL; + + } else if ((*options & PJSIP_INV_SUPPORT_TIMER) && + pj_stricmp(&req_hdr->values[i], &STR_TIMER)==0) + { + rem_option |= PJSIP_INV_REQUIRE_TIMER; + + } else if (pj_stricmp(&req_hdr->values[i], &STR_REPLACES)==0) { + pj_bool_t supp; + + supp = pjsip_endpt_has_capability(endpt, PJSIP_H_SUPPORTED, + NULL, &STR_REPLACES); + if (!supp) + unsupp_tags[unsupp_cnt++] = req_hdr->values[i]; + } else if ((*options & PJSIP_INV_SUPPORT_ICE) && + pj_stricmp(&req_hdr->values[i], &STR_ICE)==0) + { + rem_option |= PJSIP_INV_REQUIRE_ICE; + + } else if ((*options & PJSIP_INV_SUPPORT_TRICKLE_ICE) && + pj_stricmp(&req_hdr->values[i], &STR_TRICKLE_ICE)==0) + { + rem_option |= PJSIP_INV_REQUIRE_TRICKLE_ICE; + + } else if (!pjsip_endpt_has_capability(endpt, PJSIP_H_SUPPORTED, + NULL, &req_hdr->values[i])) + { + /* Unknown/unsupported extension tag! */ + unsupp_tags[unsupp_cnt++] = req_hdr->values[i]; + } + } + + /* Check if there are required tags that we don't support */ + if (unsupp_cnt) { + + code = PJSIP_SC_BAD_EXTENSION; + status = PJSIP_ERRNO_FROM_SIP_STATUS(code); + + if (p_tdata) { + pjsip_unsupported_hdr *unsupp_hdr; + const pjsip_hdr *h; + + /* Add Unsupported header. */ + unsupp_hdr = pjsip_unsupported_hdr_create(tmp_pool); + PJ_ASSERT_RETURN(unsupp_hdr != NULL, PJ_ENOMEM); + + unsupp_hdr->count = unsupp_cnt; + for (i=0; ivalues[i] = unsupp_tags[i]; + + pj_list_push_back(&res_hdr_list, unsupp_hdr); + + /* Add Supported header. */ + h = pjsip_endpt_get_capability(endpt, PJSIP_H_SUPPORTED, + NULL); + pj_assert(h); + if (h) { + sup_hdr = (pjsip_supported_hdr*) + pjsip_hdr_clone(tmp_pool, h); + pj_list_push_back(&res_hdr_list, sup_hdr); + } + } + + goto on_return; + } } /* Check if there are local requirements that are not supported @@ -1506,98 +1505,98 @@ PJ_DEF(pj_status_t) pjsip_inv_verify_request3(pjsip_rx_data *rdata, ((*options & PJSIP_INV_REQUIRE_TRICKLE_ICE)!=0 && (rem_option & PJSIP_INV_SUPPORT_TRICKLE_ICE)==0))) { - code = PJSIP_SC_EXTENSION_REQUIRED; - status = PJSIP_ERRNO_FROM_SIP_STATUS(code); - - if (p_tdata) { - const pjsip_hdr *h; - - /* Add Require header. */ - req_hdr = pjsip_require_hdr_create(tmp_pool); - PJ_ASSERT_RETURN(req_hdr != NULL, PJ_ENOMEM); - - if (*options & PJSIP_INV_REQUIRE_100REL) - req_hdr->values[req_hdr->count++] = pj_str("100rel"); - if (*options & PJSIP_INV_REQUIRE_TIMER) - req_hdr->values[req_hdr->count++] = pj_str("timer"); - if (*options & PJSIP_INV_REQUIRE_TRICKLE_ICE) - req_hdr->values[req_hdr->count++] = pj_str("trickle-ice"); - - pj_list_push_back(&res_hdr_list, req_hdr); - - /* Add Supported header. */ - h = pjsip_endpt_get_capability(endpt, PJSIP_H_SUPPORTED, - NULL); - pj_assert(h); - if (h) { - sup_hdr = (pjsip_supported_hdr*) - pjsip_hdr_clone(tmp_pool, h); - pj_list_push_back(&res_hdr_list, sup_hdr); - } + code = PJSIP_SC_EXTENSION_REQUIRED; + status = PJSIP_ERRNO_FROM_SIP_STATUS(code); + + if (p_tdata) { + const pjsip_hdr *h; + + /* Add Require header. */ + req_hdr = pjsip_require_hdr_create(tmp_pool); + PJ_ASSERT_RETURN(req_hdr != NULL, PJ_ENOMEM); + + if (*options & PJSIP_INV_REQUIRE_100REL) + req_hdr->values[req_hdr->count++] = pj_str("100rel"); + if (*options & PJSIP_INV_REQUIRE_TIMER) + req_hdr->values[req_hdr->count++] = pj_str("timer"); + if (*options & PJSIP_INV_REQUIRE_TRICKLE_ICE) + req_hdr->values[req_hdr->count++] = pj_str("trickle-ice"); + + pj_list_push_back(&res_hdr_list, req_hdr); + + /* Add Supported header. */ + h = pjsip_endpt_get_capability(endpt, PJSIP_H_SUPPORTED, + NULL); + pj_assert(h); + if (h) { + sup_hdr = (pjsip_supported_hdr*) + pjsip_hdr_clone(tmp_pool, h); + pj_list_push_back(&res_hdr_list, sup_hdr); + } - } + } - goto on_return; + goto on_return; } /* If remote Require something that we support, make us Require * that feature too. */ if (rem_option & PJSIP_INV_REQUIRE_100REL) { - pj_assert(*options & PJSIP_INV_SUPPORT_100REL); - *options |= PJSIP_INV_REQUIRE_100REL; + pj_assert(*options & PJSIP_INV_SUPPORT_100REL); + *options |= PJSIP_INV_REQUIRE_100REL; } if (rem_option & PJSIP_INV_REQUIRE_TIMER) { - pj_assert(*options & PJSIP_INV_SUPPORT_TIMER); - *options |= PJSIP_INV_REQUIRE_TIMER; + pj_assert(*options & PJSIP_INV_SUPPORT_TIMER); + *options |= PJSIP_INV_REQUIRE_TIMER; } if (rem_option & PJSIP_INV_REQUIRE_TRICKLE_ICE) { - pj_assert(*options & PJSIP_INV_SUPPORT_TRICKLE_ICE); - *options |= PJSIP_INV_REQUIRE_TRICKLE_ICE; + pj_assert(*options & PJSIP_INV_SUPPORT_TRICKLE_ICE); + *options |= PJSIP_INV_REQUIRE_TRICKLE_ICE; } on_return: /* Create response if necessary */ if (code != 200 && p_tdata) { - pjsip_tx_data *tdata; - const pjsip_hdr *h; + pjsip_tx_data *tdata; + const pjsip_hdr *h; if (!rdata) { return PJSIP_ERRNO_FROM_SIP_STATUS(code); } - if (dlg) { - status = pjsip_dlg_create_response(dlg, rdata, code, NULL, - &tdata); - } else { - status = pjsip_endpt_create_response(endpt, rdata, code, NULL, - &tdata); - } + if (dlg) { + status = pjsip_dlg_create_response(dlg, rdata, code, NULL, + &tdata); + } else { + status = pjsip_endpt_create_response(endpt, rdata, code, NULL, + &tdata); + } - if (status != PJ_SUCCESS) - return status; + if (status != PJ_SUCCESS) + return status; - /* Add response headers. */ - h = res_hdr_list.next; - while (h != &res_hdr_list) { - pjsip_hdr *cloned; + /* Add response headers. */ + h = res_hdr_list.next; + while (h != &res_hdr_list) { + pjsip_hdr *cloned; - cloned = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, h); - PJ_ASSERT_RETURN(cloned, PJ_ENOMEM); + cloned = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, h); + PJ_ASSERT_RETURN(cloned, PJ_ENOMEM); - pjsip_msg_add_hdr(tdata->msg, cloned); + pjsip_msg_add_hdr(tdata->msg, cloned); - h = h->next; - } + h = h->next; + } - *p_tdata = tdata; + *p_tdata = tdata; - /* Can not return PJ_SUCCESS when response message is produced. - * Ref: PROTOS test ~#2490 - */ - if (status == PJ_SUCCESS) - status = PJSIP_ERRNO_FROM_SIP_STATUS(code); + /* Can not return PJ_SUCCESS when response message is produced. + * Ref: PROTOS test ~#2490 + */ + if (status == PJ_SUCCESS) + status = PJSIP_ERRNO_FROM_SIP_STATUS(code); } @@ -1609,16 +1608,16 @@ PJ_DEF(pj_status_t) pjsip_inv_verify_request3(pjsip_rx_data *rdata, * Verify incoming INVITE request. */ PJ_DEF(pj_status_t) pjsip_inv_verify_request2(pjsip_rx_data *rdata, - unsigned *options, - const pjmedia_sdp_session *r_sdp, - const pjmedia_sdp_session *l_sdp, - pjsip_dialog *dlg, - pjsip_endpoint *endpt, - pjsip_tx_data **p_tdata) + unsigned *options, + const pjmedia_sdp_session *r_sdp, + const pjmedia_sdp_session *l_sdp, + pjsip_dialog *dlg, + pjsip_endpoint *endpt, + pjsip_tx_data **p_tdata) { return pjsip_inv_verify_request3(rdata, rdata->tp_info.pool, options, r_sdp, l_sdp, dlg, - endpt, p_tdata); + endpt, p_tdata); } @@ -1626,25 +1625,25 @@ PJ_DEF(pj_status_t) pjsip_inv_verify_request2(pjsip_rx_data *rdata, * Verify incoming INVITE request. */ PJ_DEF(pj_status_t) pjsip_inv_verify_request( pjsip_rx_data *rdata, - unsigned *options, - const pjmedia_sdp_session *l_sdp, - pjsip_dialog *dlg, - pjsip_endpoint *endpt, - pjsip_tx_data **p_tdata) + unsigned *options, + const pjmedia_sdp_session *l_sdp, + pjsip_dialog *dlg, + pjsip_endpoint *endpt, + pjsip_tx_data **p_tdata) { return pjsip_inv_verify_request3(rdata, rdata->tp_info.pool, options, NULL, l_sdp, dlg, - endpt, p_tdata); + endpt, p_tdata); } /* * Create UAS invite session. */ PJ_DEF(pj_status_t) pjsip_inv_create_uas( pjsip_dialog *dlg, - pjsip_rx_data *rdata, - const pjmedia_sdp_session *local_sdp, - unsigned options, - pjsip_inv_session **p_inv) + pjsip_rx_data *rdata, + const pjmedia_sdp_session *local_sdp, + unsigned options, + pjsip_inv_session **p_inv) { pjsip_inv_session *inv; struct tsx_inv_data *tsx_inv_data; @@ -1662,17 +1661,17 @@ PJ_DEF(pj_status_t) pjsip_inv_create_uas( pjsip_dialog *dlg, /* rdata MUST contain INVITE request */ PJ_ASSERT_RETURN(msg->type == PJSIP_REQUEST_MSG && - msg->line.req.method.id == PJSIP_INVITE_METHOD, - PJ_EINVALIDOP); + msg->line.req.method.id == PJSIP_INVITE_METHOD, + PJ_EINVALIDOP); /* Lock dialog */ pjsip_dlg_inc_lock(dlg); /* Normalize options */ if (options & PJSIP_INV_REQUIRE_100REL) - options |= PJSIP_INV_SUPPORT_100REL; + options |= PJSIP_INV_SUPPORT_100REL; if (options & PJSIP_INV_REQUIRE_TIMER) - options |= PJSIP_INV_SUPPORT_TIMER; + options |= PJSIP_INV_SUPPORT_TIMER; /* Create the session */ inv = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_inv_session); @@ -1680,8 +1679,8 @@ PJ_DEF(pj_status_t) pjsip_inv_create_uas( pjsip_dialog *dlg, status = pj_atomic_create(dlg->pool, 0, &inv->ref_cnt); if (status != PJ_SUCCESS) { - pjsip_dlg_dec_lock(dlg); - return status; + pjsip_dlg_dec_lock(dlg); + return status; } inv->pool = dlg->pool; @@ -1696,9 +1695,9 @@ PJ_DEF(pj_status_t) pjsip_inv_create_uas( pjsip_dialog *dlg, /* (using inv->obj_name as temporary variable for pool names */ pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg->pool); inv->pool_prov = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name, - POOL_INIT_SIZE, POOL_INC_SIZE); + POOL_INIT_SIZE, POOL_INC_SIZE); inv->pool_active = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name, - POOL_INIT_SIZE, POOL_INC_SIZE); + POOL_INIT_SIZE, POOL_INC_SIZE); /* Object name will use the same dialog pointer. */ pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg); @@ -1706,33 +1705,33 @@ PJ_DEF(pj_status_t) pjsip_inv_create_uas( pjsip_dialog *dlg, /* Process SDP in message body, if present. */ sdp_info = pjsip_rdata_get_sdp_info(rdata); if (sdp_info->sdp_err) { - pjsip_dlg_dec_lock(dlg); - return sdp_info->sdp_err; + pjsip_dlg_dec_lock(dlg); + return sdp_info->sdp_err; } /* Create negotiator. */ if (sdp_info->sdp) { - status = pjmedia_sdp_neg_create_w_remote_offer(inv->pool, local_sdp, - sdp_info->sdp, - &inv->neg); - + status = pjmedia_sdp_neg_create_w_remote_offer(inv->pool, local_sdp, + sdp_info->sdp, + &inv->neg); + } else if (local_sdp) { - status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, - local_sdp, &inv->neg); + status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, + local_sdp, &inv->neg); } else { - status = PJ_SUCCESS; + status = PJ_SUCCESS; } if (status != PJ_SUCCESS) { - pjsip_dlg_dec_lock(dlg); - return status; + pjsip_dlg_dec_lock(dlg); + return status; } /* Register invite as dialog usage. */ status = pjsip_dlg_add_usage(dlg, &mod_inv.mod, inv); if (status != PJ_SUCCESS) { - pjsip_dlg_dec_lock(dlg); - return status; + pjsip_dlg_dec_lock(dlg); + return status; } /* Increment session in the dialog. */ @@ -1749,7 +1748,7 @@ PJ_DEF(pj_status_t) pjsip_inv_create_uas( pjsip_dialog *dlg, /* Create 100rel handler */ if (inv->options & PJSIP_INV_REQUIRE_100REL) { - pjsip_100rel_attach(inv); + pjsip_100rel_attach(inv); } /* Done */ @@ -1758,7 +1757,7 @@ PJ_DEF(pj_status_t) pjsip_inv_create_uas( pjsip_dialog *dlg, *p_inv = inv; PJ_LOG(5,(inv->obj_name, "UAS invite session created for dialog %s", - dlg->obj_name)); + dlg->obj_name)); return PJ_SUCCESS; } @@ -1767,8 +1766,8 @@ PJ_DEF(pj_status_t) pjsip_inv_create_uas( pjsip_dialog *dlg, * Forcefully terminate the session. */ PJ_DEF(pj_status_t) pjsip_inv_terminate( pjsip_inv_session *inv, - int st_code, - pj_bool_t notify) + int st_code, + pj_bool_t notify) { PJ_ASSERT_RETURN(inv, PJ_EINVAL); @@ -1783,9 +1782,9 @@ PJ_DEF(pj_status_t) pjsip_inv_terminate( pjsip_inv_session *inv, * disconnected. */ if (inv->invite_tsx && - inv->invite_tsx->state <= PJSIP_TSX_STATE_COMPLETED) + inv->invite_tsx->state <= PJSIP_TSX_STATE_COMPLETED) { - pjsip_tsx_terminate(inv->invite_tsx, st_code); + pjsip_tsx_terminate(inv->invite_tsx, st_code); } @@ -1794,10 +1793,10 @@ PJ_DEF(pj_status_t) pjsip_inv_terminate( pjsip_inv_session *inv, /* Forcefully terminate the session if state is not DISCONNECTED */ if (inv->state != PJSIP_INV_STATE_DISCONNECTED) { - pjsip_event usr_event; + pjsip_event usr_event; - PJSIP_EVENT_INIT_USER(usr_event, NULL, NULL, NULL, NULL); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, &usr_event); + PJSIP_EVENT_INIT_USER(usr_event, NULL, NULL, NULL, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, &usr_event); } /* Done. @@ -1815,24 +1814,24 @@ PJ_DEF(pj_status_t) pjsip_inv_terminate( pjsip_inv_session *inv, * INVITE request due to 401/407 challenge or 3xx response. */ PJ_DEF(pj_status_t) pjsip_inv_uac_restart(pjsip_inv_session *inv, - pj_bool_t new_offer) + pj_bool_t new_offer) { PJ_ASSERT_RETURN(inv, PJ_EINVAL); inv->state = PJSIP_INV_STATE_NULL; inv->invite_tsx = NULL; if (inv->last_answer) { - pjsip_tx_data_dec_ref(inv->last_answer); - inv->last_answer = NULL; + pjsip_tx_data_dec_ref(inv->last_answer); + inv->last_answer = NULL; } if (new_offer && inv->neg) { - pjmedia_sdp_neg_state neg_state; + pjmedia_sdp_neg_state neg_state; - neg_state = pjmedia_sdp_neg_get_state(inv->neg); - if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) { - pjmedia_sdp_neg_cancel_offer(inv->neg); - } + neg_state = pjmedia_sdp_neg_get_state(inv->neg); + if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } } return PJ_SUCCESS; @@ -1852,8 +1851,8 @@ static int print_sdp(pjsip_msg_body *body, char *buf, pj_size_t len) PJ_DEF(pj_status_t) pjsip_create_sdp_body( pj_pool_t *pool, - pjmedia_sdp_session *sdp, - pjsip_msg_body **p_body) + pjmedia_sdp_session *sdp, + pjsip_msg_body **p_body) { const pj_str_t STR_APPLICATION = { "application", 11}; const pj_str_t STR_SDP = { "sdp", 3 }; @@ -1863,7 +1862,7 @@ PJ_DEF(pj_status_t) pjsip_create_sdp_body( pj_pool_t *pool, PJ_ASSERT_RETURN(body != NULL, PJ_ENOMEM); pjsip_media_type_init(&body->content_type, (pj_str_t*)&STR_APPLICATION, - (pj_str_t*)&STR_SDP); + (pj_str_t*)&STR_SDP); body->data = sdp; body->len = 0; body->clone_data = &clone_sdp; @@ -1897,8 +1896,8 @@ static pjsip_multipart_part* create_sdp_part(pj_pool_t *pool, pjmedia_sdp_sessio } PJ_DEF(pj_status_t) pjsip_create_multipart_sdp_body(pj_pool_t *pool, - pjmedia_sdp_session *sdp, - pjsip_msg_body **p_body) + pjmedia_sdp_session *sdp, + pjsip_msg_body **p_body) { pjsip_media_type media_type; pjsip_msg_body *multipart; @@ -1917,33 +1916,33 @@ PJ_DEF(pj_status_t) pjsip_create_multipart_sdp_body(pj_pool_t *pool, } static pjsip_msg_body *create_sdp_body(pj_pool_t *pool, - const pjmedia_sdp_session *c_sdp) + const pjmedia_sdp_session *c_sdp) { pjsip_msg_body *body; pj_status_t status; status = pjsip_create_sdp_body(pool, - pjmedia_sdp_session_clone(pool, c_sdp), - &body); + pjmedia_sdp_session_clone(pool, c_sdp), + &body); if (status != PJ_SUCCESS) - return NULL; + return NULL; return body; } /* Utility to remove a string value from generic array header */ static void remove_val_from_array_hdr(pjsip_generic_array_hdr *arr_hdr, - const pj_str_t *val) + const pj_str_t *val) { unsigned i; for (i=0; icount; ++i) { - if (pj_stricmp(&arr_hdr->values[i], val)==0) { - pj_array_erase(arr_hdr->values, sizeof(arr_hdr->values[0]), - arr_hdr->count, i); - --arr_hdr->count; - break; - } + if (pj_stricmp(&arr_hdr->values[i], val)==0) { + pj_array_erase(arr_hdr->values, sizeof(arr_hdr->values[0]), + arr_hdr->count, i); + --arr_hdr->count; + break; + } } } @@ -1952,50 +1951,50 @@ static void remove_val_from_array_hdr(pjsip_generic_array_hdr *arr_hdr, * headers (see ticket #1858). */ static void cleanup_allow_sup_hdr(unsigned inv_option, - pjsip_tx_data *tdata, - pjsip_allow_hdr *allow_hdr, - pjsip_supported_hdr *sup_hdr) + pjsip_tx_data *tdata, + pjsip_allow_hdr *allow_hdr, + pjsip_supported_hdr *sup_hdr) { /* If all extensions are enabled, nothing to do */ if ((inv_option & PJSIP_INV_SUPPORT_100REL) && - (inv_option & PJSIP_INV_SUPPORT_TIMER) && - (inv_option & PJSIP_INV_SUPPORT_TRICKLE_ICE)) + (inv_option & PJSIP_INV_SUPPORT_TIMER) && + (inv_option & PJSIP_INV_SUPPORT_TRICKLE_ICE)) { - return; + return; } if (!allow_hdr && tdata) { - allow_hdr = (pjsip_allow_hdr*) pjsip_msg_find_hdr(tdata->msg, - PJSIP_H_ALLOW, - NULL); + allow_hdr = (pjsip_allow_hdr*) pjsip_msg_find_hdr(tdata->msg, + PJSIP_H_ALLOW, + NULL); } if (!sup_hdr && tdata) { - sup_hdr = (pjsip_supported_hdr*) pjsip_msg_find_hdr(tdata->msg, - PJSIP_H_SUPPORTED, - NULL); + sup_hdr = (pjsip_supported_hdr*) pjsip_msg_find_hdr(tdata->msg, + PJSIP_H_SUPPORTED, + NULL); } /* Remove "timer" from Supported header if Session-Timers is * disabled (https://github.com/pjsip/pjproject/issues/1761) */ if ((inv_option & PJSIP_INV_SUPPORT_TIMER) == 0 && sup_hdr) { - const pj_str_t STR_TIMER = { "timer", 5 }; - remove_val_from_array_hdr(sup_hdr, &STR_TIMER); + const pj_str_t STR_TIMER = { "timer", 5 }; + remove_val_from_array_hdr(sup_hdr, &STR_TIMER); } if ((inv_option & PJSIP_INV_SUPPORT_TRICKLE_ICE) == 0 && sup_hdr) { - const pj_str_t STR_TRICKLE_ICE = { "trickle-ice", 11 }; - remove_val_from_array_hdr(sup_hdr, &STR_TRICKLE_ICE); + const pj_str_t STR_TRICKLE_ICE = { "trickle-ice", 11 }; + remove_val_from_array_hdr(sup_hdr, &STR_TRICKLE_ICE); } if ((inv_option & PJSIP_INV_SUPPORT_100REL) == 0) { - const pj_str_t STR_PRACK = { "PRACK", 5 }; - const pj_str_t STR_100REL = { "100rel", 6 }; + const pj_str_t STR_PRACK = { "PRACK", 5 }; + const pj_str_t STR_100REL = { "100rel", 6 }; - if (allow_hdr) - remove_val_from_array_hdr(allow_hdr, &STR_PRACK); - if (sup_hdr) - remove_val_from_array_hdr(sup_hdr, &STR_100REL); + if (allow_hdr) + remove_val_from_array_hdr(allow_hdr, &STR_PRACK); + if (sup_hdr) + remove_val_from_array_hdr(sup_hdr, &STR_100REL); } } @@ -2003,7 +2002,7 @@ static void cleanup_allow_sup_hdr(unsigned inv_option, * Create initial INVITE request. */ PJ_DEF(pj_status_t) pjsip_inv_invite( pjsip_inv_session *inv, - pjsip_tx_data **p_tdata ) + pjsip_tx_data **p_tdata ) { pjsip_tx_data *tdata; const pjsip_hdr *hdr; @@ -2017,17 +2016,17 @@ PJ_DEF(pj_status_t) pjsip_inv_invite( pjsip_inv_session *inv, /* State MUST be NULL or CONFIRMED. */ PJ_ASSERT_RETURN(inv->state == PJSIP_INV_STATE_NULL || - inv->state == PJSIP_INV_STATE_CONFIRMED, - PJ_EINVALIDOP); + inv->state == PJSIP_INV_STATE_CONFIRMED, + PJ_EINVALIDOP); /* Lock dialog. */ pjsip_dlg_inc_lock(inv->dlg); /* Create the INVITE request. */ status = pjsip_dlg_create_request(inv->dlg, pjsip_get_invite_method(), -1, - &tdata); + &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* If this is the first INVITE, then copy the headers from inv_hdr. @@ -2035,59 +2034,59 @@ PJ_DEF(pj_status_t) pjsip_inv_invite( pjsip_inv_session *inv, * dialog was created. */ if (inv->state == PJSIP_INV_STATE_NULL) { - hdr = inv->dlg->inv_hdr.next; + hdr = inv->dlg->inv_hdr.next; - while (hdr != &inv->dlg->inv_hdr) { - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, hdr)); - hdr = hdr->next; - } + while (hdr != &inv->dlg->inv_hdr) { + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, hdr)); + hdr = hdr->next; + } } /* See if we have SDP to send. */ if (inv->neg) { - pjmedia_sdp_neg_state neg_state; + pjmedia_sdp_neg_state neg_state; - neg_state = pjmedia_sdp_neg_get_state(inv->neg); + neg_state = pjmedia_sdp_neg_get_state(inv->neg); - has_sdp = (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER || - (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO && - pjmedia_sdp_neg_has_local_answer(inv->neg))); + has_sdp = (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER || + (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO && + pjmedia_sdp_neg_has_local_answer(inv->neg))); } else { - has_sdp = PJ_FALSE; + has_sdp = PJ_FALSE; } /* Add SDP, if any. */ if (has_sdp) { - const pjmedia_sdp_session *offer; + const pjmedia_sdp_session *offer; - status = pjmedia_sdp_neg_get_neg_local(inv->neg, &offer); - if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - goto on_return; - } + status = pjmedia_sdp_neg_get_neg_local(inv->neg, &offer); + if (status != PJ_SUCCESS) { + pjsip_tx_data_dec_ref(tdata); + goto on_return; + } - tdata->msg->body = create_sdp_body(tdata->pool, offer); + tdata->msg->body = create_sdp_body(tdata->pool, offer); } /* Add Allow header. */ if (inv->dlg->add_allow) { - hdr = pjsip_endpt_get_capability(inv->dlg->endpt, PJSIP_H_ALLOW, NULL); - if (hdr) { - allow_hdr = (pjsip_allow_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, hdr); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)allow_hdr); - } + hdr = pjsip_endpt_get_capability(inv->dlg->endpt, PJSIP_H_ALLOW, NULL); + if (hdr) { + allow_hdr = (pjsip_allow_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, hdr); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)allow_hdr); + } } /* Add Supported header */ hdr = pjsip_endpt_get_capability(inv->dlg->endpt, PJSIP_H_SUPPORTED, NULL); if (hdr) { - sup_hdr = (pjsip_supported_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, hdr); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)sup_hdr); + sup_hdr = (pjsip_supported_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, hdr); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)sup_hdr); } /* Cleanup Allow & Supported headers from disabled extensions */ @@ -2095,26 +2094,26 @@ PJ_DEF(pj_status_t) pjsip_inv_invite( pjsip_inv_session *inv, /* Add Require header. */ if ((inv->options & PJSIP_INV_REQUIRE_100REL) || - (inv->options & PJSIP_INV_REQUIRE_TIMER) || - (inv->options & PJSIP_INV_REQUIRE_TRICKLE_ICE)) + (inv->options & PJSIP_INV_REQUIRE_TIMER) || + (inv->options & PJSIP_INV_REQUIRE_TRICKLE_ICE)) { - pjsip_require_hdr *hreq; + pjsip_require_hdr *hreq; - hreq = pjsip_require_hdr_create(tdata->pool); + hreq = pjsip_require_hdr_create(tdata->pool); - if (inv->options & PJSIP_INV_REQUIRE_100REL) - hreq->values[hreq->count++] = pj_str("100rel"); - if (inv->options & PJSIP_INV_REQUIRE_TIMER) - hreq->values[hreq->count++] = pj_str("timer"); - if (inv->options & PJSIP_INV_REQUIRE_TRICKLE_ICE) - hreq->values[hreq->count++] = pj_str("trickle-ice"); + if (inv->options & PJSIP_INV_REQUIRE_100REL) + hreq->values[hreq->count++] = pj_str("100rel"); + if (inv->options & PJSIP_INV_REQUIRE_TIMER) + hreq->values[hreq->count++] = pj_str("timer"); + if (inv->options & PJSIP_INV_REQUIRE_TRICKLE_ICE) + hreq->values[hreq->count++] = pj_str("trickle-ice"); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) hreq); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) hreq); } status = pjsip_timer_update_req(inv, tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Done. */ *p_tdata = tdata; @@ -2143,15 +2142,15 @@ static pj_status_t inv_negotiate_sdp( pjsip_inv_session *inv ) pj_status_t status; PJ_ASSERT_RETURN(pjmedia_sdp_neg_get_state(inv->neg) == - PJMEDIA_SDP_NEG_STATE_WAIT_NEGO, - PJMEDIA_SDPNEG_EINSTATE); + PJMEDIA_SDP_NEG_STATE_WAIT_NEGO, + PJMEDIA_SDPNEG_EINSTATE); status = pjmedia_sdp_neg_negotiate(inv->pool_prov, inv->neg, 0); PJ_PERROR(4,(inv->obj_name, status, "SDP negotiation done")); if (mod_inv.cb.on_media_update && inv->notify) - (*mod_inv.cb.on_media_update)(inv, status); + (*mod_inv.cb.on_media_update)(inv, status); /* Invite session may have been terminated by the application even * after a successful SDP negotiation, for example when no audio @@ -2159,17 +2158,17 @@ static pj_status_t inv_negotiate_sdp( pjsip_inv_session *inv ) */ if (inv->state != PJSIP_INV_STATE_DISCONNECTED) { - /* Swap the flip-flop pool when SDP negotiation success. */ - if (status == PJ_SUCCESS) { - swap_pool(&inv->pool_prov, &inv->pool_active); - } + /* Swap the flip-flop pool when SDP negotiation success. */ + if (status == PJ_SUCCESS) { + swap_pool(&inv->pool_prov, &inv->pool_active); + } - /* Reset the provisional pool regardless SDP negotiation result. */ - pj_pool_reset(inv->pool_prov); + /* Reset the provisional pool regardless SDP negotiation result. */ + pj_pool_reset(inv->pool_prov); } else { - status = PJSIP_ERRNO_FROM_SIP_STATUS(inv->cause); + status = PJSIP_ERRNO_FROM_SIP_STATUS(inv->cause); } return status; @@ -2179,8 +2178,8 @@ static pj_status_t inv_negotiate_sdp( pjsip_inv_session *inv ) * Check in incoming message for SDP offer/answer. */ static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv, - pjsip_transaction *tsx, - pjsip_rx_data *rdata) + pjsip_transaction *tsx, + pjsip_rx_data *rdata) { struct tsx_inv_data *tsx_inv_data; pj_status_t status; @@ -2191,14 +2190,14 @@ static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv, msg = rdata->msg_info.msg; if (msg->body == NULL) { - /* Message doesn't have body. */ - return PJ_SUCCESS; + /* Message doesn't have body. */ + return PJ_SUCCESS; } sdp_info = pjsip_rdata_get_sdp_info(rdata); if (sdp_info->body.ptr == NULL) { - /* Message body is not "application/sdp" */ - return PJMEDIA_SDP_EINSDP; + /* Message body is not "application/sdp" */ + return PJMEDIA_SDP_EINSDP; } /* Process the SDP body. */ @@ -2212,10 +2211,10 @@ static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv, /* Get/attach invite session's transaction data */ tsx_inv_data = (struct tsx_inv_data*) tsx->mod_data[mod_inv.mod.id]; if (tsx_inv_data == NULL) { - tsx_inv_data = PJ_POOL_ZALLOC_T(tsx->pool, struct tsx_inv_data); - tsx_inv_data->inv = inv; - tsx_inv_data->has_sdp = (sdp_info->sdp!=NULL); - tsx->mod_data[mod_inv.mod.id] = tsx_inv_data; + tsx_inv_data = PJ_POOL_ZALLOC_T(tsx->pool, struct tsx_inv_data); + tsx_inv_data->inv = inv; + tsx_inv_data->has_sdp = (sdp_info->sdp!=NULL); + tsx->mod_data[mod_inv.mod.id] = tsx_inv_data; } /* Initialize info that we are following forked media */ @@ -2226,7 +2225,7 @@ static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv, * EXCEPT previous nego was in 18x (early media) and any of the following * condition is met: * - Non-forking scenario: - * - 'accept_multiple_sdp_answers' is set, and + * - 'accept_multiple_sdp_answers' is set, and * - previous early response was not reliable (rfc6337 section 3.1.1). * - Forking scenario: * - This response has different To tag than the previous response, and @@ -2236,77 +2235,77 @@ static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv, * See also tickets #657, #1644, #1764, and #2123 for more info. */ if (tsx_inv_data->sdp_done) { - pj_str_t res_tag; - int st_code; - - res_tag = rdata->msg_info.to->tag; - st_code = rdata->msg_info.msg->line.status.code; - - if (tsx->role == PJSIP_ROLE_UAC && tsx_inv_data->done_early && - ( - /* Non-forking scenario */ - ( - !tsx_inv_data->done_early_rel && - (st_code/100 == 2 || st_code/10 == 18) && + pj_str_t res_tag; + int st_code; + + res_tag = rdata->msg_info.to->tag; + st_code = rdata->msg_info.msg->line.status.code; + + if (tsx->role == PJSIP_ROLE_UAC && tsx_inv_data->done_early && + ( + /* Non-forking scenario */ + ( + !tsx_inv_data->done_early_rel && + (st_code/100 == 2 || st_code/10 == 18) && pjsip_cfg()->endpt.accept_multiple_sdp_answers && - !pj_stricmp(&tsx_inv_data->done_tag, &res_tag) - ) - || - /* Forking scenario */ - ( - (st_code/100 == 2 || - (st_code/10 == 18 && - pjsip_cfg()->endpt.follow_early_media_fork)) && - pj_stricmp(&tsx_inv_data->done_tag, &res_tag) - ) - ) - ) - { - pjsip_sdp_info *tdata_sdp_info; - const pjmedia_sdp_session *reoffer_sdp = NULL; - - if (pjmedia_sdp_neg_get_state(inv->neg) != - PJMEDIA_SDP_NEG_STATE_DONE) - { - PJ_LOG(4,(inv->obj_name, "SDP negotiation in progress, " - "message body in %s response is ignored", - (st_code/10==18? "early" : "final" ))); - return PJ_SUCCESS; - } - - PJ_LOG(4,(inv->obj_name, "Received %s response " - "after SDP negotiation has been done in early " - "media. Renegotiating SDP..", - (st_code/10==18? "early" : "final" ))); - - /* Retrieve original SDP offer from INVITE request */ - tdata_sdp_info = pjsip_tdata_get_sdp_info(tsx->last_tx); - reoffer_sdp = tdata_sdp_info->sdp; - - /* Feed the original offer to negotiator */ - status = pjmedia_sdp_neg_modify_local_offer2(inv->pool_prov, - inv->neg, + !pj_stricmp(&tsx_inv_data->done_tag, &res_tag) + ) + || + /* Forking scenario */ + ( + (st_code/100 == 2 || + (st_code/10 == 18 && + pjsip_cfg()->endpt.follow_early_media_fork)) && + pj_stricmp(&tsx_inv_data->done_tag, &res_tag) + ) + ) + ) + { + pjsip_sdp_info *tdata_sdp_info; + const pjmedia_sdp_session *reoffer_sdp = NULL; + + if (pjmedia_sdp_neg_get_state(inv->neg) != + PJMEDIA_SDP_NEG_STATE_DONE) + { + PJ_LOG(4,(inv->obj_name, "SDP negotiation in progress, " + "message body in %s response is ignored", + (st_code/10==18? "early" : "final" ))); + return PJ_SUCCESS; + } + + PJ_LOG(4,(inv->obj_name, "Received %s response " + "after SDP negotiation has been done in early " + "media. Renegotiating SDP..", + (st_code/10==18? "early" : "final" ))); + + /* Retrieve original SDP offer from INVITE request */ + tdata_sdp_info = pjsip_tdata_get_sdp_info(tsx->last_tx); + reoffer_sdp = tdata_sdp_info->sdp; + + /* Feed the original offer to negotiator */ + status = pjmedia_sdp_neg_modify_local_offer2(inv->pool_prov, + inv->neg, inv->sdp_neg_flags, - reoffer_sdp); + reoffer_sdp); - if (status != PJ_SUCCESS) { - PJ_LOG(1,(inv->obj_name, "Error updating local offer for " - "forked 2xx/18x response (err=%d)", status)); - return status; - } + if (status != PJ_SUCCESS) { + PJ_LOG(1,(inv->obj_name, "Error updating local offer for " + "forked 2xx/18x response (err=%d)", status)); + return status; + } - inv->following_fork = !!pj_stricmp(&tsx_inv_data->done_tag, - &res_tag); - inv->updated_sdp_answer = PJ_TRUE; + inv->following_fork = !!pj_stricmp(&tsx_inv_data->done_tag, + &res_tag); + inv->updated_sdp_answer = PJ_TRUE; - } else { + } else { - if (rdata->msg_info.msg->body) { - PJ_LOG(4,(inv->obj_name, "SDP negotiation done, message " - "body is ignored")); - } - return PJ_SUCCESS; - } + if (rdata->msg_info.msg->body) { + PJ_LOG(4,(inv->obj_name, "SDP negotiation done, message " + "body is ignored")); + } + return PJ_SUCCESS; + } } pj_assert(sdp_info->sdp != NULL); @@ -2314,44 +2313,44 @@ static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv, /* The SDP can be an offer or answer, depending on negotiator's state */ if (inv->neg == NULL || - pjmedia_sdp_neg_get_state(inv->neg) == PJMEDIA_SDP_NEG_STATE_DONE) + pjmedia_sdp_neg_get_state(inv->neg) == PJMEDIA_SDP_NEG_STATE_DONE) { - /* This is an offer. */ + /* This is an offer. */ - PJ_LOG(5,(inv->obj_name, "Got SDP offer in %s", - pjsip_rx_data_get_info(rdata))); + PJ_LOG(5,(inv->obj_name, "Got SDP offer in %s", + pjsip_rx_data_get_info(rdata))); - if (inv->neg == NULL) { - status=pjmedia_sdp_neg_create_w_remote_offer(inv->pool, NULL, - sdp_info->sdp, - &inv->neg); - } else { - status=pjmedia_sdp_neg_set_remote_offer(inv->pool_prov, inv->neg, - sdp_info->sdp); - } + if (inv->neg == NULL) { + status=pjmedia_sdp_neg_create_w_remote_offer(inv->pool, NULL, + sdp_info->sdp, + &inv->neg); + } else { + status=pjmedia_sdp_neg_set_remote_offer(inv->pool_prov, inv->neg, + sdp_info->sdp); + } - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, "Error processing SDP offer in %", - pjsip_rx_data_get_info(rdata))); - return PJMEDIA_SDP_EINSDP; - } + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, "Error processing SDP offer in %", + pjsip_rx_data_get_info(rdata))); + return PJMEDIA_SDP_EINSDP; + } - /* Inform application about remote offer. */ - if (mod_inv.cb.on_rx_offer2 && inv->notify) { - struct pjsip_inv_on_rx_offer_cb_param param; + /* Inform application about remote offer. */ + if (mod_inv.cb.on_rx_offer2 && inv->notify) { + struct pjsip_inv_on_rx_offer_cb_param param; - param.offer = sdp_info->sdp; - param.rdata = rdata; + param.offer = sdp_info->sdp; + param.rdata = rdata; (*mod_inv.cb.on_rx_offer2)(inv, ¶m); - } else if (mod_inv.cb.on_rx_offer && inv->notify) { + } else if (mod_inv.cb.on_rx_offer && inv->notify) { (*mod_inv.cb.on_rx_offer)(inv, sdp_info->sdp); - } + } - /* application must have supplied an answer at this point. */ - if (pjmedia_sdp_neg_get_state(inv->neg) != - PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) - { + /* application must have supplied an answer at this point. */ + if (pjmedia_sdp_neg_get_state(inv->neg) != + PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) + { if (mod_inv.cb.on_rx_reinvite && inv->notify && msg->type == PJSIP_REQUEST_MSG && msg->line.req.method.id == PJSIP_INVITE_METHOD) @@ -2359,57 +2358,57 @@ static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv, /* Do not return failure first, allow the application * to set the answer in the on_rx_reinvite() callback. */ - PJ_LOG(5,(inv->obj_name, "Ignoring on_rx_offer() status " - "because on_rx_reinvite() is implemented")); + PJ_LOG(5,(inv->obj_name, "Ignoring on_rx_offer() status " + "because on_rx_reinvite() is implemented")); return PJ_SUCCESS; } - return PJ_EINVALIDOP; - } + return PJ_EINVALIDOP; + } } else if (pjmedia_sdp_neg_get_state(inv->neg) == - PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) + PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) { - int status_code; + int status_code; - /* This is an answer. - * Process and negotiate remote answer. - */ + /* This is an answer. + * Process and negotiate remote answer. + */ - PJ_LOG(5,(inv->obj_name, "Got SDP answer in %s", - pjsip_rx_data_get_info(rdata))); + PJ_LOG(5,(inv->obj_name, "Got SDP answer in %s", + pjsip_rx_data_get_info(rdata))); - status = pjmedia_sdp_neg_set_remote_answer(inv->pool_prov, inv->neg, - sdp_info->sdp); + status = pjmedia_sdp_neg_set_remote_answer(inv->pool_prov, inv->neg, + sdp_info->sdp); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, "Error processing SDP answer in %s", - pjsip_rx_data_get_info(rdata))); - return PJMEDIA_SDP_EINSDP; - } + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, "Error processing SDP answer in %s", + pjsip_rx_data_get_info(rdata))); + return PJMEDIA_SDP_EINSDP; + } - /* Negotiate SDP */ + /* Negotiate SDP */ - inv_negotiate_sdp(inv); + inv_negotiate_sdp(inv); - /* Mark this transaction has having SDP offer/answer done, and - * save the reference to the To tag - */ + /* Mark this transaction has having SDP offer/answer done, and + * save the reference to the To tag + */ - tsx_inv_data->sdp_done = 1; - status_code = rdata->msg_info.msg->line.status.code; - tsx_inv_data->done_early = (status_code/100==1); - tsx_inv_data->done_early_rel = tsx_inv_data->done_early && - pjsip_100rel_is_reliable(rdata); - if (!inv->sdp_done_early_rel) - inv->sdp_done_early_rel = tsx_inv_data->done_early_rel; - pj_strdup(tsx->pool, &tsx_inv_data->done_tag, - &rdata->msg_info.to->tag); + tsx_inv_data->sdp_done = 1; + status_code = rdata->msg_info.msg->line.status.code; + tsx_inv_data->done_early = (status_code/100==1); + tsx_inv_data->done_early_rel = tsx_inv_data->done_early && + pjsip_100rel_is_reliable(rdata); + if (!inv->sdp_done_early_rel) + inv->sdp_done_early_rel = tsx_inv_data->done_early_rel; + pj_strdup(tsx->pool, &tsx_inv_data->done_tag, + &rdata->msg_info.to->tag); } else { - - PJ_LOG(5,(THIS_FILE, "Ignored SDP in %s: negotiator state is %s", - pjsip_rx_data_get_info(rdata), - pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_get_state(inv->neg)))); + + PJ_LOG(5,(THIS_FILE, "Ignored SDP in %s: negotiator state is %s", + pjsip_rx_data_get_info(rdata), + pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_get_state(inv->neg)))); } return PJ_SUCCESS; @@ -2420,9 +2419,9 @@ static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv, * Process INVITE answer, for both initial and subsequent re-INVITE */ static pj_status_t process_answer( pjsip_inv_session *inv, - int st_code, - pjsip_tx_data *tdata, - const pjmedia_sdp_session *local_sdp) + int st_code, + pjsip_tx_data *tdata, + const pjmedia_sdp_session *local_sdp) { pj_status_t status; const pjmedia_sdp_session *sdp = NULL; @@ -2432,24 +2431,24 @@ static pj_status_t process_answer( pjsip_inv_session *inv, */ if (local_sdp && (st_code/100==1 || st_code/100==2)) { - if (inv->neg == NULL) { - status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, - local_sdp, - &inv->neg); - } else if (pjmedia_sdp_neg_get_state(inv->neg)== - PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER) - { - status = pjmedia_sdp_neg_set_local_answer(inv->pool_prov, inv->neg, - local_sdp); - } else { + if (inv->neg == NULL) { + status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, + local_sdp, + &inv->neg); + } else if (pjmedia_sdp_neg_get_state(inv->neg)== + PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER) + { + status = pjmedia_sdp_neg_set_local_answer(inv->pool_prov, inv->neg, + local_sdp); + } else { - /* Can not specify local SDP at this state. */ - pj_assert(0); - status = PJMEDIA_SDPNEG_EINSTATE; - } + /* Can not specify local SDP at this state. */ + pj_assert(0); + status = PJMEDIA_SDPNEG_EINSTATE; + } - if (status != PJ_SUCCESS) - return status; + if (status != PJ_SUCCESS) + return status; } @@ -2457,51 +2456,51 @@ static pj_status_t process_answer( pjsip_inv_session *inv, /* If SDP negotiator is ready, start negotiation. */ if (st_code/100==2 || (st_code/10==18 && st_code!=180 && st_code!=181)) { - pjmedia_sdp_neg_state neg_state; + pjmedia_sdp_neg_state neg_state; - /* Start nego when appropriate. */ - neg_state = inv->neg ? pjmedia_sdp_neg_get_state(inv->neg) : - PJMEDIA_SDP_NEG_STATE_NULL; + /* Start nego when appropriate. */ + neg_state = inv->neg ? pjmedia_sdp_neg_get_state(inv->neg) : + PJMEDIA_SDP_NEG_STATE_NULL; - if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) { + if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) { - status = pjmedia_sdp_neg_get_neg_local(inv->neg, &sdp); + status = pjmedia_sdp_neg_get_neg_local(inv->neg, &sdp); - } else if (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO && - pjmedia_sdp_neg_has_local_answer(inv->neg) ) - { - struct tsx_inv_data *tsx_inv_data; + } else if (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO && + pjmedia_sdp_neg_has_local_answer(inv->neg) ) + { + struct tsx_inv_data *tsx_inv_data; - /* Get invite session's transaction data */ - tsx_inv_data = (struct tsx_inv_data*) - inv->invite_tsx->mod_data[mod_inv.mod.id]; + /* Get invite session's transaction data */ + tsx_inv_data = (struct tsx_inv_data*) + inv->invite_tsx->mod_data[mod_inv.mod.id]; - status = inv_negotiate_sdp(inv); - if (status != PJ_SUCCESS) - return status; - - /* Mark this transaction has having SDP offer/answer done. */ - tsx_inv_data->sdp_done = 1; + status = inv_negotiate_sdp(inv); + if (status != PJ_SUCCESS) + return status; + + /* Mark this transaction has having SDP offer/answer done. */ + tsx_inv_data->sdp_done = 1; - status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp); - } + status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp); + } } /* Include SDP when it's available for 2xx and 18x (but not 180 and 181) * response. Subsequent response will include this SDP. * * Note note: - * - When offer/answer has been completed in reliable 183, we MUST NOT - * send SDP in 2xx response. So if we don't have SDP to send, clear - * the SDP in the message body ONLY if 100rel is active in this + * - When offer/answer has been completed in reliable 183, we MUST NOT + * send SDP in 2xx response. So if we don't have SDP to send, clear + * the SDP in the message body ONLY if 100rel is active in this * session. */ if (sdp) { - tdata->msg->body = create_sdp_body(tdata->pool, sdp); + tdata->msg->body = create_sdp_body(tdata->pool, sdp); } else { - if (inv->options & PJSIP_INV_REQUIRE_100REL) { - tdata->msg->body = NULL; - } + if (inv->options & PJSIP_INV_REQUIRE_100REL) { + tdata->msg->body = NULL; + } } /* Cancel SDP negotiation if this is a negative reply to a re-INVITE */ @@ -2522,12 +2521,12 @@ static pj_status_t process_answer( pjsip_inv_session *inv, /* * Create first response to INVITE */ -PJ_DEF(pj_status_t) pjsip_inv_initial_answer( pjsip_inv_session *inv, - pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - const pjmedia_sdp_session *sdp, - pjsip_tx_data **p_tdata) +PJ_DEF(pj_status_t) pjsip_inv_initial_answer( pjsip_inv_session *inv, + pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + const pjmedia_sdp_session *sdp, + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pj_status_t status; @@ -2545,34 +2544,34 @@ PJ_DEF(pj_status_t) pjsip_inv_initial_answer( pjsip_inv_session *inv, /* Create response */ status = pjsip_dlg_create_response(inv->dlg, rdata, st_code, st_text, - &tdata); + &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Invoke Session Timers module */ status = pjsip_timer_process_req(inv, rdata, &st_code2); if (status != PJ_SUCCESS) { - pj_status_t status2; + pj_status_t status2; - status2 = pjsip_dlg_modify_response(inv->dlg, tdata, st_code2, NULL); - if (status2 != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - goto on_return; - } - status2 = pjsip_timer_update_resp(inv, tdata); - if (status2 == PJ_SUCCESS) - *p_tdata = tdata; - else - pjsip_tx_data_dec_ref(tdata); + status2 = pjsip_dlg_modify_response(inv->dlg, tdata, st_code2, NULL); + if (status2 != PJ_SUCCESS) { + pjsip_tx_data_dec_ref(tdata); + goto on_return; + } + status2 = pjsip_timer_update_resp(inv, tdata); + if (status2 == PJ_SUCCESS) + *p_tdata = tdata; + else + pjsip_tx_data_dec_ref(tdata); - goto on_return; + goto on_return; } /* Process SDP in answer */ status = process_answer(inv, st_code, tdata, sdp); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - goto on_return; + pjsip_tx_data_dec_ref(tdata); + goto on_return; } /* Cleanup Allow & Supported headers from disabled extensions */ @@ -2582,7 +2581,7 @@ PJ_DEF(pj_status_t) pjsip_inv_initial_answer( pjsip_inv_session *inv, inv->last_answer = tdata; pjsip_tx_data_add_ref(inv->last_answer); PJ_LOG(5,(inv->dlg->obj_name, "Initial answer %s", - pjsip_tx_data_get_info(inv->last_answer))); + pjsip_tx_data_get_info(inv->last_answer))); /* Invoke Session Timers */ pjsip_timer_update_resp(inv, tdata); @@ -2599,11 +2598,11 @@ PJ_DEF(pj_status_t) pjsip_inv_initial_answer( pjsip_inv_session *inv, /* * Answer INVITE request. */ -PJ_DEF(pj_status_t) pjsip_inv_answer( pjsip_inv_session *inv, - int st_code, - const pj_str_t *st_text, - const pjmedia_sdp_session *local_sdp, - pjsip_tx_data **p_tdata ) +PJ_DEF(pj_status_t) pjsip_inv_answer( pjsip_inv_session *inv, + int st_code, + const pj_str_t *st_text, + const pjmedia_sdp_session *local_sdp, + pjsip_tx_data **p_tdata ) { pjsip_tx_data *last_res; pjsip_tx_data *old_res; @@ -2629,25 +2628,25 @@ PJ_DEF(pj_status_t) pjsip_inv_answer( pjsip_inv_session *inv, */ status = pjsip_tx_data_clone(inv->last_answer, 0, &last_res); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Modify last response. */ status = pjsip_dlg_modify_response(inv->dlg, last_res, st_code, st_text); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(last_res); - goto on_return; + pjsip_tx_data_dec_ref(last_res); + goto on_return; } /* For non-2xx final response, strip message body */ if (st_code >= 300) { - last_res->msg->body = NULL; + last_res->msg->body = NULL; } /* Process SDP in answer */ status = process_answer(inv, st_code, last_res, local_sdp); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(last_res); - goto on_return; + pjsip_tx_data_dec_ref(last_res); + goto on_return; } /* Invoke Session Timers */ @@ -2676,7 +2675,7 @@ PJ_DEF(pj_status_t) pjsip_inv_answer( pjsip_inv_session *inv, * Set local SDP offer/answer. */ PJ_DEF(pj_status_t) pjsip_inv_set_local_sdp(pjsip_inv_session *inv, - const pjmedia_sdp_session *sdp ) + const pjmedia_sdp_session *sdp ) { const pjmedia_sdp_session *offer; pj_status_t status; @@ -2691,7 +2690,7 @@ PJ_DEF(pj_status_t) pjsip_inv_set_local_sdp(pjsip_inv_session *inv, pjmedia_sdp_neg_state neg_state = pjmedia_sdp_neg_get_state(inv->neg); if ((neg_state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER || - neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) && + neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) && pjmedia_sdp_neg_get_neg_remote(inv->neg, &offer) == PJ_SUCCESS) { status = pjsip_inv_set_sdp_answer(inv, sdp); @@ -2702,8 +2701,8 @@ PJ_DEF(pj_status_t) pjsip_inv_set_local_sdp(pjsip_inv_session *inv, } else return PJMEDIA_SDPNEG_EINSTATE; } else { - status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, - sdp, &inv->neg); + status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, + sdp, &inv->neg); } return status; @@ -2714,7 +2713,7 @@ PJ_DEF(pj_status_t) pjsip_inv_set_local_sdp(pjsip_inv_session *inv, * Set SDP answer. */ PJ_DEF(pj_status_t) pjsip_inv_set_sdp_answer( pjsip_inv_session *inv, - const pjmedia_sdp_session *sdp ) + const pjmedia_sdp_session *sdp ) { pj_status_t status; @@ -2732,9 +2731,9 @@ PJ_DEF(pj_status_t) pjsip_inv_set_sdp_answer( pjsip_inv_session *inv, * End session. */ PJ_DEF(pj_status_t) pjsip_inv_end_session( pjsip_inv_session *inv, - int st_code, - const pj_str_t *st_text, - pjsip_tx_data **p_tdata ) + int st_code, + const pj_str_t *st_text, + pjsip_tx_data **p_tdata ) { pjsip_tx_data *tdata; pj_status_t status; @@ -2754,88 +2753,88 @@ PJ_DEF(pj_status_t) pjsip_inv_end_session( pjsip_inv_session *inv, case PJSIP_INV_STATE_EARLY: case PJSIP_INV_STATE_INCOMING: - if (inv->role == PJSIP_ROLE_UAC) { - - /* For UAC when session has not been confirmed, create CANCEL. */ - - /* MUST have the original UAC INVITE transaction. */ - PJ_ASSERT_RETURN(inv->invite_tsx != NULL, PJ_EBUG); - - /* But CANCEL should only be called when we have received a - * provisional response. If we haven't received any responses, - * just destroy the transaction. - */ - if (inv->invite_tsx->status_code < 100) { - - /* Do not stop INVITE retransmission, see ticket #506 */ - //pjsip_tsx_stop_retransmit(inv->invite_tsx); - inv->cancelling = PJ_TRUE; - inv->pending_cancel = PJ_TRUE; - *p_tdata = NULL; - PJ_LOG(4, (inv->obj_name, "Delaying CANCEL since no " - "provisional response is received yet")); - pj_log_pop_indent(); - return PJ_SUCCESS; - } - - /* The CSeq here assumes that the dialog is started with an - * INVITE session. This may not be correct; dialog can be - * started as SUBSCRIBE session. - * So fix this! - */ - status = pjsip_endpt_create_cancel(inv->dlg->endpt, - inv->invite_tsx->last_tx, - &tdata); - if (status != PJ_SUCCESS) { - pj_log_pop_indent(); - return status; - } - - /* Set timeout for the INVITE transaction, in case UAS is not - * able to respond the INVITE with 487 final response. The - * timeout value is 64*T1. - */ - pjsip_tsx_set_timeout(inv->invite_tsx, 64 * pjsip_cfg()->tsx.t1); - - } else { - - /* For UAS, send a final response. */ - tdata = inv->invite_tsx->last_tx; - if (tdata == NULL) - tdata = inv->last_answer; - - PJ_ASSERT_RETURN(tdata != NULL, PJ_EINVALIDOP); - - //status = pjsip_dlg_modify_response(inv->dlg, tdata, st_code, - // st_text); - status = pjsip_inv_answer(inv, st_code, st_text, NULL, &tdata); - } - break; + if (inv->role == PJSIP_ROLE_UAC) { + + /* For UAC when session has not been confirmed, create CANCEL. */ + + /* MUST have the original UAC INVITE transaction. */ + PJ_ASSERT_RETURN(inv->invite_tsx != NULL, PJ_EBUG); + + /* But CANCEL should only be called when we have received a + * provisional response. If we haven't received any responses, + * just destroy the transaction. + */ + if (inv->invite_tsx->status_code < 100) { + + /* Do not stop INVITE retransmission, see ticket #506 */ + //pjsip_tsx_stop_retransmit(inv->invite_tsx); + inv->cancelling = PJ_TRUE; + inv->pending_cancel = PJ_TRUE; + *p_tdata = NULL; + PJ_LOG(4, (inv->obj_name, "Delaying CANCEL since no " + "provisional response is received yet")); + pj_log_pop_indent(); + return PJ_SUCCESS; + } + + /* The CSeq here assumes that the dialog is started with an + * INVITE session. This may not be correct; dialog can be + * started as SUBSCRIBE session. + * So fix this! + */ + status = pjsip_endpt_create_cancel(inv->dlg->endpt, + inv->invite_tsx->last_tx, + &tdata); + if (status != PJ_SUCCESS) { + pj_log_pop_indent(); + return status; + } + + /* Set timeout for the INVITE transaction, in case UAS is not + * able to respond the INVITE with 487 final response. The + * timeout value is 64*T1. + */ + pjsip_tsx_set_timeout(inv->invite_tsx, 64 * pjsip_cfg()->tsx.t1); + + } else { + + /* For UAS, send a final response. */ + tdata = inv->invite_tsx->last_tx; + if (tdata == NULL) + tdata = inv->last_answer; + + PJ_ASSERT_RETURN(tdata != NULL, PJ_EINVALIDOP); + + //status = pjsip_dlg_modify_response(inv->dlg, tdata, st_code, + // st_text); + status = pjsip_inv_answer(inv, st_code, st_text, NULL, &tdata); + } + break; case PJSIP_INV_STATE_CONNECTING: case PJSIP_INV_STATE_CONFIRMED: - /* End Session Timer */ - pjsip_timer_end_session(inv); + /* End Session Timer */ + pjsip_timer_end_session(inv); - /* For established dialog, send BYE */ - status = pjsip_dlg_create_request(inv->dlg, pjsip_get_bye_method(), - -1, &tdata); - break; + /* For established dialog, send BYE */ + status = pjsip_dlg_create_request(inv->dlg, pjsip_get_bye_method(), + -1, &tdata); + break; case PJSIP_INV_STATE_DISCONNECTED: - /* No need to do anything. */ - pj_log_pop_indent(); - return PJSIP_ESESSIONTERMINATED; + /* No need to do anything. */ + pj_log_pop_indent(); + return PJSIP_ESESSIONTERMINATED; default: - pj_assert(!"Invalid operation!"); - pj_log_pop_indent(); - return PJ_EINVALIDOP; + pj_assert(!"Invalid operation!"); + pj_log_pop_indent(); + return PJ_EINVALIDOP; } if (status != PJ_SUCCESS) { - pj_log_pop_indent(); - return status; + pj_log_pop_indent(); + return status; } @@ -2888,7 +2887,7 @@ PJ_DEF(pj_status_t) pjsip_inv_cancel_reinvite( pjsip_inv_session *inv, pj_log_pop_indent(); return status; } - break; + break; default: /* We cannot send CANCEL to a re-INVITE if the INVITE session is @@ -2915,44 +2914,44 @@ PJ_DEF(pj_status_t) pjsip_inv_cancel_reinvite( pjsip_inv_session *inv, * the event 'e' argument may be NULL. */ static pj_bool_t inv_uac_recurse(pjsip_inv_session *inv, int code, - const pj_str_t *reason, pjsip_event *e) + const pj_str_t *reason, pjsip_event *e) { pjsip_redirect_op op; pjsip_target *target; /* Won't redirect if the callback is not implemented. */ if (mod_inv.cb.on_redirected == NULL) - return PJ_FALSE; + return PJ_FALSE; if (reason == NULL) - reason = pjsip_get_status_text(code); + reason = pjsip_get_status_text(code); /* Set status of current target */ pjsip_target_assign_status(inv->dlg->target_set.current, inv->dlg->pool, - code, reason); + code, reason); /* Fetch next target from the target set. We only want to * process SIP/SIPS URI for now. */ for (;;) { - target = pjsip_target_set_get_next(&inv->dlg->target_set); - if (target == NULL) { - /* No more target. */ - return PJ_FALSE; - } - - if (!PJSIP_URI_SCHEME_IS_SIP(target->uri) && - !PJSIP_URI_SCHEME_IS_SIPS(target->uri)) - { - code = PJSIP_SC_UNSUPPORTED_URI_SCHEME; - reason = pjsip_get_status_text(code); - - /* Mark this target as unusable and fetch next target. */ - pjsip_target_assign_status(target, inv->dlg->pool, code, reason); - } else { - /* Found a target */ - break; - } + target = pjsip_target_set_get_next(&inv->dlg->target_set); + if (target == NULL) { + /* No more target. */ + return PJ_FALSE; + } + + if (!PJSIP_URI_SCHEME_IS_SIP(target->uri) && + !PJSIP_URI_SCHEME_IS_SIPS(target->uri)) + { + code = PJSIP_SC_UNSUPPORTED_URI_SCHEME; + reason = pjsip_get_status_text(code); + + /* Mark this target as unusable and fetch next target. */ + pjsip_target_assign_status(target, inv->dlg->pool, code, reason); + } else { + /* Found a target */ + break; + } } /* We have target in 'target'. Set this target as current target @@ -2968,35 +2967,35 @@ static pj_bool_t inv_uac_recurse(pjsip_inv_session *inv, int code, case PJSIP_REDIRECT_ACCEPT: case PJSIP_REDIRECT_ACCEPT_REPLACE: case PJSIP_REDIRECT_STOP: - /* Must increment session counter, that's the convention of the - * pjsip_inv_process_redirect(). - */ - pjsip_dlg_inc_session(inv->dlg, &mod_inv.mod); + /* Must increment session counter, that's the convention of the + * pjsip_inv_process_redirect(). + */ + pjsip_dlg_inc_session(inv->dlg, &mod_inv.mod); - /* Act on the recursion */ - pjsip_inv_process_redirect(inv, op, e); - return PJ_TRUE; + /* Act on the recursion */ + pjsip_inv_process_redirect(inv, op, e); + return PJ_TRUE; case PJSIP_REDIRECT_PENDING: - /* Increment session so that the dialog/session is not destroyed - * while we're waiting for user confirmation. - */ - pjsip_dlg_inc_session(inv->dlg, &mod_inv.mod); + /* Increment session so that the dialog/session is not destroyed + * while we're waiting for user confirmation. + */ + pjsip_dlg_inc_session(inv->dlg, &mod_inv.mod); - /* Also clear the invite_tsx variable, otherwise when this tsx is - * terminated, it will also terminate the session. - */ - inv->invite_tsx = NULL; + /* Also clear the invite_tsx variable, otherwise when this tsx is + * terminated, it will also terminate the session. + */ + inv->invite_tsx = NULL; - /* Done. The processing will continue once the application calls - * pjsip_inv_process_redirect(). - */ - return PJ_TRUE; + /* Done. The processing will continue once the application calls + * pjsip_inv_process_redirect(). + */ + return PJ_TRUE; case PJSIP_REDIRECT_REJECT: - /* Recursively call this function again to fetch next target, if any. - */ - return inv_uac_recurse(inv, PJSIP_SC_REQUEST_TERMINATED, NULL, e); + /* Recursively call this function again to fetch next target, if any. + */ + return inv_uac_recurse(inv, PJSIP_SC_REQUEST_TERMINATED, NULL, e); } @@ -3007,8 +3006,8 @@ static pj_bool_t inv_uac_recurse(pjsip_inv_session *inv, int code, /* Process redirection/recursion */ PJ_DEF(pj_status_t) pjsip_inv_process_redirect( pjsip_inv_session *inv, - pjsip_redirect_op op, - pjsip_event *e) + pjsip_redirect_op op, + pjsip_event *e) { const pjsip_status_code cancel_code = PJSIP_SC_REQUEST_TERMINATED; pjsip_event usr_event; @@ -3017,8 +3016,8 @@ PJ_DEF(pj_status_t) pjsip_inv_process_redirect( pjsip_inv_session *inv, PJ_ASSERT_RETURN(inv && op != PJSIP_REDIRECT_PENDING, PJ_EINVAL); if (e == NULL) { - PJSIP_EVENT_INIT_USER(usr_event, NULL, NULL, NULL, NULL); - e = &usr_event; + PJSIP_EVENT_INIT_USER(usr_event, NULL, NULL, NULL, NULL); + e = &usr_event; } pjsip_dlg_inc_lock(inv->dlg); @@ -3033,116 +3032,116 @@ PJ_DEF(pj_status_t) pjsip_inv_process_redirect( pjsip_inv_session *inv, switch (op) { case PJSIP_REDIRECT_ACCEPT: case PJSIP_REDIRECT_ACCEPT_REPLACE: - /* User accept the redirection. Reset the session and resend the - * INVITE request. - */ - { - pjsip_tx_data *tdata; - pjsip_via_hdr *via; - - /* Get the original INVITE request. */ - tdata = inv->invite_req; - pjsip_tx_data_add_ref(tdata); - - /* Restore strict route set. - * See https://github.com/pjsip/pjproject/issues/492 - */ - pjsip_restore_strict_route_set(tdata); - - /* Set target */ - tdata->msg->line.req.uri = (pjsip_uri*) - pjsip_uri_clone(tdata->pool, inv->dlg->target_set.current->uri); - - /* Remove branch param in Via header. */ - via = (pjsip_via_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); - via->branch_param.slen = 0; - - /* Process PJSIP_REDIRECT_ACCEPT_REPLACE */ - if (op == PJSIP_REDIRECT_ACCEPT_REPLACE) { - pjsip_to_hdr *to; - pjsip_dialog *dlg = inv->dlg; - enum { TMP_LEN = PJSIP_MAX_URL_SIZE }; - char tmp[TMP_LEN]; - int len; - - /* Replace To header */ - to = PJSIP_MSG_TO_HDR(tdata->msg); - to->uri = (pjsip_uri*) - pjsip_uri_clone(tdata->pool, - dlg->target_set.current->uri); - to->tag.slen = 0; - pj_list_init(&to->other_param); - - /* Re-init dialog remote info */ - dlg->remote.info = (pjsip_to_hdr*) - pjsip_hdr_clone(dlg->pool, to); - - /* Remove header param from remote info */ - if (PJSIP_URI_SCHEME_IS_SIP(dlg->remote.info->uri) || - PJSIP_URI_SCHEME_IS_SIPS(dlg->remote.info->uri)) - { - pjsip_sip_uri *sip_uri = (pjsip_sip_uri *) - pjsip_uri_get_uri(dlg->remote.info->uri); - if (!pj_list_empty(&sip_uri->header_param)) { - /* Remove all header param */ - pj_list_init(&sip_uri->header_param); - } - } - - /* Print the remote info. */ - len = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, - dlg->remote.info->uri, tmp, TMP_LEN); - if (len < 1) { - pj_ansi_strcpy(tmp, "<-error: uri too long->"); - len = (int)pj_ansi_strlen(tmp); - } - pj_strdup2_with_null(dlg->pool, &dlg->remote.info_str, tmp); - - /* Secure? */ - dlg->secure = PJSIP_URI_SCHEME_IS_SIPS(to->uri); - } - - /* Reset message destination info (see #1248). */ - pj_bzero(&tdata->dest_info, sizeof(tdata->dest_info)); - - /* Must invalidate the message! */ - pjsip_tx_data_invalidate_msg(tdata); - - /* Reset the session */ - pjsip_inv_uac_restart(inv, PJ_FALSE); - - /* (re)Send the INVITE request */ - status = pjsip_inv_send_msg(inv, tdata); - } - break; + /* User accept the redirection. Reset the session and resend the + * INVITE request. + */ + { + pjsip_tx_data *tdata; + pjsip_via_hdr *via; + + /* Get the original INVITE request. */ + tdata = inv->invite_req; + pjsip_tx_data_add_ref(tdata); + + /* Restore strict route set. + * See https://github.com/pjsip/pjproject/issues/492 + */ + pjsip_restore_strict_route_set(tdata); + + /* Set target */ + tdata->msg->line.req.uri = (pjsip_uri*) + pjsip_uri_clone(tdata->pool, inv->dlg->target_set.current->uri); + + /* Remove branch param in Via header. */ + via = (pjsip_via_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); + via->branch_param.slen = 0; + + /* Process PJSIP_REDIRECT_ACCEPT_REPLACE */ + if (op == PJSIP_REDIRECT_ACCEPT_REPLACE) { + pjsip_to_hdr *to; + pjsip_dialog *dlg = inv->dlg; + enum { TMP_LEN = PJSIP_MAX_URL_SIZE }; + char tmp[TMP_LEN]; + int len; + + /* Replace To header */ + to = PJSIP_MSG_TO_HDR(tdata->msg); + to->uri = (pjsip_uri*) + pjsip_uri_clone(tdata->pool, + dlg->target_set.current->uri); + to->tag.slen = 0; + pj_list_init(&to->other_param); + + /* Re-init dialog remote info */ + dlg->remote.info = (pjsip_to_hdr*) + pjsip_hdr_clone(dlg->pool, to); + + /* Remove header param from remote info */ + if (PJSIP_URI_SCHEME_IS_SIP(dlg->remote.info->uri) || + PJSIP_URI_SCHEME_IS_SIPS(dlg->remote.info->uri)) + { + pjsip_sip_uri *sip_uri = (pjsip_sip_uri *) + pjsip_uri_get_uri(dlg->remote.info->uri); + if (!pj_list_empty(&sip_uri->header_param)) { + /* Remove all header param */ + pj_list_init(&sip_uri->header_param); + } + } + + /* Print the remote info. */ + len = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, + dlg->remote.info->uri, tmp, TMP_LEN); + if (len < 1) { + pj_ansi_strcpy(tmp, "<-error: uri too long->"); + len = (int)pj_ansi_strlen(tmp); + } + pj_strdup2_with_null(dlg->pool, &dlg->remote.info_str, tmp); + + /* Secure? */ + dlg->secure = PJSIP_URI_SCHEME_IS_SIPS(to->uri); + } + + /* Reset message destination info (see #1248). */ + pj_bzero(&tdata->dest_info, sizeof(tdata->dest_info)); + + /* Must invalidate the message! */ + pjsip_tx_data_invalidate_msg(tdata); + + /* Reset the session */ + pjsip_inv_uac_restart(inv, PJ_FALSE); + + /* (re)Send the INVITE request */ + status = pjsip_inv_send_msg(inv, tdata); + } + break; case PJSIP_REDIRECT_STOP: - /* User doesn't want the redirection. Disconnect the session now. */ - inv_set_cause(inv, cancel_code, pjsip_get_status_text(cancel_code)); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + /* User doesn't want the redirection. Disconnect the session now. */ + inv_set_cause(inv, cancel_code, pjsip_get_status_text(cancel_code)); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - /* Caller should expect that the invite session is gone now, so - * we don't need to set status to PJSIP_ESESSIONTERMINATED here. - */ - break; + /* Caller should expect that the invite session is gone now, so + * we don't need to set status to PJSIP_ESESSIONTERMINATED here. + */ + break; case PJSIP_REDIRECT_REJECT: - /* Current target is rejected. Fetch next target if any. */ - if (inv_uac_recurse(inv, cancel_code, NULL, NULL) == PJ_FALSE) { - inv_set_cause(inv, cancel_code, - pjsip_get_status_text(cancel_code)); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - - /* Tell caller that the invite session is gone now */ - status = PJSIP_ESESSIONTERMINATED; - } - break; + /* Current target is rejected. Fetch next target if any. */ + if (inv_uac_recurse(inv, cancel_code, NULL, NULL) == PJ_FALSE) { + inv_set_cause(inv, cancel_code, + pjsip_get_status_text(cancel_code)); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + + /* Tell caller that the invite session is gone now */ + status = PJSIP_ESESSIONTERMINATED; + } + break; case PJSIP_REDIRECT_PENDING: - pj_assert(!"Should not happen"); - break; + pj_assert(!"Should not happen"); + break; } @@ -3156,9 +3155,9 @@ PJ_DEF(pj_status_t) pjsip_inv_process_redirect( pjsip_inv_session *inv, * Create re-INVITE. */ PJ_DEF(pj_status_t) pjsip_inv_reinvite( pjsip_inv_session *inv, - const pj_str_t *new_contact, - const pjmedia_sdp_session *new_offer, - pjsip_tx_data **p_tdata ) + const pj_str_t *new_contact, + const pjmedia_sdp_session *new_offer, + pjsip_tx_data **p_tdata ) { pj_status_t status; pjsip_contact_hdr *contact_hdr = NULL; @@ -3168,74 +3167,74 @@ PJ_DEF(pj_status_t) pjsip_inv_reinvite( pjsip_inv_session *inv, /* Must NOT have a pending INVITE transaction */ if (inv->invite_tsx!=NULL) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; pj_log_push_indent(); pjsip_dlg_inc_lock(inv->dlg); if (new_contact) { - pj_str_t tmp; - const pj_str_t STR_CONTACT = { "Contact", 7 }; - - pj_strdup_with_null(inv->dlg->pool, &tmp, new_contact); - contact_hdr = (pjsip_contact_hdr*) - pjsip_parse_hdr(inv->dlg->pool, &STR_CONTACT, - tmp.ptr, tmp.slen, NULL); - if (!contact_hdr) { - status = PJSIP_EINVALIDURI; - goto on_return; - } + pj_str_t tmp; + const pj_str_t STR_CONTACT = { "Contact", 7 }; + + pj_strdup_with_null(inv->dlg->pool, &tmp, new_contact); + contact_hdr = (pjsip_contact_hdr*) + pjsip_parse_hdr(inv->dlg->pool, &STR_CONTACT, + tmp.ptr, tmp.slen, NULL); + if (!contact_hdr) { + status = PJSIP_EINVALIDURI; + goto on_return; + } } if (new_offer) { - if (!inv->neg) { - status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, - new_offer, - &inv->neg); - if (status != PJ_SUCCESS) - goto on_return; - - } else switch (pjmedia_sdp_neg_get_state(inv->neg)) { - - case PJMEDIA_SDP_NEG_STATE_NULL: - pj_assert(!"Unexpected SDP neg state NULL"); - status = PJ_EBUG; - goto on_return; - - case PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER: - PJ_LOG(4,(inv->obj_name, - "pjsip_inv_reinvite: already have an offer, new " - "offer is ignored")); - break; - - case PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER: - status = pjmedia_sdp_neg_set_local_answer(inv->pool_prov, - inv->neg, - new_offer); - if (status != PJ_SUCCESS) - goto on_return; - break; - - case PJMEDIA_SDP_NEG_STATE_WAIT_NEGO: - PJ_LOG(4,(inv->obj_name, - "pjsip_inv_reinvite: SDP in WAIT_NEGO state, new " - "offer is ignored")); - break; - - case PJMEDIA_SDP_NEG_STATE_DONE: - status = pjmedia_sdp_neg_modify_local_offer2( + if (!inv->neg) { + status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, + new_offer, + &inv->neg); + if (status != PJ_SUCCESS) + goto on_return; + + } else switch (pjmedia_sdp_neg_get_state(inv->neg)) { + + case PJMEDIA_SDP_NEG_STATE_NULL: + pj_assert(!"Unexpected SDP neg state NULL"); + status = PJ_EBUG; + goto on_return; + + case PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER: + PJ_LOG(4,(inv->obj_name, + "pjsip_inv_reinvite: already have an offer, new " + "offer is ignored")); + break; + + case PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER: + status = pjmedia_sdp_neg_set_local_answer(inv->pool_prov, + inv->neg, + new_offer); + if (status != PJ_SUCCESS) + goto on_return; + break; + + case PJMEDIA_SDP_NEG_STATE_WAIT_NEGO: + PJ_LOG(4,(inv->obj_name, + "pjsip_inv_reinvite: SDP in WAIT_NEGO state, new " + "offer is ignored")); + break; + + case PJMEDIA_SDP_NEG_STATE_DONE: + status = pjmedia_sdp_neg_modify_local_offer2( inv->pool_prov, inv->neg, inv->sdp_neg_flags, new_offer); - if (status != PJ_SUCCESS) - goto on_return; - break; - } + if (status != PJ_SUCCESS) + goto on_return; + break; + } } if (contact_hdr) - inv->dlg->local.contact = contact_hdr; + inv->dlg->local.contact = contact_hdr; status = pjsip_inv_invite(inv, p_tdata); @@ -3248,10 +3247,10 @@ PJ_DEF(pj_status_t) pjsip_inv_reinvite( pjsip_inv_session *inv, /* * Create UPDATE. */ -PJ_DEF(pj_status_t) pjsip_inv_update ( pjsip_inv_session *inv, - const pj_str_t *new_contact, - const pjmedia_sdp_session *offer, - pjsip_tx_data **p_tdata ) +PJ_DEF(pj_status_t) pjsip_inv_update ( pjsip_inv_session *inv, + const pj_str_t *new_contact, + const pjmedia_sdp_session *offer, + pjsip_tx_data **p_tdata ) { pjsip_contact_hdr *contact_hdr = NULL; pjsip_tx_data *tdata = NULL; @@ -3265,11 +3264,11 @@ PJ_DEF(pj_status_t) pjsip_inv_update ( pjsip_inv_session *inv, /* Dialog must have been established */ PJ_ASSERT_RETURN(inv->dlg->state == PJSIP_DIALOG_STATE_ESTABLISHED, - PJ_EINVALIDOP); + PJ_EINVALIDOP); /* Invite session must not have been disconnected */ PJ_ASSERT_RETURN(inv->state < PJSIP_INV_STATE_DISCONNECTED, - PJ_EINVALIDOP); + PJ_EINVALIDOP); pj_log_push_indent(); @@ -3278,62 +3277,62 @@ PJ_DEF(pj_status_t) pjsip_inv_update ( pjsip_inv_session *inv, /* Process offer, if any */ if (offer) { - if (inv->state == PJSIP_INV_STATE_EARLY && !inv->sdp_done_early_rel) { - PJ_LOG(4,(inv->dlg->obj_name, - "RFC 3311 section 5.1 recommends against sending UPDATE" - " without reliable prov response")); + if (inv->state == PJSIP_INV_STATE_EARLY && !inv->sdp_done_early_rel) { + PJ_LOG(4,(inv->dlg->obj_name, + "RFC 3311 section 5.1 recommends against sending UPDATE" + " without reliable prov response")); #if PJSIP_INV_UPDATE_EARLY_CHECK_RELIABLE - status = PJ_EINVALIDOP; - goto on_error; + status = PJ_EINVALIDOP; + goto on_error; #endif - } + } - if (pjmedia_sdp_neg_get_state(inv->neg)!=PJMEDIA_SDP_NEG_STATE_DONE) { - PJ_LOG(4,(inv->dlg->obj_name, - "Invalid SDP offer/answer state for UPDATE")); - status = PJ_EINVALIDOP; - goto on_error; - } + if (pjmedia_sdp_neg_get_state(inv->neg)!=PJMEDIA_SDP_NEG_STATE_DONE) { + PJ_LOG(4,(inv->dlg->obj_name, + "Invalid SDP offer/answer state for UPDATE")); + status = PJ_EINVALIDOP; + goto on_error; + } - /* Notify negotiator about the new offer. This will fix the offer - * with correct SDP origin. - */ - status = pjmedia_sdp_neg_modify_local_offer2(inv->pool_prov, inv->neg, - inv->sdp_neg_flags, offer); - if (status != PJ_SUCCESS) - goto on_error; + /* Notify negotiator about the new offer. This will fix the offer + * with correct SDP origin. + */ + status = pjmedia_sdp_neg_modify_local_offer2(inv->pool_prov, inv->neg, + inv->sdp_neg_flags, offer); + if (status != PJ_SUCCESS) + goto on_error; - /* Retrieve the "fixed" offer from negotiator */ - pjmedia_sdp_neg_get_neg_local(inv->neg, &offer); + /* Retrieve the "fixed" offer from negotiator */ + pjmedia_sdp_neg_get_neg_local(inv->neg, &offer); } /* Update Contact if required */ if (new_contact) { - pj_str_t tmp; - const pj_str_t STR_CONTACT = { "Contact", 7 }; - - pj_strdup_with_null(inv->dlg->pool, &tmp, new_contact); - contact_hdr = (pjsip_contact_hdr*) - pjsip_parse_hdr(inv->dlg->pool, &STR_CONTACT, - tmp.ptr, tmp.slen, NULL); - if (!contact_hdr) { - status = PJSIP_EINVALIDURI; - goto on_error; - } + pj_str_t tmp; + const pj_str_t STR_CONTACT = { "Contact", 7 }; + + pj_strdup_with_null(inv->dlg->pool, &tmp, new_contact); + contact_hdr = (pjsip_contact_hdr*) + pjsip_parse_hdr(inv->dlg->pool, &STR_CONTACT, + tmp.ptr, tmp.slen, NULL); + if (!contact_hdr) { + status = PJSIP_EINVALIDURI; + goto on_error; + } - inv->dlg->local.contact = contact_hdr; + inv->dlg->local.contact = contact_hdr; } /* Create request */ status = pjsip_dlg_create_request(inv->dlg, &pjsip_update_method, - -1, &tdata); + -1, &tdata); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Attach SDP body */ if (offer) { - sdp_copy = pjmedia_sdp_session_clone(tdata->pool, offer); - pjsip_create_sdp_body(tdata->pool, sdp_copy, &tdata->msg->body); + sdp_copy = pjmedia_sdp_session_clone(tdata->pool, offer); + pjsip_create_sdp_body(tdata->pool, sdp_copy, &tdata->msg->body); } /* Session Timers spec (RFC 4028) says that Supported header MUST be put @@ -3343,14 +3342,14 @@ PJ_DEF(pj_status_t) pjsip_inv_update ( pjsip_inv_session *inv, */ hdr = pjsip_endpt_get_capability(inv->dlg->endpt, PJSIP_H_SUPPORTED, NULL); if (hdr) { - sup_hdr = (pjsip_supported_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, hdr); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)sup_hdr); + sup_hdr = (pjsip_supported_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, hdr); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)sup_hdr); } status = pjsip_timer_update_req(inv, tdata); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Cleanup Allow & Supported headers from disabled extensions */ cleanup_allow_sup_hdr(inv->options, NULL, NULL, sup_hdr); @@ -3365,7 +3364,7 @@ PJ_DEF(pj_status_t) pjsip_inv_update ( pjsip_inv_session *inv, on_error: if (tdata) - pjsip_tx_data_dec_ref(tdata); + pjsip_tx_data_dec_ref(tdata); /* Unlock dialog. */ pjsip_dlg_dec_lock(inv->dlg); @@ -3378,8 +3377,8 @@ PJ_DEF(pj_status_t) pjsip_inv_update ( pjsip_inv_session *inv, * Create an ACK request. */ PJ_DEF(pj_status_t) pjsip_inv_create_ack(pjsip_inv_session *inv, - int cseq, - pjsip_tx_data **p_tdata) + int cseq, + pjsip_tx_data **p_tdata) { const pjmedia_sdp_session *sdp = NULL; pj_status_t status; @@ -3391,22 +3390,22 @@ PJ_DEF(pj_status_t) pjsip_inv_create_ack(pjsip_inv_session *inv, /* Destroy last_ack */ if (inv->last_ack) { - pjsip_tx_data_dec_ref(inv->last_ack); - inv->last_ack = NULL; + pjsip_tx_data_dec_ref(inv->last_ack); + inv->last_ack = NULL; } /* Create new ACK request */ status = pjsip_dlg_create_request(inv->dlg, pjsip_get_ack_method(), - cseq, &inv->last_ack); + cseq, &inv->last_ack); if (status != PJ_SUCCESS) { - pjsip_dlg_dec_lock(inv->dlg); - return status; + pjsip_dlg_dec_lock(inv->dlg); + return status; } /* See if we have pending SDP answer to send */ sdp = inv_has_pending_answer(inv, inv->invite_tsx); if (sdp) { - inv->last_ack->msg->body = create_sdp_body(inv->last_ack->pool, sdp); + inv->last_ack->msg->body = create_sdp_body(inv->last_ack->pool, sdp); } /* Keep this for subsequent response retransmission */ @@ -3426,7 +3425,7 @@ PJ_DEF(pj_status_t) pjsip_inv_create_ack(pjsip_inv_session *inv, * Send a request or response message. */ PJ_DEF(pj_status_t) pjsip_inv_send_msg( pjsip_inv_session *inv, - pjsip_tx_data *tdata) + pjsip_tx_data *tdata) { pj_status_t status; @@ -3436,102 +3435,102 @@ PJ_DEF(pj_status_t) pjsip_inv_send_msg( pjsip_inv_session *inv, pj_log_push_indent(); PJ_LOG(5,(inv->obj_name, "Sending %s", - pjsip_tx_data_get_info(tdata))); + pjsip_tx_data_get_info(tdata))); if (tdata->msg->type == PJSIP_REQUEST_MSG) { - struct tsx_inv_data *tsx_inv_data; - - pjsip_dlg_inc_lock(inv->dlg); - - /* Check again that we didn't receive incoming re-INVITE */ - if (tdata->msg->line.req.method.id==PJSIP_INVITE_METHOD && - inv->invite_tsx) - { - pjsip_tx_data_dec_ref(tdata); - pjsip_dlg_dec_lock(inv->dlg); - status = PJ_EINVALIDOP; - goto on_error; - } - - /* Don't send BYE before ACK is received - * https://github.com/pjsip/pjproject/issues/1712 - */ - if (tdata->msg->line.req.method.id == PJSIP_BYE_METHOD && - inv->role == PJSIP_ROLE_UAS && - inv->state == PJSIP_INV_STATE_CONNECTING && - inv->cause != PJSIP_SC_REQUEST_TIMEOUT && - inv->cause != PJSIP_SC_TSX_TRANSPORT_ERROR) - { - if (inv->pending_bye) - pjsip_tx_data_dec_ref(inv->pending_bye); - - inv->pending_bye = tdata; - PJ_LOG(4, (inv->obj_name, "Delaying BYE request until " - "ACK is received")); - pjsip_dlg_dec_lock(inv->dlg); - goto on_return; - } - - /* Associate our data in outgoing invite transaction */ - tsx_inv_data = PJ_POOL_ZALLOC_T(inv->pool, struct tsx_inv_data); - tsx_inv_data->inv = inv; - tsx_inv_data->has_sdp = tx_data_has_sdp(tdata); - - pjsip_dlg_dec_lock(inv->dlg); - - status = pjsip_dlg_send_request(inv->dlg, tdata, mod_inv.mod.id, - tsx_inv_data); - if (status != PJ_SUCCESS) { - goto on_error; - } - - /* Check if this is delayed manual ACK (see #416) */ - if (mod_inv.cb.on_send_ack && - tdata->msg->line.req.method.id == PJSIP_ACK_METHOD && - tdata == inv->last_ack) - { - pjsip_dlg_inc_lock(inv->dlg); - - /* Set state to CONFIRMED (if we're not in CONFIRMED yet). - * But don't set it to CONFIRMED if we're already DISCONNECTED - * (this may have been a late 200/OK response. - */ - if (inv->state < PJSIP_INV_STATE_CONFIRMED) { - pjsip_event ack_e; - PJSIP_EVENT_INIT_TX_MSG(ack_e, inv->last_ack); - inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &ack_e); - } else if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { - /* Avoid possible leaked tdata when invite session is - * already destroyed. - * https://github.com/pjsip/pjproject/pull/2432 - */ - pjsip_tx_data_dec_ref(inv->last_ack); - inv->last_ack = NULL; - } - - pjsip_dlg_dec_lock(inv->dlg); - } + struct tsx_inv_data *tsx_inv_data; + + pjsip_dlg_inc_lock(inv->dlg); + + /* Check again that we didn't receive incoming re-INVITE */ + if (tdata->msg->line.req.method.id==PJSIP_INVITE_METHOD && + inv->invite_tsx) + { + pjsip_tx_data_dec_ref(tdata); + pjsip_dlg_dec_lock(inv->dlg); + status = PJ_EINVALIDOP; + goto on_error; + } + + /* Don't send BYE before ACK is received + * https://github.com/pjsip/pjproject/issues/1712 + */ + if (tdata->msg->line.req.method.id == PJSIP_BYE_METHOD && + inv->role == PJSIP_ROLE_UAS && + inv->state == PJSIP_INV_STATE_CONNECTING && + inv->cause != PJSIP_SC_REQUEST_TIMEOUT && + inv->cause != PJSIP_SC_TSX_TRANSPORT_ERROR) + { + if (inv->pending_bye) + pjsip_tx_data_dec_ref(inv->pending_bye); + + inv->pending_bye = tdata; + PJ_LOG(4, (inv->obj_name, "Delaying BYE request until " + "ACK is received")); + pjsip_dlg_dec_lock(inv->dlg); + goto on_return; + } + + /* Associate our data in outgoing invite transaction */ + tsx_inv_data = PJ_POOL_ZALLOC_T(inv->pool, struct tsx_inv_data); + tsx_inv_data->inv = inv; + tsx_inv_data->has_sdp = tx_data_has_sdp(tdata); + + pjsip_dlg_dec_lock(inv->dlg); + + status = pjsip_dlg_send_request(inv->dlg, tdata, mod_inv.mod.id, + tsx_inv_data); + if (status != PJ_SUCCESS) { + goto on_error; + } + + /* Check if this is delayed manual ACK (see #416) */ + if (mod_inv.cb.on_send_ack && + tdata->msg->line.req.method.id == PJSIP_ACK_METHOD && + tdata == inv->last_ack) + { + pjsip_dlg_inc_lock(inv->dlg); + + /* Set state to CONFIRMED (if we're not in CONFIRMED yet). + * But don't set it to CONFIRMED if we're already DISCONNECTED + * (this may have been a late 200/OK response. + */ + if (inv->state < PJSIP_INV_STATE_CONFIRMED) { + pjsip_event ack_e; + PJSIP_EVENT_INIT_TX_MSG(ack_e, inv->last_ack); + inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &ack_e); + } else if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { + /* Avoid possible leaked tdata when invite session is + * already destroyed. + * https://github.com/pjsip/pjproject/pull/2432 + */ + pjsip_tx_data_dec_ref(inv->last_ack); + inv->last_ack = NULL; + } + + pjsip_dlg_dec_lock(inv->dlg); + } } else { - pjsip_cseq_hdr *cseq; + pjsip_cseq_hdr *cseq; - /* Can only do this to send response to original INVITE - * request. - */ - PJ_ASSERT_RETURN((cseq=(pjsip_cseq_hdr*)pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL))!=NULL - && (cseq->cseq == inv->invite_tsx->cseq), - PJ_EINVALIDOP); + /* Can only do this to send response to original INVITE + * request. + */ + PJ_ASSERT_RETURN((cseq=(pjsip_cseq_hdr*)pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL))!=NULL + && (cseq->cseq == inv->invite_tsx->cseq), + PJ_EINVALIDOP); - if (inv->options & PJSIP_INV_REQUIRE_100REL) { - status = pjsip_100rel_tx_response(inv, tdata); - } else - { - status = pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata); - } + if (inv->options & PJSIP_INV_REQUIRE_100REL) { + status = pjsip_100rel_tx_response(inv, tdata); + } else + { + status = pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata); + } - if (status != PJ_SUCCESS) { - goto on_error; - } + if (status != PJ_SUCCESS) { + goto on_error; + } } /* Done */ @@ -3549,8 +3548,8 @@ PJ_DEF(pj_status_t) pjsip_inv_send_msg( pjsip_inv_session *inv, * Respond to incoming CANCEL request. */ static void inv_respond_incoming_cancel(pjsip_inv_session *inv, - pjsip_transaction *cancel_tsx, - pjsip_event *e) + pjsip_transaction *cancel_tsx, + pjsip_event *e) { pjsip_tx_data *tdata; pjsip_transaction *invite_tsx; @@ -3571,28 +3570,28 @@ static void inv_respond_incoming_cancel(pjsip_inv_session *inv, * from the INVITE session has been suppressed. */ if (mod_inv.cb.on_tsx_state_changed && inv->notify) - (*mod_inv.cb.on_tsx_state_changed)(inv, cancel_tsx, e); + (*mod_inv.cb.on_tsx_state_changed)(inv, cancel_tsx, e); /* See if we have matching INVITE server transaction: */ pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, - pjsip_get_invite_method(), rdata); + pjsip_get_invite_method(), rdata); invite_tsx = pjsip_tsx_layer_find_tsx2(&key, PJ_TRUE); if (invite_tsx == NULL) { - /* Invite transaction not found! - * Respond CANCEL with 481 (RFC 3261 Section 9.2 page 55) - */ - status = pjsip_dlg_create_response( inv->dlg, rdata, 481, NULL, - &tdata); + /* Invite transaction not found! + * Respond CANCEL with 481 (RFC 3261 Section 9.2 page 55) + */ + status = pjsip_dlg_create_response( inv->dlg, rdata, 481, NULL, + &tdata); } else { - /* Always answer CANCEL will 200 (OK) regardless of - * the state of the INVITE transaction. - */ - status = pjsip_dlg_create_response( inv->dlg, rdata, 200, NULL, - &tdata); + /* Always answer CANCEL will 200 (OK) regardless of + * the state of the INVITE transaction. + */ + status = pjsip_dlg_create_response( inv->dlg, rdata, 200, NULL, + &tdata); } /* See if we have created the response successfully. */ @@ -3608,25 +3607,25 @@ static void inv_respond_incoming_cancel(pjsip_inv_session *inv, */ if (invite_tsx && invite_tsx->status_code < 200) { - pj_assert(invite_tsx->last_tx != NULL); + pj_assert(invite_tsx->last_tx != NULL); - tdata = invite_tsx->last_tx; + tdata = invite_tsx->last_tx; - status = pjsip_dlg_modify_response(inv->dlg, tdata, 487, NULL); - if (status == PJ_SUCCESS) { - /* Remove the message body */ - tdata->msg->body = NULL; - if (inv->options & PJSIP_INV_REQUIRE_100REL) { - status = pjsip_100rel_tx_response(inv, tdata); - } else { - status = pjsip_dlg_send_response(inv->dlg, invite_tsx, - tdata); - } - } + status = pjsip_dlg_modify_response(inv->dlg, tdata, 487, NULL); + if (status == PJ_SUCCESS) { + /* Remove the message body */ + tdata->msg->body = NULL; + if (inv->options & PJSIP_INV_REQUIRE_100REL) { + status = pjsip_100rel_tx_response(inv, tdata); + } else { + status = pjsip_dlg_send_response(inv->dlg, invite_tsx, + tdata); + } + } } if (invite_tsx) - pj_grp_lock_dec_ref(invite_tsx->grp_lock); + pj_grp_lock_dec_ref(invite_tsx->grp_lock); } @@ -3634,9 +3633,9 @@ static void inv_respond_incoming_cancel(pjsip_inv_session *inv, * Respond to incoming BYE request. */ static void inv_respond_incoming_bye( pjsip_inv_session *inv, - pjsip_transaction *bye_tsx, - pjsip_rx_data *rdata, - pjsip_event *e ) + pjsip_transaction *bye_tsx, + pjsip_rx_data *rdata, + pjsip_event *e ) { pj_status_t status; pjsip_tx_data *tdata; @@ -3652,8 +3651,8 @@ static void inv_respond_incoming_bye( pjsip_inv_session *inv, /* Terminate session: */ if (inv->state != PJSIP_INV_STATE_DISCONNECTED) { - inv_set_cause(inv, PJSIP_SC_OK, NULL); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + inv_set_cause(inv, PJSIP_SC_OK, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); } } @@ -3661,52 +3660,52 @@ static void inv_respond_incoming_bye( pjsip_inv_session *inv, * Respond to BYE request. */ static void inv_handle_bye_response( pjsip_inv_session *inv, - pjsip_transaction *tsx, - pjsip_rx_data *rdata, - pjsip_event *e ) + pjsip_transaction *tsx, + pjsip_rx_data *rdata, + pjsip_event *e ) { pj_status_t status; if (e->body.tsx_state.type != PJSIP_EVENT_RX_MSG) { - inv_set_cause(inv, PJSIP_SC_OK, NULL); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - return; + inv_set_cause(inv, PJSIP_SC_OK, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + return; } /* Handle 401/407 challenge. */ if (tsx->status_code == 401 || tsx->status_code == 407) { - pjsip_tx_data *tdata; - - status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess, - rdata, - tsx->last_tx, - &tdata); - - if (status != PJ_SUCCESS) { - - /* Does not have proper credentials. - * End the session anyway. - */ - inv_set_cause(inv, PJSIP_SC_OK, NULL); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - - } else { - struct tsx_inv_data *tsx_inv_data; - - tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; - if (tsx_inv_data) - tsx_inv_data->retrying = PJ_TRUE; - - /* Re-send BYE. */ - status = pjsip_inv_send_msg(inv, tdata); - } + pjsip_tx_data *tdata; + + status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess, + rdata, + tsx->last_tx, + &tdata); + + if (status != PJ_SUCCESS) { + + /* Does not have proper credentials. + * End the session anyway. + */ + inv_set_cause(inv, PJSIP_SC_OK, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + + } else { + struct tsx_inv_data *tsx_inv_data; + + tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; + if (tsx_inv_data) + tsx_inv_data->retrying = PJ_TRUE; + + /* Re-send BYE. */ + status = pjsip_inv_send_msg(inv, tdata); + } } else { - /* End the session. */ - inv_set_cause(inv, PJSIP_SC_OK, NULL); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + /* End the session. */ + inv_set_cause(inv, PJSIP_SC_OK, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); } } @@ -3715,7 +3714,7 @@ static void inv_handle_bye_response( pjsip_inv_session *inv, * Respond to incoming UPDATE request. */ static void inv_respond_incoming_update(pjsip_inv_session *inv, - pjsip_event *e) + pjsip_event *e) { pjmedia_sdp_neg_state neg_state; pj_status_t status; @@ -3724,19 +3723,19 @@ static void inv_respond_incoming_update(pjsip_inv_session *inv, pjsip_status_code st_code; pj_assert(e->type == PJSIP_EVENT_TSX_STATE && - e->body.tsx_state.type == PJSIP_EVENT_RX_MSG); + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG); rdata = e->body.tsx_state.src.rdata; /* Check routing URI scheme for secure dialog */ if (!inv_check_secure_dlg(inv, e)) - return; + return; /* Invoke Session Timers module */ status = pjsip_timer_process_req(inv, rdata, &st_code); if (status != PJ_SUCCESS) { - status = pjsip_dlg_create_response(inv->dlg, rdata, st_code, - NULL, &tdata); - goto on_return; + status = pjsip_dlg_create_response(inv->dlg, rdata, st_code, + NULL, &tdata); + goto on_return; } neg_state = pjmedia_sdp_neg_get_state(inv->neg); @@ -3746,78 +3745,78 @@ static void inv_respond_incoming_update(pjsip_inv_session *inv, */ if (rdata->msg_info.msg->body == NULL) { - status = pjsip_dlg_create_response(inv->dlg, rdata, - 200, NULL, &tdata); + status = pjsip_dlg_create_response(inv->dlg, rdata, + 200, NULL, &tdata); } /* Send 491 if we receive UPDATE while we're waiting for an answer */ else if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) { - status = pjsip_dlg_create_response(inv->dlg, rdata, - PJSIP_SC_REQUEST_PENDING, NULL, - &tdata); - } + status = pjsip_dlg_create_response(inv->dlg, rdata, + PJSIP_SC_REQUEST_PENDING, NULL, + &tdata); + } /* Send 500 with Retry-After header set randomly between 0 and 10 if we * receive UPDATE while we haven't sent answer. */ else if (neg_state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER || - neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) + neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) { pjsip_retry_after_hdr *ra_hdr; - int val; + int val; status = pjsip_dlg_create_response(inv->dlg, rdata, - PJSIP_SC_INTERNAL_SERVER_ERROR, - NULL, &tdata); + PJSIP_SC_INTERNAL_SERVER_ERROR, + NULL, &tdata); val = (pj_rand() % 10); ra_hdr = pjsip_retry_after_hdr_create(tdata->pool, val); pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)ra_hdr); } else { - /* We receive new offer from remote */ - inv_check_sdp_in_incoming_msg(inv, pjsip_rdata_get_tsx(rdata), rdata); - - /* Application MUST have supplied the answer by now. - * If so, negotiate the SDP. - */ - neg_state = pjmedia_sdp_neg_get_state(inv->neg); - if (neg_state != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO || - (status=inv_negotiate_sdp(inv)) != PJ_SUCCESS) - { - /* Negotiation has failed. If negotiator is still - * stuck at non-DONE state, cancel any ongoing offer. - */ - neg_state = pjmedia_sdp_neg_get_state(inv->neg); - if (neg_state != PJMEDIA_SDP_NEG_STATE_DONE) { - pjmedia_sdp_neg_cancel_offer(inv->neg); - } - - status = pjsip_dlg_create_response(inv->dlg, rdata, - PJSIP_SC_NOT_ACCEPTABLE_HERE, - NULL, &tdata); - } else { - /* New media has been negotiated successfully, send 200/OK */ - status = pjsip_dlg_create_response(inv->dlg, rdata, - PJSIP_SC_OK, NULL, &tdata); - if (status == PJ_SUCCESS) { - const pjmedia_sdp_session *sdp; - status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp); - if (status == PJ_SUCCESS) - tdata->msg->body = create_sdp_body(tdata->pool, sdp); - } - } + /* We receive new offer from remote */ + inv_check_sdp_in_incoming_msg(inv, pjsip_rdata_get_tsx(rdata), rdata); + + /* Application MUST have supplied the answer by now. + * If so, negotiate the SDP. + */ + neg_state = pjmedia_sdp_neg_get_state(inv->neg); + if (neg_state != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO || + (status=inv_negotiate_sdp(inv)) != PJ_SUCCESS) + { + /* Negotiation has failed. If negotiator is still + * stuck at non-DONE state, cancel any ongoing offer. + */ + neg_state = pjmedia_sdp_neg_get_state(inv->neg); + if (neg_state != PJMEDIA_SDP_NEG_STATE_DONE) { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } + + status = pjsip_dlg_create_response(inv->dlg, rdata, + PJSIP_SC_NOT_ACCEPTABLE_HERE, + NULL, &tdata); + } else { + /* New media has been negotiated successfully, send 200/OK */ + status = pjsip_dlg_create_response(inv->dlg, rdata, + PJSIP_SC_OK, NULL, &tdata); + if (status == PJ_SUCCESS) { + const pjmedia_sdp_session *sdp; + status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp); + if (status == PJ_SUCCESS) + tdata->msg->body = create_sdp_body(tdata->pool, sdp); + } + } } on_return: /* Invoke Session Timers */ if (status == PJ_SUCCESS) - status = pjsip_timer_update_resp(inv, tdata); + status = pjsip_timer_update_resp(inv, tdata); if (status != PJ_SUCCESS) { - if (tdata != NULL) { - pjsip_tx_data_dec_ref(tdata); - tdata = NULL; - } - return; + if (tdata != NULL) { + pjsip_tx_data_dec_ref(tdata); + tdata = NULL; + } + return; } pjsip_dlg_send_response(inv->dlg, pjsip_rdata_get_tsx(rdata), tdata); @@ -3840,110 +3839,110 @@ static pj_bool_t inv_handle_update_response( pjsip_inv_session *inv, /* Handle 401/407 challenge. */ if (tsx->state == PJSIP_TSX_STATE_COMPLETED && - (tsx->status_code == 401 || tsx->status_code == 407)) + (tsx->status_code == 401 || tsx->status_code == 407)) { - pjsip_tx_data *tdata; - - status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess, - e->body.tsx_state.src.rdata, - tsx->last_tx, - &tdata); - - if (status != PJ_SUCCESS) { - - /* Somehow failed. Probably it's not a good idea to terminate - * the session since this is just a request within dialog. And - * even if we terminate we should send BYE. - */ - /* - inv_set_cause(inv, PJSIP_SC_OK, NULL); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - */ - - } else { - if (tsx_inv_data) - tsx_inv_data->retrying = PJ_TRUE; - - /* Re-send request. */ - status = pjsip_inv_send_msg(inv, tdata); - } - - handled = PJ_TRUE; + pjsip_tx_data *tdata; + + status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess, + e->body.tsx_state.src.rdata, + tsx->last_tx, + &tdata); + + if (status != PJ_SUCCESS) { + + /* Somehow failed. Probably it's not a good idea to terminate + * the session since this is just a request within dialog. And + * even if we terminate we should send BYE. + */ + /* + inv_set_cause(inv, PJSIP_SC_OK, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + */ + + } else { + if (tsx_inv_data) + tsx_inv_data->retrying = PJ_TRUE; + + /* Re-send request. */ + status = pjsip_inv_send_msg(inv, tdata); + } + + handled = PJ_TRUE; } /* Process 422 response */ else if (tsx->state == PJSIP_TSX_STATE_COMPLETED && - tsx->status_code == 422) + tsx->status_code == 422) { - status = handle_timer_response(inv, e->body.tsx_state.src.rdata, - PJ_FALSE); - handled = PJ_TRUE; + status = handle_timer_response(inv, e->body.tsx_state.src.rdata, + PJ_FALSE); + handled = PJ_TRUE; } /* Process 2xx response */ else if (tsx->state == PJSIP_TSX_STATE_COMPLETED && - tsx->status_code/100 == 2) + tsx->status_code/100 == 2) { - pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; - - /* Check routing URI scheme for secure dialog */ - if (inv_check_secure_dlg(inv, e)) { - - status = handle_timer_response(inv, rdata, PJ_FALSE); - - if (rdata->msg_info.msg->body) { - /* Only process remote SDP if we have sent local offer */ - if (inv->neg && pjmedia_sdp_neg_get_state(inv->neg) == - PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) - { - status = inv_check_sdp_in_incoming_msg(inv, tsx, rdata); - } else { - PJ_LOG(5,(THIS_FILE, "Ignored message body in %s as no " - "local offer was sent", - pjsip_rx_data_get_info(rdata))); - } - } - } + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + + /* Check routing URI scheme for secure dialog */ + if (inv_check_secure_dlg(inv, e)) { + + status = handle_timer_response(inv, rdata, PJ_FALSE); + + if (rdata->msg_info.msg->body) { + /* Only process remote SDP if we have sent local offer */ + if (inv->neg && pjmedia_sdp_neg_get_state(inv->neg) == + PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) + { + status = inv_check_sdp_in_incoming_msg(inv, tsx, rdata); + } else { + PJ_LOG(5,(THIS_FILE, "Ignored message body in %s as no " + "local offer was sent", + pjsip_rx_data_get_info(rdata))); + } + } + } handled = PJ_TRUE; } /* Process 502/503 error */ else if ((tsx->state == PJSIP_TSX_STATE_TERMINATED) && - (tsx->status_code == 503 || tsx->status_code == 502)) + (tsx->status_code == 503 || tsx->status_code == 502)) { - status = pjsip_timer_handle_refresh_error(inv, e); + status = pjsip_timer_handle_refresh_error(inv, e); - handled = PJ_TRUE; + handled = PJ_TRUE; } /* Get/attach invite session's transaction data */ else { - /* Session-Timer needs to see any error responses, to determine - * whether peer supports UPDATE with empty body. - */ - if (tsx->state == PJSIP_TSX_STATE_COMPLETED && - tsx->role == PJSIP_ROLE_UAC) - { - status = handle_timer_response(inv, e->body.tsx_state.src.rdata, - PJ_FALSE); - handled = PJ_TRUE; - } + /* Session-Timer needs to see any error responses, to determine + * whether peer supports UPDATE with empty body. + */ + if (tsx->state == PJSIP_TSX_STATE_COMPLETED && + tsx->role == PJSIP_ROLE_UAC) + { + status = handle_timer_response(inv, e->body.tsx_state.src.rdata, + PJ_FALSE); + handled = PJ_TRUE; + } } /* Cancel the negotiation if we don't get successful negotiation by now, * unless it's authentication challenge and the request is being retried. */ if (pjmedia_sdp_neg_get_state(inv->neg) == - PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER && - tsx_inv_data && tsx_inv_data->sdp_done == PJ_FALSE && - !tsx_inv_data->retrying && tsx_inv_data->has_sdp) + PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER && + tsx_inv_data && tsx_inv_data->sdp_done == PJ_FALSE && + !tsx_inv_data->retrying && tsx_inv_data->has_sdp) { - pjmedia_sdp_neg_cancel_offer(inv->neg); + pjmedia_sdp_neg_cancel_offer(inv->neg); - /* Prevent from us cancelling different offer! */ - tsx_inv_data->sdp_done = PJ_TRUE; + /* Prevent from us cancelling different offer! */ + tsx_inv_data->sdp_done = PJ_TRUE; } return handled; @@ -3954,7 +3953,7 @@ static pj_bool_t inv_handle_update_response( pjsip_inv_session *inv, * Handle incoming reliable response. */ static void inv_handle_incoming_reliable_response(pjsip_inv_session *inv, - pjsip_rx_data *rdata) + pjsip_rx_data *rdata) { pjsip_tx_data *tdata; const pjmedia_sdp_session *sdp; @@ -3963,12 +3962,12 @@ static void inv_handle_incoming_reliable_response(pjsip_inv_session *inv, /* Create PRACK */ status = pjsip_100rel_create_prack(inv, rdata, &tdata); if (status != PJ_SUCCESS) - return; + return; /* See if we need to attach SDP answer on the PRACK request */ sdp = inv_has_pending_answer(inv, pjsip_rdata_get_tsx(rdata)); if (sdp) { - tdata->msg->body = create_sdp_body(tdata->pool, sdp); + tdata->msg->body = create_sdp_body(tdata->pool, sdp); } /* Send PRACK (must be using 100rel module!) */ @@ -3980,7 +3979,7 @@ static void inv_handle_incoming_reliable_response(pjsip_inv_session *inv, * Handle incoming PRACK. */ static void inv_respond_incoming_prack(pjsip_inv_session *inv, - pjsip_rx_data *rdata) + pjsip_rx_data *rdata) { pj_status_t status; @@ -3989,15 +3988,15 @@ static void inv_respond_incoming_prack(pjsip_inv_session *inv, */ status = pjsip_100rel_on_rx_prack(inv, rdata); if (status != PJ_SUCCESS) - return; + return; /* Now check for SDP answer in the PRACK request */ if (rdata->msg_info.msg->body) { - status = inv_check_sdp_in_incoming_msg(inv, - pjsip_rdata_get_tsx(rdata), rdata); + status = inv_check_sdp_in_incoming_msg(inv, + pjsip_rdata_get_tsx(rdata), rdata); } else { - /* No SDP body */ - status = -1; + /* No SDP body */ + status = -1; } /* If SDP negotiation has been successful, also mark the @@ -4005,24 +4004,24 @@ static void inv_respond_incoming_prack(pjsip_inv_session *inv, * done too. */ if (status == PJ_SUCCESS && inv->invite_tsx) { - struct tsx_inv_data *tsx_inv_data; - - /* Get/attach invite session's transaction data */ - tsx_inv_data = (struct tsx_inv_data*) - inv->invite_tsx->mod_data[mod_inv.mod.id]; - if (tsx_inv_data == NULL) { - tsx_inv_data = PJ_POOL_ZALLOC_T(inv->invite_tsx->pool, - struct tsx_inv_data); - tsx_inv_data->inv = inv; - tsx_inv_data->has_sdp = PJ_TRUE; - inv->invite_tsx->mod_data[mod_inv.mod.id] = tsx_inv_data; - } - - tsx_inv_data->sdp_done = PJ_TRUE; + struct tsx_inv_data *tsx_inv_data; + + /* Get/attach invite session's transaction data */ + tsx_inv_data = (struct tsx_inv_data*) + inv->invite_tsx->mod_data[mod_inv.mod.id]; + if (tsx_inv_data == NULL) { + tsx_inv_data = PJ_POOL_ZALLOC_T(inv->invite_tsx->pool, + struct tsx_inv_data); + tsx_inv_data->inv = inv; + tsx_inv_data->has_sdp = PJ_TRUE; + inv->invite_tsx->mod_data[mod_inv.mod.id] = tsx_inv_data; + } + + tsx_inv_data->sdp_done = PJ_TRUE; } if (pjmedia_sdp_neg_get_state(inv->neg) == PJMEDIA_SDP_NEG_STATE_DONE) { - inv->sdp_done_early_rel = PJ_TRUE; + inv->sdp_done_early_rel = PJ_TRUE; } } @@ -4032,103 +4031,103 @@ static void inv_respond_incoming_prack(pjsip_inv_session *inv, * UPDATE specifies secure Contact and Record-Route headers. */ static pj_bool_t inv_check_secure_dlg(pjsip_inv_session *inv, - pjsip_event *e) + pjsip_event *e) { pjsip_transaction *tsx = e->body.tsx_state.tsx; pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx); if (pjsip_cfg()->endpt.disable_secure_dlg_check == PJ_FALSE && - dlg->secure && e->body.tsx_state.type==PJSIP_EVENT_RX_MSG && - ((tsx->role==PJSIP_ROLE_UAC && tsx->status_code/100 == 2) || - (tsx->role==PJSIP_ROLE_UAS && tsx->state == PJSIP_TSX_STATE_TRYING)) - && - (tsx->method.id==PJSIP_INVITE_METHOD || - pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)) + dlg->secure && e->body.tsx_state.type==PJSIP_EVENT_RX_MSG && + ((tsx->role==PJSIP_ROLE_UAC && tsx->status_code/100 == 2) || + (tsx->role==PJSIP_ROLE_UAS && tsx->state == PJSIP_TSX_STATE_TRYING)) + && + (tsx->method.id==PJSIP_INVITE_METHOD || + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)) { - const pjsip_msg *msg = e->body.tsx_state.src.rdata->msg_info.msg; - pj_status_t status = PJ_SUCCESS; - pjsip_contact_hdr *c; - - /* Check Contact header */ - c = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(msg,PJSIP_H_CONTACT, NULL); - if (!(c && c->uri && PJSIP_URI_SCHEME_IS_SIPS(c->uri))) - status = PJSIP_ESESSIONINSECURE; - - /* Check top Record-Route header */ - if (status == PJ_SUCCESS) { - pjsip_rr_hdr *r = (pjsip_rr_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_RECORD_ROUTE, - NULL); - if (r && !PJSIP_URI_SCHEME_IS_SIPS(&r->name_addr)) { - /* Not "sips", check if it is "sip" and has param - * "transport=tls". - */ - if (PJSIP_URI_SCHEME_IS_SIP(&r->name_addr)) { - pjsip_sip_uri *sip_uri = (pjsip_sip_uri*) - pjsip_uri_get_uri(r->name_addr.uri); - if (pj_stricmp2(&sip_uri->transport_param, "tls")!=0) - status = PJSIP_ESESSIONINSECURE; - } else { - /* Not "sips" nor "sip", treat it as insecure? */ - status = PJSIP_ESESSIONINSECURE; - } - } - } - - if (status == PJSIP_ESESSIONINSECURE) { - /* Found non-SIPS scheme in Contact/Record-Route header */ - - pj_str_t warn_text = pj_str("SIPS Required"); - - if (tsx->role == PJSIP_ROLE_UAC) { - - /* If we are UAC, terminate the session */ - pjsip_tx_data *bye; - - PJ_LOG(4,(inv->obj_name, - "Secure dialog requires SIPS scheme in Contact and " - "Record-Route headers, ending the session")); - - status = pjsip_inv_end_session(inv, 480, NULL, &bye); - if (status == PJ_SUCCESS && bye) { - pjsip_warning_hdr *w; - w = pjsip_warning_hdr_create(bye->pool, 381, - pjsip_endpt_name(dlg->endpt), - &warn_text); - if (w) - pjsip_msg_add_hdr(bye->msg, (pjsip_hdr*)w); - - status = pjsip_inv_send_msg(inv, bye); - } - - } else { - - /* If we are UAS, reject the request */ - pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; - pjsip_tx_data *tdata; - - PJ_LOG(4,(inv->obj_name, - "Secure dialog requires SIPS scheme in Contact and " - "Route headers, rejecting the request")); - - status = pjsip_dlg_create_response(inv->dlg, rdata, 480, - NULL, &tdata); - if (status == PJ_SUCCESS) { - pjsip_warning_hdr *w; - w = pjsip_warning_hdr_create(tdata->pool, 381, - pjsip_endpt_name(dlg->endpt), - &warn_text); - if (w) - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)w); - - pjsip_dlg_send_response(dlg, tsx, tdata); - } - - } - - return PJ_FALSE; - } + const pjsip_msg *msg = e->body.tsx_state.src.rdata->msg_info.msg; + pj_status_t status = PJ_SUCCESS; + pjsip_contact_hdr *c; + + /* Check Contact header */ + c = (pjsip_contact_hdr*) + pjsip_msg_find_hdr(msg,PJSIP_H_CONTACT, NULL); + if (!(c && c->uri && PJSIP_URI_SCHEME_IS_SIPS(c->uri))) + status = PJSIP_ESESSIONINSECURE; + + /* Check top Record-Route header */ + if (status == PJ_SUCCESS) { + pjsip_rr_hdr *r = (pjsip_rr_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_RECORD_ROUTE, + NULL); + if (r && !PJSIP_URI_SCHEME_IS_SIPS(&r->name_addr)) { + /* Not "sips", check if it is "sip" and has param + * "transport=tls". + */ + if (PJSIP_URI_SCHEME_IS_SIP(&r->name_addr)) { + pjsip_sip_uri *sip_uri = (pjsip_sip_uri*) + pjsip_uri_get_uri(r->name_addr.uri); + if (pj_stricmp2(&sip_uri->transport_param, "tls")!=0) + status = PJSIP_ESESSIONINSECURE; + } else { + /* Not "sips" nor "sip", treat it as insecure? */ + status = PJSIP_ESESSIONINSECURE; + } + } + } + + if (status == PJSIP_ESESSIONINSECURE) { + /* Found non-SIPS scheme in Contact/Record-Route header */ + + pj_str_t warn_text = pj_str("SIPS Required"); + + if (tsx->role == PJSIP_ROLE_UAC) { + + /* If we are UAC, terminate the session */ + pjsip_tx_data *bye; + + PJ_LOG(4,(inv->obj_name, + "Secure dialog requires SIPS scheme in Contact and " + "Record-Route headers, ending the session")); + + status = pjsip_inv_end_session(inv, 480, NULL, &bye); + if (status == PJ_SUCCESS && bye) { + pjsip_warning_hdr *w; + w = pjsip_warning_hdr_create(bye->pool, 381, + pjsip_endpt_name(dlg->endpt), + &warn_text); + if (w) + pjsip_msg_add_hdr(bye->msg, (pjsip_hdr*)w); + + status = pjsip_inv_send_msg(inv, bye); + } + + } else { + + /* If we are UAS, reject the request */ + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + pjsip_tx_data *tdata; + + PJ_LOG(4,(inv->obj_name, + "Secure dialog requires SIPS scheme in Contact and " + "Route headers, rejecting the request")); + + status = pjsip_dlg_create_response(inv->dlg, rdata, 480, + NULL, &tdata); + if (status == PJ_SUCCESS) { + pjsip_warning_hdr *w; + w = pjsip_warning_hdr_create(tdata->pool, 381, + pjsip_endpt_name(dlg->endpt), + &warn_text); + if (w) + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)w); + + pjsip_dlg_send_response(dlg, tsx, tdata); + } + + } + + return PJ_FALSE; + } } return PJ_TRUE; @@ -4148,57 +4147,57 @@ static void inv_on_state_null( pjsip_inv_session *inv, pjsip_event *e) if (tsx->method.id == PJSIP_INVITE_METHOD) { - /* Keep the initial INVITE transaction. */ - if (inv->invite_tsx == NULL) - inv->invite_tsx = tsx; + /* Keep the initial INVITE transaction. */ + if (inv->invite_tsx == NULL) + inv->invite_tsx = tsx; - if (dlg->role == PJSIP_ROLE_UAC) { + if (dlg->role == PJSIP_ROLE_UAC) { - /* Save the original INVITE request. + /* Save the original INVITE request. * We may need to resend the INVITE if we receive redirection * or session timer too small response. - */ - if (1) { - if (inv->invite_req) { - pjsip_tx_data_dec_ref(inv->invite_req); - inv->invite_req = NULL; - } - inv->invite_req = tsx->last_tx; - pjsip_tx_data_add_ref(inv->invite_req); - } - - switch (tsx->state) { - case PJSIP_TSX_STATE_CALLING: - inv_set_state(inv, PJSIP_INV_STATE_CALLING, e); - break; - default: - inv_on_state_calling(inv, e); - break; - } - - } else { - switch (tsx->state) { - case PJSIP_TSX_STATE_TRYING: - inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e); - break; - case PJSIP_TSX_STATE_PROCEEDING: - inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e); - if (tsx->status_code > 100) - inv_set_state(inv, PJSIP_INV_STATE_EARLY, e); - break; - case PJSIP_TSX_STATE_TERMINATED: - /* there is a failure in sending response. */ - inv_set_cause(inv, tsx->status_code, &tsx->status_text); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - break; - default: - inv_on_state_incoming(inv, e); - break; - } - } + */ + if (1) { + if (inv->invite_req) { + pjsip_tx_data_dec_ref(inv->invite_req); + inv->invite_req = NULL; + } + inv->invite_req = tsx->last_tx; + pjsip_tx_data_add_ref(inv->invite_req); + } + + switch (tsx->state) { + case PJSIP_TSX_STATE_CALLING: + inv_set_state(inv, PJSIP_INV_STATE_CALLING, e); + break; + default: + inv_on_state_calling(inv, e); + break; + } + + } else { + switch (tsx->state) { + case PJSIP_TSX_STATE_TRYING: + inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e); + break; + case PJSIP_TSX_STATE_PROCEEDING: + inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e); + if (tsx->status_code > 100) + inv_set_state(inv, PJSIP_INV_STATE_EARLY, e); + break; + case PJSIP_TSX_STATE_TERMINATED: + /* there is a failure in sending response. */ + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + break; + default: + inv_on_state_incoming(inv, e); + break; + } + } } else { - pj_assert(!"Unexpected transaction type"); + pj_assert(!"Unexpected transaction type"); } } @@ -4209,7 +4208,7 @@ static void inv_on_state_null( pjsip_inv_session *inv, pjsip_event *e) * - resend request on 422 response. */ static pj_bool_t handle_uac_tsx_response(pjsip_inv_session *inv, - pjsip_event *e) + pjsip_event *e) { /* RFC 3261 Section 12.2.1.2: * If the response for a request within a dialog is a 481 @@ -4233,79 +4232,79 @@ static pj_bool_t handle_uac_tsx_response(pjsip_inv_session *inv, * but only the transaction. */ if (inv->state != PJSIP_INV_STATE_DISCONNECTED && - ((tsx->status_code == PJSIP_SC_CALL_TSX_DOES_NOT_EXIST && - tsx->method.id != PJSIP_CANCEL_METHOD) || - (tsx->status_code == PJSIP_SC_REQUEST_TIMEOUT && - !pjsip_cfg()->endpt.keep_inv_after_tsx_timeout))) + ((tsx->status_code == PJSIP_SC_CALL_TSX_DOES_NOT_EXIST && + tsx->method.id != PJSIP_CANCEL_METHOD) || + (tsx->status_code == PJSIP_SC_REQUEST_TIMEOUT && + !pjsip_cfg()->endpt.keep_inv_after_tsx_timeout))) { - pjsip_tx_data *bye; - pj_status_t status; + pjsip_tx_data *bye; + pj_status_t status; - inv_set_cause(inv, tsx->status_code, &tsx->status_text); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - /* Send BYE */ - status = pjsip_dlg_create_request(inv->dlg, pjsip_get_bye_method(), - -1, &bye); - if (status == PJ_SUCCESS) { - pjsip_inv_send_msg(inv, bye); - } + /* Send BYE */ + status = pjsip_dlg_create_request(inv->dlg, pjsip_get_bye_method(), + -1, &bye); + if (status == PJ_SUCCESS) { + pjsip_inv_send_msg(inv, bye); + } - return PJ_TRUE; /* Handled */ + return PJ_TRUE; /* Handled */ } /* Handle 401/407 challenge. */ else if (tsx->state == PJSIP_TSX_STATE_COMPLETED && - (tsx->status_code == PJSIP_SC_UNAUTHORIZED || - tsx->status_code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED)) + (tsx->status_code == PJSIP_SC_UNAUTHORIZED || + tsx->status_code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED)) { - pjsip_tx_data *tdata; - pj_status_t status; + pjsip_tx_data *tdata; + pj_status_t status; - if (tsx->method.id == PJSIP_INVITE_METHOD) - inv->invite_tsx = NULL; + if (tsx->method.id == PJSIP_INVITE_METHOD) + inv->invite_tsx = NULL; - status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess, - e->body.tsx_state.src.rdata, - tsx->last_tx, &tdata); + status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess, + e->body.tsx_state.src.rdata, + tsx->last_tx, &tdata); - if (status != PJ_SUCCESS) { - /* Somehow failed. Probably it's not a good idea to terminate - * the session since this is just a request within dialog. And - * even if we terminate we should send BYE. - */ - /* - inv_set_cause(inv, PJSIP_SC_OK, NULL); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - */ - - } else { - struct tsx_inv_data *tsx_inv_data; - - tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; - if (tsx_inv_data) - tsx_inv_data->retrying = PJ_TRUE; - - /* Re-send request. */ - status = pjsip_inv_send_msg(inv, tdata); - } - - return PJ_TRUE; /* Handled */ + if (status != PJ_SUCCESS) { + /* Somehow failed. Probably it's not a good idea to terminate + * the session since this is just a request within dialog. And + * even if we terminate we should send BYE. + */ + /* + inv_set_cause(inv, PJSIP_SC_OK, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + */ + + } else { + struct tsx_inv_data *tsx_inv_data; + + tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; + if (tsx_inv_data) + tsx_inv_data->retrying = PJ_TRUE; + + /* Re-send request. */ + status = pjsip_inv_send_msg(inv, tdata); + } + + return PJ_TRUE; /* Handled */ } /* Handle session timer 422 response. */ else if (tsx->state == PJSIP_TSX_STATE_COMPLETED && - tsx->status_code == PJSIP_SC_SESSION_TIMER_TOO_SMALL) + tsx->status_code == PJSIP_SC_SESSION_TIMER_TOO_SMALL) { - handle_timer_response(inv, e->body.tsx_state.src.rdata, - PJ_FALSE); + handle_timer_response(inv, e->body.tsx_state.src.rdata, + PJ_FALSE); - return PJ_TRUE; /* Handled */ + return PJ_TRUE; /* Handled */ } else { - return PJ_FALSE; /* Unhandled */ + return PJ_FALSE; /* Unhandled */ } } @@ -4327,90 +4326,90 @@ static void handle_uac_call_rejection(pjsip_inv_session *inv, pjsip_event *e) if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 300)) { - if (mod_inv.cb.on_redirected == NULL) { + if (mod_inv.cb.on_redirected == NULL) { - /* Redirection callback is not implemented, disconnect the - * call. - */ - goto terminate_session; + /* Redirection callback is not implemented, disconnect the + * call. + */ + goto terminate_session; - } else { - const pjsip_msg *res_msg; + } else { + const pjsip_msg *res_msg; - res_msg = e->body.tsx_state.src.rdata->msg_info.msg; + res_msg = e->body.tsx_state.src.rdata->msg_info.msg; - /* Gather all Contact URI's in the response and add them - * to target set. The function will take care of removing - * duplicate URI's. - */ - pjsip_target_set_add_from_msg(&inv->dlg->target_set, - inv->dlg->pool, res_msg); + /* Gather all Contact URI's in the response and add them + * to target set. The function will take care of removing + * duplicate URI's. + */ + pjsip_target_set_add_from_msg(&inv->dlg->target_set, + inv->dlg->pool, res_msg); - /* Recurse to alternate targets if application allows us */ - if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e)) - { - /* Recursion fails, terminate session now */ - goto terminate_session; - } + /* Recurse to alternate targets if application allows us */ + if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e)) + { + /* Recursion fails, terminate session now */ + goto terminate_session; + } - /* Done */ - } + /* Done */ + } } else if ((tsx->status_code==401 || tsx->status_code==407) && - !inv->cancelling) + !inv->cancelling) { - /* Handle authentication failure: - * Resend the request with Authorization header. - */ - pjsip_tx_data *tdata; + /* Handle authentication failure: + * Resend the request with Authorization header. + */ + pjsip_tx_data *tdata; - status = pjsip_auth_clt_reinit_req(&inv->dlg->auth_sess, - e->body.tsx_state.src.rdata, - tsx->last_tx, - &tdata); + status = pjsip_auth_clt_reinit_req(&inv->dlg->auth_sess, + e->body.tsx_state.src.rdata, + tsx->last_tx, + &tdata); - if (status != PJ_SUCCESS) { + if (status != PJ_SUCCESS) { - /* Does not have proper credentials. If we are currently - * recursing, try the next target. Otherwise end the session. - */ - if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e)) - { - /* Recursion fails, terminate session now */ - goto terminate_session; - } + /* Does not have proper credentials. If we are currently + * recursing, try the next target. Otherwise end the session. + */ + if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e)) + { + /* Recursion fails, terminate session now */ + goto terminate_session; + } - } else { + } else { - /* Restart session. */ - pjsip_inv_uac_restart(inv, PJ_FALSE); + /* Restart session. */ + pjsip_inv_uac_restart(inv, PJ_FALSE); - /* Send the request. */ - status = pjsip_inv_send_msg(inv, tdata); - } + /* Send the request. */ + status = pjsip_inv_send_msg(inv, tdata); + } } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED && - tsx->status_code == PJSIP_SC_SESSION_TIMER_TOO_SMALL) + tsx->status_code == PJSIP_SC_SESSION_TIMER_TOO_SMALL) { - /* Handle session timer 422 response: - * Resend the request with requested session timer setting. - */ - status = handle_timer_response(inv, e->body.tsx_state.src.rdata, - PJ_FALSE); - if (status != PJ_SUCCESS) - goto terminate_session; + /* Handle session timer 422 response: + * Resend the request with requested session timer setting. + */ + status = handle_timer_response(inv, e->body.tsx_state.src.rdata, + PJ_FALSE); + if (status != PJ_SUCCESS) + goto terminate_session; } else if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 600)) { - /* Global error */ - goto terminate_session; + /* Global error */ + goto terminate_session; } else { - /* See if we have alternate target to try */ - if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e)) { - /* Recursion fails, terminate session now */ - goto terminate_session; - } + /* See if we have alternate target to try */ + if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e)) { + /* Recursion fails, terminate session now */ + goto terminate_session; + } } return; @@ -4434,157 +4433,157 @@ static void inv_on_state_calling( pjsip_inv_session *inv, pjsip_event *e) if (tsx == inv->invite_tsx) { - switch (tsx->state) { + switch (tsx->state) { - case PJSIP_TSX_STATE_CALLING: - inv_set_state(inv, PJSIP_INV_STATE_CALLING, e); - break; + case PJSIP_TSX_STATE_CALLING: + inv_set_state(inv, PJSIP_INV_STATE_CALLING, e); + break; - case PJSIP_TSX_STATE_PROCEEDING: - if (inv->pending_cancel) { - pjsip_tx_data *cancel; + case PJSIP_TSX_STATE_PROCEEDING: + if (inv->pending_cancel) { + pjsip_tx_data *cancel; - inv->pending_cancel = PJ_FALSE; + inv->pending_cancel = PJ_FALSE; - status = pjsip_inv_end_session(inv, 487, NULL, &cancel); - if (status == PJ_SUCCESS && cancel) - status = pjsip_inv_send_msg(inv, cancel); - } + status = pjsip_inv_end_session(inv, 487, NULL, &cancel); + if (status == PJ_SUCCESS && cancel) + status = pjsip_inv_send_msg(inv, cancel); + } - if (tsx->status_code != 100) { + if (tsx->status_code != 100) { - if (inv->role == PJSIP_ROLE_UAC) { - pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; - pjsip_allow_hdr *allow = NULL; - pjsip_msg *msg = rdata->msg_info.msg; + if (inv->role == PJSIP_ROLE_UAC) { + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + pjsip_allow_hdr *allow = NULL; + pjsip_msg *msg = rdata->msg_info.msg; - if (msg) { - allow = (pjsip_allow_hdr*) pjsip_msg_find_hdr(msg, + if (msg) { + allow = (pjsip_allow_hdr*) pjsip_msg_find_hdr(msg, PJSIP_H_ALLOW, NULL); - } - if (allow) { - unsigned i; - const pj_str_t STR_UPDATE = { "UPDATE", 6 }; - - for (i=0; icount; ++i) { - if (pj_stricmp(&allow->values[i], &STR_UPDATE)==0) { - /* UPDATE is present in Allow */ - inv->options |= PJSIP_INV_SUPPORT_UPDATE; - break; - } - } - } - } - - if (dlg->remote.info->tag.slen) - inv_set_state(inv, PJSIP_INV_STATE_EARLY, e); - - inv_check_sdp_in_incoming_msg(inv, tsx, - e->body.tsx_state.src.rdata); - - if (pjsip_100rel_is_reliable(e->body.tsx_state.src.rdata)) { - inv_handle_incoming_reliable_response( - inv, e->body.tsx_state.src.rdata); - } - - } else { - /* Ignore 100 (Trying) response, as it doesn't change - * session state. It only ceases retransmissions. - */ - } - break; - - case PJSIP_TSX_STATE_COMPLETED: - if (tsx->status_code/100 == 2) { - - /* This should not happen. - * When transaction receives 2xx, it should be terminated - */ - pj_assert(0); - - inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); - - /* Check routing URI scheme for secure dialog */ - if (!inv_check_secure_dlg(inv, e)) - break; - - /* Process session timer response. */ - status = handle_timer_response(inv, - e->body.tsx_state.src.rdata, - PJ_TRUE); - if (status != PJ_SUCCESS) - break; - - inv_check_sdp_in_incoming_msg(inv, tsx, - e->body.tsx_state.src.rdata); - - } else { - handle_uac_call_rejection(inv, e); - } - break; - - case PJSIP_TSX_STATE_TERMINATED: - /* INVITE transaction can be terminated either because UAC - * transaction received 2xx response or because of transport - * error. - */ - if (tsx->status_code/100 == 2) { - /* This must be receipt of 2xx response */ - pj_assert(e->body.tsx_state.type == PJSIP_EVENT_RX_MSG); - - /* Set state to CONNECTING */ - inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); - - /* Check routing URI scheme for secure dialog */ - if (!inv_check_secure_dlg(inv, e)) - break; - - /* Process session timer response. */ - status = handle_timer_response(inv, - e->body.tsx_state.src.rdata, - PJ_TRUE); - if (status != PJ_SUCCESS) - break; - - inv_check_sdp_in_incoming_msg(inv, tsx, - e->body.tsx_state.src.rdata); - /* Send ACK */ - inv_send_ack(inv, e); - - } else { - inv_set_cause(inv, tsx->status_code, &tsx->status_text); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - } - break; - - default: - break; - } + } + if (allow) { + unsigned i; + const pj_str_t STR_UPDATE = { "UPDATE", 6 }; + + for (i=0; icount; ++i) { + if (pj_stricmp(&allow->values[i], &STR_UPDATE)==0) { + /* UPDATE is present in Allow */ + inv->options |= PJSIP_INV_SUPPORT_UPDATE; + break; + } + } + } + } + + if (dlg->remote.info->tag.slen) + inv_set_state(inv, PJSIP_INV_STATE_EARLY, e); + + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + + if (pjsip_100rel_is_reliable(e->body.tsx_state.src.rdata)) { + inv_handle_incoming_reliable_response( + inv, e->body.tsx_state.src.rdata); + } + + } else { + /* Ignore 100 (Trying) response, as it doesn't change + * session state. It only ceases retransmissions. + */ + } + break; + + case PJSIP_TSX_STATE_COMPLETED: + if (tsx->status_code/100 == 2) { + + /* This should not happen. + * When transaction receives 2xx, it should be terminated + */ + pj_assert(0); + + inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); + + /* Check routing URI scheme for secure dialog */ + if (!inv_check_secure_dlg(inv, e)) + break; + + /* Process session timer response. */ + status = handle_timer_response(inv, + e->body.tsx_state.src.rdata, + PJ_TRUE); + if (status != PJ_SUCCESS) + break; + + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + + } else { + handle_uac_call_rejection(inv, e); + } + break; + + case PJSIP_TSX_STATE_TERMINATED: + /* INVITE transaction can be terminated either because UAC + * transaction received 2xx response or because of transport + * error. + */ + if (tsx->status_code/100 == 2) { + /* This must be receipt of 2xx response */ + pj_assert(e->body.tsx_state.type == PJSIP_EVENT_RX_MSG); + + /* Set state to CONNECTING */ + inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); + + /* Check routing URI scheme for secure dialog */ + if (!inv_check_secure_dlg(inv, e)) + break; + + /* Process session timer response. */ + status = handle_timer_response(inv, + e->body.tsx_state.src.rdata, + PJ_TRUE); + if (status != PJ_SUCCESS) + break; + + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + /* Send ACK */ + inv_send_ack(inv, e); + + } else { + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } + break; + + default: + break; + } } else if (tsx->role == PJSIP_ROLE_UAC) { - /* - * Handle case when outgoing request is answered with 481 (Call/ - * Transaction Does Not Exist), 408, or when it's timed out. In these - * cases, disconnect session (i.e. dialog usage only). - * Note that 481 response to CANCEL does not terminate dialog usage, - * but only the transaction. - */ - if ((tsx->status_code == PJSIP_SC_CALL_TSX_DOES_NOT_EXIST && - tsx->method.id != PJSIP_CANCEL_METHOD) || - tsx->status_code == PJSIP_SC_REQUEST_TIMEOUT || - tsx->status_code == PJSIP_SC_TSX_TIMEOUT) - { - inv_set_cause(inv, tsx->status_code, &tsx->status_text); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - } + /* + * Handle case when outgoing request is answered with 481 (Call/ + * Transaction Does Not Exist), 408, or when it's timed out. In these + * cases, disconnect session (i.e. dialog usage only). + * Note that 481 response to CANCEL does not terminate dialog usage, + * but only the transaction. + */ + if ((tsx->status_code == PJSIP_SC_CALL_TSX_DOES_NOT_EXIST && + tsx->method.id != PJSIP_CANCEL_METHOD) || + tsx->status_code == PJSIP_SC_REQUEST_TIMEOUT || + tsx->status_code == PJSIP_SC_TSX_TIMEOUT) + { + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } } else if (tsx->role == PJSIP_ROLE_UAS && - tsx->state == PJSIP_TSX_STATE_TRYING && - pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) { - /* - * Handle a very early UPDATE - */ - inv_respond_incoming_update(inv, e); + /* + * Handle a very early UPDATE + */ + inv_respond_incoming_update(inv, e); } @@ -4603,61 +4602,61 @@ static void inv_on_state_incoming( pjsip_inv_session *inv, pjsip_event *e) if (tsx == inv->invite_tsx) { - /* - * Handle the INVITE state transition. - */ - - switch (tsx->state) { - - case PJSIP_TSX_STATE_TRYING: - inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e); - break; - - case PJSIP_TSX_STATE_PROCEEDING: - /* - * Transaction sent provisional response. - */ - if (tsx->status_code > 100) - inv_set_state(inv, PJSIP_INV_STATE_EARLY, e); - break; - - case PJSIP_TSX_STATE_COMPLETED: - /* - * Transaction sent final response. - */ - if (tsx->status_code/100 == 2) { - inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); - } else { - inv_set_cause(inv, tsx->status_code, &tsx->status_text); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - } - break; - - case PJSIP_TSX_STATE_TERMINATED: - /* - * This happens on transport error (e.g. failed to send - * response) - */ - inv_set_cause(inv, tsx->status_code, &tsx->status_text); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - break; - - default: - pj_assert(!"Unexpected INVITE state"); - break; - } + /* + * Handle the INVITE state transition. + */ + + switch (tsx->state) { + + case PJSIP_TSX_STATE_TRYING: + inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e); + break; + + case PJSIP_TSX_STATE_PROCEEDING: + /* + * Transaction sent provisional response. + */ + if (tsx->status_code > 100) + inv_set_state(inv, PJSIP_INV_STATE_EARLY, e); + break; + + case PJSIP_TSX_STATE_COMPLETED: + /* + * Transaction sent final response. + */ + if (tsx->status_code/100 == 2) { + inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); + } else { + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } + break; + + case PJSIP_TSX_STATE_TERMINATED: + /* + * This happens on transport error (e.g. failed to send + * response) + */ + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + break; + + default: + pj_assert(!"Unexpected INVITE state"); + break; + } } else if (tsx->method.id == PJSIP_CANCEL_METHOD && - tsx->role == PJSIP_ROLE_UAS && - tsx->state < PJSIP_TSX_STATE_COMPLETED && - e->body.tsx_state.type == PJSIP_EVENT_RX_MSG ) + tsx->role == PJSIP_ROLE_UAS && + tsx->state < PJSIP_TSX_STATE_COMPLETED && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG ) { - /* - * Handle incoming CANCEL request. - */ + /* + * Handle incoming CANCEL request. + */ - inv_respond_incoming_cancel(inv, tsx, e); + inv_respond_incoming_cancel(inv, tsx, e); } } @@ -4675,192 +4674,192 @@ static void inv_on_state_early( pjsip_inv_session *inv, pjsip_event *e) if (tsx == inv->invite_tsx) { - /* - * Handle the INVITE state progress. - */ - - switch (tsx->state) { - - case PJSIP_TSX_STATE_PROCEEDING: - /* Send/received another provisional response. */ - inv_set_state(inv, PJSIP_INV_STATE_EARLY, e); - - if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - inv_check_sdp_in_incoming_msg(inv, tsx, - e->body.tsx_state.src.rdata); - - if (pjsip_100rel_is_reliable(e->body.tsx_state.src.rdata)) { - inv_handle_incoming_reliable_response( - inv, e->body.tsx_state.src.rdata); - } - } - break; - - case PJSIP_TSX_STATE_COMPLETED: - if (tsx->status_code/100 == 2) { - inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); - if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - pj_status_t status; - - /* Check routing URI scheme for secure dialog */ - if (!inv_check_secure_dlg(inv, e)) - break; - - /* Process session timer response. */ - status = handle_timer_response(inv, - e->body.tsx_state.src.rdata, - PJ_TRUE); - if (status != PJ_SUCCESS) - break; - - inv_check_sdp_in_incoming_msg(inv, tsx, - e->body.tsx_state.src.rdata); - } - - } else if (tsx->role == PJSIP_ROLE_UAC) { - - handle_uac_call_rejection(inv, e); - - } else { - inv_set_cause(inv, tsx->status_code, &tsx->status_text); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - } - break; - - case PJSIP_TSX_STATE_CONFIRMED: - /* For some reason can go here (maybe when ACK for 2xx has - * the same branch value as the INVITE transaction) */ - - case PJSIP_TSX_STATE_TERMINATED: - /* INVITE transaction can be terminated either because UAC - * transaction received 2xx response or because of transport - * error. - */ - if (tsx->status_code/100 == 2) { - - /* This must be receipt of 2xx response */ - - /* Set state to CONNECTING */ - inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); - - if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - pj_status_t status; - - /* Check routing URI scheme for secure dialog */ - if (!inv_check_secure_dlg(inv, e)) - break; - - /* Process session timer response. */ - status = handle_timer_response(inv, - e->body.tsx_state.src.rdata, - PJ_TRUE); - if (status != PJ_SUCCESS) - break; - - inv_check_sdp_in_incoming_msg(inv, tsx, - e->body.tsx_state.src.rdata); - } - - /* if UAC, send ACK and move state to confirmed. */ - if (tsx->role == PJSIP_ROLE_UAC) { - pj_assert(e->body.tsx_state.type == PJSIP_EVENT_RX_MSG); - - inv_send_ack(inv, e); - } - - } else { - inv_set_cause(inv, tsx->status_code, &tsx->status_text); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - } - break; - - default: - pj_assert(!"Unexpected INVITE tsx state"); - break; - } + /* + * Handle the INVITE state progress. + */ + + switch (tsx->state) { + + case PJSIP_TSX_STATE_PROCEEDING: + /* Send/received another provisional response. */ + inv_set_state(inv, PJSIP_INV_STATE_EARLY, e); + + if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + + if (pjsip_100rel_is_reliable(e->body.tsx_state.src.rdata)) { + inv_handle_incoming_reliable_response( + inv, e->body.tsx_state.src.rdata); + } + } + break; + + case PJSIP_TSX_STATE_COMPLETED: + if (tsx->status_code/100 == 2) { + inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); + if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { + pj_status_t status; + + /* Check routing URI scheme for secure dialog */ + if (!inv_check_secure_dlg(inv, e)) + break; + + /* Process session timer response. */ + status = handle_timer_response(inv, + e->body.tsx_state.src.rdata, + PJ_TRUE); + if (status != PJ_SUCCESS) + break; + + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + } + + } else if (tsx->role == PJSIP_ROLE_UAC) { + + handle_uac_call_rejection(inv, e); + + } else { + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } + break; + + case PJSIP_TSX_STATE_CONFIRMED: + /* For some reason can go here (maybe when ACK for 2xx has + * the same branch value as the INVITE transaction) */ + + case PJSIP_TSX_STATE_TERMINATED: + /* INVITE transaction can be terminated either because UAC + * transaction received 2xx response or because of transport + * error. + */ + if (tsx->status_code/100 == 2) { + + /* This must be receipt of 2xx response */ + + /* Set state to CONNECTING */ + inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); + + if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { + pj_status_t status; + + /* Check routing URI scheme for secure dialog */ + if (!inv_check_secure_dlg(inv, e)) + break; + + /* Process session timer response. */ + status = handle_timer_response(inv, + e->body.tsx_state.src.rdata, + PJ_TRUE); + if (status != PJ_SUCCESS) + break; + + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + } + + /* if UAC, send ACK and move state to confirmed. */ + if (tsx->role == PJSIP_ROLE_UAC) { + pj_assert(e->body.tsx_state.type == PJSIP_EVENT_RX_MSG); + + inv_send_ack(inv, e); + } + + } else { + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } + break; + + default: + pj_assert(!"Unexpected INVITE tsx state"); + break; + } } else if (inv->role == PJSIP_ROLE_UAS && - tsx->role == PJSIP_ROLE_UAS && - tsx->method.id == PJSIP_CANCEL_METHOD && - tsx->state < PJSIP_TSX_STATE_COMPLETED && - e->body.tsx_state.type == PJSIP_EVENT_RX_MSG ) + tsx->role == PJSIP_ROLE_UAS && + tsx->method.id == PJSIP_CANCEL_METHOD && + tsx->state < PJSIP_TSX_STATE_COMPLETED && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG ) { - /* - * Handle incoming CANCEL request. - */ + /* + * Handle incoming CANCEL request. + */ - inv_respond_incoming_cancel(inv, tsx, e); + inv_respond_incoming_cancel(inv, tsx, e); } else if (tsx->role == PJSIP_ROLE_UAS && - tsx->state == PJSIP_TSX_STATE_TRYING && - pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) { - /* - * Handle incoming UPDATE - */ - inv_respond_incoming_update(inv, e); + /* + * Handle incoming UPDATE + */ + inv_respond_incoming_update(inv, e); } else if (tsx->role == PJSIP_ROLE_UAC && - (tsx->state == PJSIP_TSX_STATE_COMPLETED || - tsx->state == PJSIP_TSX_STATE_TERMINATED) && - pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + (tsx->state == PJSIP_TSX_STATE_COMPLETED || + tsx->state == PJSIP_TSX_STATE_TERMINATED) && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) { - /* - * Handle response to outgoing UPDATE request. - */ - inv_handle_update_response(inv, e); + /* + * Handle response to outgoing UPDATE request. + */ + inv_handle_update_response(inv, e); } else if (tsx->role == PJSIP_ROLE_UAS && - tsx->state == PJSIP_TSX_STATE_TRYING && - pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0) + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0) { - /* - * Handle incoming PRACK - */ - inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata); + /* + * Handle incoming PRACK + */ + inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata); } else if (tsx->role == PJSIP_ROLE_UAC) { - - /* Generic handling for UAC tsx completion */ - handle_uac_tsx_response(inv, e); + + /* Generic handling for UAC tsx completion */ + handle_uac_tsx_response(inv, e); } else if (tsx->role == PJSIP_ROLE_UAS && - tsx->method.id == PJSIP_BYE_METHOD && - tsx->status_code < 200 && - e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + tsx->method.id == PJSIP_BYE_METHOD && + tsx->status_code < 200 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - /* Received BYE before the 2xx/OK response to INVITE. - * Assume that the 2xx/OK response is lost and the BYE - * arrives earlier. - */ - inv_respond_incoming_bye(inv, tsx, e->body.tsx_state.src.rdata, e); - - if (inv->invite_tsx->role == PJSIP_ROLE_UAC) { - /* Set timer just in case we will never get the final response - * for INVITE. - */ - pjsip_tsx_set_timeout(inv->invite_tsx, 64*pjsip_cfg()->tsx.t1); - } else if (inv->invite_tsx->status_code < 200) { - pjsip_tx_data *tdata; - pjsip_msg *msg; - - /* For UAS, send a final response. */ - tdata = inv->invite_tsx->last_tx; - PJ_ASSERT_ON_FAIL(tdata != NULL, return); - - msg = tdata->msg; - msg->line.status.code = PJSIP_SC_REQUEST_TERMINATED; - msg->line.status.reason = - *pjsip_get_status_text(PJSIP_SC_REQUEST_TERMINATED); - msg->body = NULL; - - pjsip_tx_data_invalidate_msg(tdata); - pjsip_tx_data_add_ref(tdata); - - pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata); - } + /* Received BYE before the 2xx/OK response to INVITE. + * Assume that the 2xx/OK response is lost and the BYE + * arrives earlier. + */ + inv_respond_incoming_bye(inv, tsx, e->body.tsx_state.src.rdata, e); + + if (inv->invite_tsx->role == PJSIP_ROLE_UAC) { + /* Set timer just in case we will never get the final response + * for INVITE. + */ + pjsip_tsx_set_timeout(inv->invite_tsx, 64*pjsip_cfg()->tsx.t1); + } else if (inv->invite_tsx->status_code < 200) { + pjsip_tx_data *tdata; + pjsip_msg *msg; + + /* For UAS, send a final response. */ + tdata = inv->invite_tsx->last_tx; + PJ_ASSERT_ON_FAIL(tdata != NULL, return); + + msg = tdata->msg; + msg->line.status.code = PJSIP_SC_REQUEST_TERMINATED; + msg->line.status.reason = + *pjsip_get_status_text(PJSIP_SC_REQUEST_TERMINATED); + msg->body = NULL; + + pjsip_tx_data_invalidate_msg(tdata); + pjsip_tx_data_add_ref(tdata); + + pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata); + } } } @@ -4876,169 +4875,169 @@ static void inv_on_state_connecting( pjsip_inv_session *inv, pjsip_event *e) if (tsx == inv->invite_tsx) { - /* - * Handle INVITE state progression. - */ - switch (tsx->state) { - - case PJSIP_TSX_STATE_CONFIRMED: - /* It can only go here if incoming ACK request has the same Via - * branch parameter as the INVITE transaction. - */ - if (tsx->status_code/100 == 2) { - if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - inv_check_sdp_in_incoming_msg(inv, tsx, - e->body.tsx_state.src.rdata); - } - - inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, e); - - /* Send pending BYE if any: - * https://github.com/pjsip/pjproject/issues/1712 - * Do this after setting the state to CONFIRMED, so that we - * have consistent CONFIRMED state between caller and callee. - */ - if (inv->pending_bye) - inv_perform_pending_bye(inv); - - } - break; - - case PJSIP_TSX_STATE_TERMINATED: - /* INVITE transaction can be terminated either because UAC - * transaction received 2xx response or because of transport - * error. - */ - if (tsx->status_code/100 != 2) { - if (tsx->role == PJSIP_ROLE_UAC) { - inv_set_cause(inv, tsx->status_code, &tsx->status_text); - inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); - } else { - pjsip_tx_data *bye; - pj_status_t status; - - inv_set_cause(inv, tsx->status_code, &tsx->status_text); - - /* Send BYE */ - status = pjsip_dlg_create_request(inv->dlg, - pjsip_get_bye_method(), - -1, &bye); - if (status == PJ_SUCCESS) { - pjsip_inv_send_msg(inv, bye); - - if (inv->pending_bye) { - pjsip_tx_data_dec_ref(inv->pending_bye); - inv->pending_bye = NULL; - } - } - } - } - break; - - case PJSIP_TSX_STATE_DESTROYED: - /* Do nothing. */ - break; - - default: - pj_assert(!"Unexpected state"); - break; - } + /* + * Handle INVITE state progression. + */ + switch (tsx->state) { + + case PJSIP_TSX_STATE_CONFIRMED: + /* It can only go here if incoming ACK request has the same Via + * branch parameter as the INVITE transaction. + */ + if (tsx->status_code/100 == 2) { + if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + } + + inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, e); + + /* Send pending BYE if any: + * https://github.com/pjsip/pjproject/issues/1712 + * Do this after setting the state to CONFIRMED, so that we + * have consistent CONFIRMED state between caller and callee. + */ + if (inv->pending_bye) + inv_perform_pending_bye(inv); + + } + break; + + case PJSIP_TSX_STATE_TERMINATED: + /* INVITE transaction can be terminated either because UAC + * transaction received 2xx response or because of transport + * error. + */ + if (tsx->status_code/100 != 2) { + if (tsx->role == PJSIP_ROLE_UAC) { + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } else { + pjsip_tx_data *bye; + pj_status_t status; + + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + + /* Send BYE */ + status = pjsip_dlg_create_request(inv->dlg, + pjsip_get_bye_method(), + -1, &bye); + if (status == PJ_SUCCESS) { + pjsip_inv_send_msg(inv, bye); + + if (inv->pending_bye) { + pjsip_tx_data_dec_ref(inv->pending_bye); + inv->pending_bye = NULL; + } + } + } + } + break; + + case PJSIP_TSX_STATE_DESTROYED: + /* Do nothing. */ + break; + + default: + pj_assert(!"Unexpected state"); + break; + } } else if (tsx->role == PJSIP_ROLE_UAS && - tsx->method.id == PJSIP_BYE_METHOD && - tsx->status_code < 200 && - e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + tsx->method.id == PJSIP_BYE_METHOD && + tsx->status_code < 200 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - /* - * Handle incoming BYE. - */ + /* + * Handle incoming BYE. + */ - inv_respond_incoming_bye( inv, tsx, e->body.tsx_state.src.rdata, e ); + inv_respond_incoming_bye( inv, tsx, e->body.tsx_state.src.rdata, e ); } else if (tsx->method.id == PJSIP_BYE_METHOD && - tsx->role == PJSIP_ROLE_UAC && - (tsx->state == PJSIP_TSX_STATE_COMPLETED || - tsx->state == PJSIP_TSX_STATE_TERMINATED)) + tsx->role == PJSIP_ROLE_UAC && + (tsx->state == PJSIP_TSX_STATE_COMPLETED || + tsx->state == PJSIP_TSX_STATE_TERMINATED)) { - /* - * Outgoing BYE - */ - inv_handle_bye_response( inv, tsx, e->body.tsx_state.src.rdata, e); + /* + * Outgoing BYE + */ + inv_handle_bye_response( inv, tsx, e->body.tsx_state.src.rdata, e); } else if (tsx->method.id == PJSIP_CANCEL_METHOD && - tsx->role == PJSIP_ROLE_UAS && - tsx->status_code < 200 && - e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + tsx->role == PJSIP_ROLE_UAS && + tsx->status_code < 200 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - /* - * Handle strandled incoming CANCEL or CANCEL for re-INVITE - */ + /* + * Handle strandled incoming CANCEL or CANCEL for re-INVITE + */ inv_respond_incoming_cancel(inv, tsx, e); } else if (tsx->role == PJSIP_ROLE_UAS && - tsx->state == PJSIP_TSX_STATE_TRYING && - pjsip_method_cmp(&tsx->method, pjsip_get_invite_method())==0) + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, pjsip_get_invite_method())==0) { - pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; - pjsip_tx_data *tdata; - pj_status_t status; - - /* See https://github.com/pjsip/pjproject/issues/1455 - * Handle incoming re-INVITE before current INVITE is confirmed. - * According to RFC 5407: - * - answer with 200 if we don't have pending offer-answer - * - answer with 491 if we *have* pending offer-answer - * - * But unfortunately accepting the re-INVITE would mean we have - * two outstanding INVITEs, and we don't support that because - * we will get confused when we handle the ACK. - */ - status = pjsip_dlg_create_response(inv->dlg, rdata, - PJSIP_SC_REQUEST_PENDING, - NULL, &tdata); - if (status != PJ_SUCCESS) - return; - pjsip_timer_update_resp(inv, tdata); - status = pjsip_dlg_send_response(dlg, tsx, tdata); + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + pjsip_tx_data *tdata; + pj_status_t status; + + /* See https://github.com/pjsip/pjproject/issues/1455 + * Handle incoming re-INVITE before current INVITE is confirmed. + * According to RFC 5407: + * - answer with 200 if we don't have pending offer-answer + * - answer with 491 if we *have* pending offer-answer + * + * But unfortunately accepting the re-INVITE would mean we have + * two outstanding INVITEs, and we don't support that because + * we will get confused when we handle the ACK. + */ + status = pjsip_dlg_create_response(inv->dlg, rdata, + PJSIP_SC_REQUEST_PENDING, + NULL, &tdata); + if (status != PJ_SUCCESS) + return; + pjsip_timer_update_resp(inv, tdata); + status = pjsip_dlg_send_response(dlg, tsx, tdata); } else if (tsx->role == PJSIP_ROLE_UAS && - tsx->state == PJSIP_TSX_STATE_TRYING && - pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) { - /* - * Handle incoming UPDATE - */ - inv_respond_incoming_update(inv, e); + /* + * Handle incoming UPDATE + */ + inv_respond_incoming_update(inv, e); } else if (tsx->role == PJSIP_ROLE_UAC && - (tsx->state == PJSIP_TSX_STATE_COMPLETED || - tsx->state == PJSIP_TSX_STATE_TERMINATED) && - pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + (tsx->state == PJSIP_TSX_STATE_COMPLETED || + tsx->state == PJSIP_TSX_STATE_TERMINATED) && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) { - /* - * Handle response to outgoing UPDATE request. - */ - if (inv_handle_update_response(inv, e) == PJ_FALSE) - handle_uac_tsx_response(inv, e); + /* + * Handle response to outgoing UPDATE request. + */ + if (inv_handle_update_response(inv, e) == PJ_FALSE) + handle_uac_tsx_response(inv, e); } else if (tsx->role == PJSIP_ROLE_UAS && - tsx->state == PJSIP_TSX_STATE_TRYING && - pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0) + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0) { - /* - * Handle incoming PRACK - */ - inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata); + /* + * Handle incoming PRACK + */ + inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata); } else if (tsx->role == PJSIP_ROLE_UAC) { - - /* Generic handling for UAC tsx completion */ - handle_uac_tsx_response(inv, e); + + /* Generic handling for UAC tsx completion */ + handle_uac_tsx_response(inv, e); } @@ -5056,450 +5055,450 @@ static void inv_on_state_confirmed( pjsip_inv_session *inv, pjsip_event *e) if (tsx->method.id == PJSIP_BYE_METHOD && - tsx->role == PJSIP_ROLE_UAC && - (tsx->state == PJSIP_TSX_STATE_COMPLETED || - tsx->state == PJSIP_TSX_STATE_TERMINATED)) + tsx->role == PJSIP_ROLE_UAC && + (tsx->state == PJSIP_TSX_STATE_COMPLETED || + tsx->state == PJSIP_TSX_STATE_TERMINATED)) { - /* - * Outgoing BYE - */ + /* + * Outgoing BYE + */ - inv_handle_bye_response( inv, tsx, e->body.tsx_state.src.rdata, e); + inv_handle_bye_response( inv, tsx, e->body.tsx_state.src.rdata, e); } else if (tsx->method.id == PJSIP_BYE_METHOD && - tsx->role == PJSIP_ROLE_UAS && - tsx->status_code < 200 && - e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + tsx->role == PJSIP_ROLE_UAS && + tsx->status_code < 200 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - /* - * Handle incoming BYE. - */ + /* + * Handle incoming BYE. + */ - inv_respond_incoming_bye( inv, tsx, e->body.tsx_state.src.rdata, e ); + inv_respond_incoming_bye( inv, tsx, e->body.tsx_state.src.rdata, e ); } else if (tsx->method.id == PJSIP_CANCEL_METHOD && - tsx->role == PJSIP_ROLE_UAS && - tsx->status_code < 200 && - e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + tsx->role == PJSIP_ROLE_UAS && + tsx->status_code < 200 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - /* - * Handle strandled incoming CANCEL or CANCEL for re-INVITE - */ + /* + * Handle strandled incoming CANCEL or CANCEL for re-INVITE + */ inv_respond_incoming_cancel(inv, tsx, e); } else if (tsx->method.id == PJSIP_INVITE_METHOD && - tsx->role == PJSIP_ROLE_UAS) + tsx->role == PJSIP_ROLE_UAS) { - /* - * Handle incoming re-INVITE - */ - if (tsx->state == PJSIP_TSX_STATE_TRYING) { - - pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; - pjsip_tx_data *tdata; - pj_status_t status; - pjsip_rdata_sdp_info *sdp_info = NULL; - pjsip_status_code st_code; - - /* Check if we have INVITE pending. */ - if (inv->invite_tsx && inv->invite_tsx!=tsx) { - int code; - pj_str_t reason; - - reason = pj_str("Another INVITE transaction in progress"); - - if (inv->invite_tsx->role == PJSIP_ROLE_UAC) - code = 491; - else - code = 500; - - /* Can not receive re-INVITE while another one is pending. */ - status = pjsip_dlg_create_response( inv->dlg, rdata, code, - &reason, &tdata); - if (status != PJ_SUCCESS) - return; - - if (code == 500) { - /* MUST include Retry-After header with random value - * between 0-10. - */ - pjsip_retry_after_hdr *ra_hdr; - int val = (pj_rand() % 10); - - ra_hdr = pjsip_retry_after_hdr_create(tdata->pool, val); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)ra_hdr); - } - - status = pjsip_dlg_send_response( inv->dlg, tsx, tdata); - - - return; - } - - /* Check routing URI scheme for secure dialog */ - if (!inv_check_secure_dlg(inv, e)) - return; - - /* Save the invite transaction. */ - inv->invite_tsx = tsx; - - /* Process session timers headers in the re-INVITE */ - status = pjsip_timer_process_req(inv, rdata, &st_code); - if (status != PJ_SUCCESS) { - status = pjsip_dlg_create_response(inv->dlg, rdata, st_code, - NULL, &tdata); - if (status != PJ_SUCCESS) - return; - - pjsip_timer_update_resp(inv, tdata); - status = pjsip_dlg_send_response(dlg, tsx, tdata); - return; - } - - /* Send 491 if we receive re-INVITE while another offer/answer - * negotiation is in progress - */ - if (pjmedia_sdp_neg_get_state(inv->neg) != - PJMEDIA_SDP_NEG_STATE_DONE) - { - status = pjsip_dlg_create_response(inv->dlg, rdata, - PJSIP_SC_REQUEST_PENDING, - NULL, &tdata); - if (status != PJ_SUCCESS) - return; - pjsip_timer_update_resp(inv, tdata); - status = pjsip_dlg_send_response(dlg, tsx, tdata); - return; - } - - /* Process SDP in incoming message. */ - status = inv_check_sdp_in_incoming_msg(inv, tsx, rdata); + /* + * Handle incoming re-INVITE + */ + if (tsx->state == PJSIP_TSX_STATE_TRYING) { + + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + pjsip_tx_data *tdata; + pj_status_t status; + pjsip_rdata_sdp_info *sdp_info = NULL; + pjsip_status_code st_code; + + /* Check if we have INVITE pending. */ + if (inv->invite_tsx && inv->invite_tsx!=tsx) { + int code; + pj_str_t reason; + + reason = pj_str("Another INVITE transaction in progress"); + + if (inv->invite_tsx->role == PJSIP_ROLE_UAC) + code = 491; + else + code = 500; + + /* Can not receive re-INVITE while another one is pending. */ + status = pjsip_dlg_create_response( inv->dlg, rdata, code, + &reason, &tdata); + if (status != PJ_SUCCESS) + return; + + if (code == 500) { + /* MUST include Retry-After header with random value + * between 0-10. + */ + pjsip_retry_after_hdr *ra_hdr; + int val = (pj_rand() % 10); + + ra_hdr = pjsip_retry_after_hdr_create(tdata->pool, val); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)ra_hdr); + } + + status = pjsip_dlg_send_response( inv->dlg, tsx, tdata); + + + return; + } + + /* Check routing URI scheme for secure dialog */ + if (!inv_check_secure_dlg(inv, e)) + return; + + /* Save the invite transaction. */ + inv->invite_tsx = tsx; + + /* Process session timers headers in the re-INVITE */ + status = pjsip_timer_process_req(inv, rdata, &st_code); + if (status != PJ_SUCCESS) { + status = pjsip_dlg_create_response(inv->dlg, rdata, st_code, + NULL, &tdata); + if (status != PJ_SUCCESS) + return; + + pjsip_timer_update_resp(inv, tdata); + status = pjsip_dlg_send_response(dlg, tsx, tdata); + return; + } + + /* Send 491 if we receive re-INVITE while another offer/answer + * negotiation is in progress + */ + if (pjmedia_sdp_neg_get_state(inv->neg) != + PJMEDIA_SDP_NEG_STATE_DONE) + { + status = pjsip_dlg_create_response(inv->dlg, rdata, + PJSIP_SC_REQUEST_PENDING, + NULL, &tdata); + if (status != PJ_SUCCESS) + return; + pjsip_timer_update_resp(inv, tdata); + status = pjsip_dlg_send_response(dlg, tsx, tdata); + return; + } + + /* Process SDP in incoming message. */ + status = inv_check_sdp_in_incoming_msg(inv, tsx, rdata); if (status == PJ_SUCCESS && mod_inv.cb.on_rx_reinvite && inv->notify) { - pj_status_t rc; + pj_status_t rc; - sdp_info = pjsip_rdata_get_sdp_info(rdata); + sdp_info = pjsip_rdata_get_sdp_info(rdata); rc = (*mod_inv.cb.on_rx_reinvite)(inv, sdp_info->sdp, - rdata); + rdata); if (rc == PJ_SUCCESS) { /* Application will send its own response. * Our job is done. */ - PJ_LOG(5,(inv->obj_name, "on_rx_reinvite() returns %d", - rc)); + PJ_LOG(5,(inv->obj_name, "on_rx_reinvite() returns %d", + rc)); return; } /* If application lets us answer the re-INVITE which contains - * SDP, application must set the SDP answer with + * SDP, application must set the SDP answer with * #pjsip_inv_set_sdp_answer(). */ if (sdp_info->sdp && - (pjmedia_sdp_neg_get_state(inv->neg) != - PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)) + (pjmedia_sdp_neg_get_state(inv->neg) != + PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)) { status = PJ_EINVALIDOP; } } - if (status != PJ_SUCCESS) { - pj_bool_t reject_message = PJ_TRUE; - - if (status == PJMEDIA_SDP_EINSDP) - { - sdp_info = pjsip_rdata_get_sdp_info(rdata); - if (sdp_info->body.ptr == NULL && - PJSIP_INV_ACCEPT_UNKNOWN_BODY) - { - /* Message body is not "application/sdp" */ - reject_message = PJ_FALSE; - } - } - - if (reject_message) { - /* Not Acceptable */ - const pjsip_hdr *accept; - - /* The incoming SDP is unacceptable. If the SDP negotiator - * state has just been changed, i.e: DONE -> REMOTE_OFFER, - * revert it back. - */ - if (pjmedia_sdp_neg_get_state(inv->neg) == - PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER) - { - pjmedia_sdp_neg_cancel_offer(inv->neg); - } - - status = pjsip_dlg_create_response(inv->dlg, rdata, - (status == PJMEDIA_SDP_EINSDP)?415:488, - NULL, &tdata); - - if (status != PJ_SUCCESS) - return; - - - accept = pjsip_endpt_get_capability(dlg->endpt, - PJSIP_H_ACCEPT, - NULL); - if (accept) { - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) - pjsip_hdr_clone(tdata->pool, accept)); - } - - status = pjsip_dlg_send_response(dlg, tsx, tdata); - - return; - } - } - - /* Create 2xx ANSWER */ - status = pjsip_dlg_create_response(dlg, rdata, 200, NULL, &tdata); - if (status != PJ_SUCCESS) - return; - - /* If the INVITE request has SDP body, send answer. - * Otherwise generate offer from local active SDP. - */ + if (status != PJ_SUCCESS) { + pj_bool_t reject_message = PJ_TRUE; + + if (status == PJMEDIA_SDP_EINSDP) + { + sdp_info = pjsip_rdata_get_sdp_info(rdata); + if (sdp_info->body.ptr == NULL && + PJSIP_INV_ACCEPT_UNKNOWN_BODY) + { + /* Message body is not "application/sdp" */ + reject_message = PJ_FALSE; + } + } + + if (reject_message) { + /* Not Acceptable */ + const pjsip_hdr *accept; + + /* The incoming SDP is unacceptable. If the SDP negotiator + * state has just been changed, i.e: DONE -> REMOTE_OFFER, + * revert it back. + */ + if (pjmedia_sdp_neg_get_state(inv->neg) == + PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER) + { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } + + status = pjsip_dlg_create_response(inv->dlg, rdata, + (status == PJMEDIA_SDP_EINSDP)?415:488, + NULL, &tdata); + + if (status != PJ_SUCCESS) + return; + + + accept = pjsip_endpt_get_capability(dlg->endpt, + PJSIP_H_ACCEPT, + NULL); + if (accept) { + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, accept)); + } + + status = pjsip_dlg_send_response(dlg, tsx, tdata); + + return; + } + } + + /* Create 2xx ANSWER */ + status = pjsip_dlg_create_response(dlg, rdata, 200, NULL, &tdata); + if (status != PJ_SUCCESS) + return; + + /* If the INVITE request has SDP body, send answer. + * Otherwise generate offer from local active SDP. + */ if (!sdp_info) sdp_info = pjsip_rdata_get_sdp_info(rdata); - if (sdp_info->sdp != NULL) { - status = process_answer(inv, 200, tdata, NULL); - } else { - /* INVITE does not have SDP. - * If on_create_offer() callback is implemented, ask app. - * to generate an offer, otherwise just send active local - * SDP to signal that nothing gets modified. - */ - pjmedia_sdp_session *sdp = NULL; - - if (mod_inv.cb.on_create_offer) { - (*mod_inv.cb.on_create_offer)(inv, &sdp); - if (sdp) { - /* Notify negotiator about the new offer. This will - * fix the offer with correct SDP origin. - */ - status = - pjmedia_sdp_neg_modify_local_offer2( + if (sdp_info->sdp != NULL) { + status = process_answer(inv, 200, tdata, NULL); + } else { + /* INVITE does not have SDP. + * If on_create_offer() callback is implemented, ask app. + * to generate an offer, otherwise just send active local + * SDP to signal that nothing gets modified. + */ + pjmedia_sdp_session *sdp = NULL; + + if (mod_inv.cb.on_create_offer) { + (*mod_inv.cb.on_create_offer)(inv, &sdp); + if (sdp) { + /* Notify negotiator about the new offer. This will + * fix the offer with correct SDP origin. + */ + status = + pjmedia_sdp_neg_modify_local_offer2( inv->pool_prov, inv->neg, inv->sdp_neg_flags, sdp); - /* Retrieve the "fixed" offer from negotiator */ - if (status==PJ_SUCCESS) { - const pjmedia_sdp_session *lsdp = NULL; - pjmedia_sdp_neg_get_neg_local(inv->neg, &lsdp); - sdp = (pjmedia_sdp_session*)lsdp; - } - } - } - - if (sdp == NULL) { - const pjmedia_sdp_session *active_sdp = NULL; - status = pjmedia_sdp_neg_send_local_offer(inv->pool_prov, - inv->neg, - &active_sdp); - if (status == PJ_SUCCESS) - sdp = (pjmedia_sdp_session*) active_sdp; - } - - if (sdp) { - tdata->msg->body = create_sdp_body(tdata->pool, sdp); - } - } - - if (status != PJ_SUCCESS) { - /* - * SDP negotiation has failed. - */ - pj_status_t rc; - pj_str_t reason; - - /* Delete the 2xx answer */ - pjsip_tx_data_dec_ref(tdata); - - /* Create 500 response */ - reason = pj_str("SDP negotiation failed"); - rc = pjsip_dlg_create_response(dlg, rdata, 500, &reason, - &tdata); - if (rc == PJ_SUCCESS) { - pjsip_warning_hdr *w; - const pj_str_t *endpt_name; - - endpt_name = pjsip_endpt_name(dlg->endpt); - w = pjsip_warning_hdr_create_from_status(tdata->pool, - endpt_name, - status); - if (w) - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)w); - - pjsip_inv_send_msg(inv, tdata); - } - return; - } - - /* Invoke Session Timers */ - pjsip_timer_update_resp(inv, tdata); - - /* Send 2xx regardless of the status of negotiation */ - status = pjsip_inv_send_msg(inv, tdata); - - } else if (tsx->state == PJSIP_TSX_STATE_CONFIRMED) { - /* This is the case where ACK has the same branch as - * the INVITE request. - */ - if (tsx->status_code/100 == 2 && - e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) - { - inv_check_sdp_in_incoming_msg(inv, tsx, - e->body.tsx_state.src.rdata); - - /* Check if local offer got no SDP answer */ - if (pjmedia_sdp_neg_get_state(inv->neg)== - PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) - { - pjmedia_sdp_neg_cancel_offer(inv->neg); - } - } - - } + /* Retrieve the "fixed" offer from negotiator */ + if (status==PJ_SUCCESS) { + const pjmedia_sdp_session *lsdp = NULL; + pjmedia_sdp_neg_get_neg_local(inv->neg, &lsdp); + sdp = (pjmedia_sdp_session*)lsdp; + } + } + } + + if (sdp == NULL) { + const pjmedia_sdp_session *active_sdp = NULL; + status = pjmedia_sdp_neg_send_local_offer(inv->pool_prov, + inv->neg, + &active_sdp); + if (status == PJ_SUCCESS) + sdp = (pjmedia_sdp_session*) active_sdp; + } + + if (sdp) { + tdata->msg->body = create_sdp_body(tdata->pool, sdp); + } + } + + if (status != PJ_SUCCESS) { + /* + * SDP negotiation has failed. + */ + pj_status_t rc; + pj_str_t reason; + + /* Delete the 2xx answer */ + pjsip_tx_data_dec_ref(tdata); + + /* Create 500 response */ + reason = pj_str("SDP negotiation failed"); + rc = pjsip_dlg_create_response(dlg, rdata, 500, &reason, + &tdata); + if (rc == PJ_SUCCESS) { + pjsip_warning_hdr *w; + const pj_str_t *endpt_name; + + endpt_name = pjsip_endpt_name(dlg->endpt); + w = pjsip_warning_hdr_create_from_status(tdata->pool, + endpt_name, + status); + if (w) + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)w); + + pjsip_inv_send_msg(inv, tdata); + } + return; + } + + /* Invoke Session Timers */ + pjsip_timer_update_resp(inv, tdata); + + /* Send 2xx regardless of the status of negotiation */ + status = pjsip_inv_send_msg(inv, tdata); + + } else if (tsx->state == PJSIP_TSX_STATE_CONFIRMED) { + /* This is the case where ACK has the same branch as + * the INVITE request. + */ + if (tsx->status_code/100 == 2 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + { + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + + /* Check if local offer got no SDP answer */ + if (pjmedia_sdp_neg_get_state(inv->neg)== + PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) + { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } + } + + } } else if (tsx->method.id == PJSIP_INVITE_METHOD && - tsx->role == PJSIP_ROLE_UAC) + tsx->role == PJSIP_ROLE_UAC) { - /* - * Handle outgoing re-INVITE - */ - if (tsx->state == PJSIP_TSX_STATE_CALLING) { + /* + * Handle outgoing re-INVITE + */ + if (tsx->state == PJSIP_TSX_STATE_CALLING) { - /* Must not have other pending INVITE transaction */ - pj_assert(inv->invite_tsx==NULL || tsx==inv->invite_tsx); + /* Must not have other pending INVITE transaction */ + pj_assert(inv->invite_tsx==NULL || tsx==inv->invite_tsx); - /* Save pending invite transaction */ - inv->invite_tsx = tsx; + /* Save pending invite transaction */ + inv->invite_tsx = tsx; } else if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) { /* CANCEL the re-INVITE if necessary */ if (inv->pending_cancel) { - pj_status_t status; - pjsip_tx_data *cancel; + pj_status_t status; + pjsip_tx_data *cancel; + + inv->pending_cancel = PJ_FALSE; + + status = pjsip_inv_cancel_reinvite(inv, &cancel); + if (status == PJ_SUCCESS && cancel) + status = pjsip_inv_send_msg(inv, cancel); + } + + } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED && + tsx->status_code/100 == 2) + { + pj_status_t status; + + /* Re-INVITE was accepted. */ + + /* Check routing URI scheme for secure dialog */ + if (!inv_check_secure_dlg(inv, e)) + return; + + /* Process session timer response. */ + status = handle_timer_response(inv, + e->body.tsx_state.src.rdata, + PJ_TRUE); + if (status != PJ_SUCCESS) + return; + + /* Process SDP */ + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + + /* Check if local offer got no SDP answer */ + if (pjmedia_sdp_neg_get_state(inv->neg)== + PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) + { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } + + /* Send ACK */ + inv_send_ack(inv, e); - inv->pending_cancel = PJ_FALSE; + } else if (handle_uac_tsx_response(inv, e)) { - status = pjsip_inv_cancel_reinvite(inv, &cancel); - if (status == PJ_SUCCESS && cancel) - status = pjsip_inv_send_msg(inv, cancel); + /* Handle response that terminates dialog */ + /* Nothing to do (already handled) */ + + } else if (tsx->status_code >= 300 && tsx->status_code < 700 && + e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) + { + /* Ticket #1654: do not cancel SDP offer when tsx state changing + * from 'completed' to 'terminated', as it should have already + * been cancelled when tsx state is 'completed'. + */ + + pjmedia_sdp_neg_state neg_state; + struct tsx_inv_data *tsx_inv_data; + + tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; + + /* Outgoing INVITE transaction has failed, cancel SDP nego */ + neg_state = pjmedia_sdp_neg_get_state(inv->neg); + if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER && + tsx_inv_data->retrying == PJ_FALSE) + { + pjmedia_sdp_neg_cancel_offer(inv->neg); } - } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED && - tsx->status_code/100 == 2) - { - pj_status_t status; - - /* Re-INVITE was accepted. */ - - /* Check routing URI scheme for secure dialog */ - if (!inv_check_secure_dlg(inv, e)) - return; - - /* Process session timer response. */ - status = handle_timer_response(inv, - e->body.tsx_state.src.rdata, - PJ_TRUE); - if (status != PJ_SUCCESS) - return; - - /* Process SDP */ - inv_check_sdp_in_incoming_msg(inv, tsx, - e->body.tsx_state.src.rdata); - - /* Check if local offer got no SDP answer */ - if (pjmedia_sdp_neg_get_state(inv->neg)== - PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) - { - pjmedia_sdp_neg_cancel_offer(inv->neg); - } - - /* Send ACK */ - inv_send_ack(inv, e); - - } else if (handle_uac_tsx_response(inv, e)) { - - /* Handle response that terminates dialog */ - /* Nothing to do (already handled) */ - - } else if (tsx->status_code >= 300 && tsx->status_code < 700 && - e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) - { - /* Ticket #1654: do not cancel SDP offer when tsx state changing - * from 'completed' to 'terminated', as it should have already - * been cancelled when tsx state is 'completed'. - */ - - pjmedia_sdp_neg_state neg_state; - struct tsx_inv_data *tsx_inv_data; - - tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; - - /* Outgoing INVITE transaction has failed, cancel SDP nego */ - neg_state = pjmedia_sdp_neg_get_state(inv->neg); - if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER && - tsx_inv_data->retrying == PJ_FALSE) - { - pjmedia_sdp_neg_cancel_offer(inv->neg); - } - - if (tsx == inv->invite_tsx) - inv->invite_tsx = NULL; - - /* Process 502/503 error for session timer refresh */ - if (tsx->status_code == 503 || tsx->status_code == 502) { - pjsip_timer_handle_refresh_error(inv, e); - } - } + if (tsx == inv->invite_tsx) + inv->invite_tsx = NULL; + + /* Process 502/503 error for session timer refresh */ + if (tsx->status_code == 503 || tsx->status_code == 502) { + pjsip_timer_handle_refresh_error(inv, e); + } + } } else if (tsx->role == PJSIP_ROLE_UAS && - tsx->state == PJSIP_TSX_STATE_TRYING && - pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) { - /* - * Handle incoming UPDATE - */ - inv_respond_incoming_update(inv, e); + /* + * Handle incoming UPDATE + */ + inv_respond_incoming_update(inv, e); } else if (tsx->role == PJSIP_ROLE_UAC && - (tsx->state == PJSIP_TSX_STATE_COMPLETED || - tsx->state == PJSIP_TSX_STATE_TERMINATED) && - pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + (tsx->state == PJSIP_TSX_STATE_COMPLETED || + tsx->state == PJSIP_TSX_STATE_TERMINATED) && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) { - /* - * Handle response to outgoing UPDATE request. - */ - if (inv_handle_update_response(inv, e) == PJ_FALSE) - handle_uac_tsx_response(inv, e); + /* + * Handle response to outgoing UPDATE request. + */ + if (inv_handle_update_response(inv, e) == PJ_FALSE) + handle_uac_tsx_response(inv, e); } else if (tsx->role == PJSIP_ROLE_UAS && - tsx->state == PJSIP_TSX_STATE_TRYING && - pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0) + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0) { - /* - * Handle strandled incoming PRACK - */ - inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata); + /* + * Handle strandled incoming PRACK + */ + inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata); } else if (tsx->role == PJSIP_ROLE_UAC) { - /* - * Handle 401/407/408/481/422 response - */ - handle_uac_tsx_response(inv, e); + /* + * Handle 401/407/408/481/422 response + */ + handle_uac_tsx_response(inv, e); } } @@ -5517,36 +5516,36 @@ static void inv_on_state_disconnected( pjsip_inv_session *inv, pjsip_event *e) PJ_ASSERT_ON_FAIL(tsx && dlg, return); if (tsx->role == PJSIP_ROLE_UAS && - tsx->status_code < 200 && - e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + tsx->status_code < 200 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { - pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; - /* - * Respond BYE with 200/OK - */ - if (tsx->method.id == PJSIP_BYE_METHOD) { - inv_respond_incoming_bye( inv, tsx, rdata, e ); - } else if (tsx->method.id == PJSIP_CANCEL_METHOD) { - /* - * Respond CANCEL with 200/OK too. - */ - pjsip_tx_data *tdata; - pj_status_t status; + /* + * Respond BYE with 200/OK + */ + if (tsx->method.id == PJSIP_BYE_METHOD) { + inv_respond_incoming_bye( inv, tsx, rdata, e ); + } else if (tsx->method.id == PJSIP_CANCEL_METHOD) { + /* + * Respond CANCEL with 200/OK too. + */ + pjsip_tx_data *tdata; + pj_status_t status; - status = pjsip_dlg_create_response(dlg, rdata, 200, NULL, &tdata); - if (status != PJ_SUCCESS) return; + status = pjsip_dlg_create_response(dlg, rdata, 200, NULL, &tdata); + if (status != PJ_SUCCESS) return; - status = pjsip_dlg_send_response(dlg, tsx, tdata); - if (status != PJ_SUCCESS) return; + status = pjsip_dlg_send_response(dlg, tsx, tdata); + if (status != PJ_SUCCESS) return; - } + } } else if (tsx->role == PJSIP_ROLE_UAC) { - /* - * Handle 401/407/408/481/422 response - */ - handle_uac_tsx_response(inv, e); + /* + * Handle 401/407/408/481/422 response + */ + handle_uac_tsx_response(inv, e); } } diff --git a/pjsip/src/pjsip-ua/sip_reg.c b/pjsip/src/pjsip-ua/sip_reg.c index 1ff1648f86..947e9edb7b 100644 --- a/pjsip/src/pjsip-ua/sip_reg.c +++ b/pjsip/src/pjsip-ua/sip_reg.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,16 +35,16 @@ #include -#define REFRESH_TIMER 1 +#define REFRESH_TIMER 1 #define DELAY_BEFORE_REFRESH PJSIP_REGISTER_CLIENT_DELAY_BEFORE_REFRESH -#define THIS_FILE "sip_reg.c" +#define THIS_FILE "sip_reg.c" /* Outgoing transaction timeout when server sends 100 but never replies * with final response. Value is in MILISECONDS! */ -#define REGC_TSX_TIMEOUT 33000 +#define REGC_TSX_TIMEOUT 33000 -#define NOEXP PJSIP_REGC_EXPIRATION_NOT_SPECIFIED +#define NOEXP PJSIP_REGC_EXPIRATION_NOT_SPECIFIED static const pj_str_t XUID_PARAM_NAME = { "x-uid", 5 }; @@ -63,60 +62,60 @@ enum regc_op */ struct pjsip_regc { - pj_pool_t *pool; - pjsip_endpoint *endpt; - pj_lock_t *lock; - pj_bool_t _delete_flag; - pj_bool_t has_tsx; - pj_atomic_t *busy_ctr; - enum regc_op current_op; - - pj_bool_t add_xuid_param; - - void *token; - pjsip_regc_cb *cb; + pj_pool_t *pool; + pjsip_endpoint *endpt; + pj_lock_t *lock; + pj_bool_t _delete_flag; + pj_bool_t has_tsx; + pj_atomic_t *busy_ctr; + enum regc_op current_op; + + pj_bool_t add_xuid_param; + + void *token; + pjsip_regc_cb *cb; pjsip_regc_tsx_cb *tsx_cb; - pj_str_t str_srv_url; - pjsip_uri *srv_url; - pjsip_cid_hdr *cid_hdr; - pjsip_cseq_hdr *cseq_hdr; - pj_str_t from_uri; - pjsip_from_hdr *from_hdr; - pjsip_to_hdr *to_hdr; - pjsip_contact_hdr contact_hdr_list; - pjsip_contact_hdr removed_contact_hdr_list; - pjsip_expires_hdr *expires_hdr; - pj_uint32_t expires; - pj_uint32_t expires_requested; - pj_uint32_t delay_before_refresh; - pjsip_route_hdr route_set; - pjsip_hdr hdr_list; + pj_str_t str_srv_url; + pjsip_uri *srv_url; + pjsip_cid_hdr *cid_hdr; + pjsip_cseq_hdr *cseq_hdr; + pj_str_t from_uri; + pjsip_from_hdr *from_hdr; + pjsip_to_hdr *to_hdr; + pjsip_contact_hdr contact_hdr_list; + pjsip_contact_hdr removed_contact_hdr_list; + pjsip_expires_hdr *expires_hdr; + pj_uint32_t expires; + pj_uint32_t expires_requested; + pj_uint32_t delay_before_refresh; + pjsip_route_hdr route_set; + pjsip_hdr hdr_list; pjsip_host_port via_addr; const void *via_tp; /* Authorization sessions. */ - pjsip_auth_clt_sess auth_sess; + pjsip_auth_clt_sess auth_sess; /* Auto refresh registration. */ - pj_bool_t auto_reg; - pj_time_val last_reg; - pj_time_val next_reg; - pj_timer_entry timer; + pj_bool_t auto_reg; + pj_time_val last_reg; + pj_time_val next_reg; + pj_timer_entry timer; /* Transport selector */ - pjsip_tpselector tp_sel; + pjsip_tpselector tp_sel; /* Last transport used. We acquire the transport to keep * it open. */ - pjsip_transport *last_transport; + pjsip_transport *last_transport; }; PJ_DEF(pj_status_t) pjsip_regc_create( pjsip_endpoint *endpt, void *token, - pjsip_regc_cb *cb, - pjsip_regc **p_regc) + pjsip_regc_cb *cb, + pjsip_regc **p_regc) { pj_pool_t *pool; pjsip_regc *regc; @@ -138,22 +137,22 @@ PJ_DEF(pj_status_t) pjsip_regc_create( pjsip_endpoint *endpt, void *token, regc->add_xuid_param = pjsip_cfg()->regc.add_xuid_param; status = pj_lock_create_recursive_mutex(pool, pool->obj_name, - ®c->lock); + ®c->lock); if (status != PJ_SUCCESS) { - pj_pool_release(pool); - return status; + pj_pool_release(pool); + return status; } status = pj_atomic_create(pool, 0, ®c->busy_ctr); if (status != PJ_SUCCESS) { - pj_lock_destroy(regc->lock); - pj_pool_release(pool); - return status; + pj_lock_destroy(regc->lock); + pj_pool_release(pool); + return status; } status = pjsip_auth_clt_init(®c->auth_sess, endpt, regc->pool, 0); if (status != PJ_SUCCESS) - return status; + return status; pj_list_init(®c->route_set); pj_list_init(®c->hdr_list); @@ -176,31 +175,31 @@ PJ_DEF(pj_status_t) pjsip_regc_destroy2(pjsip_regc *regc, pj_bool_t force) pj_lock_acquire(regc->lock); if (!force && regc->has_tsx) { - pj_lock_release(regc->lock); - return PJ_EBUSY; + pj_lock_release(regc->lock); + return PJ_EBUSY; } if (regc->has_tsx || pj_atomic_get(regc->busy_ctr) != 0) { - regc->_delete_flag = 1; - regc->cb = NULL; - pj_lock_release(regc->lock); + regc->_delete_flag = 1; + regc->cb = NULL; + pj_lock_release(regc->lock); } else { - pjsip_tpselector_dec_ref(®c->tp_sel); - if (regc->last_transport) { - pjsip_transport_dec_ref(regc->last_transport); - regc->last_transport = NULL; - } - if (regc->timer.id != 0) { - pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); - regc->timer.id = 0; - } - pj_atomic_destroy(regc->busy_ctr); - pj_lock_release(regc->lock); - pj_lock_destroy(regc->lock); - regc->lock = NULL; - - pjsip_auth_clt_deinit(®c->auth_sess); - pjsip_endpt_release_pool(regc->endpt, regc->pool); + pjsip_tpselector_dec_ref(®c->tp_sel); + if (regc->last_transport) { + pjsip_transport_dec_ref(regc->last_transport); + regc->last_transport = NULL; + } + if (regc->timer.id != 0) { + pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); + regc->timer.id = 0; + } + pj_atomic_destroy(regc->busy_ctr); + pj_lock_release(regc->lock); + pj_lock_destroy(regc->lock); + regc->lock = NULL; + + pjsip_auth_clt_deinit(®c->auth_sess); + pjsip_endpt_release_pool(regc->endpt, regc->pool); } return PJ_SUCCESS; @@ -208,7 +207,7 @@ PJ_DEF(pj_status_t) pjsip_regc_destroy2(pjsip_regc *regc, pj_bool_t force) PJ_DEF(pj_status_t) pjsip_regc_get_info( pjsip_regc *regc, - pjsip_regc_info *info ) + pjsip_regc_info *info ) { PJ_ASSERT_RETURN(regc && info, PJ_EINVAL); @@ -222,22 +221,22 @@ PJ_DEF(pj_status_t) pjsip_regc_get_info( pjsip_regc *regc, info->transport = regc->last_transport; if (regc->has_tsx) - info->next_reg = 0; + info->next_reg = 0; else if (regc->auto_reg == 0) - info->next_reg = 0; + info->next_reg = 0; else if (regc->expires == PJSIP_REGC_EXPIRATION_NOT_SPECIFIED) - info->next_reg = regc->expires; + info->next_reg = regc->expires; else { - pj_time_val now, next_reg; - - next_reg = regc->next_reg; - pj_gettimeofday(&now); - if (PJ_TIME_VAL_GT(next_reg, now)) { - PJ_TIME_VAL_SUB(next_reg, now); - info->next_reg = next_reg.sec; - } else { - info->next_reg = 0; - } + pj_time_val now, next_reg; + + next_reg = regc->next_reg; + pj_gettimeofday(&now); + if (PJ_TIME_VAL_GT(next_reg, now)) { + PJ_TIME_VAL_SUB(next_reg, now); + info->next_reg = next_reg.sec; + } else { + info->next_reg = 0; + } } pj_lock_release(regc->lock); @@ -254,16 +253,16 @@ PJ_DEF(pj_pool_t*) pjsip_regc_get_pool(pjsip_regc *regc) static void set_expires( pjsip_regc *regc, pj_uint32_t expires) { if (expires != regc->expires) { - regc->expires_hdr = pjsip_expires_hdr_create(regc->pool, expires); + regc->expires_hdr = pjsip_expires_hdr_create(regc->pool, expires); } else { - regc->expires_hdr = NULL; + regc->expires_hdr = NULL; } } static pj_status_t set_contact( pjsip_regc *regc, - int contact_cnt, - const pj_str_t contact[] ) + int contact_cnt, + const pj_str_t contact[] ) { const pj_str_t CONTACT = { "Contact", 7 }; pjsip_contact_hdr *h; @@ -273,68 +272,68 @@ static pj_status_t set_contact( pjsip_regc *regc, * clear contact_hdr_list. */ pj_list_merge_last(®c->removed_contact_hdr_list, - ®c->contact_hdr_list); + ®c->contact_hdr_list); /* Set the expiration of Contacts in to removed_contact_hdr_list * zero. */ h = regc->removed_contact_hdr_list.next; while (h != ®c->removed_contact_hdr_list) { - h->expires = 0; - h = h->next; + h->expires = 0; + h = h->next; } /* Process new contacts */ for (i=0; ipool, &tmp, &contact[i]); - hdr = (pjsip_contact_hdr*) + pj_strdup_with_null(regc->pool, &tmp, &contact[i]); + hdr = (pjsip_contact_hdr*) pjsip_parse_hdr(regc->pool, &CONTACT, tmp.ptr, tmp.slen, NULL); - if (hdr == NULL) { - PJ_LOG(4,(THIS_FILE, "Invalid Contact: \"%.*s\"", - (int)tmp.slen, tmp.ptr)); - return PJSIP_EINVALIDURI; - } - - /* Find the new contact in old contact list. If found, remove - * the old header from the old header list. - */ - h = regc->removed_contact_hdr_list.next; - while (h != ®c->removed_contact_hdr_list) { - int rc; - - rc = pjsip_uri_cmp(PJSIP_URI_IN_CONTACT_HDR, - h->uri, hdr->uri); - if (rc == 0) { - /* Match */ - pj_list_erase(h); - break; - } - - h = h->next; - } - - /* If add_xuid_param option is enabled and Contact URI is sip/sips, - * add xuid parameter to assist matching the Contact URI in the - * REGISTER response later. - */ - if (regc->add_xuid_param && (PJSIP_URI_SCHEME_IS_SIP(hdr->uri) || - PJSIP_URI_SCHEME_IS_SIPS(hdr->uri))) - { - pjsip_param *xuid_param; - pjsip_sip_uri *sip_uri; - - xuid_param = PJ_POOL_ZALLOC_T(regc->pool, pjsip_param); - xuid_param->name = XUID_PARAM_NAME; - pj_create_unique_string(regc->pool, &xuid_param->value); - - sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(hdr->uri); - pj_list_push_back(&sip_uri->other_param, xuid_param); - } - - pj_list_push_back(®c->contact_hdr_list, hdr); + if (hdr == NULL) { + PJ_LOG(4,(THIS_FILE, "Invalid Contact: \"%.*s\"", + (int)tmp.slen, tmp.ptr)); + return PJSIP_EINVALIDURI; + } + + /* Find the new contact in old contact list. If found, remove + * the old header from the old header list. + */ + h = regc->removed_contact_hdr_list.next; + while (h != ®c->removed_contact_hdr_list) { + int rc; + + rc = pjsip_uri_cmp(PJSIP_URI_IN_CONTACT_HDR, + h->uri, hdr->uri); + if (rc == 0) { + /* Match */ + pj_list_erase(h); + break; + } + + h = h->next; + } + + /* If add_xuid_param option is enabled and Contact URI is sip/sips, + * add xuid parameter to assist matching the Contact URI in the + * REGISTER response later. + */ + if (regc->add_xuid_param && (PJSIP_URI_SCHEME_IS_SIP(hdr->uri) || + PJSIP_URI_SCHEME_IS_SIPS(hdr->uri))) + { + pjsip_param *xuid_param; + pjsip_sip_uri *sip_uri; + + xuid_param = PJ_POOL_ZALLOC_T(regc->pool, pjsip_param); + xuid_param->name = XUID_PARAM_NAME; + pj_create_unique_string(regc->pool, &xuid_param->value); + + sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(hdr->uri); + pj_list_push_back(&sip_uri->other_param, xuid_param); + } + + pj_list_push_back(®c->contact_hdr_list, hdr); } return PJ_SUCCESS; @@ -342,18 +341,18 @@ static pj_status_t set_contact( pjsip_regc *regc, PJ_DEF(pj_status_t) pjsip_regc_init( pjsip_regc *regc, - const pj_str_t *srv_url, - const pj_str_t *from_url, - const pj_str_t *to_url, - int contact_cnt, - const pj_str_t contact[], - pj_uint32_t expires) + const pj_str_t *srv_url, + const pj_str_t *from_url, + const pj_str_t *to_url, + int contact_cnt, + const pj_str_t contact[], + pj_uint32_t expires) { pj_str_t tmp; pj_status_t status; PJ_ASSERT_RETURN(regc && srv_url && from_url && to_url && - expires, PJ_EINVAL); + expires, PJ_EINVAL); /* Copy server URL. */ pj_strdup_with_null(regc->pool, ®c->str_srv_url, srv_url); @@ -362,7 +361,7 @@ PJ_DEF(pj_status_t) pjsip_regc_init( pjsip_regc *regc, tmp = regc->str_srv_url; regc->srv_url = pjsip_parse_uri( regc->pool, tmp.ptr, tmp.slen, 0); if (regc->srv_url == NULL) { - return PJSIP_EINVALIDURI; + return PJSIP_EINVALIDURI; } /* Set "From" header. */ @@ -370,28 +369,28 @@ PJ_DEF(pj_status_t) pjsip_regc_init( pjsip_regc *regc, tmp = regc->from_uri; regc->from_hdr = pjsip_from_hdr_create(regc->pool); regc->from_hdr->uri = pjsip_parse_uri(regc->pool, tmp.ptr, tmp.slen, - PJSIP_PARSE_URI_AS_NAMEADDR); + PJSIP_PARSE_URI_AS_NAMEADDR); if (!regc->from_hdr->uri) { - PJ_LOG(4,(THIS_FILE, "regc: invalid source URI %.*s", - from_url->slen, from_url->ptr)); - return PJSIP_EINVALIDURI; + PJ_LOG(4,(THIS_FILE, "regc: invalid source URI %.*s", + from_url->slen, from_url->ptr)); + return PJSIP_EINVALIDURI; } /* Set "To" header. */ pj_strdup_with_null(regc->pool, &tmp, to_url); regc->to_hdr = pjsip_to_hdr_create(regc->pool); regc->to_hdr->uri = pjsip_parse_uri(regc->pool, tmp.ptr, tmp.slen, - PJSIP_PARSE_URI_AS_NAMEADDR); + PJSIP_PARSE_URI_AS_NAMEADDR); if (!regc->to_hdr->uri) { - PJ_LOG(4,(THIS_FILE, "regc: invalid target URI %.*s", to_url->slen, to_url->ptr)); - return PJSIP_EINVALIDURI; + PJ_LOG(4,(THIS_FILE, "regc: invalid target URI %.*s", to_url->slen, to_url->ptr)); + return PJSIP_EINVALIDURI; } /* Set "Contact" header. */ status = set_contact( regc, contact_cnt, contact); if (status != PJ_SUCCESS) - return status; + return status; /* Set "Expires" header, if required. */ set_expires( regc, expires); @@ -420,30 +419,30 @@ PJ_DEF(pj_status_t) pjsip_regc_dec_ref( pjsip_regc *regc ) { pj_assert(regc); if (pj_atomic_dec_and_get(regc->busy_ctr)==0 && regc->_delete_flag) { - pjsip_regc_destroy(regc); - return PJ_EGONE; + pjsip_regc_destroy(regc); + return PJ_EGONE; } return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjsip_regc_set_credentials( pjsip_regc *regc, - int count, - const pjsip_cred_info cred[] ) + int count, + const pjsip_cred_info cred[] ) { PJ_ASSERT_RETURN(regc && count && cred, PJ_EINVAL); return pjsip_auth_clt_set_credentials(®c->auth_sess, count, cred); } PJ_DEF(pj_status_t) pjsip_regc_set_prefs( pjsip_regc *regc, - const pjsip_auth_clt_pref *pref) + const pjsip_auth_clt_pref *pref) { PJ_ASSERT_RETURN(regc && pref, PJ_EINVAL); return pjsip_auth_clt_set_prefs(®c->auth_sess, pref); } PJ_DEF(pj_status_t) pjsip_regc_set_route_set( pjsip_regc *regc, - const pjsip_route_hdr *route_set) + const pjsip_route_hdr *route_set) { const pjsip_route_hdr *chdr; @@ -453,8 +452,8 @@ PJ_DEF(pj_status_t) pjsip_regc_set_route_set( pjsip_regc *regc, chdr = route_set->next; while (chdr != route_set) { - pj_list_push_back(®c->route_set, pjsip_hdr_clone(regc->pool, chdr)); - chdr = chdr->next; + pj_list_push_back(®c->route_set, pjsip_hdr_clone(regc->pool, chdr)); + chdr = chdr->next; } return PJ_SUCCESS; @@ -465,7 +464,7 @@ PJ_DEF(pj_status_t) pjsip_regc_set_route_set( pjsip_regc *regc, * Bind client registration to a specific transport/listener. */ PJ_DEF(pj_status_t) pjsip_regc_set_transport( pjsip_regc *regc, - const pjsip_tpselector *sel) + const pjsip_tpselector *sel) { PJ_ASSERT_RETURN(regc && sel, PJ_EINVAL); @@ -481,15 +480,15 @@ PJ_DEF(pj_status_t) pjsip_regc_release_transport(pjsip_regc *regc) { PJ_ASSERT_RETURN(regc, PJ_EINVAL); if (regc->last_transport) { - pjsip_transport_dec_ref(regc->last_transport); - regc->last_transport = NULL; + pjsip_transport_dec_ref(regc->last_transport); + regc->last_transport = NULL; } return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjsip_regc_add_headers( pjsip_regc *regc, - const pjsip_hdr *hdr_list) + const pjsip_hdr *hdr_list) { const pjsip_hdr *hdr; @@ -500,15 +499,15 @@ PJ_DEF(pj_status_t) pjsip_regc_add_headers( pjsip_regc *regc, hdr = hdr_list->next; while (hdr != hdr_list) { - pj_list_push_back(®c->hdr_list, pjsip_hdr_clone(regc->pool, hdr)); - hdr = hdr->next; + pj_list_push_back(®c->hdr_list, pjsip_hdr_clone(regc->pool, hdr)); + hdr = hdr->next; } return PJ_SUCCESS; } static pj_status_t create_request(pjsip_regc *regc, - pjsip_tx_data **p_tdata) + pjsip_tx_data **p_tdata) { pj_status_t status; pjsip_tx_data *tdata; @@ -517,52 +516,52 @@ static pj_status_t create_request(pjsip_regc *regc, /* Create the request. */ status = pjsip_endpt_create_request_from_hdr( regc->endpt, - pjsip_get_register_method(), - regc->srv_url, - regc->from_hdr, - regc->to_hdr, - NULL, - regc->cid_hdr, - regc->cseq_hdr->cseq, - NULL, - &tdata); + pjsip_get_register_method(), + regc->srv_url, + regc->from_hdr, + regc->to_hdr, + NULL, + regc->cid_hdr, + regc->cseq_hdr->cseq, + NULL, + &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Add cached authorization headers. */ pjsip_auth_clt_init_req( ®c->auth_sess, tdata ); /* Add Route headers from route set, ideally after Via header */ if (!pj_list_empty(®c->route_set)) { - pjsip_hdr *route_pos; - const pjsip_route_hdr *route; - - route_pos = (pjsip_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); - if (!route_pos) - route_pos = &tdata->msg->hdr; - - route = regc->route_set.next; - while (route != ®c->route_set) { - pjsip_hdr *new_hdr = (pjsip_hdr*) - pjsip_hdr_clone(tdata->pool, route); - pj_list_insert_after(route_pos, new_hdr); - route_pos = new_hdr; - route = route->next; - } + pjsip_hdr *route_pos; + const pjsip_route_hdr *route; + + route_pos = (pjsip_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); + if (!route_pos) + route_pos = &tdata->msg->hdr; + + route = regc->route_set.next; + while (route != ®c->route_set) { + pjsip_hdr *new_hdr = (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, route); + pj_list_insert_after(route_pos, new_hdr); + route_pos = new_hdr; + route = route->next; + } } /* Add additional request headers */ if (!pj_list_empty(®c->hdr_list)) { - const pjsip_hdr *hdr; - - hdr = regc->hdr_list.next; - while (hdr != ®c->hdr_list) { - pjsip_hdr *new_hdr = (pjsip_hdr*) - pjsip_hdr_clone(tdata->pool, hdr); - pjsip_msg_add_hdr(tdata->msg, new_hdr); - hdr = hdr->next; - } + const pjsip_hdr *hdr; + + hdr = regc->hdr_list.next; + while (hdr != ®c->hdr_list) { + pjsip_hdr *new_hdr = (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, hdr); + pjsip_msg_add_hdr(tdata->msg, new_hdr); + hdr = hdr->next; + } } /* Done. */ @@ -572,7 +571,7 @@ static pj_status_t create_request(pjsip_regc *regc, PJ_DEF(pj_status_t) pjsip_regc_register(pjsip_regc *regc, pj_bool_t autoreg, - pjsip_tx_data **p_tdata) + pjsip_tx_data **p_tdata) { pjsip_msg *msg; pjsip_contact_hdr *hdr; @@ -588,8 +587,8 @@ PJ_DEF(pj_status_t) pjsip_regc_register(pjsip_regc *regc, pj_bool_t autoreg, status = create_request(regc, &tdata); if (status != PJ_SUCCESS) { - pj_lock_release(regc->lock); - return status; + pj_lock_release(regc->lock); + return status; } msg = tdata->msg; @@ -597,35 +596,35 @@ PJ_DEF(pj_status_t) pjsip_regc_register(pjsip_regc *regc, pj_bool_t autoreg, /* Add Contact headers. */ hdr = regc->contact_hdr_list.next; while (hdr != ®c->contact_hdr_list) { - pjsip_msg_add_hdr(msg, (pjsip_hdr*) - pjsip_hdr_clone(tdata->pool, hdr)); - hdr = hdr->next; + pjsip_msg_add_hdr(msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, hdr)); + hdr = hdr->next; } /* Also add bindings which are to be removed */ while (!pj_list_empty(®c->removed_contact_hdr_list)) { - hdr = regc->removed_contact_hdr_list.next; - pjsip_msg_add_hdr(msg, (pjsip_hdr*) - pjsip_hdr_clone(tdata->pool, hdr)); - pj_list_erase(hdr); + hdr = regc->removed_contact_hdr_list.next; + pjsip_msg_add_hdr(msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, hdr)); + pj_list_erase(hdr); } if (regc->expires_hdr) - pjsip_msg_add_hdr(msg, (pjsip_hdr*) - pjsip_hdr_clone(tdata->pool, - regc->expires_hdr)); + pjsip_msg_add_hdr(msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, + regc->expires_hdr)); if (regc->timer.id != 0) { - pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); - regc->timer.id = 0; + pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); + regc->timer.id = 0; } /* Add Allow header (https://github.com/pjsip/pjproject/issues/1039) */ h_allow = pjsip_endpt_get_capability(regc->endpt, PJSIP_H_ALLOW, NULL); if (h_allow) { - pjsip_msg_add_hdr(msg, (pjsip_hdr*) - pjsip_hdr_clone(tdata->pool, h_allow)); + pjsip_msg_add_hdr(msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, h_allow)); } @@ -640,7 +639,7 @@ PJ_DEF(pj_status_t) pjsip_regc_register(pjsip_regc *regc, pj_bool_t autoreg, PJ_DEF(pj_status_t) pjsip_regc_unregister(pjsip_regc *regc, - pjsip_tx_data **p_tdata) + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pjsip_msg *msg; @@ -652,16 +651,16 @@ PJ_DEF(pj_status_t) pjsip_regc_unregister(pjsip_regc *regc, pj_lock_acquire(regc->lock); if (regc->timer.id != 0) { - pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); - regc->timer.id = 0; + pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); + regc->timer.id = 0; } regc->expires_requested = 0; status = create_request(regc, &tdata); if (status != PJ_SUCCESS) { - pj_lock_release(regc->lock); - return status; + pj_lock_release(regc->lock); + return status; } msg = tdata->msg; @@ -669,17 +668,17 @@ PJ_DEF(pj_status_t) pjsip_regc_unregister(pjsip_regc *regc, /* Add Contact headers. */ hdr = (pjsip_hdr*)regc->contact_hdr_list.next; while ((void*)hdr != (void*)®c->contact_hdr_list) { - pjsip_msg_add_hdr(msg, (pjsip_hdr*) - pjsip_hdr_clone(tdata->pool, hdr)); - hdr = hdr->next; + pjsip_msg_add_hdr(msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, hdr)); + hdr = hdr->next; } /* Also add bindings which are to be removed */ while (!pj_list_empty(®c->removed_contact_hdr_list)) { - hdr = (pjsip_hdr*)regc->removed_contact_hdr_list.next; - pjsip_msg_add_hdr(msg, (pjsip_hdr*) - pjsip_hdr_clone(tdata->pool, hdr)); - pj_list_erase(hdr); + hdr = (pjsip_hdr*)regc->removed_contact_hdr_list.next; + pjsip_msg_add_hdr(msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, hdr)); + pj_list_erase(hdr); } /* Add Expires:0 header */ @@ -693,7 +692,7 @@ PJ_DEF(pj_status_t) pjsip_regc_unregister(pjsip_regc *regc, } PJ_DEF(pj_status_t) pjsip_regc_unregister_all(pjsip_regc *regc, - pjsip_tx_data **p_tdata) + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pjsip_contact_hdr *hcontact; @@ -706,14 +705,14 @@ PJ_DEF(pj_status_t) pjsip_regc_unregister_all(pjsip_regc *regc, pj_lock_acquire(regc->lock); if (regc->timer.id != 0) { - pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); - regc->timer.id = 0; + pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); + regc->timer.id = 0; } status = create_request(regc, &tdata); if (status != PJ_SUCCESS) { - pj_lock_release(regc->lock); - return status; + pj_lock_release(regc->lock); + return status; } msg = tdata->msg; @@ -738,8 +737,8 @@ PJ_DEF(pj_status_t) pjsip_regc_unregister_all(pjsip_regc *regc, PJ_DEF(pj_status_t) pjsip_regc_update_contact( pjsip_regc *regc, - int contact_cnt, - const pj_str_t contact[] ) + int contact_cnt, + const pj_str_t contact[] ) { pj_status_t status; @@ -754,7 +753,7 @@ PJ_DEF(pj_status_t) pjsip_regc_update_contact( pjsip_regc *regc, PJ_DEF(pj_status_t) pjsip_regc_update_expires( pjsip_regc *regc, - pj_uint32_t expires ) + pj_uint32_t expires ) { PJ_ASSERT_RETURN(regc, PJ_EINVAL); @@ -768,10 +767,10 @@ PJ_DEF(pj_status_t) pjsip_regc_update_expires( pjsip_regc *regc, static void cbparam_init( struct pjsip_regc_cbparam *cbparam, pjsip_regc *regc, pj_status_t status, int st_code, - const pj_str_t *reason, - pjsip_rx_data *rdata, pj_uint32_t expiration, - int contact_cnt, pjsip_contact_hdr *contact[], - pj_bool_t is_unreg) + const pj_str_t *reason, + pjsip_rx_data *rdata, pj_uint32_t expiration, + int contact_cnt, pjsip_contact_hdr *contact[], + pj_bool_t is_unreg) { cbparam->regc = regc; cbparam->token = regc->token; @@ -781,24 +780,24 @@ static void cbparam_init( struct pjsip_regc_cbparam *cbparam, cbparam->rdata = rdata; cbparam->contact_cnt = contact_cnt; cbparam->expiration = (expiration != PJSIP_REGC_EXPIRATION_NOT_SPECIFIED? - expiration: regc->expires_requested); + expiration: regc->expires_requested); cbparam->is_unreg = is_unreg; if (contact_cnt) { - pj_memcpy( cbparam->contact, contact, - contact_cnt*sizeof(pjsip_contact_hdr*)); + pj_memcpy( cbparam->contact, contact, + contact_cnt*sizeof(pjsip_contact_hdr*)); } } static void call_callback(pjsip_regc *regc, pj_status_t status, int st_code, - const pj_str_t *reason, - pjsip_rx_data *rdata, pj_uint32_t expiration, - int contact_cnt, pjsip_contact_hdr *contact[], - pj_bool_t is_unreg) + const pj_str_t *reason, + pjsip_rx_data *rdata, pj_uint32_t expiration, + int contact_cnt, pjsip_contact_hdr *contact[], + pj_bool_t is_unreg) { struct pjsip_regc_cbparam cbparam; if (!regc->cb) - return; + return; cbparam_init(&cbparam, regc, status, st_code, reason, rdata, expiration, contact_cnt, contact, is_unreg); @@ -806,7 +805,7 @@ static void call_callback(pjsip_regc *regc, pj_status_t status, int st_code, } static void regc_refresh_timer_cb( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { pjsip_regc *regc = (pjsip_regc*) entry->user_data; pjsip_tx_data *tdata; @@ -822,14 +821,14 @@ static void regc_refresh_timer_cb( pj_timer_heap_t *timer_heap, entry->id = 0; status = pjsip_regc_register(regc, 1, &tdata); if (status == PJ_SUCCESS) { - status = pjsip_regc_send(regc, tdata); + status = pjsip_regc_send(regc, tdata); } if (status != PJ_SUCCESS && regc->cb) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_str_t reason = pj_strerror(status, errmsg, sizeof(errmsg)); - call_callback(regc, status, 400, &reason, NULL, NOEXP, 0, NULL, - PJ_FALSE); + char errmsg[PJ_ERR_MSG_SIZE]; + pj_str_t reason = pj_strerror(status, errmsg, sizeof(errmsg)); + call_callback(regc, status, 400, &reason, NULL, NOEXP, 0, NULL, + PJ_FALSE); } /* Delete the record if user destroy regc during the callback. */ @@ -863,7 +862,7 @@ static void schedule_registration ( pjsip_regc *regc, pj_uint32_t expiration ) } PJ_DEF(pj_status_t) pjsip_regc_set_reg_tsx_cb( pjsip_regc *regc, - pjsip_regc_tsx_cb *tsx_cb) + pjsip_regc_tsx_cb *tsx_cb) { PJ_ASSERT_RETURN(regc, PJ_EINVAL); regc->tsx_cb = tsx_cb; @@ -872,7 +871,7 @@ PJ_DEF(pj_status_t) pjsip_regc_set_reg_tsx_cb( pjsip_regc *regc, PJ_DEF(pj_status_t) pjsip_regc_set_via_sent_by( pjsip_regc *regc, - pjsip_host_port *via_addr, + pjsip_host_port *via_addr, pjsip_transport *via_tp) { PJ_ASSERT_RETURN(regc, PJ_EINVAL); @@ -891,7 +890,7 @@ PJ_DEF(pj_status_t) pjsip_regc_set_via_sent_by( pjsip_regc *regc, PJ_DEF(pj_status_t) pjsip_regc_set_delay_before_refresh( pjsip_regc *regc, - pj_uint32_t delay ) + pj_uint32_t delay ) { PJ_ASSERT_RETURN(regc, PJ_EINVAL); @@ -921,10 +920,10 @@ pjsip_regc_set_delay_before_refresh( pjsip_regc *regc, static pj_uint32_t calculate_response_expiration(const pjsip_regc *regc, - const pjsip_rx_data *rdata, - unsigned *contact_cnt, - unsigned max_contact, - pjsip_contact_hdr *contacts[]) + const pjsip_rx_data *rdata, + unsigned *contact_cnt, + unsigned max_contact, + pjsip_contact_hdr *contacts[]) { pj_uint32_t expiration = NOEXP; const pjsip_msg *msg = rdata->msg_info.msg; @@ -933,152 +932,152 @@ static pj_uint32_t calculate_response_expiration(const pjsip_regc *regc, /* Enumerate all Contact headers in the response */ *contact_cnt = 0; for (hdr=msg->hdr.next; hdr!=&msg->hdr; hdr=hdr->next) { - if (hdr->type == PJSIP_H_CONTACT && - *contact_cnt < max_contact) - { - contacts[*contact_cnt] = (pjsip_contact_hdr*)hdr; - ++(*contact_cnt); - } + if (hdr->type == PJSIP_H_CONTACT && + *contact_cnt < max_contact) + { + contacts[*contact_cnt] = (pjsip_contact_hdr*)hdr; + ++(*contact_cnt); + } } if (regc->current_op == REGC_REGISTERING) { - pj_bool_t has_our_contact = PJ_FALSE; - const pjsip_expires_hdr *expires; - - /* Get Expires header */ - expires = (const pjsip_expires_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_EXPIRES, NULL); - - /* Try to find the Contact URIs that we register, in the response - * to get the expires value. We'll try both with comparing the URI - * and comparing the extension param only. - */ - if (pjsip_cfg()->regc.check_contact || regc->add_xuid_param) { - unsigned i; - for (i=0; i<*contact_cnt; ++i) { - const pjsip_contact_hdr *our_hdr; - - our_hdr = (const pjsip_contact_hdr*) - regc->contact_hdr_list.next; - - /* Match with our Contact header(s) */ - while ((void*)our_hdr != (void*)®c->contact_hdr_list) { - - const pjsip_uri *uri1, *uri2; - pj_bool_t matched = PJ_FALSE; - - /* Exclude the display name when comparing the URI - * since server may not return it. - */ - uri1 = (const pjsip_uri*) - pjsip_uri_get_uri(contacts[i]->uri); - uri2 = (const pjsip_uri*) - pjsip_uri_get_uri(our_hdr->uri); - - /* First try with exact matching, according to RFC 3261 - * Section 19.1.4 URI Comparison - */ - if (pjsip_cfg()->regc.check_contact) { - matched = pjsip_uri_cmp(PJSIP_URI_IN_CONTACT_HDR, - uri1, uri2)==0; - } - - /* If no match is found, try with matching the extension - * parameter only if extension parameter was added. - */ - if (!matched && regc->add_xuid_param && - (PJSIP_URI_SCHEME_IS_SIP(uri1) || - PJSIP_URI_SCHEME_IS_SIPS(uri1)) && - (PJSIP_URI_SCHEME_IS_SIP(uri2) || - PJSIP_URI_SCHEME_IS_SIPS(uri2))) - { - const pjsip_sip_uri *sip_uri1, *sip_uri2; - const pjsip_param *p1, *p2; - - sip_uri1 = (const pjsip_sip_uri*)uri1; - sip_uri2 = (const pjsip_sip_uri*)uri2; - - p1 = pjsip_param_cfind(&sip_uri1->other_param, - &XUID_PARAM_NAME); - p2 = pjsip_param_cfind(&sip_uri2->other_param, - &XUID_PARAM_NAME); - matched = p1 && p2 && - pj_strcmp(&p1->value, &p2->value)==0; - - } - - if (matched) { - has_our_contact = PJ_TRUE; - - if (contacts[i]->expires != PJSIP_EXPIRES_NOT_SPECIFIED - && contacts[i]->expires < expiration) - { - /* Get the lowest expiration time. */ - expiration = contacts[i]->expires; - } - - break; - } - - our_hdr = our_hdr->next; - - } /* while ((void.. */ - - } /* for (i=.. */ - - /* If matching Contact header(s) are found but the - * header doesn't contain expires parameter, get the - * expiration value from the Expires header. And - * if Expires header is not present, get the expiration - * value from the request. - */ - if (has_our_contact && expiration == NOEXP) { - if (expires) { - expiration = expires->ivalue; - } else if (regc->expires_hdr) { - expiration = regc->expires_hdr->ivalue; - } else { - /* We didn't request explicit expiration value, - * and server doesn't specify it either. This - * shouldn't happen unless we have a broken - * registrar. - */ - expiration = 3600; - } - } - - } - - /* If we still couldn't get matching Contact header(s), it means - * there must be something wrong with the registrar (e.g. it may - * have modified the URI's in the response, which is prohibited). - */ - if (expiration==NOEXP) { - /* If the number of Contact headers in the response matches - * ours, they're all probably ours. Get the expiration - * from there if this is the case, or from Expires header - * if we don't have exact Contact header count, or - * from the request as the last resort. - */ - pj_size_t our_contact_cnt; - - our_contact_cnt = pj_list_size(®c->contact_hdr_list); - - if (*contact_cnt == our_contact_cnt && *contact_cnt && - contacts[0]->expires != PJSIP_EXPIRES_NOT_SPECIFIED) - { - expiration = contacts[0]->expires; - } else if (expires) - expiration = expires->ivalue; - else if (regc->expires_hdr) - expiration = regc->expires_hdr->ivalue; - else - expiration = 3600; - } + pj_bool_t has_our_contact = PJ_FALSE; + const pjsip_expires_hdr *expires; + + /* Get Expires header */ + expires = (const pjsip_expires_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_EXPIRES, NULL); + + /* Try to find the Contact URIs that we register, in the response + * to get the expires value. We'll try both with comparing the URI + * and comparing the extension param only. + */ + if (pjsip_cfg()->regc.check_contact || regc->add_xuid_param) { + unsigned i; + for (i=0; i<*contact_cnt; ++i) { + const pjsip_contact_hdr *our_hdr; + + our_hdr = (const pjsip_contact_hdr*) + regc->contact_hdr_list.next; + + /* Match with our Contact header(s) */ + while ((void*)our_hdr != (void*)®c->contact_hdr_list) { + + const pjsip_uri *uri1, *uri2; + pj_bool_t matched = PJ_FALSE; + + /* Exclude the display name when comparing the URI + * since server may not return it. + */ + uri1 = (const pjsip_uri*) + pjsip_uri_get_uri(contacts[i]->uri); + uri2 = (const pjsip_uri*) + pjsip_uri_get_uri(our_hdr->uri); + + /* First try with exact matching, according to RFC 3261 + * Section 19.1.4 URI Comparison + */ + if (pjsip_cfg()->regc.check_contact) { + matched = pjsip_uri_cmp(PJSIP_URI_IN_CONTACT_HDR, + uri1, uri2)==0; + } + + /* If no match is found, try with matching the extension + * parameter only if extension parameter was added. + */ + if (!matched && regc->add_xuid_param && + (PJSIP_URI_SCHEME_IS_SIP(uri1) || + PJSIP_URI_SCHEME_IS_SIPS(uri1)) && + (PJSIP_URI_SCHEME_IS_SIP(uri2) || + PJSIP_URI_SCHEME_IS_SIPS(uri2))) + { + const pjsip_sip_uri *sip_uri1, *sip_uri2; + const pjsip_param *p1, *p2; + + sip_uri1 = (const pjsip_sip_uri*)uri1; + sip_uri2 = (const pjsip_sip_uri*)uri2; + + p1 = pjsip_param_cfind(&sip_uri1->other_param, + &XUID_PARAM_NAME); + p2 = pjsip_param_cfind(&sip_uri2->other_param, + &XUID_PARAM_NAME); + matched = p1 && p2 && + pj_strcmp(&p1->value, &p2->value)==0; + + } + + if (matched) { + has_our_contact = PJ_TRUE; + + if (contacts[i]->expires != PJSIP_EXPIRES_NOT_SPECIFIED + && contacts[i]->expires < expiration) + { + /* Get the lowest expiration time. */ + expiration = contacts[i]->expires; + } + + break; + } + + our_hdr = our_hdr->next; + + } /* while ((void.. */ + + } /* for (i=.. */ + + /* If matching Contact header(s) are found but the + * header doesn't contain expires parameter, get the + * expiration value from the Expires header. And + * if Expires header is not present, get the expiration + * value from the request. + */ + if (has_our_contact && expiration == NOEXP) { + if (expires) { + expiration = expires->ivalue; + } else if (regc->expires_hdr) { + expiration = regc->expires_hdr->ivalue; + } else { + /* We didn't request explicit expiration value, + * and server doesn't specify it either. This + * shouldn't happen unless we have a broken + * registrar. + */ + expiration = 3600; + } + } + + } + + /* If we still couldn't get matching Contact header(s), it means + * there must be something wrong with the registrar (e.g. it may + * have modified the URI's in the response, which is prohibited). + */ + if (expiration==NOEXP) { + /* If the number of Contact headers in the response matches + * ours, they're all probably ours. Get the expiration + * from there if this is the case, or from Expires header + * if we don't have exact Contact header count, or + * from the request as the last resort. + */ + pj_size_t our_contact_cnt; + + our_contact_cnt = pj_list_size(®c->contact_hdr_list); + + if (*contact_cnt == our_contact_cnt && *contact_cnt && + contacts[0]->expires != PJSIP_EXPIRES_NOT_SPECIFIED) + { + expiration = contacts[0]->expires; + } else if (expires) + expiration = expires->ivalue; + else if (regc->expires_hdr) + expiration = regc->expires_hdr->ivalue; + else + expiration = 3600; + } } else { - /* Just assume that the unregistration has been successful. */ - expiration = 0; + /* Just assume that the unregistration has been successful. */ + expiration = 0; } /* Must have expiration value by now */ @@ -1104,15 +1103,15 @@ static void regc_tsx_callback(void *token, pjsip_event *event) /* Add reference to the transport */ if (tsx->transport != regc->last_transport) { - if (regc->last_transport) { - pjsip_transport_dec_ref(regc->last_transport); - regc->last_transport = NULL; - } - - if (tsx->transport) { - regc->last_transport = tsx->transport; - pjsip_transport_add_ref(regc->last_transport); - } + if (regc->last_transport) { + pjsip_transport_dec_ref(regc->last_transport); + regc->last_transport = NULL; + } + + if (tsx->transport) { + regc->last_transport = tsx->transport; + pjsip_transport_add_ref(regc->last_transport); + } } if (regc->_delete_flag == 0 && regc->tsx_cb && @@ -1122,9 +1121,9 @@ static void regc_tsx_callback(void *token, pjsip_event *event) param.contact_cnt = -1; cbparam_init(¶m.cbparam, regc, PJ_SUCCESS, tsx->status_code, - &tsx->status_text, + &tsx->status_text, (event->body.tsx_state.type==PJSIP_EVENT_RX_MSG) ? - event->body.tsx_state.src.rdata : NULL, + event->body.tsx_state.src.rdata : NULL, NOEXP, 0, NULL, PJ_FALSE); /* Call regc tsx callback before handling any response */ @@ -1141,8 +1140,8 @@ static void regc_tsx_callback(void *token, pjsip_event *event) if (tsx->status_code/100 != 2) { pjsip_contact_hdr *h; - h = regc->contact_hdr_list.next; - while (h != ®c->contact_hdr_list) { + h = regc->contact_hdr_list.next; + while (h != ®c->contact_hdr_list) { pjsip_contact_hdr *next = h->next; if (h->expires == PJSIP_EXPIRES_NOT_SPECIFIED) { @@ -1150,7 +1149,7 @@ static void regc_tsx_callback(void *token, pjsip_event *event) } h = next; } - } + } /* Update contact address */ pjsip_regc_update_contact(regc, param.contact_cnt, param.contact); @@ -1160,15 +1159,15 @@ static void regc_tsx_callback(void *token, pjsip_event *event) /* Handle 401/407 challenge (even when _delete_flag is set) */ if (tsx->status_code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED || - tsx->status_code == PJSIP_SC_UNAUTHORIZED) + tsx->status_code == PJSIP_SC_UNAUTHORIZED) { - pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; - pjsip_tx_data *tdata; - pj_bool_t is_unreg; + pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; + pjsip_tx_data *tdata; + pj_bool_t is_unreg; - /* reset current op */ - is_unreg = (regc->current_op == REGC_UNREGISTERING); - regc->current_op = REGC_IDLE; + /* reset current op */ + is_unreg = (regc->current_op == REGC_UNREGISTERING); + regc->current_op = REGC_IDLE; if (update_contact) { pjsip_msg *msg; @@ -1198,220 +1197,220 @@ static void regc_tsx_callback(void *token, pjsip_event *event) /* Add Contact headers. */ chdr = regc->contact_hdr_list.next; while (chdr != ®c->contact_hdr_list) { - pj_list_insert_before(ins_hdr, (pjsip_hdr*) + pj_list_insert_before(ins_hdr, (pjsip_hdr*) pjsip_hdr_clone(tsx->last_tx->pool, chdr)); - chdr = chdr->next; + chdr = chdr->next; } /* Also add bindings which are to be removed */ while (!pj_list_empty(®c->removed_contact_hdr_list)) { - chdr = regc->removed_contact_hdr_list.next; - pj_list_insert_before(ins_hdr, (pjsip_hdr*) + chdr = regc->removed_contact_hdr_list.next; + pj_list_insert_before(ins_hdr, (pjsip_hdr*) pjsip_hdr_clone(tsx->last_tx->pool, chdr)); - pj_list_erase(chdr); + pj_list_erase(chdr); } } status = pjsip_auth_clt_reinit_req( ®c->auth_sess, - rdata, - tsx->last_tx, - &tdata); - - if (status == PJ_SUCCESS) { - /* Need to unlock the regc temporarily while sending the message - * to prevent deadlock (see ticket #2260 and #1247). - * It should be safe to do this since the regc's refcount has been - * incremented. - */ - pj_lock_release(regc->lock); - status = pjsip_regc_send(regc, tdata); - pj_lock_acquire(regc->lock); - } - - if (status != PJ_SUCCESS) { - - /* Only call callback if application is still interested - * in it. - */ - if (regc->_delete_flag == 0) { - /* Should be safe to release the lock temporarily. - * We do this to avoid deadlock. - */ - pj_lock_release(regc->lock); - call_callback(regc, status, tsx->status_code, - &rdata->msg_info.msg->line.status.reason, - rdata, NOEXP, 0, NULL, is_unreg); - pj_lock_acquire(regc->lock); - } - } + rdata, + tsx->last_tx, + &tdata); + + if (status == PJ_SUCCESS) { + /* Need to unlock the regc temporarily while sending the message + * to prevent deadlock (see ticket #2260 and #1247). + * It should be safe to do this since the regc's refcount has been + * incremented. + */ + pj_lock_release(regc->lock); + status = pjsip_regc_send(regc, tdata); + pj_lock_acquire(regc->lock); + } + + if (status != PJ_SUCCESS) { + + /* Only call callback if application is still interested + * in it. + */ + if (regc->_delete_flag == 0) { + /* Should be safe to release the lock temporarily. + * We do this to avoid deadlock. + */ + pj_lock_release(regc->lock); + call_callback(regc, status, tsx->status_code, + &rdata->msg_info.msg->line.status.reason, + rdata, NOEXP, 0, NULL, is_unreg); + pj_lock_acquire(regc->lock); + } + } } else if (regc->_delete_flag) { - /* User has called pjsip_regc_destroy(), so don't call callback. - * This regc will be destroyed later in this function. - */ + /* User has called pjsip_regc_destroy(), so don't call callback. + * This regc will be destroyed later in this function. + */ - /* Just reset current op */ - regc->current_op = REGC_IDLE; + /* Just reset current op */ + regc->current_op = REGC_IDLE; } else if (tsx->status_code == PJSIP_SC_INTERVAL_TOO_BRIEF && - regc->current_op == REGC_REGISTERING) + regc->current_op == REGC_REGISTERING) { - /* Handle 423 response automatically: - * - set requested expiration to Min-Expires header, ONLY IF - * the original request is a registration (as opposed to - * unregistration) and the requested expiration was indeed - * lower than Min-Expires) - * - resend the request - */ - pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; - pjsip_min_expires_hdr *me_hdr; - pjsip_tx_data *tdata; - pj_uint32_t min_exp; - - /* reset current op */ - regc->current_op = REGC_IDLE; - - /* Update requested expiration */ - me_hdr = (pjsip_min_expires_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, - PJSIP_H_MIN_EXPIRES, NULL); - if (me_hdr) { - min_exp = me_hdr->ivalue; - } else { - /* Broken server, Min-Expires doesn't exist. - * Just guestimate then, BUT ONLY if if this is the - * first time we received such response. - */ - enum { - /* Note: changing this value would require changing couple of - * Python test scripts. - */ - UNSPECIFIED_MIN_EXPIRES = 3601 - }; - if (!regc->expires_hdr || - regc->expires_hdr->ivalue != UNSPECIFIED_MIN_EXPIRES) - { - min_exp = UNSPECIFIED_MIN_EXPIRES; - } else { - handled = PJ_FALSE; - PJ_LOG(4,(THIS_FILE, "Registration failed: 423 response " - "without Min-Expires header is invalid")); - goto handle_err; - } - } - - if (regc->expires_hdr && regc->expires_hdr->ivalue >= min_exp) { - /* But we already send with greater expiration time, why does - * the server send us with 423? Oh well, just fail the request. - */ - handled = PJ_FALSE; - PJ_LOG(4,(THIS_FILE, "Registration failed: invalid " - "Min-Expires header value in response")); - goto handle_err; - } - - set_expires(regc, min_exp); - - status = pjsip_regc_register(regc, regc->auto_reg, &tdata); - if (status == PJ_SUCCESS) { - /* Need to unlock the regc temporarily while sending the message - * to prevent deadlock (see ticket #2260 and #1247). - * It should be safe to do this since the regc's refcount has been - * incremented. - */ - pj_lock_release(regc->lock); - status = pjsip_regc_send(regc, tdata); - pj_lock_acquire(regc->lock); - } - - if (status != PJ_SUCCESS) { - /* Only call callback if application is still interested - * in it. - */ - if (!regc->_delete_flag) { - /* Should be safe to release the lock temporarily. - * We do this to avoid deadlock. - */ - pj_lock_release(regc->lock); - call_callback(regc, status, tsx->status_code, - &rdata->msg_info.msg->line.status.reason, - rdata, NOEXP, 0, NULL, PJ_FALSE); - pj_lock_acquire(regc->lock); - } - } + /* Handle 423 response automatically: + * - set requested expiration to Min-Expires header, ONLY IF + * the original request is a registration (as opposed to + * unregistration) and the requested expiration was indeed + * lower than Min-Expires) + * - resend the request + */ + pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; + pjsip_min_expires_hdr *me_hdr; + pjsip_tx_data *tdata; + pj_uint32_t min_exp; + + /* reset current op */ + regc->current_op = REGC_IDLE; + + /* Update requested expiration */ + me_hdr = (pjsip_min_expires_hdr*) + pjsip_msg_find_hdr(rdata->msg_info.msg, + PJSIP_H_MIN_EXPIRES, NULL); + if (me_hdr) { + min_exp = me_hdr->ivalue; + } else { + /* Broken server, Min-Expires doesn't exist. + * Just guestimate then, BUT ONLY if if this is the + * first time we received such response. + */ + enum { + /* Note: changing this value would require changing couple of + * Python test scripts. + */ + UNSPECIFIED_MIN_EXPIRES = 3601 + }; + if (!regc->expires_hdr || + regc->expires_hdr->ivalue != UNSPECIFIED_MIN_EXPIRES) + { + min_exp = UNSPECIFIED_MIN_EXPIRES; + } else { + handled = PJ_FALSE; + PJ_LOG(4,(THIS_FILE, "Registration failed: 423 response " + "without Min-Expires header is invalid")); + goto handle_err; + } + } + + if (regc->expires_hdr && regc->expires_hdr->ivalue >= min_exp) { + /* But we already send with greater expiration time, why does + * the server send us with 423? Oh well, just fail the request. + */ + handled = PJ_FALSE; + PJ_LOG(4,(THIS_FILE, "Registration failed: invalid " + "Min-Expires header value in response")); + goto handle_err; + } + + set_expires(regc, min_exp); + + status = pjsip_regc_register(regc, regc->auto_reg, &tdata); + if (status == PJ_SUCCESS) { + /* Need to unlock the regc temporarily while sending the message + * to prevent deadlock (see ticket #2260 and #1247). + * It should be safe to do this since the regc's refcount has been + * incremented. + */ + pj_lock_release(regc->lock); + status = pjsip_regc_send(regc, tdata); + pj_lock_acquire(regc->lock); + } + + if (status != PJ_SUCCESS) { + /* Only call callback if application is still interested + * in it. + */ + if (!regc->_delete_flag) { + /* Should be safe to release the lock temporarily. + * We do this to avoid deadlock. + */ + pj_lock_release(regc->lock); + call_callback(regc, status, tsx->status_code, + &rdata->msg_info.msg->line.status.reason, + rdata, NOEXP, 0, NULL, PJ_FALSE); + pj_lock_acquire(regc->lock); + } + } } else { - handled = PJ_FALSE; + handled = PJ_FALSE; } handle_err: if (!handled) { - pjsip_rx_data *rdata; - pj_uint32_t expiration = NOEXP; - unsigned contact_cnt = 0; - pjsip_contact_hdr *contact[PJSIP_REGC_MAX_CONTACT]; - pj_bool_t is_unreg; + pjsip_rx_data *rdata; + pj_uint32_t expiration = NOEXP; + unsigned contact_cnt = 0; + pjsip_contact_hdr *contact[PJSIP_REGC_MAX_CONTACT]; + pj_bool_t is_unreg; - if (tsx->status_code/100 == 2) { + if (tsx->status_code/100 == 2) { - rdata = event->body.tsx_state.src.rdata; + rdata = event->body.tsx_state.src.rdata; - /* Calculate expiration */ - expiration = calculate_response_expiration(regc, rdata, - &contact_cnt, - PJSIP_REGC_MAX_CONTACT, - contact); + /* Calculate expiration */ + expiration = calculate_response_expiration(regc, rdata, + &contact_cnt, + PJSIP_REGC_MAX_CONTACT, + contact); #if PJSIP_REGISTER_ALLOW_EXP_REFRESH - if (expiration == 0 && regc->current_op != REGC_UNREGISTERING) { - /* Response contain expires contact param 0, allow client to - * continue refresh registration. - * Refer to: https://github.com/pjsip/pjproject/pull/2809 - */ - const pjsip_msg *msg = rdata->msg_info.msg; - const pjsip_expires_hdr *expires; - expires = (const pjsip_expires_hdr*) pjsip_msg_find_hdr(msg, - PJSIP_H_EXPIRES, NULL); - - if (expires) { - expiration = expires->ivalue; - } else if (regc->expires_hdr && regc->expires_hdr->ivalue) { - expiration = regc->expires_hdr->ivalue; - } else { - expiration = 3600; - } - PJ_LOG(4, (THIS_FILE, "Modify response's expiration from 0 " - "to %d", expiration)); - } + if (expiration == 0 && regc->current_op != REGC_UNREGISTERING) { + /* Response contain expires contact param 0, allow client to + * continue refresh registration. + * Refer to: https://github.com/pjsip/pjproject/pull/2809 + */ + const pjsip_msg *msg = rdata->msg_info.msg; + const pjsip_expires_hdr *expires; + expires = (const pjsip_expires_hdr*) pjsip_msg_find_hdr(msg, + PJSIP_H_EXPIRES, NULL); + + if (expires) { + expiration = expires->ivalue; + } else if (regc->expires_hdr && regc->expires_hdr->ivalue) { + expiration = regc->expires_hdr->ivalue; + } else { + expiration = 3600; + } + PJ_LOG(4, (THIS_FILE, "Modify response's expiration from 0 " + "to %d", expiration)); + } #endif - /* Schedule next registration */ + /* Schedule next registration */ schedule_registration(regc, expiration); - } else { - rdata = (event->body.tsx_state.type==PJSIP_EVENT_RX_MSG) ? - event->body.tsx_state.src.rdata : NULL; - } - - /* Update registration */ - // if (expiration==NOEXP) expiration=-1; - regc->expires = expiration; - - /* Mark operation as complete */ - is_unreg = (regc->current_op == REGC_UNREGISTERING); - regc->current_op = REGC_IDLE; - - /* Call callback. */ - /* Should be safe to release the lock temporarily. - * We do this to avoid deadlock. - */ - pj_lock_release(regc->lock); - call_callback(regc, PJ_SUCCESS, tsx->status_code, - (rdata ? &rdata->msg_info.msg->line.status.reason - : &tsx->status_text), - rdata, expiration, - contact_cnt, contact, is_unreg); - pj_lock_acquire(regc->lock); + } else { + rdata = (event->body.tsx_state.type==PJSIP_EVENT_RX_MSG) ? + event->body.tsx_state.src.rdata : NULL; + } + + /* Update registration */ + // if (expiration==NOEXP) expiration=-1; + regc->expires = expiration; + + /* Mark operation as complete */ + is_unreg = (regc->current_op == REGC_UNREGISTERING); + regc->current_op = REGC_IDLE; + + /* Call callback. */ + /* Should be safe to release the lock temporarily. + * We do this to avoid deadlock. + */ + pj_lock_release(regc->lock); + call_callback(regc, PJ_SUCCESS, tsx->status_code, + (rdata ? &rdata->msg_info.msg->line.status.reason + : &tsx->status_text), + rdata, expiration, + contact_cnt, contact, is_unreg); + pj_lock_acquire(regc->lock); } pj_lock_release(regc->lock); @@ -1432,12 +1431,12 @@ PJ_DEF(pj_status_t) pjsip_regc_send(pjsip_regc *regc, pjsip_tx_data *tdata) /* Make sure we don't have pending transaction. */ if (regc->has_tsx) { - PJ_LOG(4,(THIS_FILE, "Unable to send request, regc has another " - "transaction pending")); - pjsip_tx_data_dec_ref( tdata ); - pj_lock_release(regc->lock); - pj_atomic_dec(regc->busy_ctr); - return PJSIP_EBUSY; + PJ_LOG(4,(THIS_FILE, "Unable to send request, regc has another " + "transaction pending")); + pjsip_tx_data_dec_ref( tdata ); + pj_lock_release(regc->lock); + pj_atomic_dec(regc->busy_ctr); + return PJSIP_EBUSY; } /* Just regc->has_tsx check above should be enough. This assertion check @@ -1453,12 +1452,12 @@ PJ_DEF(pj_status_t) pjsip_regc_send(pjsip_regc *regc, pjsip_tx_data *tdata) /* Increment CSeq */ cseq = ++regc->cseq_hdr->cseq; cseq_hdr = (pjsip_cseq_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL); + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL); cseq_hdr->cseq = cseq; /* Find Expires header */ expires_hdr = (pjsip_expires_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_EXPIRES, NULL); + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_EXPIRES, NULL); /* Bind to transport selector */ pjsip_tx_data_set_transport(tdata, ®c->tp_sel); @@ -1467,12 +1466,12 @@ PJ_DEF(pj_status_t) pjsip_regc_send(pjsip_regc *regc, pjsip_tx_data *tdata) /* Set current operation based on the value of Expires header */ if (expires_hdr && expires_hdr->ivalue==0) - regc->current_op = REGC_UNREGISTERING; + regc->current_op = REGC_UNREGISTERING; else - regc->current_op = REGC_REGISTERING; + regc->current_op = REGC_REGISTERING; if (expires_hdr && expires_hdr->ivalue) - regc->expires_requested = expires_hdr->ivalue; + regc->expires_requested = expires_hdr->ivalue; /* Prevent deletion of tdata, e.g: when something wrong in sending, * we need tdata to retrieve the transport. @@ -1494,37 +1493,37 @@ PJ_DEF(pj_status_t) pjsip_regc_send(pjsip_regc *regc, pjsip_tx_data *tdata) /* Now send the message */ status = pjsip_endpt_send_request(regc->endpt, tdata, REGC_TSX_TIMEOUT, - regc, ®c_tsx_callback); + regc, ®c_tsx_callback); /* Reacquire the lock */ pj_lock_acquire(regc->lock); if (status!=PJ_SUCCESS) { - /* On failure, regc_tsx_callback() may not be called, so we need - * to reset regc->has_tsx here (see also ticket #1936). - * But note that we are releasing the lock when sending the request - * above, so there can be a race with another registration send. - */ - if (cseq == regc->cseq_hdr->cseq) { - regc->has_tsx = PJ_FALSE; - } - - PJ_PERROR(4,(THIS_FILE, status, "Error sending request")); + /* On failure, regc_tsx_callback() may not be called, so we need + * to reset regc->has_tsx here (see also ticket #1936). + * But note that we are releasing the lock when sending the request + * above, so there can be a race with another registration send. + */ + if (cseq == regc->cseq_hdr->cseq) { + regc->has_tsx = PJ_FALSE; + } + + PJ_PERROR(4,(THIS_FILE, status, "Error sending request")); } /* Get last transport used and add reference to it */ if (tdata->tp_info.transport != regc->last_transport && - status==PJ_SUCCESS) + status==PJ_SUCCESS) { - if (regc->last_transport) { - pjsip_transport_dec_ref(regc->last_transport); - regc->last_transport = NULL; - } - - if (tdata->tp_info.transport) { - regc->last_transport = tdata->tp_info.transport; - pjsip_transport_add_ref(regc->last_transport); - } + if (regc->last_transport) { + pjsip_transport_dec_ref(regc->last_transport); + regc->last_transport = NULL; + } + + if (tdata->tp_info.transport) { + regc->last_transport = tdata->tp_info.transport; + pjsip_transport_add_ref(regc->last_transport); + } } /* Release tdata */ diff --git a/pjsip/src/pjsip-ua/sip_replaces.c b/pjsip/src/pjsip-ua/sip_replaces.c index b117dd327f..d3aa2ff236 100644 --- a/pjsip/src/pjsip-ua/sip_replaces.c +++ b/pjsip/src/pjsip-ua/sip_replaces.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,18 +30,18 @@ #include #include -#define THIS_FILE "sip_replaces.c" +#define THIS_FILE "sip_replaces.c" /* * Replaces header vptr. */ static int replaces_hdr_print( pjsip_replaces_hdr *hdr, - char *buf, pj_size_t size); + char *buf, pj_size_t size); static pjsip_replaces_hdr* replaces_hdr_clone( pj_pool_t *pool, - const pjsip_replaces_hdr *hdr); + const pjsip_replaces_hdr *hdr); static pjsip_replaces_hdr* replaces_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_replaces_hdr*); + const pjsip_replaces_hdr*); static pjsip_hdr_vptr replaces_hdr_vptr = { @@ -68,7 +67,7 @@ PJ_DEF(pjsip_replaces_hdr*) pjsip_replaces_hdr_create(pj_pool_t *pool) } static int replaces_hdr_print( pjsip_replaces_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { char *p = buf; char *endbuf = buf+size; @@ -84,22 +83,22 @@ static int replaces_hdr_print( pjsip_replaces_hdr *hdr, copy_advance_pair(p, ";from-tag=", 10, hdr->from_tag); if (hdr->early_only) { - const pj_str_t str_early_only = { ";early-only", 11 }; - copy_advance(p, str_early_only); + const pj_str_t str_early_only = { ";early-only", 11 }; + copy_advance(p, str_early_only); } printed = pjsip_param_print_on(&hdr->other_param, p, endbuf-p, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, ';'); + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ';'); if (printed < 0) - return (int)printed; + return (int)printed; p += printed; return (int)(p - buf); } static pjsip_replaces_hdr* replaces_hdr_clone( pj_pool_t *pool, - const pjsip_replaces_hdr *rhs) + const pjsip_replaces_hdr *rhs) { pjsip_replaces_hdr *hdr = pjsip_replaces_hdr_create(pool); pj_strdup(pool, &hdr->call_id, &rhs->call_id); @@ -112,7 +111,7 @@ static pjsip_replaces_hdr* replaces_hdr_clone( pj_pool_t *pool, static pjsip_replaces_hdr* replaces_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_replaces_hdr *rhs ) + const pjsip_replaces_hdr *rhs ) { pjsip_replaces_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_replaces_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -138,23 +137,23 @@ static pjsip_hdr *parse_hdr_replaces(pjsip_parse_ctx *ctx) pj_scan_get_until_ch(ctx->scanner, ';', &hdr->call_id); while (*ctx->scanner->curptr == ';') { - pj_str_t pname, pvalue; - - pj_scan_get_char(ctx->scanner); - pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); - - if (pj_stricmp(&pname, &to_tag)==0) { - hdr->to_tag = pvalue; - } else if (pj_stricmp(&pname, &from_tag)==0) { - hdr->from_tag = pvalue; - } else if (pj_stricmp(&pname, &early_only_tag)==0) { - hdr->early_only = PJ_TRUE; - } else { - pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); - param->name = pname; - param->value = pvalue; - pj_list_push_back(&hdr->other_param, param); - } + pj_str_t pname, pvalue; + + pj_scan_get_char(ctx->scanner); + pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); + + if (pj_stricmp(&pname, &to_tag)==0) { + hdr->to_tag = pvalue; + } else if (pj_stricmp(&pname, &from_tag)==0) { + hdr->from_tag = pvalue; + } else if (pj_stricmp(&pname, &early_only_tag)==0) { + hdr->early_only = PJ_TRUE; + } else { + pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); + param->name = pname; + param->value = pvalue; + pj_list_push_back(&hdr->other_param, param); + } } pjsip_parse_end_hdr_imp( ctx->scanner ); return (pjsip_hdr*)hdr; @@ -180,27 +179,27 @@ PJ_DEF(pj_status_t) pjsip_replaces_init_module(pjsip_endpoint *endpt) the_endpt = endpt; if (is_initialized) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Register Replaces header parser */ status = pjsip_register_hdr_parser( "Replaces", NULL, - &parse_hdr_replaces); + &parse_hdr_replaces); if (status != PJ_SUCCESS) - return status; + return status; /* Register "replaces" capability */ status = pjsip_endpt_add_capability(endpt, NULL, PJSIP_H_SUPPORTED, NULL, - 1, &STR_REPLACES); + 1, &STR_REPLACES); /* Register deinit module to be executed when PJLIB shutdown */ if (pjsip_endpt_atexit(endpt, &pjsip_replaces_deinit_module) != PJ_SUCCESS) { - /* Failure to register this function may cause this module won't - * work properly when the stack is restarted (without quitting - * application). - */ - pj_assert(!"Failed to register Replaces deinit."); - PJ_LOG(1, (THIS_FILE, "Failed to register Replaces deinit.")); + /* Failure to register this function may cause this module won't + * work properly when the stack is restarted (without quitting + * application). + */ + pj_assert(!"Failed to register Replaces deinit."); + PJ_LOG(1, (THIS_FILE, "Failed to register Replaces deinit.")); } is_initialized = PJ_TRUE; @@ -212,9 +211,9 @@ PJ_DEF(pj_status_t) pjsip_replaces_init_module(pjsip_endpoint *endpt) * Verify that incoming request with Replaces header can be processed. */ PJ_DEF(pj_status_t) pjsip_replaces_verify_request( pjsip_rx_data *rdata, - pjsip_dialog **p_dlg, - pj_bool_t lock_dlg, - pjsip_tx_data **p_tdata) + pjsip_dialog **p_dlg, + pj_bool_t lock_dlg, + pjsip_tx_data **p_tdata) { const pj_str_t STR_REPLACES = { "Replaces", 8 }; pjsip_replaces_hdr *rep_hdr; @@ -239,11 +238,11 @@ PJ_DEF(pj_status_t) pjsip_replaces_verify_request( pjsip_rx_data *rdata, /* Find Replaces header */ rep_hdr = (pjsip_replaces_hdr*) - pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_REPLACES, - NULL); + pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_REPLACES, + NULL); if (!rep_hdr) { - /* No Replaces header. No further processing is necessary. */ - return PJ_SUCCESS; + /* No Replaces header. No further processing is necessary. */ + return PJ_SUCCESS; } @@ -251,25 +250,25 @@ PJ_DEF(pj_status_t) pjsip_replaces_verify_request( pjsip_rx_data *rdata, * if not. */ if (pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_REPLACES, - rep_hdr->next)) { - code = PJSIP_SC_BAD_REQUEST; - warn_text = "Found multiple Replaces headers"; - goto on_return; + rep_hdr->next)) { + code = PJSIP_SC_BAD_REQUEST; + warn_text = "Found multiple Replaces headers"; + goto on_return; } /* Find the dialog identified by Replaces header (and always lock the * dialog no matter what application wants). */ dlg = pjsip_ua_find_dialog(&rep_hdr->call_id, &rep_hdr->to_tag, - &rep_hdr->from_tag, PJ_TRUE); + &rep_hdr->from_tag, PJ_TRUE); /* Respond with 481 "Call/Transaction Does Not Exist" response if * no dialog is found. */ if (dlg == NULL) { - code = PJSIP_SC_CALL_TSX_DOES_NOT_EXIST; - warn_text = "No dialog found for Replaces request"; - goto on_return; + code = PJSIP_SC_CALL_TSX_DOES_NOT_EXIST; + warn_text = "No dialog found for Replaces request"; + goto on_return; } /* Get the invite session within the dialog */ @@ -277,18 +276,18 @@ PJ_DEF(pj_status_t) pjsip_replaces_verify_request( pjsip_rx_data *rdata, /* Return 481 if no invite session is present. */ if (inv == NULL) { - code = PJSIP_SC_CALL_TSX_DOES_NOT_EXIST; - warn_text = "No INVITE session found for Replaces request"; - goto on_return; + code = PJSIP_SC_CALL_TSX_DOES_NOT_EXIST; + warn_text = "No INVITE session found for Replaces request"; + goto on_return; } /* Return 603 Declined response if invite session has already * terminated */ if (inv->state >= PJSIP_INV_STATE_DISCONNECTED) { - code = PJSIP_SC_DECLINE; - warn_text = "INVITE session already terminated"; - goto on_return; + code = PJSIP_SC_DECLINE; + warn_text = "INVITE session already terminated"; + goto on_return; } /* If "early-only" flag is present, check that the invite session @@ -296,9 +295,9 @@ PJ_DEF(pj_status_t) pjsip_replaces_verify_request( pjsip_rx_data *rdata, * return 486 "Busy Here" response. */ if (rep_hdr->early_only && inv->state >= PJSIP_INV_STATE_CONNECTING) { - code = PJSIP_SC_BUSY_HERE; - warn_text = "INVITE session already established"; - goto on_return; + code = PJSIP_SC_BUSY_HERE; + warn_text = "INVITE session already established"; + goto on_return; } /* If the Replaces header field matches an early dialog that was not @@ -307,17 +306,17 @@ PJ_DEF(pj_status_t) pjsip_replaces_verify_request( pjsip_rx_data *rdata, */ if (inv->state <= PJSIP_INV_STATE_EARLY && inv->role != PJSIP_ROLE_UAC) { - /* Really return 481 only if call haven't reached early state or - * accept-replace-in-early-state (ticket #1587) is not allowed. - */ - if (inv->state != PJSIP_INV_STATE_EARLY || - pjsip_cfg()->endpt.accept_replace_in_early_state == PJ_FALSE) - { - code = PJSIP_SC_CALL_TSX_DOES_NOT_EXIST; - warn_text = "Found early INVITE session but not initiated by " - "this UA"; - goto on_return; - } + /* Really return 481 only if call haven't reached early state or + * accept-replace-in-early-state (ticket #1587) is not allowed. + */ + if (inv->state != PJSIP_INV_STATE_EARLY || + pjsip_cfg()->endpt.accept_replace_in_early_state == PJ_FALSE) + { + code = PJSIP_SC_CALL_TSX_DOES_NOT_EXIST; + warn_text = "Found early INVITE session but not initiated by " + "this UA"; + goto on_return; + } } @@ -332,58 +331,58 @@ PJ_DEF(pj_status_t) pjsip_replaces_verify_request( pjsip_rx_data *rdata, /* Create response if necessary */ if (code != 200) { - /* If we have dialog we must unlock it */ - if (dlg) - pjsip_dlg_dec_lock(dlg); + /* If we have dialog we must unlock it */ + if (dlg) + pjsip_dlg_dec_lock(dlg); - /* Create response */ - if (p_tdata) { - pjsip_tx_data *tdata; - const pjsip_hdr *h; + /* Create response */ + if (p_tdata) { + pjsip_tx_data *tdata; + const pjsip_hdr *h; - status = pjsip_endpt_create_response(the_endpt, rdata, code, - NULL, &tdata); + status = pjsip_endpt_create_response(the_endpt, rdata, code, + NULL, &tdata); - if (status != PJ_SUCCESS) - return status; + if (status != PJ_SUCCESS) + return status; - /* Add response headers. */ - h = res_hdr_list.next; - while (h != &res_hdr_list) { - pjsip_hdr *cloned; + /* Add response headers. */ + h = res_hdr_list.next; + while (h != &res_hdr_list) { + pjsip_hdr *cloned; - cloned = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, h); - PJ_ASSERT_RETURN(cloned, PJ_ENOMEM); + cloned = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, h); + PJ_ASSERT_RETURN(cloned, PJ_ENOMEM); - pjsip_msg_add_hdr(tdata->msg, cloned); + pjsip_msg_add_hdr(tdata->msg, cloned); - h = h->next; - } + h = h->next; + } - /* Add warn text, if any */ - if (warn_text) { - pjsip_warning_hdr *warn_hdr; - pj_str_t warn_value = pj_str((char*)warn_text); + /* Add warn text, if any */ + if (warn_text) { + pjsip_warning_hdr *warn_hdr; + pj_str_t warn_value = pj_str((char*)warn_text); - warn_hdr=pjsip_warning_hdr_create(tdata->pool, 399, - pjsip_endpt_name(the_endpt), - &warn_value); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)warn_hdr); - } + warn_hdr=pjsip_warning_hdr_create(tdata->pool, 399, + pjsip_endpt_name(the_endpt), + &warn_value); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)warn_hdr); + } - *p_tdata = tdata; - } + *p_tdata = tdata; + } - /* Can not return PJ_SUCCESS when response message is produced. - * Ref: PROTOS test ~#2490 - */ - if (status == PJ_SUCCESS) - status = PJSIP_ERRNO_FROM_SIP_STATUS(code); + /* Can not return PJ_SUCCESS when response message is produced. + * Ref: PROTOS test ~#2490 + */ + if (status == PJ_SUCCESS) + status = PJSIP_ERRNO_FROM_SIP_STATUS(code); } else { - /* If application doesn't want to lock the dialog, unlock it */ - if (!lock_dlg) - pjsip_dlg_dec_lock(dlg); + /* If application doesn't want to lock the dialog, unlock it */ + if (!lock_dlg) + pjsip_dlg_dec_lock(dlg); } return status; diff --git a/pjsip/src/pjsip-ua/sip_timer.c b/pjsip/src/pjsip-ua/sip_timer.c index 9d54de552f..f603e8235a 100644 --- a/pjsip/src/pjsip-ua/sip_timer.c +++ b/pjsip/src/pjsip-ua/sip_timer.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * @@ -26,21 +25,21 @@ #include #include -#define THIS_FILE "sip_timer.c" +#define THIS_FILE "sip_timer.c" /* Constant of Session Timers */ -#define ABS_MIN_SE 90 /* Absolute Min-SE, in seconds */ -#define REFRESHER_EXPIRE_TIMER_ID 2 /* Refresher expire timer id */ +#define ABS_MIN_SE 90 /* Absolute Min-SE, in seconds */ +#define REFRESHER_EXPIRE_TIMER_ID 2 /* Refresher expire timer id */ /* String definitions */ -static const pj_str_t STR_SE = {"Session-Expires", 15}; -static const pj_str_t STR_SHORT_SE = {"x", 1}; -static const pj_str_t STR_MIN_SE = {"Min-SE", 6}; -static const pj_str_t STR_REFRESHER = {"refresher", 9}; -static const pj_str_t STR_UAC = {"uac", 3}; -static const pj_str_t STR_UAS = {"uas", 3}; -static const pj_str_t STR_TIMER = {"timer", 5}; +static const pj_str_t STR_SE = {"Session-Expires", 15}; +static const pj_str_t STR_SHORT_SE = {"x", 1}; +static const pj_str_t STR_MIN_SE = {"Min-SE", 6}; +static const pj_str_t STR_REFRESHER = {"refresher", 9}; +static const pj_str_t STR_UAC = {"uac", 3}; +static const pj_str_t STR_UAS = {"uas", 3}; +static const pj_str_t STR_TIMER = {"timer", 5}; /* Enumeration of refresher */ @@ -53,22 +52,22 @@ enum timer_refresher { /* Structure definition of Session Timers */ struct pjsip_timer { - pj_bool_t active; /**< Active/inactive flag */ - pjsip_timer_setting setting; /**< Session Timers setting */ - enum timer_refresher refresher; /**< Session refresher */ - pj_time_val last_refresh; /**< Timestamp of last - refresh */ - pj_timer_entry timer; /**< Timer entry */ - pj_bool_t use_update; /**< Use UPDATE method to - refresh the session */ - pj_bool_t with_sdp; /**< SDP in UPDATE? */ - pjsip_role_e role; /**< Role in last INVITE/ - UPDATE transaction. */ - void *refresh_tdata; /**< The tdata of refresh - request */ - pj_timer_entry expire_timer; /**< Timer entry for expire - refresher */ - pj_int32_t last_422_cseq; /**< Last 422 resp CSeq. */ + pj_bool_t active; /**< Active/inactive flag */ + pjsip_timer_setting setting; /**< Session Timers setting */ + enum timer_refresher refresher; /**< Session refresher */ + pj_time_val last_refresh; /**< Timestamp of last + refresh */ + pj_timer_entry timer; /**< Timer entry */ + pj_bool_t use_update; /**< Use UPDATE method to + refresh the session */ + pj_bool_t with_sdp; /**< SDP in UPDATE? */ + pjsip_role_e role; /**< Role in last INVITE/ + UPDATE transaction. */ + void *refresh_tdata; /**< The tdata of refresh + request */ + pj_timer_entry expire_timer; /**< Timer entry for expire + refresher */ + pj_int32_t last_422_cseq; /**< Last 422 resp CSeq. */ }; /* Local functions & vars */ @@ -80,12 +79,12 @@ const pjsip_method pjsip_update_method = { PJSIP_OTHER_METHOD, {"UPDATE", 6}}; * Session-Expires header vptr. */ static int se_hdr_print(pjsip_sess_expires_hdr *hdr, - char *buf, pj_size_t size); + char *buf, pj_size_t size); static pjsip_sess_expires_hdr* se_hdr_clone(pj_pool_t *pool, - const pjsip_sess_expires_hdr *hdr); + const pjsip_sess_expires_hdr *hdr); static pjsip_sess_expires_hdr* se_hdr_shallow_clone( - pj_pool_t *pool, - const pjsip_sess_expires_hdr* hdr); + pj_pool_t *pool, + const pjsip_sess_expires_hdr* hdr); static pjsip_hdr_vptr se_hdr_vptr = { @@ -98,12 +97,12 @@ static pjsip_hdr_vptr se_hdr_vptr = * Min-SE header vptr. */ static int min_se_hdr_print(pjsip_min_se_hdr *hdr, - char *buf, pj_size_t size); + char *buf, pj_size_t size); static pjsip_min_se_hdr* min_se_hdr_clone(pj_pool_t *pool, - const pjsip_min_se_hdr *hdr); + const pjsip_min_se_hdr *hdr); static pjsip_min_se_hdr* min_se_hdr_shallow_clone( - pj_pool_t *pool, - const pjsip_min_se_hdr* hdr); + pj_pool_t *pool, + const pjsip_min_se_hdr* hdr); static pjsip_hdr_vptr min_se_hdr_vptr = { @@ -116,18 +115,18 @@ static pjsip_hdr_vptr min_se_hdr_vptr = * Session-Expires header vptr. */ static int se_hdr_print(pjsip_sess_expires_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { char *p = buf; char *endbuf = buf+size; pj_ssize_t printed; const pjsip_parser_const_t *pc = pjsip_parser_const(); const pj_str_t *hname = pjsip_cfg()->endpt.use_compact_form? - &hdr->sname : &hdr->name; + &hdr->sname : &hdr->name; /* Print header name and value */ if ((endbuf - p) < (hname->slen + 16)) - return -1; + return -1; copy_advance(p, (*hname)); *p++ = ':'; @@ -139,28 +138,28 @@ static int se_hdr_print(pjsip_sess_expires_hdr *hdr, /* Print 'refresher' param */ if (hdr->refresher.slen) { - if ((endbuf - p) < (STR_REFRESHER.slen + 2 + hdr->refresher.slen)) - return -1; + if ((endbuf - p) < (STR_REFRESHER.slen + 2 + hdr->refresher.slen)) + return -1; - *p++ = ';'; - copy_advance(p, STR_REFRESHER); - *p++ = '='; - copy_advance(p, hdr->refresher); + *p++ = ';'; + copy_advance(p, STR_REFRESHER); + *p++ = '='; + copy_advance(p, hdr->refresher); } /* Print generic params */ printed = pjsip_param_print_on(&hdr->other_param, p, endbuf-p, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, ';'); + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ';'); if (printed < 0) - return (int)printed; + return (int)printed; p += printed; return (int)(p - buf); } static pjsip_sess_expires_hdr* se_hdr_clone(pj_pool_t *pool, - const pjsip_sess_expires_hdr *hsrc) + const pjsip_sess_expires_hdr *hsrc) { pjsip_sess_expires_hdr *hdr = pjsip_sess_expires_hdr_create(pool); hdr->sess_expires = hsrc->sess_expires; @@ -170,8 +169,8 @@ static pjsip_sess_expires_hdr* se_hdr_clone(pj_pool_t *pool, } static pjsip_sess_expires_hdr* se_hdr_shallow_clone( - pj_pool_t *pool, - const pjsip_sess_expires_hdr* hsrc) + pj_pool_t *pool, + const pjsip_sess_expires_hdr* hsrc) { pjsip_sess_expires_hdr *hdr = PJ_POOL_ALLOC_T(pool,pjsip_sess_expires_hdr); pj_memcpy(hdr, hsrc, sizeof(*hdr)); @@ -183,7 +182,7 @@ static pjsip_sess_expires_hdr* se_hdr_shallow_clone( * Min-SE header vptr. */ static int min_se_hdr_print(pjsip_min_se_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { char *p = buf; char *endbuf = buf+size; @@ -192,7 +191,7 @@ static int min_se_hdr_print(pjsip_min_se_hdr *hdr, /* Print header name and value */ if ((endbuf - p) < (hdr->name.slen + 16)) - return -1; + return -1; copy_advance(p, hdr->name); *p++ = ':'; @@ -203,17 +202,17 @@ static int min_se_hdr_print(pjsip_min_se_hdr *hdr, /* Print generic params */ printed = pjsip_param_print_on(&hdr->other_param, p, endbuf-p, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, ';'); + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ';'); if (printed < 0) - return (int)printed; + return (int)printed; p += printed; return (int)(p - buf); } static pjsip_min_se_hdr* min_se_hdr_clone(pj_pool_t *pool, - const pjsip_min_se_hdr *hsrc) + const pjsip_min_se_hdr *hsrc) { pjsip_min_se_hdr *hdr = pjsip_min_se_hdr_create(pool); hdr->min_se = hsrc->min_se; @@ -222,8 +221,8 @@ static pjsip_min_se_hdr* min_se_hdr_clone(pj_pool_t *pool, } static pjsip_min_se_hdr* min_se_hdr_shallow_clone( - pj_pool_t *pool, - const pjsip_min_se_hdr* hsrc) + pj_pool_t *pool, + const pjsip_min_se_hdr* hsrc) { pjsip_min_se_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_min_se_hdr); pj_memcpy(hdr, hsrc, sizeof(*hdr)); @@ -245,19 +244,19 @@ static pjsip_hdr *parse_hdr_se(pjsip_parse_ctx *ctx) hdr->sess_expires = pj_strtoul(&token); while (*ctx->scanner->curptr == ';') { - pj_str_t pname, pvalue; - - pj_scan_get_char(ctx->scanner); - pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); - - if (pj_stricmp(&pname, &STR_REFRESHER)==0) { - hdr->refresher = pvalue; - } else { - pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); - param->name = pname; - param->value = pvalue; - pj_list_push_back(&hdr->other_param, param); - } + pj_str_t pname, pvalue; + + pj_scan_get_char(ctx->scanner); + pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); + + if (pj_stricmp(&pname, &STR_REFRESHER)==0) { + hdr->refresher = pvalue; + } else { + pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); + param->name = pname; + param->value = pvalue; + pj_list_push_back(&hdr->other_param, param); + } } pjsip_parse_end_hdr_imp( ctx->scanner ); return (pjsip_hdr*)hdr; @@ -276,15 +275,15 @@ static pjsip_hdr *parse_hdr_min_se(pjsip_parse_ctx *ctx) hdr->min_se = pj_strtoul(&token); while (*ctx->scanner->curptr == ';') { - pj_str_t pname, pvalue; - pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); + pj_str_t pname, pvalue; + pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); - pj_scan_get_char(ctx->scanner); - pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); + pj_scan_get_char(ctx->scanner); + pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); - param->name = pname; - param->value = pvalue; - pj_list_push_back(&hdr->other_param, param); + param->name = pname; + param->value = pvalue; + pj_list_push_back(&hdr->other_param, param); } pjsip_parse_end_hdr_imp( ctx->scanner ); return (pjsip_hdr*)hdr; @@ -295,30 +294,30 @@ static pjsip_hdr *parse_hdr_min_se(pjsip_parse_ctx *ctx) * can only be added to INVITE/UPDATE request and 422 response. */ static void add_timer_headers(pjsip_inv_session *inv, pjsip_tx_data *tdata, - pj_bool_t add_se, pj_bool_t add_min_se) + pj_bool_t add_se, pj_bool_t add_min_se) { pjsip_timer *timer = inv->timer; /* Add Session-Expires header */ if (add_se) { - pjsip_sess_expires_hdr *hdr; + pjsip_sess_expires_hdr *hdr; - hdr = pjsip_sess_expires_hdr_create(tdata->pool); - hdr->sess_expires = timer->setting.sess_expires; - if (timer->refresher != TR_UNKNOWN) - hdr->refresher = (timer->refresher == TR_UAC? STR_UAC : STR_UAS); + hdr = pjsip_sess_expires_hdr_create(tdata->pool); + hdr->sess_expires = timer->setting.sess_expires; + if (timer->refresher != TR_UNKNOWN) + hdr->refresher = (timer->refresher == TR_UAC? STR_UAC : STR_UAS); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) hdr); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) hdr); } /* Add Min-SE header */ if (add_min_se) { - pjsip_min_se_hdr *hdr; + pjsip_min_se_hdr *hdr; - hdr = pjsip_min_se_hdr_create(tdata->pool); - hdr->min_se = timer->setting.min_se; + hdr = pjsip_min_se_hdr_create(tdata->pool); + hdr->min_se = timer->setting.min_se; - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) hdr); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) hdr); } } @@ -344,8 +343,8 @@ static void timer_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry) /* Check our role */ as_refresher = - (inv->timer->refresher == TR_UAC && inv->timer->role == PJSIP_ROLE_UAC) || - (inv->timer->refresher == TR_UAS && inv->timer->role == PJSIP_ROLE_UAS); + (inv->timer->refresher == TR_UAC && inv->timer->role == PJSIP_ROLE_UAC) || + (inv->timer->refresher == TR_UAS && inv->timer->role == PJSIP_ROLE_UAS); entry_id = entry->id; pj_ansi_strncpy(obj_name, inv->pool->obj_name, PJ_MAX_OBJ_NAME); @@ -358,95 +357,95 @@ static void timer_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry) * - end session if there is no refresh request received. */ if (as_refresher && (entry_id != REFRESHER_EXPIRE_TIMER_ID)) { - pj_time_val now; + pj_time_val now; - /* As refresher, reshedule the refresh request on the following: - * - must not send re-INVITE if another INVITE or SDP negotiation - * is in progress. - * - must not send UPDATE with SDP if SDP negotiation is in progress - */ - pjmedia_sdp_neg_state neg_state = pjmedia_sdp_neg_get_state(inv->neg); + /* As refresher, reshedule the refresh request on the following: + * - must not send re-INVITE if another INVITE or SDP negotiation + * is in progress. + * - must not send UPDATE with SDP if SDP negotiation is in progress + */ + pjmedia_sdp_neg_state neg_state = pjmedia_sdp_neg_get_state(inv->neg); - inv->timer->timer.id = 0; + inv->timer->timer.id = 0; - if ( (!inv->timer->use_update && ( - inv->invite_tsx != NULL || - neg_state != PJMEDIA_SDP_NEG_STATE_DONE) + if ( (!inv->timer->use_update && ( + inv->invite_tsx != NULL || + neg_state != PJMEDIA_SDP_NEG_STATE_DONE) ) - || - (inv->timer->use_update && inv->timer->with_sdp && - neg_state != PJMEDIA_SDP_NEG_STATE_DONE - ) - ) - { - pj_time_val delay = {1, 0}; - - inv->timer->timer.id = 1; - pjsip_endpt_schedule_timer(inv->dlg->endpt, &inv->timer->timer, - &delay); - pjsip_dlg_dec_lock(inv->dlg); - - PJ_LOG(3, (obj_name, - "Reschedule refresh request after %d seconds as " - "there is another SDP negotiation in progress", - delay.sec)); - return; - } - - /* Refresher, refresh the session */ - if (inv->timer->use_update) { - const pjmedia_sdp_session *offer = NULL; - - if (inv->timer->with_sdp) { - pjmedia_sdp_neg_get_active_local(inv->neg, &offer); - } - status = pjsip_inv_update(inv, NULL, offer, &tdata); - } else { - /* Create re-INVITE without modifying session */ - pjsip_msg_body *body; - const pjmedia_sdp_session *offer = NULL; - - pj_assert(pjmedia_sdp_neg_get_state(inv->neg) == - PJMEDIA_SDP_NEG_STATE_DONE); - - status = pjsip_inv_invite(inv, &tdata); - if (status == PJ_SUCCESS) - status = pjmedia_sdp_neg_send_local_offer(inv->pool_prov, - inv->neg, &offer); - if (status == PJ_SUCCESS) - status = pjmedia_sdp_neg_get_neg_local(inv->neg, &offer); - if (status == PJ_SUCCESS) { - status = pjsip_create_sdp_body(tdata->pool, - (pjmedia_sdp_session*)offer, &body); - tdata->msg->body = body; - } - } - - pj_gettimeofday(&now); - PJ_LOG(4, (obj_name, - "Refreshing session after %ds (expiration period=%ds)", - (now.sec-inv->timer->last_refresh.sec), - inv->timer->setting.sess_expires)); + || + (inv->timer->use_update && inv->timer->with_sdp && + neg_state != PJMEDIA_SDP_NEG_STATE_DONE + ) + ) + { + pj_time_val delay = {1, 0}; + + inv->timer->timer.id = 1; + pjsip_endpt_schedule_timer(inv->dlg->endpt, &inv->timer->timer, + &delay); + pjsip_dlg_dec_lock(inv->dlg); + + PJ_LOG(3, (obj_name, + "Reschedule refresh request after %d seconds as " + "there is another SDP negotiation in progress", + delay.sec)); + return; + } + + /* Refresher, refresh the session */ + if (inv->timer->use_update) { + const pjmedia_sdp_session *offer = NULL; + + if (inv->timer->with_sdp) { + pjmedia_sdp_neg_get_active_local(inv->neg, &offer); + } + status = pjsip_inv_update(inv, NULL, offer, &tdata); + } else { + /* Create re-INVITE without modifying session */ + pjsip_msg_body *body; + const pjmedia_sdp_session *offer = NULL; + + pj_assert(pjmedia_sdp_neg_get_state(inv->neg) == + PJMEDIA_SDP_NEG_STATE_DONE); + + status = pjsip_inv_invite(inv, &tdata); + if (status == PJ_SUCCESS) + status = pjmedia_sdp_neg_send_local_offer(inv->pool_prov, + inv->neg, &offer); + if (status == PJ_SUCCESS) + status = pjmedia_sdp_neg_get_neg_local(inv->neg, &offer); + if (status == PJ_SUCCESS) { + status = pjsip_create_sdp_body(tdata->pool, + (pjmedia_sdp_session*)offer, &body); + tdata->msg->body = body; + } + } + + pj_gettimeofday(&now); + PJ_LOG(4, (obj_name, + "Refreshing session after %ds (expiration period=%ds)", + (now.sec-inv->timer->last_refresh.sec), + inv->timer->setting.sess_expires)); } else { - - pj_time_val now; - - if (as_refresher) - inv->timer->expire_timer.id = 0; - else - inv->timer->timer.id = 0; - - /* Terminate the session */ - status = pjsip_inv_end_session(inv, PJSIP_SC_REQUEST_TIMEOUT, - NULL, &tdata); - - pj_gettimeofday(&now); - PJ_LOG(3, (obj_name, - "No session %s received after %ds " - "(expiration period=%ds), stopping session now!", - (as_refresher?"refresh response":"refresh"), - (now.sec-inv->timer->last_refresh.sec), - inv->timer->setting.sess_expires)); + + pj_time_val now; + + if (as_refresher) + inv->timer->expire_timer.id = 0; + else + inv->timer->timer.id = 0; + + /* Terminate the session */ + status = pjsip_inv_end_session(inv, PJSIP_SC_REQUEST_TIMEOUT, + NULL, &tdata); + + pj_gettimeofday(&now); + PJ_LOG(3, (obj_name, + "No session %s received after %ds " + "(expiration period=%ds), stopping session now!", + (as_refresher?"refresh response":"refresh"), + (now.sec-inv->timer->last_refresh.sec), + inv->timer->setting.sess_expires)); } @@ -455,9 +454,9 @@ static void timer_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry) /* Send message, if any */ if (tdata && status == PJ_SUCCESS) { - inv->timer->refresh_tdata = tdata; + inv->timer->refresh_tdata = tdata; - status = pjsip_inv_send_msg(inv, tdata); + status = pjsip_inv_send_msg(inv, tdata); } /* @@ -467,10 +466,10 @@ static void timer_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry) /* Print error message, if any */ if (status != PJ_SUCCESS) { - PJ_PERROR(2, (obj_name, status, - "Error in %s session timer", - ((as_refresher && entry_id != REFRESHER_EXPIRE_TIMER_ID)? - "refreshing" : "terminating"))); + PJ_PERROR(2, (obj_name, status, + "Error in %s session timer", + ((as_refresher && entry_id != REFRESHER_EXPIRE_TIMER_ID)? + "refreshing" : "terminating"))); } } @@ -486,43 +485,43 @@ static void start_timer(pjsip_inv_session *inv) stop_timer(inv); inv->timer->use_update = - (pjsip_dlg_remote_has_cap(inv->dlg, PJSIP_H_ALLOW, NULL, - &UPDATE) == PJSIP_DIALOG_CAP_SUPPORTED); + (pjsip_dlg_remote_has_cap(inv->dlg, PJSIP_H_ALLOW, NULL, + &UPDATE) == PJSIP_DIALOG_CAP_SUPPORTED); if (!inv->timer->use_update) { - /* INVITE always needs SDP */ - inv->timer->with_sdp = PJ_TRUE; + /* INVITE always needs SDP */ + inv->timer->with_sdp = PJ_TRUE; } pj_timer_entry_init(&timer->timer, - 1, /* id */ - inv, /* user data */ - timer_cb); /* callback */ + 1, /* id */ + inv, /* user data */ + timer_cb); /* callback */ /* Set delay based on role, refresher or refreshee */ if ((timer->refresher == TR_UAC && inv->timer->role == PJSIP_ROLE_UAC) || - (timer->refresher == TR_UAS && inv->timer->role == PJSIP_ROLE_UAS)) + (timer->refresher == TR_UAS && inv->timer->role == PJSIP_ROLE_UAS)) { - /* Add refresher expire timer */ - pj_timer_entry_init(&timer->expire_timer, - REFRESHER_EXPIRE_TIMER_ID, /* id */ - inv, /* user data */ - timer_cb); /* callback */ - - delay.sec = timer->setting.sess_expires; - /* Schedule the timer */ - pjsip_endpt_schedule_timer(inv->dlg->endpt, &timer->expire_timer, - &delay); - - /* Next refresh, the delay is half of session expire */ - delay.sec = timer->setting.sess_expires / 2; + /* Add refresher expire timer */ + pj_timer_entry_init(&timer->expire_timer, + REFRESHER_EXPIRE_TIMER_ID, /* id */ + inv, /* user data */ + timer_cb); /* callback */ + + delay.sec = timer->setting.sess_expires; + /* Schedule the timer */ + pjsip_endpt_schedule_timer(inv->dlg->endpt, &timer->expire_timer, + &delay); + + /* Next refresh, the delay is half of session expire */ + delay.sec = timer->setting.sess_expires / 2; } else { - /* Send BYE if no refresh received until this timer fired, delay - * is the minimum of 32 seconds and one third of the session interval - * before session expiration. - */ - delay.sec = timer->setting.sess_expires - - timer->setting.sess_expires/3; - delay.sec = PJ_MAX((long)timer->setting.sess_expires-32, delay.sec); + /* Send BYE if no refresh received until this timer fired, delay + * is the minimum of 32 seconds and one third of the session interval + * before session expiration. + */ + delay.sec = timer->setting.sess_expires - + timer->setting.sess_expires/3; + delay.sec = PJ_MAX((long)timer->setting.sess_expires-32, delay.sec); } /* Schedule the timer */ @@ -536,13 +535,13 @@ static void start_timer(pjsip_inv_session *inv) static void stop_timer(pjsip_inv_session *inv) { if (inv->timer->timer.id != 0) { - pjsip_endpt_cancel_timer(inv->dlg->endpt, &inv->timer->timer); - inv->timer->timer.id = 0; + pjsip_endpt_cancel_timer(inv->dlg->endpt, &inv->timer->timer); + inv->timer->timer.id = 0; } if (inv->timer->expire_timer.id != 0) { - pjsip_endpt_cancel_timer(inv->dlg->endpt, &inv->timer->expire_timer); - inv->timer->expire_timer.id = 0; + pjsip_endpt_cancel_timer(inv->dlg->endpt, &inv->timer->expire_timer); + inv->timer->expire_timer.id = 0; } } @@ -564,34 +563,34 @@ PJ_DEF(pj_status_t) pjsip_timer_init_module(pjsip_endpoint *endpt) PJ_ASSERT_RETURN(endpt, PJ_EINVAL); if (is_initialized) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Register Session-Expires header parser */ status = pjsip_register_hdr_parser( STR_SE.ptr, STR_SHORT_SE.ptr, - &parse_hdr_se); + &parse_hdr_se); if (status != PJ_SUCCESS) - return status; + return status; /* Register Min-SE header parser */ status = pjsip_register_hdr_parser( STR_MIN_SE.ptr, NULL, - &parse_hdr_min_se); + &parse_hdr_min_se); if (status != PJ_SUCCESS) - return status; + return status; /* Register 'timer' capability to endpoint */ status = pjsip_endpt_add_capability(endpt, NULL, PJSIP_H_SUPPORTED, - NULL, 1, &STR_TIMER); + NULL, 1, &STR_TIMER); if (status != PJ_SUCCESS) - return status; + return status; /* Register deinit module to be executed when PJLIB shutdown */ if (pjsip_endpt_atexit(endpt, &pjsip_timer_deinit_module) != PJ_SUCCESS) { - /* Failure to register this function may cause this module won't - * work properly when the stack is restarted (without quitting - * application). - */ - pj_assert(!"Failed to register Session Timer deinit."); - PJ_LOG(1, (THIS_FILE, "Failed to register Session Timer deinit.")); + /* Failure to register this function may cause this module won't + * work properly when the stack is restarted (without quitting + * application). + */ + pj_assert(!"Failed to register Session Timer deinit."); + PJ_LOG(1, (THIS_FILE, "Failed to register Session Timer deinit.")); } is_initialized = PJ_TRUE; @@ -617,8 +616,8 @@ PJ_DEF(pj_status_t) pjsip_timer_setting_default(pjsip_timer_setting *setting) * Initialize Session Timers in an INVITE session. */ PJ_DEF(pj_status_t) pjsip_timer_init_session( - pjsip_inv_session *inv, - const pjsip_timer_setting *setting) + pjsip_inv_session *inv, + const pjsip_timer_setting *setting) { pjsip_timer_setting *s; @@ -627,22 +626,22 @@ PJ_DEF(pj_status_t) pjsip_timer_init_session( /* Allocate and/or reset Session Timers structure */ if (!inv->timer) - inv->timer = PJ_POOL_ZALLOC_T(inv->pool, pjsip_timer); + inv->timer = PJ_POOL_ZALLOC_T(inv->pool, pjsip_timer); else - pj_bzero(inv->timer, sizeof(pjsip_timer)); + pj_bzero(inv->timer, sizeof(pjsip_timer)); s = &inv->timer->setting; /* Init Session Timers setting */ if (setting) { - PJ_ASSERT_RETURN(setting->min_se >= ABS_MIN_SE, - PJ_ETOOSMALL); - PJ_ASSERT_RETURN(setting->sess_expires >= setting->min_se, - PJ_EINVAL); + PJ_ASSERT_RETURN(setting->min_se >= ABS_MIN_SE, + PJ_ETOOSMALL); + PJ_ASSERT_RETURN(setting->sess_expires >= setting->min_se, + PJ_EINVAL); - pj_memcpy(s, setting, sizeof(*s)); + pj_memcpy(s, setting, sizeof(*s)); } else { - pjsip_timer_setting_default(s); + pjsip_timer_setting_default(s); } return PJ_SUCCESS; @@ -653,10 +652,10 @@ PJ_DEF(pj_status_t) pjsip_timer_init_session( * Create Session-Expires header. */ PJ_DEF(pjsip_sess_expires_hdr*) pjsip_sess_expires_hdr_create( - pj_pool_t *pool) + pj_pool_t *pool) { pjsip_sess_expires_hdr *hdr = PJ_POOL_ZALLOC_T(pool, - pjsip_sess_expires_hdr); + pjsip_sess_expires_hdr); pj_assert(is_initialized); @@ -693,36 +692,36 @@ PJ_DEF(pjsip_min_se_hdr*) pjsip_min_se_hdr_create(pj_pool_t *pool) * refresh INVITE or UPDATE. */ PJ_DEF(pj_status_t) pjsip_timer_update_req(pjsip_inv_session *inv, - pjsip_tx_data *tdata) + pjsip_tx_data *tdata) { PJ_ASSERT_RETURN(inv && tdata, PJ_EINVAL); /* Check if Session Timers is supported */ if ((inv->options & PJSIP_INV_SUPPORT_TIMER) == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; pj_assert(is_initialized); /* Make sure Session Timers is initialized */ if (inv->timer == NULL) - pjsip_timer_init_session(inv, NULL); + pjsip_timer_init_session(inv, NULL); /* If refresher role (i.e: ours or peer) has been set/negotiated, * better to keep it. */ if (inv->timer->refresher != TR_UNKNOWN) { - pj_bool_t as_refresher; + pj_bool_t as_refresher; - /* Check our refresher role */ - as_refresher = - (inv->timer->refresher==TR_UAC && inv->timer->role==PJSIP_ROLE_UAC) || - (inv->timer->refresher==TR_UAS && inv->timer->role==PJSIP_ROLE_UAS); + /* Check our refresher role */ + as_refresher = + (inv->timer->refresher==TR_UAC && inv->timer->role==PJSIP_ROLE_UAC) || + (inv->timer->refresher==TR_UAS && inv->timer->role==PJSIP_ROLE_UAS); - /* Update transaction role */ - inv->timer->role = PJSIP_ROLE_UAC; + /* Update transaction role */ + inv->timer->role = PJSIP_ROLE_UAC; - /* Update refresher role */ - inv->timer->refresher = as_refresher? TR_UAC : TR_UAS; + /* Update refresher role */ + inv->timer->refresher = as_refresher? TR_UAC : TR_UAS; } /* Add Session Timers headers */ @@ -738,13 +737,13 @@ PJ_DEF(pj_status_t) pjsip_timer_update_req(pjsip_inv_session *inv, * - 2xx final response */ PJ_DEF(pj_status_t) pjsip_timer_process_resp(pjsip_inv_session *inv, - const pjsip_rx_data *rdata, - pjsip_status_code *st_code) + const pjsip_rx_data *rdata, + pjsip_status_code *st_code) { const pjsip_msg *msg; PJ_ASSERT_ON_FAIL(inv && rdata, - {if(st_code)*st_code=PJSIP_SC_INTERNAL_SERVER_ERROR;return PJ_EINVAL;}); + {if(st_code)*st_code=PJSIP_SC_INTERNAL_SERVER_ERROR;return PJ_EINVAL;}); /* Check if Session Timers is supported */ if ((inv->options & PJSIP_INV_SUPPORT_TIMER) == 0) { @@ -764,274 +763,274 @@ PJ_DEF(pj_status_t) pjsip_timer_process_resp(pjsip_inv_session *inv, /* Only process response of INVITE or UPDATE */ if (rdata->msg_info.cseq->method.id != PJSIP_INVITE_METHOD && - pjsip_method_cmp(&rdata->msg_info.cseq->method, &pjsip_update_method)) + pjsip_method_cmp(&rdata->msg_info.cseq->method, &pjsip_update_method)) { - return PJ_SUCCESS; + return PJ_SUCCESS; } if (msg->line.status.code == PJSIP_SC_SESSION_TIMER_TOO_SMALL) { - /* Our Session-Expires is too small, let's update it based on - * Min-SE header in the response. - */ - pjsip_tx_data *tdata; - pjsip_min_se_hdr *min_se_hdr; - pjsip_hdr *hdr; - pjsip_via_hdr *via; - - /* Get Min-SE value from response */ - min_se_hdr = (pjsip_min_se_hdr*) - pjsip_msg_find_hdr_by_name(msg, &STR_MIN_SE, NULL); - if (min_se_hdr == NULL) { - /* Response 422 MUST contain Min-SE header */ - PJ_LOG(3, (inv->pool->obj_name, - "Received 422 (Session Interval Too Small) response " - "without Min-SE header!")); - - pjsip_timer_end_session(inv); - return PJSIP_EMISSINGHDR; - } - - /* Avoid 422 retry loop. Ignore it and stop retrying if dialog is - * established, otherwise, just return error to disconnect the call. - */ - if (rdata->msg_info.cseq->cseq == inv->timer->last_422_cseq + 1) { - if (inv->state == PJSIP_INV_STATE_CONFIRMED) { - inv->invite_tsx = NULL; - return PJ_SUCCESS; - } else { - return PJSIP_ERRNO_FROM_SIP_STATUS( - PJSIP_SC_SESSION_TIMER_TOO_SMALL); - } - } - inv->timer->last_422_cseq = rdata->msg_info.cseq->cseq; - - /* Session Timers should have been initialized here */ - pj_assert(inv->timer); - - /* Update Min-SE */ - inv->timer->setting.min_se = PJ_MAX(min_se_hdr->min_se, - inv->timer->setting.min_se); - - /* Update Session Timers setting */ - if (inv->timer->setting.sess_expires < inv->timer->setting.min_se) - inv->timer->setting.sess_expires = inv->timer->setting.min_se; - - /* Prepare to restart the request */ - - /* Get the original INVITE/UPDATE request. */ - tdata = pjsip_rdata_get_tsx((pjsip_rx_data*)rdata)->last_tx; - - /* Remove branch param in Via header. */ - via = (pjsip_via_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); - pj_assert(via); - via->branch_param.slen = 0; - - /* Restore strict route set. - * See https://github.com/pjsip/pjproject/issues/492 - */ - pjsip_restore_strict_route_set(tdata); - - /* Must invalidate the message! */ - pjsip_tx_data_invalidate_msg(tdata); - - pjsip_tx_data_add_ref(tdata); - - /* Update Session Timers headers */ - hdr = (pjsip_hdr*) pjsip_msg_find_hdr_by_name(tdata->msg, - &STR_MIN_SE, NULL); - if (hdr != NULL) pj_list_erase(hdr); - - hdr = (pjsip_hdr*) pjsip_msg_find_hdr_by_names(tdata->msg, &STR_SE, - &STR_SHORT_SE, NULL); - if (hdr != NULL) pj_list_erase(hdr); - - add_timer_headers(inv, tdata, PJ_TRUE, PJ_TRUE); - - /* Restart UAC if this is initial INVITE, or simply reset tsx for - * subsequent INVITE. - */ - if (inv->state < PJSIP_INV_STATE_CONFIRMED) - pjsip_inv_uac_restart(inv, PJ_FALSE); - else if (tdata->msg->line.req.method.id == PJSIP_INVITE_METHOD) - inv->invite_tsx = NULL; - - /* Resend the updated request */ - pjsip_inv_send_msg(inv, tdata); - - return PJ_SUCCESS; + /* Our Session-Expires is too small, let's update it based on + * Min-SE header in the response. + */ + pjsip_tx_data *tdata; + pjsip_min_se_hdr *min_se_hdr; + pjsip_hdr *hdr; + pjsip_via_hdr *via; + + /* Get Min-SE value from response */ + min_se_hdr = (pjsip_min_se_hdr*) + pjsip_msg_find_hdr_by_name(msg, &STR_MIN_SE, NULL); + if (min_se_hdr == NULL) { + /* Response 422 MUST contain Min-SE header */ + PJ_LOG(3, (inv->pool->obj_name, + "Received 422 (Session Interval Too Small) response " + "without Min-SE header!")); + + pjsip_timer_end_session(inv); + return PJSIP_EMISSINGHDR; + } + + /* Avoid 422 retry loop. Ignore it and stop retrying if dialog is + * established, otherwise, just return error to disconnect the call. + */ + if (rdata->msg_info.cseq->cseq == inv->timer->last_422_cseq + 1) { + if (inv->state == PJSIP_INV_STATE_CONFIRMED) { + inv->invite_tsx = NULL; + return PJ_SUCCESS; + } else { + return PJSIP_ERRNO_FROM_SIP_STATUS( + PJSIP_SC_SESSION_TIMER_TOO_SMALL); + } + } + inv->timer->last_422_cseq = rdata->msg_info.cseq->cseq; + + /* Session Timers should have been initialized here */ + pj_assert(inv->timer); + + /* Update Min-SE */ + inv->timer->setting.min_se = PJ_MAX(min_se_hdr->min_se, + inv->timer->setting.min_se); + + /* Update Session Timers setting */ + if (inv->timer->setting.sess_expires < inv->timer->setting.min_se) + inv->timer->setting.sess_expires = inv->timer->setting.min_se; + + /* Prepare to restart the request */ + + /* Get the original INVITE/UPDATE request. */ + tdata = pjsip_rdata_get_tsx((pjsip_rx_data*)rdata)->last_tx; + + /* Remove branch param in Via header. */ + via = (pjsip_via_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); + pj_assert(via); + via->branch_param.slen = 0; + + /* Restore strict route set. + * See https://github.com/pjsip/pjproject/issues/492 + */ + pjsip_restore_strict_route_set(tdata); + + /* Must invalidate the message! */ + pjsip_tx_data_invalidate_msg(tdata); + + pjsip_tx_data_add_ref(tdata); + + /* Update Session Timers headers */ + hdr = (pjsip_hdr*) pjsip_msg_find_hdr_by_name(tdata->msg, + &STR_MIN_SE, NULL); + if (hdr != NULL) pj_list_erase(hdr); + + hdr = (pjsip_hdr*) pjsip_msg_find_hdr_by_names(tdata->msg, &STR_SE, + &STR_SHORT_SE, NULL); + if (hdr != NULL) pj_list_erase(hdr); + + add_timer_headers(inv, tdata, PJ_TRUE, PJ_TRUE); + + /* Restart UAC if this is initial INVITE, or simply reset tsx for + * subsequent INVITE. + */ + if (inv->state < PJSIP_INV_STATE_CONFIRMED) + pjsip_inv_uac_restart(inv, PJ_FALSE); + else if (tdata->msg->line.req.method.id == PJSIP_INVITE_METHOD) + inv->invite_tsx = NULL; + + /* Resend the updated request */ + pjsip_inv_send_msg(inv, tdata); + + return PJ_SUCCESS; } else if (msg->line.status.code/100 == 2) { - pjsip_sess_expires_hdr *se_hdr; - - /* Find Session-Expires header */ - se_hdr = (pjsip_sess_expires_hdr*) pjsip_msg_find_hdr_by_names( - msg, &STR_SE, - &STR_SHORT_SE, NULL); - if (se_hdr == NULL) { - /* Remote doesn't support/want Session Timers, check if local - * require or force to use Session Timers. - */ - if (inv->options & PJSIP_INV_REQUIRE_TIMER) { - if (st_code) - *st_code = PJSIP_SC_EXTENSION_REQUIRED; - pjsip_timer_end_session(inv); - return PJSIP_ERRNO_FROM_SIP_STATUS( - PJSIP_SC_EXTENSION_REQUIRED); - } - - if ((inv->options & PJSIP_INV_ALWAYS_USE_TIMER) == 0) { - /* Session Timers not forced */ - pjsip_timer_end_session(inv); - return PJ_SUCCESS; - } - } - - /* Make sure Session Timers is initialized */ - if (inv->timer == NULL) - pjsip_timer_init_session(inv, NULL); - - /* Session expiration period specified by remote is lower than our - * Min-SE. - */ - if (se_hdr && - se_hdr->sess_expires < inv->timer->setting.min_se) - { - /* See ticket #954, instead of returning non-PJ_SUCCESS (which - * may cause disconnecting call/dialog), let's just accept the - * SE and update our local SE, as long as it isn't less than 90s. - */ - if (se_hdr->sess_expires >= ABS_MIN_SE) { - PJ_LOG(3, (inv->pool->obj_name, - "Peer responds with bad Session-Expires, %ds, " - "which is less than Min-SE specified in request, " - "%ds. Well, let's just accept and use it.", - se_hdr->sess_expires, inv->timer->setting.min_se)); - - inv->timer->setting.sess_expires = se_hdr->sess_expires; - inv->timer->setting.min_se = se_hdr->sess_expires; - } - - //if (st_code) - // *st_code = PJSIP_SC_SESSION_TIMER_TOO_SMALL; - //pjsip_timer_end_session(inv); - //return PJSIP_ERRNO_FROM_SIP_STATUS( - // PJSIP_SC_SESSION_TIMER_TOO_SMALL); - } - - /* Update SE. Session-Expires in response cannot be lower than Min-SE. - * Session-Expires in response can only be equal or lower than in - * request. - */ - if (se_hdr && - se_hdr->sess_expires <= inv->timer->setting.sess_expires && - se_hdr->sess_expires >= inv->timer->setting.min_se) - { - /* Good SE from remote, update local SE */ - inv->timer->setting.sess_expires = se_hdr->sess_expires; - } - - /* Set the refresher */ - if (se_hdr && pj_stricmp(&se_hdr->refresher, &STR_UAC) == 0) - inv->timer->refresher = TR_UAC; - else if (se_hdr && pj_stricmp(&se_hdr->refresher, &STR_UAS) == 0) - inv->timer->refresher = TR_UAS; - else - /* UAS should set the refresher, however, there is a case that - * UAS doesn't support/want Session Timers but the UAC insists - * to use Session Timers. - */ - inv->timer->refresher = TR_UAC; - - /* Remember our role in this transaction */ - inv->timer->role = PJSIP_ROLE_UAC; - - /* Finally, set active flag and start the Session Timers */ - inv->timer->active = PJ_TRUE; - start_timer(inv); + pjsip_sess_expires_hdr *se_hdr; + + /* Find Session-Expires header */ + se_hdr = (pjsip_sess_expires_hdr*) pjsip_msg_find_hdr_by_names( + msg, &STR_SE, + &STR_SHORT_SE, NULL); + if (se_hdr == NULL) { + /* Remote doesn't support/want Session Timers, check if local + * require or force to use Session Timers. + */ + if (inv->options & PJSIP_INV_REQUIRE_TIMER) { + if (st_code) + *st_code = PJSIP_SC_EXTENSION_REQUIRED; + pjsip_timer_end_session(inv); + return PJSIP_ERRNO_FROM_SIP_STATUS( + PJSIP_SC_EXTENSION_REQUIRED); + } + + if ((inv->options & PJSIP_INV_ALWAYS_USE_TIMER) == 0) { + /* Session Timers not forced */ + pjsip_timer_end_session(inv); + return PJ_SUCCESS; + } + } + + /* Make sure Session Timers is initialized */ + if (inv->timer == NULL) + pjsip_timer_init_session(inv, NULL); + + /* Session expiration period specified by remote is lower than our + * Min-SE. + */ + if (se_hdr && + se_hdr->sess_expires < inv->timer->setting.min_se) + { + /* See ticket #954, instead of returning non-PJ_SUCCESS (which + * may cause disconnecting call/dialog), let's just accept the + * SE and update our local SE, as long as it isn't less than 90s. + */ + if (se_hdr->sess_expires >= ABS_MIN_SE) { + PJ_LOG(3, (inv->pool->obj_name, + "Peer responds with bad Session-Expires, %ds, " + "which is less than Min-SE specified in request, " + "%ds. Well, let's just accept and use it.", + se_hdr->sess_expires, inv->timer->setting.min_se)); + + inv->timer->setting.sess_expires = se_hdr->sess_expires; + inv->timer->setting.min_se = se_hdr->sess_expires; + } + + //if (st_code) + // *st_code = PJSIP_SC_SESSION_TIMER_TOO_SMALL; + //pjsip_timer_end_session(inv); + //return PJSIP_ERRNO_FROM_SIP_STATUS( + // PJSIP_SC_SESSION_TIMER_TOO_SMALL); + } + + /* Update SE. Session-Expires in response cannot be lower than Min-SE. + * Session-Expires in response can only be equal or lower than in + * request. + */ + if (se_hdr && + se_hdr->sess_expires <= inv->timer->setting.sess_expires && + se_hdr->sess_expires >= inv->timer->setting.min_se) + { + /* Good SE from remote, update local SE */ + inv->timer->setting.sess_expires = se_hdr->sess_expires; + } + + /* Set the refresher */ + if (se_hdr && pj_stricmp(&se_hdr->refresher, &STR_UAC) == 0) + inv->timer->refresher = TR_UAC; + else if (se_hdr && pj_stricmp(&se_hdr->refresher, &STR_UAS) == 0) + inv->timer->refresher = TR_UAS; + else + /* UAS should set the refresher, however, there is a case that + * UAS doesn't support/want Session Timers but the UAC insists + * to use Session Timers. + */ + inv->timer->refresher = TR_UAC; + + /* Remember our role in this transaction */ + inv->timer->role = PJSIP_ROLE_UAC; + + /* Finally, set active flag and start the Session Timers */ + inv->timer->active = PJ_TRUE; + start_timer(inv); } else if (pjsip_method_cmp(&rdata->msg_info.cseq->method, - &pjsip_update_method) == 0 && - msg->line.status.code >= 400 && msg->line.status.code < 600) + &pjsip_update_method) == 0 && + msg->line.status.code >= 400 && msg->line.status.code < 600) { - /* This is to handle error response to previous UPDATE that was - * sent without SDP. In this case, retry sending UPDATE but - * with SDP this time. - * Note: the additional expressions are to check that the - * UPDATE was really the one sent by us, not by other - * call components (e.g. to change codec) - */ - if (inv->timer->timer.id == 0 && inv->timer->use_update && - inv->timer->with_sdp == PJ_FALSE) - { - inv->timer->with_sdp = PJ_TRUE; - timer_cb(NULL, &inv->timer->timer); - } + /* This is to handle error response to previous UPDATE that was + * sent without SDP. In this case, retry sending UPDATE but + * with SDP this time. + * Note: the additional expressions are to check that the + * UPDATE was really the one sent by us, not by other + * call components (e.g. to change codec) + */ + if (inv->timer->timer.id == 0 && inv->timer->use_update && + inv->timer->with_sdp == PJ_FALSE) + { + inv->timer->with_sdp = PJ_TRUE; + timer_cb(NULL, &inv->timer->timer); + } } return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjsip_timer_handle_refresh_error( - pjsip_inv_session *inv, - pjsip_event *event) + pjsip_inv_session *inv, + pjsip_event *event) { PJ_ASSERT_RETURN(inv && event, PJ_EINVAL); /* Check if Session Timers is supported */ if ((inv->options & PJSIP_INV_SUPPORT_TIMER) == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; pj_assert(is_initialized); if (inv->timer && inv->timer->active) { - pj_bool_t as_refresher; - - /* Check our role */ - as_refresher = ((inv->timer->refresher == TR_UAC) && - (inv->timer->role == PJSIP_ROLE_UAC)) || - ((inv->timer->refresher == TR_UAS) && - (inv->timer->role == PJSIP_ROLE_UAS)); - - - if ((as_refresher) && (event->type == PJSIP_EVENT_TSX_STATE) && - (inv->timer->refresh_tdata == event->body.tsx_state.tsx->last_tx)) - { - pjsip_status_code st_code; - pjsip_tx_data *bye; - pj_status_t status; - - st_code = - (pjsip_status_code)event->body.tsx_state.tsx->status_code; - - PJ_LOG(3, (inv->pool->obj_name, - "Receive error %d for refresh request %.*s/cseq=%d", - st_code, event->body.tsx_state.tsx->method.name.slen, - event->body.tsx_state.tsx->method.name.ptr, - event->body.tsx_state.tsx->cseq)); - - if (st_code == 503 && PJSIP_SESS_TIMER_RETRY_DELAY >= 0) { - /* Retry the refresh after some delay */ - pj_time_val delay = {PJSIP_SESS_TIMER_RETRY_DELAY, 0}; - - PJ_LOG(3, (inv->pool->obj_name, "Scheduling to retry refresh " - "request after %d second(s)", delay.sec)); - - inv->timer->timer.id = 1; - pjsip_endpt_schedule_timer(inv->dlg->endpt, - &inv->timer->timer, &delay); - } else { - PJ_LOG(3, (inv->pool->obj_name, "Ending session now")); - - status = pjsip_inv_end_session(inv, - event->body.tsx_state.tsx->status_code, - pjsip_get_status_text(st_code), - &bye); - - if (status == PJ_SUCCESS && bye) - status = pjsip_inv_send_msg(inv, bye); - } - } + pj_bool_t as_refresher; + + /* Check our role */ + as_refresher = ((inv->timer->refresher == TR_UAC) && + (inv->timer->role == PJSIP_ROLE_UAC)) || + ((inv->timer->refresher == TR_UAS) && + (inv->timer->role == PJSIP_ROLE_UAS)); + + + if ((as_refresher) && (event->type == PJSIP_EVENT_TSX_STATE) && + (inv->timer->refresh_tdata == event->body.tsx_state.tsx->last_tx)) + { + pjsip_status_code st_code; + pjsip_tx_data *bye; + pj_status_t status; + + st_code = + (pjsip_status_code)event->body.tsx_state.tsx->status_code; + + PJ_LOG(3, (inv->pool->obj_name, + "Receive error %d for refresh request %.*s/cseq=%d", + st_code, event->body.tsx_state.tsx->method.name.slen, + event->body.tsx_state.tsx->method.name.ptr, + event->body.tsx_state.tsx->cseq)); + + if (st_code == 503 && PJSIP_SESS_TIMER_RETRY_DELAY >= 0) { + /* Retry the refresh after some delay */ + pj_time_val delay = {PJSIP_SESS_TIMER_RETRY_DELAY, 0}; + + PJ_LOG(3, (inv->pool->obj_name, "Scheduling to retry refresh " + "request after %d second(s)", delay.sec)); + + inv->timer->timer.id = 1; + pjsip_endpt_schedule_timer(inv->dlg->endpt, + &inv->timer->timer, &delay); + } else { + PJ_LOG(3, (inv->pool->obj_name, "Ending session now")); + + status = pjsip_inv_end_session(inv, + event->body.tsx_state.tsx->status_code, + pjsip_get_status_text(st_code), + &bye); + + if (status == PJ_SUCCESS && bye) + status = pjsip_inv_send_msg(inv, bye); + } + } } return PJ_SUCCESS; @@ -1041,8 +1040,8 @@ PJ_DEF(pj_status_t) pjsip_timer_handle_refresh_error( * Handle incoming INVITE or UPDATE request. */ PJ_DEF(pj_status_t) pjsip_timer_process_req(pjsip_inv_session *inv, - const pjsip_rx_data *rdata, - pjsip_status_code *st_code) + const pjsip_rx_data *rdata, + pjsip_status_code *st_code) { pjsip_min_se_hdr *min_se_hdr; pjsip_sess_expires_hdr *se_hdr; @@ -1050,11 +1049,11 @@ PJ_DEF(pj_status_t) pjsip_timer_process_req(pjsip_inv_session *inv, unsigned min_se; PJ_ASSERT_ON_FAIL(inv && rdata, - {if(st_code)*st_code=PJSIP_SC_INTERNAL_SERVER_ERROR;return PJ_EINVAL;}); + {if(st_code)*st_code=PJSIP_SC_INTERNAL_SERVER_ERROR;return PJ_EINVAL;}); /* Check if Session Timers is supported */ if ((inv->options & PJSIP_INV_SUPPORT_TIMER) == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; pj_assert(is_initialized); @@ -1063,33 +1062,33 @@ PJ_DEF(pj_status_t) pjsip_timer_process_req(pjsip_inv_session *inv, /* Only process INVITE or UPDATE request */ if (msg->line.req.method.id != PJSIP_INVITE_METHOD && - pjsip_method_cmp(&rdata->msg_info.cseq->method, &pjsip_update_method)) + pjsip_method_cmp(&rdata->msg_info.cseq->method, &pjsip_update_method)) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Make sure Session Timers is initialized */ if (inv->timer == NULL) - pjsip_timer_init_session(inv, NULL); + pjsip_timer_init_session(inv, NULL); /* Find Session-Expires header */ se_hdr = (pjsip_sess_expires_hdr*) pjsip_msg_find_hdr_by_names( - msg, &STR_SE, &STR_SHORT_SE, NULL); + msg, &STR_SE, &STR_SHORT_SE, NULL); /* Find Min-SE header */ min_se_hdr = (pjsip_min_se_hdr*) pjsip_msg_find_hdr_by_name(msg, - &STR_MIN_SE, NULL); + &STR_MIN_SE, NULL); /* Update Min-SE */ min_se = inv->timer->setting.min_se; if (min_se_hdr) - min_se = PJ_MAX(min_se_hdr->min_se, min_se); + min_se = PJ_MAX(min_se_hdr->min_se, min_se); /* Validate SE. Session-Expires cannot be lower than Min-SE * (or 90 seconds if Min-SE is not set). */ if (se_hdr && se_hdr->sess_expires < min_se) { - if (st_code) - *st_code = PJSIP_SC_SESSION_TIMER_TOO_SMALL; - return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_SESSION_TIMER_TOO_SMALL); + if (st_code) + *st_code = PJSIP_SC_SESSION_TIMER_TOO_SMALL; + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_SESSION_TIMER_TOO_SMALL); } /* Update SE. Note that there is a case that SE is not available in the @@ -1097,14 +1096,14 @@ PJ_DEF(pj_status_t) pjsip_timer_process_req(pjsip_inv_session *inv, * to use Session Timers. */ if (se_hdr) { - /* Update SE as specified by peer. */ - inv->timer->setting.sess_expires = se_hdr->sess_expires; + /* Update SE as specified by peer. */ + inv->timer->setting.sess_expires = se_hdr->sess_expires; } else if (inv->timer->setting.sess_expires < min_se) { - /* There is no SE in the request (remote support Session Timers but - * doesn't want to use it, it just specify Min-SE) and local SE is - * lower than Min-SE specified by remote. - */ - inv->timer->setting.sess_expires = min_se; + /* There is no SE in the request (remote support Session Timers but + * doesn't want to use it, it just specify Min-SE) and local SE is + * lower than Min-SE specified by remote. + */ + inv->timer->setting.sess_expires = min_se; } /* If incoming request has no SE header, it means remote doesn't @@ -1113,42 +1112,42 @@ PJ_DEF(pj_status_t) pjsip_timer_process_req(pjsip_inv_session *inv, * negotiation should have been verified by invite session. */ if (se_hdr == NULL) { - if ((inv->options & - (PJSIP_INV_REQUIRE_TIMER | PJSIP_INV_ALWAYS_USE_TIMER)) == 0) - { - /* Session Timers not forced/required */ - pjsip_timer_end_session(inv); - return PJ_SUCCESS; - } + if ((inv->options & + (PJSIP_INV_REQUIRE_TIMER | PJSIP_INV_ALWAYS_USE_TIMER)) == 0) + { + /* Session Timers not forced/required */ + pjsip_timer_end_session(inv); + return PJ_SUCCESS; + } } /* Set the refresher */ if (se_hdr && pj_stricmp(&se_hdr->refresher, &STR_UAC) == 0) - inv->timer->refresher = TR_UAC; + inv->timer->refresher = TR_UAC; else if (se_hdr && pj_stricmp(&se_hdr->refresher, &STR_UAS) == 0) - inv->timer->refresher = TR_UAS; + inv->timer->refresher = TR_UAS; else { - /* If refresher role (i.e: ours or peer) has been set/negotiated, - * better to keep it. - */ - if (inv->timer->refresher != TR_UNKNOWN) { - pj_bool_t as_refresher; - - /* Check our refresher role */ - as_refresher = - (inv->timer->refresher==TR_UAC && inv->timer->role==PJSIP_ROLE_UAC) || - (inv->timer->refresher==TR_UAS && inv->timer->role==PJSIP_ROLE_UAS); - - /* Update refresher role */ - inv->timer->refresher = as_refresher? TR_UAS : TR_UAC; - } else { - /* If UAC supports timer and Session-Expires header is present + /* If refresher role (i.e: ours or peer) has been set/negotiated, + * better to keep it. + */ + if (inv->timer->refresher != TR_UNKNOWN) { + pj_bool_t as_refresher; + + /* Check our refresher role */ + as_refresher = + (inv->timer->refresher==TR_UAC && inv->timer->role==PJSIP_ROLE_UAC) || + (inv->timer->refresher==TR_UAS && inv->timer->role==PJSIP_ROLE_UAS); + + /* Update refresher role */ + inv->timer->refresher = as_refresher? TR_UAS : TR_UAC; + } else { + /* If UAC supports timer and Session-Expires header is present * in the request, set UAC as refresher. - * If UAC doesn't support timer and a proxy inserts a - * Session-Expires header, then UAS has to be the - * refresher (according to RFC 4028 Section 9). - */ - pj_bool_t uac_supports_timer = PJ_FALSE; + * If UAC doesn't support timer and a proxy inserts a + * Session-Expires header, then UAS has to be the + * refresher (according to RFC 4028 Section 9). + */ + pj_bool_t uac_supports_timer = PJ_FALSE; pjsip_supported_hdr *sup_hdr; sup_hdr = (pjsip_supported_hdr*) @@ -1164,8 +1163,8 @@ PJ_DEF(pj_status_t) pjsip_timer_process_req(pjsip_inv_session *inv, } } inv->timer->refresher = (uac_supports_timer && se_hdr)? TR_UAC: - TR_UAS; - } + TR_UAS; + } } /* Remember our role in this transaction */ @@ -1181,13 +1180,13 @@ PJ_DEF(pj_status_t) pjsip_timer_process_req(pjsip_inv_session *inv, * Handle outgoing response with status code 2xx & 422. */ PJ_DEF(pj_status_t) pjsip_timer_update_resp(pjsip_inv_session *inv, - pjsip_tx_data *tdata) + pjsip_tx_data *tdata) { pjsip_msg *msg; /* Check if Session Timers is supported */ if ((inv->options & PJSIP_INV_SUPPORT_TIMER) == 0) - return PJ_SUCCESS; + return PJ_SUCCESS; pj_assert(is_initialized); PJ_ASSERT_RETURN(inv && tdata, PJ_EINVAL); @@ -1196,43 +1195,43 @@ PJ_DEF(pj_status_t) pjsip_timer_update_resp(pjsip_inv_session *inv, if (msg->line.status.code/100 == 2) { - if (inv->timer && inv->timer->active) { - /* Add Session-Expires header and start the timer */ - add_timer_headers(inv, tdata, PJ_TRUE, PJ_FALSE); - - /* Add 'timer' to Require header (see ticket #1560). */ - if (inv->timer->refresher == TR_UAC) { - pjsip_require_hdr *req_hdr; - pj_bool_t req_hdr_has_timer = PJ_FALSE; - - req_hdr = (pjsip_require_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_REQUIRE, - NULL); - if (req_hdr == NULL) { - req_hdr = pjsip_require_hdr_create(tdata->pool); - PJ_ASSERT_RETURN(req_hdr, PJ_ENOMEM); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)req_hdr); - } else { - unsigned i; - for (i = 0; i < req_hdr->count; ++i) { - if (pj_stricmp(&req_hdr->values[i], &STR_TIMER)) { - req_hdr_has_timer = PJ_TRUE; - break; - } - } - } - if (!req_hdr_has_timer) - req_hdr->values[req_hdr->count++] = STR_TIMER; - } - - /* Finally, start timer. */ - start_timer(inv); - } + if (inv->timer && inv->timer->active) { + /* Add Session-Expires header and start the timer */ + add_timer_headers(inv, tdata, PJ_TRUE, PJ_FALSE); + + /* Add 'timer' to Require header (see ticket #1560). */ + if (inv->timer->refresher == TR_UAC) { + pjsip_require_hdr *req_hdr; + pj_bool_t req_hdr_has_timer = PJ_FALSE; + + req_hdr = (pjsip_require_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_REQUIRE, + NULL); + if (req_hdr == NULL) { + req_hdr = pjsip_require_hdr_create(tdata->pool); + PJ_ASSERT_RETURN(req_hdr, PJ_ENOMEM); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)req_hdr); + } else { + unsigned i; + for (i = 0; i < req_hdr->count; ++i) { + if (pj_stricmp(&req_hdr->values[i], &STR_TIMER)) { + req_hdr_has_timer = PJ_TRUE; + break; + } + } + } + if (!req_hdr_has_timer) + req_hdr->values[req_hdr->count++] = STR_TIMER; + } + + /* Finally, start timer. */ + start_timer(inv); + } } else if (msg->line.status.code == PJSIP_SC_SESSION_TIMER_TOO_SMALL) { - /* Add Min-SE header */ - add_timer_headers(inv, tdata, PJ_FALSE, PJ_TRUE); + /* Add Min-SE header */ + add_timer_headers(inv, tdata, PJ_FALSE, PJ_TRUE); } return PJ_SUCCESS; @@ -1247,11 +1246,11 @@ PJ_DEF(pj_status_t) pjsip_timer_end_session(pjsip_inv_session *inv) PJ_ASSERT_RETURN(inv, PJ_EINVAL); if (inv->timer) { - /* Reset active flag */ - inv->timer->active = PJ_FALSE; + /* Reset active flag */ + inv->timer->active = PJ_FALSE; - /* Stop Session Timers */ - stop_timer(inv); + /* Stop Session Timers */ + stop_timer(inv); } return PJ_SUCCESS; diff --git a/pjsip/src/pjsip-ua/sip_xfer.c b/pjsip/src/pjsip-ua/sip_xfer.c index b146a3855e..65d2c49e38 100644 --- a/pjsip/src/pjsip-ua/sip_xfer.c +++ b/pjsip/src/pjsip-ua/sip_xfer.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,7 +29,7 @@ /* Subscription expiration */ #ifndef PJSIP_XFER_EXPIRES -# define PJSIP_XFER_EXPIRES 600 +# define PJSIP_XFER_EXPIRES 600 #endif @@ -39,19 +38,19 @@ */ static struct pjsip_module mod_xfer = { - NULL, NULL, /* prev, next. */ - { "mod-refer", 9 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_DIALOG_USAGE, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - NULL, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-refer", 9 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_DIALOG_USAGE, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -86,12 +85,12 @@ static const pj_str_t STR_SIPFRAG = { "sipfrag", 7 }; */ struct pjsip_xfer { - pjsip_evsub *sub; /**< Event subscribtion record. */ - pjsip_dialog *dlg; /**< The dialog. */ - pjsip_evsub_user user_cb; /**< The user callback. */ - pj_str_t refer_to_uri; /**< The full Refer-To URI. */ - int last_st_code; /**< st_code sent in last NOTIFY */ - pj_str_t last_st_text; /**< st_text sent in last NOTIFY */ + pjsip_evsub *sub; /**< Event subscribtion record. */ + pjsip_dialog *dlg; /**< The dialog. */ + pjsip_evsub_user user_cb; /**< The user callback. */ + pj_str_t refer_to_uri; /**< The full Refer-To URI. */ + int last_st_code; /**< st_code sent in last NOTIFY */ + pj_str_t last_st_text; /**< st_text sent in last NOTIFY */ }; @@ -104,19 +103,19 @@ typedef struct pjsip_xfer pjsip_xfer; */ static void xfer_on_evsub_state( pjsip_evsub *sub, pjsip_event *event); static void xfer_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, - pjsip_event *event); + pjsip_event *event); static void xfer_on_evsub_rx_refresh( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body); + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body); static void xfer_on_evsub_rx_notify( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body); + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body); static void xfer_on_evsub_client_refresh(pjsip_evsub *sub); static void xfer_on_evsub_server_timeout(pjsip_evsub *sub); @@ -150,18 +149,18 @@ PJ_DEF(pj_status_t) pjsip_xfer_init_module(pjsip_endpoint *endpt) status = pjsip_endpt_register_module(endpt, &mod_xfer); if (status != PJ_SUCCESS) - return status; + return status; status = pjsip_endpt_add_capability( endpt, &mod_xfer, PJSIP_H_ALLOW, - NULL, 1, - &pjsip_get_refer_method()->name); + NULL, 1, + &pjsip_get_refer_method()->name); if (status != PJ_SUCCESS) - return status; + return status; status = pjsip_evsub_register_pkg(&mod_xfer, &STR_REFER, - PJSIP_XFER_EXPIRES, 1, &accept); + PJSIP_XFER_EXPIRES, 1, &accept); if (status != PJ_SUCCESS) - return status; + return status; return PJ_SUCCESS; } @@ -172,8 +171,8 @@ PJ_DEF(pj_status_t) pjsip_xfer_init_module(pjsip_endpoint *endpt) * */ PJ_DEF(pj_status_t) pjsip_xfer_create_uac( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - pjsip_evsub **p_evsub ) + const pjsip_evsub_user *user_cb, + pjsip_evsub **p_evsub ) { pj_status_t status; pjsip_xfer *xfer; @@ -185,16 +184,16 @@ PJ_DEF(pj_status_t) pjsip_xfer_create_uac( pjsip_dialog *dlg, /* Create event subscription */ status = pjsip_evsub_create_uac( dlg, &xfer_user, &STR_REFER, - PJSIP_EVSUB_NO_EVENT_ID, &sub); + PJSIP_EVSUB_NO_EVENT_ID, &sub); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create xfer session */ xfer = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_xfer); xfer->dlg = dlg; xfer->sub = sub; if (user_cb) - pj_memcpy(&xfer->user_cb, user_cb, sizeof(pjsip_evsub_user)); + pj_memcpy(&xfer->user_cb, user_cb, sizeof(pjsip_evsub_user)); /* Attach to evsub */ pjsip_evsub_set_mod_data(sub, mod_xfer.id, xfer); @@ -215,9 +214,9 @@ PJ_DEF(pj_status_t) pjsip_xfer_create_uac( pjsip_dialog *dlg, * */ PJ_DEF(pj_status_t) pjsip_xfer_create_uas( pjsip_dialog *dlg, - const pjsip_evsub_user *user_cb, - pjsip_rx_data *rdata, - pjsip_evsub **p_evsub ) + const pjsip_evsub_user *user_cb, + pjsip_rx_data *rdata, + pjsip_evsub **p_evsub ) { pjsip_evsub *sub; pjsip_xfer *xfer; @@ -230,12 +229,12 @@ PJ_DEF(pj_status_t) pjsip_xfer_create_uas( pjsip_dialog *dlg, /* Must be request message */ PJ_ASSERT_RETURN(rdata->msg_info.msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); /* Check that request is REFER */ PJ_ASSERT_RETURN(pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, - pjsip_get_refer_method())==0, - PJSIP_ENOTREFER); + pjsip_get_refer_method())==0, + PJSIP_ENOTREFER); /* Lock dialog */ pjsip_dlg_inc_lock(dlg); @@ -245,25 +244,25 @@ PJ_DEF(pj_status_t) pjsip_xfer_create_uas( pjsip_dialog *dlg, * So create a dummy Event header. */ if (pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, - &STR_EVENT, NULL)==NULL) + &STR_EVENT, NULL)==NULL) { - event_hdr = pjsip_event_hdr_create(rdata->tp_info.pool); - event_hdr->event_type = STR_REFER; - pjsip_msg_add_hdr(rdata->msg_info.msg, (pjsip_hdr*)event_hdr); + event_hdr = pjsip_event_hdr_create(rdata->tp_info.pool); + event_hdr->event_type = STR_REFER; + pjsip_msg_add_hdr(rdata->msg_info.msg, (pjsip_hdr*)event_hdr); } /* Create server subscription */ status = pjsip_evsub_create_uas( dlg, &xfer_user, rdata, - PJSIP_EVSUB_NO_EVENT_ID, &sub); + PJSIP_EVSUB_NO_EVENT_ID, &sub); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create server xfer subscription */ xfer = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_xfer); xfer->dlg = dlg; xfer->sub = sub; if (user_cb) - pj_memcpy(&xfer->user_cb, user_cb, sizeof(pjsip_evsub_user)); + pj_memcpy(&xfer->user_cb, user_cb, sizeof(pjsip_evsub_user)); /* Attach to evsub */ pjsip_evsub_set_mod_data(sub, mod_xfer.id, xfer); @@ -283,8 +282,8 @@ PJ_DEF(pj_status_t) pjsip_xfer_create_uas( pjsip_dialog *dlg, * */ PJ_DEF(pj_status_t) pjsip_xfer_initiate( pjsip_evsub *sub, - const pj_str_t *refer_to_uri, - pjsip_tx_data **p_tdata) + const pj_str_t *refer_to_uri, + pjsip_tx_data **p_tdata) { pjsip_xfer *xfer; const pj_str_t refer_to = { "Refer-To", 8}; @@ -310,24 +309,24 @@ PJ_DEF(pj_status_t) pjsip_xfer_initiate( pjsip_evsub *sub, /* Create basic REFER request */ status = pjsip_evsub_initiate(sub, pjsip_get_refer_method(), - PJSIP_EXPIRES_NOT_SPECIFIED, &tdata); + PJSIP_EXPIRES_NOT_SPECIFIED, &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Save Refer-To URI. */ if (refer_to_uri == NULL) { - refer_to_uri = &xfer->refer_to_uri; + refer_to_uri = &xfer->refer_to_uri; } else { - pj_strdup(xfer->dlg->pool, &xfer->refer_to_uri, refer_to_uri); + pj_strdup(xfer->dlg->pool, &xfer->refer_to_uri, refer_to_uri); } /* Create and add Refer-To header. */ hdr = pjsip_generic_string_hdr_create(tdata->pool, &refer_to, - refer_to_uri); + refer_to_uri); if (!hdr) { - pjsip_tx_data_dec_ref(tdata); - status = PJ_ENOMEM; - goto on_return; + pjsip_tx_data_dec_ref(tdata); + status = PJ_ENOMEM; + goto on_return; } pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hdr); @@ -349,9 +348,9 @@ PJ_DEF(pj_status_t) pjsip_xfer_initiate( pjsip_evsub *sub, * */ PJ_DEF(pj_status_t) pjsip_xfer_accept( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int st_code, - const pjsip_hdr *hdr_list ) + pjsip_rx_data *rdata, + int st_code, + const pjsip_hdr *hdr_list ) { /* * Don't need to add custom headers, so just call basic @@ -366,10 +365,10 @@ PJ_DEF(pj_status_t) pjsip_xfer_accept( pjsip_evsub *sub, * of the subscription. */ PJ_DEF(pj_status_t) pjsip_xfer_notify( pjsip_evsub *sub, - pjsip_evsub_state state, - int xfer_st_code, - const pj_str_t *xfer_st_text, - pjsip_tx_data **p_tdata) + pjsip_evsub_state state, + int xfer_st_code, + const pj_str_t *xfer_st_text, + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pjsip_xfer *xfer; @@ -398,12 +397,12 @@ PJ_DEF(pj_status_t) pjsip_xfer_notify( pjsip_evsub *sub, */ status = pjsip_evsub_notify( sub, state, NULL, &reason, &tdata); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Check status text */ if (xfer_st_text==NULL || xfer_st_text->slen==0) - xfer_st_text = pjsip_get_status_text(xfer_st_code); + xfer_st_text = pjsip_get_status_text(xfer_st_code); /* Save st_code and st_text, for current_notify() */ xfer->last_st_code = xfer_st_code; @@ -412,18 +411,18 @@ PJ_DEF(pj_status_t) pjsip_xfer_notify( pjsip_evsub *sub, /* Create sipfrag content. */ body = (char*) pj_pool_alloc(tdata->pool, 128); bodylen = pj_ansi_snprintf(body, 128, "SIP/2.0 %u %.*s\r\n", - xfer_st_code, - (int)xfer_st_text->slen, - xfer_st_text->ptr); + xfer_st_code, + (int)xfer_st_text->slen, + xfer_st_text->ptr); PJ_ASSERT_ON_FAIL(bodylen > 0 && bodylen < 128, - {status=PJ_EBUG; pjsip_tx_data_dec_ref(tdata); - goto on_return; }); + {status=PJ_EBUG; pjsip_tx_data_dec_ref(tdata); + goto on_return; }); /* Create SIP message body. */ msg_body = PJ_POOL_ZALLOC_T(tdata->pool, pjsip_msg_body); pjsip_media_type_init(&msg_body->content_type, (pj_str_t*)&STR_MESSAGE, - (pj_str_t*)&STR_SIPFRAG); + (pj_str_t*)&STR_SIPFRAG); msg_body->data = body; msg_body->len = bodylen; msg_body->print_body = &pjsip_print_text_body; @@ -453,7 +452,7 @@ PJ_DEF(pj_status_t) pjsip_xfer_notify( pjsip_evsub *sub, * Send current state and the last sipfrag body. */ PJ_DEF(pj_status_t) pjsip_xfer_current_notify( pjsip_evsub *sub, - pjsip_tx_data **p_tdata ) + pjsip_tx_data **p_tdata ) { pjsip_xfer *xfer; pj_status_t status; @@ -469,8 +468,8 @@ PJ_DEF(pj_status_t) pjsip_xfer_current_notify( pjsip_evsub *sub, pjsip_dlg_inc_lock(xfer->dlg); status = pjsip_xfer_notify(sub, pjsip_evsub_get_state(sub), - xfer->last_st_code, &xfer->last_st_text, - p_tdata); + xfer->last_st_code, &xfer->last_st_text, + p_tdata); pjsip_dlg_dec_lock(xfer->dlg); @@ -482,7 +481,7 @@ PJ_DEF(pj_status_t) pjsip_xfer_current_notify( pjsip_evsub *sub, * Send request message. */ PJ_DEF(pj_status_t) pjsip_xfer_send_request( pjsip_evsub *sub, - pjsip_tx_data *tdata) + pjsip_tx_data *tdata) { return pjsip_evsub_send_request(sub, tdata); } @@ -500,7 +499,7 @@ static void xfer_on_evsub_state( pjsip_evsub *sub, pjsip_event *event) PJ_ASSERT_ON_FAIL(xfer!=NULL, {return;}); if (xfer->user_cb.on_evsub_state) - (*xfer->user_cb.on_evsub_state)(sub, event); + (*xfer->user_cb.on_evsub_state)(sub, event); } @@ -508,7 +507,7 @@ static void xfer_on_evsub_state( pjsip_evsub *sub, pjsip_event *event) * Called when transaction state has changed. */ static void xfer_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, - pjsip_event *event) + pjsip_event *event) { pjsip_xfer *xfer; @@ -516,18 +515,18 @@ static void xfer_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, PJ_ASSERT_ON_FAIL(xfer!=NULL, {return;}); if (xfer->user_cb.on_tsx_state) - (*xfer->user_cb.on_tsx_state)(sub, tsx, event); + (*xfer->user_cb.on_tsx_state)(sub, tsx, event); } /* * Called when REFER is received to refresh subscription. */ static void xfer_on_evsub_rx_refresh( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body) + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body) { pjsip_xfer *xfer; @@ -535,27 +534,27 @@ static void xfer_on_evsub_rx_refresh( pjsip_evsub *sub, PJ_ASSERT_ON_FAIL(xfer!=NULL, {return;}); if (xfer->user_cb.on_rx_refresh) { - (*xfer->user_cb.on_rx_refresh)(sub, rdata, p_st_code, p_st_text, - res_hdr, p_body); + (*xfer->user_cb.on_rx_refresh)(sub, rdata, p_st_code, p_st_text, + res_hdr, p_body); } else { - /* Implementors MUST send NOTIFY if it implements on_rx_refresh - * (implementor == "us" from evsub point of view. - */ - pjsip_tx_data *tdata; - pj_status_t status; - - if (pjsip_evsub_get_state(sub)==PJSIP_EVSUB_STATE_TERMINATED) { - status = pjsip_xfer_notify( sub, PJSIP_EVSUB_STATE_TERMINATED, - xfer->last_st_code, - &xfer->last_st_text, - &tdata); - } else { - status = pjsip_xfer_current_notify(sub, &tdata); - } - - if (status == PJ_SUCCESS) - pjsip_xfer_send_request(sub, tdata); + /* Implementors MUST send NOTIFY if it implements on_rx_refresh + * (implementor == "us" from evsub point of view. + */ + pjsip_tx_data *tdata; + pj_status_t status; + + if (pjsip_evsub_get_state(sub)==PJSIP_EVSUB_STATE_TERMINATED) { + status = pjsip_xfer_notify( sub, PJSIP_EVSUB_STATE_TERMINATED, + xfer->last_st_code, + &xfer->last_st_text, + &tdata); + } else { + status = pjsip_xfer_current_notify(sub, &tdata); + } + + if (status == PJ_SUCCESS) + pjsip_xfer_send_request(sub, tdata); } } @@ -564,11 +563,11 @@ static void xfer_on_evsub_rx_refresh( pjsip_evsub *sub, * Called when NOTIFY is received. */ static void xfer_on_evsub_rx_notify( pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body) + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body) { pjsip_xfer *xfer; @@ -576,8 +575,8 @@ static void xfer_on_evsub_rx_notify( pjsip_evsub *sub, PJ_ASSERT_ON_FAIL(xfer!=NULL, {return;}); if (xfer->user_cb.on_rx_notify) - (*xfer->user_cb.on_rx_notify)(sub, rdata, p_st_code, p_st_text, - res_hdr, p_body); + (*xfer->user_cb.on_rx_notify)(sub, rdata, p_st_code, p_st_text, + res_hdr, p_body); } /* @@ -591,14 +590,14 @@ static void xfer_on_evsub_client_refresh(pjsip_evsub *sub) PJ_ASSERT_ON_FAIL(xfer!=NULL, {return;}); if (xfer->user_cb.on_client_refresh) { - (*xfer->user_cb.on_client_refresh)(sub); + (*xfer->user_cb.on_client_refresh)(sub); } else { - pj_status_t status; - pjsip_tx_data *tdata; + pj_status_t status; + pjsip_tx_data *tdata; - status = pjsip_evsub_initiate(sub, NULL, PJSIP_XFER_EXPIRES, &tdata); - if (status == PJ_SUCCESS) - pjsip_xfer_send_request(sub, tdata); + status = pjsip_evsub_initiate(sub, NULL, PJSIP_XFER_EXPIRES, &tdata); + if (status == PJ_SUCCESS) + pjsip_xfer_send_request(sub, tdata); } } @@ -614,16 +613,16 @@ static void xfer_on_evsub_server_timeout(pjsip_evsub *sub) PJ_ASSERT_ON_FAIL(xfer!=NULL, {return;}); if (xfer->user_cb.on_server_timeout) { - (*xfer->user_cb.on_server_timeout)(sub); + (*xfer->user_cb.on_server_timeout)(sub); } else { - pj_status_t status; - pjsip_tx_data *tdata; - - status = pjsip_xfer_notify(sub, PJSIP_EVSUB_STATE_TERMINATED, - xfer->last_st_code, - &xfer->last_st_text, &tdata); - if (status == PJ_SUCCESS) - pjsip_xfer_send_request(sub, tdata); + pj_status_t status; + pjsip_tx_data *tdata; + + status = pjsip_xfer_notify(sub, PJSIP_EVSUB_STATE_TERMINATED, + xfer->last_st_code, + &xfer->last_st_text, &tdata); + if (status == PJ_SUCCESS) + pjsip_xfer_send_request(sub, tdata); } } diff --git a/pjsip/src/pjsip/sip_auth_aka.c b/pjsip/src/pjsip/sip_auth_aka.c index b36c7dfd45..1b15e9cbd1 100644 --- a/pjsip/src/pjsip/sip_auth_aka.c +++ b/pjsip/src/pjsip/sip_auth_aka.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,11 +34,11 @@ * Create MD5-AKA1 digest response. */ PJ_DEF(pj_status_t) pjsip_auth_create_aka_response( - pj_pool_t *pool, - const pjsip_digest_challenge *chal, - const pjsip_cred_info *cred, - const pj_str_t *method, - pjsip_digest_credential *auth) + pj_pool_t *pool, + const pjsip_digest_challenge *chal, + const pjsip_cred_info *cred, + const pj_str_t *method, + pjsip_digest_credential *auth) { pj_str_t nonce_bin; int aka_version; @@ -61,31 +60,31 @@ PJ_DEF(pj_status_t) pjsip_auth_create_aka_response( /* Check the algorithm is supported. */ if (chal->algorithm.slen==0 || pj_stricmp2(&chal->algorithm, "md5") == 0) { - /* - * A normal MD5 authentication is requested. Fallback to the usual - * MD5 digest creation. - */ - status = pjsip_auth_create_digest(&auth->response, &auth->nonce, - &auth->nc, &auth->cnonce, &auth->qop, - &auth->uri, &auth->realm, cred, method); + /* + * A normal MD5 authentication is requested. Fallback to the usual + * MD5 digest creation. + */ + status = pjsip_auth_create_digest(&auth->response, &auth->nonce, + &auth->nc, &auth->cnonce, &auth->qop, + &auth->uri, &auth->realm, cred, method); - return status; + return status; } else if (pj_stricmp(&chal->algorithm, &pjsip_AKAv1_MD5) == 0) { - /* - * AKA version 1 is requested. - */ - aka_version = 1; + /* + * AKA version 1 is requested. + */ + aka_version = 1; } else if (pj_stricmp(&chal->algorithm, &pjsip_AKAv2_MD5) == 0) { - /* - * AKA version 2 is requested. - */ - aka_version = 2; + /* + * AKA version 2 is requested. + */ + aka_version = 2; } else { - /* Unsupported algorithm */ - return PJSIP_EINVALIDALGORITHM; + /* Unsupported algorithm */ + return PJSIP_EINVALIDALGORITHM; } /* Decode nonce */ @@ -94,16 +93,16 @@ PJ_DEF(pj_status_t) pjsip_auth_create_aka_response( status = pj_base64_decode(&chal->nonce, (pj_uint8_t*)nonce_bin.ptr, &len); nonce_bin.slen = len; if (status != PJ_SUCCESS) - return PJSIP_EAUTHINNONCE; + return PJSIP_EAUTHINNONCE; if (nonce_bin.slen < PJSIP_AKA_RANDLEN + PJSIP_AKA_AUTNLEN) - return PJSIP_EAUTHINNONCE; + return PJSIP_EAUTHINNONCE; /* Get RAND, AUTN, and MAC */ chal_rand = (pj_uint8_t*)(nonce_bin.ptr + 0); chal_sqnxoraka = (pj_uint8_t*) (nonce_bin.ptr + PJSIP_AKA_RANDLEN); chal_mac = (pj_uint8_t*) (nonce_bin.ptr + PJSIP_AKA_RANDLEN + - PJSIP_AKA_SQNLEN + PJSIP_AKA_AMFLEN); + PJSIP_AKA_SQNLEN + PJSIP_AKA_AMFLEN); /* Copy k. op, and amf */ pj_bzero(k, sizeof(k)); @@ -111,11 +110,11 @@ PJ_DEF(pj_status_t) pjsip_auth_create_aka_response( pj_bzero(amf, sizeof(amf)); if (cred->ext.aka.k.slen) - pj_memcpy(k, cred->ext.aka.k.ptr, cred->ext.aka.k.slen); + pj_memcpy(k, cred->ext.aka.k.ptr, cred->ext.aka.k.slen); if (cred->ext.aka.op.slen) - pj_memcpy(op, cred->ext.aka.op.ptr, cred->ext.aka.op.slen); + pj_memcpy(op, cred->ext.aka.op.ptr, cred->ext.aka.op.slen); if (cred->ext.aka.amf.slen) - pj_memcpy(amf, cred->ext.aka.amf.ptr, cred->ext.aka.amf.slen); + pj_memcpy(amf, cred->ext.aka.amf.ptr, cred->ext.aka.amf.slen); /* Given key K and random challenge RAND, compute response RES, * confidentiality key CK, integrity key IK and anonymity key AK. @@ -124,14 +123,14 @@ PJ_DEF(pj_status_t) pjsip_auth_create_aka_response( /* Compute sequence number SQN */ for (i=0; iresponse, &chal->nonce, - &auth->nc, &auth->cnonce, &auth->qop, - &auth->uri, &chal->realm, &aka_cred, method); + status = pjsip_auth_create_digest(&auth->response, &chal->nonce, + &auth->nc, &auth->cnonce, &auth->qop, + &auth->uri, &chal->realm, &aka_cred, method); } else if (aka_version == 2) { - /* - * For AKAv2, password is base64 encoded [1] parameters: - * PRF(RES||IK||CK,"http-digest-akav2-password") - * - * The pseudo-random function (PRF) is HMAC-MD5 in this case. - */ - - pj_str_t resikck; - const pj_str_t AKAv2_Passwd = { "http-digest-akav2-password", 26 }; - pj_uint8_t hmac_digest[16]; - char tmp_buf[48]; - int hmac64_len; - - resikck.slen = PJSIP_AKA_RESLEN + PJSIP_AKA_IKLEN + PJSIP_AKA_CKLEN; - pj_assert(resikck.slen <= PJ_ARRAY_SIZE(tmp_buf)); - resikck.ptr = tmp_buf; - pj_memcpy(resikck.ptr + 0, res, PJSIP_AKA_RESLEN); - pj_memcpy(resikck.ptr + PJSIP_AKA_RESLEN, ik, PJSIP_AKA_IKLEN); - pj_memcpy(resikck.ptr + PJSIP_AKA_RESLEN + PJSIP_AKA_IKLEN, - ck, PJSIP_AKA_CKLEN); - - pj_hmac_md5((const pj_uint8_t*)AKAv2_Passwd.ptr, AKAv2_Passwd.slen, - (const pj_uint8_t*)resikck.ptr, resikck.slen, - hmac_digest); - - aka_cred.data.slen = hmac64_len = - PJ_BASE256_TO_BASE64_LEN(PJ_ARRAY_SIZE(hmac_digest)); - pj_assert(aka_cred.data.slen+1 <= PJ_ARRAY_SIZE(tmp_buf)); - aka_cred.data.ptr = tmp_buf; - pj_base64_encode(hmac_digest, PJ_ARRAY_SIZE(hmac_digest), - aka_cred.data.ptr, &len); - aka_cred.data.slen = hmac64_len; - - status = pjsip_auth_create_digest(&auth->response, &chal->nonce, - &auth->nc, &auth->cnonce, &auth->qop, - &auth->uri, &chal->realm, &aka_cred, method); + /* + * For AKAv2, password is base64 encoded [1] parameters: + * PRF(RES||IK||CK,"http-digest-akav2-password") + * + * The pseudo-random function (PRF) is HMAC-MD5 in this case. + */ + + pj_str_t resikck; + const pj_str_t AKAv2_Passwd = { "http-digest-akav2-password", 26 }; + pj_uint8_t hmac_digest[16]; + char tmp_buf[48]; + int hmac64_len; + + resikck.slen = PJSIP_AKA_RESLEN + PJSIP_AKA_IKLEN + PJSIP_AKA_CKLEN; + pj_assert(resikck.slen <= PJ_ARRAY_SIZE(tmp_buf)); + resikck.ptr = tmp_buf; + pj_memcpy(resikck.ptr + 0, res, PJSIP_AKA_RESLEN); + pj_memcpy(resikck.ptr + PJSIP_AKA_RESLEN, ik, PJSIP_AKA_IKLEN); + pj_memcpy(resikck.ptr + PJSIP_AKA_RESLEN + PJSIP_AKA_IKLEN, + ck, PJSIP_AKA_CKLEN); + + pj_hmac_md5((const pj_uint8_t*)AKAv2_Passwd.ptr, AKAv2_Passwd.slen, + (const pj_uint8_t*)resikck.ptr, resikck.slen, + hmac_digest); + + aka_cred.data.slen = hmac64_len = + PJ_BASE256_TO_BASE64_LEN(PJ_ARRAY_SIZE(hmac_digest)); + pj_assert(aka_cred.data.slen+1 <= PJ_ARRAY_SIZE(tmp_buf)); + aka_cred.data.ptr = tmp_buf; + pj_base64_encode(hmac_digest, PJ_ARRAY_SIZE(hmac_digest), + aka_cred.data.ptr, &len); + aka_cred.data.slen = hmac64_len; + + status = pjsip_auth_create_digest(&auth->response, &chal->nonce, + &auth->nc, &auth->cnonce, &auth->qop, + &auth->uri, &chal->realm, &aka_cred, method); } else { - pj_assert(!"Bug!"); - return PJ_EBUG; + pj_assert(!"Bug!"); + return PJ_EBUG; } /* Done */ @@ -201,5 +200,5 @@ PJ_DEF(pj_status_t) pjsip_auth_create_aka_response( } -#endif /* PJSIP_HAS_DIGEST_AKA_AUTH */ +#endif /* PJSIP_HAS_DIGEST_AKA_AUTH */ diff --git a/pjsip/src/pjsip/sip_auth_client.c b/pjsip/src/pjsip/sip_auth_client.c index d712e2dd34..ee2876d99d 100644 --- a/pjsip/src/pjsip/sip_auth_client.c +++ b/pjsip/src/pjsip/sip_auth_client.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -19,7 +18,7 @@ */ #include -#include /* just to get pjsip_DIGEST_STR */ +#include /* just to get pjsip_DIGEST_STR */ #include #include #include @@ -40,7 +39,7 @@ # endif #else # undef PJSIP_AUTH_HAS_DIGEST_SHA256 -# define PJSIP_AUTH_HAS_DIGEST_SHA256 0 +# define PJSIP_AUTH_HAS_DIGEST_SHA256 0 #endif #if PJSIP_AUTH_HAS_DIGEST_SHA256 @@ -60,8 +59,8 @@ #endif /* A macro just to get rid of type mismatch between char and unsigned char */ -#define MD5_APPEND(pms,buf,len) pj_md5_update(pms, (const pj_uint8_t*)buf, \ - (unsigned)len) +#define MD5_APPEND(pms,buf,len) pj_md5_update(pms, (const pj_uint8_t*)buf, \ + (unsigned)len) /* Logging. */ #define THIS_FILE "sip_auth_client.c" @@ -71,8 +70,8 @@ # define AUTH_TRACE_(expr) #endif -#define PASSWD_MASK 0x000F -#define EXT_MASK 0x00F0 +#define PASSWD_MASK 0x000F +#define EXT_MASK 0x00F0 static void dup_bin(pj_pool_t *pool, pj_str_t *dst, const pj_str_t *src) @@ -80,16 +79,16 @@ static void dup_bin(pj_pool_t *pool, pj_str_t *dst, const pj_str_t *src) dst->slen = src->slen; if (dst->slen) { - dst->ptr = (char*) pj_pool_alloc(pool, src->slen); - pj_memcpy(dst->ptr, src->ptr, src->slen); + dst->ptr = (char*) pj_pool_alloc(pool, src->slen); + pj_memcpy(dst->ptr, src->ptr, src->slen); } else { - dst->ptr = NULL; + dst->ptr = NULL; } } PJ_DEF(void) pjsip_cred_info_dup(pj_pool_t *pool, - pjsip_cred_info *dst, - const pjsip_cred_info *src) + pjsip_cred_info *dst, + const pjsip_cred_info *src) { pj_memcpy(dst, src, sizeof(pjsip_cred_info)); @@ -99,15 +98,15 @@ PJ_DEF(void) pjsip_cred_info_dup(pj_pool_t *pool, pj_strdup_with_null(pool, &dst->data, &src->data); if ((dst->data_type & EXT_MASK) == PJSIP_CRED_DATA_EXT_AKA) { - dup_bin(pool, &dst->ext.aka.k, &src->ext.aka.k); - dup_bin(pool, &dst->ext.aka.op, &src->ext.aka.op); - dup_bin(pool, &dst->ext.aka.amf, &src->ext.aka.amf); + dup_bin(pool, &dst->ext.aka.k, &src->ext.aka.k); + dup_bin(pool, &dst->ext.aka.op, &src->ext.aka.op); + dup_bin(pool, &dst->ext.aka.amf, &src->ext.aka.amf); } } PJ_DEF(int) pjsip_cred_info_cmp(const pjsip_cred_info *cred1, - const pjsip_cred_info *cred2) + const pjsip_cred_info *cred2) { int result; @@ -123,12 +122,12 @@ PJ_DEF(int) pjsip_cred_info_cmp(const pjsip_cred_info *cred1, if (result) goto on_return; if ((cred1->data_type & EXT_MASK) == PJSIP_CRED_DATA_EXT_AKA) { - result = pj_strcmp(&cred1->ext.aka.k, &cred2->ext.aka.k); - if (result) goto on_return; - result = pj_strcmp(&cred1->ext.aka.op, &cred2->ext.aka.op); - if (result) goto on_return; - result = pj_strcmp(&cred1->ext.aka.amf, &cred2->ext.aka.amf); - if (result) goto on_return; + result = pj_strcmp(&cred1->ext.aka.k, &cred2->ext.aka.k); + if (result) goto on_return; + result = pj_strcmp(&cred1->ext.aka.op, &cred2->ext.aka.op); + if (result) goto on_return; + result = pj_strcmp(&cred1->ext.aka.amf, &cred2->ext.aka.amf); + if (result) goto on_return; } on_return: @@ -136,8 +135,8 @@ PJ_DEF(int) pjsip_cred_info_cmp(const pjsip_cred_info *cred1, } PJ_DEF(void) pjsip_auth_clt_pref_dup( pj_pool_t *pool, - pjsip_auth_clt_pref *dst, - const pjsip_auth_clt_pref *src) + pjsip_auth_clt_pref *dst, + const pjsip_auth_clt_pref *src) { pj_memcpy(dst, src, sizeof(pjsip_auth_clt_pref)); pj_strdup_with_null(pool, &dst->algorithm, &src->algorithm); @@ -164,14 +163,14 @@ static void digestNtoStr(const unsigned char digest[], int n, char *output) * digest ASCII in 'result'. */ PJ_DEF(pj_status_t) pjsip_auth_create_digest( pj_str_t *result, - const pj_str_t *nonce, - const pj_str_t *nc, - const pj_str_t *cnonce, - const pj_str_t *qop, - const pj_str_t *uri, - const pj_str_t *realm, - const pjsip_cred_info *cred_info, - const pj_str_t *method) + const pj_str_t *nonce, + const pj_str_t *nc, + const pj_str_t *cnonce, + const pj_str_t *qop, + const pj_str_t *uri, + const pj_str_t *realm, + const pjsip_cred_info *cred_info, + const pj_str_t *method) { char ha1[PJSIP_MD5STRLEN]; char ha2[PJSIP_MD5STRLEN]; @@ -183,32 +182,32 @@ PJ_DEF(pj_status_t) pjsip_auth_create_digest( pj_str_t *result, AUTH_TRACE_((THIS_FILE, "Begin creating digest")); if ((cred_info->data_type & PASSWD_MASK) == PJSIP_CRED_DATA_PLAIN_PASSWD) { - /*** - *** ha1 = MD5(username ":" realm ":" password) - ***/ - pj_md5_init(&pms); - MD5_APPEND( &pms, cred_info->username.ptr, cred_info->username.slen); - MD5_APPEND( &pms, ":", 1); - MD5_APPEND( &pms, realm->ptr, realm->slen); - MD5_APPEND( &pms, ":", 1); - MD5_APPEND( &pms, cred_info->data.ptr, cred_info->data.slen); - pj_md5_final(&pms, digest); - - digestNtoStr(digest, 16, ha1); + /*** + *** ha1 = MD5(username ":" realm ":" password) + ***/ + pj_md5_init(&pms); + MD5_APPEND( &pms, cred_info->username.ptr, cred_info->username.slen); + MD5_APPEND( &pms, ":", 1); + MD5_APPEND( &pms, realm->ptr, realm->slen); + MD5_APPEND( &pms, ":", 1); + MD5_APPEND( &pms, cred_info->data.ptr, cred_info->data.slen); + pj_md5_final(&pms, digest); + + digestNtoStr(digest, 16, ha1); } else if ((cred_info->data_type & PASSWD_MASK) == PJSIP_CRED_DATA_DIGEST) { - if (cred_info->data.slen != 32) { - pj_assert(!"Invalid cred_info data length"); - pj_bzero(result->ptr, result->slen); - result->slen = 0; - return PJ_EINVAL; - } - pj_memcpy( ha1, cred_info->data.ptr, cred_info->data.slen ); + if (cred_info->data.slen != 32) { + pj_assert(!"Invalid cred_info data length"); + pj_bzero(result->ptr, result->slen); + result->slen = 0; + return PJ_EINVAL; + } + pj_memcpy( ha1, cred_info->data.ptr, cred_info->data.slen ); } else { - pj_assert(!"Invalid data_type"); - pj_bzero(result->ptr, result->slen); - result->slen = 0; - return PJ_EINVAL; + pj_assert(!"Invalid data_type"); + pj_bzero(result->ptr, result->slen); + result->slen = 0; + return PJ_EINVAL; } AUTH_TRACE_((THIS_FILE, " ha1=%.32s", ha1)); @@ -237,12 +236,12 @@ PJ_DEF(pj_status_t) pjsip_auth_create_digest( pj_str_t *result, MD5_APPEND( &pms, ":", 1); MD5_APPEND( &pms, nonce->ptr, nonce->slen); if (qop && qop->slen != 0) { - MD5_APPEND( &pms, ":", 1); - MD5_APPEND( &pms, nc->ptr, nc->slen); - MD5_APPEND( &pms, ":", 1); - MD5_APPEND( &pms, cnonce->ptr, cnonce->slen); - MD5_APPEND( &pms, ":", 1); - MD5_APPEND( &pms, qop->ptr, qop->slen); + MD5_APPEND( &pms, ":", 1); + MD5_APPEND( &pms, nc->ptr, nc->slen); + MD5_APPEND( &pms, ":", 1); + MD5_APPEND( &pms, cnonce->ptr, cnonce->slen); + MD5_APPEND( &pms, ":", 1); + MD5_APPEND( &pms, qop->ptr, qop->slen); } MD5_APPEND( &pms, ":", 1); MD5_APPEND( &pms, ha2, PJSIP_MD5STRLEN); @@ -265,14 +264,14 @@ PJ_DEF(pj_status_t) pjsip_auth_create_digest( pj_str_t *result, * digest ASCII in 'result'. */ PJ_DEF(pj_status_t) pjsip_auth_create_digestSHA256(pj_str_t *result, - const pj_str_t *nonce, - const pj_str_t *nc, - const pj_str_t *cnonce, - const pj_str_t *qop, - const pj_str_t *uri, - const pj_str_t *realm, - const pjsip_cred_info *cred_info, - const pj_str_t *method) + const pj_str_t *nonce, + const pj_str_t *nc, + const pj_str_t *cnonce, + const pj_str_t *qop, + const pj_str_t *uri, + const pj_str_t *realm, + const pjsip_cred_info *cred_info, + const pj_str_t *method) { #if PJSIP_AUTH_HAS_DIGEST_SHA256 @@ -293,7 +292,7 @@ PJ_DEF(pj_status_t) pjsip_auth_create_digestSHA256(pj_str_t *result, #if OPENSSL_VERSION_NUMBER >= 0x30000000L md = EVP_get_digestbyname("SHA256"); if (md == NULL) { - return PJ_ENOTSUP; + return PJ_ENOTSUP; } #endif @@ -301,46 +300,46 @@ PJ_DEF(pj_status_t) pjsip_auth_create_digestSHA256(pj_str_t *result, if ((cred_info->data_type & PASSWD_MASK) == PJSIP_CRED_DATA_PLAIN_PASSWD) { - /*** - *** ha1 = SHA256(username ":" realm ":" password) - ***/ + /*** + *** ha1 = SHA256(username ":" realm ":" password) + ***/ #if OPENSSL_VERSION_NUMBER < 0x30000000L - SHA256_Init(&pms); - SHA256_Update( &pms, cred_info->username.ptr, - cred_info->username.slen); - SHA256_Update( &pms, ":", 1); - SHA256_Update( &pms, realm->ptr, realm->slen); - SHA256_Update( &pms, ":", 1); - SHA256_Update( &pms, cred_info->data.ptr, cred_info->data.slen); - SHA256_Final(digest, &pms); + SHA256_Init(&pms); + SHA256_Update( &pms, cred_info->username.ptr, + cred_info->username.slen); + SHA256_Update( &pms, ":", 1); + SHA256_Update( &pms, realm->ptr, realm->slen); + SHA256_Update( &pms, ":", 1); + SHA256_Update( &pms, cred_info->data.ptr, cred_info->data.slen); + SHA256_Final(digest, &pms); #else - mdctx = EVP_MD_CTX_new(); - EVP_DigestInit_ex(mdctx, md, NULL); - EVP_DigestUpdate(mdctx, cred_info->username.ptr, cred_info->username.slen); - EVP_DigestUpdate(mdctx, ":", 1); - EVP_DigestUpdate(mdctx, realm->ptr, realm->slen); - EVP_DigestUpdate(mdctx, ":", 1); - EVP_DigestUpdate(mdctx, cred_info->data.ptr, cred_info->data.slen); - - EVP_DigestFinal_ex(mdctx, digest, &dig_len); - EVP_MD_CTX_free(mdctx); + mdctx = EVP_MD_CTX_new(); + EVP_DigestInit_ex(mdctx, md, NULL); + EVP_DigestUpdate(mdctx, cred_info->username.ptr, cred_info->username.slen); + EVP_DigestUpdate(mdctx, ":", 1); + EVP_DigestUpdate(mdctx, realm->ptr, realm->slen); + EVP_DigestUpdate(mdctx, ":", 1); + EVP_DigestUpdate(mdctx, cred_info->data.ptr, cred_info->data.slen); + + EVP_DigestFinal_ex(mdctx, digest, &dig_len); + EVP_MD_CTX_free(mdctx); #endif - digestNtoStr(digest, 32, ha1); + digestNtoStr(digest, 32, ha1); } else if ((cred_info->data_type & PASSWD_MASK) == PJSIP_CRED_DATA_DIGEST) { - if (cred_info->data.slen != 64) { - pj_assert(!"Invalid cred_info data length"); - pj_bzero(result->ptr, result->slen); - result->slen = 0; - return PJ_EINVAL; - } - pj_memcpy( ha1, cred_info->data.ptr, cred_info->data.slen ); + if (cred_info->data.slen != 64) { + pj_assert(!"Invalid cred_info data length"); + pj_bzero(result->ptr, result->slen); + result->slen = 0; + return PJ_EINVAL; + } + pj_memcpy( ha1, cred_info->data.ptr, cred_info->data.slen ); } else { - pj_assert(!"Invalid data_type"); - pj_bzero(result->ptr, result->slen); - result->slen = 0; - return PJ_EINVAL; + pj_assert(!"Invalid data_type"); + pj_bzero(result->ptr, result->slen); + result->slen = 0; + return PJ_EINVAL; } AUTH_TRACE_((THIS_FILE, " ha1=%.64s", ha1)); @@ -380,12 +379,12 @@ PJ_DEF(pj_status_t) pjsip_auth_create_digestSHA256(pj_str_t *result, SHA256_Update( &pms, ":", 1); SHA256_Update( &pms, nonce->ptr, nonce->slen); if (qop && qop->slen != 0) { - SHA256_Update( &pms, ":", 1); - SHA256_Update( &pms, nc->ptr, nc->slen); - SHA256_Update( &pms, ":", 1); - SHA256_Update( &pms, cnonce->ptr, cnonce->slen); - SHA256_Update( &pms, ":", 1); - SHA256_Update( &pms, qop->ptr, qop->slen); + SHA256_Update( &pms, ":", 1); + SHA256_Update( &pms, nc->ptr, nc->slen); + SHA256_Update( &pms, ":", 1); + SHA256_Update( &pms, cnonce->ptr, cnonce->slen); + SHA256_Update( &pms, ":", 1); + SHA256_Update( &pms, qop->ptr, qop->slen); } SHA256_Update( &pms, ":", 1); SHA256_Update( &pms, ha2, PJSIP_SHA256STRLEN); @@ -399,12 +398,12 @@ PJ_DEF(pj_status_t) pjsip_auth_create_digestSHA256(pj_str_t *result, EVP_DigestUpdate(mdctx, ":", 1); EVP_DigestUpdate(mdctx, nonce->ptr, nonce->slen); if (qop && qop->slen != 0) { - EVP_DigestUpdate(mdctx, ":", 1); - EVP_DigestUpdate(mdctx, nc->ptr, nc->slen); - EVP_DigestUpdate(mdctx, ":", 1); - EVP_DigestUpdate(mdctx, cnonce->ptr, cnonce->slen); - EVP_DigestUpdate(mdctx, ":", 1); - EVP_DigestUpdate(mdctx, qop->ptr, qop->slen); + EVP_DigestUpdate(mdctx, ":", 1); + EVP_DigestUpdate(mdctx, nc->ptr, nc->slen); + EVP_DigestUpdate(mdctx, ":", 1); + EVP_DigestUpdate(mdctx, cnonce->ptr, cnonce->slen); + EVP_DigestUpdate(mdctx, ":", 1); + EVP_DigestUpdate(mdctx, qop->ptr, qop->slen); } EVP_DigestUpdate(mdctx, ":", 1); EVP_DigestUpdate(mdctx, ha2, PJSIP_SHA256STRLEN); @@ -445,21 +444,21 @@ static pj_bool_t has_auth_qop( pj_pool_t *pool, const pj_str_t *qop_offer) pj_strdup_with_null( pool, &qop, qop_offer); p = qop.ptr; while (*p) { - *p = (char)pj_tolower(*p); - ++p; + *p = (char)pj_tolower(*p); + ++p; } p = qop.ptr; while (*p) { - if (*p=='a' && *(p+1)=='u' && *(p+2)=='t' && *(p+3)=='h') { - int e = *(p+4); - if (e=='"' || e==',' || e==0) - return PJ_TRUE; - else - p += 4; - } else { - ++p; - } + if (*p=='a' && *(p+1)=='u' && *(p+2)=='t' && *(p+3)=='h') { + int e = *(p+4); + if (e=='"' || e==',' || e==0) + return PJ_TRUE; + else + p += 4; + } else { + ++p; + } } return PJ_FALSE; @@ -475,13 +474,13 @@ static pj_bool_t has_auth_qop( pj_pool_t *pool, const pj_str_t *qop_offer) * The pool is used to allocate 32 bytes to store the digest in cred->response. */ static pj_status_t respond_digest( pj_pool_t *pool, - pjsip_digest_credential *cred, - const pjsip_digest_challenge *chal, - const pj_str_t *uri, - const pjsip_cred_info *cred_info, - const pj_str_t *cnonce, - pj_uint32_t nc, - const pj_str_t *method) + pjsip_digest_credential *cred, + const pjsip_digest_challenge *chal, + const pj_str_t *uri, + const pjsip_cred_info *cred_info, + const pj_str_t *cnonce, + pj_uint32_t nc, + const pj_str_t *method) { const pj_str_t pjsip_AKAv1_MD5_STR = { "AKAv1-MD5", 9 }; pj_bool_t algo_sha256 = PJ_FALSE; @@ -495,16 +494,16 @@ static pj_status_t respond_digest( pj_pool_t *pool, /* Check algorithm is supported. We support MD5, AKAv1-MD5, and SHA256. */ if (chal->algorithm.slen==0 || (algo_sha256 || - pj_stricmp(&chal->algorithm, &pjsip_MD5_STR)==0 || + pj_stricmp(&chal->algorithm, &pjsip_MD5_STR)==0 || pj_stricmp(&chal->algorithm, &pjsip_AKAv1_MD5_STR)==0)) { - PJ_LOG(4,(THIS_FILE, "Digest algorithm is \"%.*s\"", - chal->algorithm.slen, chal->algorithm.ptr)); + PJ_LOG(4,(THIS_FILE, "Digest algorithm is \"%.*s\"", + chal->algorithm.slen, chal->algorithm.ptr)); } else { - PJ_LOG(4,(THIS_FILE, "Unsupported digest algorithm \"%.*s\"", - chal->algorithm.slen, chal->algorithm.ptr)); - return PJSIP_EINVALIDALGORITHM; + PJ_LOG(4,(THIS_FILE, "Unsupported digest algorithm \"%.*s\"", + chal->algorithm.slen, chal->algorithm.ptr)); + return PJSIP_EINVALIDALGORITHM; } /* Build digest credential from arguments. */ @@ -520,70 +519,70 @@ static pj_status_t respond_digest( pj_pool_t *pool, cred->response.ptr = (char*) pj_pool_alloc(pool, cred->response.slen); if (chal->qop.slen == 0) { - /* Server doesn't require quality of protection. */ - - if ((cred_info->data_type & EXT_MASK) == PJSIP_CRED_DATA_EXT_AKA) { - /* Call application callback to create the response digest */ - return (*cred_info->ext.aka.cb)(pool, chal, cred_info, - method, cred); - } - else { - /* Convert digest to string and store in chal->response. */ - if (algo_sha256) { - status = pjsip_auth_create_digestSHA256( - &cred->response, &cred->nonce, NULL, - NULL, NULL, uri, &chal->realm, - cred_info, method); - } else { - status = pjsip_auth_create_digest( &cred->response, - &cred->nonce, NULL, NULL, NULL, uri, - &chal->realm, cred_info, method); - } - } + /* Server doesn't require quality of protection. */ + + if ((cred_info->data_type & EXT_MASK) == PJSIP_CRED_DATA_EXT_AKA) { + /* Call application callback to create the response digest */ + return (*cred_info->ext.aka.cb)(pool, chal, cred_info, + method, cred); + } + else { + /* Convert digest to string and store in chal->response. */ + if (algo_sha256) { + status = pjsip_auth_create_digestSHA256( + &cred->response, &cred->nonce, NULL, + NULL, NULL, uri, &chal->realm, + cred_info, method); + } else { + status = pjsip_auth_create_digest( &cred->response, + &cred->nonce, NULL, NULL, NULL, uri, + &chal->realm, cred_info, method); + } + } } else if (has_auth_qop(pool, &chal->qop)) { - /* Server requires quality of protection. - * We respond with selecting "qop=auth" protection. - */ - cred->qop = pjsip_AUTH_STR; - cred->nc.ptr = (char*) pj_pool_alloc(pool, 16); - cred->nc.slen = pj_ansi_snprintf(cred->nc.ptr, 16, "%08u", nc); - - if (cnonce && cnonce->slen) { - pj_strdup(pool, &cred->cnonce, cnonce); - } else { - pj_str_t dummy_cnonce = { "b39971", 6}; - pj_strdup(pool, &cred->cnonce, &dummy_cnonce); - } - - if ((cred_info->data_type & EXT_MASK) == PJSIP_CRED_DATA_EXT_AKA) { - /* Call application callback to create the response digest */ - return (*cred_info->ext.aka.cb)(pool, chal, cred_info, - method, cred); - } - else { - /* Convert digest to string and store in chal->response. */ - if (algo_sha256) { - status = pjsip_auth_create_digestSHA256( - &cred->response, &cred->nonce, - &cred->nc, &cred->cnonce, - &pjsip_AUTH_STR, uri, - &chal->realm, cred_info, - method); - } else { - status = pjsip_auth_create_digest( &cred->response, - &cred->nonce, &cred->nc, - &cred->cnonce, &pjsip_AUTH_STR, - uri, &chal->realm, - cred_info, method); - } - } + /* Server requires quality of protection. + * We respond with selecting "qop=auth" protection. + */ + cred->qop = pjsip_AUTH_STR; + cred->nc.ptr = (char*) pj_pool_alloc(pool, 16); + cred->nc.slen = pj_ansi_snprintf(cred->nc.ptr, 16, "%08u", nc); + + if (cnonce && cnonce->slen) { + pj_strdup(pool, &cred->cnonce, cnonce); + } else { + pj_str_t dummy_cnonce = { "b39971", 6}; + pj_strdup(pool, &cred->cnonce, &dummy_cnonce); + } + + if ((cred_info->data_type & EXT_MASK) == PJSIP_CRED_DATA_EXT_AKA) { + /* Call application callback to create the response digest */ + return (*cred_info->ext.aka.cb)(pool, chal, cred_info, + method, cred); + } + else { + /* Convert digest to string and store in chal->response. */ + if (algo_sha256) { + status = pjsip_auth_create_digestSHA256( + &cred->response, &cred->nonce, + &cred->nc, &cred->cnonce, + &pjsip_AUTH_STR, uri, + &chal->realm, cred_info, + method); + } else { + status = pjsip_auth_create_digest( &cred->response, + &cred->nonce, &cred->nc, + &cred->cnonce, &pjsip_AUTH_STR, + uri, &chal->realm, + cred_info, method); + } + } } else { - /* Server requires quality protection that we don't support. */ - PJ_LOG(4,(THIS_FILE, "Unsupported qop offer %.*s", - chal->qop.slen, chal->qop.ptr)); - return PJSIP_EINVALIDQOP; + /* Server requires quality protection that we don't support. */ + PJ_LOG(4,(THIS_FILE, "Unsupported qop offer %.*s", + chal->qop.slen, chal->qop.ptr)); + return PJSIP_EINVALIDQOP; } return status; @@ -594,109 +593,109 @@ static pj_status_t respond_digest( pj_pool_t *pool, * Update authentication session with a challenge. */ static void update_digest_session( pjsip_cached_auth *cached_auth, - const pjsip_www_authenticate_hdr *hdr ) + const pjsip_www_authenticate_hdr *hdr ) { if (hdr->challenge.digest.qop.slen == 0) { #if PJSIP_AUTH_AUTO_SEND_NEXT!=0 - if (!cached_auth->last_chal || pj_stricmp2(&hdr->scheme, "digest")) { - cached_auth->last_chal = (pjsip_www_authenticate_hdr*) - pjsip_hdr_clone(cached_auth->pool, hdr); - } else { - /* Only update if the new challenge is "significantly different" - * than the one in the cache, to reduce memory usage. - */ - const pjsip_digest_challenge *d1 = - &cached_auth->last_chal->challenge.digest; - const pjsip_digest_challenge *d2 = &hdr->challenge.digest; - - if (pj_strcmp(&d1->domain, &d2->domain) || - pj_strcmp(&d1->realm, &d2->realm) || - pj_strcmp(&d1->nonce, &d2->nonce) || - pj_strcmp(&d1->opaque, &d2->opaque) || - pj_strcmp(&d1->algorithm, &d2->algorithm) || - pj_strcmp(&d1->qop, &d2->qop)) - { - cached_auth->last_chal = (pjsip_www_authenticate_hdr*) - pjsip_hdr_clone(cached_auth->pool, hdr); - } - } + if (!cached_auth->last_chal || pj_stricmp2(&hdr->scheme, "digest")) { + cached_auth->last_chal = (pjsip_www_authenticate_hdr*) + pjsip_hdr_clone(cached_auth->pool, hdr); + } else { + /* Only update if the new challenge is "significantly different" + * than the one in the cache, to reduce memory usage. + */ + const pjsip_digest_challenge *d1 = + &cached_auth->last_chal->challenge.digest; + const pjsip_digest_challenge *d2 = &hdr->challenge.digest; + + if (pj_strcmp(&d1->domain, &d2->domain) || + pj_strcmp(&d1->realm, &d2->realm) || + pj_strcmp(&d1->nonce, &d2->nonce) || + pj_strcmp(&d1->opaque, &d2->opaque) || + pj_strcmp(&d1->algorithm, &d2->algorithm) || + pj_strcmp(&d1->qop, &d2->qop)) + { + cached_auth->last_chal = (pjsip_www_authenticate_hdr*) + pjsip_hdr_clone(cached_auth->pool, hdr); + } + } #endif - return; + return; } /* Initialize cnonce and qop if not present. */ if (cached_auth->cnonce.slen == 0) { - /* Save the whole challenge */ - cached_auth->last_chal = (pjsip_www_authenticate_hdr*) - pjsip_hdr_clone(cached_auth->pool, hdr); + /* Save the whole challenge */ + cached_auth->last_chal = (pjsip_www_authenticate_hdr*) + pjsip_hdr_clone(cached_auth->pool, hdr); - /* Create cnonce */ - pj_create_unique_string( cached_auth->pool, &cached_auth->cnonce ); + /* Create cnonce */ + pj_create_unique_string( cached_auth->pool, &cached_auth->cnonce ); #if defined(PJSIP_AUTH_CNONCE_USE_DIGITS_ONLY) && \ PJSIP_AUTH_CNONCE_USE_DIGITS_ONLY!=0 - if (pj_strchr(&cached_auth->cnonce, '-')) { - /* remove hyphen character. */ - pj_size_t w, r, len = pj_strlen(&cached_auth->cnonce); - char *s = cached_auth->cnonce.ptr; - - w = r = 0; - for (; r < len; r++) { - if (s[r] != '-') - s[w++] = s[r]; - } - s[w] = '\0'; - cached_auth->cnonce.slen = w; - } + if (pj_strchr(&cached_auth->cnonce, '-')) { + /* remove hyphen character. */ + pj_size_t w, r, len = pj_strlen(&cached_auth->cnonce); + char *s = cached_auth->cnonce.ptr; + + w = r = 0; + for (; r < len; r++) { + if (s[r] != '-') + s[w++] = s[r]; + } + s[w] = '\0'; + cached_auth->cnonce.slen = w; + } #endif - /* Initialize nonce-count */ - cached_auth->nc = 1; + /* Initialize nonce-count */ + cached_auth->nc = 1; - /* Save realm. */ - /* Note: allow empty realm (https://github.com/pjsip/pjproject/issues/1061) - pj_assert(cached_auth->realm.slen != 0); - */ - if (cached_auth->realm.slen == 0) { - pj_strdup(cached_auth->pool, &cached_auth->realm, - &hdr->challenge.digest.realm); - } + /* Save realm. */ + /* Note: allow empty realm (https://github.com/pjsip/pjproject/issues/1061) + pj_assert(cached_auth->realm.slen != 0); + */ + if (cached_auth->realm.slen == 0) { + pj_strdup(cached_auth->pool, &cached_auth->realm, + &hdr->challenge.digest.realm); + } } else { - /* Update last_nonce and nonce-count */ - if (!pj_strcmp(&hdr->challenge.digest.nonce, - &cached_auth->last_chal->challenge.digest.nonce)) - { - /* Same nonce, increment nonce-count */ - ++cached_auth->nc; - } else { - /* Server gives new nonce. */ - pj_strdup(cached_auth->pool, - &cached_auth->last_chal->challenge.digest.nonce, - &hdr->challenge.digest.nonce); - /* Has the opaque changed? */ - if (pj_strcmp(&cached_auth->last_chal->challenge.digest.opaque, - &hdr->challenge.digest.opaque)) - { - pj_strdup(cached_auth->pool, - &cached_auth->last_chal->challenge.digest.opaque, - &hdr->challenge.digest.opaque); - } - cached_auth->nc = 1; - } + /* Update last_nonce and nonce-count */ + if (!pj_strcmp(&hdr->challenge.digest.nonce, + &cached_auth->last_chal->challenge.digest.nonce)) + { + /* Same nonce, increment nonce-count */ + ++cached_auth->nc; + } else { + /* Server gives new nonce. */ + pj_strdup(cached_auth->pool, + &cached_auth->last_chal->challenge.digest.nonce, + &hdr->challenge.digest.nonce); + /* Has the opaque changed? */ + if (pj_strcmp(&cached_auth->last_chal->challenge.digest.opaque, + &hdr->challenge.digest.opaque)) + { + pj_strdup(cached_auth->pool, + &cached_auth->last_chal->challenge.digest.opaque, + &hdr->challenge.digest.opaque); + } + cached_auth->nc = 1; + } } } -#endif /* PJSIP_AUTH_QOP_SUPPORT */ +#endif /* PJSIP_AUTH_QOP_SUPPORT */ /* Find cached authentication in the list for the specified realm. */ static pjsip_cached_auth *find_cached_auth( pjsip_auth_clt_sess *sess, - const pj_str_t *realm ) + const pj_str_t *realm ) { pjsip_cached_auth *auth = sess->cached_auth.next; while (auth != &sess->cached_auth) { - if (pj_stricmp(&auth->realm, realm) == 0) - return auth; - auth = auth->next; + if (pj_stricmp(&auth->realm, realm) == 0) + return auth; + auth = auth->next; } return NULL; @@ -704,8 +703,8 @@ static pjsip_cached_auth *find_cached_auth( pjsip_auth_clt_sess *sess, /* Find credential to use for the specified realm and auth scheme. */ static const pjsip_cred_info* auth_find_cred( const pjsip_auth_clt_sess *sess, - const pj_str_t *realm, - const pj_str_t *auth_scheme) + const pj_str_t *realm, + const pj_str_t *auth_scheme) { unsigned i; int wildcard = -1; @@ -713,20 +712,20 @@ static const pjsip_cred_info* auth_find_cred( const pjsip_auth_clt_sess *sess, PJ_UNUSED_ARG(auth_scheme); for (i=0; icred_cnt; ++i) { - if (pj_stricmp(&sess->cred_info[i].realm, realm) == 0) - return &sess->cred_info[i]; - else if (sess->cred_info[i].realm.slen == 1 && - sess->cred_info[i].realm.ptr[0] == '*') - { - wildcard = i; - } + if (pj_stricmp(&sess->cred_info[i].realm, realm) == 0) + return &sess->cred_info[i]; + else if (sess->cred_info[i].realm.slen == 1 && + sess->cred_info[i].realm.ptr[0] == '*') + { + wildcard = i; + } } /* No matching realm. See if we have credential with wildcard ('*') * as the realm. */ if (wildcard != -1) - return &sess->cred_info[wildcard]; + return &sess->cred_info[wildcard]; /* Nothing is suitable */ return NULL; @@ -735,9 +734,9 @@ static const pjsip_cred_info* auth_find_cred( const pjsip_auth_clt_sess *sess, /* Init client session. */ PJ_DEF(pj_status_t) pjsip_auth_clt_init( pjsip_auth_clt_sess *sess, - pjsip_endpoint *endpt, - pj_pool_t *pool, - unsigned options) + pjsip_endpoint *endpt, + pj_pool_t *pool, + unsigned options) { PJ_ASSERT_RETURN(sess && endpt && pool && (options==0), PJ_EINVAL); @@ -760,8 +759,8 @@ PJ_DEF(pj_status_t) pjsip_auth_clt_deinit(pjsip_auth_clt_sess *sess) auth = sess->cached_auth.next; while (auth != &sess->cached_auth) { - pjsip_endpt_release_pool(sess->endpt, auth->pool); - auth = auth->next; + pjsip_endpt_release_pool(sess->endpt, auth->pool); + auth = auth->next; } return PJ_SUCCESS; @@ -770,8 +769,8 @@ PJ_DEF(pj_status_t) pjsip_auth_clt_deinit(pjsip_auth_clt_sess *sess) /* Clone session. */ PJ_DEF(pj_status_t) pjsip_auth_clt_clone( pj_pool_t *pool, - pjsip_auth_clt_sess *sess, - const pjsip_auth_clt_sess *rhs ) + pjsip_auth_clt_sess *sess, + const pjsip_auth_clt_sess *rhs ) { unsigned i; @@ -781,15 +780,15 @@ PJ_DEF(pj_status_t) pjsip_auth_clt_clone( pj_pool_t *pool, sess->cred_cnt = rhs->cred_cnt; sess->cred_info = (pjsip_cred_info*) - pj_pool_alloc(pool, - sess->cred_cnt*sizeof(pjsip_cred_info)); + pj_pool_alloc(pool, + sess->cred_cnt*sizeof(pjsip_cred_info)); for (i=0; icred_cnt; ++i) { - pj_strdup(pool, &sess->cred_info[i].realm, &rhs->cred_info[i].realm); - pj_strdup(pool, &sess->cred_info[i].scheme, &rhs->cred_info[i].scheme); - pj_strdup(pool, &sess->cred_info[i].username, - &rhs->cred_info[i].username); - sess->cred_info[i].data_type = rhs->cred_info[i].data_type; - pj_strdup(pool, &sess->cred_info[i].data, &rhs->cred_info[i].data); + pj_strdup(pool, &sess->cred_info[i].realm, &rhs->cred_info[i].realm); + pj_strdup(pool, &sess->cred_info[i].scheme, &rhs->cred_info[i].scheme); + pj_strdup(pool, &sess->cred_info[i].username, + &rhs->cred_info[i].username); + sess->cred_info[i].data_type = rhs->cred_info[i].data_type; + pj_strdup(pool, &sess->cred_info[i].data, &rhs->cred_info[i].data); } /* TODO note: @@ -807,62 +806,62 @@ PJ_DEF(pj_status_t) pjsip_auth_clt_clone( pj_pool_t *pool, /* Set client credentials. */ PJ_DEF(pj_status_t) pjsip_auth_clt_set_credentials( pjsip_auth_clt_sess *sess, - int cred_cnt, - const pjsip_cred_info *c) + int cred_cnt, + const pjsip_cred_info *c) { PJ_ASSERT_RETURN(sess && c, PJ_EINVAL); if (cred_cnt == 0) { - sess->cred_cnt = 0; + sess->cred_cnt = 0; } else { - int i; - sess->cred_info = (pjsip_cred_info*) - pj_pool_alloc(sess->pool, cred_cnt * sizeof(*c)); - for (i=0; icred_info[i].data_type = c[i].data_type; + int i; + sess->cred_info = (pjsip_cred_info*) + pj_pool_alloc(sess->pool, cred_cnt * sizeof(*c)); + for (i=0; icred_info[i].data_type = c[i].data_type; - /* When data_type is PJSIP_CRED_DATA_EXT_AKA, - * callback must be specified. - */ - if ((c[i].data_type & EXT_MASK) == PJSIP_CRED_DATA_EXT_AKA) { + /* When data_type is PJSIP_CRED_DATA_EXT_AKA, + * callback must be specified. + */ + if ((c[i].data_type & EXT_MASK) == PJSIP_CRED_DATA_EXT_AKA) { #if !PJSIP_HAS_DIGEST_AKA_AUTH - if (!PJSIP_HAS_DIGEST_AKA_AUTH) { - pj_assert(!"PJSIP_HAS_DIGEST_AKA_AUTH is not enabled"); - return PJSIP_EAUTHINAKACRED; - } + if (!PJSIP_HAS_DIGEST_AKA_AUTH) { + pj_assert(!"PJSIP_HAS_DIGEST_AKA_AUTH is not enabled"); + return PJSIP_EAUTHINAKACRED; + } #endif - /* Callback must be specified */ - PJ_ASSERT_RETURN(c[i].ext.aka.cb != NULL, PJ_EINVAL); - - /* Verify K len */ - PJ_ASSERT_RETURN(c[i].ext.aka.k.slen <= PJSIP_AKA_KLEN, - PJSIP_EAUTHINAKACRED); - - /* Verify OP len */ - PJ_ASSERT_RETURN(c[i].ext.aka.op.slen <= PJSIP_AKA_OPLEN, - PJSIP_EAUTHINAKACRED); - - /* Verify AMF len */ - PJ_ASSERT_RETURN(c[i].ext.aka.amf.slen <= PJSIP_AKA_AMFLEN, - PJSIP_EAUTHINAKACRED); - - sess->cred_info[i].ext.aka.cb = c[i].ext.aka.cb; - pj_strdup(sess->pool, &sess->cred_info[i].ext.aka.k, - &c[i].ext.aka.k); - pj_strdup(sess->pool, &sess->cred_info[i].ext.aka.op, - &c[i].ext.aka.op); - pj_strdup(sess->pool, &sess->cred_info[i].ext.aka.amf, - &c[i].ext.aka.amf); - } - - pj_strdup(sess->pool, &sess->cred_info[i].scheme, &c[i].scheme); - pj_strdup(sess->pool, &sess->cred_info[i].realm, &c[i].realm); - pj_strdup(sess->pool, &sess->cred_info[i].username, &c[i].username); - pj_strdup(sess->pool, &sess->cred_info[i].data, &c[i].data); - } - sess->cred_cnt = cred_cnt; + /* Callback must be specified */ + PJ_ASSERT_RETURN(c[i].ext.aka.cb != NULL, PJ_EINVAL); + + /* Verify K len */ + PJ_ASSERT_RETURN(c[i].ext.aka.k.slen <= PJSIP_AKA_KLEN, + PJSIP_EAUTHINAKACRED); + + /* Verify OP len */ + PJ_ASSERT_RETURN(c[i].ext.aka.op.slen <= PJSIP_AKA_OPLEN, + PJSIP_EAUTHINAKACRED); + + /* Verify AMF len */ + PJ_ASSERT_RETURN(c[i].ext.aka.amf.slen <= PJSIP_AKA_AMFLEN, + PJSIP_EAUTHINAKACRED); + + sess->cred_info[i].ext.aka.cb = c[i].ext.aka.cb; + pj_strdup(sess->pool, &sess->cred_info[i].ext.aka.k, + &c[i].ext.aka.k); + pj_strdup(sess->pool, &sess->cred_info[i].ext.aka.op, + &c[i].ext.aka.op); + pj_strdup(sess->pool, &sess->cred_info[i].ext.aka.amf, + &c[i].ext.aka.amf); + } + + pj_strdup(sess->pool, &sess->cred_info[i].scheme, &c[i].scheme); + pj_strdup(sess->pool, &sess->cred_info[i].realm, &c[i].realm); + pj_strdup(sess->pool, &sess->cred_info[i].username, &c[i].username); + pj_strdup(sess->pool, &sess->cred_info[i].data, &c[i].data); + } + sess->cred_cnt = cred_cnt; } return PJ_SUCCESS; @@ -873,14 +872,14 @@ PJ_DEF(pj_status_t) pjsip_auth_clt_set_credentials( pjsip_auth_clt_sess *sess, * Set the preference for the client authentication session. */ PJ_DEF(pj_status_t) pjsip_auth_clt_set_prefs(pjsip_auth_clt_sess *sess, - const pjsip_auth_clt_pref *p) + const pjsip_auth_clt_pref *p) { PJ_ASSERT_RETURN(sess && p, PJ_EINVAL); pj_memcpy(&sess->pref, p, sizeof(*p)); pj_strdup(sess->pool, &sess->pref.algorithm, &p->algorithm); //if (sess->pref.algorithm.slen == 0) - // sess->pref.algorithm = pj_str("MD5"); + // sess->pref.algorithm = pj_str("MD5"); return PJ_SUCCESS; } @@ -890,7 +889,7 @@ PJ_DEF(pj_status_t) pjsip_auth_clt_set_prefs(pjsip_auth_clt_sess *sess, * Get the preference for the client authentication session. */ PJ_DEF(pj_status_t) pjsip_auth_clt_get_prefs(pjsip_auth_clt_sess *sess, - pjsip_auth_clt_pref *p) + pjsip_auth_clt_pref *p) { PJ_ASSERT_RETURN(sess && p, PJ_EINVAL); @@ -904,13 +903,13 @@ PJ_DEF(pj_status_t) pjsip_auth_clt_get_prefs(pjsip_auth_clt_sess *sess, * in WWW-Authenticate/Proxy-Authenticate header. */ static pj_status_t auth_respond( pj_pool_t *req_pool, - const pjsip_www_authenticate_hdr *hdr, - const pjsip_uri *uri, - const pjsip_cred_info *cred_info, - const pjsip_method *method, - pj_pool_t *sess_pool, - pjsip_cached_auth *cached_auth, - pjsip_authorization_hdr **p_h_auth) + const pjsip_www_authenticate_hdr *hdr, + const pjsip_uri *uri, + const pjsip_cred_info *cred_info, + const pjsip_method *method, + pj_pool_t *sess_pool, + pjsip_cached_auth *cached_auth, + pjsip_authorization_hdr **p_h_auth) { pjsip_authorization_hdr *hauth; char tmp[PJSIP_MAX_URL_SIZE]; @@ -920,72 +919,72 @@ static pj_status_t auth_respond( pj_pool_t *req_pool, /* Verify arguments. */ PJ_ASSERT_RETURN(req_pool && hdr && uri && cred_info && method && - sess_pool && cached_auth && p_h_auth, PJ_EINVAL); + sess_pool && cached_auth && p_h_auth, PJ_EINVAL); /* Print URL in the original request. */ uri_str.ptr = tmp; uri_str.slen = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, tmp,sizeof(tmp)); if (uri_str.slen < 1) { - return PJSIP_EURITOOLONG; + return PJSIP_EURITOOLONG; } # if (PJSIP_AUTH_HEADER_CACHING) { - pool = sess_pool; - PJ_UNUSED_ARG(req_pool); + pool = sess_pool; + PJ_UNUSED_ARG(req_pool); } # else { - pool = req_pool; - PJ_UNUSED_ARG(sess_pool); + pool = req_pool; + PJ_UNUSED_ARG(sess_pool); } # endif if (hdr->type == PJSIP_H_WWW_AUTHENTICATE) - hauth = pjsip_authorization_hdr_create(pool); + hauth = pjsip_authorization_hdr_create(pool); else if (hdr->type == PJSIP_H_PROXY_AUTHENTICATE) - hauth = pjsip_proxy_authorization_hdr_create(pool); + hauth = pjsip_proxy_authorization_hdr_create(pool); else { - return PJSIP_EINVALIDHDR; + return PJSIP_EINVALIDHDR; } /* Only support digest scheme at the moment. */ if (!pj_stricmp(&hdr->scheme, &pjsip_DIGEST_STR)) { - pj_str_t *cnonce = NULL; - pj_uint32_t nc = 1; - - /* Update the session (nonce-count etc) if required. */ -# if PJSIP_AUTH_QOP_SUPPORT - { - if (cached_auth) { - update_digest_session( cached_auth, hdr ); - - cnonce = &cached_auth->cnonce; - nc = cached_auth->nc; - } - } -# endif /* PJSIP_AUTH_QOP_SUPPORT */ - - hauth->scheme = pjsip_DIGEST_STR; - status = respond_digest( pool, &hauth->credential.digest, - &hdr->challenge.digest, &uri_str, cred_info, - cnonce, nc, &method->name); - if (status != PJ_SUCCESS) - return status; - - /* Set qop type in auth session the first time only. */ - if (hdr->challenge.digest.qop.slen != 0 && cached_auth) { - if (cached_auth->qop_value == PJSIP_AUTH_QOP_NONE) { - pj_str_t *qop_val = &hauth->credential.digest.qop; - if (!pj_strcmp(qop_val, &pjsip_AUTH_STR)) { - cached_auth->qop_value = PJSIP_AUTH_QOP_AUTH; - } else { - cached_auth->qop_value = PJSIP_AUTH_QOP_UNKNOWN; - } - } - } + pj_str_t *cnonce = NULL; + pj_uint32_t nc = 1; + + /* Update the session (nonce-count etc) if required. */ +# if PJSIP_AUTH_QOP_SUPPORT + { + if (cached_auth) { + update_digest_session( cached_auth, hdr ); + + cnonce = &cached_auth->cnonce; + nc = cached_auth->nc; + } + } +# endif /* PJSIP_AUTH_QOP_SUPPORT */ + + hauth->scheme = pjsip_DIGEST_STR; + status = respond_digest( pool, &hauth->credential.digest, + &hdr->challenge.digest, &uri_str, cred_info, + cnonce, nc, &method->name); + if (status != PJ_SUCCESS) + return status; + + /* Set qop type in auth session the first time only. */ + if (hdr->challenge.digest.qop.slen != 0 && cached_auth) { + if (cached_auth->qop_value == PJSIP_AUTH_QOP_NONE) { + pj_str_t *qop_val = &hauth->credential.digest.qop; + if (!pj_strcmp(qop_val, &pjsip_AUTH_STR)) { + cached_auth->qop_value = PJSIP_AUTH_QOP_AUTH; + } else { + cached_auth->qop_value = PJSIP_AUTH_QOP_UNKNOWN; + } + } + } } else { - return PJSIP_EINVALIDAUTHSCHEME; + return PJSIP_EINVALIDAUTHSCHEME; } /* Keep the new authorization header in the cache, only @@ -993,33 +992,33 @@ static pj_status_t auth_respond( pj_pool_t *req_pool, */ # if PJSIP_AUTH_HEADER_CACHING { - if (hauth && cached_auth && cached_auth->qop_value == PJSIP_AUTH_QOP_NONE) { - pjsip_cached_auth_hdr *cached_hdr; - - /* Delete old header with the same method. */ - cached_hdr = cached_auth->cached_hdr.next; - while (cached_hdr != &cached_auth->cached_hdr) { - if (pjsip_method_cmp(method, &cached_hdr->method)==0) - break; - cached_hdr = cached_hdr->next; - } - - /* Save the header to the list. */ - if (cached_hdr != &cached_auth->cached_hdr) { - cached_hdr->hdr = hauth; - } else { - cached_hdr = pj_pool_alloc(pool, sizeof(*cached_hdr)); - pjsip_method_copy( pool, &cached_hdr->method, method); - cached_hdr->hdr = hauth; - pj_list_insert_before( &cached_auth->cached_hdr, cached_hdr ); - } - } - -# if defined(PJSIP_AUTH_AUTO_SEND_NEXT) && PJSIP_AUTH_AUTO_SEND_NEXT!=0 - if (hdr != cached_auth->last_chal) { - cached_auth->last_chal = pjsip_hdr_clone(sess_pool, hdr); - } -# endif + if (hauth && cached_auth && cached_auth->qop_value == PJSIP_AUTH_QOP_NONE) { + pjsip_cached_auth_hdr *cached_hdr; + + /* Delete old header with the same method. */ + cached_hdr = cached_auth->cached_hdr.next; + while (cached_hdr != &cached_auth->cached_hdr) { + if (pjsip_method_cmp(method, &cached_hdr->method)==0) + break; + cached_hdr = cached_hdr->next; + } + + /* Save the header to the list. */ + if (cached_hdr != &cached_auth->cached_hdr) { + cached_hdr->hdr = hauth; + } else { + cached_hdr = pj_pool_alloc(pool, sizeof(*cached_hdr)); + pjsip_method_copy( pool, &cached_hdr->method, method); + cached_hdr->hdr = hauth; + pj_list_insert_before( &cached_auth->cached_hdr, cached_hdr ); + } + } + +# if defined(PJSIP_AUTH_AUTO_SEND_NEXT) && PJSIP_AUTH_AUTO_SEND_NEXT!=0 + if (hdr != cached_auth->last_chal) { + cached_auth->last_chal = pjsip_hdr_clone(sess_pool, hdr); + } +# endif } # endif @@ -1031,9 +1030,9 @@ static pj_status_t auth_respond( pj_pool_t *req_pool, #if defined(PJSIP_AUTH_AUTO_SEND_NEXT) && PJSIP_AUTH_AUTO_SEND_NEXT!=0 static pj_status_t new_auth_for_req( pjsip_tx_data *tdata, - pjsip_auth_clt_sess *sess, - pjsip_cached_auth *auth, - pjsip_authorization_hdr **p_h_auth) + pjsip_auth_clt_sess *sess, + pjsip_cached_auth *auth, + pjsip_authorization_hdr **p_h_auth) { const pjsip_cred_info *cred; pjsip_authorization_hdr *hauth; @@ -1044,19 +1043,19 @@ static pj_status_t new_auth_for_req( pjsip_tx_data *tdata, cred = auth_find_cred( sess, &auth->realm, &auth->last_chal->scheme ); if (!cred) - return PJSIP_ENOCREDENTIAL; + return PJSIP_ENOCREDENTIAL; status = auth_respond( tdata->pool, auth->last_chal, - tdata->msg->line.req.uri, - cred, &tdata->msg->line.req.method, - sess->pool, auth, &hauth); + tdata->msg->line.req.uri, + cred, &tdata->msg->line.req.method, + sess->pool, auth, &hauth); if (status != PJ_SUCCESS) - return status; + return status; pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*)hauth); if (p_h_auth) - *p_h_auth = hauth; + *p_h_auth = hauth; return PJ_SUCCESS; } @@ -1065,15 +1064,15 @@ static pj_status_t new_auth_for_req( pjsip_tx_data *tdata, /* Find credential in list of (Proxy-)Authorization headers */ static pjsip_authorization_hdr* get_header_for_realm(const pjsip_hdr *hdr_list, - const pj_str_t *realm) + const pj_str_t *realm) { pjsip_authorization_hdr *h; h = (pjsip_authorization_hdr*)hdr_list->next; while (h != (pjsip_authorization_hdr*)hdr_list) { - if (pj_stricmp(&h->credential.digest.realm, realm)==0) - return h; - h = h->next; + if (pj_stricmp(&h->credential.digest.realm, realm)==0) + return h; + h = h->next; } return NULL; @@ -1082,7 +1081,7 @@ static pjsip_authorization_hdr* get_header_for_realm(const pjsip_hdr *hdr_list, /* Initialize outgoing request. */ PJ_DEF(pj_status_t) pjsip_auth_clt_init_req( pjsip_auth_clt_sess *sess, - pjsip_tx_data *tdata ) + pjsip_tx_data *tdata ) { const pjsip_method *method; pjsip_cached_auth *auth; @@ -1091,7 +1090,7 @@ PJ_DEF(pj_status_t) pjsip_auth_clt_init_req( pjsip_auth_clt_sess *sess, PJ_ASSERT_RETURN(sess && tdata, PJ_EINVAL); PJ_ASSERT_RETURN(sess->pool, PJSIP_ENOTINITIALIZED); PJ_ASSERT_RETURN(tdata->msg->type==PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); /* Init list */ pj_list_init(&added); @@ -1102,135 +1101,135 @@ PJ_DEF(pj_status_t) pjsip_auth_clt_init_req( pjsip_auth_clt_sess *sess, auth = sess->cached_auth.next; while (auth != &sess->cached_auth) { - /* Reset stale counter */ - auth->stale_cnt = 0; - - if (auth->qop_value == PJSIP_AUTH_QOP_NONE) { -# if defined(PJSIP_AUTH_HEADER_CACHING) && \ - PJSIP_AUTH_HEADER_CACHING!=0 - { - pjsip_cached_auth_hdr *entry = auth->cached_hdr.next; - while (entry != &auth->cached_hdr) { - if (pjsip_method_cmp(&entry->method, method)==0) { - pjsip_authorization_hdr *hauth; - hauth = pjsip_hdr_shallow_clone(tdata->pool, entry->hdr); - //pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hauth); - pj_list_push_back(&added, hauth); - break; - } - entry = entry->next; - } - -# if defined(PJSIP_AUTH_AUTO_SEND_NEXT) && \ - PJSIP_AUTH_AUTO_SEND_NEXT!=0 - { - if (entry == &auth->cached_hdr) - new_auth_for_req( tdata, sess, auth, NULL); - } -# endif - - } -# elif defined(PJSIP_AUTH_AUTO_SEND_NEXT) && \ - PJSIP_AUTH_AUTO_SEND_NEXT!=0 - { - new_auth_for_req( tdata, sess, auth, NULL); - } -# endif - - } -# if defined(PJSIP_AUTH_QOP_SUPPORT) && \ - defined(PJSIP_AUTH_AUTO_SEND_NEXT) && \ - (PJSIP_AUTH_QOP_SUPPORT && PJSIP_AUTH_AUTO_SEND_NEXT) - else if (auth->qop_value == PJSIP_AUTH_QOP_AUTH) { - /* For qop="auth", we have to re-create the authorization header. - */ - const pjsip_cred_info *cred; - pjsip_authorization_hdr *hauth; - pj_status_t status; - - cred = auth_find_cred(sess, &auth->realm, - &auth->last_chal->scheme); - if (!cred) { - auth = auth->next; - continue; - } - - status = auth_respond( tdata->pool, auth->last_chal, - tdata->msg->line.req.uri, - cred, - &tdata->msg->line.req.method, - sess->pool, auth, &hauth); - if (status != PJ_SUCCESS) - return status; - - //pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hauth); - pj_list_push_back(&added, hauth); - } -# endif /* PJSIP_AUTH_QOP_SUPPORT && PJSIP_AUTH_AUTO_SEND_NEXT */ - - auth = auth->next; + /* Reset stale counter */ + auth->stale_cnt = 0; + + if (auth->qop_value == PJSIP_AUTH_QOP_NONE) { +# if defined(PJSIP_AUTH_HEADER_CACHING) && \ + PJSIP_AUTH_HEADER_CACHING!=0 + { + pjsip_cached_auth_hdr *entry = auth->cached_hdr.next; + while (entry != &auth->cached_hdr) { + if (pjsip_method_cmp(&entry->method, method)==0) { + pjsip_authorization_hdr *hauth; + hauth = pjsip_hdr_shallow_clone(tdata->pool, entry->hdr); + //pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hauth); + pj_list_push_back(&added, hauth); + break; + } + entry = entry->next; + } + +# if defined(PJSIP_AUTH_AUTO_SEND_NEXT) && \ + PJSIP_AUTH_AUTO_SEND_NEXT!=0 + { + if (entry == &auth->cached_hdr) + new_auth_for_req( tdata, sess, auth, NULL); + } +# endif + + } +# elif defined(PJSIP_AUTH_AUTO_SEND_NEXT) && \ + PJSIP_AUTH_AUTO_SEND_NEXT!=0 + { + new_auth_for_req( tdata, sess, auth, NULL); + } +# endif + + } +# if defined(PJSIP_AUTH_QOP_SUPPORT) && \ + defined(PJSIP_AUTH_AUTO_SEND_NEXT) && \ + (PJSIP_AUTH_QOP_SUPPORT && PJSIP_AUTH_AUTO_SEND_NEXT) + else if (auth->qop_value == PJSIP_AUTH_QOP_AUTH) { + /* For qop="auth", we have to re-create the authorization header. + */ + const pjsip_cred_info *cred; + pjsip_authorization_hdr *hauth; + pj_status_t status; + + cred = auth_find_cred(sess, &auth->realm, + &auth->last_chal->scheme); + if (!cred) { + auth = auth->next; + continue; + } + + status = auth_respond( tdata->pool, auth->last_chal, + tdata->msg->line.req.uri, + cred, + &tdata->msg->line.req.method, + sess->pool, auth, &hauth); + if (status != PJ_SUCCESS) + return status; + + //pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hauth); + pj_list_push_back(&added, hauth); + } +# endif /* PJSIP_AUTH_QOP_SUPPORT && PJSIP_AUTH_AUTO_SEND_NEXT */ + + auth = auth->next; } if (sess->pref.initial_auth == PJ_FALSE) { - pjsip_hdr *h; - - /* Don't want to send initial empty Authorization header, so - * just send whatever available in the list (maybe empty). - */ - - h = added.next; - while (h != &added) { - pjsip_hdr *next = h->next; - pjsip_msg_add_hdr(tdata->msg, h); - h = next; - } + pjsip_hdr *h; + + /* Don't want to send initial empty Authorization header, so + * just send whatever available in the list (maybe empty). + */ + + h = added.next; + while (h != &added) { + pjsip_hdr *next = h->next; + pjsip_msg_add_hdr(tdata->msg, h); + h = next; + } } else { - /* For each realm, add either the cached authorization header - * or add an empty authorization header. - */ - unsigned i; - pj_str_t uri; - - uri.ptr = (char*)pj_pool_alloc(tdata->pool, PJSIP_MAX_URL_SIZE); - uri.slen = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, - tdata->msg->line.req.uri, - uri.ptr, PJSIP_MAX_URL_SIZE); - if (uri.slen < 1 || uri.slen >= PJSIP_MAX_URL_SIZE) - return PJSIP_EURITOOLONG; - - for (i=0; icred_cnt; ++i) { - pjsip_cred_info *c = &sess->cred_info[i]; - pjsip_authorization_hdr *h; - - h = get_header_for_realm(&added, &c->realm); - if (h) { - pj_list_erase(h); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)h); - } else { - pjsip_authorization_hdr *hs; - - hs = pjsip_authorization_hdr_create(tdata->pool); - pj_strdup(tdata->pool, &hs->scheme, &c->scheme); - if (pj_stricmp(&c->scheme, &pjsip_BEARER_STR)==0) { - pj_strdup(tdata->pool, &hs->credential.oauth.username, + /* For each realm, add either the cached authorization header + * or add an empty authorization header. + */ + unsigned i; + pj_str_t uri; + + uri.ptr = (char*)pj_pool_alloc(tdata->pool, PJSIP_MAX_URL_SIZE); + uri.slen = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, + tdata->msg->line.req.uri, + uri.ptr, PJSIP_MAX_URL_SIZE); + if (uri.slen < 1 || uri.slen >= PJSIP_MAX_URL_SIZE) + return PJSIP_EURITOOLONG; + + for (i=0; icred_cnt; ++i) { + pjsip_cred_info *c = &sess->cred_info[i]; + pjsip_authorization_hdr *h; + + h = get_header_for_realm(&added, &c->realm); + if (h) { + pj_list_erase(h); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)h); + } else { + pjsip_authorization_hdr *hs; + + hs = pjsip_authorization_hdr_create(tdata->pool); + pj_strdup(tdata->pool, &hs->scheme, &c->scheme); + if (pj_stricmp(&c->scheme, &pjsip_BEARER_STR)==0) { + pj_strdup(tdata->pool, &hs->credential.oauth.username, &c->username); pj_strdup(tdata->pool, &hs->credential.oauth.realm, &c->realm); pj_strdup(tdata->pool, &hs->credential.oauth.token, &c->data); - } else { //if (pj_stricmp(&c->scheme, &pjsip_DIGEST_STR)==0) - pj_strdup(tdata->pool, &hs->credential.digest.username, - &c->username); - pj_strdup(tdata->pool, &hs->credential.digest.realm, - &c->realm); - pj_strdup(tdata->pool,&hs->credential.digest.uri, &uri); - pj_strdup(tdata->pool, &hs->credential.digest.algorithm, - &sess->pref.algorithm); - } - - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hs); - } - } + } else { //if (pj_stricmp(&c->scheme, &pjsip_DIGEST_STR)==0) + pj_strdup(tdata->pool, &hs->credential.digest.username, + &c->username); + pj_strdup(tdata->pool, &hs->credential.digest.realm, + &c->realm); + pj_strdup(tdata->pool,&hs->credential.digest.uri, &uri); + pj_strdup(tdata->pool, &hs->credential.digest.algorithm, + &sess->pref.algorithm); + } + + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hs); + } + } } return PJ_SUCCESS; @@ -1238,10 +1237,10 @@ PJ_DEF(pj_status_t) pjsip_auth_clt_init_req( pjsip_auth_clt_sess *sess, static void recreate_cached_auth_pool( pjsip_endpoint *endpt, - pjsip_cached_auth *auth ) + pjsip_cached_auth *auth ) { pj_pool_t *auth_pool = pjsip_endpt_create_pool(endpt, "auth_cli%p", 1024, - 1024); + 1024); if (auth->realm.slen) { pj_str_t realm; @@ -1257,7 +1256,7 @@ static void recreate_cached_auth_pool( pjsip_endpoint *endpt, if (auth->last_chal) { auth->last_chal = (pjsip_www_authenticate_hdr*) - pjsip_hdr_clone(auth_pool, auth->last_chal); + pjsip_hdr_clone(auth_pool, auth->last_chal); } pjsip_endpt_release_pool(endpt, auth->pool); @@ -1266,12 +1265,12 @@ static void recreate_cached_auth_pool( pjsip_endpoint *endpt, /* Process authorization challenge */ static pj_status_t process_auth( pj_pool_t *req_pool, - const pjsip_www_authenticate_hdr *hchal, - const pjsip_uri *uri, - pjsip_tx_data *tdata, - pjsip_auth_clt_sess *sess, - pjsip_cached_auth *cached_auth, - pjsip_authorization_hdr **h_auth) + const pjsip_www_authenticate_hdr *hchal, + const pjsip_uri *uri, + pjsip_tx_data *tdata, + pjsip_auth_clt_sess *sess, + pjsip_cached_auth *cached_auth, + pjsip_authorization_hdr **h_auth) { const pjsip_cred_info *cred; pjsip_authorization_hdr *sent_auth = NULL; @@ -1281,108 +1280,108 @@ static pj_status_t process_auth( pj_pool_t *req_pool, /* See if we have sent authorization header for this realm (and scheme) */ hdr = tdata->msg->hdr.next; while (hdr != &tdata->msg->hdr) { - if ((hchal->type == PJSIP_H_WWW_AUTHENTICATE && - hdr->type == PJSIP_H_AUTHORIZATION) || - (hchal->type == PJSIP_H_PROXY_AUTHENTICATE && - hdr->type == PJSIP_H_PROXY_AUTHORIZATION)) - { - sent_auth = (pjsip_authorization_hdr*) hdr; - if (pj_stricmp(&hchal->challenge.common.realm, - &sent_auth->credential.common.realm)==0 && - pj_stricmp(&hchal->scheme, &sent_auth->scheme)==0) - { - /* If this authorization has empty response, remove it. */ - if (pj_stricmp(&sent_auth->scheme, &pjsip_DIGEST_STR)==0 && - sent_auth->credential.digest.response.slen == 0) - { - /* This is empty authorization, remove it. */ - hdr = hdr->next; - pj_list_erase(sent_auth); - continue; - } else - if (pj_stricmp(&sent_auth->scheme, &pjsip_DIGEST_STR)==0 && - pj_stricmp(&sent_auth->credential.digest.algorithm, - &hchal->challenge.digest.algorithm)!=0) - { - /* Same 'digest' scheme but different algo */ - hdr = hdr->next; - continue; - } else { - /* Found previous authorization attempt */ - break; - } - } - } - hdr = hdr->next; + if ((hchal->type == PJSIP_H_WWW_AUTHENTICATE && + hdr->type == PJSIP_H_AUTHORIZATION) || + (hchal->type == PJSIP_H_PROXY_AUTHENTICATE && + hdr->type == PJSIP_H_PROXY_AUTHORIZATION)) + { + sent_auth = (pjsip_authorization_hdr*) hdr; + if (pj_stricmp(&hchal->challenge.common.realm, + &sent_auth->credential.common.realm)==0 && + pj_stricmp(&hchal->scheme, &sent_auth->scheme)==0) + { + /* If this authorization has empty response, remove it. */ + if (pj_stricmp(&sent_auth->scheme, &pjsip_DIGEST_STR)==0 && + sent_auth->credential.digest.response.slen == 0) + { + /* This is empty authorization, remove it. */ + hdr = hdr->next; + pj_list_erase(sent_auth); + continue; + } else + if (pj_stricmp(&sent_auth->scheme, &pjsip_DIGEST_STR)==0 && + pj_stricmp(&sent_auth->credential.digest.algorithm, + &hchal->challenge.digest.algorithm)!=0) + { + /* Same 'digest' scheme but different algo */ + hdr = hdr->next; + continue; + } else { + /* Found previous authorization attempt */ + break; + } + } + } + hdr = hdr->next; } /* If we have sent, see if server rejected because of stale nonce or * other causes. */ if (hdr != &tdata->msg->hdr) { - pj_bool_t stale; - - /* Detect "stale" state */ - stale = hchal->challenge.digest.stale; - if (!stale) { - /* If stale is false, check is nonce has changed. Some servers - * (broken ones!) want to change nonce but they fail to set - * stale to true. - */ - stale = pj_strcmp(&hchal->challenge.digest.nonce, - &sent_auth->credential.digest.nonce); - } - - if (stale == PJ_FALSE) { - /* Our credential is rejected. No point in trying to re-supply - * the same credential. - */ - PJ_LOG(4, (THIS_FILE, "Authorization failed for %.*s@%.*s: " - "server rejected with stale=false", - sent_auth->credential.digest.username.slen, - sent_auth->credential.digest.username.ptr, - sent_auth->credential.digest.realm.slen, - sent_auth->credential.digest.realm.ptr)); - return PJSIP_EFAILEDCREDENTIAL; - } - - cached_auth->stale_cnt++; - if (cached_auth->stale_cnt >= PJSIP_MAX_STALE_COUNT) { - /* Our credential is rejected. No point in trying to re-supply - * the same credential. - */ - PJ_LOG(4, (THIS_FILE, "Authorization failed for %.*s@%.*s: " - "maximum number of stale retries exceeded", - sent_auth->credential.digest.username.slen, - sent_auth->credential.digest.username.ptr, - sent_auth->credential.digest.realm.slen, - sent_auth->credential.digest.realm.ptr)); - return PJSIP_EAUTHSTALECOUNT; - } - - /* Otherwise remove old, stale authorization header from the mesasge. - * We will supply a new one. - */ - pj_list_erase(sent_auth); + pj_bool_t stale; + + /* Detect "stale" state */ + stale = hchal->challenge.digest.stale; + if (!stale) { + /* If stale is false, check is nonce has changed. Some servers + * (broken ones!) want to change nonce but they fail to set + * stale to true. + */ + stale = pj_strcmp(&hchal->challenge.digest.nonce, + &sent_auth->credential.digest.nonce); + } + + if (stale == PJ_FALSE) { + /* Our credential is rejected. No point in trying to re-supply + * the same credential. + */ + PJ_LOG(4, (THIS_FILE, "Authorization failed for %.*s@%.*s: " + "server rejected with stale=false", + sent_auth->credential.digest.username.slen, + sent_auth->credential.digest.username.ptr, + sent_auth->credential.digest.realm.slen, + sent_auth->credential.digest.realm.ptr)); + return PJSIP_EFAILEDCREDENTIAL; + } + + cached_auth->stale_cnt++; + if (cached_auth->stale_cnt >= PJSIP_MAX_STALE_COUNT) { + /* Our credential is rejected. No point in trying to re-supply + * the same credential. + */ + PJ_LOG(4, (THIS_FILE, "Authorization failed for %.*s@%.*s: " + "maximum number of stale retries exceeded", + sent_auth->credential.digest.username.slen, + sent_auth->credential.digest.username.ptr, + sent_auth->credential.digest.realm.slen, + sent_auth->credential.digest.realm.ptr)); + return PJSIP_EAUTHSTALECOUNT; + } + + /* Otherwise remove old, stale authorization header from the mesasge. + * We will supply a new one. + */ + pj_list_erase(sent_auth); } /* Find credential to be used for the challenge. */ cred = auth_find_cred( sess, &hchal->challenge.common.realm, - &hchal->scheme); + &hchal->scheme); if (!cred) { - const pj_str_t *realm = &hchal->challenge.common.realm; - PJ_LOG(4,(THIS_FILE, - "Unable to set auth for %s: can not find credential for %.*s/%.*s", - tdata->obj_name, - realm->slen, realm->ptr, - hchal->scheme.slen, hchal->scheme.ptr)); - return PJSIP_ENOCREDENTIAL; + const pj_str_t *realm = &hchal->challenge.common.realm; + PJ_LOG(4,(THIS_FILE, + "Unable to set auth for %s: can not find credential for %.*s/%.*s", + tdata->obj_name, + realm->slen, realm->ptr, + hchal->scheme.slen, hchal->scheme.ptr)); + return PJSIP_ENOCREDENTIAL; } /* Respond to authorization challenge. */ status = auth_respond( req_pool, hchal, uri, cred, - &tdata->msg->line.req.method, - sess->pool, cached_auth, h_auth); + &tdata->msg->line.req.method, + sess->pool, cached_auth, h_auth); return status; } @@ -1393,10 +1392,10 @@ static pj_status_t process_auth( pj_pool_t *req_pool, * - to put the newly created Authorization/Proxy-Authorization header * in cached_list. */ -PJ_DEF(pj_status_t) pjsip_auth_clt_reinit_req( pjsip_auth_clt_sess *sess, - const pjsip_rx_data *rdata, - pjsip_tx_data *old_request, - pjsip_tx_data **new_request ) +PJ_DEF(pj_status_t) pjsip_auth_clt_reinit_req( pjsip_auth_clt_sess *sess, + const pjsip_rx_data *rdata, + pjsip_tx_data *old_request, + pjsip_tx_data **new_request ) { pjsip_tx_data *tdata; const pjsip_hdr *hdr; @@ -1406,15 +1405,15 @@ PJ_DEF(pj_status_t) pjsip_auth_clt_reinit_req( pjsip_auth_clt_sess *sess, pj_status_t last_auth_err; PJ_ASSERT_RETURN(sess && rdata && old_request && new_request, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(sess->pool, PJSIP_ENOTINITIALIZED); PJ_ASSERT_RETURN(rdata->msg_info.msg->type == PJSIP_RESPONSE_MSG, - PJSIP_ENOTRESPONSEMSG); + PJSIP_ENOTRESPONSEMSG); PJ_ASSERT_RETURN(old_request->msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); PJ_ASSERT_RETURN(rdata->msg_info.msg->line.status.code == 401 || - rdata->msg_info.msg->line.status.code == 407, - PJSIP_EINVALIDSTATUS); + rdata->msg_info.msg->line.status.code == 407, + PJSIP_EINVALIDSTATUS); tdata = old_request; tdata->auth_retry = PJ_FALSE; @@ -1427,83 +1426,83 @@ PJ_DEF(pj_status_t) pjsip_auth_clt_reinit_req( pjsip_auth_clt_sess *sess, auth_cnt = 0; last_auth_err = PJSIP_EAUTHNOAUTH; while (hdr != &rdata->msg_info.msg->hdr) { - pjsip_cached_auth *cached_auth; - const pjsip_www_authenticate_hdr *hchal; - pjsip_authorization_hdr *hauth; - - /* Find WWW-Authenticate or Proxy-Authenticate header. */ - while (hdr != &rdata->msg_info.msg->hdr && - hdr->type != PJSIP_H_WWW_AUTHENTICATE && - hdr->type != PJSIP_H_PROXY_AUTHENTICATE) - { - hdr = hdr->next; - } - if (hdr == &rdata->msg_info.msg->hdr) - break; - - hchal = (const pjsip_www_authenticate_hdr*)hdr; - ++chal_cnt; - - /* Find authentication session for this realm, create a new one - * if not present. - */ - cached_auth = find_cached_auth(sess, &hchal->challenge.common.realm); - if (!cached_auth) { - cached_auth = PJ_POOL_ZALLOC_T(sess->pool, pjsip_cached_auth); - cached_auth->pool = pjsip_endpt_create_pool(sess->endpt, - "auth_cli%p", - 1024, - 1024); - pj_strdup(cached_auth->pool, &cached_auth->realm, - &hchal->challenge.common.realm); - cached_auth->is_proxy = (hchal->type == PJSIP_H_PROXY_AUTHENTICATE); -# if (PJSIP_AUTH_HEADER_CACHING) - { - pj_list_init(&cached_auth->cached_hdr); - } -# endif - pj_list_insert_before(&sess->cached_auth, cached_auth); - } - - /* Create authorization header for this challenge, and update - * authorization session. - */ - status = process_auth(tdata->pool, hchal, tdata->msg->line.req.uri, - tdata, sess, cached_auth, &hauth); - if (status != PJ_SUCCESS) { - last_auth_err = status; - - /* Process next header. */ - hdr = hdr->next; - continue; - } - - if (pj_pool_get_used_size(cached_auth->pool) > - PJSIP_AUTH_CACHED_POOL_MAX_SIZE) - { - recreate_cached_auth_pool(sess->endpt, cached_auth); - } - - /* Add to the message. */ - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hauth); - - /* Process next header. */ - hdr = hdr->next; - auth_cnt++; + pjsip_cached_auth *cached_auth; + const pjsip_www_authenticate_hdr *hchal; + pjsip_authorization_hdr *hauth; + + /* Find WWW-Authenticate or Proxy-Authenticate header. */ + while (hdr != &rdata->msg_info.msg->hdr && + hdr->type != PJSIP_H_WWW_AUTHENTICATE && + hdr->type != PJSIP_H_PROXY_AUTHENTICATE) + { + hdr = hdr->next; + } + if (hdr == &rdata->msg_info.msg->hdr) + break; + + hchal = (const pjsip_www_authenticate_hdr*)hdr; + ++chal_cnt; + + /* Find authentication session for this realm, create a new one + * if not present. + */ + cached_auth = find_cached_auth(sess, &hchal->challenge.common.realm); + if (!cached_auth) { + cached_auth = PJ_POOL_ZALLOC_T(sess->pool, pjsip_cached_auth); + cached_auth->pool = pjsip_endpt_create_pool(sess->endpt, + "auth_cli%p", + 1024, + 1024); + pj_strdup(cached_auth->pool, &cached_auth->realm, + &hchal->challenge.common.realm); + cached_auth->is_proxy = (hchal->type == PJSIP_H_PROXY_AUTHENTICATE); +# if (PJSIP_AUTH_HEADER_CACHING) + { + pj_list_init(&cached_auth->cached_hdr); + } +# endif + pj_list_insert_before(&sess->cached_auth, cached_auth); + } + + /* Create authorization header for this challenge, and update + * authorization session. + */ + status = process_auth(tdata->pool, hchal, tdata->msg->line.req.uri, + tdata, sess, cached_auth, &hauth); + if (status != PJ_SUCCESS) { + last_auth_err = status; + + /* Process next header. */ + hdr = hdr->next; + continue; + } + + if (pj_pool_get_used_size(cached_auth->pool) > + PJSIP_AUTH_CACHED_POOL_MAX_SIZE) + { + recreate_cached_auth_pool(sess->endpt, cached_auth); + } + + /* Add to the message. */ + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hauth); + + /* Process next header. */ + hdr = hdr->next; + auth_cnt++; #if defined(PJSIP_AUTH_ALLOW_MULTIPLE_AUTH_HEADER) && \ - PJSIP_AUTH_ALLOW_MULTIPLE_AUTH_HEADER==0 - break; + PJSIP_AUTH_ALLOW_MULTIPLE_AUTH_HEADER==0 + break; #endif } /* Check if challenge is present */ if (chal_cnt == 0) - return PJSIP_EAUTHNOCHAL; + return PJSIP_EAUTHNOCHAL; /* Check if any authorization header has been created */ if (auth_cnt == 0) - return last_auth_err; + return last_auth_err; /* Remove branch param in Via header. */ via = (pjsip_via_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); diff --git a/pjsip/src/pjsip/sip_auth_msg.c b/pjsip/src/pjsip/sip_auth_msg.c index 76a785ce70..1e2eba1920 100644 --- a/pjsip/src/pjsip/sip_auth_msg.c +++ b/pjsip/src/pjsip/sip_auth_msg.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,11 +30,11 @@ * Authorization and Proxy-Authorization header. */ static pjsip_authorization_hdr* pjsip_authorization_hdr_clone( pj_pool_t *pool, - const pjsip_authorization_hdr *hdr); + const pjsip_authorization_hdr *hdr); static pjsip_authorization_hdr* pjsip_authorization_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_authorization_hdr *hdr); + const pjsip_authorization_hdr *hdr); static int pjsip_authorization_hdr_print( pjsip_authorization_hdr *hdr, - char *buf, pj_size_t size); + char *buf, pj_size_t size); static pjsip_hdr_vptr authorization_hdr_vptr = { @@ -72,7 +71,7 @@ static int print_digest_credential(pjsip_digest_credential *cred, char *buf, pj_ copy_advance_pair_quote_cond(buf, "username=", 9, cred->username, '"', '"'); copy_advance_pair_quote_cond_always(buf, ", realm=", 8, cred->realm, '"', - '"'); + '"'); copy_advance_pair_quote(buf, ", nonce=", 8, cred->nonce, '"', '"'); copy_advance_pair_quote_cond(buf, ", uri=", 6, cred->uri, '"', '"'); copy_advance_pair_quote(buf, ", response=", 11, cred->response, '"', '"'); @@ -86,10 +85,10 @@ static int print_digest_credential(pjsip_digest_credential *cred, char *buf, pj_ copy_advance_pair(buf, ", nc=", 5, cred->nc); printed = pjsip_param_print_on(&cred->other_param, buf, endbuf-buf, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, ','); + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ','); if (printed < 0) - return -1; + return -1; buf += printed; return (int) (buf-startbuf); @@ -104,24 +103,24 @@ static int print_pgp_credential(pjsip_pgp_credential *cred, char *buf, pj_size_t } static int print_oauth_credential(pjsip_oauth_credential *cred, char *buf, - pj_size_t size) + pj_size_t size) { pj_ssize_t printed; char *startbuf = buf; char *endbuf = buf + size; copy_advance_pair_quote_cond_always(buf, "token=", 6, cred->token, - '"', '"'); + '"', '"'); copy_advance_pair_quote_cond_always(buf, ", username=", 11, cred->username, - '"', '"'); + '"', '"'); copy_advance_pair_quote_cond_always(buf, ", realm=", 8, cred->realm, - '"', '"'); + '"', '"'); return (int) (buf-startbuf); } static int pjsip_authorization_hdr_print( pjsip_authorization_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { int printed; char *startbuf = buf; @@ -136,24 +135,24 @@ static int pjsip_authorization_hdr_print( pjsip_authorization_hdr *hdr, if (pj_stricmp(&hdr->scheme, &pjsip_DIGEST_STR) == 0) { - printed = print_digest_credential(&hdr->credential.digest, buf, endbuf - buf); + printed = print_digest_credential(&hdr->credential.digest, buf, endbuf - buf); } else if (pj_stricmp(&hdr->scheme, &pjsip_PGP_STR) == 0) { - printed = print_pgp_credential(&hdr->credential.pgp, buf, endbuf - buf); + printed = print_pgp_credential(&hdr->credential.pgp, buf, endbuf - buf); } else if (pj_stricmp(&hdr->scheme, &pjsip_BEARER_STR) == 0) { printed = print_oauth_credential(&hdr->credential.oauth, buf, - endbuf - buf); + endbuf - buf); } else { - pj_assert(0); - return -1; + pj_assert(0); + return -1; } if (printed == -1) - return -1; + return -1; buf += printed; *buf = '\0'; @@ -161,35 +160,35 @@ static int pjsip_authorization_hdr_print( pjsip_authorization_hdr *hdr, } static pjsip_authorization_hdr* pjsip_authorization_hdr_clone( pj_pool_t *pool, - const pjsip_authorization_hdr *rhs) + const pjsip_authorization_hdr *rhs) { /* This function also serves Proxy-Authorization header. */ pjsip_authorization_hdr *hdr; if (rhs->type == PJSIP_H_AUTHORIZATION) - hdr = pjsip_authorization_hdr_create(pool); + hdr = pjsip_authorization_hdr_create(pool); else - hdr = pjsip_proxy_authorization_hdr_create(pool); + hdr = pjsip_proxy_authorization_hdr_create(pool); pj_strdup(pool, &hdr->scheme, &rhs->scheme); if (pj_stricmp2(&hdr->scheme, "digest") == 0) { - pj_strdup(pool, &hdr->credential.digest.username, &rhs->credential.digest.username); - pj_strdup(pool, &hdr->credential.digest.realm, &rhs->credential.digest.realm); - pj_strdup(pool, &hdr->credential.digest.nonce, &rhs->credential.digest.nonce); - pj_strdup(pool, &hdr->credential.digest.uri, &rhs->credential.digest.uri); - pj_strdup(pool, &hdr->credential.digest.response, &rhs->credential.digest.response); - pj_strdup(pool, &hdr->credential.digest.algorithm, &rhs->credential.digest.algorithm); - pj_strdup(pool, &hdr->credential.digest.cnonce, &rhs->credential.digest.cnonce); - pj_strdup(pool, &hdr->credential.digest.opaque, &rhs->credential.digest.opaque); - pj_strdup(pool, &hdr->credential.digest.qop, &rhs->credential.digest.qop); - pj_strdup(pool, &hdr->credential.digest.nc, &rhs->credential.digest.nc); - pjsip_param_clone(pool, &hdr->credential.digest.other_param, &rhs->credential.digest.other_param); + pj_strdup(pool, &hdr->credential.digest.username, &rhs->credential.digest.username); + pj_strdup(pool, &hdr->credential.digest.realm, &rhs->credential.digest.realm); + pj_strdup(pool, &hdr->credential.digest.nonce, &rhs->credential.digest.nonce); + pj_strdup(pool, &hdr->credential.digest.uri, &rhs->credential.digest.uri); + pj_strdup(pool, &hdr->credential.digest.response, &rhs->credential.digest.response); + pj_strdup(pool, &hdr->credential.digest.algorithm, &rhs->credential.digest.algorithm); + pj_strdup(pool, &hdr->credential.digest.cnonce, &rhs->credential.digest.cnonce); + pj_strdup(pool, &hdr->credential.digest.opaque, &rhs->credential.digest.opaque); + pj_strdup(pool, &hdr->credential.digest.qop, &rhs->credential.digest.qop); + pj_strdup(pool, &hdr->credential.digest.nc, &rhs->credential.digest.nc); + pjsip_param_clone(pool, &hdr->credential.digest.other_param, &rhs->credential.digest.other_param); } else if (pj_stricmp2(&hdr->scheme, "pgp") == 0) { - pj_assert(0); - return NULL; + pj_assert(0); + return NULL; } else { - pj_assert(0); - return NULL; + pj_assert(0); + return NULL; } return hdr; @@ -197,14 +196,14 @@ static pjsip_authorization_hdr* pjsip_authorization_hdr_clone( pj_pool_t *pool, static pjsip_authorization_hdr* pjsip_authorization_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_authorization_hdr *rhs) + const pjsip_authorization_hdr *rhs) { /* This function also serves Proxy-Authorization header. */ pjsip_authorization_hdr *hdr; hdr = PJ_POOL_ALLOC_T(pool, pjsip_authorization_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); pjsip_param_shallow_clone(pool, &hdr->credential.common.other_param, - &rhs->credential.common.other_param); + &rhs->credential.common.other_param); return hdr; } @@ -214,11 +213,11 @@ pjsip_authorization_hdr_shallow_clone( pj_pool_t *pool, * Proxy-Authenticate and WWW-Authenticate header. */ static int pjsip_www_authenticate_hdr_print( pjsip_www_authenticate_hdr *hdr, - char *buf, pj_size_t size); + char *buf, pj_size_t size); static pjsip_www_authenticate_hdr* pjsip_www_authenticate_hdr_clone( pj_pool_t *pool, - const pjsip_www_authenticate_hdr *hdr); + const pjsip_www_authenticate_hdr *hdr); static pjsip_www_authenticate_hdr* pjsip_www_authenticate_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_www_authenticate_hdr *hdr); + const pjsip_www_authenticate_hdr *hdr); static pjsip_hdr_vptr www_authenticate_hdr_vptr = { @@ -248,7 +247,7 @@ PJ_DEF(pjsip_proxy_authenticate_hdr*) pjsip_proxy_authenticate_hdr_create(pj_poo } static int print_digest_challenge( pjsip_digest_challenge *chal, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { pj_ssize_t printed; char *startbuf = buf; @@ -261,24 +260,24 @@ static int print_digest_challenge( pjsip_digest_challenge *chal, copy_advance_pair_quote_cond(buf, ",nonce=", 7, chal->nonce, '"', '"'); copy_advance_pair_quote_cond(buf, ",opaque=", 8, chal->opaque, '"', '"'); if (chal->stale) { - pj_str_t true_str = { "true", 4 }; - copy_advance_pair(buf, ",stale=", 7, true_str); + pj_str_t true_str = { "true", 4 }; + copy_advance_pair(buf, ",stale=", 7, true_str); } copy_advance_pair(buf, ",algorithm=", 11, chal->algorithm); copy_advance_pair_quote_cond(buf, ",qop=", 5, chal->qop, '"', '"'); printed = pjsip_param_print_on(&chal->other_param, buf, endbuf-buf, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, ','); + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ','); if (printed < 0) - return -1; + return -1; buf += printed; return (int)(buf-startbuf); } static int print_pgp_challenge( pjsip_pgp_challenge *chal, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { PJ_UNUSED_ARG(chal); PJ_UNUSED_ARG(buf); @@ -287,7 +286,7 @@ static int print_pgp_challenge( pjsip_pgp_challenge *chal, } static int pjsip_www_authenticate_hdr_print( pjsip_www_authenticate_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { int printed; char *startbuf = buf; @@ -301,16 +300,16 @@ static int pjsip_www_authenticate_hdr_print( pjsip_www_authenticate_hdr *hdr, copy_advance_char_check(buf, ' '); if (pj_stricmp2(&hdr->scheme, "digest") == 0) - printed = print_digest_challenge(&hdr->challenge.digest, buf, endbuf - buf); + printed = print_digest_challenge(&hdr->challenge.digest, buf, endbuf - buf); else if (pj_stricmp2(&hdr->scheme, "pgp") == 0) - printed = print_pgp_challenge(&hdr->challenge.pgp, buf, endbuf - buf); + printed = print_pgp_challenge(&hdr->challenge.pgp, buf, endbuf - buf); else { - pj_assert(0); - return -1; + pj_assert(0); + return -1; } if (printed == -1) - return -1; + return -1; buf += printed; *buf = '\0'; @@ -318,33 +317,33 @@ static int pjsip_www_authenticate_hdr_print( pjsip_www_authenticate_hdr *hdr, } static pjsip_www_authenticate_hdr* pjsip_www_authenticate_hdr_clone( pj_pool_t *pool, - const pjsip_www_authenticate_hdr *rhs) + const pjsip_www_authenticate_hdr *rhs) { /* This function also serves Proxy-Authenticate header. */ pjsip_www_authenticate_hdr *hdr; if (rhs->type == PJSIP_H_WWW_AUTHENTICATE) - hdr = pjsip_www_authenticate_hdr_create(pool); + hdr = pjsip_www_authenticate_hdr_create(pool); else - hdr = pjsip_proxy_authenticate_hdr_create(pool); + hdr = pjsip_proxy_authenticate_hdr_create(pool); pj_strdup(pool, &hdr->scheme, &rhs->scheme); if (pj_stricmp2(&hdr->scheme, "digest") == 0) { - pj_strdup(pool, &hdr->challenge.digest.realm, &rhs->challenge.digest.realm); - pj_strdup(pool, &hdr->challenge.digest.domain, &rhs->challenge.digest.domain); - pj_strdup(pool, &hdr->challenge.digest.nonce, &rhs->challenge.digest.nonce); - pj_strdup(pool, &hdr->challenge.digest.opaque, &rhs->challenge.digest.opaque); - hdr->challenge.digest.stale = rhs->challenge.digest.stale; - pj_strdup(pool, &hdr->challenge.digest.algorithm, &rhs->challenge.digest.algorithm); - pj_strdup(pool, &hdr->challenge.digest.qop, &rhs->challenge.digest.qop); - pjsip_param_clone(pool, &hdr->challenge.digest.other_param, - &rhs->challenge.digest.other_param); + pj_strdup(pool, &hdr->challenge.digest.realm, &rhs->challenge.digest.realm); + pj_strdup(pool, &hdr->challenge.digest.domain, &rhs->challenge.digest.domain); + pj_strdup(pool, &hdr->challenge.digest.nonce, &rhs->challenge.digest.nonce); + pj_strdup(pool, &hdr->challenge.digest.opaque, &rhs->challenge.digest.opaque); + hdr->challenge.digest.stale = rhs->challenge.digest.stale; + pj_strdup(pool, &hdr->challenge.digest.algorithm, &rhs->challenge.digest.algorithm); + pj_strdup(pool, &hdr->challenge.digest.qop, &rhs->challenge.digest.qop); + pjsip_param_clone(pool, &hdr->challenge.digest.other_param, + &rhs->challenge.digest.other_param); } else if (pj_stricmp2(&hdr->scheme, "pgp") == 0) { - pj_assert(0); - return NULL; + pj_assert(0); + return NULL; } else { - pj_assert(0); - return NULL; + pj_assert(0); + return NULL; } return hdr; @@ -352,14 +351,14 @@ static pjsip_www_authenticate_hdr* pjsip_www_authenticate_hdr_clone( pj_pool_t * } static pjsip_www_authenticate_hdr* pjsip_www_authenticate_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_www_authenticate_hdr *rhs) + const pjsip_www_authenticate_hdr *rhs) { /* This function also serves Proxy-Authenticate header. */ pjsip_www_authenticate_hdr *hdr; hdr = PJ_POOL_ALLOC_T(pool, pjsip_www_authenticate_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); pjsip_param_shallow_clone(pool, &hdr->challenge.common.other_param, - &rhs->challenge.common.other_param); + &rhs->challenge.common.other_param); return hdr; } diff --git a/pjsip/src/pjsip/sip_auth_parser.c b/pjsip/src/pjsip/sip_auth_parser.c index 6c6bad4518..dd98fc8891 100644 --- a/pjsip/src/pjsip/sip_auth_parser.c +++ b/pjsip/src/pjsip/sip_auth_parser.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,33 +38,33 @@ static void parse_digest_challenge ( pj_scanner *scanner, pj_pool_t *pool, static void parse_pgp_challenge ( pj_scanner *scanner, pj_pool_t *pool, pjsip_pgp_challenge *chal); -const pj_str_t pjsip_USERNAME_STR = { "username", 8 }, - pjsip_REALM_STR = { "realm", 5}, - pjsip_NONCE_STR = { "nonce", 5}, - pjsip_URI_STR = { "uri", 3 }, - pjsip_RESPONSE_STR = { "response", 8 }, - pjsip_ALGORITHM_STR = { "algorithm", 9 }, - pjsip_DOMAIN_STR = { "domain", 6 }, - pjsip_STALE_STR = { "stale", 5}, - pjsip_QOP_STR = { "qop", 3}, - pjsip_CNONCE_STR = { "cnonce", 6}, - pjsip_OPAQUE_STR = { "opaque", 6}, - pjsip_NC_STR = { "nc", 2}, - pjsip_TRUE_STR = { "true", 4}, - pjsip_QUOTED_TRUE_STR = { "\"true\"", 6}, - pjsip_FALSE_STR = { "false", 5}, - pjsip_QUOTED_FALSE_STR = { "\"false\"", 7}, - pjsip_DIGEST_STR = { "Digest", 6}, - pjsip_QUOTED_DIGEST_STR = { "\"Digest\"", 8}, - pjsip_PGP_STR = { "PGP", 3 }, - pjsip_QUOTED_PGP_STR = { "\"PGP\"", 5 }, - pjsip_BEARER_STR = { "Bearer", 6 }, - pjsip_MD5_STR = { "MD5", 3 }, - pjsip_QUOTED_MD5_STR = { "\"MD5\"", 5}, - pjsip_SHA256_STR = { "SHA-256", 7 }, - pjsip_QUOTED_SHA256_STR = { "\"SHA-256\"", 9}, - pjsip_AUTH_STR = { "auth", 4}, - pjsip_QUOTED_AUTH_STR = { "\"auth\"", 6 }; +const pj_str_t pjsip_USERNAME_STR = { "username", 8 }, + pjsip_REALM_STR = { "realm", 5}, + pjsip_NONCE_STR = { "nonce", 5}, + pjsip_URI_STR = { "uri", 3 }, + pjsip_RESPONSE_STR = { "response", 8 }, + pjsip_ALGORITHM_STR = { "algorithm", 9 }, + pjsip_DOMAIN_STR = { "domain", 6 }, + pjsip_STALE_STR = { "stale", 5}, + pjsip_QOP_STR = { "qop", 3}, + pjsip_CNONCE_STR = { "cnonce", 6}, + pjsip_OPAQUE_STR = { "opaque", 6}, + pjsip_NC_STR = { "nc", 2}, + pjsip_TRUE_STR = { "true", 4}, + pjsip_QUOTED_TRUE_STR = { "\"true\"", 6}, + pjsip_FALSE_STR = { "false", 5}, + pjsip_QUOTED_FALSE_STR = { "\"false\"", 7}, + pjsip_DIGEST_STR = { "Digest", 6}, + pjsip_QUOTED_DIGEST_STR = { "\"Digest\"", 8}, + pjsip_PGP_STR = { "PGP", 3 }, + pjsip_QUOTED_PGP_STR = { "\"PGP\"", 5 }, + pjsip_BEARER_STR = { "Bearer", 6 }, + pjsip_MD5_STR = { "MD5", 3 }, + pjsip_QUOTED_MD5_STR = { "\"MD5\"", 5}, + pjsip_SHA256_STR = { "SHA-256", 7 }, + pjsip_QUOTED_SHA256_STR = { "\"SHA-256\"", 9}, + pjsip_AUTH_STR = { "auth", 4}, + pjsip_QUOTED_AUTH_STR = { "\"auth\"", 6 }; static void parse_digest_credential( pj_scanner *scanner, pj_pool_t *pool, @@ -74,53 +73,53 @@ static void parse_digest_credential( pj_scanner *scanner, pj_pool_t *pool, pj_list_init(&cred->other_param); for (;;) { - pj_str_t name, value; + pj_str_t name, value; - pjsip_parse_param_imp(scanner, pool, &name, &value, - PJSIP_PARSE_REMOVE_QUOTE); + pjsip_parse_param_imp(scanner, pool, &name, &value, + PJSIP_PARSE_REMOVE_QUOTE); - if (!pj_stricmp(&name, &pjsip_USERNAME_STR)) { - cred->username = value; + if (!pj_stricmp(&name, &pjsip_USERNAME_STR)) { + cred->username = value; - } else if (!pj_stricmp(&name, &pjsip_REALM_STR)) { - cred->realm = value; + } else if (!pj_stricmp(&name, &pjsip_REALM_STR)) { + cred->realm = value; - } else if (!pj_stricmp(&name, &pjsip_NONCE_STR)) { - cred->nonce = value; + } else if (!pj_stricmp(&name, &pjsip_NONCE_STR)) { + cred->nonce = value; - } else if (!pj_stricmp(&name, &pjsip_URI_STR)) { - cred->uri = value; + } else if (!pj_stricmp(&name, &pjsip_URI_STR)) { + cred->uri = value; - } else if (!pj_stricmp(&name, &pjsip_RESPONSE_STR)) { - cred->response = value; + } else if (!pj_stricmp(&name, &pjsip_RESPONSE_STR)) { + cred->response = value; - } else if (!pj_stricmp(&name, &pjsip_ALGORITHM_STR)) { - cred->algorithm = value; + } else if (!pj_stricmp(&name, &pjsip_ALGORITHM_STR)) { + cred->algorithm = value; - } else if (!pj_stricmp(&name, &pjsip_CNONCE_STR)) { - cred->cnonce = value; + } else if (!pj_stricmp(&name, &pjsip_CNONCE_STR)) { + cred->cnonce = value; - } else if (!pj_stricmp(&name, &pjsip_OPAQUE_STR)) { - cred->opaque = value; + } else if (!pj_stricmp(&name, &pjsip_OPAQUE_STR)) { + cred->opaque = value; - } else if (!pj_stricmp(&name, &pjsip_QOP_STR)) { - cred->qop = value; + } else if (!pj_stricmp(&name, &pjsip_QOP_STR)) { + cred->qop = value; - } else if (!pj_stricmp(&name, &pjsip_NC_STR)) { - cred->nc = value; + } else if (!pj_stricmp(&name, &pjsip_NC_STR)) { + cred->nc = value; - } else { - pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); - p->name = name; - p->value = value; - pj_list_insert_before(&cred->other_param, p); - } + } else { + pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); + p->name = name; + p->value = value; + pj_list_insert_before(&cred->other_param, p); + } - /* Eat comma */ - if (!pj_scan_is_eof(scanner) && *scanner->curptr == ',') - pj_scan_get_char(scanner); - else - break; + /* Eat comma */ + if (!pj_scan_is_eof(scanner) && *scanner->curptr == ',') + pj_scan_get_char(scanner); + else + break; } } @@ -140,56 +139,56 @@ static void parse_digest_challenge( pj_scanner *scanner, pj_pool_t *pool, pj_list_init(&chal->other_param); for (;;) { - pj_str_t name, value, unquoted_value; + pj_str_t name, value, unquoted_value; - pjsip_parse_param_imp(scanner, pool, &name, &value, 0); + pjsip_parse_param_imp(scanner, pool, &name, &value, 0); if (value.ptr && (value.ptr[0] == '"')) { - unquoted_value.ptr = value.ptr + 1; - unquoted_value.slen = value.slen - 2; - } else { - unquoted_value.ptr = value.ptr; - unquoted_value.slen = value.slen; - } + unquoted_value.ptr = value.ptr + 1; + unquoted_value.slen = value.slen - 2; + } else { + unquoted_value.ptr = value.ptr; + unquoted_value.slen = value.slen; + } - if (!pj_stricmp(&name, &pjsip_REALM_STR)) { - chal->realm = unquoted_value; + if (!pj_stricmp(&name, &pjsip_REALM_STR)) { + chal->realm = unquoted_value; - } else if (!pj_stricmp(&name, &pjsip_DOMAIN_STR)) { - chal->domain = unquoted_value; + } else if (!pj_stricmp(&name, &pjsip_DOMAIN_STR)) { + chal->domain = unquoted_value; - } else if (!pj_stricmp(&name, &pjsip_NONCE_STR)) { - chal->nonce = unquoted_value; + } else if (!pj_stricmp(&name, &pjsip_NONCE_STR)) { + chal->nonce = unquoted_value; - } else if (!pj_stricmp(&name, &pjsip_OPAQUE_STR)) { - chal->opaque = unquoted_value; + } else if (!pj_stricmp(&name, &pjsip_OPAQUE_STR)) { + chal->opaque = unquoted_value; - } else if (!pj_stricmp(&name, &pjsip_STALE_STR)) { - if (!pj_stricmp(&value, &pjsip_TRUE_STR) || + } else if (!pj_stricmp(&name, &pjsip_STALE_STR)) { + if (!pj_stricmp(&value, &pjsip_TRUE_STR) || !pj_stricmp(&value, &pjsip_QUOTED_TRUE_STR)) { - chal->stale = 1; + chal->stale = 1; } - } else if (!pj_stricmp(&name, &pjsip_ALGORITHM_STR)) { - chal->algorithm = unquoted_value; + } else if (!pj_stricmp(&name, &pjsip_ALGORITHM_STR)) { + chal->algorithm = unquoted_value; - } else if (!pj_stricmp(&name, &pjsip_QOP_STR)) { - chal->qop = unquoted_value; + } else if (!pj_stricmp(&name, &pjsip_QOP_STR)) { + chal->qop = unquoted_value; - } else { - pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); - p->name = name; - p->value = value; - pj_list_insert_before(&chal->other_param, p); - } + } else { + pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); + p->name = name; + p->value = value; + pj_list_insert_before(&chal->other_param, p); + } - /* Eat comma */ - if (!pj_scan_is_eof(scanner) && *scanner->curptr == ',') - pj_scan_get_char(scanner); - else - break; + /* Eat comma */ + if (!pj_scan_is_eof(scanner) && *scanner->curptr == ',') + pj_scan_get_char(scanner); + else + break; } } @@ -204,56 +203,56 @@ static void parse_pgp_challenge( pj_scanner *scanner, pj_pool_t *pool, } static void int_parse_hdr_authorization( pj_scanner *scanner, pj_pool_t *pool, - pjsip_authorization_hdr *hdr) + pjsip_authorization_hdr *hdr) { const pjsip_parser_const_t *pc = pjsip_parser_const(); if (*scanner->curptr == '"') { - pj_scan_get_quote(scanner, '"', '"', &hdr->scheme); - hdr->scheme.ptr++; - hdr->scheme.slen -= 2; + pj_scan_get_quote(scanner, '"', '"', &hdr->scheme); + hdr->scheme.ptr++; + hdr->scheme.slen -= 2; } else { - pj_scan_get(scanner, &pc->pjsip_TOKEN_SPEC, &hdr->scheme); + pj_scan_get(scanner, &pc->pjsip_TOKEN_SPEC, &hdr->scheme); } if (!pj_stricmp(&hdr->scheme, &pjsip_DIGEST_STR)) { - parse_digest_credential(scanner, pool, &hdr->credential.digest); + parse_digest_credential(scanner, pool, &hdr->credential.digest); } else if (!pj_stricmp(&hdr->scheme, &pjsip_PGP_STR)) { - parse_pgp_credential( scanner, pool, &hdr->credential.pgp); + parse_pgp_credential( scanner, pool, &hdr->credential.pgp); } else { - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); } pjsip_parse_end_hdr_imp( scanner ); } static void int_parse_hdr_authenticate( pj_scanner *scanner, pj_pool_t *pool, - pjsip_www_authenticate_hdr *hdr) + pjsip_www_authenticate_hdr *hdr) { const pjsip_parser_const_t *pc = pjsip_parser_const(); if (*scanner->curptr == '"') { - pj_scan_get_quote(scanner, '"', '"', &hdr->scheme); - hdr->scheme.ptr++; - hdr->scheme.slen -= 2; + pj_scan_get_quote(scanner, '"', '"', &hdr->scheme); + hdr->scheme.ptr++; + hdr->scheme.slen -= 2; } else { - pj_scan_get(scanner, &pc->pjsip_TOKEN_SPEC, &hdr->scheme); + pj_scan_get(scanner, &pc->pjsip_TOKEN_SPEC, &hdr->scheme); } if (!pj_stricmp(&hdr->scheme, &pjsip_DIGEST_STR)) { - parse_digest_challenge(scanner, pool, &hdr->challenge.digest); + parse_digest_challenge(scanner, pool, &hdr->challenge.digest); } else if (!pj_stricmp(&hdr->scheme, &pjsip_PGP_STR)) { - parse_pgp_challenge(scanner, pool, &hdr->challenge.pgp); + parse_pgp_challenge(scanner, pool, &hdr->challenge.pgp); } else { - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); } pjsip_parse_end_hdr_imp( scanner ); diff --git a/pjsip/src/pjsip/sip_auth_parser_wrap.cpp b/pjsip/src/pjsip/sip_auth_parser_wrap.cpp index a0c083f5b8..bdb7449b5f 100644 --- a/pjsip/src/pjsip/sip_auth_parser_wrap.cpp +++ b/pjsip/src/pjsip/sip_auth_parser_wrap.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjsip/src/pjsip/sip_auth_server.c b/pjsip/src/pjsip/sip_auth_server.c index ae5b6fd436..8eee2b51b6 100644 --- a/pjsip/src/pjsip/sip_auth_server.c +++ b/pjsip/src/pjsip/sip_auth_server.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -19,7 +18,7 @@ */ #include -#include /* just to get pjsip_DIGEST_STR */ +#include /* just to get pjsip_DIGEST_STR */ #include #include #include @@ -33,10 +32,10 @@ * info. */ PJ_DEF(pj_status_t) pjsip_auth_srv_init( pj_pool_t *pool, - pjsip_auth_srv *auth_srv, - const pj_str_t *realm, - pjsip_auth_lookup_cred *lookup, - unsigned options ) + pjsip_auth_srv *auth_srv, + const pj_str_t *realm, + pjsip_auth_lookup_cred *lookup, + unsigned options ) { PJ_ASSERT_RETURN(pool && auth_srv && realm && lookup, PJ_EINVAL); @@ -54,9 +53,9 @@ PJ_DEF(pj_status_t) pjsip_auth_srv_init( pj_pool_t *pool, * info. */ PJ_DEF(pj_status_t) pjsip_auth_srv_init2( - pj_pool_t *pool, - pjsip_auth_srv *auth_srv, - const pjsip_auth_srv_init_param *param) + pj_pool_t *pool, + pjsip_auth_srv *auth_srv, + const pjsip_auth_srv_init_param *param) { PJ_ASSERT_RETURN(pool && auth_srv && param, PJ_EINVAL); @@ -73,49 +72,49 @@ PJ_DEF(pj_status_t) pjsip_auth_srv_init2( * specified credential. */ static pj_status_t pjsip_auth_verify( const pjsip_authorization_hdr *hdr, - const pj_str_t *method, - const pjsip_cred_info *cred_info ) + const pj_str_t *method, + const pjsip_cred_info *cred_info ) { if (pj_stricmp(&hdr->scheme, &pjsip_DIGEST_STR) == 0) { - char digest_buf[PJSIP_MD5STRLEN]; - pj_str_t digest; - pj_status_t status; - const pjsip_digest_credential *dig = &hdr->credential.digest; - - /* Check that username and realm match. - * These checks should have been performed before entering this - * function. - */ - PJ_ASSERT_RETURN(pj_strcmp(&dig->username, &cred_info->username) == 0, - PJ_EINVALIDOP); - PJ_ASSERT_RETURN(pj_strcmp(&dig->realm, &cred_info->realm) == 0, - PJ_EINVALIDOP); - - /* Prepare for our digest calculation. */ - digest.ptr = digest_buf; - digest.slen = PJSIP_MD5STRLEN; - - /* Create digest for comparison. */ - status = pjsip_auth_create_digest(&digest, - &hdr->credential.digest.nonce, - &hdr->credential.digest.nc, - &hdr->credential.digest.cnonce, - &hdr->credential.digest.qop, - &hdr->credential.digest.uri, - &cred_info->realm, - cred_info, - method ); - - if (status != PJ_SUCCESS) - return status; - - /* Compare digest. */ - return (pj_stricmp(&digest, &hdr->credential.digest.response) == 0) ? - PJ_SUCCESS : PJSIP_EAUTHINVALIDDIGEST; + char digest_buf[PJSIP_MD5STRLEN]; + pj_str_t digest; + pj_status_t status; + const pjsip_digest_credential *dig = &hdr->credential.digest; + + /* Check that username and realm match. + * These checks should have been performed before entering this + * function. + */ + PJ_ASSERT_RETURN(pj_strcmp(&dig->username, &cred_info->username) == 0, + PJ_EINVALIDOP); + PJ_ASSERT_RETURN(pj_strcmp(&dig->realm, &cred_info->realm) == 0, + PJ_EINVALIDOP); + + /* Prepare for our digest calculation. */ + digest.ptr = digest_buf; + digest.slen = PJSIP_MD5STRLEN; + + /* Create digest for comparison. */ + status = pjsip_auth_create_digest(&digest, + &hdr->credential.digest.nonce, + &hdr->credential.digest.nc, + &hdr->credential.digest.cnonce, + &hdr->credential.digest.qop, + &hdr->credential.digest.uri, + &cred_info->realm, + cred_info, + method ); + + if (status != PJ_SUCCESS) + return status; + + /* Compare digest. */ + return (pj_stricmp(&digest, &hdr->credential.digest.response) == 0) ? + PJ_SUCCESS : PJSIP_EAUTHINVALIDDIGEST; } else { - pj_assert(!"Unsupported authentication scheme"); - return PJSIP_EINVALIDAUTHSCHEME; + pj_assert(!"Unsupported authentication scheme"); + return PJSIP_EINVALIDAUTHSCHEME; } } @@ -125,8 +124,8 @@ static pj_status_t pjsip_auth_verify( const pjsip_authorization_hdr *hdr, * information in the specified request in rdata. */ PJ_DEF(pj_status_t) pjsip_auth_srv_verify( pjsip_auth_srv *auth_srv, - pjsip_rx_data *rdata, - int *status_code) + pjsip_rx_data *rdata, + int *status_code) { pjsip_authorization_hdr *h_auth; pjsip_msg *msg = rdata->msg_info.msg; @@ -139,7 +138,7 @@ PJ_DEF(pj_status_t) pjsip_auth_srv_verify( pjsip_auth_srv *auth_srv, PJ_ASSERT_RETURN(msg->type == PJSIP_REQUEST_MSG, PJSIP_ENOTREQUESTMSG); htype = auth_srv->is_proxy ? PJSIP_H_PROXY_AUTHORIZATION : - PJSIP_H_AUTHORIZATION; + PJSIP_H_AUTHORIZATION; /* Initialize status with 200. */ *status_code = 200; @@ -147,58 +146,58 @@ PJ_DEF(pj_status_t) pjsip_auth_srv_verify( pjsip_auth_srv *auth_srv, /* Find authorization header for our realm. */ h_auth = (pjsip_authorization_hdr*) pjsip_msg_find_hdr(msg, htype, NULL); while (h_auth) { - if (!pj_stricmp(&h_auth->credential.common.realm, &auth_srv->realm)) - break; + if (!pj_stricmp(&h_auth->credential.common.realm, &auth_srv->realm)) + break; - h_auth = h_auth->next; - if (h_auth == (void*) &msg->hdr) { - h_auth = NULL; - break; - } + h_auth = h_auth->next; + if (h_auth == (void*) &msg->hdr) { + h_auth = NULL; + break; + } - h_auth=(pjsip_authorization_hdr*)pjsip_msg_find_hdr(msg,htype,h_auth); + h_auth=(pjsip_authorization_hdr*)pjsip_msg_find_hdr(msg,htype,h_auth); } if (!h_auth) { - *status_code = auth_srv->is_proxy ? 407 : 401; - return PJSIP_EAUTHNOAUTH; + *status_code = auth_srv->is_proxy ? 407 : 401; + return PJSIP_EAUTHNOAUTH; } /* Check authorization scheme. */ if (pj_stricmp(&h_auth->scheme, &pjsip_DIGEST_STR) == 0) - acc_name = h_auth->credential.digest.username; + acc_name = h_auth->credential.digest.username; else { - *status_code = auth_srv->is_proxy ? 407 : 401; - return PJSIP_EINVALIDAUTHSCHEME; + *status_code = auth_srv->is_proxy ? 407 : 401; + return PJSIP_EINVALIDAUTHSCHEME; } /* Find the credential information for the account. */ if (auth_srv->lookup2) { - pjsip_auth_lookup_cred_param param; - - pj_bzero(¶m, sizeof(param)); - param.realm = auth_srv->realm; - param.acc_name = acc_name; - param.rdata = rdata; - status = (*auth_srv->lookup2)(rdata->tp_info.pool, ¶m, &cred_info); - if (status != PJ_SUCCESS) { - *status_code = PJSIP_SC_FORBIDDEN; - return status; - } + pjsip_auth_lookup_cred_param param; + + pj_bzero(¶m, sizeof(param)); + param.realm = auth_srv->realm; + param.acc_name = acc_name; + param.rdata = rdata; + status = (*auth_srv->lookup2)(rdata->tp_info.pool, ¶m, &cred_info); + if (status != PJ_SUCCESS) { + *status_code = PJSIP_SC_FORBIDDEN; + return status; + } } else { - status = (*auth_srv->lookup)(rdata->tp_info.pool, &auth_srv->realm, - &acc_name, &cred_info); - if (status != PJ_SUCCESS) { - *status_code = PJSIP_SC_FORBIDDEN; - return status; - } + status = (*auth_srv->lookup)(rdata->tp_info.pool, &auth_srv->realm, + &acc_name, &cred_info); + if (status != PJ_SUCCESS) { + *status_code = PJSIP_SC_FORBIDDEN; + return status; + } } /* Authenticate with the specified credential. */ status = pjsip_auth_verify(h_auth, &msg->line.req.method.name, - &cred_info); + &cred_info); if (status != PJ_SUCCESS) { - *status_code = PJSIP_SC_FORBIDDEN; + *status_code = PJSIP_SC_FORBIDDEN; } return status; } @@ -211,11 +210,11 @@ PJ_DEF(pj_status_t) pjsip_auth_srv_verify( pjsip_auth_srv *auth_srv, * random characters. */ PJ_DEF(pj_status_t) pjsip_auth_srv_challenge( pjsip_auth_srv *auth_srv, - const pj_str_t *qop, - const pj_str_t *nonce, - const pj_str_t *opaque, - pj_bool_t stale, - pjsip_tx_data *tdata) + const pj_str_t *qop, + const pj_str_t *nonce, + const pj_str_t *opaque, + pj_bool_t stale, + pjsip_tx_data *tdata) { pjsip_www_authenticate_hdr *hdr; char nonce_buf[16]; @@ -228,9 +227,9 @@ PJ_DEF(pj_status_t) pjsip_auth_srv_challenge( pjsip_auth_srv *auth_srv, /* Create the header. */ if (auth_srv->is_proxy) - hdr = pjsip_proxy_authenticate_hdr_create(tdata->pool); + hdr = pjsip_proxy_authenticate_hdr_create(tdata->pool); else - hdr = pjsip_www_authenticate_hdr_create(tdata->pool); + hdr = pjsip_www_authenticate_hdr_create(tdata->pool); /* Initialize header. * Note: only support digest authentication now. @@ -238,21 +237,21 @@ PJ_DEF(pj_status_t) pjsip_auth_srv_challenge( pjsip_auth_srv *auth_srv, hdr->scheme = pjsip_DIGEST_STR; hdr->challenge.digest.algorithm = pjsip_MD5_STR; if (nonce) { - pj_strdup(tdata->pool, &hdr->challenge.digest.nonce, nonce); + pj_strdup(tdata->pool, &hdr->challenge.digest.nonce, nonce); } else { - pj_create_random_string(nonce_buf, sizeof(nonce_buf)); - pj_strdup(tdata->pool, &hdr->challenge.digest.nonce, &random); + pj_create_random_string(nonce_buf, sizeof(nonce_buf)); + pj_strdup(tdata->pool, &hdr->challenge.digest.nonce, &random); } if (opaque) { - pj_strdup(tdata->pool, &hdr->challenge.digest.opaque, opaque); + pj_strdup(tdata->pool, &hdr->challenge.digest.opaque, opaque); } else { - pj_create_random_string(nonce_buf, sizeof(nonce_buf)); - pj_strdup(tdata->pool, &hdr->challenge.digest.opaque, &random); + pj_create_random_string(nonce_buf, sizeof(nonce_buf)); + pj_strdup(tdata->pool, &hdr->challenge.digest.opaque, &random); } if (qop) { - pj_strdup(tdata->pool, &hdr->challenge.digest.qop, qop); + pj_strdup(tdata->pool, &hdr->challenge.digest.qop, qop); } else { - hdr->challenge.digest.qop.slen = 0; + hdr->challenge.digest.qop.slen = 0; } pj_strdup(tdata->pool, &hdr->challenge.digest.realm, &auth_srv->realm); hdr->challenge.digest.stale = stale; diff --git a/pjsip/src/pjsip/sip_config.c b/pjsip/src/pjsip/sip_config.c index 6920b3dfe5..bf5f8b3471 100644 --- a/pjsip/src/pjsip/sip_config.c +++ b/pjsip/src/pjsip/sip_config.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -54,7 +53,7 @@ pjsip_cfg_t pjsip_sip_cfg_var = /* Client registration client */ { - PJSIP_REGISTER_CLIENT_CHECK_CONTACT + PJSIP_REGISTER_CLIENT_CHECK_CONTACT }, /* TCP transport settings */ @@ -72,189 +71,189 @@ PJ_DEF(void) pjsip_dump_config(void) { PJ_LOG(3, (id, "Dumping PJSIP configurations:")); PJ_LOG(3, (id, " PJSIP_MAX_DIALOG_COUNT : %d", - PJSIP_MAX_DIALOG_COUNT)); + PJSIP_MAX_DIALOG_COUNT)); PJ_LOG(3, (id, " PJSIP_MAX_TRANSPORTS : %d", - PJSIP_MAX_TRANSPORTS)); + PJSIP_MAX_TRANSPORTS)); PJ_LOG(3, (id, " PJSIP_TPMGR_HTABLE_SIZE : %d", - PJSIP_TPMGR_HTABLE_SIZE)); + PJSIP_TPMGR_HTABLE_SIZE)); PJ_LOG(3, (id, " PJSIP_MAX_URL_SIZE : %d", - PJSIP_MAX_URL_SIZE)); + PJSIP_MAX_URL_SIZE)); PJ_LOG(3, (id, " PJSIP_MAX_MODULE : %d", - PJSIP_MAX_MODULE)); + PJSIP_MAX_MODULE)); PJ_LOG(3, (id, " PJSIP_MAX_PKT_LEN : %d", - PJSIP_MAX_PKT_LEN)); + PJSIP_MAX_PKT_LEN)); PJ_LOG(3, (id, " PJSIP_HANDLE_EVENTS_HAS_SLEEP_ON_ERR : %d", - PJSIP_HANDLE_EVENTS_HAS_SLEEP_ON_ERR)); + PJSIP_HANDLE_EVENTS_HAS_SLEEP_ON_ERR)); PJ_LOG(3, (id, " PJSIP_ACCEPT_MULTIPLE_SDP_ANSWERS : %d", - PJSIP_ACCEPT_MULTIPLE_SDP_ANSWERS)); + PJSIP_ACCEPT_MULTIPLE_SDP_ANSWERS)); PJ_LOG(3, (id, " PJSIP_UDP_SIZE_THRESHOLD : %d", - PJSIP_UDP_SIZE_THRESHOLD)); + PJSIP_UDP_SIZE_THRESHOLD)); PJ_LOG(3, (id, " PJSIP_INCLUDE_ALLOW_HDR_IN_DLG : %d", - PJSIP_INCLUDE_ALLOW_HDR_IN_DLG)); + PJSIP_INCLUDE_ALLOW_HDR_IN_DLG)); PJ_LOG(3, (id, " PJSIP_SAFE_MODULE : %d", - PJSIP_SAFE_MODULE)); + PJSIP_SAFE_MODULE)); PJ_LOG(3, (id, " PJSIP_CHECK_VIA_SENT_BY : %d", - PJSIP_CHECK_VIA_SENT_BY)); + PJSIP_CHECK_VIA_SENT_BY)); PJ_LOG(3, (id, " PJSIP_UNESCAPE_IN_PLACE : %d", - PJSIP_UNESCAPE_IN_PLACE)); + PJSIP_UNESCAPE_IN_PLACE)); PJ_LOG(3, (id, " PJSIP_MAX_NET_EVENTS : %d", - PJSIP_MAX_NET_EVENTS)); + PJSIP_MAX_NET_EVENTS)); PJ_LOG(3, (id, " PJSIP_MAX_TIMED_OUT_ENTRIES : %d", - PJSIP_MAX_TIMED_OUT_ENTRIES)); + PJSIP_MAX_TIMED_OUT_ENTRIES)); PJ_LOG(3, (id, " PJSIP_TRANSPORT_IDLE_TIME : %d", - PJSIP_TRANSPORT_IDLE_TIME)); + PJSIP_TRANSPORT_IDLE_TIME)); PJ_LOG(3, (id, " PJSIP_TRANSPORT_SERVER_IDLE_TIME : %d", - PJSIP_TRANSPORT_SERVER_IDLE_TIME)); + PJSIP_TRANSPORT_SERVER_IDLE_TIME)); PJ_LOG(3, (id, " PJSIP_MAX_TRANSPORT_USAGE : %d", - PJSIP_MAX_TRANSPORT_USAGE)); + PJSIP_MAX_TRANSPORT_USAGE)); PJ_LOG(3, (id, " PJSIP_TCP_TRANSPORT_BACKLOG : %d", - PJSIP_TCP_TRANSPORT_BACKLOG)); + PJSIP_TCP_TRANSPORT_BACKLOG)); PJ_LOG(3, (id, " PJSIP_TCP_TRANSPORT_REUSEADDR : %d", - PJSIP_TCP_TRANSPORT_REUSEADDR)); + PJSIP_TCP_TRANSPORT_REUSEADDR)); PJ_LOG(3, (id, " PJSIP_TCP_TRANSPORT_DONT_CREATE_LISTENER : %d", - PJSIP_TCP_TRANSPORT_DONT_CREATE_LISTENER)); + PJSIP_TCP_TRANSPORT_DONT_CREATE_LISTENER)); PJ_LOG(3, (id, " PJSIP_TLS_TRANSPORT_DONT_CREATE_LISTENER : %d", - PJSIP_TLS_TRANSPORT_DONT_CREATE_LISTENER)); + PJSIP_TLS_TRANSPORT_DONT_CREATE_LISTENER)); PJ_LOG(3, (id, " PJSIP_TCP_KEEP_ALIVE_INTERVAL : %d", - PJSIP_TCP_KEEP_ALIVE_INTERVAL)); + PJSIP_TCP_KEEP_ALIVE_INTERVAL)); PJ_LOG(3, (id, " PJSIP_POOL_INC_TRANSPORT : %d", - PJSIP_POOL_INC_TRANSPORT)); + PJSIP_POOL_INC_TRANSPORT)); PJ_LOG(3, (id, " PJSIP_POOL_LEN_TDATA : %d", - PJSIP_POOL_LEN_TDATA)); + PJSIP_POOL_LEN_TDATA)); PJ_LOG(3, (id, " PJSIP_POOL_INC_TDATA : %d", - PJSIP_POOL_INC_TDATA)); + PJSIP_POOL_INC_TDATA)); PJ_LOG(3, (id, " PJSIP_POOL_LEN_UA : %d", - PJSIP_POOL_LEN_UA)); + PJSIP_POOL_LEN_UA)); PJ_LOG(3, (id, " PJSIP_POOL_INC_UA : %d", - PJSIP_POOL_INC_UA)); + PJSIP_POOL_INC_UA)); PJ_LOG(3, (id, " PJSIP_POOL_EVSUB_LEN : %d", - PJSIP_POOL_EVSUB_LEN)); + PJSIP_POOL_EVSUB_LEN)); PJ_LOG(3, (id, " PJSIP_POOL_EVSUB_INC : %d", - PJSIP_POOL_EVSUB_INC)); + PJSIP_POOL_EVSUB_INC)); PJ_LOG(3, (id, " PJSIP_MAX_FORWARDS_VALUE : %d", - PJSIP_MAX_FORWARDS_VALUE)); + PJSIP_MAX_FORWARDS_VALUE)); PJ_LOG(3, (id, " PJSIP_RFC3261_BRANCH_ID : %s", - PJSIP_RFC3261_BRANCH_ID)); + PJSIP_RFC3261_BRANCH_ID)); PJ_LOG(3, (id, " PJSIP_RFC3261_BRANCH_LEN : %d", - PJSIP_RFC3261_BRANCH_LEN)); + PJSIP_RFC3261_BRANCH_LEN)); PJ_LOG(3, (id, " PJSIP_POOL_TSX_LAYER_LEN : %d", - PJSIP_POOL_TSX_LAYER_LEN)); + PJSIP_POOL_TSX_LAYER_LEN)); PJ_LOG(3, (id, " PJSIP_POOL_TSX_LAYER_INC : %d", - PJSIP_POOL_TSX_LAYER_INC)); + PJSIP_POOL_TSX_LAYER_INC)); PJ_LOG(3, (id, " PJSIP_POOL_TSX_LEN : %d", - PJSIP_POOL_TSX_LEN)); + PJSIP_POOL_TSX_LEN)); PJ_LOG(3, (id, " PJSIP_POOL_TSX_INC : %d", - PJSIP_POOL_TSX_INC)); + PJSIP_POOL_TSX_INC)); PJ_LOG(3, (id, " PJSIP_TSX_1XX_RETRANS_DELAY : %d", - PJSIP_TSX_1XX_RETRANS_DELAY)); + PJSIP_TSX_1XX_RETRANS_DELAY)); PJ_LOG(3, (id, " PJSIP_TSX_UAS_CONTINUE_ON_TP_ERROR : %d", - PJSIP_TSX_UAS_CONTINUE_ON_TP_ERROR)); + PJSIP_TSX_UAS_CONTINUE_ON_TP_ERROR)); PJ_LOG(3, (id, " PJSIP_MAX_TSX_KEY_LEN : %d", - PJSIP_MAX_TSX_KEY_LEN)); + PJSIP_MAX_TSX_KEY_LEN)); PJ_LOG(3, (id, " PJSIP_POOL_LEN_USER_AGENT : %d", - PJSIP_POOL_LEN_USER_AGENT)); + PJSIP_POOL_LEN_USER_AGENT)); PJ_LOG(3, (id, " PJSIP_POOL_INC_USER_AGENT : %d", - PJSIP_POOL_INC_USER_AGENT)); + PJSIP_POOL_INC_USER_AGENT)); PJ_LOG(3, (id, " PJSIP_MAX_BRANCH_LEN : %d", - PJSIP_MAX_HNAME_LEN)); + PJSIP_MAX_HNAME_LEN)); PJ_LOG(3, (id, " PJSIP_POOL_LEN_DIALOG : %d", - PJSIP_POOL_LEN_DIALOG)); + PJSIP_POOL_LEN_DIALOG)); PJ_LOG(3, (id, " PJSIP_POOL_INC_DIALOG : %d", - PJSIP_POOL_INC_DIALOG)); + PJSIP_POOL_INC_DIALOG)); PJ_LOG(3, (id, " PJSIP_MAX_HEADER_TYPES : %d", - PJSIP_MAX_HEADER_TYPES)); + PJSIP_MAX_HEADER_TYPES)); PJ_LOG(3, (id, " PJSIP_MAX_URI_TYPES : %d", - PJSIP_MAX_URI_TYPES)); + PJSIP_MAX_URI_TYPES)); PJ_LOG(3, (id, " PJSIP_AUTH_HEADER_CACHING : %d", - PJSIP_AUTH_HEADER_CACHING)); + PJSIP_AUTH_HEADER_CACHING)); PJ_LOG(3, (id, " PJSIP_AUTH_AUTO_SEND_NEXT : %d", - PJSIP_AUTH_AUTO_SEND_NEXT)); + PJSIP_AUTH_AUTO_SEND_NEXT)); PJ_LOG(3, (id, " PJSIP_AUTH_QOP_SUPPORT : %d", - PJSIP_AUTH_QOP_SUPPORT)); + PJSIP_AUTH_QOP_SUPPORT)); PJ_LOG(3, (id, " PJSIP_MAX_STALE_COUNT : %d", - PJSIP_MAX_STALE_COUNT)); + PJSIP_MAX_STALE_COUNT)); PJ_LOG(3, (id, " PJSIP_HAS_DIGEST_AKA_AUTH : %d", - PJSIP_HAS_DIGEST_AKA_AUTH)); + PJSIP_HAS_DIGEST_AKA_AUTH)); PJ_LOG(3, (id, " PJSIP_REGISTER_CLIENT_DELAY_BEFORE_REFRESH : %d", - PJSIP_REGISTER_CLIENT_DELAY_BEFORE_REFRESH)); + PJSIP_REGISTER_CLIENT_DELAY_BEFORE_REFRESH)); PJ_LOG(3, (id, " PJSIP_REGISTER_ALLOW_EXP_REFRESH : %d", - PJSIP_REGISTER_ALLOW_EXP_REFRESH)); + PJSIP_REGISTER_ALLOW_EXP_REFRESH)); PJ_LOG(3, (id, " PJSIP_AUTH_CACHED_POOL_MAX_SIZE : %d", - PJSIP_AUTH_CACHED_POOL_MAX_SIZE)); + PJSIP_AUTH_CACHED_POOL_MAX_SIZE)); PJ_LOG(3, (id, " PJSIP_AUTH_CNONCE_USE_DIGITS_ONLY : %d", - PJSIP_AUTH_CNONCE_USE_DIGITS_ONLY)); + PJSIP_AUTH_CNONCE_USE_DIGITS_ONLY)); PJ_LOG(3, (id, " PJSIP_AUTH_ALLOW_MULTIPLE_AUTH_HEADER : %d", - PJSIP_AUTH_ALLOW_MULTIPLE_AUTH_HEADER)); + PJSIP_AUTH_ALLOW_MULTIPLE_AUTH_HEADER)); PJ_LOG(3, (id, " PJSIP_EVSUB_TIME_UAC_REFRESH : %d", - PJSIP_EVSUB_TIME_UAC_REFRESH)); + PJSIP_EVSUB_TIME_UAC_REFRESH)); PJ_LOG(3, (id, " PJSIP_PUBLISHC_DELAY_BEFORE_REFRESH : %d", - PJSIP_PUBLISHC_DELAY_BEFORE_REFRESH)); + PJSIP_PUBLISHC_DELAY_BEFORE_REFRESH)); PJ_LOG(3, (id, " PJSIP_EVSUB_TIME_UAC_TERMINATE : %d", - PJSIP_EVSUB_TIME_UAC_TERMINATE)); + PJSIP_EVSUB_TIME_UAC_TERMINATE)); PJ_LOG(3, (id, " PJSIP_EVSUB_TIME_UAC_WAIT_NOTIFY : %d", - PJSIP_EVSUB_TIME_UAC_WAIT_NOTIFY)); + PJSIP_EVSUB_TIME_UAC_WAIT_NOTIFY)); PJ_LOG(3, (id, " PJSIP_PRES_DEFAULT_EXPIRES : %d", - PJSIP_PRES_DEFAULT_EXPIRES)); + PJSIP_PRES_DEFAULT_EXPIRES)); PJ_LOG(3, (id, " PJSIP_PRES_BAD_CONTENT_RESPONSE : %d", - PJSIP_PRES_BAD_CONTENT_RESPONSE)); + PJSIP_PRES_BAD_CONTENT_RESPONSE)); PJ_LOG(3, (id, " PJSIP_PRES_PIDF_ADD_TIMESTAMP : %d", - PJSIP_PRES_PIDF_ADD_TIMESTAMP)); + PJSIP_PRES_PIDF_ADD_TIMESTAMP)); PJ_LOG(3, (id, " PJSIP_SESS_TIMER_DEF_SE : %d", - PJSIP_SESS_TIMER_DEF_SE)); + PJSIP_SESS_TIMER_DEF_SE)); PJ_LOG(3, (id, " PJSIP_SESS_TIMER_RETRY_DELAY : %d", - PJSIP_SESS_TIMER_RETRY_DELAY)); + PJSIP_SESS_TIMER_RETRY_DELAY)); PJ_LOG(3, (id, " PJSIP_PUBLISHC_QUEUE_REQUEST : %d", - PJSIP_PUBLISHC_QUEUE_REQUEST)); + PJSIP_PUBLISHC_QUEUE_REQUEST)); PJ_LOG(3, (id, " PJSIP_MWI_DEFAULT_EXPIRES : %d", - PJSIP_MWI_DEFAULT_EXPIRES)); + PJSIP_MWI_DEFAULT_EXPIRES)); PJ_LOG(3, (id, " PJSIP_HAS_TX_DATA_LIST : %d", - PJSIP_HAS_TX_DATA_LIST)); + PJSIP_HAS_TX_DATA_LIST)); PJ_LOG(3, (id, " PJSIP_INV_ACCEPT_UNKNOWN_BODY : %d", - PJSIP_INV_ACCEPT_UNKNOWN_BODY)); + PJSIP_INV_ACCEPT_UNKNOWN_BODY)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.allow_port_in_fromto_hdr : %d", - pjsip_cfg()->endpt.allow_port_in_fromto_hdr)); + pjsip_cfg()->endpt.allow_port_in_fromto_hdr)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.accept_replace_in_early_state : %d", - pjsip_cfg()->endpt.accept_replace_in_early_state)); + pjsip_cfg()->endpt.accept_replace_in_early_state)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.allow_tx_hash_in_uri : %d", - pjsip_cfg()->endpt.allow_tx_hash_in_uri)); + pjsip_cfg()->endpt.allow_tx_hash_in_uri)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.disable_rport : %d", - pjsip_cfg()->endpt.disable_rport)); + pjsip_cfg()->endpt.disable_rport)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.disable_tcp_switch : %d", - pjsip_cfg()->endpt.disable_tcp_switch)); + pjsip_cfg()->endpt.disable_tcp_switch)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.disable_tls_switch : %d", - pjsip_cfg()->endpt.disable_tls_switch)); + pjsip_cfg()->endpt.disable_tls_switch)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.follow_early_media_fork : %d", - pjsip_cfg()->endpt.follow_early_media_fork)); + pjsip_cfg()->endpt.follow_early_media_fork)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.req_has_via_alias : %d", - pjsip_cfg()->endpt.req_has_via_alias)); + pjsip_cfg()->endpt.req_has_via_alias)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.resolve_hostname_to_get_interface:%d", - pjsip_cfg()->endpt.resolve_hostname_to_get_interface)); + pjsip_cfg()->endpt.resolve_hostname_to_get_interface)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.disable_secure_dlg_check : %d", - pjsip_cfg()->endpt.disable_secure_dlg_check)); + pjsip_cfg()->endpt.disable_secure_dlg_check)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.use_compact_form : %d", - pjsip_cfg()->endpt.use_compact_form)); + pjsip_cfg()->endpt.use_compact_form)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.accept_multiple_sdp_answers : %d", - pjsip_cfg()->endpt.accept_multiple_sdp_answers)); + pjsip_cfg()->endpt.accept_multiple_sdp_answers)); PJ_LOG(3, (id, " pjsip_cfg()->endpt.keep_inv_after_tsx_timeout : %d", - pjsip_cfg()->endpt.keep_inv_after_tsx_timeout)); + pjsip_cfg()->endpt.keep_inv_after_tsx_timeout)); PJ_LOG(3, (id, " pjsip_cfg()->tsx.max_count : %d", - pjsip_cfg()->tsx.max_count)); + pjsip_cfg()->tsx.max_count)); PJ_LOG(3, (id, " pjsip_cfg()->tsx.t1 : %d", - pjsip_cfg()->tsx.t1)); + pjsip_cfg()->tsx.t1)); PJ_LOG(3, (id, " pjsip_cfg()->tsx.t2 : %d", - pjsip_cfg()->tsx.t2)); + pjsip_cfg()->tsx.t2)); PJ_LOG(3, (id, " pjsip_cfg()->tsx.t4 : %d", - pjsip_cfg()->tsx.t4)); + pjsip_cfg()->tsx.t4)); PJ_LOG(3, (id, " pjsip_cfg()->td : %d", - pjsip_cfg()->tsx.td)); + pjsip_cfg()->tsx.td)); PJ_LOG(3, (id, " pjsip_cfg()->regc.check_contact : %d", - pjsip_cfg()->regc.check_contact)); + pjsip_cfg()->regc.check_contact)); PJ_LOG(3, (id, " pjsip_cfg()->regc.add_xuid_param : %d", - pjsip_cfg()->regc.add_xuid_param)); + pjsip_cfg()->regc.add_xuid_param)); PJ_LOG(3, (id, " pjsip_cfg()->tcp.keep_alive_interval : %d", - pjsip_cfg()->tcp.keep_alive_interval)); + pjsip_cfg()->tcp.keep_alive_interval)); PJ_LOG(3, (id, " pjsip_cfg()->tls.keep_alive_interval : %d", - pjsip_cfg()->tls.keep_alive_interval)); + pjsip_cfg()->tls.keep_alive_interval)); } diff --git a/pjsip/src/pjsip/sip_dialog.c b/pjsip/src/pjsip/sip_dialog.c index 2d78aba116..bba63b78cd 100644 --- a/pjsip/src/pjsip/sip_dialog.c +++ b/pjsip/src/pjsip/sip_dialog.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,7 +35,7 @@ #include #include -#define THIS_FILE "sip_dialog.c" +#define THIS_FILE "sip_dialog.c" long pjsip_dlg_lock_tls_id; @@ -55,10 +54,10 @@ PJ_DEF(pj_bool_t) pjsip_method_creates_dialog(const pjsip_method *m) const pjsip_method update = { PJSIP_OTHER_METHOD, {"UPDATE", 6}}; return m->id == PJSIP_INVITE_METHOD || - (pjsip_method_cmp(m, &subscribe)==0) || - (pjsip_method_cmp(m, &refer)==0) || - (pjsip_method_cmp(m, ¬ify)==0) || - (pjsip_method_cmp(m, &update)==0); + (pjsip_method_cmp(m, &subscribe)==0) || + (pjsip_method_cmp(m, &refer)==0) || + (pjsip_method_cmp(m, ¬ify)==0) || + (pjsip_method_cmp(m, &update)==0); } static void dlg_on_destroy( void *arg ) @@ -71,8 +70,8 @@ static void dlg_on_destroy( void *arg ) } static pj_status_t create_dialog( pjsip_user_agent *ua, - pj_grp_lock_t *grp_lock, - pjsip_dialog **p_dlg) + pj_grp_lock_t *grp_lock, + pjsip_dialog **p_dlg) { pjsip_endpoint *endpt; pj_pool_t *pool; @@ -81,13 +80,13 @@ static pj_status_t create_dialog( pjsip_user_agent *ua, endpt = pjsip_ua_get_endpt(ua); if (!endpt) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; pool = pjsip_endpt_create_pool(endpt, "dlg%p", - PJSIP_POOL_LEN_DIALOG, - PJSIP_POOL_INC_DIALOG); + PJSIP_POOL_LEN_DIALOG, + PJSIP_POOL_INC_DIALOG); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; dlg = PJ_POOL_ZALLOC_T(pool, pjsip_dialog); PJ_ASSERT_RETURN(dlg != NULL, PJ_ENOMEM); @@ -104,17 +103,17 @@ static pj_status_t create_dialog( pjsip_user_agent *ua, /* Init client authentication session. */ status = pjsip_auth_clt_init(&dlg->auth_sess, dlg->endpt, - dlg->pool, 0); + dlg->pool, 0); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; if (grp_lock) { - dlg->grp_lock_ = grp_lock; + dlg->grp_lock_ = grp_lock; } else { - status = pj_grp_lock_create(pool, NULL, &dlg->grp_lock_); - if (status != PJ_SUCCESS) { - goto on_error; - } + status = pj_grp_lock_create(pool, NULL, &dlg->grp_lock_); + if (status != PJ_SUCCESS) { + goto on_error; + } } pj_grp_lock_add_ref(dlg->grp_lock_); @@ -133,26 +132,26 @@ static pj_status_t create_dialog( pjsip_user_agent *ua, static void destroy_dialog( pjsip_dialog *dlg, pj_bool_t unlock_mutex ) { if (dlg->tp_sel.type != PJSIP_TPSELECTOR_NONE) { - pjsip_tpselector_dec_ref(&dlg->tp_sel); - pj_bzero(&dlg->tp_sel, sizeof(pjsip_tpselector)); + pjsip_tpselector_dec_ref(&dlg->tp_sel); + pj_bzero(&dlg->tp_sel, sizeof(pjsip_tpselector)); } pjsip_auth_clt_deinit(&dlg->auth_sess); pj_grp_lock_dec_ref(dlg->grp_lock_); if (unlock_mutex) - pj_grp_lock_release(dlg->grp_lock_); + pj_grp_lock_release(dlg->grp_lock_); } /* * Create an UAC dialog. */ PJ_DEF(pj_status_t) pjsip_dlg_create_uac( pjsip_user_agent *ua, - const pj_str_t *local_uri, - const pj_str_t *local_contact, - const pj_str_t *remote_uri, - const pj_str_t *target, - pjsip_dialog **p_dlg) + const pj_str_t *local_uri, + const pj_str_t *local_contact, + const pj_str_t *remote_uri, + const pj_str_t *target, + pjsip_dialog **p_dlg) { pjsip_dlg_create_uac_param create_param; @@ -163,17 +162,17 @@ PJ_DEF(pj_status_t) pjsip_dlg_create_uac( pjsip_user_agent *ua, create_param.local_uri = *local_uri; create_param.remote_uri = *remote_uri; if (local_contact) - create_param.local_contact = *local_contact; + create_param.local_contact = *local_contact; if (target) - create_param.target = *target; + create_param.target = *target; return pjsip_dlg_create_uac2(&create_param, p_dlg); } PJ_DEF(pj_status_t) pjsip_dlg_create_uac2( - const pjsip_dlg_create_uac_param *create_param, - pjsip_dialog **p_dlg) + const pjsip_dlg_create_uac_param *create_param, + pjsip_dialog **p_dlg) { pj_status_t status; pj_str_t tmp; @@ -181,58 +180,58 @@ PJ_DEF(pj_status_t) pjsip_dlg_create_uac2( /* Check arguments. */ PJ_ASSERT_RETURN(create_param->ua && create_param->local_uri.slen && - create_param->remote_uri.slen && p_dlg, PJ_EINVAL); + create_param->remote_uri.slen && p_dlg, PJ_EINVAL); /* Create dialog instance. */ status = create_dialog(create_param->ua, create_param->grp_lock, &dlg); if (status != PJ_SUCCESS) - return status; + return status; /* Parse target. */ pj_strdup_with_null(dlg->pool, &tmp, create_param->target.slen ? - &create_param->target : &create_param->remote_uri); + &create_param->target : &create_param->remote_uri); dlg->target = pjsip_parse_uri(dlg->pool, tmp.ptr, tmp.slen, 0); if (!dlg->target) { - status = PJSIP_EINVALIDURI; - goto on_error; + status = PJSIP_EINVALIDURI; + goto on_error; } /* Put any header param in the target URI into INVITE header list. */ if (PJSIP_URI_SCHEME_IS_SIP(dlg->target) || - PJSIP_URI_SCHEME_IS_SIPS(dlg->target)) + PJSIP_URI_SCHEME_IS_SIPS(dlg->target)) { - pjsip_param *param; - pjsip_sip_uri *uri = (pjsip_sip_uri*)pjsip_uri_get_uri(dlg->target); - - param = uri->header_param.next; - while (param != &uri->header_param) { - if (param->value.ptr) { - pjsip_hdr *hdr; - int c; - - c = param->value.ptr[param->value.slen]; - param->value.ptr[param->value.slen] = '\0'; - - hdr = (pjsip_hdr*) - pjsip_parse_hdr(dlg->pool, ¶m->name, param->value.ptr, - param->value.slen, NULL); - - param->value.ptr[param->value.slen] = (char)c; - - if (hdr == NULL) { - status = PJSIP_EINVALIDURI; - goto on_error; - } - pj_list_push_back(&dlg->inv_hdr, hdr); - } - - param = param->next; - } - - /* Now must remove any header params from URL, since that would - * create another header in pjsip_endpt_create_request(). - */ - pj_list_init(&uri->header_param); + pjsip_param *param; + pjsip_sip_uri *uri = (pjsip_sip_uri*)pjsip_uri_get_uri(dlg->target); + + param = uri->header_param.next; + while (param != &uri->header_param) { + if (param->value.ptr) { + pjsip_hdr *hdr; + int c; + + c = param->value.ptr[param->value.slen]; + param->value.ptr[param->value.slen] = '\0'; + + hdr = (pjsip_hdr*) + pjsip_parse_hdr(dlg->pool, ¶m->name, param->value.ptr, + param->value.slen, NULL); + + param->value.ptr[param->value.slen] = (char)c; + + if (hdr == NULL) { + status = PJSIP_EINVALIDURI; + goto on_error; + } + pj_list_push_back(&dlg->inv_hdr, hdr); + } + + param = param->next; + } + + /* Now must remove any header params from URL, since that would + * create another header in pjsip_endpt_create_request(). + */ + pj_list_init(&uri->header_param); } /* Add target to the target set */ @@ -241,13 +240,13 @@ PJ_DEF(pj_status_t) pjsip_dlg_create_uac2( /* Init local info. */ dlg->local.info = pjsip_from_hdr_create(dlg->pool); pj_strdup_with_null(dlg->pool, &dlg->local.info_str, - &create_param->local_uri); + &create_param->local_uri); dlg->local.info->uri = pjsip_parse_uri(dlg->pool, - dlg->local.info_str.ptr, - dlg->local.info_str.slen, 0); + dlg->local.info_str.ptr, + dlg->local.info_str.slen, 0); if (!dlg->local.info->uri) { - status = PJSIP_EINVALIDURI; - goto on_error; + status = PJSIP_EINVALIDURI; + goto on_error; } /* Generate local tag. */ @@ -263,55 +262,55 @@ PJ_DEF(pj_status_t) pjsip_dlg_create_uac2( /* Init local contact. */ pj_strdup_with_null(dlg->pool, &tmp, - create_param->local_contact.slen ? - &create_param->local_contact : &create_param->local_uri); + create_param->local_contact.slen ? + &create_param->local_contact : &create_param->local_uri); dlg->local.contact = (pjsip_contact_hdr*) - pjsip_parse_hdr(dlg->pool, &HCONTACT, tmp.ptr, - tmp.slen, NULL); + pjsip_parse_hdr(dlg->pool, &HCONTACT, tmp.ptr, + tmp.slen, NULL); if (!dlg->local.contact) { - status = PJSIP_EINVALIDURI; - goto on_error; + status = PJSIP_EINVALIDURI; + goto on_error; } /* Init remote info. */ dlg->remote.info = pjsip_to_hdr_create(dlg->pool); pj_strdup_with_null(dlg->pool, &dlg->remote.info_str, - &create_param->remote_uri); + &create_param->remote_uri); dlg->remote.info->uri = pjsip_parse_uri(dlg->pool, - dlg->remote.info_str.ptr, - dlg->remote.info_str.slen, 0); + dlg->remote.info_str.ptr, + dlg->remote.info_str.slen, 0); if (!dlg->remote.info->uri) { - status = PJSIP_EINVALIDURI; - goto on_error; + status = PJSIP_EINVALIDURI; + goto on_error; } /* Remove header param from remote.info_str, if any */ if (PJSIP_URI_SCHEME_IS_SIP(dlg->remote.info->uri) || - PJSIP_URI_SCHEME_IS_SIPS(dlg->remote.info->uri)) + PJSIP_URI_SCHEME_IS_SIPS(dlg->remote.info->uri)) { - pjsip_sip_uri *sip_uri = (pjsip_sip_uri *) - pjsip_uri_get_uri(dlg->remote.info->uri); - if (!pj_list_empty(&sip_uri->header_param)) { - pj_str_t tmp2; - - /* Remove all header param */ - pj_list_init(&sip_uri->header_param); - - /* Print URI */ - tmp2.ptr = (char*) pj_pool_alloc(dlg->pool, - dlg->remote.info_str.slen); - tmp2.slen = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, - sip_uri, tmp2.ptr, - dlg->remote.info_str.slen); - - if (tmp2.slen < 1) { - status = PJSIP_EURITOOLONG; - goto on_error; - } - - /* Assign remote.info_str */ - dlg->remote.info_str = tmp2; - } + pjsip_sip_uri *sip_uri = (pjsip_sip_uri *) + pjsip_uri_get_uri(dlg->remote.info->uri); + if (!pj_list_empty(&sip_uri->header_param)) { + pj_str_t tmp2; + + /* Remove all header param */ + pj_list_init(&sip_uri->header_param); + + /* Print URI */ + tmp2.ptr = (char*) pj_pool_alloc(dlg->pool, + dlg->remote.info_str.slen); + tmp2.slen = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, + sip_uri, tmp2.ptr, + dlg->remote.info_str.slen); + + if (tmp2.slen < 1) { + status = PJSIP_EURITOOLONG; + goto on_error; + } + + /* Assign remote.info_str */ + dlg->remote.info_str = tmp2; + } } @@ -334,7 +333,7 @@ PJ_DEF(pj_status_t) pjsip_dlg_create_uac2( /* Register this dialog to user agent. */ status = pjsip_ua_register_dlg( create_param->ua, dlg ); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Done! */ *p_dlg = dlg; @@ -353,10 +352,10 @@ PJ_DEF(pj_status_t) pjsip_dlg_create_uac2( * Create UAS dialog. */ pj_status_t create_uas_dialog( pjsip_user_agent *ua, - pjsip_rx_data *rdata, - const pj_str_t *contact, - pj_bool_t inc_lock, - pjsip_dialog **p_dlg) + pjsip_rx_data *rdata, + const pj_str_t *contact, + pj_bool_t inc_lock, + pjsip_dialog **p_dlg) { pj_status_t status; pjsip_hdr *pos = NULL; @@ -374,7 +373,7 @@ pj_status_t create_uas_dialog( pjsip_user_agent *ua, /* rdata must have request message. */ PJ_ASSERT_RETURN(rdata->msg_info.msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); /* Request must not have To tag. * This should have been checked in the user agent (or application?). @@ -383,13 +382,13 @@ pj_status_t create_uas_dialog( pjsip_user_agent *ua, /* The request must be a dialog establishing request. */ PJ_ASSERT_RETURN( - pjsip_method_creates_dialog(&rdata->msg_info.msg->line.req.method), - PJ_EINVALIDOP); + pjsip_method_creates_dialog(&rdata->msg_info.msg->line.req.method), + PJ_EINVALIDOP); /* Create dialog instance. */ status = create_dialog(ua, NULL, &dlg); if (status != PJ_SUCCESS) - return status; + return status; /* Temprary string for getting the string representation of * both local and remote URI. @@ -398,7 +397,7 @@ pj_status_t create_uas_dialog( pjsip_user_agent *ua, /* Init local info from the To header. */ dlg->local.info = (pjsip_fromto_hdr*) - pjsip_hdr_clone(dlg->pool, rdata->msg_info.to); + pjsip_hdr_clone(dlg->pool, rdata->msg_info.to); pjsip_fromto_hdr_set_from(dlg->local.info); /* Generate local tag. */ @@ -407,12 +406,12 @@ pj_status_t create_uas_dialog( pjsip_user_agent *ua, /* Print the local info. */ len = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, - dlg->local.info->uri, tmp.ptr, TMP_LEN); + dlg->local.info->uri, tmp.ptr, TMP_LEN); if (len < 1) { - pj_ansi_strcpy(tmp.ptr, "<-error: uri too long->"); - tmp.slen = pj_ansi_strlen(tmp.ptr); + pj_ansi_strcpy(tmp.ptr, "<-error: uri too long->"); + tmp.slen = pj_ansi_strlen(tmp.ptr); } else - tmp.slen = len; + tmp.slen = len; /* Save the local info. */ pj_strdup(dlg->pool, &dlg->local.info_str, &tmp); @@ -435,72 +434,72 @@ pj_status_t create_uas_dialog( pjsip_user_agent *ua, * MUST be a SIPS URI. */ if (contact) { - pj_str_t tmp2; + pj_str_t tmp2; - pj_strdup_with_null(dlg->pool, &tmp2, contact); - dlg->local.contact = (pjsip_contact_hdr*) - pjsip_parse_hdr(dlg->pool, &HCONTACT, tmp2.ptr, - tmp2.slen, NULL); - if (!dlg->local.contact) { - status = PJSIP_EINVALIDURI; - goto on_error; - } + pj_strdup_with_null(dlg->pool, &tmp2, contact); + dlg->local.contact = (pjsip_contact_hdr*) + pjsip_parse_hdr(dlg->pool, &HCONTACT, tmp2.ptr, + tmp2.slen, NULL); + if (!dlg->local.contact) { + status = PJSIP_EINVALIDURI; + goto on_error; + } } else { - dlg->local.contact = pjsip_contact_hdr_create(dlg->pool); - dlg->local.contact->uri = dlg->local.info->uri; + dlg->local.contact = pjsip_contact_hdr_create(dlg->pool); + dlg->local.contact->uri = dlg->local.info->uri; } /* Init remote info from the From header. */ dlg->remote.info = (pjsip_fromto_hdr*) - pjsip_hdr_clone(dlg->pool, rdata->msg_info.from); + pjsip_hdr_clone(dlg->pool, rdata->msg_info.from); pjsip_fromto_hdr_set_to(dlg->remote.info); /* Print the remote info. */ len = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, - dlg->remote.info->uri, tmp.ptr, TMP_LEN); + dlg->remote.info->uri, tmp.ptr, TMP_LEN); if (len < 1) { - pj_ansi_strcpy(tmp.ptr, "<-error: uri too long->"); - tmp.slen = pj_ansi_strlen(tmp.ptr); + pj_ansi_strcpy(tmp.ptr, "<-error: uri too long->"); + tmp.slen = pj_ansi_strlen(tmp.ptr); } else - tmp.slen = len; + tmp.slen = len; /* Save the remote info. */ pj_strdup(dlg->pool, &dlg->remote.info_str, &tmp); /* Save initial destination host from transport's info */ pj_strdup(dlg->pool, &dlg->initial_dest, - &rdata->tp_info.transport->remote_name.host); + &rdata->tp_info.transport->remote_name.host); /* Init remote's contact from Contact header. * Iterate the Contact URI until we find sip: or sips: scheme. */ do { - contact_hdr = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, - pos); - if (contact_hdr) { - if (!contact_hdr->uri || - (!PJSIP_URI_SCHEME_IS_SIP(contact_hdr->uri) && - !PJSIP_URI_SCHEME_IS_SIPS(contact_hdr->uri))) - { - pos = (pjsip_hdr*)contact_hdr->next; - if (pos == &rdata->msg_info.msg->hdr) - contact_hdr = NULL; - } else { - break; - } - } + contact_hdr = (pjsip_contact_hdr*) + pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, + pos); + if (contact_hdr) { + if (!contact_hdr->uri || + (!PJSIP_URI_SCHEME_IS_SIP(contact_hdr->uri) && + !PJSIP_URI_SCHEME_IS_SIPS(contact_hdr->uri))) + { + pos = (pjsip_hdr*)contact_hdr->next; + if (pos == &rdata->msg_info.msg->hdr) + contact_hdr = NULL; + } else { + break; + } + } } while (contact_hdr); if (!contact_hdr) { - status = PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_REQUEST); - goto on_error; + status = PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_REQUEST); + goto on_error; } dlg->remote.contact = (pjsip_contact_hdr*) - pjsip_hdr_clone(dlg->pool, (pjsip_hdr*)contact_hdr); + pjsip_hdr_clone(dlg->pool, (pjsip_hdr*)contact_hdr); /* Init remote's CSeq from CSeq header */ dlg->remote.cseq = dlg->remote.first_cseq = rdata->msg_info.cseq->cseq; @@ -517,11 +516,11 @@ pj_status_t create_uas_dialog( pjsip_user_agent *ua, * SIPS URI, the 'secure' flag is set to TRUE. */ dlg->secure = PJSIP_TRANSPORT_IS_SECURE(rdata->tp_info.transport) && - PJSIP_URI_SCHEME_IS_SIPS(rdata->msg_info.msg->line.req.uri); + PJSIP_URI_SCHEME_IS_SIPS(rdata->msg_info.msg->line.req.uri); /* Call-ID */ dlg->call_id = (pjsip_cid_hdr*) - pjsip_hdr_clone(dlg->pool, rdata->msg_info.cid); + pjsip_hdr_clone(dlg->pool, rdata->msg_info.cid); /* Route set. * RFC 3261 Section 12.1.1: @@ -533,21 +532,21 @@ pj_status_t create_uas_dialog( pjsip_user_agent *ua, pj_list_init(&dlg->route_set); rr = rdata->msg_info.record_route; while (rr != NULL) { - pjsip_route_hdr *route; + pjsip_route_hdr *route; - /* Clone the Record-Route, change the type to Route header. */ - route = (pjsip_route_hdr*) pjsip_hdr_clone(dlg->pool, rr); - pjsip_routing_hdr_set_route(route); + /* Clone the Record-Route, change the type to Route header. */ + route = (pjsip_route_hdr*) pjsip_hdr_clone(dlg->pool, rr); + pjsip_routing_hdr_set_route(route); - /* Add to route set. */ - pj_list_push_back(&dlg->route_set, route); + /* Add to route set. */ + pj_list_push_back(&dlg->route_set, route); - /* Find next Record-Route header. */ - rr = rr->next; - if (rr == (void*)&rdata->msg_info.msg->hdr) - break; - rr = (pjsip_route_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg, - PJSIP_H_RECORD_ROUTE, rr); + /* Find next Record-Route header. */ + rr = rr->next; + if (rr == (void*)&rdata->msg_info.msg->hdr) + break; + rr = (pjsip_route_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg, + PJSIP_H_RECORD_ROUTE, rr); } dlg->route_set_frozen = PJ_TRUE; @@ -562,7 +561,7 @@ pj_status_t create_uas_dialog( pjsip_user_agent *ua, /* Create UAS transaction for this request. */ status = pjsip_tsx_create_uas(dlg->ua, rdata, &tsx); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Associate this dialog to the transaction. */ tsx->mod_data[dlg->ua->id] = dlg; @@ -579,7 +578,7 @@ pj_status_t create_uas_dialog( pjsip_user_agent *ua, /* Register this dialog to user agent. */ status = pjsip_ua_register_dlg( ua, dlg ); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Put this dialog in rdata's mod_data */ rdata->endpt_info.mod_data[ua->id] = dlg; @@ -596,9 +595,9 @@ pj_status_t create_uas_dialog( pjsip_user_agent *ua, on_error: if (tsx) { - pjsip_tsx_terminate(tsx, 500); - pj_assert(dlg->tsx_count>0); - --dlg->tsx_count; + pjsip_tsx_terminate(tsx, 500); + pj_assert(dlg->tsx_count>0); + --dlg->tsx_count; } if (lock_incremented) { @@ -616,9 +615,9 @@ pj_status_t create_uas_dialog( pjsip_user_agent *ua, * Create UAS dialog. */ PJ_DEF(pj_status_t) pjsip_dlg_create_uas( pjsip_user_agent *ua, - pjsip_rx_data *rdata, - const pj_str_t *contact, - pjsip_dialog **p_dlg) + pjsip_rx_data *rdata, + const pj_str_t *contact, + pjsip_dialog **p_dlg) { return create_uas_dialog(ua, rdata, contact, PJ_FALSE, p_dlg); } @@ -630,9 +629,9 @@ PJ_DEF(pj_status_t) pjsip_dlg_create_uas( pjsip_user_agent *ua, */ PJ_DEF(pj_status_t) pjsip_dlg_create_uas_and_inc_lock( pjsip_user_agent *ua, - pjsip_rx_data *rdata, - const pj_str_t *contact, - pjsip_dialog **p_dlg) + pjsip_rx_data *rdata, + const pj_str_t *contact, + pjsip_dialog **p_dlg) { return create_uas_dialog(ua, rdata, contact, PJ_TRUE, p_dlg); } @@ -642,7 +641,7 @@ pjsip_dlg_create_uas_and_inc_lock( pjsip_user_agent *ua, * Bind dialog to a specific transport/listener. */ PJ_DEF(pj_status_t) pjsip_dlg_set_transport( pjsip_dialog *dlg, - const pjsip_tpselector *sel) + const pjsip_tpselector *sel) { /* Validate */ PJ_ASSERT_RETURN(dlg && sel, PJ_EINVAL); @@ -669,7 +668,7 @@ PJ_DEF(pj_status_t) pjsip_dlg_set_transport( pjsip_dialog *dlg, * Set "sent-by" field of Via header. */ PJ_DEF(pj_status_t) pjsip_dlg_set_via_sent_by( pjsip_dialog *dlg, - pjsip_host_port *via_addr, + pjsip_host_port *via_addr, pjsip_transport *via_tp) { PJ_ASSERT_RETURN(dlg, PJ_EINVAL); @@ -691,8 +690,8 @@ PJ_DEF(pj_status_t) pjsip_dlg_set_via_sent_by( pjsip_dialog *dlg, * Create forked dialog from a response. */ PJ_DEF(pj_status_t) pjsip_dlg_fork( const pjsip_dialog *first_dlg, - const pjsip_rx_data *rdata, - pjsip_dialog **new_dlg ) + const pjsip_rx_data *rdata, + pjsip_dialog **new_dlg ) { pjsip_dialog *dlg; const pjsip_msg *msg = rdata->msg_info.msg; @@ -705,33 +704,33 @@ PJ_DEF(pj_status_t) pjsip_dlg_fork( const pjsip_dialog *first_dlg, /* rdata must be response message. */ PJ_ASSERT_RETURN(msg->type == PJSIP_RESPONSE_MSG, - PJSIP_ENOTRESPONSEMSG); + PJSIP_ENOTRESPONSEMSG); /* Status code MUST be 1xx (but not 100), or 2xx */ status = msg->line.status.code; PJ_ASSERT_RETURN( (status/100==1 && status!=100) || - (status/100==2), PJ_EBUG); + (status/100==2), PJ_EBUG); /* To tag must present in the response. */ PJ_ASSERT_RETURN(rdata->msg_info.to->tag.slen != 0, PJSIP_EMISSINGTAG); /* Find Contact header in the response */ contact = (const pjsip_contact_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_CONTACT, NULL); + pjsip_msg_find_hdr(msg, PJSIP_H_CONTACT, NULL); if (contact == NULL || contact->uri == NULL) - return PJSIP_EMISSINGHDR; + return PJSIP_EMISSINGHDR; /* Create the dialog. */ status = create_dialog((pjsip_user_agent*)first_dlg->ua, NULL, &dlg); if (status != PJ_SUCCESS) - return status; + return status; /* Set remote target from the response. */ dlg->target = (pjsip_uri*) pjsip_uri_clone(dlg->pool, contact->uri); /* Clone local info. */ dlg->local.info = (pjsip_fromto_hdr*) - pjsip_hdr_clone(dlg->pool, first_dlg->local.info); + pjsip_hdr_clone(dlg->pool, first_dlg->local.info); /* Clone local tag. */ pj_strdup(dlg->pool, &dlg->local.info->tag, &first_dlg->local.info->tag); @@ -743,11 +742,11 @@ PJ_DEF(pj_status_t) pjsip_dlg_fork( const pjsip_dialog *first_dlg, /* Clone local Contact. */ dlg->local.contact = (pjsip_contact_hdr*) - pjsip_hdr_clone(dlg->pool, first_dlg->local.contact); + pjsip_hdr_clone(dlg->pool, first_dlg->local.contact); /* Clone remote info. */ dlg->remote.info = (pjsip_fromto_hdr*) - pjsip_hdr_clone(dlg->pool, first_dlg->remote.info); + pjsip_hdr_clone(dlg->pool, first_dlg->remote.info); /* Set remote tag from the response. */ pj_strdup(dlg->pool, &dlg->remote.info->tag, &rdata->msg_info.to->tag); @@ -761,10 +760,10 @@ PJ_DEF(pj_status_t) pjsip_dlg_fork( const pjsip_dialog *first_dlg, /* Dialog state depends on the response. */ status = msg->line.status.code/100; if (status == 1 || status == 2) - dlg->state = PJSIP_DIALOG_STATE_ESTABLISHED; + dlg->state = PJSIP_DIALOG_STATE_ESTABLISHED; else { - pj_assert(!"Invalid status code"); - dlg->state = PJSIP_DIALOG_STATE_NULL; + pj_assert(!"Invalid status code"); + dlg->state = PJSIP_DIALOG_STATE_NULL; } /* Secure? */ @@ -772,32 +771,32 @@ PJ_DEF(pj_status_t) pjsip_dlg_fork( const pjsip_dialog *first_dlg, /* Clone Call-ID header. */ dlg->call_id = (pjsip_cid_hdr*) - pjsip_hdr_clone(dlg->pool, first_dlg->call_id); + pjsip_hdr_clone(dlg->pool, first_dlg->call_id); /* Get route-set from the response. */ pj_list_init(&dlg->route_set); end_hdr = &msg->hdr; for (hdr=msg->hdr.prev; hdr!=end_hdr; hdr=hdr->prev) { - if (hdr->type == PJSIP_H_RECORD_ROUTE) { - pjsip_route_hdr *r; - r = (pjsip_route_hdr*) pjsip_hdr_clone(dlg->pool, hdr); - pjsip_routing_hdr_set_route(r); - pj_list_push_back(&dlg->route_set, r); - } + if (hdr->type == PJSIP_H_RECORD_ROUTE) { + pjsip_route_hdr *r; + r = (pjsip_route_hdr*) pjsip_hdr_clone(dlg->pool, hdr); + pjsip_routing_hdr_set_route(r); + pj_list_push_back(&dlg->route_set, r); + } } //dlg->route_set_frozen = PJ_TRUE; /* Clone client authentication session. */ status = pjsip_auth_clt_clone(dlg->pool, &dlg->auth_sess, - &first_dlg->auth_sess); + &first_dlg->auth_sess); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Register this dialog to user agent. */ status = pjsip_ua_register_dlg(dlg->ua, dlg ); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Done! */ @@ -816,7 +815,7 @@ PJ_DEF(pj_status_t) pjsip_dlg_fork( const pjsip_dialog *first_dlg, * Unregister and destroy dialog. */ static pj_status_t unregister_and_destroy_dialog( pjsip_dialog *dlg, - pj_bool_t unlock_mutex ) + pj_bool_t unlock_mutex ) { pj_status_t status; @@ -831,11 +830,11 @@ static pj_status_t unregister_and_destroy_dialog( pjsip_dialog *dlg, /* Unregister from user agent, if it has been registered (see #1924) */ if (dlg->dlg_set) { - status = pjsip_ua_unregister_dlg(dlg->ua, dlg); - if (status != PJ_SUCCESS) { - pj_assert(!"Unexpected failed unregistration!"); - return status; - } + status = pjsip_ua_unregister_dlg(dlg->ua, dlg); + if (status != PJ_SUCCESS) { + pj_assert(!"Unexpected failed unregistration!"); + return status; + } } /* Destroy this dialog. */ @@ -864,7 +863,7 @@ PJ_DEF(pj_status_t) pjsip_dlg_terminate( pjsip_dialog *dlg ) * Set route_set */ PJ_DEF(pj_status_t) pjsip_dlg_set_route_set( pjsip_dialog *dlg, - const pjsip_route_hdr *route_set ) + const pjsip_route_hdr *route_set ) { pjsip_route_hdr *r; @@ -876,18 +875,18 @@ PJ_DEF(pj_status_t) pjsip_dlg_set_route_set( pjsip_dialog *dlg, pj_list_init(&dlg->route_set); if (!route_set) { - pjsip_dlg_dec_lock(dlg); - return PJ_SUCCESS; + pjsip_dlg_dec_lock(dlg); + return PJ_SUCCESS; } r = route_set->next; while (r != route_set) { - pjsip_route_hdr *new_r; + pjsip_route_hdr *new_r; - new_r = (pjsip_route_hdr*) pjsip_hdr_clone(dlg->pool, r); - pj_list_push_back(&dlg->route_set, new_r); + new_r = (pjsip_route_hdr*) pjsip_hdr_clone(dlg->pool, r); + pj_list_push_back(&dlg->route_set, new_r); - r = r->next; + r = r->next; } pjsip_dlg_dec_lock(dlg); @@ -899,7 +898,7 @@ PJ_DEF(pj_status_t) pjsip_dlg_set_route_set( pjsip_dialog *dlg, * Increment session counter. */ PJ_DEF(pj_status_t) pjsip_dlg_inc_session( pjsip_dialog *dlg, - pjsip_module *mod ) + pjsip_module *mod ) { PJ_ASSERT_RETURN(dlg && mod, PJ_EINVAL); @@ -910,7 +909,7 @@ PJ_DEF(pj_status_t) pjsip_dlg_inc_session( pjsip_dialog *dlg, pjsip_dlg_dec_lock(dlg); PJ_LOG(5,(dlg->obj_name, "Session count inc to %d by %.*s", - dlg->sess_count, (int)mod->name.slen, mod->name.ptr)); + dlg->sess_count, (int)mod->name.slen, mod->name.ptr)); pj_log_pop_indent(); return PJ_SUCCESS; @@ -924,13 +923,13 @@ PJ_DEF(pj_status_t) pjsip_dlg_inc_session( pjsip_dialog *dlg, PJ_DEF(void) pjsip_dlg_inc_lock(pjsip_dialog *dlg) { PJ_LOG(6,(dlg->obj_name, "Entering pjsip_dlg_inc_lock(), sess_count=%d", - dlg->sess_count)); + dlg->sess_count)); pj_grp_lock_acquire(dlg->grp_lock_); dlg->sess_count++; PJ_LOG(6,(dlg->obj_name, "Leaving pjsip_dlg_inc_lock(), sess_count=%d", - dlg->sess_count)); + dlg->sess_count)); } /* Try to acquire dialog's group lock, but bail out if group lock can not be @@ -941,18 +940,18 @@ PJ_DEF(pj_status_t) pjsip_dlg_try_inc_lock(pjsip_dialog *dlg) pj_status_t status; PJ_LOG(6,(dlg->obj_name,"Entering pjsip_dlg_try_inc_lock(), sess_count=%d", - dlg->sess_count)); + dlg->sess_count)); status = pj_grp_lock_tryacquire(dlg->grp_lock_); if (status != PJ_SUCCESS) { - PJ_LOG(6,(dlg->obj_name, "pjsip_dlg_try_inc_lock() failed")); - return status; + PJ_LOG(6,(dlg->obj_name, "pjsip_dlg_try_inc_lock() failed")); + return status; } dlg->sess_count++; PJ_LOG(6,(dlg->obj_name, "Leaving pjsip_dlg_try_inc_lock(), sess_count=%d", - dlg->sess_count)); + dlg->sess_count)); return PJ_SUCCESS; } @@ -967,21 +966,21 @@ PJ_DEF(void) pjsip_dlg_dec_lock(pjsip_dialog *dlg) PJ_ASSERT_ON_FAIL(dlg!=NULL, return); PJ_LOG(6,(dlg->obj_name, "Entering pjsip_dlg_dec_lock(), sess_count=%d", - dlg->sess_count)); + dlg->sess_count)); pj_assert(dlg->sess_count > 0); --dlg->sess_count; if (dlg->sess_count==0 && dlg->tsx_count==0) { - pj_grp_lock_release(dlg->grp_lock_); - pj_grp_lock_acquire(dlg->grp_lock_); - /* We are holding the dialog group lock here, so before we destroy - * the dialog, make sure that we unlock it first to avoid - * undefined behaviour on some platforms. See ticket #1886. - */ - unregister_and_destroy_dialog(dlg, PJ_TRUE); + pj_grp_lock_release(dlg->grp_lock_); + pj_grp_lock_acquire(dlg->grp_lock_); + /* We are holding the dialog group lock here, so before we destroy + * the dialog, make sure that we unlock it first to avoid + * undefined behaviour on some platforms. See ticket #1886. + */ + unregister_and_destroy_dialog(dlg, PJ_TRUE); } else { - pj_grp_lock_release(dlg->grp_lock_); + pj_grp_lock_release(dlg->grp_lock_); } PJ_LOG(6,(THIS_FILE, "Leaving pjsip_dlg_dec_lock() (dlg=%p)", dlg)); @@ -992,14 +991,14 @@ PJ_DEF(void) pjsip_dlg_dec_lock(pjsip_dialog *dlg) * Decrement session count. */ PJ_DEF(pj_status_t) pjsip_dlg_dec_session( pjsip_dialog *dlg, - pjsip_module *mod) + pjsip_module *mod) { PJ_ASSERT_RETURN(dlg, PJ_EINVAL); pj_log_push_indent(); PJ_LOG(5,(dlg->obj_name, "Session count dec to %d by %.*s", - dlg->sess_count-1, (int)mod->name.slen, mod->name.ptr)); + dlg->sess_count-1, (int)mod->name.slen, mod->name.ptr)); pjsip_dlg_inc_lock(dlg); --dlg->sess_count; @@ -1019,17 +1018,17 @@ PJ_DEF(pj_grp_lock_t *) pjsip_dlg_get_lock(pjsip_dialog *dlg) * Check if the module is registered as a usage */ PJ_DEF(pj_bool_t) pjsip_dlg_has_usage( pjsip_dialog *dlg, - pjsip_module *mod) + pjsip_module *mod) { unsigned index; pj_bool_t found = PJ_FALSE; pjsip_dlg_inc_lock(dlg); for (index=0; indexusage_cnt; ++index) { - if (dlg->usage[index] == mod) { - found = PJ_TRUE; - break; - } + if (dlg->usage[index] == mod) { + found = PJ_TRUE; + break; + } } pjsip_dlg_dec_lock(dlg); @@ -1040,19 +1039,19 @@ PJ_DEF(pj_bool_t) pjsip_dlg_has_usage( pjsip_dialog *dlg, * Add usage. */ PJ_DEF(pj_status_t) pjsip_dlg_add_usage( pjsip_dialog *dlg, - pjsip_module *mod, - void *mod_data ) + pjsip_module *mod, + void *mod_data ) { unsigned index; PJ_ASSERT_RETURN(dlg && mod, PJ_EINVAL); PJ_ASSERT_RETURN(mod->id >= 0 && mod->id < PJSIP_MAX_MODULE, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(dlg->usage_cnt < PJSIP_MAX_MODULE, PJ_EBUG); PJ_LOG(5,(dlg->obj_name, - "Module %.*s added as dialog usage, data=%p", - (int)mod->name.slen, mod->name.ptr, mod_data)); + "Module %.*s added as dialog usage, data=%p", + (int)mod->name.slen, mod->name.ptr, mod_data)); pjsip_dlg_inc_lock(dlg); @@ -1061,35 +1060,35 @@ PJ_DEF(pj_status_t) pjsip_dlg_add_usage( pjsip_dialog *dlg, * this module has not been registered before. */ for (index=0; indexusage_cnt; ++index) { - if (dlg->usage[index] == mod) { - /* Module may be registered more than once in the same dialog. - * For example, when call transfer fails, application may retry - * call transfer on the same dialog. - * So return PJ_SUCCESS here. - */ - PJ_LOG(4,(dlg->obj_name, - "Module %.*s already registered as dialog usage, " - "updating the data %p", - (int)mod->name.slen, mod->name.ptr, mod_data)); - dlg->mod_data[mod->id] = mod_data; - - pjsip_dlg_dec_lock(dlg); - return PJ_SUCCESS; - - //pj_assert(!"This module is already registered"); - //pjsip_dlg_dec_lock(dlg); - //return PJSIP_ETYPEEXISTS; - } - - if (dlg->usage[index]->priority > mod->priority) - break; + if (dlg->usage[index] == mod) { + /* Module may be registered more than once in the same dialog. + * For example, when call transfer fails, application may retry + * call transfer on the same dialog. + * So return PJ_SUCCESS here. + */ + PJ_LOG(4,(dlg->obj_name, + "Module %.*s already registered as dialog usage, " + "updating the data %p", + (int)mod->name.slen, mod->name.ptr, mod_data)); + dlg->mod_data[mod->id] = mod_data; + + pjsip_dlg_dec_lock(dlg); + return PJ_SUCCESS; + + //pj_assert(!"This module is already registered"); + //pjsip_dlg_dec_lock(dlg); + //return PJSIP_ETYPEEXISTS; + } + + if (dlg->usage[index]->priority > mod->priority) + break; } /* index holds position to put the module. * Insert module at this index. */ pj_array_insert(dlg->usage, sizeof(dlg->usage[0]), dlg->usage_cnt, - index, &mod); + index, &mod); /* Set module data. */ dlg->mod_data[mod->id] = mod_data; @@ -1108,12 +1107,12 @@ PJ_DEF(pj_status_t) pjsip_dlg_add_usage( pjsip_dialog *dlg, * the value directly by accessing dlg->mod_data[module_id]. */ PJ_DEF(pj_status_t) pjsip_dlg_set_mod_data( pjsip_dialog *dlg, - int mod_id, - void *data ) + int mod_id, + void *data ) { PJ_ASSERT_RETURN(dlg, PJ_EINVAL); PJ_ASSERT_RETURN(mod_id >= 0 && mod_id < PJSIP_MAX_MODULE, - PJ_EINVAL); + PJ_EINVAL); dlg->mod_data[mod_id] = data; return PJ_SUCCESS; } @@ -1123,11 +1122,11 @@ PJ_DEF(pj_status_t) pjsip_dlg_set_mod_data( pjsip_dialog *dlg, * can also get value directly by accessing dlg->mod_data[module_id]. */ PJ_DEF(void*) pjsip_dlg_get_mod_data( pjsip_dialog *dlg, - int mod_id) + int mod_id) { PJ_ASSERT_RETURN(dlg, NULL); PJ_ASSERT_RETURN(mod_id >= 0 && mod_id < PJSIP_MAX_MODULE, - NULL); + NULL); return dlg->mod_data[mod_id]; } @@ -1138,9 +1137,9 @@ PJ_DEF(void*) pjsip_dlg_get_mod_data( pjsip_dialog *dlg, * RFC3261 section 12.2.1. */ static pj_status_t dlg_create_request_throw( pjsip_dialog *dlg, - const pjsip_method *method, - int cseq, - pjsip_tx_data **p_tdata ) + const pjsip_method *method, + int cseq, + pjsip_tx_data **p_tdata ) { pjsip_tx_data *tdata; pjsip_contact_hdr *contact; @@ -1152,26 +1151,26 @@ static pj_status_t dlg_create_request_throw( pjsip_dialog *dlg, * core SIP spec, only INVITE). */ if (pjsip_method_creates_dialog(method)) - contact = dlg->local.contact; + contact = dlg->local.contact; else - contact = NULL; + contact = NULL; /* * Create the request by cloning from the headers in the * dialog. */ status = pjsip_endpt_create_request_from_hdr(dlg->endpt, - method, - dlg->target, - dlg->local.info, - dlg->remote.info, - contact, - dlg->call_id, - cseq, - NULL, - &tdata); + method, + dlg->target, + dlg->local.info, + dlg->remote.info, + contact, + dlg->call_id, + cseq, + NULL, + &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Put this dialog in tdata's mod_data */ tdata->mod_data[dlg->ua->id] = dlg; @@ -1183,24 +1182,24 @@ static pj_status_t dlg_create_request_throw( pjsip_dialog *dlg, route = dlg->route_set.next; end_list = &dlg->route_set; for (; route != end_list; route = route->next ) { - pjsip_route_hdr *r; - r = (pjsip_route_hdr*) pjsip_hdr_shallow_clone( tdata->pool, route ); - pjsip_routing_hdr_set_route(r); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)r); + pjsip_route_hdr *r; + r = (pjsip_route_hdr*) pjsip_hdr_shallow_clone( tdata->pool, route ); + pjsip_routing_hdr_set_route(r); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)r); } /* Copy authorization headers, if request is not ACK or CANCEL. */ if (method->id != PJSIP_ACK_METHOD && method->id != PJSIP_CANCEL_METHOD) { - status = pjsip_auth_clt_init_req( &dlg->auth_sess, tdata ); - if (status != PJ_SUCCESS) - return status; + status = pjsip_auth_clt_init_req( &dlg->auth_sess, tdata ); + if (status != PJ_SUCCESS) + return status; } /* Copy the initial destination host to tdata. This information can be * used later by transport for transport selection. */ if (dlg->initial_dest.slen) - pj_strdup(tdata->pool, &tdata->dest_info.name, &dlg->initial_dest); + pj_strdup(tdata->pool, &tdata->dest_info.name, &dlg->initial_dest); /* Done. */ *p_tdata = tdata; @@ -1214,9 +1213,9 @@ static pj_status_t dlg_create_request_throw( pjsip_dialog *dlg, * Create outgoing request. */ PJ_DEF(pj_status_t) pjsip_dlg_create_request( pjsip_dialog *dlg, - const pjsip_method *method, - int cseq, - pjsip_tx_data **p_tdata) + const pjsip_method *method, + int cseq, + pjsip_tx_data **p_tdata) { pj_status_t status; pjsip_tx_data *tdata = NULL; @@ -1229,24 +1228,24 @@ PJ_DEF(pj_status_t) pjsip_dlg_create_request( pjsip_dialog *dlg, /* Use outgoing CSeq, if set to -1 (other than ACK/CANCEL). */ if (cseq < 0) - cseq = dlg->local.cseq; + cseq = dlg->local.cseq; /* Keep compiler happy */ status = PJ_EBUG; /* Create the request. */ PJ_TRY { - status = dlg_create_request_throw(dlg, method, cseq, &tdata); + status = dlg_create_request_throw(dlg, method, cseq, &tdata); } PJ_CATCH_ANY { - status = PJ_ENOMEM; + status = PJ_ENOMEM; } PJ_END; /* Failed! Delete transmit data. */ if (status != PJ_SUCCESS && tdata) { - pjsip_tx_data_dec_ref( tdata ); - tdata = NULL; + pjsip_tx_data_dec_ref( tdata ); + tdata = NULL; } /* Unlock dialog. */ @@ -1261,20 +1260,20 @@ PJ_DEF(pj_status_t) pjsip_dlg_create_request( pjsip_dialog *dlg, * next server upon failure. */ static void send_ack_callback( pjsip_send_state *send_state, - pj_ssize_t sent, pj_bool_t *cont ) + pj_ssize_t sent, pj_bool_t *cont ) { if (sent > 0) - return; + return; if (*cont) { - PJ_PERROR(3,(THIS_FILE, (pj_status_t)-sent, - "Temporary failure in sending %s, " - "will try next server", - pjsip_tx_data_get_info(send_state->tdata))); + PJ_PERROR(3,(THIS_FILE, (pj_status_t)-sent, + "Temporary failure in sending %s, " + "will try next server", + pjsip_tx_data_get_info(send_state->tdata))); } else { - PJ_PERROR(3,(THIS_FILE, (pj_status_t)-sent, - "Failed to send %s!", - pjsip_tx_data_get_info(send_state->tdata))); + PJ_PERROR(3,(THIS_FILE, (pj_status_t)-sent, + "Failed to send %s!", + pjsip_tx_data_get_info(send_state->tdata))); } } @@ -1282,9 +1281,9 @@ static void send_ack_callback( pjsip_send_state *send_state, * Send request statefully, and update dialog'c CSeq. */ PJ_DEF(pj_status_t) pjsip_dlg_send_request( pjsip_dialog *dlg, - pjsip_tx_data *tdata, - int mod_data_id, - void *mod_data) + pjsip_tx_data *tdata, + int mod_data_id, + void *mod_data) { pjsip_transaction *tsx; pjsip_msg *msg = tdata->msg; @@ -1293,11 +1292,11 @@ PJ_DEF(pj_status_t) pjsip_dlg_send_request( pjsip_dialog *dlg, /* Check arguments. */ PJ_ASSERT_RETURN(dlg && tdata && tdata->msg, PJ_EINVAL); PJ_ASSERT_RETURN(tdata->msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); pj_log_push_indent(); PJ_LOG(5,(dlg->obj_name, "Sending %s", - pjsip_tx_data_get_info(tdata))); + pjsip_tx_data_get_info(tdata))); /* Lock and increment session */ pjsip_dlg_inc_lock(dlg); @@ -1315,62 +1314,62 @@ PJ_DEF(pj_status_t) pjsip_dlg_send_request( pjsip_dialog *dlg, * ACK nor CANCEL. */ if (msg->line.req.method.id != PJSIP_CANCEL_METHOD && - msg->line.req.method.id != PJSIP_ACK_METHOD) + msg->line.req.method.id != PJSIP_ACK_METHOD) { - pjsip_cseq_hdr *ch; + pjsip_cseq_hdr *ch; - ch = PJSIP_MSG_CSEQ_HDR(msg); - PJ_ASSERT_RETURN(ch!=NULL, PJ_EBUG); + ch = PJSIP_MSG_CSEQ_HDR(msg); + PJ_ASSERT_RETURN(ch!=NULL, PJ_EBUG); - ch->cseq = dlg->local.cseq++; + ch->cseq = dlg->local.cseq++; - /* Force the whole message to be re-printed. */ - pjsip_tx_data_invalidate_msg( tdata ); + /* Force the whole message to be re-printed. */ + pjsip_tx_data_invalidate_msg( tdata ); } /* Create a new transaction if method is not ACK. * The transaction user is the user agent module. */ if (msg->line.req.method.id != PJSIP_ACK_METHOD) { - int tsx_count; + int tsx_count; - status = pjsip_tsx_create_uac(dlg->ua, tdata, &tsx); - if (status != PJ_SUCCESS) - goto on_error; + status = pjsip_tsx_create_uac(dlg->ua, tdata, &tsx); + if (status != PJ_SUCCESS) + goto on_error; - /* Set transport selector */ - status = pjsip_tsx_set_transport(tsx, &dlg->tp_sel); - pj_assert(status == PJ_SUCCESS); + /* Set transport selector */ + status = pjsip_tsx_set_transport(tsx, &dlg->tp_sel); + pj_assert(status == PJ_SUCCESS); - /* Attach this dialog to the transaction, so that user agent - * will dispatch events to this dialog. - */ - tsx->mod_data[dlg->ua->id] = dlg; + /* Attach this dialog to the transaction, so that user agent + * will dispatch events to this dialog. + */ + tsx->mod_data[dlg->ua->id] = dlg; - /* Copy optional caller's mod_data, if present */ - if (mod_data_id >= 0 && mod_data_id < PJSIP_MAX_MODULE) - tsx->mod_data[mod_data_id] = mod_data; + /* Copy optional caller's mod_data, if present */ + if (mod_data_id >= 0 && mod_data_id < PJSIP_MAX_MODULE) + tsx->mod_data[mod_data_id] = mod_data; - /* Increment transaction counter. */ - tsx_count = ++dlg->tsx_count; + /* Increment transaction counter. */ + tsx_count = ++dlg->tsx_count; - /* Send the message. */ - status = pjsip_tsx_send_msg(tsx, tdata); - if (status != PJ_SUCCESS) { - if (dlg->tsx_count == tsx_count) - pjsip_tsx_terminate(tsx, tsx->status_code); - goto on_error; - } + /* Send the message. */ + status = pjsip_tsx_send_msg(tsx, tdata); + if (status != PJ_SUCCESS) { + if (dlg->tsx_count == tsx_count) + pjsip_tsx_terminate(tsx, tsx->status_code); + goto on_error; + } } else { - /* Set transport selector */ - pjsip_tx_data_set_transport(tdata, &dlg->tp_sel); + /* Set transport selector */ + pjsip_tx_data_set_transport(tdata, &dlg->tp_sel); - /* Send request */ - status = pjsip_endpt_send_request_stateless(dlg->endpt, tdata, - NULL, &send_ack_callback); - if (status != PJ_SUCCESS) - goto on_error; + /* Send request */ + status = pjsip_endpt_send_request_stateless(dlg->endpt, tdata, + NULL, &send_ack_callback); + if (status != PJ_SUCCESS) + goto on_error; } @@ -1391,9 +1390,9 @@ PJ_DEF(pj_status_t) pjsip_dlg_send_request( pjsip_dialog *dlg, /* Add standard headers for certain types of response */ static void dlg_beautify_response(pjsip_dialog *dlg, - pj_bool_t add_headers, - int st_code, - pjsip_tx_data *tdata) + pj_bool_t add_headers, + int st_code, + pjsip_tx_data *tdata) { pjsip_cseq_hdr *cseq; int st_class; @@ -1407,58 +1406,58 @@ static void dlg_beautify_response(pjsip_dialog *dlg, /* Contact, Allow, Supported header. */ if (add_headers && pjsip_method_creates_dialog(&cseq->method)) { - /* Add Contact header for 1xx, 2xx, 3xx and 485 response. */ - if (st_class==2 || st_class==3 || (st_class==1 && st_code != 100) || - st_code==485) - { - /* Add contact header only if one is not present. */ - if (pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, NULL) == 0 && - pjsip_msg_find_hdr_by_name(tdata->msg, &HCONTACT, NULL) == 0) - { - hdr = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, - dlg->local.contact); - pjsip_msg_add_hdr(tdata->msg, hdr); - } - } - - /* Add Allow header in 18x, 2xx and 405 response. */ - if ((((st_code/10==18 || st_class==2) && dlg->add_allow) - || st_code==405) && - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ALLOW, NULL)==NULL) - { - c_hdr = pjsip_endpt_get_capability(dlg->endpt, - PJSIP_H_ALLOW, NULL); - if (c_hdr) { - hdr = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, c_hdr); - pjsip_msg_add_hdr(tdata->msg, hdr); - } - } - - /* Add Supported header in 2xx response. */ - if (st_class==2 && - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_SUPPORTED, NULL)==NULL) - { - c_hdr = pjsip_endpt_get_capability(dlg->endpt, - PJSIP_H_SUPPORTED, NULL); - if (c_hdr) { - hdr = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, c_hdr); - pjsip_msg_add_hdr(tdata->msg, hdr); - } - } + /* Add Contact header for 1xx, 2xx, 3xx and 485 response. */ + if (st_class==2 || st_class==3 || (st_class==1 && st_code != 100) || + st_code==485) + { + /* Add contact header only if one is not present. */ + if (pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, NULL) == 0 && + pjsip_msg_find_hdr_by_name(tdata->msg, &HCONTACT, NULL) == 0) + { + hdr = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, + dlg->local.contact); + pjsip_msg_add_hdr(tdata->msg, hdr); + } + } + + /* Add Allow header in 18x, 2xx and 405 response. */ + if ((((st_code/10==18 || st_class==2) && dlg->add_allow) + || st_code==405) && + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ALLOW, NULL)==NULL) + { + c_hdr = pjsip_endpt_get_capability(dlg->endpt, + PJSIP_H_ALLOW, NULL); + if (c_hdr) { + hdr = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, c_hdr); + pjsip_msg_add_hdr(tdata->msg, hdr); + } + } + + /* Add Supported header in 2xx response. */ + if (st_class==2 && + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_SUPPORTED, NULL)==NULL) + { + c_hdr = pjsip_endpt_get_capability(dlg->endpt, + PJSIP_H_SUPPORTED, NULL); + if (c_hdr) { + hdr = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, c_hdr); + pjsip_msg_add_hdr(tdata->msg, hdr); + } + } } /* Add To tag in all responses except 100 */ if (st_code != 100) { - pjsip_to_hdr *to; + pjsip_to_hdr *to; - to = PJSIP_MSG_TO_HDR(tdata->msg); - pj_assert(to != NULL); + to = PJSIP_MSG_TO_HDR(tdata->msg); + pj_assert(to != NULL); - to->tag = dlg->local.info->tag; + to->tag = dlg->local.info->tag; - if (dlg->state == PJSIP_DIALOG_STATE_NULL) - dlg->state = PJSIP_DIALOG_STATE_ESTABLISHED; + if (dlg->state == PJSIP_DIALOG_STATE_NULL) + dlg->state = PJSIP_DIALOG_STATE_ESTABLISHED; } } @@ -1466,11 +1465,11 @@ static void dlg_beautify_response(pjsip_dialog *dlg, /* * Create response. */ -PJ_DEF(pj_status_t) pjsip_dlg_create_response( pjsip_dialog *dlg, - pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - pjsip_tx_data **p_tdata) +PJ_DEF(pj_status_t) pjsip_dlg_create_response( pjsip_dialog *dlg, + pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + pjsip_tx_data **p_tdata) { pj_status_t status; pjsip_tx_data *tdata; @@ -1480,9 +1479,9 @@ PJ_DEF(pj_status_t) pjsip_dlg_create_response( pjsip_dialog *dlg, * and Record-Route headers from the request. */ status = pjsip_endpt_create_response(dlg->endpt, - rdata, st_code, st_text, &tdata); + rdata, st_code, st_text, &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Lock the dialog. */ pjsip_dlg_inc_lock(dlg); @@ -1503,16 +1502,16 @@ PJ_DEF(pj_status_t) pjsip_dlg_create_response( pjsip_dialog *dlg, /* * Modify response. */ -PJ_DEF(pj_status_t) pjsip_dlg_modify_response( pjsip_dialog *dlg, - pjsip_tx_data *tdata, - int st_code, - const pj_str_t *st_text) +PJ_DEF(pj_status_t) pjsip_dlg_modify_response( pjsip_dialog *dlg, + pjsip_tx_data *tdata, + int st_code, + const pj_str_t *st_text) { pjsip_hdr *hdr; PJ_ASSERT_RETURN(dlg && tdata && tdata->msg, PJ_EINVAL); PJ_ASSERT_RETURN(tdata->msg->type == PJSIP_RESPONSE_MSG, - PJSIP_ENOTRESPONSEMSG); + PJSIP_ENOTRESPONSEMSG); PJ_ASSERT_RETURN(st_code >= 100 && st_code <= 699, PJ_EINVAL); /* Lock and increment session */ @@ -1521,9 +1520,9 @@ PJ_DEF(pj_status_t) pjsip_dlg_modify_response( pjsip_dialog *dlg, /* Replace status code and reason */ tdata->msg->line.status.code = st_code; if (st_text) { - pj_strdup(tdata->pool, &tdata->msg->line.status.reason, st_text); + pj_strdup(tdata->pool, &tdata->msg->line.status.reason, st_text); } else { - tdata->msg->line.status.reason = *pjsip_get_status_text(st_code); + tdata->msg->line.status.reason = *pjsip_get_status_text(st_code); } /* Remove existing Contact header (without this, when dialog sent @@ -1531,7 +1530,7 @@ PJ_DEF(pj_status_t) pjsip_dlg_modify_response( pjsip_dialog *dlg, */ hdr = (pjsip_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, NULL); if (hdr) - pj_list_erase(hdr); + pj_list_erase(hdr); /* Add tag etc. if necessary */ dlg_beautify_response(dlg, st_code/100 <= 2, st_code, tdata); @@ -1553,15 +1552,15 @@ PJ_DEF(pj_status_t) pjsip_dlg_modify_response( pjsip_dialog *dlg, * Send response statefully. */ PJ_DEF(pj_status_t) pjsip_dlg_send_response( pjsip_dialog *dlg, - pjsip_transaction *tsx, - pjsip_tx_data *tdata) + pjsip_transaction *tsx, + pjsip_tx_data *tdata) { pj_status_t status; /* Sanity check. */ PJ_ASSERT_RETURN(dlg && tsx && tdata && tdata->msg, PJ_EINVAL); PJ_ASSERT_RETURN(tdata->msg->type == PJSIP_RESPONSE_MSG, - PJSIP_ENOTRESPONSEMSG); + PJSIP_ENOTRESPONSEMSG); /* The transaction must belong to this dialog. */ PJ_ASSERT_RETURN(tsx->mod_data[dlg->ua->id] == dlg, PJ_EINVALIDOP); @@ -1569,7 +1568,7 @@ PJ_DEF(pj_status_t) pjsip_dlg_send_response( pjsip_dialog *dlg, pj_log_push_indent(); PJ_LOG(5,(dlg->obj_name, "Sending %s", - pjsip_tx_data_get_info(tdata))); + pjsip_tx_data_get_info(tdata))); /* Check that transaction method and cseq match the response. * This operation is sloooww (search CSeq header twice), that's why @@ -1577,9 +1576,9 @@ PJ_DEF(pj_status_t) pjsip_dlg_send_response( pjsip_dialog *dlg, */ #if defined(PJ_DEBUG) && PJ_DEBUG!=0 PJ_ASSERT_RETURN( PJSIP_MSG_CSEQ_HDR(tdata->msg)->cseq == tsx->cseq && - pjsip_method_cmp(&PJSIP_MSG_CSEQ_HDR(tdata->msg)->method, - &tsx->method)==0, - PJ_EINVALIDOP); + pjsip_method_cmp(&PJSIP_MSG_CSEQ_HDR(tdata->msg)->method, + &tsx->method)==0, + PJ_EINVALIDOP); #endif /* Must acquire dialog first, to prevent deadlock */ @@ -1594,10 +1593,10 @@ PJ_DEF(pj_status_t) pjsip_dlg_send_response( pjsip_dialog *dlg, * is locked to the same transport too. */ if (dlg->tp_sel.type != tsx->tp_sel.type || - dlg->tp_sel.u.ptr != tsx->tp_sel.u.ptr) + dlg->tp_sel.u.ptr != tsx->tp_sel.u.ptr) { - status = pjsip_tsx_set_transport(tsx, &dlg->tp_sel); - pj_assert(status == PJ_SUCCESS); + status = pjsip_tsx_set_transport(tsx, &dlg->tp_sel); + pj_assert(status == PJ_SUCCESS); } /* Ask transaction to send the response */ @@ -1608,7 +1607,7 @@ PJ_DEF(pj_status_t) pjsip_dlg_send_response( pjsip_dialog *dlg, * decrements the counter if the operation is successful. */ if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); + pjsip_tx_data_dec_ref(tdata); } pjsip_dlg_dec_lock(dlg); @@ -1622,11 +1621,11 @@ PJ_DEF(pj_status_t) pjsip_dlg_send_response( pjsip_dialog *dlg, * Combo function to create and send response statefully. */ PJ_DEF(pj_status_t) pjsip_dlg_respond( pjsip_dialog *dlg, - pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - const pjsip_hdr *hdr_list, - const pjsip_msg_body *body ) + pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + const pjsip_hdr *hdr_list, + const pjsip_msg_body *body ) { pj_status_t status; pjsip_tx_data *tdata; @@ -1634,33 +1633,33 @@ PJ_DEF(pj_status_t) pjsip_dlg_respond( pjsip_dialog *dlg, /* Sanity check. */ PJ_ASSERT_RETURN(dlg && rdata && rdata->msg_info.msg, PJ_EINVAL); PJ_ASSERT_RETURN(rdata->msg_info.msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); /* The transaction must belong to this dialog. */ PJ_ASSERT_RETURN(pjsip_rdata_get_tsx(rdata) && - pjsip_rdata_get_tsx(rdata)->mod_data[dlg->ua->id] == dlg, - PJ_EINVALIDOP); + pjsip_rdata_get_tsx(rdata)->mod_data[dlg->ua->id] == dlg, + PJ_EINVALIDOP); /* Create the response. */ status = pjsip_dlg_create_response(dlg, rdata, st_code, st_text, &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Add additional header, if any */ if (hdr_list) { - const pjsip_hdr *hdr; - - hdr = hdr_list->next; - while (hdr != hdr_list) { - pjsip_msg_add_hdr(tdata->msg, - (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, hdr)); - hdr = hdr->next; - } + const pjsip_hdr *hdr; + + hdr = hdr_list->next; + while (hdr != hdr_list) { + pjsip_msg_add_hdr(tdata->msg, + (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, hdr)); + hdr = hdr->next; + } } /* Add the message body, if any. */ if (body) { - tdata->msg->body = pjsip_msg_body_clone( tdata->pool, body); + tdata->msg->body = pjsip_msg_body_clone( tdata->pool, body); } /* Send the response. */ @@ -1679,7 +1678,7 @@ void pjsip_dlg_on_rx_request( pjsip_dialog *dlg, pjsip_rx_data *rdata ) unsigned i; PJ_LOG(5,(dlg->obj_name, "Received %s", - pjsip_rx_data_get_info(rdata))); + pjsip_rx_data_get_info(rdata))); pj_log_push_indent(); /* Lock dialog and increment session. */ @@ -1687,23 +1686,23 @@ void pjsip_dlg_on_rx_request( pjsip_dialog *dlg, pjsip_rx_data *rdata ) /* Check CSeq */ if (rdata->msg_info.cseq->cseq <= dlg->remote.cseq && - rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD && - rdata->msg_info.msg->line.req.method.id != PJSIP_CANCEL_METHOD) + rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD && + rdata->msg_info.msg->line.req.method.id != PJSIP_CANCEL_METHOD) { - /* Invalid CSeq. - * Respond statelessly with 500 (Internal Server Error) - */ - pj_str_t warn_text; - - /* Unlock dialog and dec session, may destroy dialog. */ - pjsip_dlg_dec_lock(dlg); - - pj_assert(pjsip_rdata_get_tsx(rdata) == NULL); - warn_text = pj_str("Invalid CSeq"); - pjsip_endpt_respond_stateless(dlg->endpt, - rdata, 500, &warn_text, NULL, NULL); - pj_log_pop_indent(); - return; + /* Invalid CSeq. + * Respond statelessly with 500 (Internal Server Error) + */ + pj_str_t warn_text; + + /* Unlock dialog and dec session, may destroy dialog. */ + pjsip_dlg_dec_lock(dlg); + + pj_assert(pjsip_rdata_get_tsx(rdata) == NULL); + warn_text = pj_str("Invalid CSeq"); + pjsip_endpt_respond_stateless(dlg->endpt, + rdata, 500, &warn_text, NULL, NULL); + pj_log_pop_indent(); + return; } /* Update CSeq. */ @@ -1715,33 +1714,33 @@ void pjsip_dlg_on_rx_request( pjsip_dialog *dlg, pjsip_rx_data *rdata ) * SUBSCRIBE request). */ if (dlg->remote.info->tag.slen == 0) { - pj_strdup(dlg->pool, &dlg->remote.info->tag, - &rdata->msg_info.from->tag); + pj_strdup(dlg->pool, &dlg->remote.info->tag, + &rdata->msg_info.from->tag); } /* Create UAS transaction for this request. */ if (pjsip_rdata_get_tsx(rdata) == NULL && - rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) + rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { - status = pjsip_tsx_create_uas(dlg->ua, rdata, &tsx); - if (status != PJ_SUCCESS) { - /* Once case for this is when re-INVITE contains same - * Via branch value as previous INVITE (ticket #965). - */ - char errmsg[PJ_ERR_MSG_SIZE]; - pj_str_t reason; - - reason = pj_strerror(status, errmsg, sizeof(errmsg)); - pjsip_endpt_respond_stateless(dlg->endpt, rdata, 500, &reason, - NULL, NULL); - goto on_return; - } - - /* Put this dialog in the transaction data. */ - tsx->mod_data[dlg->ua->id] = dlg; - - /* Add transaction count. */ - ++dlg->tsx_count; + status = pjsip_tsx_create_uas(dlg->ua, rdata, &tsx); + if (status != PJ_SUCCESS) { + /* Once case for this is when re-INVITE contains same + * Via branch value as previous INVITE (ticket #965). + */ + char errmsg[PJ_ERR_MSG_SIZE]; + pj_str_t reason; + + reason = pj_strerror(status, errmsg, sizeof(errmsg)); + pjsip_endpt_respond_stateless(dlg->endpt, rdata, 500, &reason, + NULL, NULL); + goto on_return; + } + + /* Put this dialog in the transaction data. */ + tsx->mod_data[dlg->ua->id] = dlg; + + /* Add transaction count. */ + ++dlg->tsx_count; } /* Update the target URI if this is a target refresh request. @@ -1752,55 +1751,55 @@ void pjsip_dlg_on_rx_request( pjsip_dialog *dlg, pjsip_rx_data *rdata ) * target URI would be wrong, wouldn't it). */ if (pjsip_method_creates_dialog(&rdata->msg_info.cseq->method)) { - pjsip_contact_hdr *contact; - - contact = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, - NULL); - if (contact && contact->uri && - (dlg->remote.contact==NULL || - pjsip_uri_cmp(PJSIP_URI_IN_REQ_URI, - dlg->remote.contact->uri, - contact->uri))) - { - dlg->remote.contact = (pjsip_contact_hdr*) - pjsip_hdr_clone(dlg->pool, contact); - dlg->target = dlg->remote.contact->uri; - } + pjsip_contact_hdr *contact; + + contact = (pjsip_contact_hdr*) + pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, + NULL); + if (contact && contact->uri && + (dlg->remote.contact==NULL || + pjsip_uri_cmp(PJSIP_URI_IN_REQ_URI, + dlg->remote.contact->uri, + contact->uri))) + { + dlg->remote.contact = (pjsip_contact_hdr*) + pjsip_hdr_clone(dlg->pool, contact); + dlg->target = dlg->remote.contact->uri; + } } /* Report the request to dialog usages. */ for (i=0; iusage_cnt; ++i) { - if (!dlg->usage[i]->on_rx_request) - continue; + if (!dlg->usage[i]->on_rx_request) + continue; - processed = (*dlg->usage[i]->on_rx_request)(rdata); + processed = (*dlg->usage[i]->on_rx_request)(rdata); - if (processed) - break; + if (processed) + break; } /* Feed the first request to the transaction. */ if (tsx) - pjsip_tsx_recv_msg(tsx, rdata); + pjsip_tsx_recv_msg(tsx, rdata); /* If no dialog usages has claimed the processing of the transaction, * and if transaction has not sent final response, respond with * 500/Internal Server Error. */ if (!processed && tsx && tsx->status_code < 200) { - pjsip_tx_data *tdata; - const pj_str_t reason = { "Unhandled by dialog usages", 26}; + pjsip_tx_data *tdata; + const pj_str_t reason = { "Unhandled by dialog usages", 26}; - PJ_LOG(4,(tsx->obj_name, "%s was unhandled by " - "dialog usages, sending 500 response", - pjsip_rx_data_get_info(rdata))); + PJ_LOG(4,(tsx->obj_name, "%s was unhandled by " + "dialog usages, sending 500 response", + pjsip_rx_data_get_info(rdata))); - status = pjsip_dlg_create_response(dlg, rdata, 500, &reason, &tdata); - if (status == PJ_SUCCESS) { - status = pjsip_dlg_send_response(dlg, tsx, tdata); - } + status = pjsip_dlg_create_response(dlg, rdata, 500, &reason, &tdata); + if (status == PJ_SUCCESS) { + status = pjsip_dlg_send_response(dlg, tsx, tdata); + } } on_return: @@ -1822,40 +1821,40 @@ static void dlg_update_routeset(pjsip_dialog *dlg, const pjsip_rx_data *rdata) /* Ignore if route set has been frozen */ if (dlg->route_set_frozen) - return; + return; /* Ignore if the message is an UPDATE response (see ticket #1781) */ if (pjsip_method_cmp(&rdata->msg_info.cseq->method, &update) == 0) - return; + return; /* Only update route set if this message belongs to the same * transaction as the initial transaction that establishes dialog. */ if (dlg->role == PJSIP_ROLE_UAC) { - /* Save initial destination host from transport's info. */ - if (!dlg->initial_dest.slen) { - pj_strdup(dlg->pool, &dlg->initial_dest, - &rdata->tp_info.transport->remote_name.host); - } - - /* Ignore subsequent request from remote */ - if (msg->type != PJSIP_RESPONSE_MSG) - return; - - /* Ignore subsequent responses with higher CSeq than initial CSeq. - * Unfortunately this would be broken when the first request is - * challenged! - */ - //if (msg_cseq != dlg->local.first_cseq) - // return; + /* Save initial destination host from transport's info. */ + if (!dlg->initial_dest.slen) { + pj_strdup(dlg->pool, &dlg->initial_dest, + &rdata->tp_info.transport->remote_name.host); + } + + /* Ignore subsequent request from remote */ + if (msg->type != PJSIP_RESPONSE_MSG) + return; + + /* Ignore subsequent responses with higher CSeq than initial CSeq. + * Unfortunately this would be broken when the first request is + * challenged! + */ + //if (msg_cseq != dlg->local.first_cseq) + // return; } else { - /* For callee dialog, route set should have been set by initial - * request and it will have been rejected by dlg->route_set_frozen - * check above. - */ - pj_assert(!"Should not happen"); + /* For callee dialog, route set should have been set by initial + * request and it will have been rejected by dlg->route_set_frozen + * check above. + */ + pj_assert(!"Should not happen"); } @@ -1864,7 +1863,7 @@ static void dlg_update_routeset(pjsip_dialog *dlg, const pjsip_rx_data *rdata) /* Ignore if this is not 1xx or 2xx response */ if (msg->line.status.code >= 300) - return; + return; /* Reset route set */ pj_list_init(&dlg->route_set); @@ -1872,12 +1871,12 @@ static void dlg_update_routeset(pjsip_dialog *dlg, const pjsip_rx_data *rdata) /* Update route set */ end_hdr = &msg->hdr; for (hdr=msg->hdr.prev; hdr!=end_hdr; hdr=hdr->prev) { - if (hdr->type == PJSIP_H_RECORD_ROUTE) { - pjsip_route_hdr *r; - r = (pjsip_route_hdr*) pjsip_hdr_clone(dlg->pool, hdr); - pjsip_routing_hdr_set_route(r); - pj_list_push_back(&dlg->route_set, r); - } + if (hdr->type == PJSIP_H_RECORD_ROUTE) { + pjsip_route_hdr *r; + r = (pjsip_route_hdr*) pjsip_hdr_clone(dlg->pool, hdr); + pjsip_routing_hdr_set_route(r); + pj_list_push_back(&dlg->route_set, r); + } } PJ_LOG(5,(dlg->obj_name, "Route-set updated")); @@ -1895,10 +1894,10 @@ static void dlg_update_routeset(pjsip_dialog *dlg, const pjsip_rx_data *rdata) * freezing the route set upon receiving 200/OK response for PRACK. */ if (pjsip_method_creates_dialog(&rdata->msg_info.cseq->method) && - PJSIP_IS_STATUS_IN_CLASS(msg->line.status.code, 200)) + PJSIP_IS_STATUS_IN_CLASS(msg->line.status.code, 200)) { - dlg->route_set_frozen = PJ_TRUE; - PJ_LOG(5,(dlg->obj_name, "Route-set frozen")); + dlg->route_set_frozen = PJ_TRUE; + PJ_LOG(5,(dlg->obj_name, "Route-set frozen")); } } @@ -1912,7 +1911,7 @@ void pjsip_dlg_on_rx_response( pjsip_dialog *dlg, pjsip_rx_data *rdata ) int res_code; PJ_LOG(5,(dlg->obj_name, "Received %s", - pjsip_rx_data_get_info(rdata))); + pjsip_rx_data_get_info(rdata))); pj_log_push_indent(); /* Lock the dialog and inc session. */ @@ -1942,68 +1941,68 @@ void pjsip_dlg_on_rx_response( pjsip_dialog *dlg, pjsip_rx_data *rdata ) * wrong target. */ if ((dlg->state == PJSIP_DIALOG_STATE_NULL && - pjsip_method_creates_dialog(&rdata->msg_info.cseq->method) && - (res_code > 100 && res_code < 300) && - rdata->msg_info.to->tag.slen) - || - (dlg->role==PJSIP_ROLE_UAC && - !dlg->uac_has_2xx && - res_code > 100 && - res_code/100 <= 2 && - pjsip_method_creates_dialog(&rdata->msg_info.cseq->method) && - pj_stricmp(&dlg->remote.info->tag, &rdata->msg_info.to->tag))) + pjsip_method_creates_dialog(&rdata->msg_info.cseq->method) && + (res_code > 100 && res_code < 300) && + rdata->msg_info.to->tag.slen) + || + (dlg->role==PJSIP_ROLE_UAC && + !dlg->uac_has_2xx && + res_code > 100 && + res_code/100 <= 2 && + pjsip_method_creates_dialog(&rdata->msg_info.cseq->method) && + pj_stricmp(&dlg->remote.info->tag, &rdata->msg_info.to->tag))) { - pjsip_contact_hdr *contact; - - /* Update remote capability info, when To tags in the dialog remote - * info and the incoming response are different, e.g: first response - * with To-tag or forking, apply strict update. - */ - pjsip_dlg_update_remote_cap(dlg, rdata->msg_info.msg, - pj_stricmp(&dlg->remote.info->tag, - &rdata->msg_info.to->tag)); - - /* Update To tag. */ - pj_strdup(dlg->pool, &dlg->remote.info->tag, &rdata->msg_info.to->tag); - /* No need to update remote's tag_hval since its never used. */ - - /* RFC 3271 Section 12.1.2: - * The route set MUST be set to the list of URIs in the Record-Route - * header field from the response, taken in reverse order and - * preserving all URI parameters. If no Record-Route header field - * is present in the response, the route set MUST be set to the - * empty set. This route set, even if empty, overrides any pre-existing - * route set for future requests in this dialog. - */ - dlg_update_routeset(dlg, rdata); - - /* The remote target MUST be set to the URI from the Contact header - * field of the response. - */ - contact = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, - NULL); - if (contact && contact->uri && - (dlg->remote.contact==NULL || - pjsip_uri_cmp(PJSIP_URI_IN_REQ_URI, - dlg->remote.contact->uri, - contact->uri))) - { - dlg->remote.contact = (pjsip_contact_hdr*) - pjsip_hdr_clone(dlg->pool, contact); - dlg->target = dlg->remote.contact->uri; - } - - dlg->state = PJSIP_DIALOG_STATE_ESTABLISHED; - - /* Prevent dialog from being updated just in case more 2xx - * gets through this dialog (it shouldn't happen). - */ - if (dlg->role==PJSIP_ROLE_UAC && !dlg->uac_has_2xx && - res_code/100==2) - { - dlg->uac_has_2xx = PJ_TRUE; - } + pjsip_contact_hdr *contact; + + /* Update remote capability info, when To tags in the dialog remote + * info and the incoming response are different, e.g: first response + * with To-tag or forking, apply strict update. + */ + pjsip_dlg_update_remote_cap(dlg, rdata->msg_info.msg, + pj_stricmp(&dlg->remote.info->tag, + &rdata->msg_info.to->tag)); + + /* Update To tag. */ + pj_strdup(dlg->pool, &dlg->remote.info->tag, &rdata->msg_info.to->tag); + /* No need to update remote's tag_hval since its never used. */ + + /* RFC 3271 Section 12.1.2: + * The route set MUST be set to the list of URIs in the Record-Route + * header field from the response, taken in reverse order and + * preserving all URI parameters. If no Record-Route header field + * is present in the response, the route set MUST be set to the + * empty set. This route set, even if empty, overrides any pre-existing + * route set for future requests in this dialog. + */ + dlg_update_routeset(dlg, rdata); + + /* The remote target MUST be set to the URI from the Contact header + * field of the response. + */ + contact = (pjsip_contact_hdr*) + pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, + NULL); + if (contact && contact->uri && + (dlg->remote.contact==NULL || + pjsip_uri_cmp(PJSIP_URI_IN_REQ_URI, + dlg->remote.contact->uri, + contact->uri))) + { + dlg->remote.contact = (pjsip_contact_hdr*) + pjsip_hdr_clone(dlg->pool, contact); + dlg->target = dlg->remote.contact->uri; + } + + dlg->state = PJSIP_DIALOG_STATE_ESTABLISHED; + + /* Prevent dialog from being updated just in case more 2xx + * gets through this dialog (it shouldn't happen). + */ + if (dlg->role==PJSIP_ROLE_UAC && !dlg->uac_has_2xx && + res_code/100==2) + { + dlg->uac_has_2xx = PJ_TRUE; + } } /* Update remote target (again) when receiving 2xx response messages @@ -2013,61 +2012,61 @@ void pjsip_dlg_on_rx_response( pjsip_dialog *dlg, pjsip_rx_data *rdata ) * This is for compatibility with RFC 2543, as described in Section * 13.2.2.4 of RFC 3261: - If the dialog identifier in the 2xx response matches the dialog - identifier of an existing dialog, the dialog MUST be transitioned to - the "confirmed" state, and the route set for the dialog MUST be - recomputed based on the 2xx response using the procedures of Section - 12.2.1.2. - - Note that the only piece of state that is recomputed is the route - set. Other pieces of state such as the highest sequence numbers - (remote and local) sent within the dialog are not recomputed. The - route set only is recomputed for backwards compatibility. RFC - 2543 did not mandate mirroring of the Record-Route header field in - a 1xx, only 2xx. + If the dialog identifier in the 2xx response matches the dialog + identifier of an existing dialog, the dialog MUST be transitioned to + the "confirmed" state, and the route set for the dialog MUST be + recomputed based on the 2xx response using the procedures of Section + 12.2.1.2. + + Note that the only piece of state that is recomputed is the route + set. Other pieces of state such as the highest sequence numbers + (remote and local) sent within the dialog are not recomputed. The + route set only is recomputed for backwards compatibility. RFC + 2543 did not mandate mirroring of the Record-Route header field in + a 1xx, only 2xx. */ if (pjsip_method_creates_dialog(&rdata->msg_info.cseq->method) && - res_code/100 == 2) + res_code/100 == 2) { - pjsip_contact_hdr *contact; - - contact = (pjsip_contact_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg, - PJSIP_H_CONTACT, - NULL); - if (contact && contact->uri && - (dlg->remote.contact==NULL || - pjsip_uri_cmp(PJSIP_URI_IN_REQ_URI, - dlg->remote.contact->uri, - contact->uri))) - { - dlg->remote.contact = (pjsip_contact_hdr*) - pjsip_hdr_clone(dlg->pool, contact); - dlg->target = dlg->remote.contact->uri; - } - - dlg_update_routeset(dlg, rdata); - - /* Update remote capability info after the first 2xx response - * (ticket #1539). Note that the remote capability retrieved here - * will be assumed to remain unchanged for the duration of the dialog. - */ - if (dlg->role==PJSIP_ROLE_UAC && !dlg->uac_has_2xx) { - pjsip_dlg_update_remote_cap(dlg, rdata->msg_info.msg, PJ_FALSE); - dlg->uac_has_2xx = PJ_TRUE; - } + pjsip_contact_hdr *contact; + + contact = (pjsip_contact_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg, + PJSIP_H_CONTACT, + NULL); + if (contact && contact->uri && + (dlg->remote.contact==NULL || + pjsip_uri_cmp(PJSIP_URI_IN_REQ_URI, + dlg->remote.contact->uri, + contact->uri))) + { + dlg->remote.contact = (pjsip_contact_hdr*) + pjsip_hdr_clone(dlg->pool, contact); + dlg->target = dlg->remote.contact->uri; + } + + dlg_update_routeset(dlg, rdata); + + /* Update remote capability info after the first 2xx response + * (ticket #1539). Note that the remote capability retrieved here + * will be assumed to remain unchanged for the duration of the dialog. + */ + if (dlg->role==PJSIP_ROLE_UAC && !dlg->uac_has_2xx) { + pjsip_dlg_update_remote_cap(dlg, rdata->msg_info.msg, PJ_FALSE); + dlg->uac_has_2xx = PJ_TRUE; + } } /* Pass to dialog usages. */ for (i=0; iusage_cnt; ++i) { - pj_bool_t processed; + pj_bool_t processed; - if (!dlg->usage[i]->on_rx_response) - continue; + if (!dlg->usage[i]->on_rx_response) + continue; - processed = (*dlg->usage[i]->on_rx_response)(rdata); + processed = (*dlg->usage[i]->on_rx_response)(rdata); - if (processed) - break; + if (processed) + break; } /* Handle the case of forked response, when the application creates @@ -2076,40 +2075,40 @@ void pjsip_dlg_on_rx_response( pjsip_dialog *dlg, pjsip_rx_data *rdata ) * here. */ if (dlg->usage_cnt==0) { - pj_status_t status; - - if (rdata->msg_info.cseq->method.id==PJSIP_INVITE_METHOD && - rdata->msg_info.msg->line.status.code/100 == 2) - { - pjsip_tx_data *ack; - - status = pjsip_dlg_create_request(dlg, &pjsip_ack_method, - rdata->msg_info.cseq->cseq, - &ack); - if (status == PJ_SUCCESS) - status = pjsip_dlg_send_request(dlg, ack, -1, NULL); - } else if (rdata->msg_info.msg->line.status.code==401 || - rdata->msg_info.msg->line.status.code==407) - { - pjsip_transaction *tsx = pjsip_rdata_get_tsx(rdata); - pjsip_tx_data *tdata; - - status = pjsip_auth_clt_reinit_req( &dlg->auth_sess, - rdata, tsx->last_tx, - &tdata); - - if (status == PJ_SUCCESS) { - /* Re-send request. */ - status = pjsip_dlg_send_request(dlg, tdata, -1, NULL); - } - } + pj_status_t status; + + if (rdata->msg_info.cseq->method.id==PJSIP_INVITE_METHOD && + rdata->msg_info.msg->line.status.code/100 == 2) + { + pjsip_tx_data *ack; + + status = pjsip_dlg_create_request(dlg, &pjsip_ack_method, + rdata->msg_info.cseq->cseq, + &ack); + if (status == PJ_SUCCESS) + status = pjsip_dlg_send_request(dlg, ack, -1, NULL); + } else if (rdata->msg_info.msg->line.status.code==401 || + rdata->msg_info.msg->line.status.code==407) + { + pjsip_transaction *tsx = pjsip_rdata_get_tsx(rdata); + pjsip_tx_data *tdata; + + status = pjsip_auth_clt_reinit_req( &dlg->auth_sess, + rdata, tsx->last_tx, + &tdata); + + if (status == PJ_SUCCESS) { + /* Re-send request. */ + status = pjsip_dlg_send_request(dlg, tdata, -1, NULL); + } + } } /* Unhandled response does not necessarily mean error because dialog usages may choose to process the transaction state instead. if (i==dlg->usage_cnt) { - PJ_LOG(4,(dlg->obj_name, "%s was not claimed by any dialog usages", - pjsip_rx_data_get_info(rdata))); + PJ_LOG(4,(dlg->obj_name, "%s was not claimed by any dialog usages", + pjsip_rx_data_get_info(rdata))); } */ @@ -2123,13 +2122,13 @@ void pjsip_dlg_on_rx_response( pjsip_dialog *dlg, pjsip_rx_data *rdata ) * state notification. */ void pjsip_dlg_on_tsx_state( pjsip_dialog *dlg, - pjsip_transaction *tsx, - pjsip_event *e ) + pjsip_transaction *tsx, + pjsip_event *e ) { unsigned i; PJ_LOG(5,(dlg->obj_name, "Transaction %s state changed to %s", - tsx->obj_name, pjsip_tsx_state_str(tsx->state))); + tsx->obj_name, pjsip_tsx_state_str(tsx->state))); pj_log_push_indent(); /* Lock the dialog and increment session. */ @@ -2138,10 +2137,10 @@ void pjsip_dlg_on_tsx_state( pjsip_dialog *dlg, /* Pass to dialog usages. */ for (i=0; iusage_cnt; ++i) { - if (!dlg->usage[i]->on_tsx_state) - continue; + if (!dlg->usage[i]->on_tsx_state) + continue; - (*dlg->usage[i]->on_tsx_state)(tsx, e); + (*dlg->usage[i]->on_tsx_state)(tsx, e); } @@ -2150,11 +2149,11 @@ void pjsip_dlg_on_tsx_state( pjsip_dialog *dlg, * the tsx_count if we're still attached to the transaction. */ if (tsx->state == PJSIP_TSX_STATE_TERMINATED && - tsx->mod_data[dlg->ua->id] == dlg) + tsx->mod_data[dlg->ua->id] == dlg) { - pj_assert(dlg->tsx_count>0); - --dlg->tsx_count; - tsx->mod_data[dlg->ua->id] = NULL; + pj_assert(dlg->tsx_count>0); + --dlg->tsx_count; + tsx->mod_data[dlg->ua->id] = NULL; } /* Unlock dialog and dec session, may destroy dialog. */ @@ -2167,10 +2166,10 @@ void pjsip_dlg_on_tsx_state( pjsip_dialog *dlg, * Check if the specified capability is supported by remote. */ PJ_DEF(pjsip_dialog_cap_status) pjsip_dlg_remote_has_cap( - pjsip_dialog *dlg, - int htype, - const pj_str_t *hname, - const pj_str_t *token) + pjsip_dialog *dlg, + int htype, + const pj_str_t *hname, + const pj_str_t *token) { const pjsip_generic_array_hdr *hdr; pjsip_dialog_cap_status cap_status = PJSIP_DIALOG_CAP_UNSUPPORTED; @@ -2181,16 +2180,16 @@ PJ_DEF(pjsip_dialog_cap_status) pjsip_dlg_remote_has_cap( pjsip_dlg_inc_lock(dlg); hdr = (const pjsip_generic_array_hdr*) - pjsip_dlg_get_remote_cap_hdr(dlg, htype, hname); + pjsip_dlg_get_remote_cap_hdr(dlg, htype, hname); if (!hdr) { - cap_status = PJSIP_DIALOG_CAP_UNKNOWN; + cap_status = PJSIP_DIALOG_CAP_UNKNOWN; } else { - for (i=0; icount; ++i) { - if (!pj_stricmp(&hdr->values[i], token)) { - cap_status = PJSIP_DIALOG_CAP_SUPPORTED; - break; - } - } + for (i=0; icount; ++i) { + if (!pj_stricmp(&hdr->values[i], token)) { + cap_status = PJSIP_DIALOG_CAP_SUPPORTED; + break; + } + } } pjsip_dlg_dec_lock(dlg); @@ -2204,11 +2203,11 @@ PJ_DEF(pjsip_dialog_cap_status) pjsip_dlg_remote_has_cap( * the received message. */ PJ_DEF(pj_status_t) pjsip_dlg_update_remote_cap(pjsip_dialog *dlg, - const pjsip_msg *msg, - pj_bool_t strict) + const pjsip_msg *msg, + pj_bool_t strict) { pjsip_hdr_e htypes[] = - { PJSIP_H_ACCEPT, PJSIP_H_ALLOW, PJSIP_H_SUPPORTED }; + { PJSIP_H_ACCEPT, PJSIP_H_ALLOW, PJSIP_H_SUPPORTED }; unsigned i; PJ_ASSERT_RETURN(dlg && msg, PJ_EINVAL); @@ -2217,52 +2216,52 @@ PJ_DEF(pj_status_t) pjsip_dlg_update_remote_cap(pjsip_dialog *dlg, /* Retrieve all specified capability header types */ for (i = 0; i < PJ_ARRAY_SIZE(htypes); ++i) { - const pjsip_generic_array_hdr *hdr; - pj_status_t status; - - /* Find this capability type in the message */ - hdr = (const pjsip_generic_array_hdr*) - pjsip_msg_find_hdr(msg, htypes[i], NULL); - if (!hdr) { - /* Not found. - * If strict update is specified, remote this capability type - * from the capability list. - */ - if (strict) - pjsip_dlg_remove_remote_cap_hdr(dlg, htypes[i], NULL); - } else { - /* Found, a capability type may be specified in multiple headers, - * so combine all the capability tags/values into a temporary - * header. - */ - pjsip_generic_array_hdr tmp_hdr; - - /* Init temporary header */ - pjsip_generic_array_hdr_init(dlg->pool, &tmp_hdr, NULL); - pj_memcpy(&tmp_hdr, hdr, sizeof(pjsip_hdr)); - - while (hdr) { - unsigned j; - - /* Append the header content to temporary header */ - for(j=0; jcount && - tmp_hdr.countvalues[j]; - } - - /* Get the next header for this capability */ - hdr = (const pjsip_generic_array_hdr*) - pjsip_msg_find_hdr(msg, htypes[i], hdr->next); - } - - /* Save this capability */ - status = pjsip_dlg_set_remote_cap_hdr(dlg, &tmp_hdr); - if (status != PJ_SUCCESS) { - pjsip_dlg_dec_lock(dlg); - return status; - } - } + const pjsip_generic_array_hdr *hdr; + pj_status_t status; + + /* Find this capability type in the message */ + hdr = (const pjsip_generic_array_hdr*) + pjsip_msg_find_hdr(msg, htypes[i], NULL); + if (!hdr) { + /* Not found. + * If strict update is specified, remote this capability type + * from the capability list. + */ + if (strict) + pjsip_dlg_remove_remote_cap_hdr(dlg, htypes[i], NULL); + } else { + /* Found, a capability type may be specified in multiple headers, + * so combine all the capability tags/values into a temporary + * header. + */ + pjsip_generic_array_hdr tmp_hdr; + + /* Init temporary header */ + pjsip_generic_array_hdr_init(dlg->pool, &tmp_hdr, NULL); + pj_memcpy(&tmp_hdr, hdr, sizeof(pjsip_hdr)); + + while (hdr) { + unsigned j; + + /* Append the header content to temporary header */ + for(j=0; jcount && + tmp_hdr.countvalues[j]; + } + + /* Get the next header for this capability */ + hdr = (const pjsip_generic_array_hdr*) + pjsip_msg_find_hdr(msg, htypes[i], hdr->next); + } + + /* Save this capability */ + status = pjsip_dlg_set_remote_cap_hdr(dlg, &tmp_hdr); + if (status != PJ_SUCCESS) { + pjsip_dlg_dec_lock(dlg); + return status; + } + } } pjsip_dlg_dec_lock(dlg); @@ -2275,27 +2274,27 @@ PJ_DEF(pj_status_t) pjsip_dlg_update_remote_cap(pjsip_dialog *dlg, * Get the value of the specified capability header field of remote. */ PJ_DEF(const pjsip_hdr*) pjsip_dlg_get_remote_cap_hdr(pjsip_dialog *dlg, - int htype, - const pj_str_t *hname) + int htype, + const pj_str_t *hname) { pjsip_hdr *hdr; /* Check arguments. */ PJ_ASSERT_RETURN(dlg, NULL); PJ_ASSERT_RETURN((htype != PJSIP_H_OTHER) || (hname && hname->slen), - NULL); + NULL); pjsip_dlg_inc_lock(dlg); hdr = dlg->rem_cap_hdr.next; while (hdr != &dlg->rem_cap_hdr) { - if ((htype != PJSIP_H_OTHER && htype == hdr->type) || - (htype == PJSIP_H_OTHER && pj_stricmp(&hdr->name, hname) == 0)) - { - pjsip_dlg_dec_lock(dlg); - return hdr; - } - hdr = hdr->next; + if ((htype != PJSIP_H_OTHER && htype == hdr->type) || + (htype == PJSIP_H_OTHER && pj_stricmp(&hdr->name, hname) == 0)) + { + pjsip_dlg_dec_lock(dlg); + return hdr; + } + hdr = hdr->next; } pjsip_dlg_dec_lock(dlg); @@ -2309,8 +2308,8 @@ PJ_DEF(const pjsip_hdr*) pjsip_dlg_get_remote_cap_hdr(pjsip_dialog *dlg, * of capability tags/values. */ PJ_DEF(pj_status_t) pjsip_dlg_set_remote_cap_hdr( - pjsip_dialog *dlg, - const pjsip_generic_array_hdr *cap_hdr) + pjsip_dialog *dlg, + const pjsip_generic_array_hdr *cap_hdr) { pjsip_generic_array_hdr *hdr; @@ -2321,28 +2320,28 @@ PJ_DEF(pj_status_t) pjsip_dlg_set_remote_cap_hdr( /* Find the header. */ hdr = (pjsip_generic_array_hdr*) - pjsip_dlg_get_remote_cap_hdr(dlg, cap_hdr->type, &cap_hdr->name); + pjsip_dlg_get_remote_cap_hdr(dlg, cap_hdr->type, &cap_hdr->name); /* Quick compare if the capability is up to date */ if (hdr && hdr->count == cap_hdr->count) { - unsigned i; - pj_bool_t uptodate = PJ_TRUE; - - for (i=0; icount; ++i) { - if (pj_stricmp(&hdr->values[i], &cap_hdr->values[i])) - uptodate = PJ_FALSE; - } - - /* Capability is up to date, just return PJ_SUCCESS */ - if (uptodate) { - pjsip_dlg_dec_lock(dlg); - return PJ_SUCCESS; - } + unsigned i; + pj_bool_t uptodate = PJ_TRUE; + + for (i=0; icount; ++i) { + if (pj_stricmp(&hdr->values[i], &cap_hdr->values[i])) + uptodate = PJ_FALSE; + } + + /* Capability is up to date, just return PJ_SUCCESS */ + if (uptodate) { + pjsip_dlg_dec_lock(dlg); + return PJ_SUCCESS; + } } /* Remove existing capability header if any */ if (hdr) - pj_list_erase(hdr); + pj_list_erase(hdr); /* Add the new capability header */ hdr = (pjsip_generic_array_hdr*) pjsip_hdr_clone(dlg->pool, cap_hdr); @@ -2360,23 +2359,23 @@ PJ_DEF(pj_status_t) pjsip_dlg_set_remote_cap_hdr( * Remove a remote capability header. */ PJ_DEF(pj_status_t) pjsip_dlg_remove_remote_cap_hdr(pjsip_dialog *dlg, - int htype, - const pj_str_t *hname) + int htype, + const pj_str_t *hname) { pjsip_generic_array_hdr *hdr; /* Check arguments. */ PJ_ASSERT_RETURN(dlg, PJ_EINVAL); PJ_ASSERT_RETURN((htype != PJSIP_H_OTHER) || (hname && hname->slen), - PJ_EINVAL); + PJ_EINVAL); pjsip_dlg_inc_lock(dlg); hdr = (pjsip_generic_array_hdr*) - pjsip_dlg_get_remote_cap_hdr(dlg, htype, hname); + pjsip_dlg_get_remote_cap_hdr(dlg, htype, hname); if (!hdr) { - pjsip_dlg_dec_lock(dlg); - return PJ_ENOTFOUND; + pjsip_dlg_dec_lock(dlg); + return PJ_ENOTFOUND; } pj_list_erase(hdr); diff --git a/pjsip/src/pjsip/sip_dialog_wrap.cpp b/pjsip/src/pjsip/sip_dialog_wrap.cpp index 8c76562a11..9ca76415e0 100644 --- a/pjsip/src/pjsip/sip_dialog_wrap.cpp +++ b/pjsip/src/pjsip/sip_dialog_wrap.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjsip/src/pjsip/sip_endpoint.c b/pjsip/src/pjsip/sip_endpoint.c index 8bc222fe26..f77e21708b 100644 --- a/pjsip/src/pjsip/sip_endpoint.c +++ b/pjsip/src/pjsip/sip_endpoint.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -37,7 +36,7 @@ #include #define PJSIP_EX_NO_MEMORY pj_NO_MEMORY_EXCEPTION() -#define THIS_FILE "sip_endpoint.c" +#define THIS_FILE "sip_endpoint.c" #define MAX_METHODS 32 @@ -45,8 +44,8 @@ /* List of SIP endpoint exit callback. */ typedef struct exit_cb { - PJ_DECL_LIST_MEMBER (struct exit_cb); - pjsip_endpt_exit_callback func; + PJ_DECL_LIST_MEMBER (struct exit_cb); + pjsip_endpt_exit_callback func; } exit_cb; @@ -56,55 +55,55 @@ typedef struct exit_cb struct pjsip_endpoint { /** Pool to allocate memory for the endpoint. */ - pj_pool_t *pool; + pj_pool_t *pool; /** Mutex for the pool, hash table, and event list/queue. */ - pj_mutex_t *mutex; + pj_mutex_t *mutex; /** Pool factory. */ - pj_pool_factory *pf; + pj_pool_factory *pf; /** Name. */ - pj_str_t name; + pj_str_t name; /** Timer heap. */ - pj_timer_heap_t *timer_heap; + pj_timer_heap_t *timer_heap; /** Transport manager. */ - pjsip_tpmgr *transport_mgr; + pjsip_tpmgr *transport_mgr; /** Ioqueue. */ - pj_ioqueue_t *ioqueue; + pj_ioqueue_t *ioqueue; /** Last ioqueue err */ - pj_status_t ioq_last_err; + pj_status_t ioq_last_err; /** DNS Resolver. */ - pjsip_resolver_t *resolver; + pjsip_resolver_t *resolver; /** Modules lock. */ - pj_rwmutex_t *mod_mutex; + pj_rwmutex_t *mod_mutex; /** Modules. */ pjsip_module *modules[PJSIP_MAX_MODULE]; /** Module list, sorted by priority. */ - pjsip_module module_list; + pjsip_module module_list; /** Capability header list. */ - pjsip_hdr cap_hdr; + pjsip_hdr cap_hdr; /** Additional request headers. */ - pjsip_hdr req_hdr; + pjsip_hdr req_hdr; /** List of exit callback. */ - exit_cb exit_cb_list; + exit_cb exit_cb_list; }; #if defined(PJSIP_SAFE_MODULE) && PJSIP_SAFE_MODULE!=0 -# define LOCK_MODULE_ACCESS(ept) pj_rwmutex_lock_read(ept->mod_mutex) -# define UNLOCK_MODULE_ACCESS(ept) pj_rwmutex_unlock_read(ept->mod_mutex) +# define LOCK_MODULE_ACCESS(ept) pj_rwmutex_lock_read(ept->mod_mutex) +# define UNLOCK_MODULE_ACCESS(ept) pj_rwmutex_unlock_read(ept->mod_mutex) #else # define LOCK_MODULE_ACCESS(endpt) # define UNLOCK_MODULE_ACCESS(endpt) @@ -116,11 +115,11 @@ struct pjsip_endpoint * Prototypes. */ static void endpt_on_rx_msg( pjsip_endpoint*, - pj_status_t, pjsip_rx_data*); + pj_status_t, pjsip_rx_data*); static pj_status_t endpt_on_tx_msg( pjsip_endpoint *endpt, - pjsip_tx_data *tdata ); + pjsip_tx_data *tdata ); static pj_status_t unload_module(pjsip_endpoint *endpt, - pjsip_module *mod); + pjsip_module *mod); /* Defined in sip_parser.c */ void init_sip_parser(void); @@ -158,7 +157,7 @@ static int cmp_mod_name(void *name, const void *mod) * module. */ PJ_DEF(pj_status_t) pjsip_endpt_register_module( pjsip_endpoint *endpt, - pjsip_module *mod ) + pjsip_module *mod ) { pj_status_t status = PJ_SUCCESS; pjsip_module *m; @@ -167,23 +166,23 @@ PJ_DEF(pj_status_t) pjsip_endpt_register_module( pjsip_endpoint *endpt, pj_rwmutex_lock_write(endpt->mod_mutex); /* Make sure that this module has not been registered. */ - PJ_ASSERT_ON_FAIL( pj_list_find_node(&endpt->module_list, mod) == NULL, - {status = PJ_EEXISTS; goto on_return;}); + PJ_ASSERT_ON_FAIL( pj_list_find_node(&endpt->module_list, mod) == NULL, + {status = PJ_EEXISTS; goto on_return;}); /* Make sure that no module with the same name has been registered. */ - PJ_ASSERT_ON_FAIL( pj_list_search(&endpt->module_list, &mod->name, - &cmp_mod_name)==NULL, - {status = PJ_EEXISTS; goto on_return; }); + PJ_ASSERT_ON_FAIL( pj_list_search(&endpt->module_list, &mod->name, + &cmp_mod_name)==NULL, + {status = PJ_EEXISTS; goto on_return; }); /* Find unused ID for this module. */ for (i=0; imodules); ++i) { - if (endpt->modules[i] == NULL) - break; + if (endpt->modules[i] == NULL) + break; } if (i == PJ_ARRAY_SIZE(endpt->modules)) { - pj_assert(!"Too many modules registered!"); - status = PJ_ETOOMANY; - goto on_return; + pj_assert(!"Too many modules registered!"); + status = PJ_ETOOMANY; + goto on_return; } /* Assign the ID. */ @@ -191,16 +190,16 @@ PJ_DEF(pj_status_t) pjsip_endpt_register_module( pjsip_endpoint *endpt, /* Try to load the module. */ if (mod->load) { - status = (*mod->load)(endpt); - if (status != PJ_SUCCESS) - goto on_return; + status = (*mod->load)(endpt); + if (status != PJ_SUCCESS) + goto on_return; } /* Try to start the module. */ if (mod->start) { - status = (*mod->start)(); - if (status != PJ_SUCCESS) - goto on_return; + status = (*mod->start)(); + if (status != PJ_SUCCESS) + goto on_return; } /* Save the module. */ @@ -209,16 +208,16 @@ PJ_DEF(pj_status_t) pjsip_endpt_register_module( pjsip_endpoint *endpt, /* Put in the module list, sorted by priority. */ m = endpt->module_list.next; while (m != &endpt->module_list) { - if (m->priority > mod->priority) - break; - m = m->next; + if (m->priority > mod->priority) + break; + m = m->next; } pj_list_insert_before(m, mod); /* Done. */ PJ_LOG(4,(THIS_FILE, "Module \"%.*s\" registered", - (int)mod->name.slen, mod->name.ptr)); + (int)mod->name.slen, mod->name.ptr)); on_return: pj_rwmutex_unlock_write(endpt->mod_mutex); @@ -231,26 +230,26 @@ PJ_DEF(pj_status_t) pjsip_endpt_register_module( pjsip_endpoint *endpt, * properly shutdown the module. */ PJ_DEF(pj_status_t) pjsip_endpt_unregister_module( pjsip_endpoint *endpt, - pjsip_module *mod ) + pjsip_module *mod ) { pj_status_t status; pj_rwmutex_lock_write(endpt->mod_mutex); /* Make sure the module exists in the list. */ - PJ_ASSERT_ON_FAIL( pj_list_find_node(&endpt->module_list, mod) == mod, - {status = PJ_ENOTFOUND;goto on_return;} ); + PJ_ASSERT_ON_FAIL( pj_list_find_node(&endpt->module_list, mod) == mod, + {status = PJ_ENOTFOUND;goto on_return;} ); /* Make sure the module exists in the array. */ - PJ_ASSERT_ON_FAIL( mod->id>=0 && - mod->id<(int)PJ_ARRAY_SIZE(endpt->modules) && - endpt->modules[mod->id] == mod, - {status = PJ_ENOTFOUND; goto on_return;}); + PJ_ASSERT_ON_FAIL( mod->id>=0 && + mod->id<(int)PJ_ARRAY_SIZE(endpt->modules) && + endpt->modules[mod->id] == mod, + {status = PJ_ENOTFOUND; goto on_return;}); /* Try to stop the module. */ if (mod->stop) { - status = (*mod->stop)(); - if (status != PJ_SUCCESS) goto on_return; + status = (*mod->stop)(); + if (status != PJ_SUCCESS) goto on_return; } /* Unload module */ @@ -260,26 +259,26 @@ PJ_DEF(pj_status_t) pjsip_endpt_unregister_module( pjsip_endpoint *endpt, pj_rwmutex_unlock_write(endpt->mod_mutex); if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; + char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(3,(THIS_FILE, "Module \"%.*s\" can not be unregistered: %s", - (int)mod->name.slen, mod->name.ptr, errmsg)); + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(3,(THIS_FILE, "Module \"%.*s\" can not be unregistered: %s", + (int)mod->name.slen, mod->name.ptr, errmsg)); } return status; } static pj_status_t unload_module(pjsip_endpoint *endpt, - pjsip_module *mod) + pjsip_module *mod) { pj_status_t status; /* Try to unload the module. */ if (mod->unload) { - status = (*mod->unload)(); - if (status != PJ_SUCCESS) - return status; + status = (*mod->unload)(); + if (status != PJ_SUCCESS) + return status; } /* Module MUST NOT set module ID to -1. */ @@ -298,7 +297,7 @@ static pj_status_t unload_module(pjsip_endpoint *endpt, status = PJ_SUCCESS; PJ_LOG(4,(THIS_FILE, "Module \"%.*s\" unregistered", - (int)mod->name.slen, mod->name.ptr)); + (int)mod->name.slen, mod->name.ptr)); return status; } @@ -308,8 +307,8 @@ static pj_status_t unload_module(pjsip_endpoint *endpt, * Get the value of the specified capability header field. */ PJ_DEF(const pjsip_hdr*) pjsip_endpt_get_capability( pjsip_endpoint *endpt, - int htype, - const pj_str_t *hname) + int htype, + const pj_str_t *hname) { pjsip_hdr *hdr = endpt->cap_hdr.next; @@ -318,11 +317,11 @@ PJ_DEF(const pjsip_hdr*) pjsip_endpt_get_capability( pjsip_endpoint *endpt, PJ_ASSERT_RETURN(htype != PJSIP_H_OTHER || hname, NULL); if (htype != PJSIP_H_OTHER) { - while (hdr != &endpt->cap_hdr) { - if (hdr->type == htype) - return hdr; - hdr = hdr->next; - } + while (hdr != &endpt->cap_hdr) { + if (hdr->type == htype) + return hdr; + hdr = hdr->next; + } } return NULL; } @@ -332,23 +331,23 @@ PJ_DEF(const pjsip_hdr*) pjsip_endpt_get_capability( pjsip_endpoint *endpt, * Check if the specified capability is supported. */ PJ_DEF(pj_bool_t) pjsip_endpt_has_capability( pjsip_endpoint *endpt, - int htype, - const pj_str_t *hname, - const pj_str_t *token) + int htype, + const pj_str_t *hname, + const pj_str_t *token) { const pjsip_generic_array_hdr *hdr; unsigned i; hdr = (const pjsip_generic_array_hdr*) - pjsip_endpt_get_capability(endpt, htype, hname); + pjsip_endpt_get_capability(endpt, htype, hname); if (!hdr) - return PJ_FALSE; + return PJ_FALSE; PJ_ASSERT_RETURN(token != NULL, PJ_FALSE); for (i=0; icount; ++i) { - if (!pj_stricmp(&hdr->values[i], token)) - return PJ_TRUE; + if (!pj_stricmp(&hdr->values[i], token)) + return PJ_TRUE; } return PJ_FALSE; @@ -359,11 +358,11 @@ PJ_DEF(pj_bool_t) pjsip_endpt_has_capability( pjsip_endpoint *endpt, * appropriate header fields in the endpoint. */ PJ_DEF(pj_status_t) pjsip_endpt_add_capability( pjsip_endpoint *endpt, - pjsip_module *mod, - int htype, - const pj_str_t *hname, - unsigned count, - const pj_str_t tags[]) + pjsip_module *mod, + int htype, + const pj_str_t *hname, + unsigned count, + const pj_str_t tags[]) { pjsip_generic_array_hdr *hdr; unsigned i; @@ -374,39 +373,39 @@ PJ_DEF(pj_status_t) pjsip_endpt_add_capability( pjsip_endpoint *endpt, PJ_ASSERT_RETURN(endpt!=NULL && count>0 && tags, PJ_EINVAL); PJ_ASSERT_RETURN(count <= PJSIP_GENERIC_ARRAY_MAX_COUNT, PJ_ETOOMANY); PJ_ASSERT_RETURN(htype==PJSIP_H_ACCEPT || - htype==PJSIP_H_ALLOW || - htype==PJSIP_H_SUPPORTED, - PJ_EINVAL); + htype==PJSIP_H_ALLOW || + htype==PJSIP_H_SUPPORTED, + PJ_EINVAL); /* Find the header. */ hdr = (pjsip_generic_array_hdr*) pjsip_endpt_get_capability(endpt, - htype, hname); + htype, hname); /* Create the header when it's not present */ if (hdr == NULL) { - switch (htype) { - case PJSIP_H_ACCEPT: - hdr = pjsip_accept_hdr_create(endpt->pool); - break; - case PJSIP_H_ALLOW: - hdr = pjsip_allow_hdr_create(endpt->pool); - break; - case PJSIP_H_SUPPORTED: - hdr = pjsip_supported_hdr_create(endpt->pool); - break; - default: - return PJ_EINVAL; - } - - if (hdr) { - pj_list_push_back(&endpt->cap_hdr, hdr); - } + switch (htype) { + case PJSIP_H_ACCEPT: + hdr = pjsip_accept_hdr_create(endpt->pool); + break; + case PJSIP_H_ALLOW: + hdr = pjsip_allow_hdr_create(endpt->pool); + break; + case PJSIP_H_SUPPORTED: + hdr = pjsip_supported_hdr_create(endpt->pool); + break; + default: + return PJ_EINVAL; + } + + if (hdr) { + pj_list_push_back(&endpt->cap_hdr, hdr); + } } /* Add the tags to the header. */ for (i=0; ipool, &hdr->values[hdr->count], &tags[i]); - ++hdr->count; + pj_strdup(endpt->pool, &hdr->values[hdr->count], &tags[i]); + ++hdr->count; } /* Done. */ @@ -426,7 +425,7 @@ PJ_DEF(const pjsip_hdr*) pjsip_endpt_get_request_headers(pjsip_endpoint *endpt) * Initialize endpoint. */ PJ_DEF(pj_status_t) pjsip_endpt_create(pj_pool_factory *pf, - const char *name, + const char *name, pjsip_endpoint **p_endpt) { pj_status_t status; @@ -437,7 +436,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_create(pj_pool_factory *pf, status = pj_register_strerror(PJSIP_ERRNO_START, PJ_ERRNO_SPACE_SIZE, - &pjsip_strerror); + &pjsip_strerror); pj_assert(status == PJ_SUCCESS); PJ_LOG(5, (THIS_FILE, "Creating endpoint instance...")); @@ -446,10 +445,10 @@ PJ_DEF(pj_status_t) pjsip_endpt_create(pj_pool_factory *pf, /* Create pool */ pool = pj_pool_create(pf, "pept%p", - PJSIP_POOL_LEN_ENDPT, PJSIP_POOL_INC_ENDPT, - &pool_callback); + PJSIP_POOL_LEN_ENDPT, PJSIP_POOL_INC_ENDPT, + &pool_callback); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create endpoint. */ endpt = PJ_POOL_ZALLOC_T(pool, pjsip_endpoint); @@ -465,7 +464,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_create(pj_pool_factory *pf, /* Create R/W mutex for module manipulation. */ status = pj_rwmutex_create(endpt->pool, "ept%p", &endpt->mod_mutex); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Init parser. */ init_sip_parser(); @@ -475,57 +474,57 @@ PJ_DEF(pj_status_t) pjsip_endpt_create(pj_pool_factory *pf, /* Get name. */ if (name != NULL) { - pj_str_t temp; - pj_strdup_with_null(endpt->pool, &endpt->name, pj_cstr(&temp, name)); + pj_str_t temp; + pj_strdup_with_null(endpt->pool, &endpt->name, pj_cstr(&temp, name)); } else { - pj_strdup_with_null(endpt->pool, &endpt->name, pj_gethostname()); + pj_strdup_with_null(endpt->pool, &endpt->name, pj_gethostname()); } /* Create mutex for the events, etc. */ status = pj_mutex_create_recursive( endpt->pool, "ept%p", &endpt->mutex ); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } /* Create timer heap to manage all timers within this endpoint. */ status = pj_timer_heap_create( endpt->pool, PJSIP_MAX_TIMER_COUNT, &endpt->timer_heap); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } /* Set recursive lock for the timer heap. */ status = pj_lock_create_recursive_mutex( endpt->pool, "edpt%p", &lock); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } pj_timer_heap_set_lock(endpt->timer_heap, lock, PJ_TRUE); /* Set maximum timed out entries to process in a single poll. */ pj_timer_heap_set_max_timed_out_per_poll(endpt->timer_heap, - PJSIP_MAX_TIMED_OUT_ENTRIES); + PJSIP_MAX_TIMED_OUT_ENTRIES); /* Create ioqueue. */ status = pj_ioqueue_create( endpt->pool, PJSIP_MAX_TRANSPORTS, &endpt->ioqueue); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } /* Create transport manager. */ status = pjsip_tpmgr_create( endpt->pool, endpt, - &endpt_on_rx_msg, - &endpt_on_tx_msg, - &endpt->transport_mgr); + &endpt_on_rx_msg, + &endpt_on_tx_msg, + &endpt->transport_mgr); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } /* Create asynchronous DNS resolver. */ status = pjsip_resolver_create(endpt->pool, &endpt->resolver); if (status != PJ_SUCCESS) { - PJ_PERROR(4, (THIS_FILE, status, - "Error creating resolver instance")); - goto on_error; + PJ_PERROR(4, (THIS_FILE, status, + "Error creating resolver instance")); + goto on_error; } /* Initialize request headers. */ @@ -533,7 +532,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_create(pj_pool_factory *pf, /* Add "Max-Forwards" for request header. */ mf_hdr = pjsip_max_fwd_hdr_create(endpt->pool, - PJSIP_MAX_FORWARDS_VALUE); + PJSIP_MAX_FORWARDS_VALUE); pj_list_insert_before( &endpt->req_hdr, mf_hdr); /* Initialize capability header list. */ @@ -546,25 +545,25 @@ PJ_DEF(pj_status_t) pjsip_endpt_create(pj_pool_factory *pf, on_error: if (endpt->transport_mgr) { - pjsip_tpmgr_destroy(endpt->transport_mgr); - endpt->transport_mgr = NULL; + pjsip_tpmgr_destroy(endpt->transport_mgr); + endpt->transport_mgr = NULL; } if (endpt->ioqueue) { - pj_ioqueue_destroy(endpt->ioqueue); - endpt->ioqueue = NULL; + pj_ioqueue_destroy(endpt->ioqueue); + endpt->ioqueue = NULL; } if (endpt->timer_heap) { - pj_timer_heap_destroy(endpt->timer_heap); - endpt->timer_heap = NULL; + pj_timer_heap_destroy(endpt->timer_heap); + endpt->timer_heap = NULL; } if (endpt->mutex) { - pj_mutex_destroy(endpt->mutex); - endpt->mutex = NULL; + pj_mutex_destroy(endpt->mutex); + endpt->mutex = NULL; } deinit_sip_parser(); if (endpt->mod_mutex) { - pj_rwmutex_destroy(endpt->mod_mutex); - endpt->mod_mutex = NULL; + pj_rwmutex_destroy(endpt->mod_mutex); + endpt->mod_mutex = NULL; } pj_pool_release( endpt->pool ); @@ -585,19 +584,19 @@ PJ_DEF(void) pjsip_endpt_destroy(pjsip_endpoint *endpt) /* Phase 1: stop all modules */ mod = endpt->module_list.prev; while (mod != &endpt->module_list) { - pjsip_module *prev = mod->prev; - if (mod->stop) { - (*mod->stop)(); - } - mod = prev; + pjsip_module *prev = mod->prev; + if (mod->stop) { + (*mod->stop)(); + } + mod = prev; } /* Phase 2: unload modules. */ mod = endpt->module_list.prev; while (mod != &endpt->module_list) { - pjsip_module *prev = mod->prev; - unload_module(endpt, mod); - mod = prev; + pjsip_module *prev = mod->prev; + unload_module(endpt, mod); + mod = prev; } /* Destroy resolver */ @@ -618,8 +617,8 @@ PJ_DEF(void) pjsip_endpt_destroy(pjsip_endpoint *endpt) /* Call all registered exit callbacks */ ecb = endpt->exit_cb_list.next; while (ecb != &endpt->exit_cb_list) { - (*ecb->func)(endpt); - ecb = ecb->next; + (*ecb->func)(endpt); + ecb = ecb->next; } /* Delete endpoint mutex. */ @@ -650,9 +649,9 @@ PJ_DEF(const pj_str_t*) pjsip_endpt_name(const pjsip_endpoint *endpt) * Create new pool. */ PJ_DEF(pj_pool_t*) pjsip_endpt_create_pool( pjsip_endpoint *endpt, - const char *pool_name, - pj_size_t initial, - pj_size_t increment ) + const char *pool_name, + pj_size_t initial, + pj_size_t increment ) { pj_pool_t *pool; @@ -663,7 +662,7 @@ PJ_DEF(pj_pool_t*) pjsip_endpt_create_pool( pjsip_endpoint *endpt, /* Create pool */ pool = pj_pool_create( endpt->pf, pool_name, - initial, increment, &pool_callback); + initial, increment, &pool_callback); /* Unlock mutex. */ /* No need to lock mutex. Factory is thread safe. @@ -671,7 +670,7 @@ PJ_DEF(pj_pool_t*) pjsip_endpt_create_pool( pjsip_endpoint *endpt, */ if (!pool) { - PJ_LOG(4, (THIS_FILE, "Unable to create pool %s!", pool_name)); + PJ_LOG(4, (THIS_FILE, "Unable to create pool %s!", pool_name)); } return pool; @@ -698,8 +697,8 @@ PJ_DEF(void) pjsip_endpt_release_pool( pjsip_endpoint *endpt, pj_pool_t *pool ) PJ_DEF(pj_status_t) pjsip_endpt_handle_events2(pjsip_endpoint *endpt, - const pj_time_val *max_timeout, - unsigned *p_count) + const pj_time_val *max_timeout, + unsigned *p_count) { enum { MAX_TIMEOUT_ON_ERR = 10 }; /* timeout is 'out' var. This just to make compiler happy. */ @@ -715,7 +714,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_handle_events2(pjsip_endpoint *endpt, timeout.sec = timeout.msec = 0; c = pj_timer_heap_poll( endpt->timer_heap, &timeout ); if (c > 0) - count += c; + count += c; /* timer_heap_poll should never ever returns negative value, or otherwise * ioqueue_poll() will block forever! @@ -727,7 +726,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_handle_events2(pjsip_endpoint *endpt, * the timeout to wait from timer, and use the minimum value. */ if (max_timeout && PJ_TIME_VAL_GT(timeout, *max_timeout)) { - timeout = *max_timeout; + timeout = *max_timeout; } /* Poll ioqueue. @@ -742,28 +741,28 @@ PJ_DEF(pj_status_t) pjsip_endpt_handle_events2(pjsip_endpoint *endpt, * reported in timely manner. */ do { - c = pj_ioqueue_poll( endpt->ioqueue, &timeout); - if (c < 0) { - pj_status_t err = pj_get_netos_error(); + c = pj_ioqueue_poll( endpt->ioqueue, &timeout); + if (c < 0) { + pj_status_t err = pj_get_netos_error(); #if PJSIP_HANDLE_EVENTS_HAS_SLEEP_ON_ERR - unsigned msec = PJ_TIME_VAL_MSEC(timeout); - pj_thread_sleep(PJ_MIN(msec, MAX_TIMEOUT_ON_ERR)); + unsigned msec = PJ_TIME_VAL_MSEC(timeout); + pj_thread_sleep(PJ_MIN(msec, MAX_TIMEOUT_ON_ERR)); #endif - if (p_count) - *p_count = count; - return err; - } else if (c == 0) { - break; - } else { - net_event_count += c; - timeout.sec = timeout.msec = 0; - } + if (p_count) + *p_count = count; + return err; + } else if (c == 0) { + break; + } else { + net_event_count += c; + timeout.sec = timeout.msec = 0; + } } while (c > 0 && net_event_count < PJSIP_MAX_NET_EVENTS); count += net_event_count; if (p_count) - *p_count = count; + *p_count = count; return PJ_SUCCESS; } @@ -772,7 +771,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_handle_events2(pjsip_endpoint *endpt, * Handle events. */ PJ_DEF(pj_status_t) pjsip_endpt_handle_events(pjsip_endpoint *endpt, - const pj_time_val *max_timeout) + const pj_time_val *max_timeout) { return pjsip_endpt_handle_events2(endpt, max_timeout, NULL); } @@ -782,23 +781,23 @@ PJ_DEF(pj_status_t) pjsip_endpt_handle_events(pjsip_endpoint *endpt, */ #if PJ_TIMER_DEBUG PJ_DEF(pj_status_t) pjsip_endpt_schedule_timer_dbg(pjsip_endpoint *endpt, - pj_timer_entry *entry, - const pj_time_val *delay, - const char *src_file, - int src_line) + pj_timer_entry *entry, + const pj_time_val *delay, + const char *src_file, + int src_line) { PJ_LOG(6, (THIS_FILE, "pjsip_endpt_schedule_timer(entry=%p, delay=%u.%u)", - entry, delay->sec, delay->msec)); + entry, delay->sec, delay->msec)); return pj_timer_heap_schedule_dbg(endpt->timer_heap, entry, delay, src_file, src_line); } #else PJ_DEF(pj_status_t) pjsip_endpt_schedule_timer( pjsip_endpoint *endpt, - pj_timer_entry *entry, - const pj_time_val *delay ) + pj_timer_entry *entry, + const pj_time_val *delay ) { PJ_LOG(6, (THIS_FILE, "pjsip_endpt_schedule_timer(entry=%p, delay=%u.%u)", - entry, delay->sec, delay->msec)); + entry, delay->sec, delay->msec)); return pj_timer_heap_schedule( endpt->timer_heap, entry, delay ); } #endif @@ -808,34 +807,34 @@ PJ_DEF(pj_status_t) pjsip_endpt_schedule_timer( pjsip_endpoint *endpt, */ #if PJ_TIMER_DEBUG PJ_DEF(pj_status_t) pjsip_endpt_schedule_timer_w_grp_lock_dbg( - pjsip_endpoint *endpt, - pj_timer_entry *entry, - const pj_time_val *delay, - int id_val, - pj_grp_lock_t *grp_lock, - const char *src_file, - int src_line) + pjsip_endpoint *endpt, + pj_timer_entry *entry, + const pj_time_val *delay, + int id_val, + pj_grp_lock_t *grp_lock, + const char *src_file, + int src_line) { PJ_LOG(6, (THIS_FILE, "pjsip_endpt_schedule_timer_w_grp_lock" - "(entry=%p, delay=%u.%u, grp_lock=%p)", - entry, delay->sec, delay->msec, grp_lock)); + "(entry=%p, delay=%u.%u, grp_lock=%p)", + entry, delay->sec, delay->msec, grp_lock)); return pj_timer_heap_schedule_w_grp_lock_dbg(endpt->timer_heap, entry, - delay, id_val, grp_lock, - src_file, src_line); + delay, id_val, grp_lock, + src_file, src_line); } #else PJ_DEF(pj_status_t) pjsip_endpt_schedule_timer_w_grp_lock( - pjsip_endpoint *endpt, - pj_timer_entry *entry, - const pj_time_val *delay, - int id_val, - pj_grp_lock_t *grp_lock ) + pjsip_endpoint *endpt, + pj_timer_entry *entry, + const pj_time_val *delay, + int id_val, + pj_grp_lock_t *grp_lock ) { PJ_LOG(6, (THIS_FILE, "pjsip_endpt_schedule_timer_w_grp_lock" - "(entry=%p, delay=%u.%u, grp_lock=%p)", - entry, delay->sec, delay->msec, grp_lock)); + "(entry=%p, delay=%u.%u, grp_lock=%p)", + entry, delay->sec, delay->msec, grp_lock)); return pj_timer_heap_schedule_w_grp_lock( endpt->timer_heap, entry, - delay, id_val, grp_lock ); + delay, id_val, grp_lock ); } #endif @@ -843,7 +842,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_schedule_timer_w_grp_lock( * Cancel the previously registered timer. */ PJ_DEF(void) pjsip_endpt_cancel_timer( pjsip_endpoint *endpt, - pj_timer_entry *entry ) + pj_timer_entry *entry ) { PJ_LOG(6, (THIS_FILE, "pjsip_endpt_cancel_timer(entry=%p)", entry)); pj_timer_heap_cancel( endpt->timer_heap, entry ); @@ -879,78 +878,78 @@ PJ_DEF(pj_status_t) pjsip_endpt_process_rx_data( pjsip_endpoint *endpt, PJ_ASSERT_RETURN(endpt && rdata, PJ_EINVAL); if (p==NULL) { - p = &def_prm; - pjsip_process_rdata_param_default(p); + p = &def_prm; + pjsip_process_rdata_param_default(p); } msg = rdata->msg_info.msg; if (p_handled) - *p_handled = PJ_FALSE; + *p_handled = PJ_FALSE; if (!p->silent) { - PJ_LOG(5, (THIS_FILE, "Distributing rdata to modules: %s", - pjsip_rx_data_get_info(rdata))); - pj_log_push_indent(); + PJ_LOG(5, (THIS_FILE, "Distributing rdata to modules: %s", + pjsip_rx_data_get_info(rdata))); + pj_log_push_indent(); } LOCK_MODULE_ACCESS(endpt); /* Find start module */ if (p->start_mod) { - mod = (pjsip_module*) - pj_list_find_node(&endpt->module_list, p->start_mod); - if (!mod) { - status = PJ_ENOTFOUND; - goto on_return; - } + mod = (pjsip_module*) + pj_list_find_node(&endpt->module_list, p->start_mod); + if (!mod) { + status = PJ_ENOTFOUND; + goto on_return; + } } else { - mod = endpt->module_list.next; + mod = endpt->module_list.next; } /* Start after the specified index */ for (i=0; i < p->idx_after_start && mod != &endpt->module_list; ++i) { - mod = mod->next; + mod = mod->next; } /* Start with the specified priority */ while (mod != &endpt->module_list && mod->priority < (int)p->start_prio) { - mod = mod->next; + mod = mod->next; } if (mod == &endpt->module_list) { - status = PJ_ENOTFOUND; - goto on_return; + status = PJ_ENOTFOUND; + goto on_return; } /* Distribute */ if (msg->type == PJSIP_REQUEST_MSG) { - do { - if (mod->on_rx_request) - handled = (*mod->on_rx_request)(rdata); - if (handled) - break; - mod = mod->next; - } while (mod != &endpt->module_list); + do { + if (mod->on_rx_request) + handled = (*mod->on_rx_request)(rdata); + if (handled) + break; + mod = mod->next; + } while (mod != &endpt->module_list); } else { - do { - if (mod->on_rx_response) - handled = (*mod->on_rx_response)(rdata); - if (handled) - break; - mod = mod->next; - } while (mod != &endpt->module_list); + do { + if (mod->on_rx_response) + handled = (*mod->on_rx_response)(rdata); + if (handled) + break; + mod = mod->next; + } while (mod != &endpt->module_list); } status = PJ_SUCCESS; on_return: if (p_handled) - *p_handled = handled; + *p_handled = handled; UNLOCK_MODULE_ACCESS(endpt); if (!p->silent) { - pj_log_pop_indent(); + pj_log_pop_indent(); } return status; } @@ -960,8 +959,8 @@ PJ_DEF(pj_status_t) pjsip_endpt_process_rx_data( pjsip_endpoint *endpt, * receives a message from the network. */ static void endpt_on_rx_msg( pjsip_endpoint *endpt, - pj_status_t status, - pjsip_rx_data *rdata ) + pj_status_t status, + pjsip_rx_data *rdata ) { pjsip_msg *msg = rdata->msg_info.msg; pjsip_process_rdata_param proc_prm; @@ -970,48 +969,48 @@ static void endpt_on_rx_msg( pjsip_endpoint *endpt, PJ_UNUSED_ARG(msg); if (status != PJ_SUCCESS) { - char info[30]; - char errmsg[PJ_ERR_MSG_SIZE]; - - info[0] = '\0'; - - if (status == PJSIP_EMISSINGHDR) { - pj_str_t p; - - p.ptr = info; p.slen = 0; - - if (rdata->msg_info.cid == NULL || rdata->msg_info.cid->id.slen) - pj_strcpy2(&p, "Call-ID"); - if (rdata->msg_info.from == NULL) - pj_strcpy2(&p, " From"); - if (rdata->msg_info.to == NULL) - pj_strcpy2(&p, " To"); - if (rdata->msg_info.via == NULL) - pj_strcpy2(&p, " Via"); - if (rdata->msg_info.cseq == NULL) - pj_strcpy2(&p, " CSeq"); - - p.ptr[p.slen] = '\0'; - } - - pj_strerror(status, errmsg, sizeof(errmsg)); - - PJ_LOG(1, (THIS_FILE, - "Error processing packet from %s:%d: %s %s [code %d]:\n" - "%.*s\n" - "-- end of packet.", - rdata->pkt_info.src_name, - rdata->pkt_info.src_port, - errmsg, - info, - status, - (int)rdata->msg_info.len, - rdata->msg_info.msg_buf)); - return; + char info[30]; + char errmsg[PJ_ERR_MSG_SIZE]; + + info[0] = '\0'; + + if (status == PJSIP_EMISSINGHDR) { + pj_str_t p; + + p.ptr = info; p.slen = 0; + + if (rdata->msg_info.cid == NULL || rdata->msg_info.cid->id.slen) + pj_strcpy2(&p, "Call-ID"); + if (rdata->msg_info.from == NULL) + pj_strcpy2(&p, " From"); + if (rdata->msg_info.to == NULL) + pj_strcpy2(&p, " To"); + if (rdata->msg_info.via == NULL) + pj_strcpy2(&p, " Via"); + if (rdata->msg_info.cseq == NULL) + pj_strcpy2(&p, " CSeq"); + + p.ptr[p.slen] = '\0'; + } + + pj_strerror(status, errmsg, sizeof(errmsg)); + + PJ_LOG(1, (THIS_FILE, + "Error processing packet from %s:%d: %s %s [code %d]:\n" + "%.*s\n" + "-- end of packet.", + rdata->pkt_info.src_name, + rdata->pkt_info.src_port, + errmsg, + info, + status, + (int)rdata->msg_info.len, + rdata->msg_info.msg_buf)); + return; } PJ_LOG(5, (THIS_FILE, "Processing incoming message: %s", - pjsip_rx_data_get_info(rdata))); + pjsip_rx_data_get_info(rdata))); pj_log_push_indent(); #if defined(PJSIP_CHECK_VIA_SENT_BY) && PJSIP_CHECK_VIA_SENT_BY != 0 @@ -1020,57 +1019,57 @@ static void endpt_on_rx_msg( pjsip_endpoint *endpt, * Ref: RFC3261 Section 18.1.2 Receiving Response */ if (msg->type == PJSIP_RESPONSE_MSG) { - const pj_str_t *local_addr; - int port = rdata->msg_info.via->sent_by.port; - pj_bool_t mismatch = PJ_FALSE; - if (port == 0) { - pjsip_transport_type_e type; - type = (pjsip_transport_type_e)rdata->tp_info.transport->key.type; - port = pjsip_transport_get_default_port_for_type(type); - } - local_addr = &rdata->tp_info.transport->local_name.host; - - if (pj_strcmp(&rdata->msg_info.via->sent_by.host, local_addr) != 0) { - - /* The RFC says that we should drop response when sent-by - * address mismatch. But it could happen (e.g. with SER) when - * endpoint with private IP is sending request to public - * server. - - mismatch = PJ_TRUE; - - */ - - } else if (port != rdata->tp_info.transport->local_name.port) { - /* Port or address mismatch, we should discard response */ - /* But we saw one implementation (we don't want to name it to - * protect the innocence) which put wrong sent-by port although - * the "rport" parameter is correct. - * So we discard the response only if the port doesn't match - * both the port in sent-by and rport. We try to be lenient here! - */ - if (rdata->msg_info.via->rport_param != - rdata->tp_info.transport->local_name.port) - mismatch = PJ_TRUE; - else { - PJ_LOG(4,(THIS_FILE, "Message %s from %s has mismatch port in " - "sent-by but the rport parameter is " - "correct", - pjsip_rx_data_get_info(rdata), - rdata->pkt_info.src_name)); - } - } - - if (mismatch) { - PJ_TODO(ENDPT_REPORT_WHEN_DROPPING_MESSAGE); - PJ_LOG(4,(THIS_FILE, "Dropping response %s from %s:%d because " - "sent-by is mismatch", - pjsip_rx_data_get_info(rdata), - rdata->pkt_info.src_name, - rdata->pkt_info.src_port)); - pj_log_pop_indent(); - return; - } + const pj_str_t *local_addr; + int port = rdata->msg_info.via->sent_by.port; + pj_bool_t mismatch = PJ_FALSE; + if (port == 0) { + pjsip_transport_type_e type; + type = (pjsip_transport_type_e)rdata->tp_info.transport->key.type; + port = pjsip_transport_get_default_port_for_type(type); + } + local_addr = &rdata->tp_info.transport->local_name.host; + + if (pj_strcmp(&rdata->msg_info.via->sent_by.host, local_addr) != 0) { + + /* The RFC says that we should drop response when sent-by + * address mismatch. But it could happen (e.g. with SER) when + * endpoint with private IP is sending request to public + * server. + + mismatch = PJ_TRUE; + + */ + + } else if (port != rdata->tp_info.transport->local_name.port) { + /* Port or address mismatch, we should discard response */ + /* But we saw one implementation (we don't want to name it to + * protect the innocence) which put wrong sent-by port although + * the "rport" parameter is correct. + * So we discard the response only if the port doesn't match + * both the port in sent-by and rport. We try to be lenient here! + */ + if (rdata->msg_info.via->rport_param != + rdata->tp_info.transport->local_name.port) + mismatch = PJ_TRUE; + else { + PJ_LOG(4,(THIS_FILE, "Message %s from %s has mismatch port in " + "sent-by but the rport parameter is " + "correct", + pjsip_rx_data_get_info(rdata), + rdata->pkt_info.src_name)); + } + } + + if (mismatch) { + PJ_TODO(ENDPT_REPORT_WHEN_DROPPING_MESSAGE); + PJ_LOG(4,(THIS_FILE, "Dropping response %s from %s:%d because " + "sent-by is mismatch", + pjsip_rx_data_get_info(rdata), + rdata->pkt_info.src_name, + rdata->pkt_info.src_port)); + pj_log_pop_indent(); + return; + } } #endif @@ -1081,11 +1080,11 @@ static void endpt_on_rx_msg( pjsip_endpoint *endpt, /* No module is able to handle the message */ if (!handled) { - PJ_LOG(4,(THIS_FILE, "%s from %s:%d was dropped/unhandled by" - " any modules", - pjsip_rx_data_get_info(rdata), - rdata->pkt_info.src_name, - rdata->pkt_info.src_port)); + PJ_LOG(4,(THIS_FILE, "%s from %s:%d was dropped/unhandled by" + " any modules", + pjsip_rx_data_get_info(rdata), + rdata->pkt_info.src_name, + rdata->pkt_info.src_port)); } /* Must clear mod_data before returning rdata to transport, since @@ -1101,7 +1100,7 @@ static void endpt_on_rx_msg( pjsip_endpoint *endpt, * Modules may inspect the message before it's actually sent. */ static pj_status_t endpt_on_tx_msg( pjsip_endpoint *endpt, - pjsip_tx_data *tdata ) + pjsip_tx_data *tdata ) { pj_status_t status = PJ_SUCCESS; pjsip_module *mod; @@ -1111,22 +1110,22 @@ static pj_status_t endpt_on_tx_msg( pjsip_endpoint *endpt, mod = endpt->module_list.prev; if (tdata->msg->type == PJSIP_REQUEST_MSG) { - while (mod != &endpt->module_list) { - if (mod->on_tx_request) - status = (*mod->on_tx_request)(tdata); - if (status != PJ_SUCCESS) - break; - mod = mod->prev; - } + while (mod != &endpt->module_list) { + if (mod->on_tx_request) + status = (*mod->on_tx_request)(tdata); + if (status != PJ_SUCCESS) + break; + mod = mod->prev; + } } else { - while (mod != &endpt->module_list) { - if (mod->on_tx_response) - status = (*mod->on_tx_response)(tdata); - if (status != PJ_SUCCESS) - break; - mod = mod->prev; - } + while (mod != &endpt->module_list) { + if (mod->on_tx_response) + status = (*mod->on_tx_response)(tdata); + if (status != PJ_SUCCESS) + break; + mod = mod->prev; + } } UNLOCK_MODULE_ACCESS(endpt); @@ -1139,7 +1138,7 @@ static pj_status_t endpt_on_tx_msg( pjsip_endpoint *endpt, * Create transmit data buffer. */ PJ_DEF(pj_status_t) pjsip_endpt_create_tdata( pjsip_endpoint *endpt, - pjsip_tx_data **p_tdata) + pjsip_tx_data **p_tdata) { return pjsip_tx_data_create(endpt->transport_mgr, p_tdata); } @@ -1148,12 +1147,12 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_tdata( pjsip_endpoint *endpt, * Create the DNS resolver instance. */ PJ_DEF(pj_status_t) pjsip_endpt_create_resolver(pjsip_endpoint *endpt, - pj_dns_resolver **p_resv) + pj_dns_resolver **p_resv) { #if PJSIP_HAS_RESOLVER PJ_ASSERT_RETURN(endpt && p_resv, PJ_EINVAL); return pj_dns_resolver_create( endpt->pf, NULL, 0, endpt->timer_heap, - endpt->ioqueue, p_resv); + endpt->ioqueue, p_resv); #else PJ_UNUSED_ARG(endpt); PJ_UNUSED_ARG(p_resv); @@ -1166,7 +1165,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_resolver(pjsip_endpoint *endpt, * Set DNS resolver to be used by the SIP resolver. */ PJ_DEF(pj_status_t) pjsip_endpt_set_resolver( pjsip_endpoint *endpt, - pj_dns_resolver *resv) + pj_dns_resolver *resv) { return pjsip_resolver_set_resolver(endpt->resolver, resv); } @@ -1175,7 +1174,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_set_resolver( pjsip_endpoint *endpt, * Set DNS external resolver implementation to be used by the SIP resolver. */ PJ_DEF(pj_status_t) pjsip_endpt_set_ext_resolver(pjsip_endpoint *endpt, - pjsip_ext_resolver *ext_res) + pjsip_ext_resolver *ext_res) { return pjsip_resolver_set_ext_resolver(endpt->resolver, ext_res); } @@ -1193,10 +1192,10 @@ PJ_DEF(pj_dns_resolver*) pjsip_endpt_get_resolver(pjsip_endpoint *endpt) * Resolve */ PJ_DEF(void) pjsip_endpt_resolve( pjsip_endpoint *endpt, - pj_pool_t *pool, - pjsip_host_info *target, - void *token, - pjsip_resolver_callback *cb) + pj_pool_t *pool, + pjsip_host_info *target, + void *token, + pjsip_resolver_callback *cb) { pjsip_resolve( endpt->resolver, pool, target, token, cb); } @@ -1221,14 +1220,14 @@ PJ_DEF(pj_ioqueue_t*) pjsip_endpt_get_ioqueue(pjsip_endpoint *endpt) * Find/create transport. */ PJ_DEF(pj_status_t) pjsip_endpt_acquire_transport(pjsip_endpoint *endpt, - pjsip_transport_type_e type, - const pj_sockaddr_t *remote, - int addr_len, - const pjsip_tpselector *sel, - pjsip_transport **transport) + pjsip_transport_type_e type, + const pj_sockaddr_t *remote, + int addr_len, + const pjsip_tpselector *sel, + pjsip_transport **transport) { return pjsip_tpmgr_acquire_transport(endpt->transport_mgr, type, - remote, addr_len, sel, transport); + remote, addr_len, sel, transport); } @@ -1236,15 +1235,15 @@ PJ_DEF(pj_status_t) pjsip_endpt_acquire_transport(pjsip_endpoint *endpt, * Find/create transport. */ PJ_DEF(pj_status_t) pjsip_endpt_acquire_transport2(pjsip_endpoint *endpt, - pjsip_transport_type_e type, - const pj_sockaddr_t *remote, - int addr_len, - const pjsip_tpselector *sel, - pjsip_tx_data *tdata, - pjsip_transport **transport) + pjsip_transport_type_e type, + const pj_sockaddr_t *remote, + int addr_len, + const pjsip_tpselector *sel, + pjsip_tx_data *tdata, + pjsip_transport **transport) { return pjsip_tpmgr_acquire_transport2(endpt->transport_mgr, type, remote, - addr_len, sel, tdata, transport); + addr_len, sel, tdata, transport); } @@ -1252,7 +1251,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_acquire_transport2(pjsip_endpoint *endpt, * Report error. */ PJ_DEF(void) pjsip_endpt_log_error( pjsip_endpoint *endpt, - const char *sender, + const char *sender, pj_status_t error_code, const char *format, ... ) @@ -1268,22 +1267,22 @@ PJ_DEF(void) pjsip_endpt_log_error( pjsip_endpoint *endpt, len = pj_ansi_strlen(format); if (len < (int)sizeof(newformat)-30) { - pj_str_t errstr; + pj_str_t errstr; - pj_ansi_strcpy(newformat, format); - pj_ansi_snprintf(newformat+len, sizeof(newformat)-len-1, - ": [err %d] ", error_code); - len += pj_ansi_strlen(newformat+len); + pj_ansi_strcpy(newformat, format); + pj_ansi_snprintf(newformat+len, sizeof(newformat)-len-1, + ": [err %d] ", error_code); + len += pj_ansi_strlen(newformat+len); - errstr = pj_strerror( error_code, newformat+len, - sizeof(newformat)-len-1); + errstr = pj_strerror( error_code, newformat+len, + sizeof(newformat)-len-1); - len += errstr.slen; - newformat[len] = '\0'; + len += errstr.slen; + newformat[len] = '\0'; - pj_log(sender, 1, newformat, marker); + pj_log(sender, 1, newformat, marker); } else { - pj_log(sender, 1, format, marker); + pj_log(sender, 1, format, marker); } va_end(marker); @@ -1314,13 +1313,13 @@ PJ_DEF(void) pjsip_endpt_dump( pjsip_endpoint *endpt, pj_bool_t detail ) /* Pool health. */ PJ_LOG(3, (THIS_FILE," Endpoint pool capacity=%u, used_size=%u", - pj_pool_get_capacity(endpt->pool), - pj_pool_get_used_size(endpt->pool))); + pj_pool_get_capacity(endpt->pool), + pj_pool_get_used_size(endpt->pool))); /* Resolver */ #if PJSIP_HAS_RESOLVER if (pjsip_endpt_get_resolver(endpt)) { - pj_dns_resolver_dump(pjsip_endpt_get_resolver(endpt), detail); + pj_dns_resolver_dump(pjsip_endpt_get_resolver(endpt), detail); } #endif @@ -1333,7 +1332,7 @@ PJ_DEF(void) pjsip_endpt_dump( pjsip_endpoint *endpt, pj_bool_t detail ) pj_timer_heap_dump(endpt->timer_heap); #else PJ_LOG(3,(THIS_FILE, " Timer heap has %u entries", - pj_timer_heap_count(endpt->timer_heap))); + pj_timer_heap_count(endpt->timer_heap))); #endif /* Unlock mutex. */ @@ -1347,7 +1346,7 @@ PJ_DEF(void) pjsip_endpt_dump( pjsip_endpoint *endpt, pj_bool_t detail ) PJ_DEF(pj_status_t) pjsip_endpt_atexit( pjsip_endpoint *endpt, - pjsip_endpt_exit_callback func) + pjsip_endpt_exit_callback func) { exit_cb *new_cb; diff --git a/pjsip/src/pjsip/sip_endpoint_wrap.cpp b/pjsip/src/pjsip/sip_endpoint_wrap.cpp index 0170f6f3df..38a9b6990a 100644 --- a/pjsip/src/pjsip/sip_endpoint_wrap.cpp +++ b/pjsip/src/pjsip/sip_endpoint_wrap.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjsip/src/pjsip/sip_errno.c b/pjsip/src/pjsip/sip_errno.c index 449f65c3c9..6ea09c7eeb 100644 --- a/pjsip/src/pjsip/sip_errno.c +++ b/pjsip/src/pjsip/sip_errno.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,82 +34,82 @@ static const struct } err_str[] = { /* Generic SIP errors */ - PJ_BUILD_ERR( PJSIP_EBUSY, "Object is busy" ), - PJ_BUILD_ERR( PJSIP_ETYPEEXISTS , "Object with the same type exists" ), - PJ_BUILD_ERR( PJSIP_ESHUTDOWN, "SIP stack shutting down" ), + PJ_BUILD_ERR( PJSIP_EBUSY, "Object is busy" ), + PJ_BUILD_ERR( PJSIP_ETYPEEXISTS , "Object with the same type exists" ), + PJ_BUILD_ERR( PJSIP_ESHUTDOWN, "SIP stack shutting down" ), PJ_BUILD_ERR( PJSIP_ENOTINITIALIZED,"SIP object is not initialized." ), - PJ_BUILD_ERR( PJSIP_ENOROUTESET, "Missing route set (for tel: URI)" ), + PJ_BUILD_ERR( PJSIP_ENOROUTESET, "Missing route set (for tel: URI)" ), /* Messaging errors */ - PJ_BUILD_ERR( PJSIP_EINVALIDMSG, "Invalid message/syntax error" ), - PJ_BUILD_ERR( PJSIP_ENOTREQUESTMSG, "Expecting request message"), + PJ_BUILD_ERR( PJSIP_EINVALIDMSG, "Invalid message/syntax error" ), + PJ_BUILD_ERR( PJSIP_ENOTREQUESTMSG, "Expecting request message"), PJ_BUILD_ERR( PJSIP_ENOTRESPONSEMSG,"Expecting response message"), - PJ_BUILD_ERR( PJSIP_EMSGTOOLONG, "Message too long" ), - PJ_BUILD_ERR( PJSIP_EPARTIALMSG, "Partial message" ), + PJ_BUILD_ERR( PJSIP_EMSGTOOLONG, "Message too long" ), + PJ_BUILD_ERR( PJSIP_EPARTIALMSG, "Partial message" ), - PJ_BUILD_ERR( PJSIP_EINVALIDSTATUS, "Invalid/unexpected SIP status code"), + PJ_BUILD_ERR( PJSIP_EINVALIDSTATUS, "Invalid/unexpected SIP status code"), - PJ_BUILD_ERR( PJSIP_EINVALIDURI, "Invalid URI" ), - PJ_BUILD_ERR( PJSIP_EINVALIDSCHEME, "Invalid URI scheme" ), - PJ_BUILD_ERR( PJSIP_EMISSINGREQURI, "Missing Request-URI" ), - PJ_BUILD_ERR( PJSIP_EINVALIDREQURI, "Invalid Request URI" ), - PJ_BUILD_ERR( PJSIP_EURITOOLONG, "URI is too long" ), + PJ_BUILD_ERR( PJSIP_EINVALIDURI, "Invalid URI" ), + PJ_BUILD_ERR( PJSIP_EINVALIDSCHEME, "Invalid URI scheme" ), + PJ_BUILD_ERR( PJSIP_EMISSINGREQURI, "Missing Request-URI" ), + PJ_BUILD_ERR( PJSIP_EINVALIDREQURI, "Invalid Request URI" ), + PJ_BUILD_ERR( PJSIP_EURITOOLONG, "URI is too long" ), - PJ_BUILD_ERR( PJSIP_EMISSINGHDR, "Missing required header(s)" ), - PJ_BUILD_ERR( PJSIP_EINVALIDHDR, "Invalid header field"), - PJ_BUILD_ERR( PJSIP_EINVALIDVIA, "Invalid Via header" ), - PJ_BUILD_ERR( PJSIP_EMULTIPLEVIA, "Multiple Via headers in response" ), + PJ_BUILD_ERR( PJSIP_EMISSINGHDR, "Missing required header(s)" ), + PJ_BUILD_ERR( PJSIP_EINVALIDHDR, "Invalid header field"), + PJ_BUILD_ERR( PJSIP_EINVALIDVIA, "Invalid Via header" ), + PJ_BUILD_ERR( PJSIP_EMULTIPLEVIA, "Multiple Via headers in response" ), - PJ_BUILD_ERR( PJSIP_EMISSINGBODY, "Missing message body" ), - PJ_BUILD_ERR( PJSIP_EINVALIDMETHOD, "Invalid/unexpected method" ), + PJ_BUILD_ERR( PJSIP_EMISSINGBODY, "Missing message body" ), + PJ_BUILD_ERR( PJSIP_EINVALIDMETHOD, "Invalid/unexpected method" ), /* Transport errors */ PJ_BUILD_ERR( PJSIP_EUNSUPTRANSPORT,"Unsupported transport"), - PJ_BUILD_ERR( PJSIP_EPENDINGTX, "Transmit buffer already pending"), - PJ_BUILD_ERR( PJSIP_ERXOVERFLOW, "Rx buffer overflow"), - PJ_BUILD_ERR( PJSIP_EBUFDESTROYED, "Buffer destroyed"), - PJ_BUILD_ERR( PJSIP_ETPNOTSUITABLE, "Unsuitable transport selected"), - PJ_BUILD_ERR( PJSIP_ETPNOTAVAIL, "Transport not available for use"), + PJ_BUILD_ERR( PJSIP_EPENDINGTX, "Transmit buffer already pending"), + PJ_BUILD_ERR( PJSIP_ERXOVERFLOW, "Rx buffer overflow"), + PJ_BUILD_ERR( PJSIP_EBUFDESTROYED, "Buffer destroyed"), + PJ_BUILD_ERR( PJSIP_ETPNOTSUITABLE, "Unsuitable transport selected"), + PJ_BUILD_ERR( PJSIP_ETPNOTAVAIL, "Transport not available for use"), /* Transaction errors */ - PJ_BUILD_ERR( PJSIP_ETSXDESTROYED, "Transaction has been destroyed"), - PJ_BUILD_ERR( PJSIP_ENOTSX, "No transaction is associated with the object " - "(expecting stateful processing)" ), + PJ_BUILD_ERR( PJSIP_ETSXDESTROYED, "Transaction has been destroyed"), + PJ_BUILD_ERR( PJSIP_ENOTSX, "No transaction is associated with the object " + "(expecting stateful processing)" ), /* URI comparison status */ - PJ_BUILD_ERR( PJSIP_ECMPSCHEME, "URI scheme mismatch" ), - PJ_BUILD_ERR( PJSIP_ECMPUSER, "URI user part mismatch" ), - PJ_BUILD_ERR( PJSIP_ECMPPASSWD, "URI password part mismatch" ), - PJ_BUILD_ERR( PJSIP_ECMPHOST, "URI host part mismatch" ), - PJ_BUILD_ERR( PJSIP_ECMPPORT, "URI port mismatch" ), + PJ_BUILD_ERR( PJSIP_ECMPSCHEME, "URI scheme mismatch" ), + PJ_BUILD_ERR( PJSIP_ECMPUSER, "URI user part mismatch" ), + PJ_BUILD_ERR( PJSIP_ECMPPASSWD, "URI password part mismatch" ), + PJ_BUILD_ERR( PJSIP_ECMPHOST, "URI host part mismatch" ), + PJ_BUILD_ERR( PJSIP_ECMPPORT, "URI port mismatch" ), PJ_BUILD_ERR( PJSIP_ECMPTRANSPORTPRM,"URI transport param mismatch" ), - PJ_BUILD_ERR( PJSIP_ECMPTTLPARAM, "URI ttl param mismatch" ), - PJ_BUILD_ERR( PJSIP_ECMPUSERPARAM, "URI user param mismatch" ), + PJ_BUILD_ERR( PJSIP_ECMPTTLPARAM, "URI ttl param mismatch" ), + PJ_BUILD_ERR( PJSIP_ECMPUSERPARAM, "URI user param mismatch" ), PJ_BUILD_ERR( PJSIP_ECMPMETHODPARAM,"URI method param mismatch" ), - PJ_BUILD_ERR( PJSIP_ECMPMADDRPARAM, "URI maddr param mismatch" ), - PJ_BUILD_ERR( PJSIP_ECMPOTHERPARAM, "URI other param mismatch" ), + PJ_BUILD_ERR( PJSIP_ECMPMADDRPARAM, "URI maddr param mismatch" ), + PJ_BUILD_ERR( PJSIP_ECMPOTHERPARAM, "URI other param mismatch" ), PJ_BUILD_ERR( PJSIP_ECMPHEADERPARAM,"URI header parameter mismatch" ), /* Authentication. */ PJ_BUILD_ERR( PJSIP_EFAILEDCREDENTIAL, "Credential failed to authenticate"), - PJ_BUILD_ERR( PJSIP_ENOCREDENTIAL, "No suitable credential"), + PJ_BUILD_ERR( PJSIP_ENOCREDENTIAL, "No suitable credential"), PJ_BUILD_ERR( PJSIP_EINVALIDALGORITHM, "Invalid/unsupported digest algorithm" ), - PJ_BUILD_ERR( PJSIP_EINVALIDQOP, "Invalid/unsupported digest qop" ), + PJ_BUILD_ERR( PJSIP_EINVALIDQOP, "Invalid/unsupported digest qop" ), PJ_BUILD_ERR( PJSIP_EINVALIDAUTHSCHEME,"Unsupported authentication scheme" ), PJ_BUILD_ERR( PJSIP_EAUTHNOPREVCHAL, "No previous challenge" ), - PJ_BUILD_ERR( PJSIP_EAUTHNOAUTH, "No suitable authorization header" ), + PJ_BUILD_ERR( PJSIP_EAUTHNOAUTH, "No suitable authorization header" ), PJ_BUILD_ERR( PJSIP_EAUTHACCNOTFOUND, "Account or credential not found" ), PJ_BUILD_ERR( PJSIP_EAUTHACCDISABLED, "Account or credential is disabled" ), PJ_BUILD_ERR( PJSIP_EAUTHINVALIDREALM, "Invalid authorization realm"), PJ_BUILD_ERR( PJSIP_EAUTHINVALIDDIGEST,"Invalid authorization digest" ), PJ_BUILD_ERR( PJSIP_EAUTHSTALECOUNT, "Maximum number of stale retries exceeded"), - PJ_BUILD_ERR( PJSIP_EAUTHINNONCE, "Invalid nonce value in authentication challenge"), - PJ_BUILD_ERR( PJSIP_EAUTHINAKACRED, "Invalid AKA credential"), - PJ_BUILD_ERR( PJSIP_EAUTHNOCHAL, "No challenge is found"), + PJ_BUILD_ERR( PJSIP_EAUTHINNONCE, "Invalid nonce value in authentication challenge"), + PJ_BUILD_ERR( PJSIP_EAUTHINAKACRED, "Invalid AKA credential"), + PJ_BUILD_ERR( PJSIP_EAUTHNOCHAL, "No challenge is found"), /* UA/dialog layer. */ - PJ_BUILD_ERR( PJSIP_EMISSINGTAG, "Missing From/To tag parameter" ), - PJ_BUILD_ERR( PJSIP_ENOTREFER, "Expecting REFER request") , + PJ_BUILD_ERR( PJSIP_EMISSINGTAG, "Missing From/To tag parameter" ), + PJ_BUILD_ERR( PJSIP_ENOTREFER, "Expecting REFER request") , PJ_BUILD_ERR( PJSIP_ENOREFERSESSION,"Not associated with REFER subscription"), /* Invite session. */ @@ -119,31 +118,31 @@ static const struct PJ_BUILD_ERR( PJSIP_ESESSIONINSECURE, "Require secure session/transport"), /* SSL errors */ - PJ_BUILD_ERR( PJSIP_TLS_EUNKNOWN, "Unknown TLS error" ), - PJ_BUILD_ERR( PJSIP_TLS_EINVMETHOD, "Invalid SSL protocol method" ), - PJ_BUILD_ERR( PJSIP_TLS_ECACERT, "Error loading/verifying SSL CA list file"), - PJ_BUILD_ERR( PJSIP_TLS_ECERTFILE, "Error loading SSL certificate chain file"), - PJ_BUILD_ERR( PJSIP_TLS_EKEYFILE, "Error adding private key from SSL certificate file"), - PJ_BUILD_ERR( PJSIP_TLS_ECIPHER, "Error setting SSL cipher list"), - PJ_BUILD_ERR( PJSIP_TLS_ECTX, "Error creating SSL context"), - PJ_BUILD_ERR( PJSIP_TLS_ESSLCONN, "Error creating SSL connection object"), - PJ_BUILD_ERR( PJSIP_TLS_ECONNECT, "Unknown error when performing SSL connect()"), - PJ_BUILD_ERR( PJSIP_TLS_EACCEPT, "Unknown error when performing SSL accept()"), - PJ_BUILD_ERR( PJSIP_TLS_ESEND, "Unknown error when sending SSL data"), - PJ_BUILD_ERR( PJSIP_TLS_EREAD, "Unknown error when reading SSL data"), - PJ_BUILD_ERR( PJSIP_TLS_ETIMEDOUT, "SSL negotiation has timed out"), - PJ_BUILD_ERR( PJSIP_TLS_ECERTVERIF, "SSL certificate verification error"), + PJ_BUILD_ERR( PJSIP_TLS_EUNKNOWN, "Unknown TLS error" ), + PJ_BUILD_ERR( PJSIP_TLS_EINVMETHOD, "Invalid SSL protocol method" ), + PJ_BUILD_ERR( PJSIP_TLS_ECACERT, "Error loading/verifying SSL CA list file"), + PJ_BUILD_ERR( PJSIP_TLS_ECERTFILE, "Error loading SSL certificate chain file"), + PJ_BUILD_ERR( PJSIP_TLS_EKEYFILE, "Error adding private key from SSL certificate file"), + PJ_BUILD_ERR( PJSIP_TLS_ECIPHER, "Error setting SSL cipher list"), + PJ_BUILD_ERR( PJSIP_TLS_ECTX, "Error creating SSL context"), + PJ_BUILD_ERR( PJSIP_TLS_ESSLCONN, "Error creating SSL connection object"), + PJ_BUILD_ERR( PJSIP_TLS_ECONNECT, "Unknown error when performing SSL connect()"), + PJ_BUILD_ERR( PJSIP_TLS_EACCEPT, "Unknown error when performing SSL accept()"), + PJ_BUILD_ERR( PJSIP_TLS_ESEND, "Unknown error when sending SSL data"), + PJ_BUILD_ERR( PJSIP_TLS_EREAD, "Unknown error when reading SSL data"), + PJ_BUILD_ERR( PJSIP_TLS_ETIMEDOUT, "SSL negotiation has timed out"), + PJ_BUILD_ERR( PJSIP_TLS_ECERTVERIF, "SSL certificate verification error"), }; -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ /* * pjsip_strerror() */ PJ_DEF(pj_str_t) pjsip_strerror( pj_status_t statcode, - char *buf, pj_size_t bufsize ) + char *buf, pj_size_t bufsize ) { pj_str_t errstr; @@ -151,61 +150,61 @@ PJ_DEF(pj_str_t) pjsip_strerror( pj_status_t statcode, if (statcode >= PJSIP_ERRNO_START && statcode < PJSIP_ERRNO_START+800) { - /* Status code. */ - const pj_str_t *status_text = - pjsip_get_status_text(PJSIP_ERRNO_TO_SIP_STATUS(statcode)); + /* Status code. */ + const pj_str_t *status_text = + pjsip_get_status_text(PJSIP_ERRNO_TO_SIP_STATUS(statcode)); - errstr.ptr = buf; - pj_strncpy_with_null(&errstr, status_text, bufsize); - return errstr; + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, status_text, bufsize); + return errstr; } else if (statcode >= PJSIP_ERRNO_START_PJSIP && - statcode < PJSIP_ERRNO_START_PJSIP + 1000) + statcode < PJSIP_ERRNO_START_PJSIP + 1000) { - /* Find the error in the table. - * Use binary search! - */ - int first = 0; - int n = PJ_ARRAY_SIZE(err_str); - - while (n > 0) { - int half = n/2; - int mid = first + half; - - if (err_str[mid].code < statcode) { - first = mid+1; - n -= (half+1); - } else if (err_str[mid].code > statcode) { - n = half; - } else { - first = mid; - break; - } - } - - - if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { - pj_str_t msg; - - msg.ptr = (char*)err_str[first].msg; - msg.slen = pj_ansi_strlen(err_str[first].msg); - - errstr.ptr = buf; - pj_strncpy_with_null(&errstr, &msg, bufsize); - return errstr; - - } + /* Find the error in the table. + * Use binary search! + */ + int first = 0; + int n = PJ_ARRAY_SIZE(err_str); + + while (n > 0) { + int half = n/2; + int mid = first + half; + + if (err_str[mid].code < statcode) { + first = mid+1; + n -= (half+1); + } else if (err_str[mid].code > statcode) { + n = half; + } else { + first = mid; + break; + } + } + + + if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { + pj_str_t msg; + + msg.ptr = (char*)err_str[first].msg; + msg.slen = pj_ansi_strlen(err_str[first].msg); + + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, &msg, bufsize); + return errstr; + + } } -#endif /* PJ_HAS_ERROR_STRING */ +#endif /* PJ_HAS_ERROR_STRING */ /* Error not found. */ errstr.ptr = buf; errstr.slen = pj_ansi_snprintf(buf, bufsize, - "Unknown pjsip error %d", - statcode); + "Unknown pjsip error %d", + statcode); if (errstr.slen < 1 || errstr.slen >= (pj_ssize_t)bufsize) - errstr.slen = bufsize - 1; + errstr.slen = bufsize - 1; return errstr; } diff --git a/pjsip/src/pjsip/sip_msg.c b/pjsip/src/pjsip/sip_msg.c index 1ca3b58d69..c375ca9b1a 100644 --- a/pjsip/src/pjsip/sip_msg.c +++ b/pjsip/src/pjsip/sip_msg.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,22 +29,22 @@ #include PJ_DEF_DATA(const pjsip_method) pjsip_invite_method = - { PJSIP_INVITE_METHOD, { "INVITE",6 }}; + { PJSIP_INVITE_METHOD, { "INVITE",6 }}; PJ_DEF_DATA(const pjsip_method) pjsip_cancel_method = - { PJSIP_CANCEL_METHOD, { "CANCEL",6 }}; + { PJSIP_CANCEL_METHOD, { "CANCEL",6 }}; PJ_DEF_DATA(const pjsip_method) pjsip_ack_method = - { PJSIP_ACK_METHOD, { "ACK",3}}; + { PJSIP_ACK_METHOD, { "ACK",3}}; PJ_DEF_DATA(const pjsip_method) pjsip_bye_method = - { PJSIP_BYE_METHOD, { "BYE",3}}; + { PJSIP_BYE_METHOD, { "BYE",3}}; PJ_DEF_DATA(const pjsip_method) pjsip_register_method = - { PJSIP_REGISTER_METHOD, { "REGISTER", 8}}; + { PJSIP_REGISTER_METHOD, { "REGISTER", 8}}; PJ_DEF_DATA(const pjsip_method) pjsip_options_method = - { PJSIP_OPTIONS_METHOD, { "OPTIONS",7}}; + { PJSIP_OPTIONS_METHOD, { "OPTIONS",7}}; /** INVITE method constant. */ @@ -97,49 +96,49 @@ static const pj_str_t *method_names[] = const pjsip_hdr_name_info_t pjsip_hdr_names[] = { - { "Accept", 6, NULL }, // PJSIP_H_ACCEPT, + { "Accept", 6, NULL }, // PJSIP_H_ACCEPT, { "Accept-Encoding", 15, NULL }, // PJSIP_H_ACCEPT_ENCODING, { "Accept-Language", 15, NULL }, // PJSIP_H_ACCEPT_LANGUAGE, - { "Alert-Info", 10, NULL }, // PJSIP_H_ALERT_INFO, - { "Allow", 5, NULL }, // PJSIP_H_ALLOW, + { "Alert-Info", 10, NULL }, // PJSIP_H_ALERT_INFO, + { "Allow", 5, NULL }, // PJSIP_H_ALLOW, { "Authentication-Info",19, NULL }, // PJSIP_H_AUTHENTICATION_INFO, - { "Authorization", 13, NULL }, // PJSIP_H_AUTHORIZATION, - { "Call-ID", 7, "i" }, // PJSIP_H_CALL_ID, - { "Call-Info", 9, NULL }, // PJSIP_H_CALL_INFO, - { "Contact", 7, "m" }, // PJSIP_H_CONTACT, + { "Authorization", 13, NULL }, // PJSIP_H_AUTHORIZATION, + { "Call-ID", 7, "i" }, // PJSIP_H_CALL_ID, + { "Call-Info", 9, NULL }, // PJSIP_H_CALL_INFO, + { "Contact", 7, "m" }, // PJSIP_H_CONTACT, { "Content-Disposition",19, NULL }, // PJSIP_H_CONTENT_DISPOSITION, { "Content-Encoding", 16, "e" }, // PJSIP_H_CONTENT_ENCODING, { "Content-Language", 16, NULL }, // PJSIP_H_CONTENT_LANGUAGE, - { "Content-Length", 14, "l" }, // PJSIP_H_CONTENT_LENGTH, - { "Content-Type", 12, "c" }, // PJSIP_H_CONTENT_TYPE, - { "CSeq", 4, NULL }, // PJSIP_H_CSEQ, - { "Date", 4, NULL }, // PJSIP_H_DATE, - { "Error-Info", 10, NULL }, // PJSIP_H_ERROR_INFO, - { "Expires", 7, NULL }, // PJSIP_H_EXPIRES, - { "From", 4, "f" }, // PJSIP_H_FROM, - { "In-Reply-To", 11, NULL }, // PJSIP_H_IN_REPLY_TO, - { "Max-Forwards", 12, NULL }, // PJSIP_H_MAX_FORWARDS, - { "MIME-Version", 12, NULL }, // PJSIP_H_MIME_VERSION, - { "Min-Expires", 11, NULL }, // PJSIP_H_MIN_EXPIRES, - { "Organization", 12, NULL }, // PJSIP_H_ORGANIZATION, - { "Priority", 8, NULL }, // PJSIP_H_PRIORITY, + { "Content-Length", 14, "l" }, // PJSIP_H_CONTENT_LENGTH, + { "Content-Type", 12, "c" }, // PJSIP_H_CONTENT_TYPE, + { "CSeq", 4, NULL }, // PJSIP_H_CSEQ, + { "Date", 4, NULL }, // PJSIP_H_DATE, + { "Error-Info", 10, NULL }, // PJSIP_H_ERROR_INFO, + { "Expires", 7, NULL }, // PJSIP_H_EXPIRES, + { "From", 4, "f" }, // PJSIP_H_FROM, + { "In-Reply-To", 11, NULL }, // PJSIP_H_IN_REPLY_TO, + { "Max-Forwards", 12, NULL }, // PJSIP_H_MAX_FORWARDS, + { "MIME-Version", 12, NULL }, // PJSIP_H_MIME_VERSION, + { "Min-Expires", 11, NULL }, // PJSIP_H_MIN_EXPIRES, + { "Organization", 12, NULL }, // PJSIP_H_ORGANIZATION, + { "Priority", 8, NULL }, // PJSIP_H_PRIORITY, { "Proxy-Authenticate", 18, NULL }, // PJSIP_H_PROXY_AUTHENTICATE, { "Proxy-Authorization",19, NULL }, // PJSIP_H_PROXY_AUTHORIZATION, - { "Proxy-Require", 13, NULL }, // PJSIP_H_PROXY_REQUIRE, - { "Record-Route", 12, NULL }, // PJSIP_H_RECORD_ROUTE, - { "Reply-To", 8, NULL }, // PJSIP_H_REPLY_TO, - { "Require", 7, NULL }, // PJSIP_H_REQUIRE, - { "Retry-After", 11, NULL }, // PJSIP_H_RETRY_AFTER, - { "Route", 5, NULL }, // PJSIP_H_ROUTE, - { "Server", 6, NULL }, // PJSIP_H_SERVER, - { "Subject", 7, "s" }, // PJSIP_H_SUBJECT, - { "Supported", 9, "k" }, // PJSIP_H_SUPPORTED, - { "Timestamp", 9, NULL }, // PJSIP_H_TIMESTAMP, - { "To", 2, "t" }, // PJSIP_H_TO, - { "Unsupported", 11, NULL }, // PJSIP_H_UNSUPPORTED, - { "User-Agent", 10, NULL }, // PJSIP_H_USER_AGENT, - { "Via", 3, "v" }, // PJSIP_H_VIA, - { "Warning", 7, NULL }, // PJSIP_H_WARNING, + { "Proxy-Require", 13, NULL }, // PJSIP_H_PROXY_REQUIRE, + { "Record-Route", 12, NULL }, // PJSIP_H_RECORD_ROUTE, + { "Reply-To", 8, NULL }, // PJSIP_H_REPLY_TO, + { "Require", 7, NULL }, // PJSIP_H_REQUIRE, + { "Retry-After", 11, NULL }, // PJSIP_H_RETRY_AFTER, + { "Route", 5, NULL }, // PJSIP_H_ROUTE, + { "Server", 6, NULL }, // PJSIP_H_SERVER, + { "Subject", 7, "s" }, // PJSIP_H_SUBJECT, + { "Supported", 9, "k" }, // PJSIP_H_SUPPORTED, + { "Timestamp", 9, NULL }, // PJSIP_H_TIMESTAMP, + { "To", 2, "t" }, // PJSIP_H_TO, + { "Unsupported", 11, NULL }, // PJSIP_H_UNSUPPORTED, + { "User-Agent", 10, NULL }, // PJSIP_H_USER_AGENT, + { "Via", 3, "v" }, // PJSIP_H_VIA, + { "Warning", 7, NULL }, // PJSIP_H_WARNING, { "WWW-Authenticate", 16, NULL }, // PJSIP_H_WWW_AUTHENTICATE, { "_Unknown-Header", 15, NULL }, // PJSIP_H_OTHER, @@ -147,7 +146,7 @@ const pjsip_hdr_name_info_t pjsip_hdr_names[] = static pj_str_t status_phrase[710]; static int print_media_type(char *buf, unsigned len, - const pjsip_media_type *media); + const pjsip_media_type *media); static int init_status_phrase() { @@ -155,7 +154,7 @@ static int init_status_phrase() pj_str_t default_reason_phrase = { "Default status message", 22}; for (i=0; iid = (pjsip_method_e)i; - m->name = *method_names[i]; - return; - } + if (pj_memcmp(str, method_names[i], sizeof(pj_str_t))==0 || + pj_stricmp(str, method_names[i])==0) + { + m->id = (pjsip_method_e)i; + m->name = *method_names[i]; + return; + } } m->id = PJSIP_OTHER_METHOD; m->name = *str; } PJ_DEF(void) pjsip_method_copy( pj_pool_t *pool, - pjsip_method *method, - const pjsip_method *rhs ) + pjsip_method *method, + const pjsip_method *rhs ) { method->id = rhs->id; if (rhs->id != PJSIP_OTHER_METHOD) { - method->name = rhs->name; + method->name = rhs->name; } else { - pj_strdup(pool, &method->name, &rhs->name); + pj_strdup(pool, &method->name, &rhs->name); } } @@ -300,10 +299,10 @@ PJ_DEF(void) pjsip_method_copy( pj_pool_t *pool, PJ_DEF(int) pjsip_method_cmp( const pjsip_method *m1, const pjsip_method *m2) { if (m1->id == m2->id) { - if (m1->id != PJSIP_OTHER_METHOD) - return 0; - /* Method comparison is case sensitive! */ - return pj_strcmp(&m1->name, &m2->name); + if (m1->id != PJSIP_OTHER_METHOD) + return 0; + /* Method comparison is case sensitive! */ + return pj_strcmp(&m1->name, &m2->name); } return ( m1->id < m2->id ) ? -1 : 1; @@ -332,113 +331,113 @@ PJ_DEF(pjsip_msg*) pjsip_msg_clone( pj_pool_t *pool, const pjsip_msg *src) /* Clone request/status line */ if (src->type == PJSIP_REQUEST_MSG) { - pjsip_method_copy(pool, &dst->line.req.method, &src->line.req.method); - dst->line.req.uri = (pjsip_uri*) pjsip_uri_clone(pool, - src->line.req.uri); + pjsip_method_copy(pool, &dst->line.req.method, &src->line.req.method); + dst->line.req.uri = (pjsip_uri*) pjsip_uri_clone(pool, + src->line.req.uri); } else { - dst->line.status.code = src->line.status.code; - pj_strdup(pool, &dst->line.status.reason, &src->line.status.reason); + dst->line.status.code = src->line.status.code; + pj_strdup(pool, &dst->line.status.reason, &src->line.status.reason); } /* Clone headers */ sh = src->hdr.next; while (sh != &src->hdr) { - pjsip_hdr *dh = (pjsip_hdr*) pjsip_hdr_clone(pool, sh); - pjsip_msg_add_hdr(dst, dh); - sh = sh->next; + pjsip_hdr *dh = (pjsip_hdr*) pjsip_hdr_clone(pool, sh); + pjsip_msg_add_hdr(dst, dh); + sh = sh->next; } /* Clone message body */ if (src->body) { - dst->body = pjsip_msg_body_clone(pool, src->body); + dst->body = pjsip_msg_body_clone(pool, src->body); } return dst; } PJ_DEF(void*) pjsip_hdr_find( const void *hdr_list, - pjsip_hdr_e hdr_type, const void *start) + pjsip_hdr_e hdr_type, const void *start) { const pjsip_hdr *hdr=(const pjsip_hdr*) start, *end=hdr_list; if (hdr == NULL) { - hdr = end->next; + hdr = end->next; } for (; hdr!=end; hdr = hdr->next) { - if (hdr->type == hdr_type) - return (void*)hdr; + if (hdr->type == hdr_type) + return (void*)hdr; } return NULL; } PJ_DEF(void*) pjsip_hdr_find_by_name( const void *hdr_list, - const pj_str_t *name, - const void *start) + const pj_str_t *name, + const void *start) { const pjsip_hdr *hdr=(const pjsip_hdr*) start, *end=hdr_list; if (hdr == NULL) { - hdr = end->next; + hdr = end->next; } for (; hdr!=end; hdr = hdr->next) { - if (pj_stricmp(&hdr->name, name) == 0) - return (void*)hdr; + if (pj_stricmp(&hdr->name, name) == 0) + return (void*)hdr; } return NULL; } PJ_DEF(void*) pjsip_hdr_find_by_names( const void *hdr_list, - const pj_str_t *name, - const pj_str_t *sname, - const void *start) + const pj_str_t *name, + const pj_str_t *sname, + const void *start) { const pjsip_hdr *hdr=(const pjsip_hdr*) start, *end=hdr_list; if (hdr == NULL) { - hdr = end->next; + hdr = end->next; } for (; hdr!=end; hdr = hdr->next) { - if (pj_stricmp(&hdr->name, name) == 0) - return (void*)hdr; - if (pj_stricmp(&hdr->name, sname) == 0) - return (void*)hdr; + if (pj_stricmp(&hdr->name, name) == 0) + return (void*)hdr; + if (pj_stricmp(&hdr->name, sname) == 0) + return (void*)hdr; } return NULL; } PJ_DEF(void*) pjsip_msg_find_hdr( const pjsip_msg *msg, - pjsip_hdr_e hdr_type, const void *start) + pjsip_hdr_e hdr_type, const void *start) { return pjsip_hdr_find(&msg->hdr, hdr_type, start); } PJ_DEF(void*) pjsip_msg_find_hdr_by_name( const pjsip_msg *msg, - const pj_str_t *name, - const void *start) + const pj_str_t *name, + const void *start) { return pjsip_hdr_find_by_name(&msg->hdr, name, start); } PJ_DEF(void*) pjsip_msg_find_hdr_by_names( const pjsip_msg *msg, - const pj_str_t *name, - const pj_str_t *sname, - const void *start) + const pj_str_t *name, + const pj_str_t *sname, + const void *start) { return pjsip_hdr_find_by_names(&msg->hdr, name, sname, start); } PJ_DEF(void*) pjsip_msg_find_remove_hdr( pjsip_msg *msg, - pjsip_hdr_e hdr_type, void *start) + pjsip_hdr_e hdr_type, void *start) { pjsip_hdr *hdr = (pjsip_hdr*) pjsip_msg_find_hdr(msg, hdr_type, start); if (hdr) { - pj_list_erase(hdr); + pj_list_erase(hdr); } return hdr; } PJ_DEF(pj_ssize_t) pjsip_msg_print( const pjsip_msg *msg, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { char *p=buf, *end=buf+size; pj_ssize_t len; @@ -446,162 +445,162 @@ PJ_DEF(pj_ssize_t) pjsip_msg_print( const pjsip_msg *msg, pj_str_t clen_hdr = { "Content-Length: ", 16}; if (pjsip_cfg()->endpt.use_compact_form) { - clen_hdr.ptr = "l: "; - clen_hdr.slen = 3; + clen_hdr.ptr = "l: "; + clen_hdr.slen = 3; } /* Get a wild guess on how many bytes are typically needed. * We'll check this later in detail, but this serves as a quick check. */ if (size < 256) - return -1; + return -1; /* Print request line or status line depending on message type */ if (msg->type == PJSIP_REQUEST_MSG) { - pjsip_uri *uri; - - /* Add method. */ - len = msg->line.req.method.name.slen; - pj_memcpy(p, msg->line.req.method.name.ptr, len); - p += len; - *p++ = ' '; - - /* Add URI */ - uri = (pjsip_uri*) pjsip_uri_get_uri(msg->line.req.uri); - len = pjsip_uri_print( PJSIP_URI_IN_REQ_URI, uri, p, end-p); - if (len < 1) - return -1; - p += len; - - /* Add ' SIP/2.0' */ - if (end-p < 16) - return -1; - pj_memcpy(p, " SIP/2.0\r\n", 10); - p += 10; + pjsip_uri *uri; + + /* Add method. */ + len = msg->line.req.method.name.slen; + pj_memcpy(p, msg->line.req.method.name.ptr, len); + p += len; + *p++ = ' '; + + /* Add URI */ + uri = (pjsip_uri*) pjsip_uri_get_uri(msg->line.req.uri); + len = pjsip_uri_print( PJSIP_URI_IN_REQ_URI, uri, p, end-p); + if (len < 1) + return -1; + p += len; + + /* Add ' SIP/2.0' */ + if (end-p < 16) + return -1; + pj_memcpy(p, " SIP/2.0\r\n", 10); + p += 10; } else { - /* Add 'SIP/2.0 ' */ - pj_memcpy(p, "SIP/2.0 ", 8); - p += 8; + /* Add 'SIP/2.0 ' */ + pj_memcpy(p, "SIP/2.0 ", 8); + p += 8; - /* Add status code. */ - len = pj_utoa(msg->line.status.code, p); - p += len; - *p++ = ' '; + /* Add status code. */ + len = pj_utoa(msg->line.status.code, p); + p += len; + *p++ = ' '; - /* Add reason text. */ - len = msg->line.status.reason.slen; - pj_memcpy(p, msg->line.status.reason.ptr, len ); - p += len; + /* Add reason text. */ + len = msg->line.status.reason.slen; + pj_memcpy(p, msg->line.status.reason.ptr, len ); + p += len; - /* Add newline. */ - *p++ = '\r'; - *p++ = '\n'; + /* Add newline. */ + *p++ = '\r'; + *p++ = '\n'; } /* Print each of the headers. */ for (hdr=msg->hdr.next; hdr!=&msg->hdr; hdr=hdr->next) { - len = pjsip_hdr_print_on(hdr, p, end-p); - if (len < 0) { - if (len == -2) { - PJ_LOG(5, ("sip_msg", "Header with no vptr encountered!! "\ - "Current buffer: %.*s", (int)(p-buf), buf)); - } - return len; - } - - if (len > 0) { - p += len; - if (p+3 >= end) - return -1; - - *p++ = '\r'; - *p++ = '\n'; - } + len = pjsip_hdr_print_on(hdr, p, end-p); + if (len < 0) { + if (len == -2) { + PJ_LOG(5, ("sip_msg", "Header with no vptr encountered!! "\ + "Current buffer: %.*s", (int)(p-buf), buf)); + } + return len; + } + + if (len > 0) { + p += len; + if (p+3 >= end) + return -1; + + *p++ = '\r'; + *p++ = '\n'; + } } /* Process message body. */ if (msg->body) { - enum { CLEN_SPACE = 5 }; - char *clen_pos = NULL; - - /* Automaticly adds Content-Type and Content-Length headers, only - * if content_type is set in the message body. - */ - if (msg->body->content_type.type.slen) { - pj_str_t ctype_hdr = { "Content-Type: ", 14}; - const pjsip_media_type *media = &msg->body->content_type; - - if (pjsip_cfg()->endpt.use_compact_form) { - ctype_hdr.ptr = "c: "; - ctype_hdr.slen = 3; - } - - /* Add Content-Type header. */ - if ( (end-p) < 24 + media->type.slen + media->subtype.slen) { - return -1; - } - pj_memcpy(p, ctype_hdr.ptr, ctype_hdr.slen); - p += ctype_hdr.slen; - p += print_media_type(p, (unsigned)(end-p), media); - *p++ = '\r'; - *p++ = '\n'; - - /* Add Content-Length header. */ - if ((end-p) < clen_hdr.slen + 12 + 2) { - return -1; - } - pj_memcpy(p, clen_hdr.ptr, clen_hdr.slen); - p += clen_hdr.slen; - - /* Print blanks after "Content-Length:", this is where we'll put - * the content length value after we know the length of the - * body. - */ - pj_memset(p, ' ', CLEN_SPACE); - clen_pos = p; - p += CLEN_SPACE; - *p++ = '\r'; - *p++ = '\n'; - } - - /* Add blank newline. */ - *p++ = '\r'; - *p++ = '\n'; - - /* Print the message body itself. */ - len = (*msg->body->print_body)(msg->body, p, end-p); - if (len < 0) { - return -1; - } - p += len; - - /* Now that we have the length of the body, print this to the - * Content-Length header. - */ - if (clen_pos) { - char tmp[16]; - len = pj_utoa((unsigned long)len, tmp); - if (len > CLEN_SPACE) len = CLEN_SPACE; - pj_memcpy(clen_pos+CLEN_SPACE-len, tmp, len); - } + enum { CLEN_SPACE = 5 }; + char *clen_pos = NULL; + + /* Automaticly adds Content-Type and Content-Length headers, only + * if content_type is set in the message body. + */ + if (msg->body->content_type.type.slen) { + pj_str_t ctype_hdr = { "Content-Type: ", 14}; + const pjsip_media_type *media = &msg->body->content_type; + + if (pjsip_cfg()->endpt.use_compact_form) { + ctype_hdr.ptr = "c: "; + ctype_hdr.slen = 3; + } + + /* Add Content-Type header. */ + if ( (end-p) < 24 + media->type.slen + media->subtype.slen) { + return -1; + } + pj_memcpy(p, ctype_hdr.ptr, ctype_hdr.slen); + p += ctype_hdr.slen; + p += print_media_type(p, (unsigned)(end-p), media); + *p++ = '\r'; + *p++ = '\n'; + + /* Add Content-Length header. */ + if ((end-p) < clen_hdr.slen + 12 + 2) { + return -1; + } + pj_memcpy(p, clen_hdr.ptr, clen_hdr.slen); + p += clen_hdr.slen; + + /* Print blanks after "Content-Length:", this is where we'll put + * the content length value after we know the length of the + * body. + */ + pj_memset(p, ' ', CLEN_SPACE); + clen_pos = p; + p += CLEN_SPACE; + *p++ = '\r'; + *p++ = '\n'; + } + + /* Add blank newline. */ + *p++ = '\r'; + *p++ = '\n'; + + /* Print the message body itself. */ + len = (*msg->body->print_body)(msg->body, p, end-p); + if (len < 0) { + return -1; + } + p += len; + + /* Now that we have the length of the body, print this to the + * Content-Length header. + */ + if (clen_pos) { + char tmp[16]; + len = pj_utoa((unsigned long)len, tmp); + if (len > CLEN_SPACE) len = CLEN_SPACE; + pj_memcpy(clen_pos+CLEN_SPACE-len, tmp, len); + } } else { - /* There's no message body. - * Add Content-Length with zero value. - */ - if ((end-p) < clen_hdr.slen+8) { - return -1; - } - pj_memcpy(p, clen_hdr.ptr, clen_hdr.slen); - p += clen_hdr.slen; - *p++ = ' '; - *p++ = '0'; - *p++ = '\r'; - *p++ = '\n'; - *p++ = '\r'; - *p++ = '\n'; + /* There's no message body. + * Add Content-Length with zero value. + */ + if ((end-p) < clen_hdr.slen+8) { + return -1; + } + pj_memcpy(p, clen_hdr.ptr, clen_hdr.slen); + p += clen_hdr.slen; + *p++ = ' '; + *p++ = '0'; + *p++ = '\r'; + *p++ = '\n'; + *p++ = '\r'; + *p++ = '\n'; } *p = '\0'; @@ -638,13 +637,13 @@ PJ_DEF(const pj_str_t*) pjsip_get_status_text(int code) { static int is_initialized; if (is_initialized == 0) { - is_initialized = 1; - init_status_phrase(); + is_initialized = 1; + init_status_phrase(); } return (code>=100 && - code<(int)(sizeof(status_phrase)/sizeof(status_phrase[0]))) ? - &status_phrase[code] : &status_phrase[0]; + code<(int)(sizeof(status_phrase)/sizeof(status_phrase[0]))) ? + &status_phrase[code] : &status_phrase[0]; } /////////////////////////////////////////////////////////////////////////////// @@ -655,35 +654,35 @@ PJ_DEF(const pj_str_t*) pjsip_get_status_text(int code) * Init media type. */ PJ_DEF(void) pjsip_media_type_init( pjsip_media_type *mt, - pj_str_t *type, - pj_str_t *subtype) + pj_str_t *type, + pj_str_t *subtype) { pj_bzero(mt, sizeof(*mt)); pj_list_init(&mt->param); if (type) - mt->type = *type; + mt->type = *type; if (subtype) - mt->subtype = *subtype; + mt->subtype = *subtype; } PJ_DEF(void) pjsip_media_type_init2( pjsip_media_type *mt, - char *type, - char *subtype) + char *type, + char *subtype) { pj_str_t s_type, s_subtype; if (type) { - s_type = pj_str(type); + s_type = pj_str(type); } else { - s_type.ptr = NULL; - s_type.slen = 0; + s_type.ptr = NULL; + s_type.slen = 0; } if (subtype) { - s_subtype = pj_str(subtype); + s_subtype = pj_str(subtype); } else { - s_subtype.ptr = NULL; - s_subtype.slen = 0; + s_subtype.ptr = NULL; + s_subtype.slen = 0; } pjsip_media_type_init(mt, &s_type, &s_subtype); @@ -693,8 +692,8 @@ PJ_DEF(void) pjsip_media_type_init2( pjsip_media_type *mt, * Compare two media types. */ PJ_DEF(int) pjsip_media_type_cmp( const pjsip_media_type *mt1, - const pjsip_media_type *mt2, - pj_bool_t cmp_param) + const pjsip_media_type *mt2, + pj_bool_t cmp_param) { int rc; @@ -707,15 +706,15 @@ PJ_DEF(int) pjsip_media_type_cmp( const pjsip_media_type *mt1, if (rc) return rc; if (cmp_param) { - rc = pjsip_param_cmp(&mt1->param, &mt2->param, (cmp_param==1)); + rc = pjsip_param_cmp(&mt1->param, &mt2->param, (cmp_param==1)); } return rc; } PJ_DEF(void) pjsip_media_type_cp( pj_pool_t *pool, - pjsip_media_type *dst, - const pjsip_media_type *src) + pjsip_media_type *dst, + const pjsip_media_type *src) { PJ_ASSERT_ON_FAIL(pool && dst && src, return); pj_strdup(pool, &dst->type, &src->type); @@ -729,11 +728,11 @@ PJ_DEF(void) pjsip_media_type_cp( pj_pool_t *pool, */ static int pjsip_generic_string_hdr_print( pjsip_generic_string_hdr *hdr, - char *buf, pj_size_t size); + char *buf, pj_size_t size); static pjsip_generic_string_hdr* pjsip_generic_string_hdr_clone( pj_pool_t *pool, - const pjsip_generic_string_hdr *hdr); + const pjsip_generic_string_hdr *hdr); static pjsip_generic_string_hdr* pjsip_generic_string_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_generic_string_hdr *hdr ); + const pjsip_generic_string_hdr *hdr ); static pjsip_hdr_vptr generic_hdr_vptr = { @@ -744,41 +743,41 @@ static pjsip_hdr_vptr generic_hdr_vptr = PJ_DEF(void) pjsip_generic_string_hdr_init2(pjsip_generic_string_hdr *hdr, - pj_str_t *hname, - pj_str_t *hvalue) + pj_str_t *hname, + pj_str_t *hvalue) { init_hdr(hdr, PJSIP_H_OTHER, &generic_hdr_vptr); if (hname) { - hdr->name = *hname; - hdr->sname = *hname; + hdr->name = *hname; + hdr->sname = *hname; } if (hvalue) { - hdr->hvalue = *hvalue; + hdr->hvalue = *hvalue; } else { - hdr->hvalue.ptr = NULL; - hdr->hvalue.slen = 0; + hdr->hvalue.ptr = NULL; + hdr->hvalue.slen = 0; } } PJ_DEF(pjsip_generic_string_hdr*) pjsip_generic_string_hdr_init(pj_pool_t *pool, - void *mem, - const pj_str_t *hnames, - const pj_str_t *hvalue) + void *mem, + const pj_str_t *hnames, + const pj_str_t *hvalue) { pjsip_generic_string_hdr *hdr = (pjsip_generic_string_hdr*) mem; pj_str_t dup_hname, dup_hval; if (hnames) { - pj_strdup(pool, &dup_hname, hnames); + pj_strdup(pool, &dup_hname, hnames); } else { - dup_hname.slen = 0; + dup_hname.slen = 0; } if (hvalue) { - pj_strdup(pool, &dup_hval, hvalue); + pj_strdup(pool, &dup_hval, hvalue); } else { - dup_hval.slen = 0; + dup_hval.slen = 0; } pjsip_generic_string_hdr_init2(hdr, &dup_hname, &dup_hval); @@ -786,22 +785,22 @@ PJ_DEF(pjsip_generic_string_hdr*) pjsip_generic_string_hdr_init(pj_pool_t *pool, } PJ_DEF(pjsip_generic_string_hdr*) pjsip_generic_string_hdr_create(pj_pool_t *pool, - const pj_str_t *hnames, - const pj_str_t *hvalue) + const pj_str_t *hnames, + const pj_str_t *hvalue) { void *mem = pj_pool_alloc(pool, sizeof(pjsip_generic_string_hdr)); return pjsip_generic_string_hdr_init(pool, mem, hnames, hvalue); } static int pjsip_generic_string_hdr_print( pjsip_generic_string_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { char *p = buf; const pj_str_t *hname = pjsip_cfg()->endpt.use_compact_form? - &hdr->sname : &hdr->name; + &hdr->sname : &hdr->name; if ((pj_ssize_t)size < hname->slen + hdr->hvalue.slen + 5) - return -1; + return -1; pj_memcpy(p, hname->ptr, hname->slen); p += hname->slen; @@ -815,7 +814,7 @@ static int pjsip_generic_string_hdr_print( pjsip_generic_string_hdr *hdr, } static pjsip_generic_string_hdr* pjsip_generic_string_hdr_clone( pj_pool_t *pool, - const pjsip_generic_string_hdr *rhs) + const pjsip_generic_string_hdr *rhs) { pjsip_generic_string_hdr *hdr; @@ -827,7 +826,7 @@ static pjsip_generic_string_hdr* pjsip_generic_string_hdr_clone( pj_pool_t *pool } static pjsip_generic_string_hdr* pjsip_generic_string_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_generic_string_hdr *rhs ) + const pjsip_generic_string_hdr *rhs ) { pjsip_generic_string_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_generic_string_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -840,11 +839,11 @@ static pjsip_generic_string_hdr* pjsip_generic_string_hdr_shallow_clone( pj_pool */ static int pjsip_generic_int_hdr_print( pjsip_generic_int_hdr *hdr, - char *buf, pj_size_t size); + char *buf, pj_size_t size); static pjsip_generic_int_hdr* pjsip_generic_int_hdr_clone( pj_pool_t *pool, - const pjsip_generic_int_hdr *hdr); + const pjsip_generic_int_hdr *hdr); static pjsip_generic_int_hdr* pjsip_generic_int_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_generic_int_hdr *hdr ); + const pjsip_generic_int_hdr *hdr ); static pjsip_hdr_vptr generic_int_hdr_vptr = { @@ -854,38 +853,38 @@ static pjsip_hdr_vptr generic_int_hdr_vptr = }; PJ_DEF(pjsip_generic_int_hdr*) pjsip_generic_int_hdr_init( pj_pool_t *pool, - void *mem, - const pj_str_t *hnames, - unsigned value) + void *mem, + const pj_str_t *hnames, + unsigned value) { pjsip_generic_int_hdr *hdr = (pjsip_generic_int_hdr*) mem; init_hdr(hdr, PJSIP_H_OTHER, &generic_int_hdr_vptr); if (hnames) { - pj_strdup(pool, &hdr->name, hnames); - hdr->sname = hdr->name; + pj_strdup(pool, &hdr->name, hnames); + hdr->sname = hdr->name; } hdr->ivalue = value; return hdr; } PJ_DEF(pjsip_generic_int_hdr*) pjsip_generic_int_hdr_create( pj_pool_t *pool, - const pj_str_t *hnames, - unsigned value) + const pj_str_t *hnames, + unsigned value) { void *mem = pj_pool_alloc(pool, sizeof(pjsip_generic_int_hdr)); return pjsip_generic_int_hdr_init(pool, mem, hnames, value); } static int pjsip_generic_int_hdr_print( pjsip_generic_int_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { char *p = buf; const pj_str_t *hname = pjsip_cfg()->endpt.use_compact_form? - &hdr->sname : &hdr->name; + &hdr->sname : &hdr->name; if ((pj_ssize_t)size < hname->slen + 15) - return -1; + return -1; pj_memcpy(p, hname->ptr, hname->slen); p += hname->slen; @@ -898,7 +897,7 @@ static int pjsip_generic_int_hdr_print( pjsip_generic_int_hdr *hdr, } static pjsip_generic_int_hdr* pjsip_generic_int_hdr_clone( pj_pool_t *pool, - const pjsip_generic_int_hdr *rhs) + const pjsip_generic_int_hdr *rhs) { pjsip_generic_int_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_generic_int_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -906,7 +905,7 @@ static pjsip_generic_int_hdr* pjsip_generic_int_hdr_clone( pj_pool_t *pool, } static pjsip_generic_int_hdr* pjsip_generic_int_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_generic_int_hdr *rhs ) + const pjsip_generic_int_hdr *rhs ) { pjsip_generic_int_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_generic_int_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -919,9 +918,9 @@ static pjsip_generic_int_hdr* pjsip_generic_int_hdr_shallow_clone( pj_pool_t *po */ static int pjsip_generic_array_hdr_print( pjsip_generic_array_hdr *hdr, char *buf, pj_size_t size); static pjsip_generic_array_hdr* pjsip_generic_array_hdr_clone( pj_pool_t *pool, - const pjsip_generic_array_hdr *hdr); + const pjsip_generic_array_hdr *hdr); static pjsip_generic_array_hdr* pjsip_generic_array_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_generic_array_hdr *hdr); + const pjsip_generic_array_hdr *hdr); static pjsip_hdr_vptr generic_array_hdr_vptr = { @@ -932,22 +931,22 @@ static pjsip_hdr_vptr generic_array_hdr_vptr = PJ_DEF(pjsip_generic_array_hdr*) pjsip_generic_array_hdr_init( pj_pool_t *pool, - void *mem, - const pj_str_t *hnames) + void *mem, + const pj_str_t *hnames) { pjsip_generic_array_hdr *hdr = (pjsip_generic_array_hdr*) mem; init_hdr(hdr, PJSIP_H_OTHER, &generic_array_hdr_vptr); if (hnames) { - pj_strdup(pool, &hdr->name, hnames); - hdr->sname = hdr->name; + pj_strdup(pool, &hdr->name, hnames); + hdr->sname = hdr->name; } hdr->count = 0; return hdr; } PJ_DEF(pjsip_generic_array_hdr*) pjsip_generic_array_hdr_create( pj_pool_t *pool, - const pj_str_t *hnames) + const pj_str_t *hnames) { void *mem = pj_pool_alloc(pool, sizeof(pjsip_generic_array_hdr)); return pjsip_generic_array_hdr_init(pool, mem, hnames); @@ -955,37 +954,37 @@ PJ_DEF(pjsip_generic_array_hdr*) pjsip_generic_array_hdr_create( pj_pool_t *pool } static int pjsip_generic_array_hdr_print( pjsip_generic_array_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { char *p = buf, *endbuf = buf+size; const pj_str_t *hname = pjsip_cfg()->endpt.use_compact_form? - &hdr->sname : &hdr->name; + &hdr->sname : &hdr->name; copy_advance(p, (*hname)); *p++ = ':'; *p++ = ' '; if (hdr->count > 0) { - unsigned i; - int printed; - copy_advance(p, hdr->values[0]); - for (i=1; icount; ++i) { - copy_advance_pair(p, ", ", 2, hdr->values[i]); - } + unsigned i; + int printed; + copy_advance(p, hdr->values[0]); + for (i=1; icount; ++i) { + copy_advance_pair(p, ", ", 2, hdr->values[i]); + } } return (int)(p - buf); } static pjsip_generic_array_hdr* pjsip_generic_array_hdr_clone( pj_pool_t *pool, - const pjsip_generic_array_hdr *rhs) + const pjsip_generic_array_hdr *rhs) { unsigned i; pjsip_generic_array_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_generic_array_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); for (i=0; icount; ++i) { - pj_strdup(pool, &hdr->values[i], &rhs->values[i]); + pj_strdup(pool, &hdr->values[i], &rhs->values[i]); } return hdr; @@ -993,7 +992,7 @@ static pjsip_generic_array_hdr* pjsip_generic_array_hdr_clone( pj_pool_t *pool, static pjsip_generic_array_hdr* pjsip_generic_array_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_generic_array_hdr *rhs) + const pjsip_generic_array_hdr *rhs) { pjsip_generic_array_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_generic_array_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -1005,7 +1004,7 @@ static pjsip_generic_array_hdr* pjsip_generic_array_hdr_shallow_clone( pj_pool_t * Accept header. */ PJ_DEF(pjsip_accept_hdr*) pjsip_accept_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_accept_hdr *hdr = (pjsip_accept_hdr*) mem; @@ -1029,7 +1028,7 @@ PJ_DEF(pjsip_accept_hdr*) pjsip_accept_hdr_create(pj_pool_t *pool) */ PJ_DEF(pjsip_allow_hdr*) pjsip_allow_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_allow_hdr *hdr = (pjsip_allow_hdr*) mem; @@ -1052,7 +1051,7 @@ PJ_DEF(pjsip_allow_hdr*) pjsip_allow_hdr_create(pj_pool_t *pool) */ PJ_DEF(pjsip_cid_hdr*) pjsip_cid_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_cid_hdr *hdr = (pjsip_cid_hdr*) mem; @@ -1086,7 +1085,7 @@ static pjsip_hdr_vptr clen_hdr_vptr = }; PJ_DEF(pjsip_clen_hdr*) pjsip_clen_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_clen_hdr *hdr = (pjsip_clen_hdr*) mem; @@ -1104,15 +1103,15 @@ PJ_DEF(pjsip_clen_hdr*) pjsip_clen_hdr_create( pj_pool_t *pool ) } static int pjsip_clen_hdr_print( pjsip_clen_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { char *p = buf; int len; const pj_str_t *hname = pjsip_cfg()->endpt.use_compact_form? - &hdr->sname : &hdr->name; + &hdr->sname : &hdr->name; if ((pj_ssize_t)size < hname->slen + 14) - return -1; + return -1; pj_memcpy(p, hname->ptr, hname->slen); p += hname->slen; @@ -1150,7 +1149,7 @@ static pjsip_hdr_vptr cseq_hdr_vptr = }; PJ_DEF(pjsip_cseq_hdr*) pjsip_cseq_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_cseq_hdr *hdr = (pjsip_cseq_hdr*) mem; @@ -1177,7 +1176,7 @@ static int pjsip_cseq_hdr_print( pjsip_cseq_hdr *hdr, char *buf, pj_size_t size) /* CSeq doesn't have compact form */ if ((pj_ssize_t)size < hdr->name.slen + hdr->method.name.slen + 15) - return -1; + return -1; pj_memcpy(p, hdr->name.ptr, hdr->name.slen); p += hdr->name.slen; @@ -1197,7 +1196,7 @@ static int pjsip_cseq_hdr_print( pjsip_cseq_hdr *hdr, char *buf, pj_size_t size) } static pjsip_cseq_hdr* pjsip_cseq_hdr_clone( pj_pool_t *pool, - const pjsip_cseq_hdr *rhs) + const pjsip_cseq_hdr *rhs) { pjsip_cseq_hdr *hdr = pjsip_cseq_hdr_create(pool); hdr->cseq = rhs->cseq; @@ -1206,7 +1205,7 @@ static pjsip_cseq_hdr* pjsip_cseq_hdr_clone( pj_pool_t *pool, } static pjsip_cseq_hdr* pjsip_cseq_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_cseq_hdr *rhs ) + const pjsip_cseq_hdr *rhs ) { pjsip_cseq_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_cseq_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -1230,7 +1229,7 @@ static pjsip_hdr_vptr contact_hdr_vptr = }; PJ_DEF(pjsip_contact_hdr*) pjsip_contact_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_contact_hdr *hdr = (pjsip_contact_hdr*) mem; @@ -1250,91 +1249,91 @@ PJ_DEF(pjsip_contact_hdr*) pjsip_contact_hdr_create( pj_pool_t *pool ) } static int pjsip_contact_hdr_print( pjsip_contact_hdr *hdr, char *buf, - pj_size_t size) + pj_size_t size) { const pj_str_t *hname = pjsip_cfg()->endpt.use_compact_form? - &hdr->sname : &hdr->name; + &hdr->sname : &hdr->name; const pjsip_parser_const_t *pc = pjsip_parser_const(); if (hdr->star) { - char *p = buf; - if ((pj_ssize_t)size < hname->slen + 6) - return -1; - pj_memcpy(p, hname->ptr, hname->slen); - p += hname->slen; - *p++ = ':'; - *p++ = ' '; - *p++ = '*'; - return (int)(p - buf); + char *p = buf; + if ((pj_ssize_t)size < hname->slen + 6) + return -1; + pj_memcpy(p, hname->ptr, hname->slen); + p += hname->slen; + *p++ = ':'; + *p++ = ' '; + *p++ = '*'; + return (int)(p - buf); } else { - int printed; - char *startbuf = buf; - char *endbuf = buf + size; - - copy_advance(buf, (*hname)); - copy_advance_char_check(buf, ':'); - copy_advance_char_check(buf, ' '); - - printed = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, hdr->uri, - buf, endbuf-buf); - if (printed < 1) - return -1; - - buf += printed; - - if (hdr->q1000) { - unsigned frac; - - if (buf+19 >= endbuf) - return -1; - - /* - printed = sprintf(buf, ";q=%u.%03u", - hdr->q1000/1000, hdr->q1000 % 1000); - */ - pj_memcpy(buf, ";q=", 3); - printed = pj_utoa(hdr->q1000/1000, buf+3); - buf += printed + 3; - frac = hdr->q1000 % 1000; - if (frac != 0) { - *buf++ = '.'; - if ((frac % 100)==0) frac /= 100; - if ((frac % 10)==0) frac /= 10; - printed = pj_utoa(frac, buf); - buf += printed; - } - } - - if (hdr->expires != PJSIP_EXPIRES_NOT_SPECIFIED) { - if (buf+23 >= endbuf) - return -1; - - pj_memcpy(buf, ";expires=", 9); - printed = pj_utoa(hdr->expires, buf+9); - buf += printed + 9; - } - - printed = (int)pjsip_param_print_on(&hdr->other_param, buf, endbuf-buf, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, - ';'); - if (printed < 0) - return printed; - buf += printed; - - return (int)(buf-startbuf); + int printed; + char *startbuf = buf; + char *endbuf = buf + size; + + copy_advance(buf, (*hname)); + copy_advance_char_check(buf, ':'); + copy_advance_char_check(buf, ' '); + + printed = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, hdr->uri, + buf, endbuf-buf); + if (printed < 1) + return -1; + + buf += printed; + + if (hdr->q1000) { + unsigned frac; + + if (buf+19 >= endbuf) + return -1; + + /* + printed = sprintf(buf, ";q=%u.%03u", + hdr->q1000/1000, hdr->q1000 % 1000); + */ + pj_memcpy(buf, ";q=", 3); + printed = pj_utoa(hdr->q1000/1000, buf+3); + buf += printed + 3; + frac = hdr->q1000 % 1000; + if (frac != 0) { + *buf++ = '.'; + if ((frac % 100)==0) frac /= 100; + if ((frac % 10)==0) frac /= 10; + printed = pj_utoa(frac, buf); + buf += printed; + } + } + + if (hdr->expires != PJSIP_EXPIRES_NOT_SPECIFIED) { + if (buf+23 >= endbuf) + return -1; + + pj_memcpy(buf, ";expires=", 9); + printed = pj_utoa(hdr->expires, buf+9); + buf += printed + 9; + } + + printed = (int)pjsip_param_print_on(&hdr->other_param, buf, endbuf-buf, + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, + ';'); + if (printed < 0) + return printed; + buf += printed; + + return (int)(buf-startbuf); } } static pjsip_contact_hdr* pjsip_contact_hdr_clone(pj_pool_t *pool, - const pjsip_contact_hdr *rhs) + const pjsip_contact_hdr *rhs) { pjsip_contact_hdr *hdr = pjsip_contact_hdr_create(pool); hdr->star = rhs->star; if (hdr->star) - return hdr; + return hdr; hdr->uri = (pjsip_uri*) pjsip_uri_clone(pool, rhs->uri); hdr->q1000 = rhs->q1000; @@ -1345,7 +1344,7 @@ static pjsip_contact_hdr* pjsip_contact_hdr_clone(pj_pool_t *pool, static pjsip_contact_hdr* pjsip_contact_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_contact_hdr *rhs) + const pjsip_contact_hdr *rhs) { pjsip_contact_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_contact_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -1358,9 +1357,9 @@ pjsip_contact_hdr_shallow_clone( pj_pool_t *pool, * Content-Type header.. */ static int pjsip_ctype_hdr_print( pjsip_ctype_hdr *hdr, char *buf, - pj_size_t size); + pj_size_t size); static pjsip_ctype_hdr* pjsip_ctype_hdr_clone(pj_pool_t *pool, - const pjsip_ctype_hdr *hdr); + const pjsip_ctype_hdr *hdr); #define pjsip_ctype_hdr_shallow_clone pjsip_ctype_hdr_clone static pjsip_hdr_vptr ctype_hdr_vptr = @@ -1371,7 +1370,7 @@ static pjsip_hdr_vptr ctype_hdr_vptr = }; PJ_DEF(pjsip_ctype_hdr*) pjsip_ctype_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_ctype_hdr *hdr = (pjsip_ctype_hdr*) mem; @@ -1391,7 +1390,7 @@ PJ_DEF(pjsip_ctype_hdr*) pjsip_ctype_hdr_create( pj_pool_t *pool ) } static int print_media_type(char *buf, unsigned len, - const pjsip_media_type *media) + const pjsip_media_type *media) { char *p = buf; pj_ssize_t printed; @@ -1405,10 +1404,10 @@ static int print_media_type(char *buf, unsigned len, pc = pjsip_parser_const(); printed = pjsip_param_print_on(&media->param, p, buf+len-p, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, ';'); + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ';'); if (printed < 0) - return -1; + return -1; p += printed; @@ -1417,23 +1416,23 @@ static int print_media_type(char *buf, unsigned len, PJ_DEF(int) pjsip_media_type_print(char *buf, unsigned len, - const pjsip_media_type *media) + const pjsip_media_type *media) { return print_media_type(buf, len, media); } static int pjsip_ctype_hdr_print( pjsip_ctype_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { char *p = buf; int len; const pj_str_t *hname = pjsip_cfg()->endpt.use_compact_form? - &hdr->sname : &hdr->name; + &hdr->sname : &hdr->name; if ((pj_ssize_t)size < hname->slen + - hdr->media.type.slen + hdr->media.subtype.slen + 8) + hdr->media.type.slen + hdr->media.subtype.slen + 8) { - return -1; + return -1; } pj_memcpy(p, hname->ptr, hname->slen); @@ -1449,7 +1448,7 @@ static int pjsip_ctype_hdr_print( pjsip_ctype_hdr *hdr, } static pjsip_ctype_hdr* pjsip_ctype_hdr_clone( pj_pool_t *pool, - const pjsip_ctype_hdr *rhs) + const pjsip_ctype_hdr *rhs) { pjsip_ctype_hdr *hdr = pjsip_ctype_hdr_create(pool); pj_strdup(pool, &hdr->media.type, &rhs->media.type); @@ -1464,8 +1463,8 @@ static pjsip_ctype_hdr* pjsip_ctype_hdr_clone( pj_pool_t *pool, * Expires header. */ PJ_DEF(pjsip_expires_hdr*) pjsip_expires_hdr_init( pj_pool_t *pool, - void *mem, - unsigned value) + void *mem, + unsigned value) { pjsip_expires_hdr *hdr = (pjsip_expires_hdr*) mem; @@ -1478,7 +1477,7 @@ PJ_DEF(pjsip_expires_hdr*) pjsip_expires_hdr_init( pj_pool_t *pool, } PJ_DEF(pjsip_expires_hdr*) pjsip_expires_hdr_create( pj_pool_t *pool, - unsigned value ) + unsigned value ) { void *mem = pj_pool_alloc(pool, sizeof(pjsip_expires_hdr)); return pjsip_expires_hdr_init(pool, mem, value); @@ -1489,11 +1488,11 @@ PJ_DEF(pjsip_expires_hdr*) pjsip_expires_hdr_create( pj_pool_t *pool, * To or From header. */ static int pjsip_fromto_hdr_print( pjsip_fromto_hdr *hdr, - char *buf, pj_size_t size); + char *buf, pj_size_t size); static pjsip_fromto_hdr* pjsip_fromto_hdr_clone( pj_pool_t *pool, - const pjsip_fromto_hdr *hdr); + const pjsip_fromto_hdr *hdr); static pjsip_fromto_hdr* pjsip_fromto_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_fromto_hdr *hdr); + const pjsip_fromto_hdr *hdr); static pjsip_hdr_vptr fromto_hdr_vptr = @@ -1504,7 +1503,7 @@ static pjsip_hdr_vptr fromto_hdr_vptr = }; PJ_DEF(pjsip_from_hdr*) pjsip_from_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_from_hdr *hdr = (pjsip_from_hdr*) mem; @@ -1523,7 +1522,7 @@ PJ_DEF(pjsip_from_hdr*) pjsip_from_hdr_create( pj_pool_t *pool ) } PJ_DEF(pjsip_to_hdr*) pjsip_to_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_to_hdr *hdr = (pjsip_to_hdr*) mem; @@ -1563,13 +1562,13 @@ PJ_DEF(pjsip_to_hdr*) pjsip_fromto_hdr_set_to( pjsip_fromto_hdr *hdr ) } static int pjsip_fromto_hdr_print( pjsip_fromto_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { pj_ssize_t printed; char *startbuf = buf; char *endbuf = buf + size; const pj_str_t *hname = pjsip_cfg()->endpt.use_compact_form? - &hdr->sname : &hdr->name; + &hdr->sname : &hdr->name; const pjsip_parser_const_t *pc = pjsip_parser_const(); copy_advance(buf, (*hname)); @@ -1577,27 +1576,27 @@ static int pjsip_fromto_hdr_print( pjsip_fromto_hdr *hdr, copy_advance_char_check(buf, ' '); printed = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, hdr->uri, - buf, endbuf-buf); + buf, endbuf-buf); if (printed < 1) - return -1; + return -1; buf += printed; copy_advance_pair_escape(buf, ";tag=", 5, hdr->tag, - pc->pjsip_TOKEN_SPEC); + pc->pjsip_TOKEN_SPEC); printed = pjsip_param_print_on(&hdr->other_param, buf, endbuf-buf, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, ';'); + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ';'); if (printed < 0) - return -1; + return -1; buf += printed; return (int)(buf-startbuf); } static pjsip_fromto_hdr* pjsip_fromto_hdr_clone( pj_pool_t *pool, - const pjsip_fromto_hdr *rhs) + const pjsip_fromto_hdr *rhs) { pjsip_fromto_hdr *hdr = pjsip_from_hdr_create(pool); @@ -1613,7 +1612,7 @@ static pjsip_fromto_hdr* pjsip_fromto_hdr_clone( pj_pool_t *pool, static pjsip_fromto_hdr* pjsip_fromto_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_fromto_hdr *rhs) + const pjsip_fromto_hdr *rhs) { pjsip_fromto_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_fromto_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -1627,8 +1626,8 @@ pjsip_fromto_hdr_shallow_clone( pj_pool_t *pool, * Max-Forwards header. */ PJ_DEF(pjsip_max_fwd_hdr*) pjsip_max_fwd_hdr_init( pj_pool_t *pool, - void *mem, - unsigned value) + void *mem, + unsigned value) { pjsip_max_fwd_hdr *hdr = (pjsip_max_fwd_hdr*) mem; @@ -1641,7 +1640,7 @@ PJ_DEF(pjsip_max_fwd_hdr*) pjsip_max_fwd_hdr_init( pj_pool_t *pool, } PJ_DEF(pjsip_max_fwd_hdr*) pjsip_max_fwd_hdr_create(pj_pool_t *pool, - unsigned value) + unsigned value) { void *mem = pj_pool_alloc(pool, sizeof(pjsip_max_fwd_hdr)); return pjsip_max_fwd_hdr_init(pool, mem, value); @@ -1653,8 +1652,8 @@ PJ_DEF(pjsip_max_fwd_hdr*) pjsip_max_fwd_hdr_create(pj_pool_t *pool, * Min-Expires header. */ PJ_DEF(pjsip_min_expires_hdr*) pjsip_min_expires_hdr_init( pj_pool_t *pool, - void *mem, - unsigned value ) + void *mem, + unsigned value ) { pjsip_min_expires_hdr *hdr = (pjsip_min_expires_hdr*) mem; @@ -1666,7 +1665,7 @@ PJ_DEF(pjsip_min_expires_hdr*) pjsip_min_expires_hdr_init( pj_pool_t *pool, } PJ_DEF(pjsip_min_expires_hdr*) pjsip_min_expires_hdr_create(pj_pool_t *pool, - unsigned value ) + unsigned value ) { void *mem = pj_pool_alloc(pool, sizeof(pjsip_min_expires_hdr)); return pjsip_min_expires_hdr_init(pool, mem, value ); @@ -1688,7 +1687,7 @@ static pjsip_hdr_vptr routing_hdr_vptr = }; PJ_DEF(pjsip_rr_hdr*) pjsip_rr_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_rr_hdr *hdr = (pjsip_rr_hdr*) mem; @@ -1708,7 +1707,7 @@ PJ_DEF(pjsip_rr_hdr*) pjsip_rr_hdr_create( pj_pool_t *pool ) } PJ_DEF(pjsip_route_hdr*) pjsip_route_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_route_hdr *hdr = (pjsip_route_hdr*) mem; @@ -1745,7 +1744,7 @@ PJ_DEF(pjsip_route_hdr*) pjsip_routing_hdr_set_route( pjsip_routing_hdr *hdr ) } static int pjsip_routing_hdr_print( pjsip_routing_hdr *hdr, - char *buf, pj_size_t size ) + char *buf, pj_size_t size ) { pj_ssize_t printed; char *startbuf = buf; @@ -1758,20 +1757,20 @@ static int pjsip_routing_hdr_print( pjsip_routing_hdr *hdr, * if it exists in the route URI. */ if (PJSIP_URI_SCHEME_IS_SIPS(hdr->name_addr.uri) || - PJSIP_URI_SCHEME_IS_SIP(hdr->name_addr.uri)) + PJSIP_URI_SCHEME_IS_SIP(hdr->name_addr.uri)) { - sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(hdr->name_addr.uri); - p = sip_uri->other_param.next; - while (p != &sip_uri->other_param) { - const pj_str_t st_hide = {"hide", 4}; - - if (pj_stricmp(&p->name, &st_hide) == 0) { - /* Check if param 'hide' is specified without 'lr'. */ - pj_assert(sip_uri->lr_param != 0); - return 0; - } - p = p->next; - } + sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(hdr->name_addr.uri); + p = sip_uri->other_param.next; + while (p != &sip_uri->other_param) { + const pj_str_t st_hide = {"hide", 4}; + + if (pj_stricmp(&p->name, &st_hide) == 0) { + /* Check if param 'hide' is specified without 'lr'. */ + pj_assert(sip_uri->lr_param != 0); + return 0; + } + p = p->next; + } } /* Route and Record-Route don't compact forms */ @@ -1781,23 +1780,23 @@ static int pjsip_routing_hdr_print( pjsip_routing_hdr *hdr, copy_advance_char_check(buf, ' '); printed = pjsip_uri_print(PJSIP_URI_IN_ROUTING_HDR, &hdr->name_addr, buf, - endbuf-buf); + endbuf-buf); if (printed < 1) - return -1; + return -1; buf += printed; printed = pjsip_param_print_on(&hdr->other_param, buf, endbuf-buf, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, ';'); + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ';'); if (printed < 0) - return -1; + return -1; buf += printed; return (int)(buf-startbuf); } static pjsip_routing_hdr* pjsip_routing_hdr_clone( pj_pool_t *pool, - const pjsip_routing_hdr *rhs ) + const pjsip_routing_hdr *rhs ) { pjsip_routing_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_routing_hdr); @@ -1809,7 +1808,7 @@ static pjsip_routing_hdr* pjsip_routing_hdr_clone( pj_pool_t *pool, } static pjsip_routing_hdr* pjsip_routing_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_routing_hdr *rhs ) + const pjsip_routing_hdr *rhs ) { pjsip_routing_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_routing_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -1823,7 +1822,7 @@ static pjsip_routing_hdr* pjsip_routing_hdr_shallow_clone( pj_pool_t *pool, * Require header. */ PJ_DEF(pjsip_require_hdr*) pjsip_require_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_require_hdr *hdr = (pjsip_require_hdr*) mem; @@ -1845,12 +1844,12 @@ PJ_DEF(pjsip_require_hdr*) pjsip_require_hdr_create(pj_pool_t *pool) * Retry-After header. */ static int pjsip_retry_after_hdr_print(pjsip_retry_after_hdr *r, - char *buf, pj_size_t size ); + char *buf, pj_size_t size ); static pjsip_retry_after_hdr* pjsip_retry_after_hdr_clone(pj_pool_t *pool, - const pjsip_retry_after_hdr *r); + const pjsip_retry_after_hdr *r); static pjsip_retry_after_hdr* pjsip_retry_after_hdr_shallow_clone(pj_pool_t *pool, - const pjsip_retry_after_hdr *r ); + const pjsip_retry_after_hdr *r ); static pjsip_hdr_vptr retry_after_hdr_vptr = { @@ -1861,8 +1860,8 @@ static pjsip_hdr_vptr retry_after_hdr_vptr = PJ_DEF(pjsip_retry_after_hdr*) pjsip_retry_after_hdr_init( pj_pool_t *pool, - void *mem, - int value ) + void *mem, + int value ) { pjsip_retry_after_hdr *hdr = (pjsip_retry_after_hdr*) mem; @@ -1876,7 +1875,7 @@ PJ_DEF(pjsip_retry_after_hdr*) pjsip_retry_after_hdr_init( pj_pool_t *pool, } PJ_DEF(pjsip_retry_after_hdr*) pjsip_retry_after_hdr_create(pj_pool_t *pool, - int value ) + int value ) { void *mem = pj_pool_alloc(pool, sizeof(pjsip_retry_after_hdr)); return pjsip_retry_after_hdr_init(pool, mem, value ); @@ -1884,7 +1883,7 @@ PJ_DEF(pjsip_retry_after_hdr*) pjsip_retry_after_hdr_create(pj_pool_t *pool, static int pjsip_retry_after_hdr_print(pjsip_retry_after_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { char *p = buf; char *endbuf = buf + size; @@ -1893,7 +1892,7 @@ static int pjsip_retry_after_hdr_print(pjsip_retry_after_hdr *hdr, pj_ssize_t printed; if ((pj_ssize_t)size < hdr->name.slen + 2+11) - return -1; + return -1; pj_memcpy(p, hdr->name.ptr, hdr->name.slen); p += hname->slen; @@ -1903,29 +1902,29 @@ static int pjsip_retry_after_hdr_print(pjsip_retry_after_hdr *hdr, p += pj_utoa(hdr->ivalue, p); if (hdr->comment.slen) { - pj_bool_t enclosed; + pj_bool_t enclosed; - if (endbuf-p < hdr->comment.slen + 3) - return -1; + if (endbuf-p < hdr->comment.slen + 3) + return -1; - enclosed = (*hdr->comment.ptr == '('); - if (!enclosed) - *p++ = '('; - pj_memcpy(p, hdr->comment.ptr, hdr->comment.slen); - p += hdr->comment.slen; - if (!enclosed) - *p++ = ')'; + enclosed = (*hdr->comment.ptr == '('); + if (!enclosed) + *p++ = '('; + pj_memcpy(p, hdr->comment.ptr, hdr->comment.slen); + p += hdr->comment.slen; + if (!enclosed) + *p++ = ')'; - if (!pj_list_empty(&hdr->param)) - *p++ = ' '; + if (!pj_list_empty(&hdr->param)) + *p++ = ' '; } printed = pjsip_param_print_on(&hdr->param, p, endbuf-p, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, - ';'); + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, + ';'); if (printed < 0) - return (int)printed; + return (int)printed; p += printed; @@ -1933,7 +1932,7 @@ static int pjsip_retry_after_hdr_print(pjsip_retry_after_hdr *hdr, } static pjsip_retry_after_hdr* pjsip_retry_after_hdr_clone(pj_pool_t *pool, - const pjsip_retry_after_hdr *rhs) + const pjsip_retry_after_hdr *rhs) { pjsip_retry_after_hdr *hdr = pjsip_retry_after_hdr_create(pool, rhs->ivalue); pj_strdup(pool, &hdr->comment, &rhs->comment); @@ -1943,7 +1942,7 @@ static pjsip_retry_after_hdr* pjsip_retry_after_hdr_clone(pj_pool_t *pool, static pjsip_retry_after_hdr* pjsip_retry_after_hdr_shallow_clone(pj_pool_t *pool, - const pjsip_retry_after_hdr *rhs) + const pjsip_retry_after_hdr *rhs) { pjsip_retry_after_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_retry_after_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -1956,7 +1955,7 @@ pjsip_retry_after_hdr_shallow_clone(pj_pool_t *pool, * Supported header. */ PJ_DEF(pjsip_supported_hdr*) pjsip_supported_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_supported_hdr *hdr = (pjsip_supported_hdr*) mem; @@ -1978,7 +1977,7 @@ PJ_DEF(pjsip_supported_hdr*) pjsip_supported_hdr_create(pj_pool_t *pool) * Unsupported header. */ PJ_DEF(pjsip_unsupported_hdr*) pjsip_unsupported_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_unsupported_hdr *hdr = (pjsip_unsupported_hdr*) mem; @@ -2011,7 +2010,7 @@ static pjsip_hdr_vptr via_hdr_vptr = }; PJ_DEF(pjsip_via_hdr*) pjsip_via_hdr_init( pj_pool_t *pool, - void *mem ) + void *mem ) { pjsip_via_hdr *hdr = (pjsip_via_hdr*) mem; @@ -2033,20 +2032,20 @@ PJ_DEF(pjsip_via_hdr*) pjsip_via_hdr_create( pj_pool_t *pool ) } static int pjsip_via_hdr_print( pjsip_via_hdr *hdr, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { pj_ssize_t printed; char *startbuf = buf; char *endbuf = buf + size; pj_str_t sip_ver = { "SIP/2.0/", 8 }; const pj_str_t *hname = pjsip_cfg()->endpt.use_compact_form? - &hdr->sname : &hdr->name; + &hdr->sname : &hdr->name; const pjsip_parser_const_t *pc = pjsip_parser_const(); if ((pj_ssize_t)size < hname->slen + sip_ver.slen + - hdr->transport.slen + hdr->sent_by.host.slen + 12) + hdr->transport.slen + hdr->sent_by.host.slen + 12) { - return -1; + return -1; } /* pjsip_hdr_names */ @@ -2060,75 +2059,75 @@ static int pjsip_via_hdr_print( pjsip_via_hdr *hdr, //pj_memcpy(buf, hdr->transport.ptr, hdr->transport.slen); /* Convert transport type to UPPERCASE (some endpoints want that) */ { - int i; - for (i=0; itransport.slen; ++i) { - buf[i] = (char)pj_toupper(hdr->transport.ptr[i]); - } + int i; + for (i=0; itransport.slen; ++i) { + buf[i] = (char)pj_toupper(hdr->transport.ptr[i]); + } } buf += hdr->transport.slen; copy_advance_char_check(buf, ' '); /* Check if host contains IPv6 */ if (pj_strchr(&hdr->sent_by.host, ':')) { - copy_advance_pair_quote_cond(buf, "", 0, hdr->sent_by.host, '[', ']'); + copy_advance_pair_quote_cond(buf, "", 0, hdr->sent_by.host, '[', ']'); } else { - copy_advance_check(buf, hdr->sent_by.host); + copy_advance_check(buf, hdr->sent_by.host); } if (hdr->sent_by.port != 0) { - copy_advance_char_check(buf, ':'); - printed = pj_utoa(hdr->sent_by.port, buf); - buf += printed; + copy_advance_char_check(buf, ':'); + printed = pj_utoa(hdr->sent_by.port, buf); + buf += printed; } if (hdr->ttl_param >= 0) { - size = endbuf-buf; - if (size < 14) - return -1; - pj_memcpy(buf, ";ttl=", 5); - printed = pj_utoa(hdr->ttl_param, buf+5); - buf += printed + 5; + size = endbuf-buf; + if (size < 14) + return -1; + pj_memcpy(buf, ";ttl=", 5); + printed = pj_utoa(hdr->ttl_param, buf+5); + buf += printed + 5; } if (hdr->rport_param >= 0) { - size = endbuf-buf; - if (size < 14) - return -1; - pj_memcpy(buf, ";rport", 6); - buf += 6; - if (hdr->rport_param > 0) { - copy_advance_char_check(buf, '='); - buf += pj_utoa(hdr->rport_param, buf); - } + size = endbuf-buf; + if (size < 14) + return -1; + pj_memcpy(buf, ";rport", 6); + buf += 6; + if (hdr->rport_param > 0) { + copy_advance_char_check(buf, '='); + buf += pj_utoa(hdr->rport_param, buf); + } } if (hdr->maddr_param.slen) { - /* Detect IPv6 IP address */ - if (pj_memchr(hdr->maddr_param.ptr, ':', hdr->maddr_param.slen)) { - copy_advance_pair_quote_cond(buf, ";maddr=", 7, hdr->maddr_param, - '[', ']'); - } else { - copy_advance_pair(buf, ";maddr=", 7, hdr->maddr_param); - } + /* Detect IPv6 IP address */ + if (pj_memchr(hdr->maddr_param.ptr, ':', hdr->maddr_param.slen)) { + copy_advance_pair_quote_cond(buf, ";maddr=", 7, hdr->maddr_param, + '[', ']'); + } else { + copy_advance_pair(buf, ";maddr=", 7, hdr->maddr_param); + } } copy_advance_pair(buf, ";received=", 10, hdr->recvd_param); copy_advance_pair_escape(buf, ";branch=", 8, hdr->branch_param, - pc->pjsip_TOKEN_SPEC); + pc->pjsip_TOKEN_SPEC); printed = pjsip_param_print_on(&hdr->other_param, buf, endbuf-buf, - &pc->pjsip_TOKEN_SPEC, - &pc->pjsip_TOKEN_SPEC, ';'); + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ';'); if (printed < 0) - return -1; + return -1; buf += printed; return (int)(buf-startbuf); } static pjsip_via_hdr* pjsip_via_hdr_clone( pj_pool_t *pool, - const pjsip_via_hdr *rhs) + const pjsip_via_hdr *rhs) { pjsip_via_hdr *hdr = pjsip_via_hdr_create(pool); pj_strdup(pool, &hdr->transport, &rhs->transport); @@ -2144,7 +2143,7 @@ static pjsip_via_hdr* pjsip_via_hdr_clone( pj_pool_t *pool, } static pjsip_via_hdr* pjsip_via_hdr_shallow_clone( pj_pool_t *pool, - const pjsip_via_hdr *rhs ) + const pjsip_via_hdr *rhs ) { pjsip_via_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_via_hdr); pj_memcpy(hdr, rhs, sizeof(*hdr)); @@ -2157,26 +2156,26 @@ static pjsip_via_hdr* pjsip_via_hdr_shallow_clone( pj_pool_t *pool, * Warning header. */ PJ_DEF(pjsip_warning_hdr*) pjsip_warning_hdr_create( pj_pool_t *pool, - int code, - const pj_str_t *host, - const pj_str_t *text) + int code, + const pj_str_t *host, + const pj_str_t *text) { const pj_str_t str_warning = { "Warning", 7 }; pj_str_t hvalue; - hvalue.ptr = (char*) pj_pool_alloc(pool, 10 + /* code */ - host->slen + 2 + /* host */ - text->slen + 2); /* text */ + hvalue.ptr = (char*) pj_pool_alloc(pool, 10 + /* code */ + host->slen + 2 + /* host */ + text->slen + 2); /* text */ hvalue.slen = pj_ansi_sprintf(hvalue.ptr, "%u %.*s \"%.*s\"", - code, (int)host->slen, host->ptr, - (int)text->slen, text->ptr); + code, (int)host->slen, host->ptr, + (int)text->slen, text->ptr); return pjsip_generic_string_hdr_create(pool, &str_warning, &hvalue); } PJ_DEF(pjsip_warning_hdr*) pjsip_warning_hdr_create_from_status(pj_pool_t *pool, - const pj_str_t *host, - pj_status_t status) + const pj_str_t *host, + pj_status_t status) { char errbuf[PJ_ERR_MSG_SIZE]; pj_str_t text; @@ -2192,37 +2191,37 @@ PJ_DEF(pjsip_warning_hdr*) pjsip_warning_hdr_create_from_status(pj_pool_t *pool, PJ_DEF(int) pjsip_print_text_body(pjsip_msg_body *msg_body, char *buf, pj_size_t size) { if (size < msg_body->len) - return -1; + return -1; pj_memcpy(buf, msg_body->data, msg_body->len); return msg_body->len; } PJ_DEF(void*) pjsip_clone_text_data( pj_pool_t *pool, const void *data, - unsigned len) + unsigned len) { char *newdata = ""; if (len) { - newdata = (char*) pj_pool_alloc(pool, len); - pj_memcpy(newdata, data, len); + newdata = (char*) pj_pool_alloc(pool, len); + pj_memcpy(newdata, data, len); } return newdata; } PJ_DEF(pj_status_t) pjsip_msg_body_copy( pj_pool_t *pool, - pjsip_msg_body *dst_body, - const pjsip_msg_body *src_body ) + pjsip_msg_body *dst_body, + const pjsip_msg_body *src_body ) { /* First check if clone_data field is initialized. */ PJ_ASSERT_RETURN( src_body->clone_data!=NULL, PJ_EINVAL ); /* Duplicate content-type */ pjsip_media_type_cp(pool, &dst_body->content_type, - &src_body->content_type); + &src_body->content_type); /* Duplicate data. */ dst_body->data = (*src_body->clone_data)(pool, src_body->data, - src_body->len ); + src_body->len ); /* Length. */ dst_body->len = src_body->len; @@ -2236,7 +2235,7 @@ PJ_DEF(pj_status_t) pjsip_msg_body_copy( pj_pool_t *pool, PJ_DEF(pjsip_msg_body*) pjsip_msg_body_clone( pj_pool_t *pool, - const pjsip_msg_body *body ) + const pjsip_msg_body *body ) { pjsip_msg_body *new_body; pj_status_t status; @@ -2251,9 +2250,9 @@ PJ_DEF(pjsip_msg_body*) pjsip_msg_body_clone( pj_pool_t *pool, PJ_DEF(pjsip_msg_body*) pjsip_msg_body_create( pj_pool_t *pool, - const pj_str_t *type, - const pj_str_t *subtype, - const pj_str_t *text ) + const pj_str_t *type, + const pj_str_t *subtype, + const pj_str_t *text ) { pjsip_msg_body *body; diff --git a/pjsip/src/pjsip/sip_multipart.c b/pjsip/src/pjsip/sip_multipart.c index 451e509797..e09167643d 100644 --- a/pjsip/src/pjsip/sip_multipart.c +++ b/pjsip/src/pjsip/sip_multipart.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -29,12 +28,12 @@ #include #include -#define THIS_FILE "sip_multipart.c" +#define THIS_FILE "sip_multipart.c" -#define IS_SPACE(c) ((c)==' ' || (c)=='\t') +#define IS_SPACE(c) ((c)==' ' || (c)=='\t') #if 0 -# define TRACE_(x) PJ_LOG(4,x) +# define TRACE_(x) PJ_LOG(4,x) #else # define TRACE_(x) #endif @@ -42,21 +41,21 @@ /* Type of "data" in multipart pjsip_msg_body */ struct multipart_data { - pj_str_t boundary; + pj_str_t boundary; pjsip_multipart_part part_head; - pj_str_t raw_data; + pj_str_t raw_data; }; static int multipart_print_body(struct pjsip_msg_body *msg_body, - char *buf, pj_size_t size) + char *buf, pj_size_t size) { const struct multipart_data *m_data; pj_str_t clen_hdr = { "Content-Length: ", 16}; pjsip_multipart_part *part; char *p = buf, *end = buf+size; -#define SIZE_LEFT() (end-p) +#define SIZE_LEFT() (end-p) m_data = (const struct multipart_data*)msg_body->data; @@ -64,109 +63,109 @@ static int multipart_print_body(struct pjsip_msg_body *msg_body, part = m_data->part_head.next; while (part != &m_data->part_head) { - enum { CLEN_SPACE = 5 }; - char *clen_pos; - const pjsip_hdr *hdr; - pj_bool_t ctype_printed = PJ_FALSE; - - clen_pos = NULL; - - /* Print delimiter */ - if (SIZE_LEFT() <= (m_data->boundary.slen+8) << 1) - return -1; - *p++ = 13; *p++ = 10; *p++ = '-'; *p++ = '-'; - pj_memcpy(p, m_data->boundary.ptr, m_data->boundary.slen); - p += m_data->boundary.slen; - *p++ = 13; *p++ = 10; - - /* Print optional headers */ - hdr = part->hdr.next; - while (hdr != &part->hdr) { - int printed = pjsip_hdr_print_on((pjsip_hdr*)hdr, p, - SIZE_LEFT()-2); - if (printed < 0) - return -1; - p += printed; - *p++ = '\r'; - *p++ = '\n'; - - if (!ctype_printed && hdr->type == PJSIP_H_CONTENT_TYPE) - ctype_printed = PJ_TRUE; - - hdr = hdr->next; - } - - /* Automaticly adds Content-Type and Content-Length headers, only - * if content_type is set in the message body and haven't been printed. - */ - if (part->body && part->body->content_type.type.slen && !ctype_printed) - { - pj_str_t ctype_hdr = { "Content-Type: ", 14}; - const pjsip_media_type *media = &part->body->content_type; - - if (pjsip_cfg()->endpt.use_compact_form) { - ctype_hdr.ptr = "c: "; - ctype_hdr.slen = 3; - } - - /* Add Content-Type header. */ - if ( (end-p) < 24 + media->type.slen + media->subtype.slen) { - return -1; - } - pj_memcpy(p, ctype_hdr.ptr, ctype_hdr.slen); - p += ctype_hdr.slen; - p += pjsip_media_type_print(p, (unsigned)(end-p), media); - *p++ = '\r'; - *p++ = '\n'; - - /* Add Content-Length header. */ - if ((end-p) < clen_hdr.slen + 12 + 2) { - return -1; - } - pj_memcpy(p, clen_hdr.ptr, clen_hdr.slen); - p += clen_hdr.slen; - - /* Print blanks after "Content-Length:", this is where we'll put - * the content length value after we know the length of the - * body. - */ - pj_memset(p, ' ', CLEN_SPACE); - clen_pos = p; - p += CLEN_SPACE; - *p++ = '\r'; - *p++ = '\n'; - } - - /* Empty newline */ - *p++ = 13; *p++ = 10; - - /* Print the body */ - pj_assert(part->body != NULL); - if (part->body) { - int printed = part->body->print_body(part->body, p, SIZE_LEFT()); - if (printed < 0) - return -1; - p += printed; - - /* Now that we have the length of the body, print this to the - * Content-Length header. - */ - if (clen_pos) { - char tmp[16]; - int len; - - len = pj_utoa(printed, tmp); - if (len > CLEN_SPACE) len = CLEN_SPACE; - pj_memcpy(clen_pos+CLEN_SPACE-len, tmp, len); - } - } - - part = part->next; + enum { CLEN_SPACE = 5 }; + char *clen_pos; + const pjsip_hdr *hdr; + pj_bool_t ctype_printed = PJ_FALSE; + + clen_pos = NULL; + + /* Print delimiter */ + if (SIZE_LEFT() <= (m_data->boundary.slen+8) << 1) + return -1; + *p++ = 13; *p++ = 10; *p++ = '-'; *p++ = '-'; + pj_memcpy(p, m_data->boundary.ptr, m_data->boundary.slen); + p += m_data->boundary.slen; + *p++ = 13; *p++ = 10; + + /* Print optional headers */ + hdr = part->hdr.next; + while (hdr != &part->hdr) { + int printed = pjsip_hdr_print_on((pjsip_hdr*)hdr, p, + SIZE_LEFT()-2); + if (printed < 0) + return -1; + p += printed; + *p++ = '\r'; + *p++ = '\n'; + + if (!ctype_printed && hdr->type == PJSIP_H_CONTENT_TYPE) + ctype_printed = PJ_TRUE; + + hdr = hdr->next; + } + + /* Automaticly adds Content-Type and Content-Length headers, only + * if content_type is set in the message body and haven't been printed. + */ + if (part->body && part->body->content_type.type.slen && !ctype_printed) + { + pj_str_t ctype_hdr = { "Content-Type: ", 14}; + const pjsip_media_type *media = &part->body->content_type; + + if (pjsip_cfg()->endpt.use_compact_form) { + ctype_hdr.ptr = "c: "; + ctype_hdr.slen = 3; + } + + /* Add Content-Type header. */ + if ( (end-p) < 24 + media->type.slen + media->subtype.slen) { + return -1; + } + pj_memcpy(p, ctype_hdr.ptr, ctype_hdr.slen); + p += ctype_hdr.slen; + p += pjsip_media_type_print(p, (unsigned)(end-p), media); + *p++ = '\r'; + *p++ = '\n'; + + /* Add Content-Length header. */ + if ((end-p) < clen_hdr.slen + 12 + 2) { + return -1; + } + pj_memcpy(p, clen_hdr.ptr, clen_hdr.slen); + p += clen_hdr.slen; + + /* Print blanks after "Content-Length:", this is where we'll put + * the content length value after we know the length of the + * body. + */ + pj_memset(p, ' ', CLEN_SPACE); + clen_pos = p; + p += CLEN_SPACE; + *p++ = '\r'; + *p++ = '\n'; + } + + /* Empty newline */ + *p++ = 13; *p++ = 10; + + /* Print the body */ + pj_assert(part->body != NULL); + if (part->body) { + int printed = part->body->print_body(part->body, p, SIZE_LEFT()); + if (printed < 0) + return -1; + p += printed; + + /* Now that we have the length of the body, print this to the + * Content-Length header. + */ + if (clen_pos) { + char tmp[16]; + int len; + + len = pj_utoa(printed, tmp); + if (len > CLEN_SPACE) len = CLEN_SPACE; + pj_memcpy(clen_pos+CLEN_SPACE-len, tmp, len); + } + } + + part = part->next; } /* Print closing delimiter */ if (SIZE_LEFT() < m_data->boundary.slen+8) - return -1; + return -1; *p++ = 13; *p++ = 10; *p++ = '-'; *p++ = '-'; pj_memcpy(p, m_data->boundary.ptr, m_data->boundary.slen); p += m_data->boundary.slen; @@ -178,7 +177,7 @@ static int multipart_print_body(struct pjsip_msg_body *msg_body, } static void* multipart_clone_data(pj_pool_t *pool, const void *data, - unsigned len) + unsigned len) { const struct multipart_data *src; struct multipart_data *dst; @@ -194,23 +193,23 @@ static void* multipart_clone_data(pj_pool_t *pool, const void *data, src_part = src->part_head.next; while (src_part != &src->part_head) { - pjsip_multipart_part *dst_part; - const pjsip_hdr *src_hdr; + pjsip_multipart_part *dst_part; + const pjsip_hdr *src_hdr; - dst_part = pjsip_multipart_create_part(pool); + dst_part = pjsip_multipart_create_part(pool); - src_hdr = src_part->hdr.next; - while (src_hdr != &src_part->hdr) { - pjsip_hdr *dst_hdr = (pjsip_hdr*)pjsip_hdr_clone(pool, src_hdr); - pj_list_push_back(&dst_part->hdr, dst_hdr); - src_hdr = src_hdr->next; - } + src_hdr = src_part->hdr.next; + while (src_hdr != &src_part->hdr) { + pjsip_hdr *dst_hdr = (pjsip_hdr*)pjsip_hdr_clone(pool, src_hdr); + pj_list_push_back(&dst_part->hdr, dst_hdr); + src_hdr = src_hdr->next; + } - dst_part->body = pjsip_msg_body_clone(pool, src_part->body); + dst_part->body = pjsip_msg_body_clone(pool, src_part->body); - pj_list_push_back(&dst->part_head, dst_part); + pj_list_push_back(&dst->part_head, dst_part); - src_part = src_part->next; + src_part = src_part->next; } return (void*)dst; @@ -220,8 +219,8 @@ static void* multipart_clone_data(pj_pool_t *pool, const void *data, * Create an empty multipart body. */ PJ_DEF(pjsip_msg_body*) pjsip_multipart_create( pj_pool_t *pool, - const pjsip_media_type *ctype, - const pj_str_t *boundary) + const pjsip_media_type *ctype, + const pj_str_t *boundary) { pjsip_msg_body *body; pjsip_param *ctype_param; @@ -234,10 +233,10 @@ PJ_DEF(pjsip_msg_body*) pjsip_multipart_create( pj_pool_t *pool, /* content-type */ if (ctype && ctype->type.slen) { - pjsip_media_type_cp(pool, &body->content_type, ctype); + pjsip_media_type_cp(pool, &body->content_type, ctype); } else { - pj_str_t STR_MULTIPART = {"multipart", 9}; - pj_str_t STR_MIXED = { "mixed", 5 }; + pj_str_t STR_MULTIPART = {"multipart", 9}; + pj_str_t STR_MIXED = { "mixed", 5 }; pjsip_media_type_init(&body->content_type, &STR_MULTIPART, &STR_MIXED); @@ -247,18 +246,18 @@ PJ_DEF(pjsip_msg_body*) pjsip_multipart_create( pj_pool_t *pool, mp_data = PJ_POOL_ZALLOC_T(pool, struct multipart_data); pj_list_init(&mp_data->part_head); if (boundary) { - pj_strdup(pool, &mp_data->boundary, boundary); + pj_strdup(pool, &mp_data->boundary, boundary); } else { - pj_create_unique_string(pool, &mp_data->boundary); + pj_create_unique_string(pool, &mp_data->boundary); } body->data = mp_data; /* Add ";boundary" parameter to content_type parameter. */ ctype_param = pjsip_param_find(&body->content_type.param, &STR_BOUNDARY); if (!ctype_param) { - ctype_param = PJ_POOL_ALLOC_T(pool, pjsip_param); - ctype_param->name = STR_BOUNDARY; - pj_list_push_back(&body->content_type.param, ctype_param); + ctype_param = PJ_POOL_ALLOC_T(pool, pjsip_param); + ctype_param->name = STR_BOUNDARY; + pj_list_push_back(&body->content_type.param, ctype_param); } ctype_param->value = mp_data->boundary; @@ -288,7 +287,7 @@ PJ_DEF(pjsip_multipart_part*) pjsip_multipart_create_part(pj_pool_t *pool) */ PJ_DEF(pjsip_multipart_part*) pjsip_multipart_clone_part(pj_pool_t *pool, - const pjsip_multipart_part *src) + const pjsip_multipart_part *src) { pjsip_multipart_part *dst; const pjsip_hdr *hdr; @@ -297,8 +296,8 @@ pjsip_multipart_clone_part(pj_pool_t *pool, hdr = src->hdr.next; while (hdr != &src->hdr) { - pj_list_push_back(&dst->hdr, pjsip_hdr_clone(pool, hdr)); - hdr = hdr->next; + pj_list_push_back(&dst->hdr, pjsip_hdr_clone(pool, hdr)); + hdr = hdr->next; } dst->body = pjsip_msg_body_clone(pool, src->body); @@ -311,8 +310,8 @@ pjsip_multipart_clone_part(pj_pool_t *pool, * Add a part into multipart bodies. */ PJ_DEF(pj_status_t) pjsip_multipart_add_part( pj_pool_t *pool, - pjsip_msg_body *mp, - pjsip_multipart_part *part) + pjsip_msg_body *mp, + pjsip_multipart_part *part) { struct multipart_data *m_data; @@ -349,7 +348,7 @@ pjsip_multipart_get_first_part(const pjsip_msg_body *mp) m_data = (struct multipart_data*)mp->data; if (pj_list_empty(&m_data->part_head)) - return NULL; + return NULL; return m_data->part_head.next; } @@ -359,7 +358,7 @@ pjsip_multipart_get_first_part(const pjsip_msg_body *mp) */ PJ_DEF(pjsip_multipart_part*) pjsip_multipart_get_next_part(const pjsip_msg_body *mp, - pjsip_multipart_part *part) + pjsip_multipart_part *part) { struct multipart_data *m_data; @@ -373,10 +372,10 @@ pjsip_multipart_get_next_part(const pjsip_msg_body *mp, /* the part parameter must be really member of the list */ PJ_ASSERT_RETURN(pj_list_find_node(&m_data->part_head, part) != NULL, - NULL); + NULL); if (part->next == &m_data->part_head) - return NULL; + return NULL; return part->next; } @@ -386,8 +385,8 @@ pjsip_multipart_get_next_part(const pjsip_msg_body *mp, */ PJ_DEF(pjsip_multipart_part*) pjsip_multipart_find_part( const pjsip_msg_body *mp, - const pjsip_media_type *content_type, - const pjsip_multipart_part *start) + const pjsip_media_type *content_type, + const pjsip_multipart_part *start) { struct multipart_data *m_data; pjsip_multipart_part *part; @@ -401,17 +400,17 @@ pjsip_multipart_find_part( const pjsip_msg_body *mp, m_data = (struct multipart_data*)mp->data; if (start) - part = start->next; + part = start->next; else - part = m_data->part_head.next; + part = m_data->part_head.next; while (part != &m_data->part_head) { - if (pjsip_media_type_cmp(&part->body->content_type, - content_type, 0)==0) - { - return part; - } - part = part->next; + if (pjsip_media_type_cmp(&part->body->content_type, + content_type, 0)==0) + { + return part; + } + part = part->next; } return NULL; @@ -422,10 +421,10 @@ pjsip_multipart_find_part( const pjsip_msg_body *mp, */ PJ_DEF(pjsip_multipart_part*) pjsip_multipart_find_part_by_header_str(pj_pool_t *pool, - const pjsip_msg_body *mp, - const pj_str_t *hdr_name, - const pj_str_t *hdr_value, - const pjsip_multipart_part *start) + const pjsip_msg_body *mp, + const pj_str_t *hdr_name, + const pj_str_t *hdr_value, + const pjsip_multipart_part *start) { struct multipart_data *m_data; pjsip_multipart_part *part; @@ -464,34 +463,34 @@ pjsip_multipart_find_part_by_header_str(pj_pool_t *pool, m_data = (struct multipart_data*)mp->data; if (start) - part = start->next; + part = start->next; else - part = m_data->part_head.next; + part = m_data->part_head.next; while (part != &m_data->part_head) { - found_hdr = NULL; - while ((found_hdr = pjsip_hdr_find_by_name(&part->hdr, hdr_name, - (found_hdr ? found_hdr->next : NULL))) != NULL) { - - found_hdr_str.slen = pjsip_hdr_print_on((void*) found_hdr, found_hdr_str.ptr, buf_size); - /* - * If the buffer was too small (slen = -1) or the result wasn't - * the same length as the search header, it can't be a match. - */ - if (found_hdr_str.slen != (pj_ssize_t)expected_hdr_slen) { - continue; - } - /* - * Set the value overlay to start at the found header value... - */ - found_hdr_value.ptr = found_hdr_str.ptr + hdr_name_len; - found_hdr_value.slen = found_hdr_str.slen - hdr_name_len; - /* ...and compare it to the supplied header value. */ - if (pj_strcmp(hdr_value, &found_hdr_value) == 0) { - return part; - } - } - part = part->next; + found_hdr = NULL; + while ((found_hdr = pjsip_hdr_find_by_name(&part->hdr, hdr_name, + (found_hdr ? found_hdr->next : NULL))) != NULL) { + + found_hdr_str.slen = pjsip_hdr_print_on((void*) found_hdr, found_hdr_str.ptr, buf_size); + /* + * If the buffer was too small (slen = -1) or the result wasn't + * the same length as the search header, it can't be a match. + */ + if (found_hdr_str.slen != (pj_ssize_t)expected_hdr_slen) { + continue; + } + /* + * Set the value overlay to start at the found header value... + */ + found_hdr_value.ptr = found_hdr_str.ptr + hdr_name_len; + found_hdr_value.slen = found_hdr_str.slen - hdr_name_len; + /* ...and compare it to the supplied header value. */ + if (pj_strcmp(hdr_value, &found_hdr_value) == 0) { + return part; + } + } + part = part->next; } return NULL; #undef SEPARATOR_LEN @@ -500,9 +499,9 @@ pjsip_multipart_find_part_by_header_str(pj_pool_t *pool, PJ_DEF(pjsip_multipart_part*) pjsip_multipart_find_part_by_header(pj_pool_t *pool, - const pjsip_msg_body *mp, - void *search_for, - const pjsip_multipart_part *start) + const pjsip_msg_body *mp, + void *search_for, + const pjsip_multipart_part *start) { pjsip_hdr *search_hdr = search_for; pj_str_t search_buf; @@ -521,7 +520,7 @@ pjsip_multipart_find_part_by_header(pj_pool_t *pool, search_buf.ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE); search_buf.slen = pjsip_hdr_print_on(search_hdr, search_buf.ptr, PJSIP_MAX_URL_SIZE - 1); if (search_buf.slen <= 0) { - return NULL; + return NULL; } /* * Set the header value to start after the header name plus the ":", then @@ -556,13 +555,13 @@ static pj_str_t cid_uri_to_hdr_value(pj_pool_t *pool, pj_str_t *cid_uri) pj_strassign(&uri_overlay, cid_uri); /* If the URI is already enclosed in angle brackets, remove them. */ if (uri_overlay.ptr[0] == '<') { - uri_overlay.ptr++; - uri_overlay.slen -= 2; + uri_overlay.ptr++; + uri_overlay.slen -= 2; } /* If the URI starts with the "cid:" scheme, skip over it. */ if (pj_strncmp2(&uri_overlay, "cid:", 4) == 0) { - uri_overlay.ptr += 4; - uri_overlay.slen -= 4; + uri_overlay.ptr += 4; + uri_overlay.slen -= 4; } /* Start building */ cid_hdr.ptr = pj_pool_alloc(pool, alloc_len); @@ -580,8 +579,8 @@ static pj_str_t cid_uri_to_hdr_value(pj_pool_t *pool, pj_str_t *cid_uri) PJ_DEF(pjsip_multipart_part*) pjsip_multipart_find_part_by_cid_str(pj_pool_t *pool, - const pjsip_msg_body *mp, - pj_str_t *cid) + const pjsip_msg_body *mp, + pj_str_t *cid) { struct multipart_data *m_data; pjsip_multipart_part *part; @@ -593,34 +592,34 @@ pjsip_multipart_find_part_by_cid_str(pj_pool_t *pool, hdr_value = cid_uri_to_hdr_value(pool, cid); if (pj_strlen(&hdr_value) == 0) { - return NULL; + return NULL; } m_data = (struct multipart_data*)mp->data; part = m_data->part_head.next; while (part != &m_data->part_head) { - found_hdr = NULL; - while ((found_hdr = pjsip_hdr_find_by_name(&part->hdr, &hdr_name, - (found_hdr ? found_hdr->next : NULL))) != NULL) { - if (pj_strcmp(&hdr_value, &found_hdr->hvalue) == 0) { - return part; - } - } - part = part->next; + found_hdr = NULL; + while ((found_hdr = pjsip_hdr_find_by_name(&part->hdr, &hdr_name, + (found_hdr ? found_hdr->next : NULL))) != NULL) { + if (pj_strcmp(&hdr_value, &found_hdr->hvalue) == 0) { + return part; + } + } + part = part->next; } return NULL; } PJ_DEF(pjsip_multipart_part*) pjsip_multipart_find_part_by_cid_uri(pj_pool_t *pool, - const pjsip_msg_body *mp, - pjsip_other_uri *cid_uri) + const pjsip_msg_body *mp, + pjsip_other_uri *cid_uri) { PJ_ASSERT_RETURN(pool && mp && cid_uri, NULL); if (pj_strcmp2(&cid_uri->scheme, "cid") != 0) { - return NULL; + return NULL; } /* * We only need to pass the URI content so we @@ -631,90 +630,90 @@ pjsip_multipart_find_part_by_cid_uri(pj_pool_t *pool, /* Parse a multipart part. "pct" is parent content-type */ static pjsip_multipart_part *parse_multipart_part(pj_pool_t *pool, - char *start, - pj_size_t len, - const pjsip_media_type *pct) + char *start, + pj_size_t len, + const pjsip_media_type *pct) { pjsip_multipart_part *part = pjsip_multipart_create_part(pool); char *p = start, *end = start+len, *end_hdr = NULL, *start_body = NULL; pjsip_ctype_hdr *ctype_hdr = NULL; TRACE_((THIS_FILE, "Parsing part: begin--\n%.*s\n--end", - (int)len, start)); + (int)len, start)); /* Find the end of header area, by looking at an empty line */ for (;;) { - while (p!=end && *p!='\n') ++p; - if (p==end) { - start_body = end; - break; - } - if ((p==start) || (p==start+1 && *(p-1)=='\r')) { - /* Empty header section */ - end_hdr = start; - start_body = ++p; - break; - } else if (p==end-1) { - /* Empty body section */ - end_hdr = end; - start_body = ++p; - } else if ((p>=start+1 && *(p-1)=='\n') || - (p>=start+2 && *(p-1)=='\r' && *(p-2)=='\n')) - { - /* Found it */ - end_hdr = (*(p-1)=='\r') ? (p-1) : p; - start_body = ++p; - break; - } else { - ++p; - } + while (p!=end && *p!='\n') ++p; + if (p==end) { + start_body = end; + break; + } + if ((p==start) || (p==start+1 && *(p-1)=='\r')) { + /* Empty header section */ + end_hdr = start; + start_body = ++p; + break; + } else if (p==end-1) { + /* Empty body section */ + end_hdr = end; + start_body = ++p; + } else if ((p>=start+1 && *(p-1)=='\n') || + (p>=start+2 && *(p-1)=='\r' && *(p-2)=='\n')) + { + /* Found it */ + end_hdr = (*(p-1)=='\r') ? (p-1) : p; + start_body = ++p; + break; + } else { + ++p; + } } /* Parse the headers */ if (end_hdr-start > 0) { - pjsip_hdr *hdr; - pj_status_t status; - - status = pjsip_parse_headers(pool, start, end_hdr-start, - &part->hdr, 0); - if (status != PJ_SUCCESS) { - PJ_PERROR(2,(THIS_FILE, status, "Warning: error parsing multipart" - " header")); - } - - /* Find Content-Type header */ - hdr = part->hdr.next; - while (hdr != &part->hdr) { - TRACE_((THIS_FILE, "Header parsed: %.*s", (int)hdr->name.slen, - hdr->name.ptr)); - if (hdr->type == PJSIP_H_CONTENT_TYPE) { - ctype_hdr = (pjsip_ctype_hdr*)hdr; - } - hdr = hdr->next; - } + pjsip_hdr *hdr; + pj_status_t status; + + status = pjsip_parse_headers(pool, start, end_hdr-start, + &part->hdr, 0); + if (status != PJ_SUCCESS) { + PJ_PERROR(2,(THIS_FILE, status, "Warning: error parsing multipart" + " header")); + } + + /* Find Content-Type header */ + hdr = part->hdr.next; + while (hdr != &part->hdr) { + TRACE_((THIS_FILE, "Header parsed: %.*s", (int)hdr->name.slen, + hdr->name.ptr)); + if (hdr->type == PJSIP_H_CONTENT_TYPE) { + ctype_hdr = (pjsip_ctype_hdr*)hdr; + } + hdr = hdr->next; + } } /* Assign the body */ part->body = PJ_POOL_ZALLOC_T(pool, pjsip_msg_body); if (ctype_hdr) { - pjsip_media_type_cp(pool, &part->body->content_type, &ctype_hdr->media); + pjsip_media_type_cp(pool, &part->body->content_type, &ctype_hdr->media); } else if (pct && pj_stricmp2(&pct->subtype, "digest")==0) { - part->body->content_type.type = pj_str("message"); - part->body->content_type.subtype = pj_str("rfc822"); + part->body->content_type.type = pj_str("message"); + part->body->content_type.subtype = pj_str("rfc822"); } else { - part->body->content_type.type = pj_str("text"); - part->body->content_type.subtype = pj_str("plain"); + part->body->content_type.type = pj_str("text"); + part->body->content_type.subtype = pj_str("plain"); } if (start_body < end) { - part->body->data = start_body; - part->body->len = (unsigned)(end - start_body); + part->body->data = start_body; + part->body->len = (unsigned)(end - start_body); } else { - part->body->data = (void*)""; - part->body->len = 0; + part->body->data = (void*)""; + part->body->len = 0; } TRACE_((THIS_FILE, "Body parsed: \"%.*s\"", (int)part->body->len, - part->body->data)); + part->body->data)); part->body->print_body = &pjsip_print_text_body; part->body->clone_data = &pjsip_clone_text_data; @@ -723,9 +722,9 @@ static pjsip_multipart_part *parse_multipart_part(pj_pool_t *pool, /* Public function to parse multipart message bodies into its parts */ PJ_DEF(pjsip_msg_body*) pjsip_multipart_parse(pj_pool_t *pool, - char *buf, pj_size_t len, - const pjsip_media_type *ctype, - unsigned options) + char *buf, pj_size_t len, + const pjsip_media_type *ctype, + unsigned options) { pj_str_t boundary, delim; char *curptr, *endptr; @@ -742,59 +741,59 @@ PJ_DEF(pjsip_msg_body*) pjsip_multipart_parse(pj_pool_t *pool, boundary.slen = 0; ctype_param = pjsip_param_find(&ctype->param, &STR_BOUNDARY); if (ctype_param) { - boundary = ctype_param->value; - if (boundary.slen>2 && *boundary.ptr=='"') { - /* Remove quote */ - boundary.ptr++; - boundary.slen -= 2; - } - TRACE_((THIS_FILE, "Boundary is specified: '%.*s'", (int)boundary.slen, - boundary.ptr)); + boundary = ctype_param->value; + if (boundary.slen>2 && *boundary.ptr=='"') { + /* Remove quote */ + boundary.ptr++; + boundary.slen -= 2; + } + TRACE_((THIS_FILE, "Boundary is specified: '%.*s'", (int)boundary.slen, + boundary.ptr)); } if (!boundary.slen) { - /* Boundary not found or not specified. Try to be clever, get - * the boundary from the body. - */ - char *p=buf, *end=buf+len; - - PJ_LOG(4,(THIS_FILE, "Warning: boundary parameter not found or " - "not specified when parsing multipart body")); - - /* Find the first "--". This "--" must be right after a CRLF, unless - * it really appears at the start of the buffer. - */ - for (;;) { - while (p!=end && *p!='-') ++p; - - if (p == end) - break; - - if ((p+1buf && *(p-1)=='\n') || (p==buf))) - { - p+=2; - break; - } else { - ++p; - } - } - - if (p==end) { - /* Unable to determine boundary. Maybe this is not a multipart - * message? - */ - PJ_LOG(4,(THIS_FILE, "Error: multipart boundary not specified and" - " unable to calculate from the body")); - return NULL; - } - - boundary.ptr = p; - while (p!=end && !pj_isspace(*p)) ++p; - boundary.slen = p - boundary.ptr; - - TRACE_((THIS_FILE, "Boundary is calculated: '%.*s'", - (int)boundary.slen, boundary.ptr)); + /* Boundary not found or not specified. Try to be clever, get + * the boundary from the body. + */ + char *p=buf, *end=buf+len; + + PJ_LOG(4,(THIS_FILE, "Warning: boundary parameter not found or " + "not specified when parsing multipart body")); + + /* Find the first "--". This "--" must be right after a CRLF, unless + * it really appears at the start of the buffer. + */ + for (;;) { + while (p!=end && *p!='-') ++p; + + if (p == end) + break; + + if ((p+1buf && *(p-1)=='\n') || (p==buf))) + { + p+=2; + break; + } else { + ++p; + } + } + + if (p==end) { + /* Unable to determine boundary. Maybe this is not a multipart + * message? + */ + PJ_LOG(4,(THIS_FILE, "Error: multipart boundary not specified and" + " unable to calculate from the body")); + return NULL; + } + + boundary.ptr = p; + while (p!=end && !pj_isspace(*p)) ++p; + boundary.slen = p - boundary.ptr; + + TRACE_((THIS_FILE, "Boundary is calculated: '%.*s'", + (int)boundary.slen, boundary.ptr)); } @@ -811,87 +810,87 @@ PJ_DEF(pjsip_msg_body*) pjsip_multipart_parse(pj_pool_t *pool, curptr = buf; endptr = buf + len; { - pj_str_t strbody; + pj_str_t strbody; - strbody.ptr = buf; strbody.slen = len; - curptr = pj_strstr(&strbody, &delim); - if (!curptr) - return NULL; + strbody.ptr = buf; strbody.slen = len; + curptr = pj_strstr(&strbody, &delim); + if (!curptr) + return NULL; } body = pjsip_multipart_create(pool, ctype, &boundary); /* Save full raw body */ { - struct multipart_data *mp = (struct multipart_data*)body->data; - pj_strset(&mp->raw_data, buf, len); + struct multipart_data *mp = (struct multipart_data*)body->data; + pj_strset(&mp->raw_data, buf, len); } for (;;) { - char *start_body, *end_body; - pjsip_multipart_part *part; - - /* Eat the boundary */ - curptr += delim.slen; - if (*curptr=='-' && curptr start_body) { - /* The newline preceeding the delimiter is conceptually part of - * the delimiter, so trim it from the body. - */ - if (*(end_body-1) == '\n') - --end_body; - if (end_body > start_body && *(end_body-1) == '\r') - --end_body; + /* The newline preceeding the delimiter is conceptually part of + * the delimiter, so trim it from the body. + */ + if (*(end_body-1) == '\n') + --end_body; + if (end_body > start_body && *(end_body-1) == '\r') + --end_body; } - /* Now that we have determined the part's boundary, parse it - * to get the header and body part of the part. - */ - part = parse_multipart_part(pool, start_body, end_body - start_body, - ctype); - if (part) { - TRACE_((THIS_FILE, "Adding part")); - pjsip_multipart_add_part(pool, body, part); - } else { - PJ_LOG(2, (THIS_FILE, "Failed to add part")); - } + /* Now that we have determined the part's boundary, parse it + * to get the header and body part of the part. + */ + part = parse_multipart_part(pool, start_body, end_body - start_body, + ctype); + if (part) { + TRACE_((THIS_FILE, "Adding part")); + pjsip_multipart_add_part(pool, body, part); + } else { + PJ_LOG(2, (THIS_FILE, "Failed to add part")); + } } TRACE_((THIS_FILE, "pjsip_multipart_parse finished: %p", body)); @@ -900,8 +899,8 @@ PJ_DEF(pjsip_msg_body*) pjsip_multipart_parse(pj_pool_t *pool, PJ_DEF(pj_status_t) pjsip_multipart_get_raw( pjsip_msg_body *mp, - pj_str_t *boundary, - pj_str_t *raw_data) + pj_str_t *boundary, + pj_str_t *raw_data) { struct multipart_data *m_data; @@ -914,10 +913,10 @@ PJ_DEF(pj_status_t) pjsip_multipart_get_raw( pjsip_msg_body *mp, m_data = (struct multipart_data*)mp->data; if (boundary) - *boundary = m_data->boundary; + *boundary = m_data->boundary; if (raw_data) - *raw_data = m_data->raw_data; + *raw_data = m_data->raw_data; return PJ_SUCCESS; } diff --git a/pjsip/src/pjsip/sip_parser.c b/pjsip/src/pjsip/sip_parser.c index 943cad358d..b17afde0ec 100644 --- a/pjsip/src/pjsip/sip_parser.c +++ b/pjsip/src/pjsip/sip_parser.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,22 +35,22 @@ #include #include -#define THIS_FILE "sip_parser.c" +#define THIS_FILE "sip_parser.c" #define ALNUM -#define RESERVED ";/?:@&=+$," -#define MARK "-_.!~*'()" -#define UNRESERVED ALNUM MARK -#define ESCAPED "%" -#define USER_UNRESERVED "&=+$,;?/" -#define PASS "&=+$," -#define TOKEN "-.!%*_`'~+" /* '=' was removed for parsing - * param */ -#define HOST "_-." -#define HEX_DIGIT "abcdefABCDEF" -#define PARAM_CHAR "[]/:&+$" UNRESERVED ESCAPED -#define HNV_UNRESERVED "[]/?:+$" -#define HDR_CHAR HNV_UNRESERVED UNRESERVED ESCAPED +#define RESERVED ";/?:@&=+$," +#define MARK "-_.!~*'()" +#define UNRESERVED ALNUM MARK +#define ESCAPED "%" +#define USER_UNRESERVED "&=+$,;?/" +#define PASS "&=+$," +#define TOKEN "-.!%*_`'~+" /* '=' was removed for parsing + * param */ +#define HOST "_-." +#define HEX_DIGIT "abcdefABCDEF" +#define PARAM_CHAR "[]/:&+$" UNRESERVED ESCAPED +#define HNV_UNRESERVED "[]/?:+$" +#define HDR_CHAR HNV_UNRESERVED UNRESERVED ESCAPED /* A generic URI can consist of (For a complete BNF see RFC 2396): #?;:@&=+-_.!~*'()%$,/ @@ -60,17 +59,17 @@ #define UNREACHED(expr) -#define IS_NEWLINE(c) ((c)=='\r' || (c)=='\n') -#define IS_SPACE(c) ((c)==' ' || (c)=='\t') +#define IS_NEWLINE(c) ((c)=='\r' || (c)=='\n') +#define IS_SPACE(c) ((c)==' ' || (c)=='\t') /* * Header parser records. */ typedef struct handler_rec { - char hname[PJSIP_MAX_HNAME_LEN+1]; - pj_size_t hname_len; - pj_uint32_t hname_hash; + char hname[PJSIP_MAX_HNAME_LEN+1]; + pj_size_t hname_len; + pj_uint32_t hname_hash; pjsip_parse_hdr_func *handler; } handler_rec; @@ -83,7 +82,7 @@ static int parser_is_initialized; */ typedef struct uri_parser_rec { - pj_str_t scheme; + pj_str_t scheme; pjsip_parse_uri_func *parse; } uri_parser_rec; @@ -99,21 +98,21 @@ int PJSIP_EINVAL_ERR_EXCEPTION = -2; /* Parser constants */ static pjsip_parser_const_t pconst = { - { "user", 4}, /* pjsip_USER_STR */ - { "method", 6}, /* pjsip_METHOD_STR */ - { "transport", 9}, /* pjsip_TRANSPORT_STR */ - { "maddr", 5 }, /* pjsip_MADDR_STR */ - { "lr", 2 }, /* pjsip_LR_STR */ - { "sip", 3 }, /* pjsip_SIP_STR */ - { "sips", 4 }, /* pjsip_SIPS_STR */ - { "tel", 3 }, /* pjsip_TEL_STR */ - { "branch", 6 }, /* pjsip_BRANCH_STR */ - { "ttl", 3 }, /* pjsip_TTL_STR */ - { "received", 8 }, /* pjsip_RECEIVED_STR */ - { "q", 1 }, /* pjsip_Q_STR */ - { "expires", 7 }, /* pjsip_EXPIRES_STR */ - { "tag", 3 }, /* pjsip_TAG_STR */ - { "rport", 5} /* pjsip_RPORT_STR */ + { "user", 4}, /* pjsip_USER_STR */ + { "method", 6}, /* pjsip_METHOD_STR */ + { "transport", 9}, /* pjsip_TRANSPORT_STR */ + { "maddr", 5 }, /* pjsip_MADDR_STR */ + { "lr", 2 }, /* pjsip_LR_STR */ + { "sip", 3 }, /* pjsip_SIP_STR */ + { "sips", 4 }, /* pjsip_SIPS_STR */ + { "tel", 3 }, /* pjsip_TEL_STR */ + { "branch", 6 }, /* pjsip_BRANCH_STR */ + { "ttl", 3 }, /* pjsip_TTL_STR */ + { "received", 8 }, /* pjsip_RECEIVED_STR */ + { "q", 1 }, /* pjsip_Q_STR */ + { "expires", 7 }, /* pjsip_EXPIRES_STR */ + { "tag", 3 }, /* pjsip_TAG_STR */ + { "rport", 5} /* pjsip_RPORT_STR */ }; /* Character Input Specification buffer. */ @@ -124,47 +123,47 @@ static pj_cis_buf_t cis_buf; * Forward decl. */ static pjsip_msg * int_parse_msg( pjsip_parse_ctx *ctx, - pjsip_parser_err_report *err_list); -static void int_parse_param( pj_scanner *scanner, - pj_pool_t *pool, - pj_str_t *pname, - pj_str_t *pvalue, - unsigned option); -static void int_parse_uri_param( pj_scanner *scanner, - pj_pool_t *pool, - pj_str_t *pname, - pj_str_t *pvalue, - unsigned option); -static void int_parse_hparam( pj_scanner *scanner, - pj_pool_t *pool, - pj_str_t *hname, - pj_str_t *hvalue ); + pjsip_parser_err_report *err_list); +static void int_parse_param( pj_scanner *scanner, + pj_pool_t *pool, + pj_str_t *pname, + pj_str_t *pvalue, + unsigned option); +static void int_parse_uri_param( pj_scanner *scanner, + pj_pool_t *pool, + pj_str_t *pname, + pj_str_t *pvalue, + unsigned option); +static void int_parse_hparam( pj_scanner *scanner, + pj_pool_t *pool, + pj_str_t *hname, + pj_str_t *hvalue ); static void int_parse_req_line( pj_scanner *scanner, - pj_pool_t *pool, - pjsip_request_line *req_line); + pj_pool_t *pool, + pjsip_request_line *req_line); static int int_is_next_user( pj_scanner *scanner); -static void int_parse_status_line( pj_scanner *scanner, - pjsip_status_line *line); -static void int_parse_user_pass( pj_scanner *scanner, - pj_pool_t *pool, - pj_str_t *user, - pj_str_t *pass); -static void int_parse_uri_host_port( pj_scanner *scanner, - pj_str_t *p_host, - int *p_port); +static void int_parse_status_line( pj_scanner *scanner, + pjsip_status_line *line); +static void int_parse_user_pass( pj_scanner *scanner, + pj_pool_t *pool, + pj_str_t *user, + pj_str_t *pass); +static void int_parse_uri_host_port( pj_scanner *scanner, + pj_str_t *p_host, + int *p_port); static pjsip_uri * int_parse_uri_or_name_addr( pj_scanner *scanner, - pj_pool_t *pool, + pj_pool_t *pool, unsigned option); -static void* int_parse_sip_url( pj_scanner *scanner, - pj_pool_t *pool, - pj_bool_t parse_params); +static void* int_parse_sip_url( pj_scanner *scanner, + pj_pool_t *pool, + pj_bool_t parse_params); static pjsip_name_addr * int_parse_name_addr( pj_scanner *scanner, - pj_pool_t *pool ); -static void* int_parse_other_uri(pj_scanner *scanner, - pj_pool_t *pool, - pj_bool_t parse_params); -static void parse_hdr_end( pj_scanner *scanner ); + pj_pool_t *pool ); +static void* int_parse_other_uri(pj_scanner *scanner, + pj_pool_t *pool, + pj_bool_t parse_params); +static void parse_hdr_end( pj_scanner *scanner ); static pjsip_hdr* parse_hdr_accept( pjsip_parse_ctx *ctx ); static pjsip_hdr* parse_hdr_allow( pjsip_parse_ctx *ctx ); @@ -196,10 +195,10 @@ static unsigned long pj_strtoul_mindigit(const pj_str_t *str, value = 0; for (i=0; i<(unsigned)str->slen; ++i) { - value = value * 10 + (str->ptr[i] - '0'); + value = value * 10 + (str->ptr[i] - '0'); } for (; i retval) { - *value = min_val; - status = PJ_ETOOSMALL; - } else if (retval > max_val) { - *value = max_val; - status = PJ_ETOOBIG; - } else - *value = (int)retval; + if (min_val > retval) { + *value = min_val; + status = PJ_ETOOSMALL; + } else if (retval > max_val) { + *value = max_val; + status = PJ_ETOOBIG; + } else + *value = (int)retval; } if (status != PJ_SUCCESS) - on_str_parse_error(str, status); + on_str_parse_error(str, status); } /* Get parser constants. */ @@ -293,9 +292,9 @@ PJ_DEF(const pjsip_parser_const_t*) pjsip_parser_const(void) /* Concatenate unrecognized params into single string. */ PJ_DEF(void) pjsip_concat_param_imp(pj_str_t *param, pj_pool_t *pool, - const pj_str_t *pname, - const pj_str_t *pvalue, - int sepchar) + const pj_str_t *pname, + const pj_str_t *pvalue, + int sepchar) { char *new_param, *p; pj_size_t len; @@ -304,18 +303,18 @@ PJ_DEF(void) pjsip_concat_param_imp(pj_str_t *param, pj_pool_t *pool, p = new_param = (char*) pj_pool_alloc(pool, len); if (param->slen) { - pj_size_t old_len = param->slen; - pj_memcpy(p, param->ptr, old_len); - p += old_len; + pj_size_t old_len = param->slen; + pj_memcpy(p, param->ptr, old_len); + p += old_len; } *p++ = (char)sepchar; pj_memcpy(p, pname->ptr, pname->slen); p += pname->slen; if (pvalue->slen) { - *p++ = '='; - pj_memcpy(p, pvalue->ptr, pvalue->slen); - p += pvalue->slen; + *p++ = '='; + pj_memcpy(p, pvalue->ptr, pvalue->slen); + p += pvalue->slen; } *p = '\0'; @@ -334,7 +333,7 @@ static pj_status_t init_parser() */ pj_assert (PJSIP_SYN_ERR_EXCEPTION == -1); status = pj_exception_id_alloc("PJSIP syntax error", - &PJSIP_SYN_ERR_EXCEPTION); + &PJSIP_SYN_ERR_EXCEPTION); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); /* @@ -342,7 +341,7 @@ static pj_status_t init_parser() */ pj_assert (PJSIP_EINVAL_ERR_EXCEPTION == -2); status = pj_exception_id_alloc("PJSIP invalid value error", - &PJSIP_EINVAL_ERR_EXCEPTION); + &PJSIP_EINVAL_ERR_EXCEPTION); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); /* @@ -549,7 +548,7 @@ void init_sip_parser(void) { pj_enter_critical_section(); if (++parser_is_initialized == 1) { - init_parser(); + init_parser(); } pj_leave_critical_section(); } @@ -558,20 +557,20 @@ void deinit_sip_parser(void) { pj_enter_critical_section(); if (--parser_is_initialized == 0) { - /* Clear header handlers */ - pj_bzero(handler, sizeof(handler)); - handler_count = 0; + /* Clear header handlers */ + pj_bzero(handler, sizeof(handler)); + handler_count = 0; - /* Clear URI handlers */ - pj_bzero(uri_handler, sizeof(uri_handler)); - uri_handler_count = 0; + /* Clear URI handlers */ + pj_bzero(uri_handler, sizeof(uri_handler)); + uri_handler_count = 0; - /* Deregister exception ID */ - pj_exception_id_free(PJSIP_SYN_ERR_EXCEPTION); - PJSIP_SYN_ERR_EXCEPTION = -1; + /* Deregister exception ID */ + pj_exception_id_free(PJSIP_SYN_ERR_EXCEPTION); + PJSIP_SYN_ERR_EXCEPTION = -1; - pj_exception_id_free(PJSIP_EINVAL_ERR_EXCEPTION); - PJSIP_EINVAL_ERR_EXCEPTION = -2; + pj_exception_id_free(PJSIP_EINVAL_ERR_EXCEPTION); + PJSIP_EINVAL_ERR_EXCEPTION = -2; } pj_leave_critical_section(); } @@ -582,24 +581,24 @@ void deinit_sip_parser(void) * - >0 if handler is 'greater' than header name. */ PJ_INLINE(int) compare_handler( const handler_rec *r1, - const char *name, - pj_size_t name_len, - pj_uint32_t hash ) + const char *name, + pj_size_t name_len, + pj_uint32_t hash ) { PJ_UNUSED_ARG(name_len); /* Compare hashed value. */ if (r1->hname_hash < hash) - return -1; + return -1; if (r1->hname_hash > hash) - return 1; + return 1; /* Compare length. */ /* if (r1->hname_len < name_len) - return -1; + return -1; if (r1->hname_len > name_len) - return 1; + return 1; */ /* Equal length and equal hash. compare the strings. */ @@ -610,20 +609,20 @@ PJ_INLINE(int) compare_handler( const handler_rec *r1, static pj_status_t int_register_parser( const char *name, pjsip_parse_hdr_func *fptr ) { - unsigned pos; + unsigned pos; handler_rec rec; if (handler_count >= PJ_ARRAY_SIZE(handler)) { - pj_assert(!"Too many handlers!"); - return PJ_ETOOMANY; + pj_assert(!"Too many handlers!"); + return PJ_ETOOMANY; } /* Initialize temporary handler. */ rec.handler = fptr; rec.hname_len = strlen(name); if (rec.hname_len >= sizeof(rec.hname)) { - pj_assert(!"Header name is too long!"); - return PJ_ENAMETOOLONG; + pj_assert(!"Header name is too long!"); + return PJ_ENAMETOOLONG; } /* Copy name. */ pj_memcpy(rec.hname, name, rec.hname_len); @@ -634,21 +633,21 @@ static pj_status_t int_register_parser( const char *name, /* Get the pos to insert the new handler. */ for (pos=0; pos < handler_count; ++pos) { - int d; - d = compare_handler(&handler[pos], rec.hname, rec.hname_len, + int d; + d = compare_handler(&handler[pos], rec.hname, rec.hname_len, rec.hname_hash); - if (d == 0) { - pj_assert(0); - return PJ_EEXISTS; - } - if (d > 0) { - break; - } + if (d == 0) { + pj_assert(0); + return PJ_EEXISTS; + } + if (d > 0) { + break; + } } /* Shift handlers. */ if (pos != handler_count) { - pj_memmove( &handler[pos+1], &handler[pos], + pj_memmove( &handler[pos+1], &handler[pos], (handler_count-pos)*sizeof(handler_rec)); } /* Add new handler. */ @@ -662,8 +661,8 @@ static pj_status_t int_register_parser( const char *name, * then two instances of handler will be registered. */ PJ_DEF(pj_status_t) pjsip_register_hdr_parser( const char *hname, - const char *hshortname, - pjsip_parse_hdr_func *fptr) + const char *hshortname, + pjsip_parse_hdr_func *fptr) { unsigned i; pj_size_t len; @@ -673,26 +672,26 @@ PJ_DEF(pj_status_t) pjsip_register_hdr_parser( const char *hname, /* Check that name is not too long */ len = pj_ansi_strlen(hname); if (len > PJSIP_MAX_HNAME_LEN) { - pj_assert(!"Header name is too long!"); - return PJ_ENAMETOOLONG; + pj_assert(!"Header name is too long!"); + return PJ_ENAMETOOLONG; } /* Register the normal Mixed-Case name */ status = int_register_parser(hname, fptr); if (status != PJ_SUCCESS) { - return status; + return status; } /* Get the lower-case name */ for (i=0; i 0; ) { - unsigned half = n / 2; - handler_rec *mid = first + half; + unsigned half = n / 2; + handler_rec *mid = first + half; - comp = compare_handler(mid, hname->ptr, hname->slen, hash); - if (comp < 0) { - first = ++mid; - n -= half + 1; - } else if (comp==0) { - first = mid; - break; - } else { - n = half; - } + comp = compare_handler(mid, hname->ptr, hname->slen, hash); + if (comp < 0) { + first = ++mid; + n -= half + 1; + } else if (comp==0) { + first = mid; + break; + } else { + n = half; + } } return comp==0 ? first->handler : NULL; @@ -747,7 +746,7 @@ static pjsip_parse_hdr_func* find_handler(const pj_str_t *hname) pjsip_parse_hdr_func *func; if (hname->slen >= PJSIP_MAX_HNAME_LEN) { - /* Guaranteed not to be able to find handler. */ + /* Guaranteed not to be able to find handler. */ return NULL; } @@ -755,7 +754,7 @@ static pjsip_parse_hdr_func* find_handler(const pj_str_t *hname) hash = pj_hash_calc(0, hname->ptr, (unsigned)hname->slen); func = find_handler_imp(hash, hname); if (func) - return func; + return func; /* If not found, try converting the header name to lowercase and @@ -773,18 +772,18 @@ static pjsip_parse_uri_func* find_uri_handler(const pj_str_t *scheme) { unsigned i; for (i=0; i= PJ_ARRAY_SIZE(uri_handler)) - return PJ_ETOOMANY; + return PJ_ETOOMANY; uri_handler[uri_handler_count].scheme = pj_str((char*)scheme); uri_handler[uri_handler_count].parse = func; @@ -796,7 +795,7 @@ PJ_DEF(pj_status_t) pjsip_register_uri_parser( char *scheme, /* Public function to parse SIP message. */ PJ_DEF(pjsip_msg*) pjsip_parse_msg( pj_pool_t *pool, char *buf, pj_size_t size, - pjsip_parser_err_report *err_list) + pjsip_parser_err_report *err_list) { pjsip_msg *msg = NULL; pj_scanner scanner; @@ -837,7 +836,7 @@ PJ_DEF(pjsip_msg *) pjsip_parse_rdata( char *buf, pj_size_t size, /* Determine if a message has been received. */ PJ_DEF(pj_status_t) pjsip_find_msg( const char *buf, pj_size_t size, - pj_bool_t is_datagram, pj_size_t *msg_size) + pj_bool_t is_datagram, pj_size_t *msg_size) { #if PJ_HAS_TCP const char *volatile hdr_end; @@ -853,7 +852,7 @@ PJ_DEF(pj_status_t) pjsip_find_msg( const char *buf, pj_size_t size, /* For datagram, the whole datagram IS the message. */ if (is_datagram) { - return PJ_SUCCESS; + return PJ_SUCCESS; } @@ -864,7 +863,7 @@ PJ_DEF(pj_status_t) pjsip_find_msg( const char *buf, pj_size_t size, cur_msg.ptr = (char*)buf; cur_msg.slen = size; pos = pj_strstr(&cur_msg, &end_hdr); if (pos == NULL) { - return PJSIP_EPARTIALMSG; + return PJSIP_EPARTIALMSG; } hdr_end = pos+1; @@ -873,73 +872,73 @@ PJ_DEF(pj_status_t) pjsip_find_msg( const char *buf, pj_size_t size, /* Find "Content-Length" header the hard way. */ line = pj_strchr(&cur_msg, '\n'); while (line && line < hdr_end) { - ++line; - if ( ((*line=='C' || *line=='c') && + ++line; + if ( ((*line=='C' || *line=='c') && strnicmp_alnum(line, "Content-Length", 14) == 0) || - ((*line=='l' || *line=='L') && + ((*line=='l' || *line=='L') && (*(line+1)==' ' || *(line+1)=='\t' || *(line+1)==':'))) - { - /* Try to parse the header. */ - pj_scanner scanner; - PJ_USE_EXCEPTION; + { + /* Try to parse the header. */ + pj_scanner scanner; + PJ_USE_EXCEPTION; - /* The buffer passed to the scanner is not NULL terminated, + /* The buffer passed to the scanner is not NULL terminated, * but should be safe. See ticket #2063. - */ - pj_scan_init(&scanner, (char*)line, hdr_end-line, - PJ_SCAN_AUTOSKIP_WS_HEADER, &on_syntax_error); - - PJ_TRY { - pj_str_t str_clen; - - /* Get "Content-Length" or "L" name */ - if (*line=='C' || *line=='c') - pj_scan_advance_n(&scanner, 14, PJ_TRUE); - else if (*line=='l' || *line=='L') - pj_scan_advance_n(&scanner, 1, PJ_TRUE); - - /* Get colon */ - if (pj_scan_get_char(&scanner) != ':') { - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); - } - - /* Get number */ - pj_scan_get(&scanner, &pconst.pjsip_DIGIT_SPEC, &str_clen); - - /* Get newline. */ - pj_scan_get_newline(&scanner); - - /* Found a valid Content-Length header. */ - strtoi_validate(&str_clen, PJSIP_MIN_CONTENT_LENGTH, - PJSIP_MAX_CONTENT_LENGTH, &content_length); - } - PJ_CATCH_ANY { - int eid = PJ_GET_EXCEPTION(); - if (eid == PJSIP_SYN_ERR_EXCEPTION) { - status = PJSIP_EMISSINGHDR; - } else if (eid == PJSIP_EINVAL_ERR_EXCEPTION) { - status = PJSIP_EINVALIDHDR; - } - content_length = -1; - } - PJ_END - - pj_scan_fini(&scanner); - } - - /* Found valid Content-Length? */ - if (content_length != -1) - break; - - /* Go to next line. */ - cur_msg.slen -= (line - cur_msg.ptr); - cur_msg.ptr = (char*)line; - line = pj_strchr(&cur_msg, '\n'); + */ + pj_scan_init(&scanner, (char*)line, hdr_end-line, + PJ_SCAN_AUTOSKIP_WS_HEADER, &on_syntax_error); + + PJ_TRY { + pj_str_t str_clen; + + /* Get "Content-Length" or "L" name */ + if (*line=='C' || *line=='c') + pj_scan_advance_n(&scanner, 14, PJ_TRUE); + else if (*line=='l' || *line=='L') + pj_scan_advance_n(&scanner, 1, PJ_TRUE); + + /* Get colon */ + if (pj_scan_get_char(&scanner) != ':') { + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + } + + /* Get number */ + pj_scan_get(&scanner, &pconst.pjsip_DIGIT_SPEC, &str_clen); + + /* Get newline. */ + pj_scan_get_newline(&scanner); + + /* Found a valid Content-Length header. */ + strtoi_validate(&str_clen, PJSIP_MIN_CONTENT_LENGTH, + PJSIP_MAX_CONTENT_LENGTH, &content_length); + } + PJ_CATCH_ANY { + int eid = PJ_GET_EXCEPTION(); + if (eid == PJSIP_SYN_ERR_EXCEPTION) { + status = PJSIP_EMISSINGHDR; + } else if (eid == PJSIP_EINVAL_ERR_EXCEPTION) { + status = PJSIP_EINVALIDHDR; + } + content_length = -1; + } + PJ_END + + pj_scan_fini(&scanner); + } + + /* Found valid Content-Length? */ + if (content_length != -1) + break; + + /* Go to next line. */ + cur_msg.slen -= (line - cur_msg.ptr); + cur_msg.ptr = (char*)line; + line = pj_strchr(&cur_msg, '\n'); } /* Found Content-Length? */ if (content_length == -1) { - return status; + return status; } /* Enough packet received? */ @@ -955,8 +954,8 @@ PJ_DEF(pj_status_t) pjsip_find_msg( const char *buf, pj_size_t size, /* Public function to parse URI */ PJ_DEF(pjsip_uri*) pjsip_parse_uri( pj_pool_t *pool, - char *buf, pj_size_t size, - unsigned option) + char *buf, pj_size_t size, + unsigned option) { pj_scanner scanner; pjsip_uri *uri = NULL; @@ -966,18 +965,18 @@ PJ_DEF(pjsip_uri*) pjsip_parse_uri( pj_pool_t *pool, PJ_TRY { - uri = int_parse_uri_or_name_addr(&scanner, pool, option); + uri = int_parse_uri_or_name_addr(&scanner, pool, option); } PJ_CATCH_ANY { - uri = NULL; + uri = NULL; } PJ_END; /* Must have exhausted all inputs. */ if (pj_scan_is_eof(&scanner) || IS_NEWLINE(*scanner.curptr)) { - /* Success. */ - pj_scan_fini(&scanner); - return uri; + /* Success. */ + pj_scan_fini(&scanner); + return uri; } /* Still have some characters unparsed. */ @@ -994,10 +993,10 @@ static void parse_sip_version(pj_scanner *scanner) pj_scan_get( scanner, &pconst.pjsip_ALPHA_SPEC, &sip); if (pj_scan_get_char(scanner) != '/') - on_syntax_error(scanner); + on_syntax_error(scanner); pj_scan_get_n( scanner, 3, &version); if (pj_stricmp(&sip, &SIP) || pj_stricmp(&version, &V2)) - on_syntax_error(scanner); + on_syntax_error(scanner); } static pj_bool_t is_next_sip_version(pj_scanner *scanner) @@ -1017,7 +1016,7 @@ static pj_bool_t is_next_sip_version(pj_scanner *scanner) /* Internal function to parse SIP message */ static pjsip_msg *int_parse_msg( pjsip_parse_ctx *ctx, - pjsip_parser_err_report *err_list) + pjsip_parser_err_report *err_list) { /* These variables require "volatile" so their values get * preserved when re-entering the PJ_TRY block after an error. @@ -1036,172 +1035,172 @@ static pjsip_msg *int_parse_msg( pjsip_parse_ctx *ctx, retry_parse: PJ_TRY { - if (parsing_headers) - goto parse_headers; - - /* Skip leading newlines. */ - while (IS_NEWLINE(*scanner->curptr)) { - pj_scan_get_newline(scanner); - } - - /* Check if we still have valid packet. - * Sometimes endpoints just send blank (CRLF) packets just to keep - * NAT bindings open. - */ - if (pj_scan_is_eof(scanner)) - return NULL; - - /* Parse request or status line */ - if (is_next_sip_version(scanner)) { - msg = pjsip_msg_create(pool, PJSIP_RESPONSE_MSG); - int_parse_status_line( scanner, &msg->line.status ); - } else { - msg = pjsip_msg_create(pool, PJSIP_REQUEST_MSG); - int_parse_req_line(scanner, pool, &msg->line.req ); - } - - parsing_headers = PJ_TRUE; + if (parsing_headers) + goto parse_headers; + + /* Skip leading newlines. */ + while (IS_NEWLINE(*scanner->curptr)) { + pj_scan_get_newline(scanner); + } + + /* Check if we still have valid packet. + * Sometimes endpoints just send blank (CRLF) packets just to keep + * NAT bindings open. + */ + if (pj_scan_is_eof(scanner)) + return NULL; + + /* Parse request or status line */ + if (is_next_sip_version(scanner)) { + msg = pjsip_msg_create(pool, PJSIP_RESPONSE_MSG); + int_parse_status_line( scanner, &msg->line.status ); + } else { + msg = pjsip_msg_create(pool, PJSIP_REQUEST_MSG); + int_parse_req_line(scanner, pool, &msg->line.req ); + } + + parsing_headers = PJ_TRUE; parse_headers: - /* Parse headers. */ - do { - pjsip_parse_hdr_func * func; - pjsip_hdr *hdr = NULL; - - /* Init hname just in case parsing fails. - * Ref: PROTOS #2412 - */ - hname.slen = 0; - - /* Get hname. */ - pj_scan_get( scanner, &pconst.pjsip_TOKEN_SPEC, &hname); - if (pj_scan_get_char( scanner ) != ':') { - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); - } - - /* Find handler. */ - func = find_handler(&hname); - - /* Call the handler if found. - * If no handler is found, then treat the header as generic - * hname/hvalue pair. - */ - if (func) { - hdr = (*func)(ctx); - - /* Note: - * hdr MAY BE NULL, if parsing does not yield a new header - * instance, e.g. the values have been added to existing - * header. See https://github.com/pjsip/pjproject/issues/940 - */ - - /* Check if we've just parsed a Content-Type header. - * We will check for a message body if we've got Content-Type - * header. - */ - if (hdr && hdr->type == PJSIP_H_CONTENT_TYPE) { - ctype_hdr = (pjsip_ctype_hdr*)hdr; - } - - } else { - hdr = parse_hdr_generic_string(ctx); - hdr->name = hdr->sname = hname; - } - - /* Single parse of header line can produce multiple headers. - * For example, if one Contact: header contains Contact list - * separated by comma, then these Contacts will be split into - * different Contact headers. - * So here we must insert list instead of just insert one header. - */ - if (hdr) - pj_list_insert_nodes_before(&msg->hdr, hdr); - - /* Parse until EOF or an empty line is found. */ - } while (!pj_scan_is_eof(scanner) && !IS_NEWLINE(*scanner->curptr)); - - parsing_headers = PJ_FALSE; - - /* If empty line is found, eat it. */ - if (!pj_scan_is_eof(scanner)) { - if (IS_NEWLINE(*scanner->curptr)) { - pj_scan_get_newline(scanner); - } - } - - /* If we have Content-Type header, treat the rest of the message - * as body. - */ - if (ctype_hdr && scanner->curptr!=scanner->end) { - /* New: if Content-Type indicates that this is a multipart - * message body, parse it. - */ - const pj_str_t STR_MULTIPART = { "multipart", 9 }; - pjsip_msg_body *body; - - if (pj_stricmp(&ctype_hdr->media.type, &STR_MULTIPART)==0) { - body = pjsip_multipart_parse(pool, scanner->curptr, - scanner->end - scanner->curptr, - &ctype_hdr->media, 0); - } else { - body = PJ_POOL_ALLOC_T(pool, pjsip_msg_body); - pjsip_media_type_cp(pool, &body->content_type, - &ctype_hdr->media); - - body->data = scanner->curptr; - body->len = (unsigned)(scanner->end - scanner->curptr); - body->print_body = &pjsip_print_text_body; - body->clone_data = &pjsip_clone_text_data; - } - - msg->body = body; - } + /* Parse headers. */ + do { + pjsip_parse_hdr_func * func; + pjsip_hdr *hdr = NULL; + + /* Init hname just in case parsing fails. + * Ref: PROTOS #2412 + */ + hname.slen = 0; + + /* Get hname. */ + pj_scan_get( scanner, &pconst.pjsip_TOKEN_SPEC, &hname); + if (pj_scan_get_char( scanner ) != ':') { + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + } + + /* Find handler. */ + func = find_handler(&hname); + + /* Call the handler if found. + * If no handler is found, then treat the header as generic + * hname/hvalue pair. + */ + if (func) { + hdr = (*func)(ctx); + + /* Note: + * hdr MAY BE NULL, if parsing does not yield a new header + * instance, e.g. the values have been added to existing + * header. See https://github.com/pjsip/pjproject/issues/940 + */ + + /* Check if we've just parsed a Content-Type header. + * We will check for a message body if we've got Content-Type + * header. + */ + if (hdr && hdr->type == PJSIP_H_CONTENT_TYPE) { + ctype_hdr = (pjsip_ctype_hdr*)hdr; + } + + } else { + hdr = parse_hdr_generic_string(ctx); + hdr->name = hdr->sname = hname; + } + + /* Single parse of header line can produce multiple headers. + * For example, if one Contact: header contains Contact list + * separated by comma, then these Contacts will be split into + * different Contact headers. + * So here we must insert list instead of just insert one header. + */ + if (hdr) + pj_list_insert_nodes_before(&msg->hdr, hdr); + + /* Parse until EOF or an empty line is found. */ + } while (!pj_scan_is_eof(scanner) && !IS_NEWLINE(*scanner->curptr)); + + parsing_headers = PJ_FALSE; + + /* If empty line is found, eat it. */ + if (!pj_scan_is_eof(scanner)) { + if (IS_NEWLINE(*scanner->curptr)) { + pj_scan_get_newline(scanner); + } + } + + /* If we have Content-Type header, treat the rest of the message + * as body. + */ + if (ctype_hdr && scanner->curptr!=scanner->end) { + /* New: if Content-Type indicates that this is a multipart + * message body, parse it. + */ + const pj_str_t STR_MULTIPART = { "multipart", 9 }; + pjsip_msg_body *body; + + if (pj_stricmp(&ctype_hdr->media.type, &STR_MULTIPART)==0) { + body = pjsip_multipart_parse(pool, scanner->curptr, + scanner->end - scanner->curptr, + &ctype_hdr->media, 0); + } else { + body = PJ_POOL_ALLOC_T(pool, pjsip_msg_body); + pjsip_media_type_cp(pool, &body->content_type, + &ctype_hdr->media); + + body->data = scanner->curptr; + body->len = (unsigned)(scanner->end - scanner->curptr); + body->print_body = &pjsip_print_text_body; + body->clone_data = &pjsip_clone_text_data; + } + + msg->body = body; + } } PJ_CATCH_ANY { - /* Exception was thrown during parsing. - * Skip until newline, and parse next header. - */ - if (err_list) { - pjsip_parser_err_report *err_info; - - err_info = PJ_POOL_ALLOC_T(pool, pjsip_parser_err_report); - err_info->except_code = PJ_GET_EXCEPTION(); - err_info->line = scanner->line; - /* Scanner's column is zero based, so add 1 */ - err_info->col = pj_scan_get_col(scanner) + 1; - if (parsing_headers) - err_info->hname = hname; - else if (msg && msg->type == PJSIP_REQUEST_MSG) - err_info->hname = pj_str("Request Line"); - else if (msg && msg->type == PJSIP_RESPONSE_MSG) - err_info->hname = pj_str("Status Line"); - else - err_info->hname.slen = 0; - - pj_list_insert_before(err_list, err_info); - } - - if (parsing_headers) { - if (!pj_scan_is_eof(scanner)) { - /* Skip until next line. - * Watch for header continuation. - */ - do { - pj_scan_skip_line(scanner); - } while (IS_SPACE(*scanner->curptr)); - } - - /* Restore flag. Flag may be set in int_parse_sip_url() */ - scanner->skip_ws = PJ_SCAN_AUTOSKIP_WS_HEADER; - - /* Continue parse next header, if any. */ - if (!pj_scan_is_eof(scanner) && !IS_NEWLINE(*scanner->curptr)) { - goto retry_parse; - } - } - - msg = NULL; + /* Exception was thrown during parsing. + * Skip until newline, and parse next header. + */ + if (err_list) { + pjsip_parser_err_report *err_info; + + err_info = PJ_POOL_ALLOC_T(pool, pjsip_parser_err_report); + err_info->except_code = PJ_GET_EXCEPTION(); + err_info->line = scanner->line; + /* Scanner's column is zero based, so add 1 */ + err_info->col = pj_scan_get_col(scanner) + 1; + if (parsing_headers) + err_info->hname = hname; + else if (msg && msg->type == PJSIP_REQUEST_MSG) + err_info->hname = pj_str("Request Line"); + else if (msg && msg->type == PJSIP_RESPONSE_MSG) + err_info->hname = pj_str("Status Line"); + else + err_info->hname.slen = 0; + + pj_list_insert_before(err_list, err_info); + } + + if (parsing_headers) { + if (!pj_scan_is_eof(scanner)) { + /* Skip until next line. + * Watch for header continuation. + */ + do { + pj_scan_skip_line(scanner); + } while (IS_SPACE(*scanner->curptr)); + } + + /* Restore flag. Flag may be set in int_parse_sip_url() */ + scanner->skip_ws = PJ_SCAN_AUTOSKIP_WS_HEADER; + + /* Continue parse next header, if any. */ + if (!pj_scan_is_eof(scanner) && !IS_NEWLINE(*scanner->curptr)) { + goto retry_parse; + } + } + + msg = NULL; } PJ_END; @@ -1211,15 +1210,15 @@ static pjsip_msg *int_parse_msg( pjsip_parse_ctx *ctx, /* Parse parameter (pname ["=" pvalue]). */ static void parse_param_imp( pj_scanner *scanner, pj_pool_t *pool, - pj_str_t *pname, pj_str_t *pvalue, - const pj_cis_t *spec, const pj_cis_t *esc_spec, - unsigned option) + pj_str_t *pname, pj_str_t *pvalue, + const pj_cis_t *spec, const pj_cis_t *esc_spec, + unsigned option) { /* pname */ if (!esc_spec) { - pj_scan_get(scanner, spec, pname); + pj_scan_get(scanner, spec, pname); } else { - parser_get_and_unescape(scanner, pool, spec, esc_spec, pname); + parser_get_and_unescape(scanner, pool, spec, esc_spec, pname); } /* init pvalue */ @@ -1228,66 +1227,66 @@ static void parse_param_imp( pj_scanner *scanner, pj_pool_t *pool, /* pvalue, if any */ if (*scanner->curptr == '=') { - pj_scan_get_char(scanner); - if (!pj_scan_is_eof(scanner)) { - /* pvalue can be a quoted string. */ - if (*scanner->curptr == '"') { - pj_scan_get_quote( scanner, '"', '"', pvalue); - if (option & PJSIP_PARSE_REMOVE_QUOTE) { - pvalue->ptr++; - pvalue->slen -= 2; - } - // } else if (*scanner->curptr == '[') { - /* pvalue can be a quoted IPv6; in this case, the - * '[' and ']' quote characters are to be removed - * from the pvalue. - * - * Update: this seems to be unnecessary and may cause - * parsing error for cases such as IPv6 reference with - * port number. - */ - // pj_scan_get_char(scanner); - // pj_scan_get_until_ch(scanner, ']', pvalue); - // pj_scan_get_char(scanner); - } else if(pj_cis_match(spec, *scanner->curptr)) { - if (!esc_spec) { - pj_scan_get(scanner, spec, pvalue); - } else { - parser_get_and_unescape(scanner, pool, spec, esc_spec, - pvalue); - } - } - } + pj_scan_get_char(scanner); + if (!pj_scan_is_eof(scanner)) { + /* pvalue can be a quoted string. */ + if (*scanner->curptr == '"') { + pj_scan_get_quote( scanner, '"', '"', pvalue); + if (option & PJSIP_PARSE_REMOVE_QUOTE) { + pvalue->ptr++; + pvalue->slen -= 2; + } + // } else if (*scanner->curptr == '[') { + /* pvalue can be a quoted IPv6; in this case, the + * '[' and ']' quote characters are to be removed + * from the pvalue. + * + * Update: this seems to be unnecessary and may cause + * parsing error for cases such as IPv6 reference with + * port number. + */ + // pj_scan_get_char(scanner); + // pj_scan_get_until_ch(scanner, ']', pvalue); + // pj_scan_get_char(scanner); + } else if(pj_cis_match(spec, *scanner->curptr)) { + if (!esc_spec) { + pj_scan_get(scanner, spec, pvalue); + } else { + parser_get_and_unescape(scanner, pool, spec, esc_spec, + pvalue); + } + } + } } } /* Parse parameter (pname ["=" pvalue]) using token. */ PJ_DEF(void) pjsip_parse_param_imp(pj_scanner *scanner, pj_pool_t *pool, - pj_str_t *pname, pj_str_t *pvalue, - unsigned option) + pj_str_t *pname, pj_str_t *pvalue, + unsigned option) { parse_param_imp(scanner, pool, pname, pvalue, &pconst.pjsip_TOKEN_SPEC, - // Token does not need to be unescaped. - // Refer to PR #2933. - // &pconst.pjsip_TOKEN_SPEC_ESC, - NULL, option); + // Token does not need to be unescaped. + // Refer to PR #2933. + // &pconst.pjsip_TOKEN_SPEC_ESC, + NULL, option); } /* Parse parameter (pname ["=" pvalue]) using paramchar. */ PJ_DEF(void) pjsip_parse_uri_param_imp( pj_scanner *scanner, pj_pool_t *pool, - pj_str_t *pname, pj_str_t *pvalue, - unsigned option) + pj_str_t *pname, pj_str_t *pvalue, + unsigned option) { parse_param_imp(scanner,pool, pname, pvalue, &pconst.pjsip_PARAM_CHAR_SPEC, - &pconst.pjsip_PARAM_CHAR_SPEC_ESC, option); + &pconst.pjsip_PARAM_CHAR_SPEC_ESC, option); } /* Parse parameter (";" pname ["=" pvalue]) in SIP header. */ static void int_parse_param( pj_scanner *scanner, pj_pool_t *pool, - pj_str_t *pname, pj_str_t *pvalue, - unsigned option) + pj_str_t *pname, pj_str_t *pvalue, + unsigned option) { /* Get ';' character */ pj_scan_get_char(scanner); @@ -1298,28 +1297,28 @@ static void int_parse_param( pj_scanner *scanner, pj_pool_t *pool, /* Parse parameter (";" pname ["=" pvalue]) in URI. */ static void int_parse_uri_param( pj_scanner *scanner, pj_pool_t *pool, - pj_str_t *pname, pj_str_t *pvalue, - unsigned option) + pj_str_t *pname, pj_str_t *pvalue, + unsigned option) { /* Get ';' character */ pj_scan_get_char(scanner); /* Get pname and optionally pvalue */ pjsip_parse_uri_param_imp(scanner, pool, pname, pvalue, - option); + option); } /* Parse header parameter. */ static void int_parse_hparam( pj_scanner *scanner, pj_pool_t *pool, - pj_str_t *hname, pj_str_t *hvalue ) + pj_str_t *hname, pj_str_t *hvalue ) { /* Get '?' or '&' character. */ pj_scan_get_char(scanner); /* hname */ parser_get_and_unescape(scanner, pool, &pconst.pjsip_HDR_CHAR_SPEC, - &pconst.pjsip_HDR_CHAR_SPEC_ESC, hname); + &pconst.pjsip_HDR_CHAR_SPEC_ESC, hname); /* Init hvalue */ hvalue->ptr = NULL; @@ -1327,13 +1326,13 @@ static void int_parse_hparam( pj_scanner *scanner, pj_pool_t *pool, /* pvalue, if any */ if (*scanner->curptr == '=') { - pj_scan_get_char(scanner); - if (!pj_scan_is_eof(scanner) && - pj_cis_match(&pconst.pjsip_HDR_CHAR_SPEC, *scanner->curptr)) - { - parser_get_and_unescape(scanner, pool, &pconst.pjsip_HDR_CHAR_SPEC, - &pconst.pjsip_HDR_CHAR_SPEC_ESC, hvalue); - } + pj_scan_get_char(scanner); + if (!pj_scan_is_eof(scanner) && + pj_cis_match(&pconst.pjsip_HDR_CHAR_SPEC, *scanner->curptr)) + { + parser_get_and_unescape(scanner, pool, &pconst.pjsip_HDR_CHAR_SPEC, + &pconst.pjsip_HDR_CHAR_SPEC_ESC, hvalue); + } } } @@ -1343,29 +1342,29 @@ static void int_parse_hparam( pj_scanner *scanner, pj_pool_t *pool, static void int_parse_host(pj_scanner *scanner, pj_str_t *host) { if (*scanner->curptr == '[') { - /* Note: the '[' and ']' characters are removed from the host */ - pj_scan_get_char(scanner); - pj_scan_get_until_ch(scanner, ']', host); - pj_scan_get_char(scanner); + /* Note: the '[' and ']' characters are removed from the host */ + pj_scan_get_char(scanner); + pj_scan_get_until_ch(scanner, ']', host); + pj_scan_get_char(scanner); } else { - pj_scan_get( scanner, &pconst.pjsip_HOST_SPEC, host); + pj_scan_get( scanner, &pconst.pjsip_HOST_SPEC, host); } } /* Parse host:port in URI. */ static void int_parse_uri_host_port( pj_scanner *scanner, - pj_str_t *host, int *p_port) + pj_str_t *host, int *p_port) { int_parse_host(scanner, host); /* RFC3261 section 19.1.2: host don't need to be unescaped */ if (*scanner->curptr == ':') { - pj_str_t port; - pj_scan_get_char(scanner); - pj_scan_get(scanner, &pconst.pjsip_DIGIT_SPEC, &port); - strtoi_validate(&port, PJSIP_MIN_PORT, PJSIP_MAX_PORT, p_port); + pj_str_t port; + pj_scan_get_char(scanner); + pj_scan_get(scanner, &pconst.pjsip_DIGIT_SPEC, &port); + strtoi_validate(&port, PJSIP_MIN_PORT, PJSIP_MAX_PORT, p_port); } else { - *p_port = 0; + *p_port = 0; } } @@ -1379,27 +1378,27 @@ static int int_is_next_user(pj_scanner *scanner) * must be a username. */ if (pj_scan_peek( scanner, &pconst.pjsip_PROBE_USER_HOST_SPEC, &dummy) == '@') - is_user = 1; + is_user = 1; else - is_user = 0; + is_user = 0; return is_user; } /* Parse user:pass tokens in an URI. */ static void int_parse_user_pass( pj_scanner *scanner, pj_pool_t *pool, - pj_str_t *user, pj_str_t *pass) + pj_str_t *user, pj_str_t *pass) { parser_get_and_unescape(scanner, pool, &pconst.pjsip_USER_SPEC_LENIENT, - &pconst.pjsip_USER_SPEC_LENIENT_ESC, user); + &pconst.pjsip_USER_SPEC_LENIENT_ESC, user); if ( *scanner->curptr == ':') { - pj_scan_get_char( scanner ); - parser_get_and_unescape(scanner, pool, &pconst.pjsip_PASSWD_SPEC, - &pconst.pjsip_PASSWD_SPEC_ESC, pass); + pj_scan_get_char( scanner ); + parser_get_and_unescape(scanner, pool, &pconst.pjsip_PASSWD_SPEC, + &pconst.pjsip_PASSWD_SPEC_ESC, pass); } else { - pass->ptr = NULL; - pass->slen = 0; + pass->ptr = NULL; + pass->slen = 0; } /* Get the '@' */ @@ -1408,7 +1407,7 @@ static void int_parse_user_pass( pj_scanner *scanner, pj_pool_t *pool, /* Parse all types of URI. */ static pjsip_uri *int_parse_uri_or_name_addr( pj_scanner *scanner, pj_pool_t *pool, - unsigned opt) + unsigned opt) { pjsip_uri *uri; int is_name_addr = 0; @@ -1417,43 +1416,43 @@ static pjsip_uri *int_parse_uri_or_name_addr( pj_scanner *scanner, pj_pool_t *po pj_scan_skip_whitespace(scanner); if (*scanner->curptr=='"' || *scanner->curptr=='<') { - uri = (pjsip_uri*)int_parse_name_addr( scanner, pool ); - is_name_addr = 1; + uri = (pjsip_uri*)int_parse_name_addr( scanner, pool ); + is_name_addr = 1; } else { - pj_str_t scheme; - int next_ch; + pj_str_t scheme; + int next_ch; - next_ch = pj_scan_peek( scanner, &pconst.pjsip_DISPLAY_SPEC, &scheme); + next_ch = pj_scan_peek( scanner, &pconst.pjsip_DISPLAY_SPEC, &scheme); - if (next_ch==':') { - pjsip_parse_uri_func *func = find_uri_handler(&scheme); + if (next_ch==':') { + pjsip_parse_uri_func *func = find_uri_handler(&scheme); - if (func == NULL) { - /* Unsupported URI scheme */ - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); - } + if (func == NULL) { + /* Unsupported URI scheme */ + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + } - uri = (pjsip_uri*) - (*func)(scanner, pool, - (opt & PJSIP_PARSE_URI_IN_FROM_TO_HDR)==0); + uri = (pjsip_uri*) + (*func)(scanner, pool, + (opt & PJSIP_PARSE_URI_IN_FROM_TO_HDR)==0); - } else { - uri = (pjsip_uri*)int_parse_name_addr( scanner, pool ); - is_name_addr = 1; - } + } else { + uri = (pjsip_uri*)int_parse_name_addr( scanner, pool ); + is_name_addr = 1; + } } /* Should we return the URI object as name address? */ if (opt & PJSIP_PARSE_URI_AS_NAMEADDR) { - if (is_name_addr == 0) { - pjsip_name_addr *name_addr; + if (is_name_addr == 0) { + pjsip_name_addr *name_addr; - name_addr = pjsip_name_addr_create(pool); - name_addr->uri = uri; + name_addr = pjsip_name_addr_create(pool); + name_addr->uri = uri; - uri = (pjsip_uri*)name_addr; - } + uri = (pjsip_uri*)name_addr; + } } return uri; @@ -1461,35 +1460,35 @@ static pjsip_uri *int_parse_uri_or_name_addr( pj_scanner *scanner, pj_pool_t *po /* Parse URI. */ static pjsip_uri *int_parse_uri(pj_scanner *scanner, pj_pool_t *pool, - pj_bool_t parse_params) + pj_bool_t parse_params) { /* Bug: * This function should not call back int_parse_name_addr() because * it is called by that function. This would cause stack overflow * with PROTOS test #1223. if (*scanner->curptr=='"' || *scanner->curptr=='<') { - return (pjsip_uri*)int_parse_name_addr( scanner, pool ); + return (pjsip_uri*)int_parse_name_addr( scanner, pool ); } else { */ - pj_str_t scheme; - int colon; - pjsip_parse_uri_func *func; - - /* Get scheme. */ - colon = pj_scan_peek(scanner, &pconst.pjsip_TOKEN_SPEC, &scheme); - if (colon != ':') { - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); - } - - func = find_uri_handler(&scheme); - if (func) { - return (pjsip_uri*)(*func)(scanner, pool, parse_params); - - } else { - /* Unsupported URI scheme */ - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); - UNREACHED({ return NULL; /* Not reached. */ }) - } + pj_str_t scheme; + int colon; + pjsip_parse_uri_func *func; + + /* Get scheme. */ + colon = pj_scan_peek(scanner, &pconst.pjsip_TOKEN_SPEC, &scheme); + if (colon != ':') { + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + } + + func = find_uri_handler(&scheme); + if (func) { + return (pjsip_uri*)(*func)(scanner, pool, parse_params); + + } else { + /* Unsupported URI scheme */ + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + UNREACHED({ return NULL; /* Not reached. */ }) + } /* } @@ -1500,8 +1499,8 @@ static pjsip_uri *int_parse_uri(pj_scanner *scanner, pj_pool_t *pool, * This actually returns (pjsip_sip_uri*) type, */ static void* int_parse_sip_url( pj_scanner *scanner, - pj_pool_t *pool, - pj_bool_t parse_params) + pj_pool_t *pool, + pj_bool_t parse_params) { pj_str_t scheme; pjsip_sip_uri *url = NULL; @@ -1512,26 +1511,26 @@ static void* int_parse_sip_url( pj_scanner *scanner, pj_scan_get(scanner, &pconst.pjsip_TOKEN_SPEC, &scheme); colon = pj_scan_get_char(scanner); if (colon != ':') { - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); } if (parser_stricmp(scheme, pconst.pjsip_SIP_STR)==0) { - url = pjsip_sip_uri_create(pool, 0); + url = pjsip_sip_uri_create(pool, 0); } else if (parser_stricmp(scheme, pconst.pjsip_SIPS_STR)==0) { - url = pjsip_sip_uri_create(pool, 1); + url = pjsip_sip_uri_create(pool, 1); } else { - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); - /* should not reach here */ - UNREACHED({ - pj_assert(0); - return 0; - }) + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + /* should not reach here */ + UNREACHED({ + pj_assert(0); + return 0; + }) } if (int_is_next_user(scanner)) { - int_parse_user_pass(scanner, pool, &url->user, &url->passwd); + int_parse_user_pass(scanner, pool, &url->user, &url->passwd); } /* Get host:port */ @@ -1540,44 +1539,44 @@ static void* int_parse_sip_url( pj_scanner *scanner, /* Get URL parameters. */ if (parse_params) { while (*scanner->curptr == ';' ) { - pj_str_t pname, pvalue; + pj_str_t pname, pvalue; - int_parse_uri_param( scanner, pool, &pname, &pvalue, 0); + int_parse_uri_param( scanner, pool, &pname, &pvalue, 0); - if (!parser_stricmp(pname, pconst.pjsip_USER_STR) && pvalue.slen) { - url->user_param = pvalue; + if (!parser_stricmp(pname, pconst.pjsip_USER_STR) && pvalue.slen) { + url->user_param = pvalue; - } else if (!parser_stricmp(pname, pconst.pjsip_METHOD_STR) && pvalue.slen) { - url->method_param = pvalue; + } else if (!parser_stricmp(pname, pconst.pjsip_METHOD_STR) && pvalue.slen) { + url->method_param = pvalue; - } else if (!parser_stricmp(pname, pconst.pjsip_TRANSPORT_STR) && pvalue.slen) { - url->transport_param = pvalue; + } else if (!parser_stricmp(pname, pconst.pjsip_TRANSPORT_STR) && pvalue.slen) { + url->transport_param = pvalue; - } else if (!parser_stricmp(pname, pconst.pjsip_TTL_STR) && pvalue.slen) { - strtoi_validate(&pvalue, PJSIP_MIN_TTL, PJSIP_MAX_TTL, - &url->ttl_param); - } else if (!parser_stricmp(pname, pconst.pjsip_MADDR_STR) && pvalue.slen) { - url->maddr_param = pvalue; + } else if (!parser_stricmp(pname, pconst.pjsip_TTL_STR) && pvalue.slen) { + strtoi_validate(&pvalue, PJSIP_MIN_TTL, PJSIP_MAX_TTL, + &url->ttl_param); + } else if (!parser_stricmp(pname, pconst.pjsip_MADDR_STR) && pvalue.slen) { + url->maddr_param = pvalue; - } else if (!parser_stricmp(pname, pconst.pjsip_LR_STR)) { - url->lr_param = 1; + } else if (!parser_stricmp(pname, pconst.pjsip_LR_STR)) { + url->lr_param = 1; - } else { - pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); - p->name = pname; - p->value = pvalue; - pj_list_insert_before(&url->other_param, p); - } + } else { + pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); + p->name = pname; + p->value = pvalue; + pj_list_insert_before(&url->other_param, p); + } } } /* Get header params. */ if (parse_params && *scanner->curptr == '?') { do { - pjsip_param *param; - param = PJ_POOL_ALLOC_T(pool, pjsip_param); - int_parse_hparam(scanner, pool, ¶m->name, ¶m->value); - pj_list_insert_before(&url->header_param, param); + pjsip_param *param; + param = PJ_POOL_ALLOC_T(pool, pjsip_param); + int_parse_hparam(scanner, pool, ¶m->name, ¶m->value); + pj_list_insert_before(&url->header_param, param); } while (*scanner->curptr == '&'); } @@ -1588,7 +1587,7 @@ static void* int_parse_sip_url( pj_scanner *scanner, /* Parse nameaddr. */ static pjsip_name_addr *int_parse_name_addr( pj_scanner *scanner, - pj_pool_t *pool ) + pj_pool_t *pool ) { int has_bracket; pjsip_name_addr *name_addr; @@ -1596,26 +1595,26 @@ static pjsip_name_addr *int_parse_name_addr( pj_scanner *scanner, name_addr = pjsip_name_addr_create(pool); if (*scanner->curptr == '"') { - pj_scan_get_quote( scanner, '"', '"', &name_addr->display); - /* Trim the leading and ending quote */ - name_addr->display.ptr++; - name_addr->display.slen -= 2; + pj_scan_get_quote( scanner, '"', '"', &name_addr->display); + /* Trim the leading and ending quote */ + name_addr->display.ptr++; + name_addr->display.slen -= 2; } else if (*scanner->curptr != '<') { - int next; - pj_str_t dummy; - - /* This can be either the start of display name, - * the start of URL ("sip:", "sips:", "tel:", etc.), or '<' char. - * We're only interested in display name, because SIP URL - * will be parser later. - */ - next = pj_scan_peek(scanner, &pconst.pjsip_DISPLAY_SPEC, &dummy); - if (next == '<') { - /* Ok, this is what we're looking for, a display name. */ - pj_scan_get_until_ch( scanner, '<', &name_addr->display); - pj_strtrim(&name_addr->display); - } + int next; + pj_str_t dummy; + + /* This can be either the start of display name, + * the start of URL ("sip:", "sips:", "tel:", etc.), or '<' char. + * We're only interested in display name, because SIP URL + * will be parser later. + */ + next = pj_scan_peek(scanner, &pconst.pjsip_DISPLAY_SPEC, &dummy); + if (next == '<') { + /* Ok, this is what we're looking for, a display name. */ + pj_scan_get_until_ch( scanner, '<', &name_addr->display); + pj_strtrim(&name_addr->display); + } } /* Manually skip whitespace. */ @@ -1624,18 +1623,18 @@ static pjsip_name_addr *int_parse_name_addr( pj_scanner *scanner, /* Get the SIP-URL */ has_bracket = (*scanner->curptr == '<'); if (has_bracket) { - pj_scan_get_char(scanner); + pj_scan_get_char(scanner); } else if (name_addr->display.slen) { - /* Must have bracket now (2012-10-26). - * Allowing (invalid) name-addr to pass URI verification will - * cause us to send invalid URI to the wire. - */ - PJ_THROW( PJSIP_SYN_ERR_EXCEPTION); + /* Must have bracket now (2012-10-26). + * Allowing (invalid) name-addr to pass URI verification will + * cause us to send invalid URI to the wire. + */ + PJ_THROW( PJSIP_SYN_ERR_EXCEPTION); } name_addr->uri = int_parse_uri( scanner, pool, PJ_TRUE ); if (has_bracket) { - if (pj_scan_get_char(scanner) != '>') - PJ_THROW( PJSIP_SYN_ERR_EXCEPTION); + if (pj_scan_get_char(scanner) != '>') + PJ_THROW( PJSIP_SYN_ERR_EXCEPTION); } return name_addr; @@ -1644,8 +1643,8 @@ static pjsip_name_addr *int_parse_name_addr( pj_scanner *scanner, /* Parse other URI */ static void* int_parse_other_uri(pj_scanner *scanner, - pj_pool_t *pool, - pj_bool_t parse_params) + pj_pool_t *pool, + pj_bool_t parse_params) { pjsip_other_uri *uri = 0; const pjsip_parser_const_t *pc = pjsip_parser_const(); @@ -1659,7 +1658,7 @@ static void* int_parse_other_uri(pj_scanner *scanner, pj_scan_get(scanner, &pc->pjsip_TOKEN_SPEC, &uri->scheme); if (pj_scan_get_char(scanner) != ':') { - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); } pj_scan_get(scanner, &pc->pjsip_OTHER_URI_CONTENT, &uri->content); @@ -1671,7 +1670,7 @@ static void* int_parse_other_uri(pj_scanner *scanner, /* Parse SIP request line. */ static void int_parse_req_line( pj_scanner *scanner, pj_pool_t *pool, - pjsip_request_line *req_line) + pjsip_request_line *req_line) { pj_str_t token; @@ -1685,7 +1684,7 @@ static void int_parse_req_line( pj_scanner *scanner, pj_pool_t *pool, /* Parse status line. */ static void int_parse_status_line( pj_scanner *scanner, - pjsip_status_line *status_line) + pjsip_status_line *status_line) { pj_str_t token; @@ -1694,9 +1693,9 @@ static void int_parse_status_line( pj_scanner *scanner, strtoi_validate(&token, PJSIP_MIN_STATUS_CODE, PJSIP_MAX_STATUS_CODE, &status_line->code); if (*scanner->curptr != '\r' && *scanner->curptr != '\n') - pj_scan_get( scanner, &pconst.pjsip_NOT_NEWLINE, &status_line->reason); + pj_scan_get( scanner, &pconst.pjsip_NOT_NEWLINE, &status_line->reason); else - status_line->reason.slen=0, status_line->reason.ptr=NULL; + status_line->reason.slen=0, status_line->reason.ptr=NULL; pj_scan_get_newline( scanner ); } @@ -1705,24 +1704,24 @@ static void int_parse_status_line( pj_scanner *scanner, * Public API to parse SIP status line. */ PJ_DEF(pj_status_t) pjsip_parse_status_line( char *buf, pj_size_t size, - pjsip_status_line *status_line) + pjsip_status_line *status_line) { pj_scanner scanner; PJ_USE_EXCEPTION; pj_bzero(status_line, sizeof(*status_line)); pj_scan_init(&scanner, buf, size, PJ_SCAN_AUTOSKIP_WS_HEADER, - &on_syntax_error); + &on_syntax_error); PJ_TRY { - int_parse_status_line(&scanner, status_line); + int_parse_status_line(&scanner, status_line); } PJ_CATCH_ANY { - /* Tolerate the error if it is caused only by missing newline */ - if (status_line->code == 0 && status_line->reason.slen == 0) { - pj_scan_fini(&scanner); - return PJSIP_EINVALIDMSG; - } + /* Tolerate the error if it is caused only by missing newline */ + if (status_line->code == 0 && status_line->reason.slen == 0) { + pj_scan_fini(&scanner); + return PJSIP_EINVALIDMSG; + } } PJ_END; @@ -1735,11 +1734,11 @@ PJ_DEF(pj_status_t) pjsip_parse_status_line( char *buf, pj_size_t size, static void parse_hdr_end( pj_scanner *scanner ) { if (pj_scan_is_eof(scanner)) { - ; /* Do nothing. */ + ; /* Do nothing. */ } else if (*scanner->curptr == '&') { - pj_scan_get_char(scanner); + pj_scan_get_char(scanner); } else { - pj_scan_get_newline(scanner); + pj_scan_get_newline(scanner); } } @@ -1751,34 +1750,34 @@ PJ_DEF(void) pjsip_parse_end_hdr_imp( pj_scanner *scanner ) /* Parse generic array header. */ static void parse_generic_array_hdr( pjsip_generic_array_hdr *hdr, - pj_scanner *scanner) + pj_scanner *scanner) { /* Some header fields allow empty elements in the value: * Accept, Allow, Supported */ if (pj_scan_is_eof(scanner) || - *scanner->curptr == '\r' || *scanner->curptr == '\n') + *scanner->curptr == '\r' || *scanner->curptr == '\n') { - goto end; + goto end; } if (hdr->count >= PJ_ARRAY_SIZE(hdr->values)) { - /* Too many elements */ - on_syntax_error(scanner); - return; + /* Too many elements */ + on_syntax_error(scanner); + return; } pj_scan_get( scanner, &pconst.pjsip_NOT_COMMA_OR_NEWLINE, - &hdr->values[hdr->count]); + &hdr->values[hdr->count]); hdr->count++; while ((hdr->count < PJSIP_GENERIC_ARRAY_MAX_COUNT) && - (*scanner->curptr == ',')) + (*scanner->curptr == ',')) { - pj_scan_get_char(scanner); - pj_scan_get( scanner, &pconst.pjsip_NOT_COMMA_OR_NEWLINE, - &hdr->values[hdr->count]); - hdr->count++; + pj_scan_get_char(scanner); + pj_scan_get( scanner, &pconst.pjsip_NOT_COMMA_OR_NEWLINE, + &hdr->values[hdr->count]); + hdr->count++; } end: @@ -1787,7 +1786,7 @@ static void parse_generic_array_hdr( pjsip_generic_array_hdr *hdr, /* Parse generic array header. */ PJ_DEF(void) pjsip_parse_generic_array_hdr_imp( pjsip_generic_array_hdr *hdr, - pj_scanner *scanner) + pj_scanner *scanner) { parse_generic_array_hdr(hdr, scanner); } @@ -1795,7 +1794,7 @@ PJ_DEF(void) pjsip_parse_generic_array_hdr_imp( pjsip_generic_array_hdr *hdr, /* Parse generic string header. */ static void parse_generic_string_hdr( pjsip_generic_string_hdr *hdr, - pjsip_parse_ctx *ctx) + pjsip_parse_ctx *ctx) { pj_scanner *scanner = ctx->scanner; @@ -1803,23 +1802,23 @@ static void parse_generic_string_hdr( pjsip_generic_string_hdr *hdr, /* header may be mangled hence the loop */ while (pj_cis_match(&pconst.pjsip_NOT_NEWLINE, *scanner->curptr)) { - pj_str_t next, tmp; + pj_str_t next, tmp; - pj_scan_get( scanner, &pconst.pjsip_NOT_NEWLINE, &hdr->hvalue); - if (pj_scan_is_eof(scanner) || IS_NEWLINE(*scanner->curptr)) - break; - /* mangled, get next fraction */ - pj_scan_get( scanner, &pconst.pjsip_NOT_NEWLINE, &next); - /* concatenate */ - tmp.ptr = (char*)pj_pool_alloc(ctx->pool, - hdr->hvalue.slen + next.slen + 2); - tmp.slen = 0; - pj_strcpy(&tmp, &hdr->hvalue); - pj_strcat2(&tmp, " "); - pj_strcat(&tmp, &next); - tmp.ptr[tmp.slen] = '\0'; + pj_scan_get( scanner, &pconst.pjsip_NOT_NEWLINE, &hdr->hvalue); + if (pj_scan_is_eof(scanner) || IS_NEWLINE(*scanner->curptr)) + break; + /* mangled, get next fraction */ + pj_scan_get( scanner, &pconst.pjsip_NOT_NEWLINE, &next); + /* concatenate */ + tmp.ptr = (char*)pj_pool_alloc(ctx->pool, + hdr->hvalue.slen + next.slen + 2); + tmp.slen = 0; + pj_strcpy(&tmp, &hdr->hvalue); + pj_strcat2(&tmp, " "); + pj_strcat(&tmp, &next); + tmp.ptr[tmp.slen] = '\0'; - hdr->hvalue = tmp; + hdr->hvalue = tmp; } parse_hdr_end(scanner); @@ -1827,7 +1826,7 @@ static void parse_generic_string_hdr( pjsip_generic_string_hdr *hdr, /* Parse generic integer header. */ static void parse_generic_int_hdr( pjsip_generic_int_hdr *hdr, - pj_scanner *scanner ) + pj_scanner *scanner ) { pj_str_t tmp; pj_scan_get( scanner, &pconst.pjsip_DIGIT_SPEC, &tmp); @@ -1867,55 +1866,55 @@ static pjsip_hdr* parse_hdr_call_id(pjsip_parse_ctx *ctx) /* Parse and interpret Contact param. */ static void int_parse_contact_param( pjsip_contact_hdr *hdr, - pj_scanner *scanner, - pj_pool_t *pool) + pj_scanner *scanner, + pj_pool_t *pool) { while ( *scanner->curptr == ';' ) { - pj_str_t pname, pvalue; + pj_str_t pname, pvalue; - int_parse_param( scanner, pool, &pname, &pvalue, 0); - if (!parser_stricmp(pname, pconst.pjsip_Q_STR) && pvalue.slen) { - char *dot_pos = (char*) pj_memchr(pvalue.ptr, '.', pvalue.slen); - if (!dot_pos) { - strtoi_validate(&pvalue, PJSIP_MIN_Q1000, PJSIP_MAX_Q1000, + int_parse_param( scanner, pool, &pname, &pvalue, 0); + if (!parser_stricmp(pname, pconst.pjsip_Q_STR) && pvalue.slen) { + char *dot_pos = (char*) pj_memchr(pvalue.ptr, '.', pvalue.slen); + if (!dot_pos) { + strtoi_validate(&pvalue, PJSIP_MIN_Q1000, PJSIP_MAX_Q1000, &hdr->q1000); - hdr->q1000 *= 1000; - } else { - pj_str_t tmp = pvalue; - unsigned long qval_frac; + hdr->q1000 *= 1000; + } else { + pj_str_t tmp = pvalue; + unsigned long qval_frac; - tmp.slen = dot_pos - pvalue.ptr; - strtoi_validate(&tmp, PJSIP_MIN_Q1000, PJSIP_MAX_Q1000, + tmp.slen = dot_pos - pvalue.ptr; + strtoi_validate(&tmp, PJSIP_MIN_Q1000, PJSIP_MAX_Q1000, &hdr->q1000); hdr->q1000 *= 1000; - pvalue.slen = (pvalue.ptr+pvalue.slen) - (dot_pos+1); - pvalue.ptr = dot_pos + 1; - if (pvalue.slen > 3) { - pvalue.slen = 3; - } - qval_frac = pj_strtoul_mindigit(&pvalue, 3); - if ((unsigned)hdr->q1000 > (PJ_MAXINT32 - qval_frac)) { - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); - } - hdr->q1000 += qval_frac; - } - } else if (!parser_stricmp(pname, pconst.pjsip_EXPIRES_STR) && + pvalue.slen = (pvalue.ptr+pvalue.slen) - (dot_pos+1); + pvalue.ptr = dot_pos + 1; + if (pvalue.slen > 3) { + pvalue.slen = 3; + } + qval_frac = pj_strtoul_mindigit(&pvalue, 3); + if ((unsigned)hdr->q1000 > (PJ_MAXINT32 - qval_frac)) { + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + } + hdr->q1000 += qval_frac; + } + } else if (!parser_stricmp(pname, pconst.pjsip_EXPIRES_STR) && pvalue.slen) { hdr->expires = pj_strtoul(&pvalue); if (hdr->expires == PJSIP_EXPIRES_NOT_SPECIFIED) - hdr->expires--; + hdr->expires--; if (hdr->expires > PJSIP_MAX_EXPIRES) - hdr->expires = PJSIP_MAX_EXPIRES; + hdr->expires = PJSIP_MAX_EXPIRES; if (hdr->expires < PJSIP_MIN_EXPIRES) - hdr->expires = PJSIP_MIN_EXPIRES; - } else { - pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); - p->name = pname; - p->value = pvalue; - pj_list_insert_before(&hdr->other_param, p); - } + hdr->expires = PJSIP_MIN_EXPIRES; + } else { + pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); + p->name = pname; + p->value = pvalue; + pj_list_insert_before(&hdr->other_param, p); + } } } @@ -1926,29 +1925,29 @@ static pjsip_hdr* parse_hdr_contact( pjsip_parse_ctx *ctx ) pj_scanner *scanner = ctx->scanner; do { - pjsip_contact_hdr *hdr = pjsip_contact_hdr_create(ctx->pool); - if (first == NULL) - first = hdr; - else - pj_list_insert_before(first, hdr); - - if (*scanner->curptr == '*') { - pj_scan_get_char(scanner); - hdr->star = 1; - - } else { - hdr->star = 0; - hdr->uri = int_parse_uri_or_name_addr(scanner, ctx->pool, + pjsip_contact_hdr *hdr = pjsip_contact_hdr_create(ctx->pool); + if (first == NULL) + first = hdr; + else + pj_list_insert_before(first, hdr); + + if (*scanner->curptr == '*') { + pj_scan_get_char(scanner); + hdr->star = 1; + + } else { + hdr->star = 0; + hdr->uri = int_parse_uri_or_name_addr(scanner, ctx->pool, PJSIP_PARSE_URI_AS_NAMEADDR | - PJSIP_PARSE_URI_IN_FROM_TO_HDR); + PJSIP_PARSE_URI_IN_FROM_TO_HDR); - int_parse_contact_param(hdr, scanner, ctx->pool); - } + int_parse_contact_param(hdr, scanner, ctx->pool); + } - if (*scanner->curptr != ',') - break; + if (*scanner->curptr != ',') + break; - pj_scan_get_char(scanner); + pj_scan_get_char(scanner); } while (1); @@ -1989,9 +1988,9 @@ static pjsip_hdr* parse_hdr_content_type( pjsip_parse_ctx *ctx ) /* Parse media parameters */ while (*scanner->curptr == ';') { - pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); - int_parse_param(scanner, ctx->pool, ¶m->name, ¶m->value, 0); - pj_list_push_back(&hdr->media.param, param); + pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); + int_parse_param(scanner, ctx->pool, ¶m->name, ¶m->value, 0); + pj_list_push_back(&hdr->media.param, param); } parse_hdr_end(ctx->scanner); @@ -2036,27 +2035,27 @@ static pjsip_hdr* parse_hdr_expires(pjsip_parse_ctx *ctx) /* Parse From: or To: header. */ static void parse_hdr_fromto( pj_scanner *scanner, - pj_pool_t *pool, - pjsip_from_hdr *hdr) + pj_pool_t *pool, + pjsip_from_hdr *hdr) { hdr->uri = int_parse_uri_or_name_addr(scanner, pool, - PJSIP_PARSE_URI_AS_NAMEADDR | - PJSIP_PARSE_URI_IN_FROM_TO_HDR); + PJSIP_PARSE_URI_AS_NAMEADDR | + PJSIP_PARSE_URI_IN_FROM_TO_HDR); while ( *scanner->curptr == ';' ) { - pj_str_t pname, pvalue; + pj_str_t pname, pvalue; - int_parse_param( scanner, pool, &pname, &pvalue, 0); + int_parse_param( scanner, pool, &pname, &pvalue, 0); - if (!parser_stricmp(pname, pconst.pjsip_TAG_STR)) { - hdr->tag = pvalue; - - } else { - pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); - p->name = pname; - p->value = pvalue; - pj_list_insert_before(&hdr->other_param, p); - } + if (!parser_stricmp(pname, pconst.pjsip_TAG_STR)) { + hdr->tag = pvalue; + + } else { + pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); + p->name = pname; + p->value = pvalue; + pj_list_insert_before(&hdr->other_param, p); + } } parse_hdr_end(scanner); @@ -2078,14 +2077,14 @@ static pjsip_hdr* parse_hdr_require( pjsip_parse_ctx *ctx ) { pjsip_require_hdr *hdr; pj_bool_t new_hdr = (ctx->rdata==NULL || - ctx->rdata->msg_info.require == NULL); + ctx->rdata->msg_info.require == NULL); if (ctx->rdata && ctx->rdata->msg_info.require) { - hdr = ctx->rdata->msg_info.require; + hdr = ctx->rdata->msg_info.require; } else { - hdr = pjsip_require_hdr_create(ctx->pool); - if (ctx->rdata) - ctx->rdata->msg_info.require = hdr; + hdr = pjsip_require_hdr_create(ctx->pool); + if (ctx->rdata) + ctx->rdata->msg_info.require = hdr; } parse_generic_array_hdr(hdr, ctx->scanner); @@ -2107,20 +2106,20 @@ static pjsip_hdr* parse_hdr_retry_after(pjsip_parse_ctx *ctx) &hdr->ivalue); while (!pj_scan_is_eof(scanner) && *scanner->curptr!='\r' && - *scanner->curptr!='\n') + *scanner->curptr!='\n') { - if (*scanner->curptr=='(') { - pj_scan_get_quote(scanner, '(', ')', &hdr->comment); - /* Trim the leading and ending parens */ - hdr->comment.ptr++; - hdr->comment.slen -= 2; - } else if (*scanner->curptr==';') { - pjsip_param *prm = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); - int_parse_param(scanner, ctx->pool, &prm->name, &prm->value, 0); - pj_list_push_back(&hdr->param, prm); - } else { - on_syntax_error(scanner); - } + if (*scanner->curptr=='(') { + pj_scan_get_quote(scanner, '(', ')', &hdr->comment); + /* Trim the leading and ending parens */ + hdr->comment.ptr++; + hdr->comment.slen -= 2; + } else if (*scanner->curptr==';') { + pjsip_param *prm = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); + int_parse_param(scanner, ctx->pool, &prm->name, &prm->value, 0); + pj_list_push_back(&hdr->param, prm); + } else { + on_syntax_error(scanner); + } } parse_hdr_end(scanner); @@ -2132,14 +2131,14 @@ static pjsip_hdr* parse_hdr_supported(pjsip_parse_ctx *ctx) { pjsip_supported_hdr *hdr; pj_bool_t new_hdr = (ctx->rdata==NULL || - ctx->rdata->msg_info.supported == NULL); + ctx->rdata->msg_info.supported == NULL); if (ctx->rdata && ctx->rdata->msg_info.supported) { - hdr = ctx->rdata->msg_info.supported; + hdr = ctx->rdata->msg_info.supported; } else { - hdr = pjsip_supported_hdr_create(ctx->pool); - if (ctx->rdata) - ctx->rdata->msg_info.supported = hdr; + hdr = pjsip_supported_hdr_create(ctx->pool); + if (ctx->rdata) + ctx->rdata->msg_info.supported = hdr; } parse_generic_array_hdr(hdr, ctx->scanner); @@ -2168,55 +2167,55 @@ static pjsip_hdr* parse_hdr_unsupported(pjsip_parse_ctx *ctx) /* Parse and interpret Via parameters. */ static void int_parse_via_param( pjsip_via_hdr *hdr, pj_scanner *scanner, - pj_pool_t *pool) + pj_pool_t *pool) { while ( *scanner->curptr == ';' ) { - pj_str_t pname, pvalue; - - //Parse with PARAM_CHAR instead, to allow IPv6 - //No, back to using int_parse_param() for the "`" character! - //int_parse_param( scanner, pool, &pname, &pvalue, 0); - //parse_param_imp(scanner, pool, &pname, &pvalue, - // &pconst.pjsip_TOKEN_SPEC, - // &pconst.pjsip_TOKEN_SPEC_ESC, 0); - //int_parse_param(scanner, pool, &pname, &pvalue, 0); - // This should be the correct one: - // added special spec for Via parameter, basically token plus - // ":" to allow IPv6 address in the received param. - pj_scan_get_char(scanner); - parse_param_imp(scanner, pool, &pname, &pvalue, - &pconst.pjsip_VIA_PARAM_SPEC, - // Token does not need to be unescaped. - // Refer to PR #2933. - // &pconst.pjsip_VIA_PARAM_SPEC_ESC, - NULL, - 0); - - if (!parser_stricmp(pname, pconst.pjsip_BRANCH_STR) && pvalue.slen) { - hdr->branch_param = pvalue; - - } else if (!parser_stricmp(pname, pconst.pjsip_TTL_STR) && pvalue.slen) { - strtoi_validate(&pvalue, PJSIP_MIN_TTL, PJSIP_MAX_TTL, + pj_str_t pname, pvalue; + + //Parse with PARAM_CHAR instead, to allow IPv6 + //No, back to using int_parse_param() for the "`" character! + //int_parse_param( scanner, pool, &pname, &pvalue, 0); + //parse_param_imp(scanner, pool, &pname, &pvalue, + // &pconst.pjsip_TOKEN_SPEC, + // &pconst.pjsip_TOKEN_SPEC_ESC, 0); + //int_parse_param(scanner, pool, &pname, &pvalue, 0); + // This should be the correct one: + // added special spec for Via parameter, basically token plus + // ":" to allow IPv6 address in the received param. + pj_scan_get_char(scanner); + parse_param_imp(scanner, pool, &pname, &pvalue, + &pconst.pjsip_VIA_PARAM_SPEC, + // Token does not need to be unescaped. + // Refer to PR #2933. + // &pconst.pjsip_VIA_PARAM_SPEC_ESC, + NULL, + 0); + + if (!parser_stricmp(pname, pconst.pjsip_BRANCH_STR) && pvalue.slen) { + hdr->branch_param = pvalue; + + } else if (!parser_stricmp(pname, pconst.pjsip_TTL_STR) && pvalue.slen) { + strtoi_validate(&pvalue, PJSIP_MIN_TTL, PJSIP_MAX_TTL, &hdr->ttl_param); - - } else if (!parser_stricmp(pname, pconst.pjsip_MADDR_STR) && pvalue.slen) { - hdr->maddr_param = pvalue; + + } else if (!parser_stricmp(pname, pconst.pjsip_MADDR_STR) && pvalue.slen) { + hdr->maddr_param = pvalue; - } else if (!parser_stricmp(pname, pconst.pjsip_RECEIVED_STR) && pvalue.slen) { - hdr->recvd_param = pvalue; + } else if (!parser_stricmp(pname, pconst.pjsip_RECEIVED_STR) && pvalue.slen) { + hdr->recvd_param = pvalue; - } else if (!parser_stricmp(pname, pconst.pjsip_RPORT_STR)) { - if (pvalue.slen) { - strtoi_validate(&pvalue, PJSIP_MIN_PORT, PJSIP_MAX_PORT, - &hdr->rport_param); + } else if (!parser_stricmp(pname, pconst.pjsip_RPORT_STR)) { + if (pvalue.slen) { + strtoi_validate(&pvalue, PJSIP_MIN_PORT, PJSIP_MAX_PORT, + &hdr->rport_param); } else - hdr->rport_param = 0; - } else { - pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); - p->name = pname; - p->value = pvalue; - pj_list_insert_before(&hdr->other_param, p); - } + hdr->rport_param = 0; + } else { + pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); + p->name = pname; + p->value = pvalue; + pj_list_insert_before(&hdr->other_param, p); + } } } @@ -2245,16 +2244,16 @@ static pjsip_hdr* parse_hdr_min_expires(pjsip_parse_ctx *ctx) /* Parse Route: or Record-Route: header. */ static void parse_hdr_rr_route( pj_scanner *scanner, pj_pool_t *pool, - pjsip_routing_hdr *hdr ) + pjsip_routing_hdr *hdr ) { pjsip_name_addr *temp=int_parse_name_addr(scanner, pool); pj_memcpy(&hdr->name_addr, temp, sizeof(*temp)); while (*scanner->curptr == ';') { - pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); - int_parse_param(scanner, pool, &p->name, &p->value, 0); - pj_list_insert_before(&hdr->other_param, p); + pjsip_param *p = PJ_POOL_ALLOC_T(pool, pjsip_param); + int_parse_param(scanner, pool, &p->name, &p->value, 0); + pj_list_insert_before(&hdr->other_param, p); } } @@ -2265,18 +2264,18 @@ static pjsip_hdr* parse_hdr_rr( pjsip_parse_ctx *ctx) pj_scanner *scanner = ctx->scanner; do { - pjsip_rr_hdr *hdr = pjsip_rr_hdr_create(ctx->pool); - if (!first) { - first = hdr; - } else { - pj_list_insert_before(first, hdr); - } - parse_hdr_rr_route(scanner, ctx->pool, hdr); - if (*scanner->curptr == ',') { - pj_scan_get_char(scanner); - } else { - break; - } + pjsip_rr_hdr *hdr = pjsip_rr_hdr_create(ctx->pool); + if (!first) { + first = hdr; + } else { + pj_list_insert_before(first, hdr); + } + parse_hdr_rr_route(scanner, ctx->pool, hdr); + if (*scanner->curptr == ',') { + pj_scan_get_char(scanner); + } else { + break; + } } while (1); parse_hdr_end(scanner); @@ -2293,18 +2292,18 @@ static pjsip_hdr* parse_hdr_route( pjsip_parse_ctx *ctx ) pj_scanner *scanner = ctx->scanner; do { - pjsip_route_hdr *hdr = pjsip_route_hdr_create(ctx->pool); - if (!first) { - first = hdr; - } else { - pj_list_insert_before(first, hdr); - } - parse_hdr_rr_route(scanner, ctx->pool, hdr); - if (*scanner->curptr == ',') { - pj_scan_get_char(scanner); - } else { - break; - } + pjsip_route_hdr *hdr = pjsip_route_hdr_create(ctx->pool); + if (!first) { + first = hdr; + } else { + pj_list_insert_before(first, hdr); + } + parse_hdr_rr_route(scanner, ctx->pool, hdr); + if (*scanner->curptr == ',') { + pj_scan_get_char(scanner); + } else { + break; + } } while (1); parse_hdr_end(scanner); @@ -2321,39 +2320,39 @@ static pjsip_hdr* parse_hdr_via( pjsip_parse_ctx *ctx ) pj_scanner *scanner = ctx->scanner; do { - pjsip_via_hdr *hdr = pjsip_via_hdr_create(ctx->pool); - if (!first) - first = hdr; - else - pj_list_insert_before(first, hdr); - - parse_sip_version(scanner); - if (pj_scan_get_char(scanner) != '/') - on_syntax_error(scanner); - - pj_scan_get( scanner, &pconst.pjsip_TOKEN_SPEC, &hdr->transport); - int_parse_host(scanner, &hdr->sent_by.host); - - if (*scanner->curptr==':') { - pj_str_t digit; - pj_scan_get_char(scanner); - pj_scan_get(scanner, &pconst.pjsip_DIGIT_SPEC, &digit); - strtoi_validate(&digit, PJSIP_MIN_PORT, PJSIP_MAX_PORT, + pjsip_via_hdr *hdr = pjsip_via_hdr_create(ctx->pool); + if (!first) + first = hdr; + else + pj_list_insert_before(first, hdr); + + parse_sip_version(scanner); + if (pj_scan_get_char(scanner) != '/') + on_syntax_error(scanner); + + pj_scan_get( scanner, &pconst.pjsip_TOKEN_SPEC, &hdr->transport); + int_parse_host(scanner, &hdr->sent_by.host); + + if (*scanner->curptr==':') { + pj_str_t digit; + pj_scan_get_char(scanner); + pj_scan_get(scanner, &pconst.pjsip_DIGIT_SPEC, &digit); + strtoi_validate(&digit, PJSIP_MIN_PORT, PJSIP_MAX_PORT, &hdr->sent_by.port); - } - - int_parse_via_param(hdr, scanner, ctx->pool); + } + + int_parse_via_param(hdr, scanner, ctx->pool); - if (*scanner->curptr == '(') { - pj_scan_get_char(scanner); - pj_scan_get_until_ch( scanner, ')', &hdr->comment); - pj_scan_get_char( scanner ); - } + if (*scanner->curptr == '(') { + pj_scan_get_char(scanner); + pj_scan_get_until_ch( scanner, ')', &hdr->comment); + pj_scan_get_char( scanner ); + } - if (*scanner->curptr != ',') - break; + if (*scanner->curptr != ',') + break; - pj_scan_get_char(scanner); + pj_scan_get_char(scanner); } while (1); @@ -2378,7 +2377,7 @@ static pjsip_hdr* parse_hdr_generic_string( pjsip_parse_ctx *ctx ) /* Public function to parse a header value. */ PJ_DEF(void*) pjsip_parse_hdr( pj_pool_t *pool, const pj_str_t *hname, - char *buf, pj_size_t size, int *parsed_len ) + char *buf, pj_size_t size, int *parsed_len ) { pj_scanner scanner; pjsip_hdr *hdr = NULL; @@ -2393,24 +2392,24 @@ PJ_DEF(void*) pjsip_parse_hdr( pj_pool_t *pool, const pj_str_t *hname, context.rdata = NULL; PJ_TRY { - pjsip_parse_hdr_func *func = find_handler(hname); - if (func) { - hdr = (*func)(&context); - } else { - hdr = parse_hdr_generic_string(&context); - hdr->type = PJSIP_H_OTHER; - pj_strdup(pool, &hdr->name, hname); - hdr->sname = hdr->name; - } + pjsip_parse_hdr_func *func = find_handler(hname); + if (func) { + hdr = (*func)(&context); + } else { + hdr = parse_hdr_generic_string(&context); + hdr->type = PJSIP_H_OTHER; + pj_strdup(pool, &hdr->name, hname); + hdr->sname = hdr->name; + } } PJ_CATCH_ANY { - hdr = NULL; + hdr = NULL; } PJ_END if (parsed_len) { - *parsed_len = (unsigned)(scanner.curptr - scanner.begin); + *parsed_len = (unsigned)(scanner.curptr - scanner.begin); } pj_scan_fini(&scanner); @@ -2420,8 +2419,8 @@ PJ_DEF(void*) pjsip_parse_hdr( pj_pool_t *pool, const pj_str_t *hname, /* Parse multiple header lines */ PJ_DEF(pj_status_t) pjsip_parse_headers( pj_pool_t *pool, char *input, - pj_size_t size, pjsip_hdr *hlist, - unsigned options) + pj_size_t size, pjsip_hdr *hlist, + unsigned options) { enum { STOP_ON_ERROR = 1 }; pj_str_t hname; @@ -2440,84 +2439,84 @@ PJ_DEF(pj_status_t) pjsip_parse_headers( pj_pool_t *pool, char *input, retry_parse: PJ_TRY { - /* Parse headers. */ - do { - pjsip_parse_hdr_func * func; - pjsip_hdr *hdr = NULL; - - /* Init hname just in case parsing fails. - * Ref: PROTOS #2412 - */ - hname.slen = 0; - - /* Get hname. */ - pj_scan_get( &scanner, &pconst.pjsip_TOKEN_SPEC, &hname); - if (pj_scan_get_char( &scanner ) != ':') { - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); - } - - /* Find handler. */ - func = find_handler(&hname); - - /* Call the handler if found. - * If no handler is found, then treat the header as generic - * hname/hvalue pair. - */ - if (func) { - hdr = (*func)(&ctx); - } else { - hdr = parse_hdr_generic_string(&ctx); - hdr->name = hdr->sname = hname; - } - - /* Single parse of header line can produce multiple headers. - * For example, if one Contact: header contains Contact list - * separated by comma, then these Contacts will be split into - * different Contact headers. - * So here we must insert list instead of just insert one header. - */ - if (hdr) - pj_list_insert_nodes_before(hlist, hdr); - - /* Parse until EOF or an empty line is found. */ - } while (!pj_scan_is_eof(&scanner) && !IS_NEWLINE(*scanner.curptr)); - - /* If empty line is found, eat it. */ - if (!pj_scan_is_eof(&scanner)) { - if (IS_NEWLINE(*scanner.curptr)) { - pj_scan_get_newline(&scanner); - } - } + /* Parse headers. */ + do { + pjsip_parse_hdr_func * func; + pjsip_hdr *hdr = NULL; + + /* Init hname just in case parsing fails. + * Ref: PROTOS #2412 + */ + hname.slen = 0; + + /* Get hname. */ + pj_scan_get( &scanner, &pconst.pjsip_TOKEN_SPEC, &hname); + if (pj_scan_get_char( &scanner ) != ':') { + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + } + + /* Find handler. */ + func = find_handler(&hname); + + /* Call the handler if found. + * If no handler is found, then treat the header as generic + * hname/hvalue pair. + */ + if (func) { + hdr = (*func)(&ctx); + } else { + hdr = parse_hdr_generic_string(&ctx); + hdr->name = hdr->sname = hname; + } + + /* Single parse of header line can produce multiple headers. + * For example, if one Contact: header contains Contact list + * separated by comma, then these Contacts will be split into + * different Contact headers. + * So here we must insert list instead of just insert one header. + */ + if (hdr) + pj_list_insert_nodes_before(hlist, hdr); + + /* Parse until EOF or an empty line is found. */ + } while (!pj_scan_is_eof(&scanner) && !IS_NEWLINE(*scanner.curptr)); + + /* If empty line is found, eat it. */ + if (!pj_scan_is_eof(&scanner)) { + if (IS_NEWLINE(*scanner.curptr)) { + pj_scan_get_newline(&scanner); + } + } } PJ_CATCH_ANY { - PJ_LOG(4,(THIS_FILE, "Error parsing header: '%.*s' line %d col %d", - (int)hname.slen, hname.ptr, scanner.line, - pj_scan_get_col(&scanner))); - - /* Exception was thrown during parsing. */ - if ((options & STOP_ON_ERROR) == STOP_ON_ERROR) { - pj_scan_fini(&scanner); - return PJSIP_EINVALIDHDR; - } - - /* Skip until newline, and parse next header. */ - if (!pj_scan_is_eof(&scanner)) { - /* Skip until next line. - * Watch for header continuation. - */ - do { - pj_scan_skip_line(&scanner); - } while (IS_SPACE(*scanner.curptr)); - } - - /* Restore flag. Flag may be set in int_parse_sip_url() */ - scanner.skip_ws = PJ_SCAN_AUTOSKIP_WS_HEADER; - - /* Continue parse next header, if any. */ - if (!pj_scan_is_eof(&scanner) && !IS_NEWLINE(*scanner.curptr)) { - goto retry_parse; - } + PJ_LOG(4,(THIS_FILE, "Error parsing header: '%.*s' line %d col %d", + (int)hname.slen, hname.ptr, scanner.line, + pj_scan_get_col(&scanner))); + + /* Exception was thrown during parsing. */ + if ((options & STOP_ON_ERROR) == STOP_ON_ERROR) { + pj_scan_fini(&scanner); + return PJSIP_EINVALIDHDR; + } + + /* Skip until newline, and parse next header. */ + if (!pj_scan_is_eof(&scanner)) { + /* Skip until next line. + * Watch for header continuation. + */ + do { + pj_scan_skip_line(&scanner); + } while (IS_SPACE(*scanner.curptr)); + } + + /* Restore flag. Flag may be set in int_parse_sip_url() */ + scanner.skip_ws = PJ_SCAN_AUTOSKIP_WS_HEADER; + + /* Continue parse next header, if any. */ + if (!pj_scan_is_eof(&scanner) && !IS_NEWLINE(*scanner.curptr)) { + goto retry_parse; + } } PJ_END; diff --git a/pjsip/src/pjsip/sip_parser_wrap.cpp b/pjsip/src/pjsip/sip_parser_wrap.cpp index e74d27c2e4..92d0a3e83c 100644 --- a/pjsip/src/pjsip/sip_parser_wrap.cpp +++ b/pjsip/src/pjsip/sip_parser_wrap.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjsip/src/pjsip/sip_resolve.c b/pjsip/src/pjsip/sip_resolve.c index ab20577a9e..bf80dc9c6d 100644 --- a/pjsip/src/pjsip/sip_resolve.c +++ b/pjsip/src/pjsip/sip_resolve.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -36,33 +35,33 @@ struct naptr_target { - pj_str_t res_type; /**< e.g. "_sip._udp" */ - pj_str_t name; /**< Domain name. */ - pjsip_transport_type_e type; /**< Transport type. */ - unsigned order; /**< Order */ - unsigned pref; /**< Preference. */ + pj_str_t res_type; /**< e.g. "_sip._udp" */ + pj_str_t name; /**< Domain name. */ + pjsip_transport_type_e type; /**< Transport type. */ + unsigned order; /**< Order */ + unsigned pref; /**< Preference. */ }; struct query { - char *objname; + char *objname; - pj_dns_type query_type; - void *token; + pj_dns_type query_type; + void *token; pjsip_resolver_callback *cb; - pj_dns_async_query *object; - pj_dns_async_query *object6; - pj_status_t last_error; + pj_dns_async_query *object; + pj_dns_async_query *object6; + pj_status_t last_error; /* Original request: */ struct { - pjsip_host_info target; - unsigned def_port; + pjsip_host_info target; + unsigned def_port; } req; /* NAPTR records: */ - unsigned naptr_cnt; - struct naptr_target naptr[8]; + unsigned naptr_cnt; + struct naptr_target naptr[8]; /* Query result */ pjsip_server_addresses server; @@ -77,21 +76,21 @@ struct pjsip_resolver_t static void srv_resolver_cb(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec); + pj_status_t status, + const pj_dns_srv_record *rec); static void dns_a_callback(void *user_data, - pj_status_t status, - pj_dns_parsed_packet *response); + pj_status_t status, + pj_dns_parsed_packet *response); static void dns_aaaa_callback(void *user_data, - pj_status_t status, - pj_dns_parsed_packet *response); + pj_status_t status, + pj_dns_parsed_packet *response); /* * Public API to create the resolver. */ PJ_DEF(pj_status_t) pjsip_resolver_create( pj_pool_t *pool, - pjsip_resolver_t **p_res) + pjsip_resolver_t **p_res) { pjsip_resolver_t *resolver; @@ -107,7 +106,7 @@ PJ_DEF(pj_status_t) pjsip_resolver_create( pj_pool_t *pool, * Public API to set the DNS resolver instance for the SIP resolver. */ PJ_DEF(pj_status_t) pjsip_resolver_set_resolver(pjsip_resolver_t *res, - pj_dns_resolver *dns_res) + pj_dns_resolver *dns_res) { #if PJSIP_HAS_RESOLVER res->res = dns_res; @@ -128,13 +127,13 @@ PJ_DEF(pj_status_t) pjsip_resolver_set_ext_resolver(pjsip_resolver_t *res, pjsip_ext_resolver *ext_res) { if (ext_res && !ext_res->resolve) - return PJ_EINVAL; + return PJ_EINVAL; if (ext_res && res->res) { #if PJSIP_HAS_RESOLVER - pj_dns_resolver_destroy(res->res, PJ_FALSE); + pj_dns_resolver_destroy(res->res, PJ_FALSE); #endif - res->res = NULL; + res->res = NULL; } res->ext_res = ext_res; return PJ_SUCCESS; @@ -157,9 +156,9 @@ PJ_DEF(void) pjsip_resolver_destroy(pjsip_resolver_t *resolver) { if (resolver->res) { #if PJSIP_HAS_RESOLVER - pj_dns_resolver_destroy(resolver->res, PJ_FALSE); + pj_dns_resolver_destroy(resolver->res, PJ_FALSE); #endif - resolver->res = NULL; + resolver->res = NULL; } } @@ -175,11 +174,11 @@ static int get_ip_addr_ver(const pj_str_t *host) /* First check if this is an IPv4 address */ if (pj_inet_pton(pj_AF_INET(), host, &dummy) == PJ_SUCCESS) - return 4; + return 4; /* Then check if this is an IPv6 address */ if (pj_inet_pton(pj_AF_INET6(), host, &dummy6) == PJ_SUCCESS) - return 6; + return 6; /* Not an IP address */ return 0; @@ -190,10 +189,10 @@ static int get_ip_addr_ver(const pj_str_t *host) * This is the main function for performing server resolution. */ PJ_DEF(void) pjsip_resolve( pjsip_resolver_t *resolver, - pj_pool_t *pool, - const pjsip_host_info *target, - void *token, - pjsip_resolver_callback *cb) + pj_pool_t *pool, + const pjsip_host_info *target, + void *token, + pjsip_resolver_callback *cb) { pjsip_server_addresses svr_addr; pj_status_t status = PJ_SUCCESS; @@ -217,9 +216,9 @@ PJ_DEF(void) pjsip_resolve( pjsip_resolver_t *resolver, */ #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6==1 if ((ip_addr_ver == 6) || (type & PJSIP_TRANSPORT_IPV6)) - af = pj_AF_INET6(); + af = pj_AF_INET6(); else if (ip_addr_ver == 4) - af = pj_AF_INET(); + af = pj_AF_INET(); #else /* IPv6 is disabled, will resolving IPv6 address be useful? */ af = pj_AF_INET(); @@ -229,38 +228,38 @@ PJ_DEF(void) pjsip_resolve( pjsip_resolver_t *resolver, * RFC 3263 section 4.1 specify rules to set up this. */ if (type == PJSIP_TRANSPORT_UNSPECIFIED) { - if (ip_addr_ver || (target->addr.port != 0)) { + if (ip_addr_ver || (target->addr.port != 0)) { #if PJ_HAS_TCP - if (target->flag & PJSIP_TRANSPORT_SECURE) - { - type = PJSIP_TRANSPORT_TLS; - } else if (target->flag & PJSIP_TRANSPORT_RELIABLE) - { - type = PJSIP_TRANSPORT_TCP; - } else + if (target->flag & PJSIP_TRANSPORT_SECURE) + { + type = PJSIP_TRANSPORT_TLS; + } else if (target->flag & PJSIP_TRANSPORT_RELIABLE) + { + type = PJSIP_TRANSPORT_TCP; + } else #endif - { - type = PJSIP_TRANSPORT_UDP; - } - } else { - /* No type or explicit port is specified, and the address is - * not IP address. - * In this case, full NAPTR resolution must be performed. - * But we don't support it (yet). - */ + { + type = PJSIP_TRANSPORT_UDP; + } + } else { + /* No type or explicit port is specified, and the address is + * not IP address. + * In this case, full NAPTR resolution must be performed. + * But we don't support it (yet). + */ #if PJ_HAS_TCP - if (target->flag & PJSIP_TRANSPORT_SECURE) - { - type = PJSIP_TRANSPORT_TLS; - } else if (target->flag & PJSIP_TRANSPORT_RELIABLE) - { - type = PJSIP_TRANSPORT_TCP; - } else + if (target->flag & PJSIP_TRANSPORT_SECURE) + { + type = PJSIP_TRANSPORT_TLS; + } else if (target->flag & PJSIP_TRANSPORT_RELIABLE) + { + type = PJSIP_TRANSPORT_TCP; + } else #endif - { - type = PJSIP_TRANSPORT_UDP; - } - } + { + type = PJSIP_TRANSPORT_UDP; + } + } } @@ -268,122 +267,122 @@ PJ_DEF(void) pjsip_resolve( pjsip_resolver_t *resolver, * we can just finish the resolution now using pj_gethostbyname() */ if (ip_addr_ver || resolver->res == NULL) { - char addr_str[PJ_INET6_ADDRSTRLEN+10]; - pj_uint16_t srv_port; - unsigned i; - - if (ip_addr_ver != 0) { - /* Target is an IP address, no need to resolve */ - svr_addr.count = 1; - if (ip_addr_ver == 4) { - if (af == pj_AF_INET6()) { - /* Generate a synthesized IPv6 address, if possible. */ - unsigned int count = 1; - pj_addrinfo ai[1]; - pj_status_t status2; + char addr_str[PJ_INET6_ADDRSTRLEN+10]; + pj_uint16_t srv_port; + unsigned i; + + if (ip_addr_ver != 0) { + /* Target is an IP address, no need to resolve */ + svr_addr.count = 1; + if (ip_addr_ver == 4) { + if (af == pj_AF_INET6()) { + /* Generate a synthesized IPv6 address, if possible. */ + unsigned int count = 1; + pj_addrinfo ai[1]; + pj_status_t status2; status2 = pj_getaddrinfo(pj_AF_INET6(), - &target->addr.host, &count, ai); - if (status2 == PJ_SUCCESS && count > 0 && - ai[0].ai_addr.addr.sa_family == pj_AF_INET6()) - { - pj_sockaddr_init(pj_AF_INET6(), - &svr_addr.entry[0].addr, - NULL, 0); - svr_addr.entry[0].addr.ipv6.sin6_addr = - ai[0].ai_addr.ipv6.sin6_addr; - } else { - pj_sockaddr_init(pj_AF_INET(), - &svr_addr.entry[0].addr, NULL, 0); - pj_inet_pton(pj_AF_INET(), &target->addr.host, - &svr_addr.entry[0].addr.ipv4.sin_addr); - } - } else { - pj_sockaddr_init(pj_AF_INET(), &svr_addr.entry[0].addr, - NULL, 0); - pj_inet_pton(pj_AF_INET(), &target->addr.host, - &svr_addr.entry[0].addr.ipv4.sin_addr); - } - } else { - pj_sockaddr_init(pj_AF_INET6(), &svr_addr.entry[0].addr, - NULL, 0); - pj_inet_pton(pj_AF_INET6(), &target->addr.host, - &svr_addr.entry[0].addr.ipv6.sin6_addr); - } - } else { - pj_addrinfo ai[PJSIP_MAX_RESOLVED_ADDRESSES]; - unsigned count; - - PJ_LOG(5,(THIS_FILE, - "DNS resolver not available, target '%.*s:%d' type=%s " - "will be resolved with getaddrinfo()", - target->addr.host.slen, - target->addr.host.ptr, - target->addr.port, - pjsip_transport_get_type_name(target->type))); - - /* Resolve */ - count = PJSIP_MAX_RESOLVED_ADDRESSES; - status = pj_getaddrinfo(af, &target->addr.host, &count, ai); - if (status != PJ_SUCCESS) { - /* "Normalize" error to PJ_ERESOLVE. This is a special error - * because it will be translated to SIP status 502 by - * sip_transaction.c - */ - status = PJ_ERESOLVE; - goto on_error; - } - - svr_addr.count = count; - for (i = 0; i < count; i++) { - pj_sockaddr_cp(&svr_addr.entry[i].addr, &ai[i].ai_addr); - } - } - - for (i = 0; i < svr_addr.count; i++) { - /* After address resolution, update IPv6 bitflag in - * transport type. - */ - af = svr_addr.entry[i].addr.addr.sa_family; - if (af == pj_AF_INET6()) { - type |= PJSIP_TRANSPORT_IPV6; - } else { - type &= ~PJSIP_TRANSPORT_IPV6; - } - - /* Set the port number */ - if (target->addr.port == 0) { - srv_port = (pj_uint16_t) - pjsip_transport_get_default_port_for_type(type); - } else { - srv_port = (pj_uint16_t)target->addr.port; - } - pj_sockaddr_set_port(&svr_addr.entry[i].addr, srv_port); - - PJ_LOG(5,(THIS_FILE, - "Target '%.*s:%d' type=%s resolved to " - "'%s' type=%s (%s)", - (int)target->addr.host.slen, - target->addr.host.ptr, - target->addr.port, - pjsip_transport_get_type_name(target->type), - pj_sockaddr_print(&svr_addr.entry[i].addr, addr_str, - sizeof(addr_str), 3), - pjsip_transport_get_type_name(type), - pjsip_transport_get_type_desc(type))); - - svr_addr.entry[i].priority = 0; - svr_addr.entry[i].weight = 0; - svr_addr.entry[i].type = type; - svr_addr.entry[i].addr_len = - pj_sockaddr_get_len(&svr_addr.entry[i].addr); - } - - /* Call the callback. */ - (*cb)(status, token, &svr_addr); - - /* Done. */ - return; + &target->addr.host, &count, ai); + if (status2 == PJ_SUCCESS && count > 0 && + ai[0].ai_addr.addr.sa_family == pj_AF_INET6()) + { + pj_sockaddr_init(pj_AF_INET6(), + &svr_addr.entry[0].addr, + NULL, 0); + svr_addr.entry[0].addr.ipv6.sin6_addr = + ai[0].ai_addr.ipv6.sin6_addr; + } else { + pj_sockaddr_init(pj_AF_INET(), + &svr_addr.entry[0].addr, NULL, 0); + pj_inet_pton(pj_AF_INET(), &target->addr.host, + &svr_addr.entry[0].addr.ipv4.sin_addr); + } + } else { + pj_sockaddr_init(pj_AF_INET(), &svr_addr.entry[0].addr, + NULL, 0); + pj_inet_pton(pj_AF_INET(), &target->addr.host, + &svr_addr.entry[0].addr.ipv4.sin_addr); + } + } else { + pj_sockaddr_init(pj_AF_INET6(), &svr_addr.entry[0].addr, + NULL, 0); + pj_inet_pton(pj_AF_INET6(), &target->addr.host, + &svr_addr.entry[0].addr.ipv6.sin6_addr); + } + } else { + pj_addrinfo ai[PJSIP_MAX_RESOLVED_ADDRESSES]; + unsigned count; + + PJ_LOG(5,(THIS_FILE, + "DNS resolver not available, target '%.*s:%d' type=%s " + "will be resolved with getaddrinfo()", + target->addr.host.slen, + target->addr.host.ptr, + target->addr.port, + pjsip_transport_get_type_name(target->type))); + + /* Resolve */ + count = PJSIP_MAX_RESOLVED_ADDRESSES; + status = pj_getaddrinfo(af, &target->addr.host, &count, ai); + if (status != PJ_SUCCESS) { + /* "Normalize" error to PJ_ERESOLVE. This is a special error + * because it will be translated to SIP status 502 by + * sip_transaction.c + */ + status = PJ_ERESOLVE; + goto on_error; + } + + svr_addr.count = count; + for (i = 0; i < count; i++) { + pj_sockaddr_cp(&svr_addr.entry[i].addr, &ai[i].ai_addr); + } + } + + for (i = 0; i < svr_addr.count; i++) { + /* After address resolution, update IPv6 bitflag in + * transport type. + */ + af = svr_addr.entry[i].addr.addr.sa_family; + if (af == pj_AF_INET6()) { + type |= PJSIP_TRANSPORT_IPV6; + } else { + type &= ~PJSIP_TRANSPORT_IPV6; + } + + /* Set the port number */ + if (target->addr.port == 0) { + srv_port = (pj_uint16_t) + pjsip_transport_get_default_port_for_type(type); + } else { + srv_port = (pj_uint16_t)target->addr.port; + } + pj_sockaddr_set_port(&svr_addr.entry[i].addr, srv_port); + + PJ_LOG(5,(THIS_FILE, + "Target '%.*s:%d' type=%s resolved to " + "'%s' type=%s (%s)", + (int)target->addr.host.slen, + target->addr.host.ptr, + target->addr.port, + pjsip_transport_get_type_name(target->type), + pj_sockaddr_print(&svr_addr.entry[i].addr, addr_str, + sizeof(addr_str), 3), + pjsip_transport_get_type_name(type), + pjsip_transport_get_type_desc(type))); + + svr_addr.entry[i].priority = 0; + svr_addr.entry[i].weight = 0; + svr_addr.entry[i].type = type; + svr_addr.entry[i].addr_len = + pj_sockaddr_get_len(&svr_addr.entry[i].addr); + } + + /* Call the callback. */ + (*cb)(status, token, &svr_addr); + + /* Done. */ + return; } /* Target is not an IP address so we need to resolve it. */ @@ -413,95 +412,95 @@ PJ_DEF(void) pjsip_resolve( pjsip_resolver_t *resolver, /* Start DNS SRV or A resolution, depending on whether port is specified */ if (target->addr.port == 0) { - query->query_type = PJ_DNS_TYPE_SRV; - - query->req.def_port = 5060; - - if (type == PJSIP_TRANSPORT_TLS || type == PJSIP_TRANSPORT_TLS6) { - query->naptr[0].res_type = pj_str("_sips._tcp."); - query->req.def_port = 5061; - } else if (type == PJSIP_TRANSPORT_TCP || type == PJSIP_TRANSPORT_TCP6) - query->naptr[0].res_type = pj_str("_sip._tcp."); - else if (type == PJSIP_TRANSPORT_UDP || type == PJSIP_TRANSPORT_UDP6) - query->naptr[0].res_type = pj_str("_sip._udp."); - else { - pj_assert(!"Unknown transport type"); - query->naptr[0].res_type = pj_str("_sip._udp."); - - } + query->query_type = PJ_DNS_TYPE_SRV; + + query->req.def_port = 5060; + + if (type == PJSIP_TRANSPORT_TLS || type == PJSIP_TRANSPORT_TLS6) { + query->naptr[0].res_type = pj_str("_sips._tcp."); + query->req.def_port = 5061; + } else if (type == PJSIP_TRANSPORT_TCP || type == PJSIP_TRANSPORT_TCP6) + query->naptr[0].res_type = pj_str("_sip._tcp."); + else if (type == PJSIP_TRANSPORT_UDP || type == PJSIP_TRANSPORT_UDP6) + query->naptr[0].res_type = pj_str("_sip._udp."); + else { + pj_assert(!"Unknown transport type"); + query->naptr[0].res_type = pj_str("_sip._udp."); + + } } else { - /* Otherwise if port is specified, start with A (or AAAA) host - * resolution - */ - query->query_type = PJ_DNS_TYPE_A; - query->naptr[0].res_type.slen = 0; - query->req.def_port = target->addr.port; + /* Otherwise if port is specified, start with A (or AAAA) host + * resolution + */ + query->query_type = PJ_DNS_TYPE_A; + query->naptr[0].res_type.slen = 0; + query->req.def_port = target->addr.port; } /* Start the asynchronous query */ PJ_LOG(5, (query->objname, - "Starting async DNS %s query: target=%.*s%.*s, transport=%s, " - "port=%d", - pj_dns_get_type_name(query->query_type), - (int)query->naptr[0].res_type.slen, - query->naptr[0].res_type.ptr, - (int)query->naptr[0].name.slen, query->naptr[0].name.ptr, - pjsip_transport_get_type_name(target->type), - target->addr.port)); + "Starting async DNS %s query: target=%.*s%.*s, transport=%s, " + "port=%d", + pj_dns_get_type_name(query->query_type), + (int)query->naptr[0].res_type.slen, + query->naptr[0].res_type.ptr, + (int)query->naptr[0].name.slen, query->naptr[0].name.ptr, + pjsip_transport_get_type_name(target->type), + target->addr.port)); if (query->query_type == PJ_DNS_TYPE_SRV) { - int opt = 0; + int opt = 0; - if (af == pj_AF_UNSPEC()) - opt = PJ_DNS_SRV_FALLBACK_A | PJ_DNS_SRV_FALLBACK_AAAA | - PJ_DNS_SRV_RESOLVE_AAAA; - else if (af == pj_AF_INET6()) - opt = PJ_DNS_SRV_FALLBACK_AAAA | PJ_DNS_SRV_RESOLVE_AAAA_ONLY; - else /* af == pj_AF_INET() */ - opt = PJ_DNS_SRV_FALLBACK_A; + if (af == pj_AF_UNSPEC()) + opt = PJ_DNS_SRV_FALLBACK_A | PJ_DNS_SRV_FALLBACK_AAAA | + PJ_DNS_SRV_RESOLVE_AAAA; + else if (af == pj_AF_INET6()) + opt = PJ_DNS_SRV_FALLBACK_AAAA | PJ_DNS_SRV_RESOLVE_AAAA_ONLY; + else /* af == pj_AF_INET() */ + opt = PJ_DNS_SRV_FALLBACK_A; - status = pj_dns_srv_resolve(&query->naptr[0].name, - &query->naptr[0].res_type, - query->req.def_port, pool, resolver->res, - opt, query, &srv_resolver_cb, NULL); + status = pj_dns_srv_resolve(&query->naptr[0].name, + &query->naptr[0].res_type, + query->req.def_port, pool, resolver->res, + opt, query, &srv_resolver_cb, NULL); } else if (query->query_type == PJ_DNS_TYPE_A) { - /* Resolve DNS A record if address family is not fixed to IPv6 */ - if (af != pj_AF_INET6()) { - - /* If there will be DNS AAAA query too, let's setup a dummy one - * here, otherwise app callback may be called immediately (before - * DNS AAAA query is sent) when DNS A record is available in the - * cache. - */ - if (af == pj_AF_UNSPEC()) - query->object6 = (pj_dns_async_query*)0x1; - - status = pj_dns_resolver_start_query(resolver->res, - &query->naptr[0].name, - PJ_DNS_TYPE_A, 0, - &dns_a_callback, - query, &query->object); - } - - /* Resolve DNS AAAA record if address family is not fixed to IPv4 */ - if (af != pj_AF_INET() && status == PJ_SUCCESS) { - status = pj_dns_resolver_start_query(resolver->res, - &query->naptr[0].name, - PJ_DNS_TYPE_AAAA, 0, - &dns_aaaa_callback, - query, &query->object6); - } + /* Resolve DNS A record if address family is not fixed to IPv6 */ + if (af != pj_AF_INET6()) { + + /* If there will be DNS AAAA query too, let's setup a dummy one + * here, otherwise app callback may be called immediately (before + * DNS AAAA query is sent) when DNS A record is available in the + * cache. + */ + if (af == pj_AF_UNSPEC()) + query->object6 = (pj_dns_async_query*)0x1; + + status = pj_dns_resolver_start_query(resolver->res, + &query->naptr[0].name, + PJ_DNS_TYPE_A, 0, + &dns_a_callback, + query, &query->object); + } + + /* Resolve DNS AAAA record if address family is not fixed to IPv4 */ + if (af != pj_AF_INET() && status == PJ_SUCCESS) { + status = pj_dns_resolver_start_query(resolver->res, + &query->naptr[0].name, + PJ_DNS_TYPE_AAAA, 0, + &dns_aaaa_callback, + query, &query->object6); + } } else { - pj_assert(!"Unexpected"); - status = PJ_EBUG; + pj_assert(!"Unexpected"); + status = PJ_EBUG; } if (status != PJ_SUCCESS) - goto on_error; + goto on_error; return; @@ -512,12 +511,12 @@ PJ_DEF(void) pjsip_resolve( pjsip_resolver_t *resolver, on_error: if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Failed to resolve '%.*s'", - (int)target->addr.host.slen, - target->addr.host.ptr)); - (*cb)(status, token, NULL); - return; + PJ_PERROR(4,(THIS_FILE, status, + "Failed to resolve '%.*s'", + (int)target->addr.host.slen, + target->addr.host.ptr)); + (*cb)(status, token, NULL); + return; } } @@ -527,8 +526,8 @@ PJ_DEF(void) pjsip_resolve( pjsip_resolver_t *resolver, * This callback is called when target is resolved with DNS A query. */ static void dns_a_callback(void *user_data, - pj_status_t status, - pj_dns_parsed_packet *pkt) + pj_status_t status, + pj_dns_parsed_packet *pkt) { struct query *query = (struct query*) user_data; pjsip_server_addresses *srv = &query->server; @@ -537,46 +536,46 @@ static void dns_a_callback(void *user_data, query->object = NULL; if (status == PJ_SUCCESS) { - pj_dns_addr_record rec; - unsigned i; - - /* Parse the response */ - rec.addr_count = 0; - status = pj_dns_parse_addr_response(pkt, &rec); - - /* Build server addresses and call callback */ - for (i = 0; i < rec.addr_count && - srv->count < PJSIP_MAX_RESOLVED_ADDRESSES; ++i) - { - /* Should not happen, just in case */ - if (rec.addr[i].af != pj_AF_INET()) - continue; - - srv->entry[srv->count].type = query->naptr[0].type; - srv->entry[srv->count].priority = 0; - srv->entry[srv->count].weight = 0; - srv->entry[srv->count].addr_len = sizeof(pj_sockaddr_in); - pj_sockaddr_in_init(&srv->entry[srv->count].addr.ipv4, - 0, (pj_uint16_t)query->req.def_port); - srv->entry[srv->count].addr.ipv4.sin_addr = rec.addr[i].ip.v4; - - ++srv->count; - } + pj_dns_addr_record rec; + unsigned i; + + /* Parse the response */ + rec.addr_count = 0; + status = pj_dns_parse_addr_response(pkt, &rec); + + /* Build server addresses and call callback */ + for (i = 0; i < rec.addr_count && + srv->count < PJSIP_MAX_RESOLVED_ADDRESSES; ++i) + { + /* Should not happen, just in case */ + if (rec.addr[i].af != pj_AF_INET()) + continue; + + srv->entry[srv->count].type = query->naptr[0].type; + srv->entry[srv->count].priority = 0; + srv->entry[srv->count].weight = 0; + srv->entry[srv->count].addr_len = sizeof(pj_sockaddr_in); + pj_sockaddr_in_init(&srv->entry[srv->count].addr.ipv4, + 0, (pj_uint16_t)query->req.def_port); + srv->entry[srv->count].addr.ipv4.sin_addr = rec.addr[i].ip.v4; + + ++srv->count; + } } if (status != PJ_SUCCESS) { - PJ_PERROR(4,(query->objname, status, - "DNS A record resolution failed")); + PJ_PERROR(4,(query->objname, status, + "DNS A record resolution failed")); - query->last_error = status; + query->last_error = status; } /* Call the callback if all DNS queries have been completed */ if (query->object == NULL && query->object6 == NULL) { - if (srv->count > 0) - (*query->cb)(PJ_SUCCESS, query->token, &query->server); - else - (*query->cb)(query->last_error, query->token, NULL); + if (srv->count > 0) + (*query->cb)(PJ_SUCCESS, query->token, &query->server); + else + (*query->cb)(query->last_error, query->token, NULL); } } @@ -585,8 +584,8 @@ static void dns_a_callback(void *user_data, * This callback is called when target is resolved with DNS AAAA query. */ static void dns_aaaa_callback(void *user_data, - pj_status_t status, - pj_dns_parsed_packet *pkt) + pj_status_t status, + pj_dns_parsed_packet *pkt) { struct query *query = (struct query*) user_data; pjsip_server_addresses *srv = &query->server; @@ -595,102 +594,102 @@ static void dns_aaaa_callback(void *user_data, query->object6 = NULL; if (status == PJ_SUCCESS) { - pj_dns_addr_record rec; - unsigned i; - - /* Parse the response */ - rec.addr_count = 0; - status = pj_dns_parse_addr_response(pkt, &rec); - - /* Build server addresses and call callback */ - for (i = 0; i < rec.addr_count && - srv->count < PJSIP_MAX_RESOLVED_ADDRESSES; ++i) - { - /* Should not happen, just in case */ - if (rec.addr[i].af != pj_AF_INET6()) - continue; - - srv->entry[srv->count].type = query->naptr[0].type | - PJSIP_TRANSPORT_IPV6; - srv->entry[srv->count].priority = 0; - srv->entry[srv->count].weight = 0; - srv->entry[srv->count].addr_len = sizeof(pj_sockaddr_in6); - pj_sockaddr_init(pj_AF_INET6(), &srv->entry[srv->count].addr, - 0, (pj_uint16_t)query->req.def_port); - srv->entry[srv->count].addr.ipv6.sin6_addr = rec.addr[i].ip.v6; - - ++srv->count; - } + pj_dns_addr_record rec; + unsigned i; + + /* Parse the response */ + rec.addr_count = 0; + status = pj_dns_parse_addr_response(pkt, &rec); + + /* Build server addresses and call callback */ + for (i = 0; i < rec.addr_count && + srv->count < PJSIP_MAX_RESOLVED_ADDRESSES; ++i) + { + /* Should not happen, just in case */ + if (rec.addr[i].af != pj_AF_INET6()) + continue; + + srv->entry[srv->count].type = query->naptr[0].type | + PJSIP_TRANSPORT_IPV6; + srv->entry[srv->count].priority = 0; + srv->entry[srv->count].weight = 0; + srv->entry[srv->count].addr_len = sizeof(pj_sockaddr_in6); + pj_sockaddr_init(pj_AF_INET6(), &srv->entry[srv->count].addr, + 0, (pj_uint16_t)query->req.def_port); + srv->entry[srv->count].addr.ipv6.sin6_addr = rec.addr[i].ip.v6; + + ++srv->count; + } } if (status != PJ_SUCCESS) { - PJ_PERROR(4,(query->objname, status, - "DNS AAAA record resolution failed")); + PJ_PERROR(4,(query->objname, status, + "DNS AAAA record resolution failed")); - query->last_error = status; + query->last_error = status; } /* Call the callback if all DNS queries have been completed */ if (query->object == NULL && query->object6 == NULL) { - if (srv->count > 0) - (*query->cb)(PJ_SUCCESS, query->token, &query->server); - else - (*query->cb)(query->last_error, query->token, NULL); + if (srv->count > 0) + (*query->cb)(PJ_SUCCESS, query->token, &query->server); + else + (*query->cb)(query->last_error, query->token, NULL); } } /* Callback to be called by DNS SRV resolution */ static void srv_resolver_cb(void *user_data, - pj_status_t status, - const pj_dns_srv_record *rec) + pj_status_t status, + const pj_dns_srv_record *rec) { struct query *query = (struct query*) user_data; pjsip_server_addresses srv; unsigned i; if (status != PJ_SUCCESS) { - PJ_PERROR(4,(query->objname, status, - "DNS A/AAAA record resolution failed")); + PJ_PERROR(4,(query->objname, status, + "DNS A/AAAA record resolution failed")); - /* Call the callback */ - (*query->cb)(status, query->token, NULL); - return; + /* Call the callback */ + (*query->cb)(status, query->token, NULL); + return; } /* Build server addresses and call callback */ srv.count = 0; for (i=0; icount; ++i) { - const pj_dns_addr_record *s = &rec->entry[i].server; - unsigned j; - - for (j = 0; j < s->addr_count && - srv.count < PJSIP_MAX_RESOLVED_ADDRESSES; ++j) - { - srv.entry[srv.count].type = query->naptr[0].type; - srv.entry[srv.count].priority = rec->entry[i].priority; - srv.entry[srv.count].weight = rec->entry[i].weight; - pj_sockaddr_init(s->addr[j].af, - &srv.entry[srv.count].addr, - 0, (pj_uint16_t)rec->entry[i].port); - if (s->addr[j].af == pj_AF_INET6()) - srv.entry[srv.count].addr.ipv6.sin6_addr = s->addr[j].ip.v6; - else - srv.entry[srv.count].addr.ipv4.sin_addr = s->addr[j].ip.v4; - srv.entry[srv.count].addr_len = - pj_sockaddr_get_len(&srv.entry[srv.count].addr); - - /* Update transport type if this is IPv6 */ - if (s->addr[j].af == pj_AF_INET6()) - srv.entry[srv.count].type |= PJSIP_TRANSPORT_IPV6; - - ++srv.count; - } + const pj_dns_addr_record *s = &rec->entry[i].server; + unsigned j; + + for (j = 0; j < s->addr_count && + srv.count < PJSIP_MAX_RESOLVED_ADDRESSES; ++j) + { + srv.entry[srv.count].type = query->naptr[0].type; + srv.entry[srv.count].priority = rec->entry[i].priority; + srv.entry[srv.count].weight = rec->entry[i].weight; + pj_sockaddr_init(s->addr[j].af, + &srv.entry[srv.count].addr, + 0, (pj_uint16_t)rec->entry[i].port); + if (s->addr[j].af == pj_AF_INET6()) + srv.entry[srv.count].addr.ipv6.sin6_addr = s->addr[j].ip.v6; + else + srv.entry[srv.count].addr.ipv4.sin_addr = s->addr[j].ip.v4; + srv.entry[srv.count].addr_len = + pj_sockaddr_get_len(&srv.entry[srv.count].addr); + + /* Update transport type if this is IPv6 */ + if (s->addr[j].af == pj_AF_INET6()) + srv.entry[srv.count].type |= PJSIP_TRANSPORT_IPV6; + + ++srv.count; + } } /* Call the callback */ (*query->cb)(PJ_SUCCESS, query->token, &srv); } -#endif /* PJSIP_HAS_RESOLVER */ +#endif /* PJSIP_HAS_RESOLVER */ diff --git a/pjsip/src/pjsip/sip_tel_uri.c b/pjsip/src/pjsip/sip_tel_uri.c index eae41d5ad1..1ee7f5b485 100644 --- a/pjsip/src/pjsip/sip_tel_uri.c +++ b/pjsip/src/pjsip/sip_tel_uri.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -30,23 +29,23 @@ #include #define ALPHA -#define DIGITS "0123456789" -#define HEX "aAbBcCdDeEfF" -#define HEX_DIGITS DIGITS HEX -#define VISUAL_SEP "-.()" -#define PHONE_DIGITS DIGITS VISUAL_SEP -#define GLOBAL_DIGITS "+" PHONE_DIGITS -#define LOCAL_DIGITS HEX_DIGITS "*#" VISUAL_SEP -#define NUMBER_SPEC LOCAL_DIGITS GLOBAL_DIGITS -#define PHONE_CONTEXT ALPHA GLOBAL_DIGITS -//#define RESERVED ";/?:@&=+$," -#define RESERVED "/:@&$,+" -#define MARK "-_.!~*'()" -#define UNRESERVED ALPHA DIGITS MARK -#define ESCAPED "%" -#define URIC RESERVED UNRESERVED ESCAPED "[]+" +#define DIGITS "0123456789" +#define HEX "aAbBcCdDeEfF" +#define HEX_DIGITS DIGITS HEX +#define VISUAL_SEP "-.()" +#define PHONE_DIGITS DIGITS VISUAL_SEP +#define GLOBAL_DIGITS "+" PHONE_DIGITS +#define LOCAL_DIGITS HEX_DIGITS "*#" VISUAL_SEP +#define NUMBER_SPEC LOCAL_DIGITS GLOBAL_DIGITS +#define PHONE_CONTEXT ALPHA GLOBAL_DIGITS +//#define RESERVED ";/?:@&=+$," +#define RESERVED "/:@&$,+" +#define MARK "-_.!~*'()" +#define UNRESERVED ALPHA DIGITS MARK +#define ESCAPED "%" +#define URIC RESERVED UNRESERVED ESCAPED "[]+" #define PARAM_UNRESERVED "[]/:&+$" -#define PARAM_CHAR PARAM_UNRESERVED UNRESERVED ESCAPED +#define PARAM_CHAR PARAM_UNRESERVED UNRESERVED ESCAPED static pj_cis_buf_t cis_buf; static pj_cis_t pjsip_TEL_NUMBER_SPEC; @@ -68,29 +67,29 @@ static pj_str_t pjsip_PH_CTX_STR = { "phone-context", 13 }; static const pj_str_t *tel_uri_get_scheme( const pjsip_tel_uri* ); static void *tel_uri_get_uri( pjsip_tel_uri* ); static pj_ssize_t tel_uri_print( pjsip_uri_context_e context, - const pjsip_tel_uri *url, - char *buf, pj_size_t size); + const pjsip_tel_uri *url, + char *buf, pj_size_t size); static int tel_uri_cmp( pjsip_uri_context_e context, - const pjsip_tel_uri *url1, const pjsip_tel_uri *url2); + const pjsip_tel_uri *url1, const pjsip_tel_uri *url2); static pjsip_tel_uri* tel_uri_clone(pj_pool_t *pool, const pjsip_tel_uri *rhs); -static void* tel_uri_parse( pj_scanner *scanner, pj_pool_t *pool, - pj_bool_t parse_params); +static void* tel_uri_parse( pj_scanner *scanner, pj_pool_t *pool, + pj_bool_t parse_params); typedef const pj_str_t* (*P_GET_SCHEME)(const void*); -typedef void* (*P_GET_URI)(void*); -typedef pj_ssize_t (*P_PRINT_URI)(pjsip_uri_context_e,const void *, - char*,pj_size_t); -typedef int (*P_CMP_URI)(pjsip_uri_context_e, const void*, - const void*); -typedef void* (*P_CLONE)(pj_pool_t*, const void*); +typedef void* (*P_GET_URI)(void*); +typedef pj_ssize_t (*P_PRINT_URI)(pjsip_uri_context_e,const void *, + char*,pj_size_t); +typedef int (*P_CMP_URI)(pjsip_uri_context_e, const void*, + const void*); +typedef void* (*P_CLONE)(pj_pool_t*, const void*); static pjsip_uri_vptr tel_uri_vptr = { - (P_GET_SCHEME) &tel_uri_get_scheme, - (P_GET_URI) &tel_uri_get_uri, - (P_PRINT_URI) &tel_uri_print, - (P_CMP_URI) &tel_uri_cmp, - (P_CLONE) &tel_uri_clone + (P_GET_SCHEME) &tel_uri_get_scheme, + (P_GET_URI) &tel_uri_get_uri, + (P_PRINT_URI) &tel_uri_print, + (P_CMP_URI) &tel_uri_cmp, + (P_CLONE) &tel_uri_clone }; @@ -166,7 +165,7 @@ pj_status_t pjsip_tel_uri_subsys_init(void) pj_cis_add_str(&pjsip_TEL_PARSING_PVALUE_SPEC, "="); status = pj_cis_dup(&pjsip_TEL_PARSING_PVALUE_SPEC_ESC, - &pjsip_TEL_PARSING_PVALUE_SPEC); + &pjsip_TEL_PARSING_PVALUE_SPEC); pj_cis_del_str(&pjsip_TEL_PARSING_PVALUE_SPEC_ESC, "%"); status = pjsip_register_uri_parser("tel", &tel_uri_parse); @@ -177,8 +176,8 @@ pj_status_t pjsip_tel_uri_subsys_init(void) /* Print tel: URI */ static pj_ssize_t tel_uri_print( pjsip_uri_context_e context, - const pjsip_tel_uri *uri, - char *buf, pj_size_t size) + const pjsip_tel_uri *uri, + char *buf, pj_size_t size) { int printed; char *startbuf = buf; @@ -198,23 +197,23 @@ static pj_ssize_t tel_uri_print( pjsip_uri_context_e context, /* Extension param. */ copy_advance_pair_escape(buf, ";ext=", 5, uri->ext_param, - pjsip_TEL_EXT_VALUE_SPEC); + pjsip_TEL_EXT_VALUE_SPEC); /* ISDN sub-address. */ copy_advance_pair_escape(buf, ";isub=", 6, uri->isub_param, - pjsip_TEL_URIC_SPEC); + pjsip_TEL_URIC_SPEC); /* Followed by phone context, if present. */ copy_advance_pair_escape(buf, ";phone-context=", 15, uri->context, - pjsip_TEL_PHONE_CONTEXT_SPEC); + pjsip_TEL_PHONE_CONTEXT_SPEC); /* Print other parameters. */ printed = (int)pjsip_param_print_on(&uri->other_param, buf, (endbuf-buf), - &pjsip_TEL_PNAME_SPEC, - &pjsip_TEL_PVALUE_SPEC, ';'); + &pjsip_TEL_PNAME_SPEC, + &pjsip_TEL_PVALUE_SPEC, ';'); if (printed < 0) - return -1; + return -1; buf += printed; *buf = '\0'; @@ -230,48 +229,48 @@ static pj_ssize_t tel_uri_print( pjsip_uri_context_e context, PJ_DEF(int) pjsip_tel_nb_cmp(const pj_str_t *number1, const pj_str_t *number2) { const char *s1 = number1->ptr, - *e1 = number1->ptr + number1->slen, - *s2 = number2->ptr, - *e2 = number2->ptr + number2->slen; + *e1 = number1->ptr + number1->slen, + *s2 = number2->ptr, + *e2 = number2->ptr + number2->slen; /* Compare each number, ignoreing visual separators. */ while (s1!=e1 && s2!=e2) { - int diff; - - if (pj_cis_match(&pjsip_TEL_VISUAL_SEP_SPEC, *s1)) { - ++s1; - continue; - } - if (pj_cis_match(&pjsip_TEL_VISUAL_SEP_SPEC, *s2)) { - ++s2; - continue; - } - - diff = pj_tolower(*s1) - pj_tolower(*s2); - if (!diff) { - ++s1, ++s2; - continue; - } else - return diff; + int diff; + + if (pj_cis_match(&pjsip_TEL_VISUAL_SEP_SPEC, *s1)) { + ++s1; + continue; + } + if (pj_cis_match(&pjsip_TEL_VISUAL_SEP_SPEC, *s2)) { + ++s2; + continue; + } + + diff = pj_tolower(*s1) - pj_tolower(*s2); + if (!diff) { + ++s1, ++s2; + continue; + } else + return diff; } /* Exhaust remaining visual separators. */ while (s1!=e1 && pj_cis_match(&pjsip_TEL_VISUAL_SEP_SPEC, *s1)) - ++s1; + ++s1; while (s2!=e2 && pj_cis_match(&pjsip_TEL_VISUAL_SEP_SPEC, *s2)) - ++s2; + ++s2; if (s1==e1 && s2==e2) - return 0; + return 0; else if (s1==e1) - return -1; + return -1; else - return 1; + return 1; } /* Compare two tel: URI */ static int tel_uri_cmp( pjsip_uri_context_e context, - const pjsip_tel_uri *url1, const pjsip_tel_uri *url2) + const pjsip_tel_uri *url1, const pjsip_tel_uri *url2) { int result; @@ -279,38 +278,38 @@ static int tel_uri_cmp( pjsip_uri_context_e context, /* Scheme must match. */ if (url1->vptr != url2->vptr) - return -1; + return -1; /* Compare number. */ result = pjsip_tel_nb_cmp(&url1->number, &url2->number); if (result != 0) - return result; + return result; /* Compare phone-context as hostname or as as global nb. */ if (url1->context.slen) { - if (*url1->context.ptr != '+') - result = pj_stricmp(&url1->context, &url2->context); - else - result = pjsip_tel_nb_cmp(&url1->context, &url2->context); + if (*url1->context.ptr != '+') + result = pj_stricmp(&url1->context, &url2->context); + else + result = pjsip_tel_nb_cmp(&url1->context, &url2->context); - if (result != 0) - return result; + if (result != 0) + return result; } else if (url2->context.slen) - return -1; + return -1; /* Compare extension. */ if (url1->ext_param.slen) { - result = pjsip_tel_nb_cmp(&url1->ext_param, &url2->ext_param); - if (result != 0) - return result; + result = pjsip_tel_nb_cmp(&url1->ext_param, &url2->ext_param); + if (result != 0) + return result; } /* Compare isub bytes by bytes. */ if (url1->isub_param.slen) { - result = pj_stricmp(&url1->isub_param, &url2->isub_param); - if (result != 0) - return result; + result = pj_stricmp(&url1->isub_param, &url2->isub_param); + if (result != 0) + return result; } /* Other parameters are compared regardless of the order. @@ -318,34 +317,34 @@ static int tel_uri_cmp( pjsip_uri_context_e context, * not equal. */ if (url1->other_param.next != &url1->other_param) { - const pjsip_param *p1, *p2; - int cnt1 = 0, cnt2 = 0; + const pjsip_param *p1, *p2; + int cnt1 = 0, cnt2 = 0; - p1 = url1->other_param.next; - while (p1 != &url1->other_param) { - p2 = pjsip_param_cfind(&url2->other_param, &p1->name); - if (!p2 ) - return 1; + p1 = url1->other_param.next; + while (p1 != &url1->other_param) { + p2 = pjsip_param_cfind(&url2->other_param, &p1->name); + if (!p2 ) + return 1; - result = pj_stricmp(&p1->value, &p2->value); - if (result != 0) - return result; + result = pj_stricmp(&p1->value, &p2->value); + if (result != 0) + return result; - p1 = p1->next; - ++cnt1; - } + p1 = p1->next; + ++cnt1; + } - p2 = url2->other_param.next; - while (p2 != &url2->other_param) - ++cnt2, p2 = p2->next; + p2 = url2->other_param.next; + while (p2 != &url2->other_param) + ++cnt2, p2 = p2->next; - if (cnt1 < cnt2) - return -1; - else if (cnt1 > cnt2) - return 1; + if (cnt1 < cnt2) + return -1; + else if (cnt1 > cnt2) + return 1; } else if (url2->other_param.next != &url2->other_param) - return -1; + return -1; /* Equal. */ return 0; @@ -369,7 +368,7 @@ static pjsip_tel_uri* tel_uri_clone(pj_pool_t *pool, const pjsip_tel_uri *rhs) * THis actually returns (pjsip_tel_uri *) type. */ static void* tel_uri_parse( pj_scanner *scanner, pj_pool_t *pool, - pj_bool_t parse_params) + pj_bool_t parse_params) { pjsip_tel_uri *uri; pj_str_t token; @@ -381,9 +380,9 @@ static void* tel_uri_parse( pj_scanner *scanner, pj_pool_t *pool, /* Parse scheme. */ pj_scan_get(scanner, &pc->pjsip_TOKEN_SPEC, &token); if (pj_scan_get_char(scanner) != ':') - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); if (pj_stricmp_alnum(&token, &pc->pjsip_TEL_STR) != 0) - PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); + PJ_THROW(PJSIP_SYN_ERR_EXCEPTION); /* Create URI */ uri = pjsip_tel_uri_create(pool); @@ -398,48 +397,48 @@ static void* tel_uri_parse( pj_scanner *scanner, pj_pool_t *pool, /* Get all parameters. */ if (parse_params && *scanner->curptr==';') { - pj_str_t pname, pvalue; - - do { - /* Eat the ';' separator. */ - pj_scan_get_char(scanner); - - /* Get pname. */ - pj_scan_get(scanner, &pc->pjsip_PARAM_CHAR_SPEC, &pname); - - if (*scanner->curptr == '=') { - pj_scan_get_char(scanner); - -# if defined(PJSIP_UNESCAPE_IN_PLACE) && PJSIP_UNESCAPE_IN_PLACE!=0 - pj_scan_get_unescape(scanner, - &pjsip_TEL_PARSING_PVALUE_SPEC_ESC, - &pvalue); -# else - pj_scan_get(scanner, &pjsip_TEL_PARSING_PVALUE_SPEC, - &pvalue); - pvalue = pj_str_unescape(pool, &pvalue); -# endif - - } else { - pvalue.slen = 0; - pvalue.ptr = NULL; - } - - /* Save the parameters. */ - if (pj_stricmp_alnum(&pname, &pjsip_ISUB_STR)==0) { - uri->isub_param = pvalue; - } else if (pj_stricmp_alnum(&pname, &pjsip_EXT_STR)==0) { - uri->ext_param = pvalue; - } else if (pj_stricmp_alnum(&pname, &pjsip_PH_CTX_STR)==0) { - uri->context = pvalue; - } else { - pjsip_param *param = PJ_POOL_ALLOC_T(pool, pjsip_param); - param->name = pname; - param->value = pvalue; - pj_list_insert_before(&uri->other_param, param); - } - - } while (*scanner->curptr==';'); + pj_str_t pname, pvalue; + + do { + /* Eat the ';' separator. */ + pj_scan_get_char(scanner); + + /* Get pname. */ + pj_scan_get(scanner, &pc->pjsip_PARAM_CHAR_SPEC, &pname); + + if (*scanner->curptr == '=') { + pj_scan_get_char(scanner); + +# if defined(PJSIP_UNESCAPE_IN_PLACE) && PJSIP_UNESCAPE_IN_PLACE!=0 + pj_scan_get_unescape(scanner, + &pjsip_TEL_PARSING_PVALUE_SPEC_ESC, + &pvalue); +# else + pj_scan_get(scanner, &pjsip_TEL_PARSING_PVALUE_SPEC, + &pvalue); + pvalue = pj_str_unescape(pool, &pvalue); +# endif + + } else { + pvalue.slen = 0; + pvalue.ptr = NULL; + } + + /* Save the parameters. */ + if (pj_stricmp_alnum(&pname, &pjsip_ISUB_STR)==0) { + uri->isub_param = pvalue; + } else if (pj_stricmp_alnum(&pname, &pjsip_EXT_STR)==0) { + uri->ext_param = pvalue; + } else if (pj_stricmp_alnum(&pname, &pjsip_PH_CTX_STR)==0) { + uri->context = pvalue; + } else { + pjsip_param *param = PJ_POOL_ALLOC_T(pool, pjsip_param); + param->name = pname; + param->value = pvalue; + pj_list_insert_before(&uri->other_param, param); + } + + } while (*scanner->curptr==';'); } scanner->skip_ws = skip_ws; diff --git a/pjsip/src/pjsip/sip_tel_uri_wrap.cpp b/pjsip/src/pjsip/sip_tel_uri_wrap.cpp index fc00ccfbf7..53755c9adb 100644 --- a/pjsip/src/pjsip/sip_tel_uri_wrap.cpp +++ b/pjsip/src/pjsip/sip_tel_uri_wrap.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjsip/src/pjsip/sip_transaction.c b/pjsip/src/pjsip/sip_transaction.c index 9fd8343966..cf9795dbbf 100644 --- a/pjsip/src/pjsip/sip_transaction.c +++ b/pjsip/src/pjsip/sip_transaction.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -71,23 +70,23 @@ static pj_bool_t mod_tsx_layer_on_rx_response(pjsip_rx_data *rdata); static struct mod_tsx_layer { struct pjsip_module mod; - pj_pool_t *pool; - pjsip_endpoint *endpt; - pj_mutex_t *mutex; - pj_hash_table_t *htable; + pj_pool_t *pool; + pjsip_endpoint *endpt; + pj_mutex_t *mutex; + pj_hash_table_t *htable; } mod_tsx_layer = { { - NULL, NULL, /* List's prev and next. */ - { "mod-tsx-layer", 13 }, /* Module name. */ - -1, /* Module ID */ - PJSIP_MOD_PRIORITY_TSX_LAYER, /* Priority. */ - mod_tsx_layer_load, /* load(). */ - mod_tsx_layer_start, /* start() */ - mod_tsx_layer_stop, /* stop() */ - mod_tsx_layer_unload, /* unload() */ - mod_tsx_layer_on_rx_request, /* on_rx_request() */ - mod_tsx_layer_on_rx_response, /* on_rx_response() */ - NULL + NULL, NULL, /* List's prev and next. */ + { "mod-tsx-layer", 13 }, /* Module name. */ + -1, /* Module ID */ + PJSIP_MOD_PRIORITY_TSX_LAYER, /* Priority. */ + mod_tsx_layer_load, /* load(). */ + mod_tsx_layer_start, /* start() */ + mod_tsx_layer_stop, /* stop() */ + mod_tsx_layer_unload, /* unload() */ + mod_tsx_layer_on_rx_request, /* on_rx_request() */ + mod_tsx_layer_on_rx_response, /* on_rx_response() */ + NULL } }; @@ -114,11 +113,11 @@ static const char *role_name[] = /* Transport flag. */ enum { - TSX_HAS_PENDING_TRANSPORT = 1, - TSX_HAS_PENDING_RESCHED = 2, - TSX_HAS_PENDING_SEND = 4, - TSX_HAS_PENDING_DESTROY = 8, - TSX_HAS_RESOLVED_SERVER = 16, + TSX_HAS_PENDING_TRANSPORT = 1, + TSX_HAS_PENDING_RESCHED = 2, + TSX_HAS_PENDING_SEND = 4, + TSX_HAS_PENDING_DESTROY = 8, + TSX_HAS_RESOLVED_SERVER = 16, }; /* Timer timeout value constants */ @@ -131,13 +130,13 @@ static pj_time_val t4_timer_val = { PJSIP_T4_TIMEOUT/1000, static pj_time_val td_timer_val = { PJSIP_TD_TIMEOUT/1000, PJSIP_TD_TIMEOUT%1000 }; static pj_time_val timeout_timer_val = { (64*PJSIP_T1_TIMEOUT)/1000, - (64*PJSIP_T1_TIMEOUT)%1000 }; + (64*PJSIP_T1_TIMEOUT)%1000 }; -#define TIMER_INACTIVE 0 -#define RETRANSMIT_TIMER 1 -#define TIMEOUT_TIMER 2 -#define TRANSPORT_ERR_TIMER 3 -#define TRANSPORT_DISC_TIMER 4 +#define TIMER_INACTIVE 0 +#define RETRANSMIT_TIMER 1 +#define TIMEOUT_TIMER 2 +#define TRANSPORT_ERR_TIMER 3 +#define TRANSPORT_DISC_TIMER 4 /* Flags for tsx_set_state() */ enum @@ -147,55 +146,55 @@ enum }; /* Prototypes. */ -static pj_status_t tsx_on_state_null( pjsip_transaction *tsx, - pjsip_event *event); -static pj_status_t tsx_on_state_calling( pjsip_transaction *tsx, - pjsip_event *event); -static pj_status_t tsx_on_state_trying( pjsip_transaction *tsx, - pjsip_event *event); +static pj_status_t tsx_on_state_null( pjsip_transaction *tsx, + pjsip_event *event); +static pj_status_t tsx_on_state_calling( pjsip_transaction *tsx, + pjsip_event *event); +static pj_status_t tsx_on_state_trying( pjsip_transaction *tsx, + pjsip_event *event); static pj_status_t tsx_on_state_proceeding_uas( pjsip_transaction *tsx, - pjsip_event *event); + pjsip_event *event); static pj_status_t tsx_on_state_proceeding_uac( pjsip_transaction *tsx, - pjsip_event *event); -static pj_status_t tsx_on_state_completed_uas( pjsip_transaction *tsx, - pjsip_event *event); -static pj_status_t tsx_on_state_completed_uac( pjsip_transaction *tsx, - pjsip_event *event); -static pj_status_t tsx_on_state_confirmed( pjsip_transaction *tsx, - pjsip_event *event); -static pj_status_t tsx_on_state_terminated( pjsip_transaction *tsx, - pjsip_event *event); -static pj_status_t tsx_on_state_destroyed( pjsip_transaction *tsx, - pjsip_event *event); + pjsip_event *event); +static pj_status_t tsx_on_state_completed_uas( pjsip_transaction *tsx, + pjsip_event *event); +static pj_status_t tsx_on_state_completed_uac( pjsip_transaction *tsx, + pjsip_event *event); +static pj_status_t tsx_on_state_confirmed( pjsip_transaction *tsx, + pjsip_event *event); +static pj_status_t tsx_on_state_terminated( pjsip_transaction *tsx, + pjsip_event *event); +static pj_status_t tsx_on_state_destroyed( pjsip_transaction *tsx, + pjsip_event *event); static void tsx_timer_callback( pj_timer_heap_t *theap, - pj_timer_entry *entry); -static void tsx_tp_state_callback( - pjsip_transport *tp, - pjsip_transport_state state, - const pjsip_transport_state_info *info); -static void tsx_set_state( pjsip_transaction *tsx, - pjsip_tsx_state_e state, - pjsip_event_id_e event_src_type, - void *event_src, - int flag); -static void tsx_set_status_code(pjsip_transaction *tsx, - int code, const pj_str_t *reason); + pj_timer_entry *entry); +static void tsx_tp_state_callback( + pjsip_transport *tp, + pjsip_transport_state state, + const pjsip_transport_state_info *info); +static void tsx_set_state( pjsip_transaction *tsx, + pjsip_tsx_state_e state, + pjsip_event_id_e event_src_type, + void *event_src, + int flag); +static void tsx_set_status_code(pjsip_transaction *tsx, + int code, const pj_str_t *reason); static pj_status_t tsx_create( pjsip_module *tsx_user, pj_grp_lock_t *grp_lock, - pjsip_transaction **p_tsx); -static void tsx_on_destroy(void *arg); + pjsip_transaction **p_tsx); +static void tsx_on_destroy(void *arg); static pj_status_t tsx_shutdown( pjsip_transaction *tsx ); -static void tsx_resched_retransmission( pjsip_transaction *tsx ); +static void tsx_resched_retransmission( pjsip_transaction *tsx ); static pj_status_t tsx_retransmit( pjsip_transaction *tsx, int resched); static int tsx_send_msg( pjsip_transaction *tsx, pjsip_tx_data *tdata); static void tsx_update_transport( pjsip_transaction *tsx, - pjsip_transport *tp); + pjsip_transport *tp); /* State handlers for UAC, indexed by state */ static int (*tsx_state_handler_uac[PJSIP_TSX_STATE_MAX])(pjsip_transaction *, - pjsip_event *) = + pjsip_event *) = { &tsx_on_state_null, &tsx_on_state_calling, @@ -209,7 +208,7 @@ static int (*tsx_state_handler_uac[PJSIP_TSX_STATE_MAX])(pjsip_transaction *, /* State handlers for UAS */ static int (*tsx_state_handler_uas[PJSIP_TSX_STATE_MAX])(pjsip_transaction *, - pjsip_event *) = + pjsip_event *) = { &tsx_on_state_null, NULL, @@ -250,29 +249,29 @@ PJ_DEF(const char *) pjsip_role_name(pjsip_role_e role) * * INVITE requests matches a transaction if the following attributes * match the original request: - * - Request-URI - * - To tag - * - From tag - * - Call-ID - * - CSeq - * - top Via header + * - Request-URI + * - To tag + * - From tag + * - Call-ID + * - CSeq + * - top Via header * * CANCEL matching is done similarly as INVITE, except: - * - CSeq method will differ - * - To tag is not matched. + * - CSeq method will differ + * - To tag is not matched. * * ACK matching is done similarly, except that: - * - method of the CSeq will differ, - * - To tag is matched to the response sent by the server transaction. + * - method of the CSeq will differ, + * - To tag is matched to the response sent by the server transaction. * * The transaction key is constructed from the common components of above * components. Additional comparison is needed to fully match a transaction. */ static pj_status_t create_tsx_key_2543( pj_pool_t *pool, - pj_str_t *str, - pjsip_role_e role, - const pjsip_method *method, - const pjsip_rx_data *rdata ) + pj_str_t *str, + pjsip_role_e role, + const pjsip_method *method, + const pjsip_rx_data *rdata ) { #define SEPARATOR '$' char *key, *p; @@ -290,12 +289,12 @@ static pj_status_t create_tsx_key_2543( pj_pool_t *pool, /* Calculate length required. */ len_required = method->name.slen + /* Method */ - 11 + /* CSeq number */ - rdata->msg_info.from->tag.slen + /* From tag. */ - rdata->msg_info.cid->id.slen + /* Call-ID */ - host->slen + /* Via host. */ - 11 + /* Via port. */ - 16; /* Separator+Allowance. */ + 11 + /* CSeq number */ + rdata->msg_info.from->tag.slen + /* From tag. */ + rdata->msg_info.cid->id.slen + /* Call-ID */ + host->slen + /* Via host. */ + 11 + /* Via port. */ + 16; /* Separator+Allowance. */ key = p = (char*) pj_pool_alloc(pool, len_required); /* Add role. */ @@ -304,9 +303,9 @@ static pj_status_t create_tsx_key_2543( pj_pool_t *pool, /* Add method, except when method is INVITE or ACK. */ if (method->id != PJSIP_INVITE_METHOD && method->id != PJSIP_ACK_METHOD) { - pj_memcpy(p, method->name.ptr, method->name.slen); - p += method->name.slen; - *p++ = '$'; + pj_memcpy(p, method->name.ptr, method->name.slen); + p += method->name.slen; + *p++ = '$'; } /* Add CSeq (only the number). */ @@ -353,17 +352,17 @@ static pj_status_t create_tsx_key_2543( pj_pool_t *pool, * Create transaction key for RFC3161 compliant system. */ static pj_status_t create_tsx_key_3261( pj_pool_t *pool, - pj_str_t *key, - pjsip_role_e role, - const pjsip_method *method, - const pj_str_t *branch) + pj_str_t *key, + pjsip_role_e role, + const pjsip_method *method, + const pj_str_t *branch) { char *p; PJ_ASSERT_RETURN(pool && key && method && branch, PJ_EINVAL); p = key->ptr = (char*) - pj_pool_alloc(pool, branch->slen + method->name.slen + 4 ); + pj_pool_alloc(pool, branch->slen + method->name.slen + 4 ); /* Add role. */ *p++ = (char)(role==PJSIP_ROLE_UAC ? 'c' : 's'); @@ -371,9 +370,9 @@ static pj_status_t create_tsx_key_3261( pj_pool_t *pool, /* Add method, except when method is INVITE or ACK. */ if (method->id != PJSIP_INVITE_METHOD && method->id != PJSIP_ACK_METHOD) { - pj_memcpy(p, method->name.ptr, method->name.slen); - p += method->name.slen; - *p++ = '$'; + pj_memcpy(p, method->name.ptr, method->name.slen); + p += method->name.slen; + *p++ = '$'; } /* Add branch ID. */ @@ -391,9 +390,9 @@ static pj_status_t create_tsx_key_3261( pj_pool_t *pool, * in the transaction hash table. */ PJ_DEF(pj_status_t) pjsip_tsx_create_key( pj_pool_t *pool, pj_str_t *key, - pjsip_role_e role, - const pjsip_method *method, - const pjsip_rx_data *rdata) + pjsip_role_e role, + const pjsip_method *method, + const pjsip_rx_data *rdata) { pj_str_t rfc3261_branch = {PJSIP_RFC3261_BRANCH_ID, PJSIP_RFC3261_BRANCH_LEN}; @@ -408,16 +407,16 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_key( pj_pool_t *pool, pj_str_t *key, if (pj_strnicmp(branch,&rfc3261_branch,PJSIP_RFC3261_BRANCH_LEN)==0) { - /* Create transaction key. */ - return create_tsx_key_3261(pool, key, role, method, branch); + /* Create transaction key. */ + return create_tsx_key_3261(pool, key, role, method, branch); } else { - /* Create the key for the message. This key will be matched up + /* Create the key for the message. This key will be matched up * with the transaction key. For RFC2563 transactions, the * transaction key was created by the same function, so it will * match the message. - */ - return create_tsx_key_2543( pool, key, role, method, rdata ); + */ + return create_tsx_key_2543( pool, key, role, method, rdata ); } } @@ -435,25 +434,25 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_key( pj_pool_t *pool, pj_str_t *key, PJ_DEF(void) pjsip_tsx_set_timers(unsigned t1, unsigned t2, unsigned t4, unsigned td) { if(t1!=0) { - t1_timer_val.sec = t1 / 1000; - t1_timer_val.msec = t1 % 1000; - pjsip_cfg()->tsx.t1=t1; + t1_timer_val.sec = t1 / 1000; + t1_timer_val.msec = t1 % 1000; + pjsip_cfg()->tsx.t1=t1; } if(t2!=0) { - t2_timer_val.sec = t2 / 1000; - t2_timer_val.msec = t2 % 1000; - pjsip_cfg()->tsx.t2=t2; + t2_timer_val.sec = t2 / 1000; + t2_timer_val.msec = t2 % 1000; + pjsip_cfg()->tsx.t2=t2; } if(t4!=0) { - t4_timer_val.sec = t4 / 1000; - t4_timer_val.msec = t4 % 1000; - pjsip_cfg()->tsx.t4=t4; + t4_timer_val.sec = t4 / 1000; + t4_timer_val.msec = t4 % 1000; + pjsip_cfg()->tsx.t4=t4; } if(td!=0) { - td_timer_val.sec = td / 1000; - td_timer_val.msec = td % 1000; - timeout_timer_val = td_timer_val; - pjsip_cfg()->tsx.td=td; + td_timer_val.sec = td / 1000; + td_timer_val.msec = td % 1000; + timeout_timer_val = td_timer_val; + pjsip_cfg()->tsx.td=td; } } @@ -499,10 +498,10 @@ PJ_DEF(pj_status_t) pjsip_tsx_layer_init_module(pjsip_endpoint *endpt) /* Create pool for the module. */ pool = pjsip_endpt_create_pool(endpt, "tsxlayer", - PJSIP_POOL_TSX_LAYER_LEN, - PJSIP_POOL_TSX_LAYER_INC ); + PJSIP_POOL_TSX_LAYER_LEN, + PJSIP_POOL_TSX_LAYER_INC ); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Initialize some attributes. */ @@ -513,15 +512,15 @@ PJ_DEF(pj_status_t) pjsip_tsx_layer_init_module(pjsip_endpoint *endpt) /* Create hash table. */ mod_tsx_layer.htable = pj_hash_create( pool, pjsip_cfg()->tsx.max_count ); if (!mod_tsx_layer.htable) { - pjsip_endpt_release_pool(endpt, pool); - return PJ_ENOMEM; + pjsip_endpt_release_pool(endpt, pool); + return PJ_ENOMEM; } /* Create group lock. */ status = pj_mutex_create_recursive(pool, "tsxlayer", &mod_tsx_layer.mutex); if (status != PJ_SUCCESS) { - pjsip_endpt_release_pool(endpt, pool); - return status; + pjsip_endpt_release_pool(endpt, pool); + return status; } /* @@ -529,15 +528,15 @@ PJ_DEF(pj_status_t) pjsip_tsx_layer_init_module(pjsip_endpoint *endpt) */ status = pjsip_endpt_register_module( endpt, &mod_tsx_layer.mod ); if (status != PJ_SUCCESS) { - pj_mutex_destroy(mod_tsx_layer.mutex); - pjsip_endpt_release_pool(endpt, pool); - return status; + pj_mutex_destroy(mod_tsx_layer.mutex); + pjsip_endpt_release_pool(endpt, pool); + return status; } /* Register mod_stateful_util module (sip_util_statefull.c) */ status = pjsip_endpt_register_module(endpt, &mod_stateful_util); if (status != PJ_SUCCESS) { - return status; + return status; } return PJ_SUCCESS; @@ -565,7 +564,7 @@ PJ_DEF(pj_status_t) pjsip_tsx_layer_destroy(void) * Clean-ups will be done in the unload() module callback. */ return pjsip_endpt_unregister_module( mod_tsx_layer.endpt, - &mod_tsx_layer.mod); + &mod_tsx_layer.mod); } @@ -584,33 +583,33 @@ static pj_status_t mod_tsx_layer_register_tsx( pjsip_transaction *tsx) * twice! */ if(pj_hash_get_lower(mod_tsx_layer.htable, - tsx->transaction_key.ptr, - (unsigned)tsx->transaction_key.slen, - NULL)) + tsx->transaction_key.ptr, + (unsigned)tsx->transaction_key.slen, + NULL)) { - pj_mutex_unlock(mod_tsx_layer.mutex); - PJ_LOG(2,(THIS_FILE, - "Unable to register %.*s transaction (key exists)", - (int)tsx->method.name.slen, - tsx->method.name.ptr)); - return PJ_EEXISTS; + pj_mutex_unlock(mod_tsx_layer.mutex); + PJ_LOG(2,(THIS_FILE, + "Unable to register %.*s transaction (key exists)", + (int)tsx->method.name.slen, + tsx->method.name.ptr)); + return PJ_EEXISTS; } TSX_TRACE_((THIS_FILE, - "Transaction %p registered with hkey=0x%p and key=%.*s", - tsx, tsx->hashed_key, tsx->transaction_key.slen, - tsx->transaction_key.ptr)); + "Transaction %p registered with hkey=0x%p and key=%.*s", + tsx, tsx->hashed_key, tsx->transaction_key.slen, + tsx->transaction_key.ptr)); /* Register the transaction to the hash table. */ #ifdef PRECALC_HASH pj_hash_set_lower( tsx->pool, mod_tsx_layer.htable, tsx->transaction_key.ptr, - (unsigned)tsx->transaction_key.slen, - tsx->hashed_key, tsx); + (unsigned)tsx->transaction_key.slen, + tsx->hashed_key, tsx); #else pj_hash_set_lower( tsx->pool, mod_tsx_layer.htable, tsx->transaction_key.ptr, - tsx->transaction_key.slen, 0, tsx); + tsx->transaction_key.slen, 0, tsx); #endif /* Unlock mutex. */ @@ -626,12 +625,12 @@ static pj_status_t mod_tsx_layer_register_tsx( pjsip_transaction *tsx) static void mod_tsx_layer_unregister_tsx( pjsip_transaction *tsx) { if (mod_tsx_layer.mod.id == -1) { - /* The transaction layer has been unregistered. This could happen - * if the transaction was pending on transport and the application - * is shutdown. See https://github.com/pjsip/pjproject/issues/1033. In - * this case just do nothing. - */ - return; + /* The transaction layer has been unregistered. This could happen + * if the transaction was pending on transport and the application + * is shutdown. See https://github.com/pjsip/pjproject/issues/1033. In + * this case just do nothing. + */ + return; } pj_assert(tsx->transaction_key.slen != 0); @@ -643,17 +642,17 @@ static void mod_tsx_layer_unregister_tsx( pjsip_transaction *tsx) /* Register the transaction to the hash table. */ #ifdef PRECALC_HASH pj_hash_set_lower( NULL, mod_tsx_layer.htable, tsx->transaction_key.ptr, - (unsigned)tsx->transaction_key.slen, tsx->hashed_key, - NULL); + (unsigned)tsx->transaction_key.slen, tsx->hashed_key, + NULL); #else pj_hash_set_lower( NULL, mod_tsx_layer.htable, tsx->transaction_key.ptr, - tsx->transaction_key.slen, 0, NULL); + tsx->transaction_key.slen, 0, NULL); #endif TSX_TRACE_((THIS_FILE, - "Transaction %p unregistered, hkey=0x%p and key=%.*s", - tsx, tsx->hashed_key, tsx->transaction_key.slen, - tsx->transaction_key.ptr)); + "Transaction %p unregistered, hkey=0x%p and key=%.*s", + tsx, tsx->hashed_key, tsx->transaction_key.slen, + tsx->transaction_key.ptr)); /* Unlock mutex. */ pj_mutex_unlock(mod_tsx_layer.mutex); @@ -683,15 +682,15 @@ PJ_DEF(unsigned) pjsip_tsx_layer_get_tsx_count(void) * Find a transaction. */ static pjsip_transaction* find_tsx( const pj_str_t *key, pj_bool_t lock, - pj_bool_t add_ref ) + pj_bool_t add_ref ) { pjsip_transaction *tsx; pj_uint32_t hval = 0; pj_mutex_lock(mod_tsx_layer.mutex); tsx = (pjsip_transaction*) - pj_hash_get_lower( mod_tsx_layer.htable, key->ptr, - (unsigned)key->slen, &hval ); + pj_hash_get_lower( mod_tsx_layer.htable, key->ptr, + (unsigned)key->slen, &hval ); /* Prevent the transaction to get deleted before we have chance to lock it. */ @@ -701,15 +700,15 @@ static pjsip_transaction* find_tsx( const pj_str_t *key, pj_bool_t lock, pj_mutex_unlock(mod_tsx_layer.mutex); TSX_TRACE_((THIS_FILE, - "Finding tsx with hkey=0x%p and key=%.*s: found %p", - hval, key->slen, key->ptr, tsx)); + "Finding tsx with hkey=0x%p and key=%.*s: found %p", + hval, key->slen, key->ptr, tsx)); /* Simulate race condition! */ PJ_RACE_ME(5); if (tsx) { - if (lock) - pj_grp_lock_acquire(tsx->grp_lock); + if (lock) + pj_grp_lock_acquire(tsx->grp_lock); if (!add_ref) pj_grp_lock_dec_ref(tsx->grp_lock); @@ -720,14 +719,14 @@ static pjsip_transaction* find_tsx( const pj_str_t *key, pj_bool_t lock, PJ_DEF(pjsip_transaction*) pjsip_tsx_layer_find_tsx( const pj_str_t *key, - pj_bool_t lock ) + pj_bool_t lock ) { return find_tsx(key, lock, PJ_FALSE); } PJ_DEF(pjsip_transaction*) pjsip_tsx_layer_find_tsx2( const pj_str_t *key, - pj_bool_t add_ref ) + pj_bool_t add_ref ) { return find_tsx(key, PJ_FALSE, add_ref); } @@ -766,15 +765,15 @@ static pj_status_t mod_tsx_layer_stop(void) /* Destroy all transactions. */ it = pj_hash_first(mod_tsx_layer.htable, &it_buf); while (it) { - pjsip_transaction *tsx = (pjsip_transaction*) - pj_hash_this(mod_tsx_layer.htable, it); - pj_hash_iterator_t *next = pj_hash_next(mod_tsx_layer.htable, it); - if (tsx) { - pjsip_tsx_terminate(tsx, PJSIP_SC_SERVICE_UNAVAILABLE); - mod_tsx_layer_unregister_tsx(tsx); - tsx_shutdown(tsx); - } - it = next; + pjsip_transaction *tsx = (pjsip_transaction*) + pj_hash_this(mod_tsx_layer.htable, it); + pj_hash_iterator_t *next = pj_hash_next(mod_tsx_layer.htable, it); + if (tsx) { + pjsip_tsx_terminate(tsx, PJSIP_SC_SERVICE_UNAVAILABLE); + mod_tsx_layer_unregister_tsx(tsx); + tsx_shutdown(tsx); + } + it = next; } pj_mutex_unlock(mod_tsx_layer.mutex); @@ -815,13 +814,13 @@ static pj_status_t mod_tsx_layer_unload(void) * from transport and when it tries to unregister itself. */ if (pj_hash_count(mod_tsx_layer.htable) != 0) { - pj_status_t status; - status = pjsip_endpt_atexit(mod_tsx_layer.endpt, &tsx_layer_destroy); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, - "Failed to register transaction layer module destroy.")); - } - return PJ_EBUSY; + pj_status_t status; + status = pjsip_endpt_atexit(mod_tsx_layer.endpt, &tsx_layer_destroy); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(THIS_FILE, status, + "Failed to register transaction layer module destroy.")); + } + return PJ_EBUSY; } tsx_layer_destroy(mod_tsx_layer.endpt); @@ -840,28 +839,28 @@ static pj_bool_t mod_tsx_layer_on_rx_request(pjsip_rx_data *rdata) pjsip_transaction *tsx; pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, - &rdata->msg_info.cseq->method, rdata); + &rdata->msg_info.cseq->method, rdata); /* Find transaction. */ pj_mutex_lock( mod_tsx_layer.mutex ); tsx = (pjsip_transaction*) - pj_hash_get_lower( mod_tsx_layer.htable, key.ptr, (unsigned)key.slen, - &hval ); + pj_hash_get_lower( mod_tsx_layer.htable, key.ptr, (unsigned)key.slen, + &hval ); TSX_TRACE_((THIS_FILE, - "Finding tsx for request, hkey=0x%p and key=%.*s, found %p", - hval, key.slen, key.ptr, tsx)); + "Finding tsx for request, hkey=0x%p and key=%.*s, found %p", + hval, key.slen, key.ptr, tsx)); if (tsx == NULL || tsx->state == PJSIP_TSX_STATE_TERMINATED) { - /* Transaction not found. - * Reject the request so that endpoint passes the request to - * upper layer modules. - */ - pj_mutex_unlock( mod_tsx_layer.mutex); - return PJ_FALSE; + /* Transaction not found. + * Reject the request so that endpoint passes the request to + * upper layer modules. + */ + pj_mutex_unlock( mod_tsx_layer.mutex); + return PJ_FALSE; } /* Prevent the transaction to get deleted before we have chance to lock it @@ -894,28 +893,28 @@ static pj_bool_t mod_tsx_layer_on_rx_response(pjsip_rx_data *rdata) pjsip_transaction *tsx; pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAC, - &rdata->msg_info.cseq->method, rdata); + &rdata->msg_info.cseq->method, rdata); /* Find transaction. */ pj_mutex_lock( mod_tsx_layer.mutex ); tsx = (pjsip_transaction*) - pj_hash_get_lower( mod_tsx_layer.htable, key.ptr, (unsigned)key.slen, - &hval ); + pj_hash_get_lower( mod_tsx_layer.htable, key.ptr, (unsigned)key.slen, + &hval ); TSX_TRACE_((THIS_FILE, - "Finding tsx for response, hkey=0x%p and key=%.*s, found %p", - hval, key.slen, key.ptr, tsx)); + "Finding tsx for response, hkey=0x%p and key=%.*s, found %p", + hval, key.slen, key.ptr, tsx)); if (tsx == NULL || tsx->state == PJSIP_TSX_STATE_TERMINATED) { - /* Transaction not found. - * Reject the request so that endpoint passes the request to - * upper layer modules. - */ - pj_mutex_unlock( mod_tsx_layer.mutex); - return PJ_FALSE; + /* Transaction not found. + * Reject the request so that endpoint passes the request to + * upper layer modules. + */ + pj_mutex_unlock( mod_tsx_layer.mutex); + return PJ_FALSE; } /* Prevent the transaction to get deleted before we have chance to lock it @@ -944,7 +943,7 @@ static pj_bool_t mod_tsx_layer_on_rx_response(pjsip_rx_data *rdata) PJ_DEF(pjsip_transaction*) pjsip_rdata_get_tsx( pjsip_rx_data *rdata ) { return (pjsip_transaction*) - rdata->endpt_info.mod_data[mod_tsx_layer.mod.id]; + rdata->endpt_info.mod_data[mod_tsx_layer.mod.id]; } @@ -961,28 +960,28 @@ PJ_DEF(void) pjsip_tsx_layer_dump(pj_bool_t detail) PJ_LOG(3, (THIS_FILE, "Dumping transaction table:")); PJ_LOG(3, (THIS_FILE, " Total %d transactions", - pj_hash_count(mod_tsx_layer.htable))); + pj_hash_count(mod_tsx_layer.htable))); if (detail) { - it = pj_hash_first(mod_tsx_layer.htable, &itbuf); - if (it == NULL) { - PJ_LOG(3, (THIS_FILE, " - none - ")); - } else { - while (it != NULL) { - pjsip_transaction *tsx = (pjsip_transaction*) - pj_hash_this(mod_tsx_layer.htable,it); - - PJ_LOG(3, (THIS_FILE, " %s %s|%d|%s", - tsx->obj_name, - (tsx->last_tx? - pjsip_tx_data_get_info(tsx->last_tx): - "none"), - tsx->status_code, - pjsip_tsx_state_str(tsx->state))); - - it = pj_hash_next(mod_tsx_layer.htable, it); - } - } + it = pj_hash_first(mod_tsx_layer.htable, &itbuf); + if (it == NULL) { + PJ_LOG(3, (THIS_FILE, " - none - ")); + } else { + while (it != NULL) { + pjsip_transaction *tsx = (pjsip_transaction*) + pj_hash_this(mod_tsx_layer.htable,it); + + PJ_LOG(3, (THIS_FILE, " %s %s|%d|%s", + tsx->obj_name, + (tsx->last_tx? + pjsip_tx_data_get_info(tsx->last_tx): + "none"), + tsx->status_code, + pjsip_tsx_state_str(tsx->state))); + + it = pj_hash_next(mod_tsx_layer.htable, it); + } + } } /* Unlock mutex. */ @@ -1038,16 +1037,16 @@ static int tsx_cancel_timer(pjsip_transaction *tsx, */ static pj_status_t tsx_create( pjsip_module *tsx_user, pj_grp_lock_t *grp_lock, - pjsip_transaction **p_tsx) + pjsip_transaction **p_tsx) { pj_pool_t *pool; pjsip_transaction *tsx; pj_status_t status; pool = pjsip_endpt_create_pool( mod_tsx_layer.endpt, "tsx", - PJSIP_POOL_TSX_LEN, PJSIP_POOL_TSX_INC ); + PJSIP_POOL_TSX_LEN, PJSIP_POOL_TSX_INC ); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; tsx = PJ_POOL_ZALLOC_T(pool, pjsip_transaction); tsx->pool = pool; @@ -1055,7 +1054,7 @@ static pj_status_t tsx_create( pjsip_module *tsx_user, tsx->endpt = mod_tsx_layer.endpt; pj_ansi_snprintf(tsx->obj_name, sizeof(tsx->obj_name), - "tsx%p", tsx); + "tsx%p", tsx); pj_memcpy(pool->obj_name, tsx->obj_name, sizeof(pool->obj_name)); tsx->handle_200resp = 1; @@ -1067,25 +1066,25 @@ static pj_status_t tsx_create( pjsip_module *tsx_user, tsx->timeout_timer.cb = &tsx_timer_callback; if (grp_lock) { - tsx->grp_lock = grp_lock; + tsx->grp_lock = grp_lock; pj_grp_lock_add_ref(tsx->grp_lock); pj_grp_lock_add_handler(tsx->grp_lock, tsx->pool, tsx, &tsx_on_destroy); } else { - status = pj_grp_lock_create_w_handler(pool, NULL, tsx, &tsx_on_destroy, - &tsx->grp_lock); - if (status != PJ_SUCCESS) { - pjsip_endpt_release_pool(mod_tsx_layer.endpt, pool); - return status; - } - - pj_grp_lock_add_ref(tsx->grp_lock); + status = pj_grp_lock_create_w_handler(pool, NULL, tsx, &tsx_on_destroy, + &tsx->grp_lock); + if (status != PJ_SUCCESS) { + pjsip_endpt_release_pool(mod_tsx_layer.endpt, pool); + return status; + } + + pj_grp_lock_add_ref(tsx->grp_lock); } status = pj_mutex_create_simple(pool, tsx->obj_name, &tsx->mutex_b); if (status != PJ_SUCCESS) { - tsx_shutdown(tsx); - return status; + tsx_shutdown(tsx); + return status; } *p_tsx = tsx; @@ -1112,13 +1111,13 @@ static pj_status_t tsx_shutdown( pjsip_transaction *tsx ) /* Decrement reference counter in transport selector, only if * we haven't been called before */ if (!tsx->terminating) { - pjsip_tpselector_dec_ref(&tsx->tp_sel); + pjsip_tpselector_dec_ref(&tsx->tp_sel); } /* Free last transmitted message. */ if (tsx->last_tx) { - pjsip_tx_data_dec_ref( tsx->last_tx ); - tsx->last_tx = NULL; + pjsip_tx_data_dec_ref( tsx->last_tx ); + tsx->last_tx = NULL; } /* Cancel timeout timer. */ tsx_cancel_timer(tsx, &tsx->timeout_timer); @@ -1132,15 +1131,15 @@ static pj_status_t tsx_shutdown( pjsip_transaction *tsx ) /* Refuse to destroy transaction if it has pending resolving. */ if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { - tsx->transport_flag |= TSX_HAS_PENDING_DESTROY; - tsx->tsx_user = NULL; - PJ_LOG(4,(tsx->obj_name, "Will destroy later because transport is " - "in progress")); + tsx->transport_flag |= TSX_HAS_PENDING_DESTROY; + tsx->tsx_user = NULL; + PJ_LOG(4,(tsx->obj_name, "Will destroy later because transport is " + "in progress")); } if (!tsx->terminating) { - tsx->terminating = PJ_TRUE; - pj_grp_lock_dec_ref(tsx->grp_lock); + tsx->terminating = PJ_TRUE; + pj_grp_lock_dec_ref(tsx->grp_lock); } /* No acccess to tsx after this, it may have been destroyed */ @@ -1166,103 +1165,103 @@ static void tsx_timer_callback( pj_timer_heap_t *theap, pj_timer_entry *entry) if (entry->id == TRANSPORT_ERR_TIMER || entry->id == TRANSPORT_DISC_TIMER) { - /* Posted transport error/disconnection event */ - pj_bool_t tp_disc = (entry->id == TRANSPORT_DISC_TIMER); + /* Posted transport error/disconnection event */ + pj_bool_t tp_disc = (entry->id == TRANSPORT_DISC_TIMER); - entry->id = 0; - if (tsx->state < PJSIP_TSX_STATE_TERMINATED) { - pjsip_tsx_state_e prev_state; - pj_time_val timeout = { 0, 0 }; + entry->id = 0; + if (tsx->state < PJSIP_TSX_STATE_TERMINATED) { + pjsip_tsx_state_e prev_state; + pj_time_val timeout = { 0, 0 }; - pj_grp_lock_acquire(tsx->grp_lock); - prev_state = tsx->state; + pj_grp_lock_acquire(tsx->grp_lock); + prev_state = tsx->state; - /* Release transport as it's no longer working. */ - tsx_update_transport(tsx, NULL); + /* Release transport as it's no longer working. */ + tsx_update_transport(tsx, NULL); #if PJSIP_TSX_UAS_CONTINUE_ON_TP_ERROR - if (tp_disc && tsx->method.id == PJSIP_INVITE_METHOD && - tsx->role == PJSIP_ROLE_UAS && tsx->status_code < 200 && - !(tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) && - !(tsx->transport_flag & TSX_HAS_PENDING_DESTROY)) + if (tp_disc && tsx->method.id == PJSIP_INVITE_METHOD && + tsx->role == PJSIP_ROLE_UAS && tsx->status_code < 200 && + !(tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) && + !(tsx->transport_flag & TSX_HAS_PENDING_DESTROY)) #else - PJ_UNUSED_ARG(tp_disc); - if (0) + PJ_UNUSED_ARG(tp_disc); + if (0) #endif - { - /* Upon transport disconnection event, if we receive - * incoming INVITE and haven't responded with a final answer, - * just return here and don't terminate the transaction, - * in case that the library can switch to another working - * transport. - */ - tsx->transport_flag = 0; - tsx->addr_len = 0; - tsx->res_addr.transport = NULL; - tsx->res_addr.addr_len = 0; - - pj_grp_lock_release(tsx->grp_lock); - return; - } - - if (tsx->status_code < 200) { - pj_str_t err; - char errmsg[PJ_ERR_MSG_SIZE]; - - err = pj_strerror(tsx->transport_err, errmsg, sizeof(errmsg)); - tsx_set_status_code(tsx, PJSIP_SC_TSX_TRANSPORT_ERROR, &err); - } - - /* Set transaction state etc, but don't notify TU now, - * otherwise we'll get a deadlock. See: - * https://github.com/pjsip/pjproject/issues/1646 - */ - /* Also don't schedule tsx handler, otherwise we'll get race - * condition of TU notifications due to delayed TERMINATED - * state TU notification. It happened in multiple worker threads - * environment between TERMINATED & DESTROYED! See: - * https://github.com/pjsip/pjproject/issues/1902 - */ - tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, - PJSIP_EVENT_TRANSPORT_ERROR, NULL, - NO_NOTIFY | NO_SCHEDULE_HANDLER); - pj_grp_lock_release(tsx->grp_lock); - - /* Now notify TU about state change, WITHOUT holding the - * group lock. It should be safe to do so; transaction will - * not get destroyed because group lock reference counter - * has been incremented by the timer heap. - */ - if (tsx->tsx_user && tsx->tsx_user->on_tsx_state) { - pjsip_event e; - PJSIP_EVENT_INIT_TSX_STATE(e, tsx, - PJSIP_EVENT_TRANSPORT_ERROR, NULL, - prev_state); - (*tsx->tsx_user->on_tsx_state)(tsx, &e); - } - - /* Now let's schedule the tsx handler */ - tsx_schedule_timer(tsx, &tsx->timeout_timer, &timeout, - TIMEOUT_TIMER); - } + { + /* Upon transport disconnection event, if we receive + * incoming INVITE and haven't responded with a final answer, + * just return here and don't terminate the transaction, + * in case that the library can switch to another working + * transport. + */ + tsx->transport_flag = 0; + tsx->addr_len = 0; + tsx->res_addr.transport = NULL; + tsx->res_addr.addr_len = 0; + + pj_grp_lock_release(tsx->grp_lock); + return; + } + + if (tsx->status_code < 200) { + pj_str_t err; + char errmsg[PJ_ERR_MSG_SIZE]; + + err = pj_strerror(tsx->transport_err, errmsg, sizeof(errmsg)); + tsx_set_status_code(tsx, PJSIP_SC_TSX_TRANSPORT_ERROR, &err); + } + + /* Set transaction state etc, but don't notify TU now, + * otherwise we'll get a deadlock. See: + * https://github.com/pjsip/pjproject/issues/1646 + */ + /* Also don't schedule tsx handler, otherwise we'll get race + * condition of TU notifications due to delayed TERMINATED + * state TU notification. It happened in multiple worker threads + * environment between TERMINATED & DESTROYED! See: + * https://github.com/pjsip/pjproject/issues/1902 + */ + tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, + PJSIP_EVENT_TRANSPORT_ERROR, NULL, + NO_NOTIFY | NO_SCHEDULE_HANDLER); + pj_grp_lock_release(tsx->grp_lock); + + /* Now notify TU about state change, WITHOUT holding the + * group lock. It should be safe to do so; transaction will + * not get destroyed because group lock reference counter + * has been incremented by the timer heap. + */ + if (tsx->tsx_user && tsx->tsx_user->on_tsx_state) { + pjsip_event e; + PJSIP_EVENT_INIT_TSX_STATE(e, tsx, + PJSIP_EVENT_TRANSPORT_ERROR, NULL, + prev_state); + (*tsx->tsx_user->on_tsx_state)(tsx, &e); + } + + /* Now let's schedule the tsx handler */ + tsx_schedule_timer(tsx, &tsx->timeout_timer, &timeout, + TIMEOUT_TIMER); + } } else { - pjsip_event event; + pjsip_event event; - entry->id = 0; + entry->id = 0; - PJ_LOG(5,(tsx->obj_name, "%s timer event", - (entry==&tsx->retransmit_timer ? "Retransmit":"Timeout"))); - pj_log_push_indent(); + PJ_LOG(5,(tsx->obj_name, "%s timer event", + (entry==&tsx->retransmit_timer ? "Retransmit":"Timeout"))); + pj_log_push_indent(); - PJSIP_EVENT_INIT_TIMER(event, entry); + PJSIP_EVENT_INIT_TIMER(event, entry); - /* Dispatch event to transaction. */ - pj_grp_lock_acquire(tsx->grp_lock); - (*tsx->state_handler)(tsx, &event); - pj_grp_lock_release(tsx->grp_lock); + /* Dispatch event to transaction. */ + pj_grp_lock_acquire(tsx->grp_lock); + (*tsx->state_handler)(tsx, &event); + pj_grp_lock_release(tsx->grp_lock); - pj_log_pop_indent(); + pj_log_pop_indent(); } } @@ -1271,10 +1270,10 @@ static void tsx_timer_callback( pj_timer_heap_t *theap, pj_timer_entry *entry) * Set transaction state, and inform TU about the transaction state change. */ static void tsx_set_state( pjsip_transaction *tsx, - pjsip_tsx_state_e state, - pjsip_event_id_e event_src_type, + pjsip_tsx_state_e state, + pjsip_event_id_e event_src_type, void *event_src, - int flag) + int flag) { pjsip_tsx_state_e prev_state = tsx->state; @@ -1282,7 +1281,7 @@ static void tsx_set_state( pjsip_transaction *tsx, pj_assert(state >= tsx->state); PJ_LOG(5, (tsx->obj_name, "State changed from %s to %s, event=%s", - state_str[tsx->state], state_str[state], + state_str[tsx->state], state_str[state], pjsip_event_str(event_src_type))); pj_log_push_indent(); @@ -1291,59 +1290,59 @@ static void tsx_set_state( pjsip_transaction *tsx, /* Update the state handlers. */ if (tsx->role == PJSIP_ROLE_UAC) { - tsx->state_handler = tsx_state_handler_uac[state]; + tsx->state_handler = tsx_state_handler_uac[state]; } else { - tsx->state_handler = tsx_state_handler_uas[state]; + tsx->state_handler = tsx_state_handler_uas[state]; } /* Before informing TU about state changed, inform TU about * rx event. */ if (event_src_type==PJSIP_EVENT_RX_MSG && tsx->tsx_user && - (flag & NO_NOTIFY)==0) + (flag & NO_NOTIFY)==0) { - pjsip_rx_data *rdata = (pjsip_rx_data*) event_src; + pjsip_rx_data *rdata = (pjsip_rx_data*) event_src; - pj_assert(rdata != NULL); + pj_assert(rdata != NULL); - if (rdata->msg_info.msg->type == PJSIP_RESPONSE_MSG && - tsx->tsx_user->on_rx_response) - { - (*tsx->tsx_user->on_rx_response)(rdata); - } + if (rdata->msg_info.msg->type == PJSIP_RESPONSE_MSG && + tsx->tsx_user->on_rx_response) + { + (*tsx->tsx_user->on_rx_response)(rdata); + } } /* Inform TU about state changed. */ if (tsx->tsx_user && tsx->tsx_user->on_tsx_state && - (flag & NO_NOTIFY) == 0) + (flag & NO_NOTIFY) == 0) { - pjsip_event e; - PJSIP_EVENT_INIT_TSX_STATE(e, tsx, event_src_type, event_src, - prev_state); - - /* For timer event, release lock to avoid deadlock. - * This should be safe because: - * 1. The tsx state just switches to TERMINATED or DESTROYED. - * 2. There should be no other processing taking place. All other - * events, such as the ones handled by tsx_on_state_terminated() - * should be ignored. + pjsip_event e; + PJSIP_EVENT_INIT_TSX_STATE(e, tsx, event_src_type, event_src, + prev_state); + + /* For timer event, release lock to avoid deadlock. + * This should be safe because: + * 1. The tsx state just switches to TERMINATED or DESTROYED. + * 2. There should be no other processing taking place. All other + * events, such as the ones handled by tsx_on_state_terminated() + * should be ignored. * 3. tsx_shutdown() hasn't been called. - * Refer to ticket #2001 (https://github.com/pjsip/pjproject/issues/2001). - */ - if (event_src_type == PJSIP_EVENT_TIMER && - (pj_timer_entry *)event_src == &tsx->timeout_timer) - { - pj_grp_lock_release(tsx->grp_lock); - } - - (*tsx->tsx_user->on_tsx_state)(tsx, &e); - - if (event_src_type == PJSIP_EVENT_TIMER && - (pj_timer_entry *)event_src == &tsx->timeout_timer) - { - pj_grp_lock_acquire(tsx->grp_lock); - } + * Refer to ticket #2001 (https://github.com/pjsip/pjproject/issues/2001). + */ + if (event_src_type == PJSIP_EVENT_TIMER && + (pj_timer_entry *)event_src == &tsx->timeout_timer) + { + pj_grp_lock_release(tsx->grp_lock); + } + + (*tsx->tsx_user->on_tsx_state)(tsx, &e); + + if (event_src_type == PJSIP_EVENT_TIMER && + (pj_timer_entry *)event_src == &tsx->timeout_timer) + { + pj_grp_lock_acquire(tsx->grp_lock); + } } @@ -1351,40 +1350,40 @@ static void tsx_set_state( pjsip_transaction *tsx, * saved last transmitted message. */ if (state == PJSIP_TSX_STATE_TERMINATED) { - pj_time_val timeout = { 0, 0 }; - - /* If we're still waiting for a message to be sent.. */ - if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { - /* Disassociate ourselves from the outstanding transmit data - * so that when the send callback is called we will be able - * to ignore that (otherwise we'll get assertion, see - * https://github.com/pjsip/pjproject/issues/1033) - */ - if (tsx->pending_tx) { - tsx->pending_tx->mod_data[mod_tsx_layer.mod.id] = NULL; - tsx->pending_tx = NULL; - - /* Decrease pending send counter */ - pj_grp_lock_dec_ref(tsx->grp_lock); - } - tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); - } - - lock_timer(tsx); - tsx_cancel_timer(tsx, &tsx->timeout_timer); - if ((flag & NO_SCHEDULE_HANDLER) == 0) { - tsx_schedule_timer(tsx, &tsx->timeout_timer, &timeout, - TIMEOUT_TIMER); - } - unlock_timer(tsx); + pj_time_val timeout = { 0, 0 }; + + /* If we're still waiting for a message to be sent.. */ + if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { + /* Disassociate ourselves from the outstanding transmit data + * so that when the send callback is called we will be able + * to ignore that (otherwise we'll get assertion, see + * https://github.com/pjsip/pjproject/issues/1033) + */ + if (tsx->pending_tx) { + tsx->pending_tx->mod_data[mod_tsx_layer.mod.id] = NULL; + tsx->pending_tx = NULL; + + /* Decrease pending send counter */ + pj_grp_lock_dec_ref(tsx->grp_lock); + } + tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); + } + + lock_timer(tsx); + tsx_cancel_timer(tsx, &tsx->timeout_timer); + if ((flag & NO_SCHEDULE_HANDLER) == 0) { + tsx_schedule_timer(tsx, &tsx->timeout_timer, &timeout, + TIMEOUT_TIMER); + } + unlock_timer(tsx); } else if (state == PJSIP_TSX_STATE_DESTROYED) { - /* Unregister transaction. */ - mod_tsx_layer_unregister_tsx(tsx); + /* Unregister transaction. */ + mod_tsx_layer_unregister_tsx(tsx); - /* Destroy transaction. */ - tsx_shutdown(tsx); + /* Destroy transaction. */ + tsx_shutdown(tsx); } pj_log_pop_indent(); @@ -1394,16 +1393,16 @@ static void tsx_set_state( pjsip_transaction *tsx, * Create, initialize, and register UAC transaction. */ PJ_DEF(pj_status_t) pjsip_tsx_create_uac( pjsip_module *tsx_user, - pjsip_tx_data *tdata, - pjsip_transaction **p_tsx) + pjsip_tx_data *tdata, + pjsip_transaction **p_tsx) { return pjsip_tsx_create_uac2(tsx_user, tdata, NULL, p_tsx); } PJ_DEF(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user, - pjsip_tx_data *tdata, - pj_grp_lock_t *grp_lock, - pjsip_transaction **p_tsx) + pjsip_tx_data *tdata, + pj_grp_lock_t *grp_lock, + pjsip_transaction **p_tsx) { pjsip_transaction *tsx; pjsip_msg *msg; @@ -1415,11 +1414,11 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user, /* Validate arguments. */ PJ_ASSERT_RETURN(tdata && tdata->msg && p_tsx, PJ_EINVAL); PJ_ASSERT_RETURN(tdata->msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); /* Method MUST NOT be ACK! */ PJ_ASSERT_RETURN(tdata->msg->line.req.method.id != PJSIP_ACK_METHOD, - PJ_EINVALIDOP); + PJ_EINVALIDOP); /* Keep shortcut */ msg = tdata->msg; @@ -1427,15 +1426,15 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user, /* Make sure CSeq header is present. */ cseq = (pjsip_cseq_hdr*) pjsip_msg_find_hdr(msg, PJSIP_H_CSEQ, NULL); if (!cseq) { - pj_assert(!"CSeq header not present in outgoing message!"); - return PJSIP_EMISSINGHDR; + pj_assert(!"CSeq header not present in outgoing message!"); + return PJSIP_EMISSINGHDR; } /* Create transaction instance. */ status = tsx_create( tsx_user, grp_lock, &tsx); if (status != PJ_SUCCESS) - return status; + return status; /* Lock transaction. @@ -1457,21 +1456,21 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user, /* Generate Via header if it doesn't exist. */ via = (pjsip_via_hdr*) pjsip_msg_find_hdr(msg, PJSIP_H_VIA, NULL); if (via == NULL) { - via = pjsip_via_hdr_create(tdata->pool); - pjsip_msg_insert_first_hdr(msg, (pjsip_hdr*) via); + via = pjsip_via_hdr_create(tdata->pool); + pjsip_msg_insert_first_hdr(msg, (pjsip_hdr*) via); } /* Generate branch parameter if it doesn't exist. */ if (via->branch_param.slen == 0) { - pj_str_t tmp; - via->branch_param.ptr = (char*) - pj_pool_alloc(tsx->pool, PJSIP_MAX_BRANCH_LEN); - via->branch_param.slen = PJSIP_MAX_BRANCH_LEN; - pj_memcpy(via->branch_param.ptr, PJSIP_RFC3261_BRANCH_ID, - PJSIP_RFC3261_BRANCH_LEN); - tmp.ptr = via->branch_param.ptr + PJSIP_RFC3261_BRANCH_LEN + 2; - *(tmp.ptr-2) = 80; *(tmp.ptr-1) = 106; - pj_generate_unique_string( &tmp ); + pj_str_t tmp; + via->branch_param.ptr = (char*) + pj_pool_alloc(tsx->pool, PJSIP_MAX_BRANCH_LEN); + via->branch_param.slen = PJSIP_MAX_BRANCH_LEN; + pj_memcpy(via->branch_param.ptr, PJSIP_RFC3261_BRANCH_ID, + PJSIP_RFC3261_BRANCH_LEN); + tmp.ptr = via->branch_param.ptr + PJSIP_RFC3261_BRANCH_LEN + 2; + *(tmp.ptr-2) = 80; *(tmp.ptr-1) = 106; + pj_generate_unique_string( &tmp ); /* Save branch parameter. */ tsx->branch = via->branch_param; @@ -1483,8 +1482,8 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user, /* Generate transaction key. */ create_tsx_key_3261( tsx->pool, &tsx->transaction_key, - PJSIP_ROLE_UAC, &tsx->method, - &via->branch_param); + PJSIP_ROLE_UAC, &tsx->method, + &via->branch_param); /* Calculate hashed key value. */ #ifdef PRECALC_HASH @@ -1492,7 +1491,7 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user, #endif PJ_LOG(6, (tsx->obj_name, "tsx_key=%.*s", tsx->transaction_key.slen, - tsx->transaction_key.ptr)); + tsx->transaction_key.ptr)); /* Begin with State_Null. * Manually set-up the state becase we don't want to call the callback. @@ -1509,23 +1508,23 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user, */ status = pjsip_get_request_dest(tdata, &dst_info); if (status != PJ_SUCCESS) { - if (grp_lock) - pj_grp_lock_release(tsx->grp_lock); - tsx_shutdown(tsx); - return status; + if (grp_lock) + pj_grp_lock_release(tsx->grp_lock); + tsx_shutdown(tsx); + return status; } tsx->is_reliable = (dst_info.flag & PJSIP_TRANSPORT_RELIABLE); /* Register transaction to hash table. */ status = mod_tsx_layer_register_tsx(tsx); if (status != PJ_SUCCESS) { - /* The assertion is removed by #1090: - pj_assert(!"Bug in branch_param generator (i.e. not unique)"); - */ - if (grp_lock) - pj_grp_lock_release(tsx->grp_lock); - tsx_shutdown(tsx); - return status; + /* The assertion is removed by #1090: + pj_assert(!"Bug in branch_param generator (i.e. not unique)"); + */ + if (grp_lock) + pj_grp_lock_release(tsx->grp_lock); + tsx_shutdown(tsx); + return status; } @@ -1535,7 +1534,7 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user, pj_log_push_indent(); PJ_LOG(5,(tsx->obj_name, "Transaction created for %s", - pjsip_tx_data_get_info(tdata))); + pjsip_tx_data_get_info(tdata))); pj_log_pop_indent(); *p_tsx = tsx; @@ -1547,16 +1546,16 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user, * Create, initialize, and register UAS transaction. */ PJ_DEF(pj_status_t) pjsip_tsx_create_uas( pjsip_module *tsx_user, - pjsip_rx_data *rdata, - pjsip_transaction **p_tsx) + pjsip_rx_data *rdata, + pjsip_transaction **p_tsx) { return pjsip_tsx_create_uas2(tsx_user, rdata, NULL, p_tsx); } PJ_DEF(pj_status_t) pjsip_tsx_create_uas2(pjsip_module *tsx_user, - pjsip_rx_data *rdata, - pj_grp_lock_t *grp_lock, - pjsip_transaction **p_tsx) + pjsip_rx_data *rdata, + pj_grp_lock_t *grp_lock, + pjsip_transaction **p_tsx) { pjsip_transaction *tsx; pjsip_msg *msg; @@ -1575,26 +1574,26 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uas2(pjsip_module *tsx_user, /* Make sure method is not ACK */ PJ_ASSERT_RETURN(msg->line.req.method.id != PJSIP_ACK_METHOD, - PJ_EINVALIDOP); + PJ_EINVALIDOP); /* Make sure CSeq header is present. */ cseq = rdata->msg_info.cseq; if (!cseq) - return PJSIP_EMISSINGHDR; + return PJSIP_EMISSINGHDR; /* Make sure Via header is present. */ if (rdata->msg_info.via == NULL) - return PJSIP_EMISSINGHDR; + return PJSIP_EMISSINGHDR; /* Check that method in CSeq header match request method. * Reference: PROTOS #1922 */ if (pjsip_method_cmp(&msg->line.req.method, - &rdata->msg_info.cseq->method) != 0) + &rdata->msg_info.cseq->method) != 0) { - PJ_LOG(4,(THIS_FILE, "Error: CSeq header contains different " - "method than the request line")); - return PJSIP_EINVALIDHDR; + PJ_LOG(4,(THIS_FILE, "Error: CSeq header contains different " + "method than the request line")); + return PJSIP_EINVALIDHDR; } /* @@ -1602,7 +1601,7 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uas2(pjsip_module *tsx_user, */ status = tsx_create( tsx_user, grp_lock, &tsx); if (status != PJ_SUCCESS) - return status; + return status; /* Lock transaction. */ @@ -1623,8 +1622,8 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uas2(pjsip_module *tsx_user, status = pjsip_tsx_create_key(tsx->pool, &tsx->transaction_key, PJSIP_ROLE_UAS, &tsx->method, rdata); if (status != PJ_SUCCESS) { - pj_grp_lock_release(tsx->grp_lock); - tsx_shutdown(tsx); + pj_grp_lock_release(tsx->grp_lock); + tsx_shutdown(tsx); return status; } @@ -1638,7 +1637,7 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uas2(pjsip_module *tsx_user, pj_strdup(tsx->pool, &tsx->branch, branch); PJ_LOG(6, (tsx->obj_name, "tsx_key=%.*s", tsx->transaction_key.slen, - tsx->transaction_key.ptr)); + tsx->transaction_key.ptr)); /* Begin with state NULL. @@ -1650,31 +1649,31 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uas2(pjsip_module *tsx_user, /* Get response address. */ status = pjsip_get_response_addr( tsx->pool, rdata, &tsx->res_addr ); if (status != PJ_SUCCESS) { - pj_grp_lock_release(tsx->grp_lock); - tsx_shutdown(tsx); - return status; + pj_grp_lock_release(tsx->grp_lock); + tsx_shutdown(tsx); + return status; } /* If it's decided that we should use current transport, keep the * transport. */ if (tsx->res_addr.transport) { - tsx_update_transport(tsx, tsx->res_addr.transport); - pj_memcpy(&tsx->addr, &tsx->res_addr.addr, tsx->res_addr.addr_len); - tsx->addr_len = tsx->res_addr.addr_len; - tsx->is_reliable = PJSIP_TRANSPORT_IS_RELIABLE(tsx->transport); + tsx_update_transport(tsx, tsx->res_addr.transport); + pj_memcpy(&tsx->addr, &tsx->res_addr.addr, tsx->res_addr.addr_len); + tsx->addr_len = tsx->res_addr.addr_len; + tsx->is_reliable = PJSIP_TRANSPORT_IS_RELIABLE(tsx->transport); } else { - tsx->is_reliable = - (tsx->res_addr.dst_host.flag & PJSIP_TRANSPORT_RELIABLE); + tsx->is_reliable = + (tsx->res_addr.dst_host.flag & PJSIP_TRANSPORT_RELIABLE); } /* Register the transaction. */ status = mod_tsx_layer_register_tsx(tsx); if (status != PJ_SUCCESS) { - pj_grp_lock_release(tsx->grp_lock); - tsx_shutdown(tsx); - return status; + pj_grp_lock_release(tsx->grp_lock); + tsx_shutdown(tsx); + return status; } /* Put this transaction in rdata's mod_data. */ @@ -1685,7 +1684,7 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uas2(pjsip_module *tsx_user, pj_log_push_indent(); PJ_LOG(5,(tsx->obj_name, "Transaction created for %s", - pjsip_rx_data_get_info(rdata))); + pjsip_rx_data_get_info(rdata))); pj_log_pop_indent(); @@ -1698,7 +1697,7 @@ PJ_DEF(pj_status_t) pjsip_tsx_create_uas2(pjsip_module *tsx_user, * Bind transaction to a specific transport/listener. */ PJ_DEF(pj_status_t) pjsip_tsx_set_transport(pjsip_transaction *tsx, - const pjsip_tpselector *sel) + const pjsip_tpselector *sel) { /* Must be UAC transaction */ PJ_ASSERT_RETURN(tsx && sel, PJ_EINVAL); @@ -1726,13 +1725,13 @@ PJ_DEF(pj_status_t) pjsip_tsx_set_transport(pjsip_transaction *tsx, * Set transaction status code and reason. */ static void tsx_set_status_code(pjsip_transaction *tsx, - int code, const pj_str_t *reason) + int code, const pj_str_t *reason) { tsx->status_code = code; if (reason) - pj_strdup(tsx->pool, &tsx->status_text, reason); + pj_strdup(tsx->pool, &tsx->status_text, reason); else - tsx->status_text = *pjsip_get_status_text(code); + tsx->status_text = *pjsip_get_status_text(code); } @@ -1754,7 +1753,7 @@ PJ_DEF(pj_status_t) pjsip_tsx_terminate( pjsip_transaction *tsx, int code ) if (tsx->state < PJSIP_TSX_STATE_TERMINATED) { tsx_set_status_code(tsx, code, NULL); tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, PJSIP_EVENT_USER, - NULL, 0); + NULL, 0); } pj_grp_lock_release(tsx->grp_lock); @@ -1773,8 +1772,8 @@ PJ_DEF(pj_status_t) pjsip_tsx_stop_retransmit(pjsip_transaction *tsx) { PJ_ASSERT_RETURN(tsx != NULL, PJ_EINVAL); PJ_ASSERT_RETURN(tsx->role == PJSIP_ROLE_UAC && - tsx->method.id == PJSIP_INVITE_METHOD, - PJ_EINVALIDOP); + tsx->method.id == PJSIP_INVITE_METHOD, + PJ_EINVALIDOP); PJ_LOG(5,(tsx->obj_name, "Request to stop retransmission")); @@ -1796,14 +1795,14 @@ PJ_DEF(pj_status_t) pjsip_tsx_stop_retransmit(pjsip_transaction *tsx) * has elapsed. */ PJ_DEF(pj_status_t) pjsip_tsx_set_timeout( pjsip_transaction *tsx, - unsigned millisec) + unsigned millisec) { pj_time_val timeout; PJ_ASSERT_RETURN(tsx != NULL, PJ_EINVAL); PJ_ASSERT_RETURN(tsx->role == PJSIP_ROLE_UAC && - tsx->method.id == PJSIP_INVITE_METHOD, - PJ_EINVALIDOP); + tsx->method.id == PJSIP_INVITE_METHOD, + PJ_EINVALIDOP); /* Note: must not call pj_grp_lock_acquire(tsx->grp_lock) as * that would introduce deadlock. See #1121. @@ -1815,9 +1814,9 @@ PJ_DEF(pj_status_t) pjsip_tsx_set_timeout( pjsip_transaction *tsx, * where this might happen. */ if (tsx->status_code >= 200 && tsx->timeout_timer.id != 0) { - /* Timeout is already set */ - unlock_timer(tsx); - return PJ_EEXISTS; + /* Timeout is already set */ + unlock_timer(tsx); + return PJ_EEXISTS; } tsx_cancel_timer(tsx, &tsx->timeout_timer); @@ -1838,19 +1837,19 @@ PJ_DEF(pj_status_t) pjsip_tsx_set_timeout( pjsip_transaction *tsx, * This function is called by TU to send a message. */ PJ_DEF(pj_status_t) pjsip_tsx_send_msg( pjsip_transaction *tsx, - pjsip_tx_data *tdata ) + pjsip_tx_data *tdata ) { pjsip_event event; pj_status_t status; if (tdata == NULL) - tdata = tsx->last_tx; + tdata = tsx->last_tx; PJ_ASSERT_RETURN(tdata != NULL, PJ_EINVALIDOP); PJ_LOG(5,(tsx->obj_name, "Sending %s in state %s", pjsip_tx_data_get_info(tdata), - state_str[tsx->state])); + state_str[tsx->state])); pj_log_push_indent(); PJSIP_EVENT_INIT_TX_MSG(event, tdata); @@ -1870,7 +1869,7 @@ PJ_DEF(pj_status_t) pjsip_tsx_send_msg( pjsip_transaction *tsx, * (This is the specification from the .PDF design document). */ if (status == PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); + pjsip_tx_data_dec_ref(tdata); } pj_log_pop_indent(); @@ -1884,12 +1883,12 @@ PJ_DEF(pj_status_t) pjsip_tsx_send_msg( pjsip_transaction *tsx, * transaction is received. */ PJ_DEF(void) pjsip_tsx_recv_msg( pjsip_transaction *tsx, - pjsip_rx_data *rdata) + pjsip_rx_data *rdata) { pjsip_event event; PJ_LOG(5,(tsx->obj_name, "Incoming %s in state %s", - pjsip_rx_data_get_info(rdata), state_str[tsx->state])); + pjsip_rx_data_get_info(rdata), state_str[tsx->state])); pj_log_push_indent(); /* Put the transaction in the rdata's mod_data. */ @@ -1909,7 +1908,7 @@ PJ_DEF(void) pjsip_tsx_recv_msg( pjsip_transaction *tsx, /* Callback called by send message framework */ static void send_msg_callback( pjsip_send_state *send_state, - pj_ssize_t sent, pj_bool_t *cont ) + pj_ssize_t sent, pj_bool_t *cont ) { pjsip_transaction *tsx = (pjsip_transaction*) send_state->token; pjsip_tx_data *tdata = send_state->tdata; @@ -1920,19 +1919,19 @@ static void send_msg_callback( pjsip_send_state *send_state, * (https://github.com/pjsip/pjproject/issues/1535) */ if (mod_tsx_layer.mod.id < 0 || - tdata->mod_data[mod_tsx_layer.mod.id] == NULL) + tdata->mod_data[mod_tsx_layer.mod.id] == NULL) { - *cont = PJ_FALSE; + *cont = PJ_FALSE; - /* Decrease pending send counter, but only if the transaction layer - * hasn't been shutdown. - */ - // If tsx has cancelled itself from this transmit notification - // it should have also decreased pending send counter. - //if (mod_tsx_layer.mod.id >= 0) - // pj_grp_lock_dec_ref(tsx->grp_lock); + /* Decrease pending send counter, but only if the transaction layer + * hasn't been shutdown. + */ + // If tsx has cancelled itself from this transmit notification + // it should have also decreased pending send counter. + //if (mod_tsx_layer.mod.id >= 0) + // pj_grp_lock_dec_ref(tsx->grp_lock); - return; + return; } pj_grp_lock_acquire(tsx->grp_lock); @@ -1945,147 +1944,147 @@ static void send_msg_callback( pjsip_send_state *send_state, tsx->pending_tx = NULL; if (sent > 0) { - /* Successfully sent! */ - pj_assert(send_state->cur_transport != NULL); - - if (tsx->transport != send_state->cur_transport) { - /* Update transport. */ - tsx_update_transport(tsx, send_state->cur_transport); - - /* Update remote address. */ - tsx->addr_len = tdata->dest_info.addr.entry[tdata->dest_info.cur_addr].addr_len; - pj_memcpy(&tsx->addr, - &tdata->dest_info.addr.entry[tdata->dest_info.cur_addr].addr, - tsx->addr_len); - - /* Update is_reliable flag. */ - tsx->is_reliable = PJSIP_TRANSPORT_IS_RELIABLE(tsx->transport); - } - - /* Clear pending transport flag. */ - tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); - - /* Mark that we have resolved the addresses. */ - tsx->transport_flag |= TSX_HAS_RESOLVED_SERVER; - - /* Pending destroy? */ - if (tsx->transport_flag & TSX_HAS_PENDING_DESTROY) { - tsx_set_state( tsx, PJSIP_TSX_STATE_DESTROYED, - PJSIP_EVENT_UNKNOWN, NULL, 0 ); - pj_grp_lock_release(tsx->grp_lock); - return; - } - - /* Need to transmit a message? */ - if (tsx->transport_flag & TSX_HAS_PENDING_SEND) { - tsx->transport_flag &= ~(TSX_HAS_PENDING_SEND); - tsx_send_msg(tsx, tsx->last_tx); - } - - /* Need to reschedule retransmission? - * Note that when sending a pending message above, tsx_send_msg() - * may set the flag TSX_HAS_PENDING_TRANSPORT. - * Please refer to ticket #1875. - */ - if (tsx->transport_flag & TSX_HAS_PENDING_RESCHED && - !(tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT)) - { - tsx->transport_flag &= ~(TSX_HAS_PENDING_RESCHED); - - /* Only update when transport turns out to be unreliable. */ - if (!tsx->is_reliable) { - tsx_resched_retransmission(tsx); - } - } + /* Successfully sent! */ + pj_assert(send_state->cur_transport != NULL); + + if (tsx->transport != send_state->cur_transport) { + /* Update transport. */ + tsx_update_transport(tsx, send_state->cur_transport); + + /* Update remote address. */ + tsx->addr_len = tdata->dest_info.addr.entry[tdata->dest_info.cur_addr].addr_len; + pj_memcpy(&tsx->addr, + &tdata->dest_info.addr.entry[tdata->dest_info.cur_addr].addr, + tsx->addr_len); + + /* Update is_reliable flag. */ + tsx->is_reliable = PJSIP_TRANSPORT_IS_RELIABLE(tsx->transport); + } + + /* Clear pending transport flag. */ + tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); + + /* Mark that we have resolved the addresses. */ + tsx->transport_flag |= TSX_HAS_RESOLVED_SERVER; + + /* Pending destroy? */ + if (tsx->transport_flag & TSX_HAS_PENDING_DESTROY) { + tsx_set_state( tsx, PJSIP_TSX_STATE_DESTROYED, + PJSIP_EVENT_UNKNOWN, NULL, 0 ); + pj_grp_lock_release(tsx->grp_lock); + return; + } + + /* Need to transmit a message? */ + if (tsx->transport_flag & TSX_HAS_PENDING_SEND) { + tsx->transport_flag &= ~(TSX_HAS_PENDING_SEND); + tsx_send_msg(tsx, tsx->last_tx); + } + + /* Need to reschedule retransmission? + * Note that when sending a pending message above, tsx_send_msg() + * may set the flag TSX_HAS_PENDING_TRANSPORT. + * Please refer to ticket #1875. + */ + if (tsx->transport_flag & TSX_HAS_PENDING_RESCHED && + !(tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT)) + { + tsx->transport_flag &= ~(TSX_HAS_PENDING_RESCHED); + + /* Only update when transport turns out to be unreliable. */ + if (!tsx->is_reliable) { + tsx_resched_retransmission(tsx); + } + } } else { - /* Failed to send! */ - pj_assert(sent != 0); - - /* If transaction is using the same transport as the failed one, - * release the transport. - */ - if (send_state->cur_transport==tsx->transport) - tsx_update_transport(tsx, NULL); - - /* Also stop processing if transaction has been flagged with - * pending destroy (https://github.com/pjsip/pjproject/issues/906) - */ - if ((!*cont) || (tsx->transport_flag & TSX_HAS_PENDING_DESTROY)) { - char errmsg[PJ_ERR_MSG_SIZE]; - pjsip_status_code sc; - pj_str_t err; - - tsx->transport_err = (pj_status_t)-sent; - - err =pj_strerror((pj_status_t)-sent, errmsg, sizeof(errmsg)); - - PJ_LOG(3,(tsx->obj_name, - "Failed to send %s! err=%d (%s)", - pjsip_tx_data_get_info(send_state->tdata), -sent, - errmsg)); - - /* Clear pending transport flag. */ - tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); - - /* Mark that we have resolved the addresses. */ - tsx->transport_flag |= TSX_HAS_RESOLVED_SERVER; - - /* Server resolution error is now mapped to 502 instead of 503, - * since with 503 normally client should try again. - * See https://github.com/pjsip/pjproject/issues/870 - */ - if (-sent==PJ_ERESOLVE || -sent==PJLIB_UTIL_EDNS_NXDOMAIN) - sc = PJSIP_SC_BAD_GATEWAY; - else - sc = PJSIP_SC_TSX_TRANSPORT_ERROR; - - /* Terminate transaction, if it's not already terminated. */ - tsx_set_status_code(tsx, sc, &err); - if (tsx->state != PJSIP_TSX_STATE_TERMINATED && - tsx->state != PJSIP_TSX_STATE_DESTROYED) - { - tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, - PJSIP_EVENT_TRANSPORT_ERROR, - send_state->tdata, 0); - } - /* Don't forget to destroy if we have pending destroy flag - * (https://github.com/pjsip/pjproject/issues/906) - */ - else if (tsx->transport_flag & TSX_HAS_PENDING_DESTROY) - { - tsx_set_state( tsx, PJSIP_TSX_STATE_DESTROYED, - PJSIP_EVENT_TRANSPORT_ERROR, - send_state->tdata, 0); - } - - } else { - PJ_PERROR(3,(tsx->obj_name, (pj_status_t)-sent, - "Temporary failure in sending %s, " - "will try next server", - pjsip_tx_data_get_info(send_state->tdata))); - - /* Reset retransmission count */ - tsx->retransmit_count = 0; - - /* And reset timeout timer */ - if (tsx->timeout_timer.id) { - lock_timer(tsx); - tsx_cancel_timer(tsx, &tsx->timeout_timer); - tsx_schedule_timer( tsx, &tsx->timeout_timer, - &timeout_timer_val, TIMEOUT_TIMER); - unlock_timer(tsx); - } - - /* Put again pending tdata */ - tdata->mod_data[mod_tsx_layer.mod.id] = tsx; - tsx->pending_tx = tdata; - - /* Increment group lock again for the next sending retry, - * to prevent us from being destroyed prematurely (ticket #1859). - */ - pj_grp_lock_add_ref(tsx->grp_lock); - } + /* Failed to send! */ + pj_assert(sent != 0); + + /* If transaction is using the same transport as the failed one, + * release the transport. + */ + if (send_state->cur_transport==tsx->transport) + tsx_update_transport(tsx, NULL); + + /* Also stop processing if transaction has been flagged with + * pending destroy (https://github.com/pjsip/pjproject/issues/906) + */ + if ((!*cont) || (tsx->transport_flag & TSX_HAS_PENDING_DESTROY)) { + char errmsg[PJ_ERR_MSG_SIZE]; + pjsip_status_code sc; + pj_str_t err; + + tsx->transport_err = (pj_status_t)-sent; + + err =pj_strerror((pj_status_t)-sent, errmsg, sizeof(errmsg)); + + PJ_LOG(3,(tsx->obj_name, + "Failed to send %s! err=%d (%s)", + pjsip_tx_data_get_info(send_state->tdata), -sent, + errmsg)); + + /* Clear pending transport flag. */ + tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); + + /* Mark that we have resolved the addresses. */ + tsx->transport_flag |= TSX_HAS_RESOLVED_SERVER; + + /* Server resolution error is now mapped to 502 instead of 503, + * since with 503 normally client should try again. + * See https://github.com/pjsip/pjproject/issues/870 + */ + if (-sent==PJ_ERESOLVE || -sent==PJLIB_UTIL_EDNS_NXDOMAIN) + sc = PJSIP_SC_BAD_GATEWAY; + else + sc = PJSIP_SC_TSX_TRANSPORT_ERROR; + + /* Terminate transaction, if it's not already terminated. */ + tsx_set_status_code(tsx, sc, &err); + if (tsx->state != PJSIP_TSX_STATE_TERMINATED && + tsx->state != PJSIP_TSX_STATE_DESTROYED) + { + tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, + PJSIP_EVENT_TRANSPORT_ERROR, + send_state->tdata, 0); + } + /* Don't forget to destroy if we have pending destroy flag + * (https://github.com/pjsip/pjproject/issues/906) + */ + else if (tsx->transport_flag & TSX_HAS_PENDING_DESTROY) + { + tsx_set_state( tsx, PJSIP_TSX_STATE_DESTROYED, + PJSIP_EVENT_TRANSPORT_ERROR, + send_state->tdata, 0); + } + + } else { + PJ_PERROR(3,(tsx->obj_name, (pj_status_t)-sent, + "Temporary failure in sending %s, " + "will try next server", + pjsip_tx_data_get_info(send_state->tdata))); + + /* Reset retransmission count */ + tsx->retransmit_count = 0; + + /* And reset timeout timer */ + if (tsx->timeout_timer.id) { + lock_timer(tsx); + tsx_cancel_timer(tsx, &tsx->timeout_timer); + tsx_schedule_timer( tsx, &tsx->timeout_timer, + &timeout_timer_val, TIMEOUT_TIMER); + unlock_timer(tsx); + } + + /* Put again pending tdata */ + tdata->mod_data[mod_tsx_layer.mod.id] = tsx; + tsx->pending_tx = tdata; + + /* Increment group lock again for the next sending retry, + * to prevent us from being destroyed prematurely (ticket #1859). + */ + pj_grp_lock_add_ref(tsx->grp_lock); + } } pj_grp_lock_release(tsx->grp_lock); @@ -2094,13 +2093,13 @@ static void send_msg_callback( pjsip_send_state *send_state, /* Transport callback. */ static void transport_callback(void *token, pjsip_tx_data *tdata, - pj_ssize_t sent) + pj_ssize_t sent) { pjsip_transaction *tsx = (pjsip_transaction*) token; /* Check if the transaction layer has been shutdown. */ if (mod_tsx_layer.mod.id < 0) - return; + return; /* In other circumstances, locking tsx->grp_lock AFTER transport mutex * will introduce deadlock if another thread is currently sending a @@ -2112,59 +2111,59 @@ static void transport_callback(void *token, pjsip_tx_data *tdata, tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); if (sent > 0) { - /* Pending destroy? */ - if (tsx->transport_flag & TSX_HAS_PENDING_DESTROY) { - tsx_set_state( tsx, PJSIP_TSX_STATE_DESTROYED, - PJSIP_EVENT_UNKNOWN, NULL, 0 ); - pj_grp_lock_release(tsx->grp_lock); - return; - } - - /* Need to transmit a message? */ - if (tsx->transport_flag & TSX_HAS_PENDING_SEND) { - tsx->transport_flag &= ~(TSX_HAS_PENDING_SEND); - tsx_send_msg(tsx, tsx->last_tx); - } - - /* Need to reschedule retransmission? - * Note that when sending a pending message above, tsx_send_msg() - * may set the flag TSX_HAS_PENDING_TRANSPORT. - * Please refer to ticket #1875. - */ - if (tsx->transport_flag & TSX_HAS_PENDING_RESCHED && - !(tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT)) - { - tsx->transport_flag &= ~(TSX_HAS_PENDING_RESCHED); - - /* Only update when transport turns out to be unreliable. */ - if (!tsx->is_reliable) { - tsx_resched_retransmission(tsx); - } - } + /* Pending destroy? */ + if (tsx->transport_flag & TSX_HAS_PENDING_DESTROY) { + tsx_set_state( tsx, PJSIP_TSX_STATE_DESTROYED, + PJSIP_EVENT_UNKNOWN, NULL, 0 ); + pj_grp_lock_release(tsx->grp_lock); + return; + } + + /* Need to transmit a message? */ + if (tsx->transport_flag & TSX_HAS_PENDING_SEND) { + tsx->transport_flag &= ~(TSX_HAS_PENDING_SEND); + tsx_send_msg(tsx, tsx->last_tx); + } + + /* Need to reschedule retransmission? + * Note that when sending a pending message above, tsx_send_msg() + * may set the flag TSX_HAS_PENDING_TRANSPORT. + * Please refer to ticket #1875. + */ + if (tsx->transport_flag & TSX_HAS_PENDING_RESCHED && + !(tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT)) + { + tsx->transport_flag &= ~(TSX_HAS_PENDING_RESCHED); + + /* Only update when transport turns out to be unreliable. */ + if (!tsx->is_reliable) { + tsx_resched_retransmission(tsx); + } + } } pj_grp_lock_release(tsx->grp_lock); if (sent < 0) { - pj_time_val delay = {0, 0}; - - PJ_PERROR(2,(tsx->obj_name, (pj_status_t)-sent, - "Transport failed to send %s!", - pjsip_tx_data_get_info(tdata))); - - /* Post the event for later processing, to avoid deadlock. - * See https://github.com/pjsip/pjproject/issues/1646 - */ - lock_timer(tsx); - tsx->transport_err = (pj_status_t)-sent; - /* Don't cancel timeout timer if tsx state is already - * PJSIP_TSX_STATE_COMPLETED (see #2076). - */ - if (tsx->state < PJSIP_TSX_STATE_COMPLETED) { - tsx_cancel_timer(tsx, &tsx->timeout_timer); - tsx_schedule_timer(tsx, &tsx->timeout_timer, &delay, - TRANSPORT_ERR_TIMER); - } - unlock_timer(tsx); + pj_time_val delay = {0, 0}; + + PJ_PERROR(2,(tsx->obj_name, (pj_status_t)-sent, + "Transport failed to send %s!", + pjsip_tx_data_get_info(tdata))); + + /* Post the event for later processing, to avoid deadlock. + * See https://github.com/pjsip/pjproject/issues/1646 + */ + lock_timer(tsx); + tsx->transport_err = (pj_status_t)-sent; + /* Don't cancel timeout timer if tsx state is already + * PJSIP_TSX_STATE_COMPLETED (see #2076). + */ + if (tsx->state < PJSIP_TSX_STATE_COMPLETED) { + tsx_cancel_timer(tsx, &tsx->timeout_timer); + tsx_schedule_timer(tsx, &tsx->timeout_timer, &delay, + TRANSPORT_ERR_TIMER); + } + unlock_timer(tsx); } /* Decrease pending send counter */ @@ -2176,33 +2175,33 @@ static void transport_callback(void *token, pjsip_tx_data *tdata, * Callback when transport state changes. */ static void tsx_tp_state_callback( pjsip_transport *tp, - pjsip_transport_state state, - const pjsip_transport_state_info *info) + pjsip_transport_state state, + const pjsip_transport_state_info *info) { PJ_UNUSED_ARG(tp); if (state == PJSIP_TP_STATE_DISCONNECTED) { - pjsip_transaction *tsx; - pj_time_val delay = {0, 0}; - - pj_assert(tp && info && info->user_data); - - tsx = (pjsip_transaction*)info->user_data; - - /* Post the event for later processing, to avoid deadlock. - * See https://github.com/pjsip/pjproject/issues/1646 - */ - lock_timer(tsx); - tsx->transport_err = info->status; - /* Don't cancel timeout timer if tsx state is already - * PJSIP_TSX_STATE_COMPLETED (see #2076). - */ - if (tsx->state < PJSIP_TSX_STATE_COMPLETED) { - tsx_cancel_timer(tsx, &tsx->timeout_timer); - tsx_schedule_timer(tsx, &tsx->timeout_timer, &delay, - TRANSPORT_DISC_TIMER); - } - unlock_timer(tsx); + pjsip_transaction *tsx; + pj_time_val delay = {0, 0}; + + pj_assert(tp && info && info->user_data); + + tsx = (pjsip_transaction*)info->user_data; + + /* Post the event for later processing, to avoid deadlock. + * See https://github.com/pjsip/pjproject/issues/1646 + */ + lock_timer(tsx); + tsx->transport_err = info->status; + /* Don't cancel timeout timer if tsx state is already + * PJSIP_TSX_STATE_COMPLETED (see #2076). + */ + if (tsx->state < PJSIP_TSX_STATE_COMPLETED) { + tsx_cancel_timer(tsx, &tsx->timeout_timer); + tsx_schedule_timer(tsx, &tsx->timeout_timer, &delay, + TRANSPORT_DISC_TIMER); + } + unlock_timer(tsx); } } @@ -2219,55 +2218,55 @@ static pj_status_t tsx_send_msg( pjsip_transaction *tsx, /* Send later if transport is still pending. */ if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { - tsx->transport_flag |= TSX_HAS_PENDING_SEND; - return PJ_SUCCESS; + tsx->transport_flag |= TSX_HAS_PENDING_SEND; + return PJ_SUCCESS; } /* Skip send if previous tdata transmission is pending (see #1665). */ if (tdata->is_pending) { - PJ_LOG(2,(THIS_FILE, "Unable to send %s: message is pending", - pjsip_tx_data_get_info(tdata))); - return PJ_SUCCESS; + PJ_LOG(2,(THIS_FILE, "Unable to send %s: message is pending", + pjsip_tx_data_get_info(tdata))); + return PJ_SUCCESS; } /* If we have the transport, send the message using that transport. * Otherwise perform full transport resolution. */ if (tsx->transport) { - /* Increment group lock while waiting for send operation to complete, - * to prevent us from being destroyed prematurely. See - * https://github.com/pjsip/pjproject/issues/1646 - */ - pj_grp_lock_add_ref(tsx->grp_lock); - tsx->transport_flag |= TSX_HAS_PENDING_TRANSPORT; - - status = pjsip_transport_send( tsx->transport, tdata, &tsx->addr, - tsx->addr_len, tsx, - &transport_callback); - if (status == PJ_EPENDING) - status = PJ_SUCCESS; - else { - /* Operation completes immediately */ - tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); - pj_grp_lock_dec_ref(tsx->grp_lock); - } - - if (status != PJ_SUCCESS) { - PJ_PERROR(2,(tsx->obj_name, status, - "Error sending %s", - pjsip_tx_data_get_info(tdata))); - - /* On error, release transport to force using full transport - * resolution procedure. - */ - tsx_update_transport(tsx, NULL); - - tsx->addr_len = 0; - tsx->res_addr.transport = NULL; - tsx->res_addr.addr_len = 0; - } else { - return PJ_SUCCESS; - } + /* Increment group lock while waiting for send operation to complete, + * to prevent us from being destroyed prematurely. See + * https://github.com/pjsip/pjproject/issues/1646 + */ + pj_grp_lock_add_ref(tsx->grp_lock); + tsx->transport_flag |= TSX_HAS_PENDING_TRANSPORT; + + status = pjsip_transport_send( tsx->transport, tdata, &tsx->addr, + tsx->addr_len, tsx, + &transport_callback); + if (status == PJ_EPENDING) + status = PJ_SUCCESS; + else { + /* Operation completes immediately */ + tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); + pj_grp_lock_dec_ref(tsx->grp_lock); + } + + if (status != PJ_SUCCESS) { + PJ_PERROR(2,(tsx->obj_name, status, + "Error sending %s", + pjsip_tx_data_get_info(tdata))); + + /* On error, release transport to force using full transport + * resolution procedure. + */ + tsx_update_transport(tsx, NULL); + + tsx->addr_len = 0; + tsx->res_addr.transport = NULL; + tsx->res_addr.addr_len = 0; + } else { + return PJ_SUCCESS; + } } /* We are here because we don't have transport, or we failed to send @@ -2281,30 +2280,30 @@ static pj_status_t tsx_send_msg( pjsip_transaction *tsx, * Terminate transaction with transport error failure. */ if (tsx->transport_flag & TSX_HAS_RESOLVED_SERVER) { - - char errmsg[PJ_ERR_MSG_SIZE]; - pj_str_t err; + + char errmsg[PJ_ERR_MSG_SIZE]; + pj_str_t err; - if (status == PJ_SUCCESS) { - pj_assert(!"Unexpected status!"); - status = PJ_EUNKNOWN; - } + if (status == PJ_SUCCESS) { + pj_assert(!"Unexpected status!"); + status = PJ_EUNKNOWN; + } - /* We have resolved the server!. - * Treat this as permanent transport error. - */ - err = pj_strerror(status, errmsg, sizeof(errmsg)); + /* We have resolved the server!. + * Treat this as permanent transport error. + */ + err = pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(2,(tsx->obj_name, - "Transport error, terminating transaction. " - "Err=%d (%s)", - status, errmsg)); + PJ_LOG(2,(tsx->obj_name, + "Transport error, terminating transaction. " + "Err=%d (%s)", + status, errmsg)); - tsx_set_status_code(tsx, PJSIP_SC_TSX_TRANSPORT_ERROR, &err); - tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, - PJSIP_EVENT_TRANSPORT_ERROR, NULL, 0 ); + tsx_set_status_code(tsx, PJSIP_SC_TSX_TRANSPORT_ERROR, &err); + tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, + PJSIP_EVENT_TRANSPORT_ERROR, NULL, 0 ); - return status; + return status; } /* Must add reference counter because the send request functions @@ -2327,42 +2326,42 @@ static pj_status_t tsx_send_msg( pjsip_transaction *tsx, /* Begin resolving destination etc to send the message. */ if (tdata->msg->type == PJSIP_REQUEST_MSG) { - tsx->transport_flag |= TSX_HAS_PENDING_TRANSPORT; - status = pjsip_endpt_send_request_stateless(tsx->endpt, tdata, tsx, - &send_msg_callback); - if (status == PJ_EPENDING) - status = PJ_SUCCESS; - if (status != PJ_SUCCESS) { - tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); - pj_grp_lock_dec_ref(tsx->grp_lock); - pjsip_tx_data_dec_ref(tdata); - tdata->mod_data[mod_tsx_layer.mod.id] = NULL; - tsx->pending_tx = NULL; - } - - /* Check if transaction is terminated. */ - if (status==PJ_SUCCESS && tsx->state == PJSIP_TSX_STATE_TERMINATED) - status = tsx->transport_err; + tsx->transport_flag |= TSX_HAS_PENDING_TRANSPORT; + status = pjsip_endpt_send_request_stateless(tsx->endpt, tdata, tsx, + &send_msg_callback); + if (status == PJ_EPENDING) + status = PJ_SUCCESS; + if (status != PJ_SUCCESS) { + tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); + pj_grp_lock_dec_ref(tsx->grp_lock); + pjsip_tx_data_dec_ref(tdata); + tdata->mod_data[mod_tsx_layer.mod.id] = NULL; + tsx->pending_tx = NULL; + } + + /* Check if transaction is terminated. */ + if (status==PJ_SUCCESS && tsx->state == PJSIP_TSX_STATE_TERMINATED) + status = tsx->transport_err; } else { - tsx->transport_flag |= TSX_HAS_PENDING_TRANSPORT; - status = pjsip_endpt_send_response( tsx->endpt, &tsx->res_addr, - tdata, tsx, - &send_msg_callback); - if (status == PJ_EPENDING) - status = PJ_SUCCESS; - if (status != PJ_SUCCESS) { - tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); - pj_grp_lock_dec_ref(tsx->grp_lock); - pjsip_tx_data_dec_ref(tdata); - tdata->mod_data[mod_tsx_layer.mod.id] = NULL; - tsx->pending_tx = NULL; - } + tsx->transport_flag |= TSX_HAS_PENDING_TRANSPORT; + status = pjsip_endpt_send_response( tsx->endpt, &tsx->res_addr, + tdata, tsx, + &send_msg_callback); + if (status == PJ_EPENDING) + status = PJ_SUCCESS; + if (status != PJ_SUCCESS) { + tsx->transport_flag &= ~(TSX_HAS_PENDING_TRANSPORT); + pj_grp_lock_dec_ref(tsx->grp_lock); + pjsip_tx_data_dec_ref(tdata); + tdata->mod_data[mod_tsx_layer.mod.id] = NULL; + tsx->pending_tx = NULL; + } - /* Check if transaction is terminated. */ - if (status==PJ_SUCCESS && tsx->state == PJSIP_TSX_STATE_TERMINATED) - status = tsx->transport_err; + /* Check if transaction is terminated. */ + if (status==PJ_SUCCESS && tsx->state == PJSIP_TSX_STATE_TERMINATED) + status = tsx->transport_err; } @@ -2375,14 +2374,14 @@ static pj_status_t tsx_send_msg( pjsip_transaction *tsx, * Manually retransmit the last messagewithout updating the transaction state. */ PJ_DEF(pj_status_t) pjsip_tsx_retransmit_no_state(pjsip_transaction *tsx, - pjsip_tx_data *tdata) + pjsip_tx_data *tdata) { pj_status_t status; pj_grp_lock_acquire(tsx->grp_lock); if (tdata == NULL) { - tdata = tsx->last_tx; - pjsip_tx_data_add_ref(tdata); + tdata = tsx->last_tx; + pjsip_tx_data_add_ref(tdata); } status = tsx_send_msg(tsx, tdata); pj_grp_lock_release(tsx->grp_lock); @@ -2391,7 +2390,7 @@ PJ_DEF(pj_status_t) pjsip_tsx_retransmit_no_state(pjsip_transaction *tsx, * (This is the specification from the .PDF design document). */ if (status == PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); + pjsip_tx_data_dec_ref(tdata); } return status; @@ -2408,40 +2407,40 @@ static void tsx_resched_retransmission( pjsip_transaction *tsx ) pj_assert((tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) == 0); if (tsx->role==PJSIP_ROLE_UAC && tsx->status_code >= 100) - msec_time = pjsip_cfg()->tsx.t2; + msec_time = pjsip_cfg()->tsx.t2; else - msec_time = (1 << (tsx->retransmit_count)) * pjsip_cfg()->tsx.t1; + msec_time = (1 << (tsx->retransmit_count)) * pjsip_cfg()->tsx.t1; if (tsx->role == PJSIP_ROLE_UAC) { - pj_assert(tsx->status_code < 200); - /* Retransmission for non-INVITE transaction caps-off at T2 */ - if (msec_time > pjsip_cfg()->tsx.t2 && - tsx->method.id != PJSIP_INVITE_METHOD) - { - msec_time = pjsip_cfg()->tsx.t2; - } + pj_assert(tsx->status_code < 200); + /* Retransmission for non-INVITE transaction caps-off at T2 */ + if (msec_time > pjsip_cfg()->tsx.t2 && + tsx->method.id != PJSIP_INVITE_METHOD) + { + msec_time = pjsip_cfg()->tsx.t2; + } } else { - /* For UAS, this can be retransmission of 2xx response for INVITE - * or non-100 1xx response. - */ - if (tsx->status_code < 200) { - /* non-100 1xx retransmission is at 60 seconds */ - msec_time = PJSIP_TSX_1XX_RETRANS_DELAY * 1000; - } else { - /* Retransmission of INVITE final response also caps-off at T2 */ - pj_assert(tsx->status_code >= 200); - if (msec_time > pjsip_cfg()->tsx.t2) - msec_time = pjsip_cfg()->tsx.t2; - } + /* For UAS, this can be retransmission of 2xx response for INVITE + * or non-100 1xx response. + */ + if (tsx->status_code < 200) { + /* non-100 1xx retransmission is at 60 seconds */ + msec_time = PJSIP_TSX_1XX_RETRANS_DELAY * 1000; + } else { + /* Retransmission of INVITE final response also caps-off at T2 */ + pj_assert(tsx->status_code >= 200); + if (msec_time > pjsip_cfg()->tsx.t2) + msec_time = pjsip_cfg()->tsx.t2; + } } if (msec_time != 0) { - pj_time_val timeout; + pj_time_val timeout; - timeout.sec = msec_time / 1000; - timeout.msec = msec_time % 1000; - tsx_schedule_timer( tsx, &tsx->retransmit_timer, &timeout, - RETRANSMIT_TIMER); + timeout.sec = msec_time / 1000; + timeout.msec = msec_time % 1000; + tsx_schedule_timer( tsx, &tsx->retransmit_timer, &timeout, + RETRANSMIT_TIMER); } } @@ -2453,22 +2452,22 @@ static pj_status_t tsx_retransmit( pjsip_transaction *tsx, int resched) pj_status_t status; if (resched && pj_timer_entry_running(&tsx->retransmit_timer)) { - /* We've been asked to reschedule but the timer is already rerunning. - * This can only happen in a race condition where, between removing - * this retransmit timer from the heap and actually scheduling it, - * another thread has got in and rescheduled the timer itself. In - * this scenario, the transmission has already happened and so we - * should just quit out immediately, without either resending the - * message or restarting the timer. - */ - return PJ_SUCCESS; + /* We've been asked to reschedule but the timer is already rerunning. + * This can only happen in a race condition where, between removing + * this retransmit timer from the heap and actually scheduling it, + * another thread has got in and rescheduled the timer itself. In + * this scenario, the transmission has already happened and so we + * should just quit out immediately, without either resending the + * message or restarting the timer. + */ + return PJ_SUCCESS; } PJ_ASSERT_RETURN(tsx->last_tx!=NULL, PJ_EBUG); PJ_LOG(5,(tsx->obj_name, "Retransmiting %s, count=%d, restart?=%d", - pjsip_tx_data_get_info(tsx->last_tx), - tsx->retransmit_count, resched)); + pjsip_tx_data_get_info(tsx->last_tx), + tsx->retransmit_count, resched)); ++tsx->retransmit_count; @@ -2476,45 +2475,45 @@ static pj_status_t tsx_retransmit( pjsip_transaction *tsx, int resched) * retransmission timer is not engaged when loop transport is used. */ if (resched) { - pj_assert(tsx->state != PJSIP_TSX_STATE_CONFIRMED); - if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { - tsx->transport_flag |= TSX_HAS_PENDING_RESCHED; - } else { - tsx_resched_retransmission(tsx); - } + pj_assert(tsx->state != PJSIP_TSX_STATE_CONFIRMED); + if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { + tsx->transport_flag |= TSX_HAS_PENDING_RESCHED; + } else { + tsx_resched_retransmission(tsx); + } } status = tsx_send_msg( tsx, tsx->last_tx); if (status != PJ_SUCCESS) { - return status; + return status; } return PJ_SUCCESS; } static void tsx_update_transport( pjsip_transaction *tsx, - pjsip_transport *tp) + pjsip_transport *tp) { pj_assert(tsx); if (tsx->transport) { - if (tsx->tp_st_key) { - pjsip_transport_remove_state_listener(tsx->transport, - tsx->tp_st_key, tsx); - } - pjsip_transport_dec_ref( tsx->transport ); - tsx->transport = NULL; + if (tsx->tp_st_key) { + pjsip_transport_remove_state_listener(tsx->transport, + tsx->tp_st_key, tsx); + } + pjsip_transport_dec_ref( tsx->transport ); + tsx->transport = NULL; } if (tp) { - tsx->transport = tp; - pjsip_transport_add_ref(tp); - pjsip_transport_add_state_listener(tp, &tsx_tp_state_callback, tsx, - &tsx->tp_st_key); - if (tp->is_shutdown || tp->is_destroying) { - pjsip_transport_state_info info; - - pj_bzero(&info, sizeof(info)); + tsx->transport = tp; + pjsip_transport_add_ref(tp); + pjsip_transport_add_state_listener(tp, &tsx_tp_state_callback, tsx, + &tsx->tp_st_key); + if (tp->is_shutdown || tp->is_destroying) { + pjsip_transport_state_info info; + + pj_bzero(&info, sizeof(info)); info.user_data = tsx; info.status = PJSIP_SC_TSX_TRANSPORT_ERROR; tsx_tp_state_callback(tp, PJSIP_TP_STATE_DISCONNECTED, &info); @@ -2534,66 +2533,66 @@ static pj_status_t tsx_on_state_null( pjsip_transaction *tsx, if (tsx->role == PJSIP_ROLE_UAS) { - /* Set state to Trying. */ - pj_assert(event->type == PJSIP_EVENT_RX_MSG && - event->body.rx_msg.rdata->msg_info.msg->type == - PJSIP_REQUEST_MSG); - tsx_set_state( tsx, PJSIP_TSX_STATE_TRYING, PJSIP_EVENT_RX_MSG, - event->body.rx_msg.rdata, 0); + /* Set state to Trying. */ + pj_assert(event->type == PJSIP_EVENT_RX_MSG && + event->body.rx_msg.rdata->msg_info.msg->type == + PJSIP_REQUEST_MSG); + tsx_set_state( tsx, PJSIP_TSX_STATE_TRYING, PJSIP_EVENT_RX_MSG, + event->body.rx_msg.rdata, 0); } else { - pjsip_tx_data *tdata; - - /* Must be transmit event. - * You may got this assertion when using loop transport with delay - * set to zero. That would cause on_rx_response() callback to be - * called before tsx_send_msg() has completed. - */ - PJ_ASSERT_RETURN(event->type == PJSIP_EVENT_TX_MSG, PJ_EBUG); - - /* Get the txdata */ - tdata = event->body.tx_msg.tdata; - - /* Save the message for retransmission. */ - if (tsx->last_tx && tsx->last_tx != tdata) { - pjsip_tx_data_dec_ref(tsx->last_tx); - tsx->last_tx = NULL; - } - if (tsx->last_tx != tdata) { - tsx->last_tx = tdata; - pjsip_tx_data_add_ref(tdata); - } - - /* Send the message. */ + pjsip_tx_data *tdata; + + /* Must be transmit event. + * You may got this assertion when using loop transport with delay + * set to zero. That would cause on_rx_response() callback to be + * called before tsx_send_msg() has completed. + */ + PJ_ASSERT_RETURN(event->type == PJSIP_EVENT_TX_MSG, PJ_EBUG); + + /* Get the txdata */ + tdata = event->body.tx_msg.tdata; + + /* Save the message for retransmission. */ + if (tsx->last_tx && tsx->last_tx != tdata) { + pjsip_tx_data_dec_ref(tsx->last_tx); + tsx->last_tx = NULL; + } + if (tsx->last_tx != tdata) { + tsx->last_tx = tdata; + pjsip_tx_data_add_ref(tdata); + } + + /* Send the message. */ status = tsx_send_msg( tsx, tdata); - if (status != PJ_SUCCESS) { - return status; - } - - /* Start Timer B (or called timer F for non-INVITE) for transaction - * timeout. - */ - lock_timer(tsx); - tsx_cancel_timer( tsx, &tsx->timeout_timer ); - tsx_schedule_timer( tsx, &tsx->timeout_timer, &timeout_timer_val, - TIMEOUT_TIMER); - unlock_timer(tsx); - - /* Start Timer A (or timer E) for retransmission only if unreliable - * transport is being used. - */ - if (!tsx->is_reliable) { - tsx->retransmit_count = 0; - if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { - tsx->transport_flag |= TSX_HAS_PENDING_RESCHED; - } else { - tsx_schedule_timer(tsx, &tsx->retransmit_timer, - &t1_timer_val, RETRANSMIT_TIMER); - } - } - - /* Move state. */ - tsx_set_state( tsx, PJSIP_TSX_STATE_CALLING, + if (status != PJ_SUCCESS) { + return status; + } + + /* Start Timer B (or called timer F for non-INVITE) for transaction + * timeout. + */ + lock_timer(tsx); + tsx_cancel_timer( tsx, &tsx->timeout_timer ); + tsx_schedule_timer( tsx, &tsx->timeout_timer, &timeout_timer_val, + TIMEOUT_TIMER); + unlock_timer(tsx); + + /* Start Timer A (or timer E) for retransmission only if unreliable + * transport is being used. + */ + if (!tsx->is_reliable) { + tsx->retransmit_count = 0; + if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { + tsx->transport_flag |= TSX_HAS_PENDING_RESCHED; + } else { + tsx_schedule_timer(tsx, &tsx->retransmit_timer, + &t1_timer_val, RETRANSMIT_TIMER); + } + } + + /* Move state. */ + tsx_set_state( tsx, PJSIP_TSX_STATE_CALLING, PJSIP_EVENT_TX_MSG, tdata, 0); } @@ -2606,112 +2605,112 @@ static pj_status_t tsx_on_state_null( pjsip_transaction *tsx, * is received. */ static pj_status_t tsx_on_state_calling( pjsip_transaction *tsx, - pjsip_event *event ) + pjsip_event *event ) { pj_assert(tsx->state == PJSIP_TSX_STATE_CALLING); pj_assert(tsx->role == PJSIP_ROLE_UAC); if (event->type == PJSIP_EVENT_TIMER && - event->body.timer.entry == &tsx->retransmit_timer) + event->body.timer.entry == &tsx->retransmit_timer) { pj_status_t status; - /* Retransmit the request. */ + /* Retransmit the request. */ status = tsx_retransmit( tsx, 1 ); - if (status != PJ_SUCCESS) { - return status; - } + if (status != PJ_SUCCESS) { + return status; + } } else if (event->type == PJSIP_EVENT_TIMER && - event->body.timer.entry == &tsx->timeout_timer) + event->body.timer.entry == &tsx->timeout_timer) { - /* Cancel retransmission timer. */ - tsx_cancel_timer(tsx, &tsx->retransmit_timer); + /* Cancel retransmission timer. */ + tsx_cancel_timer(tsx, &tsx->retransmit_timer); - tsx->transport_flag &= ~(TSX_HAS_PENDING_RESCHED); + tsx->transport_flag &= ~(TSX_HAS_PENDING_RESCHED); - /* Set status code */ - tsx_set_status_code(tsx, PJSIP_SC_TSX_TIMEOUT, NULL); + /* Set status code */ + tsx_set_status_code(tsx, PJSIP_SC_TSX_TIMEOUT, NULL); - /* Inform TU. */ - tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, + /* Inform TU. */ + tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, PJSIP_EVENT_TIMER, &tsx->timeout_timer, 0); - /* Transaction is destroyed */ - //return PJSIP_ETSXDESTROYED; + /* Transaction is destroyed */ + //return PJSIP_ETSXDESTROYED; } else if (event->type == PJSIP_EVENT_RX_MSG) { - pjsip_msg *msg; - int code; - - /* Get message instance */ - msg = event->body.rx_msg.rdata->msg_info.msg; - - /* Better be a response message. */ - if (msg->type != PJSIP_RESPONSE_MSG) - return PJSIP_ENOTRESPONSEMSG; - - code = msg->line.status.code; - - /* If the response is final, cancel both retransmission and timeout - * timer. - */ - if (code >= 200) { - tsx_cancel_timer(tsx, &tsx->retransmit_timer); - - if (tsx->timeout_timer.id != 0) { - lock_timer(tsx); - tsx_cancel_timer(tsx, &tsx->timeout_timer); - unlock_timer(tsx); - } - - } else { - /* Cancel retransmit timer (for non-INVITE transaction, the - * retransmit timer will be rescheduled at T2. - */ - tsx_cancel_timer(tsx, &tsx->retransmit_timer); - - /* For provisional response, only cancel retransmit when this - * is an INVITE transaction. For non-INVITE, section 17.1.2.1 - * of RFC 3261 says that: - * - retransmit timer is set to T2 - * - timeout timer F is not deleted. - */ - if (tsx->method.id == PJSIP_INVITE_METHOD) { - - /* Cancel timeout timer */ - lock_timer(tsx); - tsx_cancel_timer(tsx, &tsx->timeout_timer); - unlock_timer(tsx); - - } else { - if (!tsx->is_reliable) { - tsx_schedule_timer(tsx, &tsx->retransmit_timer, - &t2_timer_val, RETRANSMIT_TIMER); - } - } - } - - tsx->transport_flag &= ~(TSX_HAS_PENDING_RESCHED); - - - /* Discard retransmission message if it is not INVITE. - * The INVITE tdata is needed in case we have to generate ACK for - * the final response. - */ - /* Keep last_tx for authorization. */ - //blp: always keep last_tx until transaction is destroyed - //code = msg->line.status.code; - //if (tsx->method.id != PJSIP_INVITE_METHOD && code!=401 && code!=407) { - // pjsip_tx_data_dec_ref(tsx->last_tx); - // tsx->last_tx = NULL; - //} - - /* Processing is similar to state Proceeding. */ - tsx_on_state_proceeding_uac( tsx, event); + pjsip_msg *msg; + int code; + + /* Get message instance */ + msg = event->body.rx_msg.rdata->msg_info.msg; + + /* Better be a response message. */ + if (msg->type != PJSIP_RESPONSE_MSG) + return PJSIP_ENOTRESPONSEMSG; + + code = msg->line.status.code; + + /* If the response is final, cancel both retransmission and timeout + * timer. + */ + if (code >= 200) { + tsx_cancel_timer(tsx, &tsx->retransmit_timer); + + if (tsx->timeout_timer.id != 0) { + lock_timer(tsx); + tsx_cancel_timer(tsx, &tsx->timeout_timer); + unlock_timer(tsx); + } + + } else { + /* Cancel retransmit timer (for non-INVITE transaction, the + * retransmit timer will be rescheduled at T2. + */ + tsx_cancel_timer(tsx, &tsx->retransmit_timer); + + /* For provisional response, only cancel retransmit when this + * is an INVITE transaction. For non-INVITE, section 17.1.2.1 + * of RFC 3261 says that: + * - retransmit timer is set to T2 + * - timeout timer F is not deleted. + */ + if (tsx->method.id == PJSIP_INVITE_METHOD) { + + /* Cancel timeout timer */ + lock_timer(tsx); + tsx_cancel_timer(tsx, &tsx->timeout_timer); + unlock_timer(tsx); + + } else { + if (!tsx->is_reliable) { + tsx_schedule_timer(tsx, &tsx->retransmit_timer, + &t2_timer_val, RETRANSMIT_TIMER); + } + } + } + + tsx->transport_flag &= ~(TSX_HAS_PENDING_RESCHED); + + + /* Discard retransmission message if it is not INVITE. + * The INVITE tdata is needed in case we have to generate ACK for + * the final response. + */ + /* Keep last_tx for authorization. */ + //blp: always keep last_tx until transaction is destroyed + //code = msg->line.status.code; + //if (tsx->method.id != PJSIP_INVITE_METHOD && code!=401 && code!=407) { + // pjsip_tx_data_dec_ref(tsx->last_tx); + // tsx->last_tx = NULL; + //} + + /* Processing is similar to state Proceeding. */ + tsx_on_state_proceeding_uac( tsx, event); } else { - pj_assert(!"Unexpected event"); + pj_assert(!"Unexpected event"); return PJ_EBUG; } @@ -2723,7 +2722,7 @@ static pj_status_t tsx_on_state_calling( pjsip_transaction *tsx, * State Trying is for UAS after it received request but before any responses * is sent. * Note: this is different than RFC3261, which can use Trying state for - * non-INVITE client transaction (bug in RFC?). + * non-INVITE client transaction (bug in RFC?). */ static pj_status_t tsx_on_state_trying( pjsip_transaction *tsx, pjsip_event *event) @@ -2742,7 +2741,7 @@ static pj_status_t tsx_on_state_trying( pjsip_transaction *tsx, * response because we haven't sent any!). */ if (event->type != PJSIP_EVENT_TX_MSG) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* The rest of the processing of the event is exactly the same as in @@ -2753,7 +2752,7 @@ static pj_status_t tsx_on_state_trying( pjsip_transaction *tsx, /* Inform the TU of the state transision if state is still State_Trying */ if (status==PJ_SUCCESS && tsx->state == PJSIP_TSX_STATE_TRYING) { - tsx_set_state( tsx, PJSIP_TSX_STATE_PROCEEDING, + tsx_set_state( tsx, PJSIP_TSX_STATE_PROCEEDING, PJSIP_EVENT_TX_MSG, event->body.tx_msg.tdata, 0); } @@ -2770,7 +2769,7 @@ static pj_status_t tsx_on_state_proceeding_uas( pjsip_transaction *tsx, pjsip_event *event) { pj_assert(tsx->state == PJSIP_TSX_STATE_PROCEEDING || - tsx->state == PJSIP_TSX_STATE_TRYING); + tsx->state == PJSIP_TSX_STATE_TRYING); /* This state is only for UAS. */ pj_assert(tsx->role == PJSIP_ROLE_UAS); @@ -2780,252 +2779,252 @@ static pj_status_t tsx_on_state_proceeding_uas( pjsip_transaction *tsx, pj_status_t status; - /* Must have last response sent. */ - PJ_ASSERT_RETURN(tsx->last_tx != NULL, PJ_EBUG); - - /* Send last response */ - if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { - tsx->transport_flag |= TSX_HAS_PENDING_SEND; - } else { - status = tsx_send_msg(tsx, tsx->last_tx); - if (status != PJ_SUCCESS) - return status; - } - + /* Must have last response sent. */ + PJ_ASSERT_RETURN(tsx->last_tx != NULL, PJ_EBUG); + + /* Send last response */ + if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { + tsx->transport_flag |= TSX_HAS_PENDING_SEND; + } else { + status = tsx_send_msg(tsx, tsx->last_tx); + if (status != PJ_SUCCESS) + return status; + } + } else if (event->type == PJSIP_EVENT_TX_MSG ) { - pjsip_tx_data *tdata = event->body.tx_msg.tdata; + pjsip_tx_data *tdata = event->body.tx_msg.tdata; pj_status_t status; - /* The TU sends response message to the request. Save this message so - * that we can retransmit the last response in case we receive request - * retransmission. - */ - pjsip_msg *msg = tdata->msg; - - /* This can only be a response message. */ - PJ_ASSERT_RETURN(msg->type==PJSIP_RESPONSE_MSG, PJSIP_ENOTRESPONSEMSG); - - /* Update last status */ - tsx_set_status_code(tsx, msg->line.status.code, - &msg->line.status.reason); - - /* Discard the saved last response (it will be updated later as - * necessary). - */ - if (tsx->last_tx && tsx->last_tx != tdata) { - pjsip_tx_data_dec_ref( tsx->last_tx ); - tsx->last_tx = NULL; - } + /* The TU sends response message to the request. Save this message so + * that we can retransmit the last response in case we receive request + * retransmission. + */ + pjsip_msg *msg = tdata->msg; + + /* This can only be a response message. */ + PJ_ASSERT_RETURN(msg->type==PJSIP_RESPONSE_MSG, PJSIP_ENOTRESPONSEMSG); + + /* Update last status */ + tsx_set_status_code(tsx, msg->line.status.code, + &msg->line.status.reason); + + /* Discard the saved last response (it will be updated later as + * necessary). + */ + if (tsx->last_tx && tsx->last_tx != tdata) { + pjsip_tx_data_dec_ref( tsx->last_tx ); + tsx->last_tx = NULL; + } - /* Send the message. */ + /* Send the message. */ status = tsx_send_msg(tsx, tdata); - if (status != PJ_SUCCESS) { - return status; - } + if (status != PJ_SUCCESS) { + return status; + } - // Update To tag header for RFC2543 transaction. - // TODO: + // Update To tag header for RFC2543 transaction. + // TODO: - /* Update transaction state */ - if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 100)) { + /* Update transaction state */ + if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 100)) { - if (tsx->last_tx != tdata) { - tsx->last_tx = tdata; - pjsip_tx_data_add_ref( tdata ); - } + if (tsx->last_tx != tdata) { + tsx->last_tx = tdata; + pjsip_tx_data_add_ref( tdata ); + } - tsx_set_state( tsx, PJSIP_TSX_STATE_PROCEEDING, + tsx_set_state( tsx, PJSIP_TSX_STATE_PROCEEDING, PJSIP_EVENT_TX_MSG, tdata, 0 ); - /* Retransmit provisional response every 1 minute if this is - * an INVITE provisional response greater than 100. - */ - if (PJSIP_TSX_1XX_RETRANS_DELAY > 0 && - tsx->method.id==PJSIP_INVITE_METHOD && tsx->status_code>100) - { + /* Retransmit provisional response every 1 minute if this is + * an INVITE provisional response greater than 100. + */ + if (PJSIP_TSX_1XX_RETRANS_DELAY > 0 && + tsx->method.id==PJSIP_INVITE_METHOD && tsx->status_code>100) + { - /* Stop 1xx retransmission timer, if any */ - tsx_cancel_timer(tsx, &tsx->retransmit_timer); + /* Stop 1xx retransmission timer, if any */ + tsx_cancel_timer(tsx, &tsx->retransmit_timer); - /* Schedule retransmission */ - tsx->retransmit_count = 0; - if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { - tsx->transport_flag |= TSX_HAS_PENDING_RESCHED; - } else { - pj_time_val delay = {PJSIP_TSX_1XX_RETRANS_DELAY, 0}; - tsx_schedule_timer( tsx, &tsx->retransmit_timer, &delay, - RETRANSMIT_TIMER); - } - } + /* Schedule retransmission */ + tsx->retransmit_count = 0; + if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { + tsx->transport_flag |= TSX_HAS_PENDING_RESCHED; + } else { + pj_time_val delay = {PJSIP_TSX_1XX_RETRANS_DELAY, 0}; + tsx_schedule_timer( tsx, &tsx->retransmit_timer, &delay, + RETRANSMIT_TIMER); + } + } - } else if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 200)) { + } else if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 200)) { - /* Stop 1xx retransmission timer, if any */ - tsx_cancel_timer(tsx, &tsx->retransmit_timer); + /* Stop 1xx retransmission timer, if any */ + tsx_cancel_timer(tsx, &tsx->retransmit_timer); - if (tsx->method.id == PJSIP_INVITE_METHOD && tsx->handle_200resp==0) { + if (tsx->method.id == PJSIP_INVITE_METHOD && tsx->handle_200resp==0) { - /* 2xx class message is not saved, because retransmission + /* 2xx class message is not saved, because retransmission * is handled by TU. - */ - tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, + */ + tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, PJSIP_EVENT_TX_MSG, tdata, 0 ); - /* Transaction is destroyed. */ - //return PJSIP_ETSXDESTROYED; - - } else { - pj_time_val timeout; - - if (tsx->method.id == PJSIP_INVITE_METHOD) { - tsx->retransmit_count = 0; - if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { - tsx->transport_flag |= TSX_HAS_PENDING_RESCHED; - } else { - tsx_schedule_timer( tsx, &tsx->retransmit_timer, - &t1_timer_val, RETRANSMIT_TIMER); - } - } - - /* Save last response sent for retransmission when request - * retransmission is received. - */ - if (tsx->last_tx != tdata) { - tsx->last_tx = tdata; - pjsip_tx_data_add_ref(tdata); - } - - /* Setup timeout timer: */ - - if (tsx->method.id == PJSIP_INVITE_METHOD) { - - /* Start Timer H at 64*T1 for INVITE server transaction, - * regardless of transport. - */ - timeout = timeout_timer_val; - - } else if (!tsx->is_reliable) { - - /* For non-INVITE, start timer J at 64*T1 for unreliable - * transport. - */ - timeout = timeout_timer_val; - - } else { - - /* Transaction terminates immediately for non-INVITE when - * reliable transport is used. - */ - timeout.sec = timeout.msec = 0; - } - - lock_timer(tsx); - tsx_cancel_timer(tsx, &tsx->timeout_timer); - tsx_schedule_timer( tsx, &tsx->timeout_timer, + /* Transaction is destroyed. */ + //return PJSIP_ETSXDESTROYED; + + } else { + pj_time_val timeout; + + if (tsx->method.id == PJSIP_INVITE_METHOD) { + tsx->retransmit_count = 0; + if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { + tsx->transport_flag |= TSX_HAS_PENDING_RESCHED; + } else { + tsx_schedule_timer( tsx, &tsx->retransmit_timer, + &t1_timer_val, RETRANSMIT_TIMER); + } + } + + /* Save last response sent for retransmission when request + * retransmission is received. + */ + if (tsx->last_tx != tdata) { + tsx->last_tx = tdata; + pjsip_tx_data_add_ref(tdata); + } + + /* Setup timeout timer: */ + + if (tsx->method.id == PJSIP_INVITE_METHOD) { + + /* Start Timer H at 64*T1 for INVITE server transaction, + * regardless of transport. + */ + timeout = timeout_timer_val; + + } else if (!tsx->is_reliable) { + + /* For non-INVITE, start timer J at 64*T1 for unreliable + * transport. + */ + timeout = timeout_timer_val; + + } else { + + /* Transaction terminates immediately for non-INVITE when + * reliable transport is used. + */ + timeout.sec = timeout.msec = 0; + } + + lock_timer(tsx); + tsx_cancel_timer(tsx, &tsx->timeout_timer); + tsx_schedule_timer( tsx, &tsx->timeout_timer, &timeout, TIMEOUT_TIMER); - unlock_timer(tsx); + unlock_timer(tsx); - /* Set state to "Completed" */ - tsx_set_state( tsx, PJSIP_TSX_STATE_COMPLETED, + /* Set state to "Completed" */ + tsx_set_state( tsx, PJSIP_TSX_STATE_COMPLETED, PJSIP_EVENT_TX_MSG, tdata, 0 ); - } + } - } else if (tsx->status_code >= 300) { + } else if (tsx->status_code >= 300) { - /* Stop 1xx retransmission timer, if any */ - tsx_cancel_timer(tsx, &tsx->retransmit_timer); + /* Stop 1xx retransmission timer, if any */ + tsx_cancel_timer(tsx, &tsx->retransmit_timer); - /* 3xx-6xx class message causes transaction to move to + /* 3xx-6xx class message causes transaction to move to * "Completed" state. */ - if (tsx->last_tx != tdata) { - tsx->last_tx = tdata; - pjsip_tx_data_add_ref( tdata ); - } - - /* For INVITE, start timer H for transaction termination - * regardless whether transport is reliable or not. - * For non-INVITE, start timer J with the value of 64*T1 for - * non-reliable transports, and zero for reliable transports. - */ - lock_timer(tsx); - tsx_cancel_timer(tsx, &tsx->timeout_timer); - if (tsx->method.id == PJSIP_INVITE_METHOD) { - /* Start timer H for INVITE */ - tsx_schedule_timer(tsx, &tsx->timeout_timer, - &timeout_timer_val, TIMEOUT_TIMER); - } else if (!tsx->is_reliable) { - /* Start timer J on 64*T1 seconds for non-INVITE */ - tsx_schedule_timer(tsx, &tsx->timeout_timer, - &timeout_timer_val, TIMEOUT_TIMER); - } else { - /* Start timer J on zero seconds for non-INVITE */ - pj_time_val zero_time = { 0, 0 }; - tsx_schedule_timer(tsx, &tsx->timeout_timer, - &zero_time, TIMEOUT_TIMER); - } - unlock_timer(tsx); - - /* For INVITE, if unreliable transport is used, retransmission - * timer G will be scheduled (retransmission). - */ - if (!tsx->is_reliable) { - pjsip_cseq_hdr *cseq = (pjsip_cseq_hdr*) - pjsip_msg_find_hdr( msg, PJSIP_H_CSEQ, + if (tsx->last_tx != tdata) { + tsx->last_tx = tdata; + pjsip_tx_data_add_ref( tdata ); + } + + /* For INVITE, start timer H for transaction termination + * regardless whether transport is reliable or not. + * For non-INVITE, start timer J with the value of 64*T1 for + * non-reliable transports, and zero for reliable transports. + */ + lock_timer(tsx); + tsx_cancel_timer(tsx, &tsx->timeout_timer); + if (tsx->method.id == PJSIP_INVITE_METHOD) { + /* Start timer H for INVITE */ + tsx_schedule_timer(tsx, &tsx->timeout_timer, + &timeout_timer_val, TIMEOUT_TIMER); + } else if (!tsx->is_reliable) { + /* Start timer J on 64*T1 seconds for non-INVITE */ + tsx_schedule_timer(tsx, &tsx->timeout_timer, + &timeout_timer_val, TIMEOUT_TIMER); + } else { + /* Start timer J on zero seconds for non-INVITE */ + pj_time_val zero_time = { 0, 0 }; + tsx_schedule_timer(tsx, &tsx->timeout_timer, + &zero_time, TIMEOUT_TIMER); + } + unlock_timer(tsx); + + /* For INVITE, if unreliable transport is used, retransmission + * timer G will be scheduled (retransmission). + */ + if (!tsx->is_reliable) { + pjsip_cseq_hdr *cseq = (pjsip_cseq_hdr*) + pjsip_msg_find_hdr( msg, PJSIP_H_CSEQ, NULL); - if (cseq->method.id == PJSIP_INVITE_METHOD) { - tsx->retransmit_count = 0; - if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { - tsx->transport_flag |= TSX_HAS_PENDING_RESCHED; - } else { - tsx_schedule_timer(tsx, &tsx->retransmit_timer, - &t1_timer_val, RETRANSMIT_TIMER); - } - } - } - - /* Inform TU */ - tsx_set_state( tsx, PJSIP_TSX_STATE_COMPLETED, + if (cseq->method.id == PJSIP_INVITE_METHOD) { + tsx->retransmit_count = 0; + if (tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) { + tsx->transport_flag |= TSX_HAS_PENDING_RESCHED; + } else { + tsx_schedule_timer(tsx, &tsx->retransmit_timer, + &t1_timer_val, RETRANSMIT_TIMER); + } + } + } + + /* Inform TU */ + tsx_set_state( tsx, PJSIP_TSX_STATE_COMPLETED, PJSIP_EVENT_TX_MSG, tdata, 0 ); - } else { - pj_assert(0); - } + } else { + pj_assert(0); + } } else if (event->type == PJSIP_EVENT_TIMER && - event->body.timer.entry == &tsx->retransmit_timer) { + event->body.timer.entry == &tsx->retransmit_timer) { - /* Retransmission timer elapsed. */ + /* Retransmission timer elapsed. */ pj_status_t status; - /* Must not be triggered while transport is pending. */ - pj_assert((tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) == 0); + /* Must not be triggered while transport is pending. */ + pj_assert((tsx->transport_flag & TSX_HAS_PENDING_TRANSPORT) == 0); - /* Must have last response to retransmit. */ - pj_assert(tsx->last_tx != NULL); + /* Must have last response to retransmit. */ + pj_assert(tsx->last_tx != NULL); - /* Retransmit the last response. */ + /* Retransmit the last response. */ status = tsx_retransmit( tsx, 1 ); - if (status != PJ_SUCCESS) { - return status; - } + if (status != PJ_SUCCESS) { + return status; + } } else if (event->type == PJSIP_EVENT_TIMER && - event->body.timer.entry == &tsx->timeout_timer) { + event->body.timer.entry == &tsx->timeout_timer) { - /* Timeout timer. should not happen? */ - pj_assert(!"Should not happen(?)"); + /* Timeout timer. should not happen? */ + pj_assert(!"Should not happen(?)"); - tsx_set_status_code(tsx, PJSIP_SC_TSX_TIMEOUT, NULL); + tsx_set_status_code(tsx, PJSIP_SC_TSX_TIMEOUT, NULL); - tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, + tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, PJSIP_EVENT_TIMER, &tsx->timeout_timer, 0); - return PJ_EBUG; + return PJ_EBUG; } else { - pj_assert(!"Unexpected event"); + pj_assert(!"Unexpected event"); return PJ_EBUG; } @@ -3043,229 +3042,229 @@ static pj_status_t tsx_on_state_proceeding_uac(pjsip_transaction *tsx, { pj_assert(tsx->state == PJSIP_TSX_STATE_PROCEEDING || - tsx->state == PJSIP_TSX_STATE_CALLING); + tsx->state == PJSIP_TSX_STATE_CALLING); if (event->type != PJSIP_EVENT_TIMER) { - pjsip_msg *msg; - - /* Must be incoming response, because we should not retransmit - * request once response has been received. - */ - pj_assert(event->type == PJSIP_EVENT_RX_MSG); - if (event->type != PJSIP_EVENT_RX_MSG) { - return PJ_EINVALIDOP; - } + pjsip_msg *msg; + + /* Must be incoming response, because we should not retransmit + * request once response has been received. + */ + pj_assert(event->type == PJSIP_EVENT_RX_MSG); + if (event->type != PJSIP_EVENT_RX_MSG) { + return PJ_EINVALIDOP; + } - msg = event->body.rx_msg.rdata->msg_info.msg; + msg = event->body.rx_msg.rdata->msg_info.msg; - /* Must be a response message. */ - if (msg->type != PJSIP_RESPONSE_MSG) { - pj_assert(!"Expecting response message!"); - return PJSIP_ENOTRESPONSEMSG; - } + /* Must be a response message. */ + if (msg->type != PJSIP_RESPONSE_MSG) { + pj_assert(!"Expecting response message!"); + return PJSIP_ENOTRESPONSEMSG; + } - tsx_set_status_code(tsx, msg->line.status.code, - &msg->line.status.reason); + tsx_set_status_code(tsx, msg->line.status.code, + &msg->line.status.reason); } else { - if (event->body.timer.entry == &tsx->retransmit_timer) { - /* Retransmit message. */ + if (event->body.timer.entry == &tsx->retransmit_timer) { + /* Retransmit message. */ pj_status_t status; status = tsx_retransmit( tsx, 1 ); - - return status; + + return status; - } else { - tsx_set_status_code(tsx, PJSIP_SC_TSX_TIMEOUT, NULL); - } + } else { + tsx_set_status_code(tsx, PJSIP_SC_TSX_TIMEOUT, NULL); + } } if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 100)) { - /* Inform the message to TU. */ - tsx_set_state( tsx, PJSIP_TSX_STATE_PROCEEDING, + /* Inform the message to TU. */ + tsx_set_state( tsx, PJSIP_TSX_STATE_PROCEEDING, PJSIP_EVENT_RX_MSG, event->body.rx_msg.rdata, 0 ); } else if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code,200)) { - /* Stop timeout timer B/F. */ - lock_timer(tsx); - tsx_cancel_timer( tsx, &tsx->timeout_timer ); - unlock_timer(tsx); + /* Stop timeout timer B/F. */ + lock_timer(tsx); + tsx_cancel_timer( tsx, &tsx->timeout_timer ); + unlock_timer(tsx); - /* For INVITE, the state moves to Terminated state (because ACK is - * handled in TU). For non-INVITE, state moves to Completed. - */ - if (tsx->method.id == PJSIP_INVITE_METHOD) { - tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, + /* For INVITE, the state moves to Terminated state (because ACK is + * handled in TU). For non-INVITE, state moves to Completed. + */ + if (tsx->method.id == PJSIP_INVITE_METHOD) { + tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, PJSIP_EVENT_RX_MSG, event->body.rx_msg.rdata, 0 ); - //return PJSIP_ETSXDESTROYED; - - } else { - pj_time_val timeout; - - /* For unreliable transport, start timer D (for INVITE) or - * timer K for non-INVITE. */ - if (!tsx->is_reliable) { - if (tsx->method.id == PJSIP_INVITE_METHOD) { - timeout = td_timer_val; - } else { - timeout = t4_timer_val; - } - } else { - timeout.sec = timeout.msec = 0; - } - lock_timer(tsx); - tsx_schedule_timer( tsx, &tsx->timeout_timer, - &timeout, TIMEOUT_TIMER); - unlock_timer(tsx); - - /* Cancel retransmission timer */ - tsx_cancel_timer(tsx, &tsx->retransmit_timer); - - /* Move state to Completed, inform TU. */ - tsx_set_state( tsx, PJSIP_TSX_STATE_COMPLETED, + //return PJSIP_ETSXDESTROYED; + + } else { + pj_time_val timeout; + + /* For unreliable transport, start timer D (for INVITE) or + * timer K for non-INVITE. */ + if (!tsx->is_reliable) { + if (tsx->method.id == PJSIP_INVITE_METHOD) { + timeout = td_timer_val; + } else { + timeout = t4_timer_val; + } + } else { + timeout.sec = timeout.msec = 0; + } + lock_timer(tsx); + tsx_schedule_timer( tsx, &tsx->timeout_timer, + &timeout, TIMEOUT_TIMER); + unlock_timer(tsx); + + /* Cancel retransmission timer */ + tsx_cancel_timer(tsx, &tsx->retransmit_timer); + + /* Move state to Completed, inform TU. */ + tsx_set_state( tsx, PJSIP_TSX_STATE_COMPLETED, PJSIP_EVENT_RX_MSG, event->body.rx_msg.rdata, 0 ); - } + } } else if (event->type == PJSIP_EVENT_TIMER && - event->body.timer.entry == &tsx->timeout_timer) { + event->body.timer.entry == &tsx->timeout_timer) { - /* Inform TU. */ - tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, - PJSIP_EVENT_TIMER, &tsx->timeout_timer, 0); + /* Inform TU. */ + tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, + PJSIP_EVENT_TIMER, &tsx->timeout_timer, 0); } else if (tsx->status_code >= 300 && tsx->status_code <= 699) { #if 0 - /* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ - /* - * This is the old code; it's broken for authentication. - */ - pj_time_val timeout; + /* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ + /* + * This is the old code; it's broken for authentication. + */ + pj_time_val timeout; pj_status_t status; - /* Stop timer B. */ - tsx_cancel_timer( tsx, &tsx->timeout_timer ); + /* Stop timer B. */ + tsx_cancel_timer( tsx, &tsx->timeout_timer ); - /* Generate and send ACK for INVITE. */ - if (tsx->method.id == PJSIP_INVITE_METHOD) { - pjsip_tx_data *ack; + /* Generate and send ACK for INVITE. */ + if (tsx->method.id == PJSIP_INVITE_METHOD) { + pjsip_tx_data *ack; - status = pjsip_endpt_create_ack( tsx->endpt, tsx->last_tx, - event->body.rx_msg.rdata, - &ack); - if (status != PJ_SUCCESS) - return status; + status = pjsip_endpt_create_ack( tsx->endpt, tsx->last_tx, + event->body.rx_msg.rdata, + &ack); + if (status != PJ_SUCCESS) + return status; - if (ack != tsx->last_tx) { - pjsip_tx_data_dec_ref(tsx->last_tx); - tsx->last_tx = ack; - } + if (ack != tsx->last_tx) { + pjsip_tx_data_dec_ref(tsx->last_tx); + tsx->last_tx = ack; + } status = tsx_send_msg( tsx, tsx->last_tx); - if (status != PJ_SUCCESS) { - return status; - } - } - - /* Start Timer D with TD/T4 timer if unreliable transport is used. */ - if (!tsx->is_reliable) { - if (tsx->method.id == PJSIP_INVITE_METHOD) { - timeout = td_timer_val; - } else { - timeout = t4_timer_val; - } - } else { - timeout.sec = timeout.msec = 0; - } - tsx_schedule_timer( tsx, &tsx->timeout_timer, &timeout, TIMEOUT_TIMER); - - /* Inform TU. - * blp: You might be tempted to move this notification before - * sending ACK, but I think you shouldn't. Better set-up - * everything before calling tsx_user's callback to avoid - * mess up. - */ - tsx_set_state( tsx, PJSIP_TSX_STATE_COMPLETED, + if (status != PJ_SUCCESS) { + return status; + } + } + + /* Start Timer D with TD/T4 timer if unreliable transport is used. */ + if (!tsx->is_reliable) { + if (tsx->method.id == PJSIP_INVITE_METHOD) { + timeout = td_timer_val; + } else { + timeout = t4_timer_val; + } + } else { + timeout.sec = timeout.msec = 0; + } + tsx_schedule_timer( tsx, &tsx->timeout_timer, &timeout, TIMEOUT_TIMER); + + /* Inform TU. + * blp: You might be tempted to move this notification before + * sending ACK, but I think you shouldn't. Better set-up + * everything before calling tsx_user's callback to avoid + * mess up. + */ + tsx_set_state( tsx, PJSIP_TSX_STATE_COMPLETED, PJSIP_EVENT_RX_MSG, event->body.rx_msg.rdata ); - /* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ + /* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #endif - /* New code, taken from 0.2.9.x branch */ - pj_time_val timeout; - pjsip_tx_data *ack_tdata = NULL; - - /* Cancel retransmission timer */ - tsx_cancel_timer(tsx, &tsx->retransmit_timer); - - /* Stop timer B. */ - lock_timer(tsx); - tsx_cancel_timer( tsx, &tsx->timeout_timer ); - unlock_timer(tsx); - - /* Generate and send ACK (for INVITE) */ - if (tsx->method.id == PJSIP_INVITE_METHOD) { - pj_status_t status; - - status = pjsip_endpt_create_ack( tsx->endpt, tsx->last_tx, - event->body.rx_msg.rdata, - &ack_tdata); - if (status != PJ_SUCCESS) - return status; - - status = tsx_send_msg( tsx, ack_tdata); - if (status != PJ_SUCCESS) - return status; - } - - /* Inform TU. */ - tsx_set_state( tsx, PJSIP_TSX_STATE_COMPLETED, - PJSIP_EVENT_RX_MSG, event->body.rx_msg.rdata, 0); - - /* Generate and send ACK for INVITE. */ - if (tsx->method.id == PJSIP_INVITE_METHOD) { - if (ack_tdata != tsx->last_tx) { - pjsip_tx_data_dec_ref(tsx->last_tx); - tsx->last_tx = ack_tdata; - - /* This is a bug. - tsx_send_msg() does NOT decrement tdata's reference counter, - so if we add the reference counter here, tdata will have - reference counter 2, causing it to leak. - pjsip_tx_data_add_ref(ack_tdata); - */ - } - } - - /* Start Timer D with TD/T4 timer if unreliable transport is used. */ - /* Note: tsx->transport may be NULL! */ - if (!tsx->is_reliable) { - if (tsx->method.id == PJSIP_INVITE_METHOD) { - timeout = td_timer_val; - } else { - timeout = t4_timer_val; - } - } else { - timeout.sec = timeout.msec = 0; - } - lock_timer(tsx); - /* In the short period above timer may have been inserted - * by set_timeout() (by CANCEL). Cancel it if necessary. See: - * https://github.com/pjsip/pjproject/issues/1374 - */ - tsx_cancel_timer( tsx, &tsx->timeout_timer ); - tsx_schedule_timer( tsx, &tsx->timeout_timer, &timeout, - TIMEOUT_TIMER); - unlock_timer(tsx); + /* New code, taken from 0.2.9.x branch */ + pj_time_val timeout; + pjsip_tx_data *ack_tdata = NULL; + + /* Cancel retransmission timer */ + tsx_cancel_timer(tsx, &tsx->retransmit_timer); + + /* Stop timer B. */ + lock_timer(tsx); + tsx_cancel_timer( tsx, &tsx->timeout_timer ); + unlock_timer(tsx); + + /* Generate and send ACK (for INVITE) */ + if (tsx->method.id == PJSIP_INVITE_METHOD) { + pj_status_t status; + + status = pjsip_endpt_create_ack( tsx->endpt, tsx->last_tx, + event->body.rx_msg.rdata, + &ack_tdata); + if (status != PJ_SUCCESS) + return status; + + status = tsx_send_msg( tsx, ack_tdata); + if (status != PJ_SUCCESS) + return status; + } + + /* Inform TU. */ + tsx_set_state( tsx, PJSIP_TSX_STATE_COMPLETED, + PJSIP_EVENT_RX_MSG, event->body.rx_msg.rdata, 0); + + /* Generate and send ACK for INVITE. */ + if (tsx->method.id == PJSIP_INVITE_METHOD) { + if (ack_tdata != tsx->last_tx) { + pjsip_tx_data_dec_ref(tsx->last_tx); + tsx->last_tx = ack_tdata; + + /* This is a bug. + tsx_send_msg() does NOT decrement tdata's reference counter, + so if we add the reference counter here, tdata will have + reference counter 2, causing it to leak. + pjsip_tx_data_add_ref(ack_tdata); + */ + } + } + + /* Start Timer D with TD/T4 timer if unreliable transport is used. */ + /* Note: tsx->transport may be NULL! */ + if (!tsx->is_reliable) { + if (tsx->method.id == PJSIP_INVITE_METHOD) { + timeout = td_timer_val; + } else { + timeout = t4_timer_val; + } + } else { + timeout.sec = timeout.msec = 0; + } + lock_timer(tsx); + /* In the short period above timer may have been inserted + * by set_timeout() (by CANCEL). Cancel it if necessary. See: + * https://github.com/pjsip/pjproject/issues/1374 + */ + tsx_cancel_timer( tsx, &tsx->timeout_timer ); + tsx_schedule_timer( tsx, &tsx->timeout_timer, &timeout, + TIMEOUT_TIMER); + unlock_timer(tsx); } else { - // Shouldn't happen because there's no timer for this state. - pj_assert(!"Unexpected event"); + // Shouldn't happen because there's no timer for this state. + pj_assert(!"Unexpected event"); return PJ_EBUG; } @@ -3282,102 +3281,102 @@ static pj_status_t tsx_on_state_completed_uas( pjsip_transaction *tsx, pj_assert(tsx->state == PJSIP_TSX_STATE_COMPLETED); if (event->type == PJSIP_EVENT_RX_MSG) { - pjsip_msg *msg = event->body.rx_msg.rdata->msg_info.msg; + pjsip_msg *msg = event->body.rx_msg.rdata->msg_info.msg; - /* This must be a request message retransmission. */ - if (msg->type != PJSIP_REQUEST_MSG) - return PJSIP_ENOTREQUESTMSG; + /* This must be a request message retransmission. */ + if (msg->type != PJSIP_REQUEST_MSG) + return PJSIP_ENOTREQUESTMSG; - /* On receive request retransmission, retransmit last response. */ - if (msg->line.req.method.id != PJSIP_ACK_METHOD) { + /* On receive request retransmission, retransmit last response. */ + if (msg->line.req.method.id != PJSIP_ACK_METHOD) { pj_status_t status; status = tsx_retransmit( tsx, 0 ); - if (status != PJ_SUCCESS) { - return status; - } - - } else { - pj_time_val timeout; - - /* Process incoming ACK request. */ - - /* Verify that this is an INVITE transaction */ - if (tsx->method.id != PJSIP_INVITE_METHOD) { - PJ_LOG(2, (tsx->obj_name, - "Received illegal ACK for %.*s transaction", - (int)tsx->method.name.slen, - tsx->method.name.ptr)); - return PJSIP_EINVALIDMETHOD; - } - - /* Cease retransmission. */ - tsx_cancel_timer(tsx, &tsx->retransmit_timer); - - tsx->transport_flag &= ~(TSX_HAS_PENDING_RESCHED); - - /* Reschedule timeout timer. */ - lock_timer(tsx); - tsx_cancel_timer( tsx, &tsx->timeout_timer ); - - /* Timer I is T4 timer for unreliable transports, and - * zero seconds for reliable transports. - */ - if (tsx->is_reliable) { - timeout.sec = 0; - timeout.msec = 0; - } else { - timeout.sec = t4_timer_val.sec; - timeout.msec = t4_timer_val.msec; - } - tsx_schedule_timer( tsx, &tsx->timeout_timer, - &timeout, TIMEOUT_TIMER); - unlock_timer(tsx); - - /* Move state to "Confirmed" */ - tsx_set_state( tsx, PJSIP_TSX_STATE_CONFIRMED, + if (status != PJ_SUCCESS) { + return status; + } + + } else { + pj_time_val timeout; + + /* Process incoming ACK request. */ + + /* Verify that this is an INVITE transaction */ + if (tsx->method.id != PJSIP_INVITE_METHOD) { + PJ_LOG(2, (tsx->obj_name, + "Received illegal ACK for %.*s transaction", + (int)tsx->method.name.slen, + tsx->method.name.ptr)); + return PJSIP_EINVALIDMETHOD; + } + + /* Cease retransmission. */ + tsx_cancel_timer(tsx, &tsx->retransmit_timer); + + tsx->transport_flag &= ~(TSX_HAS_PENDING_RESCHED); + + /* Reschedule timeout timer. */ + lock_timer(tsx); + tsx_cancel_timer( tsx, &tsx->timeout_timer ); + + /* Timer I is T4 timer for unreliable transports, and + * zero seconds for reliable transports. + */ + if (tsx->is_reliable) { + timeout.sec = 0; + timeout.msec = 0; + } else { + timeout.sec = t4_timer_val.sec; + timeout.msec = t4_timer_val.msec; + } + tsx_schedule_timer( tsx, &tsx->timeout_timer, + &timeout, TIMEOUT_TIMER); + unlock_timer(tsx); + + /* Move state to "Confirmed" */ + tsx_set_state( tsx, PJSIP_TSX_STATE_CONFIRMED, PJSIP_EVENT_RX_MSG, event->body.rx_msg.rdata, 0 ); - } + } } else if (event->type == PJSIP_EVENT_TIMER) { - if (event->body.timer.entry == &tsx->retransmit_timer) { - /* Retransmit message. */ + if (event->body.timer.entry == &tsx->retransmit_timer) { + /* Retransmit message. */ pj_status_t status; status = tsx_retransmit( tsx, 1 ); - if (status != PJ_SUCCESS) { - return status; - } + if (status != PJ_SUCCESS) { + return status; + } - } else { - if (tsx->method.id == PJSIP_INVITE_METHOD) { + } else { + if (tsx->method.id == PJSIP_INVITE_METHOD) { - /* For INVITE, this means that ACK was never received. - * Set state to Terminated, and inform TU. - */ + /* For INVITE, this means that ACK was never received. + * Set state to Terminated, and inform TU. + */ - tsx_set_status_code(tsx, PJSIP_SC_TSX_TIMEOUT, NULL); + tsx_set_status_code(tsx, PJSIP_SC_TSX_TIMEOUT, NULL); - tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, + tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, PJSIP_EVENT_TIMER, &tsx->timeout_timer, 0 ); - //return PJSIP_ETSXDESTROYED; + //return PJSIP_ETSXDESTROYED; - } else { - /* Transaction terminated, it can now be deleted. */ - tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, + } else { + /* Transaction terminated, it can now be deleted. */ + tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, PJSIP_EVENT_TIMER, &tsx->timeout_timer, 0 ); - //return PJSIP_ETSXDESTROYED; - } - } + //return PJSIP_ETSXDESTROYED; + } + } } else { - PJ_ASSERT_RETURN(event->type == PJSIP_EVENT_TX_MSG, - PJ_EINVALIDOP); - /* Ignore request to transmit a new message. */ - if (event->body.tx_msg.tdata != tsx->last_tx) - return PJ_EINVALIDOP; + PJ_ASSERT_RETURN(event->type == PJSIP_EVENT_TX_MSG, + PJ_EINVALIDOP); + /* Ignore request to transmit a new message. */ + if (event->body.tx_msg.tdata != tsx->last_tx) + return PJ_EINVALIDOP; } return PJ_SUCCESS; @@ -3393,45 +3392,45 @@ static pj_status_t tsx_on_state_completed_uac( pjsip_transaction *tsx, pj_assert(tsx->state == PJSIP_TSX_STATE_COMPLETED); if (event->type == PJSIP_EVENT_TIMER) { - /* Ignore stray retransmit event - * https://github.com/pjsip/pjproject/issues/1766 - */ - if (event->body.timer.entry != &tsx->timeout_timer) - return PJ_SUCCESS; - - /* Move to Terminated state. */ - tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, + /* Ignore stray retransmit event + * https://github.com/pjsip/pjproject/issues/1766 + */ + if (event->body.timer.entry != &tsx->timeout_timer) + return PJ_SUCCESS; + + /* Move to Terminated state. */ + tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, PJSIP_EVENT_TIMER, event->body.timer.entry, 0 ); - /* Transaction has been destroyed. */ - //return PJSIP_ETSXDESTROYED; + /* Transaction has been destroyed. */ + //return PJSIP_ETSXDESTROYED; } else if (event->type == PJSIP_EVENT_RX_MSG) { - if (tsx->method.id == PJSIP_INVITE_METHOD) { - /* On received of final response retransmission, retransmit the ACK. - * TU doesn't need to be informed. - */ - pjsip_msg *msg = event->body.rx_msg.rdata->msg_info.msg; - pj_assert(msg->type == PJSIP_RESPONSE_MSG); - if (msg->type==PJSIP_RESPONSE_MSG && - msg->line.status.code >= 200) - { + if (tsx->method.id == PJSIP_INVITE_METHOD) { + /* On received of final response retransmission, retransmit the ACK. + * TU doesn't need to be informed. + */ + pjsip_msg *msg = event->body.rx_msg.rdata->msg_info.msg; + pj_assert(msg->type == PJSIP_RESPONSE_MSG); + if (msg->type==PJSIP_RESPONSE_MSG && + msg->line.status.code >= 200) + { pj_status_t status; status = tsx_retransmit( tsx, 0 ); - if (status != PJ_SUCCESS) { - return status; - } - } else { - /* Very late retransmission of privisional response. */ - pj_assert( msg->type == PJSIP_RESPONSE_MSG ); - } - } else { - /* Just drop the response. */ - } + if (status != PJ_SUCCESS) { + return status; + } + } else { + /* Very late retransmission of privisional response. */ + pj_assert( msg->type == PJSIP_RESPONSE_MSG ); + } + } else { + /* Just drop the response. */ + } } else { - pj_assert(!"Unexpected event"); + pj_assert(!"Unexpected event"); return PJ_EINVALIDOP; } @@ -3454,35 +3453,35 @@ static pj_status_t tsx_on_state_confirmed( pjsip_transaction *tsx, /* Absorb any ACK received. */ if (event->type == PJSIP_EVENT_RX_MSG) { - pjsip_msg *msg = event->body.rx_msg.rdata->msg_info.msg; + pjsip_msg *msg = event->body.rx_msg.rdata->msg_info.msg; - /* Only expecting request message. */ - if (msg->type != PJSIP_REQUEST_MSG) - return PJSIP_ENOTREQUESTMSG; + /* Only expecting request message. */ + if (msg->type != PJSIP_REQUEST_MSG) + return PJSIP_ENOTREQUESTMSG; - /* Must be an ACK request or a late INVITE retransmission. */ - pj_assert(msg->line.req.method.id == PJSIP_ACK_METHOD || - msg->line.req.method.id == PJSIP_INVITE_METHOD); + /* Must be an ACK request or a late INVITE retransmission. */ + pj_assert(msg->line.req.method.id == PJSIP_ACK_METHOD || + msg->line.req.method.id == PJSIP_INVITE_METHOD); } else if (event->type == PJSIP_EVENT_TIMER) { - /* Ignore overlapped retransmit timer. - * https://github.com/pjsip/pjproject/issues/1746 - */ - if (event->body.timer.entry == &tsx->retransmit_timer) { - /* Ignore */ - } else { - /* Must be from timeout_timer_. */ - pj_assert(event->body.timer.entry == &tsx->timeout_timer); - - /* Move to Terminated state. */ - tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, - PJSIP_EVENT_TIMER, &tsx->timeout_timer, 0 ); - - /* Transaction has been destroyed. */ - //return PJSIP_ETSXDESTROYED; - } + /* Ignore overlapped retransmit timer. + * https://github.com/pjsip/pjproject/issues/1746 + */ + if (event->body.timer.entry == &tsx->retransmit_timer) { + /* Ignore */ + } else { + /* Must be from timeout_timer_. */ + pj_assert(event->body.timer.entry == &tsx->timeout_timer); + + /* Move to Terminated state. */ + tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, + PJSIP_EVENT_TIMER, &tsx->timeout_timer, 0 ); + + /* Transaction has been destroyed. */ + //return PJSIP_ETSXDESTROYED; + } } else { - pj_assert(!"Unexpected event"); + pj_assert(!"Unexpected event"); return PJ_EBUG; } @@ -3502,7 +3501,7 @@ static pj_status_t tsx_on_state_terminated( pjsip_transaction *tsx, * events may genuinely arrive at this state. */ if (event->type != PJSIP_EVENT_TIMER) { - return PJ_EIGNORED; + return PJ_EIGNORED; } /* Destroy this transaction */ diff --git a/pjsip/src/pjsip/sip_transport.c b/pjsip/src/pjsip/sip_transport.c index 8b3beb74a5..4f483faa1b 100644 --- a/pjsip/src/pjsip/sip_transport.c +++ b/pjsip/src/pjsip/sip_transport.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -40,14 +39,14 @@ #define THIS_FILE "sip_transport.c" #if 0 -# define TRACE_(x) PJ_LOG(5,x) +# define TRACE_(x) PJ_LOG(5,x) static const char *addr_string(const pj_sockaddr_t *addr) { static char str[PJ_INET6_ADDRSTRLEN]; pj_inet_ntop(((const pj_sockaddr*)addr)->addr.sa_family, - pj_sockaddr_get_addr(addr), - str, sizeof(str)); + pj_sockaddr_get_addr(addr), + str, sizeof(str)); return str; } static const char* print_tpsel_info(const pjsip_tpselector *sel) @@ -55,17 +54,17 @@ static const char* print_tpsel_info(const pjsip_tpselector *sel) static char tpsel_info_buf[80]; if (!sel) return "(null)"; if (sel->type==PJSIP_TPSELECTOR_LISTENER) - pj_ansi_snprintf(tpsel_info_buf, sizeof(tpsel_info_buf), - "listener[%s], reuse=%d", sel->u.listener->obj_name, - !sel->disable_connection_reuse); + pj_ansi_snprintf(tpsel_info_buf, sizeof(tpsel_info_buf), + "listener[%s], reuse=%d", sel->u.listener->obj_name, + !sel->disable_connection_reuse); else if (sel->type==PJSIP_TPSELECTOR_TRANSPORT) - pj_ansi_snprintf(tpsel_info_buf, sizeof(tpsel_info_buf), - "transport[%s], reuse=%d", sel->u.transport->info, - !sel->disable_connection_reuse); + pj_ansi_snprintf(tpsel_info_buf, sizeof(tpsel_info_buf), + "transport[%s], reuse=%d", sel->u.transport->info, + !sel->disable_connection_reuse); else - pj_ansi_snprintf(tpsel_info_buf, sizeof(tpsel_info_buf), - "unknown[%p], reuse=%d", sel->u.ptr, - !sel->disable_connection_reuse); + pj_ansi_snprintf(tpsel_info_buf, sizeof(tpsel_info_buf), + "unknown[%p], reuse=%d", sel->u.ptr, + !sel->disable_connection_reuse); return tpsel_info_buf; } #else @@ -74,12 +73,12 @@ static const char* print_tpsel_info(const pjsip_tpselector *sel) /* Specify the initial size of the transport manager's pool. */ #ifndef TPMGR_POOL_INIT_SIZE -# define TPMGR_POOL_INIT_SIZE 64 +# define TPMGR_POOL_INIT_SIZE 64 #endif /* Specify the increment size of the transport manager's pool. */ #ifndef TPMGR_POOL_INC_SIZE - #define TPMGR_POOL_INC_SIZE 64 + #define TPMGR_POOL_INC_SIZE 64 #endif /* Specify transport entry allocation count. When registering a new transport, @@ -99,19 +98,19 @@ static pj_status_t mod_on_tx_msg(pjsip_tx_data *tdata); */ static pjsip_module mod_msg_print = { - NULL, NULL, /* prev and next */ - { "mod-msg-print", 13}, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_TRANSPORT_LAYER, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - NULL, /* on_rx_request() */ - NULL, /* on_rx_response() */ - &mod_on_tx_msg, /* on_tx_request() */ - &mod_on_tx_msg, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev and next */ + { "mod-msg-print", 13}, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_TRANSPORT_LAYER, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + &mod_on_tx_msg, /* on_tx_request() */ + &mod_on_tx_msg, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; /* Transport list item */ @@ -128,15 +127,15 @@ typedef struct transport struct pjsip_tpmgr { pj_hash_table_t *table; - pj_lock_t *lock; + pj_lock_t *lock; pjsip_endpoint *endpt; pjsip_tpfactory factory_list; - pj_pool_t *pool; + pj_pool_t *pool; #if defined(PJ_DEBUG) && PJ_DEBUG!=0 - pj_atomic_t *tdata_counter; + pj_atomic_t *tdata_counter; #endif void (*on_rx_msg)(pjsip_endpoint*, pj_status_t, pjsip_rx_data*); - pj_status_t (*on_tx_msg)(pjsip_endpoint*, pjsip_tx_data*); + pj_status_t (*on_tx_msg)(pjsip_endpoint*, pjsip_tx_data*); pjsip_tp_state_callback tp_state_cb; pjsip_tp_on_rx_dropped_cb tp_drop_data_cb; @@ -146,7 +145,7 @@ struct pjsip_tpmgr pjsip_tx_data tdata_list; /* List of free transport entry. */ - transport tp_entry_freelist; + transport tp_entry_freelist; }; @@ -166,8 +165,8 @@ typedef struct tp_state_listener typedef struct transport_data { /* Transport listeners */ - tp_state_listener st_listeners; - tp_state_listener st_listeners_empty; + tp_state_listener st_listeners; + tp_state_listener st_listeners_empty; } transport_data; @@ -182,111 +181,111 @@ typedef struct transport_data */ static struct transport_names_t { - pjsip_transport_type_e type; /* Transport type */ - pj_uint16_t port; /* Default port number */ - pj_str_t name; /* Id tag */ - const char *description; /* Longer description */ - unsigned flag; /* Flags */ - char name_buf[16]; /* For user's transport */ + pjsip_transport_type_e type; /* Transport type */ + pj_uint16_t port; /* Default port number */ + pj_str_t name; /* Id tag */ + const char *description; /* Longer description */ + unsigned flag; /* Flags */ + char name_buf[16]; /* For user's transport */ } transport_names[16] = { { - PJSIP_TRANSPORT_UNSPECIFIED, - 0, - {"Unspecified", 11}, - "Unspecified", - 0 + PJSIP_TRANSPORT_UNSPECIFIED, + 0, + {"Unspecified", 11}, + "Unspecified", + 0 }, { - PJSIP_TRANSPORT_UDP, - 5060, - {"UDP", 3}, - "UDP transport", - PJSIP_TRANSPORT_DATAGRAM + PJSIP_TRANSPORT_UDP, + 5060, + {"UDP", 3}, + "UDP transport", + PJSIP_TRANSPORT_DATAGRAM }, { - PJSIP_TRANSPORT_TCP, - 5060, - {"TCP", 3}, - "TCP transport", - PJSIP_TRANSPORT_RELIABLE + PJSIP_TRANSPORT_TCP, + 5060, + {"TCP", 3}, + "TCP transport", + PJSIP_TRANSPORT_RELIABLE }, { - PJSIP_TRANSPORT_TLS, - 5061, - {"TLS", 3}, - "TLS transport", - PJSIP_TRANSPORT_RELIABLE | PJSIP_TRANSPORT_SECURE + PJSIP_TRANSPORT_TLS, + 5061, + {"TLS", 3}, + "TLS transport", + PJSIP_TRANSPORT_RELIABLE | PJSIP_TRANSPORT_SECURE }, { - PJSIP_TRANSPORT_DTLS, - 5061, - {"DTLS", 4}, - "DTLS transport", - PJSIP_TRANSPORT_SECURE + PJSIP_TRANSPORT_DTLS, + 5061, + {"DTLS", 4}, + "DTLS transport", + PJSIP_TRANSPORT_SECURE }, { - PJSIP_TRANSPORT_SCTP, - 5060, - {"SCTP", 4}, - "SCTP transport", - PJSIP_TRANSPORT_RELIABLE + PJSIP_TRANSPORT_SCTP, + 5060, + {"SCTP", 4}, + "SCTP transport", + PJSIP_TRANSPORT_RELIABLE }, { - PJSIP_TRANSPORT_LOOP, - 15060, - {"LOOP", 4}, - "Loopback transport", - PJSIP_TRANSPORT_RELIABLE + PJSIP_TRANSPORT_LOOP, + 15060, + {"LOOP", 4}, + "Loopback transport", + PJSIP_TRANSPORT_RELIABLE }, { - PJSIP_TRANSPORT_LOOP_DGRAM, - 15060, - {"LOOP-DGRAM", 10}, - "Loopback datagram transport", - PJSIP_TRANSPORT_DATAGRAM + PJSIP_TRANSPORT_LOOP_DGRAM, + 15060, + {"LOOP-DGRAM", 10}, + "Loopback datagram transport", + PJSIP_TRANSPORT_DATAGRAM }, { - PJSIP_TRANSPORT_UDP6, - 5060, - {"UDP", 3}, - "UDP IPv6 transport", - PJSIP_TRANSPORT_DATAGRAM + PJSIP_TRANSPORT_UDP6, + 5060, + {"UDP", 3}, + "UDP IPv6 transport", + PJSIP_TRANSPORT_DATAGRAM }, { - PJSIP_TRANSPORT_TCP6, - 5060, - {"TCP", 3}, - "TCP IPv6 transport", - PJSIP_TRANSPORT_RELIABLE + PJSIP_TRANSPORT_TCP6, + 5060, + {"TCP", 3}, + "TCP IPv6 transport", + PJSIP_TRANSPORT_RELIABLE }, { - PJSIP_TRANSPORT_TLS6, - 5061, - {"TLS", 3}, - "TLS IPv6 transport", - PJSIP_TRANSPORT_RELIABLE | PJSIP_TRANSPORT_SECURE + PJSIP_TRANSPORT_TLS6, + 5061, + {"TLS", 3}, + "TLS IPv6 transport", + PJSIP_TRANSPORT_RELIABLE | PJSIP_TRANSPORT_SECURE }, { - PJSIP_TRANSPORT_DTLS6, - 5061, - {"DTLS", 4}, - "DTLS IPv6 transport", - PJSIP_TRANSPORT_SECURE + PJSIP_TRANSPORT_DTLS6, + 5061, + {"DTLS", 4}, + "DTLS IPv6 transport", + PJSIP_TRANSPORT_SECURE }, }; static void tp_state_callback(pjsip_transport *tp, - pjsip_transport_state state, - const pjsip_transport_state_info *info); + pjsip_transport_state state, + const pjsip_transport_state_info *info); static struct transport_names_t *get_tpname(pjsip_transport_type_e type) { unsigned i; for (i=0; islen == 0) - return PJSIP_TRANSPORT_UNSPECIFIED; + return PJSIP_TRANSPORT_UNSPECIFIED; /* Get transport type from name. */ for (i=0; itype == PJSIP_TPSELECTOR_TRANSPORT && sel->u.transport != NULL) - pjsip_transport_add_ref(sel->u.transport); + pjsip_transport_add_ref(sel->u.transport); else if (sel->type == PJSIP_TPSELECTOR_LISTENER && sel->u.listener != NULL) - ; /* Hmm.. looks like we don't have reference counter for listener */ + ; /* Hmm.. looks like we don't have reference counter for listener */ } @@ -451,9 +450,9 @@ PJ_DEF(void) pjsip_tpselector_add_ref(pjsip_tpselector *sel) PJ_DEF(void) pjsip_tpselector_dec_ref(pjsip_tpselector *sel) { if (sel->type == PJSIP_TPSELECTOR_TRANSPORT && sel->u.transport != NULL) - pjsip_transport_dec_ref(sel->u.transport); + pjsip_transport_dec_ref(sel->u.transport); else if (sel->type == PJSIP_TPSELECTOR_LISTENER && sel->u.listener != NULL) - ; /* Hmm.. looks like we don't have reference counter for listener */ + ; /* Hmm.. looks like we don't have reference counter for listener */ } @@ -467,7 +466,7 @@ PJ_DEF(void) pjsip_tpselector_dec_ref(pjsip_tpselector *sel) * Create new transmit buffer. */ PJ_DEF(pj_status_t) pjsip_tx_data_create( pjsip_tpmgr *mgr, - pjsip_tx_data **p_tdata ) + pjsip_tx_data **p_tdata ) { pj_pool_t *pool; pjsip_tx_data *tdata; @@ -476,10 +475,10 @@ PJ_DEF(pj_status_t) pjsip_tx_data_create( pjsip_tpmgr *mgr, PJ_ASSERT_RETURN(mgr && p_tdata, PJ_EINVAL); pool = pjsip_endpt_create_pool( mgr->endpt, "tdta%p", - PJSIP_POOL_LEN_TDATA, - PJSIP_POOL_INC_TDATA ); + PJSIP_POOL_LEN_TDATA, + PJSIP_POOL_INC_TDATA ); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; tdata = PJ_POOL_ZALLOC_T(pool, pjsip_tx_data); tdata->pool = pool; @@ -489,15 +488,15 @@ PJ_DEF(pj_status_t) pjsip_tx_data_create( pjsip_tpmgr *mgr, status = pj_atomic_create(tdata->pool, 0, &tdata->ref_cnt); if (status != PJ_SUCCESS) { - pjsip_endpt_release_pool( mgr->endpt, tdata->pool ); - return status; + pjsip_endpt_release_pool( mgr->endpt, tdata->pool ); + return status; } //status = pj_lock_create_simple_mutex(pool, "tdta%p", &tdata->lock); status = pj_lock_create_null_mutex(pool, "tdta%p", &tdata->lock); if (status != PJ_SUCCESS) { - pjsip_endpt_release_pool( mgr->endpt, tdata->pool ); - return status; + pjsip_endpt_release_pool( mgr->endpt, tdata->pool ); + return status; } pj_ioqueue_op_key_init(&tdata->op_key.key, sizeof(tdata->op_key.key)); @@ -530,7 +529,7 @@ PJ_DEF(void) pjsip_tx_data_add_ref( pjsip_tx_data *tdata ) static void tx_data_destroy(pjsip_tx_data *tdata) { PJ_LOG(5,(tdata->obj_name, "Destroying txdata %s", - pjsip_tx_data_get_info(tdata))); + pjsip_tx_data_get_info(tdata))); pjsip_tpselector_dec_ref(&tdata->tp_sel); #if defined(PJ_DEBUG) && PJ_DEBUG!=0 pj_atomic_dec( tdata->mgr->tdata_counter ); @@ -561,10 +560,10 @@ PJ_DEF(pj_status_t) pjsip_tx_data_dec_ref( pjsip_tx_data *tdata ) ref_cnt = pj_atomic_dec_and_get(tdata->ref_cnt); pj_assert( ref_cnt >= 0); if (ref_cnt == 0) { - tx_data_destroy(tdata); - return PJSIP_EBUFDESTROYED; + tx_data_destroy(tdata); + return PJSIP_EBUFDESTROYED; } else { - return PJ_SUCCESS; + return PJ_SUCCESS; } } @@ -585,33 +584,33 @@ PJ_DEF(pj_status_t) pjsip_tx_data_encode(pjsip_tx_data *tdata) { /* Allocate buffer if necessary. */ if (tdata->buf.start == NULL) { - PJ_USE_EXCEPTION; - - PJ_TRY { - tdata->buf.start = (char*) - pj_pool_alloc(tdata->pool, PJSIP_MAX_PKT_LEN); - } - PJ_CATCH_ANY { - return PJ_ENOMEM; - } - PJ_END - - tdata->buf.cur = tdata->buf.start; - tdata->buf.end = tdata->buf.start + PJSIP_MAX_PKT_LEN; + PJ_USE_EXCEPTION; + + PJ_TRY { + tdata->buf.start = (char*) + pj_pool_alloc(tdata->pool, PJSIP_MAX_PKT_LEN); + } + PJ_CATCH_ANY { + return PJ_ENOMEM; + } + PJ_END + + tdata->buf.cur = tdata->buf.start; + tdata->buf.end = tdata->buf.start + PJSIP_MAX_PKT_LEN; } /* Do we need to reprint? */ if (!pjsip_tx_data_is_valid(tdata)) { - pj_ssize_t size; - - size = pjsip_msg_print( tdata->msg, tdata->buf.start, - tdata->buf.end - tdata->buf.start); - if (size < 0) { - return PJSIP_EMSGTOOLONG; - } - pj_assert(size != 0); - tdata->buf.cur[size] = '\0'; - tdata->buf.cur += size; + pj_ssize_t size; + + size = pjsip_msg_print( tdata->msg, tdata->buf.start, + tdata->buf.end - tdata->buf.start); + if (size < 0) { + return PJSIP_EMSGTOOLONG; + } + pj_assert(size != 0); + tdata->buf.cur[size] = '\0'; + tdata->buf.cur += size; } return PJ_SUCCESS; @@ -623,7 +622,7 @@ PJ_DEF(pj_bool_t) pjsip_tx_data_is_valid( pjsip_tx_data *tdata ) } static char *get_msg_info(pj_pool_t *pool, const char *obj_name, - const pjsip_msg *msg) + const pjsip_msg *msg) { char info_buf[128], *info; const pjsip_cseq_hdr *cseq; @@ -633,22 +632,22 @@ static char *get_msg_info(pj_pool_t *pool, const char *obj_name, PJ_ASSERT_RETURN(cseq != NULL, "INVALID MSG"); if (msg->type == PJSIP_REQUEST_MSG) { - len = pj_ansi_snprintf(info_buf, sizeof(info_buf), - "Request msg %.*s/cseq=%d (%s)", - (int)msg->line.req.method.name.slen, - msg->line.req.method.name.ptr, - cseq->cseq, obj_name); + len = pj_ansi_snprintf(info_buf, sizeof(info_buf), + "Request msg %.*s/cseq=%d (%s)", + (int)msg->line.req.method.name.slen, + msg->line.req.method.name.ptr, + cseq->cseq, obj_name); } else { - len = pj_ansi_snprintf(info_buf, sizeof(info_buf), - "Response msg %d/%.*s/cseq=%d (%s)", - msg->line.status.code, - (int)cseq->method.name.slen, - cseq->method.name.ptr, - cseq->cseq, obj_name); + len = pj_ansi_snprintf(info_buf, sizeof(info_buf), + "Response msg %d/%.*s/cseq=%d (%s)", + msg->line.status.code, + (int)cseq->method.name.slen, + cseq->method.name.ptr, + cseq->cseq, obj_name); } if (len < 1 || len >= (int)sizeof(info_buf)) { - return (char*)obj_name; + return (char*)obj_name; } info = (char*) pj_pool_alloc(pool, len+1); @@ -665,10 +664,10 @@ PJ_DEF(char*) pjsip_tx_data_get_info( pjsip_tx_data *tdata ) * just return it. */ if (tdata->info) - return tdata->info; + return tdata->info; if (tdata->msg==NULL) - return "NULL"; + return "NULL"; pj_lock_acquire(tdata->lock); tdata->info = get_msg_info(tdata->pool, tdata->obj_name, tdata->msg); @@ -678,7 +677,7 @@ PJ_DEF(char*) pjsip_tx_data_get_info( pjsip_tx_data *tdata ) } PJ_DEF(pj_status_t) pjsip_tx_data_set_transport(pjsip_tx_data *tdata, - const pjsip_tpselector *sel) + const pjsip_tpselector *sel) { PJ_ASSERT_RETURN(tdata && sel, PJ_EINVAL); @@ -697,7 +696,7 @@ PJ_DEF(pj_status_t) pjsip_tx_data_set_transport(pjsip_tx_data *tdata, /* Clone pjsip_tx_data. */ PJ_DEF(pj_status_t) pjsip_tx_data_clone(const pjsip_tx_data *src, unsigned flags, - pjsip_tx_data ** p_tdata) + pjsip_tx_data ** p_tdata) { pjsip_tx_data *dst; const pjsip_hdr *hsrc; @@ -708,7 +707,7 @@ PJ_DEF(pj_status_t) pjsip_tx_data_clone(const pjsip_tx_data *src, status = pjsip_tx_data_create(src->mgr, p_tdata); if (status != PJ_SUCCESS) - return status; + return status; dst = *p_tdata; @@ -719,19 +718,19 @@ PJ_DEF(pj_status_t) pjsip_tx_data_clone(const pjsip_tx_data *src, /* Duplicate status line */ msg->line.status.code = src->msg->line.status.code; pj_strdup(dst->pool, &msg->line.status.reason, - &src->msg->line.status.reason); + &src->msg->line.status.reason); /* Duplicate all headers */ hsrc = src->msg->hdr.next; while (hsrc != &src->msg->hdr) { - pjsip_hdr *h = (pjsip_hdr*) pjsip_hdr_clone(dst->pool, hsrc); - pjsip_msg_add_hdr(msg, h); - hsrc = hsrc->next; + pjsip_hdr *h = (pjsip_hdr*) pjsip_hdr_clone(dst->pool, hsrc); + pjsip_msg_add_hdr(msg, h); + hsrc = hsrc->next; } /* Duplicate message body */ if (src->msg->body) - msg->body = pjsip_msg_body_clone(dst->pool, src->msg->body); + msg->body = pjsip_msg_body_clone(dst->pool, src->msg->body); /* We shouldn't copy is_pending since it's src's internal state, * indicating that it's currently being sent by the transport. @@ -740,8 +739,8 @@ PJ_DEF(pj_status_t) pjsip_tx_data_clone(const pjsip_tx_data *src, //dst->is_pending = src->is_pending; PJ_LOG(5,(THIS_FILE, - "Tx data %s cloned", - pjsip_tx_data_get_info(dst))); + "Tx data %s cloned", + pjsip_tx_data_get_info(dst))); return PJ_SUCCESS; } @@ -753,13 +752,13 @@ PJ_DEF(char*) pjsip_rx_data_get_info(pjsip_rx_data *rdata) PJ_ASSERT_RETURN(rdata->msg_info.msg, "INVALID MSG"); if (rdata->msg_info.info) - return rdata->msg_info.info; + return rdata->msg_info.info; pj_ansi_strcpy(obj_name, "rdata"); pj_ansi_snprintf(obj_name+5, sizeof(obj_name)-5, "%p", rdata); rdata->msg_info.info = get_msg_info(rdata->tp_info.pool, obj_name, - rdata->msg_info.msg); + rdata->msg_info.msg); return rdata->msg_info.info; } @@ -780,7 +779,7 @@ PJ_DEF(pj_status_t) pjsip_rx_data_clone( const pjsip_rx_data *src, PJSIP_POOL_RDATA_INC, NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; dst = PJ_POOL_ZALLOC_T(pool, pjsip_rx_data); @@ -793,38 +792,38 @@ PJ_DEF(pj_status_t) pjsip_rx_data_clone( const pjsip_rx_data *src, /* msg_info needs deep clone */ dst->msg_info.msg_buf = dst->pkt_info.packet + - (src->msg_info.msg_buf - src->pkt_info.packet); + (src->msg_info.msg_buf - src->pkt_info.packet); dst->msg_info.len = src->msg_info.len; dst->msg_info.msg = pjsip_msg_clone(pool, src->msg_info.msg); pj_list_init(&dst->msg_info.parse_err); -#define GET_MSG_HDR2(TYPE, type, var) \ - case PJSIP_H_##TYPE: \ - if (!dst->msg_info.var) { \ - dst->msg_info.var = (pjsip_##type##_hdr*)hdr; \ - } \ - break -#define GET_MSG_HDR(TYPE, var_type) GET_MSG_HDR2(TYPE, var_type, var_type) +#define GET_MSG_HDR2(TYPE, type, var) \ + case PJSIP_H_##TYPE: \ + if (!dst->msg_info.var) { \ + dst->msg_info.var = (pjsip_##type##_hdr*)hdr; \ + } \ + break +#define GET_MSG_HDR(TYPE, var_type) GET_MSG_HDR2(TYPE, var_type, var_type) hdr = dst->msg_info.msg->hdr.next; while (hdr != &dst->msg_info.msg->hdr) { - switch (hdr->type) { - GET_MSG_HDR(CALL_ID, cid); - GET_MSG_HDR(FROM, from); - GET_MSG_HDR(TO, to); - GET_MSG_HDR(VIA, via); - GET_MSG_HDR(CSEQ, cseq); - GET_MSG_HDR(MAX_FORWARDS, max_fwd); - GET_MSG_HDR(ROUTE, route); - GET_MSG_HDR2(RECORD_ROUTE, rr, record_route); - GET_MSG_HDR(CONTENT_TYPE, ctype); - GET_MSG_HDR(CONTENT_LENGTH, clen); - GET_MSG_HDR(REQUIRE, require); - GET_MSG_HDR(SUPPORTED, supported); - default: - break; - } - hdr = hdr->next; + switch (hdr->type) { + GET_MSG_HDR(CALL_ID, cid); + GET_MSG_HDR(FROM, from); + GET_MSG_HDR(TO, to); + GET_MSG_HDR(VIA, via); + GET_MSG_HDR(CSEQ, cseq); + GET_MSG_HDR(MAX_FORWARDS, max_fwd); + GET_MSG_HDR(ROUTE, route); + GET_MSG_HDR2(RECORD_ROUTE, rr, record_route); + GET_MSG_HDR(CONTENT_TYPE, ctype); + GET_MSG_HDR(CONTENT_LENGTH, clen); + GET_MSG_HDR(REQUIRE, require); + GET_MSG_HDR(SUPPORTED, supported); + default: + break; + } + hdr = hdr->next; } #undef GET_MSG_HDR @@ -861,8 +860,8 @@ PJ_DEF(pj_status_t) pjsip_rx_data_free_cloned(pjsip_rx_data *rdata) *****************************************************************************/ static void transport_send_callback(pjsip_transport *transport, - void *token, - pj_ssize_t size) + void *token, + pj_ssize_t size) { pjsip_tx_data *tdata = (pjsip_tx_data*) token; @@ -875,7 +874,7 @@ static void transport_send_callback(pjsip_transport *transport, /* Call callback, if any. */ if (tdata->cb) { - (*tdata->cb)(tdata->token, tdata, size); + (*tdata->cb)(tdata->token, tdata, size); } /* Decrement reference count. */ @@ -894,11 +893,11 @@ static pj_status_t mod_on_tx_msg(pjsip_tx_data *tdata) * Send a SIP message using the specified transport. */ PJ_DEF(pj_status_t) pjsip_transport_send( pjsip_transport *tr, - pjsip_tx_data *tdata, - const pj_sockaddr_t *addr, - int addr_len, - void *token, - pjsip_tp_send_callback cb) + pjsip_tx_data *tdata, + const pj_sockaddr_t *addr, + int addr_len, + void *token, + pjsip_tp_send_callback cb) { pj_status_t status; @@ -906,10 +905,10 @@ PJ_DEF(pj_status_t) pjsip_transport_send( pjsip_transport *tr, /* Is it currently being sent? */ if (tdata->is_pending) { - pj_assert(!"Invalid operation step!"); - PJ_LOG(2,(THIS_FILE, "Unable to send %s: message is pending", - pjsip_tx_data_get_info(tdata))); - return PJSIP_EPENDINGTX; + pj_assert(!"Invalid operation step!"); + PJ_LOG(2,(THIS_FILE, "Unable to send %s: message is pending", + pjsip_tx_data_get_info(tdata))); + return PJSIP_EPENDINGTX; } /* Add reference to prevent deletion, and to cancel idle timer if @@ -923,9 +922,9 @@ PJ_DEF(pj_status_t) pjsip_transport_send( pjsip_transport *tr, tdata->tp_info.dst_addr_len = addr_len; pj_inet_ntop(((pj_sockaddr*)addr)->addr.sa_family, - pj_sockaddr_get_addr(addr), - tdata->tp_info.dst_name, - sizeof(tdata->tp_info.dst_name)); + pj_sockaddr_get_addr(addr), + tdata->tp_info.dst_name, + sizeof(tdata->tp_info.dst_name)); tdata->tp_info.dst_port = pj_sockaddr_get_port(addr); /* Distribute to modules. @@ -933,11 +932,11 @@ PJ_DEF(pj_status_t) pjsip_transport_send( pjsip_transport *tr, * be "printed" to contiguous buffer. */ if (tr->tpmgr->on_tx_msg) { - status = (*tr->tpmgr->on_tx_msg)(tr->endpt, tdata); - if (status != PJ_SUCCESS) { - pjsip_transport_dec_ref(tr); - return status; - } + status = (*tr->tpmgr->on_tx_msg)(tr->endpt, tdata); + if (status != PJ_SUCCESS) { + pjsip_transport_dec_ref(tr); + return status; + } } /* Save callback data. */ @@ -952,11 +951,11 @@ PJ_DEF(pj_status_t) pjsip_transport_send( pjsip_transport *tr, /* Send to transport. */ status = (*tr->send_msg)(tr, tdata, addr, addr_len, (void*)tdata, - &transport_send_callback); + &transport_send_callback); if (status != PJ_EPENDING) { - tdata->is_pending = 0; - pjsip_tx_data_dec_ref(tdata); + tdata->is_pending = 0; + pjsip_tx_data_dec_ref(tdata); } pjsip_transport_dec_ref(tr); @@ -966,8 +965,8 @@ PJ_DEF(pj_status_t) pjsip_transport_send( pjsip_transport *tr, /* send_raw() callback */ static void send_raw_callback(pjsip_transport *transport, - void *token, - pj_ssize_t size) + void *token, + pj_ssize_t size) { pjsip_tx_data *tdata = (pjsip_tx_data*) token; @@ -978,7 +977,7 @@ static void send_raw_callback(pjsip_transport *transport, /* Call callback, if any. */ if (tdata->cb) { - (*tdata->cb)(tdata->token, tdata, size); + (*tdata->cb)(tdata->token, tdata, size); } /* Decrement tdata reference count. */ @@ -991,51 +990,51 @@ static void send_raw_callback(pjsip_transport *transport, /* Send raw data */ PJ_DEF(pj_status_t) pjsip_tpmgr_send_raw(pjsip_tpmgr *mgr, - pjsip_transport_type_e tp_type, - const pjsip_tpselector *sel, - pjsip_tx_data *tdata, - const void *raw_data, - pj_size_t data_len, - const pj_sockaddr_t *addr, - int addr_len, - void *token, - pjsip_tp_send_callback cb) + pjsip_transport_type_e tp_type, + const pjsip_tpselector *sel, + pjsip_tx_data *tdata, + const void *raw_data, + pj_size_t data_len, + const pj_sockaddr_t *addr, + int addr_len, + void *token, + pjsip_tp_send_callback cb) { pjsip_transport *tr; pj_status_t status; /* Acquire the transport */ status = pjsip_tpmgr_acquire_transport(mgr, tp_type, addr, addr_len, - sel, &tr); + sel, &tr); if (status != PJ_SUCCESS) - return status; + return status; /* Create transmit data buffer if one is not specified */ if (tdata == NULL) { - status = pjsip_endpt_create_tdata(tr->endpt, &tdata); - if (status != PJ_SUCCESS) { - pjsip_transport_dec_ref(tr); - return status; - } + status = pjsip_endpt_create_tdata(tr->endpt, &tdata); + if (status != PJ_SUCCESS) { + pjsip_transport_dec_ref(tr); + return status; + } - tdata->info = "raw"; + tdata->info = "raw"; - /* Add reference counter. */ - pjsip_tx_data_add_ref(tdata); + /* Add reference counter. */ + pjsip_tx_data_add_ref(tdata); } /* Allocate buffer */ if (tdata->buf.start == NULL || - (tdata->buf.end - tdata->buf.start) < (int)data_len) + (tdata->buf.end - tdata->buf.start) < (int)data_len) { - /* Note: data_len may be zero, so allocate +1 */ - tdata->buf.start = (char*) pj_pool_alloc(tdata->pool, data_len+1); - tdata->buf.end = tdata->buf.start + data_len + 1; + /* Note: data_len may be zero, so allocate +1 */ + tdata->buf.start = (char*) pj_pool_alloc(tdata->pool, data_len+1); + tdata->buf.end = tdata->buf.start + data_len + 1; } /* Copy data, if any! (application may send zero len packet) */ if (data_len) { - pj_memcpy(tdata->buf.start, raw_data, data_len); + pj_memcpy(tdata->buf.start, raw_data, data_len); } tdata->buf.cur = tdata->buf.start + data_len; @@ -1048,12 +1047,12 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_send_raw(pjsip_tpmgr *mgr, /* Send to transport */ status = tr->send_msg(tr, tdata, addr, addr_len, - tdata, &send_raw_callback); + tdata, &send_raw_callback); if (status != PJ_EPENDING) { - /* callback will not be called, so destroy tdata now. */ - pjsip_tx_data_dec_ref(tdata); - pjsip_transport_dec_ref(tr); + /* callback will not be called, so destroy tdata now. */ + pjsip_tx_data_dec_ref(tdata); + pjsip_transport_dec_ref(tr); } return status; @@ -1061,7 +1060,7 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_send_raw(pjsip_tpmgr *mgr, static void transport_idle_callback(pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { pjsip_transport *tp = (pjsip_transport*) entry->user_data; pj_assert(tp != NULL); @@ -1069,7 +1068,7 @@ static void transport_idle_callback(pj_timer_heap_t *timer_heap, PJ_UNUSED_ARG(timer_heap); if (entry->id == PJ_FALSE) - return; + return; entry->id = PJ_FALSE; @@ -1078,10 +1077,10 @@ static void transport_idle_callback(pj_timer_heap_t *timer_heap, */ pj_lock_acquire(tp->tpmgr->lock); if (pj_atomic_get(tp->ref_cnt) == 0) { - tp->is_destroying = PJ_TRUE; + tp->is_destroying = PJ_TRUE; } else { - pj_lock_release(tp->tpmgr->lock); - return; + pj_lock_release(tp->tpmgr->lock); + return; } pj_lock_release(tp->tpmgr->lock); @@ -1090,21 +1089,21 @@ static void transport_idle_callback(pj_timer_heap_t *timer_heap, static pj_bool_t is_transport_valid(pjsip_transport *tp, pjsip_tpmgr *tpmgr, - const pjsip_transport_key *key, - int key_len) + const pjsip_transport_key *key, + int key_len) { transport *tp_entry; tp_entry = (transport *)pj_hash_get(tpmgr->table, key, key_len, NULL); if (tp_entry != NULL) { - transport *tp_iter = tp_entry; - do { - if (tp_iter->tp == tp) { - return PJ_TRUE; - } - tp_iter = tp_iter->next; - } while (tp_iter != tp_entry); + transport *tp_iter = tp_entry; + do { + if (tp_iter->tp == tp) { + return PJ_TRUE; + } + tp_iter = tp_iter->next; + } while (tp_iter != tp_entry); } return PJ_FALSE; @@ -1123,7 +1122,7 @@ PJ_DEF(pj_status_t) pjsip_transport_add_ref( pjsip_transport *tp ) /* Add ref transport group lock, if any */ if (tp->grp_lock) - pj_grp_lock_add_ref(tp->grp_lock); + pj_grp_lock_add_ref(tp->grp_lock); /* Cache some vars for checking transport validity later */ tpmgr = tp->tpmgr; @@ -1131,19 +1130,19 @@ PJ_DEF(pj_status_t) pjsip_transport_add_ref( pjsip_transport *tp ) pj_memcpy(&key, &tp->key, key_len); if (pj_atomic_inc_and_get(tp->ref_cnt) == 1) { - pj_lock_acquire(tpmgr->lock); - /* Verify again. But first, make sure transport is still valid - * (see #1883). - */ - if (is_transport_valid(tp, tpmgr, &key, key_len) && - pj_atomic_get(tp->ref_cnt) == 1) - { - if (tp->idle_timer.id != PJ_FALSE) { - tp->idle_timer.id = PJ_FALSE; - pjsip_endpt_cancel_timer(tp->tpmgr->endpt, &tp->idle_timer); - } - } - pj_lock_release(tpmgr->lock); + pj_lock_acquire(tpmgr->lock); + /* Verify again. But first, make sure transport is still valid + * (see #1883). + */ + if (is_transport_valid(tp, tpmgr, &key, key_len) && + pj_atomic_get(tp->ref_cnt) == 1) + { + if (tp->idle_timer.id != PJ_FALSE) { + tp->idle_timer.id = PJ_FALSE; + pjsip_endpt_cancel_timer(tp->tpmgr->endpt, &tp->idle_timer); + } + } + pj_lock_release(tpmgr->lock); } return PJ_SUCCESS; @@ -1167,45 +1166,45 @@ PJ_DEF(pj_status_t) pjsip_transport_dec_ref( pjsip_transport *tp ) pj_memcpy(&key, &tp->key, key_len); if (pj_atomic_dec_and_get(tp->ref_cnt) == 0) { - pj_lock_acquire(tpmgr->lock); - /* Verify again. Do not register timer if the transport is - * being destroyed. But first, make sure transport is still valid - * (see #1883). - */ - if (is_transport_valid(tp, tpmgr, &key, key_len) && - !tp->is_destroying && pj_atomic_get(tp->ref_cnt) == 0) - { - pj_time_val delay; - - /* If transport is in graceful shutdown, then this is the - * last user who uses the transport. Schedule to destroy the - * transport immediately. Otherwise schedule idle timer. - */ - if (tp->is_shutdown) { - delay.sec = delay.msec = 0; - } else { - delay.sec = (tp->dir==PJSIP_TP_DIR_OUTGOING) ? - PJSIP_TRANSPORT_IDLE_TIME : - PJSIP_TRANSPORT_SERVER_IDLE_TIME; - delay.msec = 0; - } - - /* Avoid double timer entry scheduling */ - if (pj_timer_entry_running(&tp->idle_timer)) - pjsip_endpt_cancel_timer(tp->tpmgr->endpt, &tp->idle_timer); - - pjsip_endpt_schedule_timer_w_grp_lock(tp->tpmgr->endpt, - &tp->idle_timer, - &delay, - PJ_TRUE, - tp->grp_lock); - } - pj_lock_release(tpmgr->lock); + pj_lock_acquire(tpmgr->lock); + /* Verify again. Do not register timer if the transport is + * being destroyed. But first, make sure transport is still valid + * (see #1883). + */ + if (is_transport_valid(tp, tpmgr, &key, key_len) && + !tp->is_destroying && pj_atomic_get(tp->ref_cnt) == 0) + { + pj_time_val delay; + + /* If transport is in graceful shutdown, then this is the + * last user who uses the transport. Schedule to destroy the + * transport immediately. Otherwise schedule idle timer. + */ + if (tp->is_shutdown) { + delay.sec = delay.msec = 0; + } else { + delay.sec = (tp->dir==PJSIP_TP_DIR_OUTGOING) ? + PJSIP_TRANSPORT_IDLE_TIME : + PJSIP_TRANSPORT_SERVER_IDLE_TIME; + delay.msec = 0; + } + + /* Avoid double timer entry scheduling */ + if (pj_timer_entry_running(&tp->idle_timer)) + pjsip_endpt_cancel_timer(tp->tpmgr->endpt, &tp->idle_timer); + + pjsip_endpt_schedule_timer_w_grp_lock(tp->tpmgr->endpt, + &tp->idle_timer, + &delay, + PJ_TRUE, + tp->grp_lock); + } + pj_lock_release(tpmgr->lock); } /* Dec ref transport group lock, if any */ if (tp->grp_lock) { - pj_grp_lock_dec_ref(tp->grp_lock); + pj_grp_lock_dec_ref(tp->grp_lock); } return PJ_SUCCESS; @@ -1216,7 +1215,7 @@ PJ_DEF(pj_status_t) pjsip_transport_dec_ref( pjsip_transport *tp ) * Register a transport. */ PJ_DEF(pj_status_t) pjsip_transport_register( pjsip_tpmgr *mgr, - pjsip_transport *tp ) + pjsip_transport *tp ) { int key_len; pj_uint32_t hval; @@ -1240,57 +1239,57 @@ PJ_DEF(pj_status_t) pjsip_transport_register( pjsip_tpmgr *mgr, /* Get an empty entry from the freelist. */ if (pj_list_empty(&mgr->tp_entry_freelist)) { - unsigned i = 0; - - TRACE_((THIS_FILE, "Transport list is full, allocate new entry")); - /* Allocate new entry for the freelist. */ - for (; i < PJSIP_TRANSPORT_ENTRY_ALLOC_CNT; ++i) { - tp_add = PJ_POOL_ZALLOC_T(mgr->pool, transport); - if (!tp_add) - return PJ_ENOMEM; - pj_list_init(tp_add); - pj_list_push_back(&mgr->tp_entry_freelist, tp_add); - } + unsigned i = 0; + + TRACE_((THIS_FILE, "Transport list is full, allocate new entry")); + /* Allocate new entry for the freelist. */ + for (; i < PJSIP_TRANSPORT_ENTRY_ALLOC_CNT; ++i) { + tp_add = PJ_POOL_ZALLOC_T(mgr->pool, transport); + if (!tp_add) + return PJ_ENOMEM; + pj_list_init(tp_add); + pj_list_push_back(&mgr->tp_entry_freelist, tp_add); + } } tp_add = mgr->tp_entry_freelist.next; tp_add->tp = tp; pj_list_erase(tp_add); if (tp_ref) { - /* There'a already a transport list from the hash table. Add the - * new transport to the list. - */ - pj_list_push_back(tp_ref, tp_add); - TRACE_((THIS_FILE, "Remote address already registered, " - "appended the transport to the list")); + /* There'a already a transport list from the hash table. Add the + * new transport to the list. + */ + pj_list_push_back(tp_ref, tp_add); + TRACE_((THIS_FILE, "Remote address already registered, " + "appended the transport to the list")); } else { - /* Transport list not found, add it to the hash table. */ - pj_hash_set_np(mgr->table, &tp->key, key_len, hval, tp_add->tp_buf, - tp_add); - TRACE_((THIS_FILE, "Remote address not registered, " - "added the transport to the hash")); + /* Transport list not found, add it to the hash table. */ + pj_hash_set_np(mgr->table, &tp->key, key_len, hval, tp_add->tp_buf, + tp_add); + TRACE_((THIS_FILE, "Remote address not registered, " + "added the transport to the hash")); } /* Add ref transport group lock, if any */ if (tp->grp_lock) - pj_grp_lock_add_ref(tp->grp_lock); + pj_grp_lock_add_ref(tp->grp_lock); pj_lock_release(mgr->lock); TRACE_((THIS_FILE, "Transport %s registered: type=%s, remote=%s:%d", - tp->obj_name, - pjsip_transport_get_type_name(tp->key.type), - pj_sockaddr_has_addr(&tp->key.rem_addr)? - addr_string(&tp->key.rem_addr):"", - pj_sockaddr_has_addr(&tp->key.rem_addr)? - pj_sockaddr_get_port(&tp->key.rem_addr):0)); + tp->obj_name, + pjsip_transport_get_type_name(tp->key.type), + pj_sockaddr_has_addr(&tp->key.rem_addr)? + addr_string(&tp->key.rem_addr):"", + pj_sockaddr_has_addr(&tp->key.rem_addr)? + pj_sockaddr_get_port(&tp->key.rem_addr):0)); return PJ_SUCCESS; } /* Force destroy transport (e.g. during transport manager shutdown. */ static pj_status_t destroy_transport( pjsip_tpmgr *mgr, - pjsip_transport *tp ) + pjsip_transport *tp ) { int key_len; pj_uint32_t hval; @@ -1308,8 +1307,8 @@ static pj_status_t destroy_transport( pjsip_tpmgr *mgr, */ //pj_assert(tp->idle_timer.id == PJ_FALSE); if (tp->idle_timer.id != PJ_FALSE) { - tp->idle_timer.id = PJ_FALSE; - pjsip_endpt_cancel_timer(mgr->endpt, &tp->idle_timer); + tp->idle_timer.id = PJ_FALSE; + pjsip_endpt_cancel_timer(mgr->endpt, &tp->idle_timer); } /* @@ -1319,51 +1318,51 @@ static pj_status_t destroy_transport( pjsip_tpmgr *mgr, hval = 0; entry = pj_hash_get(mgr->table, &tp->key, key_len, &hval); if (entry) { - transport *tp_ref = (transport *)entry; - transport *tp_iter = tp_ref; - /* Search the matching entry from the transport list. */ - do { - if (tp_iter->tp == tp) { - transport *tp_next = tp_iter->next; - - /* Update hash table : - * - transport list only contain single element, or - * - the entry is the first element of the transport list. - */ - if (tp_iter == tp_ref) { - pj_hash_set(NULL, mgr->table, &tp->key, key_len, hval, - NULL); - - if (tp_ref->next != tp_ref) { - /* The transport list has multiple entry. */ - pj_hash_set_np(mgr->table, &tp_next->tp->key, key_len, - hval, tp_next->tp_buf, tp_next); - TRACE_((THIS_FILE, "Hash entry updated after " - "transport %d being destroyed", - tp->obj_name)); - } else { - TRACE_((THIS_FILE, "Hash entry deleted after " - "transport %d being destroyed", - tp->obj_name)); - } - } - - pj_list_erase(tp_iter); - /* Put back to the transport freelist. */ - pj_list_push_back(&mgr->tp_entry_freelist, tp_iter); - - break; - } - tp_iter = tp_iter->next; - } while (tp_iter != tp_ref); - - if (tp_iter->tp != tp) { - PJ_LOG(3, (THIS_FILE, "Warning: transport %s being destroyed is " - "not registered", tp->obj_name)); - } + transport *tp_ref = (transport *)entry; + transport *tp_iter = tp_ref; + /* Search the matching entry from the transport list. */ + do { + if (tp_iter->tp == tp) { + transport *tp_next = tp_iter->next; + + /* Update hash table : + * - transport list only contain single element, or + * - the entry is the first element of the transport list. + */ + if (tp_iter == tp_ref) { + pj_hash_set(NULL, mgr->table, &tp->key, key_len, hval, + NULL); + + if (tp_ref->next != tp_ref) { + /* The transport list has multiple entry. */ + pj_hash_set_np(mgr->table, &tp_next->tp->key, key_len, + hval, tp_next->tp_buf, tp_next); + TRACE_((THIS_FILE, "Hash entry updated after " + "transport %d being destroyed", + tp->obj_name)); + } else { + TRACE_((THIS_FILE, "Hash entry deleted after " + "transport %d being destroyed", + tp->obj_name)); + } + } + + pj_list_erase(tp_iter); + /* Put back to the transport freelist. */ + pj_list_push_back(&mgr->tp_entry_freelist, tp_iter); + + break; + } + tp_iter = tp_iter->next; + } while (tp_iter != tp_ref); + + if (tp_iter->tp != tp) { + PJ_LOG(3, (THIS_FILE, "Warning: transport %s being destroyed is " + "not registered", tp->obj_name)); + } } else { - PJ_LOG(3, (THIS_FILE, "Warning: transport %s being destroyed is " - "not found in the hash table", tp->obj_name)); + PJ_LOG(3, (THIS_FILE, "Warning: transport %s being destroyed is " + "not found in the hash table", tp->obj_name)); } pj_lock_release(mgr->lock); @@ -1371,7 +1370,7 @@ static pj_status_t destroy_transport( pjsip_tpmgr *mgr, /* Dec ref transport group lock, if any */ if (tp->grp_lock) { - pj_grp_lock_dec_ref(tp->grp_lock); + pj_grp_lock_dec_ref(tp->grp_lock); } /* Destroy. */ @@ -1392,14 +1391,14 @@ PJ_DEF(pj_status_t) pjsip_transport_shutdown(pjsip_transport *tp) * Start shutdown procedure for this transport. */ PJ_DEF(pj_status_t) pjsip_transport_shutdown2(pjsip_transport *tp, - pj_bool_t force) + pj_bool_t force) { pjsip_tpmgr *mgr; pj_status_t status; pjsip_tp_state_callback state_cb; PJ_LOG(4, (THIS_FILE, "Transport %s shutting down, force=%d", - tp->obj_name, force)); + tp->obj_name, force)); pj_lock_acquire(tp->lock); @@ -1408,35 +1407,35 @@ PJ_DEF(pj_status_t) pjsip_transport_shutdown2(pjsip_transport *tp, /* Do nothing if transport is being shutdown/destroyed already */ if (tp->is_shutdown || tp->is_destroying) { - pj_lock_release(mgr->lock); - pj_lock_release(tp->lock); - return PJ_SUCCESS; + pj_lock_release(mgr->lock); + pj_lock_release(tp->lock); + return PJ_SUCCESS; } status = PJ_SUCCESS; /* Instruct transport to shutdown itself */ if (tp->do_shutdown) - status = tp->do_shutdown(tp); + status = tp->do_shutdown(tp); if (status == PJ_SUCCESS) - tp->is_shutdown = PJ_TRUE; + tp->is_shutdown = PJ_TRUE; /* Notify application of transport shutdown */ state_cb = pjsip_tpmgr_get_state_cb(tp->tpmgr); if (state_cb) { - pjsip_transport_state_info state_info; + pjsip_transport_state_info state_info; - pj_bzero(&state_info, sizeof(state_info)); - state_info.status = PJ_ECANCELLED; - (*state_cb)(tp, (force? PJSIP_TP_STATE_DISCONNECTED: - PJSIP_TP_STATE_SHUTDOWN), &state_info); + pj_bzero(&state_info, sizeof(state_info)); + state_info.status = PJ_ECANCELLED; + (*state_cb)(tp, (force? PJSIP_TP_STATE_DISCONNECTED: + PJSIP_TP_STATE_SHUTDOWN), &state_info); } /* If transport reference count is zero, start timer count-down */ if (pj_atomic_get(tp->ref_cnt) == 0) { - pjsip_transport_add_ref(tp); - pjsip_transport_dec_ref(tp); + pjsip_transport_add_ref(tp); + pjsip_transport_dec_ref(tp); } pj_lock_release(mgr->lock); @@ -1459,9 +1458,9 @@ PJ_DEF(pj_status_t) pjsip_transport_destroy( pjsip_transport *tp) /* Notify application of transport destroy */ state_cb = pjsip_tpmgr_get_state_cb(tp->tpmgr); if (state_cb) { - pjsip_transport_state_info state_info; + pjsip_transport_state_info state_info; - pj_bzero(&state_info, sizeof(state_info)); + pj_bzero(&state_info, sizeof(state_info)); (*state_cb)(tp, PJSIP_TP_STATE_DESTROY, &state_info); } @@ -1479,7 +1478,7 @@ PJ_DEF(pj_status_t) pjsip_transport_destroy( pjsip_transport *tp) PJ_DEF(pj_status_t) pjsip_tpmgr_register_tpfactory( pjsip_tpmgr *mgr, - pjsip_tpfactory *tpf) + pjsip_tpfactory *tpf) { pjsip_tpfactory *p; pj_status_t status; @@ -1489,15 +1488,15 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_register_tpfactory( pjsip_tpmgr *mgr, /* Check that no same factory has been registered. */ status = PJ_SUCCESS; for (p=mgr->factory_list.next; p!=&mgr->factory_list; p=p->next) { - if (p == tpf) { - status = PJ_EEXISTS; - break; - } + if (p == tpf) { + status = PJ_EEXISTS; + break; + } } if (status != PJ_SUCCESS) { - pj_lock_release(mgr->lock); - return status; + pj_lock_release(mgr->lock); + return status; } pj_list_insert_before(&mgr->factory_list, tpf); @@ -1512,7 +1511,7 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_register_tpfactory( pjsip_tpmgr *mgr, * Unregister factory. */ PJ_DEF(pj_status_t) pjsip_tpmgr_unregister_tpfactory( pjsip_tpmgr *mgr, - pjsip_tpfactory *tpf) + pjsip_tpfactory *tpf) { pj_lock_acquire(mgr->lock); @@ -1530,16 +1529,16 @@ PJ_DECL(void) pjsip_tpmgr_fla2_param_default(pjsip_tpmgr_fla2_param *prm) } static pj_bool_t pjsip_tpmgr_is_tpfactory_valid(pjsip_tpmgr *mgr, - pjsip_tpfactory *tpf) + pjsip_tpfactory *tpf) { pjsip_tpfactory *p; pj_lock_acquire(mgr->lock); for (p=mgr->factory_list.next; p!=&mgr->factory_list; p=p->next) { - if (p == tpf) { - pj_lock_release(mgr->lock); - return PJ_TRUE; - } + if (p == tpf) { + pj_lock_release(mgr->lock); + return PJ_TRUE; + } } pj_lock_release(mgr->lock); @@ -1556,10 +1555,10 @@ static pj_bool_t pjsip_tpmgr_is_tpfactory_valid(pjsip_tpmgr *mgr, * Create a new transport manager. */ PJ_DEF(pj_status_t) pjsip_tpmgr_create( pj_pool_t *pool, - pjsip_endpoint *endpt, - pjsip_rx_callback rx_cb, - pjsip_tx_callback tx_cb, - pjsip_tpmgr **p_mgr) + pjsip_endpoint *endpt, + pjsip_rx_callback rx_cb, + pjsip_tx_callback tx_cb, + pjsip_tpmgr **p_mgr) { pjsip_tpmgr *mgr; pj_status_t status; @@ -1571,12 +1570,12 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_create( pj_pool_t *pool, /* Register mod_msg_print module. */ status = pjsip_endpt_register_module(endpt, &mod_msg_print); if (status != PJ_SUCCESS) - return status; + return status; /* Create and initialize transport manager. */ mgr_pool = pjsip_endpt_create_pool(endpt, "tpmgr", - TPMGR_POOL_INIT_SIZE, - TPMGR_POOL_INC_SIZE); + TPMGR_POOL_INIT_SIZE, + TPMGR_POOL_INC_SIZE); mgr = PJ_POOL_ZALLOC_T(mgr_pool, pjsip_tpmgr); mgr->endpt = endpt; mgr->on_rx_msg = rx_cb; @@ -1584,7 +1583,7 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_create( pj_pool_t *pool, mgr->pool = mgr_pool; if (!mgr->pool) - return PJ_ENOMEM; + return PJ_ENOMEM; pj_list_init(&mgr->factory_list); pj_list_init(&mgr->tdata_list); @@ -1592,27 +1591,27 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_create( pj_pool_t *pool, mgr->table = pj_hash_create(mgr->pool, PJSIP_TPMGR_HTABLE_SIZE); if (!mgr->table) - return PJ_ENOMEM; + return PJ_ENOMEM; status = pj_lock_create_recursive_mutex(mgr->pool, "tmgr%p", &mgr->lock); if (status != PJ_SUCCESS) - return status; + return status; for (; i < PJSIP_TRANSPORT_ENTRY_ALLOC_CNT; ++i) { - transport *tp_add = NULL; + transport *tp_add = NULL; - tp_add = PJ_POOL_ZALLOC_T(mgr->pool, transport); - if (!tp_add) - return PJ_ENOMEM; - pj_list_init(tp_add); - pj_list_push_back(&mgr->tp_entry_freelist, tp_add); + tp_add = PJ_POOL_ZALLOC_T(mgr->pool, transport); + if (!tp_add) + return PJ_ENOMEM; + pj_list_init(tp_add); + pj_list_push_back(&mgr->tp_entry_freelist, tp_add); } #if defined(PJ_DEBUG) && PJ_DEBUG!=0 status = pj_atomic_create(mgr->pool, 0, &mgr->tdata_counter); if (status != PJ_SUCCESS) { - pj_lock_destroy(mgr->lock); - return status; + pj_lock_destroy(mgr->lock); + return status; } #endif @@ -1627,7 +1626,7 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_create( pj_pool_t *pool, /* Get the interface to send packet to the specified address */ static pj_status_t get_net_interface(pjsip_transport_type_e tp_type, - const pj_str_t *dst, + const pj_str_t *dst, pj_str_t *itf_str_addr) { int af; @@ -1637,27 +1636,27 @@ static pj_status_t get_net_interface(pjsip_transport_type_e tp_type, af = (tp_type & PJSIP_TRANSPORT_IPV6)? pj_AF_INET6() : pj_AF_INET(); if (pjsip_cfg()->endpt.resolve_hostname_to_get_interface) { - status = pj_getipinterface(af, dst, &itf_addr, PJ_TRUE, NULL); + status = pj_getipinterface(af, dst, &itf_addr, PJ_TRUE, NULL); } if (status != PJ_SUCCESS) { - status = pj_getipinterface(af, dst, &itf_addr, PJ_FALSE, NULL); - if (status != PJ_SUCCESS) { - /* If it fails, e.g: on WM6(http://support.microsoft.com/kb/129065), - * just fallback using pj_gethostip(), see ticket #1660. - */ - PJ_PERROR(5,(THIS_FILE, status, - "Warning: unable to determine local interface, " - "fallback to default interface!")); - status = pj_gethostip(af, &itf_addr); - if (status != PJ_SUCCESS) - return status; - } + status = pj_getipinterface(af, dst, &itf_addr, PJ_FALSE, NULL); + if (status != PJ_SUCCESS) { + /* If it fails, e.g: on WM6(http://support.microsoft.com/kb/129065), + * just fallback using pj_gethostip(), see ticket #1660. + */ + PJ_PERROR(5,(THIS_FILE, status, + "Warning: unable to determine local interface, " + "fallback to default interface!")); + status = pj_gethostip(af, &itf_addr); + if (status != PJ_SUCCESS) + return status; + } } /* Print address */ pj_sockaddr_print(&itf_addr, itf_str_addr->ptr, - PJ_INET6_ADDRSTRLEN, 0); + PJ_INET6_ADDRSTRLEN, 0); itf_str_addr->slen = pj_ansi_strlen(itf_str_addr->ptr); return PJ_SUCCESS; @@ -1673,8 +1672,8 @@ static pj_status_t get_net_interface(pjsip_transport_type_e tp_type, * the transport type in the request. */ PJ_DEF(pj_status_t) pjsip_tpmgr_find_local_addr2(pjsip_tpmgr *tpmgr, - pj_pool_t *pool, - pjsip_tpmgr_fla2_param *prm) + pj_pool_t *pool, + pjsip_tpmgr_fla2_param *prm) { char tmp_buf[PJ_INET6_ADDRSTRLEN+10]; pj_str_t tmp_str; @@ -1692,112 +1691,112 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_find_local_addr2(pjsip_tpmgr *tpmgr, flag = pjsip_transport_get_flag_from_type(prm->tp_type); if (prm->tp_sel && prm->tp_sel->type == PJSIP_TPSELECTOR_TRANSPORT && - prm->tp_sel->u.transport) + prm->tp_sel->u.transport) { - const pjsip_transport *tp = prm->tp_sel->u.transport; - if (prm->local_if) { - status = get_net_interface((pjsip_transport_type_e)tp->key.type, - &prm->dst_host, &tmp_str); - if (status != PJ_SUCCESS) - goto on_return; - pj_strdup(pool, &prm->ret_addr, &tmp_str); - prm->ret_port = pj_sockaddr_get_port(&tp->local_addr); - prm->ret_tp = tp; - } else { - pj_strdup(pool, &prm->ret_addr, &tp->local_name.host); - prm->ret_port = (pj_uint16_t)tp->local_name.port; - } - status = PJ_SUCCESS; + const pjsip_transport *tp = prm->tp_sel->u.transport; + if (prm->local_if) { + status = get_net_interface((pjsip_transport_type_e)tp->key.type, + &prm->dst_host, &tmp_str); + if (status != PJ_SUCCESS) + goto on_return; + pj_strdup(pool, &prm->ret_addr, &tmp_str); + prm->ret_port = pj_sockaddr_get_port(&tp->local_addr); + prm->ret_tp = tp; + } else { + pj_strdup(pool, &prm->ret_addr, &tp->local_name.host); + prm->ret_port = (pj_uint16_t)tp->local_name.port; + } + status = PJ_SUCCESS; } else if (prm->tp_sel && prm->tp_sel->type == PJSIP_TPSELECTOR_LISTENER && - prm->tp_sel->u.listener) + prm->tp_sel->u.listener) { - if (prm->local_if) { - status = get_net_interface(prm->tp_sel->u.listener->type, - &prm->dst_host, &tmp_str); - if (status != PJ_SUCCESS) - goto on_return; - pj_strdup(pool, &prm->ret_addr, &tmp_str); - } else { - pj_strdup(pool, &prm->ret_addr, - &prm->tp_sel->u.listener->addr_name.host); - } - prm->ret_port = (pj_uint16_t)prm->tp_sel->u.listener->addr_name.port; - status = PJ_SUCCESS; + if (prm->local_if) { + status = get_net_interface(prm->tp_sel->u.listener->type, + &prm->dst_host, &tmp_str); + if (status != PJ_SUCCESS) + goto on_return; + pj_strdup(pool, &prm->ret_addr, &tmp_str); + } else { + pj_strdup(pool, &prm->ret_addr, + &prm->tp_sel->u.listener->addr_name.host); + } + prm->ret_port = (pj_uint16_t)prm->tp_sel->u.listener->addr_name.port; + status = PJ_SUCCESS; } else if ((flag & PJSIP_TRANSPORT_DATAGRAM) != 0) { - pj_sockaddr remote; - int addr_len; - pjsip_transport *tp; - - pj_bzero(&remote, sizeof(remote)); - if (prm->tp_type & PJSIP_TRANSPORT_IPV6) { - addr_len = sizeof(pj_sockaddr_in6); - remote.addr.sa_family = pj_AF_INET6(); - } else { - addr_len = sizeof(pj_sockaddr_in); - remote.addr.sa_family = pj_AF_INET(); - } - - status = pjsip_tpmgr_acquire_transport(tpmgr, prm->tp_type, &remote, - addr_len, NULL, &tp); - - if (status == PJ_SUCCESS) { - if (prm->local_if) { - status = get_net_interface((pjsip_transport_type_e) - tp->key.type, - &prm->dst_host, &tmp_str); - if (status != PJ_SUCCESS) - goto on_return; - pj_strdup(pool, &prm->ret_addr, &tmp_str); - prm->ret_port = pj_sockaddr_get_port(&tp->local_addr); - prm->ret_tp = tp; - } else { - pj_strdup(pool, &prm->ret_addr, &tp->local_name.host); - prm->ret_port = (pj_uint16_t)tp->local_name.port; - } - - pjsip_transport_dec_ref(tp); - } + pj_sockaddr remote; + int addr_len; + pjsip_transport *tp; + + pj_bzero(&remote, sizeof(remote)); + if (prm->tp_type & PJSIP_TRANSPORT_IPV6) { + addr_len = sizeof(pj_sockaddr_in6); + remote.addr.sa_family = pj_AF_INET6(); + } else { + addr_len = sizeof(pj_sockaddr_in); + remote.addr.sa_family = pj_AF_INET(); + } + + status = pjsip_tpmgr_acquire_transport(tpmgr, prm->tp_type, &remote, + addr_len, NULL, &tp); + + if (status == PJ_SUCCESS) { + if (prm->local_if) { + status = get_net_interface((pjsip_transport_type_e) + tp->key.type, + &prm->dst_host, &tmp_str); + if (status != PJ_SUCCESS) + goto on_return; + pj_strdup(pool, &prm->ret_addr, &tmp_str); + prm->ret_port = pj_sockaddr_get_port(&tp->local_addr); + prm->ret_tp = tp; + } else { + pj_strdup(pool, &prm->ret_addr, &tp->local_name.host); + prm->ret_port = (pj_uint16_t)tp->local_name.port; + } + + pjsip_transport_dec_ref(tp); + } } else { - /* For connection oriented transport, enum the factories */ - pjsip_tpfactory *f; - - pj_lock_acquire(tpmgr->lock); - - f = tpmgr->factory_list.next; - while (f != &tpmgr->factory_list) { - if (f->type == prm->tp_type) - break; - f = f->next; - } - - if (f != &tpmgr->factory_list) { - if (prm->local_if) { - status = get_net_interface(f->type, &prm->dst_host, - &tmp_str); - if (status == PJ_SUCCESS) { - pj_strdup(pool, &prm->ret_addr, &tmp_str); - } else { - /* It could fail "normally" on certain cases, e.g. - * when connecting to IPv6 link local address, it - * will wail with EINVAL. - * In this case, fallback to use the default interface - * rather than failing the call. - */ - PJ_PERROR(5,(THIS_FILE, status, "Warning: unable to " - "determine local interface")); - pj_strdup(pool, &prm->ret_addr, &f->addr_name.host); - status = PJ_SUCCESS; - } - } else { - pj_strdup(pool, &prm->ret_addr, &f->addr_name.host); - } - prm->ret_port = (pj_uint16_t)f->addr_name.port; - status = PJ_SUCCESS; - } - pj_lock_release(tpmgr->lock); + /* For connection oriented transport, enum the factories */ + pjsip_tpfactory *f; + + pj_lock_acquire(tpmgr->lock); + + f = tpmgr->factory_list.next; + while (f != &tpmgr->factory_list) { + if (f->type == prm->tp_type) + break; + f = f->next; + } + + if (f != &tpmgr->factory_list) { + if (prm->local_if) { + status = get_net_interface(f->type, &prm->dst_host, + &tmp_str); + if (status == PJ_SUCCESS) { + pj_strdup(pool, &prm->ret_addr, &tmp_str); + } else { + /* It could fail "normally" on certain cases, e.g. + * when connecting to IPv6 link local address, it + * will wail with EINVAL. + * In this case, fallback to use the default interface + * rather than failing the call. + */ + PJ_PERROR(5,(THIS_FILE, status, "Warning: unable to " + "determine local interface")); + pj_strdup(pool, &prm->ret_addr, &f->addr_name.host); + status = PJ_SUCCESS; + } + } else { + pj_strdup(pool, &prm->ret_addr, &f->addr_name.host); + } + prm->ret_port = (pj_uint16_t)f->addr_name.port; + status = PJ_SUCCESS; + } + pj_lock_release(tpmgr->lock); } on_return: @@ -1805,11 +1804,11 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_find_local_addr2(pjsip_tpmgr *tpmgr, } PJ_DEF(pj_status_t) pjsip_tpmgr_find_local_addr( pjsip_tpmgr *tpmgr, - pj_pool_t *pool, - pjsip_transport_type_e type, - const pjsip_tpselector *sel, - pj_str_t *ip_addr, - int *port) + pj_pool_t *pool, + pjsip_transport_type_e type, + const pjsip_tpselector *sel, + pj_str_t *ip_addr, + int *port) { pjsip_tpmgr_fla2_param prm; pj_status_t status; @@ -1820,7 +1819,7 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_find_local_addr( pjsip_tpmgr *tpmgr, status = pjsip_tpmgr_find_local_addr2(tpmgr, pool, &prm); if (status != PJ_SUCCESS) - return status; + return status; *ip_addr = prm.ret_addr; *port = prm.ret_port; @@ -1842,9 +1841,9 @@ PJ_DEF(unsigned) pjsip_tpmgr_get_transport_count(pjsip_tpmgr *mgr) itr = pj_hash_first(mgr->table, &itr_val); while (itr) { - transport *tp_entry = (transport *)pj_hash_this(mgr->table, itr); - nr_of_transports += (int)pj_list_size(tp_entry); - itr = pj_hash_next(mgr->table, itr); + transport *tp_entry = (transport *)pj_hash_this(mgr->table, itr); + nr_of_transports += (int)pj_list_size(tp_entry); + itr = pj_hash_next(mgr->table, itr); } pj_lock_release(mgr->lock); @@ -1872,11 +1871,11 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_destroy( pjsip_tpmgr *mgr ) * Destroy all transports in the hash table. */ for (itr = pj_hash_first(mgr->table, &itr_val); itr; - itr = pj_hash_first(mgr->table, &itr_val)) + itr = pj_hash_first(mgr->table, &itr_val)) { - transport *tp_ref; - tp_ref = pj_hash_this(mgr->table, itr); - destroy_transport(mgr, tp_ref->tp); + transport *tp_ref; + tp_ref = pj_hash_this(mgr->table, itr); + destroy_transport(mgr, tp_ref->tp); } /* @@ -1884,11 +1883,11 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_destroy( pjsip_tpmgr *mgr ) */ factory = mgr->factory_list.next; while (factory != &mgr->factory_list) { - pjsip_tpfactory *next = factory->next; + pjsip_tpfactory *next = factory->next; - factory->destroy(factory); + factory->destroy(factory); - factory = next; + factory = next; } pj_lock_release(mgr->lock); @@ -1900,8 +1899,8 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_destroy( pjsip_tpmgr *mgr ) */ //pj_assert(pj_atomic_get(mgr->tdata_counter) == 0); if (pj_atomic_get(mgr->tdata_counter) != 0) { - PJ_LOG(3,(THIS_FILE, "Warning: %d transmit buffer(s) not freed!", - pj_atomic_get(mgr->tdata_counter))); + PJ_LOG(3,(THIS_FILE, "Warning: %d transmit buffer(s) not freed!", + pj_atomic_get(mgr->tdata_counter))); } #endif @@ -1909,13 +1908,13 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_destroy( pjsip_tpmgr *mgr ) * Destroy any dangling transmit buffer. */ if (!pj_list_empty(&mgr->tdata_list)) { - pjsip_tx_data *tdata = mgr->tdata_list.next; - while (tdata != &mgr->tdata_list) { - pjsip_tx_data *next = tdata->next; - tx_data_destroy(tdata); - tdata = next; - } - PJ_LOG(3,(THIS_FILE, "Cleaned up dangling transmit buffer(s).")); + pjsip_tx_data *tdata = mgr->tdata_list.next; + while (tdata != &mgr->tdata_list) { + pjsip_tx_data *next = tdata->next; + tx_data_destroy(tdata); + tdata = next; + } + PJ_LOG(3,(THIS_FILE, "Cleaned up dangling transmit buffer(s).")); } #if defined(PJ_DEBUG) && PJ_DEBUG!=0 @@ -1926,11 +1925,11 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_destroy( pjsip_tpmgr *mgr ) /* Unregister mod_msg_print. */ if (mod_msg_print.id != -1) { - pjsip_endpt_unregister_module(endpt, &mod_msg_print); + pjsip_endpt_unregister_module(endpt, &mod_msg_print); } if (mgr->pool) { - pjsip_endpt_release_pool( mgr->endpt, mgr->pool ); + pjsip_endpt_release_pool( mgr->endpt, mgr->pool ); } return PJ_SUCCESS; @@ -1943,7 +1942,7 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_destroy( pjsip_tpmgr *mgr ) * Called by tranports when they receive a new packet. */ PJ_DEF(pj_ssize_t) pjsip_tpmgr_receive_packet( pjsip_tpmgr *mgr, - pjsip_rx_data *rdata) + pjsip_rx_data *rdata) { pjsip_transport *tr = rdata->tp_info.transport; @@ -1954,7 +1953,7 @@ PJ_DEF(pj_ssize_t) pjsip_tpmgr_receive_packet( pjsip_tpmgr *mgr, /* Check size. */ pj_assert(rdata->pkt_info.len > 0); if (rdata->pkt_info.len <= 0) - return -1; + return -1; current_pkt = rdata->pkt_info.packet; remaining_len = rdata->pkt_info.len; @@ -1970,242 +1969,242 @@ PJ_DEF(pj_ssize_t) pjsip_tpmgr_receive_packet( pjsip_tpmgr *mgr, /* Process all message fragments. */ while (remaining_len > 0) { - pjsip_msg *msg; - char *p, *end; - char saved; - pj_size_t msg_fragment_size; - - /* Skip leading newlines as pjsip_find_msg() currently can't - * handle leading newlines. - */ - for (p=current_pkt, end=p+remaining_len; p!=end; ++p) { - if (*p != '\r' && *p != '\n') - break; - } - if (p!=current_pkt) { - remaining_len -= (p - current_pkt); - total_processed += (p - current_pkt); - - /* Notify application about the dropped newlines */ - if (mgr->tp_drop_data_cb) { - pjsip_tp_dropped_data dd; - pj_bzero(&dd, sizeof(dd)); - dd.tp = tr; - dd.data = current_pkt; - dd.len = p - current_pkt; - dd.status = PJ_EIGNORED; - (*mgr->tp_drop_data_cb)(&dd); - } - - current_pkt = p; - if (remaining_len == 0) { - return total_processed; - } - } - - /* Initialize default fragment size. */ - msg_fragment_size = remaining_len; - - /* Clear and init msg_info in rdata. - * Endpoint might inspect the values there when we call the callback - * to report some errors. - */ - pj_bzero(&rdata->msg_info, sizeof(rdata->msg_info)); - pj_list_init(&rdata->msg_info.parse_err); - rdata->msg_info.msg_buf = current_pkt; - rdata->msg_info.len = (int)remaining_len; - - /* For TCP transport, check if the whole message has been received. */ - if ((tr->flag & PJSIP_TRANSPORT_DATAGRAM) == 0) { - pj_status_t msg_status; - msg_status = pjsip_find_msg(current_pkt, remaining_len, PJ_FALSE, + pjsip_msg *msg; + char *p, *end; + char saved; + pj_size_t msg_fragment_size; + + /* Skip leading newlines as pjsip_find_msg() currently can't + * handle leading newlines. + */ + for (p=current_pkt, end=p+remaining_len; p!=end; ++p) { + if (*p != '\r' && *p != '\n') + break; + } + if (p!=current_pkt) { + remaining_len -= (p - current_pkt); + total_processed += (p - current_pkt); + + /* Notify application about the dropped newlines */ + if (mgr->tp_drop_data_cb) { + pjsip_tp_dropped_data dd; + pj_bzero(&dd, sizeof(dd)); + dd.tp = tr; + dd.data = current_pkt; + dd.len = p - current_pkt; + dd.status = PJ_EIGNORED; + (*mgr->tp_drop_data_cb)(&dd); + } + + current_pkt = p; + if (remaining_len == 0) { + return total_processed; + } + } + + /* Initialize default fragment size. */ + msg_fragment_size = remaining_len; + + /* Clear and init msg_info in rdata. + * Endpoint might inspect the values there when we call the callback + * to report some errors. + */ + pj_bzero(&rdata->msg_info, sizeof(rdata->msg_info)); + pj_list_init(&rdata->msg_info.parse_err); + rdata->msg_info.msg_buf = current_pkt; + rdata->msg_info.len = (int)remaining_len; + + /* For TCP transport, check if the whole message has been received. */ + if ((tr->flag & PJSIP_TRANSPORT_DATAGRAM) == 0) { + pj_status_t msg_status; + msg_status = pjsip_find_msg(current_pkt, remaining_len, PJ_FALSE, &msg_fragment_size); - if (msg_status != PJ_SUCCESS) { - if (remaining_len == PJSIP_MAX_PKT_LEN) { - mgr->on_rx_msg(mgr->endpt, PJSIP_ERXOVERFLOW, rdata); - - /* Notify application about the message overflow */ - if (mgr->tp_drop_data_cb) { - pjsip_tp_dropped_data dd; - pj_bzero(&dd, sizeof(dd)); - dd.tp = tr; - dd.data = current_pkt; - dd.len = msg_fragment_size; - dd.status = PJSIP_ERXOVERFLOW; - (*mgr->tp_drop_data_cb)(&dd); - } - - /* Exhaust all data. */ - return rdata->pkt_info.len; - } else { - /* Not enough data in packet. */ - return total_processed; - } - } - } - - /* Update msg_info. */ - rdata->msg_info.len = (int)msg_fragment_size; - - /* Null terminate packet */ - saved = current_pkt[msg_fragment_size]; - current_pkt[msg_fragment_size] = '\0'; - - /* Parse the message. */ - rdata->msg_info.msg = msg = - pjsip_parse_rdata( current_pkt, msg_fragment_size, rdata); - - /* Restore null termination */ - current_pkt[msg_fragment_size] = saved; - - /* Check for parsing syntax error */ - if (msg==NULL || !pj_list_empty(&rdata->msg_info.parse_err)) { - pjsip_parser_err_report *err; - char buf[256]; - pj_str_t tmp; - - /* Gather syntax error information */ - tmp.ptr = buf; tmp.slen = 0; - err = rdata->msg_info.parse_err.next; - while (err != &rdata->msg_info.parse_err) { - int len; - len = pj_ansi_snprintf(tmp.ptr+tmp.slen, sizeof(buf)-tmp.slen, - ": %s exception when parsing '%.*s' " - "header on line %d col %d", - pj_exception_id_name(err->except_code), - (int)err->hname.slen, err->hname.ptr, - err->line, err->col); - if (len >= (int)sizeof(buf)-(int)tmp.slen) { - len = (int)sizeof(buf)-(int)tmp.slen; - } - if (len > 0) { - tmp.slen += len; - } - err = err->next; - } - - /* Only print error message if there's error. - * Sometimes we receive blank packets (packets with only CRLF) - * which were sent to keep NAT bindings. - */ - if (tmp.slen) { - PJ_LOG(1, (THIS_FILE, - "Error processing %d bytes packet from %s %s:%d %.*s:\n" - "%.*s\n" - "-- end of packet.", - msg_fragment_size, - rdata->tp_info.transport->type_name, - rdata->pkt_info.src_name, - rdata->pkt_info.src_port, - (int)tmp.slen, tmp.ptr, - (int)msg_fragment_size, - rdata->msg_info.msg_buf)); - } - - /* Notify application about the dropped data (syntax error) */ - if (tmp.slen && mgr->tp_drop_data_cb) { - pjsip_tp_dropped_data dd; - pj_bzero(&dd, sizeof(dd)); - dd.tp = tr; - dd.data = current_pkt; - dd.len = msg_fragment_size; - dd.status = PJSIP_EINVALIDMSG; - (*mgr->tp_drop_data_cb)(&dd); - - if (dd.len > 0 && dd.len < msg_fragment_size) - msg_fragment_size = dd.len; - } - - goto finish_process_fragment; - } - - /* Perform basic header checking. */ - if (rdata->msg_info.cid == NULL || - rdata->msg_info.cid->id.slen == 0 || - rdata->msg_info.from == NULL || - rdata->msg_info.to == NULL || - rdata->msg_info.via == NULL || - rdata->msg_info.cseq == NULL) - { - mgr->on_rx_msg(mgr->endpt, PJSIP_EMISSINGHDR, rdata); - - /* Notify application about the missing header. */ - if (mgr->tp_drop_data_cb) { - pjsip_tp_dropped_data dd; - pj_bzero(&dd, sizeof(dd)); - dd.tp = tr; - dd.data = current_pkt; - dd.len = msg_fragment_size; - dd.status = PJSIP_EMISSINGHDR; - (*mgr->tp_drop_data_cb)(&dd); - } - goto finish_process_fragment; - } - - /* For request: */ - if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) { - /* always add received parameter to the via. */ - pj_strdup2(rdata->tp_info.pool, - &rdata->msg_info.via->recvd_param, - rdata->pkt_info.src_name); - - /* RFC 3581: - * If message contains "rport" param, put the received port there. - */ - if (rdata->msg_info.via->rport_param == 0) { - rdata->msg_info.via->rport_param = rdata->pkt_info.src_port; - } - } else { - /* Drop malformed responses */ - if (rdata->msg_info.msg->line.status.code < 100 || - rdata->msg_info.msg->line.status.code >= 700) - { - mgr->on_rx_msg(mgr->endpt, PJSIP_EINVALIDSTATUS, rdata); - - /* Notify application about the invalid status. */ - if (mgr->tp_drop_data_cb) { - pjsip_tp_dropped_data dd; - pj_bzero(&dd, sizeof(dd)); - dd.tp = tr; - dd.data = current_pkt; - dd.len = msg_fragment_size; - dd.status = PJSIP_EINVALIDSTATUS; - (*mgr->tp_drop_data_cb)(&dd); - } - goto finish_process_fragment; - } - } - - /* Drop response message if it has more than one Via. - */ - /* This is wrong. Proxy DOES receive responses with multiple - * Via headers! Thanks Aldo for pointing - * this out. - - if (msg->type == PJSIP_RESPONSE_MSG) { - pjsip_hdr *hdr; - hdr = (pjsip_hdr*)rdata->msg_info.via->next; - if (hdr != &msg->hdr) { - hdr = pjsip_msg_find_hdr(msg, PJSIP_H_VIA, hdr); - if (hdr) { - mgr->on_rx_msg(mgr->endpt, PJSIP_EMULTIPLEVIA, rdata); - goto finish_process_fragment; - } - } - } - */ - - /* Call the transport manager's upstream message callback. - */ - mgr->on_rx_msg(mgr->endpt, PJ_SUCCESS, rdata); + if (msg_status != PJ_SUCCESS) { + if (remaining_len == PJSIP_MAX_PKT_LEN) { + mgr->on_rx_msg(mgr->endpt, PJSIP_ERXOVERFLOW, rdata); + + /* Notify application about the message overflow */ + if (mgr->tp_drop_data_cb) { + pjsip_tp_dropped_data dd; + pj_bzero(&dd, sizeof(dd)); + dd.tp = tr; + dd.data = current_pkt; + dd.len = msg_fragment_size; + dd.status = PJSIP_ERXOVERFLOW; + (*mgr->tp_drop_data_cb)(&dd); + } + + /* Exhaust all data. */ + return rdata->pkt_info.len; + } else { + /* Not enough data in packet. */ + return total_processed; + } + } + } + + /* Update msg_info. */ + rdata->msg_info.len = (int)msg_fragment_size; + + /* Null terminate packet */ + saved = current_pkt[msg_fragment_size]; + current_pkt[msg_fragment_size] = '\0'; + + /* Parse the message. */ + rdata->msg_info.msg = msg = + pjsip_parse_rdata( current_pkt, msg_fragment_size, rdata); + + /* Restore null termination */ + current_pkt[msg_fragment_size] = saved; + + /* Check for parsing syntax error */ + if (msg==NULL || !pj_list_empty(&rdata->msg_info.parse_err)) { + pjsip_parser_err_report *err; + char buf[256]; + pj_str_t tmp; + + /* Gather syntax error information */ + tmp.ptr = buf; tmp.slen = 0; + err = rdata->msg_info.parse_err.next; + while (err != &rdata->msg_info.parse_err) { + int len; + len = pj_ansi_snprintf(tmp.ptr+tmp.slen, sizeof(buf)-tmp.slen, + ": %s exception when parsing '%.*s' " + "header on line %d col %d", + pj_exception_id_name(err->except_code), + (int)err->hname.slen, err->hname.ptr, + err->line, err->col); + if (len >= (int)sizeof(buf)-(int)tmp.slen) { + len = (int)sizeof(buf)-(int)tmp.slen; + } + if (len > 0) { + tmp.slen += len; + } + err = err->next; + } + + /* Only print error message if there's error. + * Sometimes we receive blank packets (packets with only CRLF) + * which were sent to keep NAT bindings. + */ + if (tmp.slen) { + PJ_LOG(1, (THIS_FILE, + "Error processing %d bytes packet from %s %s:%d %.*s:\n" + "%.*s\n" + "-- end of packet.", + msg_fragment_size, + rdata->tp_info.transport->type_name, + rdata->pkt_info.src_name, + rdata->pkt_info.src_port, + (int)tmp.slen, tmp.ptr, + (int)msg_fragment_size, + rdata->msg_info.msg_buf)); + } + + /* Notify application about the dropped data (syntax error) */ + if (tmp.slen && mgr->tp_drop_data_cb) { + pjsip_tp_dropped_data dd; + pj_bzero(&dd, sizeof(dd)); + dd.tp = tr; + dd.data = current_pkt; + dd.len = msg_fragment_size; + dd.status = PJSIP_EINVALIDMSG; + (*mgr->tp_drop_data_cb)(&dd); + + if (dd.len > 0 && dd.len < msg_fragment_size) + msg_fragment_size = dd.len; + } + + goto finish_process_fragment; + } + + /* Perform basic header checking. */ + if (rdata->msg_info.cid == NULL || + rdata->msg_info.cid->id.slen == 0 || + rdata->msg_info.from == NULL || + rdata->msg_info.to == NULL || + rdata->msg_info.via == NULL || + rdata->msg_info.cseq == NULL) + { + mgr->on_rx_msg(mgr->endpt, PJSIP_EMISSINGHDR, rdata); + + /* Notify application about the missing header. */ + if (mgr->tp_drop_data_cb) { + pjsip_tp_dropped_data dd; + pj_bzero(&dd, sizeof(dd)); + dd.tp = tr; + dd.data = current_pkt; + dd.len = msg_fragment_size; + dd.status = PJSIP_EMISSINGHDR; + (*mgr->tp_drop_data_cb)(&dd); + } + goto finish_process_fragment; + } + + /* For request: */ + if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) { + /* always add received parameter to the via. */ + pj_strdup2(rdata->tp_info.pool, + &rdata->msg_info.via->recvd_param, + rdata->pkt_info.src_name); + + /* RFC 3581: + * If message contains "rport" param, put the received port there. + */ + if (rdata->msg_info.via->rport_param == 0) { + rdata->msg_info.via->rport_param = rdata->pkt_info.src_port; + } + } else { + /* Drop malformed responses */ + if (rdata->msg_info.msg->line.status.code < 100 || + rdata->msg_info.msg->line.status.code >= 700) + { + mgr->on_rx_msg(mgr->endpt, PJSIP_EINVALIDSTATUS, rdata); + + /* Notify application about the invalid status. */ + if (mgr->tp_drop_data_cb) { + pjsip_tp_dropped_data dd; + pj_bzero(&dd, sizeof(dd)); + dd.tp = tr; + dd.data = current_pkt; + dd.len = msg_fragment_size; + dd.status = PJSIP_EINVALIDSTATUS; + (*mgr->tp_drop_data_cb)(&dd); + } + goto finish_process_fragment; + } + } + + /* Drop response message if it has more than one Via. + */ + /* This is wrong. Proxy DOES receive responses with multiple + * Via headers! Thanks Aldo for pointing + * this out. + + if (msg->type == PJSIP_RESPONSE_MSG) { + pjsip_hdr *hdr; + hdr = (pjsip_hdr*)rdata->msg_info.via->next; + if (hdr != &msg->hdr) { + hdr = pjsip_msg_find_hdr(msg, PJSIP_H_VIA, hdr); + if (hdr) { + mgr->on_rx_msg(mgr->endpt, PJSIP_EMULTIPLEVIA, rdata); + goto finish_process_fragment; + } + } + } + */ + + /* Call the transport manager's upstream message callback. + */ + mgr->on_rx_msg(mgr->endpt, PJ_SUCCESS, rdata); finish_process_fragment: - total_processed += msg_fragment_size; - current_pkt += msg_fragment_size; - remaining_len -= msg_fragment_size; + total_processed += msg_fragment_size; + current_pkt += msg_fragment_size; + remaining_len -= msg_fragment_size; - } /* while (rdata->pkt_info.len > 0) */ + } /* while (rdata->pkt_info.len > 0) */ return total_processed; @@ -2219,14 +2218,14 @@ PJ_DEF(pj_ssize_t) pjsip_tpmgr_receive_packet( pjsip_tpmgr *mgr, * if necessary. */ PJ_DEF(pj_status_t) pjsip_tpmgr_acquire_transport(pjsip_tpmgr *mgr, - pjsip_transport_type_e type, - const pj_sockaddr_t *remote, - int addr_len, - const pjsip_tpselector *sel, - pjsip_transport **tp) + pjsip_transport_type_e type, + const pj_sockaddr_t *remote, + int addr_len, + const pjsip_tpselector *sel, + pjsip_transport **tp) { return pjsip_tpmgr_acquire_transport2(mgr, type, remote, addr_len, sel, - NULL, tp); + NULL, tp); } @@ -2237,21 +2236,21 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_acquire_transport(pjsip_tpmgr *mgr, * if necessary. */ PJ_DEF(pj_status_t) pjsip_tpmgr_acquire_transport2(pjsip_tpmgr *mgr, - pjsip_transport_type_e type, - const pj_sockaddr_t *remote, - int addr_len, - const pjsip_tpselector *sel, - pjsip_tx_data *tdata, - pjsip_transport **tp) + pjsip_transport_type_e type, + const pj_sockaddr_t *remote, + int addr_len, + const pjsip_tpselector *sel, + pjsip_tx_data *tdata, + pjsip_transport **tp) { pjsip_tpfactory *factory; pj_status_t status; TRACE_((THIS_FILE,"Acquiring transport type=%s, sel=%s remote=%s:%d", - pjsip_transport_get_type_name(type), - print_tpsel_info(sel), - addr_string(remote), - pj_sockaddr_get_port(remote))); + pjsip_transport_get_type_name(type), + print_tpsel_info(sel), + addr_string(remote), + pj_sockaddr_get_port(remote))); pj_lock_acquire(mgr->lock); @@ -2259,253 +2258,253 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_acquire_transport2(pjsip_tpmgr *mgr, * for the destination. */ if (sel && sel->type == PJSIP_TPSELECTOR_TRANSPORT && - sel->u.transport) + sel->u.transport) { - pjsip_transport *seltp = sel->u.transport; - - /* See if the transport is (not) suitable */ - if (seltp->key.type != type) { - pj_lock_release(mgr->lock); - TRACE_((THIS_FILE, "Transport type in tpsel not matched")); - return PJSIP_ETPNOTSUITABLE; - } - - /* Make sure the transport is not being destroyed */ - if (seltp->is_destroying) { - pj_lock_release(mgr->lock); - TRACE_((THIS_FILE,"Transport to be acquired is being destroyed")); - return PJ_ENOTFOUND; - } - - /* We could also verify that the destination address is reachable - * from this transport (i.e. both are equal), but if application - * has requested a specific transport to be used, assume that - * it knows what to do. - * - * In other words, I don't think destination verification is a good - * idea for now. - */ - - /* Transport looks to be suitable to use, so just use it. */ - pjsip_transport_add_ref(seltp); - pj_lock_release(mgr->lock); - *tp = seltp; - - TRACE_((THIS_FILE, "Transport %s acquired", seltp->obj_name)); - return PJ_SUCCESS; + pjsip_transport *seltp = sel->u.transport; + + /* See if the transport is (not) suitable */ + if (seltp->key.type != type) { + pj_lock_release(mgr->lock); + TRACE_((THIS_FILE, "Transport type in tpsel not matched")); + return PJSIP_ETPNOTSUITABLE; + } + + /* Make sure the transport is not being destroyed */ + if (seltp->is_destroying) { + pj_lock_release(mgr->lock); + TRACE_((THIS_FILE,"Transport to be acquired is being destroyed")); + return PJ_ENOTFOUND; + } + + /* We could also verify that the destination address is reachable + * from this transport (i.e. both are equal), but if application + * has requested a specific transport to be used, assume that + * it knows what to do. + * + * In other words, I don't think destination verification is a good + * idea for now. + */ + + /* Transport looks to be suitable to use, so just use it. */ + pjsip_transport_add_ref(seltp); + pj_lock_release(mgr->lock); + *tp = seltp; + + TRACE_((THIS_FILE, "Transport %s acquired", seltp->obj_name)); + return PJ_SUCCESS; } else { - /* - * This is the "normal" flow, where application doesn't specify - * specific transport to be used to send message to. - * In this case, lookup the transport from the hash table. - */ - pjsip_transport_key key; - int key_len; - pjsip_transport *tp_ref = NULL; - transport *tp_entry = NULL; - unsigned flag = pjsip_transport_get_flag_from_type(type); - - /* If listener is specified, verify that the listener type matches - * the destination type. - */ - if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && sel->u.listener) - { - if (sel->u.listener->type != type) { - pj_lock_release(mgr->lock); - TRACE_((THIS_FILE, "Listener type in tpsel not matched")); - return PJSIP_ETPNOTSUITABLE; - } - } - - if (!sel || sel->disable_connection_reuse == PJ_FALSE) { - pj_bzero(&key, sizeof(key)); - key_len = sizeof(key.type) + addr_len; - - /* First try to get exact destination. */ - key.type = type; - pj_memcpy(&key.rem_addr, remote, addr_len); - - tp_entry = (transport *)pj_hash_get(mgr->table, &key, key_len, - NULL); - if (tp_entry) { - transport *tp_iter = tp_entry; - do { - /* Don't use transport being shutdown/destroyed */ - if (!tp_iter->tp->is_shutdown && - !tp_iter->tp->is_destroying) - { - if ((flag & PJSIP_TRANSPORT_SECURE) && tdata) { - /* For secure transport, make sure tdata's - * destination host matches the transport's - * remote host. - */ - if (pj_stricmp(&tdata->dest_info.name, - &tp_iter->tp->remote_name.host)) - { - tp_iter = tp_iter->next; - continue; - } - } - - if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && - sel->u.listener) - { - /* Match listener if selector is set */ - if (tp_iter->tp->factory == sel->u.listener) { - tp_ref = tp_iter->tp; - break; - } - } else { - tp_ref = tp_iter->tp; - break; - } - } - tp_iter = tp_iter->next; - } while (tp_iter != tp_entry); - } - } - - if (tp_ref == NULL && - (!sel || sel->disable_connection_reuse == PJ_FALSE)) - { - const pj_sockaddr *remote_addr = (const pj_sockaddr*)remote; - - - /* Ignore address for loop transports. */ - if (type == PJSIP_TRANSPORT_LOOP || - type == PJSIP_TRANSPORT_LOOP_DGRAM) - { - pj_sockaddr *addr = &key.rem_addr; - - pj_bzero(addr, addr_len); - key_len = sizeof(key.type) + addr_len; - tp_entry = (transport *) pj_hash_get(mgr->table, &key, - key_len, NULL); - if (tp_entry) { - tp_ref = tp_entry->tp; - } - } - /* For datagram transports, try lookup with zero address. - */ - else if (flag & PJSIP_TRANSPORT_DATAGRAM) - { - pj_sockaddr *addr = &key.rem_addr; - - pj_bzero(addr, addr_len); - addr->addr.sa_family = remote_addr->addr.sa_family; - - key_len = sizeof(key.type) + addr_len; - tp_entry = (transport *) pj_hash_get(mgr->table, &key, - key_len, NULL); - - while (tp_entry) { - tp_ref = tp_entry->tp; + /* + * This is the "normal" flow, where application doesn't specify + * specific transport to be used to send message to. + * In this case, lookup the transport from the hash table. + */ + pjsip_transport_key key; + int key_len; + pjsip_transport *tp_ref = NULL; + transport *tp_entry = NULL; + unsigned flag = pjsip_transport_get_flag_from_type(type); + + /* If listener is specified, verify that the listener type matches + * the destination type. + */ + if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && sel->u.listener) + { + if (sel->u.listener->type != type) { + pj_lock_release(mgr->lock); + TRACE_((THIS_FILE, "Listener type in tpsel not matched")); + return PJSIP_ETPNOTSUITABLE; + } + } + + if (!sel || sel->disable_connection_reuse == PJ_FALSE) { + pj_bzero(&key, sizeof(key)); + key_len = sizeof(key.type) + addr_len; + + /* First try to get exact destination. */ + key.type = type; + pj_memcpy(&key.rem_addr, remote, addr_len); + + tp_entry = (transport *)pj_hash_get(mgr->table, &key, key_len, + NULL); + if (tp_entry) { + transport *tp_iter = tp_entry; + do { + /* Don't use transport being shutdown/destroyed */ + if (!tp_iter->tp->is_shutdown && + !tp_iter->tp->is_destroying) + { + if ((flag & PJSIP_TRANSPORT_SECURE) && tdata) { + /* For secure transport, make sure tdata's + * destination host matches the transport's + * remote host. + */ + if (pj_stricmp(&tdata->dest_info.name, + &tp_iter->tp->remote_name.host)) + { + tp_iter = tp_iter->next; + continue; + } + } + + if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && + sel->u.listener) + { + /* Match listener if selector is set */ + if (tp_iter->tp->factory == sel->u.listener) { + tp_ref = tp_iter->tp; + break; + } + } else { + tp_ref = tp_iter->tp; + break; + } + } + tp_iter = tp_iter->next; + } while (tp_iter != tp_entry); + } + } + + if (tp_ref == NULL && + (!sel || sel->disable_connection_reuse == PJ_FALSE)) + { + const pj_sockaddr *remote_addr = (const pj_sockaddr*)remote; + + + /* Ignore address for loop transports. */ + if (type == PJSIP_TRANSPORT_LOOP || + type == PJSIP_TRANSPORT_LOOP_DGRAM) + { + pj_sockaddr *addr = &key.rem_addr; + + pj_bzero(addr, addr_len); + key_len = sizeof(key.type) + addr_len; + tp_entry = (transport *) pj_hash_get(mgr->table, &key, + key_len, NULL); + if (tp_entry) { + tp_ref = tp_entry->tp; + } + } + /* For datagram transports, try lookup with zero address. + */ + else if (flag & PJSIP_TRANSPORT_DATAGRAM) + { + pj_sockaddr *addr = &key.rem_addr; + + pj_bzero(addr, addr_len); + addr->addr.sa_family = remote_addr->addr.sa_family; + + key_len = sizeof(key.type) + addr_len; + tp_entry = (transport *) pj_hash_get(mgr->table, &key, + key_len, NULL); + + while (tp_entry) { + tp_ref = tp_entry->tp; if (!tp_ref->is_shutdown && !tp_ref->is_destroying) break; tp_entry = tp_entry->next; - } - } - } - - /* If transport is found and listener is specified, verify listener */ - else if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && - sel->u.listener && tp_ref->factory != sel->u.listener) - { - tp_ref = NULL; - /* This will cause a new transport to be created which will be a - * 'duplicate' of the existing transport (same type & remote addr, - * but different factory). - */ - TRACE_((THIS_FILE, "Transport found but from different listener")); - } - - if (tp_ref!=NULL && !tp_ref->is_shutdown && !tp_ref->is_destroying) { - /* - * Transport found! - */ - pjsip_transport_add_ref(tp_ref); - pj_lock_release(mgr->lock); - *tp = tp_ref; - - TRACE_((THIS_FILE, "Transport %s acquired", tp_ref->obj_name)); - return PJ_SUCCESS; - } - - - /* - * Either transport not found, or we don't want to use the existing - * transport (such as in the case of different factory or - * if connection reuse is disabled). So we need to create one, - * find factory that can create such transport. - * - * If there's an existing transport, its place in the hash table - * will be replaced by this new one. And eventually the existing - * transport will still be freed (by application or #1774). - */ - if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && sel->u.listener) - { - /* Application has requested that a specific listener is to - * be used. - */ - - /* Verify that the listener type matches the destination type */ - /* Already checked above. */ - /* - if (sel->u.listener->type != type) { - pj_lock_release(mgr->lock); - return PJSIP_ETPNOTSUITABLE; - } - */ - - /* We'll use this listener to create transport */ - factory = sel->u.listener; - - /* Verify if listener is still valid */ - if (!pjsip_tpmgr_is_tpfactory_valid(mgr, factory)) { - pj_lock_release(mgr->lock); - PJ_LOG(3,(THIS_FILE, "Specified factory for creating " - "transport is not found")); - return PJ_ENOTFOUND; - } - - } else { - - /* Find factory with type matches the destination type */ - factory = mgr->factory_list.next; - while (factory != &mgr->factory_list) { - if (factory->type == type) - break; - factory = factory->next; - } - - if (factory == &mgr->factory_list) { - /* No factory can create the transport! */ - pj_lock_release(mgr->lock); - TRACE_((THIS_FILE, "No suitable factory was found either")); - return PJSIP_EUNSUPTRANSPORT; - } - } + } + } + } + + /* If transport is found and listener is specified, verify listener */ + else if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && + sel->u.listener && tp_ref->factory != sel->u.listener) + { + tp_ref = NULL; + /* This will cause a new transport to be created which will be a + * 'duplicate' of the existing transport (same type & remote addr, + * but different factory). + */ + TRACE_((THIS_FILE, "Transport found but from different listener")); + } + + if (tp_ref!=NULL && !tp_ref->is_shutdown && !tp_ref->is_destroying) { + /* + * Transport found! + */ + pjsip_transport_add_ref(tp_ref); + pj_lock_release(mgr->lock); + *tp = tp_ref; + + TRACE_((THIS_FILE, "Transport %s acquired", tp_ref->obj_name)); + return PJ_SUCCESS; + } + + + /* + * Either transport not found, or we don't want to use the existing + * transport (such as in the case of different factory or + * if connection reuse is disabled). So we need to create one, + * find factory that can create such transport. + * + * If there's an existing transport, its place in the hash table + * will be replaced by this new one. And eventually the existing + * transport will still be freed (by application or #1774). + */ + if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && sel->u.listener) + { + /* Application has requested that a specific listener is to + * be used. + */ + + /* Verify that the listener type matches the destination type */ + /* Already checked above. */ + /* + if (sel->u.listener->type != type) { + pj_lock_release(mgr->lock); + return PJSIP_ETPNOTSUITABLE; + } + */ + + /* We'll use this listener to create transport */ + factory = sel->u.listener; + + /* Verify if listener is still valid */ + if (!pjsip_tpmgr_is_tpfactory_valid(mgr, factory)) { + pj_lock_release(mgr->lock); + PJ_LOG(3,(THIS_FILE, "Specified factory for creating " + "transport is not found")); + return PJ_ENOTFOUND; + } + + } else { + + /* Find factory with type matches the destination type */ + factory = mgr->factory_list.next; + while (factory != &mgr->factory_list) { + if (factory->type == type) + break; + factory = factory->next; + } + + if (factory == &mgr->factory_list) { + /* No factory can create the transport! */ + pj_lock_release(mgr->lock); + TRACE_((THIS_FILE, "No suitable factory was found either")); + return PJSIP_EUNSUPTRANSPORT; + } + } } TRACE_((THIS_FILE, "Creating new transport from factory")); /* Request factory to create transport. */ if (factory->create_transport2) { - status = factory->create_transport2(factory, mgr, mgr->endpt, - (const pj_sockaddr*) remote, - addr_len, tdata, tp); + status = factory->create_transport2(factory, mgr, mgr->endpt, + (const pj_sockaddr*) remote, + addr_len, tdata, tp); } else { - status = factory->create_transport(factory, mgr, mgr->endpt, - (const pj_sockaddr*) remote, - addr_len, tp); + status = factory->create_transport(factory, mgr, mgr->endpt, + (const pj_sockaddr*) remote, + addr_len, tp); } if (status == PJ_SUCCESS) { - PJ_ASSERT_ON_FAIL(tp!=NULL, - {pj_lock_release(mgr->lock); return PJ_EBUG;}); - pjsip_transport_add_ref(*tp); - (*tp)->factory = factory; + PJ_ASSERT_ON_FAIL(tp!=NULL, + {pj_lock_release(mgr->lock); return PJ_EBUG;}); + pjsip_transport_add_ref(*tp); + (*tp)->factory = factory; } pj_lock_release(mgr->lock); return status; @@ -2525,47 +2524,47 @@ PJ_DEF(void) pjsip_tpmgr_dump_transports(pjsip_tpmgr *mgr) #if defined(PJ_DEBUG) && PJ_DEBUG!=0 PJ_LOG(3,(THIS_FILE, " Outstanding transmit buffers: %d", - pj_atomic_get(mgr->tdata_counter))); + pj_atomic_get(mgr->tdata_counter))); #endif PJ_LOG(3, (THIS_FILE, " Dumping listeners:")); factory = mgr->factory_list.next; while (factory != &mgr->factory_list) { - PJ_LOG(3, (THIS_FILE, " %s %s:%.*s:%d", - factory->obj_name, - factory->type_name, - (int)factory->addr_name.host.slen, - factory->addr_name.host.ptr, - (int)factory->addr_name.port)); - factory = factory->next; + PJ_LOG(3, (THIS_FILE, " %s %s:%.*s:%d", + factory->obj_name, + factory->type_name, + (int)factory->addr_name.host.slen, + factory->addr_name.host.ptr, + (int)factory->addr_name.port)); + factory = factory->next; } itr = pj_hash_first(mgr->table, &itr_val); if (itr) { - PJ_LOG(3, (THIS_FILE, " Dumping transports:")); - - do { - transport *tp_entry = (transport *) pj_hash_this(mgr->table, itr); - if (tp_entry) { - transport *tp_iter = tp_entry; - - do { - pjsip_transport *tp_ref = tp_iter->tp; - - PJ_LOG(3, (THIS_FILE, " %s %s%s%s%s(refcnt=%d%s)", - tp_ref->obj_name, - tp_ref->info, - (tp_ref->factory)?" listener[":"", - (tp_ref->factory)?tp_ref->factory->obj_name:"", - (tp_ref->factory)?"]":"", - pj_atomic_get(tp_ref->ref_cnt), - (tp_ref->idle_timer.id ? " [idle]" : ""))); - - tp_iter = tp_iter->next; - } while (tp_iter != tp_entry); - } - itr = pj_hash_next(mgr->table, itr); - } while (itr); + PJ_LOG(3, (THIS_FILE, " Dumping transports:")); + + do { + transport *tp_entry = (transport *) pj_hash_this(mgr->table, itr); + if (tp_entry) { + transport *tp_iter = tp_entry; + + do { + pjsip_transport *tp_ref = tp_iter->tp; + + PJ_LOG(3, (THIS_FILE, " %s %s%s%s%s(refcnt=%d%s)", + tp_ref->obj_name, + tp_ref->info, + (tp_ref->factory)?" listener[":"", + (tp_ref->factory)?tp_ref->factory->obj_name:"", + (tp_ref->factory)?"]":"", + pj_atomic_get(tp_ref->ref_cnt), + (tp_ref->idle_timer.id ? " [idle]" : ""))); + + tp_iter = tp_iter->next; + } while (tp_iter != tp_entry); + } + itr = pj_hash_next(mgr->table, itr); + } while (itr); } pj_lock_release(mgr->lock); @@ -2578,7 +2577,7 @@ PJ_DEF(void) pjsip_tpmgr_dump_transports(pjsip_tpmgr *mgr) * Set callback of global transport state notification. */ PJ_DEF(pj_status_t) pjsip_tpmgr_set_state_cb(pjsip_tpmgr *mgr, - pjsip_tp_state_callback cb) + pjsip_tp_state_callback cb) { PJ_ASSERT_RETURN(mgr, PJ_EINVAL); @@ -2591,7 +2590,7 @@ PJ_DEF(pj_status_t) pjsip_tpmgr_set_state_cb(pjsip_tpmgr *mgr, * Get callback of global transport state notification. */ PJ_DEF(pjsip_tp_state_callback) pjsip_tpmgr_get_state_cb( - const pjsip_tpmgr *mgr) + const pjsip_tpmgr *mgr) { PJ_ASSERT_RETURN(mgr, NULL); @@ -2616,8 +2615,8 @@ static void init_tp_data(pjsip_transport *tp) static void tp_state_callback(pjsip_transport *tp, - pjsip_transport_state state, - const pjsip_transport_state_info *info) + pjsip_transport_state state, + const pjsip_transport_state_info *info) { transport_data *tp_data; @@ -2627,21 +2626,21 @@ static void tp_state_callback(pjsip_transport *tp, /* Notify the transport state listeners, if any. */ if (!tp_data || pj_list_empty(&tp_data->st_listeners)) { - goto on_return; + goto on_return; } else { - pjsip_transport_state_info st_info; - tp_state_listener *st_listener = tp_data->st_listeners.next; - - /* As we need to put the user data into the transport state info, - * let's use a copy of transport state info. - */ - pj_memcpy(&st_info, info, sizeof(st_info)); - while (st_listener != &tp_data->st_listeners) { - st_info.user_data = st_listener->user_data; - (*st_listener->cb)(tp, state, &st_info); - - st_listener = st_listener->next; - } + pjsip_transport_state_info st_info; + tp_state_listener *st_listener = tp_data->st_listeners.next; + + /* As we need to put the user data into the transport state info, + * let's use a copy of transport state info. + */ + pj_memcpy(&st_info, info, sizeof(st_info)); + while (st_listener != &tp_data->st_listeners) { + st_info.user_data = st_listener->user_data; + (*st_listener->cb)(tp, state, &st_info); + + st_listener = st_listener->next; + } } on_return: @@ -2653,10 +2652,10 @@ static void tp_state_callback(pjsip_transport *tp, * Add a listener to the specified transport for transport state notification. */ PJ_DEF(pj_status_t) pjsip_transport_add_state_listener ( - pjsip_transport *tp, - pjsip_tp_state_callback cb, - void *user_data, - pjsip_tp_state_listener_key **key) + pjsip_transport *tp, + pjsip_tp_state_callback cb, + void *user_data, + pjsip_tp_state_listener_key **key) { transport_data *tp_data; tp_state_listener *entry; @@ -2664,15 +2663,15 @@ PJ_DEF(pj_status_t) pjsip_transport_add_state_listener ( PJ_ASSERT_RETURN(tp && cb && key, PJ_EINVAL); if (tp->is_shutdown || tp->is_destroying) { - *key = NULL; - return PJ_EINVALIDOP; + *key = NULL; + return PJ_EINVALIDOP; } pj_lock_acquire(tp->lock); /* Init transport data, if it hasn't */ if (!tp->data) - init_tp_data(tp); + init_tp_data(tp); tp_data = (transport_data*)tp->data; @@ -2680,10 +2679,10 @@ PJ_DEF(pj_status_t) pjsip_transport_add_state_listener ( * otherwise allocate it using the transport pool. */ if (!pj_list_empty(&tp_data->st_listeners_empty)) { - entry = tp_data->st_listeners_empty.next; - pj_list_erase(entry); + entry = tp_data->st_listeners_empty.next; + pj_list_erase(entry); } else { - entry = PJ_POOL_ZALLOC_T(tp->pool, tp_state_listener); + entry = PJ_POOL_ZALLOC_T(tp->pool, tp_state_listener); } entry->cb = cb; entry->user_data = user_data; @@ -2703,9 +2702,9 @@ PJ_DEF(pj_status_t) pjsip_transport_add_state_listener ( * notification. */ PJ_DEF(pj_status_t) pjsip_transport_remove_state_listener ( - pjsip_transport *tp, - pjsip_tp_state_listener_key *key, - const void *user_data) + pjsip_transport *tp, + pjsip_tp_state_listener_key *key, + const void *user_data) { transport_data *tp_data; tp_state_listener *entry; @@ -2718,17 +2717,17 @@ PJ_DEF(pj_status_t) pjsip_transport_remove_state_listener ( /* Transport data is NULL or no registered listener? */ if (!tp_data || pj_list_empty(&tp_data->st_listeners)) { - pj_lock_release(tp->lock); - return PJ_ENOTFOUND; + pj_lock_release(tp->lock); + return PJ_ENOTFOUND; } entry = (tp_state_listener*)key; /* Validate the user data */ if (entry->user_data != user_data) { - pj_assert(!"Invalid transport state listener key"); - pj_lock_release(tp->lock); - return PJ_EBUG; + pj_assert(!"Invalid transport state listener key"); + pj_lock_release(tp->lock); + return PJ_EBUG; } /* Reset the entry and move it to the empty list */ @@ -2746,7 +2745,7 @@ PJ_DEF(pj_status_t) pjsip_transport_remove_state_listener ( * Set callback of data dropping. */ PJ_DEF(pj_status_t) pjsip_tpmgr_set_drop_data_cb(pjsip_tpmgr *mgr, - pjsip_tp_on_rx_dropped_cb cb) + pjsip_tp_on_rx_dropped_cb cb) { PJ_ASSERT_RETURN(mgr, PJ_EINVAL); diff --git a/pjsip/src/pjsip/sip_transport_loop.c b/pjsip/src/pjsip/sip_transport_loop.c index 37e20e69b7..567edc4f97 100644 --- a/pjsip/src/pjsip/sip_transport_loop.c +++ b/pjsip/src/pjsip/sip_transport_loop.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,8 +27,8 @@ #include -#define ADDR_LOOP "128.0.0.1" -#define ADDR_LOOP_DGRAM "129.0.0.1" +#define ADDR_LOOP "128.0.0.1" +#define ADDR_LOOP_DGRAM "129.0.0.1" /** This structure describes incoming packet. */ @@ -44,40 +43,40 @@ struct send_list { PJ_DECL_LIST_MEMBER(struct send_list); pj_time_val sent_time; - pj_ssize_t sent; + pj_ssize_t sent; pjsip_tx_data *tdata; - void *token; - void (*callback)(pjsip_transport*, void*, pj_ssize_t); + void *token; + void (*callback)(pjsip_transport*, void*, pj_ssize_t); }; /** This structure describes the loop transport. */ struct loop_transport { - pjsip_transport base; - pj_pool_t *pool; - pj_thread_t *thread; - pj_bool_t thread_quit_flag; - pj_bool_t discard; - int fail_mode; - unsigned recv_delay; - unsigned send_delay; - struct recv_list recv_list; - struct send_list send_list; + pjsip_transport base; + pj_pool_t *pool; + pj_thread_t *thread; + pj_bool_t thread_quit_flag; + pj_bool_t discard; + int fail_mode; + unsigned recv_delay; + unsigned send_delay; + struct recv_list recv_list; + struct send_list send_list; }; /* Helper function to create "incoming" packet */ static struct recv_list *create_incoming_packet( struct loop_transport *loop, - pjsip_tx_data *tdata ) + pjsip_tx_data *tdata ) { pj_pool_t *pool; struct recv_list *pkt; pool = pjsip_endpt_create_pool(loop->base.endpt, "rdata", - PJSIP_POOL_RDATA_LEN, - PJSIP_POOL_RDATA_INC+5); + PJSIP_POOL_RDATA_LEN, + PJSIP_POOL_RDATA_INC+5); if (!pool) - return NULL; + return NULL; pkt = PJ_POOL_ZALLOC_T(pool, struct recv_list); @@ -87,7 +86,7 @@ static struct recv_list *create_incoming_packet( struct loop_transport *loop, /* Copy the packet. */ pj_memcpy(pkt->rdata.pkt_info.packet, tdata->buf.start, - tdata->buf.cur - tdata->buf.start); + tdata->buf.cur - tdata->buf.start); pkt->rdata.pkt_info.len = tdata->buf.cur - tdata->buf.start; /* the source address */ @@ -96,9 +95,9 @@ static struct recv_list *create_incoming_packet( struct loop_transport *loop, /* "Source address" info. */ pkt->rdata.pkt_info.src_addr_len = sizeof(pj_sockaddr_in); if (loop->base.key.type == PJSIP_TRANSPORT_LOOP) { - pj_ansi_strcpy(pkt->rdata.pkt_info.src_name, ADDR_LOOP); + pj_ansi_strcpy(pkt->rdata.pkt_info.src_name, ADDR_LOOP); } else { - pj_ansi_strcpy(pkt->rdata.pkt_info.src_name, ADDR_LOOP_DGRAM); + pj_ansi_strcpy(pkt->rdata.pkt_info.src_name, ADDR_LOOP_DGRAM); } pkt->rdata.pkt_info.src_port = loop->base.local_name.port; @@ -115,11 +114,11 @@ static struct recv_list *create_incoming_packet( struct loop_transport *loop, /* Helper function to add pending notification callback. */ static pj_status_t add_notification( struct loop_transport *loop, - pjsip_tx_data *tdata, - pj_ssize_t sent, - void *token, - void (*callback)(pjsip_transport*, - void*, pj_ssize_t)) + pjsip_tx_data *tdata, + pj_ssize_t sent, + void *token, + void (*callback)(pjsip_transport*, + void*, pj_ssize_t)) { struct send_list *sent_status; @@ -146,17 +145,17 @@ static pj_status_t add_notification( struct loop_transport *loop, /* Handler for sending outgoing message; called by transport manager. */ static pj_status_t loop_send_msg( pjsip_transport *tp, - pjsip_tx_data *tdata, - const pj_sockaddr_t *rem_addr, - int addr_len, - void *token, - pjsip_transport_callback cb) + pjsip_tx_data *tdata, + const pj_sockaddr_t *rem_addr, + int addr_len, + void *token, + pjsip_transport_callback cb) { struct loop_transport *loop = (struct loop_transport*)tp; struct recv_list *recv_pkt; PJ_ASSERT_RETURN(tp && (tp->key.type == PJSIP_TRANSPORT_LOOP || - tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); + tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); PJ_UNUSED_ARG(rem_addr); PJ_UNUSED_ARG(addr_len); @@ -164,52 +163,52 @@ static pj_status_t loop_send_msg( pjsip_transport *tp, /* Need to send failure? */ if (loop->fail_mode) { - if (loop->send_delay == 0) { - return PJ_STATUS_FROM_OS(OSERR_ECONNRESET); - } else { - add_notification(loop, tdata, -PJ_STATUS_FROM_OS(OSERR_ECONNRESET), - token, cb); - - return PJ_EPENDING; - } + if (loop->send_delay == 0) { + return PJ_STATUS_FROM_OS(OSERR_ECONNRESET); + } else { + add_notification(loop, tdata, -PJ_STATUS_FROM_OS(OSERR_ECONNRESET), + token, cb); + + return PJ_EPENDING; + } } /* Discard any packets? */ if (loop->discard) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Create rdata for the "incoming" packet. */ recv_pkt = create_incoming_packet(loop, tdata); if (!recv_pkt) - return PJ_ENOMEM; + return PJ_ENOMEM; /* If delay is not configured, deliver this packet now! */ if (loop->recv_delay == 0) { - pj_ssize_t size_eaten; + pj_ssize_t size_eaten; - size_eaten = pjsip_tpmgr_receive_packet( loop->base.tpmgr, - &recv_pkt->rdata); - pj_assert(size_eaten == recv_pkt->rdata.pkt_info.len); - PJ_UNUSED_ARG(size_eaten); + size_eaten = pjsip_tpmgr_receive_packet( loop->base.tpmgr, + &recv_pkt->rdata); + pj_assert(size_eaten == recv_pkt->rdata.pkt_info.len); + PJ_UNUSED_ARG(size_eaten); - pjsip_endpt_release_pool(loop->base.endpt, - recv_pkt->rdata.tp_info.pool); + pjsip_endpt_release_pool(loop->base.endpt, + recv_pkt->rdata.tp_info.pool); } else { - /* Otherwise if delay is configured, add the "packet" to the - * receive list to be processed by worker thread. - */ - pj_lock_acquire(loop->base.lock); - pj_list_push_back(&loop->recv_list, recv_pkt); - pj_lock_release(loop->base.lock); + /* Otherwise if delay is configured, add the "packet" to the + * receive list to be processed by worker thread. + */ + pj_lock_acquire(loop->base.lock); + pj_list_push_back(&loop->recv_list, recv_pkt); + pj_lock_release(loop->base.lock); } if (loop->send_delay != 0) { - add_notification(loop, tdata, tdata->buf.cur - tdata->buf.start, - token, cb); - return PJ_EPENDING; + add_notification(loop, tdata, tdata->buf.cur - tdata->buf.start, + token, cb); + return PJ_EPENDING; } else { - return PJ_SUCCESS; + return PJ_SUCCESS; } } @@ -219,7 +218,7 @@ static pj_status_t loop_destroy(pjsip_transport *tp) struct loop_transport *loop = (struct loop_transport*)tp; PJ_ASSERT_RETURN(tp && (tp->key.type == PJSIP_TRANSPORT_LOOP || - tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); + tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); loop->thread_quit_flag = 1; /* Unlock transport mutex before joining thread. */ @@ -231,21 +230,21 @@ static pj_status_t loop_destroy(pjsip_transport *tp) /* Clear pending send notifications. */ while (!pj_list_empty(&loop->send_list)) { - struct send_list *node = loop->send_list.next; - /* Notify callback. */ - if (node->callback) { - (*node->callback)(&loop->base, node->token, -PJSIP_ESHUTDOWN); - } - pj_list_erase(node); - pjsip_tx_data_dec_ref(node->tdata); + struct send_list *node = loop->send_list.next; + /* Notify callback. */ + if (node->callback) { + (*node->callback)(&loop->base, node->token, -PJSIP_ESHUTDOWN); + } + pj_list_erase(node); + pjsip_tx_data_dec_ref(node->tdata); } /* Clear "incoming" packets in the queue. */ while (!pj_list_empty(&loop->recv_list)) { - struct recv_list *node = loop->recv_list.next; - pj_list_erase(node); - pjsip_endpt_release_pool(loop->base.endpt, - node->rdata.tp_info.pool); + struct recv_list *node = loop->recv_list.next; + pj_list_erase(node); + pjsip_endpt_release_pool(loop->base.endpt, + node->rdata.tp_info.pool); } /* Self destruct.. heheh.. */ @@ -267,82 +266,82 @@ static int loop_transport_worker_thread(void *arg) pj_list_init(&s); while (!loop->thread_quit_flag) { - pj_time_val now; + pj_time_val now; - pj_thread_sleep(1); - pj_gettimeofday(&now); + pj_thread_sleep(1); + pj_gettimeofday(&now); - pj_lock_acquire(loop->base.lock); + pj_lock_acquire(loop->base.lock); - /* Move expired send notification to local list. */ - while (!pj_list_empty(&loop->send_list)) { - struct send_list *node = loop->send_list.next; + /* Move expired send notification to local list. */ + while (!pj_list_empty(&loop->send_list)) { + struct send_list *node = loop->send_list.next; - /* Break when next node time is greater than now. */ - if (PJ_TIME_VAL_GTE(node->sent_time, now)) - break; + /* Break when next node time is greater than now. */ + if (PJ_TIME_VAL_GTE(node->sent_time, now)) + break; - /* Delete this from the list. */ - pj_list_erase(node); + /* Delete this from the list. */ + pj_list_erase(node); - /* Add to local list. */ - pj_list_push_back(&s, node); - } + /* Add to local list. */ + pj_list_push_back(&s, node); + } - /* Move expired "incoming" packet to local list. */ - while (!pj_list_empty(&loop->recv_list)) { - struct recv_list *node = loop->recv_list.next; + /* Move expired "incoming" packet to local list. */ + while (!pj_list_empty(&loop->recv_list)) { + struct recv_list *node = loop->recv_list.next; - /* Break when next node time is greater than now. */ - if (PJ_TIME_VAL_GTE(node->rdata.pkt_info.timestamp, now)) - break; + /* Break when next node time is greater than now. */ + if (PJ_TIME_VAL_GTE(node->rdata.pkt_info.timestamp, now)) + break; - /* Delete this from the list. */ - pj_list_erase(node); + /* Delete this from the list. */ + pj_list_erase(node); - /* Add to local list. */ - pj_list_push_back(&r, node); + /* Add to local list. */ + pj_list_push_back(&r, node); - } + } - pj_lock_release(loop->base.lock); + pj_lock_release(loop->base.lock); - /* Process send notification and incoming packet notification - * without holding down the loop's mutex. - */ - while (!pj_list_empty(&s)) { - struct send_list *node = s.next; + /* Process send notification and incoming packet notification + * without holding down the loop's mutex. + */ + while (!pj_list_empty(&s)) { + struct send_list *node = s.next; - pj_list_erase(node); + pj_list_erase(node); - /* Notify callback. */ - if (node->callback) { - (*node->callback)(&loop->base, node->token, node->sent); - } + /* Notify callback. */ + if (node->callback) { + (*node->callback)(&loop->base, node->token, node->sent); + } - /* Decrement tdata reference counter. */ - pjsip_tx_data_dec_ref(node->tdata); - } + /* Decrement tdata reference counter. */ + pjsip_tx_data_dec_ref(node->tdata); + } - /* Process "incoming" packet. */ - while (!pj_list_empty(&r)) { - struct recv_list *node = r.next; - pj_ssize_t size_eaten; + /* Process "incoming" packet. */ + while (!pj_list_empty(&r)) { + struct recv_list *node = r.next; + pj_ssize_t size_eaten; - pj_list_erase(node); + pj_list_erase(node); - /* Notify transport manager about the "incoming packet" */ - size_eaten = pjsip_tpmgr_receive_packet(loop->base.tpmgr, - &node->rdata); + /* Notify transport manager about the "incoming packet" */ + size_eaten = pjsip_tpmgr_receive_packet(loop->base.tpmgr, + &node->rdata); - /* Must "eat" all the packets. */ - pj_assert(size_eaten == node->rdata.pkt_info.len); - PJ_UNUSED_ARG(size_eaten); + /* Must "eat" all the packets. */ + pj_assert(size_eaten == node->rdata.pkt_info.len); + PJ_UNUSED_ARG(size_eaten); - /* Done. */ - pjsip_endpt_release_pool(loop->base.endpt, - node->rdata.tp_info.pool); - } + /* Done. */ + pjsip_endpt_release_pool(loop->base.endpt, + node->rdata.tp_info.pool); + } } return 0; @@ -351,7 +350,7 @@ static int loop_transport_worker_thread(void *arg) /* Start loop transport. */ PJ_DEF(pj_status_t) pjsip_loop_start( pjsip_endpoint *endpt, - pjsip_transport **transport) + pjsip_transport **transport) { pj_pool_t *pool; struct loop_transport *loop; @@ -360,21 +359,21 @@ PJ_DEF(pj_status_t) pjsip_loop_start( pjsip_endpoint *endpt, /* Create pool. */ pool = pjsip_endpt_create_pool(endpt, "loop", 4000, 4000); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create the loop structure. */ loop = PJ_POOL_ZALLOC_T(pool, struct loop_transport); /* Initialize transport properties. */ pj_ansi_snprintf(loop->base.obj_name, sizeof(loop->base.obj_name), - "loop%p", loop); + "loop%p", loop); loop->base.pool = pool; status = pj_atomic_create(pool, 0, &loop->base.ref_cnt); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_lock_create_recursive_mutex(pool, "loop", &loop->base.lock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; loop->base.key.type = PJSIP_TRANSPORT_LOOP_DGRAM; //loop->base.key.rem_addr.addr.sa_family = pj_AF_INET(); loop->base.type_name = "LOOP-DGRAM"; @@ -382,8 +381,8 @@ PJ_DEF(pj_status_t) pjsip_loop_start( pjsip_endpoint *endpt, loop->base.flag = PJSIP_TRANSPORT_DATAGRAM; loop->base.local_name.host = pj_str(ADDR_LOOP_DGRAM); loop->base.local_name.port = - pjsip_transport_get_default_port_for_type((pjsip_transport_type_e) - loop->base.key.type); + pjsip_transport_get_default_port_for_type((pjsip_transport_type_e) + loop->base.key.type); loop->base.addr_len = sizeof(pj_sockaddr_in); loop->base.dir = PJSIP_TP_DIR_NONE; loop->base.endpt = endpt; @@ -396,53 +395,53 @@ PJ_DEF(pj_status_t) pjsip_loop_start( pjsip_endpoint *endpt, /* Create worker thread. */ status = pj_thread_create(pool, "loop", - &loop_transport_worker_thread, loop, 0, - PJ_THREAD_SUSPENDED, &loop->thread); + &loop_transport_worker_thread, loop, 0, + PJ_THREAD_SUSPENDED, &loop->thread); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Register to transport manager. */ status = pjsip_transport_register( loop->base.tpmgr, &loop->base); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Start the thread. */ status = pj_thread_resume(loop->thread); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* * Done. */ if (transport) - *transport = &loop->base; + *transport = &loop->base; return PJ_SUCCESS; on_error: if (loop->base.lock) - pj_lock_destroy(loop->base.lock); + pj_lock_destroy(loop->base.lock); if (loop->thread) - pj_thread_destroy(loop->thread); + pj_thread_destroy(loop->thread); if (loop->base.ref_cnt) - pj_atomic_destroy(loop->base.ref_cnt); + pj_atomic_destroy(loop->base.ref_cnt); pjsip_endpt_release_pool(endpt, loop->pool); return status; } PJ_DEF(pj_status_t) pjsip_loop_set_discard( pjsip_transport *tp, - pj_bool_t discard, - pj_bool_t *prev_value ) + pj_bool_t discard, + pj_bool_t *prev_value ) { struct loop_transport *loop = (struct loop_transport*)tp; PJ_ASSERT_RETURN(tp && (tp->key.type == PJSIP_TRANSPORT_LOOP || - tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); + tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); if (prev_value) - *prev_value = loop->discard; + *prev_value = loop->discard; loop->discard = discard; return PJ_SUCCESS; @@ -450,16 +449,16 @@ PJ_DEF(pj_status_t) pjsip_loop_set_discard( pjsip_transport *tp, PJ_DEF(pj_status_t) pjsip_loop_set_failure( pjsip_transport *tp, - int fail_flag, - int *prev_value ) + int fail_flag, + int *prev_value ) { struct loop_transport *loop = (struct loop_transport*)tp; PJ_ASSERT_RETURN(tp && (tp->key.type == PJSIP_TRANSPORT_LOOP || - tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); + tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); if (prev_value) - *prev_value = loop->fail_mode; + *prev_value = loop->fail_mode; loop->fail_mode = fail_flag; return PJ_SUCCESS; @@ -467,32 +466,32 @@ PJ_DEF(pj_status_t) pjsip_loop_set_failure( pjsip_transport *tp, PJ_DEF(pj_status_t) pjsip_loop_set_recv_delay( pjsip_transport *tp, - unsigned delay, - unsigned *prev_value) + unsigned delay, + unsigned *prev_value) { struct loop_transport *loop = (struct loop_transport*)tp; PJ_ASSERT_RETURN(tp && (tp->key.type == PJSIP_TRANSPORT_LOOP || - tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); + tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); if (prev_value) - *prev_value = loop->recv_delay; + *prev_value = loop->recv_delay; loop->recv_delay = delay; return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjsip_loop_set_send_callback_delay( pjsip_transport *tp, - unsigned delay, - unsigned *prev_value) + unsigned delay, + unsigned *prev_value) { struct loop_transport *loop = (struct loop_transport*)tp; PJ_ASSERT_RETURN(tp && (tp->key.type == PJSIP_TRANSPORT_LOOP || - tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); + tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); if (prev_value) - *prev_value = loop->send_delay; + *prev_value = loop->send_delay; loop->send_delay = delay; return PJ_SUCCESS; @@ -503,7 +502,7 @@ PJ_DEF(pj_status_t) pjsip_loop_set_delay( pjsip_transport *tp, unsigned delay ) struct loop_transport *loop = (struct loop_transport*)tp; PJ_ASSERT_RETURN(tp && (tp->key.type == PJSIP_TRANSPORT_LOOP || - tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); + tp->key.type == PJSIP_TRANSPORT_LOOP_DGRAM), PJ_EINVAL); loop->recv_delay = delay; loop->send_delay = delay; diff --git a/pjsip/src/pjsip/sip_transport_tcp.c b/pjsip/src/pjsip/sip_transport_tcp.c index e4f321019b..080e280980 100644 --- a/pjsip/src/pjsip/sip_transport_tcp.c +++ b/pjsip/src/pjsip/sip_transport_tcp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,13 +33,13 @@ #if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0 -#define THIS_FILE "sip_transport_tcp.c" +#define THIS_FILE "sip_transport_tcp.c" -#define MAX_ASYNC_CNT 16 -#define POOL_LIS_INIT 512 -#define POOL_LIS_INC 512 -#define POOL_TP_INIT 512 -#define POOL_TP_INC 512 +#define MAX_ASYNC_CNT 16 +#define POOL_LIS_INIT 512 +#define POOL_LIS_INC 512 +#define POOL_TP_INIT 512 +#define POOL_TP_INC 512 struct tcp_listener; struct tcp_transport; @@ -52,21 +51,21 @@ struct tcp_transport; */ struct tcp_listener { - pjsip_tpfactory factory; - pj_bool_t is_registered; - pjsip_endpoint *endpt; - pjsip_tpmgr *tpmgr; - pj_activesock_t *asock; - pj_sockaddr bound_addr; - pj_qos_type qos_type; - pj_qos_params qos_params; - pj_sockopt_params sockopt_params; - pj_bool_t reuse_addr; - unsigned async_cnt; - unsigned initial_timeout; + pjsip_tpfactory factory; + pj_bool_t is_registered; + pjsip_endpoint *endpt; + pjsip_tpmgr *tpmgr; + pj_activesock_t *asock; + pj_sockaddr bound_addr; + pj_qos_type qos_type; + pj_qos_params qos_params; + pj_sockopt_params sockopt_params; + pj_bool_t reuse_addr; + unsigned async_cnt; + unsigned initial_timeout; /* Group lock to be used by TCP listener and ioqueue key */ - pj_grp_lock_t *grp_lock; + pj_grp_lock_t *grp_lock; }; @@ -91,42 +90,42 @@ struct delayed_tdata */ struct tcp_transport { - pjsip_transport base; - pj_bool_t is_server; + pjsip_transport base; + pj_bool_t is_server; /* Do not save listener instance in the transport, because * listener might be destroyed during transport's lifetime. * See https://github.com/pjsip/pjproject/issues/491 - struct tcp_listener *listener; + struct tcp_listener *listener; */ - pj_bool_t is_registered; - pj_bool_t is_closing; - pj_status_t close_reason; - pj_sock_t sock; - pj_activesock_t *asock; - pj_bool_t has_pending_connect; + pj_bool_t is_registered; + pj_bool_t is_closing; + pj_status_t close_reason; + pj_sock_t sock; + pj_activesock_t *asock; + pj_bool_t has_pending_connect; /* Keep-alive timer. */ - pj_timer_entry ka_timer; - pj_time_val last_activity; + pj_timer_entry ka_timer; + pj_time_val last_activity; pjsip_tx_data_op_key ka_op_key; - pj_str_t ka_pkt; + pj_str_t ka_pkt; /* TCP transport can only have one rdata! * Otherwise chunks of incoming PDU may be received on different * buffer. */ - pjsip_rx_data rdata; + pjsip_rx_data rdata; /* Pending transmission list. */ struct delayed_tdata delayed_list; /* Group lock to be used by TCP transport and ioqueue key */ - pj_grp_lock_t *grp_lock; + pj_grp_lock_t *grp_lock; /* Initial timer. */ - pj_timer_entry initial_timer; + pj_timer_entry initial_timer; }; @@ -136,9 +135,9 @@ struct tcp_transport /* This callback is called when pending accept() operation completes. */ static pj_bool_t on_accept_complete(pj_activesock_t *asock, - pj_sock_t newsock, - const pj_sockaddr_t *src_addr, - int src_addr_len); + pj_sock_t newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len); /* This callback is called by transport manager to destroy listener */ static pj_status_t lis_destroy(pjsip_tpfactory *factory); @@ -148,31 +147,31 @@ static void lis_on_destroy(void *arg); /* This callback is called by transport manager to create transport */ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, - pjsip_tpmgr *mgr, - pjsip_endpoint *endpt, - const pj_sockaddr *rem_addr, - int addr_len, - pjsip_transport **transport); + pjsip_tpmgr *mgr, + pjsip_endpoint *endpt, + const pj_sockaddr *rem_addr, + int addr_len, + pjsip_transport **transport); /* Common function to create and initialize transport */ static pj_status_t tcp_create(struct tcp_listener *listener, - pj_pool_t *pool, - pj_sock_t sock, pj_bool_t is_server, - const pj_sockaddr *local, - const pj_sockaddr *remote, - struct tcp_transport **p_tcp); + pj_pool_t *pool, + pj_sock_t sock, pj_bool_t is_server, + const pj_sockaddr *local, + const pj_sockaddr *remote, + struct tcp_transport **p_tcp); static void tcp_perror(const char *sender, const char *title, - pj_status_t status) + pj_status_t status) { PJ_PERROR(3,(sender, status, "%s: [code=%d]", title, status)); } static void sockaddr_to_host_port( pj_pool_t *pool, - pjsip_host_port *host_port, - const pj_sockaddr *addr ) + pjsip_host_port *host_port, + const pj_sockaddr *addr ) { host_port->host.ptr = (char*) pj_pool_alloc(pool, PJ_INET6_ADDRSTRLEN+4); pj_sockaddr_print(addr, host_port->host.ptr, PJ_INET6_ADDRSTRLEN+4, 0); @@ -186,10 +185,10 @@ static void tcp_init_shutdown(struct tcp_transport *tcp, pj_status_t status) pjsip_tp_state_callback state_cb; if (tcp->close_reason == PJ_SUCCESS) - tcp->close_reason = status; + tcp->close_reason = status; if (tcp->base.is_shutdown || tcp->base.is_destroying) - return; + return; /* Prevent immediate transport destroy by application, as transport * state notification callback may be stacked and transport instance @@ -200,17 +199,17 @@ static void tcp_init_shutdown(struct tcp_transport *tcp, pj_status_t status) /* Notify application of transport disconnected state */ state_cb = pjsip_tpmgr_get_state_cb(tcp->base.tpmgr); if (state_cb) { - pjsip_transport_state_info state_info; + pjsip_transport_state_info state_info; - pj_bzero(&state_info, sizeof(state_info)); - state_info.status = tcp->close_reason; - (*state_cb)(&tcp->base, PJSIP_TP_STATE_DISCONNECTED, &state_info); + pj_bzero(&state_info, sizeof(state_info)); + state_info.status = tcp->close_reason; + (*state_cb)(&tcp->base, PJSIP_TP_STATE_DISCONNECTED, &state_info); } /* check again */ if (tcp->base.is_shutdown || tcp->base.is_destroying) { pjsip_transport_dec_ref(&tcp->base); - return; + return; } /* We can not destroy the transport since high level objects may @@ -229,7 +228,7 @@ static void tcp_init_shutdown(struct tcp_transport *tcp, pj_status_t status) * Initialize pjsip_tcp_transport_cfg structure with default values. */ PJ_DEF(void) pjsip_tcp_transport_cfg_default(pjsip_tcp_transport_cfg *cfg, - int af) + int af) { pj_bzero(cfg, sizeof(*cfg)); cfg->af = af; @@ -245,7 +244,7 @@ PJ_DEF(void) pjsip_tcp_transport_cfg_default(pjsip_tcp_transport_cfg *cfg, */ static void update_bound_addr(struct tcp_listener *listener, - const pj_sockaddr *local) + const pj_sockaddr *local) { pj_sockaddr *listener_addr = &listener->factory.local_addr; int af = pjsip_transport_type_get_af(listener->factory.type); @@ -254,16 +253,16 @@ static void update_bound_addr(struct tcp_listener *listener, * factory.local_addr will be resolved. */ if (local) { - pj_sockaddr_cp(&listener->bound_addr, local); + pj_sockaddr_cp(&listener->bound_addr, local); } else { - pj_sockaddr_init(af, &listener->bound_addr, NULL, 0); + pj_sockaddr_init(af, &listener->bound_addr, NULL, 0); } pj_sockaddr_cp(listener_addr, &listener->bound_addr); } -static pj_status_t update_factory_addr(struct tcp_listener *listener, - const pjsip_host_port *addr_name) +static pj_status_t update_factory_addr(struct tcp_listener *listener, + const pjsip_host_port *addr_name) { pj_status_t status = PJ_SUCCESS; pj_sockaddr *listener_addr = &listener->factory.local_addr; @@ -272,56 +271,56 @@ static pj_status_t update_factory_addr(struct tcp_listener *listener, * listener advertised address. */ if (addr_name && addr_name->host.slen) { - pj_sockaddr tmp; - int af = pjsip_transport_type_get_af(listener->factory.type); - - /* Verify that address given in a_name (if any) is valid */ - status = pj_sockaddr_init(af, &tmp, &addr_name->host, - (pj_uint16_t)addr_name->port); - if (status != PJ_SUCCESS || !pj_sockaddr_has_addr(&tmp) || - (af == pj_AF_INET() && tmp.ipv4.sin_addr.s_addr == PJ_INADDR_NONE)) - { - /* Invalid address */ - return PJ_EINVAL; - } - - /* Copy the address */ - listener->factory.addr_name = *addr_name; - pj_strdup(listener->factory.pool, &listener->factory.addr_name.host, - &addr_name->host); - listener->factory.addr_name.port = addr_name->port; + pj_sockaddr tmp; + int af = pjsip_transport_type_get_af(listener->factory.type); + + /* Verify that address given in a_name (if any) is valid */ + status = pj_sockaddr_init(af, &tmp, &addr_name->host, + (pj_uint16_t)addr_name->port); + if (status != PJ_SUCCESS || !pj_sockaddr_has_addr(&tmp) || + (af == pj_AF_INET() && tmp.ipv4.sin_addr.s_addr == PJ_INADDR_NONE)) + { + /* Invalid address */ + return PJ_EINVAL; + } + + /* Copy the address */ + listener->factory.addr_name = *addr_name; + pj_strdup(listener->factory.pool, &listener->factory.addr_name.host, + &addr_name->host); + listener->factory.addr_name.port = addr_name->port; } else { - /* No published address is given, use the bound address */ - - /* If the address returns 0.0.0.0, use the default - * interface address as the transport's address. - */ - if (!pj_sockaddr_has_addr(listener_addr)) { - pj_sockaddr hostip; - - status = pj_gethostip(listener->bound_addr.addr.sa_family, - &hostip); - if (status != PJ_SUCCESS) - return status; - - pj_sockaddr_copy_addr(listener_addr, &hostip); - } - - /* Save the address name */ - sockaddr_to_host_port(listener->factory.pool, - &listener->factory.addr_name, - listener_addr); + /* No published address is given, use the bound address */ + + /* If the address returns 0.0.0.0, use the default + * interface address as the transport's address. + */ + if (!pj_sockaddr_has_addr(listener_addr)) { + pj_sockaddr hostip; + + status = pj_gethostip(listener->bound_addr.addr.sa_family, + &hostip); + if (status != PJ_SUCCESS) + return status; + + pj_sockaddr_copy_addr(listener_addr, &hostip); + } + + /* Save the address name */ + sockaddr_to_host_port(listener->factory.pool, + &listener->factory.addr_name, + listener_addr); } /* If port is zero, get the bound port */ if (listener->factory.addr_name.port == 0) { - listener->factory.addr_name.port = pj_sockaddr_get_port(listener_addr); + listener->factory.addr_name.port = pj_sockaddr_get_port(listener_addr); } pj_ansi_snprintf(listener->factory.obj_name, - sizeof(listener->factory.obj_name), - "tcptp:%d", listener->factory.addr_name.port); + sizeof(listener->factory.obj_name), + "tcptp:%d", listener->factory.addr_name.port); return status; } @@ -335,29 +334,29 @@ static void update_transport_info(struct tcp_listener *listener) /* Set transport info. */ if (listener->factory.info == NULL) { - listener->factory.info = (char*)pj_pool_alloc(listener->factory.pool, - INFO_LEN); + listener->factory.info = (char*)pj_pool_alloc(listener->factory.pool, + INFO_LEN); } pj_sockaddr_print(listener_addr, local_addr, sizeof(local_addr), 3); pj_addr_str_print(&listener->factory.addr_name.host, - listener->factory.addr_name.port, pub_addr, - sizeof(pub_addr), 1); + listener->factory.addr_name.port, pub_addr, + sizeof(pub_addr), 1); len = pj_ansi_snprintf( - listener->factory.info, INFO_LEN, "tcp %s [published as %s]", - local_addr, pub_addr); + listener->factory.info, INFO_LEN, "tcp %s [published as %s]", + local_addr, pub_addr); PJ_CHECK_TRUNC_STR(len, listener->factory.info, INFO_LEN); - if (listener->asock) { - char addr[PJ_INET6_ADDRSTRLEN+10]; + if (listener->asock) { + char addr[PJ_INET6_ADDRSTRLEN+10]; - PJ_LOG(4, (listener->factory.obj_name, - "SIP TCP listener ready for incoming connections at %s", - pj_addr_str_print(&listener->factory.addr_name.host, - listener->factory.addr_name.port, addr, - sizeof(addr), 1))); + PJ_LOG(4, (listener->factory.obj_name, + "SIP TCP listener ready for incoming connections at %s", + pj_addr_str_print(&listener->factory.addr_name.host, + listener->factory.addr_name.port, addr, + sizeof(addr), 1))); } else { - PJ_LOG(4, (listener->factory.obj_name, "SIP TCP is ready " - "(client only)")); + PJ_LOG(4, (listener->factory.obj_name, "SIP TCP is ready " + "(client only)")); } } @@ -366,10 +365,10 @@ static void update_transport_info(struct tcp_listener *listener) * TCP listener. */ PJ_DEF(pj_status_t) pjsip_tcp_transport_start3( - pjsip_endpoint *endpt, - const pjsip_tcp_transport_cfg *cfg, - pjsip_tpfactory **p_factory - ) + pjsip_endpoint *endpt, + const pjsip_tcp_transport_cfg *cfg, + pjsip_tpfactory **p_factory + ) { pj_pool_t *pool; struct tcp_listener *listener; @@ -379,44 +378,44 @@ PJ_DEF(pj_status_t) pjsip_tcp_transport_start3( PJ_ASSERT_RETURN(endpt && cfg->async_cnt, PJ_EINVAL); pool = pjsip_endpt_create_pool(endpt, "tcptp", POOL_LIS_INIT, - POOL_LIS_INC); + POOL_LIS_INC); PJ_ASSERT_RETURN(pool, PJ_ENOMEM); listener = PJ_POOL_ZALLOC_T(pool, struct tcp_listener); listener->factory.pool = pool; listener->factory.type = cfg->af==pj_AF_INET() ? PJSIP_TRANSPORT_TCP : - PJSIP_TRANSPORT_TCP6; + PJSIP_TRANSPORT_TCP6; listener->factory.type_name = (char*) - pjsip_transport_get_type_name(listener->factory.type); + pjsip_transport_get_type_name(listener->factory.type); listener->factory.flag = - pjsip_transport_get_flag_from_type(listener->factory.type); + pjsip_transport_get_flag_from_type(listener->factory.type); listener->qos_type = cfg->qos_type; listener->reuse_addr = cfg->reuse_addr; listener->async_cnt = cfg->async_cnt; listener->initial_timeout = cfg->initial_timeout; pj_memcpy(&listener->qos_params, &cfg->qos_params, - sizeof(cfg->qos_params)); + sizeof(cfg->qos_params)); pj_memcpy(&listener->sockopt_params, &cfg->sockopt_params, - sizeof(cfg->sockopt_params)); + sizeof(cfg->sockopt_params)); pj_ansi_strcpy(listener->factory.obj_name, "tcptp"); if (listener->factory.type==PJSIP_TRANSPORT_TCP6) - pj_ansi_strcat(listener->factory.obj_name, "6"); + pj_ansi_strcat(listener->factory.obj_name, "6"); status = pj_lock_create_recursive_mutex(pool, listener->factory.obj_name, - &listener->factory.lock); + &listener->factory.lock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create group lock */ status = pj_grp_lock_create(pool, NULL, &listener->grp_lock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; pj_grp_lock_add_ref(listener->grp_lock); pj_grp_lock_add_handler(listener->grp_lock, pool, listener, - &lis_on_destroy); + &lis_on_destroy); /* Register to transport manager */ listener->endpt = endpt; @@ -428,15 +427,15 @@ PJ_DEF(pj_status_t) pjsip_tcp_transport_start3( PJSIP_TCP_TRANSPORT_DONT_CREATE_LISTENER != 0) /* Start listener. */ status = pjsip_tcp_transport_lis_start(&listener->factory, &cfg->bind_addr, - &cfg->addr_name); + &cfg->addr_name); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #else update_bound_addr(listener, &cfg->bind_addr); status = update_factory_addr(listener, &cfg->addr_name); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Set transport info. */ update_transport_info(listener); @@ -444,10 +443,10 @@ PJ_DEF(pj_status_t) pjsip_tcp_transport_start3( listener->is_registered = PJ_TRUE; status = pjsip_tpmgr_register_tpfactory(listener->tpmgr, - &listener->factory); + &listener->factory); if (status != PJ_SUCCESS) { - listener->is_registered = PJ_FALSE; - goto on_error; + listener->is_registered = PJ_FALSE; + goto on_error; } /* Return the pointer to user */ @@ -466,25 +465,25 @@ PJ_DEF(pj_status_t) pjsip_tcp_transport_start3( * TCP listener. */ PJ_DEF(pj_status_t) pjsip_tcp_transport_start2(pjsip_endpoint *endpt, - const pj_sockaddr_in *local, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_tpfactory **p_factory) + const pj_sockaddr_in *local, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_tpfactory **p_factory) { pjsip_tcp_transport_cfg cfg; pjsip_tcp_transport_cfg_default(&cfg, pj_AF_INET()); if (local) - pj_sockaddr_cp(&cfg.bind_addr, local); + pj_sockaddr_cp(&cfg.bind_addr, local); else - pj_sockaddr_init(cfg.af, &cfg.bind_addr, NULL, 0); + pj_sockaddr_init(cfg.af, &cfg.bind_addr, NULL, 0); if (a_name) - pj_memcpy(&cfg.addr_name, a_name, sizeof(*a_name)); + pj_memcpy(&cfg.addr_name, a_name, sizeof(*a_name)); if (async_cnt) - cfg.async_cnt = async_cnt; + cfg.async_cnt = async_cnt; return pjsip_tcp_transport_start3(endpt, &cfg, p_factory); } @@ -495,9 +494,9 @@ PJ_DEF(pj_status_t) pjsip_tcp_transport_start2(pjsip_endpoint *endpt, * TCP listener. */ PJ_DEF(pj_status_t) pjsip_tcp_transport_start( pjsip_endpoint *endpt, - const pj_sockaddr_in *local, - unsigned async_cnt, - pjsip_tpfactory **p_factory) + const pj_sockaddr_in *local, + unsigned async_cnt, + pjsip_tpfactory **p_factory) { return pjsip_tcp_transport_start2(endpt, local, NULL, async_cnt, p_factory); } @@ -509,13 +508,13 @@ static void lis_on_destroy(void *arg) struct tcp_listener *listener = (struct tcp_listener *)arg; if (listener->factory.lock) { - pj_lock_destroy(listener->factory.lock); - listener->factory.lock = NULL; + pj_lock_destroy(listener->factory.lock); + listener->factory.lock = NULL; } if (listener->factory.pool) { - PJ_LOG(4,(listener->factory.obj_name, "SIP TCP transport destroyed")); - pj_pool_safe_release(&listener->factory.pool); + PJ_LOG(4,(listener->factory.obj_name, "SIP TCP transport destroyed")); + pj_pool_safe_release(&listener->factory.pool); } } @@ -523,13 +522,13 @@ static void lis_on_destroy(void *arg) static void lis_close(struct tcp_listener *listener) { if (listener->is_registered) { - pjsip_tpmgr_unregister_tpfactory(listener->tpmgr, &listener->factory); - listener->is_registered = PJ_FALSE; + pjsip_tpmgr_unregister_tpfactory(listener->tpmgr, &listener->factory); + listener->is_registered = PJ_FALSE; } if (listener->asock) { - pj_activesock_close(listener->asock); - listener->asock = NULL; + pj_activesock_close(listener->asock); + listener->asock = NULL; } } @@ -541,12 +540,12 @@ static pj_status_t lis_destroy(pjsip_tpfactory *factory) lis_close(listener); if (listener->grp_lock) { - pj_grp_lock_t *grp_lock = listener->grp_lock; - listener->grp_lock = NULL; - pj_grp_lock_dec_ref(grp_lock); - /* Listener may have been deleted at this point */ + pj_grp_lock_t *grp_lock = listener->grp_lock; + listener->grp_lock = NULL; + pj_grp_lock_dec_ref(grp_lock); + /* Listener may have been deleted at this point */ } else { - lis_on_destroy(listener); + lis_on_destroy(listener); } return PJ_SUCCESS; @@ -563,11 +562,11 @@ static pj_status_t lis_destroy(pjsip_tpfactory *factory) */ /* Called by transport manager to send message */ static pj_status_t tcp_send_msg(pjsip_transport *transport, - pjsip_tx_data *tdata, - const pj_sockaddr_t *rem_addr, - int addr_len, - void *token, - pjsip_transport_callback callback); + pjsip_tx_data *tdata, + const pj_sockaddr_t *rem_addr, + int addr_len, + void *token, + pjsip_transport_callback callback); /* Called by transport manager to shutdown */ static pj_status_t tcp_shutdown(pjsip_transport *transport); @@ -577,23 +576,23 @@ static pj_status_t tcp_destroy_transport(pjsip_transport *transport); /* Utility to destroy transport */ static pj_status_t tcp_destroy(pjsip_transport *transport, - pj_status_t reason); + pj_status_t reason); /* Callback on incoming data */ static pj_bool_t on_data_read(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder); + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder); /* Callback when packet is sent */ static pj_bool_t on_data_sent(pj_activesock_t *asock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent); + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent); /* Callback when connect completes */ static pj_bool_t on_connect_complete(pj_activesock_t *asock, - pj_status_t status); + pj_status_t status); /* TCP keep-alive timer callback */ static void tcp_keep_alive_timer(pj_timer_heap_t *th, pj_timer_entry *e); @@ -609,11 +608,11 @@ static void tcp_on_destroy(void *arg); * pending connect() complete. */ static pj_status_t tcp_create( struct tcp_listener *listener, - pj_pool_t *pool, - pj_sock_t sock, pj_bool_t is_server, - const pj_sockaddr *local, - const pj_sockaddr *remote, - struct tcp_transport **p_tcp) + pj_pool_t *pool, + pj_sock_t sock, pj_bool_t is_server, + const pj_sockaddr *local, + const pj_sockaddr *remote, + struct tcp_transport **p_tcp) { struct tcp_transport *tcp; pj_ioqueue_t *ioqueue; @@ -628,9 +627,9 @@ static pj_status_t tcp_create( struct tcp_listener *listener, if (pool == NULL) { - pool = pjsip_endpt_create_pool(listener->endpt, "tcp", - POOL_TP_INIT, POOL_TP_INC); - PJ_ASSERT_RETURN(pool != NULL, PJ_ENOMEM); + pool = pjsip_endpt_create_pool(listener->endpt, "tcp", + POOL_TP_INIT, POOL_TP_INC); + PJ_ASSERT_RETURN(pool != NULL, PJ_ENOMEM); } /* @@ -644,24 +643,24 @@ static pj_status_t tcp_create( struct tcp_listener *listener, tcp->base.pool = pool; pj_ansi_snprintf(tcp->base.obj_name, PJ_MAX_OBJ_NAME, - (is_server ? "tcps%p" :"tcpc%p"), tcp); + (is_server ? "tcps%p" :"tcpc%p"), tcp); status = pj_atomic_create(pool, 0, &tcp->base.ref_cnt); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } status = pj_lock_create_recursive_mutex(pool, "tcp", &tcp->base.lock); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } tcp->base.key.type = listener->factory.type; pj_sockaddr_cp(&tcp->base.key.rem_addr, remote); tcp->base.type_name = (char*)pjsip_transport_get_type_name( - (pjsip_transport_type_e)tcp->base.key.type); + (pjsip_transport_type_e)tcp->base.key.type); tcp->base.flag = pjsip_transport_get_flag_from_type( - (pjsip_transport_type_e)tcp->base.key.type); + (pjsip_transport_type_e)tcp->base.key.type); tcp->base.info = (char*) pj_pool_alloc(pool, 64); pj_ansi_snprintf(tcp->base.info, 64, "%s to %s", @@ -684,9 +683,9 @@ static pj_status_t tcp_create( struct tcp_listener *listener, /* Create group lock */ status = pj_grp_lock_create_w_handler(pool, NULL, tcp, &tcp_on_destroy, - &tcp->grp_lock); + &tcp->grp_lock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; pj_grp_lock_add_ref(tcp->grp_lock); @@ -704,15 +703,15 @@ static pj_status_t tcp_create( struct tcp_listener *listener, ioqueue = pjsip_endpt_get_ioqueue(listener->endpt); status = pj_activesock_create(pool, sock, pj_SOCK_STREAM(), &asock_cfg, - ioqueue, &tcp_callback, tcp, &tcp->asock); + ioqueue, &tcp_callback, tcp, &tcp->asock); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } /* Register transport to transport manager */ status = pjsip_transport_register(listener->tpmgr, &tcp->base); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } tcp->is_registered = PJ_TRUE; @@ -725,31 +724,31 @@ static pj_status_t tcp_create( struct tcp_listener *listener, /* Initialize initial timer. */ if (is_server && listener->initial_timeout) { - pj_time_val delay = { 0 }; - - tcp->initial_timer.user_data = (void*)tcp; - tcp->initial_timer.cb = &tcp_initial_timer; - - delay.sec = listener->initial_timeout; - pjsip_endpt_schedule_timer(listener->endpt, - &tcp->initial_timer, - &delay); - tcp->initial_timer.id = PJ_TRUE; + pj_time_val delay = { 0 }; + + tcp->initial_timer.user_data = (void*)tcp; + tcp->initial_timer.cb = &tcp_initial_timer; + + delay.sec = listener->initial_timeout; + pjsip_endpt_schedule_timer(listener->endpt, + &tcp->initial_timer, + &delay); + tcp->initial_timer.id = PJ_TRUE; } /* Done setting up basic transport. */ *p_tcp = tcp; PJ_LOG(4,(tcp->base.obj_name, "TCP %s transport created", - (tcp->is_server ? "server" : "client"))); + (tcp->is_server ? "server" : "client"))); return PJ_SUCCESS; on_error: if (tcp->grp_lock && pj_grp_lock_get_ref(tcp->grp_lock)) - tcp_destroy(&tcp->base, status); + tcp_destroy(&tcp->base, status); else - tcp_on_destroy(tcp); + tcp_on_destroy(tcp); return status; } @@ -763,36 +762,36 @@ static void tcp_flush_pending_tx(struct tcp_transport *tcp) pj_gettickcount(&now); pj_lock_acquire(tcp->base.lock); while (!pj_list_empty(&tcp->delayed_list)) { - struct delayed_tdata *pending_tx; - pjsip_tx_data *tdata; - pj_ioqueue_op_key_t *op_key; - pj_ssize_t size; - pj_status_t status; + struct delayed_tdata *pending_tx; + pjsip_tx_data *tdata; + pj_ioqueue_op_key_t *op_key; + pj_ssize_t size; + pj_status_t status; - pending_tx = tcp->delayed_list.next; - pj_list_erase(pending_tx); + pending_tx = tcp->delayed_list.next; + pj_list_erase(pending_tx); - tdata = pending_tx->tdata_op_key->tdata; - op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; + tdata = pending_tx->tdata_op_key->tdata; + op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; if (pending_tx->timeout.sec > 0 && PJ_TIME_VAL_GT(now, pending_tx->timeout)) { pj_lock_release(tcp->base.lock); - on_data_sent(tcp->asock, op_key, -PJ_ETIMEDOUT); + on_data_sent(tcp->asock, op_key, -PJ_ETIMEDOUT); pj_lock_acquire(tcp->base.lock); continue; } - /* send! */ - size = tdata->buf.cur - tdata->buf.start; - status = pj_activesock_send(tcp->asock, op_key, tdata->buf.start, - &size, 0); - if (status != PJ_EPENDING) { + /* send! */ + size = tdata->buf.cur - tdata->buf.start; + status = pj_activesock_send(tcp->asock, op_key, tdata->buf.start, + &size, 0); + if (status != PJ_EPENDING) { pj_lock_release(tcp->base.lock); - on_data_sent(tcp->asock, op_key, size); + on_data_sent(tcp->asock, op_key, size); pj_lock_acquire(tcp->base.lock); - } + } } pj_lock_release(tcp->base.lock); @@ -815,21 +814,21 @@ static pj_status_t tcp_destroy_transport(pjsip_transport *transport) /* Destroy TCP transport */ static pj_status_t tcp_destroy(pjsip_transport *transport, - pj_status_t reason) + pj_status_t reason) { struct tcp_transport *tcp = (struct tcp_transport*)transport; if (tcp->close_reason == 0) - tcp->close_reason = reason; + tcp->close_reason = reason; if (tcp->is_registered) { - tcp->is_registered = PJ_FALSE; - pjsip_transport_destroy(transport); + tcp->is_registered = PJ_FALSE; + pjsip_transport_destroy(transport); - /* pjsip_transport_destroy will recursively call this function - * again. - */ - return PJ_SUCCESS; + /* pjsip_transport_destroy will recursively call this function + * again. + */ + return PJ_SUCCESS; } /* Mark transport as closing */ @@ -837,43 +836,43 @@ static pj_status_t tcp_destroy(pjsip_transport *transport, /* Stop keep-alive timer. */ if (tcp->ka_timer.id) { - pjsip_endpt_cancel_timer(tcp->base.endpt, &tcp->ka_timer); - tcp->ka_timer.id = PJ_FALSE; + pjsip_endpt_cancel_timer(tcp->base.endpt, &tcp->ka_timer); + tcp->ka_timer.id = PJ_FALSE; } /* Stop initial timer. */ if (tcp->initial_timer.id) { - pjsip_endpt_cancel_timer(tcp->base.endpt, &tcp->initial_timer); - tcp->initial_timer.id = PJ_FALSE; + pjsip_endpt_cancel_timer(tcp->base.endpt, &tcp->initial_timer); + tcp->initial_timer.id = PJ_FALSE; } /* Cancel all delayed transmits */ while (!pj_list_empty(&tcp->delayed_list)) { - struct delayed_tdata *pending_tx; - pj_ioqueue_op_key_t *op_key; + struct delayed_tdata *pending_tx; + pj_ioqueue_op_key_t *op_key; - pending_tx = tcp->delayed_list.next; - pj_list_erase(pending_tx); + pending_tx = tcp->delayed_list.next; + pj_list_erase(pending_tx); - op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; + op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; - on_data_sent(tcp->asock, op_key, -reason); + on_data_sent(tcp->asock, op_key, -reason); } if (tcp->asock) { - pj_activesock_close(tcp->asock); - tcp->asock = NULL; - tcp->sock = PJ_INVALID_SOCKET; + pj_activesock_close(tcp->asock); + tcp->asock = NULL; + tcp->sock = PJ_INVALID_SOCKET; } else if (tcp->sock != PJ_INVALID_SOCKET) { - pj_sock_close(tcp->sock); - tcp->sock = PJ_INVALID_SOCKET; + pj_sock_close(tcp->sock); + tcp->sock = PJ_INVALID_SOCKET; } if (tcp->grp_lock) { - pj_grp_lock_t *grp_lock = tcp->grp_lock; - tcp->grp_lock = NULL; - pj_grp_lock_dec_ref(grp_lock); - /* Transport may have been deleted at this point */ + pj_grp_lock_t *grp_lock = tcp->grp_lock; + tcp->grp_lock = NULL; + pj_grp_lock_dec_ref(grp_lock); + /* Transport may have been deleted at this point */ } return PJ_SUCCESS; @@ -885,41 +884,41 @@ static void tcp_on_destroy(void *arg) struct tcp_transport *tcp = (struct tcp_transport*)arg; if (tcp->base.lock) { - pj_lock_destroy(tcp->base.lock); - tcp->base.lock = NULL; + pj_lock_destroy(tcp->base.lock); + tcp->base.lock = NULL; } if (tcp->base.ref_cnt) { - pj_atomic_destroy(tcp->base.ref_cnt); - tcp->base.ref_cnt = NULL; + pj_atomic_destroy(tcp->base.ref_cnt); + tcp->base.ref_cnt = NULL; } if (tcp->rdata.tp_info.pool) { - pj_pool_release(tcp->rdata.tp_info.pool); - tcp->rdata.tp_info.pool = NULL; + pj_pool_release(tcp->rdata.tp_info.pool); + tcp->rdata.tp_info.pool = NULL; } if (tcp->base.pool) { - pj_pool_t *pool; + pj_pool_t *pool; - if (tcp->close_reason != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; + if (tcp->close_reason != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(tcp->close_reason, errmsg, sizeof(errmsg)); - PJ_LOG(4,(tcp->base.obj_name, - "TCP transport destroyed with reason %d: %s", - tcp->close_reason, errmsg)); + pj_strerror(tcp->close_reason, errmsg, sizeof(errmsg)); + PJ_LOG(4,(tcp->base.obj_name, + "TCP transport destroyed with reason %d: %s", + tcp->close_reason, errmsg)); - } else { + } else { - PJ_LOG(4,(tcp->base.obj_name, - "TCP transport destroyed normally")); + PJ_LOG(4,(tcp->base.obj_name, + "TCP transport destroyed normally")); - } + } - pool = tcp->base.pool; - tcp->base.pool = NULL; - pj_pool_release(pool); + pool = tcp->base.pool; + tcp->base.pool = NULL; + pj_pool_release(pool); } } @@ -938,12 +937,12 @@ static pj_status_t tcp_start_read(struct tcp_transport *tcp) /* Init rdata */ pool = pjsip_endpt_create_pool(tcp->base.endpt, - "rtd%p", - PJSIP_POOL_RDATA_LEN, - PJSIP_POOL_RDATA_INC); + "rtd%p", + PJSIP_POOL_RDATA_LEN, + PJSIP_POOL_RDATA_INC); if (!pool) { - tcp_perror(tcp->base.obj_name, "Unable to create pool", PJ_ENOMEM); - return PJ_ENOMEM; + tcp_perror(tcp->base.obj_name, "Unable to create pool", PJ_ENOMEM); + return PJ_ENOMEM; } tcp->rdata.tp_info.pool = pool; @@ -952,7 +951,7 @@ static pj_status_t tcp_start_read(struct tcp_transport *tcp) tcp->rdata.tp_info.tp_data = tcp; tcp->rdata.tp_info.op_key.rdata = &tcp->rdata; pj_ioqueue_op_key_init(&tcp->rdata.tp_info.op_key.op_key, - sizeof(pj_ioqueue_op_key_t)); + sizeof(pj_ioqueue_op_key_t)); tcp->rdata.pkt_info.src_addr = tcp->base.key.rem_addr; tcp->rdata.pkt_info.src_addr_len = sizeof(tcp->rdata.pkt_info.src_addr); @@ -964,11 +963,11 @@ static pj_status_t tcp_start_read(struct tcp_transport *tcp) size = sizeof(tcp->rdata.pkt_info.packet); readbuf[0] = tcp->rdata.pkt_info.packet; status = pj_activesock_start_read2(tcp->asock, tcp->base.pool, size, - readbuf, 0); + readbuf, 0); if (status != PJ_SUCCESS && status != PJ_EPENDING) { - PJ_PERROR(4, (tcp->base.obj_name, status, - "pj_activesock_start_read() error")); - return status; + PJ_PERROR(4, (tcp->base.obj_name, status, + "pj_activesock_start_read() error")); + return status; } return PJ_SUCCESS; @@ -979,11 +978,11 @@ static pj_status_t tcp_start_read(struct tcp_transport *tcp) * to create outgoing transport to the specified destination. */ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, - pjsip_tpmgr *mgr, - pjsip_endpoint *endpt, - const pj_sockaddr *rem_addr, - int addr_len, - pjsip_transport **p_transport) + pjsip_tpmgr *mgr, + pjsip_endpoint *endpt, + const pj_sockaddr *rem_addr, + int addr_len, + pjsip_transport **p_transport) { struct tcp_listener *listener; struct tcp_transport *tcp; @@ -993,13 +992,13 @@ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, /* Sanity checks */ PJ_ASSERT_RETURN(factory && mgr && endpt && rem_addr && - addr_len && p_transport, PJ_EINVAL); + addr_len && p_transport, PJ_EINVAL); /* Check that address is a sockaddr_in or sockaddr_in6*/ PJ_ASSERT_RETURN((rem_addr->addr.sa_family == pj_AF_INET() && - addr_len == sizeof(pj_sockaddr_in)) || - (rem_addr->addr.sa_family == pj_AF_INET6() && - addr_len == sizeof(pj_sockaddr_in6)), PJ_EINVAL); + addr_len == sizeof(pj_sockaddr_in)) || + (rem_addr->addr.sa_family == pj_AF_INET6() && + addr_len == sizeof(pj_sockaddr_in6)), PJ_EINVAL); listener = (struct tcp_listener*)factory; @@ -1008,17 +1007,17 @@ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, status = pj_sock_socket(rem_addr->addr.sa_family, pj_SOCK_STREAM(), 0, &sock); if (status != PJ_SUCCESS) - return status; + return status; /* Apply QoS, if specified */ status = pj_sock_apply_qos2(sock, listener->qos_type, - &listener->qos_params, - 2, listener->factory.obj_name, - "outgoing SIP TCP socket"); + &listener->qos_params, + 2, listener->factory.obj_name, + "outgoing SIP TCP socket"); /* Apply socket options, if specified */ if (listener->sockopt_params.cnt) - status = pj_sock_setsockopt_params(sock, &listener->sockopt_params); + status = pj_sock_setsockopt_params(sock, &listener->sockopt_params); /* Bind to listener's address and any port */ @@ -1029,73 +1028,73 @@ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, status = pj_sock_bind(sock, &local_addr, pj_sockaddr_get_len(&local_addr)); if (status != PJ_SUCCESS) { - pj_sock_close(sock); - return status; + pj_sock_close(sock); + return status; } /* Get the local port */ addr_len = sizeof(local_addr); status = pj_sock_getsockname(sock, &local_addr, &addr_len); if (status != PJ_SUCCESS) { - pj_sock_close(sock); - return status; + pj_sock_close(sock); + return status; } /* Initially set the address from the listener's address */ if (!pj_sockaddr_has_addr(&local_addr)) { - pj_sockaddr_copy_addr(&local_addr, &listener->factory.local_addr); + pj_sockaddr_copy_addr(&local_addr, &listener->factory.local_addr); } /* Create the transport descriptor */ status = tcp_create(listener, NULL, sock, PJ_FALSE, &local_addr, - rem_addr, &tcp); + rem_addr, &tcp); if (status != PJ_SUCCESS) - return status; + return status; /* Start asynchronous connect() operation */ tcp->has_pending_connect = PJ_TRUE; status = pj_activesock_start_connect(tcp->asock, tcp->base.pool, rem_addr, - addr_len); + addr_len); if (status == PJ_SUCCESS) { - on_connect_complete(tcp->asock, PJ_SUCCESS); + on_connect_complete(tcp->asock, PJ_SUCCESS); } else if (status != PJ_EPENDING) { - tcp_destroy(&tcp->base, status); - return status; + tcp_destroy(&tcp->base, status); + return status; } if (tcp->has_pending_connect) { - char local_addr_buf[PJ_INET6_ADDRSTRLEN+10]; - char remote_addr_buf[PJ_INET6_ADDRSTRLEN+10]; - - /* Update (again) local address, just in case local address currently - * set is different now that asynchronous connect() is started. - */ - addr_len = sizeof(local_addr); - if (pj_sock_getsockname(sock, &local_addr, &addr_len)==PJ_SUCCESS) { - pj_sockaddr *tp_addr = &tcp->base.local_addr; - - /* Some systems (like old Win32 perhaps) may not set local address - * properly before socket is fully connected. - */ - if (pj_sockaddr_cmp(tp_addr, &local_addr) && + char local_addr_buf[PJ_INET6_ADDRSTRLEN+10]; + char remote_addr_buf[PJ_INET6_ADDRSTRLEN+10]; + + /* Update (again) local address, just in case local address currently + * set is different now that asynchronous connect() is started. + */ + addr_len = sizeof(local_addr); + if (pj_sock_getsockname(sock, &local_addr, &addr_len)==PJ_SUCCESS) { + pj_sockaddr *tp_addr = &tcp->base.local_addr; + + /* Some systems (like old Win32 perhaps) may not set local address + * properly before socket is fully connected. + */ + if (pj_sockaddr_cmp(tp_addr, &local_addr) && pj_sockaddr_has_addr(&local_addr) && - pj_sockaddr_get_port(&local_addr) != 0) - { - pj_sockaddr_cp(tp_addr, &local_addr); - sockaddr_to_host_port(tcp->base.pool, &tcp->base.local_name, - &local_addr); - } - } - - PJ_LOG(4,(tcp->base.obj_name, - "TCP transport %s is connecting to %s...", - pj_addr_str_print(&tcp->base.local_name.host, - tcp->base.local_name.port, - local_addr_buf, sizeof(local_addr_buf), 1), - pj_addr_str_print(&tcp->base.remote_name.host, - tcp->base.remote_name.port, - remote_addr_buf, sizeof(remote_addr_buf), 1))); + pj_sockaddr_get_port(&local_addr) != 0) + { + pj_sockaddr_cp(tp_addr, &local_addr); + sockaddr_to_host_port(tcp->base.pool, &tcp->base.local_name, + &local_addr); + } + } + + PJ_LOG(4,(tcp->base.obj_name, + "TCP transport %s is connecting to %s...", + pj_addr_str_print(&tcp->base.local_name.host, + tcp->base.local_name.port, + local_addr_buf, sizeof(local_addr_buf), 1), + pj_addr_str_print(&tcp->base.remote_name.host, + tcp->base.remote_name.port, + remote_addr_buf, sizeof(remote_addr_buf), 1))); } /* Done */ @@ -1110,9 +1109,9 @@ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, * has completed. */ static pj_bool_t on_accept_complete(pj_activesock_t *asock, - pj_sock_t sock, - const pj_sockaddr_t *src_addr, - int src_addr_len) + pj_sock_t sock, + const pj_sockaddr_t *src_addr, + int src_addr_len) { struct tcp_listener *listener; struct tcp_transport *tcp; @@ -1130,26 +1129,26 @@ static pj_bool_t on_accept_complete(pj_activesock_t *asock, PJ_ASSERT_RETURN(sock != PJ_INVALID_SOCKET, PJ_TRUE); if (!listener->is_registered) - return PJ_FALSE; + return PJ_FALSE; PJ_LOG(4,(listener->factory.obj_name, - "TCP listener %s: got incoming TCP connection " - "from %s, sock=%d", - pj_addr_str_print(&listener->factory.addr_name.host, - listener->factory.addr_name.port, addr_buf, - sizeof(addr_buf), 1), - pj_sockaddr_print(src_addr, addr, sizeof(addr), 3), - sock)); + "TCP listener %s: got incoming TCP connection " + "from %s, sock=%d", + pj_addr_str_print(&listener->factory.addr_name.host, + listener->factory.addr_name.port, addr_buf, + sizeof(addr_buf), 1), + pj_sockaddr_print(src_addr, addr, sizeof(addr), 3), + sock)); /* Apply QoS, if specified */ status = pj_sock_apply_qos2(sock, listener->qos_type, - &listener->qos_params, - 2, listener->factory.obj_name, - "incoming SIP TCP socket"); + &listener->qos_params, + 2, listener->factory.obj_name, + "incoming SIP TCP socket"); /* Apply socket options, if specified */ if (listener->sockopt_params.cnt) - status = pj_sock_setsockopt_params(sock, &listener->sockopt_params); + status = pj_sock_setsockopt_params(sock, &listener->sockopt_params); /* tcp_create() expect pj_sockaddr, so copy src_addr to temporary var, * just in case. @@ -1161,7 +1160,7 @@ static pj_bool_t on_accept_complete(pj_activesock_t *asock, addr_len = sizeof(tmp_dst_addr); status = pj_sock_getsockname(sock, &tmp_dst_addr, &addr_len); if (status != PJ_SUCCESS) { - pj_sockaddr_cp(&tmp_dst_addr, &listener->factory.local_addr); + pj_sockaddr_cp(&tmp_dst_addr, &listener->factory.local_addr); } /* @@ -1169,35 +1168,35 @@ static pj_bool_t on_accept_complete(pj_activesock_t *asock, * Create TCP transport for the new socket. */ status = tcp_create( listener, NULL, sock, PJ_TRUE, - &tmp_dst_addr, &tmp_src_addr, &tcp); + &tmp_dst_addr, &tmp_src_addr, &tcp); if (status == PJ_SUCCESS) { - status = tcp_start_read(tcp); - if (status != PJ_SUCCESS) { - PJ_LOG(3,(tcp->base.obj_name, "New transport cancelled")); - tcp_destroy(&tcp->base, status); - } else { - if (tcp->base.is_shutdown || tcp->base.is_destroying) { - return PJ_TRUE; - } - /* Start keep-alive timer */ - if (pjsip_cfg()->tcp.keep_alive_interval) { - pj_time_val delay = { 0 }; - delay.sec = pjsip_cfg()->tcp.keep_alive_interval; - pjsip_endpt_schedule_timer(listener->endpt, - &tcp->ka_timer, - &delay); - tcp->ka_timer.id = PJ_TRUE; - pj_gettimeofday(&tcp->last_activity); - } - /* Notify application of transport state accepted */ - state_cb = pjsip_tpmgr_get_state_cb(tcp->base.tpmgr); - if (state_cb) { - pjsip_transport_state_info state_info; - - pj_bzero(&state_info, sizeof(state_info)); - (*state_cb)(&tcp->base, PJSIP_TP_STATE_CONNECTED, &state_info); - } - } + status = tcp_start_read(tcp); + if (status != PJ_SUCCESS) { + PJ_LOG(3,(tcp->base.obj_name, "New transport cancelled")); + tcp_destroy(&tcp->base, status); + } else { + if (tcp->base.is_shutdown || tcp->base.is_destroying) { + return PJ_TRUE; + } + /* Start keep-alive timer */ + if (pjsip_cfg()->tcp.keep_alive_interval) { + pj_time_val delay = { 0 }; + delay.sec = pjsip_cfg()->tcp.keep_alive_interval; + pjsip_endpt_schedule_timer(listener->endpt, + &tcp->ka_timer, + &delay); + tcp->ka_timer.id = PJ_TRUE; + pj_gettimeofday(&tcp->last_activity); + } + /* Notify application of transport state accepted */ + state_cb = pjsip_tpmgr_get_state_cb(tcp->base.tpmgr); + if (state_cb) { + pjsip_transport_state_info state_info; + + pj_bzero(&state_info, sizeof(state_info)); + (*state_cb)(&tcp->base, PJSIP_TP_STATE_CONNECTED, &state_info); + } + } } return PJ_TRUE; @@ -1208,11 +1207,11 @@ static pj_bool_t on_accept_complete(pj_activesock_t *asock, * Callback from ioqueue when packet is sent. */ static pj_bool_t on_data_sent(pj_activesock_t *asock, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_sent) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_sent) { struct tcp_transport *tcp = (struct tcp_transport*) - pj_activesock_get_user_data(asock); + pj_activesock_get_user_data(asock); pjsip_tx_data_op_key *tdata_op_key = (pjsip_tx_data_op_key*)op_key; /* Note that op_key may be the op_key from keep-alive, thus @@ -1222,32 +1221,32 @@ static pj_bool_t on_data_sent(pj_activesock_t *asock, tdata_op_key->tdata = NULL; if (tdata_op_key->callback) { - /* - * Notify sip_transport.c that packet has been sent. - */ - if (bytes_sent == 0) - bytes_sent = -PJ_RETURN_OS_ERROR(OSERR_ENOTCONN); + /* + * Notify sip_transport.c that packet has been sent. + */ + if (bytes_sent == 0) + bytes_sent = -PJ_RETURN_OS_ERROR(OSERR_ENOTCONN); - tdata_op_key->callback(&tcp->base, tdata_op_key->token, bytes_sent); + tdata_op_key->callback(&tcp->base, tdata_op_key->token, bytes_sent); - /* Mark last activity time */ - pj_gettimeofday(&tcp->last_activity); + /* Mark last activity time */ + pj_gettimeofday(&tcp->last_activity); } /* Check for error/closure */ if (bytes_sent <= 0) { - pj_status_t status; + pj_status_t status; - PJ_LOG(5,(tcp->base.obj_name, "TCP send() error, sent=%d", - bytes_sent)); + PJ_LOG(5,(tcp->base.obj_name, "TCP send() error, sent=%d", + bytes_sent)); - status = (bytes_sent == 0) ? PJ_RETURN_OS_ERROR(OSERR_ENOTCONN) : - (pj_status_t)-bytes_sent; + status = (bytes_sent == 0) ? PJ_RETURN_OS_ERROR(OSERR_ENOTCONN) : + (pj_status_t)-bytes_sent; - tcp_init_shutdown(tcp, status); + tcp_init_shutdown(tcp, status); - return PJ_FALSE; + return PJ_FALSE; } return PJ_TRUE; @@ -1258,11 +1257,11 @@ static pj_bool_t on_data_sent(pj_activesock_t *asock, * This callback is called by transport manager to send SIP message */ static pj_status_t tcp_send_msg(pjsip_transport *transport, - pjsip_tx_data *tdata, - const pj_sockaddr_t *rem_addr, - int addr_len, - void *token, - pjsip_transport_callback callback) + pjsip_tx_data *tdata, + const pj_sockaddr_t *rem_addr, + int addr_len, + void *token, + pjsip_transport_callback callback) { struct tcp_transport *tcp = (struct tcp_transport*)transport; pj_ssize_t size; @@ -1277,8 +1276,8 @@ static pj_status_t tcp_send_msg(pjsip_transport *transport, /* Check the address is supported */ PJ_ASSERT_RETURN(rem_addr && (addr_len==sizeof(pj_sockaddr_in) || - addr_len==sizeof(pj_sockaddr_in6)), - PJ_EINVAL); + addr_len==sizeof(pj_sockaddr_in6)), + PJ_EINVAL); /* Init op key. */ tdata->op_key.tdata = tdata; @@ -1291,68 +1290,68 @@ static pj_status_t tcp_send_msg(pjsip_transport *transport, */ if (tcp->has_pending_connect) { - /* - * Looks like connect() is still in progress. Check again (this time - * with holding the lock) to be sure. - */ - pj_lock_acquire(tcp->base.lock); + /* + * Looks like connect() is still in progress. Check again (this time + * with holding the lock) to be sure. + */ + pj_lock_acquire(tcp->base.lock); - if (tcp->has_pending_connect) { - struct delayed_tdata *delayed_tdata; + if (tcp->has_pending_connect) { + struct delayed_tdata *delayed_tdata; - /* - * connect() is still in progress. Put the transmit data to - * the delayed list. + /* + * connect() is still in progress. Put the transmit data to + * the delayed list. * Starting from #1583 (https://github.com/pjsip/pjproject/issues/1583), * we also add timeout value for the transmit data. When the * connect() is completed, the timeout value will be checked to * determine whether the transmit data needs to be sent. - */ - delayed_tdata = PJ_POOL_ZALLOC_T(tdata->pool, - struct delayed_tdata); - delayed_tdata->tdata_op_key = &tdata->op_key; + */ + delayed_tdata = PJ_POOL_ZALLOC_T(tdata->pool, + struct delayed_tdata); + delayed_tdata->tdata_op_key = &tdata->op_key; if (tdata->msg && tdata->msg->type == PJSIP_REQUEST_MSG) { pj_gettickcount(&delayed_tdata->timeout); delayed_tdata->timeout.msec += pjsip_cfg()->tsx.td; pj_time_val_normalize(&delayed_tdata->timeout); } - pj_list_push_back(&tcp->delayed_list, delayed_tdata); - status = PJ_EPENDING; + pj_list_push_back(&tcp->delayed_list, delayed_tdata); + status = PJ_EPENDING; - /* Prevent pj_ioqueue_send() to be called below */ - delayed = PJ_TRUE; - } + /* Prevent pj_ioqueue_send() to be called below */ + delayed = PJ_TRUE; + } - pj_lock_release(tcp->base.lock); + pj_lock_release(tcp->base.lock); } if (!delayed) { - /* - * Transport is ready to go. Send the packet to ioqueue to be - * sent asynchronously. - */ - size = tdata->buf.cur - tdata->buf.start; - status = pj_activesock_send(tcp->asock, - (pj_ioqueue_op_key_t*)&tdata->op_key, - tdata->buf.start, &size, 0); - - if (status != PJ_EPENDING) { - /* Not pending (could be immediate success or error) */ - tdata->op_key.tdata = NULL; - - /* Shutdown transport on closure/errors */ - if (size <= 0) { - - PJ_LOG(5,(tcp->base.obj_name, "TCP send() error, sent=%d", - size)); - - if (status == PJ_SUCCESS) - status = PJ_RETURN_OS_ERROR(OSERR_ENOTCONN); - - tcp_init_shutdown(tcp, status); - } - } + /* + * Transport is ready to go. Send the packet to ioqueue to be + * sent asynchronously. + */ + size = tdata->buf.cur - tdata->buf.start; + status = pj_activesock_send(tcp->asock, + (pj_ioqueue_op_key_t*)&tdata->op_key, + tdata->buf.start, &size, 0); + + if (status != PJ_EPENDING) { + /* Not pending (could be immediate success or error) */ + tdata->op_key.tdata = NULL; + + /* Shutdown transport on closure/errors */ + if (size <= 0) { + + PJ_LOG(5,(tcp->base.obj_name, "TCP send() error, sent=%d", + size)); + + if (status == PJ_SUCCESS) + status = PJ_RETURN_OS_ERROR(OSERR_ENOTCONN); + + tcp_init_shutdown(tcp, status); + } + } } return status; @@ -1368,14 +1367,14 @@ static pj_status_t tcp_shutdown(pjsip_transport *transport) /* Stop keep-alive timer. */ if (tcp->ka_timer.id) { - pjsip_endpt_cancel_timer(tcp->base.endpt, &tcp->ka_timer); - tcp->ka_timer.id = PJ_FALSE; + pjsip_endpt_cancel_timer(tcp->base.endpt, &tcp->ka_timer); + tcp->ka_timer.id = PJ_FALSE; } /* Stop initial timer. */ if (tcp->initial_timer.id) { - pjsip_endpt_cancel_timer(tcp->base.endpt, &tcp->initial_timer); - tcp->initial_timer.id = PJ_FALSE; + pjsip_endpt_cancel_timer(tcp->base.endpt, &tcp->initial_timer); + tcp->initial_timer.id = PJ_FALSE; } return PJ_SUCCESS; @@ -1386,10 +1385,10 @@ static pj_status_t tcp_shutdown(pjsip_transport *transport) * Callback from ioqueue that an incoming data is received from the socket. */ static pj_bool_t on_data_read(pj_activesock_t *asock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { enum { MAX_IMMEDIATE_PACKET = 10 }; struct tcp_transport *tcp; @@ -1402,57 +1401,57 @@ static pj_bool_t on_data_read(pj_activesock_t *asock, /* Don't do anything if transport is closing. */ if (tcp->is_closing) { - tcp->is_closing++; - return PJ_FALSE; + tcp->is_closing++; + return PJ_FALSE; } if (tcp->initial_timer.id) { - pjsip_endpt_cancel_timer(tcp->base.endpt, &tcp->initial_timer); - tcp->initial_timer.id = PJ_FALSE; + pjsip_endpt_cancel_timer(tcp->base.endpt, &tcp->initial_timer); + tcp->initial_timer.id = PJ_FALSE; } /* Houston, we have packet! Report the packet to transport manager * to be parsed. */ if (status == PJ_SUCCESS) { - pj_size_t size_eaten; - - /* Mark this as an activity */ - pj_gettimeofday(&tcp->last_activity); - - pj_assert((void*)rdata->pkt_info.packet == data); - - /* Init pkt_info part. */ - rdata->pkt_info.len = size; - rdata->pkt_info.zero = 0; - pj_gettimeofday(&rdata->pkt_info.timestamp); - - /* Report to transport manager. - * The transport manager will tell us how many bytes of the packet - * have been processed (as valid SIP message). - */ - size_eaten = - pjsip_tpmgr_receive_packet(rdata->tp_info.transport->tpmgr, - rdata); - - pj_assert(size_eaten <= (pj_size_t)rdata->pkt_info.len); - - /* Move unprocessed data to the front of the buffer */ - *remainder = size - size_eaten; - if (*remainder > 0 && *remainder != size) { - pj_memmove(rdata->pkt_info.packet, - rdata->pkt_info.packet + size_eaten, - *remainder); - } + pj_size_t size_eaten; + + /* Mark this as an activity */ + pj_gettimeofday(&tcp->last_activity); + + pj_assert((void*)rdata->pkt_info.packet == data); + + /* Init pkt_info part. */ + rdata->pkt_info.len = size; + rdata->pkt_info.zero = 0; + pj_gettimeofday(&rdata->pkt_info.timestamp); + + /* Report to transport manager. + * The transport manager will tell us how many bytes of the packet + * have been processed (as valid SIP message). + */ + size_eaten = + pjsip_tpmgr_receive_packet(rdata->tp_info.transport->tpmgr, + rdata); + + pj_assert(size_eaten <= (pj_size_t)rdata->pkt_info.len); + + /* Move unprocessed data to the front of the buffer */ + *remainder = size - size_eaten; + if (*remainder > 0 && *remainder != size) { + pj_memmove(rdata->pkt_info.packet, + rdata->pkt_info.packet + size_eaten, + *remainder); + } } else { - /* Transport is closed */ - PJ_LOG(4,(tcp->base.obj_name, "TCP connection closed")); - - tcp_init_shutdown(tcp, status); + /* Transport is closed */ + PJ_LOG(4,(tcp->base.obj_name, "TCP connection closed")); + + tcp_init_shutdown(tcp, status); - return PJ_FALSE; + return PJ_FALSE; } @@ -1467,7 +1466,7 @@ static pj_bool_t on_data_read(pj_activesock_t *asock, * Callback from ioqueue when asynchronous connect() operation completes. */ static pj_bool_t on_connect_complete(pj_activesock_t *asock, - pj_status_t status) + pj_status_t status) { struct tcp_transport *tcp; pj_sockaddr addr; @@ -1487,41 +1486,41 @@ static pj_bool_t on_connect_complete(pj_activesock_t *asock, * (see #1898). */ if ((tcp->base.is_shutdown || tcp->base.is_destroying) && - status == PJ_SUCCESS) + status == PJ_SUCCESS) { - status = PJ_ECANCELLED; + status = PJ_ECANCELLED; } /* Check connect() status */ if (status != PJ_SUCCESS) { - tcp_perror(tcp->base.obj_name, "TCP connect() error", status); + tcp_perror(tcp->base.obj_name, "TCP connect() error", status); - /* Cancel all delayed transmits */ - while (!pj_list_empty(&tcp->delayed_list)) { - struct delayed_tdata *pending_tx; - pj_ioqueue_op_key_t *op_key; + /* Cancel all delayed transmits */ + while (!pj_list_empty(&tcp->delayed_list)) { + struct delayed_tdata *pending_tx; + pj_ioqueue_op_key_t *op_key; - pending_tx = tcp->delayed_list.next; - pj_list_erase(pending_tx); + pending_tx = tcp->delayed_list.next; + pj_list_erase(pending_tx); - op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; + op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; - on_data_sent(tcp->asock, op_key, -status); - } + on_data_sent(tcp->asock, op_key, -status); + } - tcp_init_shutdown(tcp, status); - return PJ_FALSE; + tcp_init_shutdown(tcp, status); + return PJ_FALSE; } PJ_LOG(4,(tcp->base.obj_name, - "TCP transport %s is connected to %s", - pj_addr_str_print(&tcp->base.local_name.host, - tcp->base.local_name.port, local_addr_buf, - sizeof(local_addr_buf), 1), - pj_addr_str_print(&tcp->base.remote_name.host, - tcp->base.remote_name.port, remote_addr_buf, - sizeof(remote_addr_buf), 1))); + "TCP transport %s is connected to %s", + pj_addr_str_print(&tcp->base.local_name.host, + tcp->base.local_name.port, local_addr_buf, + sizeof(local_addr_buf), 1), + pj_addr_str_print(&tcp->base.remote_name.host, + tcp->base.remote_name.port, remote_addr_buf, + sizeof(remote_addr_buf), 1))); /* Update (again) local address, just in case local address currently @@ -1530,31 +1529,31 @@ static pj_bool_t on_connect_complete(pj_activesock_t *asock, */ addrlen = sizeof(addr); if (pj_sock_getsockname(tcp->sock, &addr, &addrlen)==PJ_SUCCESS) { - pj_sockaddr *tp_addr = &tcp->base.local_addr; - - if (pj_sockaddr_has_addr(&addr) && - pj_sockaddr_cmp(&addr, tp_addr) != 0) - { - pj_sockaddr_cp(tp_addr, &addr); - sockaddr_to_host_port(tcp->base.pool, &tcp->base.local_name, - tp_addr); - } + pj_sockaddr *tp_addr = &tcp->base.local_addr; + + if (pj_sockaddr_has_addr(&addr) && + pj_sockaddr_cmp(&addr, tp_addr) != 0) + { + pj_sockaddr_cp(tp_addr, &addr); + sockaddr_to_host_port(tcp->base.pool, &tcp->base.local_name, + tp_addr); + } } /* Start pending read */ status = tcp_start_read(tcp); if (status != PJ_SUCCESS) { - tcp_init_shutdown(tcp, status); - return PJ_FALSE; + tcp_init_shutdown(tcp, status); + return PJ_FALSE; } /* Notify application of transport state connected */ state_cb = pjsip_tpmgr_get_state_cb(tcp->base.tpmgr); if (state_cb) { - pjsip_transport_state_info state_info; - - pj_bzero(&state_info, sizeof(state_info)); - (*state_cb)(&tcp->base, PJSIP_TP_STATE_CONNECTED, &state_info); + pjsip_transport_state_info state_info; + + pj_bzero(&state_info, sizeof(state_info)); + (*state_cb)(&tcp->base, PJSIP_TP_STATE_CONNECTED, &state_info); } /* Flush all pending send operations */ @@ -1562,12 +1561,12 @@ static pj_bool_t on_connect_complete(pj_activesock_t *asock, /* Start keep-alive timer */ if (pjsip_cfg()->tcp.keep_alive_interval) { - pj_time_val delay = { 0 }; - delay.sec = pjsip_cfg()->tcp.keep_alive_interval; - pjsip_endpt_schedule_timer(tcp->base.endpt, &tcp->ka_timer, - &delay); - tcp->ka_timer.id = PJ_TRUE; - pj_gettimeofday(&tcp->last_activity); + pj_time_val delay = { 0 }; + delay.sec = pjsip_cfg()->tcp.keep_alive_interval; + pjsip_endpt_schedule_timer(tcp->base.endpt, &tcp->ka_timer, + &delay); + tcp->ka_timer.id = PJ_TRUE; + pj_gettimeofday(&tcp->last_activity); } return PJ_TRUE; @@ -1591,32 +1590,32 @@ static void tcp_keep_alive_timer(pj_timer_heap_t *th, pj_timer_entry *e) PJ_TIME_VAL_SUB(now, tcp->last_activity); if (now.sec > 0 && now.sec < pjsip_cfg()->tcp.keep_alive_interval) { - /* There has been activity, so don't send keep-alive */ - delay.sec = pjsip_cfg()->tcp.keep_alive_interval - now.sec; - delay.msec = 0; - - pjsip_endpt_schedule_timer(tcp->base.endpt, &tcp->ka_timer, - &delay); - tcp->ka_timer.id = PJ_TRUE; - return; + /* There has been activity, so don't send keep-alive */ + delay.sec = pjsip_cfg()->tcp.keep_alive_interval - now.sec; + delay.msec = 0; + + pjsip_endpt_schedule_timer(tcp->base.endpt, &tcp->ka_timer, + &delay); + tcp->ka_timer.id = PJ_TRUE; + return; } PJ_LOG(5,(tcp->base.obj_name, "Sending %d byte(s) keep-alive to %s", - (int)tcp->ka_pkt.slen, - pj_addr_str_print(&tcp->base.remote_name.host, - tcp->base.remote_name.port, addr, - sizeof(addr), 1))); + (int)tcp->ka_pkt.slen, + pj_addr_str_print(&tcp->base.remote_name.host, + tcp->base.remote_name.port, addr, + sizeof(addr), 1))); /* Send the data */ size = tcp->ka_pkt.slen; status = pj_activesock_send(tcp->asock, &tcp->ka_op_key.key, - tcp->ka_pkt.ptr, &size, 0); + tcp->ka_pkt.ptr, &size, 0); if (status != PJ_SUCCESS && status != PJ_EPENDING) { - tcp_perror(tcp->base.obj_name, - "Error sending keep-alive packet", status); - tcp_init_shutdown(tcp, status); - return; + tcp_perror(tcp->base.obj_name, + "Error sending keep-alive packet", status); + tcp_init_shutdown(tcp, status); + return; } /* Register next keep-alive */ @@ -1624,7 +1623,7 @@ static void tcp_keep_alive_timer(pj_timer_heap_t *th, pj_timer_entry *e) delay.msec = 0; pjsip_endpt_schedule_timer(tcp->base.endpt, &tcp->ka_timer, - &delay); + &delay); tcp->ka_timer.id = PJ_TRUE; } @@ -1649,8 +1648,8 @@ PJ_DEF(pj_sock_t) pjsip_tcp_transport_get_socket(pjsip_transport *transport) PJ_DEF(pj_status_t) pjsip_tcp_transport_lis_start(pjsip_tpfactory *factory, - const pj_sockaddr *local, - const pjsip_host_port *a_name) + const pj_sockaddr *local, + const pjsip_host_port *a_name) { pj_activesock_cfg asock_cfg; pj_activesock_cb listener_cb; @@ -1662,7 +1661,7 @@ PJ_DEF(pj_status_t) pjsip_tcp_transport_lis_start(pjsip_tpfactory *factory, /* Nothing to be done, if listener already started. */ if (listener->asock) - return PJ_SUCCESS; + return PJ_SUCCESS; update_bound_addr(listener, local); @@ -1672,69 +1671,69 @@ PJ_DEF(pj_status_t) pjsip_tcp_transport_lis_start(pjsip_tpfactory *factory, /* Create socket */ status = pj_sock_socket(af, pj_SOCK_STREAM(), 0, &sock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Apply QoS, if specified */ status = pj_sock_apply_qos2(sock, listener->qos_type, - &listener->qos_params, 2, - listener->factory.obj_name, - "SIP TCP listener socket"); + &listener->qos_params, 2, + listener->factory.obj_name, + "SIP TCP listener socket"); /* Apply SO_REUSEADDR */ if (listener->reuse_addr) { - int enabled = 1; - status = pj_sock_setsockopt(sock, pj_SOL_SOCKET(), pj_SO_REUSEADDR(), - &enabled, sizeof(enabled)); - if (status != PJ_SUCCESS) { - PJ_PERROR(4, (listener->factory.obj_name, status, - "Warning: error applying SO_REUSEADDR")); - } + int enabled = 1; + status = pj_sock_setsockopt(sock, pj_SOL_SOCKET(), pj_SO_REUSEADDR(), + &enabled, sizeof(enabled)); + if (status != PJ_SUCCESS) { + PJ_PERROR(4, (listener->factory.obj_name, status, + "Warning: error applying SO_REUSEADDR")); + } } /* Apply socket options, if specified */ if (listener->sockopt_params.cnt) - status = pj_sock_setsockopt_params(sock, &listener->sockopt_params); + status = pj_sock_setsockopt_params(sock, &listener->sockopt_params); status = pj_sock_bind(sock, listener_addr, addr_len); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Retrieve the bound address */ status = pj_sock_getsockname(sock, &listener->factory.local_addr, - &addr_len); + &addr_len); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = update_factory_addr(listener, a_name); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Start listening to the address */ status = pj_sock_listen(sock, PJSIP_TCP_TRANSPORT_BACKLOG); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Create active socket */ pj_activesock_cfg_default(&asock_cfg); if (listener->async_cnt > MAX_ASYNC_CNT) - asock_cfg.async_cnt = MAX_ASYNC_CNT; + asock_cfg.async_cnt = MAX_ASYNC_CNT; else - asock_cfg.async_cnt = listener->async_cnt; + asock_cfg.async_cnt = listener->async_cnt; asock_cfg.grp_lock = listener->grp_lock; pj_bzero(&listener_cb, sizeof(listener_cb)); listener_cb.on_accept_complete = &on_accept_complete; status = pj_activesock_create(listener->factory.pool, sock, - pj_SOCK_STREAM(), &asock_cfg, - pjsip_endpt_get_ioqueue(listener->endpt), - &listener_cb, listener, - &listener->asock); + pj_SOCK_STREAM(), &asock_cfg, + pjsip_endpt_get_ioqueue(listener->endpt), + &listener_cb, listener, + &listener->asock); /* Start pending accept() operations */ status = pj_activesock_start_accept(listener->asock, - listener->factory.pool); + listener->factory.pool); update_transport_info(listener); @@ -1742,15 +1741,15 @@ PJ_DEF(pj_status_t) pjsip_tcp_transport_lis_start(pjsip_tpfactory *factory, on_error: if (listener->asock == NULL && sock != PJ_INVALID_SOCKET) - pj_sock_close(sock); + pj_sock_close(sock); return status; } PJ_DEF(pj_status_t) pjsip_tcp_transport_restart(pjsip_tpfactory *factory, - const pj_sockaddr *local, - const pjsip_host_port *a_name) + const pj_sockaddr *local, + const pjsip_host_port *a_name) { pj_status_t status = PJ_SUCCESS; struct tcp_listener *listener = (struct tcp_listener *)factory; @@ -1758,24 +1757,24 @@ PJ_DEF(pj_status_t) pjsip_tcp_transport_restart(pjsip_tpfactory *factory, lis_close(listener); status = pjsip_tcp_transport_lis_start(factory, local, a_name); - if (status != PJ_SUCCESS) { - tcp_perror(listener->factory.obj_name, - "Unable to start listener after closing it", status); + if (status != PJ_SUCCESS) { + tcp_perror(listener->factory.obj_name, + "Unable to start listener after closing it", status); - return status; + return status; } status = pjsip_tpmgr_register_tpfactory(listener->tpmgr, - &listener->factory); + &listener->factory); if (status != PJ_SUCCESS) { - tcp_perror(listener->factory.obj_name, - "Unable to register the transport listener", status); + tcp_perror(listener->factory.obj_name, + "Unable to register the transport listener", status); } else { - listener->is_registered = PJ_TRUE; + listener->is_registered = PJ_TRUE; } return status; } -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ diff --git a/pjsip/src/pjsip/sip_transport_tls.c b/pjsip/src/pjsip/sip_transport_tls.c index 6c4011b020..ad59a1e60d 100644 --- a/pjsip/src/pjsip/sip_transport_tls.c +++ b/pjsip/src/pjsip/sip_transport_tls.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * @@ -33,13 +32,13 @@ #if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0 -#define THIS_FILE "sip_transport_tls.c" +#define THIS_FILE "sip_transport_tls.c" -#define MAX_ASYNC_CNT 16 -#define POOL_LIS_INIT 512 -#define POOL_LIS_INC 512 -#define POOL_TP_INIT 512 -#define POOL_TP_INC 512 +#define MAX_ASYNC_CNT 16 +#define POOL_LIS_INIT 512 +#define POOL_LIS_INC 512 +#define POOL_TP_INIT 512 +#define POOL_TP_INC 512 struct tls_listener; struct tls_transport; @@ -50,18 +49,18 @@ struct tls_transport; */ struct tls_listener { - pjsip_tpfactory factory; - pj_bool_t is_registered; - pjsip_endpoint *endpt; - pjsip_tpmgr *tpmgr; - pj_ssl_sock_t *ssock; - pj_sockaddr bound_addr; - pj_ssl_cert_t *cert; - pjsip_tls_setting tls_setting; - unsigned async_cnt; + pjsip_tpfactory factory; + pj_bool_t is_registered; + pjsip_endpoint *endpt; + pjsip_tpmgr *tpmgr; + pj_ssl_sock_t *ssock; + pj_sockaddr bound_addr; + pj_ssl_cert_t *cert; + pjsip_tls_setting tls_setting; + unsigned async_cnt; /* Group lock to be used by TLS transport and ioqueue key */ - pj_grp_lock_t *grp_lock; + pj_grp_lock_t *grp_lock; }; @@ -85,34 +84,34 @@ struct delayed_tdata */ struct tls_transport { - pjsip_transport base; - pj_bool_t is_server; - pj_str_t remote_name; + pjsip_transport base; + pj_bool_t is_server; + pj_str_t remote_name; - pj_bool_t is_registered; - pj_bool_t is_closing; - pj_status_t close_reason; - pj_ssl_sock_t *ssock; - pj_bool_t has_pending_connect; - pj_bool_t verify_server; + pj_bool_t is_registered; + pj_bool_t is_closing; + pj_status_t close_reason; + pj_ssl_sock_t *ssock; + pj_bool_t has_pending_connect; + pj_bool_t verify_server; /* Keep-alive timer. */ - pj_timer_entry ka_timer; - pj_time_val last_activity; + pj_timer_entry ka_timer; + pj_time_val last_activity; pjsip_tx_data_op_key ka_op_key; - pj_str_t ka_pkt; + pj_str_t ka_pkt; /* TLS transport can only have one rdata! * Otherwise chunks of incoming PDU may be received on different * buffer. */ - pjsip_rx_data rdata; + pjsip_rx_data rdata; /* Pending transmission list. */ struct delayed_tdata delayed_list; /* Group lock to be used by TLS transport and ioqueue key */ - pj_grp_lock_t *grp_lock; + pj_grp_lock_t *grp_lock; /* Verify callback. */ pj_bool_t(*on_verify_cb)(const pjsip_tls_on_verify_param *param); @@ -125,22 +124,22 @@ struct tls_transport /* This callback is called when pending accept() operation completes. */ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock, - pj_ssl_sock_t *new_ssock, - const pj_sockaddr_t *src_addr, - int src_addr_len, - pj_status_t status); + pj_ssl_sock_t *new_ssock, + const pj_sockaddr_t *src_addr, + int src_addr_len, + pj_status_t status); /* Callback on incoming data */ static pj_bool_t on_data_read(pj_ssl_sock_t *ssock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder); + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder); /* Callback when packet is sent */ static pj_bool_t on_data_sent(pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *send_key, - pj_ssize_t sent); + pj_ioqueue_op_key_t *send_key, + pj_ssize_t sent); static pj_bool_t on_verify_cb(pj_ssl_sock_t *ssock, pj_bool_t is_server); @@ -152,23 +151,23 @@ static void lis_on_destroy(void *arg); /* This callback is called by transport manager to create transport */ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, - pjsip_tpmgr *mgr, - pjsip_endpoint *endpt, - const pj_sockaddr *rem_addr, - int addr_len, - pjsip_tx_data *tdata, - pjsip_transport **transport); + pjsip_tpmgr *mgr, + pjsip_endpoint *endpt, + const pj_sockaddr *rem_addr, + int addr_len, + pjsip_tx_data *tdata, + pjsip_transport **transport); /* Common function to create and initialize transport */ static pj_status_t tls_create(struct tls_listener *listener, - pj_pool_t *pool, - pj_ssl_sock_t *ssock, - pj_bool_t is_server, - const pj_sockaddr *local, - const pj_sockaddr *remote, - const pj_str_t *remote_name, - pj_grp_lock_t *glock, - struct tls_transport **p_tls); + pj_pool_t *pool, + pj_ssl_sock_t *ssock, + pj_bool_t is_server, + const pj_sockaddr *local, + const pj_sockaddr *remote, + const pj_str_t *remote_name, + pj_grp_lock_t *glock, + struct tls_transport **p_tls); /* Clean up TLS resources */ @@ -178,17 +177,17 @@ static void wipe_buf(pj_str_t *buf); static void tls_perror(const char *sender, const char *title, - pj_status_t status, pj_str_t *remote_name) + pj_status_t status, pj_str_t *remote_name) { PJ_PERROR(3,(sender, status, "%s: [code=%d]%s%.*s", title, status, remote_name ? " peer: " : "", remote_name ? remote_name->slen : 0, - remote_name ? remote_name->ptr : "")); + remote_name ? remote_name->ptr : "")); } static void sockaddr_to_host_port( pj_pool_t *pool, - pjsip_host_port *host_port, - const pj_sockaddr *addr ) + pjsip_host_port *host_port, + const pj_sockaddr *addr ) { host_port->host.ptr = (char*) pj_pool_alloc(pool, PJ_INET6_ADDRSTRLEN+4); pj_sockaddr_print(addr, host_port->host.ptr, PJ_INET6_ADDRSTRLEN+4, 0); @@ -202,36 +201,36 @@ static pj_uint32_t ssl_get_proto(pjsip_ssl_method ssl_method, pj_uint32_t proto) pj_uint32_t out_proto; if (proto) - return proto; + return proto; if (ssl_method == PJSIP_SSL_UNSPECIFIED_METHOD) - ssl_method = PJSIP_SSL_DEFAULT_METHOD; + ssl_method = PJSIP_SSL_DEFAULT_METHOD; switch(ssl_method) { case PJSIP_SSLV2_METHOD: - out_proto = PJ_SSL_SOCK_PROTO_SSL2; - break; + out_proto = PJ_SSL_SOCK_PROTO_SSL2; + break; case PJSIP_SSLV3_METHOD: - out_proto = PJ_SSL_SOCK_PROTO_SSL3; - break; + out_proto = PJ_SSL_SOCK_PROTO_SSL3; + break; case PJSIP_TLSV1_METHOD: - out_proto = PJ_SSL_SOCK_PROTO_TLS1; - break; + out_proto = PJ_SSL_SOCK_PROTO_TLS1; + break; case PJSIP_TLSV1_1_METHOD: - out_proto = PJ_SSL_SOCK_PROTO_TLS1_1; - break; + out_proto = PJ_SSL_SOCK_PROTO_TLS1_1; + break; case PJSIP_TLSV1_2_METHOD: - out_proto = PJ_SSL_SOCK_PROTO_TLS1_2; - break; + out_proto = PJ_SSL_SOCK_PROTO_TLS1_2; + break; case PJSIP_TLSV1_3_METHOD: - out_proto = PJ_SSL_SOCK_PROTO_TLS1_3; - break; + out_proto = PJ_SSL_SOCK_PROTO_TLS1_3; + break; case PJSIP_SSLV23_METHOD: - out_proto = PJ_SSL_SOCK_PROTO_SSL23; - break; + out_proto = PJ_SSL_SOCK_PROTO_SSL23; + break; default: - out_proto = PJ_SSL_SOCK_PROTO_DEFAULT; - break; + out_proto = PJ_SSL_SOCK_PROTO_DEFAULT; + break; } return out_proto; } @@ -242,10 +241,10 @@ static void tls_init_shutdown(struct tls_transport *tls, pj_status_t status) pjsip_tp_state_callback state_cb; if (tls->close_reason == PJ_SUCCESS) - tls->close_reason = status; + tls->close_reason = status; if (tls->base.is_shutdown || tls->base.is_destroying) - return; + return; /* Prevent immediate transport destroy by application, as transport * state notification callback may be stacked and transport instance @@ -256,29 +255,29 @@ static void tls_init_shutdown(struct tls_transport *tls, pj_status_t status) /* Notify application of transport disconnected state */ state_cb = pjsip_tpmgr_get_state_cb(tls->base.tpmgr); if (state_cb) { - pjsip_transport_state_info state_info; - pjsip_tls_state_info tls_info; - pj_ssl_sock_info ssl_info; - - /* Init transport state info */ - pj_bzero(&state_info, sizeof(state_info)); - state_info.status = tls->close_reason; - - if (tls->ssock && - pj_ssl_sock_get_info(tls->ssock, &ssl_info) == PJ_SUCCESS) - { - pj_bzero(&tls_info, sizeof(tls_info)); - tls_info.ssl_sock_info = &ssl_info; - state_info.ext_info = &tls_info; - } + pjsip_transport_state_info state_info; + pjsip_tls_state_info tls_info; + pj_ssl_sock_info ssl_info; + + /* Init transport state info */ + pj_bzero(&state_info, sizeof(state_info)); + state_info.status = tls->close_reason; + + if (tls->ssock && + pj_ssl_sock_get_info(tls->ssock, &ssl_info) == PJ_SUCCESS) + { + pj_bzero(&tls_info, sizeof(tls_info)); + tls_info.ssl_sock_info = &ssl_info; + state_info.ext_info = &tls_info; + } - (*state_cb)(&tls->base, PJSIP_TP_STATE_DISCONNECTED, &state_info); + (*state_cb)(&tls->base, PJSIP_TP_STATE_DISCONNECTED, &state_info); } /* check again */ if (tls->base.is_shutdown || tls->base.is_destroying) { pjsip_transport_dec_ref(&tls->base); - return; + return; } /* We can not destroy the transport since high level objects may @@ -310,7 +309,7 @@ static void set_ssock_param(pj_ssl_sock_param *ssock_param, ssock_param->sock_af = af; ssock_param->cb.on_accept_complete2 = &on_accept_complete2; if (listener->tls_setting.on_verify_cb) - ssock_param->cb.on_verify_cb = &on_verify_cb; + ssock_param->cb.on_verify_cb = &on_verify_cb; ssock_param->async_cnt = listener->async_cnt; ssock_param->ioqueue = pjsip_endpt_get_ioqueue(listener->endpt); @@ -319,11 +318,11 @@ static void set_ssock_param(pj_ssl_sock_param *ssock_param, ssock_param->timeout = listener->tls_setting.timeout; ssock_param->user_data = listener; ssock_param->verify_peer = PJ_FALSE; /* avoid SSL socket closing the socket - * due to verification error */ + * due to verification error */ if (ssock_param->send_buffer_size < PJSIP_MAX_PKT_LEN) - ssock_param->send_buffer_size = PJSIP_MAX_PKT_LEN; + ssock_param->send_buffer_size = PJSIP_MAX_PKT_LEN; if (ssock_param->read_buffer_size < PJSIP_MAX_PKT_LEN) - ssock_param->read_buffer_size = PJSIP_MAX_PKT_LEN; + ssock_param->read_buffer_size = PJSIP_MAX_PKT_LEN; ssock_param->ciphers_num = listener->tls_setting.ciphers_num; ssock_param->ciphers = listener->tls_setting.ciphers; ssock_param->curves_num = listener->tls_setting.curves_num; @@ -335,14 +334,14 @@ static void set_ssock_param(pj_ssl_sock_param *ssock_param, ssock_param->qos_type = listener->tls_setting.qos_type; ssock_param->qos_ignore_error = listener->tls_setting.qos_ignore_error; pj_memcpy(&ssock_param->qos_params, &listener->tls_setting.qos_params, - sizeof(ssock_param->qos_params)); + sizeof(ssock_param->qos_params)); ssock_param->sockopt_ignore_error = - listener->tls_setting.sockopt_ignore_error; + listener->tls_setting.sockopt_ignore_error; /* Copy the sockopt */ pj_memcpy(&ssock_param->sockopt_params, - &listener->tls_setting.sockopt_params, - sizeof(listener->tls_setting.sockopt_params)); + &listener->tls_setting.sockopt_params, + sizeof(listener->tls_setting.sockopt_params)); sip_ssl_method = listener->tls_setting.method; sip_ssl_proto = listener->tls_setting.proto; @@ -350,7 +349,7 @@ static void set_ssock_param(pj_ssl_sock_param *ssock_param, } static void update_bound_addr(struct tls_listener *listener, - const pj_sockaddr *local) + const pj_sockaddr *local) { pj_sockaddr *listener_addr = &listener->factory.local_addr; int af = pjsip_transport_type_get_af(listener->factory.type); @@ -359,69 +358,69 @@ static void update_bound_addr(struct tls_listener *listener, * factory.local_addr will be resolved. */ if (local) { - pj_sockaddr_cp(&listener->bound_addr, local); + pj_sockaddr_cp(&listener->bound_addr, local); } else { - pj_sockaddr_init(af, &listener->bound_addr, NULL, 0); + pj_sockaddr_init(af, &listener->bound_addr, NULL, 0); } pj_sockaddr_cp(listener_addr, &listener->bound_addr); } static pj_status_t update_factory_addr(struct tls_listener *listener, - const pjsip_host_port *addr_name) + const pjsip_host_port *addr_name) { pj_status_t status = PJ_SUCCESS; pj_sockaddr *listener_addr = &listener->factory.local_addr; if (addr_name && addr_name->host.slen) { - pj_sockaddr tmp; - int af = pjsip_transport_type_get_af(listener->factory.type); + pj_sockaddr tmp; + int af = pjsip_transport_type_get_af(listener->factory.type); - status = pj_sockaddr_init(af, &tmp, &addr_name->host, - (pj_uint16_t)addr_name->port); - if (status != PJ_SUCCESS || !pj_sockaddr_has_addr(&tmp) || - (af == pj_AF_INET() && tmp.ipv4.sin_addr.s_addr == PJ_INADDR_NONE)) - { - /* Invalid address */ - return PJ_EINVAL; - } + status = pj_sockaddr_init(af, &tmp, &addr_name->host, + (pj_uint16_t)addr_name->port); + if (status != PJ_SUCCESS || !pj_sockaddr_has_addr(&tmp) || + (af == pj_AF_INET() && tmp.ipv4.sin_addr.s_addr == PJ_INADDR_NONE)) + { + /* Invalid address */ + return PJ_EINVAL; + } - /* Copy the address */ - listener->factory.addr_name = *addr_name; - pj_strdup(listener->factory.pool, &listener->factory.addr_name.host, - &addr_name->host); - listener->factory.addr_name.port = addr_name->port; + /* Copy the address */ + listener->factory.addr_name = *addr_name; + pj_strdup(listener->factory.pool, &listener->factory.addr_name.host, + &addr_name->host); + listener->factory.addr_name.port = addr_name->port; } else { - /* No published address is given, use the bound address */ + /* No published address is given, use the bound address */ - /* If the address returns 0.0.0.0, use the default - * interface address as the transport's address. - */ - if (!pj_sockaddr_has_addr(listener_addr)) { - pj_sockaddr hostip; + /* If the address returns 0.0.0.0, use the default + * interface address as the transport's address. + */ + if (!pj_sockaddr_has_addr(listener_addr)) { + pj_sockaddr hostip; - status = pj_gethostip(listener->bound_addr.addr.sa_family, - &hostip); - if (status != PJ_SUCCESS) - return status; + status = pj_gethostip(listener->bound_addr.addr.sa_family, + &hostip); + if (status != PJ_SUCCESS) + return status; - pj_sockaddr_copy_addr(listener_addr, &hostip); - } + pj_sockaddr_copy_addr(listener_addr, &hostip); + } - /* Save the address name */ - sockaddr_to_host_port(listener->factory.pool, - &listener->factory.addr_name, listener_addr); + /* Save the address name */ + sockaddr_to_host_port(listener->factory.pool, + &listener->factory.addr_name, listener_addr); } /* If port is zero, get the bound port */ if (listener->factory.addr_name.port == 0) { - listener->factory.addr_name.port = pj_sockaddr_get_port(listener_addr); + listener->factory.addr_name.port = pj_sockaddr_get_port(listener_addr); } pj_ansi_snprintf(listener->factory.obj_name, - sizeof(listener->factory.obj_name), - "tlstp:%d", listener->factory.addr_name.port); + sizeof(listener->factory.obj_name), + "tlstp:%d", listener->factory.addr_name.port); return status; } @@ -434,29 +433,29 @@ static void update_transport_info(struct tls_listener *listener) pj_sockaddr *listener_addr = &listener->factory.local_addr; if (listener->factory.info == NULL) { - listener->factory.info = (char*)pj_pool_alloc(listener->factory.pool, - INFO_LEN); + listener->factory.info = (char*)pj_pool_alloc(listener->factory.pool, + INFO_LEN); } pj_sockaddr_print(listener_addr, local_addr, sizeof(local_addr), 3); pj_addr_str_print(&listener->factory.addr_name.host, - listener->factory.addr_name.port, pub_addr, - sizeof(pub_addr), 1); + listener->factory.addr_name.port, pub_addr, + sizeof(pub_addr), 1); len = pj_ansi_snprintf( - listener->factory.info, INFO_LEN, "tls %s [published as %s]", - local_addr, pub_addr); + listener->factory.info, INFO_LEN, "tls %s [published as %s]", + local_addr, pub_addr); PJ_CHECK_TRUNC_STR(len, listener->factory.info, INFO_LEN); if (listener->ssock) { - char addr[PJ_INET6_ADDRSTRLEN+10]; + char addr[PJ_INET6_ADDRSTRLEN+10]; - PJ_LOG(4, (listener->factory.obj_name, - "SIP TLS listener is ready for incoming connections at %s", - pj_addr_str_print(&listener->factory.addr_name.host, - listener->factory.addr_name.port, addr, - sizeof(addr), 1))); + PJ_LOG(4, (listener->factory.obj_name, + "SIP TLS listener is ready for incoming connections at %s", + pj_addr_str_print(&listener->factory.addr_name.host, + listener->factory.addr_name.port, addr, + sizeof(addr), 1))); } else { - PJ_LOG(4, (listener->factory.obj_name, "SIP TLS is ready " - "(client only)")); + PJ_LOG(4, (listener->factory.obj_name, "SIP TLS is ready " + "(client only)")); } } @@ -475,16 +474,16 @@ PJ_DEF(pj_status_t) pjsip_tls_transport_start(pjsip_endpoint *endpt, pj_sockaddr local; if (local_in) - pj_sockaddr_cp(&local, local_in); + pj_sockaddr_cp(&local, local_in); return pjsip_tls_transport_start2(endpt, opt, (local_in ? &local : NULL), - a_name, async_cnt, p_factory); + a_name, async_cnt, p_factory); } PJ_DEF(pj_status_t) pjsip_tls_transport_lis_start(pjsip_tpfactory *factory, - const pj_sockaddr *local, - const pjsip_host_port *a_name) + const pj_sockaddr *local, + const pjsip_host_port *a_name) { pj_status_t status = PJ_SUCCESS; pj_ssl_sock_param ssock_param, newsock_param; @@ -492,7 +491,7 @@ PJ_DEF(pj_status_t) pjsip_tls_transport_lis_start(pjsip_tpfactory *factory, pj_sockaddr *listener_addr = &listener->factory.local_addr; if (listener->ssock) - return PJ_SUCCESS; + return PJ_SUCCESS; set_ssock_param(&ssock_param, listener); update_bound_addr(listener, local); @@ -500,15 +499,15 @@ PJ_DEF(pj_status_t) pjsip_tls_transport_lis_start(pjsip_tpfactory *factory, /* Create SSL socket */ status = pj_ssl_sock_create(listener->factory.pool, &ssock_param, - &listener->ssock); + &listener->ssock); if (status != PJ_SUCCESS) - return status; + return status; if (listener->cert) { - status = pj_ssl_sock_set_certificate(listener->ssock, - listener->factory.pool, listener->cert); - if (status != PJ_SUCCESS) - return status; + status = pj_ssl_sock_set_certificate(listener->ssock, + listener->factory.pool, listener->cert); + if (status != PJ_SUCCESS) + return status; } /* Start accepting incoming connections. Note that some TLS/SSL @@ -519,22 +518,22 @@ PJ_DEF(pj_status_t) pjsip_tls_transport_lis_start(pjsip_tpfactory *factory, newsock_param.cb.on_data_read = &on_data_read; newsock_param.cb.on_data_sent = &on_data_sent; status = pj_ssl_sock_start_accept2(listener->ssock, listener->factory.pool, - (pj_sockaddr_t*)listener_addr, - pj_sockaddr_get_len((pj_sockaddr_t*)listener_addr), - &newsock_param); + (pj_sockaddr_t*)listener_addr, + pj_sockaddr_get_len((pj_sockaddr_t*)listener_addr), + &newsock_param); if (status == PJ_SUCCESS || status == PJ_EPENDING) { - pj_ssl_sock_info info; + pj_ssl_sock_info info; - /* Retrieve the bound address */ - status = pj_ssl_sock_get_info(listener->ssock, &info); - if (status == PJ_SUCCESS) - pj_sockaddr_cp(listener_addr, (pj_sockaddr_t*)&info.local_addr); + /* Retrieve the bound address */ + status = pj_ssl_sock_get_info(listener->ssock, &info); + if (status == PJ_SUCCESS) + pj_sockaddr_cp(listener_addr, (pj_sockaddr_t*)&info.local_addr); } status = update_factory_addr(listener, a_name); if (status != PJ_SUCCESS) - return status; + return status; update_transport_info(listener); @@ -543,11 +542,11 @@ PJ_DEF(pj_status_t) pjsip_tls_transport_lis_start(pjsip_tpfactory *factory, PJ_DEF(pj_status_t) pjsip_tls_transport_start2( pjsip_endpoint *endpt, - const pjsip_tls_setting *opt, - const pj_sockaddr *local, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_tpfactory **p_factory) + const pjsip_tls_setting *opt, + const pj_sockaddr *local, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_tpfactory **p_factory) { pj_pool_t *pool; pj_bool_t is_ipv6; @@ -560,77 +559,77 @@ PJ_DEF(pj_status_t) pjsip_tls_transport_start2( pjsip_endpoint *endpt, is_ipv6 = (local && local->addr.sa_family == pj_AF_INET6()); pool = pjsip_endpt_create_pool(endpt, "tlstp", POOL_LIS_INIT, - POOL_LIS_INC); + POOL_LIS_INC); PJ_ASSERT_RETURN(pool, PJ_ENOMEM); listener = PJ_POOL_ZALLOC_T(pool, struct tls_listener); listener->factory.pool = pool; if (is_ipv6) - listener->factory.type = PJSIP_TRANSPORT_TLS6; + listener->factory.type = PJSIP_TRANSPORT_TLS6; else - listener->factory.type = PJSIP_TRANSPORT_TLS; + listener->factory.type = PJSIP_TRANSPORT_TLS; listener->factory.type_name = (char*) - pjsip_transport_get_type_name(listener->factory.type); + pjsip_transport_get_type_name(listener->factory.type); listener->factory.flag = - pjsip_transport_get_flag_from_type(listener->factory.type); + pjsip_transport_get_flag_from_type(listener->factory.type); listener->endpt = endpt; pj_ansi_strcpy(listener->factory.obj_name, "tlstp"); if (is_ipv6) - pj_ansi_strcat(listener->factory.obj_name, "6"); + pj_ansi_strcat(listener->factory.obj_name, "6"); if (opt) - pjsip_tls_setting_copy(pool, &listener->tls_setting, opt); + pjsip_tls_setting_copy(pool, &listener->tls_setting, opt); else - pjsip_tls_setting_default(&listener->tls_setting); + pjsip_tls_setting_default(&listener->tls_setting); status = pj_lock_create_recursive_mutex(pool, listener->factory.obj_name, - &listener->factory.lock); + &listener->factory.lock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; if (async_cnt > MAX_ASYNC_CNT) - async_cnt = MAX_ASYNC_CNT; + async_cnt = MAX_ASYNC_CNT; listener->async_cnt = async_cnt; /* Create group lock */ status = pj_grp_lock_create(pool, NULL, &listener->grp_lock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Setup group lock handler */ pj_grp_lock_add_ref(listener->grp_lock); pj_grp_lock_add_handler(listener->grp_lock, pool, listener, - &lis_on_destroy); + &lis_on_destroy); /* Check if certificate/CA list for SSL socket is set */ if (listener->tls_setting.cert_file.slen || - listener->tls_setting.ca_list_file.slen || - listener->tls_setting.ca_list_path.slen || - listener->tls_setting.privkey_file.slen) + listener->tls_setting.ca_list_file.slen || + listener->tls_setting.ca_list_path.slen || + listener->tls_setting.privkey_file.slen) { - status = pj_ssl_cert_load_from_files2(pool, - &listener->tls_setting.ca_list_file, - &listener->tls_setting.ca_list_path, - &listener->tls_setting.cert_file, - &listener->tls_setting.privkey_file, - &listener->tls_setting.password, - &listener->cert); - if (status != PJ_SUCCESS) - goto on_error; + status = pj_ssl_cert_load_from_files2(pool, + &listener->tls_setting.ca_list_file, + &listener->tls_setting.ca_list_path, + &listener->tls_setting.cert_file, + &listener->tls_setting.privkey_file, + &listener->tls_setting.password, + &listener->cert); + if (status != PJ_SUCCESS) + goto on_error; } else if (listener->tls_setting.ca_buf.slen || - listener->tls_setting.cert_buf.slen|| - listener->tls_setting.privkey_buf.slen) + listener->tls_setting.cert_buf.slen|| + listener->tls_setting.privkey_buf.slen) { - status = pj_ssl_cert_load_from_buffer(pool, - &listener->tls_setting.ca_buf, - &listener->tls_setting.cert_buf, - &listener->tls_setting.privkey_buf, - &listener->tls_setting.password, - &listener->cert); - if (status != PJ_SUCCESS) - goto on_error; + status = pj_ssl_cert_load_from_buffer(pool, + &listener->tls_setting.ca_buf, + &listener->tls_setting.cert_buf, + &listener->tls_setting.privkey_buf, + &listener->tls_setting.password, + &listener->cert); + if (status != PJ_SUCCESS) + goto on_error; } /* Register to transport manager */ @@ -644,7 +643,7 @@ PJ_DEF(pj_status_t) pjsip_tls_transport_start2( pjsip_endpoint *endpt, /* Start listener. */ status = pjsip_tls_transport_lis_start(&listener->factory, local, a_name); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #else update_bound_addr(listener, local); /* If published host/IP is specified, then use that address as the @@ -652,7 +651,7 @@ PJ_DEF(pj_status_t) pjsip_tls_transport_start2( pjsip_endpoint *endpt, */ status = update_factory_addr(listener, a_name); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Set transport info. */ update_transport_info(listener); @@ -660,10 +659,10 @@ PJ_DEF(pj_status_t) pjsip_tls_transport_start2( pjsip_endpoint *endpt, listener->is_registered = PJ_TRUE; status = pjsip_tpmgr_register_tpfactory(listener->tpmgr, - &listener->factory); + &listener->factory); if (status != PJ_SUCCESS) { - listener->is_registered = PJ_FALSE; - goto on_error; + listener->is_registered = PJ_FALSE; + goto on_error; } /* Return the pointer to user */ @@ -683,18 +682,18 @@ static void lis_on_destroy(void *arg) struct tls_listener *listener = (struct tls_listener*)arg; if (listener->cert) { - pj_ssl_cert_wipe_keys(listener->cert); - listener->cert = NULL; + pj_ssl_cert_wipe_keys(listener->cert); + listener->cert = NULL; } if (listener->factory.lock) { - pj_lock_destroy(listener->factory.lock); - listener->factory.lock = NULL; + pj_lock_destroy(listener->factory.lock); + listener->factory.lock = NULL; } if (listener->factory.pool) { - PJ_LOG(4,(listener->factory.obj_name, "SIP TLS transport destroyed")); - pj_pool_secure_release(&listener->factory.pool); + PJ_LOG(4,(listener->factory.obj_name, "SIP TLS transport destroyed")); + pj_pool_secure_release(&listener->factory.pool); } } @@ -702,13 +701,13 @@ static void lis_on_destroy(void *arg) static void lis_close(struct tls_listener *listener) { if (listener->is_registered) { - pjsip_tpmgr_unregister_tpfactory(listener->tpmgr, &listener->factory); - listener->is_registered = PJ_FALSE; + pjsip_tpmgr_unregister_tpfactory(listener->tpmgr, &listener->factory); + listener->is_registered = PJ_FALSE; } if (listener->ssock) { - pj_ssl_sock_close(listener->ssock); - listener->ssock = NULL; + pj_ssl_sock_close(listener->ssock); + listener->ssock = NULL; } } @@ -721,12 +720,12 @@ static pj_status_t lis_destroy(pjsip_tpfactory *factory) lis_close(listener); if (listener->grp_lock) { - pj_grp_lock_t *grp_lock = listener->grp_lock; - listener->grp_lock = NULL; - pj_grp_lock_dec_ref(grp_lock); - /* Listener may have been deleted at this point */ + pj_grp_lock_t *grp_lock = listener->grp_lock; + listener->grp_lock = NULL; + pj_grp_lock_dec_ref(grp_lock); + /* Listener may have been deleted at this point */ } else { - lis_on_destroy(listener); + lis_on_destroy(listener); } return PJ_SUCCESS; @@ -734,8 +733,8 @@ static pj_status_t lis_destroy(pjsip_tpfactory *factory) PJ_DEF(pj_status_t) pjsip_tls_transport_restart(pjsip_tpfactory *factory, - const pj_sockaddr *local, - const pjsip_host_port *a_name) + const pj_sockaddr *local, + const pjsip_host_port *a_name) { pj_status_t status = PJ_SUCCESS; struct tls_listener *listener = (struct tls_listener *)factory; @@ -743,22 +742,22 @@ PJ_DEF(pj_status_t) pjsip_tls_transport_restart(pjsip_tpfactory *factory, lis_close(listener); status = pjsip_tls_transport_lis_start(factory, local, a_name); - if (status != PJ_SUCCESS) { - tls_perror(listener->factory.obj_name, - "Unable to start listener after closing it", status, NULL); + if (status != PJ_SUCCESS) { + tls_perror(listener->factory.obj_name, + "Unable to start listener after closing it", status, NULL); - return status; + return status; } status = pjsip_tpmgr_register_tpfactory(listener->tpmgr, - &listener->factory); + &listener->factory); if (status != PJ_SUCCESS) { - tls_perror(listener->factory.obj_name, - "Unable to register the transport listener", status, NULL); + tls_perror(listener->factory.obj_name, + "Unable to register the transport listener", status, NULL); - listener->is_registered = PJ_FALSE; + listener->is_registered = PJ_FALSE; } else { - listener->is_registered = PJ_TRUE; + listener->is_registered = PJ_TRUE; } return status; @@ -775,11 +774,11 @@ PJ_DEF(pj_status_t) pjsip_tls_transport_restart(pjsip_tpfactory *factory, */ /* Called by transport manager to send message */ static pj_status_t tls_send_msg(pjsip_transport *transport, - pjsip_tx_data *tdata, - const pj_sockaddr_t *rem_addr, - int addr_len, - void *token, - pjsip_transport_callback callback); + pjsip_tx_data *tdata, + const pj_sockaddr_t *rem_addr, + int addr_len, + void *token, + pjsip_transport_callback callback); /* Called by transport manager to shutdown */ static pj_status_t tls_shutdown(pjsip_transport *transport); @@ -789,11 +788,11 @@ static pj_status_t tls_destroy_transport(pjsip_transport *transport); /* Utility to destroy transport */ static pj_status_t tls_destroy(pjsip_transport *transport, - pj_status_t reason); + pj_status_t reason); /* Callback when connect completes */ static pj_bool_t on_connect_complete(pj_ssl_sock_t *ssock, - pj_status_t status); + pj_status_t status); /* TLS keep-alive timer callback */ static void tls_keep_alive_timer(pj_timer_heap_t *th, pj_timer_entry *e); @@ -803,14 +802,14 @@ static void tls_keep_alive_timer(pj_timer_heap_t *th, pj_timer_entry *e); * pending connect() complete. */ static pj_status_t tls_create( struct tls_listener *listener, - pj_pool_t *pool, - pj_ssl_sock_t *ssock, - pj_bool_t is_server, - const pj_sockaddr *local, - const pj_sockaddr *remote, - const pj_str_t *remote_name, - pj_grp_lock_t *glock, - struct tls_transport **p_tls) + pj_pool_t *pool, + pj_ssl_sock_t *ssock, + pj_bool_t is_server, + const pj_sockaddr *local, + const pj_sockaddr *remote, + const pj_str_t *remote_name, + pj_grp_lock_t *glock, + struct tls_transport **p_tls) { struct tls_transport *tls; const pj_str_t ka_pkt = PJSIP_TLS_KEEP_ALIVE_DATA; @@ -822,9 +821,9 @@ static pj_status_t tls_create( struct tls_listener *listener, if (pool == NULL) { - pool = pjsip_endpt_create_pool(listener->endpt, "tls", - POOL_TP_INIT, POOL_TP_INC); - PJ_ASSERT_RETURN(pool != NULL, PJ_ENOMEM); + pool = pjsip_endpt_create_pool(listener->endpt, "tls", + POOL_TP_INIT, POOL_TP_INC); + PJ_ASSERT_RETURN(pool != NULL, PJ_ENOMEM); } /* @@ -837,27 +836,27 @@ static pj_status_t tls_create( struct tls_listener *listener, tls->base.pool = pool; pj_ansi_snprintf(tls->base.obj_name, PJ_MAX_OBJ_NAME, - (is_server ? "tlss%p" :"tlsc%p"), tls); + (is_server ? "tlss%p" :"tlsc%p"), tls); status = pj_atomic_create(pool, 0, &tls->base.ref_cnt); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } status = pj_lock_create_recursive_mutex(pool, "tls", &tls->base.lock); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } if (remote_name) - pj_strdup(pool, &tls->remote_name, remote_name); + pj_strdup(pool, &tls->remote_name, remote_name); tls->base.key.type = listener->factory.type; pj_sockaddr_cp(&tls->base.key.rem_addr, remote); tls->base.type_name = (char*)pjsip_transport_get_type_name( - (pjsip_transport_type_e)tls->base.key.type); + (pjsip_transport_type_e)tls->base.key.type); tls->base.flag = pjsip_transport_get_flag_from_type( - (pjsip_transport_type_e)tls->base.key.type); + (pjsip_transport_type_e)tls->base.key.type); tls->base.info = (char*) pj_pool_alloc(pool, 64); pj_ansi_snprintf(tls->base.info, 64, "%s to %s", @@ -874,15 +873,15 @@ static pj_status_t tls_create( struct tls_listener *listener, pj_sockaddr_cp(&tls->base.local_addr, &listener->factory.local_addr); } else { - pj_sockaddr_cp(&tls->base.local_addr, local); + pj_sockaddr_cp(&tls->base.local_addr, local); } sockaddr_to_host_port(pool, &tls->base.local_name, &tls->base.local_addr); if (tls->remote_name.slen) { - tls->base.remote_name.host = tls->remote_name; - tls->base.remote_name.port = pj_sockaddr_get_port(remote); + tls->base.remote_name.host = tls->remote_name; + tls->base.remote_name.port = pj_sockaddr_get_port(remote); } else { - sockaddr_to_host_port(pool, &tls->base.remote_name, remote); + sockaddr_to_host_port(pool, &tls->base.remote_name, remote); } tls->base.endpt = listener->endpt; @@ -903,7 +902,7 @@ static pj_status_t tls_create( struct tls_listener *listener, /* Register transport to transport manager */ status = pjsip_transport_register(listener->tpmgr, &tls->base); if (status != PJ_SUCCESS) { - goto on_error; + goto on_error; } tls->is_registered = PJ_TRUE; @@ -918,15 +917,15 @@ static pj_status_t tls_create( struct tls_listener *listener, *p_tls = tls; PJ_LOG(4,(tls->base.obj_name, "TLS %s transport created", - (tls->is_server ? "server" : "client"))); + (tls->is_server ? "server" : "client"))); return PJ_SUCCESS; on_error: if (tls->grp_lock && pj_grp_lock_get_ref(tls->grp_lock)) - tls_destroy(&tls->base, status); + tls_destroy(&tls->base, status); else - tls_on_destroy(tls); + tls_on_destroy(tls); return status; } @@ -940,37 +939,37 @@ static void tls_flush_pending_tx(struct tls_transport *tls) pj_gettickcount(&now); pj_lock_acquire(tls->base.lock); while (!pj_list_empty(&tls->delayed_list)) { - struct delayed_tdata *pending_tx; - pjsip_tx_data *tdata; - pj_ioqueue_op_key_t *op_key; - pj_ssize_t size; - pj_status_t status; + struct delayed_tdata *pending_tx; + pjsip_tx_data *tdata; + pj_ioqueue_op_key_t *op_key; + pj_ssize_t size; + pj_status_t status; - pending_tx = tls->delayed_list.next; - pj_list_erase(pending_tx); + pending_tx = tls->delayed_list.next; + pj_list_erase(pending_tx); - tdata = pending_tx->tdata_op_key->tdata; - op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; + tdata = pending_tx->tdata_op_key->tdata; + op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; if (pending_tx->timeout.sec > 0 && PJ_TIME_VAL_GT(now, pending_tx->timeout)) { pj_lock_release(tls->base.lock); - on_data_sent(tls->ssock, op_key, -PJ_ETIMEDOUT); + on_data_sent(tls->ssock, op_key, -PJ_ETIMEDOUT); pj_lock_acquire(tls->base.lock); continue; } - /* send! */ - size = tdata->buf.cur - tdata->buf.start; - status = pj_ssl_sock_send(tls->ssock, op_key, tdata->buf.start, - &size, 0); + /* send! */ + size = tdata->buf.cur - tdata->buf.start; + status = pj_ssl_sock_send(tls->ssock, op_key, tdata->buf.start, + &size, 0); - if (status != PJ_EPENDING) { + if (status != PJ_EPENDING) { pj_lock_release(tls->base.lock); - on_data_sent(tls->ssock, op_key, size); + on_data_sent(tls->ssock, op_key, size); pj_lock_acquire(tls->base.lock); - } + } } pj_lock_release(tls->base.lock); } @@ -996,55 +995,55 @@ static void tls_on_destroy(void *arg) struct tls_transport *tls = (struct tls_transport*)arg; if (tls->rdata.tp_info.pool) { - pj_pool_secure_release(&tls->rdata.tp_info.pool); + pj_pool_secure_release(&tls->rdata.tp_info.pool); } if (tls->base.lock) { - pj_lock_destroy(tls->base.lock); - tls->base.lock = NULL; + pj_lock_destroy(tls->base.lock); + tls->base.lock = NULL; } if (tls->base.ref_cnt) { - pj_atomic_destroy(tls->base.ref_cnt); - tls->base.ref_cnt = NULL; + pj_atomic_destroy(tls->base.ref_cnt); + tls->base.ref_cnt = NULL; } if (tls->base.pool) { - if (tls->close_reason != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; + if (tls->close_reason != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(tls->close_reason, errmsg, sizeof(errmsg)); - PJ_LOG(4,(tls->base.obj_name, - "TLS transport destroyed with reason %d: %s", - tls->close_reason, errmsg)); + pj_strerror(tls->close_reason, errmsg, sizeof(errmsg)); + PJ_LOG(4,(tls->base.obj_name, + "TLS transport destroyed with reason %d: %s", + tls->close_reason, errmsg)); - } else { + } else { - PJ_LOG(4,(tls->base.obj_name, - "TLS transport destroyed normally")); + PJ_LOG(4,(tls->base.obj_name, + "TLS transport destroyed normally")); - } - pj_pool_secure_release(&tls->base.pool); + } + pj_pool_secure_release(&tls->base.pool); } } /* Destroy TLS transport */ static pj_status_t tls_destroy(pjsip_transport *transport, - pj_status_t reason) + pj_status_t reason) { struct tls_transport *tls = (struct tls_transport*)transport; if (tls->close_reason == 0) - tls->close_reason = reason; + tls->close_reason = reason; if (tls->is_registered) { - tls->is_registered = PJ_FALSE; - pjsip_transport_destroy(transport); + tls->is_registered = PJ_FALSE; + pjsip_transport_destroy(transport); - /* pjsip_transport_destroy will recursively call this function - * again. - */ - return PJ_SUCCESS; + /* pjsip_transport_destroy will recursively call this function + * again. + */ + return PJ_SUCCESS; } /* Mark transport as closing */ @@ -1052,33 +1051,33 @@ static pj_status_t tls_destroy(pjsip_transport *transport, /* Stop keep-alive timer. */ if (tls->ka_timer.id) { - pjsip_endpt_cancel_timer(tls->base.endpt, &tls->ka_timer); - tls->ka_timer.id = PJ_FALSE; + pjsip_endpt_cancel_timer(tls->base.endpt, &tls->ka_timer); + tls->ka_timer.id = PJ_FALSE; } /* Cancel all delayed transmits */ while (!pj_list_empty(&tls->delayed_list)) { - struct delayed_tdata *pending_tx; - pj_ioqueue_op_key_t *op_key; + struct delayed_tdata *pending_tx; + pj_ioqueue_op_key_t *op_key; - pending_tx = tls->delayed_list.next; - pj_list_erase(pending_tx); + pending_tx = tls->delayed_list.next; + pj_list_erase(pending_tx); - op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; + op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; - on_data_sent(tls->ssock, op_key, -reason); + on_data_sent(tls->ssock, op_key, -reason); } if (tls->ssock) { - pj_ssl_sock_close(tls->ssock); - tls->ssock = NULL; + pj_ssl_sock_close(tls->ssock); + tls->ssock = NULL; } if (tls->grp_lock) { - pj_grp_lock_t *grp_lock = tls->grp_lock; - tls->grp_lock = NULL; - pj_grp_lock_dec_ref(grp_lock); - /* Transport may have been deleted at this point */ + pj_grp_lock_t *grp_lock = tls->grp_lock; + tls->grp_lock = NULL; + pj_grp_lock_dec_ref(grp_lock); + /* Transport may have been deleted at this point */ } return PJ_SUCCESS; @@ -1100,13 +1099,13 @@ static pj_status_t tls_start_read(struct tls_transport *tls) /* Init rdata */ pool = pjsip_endpt_create_pool(tls->base.endpt, - "rtd%p", - PJSIP_POOL_RDATA_LEN, - PJSIP_POOL_RDATA_INC); + "rtd%p", + PJSIP_POOL_RDATA_LEN, + PJSIP_POOL_RDATA_INC); if (!pool) { - tls_perror(tls->base.obj_name, "Unable to create pool", PJ_ENOMEM, - NULL); - return PJ_ENOMEM; + tls_perror(tls->base.obj_name, "Unable to create pool", PJ_ENOMEM, + NULL); + return PJ_ENOMEM; } tls->rdata.tp_info.pool = pool; @@ -1115,7 +1114,7 @@ static pj_status_t tls_start_read(struct tls_transport *tls) tls->rdata.tp_info.tp_data = tls; tls->rdata.tp_info.op_key.rdata = &tls->rdata; pj_ioqueue_op_key_init(&tls->rdata.tp_info.op_key.op_key, - sizeof(pj_ioqueue_op_key_t)); + sizeof(pj_ioqueue_op_key_t)); tls->rdata.pkt_info.src_addr = tls->base.key.rem_addr; tls->rdata.pkt_info.src_addr_len = sizeof(tls->rdata.pkt_info.src_addr); @@ -1127,11 +1126,11 @@ static pj_status_t tls_start_read(struct tls_transport *tls) size = sizeof(tls->rdata.pkt_info.packet); readbuf[0] = tls->rdata.pkt_info.packet; status = pj_ssl_sock_start_read2(tls->ssock, tls->base.pool, size, - readbuf, 0); + readbuf, 0); if (status != PJ_SUCCESS && status != PJ_EPENDING) { - PJ_PERROR(4, (tls->base.obj_name, status, - "pj_ssl_sock_start_read() error")); - return status; + PJ_PERROR(4, (tls->base.obj_name, status, + "pj_ssl_sock_start_read() error")); + return status; } return PJ_SUCCESS; @@ -1142,12 +1141,12 @@ static pj_status_t tls_start_read(struct tls_transport *tls) * to create outgoing transport to the specified destination. */ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, - pjsip_tpmgr *mgr, - pjsip_endpoint *endpt, - const pj_sockaddr *rem_addr, - int addr_len, - pjsip_tx_data *tdata, - pjsip_transport **p_transport) + pjsip_tpmgr *mgr, + pjsip_endpoint *endpt, + const pj_sockaddr *rem_addr, + int addr_len, + pjsip_tx_data *tdata, + pjsip_transport **p_transport) { struct tls_listener *listener; struct tls_transport *tls; @@ -1163,36 +1162,36 @@ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, /* Sanity checks */ PJ_ASSERT_RETURN(factory && mgr && endpt && rem_addr && - addr_len && p_transport, PJ_EINVAL); + addr_len && p_transport, PJ_EINVAL); /* Check that address is a sockaddr_in or sockaddr_in6*/ PJ_ASSERT_RETURN((rem_addr->addr.sa_family == pj_AF_INET() && - addr_len == sizeof(pj_sockaddr_in)) || - (rem_addr->addr.sa_family == pj_AF_INET6() && - addr_len == sizeof(pj_sockaddr_in6)), PJ_EINVAL); + addr_len == sizeof(pj_sockaddr_in)) || + (rem_addr->addr.sa_family == pj_AF_INET6() && + addr_len == sizeof(pj_sockaddr_in6)), PJ_EINVAL); listener = (struct tls_listener*)factory; pool = pjsip_endpt_create_pool(listener->endpt, "tls", - POOL_TP_INIT, POOL_TP_INC); + POOL_TP_INIT, POOL_TP_INC); PJ_ASSERT_RETURN(pool != NULL, PJ_ENOMEM); /* Get remote host name from tdata */ if (tdata) - remote_name = tdata->dest_info.name; + remote_name = tdata->dest_info.name; else - pj_bzero(&remote_name, sizeof(remote_name)); + pj_bzero(&remote_name, sizeof(remote_name)); /* Build SSL socket param */ pj_ssl_sock_param_default(&ssock_param); ssock_param.sock_af = (factory->type & PJSIP_TRANSPORT_IPV6) ? - pj_AF_INET6() : pj_AF_INET(); + pj_AF_INET6() : pj_AF_INET(); ssock_param.cb.on_connect_complete = &on_connect_complete; ssock_param.cb.on_data_read = &on_data_read; ssock_param.cb.on_data_sent = &on_data_sent; if (listener->tls_setting.on_verify_cb) - ssock_param.cb.on_verify_cb = &on_verify_cb; + ssock_param.cb.on_verify_cb = &on_verify_cb; ssock_param.async_cnt = 1; ssock_param.ioqueue = pjsip_endpt_get_ioqueue(listener->endpt); ssock_param.timer_heap = pjsip_endpt_get_timer_heap(listener->endpt); @@ -1200,11 +1199,11 @@ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, ssock_param.timeout = listener->tls_setting.timeout; ssock_param.user_data = NULL; /* pending, must be set later */ ssock_param.verify_peer = PJ_FALSE; /* avoid SSL socket closing the socket - * due to verification error */ + * due to verification error */ if (ssock_param.send_buffer_size < PJSIP_MAX_PKT_LEN) - ssock_param.send_buffer_size = PJSIP_MAX_PKT_LEN; + ssock_param.send_buffer_size = PJSIP_MAX_PKT_LEN; if (ssock_param.read_buffer_size < PJSIP_MAX_PKT_LEN) - ssock_param.read_buffer_size = PJSIP_MAX_PKT_LEN; + ssock_param.read_buffer_size = PJSIP_MAX_PKT_LEN; ssock_param.ciphers_num = listener->tls_setting.ciphers_num; ssock_param.ciphers = listener->tls_setting.ciphers; ssock_param.curves_num = listener->tls_setting.curves_num; @@ -1215,14 +1214,14 @@ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, ssock_param.qos_type = listener->tls_setting.qos_type; ssock_param.qos_ignore_error = listener->tls_setting.qos_ignore_error; pj_memcpy(&ssock_param.qos_params, &listener->tls_setting.qos_params, - sizeof(ssock_param.qos_params)); + sizeof(ssock_param.qos_params)); ssock_param.sockopt_ignore_error = - listener->tls_setting.sockopt_ignore_error; + listener->tls_setting.sockopt_ignore_error; /* Copy the sockopt */ pj_memcpy(&ssock_param.sockopt_params, - &listener->tls_setting.sockopt_params, - sizeof(listener->tls_setting.sockopt_params)); + &listener->tls_setting.sockopt_params, + sizeof(listener->tls_setting.sockopt_params)); sip_ssl_method = listener->tls_setting.method; sip_ssl_proto = listener->tls_setting.proto; @@ -1231,34 +1230,34 @@ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, /* Create group lock */ status = pj_grp_lock_create(pool, NULL, &glock); if (status != PJ_SUCCESS) - return status; + return status; ssock_param.grp_lock = glock; status = pj_ssl_sock_create(pool, &ssock_param, &ssock); if (status != PJ_SUCCESS) { - pj_grp_lock_destroy(glock); - return status; + pj_grp_lock_destroy(glock); + return status; } /* Apply SSL certificate */ if (listener->cert) { - status = pj_ssl_sock_set_certificate(ssock, pool, listener->cert); - if (status != PJ_SUCCESS) { - pj_grp_lock_destroy(glock); - return status; - } + status = pj_ssl_sock_set_certificate(ssock, pool, listener->cert); + if (status != PJ_SUCCESS) { + pj_grp_lock_destroy(glock); + return status; + } } /* Initially set bind address to listener's bind address */ pj_sockaddr_init(listener->bound_addr.addr.sa_family, - &local_addr, NULL, 0); + &local_addr, NULL, 0); pj_sockaddr_copy_addr(&local_addr, &listener->bound_addr); /* Create the transport descriptor */ status = tls_create(listener, pool, ssock, PJ_FALSE, &local_addr, - rem_addr, &remote_name, glock, &tls); + rem_addr, &remote_name, glock, &tls); if (status != PJ_SUCCESS) - return status; + return status; /* Set the "pending" SSL socket user data */ pj_ssl_sock_set_user_data(tls->ssock, tls); @@ -1266,56 +1265,56 @@ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, /* Start asynchronous connect() operation */ tls->has_pending_connect = PJ_TRUE; status = pj_ssl_sock_start_connect(tls->ssock, tls->base.pool, - (pj_sockaddr_t*)&local_addr, - (pj_sockaddr_t*)rem_addr, - addr_len); + (pj_sockaddr_t*)&local_addr, + (pj_sockaddr_t*)rem_addr, + addr_len); if (status == PJ_SUCCESS) { - on_connect_complete(tls->ssock, PJ_SUCCESS); + on_connect_complete(tls->ssock, PJ_SUCCESS); } else if (status != PJ_EPENDING) { - tls_destroy(&tls->base, status); - return status; + tls_destroy(&tls->base, status); + return status; } if (tls->has_pending_connect) { - pj_ssl_sock_info info; - char local_addr_buf[PJ_INET6_ADDRSTRLEN+10]; - char remote_addr_buf[PJ_INET6_ADDRSTRLEN+10]; - - /* Update local address, just in case local address currently set is - * different now that asynchronous connect() is started. - */ - - /* Retrieve the bound address */ - status = pj_ssl_sock_get_info(tls->ssock, &info); - if (status == PJ_SUCCESS) { - pj_uint16_t new_port; - - new_port = pj_sockaddr_get_port((pj_sockaddr_t*)&info.local_addr); - - if (pj_sockaddr_has_addr((pj_sockaddr_t*)&info.local_addr)) { - /* Update sockaddr */ - pj_sockaddr_cp((pj_sockaddr_t*)&tls->base.local_addr, - (pj_sockaddr_t*)&info.local_addr); - } else if (new_port && new_port != pj_sockaddr_get_port( - (pj_sockaddr_t*)&tls->base.local_addr)) - { - /* Update port only */ - pj_sockaddr_set_port(&tls->base.local_addr, - new_port); - } - - sockaddr_to_host_port(tls->base.pool, &tls->base.local_name, - &tls->base.local_addr); - } - - PJ_LOG(4,(tls->base.obj_name, - "TLS transport %s is connecting to %s...", - pj_addr_str_print(&tls->base.local_name.host, - tls->base.local_name.port, - local_addr_buf, sizeof(local_addr_buf), 1), - pj_addr_str_print(&tls->base.remote_name.host, - tls->base.remote_name.port, - remote_addr_buf, sizeof(remote_addr_buf), 1))); + pj_ssl_sock_info info; + char local_addr_buf[PJ_INET6_ADDRSTRLEN+10]; + char remote_addr_buf[PJ_INET6_ADDRSTRLEN+10]; + + /* Update local address, just in case local address currently set is + * different now that asynchronous connect() is started. + */ + + /* Retrieve the bound address */ + status = pj_ssl_sock_get_info(tls->ssock, &info); + if (status == PJ_SUCCESS) { + pj_uint16_t new_port; + + new_port = pj_sockaddr_get_port((pj_sockaddr_t*)&info.local_addr); + + if (pj_sockaddr_has_addr((pj_sockaddr_t*)&info.local_addr)) { + /* Update sockaddr */ + pj_sockaddr_cp((pj_sockaddr_t*)&tls->base.local_addr, + (pj_sockaddr_t*)&info.local_addr); + } else if (new_port && new_port != pj_sockaddr_get_port( + (pj_sockaddr_t*)&tls->base.local_addr)) + { + /* Update port only */ + pj_sockaddr_set_port(&tls->base.local_addr, + new_port); + } + + sockaddr_to_host_port(tls->base.pool, &tls->base.local_name, + &tls->base.local_addr); + } + + PJ_LOG(4,(tls->base.obj_name, + "TLS transport %s is connecting to %s...", + pj_addr_str_print(&tls->base.local_name.host, + tls->base.local_name.port, + local_addr_buf, sizeof(local_addr_buf), 1), + pj_addr_str_print(&tls->base.remote_name.host, + tls->base.remote_name.port, + remote_addr_buf, sizeof(remote_addr_buf), 1))); } /* Done */ @@ -1326,10 +1325,10 @@ static pj_status_t lis_create_transport(pjsip_tpfactory *factory, static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock, - pj_ssl_sock_t *new_ssock, - const pj_sockaddr_t *src_addr, - int src_addr_len, - pj_status_t accept_status) + pj_ssl_sock_t *new_ssock, + const pj_sockaddr_t *src_addr, + int src_addr_len, + pj_status_t accept_status) { struct tls_listener *listener; struct tls_transport *tls; @@ -1345,85 +1344,85 @@ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock, listener = (struct tls_listener*) pj_ssl_sock_get_user_data(ssock); if (!listener) { - /* Listener already destroyed, e.g: after TCP accept but before SSL - * handshake is completed. - */ - if (new_ssock && accept_status == PJ_SUCCESS) { - /* Close the SSL socket if the accept op is successful */ - PJ_LOG(4,(THIS_FILE, - "Incoming TLS connection from %s (sock=%d) is discarded " - "because listener is already destroyed", - pj_sockaddr_print(src_addr, addr, sizeof(addr), 3), - new_ssock)); - - pj_ssl_sock_close(new_ssock); - } + /* Listener already destroyed, e.g: after TCP accept but before SSL + * handshake is completed. + */ + if (new_ssock && accept_status == PJ_SUCCESS) { + /* Close the SSL socket if the accept op is successful */ + PJ_LOG(4,(THIS_FILE, + "Incoming TLS connection from %s (sock=%d) is discarded " + "because listener is already destroyed", + pj_sockaddr_print(src_addr, addr, sizeof(addr), 3), + new_ssock)); + + pj_ssl_sock_close(new_ssock); + } - return PJ_FALSE; + return PJ_FALSE; } if (accept_status != PJ_SUCCESS) { - if (listener->tls_setting.on_accept_fail_cb) { - pjsip_tls_on_accept_fail_param param; - pj_ssl_sock_info ssi; - - pj_bzero(¶m, sizeof(param)); - param.status = accept_status; - param.local_addr = &listener->factory.local_addr; - param.remote_addr = src_addr; - if (new_ssock && - pj_ssl_sock_get_info(new_ssock, &ssi) == PJ_SUCCESS) - { - param.last_native_err = ssi.last_native_err; - } + if (listener->tls_setting.on_accept_fail_cb) { + pjsip_tls_on_accept_fail_param param; + pj_ssl_sock_info ssi; + + pj_bzero(¶m, sizeof(param)); + param.status = accept_status; + param.local_addr = &listener->factory.local_addr; + param.remote_addr = src_addr; + if (new_ssock && + pj_ssl_sock_get_info(new_ssock, &ssi) == PJ_SUCCESS) + { + param.last_native_err = ssi.last_native_err; + } - (*listener->tls_setting.on_accept_fail_cb) (¶m); - } + (*listener->tls_setting.on_accept_fail_cb) (¶m); + } - return PJ_FALSE; + return PJ_FALSE; } PJ_ASSERT_RETURN(new_ssock, PJ_TRUE); if (!listener->is_registered) { - pj_ssl_sock_close(new_ssock); - - if (listener->tls_setting.on_accept_fail_cb) { - pjsip_tls_on_accept_fail_param param; - pj_bzero(¶m, sizeof(param)); - param.status = PJSIP_TLS_EACCEPT; - param.local_addr = &listener->factory.local_addr; - param.remote_addr = src_addr; - (*listener->tls_setting.on_accept_fail_cb) (¶m); - } - return PJ_FALSE; - } + pj_ssl_sock_close(new_ssock); + + if (listener->tls_setting.on_accept_fail_cb) { + pjsip_tls_on_accept_fail_param param; + pj_bzero(¶m, sizeof(param)); + param.status = PJSIP_TLS_EACCEPT; + param.local_addr = &listener->factory.local_addr; + param.remote_addr = src_addr; + (*listener->tls_setting.on_accept_fail_cb) (¶m); + } + return PJ_FALSE; + } PJ_LOG(4,(listener->factory.obj_name, - "TLS listener %s: got incoming TLS connection " - "from %s, sock=%d", - pj_addr_str_print(&listener->factory.addr_name.host, - listener->factory.addr_name.port, addr_buf, - sizeof(addr_buf), 1), - pj_sockaddr_print(src_addr, addr, sizeof(addr), 3), - new_ssock)); + "TLS listener %s: got incoming TLS connection " + "from %s, sock=%d", + pj_addr_str_print(&listener->factory.addr_name.host, + listener->factory.addr_name.port, addr_buf, + sizeof(addr_buf), 1), + pj_sockaddr_print(src_addr, addr, sizeof(addr), 3), + new_ssock)); /* Retrieve SSL socket info, close the socket if this is failed * as the SSL socket info availability is rather critical here. */ status = pj_ssl_sock_get_info(new_ssock, &ssl_info); if (status != PJ_SUCCESS) { - pj_ssl_sock_close(new_ssock); - - if (listener->tls_setting.on_accept_fail_cb) { - pjsip_tls_on_accept_fail_param param; - pj_bzero(¶m, sizeof(param)); - param.status = status; - param.local_addr = &listener->factory.local_addr; - param.remote_addr = src_addr; - (*listener->tls_setting.on_accept_fail_cb) (¶m); - } - return PJ_TRUE; + pj_ssl_sock_close(new_ssock); + + if (listener->tls_setting.on_accept_fail_cb) { + pjsip_tls_on_accept_fail_param param; + pj_bzero(¶m, sizeof(param)); + param.status = status; + param.local_addr = &listener->factory.local_addr; + param.remote_addr = src_addr; + (*listener->tls_setting.on_accept_fail_cb) (¶m); + } + return PJ_TRUE; } /* Copy to larger buffer, just in case */ @@ -1435,21 +1434,21 @@ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock, * Create TLS transport for the new socket. */ status = tls_create( listener, NULL, new_ssock, PJ_TRUE, - &ssl_info.local_addr, &tmp_src_addr, NULL, - ssl_info.grp_lock, &tls); + &ssl_info.local_addr, &tmp_src_addr, NULL, + ssl_info.grp_lock, &tls); if (status != PJ_SUCCESS) { - pj_ssl_sock_close(new_ssock); - - if (listener->tls_setting.on_accept_fail_cb) { - pjsip_tls_on_accept_fail_param param; - pj_bzero(¶m, sizeof(param)); - param.status = status; - param.local_addr = &listener->factory.local_addr; - param.remote_addr = src_addr; - (*listener->tls_setting.on_accept_fail_cb) (¶m); - } - return PJ_TRUE; + pj_ssl_sock_close(new_ssock); + + if (listener->tls_setting.on_accept_fail_cb) { + pjsip_tls_on_accept_fail_param param; + pj_bzero(¶m, sizeof(param)); + param.status = status; + param.local_addr = &listener->factory.local_addr; + param.remote_addr = src_addr; + (*listener->tls_setting.on_accept_fail_cb) (¶m); + } + return PJ_TRUE; } /* Set the "pending" SSL socket user data */ @@ -1464,34 +1463,34 @@ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock, * and destroy the transport. */ if (ssl_info.verify_status && listener->tls_setting.verify_client) { - if (tls->close_reason == PJ_SUCCESS) - tls->close_reason = PJSIP_TLS_ECERTVERIF; - pjsip_transport_shutdown(&tls->base); + if (tls->close_reason == PJ_SUCCESS) + tls->close_reason = PJSIP_TLS_ECERTVERIF; + pjsip_transport_shutdown(&tls->base); } /* Notify transport state to application */ state_cb = pjsip_tpmgr_get_state_cb(tls->base.tpmgr); if (state_cb) { - pjsip_transport_state_info state_info; - pjsip_tls_state_info tls_info; - pjsip_transport_state tp_state; - - /* Init transport state info */ - pj_bzero(&tls_info, sizeof(tls_info)); - pj_bzero(&state_info, sizeof(state_info)); - tls_info.ssl_sock_info = &ssl_info; - state_info.ext_info = &tls_info; - - /* Set transport state based on verification status */ - if (ssl_info.verify_status && listener->tls_setting.verify_client) - { - tp_state = PJSIP_TP_STATE_DISCONNECTED; - state_info.status = PJSIP_TLS_ECERTVERIF; - } else { - tp_state = PJSIP_TP_STATE_CONNECTED; - state_info.status = PJ_SUCCESS; - } + pjsip_transport_state_info state_info; + pjsip_tls_state_info tls_info; + pjsip_transport_state tp_state; + + /* Init transport state info */ + pj_bzero(&tls_info, sizeof(tls_info)); + pj_bzero(&state_info, sizeof(state_info)); + tls_info.ssl_sock_info = &ssl_info; + state_info.ext_info = &tls_info; + + /* Set transport state based on verification status */ + if (ssl_info.verify_status && listener->tls_setting.verify_client) + { + tp_state = PJSIP_TP_STATE_DISCONNECTED; + state_info.status = PJSIP_TLS_ECERTVERIF; + } else { + tp_state = PJSIP_TP_STATE_CONNECTED; + state_info.status = PJ_SUCCESS; + } - (*state_cb)(&tls->base, tp_state, &state_info); + (*state_cb)(&tls->base, tp_state, &state_info); } /* Release transport reference. If transport is shutting down, it may @@ -1500,25 +1499,25 @@ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock, is_shutdown = tls->base.is_shutdown; pjsip_transport_dec_ref(&tls->base); if (is_shutdown) - return PJ_TRUE; + return PJ_TRUE; status = tls_start_read(tls); if (status != PJ_SUCCESS) { - PJ_LOG(3,(tls->base.obj_name, "New transport cancelled")); - tls_init_shutdown(tls, status); - tls_destroy(&tls->base, status); + PJ_LOG(3,(tls->base.obj_name, "New transport cancelled")); + tls_init_shutdown(tls, status); + tls_destroy(&tls->base, status); } else { - /* Start keep-alive timer */ - if (pjsip_cfg()->tls.keep_alive_interval) { - pj_time_val delay = {0}; - delay.sec = pjsip_cfg()->tls.keep_alive_interval; - pjsip_endpt_schedule_timer(listener->endpt, - &tls->ka_timer, - &delay); - tls->ka_timer.id = PJ_TRUE; - pj_gettimeofday(&tls->last_activity); - } + /* Start keep-alive timer */ + if (pjsip_cfg()->tls.keep_alive_interval) { + pj_time_val delay = {0}; + delay.sec = pjsip_cfg()->tls.keep_alive_interval; + pjsip_endpt_schedule_timer(listener->endpt, + &tls->ka_timer, + &delay); + tls->ka_timer.id = PJ_TRUE; + pj_gettimeofday(&tls->last_activity); + } } return PJ_TRUE; @@ -1529,9 +1528,9 @@ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock, * has completed. */ //static pj_bool_t on_accept_complete(pj_ssl_sock_t *ssock, -// pj_ssl_sock_t *new_ssock, -// const pj_sockaddr_t *src_addr, -// int src_addr_len) +// pj_ssl_sock_t *new_ssock, +// const pj_sockaddr_t *src_addr, +// int src_addr_len) //{ // PJ_UNUSED_ARG(src_addr_len); //} @@ -1541,11 +1540,11 @@ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock, * Callback from ioqueue when packet is sent. */ static pj_bool_t on_data_sent(pj_ssl_sock_t *ssock, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_sent) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_sent) { struct tls_transport *tls = (struct tls_transport*) - pj_ssl_sock_get_user_data(ssock); + pj_ssl_sock_get_user_data(ssock); pjsip_tx_data_op_key *tdata_op_key = (pjsip_tx_data_op_key*)op_key; /* Note that op_key may be the op_key from keep-alive, thus @@ -1555,32 +1554,32 @@ static pj_bool_t on_data_sent(pj_ssl_sock_t *ssock, tdata_op_key->tdata = NULL; if (tdata_op_key->callback) { - /* - * Notify sip_transport.c that packet has been sent. - */ - if (bytes_sent == 0) - bytes_sent = -PJ_RETURN_OS_ERROR(OSERR_ENOTCONN); + /* + * Notify sip_transport.c that packet has been sent. + */ + if (bytes_sent == 0) + bytes_sent = -PJ_RETURN_OS_ERROR(OSERR_ENOTCONN); - tdata_op_key->callback(&tls->base, tdata_op_key->token, bytes_sent); + tdata_op_key->callback(&tls->base, tdata_op_key->token, bytes_sent); - /* Mark last activity time */ - pj_gettimeofday(&tls->last_activity); + /* Mark last activity time */ + pj_gettimeofday(&tls->last_activity); } /* Check for error/closure */ if (bytes_sent <= 0) { - pj_status_t status; + pj_status_t status; - PJ_LOG(5,(tls->base.obj_name, "TLS send() error, sent=%d", - bytes_sent)); + PJ_LOG(5,(tls->base.obj_name, "TLS send() error, sent=%d", + bytes_sent)); - status = (bytes_sent == 0) ? PJ_RETURN_OS_ERROR(OSERR_ENOTCONN) : - (pj_status_t)-bytes_sent; + status = (bytes_sent == 0) ? PJ_RETURN_OS_ERROR(OSERR_ENOTCONN) : + (pj_status_t)-bytes_sent; - tls_init_shutdown(tls, status); + tls_init_shutdown(tls, status); - return PJ_FALSE; + return PJ_FALSE; } return PJ_TRUE; @@ -1591,31 +1590,31 @@ static pj_bool_t on_verify_cb(pj_ssl_sock_t* ssock, pj_bool_t is_server) pj_bool_t(*verify_cb)(const pjsip_tls_on_verify_param * param) = NULL; if (is_server) { - struct tls_listener* tls; + struct tls_listener* tls; - tls = (struct tls_listener*)pj_ssl_sock_get_user_data(ssock); - verify_cb = tls->tls_setting.on_verify_cb; + tls = (struct tls_listener*)pj_ssl_sock_get_user_data(ssock); + verify_cb = tls->tls_setting.on_verify_cb; } else { - struct tls_transport* tls; + struct tls_transport* tls; - tls = (struct tls_transport*)pj_ssl_sock_get_user_data(ssock); - verify_cb = tls->on_verify_cb; + tls = (struct tls_transport*)pj_ssl_sock_get_user_data(ssock); + verify_cb = tls->on_verify_cb; } if (verify_cb) { - pjsip_tls_on_verify_param param; - pj_ssl_sock_info info; + pjsip_tls_on_verify_param param; + pj_ssl_sock_info info; - pj_bzero(¶m, sizeof(param)); - pj_ssl_sock_get_info(ssock, &info); + pj_bzero(¶m, sizeof(param)); + pj_ssl_sock_get_info(ssock, &info); - param.local_addr = &info.local_addr; - param.remote_addr = &info.remote_addr; - param.local_cert_info = info.local_cert_info; - param.remote_cert_info = info.remote_cert_info; - param.tp_dir = is_server?PJSIP_TP_DIR_INCOMING:PJSIP_TP_DIR_OUTGOING; - - return (*verify_cb)(¶m); + param.local_addr = &info.local_addr; + param.remote_addr = &info.remote_addr; + param.local_cert_info = info.local_cert_info; + param.remote_cert_info = info.remote_cert_info; + param.tp_dir = is_server?PJSIP_TP_DIR_INCOMING:PJSIP_TP_DIR_OUTGOING; + + return (*verify_cb)(¶m); } return PJ_TRUE; } @@ -1625,11 +1624,11 @@ static pj_bool_t on_verify_cb(pj_ssl_sock_t* ssock, pj_bool_t is_server) * This callback is called by transport manager to send SIP message */ static pj_status_t tls_send_msg(pjsip_transport *transport, - pjsip_tx_data *tdata, - const pj_sockaddr_t *rem_addr, - int addr_len, - void *token, - pjsip_transport_callback callback) + pjsip_tx_data *tdata, + const pj_sockaddr_t *rem_addr, + int addr_len, + void *token, + pjsip_transport_callback callback) { struct tls_transport *tls = (struct tls_transport*)transport; pj_ssize_t size; @@ -1644,8 +1643,8 @@ static pj_status_t tls_send_msg(pjsip_transport *transport, /* Check the address is supported */ PJ_ASSERT_RETURN(rem_addr && (addr_len==sizeof(pj_sockaddr_in) || - addr_len==sizeof(pj_sockaddr_in6)), - PJ_EINVAL); + addr_len==sizeof(pj_sockaddr_in6)), + PJ_EINVAL); /* Init op key. */ tdata->op_key.tdata = tdata; @@ -1658,68 +1657,68 @@ static pj_status_t tls_send_msg(pjsip_transport *transport, */ if (tls->has_pending_connect) { - /* - * Looks like connect() is still in progress. Check again (this time - * with holding the lock) to be sure. - */ - pj_lock_acquire(tls->base.lock); + /* + * Looks like connect() is still in progress. Check again (this time + * with holding the lock) to be sure. + */ + pj_lock_acquire(tls->base.lock); - if (tls->has_pending_connect) { - struct delayed_tdata *delayed_tdata; + if (tls->has_pending_connect) { + struct delayed_tdata *delayed_tdata; - /* - * connect() is still in progress. Put the transmit data to - * the delayed list. + /* + * connect() is still in progress. Put the transmit data to + * the delayed list. * Starting from #1583 (https://github.com/pjsip/pjproject/issues/1583), * we also add timeout value for the transmit data. When the * connect() is completed, the timeout value will be checked to * determine whether the transmit data needs to be sent. - */ - delayed_tdata = PJ_POOL_ZALLOC_T(tdata->pool, - struct delayed_tdata); - delayed_tdata->tdata_op_key = &tdata->op_key; + */ + delayed_tdata = PJ_POOL_ZALLOC_T(tdata->pool, + struct delayed_tdata); + delayed_tdata->tdata_op_key = &tdata->op_key; if (tdata->msg && tdata->msg->type == PJSIP_REQUEST_MSG) { pj_gettickcount(&delayed_tdata->timeout); delayed_tdata->timeout.msec += pjsip_cfg()->tsx.td; pj_time_val_normalize(&delayed_tdata->timeout); } - pj_list_push_back(&tls->delayed_list, delayed_tdata); - status = PJ_EPENDING; + pj_list_push_back(&tls->delayed_list, delayed_tdata); + status = PJ_EPENDING; - /* Prevent pj_ioqueue_send() to be called below */ - delayed = PJ_TRUE; - } + /* Prevent pj_ioqueue_send() to be called below */ + delayed = PJ_TRUE; + } - pj_lock_release(tls->base.lock); + pj_lock_release(tls->base.lock); } if (!delayed) { - /* - * Transport is ready to go. Send the packet to ioqueue to be - * sent asynchronously. - */ - size = tdata->buf.cur - tdata->buf.start; - status = pj_ssl_sock_send(tls->ssock, - (pj_ioqueue_op_key_t*)&tdata->op_key, - tdata->buf.start, &size, 0); + /* + * Transport is ready to go. Send the packet to ioqueue to be + * sent asynchronously. + */ + size = tdata->buf.cur - tdata->buf.start; + status = pj_ssl_sock_send(tls->ssock, + (pj_ioqueue_op_key_t*)&tdata->op_key, + tdata->buf.start, &size, 0); - if (status != PJ_EPENDING) { - /* Not pending (could be immediate success or error) */ - tdata->op_key.tdata = NULL; + if (status != PJ_EPENDING) { + /* Not pending (could be immediate success or error) */ + tdata->op_key.tdata = NULL; - /* Shutdown transport on closure/errors */ - if (size <= 0) { + /* Shutdown transport on closure/errors */ + if (size <= 0) { - PJ_LOG(5,(tls->base.obj_name, "TLS send() error, sent=%d", - size)); + PJ_LOG(5,(tls->base.obj_name, "TLS send() error, sent=%d", + size)); - if (status == PJ_SUCCESS) - status = PJ_RETURN_OS_ERROR(OSERR_ENOTCONN); + if (status == PJ_SUCCESS) + status = PJ_RETURN_OS_ERROR(OSERR_ENOTCONN); - tls_init_shutdown(tls, status); - } - } + tls_init_shutdown(tls, status); + } + } } return status; @@ -1735,8 +1734,8 @@ static pj_status_t tls_shutdown(pjsip_transport *transport) /* Stop keep-alive timer. */ if (tls->ka_timer.id) { - pjsip_endpt_cancel_timer(tls->base.endpt, &tls->ka_timer); - tls->ka_timer.id = PJ_FALSE; + pjsip_endpt_cancel_timer(tls->base.endpt, &tls->ka_timer); + tls->ka_timer.id = PJ_FALSE; } return PJ_SUCCESS; @@ -1747,10 +1746,10 @@ static pj_status_t tls_shutdown(pjsip_transport *transport) * Callback from ioqueue that an incoming data is received from the socket. */ static pj_bool_t on_data_read(pj_ssl_sock_t *ssock, - void *data, - pj_size_t size, - pj_status_t status, - pj_size_t *remainder) + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) { enum { MAX_IMMEDIATE_PACKET = 10 }; struct tls_transport *tls; @@ -1763,52 +1762,52 @@ static pj_bool_t on_data_read(pj_ssl_sock_t *ssock, /* Don't do anything if transport is closing. */ if (tls->is_closing) { - tls->is_closing++; - return PJ_FALSE; + tls->is_closing++; + return PJ_FALSE; } /* Houston, we have packet! Report the packet to transport manager * to be parsed. */ if (status == PJ_SUCCESS) { - pj_size_t size_eaten; - - /* Mark this as an activity */ - pj_gettimeofday(&tls->last_activity); - - pj_assert((void*)rdata->pkt_info.packet == data); - - /* Init pkt_info part. */ - rdata->pkt_info.len = size; - rdata->pkt_info.zero = 0; - pj_gettimeofday(&rdata->pkt_info.timestamp); - - /* Report to transport manager. - * The transport manager will tell us how many bytes of the packet - * have been processed (as valid SIP message). - */ - size_eaten = - pjsip_tpmgr_receive_packet(rdata->tp_info.transport->tpmgr, - rdata); - - pj_assert(size_eaten <= (pj_size_t)rdata->pkt_info.len); - - /* Move unprocessed data to the front of the buffer */ - *remainder = size - size_eaten; - if (*remainder > 0 && *remainder != size) { - pj_memmove(rdata->pkt_info.packet, - rdata->pkt_info.packet + size_eaten, - *remainder); - } + pj_size_t size_eaten; + + /* Mark this as an activity */ + pj_gettimeofday(&tls->last_activity); + + pj_assert((void*)rdata->pkt_info.packet == data); + + /* Init pkt_info part. */ + rdata->pkt_info.len = size; + rdata->pkt_info.zero = 0; + pj_gettimeofday(&rdata->pkt_info.timestamp); + + /* Report to transport manager. + * The transport manager will tell us how many bytes of the packet + * have been processed (as valid SIP message). + */ + size_eaten = + pjsip_tpmgr_receive_packet(rdata->tp_info.transport->tpmgr, + rdata); + + pj_assert(size_eaten <= (pj_size_t)rdata->pkt_info.len); + + /* Move unprocessed data to the front of the buffer */ + *remainder = size - size_eaten; + if (*remainder > 0 && *remainder != size) { + pj_memmove(rdata->pkt_info.packet, + rdata->pkt_info.packet + size_eaten, + *remainder); + } } else { - /* Transport is closed */ - PJ_LOG(4,(tls->base.obj_name, "TLS connection closed")); + /* Transport is closed */ + PJ_LOG(4,(tls->base.obj_name, "TLS connection closed")); - tls_init_shutdown(tls, status); + tls_init_shutdown(tls, status); - return PJ_FALSE; + return PJ_FALSE; } @@ -1823,7 +1822,7 @@ static pj_bool_t on_data_read(pj_ssl_sock_t *ssock, * Callback from ioqueue when asynchronous connect() operation completes. */ static pj_bool_t on_connect_complete(pj_ssl_sock_t *ssock, - pj_status_t status) + pj_status_t status) { struct tls_transport *tls; pj_ssl_sock_info ssl_info; @@ -1841,31 +1840,31 @@ static pj_bool_t on_connect_complete(pj_ssl_sock_t *ssock, * (see #1898). */ if ((tls->base.is_shutdown || tls->base.is_destroying) && - status == PJ_SUCCESS) + status == PJ_SUCCESS) { - status = PJ_ECANCELLED; + status = PJ_ECANCELLED; } /* Check connect() status */ if (status != PJ_SUCCESS) { - tls_perror(tls->base.obj_name, "TLS connect() error", status, - &tls->remote_name); + tls_perror(tls->base.obj_name, "TLS connect() error", status, + &tls->remote_name); - /* Cancel all delayed transmits */ - while (!pj_list_empty(&tls->delayed_list)) { - struct delayed_tdata *pending_tx; - pj_ioqueue_op_key_t *op_key; + /* Cancel all delayed transmits */ + while (!pj_list_empty(&tls->delayed_list)) { + struct delayed_tdata *pending_tx; + pj_ioqueue_op_key_t *op_key; - pending_tx = tls->delayed_list.next; - pj_list_erase(pending_tx); + pending_tx = tls->delayed_list.next; + pj_list_erase(pending_tx); - op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; + op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; - on_data_sent(tls->ssock, op_key, -status); - } + on_data_sent(tls->ssock, op_key, -status); + } - goto on_error; + goto on_error; } /* Retrieve SSL socket info, shutdown the transport if this is failed @@ -1873,7 +1872,7 @@ static pj_bool_t on_connect_complete(pj_ssl_sock_t *ssock, */ status = pj_ssl_sock_get_info(tls->ssock, &ssl_info); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Update (again) local address, just in case local address currently * set is different now that the socket is connected (could happen @@ -1881,70 +1880,70 @@ static pj_bool_t on_connect_complete(pj_ssl_sock_t *ssock, */ tp_addr = &tls->base.local_addr; pj_sockaddr_cp((pj_sockaddr_t*)&addr, - (pj_sockaddr_t*)&ssl_info.local_addr); + (pj_sockaddr_t*)&ssl_info.local_addr); if (pj_sockaddr_cmp(tp_addr, &addr) != 0) { - pj_sockaddr_cp(tp_addr, &addr); - sockaddr_to_host_port(tls->base.pool, &tls->base.local_name, - tp_addr); + pj_sockaddr_cp(tp_addr, &addr); + sockaddr_to_host_port(tls->base.pool, &tls->base.local_name, + tp_addr); } /* Server identity verification based on server certificate. */ if (ssl_info.remote_cert_info->version) { - pj_str_t *remote_name; - pj_ssl_cert_info *serv_cert = ssl_info.remote_cert_info; - pj_bool_t matched = PJ_FALSE; - unsigned i; - - /* Remote name may be hostname or IP address */ - if (tls->remote_name.slen) - remote_name = &tls->remote_name; - else - remote_name = &tls->base.remote_name.host; - - /* Start matching remote name with SubjectAltName fields of - * server certificate. - */ - for (i = 0; i < serv_cert->subj_alt_name.cnt && !matched; ++i) { - pj_str_t *cert_name = &serv_cert->subj_alt_name.entry[i].name; - - switch (serv_cert->subj_alt_name.entry[i].type) { - case PJ_SSL_CERT_NAME_DNS: - case PJ_SSL_CERT_NAME_IP: - matched = !pj_stricmp(remote_name, cert_name); - break; - case PJ_SSL_CERT_NAME_URI: - if (pj_strnicmp2(cert_name, "sip:", 4) == 0 || - pj_strnicmp2(cert_name, "sips:", 5) == 0) - { - pj_str_t host_part; - char *p; - - p = pj_strchr(cert_name, ':') + 1; - pj_strset(&host_part, p, cert_name->slen - - (p - cert_name->ptr)); - matched = !pj_stricmp(remote_name, &host_part); - } - break; - default: - break; - } - } - - /* When still not matched or no SubjectAltName fields in server - * certificate, try with Common Name of Subject field. - */ - if (!matched) { - matched = !pj_stricmp(remote_name, &serv_cert->subject.cn); - } - - if (!matched) { - if (pj_strnicmp2(&serv_cert->subject.cn, "*.", 2) == 0) { - PJ_LOG(1,(tls->base.obj_name, - "RFC 5922 (section 7.2) does not allow TLS wildcard " - "certificates. Advise your SIP provider, please!")); - } - ssl_info.verify_status |= PJ_SSL_CERT_EIDENTITY_NOT_MATCH; - } + pj_str_t *remote_name; + pj_ssl_cert_info *serv_cert = ssl_info.remote_cert_info; + pj_bool_t matched = PJ_FALSE; + unsigned i; + + /* Remote name may be hostname or IP address */ + if (tls->remote_name.slen) + remote_name = &tls->remote_name; + else + remote_name = &tls->base.remote_name.host; + + /* Start matching remote name with SubjectAltName fields of + * server certificate. + */ + for (i = 0; i < serv_cert->subj_alt_name.cnt && !matched; ++i) { + pj_str_t *cert_name = &serv_cert->subj_alt_name.entry[i].name; + + switch (serv_cert->subj_alt_name.entry[i].type) { + case PJ_SSL_CERT_NAME_DNS: + case PJ_SSL_CERT_NAME_IP: + matched = !pj_stricmp(remote_name, cert_name); + break; + case PJ_SSL_CERT_NAME_URI: + if (pj_strnicmp2(cert_name, "sip:", 4) == 0 || + pj_strnicmp2(cert_name, "sips:", 5) == 0) + { + pj_str_t host_part; + char *p; + + p = pj_strchr(cert_name, ':') + 1; + pj_strset(&host_part, p, cert_name->slen - + (p - cert_name->ptr)); + matched = !pj_stricmp(remote_name, &host_part); + } + break; + default: + break; + } + } + + /* When still not matched or no SubjectAltName fields in server + * certificate, try with Common Name of Subject field. + */ + if (!matched) { + matched = !pj_stricmp(remote_name, &serv_cert->subject.cn); + } + + if (!matched) { + if (pj_strnicmp2(&serv_cert->subject.cn, "*.", 2) == 0) { + PJ_LOG(1,(tls->base.obj_name, + "RFC 5922 (section 7.2) does not allow TLS wildcard " + "certificates. Advise your SIP provider, please!")); + } + ssl_info.verify_status |= PJ_SSL_CERT_EIDENTITY_NOT_MATCH; + } } /* Prevent immediate transport destroy as application may access it @@ -1956,35 +1955,35 @@ static pj_bool_t on_connect_complete(pj_ssl_sock_t *ssock, * and destroy the transport. */ if (ssl_info.verify_status && tls->verify_server) { - if (tls->close_reason == PJ_SUCCESS) - tls->close_reason = PJSIP_TLS_ECERTVERIF; - pjsip_transport_shutdown(&tls->base); + if (tls->close_reason == PJ_SUCCESS) + tls->close_reason = PJSIP_TLS_ECERTVERIF; + pjsip_transport_shutdown(&tls->base); } /* Notify transport state to application */ state_cb = pjsip_tpmgr_get_state_cb(tls->base.tpmgr); if (state_cb) { - pjsip_transport_state_info state_info; - pjsip_tls_state_info tls_info; - pjsip_transport_state tp_state; - - /* Init transport state info */ - pj_bzero(&state_info, sizeof(state_info)); - pj_bzero(&tls_info, sizeof(tls_info)); - state_info.ext_info = &tls_info; - tls_info.ssl_sock_info = &ssl_info; - - /* Set transport state based on verification status */ - if (ssl_info.verify_status && tls->verify_server) - { - tp_state = PJSIP_TP_STATE_DISCONNECTED; - state_info.status = PJSIP_TLS_ECERTVERIF; - } else { - tp_state = PJSIP_TP_STATE_CONNECTED; - state_info.status = PJ_SUCCESS; - } + pjsip_transport_state_info state_info; + pjsip_tls_state_info tls_info; + pjsip_transport_state tp_state; + + /* Init transport state info */ + pj_bzero(&state_info, sizeof(state_info)); + pj_bzero(&tls_info, sizeof(tls_info)); + state_info.ext_info = &tls_info; + tls_info.ssl_sock_info = &ssl_info; + + /* Set transport state based on verification status */ + if (ssl_info.verify_status && tls->verify_server) + { + tp_state = PJSIP_TP_STATE_DISCONNECTED; + state_info.status = PJSIP_TLS_ECERTVERIF; + } else { + tp_state = PJSIP_TP_STATE_CONNECTED; + state_info.status = PJ_SUCCESS; + } - (*state_cb)(&tls->base, tp_state, &state_info); + (*state_cb)(&tls->base, tp_state, &state_info); } /* Release transport reference. If transport is shutting down, it may @@ -1993,24 +1992,24 @@ static pj_bool_t on_connect_complete(pj_ssl_sock_t *ssock, is_shutdown = tls->base.is_shutdown; pjsip_transport_dec_ref(&tls->base); if (is_shutdown) { - status = tls->close_reason; - tls_perror(tls->base.obj_name, "TLS connect() error", status, - &tls->remote_name); + status = tls->close_reason; + tls_perror(tls->base.obj_name, "TLS connect() error", status, + &tls->remote_name); - /* Cancel all delayed transmits */ - while (!pj_list_empty(&tls->delayed_list)) { - struct delayed_tdata *pending_tx; - pj_ioqueue_op_key_t *op_key; + /* Cancel all delayed transmits */ + while (!pj_list_empty(&tls->delayed_list)) { + struct delayed_tdata *pending_tx; + pj_ioqueue_op_key_t *op_key; - pending_tx = tls->delayed_list.next; - pj_list_erase(pending_tx); + pending_tx = tls->delayed_list.next; + pj_list_erase(pending_tx); - op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; + op_key = (pj_ioqueue_op_key_t*)pending_tx->tdata_op_key; - on_data_sent(tls->ssock, op_key, -status); - } + on_data_sent(tls->ssock, op_key, -status); + } - return PJ_FALSE; + return PJ_FALSE; } @@ -2018,30 +2017,30 @@ static pj_bool_t on_connect_complete(pj_ssl_sock_t *ssock, tls->has_pending_connect = PJ_FALSE; PJ_LOG(4,(tls->base.obj_name, - "TLS transport %s is connected to %s", - pj_addr_str_print(&tls->base.local_name.host, - tls->base.local_name.port, local_addr_buf, - sizeof(local_addr_buf), 1), - pj_addr_str_print(&tls->base.remote_name.host, - tls->base.remote_name.port, remote_addr_buf, - sizeof(remote_addr_buf), 1))); + "TLS transport %s is connected to %s", + pj_addr_str_print(&tls->base.local_name.host, + tls->base.local_name.port, local_addr_buf, + sizeof(local_addr_buf), 1), + pj_addr_str_print(&tls->base.remote_name.host, + tls->base.remote_name.port, remote_addr_buf, + sizeof(remote_addr_buf), 1))); /* Start pending read */ status = tls_start_read(tls); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Flush all pending send operations */ tls_flush_pending_tx(tls); /* Start keep-alive timer */ if (pjsip_cfg()->tls.keep_alive_interval) { - pj_time_val delay = {0}; - delay.sec = pjsip_cfg()->tls.keep_alive_interval; - pjsip_endpt_schedule_timer(tls->base.endpt, &tls->ka_timer, - &delay); - tls->ka_timer.id = PJ_TRUE; - pj_gettimeofday(&tls->last_activity); + pj_time_val delay = {0}; + delay.sec = pjsip_cfg()->tls.keep_alive_interval; + pjsip_endpt_schedule_timer(tls->base.endpt, &tls->ka_timer, + &delay); + tls->ka_timer.id = PJ_TRUE; + pj_gettimeofday(&tls->last_activity); } return PJ_TRUE; @@ -2071,34 +2070,34 @@ static void tls_keep_alive_timer(pj_timer_heap_t *th, pj_timer_entry *e) PJ_TIME_VAL_SUB(now, tls->last_activity); if (now.sec > 0 && now.sec < pjsip_cfg()->tls.keep_alive_interval) { - /* There has been activity, so don't send keep-alive */ - delay.sec = pjsip_cfg()->tls.keep_alive_interval - now.sec; - delay.msec = 0; + /* There has been activity, so don't send keep-alive */ + delay.sec = pjsip_cfg()->tls.keep_alive_interval - now.sec; + delay.msec = 0; - pjsip_endpt_schedule_timer(tls->base.endpt, &tls->ka_timer, - &delay); - tls->ka_timer.id = PJ_TRUE; - return; + pjsip_endpt_schedule_timer(tls->base.endpt, &tls->ka_timer, + &delay); + tls->ka_timer.id = PJ_TRUE; + return; } PJ_LOG(5,(tls->base.obj_name, "Sending %d byte(s) keep-alive to %s", - (int)tls->ka_pkt.slen, - pj_addr_str_print(&tls->base.remote_name.host, - tls->base.remote_name.port, addr, - sizeof(addr), 1))); + (int)tls->ka_pkt.slen, + pj_addr_str_print(&tls->base.remote_name.host, + tls->base.remote_name.port, addr, + sizeof(addr), 1))); /* Send the data */ size = tls->ka_pkt.slen; status = pj_ssl_sock_send(tls->ssock, &tls->ka_op_key.key, - tls->ka_pkt.ptr, &size, 0); + tls->ka_pkt.ptr, &size, 0); if (status != PJ_SUCCESS && status != PJ_EPENDING) { - tls_perror(tls->base.obj_name, - "Error sending keep-alive packet", status, - &tls->remote_name); + tls_perror(tls->base.obj_name, + "Error sending keep-alive packet", status, + &tls->remote_name); - tls_init_shutdown(tls, status); - return; + tls_init_shutdown(tls, status); + return; } /* Register next keep-alive */ @@ -2106,7 +2105,7 @@ static void tls_keep_alive_timer(pj_timer_heap_t *th, pj_timer_entry *e) delay.msec = 0; pjsip_endpt_schedule_timer(tls->base.endpt, &tls->ka_timer, - &delay); + &delay); tls->ka_timer.id = PJ_TRUE; } diff --git a/pjsip/src/pjsip/sip_transport_udp.c b/pjsip/src/pjsip/sip_transport_udp.c index c1fdc17988..feeaa31b52 100644 --- a/pjsip/src/pjsip/sip_transport_udp.c +++ b/pjsip/src/pjsip/sip_transport_udp.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -56,27 +55,27 @@ * still do so by declaring these two macros in config_site.h */ #ifndef PJSIP_UDP_SO_SNDBUF_SIZE -/*# define PJSIP_UDP_SO_SNDBUF_SIZE (24*1024*1024)*/ -# define PJSIP_UDP_SO_SNDBUF_SIZE 0 +/*# define PJSIP_UDP_SO_SNDBUF_SIZE (24*1024*1024)*/ +# define PJSIP_UDP_SO_SNDBUF_SIZE 0 #endif #ifndef PJSIP_UDP_SO_RCVBUF_SIZE -/*# define PJSIP_UDP_SO_RCVBUF_SIZE (24*1024*1024)*/ -# define PJSIP_UDP_SO_RCVBUF_SIZE 0 +/*# define PJSIP_UDP_SO_RCVBUF_SIZE (24*1024*1024)*/ +# define PJSIP_UDP_SO_RCVBUF_SIZE 0 #endif /* Struct udp_transport "inherits" struct pjsip_transport */ struct udp_transport { - pjsip_transport base; - pj_sock_t sock; + pjsip_transport base; + pj_sock_t sock; pj_ioqueue_key_t *key; - int rdata_cnt; + int rdata_cnt; pjsip_rx_data **rdata; - int is_closing; - pj_bool_t is_paused; - int read_loop_spin; + int is_closing; + pj_bool_t is_paused; + int read_loop_spin; /* Group lock to be used by UDP transport and ioqueue key */ pj_grp_lock_t *grp_lock; @@ -87,7 +86,7 @@ struct udp_transport * Initialize transport's receive buffer from the specified pool. */ static void init_rdata(struct udp_transport *tp, unsigned rdata_index, - pj_pool_t *pool, pjsip_rx_data **p_rdata) + pj_pool_t *pool, pjsip_rx_data **p_rdata) { pjsip_rx_data *rdata; @@ -103,12 +102,12 @@ static void init_rdata(struct udp_transport *tp, unsigned rdata_index, rdata->tp_info.tp_data = (void*)(pj_ssize_t)rdata_index; rdata->tp_info.op_key.rdata = rdata; pj_ioqueue_op_key_init(&rdata->tp_info.op_key.op_key, - sizeof(pj_ioqueue_op_key_t)); + sizeof(pj_ioqueue_op_key_t)); tp->rdata[rdata_index] = rdata; if (p_rdata) - *p_rdata = rdata; + *p_rdata = rdata; } @@ -119,8 +118,8 @@ static void init_rdata(struct udp_transport *tp, unsigned rdata_index, * operation has completed. */ static void udp_on_read_complete( pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_read) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_read) { /* See https://github.com/pjsip/pjproject/issues/1197 */ enum { MAX_IMMEDIATE_PACKET = 50 }; @@ -134,34 +133,34 @@ static void udp_on_read_complete( pj_ioqueue_key_t *key, /* Don't do anything if transport is closing. */ if (tp->is_closing) { - tp->is_closing++; - goto on_return; + tp->is_closing++; + goto on_return; } /* Don't do anything if transport is being paused. */ if (tp->is_paused) - goto on_return; + goto on_return; if (-bytes_read == PJ_ESOCKETSTOP) { #if 0 - /* Auto restart is disabled, see #2881 */ - --tp->read_loop_spin; - /* Try to recover by restarting the transport. */ - PJ_LOG(4,(tp->base.obj_name, "Restarting SIP UDP transport")); - status = pjsip_udp_transport_restart2( - &tp->base, - PJSIP_UDP_TRANSPORT_DESTROY_SOCKET, - PJ_INVALID_SOCKET, - &tp->base.local_addr, - &tp->base.local_name); - - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "Error restarting SIP UDP transport")); - } + /* Auto restart is disabled, see #2881 */ + --tp->read_loop_spin; + /* Try to recover by restarting the transport. */ + PJ_LOG(4,(tp->base.obj_name, "Restarting SIP UDP transport")); + status = pjsip_udp_transport_restart2( + &tp->base, + PJSIP_UDP_TRANSPORT_DESTROY_SOCKET, + PJ_INVALID_SOCKET, + &tp->base.local_addr, + &tp->base.local_name); + + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "Error restarting SIP UDP transport")); + } return; #else - goto on_return; + goto on_return; #endif } @@ -172,138 +171,138 @@ static void udp_on_read_complete( pj_ioqueue_key_t *key, * complete asynchronously, to allow other sockets to get their data. */ for (i=0;; ++i) { - enum { MIN_SIZE = 32 }; - pj_uint32_t flags; - - /* Report the packet to transport manager. Only do so if packet size - * is relatively big enough for a SIP packet. - */ - if (bytes_read > MIN_SIZE) { - pj_ssize_t size_eaten; - const pj_sockaddr *src_addr = &rdata->pkt_info.src_addr; - - /* Init pkt_info part. */ - rdata->pkt_info.len = bytes_read; - rdata->pkt_info.zero = 0; - pj_gettimeofday(&rdata->pkt_info.timestamp); - pj_sockaddr_print(src_addr, rdata->pkt_info.src_name, - sizeof(rdata->pkt_info.src_name), 0); - rdata->pkt_info.src_port = pj_sockaddr_get_port(src_addr); - - size_eaten = - pjsip_tpmgr_receive_packet(rdata->tp_info.transport->tpmgr, - rdata); - - if (size_eaten < 0) { - pj_assert(!"It shouldn't happen!"); - size_eaten = rdata->pkt_info.len; - } - - /* Since this is UDP, the whole buffer is the message. */ - rdata->pkt_info.len = 0; - - } else if (bytes_read <= MIN_SIZE) { - - /* TODO: */ - - } else if (-bytes_read != PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK) && - -bytes_read != PJ_STATUS_FROM_OS(OSERR_EINPROGRESS) && - -bytes_read != PJ_STATUS_FROM_OS(OSERR_ECONNRESET)) - { - - /* Report error to endpoint. */ - PJSIP_ENDPT_LOG_ERROR((rdata->tp_info.transport->endpt, - rdata->tp_info.transport->obj_name, - (pj_status_t)-bytes_read, - "Warning: pj_ioqueue_recvfrom()" - " callback error")); - } - - if (i >= MAX_IMMEDIATE_PACKET) { - /* Force ioqueue_recvfrom() to return PJ_EPENDING */ - flags = PJ_IOQUEUE_ALWAYS_ASYNC; - } else { - flags = 0; - } - - /* Reset pool. - * Need to copy rdata fields to temp variable because they will - * be invalid after pj_pool_reset(). - */ - { - pj_pool_t *rdata_pool = rdata->tp_info.pool; - struct udp_transport *rdata_tp ; - unsigned rdata_index; - - rdata_tp = (struct udp_transport*)rdata->tp_info.transport; - rdata_index = (unsigned)(unsigned long)(pj_ssize_t) - rdata->tp_info.tp_data; - - pj_pool_reset(rdata_pool); - init_rdata(rdata_tp, rdata_index, rdata_pool, &rdata); - - /* Change some vars to point to new location after - * pool reset. - */ - op_key = &rdata->tp_info.op_key.op_key; - } - - /* Only read next packet if transport is not being paused. This - * check handles the case where transport is paused while endpoint - * is still processing a SIP message. - */ - if (tp->is_paused) - break; - - /* Read next packet. */ - bytes_read = sizeof(rdata->pkt_info.packet); - rdata->pkt_info.src_addr_len = sizeof(rdata->pkt_info.src_addr); - status = pj_ioqueue_recvfrom(key, op_key, - rdata->pkt_info.packet, - &bytes_read, flags, - &rdata->pkt_info.src_addr, - &rdata->pkt_info.src_addr_len); - - if (status == PJ_SUCCESS) { - /* Continue loop. */ - pj_assert(i < MAX_IMMEDIATE_PACKET); - - } else if (status == PJ_EPENDING) { - break; - - } else if (status == PJ_ECANCELLED) { - /* Socket is closing, quit loop */ - break; - - } else { - - if (i < MAX_IMMEDIATE_PACKET) { - - /* Report error to endpoint if this is not EWOULDBLOCK error.*/ - if (status != PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK) && - status != PJ_STATUS_FROM_OS(OSERR_EINPROGRESS) && - status != PJ_STATUS_FROM_OS(OSERR_ECONNRESET)) - { - PJSIP_ENDPT_LOG_ERROR((rdata->tp_info.transport->endpt, - rdata->tp_info.transport->obj_name, - status, - "Warning: pj_ioqueue_recvfrom")); - } - - /* Continue loop. */ - bytes_read = 0; - } else { - /* This is fatal error. - * Ioqueue operation will stop for this transport! - */ - PJSIP_ENDPT_LOG_ERROR((rdata->tp_info.transport->endpt, - rdata->tp_info.transport->obj_name, - status, - "FATAL: pj_ioqueue_recvfrom() error, " - "UDP transport stopping! Error")); - break; - } - } + enum { MIN_SIZE = 32 }; + pj_uint32_t flags; + + /* Report the packet to transport manager. Only do so if packet size + * is relatively big enough for a SIP packet. + */ + if (bytes_read > MIN_SIZE) { + pj_ssize_t size_eaten; + const pj_sockaddr *src_addr = &rdata->pkt_info.src_addr; + + /* Init pkt_info part. */ + rdata->pkt_info.len = bytes_read; + rdata->pkt_info.zero = 0; + pj_gettimeofday(&rdata->pkt_info.timestamp); + pj_sockaddr_print(src_addr, rdata->pkt_info.src_name, + sizeof(rdata->pkt_info.src_name), 0); + rdata->pkt_info.src_port = pj_sockaddr_get_port(src_addr); + + size_eaten = + pjsip_tpmgr_receive_packet(rdata->tp_info.transport->tpmgr, + rdata); + + if (size_eaten < 0) { + pj_assert(!"It shouldn't happen!"); + size_eaten = rdata->pkt_info.len; + } + + /* Since this is UDP, the whole buffer is the message. */ + rdata->pkt_info.len = 0; + + } else if (bytes_read <= MIN_SIZE) { + + /* TODO: */ + + } else if (-bytes_read != PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK) && + -bytes_read != PJ_STATUS_FROM_OS(OSERR_EINPROGRESS) && + -bytes_read != PJ_STATUS_FROM_OS(OSERR_ECONNRESET)) + { + + /* Report error to endpoint. */ + PJSIP_ENDPT_LOG_ERROR((rdata->tp_info.transport->endpt, + rdata->tp_info.transport->obj_name, + (pj_status_t)-bytes_read, + "Warning: pj_ioqueue_recvfrom()" + " callback error")); + } + + if (i >= MAX_IMMEDIATE_PACKET) { + /* Force ioqueue_recvfrom() to return PJ_EPENDING */ + flags = PJ_IOQUEUE_ALWAYS_ASYNC; + } else { + flags = 0; + } + + /* Reset pool. + * Need to copy rdata fields to temp variable because they will + * be invalid after pj_pool_reset(). + */ + { + pj_pool_t *rdata_pool = rdata->tp_info.pool; + struct udp_transport *rdata_tp ; + unsigned rdata_index; + + rdata_tp = (struct udp_transport*)rdata->tp_info.transport; + rdata_index = (unsigned)(unsigned long)(pj_ssize_t) + rdata->tp_info.tp_data; + + pj_pool_reset(rdata_pool); + init_rdata(rdata_tp, rdata_index, rdata_pool, &rdata); + + /* Change some vars to point to new location after + * pool reset. + */ + op_key = &rdata->tp_info.op_key.op_key; + } + + /* Only read next packet if transport is not being paused. This + * check handles the case where transport is paused while endpoint + * is still processing a SIP message. + */ + if (tp->is_paused) + break; + + /* Read next packet. */ + bytes_read = sizeof(rdata->pkt_info.packet); + rdata->pkt_info.src_addr_len = sizeof(rdata->pkt_info.src_addr); + status = pj_ioqueue_recvfrom(key, op_key, + rdata->pkt_info.packet, + &bytes_read, flags, + &rdata->pkt_info.src_addr, + &rdata->pkt_info.src_addr_len); + + if (status == PJ_SUCCESS) { + /* Continue loop. */ + pj_assert(i < MAX_IMMEDIATE_PACKET); + + } else if (status == PJ_EPENDING) { + break; + + } else if (status == PJ_ECANCELLED) { + /* Socket is closing, quit loop */ + break; + + } else { + + if (i < MAX_IMMEDIATE_PACKET) { + + /* Report error to endpoint if this is not EWOULDBLOCK error.*/ + if (status != PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK) && + status != PJ_STATUS_FROM_OS(OSERR_EINPROGRESS) && + status != PJ_STATUS_FROM_OS(OSERR_ECONNRESET)) + { + PJSIP_ENDPT_LOG_ERROR((rdata->tp_info.transport->endpt, + rdata->tp_info.transport->obj_name, + status, + "Warning: pj_ioqueue_recvfrom")); + } + + /* Continue loop. */ + bytes_read = 0; + } else { + /* This is fatal error. + * Ioqueue operation will stop for this transport! + */ + PJSIP_ENDPT_LOG_ERROR((rdata->tp_info.transport->endpt, + rdata->tp_info.transport->obj_name, + status, + "FATAL: pj_ioqueue_recvfrom() error, " + "UDP transport stopping! Error")); + break; + } + } } on_return: @@ -317,11 +316,11 @@ static void udp_on_read_complete( pj_ioqueue_key_t *key, * operation has completed. */ static void udp_on_write_complete( pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_sent) + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_sent) { struct udp_transport *tp = (struct udp_transport*) - pj_ioqueue_get_user_data(key); + pj_ioqueue_get_user_data(key); pjsip_tx_data_op_key *tdata_op_key = (pjsip_tx_data_op_key*)op_key; tdata_op_key->tdata = NULL; @@ -329,26 +328,26 @@ static void udp_on_write_complete( pj_ioqueue_key_t *key, #if 0 /* Auto restart is disabled, see #2881 */ if (-bytes_sent == PJ_ESOCKETSTOP) { - pj_status_t status; - /* Try to recover by restarting the transport. */ - PJ_LOG(4,(tp->base.obj_name, "Restarting SIP UDP transport")); - status = pjsip_udp_transport_restart2( - &tp->base, - PJSIP_UDP_TRANSPORT_DESTROY_SOCKET, - PJ_INVALID_SOCKET, - &tp->base.local_addr, - &tp->base.local_name); - - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "Error restarting SIP UDP transport")); - } + pj_status_t status; + /* Try to recover by restarting the transport. */ + PJ_LOG(4,(tp->base.obj_name, "Restarting SIP UDP transport")); + status = pjsip_udp_transport_restart2( + &tp->base, + PJSIP_UDP_TRANSPORT_DESTROY_SOCKET, + PJ_INVALID_SOCKET, + &tp->base.local_addr, + &tp->base.local_name); + + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "Error restarting SIP UDP transport")); + } return; } #endif if (tdata_op_key->callback) { - tdata_op_key->callback(&tp->base, tdata_op_key->token, bytes_sent); + tdata_op_key->callback(&tp->base, tdata_op_key->token, bytes_sent); } } @@ -359,11 +358,11 @@ static void udp_on_write_complete( pj_ioqueue_key_t *key, * to send outgoing message. */ static pj_status_t udp_send_msg( pjsip_transport *transport, - pjsip_tx_data *tdata, - const pj_sockaddr_t *rem_addr, - int addr_len, - void *token, - pjsip_transport_callback callback) + pjsip_tx_data *tdata, + const pj_sockaddr_t *rem_addr, + int addr_len, + void *token, + pjsip_transport_callback callback) { struct udp_transport *tp = (struct udp_transport*)transport; pj_ssize_t size; @@ -374,7 +373,7 @@ static pj_status_t udp_send_msg( pjsip_transport *transport, /* Return error if transport is paused */ if (tp->is_paused) - return PJSIP_ETPNOTAVAIL; + return PJSIP_ETPNOTAVAIL; /* Init op key. */ tdata->op_key.tdata = tdata; @@ -384,29 +383,29 @@ static pj_status_t udp_send_msg( pjsip_transport *transport, /* Send to ioqueue! */ size = tdata->buf.cur - tdata->buf.start; status = pj_ioqueue_sendto(tp->key, (pj_ioqueue_op_key_t*)&tdata->op_key, - tdata->buf.start, &size, 0, - rem_addr, addr_len); + tdata->buf.start, &size, 0, + rem_addr, addr_len); if (status != PJ_EPENDING) { #if 0 - /* Auto restart is disabled, see #2881 */ - if (status == PJ_ESOCKETSTOP) { - /* Try to recover by restarting the transport. */ - PJ_LOG(4,(tp->base.obj_name, "Restarting SIP UDP transport")); - status = pjsip_udp_transport_restart2( - &tp->base, - PJSIP_UDP_TRANSPORT_DESTROY_SOCKET, - PJ_INVALID_SOCKET, - &tp->base.local_addr, - &tp->base.local_name); - - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "Error restarting SIP UDP transport")); - } - } + /* Auto restart is disabled, see #2881 */ + if (status == PJ_ESOCKETSTOP) { + /* Try to recover by restarting the transport. */ + PJ_LOG(4,(tp->base.obj_name, "Restarting SIP UDP transport")); + status = pjsip_udp_transport_restart2( + &tp->base, + PJSIP_UDP_TRANSPORT_DESTROY_SOCKET, + PJ_INVALID_SOCKET, + &tp->base.local_addr, + &tp->base.local_name); + + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "Error restarting SIP UDP transport")); + } + } #endif - tdata->op_key.tdata = NULL; + tdata->op_key.tdata = NULL; } return status; @@ -421,16 +420,16 @@ static void udp_on_destroy(void *arg) /* Destroy rdata */ for (i=0; irdata_cnt; ++i) { - pj_pool_release(tp->rdata[i]->tp_info.pool); + pj_pool_release(tp->rdata[i]->tp_info.pool); } /* Destroy reference counter. */ if (tp->base.ref_cnt) - pj_atomic_destroy(tp->base.ref_cnt); + pj_atomic_destroy(tp->base.ref_cnt); /* Destroy lock */ if (tp->base.lock) - pj_lock_destroy(tp->base.lock); + pj_lock_destroy(tp->base.lock); PJ_LOG(4,(tp->base.obj_name, "SIP UDP transport destroyed")); @@ -460,21 +459,21 @@ static pj_status_t udp_destroy( pjsip_transport *transport ) * and another one for closing the socket. * for (i=0; irdata_cnt; ++i) { - pj_ioqueue_post_completion(tp->key, - &tp->rdata[i]->tp_info.op_key.op_key, -1); + pj_ioqueue_post_completion(tp->key, + &tp->rdata[i]->tp_info.op_key.op_key, -1); } */ /* Unregister from ioqueue. */ if (tp->key) { - pj_ioqueue_unregister(tp->key); - tp->key = NULL; + pj_ioqueue_unregister(tp->key); + tp->key = NULL; } else { - /* Close socket. */ - if (tp->sock && tp->sock != PJ_INVALID_SOCKET) { - pj_sock_close(tp->sock); - tp->sock = PJ_INVALID_SOCKET; - } + /* Close socket. */ + if (tp->sock && tp->sock != PJ_INVALID_SOCKET) { + pj_sock_close(tp->sock); + tp->sock = PJ_INVALID_SOCKET; + } } /* Must poll ioqueue because IOCP calls the callback when socket @@ -482,13 +481,13 @@ static pj_status_t udp_destroy( pjsip_transport *transport ) * have been called. */ for (i=0; i<50 && tp->is_closing < 1+tp->rdata_cnt; ++i) { - int cnt; - pj_time_val timeout = {0, 1}; + int cnt; + pj_time_val timeout = {0, 1}; - cnt = pj_ioqueue_poll(pjsip_endpt_get_ioqueue(transport->endpt), - &timeout); - if (cnt == 0) - break; + cnt = pj_ioqueue_poll(pjsip_endpt_get_ioqueue(transport->endpt), + &timeout); + if (cnt == 0) + break; } /* When creating this transport, reference count was incremented to flag @@ -498,16 +497,16 @@ static pj_status_t udp_destroy( pjsip_transport *transport ) * let's do it now, so this transport can be destroyed. */ if (pj_atomic_get(tp->base.ref_cnt) > 0) - pjsip_transport_dec_ref(&tp->base); + pjsip_transport_dec_ref(&tp->base); /* Destroy transport */ if (tp->grp_lock) { - pj_grp_lock_t *grp_lock = tp->grp_lock; - tp->grp_lock = NULL; - pj_grp_lock_dec_ref(grp_lock); - /* Transport may have been deleted at this point */ + pj_grp_lock_t *grp_lock = tp->grp_lock; + tp->grp_lock = NULL; + pj_grp_lock_dec_ref(grp_lock); + /* Transport may have been deleted at this point */ } else { - udp_on_destroy(tp); + udp_on_destroy(tp); } return PJ_SUCCESS; @@ -527,7 +526,7 @@ static pj_status_t udp_shutdown(pjsip_transport *transport) /* Create socket */ static pj_status_t create_socket(int af, const pj_sockaddr_t *local_a, - int addr_len, pj_sock_t *p_sock) + int addr_len, pj_sock_t *p_sock) { pj_sock_t sock; pj_sockaddr_in tmp_addr; @@ -536,25 +535,25 @@ static pj_status_t create_socket(int af, const pj_sockaddr_t *local_a, status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &sock); if (status != PJ_SUCCESS) - return status; + return status; if (local_a == NULL) { - if (af == pj_AF_INET6()) { - pj_bzero(&tmp_addr6, sizeof(tmp_addr6)); - tmp_addr6.sin6_family = (pj_uint16_t)af; - local_a = &tmp_addr6; - addr_len = sizeof(tmp_addr6); - } else { - pj_sockaddr_in_init(&tmp_addr, NULL, 0); - local_a = &tmp_addr; - addr_len = sizeof(tmp_addr); - } + if (af == pj_AF_INET6()) { + pj_bzero(&tmp_addr6, sizeof(tmp_addr6)); + tmp_addr6.sin6_family = (pj_uint16_t)af; + local_a = &tmp_addr6; + addr_len = sizeof(tmp_addr6); + } else { + pj_sockaddr_in_init(&tmp_addr, NULL, 0); + local_a = &tmp_addr; + addr_len = sizeof(tmp_addr); + } } status = pj_sock_bind(sock, local_a, addr_len); if (status != PJ_SUCCESS) { - pj_sock_close(sock); - return status; + pj_sock_close(sock); + return status; } *p_sock = sock; @@ -564,9 +563,9 @@ static pj_status_t create_socket(int af, const pj_sockaddr_t *local_a, /* Generate transport's published address */ static pj_status_t get_published_name(pj_sock_t sock, - char hostbuf[], - int hostbufsz, - pjsip_host_port *bound_name) + char hostbuf[], + int hostbufsz, + pjsip_host_port *bound_name) { pj_sockaddr tmp_addr; int addr_len; @@ -575,50 +574,50 @@ static pj_status_t get_published_name(pj_sock_t sock, addr_len = sizeof(tmp_addr); status = pj_sock_getsockname(sock, &tmp_addr, &addr_len); if (status != PJ_SUCCESS) - return status; + return status; bound_name->host.ptr = hostbuf; if (tmp_addr.addr.sa_family == pj_AF_INET()) { - bound_name->port = pj_ntohs(tmp_addr.ipv4.sin_port); - - /* If bound address specifies "0.0.0.0", get the IP address - * of local hostname. - */ - if (tmp_addr.ipv4.sin_addr.s_addr == PJ_INADDR_ANY) { - pj_sockaddr hostip; - - status = pj_gethostip(pj_AF_INET(), &hostip); - if (status != PJ_SUCCESS) - return status; - - status = pj_inet_ntop(pj_AF_INET(), &hostip.ipv4.sin_addr, - hostbuf, hostbufsz); - } else { - /* Otherwise use bound address. */ - status = pj_inet_ntop(pj_AF_INET(), &tmp_addr.ipv4.sin_addr, - hostbuf, hostbufsz); - } + bound_name->port = pj_ntohs(tmp_addr.ipv4.sin_port); + + /* If bound address specifies "0.0.0.0", get the IP address + * of local hostname. + */ + if (tmp_addr.ipv4.sin_addr.s_addr == PJ_INADDR_ANY) { + pj_sockaddr hostip; + + status = pj_gethostip(pj_AF_INET(), &hostip); + if (status != PJ_SUCCESS) + return status; + + status = pj_inet_ntop(pj_AF_INET(), &hostip.ipv4.sin_addr, + hostbuf, hostbufsz); + } else { + /* Otherwise use bound address. */ + status = pj_inet_ntop(pj_AF_INET(), &tmp_addr.ipv4.sin_addr, + hostbuf, hostbufsz); + } } else { - /* If bound address specifies "INADDR_ANY" (IPv6), get the + /* If bound address specifies "INADDR_ANY" (IPv6), get the * IP address of local hostname */ - pj_uint32_t loop6[4] = { 0, 0, 0, 0}; + pj_uint32_t loop6[4] = { 0, 0, 0, 0}; - bound_name->port = pj_ntohs(tmp_addr.ipv6.sin6_port); + bound_name->port = pj_ntohs(tmp_addr.ipv6.sin6_port); - if (pj_memcmp(&tmp_addr.ipv6.sin6_addr, loop6, sizeof(loop6))==0) { - status = pj_gethostip(tmp_addr.addr.sa_family, &tmp_addr); - if (status != PJ_SUCCESS) - return status; - } + if (pj_memcmp(&tmp_addr.ipv6.sin6_addr, loop6, sizeof(loop6))==0) { + status = pj_gethostip(tmp_addr.addr.sa_family, &tmp_addr); + if (status != PJ_SUCCESS) + return status; + } - status = pj_inet_ntop(tmp_addr.addr.sa_family, - pj_sockaddr_get_addr(&tmp_addr), - hostbuf, hostbufsz); + status = pj_inet_ntop(tmp_addr.addr.sa_family, + pj_sockaddr_get_addr(&tmp_addr), + hostbuf, hostbufsz); } if (status == PJ_SUCCESS) { - bound_name->host.slen = pj_ansi_strlen(hostbuf); + bound_name->host.slen = pj_ansi_strlen(hostbuf); } @@ -627,7 +626,7 @@ static pj_status_t get_published_name(pj_sock_t sock, /* Set the published address of the transport */ static void udp_set_pub_name(struct udp_transport *tp, - const pjsip_host_port *a_name) + const pjsip_host_port *a_name) { enum { INFO_LEN = 80 }; char local_addr[PJ_INET6_ADDRSTRLEN+10]; @@ -643,28 +642,28 @@ static void udp_set_pub_name(struct udp_transport *tp, } pj_strdup_with_null(tp->base.pool, &tp->base.local_name.host, - &a_name->host); + &a_name->host); tp->base.local_name.port = a_name->port; /* Update transport info. */ if (tp->base.info == NULL) { - tp->base.info = (char*) pj_pool_alloc(tp->base.pool, INFO_LEN); + tp->base.info = (char*) pj_pool_alloc(tp->base.pool, INFO_LEN); } pj_sockaddr_print(&tp->base.local_addr, local_addr, sizeof(local_addr), 3); pj_addr_str_print(&tp->base.local_name.host, - tp->base.local_name.port, - pub_addr, sizeof(pub_addr), 1), + tp->base.local_name.port, + pub_addr, sizeof(pub_addr), 1), len = pj_ansi_snprintf( tp->base.info, INFO_LEN, "udp %s [published as %s]", - local_addr, pub_addr); + local_addr, pub_addr); PJ_CHECK_TRUNC_STR(len, tp->base.info, INFO_LEN); } /* Set the socket handle of the transport */ static void udp_set_socket(struct udp_transport *tp, - pj_sock_t sock, - const pjsip_host_port *a_name) + pj_sock_t sock, + const pjsip_host_port *a_name) { #if PJSIP_UDP_SO_RCVBUF_SIZE || PJSIP_UDP_SO_SNDBUF_SIZE long sobuf_size; @@ -675,9 +674,9 @@ static void udp_set_socket(struct udp_transport *tp, #if PJSIP_UDP_SO_RCVBUF_SIZE sobuf_size = PJSIP_UDP_SO_RCVBUF_SIZE; status = pj_sock_setsockopt(sock, pj_SOL_SOCKET(), pj_SO_RCVBUF(), - &sobuf_size, sizeof(sobuf_size)); + &sobuf_size, sizeof(sobuf_size)); if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, "Error setting SO_RCVBUF")); + PJ_PERROR(4,(THIS_FILE, status, "Error setting SO_RCVBUF")); } #endif @@ -685,9 +684,9 @@ static void udp_set_socket(struct udp_transport *tp, #if PJSIP_UDP_SO_SNDBUF_SIZE sobuf_size = PJSIP_UDP_SO_SNDBUF_SIZE; status = pj_sock_setsockopt(sock, pj_SOL_SOCKET(), pj_SO_SNDBUF(), - &sobuf_size, sizeof(sobuf_size)); + &sobuf_size, sizeof(sobuf_size)); if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, "Error setting SO_SNDBUF")); + PJ_PERROR(4,(THIS_FILE, status, "Error setting SO_SNDBUF")); } #endif @@ -707,19 +706,19 @@ static pj_status_t register_to_ioqueue(struct udp_transport *tp) /* Ignore if already registered */ if (tp->key != NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Create group lock if not yet (don't need to do so on UDP restart) */ if (!tp->grp_lock) { - status = pj_grp_lock_create(tp->base.pool, NULL, &tp->grp_lock); - if (status != PJ_SUCCESS) - return status; + status = pj_grp_lock_create(tp->base.pool, NULL, &tp->grp_lock); + if (status != PJ_SUCCESS) + return status; - pj_grp_lock_add_ref(tp->grp_lock); - pj_grp_lock_add_handler(tp->grp_lock, tp->base.pool, tp, - &udp_on_destroy); + pj_grp_lock_add_ref(tp->grp_lock); + pj_grp_lock_add_handler(tp->grp_lock, tp->base.pool, tp, + &udp_on_destroy); - tp->base.grp_lock = tp->grp_lock; + tp->base.grp_lock = tp->grp_lock; } /* Register to ioqueue. */ @@ -729,7 +728,7 @@ static pj_status_t register_to_ioqueue(struct udp_transport *tp) ioqueue_cb.on_write_complete = &udp_on_write_complete; return pj_ioqueue_register_sock2(tp->base.pool, ioqueue, tp->sock, - tp->grp_lock, tp, &ioqueue_cb, &tp->key); + tp->grp_lock, tp, &ioqueue_cb, &tp->key); } /* Start ioqueue asynchronous reading to all rdata */ @@ -740,24 +739,24 @@ static pj_status_t start_async_read(struct udp_transport *tp) /* Start reading the ioqueue. */ for (i=0; irdata_cnt; ++i) { - pj_ssize_t size; - - size = sizeof(tp->rdata[i]->pkt_info.packet); - tp->rdata[i]->pkt_info.src_addr_len = sizeof(tp->rdata[i]->pkt_info.src_addr); - status = pj_ioqueue_recvfrom(tp->key, - &tp->rdata[i]->tp_info.op_key.op_key, - tp->rdata[i]->pkt_info.packet, - &size, PJ_IOQUEUE_ALWAYS_ASYNC, - &tp->rdata[i]->pkt_info.src_addr, - &tp->rdata[i]->pkt_info.src_addr_len); - if (status == PJ_SUCCESS) { - pj_assert(!"Shouldn't happen because PJ_IOQUEUE_ALWAYS_ASYNC!"); - udp_on_read_complete(tp->key, &tp->rdata[i]->tp_info.op_key.op_key, - size); - } else if (status != PJ_EPENDING) { - /* Error! */ - return status; - } + pj_ssize_t size; + + size = sizeof(tp->rdata[i]->pkt_info.packet); + tp->rdata[i]->pkt_info.src_addr_len = sizeof(tp->rdata[i]->pkt_info.src_addr); + status = pj_ioqueue_recvfrom(tp->key, + &tp->rdata[i]->tp_info.op_key.op_key, + tp->rdata[i]->pkt_info.packet, + &size, PJ_IOQUEUE_ALWAYS_ASYNC, + &tp->rdata[i]->pkt_info.src_addr, + &tp->rdata[i]->pkt_info.src_addr_len); + if (status == PJ_SUCCESS) { + pj_assert(!"Shouldn't happen because PJ_IOQUEUE_ALWAYS_ASYNC!"); + udp_on_read_complete(tp->key, &tp->rdata[i]->tp_info.op_key.op_key, + size); + } else if (status != PJ_EPENDING) { + /* Error! */ + return status; + } } return PJ_SUCCESS; @@ -770,11 +769,11 @@ static pj_status_t start_async_read(struct udp_transport *tp) * Attach UDP socket and start transport. */ static pj_status_t transport_attach( pjsip_endpoint *endpt, - pjsip_transport_type_e type, - pj_sock_t sock, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_transport **p_transport) + pjsip_transport_type_e type, + pj_sock_t sock, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_transport **p_transport) { pj_pool_t *pool; struct udp_transport *tp; @@ -783,29 +782,29 @@ static pj_status_t transport_attach( pjsip_endpoint *endpt, pj_status_t status; PJ_ASSERT_RETURN(endpt && sock!=PJ_INVALID_SOCKET && a_name && async_cnt>0, - PJ_EINVAL); + PJ_EINVAL); /* Object name. */ if (type & PJSIP_TRANSPORT_IPV6) { pj_in6_addr dummy6; - format = "udpv6%p"; - /* We don't need to add quote if the transport type is IPv6, but - * actually translated to IPv4. - */ + format = "udpv6%p"; + /* We don't need to add quote if the transport type is IPv6, but + * actually translated to IPv4. + */ if (pj_inet_pton(pj_AF_INET6(), &a_name->host, &dummy6)==PJ_SUCCESS) { - ipv6_quoteb = "["; - ipv6_quotee = "]"; - } + ipv6_quoteb = "["; + ipv6_quotee = "]"; + } } else { - format = "udp%p"; + format = "udp%p"; } /* Create pool. */ pool = pjsip_endpt_create_pool(endpt, format, PJSIP_POOL_LEN_TRANSPORT, - PJSIP_POOL_INC_TRANSPORT); + PJSIP_POOL_INC_TRANSPORT); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; /* Create the UDP transport object. */ tp = PJ_POOL_ZALLOC_T(pool, struct udp_transport); @@ -818,20 +817,20 @@ static pj_status_t transport_attach( pjsip_endpoint *endpt, /* Init reference counter. */ status = pj_atomic_create(pool, 0, &tp->base.ref_cnt); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Init lock. */ status = pj_lock_create_recursive_mutex(pool, pool->obj_name, - &tp->base.lock); + &tp->base.lock); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Set type. */ tp->base.key.type = type; /* Remote address is left zero (except the family) */ tp->base.key.rem_addr.addr.sa_family = (pj_uint16_t) - ((type & PJSIP_TRANSPORT_IPV6) ? pj_AF_INET6() : pj_AF_INET()); + ((type & PJSIP_TRANSPORT_IPV6) ? pj_AF_INET6() : pj_AF_INET()); /* Type name. */ tp->base.type_name = "UDP"; @@ -845,15 +844,15 @@ static pj_status_t transport_attach( pjsip_endpoint *endpt, /* Init local address. */ status = pj_sock_getsockname(sock, &tp->base.local_addr, - &tp->base.addr_len); + &tp->base.addr_len); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Init remote name. */ if (type == PJSIP_TRANSPORT_UDP) - tp->base.remote_name.host = pj_str("0.0.0.0"); + tp->base.remote_name.host = pj_str("0.0.0.0"); else - tp->base.remote_name.host = pj_str("::0"); + tp->base.remote_name.host = pj_str("::0"); tp->base.remote_name.port = 0; /* Init direction */ @@ -870,7 +869,7 @@ static pj_status_t transport_attach( pjsip_endpoint *endpt, /* Register to ioqueue */ status = register_to_ioqueue(tp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Set functions. */ tp->base.send_msg = &udp_send_msg; @@ -881,7 +880,7 @@ static pj_status_t transport_attach( pjsip_endpoint *endpt, tp->base.tpmgr = pjsip_endpt_get_tpmgr(endpt); status = pjsip_transport_register( tp->base.tpmgr, (pjsip_transport*)tp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* This is a permanent transport, so we initialize the ref count * to one so that transport manager won't destroy this transport @@ -892,41 +891,41 @@ static pj_status_t transport_attach( pjsip_endpoint *endpt, /* Create rdata and put it in the array. */ tp->rdata_cnt = 0; tp->rdata = (pjsip_rx_data**) - pj_pool_calloc(tp->base.pool, async_cnt, - sizeof(pjsip_rx_data*)); + pj_pool_calloc(tp->base.pool, async_cnt, + sizeof(pjsip_rx_data*)); for (i=0; ibase.ref_cnt, 0); - pjsip_transport_destroy(&tp->base); - return PJ_ENOMEM; - } - - init_rdata(tp, i, rdata_pool, NULL); - tp->rdata_cnt++; + pj_pool_t *rdata_pool = pjsip_endpt_create_pool(endpt, "rtd%p", + PJSIP_POOL_RDATA_LEN, + PJSIP_POOL_RDATA_INC); + if (!rdata_pool) { + pj_atomic_set(tp->base.ref_cnt, 0); + pjsip_transport_destroy(&tp->base); + return PJ_ENOMEM; + } + + init_rdata(tp, i, rdata_pool, NULL); + tp->rdata_cnt++; } /* Start reading the ioqueue. */ status = start_async_read(tp); if (status != PJ_SUCCESS) { - pjsip_transport_destroy(&tp->base); - return status; + pjsip_transport_destroy(&tp->base); + return status; } /* Done. */ if (p_transport) - *p_transport = &tp->base; + *p_transport = &tp->base; PJ_LOG(4,(tp->base.obj_name, - "SIP %s started, published address is %s%.*s%s:%d", - pjsip_transport_get_type_desc((pjsip_transport_type_e)tp->base.key.type), - ipv6_quoteb, - (int)tp->base.local_name.host.slen, - tp->base.local_name.host.ptr, - ipv6_quotee, - tp->base.local_name.port)); + "SIP %s started, published address is %s%.*s%s:%d", + pjsip_transport_get_type_desc((pjsip_transport_type_e)tp->base.key.type), + ipv6_quoteb, + (int)tp->base.local_name.host.slen, + tp->base.local_name.host.ptr, + ipv6_quotee, + tp->base.local_name.port)); return PJ_SUCCESS; @@ -937,24 +936,24 @@ static pj_status_t transport_attach( pjsip_endpoint *endpt, PJ_DEF(pj_status_t) pjsip_udp_transport_attach( pjsip_endpoint *endpt, - pj_sock_t sock, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_transport **p_transport) + pj_sock_t sock, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_transport **p_transport) { return transport_attach(endpt, PJSIP_TRANSPORT_UDP, sock, a_name, - async_cnt, p_transport); + async_cnt, p_transport); } PJ_DEF(pj_status_t) pjsip_udp_transport_attach2( pjsip_endpoint *endpt, - pjsip_transport_type_e type, - pj_sock_t sock, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_transport **p_transport) + pjsip_transport_type_e type, + pj_sock_t sock, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_transport **p_transport) { return transport_attach(endpt, type, sock, a_name, - async_cnt, p_transport); + async_cnt, p_transport); } @@ -962,7 +961,7 @@ PJ_DEF(pj_status_t) pjsip_udp_transport_attach2( pjsip_endpoint *endpt, * Initialize pjsip_udp_transport_cfg structure with default values. */ PJ_DEF(void) pjsip_udp_transport_cfg_default(pjsip_udp_transport_cfg *cfg, - int af) + int af) { pj_bzero(cfg, sizeof(*cfg)); cfg->af = af; @@ -977,9 +976,9 @@ PJ_DEF(void) pjsip_udp_transport_cfg_default(pjsip_udp_transport_cfg *cfg, * Create a UDP socket in the specified address and start a transport. */ PJ_DEF(pj_status_t) pjsip_udp_transport_start2( - pjsip_endpoint *endpt, - const pjsip_udp_transport_cfg *cfg, - pjsip_transport **p_transport) + pjsip_endpoint *endpt, + const pjsip_udp_transport_cfg *cfg, + pjsip_transport **p_transport) { pj_sock_t sock; pj_status_t status; @@ -992,44 +991,44 @@ PJ_DEF(pj_status_t) pjsip_udp_transport_start2( PJ_ASSERT_RETURN(endpt && cfg && cfg->async_cnt, PJ_EINVAL); if (cfg->bind_addr.addr.sa_family == pj_AF_INET()) { - af = pj_AF_INET(); - transport_type = PJSIP_TRANSPORT_UDP; - addr_len = sizeof(pj_sockaddr_in); + af = pj_AF_INET(); + transport_type = PJSIP_TRANSPORT_UDP; + addr_len = sizeof(pj_sockaddr_in); } else { - af = pj_AF_INET6(); - transport_type = PJSIP_TRANSPORT_UDP6; - addr_len = sizeof(pj_sockaddr_in6); + af = pj_AF_INET6(); + transport_type = PJSIP_TRANSPORT_UDP6; + addr_len = sizeof(pj_sockaddr_in6); } status = create_socket(af, &cfg->bind_addr, addr_len, &sock); if (status != PJ_SUCCESS) - return status; + return status; /* Apply QoS, if specified */ pj_sock_apply_qos2(sock, cfg->qos_type, &cfg->qos_params, - 2, THIS_FILE, "SIP UDP transport"); + 2, THIS_FILE, "SIP UDP transport"); /* Apply sockopt, if specified */ if (cfg->sockopt_params.cnt) - pj_sock_setsockopt_params(sock, &cfg->sockopt_params); + pj_sock_setsockopt_params(sock, &cfg->sockopt_params); if (cfg->addr_name.host.slen == 0) { - /* Address name is not specified. - * Build a name based on bound address. - */ - status = get_published_name(sock, addr_buf, sizeof(addr_buf), - &addr_name); - if (status != PJ_SUCCESS) { - pj_sock_close(sock); - return status; - } + /* Address name is not specified. + * Build a name based on bound address. + */ + status = get_published_name(sock, addr_buf, sizeof(addr_buf), + &addr_name); + if (status != PJ_SUCCESS) { + pj_sock_close(sock); + return status; + } } else { - addr_name = cfg->addr_name; + addr_name = cfg->addr_name; } return pjsip_udp_transport_attach2(endpt, transport_type, sock, - &addr_name, cfg->async_cnt, - p_transport); + &addr_name, cfg->async_cnt, + p_transport); } /* @@ -1038,18 +1037,18 @@ PJ_DEF(pj_status_t) pjsip_udp_transport_start2( * Create a UDP socket in the specified address and start a transport. */ PJ_DEF(pj_status_t) pjsip_udp_transport_start( pjsip_endpoint *endpt, - const pj_sockaddr_in *local_a, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_transport **p_transport) + const pj_sockaddr_in *local_a, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_transport **p_transport) { pjsip_udp_transport_cfg cfg; pjsip_udp_transport_cfg_default(&cfg, pj_AF_INET()); if (local_a) - pj_sockaddr_cp(&cfg.bind_addr, local_a); + pj_sockaddr_cp(&cfg.bind_addr, local_a); if (a_name) - cfg.addr_name = *a_name; + cfg.addr_name = *a_name; cfg.async_cnt = async_cnt; return pjsip_udp_transport_start2(endpt, &cfg, p_transport); @@ -1061,18 +1060,18 @@ PJ_DEF(pj_status_t) pjsip_udp_transport_start( pjsip_endpoint *endpt, * Create a UDP socket in the specified address and start a transport. */ PJ_DEF(pj_status_t) pjsip_udp_transport_start6(pjsip_endpoint *endpt, - const pj_sockaddr_in6 *local_a, - const pjsip_host_port *a_name, - unsigned async_cnt, - pjsip_transport **p_transport) + const pj_sockaddr_in6 *local_a, + const pjsip_host_port *a_name, + unsigned async_cnt, + pjsip_transport **p_transport) { pjsip_udp_transport_cfg cfg; pjsip_udp_transport_cfg_default(&cfg, pj_AF_INET6()); if (local_a) - pj_sockaddr_cp(&cfg.bind_addr, local_a); + pj_sockaddr_cp(&cfg.bind_addr, local_a); if (a_name) - cfg.addr_name = *a_name; + cfg.addr_name = *a_name; cfg.async_cnt = async_cnt; return pjsip_udp_transport_start2(endpt, &cfg, p_transport); @@ -1097,7 +1096,7 @@ PJ_DEF(pj_sock_t) pjsip_udp_transport_get_socket(pjsip_transport *transport) * Temporarily pause or shutdown the transport. */ PJ_DEF(pj_status_t) pjsip_udp_transport_pause(pjsip_transport *transport, - unsigned option) + unsigned option) { struct udp_transport *tp; unsigned i; @@ -1120,25 +1119,25 @@ PJ_DEF(pj_status_t) pjsip_udp_transport_pause(pjsip_transport *transport, /* Cancel the ioqueue operation. */ for (i=0; i<(unsigned)tp->rdata_cnt; ++i) { - pj_ioqueue_post_completion(tp->key, - &tp->rdata[i]->tp_info.op_key.op_key, -1); + pj_ioqueue_post_completion(tp->key, + &tp->rdata[i]->tp_info.op_key.op_key, -1); } /* Destroy the socket? */ if (option & PJSIP_UDP_TRANSPORT_DESTROY_SOCKET) { - if (tp->key) { - /* This implicitly closes the socket */ - pj_ioqueue_unregister(tp->key); - tp->key = NULL; - } else { - /* Close socket. */ - if (tp->sock && tp->sock != PJ_INVALID_SOCKET) { - pj_sock_close(tp->sock); - tp->sock = PJ_INVALID_SOCKET; - } - } - tp->sock = PJ_INVALID_SOCKET; - + if (tp->key) { + /* This implicitly closes the socket */ + pj_ioqueue_unregister(tp->key); + tp->key = NULL; + } else { + /* Close socket. */ + if (tp->sock && tp->sock != PJ_INVALID_SOCKET) { + pj_sock_close(tp->sock); + tp->sock = PJ_INVALID_SOCKET; + } + } + tp->sock = PJ_INVALID_SOCKET; + } PJ_LOG(4,(tp->base.obj_name, "SIP UDP transport paused")); @@ -1157,21 +1156,21 @@ PJ_DEF(pj_status_t) pjsip_udp_transport_pause(pjsip_transport *transport, * - if socket is not specified, create and replace. */ PJ_DEF(pj_status_t) pjsip_udp_transport_restart(pjsip_transport *transport, - unsigned option, - pj_sock_t sock, - const pj_sockaddr_in *local, - const pjsip_host_port *a_name) + unsigned option, + pj_sock_t sock, + const pj_sockaddr_in *local, + const pjsip_host_port *a_name) { return pjsip_udp_transport_restart2(transport, option, sock, - (pj_sockaddr*)local, a_name); + (pj_sockaddr*)local, a_name); } PJ_DEF(pj_status_t) pjsip_udp_transport_restart2(pjsip_transport *transport, - unsigned option, - pj_sock_t sock, - const pj_sockaddr *local, - const pjsip_host_port *a_name) + unsigned option, + pj_sock_t sock, + const pj_sockaddr *local, + const pjsip_host_port *a_name) { struct udp_transport *tp; pj_status_t status; @@ -1190,99 +1189,99 @@ PJ_DEF(pj_status_t) pjsip_udp_transport_restart2(pjsip_transport *transport, tp->is_paused = PJ_TRUE; if (option & PJSIP_UDP_TRANSPORT_DESTROY_SOCKET) { - char addr_buf[PJ_INET6_ADDRSTRLEN]; - pjsip_host_port bound_name; - - /* Request to recreate transport */ - - /* Destroy existing socket, if any. */ - if (tp->key) { - /* This implicitly closes the socket */ - pj_ioqueue_unregister(tp->key); - tp->key = NULL; - } else { - /* Close socket. */ - if (tp->sock && tp->sock != PJ_INVALID_SOCKET) { - pj_sock_close(tp->sock); - tp->sock = PJ_INVALID_SOCKET; - } - } - tp->sock = PJ_INVALID_SOCKET; - - /* Create the socket if it's not specified */ - if (sock == PJ_INVALID_SOCKET) { - status = create_socket(local?local->addr.sa_family:pj_AF_UNSPEC(), - local, local?pj_sockaddr_get_len(local):0, - &sock); - if (status != PJ_SUCCESS) - return status; - } - - /* If transport published name is not specified, calculate it - * from the bound address. - */ - if (a_name == NULL) { - status = get_published_name(sock, addr_buf, sizeof(addr_buf), - &bound_name); - if (status != PJ_SUCCESS) { - pj_sock_close(sock); - return status; - } - - a_name = &bound_name; - } + char addr_buf[PJ_INET6_ADDRSTRLEN]; + pjsip_host_port bound_name; + + /* Request to recreate transport */ + + /* Destroy existing socket, if any. */ + if (tp->key) { + /* This implicitly closes the socket */ + pj_ioqueue_unregister(tp->key); + tp->key = NULL; + } else { + /* Close socket. */ + if (tp->sock && tp->sock != PJ_INVALID_SOCKET) { + pj_sock_close(tp->sock); + tp->sock = PJ_INVALID_SOCKET; + } + } + tp->sock = PJ_INVALID_SOCKET; + + /* Create the socket if it's not specified */ + if (sock == PJ_INVALID_SOCKET) { + status = create_socket(local?local->addr.sa_family:pj_AF_UNSPEC(), + local, local?pj_sockaddr_get_len(local):0, + &sock); + if (status != PJ_SUCCESS) + return status; + } + + /* If transport published name is not specified, calculate it + * from the bound address. + */ + if (a_name == NULL) { + status = get_published_name(sock, addr_buf, sizeof(addr_buf), + &bound_name); + if (status != PJ_SUCCESS) { + pj_sock_close(sock); + return status; + } + + a_name = &bound_name; + } /* Init local address. */ status = pj_sock_getsockname(sock, &tp->base.local_addr, - &tp->base.addr_len); + &tp->base.addr_len); if (status != PJ_SUCCESS) { pj_sock_close(sock); return status; } - /* Assign the socket and published address to transport. */ - udp_set_socket(tp, sock, a_name); + /* Assign the socket and published address to transport. */ + udp_set_socket(tp, sock, a_name); } else { - /* For KEEP_SOCKET, transport must have been paused before */ - PJ_ASSERT_RETURN(tp->is_paused, PJ_EINVALIDOP); + /* For KEEP_SOCKET, transport must have been paused before */ + PJ_ASSERT_RETURN(tp->is_paused, PJ_EINVALIDOP); - /* If address name is specified, update it */ - if (a_name != NULL) - udp_set_pub_name(tp, a_name); + /* If address name is specified, update it */ + if (a_name != NULL) + udp_set_pub_name(tp, a_name); } /* Make sure all udp_on_read_complete() loop spin are stopped */ do { - pj_thread_sleep(1); + pj_thread_sleep(1); } while (tp->read_loop_spin); /* Re-register new or existing socket to ioqueue. */ status = register_to_ioqueue(tp); if (status != PJ_SUCCESS) { - return status; + return status; } /* Re-init op_key. */ for (i = 0; i < tp->rdata_cnt; ++i) { - pj_ioqueue_op_key_init(&tp->rdata[i]->tp_info.op_key.op_key, - sizeof(pj_ioqueue_op_key_t)); + pj_ioqueue_op_key_init(&tp->rdata[i]->tp_info.op_key.op_key, + sizeof(pj_ioqueue_op_key_t)); } /* Restart async read operation. */ status = start_async_read(tp); if (status != PJ_SUCCESS) - return status; + return status; /* Everything has been set up */ tp->is_paused = PJ_FALSE; PJ_LOG(4, (tp->base.obj_name, - "SIP UDP transport restarted, published address is %s", - pj_addr_str_print(&tp->base.local_name.host, - tp->base.local_name.port, - addr, sizeof(addr), 1))); + "SIP UDP transport restarted, published address is %s", + pj_addr_str_print(&tp->base.local_name.host, + tp->base.local_name.port, + addr, sizeof(addr), 1))); return PJ_SUCCESS; } diff --git a/pjsip/src/pjsip/sip_transport_wrap.cpp b/pjsip/src/pjsip/sip_transport_wrap.cpp index 3faad08873..f4d1091fbe 100644 --- a/pjsip/src/pjsip/sip_transport_wrap.cpp +++ b/pjsip/src/pjsip/sip_transport_wrap.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjsip/src/pjsip/sip_ua_layer.c b/pjsip/src/pjsip/sip_ua_layer.c index 5d79882a19..e6a7eaa9f3 100644 --- a/pjsip/src/pjsip/sip_ua_layer.c +++ b/pjsip/src/pjsip/sip_ua_layer.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -40,10 +39,10 @@ static pj_status_t mod_ua_load(pjsip_endpoint *endpt); static pj_status_t mod_ua_unload(void); static pj_bool_t mod_ua_on_rx_request(pjsip_rx_data *rdata); static pj_bool_t mod_ua_on_rx_response(pjsip_rx_data *rdata); -static void mod_ua_on_tsx_state(pjsip_transaction*, pjsip_event*); +static void mod_ua_on_tsx_state(pjsip_transaction*, pjsip_event*); -extern long pjsip_dlg_lock_tls_id; /* defined in sip_dialog.c */ +extern long pjsip_dlg_lock_tls_id; /* defined in sip_dialog.c */ /* This struct is used to represent list of dialog inside a dialog set. * We don't want to use pjsip_dialog for this purpose, to save some @@ -78,30 +77,30 @@ struct dlg_set */ static struct user_agent { - pjsip_module mod; - pj_pool_t *pool; - pjsip_endpoint *endpt; - pj_mutex_t *mutex; - pj_hash_table_t *dlg_table; + pjsip_module mod; + pj_pool_t *pool; + pjsip_endpoint *endpt; + pj_mutex_t *mutex; + pj_hash_table_t *dlg_table; pjsip_ua_init_param param; - struct dlg_set free_dlgset_nodes; + struct dlg_set free_dlgset_nodes; } mod_ua = { { - NULL, NULL, /* prev, next. */ - { "mod-ua", 6 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_UA_PROXY_LAYER, /* Priority */ - &mod_ua_load, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - &mod_ua_unload, /* unload() */ - &mod_ua_on_rx_request, /* on_rx_request() */ - &mod_ua_on_rx_response, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - &mod_ua_on_tsx_state, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-ua", 6 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_UA_PROXY_LAYER, /* Priority */ + &mod_ua_load, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + &mod_ua_unload, /* unload() */ + &mod_ua_on_rx_request, /* on_rx_request() */ + &mod_ua_on_rx_response, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + &mod_ua_on_tsx_state, /* on_tsx_state() */ } }; @@ -117,24 +116,24 @@ static pj_status_t mod_ua_load(pjsip_endpoint *endpt) /* Initialize the user agent. */ mod_ua.endpt = endpt; mod_ua.pool = pjsip_endpt_create_pool( endpt, "ua%p", PJSIP_POOL_LEN_UA, - PJSIP_POOL_INC_UA); + PJSIP_POOL_INC_UA); if (mod_ua.pool == NULL) - return PJ_ENOMEM; + return PJ_ENOMEM; status = pj_mutex_create_recursive(mod_ua.pool, " ua%p", &mod_ua.mutex); if (status != PJ_SUCCESS) - return status; + return status; mod_ua.dlg_table = pj_hash_create(mod_ua.pool, PJSIP_MAX_DIALOG_COUNT); if (mod_ua.dlg_table == NULL) - return PJ_ENOMEM; + return PJ_ENOMEM; pj_list_init(&mod_ua.free_dlgset_nodes); /* Initialize dialog lock. */ status = pj_thread_local_alloc(&pjsip_dlg_lock_tls_id); if (status != PJ_SUCCESS) - return status; + return status; pj_thread_local_set(pjsip_dlg_lock_tls_id, NULL); @@ -154,7 +153,7 @@ static pj_status_t mod_ua_unload(void) /* Release pool */ if (mod_ua.pool) { - pjsip_endpt_release_pool( mod_ua.endpt, mod_ua.pool ); + pjsip_endpt_release_pool( mod_ua.endpt, mod_ua.pool ); } return PJ_SUCCESS; } @@ -172,7 +171,7 @@ static void mod_ua_on_tsx_state( pjsip_transaction *tsx, pjsip_event *e) * destroyed. */ if (mod_ua.mod.id == -1) - return; + return; /* Get the dialog where this transaction belongs. */ dlg = (pjsip_dialog*) tsx->mod_data[mod_ua.mod.id]; @@ -181,7 +180,7 @@ static void mod_ua_on_tsx_state( pjsip_transaction *tsx, pjsip_event *e) * may has been destroyed. */ if (dlg == NULL) - return; + return; /* Hand over the event to the dialog. */ pjsip_dlg_on_tsx_state(dlg, tsx, e); @@ -192,7 +191,7 @@ static void mod_ua_on_tsx_state( pjsip_transaction *tsx, pjsip_event *e) * Init user agent module and register it to the endpoint. */ PJ_DEF(pj_status_t) pjsip_ua_init_module( pjsip_endpoint *endpt, - const pjsip_ua_init_param *prm) + const pjsip_ua_init_param *prm) { pj_status_t status; @@ -201,7 +200,7 @@ PJ_DEF(pj_status_t) pjsip_ua_init_module( pjsip_endpoint *endpt, /* Copy param, if exists. */ if (prm) - pj_memcpy(&mod_ua.param, prm, sizeof(pjsip_ua_init_param)); + pj_memcpy(&mod_ua.param, prm, sizeof(pjsip_ua_init_param)); /* Register the module. */ status = pjsip_endpt_register_module(endpt, &mod_ua.mod); @@ -248,9 +247,9 @@ PJ_DEF(pj_status_t) pjsip_ua_destroy(void) */ /* PJ_DEF(void) pjsip_ua_create_dlg_set_key( pj_pool_t *pool, - pj_str_t *set_key, - const pj_str_t *call_id, - const pj_str_t *local_tag) + pj_str_t *set_key, + const pj_str_t *call_id, + const pj_str_t *local_tag) { PJ_ASSERT_ON_FAIL(pool && set_key && call_id && local_tag, return;); @@ -261,7 +260,7 @@ PJ_DEF(void) pjsip_ua_create_dlg_set_key( pj_pool_t *pool, pj_memcpy(set_key->ptr, call_id->ptr, call_id->slen); set_key->ptr[call_id->slen] = '$'; pj_memcpy(set_key->ptr + call_id->slen + 1, - local_tag->ptr, local_tag->slen); + local_tag->ptr, local_tag->slen); } */ @@ -275,12 +274,12 @@ static struct dlg_set *alloc_dlgset_node(void) struct dlg_set *set; if (!pj_list_empty(&mod_ua.free_dlgset_nodes)) { - set = mod_ua.free_dlgset_nodes.next; - pj_list_erase(set); - return set; + set = mod_ua.free_dlgset_nodes.next; + pj_list_erase(set); + return set; } else { - set = PJ_POOL_ALLOC_T(mod_ua.pool, struct dlg_set); - return set; + set = PJ_POOL_ALLOC_T(mod_ua.pool, struct dlg_set); + return set; } } @@ -289,76 +288,76 @@ static struct dlg_set *alloc_dlgset_node(void) * pjsip_dlg_create_uas_and_inc_lock(); */ PJ_DEF(pj_status_t) pjsip_ua_register_dlg( pjsip_user_agent *ua, - pjsip_dialog *dlg ) + pjsip_dialog *dlg ) { /* Sanity check. */ PJ_ASSERT_RETURN(ua && dlg, PJ_EINVAL); /* For all dialogs, local tag (inc hash) must has been initialized. */ PJ_ASSERT_RETURN(dlg->local.info && dlg->local.info->tag.slen && - dlg->local.tag_hval != 0, PJ_EBUG); + dlg->local.tag_hval != 0, PJ_EBUG); /* For UAS dialog, remote tag (inc hash) must have been initialized. */ //PJ_ASSERT_RETURN(dlg->role==PJSIP_ROLE_UAC || - // (dlg->role==PJSIP_ROLE_UAS && dlg->remote.info->tag.slen - // && dlg->remote.tag_hval != 0), PJ_EBUG); + // (dlg->role==PJSIP_ROLE_UAS && dlg->remote.info->tag.slen + // && dlg->remote.tag_hval != 0), PJ_EBUG); /* Lock the user agent. */ pj_mutex_lock(mod_ua.mutex); /* For UAC, check if there is existing dialog in the same set. */ if (dlg->role == PJSIP_ROLE_UAC) { - struct dlg_set *dlg_set; + struct dlg_set *dlg_set; - dlg_set = (struct dlg_set*) - pj_hash_get_lower( mod_ua.dlg_table, + dlg_set = (struct dlg_set*) + pj_hash_get_lower( mod_ua.dlg_table, dlg->local.info->tag.ptr, - (unsigned)dlg->local.info->tag.slen, - &dlg->local.tag_hval); - - if (dlg_set) { - /* This is NOT the first dialog in the dialog set. - * Just add this dialog in the list. - */ - pj_assert(dlg_set->dlg_list.next != (void*)&dlg_set->dlg_list); - pj_list_push_back(&dlg_set->dlg_list, dlg); - - dlg->dlg_set = dlg_set; - - } else { - /* This is the first dialog in the dialog set. - * Create the dialog set and add this dialog to it. - */ - dlg_set = alloc_dlgset_node(); - dlg_set->ht_key = dlg->local.info->tag; - pj_list_init(&dlg_set->dlg_list); - pj_list_push_back(&dlg_set->dlg_list, dlg); - - dlg->dlg_set = dlg_set; - - /* Register the dialog set in the hash table. */ - pj_hash_set_np_lower(mod_ua.dlg_table, - dlg_set->ht_key.ptr, + (unsigned)dlg->local.info->tag.slen, + &dlg->local.tag_hval); + + if (dlg_set) { + /* This is NOT the first dialog in the dialog set. + * Just add this dialog in the list. + */ + pj_assert(dlg_set->dlg_list.next != (void*)&dlg_set->dlg_list); + pj_list_push_back(&dlg_set->dlg_list, dlg); + + dlg->dlg_set = dlg_set; + + } else { + /* This is the first dialog in the dialog set. + * Create the dialog set and add this dialog to it. + */ + dlg_set = alloc_dlgset_node(); + dlg_set->ht_key = dlg->local.info->tag; + pj_list_init(&dlg_set->dlg_list); + pj_list_push_back(&dlg_set->dlg_list, dlg); + + dlg->dlg_set = dlg_set; + + /* Register the dialog set in the hash table. */ + pj_hash_set_np_lower(mod_ua.dlg_table, + dlg_set->ht_key.ptr, (unsigned)dlg_set->ht_key.slen, - dlg->local.tag_hval, dlg_set->ht_entry, + dlg->local.tag_hval, dlg_set->ht_entry, dlg_set); - } + } } else { - /* For UAS, create the dialog set with a single dialog as member. */ - struct dlg_set *dlg_set; + /* For UAS, create the dialog set with a single dialog as member. */ + struct dlg_set *dlg_set; - dlg_set = alloc_dlgset_node(); - dlg_set->ht_key = dlg->local.info->tag; - pj_list_init(&dlg_set->dlg_list); - pj_list_push_back(&dlg_set->dlg_list, dlg); + dlg_set = alloc_dlgset_node(); + dlg_set->ht_key = dlg->local.info->tag; + pj_list_init(&dlg_set->dlg_list); + pj_list_push_back(&dlg_set->dlg_list, dlg); - dlg->dlg_set = dlg_set; + dlg->dlg_set = dlg_set; - pj_hash_set_np_lower(mod_ua.dlg_table, - dlg_set->ht_key.ptr, + pj_hash_set_np_lower(mod_ua.dlg_table, + dlg_set->ht_key.ptr, (unsigned)dlg_set->ht_key.slen, - dlg->local.tag_hval, dlg_set->ht_entry, dlg_set); + dlg->local.tag_hval, dlg_set->ht_entry, dlg_set); } /* Unlock user agent. */ @@ -370,7 +369,7 @@ PJ_DEF(pj_status_t) pjsip_ua_register_dlg( pjsip_user_agent *ua, PJ_DEF(pj_status_t) pjsip_ua_unregister_dlg( pjsip_user_agent *ua, - pjsip_dialog *dlg ) + pjsip_dialog *dlg ) { struct dlg_set *dlg_set; pjsip_dialog *d; @@ -388,13 +387,13 @@ PJ_DEF(pj_status_t) pjsip_ua_unregister_dlg( pjsip_user_agent *ua, dlg_set = (struct dlg_set*) dlg->dlg_set; d = dlg_set->dlg_list.next; while (d != (pjsip_dialog*)&dlg_set->dlg_list && d != dlg) { - d = d->next; + d = d->next; } if (d != dlg) { - pj_assert(!"Dialog is not registered!"); - pj_mutex_unlock(mod_ua.mutex); - return PJ_EINVALIDOP; + pj_assert(!"Dialog is not registered!"); + pj_mutex_unlock(mod_ua.mutex); + return PJ_EINVALIDOP; } /* Remove this dialog from the list. */ @@ -403,42 +402,42 @@ PJ_DEF(pj_status_t) pjsip_ua_unregister_dlg( pjsip_user_agent *ua, /* If dialog list is empty, remove the dialog set from the hash table. */ if (pj_list_empty(&dlg_set->dlg_list)) { - /* Verify that the dialog set is valid */ - pj_assert(pj_hash_get_lower(mod_ua.dlg_table, dlg_set->ht_key.ptr, - (unsigned)dlg_set->ht_key.slen, - &dlg->local.tag_hval) == dlg_set); + /* Verify that the dialog set is valid */ + pj_assert(pj_hash_get_lower(mod_ua.dlg_table, dlg_set->ht_key.ptr, + (unsigned)dlg_set->ht_key.slen, + &dlg->local.tag_hval) == dlg_set); - pj_hash_set_lower(NULL, mod_ua.dlg_table, dlg_set->ht_key.ptr, - (unsigned)dlg_set->ht_key.slen, - dlg->local.tag_hval, NULL); + pj_hash_set_lower(NULL, mod_ua.dlg_table, dlg_set->ht_key.ptr, + (unsigned)dlg_set->ht_key.slen, + dlg->local.tag_hval, NULL); - /* Return dlg_set to free nodes. */ - pj_list_push_back(&mod_ua.free_dlgset_nodes, dlg_set); + /* Return dlg_set to free nodes. */ + pj_list_push_back(&mod_ua.free_dlgset_nodes, dlg_set); } else { - /* If the just unregistered dialog is being used as hash key, - * reset the dlg_set entry with a new key (i.e: from the first dialog - * in dlg_set). - */ - if (dlg_set->ht_key.ptr == dlg->local.info->tag.ptr && - dlg_set->ht_key.slen == dlg->local.info->tag.slen) - { - pjsip_dialog* key_dlg = dlg_set->dlg_list.next; - - /* Verify that the old & new keys share the hash value */ - pj_assert(key_dlg->local.tag_hval == dlg->local.tag_hval); - - pj_hash_set_lower(NULL, mod_ua.dlg_table, dlg_set->ht_key.ptr, - (unsigned)dlg_set->ht_key.slen, - dlg->local.tag_hval, NULL); - - dlg_set->ht_key = key_dlg->local.info->tag; - - pj_hash_set_np_lower(mod_ua.dlg_table, - dlg_set->ht_key.ptr, - (unsigned)dlg_set->ht_key.slen, - key_dlg->local.tag_hval, dlg_set->ht_entry, - dlg_set); - } + /* If the just unregistered dialog is being used as hash key, + * reset the dlg_set entry with a new key (i.e: from the first dialog + * in dlg_set). + */ + if (dlg_set->ht_key.ptr == dlg->local.info->tag.ptr && + dlg_set->ht_key.slen == dlg->local.info->tag.slen) + { + pjsip_dialog* key_dlg = dlg_set->dlg_list.next; + + /* Verify that the old & new keys share the hash value */ + pj_assert(key_dlg->local.tag_hval == dlg->local.tag_hval); + + pj_hash_set_lower(NULL, mod_ua.dlg_table, dlg_set->ht_key.ptr, + (unsigned)dlg_set->ht_key.slen, + dlg->local.tag_hval, NULL); + + dlg_set->ht_key = key_dlg->local.info->tag; + + pj_hash_set_np_lower(mod_ua.dlg_table, + dlg_set->ht_key.ptr, + (unsigned)dlg_set->ht_key.slen, + key_dlg->local.tag_hval, dlg_set->ht_entry, + dlg_set); + } } /* Unlock user agent. */ @@ -487,9 +486,9 @@ PJ_DEF(unsigned) pjsip_ua_get_dlg_set_count(void) * Find a dialog. */ PJ_DEF(pjsip_dialog*) pjsip_ua_find_dialog(const pj_str_t *call_id, - const pj_str_t *local_tag, - const pj_str_t *remote_tag, - pj_bool_t lock_dialog) + const pj_str_t *local_tag, + const pj_str_t *remote_tag, + pj_bool_t lock_dialog) { struct dlg_set *dlg_set; pjsip_dialog *dlg; @@ -501,64 +500,64 @@ PJ_DEF(pjsip_dialog*) pjsip_ua_find_dialog(const pj_str_t *call_id, /* Lookup the dialog set. */ dlg_set = (struct dlg_set*) - pj_hash_get_lower(mod_ua.dlg_table, local_tag->ptr, + pj_hash_get_lower(mod_ua.dlg_table, local_tag->ptr, (unsigned)local_tag->slen, NULL); if (dlg_set == NULL) { - /* Not found */ - pj_mutex_unlock(mod_ua.mutex); - return NULL; + /* Not found */ + pj_mutex_unlock(mod_ua.mutex); + return NULL; } /* Dialog set is found, now find the matching dialog based on the * remote tag. */ dlg = dlg_set->dlg_list.next; - while (dlg != (pjsip_dialog*)&dlg_set->dlg_list) { - if (pj_stricmp(&dlg->remote.info->tag, remote_tag) == 0) - break; - dlg = dlg->next; + while (dlg != (pjsip_dialog*)&dlg_set->dlg_list) { + if (pj_stricmp(&dlg->remote.info->tag, remote_tag) == 0) + break; + dlg = dlg->next; } if (dlg == (pjsip_dialog*)&dlg_set->dlg_list) { - /* Not found */ - pj_mutex_unlock(mod_ua.mutex); - return NULL; + /* Not found */ + pj_mutex_unlock(mod_ua.mutex); + return NULL; } /* Dialog has been found. It SHOULD have the right Call-ID!! */ if (pj_strcmp(&dlg->call_id->id, call_id)!=0) { - PJ_LOG(6, (THIS_FILE, "Dialog not found: local and remote tags " - "matched but not call id")); + PJ_LOG(6, (THIS_FILE, "Dialog not found: local and remote tags " + "matched but not call id")); pj_mutex_unlock(mod_ua.mutex); return NULL; } if (lock_dialog) { - if (pjsip_dlg_try_inc_lock(dlg) != PJ_SUCCESS) { - - /* - * Unable to acquire dialog's lock while holding the user - * agent's mutex. Release the UA mutex before retrying once - * more. - * - * THIS MAY CAUSE RACE CONDITION! - */ - - /* Unlock user agent. */ - pj_mutex_unlock(mod_ua.mutex); - /* Lock dialog */ - pjsip_dlg_inc_lock(dlg); - - } else { - /* Unlock user agent. */ - pj_mutex_unlock(mod_ua.mutex); - } + if (pjsip_dlg_try_inc_lock(dlg) != PJ_SUCCESS) { + + /* + * Unable to acquire dialog's lock while holding the user + * agent's mutex. Release the UA mutex before retrying once + * more. + * + * THIS MAY CAUSE RACE CONDITION! + */ + + /* Unlock user agent. */ + pj_mutex_unlock(mod_ua.mutex); + /* Lock dialog */ + pjsip_dlg_inc_lock(dlg); + + } else { + /* Unlock user agent. */ + pj_mutex_unlock(mod_ua.mutex); + } } else { - /* Unlock user agent. */ - pj_mutex_unlock(mod_ua.mutex); + /* Unlock user agent. */ + pj_mutex_unlock(mod_ua.mutex); } return dlg; @@ -575,55 +574,55 @@ static struct dlg_set *find_dlg_set_for_msg( pjsip_rx_data *rdata ) */ if (rdata->msg_info.cseq->method.id == PJSIP_CANCEL_METHOD) { - pjsip_dialog *dlg; + pjsip_dialog *dlg; - /* Create key for the rdata, but this time, use INVITE as the - * method. - */ - pj_str_t key; - pjsip_role_e role; - pjsip_transaction *tsx; + /* Create key for the rdata, but this time, use INVITE as the + * method. + */ + pj_str_t key; + pjsip_role_e role; + pjsip_transaction *tsx; - if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) - role = PJSIP_ROLE_UAS; - else - role = PJSIP_ROLE_UAC; + if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) + role = PJSIP_ROLE_UAS; + else + role = PJSIP_ROLE_UAC; - pjsip_tsx_create_key(rdata->tp_info.pool, &key, role, - pjsip_get_invite_method(), rdata); + pjsip_tsx_create_key(rdata->tp_info.pool, &key, role, + pjsip_get_invite_method(), rdata); - /* Lookup the INVITE transaction */ - tsx = pjsip_tsx_layer_find_tsx2(&key, PJ_TRUE); + /* Lookup the INVITE transaction */ + tsx = pjsip_tsx_layer_find_tsx2(&key, PJ_TRUE); - /* We should find the dialog attached to the INVITE transaction */ - if (tsx) { - dlg = (pjsip_dialog*) tsx->mod_data[mod_ua.mod.id]; - pj_grp_lock_dec_ref(tsx->grp_lock); + /* We should find the dialog attached to the INVITE transaction */ + if (tsx) { + dlg = (pjsip_dialog*) tsx->mod_data[mod_ua.mod.id]; + pj_grp_lock_dec_ref(tsx->grp_lock); - /* Dlg may be NULL on some extreme condition - * (e.g. during debugging where initially there is a dialog) - */ - return dlg ? (struct dlg_set*) dlg->dlg_set : NULL; + /* Dlg may be NULL on some extreme condition + * (e.g. during debugging where initially there is a dialog) + */ + return dlg ? (struct dlg_set*) dlg->dlg_set : NULL; - } else { - return NULL; - } + } else { + return NULL; + } } else { - pj_str_t *tag; - struct dlg_set *dlg_set; - - if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) - tag = &rdata->msg_info.to->tag; - else - tag = &rdata->msg_info.from->tag; - - /* Lookup the dialog set. */ - dlg_set = (struct dlg_set*) - pj_hash_get_lower(mod_ua.dlg_table, tag->ptr, - (unsigned)tag->slen, NULL); - return dlg_set; + pj_str_t *tag; + struct dlg_set *dlg_set; + + if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) + tag = &rdata->msg_info.to->tag; + else + tag = &rdata->msg_info.from->tag; + + /* Lookup the dialog set. */ + dlg_set = (struct dlg_set*) + pj_hash_get_lower(mod_ua.dlg_table, tag->ptr, + (unsigned)tag->slen, NULL); + return dlg_set; } } @@ -639,14 +638,14 @@ static pj_bool_t mod_ua_on_rx_request(pjsip_rx_data *rdata) * have To tag */ if (rdata->msg_info.to->tag.slen == 0 && - rdata->msg_info.msg->line.req.method.id != PJSIP_CANCEL_METHOD) + rdata->msg_info.msg->line.req.method.id != PJSIP_CANCEL_METHOD) { - return PJ_FALSE; + return PJ_FALSE; } /* Incoming REGISTER may have tags in it */ if (rdata->msg_info.msg->line.req.method.id == PJSIP_REGISTER_METHOD) - return PJ_FALSE; + return PJ_FALSE; retry_on_deadlock: @@ -660,19 +659,19 @@ static pj_bool_t mod_ua_on_rx_request(pjsip_rx_data *rdata) * Does Not Exist). */ if (dlg_set == NULL) { - /* Unable to find dialog. */ - pj_mutex_unlock(mod_ua.mutex); - - if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { - PJ_LOG(5,(THIS_FILE, - "Unable to find dialogset for %s, answering with 481", - pjsip_rx_data_get_info(rdata))); - - /* Respond with 481 . */ - pjsip_endpt_respond_stateless( mod_ua.endpt, rdata, 481, NULL, - NULL, NULL ); - } - return PJ_TRUE; + /* Unable to find dialog. */ + pj_mutex_unlock(mod_ua.mutex); + + if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { + PJ_LOG(5,(THIS_FILE, + "Unable to find dialogset for %s, answering with 481", + pjsip_rx_data_get_info(rdata))); + + /* Respond with 481 . */ + pjsip_endpt_respond_stateless( mod_ua.endpt, rdata, 481, NULL, + NULL, NULL ); + } + return PJ_TRUE; } /* Dialog set has been found. @@ -682,15 +681,15 @@ static pj_bool_t mod_ua_on_rx_request(pjsip_rx_data *rdata) from_tag = &rdata->msg_info.from->tag; dlg = dlg_set->dlg_list.next; while (dlg != (pjsip_dialog*)&dlg_set->dlg_list) { - - if (pj_stricmp(&dlg->remote.info->tag, from_tag) == 0) - break; + + if (pj_stricmp(&dlg->remote.info->tag, from_tag) == 0) + break; - dlg = dlg->next; + dlg = dlg->next; } /* Dialog may not be found, e.g. in this case: - * - UAC sends SUBSCRIBE, then UAS sends NOTIFY before answering + * - UAC sends SUBSCRIBE, then UAS sends NOTIFY before answering * SUBSCRIBE request with 2xx. * * In this case, we can accept the request ONLY when the original @@ -698,29 +697,29 @@ static pj_bool_t mod_ua_on_rx_request(pjsip_rx_data *rdata) */ if (dlg == (pjsip_dialog*)&dlg_set->dlg_list) { - pjsip_dialog *first_dlg = dlg_set->dlg_list.next; - - if (first_dlg->remote.info->tag.slen != 0) { - /* Not found. Mulfunction UAC? */ - pj_mutex_unlock(mod_ua.mutex); - - if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { - PJ_LOG(5,(THIS_FILE, - "Unable to find dialog for %s, answering with 481", - pjsip_rx_data_get_info(rdata))); - - pjsip_endpt_respond_stateless(mod_ua.endpt, rdata, - PJSIP_SC_CALL_TSX_DOES_NOT_EXIST, - NULL, NULL, NULL); - } else { - PJ_LOG(5,(THIS_FILE, - "Unable to find dialog for %s", - pjsip_rx_data_get_info(rdata))); - } - return PJ_TRUE; - } - - dlg = first_dlg; + pjsip_dialog *first_dlg = dlg_set->dlg_list.next; + + if (first_dlg->remote.info->tag.slen != 0) { + /* Not found. Mulfunction UAC? */ + pj_mutex_unlock(mod_ua.mutex); + + if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { + PJ_LOG(5,(THIS_FILE, + "Unable to find dialog for %s, answering with 481", + pjsip_rx_data_get_info(rdata))); + + pjsip_endpt_respond_stateless(mod_ua.endpt, rdata, + PJSIP_SC_CALL_TSX_DOES_NOT_EXIST, + NULL, NULL, NULL); + } else { + PJ_LOG(5,(THIS_FILE, + "Unable to find dialog for %s", + pjsip_rx_data_get_info(rdata))); + } + return PJ_TRUE; + } + + dlg = first_dlg; } /* Mark the dialog id of the request. */ @@ -730,13 +729,13 @@ static pj_bool_t mod_ua_on_rx_request(pjsip_rx_data *rdata) PJ_LOG(6,(dlg->obj_name, "UA layer acquiring dialog lock for request")); status = pjsip_dlg_try_inc_lock(dlg); if (status != PJ_SUCCESS) { - /* Failed to acquire dialog mutex immediately, this could be - * because of deadlock. Release UA mutex, yield, and retry - * the whole thing once again. - */ - pj_mutex_unlock(mod_ua.mutex); - pj_thread_sleep(0); - goto retry_on_deadlock; + /* Failed to acquire dialog mutex immediately, this could be + * because of deadlock. Release UA mutex, yield, and retry + * the whole thing once again. + */ + pj_mutex_unlock(mod_ua.mutex); + pj_thread_sleep(0); + goto retry_on_deadlock; } /* Done with processing in UA layer, release lock */ @@ -782,62 +781,62 @@ static pj_bool_t mod_ua_on_rx_response(pjsip_rx_data *rdata) /* Check if transaction is present. */ tsx = pjsip_rdata_get_tsx(rdata); if (tsx) { - /* Check if dialog is present in the transaction. */ - dlg = pjsip_tsx_get_dlg(tsx); - if (!dlg) { - /* Unlock dialog hash table. */ - pj_mutex_unlock(mod_ua.mutex); - return PJ_FALSE; - } + /* Check if dialog is present in the transaction. */ + dlg = pjsip_tsx_get_dlg(tsx); + if (!dlg) { + /* Unlock dialog hash table. */ + pj_mutex_unlock(mod_ua.mutex); + return PJ_FALSE; + } - /* Get the dialog set. */ - dlg_set = (struct dlg_set*) dlg->dlg_set; + /* Get the dialog set. */ + dlg_set = (struct dlg_set*) dlg->dlg_set; - /* Even if transaction is found and (candidate) dialog has been - * identified, it's possible that the request has forked. - */ + /* Even if transaction is found and (candidate) dialog has been + * identified, it's possible that the request has forked. + */ } else { - /* Transaction is not present. - * Check if this is a 2xx/OK response to INVITE, which in this - * case the response will be handled directly by the - * dialog. - */ - pjsip_cseq_hdr *cseq_hdr = rdata->msg_info.cseq; - - if (cseq_hdr->method.id != PJSIP_INVITE_METHOD || - rdata->msg_info.msg->line.status.code / 100 != 2) - { - /* Not a 2xx response to INVITE. - * This must be some stateless response sent by other modules, - * or a very late response. - */ - /* Unlock dialog hash table. */ - pj_mutex_unlock(mod_ua.mutex); - return PJ_FALSE; - } - - - /* Get the dialog set. */ - dlg_set = (struct dlg_set*) - pj_hash_get_lower(mod_ua.dlg_table, - rdata->msg_info.from->tag.ptr, - (unsigned)rdata->msg_info.from->tag.slen, - NULL); - - if (!dlg_set) { - /* Unlock dialog hash table. */ - pj_mutex_unlock(mod_ua.mutex); - - /* Strayed 2xx response!! */ - PJ_LOG(4,(THIS_FILE, - "Received strayed 2xx response (no dialog is found)" - " from %s:%d: %s", - rdata->pkt_info.src_name, rdata->pkt_info.src_port, - pjsip_rx_data_get_info(rdata))); - - return PJ_TRUE; - } + /* Transaction is not present. + * Check if this is a 2xx/OK response to INVITE, which in this + * case the response will be handled directly by the + * dialog. + */ + pjsip_cseq_hdr *cseq_hdr = rdata->msg_info.cseq; + + if (cseq_hdr->method.id != PJSIP_INVITE_METHOD || + rdata->msg_info.msg->line.status.code / 100 != 2) + { + /* Not a 2xx response to INVITE. + * This must be some stateless response sent by other modules, + * or a very late response. + */ + /* Unlock dialog hash table. */ + pj_mutex_unlock(mod_ua.mutex); + return PJ_FALSE; + } + + + /* Get the dialog set. */ + dlg_set = (struct dlg_set*) + pj_hash_get_lower(mod_ua.dlg_table, + rdata->msg_info.from->tag.ptr, + (unsigned)rdata->msg_info.from->tag.slen, + NULL); + + if (!dlg_set) { + /* Unlock dialog hash table. */ + pj_mutex_unlock(mod_ua.mutex); + + /* Strayed 2xx response!! */ + PJ_LOG(4,(THIS_FILE, + "Received strayed 2xx response (no dialog is found)" + " from %s:%d: %s", + rdata->pkt_info.src_name, rdata->pkt_info.src_port, + pjsip_rx_data_get_info(rdata))); + + return PJ_TRUE; + } } /* At this point, we must have the dialog set, and the dialog set @@ -852,81 +851,81 @@ static pj_bool_t mod_ua_on_rx_response(pjsip_rx_data *rdata) //This doesn't work when there is authentication challenge, since //first_cseq evaluation will yield false. //if (rdata->msg_info.cseq->method.id == PJSIP_INVITE_METHOD && - // rdata->msg_info.cseq->cseq == dlg_set->dlg_list.next->local.first_cseq) + // rdata->msg_info.cseq->cseq == dlg_set->dlg_list.next->local.first_cseq) if (rdata->msg_info.cseq->method.id == PJSIP_INVITE_METHOD) { - - int st_code = rdata->msg_info.msg->line.status.code; - pj_str_t *to_tag = &rdata->msg_info.to->tag; - - dlg = dlg_set->dlg_list.next; - - while (dlg != (pjsip_dialog*)&dlg_set->dlg_list) { - - /* If there is dialog with no remote tag (i.e. dialog has not - * been established yet), then send this response to that - * dialog. - */ - if (dlg->remote.info->tag.slen == 0) - break; - - /* Otherwise find the one with matching To tag. */ - if (pj_stricmp(to_tag, &dlg->remote.info->tag) == 0) - break; - - dlg = dlg->next; - } - - /* If no dialog with matching remote tag is found, this must be - * a forked response. Respond to this ONLY when response is non-100 - * provisional response OR a 2xx response. - */ - if (dlg == (pjsip_dialog*)&dlg_set->dlg_list && - ((st_code/100==1 && st_code!=100) || st_code/100==2)) - { - - PJ_LOG(5,(THIS_FILE, - "Received forked %s for existing dialog %s", - pjsip_rx_data_get_info(rdata), - dlg_set->dlg_list.next->obj_name)); - - /* Report to application about forked condition. - * Application can either create a dialog or ignore the response. - */ - if (mod_ua.param.on_dlg_forked) { - dlg = (*mod_ua.param.on_dlg_forked)(dlg_set->dlg_list.next, - rdata); - if (dlg == NULL) { - pj_mutex_unlock(mod_ua.mutex); - return PJ_TRUE; - } - } else { - dlg = dlg_set->dlg_list.next; - - PJ_LOG(4,(THIS_FILE, - "Unhandled forked %s from %s:%d, response will be " - "handed over to the first dialog", - pjsip_rx_data_get_info(rdata), - rdata->pkt_info.src_name, rdata->pkt_info.src_port)); - } - - } else if (dlg == (pjsip_dialog*)&dlg_set->dlg_list) { - - /* For 100 or non-2xx response which has different To tag, - * pass the response to the first dialog. - */ - - dlg = dlg_set->dlg_list.next; - - } + + int st_code = rdata->msg_info.msg->line.status.code; + pj_str_t *to_tag = &rdata->msg_info.to->tag; + + dlg = dlg_set->dlg_list.next; + + while (dlg != (pjsip_dialog*)&dlg_set->dlg_list) { + + /* If there is dialog with no remote tag (i.e. dialog has not + * been established yet), then send this response to that + * dialog. + */ + if (dlg->remote.info->tag.slen == 0) + break; + + /* Otherwise find the one with matching To tag. */ + if (pj_stricmp(to_tag, &dlg->remote.info->tag) == 0) + break; + + dlg = dlg->next; + } + + /* If no dialog with matching remote tag is found, this must be + * a forked response. Respond to this ONLY when response is non-100 + * provisional response OR a 2xx response. + */ + if (dlg == (pjsip_dialog*)&dlg_set->dlg_list && + ((st_code/100==1 && st_code!=100) || st_code/100==2)) + { + + PJ_LOG(5,(THIS_FILE, + "Received forked %s for existing dialog %s", + pjsip_rx_data_get_info(rdata), + dlg_set->dlg_list.next->obj_name)); + + /* Report to application about forked condition. + * Application can either create a dialog or ignore the response. + */ + if (mod_ua.param.on_dlg_forked) { + dlg = (*mod_ua.param.on_dlg_forked)(dlg_set->dlg_list.next, + rdata); + if (dlg == NULL) { + pj_mutex_unlock(mod_ua.mutex); + return PJ_TRUE; + } + } else { + dlg = dlg_set->dlg_list.next; + + PJ_LOG(4,(THIS_FILE, + "Unhandled forked %s from %s:%d, response will be " + "handed over to the first dialog", + pjsip_rx_data_get_info(rdata), + rdata->pkt_info.src_name, rdata->pkt_info.src_port)); + } + + } else if (dlg == (pjsip_dialog*)&dlg_set->dlg_list) { + + /* For 100 or non-2xx response which has different To tag, + * pass the response to the first dialog. + */ + + dlg = dlg_set->dlg_list.next; + + } } else { - /* Either this is a non-INVITE response, or subsequent INVITE - * within dialog. The dialog should have been identified when - * the transaction was found. - */ - pj_assert(tsx != NULL); - pj_assert(dlg != NULL); + /* Either this is a non-INVITE response, or subsequent INVITE + * within dialog. The dialog should have been identified when + * the transaction was found. + */ + pj_assert(tsx != NULL); + pj_assert(dlg != NULL); } /* The dialog must have been found. */ @@ -939,13 +938,13 @@ static pj_bool_t mod_ua_on_rx_response(pjsip_rx_data *rdata) PJ_LOG(6,(dlg->obj_name, "UA layer acquiring dialog lock for response")); status = pjsip_dlg_try_inc_lock(dlg); if (status != PJ_SUCCESS) { - /* Failed to acquire dialog mutex. This could indicate a deadlock - * situation, and for safety, try to avoid deadlock by releasing - * UA mutex, yield, and retry the whole processing once again. - */ - pj_mutex_unlock(mod_ua.mutex); - pj_thread_sleep(0); - goto retry_on_deadlock; + /* Failed to acquire dialog mutex. This could indicate a deadlock + * situation, and for safety, try to avoid deadlock by releasing + * UA mutex, yield, and retry the whole processing once again. + */ + pj_mutex_unlock(mod_ua.mutex); + pj_thread_sleep(0); + goto retry_on_deadlock; } /* We're done with processing in the UA layer, we can release the mutex */ @@ -964,26 +963,26 @@ static pj_bool_t mod_ua_on_rx_response(pjsip_rx_data *rdata) #if PJ_LOG_MAX_LEVEL >= 3 static void print_dialog( const char *title, - pjsip_dialog *dlg, char *buf, pj_size_t size) + pjsip_dialog *dlg, char *buf, pj_size_t size) { int len; char userinfo[PJSIP_MAX_URL_SIZE]; len = pjsip_hdr_print_on(dlg->remote.info, userinfo, sizeof(userinfo)); if (len < 0) - pj_ansi_strcpy(userinfo, "<--uri too long-->"); + pj_ansi_strcpy(userinfo, "<--uri too long-->"); else - userinfo[len] = '\0'; + userinfo[len] = '\0'; len = pj_ansi_snprintf(buf, size, "%s[%s] %s", - title, - (dlg->state==PJSIP_DIALOG_STATE_NULL ? " - " : - "est"), - userinfo); + title, + (dlg->state==PJSIP_DIALOG_STATE_NULL ? " - " : + "est"), + userinfo); if (len < 1 || len >= (int)size) { - pj_ansi_strcpy(buf, "<--uri too long-->"); + pj_ansi_strcpy(buf, "<--uri too long-->"); } else - buf[len] = '\0'; + buf[len] = '\0'; } #endif @@ -999,36 +998,36 @@ PJ_DEF(void) pjsip_ua_dump(pj_bool_t detail) pj_mutex_lock(mod_ua.mutex); PJ_LOG(3, (THIS_FILE, "Number of dialog sets: %u", - pj_hash_count(mod_ua.dlg_table))); + pj_hash_count(mod_ua.dlg_table))); if (detail && pj_hash_count(mod_ua.dlg_table)) { - PJ_LOG(3, (THIS_FILE, "Dumping dialog sets:")); - it = pj_hash_first(mod_ua.dlg_table, &itbuf); - for (; it != NULL; it = pj_hash_next(mod_ua.dlg_table, it)) { - struct dlg_set *dlg_set; - pjsip_dialog *dlg; - const char *title; - - dlg_set = (struct dlg_set*) pj_hash_this(mod_ua.dlg_table, it); - if (!dlg_set || pj_list_empty(&dlg_set->dlg_list)) continue; - - /* First dialog in dialog set. */ - dlg = dlg_set->dlg_list.next; - if (dlg->role == PJSIP_ROLE_UAC) - title = " [out] "; - else - title = " [in] "; - - print_dialog(title, dlg, dlginfo, sizeof(dlginfo)); - PJ_LOG(3,(THIS_FILE, "%s", dlginfo)); - - /* Next dialog in dialog set (forked) */ - dlg = dlg->next; - while (dlg != (pjsip_dialog*) &dlg_set->dlg_list) { - print_dialog(" [forked] ", dlg, dlginfo, sizeof(dlginfo)); - dlg = dlg->next; - } - } + PJ_LOG(3, (THIS_FILE, "Dumping dialog sets:")); + it = pj_hash_first(mod_ua.dlg_table, &itbuf); + for (; it != NULL; it = pj_hash_next(mod_ua.dlg_table, it)) { + struct dlg_set *dlg_set; + pjsip_dialog *dlg; + const char *title; + + dlg_set = (struct dlg_set*) pj_hash_this(mod_ua.dlg_table, it); + if (!dlg_set || pj_list_empty(&dlg_set->dlg_list)) continue; + + /* First dialog in dialog set. */ + dlg = dlg_set->dlg_list.next; + if (dlg->role == PJSIP_ROLE_UAC) + title = " [out] "; + else + title = " [in] "; + + print_dialog(title, dlg, dlginfo, sizeof(dlginfo)); + PJ_LOG(3,(THIS_FILE, "%s", dlginfo)); + + /* Next dialog in dialog set (forked) */ + dlg = dlg->next; + while (dlg != (pjsip_dialog*) &dlg_set->dlg_list) { + print_dialog(" [forked] ", dlg, dlginfo, sizeof(dlginfo)); + dlg = dlg->next; + } + } } pj_mutex_unlock(mod_ua.mutex); diff --git a/pjsip/src/pjsip/sip_uri.c b/pjsip/src/pjsip/sip_uri.c index f5592cf059..f823d12bd4 100644 --- a/pjsip/src/pjsip/sip_uri.c +++ b/pjsip/src/pjsip/sip_uri.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,80 +30,80 @@ * Generic parameter manipulation. */ PJ_DEF(pjsip_param*) pjsip_param_find( const pjsip_param *param_list, - const pj_str_t *name ) + const pj_str_t *name ) { pjsip_param *p = (pjsip_param*)param_list->next; while (p != param_list) { - if (pj_stricmp(&p->name, name)==0) - return p; - p = p->next; + if (pj_stricmp(&p->name, name)==0) + return p; + p = p->next; } return NULL; } PJ_DEF(int) pjsip_param_cmp( const pjsip_param *param_list1, - const pjsip_param *param_list2, - pj_bool_t ig_nf) + const pjsip_param *param_list2, + pj_bool_t ig_nf) { const pjsip_param *p1; if ((ig_nf & 1)==0 && pj_list_size(param_list1)!=pj_list_size(param_list2)) - return 1; + return 1; p1 = param_list1->next; while (p1 != param_list1) { - const pjsip_param *p2; - p2 = pjsip_param_find(param_list2, &p1->name); - if (p2 ) { - int rc = pj_stricmp(&p1->value, &p2->value); - if (rc != 0) - return rc; - } else if ((ig_nf & 1)==0) - return 1; - - p1 = p1->next; + const pjsip_param *p2; + p2 = pjsip_param_find(param_list2, &p1->name); + if (p2 ) { + int rc = pj_stricmp(&p1->value, &p2->value); + if (rc != 0) + return rc; + } else if ((ig_nf & 1)==0) + return 1; + + p1 = p1->next; } return 0; } PJ_DEF(void) pjsip_param_clone( pj_pool_t *pool, pjsip_param *dst_list, - const pjsip_param *src_list) + const pjsip_param *src_list) { const pjsip_param *p = src_list->next; pj_list_init(dst_list); while (p && p != src_list) { - pjsip_param *new_param = PJ_POOL_ALLOC_T(pool, pjsip_param); - pj_strdup(pool, &new_param->name, &p->name); - pj_strdup(pool, &new_param->value, &p->value); - pj_list_insert_before(dst_list, new_param); - p = p->next; + pjsip_param *new_param = PJ_POOL_ALLOC_T(pool, pjsip_param); + pj_strdup(pool, &new_param->name, &p->name); + pj_strdup(pool, &new_param->value, &p->value); + pj_list_insert_before(dst_list, new_param); + p = p->next; } } PJ_DEF(void) pjsip_param_shallow_clone( pj_pool_t *pool, - pjsip_param *dst_list, - const pjsip_param *src_list) + pjsip_param *dst_list, + const pjsip_param *src_list) { const pjsip_param *p = src_list->next; pj_list_init(dst_list); while (p != src_list) { - pjsip_param *new_param = PJ_POOL_ALLOC_T(pool, pjsip_param); - new_param->name = p->name; - new_param->value = p->value; - pj_list_insert_before(dst_list, new_param); - p = p->next; + pjsip_param *new_param = PJ_POOL_ALLOC_T(pool, pjsip_param); + new_param->name = p->name; + new_param->value = p->value; + pj_list_insert_before(dst_list, new_param); + p = p->next; } } PJ_DEF(pj_ssize_t) pjsip_param_print_on( const pjsip_param *param_list, - char *buf, pj_size_t size, - const pj_cis_t *pname_spec, - const pj_cis_t *pvalue_spec, - int sep) + char *buf, pj_size_t size, + const pj_cis_t *pname_spec, + const pj_cis_t *pvalue_spec, + int sep) { const pjsip_param *p; char *startbuf; @@ -113,7 +112,7 @@ PJ_DEF(pj_ssize_t) pjsip_param_print_on( const pjsip_param *param_list, p = param_list->next; if (p == NULL || p == param_list) - return 0; + return 0; startbuf = buf; endbuf = buf + size; @@ -121,17 +120,17 @@ PJ_DEF(pj_ssize_t) pjsip_param_print_on( const pjsip_param *param_list, PJ_UNUSED_ARG(pname_spec); do { - copy_advance_char_check(buf, (char)sep); - copy_advance_escape(buf, p->name, (*pname_spec)); - if (p->value.slen) { - copy_advance_char_check(buf, '='); - if (*p->value.ptr == '"') - copy_advance(buf, p->value); - else - copy_advance_escape(buf, p->value, (*pvalue_spec)); - } - p = p->next; - if (sep == '?') sep = '&'; + copy_advance_char_check(buf, (char)sep); + copy_advance_escape(buf, p->name, (*pname_spec)); + if (p->value.slen) { + copy_advance_char_check(buf, '='); + if (*p->value.ptr == '"') + copy_advance(buf, p->value); + else + copy_advance_escape(buf, p->value, (*pvalue_spec)); + } + p = p->next; + if (sep == '?') sep = '&'; } while (p != param_list); return buf-startbuf; @@ -141,7 +140,7 @@ PJ_DEF(pj_ssize_t) pjsip_param_print_on( const pjsip_param *param_list, /* * URI stuffs */ -#define IS_SIPS(url) ((url)->vptr==&sips_url_vptr) +#define IS_SIPS(url) ((url)->vptr==&sips_url_vptr) static const pj_str_t *pjsip_url_get_scheme( const pjsip_sip_uri* ); static const pj_str_t *pjsips_url_get_scheme( const pjsip_sip_uri* ); @@ -153,56 +152,56 @@ static pj_str_t sip_str = { "sip", 3 }; static pj_str_t sips_str = { "sips", 4 }; static pjsip_name_addr* pjsip_name_addr_clone( pj_pool_t *pool, - const pjsip_name_addr *rhs); + const pjsip_name_addr *rhs); static pj_ssize_t pjsip_name_addr_print(pjsip_uri_context_e context, - const pjsip_name_addr *name, - char *buf, pj_size_t size); + const pjsip_name_addr *name, + char *buf, pj_size_t size); static int pjsip_name_addr_compare( pjsip_uri_context_e context, - const pjsip_name_addr *naddr1, - const pjsip_name_addr *naddr2); + const pjsip_name_addr *naddr1, + const pjsip_name_addr *naddr2); static pj_ssize_t pjsip_url_print( pjsip_uri_context_e context, - const pjsip_sip_uri *url, - char *buf, pj_size_t size); + const pjsip_sip_uri *url, + char *buf, pj_size_t size); static int pjsip_url_compare( pjsip_uri_context_e context, - const pjsip_sip_uri *url1, - const pjsip_sip_uri *url2); + const pjsip_sip_uri *url1, + const pjsip_sip_uri *url2); static pjsip_sip_uri* pjsip_url_clone(pj_pool_t *pool, - const pjsip_sip_uri *rhs); + const pjsip_sip_uri *rhs); typedef const pj_str_t* (*P_GET_SCHEME)(const void*); -typedef void* (*P_GET_URI)(void*); -typedef pj_ssize_t (*P_PRINT_URI)(pjsip_uri_context_e,const void *, - char*,pj_size_t); -typedef int (*P_CMP_URI)(pjsip_uri_context_e, const void*, - const void*); -typedef void* (*P_CLONE)(pj_pool_t*, const void*); +typedef void* (*P_GET_URI)(void*); +typedef pj_ssize_t (*P_PRINT_URI)(pjsip_uri_context_e,const void *, + char*,pj_size_t); +typedef int (*P_CMP_URI)(pjsip_uri_context_e, const void*, + const void*); +typedef void* (*P_CLONE)(pj_pool_t*, const void*); static pjsip_uri_vptr sip_url_vptr = { - (P_GET_SCHEME) &pjsip_url_get_scheme, - (P_GET_URI) &pjsip_get_uri, - (P_PRINT_URI) &pjsip_url_print, - (P_CMP_URI) &pjsip_url_compare, - (P_CLONE) &pjsip_url_clone + (P_GET_SCHEME) &pjsip_url_get_scheme, + (P_GET_URI) &pjsip_get_uri, + (P_PRINT_URI) &pjsip_url_print, + (P_CMP_URI) &pjsip_url_compare, + (P_CLONE) &pjsip_url_clone }; static pjsip_uri_vptr sips_url_vptr = { - (P_GET_SCHEME) &pjsips_url_get_scheme, - (P_GET_URI) &pjsip_get_uri, - (P_PRINT_URI) &pjsip_url_print, - (P_CMP_URI) &pjsip_url_compare, - (P_CLONE) &pjsip_url_clone + (P_GET_SCHEME) &pjsips_url_get_scheme, + (P_GET_URI) &pjsip_get_uri, + (P_PRINT_URI) &pjsip_url_print, + (P_CMP_URI) &pjsip_url_compare, + (P_CLONE) &pjsip_url_clone }; static pjsip_uri_vptr name_addr_vptr = { - (P_GET_SCHEME) &pjsip_name_addr_get_scheme, - (P_GET_URI) &pjsip_name_addr_get_uri, - (P_PRINT_URI) &pjsip_name_addr_print, - (P_CMP_URI) &pjsip_name_addr_compare, - (P_CLONE) &pjsip_name_addr_clone + (P_GET_SCHEME) &pjsip_name_addr_get_scheme, + (P_GET_URI) &pjsip_name_addr_get_uri, + (P_PRINT_URI) &pjsip_name_addr_print, + (P_CMP_URI) &pjsip_name_addr_compare, + (P_CLONE) &pjsip_name_addr_clone }; static const pj_str_t *pjsip_url_get_scheme(const pjsip_sip_uri *url) @@ -228,7 +227,7 @@ static void *pjsip_name_addr_get_uri( pjsip_name_addr *name ) } PJ_DEF(void) pjsip_sip_uri_set_secure( pjsip_sip_uri *url, - pj_bool_t secure ) + pj_bool_t secure ) { url->vptr = secure ? &sips_url_vptr : &sip_url_vptr; } @@ -243,7 +242,7 @@ PJ_DEF(void) pjsip_sip_uri_init(pjsip_sip_uri *url, pj_bool_t secure) } PJ_DEF(pjsip_sip_uri*) pjsip_sip_uri_create( pj_pool_t *pool, - pj_bool_t secure ) + pj_bool_t secure ) { pjsip_sip_uri *url = PJ_POOL_ALLOC_T(pool, pjsip_sip_uri); pjsip_sip_uri_init(url, secure); @@ -251,8 +250,8 @@ PJ_DEF(pjsip_sip_uri*) pjsip_sip_uri_create( pj_pool_t *pool, } static pj_ssize_t pjsip_url_print( pjsip_uri_context_e context, - const pjsip_sip_uri *url, - char *buf, pj_size_t size) + const pjsip_sip_uri *url, + char *buf, pj_size_t size) { int printed; char *startbuf = buf; @@ -270,25 +269,25 @@ static pj_ssize_t pjsip_url_print( pjsip_uri_context_e context, /* Print "user:password@", if any. */ if (url->user.slen) { - const pj_cis_t *spec = pjsip_cfg()->endpt.allow_tx_hash_in_uri ? - &pc->pjsip_USER_SPEC_LENIENT : - &pc->pjsip_USER_SPEC; - copy_advance_escape(buf, url->user, *spec); - if (url->passwd.slen) { - copy_advance_char_check(buf, ':'); - copy_advance_escape(buf, url->passwd, pc->pjsip_PASSWD_SPEC); - } - - copy_advance_char_check(buf, '@'); + const pj_cis_t *spec = pjsip_cfg()->endpt.allow_tx_hash_in_uri ? + &pc->pjsip_USER_SPEC_LENIENT : + &pc->pjsip_USER_SPEC; + copy_advance_escape(buf, url->user, *spec); + if (url->passwd.slen) { + copy_advance_char_check(buf, ':'); + copy_advance_escape(buf, url->passwd, pc->pjsip_PASSWD_SPEC); + } + + copy_advance_char_check(buf, '@'); } /* Print host. */ pj_assert(url->host.slen != 0); /* Detect IPv6 IP address */ if (pj_memchr(url->host.ptr, ':', url->host.slen)) { - copy_advance_pair_quote_cond(buf, "", 0, url->host, '[', ']'); + copy_advance_pair_quote_cond(buf, "", 0, url->host, '[', ']'); } else { - copy_advance_check(buf, url->host); + copy_advance_check(buf, url->host); } /* Only print port if it is explicitly specified. @@ -299,15 +298,15 @@ static pj_ssize_t pjsip_url_print( pjsip_uri_context_e context, * appear in From/To header. Default is still false. */ if (url->port && - (context != PJSIP_URI_IN_FROMTO_HDR || - pjsip_cfg()->endpt.allow_port_in_fromto_hdr)) + (context != PJSIP_URI_IN_FROMTO_HDR || + pjsip_cfg()->endpt.allow_port_in_fromto_hdr)) { - if (endbuf - buf < 10) - return -1; + if (endbuf - buf < 10) + return -1; - copy_advance_char_check(buf, ':'); - printed = pj_utoa(url->port, buf); - buf += printed; + copy_advance_char_check(buf, ':'); + printed = pj_utoa(url->port, buf); + buf += printed; } /* User param is allowed in all contexes */ @@ -315,69 +314,69 @@ static pj_ssize_t pjsip_url_print( pjsip_uri_context_e context, /* Method param is only allowed in external/other context. */ if (context == PJSIP_URI_IN_OTHER) { - copy_advance_pair_escape(buf, ";method=", 8, url->method_param, - pc->pjsip_PARAM_CHAR_SPEC); + copy_advance_pair_escape(buf, ";method=", 8, url->method_param, + pc->pjsip_PARAM_CHAR_SPEC); } /* Transport is not allowed in From/To header. */ if (context != PJSIP_URI_IN_FROMTO_HDR) { - copy_advance_pair_escape(buf, ";transport=", 11, url->transport_param, - pc->pjsip_PARAM_CHAR_SPEC); + copy_advance_pair_escape(buf, ";transport=", 11, url->transport_param, + pc->pjsip_PARAM_CHAR_SPEC); } /* TTL param is not allowed in From, To, Route, and Record-Route header. */ if (url->ttl_param >= 0 && context != PJSIP_URI_IN_FROMTO_HDR && - context != PJSIP_URI_IN_ROUTING_HDR) + context != PJSIP_URI_IN_ROUTING_HDR) { - if (endbuf - buf < 15) - return -1; - pj_memcpy(buf, ";ttl=", 5); - printed = pj_utoa(url->ttl_param, buf+5); - buf += printed + 5; + if (endbuf - buf < 15) + return -1; + pj_memcpy(buf, ";ttl=", 5); + printed = pj_utoa(url->ttl_param, buf+5); + buf += printed + 5; } /* maddr param is not allowed in From and To header. */ if (context != PJSIP_URI_IN_FROMTO_HDR && url->maddr_param.slen) { - /* Detect IPv6 IP address */ - if (pj_memchr(url->maddr_param.ptr, ':', url->maddr_param.slen)) { - copy_advance_pair_quote_cond(buf, ";maddr=", 7, url->maddr_param, - '[', ']'); - } else { - copy_advance_pair_escape(buf, ";maddr=", 7, url->maddr_param, - pc->pjsip_PARAM_CHAR_SPEC); - } + /* Detect IPv6 IP address */ + if (pj_memchr(url->maddr_param.ptr, ':', url->maddr_param.slen)) { + copy_advance_pair_quote_cond(buf, ";maddr=", 7, url->maddr_param, + '[', ']'); + } else { + copy_advance_pair_escape(buf, ";maddr=", 7, url->maddr_param, + pc->pjsip_PARAM_CHAR_SPEC); + } } /* lr param is not allowed in From, To, and Contact header. */ if (url->lr_param && context != PJSIP_URI_IN_FROMTO_HDR && - context != PJSIP_URI_IN_CONTACT_HDR) + context != PJSIP_URI_IN_CONTACT_HDR) { - pj_str_t lr = { ";lr", 3 }; - if (endbuf - buf < 3) - return -1; - copy_advance_check(buf, lr); + pj_str_t lr = { ";lr", 3 }; + if (endbuf - buf < 3) + return -1; + copy_advance_check(buf, lr); } /* Other param. */ printed = (int)pjsip_param_print_on(&url->other_param, buf, endbuf-buf, - &pc->pjsip_PARAM_CHAR_SPEC, - &pc->pjsip_PARAM_CHAR_SPEC, ';'); + &pc->pjsip_PARAM_CHAR_SPEC, + &pc->pjsip_PARAM_CHAR_SPEC, ';'); if (printed < 0) - return -1; + return -1; buf += printed; /* Header param. * Header param is only allowed in these contexts: - * - PJSIP_URI_IN_CONTACT_HDR - * - PJSIP_URI_IN_OTHER + * - PJSIP_URI_IN_CONTACT_HDR + * - PJSIP_URI_IN_OTHER */ if (context == PJSIP_URI_IN_CONTACT_HDR || context == PJSIP_URI_IN_OTHER) { - printed = (int)pjsip_param_print_on(&url->header_param, buf, endbuf-buf, - &pc->pjsip_HDR_CHAR_SPEC, - &pc->pjsip_HDR_CHAR_SPEC, '?'); - if (printed < 0) - return -1; - buf += printed; + printed = (int)pjsip_param_print_on(&url->header_param, buf, endbuf-buf, + &pc->pjsip_HDR_CHAR_SPEC, + &pc->pjsip_HDR_CHAR_SPEC, '?'); + if (printed < 0) + return -1; + buf += printed; } *buf = '\0'; @@ -385,8 +384,8 @@ static pj_ssize_t pjsip_url_print( pjsip_uri_context_e context, } static pj_status_t pjsip_url_compare( pjsip_uri_context_e context, - const pjsip_sip_uri *url1, - const pjsip_sip_uri *url2) + const pjsip_sip_uri *url1, + const pjsip_sip_uri *url2) { const pjsip_param *p1; @@ -399,16 +398,16 @@ static pj_status_t pjsip_url_compare( pjsip_uri_context_e context, * Pretty neat huh!! */ if (url1->vptr != url2->vptr) - return PJSIP_ECMPSCHEME; + return PJSIP_ECMPSCHEME; /* Comparison of the userinfo of SIP and SIPS URIs is case-sensitive. * This includes userinfo containing passwords or formatted as * telephone-subscribers. */ if (pj_strcmp(&url1->user, &url2->user) != 0) - return PJSIP_ECMPUSER; + return PJSIP_ECMPUSER; if (pj_strcmp(&url1->passwd, &url2->passwd) != 0) - return PJSIP_ECMPPASSWD; + return PJSIP_ECMPPASSWD; /* Comparison of all other components of the URI is * case-insensitive unless explicitly defined otherwise. @@ -426,7 +425,7 @@ static pj_status_t pjsip_url_compare( pjsip_uri_context_e context, * does not match that host name. */ if (pj_stricmp(&url1->host, &url2->host) != 0) - return PJSIP_ECMPHOST; + return PJSIP_ECMPHOST; /* A URI omitting any component with a default value will not match a URI * explicitly containing that component with its default value. @@ -439,33 +438,33 @@ static pj_status_t pjsip_url_compare( pjsip_uri_context_e context, /* Port is not allowed in To and From header. */ if (context != PJSIP_URI_IN_FROMTO_HDR) { - if (url1->port != url2->port) - return PJSIP_ECMPPORT; + if (url1->port != url2->port) + return PJSIP_ECMPPORT; } /* Transport is not allowed in From/To header. */ if (context != PJSIP_URI_IN_FROMTO_HDR) { - if (pj_stricmp(&url1->transport_param, &url2->transport_param) != 0) - return PJSIP_ECMPTRANSPORTPRM; + if (pj_stricmp(&url1->transport_param, &url2->transport_param) != 0) + return PJSIP_ECMPTRANSPORTPRM; } /* TTL param is not allowed in From, To, Route, and Record-Route header. */ if (context != PJSIP_URI_IN_FROMTO_HDR && - context != PJSIP_URI_IN_ROUTING_HDR) + context != PJSIP_URI_IN_ROUTING_HDR) { - if (url1->ttl_param != url2->ttl_param) - return PJSIP_ECMPTTLPARAM; + if (url1->ttl_param != url2->ttl_param) + return PJSIP_ECMPTTLPARAM; } /* User param is allowed in all contexes */ if (pj_stricmp(&url1->user_param, &url2->user_param) != 0) - return PJSIP_ECMPUSERPARAM; + return PJSIP_ECMPUSERPARAM; /* Method param is only allowed in external/other context. */ if (context == PJSIP_URI_IN_OTHER) { - if (pj_stricmp(&url1->method_param, &url2->method_param) != 0) - return PJSIP_ECMPMETHODPARAM; + if (pj_stricmp(&url1->method_param, &url2->method_param) != 0) + return PJSIP_ECMPMETHODPARAM; } /* maddr param is not allowed in From and To header. */ if (context != PJSIP_URI_IN_FROMTO_HDR) { - if (pj_stricmp(&url1->maddr_param, &url2->maddr_param) != 0) - return PJSIP_ECMPMADDRPARAM; + if (pj_stricmp(&url1->maddr_param, &url2->maddr_param) != 0) + return PJSIP_ECMPMADDRPARAM; } /* lr parameter is ignored (?) */ @@ -476,7 +475,7 @@ static pj_status_t pjsip_url_compare( pjsip_uri_context_e context, * comparing the URIs. */ if (pjsip_param_cmp(&url1->other_param, &url2->other_param, 1)!=0) - return PJSIP_ECMPOTHERPARAM; + return PJSIP_ECMPOTHERPARAM; /* URI header components are never ignored. Any present header component * MUST be present in both URIs and match for the URIs to match. @@ -484,19 +483,19 @@ static pj_status_t pjsip_url_compare( pjsip_uri_context_e context, */ p1 = url1->header_param.next; while (p1 != &url1->header_param) { - const pjsip_param *p2; - p2 = pjsip_param_find(&url2->header_param, &p1->name); - if (p2) { - /* It seems too much to compare two header params according to - * the rule of each header. We'll just compare them string to - * string.. - */ - if (pj_stricmp(&p1->value, &p2->value) != 0) - return PJSIP_ECMPHEADERPARAM; - } else { - return PJSIP_ECMPHEADERPARAM; - } - p1 = p1->next; + const pjsip_param *p2; + p2 = pjsip_param_find(&url2->header_param, &p1->name); + if (p2) { + /* It seems too much to compare two header params according to + * the rule of each header. We'll just compare them string to + * string.. + */ + if (pj_stricmp(&p1->value, &p2->value) != 0) + return PJSIP_ECMPHEADERPARAM; + } else { + return PJSIP_ECMPHEADERPARAM; + } + p1 = p1->next; } /* Equal!! Pheuww.. */ @@ -505,7 +504,7 @@ static pj_status_t pjsip_url_compare( pjsip_uri_context_e context, PJ_DEF(void) pjsip_sip_uri_assign(pj_pool_t *pool, pjsip_sip_uri *url, - const pjsip_sip_uri *rhs) + const pjsip_sip_uri *rhs) { pj_strdup( pool, &url->user, &rhs->user); pj_strdup( pool, &url->passwd, &rhs->passwd); @@ -525,7 +524,7 @@ static pjsip_sip_uri* pjsip_url_clone(pj_pool_t *pool, const pjsip_sip_uri *rhs) { pjsip_sip_uri *url = PJ_POOL_ALLOC_T(pool, pjsip_sip_uri); if (!url) - return NULL; + return NULL; pjsip_sip_uri_init(url, IS_SIPS(rhs)); pjsip_sip_uri_assign(pool, url, rhs); @@ -554,8 +553,8 @@ PJ_DEF(pjsip_name_addr*) pjsip_name_addr_create(pj_pool_t *pool) } static pj_ssize_t pjsip_name_addr_print(pjsip_uri_context_e context, - const pjsip_name_addr *name, - char *buf, pj_size_t size) + const pjsip_name_addr *name, + char *buf, pj_size_t size) { int printed; char *startbuf = buf; @@ -566,23 +565,23 @@ static pj_ssize_t pjsip_name_addr_print(pjsip_uri_context_e context, pj_assert(uri != NULL); if (context != PJSIP_URI_IN_REQ_URI) { - if (name->display.slen) { - if (endbuf-buf < name->display.slen + 3) return -1; - copy_advance_char_check(buf, '"'); - copy_advance(buf, name->display); - copy_advance_char_check(buf, '"'); - copy_advance_char_check(buf, ' '); - } - copy_advance_char_check(buf, '<');; + if (name->display.slen) { + if (endbuf-buf < name->display.slen + 3) return -1; + copy_advance_char_check(buf, '"'); + copy_advance(buf, name->display); + copy_advance_char_check(buf, '"'); + copy_advance_char_check(buf, ' '); + } + copy_advance_char_check(buf, '<');; } printed = pjsip_uri_print(context,uri, buf, endbuf - buf); if (printed < 1) - return -1; + return -1; buf += printed; if (context != PJSIP_URI_IN_REQ_URI) { - copy_advance_char_check(buf, '>'); + copy_advance_char_check(buf, '>'); } *buf = '\0'; @@ -590,18 +589,18 @@ static pj_ssize_t pjsip_name_addr_print(pjsip_uri_context_e context, } PJ_DEF(void) pjsip_name_addr_assign(pj_pool_t *pool, pjsip_name_addr *dst, - const pjsip_name_addr *src) + const pjsip_name_addr *src) { pj_strdup( pool, &dst->display, &src->display); dst->uri = (pjsip_uri*) pjsip_uri_clone(pool, src->uri); } static pjsip_name_addr* pjsip_name_addr_clone( pj_pool_t *pool, - const pjsip_name_addr *rhs) + const pjsip_name_addr *rhs) { pjsip_name_addr *addr = PJ_POOL_ALLOC_T(pool, pjsip_name_addr); if (!addr) - return NULL; + return NULL; pjsip_name_addr_init(addr); pjsip_name_addr_assign(pool, addr, rhs); @@ -609,18 +608,18 @@ static pjsip_name_addr* pjsip_name_addr_clone( pj_pool_t *pool, } static int pjsip_name_addr_compare( pjsip_uri_context_e context, - const pjsip_name_addr *naddr1, - const pjsip_name_addr *naddr2) + const pjsip_name_addr *naddr1, + const pjsip_name_addr *naddr2) { int d; /* Check that naddr2 is also a name_addr */ if (naddr1->vptr != naddr2->vptr) - return -1; + return -1; /* I'm not sure whether display name is included in the comparison. */ if (pj_strcmp(&naddr1->display, &naddr2->display) != 0) { - return -1; + return -1; } pj_assert( naddr1->uri != NULL ); @@ -629,7 +628,7 @@ static int pjsip_name_addr_compare( pjsip_uri_context_e context, /* Compare name-addr as URL */ d = pjsip_uri_cmp( context, naddr1->uri, naddr2->uri); if (d) - return d; + return d; return 0; } @@ -639,21 +638,21 @@ static int pjsip_name_addr_compare( pjsip_uri_context_e context, static const pj_str_t *other_uri_get_scheme( const pjsip_other_uri*); static void *other_uri_get_uri( pjsip_other_uri*); static pj_ssize_t other_uri_print( pjsip_uri_context_e context, - const pjsip_other_uri *url, - char *buf, pj_size_t size); + const pjsip_other_uri *url, + char *buf, pj_size_t size); static int other_uri_cmp( pjsip_uri_context_e context, - const pjsip_other_uri *url1, - const pjsip_other_uri *url2); + const pjsip_other_uri *url1, + const pjsip_other_uri *url2); static pjsip_other_uri* other_uri_clone( pj_pool_t *pool, - const pjsip_other_uri *rhs); + const pjsip_other_uri *rhs); static pjsip_uri_vptr other_uri_vptr = { (P_GET_SCHEME) &other_uri_get_scheme, - (P_GET_URI) &other_uri_get_uri, + (P_GET_URI) &other_uri_get_uri, (P_PRINT_URI) &other_uri_print, - (P_CMP_URI) &other_uri_cmp, - (P_CLONE) &other_uri_clone + (P_CMP_URI) &other_uri_cmp, + (P_CLONE) &other_uri_clone }; @@ -666,7 +665,7 @@ PJ_DEF(pjsip_other_uri*) pjsip_other_uri_create(pj_pool_t *pool) static const pj_str_t *other_uri_get_scheme( const pjsip_other_uri *uri ) { - return &uri->scheme; + return &uri->scheme; } static void *other_uri_get_uri( pjsip_other_uri *uri ) @@ -675,8 +674,8 @@ static void *other_uri_get_uri( pjsip_other_uri *uri ) } static pj_ssize_t other_uri_print(pjsip_uri_context_e context, - const pjsip_other_uri *uri, - char *buf, pj_size_t size) + const pjsip_other_uri *uri, + char *buf, pj_size_t size) { char *startbuf = buf; char *endbuf = buf + size - 1; // Need to minus one for NULL terminator @@ -684,7 +683,7 @@ static pj_ssize_t other_uri_print(pjsip_uri_context_e context, PJ_UNUSED_ARG(context); if (uri->scheme.slen + uri->content.slen + 1 > (int)size) - return -1; + return -1; /* Print scheme. */ copy_advance(buf, uri->scheme); @@ -698,23 +697,23 @@ static pj_ssize_t other_uri_print(pjsip_uri_context_e context, } static int other_uri_cmp(pjsip_uri_context_e context, - const pjsip_other_uri *uri1, - const pjsip_other_uri *uri2) + const pjsip_other_uri *uri1, + const pjsip_other_uri *uri2) { PJ_UNUSED_ARG(context); /* Check that uri2 is also an other_uri */ if (uri1->vptr != uri2->vptr) - return -1; + return -1; /* Scheme must match. */ if (pj_stricmp(&uri1->scheme, &uri2->scheme) != 0) { - return PJSIP_ECMPSCHEME; + return PJSIP_ECMPSCHEME; } /* Content must match. */ if(pj_stricmp(&uri1->content, &uri2->content) != 0) { - return -1; + return -1; } /* Equal. */ @@ -723,7 +722,7 @@ static int other_uri_cmp(pjsip_uri_context_e context, /* Clone *: URI */ static pjsip_other_uri* other_uri_clone(pj_pool_t *pool, - const pjsip_other_uri *rhs) + const pjsip_other_uri *rhs) { pjsip_other_uri *uri = pjsip_other_uri_create(pool); pj_strdup(pool, &uri->scheme, &rhs->scheme); diff --git a/pjsip/src/pjsip/sip_util.c b/pjsip/src/pjsip/sip_util.c index 65a8072aeb..86853f4f5e 100644 --- a/pjsip/src/pjsip/sip_util.c +++ b/pjsip/src/pjsip/sip_util.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -48,13 +47,13 @@ static const char *event_str[] = }; static pj_str_t str_TEXT = { "text", 4}, - str_PLAIN = { "plain", 5 }; + str_PLAIN = { "plain", 5 }; /* Add URI to target-set */ PJ_DEF(pj_status_t) pjsip_target_set_add_uri( pjsip_target_set *tset, - pj_pool_t *pool, - const pjsip_uri *uri, - int q1000) + pj_pool_t *pool, + const pjsip_uri *uri, + int q1000) { pjsip_target *t, *pos = NULL; @@ -62,7 +61,7 @@ PJ_DEF(pj_status_t) pjsip_target_set_add_uri( pjsip_target_set *tset, /* Set q-value to 1 if it is not set */ if (q1000 <= 0) - q1000 = 1000; + q1000 = 1000; /* Scan all the elements to see for duplicates, and at the same time * get the position where the new element should be inserted to @@ -70,11 +69,11 @@ PJ_DEF(pj_status_t) pjsip_target_set_add_uri( pjsip_target_set *tset, */ t = tset->head.next; while (t != &tset->head) { - if (pjsip_uri_cmp(PJSIP_URI_IN_REQ_URI, t->uri, uri)==PJ_SUCCESS) - return PJ_EEXISTS; - if (pos==NULL && t->q1000 < q1000) - pos = t; - t = t->next; + if (pjsip_uri_cmp(PJSIP_URI_IN_REQ_URI, t->uri, uri)==PJ_SUCCESS) + return PJ_EEXISTS; + if (pos==NULL && t->q1000 < q1000) + pos = t; + t = t->next; } /* Create new element */ @@ -84,21 +83,21 @@ PJ_DEF(pj_status_t) pjsip_target_set_add_uri( pjsip_target_set *tset, /* Insert */ if (pos == NULL) - pj_list_push_back(&tset->head, t); + pj_list_push_back(&tset->head, t); else - pj_list_insert_before(pos, t); + pj_list_insert_before(pos, t); /* Set current target if this is the first URI */ if (tset->current == NULL) - tset->current = t; + tset->current = t; return PJ_SUCCESS; } /* Add URI's in the Contact header in the message to target-set */ PJ_DEF(pj_status_t) pjsip_target_set_add_from_msg( pjsip_target_set *tset, - pj_pool_t *pool, - const pjsip_msg *msg) + pj_pool_t *pool, + const pjsip_msg *msg) { const pjsip_hdr *hdr; unsigned added = 0; @@ -108,18 +107,18 @@ PJ_DEF(pj_status_t) pjsip_target_set_add_from_msg( pjsip_target_set *tset, /* Scan for Contact headers and add the URI */ hdr = msg->hdr.next; while (hdr != &msg->hdr) { - if (hdr->type == PJSIP_H_CONTACT) { - const pjsip_contact_hdr *cn_hdr = (const pjsip_contact_hdr*)hdr; - - if (!cn_hdr->star) { - pj_status_t rc; - rc = pjsip_target_set_add_uri(tset, pool, cn_hdr->uri, - cn_hdr->q1000); - if (rc == PJ_SUCCESS) - ++added; - } - } - hdr = hdr->next; + if (hdr->type == PJSIP_H_CONTACT) { + const pjsip_contact_hdr *cn_hdr = (const pjsip_contact_hdr*)hdr; + + if (!cn_hdr->star) { + pj_status_t rc; + rc = pjsip_target_set_add_uri(tset, pool, cn_hdr->uri, + cn_hdr->q1000); + if (rc == PJ_SUCCESS) + ++added; + } + } + hdr = hdr->next; } return added ? PJ_SUCCESS : PJ_EEXISTS; @@ -133,21 +132,21 @@ PJ_DEF(pjsip_target*) pjsip_target_set_get_next(const pjsip_target_set *tset) t = tset->head.next; while (t != &tset->head) { - if (PJSIP_IS_STATUS_IN_CLASS(t->code, 200)) { - /* No more target since one target has been successful */ - return NULL; - } - if (PJSIP_IS_STATUS_IN_CLASS(t->code, 600)) { - /* No more target since one target returned global error */ - return NULL; - } - if (t->code==0 && next==NULL) { - /* This would be the next target as long as we don't find - * targets with 2xx or 6xx status after this. - */ - next = t; - } - t = t->next; + if (PJSIP_IS_STATUS_IN_CLASS(t->code, 200)) { + /* No more target since one target has been successful */ + return NULL; + } + if (PJSIP_IS_STATUS_IN_CLASS(t->code, 600)) { + /* No more target since one target returned global error */ + return NULL; + } + if (t->code==0 && next==NULL) { + /* This would be the next target as long as we don't find + * targets with 2xx or 6xx status after this. + */ + next = t; + } + t = t->next; } return (pjsip_target*)next; @@ -156,7 +155,7 @@ PJ_DEF(pjsip_target*) pjsip_target_set_get_next(const pjsip_target_set *tset) /* Set current target */ PJ_DEF(pj_status_t) pjsip_target_set_set_current( pjsip_target_set *tset, - pjsip_target *target) + pjsip_target *target) { PJ_ASSERT_RETURN(tset && target, PJ_EINVAL); PJ_ASSERT_RETURN(pj_list_find_node(tset, target) != NULL, PJ_ENOTFOUND); @@ -169,9 +168,9 @@ PJ_DEF(pj_status_t) pjsip_target_set_set_current( pjsip_target_set *tset, /* Assign status to a target */ PJ_DEF(pj_status_t) pjsip_target_assign_status( pjsip_target *target, - pj_pool_t *pool, - int status_code, - const pj_str_t *reason) + pj_pool_t *pool, + int status_code, + const pj_str_t *reason) { PJ_ASSERT_RETURN(target && pool && status_code && reason, PJ_EINVAL); @@ -194,14 +193,14 @@ PJ_DEF(pj_status_t) pjsip_target_assign_status( pjsip_target *target, */ static void init_request_throw( pjsip_endpoint *endpt, pjsip_tx_data *tdata, - pjsip_method *method, - pjsip_uri *param_target, - pjsip_from_hdr *param_from, - pjsip_to_hdr *param_to, - pjsip_contact_hdr *param_contact, - pjsip_cid_hdr *param_call_id, - pjsip_cseq_hdr *param_cseq, - const pj_str_t *param_text) + pjsip_method *method, + pjsip_uri *param_target, + pjsip_from_hdr *param_from, + pjsip_to_hdr *param_to, + pjsip_contact_hdr *param_contact, + pjsip_cid_hdr *param_call_id, + pjsip_cseq_hdr *param_cseq, + const pj_str_t *param_text) { pjsip_msg *msg; pjsip_msg_body *body; @@ -218,15 +217,15 @@ static void init_request_throw( pjsip_endpoint *endpt, /* Add additional request headers from endpoint. */ endpt_hdr = pjsip_endpt_get_request_headers(endpt)->next; while (endpt_hdr != pjsip_endpt_get_request_headers(endpt)) { - pjsip_hdr *hdr = (pjsip_hdr*) - pjsip_hdr_shallow_clone(tdata->pool, endpt_hdr); - pjsip_msg_add_hdr( tdata->msg, hdr ); - endpt_hdr = endpt_hdr->next; + pjsip_hdr *hdr = (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, endpt_hdr); + pjsip_msg_add_hdr( tdata->msg, hdr ); + endpt_hdr = endpt_hdr->next; } /* Add From header. */ if (param_from->tag.slen == 0) - pj_create_unique_string(tdata->pool, ¶m_from->tag); + pj_create_unique_string(tdata->pool, ¶m_from->tag); pjsip_msg_add_hdr(msg, (pjsip_hdr*)param_from); /* Add To header. */ @@ -234,7 +233,7 @@ static void init_request_throw( pjsip_endpoint *endpt, /* Add Contact header. */ if (param_contact) { - pjsip_msg_add_hdr(msg, (pjsip_hdr*)param_contact); + pjsip_msg_add_hdr(msg, (pjsip_hdr*)param_contact); } /* Add Call-ID header. */ @@ -250,37 +249,37 @@ static void init_request_throw( pjsip_endpoint *endpt, /* Add header params as request headers */ if (PJSIP_URI_SCHEME_IS_SIP(param_target) || - PJSIP_URI_SCHEME_IS_SIPS(param_target)) + PJSIP_URI_SCHEME_IS_SIPS(param_target)) { - pjsip_sip_uri *uri = (pjsip_sip_uri*) pjsip_uri_get_uri(param_target); - pjsip_param *hparam; - - hparam = uri->header_param.next; - while (hparam != &uri->header_param) { - pjsip_generic_string_hdr *hdr; - - hdr = pjsip_generic_string_hdr_create(tdata->pool, - &hparam->name, - &hparam->value); - pjsip_msg_add_hdr(msg, (pjsip_hdr*)hdr); - hparam = hparam->next; - } + pjsip_sip_uri *uri = (pjsip_sip_uri*) pjsip_uri_get_uri(param_target); + pjsip_param *hparam; + + hparam = uri->header_param.next; + while (hparam != &uri->header_param) { + pjsip_generic_string_hdr *hdr; + + hdr = pjsip_generic_string_hdr_create(tdata->pool, + &hparam->name, + &hparam->value); + pjsip_msg_add_hdr(msg, (pjsip_hdr*)hdr); + hparam = hparam->next; + } } /* Create message body. */ if (param_text) { - body = PJ_POOL_ZALLOC_T(tdata->pool, pjsip_msg_body); - body->content_type.type = str_TEXT; - body->content_type.subtype = str_PLAIN; - body->data = pj_pool_alloc(tdata->pool, param_text->slen ); - pj_memcpy(body->data, param_text->ptr, param_text->slen); - body->len = (unsigned)param_text->slen; - body->print_body = &pjsip_print_text_body; - msg->body = body; + body = PJ_POOL_ZALLOC_T(tdata->pool, pjsip_msg_body); + body->content_type.type = str_TEXT; + body->content_type.subtype = str_PLAIN; + body->data = pj_pool_alloc(tdata->pool, param_text->slen ); + pj_memcpy(body->data, param_text->ptr, param_text->slen); + body->len = (unsigned)param_text->slen; + body->print_body = &pjsip_print_text_body; + msg->body = body; } PJ_LOG(5,(THIS_FILE, "%s created.", - pjsip_tx_data_get_info(tdata))); + pjsip_tx_data_get_info(tdata))); } @@ -288,15 +287,15 @@ static void init_request_throw( pjsip_endpoint *endpt, * Create arbitrary request. */ PJ_DEF(pj_status_t) pjsip_endpt_create_request( pjsip_endpoint *endpt, - const pjsip_method *method, - const pj_str_t *param_target, - const pj_str_t *param_from, - const pj_str_t *param_to, - const pj_str_t *param_contact, - const pj_str_t *param_call_id, - int param_cseq, - const pj_str_t *param_text, - pjsip_tx_data **p_tdata) + const pjsip_method *method, + const pj_str_t *param_target, + const pj_str_t *param_from, + const pj_str_t *param_to, + const pj_str_t *param_contact, + const pj_str_t *param_call_id, + int param_cseq, + const pj_str_t *param_text, + pjsip_tx_data **p_tdata) { pjsip_uri *target; pjsip_tx_data *tdata; @@ -312,79 +311,79 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_request( pjsip_endpoint *endpt, status = pjsip_endpt_create_tdata(endpt, &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Init reference counter to 1. */ pjsip_tx_data_add_ref(tdata); PJ_TRY { - /* Request target. */ - pj_strdup_with_null(tdata->pool, &tmp, param_target); - target = pjsip_parse_uri( tdata->pool, tmp.ptr, tmp.slen, 0); - if (target == NULL) { - status = PJSIP_EINVALIDREQURI; - goto on_error; - } - - /* From */ - from = pjsip_from_hdr_create(tdata->pool); - pj_strdup_with_null(tdata->pool, &tmp, param_from); - from->uri = pjsip_parse_uri( tdata->pool, tmp.ptr, tmp.slen, - PJSIP_PARSE_URI_AS_NAMEADDR); - if (from->uri == NULL) { - status = PJSIP_EINVALIDHDR; - goto on_error; - } - pj_create_unique_string(tdata->pool, &from->tag); - - /* To */ - to = pjsip_to_hdr_create(tdata->pool); - pj_strdup_with_null(tdata->pool, &tmp, param_to); - to->uri = pjsip_parse_uri( tdata->pool, tmp.ptr, tmp.slen, - PJSIP_PARSE_URI_AS_NAMEADDR); - if (to->uri == NULL) { - status = PJSIP_EINVALIDHDR; - goto on_error; - } - - /* Contact. */ - if (param_contact) { - pj_strdup_with_null(tdata->pool, &tmp, param_contact); - contact = (pjsip_contact_hdr*) - pjsip_parse_hdr(tdata->pool, &STR_CONTACT, tmp.ptr, - tmp.slen, NULL); - if (contact == NULL) { - status = PJSIP_EINVALIDHDR; - goto on_error; - } - } else { - contact = NULL; - } - - /* Call-ID */ - call_id = pjsip_cid_hdr_create(tdata->pool); - if (param_call_id != NULL && param_call_id->slen) - pj_strdup(tdata->pool, &call_id->id, param_call_id); - else - pj_create_unique_string(tdata->pool, &call_id->id); - - /* CSeq */ - cseq = pjsip_cseq_hdr_create(tdata->pool); - if (param_cseq >= 0) - cseq->cseq = param_cseq; - else - cseq->cseq = pj_rand() & 0xFFFF; - - /* Method */ - pjsip_method_copy(tdata->pool, &cseq->method, method); - - /* Create the request. */ - init_request_throw( endpt, tdata, &cseq->method, target, from, to, + /* Request target. */ + pj_strdup_with_null(tdata->pool, &tmp, param_target); + target = pjsip_parse_uri( tdata->pool, tmp.ptr, tmp.slen, 0); + if (target == NULL) { + status = PJSIP_EINVALIDREQURI; + goto on_error; + } + + /* From */ + from = pjsip_from_hdr_create(tdata->pool); + pj_strdup_with_null(tdata->pool, &tmp, param_from); + from->uri = pjsip_parse_uri( tdata->pool, tmp.ptr, tmp.slen, + PJSIP_PARSE_URI_AS_NAMEADDR); + if (from->uri == NULL) { + status = PJSIP_EINVALIDHDR; + goto on_error; + } + pj_create_unique_string(tdata->pool, &from->tag); + + /* To */ + to = pjsip_to_hdr_create(tdata->pool); + pj_strdup_with_null(tdata->pool, &tmp, param_to); + to->uri = pjsip_parse_uri( tdata->pool, tmp.ptr, tmp.slen, + PJSIP_PARSE_URI_AS_NAMEADDR); + if (to->uri == NULL) { + status = PJSIP_EINVALIDHDR; + goto on_error; + } + + /* Contact. */ + if (param_contact) { + pj_strdup_with_null(tdata->pool, &tmp, param_contact); + contact = (pjsip_contact_hdr*) + pjsip_parse_hdr(tdata->pool, &STR_CONTACT, tmp.ptr, + tmp.slen, NULL); + if (contact == NULL) { + status = PJSIP_EINVALIDHDR; + goto on_error; + } + } else { + contact = NULL; + } + + /* Call-ID */ + call_id = pjsip_cid_hdr_create(tdata->pool); + if (param_call_id != NULL && param_call_id->slen) + pj_strdup(tdata->pool, &call_id->id, param_call_id); + else + pj_create_unique_string(tdata->pool, &call_id->id); + + /* CSeq */ + cseq = pjsip_cseq_hdr_create(tdata->pool); + if (param_cseq >= 0) + cseq->cseq = param_cseq; + else + cseq->cseq = pj_rand() & 0xFFFF; + + /* Method */ + pjsip_method_copy(tdata->pool, &cseq->method, method); + + /* Create the request. */ + init_request_throw( endpt, tdata, &cseq->method, target, from, to, contact, call_id, cseq, param_text); } PJ_CATCH_ANY { - status = PJ_ENOMEM; - goto on_error; + status = PJ_ENOMEM; + goto on_error; } PJ_END @@ -397,15 +396,15 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_request( pjsip_endpoint *endpt, } PJ_DEF(pj_status_t) pjsip_endpt_create_request_from_hdr( pjsip_endpoint *endpt, - const pjsip_method *method, - const pjsip_uri *param_target, - const pjsip_from_hdr *param_from, - const pjsip_to_hdr *param_to, - const pjsip_contact_hdr *param_contact, - const pjsip_cid_hdr *param_call_id, - int param_cseq, - const pj_str_t *param_text, - pjsip_tx_data **p_tdata) + const pjsip_method *method, + const pjsip_uri *param_target, + const pjsip_from_hdr *param_from, + const pjsip_to_hdr *param_to, + const pjsip_contact_hdr *param_contact, + const pjsip_cid_hdr *param_call_id, + int param_cseq, + const pj_str_t *param_text, + pjsip_tx_data **p_tdata) { pjsip_uri *target; pjsip_tx_data *tdata; @@ -419,49 +418,49 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_request_from_hdr( pjsip_endpoint *endpt, /* Check arguments. */ PJ_ASSERT_RETURN(endpt && method && param_target && param_from && - param_to && p_tdata, PJ_EINVAL); + param_to && p_tdata, PJ_EINVAL); /* Create new transmit data. */ status = pjsip_endpt_create_tdata(endpt, &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Set initial reference counter to 1. */ pjsip_tx_data_add_ref(tdata); PJ_TRY { - /* Duplicate target URI and headers. */ - target = (pjsip_uri*) pjsip_uri_clone(tdata->pool, param_target); - from = (pjsip_from_hdr*) pjsip_hdr_clone(tdata->pool, param_from); - pjsip_fromto_hdr_set_from(from); - to = (pjsip_to_hdr*) pjsip_hdr_clone(tdata->pool, param_to); - pjsip_fromto_hdr_set_to(to); - if (param_contact) { - contact = (pjsip_contact_hdr*) - pjsip_hdr_clone(tdata->pool, param_contact); - } else { - contact = NULL; - } - call_id = pjsip_cid_hdr_create(tdata->pool); - if (param_call_id != NULL && param_call_id->id.slen) - pj_strdup(tdata->pool, &call_id->id, ¶m_call_id->id); - else - pj_create_unique_string(tdata->pool, &call_id->id); - - cseq = pjsip_cseq_hdr_create(tdata->pool); - if (param_cseq >= 0) - cseq->cseq = param_cseq; - else - cseq->cseq = pj_rand() % 0xFFFF; - pjsip_method_copy(tdata->pool, &cseq->method, method); - - /* Copy headers to the request. */ - init_request_throw(endpt, tdata, &cseq->method, target, from, to, + /* Duplicate target URI and headers. */ + target = (pjsip_uri*) pjsip_uri_clone(tdata->pool, param_target); + from = (pjsip_from_hdr*) pjsip_hdr_clone(tdata->pool, param_from); + pjsip_fromto_hdr_set_from(from); + to = (pjsip_to_hdr*) pjsip_hdr_clone(tdata->pool, param_to); + pjsip_fromto_hdr_set_to(to); + if (param_contact) { + contact = (pjsip_contact_hdr*) + pjsip_hdr_clone(tdata->pool, param_contact); + } else { + contact = NULL; + } + call_id = pjsip_cid_hdr_create(tdata->pool); + if (param_call_id != NULL && param_call_id->id.slen) + pj_strdup(tdata->pool, &call_id->id, ¶m_call_id->id); + else + pj_create_unique_string(tdata->pool, &call_id->id); + + cseq = pjsip_cseq_hdr_create(tdata->pool); + if (param_cseq >= 0) + cseq->cseq = param_cseq; + else + cseq->cseq = pj_rand() % 0xFFFF; + pjsip_method_copy(tdata->pool, &cseq->method, method); + + /* Copy headers to the request. */ + init_request_throw(endpt, tdata, &cseq->method, target, from, to, contact, call_id, cseq, param_text); } PJ_CATCH_ANY { - status = PJ_ENOMEM; - goto on_error; + status = PJ_ENOMEM; + goto on_error; } PJ_END; @@ -477,10 +476,10 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_request_from_hdr( pjsip_endpoint *endpt, * Construct a minimal response message for the received request. */ PJ_DEF(pj_status_t) pjsip_endpt_create_response( pjsip_endpoint *endpt, - const pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - pjsip_tx_data **p_tdata) + const pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pjsip_msg *msg, *req_msg; @@ -502,12 +501,12 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_response( pjsip_endpoint *endpt, /* Request MUST NOT be ACK request! */ PJ_ASSERT_RETURN(req_msg->line.req.method.id != PJSIP_ACK_METHOD, - PJ_EINVALIDOP); + PJ_EINVALIDOP); /* Create a new transmit buffer. */ status = pjsip_endpt_create_tdata( endpt, &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Set initial reference count to 1. */ pjsip_tx_data_add_ref(tdata); @@ -518,9 +517,9 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_response( pjsip_endpoint *endpt, /* Set status code and reason text. */ msg->line.status.code = st_code; if (st_text) - pj_strdup(tdata->pool, &msg->line.status.reason, st_text); + pj_strdup(tdata->pool, &msg->line.status.reason, st_text); else - msg->line.status.reason = *pjsip_get_status_text(st_code); + msg->line.status.reason = *pjsip_get_status_text(st_code); /* Set TX data attributes. */ tdata->rx_timestamp = rdata->pkt_info.timestamp; @@ -528,32 +527,32 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_response( pjsip_endpoint *endpt, /* Copy all the via headers, in order. */ via = rdata->msg_info.via; while (via) { - pjsip_via_hdr *new_via; - - new_via = (pjsip_via_hdr*)pjsip_hdr_clone(tdata->pool, via); - if (top_via == NULL) - top_via = new_via; - - pjsip_msg_add_hdr( msg, (pjsip_hdr*)new_via); - via = via->next; - if (via != (void*)&req_msg->hdr) - via = (pjsip_via_hdr*) - pjsip_msg_find_hdr(req_msg, PJSIP_H_VIA, via); - else - break; + pjsip_via_hdr *new_via; + + new_via = (pjsip_via_hdr*)pjsip_hdr_clone(tdata->pool, via); + if (top_via == NULL) + top_via = new_via; + + pjsip_msg_add_hdr( msg, (pjsip_hdr*)new_via); + via = via->next; + if (via != (void*)&req_msg->hdr) + via = (pjsip_via_hdr*) + pjsip_msg_find_hdr(req_msg, PJSIP_H_VIA, via); + else + break; } /* Copy all Record-Route headers, in order. */ rr = (pjsip_rr_hdr*) - pjsip_msg_find_hdr(req_msg, PJSIP_H_RECORD_ROUTE, NULL); + pjsip_msg_find_hdr(req_msg, PJSIP_H_RECORD_ROUTE, NULL); while (rr) { - pjsip_msg_add_hdr(msg, (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, rr)); - rr = rr->next; - if (rr != (void*)&req_msg->hdr) - rr = (pjsip_rr_hdr*) pjsip_msg_find_hdr(req_msg, - PJSIP_H_RECORD_ROUTE, rr); - else - break; + pjsip_msg_add_hdr(msg, (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, rr)); + rr = rr->next; + if (rr != (void*)&req_msg->hdr) + rr = (pjsip_rr_hdr*) pjsip_msg_find_hdr(req_msg, + PJSIP_H_RECORD_ROUTE, rr); + else + break; } /* Copy Call-ID header. */ @@ -575,7 +574,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_response( pjsip_endpoint *endpt, * use it directly). */ if (to_hdr->tag.slen==0 && st_code > 100 && top_via) { - to_hdr->tag = top_via->branch_param; + to_hdr->tag = top_via->branch_param; } /* Copy CSeq header. */ @@ -596,9 +595,9 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_response( pjsip_endpoint *endpt, * and one must not use this function to generate such ACK. */ PJ_DEF(pj_status_t) pjsip_endpt_create_ack( pjsip_endpoint *endpt, - const pjsip_tx_data *tdata, - const pjsip_rx_data *rdata, - pjsip_tx_data **ack_tdata) + const pjsip_tx_data *tdata, + const pjsip_rx_data *rdata, + pjsip_tx_data **ack_tdata) { pjsip_tx_data *ack = NULL; const pjsip_msg *invite_msg; @@ -613,7 +612,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_ack( pjsip_endpoint *endpt, /* rdata must be a non-2xx final response. */ pj_assert(rdata->msg_info.msg->type==PJSIP_RESPONSE_MSG && - rdata->msg_info.msg->line.status.code >= 300); + rdata->msg_info.msg->line.status.code >= 300); /* Initialize return value to NULL. */ *ack_tdata = NULL; @@ -640,15 +639,15 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_ack( pjsip_endpoint *endpt, /* Create new request message from the headers. */ status = pjsip_endpt_create_request_from_hdr(endpt, - pjsip_get_ack_method(), - tdata->msg->line.req.uri, - from_hdr, to_hdr, - NULL, cid_hdr, - cseq_hdr->cseq, NULL, - &ack); + pjsip_get_ack_method(), + tdata->msg->line.req.uri, + from_hdr, to_hdr, + NULL, cid_hdr, + cseq_hdr->cseq, NULL, + &ack); if (status != PJ_SUCCESS) - return status; + return status; /* Update tag in To header with the one from the response (if any). */ to = (pjsip_to_hdr*) pjsip_msg_find_hdr(ack->msg, PJSIP_H_TO, NULL); @@ -657,24 +656,24 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_ack( pjsip_endpoint *endpt, /* Clear Via headers in the new request. */ while ((via=(pjsip_hdr*)pjsip_msg_find_hdr(ack->msg, PJSIP_H_VIA, NULL)) != NULL) - pj_list_erase(via); + pj_list_erase(via); /* Must contain single Via, just as the original INVITE. */ hdr = (pjsip_hdr*) pjsip_msg_find_hdr( invite_msg, PJSIP_H_VIA, NULL); pjsip_msg_insert_first_hdr( ack->msg, - (pjsip_hdr*) pjsip_hdr_clone(ack->pool,hdr) ); + (pjsip_hdr*) pjsip_hdr_clone(ack->pool,hdr) ); /* If the original INVITE has Route headers, those header fields MUST * appear in the ACK. */ hdr = (pjsip_hdr*) pjsip_msg_find_hdr( invite_msg, PJSIP_H_ROUTE, NULL); while (hdr != NULL) { - pjsip_msg_add_hdr( ack->msg, - (pjsip_hdr*) pjsip_hdr_clone(ack->pool, hdr) ); - hdr = hdr->next; - if (hdr == &invite_msg->hdr) - break; - hdr = (pjsip_hdr*) pjsip_msg_find_hdr( invite_msg, PJSIP_H_ROUTE, hdr); + pjsip_msg_add_hdr( ack->msg, + (pjsip_hdr*) pjsip_hdr_clone(ack->pool, hdr) ); + hdr = hdr->next; + if (hdr == &invite_msg->hdr) + break; + hdr = (pjsip_hdr*) pjsip_msg_find_hdr( invite_msg, PJSIP_H_ROUTE, hdr); } /* We're done. @@ -685,7 +684,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_ack( pjsip_endpoint *endpt, on_missing_hdr: if (ack) - pjsip_tx_data_dec_ref(ack); + pjsip_tx_data_dec_ref(ack); return PJSIP_EMISSINGHDR; } @@ -695,8 +694,8 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_ack( pjsip_endpoint *endpt, * chapter 9.1 of RFC3261. */ PJ_DEF(pj_status_t) pjsip_endpt_create_cancel( pjsip_endpoint *endpt, - const pjsip_tx_data *req_tdata, - pjsip_tx_data **p_tdata) + const pjsip_tx_data *req_tdata, + pjsip_tx_data **p_tdata) { pjsip_tx_data *cancel_tdata = NULL; const pjsip_from_hdr *from_hdr; @@ -709,8 +708,8 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_cancel( pjsip_endpoint *endpt, /* The transmit buffer must INVITE request. */ PJ_ASSERT_RETURN(req_tdata->msg->type == PJSIP_REQUEST_MSG && - req_tdata->msg->line.req.method.id == PJSIP_INVITE_METHOD, - PJ_EINVAL); + req_tdata->msg->line.req.method.id == PJSIP_INVITE_METHOD, + PJ_EINVAL); /* Get the headers from original INVITE request. */ # define FIND_HDR(m,HNAME) pjsip_msg_find_hdr(m, PJSIP_H_##HNAME, NULL) @@ -731,19 +730,19 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_cancel( pjsip_endpoint *endpt, /* Create new request message from the headers. */ status = pjsip_endpt_create_request_from_hdr(endpt, - pjsip_get_cancel_method(), - req_tdata->msg->line.req.uri, - from_hdr, to_hdr, - NULL, cid_hdr, - cseq_hdr->cseq, NULL, - &cancel_tdata); + pjsip_get_cancel_method(), + req_tdata->msg->line.req.uri, + from_hdr, to_hdr, + NULL, cid_hdr, + cseq_hdr->cseq, NULL, + &cancel_tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Clear Via headers in the new request. */ while ((via=(pjsip_hdr*)pjsip_msg_find_hdr(cancel_tdata->msg, PJSIP_H_VIA, NULL)) != NULL) - pj_list_erase(via); + pj_list_erase(via); /* Must only have single Via which matches the top-most Via in the @@ -751,8 +750,8 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_cancel( pjsip_endpoint *endpt, */ hdr = (pjsip_hdr*) pjsip_msg_find_hdr(req_tdata->msg, PJSIP_H_VIA, NULL); if (hdr) { - pjsip_msg_insert_first_hdr(cancel_tdata->msg, - (pjsip_hdr*)pjsip_hdr_clone(cancel_tdata->pool, hdr)); + pjsip_msg_insert_first_hdr(cancel_tdata->msg, + (pjsip_hdr*)pjsip_hdr_clone(cancel_tdata->pool, hdr)); } /* If the original request has Route header, the CANCEL request must also @@ -761,31 +760,31 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_cancel( pjsip_endpoint *endpt, */ hdr = (pjsip_hdr*) pjsip_msg_find_hdr(req_tdata->msg, PJSIP_H_ROUTE, NULL); while (hdr != NULL) { - pjsip_msg_add_hdr(cancel_tdata->msg, - (pjsip_hdr*) pjsip_hdr_clone(cancel_tdata->pool, hdr)); - hdr = hdr->next; - if (hdr != &req_tdata->msg->hdr) - hdr = (pjsip_hdr*) pjsip_msg_find_hdr(req_tdata->msg, - PJSIP_H_ROUTE, hdr); - else - break; + pjsip_msg_add_hdr(cancel_tdata->msg, + (pjsip_hdr*) pjsip_hdr_clone(cancel_tdata->pool, hdr)); + hdr = hdr->next; + if (hdr != &req_tdata->msg->hdr) + hdr = (pjsip_hdr*) pjsip_msg_find_hdr(req_tdata->msg, + PJSIP_H_ROUTE, hdr); + else + break; } /* Must also copy the saved strict route header, otherwise CANCEL will be * sent with swapped Route and request URI! */ if (req_tdata->saved_strict_route) { - cancel_tdata->saved_strict_route = (pjsip_route_hdr*) - pjsip_hdr_clone(cancel_tdata->pool, req_tdata->saved_strict_route); + cancel_tdata->saved_strict_route = (pjsip_route_hdr*) + pjsip_hdr_clone(cancel_tdata->pool, req_tdata->saved_strict_route); } /* Copy the destination info from the original request */ pj_memcpy(&cancel_tdata->dest_info, &req_tdata->dest_info, - sizeof(req_tdata->dest_info)); + sizeof(req_tdata->dest_info)); /* Finally, copy the destination host name from the original request */ pj_strdup(cancel_tdata->pool, &cancel_tdata->dest_info.name, - &req_tdata->dest_info.name); + &req_tdata->dest_info.name); /* Done. * Return the transmit buffer containing the CANCEL request. @@ -795,16 +794,16 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_cancel( pjsip_endpoint *endpt, on_missing_hdr: if (cancel_tdata) - pjsip_tx_data_dec_ref(cancel_tdata); + pjsip_tx_data_dec_ref(cancel_tdata); return PJSIP_EMISSINGHDR; } /* Fill-up destination information from a target URI */ PJ_DEF(pj_status_t) pjsip_get_dest_info(const pjsip_uri *target_uri, - const pjsip_uri *request_uri, - pj_pool_t *pool, - pjsip_host_info *dest_info) + const pjsip_uri *request_uri, + pj_pool_t *pool, + pjsip_host_info *dest_info) { /* The target URI must be a SIP/SIPS URL so we can resolve it's address. * Otherwise we're in trouble (i.e. there's no host part in tel: URL). @@ -815,66 +814,66 @@ PJ_DEF(pj_status_t) pjsip_get_dest_info(const pjsip_uri *target_uri, * of the target scheme or transport type (see ticket #1740). */ if (PJSIP_URI_SCHEME_IS_SIPS(target_uri) || - (pjsip_cfg()->endpt.disable_tls_switch == 0 && request_uri && - PJSIP_URI_SCHEME_IS_SIPS(request_uri))) + (pjsip_cfg()->endpt.disable_tls_switch == 0 && request_uri && + PJSIP_URI_SCHEME_IS_SIPS(request_uri))) { - pjsip_uri *uri = (pjsip_uri*) target_uri; - const pjsip_sip_uri *url=(const pjsip_sip_uri*)pjsip_uri_get_uri(uri); - unsigned flag; - - if (!PJSIP_URI_SCHEME_IS_SIPS(target_uri)) { - PJ_LOG(4,(THIS_FILE, "Automatic switch to TLS transport as " - "request-URI uses ""sips"" scheme.")); - } - - dest_info->flag |= (PJSIP_TRANSPORT_SECURE | PJSIP_TRANSPORT_RELIABLE); - if (url->maddr_param.slen) - pj_strdup(pool, &dest_info->addr.host, &url->maddr_param); - else - pj_strdup(pool, &dest_info->addr.host, &url->host); + pjsip_uri *uri = (pjsip_uri*) target_uri; + const pjsip_sip_uri *url=(const pjsip_sip_uri*)pjsip_uri_get_uri(uri); + unsigned flag; + + if (!PJSIP_URI_SCHEME_IS_SIPS(target_uri)) { + PJ_LOG(4,(THIS_FILE, "Automatic switch to TLS transport as " + "request-URI uses ""sips"" scheme.")); + } + + dest_info->flag |= (PJSIP_TRANSPORT_SECURE | PJSIP_TRANSPORT_RELIABLE); + if (url->maddr_param.slen) + pj_strdup(pool, &dest_info->addr.host, &url->maddr_param); + else + pj_strdup(pool, &dest_info->addr.host, &url->host); dest_info->addr.port = url->port; - dest_info->type = + dest_info->type = pjsip_transport_get_type_from_name(&url->transport_param); - /* Double-check that the transport parameter match. - * Sample case: sips:host;transport=tcp - * See https://github.com/pjsip/pjproject/issues/1319 - */ - flag = pjsip_transport_get_flag_from_type(dest_info->type); - if ((flag & dest_info->flag) != dest_info->flag) { - pjsip_transport_type_e t; - - t = pjsip_transport_get_type_from_flag(dest_info->flag); - if (t != PJSIP_TRANSPORT_UNSPECIFIED) - dest_info->type = t; - } + /* Double-check that the transport parameter match. + * Sample case: sips:host;transport=tcp + * See https://github.com/pjsip/pjproject/issues/1319 + */ + flag = pjsip_transport_get_flag_from_type(dest_info->type); + if ((flag & dest_info->flag) != dest_info->flag) { + pjsip_transport_type_e t; + + t = pjsip_transport_get_type_from_flag(dest_info->flag); + if (t != PJSIP_TRANSPORT_UNSPECIFIED) + dest_info->type = t; + } } else if (PJSIP_URI_SCHEME_IS_SIP(target_uri)) { - pjsip_uri *uri = (pjsip_uri*) target_uri; - const pjsip_sip_uri *url=(const pjsip_sip_uri*)pjsip_uri_get_uri(uri); - if (url->maddr_param.slen) - pj_strdup(pool, &dest_info->addr.host, &url->maddr_param); - else - pj_strdup(pool, &dest_info->addr.host, &url->host); - dest_info->addr.port = url->port; - dest_info->type = + pjsip_uri *uri = (pjsip_uri*) target_uri; + const pjsip_sip_uri *url=(const pjsip_sip_uri*)pjsip_uri_get_uri(uri); + if (url->maddr_param.slen) + pj_strdup(pool, &dest_info->addr.host, &url->maddr_param); + else + pj_strdup(pool, &dest_info->addr.host, &url->host); + dest_info->addr.port = url->port; + dest_info->type = pjsip_transport_get_type_from_name(&url->transport_param); - dest_info->flag = - pjsip_transport_get_flag_from_type(dest_info->type); + dest_info->flag = + pjsip_transport_get_flag_from_type(dest_info->type); } else { - /* Should have never reached here; app should have configured route - * set when sending to tel: URI + /* Should have never reached here; app should have configured route + * set when sending to tel: URI pj_assert(!"Unsupported URI scheme!"); - */ - PJ_TODO(SUPPORT_REQUEST_ADDR_RESOLUTION_FOR_TEL_URI); - return PJSIP_ENOROUTESET; + */ + PJ_TODO(SUPPORT_REQUEST_ADDR_RESOLUTION_FOR_TEL_URI); + return PJSIP_ENOROUTESET; } /* Handle IPv6 (https://github.com/pjsip/pjproject/issues/861) */ if (dest_info->type != PJSIP_TRANSPORT_UNSPECIFIED && - pj_strchr(&dest_info->addr.host, ':')) + pj_strchr(&dest_info->addr.host, ':')) { - dest_info->type = (pjsip_transport_type_e) - ((int)dest_info->type | PJSIP_TRANSPORT_IPV6); + dest_info->type = (pjsip_transport_type_e) + ((int)dest_info->type | PJSIP_TRANSPORT_IPV6); } return PJ_SUCCESS; @@ -888,27 +887,27 @@ PJ_DEF(pj_status_t) pjsip_get_dest_info(const pjsip_uri *target_uri, * chapter 8.1.2. */ PJ_DEF(pj_status_t) pjsip_get_request_dest(const pjsip_tx_data *tdata, - pjsip_host_info *dest_info ) + pjsip_host_info *dest_info ) { const pjsip_uri *target_uri; const pjsip_route_hdr *first_route_hdr; PJ_ASSERT_RETURN(tdata->msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); PJ_ASSERT_RETURN(dest_info != NULL, PJ_EINVAL); /* Get the first "Route" header from the message. */ first_route_hdr = (const pjsip_route_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, NULL); + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, NULL); if (first_route_hdr) { - target_uri = first_route_hdr->name_addr.uri; + target_uri = first_route_hdr->name_addr.uri; } else { - target_uri = tdata->msg->line.req.uri; + target_uri = tdata->msg->line.req.uri; } return pjsip_get_dest_info(target_uri, tdata->msg->line.req.uri, - (pj_pool_t*)tdata->pool, dest_info); + (pj_pool_t*)tdata->pool, dest_info); } @@ -920,7 +919,7 @@ PJ_DEF(pj_status_t) pjsip_get_request_dest(const pjsip_tx_data *tdata, * chapter 8.1.2. */ PJ_DEF(pj_status_t) pjsip_process_route_set(pjsip_tx_data *tdata, - pjsip_host_info *dest_info ) + pjsip_host_info *dest_info ) { const pjsip_uri *new_request_uri, *target_uri; const pjsip_name_addr *topmost_route_uri; @@ -928,7 +927,7 @@ PJ_DEF(pj_status_t) pjsip_process_route_set(pjsip_tx_data *tdata, pj_status_t status; PJ_ASSERT_RETURN(tdata->msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); PJ_ASSERT_RETURN(dest_info != NULL, PJ_EINVAL); /* If the request contains strict route, check that the strict route @@ -940,26 +939,26 @@ PJ_DEF(pj_status_t) pjsip_process_route_set(pjsip_tx_data *tdata, * twice! */ if (tdata->saved_strict_route != NULL) { - pjsip_restore_strict_route_set(tdata); + pjsip_restore_strict_route_set(tdata); } PJ_ASSERT_RETURN(tdata->saved_strict_route==NULL, PJ_EBUG); /* Find the first and last "Route" headers from the message. */ last_route_hdr = first_route_hdr = (pjsip_route_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, NULL); + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, NULL); if (first_route_hdr) { - topmost_route_uri = &first_route_hdr->name_addr; - while (last_route_hdr->next != (void*)&tdata->msg->hdr) { - pjsip_route_hdr *hdr; - hdr = (pjsip_route_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, + topmost_route_uri = &first_route_hdr->name_addr; + while (last_route_hdr->next != (void*)&tdata->msg->hdr) { + pjsip_route_hdr *hdr; + hdr = (pjsip_route_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, last_route_hdr->next); - if (!hdr) - break; - last_route_hdr = hdr; - } + if (!hdr) + break; + last_route_hdr = hdr; + } } else { - topmost_route_uri = NULL; + topmost_route_uri = NULL; } /* If Route headers exist, and the first element indicates loose-route, @@ -972,70 +971,70 @@ PJ_DEF(pj_status_t) pjsip_process_route_set(pjsip_tx_data *tdata, * Request-URI. */ if (topmost_route_uri) { - pj_bool_t has_lr_param; - - if (PJSIP_URI_SCHEME_IS_SIP(topmost_route_uri) || - PJSIP_URI_SCHEME_IS_SIPS(topmost_route_uri)) - { - const pjsip_sip_uri *url = (const pjsip_sip_uri*) - pjsip_uri_get_uri((const void*)topmost_route_uri); - has_lr_param = url->lr_param; - } else { - has_lr_param = 0; - } - - if (has_lr_param) { - new_request_uri = tdata->msg->line.req.uri; - /* We shouldn't need to delete topmost Route if it has lr param. - * But seems like it breaks some proxy implementation, so we - * delete it anyway. - */ - /* - pj_list_erase(first_route_hdr); - if (first_route_hdr == last_route_hdr) - last_route_hdr = NULL; - */ - } else { - new_request_uri = (const pjsip_uri*) - pjsip_uri_get_uri((pjsip_uri*)topmost_route_uri); - pj_list_erase(first_route_hdr); - tdata->saved_strict_route = first_route_hdr; - if (first_route_hdr == last_route_hdr) - first_route_hdr = last_route_hdr = NULL; - } - - target_uri = (pjsip_uri*)topmost_route_uri; + pj_bool_t has_lr_param; + + if (PJSIP_URI_SCHEME_IS_SIP(topmost_route_uri) || + PJSIP_URI_SCHEME_IS_SIPS(topmost_route_uri)) + { + const pjsip_sip_uri *url = (const pjsip_sip_uri*) + pjsip_uri_get_uri((const void*)topmost_route_uri); + has_lr_param = url->lr_param; + } else { + has_lr_param = 0; + } + + if (has_lr_param) { + new_request_uri = tdata->msg->line.req.uri; + /* We shouldn't need to delete topmost Route if it has lr param. + * But seems like it breaks some proxy implementation, so we + * delete it anyway. + */ + /* + pj_list_erase(first_route_hdr); + if (first_route_hdr == last_route_hdr) + last_route_hdr = NULL; + */ + } else { + new_request_uri = (const pjsip_uri*) + pjsip_uri_get_uri((pjsip_uri*)topmost_route_uri); + pj_list_erase(first_route_hdr); + tdata->saved_strict_route = first_route_hdr; + if (first_route_hdr == last_route_hdr) + first_route_hdr = last_route_hdr = NULL; + } + + target_uri = (pjsip_uri*)topmost_route_uri; } else { - target_uri = new_request_uri = tdata->msg->line.req.uri; + target_uri = new_request_uri = tdata->msg->line.req.uri; } /* Fill up the destination host/port from the URI. */ status = pjsip_get_dest_info(target_uri, new_request_uri, tdata->pool, - dest_info); + dest_info); if (status != PJ_SUCCESS) - return status; + return status; /* If transport selector is set, set destination type accordingly */ if (tdata->tp_sel.type != PJSIP_TPSELECTOR_NONE && tdata->tp_sel.u.ptr) { - if (tdata->tp_sel.type == PJSIP_TPSELECTOR_TRANSPORT) - dest_info->type = tdata->tp_sel.u.transport->key.type; - else if (tdata->tp_sel.type == PJSIP_TPSELECTOR_LISTENER) - dest_info->type = tdata->tp_sel.u.listener->type; + if (tdata->tp_sel.type == PJSIP_TPSELECTOR_TRANSPORT) + dest_info->type = tdata->tp_sel.u.transport->key.type; + else if (tdata->tp_sel.type == PJSIP_TPSELECTOR_LISTENER) + dest_info->type = tdata->tp_sel.u.listener->type; } /* If target URI is different than request URI, replace * request URI add put the original URI in the last Route header. */ if (new_request_uri && new_request_uri!=tdata->msg->line.req.uri) { - pjsip_route_hdr *route = pjsip_route_hdr_create(tdata->pool); - route->name_addr.uri = (pjsip_uri*) - pjsip_uri_get_uri(tdata->msg->line.req.uri); - if (last_route_hdr) - pj_list_insert_after(last_route_hdr, route); - else - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)route); - tdata->msg->line.req.uri = (pjsip_uri*)new_request_uri; + pjsip_route_hdr *route = pjsip_route_hdr_create(tdata->pool); + route->name_addr.uri = (pjsip_uri*) + pjsip_uri_get_uri(tdata->msg->line.req.uri); + if (last_route_hdr) + pj_list_insert_after(last_route_hdr, route); + else + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)route); + tdata->msg->line.req.uri = (pjsip_uri*)new_request_uri; } /* Success. */ @@ -1054,31 +1053,31 @@ PJ_DEF(void) pjsip_restore_strict_route_set(pjsip_tx_data *tdata) /* Check if we have found strict route before */ if (tdata->saved_strict_route == NULL) { - /* This request doesn't contain strict route */ - return; + /* This request doesn't contain strict route */ + return; } /* Find the first "Route" headers from the message. */ first_route_hdr = (pjsip_route_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, NULL); + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, NULL); if (first_route_hdr == NULL) { - /* User has modified message route? We don't expect this! */ - pj_assert(!"Message route was modified?"); - tdata->saved_strict_route = NULL; - return; + /* User has modified message route? We don't expect this! */ + pj_assert(!"Message route was modified?"); + tdata->saved_strict_route = NULL; + return; } /* Find last Route header */ last_route_hdr = first_route_hdr; while (last_route_hdr->next != (void*)&tdata->msg->hdr) { - pjsip_route_hdr *hdr; - hdr = (pjsip_route_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, + pjsip_route_hdr *hdr; + hdr = (pjsip_route_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, last_route_hdr->next); - if (!hdr) - break; - last_route_hdr = hdr; + if (!hdr) + break; + last_route_hdr = hdr; } /* Put the last Route header as request URI, delete last Route @@ -1098,8 +1097,8 @@ PJ_DEF(void) pjsip_restore_strict_route_set(pjsip_tx_data *tdata) * good luck if you happen to debug this function!! */ static void stateless_send_transport_cb( void *token, - pjsip_tx_data *tdata, - pj_ssize_t sent ) + pjsip_tx_data *tdata, + pj_ssize_t sent ) { pjsip_send_state *stateless_data = (pjsip_send_state*) token; pj_status_t need_update_via = PJ_TRUE; @@ -1108,192 +1107,192 @@ static void stateless_send_transport_cb( void *token, pj_assert(tdata == stateless_data->tdata); for (;;) { - pj_status_t status; - pj_bool_t cont; - - pj_sockaddr_t *cur_addr; - pjsip_transport_type_e cur_addr_type; - int cur_addr_len; - - pjsip_via_hdr *via; - - if (sent == -PJ_EPENDING) { - /* This is the initial process. - * When the process started, this function will be called by - * stateless_send_resolver_callback() with sent argument set to - * -PJ_EPENDING. - */ - cont = PJ_TRUE; - } else { - /* There are two conditions here: - * (1) Message is sent (i.e. sent > 0), - * (2) Failure (i.e. sent <= 0) - */ - cont = (sent > 0) ? PJ_FALSE : - (tdata->dest_info.cur_addrdest_info.addr.count-1); - if (stateless_data->app_cb) { - (*stateless_data->app_cb)(stateless_data, sent, &cont); - } else { - /* Doesn't have application callback. - * Terminate the process. - */ - cont = PJ_FALSE; - } - } - - /* Finished with this transport. */ - if (stateless_data->cur_transport) { - pjsip_transport_dec_ref(stateless_data->cur_transport); - stateless_data->cur_transport = NULL; - } - - /* Done if application doesn't want to continue. */ - if (sent > 0 || !cont) { - pjsip_tx_data_dec_ref(tdata); - return; - } - - /* Try next address, if any, and only when this is not the - * first invocation. - */ - if (sent != -PJ_EPENDING) { - tdata->dest_info.cur_addr++; - } - - /* Have next address? */ - if (tdata->dest_info.cur_addr >= tdata->dest_info.addr.count) { - /* This only happens when a rather buggy application has - * sent 'cont' to PJ_TRUE when the initial value was PJ_FALSE. - * In this case just stop the processing; we don't need to - * call the callback again as application has been informed - * before. - */ - pjsip_tx_data_dec_ref(tdata); - return; - } - - /* Keep current server address information handy. */ - cur_addr = &tdata->dest_info.addr.entry[tdata->dest_info.cur_addr].addr; - cur_addr_type = tdata->dest_info.addr.entry[tdata->dest_info.cur_addr].type; - cur_addr_len = tdata->dest_info.addr.entry[tdata->dest_info.cur_addr].addr_len; - - /* Acquire transport. */ - status = pjsip_endpt_acquire_transport2(stateless_data->endpt, - cur_addr_type, - cur_addr, - cur_addr_len, - &tdata->tp_sel, - tdata, - &stateless_data->cur_transport); - if (status != PJ_SUCCESS) { - sent = -status; - continue; - } - - /* Modify Via header. */ - via = (pjsip_via_hdr*) pjsip_msg_find_hdr( tdata->msg, - PJSIP_H_VIA, NULL); - if (!via) { - /* Shouldn't happen if request was created with PJSIP API! - * But we handle the case anyway for robustness. - */ - pj_assert(!"Via header not found!"); - via = pjsip_via_hdr_create(tdata->pool); - pjsip_msg_insert_first_hdr(tdata->msg, (pjsip_hdr*)via); - } - - if (tdata->msg->line.req.method.id == PJSIP_CANCEL_METHOD) { - if (via->sent_by.host.slen > 0) { - /* Don't update Via header on a CANCEL request if the sent-by - * parameter is already set since it needs to match the - * original request. */ - need_update_via = PJ_FALSE; - } - } - - if (via->branch_param.slen == 0) { - pj_str_t tmp; - via->branch_param.ptr = (char*)pj_pool_alloc(tdata->pool, - PJSIP_MAX_BRANCH_LEN); - via->branch_param.slen = PJSIP_MAX_BRANCH_LEN; - pj_memcpy(via->branch_param.ptr, PJSIP_RFC3261_BRANCH_ID, - PJSIP_RFC3261_BRANCH_LEN); - tmp.ptr = via->branch_param.ptr + PJSIP_RFC3261_BRANCH_LEN + 2; - *(tmp.ptr-2) = 80; *(tmp.ptr-1) = 106; - pj_generate_unique_string(&tmp); - } - - if (need_update_via) { - via->transport = pj_str(stateless_data->cur_transport->type_name); - - if (tdata->via_addr.host.slen > 0 && - (!tdata->via_tp || - tdata->via_tp == (void *)stateless_data->cur_transport)) - { - via->sent_by = tdata->via_addr; - - /* Better also update tdata via_tp, e.g: CANCEL may need to - * refer to original INVITE tdata. - */ - tdata->via_tp = stateless_data->cur_transport; - } else { - via->sent_by = stateless_data->cur_transport->local_name; - - /* Better also update tdata via_tp & via_addr, e.g: CANCEL - * may need to refer to original INVITE tdata. - */ - tdata->via_tp = stateless_data->cur_transport; - tdata->via_addr = via->sent_by; - } - - via->rport_param = pjsip_cfg()->endpt.disable_rport ? -1 : 0; - - /* Add/remove "alias" param to/from Via header on connection - * oriented/less transport, if configured. - */ - if (pjsip_cfg()->endpt.req_has_via_alias && - tdata->msg->type == PJSIP_REQUEST_MSG) - { - const pj_str_t ALIAS_STR = {"alias", 5}; - pjsip_param *alias_param; - pj_bool_t is_datagram; - - alias_param = pjsip_param_find(&via->other_param, &ALIAS_STR); - is_datagram = (stateless_data->cur_transport->flag & - PJSIP_TRANSPORT_DATAGRAM); - if (!is_datagram && !alias_param) { - alias_param = PJ_POOL_ZALLOC_T(tdata->pool, pjsip_param); - alias_param->name = ALIAS_STR; - pj_list_push_back(&via->other_param, alias_param); - } else if (is_datagram && alias_param) { - pj_list_erase(alias_param); - } - } - } - - pjsip_tx_data_invalidate_msg(tdata); - - /* Send message using this transport. */ - status = pjsip_transport_send( stateless_data->cur_transport, - tdata, - cur_addr, - cur_addr_len, - stateless_data, - &stateless_send_transport_cb); - if (status == PJ_SUCCESS) { - /* Recursively call this function. */ - sent = tdata->buf.cur - tdata->buf.start; - stateless_send_transport_cb( stateless_data, tdata, sent ); - return; - } else if (status == PJ_EPENDING) { - /* This callback will be called later. */ - return; - } else { - /* Recursively call this function. */ - sent = -status; - stateless_send_transport_cb( stateless_data, tdata, sent ); - return; - } + pj_status_t status; + pj_bool_t cont; + + pj_sockaddr_t *cur_addr; + pjsip_transport_type_e cur_addr_type; + int cur_addr_len; + + pjsip_via_hdr *via; + + if (sent == -PJ_EPENDING) { + /* This is the initial process. + * When the process started, this function will be called by + * stateless_send_resolver_callback() with sent argument set to + * -PJ_EPENDING. + */ + cont = PJ_TRUE; + } else { + /* There are two conditions here: + * (1) Message is sent (i.e. sent > 0), + * (2) Failure (i.e. sent <= 0) + */ + cont = (sent > 0) ? PJ_FALSE : + (tdata->dest_info.cur_addrdest_info.addr.count-1); + if (stateless_data->app_cb) { + (*stateless_data->app_cb)(stateless_data, sent, &cont); + } else { + /* Doesn't have application callback. + * Terminate the process. + */ + cont = PJ_FALSE; + } + } + + /* Finished with this transport. */ + if (stateless_data->cur_transport) { + pjsip_transport_dec_ref(stateless_data->cur_transport); + stateless_data->cur_transport = NULL; + } + + /* Done if application doesn't want to continue. */ + if (sent > 0 || !cont) { + pjsip_tx_data_dec_ref(tdata); + return; + } + + /* Try next address, if any, and only when this is not the + * first invocation. + */ + if (sent != -PJ_EPENDING) { + tdata->dest_info.cur_addr++; + } + + /* Have next address? */ + if (tdata->dest_info.cur_addr >= tdata->dest_info.addr.count) { + /* This only happens when a rather buggy application has + * sent 'cont' to PJ_TRUE when the initial value was PJ_FALSE. + * In this case just stop the processing; we don't need to + * call the callback again as application has been informed + * before. + */ + pjsip_tx_data_dec_ref(tdata); + return; + } + + /* Keep current server address information handy. */ + cur_addr = &tdata->dest_info.addr.entry[tdata->dest_info.cur_addr].addr; + cur_addr_type = tdata->dest_info.addr.entry[tdata->dest_info.cur_addr].type; + cur_addr_len = tdata->dest_info.addr.entry[tdata->dest_info.cur_addr].addr_len; + + /* Acquire transport. */ + status = pjsip_endpt_acquire_transport2(stateless_data->endpt, + cur_addr_type, + cur_addr, + cur_addr_len, + &tdata->tp_sel, + tdata, + &stateless_data->cur_transport); + if (status != PJ_SUCCESS) { + sent = -status; + continue; + } + + /* Modify Via header. */ + via = (pjsip_via_hdr*) pjsip_msg_find_hdr( tdata->msg, + PJSIP_H_VIA, NULL); + if (!via) { + /* Shouldn't happen if request was created with PJSIP API! + * But we handle the case anyway for robustness. + */ + pj_assert(!"Via header not found!"); + via = pjsip_via_hdr_create(tdata->pool); + pjsip_msg_insert_first_hdr(tdata->msg, (pjsip_hdr*)via); + } + + if (tdata->msg->line.req.method.id == PJSIP_CANCEL_METHOD) { + if (via->sent_by.host.slen > 0) { + /* Don't update Via header on a CANCEL request if the sent-by + * parameter is already set since it needs to match the + * original request. */ + need_update_via = PJ_FALSE; + } + } + + if (via->branch_param.slen == 0) { + pj_str_t tmp; + via->branch_param.ptr = (char*)pj_pool_alloc(tdata->pool, + PJSIP_MAX_BRANCH_LEN); + via->branch_param.slen = PJSIP_MAX_BRANCH_LEN; + pj_memcpy(via->branch_param.ptr, PJSIP_RFC3261_BRANCH_ID, + PJSIP_RFC3261_BRANCH_LEN); + tmp.ptr = via->branch_param.ptr + PJSIP_RFC3261_BRANCH_LEN + 2; + *(tmp.ptr-2) = 80; *(tmp.ptr-1) = 106; + pj_generate_unique_string(&tmp); + } + + if (need_update_via) { + via->transport = pj_str(stateless_data->cur_transport->type_name); + + if (tdata->via_addr.host.slen > 0 && + (!tdata->via_tp || + tdata->via_tp == (void *)stateless_data->cur_transport)) + { + via->sent_by = tdata->via_addr; + + /* Better also update tdata via_tp, e.g: CANCEL may need to + * refer to original INVITE tdata. + */ + tdata->via_tp = stateless_data->cur_transport; + } else { + via->sent_by = stateless_data->cur_transport->local_name; + + /* Better also update tdata via_tp & via_addr, e.g: CANCEL + * may need to refer to original INVITE tdata. + */ + tdata->via_tp = stateless_data->cur_transport; + tdata->via_addr = via->sent_by; + } + + via->rport_param = pjsip_cfg()->endpt.disable_rport ? -1 : 0; + + /* Add/remove "alias" param to/from Via header on connection + * oriented/less transport, if configured. + */ + if (pjsip_cfg()->endpt.req_has_via_alias && + tdata->msg->type == PJSIP_REQUEST_MSG) + { + const pj_str_t ALIAS_STR = {"alias", 5}; + pjsip_param *alias_param; + pj_bool_t is_datagram; + + alias_param = pjsip_param_find(&via->other_param, &ALIAS_STR); + is_datagram = (stateless_data->cur_transport->flag & + PJSIP_TRANSPORT_DATAGRAM); + if (!is_datagram && !alias_param) { + alias_param = PJ_POOL_ZALLOC_T(tdata->pool, pjsip_param); + alias_param->name = ALIAS_STR; + pj_list_push_back(&via->other_param, alias_param); + } else if (is_datagram && alias_param) { + pj_list_erase(alias_param); + } + } + } + + pjsip_tx_data_invalidate_msg(tdata); + + /* Send message using this transport. */ + status = pjsip_transport_send( stateless_data->cur_transport, + tdata, + cur_addr, + cur_addr_len, + stateless_data, + &stateless_send_transport_cb); + if (status == PJ_SUCCESS) { + /* Recursively call this function. */ + sent = tdata->buf.cur - tdata->buf.start; + stateless_send_transport_cb( stateless_data, tdata, sent ); + return; + } else if (status == PJ_EPENDING) { + /* This callback will be called later. */ + return; + } else { + /* Recursively call this function. */ + sent = -status; + stateless_send_transport_cb( stateless_data, tdata, sent ); + return; + } } } @@ -1301,26 +1300,26 @@ static void stateless_send_transport_cb( void *token, /* Resolver callback for sending stateless request. */ static void stateless_send_resolver_callback( pj_status_t status, - void *token, - const struct pjsip_server_addresses *addr) + void *token, + const struct pjsip_server_addresses *addr) { pjsip_send_state *stateless_data = (pjsip_send_state*) token; pjsip_tx_data *tdata = stateless_data->tdata; /* Fail on server resolution. */ if (status != PJ_SUCCESS) { - if (stateless_data->app_cb) { - pj_bool_t cont = PJ_FALSE; - (*stateless_data->app_cb)(stateless_data, -status, &cont); - } - pjsip_tx_data_dec_ref(tdata); - return; + if (stateless_data->app_cb) { + pj_bool_t cont = PJ_FALSE; + (*stateless_data->app_cb)(stateless_data, -status, &cont); + } + pjsip_tx_data_dec_ref(tdata); + return; } /* Copy server addresses */ if (addr && addr != &tdata->dest_info.addr) { - pj_memcpy( &tdata->dest_info.addr, addr, - sizeof(pjsip_server_addresses)); + pj_memcpy( &tdata->dest_info.addr, addr, + sizeof(pjsip_server_addresses)); } pj_assert(tdata->dest_info.addr.count != 0); @@ -1331,47 +1330,47 @@ stateless_send_resolver_callback( pj_status_t status, * as TCP. */ if (pjsip_cfg()->endpt.disable_tcp_switch==0 && - tdata->msg->type == PJSIP_REQUEST_MSG && - tdata->dest_info.addr.count > 0 && - tdata->dest_info.addr.entry[0].type == PJSIP_TRANSPORT_UDP) + tdata->msg->type == PJSIP_REQUEST_MSG && + tdata->dest_info.addr.count > 0 && + tdata->dest_info.addr.entry[0].type == PJSIP_TRANSPORT_UDP) { - int len; - - /* Encode the request */ - status = pjsip_tx_data_encode(tdata); - if (status != PJ_SUCCESS) { - if (stateless_data->app_cb) { - pj_bool_t cont = PJ_FALSE; - (*stateless_data->app_cb)(stateless_data, -status, &cont); - } - pjsip_tx_data_dec_ref(tdata); - return; - } - - /* Check if request message is larger than 1300 bytes. */ - len = (int)(tdata->buf.cur - tdata->buf.start); - if (len >= PJSIP_UDP_SIZE_THRESHOLD) { - int i; - int count = tdata->dest_info.addr.count; - - PJ_LOG(5,(THIS_FILE, "%s exceeds UDP size threshold (%u), " - "sending with TCP", - pjsip_tx_data_get_info(tdata), - PJSIP_UDP_SIZE_THRESHOLD)); - - /* Insert "TCP version" of resolved UDP addresses at the - * beginning. - */ - if (count * 2 > PJSIP_MAX_RESOLVED_ADDRESSES) - count = PJSIP_MAX_RESOLVED_ADDRESSES / 2; - for (i = 0; i < count; ++i) { - pj_memcpy(&tdata->dest_info.addr.entry[i+count], - &tdata->dest_info.addr.entry[i], - sizeof(tdata->dest_info.addr.entry[0])); - tdata->dest_info.addr.entry[i].type = PJSIP_TRANSPORT_TCP; - } - tdata->dest_info.addr.count = count * 2; - } + int len; + + /* Encode the request */ + status = pjsip_tx_data_encode(tdata); + if (status != PJ_SUCCESS) { + if (stateless_data->app_cb) { + pj_bool_t cont = PJ_FALSE; + (*stateless_data->app_cb)(stateless_data, -status, &cont); + } + pjsip_tx_data_dec_ref(tdata); + return; + } + + /* Check if request message is larger than 1300 bytes. */ + len = (int)(tdata->buf.cur - tdata->buf.start); + if (len >= PJSIP_UDP_SIZE_THRESHOLD) { + int i; + int count = tdata->dest_info.addr.count; + + PJ_LOG(5,(THIS_FILE, "%s exceeds UDP size threshold (%u), " + "sending with TCP", + pjsip_tx_data_get_info(tdata), + PJSIP_UDP_SIZE_THRESHOLD)); + + /* Insert "TCP version" of resolved UDP addresses at the + * beginning. + */ + if (count * 2 > PJSIP_MAX_RESOLVED_ADDRESSES) + count = PJSIP_MAX_RESOLVED_ADDRESSES / 2; + for (i = 0; i < count; ++i) { + pj_memcpy(&tdata->dest_info.addr.entry[i+count], + &tdata->dest_info.addr.entry[i], + sizeof(tdata->dest_info.addr.entry[0])); + tdata->dest_info.addr.entry[i].type = PJSIP_TRANSPORT_TCP; + } + tdata->dest_info.addr.count = count * 2; + } } /* Process the addresses. */ @@ -1387,9 +1386,9 @@ stateless_send_resolver_callback( pj_status_t status, * - send the message (#pjsip_transport_send) */ PJ_DEF(pj_status_t) pjsip_endpt_send_request_stateless(pjsip_endpoint *endpt, - pjsip_tx_data *tdata, - void *token, - pjsip_send_callback cb) + pjsip_tx_data *tdata, + void *token, + pjsip_send_callback cb) { pjsip_host_info dest_info; pjsip_send_state *stateless_data; @@ -1400,7 +1399,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_request_stateless(pjsip_endpoint *endpt, /* Get destination name to contact. */ status = pjsip_process_route_set(tdata, &dest_info); if (status != PJ_SUCCESS) - return status; + return status; /* Keep stateless data. */ stateless_data = PJ_POOL_ZALLOC_T(tdata->pool, pjsip_send_state); @@ -1416,20 +1415,20 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_request_stateless(pjsip_endpoint *endpt, * proceed to sending the request directly. */ if (tdata->dest_info.addr.count == 0) { - /* Copy the destination host name to TX data */ - if (!tdata->dest_info.name.slen) { - pj_strdup(tdata->pool, &tdata->dest_info.name, - &dest_info.addr.host); - } - - pjsip_endpt_resolve( endpt, tdata->pool, &dest_info, stateless_data, - &stateless_send_resolver_callback); + /* Copy the destination host name to TX data */ + if (!tdata->dest_info.name.slen) { + pj_strdup(tdata->pool, &tdata->dest_info.name, + &dest_info.addr.host); + } + + pjsip_endpt_resolve( endpt, tdata->pool, &dest_info, stateless_data, + &stateless_send_resolver_callback); } else { - PJ_LOG(5,(THIS_FILE, "%s: skipping target resolution because " - "address is already set", - pjsip_tx_data_get_info(tdata))); - stateless_send_resolver_callback(PJ_SUCCESS, stateless_data, - &tdata->dest_info.addr); + PJ_LOG(5,(THIS_FILE, "%s: skipping target resolution because " + "address is already set", + pjsip_tx_data_get_info(tdata))); + stateless_send_resolver_callback(PJ_SUCCESS, stateless_data, + &tdata->dest_info.addr); } return PJ_SUCCESS; } @@ -1439,72 +1438,72 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_request_stateless(pjsip_endpoint *endpt, * Send raw data to a destination. */ PJ_DEF(pj_status_t) pjsip_endpt_send_raw( pjsip_endpoint *endpt, - pjsip_transport_type_e tp_type, - const pjsip_tpselector *sel, - const void *raw_data, - pj_size_t data_len, - const pj_sockaddr_t *addr, - int addr_len, - void *token, - pjsip_tp_send_callback cb) + pjsip_transport_type_e tp_type, + const pjsip_tpselector *sel, + const void *raw_data, + pj_size_t data_len, + const pj_sockaddr_t *addr, + int addr_len, + void *token, + pjsip_tp_send_callback cb) { return pjsip_tpmgr_send_raw(pjsip_endpt_get_tpmgr(endpt), tp_type, sel, - NULL, raw_data, data_len, addr, addr_len, - token, cb); + NULL, raw_data, data_len, addr, addr_len, + token, cb); } /* Callback data for sending raw data */ struct send_raw_data { - pjsip_endpoint *endpt; - pjsip_tx_data *tdata; - pjsip_tpselector *sel; - void *app_token; + pjsip_endpoint *endpt; + pjsip_tx_data *tdata; + pjsip_tpselector *sel; + void *app_token; pjsip_tp_send_callback app_cb; }; /* Resolver callback for sending raw data. */ static void send_raw_resolver_callback( pj_status_t status, - void *token, - const pjsip_server_addresses *addr) + void *token, + const pjsip_server_addresses *addr) { struct send_raw_data *sraw_data = (struct send_raw_data*) token; if (status != PJ_SUCCESS) { - if (sraw_data->app_cb) { - (*sraw_data->app_cb)(sraw_data->app_token, sraw_data->tdata, - -status); - } + if (sraw_data->app_cb) { + (*sraw_data->app_cb)(sraw_data->app_token, sraw_data->tdata, + -status); + } } else { - pj_size_t data_len; - - pj_assert(addr->count != 0); - - /* Avoid tdata destroyed by pjsip_tpmgr_send_raw(). */ - pjsip_tx_data_add_ref(sraw_data->tdata); - - data_len = sraw_data->tdata->buf.cur - sraw_data->tdata->buf.start; - status = pjsip_tpmgr_send_raw(pjsip_endpt_get_tpmgr(sraw_data->endpt), - addr->entry[0].type, - sraw_data->sel, sraw_data->tdata, - sraw_data->tdata->buf.start, data_len, - &addr->entry[0].addr, - addr->entry[0].addr_len, - sraw_data->app_token, - sraw_data->app_cb); - if (status == PJ_SUCCESS) { - (*sraw_data->app_cb)(sraw_data->app_token, sraw_data->tdata, - data_len); - } else if (status != PJ_EPENDING) { - (*sraw_data->app_cb)(sraw_data->app_token, sraw_data->tdata, - -status); - } + pj_size_t data_len; + + pj_assert(addr->count != 0); + + /* Avoid tdata destroyed by pjsip_tpmgr_send_raw(). */ + pjsip_tx_data_add_ref(sraw_data->tdata); + + data_len = sraw_data->tdata->buf.cur - sraw_data->tdata->buf.start; + status = pjsip_tpmgr_send_raw(pjsip_endpt_get_tpmgr(sraw_data->endpt), + addr->entry[0].type, + sraw_data->sel, sraw_data->tdata, + sraw_data->tdata->buf.start, data_len, + &addr->entry[0].addr, + addr->entry[0].addr_len, + sraw_data->app_token, + sraw_data->app_cb); + if (status == PJ_SUCCESS) { + (*sraw_data->app_cb)(sraw_data->app_token, sraw_data->tdata, + data_len); + } else if (status != PJ_EPENDING) { + (*sraw_data->app_cb)(sraw_data->app_token, sraw_data->tdata, + -status); + } } if (sraw_data->sel) { - pjsip_tpselector_dec_ref(sraw_data->sel); + pjsip_tpselector_dec_ref(sraw_data->sel); } pjsip_tx_data_dec_ref(sraw_data->tdata); } @@ -1514,12 +1513,12 @@ static void send_raw_resolver_callback( pj_status_t status, * Send raw data to the specified destination URI. */ PJ_DEF(pj_status_t) pjsip_endpt_send_raw_to_uri(pjsip_endpoint *endpt, - const pj_str_t *p_dst_uri, - const pjsip_tpselector *sel, - const void *raw_data, - pj_size_t data_len, - void *token, - pjsip_tp_send_callback cb) + const pj_str_t *p_dst_uri, + const pjsip_tpselector *sel, + const void *raw_data, + pj_size_t data_len, + void *token, + pjsip_tp_send_callback cb) { pjsip_tx_data *tdata; struct send_raw_data *sraw_data; @@ -1531,7 +1530,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_raw_to_uri(pjsip_endpoint *endpt, /* Allocate buffer */ status = pjsip_endpt_create_tdata(endpt, &tdata); if (status != PJ_SUCCESS) - return status; + return status; pjsip_tx_data_add_ref(tdata); @@ -1541,22 +1540,22 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_raw_to_uri(pjsip_endpoint *endpt, /* Parse URI */ uri = pjsip_parse_uri(tdata->pool, dst_uri.ptr, dst_uri.slen, 0); if (uri == NULL) { - pjsip_tx_data_dec_ref(tdata); - return PJSIP_EINVALIDURI; + pjsip_tx_data_dec_ref(tdata); + return PJSIP_EINVALIDURI; } /* Build destination info. */ status = pjsip_get_dest_info(uri, NULL, tdata->pool, &dest_info); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - return status; + pjsip_tx_data_dec_ref(tdata); + return status; } /* Copy data (note: data_len may be zero!) */ tdata->buf.start = (char*) pj_pool_alloc(tdata->pool, data_len+1); tdata->buf.end = tdata->buf.start + data_len + 1; if (data_len) - pj_memcpy(tdata->buf.start, raw_data, data_len); + pj_memcpy(tdata->buf.start, raw_data, data_len); tdata->buf.cur = tdata->buf.start + data_len; /* Init send_raw_data */ @@ -1567,9 +1566,9 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_raw_to_uri(pjsip_endpoint *endpt, sraw_data->app_cb = cb; if (sel) { - sraw_data->sel = PJ_POOL_ALLOC_T(tdata->pool, pjsip_tpselector); - pj_memcpy(sraw_data->sel, sel, sizeof(pjsip_tpselector)); - pjsip_tpselector_add_ref(sraw_data->sel); + sraw_data->sel = PJ_POOL_ALLOC_T(tdata->pool, pjsip_tpselector); + pj_memcpy(sraw_data->sel, sel, sizeof(pjsip_tpselector)); + pjsip_tpselector_add_ref(sraw_data->sel); } /* Copy the destination host name to TX data */ @@ -1579,7 +1578,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_raw_to_uri(pjsip_endpoint *endpt, * The processing then resumed when the resolving callback is called. */ pjsip_endpt_resolve( endpt, tdata->pool, &dest_info, sraw_data, - &send_raw_resolver_callback); + &send_raw_resolver_callback); return PJ_SUCCESS; } @@ -1591,8 +1590,8 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_raw_to_uri(pjsip_endpoint *endpt, * address and transport. */ PJ_DEF(pj_status_t) pjsip_get_response_addr( pj_pool_t *pool, - pjsip_rx_data *rdata, - pjsip_response_addr *res_addr ) + pjsip_rx_data *rdata, + pjsip_response_addr *res_addr ) { pjsip_transport *src_transport = rdata->tp_info.transport; @@ -1601,7 +1600,7 @@ PJ_DEF(pj_status_t) pjsip_get_response_addr( pj_pool_t *pool, /* rdata must be a request message! */ PJ_ASSERT_RETURN(rdata->msg_info.msg->type == PJSIP_REQUEST_MSG, - PJ_EINVAL); + PJ_EINVAL); /* All requests must have "received" parameter. * This must always be done in transport layer. @@ -1611,81 +1610,81 @@ PJ_DEF(pj_status_t) pjsip_get_response_addr( pj_pool_t *pool, /* Do the calculation based on RFC 3261 Section 18.2.2 and RFC 3581 */ if (PJSIP_TRANSPORT_IS_RELIABLE(src_transport)) { - /* For reliable protocol such as TCP or SCTP, or TLS over those, the - * response MUST be sent using the existing connection to the source - * of the original request that created the transaction, if that - * connection is still open. - * If that connection is no longer open, the server SHOULD open a - * connection to the IP address in the received parameter, if present, - * using the port in the sent-by value, or the default port for that - * transport, if no port is specified. - * If that connection attempt fails, the server SHOULD use the - * procedures in [4] for servers in order to determine the IP address - * and port to open the connection and send the response to. - */ - res_addr->transport = rdata->tp_info.transport; - pj_memcpy(&res_addr->addr, &rdata->pkt_info.src_addr, - rdata->pkt_info.src_addr_len); - res_addr->addr_len = rdata->pkt_info.src_addr_len; - res_addr->dst_host.type=(pjsip_transport_type_e)src_transport->key.type; - res_addr->dst_host.flag = src_transport->flag; - pj_strdup( pool, &res_addr->dst_host.addr.host, - &rdata->msg_info.via->recvd_param); - res_addr->dst_host.addr.port = rdata->msg_info.via->sent_by.port; - if (res_addr->dst_host.addr.port == 0) { - res_addr->dst_host.addr.port = - pjsip_transport_get_default_port_for_type(res_addr->dst_host.type); - } + /* For reliable protocol such as TCP or SCTP, or TLS over those, the + * response MUST be sent using the existing connection to the source + * of the original request that created the transaction, if that + * connection is still open. + * If that connection is no longer open, the server SHOULD open a + * connection to the IP address in the received parameter, if present, + * using the port in the sent-by value, or the default port for that + * transport, if no port is specified. + * If that connection attempt fails, the server SHOULD use the + * procedures in [4] for servers in order to determine the IP address + * and port to open the connection and send the response to. + */ + res_addr->transport = rdata->tp_info.transport; + pj_memcpy(&res_addr->addr, &rdata->pkt_info.src_addr, + rdata->pkt_info.src_addr_len); + res_addr->addr_len = rdata->pkt_info.src_addr_len; + res_addr->dst_host.type=(pjsip_transport_type_e)src_transport->key.type; + res_addr->dst_host.flag = src_transport->flag; + pj_strdup( pool, &res_addr->dst_host.addr.host, + &rdata->msg_info.via->recvd_param); + res_addr->dst_host.addr.port = rdata->msg_info.via->sent_by.port; + if (res_addr->dst_host.addr.port == 0) { + res_addr->dst_host.addr.port = + pjsip_transport_get_default_port_for_type(res_addr->dst_host.type); + } } else if (rdata->msg_info.via->maddr_param.slen) { - /* Otherwise, if the Via header field value contains a maddr parameter, - * the response MUST be forwarded to the address listed there, using - * the port indicated in sent-by, or port 5060 if none is present. - * If the address is a multicast address, the response SHOULD be sent - * using the TTL indicated in the ttl parameter, or with a TTL of 1 if - * that parameter is not present. - */ - res_addr->transport = NULL; - res_addr->dst_host.type=(pjsip_transport_type_e)src_transport->key.type; - res_addr->dst_host.flag = src_transport->flag; - pj_strdup( pool, &res_addr->dst_host.addr.host, - &rdata->msg_info.via->maddr_param); - res_addr->dst_host.addr.port = rdata->msg_info.via->sent_by.port; - if (res_addr->dst_host.addr.port == 0) - res_addr->dst_host.addr.port = 5060; + /* Otherwise, if the Via header field value contains a maddr parameter, + * the response MUST be forwarded to the address listed there, using + * the port indicated in sent-by, or port 5060 if none is present. + * If the address is a multicast address, the response SHOULD be sent + * using the TTL indicated in the ttl parameter, or with a TTL of 1 if + * that parameter is not present. + */ + res_addr->transport = NULL; + res_addr->dst_host.type=(pjsip_transport_type_e)src_transport->key.type; + res_addr->dst_host.flag = src_transport->flag; + pj_strdup( pool, &res_addr->dst_host.addr.host, + &rdata->msg_info.via->maddr_param); + res_addr->dst_host.addr.port = rdata->msg_info.via->sent_by.port; + if (res_addr->dst_host.addr.port == 0) + res_addr->dst_host.addr.port = 5060; } else if (rdata->msg_info.via->rport_param >= 0) { - /* There is both a "received" parameter and an "rport" parameter, - * the response MUST be sent to the IP address listed in the "received" - * parameter, and the port in the "rport" parameter. - * The response MUST be sent from the same address and port that the - * corresponding request was received on. - */ - res_addr->transport = rdata->tp_info.transport; - pj_memcpy(&res_addr->addr, &rdata->pkt_info.src_addr, - rdata->pkt_info.src_addr_len); - res_addr->addr_len = rdata->pkt_info.src_addr_len; - res_addr->dst_host.type=(pjsip_transport_type_e)src_transport->key.type; - res_addr->dst_host.flag = src_transport->flag; - pj_strdup( pool, &res_addr->dst_host.addr.host, - &rdata->msg_info.via->recvd_param); - res_addr->dst_host.addr.port = rdata->msg_info.via->sent_by.port; - if (res_addr->dst_host.addr.port == 0) { - res_addr->dst_host.addr.port = - pjsip_transport_get_default_port_for_type(res_addr->dst_host.type); - } + /* There is both a "received" parameter and an "rport" parameter, + * the response MUST be sent to the IP address listed in the "received" + * parameter, and the port in the "rport" parameter. + * The response MUST be sent from the same address and port that the + * corresponding request was received on. + */ + res_addr->transport = rdata->tp_info.transport; + pj_memcpy(&res_addr->addr, &rdata->pkt_info.src_addr, + rdata->pkt_info.src_addr_len); + res_addr->addr_len = rdata->pkt_info.src_addr_len; + res_addr->dst_host.type=(pjsip_transport_type_e)src_transport->key.type; + res_addr->dst_host.flag = src_transport->flag; + pj_strdup( pool, &res_addr->dst_host.addr.host, + &rdata->msg_info.via->recvd_param); + res_addr->dst_host.addr.port = rdata->msg_info.via->sent_by.port; + if (res_addr->dst_host.addr.port == 0) { + res_addr->dst_host.addr.port = + pjsip_transport_get_default_port_for_type(res_addr->dst_host.type); + } } else { - res_addr->transport = NULL; - res_addr->dst_host.type=(pjsip_transport_type_e)src_transport->key.type; - res_addr->dst_host.flag = src_transport->flag; - pj_strdup( pool, &res_addr->dst_host.addr.host, - &rdata->msg_info.via->recvd_param); - res_addr->dst_host.addr.port = rdata->msg_info.via->sent_by.port; - if (res_addr->dst_host.addr.port == 0) { - res_addr->dst_host.addr.port = - pjsip_transport_get_default_port_for_type(res_addr->dst_host.type); - } + res_addr->transport = NULL; + res_addr->dst_host.type=(pjsip_transport_type_e)src_transport->key.type; + res_addr->dst_host.flag = src_transport->flag; + pj_strdup( pool, &res_addr->dst_host.addr.host, + &rdata->msg_info.via->recvd_param); + res_addr->dst_host.addr.port = rdata->msg_info.via->sent_by.port; + if (res_addr->dst_host.addr.port == 0) { + res_addr->dst_host.addr.port = + pjsip_transport_get_default_port_for_type(res_addr->dst_host.type); + } } return PJ_SUCCESS; @@ -1695,14 +1694,14 @@ PJ_DEF(pj_status_t) pjsip_get_response_addr( pj_pool_t *pool, * Callback called by transport during send_response. */ static void send_response_transport_cb(void *token, pjsip_tx_data *tdata, - pj_ssize_t sent) + pj_ssize_t sent) { pjsip_send_state *send_state = (pjsip_send_state*) token; pj_bool_t cont = PJ_FALSE; /* Call callback, if any. */ if (send_state->app_cb) - (*send_state->app_cb)(send_state, sent, &cont); + (*send_state->app_cb)(send_state, sent, &cont); /* Decrement transport reference counter. */ pjsip_transport_dec_ref(send_state->cur_transport); @@ -1715,36 +1714,36 @@ static void send_response_transport_cb(void *token, pjsip_tx_data *tdata, * Resolver calback during send_response. */ static void send_response_resolver_cb( pj_status_t status, void *token, - const pjsip_server_addresses *addr ) + const pjsip_server_addresses *addr ) { pjsip_send_state *send_state = (pjsip_send_state*) token; if (status != PJ_SUCCESS) { - if (send_state->app_cb) { - pj_bool_t cont = PJ_FALSE; - (*send_state->app_cb)(send_state, -status, &cont); - } - pjsip_tx_data_dec_ref(send_state->tdata); - return; + if (send_state->app_cb) { + pj_bool_t cont = PJ_FALSE; + (*send_state->app_cb)(send_state, -status, &cont); + } + pjsip_tx_data_dec_ref(send_state->tdata); + return; } /* Only handle the first address resolved. */ /* Acquire transport. */ status = pjsip_endpt_acquire_transport2(send_state->endpt, - addr->entry[0].type, - &addr->entry[0].addr, - addr->entry[0].addr_len, - &send_state->tdata->tp_sel, - send_state->tdata, - &send_state->cur_transport); + addr->entry[0].type, + &addr->entry[0].addr, + addr->entry[0].addr_len, + &send_state->tdata->tp_sel, + send_state->tdata, + &send_state->cur_transport); if (status != PJ_SUCCESS) { - if (send_state->app_cb) { - pj_bool_t cont = PJ_FALSE; - (*send_state->app_cb)(send_state, -status, &cont); - } - pjsip_tx_data_dec_ref(send_state->tdata); - return; + if (send_state->app_cb) { + pj_bool_t cont = PJ_FALSE; + (*send_state->app_cb)(send_state, -status, &cont); + } + pjsip_tx_data_dec_ref(send_state->tdata); + return; } /* Update address in send_state. */ @@ -1752,20 +1751,20 @@ static void send_response_resolver_cb( pj_status_t status, void *token, /* Send response using the transoprt. */ status = pjsip_transport_send( send_state->cur_transport, - send_state->tdata, - &addr->entry[0].addr, - addr->entry[0].addr_len, - send_state, - &send_response_transport_cb); + send_state->tdata, + &addr->entry[0].addr, + addr->entry[0].addr_len, + send_state, + &send_response_transport_cb); if (status == PJ_SUCCESS) { - pj_ssize_t sent = send_state->tdata->buf.cur - - send_state->tdata->buf.start; - send_response_transport_cb(send_state, send_state->tdata, sent); + pj_ssize_t sent = send_state->tdata->buf.cur - + send_state->tdata->buf.start; + send_response_transport_cb(send_state, send_state->tdata, sent); } else if (status == PJ_EPENDING) { - /* Transport callback will be called later. */ + /* Transport callback will be called later. */ } else { - send_response_transport_cb(send_state, send_state->tdata, -status); + send_response_transport_cb(send_state, send_state->tdata, -status); } } @@ -1773,10 +1772,10 @@ static void send_response_resolver_cb( pj_status_t status, void *token, * Send response. */ PJ_DEF(pj_status_t) pjsip_endpt_send_response( pjsip_endpoint *endpt, - pjsip_response_addr *res_addr, - pjsip_tx_data *tdata, - void *token, - pjsip_send_callback cb) + pjsip_response_addr *res_addr, + pjsip_tx_data *tdata, + void *token, + pjsip_send_callback cb) { /* Determine which transports and addresses to send the response, * based on Section 18.2.2 of RFC 3261. @@ -1792,35 +1791,35 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_response( pjsip_endpoint *endpt, send_state->app_cb = cb; if (res_addr->transport != NULL) { - send_state->cur_transport = res_addr->transport; - pjsip_transport_add_ref(send_state->cur_transport); - - status = pjsip_transport_send( send_state->cur_transport, tdata, - &res_addr->addr, - res_addr->addr_len, - send_state, - &send_response_transport_cb ); - if (status == PJ_SUCCESS) { - pj_ssize_t sent = tdata->buf.cur - tdata->buf.start; - send_response_transport_cb(send_state, tdata, sent); - return PJ_SUCCESS; - } else if (status == PJ_EPENDING) { - /* Callback will be called later. */ - return PJ_SUCCESS; - } else { - pjsip_transport_dec_ref(send_state->cur_transport); - return status; - } + send_state->cur_transport = res_addr->transport; + pjsip_transport_add_ref(send_state->cur_transport); + + status = pjsip_transport_send( send_state->cur_transport, tdata, + &res_addr->addr, + res_addr->addr_len, + send_state, + &send_response_transport_cb ); + if (status == PJ_SUCCESS) { + pj_ssize_t sent = tdata->buf.cur - tdata->buf.start; + send_response_transport_cb(send_state, tdata, sent); + return PJ_SUCCESS; + } else if (status == PJ_EPENDING) { + /* Callback will be called later. */ + return PJ_SUCCESS; + } else { + pjsip_transport_dec_ref(send_state->cur_transport); + return status; + } } else { - /* Copy the destination host name to TX data */ - if (!tdata->dest_info.name.slen) { - pj_strdup(tdata->pool, &tdata->dest_info.name, - &res_addr->dst_host.addr.host); - } - - pjsip_endpt_resolve(endpt, tdata->pool, &res_addr->dst_host, - send_state, &send_response_resolver_cb); - return PJ_SUCCESS; + /* Copy the destination host name to TX data */ + if (!tdata->dest_info.name.slen) { + pj_strdup(tdata->pool, &tdata->dest_info.name, + &res_addr->dst_host.addr.host); + } + + pjsip_endpt_resolve(endpt, tdata->pool, &res_addr->dst_host, + send_state, &send_response_resolver_cb); + return PJ_SUCCESS; } } @@ -1828,18 +1827,18 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_response( pjsip_endpoint *endpt, * Send response combo */ PJ_DEF(pj_status_t) pjsip_endpt_send_response2( pjsip_endpoint *endpt, - pjsip_rx_data *rdata, - pjsip_tx_data *tdata, - void *token, - pjsip_send_callback cb) + pjsip_rx_data *rdata, + pjsip_tx_data *tdata, + void *token, + pjsip_send_callback cb) { pjsip_response_addr res_addr; pj_status_t status; status = pjsip_get_response_addr(tdata->pool, rdata, &res_addr); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - return PJ_SUCCESS; + pjsip_tx_data_dec_ref(tdata); + return PJ_SUCCESS; } status = pjsip_endpt_send_response(endpt, &res_addr, tdata, token, cb); @@ -1851,11 +1850,11 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_response2( pjsip_endpoint *endpt, * Send response */ PJ_DEF(pj_status_t) pjsip_endpt_respond_stateless( pjsip_endpoint *endpt, - pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - const pjsip_hdr *hdr_list, - const pjsip_msg_body *body) + pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + const pjsip_hdr *hdr_list, + const pjsip_msg_body *body) { pj_status_t status; pjsip_response_addr res_addr; @@ -1864,7 +1863,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_respond_stateless( pjsip_endpoint *endpt, /* Verify arguments. */ PJ_ASSERT_RETURN(endpt && rdata, PJ_EINVAL); PJ_ASSERT_RETURN(rdata->msg_info.msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); /* Check that no UAS transaction has been created for this request. * If UAS transaction has been created for this request, application @@ -1874,41 +1873,41 @@ PJ_DEF(pj_status_t) pjsip_endpt_respond_stateless( pjsip_endpoint *endpt, /* Create response message */ status = pjsip_endpt_create_response( endpt, rdata, st_code, st_text, - &tdata); + &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Add the message headers, if any */ if (hdr_list) { - const pjsip_hdr *hdr = hdr_list->next; - while (hdr != hdr_list) { - pjsip_msg_add_hdr(tdata->msg, - (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, hdr) ); - hdr = hdr->next; - } + const pjsip_hdr *hdr = hdr_list->next; + while (hdr != hdr_list) { + pjsip_msg_add_hdr(tdata->msg, + (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, hdr) ); + hdr = hdr->next; + } } /* Add the message body, if any. */ if (body) { - tdata->msg->body = pjsip_msg_body_clone( tdata->pool, body ); - if (tdata->msg->body == NULL) { - pjsip_tx_data_dec_ref(tdata); - return status; - } + tdata->msg->body = pjsip_msg_body_clone( tdata->pool, body ); + if (tdata->msg->body == NULL) { + pjsip_tx_data_dec_ref(tdata); + return status; + } } /* Get where to send request. */ status = pjsip_get_response_addr( tdata->pool, rdata, &res_addr ); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - return status; + pjsip_tx_data_dec_ref(tdata); + return status; } /* Send! */ status = pjsip_endpt_send_response( endpt, &res_addr, tdata, NULL, NULL ); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - return status; + pjsip_tx_data_dec_ref(tdata); + return status; } return PJ_SUCCESS; diff --git a/pjsip/src/pjsip/sip_util_proxy.c b/pjsip/src/pjsip/sip_util_proxy.c index 2264accbf0..afef3f0ef8 100644 --- a/pjsip/src/pjsip/sip_util_proxy.c +++ b/pjsip/src/pjsip/sip_util_proxy.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -37,24 +36,24 @@ * * Once a transmit data is created, the reference counter is initialized to 1. * - * @param endpt The endpoint instance. - * @param rdata The incoming SIP message. + * @param endpt The endpoint instance. + * @param rdata The incoming SIP message. * @param p_tdata Pointer to receive the transmit data containing - * the duplicated message. + * the duplicated message. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ /* PJ_DEF(pj_status_t) pjsip_endpt_clone_msg( pjsip_endpoint *endpt, - const pjsip_rx_data *rdata, - pjsip_tx_data **p_tdata) + const pjsip_rx_data *rdata, + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pj_status_t status; status = pjsip_endpt_create_tdata(endpt, &tdata); if (status != PJ_SUCCESS) - return status; + return status; tdata->msg = pjsip_msg_clone(tdata->pool, rdata->msg_info.msg); @@ -72,11 +71,11 @@ PJ_DEF(pj_status_t) pjsip_endpt_clone_msg( pjsip_endpoint *endpt, * in uri. */ PJ_DEF(pj_status_t) pjsip_endpt_create_request_fwd(pjsip_endpoint *endpt, - pjsip_rx_data *rdata, - const pjsip_uri *uri, - const pj_str_t *branch, - unsigned options, - pjsip_tx_data **p_tdata) + pjsip_rx_data *rdata, + const pjsip_uri *uri, + const pj_str_t *branch, + unsigned options, + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pj_status_t status; @@ -85,7 +84,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_request_fwd(pjsip_endpoint *endpt, PJ_ASSERT_RETURN(endpt && rdata && p_tdata, PJ_EINVAL); PJ_ASSERT_RETURN(rdata->msg_info.msg->type == PJSIP_REQUEST_MSG, - PJSIP_ENOTREQUESTMSG); + PJSIP_ENOTREQUESTMSG); PJ_UNUSED_ARG(options); @@ -112,126 +111,126 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_request_fwd(pjsip_endpoint *endpt, status = pjsip_endpt_create_tdata(endpt, &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Always increment ref counter to 1 */ pjsip_tx_data_add_ref(tdata); /* Duplicate the request */ PJ_TRY { - pjsip_msg *dst; - const pjsip_msg *src = rdata->msg_info.msg; - const pjsip_hdr *hsrc; - - /* Create the request */ - tdata->msg = dst = pjsip_msg_create(tdata->pool, PJSIP_REQUEST_MSG); - - /* Duplicate request method */ - pjsip_method_copy(tdata->pool, &tdata->msg->line.req.method, - &src->line.req.method); - - /* Set request URI */ - if (uri) { - dst->line.req.uri = (pjsip_uri*) - pjsip_uri_clone(tdata->pool, uri); - } else { - dst->line.req.uri= (pjsip_uri*) - pjsip_uri_clone(tdata->pool, src->line.req.uri); - } - - /* Clone ALL headers */ - hsrc = src->hdr.next; - while (hsrc != &src->hdr) { - - pjsip_hdr *hdst; - - /* If this is the top-most Via header, insert our own before - * cloning the header. - */ - if (hsrc == (pjsip_hdr*)rdata->msg_info.via) { - pjsip_via_hdr *hvia; - hvia = pjsip_via_hdr_create(tdata->pool); - if (branch) - pj_strdup(tdata->pool, &hvia->branch_param, branch); - else { - pj_str_t new_branch = pjsip_calculate_branch_id(rdata); - pj_strdup(tdata->pool, &hvia->branch_param, &new_branch); - } - pjsip_msg_add_hdr(dst, (pjsip_hdr*)hvia); - - } - /* Skip Content-Type and Content-Length as these would be - * generated when the the message is printed. - */ - else if (hsrc->type == PJSIP_H_CONTENT_LENGTH || - hsrc->type == PJSIP_H_CONTENT_TYPE) { - - hsrc = hsrc->next; - continue; - - } + pjsip_msg *dst; + const pjsip_msg *src = rdata->msg_info.msg; + const pjsip_hdr *hsrc; + + /* Create the request */ + tdata->msg = dst = pjsip_msg_create(tdata->pool, PJSIP_REQUEST_MSG); + + /* Duplicate request method */ + pjsip_method_copy(tdata->pool, &tdata->msg->line.req.method, + &src->line.req.method); + + /* Set request URI */ + if (uri) { + dst->line.req.uri = (pjsip_uri*) + pjsip_uri_clone(tdata->pool, uri); + } else { + dst->line.req.uri= (pjsip_uri*) + pjsip_uri_clone(tdata->pool, src->line.req.uri); + } + + /* Clone ALL headers */ + hsrc = src->hdr.next; + while (hsrc != &src->hdr) { + + pjsip_hdr *hdst; + + /* If this is the top-most Via header, insert our own before + * cloning the header. + */ + if (hsrc == (pjsip_hdr*)rdata->msg_info.via) { + pjsip_via_hdr *hvia; + hvia = pjsip_via_hdr_create(tdata->pool); + if (branch) + pj_strdup(tdata->pool, &hvia->branch_param, branch); + else { + pj_str_t new_branch = pjsip_calculate_branch_id(rdata); + pj_strdup(tdata->pool, &hvia->branch_param, &new_branch); + } + pjsip_msg_add_hdr(dst, (pjsip_hdr*)hvia); + + } + /* Skip Content-Type and Content-Length as these would be + * generated when the the message is printed. + */ + else if (hsrc->type == PJSIP_H_CONTENT_LENGTH || + hsrc->type == PJSIP_H_CONTENT_TYPE) { + + hsrc = hsrc->next; + continue; + + } #if 0 - /* If this is the top-most Route header and it indicates loose - * route, remove the header. - */ - else if (hsrc == (pjsip_hdr*)rdata->msg_info.route) { - - const pjsip_route_hdr *hroute = (const pjsip_route_hdr*) hsrc; - const pjsip_sip_uri *sip_uri; - - if (!PJSIP_URI_SCHEME_IS_SIP(hroute->name_addr.uri) && - !PJSIP_URI_SCHEME_IS_SIPS(hroute->name_addr.uri)) - { - /* This is a bad request! */ - status = PJSIP_EINVALIDHDR; - goto on_error; - } - - sip_uri = (pjsip_sip_uri*) hroute->name_addr.uri; - - if (sip_uri->lr_param) { - /* Yes lr param is present, skip this Route header */ - hsrc = hsrc->next; - continue; - } - } + /* If this is the top-most Route header and it indicates loose + * route, remove the header. + */ + else if (hsrc == (pjsip_hdr*)rdata->msg_info.route) { + + const pjsip_route_hdr *hroute = (const pjsip_route_hdr*) hsrc; + const pjsip_sip_uri *sip_uri; + + if (!PJSIP_URI_SCHEME_IS_SIP(hroute->name_addr.uri) && + !PJSIP_URI_SCHEME_IS_SIPS(hroute->name_addr.uri)) + { + /* This is a bad request! */ + status = PJSIP_EINVALIDHDR; + goto on_error; + } + + sip_uri = (pjsip_sip_uri*) hroute->name_addr.uri; + + if (sip_uri->lr_param) { + /* Yes lr param is present, skip this Route header */ + hsrc = hsrc->next; + continue; + } + } #endif - /* Clone the header */ - hdst = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, hsrc); + /* Clone the header */ + hdst = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, hsrc); - /* If this is Max-Forward header, decrement the value */ - if (hdst->type == PJSIP_H_MAX_FORWARDS) { - pjsip_max_fwd_hdr *hmaxfwd = (pjsip_max_fwd_hdr*)hdst; - --hmaxfwd->ivalue; - } + /* If this is Max-Forward header, decrement the value */ + if (hdst->type == PJSIP_H_MAX_FORWARDS) { + pjsip_max_fwd_hdr *hmaxfwd = (pjsip_max_fwd_hdr*)hdst; + --hmaxfwd->ivalue; + } - /* Append header to new request */ - pjsip_msg_add_hdr(dst, hdst); + /* Append header to new request */ + pjsip_msg_add_hdr(dst, hdst); - hsrc = hsrc->next; - } + hsrc = hsrc->next; + } - /* 16.6.3: - * If the copy does not contain a Max-Forwards header field, the + /* 16.6.3: + * If the copy does not contain a Max-Forwards header field, the * proxy MUST add one with a field value, which SHOULD be 70. - */ - if (rdata->msg_info.max_fwd == NULL) { - pjsip_max_fwd_hdr *hmaxfwd = - pjsip_max_fwd_hdr_create(tdata->pool, 70); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hmaxfwd); - } - - /* Clone request body */ - if (src->body) { - dst->body = pjsip_msg_body_clone(tdata->pool, src->body); - } + */ + if (rdata->msg_info.max_fwd == NULL) { + pjsip_max_fwd_hdr *hmaxfwd = + pjsip_max_fwd_hdr_create(tdata->pool, 70); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hmaxfwd); + } + + /* Clone request body */ + if (src->body) { + dst->body = pjsip_msg_body_clone(tdata->pool, src->body); + } } PJ_CATCH_ANY { - status = PJ_ENOMEM; - goto on_error; + status = PJ_ENOMEM; + goto on_error; } PJ_END @@ -247,9 +246,9 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_request_fwd(pjsip_endpoint *endpt, PJ_DEF(pj_status_t) pjsip_endpt_create_response_fwd( pjsip_endpoint *endpt, - pjsip_rx_data *rdata, - unsigned options, - pjsip_tx_data **p_tdata) + pjsip_rx_data *rdata, + unsigned options, + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pj_status_t status; @@ -259,59 +258,59 @@ PJ_DEF(pj_status_t) pjsip_endpt_create_response_fwd( pjsip_endpoint *endpt, status = pjsip_endpt_create_tdata(endpt, &tdata); if (status != PJ_SUCCESS) - return status; + return status; pjsip_tx_data_add_ref(tdata); PJ_TRY { - pjsip_msg *dst; - const pjsip_msg *src = rdata->msg_info.msg; - const pjsip_hdr *hsrc; + pjsip_msg *dst; + const pjsip_msg *src = rdata->msg_info.msg; + const pjsip_hdr *hsrc; - /* Create the request */ - tdata->msg = dst = pjsip_msg_create(tdata->pool, PJSIP_RESPONSE_MSG); + /* Create the request */ + tdata->msg = dst = pjsip_msg_create(tdata->pool, PJSIP_RESPONSE_MSG); - /* Clone the status line */ - dst->line.status.code = src->line.status.code; - pj_strdup(tdata->pool, &dst->line.status.reason, - &src->line.status.reason); + /* Clone the status line */ + dst->line.status.code = src->line.status.code; + pj_strdup(tdata->pool, &dst->line.status.reason, + &src->line.status.reason); - /* Duplicate all headers */ - hsrc = src->hdr.next; - while (hsrc != &src->hdr) { - - /* Skip Content-Type and Content-Length as these would be - * generated when the the message is printed. - */ - if (hsrc->type == PJSIP_H_CONTENT_LENGTH || - hsrc->type == PJSIP_H_CONTENT_TYPE) { + /* Duplicate all headers */ + hsrc = src->hdr.next; + while (hsrc != &src->hdr) { + + /* Skip Content-Type and Content-Length as these would be + * generated when the the message is printed. + */ + if (hsrc->type == PJSIP_H_CONTENT_LENGTH || + hsrc->type == PJSIP_H_CONTENT_TYPE) { - hsrc = hsrc->next; - continue; + hsrc = hsrc->next; + continue; - } - /* Remove the first Via header */ - else if (hsrc == (pjsip_hdr*) rdata->msg_info.via) { + } + /* Remove the first Via header */ + else if (hsrc == (pjsip_hdr*) rdata->msg_info.via) { - hsrc = hsrc->next; - continue; - } + hsrc = hsrc->next; + continue; + } - pjsip_msg_add_hdr(dst, - (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, hsrc)); + pjsip_msg_add_hdr(dst, + (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, hsrc)); - hsrc = hsrc->next; - } + hsrc = hsrc->next; + } - /* Clone message body */ - if (src->body) - dst->body = pjsip_msg_body_clone(tdata->pool, src->body); + /* Clone message body */ + if (src->body) + dst->body = pjsip_msg_body_clone(tdata->pool, src->body); } PJ_CATCH_ANY { - status = PJ_ENOMEM; - goto on_error; + status = PJ_ENOMEM; + goto on_error; } PJ_END; @@ -328,8 +327,8 @@ static void digest2str(const unsigned char digest[], char *output) { int i; for (i = 0; i<16; ++i) { - pj_val_to_hex_digit(digest[i], output); - output += 2; + pj_val_to_hex_digit(digest[i], output); + output += 2; } } @@ -346,23 +345,23 @@ PJ_DEF(pj_str_t) pjsip_calculate_branch_id( pjsip_rx_data *rdata ) * a branch value from GUID . */ if (pj_strnicmp(&rdata->msg_info.via->branch_param, - &rfc3261_branch, PJSIP_RFC3261_BRANCH_LEN) != 0 ) + &rfc3261_branch, PJSIP_RFC3261_BRANCH_LEN) != 0 ) { - pj_str_t tmp; + pj_str_t tmp; - branch.ptr = (char*) - pj_pool_alloc(rdata->tp_info.pool, PJSIP_MAX_BRANCH_LEN); - branch.slen = PJSIP_RFC3261_BRANCH_LEN; - pj_memcpy(branch.ptr, PJSIP_RFC3261_BRANCH_ID, - PJSIP_RFC3261_BRANCH_LEN); + branch.ptr = (char*) + pj_pool_alloc(rdata->tp_info.pool, PJSIP_MAX_BRANCH_LEN); + branch.slen = PJSIP_RFC3261_BRANCH_LEN; + pj_memcpy(branch.ptr, PJSIP_RFC3261_BRANCH_ID, + PJSIP_RFC3261_BRANCH_LEN); - tmp.ptr = branch.ptr + PJSIP_RFC3261_BRANCH_LEN + 2; - *(tmp.ptr-2) = (pj_int8_t)(branch.slen+73); - *(tmp.ptr-1) = (pj_int8_t)(branch.slen+99); - pj_generate_unique_string( &tmp ); + tmp.ptr = branch.ptr + PJSIP_RFC3261_BRANCH_LEN + 2; + *(tmp.ptr-2) = (pj_int8_t)(branch.slen+73); + *(tmp.ptr-1) = (pj_int8_t)(branch.slen+99); + pj_generate_unique_string( &tmp ); - branch.slen = PJSIP_MAX_BRANCH_LEN; - return branch; + branch.slen = PJSIP_MAX_BRANCH_LEN; + return branch; } /* Create branch ID for new request by calculating MD5 hash @@ -370,12 +369,12 @@ PJ_DEF(pj_str_t) pjsip_calculate_branch_id( pjsip_rx_data *rdata ) */ pj_md5_init(&ctx); pj_md5_update(&ctx, (pj_uint8_t*)rdata->msg_info.via->branch_param.ptr, - (unsigned)rdata->msg_info.via->branch_param.slen); + (unsigned)rdata->msg_info.via->branch_param.slen); pj_md5_final(&ctx, digest); branch.ptr = (char*) - pj_pool_alloc(rdata->tp_info.pool, - 34 + PJSIP_RFC3261_BRANCH_LEN); + pj_pool_alloc(rdata->tp_info.pool, + 34 + PJSIP_RFC3261_BRANCH_LEN); pj_memcpy(branch.ptr, PJSIP_RFC3261_BRANCH_ID, PJSIP_RFC3261_BRANCH_LEN); branch.slen = PJSIP_RFC3261_BRANCH_LEN; *(branch.ptr+PJSIP_RFC3261_BRANCH_LEN) = (pj_int8_t)(branch.slen+73); diff --git a/pjsip/src/pjsip/sip_util_proxy_wrap.cpp b/pjsip/src/pjsip/sip_util_proxy_wrap.cpp index 3cbd3bd75f..8254908997 100644 --- a/pjsip/src/pjsip/sip_util_proxy_wrap.cpp +++ b/pjsip/src/pjsip/sip_util_proxy_wrap.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjsip/src/pjsip/sip_util_statefull.c b/pjsip/src/pjsip/sip_util_statefull.c index 9036a02769..005c27ad8c 100644 --- a/pjsip/src/pjsip/sip_util_statefull.c +++ b/pjsip/src/pjsip/sip_util_statefull.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -40,19 +39,19 @@ static void mod_util_on_tsx_state(pjsip_transaction*, pjsip_event*); pjsip_module mod_stateful_util = { - NULL, NULL, /* prev, next. */ - { "mod-stateful-util", 17 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - NULL, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - &mod_util_on_tsx_state, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-stateful-util", 17 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + &mod_util_on_tsx_state, /* on_tsx_state() */ }; static void mod_util_on_tsx_state(pjsip_transaction *tsx, pjsip_event *event) @@ -63,14 +62,14 @@ static void mod_util_on_tsx_state(pjsip_transaction *tsx, pjsip_event *event) * verify the event type. */ if (mod_stateful_util.id < 0 || event->type != PJSIP_EVENT_TSX_STATE) - return; + return; tsx_data = (struct tsx_data*) tsx->mod_data[mod_stateful_util.id]; if (tsx_data == NULL) - return; + return; if (tsx->status_code < 200) - return; + return; /* Call the callback, if any, and prevent the callback to be called again * by clearing the transaction's module_data. @@ -78,16 +77,16 @@ static void mod_util_on_tsx_state(pjsip_transaction *tsx, pjsip_event *event) tsx->mod_data[mod_stateful_util.id] = NULL; if (tsx_data->cb) { - (*tsx_data->cb)(tsx_data->token, event); + (*tsx_data->cb)(tsx_data->token, event); } } PJ_DEF(pj_status_t) pjsip_endpt_send_request( pjsip_endpoint *endpt, - pjsip_tx_data *tdata, - pj_int32_t timeout, - void *token, - pjsip_endpt_send_callback cb) + pjsip_tx_data *tdata, + pj_int32_t timeout, + void *token, + pjsip_endpt_send_callback cb) { pjsip_transaction *tsx; struct tsx_data *tsx_data; @@ -102,8 +101,8 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_request( pjsip_endpoint *endpt, status = pjsip_tsx_create_uac(&mod_stateful_util, tdata, &tsx); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - return status; + pjsip_tx_data_dec_ref(tdata); + return status; } pjsip_tsx_set_transport(tsx, &tdata->tp_sel); @@ -116,7 +115,7 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_request( pjsip_endpoint *endpt, status = pjsip_tsx_send_msg(tsx, NULL); if (status != PJ_SUCCESS) - pjsip_tx_data_dec_ref(tdata); + pjsip_tx_data_dec_ref(tdata); return status; } @@ -126,13 +125,13 @@ PJ_DEF(pj_status_t) pjsip_endpt_send_request( pjsip_endpoint *endpt, * Send response statefully. */ PJ_DEF(pj_status_t) pjsip_endpt_respond( pjsip_endpoint *endpt, - pjsip_module *tsx_user, - pjsip_rx_data *rdata, - int st_code, - const pj_str_t *st_text, - const pjsip_hdr *hdr_list, - const pjsip_msg_body *body, - pjsip_transaction **p_tsx ) + pjsip_module *tsx_user, + pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + const pjsip_hdr *hdr_list, + const pjsip_msg_body *body, + pjsip_transaction **p_tsx ) { pj_status_t status; pjsip_tx_data *tdata; @@ -145,34 +144,34 @@ PJ_DEF(pj_status_t) pjsip_endpt_respond( pjsip_endpoint *endpt, /* Create response message */ status = pjsip_endpt_create_response( endpt, rdata, st_code, st_text, - &tdata); + &tdata); if (status != PJ_SUCCESS) - return status; + return status; /* Add the message headers, if any */ if (hdr_list) { - const pjsip_hdr *hdr = hdr_list->next; - while (hdr != hdr_list) { - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) - pjsip_hdr_clone(tdata->pool, hdr) ); - hdr = hdr->next; - } + const pjsip_hdr *hdr = hdr_list->next; + while (hdr != hdr_list) { + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, hdr) ); + hdr = hdr->next; + } } /* Add the message body, if any. */ if (body) { - tdata->msg->body = pjsip_msg_body_clone( tdata->pool, body ); - if (tdata->msg->body == NULL) { - pjsip_tx_data_dec_ref(tdata); - return status; - } + tdata->msg->body = pjsip_msg_body_clone( tdata->pool, body ); + if (tdata->msg->body == NULL) { + pjsip_tx_data_dec_ref(tdata); + return status; + } } /* Create UAS transaction. */ status = pjsip_tsx_create_uas(tsx_user, rdata, &tsx); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - return status; + pjsip_tx_data_dec_ref(tdata); + return status; } /* Feed the request to the transaction. */ @@ -181,9 +180,9 @@ PJ_DEF(pj_status_t) pjsip_endpt_respond( pjsip_endpoint *endpt, /* Send the message. */ status = pjsip_tsx_send_msg(tsx, tdata); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); + pjsip_tx_data_dec_ref(tdata); } else if (p_tsx) { - *p_tsx = tsx; + *p_tsx = tsx; } return status; diff --git a/pjsip/src/pjsip/sip_util_wrap.cpp b/pjsip/src/pjsip/sip_util_wrap.cpp index a6878a0205..b9f0d49b2f 100644 --- a/pjsip/src/pjsip/sip_util_wrap.cpp +++ b/pjsip/src/pjsip/sip_util_wrap.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) * diff --git a/pjsip/src/pjsua-lib/pjsua_acc.c b/pjsip/src/pjsua-lib/pjsua_acc.c index 8275c39256..9982b03c73 100644 --- a/pjsip/src/pjsua-lib/pjsua_acc.c +++ b/pjsip/src/pjsua-lib/pjsua_acc.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,14 +20,14 @@ #include -#define THIS_FILE "pjsua_acc.c" +#define THIS_FILE "pjsua_acc.c" enum { - OUTBOUND_UNKNOWN, // status unknown - OUTBOUND_WANTED, // initiated in registration - OUTBOUND_ACTIVE, // got positive response from server - OUTBOUND_NA // not wanted or got negative response from server + OUTBOUND_UNKNOWN, // status unknown + OUTBOUND_WANTED, // initiated in registration + OUTBOUND_ACTIVE, // got positive response from server + OUTBOUND_NA // not wanted or got negative response from server }; @@ -51,7 +50,7 @@ PJ_DEF(unsigned) pjsua_acc_get_count(void) PJ_DEF(pj_bool_t) pjsua_acc_is_valid(pjsua_acc_id acc_id) { return acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc) && - pjsua_var.acc[acc_id].valid; + pjsua_var.acc[acc_id].valid; } @@ -78,8 +77,8 @@ PJ_DEF(pjsua_acc_id) pjsua_acc_get_default(void) * Copy account configuration. */ PJ_DEF(void) pjsua_acc_config_dup( pj_pool_t *pool, - pjsua_acc_config *dst, - const pjsua_acc_config *src) + pjsua_acc_config *dst, + const pjsua_acc_config *src) { unsigned i; @@ -89,9 +88,9 @@ PJ_DEF(void) pjsua_acc_config_dup( pj_pool_t *pool, pj_strdup_with_null(pool, &dst->reg_uri, &src->reg_uri); pj_strdup_with_null(pool, &dst->force_contact, &src->force_contact); pj_strdup_with_null(pool, &dst->reg_contact_params, - &src->reg_contact_params); + &src->reg_contact_params); pj_strdup_with_null(pool, &dst->reg_contact_uri_params, - &src->reg_contact_uri_params); + &src->reg_contact_uri_params); pj_strdup_with_null(pool, &dst->contact_params, &src->contact_params); pj_strdup_with_null(pool, &dst->contact_uri_params, &src->contact_uri_params); @@ -102,36 +101,36 @@ PJ_DEF(void) pjsua_acc_config_dup( pj_pool_t *pool, dst->proxy_cnt = src->proxy_cnt; for (i=0; iproxy_cnt; ++i) - pj_strdup_with_null(pool, &dst->proxy[i], &src->proxy[i]); + pj_strdup_with_null(pool, &dst->proxy[i], &src->proxy[i]); dst->reg_timeout = src->reg_timeout; dst->reg_delay_before_refresh = src->reg_delay_before_refresh; dst->cred_count = src->cred_count; for (i=0; icred_count; ++i) { - pjsip_cred_dup(pool, &dst->cred_info[i], &src->cred_info[i]); + pjsip_cred_dup(pool, &dst->cred_info[i], &src->cred_info[i]); } pj_list_init(&dst->reg_hdr_list); if (!pj_list_empty(&src->reg_hdr_list)) { - const pjsip_hdr *hdr; + const pjsip_hdr *hdr; - hdr = src->reg_hdr_list.next; - while (hdr != &src->reg_hdr_list) { - pj_list_push_back(&dst->reg_hdr_list, pjsip_hdr_clone(pool, hdr)); - hdr = hdr->next; - } + hdr = src->reg_hdr_list.next; + while (hdr != &src->reg_hdr_list) { + pj_list_push_back(&dst->reg_hdr_list, pjsip_hdr_clone(pool, hdr)); + hdr = hdr->next; + } } pj_list_init(&dst->sub_hdr_list); if (!pj_list_empty(&src->sub_hdr_list)) { - const pjsip_hdr *hdr; + const pjsip_hdr *hdr; - hdr = src->sub_hdr_list.next; - while (hdr != &src->sub_hdr_list) { - pj_list_push_back(&dst->sub_hdr_list, pjsip_hdr_clone(pool, hdr)); - hdr = hdr->next; - } + hdr = src->sub_hdr_list.next; + while (hdr != &src->sub_hdr_list) { + pj_list_push_back(&dst->sub_hdr_list, pjsip_hdr_clone(pool, hdr)); + hdr = hdr->next; + } } pjsip_auth_clt_pref_dup(pool, &dst->auth_pref, &src->auth_pref); @@ -158,7 +157,7 @@ static pj_uint32_t calc_proxy_crc(const pj_str_t proxy[], pj_size_t cnt) pj_crc32_init(&ctx); for (i=0; icfg; if (acc_cfg->rfc5626_instance_id.slen == 0) { - const pj_str_t *hostname; - pj_uint32_t hval; - pj_size_t pos; - char instprm[] = ";+sip.instance=\"\""; - - hostname = pj_gethostname(); - pos = pj_ansi_strlen(instprm) - 10; - hval = pj_hash_calc(0, hostname->ptr, (unsigned)hostname->slen); - pj_val_to_hex_digit(((char*)&hval)[0], instprm + pos + 0); - pj_val_to_hex_digit(((char*)&hval)[1], instprm + pos + 2); - pj_val_to_hex_digit(((char*)&hval)[2], instprm + pos + 4); - pj_val_to_hex_digit(((char*)&hval)[3], instprm + pos + 6); - - pj_strdup2(acc->pool, &acc->rfc5626_instprm, instprm); + const pj_str_t *hostname; + pj_uint32_t hval; + pj_size_t pos; + char instprm[] = ";+sip.instance=\"\""; + + hostname = pj_gethostname(); + pos = pj_ansi_strlen(instprm) - 10; + hval = pj_hash_calc(0, hostname->ptr, (unsigned)hostname->slen); + pj_val_to_hex_digit(((char*)&hval)[0], instprm + pos + 0); + pj_val_to_hex_digit(((char*)&hval)[1], instprm + pos + 2); + pj_val_to_hex_digit(((char*)&hval)[2], instprm + pos + 4); + pj_val_to_hex_digit(((char*)&hval)[3], instprm + pos + 6); + + pj_strdup2(acc->pool, &acc->rfc5626_instprm, instprm); } else { - const char *prmname = ";+sip.instance=\""; - pj_size_t len; + const char *prmname = ";+sip.instance=\""; + pj_size_t len; - len = pj_ansi_strlen(prmname) + acc_cfg->rfc5626_instance_id.slen + 1; - acc->rfc5626_instprm.ptr = (char*)pj_pool_alloc(acc->pool, len + 1); - pj_ansi_snprintf(acc->rfc5626_instprm.ptr, len + 1, - "%s%.*s\"", - prmname, - (int)acc_cfg->rfc5626_instance_id.slen, - acc_cfg->rfc5626_instance_id.ptr); - acc->rfc5626_instprm.slen = len; + len = pj_ansi_strlen(prmname) + acc_cfg->rfc5626_instance_id.slen + 1; + acc->rfc5626_instprm.ptr = (char*)pj_pool_alloc(acc->pool, len + 1); + pj_ansi_snprintf(acc->rfc5626_instprm.ptr, len + 1, + "%s%.*s\"", + prmname, + (int)acc_cfg->rfc5626_instance_id.slen, + acc_cfg->rfc5626_instance_id.ptr); + acc->rfc5626_instprm.slen = len; } if (acc_cfg->rfc5626_reg_id.slen == 0) { - acc->rfc5626_regprm = pj_str(";reg-id=1"); + acc->rfc5626_regprm = pj_str(";reg-id=1"); } else { - const char *prmname = ";reg-id="; - pj_size_t len; + const char *prmname = ";reg-id="; + pj_size_t len; - len = pj_ansi_strlen(prmname) + acc_cfg->rfc5626_reg_id.slen; - acc->rfc5626_regprm.ptr = (char*)pj_pool_alloc(acc->pool, len + 1); - pj_ansi_snprintf(acc->rfc5626_regprm.ptr, len + 1, - "%s%.*s\"", - prmname, - (int)acc_cfg->rfc5626_reg_id.slen, - acc_cfg->rfc5626_reg_id.ptr); - acc->rfc5626_regprm.slen = len; + len = pj_ansi_strlen(prmname) + acc_cfg->rfc5626_reg_id.slen; + acc->rfc5626_regprm.ptr = (char*)pj_pool_alloc(acc->pool, len + 1); + pj_ansi_snprintf(acc->rfc5626_regprm.ptr, len + 1, + "%s%.*s\"", + prmname, + (int)acc_cfg->rfc5626_reg_id.slen, + acc_cfg->rfc5626_reg_id.ptr); + acc->rfc5626_regprm.slen = len; } acc->rfc5626_status = OUTBOUND_WANTED; @@ -233,88 +232,88 @@ static pj_status_t initialize_acc(unsigned acc_id) /* Need to parse local_uri to get the elements: */ name_addr = (pjsip_name_addr*) - pjsip_parse_uri(acc->pool, acc_cfg->id.ptr, - acc_cfg->id.slen, - PJSIP_PARSE_URI_AS_NAMEADDR); + pjsip_parse_uri(acc->pool, acc_cfg->id.ptr, + acc_cfg->id.slen, + PJSIP_PARSE_URI_AS_NAMEADDR); if (name_addr == NULL) { - pjsua_perror(THIS_FILE, "Invalid local URI", - PJSIP_EINVALIDURI); - return PJSIP_EINVALIDURI; + pjsua_perror(THIS_FILE, "Invalid local URI", + PJSIP_EINVALIDURI); + return PJSIP_EINVALIDURI; } /* Local URI MUST be a SIP or SIPS: */ if (!PJSIP_URI_SCHEME_IS_SIP(name_addr) && - !PJSIP_URI_SCHEME_IS_SIPS(name_addr)) + !PJSIP_URI_SCHEME_IS_SIPS(name_addr)) { - acc->display = name_addr->display; - acc->user_part = name_addr->display; - acc->srv_domain = pj_str(""); - acc->srv_port = 0; + acc->display = name_addr->display; + acc->user_part = name_addr->display; + acc->srv_domain = pj_str(""); + acc->srv_port = 0; } else { - pjsip_sip_uri *sip_uri; - - /* Get the SIP URI object: */ - sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(name_addr); - - /* Save the user and domain part. These will be used when finding an - * account for incoming requests. - */ - acc->display = name_addr->display; - acc->user_part = sip_uri->user; - acc->srv_domain = sip_uri->host; - acc->srv_port = 0; - - /* Escape user part (ticket #2010) */ - if (acc->user_part.slen) { - const pjsip_parser_const_t *pconst; - char buf[PJSIP_MAX_URL_SIZE]; - pj_str_t user_part; - - pconst = pjsip_parser_const(); - pj_strset(&user_part, buf, sizeof(buf)); - pj_strncpy_escape(&user_part, &sip_uri->user, sizeof(buf), - &pconst->pjsip_USER_SPEC_LENIENT); - if (user_part.slen > acc->user_part.slen) - pj_strdup(acc->pool, &acc->user_part, &user_part); - } + pjsip_sip_uri *sip_uri; + + /* Get the SIP URI object: */ + sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(name_addr); + + /* Save the user and domain part. These will be used when finding an + * account for incoming requests. + */ + acc->display = name_addr->display; + acc->user_part = sip_uri->user; + acc->srv_domain = sip_uri->host; + acc->srv_port = 0; + + /* Escape user part (ticket #2010) */ + if (acc->user_part.slen) { + const pjsip_parser_const_t *pconst; + char buf[PJSIP_MAX_URL_SIZE]; + pj_str_t user_part; + + pconst = pjsip_parser_const(); + pj_strset(&user_part, buf, sizeof(buf)); + pj_strncpy_escape(&user_part, &sip_uri->user, sizeof(buf), + &pconst->pjsip_USER_SPEC_LENIENT); + if (user_part.slen > acc->user_part.slen) + pj_strdup(acc->pool, &acc->user_part, &user_part); + } } acc->is_sips = PJSIP_URI_SCHEME_IS_SIPS(name_addr); /* Parse registrar URI, if any */ if (acc_cfg->reg_uri.slen) { - pjsip_uri *reg_uri; - - reg_uri = pjsip_parse_uri(acc->pool, acc_cfg->reg_uri.ptr, - acc_cfg->reg_uri.slen, 0); - if (reg_uri == NULL) { - pjsua_perror(THIS_FILE, "Invalid registrar URI", - PJSIP_EINVALIDURI); - return PJSIP_EINVALIDURI; - } - - /* Registrar URI MUST be a SIP or SIPS: */ - if (!PJSIP_URI_SCHEME_IS_SIP(reg_uri) && - !PJSIP_URI_SCHEME_IS_SIPS(reg_uri)) - { - pjsua_perror(THIS_FILE, "Invalid registar URI", - PJSIP_EINVALIDSCHEME); - return PJSIP_EINVALIDSCHEME; - } - - sip_reg_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(reg_uri); + pjsip_uri *reg_uri; + + reg_uri = pjsip_parse_uri(acc->pool, acc_cfg->reg_uri.ptr, + acc_cfg->reg_uri.slen, 0); + if (reg_uri == NULL) { + pjsua_perror(THIS_FILE, "Invalid registrar URI", + PJSIP_EINVALIDURI); + return PJSIP_EINVALIDURI; + } + + /* Registrar URI MUST be a SIP or SIPS: */ + if (!PJSIP_URI_SCHEME_IS_SIP(reg_uri) && + !PJSIP_URI_SCHEME_IS_SIPS(reg_uri)) + { + pjsua_perror(THIS_FILE, "Invalid registar URI", + PJSIP_EINVALIDSCHEME); + return PJSIP_EINVALIDSCHEME; + } + + sip_reg_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(reg_uri); } else { - sip_reg_uri = NULL; + sip_reg_uri = NULL; } if (sip_reg_uri) { - acc->srv_port = sip_reg_uri->port; + acc->srv_port = sip_reg_uri->port; } /* Create Contact header if not present. */ //if (acc_cfg->contact.slen == 0) { - // acc_cfg->contact = acc_cfg->id; + // acc_cfg->contact = acc_cfg->id; //} /* Build account route-set from outbound proxies and route set from @@ -323,53 +322,53 @@ static pj_status_t initialize_acc(unsigned acc_id) pj_list_init(&acc->route_set); if (!pj_list_empty(&pjsua_var.outbound_proxy)) { - pjsip_route_hdr *r; + pjsip_route_hdr *r; - r = pjsua_var.outbound_proxy.next; - while (r != &pjsua_var.outbound_proxy) { - pj_list_push_back(&acc->route_set, - pjsip_hdr_shallow_clone(acc->pool, r)); - r = r->next; - } + r = pjsua_var.outbound_proxy.next; + while (r != &pjsua_var.outbound_proxy) { + pj_list_push_back(&acc->route_set, + pjsip_hdr_shallow_clone(acc->pool, r)); + r = r->next; + } } for (i=0; iproxy_cnt; ++i) { - pj_str_t hname = { "Route", 5}; - pjsip_route_hdr *r; - pj_str_t tmp; - - pj_strdup_with_null(acc->pool, &tmp, &acc_cfg->proxy[i]); - r = (pjsip_route_hdr*) - pjsip_parse_hdr(acc->pool, &hname, tmp.ptr, tmp.slen, NULL); - if (r == NULL) { - pjsua_perror(THIS_FILE, "Invalid URI in account route set", - PJ_EINVAL); - return PJ_EINVAL; - } - pj_list_push_back(&acc->route_set, r); + pj_str_t hname = { "Route", 5}; + pjsip_route_hdr *r; + pj_str_t tmp; + + pj_strdup_with_null(acc->pool, &tmp, &acc_cfg->proxy[i]); + r = (pjsip_route_hdr*) + pjsip_parse_hdr(acc->pool, &hname, tmp.ptr, tmp.slen, NULL); + if (r == NULL) { + pjsua_perror(THIS_FILE, "Invalid URI in account route set", + PJ_EINVAL); + return PJ_EINVAL; + } + pj_list_push_back(&acc->route_set, r); } /* Concatenate credentials from account config and global config */ acc->cred_cnt = 0; for (i=0; icred_count; ++i) { - acc->cred[acc->cred_cnt++] = acc_cfg->cred_info[i]; + acc->cred[acc->cred_cnt++] = acc_cfg->cred_info[i]; } for (i=0; icred_cnt < PJ_ARRAY_SIZE(acc->cred); ++i) + acc->cred_cnt < PJ_ARRAY_SIZE(acc->cred); ++i) { - acc->cred[acc->cred_cnt++] = pjsua_var.ua_cfg.cred_info[i]; + acc->cred[acc->cred_cnt++] = pjsua_var.ua_cfg.cred_info[i]; } /* If account's ICE and TURN customization is not set, then * initialize it with the settings from the global media config. */ if (acc->cfg.ice_cfg_use == PJSUA_ICE_CONFIG_USE_DEFAULT) { - pjsua_ice_config_from_media_config(NULL, &acc->cfg.ice_cfg, - &pjsua_var.media_cfg); + pjsua_ice_config_from_media_config(NULL, &acc->cfg.ice_cfg, + &pjsua_var.media_cfg); } if (acc->cfg.turn_cfg_use == PJSUA_TURN_CONFIG_USE_DEFAULT) { - pjsua_turn_config_from_media_config(NULL, &acc->cfg.turn_cfg, - &pjsua_var.media_cfg); + pjsua_turn_config_from_media_config(NULL, &acc->cfg.turn_cfg, + &pjsua_var.media_cfg); } /* If ICE is enabled, add "+sip.ice" media feature tag in account's @@ -377,26 +376,26 @@ static pj_status_t initialize_acc(unsigned acc_id) */ #if PJSUA_ADD_ICE_TAGS if (acc_cfg->ice_cfg.enable_ice) { - pj_ssize_t new_len; - pj_str_t new_prm; + pj_ssize_t new_len; + pj_str_t new_prm; - new_len = acc_cfg->contact_params.slen + 10; - new_prm.ptr = (char*)pj_pool_alloc(acc->pool, new_len); - pj_strcpy(&new_prm, &acc_cfg->contact_params); - pj_strcat2(&new_prm, ";+sip.ice"); - acc_cfg->contact_params = new_prm; + new_len = acc_cfg->contact_params.slen + 10; + new_prm.ptr = (char*)pj_pool_alloc(acc->pool, new_len); + pj_strcpy(&new_prm, &acc_cfg->contact_params); + pj_strcat2(&new_prm, ";+sip.ice"); + acc_cfg->contact_params = new_prm; } #endif status = pjsua_pres_init_acc(acc_id); if (status != PJ_SUCCESS) - return status; + return status; /* If SIP outbound is enabled, generate instance and reg ID if they are * not specified */ if (acc_cfg->use_rfc5626) { - init_outbound_setting(acc); + init_outbound_setting(acc); } /* Mark account as valid */ @@ -404,14 +403,14 @@ static pj_status_t initialize_acc(unsigned acc_id) /* Insert account ID into account ID array, sorted by priority */ for (i=0; itransport_id != PJSUA_INVALID_ID) { acc->tp_type = pjsua_var.tpdata[acc_cfg->transport_id].type; @@ -429,8 +428,8 @@ static pj_status_t initialize_acc(unsigned acc_id) * Add a new account to pjsua. */ PJ_DEF(pj_status_t) pjsua_acc_add( const pjsua_acc_config *cfg, - pj_bool_t is_default, - pjsua_acc_id *p_acc_id) + pj_bool_t is_default, + pjsua_acc_id *p_acc_id) { pjsua_acc *acc; unsigned i, id; @@ -438,34 +437,34 @@ PJ_DEF(pj_status_t) pjsua_acc_add( const pjsua_acc_config *cfg, PJ_ASSERT_RETURN(cfg, PJ_EINVAL); PJ_ASSERT_RETURN(pjsua_var.acc_cnt < PJ_ARRAY_SIZE(pjsua_var.acc), - PJ_ETOOMANY); + PJ_ETOOMANY); /* Must have a transport */ PJ_ASSERT_RETURN(pjsua_var.tpdata[0].data.ptr != NULL, PJ_EINVALIDOP); PJ_LOG(4,(THIS_FILE, "Adding account: id=%.*s", - (int)cfg->id.slen, cfg->id.ptr)); + (int)cfg->id.slen, cfg->id.ptr)); pj_log_push_indent(); PJSUA_LOCK(); /* Find empty account id. */ for (id=0; id < PJ_ARRAY_SIZE(pjsua_var.acc); ++id) { - if (pjsua_var.acc[id].valid == PJ_FALSE) - break; + if (pjsua_var.acc[id].valid == PJ_FALSE) + break; } /* Expect to find a slot */ - PJ_ASSERT_ON_FAIL( id < PJ_ARRAY_SIZE(pjsua_var.acc), - {PJSUA_UNLOCK(); return PJ_EBUG;}); + PJ_ASSERT_ON_FAIL( id < PJ_ARRAY_SIZE(pjsua_var.acc), + {PJSUA_UNLOCK(); return PJ_EBUG;}); acc = &pjsua_var.acc[id]; /* Create pool for this account. */ if (acc->pool) - pj_pool_reset(acc->pool); + pj_pool_reset(acc->pool); else - acc->pool = pjsua_pool_create("acc%p", PJSUA_POOL_LEN_ACC, + acc->pool = pjsua_pool_create("acc%p", PJSUA_POOL_LEN_ACC, PJSUA_POOL_INC_ACC); /* Copy config */ @@ -484,12 +483,12 @@ PJ_DEF(pj_status_t) pjsua_acc_add( const pjsua_acc_config *cfg, /* Check the route URI's and force loose route if required */ for (i=0; icfg.proxy_cnt; ++i) { - status = normalize_route_uri(acc->pool, &acc->cfg.proxy[i]); - if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return status; - } + status = normalize_route_uri(acc->pool, &acc->cfg.proxy[i]); + if (status != PJ_SUCCESS) { + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return status; + } } /* Get CRC of account proxy setting */ @@ -497,43 +496,43 @@ PJ_DEF(pj_status_t) pjsua_acc_add( const pjsua_acc_config *cfg, /* Get CRC of global outbound proxy setting */ acc->global_route_crc=calc_proxy_crc(pjsua_var.ua_cfg.outbound_proxy, - pjsua_var.ua_cfg.outbound_proxy_cnt); + pjsua_var.ua_cfg.outbound_proxy_cnt); status = initialize_acc(id); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error adding account", status); - pj_pool_release(acc->pool); - acc->pool = NULL; - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return status; + pjsua_perror(THIS_FILE, "Error adding account", status); + pj_pool_release(acc->pool); + acc->pool = NULL; + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return status; } if (is_default) - pjsua_var.default_acc = id; + pjsua_var.default_acc = id; if (p_acc_id) - *p_acc_id = id; + *p_acc_id = id; pjsua_var.acc_cnt++; PJSUA_UNLOCK(); PJ_LOG(4,(THIS_FILE, "Account %.*s added with id %d", - (int)cfg->id.slen, cfg->id.ptr, id)); + (int)cfg->id.slen, cfg->id.ptr, id)); /* If accounts has registration enabled, start registration */ if (pjsua_var.acc[id].cfg.reg_uri.slen) { - if (pjsua_var.acc[id].cfg.register_on_acc_add) + if (pjsua_var.acc[id].cfg.register_on_acc_add) pjsua_acc_set_registration(id, PJ_TRUE); } else { - /* Otherwise subscribe to MWI, if it's enabled */ - if (pjsua_var.acc[id].cfg.mwi_enabled) - pjsua_start_mwi(id, PJ_TRUE); + /* Otherwise subscribe to MWI, if it's enabled */ + if (pjsua_var.acc[id].cfg.mwi_enabled) + pjsua_start_mwi(id, PJ_TRUE); - /* Start publish too */ - if (acc->cfg.publish_enabled) - pjsua_pres_init_publish_acc(id); + /* Start publish too */ + if (acc->cfg.publish_enabled) + pjsua_pres_init_publish_acc(id); } pj_log_pop_indent(); @@ -545,8 +544,8 @@ PJ_DEF(pj_status_t) pjsua_acc_add( const pjsua_acc_config *cfg, * Add local account */ PJ_DEF(pj_status_t) pjsua_acc_add_local( pjsua_transport_id tid, - pj_bool_t is_default, - pjsua_acc_id *p_acc_id) + pj_bool_t is_default, + pjsua_acc_id *p_acc_id) { pjsua_acc_config cfg; pjsua_transport_data *t = &pjsua_var.tpdata[tid]; @@ -558,7 +557,7 @@ PJ_DEF(pj_status_t) pjsua_acc_add_local( pjsua_transport_id tid, /* ID must be valid */ PJ_ASSERT_RETURN(tid>=0 && tid<(int)PJ_ARRAY_SIZE(pjsua_var.tpdata), - PJ_EINVAL); + PJ_EINVAL); /* Transport must be valid */ PJ_ASSERT_RETURN(t->data.ptr != NULL, PJ_EINVAL); @@ -570,28 +569,28 @@ PJ_DEF(pj_status_t) pjsua_acc_add_local( pjsua_transport_id tid, /* Don't add transport parameter if it's UDP */ if (t->type!=PJSIP_TRANSPORT_UDP && t->type!=PJSIP_TRANSPORT_UDP6) { - pj_ansi_snprintf(transport_param, sizeof(transport_param), - ";transport=%s", - pjsip_transport_get_type_name(t->type)); + pj_ansi_snprintf(transport_param, sizeof(transport_param), + ";transport=%s", + pjsip_transport_get_type_name(t->type)); } else { - transport_param[0] = '\0'; + transport_param[0] = '\0'; } /* Build URI for the account */ - pj_ansi_snprintf(uri, PJSIP_MAX_URL_SIZE, - "", - pj_addr_str_print(&t->local_name.host, t->local_name.port, - addr_buf, sizeof(addr_buf), 1), - transport_param); + pj_ansi_snprintf(uri, PJSIP_MAX_URL_SIZE, + "", + pj_addr_str_print(&t->local_name.host, t->local_name.port, + addr_buf, sizeof(addr_buf), 1), + transport_param); cfg.id = pj_str(uri); cfg.transport_id = tid; status = pjsua_acc_add(&cfg, is_default, &acc_id); if (status == PJ_SUCCESS) { - pjsua_var.acc[acc_id].tp_type = t->type; - if (p_acc_id) - *p_acc_id = acc_id; + pjsua_var.acc[acc_id].tp_type = t->type; + if (p_acc_id) + *p_acc_id = acc_id; } return status; @@ -602,10 +601,10 @@ PJ_DEF(pj_status_t) pjsua_acc_add_local( pjsua_transport_id tid, * Set arbitrary data to be associated with the account. */ PJ_DEF(pj_status_t) pjsua_acc_set_user_data(pjsua_acc_id acc_id, - void *user_data) + void *user_data) { PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc), - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP); PJSUA_LOCK(); @@ -624,7 +623,7 @@ PJ_DEF(pj_status_t) pjsua_acc_set_user_data(pjsua_acc_id acc_id, PJ_DEF(void*) pjsua_acc_get_user_data(pjsua_acc_id acc_id) { PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc), - NULL); + NULL); PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, NULL); return pjsua_var.acc[acc_id].cfg.user_data; @@ -640,7 +639,7 @@ PJ_DEF(pj_status_t) pjsua_acc_del(pjsua_acc_id acc_id) unsigned i; PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc), - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP); PJ_LOG(4,(THIS_FILE, "Deleting account %d..", acc_id)); @@ -652,27 +651,27 @@ PJ_DEF(pj_status_t) pjsua_acc_del(pjsua_acc_id acc_id) /* Cancel keep-alive timer, if any */ if (acc->ka_timer.id) { - pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer); - acc->ka_timer.id = PJ_FALSE; + pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer); + acc->ka_timer.id = PJ_FALSE; } if (acc->ka_transport) { - pjsip_transport_dec_ref(acc->ka_transport); - acc->ka_transport = NULL; + pjsip_transport_dec_ref(acc->ka_transport); + acc->ka_transport = NULL; } /* Cancel any re-registration timer */ if (acc->auto_rereg.timer.id) { - acc->auto_rereg.timer.id = PJ_FALSE; - pjsua_cancel_timer(&acc->auto_rereg.timer); + acc->auto_rereg.timer.id = PJ_FALSE; + pjsua_cancel_timer(&acc->auto_rereg.timer); } /* Delete registration */ if (acc->regc != NULL) { - pjsua_acc_set_registration(acc_id, PJ_FALSE); - if (acc->regc) { - pjsip_regc_destroy(acc->regc); - } - acc->regc = NULL; + pjsua_acc_set_registration(acc_id, PJ_FALSE); + if (acc->regc) { + pjsip_regc_destroy(acc->regc); + } + acc->regc = NULL; } /* Terminate mwi subscription */ @@ -686,8 +685,8 @@ PJ_DEF(pj_status_t) pjsua_acc_del(pjsua_acc_id acc_id) /* Release account pool */ if (acc->pool) { - pj_pool_release(acc->pool); - acc->pool = NULL; + pj_pool_release(acc->pool); + acc->pool = NULL; } /* Invalidate */ @@ -702,13 +701,13 @@ PJ_DEF(pj_status_t) pjsua_acc_del(pjsua_acc_id acc_id) /* Remove from array */ for (i=0; icfg.turn_cfg.turn_tls_setting); @@ -759,10 +758,10 @@ static int pjsip_hdr_cmp(const pjsip_hdr *h1, const pjsip_hdr *h2) p1.slen = pjsip_hdr_print_on((void*)h1, buf1, sizeof(buf1)); if (p1.slen < 0) - p1.slen = 0; + p1.slen = 0; p2.slen = pjsip_hdr_print_on((void*)h2, buf2, sizeof(buf2)); if (p2.slen < 0) - p2.slen = 0; + p2.slen = 0; return pj_strcmp(&p1, &p2); } @@ -778,31 +777,31 @@ static pj_bool_t update_hdr_list(pj_pool_t *pool, pjsip_hdr *dst, /* Remove header that's no longer needed */ for (dst_i = dst->next; dst_i != dst; ) { - for (src_i = src->next; src_i != src; src_i = src_i->next) { - if (pjsip_hdr_cmp(dst_i, src_i) == 0) - break; - } - if (src_i == src) { - pjsip_hdr *next = dst_i->next; - pj_list_erase(dst_i); - changed = PJ_TRUE; - dst_i = next; - } else { - dst_i = dst_i->next; - } + for (src_i = src->next; src_i != src; src_i = src_i->next) { + if (pjsip_hdr_cmp(dst_i, src_i) == 0) + break; + } + if (src_i == src) { + pjsip_hdr *next = dst_i->next; + pj_list_erase(dst_i); + changed = PJ_TRUE; + dst_i = next; + } else { + dst_i = dst_i->next; + } } /* Add new header */ for (src_i = src->next; src_i != src; src_i = src_i->next) { - for (dst_i = dst->next; dst_i != dst; dst_i = dst_i->next) { - if (pjsip_hdr_cmp(dst_i, src_i) == 0) - break; - } - if (dst_i == dst) { - dst_i = pjsip_hdr_clone(pool, src_i); - pj_list_push_back(dst, dst_i); - changed = PJ_TRUE; - } + for (dst_i = dst->next; dst_i != dst; dst_i = dst_i->next) { + if (pjsip_hdr_cmp(dst_i, src_i) == 0) + break; + } + if (dst_i == dst) { + dst_i = pjsip_hdr_clone(pool, src_i); + pj_list_push_back(dst, dst_i); + changed = PJ_TRUE; + } } return changed; @@ -812,7 +811,7 @@ static pj_bool_t update_hdr_list(pj_pool_t *pool, pjsip_hdr *dst, * Modify account information. */ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, - const pjsua_acc_config *cfg) + const pjsua_acc_config *cfg) { pjsua_acc *acc; pjsip_name_addr *id_name_addr = NULL; @@ -828,7 +827,7 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, pj_status_t status = PJ_SUCCESS; PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc), - PJ_EINVAL); + PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Modifying account %d", acc_id)); pj_log_push_indent(); @@ -837,66 +836,66 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, acc = &pjsua_var.acc[acc_id]; if (!acc->valid) { - status = PJ_EINVAL; - goto on_return; + status = PJ_EINVAL; + goto on_return; } /* == Validate first == */ /* Account id */ if (pj_strcmp(&acc->cfg.id, &cfg->id)) { - /* Need to parse id to get the elements: */ - id_name_addr = (pjsip_name_addr*) - pjsip_parse_uri(acc->pool, cfg->id.ptr, cfg->id.slen, - PJSIP_PARSE_URI_AS_NAMEADDR); - if (id_name_addr == NULL) { - status = PJSIP_EINVALIDURI; - pjsua_perror(THIS_FILE, "Invalid local URI", status); - goto on_return; - } - - /* URI MUST be a SIP or SIPS: */ - if (!PJSIP_URI_SCHEME_IS_SIP(id_name_addr) && - !PJSIP_URI_SCHEME_IS_SIPS(id_name_addr)) - { - status = PJSIP_EINVALIDSCHEME; - pjsua_perror(THIS_FILE, "Invalid local URI", status); - goto on_return; - } - - /* Get the SIP URI object: */ - id_sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(id_name_addr); + /* Need to parse id to get the elements: */ + id_name_addr = (pjsip_name_addr*) + pjsip_parse_uri(acc->pool, cfg->id.ptr, cfg->id.slen, + PJSIP_PARSE_URI_AS_NAMEADDR); + if (id_name_addr == NULL) { + status = PJSIP_EINVALIDURI; + pjsua_perror(THIS_FILE, "Invalid local URI", status); + goto on_return; + } + + /* URI MUST be a SIP or SIPS: */ + if (!PJSIP_URI_SCHEME_IS_SIP(id_name_addr) && + !PJSIP_URI_SCHEME_IS_SIPS(id_name_addr)) + { + status = PJSIP_EINVALIDSCHEME; + pjsua_perror(THIS_FILE, "Invalid local URI", status); + goto on_return; + } + + /* Get the SIP URI object: */ + id_sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(id_name_addr); } /* Registrar URI */ if (pj_strcmp(&acc->cfg.reg_uri, &cfg->reg_uri) && cfg->reg_uri.slen) { - pjsip_uri *reg_uri; - - /* Need to parse reg_uri to get the elements: */ - reg_uri = pjsip_parse_uri(acc->pool, cfg->reg_uri.ptr, - cfg->reg_uri.slen, 0); - if (reg_uri == NULL) { - status = PJSIP_EINVALIDURI; - pjsua_perror(THIS_FILE, "Invalid registrar URI", status); - goto on_return; - } + pjsip_uri *reg_uri; + + /* Need to parse reg_uri to get the elements: */ + reg_uri = pjsip_parse_uri(acc->pool, cfg->reg_uri.ptr, + cfg->reg_uri.slen, 0); + if (reg_uri == NULL) { + status = PJSIP_EINVALIDURI; + pjsua_perror(THIS_FILE, "Invalid registrar URI", status); + goto on_return; + } - /* Registrar URI MUST be a SIP or SIPS: */ - if (!PJSIP_URI_SCHEME_IS_SIP(reg_uri) && - !PJSIP_URI_SCHEME_IS_SIPS(reg_uri)) - { - status = PJSIP_EINVALIDSCHEME; - pjsua_perror(THIS_FILE, "Invalid registar URI", status); - goto on_return; - } + /* Registrar URI MUST be a SIP or SIPS: */ + if (!PJSIP_URI_SCHEME_IS_SIP(reg_uri) && + !PJSIP_URI_SCHEME_IS_SIPS(reg_uri)) + { + status = PJSIP_EINVALIDSCHEME; + pjsua_perror(THIS_FILE, "Invalid registar URI", status); + goto on_return; + } - reg_sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(reg_uri); + reg_sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(reg_uri); } /* REGISTER header list */ if (update_hdr_list(acc->pool, &acc->cfg.reg_hdr_list, &cfg->reg_hdr_list)) { - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* SUBSCRIBE header list */ @@ -904,50 +903,50 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, /* Global outbound proxy */ global_route_crc = calc_proxy_crc(pjsua_var.ua_cfg.outbound_proxy, - pjsua_var.ua_cfg.outbound_proxy_cnt); + pjsua_var.ua_cfg.outbound_proxy_cnt); if (global_route_crc != acc->global_route_crc) { - pjsip_route_hdr *r; - - /* Copy from global outbound proxies */ - pj_list_init(&global_route); - r = pjsua_var.outbound_proxy.next; - while (r != &pjsua_var.outbound_proxy) { - pj_list_push_back(&global_route, - pjsip_hdr_shallow_clone(acc->pool, r)); - r = r->next; - } + pjsip_route_hdr *r; + + /* Copy from global outbound proxies */ + pj_list_init(&global_route); + r = pjsua_var.outbound_proxy.next; + while (r != &pjsua_var.outbound_proxy) { + pj_list_push_back(&global_route, + pjsip_hdr_shallow_clone(acc->pool, r)); + r = r->next; + } } /* Account proxy */ local_route_crc = calc_proxy_crc(cfg->proxy, cfg->proxy_cnt); if (local_route_crc != acc->local_route_crc) { - pjsip_route_hdr *r; - unsigned i; - - /* Validate the local route and save it to temporary var */ - pj_list_init(&local_route); - for (i=0; iproxy_cnt; ++i) { - pj_str_t hname = { "Route", 5}; - - pj_strdup_with_null(acc->pool, &acc_proxy[i], &cfg->proxy[i]); - status = normalize_route_uri(acc->pool, &acc_proxy[i]); - if (status != PJ_SUCCESS) - goto on_return; - r = (pjsip_route_hdr*) - pjsip_parse_hdr(acc->pool, &hname, acc_proxy[i].ptr, - acc_proxy[i].slen, NULL); - if (r == NULL) { - status = PJSIP_EINVALIDURI; - pjsua_perror(THIS_FILE, "Invalid URI in account route set", - status); - goto on_return; - } - - pj_list_push_back(&local_route, r); - } + pjsip_route_hdr *r; + unsigned i; + + /* Validate the local route and save it to temporary var */ + pj_list_init(&local_route); + for (i=0; iproxy_cnt; ++i) { + pj_str_t hname = { "Route", 5}; + + pj_strdup_with_null(acc->pool, &acc_proxy[i], &cfg->proxy[i]); + status = normalize_route_uri(acc->pool, &acc_proxy[i]); + if (status != PJ_SUCCESS) + goto on_return; + r = (pjsip_route_hdr*) + pjsip_parse_hdr(acc->pool, &hname, acc_proxy[i].ptr, + acc_proxy[i].slen, NULL); + if (r == NULL) { + status = PJSIP_EINVALIDURI; + pjsua_perror(THIS_FILE, "Invalid URI in account route set", + status); + goto on_return; + } + + pj_list_push_back(&local_route, r); + } - /* Recalculate the CRC again after route URI normalization */ - local_route_crc = calc_proxy_crc(acc_proxy, cfg->proxy_cnt); + /* Recalculate the CRC again after route URI normalization */ + local_route_crc = calc_proxy_crc(acc_proxy, cfg->proxy_cnt); } @@ -955,14 +954,14 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, /* Account ID. */ if (id_name_addr && id_sip_uri) { - pj_strdup_with_null(acc->pool, &acc->cfg.id, &cfg->id); - pj_strdup_with_null(acc->pool, &acc->display, &id_name_addr->display); - pj_strdup_with_null(acc->pool, &acc->user_part, &id_sip_uri->user); - pj_strdup_with_null(acc->pool, &acc->srv_domain, &id_sip_uri->host); - acc->srv_port = 0; - acc->is_sips = PJSIP_URI_SCHEME_IS_SIPS(id_name_addr); - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + pj_strdup_with_null(acc->pool, &acc->cfg.id, &cfg->id); + pj_strdup_with_null(acc->pool, &acc->display, &id_name_addr->display); + pj_strdup_with_null(acc->pool, &acc->user_part, &id_sip_uri->user); + pj_strdup_with_null(acc->pool, &acc->srv_domain, &id_sip_uri->host); + acc->srv_port = 0; + acc->is_sips = PJSIP_URI_SCHEME_IS_SIPS(id_name_addr); + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* User data */ @@ -970,95 +969,95 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, /* Priority */ if (acc->cfg.priority != cfg->priority) { - unsigned i; - - acc->cfg.priority = cfg->priority; - - /* Resort accounts priority */ - for (i=0; icfg.priority) - { - break; - } - } - pj_array_insert(pjsua_var.acc_ids, sizeof(acc_id), - pjsua_var.acc_cnt, i, &acc_id); + unsigned i; + + acc->cfg.priority = cfg->priority; + + /* Resort accounts priority */ + for (i=0; icfg.priority) + { + break; + } + } + pj_array_insert(pjsua_var.acc_ids, sizeof(acc_id), + pjsua_var.acc_cnt, i, &acc_id); } /* MWI */ if (acc->cfg.mwi_enabled != cfg->mwi_enabled) { - acc->cfg.mwi_enabled = cfg->mwi_enabled; - update_mwi = PJ_TRUE; + acc->cfg.mwi_enabled = cfg->mwi_enabled; + update_mwi = PJ_TRUE; } if (acc->cfg.mwi_expires != cfg->mwi_expires && cfg->mwi_expires > 0) { - acc->cfg.mwi_expires = cfg->mwi_expires; - update_mwi = PJ_TRUE; + acc->cfg.mwi_expires = cfg->mwi_expires; + update_mwi = PJ_TRUE; } /* PIDF tuple ID */ if (pj_strcmp(&acc->cfg.pidf_tuple_id, &cfg->pidf_tuple_id)) - pj_strdup_with_null(acc->pool, &acc->cfg.pidf_tuple_id, - &cfg->pidf_tuple_id); + pj_strdup_with_null(acc->pool, &acc->cfg.pidf_tuple_id, + &cfg->pidf_tuple_id); /* Publish */ acc->cfg.publish_opt = cfg->publish_opt; acc->cfg.unpublish_max_wait_time_msec = cfg->unpublish_max_wait_time_msec; if (acc->cfg.publish_enabled != cfg->publish_enabled) { - acc->cfg.publish_enabled = cfg->publish_enabled; - if (!acc->cfg.publish_enabled) - pjsua_pres_unpublish(acc, 0); - else - update_reg = PJ_TRUE; + acc->cfg.publish_enabled = cfg->publish_enabled; + if (!acc->cfg.publish_enabled) + pjsua_pres_unpublish(acc, 0); + else + update_reg = PJ_TRUE; } /* Force contact URI */ if (pj_strcmp(&acc->cfg.force_contact, &cfg->force_contact)) { - pj_strdup_with_null(acc->pool, &acc->cfg.force_contact, - &cfg->force_contact); - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + pj_strdup_with_null(acc->pool, &acc->cfg.force_contact, + &cfg->force_contact); + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* Register contact params */ if (pj_strcmp(&acc->cfg.reg_contact_params, &cfg->reg_contact_params)) { - pj_strdup_with_null(acc->pool, &acc->cfg.reg_contact_params, - &cfg->reg_contact_params); - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + pj_strdup_with_null(acc->pool, &acc->cfg.reg_contact_params, + &cfg->reg_contact_params); + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* Register contact URI params */ if (pj_strcmp(&acc->cfg.reg_contact_uri_params, - &cfg->reg_contact_uri_params)) + &cfg->reg_contact_uri_params)) { - pj_strdup_with_null(acc->pool, &acc->cfg.reg_contact_uri_params, - &cfg->reg_contact_uri_params); - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + pj_strdup_with_null(acc->pool, &acc->cfg.reg_contact_uri_params, + &cfg->reg_contact_uri_params); + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* Contact param */ if (pj_strcmp(&acc->cfg.contact_params, &cfg->contact_params)) { - pj_strdup_with_null(acc->pool, &acc->cfg.contact_params, - &cfg->contact_params); - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + pj_strdup_with_null(acc->pool, &acc->cfg.contact_params, + &cfg->contact_params); + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* Contact URI params */ if (pj_strcmp(&acc->cfg.contact_uri_params, &cfg->contact_uri_params)) { - pj_strdup_with_null(acc->pool, &acc->cfg.contact_uri_params, - &cfg->contact_uri_params); - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + pj_strdup_with_null(acc->pool, &acc->cfg.contact_uri_params, + &cfg->contact_uri_params); + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* Reliable provisional response */ @@ -1070,63 +1069,63 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, /* Transport */ if (acc->cfg.transport_id != cfg->transport_id) { - pjsua_acc_set_transport(acc_id, cfg->transport_id); + pjsua_acc_set_transport(acc_id, cfg->transport_id); - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* Update keep-alive */ if (acc->cfg.ka_interval != cfg->ka_interval || - pj_strcmp(&acc->cfg.ka_data, &cfg->ka_data)) + pj_strcmp(&acc->cfg.ka_data, &cfg->ka_data)) { - pjsip_transport *ka_transport = acc->ka_transport; - - if (acc->ka_timer.id) { - pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer); - acc->ka_timer.id = PJ_FALSE; - } - if (acc->ka_transport) { - pjsip_transport_dec_ref(acc->ka_transport); - acc->ka_transport = NULL; - } - - acc->cfg.ka_interval = cfg->ka_interval; - - if (cfg->ka_interval) { - if (ka_transport) { - /* Keep-alive has been running so we can just restart it */ - pj_time_val delay; - - pjsip_transport_add_ref(ka_transport); - acc->ka_transport = ka_transport; - - acc->ka_timer.cb = &keep_alive_timer_cb; - acc->ka_timer.user_data = (void*)acc; - - delay.sec = acc->cfg.ka_interval; - delay.msec = 0; - status = pjsua_schedule_timer(&acc->ka_timer, &delay); - if (status == PJ_SUCCESS) { - acc->ka_timer.id = PJ_TRUE; - } else { - pjsip_transport_dec_ref(ka_transport); - acc->ka_transport = NULL; - pjsua_perror(THIS_FILE, "Error starting keep-alive timer", - status); - } - - } else { - /* Keep-alive has not been running, we need to (re)register - * first. - */ - update_reg = PJ_TRUE; - } - } + pjsip_transport *ka_transport = acc->ka_transport; + + if (acc->ka_timer.id) { + pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer); + acc->ka_timer.id = PJ_FALSE; + } + if (acc->ka_transport) { + pjsip_transport_dec_ref(acc->ka_transport); + acc->ka_transport = NULL; + } + + acc->cfg.ka_interval = cfg->ka_interval; + + if (cfg->ka_interval) { + if (ka_transport) { + /* Keep-alive has been running so we can just restart it */ + pj_time_val delay; + + pjsip_transport_add_ref(ka_transport); + acc->ka_transport = ka_transport; + + acc->ka_timer.cb = &keep_alive_timer_cb; + acc->ka_timer.user_data = (void*)acc; + + delay.sec = acc->cfg.ka_interval; + delay.msec = 0; + status = pjsua_schedule_timer(&acc->ka_timer, &delay); + if (status == PJ_SUCCESS) { + acc->ka_timer.id = PJ_TRUE; + } else { + pjsip_transport_dec_ref(ka_transport); + acc->ka_transport = NULL; + pjsua_perror(THIS_FILE, "Error starting keep-alive timer", + status); + } + + } else { + /* Keep-alive has not been running, we need to (re)register + * first. + */ + update_reg = PJ_TRUE; + } + } } if (pj_strcmp(&acc->cfg.ka_data, &cfg->ka_data)) - pj_strdup(acc->pool, &acc->cfg.ka_data, &cfg->ka_data); + pj_strdup(acc->pool, &acc->cfg.ka_data, &cfg->ka_data); #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) acc->cfg.use_srtp = cfg->use_srtp; acc->cfg.srtp_secure_signaling = cfg->srtp_secure_signaling; @@ -1141,133 +1140,133 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, if (acc->cfg.reg_use_proxy != cfg->reg_use_proxy) { acc->cfg.reg_use_proxy = cfg->reg_use_proxy; update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + unreg_first = PJ_TRUE; } /* Global outbound proxy */ if (global_route_crc != acc->global_route_crc) { - unsigned i; - pj_size_t rcnt; - - /* Remove the outbound proxies from the route set */ - rcnt = pj_list_size(&acc->route_set); - for (i=0; i < rcnt - acc->cfg.proxy_cnt; ++i) { - pjsip_route_hdr *r = acc->route_set.next; - pj_list_erase(r); - } + unsigned i; + pj_size_t rcnt; + + /* Remove the outbound proxies from the route set */ + rcnt = pj_list_size(&acc->route_set); + for (i=0; i < rcnt - acc->cfg.proxy_cnt; ++i) { + pjsip_route_hdr *r = acc->route_set.next; + pj_list_erase(r); + } - /* Insert the outbound proxies to the beginning of route set */ - pj_list_merge_first(&acc->route_set, &global_route); + /* Insert the outbound proxies to the beginning of route set */ + pj_list_merge_first(&acc->route_set, &global_route); - /* Update global route CRC */ - acc->global_route_crc = global_route_crc; + /* Update global route CRC */ + acc->global_route_crc = global_route_crc; - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* Account proxy */ if (local_route_crc != acc->local_route_crc) { - unsigned i; + unsigned i; - /* Remove the current account proxies from the route set */ - for (i=0; i < acc->cfg.proxy_cnt; ++i) { - pjsip_route_hdr *r = acc->route_set.prev; - pj_list_erase(r); - } + /* Remove the current account proxies from the route set */ + for (i=0; i < acc->cfg.proxy_cnt; ++i) { + pjsip_route_hdr *r = acc->route_set.prev; + pj_list_erase(r); + } - /* Insert new proxy setting to the route set */ - pj_list_merge_last(&acc->route_set, &local_route); + /* Insert new proxy setting to the route set */ + pj_list_merge_last(&acc->route_set, &local_route); - /* Update the proxy setting */ - acc->cfg.proxy_cnt = cfg->proxy_cnt; - for (i = 0; i < cfg->proxy_cnt; ++i) - acc->cfg.proxy[i] = acc_proxy[i]; + /* Update the proxy setting */ + acc->cfg.proxy_cnt = cfg->proxy_cnt; + for (i = 0; i < cfg->proxy_cnt; ++i) + acc->cfg.proxy[i] = acc_proxy[i]; - /* Update local route CRC */ - acc->local_route_crc = local_route_crc; + /* Update local route CRC */ + acc->local_route_crc = local_route_crc; - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* Credential info */ { - unsigned i; - pj_bool_t cred_changed = PJ_FALSE; - - /* Selective update credential info. */ - for (i = 0; i < cfg->cred_count; ++i) { - unsigned j; - pjsip_cred_info ci; - - /* Find if this credential is already listed */ - for (j = i; j < acc->cfg.cred_count; ++j) { - if (pjsip_cred_info_cmp(&acc->cfg.cred_info[j], - &cfg->cred_info[i]) == 0) - { - /* Found, but different index/position, swap */ - if (j != i) { - ci = acc->cfg.cred_info[i]; - acc->cfg.cred_info[i] = acc->cfg.cred_info[j]; - acc->cfg.cred_info[j] = ci; - } - break; - } - } - - /* Not found, insert this */ - if (j == acc->cfg.cred_count) { - cred_changed = PJ_TRUE; - - /* If account credential is full, discard the last one. */ - if (acc->cfg.cred_count == PJ_ARRAY_SIZE(acc->cfg.cred_info)) { - pj_array_erase(acc->cfg.cred_info, sizeof(pjsip_cred_info), - acc->cfg.cred_count, acc->cfg.cred_count-1); - acc->cfg.cred_count--; - } - - /* Insert this */ - pjsip_cred_info_dup(acc->pool, &ci, &cfg->cred_info[i]); - pj_array_insert(acc->cfg.cred_info, sizeof(pjsip_cred_info), - acc->cfg.cred_count, i, &ci); - } - } - acc->cfg.cred_count = cfg->cred_count; - - /* Concatenate credentials from account config and global config */ - acc->cred_cnt = 0; - for (i=0; icfg.cred_count; ++i) { - acc->cred[acc->cred_cnt++] = acc->cfg.cred_info[i]; - } - for (i=0; icred_cnt < PJ_ARRAY_SIZE(acc->cred); ++i) - { - acc->cred[acc->cred_cnt++] = pjsua_var.ua_cfg.cred_info[i]; - } - - if (cred_changed) { - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; - } + unsigned i; + pj_bool_t cred_changed = PJ_FALSE; + + /* Selective update credential info. */ + for (i = 0; i < cfg->cred_count; ++i) { + unsigned j; + pjsip_cred_info ci; + + /* Find if this credential is already listed */ + for (j = i; j < acc->cfg.cred_count; ++j) { + if (pjsip_cred_info_cmp(&acc->cfg.cred_info[j], + &cfg->cred_info[i]) == 0) + { + /* Found, but different index/position, swap */ + if (j != i) { + ci = acc->cfg.cred_info[i]; + acc->cfg.cred_info[i] = acc->cfg.cred_info[j]; + acc->cfg.cred_info[j] = ci; + } + break; + } + } + + /* Not found, insert this */ + if (j == acc->cfg.cred_count) { + cred_changed = PJ_TRUE; + + /* If account credential is full, discard the last one. */ + if (acc->cfg.cred_count == PJ_ARRAY_SIZE(acc->cfg.cred_info)) { + pj_array_erase(acc->cfg.cred_info, sizeof(pjsip_cred_info), + acc->cfg.cred_count, acc->cfg.cred_count-1); + acc->cfg.cred_count--; + } + + /* Insert this */ + pjsip_cred_info_dup(acc->pool, &ci, &cfg->cred_info[i]); + pj_array_insert(acc->cfg.cred_info, sizeof(pjsip_cred_info), + acc->cfg.cred_count, i, &ci); + } + } + acc->cfg.cred_count = cfg->cred_count; + + /* Concatenate credentials from account config and global config */ + acc->cred_cnt = 0; + for (i=0; icfg.cred_count; ++i) { + acc->cred[acc->cred_cnt++] = acc->cfg.cred_info[i]; + } + for (i=0; icred_cnt < PJ_ARRAY_SIZE(acc->cred); ++i) + { + acc->cred[acc->cred_cnt++] = pjsua_var.ua_cfg.cred_info[i]; + } + + if (cred_changed) { + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; + } } /* Authentication preference */ acc->cfg.auth_pref.initial_auth = cfg->auth_pref.initial_auth; if (pj_strcmp(&acc->cfg.auth_pref.algorithm, &cfg->auth_pref.algorithm)) { - pj_strdup_with_null(acc->pool, &acc->cfg.auth_pref.algorithm, - &cfg->auth_pref.algorithm); - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + pj_strdup_with_null(acc->pool, &acc->cfg.auth_pref.algorithm, + &cfg->auth_pref.algorithm); + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* Registration */ if (acc->cfg.reg_timeout != cfg->reg_timeout) { - acc->cfg.reg_timeout = cfg->reg_timeout; - if (acc->regc != NULL) - pjsip_regc_update_expires(acc->regc, acc->cfg.reg_timeout); + acc->cfg.reg_timeout = cfg->reg_timeout; + if (acc->regc != NULL) + pjsip_regc_update_expires(acc->regc, acc->cfg.reg_timeout); - update_reg = PJ_TRUE; + update_reg = PJ_TRUE; } acc->cfg.unreg_timeout = cfg->unreg_timeout; acc->cfg.allow_contact_rewrite = cfg->allow_contact_rewrite; @@ -1278,9 +1277,9 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, acc->cfg.register_on_acc_add = cfg->register_on_acc_add; if (acc->cfg.reg_delay_before_refresh != cfg->reg_delay_before_refresh) { acc->cfg.reg_delay_before_refresh = cfg->reg_delay_before_refresh; - if (acc->regc != NULL) - pjsip_regc_set_delay_before_refresh(acc->regc, - cfg->reg_delay_before_refresh); + if (acc->regc != NULL) + pjsip_regc_set_delay_before_refresh(acc->regc, + cfg->reg_delay_before_refresh); } /* Allow via rewrite */ @@ -1308,43 +1307,43 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, acc->cfg.reg_timeout = PJSUA_REG_INTERVAL; } if (acc->cfg.reg_delay_before_refresh == 0) { - acc->cfg.reg_delay_before_refresh = + acc->cfg.reg_delay_before_refresh = PJSIP_REGISTER_CLIENT_DELAY_BEFORE_REFRESH; } } /* Registrar URI */ if (pj_strcmp(&acc->cfg.reg_uri, &cfg->reg_uri)) { - if (cfg->reg_uri.slen) { - pj_strdup_with_null(acc->pool, &acc->cfg.reg_uri, &cfg->reg_uri); - if (reg_sip_uri) - acc->srv_port = reg_sip_uri->port; - } - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + if (cfg->reg_uri.slen) { + pj_strdup_with_null(acc->pool, &acc->cfg.reg_uri, &cfg->reg_uri); + if (reg_sip_uri) + acc->srv_port = reg_sip_uri->port; + } + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* SIP outbound setting */ if (acc->cfg.use_rfc5626 != cfg->use_rfc5626 || - pj_strcmp(&acc->cfg.rfc5626_instance_id, &cfg->rfc5626_instance_id) || - pj_strcmp(&acc->cfg.rfc5626_reg_id, &cfg->rfc5626_reg_id)) - { - if (acc->cfg.use_rfc5626 != cfg->use_rfc5626) - acc->cfg.use_rfc5626 = cfg->use_rfc5626; - - if (pj_strcmp(&acc->cfg.rfc5626_instance_id, - &cfg->rfc5626_instance_id)) - { - pj_strdup_with_null(acc->pool, &acc->cfg.rfc5626_instance_id, - &cfg->rfc5626_instance_id); - } - if (pj_strcmp(&acc->cfg.rfc5626_reg_id, &cfg->rfc5626_reg_id)) { - pj_strdup_with_null(acc->pool, &acc->cfg.rfc5626_reg_id, - &cfg->rfc5626_reg_id); - } - init_outbound_setting(acc); - update_reg = PJ_TRUE; - unreg_first = PJ_TRUE; + pj_strcmp(&acc->cfg.rfc5626_instance_id, &cfg->rfc5626_instance_id) || + pj_strcmp(&acc->cfg.rfc5626_reg_id, &cfg->rfc5626_reg_id)) + { + if (acc->cfg.use_rfc5626 != cfg->use_rfc5626) + acc->cfg.use_rfc5626 = cfg->use_rfc5626; + + if (pj_strcmp(&acc->cfg.rfc5626_instance_id, + &cfg->rfc5626_instance_id)) + { + pj_strdup_with_null(acc->pool, &acc->cfg.rfc5626_instance_id, + &cfg->rfc5626_instance_id); + } + if (pj_strcmp(&acc->cfg.rfc5626_reg_id, &cfg->rfc5626_reg_id)) { + pj_strdup_with_null(acc->pool, &acc->cfg.rfc5626_reg_id, + &cfg->rfc5626_reg_id); + } + init_outbound_setting(acc); + update_reg = PJ_TRUE; + unreg_first = PJ_TRUE; } /* Video settings */ @@ -1357,25 +1356,25 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, /* Media settings */ if (acc->cfg.rtp_cfg.port != cfg->rtp_cfg.port) { - /* Note that changing port range only changes the calculation of - * the next rtp port but doesn't reset it. - */ - acc->next_rtp_port = 0; + /* Note that changing port range only changes the calculation of + * the next rtp port but doesn't reset it. + */ + acc->next_rtp_port = 0; } if (pj_stricmp(&acc->cfg.rtp_cfg.public_addr, &cfg->rtp_cfg.public_addr) || - pj_stricmp(&acc->cfg.rtp_cfg.bound_addr, &cfg->rtp_cfg.bound_addr)) + pj_stricmp(&acc->cfg.rtp_cfg.bound_addr, &cfg->rtp_cfg.bound_addr)) { - pjsua_transport_config_dup(acc->pool, &acc->cfg.rtp_cfg, - &cfg->rtp_cfg); + pjsua_transport_config_dup(acc->pool, &acc->cfg.rtp_cfg, + &cfg->rtp_cfg); } else { - pj_str_t p_addr = acc->cfg.rtp_cfg.public_addr; - pj_str_t b_addr = acc->cfg.rtp_cfg.bound_addr; - - /* ..to save memory by not using the pool */ - acc->cfg.rtp_cfg = cfg->rtp_cfg; - acc->cfg.rtp_cfg.public_addr = p_addr; - acc->cfg.rtp_cfg.bound_addr = b_addr; + pj_str_t p_addr = acc->cfg.rtp_cfg.public_addr; + pj_str_t b_addr = acc->cfg.rtp_cfg.bound_addr; + + /* ..to save memory by not using the pool */ + acc->cfg.rtp_cfg = cfg->rtp_cfg; + acc->cfg.rtp_cfg.public_addr = p_addr; + acc->cfg.rtp_cfg.bound_addr = b_addr; } acc->cfg.nat64_opt = cfg->nat64_opt; @@ -1386,8 +1385,8 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, /* STUN and Media customization */ if (acc->cfg.sip_stun_use != cfg->sip_stun_use) { - acc->cfg.sip_stun_use = cfg->sip_stun_use; - update_reg = PJ_TRUE; + acc->cfg.sip_stun_use = cfg->sip_stun_use; + update_reg = PJ_TRUE; } acc->cfg.media_stun_use = cfg->media_stun_use; @@ -1395,31 +1394,31 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, acc->cfg.ice_cfg_use = cfg->ice_cfg_use; switch (acc->cfg.ice_cfg_use) { case PJSUA_ICE_CONFIG_USE_DEFAULT: - /* Copy ICE settings from media settings so that we don't need to - * check the media config if we look for ICE config. - */ - pjsua_ice_config_from_media_config(NULL, &acc->cfg.ice_cfg, - &pjsua_var.media_cfg); - break; + /* Copy ICE settings from media settings so that we don't need to + * check the media config if we look for ICE config. + */ + pjsua_ice_config_from_media_config(NULL, &acc->cfg.ice_cfg, + &pjsua_var.media_cfg); + break; case PJSUA_ICE_CONFIG_USE_CUSTOM: - pjsua_ice_config_dup(acc->pool, &acc->cfg.ice_cfg, &cfg->ice_cfg); - break; + pjsua_ice_config_dup(acc->pool, &acc->cfg.ice_cfg, &cfg->ice_cfg); + break; } /* TURN settings */ acc->cfg.turn_cfg_use = cfg->turn_cfg_use; switch (acc->cfg.turn_cfg_use) { case PJSUA_TURN_CONFIG_USE_DEFAULT: - /* Copy TURN settings from media settings so that we don't need to - * check the media config if we look for TURN config. - */ - pjsua_turn_config_from_media_config(NULL, &acc->cfg.turn_cfg, - &pjsua_var.media_cfg); - break; + /* Copy TURN settings from media settings so that we don't need to + * check the media config if we look for TURN config. + */ + pjsua_turn_config_from_media_config(NULL, &acc->cfg.turn_cfg, + &pjsua_var.media_cfg); + break; case PJSUA_TURN_CONFIG_USE_CUSTOM: - pjsua_turn_config_dup(acc->pool, &acc->cfg.turn_cfg, - &cfg->turn_cfg); - break; + pjsua_turn_config_dup(acc->pool, &acc->cfg.turn_cfg, + &cfg->turn_cfg); + break; } acc->cfg.use_srtp = cfg->use_srtp; @@ -1429,50 +1428,50 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, /* Unregister first */ if (unreg_first) { - if (acc->regc) { - status = pjsua_acc_set_registration(acc->index, PJ_FALSE); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Ignored failure in unregistering the " - "old account setting in modifying account", - status); - /* Not really sure if we should return error */ - status = PJ_SUCCESS; - } - } - if (acc->regc != NULL) { - pjsip_regc_destroy(acc->regc); - acc->regc = NULL; - acc->contact.slen = 0; - acc->reg_mapped_addr.slen = 0; - acc->rfc5626_status = OUTBOUND_UNKNOWN; - } - - if (!cfg->reg_uri.slen) { - /* Reg URI still needed, delay unset after sending unregister. */ - pj_bzero(&acc->cfg.reg_uri, sizeof(acc->cfg.reg_uri)); - } + if (acc->regc) { + status = pjsua_acc_set_registration(acc->index, PJ_FALSE); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Ignored failure in unregistering the " + "old account setting in modifying account", + status); + /* Not really sure if we should return error */ + status = PJ_SUCCESS; + } + } + if (acc->regc != NULL) { + pjsip_regc_destroy(acc->regc); + acc->regc = NULL; + acc->contact.slen = 0; + acc->reg_mapped_addr.slen = 0; + acc->rfc5626_status = OUTBOUND_UNKNOWN; + } + + if (!cfg->reg_uri.slen) { + /* Reg URI still needed, delay unset after sending unregister. */ + pj_bzero(&acc->cfg.reg_uri, sizeof(acc->cfg.reg_uri)); + } } /* Update registration */ if (update_reg) { - /* If accounts has registration enabled, start registration */ - if (acc->cfg.reg_uri.slen) { - status = pjsua_acc_set_registration(acc->index, PJ_TRUE); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Failed to register with new account " - "setting in modifying account", status); - goto on_return; - } - } + /* If accounts has registration enabled, start registration */ + if (acc->cfg.reg_uri.slen) { + status = pjsua_acc_set_registration(acc->index, PJ_TRUE); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Failed to register with new account " + "setting in modifying account", status); + goto on_return; + } + } } /* Update MWI subscription */ if (update_mwi) { - status = pjsua_start_mwi(acc_id, PJ_TRUE); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Failed in starting MWI subscription for " - "new account setting in modifying account", status); - } + status = pjsua_start_mwi(acc_id, PJ_TRUE); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Failed in starting MWI subscription for " + "new account setting in modifying account", status); + } } /* IP Change config */ @@ -1482,11 +1481,11 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, /* SRTP setting */ pjsua_srtp_opt_dup(acc->pool, &acc->cfg.srtp_opt, &cfg->srtp_opt, - PJ_TRUE); + PJ_TRUE); /* RTCP-FB config */ pjmedia_rtcp_fb_setting_dup(acc->pool, &acc->cfg.rtcp_fb_cfg, - &cfg->rtcp_fb_cfg); + &cfg->rtcp_fb_cfg); on_return: PJSUA_UNLOCK(); @@ -1500,14 +1499,14 @@ PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id, * subscribers. */ PJ_DEF(pj_status_t) pjsua_acc_set_online_status( pjsua_acc_id acc_id, - pj_bool_t is_online) + pj_bool_t is_online) { PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc), - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP); PJ_LOG(4,(THIS_FILE, "Acc %d: setting online status to %d..", - acc_id, is_online)); + acc_id, is_online)); pj_log_push_indent(); pjsua_var.acc[acc_id].online_status = is_online; @@ -1523,15 +1522,15 @@ PJ_DEF(pj_status_t) pjsua_acc_set_online_status( pjsua_acc_id acc_id, * Set online status with extended information */ PJ_DEF(pj_status_t) pjsua_acc_set_online_status2( pjsua_acc_id acc_id, - pj_bool_t is_online, - const pjrpid_element *pr) + pj_bool_t is_online, + const pjrpid_element *pr) { PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc), - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP); PJ_LOG(4,(THIS_FILE, "Acc %d: setting online status to %d..", - acc_id, is_online)); + acc_id, is_online)); pj_log_push_indent(); PJSUA_LOCK(); @@ -1556,19 +1555,19 @@ static void update_regc_contact(pjsua_acc *acc) const pj_str_t tls_param = pj_str(";transport=tls"); if (!acc_cfg->use_rfc5626) - goto done; + goto done; /* Check if outbound has been requested and rejected */ if (acc->rfc5626_status == OUTBOUND_NA) - goto done; + goto done; if (pj_stristr(&acc->contact, &tcp_param)==NULL && - pj_stristr(&acc->contact, &tls_param)==NULL) + pj_stristr(&acc->contact, &tls_param)==NULL) { - /* Currently we can only do SIP outbound for TCP - * and TLS. - */ - goto done; + /* Currently we can only do SIP outbound for TCP + * and TLS. + */ + goto done; } /* looks like we can use outbound */ @@ -1576,90 +1575,90 @@ static void update_regc_contact(pjsua_acc *acc) done: { - pj_ssize_t len; - pj_str_t reg_contact; - - acc->rfc5626_status = OUTBOUND_WANTED; - len = acc->contact.slen + - acc->cfg.contact_params.slen + - acc->cfg.reg_contact_params.slen + - acc->cfg.reg_contact_uri_params.slen + - (need_outbound? - (acc->rfc5626_instprm.slen + acc->rfc5626_regprm.slen): 0); - if (len > acc->contact.slen) { - reg_contact.ptr = (char*) pj_pool_alloc(acc->pool, len); - - pj_strcpy(®_contact, &acc->contact); - - /* Contact URI params */ - if (acc->cfg.reg_contact_uri_params.slen) { - pj_pool_t *pool; - pjsip_contact_hdr *contact_hdr; - pjsip_sip_uri *uri; - pj_str_t uri_param = acc->cfg.reg_contact_uri_params; - const pj_str_t STR_CONTACT = { "Contact", 7 }; - char tmp_uri[PJSIP_MAX_URL_SIZE]; - pj_ssize_t tmp_len; - - /* Get the URI string */ - pool = pjsua_pool_create("tmp", 512, 512); - contact_hdr = (pjsip_contact_hdr*) - pjsip_parse_hdr(pool, &STR_CONTACT, - reg_contact.ptr, - reg_contact.slen, NULL); - pj_assert(contact_hdr != NULL); - uri = (pjsip_sip_uri*) contact_hdr->uri; - pj_assert(uri != NULL); - uri = (pjsip_sip_uri*) pjsip_uri_get_uri(uri); - tmp_len = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, - uri, tmp_uri, - sizeof(tmp_uri)); - pj_assert(tmp_len > 0); - pj_pool_release(pool); - - /* Regenerate Contact */ - reg_contact.slen = pj_ansi_snprintf( - reg_contact.ptr, len, - "<%.*s%.*s>%.*s", - (int)tmp_len, tmp_uri, - (int)uri_param.slen, uri_param.ptr, - (int)acc->cfg.contact_params.slen, - acc->cfg.contact_params.ptr); - pj_assert(reg_contact.slen > 0); - } - - /* Outbound */ - if (need_outbound) { - acc->rfc5626_status = OUTBOUND_WANTED; - - /* Need to use outbound, append the contact with - * +sip.instance and reg-id parameters. - */ - pj_strcat(®_contact, &acc->rfc5626_regprm); - pj_strcat(®_contact, &acc->rfc5626_instprm); - } else { - acc->rfc5626_status = OUTBOUND_NA; - } - - /* Contact params */ - pj_strcat(®_contact, &acc->cfg.reg_contact_params); - - acc->reg_contact = reg_contact; - - PJ_LOG(4,(THIS_FILE, - "Contact for acc %d updated: %.*s", - acc->index, - (int)acc->reg_contact.slen, - acc->reg_contact.ptr)); - - } else { - /* Outbound is not needed/wanted for the account and there's - * no custom registration Contact params. acc->reg_contact - * is set to the same as acc->contact. - */ - acc->reg_contact = acc->contact; - acc->rfc5626_status = OUTBOUND_NA; - } + pj_ssize_t len; + pj_str_t reg_contact; + + acc->rfc5626_status = OUTBOUND_WANTED; + len = acc->contact.slen + + acc->cfg.contact_params.slen + + acc->cfg.reg_contact_params.slen + + acc->cfg.reg_contact_uri_params.slen + + (need_outbound? + (acc->rfc5626_instprm.slen + acc->rfc5626_regprm.slen): 0); + if (len > acc->contact.slen) { + reg_contact.ptr = (char*) pj_pool_alloc(acc->pool, len); + + pj_strcpy(®_contact, &acc->contact); + + /* Contact URI params */ + if (acc->cfg.reg_contact_uri_params.slen) { + pj_pool_t *pool; + pjsip_contact_hdr *contact_hdr; + pjsip_sip_uri *uri; + pj_str_t uri_param = acc->cfg.reg_contact_uri_params; + const pj_str_t STR_CONTACT = { "Contact", 7 }; + char tmp_uri[PJSIP_MAX_URL_SIZE]; + pj_ssize_t tmp_len; + + /* Get the URI string */ + pool = pjsua_pool_create("tmp", 512, 512); + contact_hdr = (pjsip_contact_hdr*) + pjsip_parse_hdr(pool, &STR_CONTACT, + reg_contact.ptr, + reg_contact.slen, NULL); + pj_assert(contact_hdr != NULL); + uri = (pjsip_sip_uri*) contact_hdr->uri; + pj_assert(uri != NULL); + uri = (pjsip_sip_uri*) pjsip_uri_get_uri(uri); + tmp_len = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, + uri, tmp_uri, + sizeof(tmp_uri)); + pj_assert(tmp_len > 0); + pj_pool_release(pool); + + /* Regenerate Contact */ + reg_contact.slen = pj_ansi_snprintf( + reg_contact.ptr, len, + "<%.*s%.*s>%.*s", + (int)tmp_len, tmp_uri, + (int)uri_param.slen, uri_param.ptr, + (int)acc->cfg.contact_params.slen, + acc->cfg.contact_params.ptr); + pj_assert(reg_contact.slen > 0); + } + + /* Outbound */ + if (need_outbound) { + acc->rfc5626_status = OUTBOUND_WANTED; + + /* Need to use outbound, append the contact with + * +sip.instance and reg-id parameters. + */ + pj_strcat(®_contact, &acc->rfc5626_regprm); + pj_strcat(®_contact, &acc->rfc5626_instprm); + } else { + acc->rfc5626_status = OUTBOUND_NA; + } + + /* Contact params */ + pj_strcat(®_contact, &acc->cfg.reg_contact_params); + + acc->reg_contact = reg_contact; + + PJ_LOG(4,(THIS_FILE, + "Contact for acc %d updated: %.*s", + acc->index, + (int)acc->reg_contact.slen, + acc->reg_contact.ptr)); + + } else { + /* Outbound is not needed/wanted for the account and there's + * no custom registration Contact params. acc->reg_contact + * is set to the same as acc->contact. + */ + acc->reg_contact = acc->contact; + acc->rfc5626_status = OUTBOUND_NA; + } } } @@ -1668,19 +1667,19 @@ static pj_bool_t is_private_ip(const pj_str_t *addr) { const pj_str_t private_net[] = { - { "10.", 3 }, - { "127.", 4 }, - { "172.16.", 7 }, { "172.17.", 7 }, { "172.18.", 7 }, { "172.19.", 7 }, + { "10.", 3 }, + { "127.", 4 }, + { "172.16.", 7 }, { "172.17.", 7 }, { "172.18.", 7 }, { "172.19.", 7 }, { "172.20.", 7 }, { "172.21.", 7 }, { "172.22.", 7 }, { "172.23.", 7 }, { "172.24.", 7 }, { "172.25.", 7 }, { "172.26.", 7 }, { "172.27.", 7 }, { "172.28.", 7 }, { "172.29.", 7 }, { "172.30.", 7 }, { "172.31.", 7 }, - { "192.168.", 8 } + { "192.168.", 8 } }; unsigned i; for (i=0; irdata->msg_info.via; if (via->rport_param < 1) { - /* Remote doesn't support rport */ - rport = via->sent_by.port; - if (rport==0) { - pjsip_transport_type_e tp_type; - tp_type = (pjsip_transport_type_e) tp->key.type; - rport = pjsip_transport_get_default_port_for_type(tp_type); - } + /* Remote doesn't support rport */ + rport = via->sent_by.port; + if (rport==0) { + pjsip_transport_type_e tp_type; + tp_type = (pjsip_transport_type_e) tp->key.type; + rport = pjsip_transport_get_default_port_for_type(tp_type); + } } else - rport = via->rport_param; + rport = via->rport_param; if (via->recvd_param.slen != 0) via_addr = &via->recvd_param; @@ -1753,20 +1752,20 @@ static pj_bool_t acc_check_nat_addr(pjsua_acc *acc, /* Save mapped address if needed */ if (acc->cfg.allow_sdp_nat_rewrite && - pj_strcmp(&acc->reg_mapped_addr, via_addr)) + pj_strcmp(&acc->reg_mapped_addr, via_addr)) { - pj_strdup(acc->pool, &acc->reg_mapped_addr, via_addr); + pj_strdup(acc->pool, &acc->reg_mapped_addr, via_addr); } /* Only update if account is configured to auto-update */ if (acc->cfg.allow_contact_rewrite == PJ_FALSE) - return PJ_FALSE; + return PJ_FALSE; /* If SIP outbound is active, no need to update */ if (acc->rfc5626_status == OUTBOUND_ACTIVE) { - PJ_LOG(4,(THIS_FILE, "Acc %d has SIP outbound active, no need to " - "update registration Contact", acc->index)); - return PJ_FALSE; + PJ_LOG(4,(THIS_FILE, "Acc %d has SIP outbound active, no need to " + "update registration Contact", acc->index)); + return PJ_FALSE; } #if 0 @@ -1777,62 +1776,62 @@ static pj_bool_t acc_check_nat_addr(pjsua_acc *acc, * For TCP/TLS, always check. */ if ((tp->key.type == PJSIP_TRANSPORT_UDP && - (pjsua_var.ua_cfg.stun_domain.slen != 0 || - (pjsua_var.ua_cfg.stun_host.slen != 0)) || - (tp->key.type == PJSIP_TRANSPORT_TCP) || - (tp->key.type == PJSIP_TRANSPORT_TLS)) + (pjsua_var.ua_cfg.stun_domain.slen != 0 || + (pjsua_var.ua_cfg.stun_host.slen != 0)) || + (tp->key.type == PJSIP_TRANSPORT_TCP) || + (tp->key.type == PJSIP_TRANSPORT_TLS)) { - /* Yes we will check */ + /* Yes we will check */ } else { - return PJ_FALSE; + return PJ_FALSE; } #endif /* Compare received and rport with the URI in our registration */ pool = pjsua_pool_create("tmp", 512, 512); contact_hdr = (pjsip_contact_hdr*) - pjsip_parse_hdr(pool, &STR_CONTACT, acc->contact.ptr, - acc->contact.slen, NULL); + pjsip_parse_hdr(pool, &STR_CONTACT, acc->contact.ptr, + acc->contact.slen, NULL); pj_assert(contact_hdr != NULL); uri = (pjsip_sip_uri*) contact_hdr->uri; pj_assert(uri != NULL); uri = (pjsip_sip_uri*) pjsip_uri_get_uri(uri); if (uri->port == 0) { - pjsip_transport_type_e tp_type; - tp_type = (pjsip_transport_type_e) tp->key.type; - uri->port = pjsip_transport_get_default_port_for_type(tp_type); + pjsip_transport_type_e tp_type; + tp_type = (pjsip_transport_type_e) tp->key.type; + uri->port = pjsip_transport_get_default_port_for_type(tp_type); } /* Convert IP address strings into sockaddr for comparison. * (https://github.com/pjsip/pjproject/issues/863) */ status = pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &uri->host, - &contact_addr); + &contact_addr); if (status == PJ_SUCCESS) - status = pj_sockaddr_parse(pj_AF_UNSPEC(), 0, via_addr, - &recv_addr); + status = pj_sockaddr_parse(pj_AF_UNSPEC(), 0, via_addr, + &recv_addr); if (status == PJ_SUCCESS) { - /* Compare the addresses as sockaddr according to the ticket above, - * but only if they have the same family (ipv4 vs ipv4, or - * ipv6 vs ipv6). - * Checking for the same address family is currently disabled, - * since it can be useful in cases such as when on NAT64, - * in order to get the IPv4-mapped address from IPv6. - */ - matched = //(contact_addr.addr.sa_family != recv_addr.addr.sa_family)|| - (uri->port == rport && - pj_sockaddr_cmp(&contact_addr, &recv_addr)==0); + /* Compare the addresses as sockaddr according to the ticket above, + * but only if they have the same family (ipv4 vs ipv4, or + * ipv6 vs ipv6). + * Checking for the same address family is currently disabled, + * since it can be useful in cases such as when on NAT64, + * in order to get the IPv4-mapped address from IPv6. + */ + matched = //(contact_addr.addr.sa_family != recv_addr.addr.sa_family)|| + (uri->port == rport && + pj_sockaddr_cmp(&contact_addr, &recv_addr)==0); } else { - /* Compare the addresses as string, as before */ - matched = (uri->port == rport && - pj_stricmp(&uri->host, via_addr)==0); + /* Compare the addresses as string, as before */ + matched = (uri->port == rport && + pj_stricmp(&uri->host, via_addr)==0); } if (matched) { - /* Address doesn't change */ - pj_pool_release(pool); - return PJ_FALSE; + /* Address doesn't change */ + pj_pool_release(pool); + return PJ_FALSE; } /* Get server IP */ @@ -1852,11 +1851,11 @@ static pj_bool_t acc_check_nat_addr(pjsua_acc *acc, * is difference in the IP address in the response. */ if (acc->cfg.allow_contact_rewrite != 2 && !is_private_ip(&uri->host) && - !is_private_ip(&srv_ip) && is_private_ip(via_addr)) + !is_private_ip(&srv_ip) && is_private_ip(via_addr)) { - /* Don't switch */ - pj_pool_release(pool); - return PJ_FALSE; + /* Don't switch */ + pj_pool_release(pool); + return PJ_FALSE; } /* Also don't switch if only the port number part is different, and @@ -1864,51 +1863,51 @@ static pj_bool_t acc_check_nat_addr(pjsua_acc *acc, * See https://github.com/pjsip/pjproject/issues/864 */ if (acc->cfg.allow_contact_rewrite != 2 && - pj_sockaddr_cmp(&contact_addr, &recv_addr)==0 && - is_private_ip(via_addr)) + pj_sockaddr_cmp(&contact_addr, &recv_addr)==0 && + is_private_ip(via_addr)) { - /* Don't switch */ - pj_pool_release(pool); - return PJ_FALSE; + /* Don't switch */ + pj_pool_release(pool); + return PJ_FALSE; } pj_addr_str_print(&uri->host, uri->port, host_addr_buf, - sizeof(host_addr_buf), 1); + sizeof(host_addr_buf), 1); pj_addr_str_print(via_addr, rport, via_addr_buf, - sizeof(via_addr_buf), 1); + sizeof(via_addr_buf), 1); PJ_LOG(3,(THIS_FILE, "IP address change detected for account %d " - "(%s --> %s). Updating registration " - "(using method %d)", - acc->index, host_addr_buf, via_addr_buf, - contact_rewrite_method)); + "(%s --> %s). Updating registration " + "(using method %d)", + acc->index, host_addr_buf, via_addr_buf, + contact_rewrite_method)); pj_assert(contact_rewrite_method == PJSUA_CONTACT_REWRITE_UNREGISTER || - contact_rewrite_method == PJSUA_CONTACT_REWRITE_NO_UNREG || + contact_rewrite_method == PJSUA_CONTACT_REWRITE_NO_UNREG || contact_rewrite_method == PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE); if (contact_rewrite_method == PJSUA_CONTACT_REWRITE_UNREGISTER) { - /* Unregister current contact */ - pjsua_acc_set_registration(acc->index, PJ_FALSE); - if (acc->regc != NULL) { - pjsip_regc_destroy(acc->regc); - acc->regc = NULL; - acc->contact.slen = 0; - } + /* Unregister current contact */ + pjsua_acc_set_registration(acc->index, PJ_FALSE); + if (acc->regc != NULL) { + pjsip_regc_destroy(acc->regc); + acc->regc = NULL; + acc->contact.slen = 0; + } } /* * Build new Contact header */ { - const char *ob = ";ob"; - char *tmp; - const char *beginquote, *endquote; - char transport_param[32]; - int len; - pj_bool_t secure; - - secure = pjsip_transport_get_flag_from_type(tp->key.type) & - PJSIP_TRANSPORT_SECURE; - + const char *ob = ";ob"; + char *tmp; + const char *beginquote, *endquote; + char transport_param[32]; + int len; + pj_bool_t secure; + + secure = pjsip_transport_get_flag_from_type(tp->key.type) & + PJSIP_TRANSPORT_SECURE; + /* Enclose IPv6 address in square brackets */ if (tp->key.type & PJSIP_TRANSPORT_IPV6) { beginquote = "["; @@ -1917,53 +1916,53 @@ static pj_bool_t acc_check_nat_addr(pjsua_acc *acc, beginquote = endquote = ""; } - /* Don't add transport parameter if it's UDP */ - if (tp->key.type != PJSIP_TRANSPORT_UDP && - tp->key.type != PJSIP_TRANSPORT_UDP6) - { - pj_ansi_snprintf(transport_param, sizeof(transport_param), - ";transport=%s", - pjsip_transport_get_type_name( - (pjsip_transport_type_e)tp->key.type)); - } else { - transport_param[0] = '\0'; - } - - tmp = (char*) pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE); - len = pj_ansi_snprintf(tmp, PJSIP_MAX_URL_SIZE, - "<%s:%.*s%s%s%.*s%s:%d%s%.*s%s>%.*s", - ((secure && acc->is_sips)? "sips" : "sip"), - (int)acc->user_part.slen, - acc->user_part.ptr, - (acc->user_part.slen? "@" : ""), - beginquote, - (int)via_addr->slen, - via_addr->ptr, - endquote, - rport, - transport_param, - (int)acc->cfg.contact_uri_params.slen, - acc->cfg.contact_uri_params.ptr, - (acc->cfg.use_rfc5626? ob: ""), - (int)acc->cfg.contact_params.slen, - acc->cfg.contact_params.ptr); - if (len < 1 || len >= PJSIP_MAX_URL_SIZE) { - PJ_LOG(1,(THIS_FILE, "URI too long")); - pj_pool_release(pool); - return PJ_FALSE; - } - pj_strdup2_with_null(acc->pool, &acc->contact, tmp); - - update_regc_contact(acc); - - /* Always update, by https://github.com/pjsip/pjproject/issues/864. */ + /* Don't add transport parameter if it's UDP */ + if (tp->key.type != PJSIP_TRANSPORT_UDP && + tp->key.type != PJSIP_TRANSPORT_UDP6) + { + pj_ansi_snprintf(transport_param, sizeof(transport_param), + ";transport=%s", + pjsip_transport_get_type_name( + (pjsip_transport_type_e)tp->key.type)); + } else { + transport_param[0] = '\0'; + } + + tmp = (char*) pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE); + len = pj_ansi_snprintf(tmp, PJSIP_MAX_URL_SIZE, + "<%s:%.*s%s%s%.*s%s:%d%s%.*s%s>%.*s", + ((secure && acc->is_sips)? "sips" : "sip"), + (int)acc->user_part.slen, + acc->user_part.ptr, + (acc->user_part.slen? "@" : ""), + beginquote, + (int)via_addr->slen, + via_addr->ptr, + endquote, + rport, + transport_param, + (int)acc->cfg.contact_uri_params.slen, + acc->cfg.contact_uri_params.ptr, + (acc->cfg.use_rfc5626? ob: ""), + (int)acc->cfg.contact_params.slen, + acc->cfg.contact_params.ptr); + if (len < 1 || len >= PJSIP_MAX_URL_SIZE) { + PJ_LOG(1,(THIS_FILE, "URI too long")); + pj_pool_release(pool); + return PJ_FALSE; + } + pj_strdup2_with_null(acc->pool, &acc->contact, tmp); + + update_regc_contact(acc); + + /* Always update, by https://github.com/pjsip/pjproject/issues/864. */ /* Since the Via address will now be overwritten to the correct * address by https://github.com/pjsip/pjproject/issues/1537, we do * not need to update the transport address. */ /* - pj_strdup_with_null(tp->pool, &tp->local_name.host, via_addr); - tp->local_name.port = rport; + pj_strdup_with_null(tp->pool, &tp->local_name.host, via_addr); + tp->local_name.port = rport; */ } @@ -1971,7 +1970,7 @@ static pj_bool_t acc_check_nat_addr(pjsua_acc *acc, if (contact_rewrite_method == PJSUA_CONTACT_REWRITE_NO_UNREG && acc->regc != NULL) { - pjsip_regc_update_contact(acc->regc, 1, &acc->reg_contact); + pjsip_regc_update_contact(acc->regc, 1, &acc->reg_contact); } /* Perform new registration */ @@ -1997,59 +1996,59 @@ static void update_service_route(pjsua_acc *acc, pjsip_rx_data *rdata) /* Find and parse Service-Route headers */ for (;;) { - char saved; - int parsed_len; - - /* Find Service-Route header */ - hsr = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &HNAME, hsr); - if (!hsr) - break; - - /* Parse as Route header since the syntax is similar. This may - * return more than one headers. - */ - saved = hsr->hvalue.ptr[hsr->hvalue.slen]; - hsr->hvalue.ptr[hsr->hvalue.slen] = '\0'; - hr = (pjsip_route_hdr*) - pjsip_parse_hdr(rdata->tp_info.pool, &HROUTE, hsr->hvalue.ptr, - hsr->hvalue.slen, &parsed_len); - hsr->hvalue.ptr[hsr->hvalue.slen] = saved; - - if (hr == NULL) { - /* Error */ - PJ_LOG(1,(THIS_FILE, "Error parsing Service-Route header")); - return; - } - - /* Save each URI in the result */ - h = hr; - do { - if (!PJSIP_URI_SCHEME_IS_SIP(h->name_addr.uri) && - !PJSIP_URI_SCHEME_IS_SIPS(h->name_addr.uri)) - { - PJ_LOG(1,(THIS_FILE,"Error: non SIP URI in Service-Route: %.*s", - (int)hsr->hvalue.slen, hsr->hvalue.ptr)); - return; - } - - uri[uri_cnt++] = h->name_addr.uri; - h = h->next; - } while (h != hr && uri_cnt != PJ_ARRAY_SIZE(uri)); - - if (h != hr) { - PJ_LOG(1,(THIS_FILE, "Error: too many Service-Route headers")); - return; - } - - /* Prepare to find next Service-Route header */ - hsr = hsr->next; - if ((void*)hsr == (void*)&rdata->msg_info.msg->hdr) - break; + char saved; + int parsed_len; + + /* Find Service-Route header */ + hsr = (pjsip_generic_string_hdr*) + pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &HNAME, hsr); + if (!hsr) + break; + + /* Parse as Route header since the syntax is similar. This may + * return more than one headers. + */ + saved = hsr->hvalue.ptr[hsr->hvalue.slen]; + hsr->hvalue.ptr[hsr->hvalue.slen] = '\0'; + hr = (pjsip_route_hdr*) + pjsip_parse_hdr(rdata->tp_info.pool, &HROUTE, hsr->hvalue.ptr, + hsr->hvalue.slen, &parsed_len); + hsr->hvalue.ptr[hsr->hvalue.slen] = saved; + + if (hr == NULL) { + /* Error */ + PJ_LOG(1,(THIS_FILE, "Error parsing Service-Route header")); + return; + } + + /* Save each URI in the result */ + h = hr; + do { + if (!PJSIP_URI_SCHEME_IS_SIP(h->name_addr.uri) && + !PJSIP_URI_SCHEME_IS_SIPS(h->name_addr.uri)) + { + PJ_LOG(1,(THIS_FILE,"Error: non SIP URI in Service-Route: %.*s", + (int)hsr->hvalue.slen, hsr->hvalue.ptr)); + return; + } + + uri[uri_cnt++] = h->name_addr.uri; + h = h->next; + } while (h != hr && uri_cnt != PJ_ARRAY_SIZE(uri)); + + if (h != hr) { + PJ_LOG(1,(THIS_FILE, "Error: too many Service-Route headers")); + return; + } + + /* Prepare to find next Service-Route header */ + hsr = hsr->next; + if ((void*)hsr == (void*)&rdata->msg_info.msg->hdr) + break; } if (uri_cnt == 0) - return; + return; /* * Update account's route set @@ -2058,28 +2057,28 @@ static void update_service_route(pjsua_acc *acc, pjsip_rx_data *rdata) /* First remove all routes which are not the outbound proxies */ rcnt = pj_list_size(&acc->route_set); if (rcnt != pjsua_var.ua_cfg.outbound_proxy_cnt + acc->cfg.proxy_cnt) { - for (i=pjsua_var.ua_cfg.outbound_proxy_cnt + acc->cfg.proxy_cnt, - hr=acc->route_set.prev; - iprev; - pj_list_erase(hr); - hr = prev; - } + for (i=pjsua_var.ua_cfg.outbound_proxy_cnt + acc->cfg.proxy_cnt, + hr=acc->route_set.prev; + iprev; + pj_list_erase(hr); + hr = prev; + } } /* Then append the Service-Route URIs */ for (i=0; ipool); - hr->name_addr.uri = (pjsip_uri*)pjsip_uri_clone(acc->pool, uri[i]); - pj_list_push_back(&acc->route_set, hr); + hr = pjsip_route_hdr_create(acc->pool); + hr->name_addr.uri = (pjsip_uri*)pjsip_uri_clone(acc->pool, uri[i]); + pj_list_push_back(&acc->route_set, hr); } /* Done */ PJ_LOG(4,(THIS_FILE, "Service-Route updated for acc %d with %d URI(s)", - acc->index, uri_cnt)); + acc->index, uri_cnt)); } /* Keep alive timer callback */ @@ -2105,7 +2104,7 @@ static void keep_alive_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te) * while the keep-alive timer was about to be called (race condition). */ if (acc->ka_transport == NULL) - goto on_return; + goto on_return; /* Select the transport to send the packet */ pj_bzero(&tp_sel, sizeof(tp_sel)); @@ -2113,20 +2112,20 @@ static void keep_alive_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te) tp_sel.u.transport = acc->ka_transport; PJ_LOG(5,(THIS_FILE, - "Sending %d bytes keep-alive packet for acc %d to %s", - acc->cfg.ka_data.slen, acc->index, - pj_sockaddr_print(&acc->ka_target, addrtxt, sizeof(addrtxt),3))); + "Sending %d bytes keep-alive packet for acc %d to %s", + acc->cfg.ka_data.slen, acc->index, + pj_sockaddr_print(&acc->ka_target, addrtxt, sizeof(addrtxt),3))); /* Send raw packet */ status = pjsip_tpmgr_send_raw(pjsip_endpt_get_tpmgr(pjsua_var.endpt), - acc->ka_transport->key.type, &tp_sel, - NULL, acc->cfg.ka_data.ptr, - acc->cfg.ka_data.slen, - &acc->ka_target, acc->ka_target_len, - NULL, NULL); + acc->ka_transport->key.type, &tp_sel, + NULL, acc->cfg.ka_data.ptr, + acc->cfg.ka_data.slen, + &acc->ka_target, acc->ka_target_len, + NULL, NULL); if (status != PJ_SUCCESS && status != PJ_EPENDING) { - pjsua_perror(THIS_FILE, "Error sending keep-alive packet", status); + pjsua_perror(THIS_FILE, "Error sending keep-alive packet", status); } /* Check just in case keep-alive has been disabled. This shouldn't happen @@ -2136,10 +2135,10 @@ static void keep_alive_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te) * Also check if Flow Timer (rfc5626) is not set. */ if (acc->cfg.ka_interval == 0 && acc->rfc5626_flowtmr == 0) - goto on_return; + goto on_return; ka_timer = acc->rfc5626_flowtmr ? acc->rfc5626_flowtmr : - acc->cfg.ka_interval; + acc->cfg.ka_interval; lower_bound = (unsigned)((float)ka_timer * 0.8f); delay.sec = pj_rand() % (ka_timer - lower_bound) + lower_bound; @@ -2148,9 +2147,9 @@ static void keep_alive_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te) /* Reschedule next timer */ status = pjsip_endpt_schedule_timer(pjsua_var.endpt, te, &delay); if (status == PJ_SUCCESS) { - te->id = PJ_TRUE; + te->id = PJ_TRUE; } else { - pjsua_perror(THIS_FILE, "Error starting keep-alive timer", status); + pjsua_perror(THIS_FILE, "Error starting keep-alive timer", status); } on_return: @@ -2160,112 +2159,112 @@ static void keep_alive_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te) /* Update keep-alive for the account */ static void update_keep_alive(pjsua_acc *acc, pj_bool_t start, - struct pjsip_regc_cbparam *param) + struct pjsip_regc_cbparam *param) { /* In all cases, stop keep-alive timer if it's running. */ if (acc->ka_timer.id) { - pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer); - acc->ka_timer.id = PJ_FALSE; + pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer); + acc->ka_timer.id = PJ_FALSE; - if (acc->ka_transport) { - pjsip_transport_dec_ref(acc->ka_transport); - acc->ka_transport = NULL; - } + if (acc->ka_transport) { + pjsip_transport_dec_ref(acc->ka_transport); + acc->ka_transport = NULL; + } } if (start) { - pj_time_val delay; - pj_status_t status; - pjsip_generic_string_hdr *hsr = NULL; - unsigned ka_timer; - unsigned lower_bound; - - static const pj_str_t STR_FLOW_TIMER = { "Flow-Timer", 10 }; - - hsr = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(param->rdata->msg_info.msg, - &STR_FLOW_TIMER, hsr); - - if (hsr) { - acc->rfc5626_flowtmr = pj_strtoul(&hsr->hvalue); - } - - /* Only do keep-alive if: - * - REGISTER response contain Flow-Timer header, otherwise - * - ka_interval is not zero in the account, and - * - transport is UDP. - * - * Previously we only enabled keep-alive when STUN is enabled, since - * we thought that keep-alive is only needed in Internet situation. - * But it has been discovered that Windows Firewall on WinXP also - * needs to be kept-alive, otherwise incoming packets will be dropped. - * So because of this, now keep-alive is always enabled for UDP, - * regardless of whether STUN is enabled or not. - * - * Note that this applies only for UDP. For TCP/TLS, the keep-alive - * is done by the transport layer. - */ - if (/*pjsua_var.stun_srv.ipv4.sin_family == 0 ||*/ - ((acc->cfg.ka_interval == 0) && (acc->rfc5626_flowtmr == 0)) || - (!hsr && ((param->rdata->tp_info.transport->key.type & - ~PJSIP_TRANSPORT_IPV6) != PJSIP_TRANSPORT_UDP))) - { - /* Keep alive is not necessary */ - return; - } - - /* Save transport and destination address. */ - acc->ka_transport = param->rdata->tp_info.transport; - pjsip_transport_add_ref(acc->ka_transport); - - /* https://github.com/pjsip/pjproject/issues/1607: - * Calculate the destination address from the original request. Some - * (broken) servers send the response using different source address - * than the one that receives the request, which is forbidden by RFC - * 3581. - */ - { - pjsip_transaction *tsx; - pjsip_tx_data *req; - - tsx = pjsip_rdata_get_tsx(param->rdata); - PJ_ASSERT_ON_FAIL(tsx, return); - - req = tsx->last_tx; - - pj_memcpy(&acc->ka_target, &req->tp_info.dst_addr, - req->tp_info.dst_addr_len); - acc->ka_target_len = req->tp_info.dst_addr_len; - } - - /* Setup and start the timer */ - acc->ka_timer.cb = &keep_alive_timer_cb; - acc->ka_timer.user_data = (void*)acc; - - ka_timer = acc->rfc5626_flowtmr ? acc->rfc5626_flowtmr : - acc->cfg.ka_interval; - - lower_bound = (unsigned)((float)ka_timer * 0.8f); - delay.sec = pj_rand() % (ka_timer - lower_bound) + lower_bound; - delay.msec = 0; - status = pjsip_endpt_schedule_timer(pjsua_var.endpt, &acc->ka_timer, - &delay); - if (status == PJ_SUCCESS) { - char addr[PJ_INET6_ADDRSTRLEN+10]; - pj_str_t input_str = pj_str(param->rdata->pkt_info.src_name); - acc->ka_timer.id = PJ_TRUE; - - pj_addr_str_print(&input_str, param->rdata->pkt_info.src_port, - addr, sizeof(addr), 1); - PJ_LOG(4,(THIS_FILE, "Keep-alive timer started for acc %d, " - "destination:%s, interval:%ds", - acc->index, addr, delay.sec)); - } else { - acc->ka_timer.id = PJ_FALSE; - pjsip_transport_dec_ref(acc->ka_transport); - acc->ka_transport = NULL; - pjsua_perror(THIS_FILE, "Error starting keep-alive timer", status); - } + pj_time_val delay; + pj_status_t status; + pjsip_generic_string_hdr *hsr = NULL; + unsigned ka_timer; + unsigned lower_bound; + + static const pj_str_t STR_FLOW_TIMER = { "Flow-Timer", 10 }; + + hsr = (pjsip_generic_string_hdr*) + pjsip_msg_find_hdr_by_name(param->rdata->msg_info.msg, + &STR_FLOW_TIMER, hsr); + + if (hsr) { + acc->rfc5626_flowtmr = pj_strtoul(&hsr->hvalue); + } + + /* Only do keep-alive if: + * - REGISTER response contain Flow-Timer header, otherwise + * - ka_interval is not zero in the account, and + * - transport is UDP. + * + * Previously we only enabled keep-alive when STUN is enabled, since + * we thought that keep-alive is only needed in Internet situation. + * But it has been discovered that Windows Firewall on WinXP also + * needs to be kept-alive, otherwise incoming packets will be dropped. + * So because of this, now keep-alive is always enabled for UDP, + * regardless of whether STUN is enabled or not. + * + * Note that this applies only for UDP. For TCP/TLS, the keep-alive + * is done by the transport layer. + */ + if (/*pjsua_var.stun_srv.ipv4.sin_family == 0 ||*/ + ((acc->cfg.ka_interval == 0) && (acc->rfc5626_flowtmr == 0)) || + (!hsr && ((param->rdata->tp_info.transport->key.type & + ~PJSIP_TRANSPORT_IPV6) != PJSIP_TRANSPORT_UDP))) + { + /* Keep alive is not necessary */ + return; + } + + /* Save transport and destination address. */ + acc->ka_transport = param->rdata->tp_info.transport; + pjsip_transport_add_ref(acc->ka_transport); + + /* https://github.com/pjsip/pjproject/issues/1607: + * Calculate the destination address from the original request. Some + * (broken) servers send the response using different source address + * than the one that receives the request, which is forbidden by RFC + * 3581. + */ + { + pjsip_transaction *tsx; + pjsip_tx_data *req; + + tsx = pjsip_rdata_get_tsx(param->rdata); + PJ_ASSERT_ON_FAIL(tsx, return); + + req = tsx->last_tx; + + pj_memcpy(&acc->ka_target, &req->tp_info.dst_addr, + req->tp_info.dst_addr_len); + acc->ka_target_len = req->tp_info.dst_addr_len; + } + + /* Setup and start the timer */ + acc->ka_timer.cb = &keep_alive_timer_cb; + acc->ka_timer.user_data = (void*)acc; + + ka_timer = acc->rfc5626_flowtmr ? acc->rfc5626_flowtmr : + acc->cfg.ka_interval; + + lower_bound = (unsigned)((float)ka_timer * 0.8f); + delay.sec = pj_rand() % (ka_timer - lower_bound) + lower_bound; + delay.msec = 0; + status = pjsip_endpt_schedule_timer(pjsua_var.endpt, &acc->ka_timer, + &delay); + if (status == PJ_SUCCESS) { + char addr[PJ_INET6_ADDRSTRLEN+10]; + pj_str_t input_str = pj_str(param->rdata->pkt_info.src_name); + acc->ka_timer.id = PJ_TRUE; + + pj_addr_str_print(&input_str, param->rdata->pkt_info.src_port, + addr, sizeof(addr), 1); + PJ_LOG(4,(THIS_FILE, "Keep-alive timer started for acc %d, " + "destination:%s, interval:%ds", + acc->index, addr, delay.sec)); + } else { + acc->ka_timer.id = PJ_FALSE; + pjsip_transport_dec_ref(acc->ka_transport); + acc->ka_transport = NULL; + pjsua_perror(THIS_FILE, "Error starting keep-alive timer", status); + } } } @@ -2278,20 +2277,20 @@ static void update_rfc5626_status(pjsua_acc *acc, pjsip_rx_data *rdata) unsigned i; if (acc->rfc5626_status == OUTBOUND_UNKNOWN) { - goto on_return; + goto on_return; } hreq = rdata->msg_info.require; if (!hreq) { - acc->rfc5626_status = OUTBOUND_NA; - goto on_return; + acc->rfc5626_status = OUTBOUND_NA; + goto on_return; } for (i=0; icount; ++i) { - if (pj_stricmp(&hreq->values[i], &STR_OUTBOUND)==0) { - acc->rfc5626_status = OUTBOUND_ACTIVE; - goto on_return; - } + if (pj_stricmp(&hreq->values[i], &STR_OUTBOUND)==0) { + acc->rfc5626_status = OUTBOUND_ACTIVE; + goto on_return; + } } /* Server does not support outbound */ @@ -2299,11 +2298,11 @@ static void update_rfc5626_status(pjsua_acc *acc, pjsip_rx_data *rdata) on_return: if (acc->rfc5626_status != OUTBOUND_ACTIVE) { - acc->reg_contact = acc->contact; + acc->reg_contact = acc->contact; } PJ_LOG(4,(THIS_FILE, "SIP outbound status for acc %d is %s", - acc->index, (acc->rfc5626_status==OUTBOUND_ACTIVE? - "active": "not active"))); + acc->index, (acc->rfc5626_status==OUTBOUND_ACTIVE? + "active": "not active"))); } static void regc_tsx_cb(struct pjsip_regc_tsx_cb_param *param) @@ -2314,7 +2313,7 @@ static void regc_tsx_cb(struct pjsip_regc_tsx_cb_param *param) if (param->cbparam.regc != acc->regc) { PJSUA_UNLOCK(); - return; + return; } pj_log_push_indent(); @@ -2324,7 +2323,7 @@ static void regc_tsx_cb(struct pjsip_regc_tsx_cb_param *param) * the current contact generated from last 2xx. */ if (!acc->contact_rewritten && - (acc->cfg.contact_rewrite_method & + (acc->cfg.contact_rewrite_method & PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE) == PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE && param->cbparam.code >= 400 && @@ -2336,9 +2335,9 @@ static void regc_tsx_cb(struct pjsip_regc_tsx_cb_param *param) param->contact_cnt = 1; param->contact[0] = acc->reg_contact; - /* Don't set 'contact_rewritten' to PJ_TRUE here to allow - * further check of NAT bound address in 2xx response. - */ + /* Don't set 'contact_rewritten' to PJ_TRUE here to allow + * further check of NAT bound address in 2xx response. + */ } } @@ -2368,7 +2367,7 @@ static void regc_cb(struct pjsip_regc_cbparam *param) if (param->regc != acc->regc) { PJSUA_UNLOCK(); - return; + return; } pj_log_push_indent(); @@ -2377,97 +2376,97 @@ static void regc_cb(struct pjsip_regc_cbparam *param) * Print registration status. */ if (param->status!=PJ_SUCCESS) { - pj_status_t status; + pj_status_t status; - pjsua_perror(THIS_FILE, "SIP registration error", - param->status); + pjsua_perror(THIS_FILE, "SIP registration error", + param->status); - if (param->status == PJSIP_EBUSY) { - pj_log_pop_indent(); + if (param->status == PJSIP_EBUSY) { + pj_log_pop_indent(); PJSUA_UNLOCK(); - return; - } - - /* This callback is called without holding the registration's lock, - * so there can be a race condition with another registration - * process. Therefore, we must not forcefully try to destroy - * the registration here. - */ - status = pjsip_regc_destroy2(acc->regc, PJ_FALSE); - if (status == PJ_SUCCESS) { - acc->regc = NULL; - acc->contact.slen = 0; - acc->reg_mapped_addr.slen = 0; - acc->rfc5626_status = OUTBOUND_UNKNOWN; - acc->rfc5626_flowtmr = 0; - - /* Stop keep-alive timer if any. */ - update_keep_alive(acc, PJ_FALSE, NULL); - } else { - /* Another registration is in progress. */ - pj_assert(status == PJ_EBUSY); - pjsua_perror(THIS_FILE, "Deleting registration failed", - status); - } + return; + } + + /* This callback is called without holding the registration's lock, + * so there can be a race condition with another registration + * process. Therefore, we must not forcefully try to destroy + * the registration here. + */ + status = pjsip_regc_destroy2(acc->regc, PJ_FALSE); + if (status == PJ_SUCCESS) { + acc->regc = NULL; + acc->contact.slen = 0; + acc->reg_mapped_addr.slen = 0; + acc->rfc5626_status = OUTBOUND_UNKNOWN; + acc->rfc5626_flowtmr = 0; + + /* Stop keep-alive timer if any. */ + update_keep_alive(acc, PJ_FALSE, NULL); + } else { + /* Another registration is in progress. */ + pj_assert(status == PJ_EBUSY); + pjsua_perror(THIS_FILE, "Deleting registration failed", + status); + } } else if (param->code < 0 || param->code >= 300) { - PJ_LOG(2, (THIS_FILE, "SIP registration failed, status=%d (%.*s)", - param->code, - (int)param->reason.slen, param->reason.ptr)); - pjsip_regc_destroy(acc->regc); - acc->regc = NULL; - acc->contact.slen = 0; - acc->reg_mapped_addr.slen = 0; - acc->rfc5626_status = OUTBOUND_UNKNOWN; - acc->rfc5626_flowtmr = 0; - - /* Stop keep-alive timer if any. */ - update_keep_alive(acc, PJ_FALSE, NULL); + PJ_LOG(2, (THIS_FILE, "SIP registration failed, status=%d (%.*s)", + param->code, + (int)param->reason.slen, param->reason.ptr)); + pjsip_regc_destroy(acc->regc); + acc->regc = NULL; + acc->contact.slen = 0; + acc->reg_mapped_addr.slen = 0; + acc->rfc5626_status = OUTBOUND_UNKNOWN; + acc->rfc5626_flowtmr = 0; + + /* Stop keep-alive timer if any. */ + update_keep_alive(acc, PJ_FALSE, NULL); } else if (PJSIP_IS_STATUS_IN_CLASS(param->code, 200)) { - /* Update auto registration flag */ - acc->auto_rereg.active = PJ_FALSE; - acc->auto_rereg.attempt_cnt = 0; + /* Update auto registration flag */ + acc->auto_rereg.active = PJ_FALSE; + acc->auto_rereg.attempt_cnt = 0; - if (param->expiration < 1) { - pjsip_regc_destroy(acc->regc); - acc->regc = NULL; - acc->contact.slen = 0; - acc->reg_mapped_addr.slen = 0; - acc->rfc5626_status = OUTBOUND_UNKNOWN; - acc->rfc5626_flowtmr = 0; + if (param->expiration < 1) { + pjsip_regc_destroy(acc->regc); + acc->regc = NULL; + acc->contact.slen = 0; + acc->reg_mapped_addr.slen = 0; + acc->rfc5626_status = OUTBOUND_UNKNOWN; + acc->rfc5626_flowtmr = 0; - /* Reset pointer to registration transport */ - //acc->auto_rereg.reg_tp = NULL; + /* Reset pointer to registration transport */ + //acc->auto_rereg.reg_tp = NULL; - /* Stop keep-alive timer if any. */ - update_keep_alive(acc, PJ_FALSE, NULL); + /* Stop keep-alive timer if any. */ + update_keep_alive(acc, PJ_FALSE, NULL); - PJ_LOG(3,(THIS_FILE, "%s: unregistration success", - pjsua_var.acc[acc->index].cfg.id.ptr)); + PJ_LOG(3,(THIS_FILE, "%s: unregistration success", + pjsua_var.acc[acc->index].cfg.id.ptr)); - } else { - /* Check and update SIP outbound status first, since the result - * will determine if we should update re-registration - */ - update_rfc5626_status(acc, param->rdata); + } else { + /* Check and update SIP outbound status first, since the result + * will determine if we should update re-registration + */ + update_rfc5626_status(acc, param->rdata); - /* Check NAT bound address if it hasn't been done before */ + /* Check NAT bound address if it hasn't been done before */ if (!acc->contact_rewritten && - acc_check_nat_addr(acc, (acc->cfg.contact_rewrite_method & 3), + acc_check_nat_addr(acc, (acc->cfg.contact_rewrite_method & 3), param)) { - PJSUA_UNLOCK(); - pj_log_pop_indent(); + PJSUA_UNLOCK(); + pj_log_pop_indent(); - /* Avoid another check of NAT bound address */ - acc->contact_rewritten = PJ_TRUE; - return; - } + /* Avoid another check of NAT bound address */ + acc->contact_rewritten = PJ_TRUE; + return; + } - /* Check and update Service-Route header */ - update_service_route(acc, param->rdata); + /* Check and update Service-Route header */ + update_service_route(acc, param->rdata); #if PJSUA_REG_AUTO_REG_REFRESH @@ -2489,20 +2488,20 @@ static void regc_cb(struct pjsip_regc_cbparam *param) (int)param->reason.slen, param->reason.ptr)); #endif - /* Start keep-alive timer if necessary. */ - update_keep_alive(acc, PJ_TRUE, param); + /* Start keep-alive timer if necessary. */ + update_keep_alive(acc, PJ_TRUE, param); - /* Send initial PUBLISH if it is enabled */ - if (acc->cfg.publish_enabled && acc->publish_sess==NULL) - pjsua_pres_init_publish_acc(acc->index); + /* Send initial PUBLISH if it is enabled */ + if (acc->cfg.publish_enabled && acc->publish_sess==NULL) + pjsua_pres_init_publish_acc(acc->index); - /* Subscribe to MWI, if it's enabled */ - if (acc->cfg.mwi_enabled) - pjsua_start_mwi(acc->index, PJ_FALSE); + /* Subscribe to MWI, if it's enabled */ + if (acc->cfg.mwi_enabled) + pjsua_start_mwi(acc->index, PJ_FALSE); - } + } } else { - PJ_LOG(4, (THIS_FILE, "SIP registration updated status=%d", param->code)); + PJ_LOG(4, (THIS_FILE, "SIP registration updated status=%d", param->code)); } acc->reg_last_err = param->status; @@ -2516,81 +2515,81 @@ static void regc_cb(struct pjsip_regc_cbparam *param) * considered to be recoverable in relatively short term. */ if (acc->cfg.reg_retry_interval && - acc->ip_change_op != PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT && - (param->code == PJSIP_SC_REQUEST_TIMEOUT || - param->code == PJSIP_SC_INTERNAL_SERVER_ERROR || - param->code == PJSIP_SC_BAD_GATEWAY || - param->code == PJSIP_SC_SERVICE_UNAVAILABLE || - param->code == PJSIP_SC_SERVER_TIMEOUT || - param->code == PJSIP_SC_TEMPORARILY_UNAVAILABLE || - PJSIP_IS_STATUS_IN_CLASS(param->code, 600))) /* Global failure */ + acc->ip_change_op != PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT && + (param->code == PJSIP_SC_REQUEST_TIMEOUT || + param->code == PJSIP_SC_INTERNAL_SERVER_ERROR || + param->code == PJSIP_SC_BAD_GATEWAY || + param->code == PJSIP_SC_SERVICE_UNAVAILABLE || + param->code == PJSIP_SC_SERVER_TIMEOUT || + param->code == PJSIP_SC_TEMPORARILY_UNAVAILABLE || + PJSIP_IS_STATUS_IN_CLASS(param->code, 600))) /* Global failure */ { - schedule_reregistration(acc); + schedule_reregistration(acc); } /* Call the registration status callback */ if (pjsua_var.ua_cfg.cb.on_reg_state) { - (*pjsua_var.ua_cfg.cb.on_reg_state)(acc->index); + (*pjsua_var.ua_cfg.cb.on_reg_state)(acc->index); } if (pjsua_var.ua_cfg.cb.on_reg_state2) { - pjsua_reg_info reg_info; - pjsip_regc_info rinfo; + pjsua_reg_info reg_info; + pjsip_regc_info rinfo; - pjsip_regc_get_info(param->regc, &rinfo); - reg_info.cbparam = param; - reg_info.regc = param->regc; - reg_info.renew = !param->is_unreg; - (*pjsua_var.ua_cfg.cb.on_reg_state2)(acc->index, ®_info); + pjsip_regc_get_info(param->regc, &rinfo); + reg_info.cbparam = param; + reg_info.regc = param->regc; + reg_info.renew = !param->is_unreg; + (*pjsua_var.ua_cfg.cb.on_reg_state2)(acc->index, ®_info); } if (acc->ip_change_op == PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT) { - if (pjsua_var.ua_cfg.cb.on_ip_change_progress) { - pjsua_ip_change_op_info ip_chg_info; - pjsip_regc_info rinfo; - - pj_bzero(&ip_chg_info, sizeof(ip_chg_info)); - pjsip_regc_get_info(param->regc, &rinfo); - ip_chg_info.acc_update_contact.acc_id = acc->index; - ip_chg_info.acc_update_contact.code = param->code; - ip_chg_info.acc_update_contact.is_register = !param->is_unreg; - (*pjsua_var.ua_cfg.cb.on_ip_change_progress)(acc->ip_change_op, - param->status, - &ip_chg_info); - } - - if (PJSIP_IS_STATUS_IN_CLASS(param->code, 200)) { - if (param->expiration < 1) { - pj_status_t status; - /* Send re-register. */ - PJ_LOG(3, (THIS_FILE, "%.*s: send registration triggered by IP" - " change", pjsua_var.acc[acc->index].cfg.id.slen, - pjsua_var.acc[acc->index].cfg.id.ptr)); - - status = pjsua_acc_set_registration(acc->index, PJ_TRUE); - if (status != PJ_SUCCESS) { - if (pjsua_var.ua_cfg.cb.on_ip_change_progress) { - pjsua_ip_change_op_info ip_chg_info; - - pj_bzero(&ip_chg_info, sizeof(ip_chg_info)); - ip_chg_info.acc_update_contact.acc_id = acc->index; - ip_chg_info.acc_update_contact.is_register = PJ_TRUE; - (*pjsua_var.ua_cfg.cb.on_ip_change_progress)( - acc->ip_change_op, - status, - &ip_chg_info); - } - pjsua_acc_end_ip_change(acc); - } - } else { + if (pjsua_var.ua_cfg.cb.on_ip_change_progress) { + pjsua_ip_change_op_info ip_chg_info; + pjsip_regc_info rinfo; + + pj_bzero(&ip_chg_info, sizeof(ip_chg_info)); + pjsip_regc_get_info(param->regc, &rinfo); + ip_chg_info.acc_update_contact.acc_id = acc->index; + ip_chg_info.acc_update_contact.code = param->code; + ip_chg_info.acc_update_contact.is_register = !param->is_unreg; + (*pjsua_var.ua_cfg.cb.on_ip_change_progress)(acc->ip_change_op, + param->status, + &ip_chg_info); + } + + if (PJSIP_IS_STATUS_IN_CLASS(param->code, 200)) { + if (param->expiration < 1) { + pj_status_t status; + /* Send re-register. */ + PJ_LOG(3, (THIS_FILE, "%.*s: send registration triggered by IP" + " change", pjsua_var.acc[acc->index].cfg.id.slen, + pjsua_var.acc[acc->index].cfg.id.ptr)); + + status = pjsua_acc_set_registration(acc->index, PJ_TRUE); + if (status != PJ_SUCCESS) { + if (pjsua_var.ua_cfg.cb.on_ip_change_progress) { + pjsua_ip_change_op_info ip_chg_info; + + pj_bzero(&ip_chg_info, sizeof(ip_chg_info)); + ip_chg_info.acc_update_contact.acc_id = acc->index; + ip_chg_info.acc_update_contact.is_register = PJ_TRUE; + (*pjsua_var.ua_cfg.cb.on_ip_change_progress)( + acc->ip_change_op, + status, + &ip_chg_info); + } + pjsua_acc_end_ip_change(acc); + } + } else { /* Avoid deadlock issue when sending BYE or Re-INVITE. */ - pjsua_schedule_timer2(&handle_call_on_ip_change_cb, - (void*)acc, 0); - } - } else { - pjsua_acc_end_ip_change(acc); - } + pjsua_schedule_timer2(&handle_call_on_ip_change_cb, + (void*)acc, 0); + } + } else { + pjsua_acc_end_ip_change(acc); + } } PJSUA_UNLOCK(); @@ -2611,69 +2610,69 @@ static pj_status_t pjsua_regc_init(int acc_id) acc = &pjsua_var.acc[acc_id]; if (acc->cfg.reg_uri.slen == 0) { - PJ_LOG(3,(THIS_FILE, "Registrar URI is not specified")); - return PJ_SUCCESS; + PJ_LOG(3,(THIS_FILE, "Registrar URI is not specified")); + return PJ_SUCCESS; } /* Destroy existing session, if any */ if (acc->regc) { - pjsip_regc_destroy(acc->regc); - acc->regc = NULL; - acc->contact.slen = 0; - acc->reg_mapped_addr.slen = 0; - acc->rfc5626_status = OUTBOUND_UNKNOWN; + pjsip_regc_destroy(acc->regc); + acc->regc = NULL; + acc->contact.slen = 0; + acc->reg_mapped_addr.slen = 0; + acc->rfc5626_status = OUTBOUND_UNKNOWN; } /* initialize SIP registration if registrar is configured */ status = pjsip_regc_create( pjsua_var.endpt, - acc, ®c_cb, &acc->regc); + acc, ®c_cb, &acc->regc); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create client registration", - status); - return status; + pjsua_perror(THIS_FILE, "Unable to create client registration", + status); + return status; } pool = pjsua_pool_create("tmpregc", 512, 512); if (acc->contact.slen == 0) { - pj_str_t tmp_contact; - - status = pjsua_acc_create_uac_contact( pool, &tmp_contact, - acc_id, &acc->cfg.reg_uri); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to generate suitable Contact header" - " for registration", - status); - pjsip_regc_destroy(acc->regc); - pj_pool_release(pool); - acc->regc = NULL; - return status; - } + pj_str_t tmp_contact; + + status = pjsua_acc_create_uac_contact( pool, &tmp_contact, + acc_id, &acc->cfg.reg_uri); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to generate suitable Contact header" + " for registration", + status); + pjsip_regc_destroy(acc->regc); + pj_pool_release(pool); + acc->regc = NULL; + return status; + } - pj_strdup_with_null(acc->pool, &acc->contact, &tmp_contact); - update_regc_contact(acc); + pj_strdup_with_null(acc->pool, &acc->contact, &tmp_contact); + update_regc_contact(acc); } status = pjsip_regc_init( acc->regc, - &acc->cfg.reg_uri, - &acc->cfg.id, - &acc->cfg.id, - 1, &acc->reg_contact, - acc->cfg.reg_timeout); + &acc->cfg.reg_uri, + &acc->cfg.id, + &acc->cfg.id, + 1, &acc->reg_contact, + acc->cfg.reg_timeout); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Client registration initialization error", - status); - pjsip_regc_destroy(acc->regc); - pj_pool_release(pool); - acc->regc = NULL; - acc->contact.slen = 0; - acc->reg_mapped_addr.slen = 0; - acc->rfc5626_status = OUTBOUND_UNKNOWN; + pjsua_perror(THIS_FILE, + "Client registration initialization error", + status); + pjsip_regc_destroy(acc->regc); + pj_pool_release(pool); + acc->regc = NULL; + acc->contact.slen = 0; + acc->reg_mapped_addr.slen = 0; + acc->rfc5626_status = OUTBOUND_UNKNOWN; - return status; + return status; } pjsip_regc_set_reg_tsx_cb(acc->regc, regc_tsx_cb); @@ -2682,17 +2681,17 @@ static pj_status_t pjsua_regc_init(int acc_id) * the client registration. */ if (pjsua_var.acc[acc_id].cfg.transport_id != PJSUA_INVALID_ID) { - pjsip_tpselector tp_sel; + pjsip_tpselector tp_sel; - pjsua_init_tpselector(pjsua_var.acc[acc_id].cfg.transport_id, &tp_sel); - pjsip_regc_set_transport(acc->regc, &tp_sel); + pjsua_init_tpselector(pjsua_var.acc[acc_id].cfg.transport_id, &tp_sel); + pjsip_regc_set_transport(acc->regc, &tp_sel); } /* Set credentials */ if (acc->cred_cnt) { - pjsip_regc_set_credentials( acc->regc, acc->cred_cnt, acc->cred); + pjsip_regc_set_credentials( acc->regc, acc->cred_cnt, acc->cred); } /* Set delay before registration refresh */ @@ -2705,35 +2704,35 @@ static pj_status_t pjsua_regc_init(int acc_id) /* Set route-set */ if (acc->cfg.reg_use_proxy) { - pjsip_route_hdr route_set; - const pjsip_route_hdr *r; - - pj_list_init(&route_set); + pjsip_route_hdr route_set; + const pjsip_route_hdr *r; - if (acc->cfg.reg_use_proxy & PJSUA_REG_USE_OUTBOUND_PROXY) { - r = pjsua_var.outbound_proxy.next; - while (r != &pjsua_var.outbound_proxy) { - pj_list_push_back(&route_set, pjsip_hdr_shallow_clone(pool, r)); - r = r->next; - } - } + pj_list_init(&route_set); - if (acc->cfg.reg_use_proxy & PJSUA_REG_USE_ACC_PROXY && - acc->cfg.proxy_cnt) - { - int cnt = acc->cfg.proxy_cnt; - pjsip_route_hdr *pos = route_set.prev; - int i; + if (acc->cfg.reg_use_proxy & PJSUA_REG_USE_OUTBOUND_PROXY) { + r = pjsua_var.outbound_proxy.next; + while (r != &pjsua_var.outbound_proxy) { + pj_list_push_back(&route_set, pjsip_hdr_shallow_clone(pool, r)); + r = r->next; + } + } - r = acc->route_set.prev; - for (i=0; iprev; - } - } + if (acc->cfg.reg_use_proxy & PJSUA_REG_USE_ACC_PROXY && + acc->cfg.proxy_cnt) + { + int cnt = acc->cfg.proxy_cnt; + pjsip_route_hdr *pos = route_set.prev; + int i; + + r = acc->route_set.prev; + for (i=0; iprev; + } + } - if (!pj_list_empty(&route_set)) - pjsip_regc_set_route_set( acc->regc, &route_set ); + if (!pj_list_empty(&route_set)) + pjsip_regc_set_route_set( acc->regc, &route_set ); } /* Add custom request headers specified in the account config */ @@ -2741,35 +2740,35 @@ static pj_status_t pjsua_regc_init(int acc_id) /* Add other request headers. */ if (pjsua_var.ua_cfg.user_agent.slen) { - pjsip_hdr hdr_list; - const pj_str_t STR_USER_AGENT = { "User-Agent", 10 }; - pjsip_generic_string_hdr *h; + pjsip_hdr hdr_list; + const pj_str_t STR_USER_AGENT = { "User-Agent", 10 }; + pjsip_generic_string_hdr *h; - pj_list_init(&hdr_list); + pj_list_init(&hdr_list); - h = pjsip_generic_string_hdr_create(pool, &STR_USER_AGENT, - &pjsua_var.ua_cfg.user_agent); - pj_list_push_back(&hdr_list, (pjsip_hdr*)h); + h = pjsip_generic_string_hdr_create(pool, &STR_USER_AGENT, + &pjsua_var.ua_cfg.user_agent); + pj_list_push_back(&hdr_list, (pjsip_hdr*)h); - pjsip_regc_add_headers(acc->regc, &hdr_list); + pjsip_regc_add_headers(acc->regc, &hdr_list); } /* If SIP outbound is used, add "Supported: outbound, path header" */ if (acc->rfc5626_status == OUTBOUND_WANTED || - acc->rfc5626_status == OUTBOUND_ACTIVE) + acc->rfc5626_status == OUTBOUND_ACTIVE) { - pjsip_hdr hdr_list; - pjsip_supported_hdr *hsup; + pjsip_hdr hdr_list; + pjsip_supported_hdr *hsup; - pj_list_init(&hdr_list); - hsup = pjsip_supported_hdr_create(pool); - pj_list_push_back(&hdr_list, hsup); + pj_list_init(&hdr_list); + hsup = pjsip_supported_hdr_create(pool); + pj_list_push_back(&hdr_list, hsup); - hsup->count = 2; - hsup->values[0] = pj_str("outbound"); - hsup->values[1] = pj_str("path"); + hsup->count = 2; + hsup->values[0] = pj_str("outbound"); + hsup->values[1] = pj_str("path"); - pjsip_regc_add_headers(acc->regc, &hdr_list); + pjsip_regc_add_headers(acc->regc, &hdr_list); } pj_pool_release(pool); @@ -2789,7 +2788,7 @@ pj_bool_t pjsua_sip_acc_is_using_stun(pjsua_acc_id acc_id) pjsua_acc *acc = &pjsua_var.acc[acc_id]; return acc->cfg.sip_stun_use != PJSUA_STUN_USE_DISABLED && - pjsua_var.ua_cfg.stun_srv_cnt != 0; + pjsua_var.ua_cfg.stun_srv_cnt != 0; } pj_bool_t pjsua_media_acc_is_using_stun(pjsua_acc_id acc_id) @@ -2797,7 +2796,7 @@ pj_bool_t pjsua_media_acc_is_using_stun(pjsua_acc_id acc_id) pjsua_acc *acc = &pjsua_var.acc[acc_id]; return acc->cfg.media_stun_use != PJSUA_STUN_USE_DISABLED && - pjsua_var.ua_cfg.stun_srv_cnt != 0; + pjsua_var.ua_cfg.stun_srv_cnt != 0; } pj_bool_t pjsua_sip_acc_is_using_upnp(pjsua_acc_id acc_id) @@ -2805,8 +2804,8 @@ pj_bool_t pjsua_sip_acc_is_using_upnp(pjsua_acc_id acc_id) pjsua_acc *acc = &pjsua_var.acc[acc_id]; return acc->cfg.sip_upnp_use != PJSUA_UPNP_USE_DISABLED && - pjsua_var.ua_cfg.enable_upnp && - pjsua_var.upnp_status == PJ_SUCCESS; + pjsua_var.ua_cfg.enable_upnp && + pjsua_var.upnp_status == PJ_SUCCESS; } pj_bool_t pjsua_media_acc_is_using_upnp(pjsua_acc_id acc_id) @@ -2814,26 +2813,26 @@ pj_bool_t pjsua_media_acc_is_using_upnp(pjsua_acc_id acc_id) pjsua_acc *acc = &pjsua_var.acc[acc_id]; return acc->cfg.media_upnp_use != PJSUA_UPNP_USE_DISABLED && - pjsua_var.ua_cfg.enable_upnp && - pjsua_var.upnp_status == PJ_SUCCESS; + pjsua_var.ua_cfg.enable_upnp && + pjsua_var.upnp_status == PJ_SUCCESS; } /* * Update registration or perform unregistration. */ PJ_DEF(pj_status_t) pjsua_acc_set_registration( pjsua_acc_id acc_id, - pj_bool_t renew) + pj_bool_t renew) { pjsua_acc *acc; pj_status_t status = 0; pjsip_tx_data *tdata = 0; PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc), - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP); PJ_LOG(4,(THIS_FILE, "Acc %d: setting %sregistration..", - acc_id, (renew? "" : "un"))); + acc_id, (renew? "" : "un"))); pj_log_push_indent(); PJSUA_LOCK(); @@ -2842,8 +2841,8 @@ PJ_DEF(pj_status_t) pjsua_acc_set_registration( pjsua_acc_id acc_id, /* Cancel any re-registration timer */ if (pjsua_var.acc[acc_id].auto_rereg.timer.id) { - pjsua_var.acc[acc_id].auto_rereg.timer.id = PJ_FALSE; - pjsua_cancel_timer(&pjsua_var.acc[acc_id].auto_rereg.timer); + pjsua_var.acc[acc_id].auto_rereg.timer.id = PJ_FALSE; + pjsua_cancel_timer(&pjsua_var.acc[acc_id].auto_rereg.timer); } /* Reset pointer to registration transport */ @@ -2854,54 +2853,54 @@ PJ_DEF(pj_status_t) pjsua_acc_set_registration( pjsua_acc_id acc_id, //pjsua_var.acc[acc_id].auto_rereg.reg_tp = NULL; if (renew) { - if (pjsua_var.acc[acc_id].regc == NULL) { - status = pjsua_regc_init(acc_id); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create registration", - status); - goto on_return; - } - } - if (!pjsua_var.acc[acc_id].regc) { - status = PJ_EINVALIDOP; - goto on_return; - } - - status = pjsip_regc_register(pjsua_var.acc[acc_id].regc, - PJSUA_REG_AUTO_REG_REFRESH, - &tdata); - - if (0 && status == PJ_SUCCESS && pjsua_var.acc[acc_id].cred_cnt) { - pjsip_authorization_hdr *h; - char *uri; - int d; - - uri = (char*) pj_pool_alloc(tdata->pool, acc->cfg.reg_uri.slen+10); - d = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, tdata->msg->line.req.uri, - uri, acc->cfg.reg_uri.slen+10); - pj_assert(d > 0); - PJ_UNUSED_ARG(d); - - h = pjsip_authorization_hdr_create(tdata->pool); - h->scheme = pjsip_DIGEST_STR; - h->credential.digest.username = acc->cred[0].username; - h->credential.digest.realm = acc->srv_domain; - h->credential.digest.uri = pj_str(uri); - h->credential.digest.algorithm = pjsip_MD5_STR; + if (pjsua_var.acc[acc_id].regc == NULL) { + status = pjsua_regc_init(acc_id); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to create registration", + status); + goto on_return; + } + } + if (!pjsua_var.acc[acc_id].regc) { + status = PJ_EINVALIDOP; + goto on_return; + } - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)h); - } + status = pjsip_regc_register(pjsua_var.acc[acc_id].regc, + PJSUA_REG_AUTO_REG_REFRESH, + &tdata); + + if (0 && status == PJ_SUCCESS && pjsua_var.acc[acc_id].cred_cnt) { + pjsip_authorization_hdr *h; + char *uri; + int d; + + uri = (char*) pj_pool_alloc(tdata->pool, acc->cfg.reg_uri.slen+10); + d = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, tdata->msg->line.req.uri, + uri, acc->cfg.reg_uri.slen+10); + pj_assert(d > 0); + PJ_UNUSED_ARG(d); + + h = pjsip_authorization_hdr_create(tdata->pool); + h->scheme = pjsip_DIGEST_STR; + h->credential.digest.username = acc->cred[0].username; + h->credential.digest.realm = acc->srv_domain; + h->credential.digest.uri = pj_str(uri); + h->credential.digest.algorithm = pjsip_MD5_STR; + + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)h); + } } else { - if (pjsua_var.acc[acc_id].regc == NULL) { - PJ_LOG(3,(THIS_FILE, "Currently not registered")); - status = PJ_EINVALIDOP; - goto on_return; - } + if (pjsua_var.acc[acc_id].regc == NULL) { + PJ_LOG(3,(THIS_FILE, "Currently not registered")); + status = PJ_EINVALIDOP; + goto on_return; + } - pjsua_pres_unpublish(&pjsua_var.acc[acc_id], 0); + pjsua_pres_unpublish(&pjsua_var.acc[acc_id], 0); - status = pjsip_regc_unregister(pjsua_var.acc[acc_id].regc, &tdata); + status = pjsip_regc_unregister(pjsua_var.acc[acc_id].regc, &tdata); } if (status == PJ_SUCCESS) { @@ -2914,32 +2913,32 @@ PJ_DEF(pj_status_t) pjsua_acc_set_registration( pjsua_acc_id acc_id, &pjsua_var.acc[acc_id].via_addr, pjsua_var.acc[acc_id].via_tp); } else if (!pjsua_sip_acc_is_using_stun(acc_id) && - !pjsua_sip_acc_is_using_upnp(acc_id)) + !pjsua_sip_acc_is_using_upnp(acc_id)) { /* Choose local interface to use in Via if acc is not using * STUN nor UPnP. */ pjsua_acc_get_uac_addr(acc_id, tdata->pool, - &acc->cfg.reg_uri, - &tdata->via_addr, - NULL, NULL, - &tdata->via_tp); + &acc->cfg.reg_uri, + &tdata->via_addr, + NULL, NULL, + &tdata->via_tp); } - /* Increment ref counter and release PJSUA lock here, to avoid - * deadlock while making sure that regc won't be destroyed. - */ - pjsip_regc_add_ref(regc); - PJSUA_UNLOCK(); - - //pjsua_process_msg_data(tdata, NULL); - status = pjsip_regc_send( regc, tdata ); - - PJSUA_LOCK(); - if (pjsip_regc_dec_ref(regc) == PJ_EGONE) { - /* regc has been deleted. */ - goto on_return; - } + /* Increment ref counter and release PJSUA lock here, to avoid + * deadlock while making sure that regc won't be destroyed. + */ + pjsip_regc_add_ref(regc); + PJSUA_UNLOCK(); + + //pjsua_process_msg_data(tdata, NULL); + status = pjsip_regc_send( regc, tdata ); + + PJSUA_LOCK(); + if (pjsip_regc_dec_ref(regc) == PJ_EGONE) { + /* regc has been deleted. */ + goto on_return; + } } /* Update pointer to registration transport */ @@ -2949,30 +2948,30 @@ PJ_DEF(pj_status_t) pjsua_acc_set_registration( pjsua_acc_id acc_id, * employed). A more reliable way is to query the regc directly * when needed. */ - //pjsip_regc_info reg_info; + //pjsip_regc_info reg_info; - //pjsip_regc_get_info(pjsua_var.acc[acc_id].regc, ®_info); - //pjsua_var.acc[acc_id].auto_rereg.reg_tp = reg_info.transport; + //pjsip_regc_get_info(pjsua_var.acc[acc_id].regc, ®_info); + //pjsua_var.acc[acc_id].auto_rereg.reg_tp = reg_info.transport; if (pjsua_var.ua_cfg.cb.on_reg_started) { (*pjsua_var.ua_cfg.cb.on_reg_started)(acc_id, renew); } - if (pjsua_var.ua_cfg.cb.on_reg_started2) { - pjsua_reg_info rinfo; + if (pjsua_var.ua_cfg.cb.on_reg_started2) { + pjsua_reg_info rinfo; - rinfo.cbparam = NULL; - rinfo.regc = pjsua_var.acc[acc_id].regc; - rinfo.renew = renew; + rinfo.cbparam = NULL; + rinfo.regc = pjsua_var.acc[acc_id].regc; + rinfo.renew = renew; (*pjsua_var.ua_cfg.cb.on_reg_started2)(acc_id, &rinfo); } } if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create/send REGISTER", - status); + pjsua_perror(THIS_FILE, "Unable to create/send REGISTER", + status); } else { - PJ_LOG(4,(THIS_FILE, "Acc %d: %s sent", acc_id, - (renew? "Registration" : "Unregistration"))); + PJ_LOG(4,(THIS_FILE, "Acc %d: %s sent", acc_id, + (renew? "Registration" : "Unregistration"))); } on_return: @@ -2986,7 +2985,7 @@ PJ_DEF(pj_status_t) pjsua_acc_set_registration( pjsua_acc_id acc_id, * Get account information. */ PJ_DEF(pj_status_t) pjsua_acc_get_info( pjsua_acc_id acc_id, - pjsua_acc_info *info) + pjsua_acc_info *info) { pjsua_acc *acc = &pjsua_var.acc[acc_id]; pjsua_acc_config *acc_cfg = &pjsua_var.acc[acc_id].cfg; @@ -2997,14 +2996,14 @@ PJ_DEF(pj_status_t) pjsua_acc_get_info( pjsua_acc_id acc_id, pj_bzero(info, sizeof(pjsua_acc_info)); PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc), - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP); PJSUA_LOCK(); if (pjsua_var.acc[acc_id].valid == PJ_FALSE) { - PJSUA_UNLOCK(); - return PJ_EINVALIDOP; + PJSUA_UNLOCK(); + return PJ_EINVALIDOP; } info->id = acc_id; @@ -3014,36 +3013,36 @@ PJ_DEF(pj_status_t) pjsua_acc_get_info( pjsua_acc_id acc_id, info->online_status = acc->online_status; pj_memcpy(&info->rpid, &acc->rpid, sizeof(pjrpid_element)); if (info->rpid.note.slen) - info->online_status_text = info->rpid.note; + info->online_status_text = info->rpid.note; else if (info->online_status) - info->online_status_text = pj_str("Online"); + info->online_status_text = pj_str("Online"); else - info->online_status_text = pj_str("Offline"); + info->online_status_text = pj_str("Offline"); if (acc->reg_last_code) { - if (info->has_registration) { - info->status = (pjsip_status_code) acc->reg_last_code; - info->status_text = *pjsip_get_status_text(acc->reg_last_code); + if (info->has_registration) { + info->status = (pjsip_status_code) acc->reg_last_code; + info->status_text = *pjsip_get_status_text(acc->reg_last_code); if (acc->reg_last_err) - info->reg_last_err = acc->reg_last_err; - } else { - info->status = (pjsip_status_code) 0; - info->status_text = pj_str("not registered"); - } + info->reg_last_err = acc->reg_last_err; + } else { + info->status = (pjsip_status_code) 0; + info->status_text = pj_str("not registered"); + } } else if (acc->cfg.reg_uri.slen) { - info->status = PJSIP_SC_TRYING; - info->status_text = pj_str("In Progress"); + info->status = PJSIP_SC_TRYING; + info->status_text = pj_str("In Progress"); } else { - info->status = (pjsip_status_code) 0; - info->status_text = pj_str("does not register"); + info->status = (pjsip_status_code) 0; + info->status_text = pj_str("does not register"); } if (acc->regc) { - pjsip_regc_info regc_info; - pjsip_regc_get_info(acc->regc, ®c_info); - info->expires = regc_info.next_reg; + pjsip_regc_info regc_info; + pjsip_regc_get_info(acc->regc, ®c_info); + info->expires = regc_info.next_reg; } else { - info->expires = PJSIP_EXPIRES_NOT_SPECIFIED; + info->expires = PJSIP_EXPIRES_NOT_SPECIFIED; } PJSUA_UNLOCK(); @@ -3057,7 +3056,7 @@ PJ_DEF(pj_status_t) pjsua_acc_get_info( pjsua_acc_id acc_id, * Enum accounts all account ids. */ PJ_DEF(pj_status_t) pjsua_enum_accs(pjsua_acc_id ids[], - unsigned *count ) + unsigned *count ) { unsigned i, c; @@ -3066,10 +3065,10 @@ PJ_DEF(pj_status_t) pjsua_enum_accs(pjsua_acc_id ids[], PJSUA_LOCK(); for (i=0, c=0; c<*count && ihost)==0 && - pjsua_var.acc[acc_id].srv_port == sip_uri->port) - { - pj_pool_release(tmp_pool); - PJSUA_UNLOCK(); - return acc_id; - } + unsigned acc_id = pjsua_var.acc_ids[i]; + if (pj_stricmp(&pjsua_var.acc[acc_id].srv_domain, &sip_uri->host)==0 && + pjsua_var.acc[acc_id].srv_port == sip_uri->port) + { + pj_pool_release(tmp_pool); + PJSUA_UNLOCK(); + return acc_id; + } } /* If no match, try to match the domain part only */ for (i=0; ihost)==0) - { - pj_pool_release(tmp_pool); - PJSUA_UNLOCK(); - return acc_id; - } + unsigned acc_id = pjsua_var.acc_ids[i]; + if (pj_stricmp(&pjsua_var.acc[acc_id].srv_domain, &sip_uri->host)==0) + { + pj_pool_release(tmp_pool); + PJSUA_UNLOCK(); + return acc_id; + } } @@ -3203,10 +3202,10 @@ PJ_DEF(pjsua_acc_id) pjsua_acc_find_for_incoming(pjsip_rx_data *rdata) unsigned i; if (pjsua_var.acc_cnt == 0) { - PJ_LOG(2, (THIS_FILE, "No available account to handle %s", - pjsip_rx_data_get_info(rdata))); + PJ_LOG(2, (THIS_FILE, "No available account to handle %s", + pjsip_rx_data_get_info(rdata))); - return PJSUA_INVALID_ID; + return PJSUA_INVALID_ID; } uri = rdata->msg_info.to->uri; @@ -3215,19 +3214,19 @@ PJ_DEF(pjsua_acc_id) pjsua_acc_find_for_incoming(pjsip_rx_data *rdata) /* Use Req URI if To URI is not SIP */ if (!PJSIP_URI_SCHEME_IS_SIP(uri) && - !PJSIP_URI_SCHEME_IS_SIPS(uri)) + !PJSIP_URI_SCHEME_IS_SIPS(uri)) { - if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) - uri = rdata->msg_info.msg->line.req.uri; - else - goto on_return; + if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) + uri = rdata->msg_info.msg->line.req.uri; + else + goto on_return; } /* Just return default account if both To and Req URI are not SIP: */ if (!PJSIP_URI_SCHEME_IS_SIP(uri) && - !PJSIP_URI_SCHEME_IS_SIPS(uri)) + !PJSIP_URI_SCHEME_IS_SIPS(uri)) { - goto on_return; + goto on_return; } sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri); @@ -3239,34 +3238,34 @@ PJ_DEF(pjsua_acc_id) pjsua_acc_find_for_incoming(pjsip_rx_data *rdata) */ max_score = 0; for (i=0; i < pjsua_var.acc_cnt; ++i) { - unsigned acc_id = pjsua_var.acc_ids[i]; - pjsua_acc *acc = &pjsua_var.acc[acc_id]; - int score = 0; + unsigned acc_id = pjsua_var.acc_ids[i]; + pjsua_acc *acc = &pjsua_var.acc[acc_id]; + int score = 0; - if (!acc->valid) - continue; + if (!acc->valid) + continue; - /* Match transport type */ - if (acc->tp_type == rdata->tp_info.transport->key.type || - acc->tp_type == PJSIP_TRANSPORT_UNSPECIFIED) - { - score |= 4; - } + /* Match transport type */ + if (acc->tp_type == rdata->tp_info.transport->key.type || + acc->tp_type == PJSIP_TRANSPORT_UNSPECIFIED) + { + score |= 4; + } - /* Match domain */ - if (pj_stricmp(&acc->srv_domain, &sip_uri->host)==0) { - score |= 2; - } + /* Match domain */ + if (pj_stricmp(&acc->srv_domain, &sip_uri->host)==0) { + score |= 2; + } - /* Match username */ - if (pj_stricmp(&acc->user_part, &sip_uri->user)==0) { - score |= 1; - } + /* Match username */ + if (pj_stricmp(&acc->user_part, &sip_uri->user)==0) { + score |= 1; + } - if (score > max_score) { - id = acc_id; - max_score = score; - } + if (score > max_score) { + id = acc_id; + max_score = score; + } } on_return: @@ -3274,15 +3273,15 @@ PJ_DEF(pjsua_acc_id) pjsua_acc_find_for_incoming(pjsip_rx_data *rdata) /* Still no match, use default account */ if (id == PJSUA_INVALID_ID) - id = pjsua_var.default_acc; + id = pjsua_var.default_acc; /* Invoke account find callback */ if (pjsua_var.ua_cfg.cb.on_acc_find_for_incoming) - (*pjsua_var.ua_cfg.cb.on_acc_find_for_incoming)(rdata, &id); + (*pjsua_var.ua_cfg.cb.on_acc_find_for_incoming)(rdata, &id); /* Verify if the specified account id is valid */ if (!pjsua_acc_is_valid(id)) - id = pjsua_var.default_acc; + id = pjsua_var.default_acc; return id; } @@ -3292,9 +3291,9 @@ PJ_DEF(pjsua_acc_id) pjsua_acc_find_for_incoming(pjsip_rx_data *rdata) * Create arbitrary requests for this account. */ PJ_DEF(pj_status_t) pjsua_acc_create_request(pjsua_acc_id acc_id, - const pjsip_method *method, - const pj_str_t *target, - pjsip_tx_data **p_tdata) + const pjsip_method *method, + const pj_str_t *target, + pjsip_tx_data **p_tdata) { pjsip_tx_data *tdata; pjsua_acc *acc; @@ -3307,29 +3306,29 @@ PJ_DEF(pj_status_t) pjsua_acc_create_request(pjsua_acc_id acc_id, acc = &pjsua_var.acc[acc_id]; status = pjsip_endpt_create_request(pjsua_var.endpt, method, target, - &acc->cfg.id, target, - NULL, NULL, -1, NULL, &tdata); + &acc->cfg.id, target, + NULL, NULL, -1, NULL, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create request", status); - return status; + pjsua_perror(THIS_FILE, "Unable to create request", status); + return status; } /* Copy routeset */ r = acc->route_set.next; while (r != &acc->route_set) { - pjsip_msg_add_hdr(tdata->msg, - (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, r)); - r = r->next; + pjsip_msg_add_hdr(tdata->msg, + (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, r)); + r = r->next; } /* If account is locked to specific transport, then set that transport to * the transmit data. */ if (pjsua_var.acc[acc_id].cfg.transport_id != PJSUA_INVALID_ID) { - pjsip_tpselector tp_sel; + pjsip_tpselector tp_sel; - pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); - pjsip_tx_data_set_transport(tdata, &tp_sel); + pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); + pjsip_tx_data_set_transport(tdata, &tp_sel); } /* If via_addr is set, use this address for the Via header. */ @@ -3339,16 +3338,16 @@ PJ_DEF(pj_status_t) pjsua_acc_create_request(pjsua_acc_id acc_id, tdata->via_addr = pjsua_var.acc[acc_id].via_addr; tdata->via_tp = pjsua_var.acc[acc_id].via_tp; } else if (!pjsua_sip_acc_is_using_stun(acc_id) && - !pjsua_sip_acc_is_using_upnp(acc_id)) + !pjsua_sip_acc_is_using_upnp(acc_id)) { /* Choose local interface to use in Via if acc is not using * STUN nor UPnP. */ pjsua_acc_get_uac_addr(acc_id, tdata->pool, - target, - &tdata->via_addr, - NULL, NULL, - &tdata->via_tp); + target, + &tdata->via_addr, + NULL, NULL, + &tdata->via_tp); } /* Done */ @@ -3368,11 +3367,11 @@ static int get_ip_addr_ver(const pj_str_t *host) /* First check if this is an IPv4 address */ if (pj_inet_pton(pj_AF_INET(), host, &dummy) == PJ_SUCCESS) - return 4; + return 4; /* Then check if this is an IPv6 address */ if (pj_inet_pton(pj_AF_INET6(), host, &dummy6) == PJ_SUCCESS) - return 6; + return 6; /* Not an IP address */ return 0; @@ -3382,12 +3381,12 @@ static int get_ip_addr_ver(const pj_str_t *host) * to send request to the specified destination URI. */ pj_status_t pjsua_acc_get_uac_addr(pjsua_acc_id acc_id, - pj_pool_t *pool, - const pj_str_t *dst_uri, - pjsip_host_port *addr, - pjsip_transport_type_e *p_tp_type, - int *secure, - const void **p_tp) + pj_pool_t *pool, + const pj_str_t *dst_uri, + pjsip_host_port *addr, + pjsip_transport_type_e *p_tp_type, + int *secure, + const void **p_tp) { pjsua_acc *acc; pjsip_sip_uri *sip_uri; @@ -3406,42 +3405,42 @@ pj_status_t pjsua_acc_get_uac_addr(pjsua_acc_id acc_id, * first entry of the route-set. */ if (!pj_list_empty(&acc->route_set)) { - sip_uri = (pjsip_sip_uri*) - pjsip_uri_get_uri(acc->route_set.next->name_addr.uri); + sip_uri = (pjsip_sip_uri*) + pjsip_uri_get_uri(acc->route_set.next->name_addr.uri); } else { - pj_str_t tmp; - pjsip_uri *uri; + pj_str_t tmp; + pjsip_uri *uri; - pj_strdup_with_null(pool, &tmp, dst_uri); + pj_strdup_with_null(pool, &tmp, dst_uri); - uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0); - if (uri == NULL) - return PJSIP_EINVALIDURI; + uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0); + if (uri == NULL) + return PJSIP_EINVALIDURI; - /* For non-SIP scheme, route set should be configured */ - if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri)) - return PJSIP_ENOROUTESET; + /* For non-SIP scheme, route set should be configured */ + if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri)) + return PJSIP_ENOROUTESET; - sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri); + sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri); } /* Get transport type of the URI */ if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) - tp_type = PJSIP_TRANSPORT_TLS; + tp_type = PJSIP_TRANSPORT_TLS; else if (sip_uri->transport_param.slen == 0) { - tp_type = PJSIP_TRANSPORT_UDP; + tp_type = PJSIP_TRANSPORT_UDP; } else - tp_type = pjsip_transport_get_type_from_name(&sip_uri->transport_param); + tp_type = pjsip_transport_get_type_from_name(&sip_uri->transport_param); if (tp_type == PJSIP_TRANSPORT_UNSPECIFIED) - return PJSIP_EUNSUPTRANSPORT; + return PJSIP_EUNSUPTRANSPORT; /* If destination URI specifies IPv6 or account is configured to use IPv6, * then set transport type to use IPv6 as well. */ if (pj_strchr(&sip_uri->host, ':') || pjsua_sip_acc_is_using_ipv6(acc_id)) - tp_type = (pjsip_transport_type_e)(((int)tp_type) | - PJSIP_TRANSPORT_IPV6); + tp_type = (pjsip_transport_type_e)(((int)tp_type) | + PJSIP_TRANSPORT_IPV6); flag = pjsip_transport_get_flag_from_type(tp_type); @@ -3454,13 +3453,13 @@ pj_status_t pjsua_acc_get_uac_addr(pjsua_acc_id acc_id, tfla2_prm.tp_sel = &tp_sel; tfla2_prm.dst_host = sip_uri->host; tfla2_prm.local_if = ((!pjsua_sip_acc_is_using_stun(acc_id) && - !pjsua_sip_acc_is_using_upnp(acc_id)) || - (flag & PJSIP_TRANSPORT_RELIABLE)); + !pjsua_sip_acc_is_using_upnp(acc_id)) || + (flag & PJSIP_TRANSPORT_RELIABLE)); tpmgr = pjsip_endpt_get_tpmgr(pjsua_var.endpt); status = pjsip_tpmgr_find_local_addr2(tpmgr, pool, &tfla2_prm); if (status != PJ_SUCCESS) - return status; + return status; /* Set this as default return value. This may be changed below. */ addr->host = tfla2_prm.ret_addr; @@ -3475,173 +3474,173 @@ pj_status_t pjsua_acc_get_uac_addr(pjsua_acc_id acc_id, tfla2_prm2.tp_type = PJSIP_TRANSPORT_UDP6; tfla2_prm2.tp_sel = NULL; tfla2_prm2.local_if = (!pjsua_sip_acc_is_using_stun(acc_id) && - !pjsua_sip_acc_is_using_upnp(acc_id)); + !pjsua_sip_acc_is_using_upnp(acc_id)); status = pjsip_tpmgr_find_local_addr2(tpmgr, pool, &tfla2_prm2); - if (status == PJ_SUCCESS) { - update_addr = PJ_FALSE; - addr->host = tfla2_prm2.ret_addr; - pj_strdup(acc->pool, &acc->via_addr.host, &addr->host); - acc->via_addr.port = addr->port; - acc->via_tp = (pjsip_transport *)tfla2_prm.ret_tp; - } + if (status == PJ_SUCCESS) { + update_addr = PJ_FALSE; + addr->host = tfla2_prm2.ret_addr; + pj_strdup(acc->pool, &acc->via_addr.host, &addr->host); + acc->via_addr.port = addr->port; + acc->via_tp = (pjsip_transport *)tfla2_prm.ret_tp; + } } else /* For UDP transport, check if we need to overwrite the address * with its bound address. */ if ((flag & PJSIP_TRANSPORT_DATAGRAM) && tfla2_prm.local_if && - tfla2_prm.ret_tp) + tfla2_prm.ret_tp) { - int i; - - for (i = 0; i < sizeof(pjsua_var.tpdata); i++) { - if (tfla2_prm.ret_tp==(const void *)pjsua_var.tpdata[i].data.tp) { - if (pjsua_var.tpdata[i].has_bound_addr) { - pj_strdup(pool, &addr->host, - &pjsua_var.tpdata[i].data.tp->local_name.host); - addr->port = (pj_uint16_t) - pjsua_var.tpdata[i].data.tp->local_name.port; - } - break; - } - } + int i; + + for (i = 0; i < sizeof(pjsua_var.tpdata); i++) { + if (tfla2_prm.ret_tp==(const void *)pjsua_var.tpdata[i].data.tp) { + if (pjsua_var.tpdata[i].has_bound_addr) { + pj_strdup(pool, &addr->host, + &pjsua_var.tpdata[i].data.tp->local_name.host); + addr->port = (pj_uint16_t) + pjsua_var.tpdata[i].data.tp->local_name.port; + } + break; + } + } } /* For TCP/TLS, acc may request to specify source port */ if (acc->cfg.contact_use_src_port) { - pjsip_host_info dinfo; - pjsip_transport *tp = NULL; - pj_addrinfo ai; - pj_bool_t log_written = PJ_FALSE; - - status = pjsip_get_dest_info((pjsip_uri*)sip_uri, NULL, - pool, &dinfo); - - if (status==PJ_SUCCESS && (dinfo.flag & PJSIP_TRANSPORT_RELIABLE)==0) { - /* Not TCP or TLS. No need to do this */ - status = PJ_EINVALIDOP; - log_written = PJ_TRUE; - } - - if (status==PJ_SUCCESS && - get_ip_addr_ver(&dinfo.addr.host)==0 && - pjsua_var.ua_cfg.nameserver_count) - { - /* If nameserver is configured, PJSIP will resolve destinations - * by their DNS SRV record first. On the other hand, we will - * resolve destination with DNS A record via pj_getaddrinfo(). - * They may yield different IP addresses, hence causing different - * TCP/TLS connection to be created and hence different source - * address. - */ - PJ_LOG(4,(THIS_FILE, "Warning: cannot use source TCP/TLS socket" - " address for Contact when nameserver is configured.")); - status = PJ_ENOTSUP; - log_written = PJ_TRUE; - } - - if (status == PJ_SUCCESS) { - unsigned cnt=1; - int af = pj_AF_UNSPEC(); - - if (pjsua_sip_acc_is_using_ipv6(acc_id) || - (dinfo.type & PJSIP_TRANSPORT_IPV6)) - { - af = pj_AF_INET6(); - } - status = pj_getaddrinfo(af, &dinfo.addr.host, &cnt, &ai); - if (cnt == 0) { - status = PJ_ENOTSUP; - } else if ((dinfo.type & PJSIP_TRANSPORT_IPV6)==0 && - ai.ai_addr.addr.sa_family == pj_AF_INET6()) - { - /* Destination is a hostname and account is not bound to IPv6, - * but hostname resolution reveals that it has IPv6 address, - * so let's use IPv6 transport type. - */ - dinfo.type |= PJSIP_TRANSPORT_IPV6; - tp_type |= PJSIP_TRANSPORT_IPV6; - } - } - - if (status == PJ_SUCCESS) { - pjsip_tx_data tdata; - int addr_len = pj_sockaddr_get_len(&ai.ai_addr); - pj_uint16_t port = (pj_uint16_t)dinfo.addr.port; - - /* Create a dummy tdata to inform remote host name to transport */ - pj_bzero(&tdata, sizeof(tdata)); - pj_strdup(pool, &tdata.dest_info.name, &dinfo.addr.host); - - if (port==0) { - port = (dinfo.flag & PJSIP_TRANSPORT_SECURE) ? 5061 : 5060; - } - pj_sockaddr_set_port(&ai.ai_addr, port); - status = pjsip_endpt_acquire_transport2(pjsua_var.endpt, - dinfo.type, - &ai.ai_addr, - addr_len, - &tp_sel, - &tdata, &tp); - } - - if (status == PJ_SUCCESS && (tp->local_name.port == 0 || - tp->local_name.host.slen==0 || - *tp->local_name.host.ptr=='0')) - { - /* Trap zero port or "0.0.0.0" address. */ - /* The TCP/TLS transport is still connecting and unfortunately - * this OS doesn't report the bound local address in this state. - */ - PJ_LOG(4,(THIS_FILE, "Unable to get transport local port " - "for Contact address (OS doesn't support)")); - status = PJ_ENOTSUP; - log_written = PJ_TRUE; - } - - if (status == PJ_SUCCESS) { - /* Got the local transport address, don't update if - * we are on NAT64 and already obtained the address - * from STUN above. - */ - if (update_addr) - pj_strdup(pool, &addr->host, &tp->local_name.host); - addr->port = tp->local_name.port; - } - - if (tp) { - /* Here the transport's ref counter WILL reach zero. But the - * transport will NOT get destroyed because it should have an - * idle timer. - */ - pjsip_transport_dec_ref(tp); - tp = NULL; - } - - if (status != PJ_SUCCESS && !log_written) { - PJ_PERROR(4,(THIS_FILE, status, "Unable to use source local " - "TCP socket address for Contact")); - } - status = PJ_SUCCESS; + pjsip_host_info dinfo; + pjsip_transport *tp = NULL; + pj_addrinfo ai; + pj_bool_t log_written = PJ_FALSE; + + status = pjsip_get_dest_info((pjsip_uri*)sip_uri, NULL, + pool, &dinfo); + + if (status==PJ_SUCCESS && (dinfo.flag & PJSIP_TRANSPORT_RELIABLE)==0) { + /* Not TCP or TLS. No need to do this */ + status = PJ_EINVALIDOP; + log_written = PJ_TRUE; + } + + if (status==PJ_SUCCESS && + get_ip_addr_ver(&dinfo.addr.host)==0 && + pjsua_var.ua_cfg.nameserver_count) + { + /* If nameserver is configured, PJSIP will resolve destinations + * by their DNS SRV record first. On the other hand, we will + * resolve destination with DNS A record via pj_getaddrinfo(). + * They may yield different IP addresses, hence causing different + * TCP/TLS connection to be created and hence different source + * address. + */ + PJ_LOG(4,(THIS_FILE, "Warning: cannot use source TCP/TLS socket" + " address for Contact when nameserver is configured.")); + status = PJ_ENOTSUP; + log_written = PJ_TRUE; + } + + if (status == PJ_SUCCESS) { + unsigned cnt=1; + int af = pj_AF_UNSPEC(); + + if (pjsua_sip_acc_is_using_ipv6(acc_id) || + (dinfo.type & PJSIP_TRANSPORT_IPV6)) + { + af = pj_AF_INET6(); + } + status = pj_getaddrinfo(af, &dinfo.addr.host, &cnt, &ai); + if (cnt == 0) { + status = PJ_ENOTSUP; + } else if ((dinfo.type & PJSIP_TRANSPORT_IPV6)==0 && + ai.ai_addr.addr.sa_family == pj_AF_INET6()) + { + /* Destination is a hostname and account is not bound to IPv6, + * but hostname resolution reveals that it has IPv6 address, + * so let's use IPv6 transport type. + */ + dinfo.type |= PJSIP_TRANSPORT_IPV6; + tp_type |= PJSIP_TRANSPORT_IPV6; + } + } + + if (status == PJ_SUCCESS) { + pjsip_tx_data tdata; + int addr_len = pj_sockaddr_get_len(&ai.ai_addr); + pj_uint16_t port = (pj_uint16_t)dinfo.addr.port; + + /* Create a dummy tdata to inform remote host name to transport */ + pj_bzero(&tdata, sizeof(tdata)); + pj_strdup(pool, &tdata.dest_info.name, &dinfo.addr.host); + + if (port==0) { + port = (dinfo.flag & PJSIP_TRANSPORT_SECURE) ? 5061 : 5060; + } + pj_sockaddr_set_port(&ai.ai_addr, port); + status = pjsip_endpt_acquire_transport2(pjsua_var.endpt, + dinfo.type, + &ai.ai_addr, + addr_len, + &tp_sel, + &tdata, &tp); + } + + if (status == PJ_SUCCESS && (tp->local_name.port == 0 || + tp->local_name.host.slen==0 || + *tp->local_name.host.ptr=='0')) + { + /* Trap zero port or "0.0.0.0" address. */ + /* The TCP/TLS transport is still connecting and unfortunately + * this OS doesn't report the bound local address in this state. + */ + PJ_LOG(4,(THIS_FILE, "Unable to get transport local port " + "for Contact address (OS doesn't support)")); + status = PJ_ENOTSUP; + log_written = PJ_TRUE; + } + + if (status == PJ_SUCCESS) { + /* Got the local transport address, don't update if + * we are on NAT64 and already obtained the address + * from STUN above. + */ + if (update_addr) + pj_strdup(pool, &addr->host, &tp->local_name.host); + addr->port = tp->local_name.port; + } + + if (tp) { + /* Here the transport's ref counter WILL reach zero. But the + * transport will NOT get destroyed because it should have an + * idle timer. + */ + pjsip_transport_dec_ref(tp); + tp = NULL; + } + + if (status != PJ_SUCCESS && !log_written) { + PJ_PERROR(4,(THIS_FILE, status, "Unable to use source local " + "TCP socket address for Contact")); + } + status = PJ_SUCCESS; } if (p_tp_type) - *p_tp_type = tp_type; + *p_tp_type = tp_type; if (secure) { - *secure = (flag & PJSIP_TRANSPORT_SECURE) != 0; + *secure = (flag & PJSIP_TRANSPORT_SECURE) != 0; } if (p_tp) - *p_tp = tfla2_prm.ret_tp; + *p_tp = tfla2_prm.ret_tp; return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjsua_acc_create_uac_contact( pj_pool_t *pool, - pj_str_t *contact, - pjsua_acc_id acc_id, - const pj_str_t *suri) + pj_str_t *contact, + pjsua_acc_id acc_id, + const pj_str_t *suri) { pjsua_acc *acc; pj_status_t status; @@ -3658,67 +3657,67 @@ PJ_DEF(pj_status_t) pjsua_acc_create_uac_contact( pj_pool_t *pool, /* If force_contact is configured, then use use it */ if (acc->cfg.force_contact.slen) { - *contact = acc->cfg.force_contact; - return PJ_SUCCESS; + *contact = acc->cfg.force_contact; + return PJ_SUCCESS; } status = pjsua_acc_get_uac_addr(acc_id, pool, suri, &addr, &tp_type, &secure, NULL); if (status != PJ_SUCCESS) - return status; + return status; /* Enclose IPv6 address in square brackets */ if (tp_type & PJSIP_TRANSPORT_IPV6) { - beginquote = "["; - endquote = "]"; + beginquote = "["; + endquote = "]"; } else { - beginquote = endquote = ""; + beginquote = endquote = ""; } /* Don't add transport parameter if it's UDP */ if (tp_type!=PJSIP_TRANSPORT_UDP && tp_type!=PJSIP_TRANSPORT_UDP6) { - pj_ansi_snprintf(transport_param, sizeof(transport_param), - ";transport=%s", - pjsip_transport_get_type_name(tp_type)); + pj_ansi_snprintf(transport_param, sizeof(transport_param), + ";transport=%s", + pjsip_transport_get_type_name(tp_type)); } else { - transport_param[0] = '\0'; + transport_param[0] = '\0'; } /* Create the contact header */ contact->ptr = (char*)pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE); contact->slen = pj_ansi_snprintf(contact->ptr, PJSIP_MAX_URL_SIZE, - "%s%.*s%s<%s:%.*s%s%s%.*s%s:%d%s%.*s%s>%.*s", - (acc->display.slen?"\"" : ""), - (int)acc->display.slen, - acc->display.ptr, - (acc->display.slen?"\" " : ""), - ((secure && acc->is_sips)? "sips" : "sip"), - (int)acc->user_part.slen, - acc->user_part.ptr, - (acc->user_part.slen?"@":""), - beginquote, - (int)addr.host.slen, - addr.host.ptr, - endquote, - addr.port, - transport_param, - (int)acc->cfg.contact_uri_params.slen, - acc->cfg.contact_uri_params.ptr, - (acc->cfg.use_rfc5626? ob: ""), - (int)acc->cfg.contact_params.slen, - acc->cfg.contact_params.ptr); + "%s%.*s%s<%s:%.*s%s%s%.*s%s:%d%s%.*s%s>%.*s", + (acc->display.slen?"\"" : ""), + (int)acc->display.slen, + acc->display.ptr, + (acc->display.slen?"\" " : ""), + ((secure && acc->is_sips)? "sips" : "sip"), + (int)acc->user_part.slen, + acc->user_part.ptr, + (acc->user_part.slen?"@":""), + beginquote, + (int)addr.host.slen, + addr.host.ptr, + endquote, + addr.port, + transport_param, + (int)acc->cfg.contact_uri_params.slen, + acc->cfg.contact_uri_params.ptr, + (acc->cfg.use_rfc5626? ob: ""), + (int)acc->cfg.contact_params.slen, + acc->cfg.contact_params.ptr); if (contact->slen < 1 || contact->slen >= (int)PJSIP_MAX_URL_SIZE) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjsua_acc_create_uas_contact( pj_pool_t *pool, - pj_str_t *contact, - pjsua_acc_id acc_id, - pjsip_rx_data *rdata ) + pj_str_t *contact, + pjsua_acc_id acc_id, + pjsip_rx_data *rdata ) { /* * Section 12.1.1, paragraph about using SIPS URI in Contact. @@ -3747,79 +3746,79 @@ PJ_DEF(pj_status_t) pjsua_acc_create_uas_contact( pj_pool_t *pool, /* If force_contact is configured, then use use it */ if (acc->cfg.force_contact.slen) { - *contact = acc->cfg.force_contact; - return PJ_SUCCESS; + *contact = acc->cfg.force_contact; + return PJ_SUCCESS; } /* If Record-Route is present, then URI is the top Record-Route. */ if (rdata->msg_info.record_route) { - sip_uri = (pjsip_sip_uri*) - pjsip_uri_get_uri(rdata->msg_info.record_route->name_addr.uri); + sip_uri = (pjsip_sip_uri*) + pjsip_uri_get_uri(rdata->msg_info.record_route->name_addr.uri); } else { - pjsip_hdr *pos = NULL; - pjsip_contact_hdr *h_contact; - pjsip_uri *uri = NULL; - - /* Otherwise URI is Contact URI. - * Iterate the Contact URI until we find sip: or sips: scheme. - */ - do { - h_contact = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, - pos); - if (h_contact) { - if (h_contact->uri) - uri = (pjsip_uri*) pjsip_uri_get_uri(h_contact->uri); - else - uri = NULL; - if (!uri || (!PJSIP_URI_SCHEME_IS_SIP(uri) && - !PJSIP_URI_SCHEME_IS_SIPS(uri))) - { - pos = (pjsip_hdr*)h_contact->next; - if (pos == &rdata->msg_info.msg->hdr) - h_contact = NULL; - } else { - break; - } - } - } while (h_contact); - - - /* Or if Contact URI is not present, take the remote URI from - * the From URI. - */ - if (uri == NULL) - uri = (pjsip_uri*) pjsip_uri_get_uri(rdata->msg_info.from->uri); - - - /* Can only do sip/sips scheme at present. */ - if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri)) - return PJSIP_EINVALIDREQURI; - - sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri); + pjsip_hdr *pos = NULL; + pjsip_contact_hdr *h_contact; + pjsip_uri *uri = NULL; + + /* Otherwise URI is Contact URI. + * Iterate the Contact URI until we find sip: or sips: scheme. + */ + do { + h_contact = (pjsip_contact_hdr*) + pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, + pos); + if (h_contact) { + if (h_contact->uri) + uri = (pjsip_uri*) pjsip_uri_get_uri(h_contact->uri); + else + uri = NULL; + if (!uri || (!PJSIP_URI_SCHEME_IS_SIP(uri) && + !PJSIP_URI_SCHEME_IS_SIPS(uri))) + { + pos = (pjsip_hdr*)h_contact->next; + if (pos == &rdata->msg_info.msg->hdr) + h_contact = NULL; + } else { + break; + } + } + } while (h_contact); + + + /* Or if Contact URI is not present, take the remote URI from + * the From URI. + */ + if (uri == NULL) + uri = (pjsip_uri*) pjsip_uri_get_uri(rdata->msg_info.from->uri); + + + /* Can only do sip/sips scheme at present. */ + if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri)) + return PJSIP_EINVALIDREQURI; + + sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri); } /* Get transport type of the URI */ if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) - tp_type = PJSIP_TRANSPORT_TLS; + tp_type = PJSIP_TRANSPORT_TLS; else if (sip_uri->transport_param.slen == 0) { - tp_type = PJSIP_TRANSPORT_UDP; + tp_type = PJSIP_TRANSPORT_UDP; } else - tp_type = pjsip_transport_get_type_from_name(&sip_uri->transport_param); + tp_type = pjsip_transport_get_type_from_name(&sip_uri->transport_param); if (tp_type == PJSIP_TRANSPORT_UNSPECIFIED) - return PJSIP_EUNSUPTRANSPORT; + return PJSIP_EUNSUPTRANSPORT; /* If destination URI specifies IPv6 or account is configured to use IPv6 * or the transport being used to receive data is an IPv6 transport, * then set transport type to use IPv6 as well. */ if (pj_strchr(&sip_uri->host, ':') || - pjsua_sip_acc_is_using_ipv6(acc_id) || - (rdata->tp_info.transport->key.type & PJSIP_TRANSPORT_IPV6)) + pjsua_sip_acc_is_using_ipv6(acc_id) || + (rdata->tp_info.transport->key.type & PJSIP_TRANSPORT_IPV6)) { - tp_type = (pjsip_transport_type_e) - (((int)tp_type) | PJSIP_TRANSPORT_IPV6); + tp_type = (pjsip_transport_type_e) + (((int)tp_type) | PJSIP_TRANSPORT_IPV6); } flag = pjsip_transport_get_flag_from_type(tp_type); @@ -3834,13 +3833,13 @@ PJ_DEF(pj_status_t) pjsua_acc_create_uas_contact( pj_pool_t *pool, tfla2_prm.tp_sel = &tp_sel; tfla2_prm.dst_host = sip_uri->host; tfla2_prm.local_if = ((!pjsua_sip_acc_is_using_stun(acc_id) && - !pjsua_sip_acc_is_using_upnp(acc_id)) || - (flag & PJSIP_TRANSPORT_RELIABLE)); + !pjsua_sip_acc_is_using_upnp(acc_id)) || + (flag & PJSIP_TRANSPORT_RELIABLE)); tpmgr = pjsip_endpt_get_tpmgr(pjsua_var.endpt); status = pjsip_tpmgr_find_local_addr2(tpmgr, pool, &tfla2_prm); if (status != PJ_SUCCESS) - return status; + return status; local_addr = tfla2_prm.ret_addr; local_port = tfla2_prm.ret_port; @@ -3848,53 +3847,53 @@ PJ_DEF(pj_status_t) pjsua_acc_create_uas_contact( pj_pool_t *pool, /* Enclose IPv6 address in square brackets */ if (tp_type & PJSIP_TRANSPORT_IPV6) { - beginquote = "["; - endquote = "]"; + beginquote = "["; + endquote = "]"; } else { - beginquote = endquote = ""; + beginquote = endquote = ""; } /* Don't add transport parameter if it's UDP */ if (tp_type!=PJSIP_TRANSPORT_UDP && tp_type!=PJSIP_TRANSPORT_UDP6) { - pj_ansi_snprintf(transport_param, sizeof(transport_param), - ";transport=%s", - pjsip_transport_get_type_name(tp_type)); + pj_ansi_snprintf(transport_param, sizeof(transport_param), + ";transport=%s", + pjsip_transport_get_type_name(tp_type)); } else { - transport_param[0] = '\0'; + transport_param[0] = '\0'; } /* Create the contact header */ contact->ptr = (char*) pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE); contact->slen = pj_ansi_snprintf(contact->ptr, PJSIP_MAX_URL_SIZE, - "%s%.*s%s<%s:%.*s%s%s%.*s%s:%d%s%.*s>%.*s", - (acc->display.slen?"\"" : ""), - (int)acc->display.slen, - acc->display.ptr, - (acc->display.slen?"\" " : ""), - ((secure && acc->is_sips)? "sips" : "sip"), - (int)acc->user_part.slen, - acc->user_part.ptr, - (acc->user_part.slen?"@":""), - beginquote, - (int)local_addr.slen, - local_addr.ptr, - endquote, - local_port, - transport_param, - (int)acc->cfg.contact_uri_params.slen, - acc->cfg.contact_uri_params.ptr, - (int)acc->cfg.contact_params.slen, - acc->cfg.contact_params.ptr); + "%s%.*s%s<%s:%.*s%s%s%.*s%s:%d%s%.*s>%.*s", + (acc->display.slen?"\"" : ""), + (int)acc->display.slen, + acc->display.ptr, + (acc->display.slen?"\" " : ""), + ((secure && acc->is_sips)? "sips" : "sip"), + (int)acc->user_part.slen, + acc->user_part.ptr, + (acc->user_part.slen?"@":""), + beginquote, + (int)local_addr.slen, + local_addr.ptr, + endquote, + local_port, + transport_param, + (int)acc->cfg.contact_uri_params.slen, + acc->cfg.contact_uri_params.ptr, + (int)acc->cfg.contact_params.slen, + acc->cfg.contact_params.ptr); if (contact->slen < 1 || contact->slen >= (int)PJSIP_MAX_URL_SIZE) - return PJ_ETOOSMALL; + return PJ_ETOOSMALL; return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjsua_acc_set_transport( pjsua_acc_id acc_id, - pjsua_transport_id tp_id) + pjsua_transport_id tp_id) { pjsua_acc *acc; @@ -3904,21 +3903,21 @@ PJ_DEF(pj_status_t) pjsua_acc_set_transport( pjsua_acc_id acc_id, PJ_ASSERT_RETURN(tp_id < (int)PJ_ARRAY_SIZE(pjsua_var.tpdata), PJ_EINVAL); if (acc->cfg.transport_id == tp_id) - return PJ_SUCCESS; + return PJ_SUCCESS; acc->cfg.transport_id = tp_id; if (acc->cfg.transport_id != PJSUA_INVALID_ID) { - acc->tp_type = pjsua_var.tpdata[acc->cfg.transport_id].type; - if (acc->regc) { - /* Update client registration's transport. */ - pjsip_tpselector tp_sel; - - pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); - pjsip_regc_set_transport(acc->regc, &tp_sel); - } + acc->tp_type = pjsua_var.tpdata[acc->cfg.transport_id].type; + if (acc->regc) { + /* Update client registration's transport. */ + pjsip_tpselector tp_sel; + + pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); + pjsip_regc_set_transport(acc->regc, &tp_sel); + } } else { - acc->tp_type = PJSIP_TRANSPORT_UNSPECIFIED; + acc->tp_type = PJSIP_TRANSPORT_UNSPECIFIED; } return PJ_SUCCESS; @@ -3942,9 +3941,9 @@ static void auto_rereg_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te) * the auto-reregistration. */ if (!acc->valid || !acc->auto_rereg.active || - acc->cfg.reg_retry_interval == 0) + acc->cfg.reg_retry_interval == 0) { - goto on_return; + goto on_return; } /* Start re-registration */ @@ -3956,39 +3955,39 @@ static void auto_rereg_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te) * contact the UA). */ if (acc->rfc5626_status != OUTBOUND_ACTIVE && !acc->contact_rewritten) { - pj_str_t tmp_contact; - pj_pool_t *pool; - - pool = pjsua_pool_create("tmpregc", 512, 512); - - status = pjsua_acc_create_uac_contact(pool, &tmp_contact, acc->index, - &acc->cfg.reg_uri); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Unable to generate suitable Contact header" - " for re-registration", status); - pj_pool_release(pool); - schedule_reregistration(acc); - goto on_return; - } - - if (pj_strcmp(&tmp_contact, &acc->contact)) { - if (acc->contact.slen < tmp_contact.slen) { - pj_strdup_with_null(acc->pool, &acc->contact, &tmp_contact); - } else { - pj_strncpy_with_null(&acc->contact, &tmp_contact, - PJSIP_MAX_URL_SIZE); - } - update_regc_contact(acc); - if (acc->regc) - pjsip_regc_update_contact(acc->regc, 1, &acc->reg_contact); - } - pj_pool_release(pool); + pj_str_t tmp_contact; + pj_pool_t *pool; + + pool = pjsua_pool_create("tmpregc", 512, 512); + + status = pjsua_acc_create_uac_contact(pool, &tmp_contact, acc->index, + &acc->cfg.reg_uri); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, + "Unable to generate suitable Contact header" + " for re-registration", status); + pj_pool_release(pool); + schedule_reregistration(acc); + goto on_return; + } + + if (pj_strcmp(&tmp_contact, &acc->contact)) { + if (acc->contact.slen < tmp_contact.slen) { + pj_strdup_with_null(acc->pool, &acc->contact, &tmp_contact); + } else { + pj_strncpy_with_null(&acc->contact, &tmp_contact, + PJSIP_MAX_URL_SIZE); + } + update_regc_contact(acc); + if (acc->regc) + pjsip_regc_update_contact(acc->regc, 1, &acc->reg_contact); + } + pj_pool_release(pool); } status = pjsua_acc_set_registration(acc->index, PJ_TRUE); if (status != PJ_SUCCESS) - schedule_reregistration(acc); + schedule_reregistration(acc); on_return: PJSUA_UNLOCK(); @@ -4007,7 +4006,7 @@ static void schedule_reregistration(pjsua_acc *acc) /* Validate the account and re-registration feature status */ if (!acc->valid || acc->cfg.reg_retry_interval == 0) { - return; + return; } /* If configured, disconnect calls of this account after the first @@ -4015,26 +4014,26 @@ static void schedule_reregistration(pjsua_acc *acc) */ if (acc->cfg.drop_calls_on_reg_fail && acc->auto_rereg.attempt_cnt >= 1) { - unsigned i, cnt; + unsigned i, cnt; - for (i = 0, cnt = 0; i < pjsua_var.ua_cfg.max_calls; ++i) { - if (pjsua_var.calls[i].acc_id == acc->index) { - pjsua_call_hangup(i, 0, NULL, NULL); - ++cnt; - } - } + for (i = 0, cnt = 0; i < pjsua_var.ua_cfg.max_calls; ++i) { + if (pjsua_var.calls[i].acc_id == acc->index) { + pjsua_call_hangup(i, 0, NULL, NULL); + ++cnt; + } + } - if (cnt) { - PJ_LOG(3, (THIS_FILE, "Disconnecting %d call(s) of account #%d " - "after reregistration attempt failed", - cnt, acc->index)); - } + if (cnt) { + PJ_LOG(3, (THIS_FILE, "Disconnecting %d call(s) of account #%d " + "after reregistration attempt failed", + cnt, acc->index)); + } } /* Cancel any re-registration timer */ if (acc->auto_rereg.timer.id) { - acc->auto_rereg.timer.id = PJ_FALSE; - pjsua_cancel_timer(&acc->auto_rereg.timer); + acc->auto_rereg.timer.id = PJ_FALSE; + pjsua_cancel_timer(&acc->auto_rereg.timer); } /* Update re-registration flag */ @@ -4046,28 +4045,28 @@ static void schedule_reregistration(pjsua_acc *acc) /* Reregistration attempt. The first attempt will be done immediately. */ delay.sec = acc->auto_rereg.attempt_cnt? acc->cfg.reg_retry_interval : - acc->cfg.reg_first_retry_interval; + acc->cfg.reg_first_retry_interval; delay.msec = 0; /* Randomize interval by +/- reg_retry_random_interval, if configured */ if (acc->cfg.reg_retry_random_interval) { - long rand_ms = acc->cfg.reg_retry_random_interval * 1000; - if (delay.sec >= (long)acc->cfg.reg_retry_random_interval) { - delay.msec = -rand_ms + (pj_rand() % (rand_ms * 2)); - } else { - delay.sec = 0; - delay.msec = (pj_rand() % (delay.sec * 1000 + rand_ms)); - } + long rand_ms = acc->cfg.reg_retry_random_interval * 1000; + if (delay.sec >= (long)acc->cfg.reg_retry_random_interval) { + delay.msec = -rand_ms + (pj_rand() % (rand_ms * 2)); + } else { + delay.sec = 0; + delay.msec = (pj_rand() % (delay.sec * 1000 + rand_ms)); + } } pj_time_val_normalize(&delay); PJ_LOG(4,(THIS_FILE, - "Scheduling re-registration retry for acc %d in %u seconds..", - acc->index, delay.sec)); + "Scheduling re-registration retry for acc %d in %u seconds..", + acc->index, delay.sec)); acc->auto_rereg.timer.id = PJ_TRUE; if (pjsua_schedule_timer(&acc->auto_rereg.timer, &delay) != PJ_SUCCESS) - acc->auto_rereg.timer.id = PJ_FALSE; + acc->auto_rereg.timer.id = PJ_FALSE; } @@ -4075,8 +4074,8 @@ static void schedule_reregistration(pjsua_acc *acc) * connection/disconnection events. */ void pjsua_acc_on_tp_state_changed(pjsip_transport *tp, - pjsip_transport_state state, - const pjsip_transport_state_info *info) + pjsip_transport_state state, + const pjsip_transport_state_info *info) { unsigned i; @@ -4084,10 +4083,10 @@ void pjsua_acc_on_tp_state_changed(pjsip_transport *tp, /* Only care for transport disconnection events */ if (state != PJSIP_TP_STATE_DISCONNECTED) - return; + return; PJ_LOG(4,(THIS_FILE, "Disconnected notification for transport %s", - tp->obj_name)); + tp->obj_name)); pj_log_push_indent(); /* Shutdown this transport, to make sure that the transport manager @@ -4101,60 +4100,60 @@ void pjsua_acc_on_tp_state_changed(pjsip_transport *tp, * based on the transport state. */ for (i = 0; i < PJ_ARRAY_SIZE(pjsua_var.acc); ++i) { - pjsua_acc *acc = &pjsua_var.acc[i]; - - /* Skip if this account is not valid. */ - if (!acc->valid) - continue; - - /* Reset Account's via transport and via address */ - if (acc->via_tp == (void*)tp) { - pj_bzero(&acc->via_addr, sizeof(acc->via_addr)); - acc->via_tp = NULL; - - /* Also reset regc's Via addr */ - if (acc->regc) - pjsip_regc_set_via_sent_by(acc->regc, NULL, NULL); - } - - /* Release transport immediately if regc is using it - * See https://github.com/pjsip/pjproject/issues/1481 - */ - if (acc->regc) { - pjsip_regc_info reg_info; - - pjsip_regc_get_info(acc->regc, ®_info); - if (reg_info.transport != tp) - continue; - - pjsip_regc_release_transport(pjsua_var.acc[i].regc); - - if (pjsua_var.acc[i].ip_change_op == - PJSUA_IP_CHANGE_OP_ACC_SHUTDOWN_TP) - { - /* Before progressing to next step, report here. */ - if (pjsua_var.ua_cfg.cb.on_ip_change_progress) { - pjsua_ip_change_op_info ch_info; - - pj_bzero(&ch_info, sizeof(ch_info)); - ch_info.acc_shutdown_tp.acc_id = acc->index; - - pjsua_var.ua_cfg.cb.on_ip_change_progress( - acc->ip_change_op, - PJ_SUCCESS, - &ch_info); - } - - if (acc->cfg.allow_contact_rewrite) { - pjsua_acc_update_contact_on_ip_change(acc); - } else { - pjsua_acc_handle_call_on_ip_change(acc); - } - } else if (acc->cfg.reg_retry_interval) { - /* Schedule reregistration for this account */ - schedule_reregistration(acc); - } - } + pjsua_acc *acc = &pjsua_var.acc[i]; + + /* Skip if this account is not valid. */ + if (!acc->valid) + continue; + + /* Reset Account's via transport and via address */ + if (acc->via_tp == (void*)tp) { + pj_bzero(&acc->via_addr, sizeof(acc->via_addr)); + acc->via_tp = NULL; + + /* Also reset regc's Via addr */ + if (acc->regc) + pjsip_regc_set_via_sent_by(acc->regc, NULL, NULL); + } + + /* Release transport immediately if regc is using it + * See https://github.com/pjsip/pjproject/issues/1481 + */ + if (acc->regc) { + pjsip_regc_info reg_info; + + pjsip_regc_get_info(acc->regc, ®_info); + if (reg_info.transport != tp) + continue; + + pjsip_regc_release_transport(pjsua_var.acc[i].regc); + + if (pjsua_var.acc[i].ip_change_op == + PJSUA_IP_CHANGE_OP_ACC_SHUTDOWN_TP) + { + /* Before progressing to next step, report here. */ + if (pjsua_var.ua_cfg.cb.on_ip_change_progress) { + pjsua_ip_change_op_info ch_info; + + pj_bzero(&ch_info, sizeof(ch_info)); + ch_info.acc_shutdown_tp.acc_id = acc->index; + + pjsua_var.ua_cfg.cb.on_ip_change_progress( + acc->ip_change_op, + PJ_SUCCESS, + &ch_info); + } + + if (acc->cfg.allow_contact_rewrite) { + pjsua_acc_update_contact_on_ip_change(acc); + } else { + pjsua_acc_handle_call_on_ip_change(acc); + } + } else if (acc->cfg.reg_retry_interval) { + /* Schedule reregistration for this account */ + schedule_reregistration(acc); + } + } } PJSUA_UNLOCK(); @@ -4169,33 +4168,33 @@ pj_status_t pjsua_acc_update_contact_on_ip_change(pjsua_acc *acc) { pj_status_t status; pj_bool_t need_unreg = ((acc->cfg.contact_rewrite_method & - PJSUA_CONTACT_REWRITE_UNREGISTER) != 0); + PJSUA_CONTACT_REWRITE_UNREGISTER) != 0); acc->ip_change_op = PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT; PJ_LOG(3, (THIS_FILE, "%.*s: send %sregistration triggered " - "by IP change", acc->cfg.id.slen, - acc->cfg.id.ptr, (need_unreg ? "un-" : ""))); + "by IP change", acc->cfg.id.slen, + acc->cfg.id.ptr, (need_unreg ? "un-" : ""))); status = pjsua_acc_set_registration(acc->index, !need_unreg); if ((status != PJ_SUCCESS) && (pjsua_var.ua_cfg.cb.on_ip_change_progress) - && (acc->ip_change_op == PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT)) + && (acc->ip_change_op == PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT)) { - /* If update contact fails, notification might already been triggered - * from registration callback. - */ - pjsua_ip_change_op_info info; + /* If update contact fails, notification might already been triggered + * from registration callback. + */ + pjsua_ip_change_op_info info; - pj_bzero(&info, sizeof(info)); - info.acc_update_contact.acc_id = acc->index; - info.acc_update_contact.is_register = !need_unreg; + pj_bzero(&info, sizeof(info)); + info.acc_update_contact.acc_id = acc->index; + info.acc_update_contact.is_register = !need_unreg; - pjsua_var.ua_cfg.cb.on_ip_change_progress(acc->ip_change_op, - status, - &info); + pjsua_var.ua_cfg.cb.on_ip_change_progress(acc->ip_change_op, + status, + &info); - pjsua_acc_end_ip_change(acc); + pjsua_acc_end_ip_change(acc); } return status; } @@ -4211,127 +4210,127 @@ pj_status_t pjsua_acc_handle_call_on_ip_change(pjsua_acc *acc) PJSUA_LOCK(); if (acc->cfg.ip_change_cfg.hangup_calls || - acc->cfg.ip_change_cfg.reinvite_flags) + acc->cfg.ip_change_cfg.reinvite_flags) { - for (i = 0; i < (int)pjsua_var.ua_cfg.max_calls; ++i) { - pjsua_call_info call_info; - - if (!pjsua_call_is_active(i) || - pjsua_var.calls[i].acc_id != acc->index || - pjsua_call_get_info(i, &call_info) != PJ_SUCCESS) - { - continue; - } - - if ((acc->cfg.ip_change_cfg.hangup_calls) && - (call_info.state >= PJSIP_INV_STATE_EARLY)) - { - acc->ip_change_op = PJSUA_IP_CHANGE_OP_ACC_HANGUP_CALLS; - PJ_LOG(3, (THIS_FILE, "call to %.*s: hangup " - "triggered by IP change", - (int)call_info.remote_info.slen, - call_info.remote_info.ptr)); - - status = pjsua_call_hangup(i, PJSIP_SC_GONE, NULL, NULL); - - if (pjsua_var.ua_cfg.cb.on_ip_change_progress) { - pjsua_ip_change_op_info info; - - pj_bzero(&info, sizeof(info)); - info.acc_hangup_calls.acc_id = acc->index; - info.acc_hangup_calls.call_id = call_info.id; - - pjsua_var.ua_cfg.cb.on_ip_change_progress( - acc->ip_change_op, - status, - &info); - } - } else if ((acc->cfg.ip_change_cfg.reinvite_flags) && - (call_info.state == PJSIP_INV_STATE_CONFIRMED)) - { - pj_bool_t use_update = acc->cfg.ip_change_cfg.reinv_use_update; - - /* Check if remote support SIP UPDATE method */ - if (use_update) { - pjsua_call *call; - pjsip_dialog *dlg = NULL; - - PJ_LOG(5, (THIS_FILE, "Call #%d: IP change is configured " - "to using UPDATE", i)); - - status = acquire_call("handle_call_on_ip_change()", - i, &call, &dlg); - if (status != PJ_SUCCESS) { - use_update = PJ_FALSE; - PJ_PERROR(3,(THIS_FILE, status, - "Call #%d: IP change cannot " - "check if remote supports UPDATE due to " - "failure in acquiring dialog lock", i)); - } else { - const pj_str_t ST_UPDATE = {"UPDATE", 6}; - use_update = pjsip_dlg_remote_has_cap( - dlg, PJSIP_H_ALLOW, NULL, - &ST_UPDATE) - == PJSIP_DIALOG_CAP_SUPPORTED; - pjsip_dlg_dec_lock(dlg); - - if (!use_update) { - PJ_LOG(3, (THIS_FILE, "Call #%d: IP change will " - "use re-INVITE because remote does " - "not support UPDATE", i)); - } - } - } - - acc->ip_change_op = PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS; - - pjsua_call_cleanup_flag(&call_info.setting); - call_info.setting.flag |= - acc->cfg.ip_change_cfg.reinvite_flags; - - PJ_LOG(3, (THIS_FILE, "Call #%d to %.*s: send %s " - "with flags 0x%x triggered " - "by IP change (IP change flag: 0x%x)", - i, - call_info.remote_info.slen, - call_info.remote_info.ptr, - (use_update? "UPDATE" : "re-INVITE"), - call_info.setting.flag, - acc->cfg.ip_change_cfg.reinvite_flags)); - - /* Refresh call using UPDATE */ - if (use_update) { - status = pjsua_call_update(i, call_info.setting.flag, - NULL); - /* If this fails, retry using INVITE below */ - if (status != PJ_SUCCESS) { - PJ_LOG(3, (THIS_FILE, "Call #%d: failed sending UPDATE" - " retrying using re-INVITE", i)); - use_update = PJ_FALSE; - } - } - - /* Refresh call using re-INVITE */ - if (!use_update) { - status = pjsua_call_reinvite(i, call_info.setting.flag, - NULL); - } - - if (pjsua_var.ua_cfg.cb.on_ip_change_progress) { - pjsua_ip_change_op_info info; - - pj_bzero(&info, sizeof(info)); - info.acc_reinvite_calls.acc_id = acc->index; - info.acc_reinvite_calls.call_id = call_info.id; - - pjsua_var.ua_cfg.cb.on_ip_change_progress( - acc->ip_change_op, - status, - &info); - } - - } - } + for (i = 0; i < (int)pjsua_var.ua_cfg.max_calls; ++i) { + pjsua_call_info call_info; + + if (!pjsua_call_is_active(i) || + pjsua_var.calls[i].acc_id != acc->index || + pjsua_call_get_info(i, &call_info) != PJ_SUCCESS) + { + continue; + } + + if ((acc->cfg.ip_change_cfg.hangup_calls) && + (call_info.state >= PJSIP_INV_STATE_EARLY)) + { + acc->ip_change_op = PJSUA_IP_CHANGE_OP_ACC_HANGUP_CALLS; + PJ_LOG(3, (THIS_FILE, "call to %.*s: hangup " + "triggered by IP change", + (int)call_info.remote_info.slen, + call_info.remote_info.ptr)); + + status = pjsua_call_hangup(i, PJSIP_SC_GONE, NULL, NULL); + + if (pjsua_var.ua_cfg.cb.on_ip_change_progress) { + pjsua_ip_change_op_info info; + + pj_bzero(&info, sizeof(info)); + info.acc_hangup_calls.acc_id = acc->index; + info.acc_hangup_calls.call_id = call_info.id; + + pjsua_var.ua_cfg.cb.on_ip_change_progress( + acc->ip_change_op, + status, + &info); + } + } else if ((acc->cfg.ip_change_cfg.reinvite_flags) && + (call_info.state == PJSIP_INV_STATE_CONFIRMED)) + { + pj_bool_t use_update = acc->cfg.ip_change_cfg.reinv_use_update; + + /* Check if remote support SIP UPDATE method */ + if (use_update) { + pjsua_call *call; + pjsip_dialog *dlg = NULL; + + PJ_LOG(5, (THIS_FILE, "Call #%d: IP change is configured " + "to using UPDATE", i)); + + status = acquire_call("handle_call_on_ip_change()", + i, &call, &dlg); + if (status != PJ_SUCCESS) { + use_update = PJ_FALSE; + PJ_PERROR(3,(THIS_FILE, status, + "Call #%d: IP change cannot " + "check if remote supports UPDATE due to " + "failure in acquiring dialog lock", i)); + } else { + const pj_str_t ST_UPDATE = {"UPDATE", 6}; + use_update = pjsip_dlg_remote_has_cap( + dlg, PJSIP_H_ALLOW, NULL, + &ST_UPDATE) + == PJSIP_DIALOG_CAP_SUPPORTED; + pjsip_dlg_dec_lock(dlg); + + if (!use_update) { + PJ_LOG(3, (THIS_FILE, "Call #%d: IP change will " + "use re-INVITE because remote does " + "not support UPDATE", i)); + } + } + } + + acc->ip_change_op = PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS; + + pjsua_call_cleanup_flag(&call_info.setting); + call_info.setting.flag |= + acc->cfg.ip_change_cfg.reinvite_flags; + + PJ_LOG(3, (THIS_FILE, "Call #%d to %.*s: send %s " + "with flags 0x%x triggered " + "by IP change (IP change flag: 0x%x)", + i, + call_info.remote_info.slen, + call_info.remote_info.ptr, + (use_update? "UPDATE" : "re-INVITE"), + call_info.setting.flag, + acc->cfg.ip_change_cfg.reinvite_flags)); + + /* Refresh call using UPDATE */ + if (use_update) { + status = pjsua_call_update(i, call_info.setting.flag, + NULL); + /* If this fails, retry using INVITE below */ + if (status != PJ_SUCCESS) { + PJ_LOG(3, (THIS_FILE, "Call #%d: failed sending UPDATE" + " retrying using re-INVITE", i)); + use_update = PJ_FALSE; + } + } + + /* Refresh call using re-INVITE */ + if (!use_update) { + status = pjsua_call_reinvite(i, call_info.setting.flag, + NULL); + } + + if (pjsua_var.ua_cfg.cb.on_ip_change_progress) { + pjsua_ip_change_op_info info; + + pj_bzero(&info, sizeof(info)); + info.acc_reinvite_calls.acc_id = acc->index; + info.acc_reinvite_calls.call_id = call_info.id; + + pjsua_var.ua_cfg.cb.on_ip_change_progress( + acc->ip_change_op, + status, + &info); + } + + } + } } pjsua_acc_end_ip_change(acc); PJSUA_UNLOCK(); @@ -4345,27 +4344,27 @@ void pjsua_acc_end_ip_change(pjsua_acc *acc) PJSUA_LOCK(); if (acc && acc->ip_change_op < PJSUA_IP_CHANGE_OP_COMPLETED) { - PJ_LOG(3, (THIS_FILE, "IP address change handling for acc %d " - "completed", acc->index)); - acc->ip_change_op = PJSUA_IP_CHANGE_OP_COMPLETED; - if (pjsua_var.acc_cnt) { - for (; i < (int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) { - if (pjsua_var.acc[i].valid && - pjsua_var.acc[i].ip_change_op != - PJSUA_IP_CHANGE_OP_COMPLETED) - { - all_done = PJ_FALSE; - break; - } - } - } + PJ_LOG(3, (THIS_FILE, "IP address change handling for acc %d " + "completed", acc->index)); + acc->ip_change_op = PJSUA_IP_CHANGE_OP_COMPLETED; + if (pjsua_var.acc_cnt) { + for (; i < (int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) { + if (pjsua_var.acc[i].valid && + pjsua_var.acc[i].ip_change_op != + PJSUA_IP_CHANGE_OP_COMPLETED) + { + all_done = PJ_FALSE; + break; + } + } + } } if (all_done && pjsua_var.ua_cfg.cb.on_ip_change_progress) { - PJ_LOG(3, (THIS_FILE, "IP address change handling completed")); - pjsua_var.ua_cfg.cb.on_ip_change_progress( - PJSUA_IP_CHANGE_OP_COMPLETED, - PJ_SUCCESS, - NULL); + PJ_LOG(3, (THIS_FILE, "IP address change handling completed")); + pjsua_var.ua_cfg.cb.on_ip_change_progress( + PJSUA_IP_CHANGE_OP_COMPLETED, + PJ_SUCCESS, + NULL); } PJSUA_UNLOCK(); } diff --git a/pjsip/src/pjsua-lib/pjsua_aud.c b/pjsip/src/pjsua-lib/pjsua_aud.c index c2f61354d8..d61a4f9b08 100644 --- a/pjsip/src/pjsua-lib/pjsua_aud.c +++ b/pjsip/src/pjsua-lib/pjsua_aud.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -22,7 +21,7 @@ #if defined(PJSUA_MEDIA_HAS_PJMEDIA) && PJSUA_MEDIA_HAS_PJMEDIA != 0 -#define THIS_FILE "pjsua_aud.c" +#define THIS_FILE "pjsua_aud.c" /***************************************************************************** * @@ -34,13 +33,13 @@ static pj_status_t open_snd_dev(pjmedia_snd_port_param *param); static void close_snd_dev(void); /* Create audio device param */ static pj_status_t create_aud_param(pjmedia_aud_param *param, - pjmedia_aud_dev_index capture_dev, - pjmedia_aud_dev_index playback_dev, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pj_bool_t use_default_settings); + pjmedia_aud_dev_index capture_dev, + pjmedia_aud_dev_index playback_dev, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pj_bool_t use_default_settings); /***************************************************************************** * @@ -53,7 +52,7 @@ PJ_DEF(pj_bool_t) pjsua_call_has_media(pjsua_call_id call_id) { pjsua_call *call = &pjsua_var.calls[call_id]; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); return call->audio_idx >= 0 && call->media[call->audio_idx].strm.a.stream; } @@ -67,7 +66,7 @@ PJ_DEF(pjsua_conf_port_id) pjsua_call_get_conf_port(pjsua_call_id call_id) pjsua_conf_port_id port_id = PJSUA_INVALID_ID; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); /* Use PJSUA_LOCK() instead of acquire_call(): * https://github.com/pjsip/pjproject/issues/1371 @@ -75,11 +74,11 @@ PJ_DEF(pjsua_conf_port_id) pjsua_call_get_conf_port(pjsua_call_id call_id) PJSUA_LOCK(); if (!pjsua_call_is_active(call_id)) - goto on_return; + goto on_return; call = &pjsua_var.calls[call_id]; if (call->audio_idx >= 0) - port_id = call->media[call->audio_idx].strm.a.conf_slot; + port_id = call->media[call->audio_idx].strm.a.conf_slot; on_return: PJSUA_UNLOCK(); @@ -94,36 +93,36 @@ PJ_DEF(pjsua_conf_port_id) pjsua_call_get_conf_port(pjsua_call_id call_id) PJ_DEF(pj_status_t) pjsua_call_aud_stream_modify_codec_param(pjsua_call_id call_id, int med_idx, - const pjmedia_codec_param *param) + const pjmedia_codec_param *param) { pjsua_call *call; pjsua_call_media *call_med; pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls && - param, PJ_EINVAL); + param, PJ_EINVAL); PJSUA_LOCK(); /* Verify media index */ call = &pjsua_var.calls[call_id]; if (med_idx == -1) { - med_idx = call->audio_idx; + med_idx = call->audio_idx; } if (med_idx < 0 || med_idx >= (int)call->med_cnt) { - PJSUA_UNLOCK(); - return PJ_EINVAL; + PJSUA_UNLOCK(); + return PJ_EINVAL; } /* Verify if the media is audio */ call_med = &call->media[med_idx]; if (call_med->type != PJMEDIA_TYPE_AUDIO || !call_med->strm.a.stream) { - PJSUA_UNLOCK(); - return PJ_EINVALIDOP; + PJSUA_UNLOCK(); + return PJ_EINVALIDOP; } status = pjmedia_stream_modify_codec_param(call_med->strm.a.stream, - param); + param); PJSUA_UNLOCK(); return status; @@ -142,7 +141,7 @@ PJ_DEF(pj_status_t) pjsua_call_get_stream_info( pjsua_call_id call_id, pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(psi, PJ_EINVAL); PJSUA_LOCK(); @@ -150,26 +149,26 @@ PJ_DEF(pj_status_t) pjsua_call_get_stream_info( pjsua_call_id call_id, call = &pjsua_var.calls[call_id]; if (med_idx >= call->med_cnt) { - PJSUA_UNLOCK(); - return PJ_EINVAL; + PJSUA_UNLOCK(); + return PJ_EINVAL; } call_med = &call->media[med_idx]; psi->type = call_med->type; switch (call_med->type) { case PJMEDIA_TYPE_AUDIO: - status = pjmedia_stream_get_info(call_med->strm.a.stream, - &psi->info.aud); - break; + status = pjmedia_stream_get_info(call_med->strm.a.stream, + &psi->info.aud); + break; #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) case PJMEDIA_TYPE_VIDEO: - status = pjmedia_vid_stream_get_info(call_med->strm.v.stream, - &psi->info.vid); - break; + status = pjmedia_vid_stream_get_info(call_med->strm.v.stream, + &psi->info.vid); + break; #endif default: - status = PJMEDIA_EINVALIMEDIATYPE; - break; + status = PJMEDIA_EINVALIMEDIATYPE; + break; } PJSUA_UNLOCK(); @@ -189,7 +188,7 @@ PJ_DEF(pj_status_t) pjsua_call_get_stream_stat( pjsua_call_id call_id, pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(stat, PJ_EINVAL); PJSUA_LOCK(); @@ -197,31 +196,31 @@ PJ_DEF(pj_status_t) pjsua_call_get_stream_stat( pjsua_call_id call_id, call = &pjsua_var.calls[call_id]; if (med_idx >= call->med_cnt) { - PJSUA_UNLOCK(); - return PJ_EINVAL; + PJSUA_UNLOCK(); + return PJ_EINVAL; } call_med = &call->media[med_idx]; switch (call_med->type) { case PJMEDIA_TYPE_AUDIO: - status = pjmedia_stream_get_stat(call_med->strm.a.stream, - &stat->rtcp); - if (status == PJ_SUCCESS) - status = pjmedia_stream_get_stat_jbuf(call_med->strm.a.stream, - &stat->jbuf); - break; + status = pjmedia_stream_get_stat(call_med->strm.a.stream, + &stat->rtcp); + if (status == PJ_SUCCESS) + status = pjmedia_stream_get_stat_jbuf(call_med->strm.a.stream, + &stat->jbuf); + break; #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) case PJMEDIA_TYPE_VIDEO: - status = pjmedia_vid_stream_get_stat(call_med->strm.v.stream, - &stat->rtcp); - if (status == PJ_SUCCESS) - status = pjmedia_vid_stream_get_stat_jbuf(call_med->strm.v.stream, - &stat->jbuf); - break; + status = pjmedia_vid_stream_get_stat(call_med->strm.v.stream, + &stat->rtcp); + if (status == PJ_SUCCESS) + status = pjmedia_vid_stream_get_stat_jbuf(call_med->strm.v.stream, + &stat->jbuf); + break; #endif default: - status = PJMEDIA_EINVALIMEDIATYPE; - break; + status = PJMEDIA_EINVALIMEDIATYPE; + break; } PJSUA_UNLOCK(); @@ -232,31 +231,31 @@ PJ_DEF(pj_status_t) pjsua_call_get_stream_stat( pjsua_call_id call_id, * Send DTMF digits to remote using RFC 2833 payload formats. */ PJ_DEF(pj_status_t) pjsua_call_dial_dtmf( pjsua_call_id call_id, - const pj_str_t *digits) + const pj_str_t *digits) { pjsua_call *call; pjsip_dialog *dlg = NULL; pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Call %d dialing DTMF %.*s", - call_id, (int)digits->slen, digits->ptr)); + call_id, (int)digits->slen, digits->ptr)); pj_log_push_indent(); status = acquire_call("pjsua_call_dial_dtmf()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; if (!pjsua_call_has_media(call_id)) { - PJ_LOG(3,(THIS_FILE, "Media is not established yet!")); - status = PJ_EINVALIDOP; - goto on_return; + PJ_LOG(3,(THIS_FILE, "Media is not established yet!")); + status = PJ_EINVALIDOP; + goto on_return; } status = pjmedia_stream_dial_dtmf( - call->media[call->audio_idx].strm.a.stream, digits); + call->media[call->audio_idx].strm.a.stream, digits); on_return: if (dlg) pjsip_dlg_dec_lock(dlg); @@ -292,49 +291,49 @@ pj_status_t pjsua_aud_subsys_init() #if PJMEDIA_HAS_PASSTHROUGH_CODECS /* Register passthrough codecs */ { - unsigned aud_idx; - unsigned ext_fmt_cnt = 0; - pjmedia_format ext_fmts[32]; - - /* List extended formats supported by audio devices */ - for (aud_idx = 0; aud_idx < pjmedia_aud_dev_count(); ++aud_idx) { - pjmedia_aud_dev_info aud_info; - unsigned i; - - status = pjmedia_aud_dev_get_info(aud_idx, &aud_info); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error querying audio device info", - status); - goto on_error; - } - - /* Collect extended formats supported by this audio device */ - for (i = 0; i < aud_info.ext_fmt_cnt; ++i) { - unsigned j; - pj_bool_t is_listed = PJ_FALSE; - - /* See if this extended format is already in the list */ - for (j = 0; j < ext_fmt_cnt && !is_listed; ++j) { - if (ext_fmts[j].id == aud_info.ext_fmt[i].id && - ext_fmts[j].det.aud.avg_bps == - aud_info.ext_fmt[i].det.aud.avg_bps) - { - is_listed = PJ_TRUE; - } - } - - /* Put this format into the list, if it is not in the list */ - if (!is_listed) - ext_fmts[ext_fmt_cnt++] = aud_info.ext_fmt[i]; - - pj_assert(ext_fmt_cnt <= PJ_ARRAY_SIZE(ext_fmts)); - } - } - - /* Init the passthrough codec with supported formats only */ - codec_cfg.passthrough.setting.fmt_cnt = ext_fmt_cnt; - codec_cfg.passthrough.setting.fmts = ext_fmts; - codec_cfg.passthrough.setting.ilbc_mode = + unsigned aud_idx; + unsigned ext_fmt_cnt = 0; + pjmedia_format ext_fmts[32]; + + /* List extended formats supported by audio devices */ + for (aud_idx = 0; aud_idx < pjmedia_aud_dev_count(); ++aud_idx) { + pjmedia_aud_dev_info aud_info; + unsigned i; + + status = pjmedia_aud_dev_get_info(aud_idx, &aud_info); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error querying audio device info", + status); + goto on_error; + } + + /* Collect extended formats supported by this audio device */ + for (i = 0; i < aud_info.ext_fmt_cnt; ++i) { + unsigned j; + pj_bool_t is_listed = PJ_FALSE; + + /* See if this extended format is already in the list */ + for (j = 0; j < ext_fmt_cnt && !is_listed; ++j) { + if (ext_fmts[j].id == aud_info.ext_fmt[i].id && + ext_fmts[j].det.aud.avg_bps == + aud_info.ext_fmt[i].det.aud.avg_bps) + { + is_listed = PJ_TRUE; + } + } + + /* Put this format into the list, if it is not in the list */ + if (!is_listed) + ext_fmts[ext_fmt_cnt++] = aud_info.ext_fmt[i]; + + pj_assert(ext_fmt_cnt <= PJ_ARRAY_SIZE(ext_fmts)); + } + } + + /* Init the passthrough codec with supported formats only */ + codec_cfg.passthrough.setting.fmt_cnt = ext_fmt_cnt; + codec_cfg.passthrough.setting.fmts = ext_fmts; + codec_cfg.passthrough.setting.ilbc_mode = pjsua_var.media_cfg.ilbc_mode; } #endif /* PJMEDIA_HAS_PASSTHROUGH_CODECS */ @@ -343,27 +342,27 @@ pj_status_t pjsua_aud_subsys_init() status = pjmedia_codec_register_audio_codecs(pjsua_var.med_endpt, &codec_cfg); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error registering codecs", status); - goto on_error; + pjsua_perror(THIS_FILE, "Error registering codecs", status); + goto on_error; } /* Set speex/16000 to higher priority*/ codec_id = pj_str("speex/16000"); pjmedia_codec_mgr_set_codec_priority( - pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt), - &codec_id, PJMEDIA_CODEC_PRIO_NORMAL+2); + pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt), + &codec_id, PJMEDIA_CODEC_PRIO_NORMAL+2); /* Set speex/8000 to next higher priority*/ codec_id = pj_str("speex/8000"); pjmedia_codec_mgr_set_codec_priority( - pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt), - &codec_id, PJMEDIA_CODEC_PRIO_NORMAL+1); + pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt), + &codec_id, PJMEDIA_CODEC_PRIO_NORMAL+1); /* Disable ALL L16 codecs */ codec_id = pj_str("L16"); pjmedia_codec_mgr_set_codec_priority( - pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt), - &codec_id, PJMEDIA_CODEC_PRIO_DISABLED); + pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt), + &codec_id, PJMEDIA_CODEC_PRIO_DISABLED); /* Save additional conference bridge parameters for future @@ -372,46 +371,46 @@ pj_status_t pjsua_aud_subsys_init() pjsua_var.mconf_cfg.channel_count = pjsua_var.media_cfg.channel_count; pjsua_var.mconf_cfg.bits_per_sample = 16; pjsua_var.mconf_cfg.samples_per_frame = pjsua_var.media_cfg.clock_rate * - pjsua_var.mconf_cfg.channel_count * - pjsua_var.media_cfg.audio_frame_ptime / - 1000; + pjsua_var.mconf_cfg.channel_count * + pjsua_var.media_cfg.audio_frame_ptime / + 1000; /* Init options for conference bridge. */ opt = PJMEDIA_CONF_NO_DEVICE; if (pjsua_var.media_cfg.quality >= 3 && - pjsua_var.media_cfg.quality <= 4) + pjsua_var.media_cfg.quality <= 4) { - opt |= PJMEDIA_CONF_SMALL_FILTER; + opt |= PJMEDIA_CONF_SMALL_FILTER; } else if (pjsua_var.media_cfg.quality < 3) { - opt |= PJMEDIA_CONF_USE_LINEAR; + opt |= PJMEDIA_CONF_USE_LINEAR; } /* Init conference bridge. */ status = pjmedia_conf_create(pjsua_var.pool, - pjsua_var.media_cfg.max_media_ports, - pjsua_var.media_cfg.clock_rate, - pjsua_var.mconf_cfg.channel_count, - pjsua_var.mconf_cfg.samples_per_frame, - pjsua_var.mconf_cfg.bits_per_sample, - opt, &pjsua_var.mconf); + pjsua_var.media_cfg.max_media_ports, + pjsua_var.media_cfg.clock_rate, + pjsua_var.mconf_cfg.channel_count, + pjsua_var.mconf_cfg.samples_per_frame, + pjsua_var.mconf_cfg.bits_per_sample, + opt, &pjsua_var.mconf); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating conference bridge", - status); - goto on_error; + pjsua_perror(THIS_FILE, "Error creating conference bridge", + status); + goto on_error; } /* Are we using the audio switchboard (a.k.a APS-Direct)? */ pjsua_var.is_mswitch = pjmedia_conf_get_master_port(pjsua_var.mconf) - ->info.signature == PJMEDIA_CONF_SWITCH_SIGNATURE; + ->info.signature == PJMEDIA_CONF_SWITCH_SIGNATURE; /* Create null port just in case user wants to use null sound. */ status = pjmedia_null_port_create(pjsua_var.pool, - pjsua_var.media_cfg.clock_rate, - pjsua_var.mconf_cfg.channel_count, - pjsua_var.mconf_cfg.samples_per_frame, - pjsua_var.mconf_cfg.bits_per_sample, - &pjsua_var.null_port); + pjsua_var.media_cfg.clock_rate, + pjsua_var.mconf_cfg.channel_count, + pjsua_var.mconf_cfg.samples_per_frame, + pjsua_var.mconf_cfg.bits_per_sample, + &pjsua_var.null_port); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); return status; @@ -427,11 +426,11 @@ void pjsua_check_snd_dev_idle() /* Check if the sound device auto-close feature is disabled. */ if (pjsua_var.media_cfg.snd_auto_close_time < 0) - return; + return; /* Check if the sound device is currently closed. */ if (!pjsua_var.snd_is_on) - return; + return; /* Get the call count, we shouldn't close the sound device when there is * any calls active. @@ -445,15 +444,15 @@ void pjsua_check_snd_dev_idle() * call. */ if (call_cnt == 1) { - pjsua_call_id call_id; - pj_status_t status; - - status = pjsua_enum_calls(&call_id, &call_cnt); - if (status == PJ_SUCCESS && call_cnt > 0 && - !pjsua_call_is_active(call_id)) - { - call_cnt = 0; - } + pjsua_call_id call_id; + pj_status_t status; + + status = pjsua_enum_calls(&call_id, &call_cnt); + if (status == PJ_SUCCESS && call_cnt > 0 && + !pjsua_call_is_active(call_id)) + { + call_cnt = 0; + } } /* Activate sound device auto-close timer if sound device is idle. @@ -461,34 +460,34 @@ void pjsua_check_snd_dev_idle() * there is no active call. */ if (pjsua_var.snd_idle_timer.id == PJ_FALSE && - call_cnt == 0 && - pjmedia_conf_get_connect_count(pjsua_var.mconf) == 0) + call_cnt == 0 && + pjmedia_conf_get_connect_count(pjsua_var.mconf) == 0) { - pj_time_val delay; + pj_time_val delay; - delay.msec = 0; - delay.sec = pjsua_var.media_cfg.snd_auto_close_time; + delay.msec = 0; + delay.sec = pjsua_var.media_cfg.snd_auto_close_time; - pjsua_var.snd_idle_timer.id = PJ_TRUE; - pjsip_endpt_schedule_timer(pjsua_var.endpt, &pjsua_var.snd_idle_timer, - &delay); + pjsua_var.snd_idle_timer.id = PJ_TRUE; + pjsip_endpt_schedule_timer(pjsua_var.endpt, &pjsua_var.snd_idle_timer, + &delay); } } /* Timer callback to close sound device */ static void close_snd_timer_cb( pj_timer_heap_t *th, - pj_timer_entry *entry) + pj_timer_entry *entry) { PJ_UNUSED_ARG(th); PJSUA_LOCK(); if (entry->id) { - PJ_LOG(4,(THIS_FILE,"Closing sound device after idle for %d second(s)", - pjsua_var.media_cfg.snd_auto_close_time)); + PJ_LOG(4,(THIS_FILE,"Closing sound device after idle for %d second(s)", + pjsua_var.media_cfg.snd_auto_close_time)); - entry->id = PJ_FALSE; + entry->id = PJ_FALSE; - close_snd_dev(); + close_snd_dev(); } PJSUA_UNLOCK(); } @@ -498,7 +497,7 @@ pj_status_t pjsua_aud_subsys_start(void) pj_status_t status = PJ_SUCCESS; pj_timer_entry_init(&pjsua_var.snd_idle_timer, PJ_FALSE, NULL, - &close_snd_timer_cb); + &close_snd_timer_cb); pjsua_check_snd_dev_idle(); return status; @@ -512,30 +511,30 @@ pj_status_t pjsua_aud_subsys_destroy() /* Destroy file players */ for (i=0; iprev_aud_si); - - /* Unsubscribe from stream events */ - pjmedia_event_unsubscribe(NULL, &call_media_on_event, call_med, strm); - - pjmedia_stream_send_rtcp_bye(strm); - - if (call_med->strm.a.conf_slot != PJSUA_INVALID_ID) { - if (pjsua_var.mconf) { - pjsua_conf_remove_port(call_med->strm.a.conf_slot); - } - call_med->strm.a.conf_slot = PJSUA_INVALID_ID; - } - - /* Don't check for direction and transmitted packets count as we - * assume that RTP timestamp remains increasing when outgoing - * direction is disabled/paused. - */ - //if ((call_med->dir & PJMEDIA_DIR_ENCODING) && - // (pjmedia_stream_get_stat(strm, &stat) == PJ_SUCCESS) && - // stat.tx.pkt) - if (pjmedia_stream_get_stat(strm, &stat) == PJ_SUCCESS) - { - /* Save RTP timestamp & sequence, so when media session is - * restarted, those values will be restored as the initial - * RTP timestamp & sequence of the new media session. So in - * the same call session, RTP timestamp and sequence are - * guaranteed to be contigue. - */ - call_med->rtp_tx_seq_ts_set = 1 | (1 << 1); - call_med->rtp_tx_seq = stat.rtp_tx_last_seq; - call_med->rtp_tx_ts = stat.rtp_tx_last_ts; - } - - if (!call_med->call->hanging_up && - pjsua_var.ua_cfg.cb.on_stream_destroyed) - { - pjsua_var.ua_cfg.cb.on_stream_destroyed(call_med->call->index, - strm, call_med->idx); - } - - if (call_med->strm.a.media_port) { - if (call_med->strm.a.destroy_port) - pjmedia_port_destroy(call_med->strm.a.media_port); - call_med->strm.a.media_port = NULL; - } - - pjmedia_stream_destroy(strm); - call_med->strm.a.stream = NULL; + pjmedia_stream_get_info(strm, &call_med->prev_aud_si); + + /* Unsubscribe from stream events */ + pjmedia_event_unsubscribe(NULL, &call_media_on_event, call_med, strm); + + pjmedia_stream_send_rtcp_bye(strm); + + if (call_med->strm.a.conf_slot != PJSUA_INVALID_ID) { + if (pjsua_var.mconf) { + pjsua_conf_remove_port(call_med->strm.a.conf_slot); + } + call_med->strm.a.conf_slot = PJSUA_INVALID_ID; + } + + /* Don't check for direction and transmitted packets count as we + * assume that RTP timestamp remains increasing when outgoing + * direction is disabled/paused. + */ + //if ((call_med->dir & PJMEDIA_DIR_ENCODING) && + // (pjmedia_stream_get_stat(strm, &stat) == PJ_SUCCESS) && + // stat.tx.pkt) + if (pjmedia_stream_get_stat(strm, &stat) == PJ_SUCCESS) + { + /* Save RTP timestamp & sequence, so when media session is + * restarted, those values will be restored as the initial + * RTP timestamp & sequence of the new media session. So in + * the same call session, RTP timestamp and sequence are + * guaranteed to be contigue. + */ + call_med->rtp_tx_seq_ts_set = 1 | (1 << 1); + call_med->rtp_tx_seq = stat.rtp_tx_last_seq; + call_med->rtp_tx_ts = stat.rtp_tx_last_ts; + } + + if (!call_med->call->hanging_up && + pjsua_var.ua_cfg.cb.on_stream_destroyed) + { + pjsua_var.ua_cfg.cb.on_stream_destroyed(call_med->call->index, + strm, call_med->idx); + } + + if (call_med->strm.a.media_port) { + if (call_med->strm.a.destroy_port) + pjmedia_port_destroy(call_med->strm.a.media_port); + call_med->strm.a.media_port = NULL; + } + + pjmedia_stream_destroy(strm); + call_med->strm.a.stream = NULL; } pjsua_check_snd_dev_idle(); @@ -605,7 +604,7 @@ void pjsua_aud_stop_stream(pjsua_call_media *call_med) * DTMF callback from the stream. */ static void dtmf_callback(pjmedia_stream *strm, void *user_data, - int digit) + int digit) { pjsua_call_id call_id; @@ -613,23 +612,23 @@ static void dtmf_callback(pjmedia_stream *strm, void *user_data, call_id = (pjsua_call_id)(pj_ssize_t)user_data; if (pjsua_var.calls[call_id].hanging_up) - return; + return; pj_log_push_indent(); if (pjsua_var.ua_cfg.cb.on_dtmf_digit2) { - pjsua_dtmf_info info; + pjsua_dtmf_info info; - info.method = PJSUA_DTMF_METHOD_RFC2833; - info.digit = digit; + info.method = PJSUA_DTMF_METHOD_RFC2833; + info.digit = digit; info.duration = PJSUA_UNKNOWN_DTMF_DURATION; - (*pjsua_var.ua_cfg.cb.on_dtmf_digit2)(call_id, &info); + (*pjsua_var.ua_cfg.cb.on_dtmf_digit2)(call_id, &info); } else if (pjsua_var.ua_cfg.cb.on_dtmf_digit) { - /* For discussions about call mutex protection related to this - * callback, please see ticket #460: - * https://github.com/pjsip/pjproject/issues/460#comment:4 - */ - (*pjsua_var.ua_cfg.cb.on_dtmf_digit)(call_id, digit); + /* For discussions about call mutex protection related to this + * callback, please see ticket #460: + * https://github.com/pjsip/pjproject/issues/460#comment:4 + */ + (*pjsua_var.ua_cfg.cb.on_dtmf_digit)(call_id, digit); } pj_log_pop_indent(); @@ -648,7 +647,7 @@ static void dtmf_event_callback(pjmedia_stream *strm, void *user_data, call_id = (pjsua_call_id)(pj_ssize_t)user_data; if (pjsua_var.calls[call_id].hanging_up) - return; + return; pj_log_push_indent(); @@ -667,14 +666,14 @@ static void dtmf_event_callback(pjmedia_stream *strm, void *user_data, /* Internal function: update audio channel after SDP negotiation. * Warning: do not use temporary/flip-flop pool, e.g: inv->pool_prov, * for creating stream, etc, as after SDP negotiation and when - * the SDP media is not changed, the stream should remain running + * the SDP media is not changed, the stream should remain running * while the temporary/flip-flop pool may be released. */ pj_status_t pjsua_aud_channel_update(pjsua_call_media *call_med, pj_pool_t *tmp_pool, pjmedia_stream_info *si, - const pjmedia_sdp_session *local_sdp, - const pjmedia_sdp_session *remote_sdp) + const pjmedia_sdp_session *local_sdp, + const pjmedia_sdp_session *remote_sdp) { pjsua_call *call = call_med->call; unsigned strm_idx = call_med->idx; @@ -692,31 +691,31 @@ pj_status_t pjsua_aud_channel_update(pjsua_call_media *call_med, /* Check if no media is active */ if (local_sdp->media[strm_idx]->desc.port != 0) { - /* Optionally, application may modify other stream settings here - * (such as jitter buffer parameters, codec ptime, etc.) - */ - si->jb_init = pjsua_var.media_cfg.jb_init; - si->jb_min_pre = pjsua_var.media_cfg.jb_min_pre; - si->jb_max_pre = pjsua_var.media_cfg.jb_max_pre; - si->jb_max = pjsua_var.media_cfg.jb_max; + /* Optionally, application may modify other stream settings here + * (such as jitter buffer parameters, codec ptime, etc.) + */ + si->jb_init = pjsua_var.media_cfg.jb_init; + si->jb_min_pre = pjsua_var.media_cfg.jb_min_pre; + si->jb_max_pre = pjsua_var.media_cfg.jb_max_pre; + si->jb_max = pjsua_var.media_cfg.jb_max; si->jb_discard_algo = pjsua_var.media_cfg.jb_discard_algo; - /* Set SSRC and CNAME */ - si->ssrc = call_med->ssrc; - si->cname = call->cname; + /* Set SSRC and CNAME */ + si->ssrc = call_med->ssrc; + si->cname = call->cname; - /* Set RTP timestamp & sequence, normally these value are intialized - * automatically when stream session created, but for some cases (e.g: - * call reinvite, call update) timestamp and sequence need to be kept - * contigue. - */ - si->rtp_ts = call_med->rtp_tx_ts; - si->rtp_seq = call_med->rtp_tx_seq; - si->rtp_seq_ts_set = call_med->rtp_tx_seq_ts_set; + /* Set RTP timestamp & sequence, normally these value are intialized + * automatically when stream session created, but for some cases (e.g: + * call reinvite, call update) timestamp and sequence need to be kept + * contigue. + */ + si->rtp_ts = call_med->rtp_tx_ts; + si->rtp_seq = call_med->rtp_tx_seq; + si->rtp_seq_ts_set = call_med->rtp_tx_seq_ts_set; #if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0 - /* Enable/disable stream keep-alive and NAT hole punch. */ - si->use_ka = pjsua_var.acc[call->acc_id].cfg.use_stream_ka; + /* Enable/disable stream keep-alive and NAT hole punch. */ + si->use_ka = pjsua_var.acc[call->acc_id].cfg.use_stream_ka; si->ka_cfg = pjsua_var.acc[call->acc_id].cfg.stream_ka_cfg; #endif @@ -740,97 +739,97 @@ pj_status_t pjsua_aud_channel_update(pjsua_call_media *call_med, si->rtcp_sdes_bye_disabled = prm.stream_info.info.aud.rtcp_sdes_bye_disabled; } - /* Create session based on session info. */ - status = pjmedia_stream_create(pjsua_var.med_endpt, NULL, si, - call_med->tp, NULL, - &call_med->strm.a.stream); - if (status != PJ_SUCCESS) { - goto on_return; - } + /* Create session based on session info. */ + status = pjmedia_stream_create(pjsua_var.med_endpt, NULL, si, + call_med->tp, NULL, + &call_med->strm.a.stream); + if (status != PJ_SUCCESS) { + goto on_return; + } - /* Start stream */ - status = pjmedia_stream_start(call_med->strm.a.stream); - if (status != PJ_SUCCESS) { - goto on_return; - } + /* Start stream */ + status = pjmedia_stream_start(call_med->strm.a.stream); + if (status != PJ_SUCCESS) { + goto on_return; + } if (call_med->prev_state == PJSUA_CALL_MEDIA_NONE) pjmedia_stream_send_rtcp_sdes(call_med->strm.a.stream); - /* If DTMF callback is installed by application, install our - * callback to the session. - */ + /* If DTMF callback is installed by application, install our + * callback to the session. + */ if (!call->hanging_up && pjsua_var.ua_cfg.cb.on_dtmf_event) { pjmedia_stream_set_dtmf_event_callback(call_med->strm.a.stream, &dtmf_event_callback, (void*)(pj_ssize_t)(call->index)); } else if (!call->hanging_up && - (pjsua_var.ua_cfg.cb.on_dtmf_digit || - pjsua_var.ua_cfg.cb.on_dtmf_digit2)) - { - pjmedia_stream_set_dtmf_callback(call_med->strm.a.stream, - &dtmf_callback, - (void*)(pj_ssize_t)(call->index)); - } - - /* Get the port interface of the first stream in the session. - * We need the port interface to add to the conference bridge. - */ - pjmedia_stream_get_port(call_med->strm.a.stream, - &call_med->strm.a.media_port); - - /* Notify application about stream creation. - * Note: application may modify media_port to point to different - * media port - */ - if (!call->hanging_up && pjsua_var.ua_cfg.cb.on_stream_created2) { - pjsua_on_stream_created_param prm; - - prm.stream = call_med->strm.a.stream; - prm.stream_idx = strm_idx; - prm.destroy_port = PJ_FALSE; - prm.port = call_med->strm.a.media_port; - (*pjsua_var.ua_cfg.cb.on_stream_created2)(call->index, &prm); - - call_med->strm.a.destroy_port = prm.destroy_port; - call_med->strm.a.media_port = prm.port; - - } else if (!call->hanging_up && pjsua_var.ua_cfg.cb.on_stream_created) - { - (*pjsua_var.ua_cfg.cb.on_stream_created)(call->index, - call_med->strm.a.stream, - strm_idx, - &call_med->strm.a.media_port); - } - - /* - * Add the call to conference bridge. - */ - { - char tmp[PJSIP_MAX_URL_SIZE]; - pj_str_t port_name; - - port_name.ptr = tmp; - port_name.slen = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, - call->inv->dlg->remote.info->uri, - tmp, sizeof(tmp)); - if (port_name.slen < 1) { - port_name = pj_str("call"); - } - status = pjmedia_conf_add_port(pjsua_var.mconf, - call->inv->pool, - call_med->strm.a.media_port, - &port_name, - (unsigned*) - &call_med->strm.a.conf_slot); - if (status != PJ_SUCCESS) { - goto on_return; - } - } - - /* Subscribe to stream events */ - pjmedia_event_subscribe(NULL, &call_media_on_event, call_med, - call_med->strm.a.stream); + (pjsua_var.ua_cfg.cb.on_dtmf_digit || + pjsua_var.ua_cfg.cb.on_dtmf_digit2)) + { + pjmedia_stream_set_dtmf_callback(call_med->strm.a.stream, + &dtmf_callback, + (void*)(pj_ssize_t)(call->index)); + } + + /* Get the port interface of the first stream in the session. + * We need the port interface to add to the conference bridge. + */ + pjmedia_stream_get_port(call_med->strm.a.stream, + &call_med->strm.a.media_port); + + /* Notify application about stream creation. + * Note: application may modify media_port to point to different + * media port + */ + if (!call->hanging_up && pjsua_var.ua_cfg.cb.on_stream_created2) { + pjsua_on_stream_created_param prm; + + prm.stream = call_med->strm.a.stream; + prm.stream_idx = strm_idx; + prm.destroy_port = PJ_FALSE; + prm.port = call_med->strm.a.media_port; + (*pjsua_var.ua_cfg.cb.on_stream_created2)(call->index, &prm); + + call_med->strm.a.destroy_port = prm.destroy_port; + call_med->strm.a.media_port = prm.port; + + } else if (!call->hanging_up && pjsua_var.ua_cfg.cb.on_stream_created) + { + (*pjsua_var.ua_cfg.cb.on_stream_created)(call->index, + call_med->strm.a.stream, + strm_idx, + &call_med->strm.a.media_port); + } + + /* + * Add the call to conference bridge. + */ + { + char tmp[PJSIP_MAX_URL_SIZE]; + pj_str_t port_name; + + port_name.ptr = tmp; + port_name.slen = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, + call->inv->dlg->remote.info->uri, + tmp, sizeof(tmp)); + if (port_name.slen < 1) { + port_name = pj_str("call"); + } + status = pjmedia_conf_add_port(pjsua_var.mconf, + call->inv->pool, + call_med->strm.a.media_port, + &port_name, + (unsigned*) + &call_med->strm.a.conf_slot); + if (status != PJ_SUCCESS) { + goto on_return; + } + } + + /* Subscribe to stream events */ + pjmedia_event_subscribe(NULL, &call_media_on_event, call_med, + call_med->strm.a.stream); } on_return: @@ -871,7 +870,7 @@ PJ_DEF(unsigned) pjsua_conf_get_active_ports(void) status = pjmedia_conf_enum_ports(pjsua_var.mconf, ports, &count); if (status != PJ_SUCCESS) - count = 0; + count = 0; return count; } @@ -881,7 +880,7 @@ PJ_DEF(unsigned) pjsua_conf_get_active_ports(void) * Enumerate all conference ports. */ PJ_DEF(pj_status_t) pjsua_enum_conf_ports(pjsua_conf_port_id id[], - unsigned *count) + unsigned *count) { return pjmedia_conf_enum_ports(pjsua_var.mconf, (unsigned*)id, count); } @@ -891,7 +890,7 @@ PJ_DEF(pj_status_t) pjsua_enum_conf_ports(pjsua_conf_port_id id[], * Get information about the specified conference port */ PJ_DEF(pj_status_t) pjsua_conf_get_port_info( pjsua_conf_port_id id, - pjsua_conf_port_info *info) + pjsua_conf_port_info *info) { pjmedia_conf_port_info cinfo; unsigned i; @@ -901,7 +900,7 @@ PJ_DEF(pj_status_t) pjsua_conf_get_port_info( pjsua_conf_port_id id, status = pjmedia_conf_get_port_info( pjsua_var.mconf, id, &cinfo); if (status != PJ_SUCCESS) - return status; + return status; pj_bzero(info, sizeof(*info)); info->slot_id = id; @@ -917,7 +916,7 @@ PJ_DEF(pj_status_t) pjsua_conf_get_port_info( pjsua_conf_port_id id, /* Build array of listeners */ info->listener_cnt = cinfo.listener_cnt; for (i=0; ilisteners[i] = cinfo.listener_slots[i]; + info->listeners[i] = cinfo.listener_slots[i]; } return PJ_SUCCESS; @@ -928,16 +927,16 @@ PJ_DEF(pj_status_t) pjsua_conf_get_port_info( pjsua_conf_port_id id, * Add arbitrary media port to PJSUA's conference bridge. */ PJ_DEF(pj_status_t) pjsua_conf_add_port( pj_pool_t *pool, - pjmedia_port *port, - pjsua_conf_port_id *p_id) + pjmedia_port *port, + pjsua_conf_port_id *p_id) { pj_status_t status; status = pjmedia_conf_add_port(pjsua_var.mconf, pool, - port, NULL, (unsigned*)p_id); + port, NULL, (unsigned*)p_id); if (status != PJ_SUCCESS) { - if (p_id) - *p_id = PJSUA_INVALID_ID; + if (p_id) + *p_id = PJSUA_INVALID_ID; } return status; @@ -964,27 +963,27 @@ PJ_DEF(pj_status_t) pjsua_conf_remove_port(pjsua_conf_port_id id) * Establish unidirectional media flow from souce to sink. */ PJ_DEF(pj_status_t) pjsua_conf_connect( pjsua_conf_port_id source, - pjsua_conf_port_id sink) + pjsua_conf_port_id sink) { pjsua_conf_connect_param prm; pjsua_conf_connect_param_default(&prm); return pjsua_conf_connect2(source, sink, &prm); } - + /* * Establish unidirectional media flow from souce to sink, with signal * level adjustment. */ PJ_DEF(pj_status_t) pjsua_conf_connect2( pjsua_conf_port_id source, - pjsua_conf_port_id sink, - const pjsua_conf_connect_param *prm) + pjsua_conf_port_id sink, + const pjsua_conf_connect_param *prm) { pj_status_t status = PJ_SUCCESS; PJ_LOG(4,(THIS_FILE, "%s connect: %d --> %d", - (pjsua_var.is_mswitch ? "Switch" : "Conf"), - source, sink)); + (pjsua_var.is_mswitch ? "Switch" : "Conf"), + source, sink)); PJ_ASSERT_RETURN(source >= 0 && sink >= 0, PJ_EINVAL); @@ -994,8 +993,8 @@ PJ_DEF(pj_status_t) pjsua_conf_connect2( pjsua_conf_port_id source, /* If sound device idle timer is active, cancel it first. */ if (pjsua_var.snd_idle_timer.id) { - pjsip_endpt_cancel_timer(pjsua_var.endpt, &pjsua_var.snd_idle_timer); - pjsua_var.snd_idle_timer.id = PJ_FALSE; + pjsip_endpt_cancel_timer(pjsua_var.endpt, &pjsua_var.snd_idle_timer); + pjsua_var.snd_idle_timer.id = PJ_FALSE; } @@ -1006,124 +1005,124 @@ PJ_DEF(pj_status_t) pjsua_conf_connect2( pjsua_conf_port_id source, * any connection. */ if (pjsua_var.is_mswitch) { - pjmedia_conf_port_info port0_info; - pjmedia_conf_port_info peer_info; - unsigned peer_id; - pj_bool_t need_reopen = PJ_FALSE; - - peer_id = (source!=0)? source : sink; - status = pjmedia_conf_get_port_info(pjsua_var.mconf, peer_id, - &peer_info); - pj_assert(status == PJ_SUCCESS); - - status = pjmedia_conf_get_port_info(pjsua_var.mconf, 0, &port0_info); - pj_assert(status == PJ_SUCCESS); - - /* Check if sound device is instantiated. */ - need_reopen = (pjsua_var.snd_port==NULL && pjsua_var.null_snd==NULL && - !pjsua_var.no_snd); - - /* Check if sound device need to reopen because it needs to modify - * settings to match its peer. Sound device must be idle in this case - * though. - */ - if (!need_reopen && - port0_info.listener_cnt==0 && port0_info.transmitter_cnt==0) - { - need_reopen = (peer_info.format.id != port0_info.format.id || - peer_info.format.det.aud.avg_bps != - port0_info.format.det.aud.avg_bps || - peer_info.clock_rate != port0_info.clock_rate || - peer_info.channel_count!=port0_info.channel_count); - } - - if (need_reopen) { - if (pjsua_var.cap_dev != PJSUA_SND_NULL_DEV) { - pjmedia_snd_port_param param; - - pjmedia_snd_port_param_default(¶m); - param.ec_options = pjsua_var.media_cfg.ec_options; - - /* Create parameter based on peer info */ - status = create_aud_param(¶m.base, pjsua_var.cap_dev, - pjsua_var.play_dev, - peer_info.clock_rate, - peer_info.channel_count, - peer_info.samples_per_frame, - peer_info.bits_per_sample, - PJ_FALSE); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error opening sound device", - status); - goto on_return; - } - - /* And peer format */ - if (peer_info.format.id != PJMEDIA_FORMAT_PCM) { - param.base.flags |= PJMEDIA_AUD_DEV_CAP_EXT_FORMAT; - param.base.ext_fmt = peer_info.format; - } - - param.options = 0; - status = open_snd_dev(¶m); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error opening sound device", - status); - goto on_return; - } - } else { - /* Null-audio */ - status = pjsua_set_snd_dev(pjsua_var.cap_dev, - pjsua_var.play_dev); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error opening sound device", - status); - goto on_return; - } - } - } else if (pjsua_var.no_snd) { - if (!pjsua_var.snd_is_on) { - pjsua_var.snd_is_on = PJ_TRUE; - /* Notify app */ - if (pjsua_var.ua_cfg.cb.on_snd_dev_operation) { - (*pjsua_var.ua_cfg.cb.on_snd_dev_operation)(1); - } - } - } + pjmedia_conf_port_info port0_info; + pjmedia_conf_port_info peer_info; + unsigned peer_id; + pj_bool_t need_reopen = PJ_FALSE; + + peer_id = (source!=0)? source : sink; + status = pjmedia_conf_get_port_info(pjsua_var.mconf, peer_id, + &peer_info); + pj_assert(status == PJ_SUCCESS); + + status = pjmedia_conf_get_port_info(pjsua_var.mconf, 0, &port0_info); + pj_assert(status == PJ_SUCCESS); + + /* Check if sound device is instantiated. */ + need_reopen = (pjsua_var.snd_port==NULL && pjsua_var.null_snd==NULL && + !pjsua_var.no_snd); + + /* Check if sound device need to reopen because it needs to modify + * settings to match its peer. Sound device must be idle in this case + * though. + */ + if (!need_reopen && + port0_info.listener_cnt==0 && port0_info.transmitter_cnt==0) + { + need_reopen = (peer_info.format.id != port0_info.format.id || + peer_info.format.det.aud.avg_bps != + port0_info.format.det.aud.avg_bps || + peer_info.clock_rate != port0_info.clock_rate || + peer_info.channel_count!=port0_info.channel_count); + } + + if (need_reopen) { + if (pjsua_var.cap_dev != PJSUA_SND_NULL_DEV) { + pjmedia_snd_port_param param; + + pjmedia_snd_port_param_default(¶m); + param.ec_options = pjsua_var.media_cfg.ec_options; + + /* Create parameter based on peer info */ + status = create_aud_param(¶m.base, pjsua_var.cap_dev, + pjsua_var.play_dev, + peer_info.clock_rate, + peer_info.channel_count, + peer_info.samples_per_frame, + peer_info.bits_per_sample, + PJ_FALSE); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error opening sound device", + status); + goto on_return; + } + + /* And peer format */ + if (peer_info.format.id != PJMEDIA_FORMAT_PCM) { + param.base.flags |= PJMEDIA_AUD_DEV_CAP_EXT_FORMAT; + param.base.ext_fmt = peer_info.format; + } + + param.options = 0; + status = open_snd_dev(¶m); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error opening sound device", + status); + goto on_return; + } + } else { + /* Null-audio */ + status = pjsua_set_snd_dev(pjsua_var.cap_dev, + pjsua_var.play_dev); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error opening sound device", + status); + goto on_return; + } + } + } else if (pjsua_var.no_snd) { + if (!pjsua_var.snd_is_on) { + pjsua_var.snd_is_on = PJ_TRUE; + /* Notify app */ + if (pjsua_var.ua_cfg.cb.on_snd_dev_operation) { + (*pjsua_var.ua_cfg.cb.on_snd_dev_operation)(1); + } + } + } } else { - /* The bridge version */ - - /* Create sound port if none is instantiated */ - if (pjsua_var.snd_port==NULL && pjsua_var.null_snd==NULL && - !pjsua_var.no_snd) - { - status = pjsua_set_snd_dev(pjsua_var.cap_dev, pjsua_var.play_dev); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error opening sound device", status); - goto on_return; - } - } else if (pjsua_var.no_snd && !pjsua_var.snd_is_on) { - pjsua_var.snd_is_on = PJ_TRUE; - /* Notify app */ - if (pjsua_var.ua_cfg.cb.on_snd_dev_operation) { - (*pjsua_var.ua_cfg.cb.on_snd_dev_operation)(1); - } - } + /* The bridge version */ + + /* Create sound port if none is instantiated */ + if (pjsua_var.snd_port==NULL && pjsua_var.null_snd==NULL && + !pjsua_var.no_snd) + { + status = pjsua_set_snd_dev(pjsua_var.cap_dev, pjsua_var.play_dev); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error opening sound device", status); + goto on_return; + } + } else if (pjsua_var.no_snd && !pjsua_var.snd_is_on) { + pjsua_var.snd_is_on = PJ_TRUE; + /* Notify app */ + if (pjsua_var.ua_cfg.cb.on_snd_dev_operation) { + (*pjsua_var.ua_cfg.cb.on_snd_dev_operation)(1); + } + } } on_return: PJSUA_UNLOCK(); if (status == PJ_SUCCESS) { - pjsua_conf_connect_param cc_param; - - if (!prm) - pjsua_conf_connect_param_default(&cc_param); - else - pj_memcpy(&cc_param, prm, sizeof(cc_param)); - status = pjmedia_conf_connect_port(pjsua_var.mconf, source, sink, - (int)((cc_param.level-1) * 128)); + pjsua_conf_connect_param cc_param; + + if (!prm) + pjsua_conf_connect_param_default(&cc_param); + else + pj_memcpy(&cc_param, prm, sizeof(cc_param)); + status = pjmedia_conf_connect_port(pjsua_var.mconf, source, sink, + (int)((cc_param.level-1) * 128)); } pj_log_pop_indent(); @@ -1135,13 +1134,13 @@ PJ_DEF(pj_status_t) pjsua_conf_connect2( pjsua_conf_port_id source, * Disconnect media flow from the source to destination port. */ PJ_DEF(pj_status_t) pjsua_conf_disconnect( pjsua_conf_port_id source, - pjsua_conf_port_id sink) + pjsua_conf_port_id sink) { pj_status_t status; PJ_LOG(4,(THIS_FILE, "%s disconnect: %d -x- %d", - (pjsua_var.is_mswitch ? "Switch" : "Conf"), - source, sink)); + (pjsua_var.is_mswitch ? "Switch" : "Conf"), + source, sink)); PJ_ASSERT_RETURN(source >= 0 && sink >= 0, PJ_EINVAL); pj_log_push_indent(); @@ -1159,12 +1158,12 @@ PJ_DEF(pj_status_t) pjsua_conf_disconnect( pjsua_conf_port_id source, * specified port by making it louder or quieter. */ PJ_DEF(pj_status_t) pjsua_conf_adjust_tx_level(pjsua_conf_port_id slot, - float level) + float level) { PJ_ASSERT_RETURN(slot >= 0, PJ_EINVAL); return pjmedia_conf_adjust_tx_level(pjsua_var.mconf, slot, - (int)((level-1) * 128)); + (int)((level-1) * 128)); } /* @@ -1172,12 +1171,12 @@ PJ_DEF(pj_status_t) pjsua_conf_adjust_tx_level(pjsua_conf_port_id slot, * the bridge) by making it louder or quieter. */ PJ_DEF(pj_status_t) pjsua_conf_adjust_rx_level(pjsua_conf_port_id slot, - float level) + float level) { PJ_ASSERT_RETURN(slot >= 0, PJ_EINVAL); return pjmedia_conf_adjust_rx_level(pjsua_var.mconf, slot, - (int)((level-1) * 128)); + (int)((level-1) * 128)); } @@ -1185,13 +1184,13 @@ PJ_DEF(pj_status_t) pjsua_conf_adjust_rx_level(pjsua_conf_port_id slot, * Get last signal level transmitted to or received from the specified port. */ PJ_DEF(pj_status_t) pjsua_conf_get_signal_level(pjsua_conf_port_id slot, - unsigned *tx_level, - unsigned *rx_level) + unsigned *tx_level, + unsigned *rx_level) { PJ_ASSERT_RETURN(slot >= 0, PJ_EINVAL); return pjmedia_conf_get_signal_level(pjsua_var.mconf, slot, - tx_level, rx_level); + tx_level, rx_level); } /***************************************************************************** @@ -1203,7 +1202,7 @@ static char* get_basename(const char *path, unsigned len) char *p = ((char*)path) + len; if (len==0) - return p; + return p; for (--p; p!=path && *p!='/' && *p!='\\'; ) --p; @@ -1216,8 +1215,8 @@ static char* get_basename(const char *path, unsigned len) * the conference bridge. */ PJ_DEF(pj_status_t) pjsua_player_create( const pj_str_t *filename, - unsigned options, - pjsua_player_id *p_id) + unsigned options, + pjsua_player_id *p_id) { unsigned slot, file_id; char path[PJ_MAXPATH]; @@ -1226,57 +1225,57 @@ PJ_DEF(pj_status_t) pjsua_player_create( const pj_str_t *filename, pj_status_t status = PJ_SUCCESS; if (pjsua_var.player_cnt >= PJ_ARRAY_SIZE(pjsua_var.player)) - return PJ_ETOOMANY; + return PJ_ETOOMANY; if (filename->slen >= PJ_MAXPATH) - return PJ_ENAMETOOLONG; + return PJ_ENAMETOOLONG; PJ_LOG(4,(THIS_FILE, "Creating file player: %.*s..", - (int)filename->slen, filename->ptr)); + (int)filename->slen, filename->ptr)); pj_log_push_indent(); PJSUA_LOCK(); for (file_id=0; file_idptr, filename->slen); path[filename->slen] = '\0'; pool = pjsua_pool_create(get_basename(path, (unsigned)filename->slen), 1000, - 1000); + 1000); if (!pool) { - status = PJ_ENOMEM; - goto on_error; + status = PJ_ENOMEM; + goto on_error; } status = pjmedia_wav_player_port_create( - pool, path, - pjsua_var.mconf_cfg.samples_per_frame * - 1000 / pjsua_var.media_cfg.channel_count / - pjsua_var.media_cfg.clock_rate, - options, 0, &port); + pool, path, + pjsua_var.mconf_cfg.samples_per_frame * + 1000 / pjsua_var.media_cfg.channel_count / + pjsua_var.media_cfg.clock_rate, + options, 0, &port); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to open file for playback", status); - goto on_error; + pjsua_perror(THIS_FILE, "Unable to open file for playback", status); + goto on_error; } status = pjmedia_conf_add_port(pjsua_var.mconf, pool, - port, filename, &slot); + port, filename, &slot); if (status != PJ_SUCCESS) { - pjmedia_port_destroy(port); - pjsua_perror(THIS_FILE, "Unable to add file to conference bridge", - status); - goto on_error; + pjmedia_port_destroy(port); + pjsua_perror(THIS_FILE, "Unable to add file to conference bridge", + status); + goto on_error; } pjsua_var.player[file_id].type = 0; @@ -1308,10 +1307,10 @@ PJ_DEF(pj_status_t) pjsua_player_create( const pj_str_t *filename, * to the conference bridge. */ PJ_DEF(pj_status_t) pjsua_playlist_create( const pj_str_t file_names[], - unsigned file_count, - const pj_str_t *label, - unsigned options, - pjsua_player_id *p_id) + unsigned file_count, + const pj_str_t *label, + unsigned options, + pjsua_player_id *p_id) { unsigned slot, file_id, ptime; pj_pool_t *pool = NULL; @@ -1319,7 +1318,7 @@ PJ_DEF(pj_status_t) pjsua_playlist_create( const pj_str_t file_names[], pj_status_t status = PJ_SUCCESS; if (pjsua_var.player_cnt >= PJ_ARRAY_SIZE(pjsua_var.player)) - return PJ_ETOOMANY; + return PJ_ETOOMANY; PJ_LOG(4,(THIS_FILE, "Creating playlist with %d file(s)..", file_count)); pj_log_push_indent(); @@ -1327,41 +1326,41 @@ PJ_DEF(pj_status_t) pjsua_playlist_create( const pj_str_t file_names[], PJSUA_LOCK(); for (file_id=0; file_idinfo.name, &slot); + port, &port->info.name, &slot); if (status != PJ_SUCCESS) { - pjmedia_port_destroy(port); - pjsua_perror(THIS_FILE, "Unable to add port", status); - goto on_error; + pjmedia_port_destroy(port); + pjsua_perror(THIS_FILE, "Unable to add port", status); + goto on_error; } pjsua_var.player[file_id].type = 1; @@ -1405,7 +1404,7 @@ PJ_DEF(pjsua_conf_port_id) pjsua_player_get_conf_port(pjsua_player_id id) * Get the media port for the player. */ PJ_DEF(pj_status_t) pjsua_player_get_port( pjsua_player_id id, - pjmedia_port **p_port) + pjmedia_port **p_port) { PJ_ASSERT_RETURN(id>=0&&id<(int)PJ_ARRAY_SIZE(pjsua_var.player),PJ_EINVAL); PJ_ASSERT_RETURN(pjsua_var.player[id].port != NULL, PJ_EINVAL); @@ -1446,11 +1445,11 @@ PJ_DEF(pj_ssize_t) pjsua_player_get_pos( pjsua_player_id id ) pos_bytes = pjmedia_wav_player_port_get_pos(pjsua_var.player[id].port); if (pos_bytes < 0) - return pos_bytes; + return pos_bytes; status = pjmedia_wav_player_get_info(pjsua_var.player[id].port, &info); if (status != PJ_SUCCESS) - return -status; + return -status; return pos_bytes / (info.payload_bits_per_sample / 8); } @@ -1459,7 +1458,7 @@ PJ_DEF(pj_ssize_t) pjsua_player_get_pos( pjsua_player_id id ) * Set playback position. */ PJ_DEF(pj_status_t) pjsua_player_set_pos( pjsua_player_id id, - pj_uint32_t samples) + pj_uint32_t samples) { pjmedia_wav_player_info info; pj_uint32_t pos_bytes; @@ -1471,7 +1470,7 @@ PJ_DEF(pj_status_t) pjsua_player_set_pos( pjsua_player_id id, status = pjmedia_wav_player_get_info(pjsua_var.player[id].port, &info); if (status != PJ_SUCCESS) - return status; + return status; pos_bytes = samples * (info.payload_bits_per_sample / 8); return pjmedia_wav_player_port_set_pos(pjsua_var.player[id].port, @@ -1494,13 +1493,13 @@ PJ_DEF(pj_status_t) pjsua_player_destroy(pjsua_player_id id) PJSUA_LOCK(); if (pjsua_var.player[id].port) { - pjsua_conf_remove_port(pjsua_var.player[id].slot); - pjmedia_port_destroy(pjsua_var.player[id].port); - pjsua_var.player[id].port = NULL; - pjsua_var.player[id].slot = 0xFFFF; - pj_pool_release(pjsua_var.player[id].pool); - pjsua_var.player[id].pool = NULL; - pjsua_var.player_cnt--; + pjsua_conf_remove_port(pjsua_var.player[id].slot); + pjmedia_port_destroy(pjsua_var.player[id].port); + pjsua_var.player[id].port = NULL; + pjsua_var.player[id].slot = 0xFFFF; + pj_pool_release(pjsua_var.player[id].pool); + pjsua_var.player[id].pool = NULL; + pjsua_var.player_cnt--; } PJSUA_UNLOCK(); @@ -1519,17 +1518,17 @@ PJ_DEF(pj_status_t) pjsua_player_destroy(pjsua_player_id id) * the conference bridge. */ PJ_DEF(pj_status_t) pjsua_recorder_create( const pj_str_t *filename, - unsigned enc_type, - void *enc_param, - pj_ssize_t max_size, - unsigned options, - pjsua_recorder_id *p_id) + unsigned enc_type, + void *enc_param, + pj_ssize_t max_size, + unsigned options, + pjsua_recorder_id *p_id) { enum Format { - FMT_UNKNOWN, - FMT_WAV, - FMT_MP3, + FMT_UNKNOWN, + FMT_WAV, + FMT_MP3, }; unsigned slot, file_id; char path[PJ_MAXPATH]; @@ -1549,17 +1548,17 @@ PJ_DEF(pj_status_t) pjsua_recorder_create( const pj_str_t *filename, PJ_ASSERT_RETURN(enc_type == 0, PJ_EINVAL); if (filename->slen >= PJ_MAXPATH) - return PJ_ENAMETOOLONG; + return PJ_ENAMETOOLONG; if (filename->slen < 4) - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; PJ_LOG(4,(THIS_FILE, "Creating recorder %.*s..", - (int)filename->slen, filename->ptr)); + (int)filename->slen, filename->ptr)); pj_log_push_indent(); if (pjsua_var.rec_cnt >= PJ_ARRAY_SIZE(pjsua_var.recorder)) { - pj_log_pop_indent(); - return PJ_ETOOMANY; + pj_log_pop_indent(); + return PJ_ETOOMANY; } /* Determine the file format */ @@ -1567,64 +1566,64 @@ PJ_DEF(pj_status_t) pjsua_recorder_create( const pj_str_t *filename, ext.slen = 4; if (pj_stricmp2(&ext, ".wav") == 0) - file_format = FMT_WAV; + file_format = FMT_WAV; else if (pj_stricmp2(&ext, ".mp3") == 0) - file_format = FMT_MP3; + file_format = FMT_MP3; else { - PJ_LOG(1,(THIS_FILE, "pjsua_recorder_create() error: unable to " - "determine file format for %.*s", - (int)filename->slen, filename->ptr)); - pj_log_pop_indent(); - return PJ_ENOTSUP; + PJ_LOG(1,(THIS_FILE, "pjsua_recorder_create() error: unable to " + "determine file format for %.*s", + (int)filename->slen, filename->ptr)); + pj_log_pop_indent(); + return PJ_ENOTSUP; } PJSUA_LOCK(); for (file_id=0; file_idptr, filename->slen); path[filename->slen] = '\0'; pool = pjsua_pool_create(get_basename(path, (unsigned)filename->slen), 1000, - 1000); + 1000); if (!pool) { - status = PJ_ENOMEM; - goto on_return; + status = PJ_ENOMEM; + goto on_return; } if (file_format == FMT_WAV) { - status = pjmedia_wav_writer_port_create(pool, path, - pjsua_var.media_cfg.clock_rate, - pjsua_var.mconf_cfg.channel_count, - pjsua_var.mconf_cfg.samples_per_frame, - pjsua_var.mconf_cfg.bits_per_sample, - options, 0, &port); + status = pjmedia_wav_writer_port_create(pool, path, + pjsua_var.media_cfg.clock_rate, + pjsua_var.mconf_cfg.channel_count, + pjsua_var.mconf_cfg.samples_per_frame, + pjsua_var.mconf_cfg.bits_per_sample, + options, 0, &port); } else { - PJ_UNUSED_ARG(enc_param); - port = NULL; - status = PJ_ENOTSUP; + PJ_UNUSED_ARG(enc_param); + port = NULL; + status = PJ_ENOTSUP; } if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to open file for recording", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to open file for recording", status); + goto on_return; } status = pjmedia_conf_add_port(pjsua_var.mconf, pool, - port, filename, &slot); + port, filename, &slot); if (status != PJ_SUCCESS) { - pjmedia_port_destroy(port); - goto on_return; + pjmedia_port_destroy(port); + goto on_return; } pjsua_var.recorder[file_id].port = port; @@ -1656,7 +1655,7 @@ PJ_DEF(pj_status_t) pjsua_recorder_create( const pj_str_t *filename, PJ_DEF(pjsua_conf_port_id) pjsua_recorder_get_conf_port(pjsua_recorder_id id) { PJ_ASSERT_RETURN(id>=0 && id<(int)PJ_ARRAY_SIZE(pjsua_var.recorder), - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(pjsua_var.recorder[id].port != NULL, PJ_EINVAL); return pjsua_var.recorder[id].slot; @@ -1666,10 +1665,10 @@ PJ_DEF(pjsua_conf_port_id) pjsua_recorder_get_conf_port(pjsua_recorder_id id) * Get the media port for the recorder. */ PJ_DEF(pj_status_t) pjsua_recorder_get_port( pjsua_recorder_id id, - pjmedia_port **p_port) + pjmedia_port **p_port) { PJ_ASSERT_RETURN(id>=0 && id<(int)PJ_ARRAY_SIZE(pjsua_var.recorder), - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(pjsua_var.recorder[id].port != NULL, PJ_EINVAL); PJ_ASSERT_RETURN(p_port != NULL, PJ_EINVAL); @@ -1683,7 +1682,7 @@ PJ_DEF(pj_status_t) pjsua_recorder_get_port( pjsua_recorder_id id, PJ_DEF(pj_status_t) pjsua_recorder_destroy(pjsua_recorder_id id) { PJ_ASSERT_RETURN(id>=0 && id<(int)PJ_ARRAY_SIZE(pjsua_var.recorder), - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(pjsua_var.recorder[id].port != NULL, PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Destroying recorder %d..", id)); @@ -1692,13 +1691,13 @@ PJ_DEF(pj_status_t) pjsua_recorder_destroy(pjsua_recorder_id id) PJSUA_LOCK(); if (pjsua_var.recorder[id].port) { - pjsua_conf_remove_port(pjsua_var.recorder[id].slot); - pjmedia_port_destroy(pjsua_var.recorder[id].port); - pjsua_var.recorder[id].port = NULL; - pjsua_var.recorder[id].slot = 0xFFFF; - pj_pool_release(pjsua_var.recorder[id].pool); - pjsua_var.recorder[id].pool = NULL; - pjsua_var.rec_cnt--; + pjsua_conf_remove_port(pjsua_var.recorder[id].slot); + pjmedia_port_destroy(pjsua_var.recorder[id].port); + pjsua_var.recorder[id].port = NULL; + pjsua_var.recorder[id].slot = 0xFFFF; + pj_pool_release(pjsua_var.recorder[id].pool); + pjsua_var.recorder[id].pool = NULL; + pjsua_var.rec_cnt--; } PJSUA_UNLOCK(); @@ -1717,7 +1716,7 @@ PJ_DEF(pj_status_t) pjsua_recorder_destroy(pjsua_recorder_id id) */ PJ_DEF(pj_status_t) pjsua_enum_aud_devs( pjmedia_aud_dev_info info[], - unsigned *count) + unsigned *count) { unsigned i, dev_count; @@ -1726,11 +1725,11 @@ PJ_DEF(pj_status_t) pjsua_enum_aud_devs( pjmedia_aud_dev_info info[], if (dev_count > *count) dev_count = *count; for (i=0; idir = PJMEDIA_DIR_CAPTURE_PLAYBACK; param->rec_id = capture_dev; @@ -1803,43 +1802,43 @@ static pj_status_t create_aud_param(pjmedia_aud_param *param, param->bits_per_sample = bits_per_sample; if (use_default_settings) { - /* Reset the sound device settings. */ - pjsua_var.aud_open_cnt = 0; + /* Reset the sound device settings. */ + pjsua_var.aud_open_cnt = 0; } else { - /* Update the setting with user preference */ -#define update_param(cap, field) \ - if (pjsua_var.aud_param.flags & cap) { \ - param->flags |= cap; \ - param->field = pjsua_var.aud_param.field; \ - } - update_param(PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING, input_vol); - update_param(PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, output_vol); - update_param(PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE, input_route); - update_param(PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, output_route); + /* Update the setting with user preference */ +#define update_param(cap, field) \ + if (pjsua_var.aud_param.flags & cap) { \ + param->flags |= cap; \ + param->field = pjsua_var.aud_param.field; \ + } + update_param(PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING, input_vol); + update_param(PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, output_vol); + update_param(PJMEDIA_AUD_DEV_CAP_INPUT_ROUTE, input_route); + update_param(PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, output_route); #undef update_param } /* Latency settings */ param->flags |= (PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | - PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY); + PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY); param->input_latency_ms = pjsua_var.media_cfg.snd_rec_latency; param->output_latency_ms = pjsua_var.media_cfg.snd_play_latency; /* EC settings */ if (pjsua_var.media_cfg.ec_tail_len) { - param->flags |= (PJMEDIA_AUD_DEV_CAP_EC | PJMEDIA_AUD_DEV_CAP_EC_TAIL); - param->ec_enabled = PJ_TRUE; - param->ec_tail_ms = pjsua_var.media_cfg.ec_tail_len; + param->flags |= (PJMEDIA_AUD_DEV_CAP_EC | PJMEDIA_AUD_DEV_CAP_EC_TAIL); + param->ec_enabled = PJ_TRUE; + param->ec_tail_ms = pjsua_var.media_cfg.ec_tail_len; } else { - param->flags &= ~(PJMEDIA_AUD_DEV_CAP_EC|PJMEDIA_AUD_DEV_CAP_EC_TAIL); + param->flags &= ~(PJMEDIA_AUD_DEV_CAP_EC|PJMEDIA_AUD_DEV_CAP_EC_TAIL); } /* VAD settings */ if (pjsua_var.media_cfg.no_vad) { - param->flags &= ~PJMEDIA_AUD_DEV_CAP_VAD; + param->flags &= ~PJMEDIA_AUD_DEV_CAP_VAD; } else { - param->flags |= PJMEDIA_AUD_DEV_CAP_VAD; - param->vad_enabled = PJ_TRUE; + param->flags |= PJMEDIA_AUD_DEV_CAP_VAD; + param->vad_enabled = PJ_TRUE; } return PJ_SUCCESS; @@ -1861,17 +1860,17 @@ static pj_status_t update_initial_aud_param() status = pjmedia_aud_stream_get_param(strm, ¶m); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error audio stream " - "device parameters", status); - return status; + pjsua_perror(THIS_FILE, "Error audio stream " + "device parameters", status); + return status; } pjsua_var.aud_param.flags = 0; #define update_saved_param(cap, field) \ - if (param.flags & cap) { \ - pjsua_var.aud_param.flags |= cap; \ - pjsua_var.aud_param.field = param.field; \ - } + if (param.flags & cap) { \ + pjsua_var.aud_param.flags |= cap; \ + pjsua_var.aud_param.field = param.field; \ + } update_saved_param(PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING, input_vol); update_saved_param(PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, output_vol); @@ -1888,7 +1887,7 @@ static const char *get_fmt_name(pj_uint32_t id) static char name[8]; if (id == PJMEDIA_FORMAT_L16) - return "PCM"; + return "PCM"; pj_memcpy(name, &id, 4); name[4] = '\0'; return name; @@ -1919,9 +1918,9 @@ static pj_status_t open_snd_dev(pjmedia_snd_port_param *param) /* Check if NULL sound device is used */ if (PJSUA_SND_NULL_DEV==param->base.rec_id || - PJSUA_SND_NULL_DEV==param->base.play_id) + PJSUA_SND_NULL_DEV==param->base.play_id) { - return pjsua_set_null_snd_dev(); + return pjsua_set_null_snd_dev(); } /* Close existing sound port */ @@ -1933,7 +1932,7 @@ static pj_status_t open_snd_dev(pjmedia_snd_port_param *param) /* Notify app */ if (pjsua_var.ua_cfg.cb.on_snd_dev_operation) { - (*pjsua_var.ua_cfg.cb.on_snd_dev_operation)(1); + (*pjsua_var.ua_cfg.cb.on_snd_dev_operation)(1); } /* Create memory pool for sound device. */ @@ -1942,41 +1941,41 @@ static pj_status_t open_snd_dev(pjmedia_snd_port_param *param) /* Setup preview callbacks, if configured */ if (pjsua_var.media_cfg.on_aud_prev_play_frame) - param->on_play_frame = &on_aud_prev_play_frame; + param->on_play_frame = &on_aud_prev_play_frame; if (pjsua_var.media_cfg.on_aud_prev_rec_frame) - param->on_rec_frame = &on_aud_prev_rec_frame; + param->on_rec_frame = &on_aud_prev_rec_frame; PJ_LOG(4,(THIS_FILE, "Opening sound device (%s) %s@%d/%d/%dms", - speaker_only?"speaker only":"speaker + mic", - get_fmt_name(param->base.ext_fmt.id), - param->base.clock_rate, param->base.channel_count, - param->base.samples_per_frame / param->base.channel_count * - 1000 / param->base.clock_rate)); + speaker_only?"speaker only":"speaker + mic", + get_fmt_name(param->base.ext_fmt.id), + param->base.clock_rate, param->base.channel_count, + param->base.samples_per_frame / param->base.channel_count * + 1000 / param->base.clock_rate)); pj_log_push_indent(); if (speaker_only) { - pjmedia_snd_port_param cp_param; - int dev_id = param->base.play_id; + pjmedia_snd_port_param cp_param; + int dev_id = param->base.play_id; - /* Normalize dev_id */ - if (dev_id < 0) - dev_id = PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV; + /* Normalize dev_id */ + if (dev_id < 0) + dev_id = PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV; - pjmedia_snd_port_param_default(&cp_param); - pj_memcpy(&cp_param.base, ¶m->base, sizeof(cp_param.base)); - cp_param.base.dir = PJMEDIA_DIR_PLAYBACK; - cp_param.base.play_id = dev_id; + pjmedia_snd_port_param_default(&cp_param); + pj_memcpy(&cp_param.base, ¶m->base, sizeof(cp_param.base)); + cp_param.base.dir = PJMEDIA_DIR_PLAYBACK; + cp_param.base.play_id = dev_id; - status = pjmedia_snd_port_create2(pjsua_var.snd_pool, &cp_param, - &pjsua_var.snd_port); + status = pjmedia_snd_port_create2(pjsua_var.snd_pool, &cp_param, + &pjsua_var.snd_port); } else { - status = pjmedia_snd_port_create2(pjsua_var.snd_pool, - param, &pjsua_var.snd_port); + status = pjmedia_snd_port_create2(pjsua_var.snd_pool, + param, &pjsua_var.snd_port); } if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Get the port0 of the conference bridge. */ conf_port = pjmedia_conf_get_master_port(pjsua_var.mconf); @@ -1986,106 +1985,106 @@ static pj_status_t open_snd_dev(pjmedia_snd_port_param *param) * clock rate is different than the sound device's clock rate. */ if (!pjsua_var.is_mswitch && - param->base.ext_fmt.id == PJMEDIA_FORMAT_PCM && - PJMEDIA_PIA_SRATE(&conf_port->info) != param->base.clock_rate) + param->base.ext_fmt.id == PJMEDIA_FORMAT_PCM && + PJMEDIA_PIA_SRATE(&conf_port->info) != param->base.clock_rate) { - pjmedia_port *resample_port; - unsigned resample_opt = 0; - - if (pjsua_var.media_cfg.quality >= 3 && - pjsua_var.media_cfg.quality <= 4) - { - resample_opt |= PJMEDIA_RESAMPLE_USE_SMALL_FILTER; - } - else if (pjsua_var.media_cfg.quality < 3) { - resample_opt |= PJMEDIA_RESAMPLE_USE_LINEAR; - } - - status = pjmedia_resample_port_create(pjsua_var.snd_pool, - conf_port, - param->base.clock_rate, - resample_opt, - &resample_port); - if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(4, (THIS_FILE, - "Error creating resample port: %s", - errmsg)); - close_snd_dev(); - goto on_error; - } - - conf_port = resample_port; + pjmedia_port *resample_port; + unsigned resample_opt = 0; + + if (pjsua_var.media_cfg.quality >= 3 && + pjsua_var.media_cfg.quality <= 4) + { + resample_opt |= PJMEDIA_RESAMPLE_USE_SMALL_FILTER; + } + else if (pjsua_var.media_cfg.quality < 3) { + resample_opt |= PJMEDIA_RESAMPLE_USE_LINEAR; + } + + status = pjmedia_resample_port_create(pjsua_var.snd_pool, + conf_port, + param->base.clock_rate, + resample_opt, + &resample_port); + if (status != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(4, (THIS_FILE, + "Error creating resample port: %s", + errmsg)); + close_snd_dev(); + goto on_error; + } + + conf_port = resample_port; } /* Otherwise for audio switchboard, the switch's port0 setting is * derived from the sound device setting, so update the setting. */ if (pjsua_var.is_mswitch) { - if (param->base.flags & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT) { - conf_port->info.fmt = param->base.ext_fmt; - } else { - unsigned bps, ptime_usec; - bps = param->base.clock_rate * param->base.bits_per_sample; - ptime_usec = param->base.samples_per_frame / - param->base.channel_count * 1000000 / - param->base.clock_rate; - pjmedia_format_init_audio(&conf_port->info.fmt, - PJMEDIA_FORMAT_PCM, - param->base.clock_rate, - param->base.channel_count, - param->base.bits_per_sample, - ptime_usec, - bps, bps); - } + if (param->base.flags & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT) { + conf_port->info.fmt = param->base.ext_fmt; + } else { + unsigned bps, ptime_usec; + bps = param->base.clock_rate * param->base.bits_per_sample; + ptime_usec = param->base.samples_per_frame / + param->base.channel_count * 1000000 / + param->base.clock_rate; + pjmedia_format_init_audio(&conf_port->info.fmt, + PJMEDIA_FORMAT_PCM, + param->base.clock_rate, + param->base.channel_count, + param->base.bits_per_sample, + ptime_usec, + bps, bps); + } } /* Connect sound port to the bridge */ status = pjmedia_snd_port_connect(pjsua_var.snd_port, - conf_port ); + conf_port ); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to connect conference port to " - "sound device", status); - pjmedia_snd_port_destroy(pjsua_var.snd_port); - pjsua_var.snd_port = NULL; - goto on_error; + pjsua_perror(THIS_FILE, "Unable to connect conference port to " + "sound device", status); + pjmedia_snd_port_destroy(pjsua_var.snd_port); + pjsua_var.snd_port = NULL; + goto on_error; } /* Update sound device name. */ if (!speaker_only) { - pjmedia_aud_dev_info rec_info; - pjmedia_aud_stream *strm; - pjmedia_aud_param si; + pjmedia_aud_dev_info rec_info; + pjmedia_aud_stream *strm; + pjmedia_aud_param si; pj_str_t tmp; - strm = pjmedia_snd_port_get_snd_stream(pjsua_var.snd_port); - status = pjmedia_aud_stream_get_param(strm, &si); - if (status == PJ_SUCCESS) - status = pjmedia_aud_dev_get_info(si.rec_id, &rec_info); - - if (status==PJ_SUCCESS) { - if (param->base.clock_rate != pjsua_var.media_cfg.clock_rate) { - char tmp_buf[128]; - int tmp_buf_len; - - tmp_buf_len = pj_ansi_snprintf(tmp_buf, sizeof(tmp_buf), - "%s (%dKHz)", - rec_info.name, - param->base.clock_rate/1000); - if (tmp_buf_len < 1 || tmp_buf_len >= (int)sizeof(tmp_buf)) - tmp_buf_len = sizeof(tmp_buf) - 1; - pj_strset(&tmp, tmp_buf, tmp_buf_len); - pjmedia_conf_set_port0_name(pjsua_var.mconf, &tmp); - } else { - pjmedia_conf_set_port0_name(pjsua_var.mconf, - pj_cstr(&tmp, rec_info.name)); - } - } - - /* Any error is not major, let it through */ - status = PJ_SUCCESS; + strm = pjmedia_snd_port_get_snd_stream(pjsua_var.snd_port); + status = pjmedia_aud_stream_get_param(strm, &si); + if (status == PJ_SUCCESS) + status = pjmedia_aud_dev_get_info(si.rec_id, &rec_info); + + if (status==PJ_SUCCESS) { + if (param->base.clock_rate != pjsua_var.media_cfg.clock_rate) { + char tmp_buf[128]; + int tmp_buf_len; + + tmp_buf_len = pj_ansi_snprintf(tmp_buf, sizeof(tmp_buf), + "%s (%dKHz)", + rec_info.name, + param->base.clock_rate/1000); + if (tmp_buf_len < 1 || tmp_buf_len >= (int)sizeof(tmp_buf)) + tmp_buf_len = sizeof(tmp_buf) - 1; + pj_strset(&tmp, tmp_buf, tmp_buf_len); + pjmedia_conf_set_port0_name(pjsua_var.mconf, &tmp); + } else { + pjmedia_conf_set_port0_name(pjsua_var.mconf, + pj_cstr(&tmp, rec_info.name)); + } + } + + /* Any error is not major, let it through */ + status = PJ_SUCCESS; } /* If this is the first time the audio device is open, retrieve some @@ -2093,15 +2092,15 @@ static pj_status_t open_snd_dev(pjmedia_snd_port_param *param) * pjsua_snd_get_setting() work. */ if (pjsua_var.aud_open_cnt == 0) { - update_initial_aud_param(); - ++pjsua_var.aud_open_cnt; + update_initial_aud_param(); + ++pjsua_var.aud_open_cnt; } pjsua_var.snd_is_on = PJ_TRUE; /* Subscribe to audio device events */ pjmedia_event_subscribe(NULL, &on_media_event, NULL, - pjmedia_snd_port_get_snd_stream(pjsua_var.snd_port)); + pjmedia_snd_port_get_snd_stream(pjsua_var.snd_port)); pj_log_pop_indent(); return PJ_SUCCESS; @@ -2119,47 +2118,47 @@ static void close_snd_dev(void) /* Notify app */ if (pjsua_var.snd_is_on && pjsua_var.ua_cfg.cb.on_snd_dev_operation) { - (*pjsua_var.ua_cfg.cb.on_snd_dev_operation)(0); + (*pjsua_var.ua_cfg.cb.on_snd_dev_operation)(0); } /* Close sound device */ if (pjsua_var.snd_port) { - pjmedia_aud_dev_info cap_info, play_info; - pjmedia_aud_stream *strm; - pjmedia_aud_param param; + pjmedia_aud_dev_info cap_info, play_info; + pjmedia_aud_stream *strm; + pjmedia_aud_param param; - strm = pjmedia_snd_port_get_snd_stream(pjsua_var.snd_port); - pjmedia_aud_stream_get_param(strm, ¶m); + strm = pjmedia_snd_port_get_snd_stream(pjsua_var.snd_port); + pjmedia_aud_stream_get_param(strm, ¶m); - if (param.rec_id == PJSUA_SND_NO_DEV || - pjmedia_aud_dev_get_info(param.rec_id, &cap_info) != PJ_SUCCESS) - { - cap_info.name[0] = '\0'; - } - if (pjmedia_aud_dev_get_info(param.play_id, &play_info) != PJ_SUCCESS) - play_info.name[0] = '\0'; + if (param.rec_id == PJSUA_SND_NO_DEV || + pjmedia_aud_dev_get_info(param.rec_id, &cap_info) != PJ_SUCCESS) + { + cap_info.name[0] = '\0'; + } + if (pjmedia_aud_dev_get_info(param.play_id, &play_info) != PJ_SUCCESS) + play_info.name[0] = '\0'; - PJ_LOG(4,(THIS_FILE, "Closing %s sound playback device and " - "%s sound capture device", - play_info.name, cap_info.name)); + PJ_LOG(4,(THIS_FILE, "Closing %s sound playback device and " + "%s sound capture device", + play_info.name, cap_info.name)); - /* Unsubscribe from audio device events */ - pjmedia_event_unsubscribe(NULL, &on_media_event, NULL, strm); + /* Unsubscribe from audio device events */ + pjmedia_event_unsubscribe(NULL, &on_media_event, NULL, strm); - pjmedia_snd_port_disconnect(pjsua_var.snd_port); - pjmedia_snd_port_destroy(pjsua_var.snd_port); - pjsua_var.snd_port = NULL; + pjmedia_snd_port_disconnect(pjsua_var.snd_port); + pjmedia_snd_port_destroy(pjsua_var.snd_port); + pjsua_var.snd_port = NULL; } /* Close null sound device */ if (pjsua_var.null_snd) { - PJ_LOG(4,(THIS_FILE, "Closing null sound device..")); - pjmedia_master_port_destroy(pjsua_var.null_snd, PJ_FALSE); - pjsua_var.null_snd = NULL; + PJ_LOG(4,(THIS_FILE, "Closing null sound device..")); + pjmedia_master_port_destroy(pjsua_var.null_snd, PJ_FALSE); + pjsua_var.null_snd = NULL; } if (pjsua_var.snd_pool) - pj_pool_release(pjsua_var.snd_pool); + pj_pool_release(pjsua_var.snd_pool); pjsua_var.snd_pool = NULL; pjsua_var.snd_is_on = PJ_FALSE; @@ -2169,7 +2168,7 @@ static void close_snd_dev(void) PJ_DEF(pj_status_t) pjsua_set_snd_dev(int capture_dev, - int playback_dev) + int playback_dev) { pjsua_snd_dev_param param; @@ -2214,9 +2213,9 @@ PJ_DEF(pj_status_t) pjsua_set_snd_dev2(const pjsua_snd_dev_param *snd_param) PJ_ASSERT_RETURN(snd_param, PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Set sound device: capture=%d, playback=%d, mode=%d, " - "use_default_settings=%d", - snd_param->capture_dev, snd_param->playback_dev, - snd_param->mode, snd_param->use_default_settings)); + "use_default_settings=%d", + snd_param->capture_dev, snd_param->playback_dev, + snd_param->mode, snd_param->use_default_settings)); pj_log_push_indent(); @@ -2224,43 +2223,43 @@ PJ_DEF(pj_status_t) pjsua_set_snd_dev2(const pjsua_snd_dev_param *snd_param) /* Check if there are no changes in sound device settings */ if (pjsua_var.cap_dev == snd_param->capture_dev && - pjsua_var.play_dev == snd_param->playback_dev && - pjsua_var.snd_mode == snd_param->mode) + pjsua_var.play_dev == snd_param->playback_dev && + pjsua_var.snd_mode == snd_param->mode) { - /* If sound device is already opened, just print log and return. - * Also if PJSUA_SND_DEV_NO_IMMEDIATE_OPEN is set. - */ - if (pjsua_var.snd_is_on || (snd_param->mode & - PJSUA_SND_DEV_NO_IMMEDIATE_OPEN)) - { - PJ_LOG(4,(THIS_FILE,"No changes in capture and playback devices")); - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return PJ_SUCCESS; - } + /* If sound device is already opened, just print log and return. + * Also if PJSUA_SND_DEV_NO_IMMEDIATE_OPEN is set. + */ + if (pjsua_var.snd_is_on || (snd_param->mode & + PJSUA_SND_DEV_NO_IMMEDIATE_OPEN)) + { + PJ_LOG(4,(THIS_FILE,"No changes in capture and playback devices")); + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return PJ_SUCCESS; + } } /* No sound */ if (snd_param->capture_dev == PJSUA_SND_NO_DEV && - snd_param->playback_dev == PJSUA_SND_NO_DEV) + snd_param->playback_dev == PJSUA_SND_NO_DEV) { - PJSUA_UNLOCK(); - PJ_LOG(4, (THIS_FILE, "No sound device, mode setting is ignored")); - if (!pjsua_var.no_snd) - pjsua_set_no_snd_dev(); - pj_log_pop_indent(); - return status; + PJSUA_UNLOCK(); + PJ_LOG(4, (THIS_FILE, "No sound device, mode setting is ignored")); + if (!pjsua_var.no_snd) + pjsua_set_no_snd_dev(); + pj_log_pop_indent(); + return status; } /* Null-sound */ if (snd_param->capture_dev == PJSUA_SND_NULL_DEV && - snd_param->playback_dev == PJSUA_SND_NULL_DEV) + snd_param->playback_dev == PJSUA_SND_NULL_DEV) { - PJSUA_UNLOCK(); - PJ_LOG(4, (THIS_FILE, "Null sound device, mode setting is ignored")); - status = pjsua_set_null_snd_dev(); - pj_log_pop_indent(); - return status; + PJSUA_UNLOCK(); + PJ_LOG(4, (THIS_FILE, "Null sound device, mode setting is ignored")); + status = pjsua_set_null_snd_dev(); + pj_log_pop_indent(); + return status; } pjsua_var.snd_mode = snd_param->mode; @@ -2269,61 +2268,61 @@ PJ_DEF(pj_status_t) pjsua_set_snd_dev2(const pjsua_snd_dev_param *snd_param) * audio is off. */ if (!pjsua_var.snd_is_on && - (snd_param->mode & PJSUA_SND_DEV_NO_IMMEDIATE_OPEN)) + (snd_param->mode & PJSUA_SND_DEV_NO_IMMEDIATE_OPEN)) { - pjsua_var.cap_dev = snd_param->capture_dev; - pjsua_var.play_dev = snd_param->playback_dev; - pjsua_var.no_snd = PJ_FALSE; + pjsua_var.cap_dev = snd_param->capture_dev; + pjsua_var.play_dev = snd_param->playback_dev; + pjsua_var.no_snd = PJ_FALSE; - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return PJ_SUCCESS; + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return PJ_SUCCESS; } /* Set default clock rate */ alt_cr[0] = pjsua_var.media_cfg.snd_clock_rate; if (alt_cr[0] == 0) - alt_cr[0] = pjsua_var.media_cfg.clock_rate; + alt_cr[0] = pjsua_var.media_cfg.clock_rate; /* Allow retrying of different clock rate if we're using conference * bridge (meaning audio format is always PCM), otherwise lock on * to one clock rate. */ if (pjsua_var.is_mswitch) { - alt_cr_cnt = 1; + alt_cr_cnt = 1; } else { - alt_cr_cnt = PJ_ARRAY_SIZE(alt_cr); + alt_cr_cnt = PJ_ARRAY_SIZE(alt_cr); } /* Attempts to open the sound device with different clock rates */ for (i=0; icapture_dev, - snd_param->playback_dev, - alt_cr[i], pjsua_var.media_cfg.channel_count, - samples_per_frame, 16, - snd_param->use_default_settings); - if (status != PJ_SUCCESS) - goto on_error; - - /* Open! */ - param.options = 0; - status = open_snd_dev(¶m); - if (status == PJ_SUCCESS) - break; + pjmedia_snd_port_param param; + unsigned samples_per_frame; + + /* Create the default audio param */ + samples_per_frame = alt_cr[i] * + pjsua_var.media_cfg.audio_frame_ptime * + pjsua_var.media_cfg.channel_count / 1000; + pjmedia_snd_port_param_default(¶m); + param.ec_options = pjsua_var.media_cfg.ec_options; + status = create_aud_param(¶m.base, snd_param->capture_dev, + snd_param->playback_dev, + alt_cr[i], pjsua_var.media_cfg.channel_count, + samples_per_frame, 16, + snd_param->use_default_settings); + if (status != PJ_SUCCESS) + goto on_error; + + /* Open! */ + param.options = 0; + status = open_snd_dev(¶m); + if (status == PJ_SUCCESS) + break; } if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to open sound device", status); - goto on_error; + pjsua_perror(THIS_FILE, "Unable to open sound device", status); + goto on_error; } pjsua_var.no_snd = PJ_FALSE; @@ -2347,15 +2346,15 @@ PJ_DEF(pj_status_t) pjsua_set_snd_dev2(const pjsua_snd_dev_param *snd_param) * the function returns PJ_SUCCESS with -1 as device IDs. */ PJ_DEF(pj_status_t) pjsua_get_snd_dev(int *capture_dev, - int *playback_dev) + int *playback_dev) { PJSUA_LOCK(); if (capture_dev) { - *capture_dev = pjsua_var.cap_dev; + *capture_dev = pjsua_var.cap_dev; } if (playback_dev) { - *playback_dev = pjsua_var.play_dev; + *playback_dev = pjsua_var.play_dev; } PJSUA_UNLOCK(); @@ -2384,7 +2383,7 @@ PJ_DEF(pj_status_t) pjsua_set_null_snd_dev(void) /* Notify app */ if (pjsua_var.ua_cfg.cb.on_snd_dev_operation) { - (*pjsua_var.ua_cfg.cb.on_snd_dev_operation)(1); + (*pjsua_var.ua_cfg.cb.on_snd_dev_operation)(1); } /* Create memory pool for sound device. */ @@ -2401,13 +2400,13 @@ PJ_DEF(pj_status_t) pjsua_set_null_snd_dev(void) * a null port. */ status = pjmedia_master_port_create(pjsua_var.snd_pool, pjsua_var.null_port, - conf_port, 0, &pjsua_var.null_snd); + conf_port, 0, &pjsua_var.null_snd); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create null sound device", - status); - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return status; + pjsua_perror(THIS_FILE, "Unable to create null sound device", + status); + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return status; } /* Start the master port */ @@ -2456,8 +2455,8 @@ PJ_DEF(pj_status_t) pjsua_set_ec(unsigned tail_ms, unsigned options) pjsua_var.media_cfg.ec_options = options; if (pjsua_var.snd_port) - status = pjmedia_snd_port_set_ec(pjsua_var.snd_port, pjsua_var.pool, - tail_ms, options); + status = pjmedia_snd_port_set_ec(pjsua_var.snd_port, pjsua_var.pool, + tail_ms, options); PJSUA_UNLOCK(); return status; @@ -2480,9 +2479,9 @@ PJ_DEF(pj_status_t) pjsua_get_ec_tail(unsigned *p_tail_ms) PJ_DEF(pj_status_t) pjsua_get_ec_stat(pjmedia_echo_stat *p_stat) { if (pjsua_var.snd_port) { - return pjmedia_snd_port_get_ec_stat(pjsua_var.snd_port, p_stat); + return pjmedia_snd_port_get_ec_stat(pjsua_var.snd_port, p_stat); } else { - return PJ_ENOTFOUND; + return PJ_ENOTFOUND; } } @@ -2500,37 +2499,37 @@ PJ_DEF(pj_bool_t) pjsua_snd_is_active(void) * Configure sound device setting to the sound device being used. */ PJ_DEF(pj_status_t) pjsua_snd_set_setting( pjmedia_aud_dev_cap cap, - const void *pval, - pj_bool_t keep) + const void *pval, + pj_bool_t keep) { pj_status_t status; /* Check if we are allowed to set the cap */ if ((cap & pjsua_var.aud_svmask) == 0) { - return PJMEDIA_EAUD_INVCAP; + return PJMEDIA_EAUD_INVCAP; } PJSUA_LOCK(); /* If sound is active, set it immediately */ if (pjsua_snd_is_active()) { - pjmedia_aud_stream *strm; + pjmedia_aud_stream *strm; - strm = pjmedia_snd_port_get_snd_stream(pjsua_var.snd_port); - status = pjmedia_aud_stream_set_cap(strm, cap, pval); + strm = pjmedia_snd_port_get_snd_stream(pjsua_var.snd_port); + status = pjmedia_aud_stream_set_cap(strm, cap, pval); } else { - status = PJ_SUCCESS; + status = PJ_SUCCESS; } if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - return status; + PJSUA_UNLOCK(); + return status; } /* Save in internal param for later device open */ if (keep) { - status = pjmedia_aud_param_set_cap(&pjsua_var.aud_param, - cap, pval); + status = pjmedia_aud_param_set_cap(&pjsua_var.aud_param, + cap, pval); } PJSUA_UNLOCK(); @@ -2541,7 +2540,7 @@ PJ_DEF(pj_status_t) pjsua_snd_set_setting( pjmedia_aud_dev_cap cap, * Retrieve a sound device setting. */ PJ_DEF(pj_status_t) pjsua_snd_get_setting( pjmedia_aud_dev_cap cap, - void *pval) + void *pval) { pj_status_t status; @@ -2552,21 +2551,21 @@ PJ_DEF(pj_status_t) pjsua_snd_get_setting( pjmedia_aud_dev_cap cap, * volume) */ if (pjsua_var.aud_open_cnt==0) { - PJ_LOG(4,(THIS_FILE, "Opening sound device to get initial settings")); - pjsua_set_snd_dev(pjsua_var.cap_dev, pjsua_var.play_dev); - close_snd_dev(); + PJ_LOG(4,(THIS_FILE, "Opening sound device to get initial settings")); + pjsua_set_snd_dev(pjsua_var.cap_dev, pjsua_var.play_dev); + close_snd_dev(); } if (pjsua_snd_is_active()) { - /* Sound is active, retrieve from device directly */ - pjmedia_aud_stream *strm; + /* Sound is active, retrieve from device directly */ + pjmedia_aud_stream *strm; - strm = pjmedia_snd_port_get_snd_stream(pjsua_var.snd_port); - status = pjmedia_aud_stream_get_cap(strm, cap, pval); + strm = pjmedia_snd_port_get_snd_stream(pjsua_var.snd_port); + status = pjmedia_aud_stream_get_cap(strm, cap, pval); } else { - /* Otherwise retrieve from internal param */ - status = pjmedia_aud_param_get_cap(&pjsua_var.aud_param, - cap, pval); + /* Otherwise retrieve from internal param */ + status = pjmedia_aud_param_get_cap(&pjsua_var.aud_param, + cap, pval); } PJSUA_UNLOCK(); @@ -2579,11 +2578,11 @@ PJ_DEF(pj_status_t) pjsua_snd_get_setting( pjmedia_aud_dev_cap cap, */ struct pjsua_ext_snd_dev { - pj_pool_t *pool; - pjmedia_port *splitcomb; - pjmedia_port *rev_port; - pjmedia_snd_port *snd_port; - pjsua_conf_port_id port_id; + pj_pool_t *pool; + pjmedia_port *splitcomb; + pjmedia_port *rev_port; + pjmedia_snd_port *snd_port; + pjsua_conf_port_id port_id; }; @@ -2591,7 +2590,7 @@ struct pjsua_ext_snd_dev * Create an extra sound device and register it to conference bridge. */ PJ_DEF(pj_status_t) pjsua_ext_snd_dev_create( pjmedia_snd_port_param *param, - pjsua_ext_snd_dev **p_snd) + pjsua_ext_snd_dev **p_snd) { pjsua_ext_snd_dev *snd = NULL; pj_pool_t *pool; @@ -2602,12 +2601,12 @@ PJ_DEF(pj_status_t) pjsua_ext_snd_dev_create( pjmedia_snd_port_param *param, pool = pjsua_pool_create("extsnd%p", 512, 512); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; snd = PJ_POOL_ZALLOC_T(pool, pjsua_ext_snd_dev); if (!snd) { - pj_pool_release(pool); - return PJ_ENOMEM; + pj_pool_release(pool); + return PJ_ENOMEM; } snd->pool = pool; @@ -2615,40 +2614,40 @@ PJ_DEF(pj_status_t) pjsua_ext_snd_dev_create( pjmedia_snd_port_param *param, /* Create mono splitter/combiner */ status = pjmedia_splitcomb_create( - pool, - param->base.clock_rate, - param->base.channel_count, - param->base.samples_per_frame, - param->base.bits_per_sample, - 0, /* options */ - &snd->splitcomb); + pool, + param->base.clock_rate, + param->base.channel_count, + param->base.samples_per_frame, + param->base.bits_per_sample, + 0, /* options */ + &snd->splitcomb); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create reverse channel */ status = pjmedia_splitcomb_create_rev_channel( - pool, - snd->splitcomb, - 0 /* channel #1 */, - 0 /* options */, - &snd->rev_port); + pool, + snd->splitcomb, + 0 /* channel #1 */, + 0 /* options */, + &snd->rev_port); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* And register it to conference bridge */ status = pjsua_conf_add_port(pool, snd->rev_port, &snd->port_id); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create sound device */ status = pjmedia_snd_port_create2(pool, param, &snd->snd_port); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Connect the splitter to the sound device */ status = pjmedia_snd_port_connect(snd->snd_port, snd->splitcomb); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Finally */ *p_snd = snd; @@ -2656,8 +2655,8 @@ PJ_DEF(pj_status_t) pjsua_ext_snd_dev_create( pjmedia_snd_port_param *param, on_return: if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Failed creating extra sound device", status); - pjsua_ext_snd_dev_destroy(snd); + pjsua_perror(THIS_FILE, "Failed creating extra sound device", status); + pjsua_ext_snd_dev_destroy(snd); } return status; @@ -2673,23 +2672,23 @@ PJ_DEF(pj_status_t) pjsua_ext_snd_dev_destroy(pjsua_ext_snd_dev *snd) /* Unregister from the conference bridge */ if (snd->port_id != PJSUA_INVALID_ID) { - pjsua_conf_remove_port(snd->port_id); - snd->port_id = PJSUA_INVALID_ID; + pjsua_conf_remove_port(snd->port_id); + snd->port_id = PJSUA_INVALID_ID; } /* Destroy all components */ if (snd->snd_port) { - pjmedia_snd_port_disconnect(snd->snd_port); - pjmedia_snd_port_destroy(snd->snd_port); - snd->snd_port = NULL; + pjmedia_snd_port_disconnect(snd->snd_port); + pjmedia_snd_port_destroy(snd->snd_port); + snd->snd_port = NULL; } if (snd->rev_port) { - pjmedia_port_destroy(snd->rev_port); - snd->rev_port = NULL; + pjmedia_port_destroy(snd->rev_port); + snd->rev_port = NULL; } if (snd->splitcomb) { - pjmedia_port_destroy(snd->splitcomb); - snd->splitcomb = NULL; + pjmedia_port_destroy(snd->splitcomb); + snd->splitcomb = NULL; } /* Finally */ @@ -2705,7 +2704,7 @@ PJ_DEF(pj_status_t) pjsua_ext_snd_dev_destroy(pjsua_ext_snd_dev *snd) * Get sound port instance of an extra sound device. */ PJ_DEF(pjmedia_snd_port*) pjsua_ext_snd_dev_get_snd_port( - pjsua_ext_snd_dev *snd) + pjsua_ext_snd_dev *snd) { PJ_ASSERT_RETURN(snd, NULL); return snd->snd_port; @@ -2715,7 +2714,7 @@ PJ_DEF(pjmedia_snd_port*) pjsua_ext_snd_dev_get_snd_port( * Get conference port ID of an extra sound device. */ PJ_DEF(pjsua_conf_port_id) pjsua_ext_snd_dev_get_conf_port( - pjsua_ext_snd_dev *snd) + pjsua_ext_snd_dev *snd) { PJ_ASSERT_RETURN(snd, PJSUA_INVALID_ID); return snd->port_id; diff --git a/pjsip/src/pjsua-lib/pjsua_call.c b/pjsip/src/pjsua-lib/pjsua_call.c index b646a96f3f..1faf16e0d4 100644 --- a/pjsip/src/pjsua-lib/pjsua_call.c +++ b/pjsip/src/pjsua-lib/pjsua_call.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,7 +20,7 @@ #include -#define THIS_FILE "pjsua_call.c" +#define THIS_FILE "pjsua_call.c" /* Retry interval of sending re-INVITE for locking a codec when remote @@ -32,7 +31,7 @@ /* * Max UPDATE/re-INVITE retry to lock codec */ -#define LOCK_CODEC_MAX_RETRY 5 +#define LOCK_CODEC_MAX_RETRY 5 /* Determine whether we should restart ICE upon receiving a re-INVITE * with no SDP. @@ -43,7 +42,7 @@ #define CALL_HANGUP_RETRY_INTERVAL 5000 /* Max number of hangup retries. */ -#define CALL_HANGUP_MAX_RETRY 4 +#define CALL_HANGUP_MAX_RETRY 4 /* * The INFO method. @@ -65,13 +64,13 @@ static const pjsip_method pjsip_update_method = * session state has changed. */ static void pjsua_call_on_state_changed(pjsip_inv_session *inv, - pjsip_event *e); + pjsip_event *e); /* This callback is called by invite session framework when UAC session * has forked. */ static void pjsua_call_on_forked( pjsip_inv_session *inv, - pjsip_event *e); + pjsip_event *e); /* * Callback to be called when SDP offer/answer negotiation has just completed @@ -79,26 +78,26 @@ static void pjsua_call_on_forked( pjsip_inv_session *inv, * has succeeded. */ static void pjsua_call_on_media_update(pjsip_inv_session *inv, - pj_status_t status); + pj_status_t status); /* * Called when session received new offer. */ static void pjsua_call_on_rx_offer(pjsip_inv_session *inv, - struct pjsip_inv_on_rx_offer_cb_param *param); + struct pjsip_inv_on_rx_offer_cb_param *param); /* * Called when receiving re-INVITE. */ static pj_status_t pjsua_call_on_rx_reinvite(pjsip_inv_session *inv, - const pjmedia_sdp_session *offer, - pjsip_rx_data *rdata); + const pjmedia_sdp_session *offer, + pjsip_rx_data *rdata); /* * Called to generate new offer. */ static void pjsua_call_on_create_offer(pjsip_inv_session *inv, - pjmedia_sdp_session **offer); + pjmedia_sdp_session **offer); /* * This callback is called when transaction state has changed in INVITE @@ -107,20 +106,20 @@ static void pjsua_call_on_create_offer(pjsip_inv_session *inv, * - incoming MESSAGE request. */ static void pjsua_call_on_tsx_state_changed(pjsip_inv_session *inv, - pjsip_transaction *tsx, - pjsip_event *e); + pjsip_transaction *tsx, + pjsip_event *e); /* * Redirection handler. */ static pjsip_redirect_op pjsua_call_on_redirected(pjsip_inv_session *inv, - const pjsip_uri *target, - const pjsip_event *e); + const pjsip_uri *target, + const pjsip_event *e); /* Create SDP for call hold. */ static pj_status_t create_sdp_of_call_hold(pjsua_call *call, - pjmedia_sdp_session **p_sdp); + pjmedia_sdp_session **p_sdp); /* * Callback called by event framework when the xfer subscription state @@ -140,15 +139,15 @@ static pj_status_t process_pending_reinvite(pjsua_call *call); /* Timer callbacks for trickle ICE */ static void trickle_ice_send_sip_info(pj_timer_heap_t *th, - struct pj_timer_entry *te); + struct pj_timer_entry *te); static void trickle_ice_retrans_18x(pj_timer_heap_t *th, - struct pj_timer_entry *te); + struct pj_timer_entry *te); /* End call session */ static pj_status_t call_inv_end_session(pjsua_call *call, - unsigned code, - const pj_str_t *reason, - const pjsua_msg_data *msg_data); + unsigned code, + const pj_str_t *reason, + const pjsua_msg_data *msg_data); /* * Reset call descriptor. @@ -159,8 +158,8 @@ static void reset_call(pjsua_call_id id) unsigned i; if (call->incoming_data) { - pjsip_rx_data_free_cloned(call->incoming_data); - call->incoming_data = NULL; + pjsip_rx_data_free_cloned(call->incoming_data); + call->incoming_data = NULL; } pj_bzero(call, sizeof(*call)); call->index = id; @@ -168,33 +167,33 @@ static void reset_call(pjsua_call_id id) call->cname.ptr = call->cname_buf; call->cname.slen = sizeof(call->cname_buf); for (i=0; imedia); ++i) { - pjsua_call_media *call_med = &call->media[i]; - call_med->ssrc = pj_rand(); - call_med->strm.a.conf_slot = PJSUA_INVALID_ID; - call_med->strm.v.cap_win_id = PJSUA_INVALID_ID; - call_med->strm.v.rdr_win_id = PJSUA_INVALID_ID; - call_med->strm.v.strm_dec_slot = PJSUA_INVALID_ID; - call_med->strm.v.strm_enc_slot = PJSUA_INVALID_ID; - call_med->call = call; - call_med->idx = i; - call_med->tp_auto_del = PJ_TRUE; + pjsua_call_media *call_med = &call->media[i]; + call_med->ssrc = pj_rand(); + call_med->strm.a.conf_slot = PJSUA_INVALID_ID; + call_med->strm.v.cap_win_id = PJSUA_INVALID_ID; + call_med->strm.v.rdr_win_id = PJSUA_INVALID_ID; + call_med->strm.v.strm_dec_slot = PJSUA_INVALID_ID; + call_med->strm.v.strm_enc_slot = PJSUA_INVALID_ID; + call_med->call = call; + call_med->idx = i; + call_med->tp_auto_del = PJ_TRUE; } pjsua_call_setting_default(&call->opt); pj_timer_entry_init(&call->reinv_timer, PJ_FALSE, - (void*)(pj_size_t)id, &reinv_timer_cb); + (void*)(pj_size_t)id, &reinv_timer_cb); pj_bzero(&call->trickle_ice, sizeof(call->trickle_ice)); pj_timer_entry_init(&call->trickle_ice.timer, 0, call, - &trickle_ice_send_sip_info); + &trickle_ice_send_sip_info); } /* Get DTMF method type name */ static const char* get_dtmf_method_name(int type) { switch (type) { - case PJSUA_DTMF_METHOD_RFC2833: - return "RFC2833"; - case PJSUA_DTMF_METHOD_SIP_INFO: - return "SIP INFO"; + case PJSUA_DTMF_METHOD_RFC2833: + return "RFC2833"; + case PJSUA_DTMF_METHOD_SIP_INFO: + return "SIP INFO"; } return "(Unknown)"; } @@ -212,22 +211,22 @@ pj_status_t pjsua_call_subsys_init(const pjsua_config *cfg) /* Init calls array. */ for (i=0; i= PJSUA_MAX_CALLS) { - pjsua_var.ua_cfg.max_calls = PJSUA_MAX_CALLS; + pjsua_var.ua_cfg.max_calls = PJSUA_MAX_CALLS; } /* Check the route URI's and force loose route if required */ for (i=0; i= (int)pjsua_var.ua_cfg.max_calls || - pjsua_var.next_call_id < 0) + pjsua_var.next_call_id < 0) { - pjsua_var.next_call_id = 0; + pjsua_var.next_call_id = 0; } for (cid=pjsua_var.next_call_id; - cid<(int)pjsua_var.ua_cfg.max_calls; - ++cid) + cid<(int)pjsua_var.ua_cfg.max_calls; + ++cid) { - if (pjsua_var.calls[cid].inv == NULL && + if (pjsua_var.calls[cid].inv == NULL && pjsua_var.calls[cid].async_call.dlg == NULL) { - ++pjsua_var.next_call_id; - return cid; - } + ++pjsua_var.next_call_id; + return cid; + } } for (cid=0; cid < pjsua_var.next_call_id; ++cid) { - if (pjsua_var.calls[cid].inv == NULL && + if (pjsua_var.calls[cid].inv == NULL && pjsua_var.calls[cid].async_call.dlg == NULL) { - ++pjsua_var.next_call_id; - return cid; - } + ++pjsua_var.next_call_id; + return cid; + } } #else /* Old algorithm */ for (cid=0; cid<(int)pjsua_var.ua_cfg.max_calls; ++cid) { - if (pjsua_var.calls[cid].inv == NULL) - return cid; + if (pjsua_var.calls[cid].inv == NULL) + return cid; } #endif @@ -376,20 +375,20 @@ static int get_secure_level(pjsua_acc_id acc_id, const pj_str_t *dst_uri) pjsua_acc *acc = &pjsua_var.acc[acc_id]; if (pj_stristr(dst_uri, &sips)) - return 2; + return 2; if (!pj_list_empty(&acc->route_set)) { - pjsip_route_hdr *r = acc->route_set.next; - pjsip_uri *uri = r->name_addr.uri; - pjsip_sip_uri *sip_uri; + pjsip_route_hdr *r = acc->route_set.next; + pjsip_uri *uri = r->name_addr.uri; + pjsip_sip_uri *sip_uri; - sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri); - if (pj_stricmp2(&sip_uri->transport_param, "tls")==0) - return 1; + sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri); + if (pj_stricmp2(&sip_uri->transport_param, "tls")==0) + return 1; } else { - if (pj_stristr(dst_uri, &tls)) - return 1; + if (pj_stristr(dst_uri, &tls)) + return 1; } return 0; @@ -399,28 +398,28 @@ static int get_secure_level(pjsua_acc_id acc_id, const pj_str_t *dst_uri) static int call_get_secure_level(pjsua_call *call) { if (call->inv->dlg->secure) - return 2; + return 2; if (!pj_list_empty(&call->inv->dlg->route_set)) { - pjsip_route_hdr *r = call->inv->dlg->route_set.next; - pjsip_uri *uri = r->name_addr.uri; - pjsip_sip_uri *sip_uri; + pjsip_route_hdr *r = call->inv->dlg->route_set.next; + pjsip_uri *uri = r->name_addr.uri; + pjsip_sip_uri *sip_uri; - sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri); - if (pj_stricmp2(&sip_uri->transport_param, "tls")==0) - return 1; + sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri); + if (pj_stricmp2(&sip_uri->transport_param, "tls")==0) + return 1; } else { - pjsip_sip_uri *sip_uri; + pjsip_sip_uri *sip_uri; - if (PJSIP_URI_SCHEME_IS_SIPS(call->inv->dlg->target)) - return 2; - if (!PJSIP_URI_SCHEME_IS_SIP(call->inv->dlg->target)) - return 0; + if (PJSIP_URI_SCHEME_IS_SIPS(call->inv->dlg->target)) + return 2; + if (!PJSIP_URI_SCHEME_IS_SIP(call->inv->dlg->target)) + return 0; - sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(call->inv->dlg->target); - if (pj_stricmp2(&sip_uri->transport_param, "tls")==0) - return 1; + sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(call->inv->dlg->target); + if (pj_stricmp2(&sip_uri->transport_param, "tls")==0) + return 1; } return 0; @@ -453,19 +452,19 @@ on_make_call_med_tp_complete(pjsua_call_id call_id, pjsip_dlg_dec_session(dlg, &pjsua_var.mod); if (status != PJ_SUCCESS) { - pj_str_t err_str; - pj_ssize_t title_len; + pj_str_t err_str; + pj_ssize_t title_len; - call->last_code = PJSIP_SC_TEMPORARILY_UNAVAILABLE; - pj_strcpy2(&call->last_text, "Media init error: "); + call->last_code = PJSIP_SC_TEMPORARILY_UNAVAILABLE; + pj_strcpy2(&call->last_text, "Media init error: "); - title_len = call->last_text.slen; - err_str = pj_strerror(status, call->last_text_buf_ + title_len, - sizeof(call->last_text_buf_) - title_len); - call->last_text.slen += err_str.slen; + title_len = call->last_text.slen; + err_str = pj_strerror(status, call->last_text_buf_ + title_len, + sizeof(call->last_text_buf_) - title_len); + call->last_text.slen += err_str.slen; - pjsua_perror(THIS_FILE, "Error initializing media channel", status); - goto on_error; + pjsua_perror(THIS_FILE, "Error initializing media channel", status); + goto on_error; } /* pjsua_media_channel_deinit() has been called or @@ -492,31 +491,31 @@ on_make_call_med_tp_complete(pjsua_call_id call_id, /* Create the INVITE session: */ options |= PJSIP_INV_SUPPORT_100REL; if (acc->cfg.require_100rel == PJSUA_100REL_MANDATORY) - options |= PJSIP_INV_REQUIRE_100REL; + options |= PJSIP_INV_REQUIRE_100REL; if (acc->cfg.use_timer != PJSUA_SIP_TIMER_INACTIVE) { - options |= PJSIP_INV_SUPPORT_TIMER; - if (acc->cfg.use_timer == PJSUA_SIP_TIMER_REQUIRED) - options |= PJSIP_INV_REQUIRE_TIMER; - else if (acc->cfg.use_timer == PJSUA_SIP_TIMER_ALWAYS) - options |= PJSIP_INV_ALWAYS_USE_TIMER; + options |= PJSIP_INV_SUPPORT_TIMER; + if (acc->cfg.use_timer == PJSUA_SIP_TIMER_REQUIRED) + options |= PJSIP_INV_REQUIRE_TIMER; + else if (acc->cfg.use_timer == PJSUA_SIP_TIMER_ALWAYS) + options |= PJSIP_INV_ALWAYS_USE_TIMER; } if (acc->cfg.ice_cfg.enable_ice && - acc->cfg.ice_cfg.ice_opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED) + acc->cfg.ice_cfg.ice_opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED) { - options |= PJSIP_INV_SUPPORT_TRICKLE_ICE; + options |= PJSIP_INV_SUPPORT_TRICKLE_ICE; } status = pjsip_inv_create_uac( dlg, offer, options, &inv); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Invite session creation failed", status); - goto on_error; + pjsua_perror(THIS_FILE, "Invite session creation failed", status); + goto on_error; } /* Init Session Timers */ status = pjsip_timer_init_session(inv, &acc->cfg.timer_setting); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Session Timer init failed", status); - goto on_error; + pjsua_perror(THIS_FILE, "Session Timer init failed", status); + goto on_error; } /* Create and associate our data in the session. */ @@ -529,21 +528,21 @@ on_make_call_med_tp_complete(pjsua_call_id call_id, * to this transport too. */ if (acc->cfg.transport_id != PJSUA_INVALID_ID) { - pjsip_tpselector tp_sel; + pjsip_tpselector tp_sel; - pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); - pjsip_dlg_set_transport(dlg, &tp_sel); + pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); + pjsip_dlg_set_transport(dlg, &tp_sel); } /* Set dialog Route-Set: */ if (!pj_list_empty(&acc->route_set)) - pjsip_dlg_set_route_set(dlg, &acc->route_set); + pjsip_dlg_set_route_set(dlg, &acc->route_set); /* Set credentials: */ if (acc->cred_cnt) { - pjsip_auth_clt_set_credentials( &dlg->auth_sess, - acc->cred_cnt, acc->cred); + pjsip_auth_clt_set_credentials( &dlg->auth_sess, + acc->cred_cnt, acc->cred); } /* Set authentication preference */ @@ -553,9 +552,9 @@ on_make_call_med_tp_complete(pjsua_call_id call_id, status = pjsip_inv_invite(inv, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create initial INVITE request", - status); - goto on_error; + pjsua_perror(THIS_FILE, "Unable to create initial INVITE request", + status); + goto on_error; } @@ -571,13 +570,13 @@ on_make_call_med_tp_complete(pjsua_call_id call_id, status = pjsip_inv_send_msg(inv, tdata); if (status != PJ_SUCCESS) { - cb_called = PJ_TRUE; + cb_called = PJ_TRUE; - /* Upon failure to send first request, the invite - * session would have been cleared. - */ - call->inv = inv = NULL; - goto on_error; + /* Upon failure to send first request, the invite + * session would have been cleared. + */ + call->inv = inv = NULL; + goto on_error; } /* Done. */ @@ -590,32 +589,32 @@ on_make_call_med_tp_complete(pjsua_call_id call_id, on_error: if (inv == NULL && call_id != -1 && !cb_called && - !call->hanging_up && - pjsua_var.ua_cfg.cb.on_call_state) + !call->hanging_up && + pjsua_var.ua_cfg.cb.on_call_state) { - /* Use user event rather than NULL to avoid crash in - * unsuspecting app. - */ - pjsip_event user_event; - PJSIP_EVENT_INIT_USER(user_event, 0, 0, 0, 0); + /* Use user event rather than NULL to avoid crash in + * unsuspecting app. + */ + pjsip_event user_event; + PJSIP_EVENT_INIT_USER(user_event, 0, 0, 0, 0); (*pjsua_var.ua_cfg.cb.on_call_state)(call_id, &user_event); } if (dlg) { - /* This may destroy the dialog */ - pjsip_dlg_dec_lock(dlg); - call->async_call.dlg = NULL; + /* This may destroy the dialog */ + pjsip_dlg_dec_lock(dlg); + call->async_call.dlg = NULL; } if (inv != NULL) { - pjsip_inv_terminate(inv, PJSIP_SC_OK, PJ_FALSE); - call->inv = NULL; + pjsip_inv_terminate(inv, PJSIP_SC_OK, PJ_FALSE); + call->inv = NULL; } if (call_id != -1) { - pjsua_media_channel_deinit(call_id); - reset_call(call_id); + pjsua_media_channel_deinit(call_id); + reset_call(call_id); } call->med_ch_cb = NULL; @@ -635,8 +634,8 @@ on_make_call_med_tp_complete(pjsua_call_id call_id, void pjsua_call_cleanup_flag(pjsua_call_setting *opt) { opt->flag &= ~(PJSUA_CALL_UNHOLD | PJSUA_CALL_UPDATE_CONTACT | - PJSUA_CALL_NO_SDP_OFFER | PJSUA_CALL_REINIT_MEDIA | - PJSUA_CALL_UPDATE_VIA | PJSUA_CALL_SET_MEDIA_DIR); + PJSUA_CALL_NO_SDP_OFFER | PJSUA_CALL_REINIT_MEDIA | + PJSUA_CALL_UPDATE_VIA | PJSUA_CALL_SET_MEDIA_DIR); } @@ -656,11 +655,11 @@ PJ_DEF(void) pjsua_call_setting_default(pjsua_call_setting *opt) #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) opt->vid_cnt = 1; opt->req_keyframe_method = PJSUA_VID_REQ_KEYFRAME_SIP_INFO | - PJSUA_VID_REQ_KEYFRAME_RTCP_PLI; + PJSUA_VID_REQ_KEYFRAME_RTCP_PLI; #endif for (i = 0; i < PJMEDIA_MAX_SDP_MEDIA; i++) { - opt->media_dir[i] = PJMEDIA_DIR_ENCODING_DECODING; + opt->media_dir[i] = PJMEDIA_DIR_ENCODING_DECODING; } } @@ -668,22 +667,22 @@ PJ_DEF(void) pjsua_call_setting_default(pjsua_call_setting *opt) * Initialize pjsua_call_send_dtmf_param default values. */ PJ_DEF(void) pjsua_call_send_dtmf_param_default( - pjsua_call_send_dtmf_param *param) + pjsua_call_send_dtmf_param *param) { pj_bzero(param, sizeof(*param)); param->duration = PJSUA_CALL_SEND_DTMF_DURATION_DEFAULT; } static pj_status_t apply_call_setting(pjsua_call *call, - const pjsua_call_setting *opt, - const pjmedia_sdp_session *rem_sdp) + const pjsua_call_setting *opt, + const pjmedia_sdp_session *rem_sdp) { pj_assert(call); if (!opt) { - pjsua_call_cleanup_flag(&call->opt); + pjsua_call_cleanup_flag(&call->opt); } else { - call->opt = *opt; + call->opt = *opt; } #if !PJMEDIA_HAS_VIDEO @@ -691,8 +690,8 @@ static pj_status_t apply_call_setting(pjsua_call *call, #endif if (call->opt.flag & PJSUA_CALL_REINIT_MEDIA) { - PJ_LOG(4, (THIS_FILE, "PJSUA_CALL_REINIT_MEDIA")); - pjsua_media_channel_deinit(call->index); + PJ_LOG(4, (THIS_FILE, "PJSUA_CALL_REINIT_MEDIA")); + pjsua_media_channel_deinit(call->index); } /* If call is established or media channel hasn't been initialized, @@ -703,19 +702,19 @@ static pj_status_t apply_call_setting(pjsua_call *call, (call->inv && call->inv->state == PJSIP_INV_STATE_CONFIRMED) || (call->opt.flag & PJSUA_CALL_REINIT_MEDIA)) { - pjsip_role_e role = rem_sdp? PJSIP_ROLE_UAS : PJSIP_ROLE_UAC; - pj_status_t status; - - status = pjsua_media_channel_init(call->index, role, - call->secure_level, - call->inv->pool_prov, - rem_sdp, NULL, - PJ_FALSE, NULL); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error re-initializing media channel", - status); - return status; - } + pjsip_role_e role = rem_sdp? PJSIP_ROLE_UAS : PJSIP_ROLE_UAC; + pj_status_t status; + + status = pjsua_media_channel_init(call->index, role, + call->secure_level, + call->inv->pool_prov, + rem_sdp, NULL, + PJ_FALSE, NULL); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error re-initializing media channel", + status); + return status; + } } return PJ_SUCCESS; @@ -726,21 +725,21 @@ static void dlg_set_via(pjsip_dialog *dlg, pjsua_acc *acc) if (acc->cfg.allow_via_rewrite && acc->via_addr.host.slen > 0) { pjsip_dlg_set_via_sent_by(dlg, &acc->via_addr, acc->via_tp); } else if (!pjsua_sip_acc_is_using_stun(acc->index) && - !pjsua_sip_acc_is_using_upnp(acc->index)) + !pjsua_sip_acc_is_using_upnp(acc->index)) { - /* Choose local interface to use in Via if acc is not using - * STUN nor UPnP. See https://github.com/pjsip/pjproject/issues/1804 - */ - pjsip_host_port via_addr; - const void *via_tp; - - if (pjsua_acc_get_uac_addr(acc->index, dlg->pool, &acc->cfg.id, - &via_addr, NULL, NULL, - &via_tp) == PJ_SUCCESS) - { - pjsip_dlg_set_via_sent_by(dlg, &via_addr, - (pjsip_transport*)via_tp); - } + /* Choose local interface to use in Via if acc is not using + * STUN nor UPnP. See https://github.com/pjsip/pjproject/issues/1804 + */ + pjsip_host_port via_addr; + const void *via_tp; + + if (pjsua_acc_get_uac_addr(acc->index, dlg->pool, &acc->cfg.id, + &via_addr, NULL, NULL, + &via_tp) == PJ_SUCCESS) + { + pjsip_dlg_set_via_sent_by(dlg, &via_addr, + (pjsip_transport*)via_tp); + } } } @@ -755,25 +754,25 @@ static pj_status_t dlg_set_target(pjsip_dialog *dlg, const pj_str_t *target) pj_strdup_with_null(dlg->pool, &tmp, target); target_uri = pjsip_parse_uri(dlg->pool, tmp.ptr, tmp.slen, 0); if (!target_uri) { - return PJSIP_EINVALIDURI; + return PJSIP_EINVALIDURI; } if (!PJSIP_URI_SCHEME_IS_SIP(target_uri) && - !PJSIP_URI_SCHEME_IS_SIPS(target_uri)) + !PJSIP_URI_SCHEME_IS_SIPS(target_uri)) { - return PJSIP_EINVALIDSCHEME; + return PJSIP_EINVALIDSCHEME; } /* Add the new target */ status = pjsip_target_set_add_uri(&dlg->target_set, dlg->pool, - target_uri, 0); + target_uri, 0); if (status != PJ_SUCCESS) - return status; + return status; /* Set it as current target */ status = pjsip_target_set_set_current(&dlg->target_set, - pjsip_target_set_get_next(&dlg->target_set)); + pjsip_target_set_get_next(&dlg->target_set)); if (status != PJ_SUCCESS) - return status; + return status; /* Update dialog target URI */ dlg->target = target_uri; @@ -789,27 +788,27 @@ void call_update_contact(pjsua_call *call, pj_str_t **new_contact) pjsua_acc *acc = &pjsua_var.acc[call->acc_id]; if (acc->cfg.force_contact.slen) - *new_contact = &acc->cfg.force_contact; + *new_contact = &acc->cfg.force_contact; else if (acc->contact.slen) - *new_contact = &acc->contact; + *new_contact = &acc->contact; else { - /* Non-registering account */ - pjsip_dialog *dlg = call->inv->dlg; - pj_str_t tmp_contact; - pj_status_t status; - - status = pjsua_acc_create_uac_contact(dlg->pool, - &tmp_contact, - acc->index, - &dlg->remote.info_str); - if (status == PJ_SUCCESS) { - *new_contact = PJ_POOL_ZALLOC_T(dlg->pool, pj_str_t); - **new_contact = tmp_contact; - } else { - PJ_PERROR(3,(THIS_FILE, status, - "Call %d: failed creating contact " - "for contact update", call->index)); - } + /* Non-registering account */ + pjsip_dialog *dlg = call->inv->dlg; + pj_str_t tmp_contact; + pj_status_t status; + + status = pjsua_acc_create_uac_contact(dlg->pool, + &tmp_contact, + acc->index, + &dlg->remote.info_str); + if (status == PJ_SUCCESS) { + *new_contact = PJ_POOL_ZALLOC_T(dlg->pool, pj_str_t); + **new_contact = tmp_contact; + } else { + PJ_PERROR(3,(THIS_FILE, status, + "Call %d: failed creating contact " + "for contact update", call->index)); + } } @@ -826,11 +825,11 @@ void call_update_contact(pjsua_call *call, pj_str_t **new_contact) * Make outgoing call to the specified URI using the specified account. */ PJ_DEF(pj_status_t) pjsua_call_make_call(pjsua_acc_id acc_id, - const pj_str_t *dest_uri, - const pjsua_call_setting *opt, - void *user_data, - const pjsua_msg_data *msg_data, - pjsua_call_id *p_call_id) + const pj_str_t *dest_uri, + const pjsua_call_setting *opt, + void *user_data, + const pjsua_msg_data *msg_data, + pjsua_call_id *p_call_id) { pj_pool_t *tmp_pool = NULL; pjsip_dialog *dlg = NULL; @@ -842,13 +841,13 @@ PJ_DEF(pj_status_t) pjsua_call_make_call(pjsua_acc_id acc_id, /* Check that account is valid */ PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc), - PJ_EINVAL); + PJ_EINVAL); /* Check arguments */ PJ_ASSERT_RETURN(dest_uri, PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Making call with acc #%d to %.*s", acc_id, - (int)dest_uri->slen, dest_uri->ptr)); + (int)dest_uri->slen, dest_uri->ptr)); pj_log_push_indent(); @@ -856,19 +855,19 @@ PJ_DEF(pj_status_t) pjsua_call_make_call(pjsua_acc_id acc_id, acc = &pjsua_var.acc[acc_id]; if (!acc->valid) { - pjsua_perror(THIS_FILE, "Unable to make call because account " - "is not valid", PJ_EINVALIDOP); - status = PJ_EINVALIDOP; - goto on_error; + pjsua_perror(THIS_FILE, "Unable to make call because account " + "is not valid", PJ_EINVALIDOP); + status = PJ_EINVALIDOP; + goto on_error; } /* Find free call slot. */ call_id = alloc_call_id(); if (call_id == PJSUA_INVALID_ID) { - pjsua_perror(THIS_FILE, "Error making call", PJ_ETOOMANY); - status = PJ_ETOOMANY; - goto on_error; + pjsua_perror(THIS_FILE, "Error making call", PJ_ETOOMANY); + status = PJ_ETOOMANY; + goto on_error; } /* Clear call descriptor */ @@ -886,8 +885,8 @@ PJ_DEF(pj_status_t) pjsua_call_make_call(pjsua_acc_id acc_id, /* Apply call setting */ status = apply_call_setting(call, opt, NULL); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Failed to apply call setting", status); - goto on_error; + pjsua_perror(THIS_FILE, "Failed to apply call setting", status); + goto on_error; } /* Create sound port if none is instantiated, to check if sound device @@ -896,11 +895,11 @@ PJ_DEF(pj_status_t) pjsua_call_make_call(pjsua_acc_id acc_id, * device once the correct format has been known */ if (!pjsua_var.is_mswitch && pjsua_var.snd_port==NULL && - pjsua_var.null_snd==NULL && !pjsua_var.no_snd && call->opt.aud_cnt > 0) + pjsua_var.null_snd==NULL && !pjsua_var.no_snd && call->opt.aud_cnt > 0) { - status = pjsua_set_snd_dev(pjsua_var.cap_dev, pjsua_var.play_dev); - if (status != PJ_SUCCESS) - goto on_error; + status = pjsua_set_snd_dev(pjsua_var.cap_dev, pjsua_var.play_dev); + if (status != PJ_SUCCESS) + goto on_error; } /* Create temporary pool */ @@ -912,18 +911,18 @@ PJ_DEF(pj_status_t) pjsua_call_make_call(pjsua_acc_id acc_id, * when pjsua_acc_create_uac_contact() fails. */ if (1) { - pjsip_uri *uri; - pj_str_t dup; + pjsip_uri *uri; + pj_str_t dup; - pj_strdup_with_null(tmp_pool, &dup, dest_uri); - uri = pjsip_parse_uri(tmp_pool, dup.ptr, dup.slen, 0); + pj_strdup_with_null(tmp_pool, &dup, dest_uri); + uri = pjsip_parse_uri(tmp_pool, dup.ptr, dup.slen, 0); - if (uri == NULL) { - pjsua_perror(THIS_FILE, "Unable to make call", - PJSIP_EINVALIDREQURI); - status = PJSIP_EINVALIDREQURI; - goto on_error; - } + if (uri == NULL) { + pjsua_perror(THIS_FILE, "Unable to make call", + PJSIP_EINVALIDREQURI); + status = PJSIP_EINVALIDREQURI; + goto on_error; + } } /* Mark call start time. */ @@ -936,27 +935,27 @@ PJ_DEF(pj_status_t) pjsua_call_make_call(pjsua_acc_id acc_id, * set in the account. */ if (acc->contact.slen) { - contact = acc->contact; + contact = acc->contact; } else { - status = pjsua_acc_create_uac_contact(tmp_pool, &contact, - acc_id, dest_uri); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to generate Contact header", - status); - goto on_error; - } + status = pjsua_acc_create_uac_contact(tmp_pool, &contact, + acc_id, dest_uri); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to generate Contact header", + status); + goto on_error; + } } /* Create outgoing dialog: */ status = pjsip_dlg_create_uac( pjsip_ua_instance(), - &acc->cfg.id, &contact, - dest_uri, + &acc->cfg.id, &contact, + dest_uri, (msg_data && msg_data->target_uri.slen? &msg_data->target_uri: dest_uri), &dlg); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Dialog creation failed", status); - goto on_error; + pjsua_perror(THIS_FILE, "Dialog creation failed", status); + goto on_error; } /* Increment the dialog's lock otherwise when invite session creation @@ -976,7 +975,7 @@ PJ_DEF(pj_status_t) pjsua_call_make_call(pjsua_acc_id acc_id, * media transport creation is completed. */ if (msg_data) { - call->async_call.call_var.out_call.msg_data = pjsua_msg_data_clone( + call->async_call.call_var.out_call.msg_data = pjsua_msg_data_clone( dlg->pool, msg_data); } call->async_call.dlg = dlg; @@ -997,17 +996,17 @@ PJ_DEF(pj_status_t) pjsua_call_make_call(pjsua_acc_id acc_id, if (status == PJ_SUCCESS) { status = on_make_call_med_tp_complete(call->index, NULL); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; } else if (status != PJ_EPENDING) { - pjsua_perror(THIS_FILE, "Error initializing media channel", status); + pjsua_perror(THIS_FILE, "Error initializing media channel", status); pjsip_dlg_dec_session(dlg, &pjsua_var.mod); - goto on_error; + goto on_error; } /* Done. */ if (p_call_id) - *p_call_id = call_id; + *p_call_id = call_id; pjsip_dlg_dec_lock(dlg); pj_pool_release(tmp_pool); @@ -1020,20 +1019,20 @@ PJ_DEF(pj_status_t) pjsua_call_make_call(pjsua_acc_id acc_id, on_error: if (dlg && call) { - /* This may destroy the dialog */ - pjsip_dlg_dec_lock(dlg); - call->async_call.dlg = NULL; + /* This may destroy the dialog */ + pjsip_dlg_dec_lock(dlg); + call->async_call.dlg = NULL; } if (call_id != -1) { - pjsua_media_channel_deinit(call_id); - reset_call(call_id); + pjsua_media_channel_deinit(call_id); + reset_call(call_id); } pjsua_check_snd_dev_idle(); if (tmp_pool) - pj_pool_release(tmp_pool); + pj_pool_release(tmp_pool); PJSUA_UNLOCK(); pj_log_pop_indent(); @@ -1043,24 +1042,24 @@ PJ_DEF(pj_status_t) pjsua_call_make_call(pjsua_acc_id acc_id, /* Get the NAT type information in remote's SDP */ static void update_remote_nat_type(pjsua_call *call, - const pjmedia_sdp_session *sdp) + const pjmedia_sdp_session *sdp) { const pjmedia_sdp_attr *xnat; xnat = pjmedia_sdp_attr_find2(sdp->attr_count, sdp->attr, "X-nat", NULL); if (xnat) { - call->rem_nat_type = (pj_stun_nat_type) (xnat->value.ptr[0] - '0'); + call->rem_nat_type = (pj_stun_nat_type) (xnat->value.ptr[0] - '0'); } else { - call->rem_nat_type = PJ_STUN_NAT_TYPE_UNKNOWN; + call->rem_nat_type = PJ_STUN_NAT_TYPE_UNKNOWN; } PJ_LOG(5,(THIS_FILE, "Call %d: remote NAT type is %d (%s)", call->index, - call->rem_nat_type, pj_stun_get_nat_name(call->rem_nat_type))); + call->rem_nat_type, pj_stun_get_nat_name(call->rem_nat_type))); } static pj_status_t process_incoming_call_replace(pjsua_call *call, - pjsip_dialog *replaced_dlg) + pjsip_dialog *replaced_dlg) { pjsip_inv_session *replaced_inv; struct pjsua_call *replaced_call; @@ -1075,52 +1074,52 @@ static pj_status_t process_incoming_call_replace(pjsua_call *call, /* Notify application */ if (!replaced_call->hanging_up && pjsua_var.ua_cfg.cb.on_call_replaced) - pjsua_var.ua_cfg.cb.on_call_replaced(replaced_call->index, - call->index); + pjsua_var.ua_cfg.cb.on_call_replaced(replaced_call->index, + call->index); if (replaced_call->inv->state <= PJSIP_INV_STATE_EARLY && - replaced_call->inv->role != PJSIP_ROLE_UAC) + replaced_call->inv->role != PJSIP_ROLE_UAC) { - if (replaced_call->last_code > 100 && replaced_call->last_code < 200) - { - pjsip_status_code code = replaced_call->last_code; - pj_str_t *text = &replaced_call->last_text; + if (replaced_call->last_code > 100 && replaced_call->last_code < 200) + { + pjsip_status_code code = replaced_call->last_code; + pj_str_t *text = &replaced_call->last_text; - PJ_LOG(4,(THIS_FILE, "Answering replacement call %d with %d/%.*s", - call->index, code, text->slen, text->ptr)); + PJ_LOG(4,(THIS_FILE, "Answering replacement call %d with %d/%.*s", + call->index, code, text->slen, text->ptr)); - /* Answer the new call with last response in the replaced call */ - status = pjsip_inv_answer(call->inv, code, text, NULL, &tdata); - } + /* Answer the new call with last response in the replaced call */ + status = pjsip_inv_answer(call->inv, code, text, NULL, &tdata); + } } else { - PJ_LOG(4,(THIS_FILE, "Answering replacement call %d with 200/OK", - call->index)); + PJ_LOG(4,(THIS_FILE, "Answering replacement call %d with 200/OK", + call->index)); - /* Answer the new call with 200 response */ - status = pjsip_inv_answer(call->inv, 200, NULL, NULL, &tdata); + /* Answer the new call with 200 response */ + status = pjsip_inv_answer(call->inv, 200, NULL, NULL, &tdata); } if (status == PJ_SUCCESS && tdata) - status = pjsip_inv_send_msg(call->inv, tdata); + status = pjsip_inv_send_msg(call->inv, tdata); if (status != PJ_SUCCESS) - pjsua_perror(THIS_FILE, "Error answering session", status); + pjsua_perror(THIS_FILE, "Error answering session", status); /* Note that inv may be invalid if 200/OK has caused error in * starting the media. */ PJ_LOG(4,(THIS_FILE, "Disconnecting replaced call %d", - replaced_call->index)); + replaced_call->index)); /* Disconnect replaced invite session */ status = pjsip_inv_end_session(replaced_inv, PJSIP_SC_GONE, NULL, - &tdata); + &tdata); if (status == PJ_SUCCESS && tdata) - status = pjsip_inv_send_msg(replaced_inv, tdata); + status = pjsip_inv_send_msg(replaced_inv, tdata); if (status != PJ_SUCCESS) - pjsua_perror(THIS_FILE, "Error terminating session", status); + pjsua_perror(THIS_FILE, "Error terminating session", status); return status; } @@ -1132,13 +1131,13 @@ static void process_pending_call_answer(pjsua_call *call) /* No initial answer yet, this function should be called again later */ if (!call->inv->last_answer) - return; + return; answer = call->async_call.call_var.inc_call.answers.next; while (answer != &call->async_call.call_var.inc_call.answers) { next = answer->next; - pjsua_call_answer2(call->index, answer->opt, answer->code, - answer->reason, answer->msg_data); + pjsua_call_answer2(call->index, answer->opt, answer->code, + answer->reason, answer->msg_data); /* Call might have been disconnected if application is answering * with 200/OK and the media failed to start. @@ -1158,21 +1157,21 @@ static pj_status_t process_pending_call_hangup(pjsua_call *call) pj_status_t status; PJ_LOG(4,(THIS_FILE, "Call %d processing pending hangup: code=%d..", - call->index, call->last_code)); + call->index, call->last_code)); pj_log_push_indent(); status = acquire_call("pending_hangup()", call->index, &call, &dlg); if (status != PJ_SUCCESS) { - PJ_LOG(3, (THIS_FILE, "Call %d failed to process pending hangup", - call->index)); - goto on_return; + PJ_LOG(3, (THIS_FILE, "Call %d failed to process pending hangup", + call->index)); + goto on_return; } pjsua_media_channel_deinit(call->index); pjsua_check_snd_dev_idle(); if (call->inv) - call_inv_end_session(call, call->last_code, &call->last_text, NULL); + call_inv_end_session(call, call->last_code, &call->last_text, NULL); on_return: if (dlg) pjsip_dlg_dec_lock(dlg); @@ -1181,8 +1180,8 @@ static pj_status_t process_pending_call_hangup(pjsua_call *call) } pj_status_t create_temp_sdp(pj_pool_t *pool, - const pjmedia_sdp_session *rem_sdp, - pjmedia_sdp_session **p_sdp) + const pjmedia_sdp_session *rem_sdp, + pjmedia_sdp_session **p_sdp) { const pj_str_t STR_AUDIO = { "audio", 5 }; const pj_str_t STR_VIDEO = { "video", 5 }; @@ -1203,90 +1202,90 @@ pj_status_t create_temp_sdp(pj_pool_t *pool, status = pjmedia_endpt_create_base_sdp(pjsua_var.med_endpt, pool, NULL, &origin, &sdp); if (status != PJ_SUCCESS) - return status; + return status; if (rem_sdp->conn && pj_stricmp(&rem_sdp->conn->addr_type, &STR_IP6)==0) { - sess_use_ipv4 = PJ_FALSE; + sess_use_ipv4 = PJ_FALSE; } for (; i< rem_sdp->media_count ; ++i) { - pjmedia_sdp_media *m = NULL; - pjmedia_sock_info sock_info; - pj_bool_t med_use_ipv4 = sess_use_ipv4; - - if (rem_sdp->media[i]->conn && - pj_stricmp(&rem_sdp->media[i]->conn->addr_type, &STR_IP6) == 0) - { - med_use_ipv4 = PJ_FALSE; - } - - pj_sockaddr_init(med_use_ipv4?PJ_AF_INET:PJ_AF_INET6, - &sock_info.rtp_addr_name, - med_use_ipv4?pj_strset2(&tmp_st, "127.0.0.1"): - pj_strset2(&tmp_st, "::1"), - rem_sdp->media[i]->desc.port? (tmp_port++):0); - - pj_sockaddr_init(med_use_ipv4?PJ_AF_INET:PJ_AF_INET6, - &sock_info.rtcp_addr_name, - med_use_ipv4?pj_strset2(&tmp_st, "127.0.0.1"): - pj_strset2(&tmp_st, "::1"), - rem_sdp->media[i]->desc.port? (tmp_port++):0); - - if (pj_stricmp(&rem_sdp->media[i]->desc.media, &STR_AUDIO)==0) { - m = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_media); - status = pjmedia_endpt_create_audio_sdp(pjsua_var.med_endpt, - pool, &sock_info, 0, &m); - - if (status != PJ_SUCCESS) - return status; - - } else if (pj_stricmp(&rem_sdp->media[i]->desc.media, &STR_VIDEO)==0) { + pjmedia_sdp_media *m = NULL; + pjmedia_sock_info sock_info; + pj_bool_t med_use_ipv4 = sess_use_ipv4; + + if (rem_sdp->media[i]->conn && + pj_stricmp(&rem_sdp->media[i]->conn->addr_type, &STR_IP6) == 0) + { + med_use_ipv4 = PJ_FALSE; + } + + pj_sockaddr_init(med_use_ipv4?PJ_AF_INET:PJ_AF_INET6, + &sock_info.rtp_addr_name, + med_use_ipv4?pj_strset2(&tmp_st, "127.0.0.1"): + pj_strset2(&tmp_st, "::1"), + rem_sdp->media[i]->desc.port? (tmp_port++):0); + + pj_sockaddr_init(med_use_ipv4?PJ_AF_INET:PJ_AF_INET6, + &sock_info.rtcp_addr_name, + med_use_ipv4?pj_strset2(&tmp_st, "127.0.0.1"): + pj_strset2(&tmp_st, "::1"), + rem_sdp->media[i]->desc.port? (tmp_port++):0); + + if (pj_stricmp(&rem_sdp->media[i]->desc.media, &STR_AUDIO)==0) { + m = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_media); + status = pjmedia_endpt_create_audio_sdp(pjsua_var.med_endpt, + pool, &sock_info, 0, &m); + + if (status != PJ_SUCCESS) + return status; + + } else if (pj_stricmp(&rem_sdp->media[i]->desc.media, &STR_VIDEO)==0) { #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) - m = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_media); - status = pjmedia_endpt_create_video_sdp(pjsua_var.med_endpt, pool, - &sock_info, 0, &m); - if (status != PJ_SUCCESS) - return status; -#else - m = pjmedia_sdp_media_clone_deactivate(pool, rem_sdp->media[i]); -#endif - } else { - m = pjmedia_sdp_media_clone_deactivate(pool, rem_sdp->media[i]); - } - if (status != PJ_SUCCESS) - return status; - - /* Add connection line, if none */ - if (m->conn == NULL && sdp->conn == NULL) { - m->conn = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_conn); - m->conn->net_type = pj_str("IN"); - if (med_use_ipv4) { - m->conn->addr_type = pj_str("IP4"); - m->conn->addr = pj_str("127.0.0.1"); - } else { - m->conn->addr_type = pj_str("IP6"); - m->conn->addr = pj_str("::1"); - } - } - - /* Disable media if it has zero format/codec */ - if (m->desc.fmt_count == 0) { - m->desc.fmt[m->desc.fmt_count++] = pj_str("0"); - pjmedia_sdp_media_deactivate(pool, m); - } - - sdp->media[sdp->media_count++] = m; - } + m = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_media); + status = pjmedia_endpt_create_video_sdp(pjsua_var.med_endpt, pool, + &sock_info, 0, &m); + if (status != PJ_SUCCESS) + return status; +#else + m = pjmedia_sdp_media_clone_deactivate(pool, rem_sdp->media[i]); +#endif + } else { + m = pjmedia_sdp_media_clone_deactivate(pool, rem_sdp->media[i]); + } + if (status != PJ_SUCCESS) + return status; + + /* Add connection line, if none */ + if (m->conn == NULL && sdp->conn == NULL) { + m->conn = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_conn); + m->conn->net_type = pj_str("IN"); + if (med_use_ipv4) { + m->conn->addr_type = pj_str("IP4"); + m->conn->addr = pj_str("127.0.0.1"); + } else { + m->conn->addr_type = pj_str("IP6"); + m->conn->addr = pj_str("::1"); + } + } + + /* Disable media if it has zero format/codec */ + if (m->desc.fmt_count == 0) { + m->desc.fmt[m->desc.fmt_count++] = pj_str("0"); + pjmedia_sdp_media_deactivate(pool, m); + } + + sdp->media[sdp->media_count++] = m; + } *p_sdp = sdp; return PJ_SUCCESS; } static pj_status_t verify_request(const pjsua_call *call, - pjsip_rx_data *rdata, - pj_bool_t use_tmp_sdp, - int *sip_err_code, - pjsip_tx_data **response) + pjsip_rx_data *rdata, + pj_bool_t use_tmp_sdp, + int *sip_err_code, + pjsip_tx_data **response) { const pjmedia_sdp_session *offer = NULL; pjmedia_sdp_session *answer; @@ -1296,62 +1295,62 @@ static pj_status_t verify_request(const pjsua_call *call, /* Get remote SDP offer (if any). */ if (call->inv->neg) { - pjmedia_sdp_neg_get_neg_remote(call->inv->neg, &offer); + pjmedia_sdp_neg_get_neg_remote(call->inv->neg, &offer); } if (use_tmp_sdp) { - if (offer == NULL) - return PJ_SUCCESS; - - /* Create temporary SDP to check for codec support and capability - * to handle the required SIP extensions. - */ - status = create_temp_sdp(call->inv->pool_prov, offer, &answer); - - if (status != PJ_SUCCESS) { - err_code = PJSIP_SC_INTERNAL_SERVER_ERROR; - pjsua_perror(THIS_FILE, "Error creating SDP answer", status); - } + if (offer == NULL) + return PJ_SUCCESS; + + /* Create temporary SDP to check for codec support and capability + * to handle the required SIP extensions. + */ + status = create_temp_sdp(call->inv->pool_prov, offer, &answer); + + if (status != PJ_SUCCESS) { + err_code = PJSIP_SC_INTERNAL_SERVER_ERROR; + pjsua_perror(THIS_FILE, "Error creating SDP answer", status); + } } else { - status = pjsua_media_channel_create_sdp(call->index, - call->async_call.dlg->pool, - offer, &answer, sip_err_code); - - if (status != PJ_SUCCESS) { - err_code = *sip_err_code; - pjsua_perror(THIS_FILE, "Error creating SDP answer", status); - } else { - status = pjsip_inv_set_local_sdp(call->inv, answer); - if (status != PJ_SUCCESS) { - err_code = PJSIP_SC_NOT_ACCEPTABLE_HERE; - pjsua_perror(THIS_FILE, "Error setting local SDP", status); - } - } + status = pjsua_media_channel_create_sdp(call->index, + call->async_call.dlg->pool, + offer, &answer, sip_err_code); + + if (status != PJ_SUCCESS) { + err_code = *sip_err_code; + pjsua_perror(THIS_FILE, "Error creating SDP answer", status); + } else { + status = pjsip_inv_set_local_sdp(call->inv, answer); + if (status != PJ_SUCCESS) { + err_code = PJSIP_SC_NOT_ACCEPTABLE_HERE; + pjsua_perror(THIS_FILE, "Error setting local SDP", status); + } + } } if (status == PJ_SUCCESS) { - unsigned options = 0; - - /* Verify that we can handle the request. */ - status = pjsip_inv_verify_request3(rdata, - call->inv->pool_prov, &options, - offer, answer, NULL, - pjsua_var.endpt, response); - if (status != PJ_SUCCESS) { - /* - * No we can't handle the incoming INVITE request. - */ - pjsua_perror(THIS_FILE, "Request verification failed", status); - - if (response) - err_code = (*response)->msg->line.status.code; - else - err_code = PJSIP_SC_NOT_ACCEPTABLE_HERE; - } + unsigned options = 0; + + /* Verify that we can handle the request. */ + status = pjsip_inv_verify_request3(rdata, + call->inv->pool_prov, &options, + offer, answer, NULL, + pjsua_var.endpt, response); + if (status != PJ_SUCCESS) { + /* + * No we can't handle the incoming INVITE request. + */ + pjsua_perror(THIS_FILE, "Request verification failed", status); + + if (response) + err_code = (*response)->msg->line.status.code; + else + err_code = PJSIP_SC_NOT_ACCEPTABLE_HERE; + } } if (sip_err_code && status != PJ_SUCCESS) - *sip_err_code = err_code? err_code:PJSIP_ERRNO_TO_SIP_STATUS(status); + *sip_err_code = err_code? err_code:PJSIP_ERRNO_TO_SIP_STATUS(status); return status; } @@ -1359,10 +1358,10 @@ static pj_status_t verify_request(const pjsua_call *call, /* Incoming call callback when media transport creation is completed. */ static pj_status_t on_incoming_call_med_tp_complete2(pjsua_call_id call_id, - const pjsua_med_tp_state_info *info, - pjsip_rx_data *rdata, - int *sip_err_code, - pjsip_tx_data **tdata) + const pjsua_med_tp_state_info *info, + pjsip_rx_data *rdata, + int *sip_err_code, + pjsip_tx_data **tdata) { pjsua_call *call = &pjsua_var.calls[call_id]; pjsip_dialog *dlg = call->async_call.dlg; @@ -1381,7 +1380,7 @@ on_incoming_call_med_tp_complete2(pjsua_call_id call_id, pjsip_dlg_dec_session(dlg, &pjsua_var.mod); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error initializing media channel", status); + pjsua_perror(THIS_FILE, "Error initializing media channel", status); goto on_return; } @@ -1398,11 +1397,11 @@ on_incoming_call_med_tp_complete2(pjsua_call_id call_id, on_return: if (status != PJ_SUCCESS) { - if (err_code == 0) - err_code = PJSIP_ERRNO_TO_SIP_STATUS(status); + if (err_code == 0) + err_code = PJSIP_ERRNO_TO_SIP_STATUS(status); - if (sip_err_code) - *sip_err_code = err_code; + if (sip_err_code) + *sip_err_code = err_code; /* If the callback is called from pjsua_call_on_incoming(), the * invite's state is PJSIP_INV_STATE_NULL, so the invite session @@ -1411,14 +1410,14 @@ on_incoming_call_med_tp_complete2(pjsua_call_id call_id, if (call->inv->state > PJSIP_INV_STATE_NULL) { pj_status_t status_ = PJ_SUCCESS; - if (response == NULL) { - status_ = pjsip_inv_end_session(call->inv, err_code, NULL, - &response); - } + if (response == NULL) { + status_ = pjsip_inv_end_session(call->inv, err_code, NULL, + &response); + } - if (status_ == PJ_SUCCESS && response) - status_ = pjsip_inv_send_msg(call->inv, response); - } + if (status_ == PJ_SUCCESS && response) + status_ = pjsip_inv_send_msg(call->inv, response); + } pjsua_media_channel_deinit(call->index); } @@ -1429,21 +1428,21 @@ on_incoming_call_med_tp_complete2(pjsua_call_id call_id, /* Finish any pending process */ if (status == PJ_SUCCESS) { - if (call->async_call.call_var.inc_call.replaced_dlg) { - /* Process pending call replace */ - pjsip_dialog *replaced_dlg = - call->async_call.call_var.inc_call.replaced_dlg; - process_incoming_call_replace(call, replaced_dlg); - } else { - /* Process pending call answers */ - process_pending_call_answer(call); - } + if (call->async_call.call_var.inc_call.replaced_dlg) { + /* Process pending call replace */ + pjsip_dialog *replaced_dlg = + call->async_call.call_var.inc_call.replaced_dlg; + process_incoming_call_replace(call, replaced_dlg); + } else { + /* Process pending call answers */ + process_pending_call_answer(call); + } } pjsip_dlg_dec_lock(dlg); if (tdata) - *tdata = response; + *tdata = response; PJSUA_UNLOCK(); return status; @@ -1451,7 +1450,7 @@ on_incoming_call_med_tp_complete2(pjsua_call_id call_id, static pj_status_t on_incoming_call_med_tp_complete(pjsua_call_id call_id, - const pjsua_med_tp_state_info *info) + const pjsua_med_tp_state_info *info) { return on_incoming_call_med_tp_complete2(call_id, info, NULL, NULL, NULL); } @@ -1481,20 +1480,20 @@ pj_bool_t pjsua_call_on_incoming(pjsip_rx_data *rdata) /* Don't want to handle anything but INVITE */ if (msg->line.req.method.id != PJSIP_INVITE_METHOD) - return PJ_FALSE; + return PJ_FALSE; /* Don't want to handle anything that's already associated with * existing dialog or transaction. */ if (dlg || tsx) - return PJ_FALSE; + return PJ_FALSE; /* Don't want to accept the call if shutdown is in progress */ if (pjsua_var.thread_quit_flag) { - pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, - PJSIP_SC_TEMPORARILY_UNAVAILABLE, NULL, - NULL, NULL); - return PJ_TRUE; + pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, + PJSIP_SC_TEMPORARILY_UNAVAILABLE, NULL, + NULL, NULL); + return PJ_TRUE; } PJ_LOG(4,(THIS_FILE, "Incoming %s", rdata->msg_info.info)); @@ -1506,12 +1505,12 @@ pj_bool_t pjsua_call_on_incoming(pjsip_rx_data *rdata) call_id = alloc_call_id(); if (call_id == PJSUA_INVALID_ID) { - pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, - PJSIP_SC_BUSY_HERE, NULL, - NULL, NULL); - PJ_LOG(2,(THIS_FILE, - "Unable to accept incoming call (too many calls)")); - goto on_return; + pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, + PJSIP_SC_BUSY_HERE, NULL, + NULL, NULL); + PJ_LOG(2,(THIS_FILE, + "Unable to accept incoming call (too many calls)")); + goto on_return; } /* Clear call descriptor */ @@ -1529,26 +1528,26 @@ pj_bool_t pjsua_call_on_incoming(pjsip_rx_data *rdata) * present, the function will make sure that we can handle the request. */ status = pjsip_replaces_verify_request(rdata, &replaced_dlg, PJ_FALSE, - &response); + &response); if (status != PJ_SUCCESS) { - /* - * Something wrong with the Replaces header. - */ - if (response) { - pjsip_response_addr res_addr; + /* + * Something wrong with the Replaces header. + */ + if (response) { + pjsip_response_addr res_addr; - pjsip_get_response_addr(response->pool, rdata, &res_addr); - status = pjsip_endpt_send_response(pjsua_var.endpt, &res_addr, response, - NULL, NULL); - if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(response); - } else { + pjsip_get_response_addr(response->pool, rdata, &res_addr); + status = pjsip_endpt_send_response(pjsua_var.endpt, &res_addr, response, + NULL, NULL); + if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(response); + } else { - /* Respond with 500 (Internal Server Error) */ - pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, 500, NULL, - NULL, NULL); - } + /* Respond with 500 (Internal Server Error) */ + pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, 500, NULL, + NULL, NULL); + } - goto on_return; + goto on_return; } /* If this INVITE request contains Replaces header, notify application @@ -1556,62 +1555,62 @@ pj_bool_t pjsua_call_on_incoming(pjsip_rx_data *rdata) * if it wants to. */ if (replaced_dlg != NULL && - (pjsua_var.ua_cfg.cb.on_call_replace_request || - pjsua_var.ua_cfg.cb.on_call_replace_request2)) + (pjsua_var.ua_cfg.cb.on_call_replace_request || + pjsua_var.ua_cfg.cb.on_call_replace_request2)) { - pjsua_call *replaced_call; - int st_code = 200; - pj_str_t st_text = { "OK", 2 }; - - /* Get the replaced call instance */ - replaced_call = (pjsua_call*) replaced_dlg->mod_data[pjsua_var.mod.id]; - - /* Copy call setting from the replaced call */ - call->opt = replaced_call->opt; - pjsua_call_cleanup_flag(&call->opt); - - /* Notify application */ - if (!replaced_call->hanging_up && - pjsua_var.ua_cfg.cb.on_call_replace_request) - { - pjsua_var.ua_cfg.cb.on_call_replace_request(replaced_call->index, - rdata, - &st_code, &st_text); - } - - if (!replaced_call->hanging_up && - pjsua_var.ua_cfg.cb.on_call_replace_request2) - { - pjsua_var.ua_cfg.cb.on_call_replace_request2(replaced_call->index, - rdata, - &st_code, &st_text, - &call->opt); - } - - /* Must specify final response */ - PJ_ASSERT_ON_FAIL(st_code >= 200, st_code = 200); - - /* Check if application rejects this request. */ - if (st_code >= 300) { - - if (st_text.slen == 2) - st_text = *pjsip_get_status_text(st_code); - - pjsip_endpt_respond(pjsua_var.endpt, NULL, rdata, - st_code, &st_text, NULL, NULL, NULL); - goto on_return; - } - - /* Set the user_data of the new call to the existing/parent call, - * it is needed by PJSUA2 to update its states. While PJSUA app can - * always override it anytime. - */ - pjsua_call_set_user_data(call_id, replaced_call->user_data); + pjsua_call *replaced_call; + int st_code = 200; + pj_str_t st_text = { "OK", 2 }; + + /* Get the replaced call instance */ + replaced_call = (pjsua_call*) replaced_dlg->mod_data[pjsua_var.mod.id]; + + /* Copy call setting from the replaced call */ + call->opt = replaced_call->opt; + pjsua_call_cleanup_flag(&call->opt); + + /* Notify application */ + if (!replaced_call->hanging_up && + pjsua_var.ua_cfg.cb.on_call_replace_request) + { + pjsua_var.ua_cfg.cb.on_call_replace_request(replaced_call->index, + rdata, + &st_code, &st_text); + } + + if (!replaced_call->hanging_up && + pjsua_var.ua_cfg.cb.on_call_replace_request2) + { + pjsua_var.ua_cfg.cb.on_call_replace_request2(replaced_call->index, + rdata, + &st_code, &st_text, + &call->opt); + } + + /* Must specify final response */ + PJ_ASSERT_ON_FAIL(st_code >= 200, st_code = 200); + + /* Check if application rejects this request. */ + if (st_code >= 300) { + + if (st_text.slen == 2) + st_text = *pjsip_get_status_text(st_code); + + pjsip_endpt_respond(pjsua_var.endpt, NULL, rdata, + st_code, &st_text, NULL, NULL, NULL); + goto on_return; + } + + /* Set the user_data of the new call to the existing/parent call, + * it is needed by PJSUA2 to update its states. While PJSUA app can + * always override it anytime. + */ + pjsua_call_set_user_data(call_id, replaced_call->user_data); } if (!replaced_dlg) { - /* Clone rdata. */ - pjsip_rx_data_clone(rdata, 0, &call->incoming_data); + /* Clone rdata. */ + pjsip_rx_data_clone(rdata, 0, &call->incoming_data); } /* @@ -1620,170 +1619,170 @@ pj_bool_t pjsua_call_on_incoming(pjsip_rx_data *rdata) * the call. */ if (replaced_dlg) { - /* For call replace, use the same account as the replaced call */ - pjsua_call *replaced_call; - replaced_call = (pjsua_call*)replaced_dlg->mod_data[pjsua_var.mod.id]; - acc_id = call->acc_id = replaced_call->acc_id; + /* For call replace, use the same account as the replaced call */ + pjsua_call *replaced_call; + replaced_call = (pjsua_call*)replaced_dlg->mod_data[pjsua_var.mod.id]; + acc_id = call->acc_id = replaced_call->acc_id; } else { - acc_id = call->acc_id = pjsua_acc_find_for_incoming(rdata); - if (acc_id == PJSUA_INVALID_ID) { - pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, - PJSIP_SC_TEMPORARILY_UNAVAILABLE, - NULL, NULL, NULL); + acc_id = call->acc_id = pjsua_acc_find_for_incoming(rdata); + if (acc_id == PJSUA_INVALID_ID) { + pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, + PJSIP_SC_TEMPORARILY_UNAVAILABLE, + NULL, NULL, NULL); - PJ_LOG(2,(THIS_FILE, - "Unable to accept incoming call (no available account)")); + PJ_LOG(2,(THIS_FILE, + "Unable to accept incoming call (no available account)")); - goto on_return; - } + goto on_return; + } } call->call_hold_type = pjsua_var.acc[acc_id].cfg.call_hold_type; /* Get call's secure level */ if (PJSIP_URI_SCHEME_IS_SIPS(rdata->msg_info.msg->line.req.uri)) - call->secure_level = 2; + call->secure_level = 2; else if (PJSIP_TRANSPORT_IS_SECURE(rdata->tp_info.transport)) - call->secure_level = 1; + call->secure_level = 1; else - call->secure_level = 0; + call->secure_level = 0; /* Parse SDP from incoming request */ if (rdata->msg_info.msg->body) { - pjsip_rdata_sdp_info *sdp_info; - - sdp_info = pjsip_rdata_get_sdp_info(rdata); - offer = sdp_info->sdp; - - status = sdp_info->sdp_err; - if (status==PJ_SUCCESS && sdp_info->sdp==NULL && - !PJSIP_INV_ACCEPT_UNKNOWN_BODY) - { - if (sdp_info->body.ptr == NULL) { - status = PJSIP_ERRNO_FROM_SIP_STATUS( - PJSIP_SC_UNSUPPORTED_MEDIA_TYPE); - } else { - status = PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_NOT_ACCEPTABLE); - } - } - - if (status != PJ_SUCCESS) { - pjsip_hdr hdr_list; - - /* Check if body really contains SDP. */ - if (sdp_info->body.ptr == NULL) { - /* Couldn't find "application/sdp" */ - pjsip_accept_hdr *acc; - - pjsua_perror(THIS_FILE, "Unknown Content-Type in incoming "\ - "INVITE", status); - - /* Add Accept header to response */ - acc = pjsip_accept_hdr_create(rdata->tp_info.pool); - PJ_ASSERT_RETURN(acc, PJ_ENOMEM); - acc->values[acc->count++] = pj_str("application/sdp"); - pj_list_init(&hdr_list); - pj_list_push_back(&hdr_list, acc); - - pjsip_endpt_respond(pjsua_var.endpt, NULL, rdata, - PJSIP_SC_UNSUPPORTED_MEDIA_TYPE, - NULL, &hdr_list, NULL, NULL); - } else { - const pj_str_t reason = pj_str("Bad SDP"); - pjsip_warning_hdr *w; - - pjsua_perror(THIS_FILE, "Bad SDP in incoming INVITE", - status); - - w = pjsip_warning_hdr_create_from_status(rdata->tp_info.pool, - pjsip_endpt_name(pjsua_var.endpt), - status); - pj_list_init(&hdr_list); - pj_list_push_back(&hdr_list, w); - - pjsip_endpt_respond(pjsua_var.endpt, NULL, rdata, 400, - &reason, &hdr_list, NULL, NULL); - } - goto on_return; - } - - /* Do quick checks on SDP before passing it to transports. More elabore - * checks will be done in pjsip_inv_verify_request2() below. - */ - if ((offer) && (offer->media_count==0)) { - const pj_str_t reason = pj_str("Missing media in SDP"); - pjsip_endpt_respond(pjsua_var.endpt, NULL, rdata, 400, &reason, - NULL, NULL, NULL); - goto on_return; - } + pjsip_rdata_sdp_info *sdp_info; + + sdp_info = pjsip_rdata_get_sdp_info(rdata); + offer = sdp_info->sdp; + + status = sdp_info->sdp_err; + if (status==PJ_SUCCESS && sdp_info->sdp==NULL && + !PJSIP_INV_ACCEPT_UNKNOWN_BODY) + { + if (sdp_info->body.ptr == NULL) { + status = PJSIP_ERRNO_FROM_SIP_STATUS( + PJSIP_SC_UNSUPPORTED_MEDIA_TYPE); + } else { + status = PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_NOT_ACCEPTABLE); + } + } + + if (status != PJ_SUCCESS) { + pjsip_hdr hdr_list; + + /* Check if body really contains SDP. */ + if (sdp_info->body.ptr == NULL) { + /* Couldn't find "application/sdp" */ + pjsip_accept_hdr *acc; + + pjsua_perror(THIS_FILE, "Unknown Content-Type in incoming "\ + "INVITE", status); + + /* Add Accept header to response */ + acc = pjsip_accept_hdr_create(rdata->tp_info.pool); + PJ_ASSERT_RETURN(acc, PJ_ENOMEM); + acc->values[acc->count++] = pj_str("application/sdp"); + pj_list_init(&hdr_list); + pj_list_push_back(&hdr_list, acc); + + pjsip_endpt_respond(pjsua_var.endpt, NULL, rdata, + PJSIP_SC_UNSUPPORTED_MEDIA_TYPE, + NULL, &hdr_list, NULL, NULL); + } else { + const pj_str_t reason = pj_str("Bad SDP"); + pjsip_warning_hdr *w; + + pjsua_perror(THIS_FILE, "Bad SDP in incoming INVITE", + status); + + w = pjsip_warning_hdr_create_from_status(rdata->tp_info.pool, + pjsip_endpt_name(pjsua_var.endpt), + status); + pj_list_init(&hdr_list); + pj_list_push_back(&hdr_list, w); + + pjsip_endpt_respond(pjsua_var.endpt, NULL, rdata, 400, + &reason, &hdr_list, NULL, NULL); + } + goto on_return; + } + + /* Do quick checks on SDP before passing it to transports. More elabore + * checks will be done in pjsip_inv_verify_request2() below. + */ + if ((offer) && (offer->media_count==0)) { + const pj_str_t reason = pj_str("Missing media in SDP"); + pjsip_endpt_respond(pjsua_var.endpt, NULL, rdata, 400, &reason, + NULL, NULL, NULL); + goto on_return; + } } else { - offer = NULL; + offer = NULL; } /* Verify that we can handle the request. */ options |= PJSIP_INV_SUPPORT_100REL; options |= PJSIP_INV_SUPPORT_TIMER; if (pjsua_var.acc[acc_id].cfg.require_100rel == PJSUA_100REL_MANDATORY) - options |= PJSIP_INV_REQUIRE_100REL; + options |= PJSIP_INV_REQUIRE_100REL; if (pjsua_var.acc[acc_id].cfg.ice_cfg.enable_ice) { - options |= PJSIP_INV_SUPPORT_ICE; - if (pjsua_var.acc[acc_id].cfg.ice_cfg.ice_opt.trickle != - PJ_ICE_SESS_TRICKLE_DISABLED) - { - options |= PJSIP_INV_SUPPORT_TRICKLE_ICE; - } + options |= PJSIP_INV_SUPPORT_ICE; + if (pjsua_var.acc[acc_id].cfg.ice_cfg.ice_opt.trickle != + PJ_ICE_SESS_TRICKLE_DISABLED) + { + options |= PJSIP_INV_SUPPORT_TRICKLE_ICE; + } } if (pjsua_var.acc[acc_id].cfg.use_timer == PJSUA_SIP_TIMER_REQUIRED) - options |= PJSIP_INV_REQUIRE_TIMER; + options |= PJSIP_INV_REQUIRE_TIMER; else if (pjsua_var.acc[acc_id].cfg.use_timer == PJSUA_SIP_TIMER_ALWAYS) - options |= PJSIP_INV_ALWAYS_USE_TIMER; + options |= PJSIP_INV_ALWAYS_USE_TIMER; status = pjsip_inv_verify_request2(rdata, &options, offer, NULL, NULL, - pjsua_var.endpt, &response); + pjsua_var.endpt, &response); if (status != PJ_SUCCESS) { - /* - * No we can't handle the incoming INVITE request. - */ - if (response) { - pjsip_response_addr res_addr; + /* + * No we can't handle the incoming INVITE request. + */ + if (response) { + pjsip_response_addr res_addr; - pjsip_get_response_addr(response->pool, rdata, &res_addr); - status = pjsip_endpt_send_response(pjsua_var.endpt, &res_addr, response, - NULL, NULL); - if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(response); + pjsip_get_response_addr(response->pool, rdata, &res_addr); + status = pjsip_endpt_send_response(pjsua_var.endpt, &res_addr, response, + NULL, NULL); + if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(response); - } else { - /* Respond with 500 (Internal Server Error) */ - pjsip_endpt_respond(pjsua_var.endpt, NULL, rdata, 500, NULL, - NULL, NULL, NULL); - } + } else { + /* Respond with 500 (Internal Server Error) */ + pjsip_endpt_respond(pjsua_var.endpt, NULL, rdata, 500, NULL, + NULL, NULL, NULL); + } - goto on_return; + goto on_return; } /* Get suitable Contact header */ if (pjsua_var.acc[acc_id].contact.slen) { - contact = pjsua_var.acc[acc_id].contact; + contact = pjsua_var.acc[acc_id].contact; } else { - status = pjsua_acc_create_uas_contact(rdata->tp_info.pool, &contact, - acc_id, rdata); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to generate Contact header", - status); - pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, 500, NULL, - NULL, NULL); - goto on_return; - } + status = pjsua_acc_create_uas_contact(rdata->tp_info.pool, &contact, + acc_id, rdata); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to generate Contact header", + status); + pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, 500, NULL, + NULL, NULL); + goto on_return; + } } /* Create dialog: */ status = pjsip_dlg_create_uas_and_inc_lock( pjsip_ua_instance(), rdata, - &contact, &dlg); + &contact, &dlg); if (status != PJ_SUCCESS) { - pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, 500, NULL, - NULL, NULL); - goto on_return; + pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, 500, NULL, + NULL, NULL); + goto on_return; } if (pjsua_var.acc[acc_id].cfg.allow_via_rewrite && @@ -1792,92 +1791,92 @@ pj_bool_t pjsua_call_on_incoming(pjsip_rx_data *rdata) pjsip_dlg_set_via_sent_by(dlg, &pjsua_var.acc[acc_id].via_addr, pjsua_var.acc[acc_id].via_tp); } else if (!pjsua_sip_acc_is_using_stun(acc_id) && - !pjsua_sip_acc_is_using_upnp(acc_id)) + !pjsua_sip_acc_is_using_upnp(acc_id)) { - /* Choose local interface to use in Via if acc is not using - * STUN nor UPnP. See https://github.com/pjsip/pjproject/issues/1804 - */ - char target_buf[PJSIP_MAX_URL_SIZE]; - pj_str_t target; - pjsip_host_port via_addr; - const void *via_tp; - - target.ptr = target_buf; - target.slen = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, - dlg->target, - target_buf, sizeof(target_buf)); - if (target.slen < 0) target.slen = 0; - - if (pjsua_acc_get_uac_addr(acc_id, dlg->pool, &target, - &via_addr, NULL, NULL, - &via_tp) == PJ_SUCCESS) - { - pjsip_dlg_set_via_sent_by(dlg, &via_addr, - (pjsip_transport*)via_tp); - } + /* Choose local interface to use in Via if acc is not using + * STUN nor UPnP. See https://github.com/pjsip/pjproject/issues/1804 + */ + char target_buf[PJSIP_MAX_URL_SIZE]; + pj_str_t target; + pjsip_host_port via_addr; + const void *via_tp; + + target.ptr = target_buf; + target.slen = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, + dlg->target, + target_buf, sizeof(target_buf)); + if (target.slen < 0) target.slen = 0; + + if (pjsua_acc_get_uac_addr(acc_id, dlg->pool, &target, + &via_addr, NULL, NULL, + &via_tp) == PJ_SUCCESS) + { + pjsip_dlg_set_via_sent_by(dlg, &via_addr, + (pjsip_transport*)via_tp); + } } /* Set credentials */ if (pjsua_var.acc[acc_id].cred_cnt) { - pjsip_auth_clt_set_credentials(&dlg->auth_sess, - pjsua_var.acc[acc_id].cred_cnt, - pjsua_var.acc[acc_id].cred); + pjsip_auth_clt_set_credentials(&dlg->auth_sess, + pjsua_var.acc[acc_id].cred_cnt, + pjsua_var.acc[acc_id].cred); } /* Set preference */ pjsip_auth_clt_set_prefs(&dlg->auth_sess, - &pjsua_var.acc[acc_id].cfg.auth_pref); + &pjsua_var.acc[acc_id].cfg.auth_pref); /* Disable Session Timers if not prefered and the incoming INVITE request * did not require it. */ if (pjsua_var.acc[acc_id].cfg.use_timer == PJSUA_SIP_TIMER_INACTIVE && - (options & PJSIP_INV_REQUIRE_TIMER) == 0) + (options & PJSIP_INV_REQUIRE_TIMER) == 0) { - options &= ~(PJSIP_INV_SUPPORT_TIMER); + options &= ~(PJSIP_INV_SUPPORT_TIMER); } /* If 100rel is optional and UAC supports it, use it. */ if ((options & PJSIP_INV_REQUIRE_100REL)==0 && - pjsua_var.acc[acc_id].cfg.require_100rel == PJSUA_100REL_OPTIONAL) + pjsua_var.acc[acc_id].cfg.require_100rel == PJSUA_100REL_OPTIONAL) { - const pj_str_t token = { "100rel", 6}; - pjsip_dialog_cap_status cap_status; + const pj_str_t token = { "100rel", 6}; + pjsip_dialog_cap_status cap_status; - cap_status = pjsip_dlg_remote_has_cap(dlg, PJSIP_H_SUPPORTED, NULL, - &token); - if (cap_status == PJSIP_DIALOG_CAP_SUPPORTED) - options |= PJSIP_INV_REQUIRE_100REL; + cap_status = pjsip_dlg_remote_has_cap(dlg, PJSIP_H_SUPPORTED, NULL, + &token); + if (cap_status == PJSIP_DIALOG_CAP_SUPPORTED) + options |= PJSIP_INV_REQUIRE_100REL; } /* Create invite session: */ status = pjsip_inv_create_uas( dlg, rdata, NULL, options, &inv); if (status != PJ_SUCCESS) { - pjsip_hdr hdr_list; - pjsip_warning_hdr *w; + pjsip_hdr hdr_list; + pjsip_warning_hdr *w; - w = pjsip_warning_hdr_create_from_status(dlg->pool, - pjsip_endpt_name(pjsua_var.endpt), - status); - pj_list_init(&hdr_list); - pj_list_push_back(&hdr_list, w); + w = pjsip_warning_hdr_create_from_status(dlg->pool, + pjsip_endpt_name(pjsua_var.endpt), + status); + pj_list_init(&hdr_list); + pj_list_push_back(&hdr_list, w); - pjsip_dlg_respond(dlg, rdata, 500, NULL, &hdr_list, NULL); + pjsip_dlg_respond(dlg, rdata, 500, NULL, &hdr_list, NULL); - /* Can't terminate dialog because transaction is in progress. - pjsip_dlg_terminate(dlg); - */ - goto on_return; + /* Can't terminate dialog because transaction is in progress. + pjsip_dlg_terminate(dlg); + */ + goto on_return; } /* If account is locked to specific transport, then lock dialog * to this transport too. */ if (pjsua_var.acc[acc_id].cfg.transport_id != PJSUA_INVALID_ID) { - pjsip_tpselector tp_sel; + pjsip_tpselector tp_sel; - pjsua_init_tpselector(pjsua_var.acc[acc_id].cfg.transport_id, &tp_sel); - pjsip_dlg_set_transport(dlg, &tp_sel); + pjsua_init_tpselector(pjsua_var.acc[acc_id].cfg.transport_id, &tp_sel); + pjsip_dlg_set_transport(dlg, &tp_sel); } /* Create and attach pjsua_var data to the dialog */ @@ -1898,130 +1897,130 @@ pj_bool_t pjsua_call_on_incoming(pjsip_rx_data *rdata) */ if (offer || replaced_dlg) { - /* This is only for initial verification, it will check the SDP for - * codec support and the capability to handle the required - * SIP extensions. - */ - status = verify_request(call, rdata, PJ_TRUE, &sip_err_code, - &response); - - if (status != PJ_SUCCESS) { - pjsip_dlg_inc_lock(dlg); - - if (response) { - pjsip_dlg_send_response(dlg, call->inv->invite_tsx, response); - } else { - pjsip_dlg_respond(dlg, rdata, sip_err_code, NULL, NULL, NULL); - } - - if (call->inv && call->inv->dlg) { - pjsip_inv_terminate(call->inv, sip_err_code, PJ_FALSE); - } - pjsip_dlg_dec_lock(dlg); - - call->inv = NULL; - call->async_call.dlg = NULL; - goto on_return; - } - status = pjsua_media_channel_init(call->index, PJSIP_ROLE_UAS, - call->secure_level, - rdata->tp_info.pool, - offer, - &sip_err_code, PJ_TRUE, - &on_incoming_call_med_tp_complete); - if (status == PJ_EPENDING) { - /* on_incoming_call_med_tp_complete() will call - * pjsip_dlg_dec_session(). - */ - should_dec_dlg = PJ_FALSE; - } else if (status == PJ_SUCCESS) { - /* on_incoming_call_med_tp_complete2() will call - * pjsip_dlg_dec_session(). - */ - should_dec_dlg = PJ_FALSE; - - status = on_incoming_call_med_tp_complete2(call_id, NULL, - rdata, &sip_err_code, - &response); - if (status != PJ_SUCCESS) { - /* Since the call invite's state is still PJSIP_INV_STATE_NULL, - * the invite session was not ended in - * on_incoming_call_med_tp_complete(), so we need to send - * a response message and terminate the invite here. - */ - pjsip_dlg_inc_lock(dlg); - - if (response) { - pjsip_dlg_send_response(dlg, call->inv->invite_tsx, - response); - - } else { - pjsip_dlg_respond(dlg, rdata, sip_err_code, NULL, NULL, - NULL); - } - - if (call->inv && call->inv->dlg) { - pjsip_inv_terminate(call->inv, sip_err_code, PJ_FALSE); - } - pjsip_dlg_dec_lock(dlg); - - call->inv = NULL; - call->async_call.dlg = NULL; - goto on_return; - } - } else if (status != PJ_EPENDING) { - pjsua_perror(THIS_FILE, "Error initializing media channel", status); - - pjsip_dlg_inc_lock(dlg); - pjsip_dlg_respond(dlg, rdata, sip_err_code, NULL, NULL, NULL); - if (call->inv && call->inv->dlg) { - pjsip_inv_terminate(call->inv, sip_err_code, PJ_FALSE); - } - pjsip_dlg_dec_lock(dlg); - - call->inv = NULL; - call->async_call.dlg = NULL; - goto on_return; - } + /* This is only for initial verification, it will check the SDP for + * codec support and the capability to handle the required + * SIP extensions. + */ + status = verify_request(call, rdata, PJ_TRUE, &sip_err_code, + &response); + + if (status != PJ_SUCCESS) { + pjsip_dlg_inc_lock(dlg); + + if (response) { + pjsip_dlg_send_response(dlg, call->inv->invite_tsx, response); + } else { + pjsip_dlg_respond(dlg, rdata, sip_err_code, NULL, NULL, NULL); + } + + if (call->inv && call->inv->dlg) { + pjsip_inv_terminate(call->inv, sip_err_code, PJ_FALSE); + } + pjsip_dlg_dec_lock(dlg); + + call->inv = NULL; + call->async_call.dlg = NULL; + goto on_return; + } + status = pjsua_media_channel_init(call->index, PJSIP_ROLE_UAS, + call->secure_level, + rdata->tp_info.pool, + offer, + &sip_err_code, PJ_TRUE, + &on_incoming_call_med_tp_complete); + if (status == PJ_EPENDING) { + /* on_incoming_call_med_tp_complete() will call + * pjsip_dlg_dec_session(). + */ + should_dec_dlg = PJ_FALSE; + } else if (status == PJ_SUCCESS) { + /* on_incoming_call_med_tp_complete2() will call + * pjsip_dlg_dec_session(). + */ + should_dec_dlg = PJ_FALSE; + + status = on_incoming_call_med_tp_complete2(call_id, NULL, + rdata, &sip_err_code, + &response); + if (status != PJ_SUCCESS) { + /* Since the call invite's state is still PJSIP_INV_STATE_NULL, + * the invite session was not ended in + * on_incoming_call_med_tp_complete(), so we need to send + * a response message and terminate the invite here. + */ + pjsip_dlg_inc_lock(dlg); + + if (response) { + pjsip_dlg_send_response(dlg, call->inv->invite_tsx, + response); + + } else { + pjsip_dlg_respond(dlg, rdata, sip_err_code, NULL, NULL, + NULL); + } + + if (call->inv && call->inv->dlg) { + pjsip_inv_terminate(call->inv, sip_err_code, PJ_FALSE); + } + pjsip_dlg_dec_lock(dlg); + + call->inv = NULL; + call->async_call.dlg = NULL; + goto on_return; + } + } else if (status != PJ_EPENDING) { + pjsua_perror(THIS_FILE, "Error initializing media channel", status); + + pjsip_dlg_inc_lock(dlg); + pjsip_dlg_respond(dlg, rdata, sip_err_code, NULL, NULL, NULL); + if (call->inv && call->inv->dlg) { + pjsip_inv_terminate(call->inv, sip_err_code, PJ_FALSE); + } + pjsip_dlg_dec_lock(dlg); + + call->inv = NULL; + call->async_call.dlg = NULL; + goto on_return; + } } /* Create answer */ /* status = pjsua_media_channel_create_sdp(call->index, rdata->tp_info.pool, - offer, &answer, &sip_err_code); + offer, &answer, &sip_err_code); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating SDP answer", status); - pjsip_endpt_respond(pjsua_var.endpt, NULL, rdata, - sip_err_code, NULL, NULL, NULL, NULL); - goto on_return; + pjsua_perror(THIS_FILE, "Error creating SDP answer", status); + pjsip_endpt_respond(pjsua_var.endpt, NULL, rdata, + sip_err_code, NULL, NULL, NULL, NULL); + goto on_return; } */ /* Init Session Timers */ status = pjsip_timer_init_session(inv, - &pjsua_var.acc[acc_id].cfg.timer_setting); + &pjsua_var.acc[acc_id].cfg.timer_setting); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Session Timer init failed", status); + pjsua_perror(THIS_FILE, "Session Timer init failed", status); pjsip_dlg_respond(dlg, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL, NULL); - pjsip_inv_terminate(inv, PJSIP_SC_INTERNAL_SERVER_ERROR, PJ_FALSE); + pjsip_inv_terminate(inv, PJSIP_SC_INTERNAL_SERVER_ERROR, PJ_FALSE); - pjsua_media_channel_deinit(call->index); - call->inv = NULL; - call->async_call.dlg = NULL; + pjsua_media_channel_deinit(call->index); + call->inv = NULL; + call->async_call.dlg = NULL; - goto on_return; + goto on_return; } /* Update NAT type of remote endpoint, only when there is SDP in * incoming INVITE! */ if (pjsua_var.ua_cfg.nat_type_in_sdp && inv->neg && - pjmedia_sdp_neg_get_state(inv->neg) > PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) + pjmedia_sdp_neg_get_state(inv->neg) > PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) { - const pjmedia_sdp_session *remote_sdp; + const pjmedia_sdp_session *remote_sdp; - if (pjmedia_sdp_neg_get_neg_remote(inv->neg, &remote_sdp)==PJ_SUCCESS) - update_remote_nat_type(call, remote_sdp); + if (pjmedia_sdp_neg_get_neg_remote(inv->neg, &remote_sdp)==PJ_SUCCESS) + update_remote_nat_type(call, remote_sdp); } /* Must answer with some response to initial INVITE. We'll do this before @@ -2033,33 +2032,33 @@ pj_bool_t pjsua_call_on_incoming(pjsip_rx_data *rdata) * callback is called, which is not right). */ status = pjsip_inv_initial_answer(inv, rdata, - 100, NULL, NULL, &response); + 100, NULL, NULL, &response); if (status != PJ_SUCCESS) { - if (response == NULL) { - pjsua_perror(THIS_FILE, "Unable to send answer to incoming INVITE", - status); - pjsip_dlg_respond(dlg, rdata, 500, NULL, NULL, NULL); - pjsip_inv_terminate(inv, 500, PJ_FALSE); - } else { - pjsip_inv_send_msg(inv, response); - pjsip_inv_terminate(inv, response->msg->line.status.code, - PJ_FALSE); - } - pjsua_media_channel_deinit(call->index); - call->inv = NULL; - call->async_call.dlg = NULL; - goto on_return; + if (response == NULL) { + pjsua_perror(THIS_FILE, "Unable to send answer to incoming INVITE", + status); + pjsip_dlg_respond(dlg, rdata, 500, NULL, NULL, NULL); + pjsip_inv_terminate(inv, 500, PJ_FALSE); + } else { + pjsip_inv_send_msg(inv, response); + pjsip_inv_terminate(inv, response->msg->line.status.code, + PJ_FALSE); + } + pjsua_media_channel_deinit(call->index); + call->inv = NULL; + call->async_call.dlg = NULL; + goto on_return; } else { #if !PJSUA_DISABLE_AUTO_SEND_100 - status = pjsip_inv_send_msg(inv, response); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send 100 response", status); - pjsua_media_channel_deinit(call->index); - call->inv = NULL; - call->async_call.dlg = NULL; - goto on_return; - } + status = pjsip_inv_send_msg(inv, response); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to send 100 response", status); + pjsua_media_channel_deinit(call->index); + call->inv = NULL; + call->async_call.dlg = NULL; + goto on_return; + } #endif } @@ -2067,68 +2066,68 @@ pj_bool_t pjsua_call_on_incoming(pjsip_rx_data *rdata) * above) */ if (dlg->mod_data[pjsua_var.mod.id] == NULL) { - /* In PJSUA2, on_incoming_call() may be called from - * on_media_transport_created() hence this might already set - * to allow notification about fail events via on_call_state() and - * on_call_tsx_state(). - */ - dlg->mod_data[pjsua_var.mod.id] = call; - inv->mod_data[pjsua_var.mod.id] = call; - ++pjsua_var.call_cnt; + /* In PJSUA2, on_incoming_call() may be called from + * on_media_transport_created() hence this might already set + * to allow notification about fail events via on_call_state() and + * on_call_tsx_state(). + */ + dlg->mod_data[pjsua_var.mod.id] = call; + inv->mod_data[pjsua_var.mod.id] = call; + ++pjsua_var.call_cnt; } /* Check if this request should replace existing call */ if (replaced_dlg) { - /* Process call replace. If the media channel init has been completed, - * just process now, otherwise, just queue the replaced dialog so - * it will be processed once the media channel async init is finished - * successfully. - */ - if (call->med_ch_cb == NULL) { - process_incoming_call_replace(call, replaced_dlg); - } else { - call->async_call.call_var.inc_call.replaced_dlg = replaced_dlg; - } + /* Process call replace. If the media channel init has been completed, + * just process now, otherwise, just queue the replaced dialog so + * it will be processed once the media channel async init is finished + * successfully. + */ + if (call->med_ch_cb == NULL) { + process_incoming_call_replace(call, replaced_dlg); + } else { + call->async_call.call_var.inc_call.replaced_dlg = replaced_dlg; + } } else { - /* Notify application if on_incoming_call() is overriden, - * otherwise hangup the call with 480 - */ - if (pjsua_var.ua_cfg.cb.on_incoming_call) { - pjsua_var.ua_cfg.cb.on_incoming_call(acc_id, call_id, rdata); + /* Notify application if on_incoming_call() is overriden, + * otherwise hangup the call with 480 + */ + if (pjsua_var.ua_cfg.cb.on_incoming_call) { + pjsua_var.ua_cfg.cb.on_incoming_call(acc_id, call_id, rdata); /* Notes: * - the call might be reset when it's rejected or hangup * by application from the callback. - * - onIncomingCall() may be simulated by onCreateMediaTransport() - * when media init is done synchrounously (see #1916). And if app - * happens to answer/hangup the call from the callback, the - * answer/hangup should have been delayed (see #1923), - * so let's process the answer/hangup now. - */ - if (call->async_call.call_var.inc_call.hangup) { - process_pending_call_hangup(call); - } else if (call->med_ch_cb == NULL && call->inv) { - process_pending_call_answer(call); - } - } else { - pjsua_call_hangup(call_id, PJSIP_SC_TEMPORARILY_UNAVAILABLE, - NULL, NULL); - } + * - onIncomingCall() may be simulated by onCreateMediaTransport() + * when media init is done synchrounously (see #1916). And if app + * happens to answer/hangup the call from the callback, the + * answer/hangup should have been delayed (see #1923), + * so let's process the answer/hangup now. + */ + if (call->async_call.call_var.inc_call.hangup) { + process_pending_call_hangup(call); + } else if (call->med_ch_cb == NULL && call->inv) { + process_pending_call_answer(call); + } + } else { + pjsua_call_hangup(call_id, PJSIP_SC_TEMPORARILY_UNAVAILABLE, + NULL, NULL); + } } /* This INVITE request has been handled. */ on_return: if (dlg) { - if (should_dec_dlg) - pjsip_dlg_dec_session(dlg, &pjsua_var.mod); + if (should_dec_dlg) + pjsip_dlg_dec_session(dlg, &pjsua_var.mod); pjsip_dlg_dec_lock(dlg); } if (call && call->incoming_data) { - pjsip_rx_data_free_cloned(call->incoming_data); - call->incoming_data = NULL; + pjsip_rx_data_free_cloned(call->incoming_data); + call->incoming_data = NULL; } pj_log_pop_indent(); @@ -2145,18 +2144,18 @@ pj_bool_t pjsua_call_on_incoming(pjsip_rx_data *rdata) PJ_DEF(pj_bool_t) pjsua_call_is_active(pjsua_call_id call_id) { PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); return !pjsua_var.calls[call_id].hanging_up && - pjsua_var.calls[call_id].inv != NULL && - pjsua_var.calls[call_id].inv->state != PJSIP_INV_STATE_DISCONNECTED; + pjsua_var.calls[call_id].inv != NULL && + pjsua_var.calls[call_id].inv->state != PJSIP_INV_STATE_DISCONNECTED; } /* Acquire lock to the specified call_id */ pj_status_t acquire_call(const char *title, - pjsua_call_id call_id, - pjsua_call **p_call, - pjsip_dialog **p_dlg) + pjsua_call_id call_id, + pjsua_call **p_call, + pjsip_dialog **p_dlg) { unsigned retry; pjsua_call *call = NULL; @@ -2181,49 +2180,49 @@ pj_status_t acquire_call(const char *title, break; } - has_pjsua_lock = PJ_FALSE; + has_pjsua_lock = PJ_FALSE; - status = PJSUA_TRY_LOCK(); - if (status != PJ_SUCCESS) { - pj_thread_sleep(retry/10); - continue; - } + status = PJSUA_TRY_LOCK(); + if (status != PJ_SUCCESS) { + pj_thread_sleep(retry/10); + continue; + } - has_pjsua_lock = PJ_TRUE; - call = &pjsua_var.calls[call_id]; + has_pjsua_lock = PJ_TRUE; + call = &pjsua_var.calls[call_id]; if (call->inv) dlg = call->inv->dlg; else dlg = call->async_call.dlg; - if (dlg == NULL) { - PJSUA_UNLOCK(); - PJ_LOG(3,(THIS_FILE, "Invalid call_id %d in %s", call_id, title)); - return PJSIP_ESESSIONTERMINATED; - } + if (dlg == NULL) { + PJSUA_UNLOCK(); + PJ_LOG(3,(THIS_FILE, "Invalid call_id %d in %s", call_id, title)); + return PJSIP_ESESSIONTERMINATED; + } - status = pjsip_dlg_try_inc_lock(dlg); - if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - pj_thread_sleep(retry/10); - continue; - } + status = pjsip_dlg_try_inc_lock(dlg); + if (status != PJ_SUCCESS) { + PJSUA_UNLOCK(); + pj_thread_sleep(retry/10); + continue; + } - PJSUA_UNLOCK(); + PJSUA_UNLOCK(); - break; + break; } if (status != PJ_SUCCESS) { - if (has_pjsua_lock == PJ_FALSE) - PJ_LOG(1,(THIS_FILE, "Timed-out trying to acquire PJSUA mutex " - "(possibly system has deadlocked) in %s", - title)); - else - PJ_LOG(1,(THIS_FILE, "Timed-out trying to acquire dialog mutex " - "(possibly system has deadlocked) in %s", - title)); - return PJ_ETIMEDOUT; + if (has_pjsua_lock == PJ_FALSE) + PJ_LOG(1,(THIS_FILE, "Timed-out trying to acquire PJSUA mutex " + "(possibly system has deadlocked) in %s", + title)); + else + PJ_LOG(1,(THIS_FILE, "Timed-out trying to acquire dialog mutex " + "(possibly system has deadlocked) in %s", + title)); + return PJ_ETIMEDOUT; } *p_call = call; @@ -2237,14 +2236,14 @@ pj_status_t acquire_call(const char *title, * Obtain detail information about the specified call. */ PJ_DEF(pj_status_t) pjsua_call_get_info( pjsua_call_id call_id, - pjsua_call_info *info) + pjsua_call_info *info) { pjsua_call *call; pjsip_dialog *dlg; unsigned mi; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); pj_bzero(info, sizeof(*info)); @@ -2256,8 +2255,8 @@ PJ_DEF(pj_status_t) pjsua_call_get_info( pjsua_call_id call_id, call = &pjsua_var.calls[call_id]; dlg = (call->inv ? call->inv->dlg : call->async_call.dlg); if (!dlg) { - PJSUA_UNLOCK(); - return PJSIP_ESESSIONTERMINATED; + PJSUA_UNLOCK(); + return PJSIP_ESESSIONTERMINATED; } /* id and role */ @@ -2268,40 +2267,40 @@ PJ_DEF(pj_status_t) pjsua_call_get_info( pjsua_call_id call_id, /* local info */ info->local_info.ptr = info->buf_.local_info; pj_strncpy(&info->local_info, &dlg->local.info_str, - sizeof(info->buf_.local_info)); + sizeof(info->buf_.local_info)); /* local contact */ info->local_contact.ptr = info->buf_.local_contact; info->local_contact.slen = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, - dlg->local.contact->uri, - info->local_contact.ptr, - sizeof(info->buf_.local_contact)); + dlg->local.contact->uri, + info->local_contact.ptr, + sizeof(info->buf_.local_contact)); if (info->local_contact.slen < 0) - info->local_contact.slen = 0; + info->local_contact.slen = 0; /* remote info */ info->remote_info.ptr = info->buf_.remote_info; pj_strncpy(&info->remote_info, &dlg->remote.info_str, - sizeof(info->buf_.remote_info)); + sizeof(info->buf_.remote_info)); /* remote contact */ if (dlg->remote.contact) { - int len; - info->remote_contact.ptr = info->buf_.remote_contact; - len = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, - dlg->remote.contact->uri, - info->remote_contact.ptr, - sizeof(info->buf_.remote_contact)); - if (len < 0) len = 0; - info->remote_contact.slen = len; + int len; + info->remote_contact.ptr = info->buf_.remote_contact; + len = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, + dlg->remote.contact->uri, + info->remote_contact.ptr, + sizeof(info->buf_.remote_contact)); + if (len < 0) len = 0; + info->remote_contact.slen = len; } else { - info->remote_contact.slen = 0; + info->remote_contact.slen = 0; } /* call id */ info->call_id.ptr = info->buf_.call_id; pj_strncpy(&info->call_id, &dlg->call_id->id, - sizeof(info->buf_.call_id)); + sizeof(info->buf_.call_id)); /* call setting */ pj_memcpy(&info->setting, &call->opt, sizeof(call->opt)); @@ -2325,122 +2324,122 @@ PJ_DEF(pj_status_t) pjsua_call_get_info( pjsua_call_id call_id, /* If call is disconnected, set the last_status from the cause code */ if (call->inv && call->inv->state >= PJSIP_INV_STATE_DISCONNECTED) { - /* last_status, last_status_text */ - info->last_status = call->inv->cause; + /* last_status, last_status_text */ + info->last_status = call->inv->cause; - info->last_status_text.ptr = info->buf_.last_status_text; - pj_strncpy(&info->last_status_text, &call->inv->cause_text, - sizeof(info->buf_.last_status_text)); + info->last_status_text.ptr = info->buf_.last_status_text; + pj_strncpy(&info->last_status_text, &call->inv->cause_text, + sizeof(info->buf_.last_status_text)); } else { - /* last_status, last_status_text */ - info->last_status = call->last_code; + /* last_status, last_status_text */ + info->last_status = call->last_code; - info->last_status_text.ptr = info->buf_.last_status_text; - pj_strncpy(&info->last_status_text, &call->last_text, - sizeof(info->buf_.last_status_text)); + info->last_status_text.ptr = info->buf_.last_status_text; + pj_strncpy(&info->last_status_text, &call->last_text, + sizeof(info->buf_.last_status_text)); } /* Audio & video count offered by remote */ info->rem_offerer = call->rem_offerer; if (call->rem_offerer) { - info->rem_aud_cnt = call->rem_aud_cnt; - info->rem_vid_cnt = call->rem_vid_cnt; + info->rem_aud_cnt = call->rem_aud_cnt; + info->rem_vid_cnt = call->rem_vid_cnt; } /* Build array of active media info */ info->media_cnt = 0; for (mi=0; mi < call->med_cnt && - info->media_cnt < PJ_ARRAY_SIZE(info->media); ++mi) + info->media_cnt < PJ_ARRAY_SIZE(info->media); ++mi) { - pjsua_call_media *call_med = &call->media[mi]; + pjsua_call_media *call_med = &call->media[mi]; - info->media[info->media_cnt].index = mi; - info->media[info->media_cnt].status = call_med->state; - info->media[info->media_cnt].dir = call_med->dir; - info->media[info->media_cnt].type = call_med->type; + info->media[info->media_cnt].index = mi; + info->media[info->media_cnt].status = call_med->state; + info->media[info->media_cnt].dir = call_med->dir; + info->media[info->media_cnt].type = call_med->type; - if (call_med->type == PJMEDIA_TYPE_AUDIO) { - info->media[info->media_cnt].stream.aud.conf_slot = - call_med->strm.a.conf_slot; - } else if (call_med->type == PJMEDIA_TYPE_VIDEO) { - pjmedia_vid_dev_index cap_dev = PJMEDIA_VID_INVALID_DEV; + if (call_med->type == PJMEDIA_TYPE_AUDIO) { + info->media[info->media_cnt].stream.aud.conf_slot = + call_med->strm.a.conf_slot; + } else if (call_med->type == PJMEDIA_TYPE_VIDEO) { + pjmedia_vid_dev_index cap_dev = PJMEDIA_VID_INVALID_DEV; - info->media[info->media_cnt].stream.vid.win_in = - call_med->strm.v.rdr_win_id; + info->media[info->media_cnt].stream.vid.win_in = + call_med->strm.v.rdr_win_id; - info->media[info->media_cnt].stream.vid.dec_slot = - call_med->strm.v.strm_dec_slot; - info->media[info->media_cnt].stream.vid.enc_slot = - call_med->strm.v.strm_enc_slot; + info->media[info->media_cnt].stream.vid.dec_slot = + call_med->strm.v.strm_dec_slot; + info->media[info->media_cnt].stream.vid.enc_slot = + call_med->strm.v.strm_enc_slot; - if (call_med->strm.v.cap_win_id != PJSUA_INVALID_ID) { - cap_dev = call_med->strm.v.cap_dev; - } - info->media[info->media_cnt].stream.vid.cap_dev = cap_dev; - } else { - continue; - } - ++info->media_cnt; + if (call_med->strm.v.cap_win_id != PJSUA_INVALID_ID) { + cap_dev = call_med->strm.v.cap_dev; + } + info->media[info->media_cnt].stream.vid.cap_dev = cap_dev; + } else { + continue; + } + ++info->media_cnt; } if (call->audio_idx != -1) { - info->media_status = call->media[call->audio_idx].state; - info->media_dir = call->media[call->audio_idx].dir; - info->conf_slot = call->media[call->audio_idx].strm.a.conf_slot; + info->media_status = call->media[call->audio_idx].state; + info->media_dir = call->media[call->audio_idx].dir; + info->conf_slot = call->media[call->audio_idx].strm.a.conf_slot; } /* Build array of provisional media info */ info->prov_media_cnt = 0; for (mi=0; mi < call->med_prov_cnt && - info->prov_media_cnt < PJ_ARRAY_SIZE(info->prov_media); ++mi) + info->prov_media_cnt < PJ_ARRAY_SIZE(info->prov_media); ++mi) { - pjsua_call_media *call_med = &call->media_prov[mi]; - - info->prov_media[info->prov_media_cnt].index = mi; - info->prov_media[info->prov_media_cnt].status = call_med->state; - info->prov_media[info->prov_media_cnt].dir = call_med->dir; - info->prov_media[info->prov_media_cnt].type = call_med->type; - if (call_med->type == PJMEDIA_TYPE_AUDIO) { - info->prov_media[info->prov_media_cnt].stream.aud.conf_slot = - call_med->strm.a.conf_slot; - } else if (call_med->type == PJMEDIA_TYPE_VIDEO) { - pjmedia_vid_dev_index cap_dev = PJMEDIA_VID_INVALID_DEV; - - info->prov_media[info->prov_media_cnt].stream.vid.win_in = - call_med->strm.v.rdr_win_id; - - if (call_med->strm.v.cap_win_id != PJSUA_INVALID_ID) { - cap_dev = call_med->strm.v.cap_dev; - } - info->prov_media[info->prov_media_cnt].stream.vid.cap_dev=cap_dev; - } else { - continue; - } - ++info->prov_media_cnt; + pjsua_call_media *call_med = &call->media_prov[mi]; + + info->prov_media[info->prov_media_cnt].index = mi; + info->prov_media[info->prov_media_cnt].status = call_med->state; + info->prov_media[info->prov_media_cnt].dir = call_med->dir; + info->prov_media[info->prov_media_cnt].type = call_med->type; + if (call_med->type == PJMEDIA_TYPE_AUDIO) { + info->prov_media[info->prov_media_cnt].stream.aud.conf_slot = + call_med->strm.a.conf_slot; + } else if (call_med->type == PJMEDIA_TYPE_VIDEO) { + pjmedia_vid_dev_index cap_dev = PJMEDIA_VID_INVALID_DEV; + + info->prov_media[info->prov_media_cnt].stream.vid.win_in = + call_med->strm.v.rdr_win_id; + + if (call_med->strm.v.cap_win_id != PJSUA_INVALID_ID) { + cap_dev = call_med->strm.v.cap_dev; + } + info->prov_media[info->prov_media_cnt].stream.vid.cap_dev=cap_dev; + } else { + continue; + } + ++info->prov_media_cnt; } /* calculate duration */ if (info->state >= PJSIP_INV_STATE_DISCONNECTED) { - info->total_duration = call->dis_time; - PJ_TIME_VAL_SUB(info->total_duration, call->start_time); + info->total_duration = call->dis_time; + PJ_TIME_VAL_SUB(info->total_duration, call->start_time); - if (call->conn_time.sec) { - info->connect_duration = call->dis_time; - PJ_TIME_VAL_SUB(info->connect_duration, call->conn_time); - } + if (call->conn_time.sec) { + info->connect_duration = call->dis_time; + PJ_TIME_VAL_SUB(info->connect_duration, call->conn_time); + } } else if (info->state == PJSIP_INV_STATE_CONFIRMED) { - pj_gettimeofday(&info->total_duration); - PJ_TIME_VAL_SUB(info->total_duration, call->start_time); + pj_gettimeofday(&info->total_duration); + PJ_TIME_VAL_SUB(info->total_duration, call->start_time); - pj_gettimeofday(&info->connect_duration); - PJ_TIME_VAL_SUB(info->connect_duration, call->conn_time); + pj_gettimeofday(&info->connect_duration); + PJ_TIME_VAL_SUB(info->connect_duration, call->conn_time); } else { - pj_gettimeofday(&info->total_duration); - PJ_TIME_VAL_SUB(info->total_duration, call->start_time); + pj_gettimeofday(&info->total_duration); + PJ_TIME_VAL_SUB(info->total_duration, call->start_time); } PJSUA_UNLOCK(); @@ -2452,10 +2451,10 @@ PJ_DEF(pj_status_t) pjsua_call_get_info( pjsua_call_id call_id, * Check if call remote peer support the specified capability. */ PJ_DEF(pjsip_dialog_cap_status) pjsua_call_remote_has_cap( - pjsua_call_id call_id, - int htype, - const pj_str_t *hname, - const pj_str_t *token) + pjsua_call_id call_id, + int htype, + const pj_str_t *hname, + const pj_str_t *token) { pjsua_call *call; pjsip_dialog *dlg; @@ -2464,7 +2463,7 @@ PJ_DEF(pjsip_dialog_cap_status) pjsua_call_remote_has_cap( status = acquire_call("pjsua_call_peer_has_cap()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - return PJSIP_DIALOG_CAP_UNKNOWN; + return PJSIP_DIALOG_CAP_UNKNOWN; cap_status = pjsip_dlg_remote_has_cap(dlg, htype, hname, token); @@ -2478,10 +2477,10 @@ PJ_DEF(pjsip_dialog_cap_status) pjsua_call_remote_has_cap( * Attach application specific data to the call. */ PJ_DEF(pj_status_t) pjsua_call_set_user_data( pjsua_call_id call_id, - void *user_data) + void *user_data) { PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); pjsua_var.calls[call_id].user_data = user_data; return PJ_SUCCESS; @@ -2494,7 +2493,7 @@ PJ_DEF(pj_status_t) pjsua_call_set_user_data( pjsua_call_id call_id, PJ_DEF(void*) pjsua_call_get_user_data(pjsua_call_id call_id) { PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - NULL); + NULL); return pjsua_var.calls[call_id].user_data; } @@ -2503,10 +2502,10 @@ PJ_DEF(void*) pjsua_call_get_user_data(pjsua_call_id call_id) * Get remote's NAT type. */ PJ_DEF(pj_status_t) pjsua_call_get_rem_nat_type(pjsua_call_id call_id, - pj_stun_nat_type *p_type) + pj_stun_nat_type *p_type) { PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(p_type != NULL, PJ_EINVAL); *p_type = pjsua_var.calls[call_id].rem_nat_type; @@ -2527,7 +2526,7 @@ pjsua_call_get_med_transport_info(pjsua_call_id call_id, pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(t, PJ_EINVAL); PJSUA_LOCK(); @@ -2535,8 +2534,8 @@ pjsua_call_get_med_transport_info(pjsua_call_id call_id, call = &pjsua_var.calls[call_id]; if (med_idx >= call->med_cnt) { - PJSUA_UNLOCK(); - return PJ_EINVAL; + PJSUA_UNLOCK(); + return PJ_EINVAL; } call_med = &call->media[med_idx]; @@ -2562,7 +2561,7 @@ on_answer_call_med_tp_complete(pjsua_call_id call_id, PJSUA_LOCK(); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error initializing media channel", status); + pjsua_perror(THIS_FILE, "Error initializing media channel", status); goto on_return; } @@ -2576,15 +2575,15 @@ on_answer_call_med_tp_complete(pjsua_call_id call_id, status = pjsua_media_channel_create_sdp(call_id, call->async_call.dlg->pool, - NULL, &sdp, &sip_err_code); + NULL, &sdp, &sip_err_code); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating SDP answer", status); + pjsua_perror(THIS_FILE, "Error creating SDP answer", status); goto on_return; } status = pjsip_inv_set_local_sdp(call->inv, sdp); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error setting local SDP", status); + pjsua_perror(THIS_FILE, "Error setting local SDP", status); sip_err_code = PJSIP_SC_NOT_ACCEPTABLE_HERE; goto on_return; } @@ -2599,13 +2598,13 @@ on_answer_call_med_tp_complete(pjsua_call_id call_id, pjsip_tx_data *tdata; pj_status_t status_; - if (sip_err_code == 0) - sip_err_code = PJSIP_ERRNO_TO_SIP_STATUS(status); + if (sip_err_code == 0) + sip_err_code = PJSIP_ERRNO_TO_SIP_STATUS(status); - status_ = pjsip_inv_end_session(call->inv, sip_err_code, NULL, + status_ = pjsip_inv_end_session(call->inv, sip_err_code, NULL, &tdata); - if (status_ == PJ_SUCCESS && tdata) - status_ = pjsip_inv_send_msg(call->inv, tdata); + if (status_ == PJ_SUCCESS && tdata) + status_ = pjsip_inv_send_msg(call->inv, tdata); } pjsua_media_channel_deinit(call->index); @@ -2618,8 +2617,8 @@ on_answer_call_med_tp_complete(pjsua_call_id call_id, /* Finish any pending process */ if (status == PJ_SUCCESS) { - /* Process pending call answers */ - process_pending_call_answer(call); + /* Process pending call answers */ + process_pending_call_answer(call); } PJSUA_UNLOCK(); @@ -2631,9 +2630,9 @@ on_answer_call_med_tp_complete(pjsua_call_id call_id, * Send response to incoming INVITE request. */ PJ_DEF(pj_status_t) pjsua_call_answer( pjsua_call_id call_id, - unsigned code, - const pj_str_t *reason, - const pjsua_msg_data *msg_data) + unsigned code, + const pj_str_t *reason, + const pjsua_msg_data *msg_data) { return pjsua_call_answer2(call_id, NULL, code, reason, msg_data); } @@ -2643,10 +2642,10 @@ PJ_DEF(pj_status_t) pjsua_call_answer( pjsua_call_id call_id, * Send response to incoming INVITE request. */ PJ_DEF(pj_status_t) pjsua_call_answer2(pjsua_call_id call_id, - const pjsua_call_setting *opt, - unsigned code, - const pj_str_t *reason, - const pjsua_msg_data *msg_data) + const pjsua_call_setting *opt, + unsigned code, + const pj_str_t *reason, + const pjsua_msg_data *msg_data) { pjsua_call *call; pjsip_dialog *dlg = NULL; @@ -2654,36 +2653,36 @@ PJ_DEF(pj_status_t) pjsua_call_answer2(pjsua_call_id call_id, pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Answering call %d: code=%d", call_id, code)); pj_log_push_indent(); status = acquire_call("pjsua_call_answer()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; if (!call->inv->invite_tsx || - call->inv->invite_tsx->state >= PJSIP_TSX_STATE_COMPLETED) + call->inv->invite_tsx->state >= PJSIP_TSX_STATE_COMPLETED) { - PJ_LOG(3,(THIS_FILE, "Unable to answer call (no incoming INVITE or " - "already answered)")); - status = PJ_EINVALIDOP; - goto on_return; + PJ_LOG(3,(THIS_FILE, "Unable to answer call (no incoming INVITE or " + "already answered)")); + status = PJ_EINVALIDOP; + goto on_return; } /* Apply call setting, only if status code is 1xx or 2xx. */ if (opt && code < 300) { - /* Check if it has not been set previously or it is different to - * the previous one. - */ - if (!call->opt_inited) { - call->opt_inited = PJ_TRUE; - apply_call_setting(call, opt, NULL); - } else if (pj_memcmp(opt, &call->opt, sizeof(*opt)) != 0) { - /* Warn application about call setting inconsistency */ - PJ_LOG(2,(THIS_FILE, "The call setting changes is ignored.")); - } + /* Check if it has not been set previously or it is different to + * the previous one. + */ + if (!call->opt_inited) { + call->opt_inited = PJ_TRUE; + apply_call_setting(call, opt, NULL); + } else if (pj_memcmp(opt, &call->opt, sizeof(*opt)) != 0) { + /* Warn application about call setting inconsistency */ + PJ_LOG(2,(THIS_FILE, "The call setting changes is ignored.")); + } } PJSUA_LOCK(); @@ -2698,32 +2697,32 @@ PJ_DEF(pj_status_t) pjsua_call_answer2(pjsua_call_id call_id, * answer code 183 or 2xx is issued */ if (!call->med_ch_cb && - (call->opt_inited || (code==183 || code/100==2)) && - (!call->inv->neg || - pjmedia_sdp_neg_get_state(call->inv->neg) == - PJMEDIA_SDP_NEG_STATE_NULL)) + (call->opt_inited || (code==183 || code/100==2)) && + (!call->inv->neg || + pjmedia_sdp_neg_get_state(call->inv->neg) == + PJMEDIA_SDP_NEG_STATE_NULL)) { - /* Mark call setting as initialized as it is just about to be used - * for initializing the media channel. - */ - call->opt_inited = PJ_TRUE; - - status = pjsua_media_channel_init(call->index, PJSIP_ROLE_UAC, - call->secure_level, - dlg->pool, - NULL, NULL, PJ_TRUE, - &on_answer_call_med_tp_complete); - if (status == PJ_SUCCESS) { - status = on_answer_call_med_tp_complete(call->index, NULL); - if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - goto on_return; - } - } else if (status != PJ_EPENDING) { - PJSUA_UNLOCK(); - pjsua_perror(THIS_FILE, "Error initializing media channel", status); - goto on_return; - } + /* Mark call setting as initialized as it is just about to be used + * for initializing the media channel. + */ + call->opt_inited = PJ_TRUE; + + status = pjsua_media_channel_init(call->index, PJSIP_ROLE_UAC, + call->secure_level, + dlg->pool, + NULL, NULL, PJ_TRUE, + &on_answer_call_med_tp_complete); + if (status == PJ_SUCCESS) { + status = on_answer_call_med_tp_complete(call->index, NULL); + if (status != PJ_SUCCESS) { + PJSUA_UNLOCK(); + goto on_return; + } + } else if (status != PJ_EPENDING) { + PJSUA_UNLOCK(); + pjsua_perror(THIS_FILE, "Error initializing media channel", status); + goto on_return; + } } /* If media transport creation is not yet completed, we will answer @@ -2739,13 +2738,13 @@ PJ_DEF(pj_status_t) pjsua_call_answer2(pjsua_call_id call_id, answer = PJ_POOL_ZALLOC_T(call->inv->pool_prov, struct call_answer); answer->code = code; - if (opt) { - answer->opt = PJ_POOL_ZALLOC_T(call->inv->pool_prov, - pjsua_call_setting); - *answer->opt = *opt; - } + if (opt) { + answer->opt = PJ_POOL_ZALLOC_T(call->inv->pool_prov, + pjsua_call_setting); + *answer->opt = *opt; + } if (reason) { - answer->reason = PJ_POOL_ZALLOC_T(call->inv->pool_prov, pj_str_t); + answer->reason = PJ_POOL_ZALLOC_T(call->inv->pool_prov, pj_str_t); pj_strdup(call->inv->pool_prov, answer->reason, reason); } if (msg_data) { @@ -2764,24 +2763,24 @@ PJ_DEF(pj_status_t) pjsua_call_answer2(pjsua_call_id call_id, PJSUA_UNLOCK(); if (call->res_time.sec == 0) - pj_gettimeofday(&call->res_time); + pj_gettimeofday(&call->res_time); if (reason && reason->slen == 0) - reason = NULL; + reason = NULL; /* Create response message */ status = pjsip_inv_answer(call->inv, code, reason, NULL, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating response", - status); - goto on_return; + pjsua_perror(THIS_FILE, "Error creating response", + status); + goto on_return; } /* Call might have been disconnected if application is answering with * 200/OK and the media failed to start. */ if (call->inv == NULL) - goto on_return; + goto on_return; /* Add additional headers etc */ pjsua_process_msg_data( tdata, msg_data); @@ -2789,8 +2788,8 @@ PJ_DEF(pj_status_t) pjsua_call_answer2(pjsua_call_id call_id, /* Send the message */ status = pjsip_inv_send_msg(call->inv, tdata); if (status != PJ_SUCCESS) - pjsua_perror(THIS_FILE, "Error sending response", - status); + pjsua_perror(THIS_FILE, "Error sending response", + status); on_return: if (dlg) pjsip_dlg_dec_lock(dlg); @@ -2804,64 +2803,64 @@ PJ_DEF(pj_status_t) pjsua_call_answer2(pjsua_call_id call_id, */ PJ_DEF(pj_status_t) pjsua_call_answer_with_sdp(pjsua_call_id call_id, - const pjmedia_sdp_session *sdp, - const pjsua_call_setting *opt, - unsigned code, - const pj_str_t *reason, - const pjsua_msg_data *msg_data) + const pjmedia_sdp_session *sdp, + const pjsua_call_setting *opt, + unsigned code, + const pj_str_t *reason, + const pjsua_msg_data *msg_data) { pjsua_call *call; pjsip_dialog *dlg = NULL; pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); status = acquire_call("pjsua_call_answer_with_sdp()", - call_id, &call, &dlg); + call_id, &call, &dlg); if (status != PJ_SUCCESS) - return status; + return status; status = pjsip_inv_set_sdp_answer(call->inv, sdp); pjsip_dlg_dec_lock(dlg); if (status != PJ_SUCCESS) - return status; + return status; return pjsua_call_answer2(call_id, opt, code, reason, msg_data); } static pj_status_t call_inv_end_session(pjsua_call *call, - unsigned code, - const pj_str_t *reason, - const pjsua_msg_data *msg_data) + unsigned code, + const pj_str_t *reason, + const pjsua_msg_data *msg_data) { pjsip_tx_data *tdata; pj_status_t status; if (code==0) { - if (call->inv->state == PJSIP_INV_STATE_CONFIRMED) - code = PJSIP_SC_OK; - else if (call->inv->role == PJSIP_ROLE_UAS) - code = PJSIP_SC_DECLINE; - else - code = PJSIP_SC_REQUEST_TERMINATED; + if (call->inv->state == PJSIP_INV_STATE_CONFIRMED) + code = PJSIP_SC_OK; + else if (call->inv->role == PJSIP_ROLE_UAS) + code = PJSIP_SC_DECLINE; + else + code = PJSIP_SC_REQUEST_TERMINATED; } /* Stop hangup timer, if it is active. */ if (call->hangup_timer.id) { - pjsua_cancel_timer(&call->hangup_timer); - call->hangup_timer.id = PJ_FALSE; + pjsua_cancel_timer(&call->hangup_timer); + call->hangup_timer.id = PJ_FALSE; } status = pjsip_inv_end_session(call->inv, code, reason, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Failed to create end session message", - status); - goto on_return; + pjsua_perror(THIS_FILE, + "Failed to create end session message", + status); + goto on_return; } /* pjsip_inv_end_session may return PJ_SUCCESS with NULL @@ -2869,7 +2868,7 @@ static pj_status_t call_inv_end_session(pjsua_call *call, * with any provisional responses. */ if (tdata == NULL) { - goto on_return; + goto on_return; } /* Add additional headers etc */ @@ -2878,10 +2877,10 @@ static pj_status_t call_inv_end_session(pjsua_call *call, /* Send the message */ status = pjsip_inv_send_msg(call->inv, tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Failed to send end session message", - status); - goto on_return; + pjsua_perror(THIS_FILE, + "Failed to send end session message", + status); + goto on_return; } on_return: @@ -2890,42 +2889,42 @@ static pj_status_t call_inv_end_session(pjsua_call *call, * so we need to check for call->inv as well. */ if (status != PJ_SUCCESS && call->inv) { - pj_time_val delay; - - /* Schedule a retry */ - if (call->hangup_retry >= CALL_HANGUP_MAX_RETRY) { - /* Forcefully terminate the invite session. */ - PJ_LOG(1,(THIS_FILE,"Call %d: failed to hangup after %d retries, " - "terminating the session forcefully now!", - call->index, call->hangup_retry)); - pjsip_inv_terminate(call->inv, call->hangup_code, PJ_TRUE); - return PJ_SUCCESS; - } - - if (call->hangup_retry == 0) { - pj_timer_entry_init(&call->hangup_timer, PJ_FALSE, - (void*)call, &hangup_timer_cb); - - call->hangup_code = code; - if (reason) { - pj_strdup(call->inv->pool_prov, &call->hangup_reason, - reason); - } - if (msg_data) { - call->hangup_msg_data = pjsua_msg_data_clone( - call->inv->pool_prov, - msg_data); - } - } - - delay.sec = 0; - delay.msec = CALL_HANGUP_RETRY_INTERVAL; - pj_time_val_normalize(&delay); - call->hangup_timer.id = PJ_TRUE; - pjsua_schedule_timer(&call->hangup_timer, &delay); - call->hangup_retry++; - - PJ_LOG(4, (THIS_FILE, "Will retry call %d hangup in %d msec", + pj_time_val delay; + + /* Schedule a retry */ + if (call->hangup_retry >= CALL_HANGUP_MAX_RETRY) { + /* Forcefully terminate the invite session. */ + PJ_LOG(1,(THIS_FILE,"Call %d: failed to hangup after %d retries, " + "terminating the session forcefully now!", + call->index, call->hangup_retry)); + pjsip_inv_terminate(call->inv, call->hangup_code, PJ_TRUE); + return PJ_SUCCESS; + } + + if (call->hangup_retry == 0) { + pj_timer_entry_init(&call->hangup_timer, PJ_FALSE, + (void*)call, &hangup_timer_cb); + + call->hangup_code = code; + if (reason) { + pj_strdup(call->inv->pool_prov, &call->hangup_reason, + reason); + } + if (msg_data) { + call->hangup_msg_data = pjsua_msg_data_clone( + call->inv->pool_prov, + msg_data); + } + } + + delay.sec = 0; + delay.msec = CALL_HANGUP_RETRY_INTERVAL; + pj_time_val_normalize(&delay); + call->hangup_timer.id = PJ_TRUE; + pjsua_schedule_timer(&call->hangup_timer, &delay); + call->hangup_retry++; + + PJ_LOG(4, (THIS_FILE, "Will retry call %d hangup in %d msec", call->index, CALL_HANGUP_RETRY_INTERVAL)); } @@ -2945,13 +2944,13 @@ static void hangup_timer_cb(pj_timer_heap_t *th, pj_timer_entry *entry) status = acquire_call("hangup_timer_cb()", call->index, &call, &dlg); if (status != PJ_SUCCESS) { - pj_log_pop_indent(); - return; + pj_log_pop_indent(); + return; } call->hangup_timer.id = PJ_FALSE; call_inv_end_session(call, call->hangup_code, &call->hangup_reason, - call->hangup_msg_data); + call->hangup_msg_data); pjsip_dlg_dec_lock(dlg); @@ -2963,103 +2962,103 @@ static void hangup_timer_cb(pj_timer_heap_t *th, pj_timer_entry *entry) * call state. */ PJ_DEF(pj_status_t) pjsua_call_hangup(pjsua_call_id call_id, - unsigned code, - const pj_str_t *reason, - const pjsua_msg_data *msg_data) + unsigned code, + const pj_str_t *reason, + const pjsua_msg_data *msg_data) { pjsua_call *call; pjsip_dialog *dlg = NULL; pj_status_t status; if (call_id<0 || call_id>=(int)pjsua_var.ua_cfg.max_calls) { - PJ_LOG(1,(THIS_FILE, "pjsua_call_hangup(): invalid call id %d", - call_id)); + PJ_LOG(1,(THIS_FILE, "pjsua_call_hangup(): invalid call id %d", + call_id)); } PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Call %d hanging up: code=%d..", call_id, code)); pj_log_push_indent(); status = acquire_call("pjsua_call_hangup()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; if (!call->hanging_up) { - pj_bool_t delay_hangup = PJ_FALSE; - pjsip_event user_event; - - pj_gettimeofday(&call->dis_time); - if (call->res_time.sec == 0) - pj_gettimeofday(&call->res_time); - - if (code==0) { - if (call->inv && call->inv->state == PJSIP_INV_STATE_CONFIRMED) - code = PJSIP_SC_OK; - else if (call->inv && call->inv->role == PJSIP_ROLE_UAS) - code = PJSIP_SC_DECLINE; - else - code = PJSIP_SC_REQUEST_TERMINATED; - } - - call->last_code = code; - pj_strncpy(&call->last_text, - pjsip_get_status_text(call->last_code), - sizeof(call->last_text_buf_)); - - /* Stop reinvite timer, if it is active. */ - if (call->reinv_timer.id) { - pjsua_cancel_timer(&call->reinv_timer); - call->reinv_timer.id = PJ_FALSE; - } - - /* If media transport creation is not yet completed, we will continue - * from the media transport creation callback instead. + pj_bool_t delay_hangup = PJ_FALSE; + pjsip_event user_event; + + pj_gettimeofday(&call->dis_time); + if (call->res_time.sec == 0) + pj_gettimeofday(&call->res_time); + + if (code==0) { + if (call->inv && call->inv->state == PJSIP_INV_STATE_CONFIRMED) + code = PJSIP_SC_OK; + else if (call->inv && call->inv->role == PJSIP_ROLE_UAS) + code = PJSIP_SC_DECLINE; + else + code = PJSIP_SC_REQUEST_TERMINATED; + } + + call->last_code = code; + pj_strncpy(&call->last_text, + pjsip_get_status_text(call->last_code), + sizeof(call->last_text_buf_)); + + /* Stop reinvite timer, if it is active. */ + if (call->reinv_timer.id) { + pjsua_cancel_timer(&call->reinv_timer); + call->reinv_timer.id = PJ_FALSE; + } + + /* If media transport creation is not yet completed, we will continue + * from the media transport creation callback instead. */ - if ((call->med_ch_cb && !call->inv) || - ((call->inv != NULL) && - (call->inv->state == PJSIP_INV_STATE_NULL))) - { - delay_hangup = PJ_TRUE; + if ((call->med_ch_cb && !call->inv) || + ((call->inv != NULL) && + (call->inv->state == PJSIP_INV_STATE_NULL))) + { + delay_hangup = PJ_TRUE; PJ_LOG(4,(THIS_FILE, "Will continue call %d hangup upon " - "completion of media transport", call_id)); + "completion of media transport", call_id)); - if (call->inv && call->inv->role == PJSIP_ROLE_UAS) - call->async_call.call_var.inc_call.hangup = PJ_TRUE; - else - call->async_call.call_var.out_call.hangup = PJ_TRUE; + if (call->inv && call->inv->role == PJSIP_ROLE_UAS) + call->async_call.call_var.inc_call.hangup = PJ_TRUE; + else + call->async_call.call_var.out_call.hangup = PJ_TRUE; if (reason) { - pj_strncpy(&call->last_text, reason, - sizeof(call->last_text_buf_)); + pj_strncpy(&call->last_text, reason, + sizeof(call->last_text_buf_)); } - call->hanging_up = PJ_TRUE; - } else { - /* Destroy media session. */ - pjsua_media_channel_deinit(call_id); - call->hanging_up = PJ_TRUE; - pjsua_check_snd_dev_idle(); - } - - /* Call callback which will report DISCONNECTED state. - * Use user event rather than NULL to avoid crash in - * unsuspecting app. - */ - PJSIP_EVENT_INIT_USER(user_event, 0, 0, 0, 0); - if (pjsua_var.ua_cfg.cb.on_call_state) { - (*pjsua_var.ua_cfg.cb.on_call_state)(call->index, - &user_event); - } - - if (call->inv && !delay_hangup) { - call_inv_end_session(call, code, reason, msg_data); - } + call->hanging_up = PJ_TRUE; + } else { + /* Destroy media session. */ + pjsua_media_channel_deinit(call_id); + call->hanging_up = PJ_TRUE; + pjsua_check_snd_dev_idle(); + } + + /* Call callback which will report DISCONNECTED state. + * Use user event rather than NULL to avoid crash in + * unsuspecting app. + */ + PJSIP_EVENT_INIT_USER(user_event, 0, 0, 0, 0); + if (pjsua_var.ua_cfg.cb.on_call_state) { + (*pjsua_var.ua_cfg.cb.on_call_state)(call->index, + &user_event); + } + + if (call->inv && !delay_hangup) { + call_inv_end_session(call, code, reason, msg_data); + } } else { - /* Already requested and on progress */ + /* Already requested and on progress */ PJ_LOG(4,(THIS_FILE, "Call %d hangup request ignored as " - "it is on progress", call_id)); + "it is on progress", call_id)); } on_return: @@ -3073,19 +3072,19 @@ PJ_DEF(pj_status_t) pjsua_call_hangup(pjsua_call_id call_id, * Accept or reject redirection. */ PJ_DEF(pj_status_t) pjsua_call_process_redirect( pjsua_call_id call_id, - pjsip_redirect_op cmd) + pjsip_redirect_op cmd) { pjsua_call *call; pjsip_dialog *dlg; pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); status = acquire_call("pjsua_call_process_redirect()", call_id, - &call, &dlg); + &call, &dlg); if (status != PJ_SUCCESS) - return status; + return status; status = pjsip_inv_process_redirect(call->inv, cmd, NULL); @@ -3099,14 +3098,14 @@ PJ_DEF(pj_status_t) pjsua_call_process_redirect( pjsua_call_id call_id, * Put the specified call on hold. */ PJ_DEF(pj_status_t) pjsua_call_set_hold(pjsua_call_id call_id, - const pjsua_msg_data *msg_data) + const pjsua_msg_data *msg_data) { return pjsua_call_set_hold2(call_id, 0, msg_data); } PJ_DEF(pj_status_t) pjsua_call_set_hold2(pjsua_call_id call_id, unsigned options, - const pjsua_msg_data *msg_data) + const pjsua_msg_data *msg_data) { pjmedia_sdp_session *sdp; pjsua_call *call; @@ -3116,59 +3115,59 @@ PJ_DEF(pj_status_t) pjsua_call_set_hold2(pjsua_call_id call_id, pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Putting call %d on hold", call_id)); pj_log_push_indent(); status = acquire_call("pjsua_call_set_hold()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; if (call->inv->state != PJSIP_INV_STATE_CONFIRMED) { - PJ_LOG(3,(THIS_FILE, "Can not hold call that is not confirmed")); - status = PJSIP_ESESSIONSTATE; - goto on_return; + PJ_LOG(3,(THIS_FILE, "Can not hold call that is not confirmed")); + status = PJSIP_ESESSIONSTATE; + goto on_return; } /* We may need to re-initialize media before creating SDP */ if (call->med_prov_cnt == 0) { - status = apply_call_setting(call, &call->opt, NULL); - if (status != PJ_SUCCESS) - goto on_return; + status = apply_call_setting(call, &call->opt, NULL); + if (status != PJ_SUCCESS) + goto on_return; } status = create_sdp_of_call_hold(call, &sdp); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; if ((options & PJSUA_CALL_UPDATE_CONTACT) && - pjsua_acc_is_valid(call->acc_id)) + pjsua_acc_is_valid(call->acc_id)) { - call_update_contact(call, &new_contact); + call_update_contact(call, &new_contact); } if ((options & PJSUA_CALL_UPDATE_VIA) && - pjsua_acc_is_valid(call->acc_id)) + pjsua_acc_is_valid(call->acc_id)) { - dlg_set_via(call->inv->dlg, &pjsua_var.acc[call->acc_id]); + dlg_set_via(call->inv->dlg, &pjsua_var.acc[call->acc_id]); } if ((call->opt.flag & PJSUA_CALL_UPDATE_TARGET) && - msg_data && msg_data->target_uri.slen) + msg_data && msg_data->target_uri.slen) { - status = dlg_set_target(dlg, &msg_data->target_uri); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to set new target", status); - goto on_return; - } + status = dlg_set_target(dlg, &msg_data->target_uri); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to set new target", status); + goto on_return; + } } /* Create re-INVITE with new offer */ status = pjsip_inv_reinvite( call->inv, new_contact, sdp, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create re-INVITE", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to create re-INVITE", status); + goto on_return; } /* Add additional headers etc */ @@ -3180,9 +3179,9 @@ PJ_DEF(pj_status_t) pjsua_call_set_hold2(pjsua_call_id call_id, /* Send the request */ status = pjsip_inv_send_msg( call->inv, tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send re-INVITE", status); - call->hold_msg = NULL; - goto on_return; + pjsua_perror(THIS_FILE, "Unable to send re-INVITE", status); + call->hold_msg = NULL; + goto on_return; } /* Set flag that local put the call on hold */ @@ -3203,7 +3202,7 @@ PJ_DEF(pj_status_t) pjsua_call_set_hold2(pjsua_call_id call_id, */ PJ_DEF(pj_status_t) pjsua_call_reinvite( pjsua_call_id call_id, unsigned options, - const pjsua_msg_data *msg_data) + const pjsua_msg_data *msg_data) { pjsua_call *call; pjsip_dialog *dlg = NULL; @@ -3211,10 +3210,10 @@ PJ_DEF(pj_status_t) pjsua_call_reinvite( pjsua_call_id call_id, status = acquire_call("pjsua_call_reinvite()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; if (options != call->opt.flag) - call->opt.flag = options; + call->opt.flag = options; status = pjsua_call_reinvite2(call_id, &call->opt, msg_data); @@ -3229,7 +3228,7 @@ PJ_DEF(pj_status_t) pjsua_call_reinvite( pjsua_call_id call_id, */ PJ_DEF(pj_status_t) pjsua_call_reinvite2(pjsua_call_id call_id, const pjsua_call_setting *opt, - const pjsua_msg_data *msg_data) + const pjsua_msg_data *msg_data) { pjmedia_sdp_session *sdp = NULL; pj_str_t *new_contact = NULL; @@ -3240,74 +3239,74 @@ PJ_DEF(pj_status_t) pjsua_call_reinvite2(pjsua_call_id call_id, PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Sending re-INVITE on call %d", call_id)); pj_log_push_indent(); status = acquire_call("pjsua_call_reinvite2()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; if (pjsua_call_media_is_changing(call)) { - PJ_LOG(1,(THIS_FILE, "Unable to reinvite" ERR_MEDIA_CHANGING)); - status = PJ_EINVALIDOP; - goto on_return; + PJ_LOG(1,(THIS_FILE, "Unable to reinvite" ERR_MEDIA_CHANGING)); + status = PJ_EINVALIDOP; + goto on_return; } if (call->inv->state != PJSIP_INV_STATE_CONFIRMED) { - PJ_LOG(3,(THIS_FILE, "Can not re-INVITE call that is not confirmed")); - status = PJSIP_ESESSIONSTATE; - goto on_return; + PJ_LOG(3,(THIS_FILE, "Can not re-INVITE call that is not confirmed")); + status = PJSIP_ESESSIONSTATE; + goto on_return; } status = apply_call_setting(call, opt, NULL); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Failed to apply call setting", status); - goto on_return; + pjsua_perror(THIS_FILE, "Failed to apply call setting", status); + goto on_return; } /* Create SDP */ if (call->local_hold && (call->opt.flag & PJSUA_CALL_UNHOLD)==0) { - status = create_sdp_of_call_hold(call, &sdp); + status = create_sdp_of_call_hold(call, &sdp); } else if ((call->opt.flag & PJSUA_CALL_NO_SDP_OFFER) == 0) { - status = pjsua_media_channel_create_sdp(call->index, - call->inv->pool_prov, - NULL, &sdp, NULL); + status = pjsua_media_channel_create_sdp(call->index, + call->inv->pool_prov, + NULL, &sdp, NULL); } if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to get SDP from media endpoint", - status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to get SDP from media endpoint", + status); + goto on_return; } if ((call->opt.flag & PJSUA_CALL_UPDATE_CONTACT) && - pjsua_acc_is_valid(call->acc_id)) + pjsua_acc_is_valid(call->acc_id)) { - call_update_contact(call, &new_contact); + call_update_contact(call, &new_contact); } if ((call->opt.flag & PJSUA_CALL_UPDATE_VIA) && - pjsua_acc_is_valid(call->acc_id)) + pjsua_acc_is_valid(call->acc_id)) { - dlg_set_via(call->inv->dlg, &pjsua_var.acc[call->acc_id]); + dlg_set_via(call->inv->dlg, &pjsua_var.acc[call->acc_id]); } if ((call->opt.flag & PJSUA_CALL_UPDATE_TARGET) && - msg_data && msg_data->target_uri.slen) + msg_data && msg_data->target_uri.slen) { - status = dlg_set_target(dlg, &msg_data->target_uri); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to set new target", status); - goto on_return; - } + status = dlg_set_target(dlg, &msg_data->target_uri); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to set new target", status); + goto on_return; + } } /* Create re-INVITE with new offer */ status = pjsip_inv_reinvite( call->inv, new_contact, sdp, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create re-INVITE", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to create re-INVITE", status); + goto on_return; } /* Add additional headers etc */ @@ -3320,10 +3319,10 @@ PJ_DEF(pj_status_t) pjsua_call_reinvite2(pjsua_call_id call_id, ((call->opt.flag & PJSUA_CALL_UNHOLD) && (call->opt.flag & PJSUA_CALL_NO_SDP_OFFER) == 0)) { - call->local_hold = PJ_FALSE; + call->local_hold = PJ_FALSE; } else if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send re-INVITE", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to send re-INVITE", status); + goto on_return; } on_return: @@ -3337,8 +3336,8 @@ PJ_DEF(pj_status_t) pjsua_call_reinvite2(pjsua_call_id call_id, * Send UPDATE request. */ PJ_DEF(pj_status_t) pjsua_call_update( pjsua_call_id call_id, - unsigned options, - const pjsua_msg_data *msg_data) + unsigned options, + const pjsua_msg_data *msg_data) { pjsua_call *call; pjsip_dialog *dlg = NULL; @@ -3346,10 +3345,10 @@ PJ_DEF(pj_status_t) pjsua_call_update( pjsua_call_id call_id, status = acquire_call("pjsua_call_update()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; if (options != call->opt.flag) - call->opt.flag = options; + call->opt.flag = options; status = pjsua_call_update2(call_id, &call->opt, msg_data); @@ -3363,8 +3362,8 @@ PJ_DEF(pj_status_t) pjsua_call_update( pjsua_call_id call_id, * Send UPDATE request. */ PJ_DEF(pj_status_t) pjsua_call_update2(pjsua_call_id call_id, - const pjsua_call_setting *opt, - const pjsua_msg_data *msg_data) + const pjsua_call_setting *opt, + const pjsua_msg_data *msg_data) { pjmedia_sdp_session *sdp = NULL; pj_str_t *new_contact = NULL; @@ -3374,72 +3373,72 @@ PJ_DEF(pj_status_t) pjsua_call_update2(pjsua_call_id call_id, pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Sending UPDATE on call %d", call_id)); pj_log_push_indent(); status = acquire_call("pjsua_call_update2()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Don't check media changing if UPDATE is sent without SDP */ if (pjsua_call_media_is_changing(call) && - (opt && opt->flag & PJSUA_CALL_NO_SDP_OFFER) == 0) + (opt && opt->flag & PJSUA_CALL_NO_SDP_OFFER) == 0) { - PJ_LOG(1,(THIS_FILE, "Unable to send UPDATE" ERR_MEDIA_CHANGING)); - status = PJ_EINVALIDOP; - goto on_return; + PJ_LOG(1,(THIS_FILE, "Unable to send UPDATE" ERR_MEDIA_CHANGING)); + status = PJ_EINVALIDOP; + goto on_return; } status = apply_call_setting(call, opt, NULL); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Failed to apply call setting", status); - goto on_return; + pjsua_perror(THIS_FILE, "Failed to apply call setting", status); + goto on_return; } /* Create SDP */ if (call->local_hold && (call->opt.flag & PJSUA_CALL_UNHOLD)==0) { - status = create_sdp_of_call_hold(call, &sdp); + status = create_sdp_of_call_hold(call, &sdp); } else if ((call->opt.flag & PJSUA_CALL_NO_SDP_OFFER) == 0) { - status = pjsua_media_channel_create_sdp(call->index, - call->inv->pool_prov, - NULL, &sdp, NULL); + status = pjsua_media_channel_create_sdp(call->index, + call->inv->pool_prov, + NULL, &sdp, NULL); } if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to get SDP from media endpoint", - status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to get SDP from media endpoint", + status); + goto on_return; } if ((call->opt.flag & PJSUA_CALL_UPDATE_CONTACT) && - pjsua_acc_is_valid(call->acc_id)) + pjsua_acc_is_valid(call->acc_id)) { - call_update_contact(call, &new_contact); + call_update_contact(call, &new_contact); } if ((call->opt.flag & PJSUA_CALL_UPDATE_VIA) && - pjsua_acc_is_valid(call->acc_id)) + pjsua_acc_is_valid(call->acc_id)) { - dlg_set_via(call->inv->dlg, &pjsua_var.acc[call->acc_id]); + dlg_set_via(call->inv->dlg, &pjsua_var.acc[call->acc_id]); } if ((call->opt.flag & PJSUA_CALL_UPDATE_TARGET) && - msg_data && msg_data->target_uri.slen) + msg_data && msg_data->target_uri.slen) { - status = dlg_set_target(dlg, &msg_data->target_uri); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to set new target", status); - goto on_return; - } + status = dlg_set_target(dlg, &msg_data->target_uri); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to set new target", status); + goto on_return; + } } /* Create UPDATE with new offer */ status = pjsip_inv_update(call->inv, new_contact, sdp, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create UPDATE request", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to create UPDATE request", status); + goto on_return; } /* Add additional headers etc */ @@ -3452,10 +3451,10 @@ PJ_DEF(pj_status_t) pjsua_call_update2(pjsua_call_id call_id, ((call->opt.flag & PJSUA_CALL_UNHOLD) && (call->opt.flag & PJSUA_CALL_NO_SDP_OFFER) == 0)) { - call->local_hold = PJ_FALSE; + call->local_hold = PJ_FALSE; } else if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send UPDATE request", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to send UPDATE request", status); + goto on_return; } on_return: @@ -3469,8 +3468,8 @@ PJ_DEF(pj_status_t) pjsua_call_update2(pjsua_call_id call_id, * Initiate call transfer to the specified address. */ PJ_DEF(pj_status_t) pjsua_call_xfer( pjsua_call_id call_id, - const pj_str_t *dest, - const pjsua_msg_data *msg_data) + const pj_str_t *dest, + const pjsua_msg_data *msg_data) { pjsip_evsub *sub; pjsip_tx_data *tdata; @@ -3486,12 +3485,12 @@ PJ_DEF(pj_status_t) pjsua_call_xfer( pjsua_call_id call_id, dest, PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Transferring call %d to %.*s", call_id, - (int)dest->slen, dest->ptr)); + (int)dest->slen, dest->ptr)); pj_log_push_indent(); status = acquire_call("pjsua_call_xfer()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create xfer client subscription. */ pj_bzero(&xfer_cb, sizeof(xfer_cb)); @@ -3499,8 +3498,8 @@ PJ_DEF(pj_status_t) pjsua_call_xfer( pjsua_call_id call_id, status = pjsip_xfer_create_uac(call->inv->dlg, &xfer_cb, &sub); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create xfer", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to create xfer", status); + goto on_return; } /* Associate this call with the client subscription */ @@ -3511,13 +3510,13 @@ PJ_DEF(pj_status_t) pjsua_call_xfer( pjsua_call_id call_id, */ status = pjsip_xfer_initiate(sub, dest, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create REFER request", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to create REFER request", status); + goto on_return; } /* Add Referred-By header */ gs_hdr = pjsip_generic_string_hdr_create(tdata->pool, &str_ref_by, - &dlg->local.info_str); + &dlg->local.info_str); pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)gs_hdr); @@ -3527,8 +3526,8 @@ PJ_DEF(pj_status_t) pjsua_call_xfer( pjsua_call_id call_id, /* Send. */ status = pjsip_xfer_send_request(sub, tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send REFER request", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to send REFER request", status); + goto on_return; } /* For simplicity (that's what this program is intended to be!), @@ -3547,9 +3546,9 @@ PJ_DEF(pj_status_t) pjsua_call_xfer( pjsua_call_id call_id, * Initiate attended call transfer to the specified address. */ PJ_DEF(pj_status_t) pjsua_call_xfer_replaces( pjsua_call_id call_id, - pjsua_call_id dest_call_id, - unsigned options, - const pjsua_msg_data *msg_data) + pjsua_call_id dest_call_id, + unsigned options, + const pjsua_msg_data *msg_data) { pjsua_call *dest_call; pjsip_dialog *dest_dlg; @@ -3564,20 +3563,20 @@ PJ_DEF(pj_status_t) pjsua_call_xfer_replaces( pjsua_call_id call_id, PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(dest_call_id>=0 && - dest_call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + dest_call_id<(int)pjsua_var.ua_cfg.max_calls, + PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Transferring call %d replacing with call %d", - call_id, dest_call_id)); + call_id, dest_call_id)); pj_log_push_indent(); status = acquire_call("pjsua_call_xfer_replaces()", dest_call_id, - &dest_call, &dest_dlg); + &dest_call, &dest_dlg); if (status != PJ_SUCCESS) { - pj_log_pop_indent(); - return status; + pj_log_pop_indent(); + return status; } /* @@ -3586,11 +3585,11 @@ PJ_DEF(pj_status_t) pjsua_call_xfer_replaces( pjsua_call_id call_id, /* Make sure we have sufficient buffer's length */ PJ_ASSERT_ON_FAIL(dest_dlg->remote.info_str.slen + - dest_dlg->call_id->id.slen + - dest_dlg->remote.info->tag.slen + - dest_dlg->local.info->tag.slen + 32 - < (long)sizeof(str_dest_buf), - { status=PJSIP_EURITOOLONG; goto on_error; }); + dest_dlg->call_id->id.slen + + dest_dlg->remote.info->tag.slen + + dest_dlg->local.info->tag.slen + 32 + < (long)sizeof(str_dest_buf), + { status=PJSIP_EURITOOLONG; goto on_error; }); /* Print URI */ str_dest_buf[0] = '<'; @@ -3598,14 +3597,14 @@ PJ_DEF(pj_status_t) pjsua_call_xfer_replaces( pjsua_call_id call_id, uri = (pjsip_uri*) pjsip_uri_get_uri(dest_dlg->remote.info->uri); len = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, - str_dest_buf+1, sizeof(str_dest_buf)-1); + str_dest_buf+1, sizeof(str_dest_buf)-1); if (len < 0) { - status = PJSIP_EURITOOLONG; - goto on_error; + status = PJSIP_EURITOOLONG; + goto on_error; } str_dest.slen += len; - + /* This uses the the same scanner definition used for SIP parsing * to escape the call-id in the refer. * @@ -3613,33 +3612,33 @@ PJ_DEF(pj_status_t) pjsua_call_xfer_replaces( pjsua_call_id call_id, * when used in a URL parameter, throws off many SIP parsers. * URL escape it based off of the allowed characters for header values. */ - pconst = pjsip_parser_const(); + pconst = pjsip_parser_const(); call_id_len = (int)pj_strncpy2_escape(call_id_dest_buf, &dest_dlg->call_id->id, - PJ_ARRAY_SIZE(call_id_dest_buf), - &pconst->pjsip_HDR_CHAR_SPEC); + PJ_ARRAY_SIZE(call_id_dest_buf), + &pconst->pjsip_HDR_CHAR_SPEC); if (call_id_len < 0) { - status = PJSIP_EURITOOLONG; - goto on_error; + status = PJSIP_EURITOOLONG; + goto on_error; } /* Build the URI */ len = pj_ansi_snprintf(str_dest_buf + str_dest.slen, - sizeof(str_dest_buf) - str_dest.slen, - "?%s" - "Replaces=%.*s" - "%%3Bto-tag%%3D%.*s" - "%%3Bfrom-tag%%3D%.*s>", - ((options&PJSUA_XFER_NO_REQUIRE_REPLACES) ? - "" : "Require=replaces&"), - call_id_len, - call_id_dest_buf, - (int)dest_dlg->remote.info->tag.slen, - dest_dlg->remote.info->tag.ptr, - (int)dest_dlg->local.info->tag.slen, - dest_dlg->local.info->tag.ptr); + sizeof(str_dest_buf) - str_dest.slen, + "?%s" + "Replaces=%.*s" + "%%3Bto-tag%%3D%.*s" + "%%3Bfrom-tag%%3D%.*s>", + ((options&PJSUA_XFER_NO_REQUIRE_REPLACES) ? + "" : "Require=replaces&"), + call_id_len, + call_id_dest_buf, + (int)dest_dlg->remote.info->tag.slen, + dest_dlg->remote.info->tag.ptr, + (int)dest_dlg->local.info->tag.slen, + dest_dlg->local.info->tag.ptr); PJ_ASSERT_ON_FAIL(len > 0 && len <= (int)sizeof(str_dest_buf)-str_dest.slen, - { status=PJSIP_EURITOOLONG; goto on_error; }); + { status=PJSIP_EURITOOLONG; goto on_error; }); str_dest.ptr = str_dest_buf; str_dest.slen += len; @@ -3661,38 +3660,38 @@ PJ_DEF(pj_status_t) pjsua_call_xfer_replaces( pjsua_call_id call_id, * Send DTMF digits to remote. */ PJ_DEF(pj_status_t) pjsua_call_send_dtmf(pjsua_call_id call_id, - const pjsua_call_send_dtmf_param *param) + const pjsua_call_send_dtmf_param *param) { pj_status_t status = PJ_EINVAL; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls && - param, PJ_EINVAL); + param, PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Call %d sending DTMF %.*s using %s method", - call_id, (int)param->digits.slen, param->digits.ptr, - get_dtmf_method_name(param->method))); + call_id, (int)param->digits.slen, param->digits.ptr, + get_dtmf_method_name(param->method))); if (param->method == PJSUA_DTMF_METHOD_RFC2833) { - status = pjsua_call_dial_dtmf(call_id, ¶m->digits); + status = pjsua_call_dial_dtmf(call_id, ¶m->digits); } else if (param->method == PJSUA_DTMF_METHOD_SIP_INFO) { - const pj_str_t SIP_INFO = pj_str("INFO"); - int i; + const pj_str_t SIP_INFO = pj_str("INFO"); + int i; - for (i = 0; i < param->digits.slen; ++i) { - char body[80]; - pjsua_msg_data msg_data_; + for (i = 0; i < param->digits.slen; ++i) { + char body[80]; + pjsua_msg_data msg_data_; - pjsua_msg_data_init(&msg_data_); - msg_data_.content_type = pj_str("application/dtmf-relay"); + pjsua_msg_data_init(&msg_data_); + msg_data_.content_type = pj_str("application/dtmf-relay"); - pj_ansi_snprintf(body, sizeof(body), - "Signal=%c\r\n" - "Duration=%d", - param->digits.ptr[i], param->duration); - msg_data_.msg_body = pj_str(body); + pj_ansi_snprintf(body, sizeof(body), + "Signal=%c\r\n" + "Duration=%d", + param->digits.ptr[i], param->duration); + msg_data_.msg_body = pj_str(body); - status = pjsua_call_send_request(call_id, &SIP_INFO, &msg_data_); - } + status = pjsua_call_send_request(call_id, &SIP_INFO, &msg_data_); + } } return status; @@ -3702,10 +3701,10 @@ PJ_DEF(pj_status_t) pjsua_call_send_dtmf(pjsua_call_id call_id, * Send instant messaging inside INVITE session. */ PJ_DEF(pj_status_t) pjsua_call_send_im( pjsua_call_id call_id, - const pj_str_t *mime_type, - const pj_str_t *content, - const pjsua_msg_data *msg_data, - void *user_data) + const pj_str_t *mime_type, + const pj_str_t *content, + const pjsua_msg_data *msg_data, + void *user_data) { pjsua_call *call; pjsip_dialog *dlg = NULL; @@ -3717,58 +3716,58 @@ PJ_DEF(pj_status_t) pjsua_call_send_im( pjsua_call_id call_id, pj_status_t status; content_in_msg_data = msg_data && (msg_data->msg_body.slen || - msg_data->multipart_ctype.type.slen); + msg_data->multipart_ctype.type.slen); PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); /* Message body must be specified. */ PJ_ASSERT_RETURN(content || content_in_msg_data, PJ_EINVAL); if (content) { - PJ_LOG(4,(THIS_FILE, "Call %d sending %d bytes MESSAGE..", - call_id, (int)content->slen)); + PJ_LOG(4,(THIS_FILE, "Call %d sending %d bytes MESSAGE..", + call_id, (int)content->slen)); } else { - PJ_LOG(4,(THIS_FILE, "Call %d sending MESSAGE..", - call_id)); + PJ_LOG(4,(THIS_FILE, "Call %d sending MESSAGE..", + call_id)); } pj_log_push_indent(); status = acquire_call("pjsua_call_send_im()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create request message. */ status = pjsip_dlg_create_request( call->inv->dlg, &pjsip_message_method, - -1, &tdata); + -1, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create MESSAGE request", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to create MESSAGE request", status); + goto on_return; } /* Add accept header. */ pjsip_msg_add_hdr( tdata->msg, - (pjsip_hdr*)pjsua_im_create_accept(tdata->pool)); + (pjsip_hdr*)pjsua_im_create_accept(tdata->pool)); /* Add message body, if content is set */ if (content) { - /* Set default media type if none is specified */ - if (mime_type == NULL) { - mime_type = &mime_text_plain; - } + /* Set default media type if none is specified */ + if (mime_type == NULL) { + mime_type = &mime_text_plain; + } - /* Parse MIME type */ - pjsua_parse_media_type(tdata->pool, mime_type, &ctype); + /* Parse MIME type */ + pjsua_parse_media_type(tdata->pool, mime_type, &ctype); - /* Create "text/plain" message body. */ - tdata->msg->body = pjsip_msg_body_create( tdata->pool, &ctype.type, - &ctype.subtype, content); - if (tdata->msg->body == NULL) { - pjsua_perror(THIS_FILE, "Unable to create msg body", PJ_ENOMEM); - pjsip_tx_data_dec_ref(tdata); - goto on_return; - } + /* Create "text/plain" message body. */ + tdata->msg->body = pjsip_msg_body_create( tdata->pool, &ctype.type, + &ctype.subtype, content); + if (tdata->msg->body == NULL) { + pjsua_perror(THIS_FILE, "Unable to create msg body", PJ_ENOMEM); + pjsip_tx_data_dec_ref(tdata); + goto on_return; + } } /* Add additional headers etc */ @@ -3780,16 +3779,16 @@ PJ_DEF(pj_status_t) pjsua_call_send_im( pjsua_call_id call_id, im_data->call_id = call_id; im_data->to = call->inv->dlg->remote.info_str; if (content) - pj_strdup_with_null(tdata->pool, &im_data->body, content); + pj_strdup_with_null(tdata->pool, &im_data->body, content); im_data->user_data = user_data; /* Send the request. */ status = pjsip_dlg_send_request( call->inv->dlg, tdata, - pjsua_var.mod.id, im_data); + pjsua_var.mod.id, im_data); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send MESSAGE request", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to send MESSAGE request", status); + goto on_return; } on_return: @@ -3803,8 +3802,8 @@ PJ_DEF(pj_status_t) pjsua_call_send_im( pjsua_call_id call_id, * Send IM typing indication inside INVITE session. */ PJ_DEF(pj_status_t) pjsua_call_send_typing_ind( pjsua_call_id call_id, - pj_bool_t is_typing, - const pjsua_msg_data*msg_data) + pj_bool_t is_typing, + const pjsua_msg_data*msg_data) { pjsua_call *call; pjsip_dialog *dlg = NULL; @@ -3812,27 +3811,27 @@ PJ_DEF(pj_status_t) pjsua_call_send_typing_ind( pjsua_call_id call_id, pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Call %d sending typing indication..", - call_id)); + call_id)); pj_log_push_indent(); status = acquire_call("pjsua_call_send_typing_ind", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Create request message. */ status = pjsip_dlg_create_request( call->inv->dlg, &pjsip_message_method, - -1, &tdata); + -1, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create MESSAGE request", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to create MESSAGE request", status); + goto on_return; } /* Create "application/im-iscomposing+xml" msg body. */ tdata->msg->body = pjsip_iscomposing_create_body(tdata->pool, is_typing, - NULL, NULL, -1); + NULL, NULL, -1); /* Add additional headers etc */ pjsua_process_msg_data( tdata, msg_data); @@ -3840,8 +3839,8 @@ PJ_DEF(pj_status_t) pjsua_call_send_typing_ind( pjsua_call_id call_id, /* Send the request. */ status = pjsip_dlg_send_request( call->inv->dlg, tdata, -1, NULL); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send MESSAGE request", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to send MESSAGE request", status); + goto on_return; } on_return: @@ -3855,8 +3854,8 @@ PJ_DEF(pj_status_t) pjsua_call_send_typing_ind( pjsua_call_id call_id, * Send arbitrary request. */ PJ_DEF(pj_status_t) pjsua_call_send_request(pjsua_call_id call_id, - const pj_str_t *method_str, - const pjsua_msg_data *msg_data) + const pj_str_t *method_str, + const pjsua_msg_data *msg_data) { pjsua_call *call; pjsip_dialog *dlg = NULL; @@ -3865,15 +3864,15 @@ PJ_DEF(pj_status_t) pjsua_call_send_request(pjsua_call_id call_id, pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Call %d sending %.*s request..", - call_id, (int)method_str->slen, method_str->ptr)); + call_id, (int)method_str->slen, method_str->ptr)); pj_log_push_indent(); status = acquire_call("pjsua_call_send_request", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Init method */ pjsip_method_init_np(&method, (pj_str_t*)method_str); @@ -3881,8 +3880,8 @@ PJ_DEF(pj_status_t) pjsua_call_send_request(pjsua_call_id call_id, /* Create request message. */ status = pjsip_dlg_create_request( call->inv->dlg, &method, -1, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create request", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to create request", status); + goto on_return; } /* Add additional headers etc */ @@ -3891,8 +3890,8 @@ PJ_DEF(pj_status_t) pjsua_call_send_request(pjsua_call_id call_id, /* Send the request. */ status = pjsip_dlg_send_request( call->inv->dlg, tdata, -1, NULL); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send request", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to send request", status); + goto on_return; } on_return: @@ -3916,8 +3915,8 @@ PJ_DEF(void) pjsua_call_hangup_all(void) //PJSUA_LOCK(); for (i=0; i= 96) { - pjmedia_sdp_attr *a; - pjmedia_sdp_rtpmap rtpmap; - - /* Get the format name */ - a = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "rtpmap", fmt); - if (a && pjmedia_sdp_attr_get_rtpmap(a, &rtpmap)==PJ_SUCCESS) { - /* Check for telephone-event */ - if (pj_stricmp(&rtpmap.enc_name, &STR_TEL)==0) - return PJ_TRUE; - } else { - /* Invalid SDP, should not reach here */ - pj_assert(!"SDP should have been validated!"); - return PJ_TRUE; - } + pjmedia_sdp_attr *a; + pjmedia_sdp_rtpmap rtpmap; + + /* Get the format name */ + a = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "rtpmap", fmt); + if (a && pjmedia_sdp_attr_get_rtpmap(a, &rtpmap)==PJ_SUCCESS) { + /* Check for telephone-event */ + if (pj_stricmp(&rtpmap.enc_name, &STR_TEL)==0) + return PJ_TRUE; + } else { + /* Invalid SDP, should not reach here */ + pj_assert(!"SDP should have been validated!"); + return PJ_TRUE; + } } return PJ_FALSE; @@ -3999,7 +3998,7 @@ void pjsua_call_schedule_reinvite_check(pjsua_call *call, unsigned delay_ms) /* Stop reinvite timer, if it is active */ if (call->reinv_timer.id) - pjsua_cancel_timer(&call->reinv_timer); + pjsua_cancel_timer(&call->reinv_timer); delay.sec = 0; delay.msec = delay_ms; @@ -4019,7 +4018,7 @@ static pj_bool_t check_lock_codec(pjsua_call *call) /* Check if lock codec is disabled */ if (!pjsua_var.acc[call->acc_id].cfg.lock_codec) - return PJ_FALSE; + return PJ_FALSE; /* Check lock codec retry count */ if (call->lock_codec.retry_cnt >= LOCK_CODEC_MAX_RETRY) @@ -4032,46 +4031,46 @@ static pj_bool_t check_lock_codec(pjsua_call *call) /* Check if remote answerer has given us more than one codecs. */ status = pjmedia_sdp_neg_get_active_local(call->inv->neg, &local_sdp); if (status != PJ_SUCCESS) - return PJ_FALSE; + return PJ_FALSE; status = pjmedia_sdp_neg_get_active_remote(call->inv->neg, &remote_sdp); if (status != PJ_SUCCESS) - return PJ_FALSE; + return PJ_FALSE; for (i = 0; i < call->med_cnt && !has_mult_fmt; ++i) { - pjsua_call_media *call_med = &call->media[i]; - const pjmedia_sdp_media *rem_m, *loc_m; - unsigned codec_cnt = 0; - unsigned j; - - /* Skip this if the media is inactive or error */ - if (call_med->state == PJSUA_CALL_MEDIA_NONE || - call_med->state == PJSUA_CALL_MEDIA_ERROR || - call_med->dir == PJMEDIA_DIR_NONE) - { - continue; - } + pjsua_call_media *call_med = &call->media[i]; + const pjmedia_sdp_media *rem_m, *loc_m; + unsigned codec_cnt = 0; + unsigned j; + + /* Skip this if the media is inactive or error */ + if (call_med->state == PJSUA_CALL_MEDIA_NONE || + call_med->state == PJSUA_CALL_MEDIA_ERROR || + call_med->dir == PJMEDIA_DIR_NONE) + { + continue; + } - /* Remote may answer with less media lines. */ - if (i >= remote_sdp->media_count) - continue; + /* Remote may answer with less media lines. */ + if (i >= remote_sdp->media_count) + continue; - rem_m = remote_sdp->media[i]; - loc_m = local_sdp->media[i]; + rem_m = remote_sdp->media[i]; + loc_m = local_sdp->media[i]; - /* Verify that media must be active. */ - pj_assert(loc_m->desc.port && rem_m->desc.port); - PJ_UNUSED_ARG(loc_m); + /* Verify that media must be active. */ + pj_assert(loc_m->desc.port && rem_m->desc.port); + PJ_UNUSED_ARG(loc_m); - /* Count the formats in the answer. */ - for (j=0; jdesc.fmt_count && codec_cnt <= 1; ++j) { - if (!is_non_av_fmt(rem_m, &rem_m->desc.fmt[j]) && ++codec_cnt > 1) - has_mult_fmt = PJ_TRUE; - } + /* Count the formats in the answer. */ + for (j=0; jdesc.fmt_count && codec_cnt <= 1; ++j) { + if (!is_non_av_fmt(rem_m, &rem_m->desc.fmt[j]) && ++codec_cnt > 1) + has_mult_fmt = PJ_TRUE; + } } /* Reset retry count when remote answer has one codec */ if (!has_mult_fmt) - call->lock_codec.retry_cnt = 0; + call->lock_codec.retry_cnt = 0; return has_mult_fmt; } @@ -4085,50 +4084,50 @@ static pj_bool_t check_ice_complete(pjsua_call *call, pj_bool_t *need_reinv) /* Check if ICE setup is complete and if it needs reinvite */ for (i = 0; i < call->med_cnt; ++i) { - pjsua_call_media *call_med = &call->media[i]; - pjmedia_transport_info tpinfo; - pjmedia_ice_transport_info *ice_info; - - if (call_med->tp_st == PJSUA_MED_TP_NULL || - call_med->tp_st == PJSUA_MED_TP_DISABLED || - call_med->state == PJSUA_CALL_MEDIA_ERROR) - { - continue; - } - - pjmedia_transport_info_init(&tpinfo); - pjmedia_transport_get_info(call_med->tp, &tpinfo); - ice_info = (pjmedia_ice_transport_info*) - pjmedia_transport_info_get_spc_info( - &tpinfo, PJMEDIA_TRANSPORT_TYPE_ICE); - - /* Check if ICE is active */ - if (!ice_info || !ice_info->active) - continue; - - /* Check if ICE setup not completed yet */ - if (ice_info->sess_state < PJ_ICE_STRANS_STATE_RUNNING) { - ice_complete = PJ_FALSE; - break; - } - - /* Check if ICE needs to send reinvite */ - if (!ice_need_reinv && - ice_info->sess_state == PJ_ICE_STRANS_STATE_RUNNING && - ice_info->role == PJ_ICE_SESS_ROLE_CONTROLLING) - { - pjsua_ice_config *cfg=&pjsua_var.acc[call->acc_id].cfg.ice_cfg; - if ((cfg->ice_always_update && !call->reinv_ice_sent) || - pj_sockaddr_cmp(&tpinfo.sock_info.rtp_addr_name, - &call_med->rtp_addr)) - { - ice_need_reinv = PJ_TRUE; - } - } + pjsua_call_media *call_med = &call->media[i]; + pjmedia_transport_info tpinfo; + pjmedia_ice_transport_info *ice_info; + + if (call_med->tp_st == PJSUA_MED_TP_NULL || + call_med->tp_st == PJSUA_MED_TP_DISABLED || + call_med->state == PJSUA_CALL_MEDIA_ERROR) + { + continue; + } + + pjmedia_transport_info_init(&tpinfo); + pjmedia_transport_get_info(call_med->tp, &tpinfo); + ice_info = (pjmedia_ice_transport_info*) + pjmedia_transport_info_get_spc_info( + &tpinfo, PJMEDIA_TRANSPORT_TYPE_ICE); + + /* Check if ICE is active */ + if (!ice_info || !ice_info->active) + continue; + + /* Check if ICE setup not completed yet */ + if (ice_info->sess_state < PJ_ICE_STRANS_STATE_RUNNING) { + ice_complete = PJ_FALSE; + break; + } + + /* Check if ICE needs to send reinvite */ + if (!ice_need_reinv && + ice_info->sess_state == PJ_ICE_STRANS_STATE_RUNNING && + ice_info->role == PJ_ICE_SESS_ROLE_CONTROLLING) + { + pjsua_ice_config *cfg=&pjsua_var.acc[call->acc_id].cfg.ice_cfg; + if ((cfg->ice_always_update && !call->reinv_ice_sent) || + pj_sockaddr_cmp(&tpinfo.sock_info.rtp_addr_name, + &call_med->rtp_addr)) + { + ice_need_reinv = PJ_TRUE; + } + } } if (ice_complete && need_reinv) - *need_reinv = ice_need_reinv; + *need_reinv = ice_need_reinv; return ice_complete; } @@ -4152,27 +4151,27 @@ static pj_status_t process_pending_reinvite(pjsua_call *call) * or another re-INVITE. */ if (inv==NULL || inv->neg==NULL || - pjmedia_sdp_neg_get_state(inv->neg)!=PJMEDIA_SDP_NEG_STATE_DONE) + pjmedia_sdp_neg_get_state(inv->neg)!=PJMEDIA_SDP_NEG_STATE_DONE) { - return PJMEDIA_SDPNEG_EINSTATE; + return PJMEDIA_SDPNEG_EINSTATE; } /* Don't do this if call is disconnecting! */ if (inv->state > PJSIP_INV_STATE_CONFIRMED || inv->cause >= 200) { - return PJ_EINVALIDOP; + return PJ_EINVALIDOP; } if (inv->state == PJSIP_INV_STATE_EARLY) { - if (pjsip_dlg_remote_has_cap(inv->dlg, PJSIP_H_ALLOW, NULL, - &ST_UPDATE) == PJSIP_DIALOG_CAP_SUPPORTED && - inv->sdp_done_early_rel && - !PJSUA_LOCK_CODEC_DONT_USE_UPDATE) - { - /* Yes, remote supports UPDATE and SDP negotiation was done - * using reliable provisional responses. We can proceed. - */ - } else { + if (pjsip_dlg_remote_has_cap(inv->dlg, PJSIP_H_ALLOW, NULL, + &ST_UPDATE) == PJSIP_DIALOG_CAP_SUPPORTED && + inv->sdp_done_early_rel && + !PJSUA_LOCK_CODEC_DONT_USE_UPDATE) + { + /* Yes, remote supports UPDATE and SDP negotiation was done + * using reliable provisional responses. We can proceed. + */ + } else { call->reinv_pending = PJ_TRUE; return PJ_EPENDING; } @@ -4181,36 +4180,36 @@ static pj_status_t process_pending_reinvite(pjsua_call *call) /* Check if ICE setup is complete and if it needs reinvite */ ice_completed = check_ice_complete(call, &ice_need_reinv); if (!ice_completed) - return PJ_EPENDING; + return PJ_EPENDING; /* Check if we need to lock codec */ need_lock_codec = check_lock_codec(call); /* Check if reinvite is really needed */ if (!need_lock_codec && !ice_need_reinv) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Okay! So we need to send re-INVITE/UPDATE */ /* Check if remote support UPDATE */ rem_can_update = !PJSUA_LOCK_CODEC_DONT_USE_UPDATE && - pjsip_dlg_remote_has_cap(inv->dlg, PJSIP_H_ALLOW, NULL, - &ST_UPDATE) == - PJSIP_DIALOG_CAP_SUPPORTED; + pjsip_dlg_remote_has_cap(inv->dlg, PJSIP_H_ALLOW, NULL, + &ST_UPDATE) == + PJSIP_DIALOG_CAP_SUPPORTED; /* Logging stuff */ { - const char *ST_ICE_UPDATE = "ICE transport address after " - "ICE negotiation"; - const char *ST_LOCK_CODEC = "media session to use only one codec"; - PJ_LOG(4,(THIS_FILE, "Call %d sending %s for updating %s%s%s", - call->index, - (rem_can_update? "UPDATE" : "re-INVITE"), - (ice_need_reinv? ST_ICE_UPDATE : ST_LOCK_CODEC), - (ice_need_reinv && need_lock_codec? " and " : ""), - (ice_need_reinv && need_lock_codec? ST_LOCK_CODEC : "") - )); + const char *ST_ICE_UPDATE = "ICE transport address after " + "ICE negotiation"; + const char *ST_LOCK_CODEC = "media session to use only one codec"; + PJ_LOG(4,(THIS_FILE, "Call %d sending %s for updating %s%s%s", + call->index, + (rem_can_update? "UPDATE" : "re-INVITE"), + (ice_need_reinv? ST_ICE_UPDATE : ST_LOCK_CODEC), + (ice_need_reinv && need_lock_codec? " and " : ""), + (ice_need_reinv && need_lock_codec? ST_LOCK_CODEC : "") + )); } /* Clear reinit media flag. Should we also cleanup other flags here? */ @@ -4218,10 +4217,10 @@ static pj_status_t process_pending_reinvite(pjsua_call *call) /* Generate SDP re-offer */ status = pjsua_media_channel_create_sdp(call->index, pool, NULL, - &new_offer, NULL); + &new_offer, NULL); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create local SDP", status); - return status; + pjsua_perror(THIS_FILE, "Unable to create local SDP", status); + return status; } /* Update the new offer so it contains only a codec. Note that @@ -4231,173 +4230,173 @@ static pj_status_t process_pending_reinvite(pjsua_call *call) * local SDP and leave just one codec for the next SDP re-offer. */ if (need_lock_codec) { - const pjmedia_sdp_session *ref_sdp; - - /* Get local active SDP as reference */ - status = pjmedia_sdp_neg_get_active_local(call->inv->neg, &ref_sdp); - if (status != PJ_SUCCESS) - return status; - - /* Verify media count. Note that remote may add/remove media line - * in the answer. When answer has less media, it must have been - * handled by pjsua_media_channel_update() as disabled media. - * When answer has more media, it must have been ignored (treated - * as non-exist) anywhere. Local media count should not be updated - * at this point, as modifying media count operation (i.e: reinvite, - * update, vid_set_strm) is currently blocking, protected with - * dialog mutex, and eventually reset SDP nego state to LOCAL OFFER. - */ - if (call->med_cnt != ref_sdp->media_count || - ref_sdp->media_count != new_offer->media_count) - { - /* Anyway, just in case, let's just return error */ - return PJMEDIA_SDPNEG_EINSTATE; - } - - for (i = 0; i < call->med_cnt; ++i) { - unsigned j, codec_cnt = 0; - const pjmedia_sdp_media *ref_m = ref_sdp->media[i]; - pjmedia_sdp_media *m = new_offer->media[i]; - pjsua_call_media *call_med = &call->media[i]; - - /* Verify if media is deactivated */ - if (call_med->state == PJSUA_CALL_MEDIA_NONE || - call_med->state == PJSUA_CALL_MEDIA_ERROR || - call_med->dir == PJMEDIA_DIR_NONE) - { - continue; - } - - /* Reset formats */ - m->desc.fmt_count = 0; - pjmedia_sdp_attr_remove_all(&m->attr_count, m->attr, "rtpmap"); - pjmedia_sdp_attr_remove_all(&m->attr_count, m->attr, "fmtp"); - - /* Copy only the first format + any non-AV formats from - * the active local SDP. - */ - for (j = 0; j < ref_m->desc.fmt_count; ++j) { - const pj_str_t *fmt = &ref_m->desc.fmt[j]; - - if (is_non_av_fmt(ref_m, fmt) || (++codec_cnt == 1)) { - pjmedia_sdp_attr *a; - - m->desc.fmt[m->desc.fmt_count++] = *fmt; - a = pjmedia_sdp_attr_find2(ref_m->attr_count, ref_m->attr, - "rtpmap", fmt); - if (a) { - pjmedia_sdp_attr_add(&m->attr_count, m->attr, - pjmedia_sdp_attr_clone(pool, a)); - } - a = pjmedia_sdp_attr_find2(ref_m->attr_count, ref_m->attr, - "fmtp", fmt); - if (a) { - pjmedia_sdp_attr_add(&m->attr_count, m->attr, - pjmedia_sdp_attr_clone(pool, a)); - } - } - } - } + const pjmedia_sdp_session *ref_sdp; + + /* Get local active SDP as reference */ + status = pjmedia_sdp_neg_get_active_local(call->inv->neg, &ref_sdp); + if (status != PJ_SUCCESS) + return status; + + /* Verify media count. Note that remote may add/remove media line + * in the answer. When answer has less media, it must have been + * handled by pjsua_media_channel_update() as disabled media. + * When answer has more media, it must have been ignored (treated + * as non-exist) anywhere. Local media count should not be updated + * at this point, as modifying media count operation (i.e: reinvite, + * update, vid_set_strm) is currently blocking, protected with + * dialog mutex, and eventually reset SDP nego state to LOCAL OFFER. + */ + if (call->med_cnt != ref_sdp->media_count || + ref_sdp->media_count != new_offer->media_count) + { + /* Anyway, just in case, let's just return error */ + return PJMEDIA_SDPNEG_EINSTATE; + } + + for (i = 0; i < call->med_cnt; ++i) { + unsigned j, codec_cnt = 0; + const pjmedia_sdp_media *ref_m = ref_sdp->media[i]; + pjmedia_sdp_media *m = new_offer->media[i]; + pjsua_call_media *call_med = &call->media[i]; + + /* Verify if media is deactivated */ + if (call_med->state == PJSUA_CALL_MEDIA_NONE || + call_med->state == PJSUA_CALL_MEDIA_ERROR || + call_med->dir == PJMEDIA_DIR_NONE) + { + continue; + } + + /* Reset formats */ + m->desc.fmt_count = 0; + pjmedia_sdp_attr_remove_all(&m->attr_count, m->attr, "rtpmap"); + pjmedia_sdp_attr_remove_all(&m->attr_count, m->attr, "fmtp"); + + /* Copy only the first format + any non-AV formats from + * the active local SDP. + */ + for (j = 0; j < ref_m->desc.fmt_count; ++j) { + const pj_str_t *fmt = &ref_m->desc.fmt[j]; + + if (is_non_av_fmt(ref_m, fmt) || (++codec_cnt == 1)) { + pjmedia_sdp_attr *a; + + m->desc.fmt[m->desc.fmt_count++] = *fmt; + a = pjmedia_sdp_attr_find2(ref_m->attr_count, ref_m->attr, + "rtpmap", fmt); + if (a) { + pjmedia_sdp_attr_add(&m->attr_count, m->attr, + pjmedia_sdp_attr_clone(pool, a)); + } + a = pjmedia_sdp_attr_find2(ref_m->attr_count, ref_m->attr, + "fmtp", fmt); + if (a) { + pjmedia_sdp_attr_add(&m->attr_count, m->attr, + pjmedia_sdp_attr_clone(pool, a)); + } + } + } + } } /* Put back original direction and "c=0.0.0.0" line */ { - const pjmedia_sdp_session *cur_sdp; - - /* Get local active SDP */ - status = pjmedia_sdp_neg_get_active_local(call->inv->neg, &cur_sdp); - if (status != PJ_SUCCESS) - return status; - - /* Make sure media count has not been changed */ - if (call->med_cnt != cur_sdp->media_count) - return PJMEDIA_SDPNEG_EINSTATE; - - for (i = 0; i < call->med_cnt; ++i) { - const pjmedia_sdp_media *m = cur_sdp->media[i]; - pjmedia_sdp_media *new_m = new_offer->media[i]; - pjsua_call_media *call_med = &call->media[i]; - pjmedia_sdp_attr *a = NULL; - - /* Update direction to the current dir */ - pjmedia_sdp_media_remove_all_attr(new_m, "sendrecv"); - pjmedia_sdp_media_remove_all_attr(new_m, "sendonly"); - pjmedia_sdp_media_remove_all_attr(new_m, "recvonly"); - pjmedia_sdp_media_remove_all_attr(new_m, "inactive"); - - if (call_med->dir == PJMEDIA_DIR_ENCODING_DECODING) { - a = pjmedia_sdp_attr_create(pool, "sendrecv", NULL); - } else if (call_med->dir == PJMEDIA_DIR_ENCODING) { - a = pjmedia_sdp_attr_create(pool, "sendonly", NULL); - } else if (call_med->dir == PJMEDIA_DIR_DECODING) { - a = pjmedia_sdp_attr_create(pool, "recvonly", NULL); - } else { - const pjmedia_sdp_conn *conn; - a = pjmedia_sdp_attr_create(pool, "inactive", NULL); - - /* Also check if the original c= line address is zero */ - conn = m->conn; - if (!conn) - conn = cur_sdp->conn; - if (pj_strcmp2(&conn->addr, "0.0.0.0")==0 || - pj_strcmp2(&conn->addr, "0")==0) - { - if (!new_m->conn) { - new_m->conn = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_conn); - } - - if (pj_strcmp2(&new_m->conn->addr, "0.0.0.0")) { - new_m->conn->net_type = pj_str("IN"); - new_m->conn->addr_type = pj_str("IP4"); - new_m->conn->addr = pj_str("0.0.0.0"); - } - } - } - - pj_assert(a); - pjmedia_sdp_media_add_attr(new_m, a); - } + const pjmedia_sdp_session *cur_sdp; + + /* Get local active SDP */ + status = pjmedia_sdp_neg_get_active_local(call->inv->neg, &cur_sdp); + if (status != PJ_SUCCESS) + return status; + + /* Make sure media count has not been changed */ + if (call->med_cnt != cur_sdp->media_count) + return PJMEDIA_SDPNEG_EINSTATE; + + for (i = 0; i < call->med_cnt; ++i) { + const pjmedia_sdp_media *m = cur_sdp->media[i]; + pjmedia_sdp_media *new_m = new_offer->media[i]; + pjsua_call_media *call_med = &call->media[i]; + pjmedia_sdp_attr *a = NULL; + + /* Update direction to the current dir */ + pjmedia_sdp_media_remove_all_attr(new_m, "sendrecv"); + pjmedia_sdp_media_remove_all_attr(new_m, "sendonly"); + pjmedia_sdp_media_remove_all_attr(new_m, "recvonly"); + pjmedia_sdp_media_remove_all_attr(new_m, "inactive"); + + if (call_med->dir == PJMEDIA_DIR_ENCODING_DECODING) { + a = pjmedia_sdp_attr_create(pool, "sendrecv", NULL); + } else if (call_med->dir == PJMEDIA_DIR_ENCODING) { + a = pjmedia_sdp_attr_create(pool, "sendonly", NULL); + } else if (call_med->dir == PJMEDIA_DIR_DECODING) { + a = pjmedia_sdp_attr_create(pool, "recvonly", NULL); + } else { + const pjmedia_sdp_conn *conn; + a = pjmedia_sdp_attr_create(pool, "inactive", NULL); + + /* Also check if the original c= line address is zero */ + conn = m->conn; + if (!conn) + conn = cur_sdp->conn; + if (pj_strcmp2(&conn->addr, "0.0.0.0")==0 || + pj_strcmp2(&conn->addr, "0")==0) + { + if (!new_m->conn) { + new_m->conn = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_conn); + } + + if (pj_strcmp2(&new_m->conn->addr, "0.0.0.0")) { + new_m->conn->net_type = pj_str("IN"); + new_m->conn->addr_type = pj_str("IP4"); + new_m->conn->addr = pj_str("0.0.0.0"); + } + } + } + + pj_assert(a); + pjmedia_sdp_media_add_attr(new_m, a); + } } if (rem_can_update) { - status = pjsip_inv_update(inv, NULL, new_offer, &tdata); + status = pjsip_inv_update(inv, NULL, new_offer, &tdata); } else { - status = pjsip_inv_reinvite(inv, NULL, new_offer, &tdata); + status = pjsip_inv_reinvite(inv, NULL, new_offer, &tdata); } if (status==PJ_EINVALIDOP && - ++call->lock_codec.retry_cnt < LOCK_CODEC_MAX_RETRY) + ++call->lock_codec.retry_cnt < LOCK_CODEC_MAX_RETRY) { - /* Ups, let's reschedule again */ - pjsua_call_schedule_reinvite_check(call, LOCK_CODEC_RETRY_INTERVAL); - return PJ_SUCCESS; + /* Ups, let's reschedule again */ + pjsua_call_schedule_reinvite_check(call, LOCK_CODEC_RETRY_INTERVAL); + return PJ_SUCCESS; } else if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating UPDATE/re-INVITE", - status); - return status; + pjsua_perror(THIS_FILE, "Error creating UPDATE/re-INVITE", + status); + return status; } /* Send the UPDATE/re-INVITE request */ status = pjsip_inv_send_msg(inv, tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error sending UPDATE/re-INVITE", - status); - return status; + pjsua_perror(THIS_FILE, "Error sending UPDATE/re-INVITE", + status); + return status; } /* Update flags */ if (ice_need_reinv) - call->reinv_ice_sent = PJ_TRUE; + call->reinv_ice_sent = PJ_TRUE; if (need_lock_codec) - ++call->lock_codec.retry_cnt; + ++call->lock_codec.retry_cnt; return PJ_SUCCESS; } static void trickle_ice_retrans_18x(pj_timer_heap_t *th, - struct pj_timer_entry *te) + struct pj_timer_entry *te) { pjsua_call *call = (pjsua_call*)te->user_data; pjsip_tx_data *tdata = NULL; @@ -4409,39 +4408,39 @@ static void trickle_ice_retrans_18x(pj_timer_heap_t *th, * both sides, stop 18x retransmission. */ if (call->trickle_ice.trickling >= PJSUA_OP_STATE_RUNNING || - call->trickle_ice.remote_dlg_est) + call->trickle_ice.remote_dlg_est) { - return; + return; } /* Make sure last tdata is 18x response */ if (call->inv->invite_tsx) - tdata = call->inv->invite_tsx->last_tx; + tdata = call->inv->invite_tsx->last_tx; if (!tdata || tdata->msg->type != PJSIP_RESPONSE_MSG || - tdata->msg->line.status.code/10 != 18) + tdata->msg->line.status.code/10 != 18) { - return; + return; } /* Retransmit 18x */ ++call->trickle_ice.retrans18x_count; PJ_LOG(4,(THIS_FILE, - "Call %d: ICE trickle retransmitting 18x (retrans #%d)", - call->index, call->trickle_ice.retrans18x_count)); + "Call %d: ICE trickle retransmitting 18x (retrans #%d)", + call->index, call->trickle_ice.retrans18x_count)); pjsip_tx_data_add_ref(tdata); pjsip_tsx_retransmit_no_state(call->inv->invite_tsx, tdata); /* Schedule next retransmission */ if (call->trickle_ice.retrans18x_count < 6) { - pj_uint32_t tmp; - tmp = (1 << call->trickle_ice.retrans18x_count) * pjsip_cfg()->tsx.t1; - delay.sec = 0; - delay.msec = tmp; - pj_time_val_normalize(&delay); + pj_uint32_t tmp; + tmp = (1 << call->trickle_ice.retrans18x_count) * pjsip_cfg()->tsx.t1; + delay.sec = 0; + delay.msec = tmp; + pj_time_val_normalize(&delay); } else { - delay.sec = 1; - delay.msec = 500; + delay.sec = 1; + delay.msec = 500; } pjsua_schedule_timer(te, &delay); } @@ -4460,10 +4459,10 @@ static void trickle_ice_recv_sip_info(pjsua_call *call, pjsip_rx_data *rdata) /* Parse the SDP */ sdp_info = pjsip_rdata_get_sdp_info2(rdata, &med_type); if (!sdp_info->sdp) { - pj_status_t err = sdp_info->body.ptr? sdp_info->sdp_err:PJ_ENOTFOUND; - pjsua_perror(THIS_FILE, "Failed to parse trickle ICE SDP in " - "incoming INFO", err); - return; + pj_status_t err = sdp_info->body.ptr? sdp_info->sdp_err:PJ_ENOTFOUND; + pjsua_perror(THIS_FILE, "Failed to parse trickle ICE SDP in " + "incoming INFO", err); + return; } PJSUA_LOCK(); @@ -4472,49 +4471,49 @@ static void trickle_ice_recv_sip_info(pjsua_call *call, pjsip_rx_data *rdata) use_med_prov = call->med_prov_cnt > call->med_cnt; med_cnt = use_med_prov? call->med_prov_cnt : call->med_cnt; for (i = 0; i < sdp_info->sdp->media_count; ++i) { - pjmedia_transport *tp = NULL; - pj_str_t mid, ufrag, pwd; - unsigned cand_cnt = PJ_ICE_ST_MAX_CAND; - pj_ice_sess_cand cand[PJ_ICE_ST_MAX_CAND]; - pj_bool_t end_of_cand; - - status = pjmedia_ice_trickle_decode_sdp(sdp_info->sdp, i, &mid, - &ufrag, &pwd, - &cand_cnt, cand, - &end_of_cand); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Failed to retrive ICE candidates from " - "SDP in incoming INFO", status); - continue; - } - - for (j = 0; j < med_cnt; ++j) { - pjsua_call_media *cm = use_med_prov? &call->media_prov[j] : - &call->media[j]; - tp = cm->tp_orig; - - if (tp && tp->type == PJMEDIA_TRANSPORT_TYPE_ICE && - pj_strcmp(&cm->rem_mid, &mid) == 0) - { - break; - } - } - - if (j == med_cnt) { - pjsua_perror(THIS_FILE, "Cannot add remote candidates from SDP in " - "incoming INFO because media ID (SDP a=mid) is not " - "recognized", - PJ_EIGNORED); - continue; - } - - /* Update ICE checklist */ - status = pjmedia_ice_trickle_update(tp, &ufrag, &pwd, cand_cnt, cand, - end_of_cand); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Failed to update ICE checklist from " - "incoming INFO", status); - } + pjmedia_transport *tp = NULL; + pj_str_t mid, ufrag, pwd; + unsigned cand_cnt = PJ_ICE_ST_MAX_CAND; + pj_ice_sess_cand cand[PJ_ICE_ST_MAX_CAND]; + pj_bool_t end_of_cand; + + status = pjmedia_ice_trickle_decode_sdp(sdp_info->sdp, i, &mid, + &ufrag, &pwd, + &cand_cnt, cand, + &end_of_cand); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Failed to retrive ICE candidates from " + "SDP in incoming INFO", status); + continue; + } + + for (j = 0; j < med_cnt; ++j) { + pjsua_call_media *cm = use_med_prov? &call->media_prov[j] : + &call->media[j]; + tp = cm->tp_orig; + + if (tp && tp->type == PJMEDIA_TRANSPORT_TYPE_ICE && + pj_strcmp(&cm->rem_mid, &mid) == 0) + { + break; + } + } + + if (j == med_cnt) { + pjsua_perror(THIS_FILE, "Cannot add remote candidates from SDP in " + "incoming INFO because media ID (SDP a=mid) is not " + "recognized", + PJ_EIGNORED); + continue; + } + + /* Update ICE checklist */ + status = pjmedia_ice_trickle_update(tp, &ufrag, &pwd, cand_cnt, cand, + end_of_cand); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Failed to update ICE checklist from " + "incoming INFO", status); + } } PJSUA_UNLOCK(); @@ -4522,7 +4521,7 @@ static void trickle_ice_recv_sip_info(pjsua_call *call, pjsip_rx_data *rdata) static void trickle_ice_send_sip_info(pj_timer_heap_t *th, - struct pj_timer_entry *te) + struct pj_timer_entry *te) { pjsua_call *call = (pjsua_call*)te->user_data; pj_pool_t *tmp_pool = NULL; @@ -4535,10 +4534,10 @@ static void trickle_ice_send_sip_info(pj_timer_heap_t *th, pj_bool_t forced, need_send = PJ_FALSE; pj_sockaddr orig_addr; - pj_str_t SIP_INFO = {"INFO", 4}; - pj_str_t CONTENT_DISP_STR = {"Content-Disposition", 19}; - pj_str_t INFO_PKG_STR = {"Info-Package", 12}; - pj_str_t TRICKLE_ICE_STR = {"trickle-ice", 11}; + pj_str_t SIP_INFO = {"INFO", 4}; + pj_str_t CONTENT_DISP_STR = {"Content-Disposition", 19}; + pj_str_t INFO_PKG_STR = {"Info-Package", 12}; + pj_str_t TRICKLE_ICE_STR = {"trickle-ice", 11}; PJ_UNUSED_ARG(th); @@ -4550,30 +4549,30 @@ static void trickle_ice_send_sip_info(pj_timer_heap_t *th, /* Check if any pending INFO already */ if (call->trickle_ice.pending_info) - goto on_return; + goto on_return; /* Check if any new candidate, if not forced */ forced = (te->id == 2); if (!forced) { - for (i = 0; i < med_cnt; ++i) { - pjsua_call_media *cm = use_med_prov? &call->media_prov[i] : - &call->media[i]; - pjmedia_transport *tp = cm->tp_orig; + for (i = 0; i < med_cnt; ++i) { + pjsua_call_media *cm = use_med_prov? &call->media_prov[i] : + &call->media[i]; + pjmedia_transport *tp = cm->tp_orig; - if (!tp || tp->type != PJMEDIA_TRANSPORT_TYPE_ICE) - continue; + if (!tp || tp->type != PJMEDIA_TRANSPORT_TYPE_ICE) + continue; - if (pjmedia_ice_trickle_has_new_cand(tp)) - break; - } + if (pjmedia_ice_trickle_has_new_cand(tp)) + break; + } - /* No new local candidate */ - if (i == med_cnt) - goto on_return; + /* No new local candidate */ + if (i == med_cnt) + goto on_return; } PJ_LOG(4,(THIS_FILE, "Call %d: ICE trickle sending SIP INFO%s", - call->index, (forced? " (forced)":""))); + call->index, (forced? " (forced)":""))); /* Create temporary pool */ tmp_pool = pjsua_pool_create("tmp_ice", 128, 128); @@ -4581,31 +4580,31 @@ static void trickle_ice_send_sip_info(pj_timer_heap_t *th, /* Create empty SDP */ pj_sockaddr_init(pj_AF_INET(), &orig_addr, NULL, 0); status = pjmedia_endpt_create_base_sdp(pjsua_var.med_endpt, tmp_pool, - NULL, &orig_addr, &sdp); + NULL, &orig_addr, &sdp); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Generate SDP for SIP INFO */ all_end_of_cand = PJ_TRUE; for (i = 0; i < med_cnt; ++i) { - pjsua_call_media *cm = use_med_prov? &call->media_prov[i] : - &call->media[i]; - pjmedia_transport *tp = cm->tp_orig; - pj_bool_t end_of_cand = PJ_FALSE; + pjsua_call_media *cm = use_med_prov? &call->media_prov[i] : + &call->media[i]; + pjmedia_transport *tp = cm->tp_orig; + pj_bool_t end_of_cand = PJ_FALSE; - if (!tp || tp->type != PJMEDIA_TRANSPORT_TYPE_ICE) - continue; + if (!tp || tp->type != PJMEDIA_TRANSPORT_TYPE_ICE) + continue; - status = pjmedia_ice_trickle_send_local_cand(tp, tmp_pool, sdp, - &end_of_cand); - if (status != PJ_SUCCESS || !end_of_cand) - all_end_of_cand = PJ_FALSE; + status = pjmedia_ice_trickle_send_local_cand(tp, tmp_pool, sdp, + &end_of_cand); + if (status != PJ_SUCCESS || !end_of_cand) + all_end_of_cand = PJ_FALSE; - need_send |= (status==PJ_SUCCESS); + need_send |= (status==PJ_SUCCESS); } if (!need_send) - goto on_return; + goto on_return; /* Generate and send SIP INFO */ pjsua_msg_data_init(&msg_data); @@ -4618,53 +4617,53 @@ static void trickle_ice_send_sip_info(pj_timer_heap_t *th, msg_data.content_type = pj_str("application/trickle-ice-sdpfrag"); msg_data.msg_body.ptr = pj_pool_alloc(tmp_pool, PJSIP_MAX_PKT_LEN); msg_data.msg_body.slen = pjmedia_sdp_print(sdp, msg_data.msg_body.ptr, - PJSIP_MAX_PKT_LEN); + PJSIP_MAX_PKT_LEN); if (msg_data.msg_body.slen == -1) { - PJ_LOG(3,(THIS_FILE, - "Warning! Call %d: ICE trickle failed to print SDP for " - "SIP INFO due to insufficient buffer", call->index)); - goto on_return; + PJ_LOG(3,(THIS_FILE, + "Warning! Call %d: ICE trickle failed to print SDP for " + "SIP INFO due to insufficient buffer", call->index)); + goto on_return; } status = pjsua_call_send_request(call->index, &SIP_INFO, &msg_data); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; /* Set flag for pending SIP INFO */ call->trickle_ice.pending_info = PJ_TRUE; /* Stop trickling if local candidate gathering for all media is done */ if (all_end_of_cand) { - PJ_LOG(4,(THIS_FILE, "Call %d: ICE trickle stopped trickling " - "as local candidate gathering completed", - call->index)); - call->trickle_ice.trickling = PJSUA_OP_STATE_DONE; + PJ_LOG(4,(THIS_FILE, "Call %d: ICE trickle stopped trickling " + "as local candidate gathering completed", + call->index)); + call->trickle_ice.trickling = PJSUA_OP_STATE_DONE; } /* Update ICE checklist after conveying local candidates. */ for (i = 0; i < med_cnt; ++i) { - pjsua_call_media *cm = use_med_prov? &call->media_prov[i] : - &call->media[i]; - pjmedia_transport *tp = cm->tp_orig; - if (!tp || tp->type != PJMEDIA_TRANSPORT_TYPE_ICE) - continue; + pjsua_call_media *cm = use_med_prov? &call->media_prov[i] : + &call->media[i]; + pjmedia_transport *tp = cm->tp_orig; + if (!tp || tp->type != PJMEDIA_TRANSPORT_TYPE_ICE) + continue; - pjmedia_ice_trickle_update(tp, NULL, NULL, 0, NULL, PJ_FALSE); + pjmedia_ice_trickle_update(tp, NULL, NULL, 0, NULL, PJ_FALSE); } on_return: if (tmp_pool) - pj_pool_release(tmp_pool); + pj_pool_release(tmp_pool); /* Reschedule if we are trickling */ if (call->trickle_ice.trickling == PJSUA_OP_STATE_RUNNING) { - pj_time_val delay = {0, PJSUA_TRICKLE_ICE_NEW_CAND_CHECK_INTERVAL}; + pj_time_val delay = {0, PJSUA_TRICKLE_ICE_NEW_CAND_CHECK_INTERVAL}; - /* Reset forced mode after successfully sending forced SIP INFO */ - te->id = (status==PJ_SUCCESS? 0 : 2); + /* Reset forced mode after successfully sending forced SIP INFO */ + te->id = (status==PJ_SUCCESS? 0 : 2); - pj_time_val_normalize(&delay); - pjsua_schedule_timer(te, &delay); + pj_time_val_normalize(&delay); + pjsua_schedule_timer(te, &delay); } PJSUA_UNLOCK(); @@ -4684,186 +4683,186 @@ static void trickle_ice_send_sip_info(pj_timer_heap_t *th, * to start trickling. */ void pjsua_ice_check_start_trickling(pjsua_call *call, - pj_bool_t forceful, - pjsip_event *e) + pj_bool_t forceful, + pjsip_event *e) { pjsip_inv_session *inv = call->inv; /* Make sure trickling/sending-INFO has not been started */ if (!forceful && call->trickle_ice.trickling >= PJSUA_OP_STATE_RUNNING) - return; + return; /* Make sure trickle ICE is enabled */ if (!call->trickle_ice.enabled) - return; + return; /* Make sure the dialog state is established */ if (!inv || inv->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) - return; + return; /* First, make sure remote dialog is also established. */ if (inv->state == PJSIP_INV_STATE_CONFIRMED) { - /* Set flag indicating remote dialog is established */ - call->trickle_ice.remote_dlg_est = PJ_TRUE; + /* Set flag indicating remote dialog is established */ + call->trickle_ice.remote_dlg_est = PJ_TRUE; } else if (inv->state > PJSIP_INV_STATE_CONFIRMED) { - /* Call is terminating/terminated (just trying to be safe) */ - call->trickle_ice.remote_dlg_est = PJ_FALSE; + /* Call is terminating/terminated (just trying to be safe) */ + call->trickle_ice.remote_dlg_est = PJ_FALSE; } else if (!call->trickle_ice.remote_dlg_est && e) { - /* Call is being initialized */ - pjsip_msg *msg = NULL; - pjsip_rx_data *rdata = NULL; - pjsip_tx_data *tdata = NULL; - pj_bool_t has_100rel = (inv->options & PJSIP_INV_REQUIRE_100REL); - pj_timer_entry *te = &call->trickle_ice.timer; - - if (e->type == PJSIP_EVENT_TSX_STATE && - e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) - { - rdata = e->body.tsx_state.src.rdata; - } else if (e->type == PJSIP_EVENT_TSX_STATE && - e->body.tsx_state.type == PJSIP_EVENT_TX_MSG) - { - tdata = e->body.tsx_state.src.tdata; - } else { - return; - } - - /* UAC must have received 18x at this point, so dialog must have been - * established at the remote side. - */ - if (inv->role == PJSIP_ROLE_UAC) { - /* UAC needs to send SIP INFO when receiving 18x and 100rel is not - * active. - * Note that 18x may not have SDP (so we don't know if remote - * supports trickle ICE), but we should send INFO anyway, as the - * draft allows start trickling without answer. - */ - if (!has_100rel && rdata && - rdata->msg_info.msg->type == PJSIP_RESPONSE_MSG && - rdata->msg_info.msg->line.status.code/10 == 18) - { - pjsip_rdata_sdp_info *sdp_info; - sdp_info = pjsip_rdata_get_sdp_info(rdata); - if (sdp_info->sdp) { - unsigned i; - for (i = 0; i < sdp_info->sdp->media_count; ++i) { - if (pjmedia_ice_sdp_has_trickle(sdp_info->sdp, i)) { - call->trickle_ice.remote_sup = PJ_TRUE; - break; - } - } - } else { - /* Start sending SIP INFO forcefully */ - forceful = PJ_TRUE; - } - - if (forceful || call->trickle_ice.remote_sup) { - PJ_LOG(4,(THIS_FILE, - "Call %d: ICE trickle started after UAC " - "receiving 18x (with%s SDP)", - call->index, sdp_info->sdp?"":"out")); - } - } - } - - /* But if we are the UAS, we need to wait for SIP PRACK or INFO to - * confirm dialog state at remote. And while waiting, 18x needs to be - * retransmitted. - */ - else { - - if (tdata && e->body.tsx_state.tsx == inv->invite_tsx && - call->trickle_ice.retrans18x_count == 0) - { - /* Ignite 18x retransmission */ - msg = tdata->msg; - if (msg->type == PJSIP_RESPONSE_MSG && - msg->line.status.code/10 == 18) - { - pj_time_val delay; - delay.sec = pjsip_cfg()->tsx.t1 / 1000; - delay.msec = pjsip_cfg()->tsx.t1 % 1000; - pj_assert(!pj_timer_entry_running(te)); - te->cb = &trickle_ice_retrans_18x; - pjsua_schedule_timer(te, &delay); - - PJ_LOG(4,(THIS_FILE, - "Call %d: ICE trickle start retransmitting 18x", - call->index)); - } - return; - } - - /* Check for incoming PRACK or INFO to stop 18x retransmission */ - if (!rdata) - return; - - msg = rdata->msg_info.msg; - if (has_100rel) { - /* With 100rel, has received PRACK? */ - if (msg->type != PJSIP_REQUEST_MSG || - pjsip_method_cmp(&msg->line.req.method, - pjsip_get_prack_method())) - { - return; - } - } else { - pj_str_t INFO_PKG_STR = {"Info-Package", 12}; - pjsip_generic_string_hdr *hdr; - - /* Without 100rel, has received INFO? */ - if (msg->type != PJSIP_REQUEST_MSG || - pjsip_method_cmp(&msg->line.req.method, - &pjsip_info_method)) - { - return; - } - - /* With Info-Package header containing 'trickle-ice' */ - hdr = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(msg, &INFO_PKG_STR, NULL); - if (!hdr || pj_strcmp2(&hdr->hvalue, "trickle-ice")) - return; - - /* Set the flag indicating remote supports trickle ICE */ - call->trickle_ice.remote_sup = PJ_TRUE; - } - PJ_LOG(4,(THIS_FILE, - "Call %d: ICE trickle stop retransmitting 18x after " - "receiving %s", - call->index, (has_100rel?"PRACK":"INFO"))); - } - - /* Set flag indicating remote dialog is established. - * Any 18x retransmission should be ceased automatically. - */ - call->trickle_ice.remote_dlg_est = PJ_TRUE; + /* Call is being initialized */ + pjsip_msg *msg = NULL; + pjsip_rx_data *rdata = NULL; + pjsip_tx_data *tdata = NULL; + pj_bool_t has_100rel = (inv->options & PJSIP_INV_REQUIRE_100REL); + pj_timer_entry *te = &call->trickle_ice.timer; + + if (e->type == PJSIP_EVENT_TSX_STATE && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + { + rdata = e->body.tsx_state.src.rdata; + } else if (e->type == PJSIP_EVENT_TSX_STATE && + e->body.tsx_state.type == PJSIP_EVENT_TX_MSG) + { + tdata = e->body.tsx_state.src.tdata; + } else { + return; + } + + /* UAC must have received 18x at this point, so dialog must have been + * established at the remote side. + */ + if (inv->role == PJSIP_ROLE_UAC) { + /* UAC needs to send SIP INFO when receiving 18x and 100rel is not + * active. + * Note that 18x may not have SDP (so we don't know if remote + * supports trickle ICE), but we should send INFO anyway, as the + * draft allows start trickling without answer. + */ + if (!has_100rel && rdata && + rdata->msg_info.msg->type == PJSIP_RESPONSE_MSG && + rdata->msg_info.msg->line.status.code/10 == 18) + { + pjsip_rdata_sdp_info *sdp_info; + sdp_info = pjsip_rdata_get_sdp_info(rdata); + if (sdp_info->sdp) { + unsigned i; + for (i = 0; i < sdp_info->sdp->media_count; ++i) { + if (pjmedia_ice_sdp_has_trickle(sdp_info->sdp, i)) { + call->trickle_ice.remote_sup = PJ_TRUE; + break; + } + } + } else { + /* Start sending SIP INFO forcefully */ + forceful = PJ_TRUE; + } + + if (forceful || call->trickle_ice.remote_sup) { + PJ_LOG(4,(THIS_FILE, + "Call %d: ICE trickle started after UAC " + "receiving 18x (with%s SDP)", + call->index, sdp_info->sdp?"":"out")); + } + } + } + + /* But if we are the UAS, we need to wait for SIP PRACK or INFO to + * confirm dialog state at remote. And while waiting, 18x needs to be + * retransmitted. + */ + else { + + if (tdata && e->body.tsx_state.tsx == inv->invite_tsx && + call->trickle_ice.retrans18x_count == 0) + { + /* Ignite 18x retransmission */ + msg = tdata->msg; + if (msg->type == PJSIP_RESPONSE_MSG && + msg->line.status.code/10 == 18) + { + pj_time_val delay; + delay.sec = pjsip_cfg()->tsx.t1 / 1000; + delay.msec = pjsip_cfg()->tsx.t1 % 1000; + pj_assert(!pj_timer_entry_running(te)); + te->cb = &trickle_ice_retrans_18x; + pjsua_schedule_timer(te, &delay); + + PJ_LOG(4,(THIS_FILE, + "Call %d: ICE trickle start retransmitting 18x", + call->index)); + } + return; + } + + /* Check for incoming PRACK or INFO to stop 18x retransmission */ + if (!rdata) + return; + + msg = rdata->msg_info.msg; + if (has_100rel) { + /* With 100rel, has received PRACK? */ + if (msg->type != PJSIP_REQUEST_MSG || + pjsip_method_cmp(&msg->line.req.method, + pjsip_get_prack_method())) + { + return; + } + } else { + pj_str_t INFO_PKG_STR = {"Info-Package", 12}; + pjsip_generic_string_hdr *hdr; + + /* Without 100rel, has received INFO? */ + if (msg->type != PJSIP_REQUEST_MSG || + pjsip_method_cmp(&msg->line.req.method, + &pjsip_info_method)) + { + return; + } + + /* With Info-Package header containing 'trickle-ice' */ + hdr = (pjsip_generic_string_hdr*) + pjsip_msg_find_hdr_by_name(msg, &INFO_PKG_STR, NULL); + if (!hdr || pj_strcmp2(&hdr->hvalue, "trickle-ice")) + return; + + /* Set the flag indicating remote supports trickle ICE */ + call->trickle_ice.remote_sup = PJ_TRUE; + } + PJ_LOG(4,(THIS_FILE, + "Call %d: ICE trickle stop retransmitting 18x after " + "receiving %s", + call->index, (has_100rel?"PRACK":"INFO"))); + } + + /* Set flag indicating remote dialog is established. + * Any 18x retransmission should be ceased automatically. + */ + call->trickle_ice.remote_dlg_est = PJ_TRUE; } /* Check if ICE trickling can be started */ if (!forceful && - (!call->trickle_ice.remote_dlg_est || !call->trickle_ice.remote_sup)) + (!call->trickle_ice.remote_dlg_est || !call->trickle_ice.remote_sup)) { - return; + return; } /* Let's start trickling (or sending SIP INFO) */ if (forceful || call->trickle_ice.trickling < PJSUA_OP_STATE_RUNNING) { - pj_timer_entry *te = &call->trickle_ice.timer; - pj_time_val delay = {0,0}; + pj_timer_entry *te = &call->trickle_ice.timer; + pj_time_val delay = {0,0}; - if (call->trickle_ice.trickling < PJSUA_OP_STATE_RUNNING) - call->trickle_ice.trickling = PJSUA_OP_STATE_RUNNING; + if (call->trickle_ice.trickling < PJSUA_OP_STATE_RUNNING) + call->trickle_ice.trickling = PJSUA_OP_STATE_RUNNING; - pjsua_cancel_timer(te); - te->id = forceful? 2 : 0; - te->cb = &trickle_ice_send_sip_info; - pjsua_schedule_timer(te, &delay); + pjsua_cancel_timer(te); + te->id = forceful? 2 : 0; + te->cb = &trickle_ice_send_sip_info; + pjsua_schedule_timer(te, &delay); - PJ_LOG(4,(THIS_FILE, - "Call %d: ICE trickle start trickling", - call->index)); + PJ_LOG(4,(THIS_FILE, + "Call %d: ICE trickle start trickling", + call->index)); } } @@ -4873,7 +4872,7 @@ void pjsua_ice_check_start_trickling(pjsua_call *call, * session state has changed. */ static void pjsua_call_on_state_changed(pjsip_inv_session *inv, - pjsip_event *e) + pjsip_event *e) { pjsua_call *call; unsigned num_locks = 0; @@ -4883,199 +4882,199 @@ static void pjsua_call_on_state_changed(pjsip_inv_session *inv, call = (pjsua_call*) inv->dlg->mod_data[pjsua_var.mod.id]; if (!call) { - pj_log_pop_indent(); - return; + pj_log_pop_indent(); + return; } /* Get call times */ switch (inv->state) { - case PJSIP_INV_STATE_EARLY: - case PJSIP_INV_STATE_CONNECTING: - if (call->res_time.sec == 0) - pj_gettimeofday(&call->res_time); - call->last_code = (pjsip_status_code) - e->body.tsx_state.tsx->status_code; - pj_strncpy(&call->last_text, - &e->body.tsx_state.tsx->status_text, - sizeof(call->last_text_buf_)); - break; - case PJSIP_INV_STATE_CONFIRMED: - if (call->hanging_up) { - /* This can happen if there is a crossover between - * our CANCEL request and the remote's 200 response. - * So we send BYE here. - */ - call_inv_end_session(call, 200, NULL, NULL); - return; - } - pj_gettimeofday(&call->conn_time); - - if (call->trickle_ice.enabled) { - call->trickle_ice.remote_dlg_est = PJ_TRUE; - pjsua_ice_check_start_trickling(call, PJ_FALSE, NULL); - } + case PJSIP_INV_STATE_EARLY: + case PJSIP_INV_STATE_CONNECTING: + if (call->res_time.sec == 0) + pj_gettimeofday(&call->res_time); + call->last_code = (pjsip_status_code) + e->body.tsx_state.tsx->status_code; + pj_strncpy(&call->last_text, + &e->body.tsx_state.tsx->status_text, + sizeof(call->last_text_buf_)); + break; + case PJSIP_INV_STATE_CONFIRMED: + if (call->hanging_up) { + /* This can happen if there is a crossover between + * our CANCEL request and the remote's 200 response. + * So we send BYE here. + */ + call_inv_end_session(call, 200, NULL, NULL); + return; + } + pj_gettimeofday(&call->conn_time); + + if (call->trickle_ice.enabled) { + call->trickle_ice.remote_dlg_est = PJ_TRUE; + pjsua_ice_check_start_trickling(call, PJ_FALSE, NULL); + } /* See if auto reinvite was pended as media update was done in the * EARLY state and remote does not support UPDATE. */ if (call->reinv_pending) { - call->reinv_pending = PJ_FALSE; - pjsua_call_schedule_reinvite_check(call, 0); - } - break; - case PJSIP_INV_STATE_DISCONNECTED: - pj_gettimeofday(&call->dis_time); - if (call->res_time.sec == 0) - pj_gettimeofday(&call->res_time); - if (e->type == PJSIP_EVENT_TSX_STATE && - e->body.tsx_state.tsx->status_code > call->last_code) - { - call->last_code = (pjsip_status_code) - e->body.tsx_state.tsx->status_code; - pj_strncpy(&call->last_text, - &e->body.tsx_state.tsx->status_text, - sizeof(call->last_text_buf_)); - } else { - call->last_code = PJSIP_SC_REQUEST_TERMINATED; - pj_strncpy(&call->last_text, - pjsip_get_status_text(call->last_code), - sizeof(call->last_text_buf_)); - } - - /* Stop reinvite timer, if it is active */ - if (call->reinv_timer.id) { - pjsua_cancel_timer(&call->reinv_timer); - call->reinv_timer.id = PJ_FALSE; - } - break; - default: - call->last_code = (pjsip_status_code) - e->body.tsx_state.tsx->status_code; - pj_strncpy(&call->last_text, - &e->body.tsx_state.tsx->status_text, - sizeof(call->last_text_buf_)); - break; + call->reinv_pending = PJ_FALSE; + pjsua_call_schedule_reinvite_check(call, 0); + } + break; + case PJSIP_INV_STATE_DISCONNECTED: + pj_gettimeofday(&call->dis_time); + if (call->res_time.sec == 0) + pj_gettimeofday(&call->res_time); + if (e->type == PJSIP_EVENT_TSX_STATE && + e->body.tsx_state.tsx->status_code > call->last_code) + { + call->last_code = (pjsip_status_code) + e->body.tsx_state.tsx->status_code; + pj_strncpy(&call->last_text, + &e->body.tsx_state.tsx->status_text, + sizeof(call->last_text_buf_)); + } else { + call->last_code = PJSIP_SC_REQUEST_TERMINATED; + pj_strncpy(&call->last_text, + pjsip_get_status_text(call->last_code), + sizeof(call->last_text_buf_)); + } + + /* Stop reinvite timer, if it is active */ + if (call->reinv_timer.id) { + pjsua_cancel_timer(&call->reinv_timer); + call->reinv_timer.id = PJ_FALSE; + } + break; + default: + call->last_code = (pjsip_status_code) + e->body.tsx_state.tsx->status_code; + pj_strncpy(&call->last_text, + &e->body.tsx_state.tsx->status_text, + sizeof(call->last_text_buf_)); + break; } /* If this is an outgoing INVITE that was created because of * REFER/transfer, send NOTIFY to transferer. */ if (call->xfer_sub && e->type==PJSIP_EVENT_TSX_STATE) { - int st_code = -1; - pjsip_evsub_state ev_state = PJSIP_EVSUB_STATE_ACTIVE; - - - switch (call->inv->state) { - case PJSIP_INV_STATE_NULL: - case PJSIP_INV_STATE_CALLING: - /* Do nothing */ - break; - - case PJSIP_INV_STATE_EARLY: - case PJSIP_INV_STATE_CONNECTING: - st_code = e->body.tsx_state.tsx->status_code; - if (call->inv->state == PJSIP_INV_STATE_CONNECTING) - ev_state = PJSIP_EVSUB_STATE_TERMINATED; - else - ev_state = PJSIP_EVSUB_STATE_ACTIVE; - break; - - case PJSIP_INV_STATE_CONFIRMED: + int st_code = -1; + pjsip_evsub_state ev_state = PJSIP_EVSUB_STATE_ACTIVE; + + + switch (call->inv->state) { + case PJSIP_INV_STATE_NULL: + case PJSIP_INV_STATE_CALLING: + /* Do nothing */ + break; + + case PJSIP_INV_STATE_EARLY: + case PJSIP_INV_STATE_CONNECTING: + st_code = e->body.tsx_state.tsx->status_code; + if (call->inv->state == PJSIP_INV_STATE_CONNECTING) + ev_state = PJSIP_EVSUB_STATE_TERMINATED; + else + ev_state = PJSIP_EVSUB_STATE_ACTIVE; + break; + + case PJSIP_INV_STATE_CONFIRMED: #if 0 /* We don't need this, as we've terminated the subscription in * CONNECTING state. */ - /* When state is confirmed, send the final 200/OK and terminate - * subscription. - */ - st_code = e->body.tsx_state.tsx->status_code; - ev_state = PJSIP_EVSUB_STATE_TERMINATED; + /* When state is confirmed, send the final 200/OK and terminate + * subscription. + */ + st_code = e->body.tsx_state.tsx->status_code; + ev_state = PJSIP_EVSUB_STATE_TERMINATED; #endif - break; - - case PJSIP_INV_STATE_DISCONNECTED: - st_code = e->body.tsx_state.tsx->status_code; - ev_state = PJSIP_EVSUB_STATE_TERMINATED; - break; - - case PJSIP_INV_STATE_INCOMING: - /* Nothing to do. Just to keep gcc from complaining about - * unused enums. - */ - break; - } - - if (st_code != -1) { - pjsip_tx_data *tdata; - pj_status_t status; - - status = pjsip_xfer_notify( call->xfer_sub, - ev_state, st_code, - NULL, &tdata); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create NOTIFY", status); - } else { - status = pjsip_xfer_send_request(call->xfer_sub, tdata); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send NOTIFY", status); - } - } - } + break; + + case PJSIP_INV_STATE_DISCONNECTED: + st_code = e->body.tsx_state.tsx->status_code; + ev_state = PJSIP_EVSUB_STATE_TERMINATED; + break; + + case PJSIP_INV_STATE_INCOMING: + /* Nothing to do. Just to keep gcc from complaining about + * unused enums. + */ + break; + } + + if (st_code != -1) { + pjsip_tx_data *tdata; + pj_status_t status; + + status = pjsip_xfer_notify( call->xfer_sub, + ev_state, st_code, + NULL, &tdata); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to create NOTIFY", status); + } else { + status = pjsip_xfer_send_request(call->xfer_sub, tdata); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to send NOTIFY", status); + } + } + } } /* Destroy media session when invite session is disconnected. */ if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { - PJSUA_LOCK(); + PJSUA_LOCK(); - if (!call->hanging_up) - pjsua_media_channel_deinit(call->index); - - PJSUA_UNLOCK(); + if (!call->hanging_up) + pjsua_media_channel_deinit(call->index); + + PJSUA_UNLOCK(); } /* Release locks before calling callbacks, to avoid deadlock. */ while (PJSUA_LOCK_IS_LOCKED()) { - num_locks++; - PJSUA_UNLOCK(); + num_locks++; + PJSUA_UNLOCK(); } /* Ticket #1627: Invoke on_call_tsx_state() when call is disconnected. */ if (inv->state == PJSIP_INV_STATE_DISCONNECTED && - e->type == PJSIP_EVENT_TSX_STATE && - !call->hanging_up && call->inv && - pjsua_var.ua_cfg.cb.on_call_tsx_state) + e->type == PJSIP_EVENT_TSX_STATE && + !call->hanging_up && call->inv && + pjsua_var.ua_cfg.cb.on_call_tsx_state) { - (*pjsua_var.ua_cfg.cb.on_call_tsx_state)(call->index, - e->body.tsx_state.tsx, e); + (*pjsua_var.ua_cfg.cb.on_call_tsx_state)(call->index, + e->body.tsx_state.tsx, e); } if (!call->hanging_up && pjsua_var.ua_cfg.cb.on_call_state) - (*pjsua_var.ua_cfg.cb.on_call_state)(call->index, e); + (*pjsua_var.ua_cfg.cb.on_call_state)(call->index, e); /* Re-acquire the locks. */ for (;num_locks > 0; num_locks--) - PJSUA_LOCK(); + PJSUA_LOCK(); /* call->inv may be NULL now */ /* Finally, free call when invite session is disconnected. */ if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { - PJSUA_LOCK(); + PJSUA_LOCK(); - /* Free call */ - call->inv = NULL; + /* Free call */ + call->inv = NULL; - pj_assert(pjsua_var.call_cnt > 0); - --pjsua_var.call_cnt; + pj_assert(pjsua_var.call_cnt > 0); + --pjsua_var.call_cnt; - /* Reset call */ - reset_call(call->index); + /* Reset call */ + reset_call(call->index); - pjsua_check_snd_dev_idle(); + pjsua_check_snd_dev_idle(); - PJSUA_UNLOCK(); + PJSUA_UNLOCK(); } pj_log_pop_indent(); } @@ -5085,7 +5084,7 @@ static void pjsua_call_on_state_changed(pjsip_inv_session *inv, * has forked. */ static void pjsua_call_on_forked( pjsip_inv_session *inv, - pjsip_event *e) + pjsip_event *e) { PJ_UNUSED_ARG(inv); PJ_UNUSED_ARG(e); @@ -5100,38 +5099,38 @@ static void pjsua_call_on_forked( pjsip_inv_session *inv, pjsip_dialog* on_dlg_forked(pjsip_dialog *dlg, pjsip_rx_data *res) { if (dlg->uac_has_2xx && - res->msg_info.cseq->method.id == PJSIP_INVITE_METHOD && - pjsip_rdata_get_tsx(res) == NULL && - res->msg_info.msg->line.status.code/100 == 2) + res->msg_info.cseq->method.id == PJSIP_INVITE_METHOD && + pjsip_rdata_get_tsx(res) == NULL && + res->msg_info.msg->line.status.code/100 == 2) { - pjsip_dialog *forked_dlg; - pjsip_tx_data *bye; - pj_status_t status; + pjsip_dialog *forked_dlg; + pjsip_tx_data *bye; + pj_status_t status; - /* Create forked dialog */ - status = pjsip_dlg_fork(dlg, res, &forked_dlg); - if (status != PJ_SUCCESS) - return NULL; + /* Create forked dialog */ + status = pjsip_dlg_fork(dlg, res, &forked_dlg); + if (status != PJ_SUCCESS) + return NULL; - pjsip_dlg_inc_lock(forked_dlg); + pjsip_dlg_inc_lock(forked_dlg); - /* Disconnect the call */ - status = pjsip_dlg_create_request(forked_dlg, pjsip_get_bye_method(), - -1, &bye); - if (status == PJ_SUCCESS) { - status = pjsip_dlg_send_request(forked_dlg, bye, -1, NULL); - } + /* Disconnect the call */ + status = pjsip_dlg_create_request(forked_dlg, pjsip_get_bye_method(), + -1, &bye); + if (status == PJ_SUCCESS) { + status = pjsip_dlg_send_request(forked_dlg, bye, -1, NULL); + } - pjsip_dlg_dec_lock(forked_dlg); + pjsip_dlg_dec_lock(forked_dlg); - if (status != PJ_SUCCESS) { - return NULL; - } + if (status != PJ_SUCCESS) { + return NULL; + } - return forked_dlg; + return forked_dlg; } else { - return dlg; + return dlg; } } @@ -5139,14 +5138,14 @@ pjsip_dialog* on_dlg_forked(pjsip_dialog *dlg, pjsip_rx_data *res) * Disconnect call upon error. */ static void call_disconnect( pjsip_inv_session *inv, - int code ) + int code ) { pjsip_tx_data *tdata; pj_status_t status; status = pjsip_inv_end_session(inv, code, NULL, &tdata); if (status != PJ_SUCCESS || !tdata) - return; + return; #if DISABLED_FOR_TICKET_1185 pjsua_call *call; @@ -5155,19 +5154,19 @@ static void call_disconnect( pjsip_inv_session *inv, call = (pjsua_call*) inv->dlg->mod_data[pjsua_var.mod.id]; if (call && call->tp && tdata->msg->type==PJSIP_RESPONSE_MSG && - code==PJSIP_SC_NOT_ACCEPTABLE_HERE) + code==PJSIP_SC_NOT_ACCEPTABLE_HERE) { - pjmedia_sdp_session *local_sdp; - pjmedia_transport_info ti; - - pjmedia_transport_info_init(&ti); - pjmedia_transport_get_info(call->med_tp, &ti); - status = pjmedia_endpt_create_sdp(pjsua_var.med_endpt, tdata->pool, - 1, &ti.sock_info, &local_sdp); - if (status == PJ_SUCCESS) { - pjsip_create_sdp_body(tdata->pool, local_sdp, - &tdata->msg->body); - } + pjmedia_sdp_session *local_sdp; + pjmedia_transport_info ti; + + pjmedia_transport_info_init(&ti); + pjmedia_transport_get_info(call->med_tp, &ti); + status = pjmedia_endpt_create_sdp(pjsua_var.med_endpt, tdata->pool, + 1, &ti.sock_info, &local_sdp); + if (status == PJ_SUCCESS) { + pjsip_create_sdp_body(tdata->pool, local_sdp, + &tdata->msg->body); + } } #endif @@ -5180,7 +5179,7 @@ static void call_disconnect( pjsip_inv_session *inv, * has succeeded. */ static void pjsua_call_on_media_update(pjsip_inv_session *inv, - pj_status_t status) + pj_status_t status) { pjsua_call *call; const pjmedia_sdp_session *local_sdp; @@ -5196,51 +5195,51 @@ static void pjsua_call_on_media_update(pjsip_inv_session *inv, if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "SDP negotiation has failed", status); + pjsua_perror(THIS_FILE, "SDP negotiation has failed", status); - /* Revert back provisional media. */ - pjsua_media_prov_revert(call->index); + /* Revert back provisional media. */ + pjsua_media_prov_revert(call->index); - /* Do not deinitialize media since this may be a re-INVITE or - * UPDATE (which in this case the media should not get affected - * by the failed re-INVITE/UPDATE). The media will be shutdown - * when call is disconnected anyway. - */ - /* Stop/destroy media, if any */ - /*pjsua_media_channel_deinit(call->index);*/ + /* Do not deinitialize media since this may be a re-INVITE or + * UPDATE (which in this case the media should not get affected + * by the failed re-INVITE/UPDATE). The media will be shutdown + * when call is disconnected anyway. + */ + /* Stop/destroy media, if any */ + /*pjsua_media_channel_deinit(call->index);*/ - /* Disconnect call if we're not in the middle of initializing an - * UAS dialog and if this is not a re-INVITE - */ - if ((inv->state != PJSIP_INV_STATE_NULL && - inv->state != PJSIP_INV_STATE_EARLY && - inv->state != PJSIP_INV_STATE_CONFIRMED) || - (inv->state == PJSIP_INV_STATE_EARLY && call->med_cnt == 0)) - { - call_disconnect(inv, PJSIP_SC_UNSUPPORTED_MEDIA_TYPE); - } + /* Disconnect call if we're not in the middle of initializing an + * UAS dialog and if this is not a re-INVITE + */ + if ((inv->state != PJSIP_INV_STATE_NULL && + inv->state != PJSIP_INV_STATE_EARLY && + inv->state != PJSIP_INV_STATE_CONFIRMED) || + (inv->state == PJSIP_INV_STATE_EARLY && call->med_cnt == 0)) + { + call_disconnect(inv, PJSIP_SC_UNSUPPORTED_MEDIA_TYPE); + } - goto on_return; + goto on_return; } /* Get local and remote SDP */ status = pjmedia_sdp_neg_get_active_local(call->inv->neg, &local_sdp); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Unable to retrieve currently active local SDP", - status); - //call_disconnect(inv, PJSIP_SC_UNSUPPORTED_MEDIA_TYPE); - goto on_return; + pjsua_perror(THIS_FILE, + "Unable to retrieve currently active local SDP", + status); + //call_disconnect(inv, PJSIP_SC_UNSUPPORTED_MEDIA_TYPE); + goto on_return; } status = pjmedia_sdp_neg_get_active_remote(call->inv->neg, &remote_sdp); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Unable to retrieve currently active remote SDP", - status); - //call_disconnect(inv, PJSIP_SC_UNSUPPORTED_MEDIA_TYPE); - goto on_return; + pjsua_perror(THIS_FILE, + "Unable to retrieve currently active remote SDP", + status); + //call_disconnect(inv, PJSIP_SC_UNSUPPORTED_MEDIA_TYPE); + goto on_return; } call->med_update_success = (status == PJ_SUCCESS); @@ -5249,19 +5248,19 @@ static void pjsua_call_on_media_update(pjsip_inv_session *inv, * - Check remote SDP for trickle ICE support & start sending SIP INFO. */ { - unsigned i; - for (i = 0; i < remote_sdp->media_count; ++i) { - if (pjmedia_ice_sdp_has_trickle(remote_sdp, i)) - break; - } - call->trickle_ice.remote_sup = (i < remote_sdp->media_count); - if (call->trickle_ice.remote_sup) - pjsua_ice_check_start_trickling(call, PJ_FALSE, NULL); + unsigned i; + for (i = 0; i < remote_sdp->media_count; ++i) { + if (pjmedia_ice_sdp_has_trickle(remote_sdp, i)) + break; + } + call->trickle_ice.remote_sup = (i < remote_sdp->media_count); + if (call->trickle_ice.remote_sup) + pjsua_ice_check_start_trickling(call, PJ_FALSE, NULL); } /* Update remote's NAT type */ if (pjsua_var.ua_cfg.nat_type_in_sdp) { - update_remote_nat_type(call, remote_sdp); + update_remote_nat_type(call, remote_sdp); } /* Update media channel with the new SDP */ @@ -5271,21 +5270,21 @@ static void pjsua_call_on_media_update(pjsip_inv_session *inv, * no media after SDP negotiation. */ if (status == PJMEDIA_SDPNEG_ENOMEDIA && - call->inv->state == PJSIP_INV_STATE_CONFIRMED) + call->inv->state == PJSIP_INV_STATE_CONFIRMED) { - status = PJ_SUCCESS; + status = PJ_SUCCESS; } /* Disconnect call after failure in media channel update */ if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create media session", - status); - call_disconnect(inv, PJSIP_SC_NOT_ACCEPTABLE_HERE); - /* No need to deinitialize; media will be shutdown when call - * state is disconnected anyway. - */ - /*pjsua_media_channel_deinit(call->index);*/ - goto on_return; + pjsua_perror(THIS_FILE, "Unable to create media session", + status); + call_disconnect(inv, PJSIP_SC_NOT_ACCEPTABLE_HERE); + /* No need to deinitialize; media will be shutdown when call + * state is disconnected anyway. + */ + /*pjsua_media_channel_deinit(call->index);*/ + goto on_return; } /* Ticket #476: make sure only one codec is specified in the answer. */ @@ -5293,7 +5292,7 @@ static void pjsua_call_on_media_update(pjsip_inv_session *inv, /* Call application callback, if any */ if (!call->hanging_up && pjsua_var.ua_cfg.cb.on_call_media_state) - pjsua_var.ua_cfg.cb.on_call_media_state(call->index); + pjsua_var.ua_cfg.cb.on_call_media_state(call->index); on_return: pj_log_pop_indent(); @@ -5302,9 +5301,9 @@ static void pjsua_call_on_media_update(pjsip_inv_session *inv, /* Modify SDP for call hold. */ static pj_status_t modify_sdp_of_call_hold(pjsua_call *call, - pj_pool_t *pool, - pjmedia_sdp_session *sdp, - pj_bool_t as_answerer) + pj_pool_t *pool, + pjmedia_sdp_session *sdp, + pj_bool_t as_answerer) { unsigned mi; @@ -5321,54 +5320,54 @@ static pj_status_t modify_sdp_of_call_hold(pjsua_call *call, */ for (mi=0; mimedia_count; ++mi) { - pjmedia_sdp_media *m = sdp->media[mi]; - - if (call->call_hold_type == PJSUA_CALL_HOLD_TYPE_RFC2543) { - pjmedia_sdp_conn *conn; - pjmedia_sdp_attr *attr; - - /* Get SDP media connection line */ - conn = m->conn; - if (!conn) - conn = sdp->conn; - - /* Modify address */ - conn->addr = pj_str("0.0.0.0"); - - /* Remove existing directions attributes */ - pjmedia_sdp_media_remove_all_attr(m, "sendrecv"); - pjmedia_sdp_media_remove_all_attr(m, "sendonly"); - pjmedia_sdp_media_remove_all_attr(m, "recvonly"); - pjmedia_sdp_media_remove_all_attr(m, "inactive"); - - /* Add inactive attribute */ - attr = pjmedia_sdp_attr_create(pool, "inactive", NULL); - pjmedia_sdp_media_add_attr(m, attr); - - - } else { - pjmedia_sdp_attr *attr; - - /* Remove existing directions attributes */ - pjmedia_sdp_media_remove_all_attr(m, "sendrecv"); - pjmedia_sdp_media_remove_all_attr(m, "sendonly"); - pjmedia_sdp_media_remove_all_attr(m, "recvonly"); - pjmedia_sdp_media_remove_all_attr(m, "inactive"); - - /* When as answerer, just simply set dir to "sendonly", note that - * if the offer uses "sendonly" or "inactive", the SDP negotiator - * will change our answer dir to "inactive". - */ - if (as_answerer || (call->media[mi].dir & PJMEDIA_DIR_ENCODING)) { - /* Add sendonly attribute */ - attr = pjmedia_sdp_attr_create(pool, "sendonly", NULL); - pjmedia_sdp_media_add_attr(m, attr); - } else { - /* Add inactive attribute */ - attr = pjmedia_sdp_attr_create(pool, "inactive", NULL); - pjmedia_sdp_media_add_attr(m, attr); - } - } + pjmedia_sdp_media *m = sdp->media[mi]; + + if (call->call_hold_type == PJSUA_CALL_HOLD_TYPE_RFC2543) { + pjmedia_sdp_conn *conn; + pjmedia_sdp_attr *attr; + + /* Get SDP media connection line */ + conn = m->conn; + if (!conn) + conn = sdp->conn; + + /* Modify address */ + conn->addr = pj_str("0.0.0.0"); + + /* Remove existing directions attributes */ + pjmedia_sdp_media_remove_all_attr(m, "sendrecv"); + pjmedia_sdp_media_remove_all_attr(m, "sendonly"); + pjmedia_sdp_media_remove_all_attr(m, "recvonly"); + pjmedia_sdp_media_remove_all_attr(m, "inactive"); + + /* Add inactive attribute */ + attr = pjmedia_sdp_attr_create(pool, "inactive", NULL); + pjmedia_sdp_media_add_attr(m, attr); + + + } else { + pjmedia_sdp_attr *attr; + + /* Remove existing directions attributes */ + pjmedia_sdp_media_remove_all_attr(m, "sendrecv"); + pjmedia_sdp_media_remove_all_attr(m, "sendonly"); + pjmedia_sdp_media_remove_all_attr(m, "recvonly"); + pjmedia_sdp_media_remove_all_attr(m, "inactive"); + + /* When as answerer, just simply set dir to "sendonly", note that + * if the offer uses "sendonly" or "inactive", the SDP negotiator + * will change our answer dir to "inactive". + */ + if (as_answerer || (call->media[mi].dir & PJMEDIA_DIR_ENCODING)) { + /* Add sendonly attribute */ + attr = pjmedia_sdp_attr_create(pool, "sendonly", NULL); + pjmedia_sdp_media_add_attr(m, attr); + } else { + /* Add inactive attribute */ + attr = pjmedia_sdp_attr_create(pool, "inactive", NULL); + pjmedia_sdp_media_add_attr(m, attr); + } + } } return PJ_SUCCESS; @@ -5376,7 +5375,7 @@ static pj_status_t modify_sdp_of_call_hold(pjsua_call *call, /* Create SDP for call hold. */ static pj_status_t create_sdp_of_call_hold(pjsua_call *call, - pjmedia_sdp_session **p_sdp) + pjmedia_sdp_session **p_sdp) { pj_status_t status; pj_pool_t *pool; @@ -5387,15 +5386,15 @@ static pj_status_t create_sdp_of_call_hold(pjsua_call *call, /* Create new offer */ status = pjsua_media_channel_create_sdp(call->index, pool, NULL, &sdp, - NULL); + NULL); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create local SDP", status); - return status; + pjsua_perror(THIS_FILE, "Unable to create local SDP", status); + return status; } status = modify_sdp_of_call_hold(call, pool, sdp, PJ_FALSE); if (status != PJ_SUCCESS) - return status; + return status; *p_sdp = sdp; @@ -5406,7 +5405,7 @@ static pj_status_t create_sdp_of_call_hold(pjsua_call *call, * Called when session received new offer. */ static void pjsua_call_on_rx_offer(pjsip_inv_session *inv, - struct pjsip_inv_on_rx_offer_cb_param *param) + struct pjsip_inv_on_rx_offer_cb_param *param) { pjsua_call *call; pjmedia_sdp_session *answer; @@ -5418,17 +5417,17 @@ static void pjsua_call_on_rx_offer(pjsip_inv_session *inv, call = (pjsua_call*) inv->dlg->mod_data[pjsua_var.mod.id]; if (call->hanging_up) - return; + return; /* Supply candidate answer */ PJ_LOG(4,(THIS_FILE, "Call %d: received updated media offer", - call->index)); + call->index)); pj_log_push_indent(); if (pjsua_call_media_is_changing(call)) { - PJ_LOG(1,(THIS_FILE, "Unable to process offer" ERR_MEDIA_CHANGING)); - goto on_return; + PJ_LOG(1,(THIS_FILE, "Unable to process offer" ERR_MEDIA_CHANGING)); + goto on_return; } pjsua_call_cleanup_flag(&call->opt); @@ -5440,75 +5439,75 @@ static void pjsua_call_on_rx_offer(pjsip_inv_session *inv, { pjsip_status_code code = PJSIP_SC_OK; - /* If on_call_rx_reinvite() callback is implemented, - * call it first. - */ - (*pjsua_var.ua_cfg.cb.on_call_rx_reinvite)( - call->index, offer, - (pjsip_rx_data *)param->rdata, - NULL, &async, &code, &opt); - if (async) { - pjsip_tx_data *response; - - status = pjsip_inv_initial_answer(inv, - (pjsip_rx_data *)param->rdata, - 100, NULL, NULL, &response); - if (status != PJ_SUCCESS) { - PJ_PERROR(3, (THIS_FILE, status, - "Failed to create initial answer")); - goto on_return; - } - - status = pjsip_inv_send_msg(inv, response); - if (status != PJ_SUCCESS) { - PJ_PERROR(3, (THIS_FILE, status, - "Failed to send initial answer")); - goto on_return; - } - - PJ_LOG(4,(THIS_FILE, "App will manually answer the re-INVITE " - "on call %d", call->index)); - } - if (code != PJSIP_SC_OK) { - PJ_LOG(4,(THIS_FILE, "Rejecting re-INVITE updated media offer " - "on call %d", call->index)); - goto on_return; - } - - call->opt = opt; + /* If on_call_rx_reinvite() callback is implemented, + * call it first. + */ + (*pjsua_var.ua_cfg.cb.on_call_rx_reinvite)( + call->index, offer, + (pjsip_rx_data *)param->rdata, + NULL, &async, &code, &opt); + if (async) { + pjsip_tx_data *response; + + status = pjsip_inv_initial_answer(inv, + (pjsip_rx_data *)param->rdata, + 100, NULL, NULL, &response); + if (status != PJ_SUCCESS) { + PJ_PERROR(3, (THIS_FILE, status, + "Failed to create initial answer")); + goto on_return; + } + + status = pjsip_inv_send_msg(inv, response); + if (status != PJ_SUCCESS) { + PJ_PERROR(3, (THIS_FILE, status, + "Failed to send initial answer")); + goto on_return; + } + + PJ_LOG(4,(THIS_FILE, "App will manually answer the re-INVITE " + "on call %d", call->index)); + } + if (code != PJSIP_SC_OK) { + PJ_LOG(4,(THIS_FILE, "Rejecting re-INVITE updated media offer " + "on call %d", call->index)); + goto on_return; + } + + call->opt = opt; } if (pjsua_var.ua_cfg.cb.on_call_rx_offer && !async) { - pjsip_status_code code = PJSIP_SC_OK; + pjsip_status_code code = PJSIP_SC_OK; - (*pjsua_var.ua_cfg.cb.on_call_rx_offer)(call->index, offer, NULL, - &code, &opt); + (*pjsua_var.ua_cfg.cb.on_call_rx_offer)(call->index, offer, NULL, + &code, &opt); - if (code != PJSIP_SC_OK) { - PJ_LOG(4,(THIS_FILE, "Rejecting updated media offer on call %d", - call->index)); - goto on_return; - } + if (code != PJSIP_SC_OK) { + PJ_LOG(4,(THIS_FILE, "Rejecting updated media offer on call %d", + call->index)); + goto on_return; + } - call->opt = opt; + call->opt = opt; } /* Re-init media for the new remote offer before creating SDP */ status = apply_call_setting(call, &call->opt, offer); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; status = pjsua_media_channel_create_sdp(call->index, - call->inv->pool_prov, - offer, &answer, NULL); + call->inv->pool_prov, + offer, &answer, NULL); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create local SDP", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to create local SDP", status); + goto on_return; } if (async) { - call->rx_reinv_async = async; - goto on_return; + call->rx_reinv_async = async; + goto on_return; } /* Validate media count in the generated answer */ @@ -5516,42 +5515,42 @@ static void pjsua_call_on_rx_offer(pjsip_inv_session *inv, /* Check if offer's conn address is zero */ for (i = 0; i < answer->media_count; ++i) { - pjmedia_sdp_conn *conn; - - conn = offer->media[i]->conn; - if (!conn) - conn = offer->conn; - - if (pj_strcmp2(&conn->addr, "0.0.0.0")==0 || - pj_strcmp2(&conn->addr, "0")==0) - { - pjmedia_sdp_conn *a_conn = answer->media[i]->conn; - - /* Modify answer address */ - if (a_conn) { - a_conn->addr = pj_str("0.0.0.0"); - } else if (answer->conn == NULL || - pj_strcmp2(&answer->conn->addr, "0.0.0.0") != 0) - { - a_conn = PJ_POOL_ZALLOC_T(call->inv->pool_prov, - pjmedia_sdp_conn); - a_conn->net_type = pj_str("IN"); - a_conn->addr_type = pj_str("IP4"); - a_conn->addr = pj_str("0.0.0.0"); - answer->media[i]->conn = a_conn; - } - } + pjmedia_sdp_conn *conn; + + conn = offer->media[i]->conn; + if (!conn) + conn = offer->conn; + + if (pj_strcmp2(&conn->addr, "0.0.0.0")==0 || + pj_strcmp2(&conn->addr, "0")==0) + { + pjmedia_sdp_conn *a_conn = answer->media[i]->conn; + + /* Modify answer address */ + if (a_conn) { + a_conn->addr = pj_str("0.0.0.0"); + } else if (answer->conn == NULL || + pj_strcmp2(&answer->conn->addr, "0.0.0.0") != 0) + { + a_conn = PJ_POOL_ZALLOC_T(call->inv->pool_prov, + pjmedia_sdp_conn); + a_conn->net_type = pj_str("IN"); + a_conn->addr_type = pj_str("IP4"); + a_conn->addr = pj_str("0.0.0.0"); + answer->media[i]->conn = a_conn; + } + } } /* Check if call is on-hold */ if (call->local_hold) { - modify_sdp_of_call_hold(call, call->inv->pool_prov, answer, PJ_TRUE); + modify_sdp_of_call_hold(call, call->inv->pool_prov, answer, PJ_TRUE); } status = pjsip_inv_set_sdp_answer(call->inv, answer); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to set answer", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to set answer", status); + goto on_return; } on_return: @@ -5563,8 +5562,8 @@ static void pjsua_call_on_rx_offer(pjsip_inv_session *inv, * Called when receiving re-INVITE. */ static pj_status_t pjsua_call_on_rx_reinvite(pjsip_inv_session *inv, - const pjmedia_sdp_session *offer, - pjsip_rx_data *rdata) + const pjmedia_sdp_session *offer, + pjsip_rx_data *rdata) { pjsua_call *call; pj_bool_t async; @@ -5584,7 +5583,7 @@ static pj_status_t pjsua_call_on_rx_reinvite(pjsip_inv_session *inv, * Called to generate new offer. */ static void pjsua_call_on_create_offer(pjsip_inv_session *inv, - pjmedia_sdp_session **offer) + pjmedia_sdp_session **offer) { pjsua_call *call; pj_status_t status; @@ -5594,11 +5593,11 @@ static void pjsua_call_on_create_offer(pjsip_inv_session *inv, call = (pjsua_call*) inv->dlg->mod_data[pjsua_var.mod.id]; if (call->hanging_up || pjsua_call_media_is_changing(call)) { - *offer = NULL; - PJ_LOG(1,(THIS_FILE, "Unable to create offer%s", - call->hanging_up? ", call hanging up": - ERR_MEDIA_CHANGING)); - goto on_return; + *offer = NULL; + PJ_LOG(1,(THIS_FILE, "Unable to create offer%s", + call->hanging_up? ", call hanging up": + ERR_MEDIA_CHANGING)); + goto on_return; } #if RESTART_ICE_ON_REINVITE @@ -5609,18 +5608,18 @@ static void pjsua_call_on_create_offer(pjsip_inv_session *inv, * of gathering new candidates. */ for (mi=0; mimed_cnt; ++mi) { - pjsua_call_media *call_med = &call->media[mi]; - pjmedia_transport_info tpinfo; - pjmedia_ice_transport_info *ice_info; + pjsua_call_media *call_med = &call->media[mi]; + pjmedia_transport_info tpinfo; + pjmedia_ice_transport_info *ice_info; /* Check if the media is using ICE */ pjmedia_transport_info_init(&tpinfo); - pjmedia_transport_get_info(call_med->tp, &tpinfo); - ice_info = (pjmedia_ice_transport_info*) + pjmedia_transport_get_info(call_med->tp, &tpinfo); + ice_info = (pjmedia_ice_transport_info*) pjmedia_transport_info_get_spc_info( &tpinfo, PJMEDIA_TRANSPORT_TYPE_ICE); if (!ice_info) - continue; + continue; /* Stop and re-init ICE stream transport. * According to RFC 5245 section 9.1.1.1, during ICE restart, @@ -5629,8 +5628,8 @@ static void pjsua_call_on_create_offer(pjsip_inv_session *inv, pjmedia_transport_media_stop(call_med->tp); pjmedia_transport_media_create(call_med->tp, call->inv->pool_prov, (call_med->enable_rtcp_mux? - PJMEDIA_TPMED_RTCP_MUX: 0), - NULL, mi); + PJMEDIA_TPMED_RTCP_MUX: 0), + NULL, mi); PJ_LOG(4, (THIS_FILE, "Restarting ICE for media %d", mi)); } @@ -5639,35 +5638,35 @@ static void pjsua_call_on_create_offer(pjsip_inv_session *inv, pjsua_call_cleanup_flag(&call->opt); if (pjsua_var.ua_cfg.cb.on_call_tx_offer) { - (*pjsua_var.ua_cfg.cb.on_call_tx_offer)(call->index, NULL, - &call->opt); + (*pjsua_var.ua_cfg.cb.on_call_tx_offer)(call->index, NULL, + &call->opt); } /* We may need to re-initialize media before creating SDP */ if (call->med_prov_cnt == 0 || pjsua_var.ua_cfg.cb.on_call_tx_offer) { - status = apply_call_setting(call, &call->opt, NULL); - if (status != PJ_SUCCESS) - goto on_return; + status = apply_call_setting(call, &call->opt, NULL); + if (status != PJ_SUCCESS) + goto on_return; } /* See if we've put call on hold. */ if (call->local_hold) { - PJ_LOG(4,(THIS_FILE, - "Call %d: call is on-hold locally, creating call-hold SDP ", - call->index)); - status = create_sdp_of_call_hold( call, offer ); + PJ_LOG(4,(THIS_FILE, + "Call %d: call is on-hold locally, creating call-hold SDP ", + call->index)); + status = create_sdp_of_call_hold( call, offer ); } else { - PJ_LOG(4,(THIS_FILE, "Call %d: asked to send a new offer", - call->index)); + PJ_LOG(4,(THIS_FILE, "Call %d: asked to send a new offer", + call->index)); - status = pjsua_media_channel_create_sdp(call->index, - call->inv->pool_prov, - NULL, offer, NULL); + status = pjsua_media_channel_create_sdp(call->index, + call->inv->pool_prov, + NULL, offer, NULL); } if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create local SDP", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to create local SDP", status); + goto on_return; } on_return: @@ -5692,169 +5691,169 @@ static void xfer_client_on_evsub_state( pjsip_evsub *sub, pjsip_event *event) */ if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_ACCEPTED) { - pjsip_rx_data *rdata; - pjsip_generic_string_hdr *refer_sub; - const pj_str_t REFER_SUB = { "Refer-Sub", 9 }; - pjsua_call *call; - - call = (pjsua_call*) pjsip_evsub_get_mod_data(sub, pjsua_var.mod.id); - - /* Must be receipt of response message */ - pj_assert(event->type == PJSIP_EVENT_TSX_STATE && - event->body.tsx_state.type == PJSIP_EVENT_RX_MSG); - rdata = event->body.tsx_state.src.rdata; - - /* Find Refer-Sub header */ - refer_sub = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, - &REFER_SUB, NULL); - - /* Check if subscription is suppressed */ - if (refer_sub && pj_stricmp2(&refer_sub->hvalue, "false")==0) { - /* Since no subscription is desired, assume that call has been - * transferred successfully. - */ - if (call && !call->hanging_up && - pjsua_var.ua_cfg.cb.on_call_transfer_status) - { - const pj_str_t ACCEPTED = { "Accepted", 8 }; - pj_bool_t cont = PJ_FALSE; - (*pjsua_var.ua_cfg.cb.on_call_transfer_status)(call->index, - 200, - &ACCEPTED, - PJ_TRUE, - &cont); - } - - /* Yes, subscription is suppressed. - * Terminate our subscription now. - */ - PJ_LOG(4,(THIS_FILE, "Xfer subscription suppressed, terminating " - "event subcription...")); - pjsip_evsub_terminate(sub, PJ_TRUE); - - } else { - /* Notify application about call transfer progress. - * Initially notify with 100/Accepted status. - */ - if (call && !call->hanging_up && - pjsua_var.ua_cfg.cb.on_call_transfer_status) - { - const pj_str_t ACCEPTED = { "Accepted", 8 }; - pj_bool_t cont = PJ_FALSE; - (*pjsua_var.ua_cfg.cb.on_call_transfer_status)(call->index, - 100, - &ACCEPTED, - PJ_FALSE, - &cont); - } - } + pjsip_rx_data *rdata; + pjsip_generic_string_hdr *refer_sub; + const pj_str_t REFER_SUB = { "Refer-Sub", 9 }; + pjsua_call *call; + + call = (pjsua_call*) pjsip_evsub_get_mod_data(sub, pjsua_var.mod.id); + + /* Must be receipt of response message */ + pj_assert(event->type == PJSIP_EVENT_TSX_STATE && + event->body.tsx_state.type == PJSIP_EVENT_RX_MSG); + rdata = event->body.tsx_state.src.rdata; + + /* Find Refer-Sub header */ + refer_sub = (pjsip_generic_string_hdr*) + pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, + &REFER_SUB, NULL); + + /* Check if subscription is suppressed */ + if (refer_sub && pj_stricmp2(&refer_sub->hvalue, "false")==0) { + /* Since no subscription is desired, assume that call has been + * transferred successfully. + */ + if (call && !call->hanging_up && + pjsua_var.ua_cfg.cb.on_call_transfer_status) + { + const pj_str_t ACCEPTED = { "Accepted", 8 }; + pj_bool_t cont = PJ_FALSE; + (*pjsua_var.ua_cfg.cb.on_call_transfer_status)(call->index, + 200, + &ACCEPTED, + PJ_TRUE, + &cont); + } + + /* Yes, subscription is suppressed. + * Terminate our subscription now. + */ + PJ_LOG(4,(THIS_FILE, "Xfer subscription suppressed, terminating " + "event subcription...")); + pjsip_evsub_terminate(sub, PJ_TRUE); + + } else { + /* Notify application about call transfer progress. + * Initially notify with 100/Accepted status. + */ + if (call && !call->hanging_up && + pjsua_var.ua_cfg.cb.on_call_transfer_status) + { + const pj_str_t ACCEPTED = { "Accepted", 8 }; + pj_bool_t cont = PJ_FALSE; + (*pjsua_var.ua_cfg.cb.on_call_transfer_status)(call->index, + 100, + &ACCEPTED, + PJ_FALSE, + &cont); + } + } } /* * On incoming NOTIFY or an error response, notify application about call * transfer progress. */ else if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_ACTIVE || - pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) + pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) { - pjsua_call *call; - pjsip_msg *msg; - pjsip_msg_body *body; - pjsip_status_line status_line; - pj_bool_t is_last; - pj_bool_t cont; - pj_status_t status; - - call = (pjsua_call*) pjsip_evsub_get_mod_data(sub, pjsua_var.mod.id); - - /* When subscription is terminated, clear the xfer_sub member of - * the inv_data. - */ - if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) { - pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); - PJ_LOG(4,(THIS_FILE, "Xfer client subscription terminated")); - - } - - if (!call || call->hanging_up || !event || - !pjsua_var.ua_cfg.cb.on_call_transfer_status) - { - /* Application is not interested with call progress status */ - goto on_return; - } - - if (event->type == PJSIP_EVENT_TSX_STATE && - event->body.tsx_state.type == PJSIP_EVENT_RX_MSG) - { - pjsip_rx_data *rdata; - - rdata = event->body.tsx_state.src.rdata; - msg = rdata->msg_info.msg; - - /* This better be a NOTIFY request */ - if (pjsip_method_cmp(&msg->line.req.method, - pjsip_get_notify_method()) == 0) - { - /* Check if there's body */ - body = msg->body; - if (!body) { - PJ_LOG(2, (THIS_FILE, - "Warning: received NOTIFY without message " - "body")); - goto on_return; - } - - /* Check for appropriate content */ - if (pj_stricmp2(&body->content_type.type, "message") != 0 || - pj_stricmp2(&body->content_type.subtype, "sipfrag") != 0) - { - PJ_LOG(2, (THIS_FILE, - "Warning: received NOTIFY with non " - "message/sipfrag content")); - goto on_return; - } - - /* Try to parse the content */ - status = pjsip_parse_status_line((char*)body->data, body->len, - &status_line); - if (status != PJ_SUCCESS) { - PJ_LOG(2, (THIS_FILE, - "Warning: received NOTIFY with invalid " - "message/sipfrag content")); - goto on_return; - } - } else { - status_line.code = msg->line.status.code; - status_line.reason = msg->line.status.reason; - } - } else { - status_line.code = 500; - status_line.reason = *pjsip_get_status_text(500); - } - - /* Notify application */ - is_last = (pjsip_evsub_get_state(sub)==PJSIP_EVSUB_STATE_TERMINATED); - cont = !is_last; - (*pjsua_var.ua_cfg.cb.on_call_transfer_status)(call->index, - status_line.code, - &status_line.reason, - is_last, &cont); - - if (!cont) { - pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); - } - - /* If the call transfer has completed but the subscription is - * not terminated, terminate it now. - */ - if (status_line.code/100 == 2 && !is_last) { - pjsip_tx_data *tdata; - - status = pjsip_evsub_initiate(sub, pjsip_get_subscribe_method(), - 0, &tdata); - if (status == PJ_SUCCESS) - status = pjsip_evsub_send_request(sub, tdata); - } + pjsua_call *call; + pjsip_msg *msg; + pjsip_msg_body *body; + pjsip_status_line status_line; + pj_bool_t is_last; + pj_bool_t cont; + pj_status_t status; + + call = (pjsua_call*) pjsip_evsub_get_mod_data(sub, pjsua_var.mod.id); + + /* When subscription is terminated, clear the xfer_sub member of + * the inv_data. + */ + if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) { + pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); + PJ_LOG(4,(THIS_FILE, "Xfer client subscription terminated")); + + } + + if (!call || call->hanging_up || !event || + !pjsua_var.ua_cfg.cb.on_call_transfer_status) + { + /* Application is not interested with call progress status */ + goto on_return; + } + + if (event->type == PJSIP_EVENT_TSX_STATE && + event->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + { + pjsip_rx_data *rdata; + + rdata = event->body.tsx_state.src.rdata; + msg = rdata->msg_info.msg; + + /* This better be a NOTIFY request */ + if (pjsip_method_cmp(&msg->line.req.method, + pjsip_get_notify_method()) == 0) + { + /* Check if there's body */ + body = msg->body; + if (!body) { + PJ_LOG(2, (THIS_FILE, + "Warning: received NOTIFY without message " + "body")); + goto on_return; + } + + /* Check for appropriate content */ + if (pj_stricmp2(&body->content_type.type, "message") != 0 || + pj_stricmp2(&body->content_type.subtype, "sipfrag") != 0) + { + PJ_LOG(2, (THIS_FILE, + "Warning: received NOTIFY with non " + "message/sipfrag content")); + goto on_return; + } + + /* Try to parse the content */ + status = pjsip_parse_status_line((char*)body->data, body->len, + &status_line); + if (status != PJ_SUCCESS) { + PJ_LOG(2, (THIS_FILE, + "Warning: received NOTIFY with invalid " + "message/sipfrag content")); + goto on_return; + } + } else { + status_line.code = msg->line.status.code; + status_line.reason = msg->line.status.reason; + } + } else { + status_line.code = 500; + status_line.reason = *pjsip_get_status_text(500); + } + + /* Notify application */ + is_last = (pjsip_evsub_get_state(sub)==PJSIP_EVSUB_STATE_TERMINATED); + cont = !is_last; + (*pjsua_var.ua_cfg.cb.on_call_transfer_status)(call->index, + status_line.code, + &status_line.reason, + is_last, &cont); + + if (!cont) { + pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); + } + + /* If the call transfer has completed but the subscription is + * not terminated, terminate it now. + */ + if (status_line.code/100 == 2 && !is_last) { + pjsip_tx_data *tdata; + + status = pjsip_evsub_initiate(sub, pjsip_get_subscribe_method(), + 0, &tdata); + if (status == PJ_SUCCESS) + status = pjsip_evsub_send_request(sub, tdata); + } } on_return: @@ -5877,16 +5876,16 @@ static void xfer_server_on_evsub_state( pjsip_evsub *sub, pjsip_event *event) * the inv_data. */ if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) { - pjsua_call *call; + pjsua_call *call; - call = (pjsua_call*) pjsip_evsub_get_mod_data(sub, pjsua_var.mod.id); - if (!call) - goto on_return; + call = (pjsua_call*) pjsip_evsub_get_mod_data(sub, pjsua_var.mod.id); + if (!call) + goto on_return; - pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); - call->xfer_sub = NULL; + pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); + call->xfer_sub = NULL; - PJ_LOG(4,(THIS_FILE, "Xfer server subscription terminated")); + PJ_LOG(4,(THIS_FILE, "Xfer server subscription terminated")); } on_return: @@ -5898,7 +5897,7 @@ static void xfer_server_on_evsub_state( pjsip_evsub *sub, pjsip_event *event) * Follow transfer (REFER) request. */ static void on_call_transferred( pjsip_inv_session *inv, - pjsip_rx_data *rdata ) + pjsip_rx_data *rdata ) { pj_status_t status; pjsip_tx_data *tdata; @@ -5922,157 +5921,157 @@ static void on_call_transferred( pjsip_inv_session *inv, existing_call = (pjsua_call*) inv->dlg->mod_data[pjsua_var.mod.id]; if (existing_call->hanging_up) { - pjsip_dlg_respond( inv->dlg, rdata, 487, NULL, NULL, NULL); - goto on_return; + pjsip_dlg_respond( inv->dlg, rdata, 487, NULL, NULL, NULL); + goto on_return; } /* Find the Refer-To header */ refer_to = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_to, NULL); + pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_to, NULL); if (refer_to == NULL) { - /* Invalid Request. - * No Refer-To header! - */ - PJ_LOG(4,(THIS_FILE, "Received REFER without Refer-To header!")); - pjsip_dlg_respond( inv->dlg, rdata, 400, NULL, NULL, NULL); - goto on_return; + /* Invalid Request. + * No Refer-To header! + */ + PJ_LOG(4,(THIS_FILE, "Received REFER without Refer-To header!")); + pjsip_dlg_respond( inv->dlg, rdata, 400, NULL, NULL, NULL); + goto on_return; } /* Find optional Refer-Sub header */ refer_sub = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_sub, NULL); + pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_sub, NULL); if (refer_sub) { - if (pj_strnicmp2(&refer_sub->hvalue, "true", 4)!=0) - no_refer_sub = PJ_TRUE; + if (pj_strnicmp2(&refer_sub->hvalue, "true", 4)!=0) + no_refer_sub = PJ_TRUE; } /* Find optional Referred-By header (to be copied onto outgoing INVITE * request. */ ref_by_hdr = (pjsip_hdr*) - pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_ref_by, - NULL); + pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_ref_by, + NULL); /* Notify callback */ code = PJSIP_SC_ACCEPTED; if (pjsua_var.ua_cfg.cb.on_call_transfer_request) { - (*pjsua_var.ua_cfg.cb.on_call_transfer_request)(existing_call->index, - &refer_to->hvalue, - &code); + (*pjsua_var.ua_cfg.cb.on_call_transfer_request)(existing_call->index, + &refer_to->hvalue, + &code); } pjsua_call_cleanup_flag(&existing_call->opt); call_opt = existing_call->opt; if (pjsua_var.ua_cfg.cb.on_call_transfer_request2) { - (*pjsua_var.ua_cfg.cb.on_call_transfer_request2)(existing_call->index, - &refer_to->hvalue, - &code, - &call_opt); + (*pjsua_var.ua_cfg.cb.on_call_transfer_request2)(existing_call->index, + &refer_to->hvalue, + &code, + &call_opt); } if (code < 200) - code = PJSIP_SC_ACCEPTED; + code = PJSIP_SC_ACCEPTED; if (code >= 300) { - /* Application rejects call transfer request */ - pjsip_dlg_respond( inv->dlg, rdata, code, NULL, NULL, NULL); - goto on_return; + /* Application rejects call transfer request */ + pjsip_dlg_respond( inv->dlg, rdata, code, NULL, NULL, NULL); + goto on_return; } PJ_LOG(3,(THIS_FILE, "Call to %.*s is being transferred to %.*s", - (int)inv->dlg->remote.info_str.slen, - inv->dlg->remote.info_str.ptr, - (int)refer_to->hvalue.slen, - refer_to->hvalue.ptr)); + (int)inv->dlg->remote.info_str.slen, + inv->dlg->remote.info_str.ptr, + (int)refer_to->hvalue.slen, + refer_to->hvalue.ptr)); if (no_refer_sub) { - /* - * Always answer with 2xx. - */ - pjsip_tx_data *tdata2; - const pj_str_t str_false = { "false", 5}; - pjsip_hdr *hdr; - - status = pjsip_dlg_create_response(inv->dlg, rdata, code, NULL, - &tdata2); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create 2xx response to REFER", - status); - goto on_return; - } - - /* Add Refer-Sub header */ - hdr = (pjsip_hdr*) - pjsip_generic_string_hdr_create(tdata2->pool, &str_refer_sub, - &str_false); - pjsip_msg_add_hdr(tdata2->msg, hdr); - - - /* Send answer */ - status = pjsip_dlg_send_response(inv->dlg, pjsip_rdata_get_tsx(rdata), - tdata2); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create 2xx response to REFER", - status); - goto on_return; - } - - /* Don't have subscription */ - sub = NULL; + /* + * Always answer with 2xx. + */ + pjsip_tx_data *tdata2; + const pj_str_t str_false = { "false", 5}; + pjsip_hdr *hdr; + + status = pjsip_dlg_create_response(inv->dlg, rdata, code, NULL, + &tdata2); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to create 2xx response to REFER", + status); + goto on_return; + } + + /* Add Refer-Sub header */ + hdr = (pjsip_hdr*) + pjsip_generic_string_hdr_create(tdata2->pool, &str_refer_sub, + &str_false); + pjsip_msg_add_hdr(tdata2->msg, hdr); + + + /* Send answer */ + status = pjsip_dlg_send_response(inv->dlg, pjsip_rdata_get_tsx(rdata), + tdata2); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to create 2xx response to REFER", + status); + goto on_return; + } + + /* Don't have subscription */ + sub = NULL; } else { - struct pjsip_evsub_user xfer_cb; - pjsip_hdr hdr_list; - - /* Init callback */ - pj_bzero(&xfer_cb, sizeof(xfer_cb)); - xfer_cb.on_evsub_state = &xfer_server_on_evsub_state; - - /* Init additional header list to be sent with REFER response */ - pj_list_init(&hdr_list); - - /* Create transferee event subscription */ - status = pjsip_xfer_create_uas( inv->dlg, &xfer_cb, rdata, &sub); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create xfer uas", status); - pjsip_dlg_respond( inv->dlg, rdata, 500, NULL, NULL, NULL); - goto on_return; - } - - /* If there's Refer-Sub header and the value is "true", send back - * Refer-Sub in the response with value "true" too. - */ - if (refer_sub) { - const pj_str_t str_true = { "true", 4 }; - pjsip_hdr *hdr; - - hdr = (pjsip_hdr*) - pjsip_generic_string_hdr_create(inv->dlg->pool, - &str_refer_sub, - &str_true); - pj_list_push_back(&hdr_list, hdr); - - } - - /* Accept the REFER request, send 2xx. */ - pjsip_xfer_accept(sub, rdata, code, &hdr_list); - - /* Create initial NOTIFY request */ - status = pjsip_xfer_notify( sub, PJSIP_EVSUB_STATE_ACTIVE, - 100, NULL, &tdata); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create NOTIFY to REFER", - status); - goto on_return; - } - - /* Send initial NOTIFY request */ - status = pjsip_xfer_send_request( sub, tdata); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send NOTIFY to REFER", status); - goto on_return; - } + struct pjsip_evsub_user xfer_cb; + pjsip_hdr hdr_list; + + /* Init callback */ + pj_bzero(&xfer_cb, sizeof(xfer_cb)); + xfer_cb.on_evsub_state = &xfer_server_on_evsub_state; + + /* Init additional header list to be sent with REFER response */ + pj_list_init(&hdr_list); + + /* Create transferee event subscription */ + status = pjsip_xfer_create_uas( inv->dlg, &xfer_cb, rdata, &sub); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to create xfer uas", status); + pjsip_dlg_respond( inv->dlg, rdata, 500, NULL, NULL, NULL); + goto on_return; + } + + /* If there's Refer-Sub header and the value is "true", send back + * Refer-Sub in the response with value "true" too. + */ + if (refer_sub) { + const pj_str_t str_true = { "true", 4 }; + pjsip_hdr *hdr; + + hdr = (pjsip_hdr*) + pjsip_generic_string_hdr_create(inv->dlg->pool, + &str_refer_sub, + &str_true); + pj_list_push_back(&hdr_list, hdr); + + } + + /* Accept the REFER request, send 2xx. */ + pjsip_xfer_accept(sub, rdata, code, &hdr_list); + + /* Create initial NOTIFY request */ + status = pjsip_xfer_notify( sub, PJSIP_EVSUB_STATE_ACTIVE, + 100, NULL, &tdata); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to create NOTIFY to REFER", + status); + goto on_return; + } + + /* Send initial NOTIFY request */ + status = pjsip_xfer_send_request( sub, tdata); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to send NOTIFY to REFER", status); + goto on_return; + } } /* We're cheating here. @@ -6090,9 +6089,9 @@ static void on_call_transferred( pjsip_inv_session *inv, * to the outgoing INVITE request. */ if (ref_by_hdr != NULL) { - pjsip_hdr *dup = (pjsip_hdr*) - pjsip_hdr_clone(rdata->tp_info.pool, ref_by_hdr); - pj_list_push_back(&msg_data.hdr_list, dup); + pjsip_hdr *dup = (pjsip_hdr*) + pjsip_hdr_clone(rdata->tp_info.pool, ref_by_hdr); + pj_list_push_back(&msg_data.hdr_list, dup); } /* Now make the outgoing call. @@ -6102,39 +6101,39 @@ static void on_call_transferred( pjsip_inv_session *inv, */ tmp = pj_str(uri); status = pjsua_call_make_call(existing_call->acc_id, &tmp, &call_opt, - existing_call->user_data, &msg_data, - &new_call); + existing_call->user_data, &msg_data, + &new_call); if (status != PJ_SUCCESS) { - /* Notify xferer about the error (if we have subscription) */ - if (sub) { - status = pjsip_xfer_notify(sub, PJSIP_EVSUB_STATE_TERMINATED, - 500, NULL, &tdata); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create NOTIFY to REFER", - status); - goto on_return; - } - status = pjsip_xfer_send_request(sub, tdata); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send NOTIFY to REFER", - status); - goto on_return; - } - } - goto on_return; + /* Notify xferer about the error (if we have subscription) */ + if (sub) { + status = pjsip_xfer_notify(sub, PJSIP_EVSUB_STATE_TERMINATED, + 500, NULL, &tdata); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to create NOTIFY to REFER", + status); + goto on_return; + } + status = pjsip_xfer_send_request(sub, tdata); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to send NOTIFY to REFER", + status); + goto on_return; + } + } + goto on_return; } if (sub) { - /* Put the server subscription in inv_data. - * Subsequent state changed in pjsua_inv_on_state_changed() will be - * reported back to the server subscription. - */ - pjsua_var.calls[new_call].xfer_sub = sub; + /* Put the server subscription in inv_data. + * Subsequent state changed in pjsua_inv_on_state_changed() will be + * reported back to the server subscription. + */ + pjsua_var.calls[new_call].xfer_sub = sub; - /* Put the invite_data in the subscription. */ - pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, - &pjsua_var.calls[new_call]); + /* Put the invite_data in the subscription. */ + pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, + &pjsua_var.calls[new_call]); } on_return: @@ -6150,14 +6149,14 @@ static void on_call_transferred( pjsip_inv_session *inv, * - incoming MESSAGE request. */ static void pjsua_call_on_tsx_state_changed(pjsip_inv_session *inv, - pjsip_transaction *tsx, - pjsip_event *e) + pjsip_transaction *tsx, + pjsip_event *e) { /* Incoming INFO request for media control, DTMF, trickle ICE, etc. */ - const pj_str_t STR_APPLICATION = { "application", 11}; + const pj_str_t STR_APPLICATION = { "application", 11}; const pj_str_t STR_MEDIA_CONTROL_XML = { "media_control+xml", 17 }; - const pj_str_t STR_DTMF_RELAY = { "dtmf-relay", 10 }; - const pj_str_t STR_TRICKLE_ICE_SDP = { "trickle-ice-sdpfrag", 19 }; + const pj_str_t STR_DTMF_RELAY = { "dtmf-relay", 10 }; + const pj_str_t STR_TRICKLE_ICE_SDP = { "trickle-ice-sdpfrag", 19 }; pjsua_call *call; @@ -6166,11 +6165,11 @@ static void pjsua_call_on_tsx_state_changed(pjsip_inv_session *inv, call = (pjsua_call*) inv->dlg->mod_data[pjsua_var.mod.id]; if (call == NULL) - goto on_return; + goto on_return; if (call->inv == NULL || call->hanging_up) { - /* Call has been disconnected. */ - goto on_return; + /* Call has been disconnected. */ + goto on_return; } /* https://github.com/pjsip/pjproject/issues/1452: @@ -6178,62 +6177,62 @@ static void pjsua_call_on_tsx_state_changed(pjsip_inv_session *inv, * transaction first but wait until we've retried it. */ if (tsx->role == PJSIP_ROLE_UAC && - (tsx->status_code==401 || tsx->status_code==407) && - tsx->last_tx && tsx->last_tx->auth_retry) + (tsx->status_code==401 || tsx->status_code==407) && + tsx->last_tx && tsx->last_tx->auth_retry) { - goto on_return; + goto on_return; } /* Notify application callback first */ if (pjsua_var.ua_cfg.cb.on_call_tsx_state) { - (*pjsua_var.ua_cfg.cb.on_call_tsx_state)(call->index, tsx, e); + (*pjsua_var.ua_cfg.cb.on_call_tsx_state)(call->index, tsx, e); } if (tsx->role==PJSIP_ROLE_UAS && - tsx->state==PJSIP_TSX_STATE_TRYING && - pjsip_method_cmp(&tsx->method, pjsip_get_refer_method())==0) + tsx->state==PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, pjsip_get_refer_method())==0) { - /* - * Incoming REFER request. - */ - on_call_transferred(call->inv, e->body.tsx_state.src.rdata); + /* + * Incoming REFER request. + */ + on_call_transferred(call->inv, e->body.tsx_state.src.rdata); } else if (tsx->role==PJSIP_ROLE_UAS && - tsx->state==PJSIP_TSX_STATE_TRYING && - pjsip_method_cmp(&tsx->method, &pjsip_message_method)==0) + tsx->state==PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_message_method)==0) { - /* - * Incoming MESSAGE request! - */ - pjsip_rx_data *rdata; - pjsip_accept_hdr *accept_hdr; + /* + * Incoming MESSAGE request! + */ + pjsip_rx_data *rdata; + pjsip_accept_hdr *accept_hdr; - rdata = e->body.tsx_state.src.rdata; + rdata = e->body.tsx_state.src.rdata; - /* Request MUST have message body, with Content-Type equal to - * "text/plain". - */ - if (pjsua_im_accept_pager(rdata, &accept_hdr) == PJ_FALSE) { + /* Request MUST have message body, with Content-Type equal to + * "text/plain". + */ + if (pjsua_im_accept_pager(rdata, &accept_hdr) == PJ_FALSE) { - pjsip_hdr hdr_list; + pjsip_hdr hdr_list; - pj_list_init(&hdr_list); - pj_list_push_back(&hdr_list, accept_hdr); + pj_list_init(&hdr_list); + pj_list_push_back(&hdr_list, accept_hdr); - pjsip_dlg_respond( inv->dlg, rdata, PJSIP_SC_NOT_ACCEPTABLE_HERE, - NULL, &hdr_list, NULL ); - goto on_return; - } + pjsip_dlg_respond( inv->dlg, rdata, PJSIP_SC_NOT_ACCEPTABLE_HERE, + NULL, &hdr_list, NULL ); + goto on_return; + } - /* Respond with 200 first, so that remote doesn't retransmit in case - * the UI takes too long to process the message. - */ - pjsip_dlg_respond( inv->dlg, rdata, 200, NULL, NULL, NULL); + /* Respond with 200 first, so that remote doesn't retransmit in case + * the UI takes too long to process the message. + */ + pjsip_dlg_respond( inv->dlg, rdata, 200, NULL, NULL, NULL); - /* Process MESSAGE request */ - pjsua_im_process_pager(call->index, &inv->dlg->remote.info_str, - &inv->dlg->local.info_str, rdata); + /* Process MESSAGE request */ + pjsua_im_process_pager(call->index, &inv->dlg->remote.info_str, + &inv->dlg->local.info_str, rdata); } else if (e->type == PJSIP_EVENT_TSX_STATE && @@ -6290,7 +6289,7 @@ static void pjsua_call_on_tsx_state_changed(pjsip_inv_session *inv, } else if (tsx->role == PJSIP_ROLE_UAC && pjsip_method_cmp(&tsx->method, pjsip_get_invite_method())==0 && tsx->state >= PJSIP_TSX_STATE_COMPLETED && - e->body.tsx_state.prev_state < PJSIP_TSX_STATE_COMPLETED && + e->body.tsx_state.prev_state < PJSIP_TSX_STATE_COMPLETED && (!PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 300) && tsx->status_code!=401 && tsx->status_code!=407 && tsx->status_code!=422)) @@ -6301,23 +6300,23 @@ static void pjsua_call_on_tsx_state_changed(pjsip_inv_session *inv, */ if (call->hanging_up) { PJ_LOG(3,(THIS_FILE, "Unsuccessful in cancelling the original " - "INVITE for call %d due to %d response, sending BYE " - "instead", call->index, tsx->status_code)); - call_disconnect(call->inv, PJSIP_SC_OK); + "INVITE for call %d due to %d response, sending BYE " + "instead", call->index, tsx->status_code)); + call_disconnect(call->inv, PJSIP_SC_OK); } } else { /* Monitor the status of call hold/unhold request */ if (tsx->last_tx == (pjsip_tx_data*)call->hold_msg) { - /* Outgoing call hold failed */ - call->local_hold = PJ_FALSE; - PJ_LOG(3,(THIS_FILE, "Error putting call %d on hold " - "(reason=%d)", call->index, tsx->status_code)); + /* Outgoing call hold failed */ + call->local_hold = PJ_FALSE; + PJ_LOG(3,(THIS_FILE, "Error putting call %d on hold " + "(reason=%d)", call->index, tsx->status_code)); } else if (call->opt.flag & PJSUA_CALL_UNHOLD) { - /* Call unhold failed */ - call->local_hold = PJ_TRUE; - PJ_LOG(3,(THIS_FILE, "Error releasing hold on call %d " - "(reason=%d)", call->index, tsx->status_code)); - } + /* Call unhold failed */ + call->local_hold = PJ_TRUE; + PJ_LOG(3,(THIS_FILE, "Error releasing hold on call %d " + "(reason=%d)", call->index, tsx->status_code)); + } } if (tsx->last_tx == (pjsip_tx_data*)call->hold_msg) { @@ -6330,12 +6329,12 @@ static void pjsua_call_on_tsx_state_changed(pjsip_inv_session *inv, /* Either we get non-2xx or media update failed, * revert back provisional media. */ - pjsua_media_prov_revert(call->index); + pjsua_media_prov_revert(call->index); } } else if (tsx->role == PJSIP_ROLE_UAC && pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0 && tsx->state >= PJSIP_TSX_STATE_COMPLETED && - e->body.tsx_state.prev_state < PJSIP_TSX_STATE_COMPLETED && + e->body.tsx_state.prev_state < PJSIP_TSX_STATE_COMPLETED && (!PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 300) && tsx->status_code!=401 && tsx->status_code!=407 && tsx->status_code!=422)) @@ -6346,118 +6345,118 @@ static void pjsua_call_on_tsx_state_changed(pjsip_inv_session *inv, /* Either we get non-2xx or media update failed, * revert back provisional media. */ - pjsua_media_prov_revert(call->index); + pjsua_media_prov_revert(call->index); } } else if (tsx->role==PJSIP_ROLE_UAS && - tsx->state==PJSIP_TSX_STATE_TRYING && - pjsip_method_cmp(&tsx->method, &pjsip_info_method)==0) + tsx->state==PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_info_method)==0) { - pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; - pjsip_msg_body *body = rdata->msg_info.msg->body; - - /* Check Media Control content in the INFO message */ - if (body && body->len && - pj_stricmp(&body->content_type.type, &STR_APPLICATION)==0 && - pj_stricmp(&body->content_type.subtype, &STR_MEDIA_CONTROL_XML)==0) - { - pjsip_tx_data *tdata; - pj_str_t control_st; - pj_status_t status; - - /* Apply and answer the INFO request */ - pj_strset(&control_st, (char*)body->data, body->len); - status = pjsua_media_apply_xml_control(call->index, &control_st); - if (status == PJ_SUCCESS) { - status = pjsip_endpt_create_response(tsx->endpt, rdata, - 200, NULL, &tdata); - if (status == PJ_SUCCESS) - status = pjsip_tsx_send_msg(tsx, tdata); - } else { - status = pjsip_endpt_create_response(tsx->endpt, rdata, - 400, NULL, &tdata); - if (status == PJ_SUCCESS) - status = pjsip_tsx_send_msg(tsx, tdata); - } - } - - /* Check DTMF content in the INFO message */ - else if (body && body->len && - pj_stricmp(&body->content_type.type, &STR_APPLICATION)==0 && - pj_stricmp(&body->content_type.subtype, &STR_DTMF_RELAY)==0) - { - pjsip_tx_data *tdata; - pj_status_t status; - pj_bool_t is_handled = PJ_FALSE; - - if (pjsua_var.ua_cfg.cb.on_dtmf_digit2 || + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + pjsip_msg_body *body = rdata->msg_info.msg->body; + + /* Check Media Control content in the INFO message */ + if (body && body->len && + pj_stricmp(&body->content_type.type, &STR_APPLICATION)==0 && + pj_stricmp(&body->content_type.subtype, &STR_MEDIA_CONTROL_XML)==0) + { + pjsip_tx_data *tdata; + pj_str_t control_st; + pj_status_t status; + + /* Apply and answer the INFO request */ + pj_strset(&control_st, (char*)body->data, body->len); + status = pjsua_media_apply_xml_control(call->index, &control_st); + if (status == PJ_SUCCESS) { + status = pjsip_endpt_create_response(tsx->endpt, rdata, + 200, NULL, &tdata); + if (status == PJ_SUCCESS) + status = pjsip_tsx_send_msg(tsx, tdata); + } else { + status = pjsip_endpt_create_response(tsx->endpt, rdata, + 400, NULL, &tdata); + if (status == PJ_SUCCESS) + status = pjsip_tsx_send_msg(tsx, tdata); + } + } + + /* Check DTMF content in the INFO message */ + else if (body && body->len && + pj_stricmp(&body->content_type.type, &STR_APPLICATION)==0 && + pj_stricmp(&body->content_type.subtype, &STR_DTMF_RELAY)==0) + { + pjsip_tx_data *tdata; + pj_status_t status; + pj_bool_t is_handled = PJ_FALSE; + + if (pjsua_var.ua_cfg.cb.on_dtmf_digit2 || pjsua_var.ua_cfg.cb.on_dtmf_event) { - pjsua_dtmf_info info = {0}; - pj_str_t delim, token, input; - pj_ssize_t found_idx; - - delim = pj_str("\r\n"); - input = pj_str(rdata->msg_info.msg->body->data); - found_idx = pj_strtok(&input, &delim, &token, 0); - if (found_idx != input.slen) { - /* Get signal/digit */ - const pj_str_t STR_SIGNAL = { "Signal", 6 }; - const pj_str_t STR_DURATION = { "Duration", 8 }; - char *val; - pj_ssize_t count_equal_sign; - - val = pj_strstr(&input, &STR_SIGNAL); - if (val) { - char* p = val + STR_SIGNAL.slen; - count_equal_sign = 0; - while ((p - input.ptr < input.slen) && (*p == ' ' || *p == '=')) { - if(*p == '=') - count_equal_sign++; - ++p; - } - - if (count_equal_sign == 1 && (p - input.ptr < input.slen)) { - info.digit = *p; - is_handled = PJ_TRUE; - } else { - PJ_LOG(2, (THIS_FILE, "Invalid dtmf-relay format")); - } - - /* Get duration */ - input.ptr += token.slen + 2; - input.slen -= (token.slen + 2); - - val = pj_strstr(&input, &STR_DURATION); - if (val && is_handled) { - pj_str_t val_str; - char* ptr = val + STR_DURATION.slen; - count_equal_sign = 0; - while ((ptr - input.ptr < input.slen) && + pjsua_dtmf_info info = {0}; + pj_str_t delim, token, input; + pj_ssize_t found_idx; + + delim = pj_str("\r\n"); + input = pj_str(rdata->msg_info.msg->body->data); + found_idx = pj_strtok(&input, &delim, &token, 0); + if (found_idx != input.slen) { + /* Get signal/digit */ + const pj_str_t STR_SIGNAL = { "Signal", 6 }; + const pj_str_t STR_DURATION = { "Duration", 8 }; + char *val; + pj_ssize_t count_equal_sign; + + val = pj_strstr(&input, &STR_SIGNAL); + if (val) { + char* p = val + STR_SIGNAL.slen; + count_equal_sign = 0; + while ((p - input.ptr < input.slen) && (*p == ' ' || *p == '=')) { + if(*p == '=') + count_equal_sign++; + ++p; + } + + if (count_equal_sign == 1 && (p - input.ptr < input.slen)) { + info.digit = *p; + is_handled = PJ_TRUE; + } else { + PJ_LOG(2, (THIS_FILE, "Invalid dtmf-relay format")); + } + + /* Get duration */ + input.ptr += token.slen + 2; + input.slen -= (token.slen + 2); + + val = pj_strstr(&input, &STR_DURATION); + if (val && is_handled) { + pj_str_t val_str; + char* ptr = val + STR_DURATION.slen; + count_equal_sign = 0; + while ((ptr - input.ptr < input.slen) && (*ptr == ' ' || *ptr == '=')) { - if (*ptr == '=') - count_equal_sign++; - ++ptr; - } + if (*ptr == '=') + count_equal_sign++; + ++ptr; + } - if ((count_equal_sign == 1) && + if ((count_equal_sign == 1) && (ptr - input.ptr < input.slen)) { - val_str.ptr = ptr; - val_str.slen = input.slen - (ptr - input.ptr); - info.duration = pj_strtoul(&val_str); - } else { + val_str.ptr = ptr; + val_str.slen = input.slen - (ptr - input.ptr); + info.duration = pj_strtoul(&val_str); + } else { info.duration = PJSUA_UNKNOWN_DTMF_DURATION; - is_handled = PJ_FALSE; - PJ_LOG(2, (THIS_FILE, + is_handled = PJ_FALSE; + PJ_LOG(2, (THIS_FILE, "Invalid dtmf-relay format")); - } - } + } + } - if (is_handled) { - info.method = PJSUA_DTMF_METHOD_SIP_INFO; + if (is_handled) { + info.method = PJSUA_DTMF_METHOD_SIP_INFO; if (pjsua_var.ua_cfg.cb.on_dtmf_event) { - pjsua_dtmf_event evt; + pjsua_dtmf_event evt; pj_timestamp begin_of_time, timestamp; /* Use the current instant as the events start * time. @@ -6476,118 +6475,118 @@ static void pjsua_call_on_tsx_state_changed(pjsip_inv_session *inv, (*pjsua_var.ua_cfg.cb.on_dtmf_event)(call->index, &evt); } else { - (*pjsua_var.ua_cfg.cb.on_dtmf_digit2)(call->index, - &info); + (*pjsua_var.ua_cfg.cb.on_dtmf_digit2)(call->index, + &info); } - status = pjsip_endpt_create_response(tsx->endpt, rdata, - 200, NULL, &tdata); - if (status == PJ_SUCCESS) - status = pjsip_tsx_send_msg(tsx, tdata); - } - } - } - } - - if (!is_handled) { - status = pjsip_endpt_create_response(tsx->endpt, rdata, - 400, NULL, &tdata); - if (status == PJ_SUCCESS) - status = pjsip_tsx_send_msg(tsx, tdata); - } - } - - /* Check Trickle ICE content in the INFO message */ - else if (body && body->len && - pj_stricmp(&body->content_type.type, &STR_APPLICATION)==0 && - pj_stricmp(&body->content_type.subtype, - &STR_TRICKLE_ICE_SDP)==0) - { - pjsip_tx_data *tdata; - pj_status_t status; - - /* Trickle ICE tasks: - * - UAS receiving INFO, cease 18x retrans & start trickling - */ - if (call->trickle_ice.enabled) { - pjsua_ice_check_start_trickling(call, PJ_FALSE, e); - - /* Process the SIP INFO content */ - trickle_ice_recv_sip_info(call, rdata); - - /* Send 200 response, regardless */ - status = pjsip_endpt_create_response(tsx->endpt, rdata, - 200, NULL, &tdata); - } else { - /* Trickle ICE not enabled, send 400 response */ - status = pjsip_endpt_create_response(tsx->endpt, rdata, - 400, NULL, &tdata); - } - if (status == PJ_SUCCESS) - status = pjsip_tsx_send_msg(tsx, tdata); - } + status = pjsip_endpt_create_response(tsx->endpt, rdata, + 200, NULL, &tdata); + if (status == PJ_SUCCESS) + status = pjsip_tsx_send_msg(tsx, tdata); + } + } + } + } + + if (!is_handled) { + status = pjsip_endpt_create_response(tsx->endpt, rdata, + 400, NULL, &tdata); + if (status == PJ_SUCCESS) + status = pjsip_tsx_send_msg(tsx, tdata); + } + } + + /* Check Trickle ICE content in the INFO message */ + else if (body && body->len && + pj_stricmp(&body->content_type.type, &STR_APPLICATION)==0 && + pj_stricmp(&body->content_type.subtype, + &STR_TRICKLE_ICE_SDP)==0) + { + pjsip_tx_data *tdata; + pj_status_t status; + + /* Trickle ICE tasks: + * - UAS receiving INFO, cease 18x retrans & start trickling + */ + if (call->trickle_ice.enabled) { + pjsua_ice_check_start_trickling(call, PJ_FALSE, e); + + /* Process the SIP INFO content */ + trickle_ice_recv_sip_info(call, rdata); + + /* Send 200 response, regardless */ + status = pjsip_endpt_create_response(tsx->endpt, rdata, + 200, NULL, &tdata); + } else { + /* Trickle ICE not enabled, send 400 response */ + status = pjsip_endpt_create_response(tsx->endpt, rdata, + 400, NULL, &tdata); + } + if (status == PJ_SUCCESS) + status = pjsip_tsx_send_msg(tsx, tdata); + } } else if (tsx->role == PJSIP_ROLE_UAC && - pjsip_method_cmp(&tsx->method, &pjsip_info_method)==0 && - (tsx->state == PJSIP_TSX_STATE_COMPLETED || - (tsx->state == PJSIP_TSX_STATE_TERMINATED && - e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED))) + pjsip_method_cmp(&tsx->method, &pjsip_info_method)==0 && + (tsx->state == PJSIP_TSX_STATE_COMPLETED || + (tsx->state == PJSIP_TSX_STATE_TERMINATED && + e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED))) { - pjsip_msg_body *body = NULL; - - if (e->body.tsx_state.type == PJSIP_EVENT_TX_MSG) - body = e->body.tsx_state.src.tdata->msg->body; - else - body = e->body.tsx_state.tsx->last_tx->msg->body; - - /* Check DTMF content in the INFO message */ - if (body && body->len && - pj_stricmp(&body->content_type.type, &STR_APPLICATION)==0 && - pj_stricmp(&body->content_type.subtype, &STR_DTMF_RELAY)==0) - { - /* Status of outgoing INFO request */ - if (tsx->status_code >= 200 && tsx->status_code < 300) { - PJ_LOG(4,(THIS_FILE, - "Call %d: DTMF sent successfully with INFO", - call->index)); - } else if (tsx->status_code >= 300) { - PJ_LOG(4,(THIS_FILE, - "Call %d: Failed to send DTMF with INFO: %d/%.*s", - call->index, - tsx->status_code, - (int)tsx->status_text.slen, - tsx->status_text.ptr)); - } - } - - /* Check Trickle ICE content in the INFO message */ - else if (body && body->len && - pj_stricmp(&body->content_type.type, &STR_APPLICATION)==0 && - pj_stricmp(&body->content_type.subtype, - &STR_TRICKLE_ICE_SDP)==0) - { - /* Reset pending SIP INFO for Trickle ICE */ - call->trickle_ice.pending_info = PJ_FALSE; - } + pjsip_msg_body *body = NULL; + + if (e->body.tsx_state.type == PJSIP_EVENT_TX_MSG) + body = e->body.tsx_state.src.tdata->msg->body; + else + body = e->body.tsx_state.tsx->last_tx->msg->body; + + /* Check DTMF content in the INFO message */ + if (body && body->len && + pj_stricmp(&body->content_type.type, &STR_APPLICATION)==0 && + pj_stricmp(&body->content_type.subtype, &STR_DTMF_RELAY)==0) + { + /* Status of outgoing INFO request */ + if (tsx->status_code >= 200 && tsx->status_code < 300) { + PJ_LOG(4,(THIS_FILE, + "Call %d: DTMF sent successfully with INFO", + call->index)); + } else if (tsx->status_code >= 300) { + PJ_LOG(4,(THIS_FILE, + "Call %d: Failed to send DTMF with INFO: %d/%.*s", + call->index, + tsx->status_code, + (int)tsx->status_text.slen, + tsx->status_text.ptr)); + } + } + + /* Check Trickle ICE content in the INFO message */ + else if (body && body->len && + pj_stricmp(&body->content_type.type, &STR_APPLICATION)==0 && + pj_stricmp(&body->content_type.subtype, + &STR_TRICKLE_ICE_SDP)==0) + { + /* Reset pending SIP INFO for Trickle ICE */ + call->trickle_ice.pending_info = PJ_FALSE; + } } else if (inv->state < PJSIP_INV_STATE_CONFIRMED && - pjsip_method_cmp(&tsx->method, pjsip_get_invite_method())==0 && - tsx->state == PJSIP_TSX_STATE_PROCEEDING && - tsx->status_code/10 == 18) + pjsip_method_cmp(&tsx->method, pjsip_get_invite_method())==0 && + tsx->state == PJSIP_TSX_STATE_PROCEEDING && + tsx->status_code/10 == 18) { - /* Trickle ICE tasks: - * - UAS sending 18x, start 18x retrans - * - UAC receiving 18x, forcefully send SIP INFO & start trickling - */ - pj_bool_t force = call->trickle_ice.tricklingtrickle_ice.tricklingrole == PJSIP_ROLE_UAS && - pjsip_method_cmp(&tsx->method, pjsip_get_prack_method())==0 && - tsx->state==PJSIP_TSX_STATE_TRYING) + pjsip_method_cmp(&tsx->method, pjsip_get_prack_method())==0 && + tsx->state==PJSIP_TSX_STATE_TRYING) { - /* Trickle ICE tasks: - * - UAS receiving PRACK, start trickling - */ - pjsua_ice_check_start_trickling(call, PJ_FALSE, e); + /* Trickle ICE tasks: + * - UAS receiving PRACK, start trickling + */ + pjsua_ice_check_start_trickling(call, PJ_FALSE, e); } on_return: @@ -6597,8 +6596,8 @@ static void pjsua_call_on_tsx_state_changed(pjsip_inv_session *inv, /* Redirection handler */ static pjsip_redirect_op pjsua_call_on_redirected(pjsip_inv_session *inv, - const pjsip_uri *target, - const pjsip_event *e) + const pjsip_uri *target, + const pjsip_event *e) { pjsua_call *call = (pjsua_call*) inv->dlg->mod_data[pjsua_var.mod.id]; pjsip_redirect_op op; @@ -6606,16 +6605,16 @@ static pjsip_redirect_op pjsua_call_on_redirected(pjsip_inv_session *inv, pj_log_push_indent(); if (!call->hanging_up && pjsua_var.ua_cfg.cb.on_call_redirected) { - op = (*pjsua_var.ua_cfg.cb.on_call_redirected)(call->index, - target, e); + op = (*pjsua_var.ua_cfg.cb.on_call_redirected)(call->index, + target, e); } else { - if (!call->hanging_up) { - PJ_LOG(4,(THIS_FILE, "Unhandled redirection for call %d " - "(callback not implemented by application). " - "Disconnecting call.", - call->index)); - } - op = PJSIP_REDIRECT_STOP; + if (!call->hanging_up) { + PJ_LOG(4,(THIS_FILE, "Unhandled redirection for call %d " + "(callback not implemented by application). " + "Disconnecting call.", + call->index)); + } + op = PJSIP_REDIRECT_STOP; } pj_log_pop_indent(); diff --git a/pjsip/src/pjsua-lib/pjsua_core.c b/pjsip/src/pjsua-lib/pjsua_core.c index 193b9053ea..5425bd489f 100644 --- a/pjsip/src/pjsua-lib/pjsua_core.c +++ b/pjsip/src/pjsua-lib/pjsua_core.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -23,7 +22,7 @@ #define THIS_FILE "pjsua_core.c" -#define DEFAULT_RTP_PORT 4000 +#define DEFAULT_RTP_PORT 4000 /* Internal prototypes */ @@ -42,7 +41,7 @@ PJ_DEF(struct pjsua_data*) pjsua_get_var(void) /* Display error */ PJ_DEF(void) pjsua_perror( const char *sender, const char *title, - pj_status_t status) + pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; @@ -58,10 +57,10 @@ static void init_data() pj_bzero(&pjsua_var, sizeof(pjsua_var)); for (i=0; ilevel = 5; cfg->console_level = 4; cfg->decor = PJ_LOG_HAS_SENDER | PJ_LOG_HAS_TIME | - PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_NEWLINE | - PJ_LOG_HAS_SPACE | PJ_LOG_HAS_THREAD_SWC | - PJ_LOG_HAS_INDENT; + PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_NEWLINE | + PJ_LOG_HAS_SPACE | PJ_LOG_HAS_THREAD_SWC | + PJ_LOG_HAS_INDENT; #if (defined(PJ_WIN32) && PJ_WIN32 != 0) || (defined(PJ_WIN64) && PJ_WIN64 != 0) cfg->decor |= PJ_LOG_HAS_COLOR; #endif } PJ_DEF(void) pjsua_logging_config_dup(pj_pool_t *pool, - pjsua_logging_config *dst, - const pjsua_logging_config *src) + pjsua_logging_config *dst, + const pjsua_logging_config *src) { pj_memcpy(dst, src, sizeof(*src)); pj_strdup_with_null(pool, &dst->log_filename, &src->log_filename); @@ -120,20 +119,20 @@ PJ_DEF(void) pjsua_config_default(pjsua_config *cfg) } PJ_DEF(void) pjsua_config_dup(pj_pool_t *pool, - pjsua_config *dst, - const pjsua_config *src) + pjsua_config *dst, + const pjsua_config *src) { unsigned i; pj_memcpy(dst, src, sizeof(*src)); for (i=0; ioutbound_proxy_cnt; ++i) { - pj_strdup_with_null(pool, &dst->outbound_proxy[i], - &src->outbound_proxy[i]); + pj_strdup_with_null(pool, &dst->outbound_proxy[i], + &src->outbound_proxy[i]); } for (i=0; icred_count; ++i) { - pjsip_cred_dup(pool, &dst->cred_info[i], &src->cred_info[i]); + pjsip_cred_dup(pool, &dst->cred_info[i], &src->cred_info[i]); } pj_strdup_with_null(pool, &dst->user_agent, &src->user_agent); @@ -141,7 +140,7 @@ PJ_DEF(void) pjsua_config_dup(pj_pool_t *pool, pj_strdup_with_null(pool, &dst->stun_host, &src->stun_host); for (i=0; istun_srv_cnt; ++i) { - pj_strdup_with_null(pool, &dst->stun_srv[i], &src->stun_srv[i]); + pj_strdup_with_null(pool, &dst->stun_srv[i], &src->stun_srv[i]); } pjsua_srtp_opt_dup(pool, &dst->srtp_opt, &src->srtp_opt, PJ_FALSE); @@ -172,8 +171,8 @@ PJ_DEF(pjsua_msg_data*) pjsua_msg_data_clone(pj_pool_t *pool, pj_list_init(&msg_data->hdr_list); hdr = rhs->hdr_list.next; while (hdr != &rhs->hdr_list) { - pj_list_push_back(&msg_data->hdr_list, pjsip_hdr_clone(pool, hdr)); - hdr = hdr->next; + pj_list_push_back(&msg_data->hdr_list, pjsip_hdr_clone(pool, hdr)); + hdr = hdr->next; } pj_strdup(pool, &msg_data->content_type, &rhs->content_type); @@ -185,9 +184,9 @@ PJ_DEF(pjsua_msg_data*) pjsua_msg_data_clone(pj_pool_t *pool, pj_list_init(&msg_data->multipart_parts); mpart = rhs->multipart_parts.next; while (mpart != &rhs->multipart_parts) { - pj_list_push_back(&msg_data->multipart_parts, + pj_list_push_back(&msg_data->multipart_parts, pjsip_multipart_clone_part(pool, mpart)); - mpart = mpart->next; + mpart = mpart->next; } return msg_data; @@ -200,8 +199,8 @@ PJ_DEF(void) pjsua_transport_config_default(pjsua_transport_config *cfg) } PJ_DEF(void) pjsua_transport_config_dup(pj_pool_t *pool, - pjsua_transport_config *dst, - const pjsua_transport_config *src) + pjsua_transport_config *dst, + const pjsua_transport_config *src) { pj_memcpy(dst, src, sizeof(*src)); pj_strdup(pool, &dst->public_addr, &src->public_addr); @@ -236,22 +235,22 @@ PJ_DEF(void) pjsua_turn_config_from_media_config(pj_pool_t *pool, dst->enable_turn = src->enable_turn; dst->turn_conn_type = src->turn_conn_type; if (pool == NULL) { - dst->turn_server = src->turn_server; - dst->turn_auth_cred = src->turn_auth_cred; + dst->turn_server = src->turn_server; + dst->turn_auth_cred = src->turn_auth_cred; #if PJ_HAS_SSL_SOCK - pj_memcpy(&dst->turn_tls_setting, &src->turn_tls_setting, - sizeof(src->turn_tls_setting)); + pj_memcpy(&dst->turn_tls_setting, &src->turn_tls_setting, + sizeof(src->turn_tls_setting)); #endif } else { - if (pj_stricmp(&dst->turn_server, &src->turn_server)) - pj_strdup(pool, &dst->turn_server, &src->turn_server); - pj_stun_auth_cred_dup(pool, &dst->turn_auth_cred, - &src->turn_auth_cred); + if (pj_stricmp(&dst->turn_server, &src->turn_server)) + pj_strdup(pool, &dst->turn_server, &src->turn_server); + pj_stun_auth_cred_dup(pool, &dst->turn_auth_cred, + &src->turn_auth_cred); #if PJ_HAS_SSL_SOCK - pj_turn_sock_tls_cfg_dup(pool, &dst->turn_tls_setting, - &src->turn_tls_setting); + pj_turn_sock_tls_cfg_dup(pool, &dst->turn_tls_setting, + &src->turn_tls_setting); #endif } } @@ -262,13 +261,13 @@ PJ_DEF(void) pjsua_turn_config_dup(pj_pool_t *pool, { pj_memcpy(dst, src, sizeof(*src)); if (pool) { - pj_strdup(pool, &dst->turn_server, &src->turn_server); - pj_stun_auth_cred_dup(pool, &dst->turn_auth_cred, - &src->turn_auth_cred); + pj_strdup(pool, &dst->turn_server, &src->turn_server); + pj_stun_auth_cred_dup(pool, &dst->turn_auth_cred, + &src->turn_auth_cred); #if PJ_HAS_SSL_SOCK - pj_turn_sock_tls_cfg_dup(pool, &dst->turn_tls_setting, - &src->turn_tls_setting); + pj_turn_sock_tls_cfg_dup(pool, &dst->turn_tls_setting, + &src->turn_tls_setting); #endif } } @@ -290,30 +289,30 @@ PJ_DEF(void) pjsua_srtp_opt_dup( pj_pool_t *pool, pjsua_srtp_opt *dst, pj_memcpy(dst, src, sizeof(*src)); if (pool) { - unsigned i; - - for (i = 0; i < src->crypto_count; i++) { - if (!check_str || - pj_stricmp(&backup_dst.crypto[i].key, &src->crypto[i].key)) - { - pj_strdup(pool, &dst->crypto[i].key, &src->crypto[i].key); - } else { - /* If strings are identical, use the old string to - * avoid wasting memory. - */ - dst->crypto[i].key = backup_dst.crypto[i].key; - } - if (!check_str || - pj_stricmp(&backup_dst.crypto[i].name, &src->crypto[i].name)) - { - pj_strdup(pool, &dst->crypto[i].name, &src->crypto[i].name); - } else { - /* If strings are identical, use the old string to - * avoid wasting memory. - */ - dst->crypto[i].name = backup_dst.crypto[i].name; - } - } + unsigned i; + + for (i = 0; i < src->crypto_count; i++) { + if (!check_str || + pj_stricmp(&backup_dst.crypto[i].key, &src->crypto[i].key)) + { + pj_strdup(pool, &dst->crypto[i].key, &src->crypto[i].key); + } else { + /* If strings are identical, use the old string to + * avoid wasting memory. + */ + dst->crypto[i].key = backup_dst.crypto[i].key; + } + if (!check_str || + pj_stricmp(&backup_dst.crypto[i].name, &src->crypto[i].name)) + { + pj_strdup(pool, &dst->crypto[i].name, &src->crypto[i].name); + } else { + /* If strings are identical, use the old string to + * avoid wasting memory. + */ + dst->crypto[i].name = backup_dst.crypto[i].name; + } + } } } @@ -362,7 +361,7 @@ PJ_DEF(void) pjsua_acc_config_default(pjsua_acc_config *cfg) cfg->contact_use_src_port = PJ_TRUE; cfg->use_rfc5626 = PJ_TRUE; cfg->reg_use_proxy = PJSUA_REG_USE_OUTBOUND_PROXY | - PJSUA_REG_USE_ACC_PROXY; + PJSUA_REG_USE_ACC_PROXY; #if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0 cfg->use_stream_ka = (PJMEDIA_STREAM_ENABLE_KA != 0); pjmedia_stream_ka_config_default(&cfg->stream_ka_cfg); @@ -377,8 +376,8 @@ PJ_DEF(void) pjsua_acc_config_default(pjsua_acc_config *cfg) cfg->ip_change_cfg.shutdown_tp = PJ_TRUE; cfg->ip_change_cfg.hangup_calls = PJ_FALSE; cfg->ip_change_cfg.reinvite_flags = PJSUA_CALL_REINIT_MEDIA | - PJSUA_CALL_UPDATE_CONTACT | - PJSUA_CALL_UPDATE_VIA; + PJSUA_CALL_UPDATE_CONTACT | + PJSUA_CALL_UPDATE_VIA; cfg->enable_rtcp_xr = (PJMEDIA_HAS_RTCP_XR && PJMEDIA_STREAM_ENABLE_XR); } @@ -452,18 +451,18 @@ static pj_bool_t logging_on_rx_msg(pjsip_rx_data *rdata) pj_str_t input_str = pj_str(rdata->pkt_info.src_name); PJ_LOG(4,(THIS_FILE, "RX %d bytes %s from %s %s:\n" - "%.*s\n" - "--end msg--", - rdata->msg_info.len, - pjsip_rx_data_get_info(rdata), - rdata->tp_info.transport->type_name, - pj_addr_str_print(&input_str, - rdata->pkt_info.src_port, - addr, - sizeof(addr), - 1), - (int)rdata->msg_info.len, - rdata->msg_info.msg_buf)); + "%.*s\n" + "--end msg--", + rdata->msg_info.len, + pjsip_rx_data_get_info(rdata), + rdata->tp_info.transport->type_name, + pj_addr_str_print(&input_str, + rdata->pkt_info.src_port, + addr, + sizeof(addr), + 1), + (int)rdata->msg_info.len, + rdata->msg_info.msg_buf)); /* Always return false, otherwise messages will not get processed! */ return PJ_FALSE; @@ -476,23 +475,23 @@ static pj_status_t logging_on_tx_msg(pjsip_tx_data *tdata) pj_str_t input_str = pj_str(tdata->tp_info.dst_name); /* Important note: - * tp_info field is only valid after outgoing messages has passed - * transport layer. So don't try to access tp_info when the module - * has lower priority than transport layer. + * tp_info field is only valid after outgoing messages has passed + * transport layer. So don't try to access tp_info when the module + * has lower priority than transport layer. */ PJ_LOG(4,(THIS_FILE, "TX %d bytes %s to %s %s:\n" - "%.*s\n" - "--end msg--", - (tdata->buf.cur - tdata->buf.start), - pjsip_tx_data_get_info(tdata), - tdata->tp_info.transport->type_name, - pj_addr_str_print(&input_str, - tdata->tp_info.dst_port, - addr, - sizeof(addr), - 1), - (int)(tdata->buf.cur - tdata->buf.start), - tdata->buf.start)); + "%.*s\n" + "--end msg--", + (tdata->buf.cur - tdata->buf.start), + pjsip_tx_data_get_info(tdata), + tdata->tp_info.transport->type_name, + pj_addr_str_print(&input_str, + tdata->tp_info.dst_port, + addr, + sizeof(addr), + 1), + (int)(tdata->buf.cur - tdata->buf.start), + tdata->buf.start)); /* Always return success, otherwise message will not get sent! */ @@ -502,19 +501,19 @@ static pj_status_t logging_on_tx_msg(pjsip_tx_data *tdata) /* The module instance. */ static pjsip_module pjsua_msg_logger = { - NULL, NULL, /* prev, next. */ - { "mod-pjsua-log", 13 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &logging_on_rx_msg, /* on_rx_request() */ - &logging_on_rx_msg, /* on_rx_response() */ - &logging_on_tx_msg, /* on_tx_request. */ - &logging_on_tx_msg, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-pjsua-log", 13 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &logging_on_rx_msg, /* on_rx_request() */ + &logging_on_rx_msg, /* on_rx_response() */ + &logging_on_tx_msg, /* on_tx_request. */ + &logging_on_tx_msg, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -533,81 +532,81 @@ static pj_bool_t options_on_rx_request(pjsip_rx_data *rdata) /* Only want to handle OPTIONS requests */ if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, - pjsip_get_options_method()) != 0) + pjsip_get_options_method()) != 0) { - return PJ_FALSE; + return PJ_FALSE; } /* Don't want to handle if shutdown is in progress */ if (pjsua_var.thread_quit_flag) { - pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, - PJSIP_SC_TEMPORARILY_UNAVAILABLE, NULL, - NULL, NULL); - return PJ_TRUE; + pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, + PJSIP_SC_TEMPORARILY_UNAVAILABLE, NULL, + NULL, NULL); + return PJ_TRUE; } /* Create basic response. */ status = pjsip_endpt_create_response(pjsua_var.endpt, rdata, 200, NULL, - &tdata); + &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create OPTIONS response", status); - return PJ_TRUE; + pjsua_perror(THIS_FILE, "Unable to create OPTIONS response", status); + return PJ_TRUE; } /* Add Allow header */ cap_hdr = pjsip_endpt_get_capability(pjsua_var.endpt, PJSIP_H_ALLOW, NULL); if (cap_hdr) { - pjsip_msg_add_hdr(tdata->msg, - (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr)); + pjsip_msg_add_hdr(tdata->msg, + (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr)); } /* Add Accept header */ cap_hdr = pjsip_endpt_get_capability(pjsua_var.endpt, PJSIP_H_ACCEPT, NULL); if (cap_hdr) { - pjsip_msg_add_hdr(tdata->msg, - (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr)); + pjsip_msg_add_hdr(tdata->msg, + (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr)); } /* Add Supported header */ cap_hdr = pjsip_endpt_get_capability(pjsua_var.endpt, PJSIP_H_SUPPORTED, NULL); if (cap_hdr) { - pjsip_msg_add_hdr(tdata->msg, - (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr)); + pjsip_msg_add_hdr(tdata->msg, + (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr)); } /* Add Allow-Events header from the evsub module */ cap_hdr = pjsip_evsub_get_allow_events_hdr(NULL); if (cap_hdr) { - pjsip_msg_add_hdr(tdata->msg, - (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr)); + pjsip_msg_add_hdr(tdata->msg, + (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr)); } /* Add User-Agent header */ if (pjsua_var.ua_cfg.user_agent.slen) { - const pj_str_t USER_AGENT = { "User-Agent", 10}; - pjsip_hdr *h; + const pj_str_t USER_AGENT = { "User-Agent", 10}; + pjsip_hdr *h; - h = (pjsip_hdr*) pjsip_generic_string_hdr_create(tdata->pool, - &USER_AGENT, - &pjsua_var.ua_cfg.user_agent); - pjsip_msg_add_hdr(tdata->msg, h); + h = (pjsip_hdr*) pjsip_generic_string_hdr_create(tdata->pool, + &USER_AGENT, + &pjsua_var.ua_cfg.user_agent); + pjsip_msg_add_hdr(tdata->msg, h); } /* Get media socket info, make sure transport is ready */ #if DISABLED_FOR_TICKET_1185 if (pjsua_var.calls[0].med_tp) { - pjmedia_transport_info tpinfo; - pjmedia_sdp_session *sdp; + pjmedia_transport_info tpinfo; + pjmedia_sdp_session *sdp; - pjmedia_transport_info_init(&tpinfo); - pjmedia_transport_get_info(pjsua_var.calls[0].med_tp, &tpinfo); + pjmedia_transport_info_init(&tpinfo); + pjmedia_transport_get_info(pjsua_var.calls[0].med_tp, &tpinfo); - /* Add SDP body, using call0's RTP address */ - status = pjmedia_endpt_create_sdp(pjsua_var.med_endpt, tdata->pool, 1, - &tpinfo.sock_info, &sdp); - if (status == PJ_SUCCESS) { - pjsip_create_sdp_body(tdata->pool, sdp, &tdata->msg->body); - } + /* Add SDP body, using call0's RTP address */ + status = pjmedia_endpt_create_sdp(pjsua_var.med_endpt, tdata->pool, 1, + &tpinfo.sock_info, &sdp); + if (status == PJ_SUCCESS) { + pjsip_create_sdp_body(tdata->pool, sdp, &tdata->msg->body); + } } #endif @@ -615,7 +614,7 @@ static pj_bool_t options_on_rx_request(pjsip_rx_data *rdata) pjsip_get_response_addr(tdata->pool, rdata, &res_addr); status = pjsip_endpt_send_response(pjsua_var.endpt, &res_addr, tdata, NULL, NULL); if (status != PJ_SUCCESS) - pjsip_tx_data_dec_ref(tdata); + pjsip_tx_data_dec_ref(tdata); return PJ_TRUE; } @@ -624,19 +623,19 @@ static pj_bool_t options_on_rx_request(pjsip_rx_data *rdata) /* The module instance. */ static pjsip_module pjsua_options_handler = { - NULL, NULL, /* prev, next. */ - { "mod-pjsua-options", 17 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &options_on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-pjsua-options", 17 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &options_on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -664,7 +663,7 @@ static pj_bool_t mod_pjsua_on_rx_request(pjsip_rx_data *rdata) if (rdata->msg_info.msg->line.req.method.id == PJSIP_INVITE_METHOD) { - processed = pjsua_call_on_incoming(rdata); + processed = pjsua_call_on_incoming(rdata); } PJSUA_UNLOCK(); @@ -701,18 +700,18 @@ static void log_writer(int level, const char *buffer, int len) /* Write to file, stdout or application callback. */ if (pjsua_var.log_file) { - pj_ssize_t size = len; - pj_file_write(pjsua_var.log_file, buffer, &size); - /* This will slow things down considerably! Don't do it! - pj_file_flush(pjsua_var.log_file); - */ + pj_ssize_t size = len; + pj_file_write(pjsua_var.log_file, buffer, &size); + /* This will slow things down considerably! Don't do it! + pj_file_flush(pjsua_var.log_file); + */ } if (level <= (int)pjsua_var.log_cfg.console_level) { - if (pjsua_var.log_cfg.cb) - (*pjsua_var.log_cfg.cb)(level, buffer, len); - else - pj_log_write(level, buffer, len); + if (pjsua_var.log_cfg.cb) + (*pjsua_var.log_cfg.cb)(level, buffer, len); + else + pj_log_write(level, buffer, len); } } @@ -739,34 +738,34 @@ PJ_DEF(pj_status_t) pjsua_reconfigure_logging(const pjsua_logging_config *cfg) /* Close existing file, if any */ if (pjsua_var.log_file) { - pj_file_close(pjsua_var.log_file); - pjsua_var.log_file = NULL; + pj_file_close(pjsua_var.log_file); + pjsua_var.log_file = NULL; } /* If output log file is desired, create the file: */ if (pjsua_var.log_cfg.log_filename.slen) { - unsigned flags = PJ_O_WRONLY; - flags |= pjsua_var.log_cfg.log_file_flags; - status = pj_file_open(pjsua_var.pool, - pjsua_var.log_cfg.log_filename.ptr, - flags, - &pjsua_var.log_file); - - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating log file", status); - return status; - } + unsigned flags = PJ_O_WRONLY; + flags |= pjsua_var.log_cfg.log_file_flags; + status = pj_file_open(pjsua_var.pool, + pjsua_var.log_cfg.log_filename.ptr, + flags, + &pjsua_var.log_file); + + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error creating log file", status); + return status; + } } /* Unregister msg logging if it's previously registered */ if (pjsua_msg_logger.id >= 0) { - pjsip_endpt_unregister_module(pjsua_var.endpt, &pjsua_msg_logger); - pjsua_msg_logger.id = -1; + pjsip_endpt_unregister_module(pjsua_var.endpt, &pjsua_msg_logger); + pjsua_msg_logger.id = -1; } /* Enable SIP message logging */ if (pjsua_var.log_cfg.msg_logging) - pjsip_endpt_register_module(pjsua_var.endpt, &pjsua_msg_logger); + pjsip_endpt_register_module(pjsua_var.endpt, &pjsua_msg_logger); return PJ_SUCCESS; } @@ -784,11 +783,11 @@ static int worker_thread(void *arg) PJ_UNUSED_ARG(arg); while (!pjsua_var.thread_quit_flag) { - int count; + int count; - count = pjsua_handle_events(TIMEOUT); - if (count < 0) - pj_thread_sleep(TIMEOUT); + count = pjsua_handle_events(TIMEOUT); + if (count < 0) + pj_thread_sleep(TIMEOUT); } return 0; @@ -805,18 +804,18 @@ static int worker_thread_timer(void *arg) th = pjsip_endpt_get_timer_heap(pjsua_var.endpt); while (!pjsua_var.thread_quit_flag) { - pj_time_val timeout = {0, 0}; - int c; - - c = pj_timer_heap_poll(th, &timeout); - if (c == 0) { - /* Sleep if no event */ - enum { MAX_SLEEP_MS = 100 }; - if (PJ_TIME_VAL_MSEC(timeout) < MAX_SLEEP_MS) - pj_thread_sleep(PJ_TIME_VAL_MSEC(timeout)); - else - pj_thread_sleep(MAX_SLEEP_MS); - } + pj_time_val timeout = {0, 0}; + int c; + + c = pj_timer_heap_poll(th, &timeout); + if (c == 0) { + /* Sleep if no event */ + enum { MAX_SLEEP_MS = 100 }; + if (PJ_TIME_VAL_MSEC(timeout) < MAX_SLEEP_MS) + pj_thread_sleep(PJ_TIME_VAL_MSEC(timeout)); + else + pj_thread_sleep(MAX_SLEEP_MS); + } } return 0; } @@ -830,8 +829,8 @@ static int worker_thread_ioqueue(void *arg) ioq = pjsip_endpt_get_ioqueue(pjsua_var.endpt); while (!pjsua_var.thread_quit_flag) { - pj_time_val timeout = {0, 100}; - pj_ioqueue_poll(ioq, &timeout); + pj_time_val timeout = {0, 100}; + pj_ioqueue_poll(ioq, &timeout); } return 0; } @@ -846,16 +845,16 @@ PJ_DEF(void) pjsua_stop_worker_threads(void) /* Wait worker threads to quit: */ for (i=0; i<(int)pjsua_var.ua_cfg.thread_cnt; ++i) { - if (pjsua_var.thread[i]) { - pj_status_t status; - status = pj_thread_join(pjsua_var.thread[i]); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, "Error joining worker thread")); - pj_thread_sleep(1000); - } - pj_thread_destroy(pjsua_var.thread[i]); - pjsua_var.thread[i] = NULL; - } + if (pjsua_var.thread[i]) { + pj_status_t status; + status = pj_thread_join(pjsua_var.thread[i]); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, "Error joining worker thread")); + pj_thread_sleep(1000); + } + pj_thread_destroy(pjsua_var.thread[i]); + pjsua_var.thread[i] = NULL; + } } } @@ -874,7 +873,7 @@ static void init_random_seed(void) /* Add primary IP address */ if (pj_gethostip(pj_AF_INET(), &addr)==PJ_SUCCESS) - seed = pj_hash_calc(seed, &addr.ipv4.sin_addr, 4); + seed = pj_hash_calc(seed, &addr.ipv4.sin_addr, 4); /* Get timeofday */ pj_gettimeofday(&t); @@ -913,19 +912,19 @@ PJ_DEF(pj_status_t) pjsua_create(void) /* Init PJLIB-UTIL: */ status = pjlib_util_init(); if (status != PJ_SUCCESS) { - pj_log_pop_indent(); - pjsua_perror(THIS_FILE, "Failed in initializing pjlib-util", status); - pj_shutdown(); - return status; + pj_log_pop_indent(); + pjsua_perror(THIS_FILE, "Failed in initializing pjlib-util", status); + pj_shutdown(); + return status; } /* Init PJNATH */ status = pjnath_init(); if (status != PJ_SUCCESS) { - pj_log_pop_indent(); - pjsua_perror(THIS_FILE, "Failed in initializing pjnath", status); - pj_shutdown(); - return status; + pj_log_pop_indent(); + pjsua_perror(THIS_FILE, "Failed in initializing pjnath", status); + pj_shutdown(); + return status; } /* Set default sound device ID */ @@ -943,34 +942,34 @@ PJ_DEF(pj_status_t) pjsua_create(void) pjsua_var.pool = pjsua_pool_create("pjsua", PJSUA_POOL_LEN, PJSUA_POOL_INC); pjsua_var.timer_pool = pjsua_pool_create("pjsua_timer", 500, 500); if (pjsua_var.pool == NULL || pjsua_var.timer_pool == NULL) { - pj_log_pop_indent(); - status = PJ_ENOMEM; - pjsua_perror(THIS_FILE, "Unable to create pjsua/timer pool", status); - pj_shutdown(); - return status; + pj_log_pop_indent(); + status = PJ_ENOMEM; + pjsua_perror(THIS_FILE, "Unable to create pjsua/timer pool", status); + pj_shutdown(); + return status; } /* Create mutex */ status = pj_mutex_create_recursive(pjsua_var.pool, "pjsua", - &pjsua_var.mutex); + &pjsua_var.mutex); if (status != PJ_SUCCESS) { - pj_log_pop_indent(); - pjsua_perror(THIS_FILE, "Unable to create mutex", status); - pjsua_destroy(); - return status; + pj_log_pop_indent(); + pjsua_perror(THIS_FILE, "Unable to create mutex", status); + pjsua_destroy(); + return status; } /* Must create SIP endpoint to initialize SIP parser. The parser * is needed for example when application needs to call pjsua_verify_url(). */ status = pjsip_endpt_create(&pjsua_var.cp.factory, - pj_gethostname()->ptr, - &pjsua_var.endpt); + pj_gethostname()->ptr, + &pjsua_var.endpt); if (status != PJ_SUCCESS) { - pj_log_pop_indent(); - pjsua_perror(THIS_FILE, "Unable to create endpoint", status); - pjsua_destroy(); - return status; + pj_log_pop_indent(); + pjsua_perror(THIS_FILE, "Unable to create endpoint", status); + pjsua_destroy(); + return status; } /* Init timer entry and event list */ @@ -980,12 +979,12 @@ PJ_DEF(pj_status_t) pjsua_create(void) /* Create timer mutex */ status = pj_mutex_create_recursive(pjsua_var.pool, "pjsua_timer", - &pjsua_var.timer_mutex); + &pjsua_var.timer_mutex); if (status != PJ_SUCCESS) { - pj_log_pop_indent(); - pjsua_perror(THIS_FILE, "Unable to create mutex", status); - pjsua_destroy(); - return status; + pj_log_pop_indent(); + pjsua_perror(THIS_FILE, "Unable to create mutex", status); + pjsua_destroy(); + return status; } pjsua_set_state(PJSUA_STATE_CREATED); @@ -1008,12 +1007,12 @@ static void upnp_cb(pj_status_t status) * specified. */ PJ_DEF(pj_status_t) pjsua_init( const pjsua_config *ua_cfg, - const pjsua_logging_config *log_cfg, - const pjsua_media_config *media_cfg) + const pjsua_logging_config *log_cfg, + const pjsua_media_config *media_cfg) { - pjsua_config default_cfg; - pjsua_media_config default_media_cfg; - const pj_str_t STR_OPTIONS = { "OPTIONS", 7 }; + pjsua_config default_cfg; + pjsua_media_config default_media_cfg; + const pj_str_t STR_OPTIONS = { "OPTIONS", 7 }; pjsip_ua_init_param ua_init_param; unsigned i; pj_status_t status; @@ -1023,28 +1022,28 @@ PJ_DEF(pj_status_t) pjsua_init( const pjsua_config *ua_cfg, /* Create default configurations when the config is not supplied */ if (ua_cfg == NULL) { - pjsua_config_default(&default_cfg); - ua_cfg = &default_cfg; + pjsua_config_default(&default_cfg); + ua_cfg = &default_cfg; } if (media_cfg == NULL) { - pjsua_media_config_default(&default_media_cfg); - media_cfg = &default_media_cfg; + pjsua_media_config_default(&default_media_cfg); + media_cfg = &default_media_cfg; } /* Initialize logging first so that info/errors can be captured */ if (log_cfg) { - status = pjsua_reconfigure_logging(log_cfg); - if (status != PJ_SUCCESS) - goto on_error; + status = pjsua_reconfigure_logging(log_cfg); + if (status != PJ_SUCCESS) + goto on_error; } #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT != 0 if (!(pj_get_sys_info()->flags & PJ_SYS_HAS_IOS_BG)) { - PJ_LOG(5, (THIS_FILE, "Device does not support " - "background mode")); - pj_activesock_enable_iphone_os_bg(PJ_FALSE); + PJ_LOG(5, (THIS_FILE, "Device does not support " + "background mode")); + pj_activesock_enable_iphone_os_bg(PJ_FALSE); } #endif @@ -1053,41 +1052,41 @@ PJ_DEF(pj_status_t) pjsua_init( const pjsua_config *ua_cfg, */ if (ua_cfg->nameserver_count) { #if PJSIP_HAS_RESOLVER - unsigned ii; - - /* Create DNS resolver */ - status = pjsip_endpt_create_resolver(pjsua_var.endpt, - &pjsua_var.resolver); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating resolver", status); - goto on_error; - } - - /* Configure nameserver for the DNS resolver */ - status = pj_dns_resolver_set_ns(pjsua_var.resolver, - ua_cfg->nameserver_count, - ua_cfg->nameserver, NULL); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error setting nameserver", status); - goto on_error; - } - - /* Set this DNS resolver to be used by the SIP resolver */ - status = pjsip_endpt_set_resolver(pjsua_var.endpt, pjsua_var.resolver); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error setting DNS resolver", status); - goto on_error; - } - - /* Print nameservers */ - for (ii=0; iinameserver_count; ++ii) { - PJ_LOG(4,(THIS_FILE, "Nameserver %.*s added", - (int)ua_cfg->nameserver[ii].slen, - ua_cfg->nameserver[ii].ptr)); - } + unsigned ii; + + /* Create DNS resolver */ + status = pjsip_endpt_create_resolver(pjsua_var.endpt, + &pjsua_var.resolver); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error creating resolver", status); + goto on_error; + } + + /* Configure nameserver for the DNS resolver */ + status = pj_dns_resolver_set_ns(pjsua_var.resolver, + ua_cfg->nameserver_count, + ua_cfg->nameserver, NULL); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error setting nameserver", status); + goto on_error; + } + + /* Set this DNS resolver to be used by the SIP resolver */ + status = pjsip_endpt_set_resolver(pjsua_var.endpt, pjsua_var.resolver); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error setting DNS resolver", status); + goto on_error; + } + + /* Print nameservers */ + for (ii=0; iinameserver_count; ++ii) { + PJ_LOG(4,(THIS_FILE, "Nameserver %.*s added", + (int)ua_cfg->nameserver[ii].slen, + ua_cfg->nameserver[ii].ptr)); + } #else - PJ_LOG(2,(THIS_FILE, - "DNS resolver is disabled (PJSIP_HAS_RESOLVER==0)")); + PJ_LOG(2,(THIS_FILE, + "DNS resolver is disabled (PJSIP_HAS_RESOLVER==0)")); #endif } @@ -1101,7 +1100,7 @@ PJ_DEF(pj_status_t) pjsua_init( const pjsua_config *ua_cfg, /* Initialize UA layer module: */ pj_bzero(&ua_init_param, sizeof(ua_init_param)); if (ua_cfg->hangup_forked_call) { - ua_init_param.on_dlg_forked = &on_dlg_forked; + ua_init_param.on_dlg_forked = &on_dlg_forked; } status = pjsip_ua_init_module( pjsua_var.endpt, &ua_init_param); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); @@ -1121,102 +1120,102 @@ PJ_DEF(pj_status_t) pjsua_init( const pjsua_config *ua_cfg, /* Initialize and register PJSUA application module. */ { - const pjsip_module mod_initializer = - { - NULL, NULL, /* prev, next. */ - { "mod-pjsua", 9 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &mod_pjsua_on_rx_request, /* on_rx_request() */ - &mod_pjsua_on_rx_response, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ - }; - - pjsua_var.mod = mod_initializer; - - status = pjsip_endpt_register_module(pjsua_var.endpt, &pjsua_var.mod); - PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); + const pjsip_module mod_initializer = + { + NULL, NULL, /* prev, next. */ + { "mod-pjsua", 9 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &mod_pjsua_on_rx_request, /* on_rx_request() */ + &mod_pjsua_on_rx_response, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ + }; + + pjsua_var.mod = mod_initializer; + + status = pjsip_endpt_register_module(pjsua_var.endpt, &pjsua_var.mod); + PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); } /* Parse outbound proxies */ for (i=0; ioutbound_proxy_cnt; ++i) { - pj_str_t tmp; - pj_str_t hname = { "Route", 5}; - pjsip_route_hdr *r; - - pj_strdup_with_null(pjsua_var.pool, &tmp, &ua_cfg->outbound_proxy[i]); - - r = (pjsip_route_hdr*) - pjsip_parse_hdr(pjsua_var.pool, &hname, tmp.ptr, - (unsigned)tmp.slen, NULL); - if (r == NULL) { - pjsua_perror(THIS_FILE, "Invalid outbound proxy URI", - PJSIP_EINVALIDURI); - status = PJSIP_EINVALIDURI; - goto on_error; - } - - if (pjsua_var.ua_cfg.force_lr) { - pjsip_sip_uri *sip_url; - if (!PJSIP_URI_SCHEME_IS_SIP(r->name_addr.uri) && - !PJSIP_URI_SCHEME_IS_SIPS(r->name_addr.uri)) - { - status = PJSIP_EINVALIDSCHEME; - goto on_error; - } - sip_url = (pjsip_sip_uri*)r->name_addr.uri; - sip_url->lr_param = 1; - } - - pj_list_push_back(&pjsua_var.outbound_proxy, r); + pj_str_t tmp; + pj_str_t hname = { "Route", 5}; + pjsip_route_hdr *r; + + pj_strdup_with_null(pjsua_var.pool, &tmp, &ua_cfg->outbound_proxy[i]); + + r = (pjsip_route_hdr*) + pjsip_parse_hdr(pjsua_var.pool, &hname, tmp.ptr, + (unsigned)tmp.slen, NULL); + if (r == NULL) { + pjsua_perror(THIS_FILE, "Invalid outbound proxy URI", + PJSIP_EINVALIDURI); + status = PJSIP_EINVALIDURI; + goto on_error; + } + + if (pjsua_var.ua_cfg.force_lr) { + pjsip_sip_uri *sip_url; + if (!PJSIP_URI_SCHEME_IS_SIP(r->name_addr.uri) && + !PJSIP_URI_SCHEME_IS_SIPS(r->name_addr.uri)) + { + status = PJSIP_EINVALIDSCHEME; + goto on_error; + } + sip_url = (pjsip_sip_uri*)r->name_addr.uri; + sip_url->lr_param = 1; + } + + pj_list_push_back(&pjsua_var.outbound_proxy, r); } /* Initialize PJSUA call subsystem: */ status = pjsua_call_subsys_init(ua_cfg); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Convert deprecated STUN settings */ if (pjsua_var.ua_cfg.stun_srv_cnt==0) { - if (pjsua_var.ua_cfg.stun_domain.slen) { - pjsua_var.ua_cfg.stun_srv[pjsua_var.ua_cfg.stun_srv_cnt++] = - pjsua_var.ua_cfg.stun_domain; - } - if (pjsua_var.ua_cfg.stun_host.slen) { - pjsua_var.ua_cfg.stun_srv[pjsua_var.ua_cfg.stun_srv_cnt++] = - pjsua_var.ua_cfg.stun_host; - } + if (pjsua_var.ua_cfg.stun_domain.slen) { + pjsua_var.ua_cfg.stun_srv[pjsua_var.ua_cfg.stun_srv_cnt++] = + pjsua_var.ua_cfg.stun_domain; + } + if (pjsua_var.ua_cfg.stun_host.slen) { + pjsua_var.ua_cfg.stun_srv[pjsua_var.ua_cfg.stun_srv_cnt++] = + pjsua_var.ua_cfg.stun_host; + } } /* Start resolving STUN server */ status = resolve_stun_server(PJ_FALSE, PJ_FALSE, 0); if (status != PJ_SUCCESS && status != PJ_EPENDING) { - pjsua_perror(THIS_FILE, "Error resolving STUN server", status); - goto on_error; + pjsua_perror(THIS_FILE, "Error resolving STUN server", status); + goto on_error; } #if defined(PJNATH_HAS_UPNP) && (PJNATH_HAS_UPNP != 0) /* Initialize UPnP if enabled */ if (pjsua_var.ua_cfg.enable_upnp) { - pj_upnp_init_param param; + pj_upnp_init_param param; - pj_bzero(¶m, sizeof(param)); - param.factory = pjsua_var.pool->factory; - if (pjsua_var.ua_cfg.upnp_if_name.slen > 0) - param.if_name = pjsua_var.ua_cfg.upnp_if_name.ptr; - param.upnp_cb = &upnp_cb; + pj_bzero(¶m, sizeof(param)); + param.factory = pjsua_var.pool->factory; + if (pjsua_var.ua_cfg.upnp_if_name.slen > 0) + param.if_name = pjsua_var.ua_cfg.upnp_if_name.ptr; + param.upnp_cb = &upnp_cb; - pjsua_var.upnp_status = pj_upnp_init(¶m); + pjsua_var.upnp_status = pj_upnp_init(¶m); if (pjsua_var.upnp_status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error initializing UPnP", - pjsua_var.upnp_status); + pjsua_perror(THIS_FILE, "Error initializing UPnP", + pjsua_var.upnp_status); } } #endif @@ -1224,7 +1223,7 @@ PJ_DEF(pj_status_t) pjsua_init( const pjsua_config *ua_cfg, /* Initialize PJSUA media subsystem */ status = pjsua_media_subsys_init(media_cfg); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Init core SIMPLE module : */ @@ -1249,64 +1248,64 @@ PJ_DEF(pj_status_t) pjsua_init( const pjsua_config *ua_cfg, /* Init pjsua presence handler: */ status = pjsua_pres_init(); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Init out-of-dialog MESSAGE request handler. */ status = pjsua_im_init(); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Register OPTIONS handler */ pjsip_endpt_register_module(pjsua_var.endpt, &pjsua_options_handler); /* Add OPTIONS in Allow header */ pjsip_endpt_add_capability(pjsua_var.endpt, NULL, PJSIP_H_ALLOW, - NULL, 1, &STR_OPTIONS); + NULL, 1, &STR_OPTIONS); /* Start worker thread if needed. */ if (pjsua_var.ua_cfg.thread_cnt) { - unsigned ii; + unsigned ii; - if (pjsua_var.ua_cfg.thread_cnt > PJ_ARRAY_SIZE(pjsua_var.thread)) - pjsua_var.ua_cfg.thread_cnt = PJ_ARRAY_SIZE(pjsua_var.thread); + if (pjsua_var.ua_cfg.thread_cnt > PJ_ARRAY_SIZE(pjsua_var.thread)) + pjsua_var.ua_cfg.thread_cnt = PJ_ARRAY_SIZE(pjsua_var.thread); #if PJSUA_SEPARATE_WORKER_FOR_TIMER - if (pjsua_var.ua_cfg.thread_cnt < 2) - pjsua_var.ua_cfg.thread_cnt = 2; + if (pjsua_var.ua_cfg.thread_cnt < 2) + pjsua_var.ua_cfg.thread_cnt = 2; #endif - for (ii=0; iiinfo.ptr)); + pj_get_version(), pj_get_sys_info()->info.ptr)); pjsua_set_state(PJSUA_STATE_INIT); pj_log_pop_indent(); @@ -1328,11 +1327,11 @@ static void busy_sleep(unsigned msec) pj_time_val_normalize(&timeout); do { - int i; - i = msec / 10; - while (pjsua_handle_events(10) > 0 && i > 0) - --i; - pj_gettickcount(&now); + int i; + i = msec / 10; + while (pjsua_handle_events(10) > 0 && i > 0) + --i; + pj_gettickcount(&now); } while (PJ_TIME_VAL_LT(now, timeout)); } @@ -1366,7 +1365,7 @@ static void destroy_stun_resolve(pjsua_stun_resolve *sess, pj_bool_t forced) pj_time_val timeout = {0, 0}; if (sess->destroy_flag) - return; + return; sess->destroy_flag = PJ_TRUE; if (sess->stun_sock) { @@ -1375,22 +1374,22 @@ static void destroy_stun_resolve(pjsua_stun_resolve *sess, pj_bool_t forced) } if (pjsua_var.stun_status == PJ_EUNKNOWN || - pjsua_var.stun_status == PJ_EPENDING) + pjsua_var.stun_status == PJ_EPENDING) { pjsua_var.stun_status = PJNATH_ESTUNDESTROYED; } if (forced) { - release_stun_session(sess); + release_stun_session(sess); } else { - /* Schedule session clean up, it needs PJSUA lock and locking it here - * may cause deadlock as this function may be called by STUN socket - * while holding STUN socket lock, while application may wait for STUN - * resolution while holding PJSUA lock. - */ - pj_timer_entry_init(&sess->timer, 0, (void*)sess, - &destroy_stun_resolve_cb); - pjsua_schedule_timer(&sess->timer, &timeout); + /* Schedule session clean up, it needs PJSUA lock and locking it here + * may cause deadlock as this function may be called by STUN socket + * while holding STUN socket lock, while application may wait for STUN + * resolution while holding PJSUA lock. + */ + pj_timer_entry_init(&sess->timer, 0, (void*)sess, + &destroy_stun_resolve_cb); + pjsua_schedule_timer(&sess->timer, &timeout); } } @@ -1401,9 +1400,9 @@ static void stun_resolve_dec_ref(pjsua_stun_resolve *sess) * is allowed to destroy the session, otherwise it may cause deadlock. */ if ((ref_cnt > 0) || - (sess->blocking && (sess->waiter != pj_thread_this()))) + (sess->blocking && (sess->waiter != pj_thread_this()))) { - return; + return; } destroy_stun_resolve(sess, PJ_FALSE); @@ -1418,7 +1417,7 @@ static void stun_resolve_complete(pjsua_stun_resolve *sess) pj_stun_resolve_result result; if (sess->has_result) - goto on_return; + goto on_return; pj_bzero(&result, sizeof(result)); result.token = sess->token; @@ -1429,24 +1428,24 @@ static void stun_resolve_complete(pjsua_stun_resolve *sess) sess->has_result = PJ_TRUE; if (result.status == PJ_SUCCESS) { - char addr[PJ_INET6_ADDRSTRLEN+10]; - pj_sockaddr_print(&result.addr, addr, sizeof(addr), 3); - PJ_LOG(4,(THIS_FILE, - "STUN resolution success, using %.*s, address is %s", - (int)sess->srv[sess->idx].slen, - sess->srv[sess->idx].ptr, - addr)); + char addr[PJ_INET6_ADDRSTRLEN+10]; + pj_sockaddr_print(&result.addr, addr, sizeof(addr), 3); + PJ_LOG(4,(THIS_FILE, + "STUN resolution success, using %.*s, address is %s", + (int)sess->srv[sess->idx].slen, + sess->srv[sess->idx].ptr, + addr)); } else { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(result.status, errmsg, sizeof(errmsg)); - PJ_LOG(1,(THIS_FILE, "STUN resolution failed: %s", errmsg)); + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(result.status, errmsg, sizeof(errmsg)); + PJ_LOG(1,(THIS_FILE, "STUN resolution failed: %s", errmsg)); } sess->cb(&result); on_return: if (!sess->blocking) { - stun_resolve_dec_ref(sess); + stun_resolve_dec_ref(sess); } } @@ -1455,8 +1454,8 @@ static void stun_resolve_complete(pjsua_stun_resolve *sess) * STUN server. */ static pj_bool_t test_stun_on_status(pj_stun_sock *stun_sock, - pj_stun_sock_op op, - pj_status_t status) + pj_stun_sock_op op, + pj_status_t status) { pjsua_stun_resolve *sess; @@ -1464,61 +1463,61 @@ static pj_bool_t test_stun_on_status(pj_stun_sock *stun_sock, pj_assert(stun_sock == sess->stun_sock); if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - - PJ_LOG(4,(THIS_FILE, "STUN resolution for %.*s failed: %s", - (int)sess->srv[sess->idx].slen, - sess->srv[sess->idx].ptr, errmsg)); - - if (op == PJ_STUN_SOCK_BINDING_OP && !sess->async_wait) { - /* Just return here, we will destroy the STUN socket and - * continue the STUN resolution later in resolve_stun_entry(). - * For more details, please refer to ticket #1962. - */ + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + + PJ_LOG(4,(THIS_FILE, "STUN resolution for %.*s failed: %s", + (int)sess->srv[sess->idx].slen, + sess->srv[sess->idx].ptr, errmsg)); + + if (op == PJ_STUN_SOCK_BINDING_OP && !sess->async_wait) { + /* Just return here, we will destroy the STUN socket and + * continue the STUN resolution later in resolve_stun_entry(). + * For more details, please refer to ticket #1962. + */ return PJ_FALSE; - } + } - pj_stun_sock_destroy(stun_sock); - sess->stun_sock = NULL; + pj_stun_sock_destroy(stun_sock); + sess->stun_sock = NULL; - stun_resolve_add_ref(sess); + stun_resolve_add_ref(sess); - if (pjsua_var.ua_cfg.stun_try_ipv6 && sess->af == pj_AF_INET()) { - sess->af = pj_AF_INET6(); - } else { - ++sess->idx; - sess->af = pj_AF_INET(); - if (sess->idx >= sess->count) + if (pjsua_var.ua_cfg.stun_try_ipv6 && sess->af == pj_AF_INET()) { + sess->af = pj_AF_INET6(); + } else { + ++sess->idx; + sess->af = pj_AF_INET(); + if (sess->idx >= sess->count) sess->status = status; } - resolve_stun_entry(sess); + resolve_stun_entry(sess); - stun_resolve_dec_ref(sess); + stun_resolve_dec_ref(sess); - return PJ_FALSE; + return PJ_FALSE; } else if (op == PJ_STUN_SOCK_BINDING_OP) { - pj_stun_sock_info ssi; + pj_stun_sock_info ssi; - pj_stun_sock_get_info(stun_sock, &ssi); - pj_memcpy(&sess->addr, &ssi.srv_addr, sizeof(sess->addr)); + pj_stun_sock_get_info(stun_sock, &ssi); + pj_memcpy(&sess->addr, &ssi.srv_addr, sizeof(sess->addr)); - stun_resolve_add_ref(sess); + stun_resolve_add_ref(sess); - sess->status = PJ_SUCCESS; - pj_stun_sock_destroy(stun_sock); - sess->stun_sock = NULL; + sess->status = PJ_SUCCESS; + pj_stun_sock_destroy(stun_sock); + sess->stun_sock = NULL; - stun_resolve_complete(sess); + stun_resolve_complete(sess); - stun_resolve_dec_ref(sess); + stun_resolve_dec_ref(sess); - return PJ_FALSE; + return PJ_FALSE; } else - return PJ_TRUE; + return PJ_TRUE; } @@ -1532,98 +1531,98 @@ static void resolve_stun_entry(pjsua_stun_resolve *sess) /* Loop while we have entry to try */ for (; sess->idx < sess->count; - (pjsua_var.ua_cfg.stun_try_ipv6 && sess->af == pj_AF_INET())? - sess->af = pj_AF_INET6(): (++sess->idx, sess->af = pj_AF_INET())) + (pjsua_var.ua_cfg.stun_try_ipv6 && sess->af == pj_AF_INET())? + sess->af = pj_AF_INET6(): (++sess->idx, sess->af = pj_AF_INET())) { - int af; - char target[64]; - pj_str_t hostpart; - pj_uint16_t port; - pj_stun_sock_cb stun_sock_cb; - - pj_assert(sess->idx < sess->count); - - if (pjsua_var.ua_cfg.stun_try_ipv6 && - pjsua_var.stun_opt != PJSUA_NAT64_DISABLED && - sess->af == pj_AF_INET()) - { - /* Skip IPv4 STUN resolution if NAT64 is not disabled. */ - PJ_LOG(4,(THIS_FILE, "Skipping IPv4 resolution of STUN server " - "%s (%d of %d)", target, - sess->idx+1, sess->count)); - continue; - } - - pj_ansi_snprintf(target, sizeof(target), "%.*s", - (int)sess->srv[sess->idx].slen, - sess->srv[sess->idx].ptr); - - /* Parse the server entry into host:port */ - status = pj_sockaddr_parse2(pj_AF_UNSPEC(), 0, &sess->srv[sess->idx], - &hostpart, &port, &af); - if (status != PJ_SUCCESS) { - PJ_LOG(2,(THIS_FILE, "Invalid STUN server entry %s", target)); - continue; - } - - /* Use default port if not specified */ - if (port == 0) - port = PJ_STUN_PORT; - - pj_assert(sess->stun_sock == NULL); - - PJ_LOG(4,(THIS_FILE, "Trying STUN server %s %s (%d of %d)..", - target, (sess->af == pj_AF_INET()? "IPv4": "IPv6"), - sess->idx+1, sess->count)); - - /* Use STUN_sock to test this entry */ - pj_bzero(&stun_sock_cb, sizeof(stun_sock_cb)); - stun_sock_cb.on_status = &test_stun_on_status; - sess->async_wait = PJ_FALSE; - status = pj_stun_sock_create(&pjsua_var.stun_cfg, "stunresolve", - sess->af, &stun_sock_cb, - NULL, sess, &sess->stun_sock); - if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(4,(THIS_FILE, - "Error creating STUN socket for %s: %s", - target, errmsg)); - - continue; - } - - status = pj_stun_sock_start(sess->stun_sock, &hostpart, port, - pjsua_var.resolver); - if (status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(4,(THIS_FILE, - "Error starting STUN socket for %s: %s", - target, errmsg)); - - if (sess->stun_sock) { - pj_stun_sock_destroy(sess->stun_sock); - sess->stun_sock = NULL; - } - continue; - } - - /* Done for now, testing will resume/complete asynchronously in - * stun_sock_cb() - */ - sess->async_wait = PJ_TRUE; - return; + int af; + char target[64]; + pj_str_t hostpart; + pj_uint16_t port; + pj_stun_sock_cb stun_sock_cb; + + pj_assert(sess->idx < sess->count); + + if (pjsua_var.ua_cfg.stun_try_ipv6 && + pjsua_var.stun_opt != PJSUA_NAT64_DISABLED && + sess->af == pj_AF_INET()) + { + /* Skip IPv4 STUN resolution if NAT64 is not disabled. */ + PJ_LOG(4,(THIS_FILE, "Skipping IPv4 resolution of STUN server " + "%s (%d of %d)", target, + sess->idx+1, sess->count)); + continue; + } + + pj_ansi_snprintf(target, sizeof(target), "%.*s", + (int)sess->srv[sess->idx].slen, + sess->srv[sess->idx].ptr); + + /* Parse the server entry into host:port */ + status = pj_sockaddr_parse2(pj_AF_UNSPEC(), 0, &sess->srv[sess->idx], + &hostpart, &port, &af); + if (status != PJ_SUCCESS) { + PJ_LOG(2,(THIS_FILE, "Invalid STUN server entry %s", target)); + continue; + } + + /* Use default port if not specified */ + if (port == 0) + port = PJ_STUN_PORT; + + pj_assert(sess->stun_sock == NULL); + + PJ_LOG(4,(THIS_FILE, "Trying STUN server %s %s (%d of %d)..", + target, (sess->af == pj_AF_INET()? "IPv4": "IPv6"), + sess->idx+1, sess->count)); + + /* Use STUN_sock to test this entry */ + pj_bzero(&stun_sock_cb, sizeof(stun_sock_cb)); + stun_sock_cb.on_status = &test_stun_on_status; + sess->async_wait = PJ_FALSE; + status = pj_stun_sock_create(&pjsua_var.stun_cfg, "stunresolve", + sess->af, &stun_sock_cb, + NULL, sess, &sess->stun_sock); + if (status != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(4,(THIS_FILE, + "Error creating STUN socket for %s: %s", + target, errmsg)); + + continue; + } + + status = pj_stun_sock_start(sess->stun_sock, &hostpart, port, + pjsua_var.resolver); + if (status != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(4,(THIS_FILE, + "Error starting STUN socket for %s: %s", + target, errmsg)); + + if (sess->stun_sock) { + pj_stun_sock_destroy(sess->stun_sock); + sess->stun_sock = NULL; + } + continue; + } + + /* Done for now, testing will resume/complete asynchronously in + * stun_sock_cb() + */ + sess->async_wait = PJ_TRUE; + return; } if (sess->idx >= sess->count) { - /* No more entries to try */ - stun_resolve_add_ref(sess); - pj_assert(status != PJ_SUCCESS || sess->status != PJ_EPENDING); + /* No more entries to try */ + stun_resolve_add_ref(sess); + pj_assert(status != PJ_SUCCESS || sess->status != PJ_EPENDING); if (sess->status == PJ_EPENDING) sess->status = status; - stun_resolve_complete(sess); - stun_resolve_dec_ref(sess); + stun_resolve_complete(sess); + stun_resolve_dec_ref(sess); } } @@ -1632,7 +1631,7 @@ static void resolve_stun_entry(pjsua_stun_resolve *sess) * Update STUN servers. */ PJ_DEF(pj_status_t) pjsua_update_stun_servers(unsigned count, pj_str_t srv[], - pj_bool_t wait) + pj_bool_t wait) { unsigned i; pj_status_t status; @@ -1662,10 +1661,10 @@ PJ_DEF(pj_status_t) pjsua_update_stun_servers(unsigned count, pj_str_t srv[], * Resolve STUN server. */ PJ_DEF(pj_status_t) pjsua_resolve_stun_servers( unsigned count, - pj_str_t srv[], - pj_bool_t wait, - void *token, - pj_stun_resolve_cb cb) + pj_str_t srv[], + pj_bool_t wait, + void *token, + pj_stun_resolve_cb cb) { pj_pool_t *pool; pjsua_stun_resolve *sess; @@ -1677,7 +1676,7 @@ PJ_DEF(pj_status_t) pjsua_resolve_stun_servers( unsigned count, pool = pjsua_pool_create("stunres", 256, 256); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; sess = PJ_POOL_ZALLOC_T(pool, pjsua_stun_resolve); sess->pool = pool; @@ -1691,7 +1690,7 @@ PJ_DEF(pj_status_t) pjsua_resolve_stun_servers( unsigned count, stun_resolve_add_ref(sess); sess->srv = (pj_str_t*) pj_pool_calloc(pool, count, sizeof(pj_str_t)); for (i=0; isrv[i], &srv[i]); + pj_strdup(pool, &sess->srv[i], &srv[i]); } PJSUA_LOCK(); @@ -1701,7 +1700,7 @@ PJ_DEF(pj_status_t) pjsua_resolve_stun_servers( unsigned count, resolve_stun_entry(sess); if (!wait) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Should limit the wait time to avoid deadlock. For example, * if app holds dlg/tsx lock, pjsua worker thread will block on @@ -1724,9 +1723,9 @@ PJ_DEF(pj_status_t) pjsua_resolve_stun_servers( unsigned count, pj_thread_sleep(20); } - pj_get_timestamp(&now); - if (pj_elapsed_msec(&start, &now) > max_wait_ms) - sess->status = PJ_ETIMEDOUT; + pj_get_timestamp(&now); + if (pj_elapsed_msec(&start, &now) > max_wait_ms) + sess->status = PJ_ETIMEDOUT; } status = sess->status; @@ -1739,7 +1738,7 @@ PJ_DEF(pj_status_t) pjsua_resolve_stun_servers( unsigned count, * Cancel pending STUN resolution. */ PJ_DEF(pj_status_t) pjsua_cancel_stun_resolution( void *token, - pj_bool_t notify_cb) + pj_bool_t notify_cb) { pjsua_stun_resolve *sess; unsigned cancelled_count = 0; @@ -1747,24 +1746,24 @@ PJ_DEF(pj_status_t) pjsua_cancel_stun_resolution( void *token, PJSUA_LOCK(); sess = pjsua_var.stun_res.next; while (sess != &pjsua_var.stun_res) { - pjsua_stun_resolve *next = sess->next; + pjsua_stun_resolve *next = sess->next; - if (sess->token == token) { - sess->has_result = PJ_TRUE; - sess->status = PJ_ECANCELLED; - if (notify_cb) { - pj_stun_resolve_result result; + if (sess->token == token) { + sess->has_result = PJ_TRUE; + sess->status = PJ_ECANCELLED; + if (notify_cb) { + pj_stun_resolve_result result; - pj_bzero(&result, sizeof(result)); - result.token = token; - result.status = PJ_ECANCELLED; + pj_bzero(&result, sizeof(result)); + result.token = token; + result.status = PJ_ECANCELLED; - sess->cb(&result); - } - ++cancelled_count; - } + sess->cb(&result); + } + ++cancelled_count; + } - sess = next; + sess = next; } PJSUA_UNLOCK(); @@ -1775,105 +1774,105 @@ static void internal_stun_resolve_cb(const pj_stun_resolve_result *result) { pjsua_var.stun_status = result->status; if ((result->status == PJ_SUCCESS) && (pjsua_var.ua_cfg.stun_srv_cnt>0)) { - pj_memcpy(&pjsua_var.stun_srv, &result->addr, sizeof(result->addr)); - pjsua_var.stun_srv_idx = result->index; - - /* Perform NAT type detection if not yet */ - if (pjsua_var.nat_type == PJ_STUN_NAT_TYPE_UNKNOWN && - !pjsua_var.nat_in_progress && - pjsua_var.ua_cfg.nat_type_in_sdp) - { - pjsua_detect_nat_type(); - } + pj_memcpy(&pjsua_var.stun_srv, &result->addr, sizeof(result->addr)); + pjsua_var.stun_srv_idx = result->index; + + /* Perform NAT type detection if not yet */ + if (pjsua_var.nat_type == PJ_STUN_NAT_TYPE_UNKNOWN && + !pjsua_var.nat_in_progress && + pjsua_var.ua_cfg.nat_type_in_sdp) + { + pjsua_detect_nat_type(); + } } if (pjsua_var.ua_cfg.cb.on_stun_resolution_complete) - (*pjsua_var.ua_cfg.cb.on_stun_resolution_complete)(result); + (*pjsua_var.ua_cfg.cb.on_stun_resolution_complete)(result); } /* * Resolve STUN server. */ pj_status_t resolve_stun_server(pj_bool_t wait, pj_bool_t retry_if_cur_error, - unsigned options) + unsigned options) { pjsua_var.stun_opt = options; /* Retry resolving if currently the STUN status is error */ if (pjsua_var.stun_status != PJ_EPENDING && - pjsua_var.stun_status != PJ_SUCCESS && - retry_if_cur_error) + pjsua_var.stun_status != PJ_SUCCESS && + retry_if_cur_error) { - pjsua_var.stun_status = PJ_EUNKNOWN; + pjsua_var.stun_status = PJ_EUNKNOWN; } if (pjsua_var.stun_status == PJ_EUNKNOWN) { - pj_status_t status; - - /* Initialize STUN configuration */ - pj_stun_config_init(&pjsua_var.stun_cfg, &pjsua_var.cp.factory, 0, - pjsip_endpt_get_ioqueue(pjsua_var.endpt), - pjsip_endpt_get_timer_heap(pjsua_var.endpt)); - - /* Start STUN server resolution */ - if (pjsua_var.ua_cfg.stun_srv_cnt) { - pjsua_var.stun_status = PJ_EPENDING; - status = pjsua_resolve_stun_servers(pjsua_var.ua_cfg.stun_srv_cnt, - pjsua_var.ua_cfg.stun_srv, - wait, NULL, - &internal_stun_resolve_cb); - if (wait || status != PJ_SUCCESS) { - pjsua_var.stun_status = status; - } - } else { - pjsua_var.stun_status = PJ_SUCCESS; - } + pj_status_t status; + + /* Initialize STUN configuration */ + pj_stun_config_init(&pjsua_var.stun_cfg, &pjsua_var.cp.factory, 0, + pjsip_endpt_get_ioqueue(pjsua_var.endpt), + pjsip_endpt_get_timer_heap(pjsua_var.endpt)); + + /* Start STUN server resolution */ + if (pjsua_var.ua_cfg.stun_srv_cnt) { + pjsua_var.stun_status = PJ_EPENDING; + status = pjsua_resolve_stun_servers(pjsua_var.ua_cfg.stun_srv_cnt, + pjsua_var.ua_cfg.stun_srv, + wait, NULL, + &internal_stun_resolve_cb); + if (wait || status != PJ_SUCCESS) { + pjsua_var.stun_status = status; + } + } else { + pjsua_var.stun_status = PJ_SUCCESS; + } } else if (pjsua_var.stun_status == PJ_EPENDING) { - /* STUN server resolution has been started, wait for the - * result. - */ - if (wait) { - unsigned max_wait_ms; - pj_timestamp start, now; - - /* Should limit the wait time to avoid deadlock. For example, - * if app holds dlg/tsx lock, pjsua worker thread will block on - * any dlg/tsx state change. - */ - max_wait_ms = pjsua_var.ua_cfg.stun_srv_cnt * - pjsua_var.stun_cfg.rto_msec * (1 << 7); - pj_get_timestamp(&start); - - while (pjsua_var.stun_status == PJ_EPENDING) { + /* STUN server resolution has been started, wait for the + * result. + */ + if (wait) { + unsigned max_wait_ms; + pj_timestamp start, now; + + /* Should limit the wait time to avoid deadlock. For example, + * if app holds dlg/tsx lock, pjsua worker thread will block on + * any dlg/tsx state change. + */ + max_wait_ms = pjsua_var.ua_cfg.stun_srv_cnt * + pjsua_var.stun_cfg.rto_msec * (1 << 7); + pj_get_timestamp(&start); + + while (pjsua_var.stun_status == PJ_EPENDING) { /* If there is no worker thread or * the function is called from the only worker thread, * we have to handle the events here. */ - if (pjsua_var.thread[0] == NULL || + if (pjsua_var.thread[0] == NULL || (pj_thread_this() == pjsua_var.thread[0] && pjsua_var.ua_cfg.thread_cnt == 1)) { - pjsua_handle_events(10); + pjsua_handle_events(10); } else { - pj_thread_sleep(10); + pj_thread_sleep(10); } - pj_get_timestamp(&now); - if (pj_elapsed_msec(&start, &now) > max_wait_ms) - return PJ_ETIMEDOUT; - } - } + pj_get_timestamp(&now); + if (pj_elapsed_msec(&start, &now) > max_wait_ms) + return PJ_ETIMEDOUT; + } + } } if (pjsua_var.stun_status != PJ_EPENDING && - pjsua_var.stun_status != PJ_SUCCESS && - pjsua_var.ua_cfg.stun_ignore_failure) + pjsua_var.stun_status != PJ_SUCCESS && + pjsua_var.ua_cfg.stun_ignore_failure) { - PJ_LOG(2,(THIS_FILE, - "Ignoring STUN resolution failure (by setting)")); - //pjsua_var.stun_status = PJ_SUCCESS; - return PJ_SUCCESS; + PJ_LOG(2,(THIS_FILE, + "Ignoring STUN resolution failure (by setting)")); + //pjsua_var.stun_status = PJ_SUCCESS; + return PJ_SUCCESS; } return pjsua_var.stun_status; @@ -1887,202 +1886,202 @@ PJ_DEF(pj_status_t) pjsua_destroy2(unsigned flags) int i; /* Must be signed */ if (pjsua_var.endpt) { - PJ_LOG(4,(THIS_FILE, "Shutting down, flags=%d...", flags)); + PJ_LOG(4,(THIS_FILE, "Shutting down, flags=%d...", flags)); } if (pjsua_var.state > PJSUA_STATE_NULL && - pjsua_var.state < PJSUA_STATE_CLOSING) + pjsua_var.state < PJSUA_STATE_CLOSING) { - pjsua_set_state(PJSUA_STATE_CLOSING); + pjsua_set_state(PJSUA_STATE_CLOSING); } /* Signal threads to quit: */ pjsua_stop_worker_threads(); if (pjsua_var.endpt) { - unsigned max_wait; - - pj_log_push_indent(); - - /* Terminate all calls. */ - if ((flags & PJSUA_DESTROY_NO_TX_MSG) == 0) { - pjsua_call_hangup_all(); - } - - /* Deinit media channel of all calls (see #1717) */ - for (i=0; i<(int)pjsua_var.ua_cfg.max_calls; ++i) { - /* TODO: check if we're not allowed to send to network in the - * "flags", and if so do not do TURN allocation... - */ - pjsua_media_channel_deinit(i); - } - - /* Set all accounts to offline */ - for (i=0; i<(int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) { - if (!pjsua_var.acc[i].valid) - continue; - pjsua_var.acc[i].online_status = PJ_FALSE; - pj_bzero(&pjsua_var.acc[i].rpid, sizeof(pjrpid_element)); - } - - /* Terminate all presence subscriptions. */ - pjsua_pres_shutdown(flags); - - /* Wait for sometime until all publish client sessions are done - * (ticket #364) - */ - /* First stage, get the maximum wait time */ - max_wait = 100; - for (i=0; i<(int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) { - if (!pjsua_var.acc[i].valid) - continue; - if (pjsua_var.acc[i].cfg.unpublish_max_wait_time_msec > max_wait) - max_wait = pjsua_var.acc[i].cfg.unpublish_max_wait_time_msec; - } - - /* No waiting if RX is disabled */ - if (flags & PJSUA_DESTROY_NO_RX_MSG) { - max_wait = 0; - } - - /* Second stage, wait for unpublications to complete */ - for (i=0; i<(int)(max_wait/50); ++i) { - unsigned j; - for (j=0; j max_wait) + max_wait = pjsua_var.acc[i].cfg.unpublish_max_wait_time_msec; + } + + /* No waiting if RX is disabled */ + if (flags & PJSUA_DESTROY_NO_RX_MSG) { + max_wait = 0; + } + + /* Second stage, wait for unpublications to complete */ + for (i=0; i<(int)(max_wait/50); ++i) { + unsigned j; + for (j=0; j max_wait) - max_wait = pjsua_var.acc[i].cfg.unreg_timeout; - } - - /* No waiting if RX is disabled */ - if (flags & PJSUA_DESTROY_NO_RX_MSG) { - max_wait = 0; - } - - /* Second stage, wait for unregistrations to complete */ - for (i=0; i<(int)(max_wait/50); ++i) { - unsigned j; - for (j=0; jnext; - destroy_stun_resolve(sess, PJ_TRUE); - sess = next; - } - } - - /* Close pjsua transports */ - for (i = 0; i < (int)PJ_ARRAY_SIZE(pjsua_var.tpdata); i++) { - if (pjsua_var.tpdata[i].data.ptr) { - pjsip_transport_type_e tp_type; - - tp_type = pjsua_var.tpdata[i].type & ~PJSIP_TRANSPORT_IPV6; - if ((flags & PJSUA_DESTROY_NO_TX_MSG) && - tp_type == PJSIP_TRANSPORT_UDP && - pjsua_var.ua_cfg.enable_upnp && - pjsua_var.upnp_status == PJ_SUCCESS) - { - /* If we are not supposed to send any outgoing message - * at all, avoid sending UPnP message as it may take - * a while to time out. - */ - continue; - } - - pjsua_transport_close(i, PJ_FALSE); - } - } - - /* Destroy media (to shutdown media endpoint, etc) */ - pjsua_media_subsys_destroy(flags); - - /* Must destroy endpoint first before destroying pools in - * buddies or accounts, since shutting down transaction layer - * may emit events which trigger some buddy or account callbacks - * to be called. - */ - pjsip_endpt_destroy(pjsua_var.endpt); - pjsua_var.endpt = NULL; - - /* Destroy pool in the buddy object */ - for (i=0; i<(int)PJ_ARRAY_SIZE(pjsua_var.buddy); ++i) { - if (pjsua_var.buddy[i].pool) { - pj_pool_release(pjsua_var.buddy[i].pool); - pjsua_var.buddy[i].pool = NULL; - } - } - - /* Destroy accounts */ - for (i=0; i<(int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) { - if (pjsua_var.acc[i].pool) { - pj_pool_release(pjsua_var.acc[i].pool); - pjsua_var.acc[i].pool = NULL; - } - } + } + + /* Wait until all unregistrations are done (ticket #364) */ + /* First stage, get the maximum wait time */ + max_wait = 100; + for (i=0; i<(int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) { + if (!pjsua_var.acc[i].valid) + continue; + if (pjsua_var.acc[i].cfg.unreg_timeout > max_wait) + max_wait = pjsua_var.acc[i].cfg.unreg_timeout; + } + + /* No waiting if RX is disabled */ + if (flags & PJSUA_DESTROY_NO_RX_MSG) { + max_wait = 0; + } + + /* Second stage, wait for unregistrations to complete */ + for (i=0; i<(int)(max_wait/50); ++i) { + unsigned j; + for (j=0; jnext; + destroy_stun_resolve(sess, PJ_TRUE); + sess = next; + } + } + + /* Close pjsua transports */ + for (i = 0; i < (int)PJ_ARRAY_SIZE(pjsua_var.tpdata); i++) { + if (pjsua_var.tpdata[i].data.ptr) { + pjsip_transport_type_e tp_type; + + tp_type = pjsua_var.tpdata[i].type & ~PJSIP_TRANSPORT_IPV6; + if ((flags & PJSUA_DESTROY_NO_TX_MSG) && + tp_type == PJSIP_TRANSPORT_UDP && + pjsua_var.ua_cfg.enable_upnp && + pjsua_var.upnp_status == PJ_SUCCESS) + { + /* If we are not supposed to send any outgoing message + * at all, avoid sending UPnP message as it may take + * a while to time out. + */ + continue; + } + + pjsua_transport_close(i, PJ_FALSE); + } + } + + /* Destroy media (to shutdown media endpoint, etc) */ + pjsua_media_subsys_destroy(flags); + + /* Must destroy endpoint first before destroying pools in + * buddies or accounts, since shutting down transaction layer + * may emit events which trigger some buddy or account callbacks + * to be called. + */ + pjsip_endpt_destroy(pjsua_var.endpt); + pjsua_var.endpt = NULL; + + /* Destroy pool in the buddy object */ + for (i=0; i<(int)PJ_ARRAY_SIZE(pjsua_var.buddy); ++i) { + if (pjsua_var.buddy[i].pool) { + pj_pool_release(pjsua_var.buddy[i].pool); + pjsua_var.buddy[i].pool = NULL; + } + } + + /* Destroy accounts */ + for (i=0; i<(int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) { + if (pjsua_var.acc[i].pool) { + pj_pool_release(pjsua_var.acc[i].pool); + pjsua_var.acc[i].pool = NULL; + } + } } #if defined(PJNATH_HAS_UPNP) && (PJNATH_HAS_UPNP != 0) @@ -2094,8 +2093,8 @@ PJ_DEF(pj_status_t) pjsua_destroy2(unsigned flags) /* Destroy mutex */ if (pjsua_var.mutex) { - pj_mutex_destroy(pjsua_var.mutex); - pjsua_var.mutex = NULL; + pj_mutex_destroy(pjsua_var.mutex); + pjsua_var.mutex = NULL; } if (pjsua_var.timer_mutex) { @@ -2105,28 +2104,28 @@ PJ_DEF(pj_status_t) pjsua_destroy2(unsigned flags) /* Destroy pools and pool factory. */ if (pjsua_var.timer_pool) { - pj_pool_release(pjsua_var.timer_pool); - pjsua_var.timer_pool = NULL; + pj_pool_release(pjsua_var.timer_pool); + pjsua_var.timer_pool = NULL; } if (pjsua_var.pool) { - pj_pool_release(pjsua_var.pool); - pjsua_var.pool = NULL; - pj_caching_pool_destroy(&pjsua_var.cp); + pj_pool_release(pjsua_var.pool); + pjsua_var.pool = NULL; + pj_caching_pool_destroy(&pjsua_var.cp); - pjsua_set_state(PJSUA_STATE_NULL); + pjsua_set_state(PJSUA_STATE_NULL); - PJ_LOG(4,(THIS_FILE, "PJSUA destroyed...")); + PJ_LOG(4,(THIS_FILE, "PJSUA destroyed...")); - /* End logging */ - if (pjsua_var.log_file) { - pj_file_close(pjsua_var.log_file); - pjsua_var.log_file = NULL; - } + /* End logging */ + if (pjsua_var.log_file) { + pj_file_close(pjsua_var.log_file); + pjsua_var.log_file = NULL; + } - pj_log_pop_indent(); + pj_log_pop_indent(); - /* Shutdown PJLIB */ - pj_shutdown(); + /* Shutdown PJLIB */ + pj_shutdown(); } /* Clear pjsua_var */ @@ -2150,7 +2149,7 @@ void pjsua_set_state(pjsua_state new_state) pjsua_var.state = new_state; PJ_LOG(4,(THIS_FILE, "PJSUA state changed: %s --> %s", - state_name[old_state], state_name[new_state])); + state_name[old_state], state_name[new_state])); } /* Get state */ @@ -2170,7 +2169,7 @@ PJ_DEF(pj_status_t) pjsua_destroy(void) * is done, so that the library can do additional checking set up * additional * - * @return PJ_SUCCESS on success, or the appropriate error code. + * @return PJ_SUCCESS on success, or the appropriate error code. */ PJ_DEF(pj_status_t) pjsua_start(void) { @@ -2181,15 +2180,15 @@ PJ_DEF(pj_status_t) pjsua_start(void) status = pjsua_call_subsys_start(); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; status = pjsua_media_subsys_start(); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; status = pjsua_pres_start(); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; pjsua_set_state(PJSUA_STATE_RUNNING); @@ -2222,7 +2221,7 @@ PJ_DEF(int) pjsua_handle_events(unsigned msec_timeout) status = pjsip_endpt_handle_events2(pjsua_var.endpt, &tv, &count); if (status != PJ_SUCCESS) - return -status; + return -status; return count; @@ -2234,11 +2233,11 @@ PJ_DEF(int) pjsua_handle_events(unsigned msec_timeout) * Create memory pool. */ PJ_DEF(pj_pool_t*) pjsua_pool_create( const char *name, pj_size_t init_size, - pj_size_t increment) + pj_size_t increment) { /* Pool factory is thread safe, no need to lock */ return pj_pool_create(&pjsua_var.cp.factory, name, init_size, increment, - NULL); + NULL); } @@ -2281,25 +2280,25 @@ static const char *addr_string(const pj_sockaddr_t *addr) static char str[128]; str[0] = '\0'; pj_inet_ntop(((const pj_sockaddr*)addr)->addr.sa_family, - pj_sockaddr_get_addr(addr), - str, sizeof(str)); + pj_sockaddr_get_addr(addr), + str, sizeof(str)); return str; } void pjsua_acc_on_tp_state_changed(pjsip_transport *tp, - pjsip_transport_state state, - const pjsip_transport_state_info *info); + pjsip_transport_state state, + const pjsip_transport_state_info *info); /* Callback to receive transport state notifications */ static void on_tp_state_callback(pjsip_transport *tp, - pjsip_transport_state state, - const pjsip_transport_state_info *info) + pjsip_transport_state state, + const pjsip_transport_state_info *info) { if (pjsua_var.ua_cfg.cb.on_transport_state) { - (*pjsua_var.ua_cfg.cb.on_transport_state)(tp, state, info); + (*pjsua_var.ua_cfg.cb.on_transport_state)(tp, state, info); } if (pjsua_var.old_tp_cb) { - (*pjsua_var.old_tp_cb)(tp, state, info); + (*pjsua_var.old_tp_cb)(tp, state, info); } pjsua_acc_on_tp_state_changed(tp, state, info); } @@ -2314,8 +2313,8 @@ static void set_tp_state_cb() tpcb = pjsip_tpmgr_get_state_cb(tpmgr); if (tpcb != &on_tp_state_callback) { - pjsua_var.old_tp_cb = tpcb; - pjsip_tpmgr_set_state_cb(tpmgr, &on_tp_state_callback); + pjsua_var.old_tp_cb = tpcb; + pjsip_tpmgr_set_state_cb(tpmgr, &on_tp_state_callback); } } @@ -2324,9 +2323,9 @@ static void set_tp_state_cb() * address via STUN, depending on config). */ static pj_status_t create_sip_udp_sock(int af, - const pjsua_transport_config *cfg, - pj_sock_t *p_sock, - pj_sockaddr *p_pub_addr) + const pjsua_transport_config *cfg, + pj_sock_t *p_sock, + pj_sockaddr *p_pub_addr) { char stun_ip_addr[PJ_INET6_ADDRSTRLEN]; unsigned port = cfg->port; @@ -2338,68 +2337,68 @@ static pj_status_t create_sip_udp_sock(int af, /* Make sure STUN server resolution has completed */ status = resolve_stun_server(PJ_TRUE, PJ_TRUE, 0); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error resolving STUN server", status); - return status; + pjsua_perror(THIS_FILE, "Error resolving STUN server", status); + return status; } /* Initialize bound address */ if (cfg->bound_addr.slen) { - status = pj_sockaddr_init(af, &bind_addr, &cfg->bound_addr, - (pj_uint16_t)port); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Unable to resolve transport bound address", - status); - return status; - } + status = pj_sockaddr_init(af, &bind_addr, &cfg->bound_addr, + (pj_uint16_t)port); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, + "Unable to resolve transport bound address", + status); + return status; + } } else { - pj_sockaddr_init(af, &bind_addr, NULL, (pj_uint16_t)port); + pj_sockaddr_init(af, &bind_addr, NULL, (pj_uint16_t)port); } /* Create socket */ status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &sock); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "socket() error", status); - return status; + pjsua_perror(THIS_FILE, "socket() error", status); + return status; } /* Apply QoS, if specified */ status = pj_sock_apply_qos2(sock, cfg->qos_type, - &cfg->qos_params, - 2, THIS_FILE, "SIP UDP socket"); + &cfg->qos_params, + 2, THIS_FILE, "SIP UDP socket"); /* Apply sockopt, if specified */ if (cfg->sockopt_params.cnt) - status = pj_sock_setsockopt_params(sock, &cfg->sockopt_params); + status = pj_sock_setsockopt_params(sock, &cfg->sockopt_params); /* Bind socket */ status = pj_sock_bind(sock, &bind_addr, pj_sockaddr_get_len(&bind_addr)); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "bind() error", status); - pj_sock_close(sock); - return status; + pjsua_perror(THIS_FILE, "bind() error", status); + pj_sock_close(sock); + return status; } /* If port is zero, get the bound port */ if (port == 0) { - pj_sockaddr bound_addr; - int namelen = sizeof(bound_addr); - status = pj_sock_getsockname(sock, &bound_addr, &namelen); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "getsockname() error", status); - pj_sock_close(sock); - return status; - } + pj_sockaddr bound_addr; + int namelen = sizeof(bound_addr); + status = pj_sock_getsockname(sock, &bound_addr, &namelen); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "getsockname() error", status); + pj_sock_close(sock); + return status; + } - port = pj_sockaddr_get_port(&bound_addr); + port = pj_sockaddr_get_port(&bound_addr); } if (pjsua_var.stun_srv.addr.sa_family != 0) { - pj_sockaddr_print(&pjsua_var.stun_srv, - stun_ip_addr, sizeof(stun_ip_addr), 0); - stun_srv = pj_str(stun_ip_addr); + pj_sockaddr_print(&pjsua_var.stun_srv, + stun_ip_addr, sizeof(stun_ip_addr), 0); + stun_srv = pj_str(stun_ip_addr); } else { - stun_srv.slen = 0; + stun_srv.slen = 0; } /* Get the published address, either by STUN or by resolving @@ -2407,86 +2406,86 @@ static pj_status_t create_sip_udp_sock(int af, */ status = PJ_SUCCESS; if (pj_sockaddr_has_addr(p_pub_addr)) { - /* - * Public address is already specified, no need to resolve the - * address, only set the port. - */ - if (pj_sockaddr_get_port(p_pub_addr) == 0) - pj_sockaddr_set_port(p_pub_addr, (pj_uint16_t)port); + /* + * Public address is already specified, no need to resolve the + * address, only set the port. + */ + if (pj_sockaddr_get_port(p_pub_addr) == 0) + pj_sockaddr_set_port(p_pub_addr, (pj_uint16_t)port); } else if (stun_srv.slen && (af == pj_AF_INET() || pjsua_var.ua_cfg.stun_try_ipv6)) { - pjstun_setting stun_opt; - - /* - * STUN is specified, resolve the address with STUN. - * Currently, this is only to get IPv4 mapped address - * (does IPv6 still need a mapped address?). - */ - pj_bzero(&stun_opt, sizeof(stun_opt)); - stun_opt.use_stun2 = pjsua_var.ua_cfg.stun_map_use_stun2; - stun_opt.af = pjsua_var.stun_srv.addr.sa_family; - stun_opt.srv1 = stun_opt.srv2 = stun_srv; - stun_opt.port1 = stun_opt.port2 = - pj_sockaddr_get_port(&pjsua_var.stun_srv); - status = pjstun_get_mapped_addr2(&pjsua_var.cp.factory, &stun_opt, - 1, &sock, &p_pub_addr->ipv4); - if (status != PJ_SUCCESS) { - /* Failed getting mapped address via STUN */ - pjsua_perror(THIS_FILE, "Error contacting STUN server", status); - - /* Return error if configured to not ignore STUN failure */ - if (!pjsua_var.ua_cfg.stun_ignore_failure) { - pj_sock_close(sock); - return status; - } - } + pjstun_setting stun_opt; + + /* + * STUN is specified, resolve the address with STUN. + * Currently, this is only to get IPv4 mapped address + * (does IPv6 still need a mapped address?). + */ + pj_bzero(&stun_opt, sizeof(stun_opt)); + stun_opt.use_stun2 = pjsua_var.ua_cfg.stun_map_use_stun2; + stun_opt.af = pjsua_var.stun_srv.addr.sa_family; + stun_opt.srv1 = stun_opt.srv2 = stun_srv; + stun_opt.port1 = stun_opt.port2 = + pj_sockaddr_get_port(&pjsua_var.stun_srv); + status = pjstun_get_mapped_addr2(&pjsua_var.cp.factory, &stun_opt, + 1, &sock, &p_pub_addr->ipv4); + if (status != PJ_SUCCESS) { + /* Failed getting mapped address via STUN */ + pjsua_perror(THIS_FILE, "Error contacting STUN server", status); + + /* Return error if configured to not ignore STUN failure */ + if (!pjsua_var.ua_cfg.stun_ignore_failure) { + pj_sock_close(sock); + return status; + } + } } #if defined(PJNATH_HAS_UPNP) && (PJNATH_HAS_UPNP != 0) else if (pjsua_var.ua_cfg.enable_upnp && - pjsua_var.upnp_status == PJ_SUCCESS) + pjsua_var.upnp_status == PJ_SUCCESS) { - status = pj_upnp_add_port_mapping(1, &sock, NULL, p_pub_addr); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error adding UPnP port mapping", status); - } + status = pj_upnp_add_port_mapping(1, &sock, NULL, p_pub_addr); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error adding UPnP port mapping", status); + } } #endif if (!pj_sockaddr_has_addr(p_pub_addr)) { - pj_bzero(p_pub_addr, sizeof(pj_sockaddr)); + pj_bzero(p_pub_addr, sizeof(pj_sockaddr)); - if (pj_sockaddr_has_addr(&bind_addr)) { - pj_sockaddr_copy_addr(p_pub_addr, &bind_addr); - } else { - status = pj_gethostip(af, p_pub_addr); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to get local host IP", status); - pj_sock_close(sock); - return status; - } - } + if (pj_sockaddr_has_addr(&bind_addr)) { + pj_sockaddr_copy_addr(p_pub_addr, &bind_addr); + } else { + status = pj_gethostip(af, p_pub_addr); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to get local host IP", status); + pj_sock_close(sock); + return status; + } + } - p_pub_addr->addr.sa_family = (pj_uint16_t)af; - pj_sockaddr_set_port(p_pub_addr, (pj_uint16_t)port); + p_pub_addr->addr.sa_family = (pj_uint16_t)af; + pj_sockaddr_set_port(p_pub_addr, (pj_uint16_t)port); - if (stun_srv.slen && af != pj_AF_INET()) { - /* STUN is specified, but it is not IPv4, just print warning */ - PJ_PERROR(2, (THIS_FILE, PJ_EAFNOTSUP, - "Cannot use STUN for SIP UDP socket %s:%d", - addr_string(p_pub_addr), - (int)pj_sockaddr_get_port(p_pub_addr))); - } + if (stun_srv.slen && af != pj_AF_INET()) { + /* STUN is specified, but it is not IPv4, just print warning */ + PJ_PERROR(2, (THIS_FILE, PJ_EAFNOTSUP, + "Cannot use STUN for SIP UDP socket %s:%d", + addr_string(p_pub_addr), + (int)pj_sockaddr_get_port(p_pub_addr))); + } } *p_sock = sock; PJ_LOG(4,(THIS_FILE, "SIP UDP socket reachable at %s:%d", - addr_string(p_pub_addr), - (int)pj_sockaddr_get_port(p_pub_addr))); + addr_string(p_pub_addr), + (int)pj_sockaddr_get_port(p_pub_addr))); return PJ_SUCCESS; } @@ -2496,8 +2495,8 @@ static pj_status_t create_sip_udp_sock(int af, * Create SIP transport. */ PJ_DEF(pj_status_t) pjsua_transport_create( pjsip_transport_type_e type, - const pjsua_transport_config *cfg, - pjsua_transport_id *p_id) + const pjsua_transport_config *cfg, + pjsua_transport_id *p_id) { pjsip_transport *tp; unsigned id; @@ -2507,202 +2506,202 @@ PJ_DEF(pj_status_t) pjsua_transport_create( pjsip_transport_type_e type, /* Find empty transport slot */ for (id=0; id < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++id) { - if (pjsua_var.tpdata[id].data.ptr == NULL) - break; + if (pjsua_var.tpdata[id].data.ptr == NULL) + break; } if (id == PJ_ARRAY_SIZE(pjsua_var.tpdata)) { - status = PJ_ETOOMANY; - pjsua_perror(THIS_FILE, "Error creating transport", status); - goto on_return; + status = PJ_ETOOMANY; + pjsua_perror(THIS_FILE, "Error creating transport", status); + goto on_return; } /* Create the transport */ if (type==PJSIP_TRANSPORT_UDP || type==PJSIP_TRANSPORT_UDP6) { - /* - * Create UDP transport (IPv4 or IPv6). - */ - pjsua_transport_config config; - char hostbuf[PJ_INET6_ADDRSTRLEN]; - pj_sock_t sock = PJ_INVALID_SOCKET; - pj_sockaddr pub_addr; - pjsip_host_port addr_name; - - /* Supply default config if it's not specified */ - if (cfg == NULL) { - pjsua_transport_config_default(&config); - cfg = &config; - } - - /* Initialize the public address from the config, if any */ - pj_sockaddr_init(pjsip_transport_type_get_af(type), &pub_addr, - NULL, (pj_uint16_t)cfg->port); - if (cfg->public_addr.slen) { - status = pj_sockaddr_set_str_addr(pjsip_transport_type_get_af(type), - &pub_addr, &cfg->public_addr); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Unable to resolve transport public address", - status); - goto on_return; - } - } - - /* Create the socket and possibly resolve the address with STUN - * (only when public address is not specified). - */ - status = create_sip_udp_sock(pjsip_transport_type_get_af(type), - cfg, &sock, &pub_addr); - if (status != PJ_SUCCESS) - goto on_return; - - pj_ansi_strcpy(hostbuf, addr_string(&pub_addr)); - addr_name.host = pj_str(hostbuf); - addr_name.port = pj_sockaddr_get_port(&pub_addr); - - /* Create UDP transport */ - status = pjsip_udp_transport_attach2(pjsua_var.endpt, type, sock, - &addr_name, 1, &tp); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating SIP UDP transport", - status); - pj_sock_close(sock); - goto on_return; - } - - - /* Save the transport */ - pjsua_var.tpdata[id].type = type; - pjsua_var.tpdata[id].local_name = tp->local_name; - pjsua_var.tpdata[id].data.tp = tp; - pj_sockaddr_cp(&pjsua_var.tpdata[id].pub_addr, &pub_addr); - if (cfg->bound_addr.slen) - pjsua_var.tpdata[id].has_bound_addr = PJ_TRUE; + /* + * Create UDP transport (IPv4 or IPv6). + */ + pjsua_transport_config config; + char hostbuf[PJ_INET6_ADDRSTRLEN]; + pj_sock_t sock = PJ_INVALID_SOCKET; + pj_sockaddr pub_addr; + pjsip_host_port addr_name; + + /* Supply default config if it's not specified */ + if (cfg == NULL) { + pjsua_transport_config_default(&config); + cfg = &config; + } + + /* Initialize the public address from the config, if any */ + pj_sockaddr_init(pjsip_transport_type_get_af(type), &pub_addr, + NULL, (pj_uint16_t)cfg->port); + if (cfg->public_addr.slen) { + status = pj_sockaddr_set_str_addr(pjsip_transport_type_get_af(type), + &pub_addr, &cfg->public_addr); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, + "Unable to resolve transport public address", + status); + goto on_return; + } + } + + /* Create the socket and possibly resolve the address with STUN + * (only when public address is not specified). + */ + status = create_sip_udp_sock(pjsip_transport_type_get_af(type), + cfg, &sock, &pub_addr); + if (status != PJ_SUCCESS) + goto on_return; + + pj_ansi_strcpy(hostbuf, addr_string(&pub_addr)); + addr_name.host = pj_str(hostbuf); + addr_name.port = pj_sockaddr_get_port(&pub_addr); + + /* Create UDP transport */ + status = pjsip_udp_transport_attach2(pjsua_var.endpt, type, sock, + &addr_name, 1, &tp); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error creating SIP UDP transport", + status); + pj_sock_close(sock); + goto on_return; + } + + + /* Save the transport */ + pjsua_var.tpdata[id].type = type; + pjsua_var.tpdata[id].local_name = tp->local_name; + pjsua_var.tpdata[id].data.tp = tp; + pj_sockaddr_cp(&pjsua_var.tpdata[id].pub_addr, &pub_addr); + if (cfg->bound_addr.slen) + pjsua_var.tpdata[id].has_bound_addr = PJ_TRUE; #if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0 } else if (type == PJSIP_TRANSPORT_TCP || type == PJSIP_TRANSPORT_TCP6) { - /* - * Create TCP transport. - */ - pjsua_transport_config config; - pjsip_tpfactory *tcp; - pjsip_tcp_transport_cfg tcp_cfg; - int af; - - af = (type==PJSIP_TRANSPORT_TCP6) ? pj_AF_INET6() : pj_AF_INET(); - pjsip_tcp_transport_cfg_default(&tcp_cfg, af); - - /* Supply default config if it's not specified */ - if (cfg == NULL) { - pjsua_transport_config_default(&config); - cfg = &config; - } - - /* Configure bind address */ - if (cfg->port) - pj_sockaddr_set_port(&tcp_cfg.bind_addr, (pj_uint16_t)cfg->port); - - if (cfg->bound_addr.slen) { - status = pj_sockaddr_set_str_addr(tcp_cfg.af, - &tcp_cfg.bind_addr, - &cfg->bound_addr); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Unable to resolve transport bound address", - status); - goto on_return; - } - } - - /* Set published name */ - if (cfg->public_addr.slen) - tcp_cfg.addr_name.host = cfg->public_addr; - - /* Copy the QoS settings */ - tcp_cfg.qos_type = cfg->qos_type; - pj_memcpy(&tcp_cfg.qos_params, &cfg->qos_params, - sizeof(cfg->qos_params)); - - /* Copy the sockopt */ - pj_memcpy(&tcp_cfg.sockopt_params, &cfg->sockopt_params, - sizeof(tcp_cfg.sockopt_params)); - - /* Create the TCP transport */ - status = pjsip_tcp_transport_start3(pjsua_var.endpt, &tcp_cfg, &tcp); - - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating SIP TCP listener", - status); - goto on_return; - } - - /* Save the transport */ - pjsua_var.tpdata[id].type = type; - pjsua_var.tpdata[id].local_name = tcp->addr_name; - pjsua_var.tpdata[id].data.factory = tcp; - -#endif /* PJ_HAS_TCP */ + /* + * Create TCP transport. + */ + pjsua_transport_config config; + pjsip_tpfactory *tcp; + pjsip_tcp_transport_cfg tcp_cfg; + int af; + + af = (type==PJSIP_TRANSPORT_TCP6) ? pj_AF_INET6() : pj_AF_INET(); + pjsip_tcp_transport_cfg_default(&tcp_cfg, af); + + /* Supply default config if it's not specified */ + if (cfg == NULL) { + pjsua_transport_config_default(&config); + cfg = &config; + } + + /* Configure bind address */ + if (cfg->port) + pj_sockaddr_set_port(&tcp_cfg.bind_addr, (pj_uint16_t)cfg->port); + + if (cfg->bound_addr.slen) { + status = pj_sockaddr_set_str_addr(tcp_cfg.af, + &tcp_cfg.bind_addr, + &cfg->bound_addr); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, + "Unable to resolve transport bound address", + status); + goto on_return; + } + } + + /* Set published name */ + if (cfg->public_addr.slen) + tcp_cfg.addr_name.host = cfg->public_addr; + + /* Copy the QoS settings */ + tcp_cfg.qos_type = cfg->qos_type; + pj_memcpy(&tcp_cfg.qos_params, &cfg->qos_params, + sizeof(cfg->qos_params)); + + /* Copy the sockopt */ + pj_memcpy(&tcp_cfg.sockopt_params, &cfg->sockopt_params, + sizeof(tcp_cfg.sockopt_params)); + + /* Create the TCP transport */ + status = pjsip_tcp_transport_start3(pjsua_var.endpt, &tcp_cfg, &tcp); + + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error creating SIP TCP listener", + status); + goto on_return; + } + + /* Save the transport */ + pjsua_var.tpdata[id].type = type; + pjsua_var.tpdata[id].local_name = tcp->addr_name; + pjsua_var.tpdata[id].data.factory = tcp; + +#endif /* PJ_HAS_TCP */ #if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0 } else if (type == PJSIP_TRANSPORT_TLS || type == PJSIP_TRANSPORT_TLS6) { - /* - * Create TLS transport. - */ - pjsua_transport_config config; - pjsip_host_port a_name; - pjsip_tpfactory *tls; - pj_sockaddr local_addr; - int af; - - /* Supply default config if it's not specified */ - if (cfg == NULL) { - pjsua_transport_config_default(&config); - config.port = 5061; - cfg = &config; - } - - /* Init local address */ - af = (type==PJSIP_TRANSPORT_TLS) ? pj_AF_INET() : pj_AF_INET6(); - pj_sockaddr_init(af, &local_addr, NULL, 0); - - if (cfg->port) - pj_sockaddr_set_port(&local_addr, (pj_uint16_t)cfg->port); - - if (cfg->bound_addr.slen) { - status = pj_sockaddr_set_str_addr(af, &local_addr, - &cfg->bound_addr); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Unable to resolve transport bound address", - status); - goto on_return; - } - } - - /* Init published name */ - pj_bzero(&a_name, sizeof(pjsip_host_port)); - if (cfg->public_addr.slen) - a_name.host = cfg->public_addr; - - status = pjsip_tls_transport_start2(pjsua_var.endpt, &cfg->tls_setting, - &local_addr, &a_name, 1, &tls); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating SIP TLS listener", - status); - goto on_return; - } - - /* Save the transport */ - pjsua_var.tpdata[id].type = type; - pjsua_var.tpdata[id].local_name = tls->addr_name; - pjsua_var.tpdata[id].data.factory = tls; + /* + * Create TLS transport. + */ + pjsua_transport_config config; + pjsip_host_port a_name; + pjsip_tpfactory *tls; + pj_sockaddr local_addr; + int af; + + /* Supply default config if it's not specified */ + if (cfg == NULL) { + pjsua_transport_config_default(&config); + config.port = 5061; + cfg = &config; + } + + /* Init local address */ + af = (type==PJSIP_TRANSPORT_TLS) ? pj_AF_INET() : pj_AF_INET6(); + pj_sockaddr_init(af, &local_addr, NULL, 0); + + if (cfg->port) + pj_sockaddr_set_port(&local_addr, (pj_uint16_t)cfg->port); + + if (cfg->bound_addr.slen) { + status = pj_sockaddr_set_str_addr(af, &local_addr, + &cfg->bound_addr); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, + "Unable to resolve transport bound address", + status); + goto on_return; + } + } + + /* Init published name */ + pj_bzero(&a_name, sizeof(pjsip_host_port)); + if (cfg->public_addr.slen) + a_name.host = cfg->public_addr; + + status = pjsip_tls_transport_start2(pjsua_var.endpt, &cfg->tls_setting, + &local_addr, &a_name, 1, &tls); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error creating SIP TLS listener", + status); + goto on_return; + } + + /* Save the transport */ + pjsua_var.tpdata[id].type = type; + pjsua_var.tpdata[id].local_name = tls->addr_name; + pjsua_var.tpdata[id].data.factory = tls; #endif } else { - status = PJSIP_EUNSUPTRANSPORT; - pjsua_perror(THIS_FILE, "Error creating transport", status); - goto on_return; + status = PJSIP_EUNSUPTRANSPORT; + pjsua_perror(THIS_FILE, "Error creating transport", status); + goto on_return; } /* Set transport state callback */ @@ -2725,7 +2724,7 @@ PJ_DEF(pj_status_t) pjsua_transport_create( pjsip_transport_type_e type, * Register transport that has been created by application. */ PJ_DEF(pj_status_t) pjsua_transport_register( pjsip_transport *tp, - pjsua_transport_id *p_id) + pjsua_transport_id *p_id) { unsigned id; @@ -2733,14 +2732,14 @@ PJ_DEF(pj_status_t) pjsua_transport_register( pjsip_transport *tp, /* Find empty transport slot */ for (id=0; id < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++id) { - if (pjsua_var.tpdata[id].data.ptr == NULL) - break; + if (pjsua_var.tpdata[id].data.ptr == NULL) + break; } if (id == PJ_ARRAY_SIZE(pjsua_var.tpdata)) { - pjsua_perror(THIS_FILE, "Error creating transport", PJ_ETOOMANY); - PJSUA_UNLOCK(); - return PJ_ETOOMANY; + pjsua_perror(THIS_FILE, "Error creating transport", PJ_ETOOMANY); + PJSUA_UNLOCK(); + return PJ_ETOOMANY; } /* Save the transport */ @@ -2764,7 +2763,7 @@ PJ_DEF(pj_status_t) pjsua_transport_register( pjsip_transport *tp, * Register transport factory that has been created by application. */ PJ_DEF(pj_status_t) pjsua_tpfactory_register( pjsip_tpfactory *tf, - pjsua_transport_id *p_id) + pjsua_transport_id *p_id) { unsigned id; @@ -2772,14 +2771,14 @@ PJ_DEF(pj_status_t) pjsua_tpfactory_register( pjsip_tpfactory *tf, /* Find empty transport slot */ for (id=0; id < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++id) { - if (pjsua_var.tpdata[id].data.ptr == NULL) - break; + if (pjsua_var.tpdata[id].data.ptr == NULL) + break; } if (id == PJ_ARRAY_SIZE(pjsua_var.tpdata)) { - pjsua_perror(THIS_FILE, "Error creating transport", PJ_ETOOMANY); - PJSUA_UNLOCK(); - return PJ_ETOOMANY; + pjsua_perror(THIS_FILE, "Error creating transport", PJ_ETOOMANY); + PJSUA_UNLOCK(); + return PJ_ETOOMANY; } /* Save the transport */ @@ -2803,19 +2802,19 @@ PJ_DEF(pj_status_t) pjsua_tpfactory_register( pjsip_tpfactory *tf, * Enumerate all transports currently created in the system. */ PJ_DEF(pj_status_t) pjsua_enum_transports( pjsua_transport_id id[], - unsigned *p_count ) + unsigned *p_count ) { unsigned i, count; PJSUA_LOCK(); for (i=0, count=0; i=0 && id<(int)PJ_ARRAY_SIZE(pjsua_var.tpdata), - PJ_EINVAL); + PJ_EINVAL); /* Make sure that transport exists */ PJ_ASSERT_RETURN(pjsua_var.tpdata[id].data.ptr != NULL, PJ_EINVAL); @@ -2848,51 +2847,51 @@ PJ_DEF(pj_status_t) pjsua_transport_get_info( pjsua_transport_id id, if ((t->type & ~PJSIP_TRANSPORT_IPV6) == PJSIP_TRANSPORT_UDP) { - pjsip_transport *tp = t->data.tp; + pjsip_transport *tp = t->data.tp; - if (tp == NULL) { - PJSUA_UNLOCK(); - return PJ_EINVALIDOP; - } + if (tp == NULL) { + PJSUA_UNLOCK(); + return PJ_EINVALIDOP; + } - info->id = id; - info->type = (pjsip_transport_type_e) tp->key.type; - info->type_name = pj_str(tp->type_name); - info->info = pj_str(tp->info); - info->flag = tp->flag; - info->addr_len = tp->addr_len; - info->local_addr = tp->local_addr; - info->local_name = tp->local_name; - info->usage_count = pj_atomic_get(tp->ref_cnt); - - status = PJ_SUCCESS; + info->id = id; + info->type = (pjsip_transport_type_e) tp->key.type; + info->type_name = pj_str(tp->type_name); + info->info = pj_str(tp->info); + info->flag = tp->flag; + info->addr_len = tp->addr_len; + info->local_addr = tp->local_addr; + info->local_name = tp->local_name; + info->usage_count = pj_atomic_get(tp->ref_cnt); + + status = PJ_SUCCESS; } else if ((t->type & ~PJSIP_TRANSPORT_IPV6) == PJSIP_TRANSPORT_TCP || - (t->type & ~PJSIP_TRANSPORT_IPV6) == PJSIP_TRANSPORT_TLS) + (t->type & ~PJSIP_TRANSPORT_IPV6) == PJSIP_TRANSPORT_TLS) { - pjsip_tpfactory *factory = t->data.factory; + pjsip_tpfactory *factory = t->data.factory; - if (factory == NULL) { - PJSUA_UNLOCK(); - return PJ_EINVALIDOP; - } + if (factory == NULL) { + PJSUA_UNLOCK(); + return PJ_EINVALIDOP; + } - info->id = id; - info->type = t->type; - info->type_name = pj_str(factory->type_name); - info->info = pj_str(factory->info); - info->flag = factory->flag; - info->addr_len = sizeof(factory->local_addr); - info->local_addr = factory->local_addr; - info->local_name = factory->addr_name; - info->usage_count = 0; - - status = PJ_SUCCESS; + info->id = id; + info->type = t->type; + info->type_name = pj_str(factory->type_name); + info->info = pj_str(factory->info); + info->flag = factory->flag; + info->addr_len = sizeof(factory->local_addr); + info->local_addr = factory->local_addr; + info->local_name = factory->addr_name; + info->usage_count = 0; + + status = PJ_SUCCESS; } else { - pj_assert(!"Unsupported transport"); - status = PJ_EINVALIDOP; + pj_assert(!"Unsupported transport"); + status = PJ_EINVALIDOP; } @@ -2906,11 +2905,11 @@ PJ_DEF(pj_status_t) pjsua_transport_get_info( pjsua_transport_id id, * Disable a transport or re-enable it. */ PJ_DEF(pj_status_t) pjsua_transport_set_enable( pjsua_transport_id id, - pj_bool_t enabled) + pj_bool_t enabled) { /* Make sure id is in range. */ PJ_ASSERT_RETURN(id>=0 && id<(int)PJ_ARRAY_SIZE(pjsua_var.tpdata), - PJ_EINVAL); + PJ_EINVAL); /* Make sure that transport exists */ PJ_ASSERT_RETURN(pjsua_var.tpdata[id].data.ptr != NULL, PJ_EINVAL); @@ -2928,14 +2927,14 @@ PJ_DEF(pj_status_t) pjsua_transport_set_enable( pjsua_transport_id id, * Close the transport. */ PJ_DEF(pj_status_t) pjsua_transport_close( pjsua_transport_id id, - pj_bool_t force ) + pj_bool_t force ) { pj_status_t status; pjsip_transport_type_e tp_type; /* Make sure id is in range. */ PJ_ASSERT_RETURN(id>=0 && id<(int)PJ_ARRAY_SIZE(pjsua_var.tpdata), - PJ_EINVAL); + PJ_EINVAL); /* Make sure that transport exists */ PJ_ASSERT_RETURN(pjsua_var.tpdata[id].data.ptr != NULL, PJ_EINVAL); @@ -2943,49 +2942,49 @@ PJ_DEF(pj_status_t) pjsua_transport_close( pjsua_transport_id id, tp_type = pjsua_var.tpdata[id].type & ~PJSIP_TRANSPORT_IPV6; if (force) { - /* Forcefully closing transport is deprecated, since any pending - * transactions that are using the transport may not terminate - * properly and can even crash. - */ - PJ_LOG(1, (THIS_FILE, "pjsua_transport_close(force=PJ_TRUE) is " - "deprecated.")); - - /* To minimize the effect to users, we shouldn't hard-deprecate this - * and let it continue as if force is false. - */ - // return PJ_EINVAL; + /* Forcefully closing transport is deprecated, since any pending + * transactions that are using the transport may not terminate + * properly and can even crash. + */ + PJ_LOG(1, (THIS_FILE, "pjsua_transport_close(force=PJ_TRUE) is " + "deprecated.")); + + /* To minimize the effect to users, we shouldn't hard-deprecate this + * and let it continue as if force is false. + */ + // return PJ_EINVAL; } /* If force is not specified, transports will be closed at their * convenient time. */ switch (tp_type) { - case PJSIP_TRANSPORT_UDP: + case PJSIP_TRANSPORT_UDP: #if defined(PJNATH_HAS_UPNP) && (PJNATH_HAS_UPNP != 0) - if (pjsua_var.ua_cfg.enable_upnp && - pjsua_var.upnp_status == PJ_SUCCESS) + if (pjsua_var.ua_cfg.enable_upnp && + pjsua_var.upnp_status == PJ_SUCCESS) { - status = pj_upnp_del_port_mapping( - &pjsua_var.tpdata[id].pub_addr); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error deleting pjsua_transport " - "UPnP port mapping", status); - } - } + status = pj_upnp_del_port_mapping( + &pjsua_var.tpdata[id].pub_addr); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error deleting pjsua_transport " + "UPnP port mapping", status); + } + } #endif - status = pjsip_transport_shutdown(pjsua_var.tpdata[id].data.tp); - break; - case PJSIP_TRANSPORT_TLS: - case PJSIP_TRANSPORT_TCP: - /* This will close the TCP listener, but existing TCP/TLS - * connections (if any) will still linger - */ - status = (*pjsua_var.tpdata[id].data.factory->destroy) - (pjsua_var.tpdata[id].data.factory); - break; - default: - return PJ_EINVAL; + status = pjsip_transport_shutdown(pjsua_var.tpdata[id].data.tp); + break; + case PJSIP_TRANSPORT_TLS: + case PJSIP_TRANSPORT_TCP: + /* This will close the TCP listener, but existing TCP/TLS + * connections (if any) will still linger + */ + status = (*pjsua_var.tpdata[id].data.factory->destroy) + (pjsua_var.tpdata[id].data.factory); + break; + default: + return PJ_EINVAL; } /* Cleanup pjsua data. We don't need to keep the transport @@ -2993,8 +2992,8 @@ PJ_DEF(pj_status_t) pjsua_transport_close( pjsua_transport_id id, * which decrements the transport's reference. */ if (status == PJ_SUCCESS) { - pjsua_var.tpdata[id].type = PJSIP_TRANSPORT_UNSPECIFIED; - pjsua_var.tpdata[id].data.ptr = NULL; + pjsua_var.tpdata[id].type = PJSIP_TRANSPORT_UNSPECIFIED; + pjsua_var.tpdata[id].data.ptr = NULL; } return status; @@ -3002,14 +3001,14 @@ PJ_DEF(pj_status_t) pjsua_transport_close( pjsua_transport_id id, PJ_DEF(pj_status_t) pjsua_transport_lis_start(pjsua_transport_id id, - const pjsua_transport_config *cfg) + const pjsua_transport_config *cfg) { pj_status_t status = PJ_SUCCESS; pjsip_transport_type_e tp_type; /* Make sure id is in range. */ PJ_ASSERT_RETURN(id>=0 && id<(int)PJ_ARRAY_SIZE(pjsua_var.tpdata), - PJ_EINVAL); + PJ_EINVAL); /* Make sure that transport exists */ PJ_ASSERT_RETURN(pjsua_var.tpdata[id].data.ptr != NULL, PJ_EINVAL); @@ -3017,45 +3016,45 @@ PJ_DEF(pj_status_t) pjsua_transport_lis_start(pjsua_transport_id id, tp_type = pjsua_var.tpdata[id].type & ~PJSIP_TRANSPORT_IPV6; if ((tp_type == PJSIP_TRANSPORT_TLS) || (tp_type == PJSIP_TRANSPORT_TCP)) { - pj_sockaddr bind_addr; - pjsip_host_port addr_name; - pjsip_tpfactory *factory = pjsua_var.tpdata[id].data.factory; - + pj_sockaddr bind_addr; + pjsip_host_port addr_name; + pjsip_tpfactory *factory = pjsua_var.tpdata[id].data.factory; + int af = pjsip_transport_type_get_af(factory->type); - if (cfg->port) - pj_sockaddr_set_port(&bind_addr, (pj_uint16_t)cfg->port); - - if (cfg->bound_addr.slen) { - status = pj_sockaddr_set_str_addr(af, - &bind_addr, - &cfg->bound_addr); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Unable to resolve transport bound address", - status); - return status; - } - } - - /* Set published name */ - if (cfg->public_addr.slen) - addr_name.host = cfg->public_addr; - - if (tp_type == PJSIP_TRANSPORT_TCP) { - status = pjsip_tcp_transport_lis_start(factory, &bind_addr, - &addr_name); - } + if (cfg->port) + pj_sockaddr_set_port(&bind_addr, (pj_uint16_t)cfg->port); + + if (cfg->bound_addr.slen) { + status = pj_sockaddr_set_str_addr(af, + &bind_addr, + &cfg->bound_addr); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, + "Unable to resolve transport bound address", + status); + return status; + } + } + + /* Set published name */ + if (cfg->public_addr.slen) + addr_name.host = cfg->public_addr; + + if (tp_type == PJSIP_TRANSPORT_TCP) { + status = pjsip_tcp_transport_lis_start(factory, &bind_addr, + &addr_name); + } #if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0 - else { - status = pjsip_tls_transport_lis_start(factory, &bind_addr, - &addr_name); - } -#endif + else { + status = pjsip_tls_transport_lis_start(factory, &bind_addr, + &addr_name); + } +#endif } else if (tp_type == PJSIP_TRANSPORT_UDP) { - status = PJ_SUCCESS; + status = PJ_SUCCESS; } else { - status = PJ_EINVAL; + status = PJ_EINVAL; } return status; } @@ -3066,77 +3065,77 @@ PJ_DEF(pj_status_t) pjsua_transport_lis_start(pjsua_transport_id id, * when sending requests. */ void pjsua_process_msg_data(pjsip_tx_data *tdata, - const pjsua_msg_data *msg_data) + const pjsua_msg_data *msg_data) { pj_bool_t allow_body; const pjsip_hdr *hdr; /* Always add User-Agent */ if (pjsua_var.ua_cfg.user_agent.slen && - tdata->msg->type == PJSIP_REQUEST_MSG) + tdata->msg->type == PJSIP_REQUEST_MSG) { - const pj_str_t STR_USER_AGENT = { "User-Agent", 10 }; - pjsip_hdr *h; - h = (pjsip_hdr*)pjsip_generic_string_hdr_create(tdata->pool, - &STR_USER_AGENT, - &pjsua_var.ua_cfg.user_agent); - pjsip_msg_add_hdr(tdata->msg, h); + const pj_str_t STR_USER_AGENT = { "User-Agent", 10 }; + pjsip_hdr *h; + h = (pjsip_hdr*)pjsip_generic_string_hdr_create(tdata->pool, + &STR_USER_AGENT, + &pjsua_var.ua_cfg.user_agent); + pjsip_msg_add_hdr(tdata->msg, h); } if (!msg_data) - return; + return; hdr = msg_data->hdr_list.next; while (hdr && hdr != &msg_data->hdr_list) { - pjsip_hdr *new_hdr; + pjsip_hdr *new_hdr; - new_hdr = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, hdr); - pjsip_msg_add_hdr(tdata->msg, new_hdr); + new_hdr = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, hdr); + pjsip_msg_add_hdr(tdata->msg, new_hdr); - hdr = hdr->next; + hdr = hdr->next; } allow_body = (tdata->msg->body == NULL); if (allow_body && msg_data->content_type.slen && msg_data->msg_body.slen) { - pjsip_media_type ctype; - pjsip_msg_body *body; + pjsip_media_type ctype; + pjsip_msg_body *body; - pjsua_parse_media_type(tdata->pool, &msg_data->content_type, &ctype); - body = pjsip_msg_body_create(tdata->pool, &ctype.type, &ctype.subtype, - &msg_data->msg_body); - tdata->msg->body = body; + pjsua_parse_media_type(tdata->pool, &msg_data->content_type, &ctype); + body = pjsip_msg_body_create(tdata->pool, &ctype.type, &ctype.subtype, + &msg_data->msg_body); + tdata->msg->body = body; } /* Multipart */ if (!pj_list_empty(&msg_data->multipart_parts) && - msg_data->multipart_ctype.type.slen) + msg_data->multipart_ctype.type.slen) { - pjsip_msg_body *bodies; - pjsip_multipart_part *part; - pj_str_t *boundary = NULL; - - bodies = pjsip_multipart_create(tdata->pool, - &msg_data->multipart_ctype, - boundary); - part = msg_data->multipart_parts.next; - while (part != &msg_data->multipart_parts) { - pjsip_multipart_part *part_copy; - - part_copy = pjsip_multipart_clone_part(tdata->pool, part); - pjsip_multipart_add_part(tdata->pool, bodies, part_copy); - part = part->next; - } + pjsip_msg_body *bodies; + pjsip_multipart_part *part; + pj_str_t *boundary = NULL; + + bodies = pjsip_multipart_create(tdata->pool, + &msg_data->multipart_ctype, + boundary); + part = msg_data->multipart_parts.next; + while (part != &msg_data->multipart_parts) { + pjsip_multipart_part *part_copy; + + part_copy = pjsip_multipart_clone_part(tdata->pool, part); + pjsip_multipart_add_part(tdata->pool, bodies, part_copy); + part = part->next; + } - if (tdata->msg->body) { - part = pjsip_multipart_create_part(tdata->pool); - part->body = tdata->msg->body; - pjsip_multipart_add_part(tdata->pool, bodies, part); + if (tdata->msg->body) { + part = pjsip_multipart_create_part(tdata->pool); + part->body = tdata->msg->body; + pjsip_multipart_add_part(tdata->pool, bodies, part); - tdata->msg->body = NULL; - } + tdata->msg->body = NULL; + } - tdata->msg->body = bodies; + tdata->msg->body = bodies; } } @@ -3145,18 +3144,18 @@ void pjsua_process_msg_data(pjsip_tx_data *tdata, * Add route_set to outgoing requests */ void pjsua_set_msg_route_set( pjsip_tx_data *tdata, - const pjsip_route_hdr *route_set ) + const pjsip_route_hdr *route_set ) { const pjsip_route_hdr *r; r = route_set->next; while (r != route_set) { - pjsip_route_hdr *new_r; + pjsip_route_hdr *new_r; - new_r = (pjsip_route_hdr*) pjsip_hdr_clone(tdata->pool, r); - pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)new_r); + new_r = (pjsip_route_hdr*) pjsip_hdr_clone(tdata->pool, r); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)new_r); - r = r->next; + r = r->next; } } @@ -3165,8 +3164,8 @@ void pjsua_set_msg_route_set( pjsip_tx_data *tdata, * Simple version of MIME type parsing (it doesn't support parameters) */ void pjsua_parse_media_type( pj_pool_t *pool, - const pj_str_t *mime, - pjsip_media_type *media_type) + const pj_str_t *mime, + pjsip_media_type *media_type) { pj_str_t tmp; char *pos; @@ -3177,12 +3176,12 @@ void pjsua_parse_media_type( pj_pool_t *pool, pos = pj_strchr(&tmp, '/'); if (pos) { - media_type->type.ptr = tmp.ptr; - media_type->type.slen = (pos-tmp.ptr); - media_type->subtype.ptr = pos+1; - media_type->subtype.slen = tmp.ptr+tmp.slen-pos-1; + media_type->type.ptr = tmp.ptr; + media_type->type.slen = (pos-tmp.ptr); + media_type->subtype.ptr = pos+1; + media_type->subtype.slen = tmp.ptr+tmp.slen-pos-1; } else { - media_type->type = tmp; + media_type->type = tmp; } } @@ -3191,27 +3190,27 @@ void pjsua_parse_media_type( pj_pool_t *pool, * Internal function to init transport selector from transport id. */ void pjsua_init_tpselector(pjsua_transport_id tp_id, - pjsip_tpselector *sel) + pjsip_tpselector *sel) { pjsua_transport_data *tpdata; unsigned flag; pj_bzero(sel, sizeof(*sel)); if (tp_id == PJSUA_INVALID_ID) - return; + return; PJ_ASSERT_RETURN(tp_id >= 0 && - tp_id < (int)PJ_ARRAY_SIZE(pjsua_var.tpdata), ); + tp_id < (int)PJ_ARRAY_SIZE(pjsua_var.tpdata), ); tpdata = &pjsua_var.tpdata[tp_id]; flag = pjsip_transport_get_flag_from_type(tpdata->type); if (flag & PJSIP_TRANSPORT_DATAGRAM) { - sel->type = PJSIP_TPSELECTOR_TRANSPORT; - sel->u.transport = tpdata->data.tp; + sel->type = PJSIP_TPSELECTOR_TRANSPORT; + sel->u.transport = tpdata->data.tp; } else { - sel->type = PJSIP_TPSELECTOR_LISTENER; - sel->u.listener = tpdata->data.factory; + sel->type = PJSIP_TPSELECTOR_LISTENER; + sel->u.listener = tpdata->data.factory; } } @@ -3226,7 +3225,7 @@ PJ_DEF(void) pjsua_ip_change_param_default(pjsua_ip_change_param *param) /* Callback upon NAT detection completion */ static void nat_detect_cb(void *user_data, - const pj_stun_nat_detect_result *res) + const pj_stun_nat_detect_result *res) { PJ_UNUSED_ARG(user_data); @@ -3235,7 +3234,7 @@ static void nat_detect_cb(void *user_data, pjsua_var.nat_type = res->nat_type; if (pjsua_var.ua_cfg.cb.on_nat_detect) { - (*pjsua_var.ua_cfg.cb.on_nat_detect)(res); + (*pjsua_var.ua_cfg.cb.on_nat_detect)(res); } } @@ -3248,30 +3247,30 @@ PJ_DEF(pj_status_t) pjsua_detect_nat_type() pj_status_t status; if (pjsua_var.nat_in_progress) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Make sure STUN server resolution has completed */ status = resolve_stun_server(PJ_TRUE, PJ_TRUE, 0); if (status != PJ_SUCCESS) { - pjsua_var.nat_status = status; - pjsua_var.nat_type = PJ_STUN_NAT_TYPE_ERR_UNKNOWN; - return status; + pjsua_var.nat_status = status; + pjsua_var.nat_type = PJ_STUN_NAT_TYPE_ERR_UNKNOWN; + return status; } /* Make sure we have STUN */ if (pjsua_var.stun_srv.addr.sa_family == 0) { - pjsua_var.nat_status = PJNATH_ESTUNINSERVER; - return PJNATH_ESTUNINSERVER; + pjsua_var.nat_status = PJNATH_ESTUNINSERVER; + return PJNATH_ESTUNINSERVER; } status = pj_stun_detect_nat_type2(&pjsua_var.stun_srv, - &pjsua_var.stun_cfg, - NULL, &nat_detect_cb); + &pjsua_var.stun_cfg, + NULL, &nat_detect_cb); if (status != PJ_SUCCESS) { - pjsua_var.nat_status = status; - pjsua_var.nat_type = PJ_STUN_NAT_TYPE_ERR_UNKNOWN; - return status; + pjsua_var.nat_status = status; + pjsua_var.nat_type = PJ_STUN_NAT_TYPE_ERR_UNKNOWN; + return status; } pjsua_var.nat_in_progress = PJ_TRUE; @@ -3333,9 +3332,9 @@ PJ_DEF(pj_status_t) pjsua_verify_sip_url(const char *c_url) p = pjsip_parse_uri(pool, url, len, 0); if (!p || (pj_stricmp2(pjsip_uri_get_scheme(p), "sip") != 0 && - pj_stricmp2(pjsip_uri_get_scheme(p), "sips") != 0)) + pj_stricmp2(pjsip_uri_get_scheme(p), "sips") != 0)) { - p = NULL; + p = NULL; } pj_pool_release(pool); @@ -3356,7 +3355,7 @@ PJ_DEF(pj_status_t) pjsua_schedule_timer_dbg( pj_timer_entry *entry, } #else PJ_DEF(pj_status_t) pjsua_schedule_timer( pj_timer_entry *entry, - const pj_time_val *delay) + const pj_time_val *delay) { return pjsip_endpt_schedule_timer(pjsua_var.endpt, entry, delay); } @@ -3364,7 +3363,7 @@ PJ_DEF(pj_status_t) pjsua_schedule_timer( pj_timer_entry *entry, /* Timer callback */ static void timer_cb( pj_timer_heap_t *th, - pj_timer_entry *entry) + pj_timer_entry *entry) { pjsua_timer_list *tmr = (pjsua_timer_list *)entry->user_data; void (*cb)(void *user_data) = tmr->cb; @@ -3421,7 +3420,7 @@ PJ_DEF(pj_status_t) pjsua_schedule_timer2( void (*cb)(void *user_data), status = pjsip_endpt_schedule_timer(pjsua_var.endpt, &tmr->entry, &delay); #endif if (status == PJ_SUCCESS) { - pj_list_push_back(&pjsua_var.active_timer_list, tmr); + pj_list_push_back(&pjsua_var.active_timer_list, tmr); } else { pj_list_push_back(&pjsua_var.timer_list, tmr); } @@ -3453,33 +3452,33 @@ pj_status_t normalize_route_uri(pj_pool_t *pool, pj_str_t *uri) tmp_pool = pjsua_pool_create("tmplr%p", 512, 512); if (!tmp_pool) - return PJ_ENOMEM; + return PJ_ENOMEM; pj_strdup_with_null(tmp_pool, &tmp_uri, uri); uri_obj = pjsip_parse_uri(tmp_pool, tmp_uri.ptr, tmp_uri.slen, 0); if (!uri_obj) { - PJ_LOG(1,(THIS_FILE, "Invalid route URI: %.*s", - (int)uri->slen, uri->ptr)); - pj_pool_release(tmp_pool); - return PJSIP_EINVALIDURI; + PJ_LOG(1,(THIS_FILE, "Invalid route URI: %.*s", + (int)uri->slen, uri->ptr)); + pj_pool_release(tmp_pool); + return PJSIP_EINVALIDURI; } if (!PJSIP_URI_SCHEME_IS_SIP(uri_obj) && - !PJSIP_URI_SCHEME_IS_SIPS(uri_obj)) + !PJSIP_URI_SCHEME_IS_SIPS(uri_obj)) { - PJ_LOG(1,(THIS_FILE, "Route URI must be SIP URI: %.*s", - (int)uri->slen, uri->ptr)); - pj_pool_release(tmp_pool); - return PJSIP_EINVALIDSCHEME; + PJ_LOG(1,(THIS_FILE, "Route URI must be SIP URI: %.*s", + (int)uri->slen, uri->ptr)); + pj_pool_release(tmp_pool); + return PJSIP_EINVALIDSCHEME; } sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(uri_obj); /* Done if force_lr is disabled or if lr parameter is present */ if (!pjsua_var.ua_cfg.force_lr || sip_uri->lr_param) { - pj_pool_release(tmp_pool); - return PJ_SUCCESS; + pj_pool_release(tmp_pool); + return PJ_SUCCESS; } /* Set lr param */ @@ -3488,12 +3487,12 @@ pj_status_t normalize_route_uri(pj_pool_t *pool, pj_str_t *uri) /* Print the URI */ tmp_uri.ptr = (char*) pj_pool_alloc(tmp_pool, PJSIP_MAX_URL_SIZE); tmp_uri.slen = pjsip_uri_print(PJSIP_URI_IN_ROUTING_HDR, uri_obj, - tmp_uri.ptr, PJSIP_MAX_URL_SIZE); + tmp_uri.ptr, PJSIP_MAX_URL_SIZE); if (tmp_uri.slen < 1) { - PJ_LOG(1,(THIS_FILE, "Route URI is too long: %.*s", - (int)uri->slen, uri->ptr)); - pj_pool_release(tmp_pool); - return PJSIP_EURITOOLONG; + PJ_LOG(1,(THIS_FILE, "Route URI is too long: %.*s", + (int)uri->slen, uri->ptr)); + pj_pool_release(tmp_pool); + return PJSIP_EURITOOLONG; } /* Clone the URI */ @@ -3518,8 +3517,8 @@ PJ_DEF(void) pjsua_dump(pj_bool_t detail) pj_log_set_decor(old_decor & (PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_CR)); if (detail) { - pj_dump_config(); - pjsip_dump_config(); + pj_dump_config(); + pjsip_dump_config(); } pjsip_endpt_dump(pjsua_get_pjsip_endpt(), detail); @@ -3528,48 +3527,48 @@ PJ_DEF(void) pjsua_dump(pj_bool_t detail) PJ_LOG(3,(THIS_FILE, "Dumping media transports:")); for (i=0; imed_cnt; ++j) { - if (call->media[j].tp != NULL) - tp[tp_cnt++] = call->media[j].tp; - } - for (j = 0; j < call->med_prov_cnt; ++j) { - pjmedia_transport *med_tp = call->media_prov[j].tp; - if (med_tp) { - unsigned k; - pj_bool_t used = PJ_FALSE; - for (k = 0; k < tp_cnt; ++k) { - if (med_tp == tp[k]) { - used = PJ_TRUE; - break; - } - } - if (!used) - tp[tp_cnt++] = med_tp; - } - } - - acc_cfg = &pjsua_var.acc[call->acc_id].cfg; - - /* Dump the media transports in this call */ - for (j = 0; j < tp_cnt; ++j) { - pjmedia_transport_info tpinfo; - char addr_buf[80]; - - pjmedia_transport_info_init(&tpinfo); - pjmedia_transport_get_info(tp[j], &tpinfo); - PJ_LOG(3,(THIS_FILE, " %s: %s", - (acc_cfg->ice_cfg.enable_ice ? "ICE" : "UDP"), - pj_sockaddr_print(&tpinfo.sock_info.rtp_addr_name, - addr_buf, - sizeof(addr_buf), 3))); - } + pjsua_call *call = &pjsua_var.calls[i]; + pjsua_acc_config *acc_cfg; + pjmedia_transport *tp[PJSUA_MAX_CALL_MEDIA*2]; + unsigned tp_cnt = 0; + unsigned j; + + /* Collect media transports in this call */ + for (j = 0; j < call->med_cnt; ++j) { + if (call->media[j].tp != NULL) + tp[tp_cnt++] = call->media[j].tp; + } + for (j = 0; j < call->med_prov_cnt; ++j) { + pjmedia_transport *med_tp = call->media_prov[j].tp; + if (med_tp) { + unsigned k; + pj_bool_t used = PJ_FALSE; + for (k = 0; k < tp_cnt; ++k) { + if (med_tp == tp[k]) { + used = PJ_TRUE; + break; + } + } + if (!used) + tp[tp_cnt++] = med_tp; + } + } + + acc_cfg = &pjsua_var.acc[call->acc_id].cfg; + + /* Dump the media transports in this call */ + for (j = 0; j < tp_cnt; ++j) { + pjmedia_transport_info tpinfo; + char addr_buf[80]; + + pjmedia_transport_info_init(&tpinfo); + pjmedia_transport_get_info(tp[j], &tpinfo); + PJ_LOG(3,(THIS_FILE, " %s: %s", + (acc_cfg->ice_cfg.enable_ice ? "ICE" : "UDP"), + pj_sockaddr_print(&tpinfo.sock_info.rtp_addr_name, + addr_buf, + sizeof(addr_buf), 3))); + } } pjsip_tsx_layer_dump(detail); @@ -3583,48 +3582,48 @@ PJ_DEF(void) pjsua_dump(pj_bool_t detail) if (pjsua_call_get_count() == 0) { - PJ_LOG(3,(THIS_FILE, " - no sessions -")); + PJ_LOG(3,(THIS_FILE, " - no sessions -")); } else { - unsigned i; - - for (i=0; i call_dump_len) - part_len = call_dump_len - part_idx; - p_orig = p[part_len]; - p[part_len] = '\0'; - PJ_LOG(3,(THIS_FILE, "%s", p)); - p[part_len] = p_orig; - part_idx += part_len; - } - pj_log_set_decor(log_decor); - } - } + unsigned i; + + for (i=0; i call_dump_len) + part_len = call_dump_len - part_idx; + p_orig = p[part_len]; + p[part_len] = '\0'; + PJ_LOG(3,(THIS_FILE, "%s", p)); + p[part_len] = p_orig; + part_idx += part_len; + } + pj_log_set_decor(log_decor); + } + } } #endif @@ -3649,108 +3648,108 @@ static pj_status_t handle_ip_change_on_acc() PJSUA_LOCK(); if (pjsua_var.acc_cnt == 0) { - PJ_LOG(3, (THIS_FILE, - "No account is set, IP change handling will stop")); - pjsua_acc_end_ip_change(NULL); - PJSUA_UNLOCK(); - return status; + PJ_LOG(3, (THIS_FILE, + "No account is set, IP change handling will stop")); + pjsua_acc_end_ip_change(NULL); + PJSUA_UNLOCK(); + return status; } /* Reset ip_change_active flag. */ for (; i < (int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) { - pjsua_var.acc[i].ip_change_op = PJSUA_IP_CHANGE_OP_NULL; - acc_done[i] = PJ_FALSE; + pjsua_var.acc[i].ip_change_op = PJSUA_IP_CHANGE_OP_NULL; + acc_done[i] = PJ_FALSE; } for (i = 0; i < (int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) { - pj_bool_t shutdown_transport = PJ_FALSE; - pjsip_regc_info regc_info; - char acc_id[PJSUA_MAX_ACC * 4]; - pjsua_acc *acc = &pjsua_var.acc[i]; - pjsip_transport *transport = NULL; - pjsua_acc_id shut_acc_ids[PJSUA_MAX_ACC]; - unsigned shut_acc_cnt = 0; - - if (!acc->valid || (acc_done[i])) - continue; - - if (acc->regc) { - int j = 0; - pj_status_t found_restart_tp_fail = PJ_FALSE; - - pjsip_regc_get_info(acc->regc, ®c_info); - - /* Check if transport restart listener succeed. */ - for (; j < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++j) { - if (pjsua_var.tpdata[j].data.ptr != NULL && - pjsua_var.tpdata[j].restart_status != PJ_SUCCESS && - pjsua_var.tpdata[j].type == regc_info.transport->key.type) - { - if ((pjsua_var.tpdata[j].data.factory - == regc_info.transport->factory) || - (pjsua_var.tpdata[j].data.tp - == regc_info.transport)) - { - found_restart_tp_fail = PJ_TRUE; - break; - } - } - } - - if (found_restart_tp_fail) { - if (acc->ka_timer.id) { - pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer); - acc->ka_timer.id = PJ_FALSE; - - if (acc->ka_transport) { - pjsip_transport_dec_ref(acc->ka_transport); - acc->ka_transport = NULL; - } - } - pjsua_acc_end_ip_change(acc); - continue; - } - - if ((regc_info.transport) && - ((regc_info.transport->flag & PJSIP_TRANSPORT_DATAGRAM) == 0)) - { - transport = regc_info.transport; - shutdown_transport = acc->cfg.ip_change_cfg.shutdown_tp; - shut_acc_ids[shut_acc_cnt++] = acc->index; - } - } else if (acc->cfg.reg_uri.slen && - acc->reg_last_code != PJSIP_SC_OK && - acc->reg_last_code != PJSIP_SC_REQUEST_TIMEOUT && - acc->reg_last_code != PJSIP_SC_INTERNAL_SERVER_ERROR && - acc->reg_last_code != PJSIP_SC_BAD_GATEWAY && - acc->reg_last_code != PJSIP_SC_SERVICE_UNAVAILABLE && - acc->reg_last_code != PJSIP_SC_SERVER_TIMEOUT && - acc->reg_last_code != PJSIP_SC_TEMPORARILY_UNAVAILABLE) - { - PJ_LOG(3, (THIS_FILE, "Permanent registration failure, " - "IP change handling will stop for acc %d", acc->index)); - - pjsua_acc_end_ip_change(acc); - continue; - } - pj_ansi_snprintf(acc_id, sizeof(acc_id), "#%d", i); - - if (transport) { - unsigned j = i + 1; - - /* Find other account that uses the same transport. */ - for (; j < (int)PJ_ARRAY_SIZE(pjsua_var.acc); ++j) { - pjsip_regc_info tmp_regc_info; - pjsua_acc *next_acc = &pjsua_var.acc[j]; - - if (!next_acc->valid || !next_acc->regc || - (next_acc->ip_change_op > PJSUA_IP_CHANGE_OP_NULL)) - { - continue; - } - - pjsip_regc_get_info(next_acc->regc, &tmp_regc_info); - if (transport == tmp_regc_info.transport) { + pj_bool_t shutdown_transport = PJ_FALSE; + pjsip_regc_info regc_info; + char acc_id[PJSUA_MAX_ACC * 4]; + pjsua_acc *acc = &pjsua_var.acc[i]; + pjsip_transport *transport = NULL; + pjsua_acc_id shut_acc_ids[PJSUA_MAX_ACC]; + unsigned shut_acc_cnt = 0; + + if (!acc->valid || (acc_done[i])) + continue; + + if (acc->regc) { + int j = 0; + pj_status_t found_restart_tp_fail = PJ_FALSE; + + pjsip_regc_get_info(acc->regc, ®c_info); + + /* Check if transport restart listener succeed. */ + for (; j < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++j) { + if (pjsua_var.tpdata[j].data.ptr != NULL && + pjsua_var.tpdata[j].restart_status != PJ_SUCCESS && + pjsua_var.tpdata[j].type == regc_info.transport->key.type) + { + if ((pjsua_var.tpdata[j].data.factory + == regc_info.transport->factory) || + (pjsua_var.tpdata[j].data.tp + == regc_info.transport)) + { + found_restart_tp_fail = PJ_TRUE; + break; + } + } + } + + if (found_restart_tp_fail) { + if (acc->ka_timer.id) { + pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer); + acc->ka_timer.id = PJ_FALSE; + + if (acc->ka_transport) { + pjsip_transport_dec_ref(acc->ka_transport); + acc->ka_transport = NULL; + } + } + pjsua_acc_end_ip_change(acc); + continue; + } + + if ((regc_info.transport) && + ((regc_info.transport->flag & PJSIP_TRANSPORT_DATAGRAM) == 0)) + { + transport = regc_info.transport; + shutdown_transport = acc->cfg.ip_change_cfg.shutdown_tp; + shut_acc_ids[shut_acc_cnt++] = acc->index; + } + } else if (acc->cfg.reg_uri.slen && + acc->reg_last_code != PJSIP_SC_OK && + acc->reg_last_code != PJSIP_SC_REQUEST_TIMEOUT && + acc->reg_last_code != PJSIP_SC_INTERNAL_SERVER_ERROR && + acc->reg_last_code != PJSIP_SC_BAD_GATEWAY && + acc->reg_last_code != PJSIP_SC_SERVICE_UNAVAILABLE && + acc->reg_last_code != PJSIP_SC_SERVER_TIMEOUT && + acc->reg_last_code != PJSIP_SC_TEMPORARILY_UNAVAILABLE) + { + PJ_LOG(3, (THIS_FILE, "Permanent registration failure, " + "IP change handling will stop for acc %d", acc->index)); + + pjsua_acc_end_ip_change(acc); + continue; + } + pj_ansi_snprintf(acc_id, sizeof(acc_id), "#%d", i); + + if (transport) { + unsigned j = i + 1; + + /* Find other account that uses the same transport. */ + for (; j < (int)PJ_ARRAY_SIZE(pjsua_var.acc); ++j) { + pjsip_regc_info tmp_regc_info; + pjsua_acc *next_acc = &pjsua_var.acc[j]; + + if (!next_acc->valid || !next_acc->regc || + (next_acc->ip_change_op > PJSUA_IP_CHANGE_OP_NULL)) + { + continue; + } + + pjsip_regc_get_info(next_acc->regc, &tmp_regc_info); + if (transport == tmp_regc_info.transport) { char tmp_buf[4]; pj_ansi_snprintf(tmp_buf, sizeof(tmp_buf), " #%d", j); @@ -3760,36 +3759,36 @@ static pj_status_t handle_ip_change_on_acc() pj_ansi_strcat(acc_id, tmp_buf); } - shut_acc_ids[shut_acc_cnt++] = j; - if (!shutdown_transport) { - shutdown_transport = - next_acc->cfg.ip_change_cfg.shutdown_tp; - } - } - } - } - - if (shutdown_transport) { - unsigned j; - /* Shutdown the transport. */ - PJ_LOG(3, (THIS_FILE, "Shutdown transport %s used by account %s " - "triggered by IP change", transport->obj_name, acc_id)); - - for (j = 0; j < shut_acc_cnt; ++j) { - pjsua_acc *tmp_acc = &pjsua_var.acc[shut_acc_ids[j]]; - tmp_acc->ip_change_op = PJSUA_IP_CHANGE_OP_ACC_SHUTDOWN_TP; - acc_done[shut_acc_ids[j]] = PJ_TRUE; - } - - status = pjsip_transport_shutdown2(transport, PJ_TRUE); - } else { - acc_done[i] = PJ_TRUE; - if (acc->cfg.allow_contact_rewrite && acc->cfg.reg_uri.slen) { - status = pjsua_acc_update_contact_on_ip_change(acc); - } else { - status = pjsua_acc_handle_call_on_ip_change(acc); - } - } + shut_acc_ids[shut_acc_cnt++] = j; + if (!shutdown_transport) { + shutdown_transport = + next_acc->cfg.ip_change_cfg.shutdown_tp; + } + } + } + } + + if (shutdown_transport) { + unsigned j; + /* Shutdown the transport. */ + PJ_LOG(3, (THIS_FILE, "Shutdown transport %s used by account %s " + "triggered by IP change", transport->obj_name, acc_id)); + + for (j = 0; j < shut_acc_cnt; ++j) { + pjsua_acc *tmp_acc = &pjsua_var.acc[shut_acc_ids[j]]; + tmp_acc->ip_change_op = PJSUA_IP_CHANGE_OP_ACC_SHUTDOWN_TP; + acc_done[shut_acc_ids[j]] = PJ_TRUE; + } + + status = pjsip_transport_shutdown2(transport, PJ_TRUE); + } else { + acc_done[i] = PJ_TRUE; + if (acc->cfg.allow_contact_rewrite && acc->cfg.reg_uri.slen) { + status = pjsua_acc_update_contact_on_ip_change(acc); + } else { + status = pjsua_acc_handle_call_on_ip_change(acc); + } + } } PJSUA_UNLOCK(); return status; @@ -3797,7 +3796,7 @@ static pj_status_t handle_ip_change_on_acc() static pj_status_t restart_listener(pjsua_transport_id id, - unsigned restart_lis_delay) + unsigned restart_lis_delay) { pj_sockaddr bind_addr; pjsua_transport_info tp_info; @@ -3805,98 +3804,98 @@ static pj_status_t restart_listener(pjsua_transport_id id, pjsua_transport_get_info(id, &tp_info); pj_sockaddr_init(pjsip_transport_type_get_af(tp_info.type), - &bind_addr, - NULL, - pj_sockaddr_get_port(&tp_info.local_addr)); + &bind_addr, + NULL, + pj_sockaddr_get_port(&tp_info.local_addr)); switch (tp_info.type) { case PJSIP_TRANSPORT_UDP: case PJSIP_TRANSPORT_UDP6: { - unsigned num_locks = 0; + unsigned num_locks = 0; - /* Release locks before restarting the transport, to avoid deadlock. */ - while (PJSUA_LOCK_IS_LOCKED()) { - num_locks++; - PJSUA_UNLOCK(); - } + /* Release locks before restarting the transport, to avoid deadlock. */ + while (PJSUA_LOCK_IS_LOCKED()) { + num_locks++; + PJSUA_UNLOCK(); + } - status = pjsip_udp_transport_restart2( - pjsua_var.tpdata[id].data.tp, - PJSIP_UDP_TRANSPORT_DESTROY_SOCKET, - PJ_INVALID_SOCKET, - &bind_addr, - NULL); + status = pjsip_udp_transport_restart2( + pjsua_var.tpdata[id].data.tp, + PJSIP_UDP_TRANSPORT_DESTROY_SOCKET, + PJ_INVALID_SOCKET, + &bind_addr, + NULL); - /* Re-acquire the locks. */ - for (;num_locks > 0; num_locks--) - PJSUA_LOCK(); + /* Re-acquire the locks. */ + for (;num_locks > 0; num_locks--) + PJSUA_LOCK(); } - break; + break; #if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0 case PJSIP_TRANSPORT_TLS: case PJSIP_TRANSPORT_TLS6: - status = pjsip_tls_transport_restart( - pjsua_var.tpdata[id].data.factory, - &bind_addr, - NULL); - break; + status = pjsip_tls_transport_restart( + pjsua_var.tpdata[id].data.factory, + &bind_addr, + NULL); + break; #endif case PJSIP_TRANSPORT_TCP: case PJSIP_TRANSPORT_TCP6: - status = pjsip_tcp_transport_restart( - pjsua_var.tpdata[id].data.factory, - &bind_addr, - NULL); - break; + status = pjsip_tcp_transport_restart( + pjsua_var.tpdata[id].data.factory, + &bind_addr, + NULL); + break; default: - status = PJ_EINVAL; + status = PJ_EINVAL; } PJ_PERROR(3,(THIS_FILE, status, "Listener %.*s restart", - tp_info.info.slen, tp_info.info.ptr)); + tp_info.info.slen, tp_info.info.ptr)); if (status != PJ_SUCCESS && (restart_lis_delay > 0)) { - /* Try restarting again, with delay. */ - pjsua_schedule_timer2(&restart_listener_cb, - (void*)(pj_size_t)id, - restart_lis_delay); + /* Try restarting again, with delay. */ + pjsua_schedule_timer2(&restart_listener_cb, + (void*)(pj_size_t)id, + restart_lis_delay); - PJ_LOG(3,(THIS_FILE, "Retry listener %.*s restart in %d ms", - tp_info.info.slen, tp_info.info.ptr, restart_lis_delay)); + PJ_LOG(3,(THIS_FILE, "Retry listener %.*s restart in %d ms", + tp_info.info.slen, tp_info.info.ptr, restart_lis_delay)); - status = PJ_SUCCESS; + status = PJ_SUCCESS; } else { - int i = 0; - pj_bool_t all_done = PJ_TRUE; - - pjsua_var.tpdata[id].is_restarting = PJ_FALSE; - pjsua_var.tpdata[id].restart_status = status; - if (pjsua_var.ua_cfg.cb.on_ip_change_progress) { - pjsua_ip_change_op_info info; - - pj_bzero(&info, sizeof(info)); - info.lis_restart.transport_id = id; - pjsua_var.ua_cfg.cb.on_ip_change_progress( - PJSUA_IP_CHANGE_OP_RESTART_LIS, - status, - &info); - } - - /* Move forward if all listener has been restarted. */ - for (; i < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++i) { - if (pjsua_var.tpdata[i].data.ptr != NULL && - pjsua_var.tpdata[i].is_restarting) - { - all_done = PJ_FALSE; - break; - } - } - if (all_done) - status = handle_ip_change_on_acc(); + int i = 0; + pj_bool_t all_done = PJ_TRUE; + + pjsua_var.tpdata[id].is_restarting = PJ_FALSE; + pjsua_var.tpdata[id].restart_status = status; + if (pjsua_var.ua_cfg.cb.on_ip_change_progress) { + pjsua_ip_change_op_info info; + + pj_bzero(&info, sizeof(info)); + info.lis_restart.transport_id = id; + pjsua_var.ua_cfg.cb.on_ip_change_progress( + PJSUA_IP_CHANGE_OP_RESTART_LIS, + status, + &info); + } + + /* Move forward if all listener has been restarted. */ + for (; i < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++i) { + if (pjsua_var.tpdata[i].data.ptr != NULL && + pjsua_var.tpdata[i].is_restarting) + { + all_done = PJ_FALSE; + break; + } + } + if (all_done) + status = handle_ip_change_on_acc(); } return status; } @@ -3926,13 +3925,13 @@ PJ_DEF(pj_status_t) pjsua_handle_ip_change(const pjsua_ip_change_param *param) PJ_ASSERT_RETURN(param, PJ_EINVAL); for (; i < (int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) { - if (pjsua_var.acc[i].valid && - pjsua_var.acc[i].ip_change_op != PJSUA_IP_CHANGE_OP_NULL && - pjsua_var.acc[i].ip_change_op != PJSUA_IP_CHANGE_OP_COMPLETED) - { - PJ_LOG(2, (THIS_FILE, - "Previous IP address change handling still in progress")); - } + if (pjsua_var.acc[i].valid && + pjsua_var.acc[i].ip_change_op != PJSUA_IP_CHANGE_OP_NULL && + pjsua_var.acc[i].ip_change_op != PJSUA_IP_CHANGE_OP_COMPLETED) + { + PJ_LOG(2, (THIS_FILE, + "Previous IP address change handling still in progress")); + } } PJ_LOG(3, (THIS_FILE, "Start handling IP address change")); @@ -3942,39 +3941,39 @@ PJ_DEF(pj_status_t) pjsua_handle_ip_change(const pjsua_ip_change_param *param) * timed out and cause call disconnection. */ if (!pjsip_cfg()->endpt.keep_inv_after_tsx_timeout) { - pjsip_cfg()->endpt.keep_inv_after_tsx_timeout = PJ_TRUE; + pjsip_cfg()->endpt.keep_inv_after_tsx_timeout = PJ_TRUE; - /* Put it back after some time (transaction timeout setting value) */ - pjsua_schedule_timer2(&ip_change_put_back_inv_config, NULL, - pjsip_cfg()->tsx.td); + /* Put it back after some time (transaction timeout setting value) */ + pjsua_schedule_timer2(&ip_change_put_back_inv_config, NULL, + pjsip_cfg()->tsx.td); - PJ_LOG(4,(THIS_FILE,"IP change temporarily ignores request timeout")); + PJ_LOG(4,(THIS_FILE,"IP change temporarily ignores request timeout")); } if (param->restart_listener) { - PJSUA_LOCK(); - /* Restart listener/transport, handle_ip_change_on_acc() will - * be called after listener restart is completed successfully. - */ - for (i = 0; i < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++i) { - if (pjsua_var.tpdata[i].data.ptr != NULL) { - pjsua_var.tpdata[i].is_restarting = PJ_TRUE; - pjsua_var.tpdata[i].restart_status = PJ_EUNKNOWN; - } - } - for (i = 0; i < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++i) { - if (pjsua_var.tpdata[i].data.ptr != NULL) { - status = restart_listener(i, param->restart_lis_delay); - } - } + PJSUA_LOCK(); + /* Restart listener/transport, handle_ip_change_on_acc() will + * be called after listener restart is completed successfully. + */ + for (i = 0; i < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++i) { + if (pjsua_var.tpdata[i].data.ptr != NULL) { + pjsua_var.tpdata[i].is_restarting = PJ_TRUE; + pjsua_var.tpdata[i].restart_status = PJ_EUNKNOWN; + } + } + for (i = 0; i < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++i) { + if (pjsua_var.tpdata[i].data.ptr != NULL) { + status = restart_listener(i, param->restart_lis_delay); + } + } PJSUA_UNLOCK(); } else { - for (i = 0; i < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++i) { - if (pjsua_var.tpdata[i].data.ptr != NULL) { - pjsua_var.tpdata[i].restart_status = PJ_SUCCESS; - } - } - status = handle_ip_change_on_acc(); + for (i = 0; i < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++i) { + if (pjsua_var.tpdata[i].data.ptr != NULL) { + pjsua_var.tpdata[i].restart_status = PJ_SUCCESS; + } + } + status = handle_ip_change_on_acc(); } return status; diff --git a/pjsip/src/pjsua-lib/pjsua_dump.c b/pjsip/src/pjsua-lib/pjsua_dump.c index 7299775f57..8924b8c5f0 100644 --- a/pjsip/src/pjsua-lib/pjsua_dump.c +++ b/pjsip/src/pjsua-lib/pjsua_dump.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2011-2011 Teluu Inc. (http://www.teluu.com) * @@ -22,24 +21,24 @@ const char *good_number(char *buf, pj_int32_t val) { if (val < 1000) { - pj_ansi_sprintf(buf, "%d", val); + pj_ansi_sprintf(buf, "%d", val); } else if (val < 1000000) { - pj_ansi_sprintf(buf, "%d.%dK", - val / 1000, - (val % 1000) / 100); + pj_ansi_sprintf(buf, "%d.%dK", + val / 1000, + (val % 1000) / 100); } else { - pj_ansi_sprintf(buf, "%d.%02dM", - val / 1000000, - (val % 1000000) / 10000); + pj_ansi_sprintf(buf, "%d.%02dM", + val / 1000000, + (val % 1000000) / 10000); } return buf; } static unsigned dump_media_stat(const char *indent, - char *buf, unsigned maxlen, - const pjmedia_rtcp_stat *stat, - const char *rx_info, const char *tx_info) + char *buf, unsigned maxlen, + const pjmedia_rtcp_stat *stat, + const char *rx_info, const char *tx_info) { char last_update[64]; char packets[32], bytes[32], ipbytes[32], avg_bps[32], avg_ipbps[32]; @@ -48,162 +47,162 @@ static unsigned dump_media_stat(const char *indent, int len; if (stat->rx.update_cnt == 0) - strcpy(last_update, "never"); + strcpy(last_update, "never"); else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, stat->rx.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, stat->rx.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); } pj_gettimeofday(&media_duration); PJ_TIME_VAL_SUB(media_duration, stat->start); if (PJ_TIME_VAL_MSEC(media_duration) == 0) - media_duration.msec = 1; + media_duration.msec = 1; len = pj_ansi_snprintf(p, end-p, - "%s RX %s last update:%s\n" - "%s total %spkt %sB (%sB +IP hdr) @avg=%sbps/%sbps\n" - "%s pkt loss=%d (%3.1f%%), discrd=%d (%3.1f%%), dup=%d (%2.1f%%), reord=%d (%3.1f%%)\n" - "%s (msec) min avg max last dev\n" - "%s loss period: %7.3f %7.3f %7.3f %7.3f %7.3f\n" - "%s jitter : %7.3f %7.3f %7.3f %7.3f %7.3f\n" + "%s RX %s last update:%s\n" + "%s total %spkt %sB (%sB +IP hdr) @avg=%sbps/%sbps\n" + "%s pkt loss=%d (%3.1f%%), discrd=%d (%3.1f%%), dup=%d (%2.1f%%), reord=%d (%3.1f%%)\n" + "%s (msec) min avg max last dev\n" + "%s loss period: %7.3f %7.3f %7.3f %7.3f %7.3f\n" + "%s jitter : %7.3f %7.3f %7.3f %7.3f %7.3f\n" #if defined(PJMEDIA_RTCP_STAT_HAS_RAW_JITTER) && PJMEDIA_RTCP_STAT_HAS_RAW_JITTER!=0 - "%s raw jitter : %7.3f %7.3f %7.3f %7.3f %7.3f\n" + "%s raw jitter : %7.3f %7.3f %7.3f %7.3f %7.3f\n" #endif #if defined(PJMEDIA_RTCP_STAT_HAS_IPDV) && PJMEDIA_RTCP_STAT_HAS_IPDV!=0 - "%s IPDV : %7.3f %7.3f %7.3f %7.3f %7.3f\n" + "%s IPDV : %7.3f %7.3f %7.3f %7.3f %7.3f\n" #endif - "%s", - indent, - rx_info? rx_info : "", - last_update, - - indent, - good_number(packets, stat->rx.pkt), - good_number(bytes, stat->rx.bytes), - good_number(ipbytes, stat->rx.bytes + stat->rx.pkt * 40), - good_number(avg_bps, (pj_int32_t)((pj_int64_t)stat->rx.bytes * 8 * 1000 / PJ_TIME_VAL_MSEC(media_duration))), - good_number(avg_ipbps, (pj_int32_t)(((pj_int64_t)stat->rx.bytes + stat->rx.pkt * 40) * 8 * 1000 / PJ_TIME_VAL_MSEC(media_duration))), - indent, - stat->rx.loss, - (stat->rx.loss? stat->rx.loss * 100.0 / (stat->rx.pkt + stat->rx.loss) : 0), - stat->rx.discard, - (stat->rx.discard? stat->rx.discard * 100.0 / (stat->rx.pkt + stat->rx.loss) : 0), - stat->rx.dup, - (stat->rx.dup? stat->rx.dup * 100.0 / (stat->rx.pkt + stat->rx.loss) : 0), - stat->rx.reorder, - (stat->rx.reorder? stat->rx.reorder * 100.0 / (stat->rx.pkt + stat->rx.loss) : 0), - indent, indent, - stat->rx.loss_period.min / 1000.0, - stat->rx.loss_period.mean / 1000.0, - stat->rx.loss_period.max / 1000.0, - stat->rx.loss_period.last / 1000.0, - pj_math_stat_get_stddev(&stat->rx.loss_period) / 1000.0, - indent, - stat->rx.jitter.min / 1000.0, - stat->rx.jitter.mean / 1000.0, - stat->rx.jitter.max / 1000.0, - stat->rx.jitter.last / 1000.0, - pj_math_stat_get_stddev(&stat->rx.jitter) / 1000.0, + "%s", + indent, + rx_info? rx_info : "", + last_update, + + indent, + good_number(packets, stat->rx.pkt), + good_number(bytes, stat->rx.bytes), + good_number(ipbytes, stat->rx.bytes + stat->rx.pkt * 40), + good_number(avg_bps, (pj_int32_t)((pj_int64_t)stat->rx.bytes * 8 * 1000 / PJ_TIME_VAL_MSEC(media_duration))), + good_number(avg_ipbps, (pj_int32_t)(((pj_int64_t)stat->rx.bytes + stat->rx.pkt * 40) * 8 * 1000 / PJ_TIME_VAL_MSEC(media_duration))), + indent, + stat->rx.loss, + (stat->rx.loss? stat->rx.loss * 100.0 / (stat->rx.pkt + stat->rx.loss) : 0), + stat->rx.discard, + (stat->rx.discard? stat->rx.discard * 100.0 / (stat->rx.pkt + stat->rx.loss) : 0), + stat->rx.dup, + (stat->rx.dup? stat->rx.dup * 100.0 / (stat->rx.pkt + stat->rx.loss) : 0), + stat->rx.reorder, + (stat->rx.reorder? stat->rx.reorder * 100.0 / (stat->rx.pkt + stat->rx.loss) : 0), + indent, indent, + stat->rx.loss_period.min / 1000.0, + stat->rx.loss_period.mean / 1000.0, + stat->rx.loss_period.max / 1000.0, + stat->rx.loss_period.last / 1000.0, + pj_math_stat_get_stddev(&stat->rx.loss_period) / 1000.0, + indent, + stat->rx.jitter.min / 1000.0, + stat->rx.jitter.mean / 1000.0, + stat->rx.jitter.max / 1000.0, + stat->rx.jitter.last / 1000.0, + pj_math_stat_get_stddev(&stat->rx.jitter) / 1000.0, #if defined(PJMEDIA_RTCP_STAT_HAS_RAW_JITTER) && PJMEDIA_RTCP_STAT_HAS_RAW_JITTER!=0 - indent, - stat->rx_raw_jitter.min / 1000.0, - stat->rx_raw_jitter.mean / 1000.0, - stat->rx_raw_jitter.max / 1000.0, - stat->rx_raw_jitter.last / 1000.0, - pj_math_stat_get_stddev(&stat->rx_raw_jitter) / 1000.0, + indent, + stat->rx_raw_jitter.min / 1000.0, + stat->rx_raw_jitter.mean / 1000.0, + stat->rx_raw_jitter.max / 1000.0, + stat->rx_raw_jitter.last / 1000.0, + pj_math_stat_get_stddev(&stat->rx_raw_jitter) / 1000.0, #endif #if defined(PJMEDIA_RTCP_STAT_HAS_IPDV) && PJMEDIA_RTCP_STAT_HAS_IPDV!=0 - indent, - stat->rx_ipdv.min / 1000.0, - stat->rx_ipdv.mean / 1000.0, - stat->rx_ipdv.max / 1000.0, - stat->rx_ipdv.last / 1000.0, - pj_math_stat_get_stddev(&stat->rx_ipdv) / 1000.0, + indent, + stat->rx_ipdv.min / 1000.0, + stat->rx_ipdv.mean / 1000.0, + stat->rx_ipdv.max / 1000.0, + stat->rx_ipdv.last / 1000.0, + pj_math_stat_get_stddev(&stat->rx_ipdv) / 1000.0, #endif - "" - ); + "" + ); if (len < 1 || len >= end-p) { - *p = '\0'; - return (unsigned)(p-buf); + *p = '\0'; + return (unsigned)(p-buf); } p += len; if (stat->tx.update_cnt == 0) - strcpy(last_update, "never"); + strcpy(last_update, "never"); else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, stat->tx.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, stat->tx.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); } len = pj_ansi_snprintf(p, end-p, - "%s TX %s last update:%s\n" - "%s total %spkt %sB (%sB +IP hdr) @avg=%sbps/%sbps\n" - "%s pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)\n" - "%s (msec) min avg max last dev \n" - "%s loss period: %7.3f %7.3f %7.3f %7.3f %7.3f\n" - "%s jitter : %7.3f %7.3f %7.3f %7.3f %7.3f\n", - indent, - tx_info, - last_update, - - indent, - good_number(packets, stat->tx.pkt), - good_number(bytes, stat->tx.bytes), - good_number(ipbytes, stat->tx.bytes + stat->tx.pkt * 40), - good_number(avg_bps, (pj_int32_t)((pj_int64_t)stat->tx.bytes * 8 * 1000 / PJ_TIME_VAL_MSEC(media_duration))), - good_number(avg_ipbps, (pj_int32_t)(((pj_int64_t)stat->tx.bytes + stat->tx.pkt * 40) * 8 * 1000 / PJ_TIME_VAL_MSEC(media_duration))), - - indent, - stat->tx.loss, - (stat->tx.loss? stat->tx.loss * 100.0 / stat->tx.pkt : 0), - stat->tx.dup, - (stat->tx.dup? stat->tx.dup * 100.0 / stat->tx.pkt : 0), - stat->tx.reorder, - (stat->tx.reorder? stat->tx.reorder * 100.0 / stat->tx.pkt : 0), - - indent, indent, - stat->tx.loss_period.min / 1000.0, - stat->tx.loss_period.mean / 1000.0, - stat->tx.loss_period.max / 1000.0, - stat->tx.loss_period.last / 1000.0, - pj_math_stat_get_stddev(&stat->tx.loss_period) / 1000.0, - indent, - stat->tx.jitter.min / 1000.0, - stat->tx.jitter.mean / 1000.0, - stat->tx.jitter.max / 1000.0, - stat->tx.jitter.last / 1000.0, - pj_math_stat_get_stddev(&stat->tx.jitter) / 1000.0 - ); + "%s TX %s last update:%s\n" + "%s total %spkt %sB (%sB +IP hdr) @avg=%sbps/%sbps\n" + "%s pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)\n" + "%s (msec) min avg max last dev \n" + "%s loss period: %7.3f %7.3f %7.3f %7.3f %7.3f\n" + "%s jitter : %7.3f %7.3f %7.3f %7.3f %7.3f\n", + indent, + tx_info, + last_update, + + indent, + good_number(packets, stat->tx.pkt), + good_number(bytes, stat->tx.bytes), + good_number(ipbytes, stat->tx.bytes + stat->tx.pkt * 40), + good_number(avg_bps, (pj_int32_t)((pj_int64_t)stat->tx.bytes * 8 * 1000 / PJ_TIME_VAL_MSEC(media_duration))), + good_number(avg_ipbps, (pj_int32_t)(((pj_int64_t)stat->tx.bytes + stat->tx.pkt * 40) * 8 * 1000 / PJ_TIME_VAL_MSEC(media_duration))), + + indent, + stat->tx.loss, + (stat->tx.loss? stat->tx.loss * 100.0 / stat->tx.pkt : 0), + stat->tx.dup, + (stat->tx.dup? stat->tx.dup * 100.0 / stat->tx.pkt : 0), + stat->tx.reorder, + (stat->tx.reorder? stat->tx.reorder * 100.0 / stat->tx.pkt : 0), + + indent, indent, + stat->tx.loss_period.min / 1000.0, + stat->tx.loss_period.mean / 1000.0, + stat->tx.loss_period.max / 1000.0, + stat->tx.loss_period.last / 1000.0, + pj_math_stat_get_stddev(&stat->tx.loss_period) / 1000.0, + indent, + stat->tx.jitter.min / 1000.0, + stat->tx.jitter.mean / 1000.0, + stat->tx.jitter.max / 1000.0, + stat->tx.jitter.last / 1000.0, + pj_math_stat_get_stddev(&stat->tx.jitter) / 1000.0 + ); if (len < 1 || len >= end-p) { - *p = '\0'; - return (unsigned)(p-buf); + *p = '\0'; + return (unsigned)(p-buf); } p += len; len = pj_ansi_snprintf(p, end-p, - "%s RTT msec : %7.3f %7.3f %7.3f %7.3f %7.3f\n", - indent, - stat->rtt.min / 1000.0, - stat->rtt.mean / 1000.0, - stat->rtt.max / 1000.0, - stat->rtt.last / 1000.0, - pj_math_stat_get_stddev(&stat->rtt) / 1000.0 - ); + "%s RTT msec : %7.3f %7.3f %7.3f %7.3f %7.3f\n", + indent, + stat->rtt.min / 1000.0, + stat->rtt.mean / 1000.0, + stat->rtt.max / 1000.0, + stat->rtt.last / 1000.0, + pj_math_stat_get_stddev(&stat->rtt) / 1000.0 + ); if (len < 1 || len >= end-p) { - *p = '\0'; - return (unsigned)(p-buf); + *p = '\0'; + return (unsigned)(p-buf); } p += len; @@ -217,678 +216,678 @@ static unsigned dump_media_stat(const char *indent, PJSUA_THIRD_PARTY_STREAM_HAS_GET_STAT) static void dump_media_session(const char *indent, - char *buf, unsigned maxlen, - pjsua_call *call) + char *buf, unsigned maxlen, + pjsua_call *call) { unsigned i; char *p = buf, *end = buf+maxlen; int len; for (i=0; imed_cnt; ++i) { - pjsua_call_media *call_med = &call->media[i]; - pjmedia_rtcp_stat stat; - pj_bool_t has_stat; - pjmedia_transport_info tp_info; - char rem_addr_buf[80]; - char codec_info[32] = {'0'}; - char rx_info[80] = {'\0'}; - char tx_info[80] = {'\0'}; - const char *rem_addr; - const char *dir_str; - const char *media_type_str; - - switch (call_med->type) { - case PJMEDIA_TYPE_AUDIO: - media_type_str = "audio"; - break; - case PJMEDIA_TYPE_VIDEO: - media_type_str = "video"; - break; - case PJMEDIA_TYPE_APPLICATION: - media_type_str = "application"; - break; - default: - media_type_str = "unknown"; - break; - } - - /* Check if the stream is deactivated */ - if (call_med->tp == NULL || - (!call_med->strm.a.stream && !call_med->strm.v.stream)) - { - len = pj_ansi_snprintf(p, end-p, - "%s #%d %s deactivated\n", - indent, i, media_type_str); - if (len < 1 || len >= end-p) { - *p = '\0'; - return; - } - - p += len; - continue; - } - - pjmedia_transport_info_init(&tp_info); - pjmedia_transport_get_info(call_med->tp, &tp_info); - - // rem_addr will contain actual address of RTP originator, instead of - // remote RTP address specified by stream which is fetched from the SDP. - // Please note that we are assuming only one stream per call. - //rem_addr = pj_sockaddr_print(&info.stream_info[i].rem_addr, - // rem_addr_buf, sizeof(rem_addr_buf), 3); - if (pj_sockaddr_has_addr(&tp_info.src_rtp_name)) { - rem_addr = pj_sockaddr_print(&tp_info.src_rtp_name, rem_addr_buf, - sizeof(rem_addr_buf), 3); - } else { - pj_ansi_snprintf(rem_addr_buf, sizeof(rem_addr_buf), "-"); - rem_addr = rem_addr_buf; - } - - if (call_med->dir == PJMEDIA_DIR_NONE) { - /* To handle when the stream that is currently being paused - * (https://github.com/pjsip/pjproject/issues/1079) - */ - dir_str = "inactive"; - } else if (call_med->dir == PJMEDIA_DIR_ENCODING) - dir_str = "sendonly"; - else if (call_med->dir == PJMEDIA_DIR_DECODING) - dir_str = "recvonly"; - else if (call_med->dir == PJMEDIA_DIR_ENCODING_DECODING) - dir_str = "sendrecv"; - else - dir_str = "inactive"; - - if (call_med->type == PJMEDIA_TYPE_AUDIO) { - pjmedia_stream *stream = call_med->strm.a.stream; - pjmedia_stream_info info; - - pjmedia_stream_get_stat(stream, &stat); - has_stat = PJ_TRUE; - - pjmedia_stream_get_info(stream, &info); - pj_ansi_snprintf(codec_info, sizeof(codec_info), " %.*s @%dkHz", - (int)info.fmt.encoding_name.slen, - info.fmt.encoding_name.ptr, - info.fmt.clock_rate / 1000); - pj_ansi_snprintf(rx_info, sizeof(rx_info), "pt=%d,", - info.rx_pt); - pj_ansi_snprintf(tx_info, sizeof(tx_info), "pt=%d, ptime=%d,", - info.tx_pt, - info.param->setting.frm_per_pkt* - info.param->info.frm_ptime); + pjsua_call_media *call_med = &call->media[i]; + pjmedia_rtcp_stat stat; + pj_bool_t has_stat; + pjmedia_transport_info tp_info; + char rem_addr_buf[80]; + char codec_info[32] = {'0'}; + char rx_info[80] = {'\0'}; + char tx_info[80] = {'\0'}; + const char *rem_addr; + const char *dir_str; + const char *media_type_str; + + switch (call_med->type) { + case PJMEDIA_TYPE_AUDIO: + media_type_str = "audio"; + break; + case PJMEDIA_TYPE_VIDEO: + media_type_str = "video"; + break; + case PJMEDIA_TYPE_APPLICATION: + media_type_str = "application"; + break; + default: + media_type_str = "unknown"; + break; + } + + /* Check if the stream is deactivated */ + if (call_med->tp == NULL || + (!call_med->strm.a.stream && !call_med->strm.v.stream)) + { + len = pj_ansi_snprintf(p, end-p, + "%s #%d %s deactivated\n", + indent, i, media_type_str); + if (len < 1 || len >= end-p) { + *p = '\0'; + return; + } + + p += len; + continue; + } + + pjmedia_transport_info_init(&tp_info); + pjmedia_transport_get_info(call_med->tp, &tp_info); + + // rem_addr will contain actual address of RTP originator, instead of + // remote RTP address specified by stream which is fetched from the SDP. + // Please note that we are assuming only one stream per call. + //rem_addr = pj_sockaddr_print(&info.stream_info[i].rem_addr, + // rem_addr_buf, sizeof(rem_addr_buf), 3); + if (pj_sockaddr_has_addr(&tp_info.src_rtp_name)) { + rem_addr = pj_sockaddr_print(&tp_info.src_rtp_name, rem_addr_buf, + sizeof(rem_addr_buf), 3); + } else { + pj_ansi_snprintf(rem_addr_buf, sizeof(rem_addr_buf), "-"); + rem_addr = rem_addr_buf; + } + + if (call_med->dir == PJMEDIA_DIR_NONE) { + /* To handle when the stream that is currently being paused + * (https://github.com/pjsip/pjproject/issues/1079) + */ + dir_str = "inactive"; + } else if (call_med->dir == PJMEDIA_DIR_ENCODING) + dir_str = "sendonly"; + else if (call_med->dir == PJMEDIA_DIR_DECODING) + dir_str = "recvonly"; + else if (call_med->dir == PJMEDIA_DIR_ENCODING_DECODING) + dir_str = "sendrecv"; + else + dir_str = "inactive"; + + if (call_med->type == PJMEDIA_TYPE_AUDIO) { + pjmedia_stream *stream = call_med->strm.a.stream; + pjmedia_stream_info info; + + pjmedia_stream_get_stat(stream, &stat); + has_stat = PJ_TRUE; + + pjmedia_stream_get_info(stream, &info); + pj_ansi_snprintf(codec_info, sizeof(codec_info), " %.*s @%dkHz", + (int)info.fmt.encoding_name.slen, + info.fmt.encoding_name.ptr, + info.fmt.clock_rate / 1000); + pj_ansi_snprintf(rx_info, sizeof(rx_info), "pt=%d,", + info.rx_pt); + pj_ansi_snprintf(tx_info, sizeof(tx_info), "pt=%d, ptime=%d,", + info.tx_pt, + info.param->setting.frm_per_pkt* + info.param->info.frm_ptime); #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) - } else if (call_med->type == PJMEDIA_TYPE_VIDEO) { - pjmedia_vid_stream *stream = call_med->strm.v.stream; - pjmedia_vid_stream_info info; - - pjmedia_vid_stream_get_stat(stream, &stat); - has_stat = PJ_TRUE; - - pjmedia_vid_stream_get_info(stream, &info); - pj_ansi_snprintf(codec_info, sizeof(codec_info), " %.*s", - (int)info.codec_info.encoding_name.slen, - info.codec_info.encoding_name.ptr); - if (call_med->dir & PJMEDIA_DIR_DECODING) { - pjmedia_video_format_detail *vfd; - vfd = pjmedia_format_get_video_format_detail( - &info.codec_param->dec_fmt, PJ_TRUE); - pj_ansi_snprintf(rx_info, sizeof(rx_info), - "pt=%d, size=%dx%d, fps=%.2f,", - info.rx_pt, - vfd->size.w, vfd->size.h, - vfd->fps.num*1.0/vfd->fps.denum); - } - if (call_med->dir & PJMEDIA_DIR_ENCODING) { - pjmedia_video_format_detail *vfd; - vfd = pjmedia_format_get_video_format_detail( - &info.codec_param->enc_fmt, PJ_TRUE); - pj_ansi_snprintf(tx_info, sizeof(tx_info), - "pt=%d, size=%dx%d, fps=%.2f,", - info.tx_pt, - vfd->size.w, vfd->size.h, - vfd->fps.num*1.0/vfd->fps.denum); - } + } else if (call_med->type == PJMEDIA_TYPE_VIDEO) { + pjmedia_vid_stream *stream = call_med->strm.v.stream; + pjmedia_vid_stream_info info; + + pjmedia_vid_stream_get_stat(stream, &stat); + has_stat = PJ_TRUE; + + pjmedia_vid_stream_get_info(stream, &info); + pj_ansi_snprintf(codec_info, sizeof(codec_info), " %.*s", + (int)info.codec_info.encoding_name.slen, + info.codec_info.encoding_name.ptr); + if (call_med->dir & PJMEDIA_DIR_DECODING) { + pjmedia_video_format_detail *vfd; + vfd = pjmedia_format_get_video_format_detail( + &info.codec_param->dec_fmt, PJ_TRUE); + pj_ansi_snprintf(rx_info, sizeof(rx_info), + "pt=%d, size=%dx%d, fps=%.2f,", + info.rx_pt, + vfd->size.w, vfd->size.h, + vfd->fps.num*1.0/vfd->fps.denum); + } + if (call_med->dir & PJMEDIA_DIR_ENCODING) { + pjmedia_video_format_detail *vfd; + vfd = pjmedia_format_get_video_format_detail( + &info.codec_param->enc_fmt, PJ_TRUE); + pj_ansi_snprintf(tx_info, sizeof(tx_info), + "pt=%d, size=%dx%d, fps=%.2f,", + info.tx_pt, + vfd->size.w, vfd->size.h, + vfd->fps.num*1.0/vfd->fps.denum); + } #endif /* PJMEDIA_HAS_VIDEO */ - } else { - has_stat = PJ_FALSE; - } - - len = pj_ansi_snprintf(p, end-p, - "%s #%d %s%s, %s, peer=%s\n", - indent, - call_med->idx, - media_type_str, - codec_info, - dir_str, - rem_addr); - if (len < 1 || len >= end-p) { - *p = '\0'; - return; - } - p += len; - - if (call_med->type == PJMEDIA_TYPE_AUDIO) { - if (pjsua_snd_is_active()) { - pjmedia_echo_stat ec_stat; - pj_status_t status; - - status = pjsua_get_ec_stat(&ec_stat); - if (status == PJ_SUCCESS) { - len = pj_ansi_snprintf(p, end-p, " %s EC stat: %.*s\n", - indent, - (int)ec_stat.stat_info.slen, - ec_stat.stat_info.ptr); - if (len < 1 || len >= end-p) { - *p = '\0'; - return; - } - p += len; - } - } - } - - /* Get and ICE SRTP status */ - if (call_med->tp) { - if (tp_info.specific_info_cnt > 0) { - unsigned j; - for (j = 0; j < tp_info.specific_info_cnt; ++j) { - if (tp_info.spc_info[j].type == PJMEDIA_TRANSPORT_TYPE_SRTP) - { - pjmedia_srtp_info *srtp_info = - (pjmedia_srtp_info*) tp_info.spc_info[j].buffer; - const char *policy_name = srtp_info->tx_policy.name.ptr; - - if (!policy_name) - policy_name = ""; - - len = pj_ansi_snprintf(p, end-p, - " %s SRTP status: %s Crypto-suite: %s", - indent, - (srtp_info->active?"Active":"Not active"), - policy_name); - if (len > 0 && len < end-p) { - p += len; - *p++ = '\n'; - *p = '\0'; - } - } else if (tp_info.spc_info[j].type==PJMEDIA_TRANSPORT_TYPE_ICE) { - const pjmedia_ice_transport_info *ii; - unsigned jj; - - ii = (const pjmedia_ice_transport_info*) - tp_info.spc_info[j].buffer; - - len = pj_ansi_snprintf(p, end-p, - " %s ICE role: %s, state: %s, comp_cnt: %u", - indent, - pj_ice_sess_role_name(ii->role), - pj_ice_strans_state_name(ii->sess_state), - ii->comp_cnt); - if (len > 0 && len < end-p) { - p += len; - *p++ = '\n'; - *p = '\0'; - } - - for (jj=0; ii->sess_state==PJ_ICE_STRANS_STATE_RUNNING && jj<2; ++jj) { - const char *type1 = pj_ice_get_cand_type_name(ii->comp[jj].lcand_type); - const char *type2 = pj_ice_get_cand_type_name(ii->comp[jj].rcand_type); - char addr1[PJ_INET6_ADDRSTRLEN+10]; - char addr2[PJ_INET6_ADDRSTRLEN+10]; - - if (pj_sockaddr_has_addr(&ii->comp[jj].lcand_addr)) - pj_sockaddr_print(&ii->comp[jj].lcand_addr, addr1, sizeof(addr1), 3); - else - strcpy(addr1, "0.0.0.0:0"); - if (pj_sockaddr_has_addr(&ii->comp[jj].rcand_addr)) - pj_sockaddr_print(&ii->comp[jj].rcand_addr, addr2, sizeof(addr2), 3); - else - strcpy(addr2, "0.0.0.0:0"); - len = pj_ansi_snprintf(p, end-p, - " %s [%d]: L:%s (%c) --> R:%s (%c)\n", - indent, jj, - addr1, type1[0], - addr2, type2[0]); - if (len > 0 && len < end-p) { - p += len; - *p = '\0'; - } - } - } - } - } - } - - - if (has_stat) { - len = dump_media_stat(indent, p, (unsigned)(end-p), &stat, - rx_info, tx_info); - p += len; - } + } else { + has_stat = PJ_FALSE; + } + + len = pj_ansi_snprintf(p, end-p, + "%s #%d %s%s, %s, peer=%s\n", + indent, + call_med->idx, + media_type_str, + codec_info, + dir_str, + rem_addr); + if (len < 1 || len >= end-p) { + *p = '\0'; + return; + } + p += len; + + if (call_med->type == PJMEDIA_TYPE_AUDIO) { + if (pjsua_snd_is_active()) { + pjmedia_echo_stat ec_stat; + pj_status_t status; + + status = pjsua_get_ec_stat(&ec_stat); + if (status == PJ_SUCCESS) { + len = pj_ansi_snprintf(p, end-p, " %s EC stat: %.*s\n", + indent, + (int)ec_stat.stat_info.slen, + ec_stat.stat_info.ptr); + if (len < 1 || len >= end-p) { + *p = '\0'; + return; + } + p += len; + } + } + } + + /* Get and ICE SRTP status */ + if (call_med->tp) { + if (tp_info.specific_info_cnt > 0) { + unsigned j; + for (j = 0; j < tp_info.specific_info_cnt; ++j) { + if (tp_info.spc_info[j].type == PJMEDIA_TRANSPORT_TYPE_SRTP) + { + pjmedia_srtp_info *srtp_info = + (pjmedia_srtp_info*) tp_info.spc_info[j].buffer; + const char *policy_name = srtp_info->tx_policy.name.ptr; + + if (!policy_name) + policy_name = ""; + + len = pj_ansi_snprintf(p, end-p, + " %s SRTP status: %s Crypto-suite: %s", + indent, + (srtp_info->active?"Active":"Not active"), + policy_name); + if (len > 0 && len < end-p) { + p += len; + *p++ = '\n'; + *p = '\0'; + } + } else if (tp_info.spc_info[j].type==PJMEDIA_TRANSPORT_TYPE_ICE) { + const pjmedia_ice_transport_info *ii; + unsigned jj; + + ii = (const pjmedia_ice_transport_info*) + tp_info.spc_info[j].buffer; + + len = pj_ansi_snprintf(p, end-p, + " %s ICE role: %s, state: %s, comp_cnt: %u", + indent, + pj_ice_sess_role_name(ii->role), + pj_ice_strans_state_name(ii->sess_state), + ii->comp_cnt); + if (len > 0 && len < end-p) { + p += len; + *p++ = '\n'; + *p = '\0'; + } + + for (jj=0; ii->sess_state==PJ_ICE_STRANS_STATE_RUNNING && jj<2; ++jj) { + const char *type1 = pj_ice_get_cand_type_name(ii->comp[jj].lcand_type); + const char *type2 = pj_ice_get_cand_type_name(ii->comp[jj].rcand_type); + char addr1[PJ_INET6_ADDRSTRLEN+10]; + char addr2[PJ_INET6_ADDRSTRLEN+10]; + + if (pj_sockaddr_has_addr(&ii->comp[jj].lcand_addr)) + pj_sockaddr_print(&ii->comp[jj].lcand_addr, addr1, sizeof(addr1), 3); + else + strcpy(addr1, "0.0.0.0:0"); + if (pj_sockaddr_has_addr(&ii->comp[jj].rcand_addr)) + pj_sockaddr_print(&ii->comp[jj].rcand_addr, addr2, sizeof(addr2), 3); + else + strcpy(addr2, "0.0.0.0:0"); + len = pj_ansi_snprintf(p, end-p, + " %s [%d]: L:%s (%c) --> R:%s (%c)\n", + indent, jj, + addr1, type1[0], + addr2, type2[0]); + if (len > 0 && len < end-p) { + p += len; + *p = '\0'; + } + } + } + } + } + } + + + if (has_stat) { + len = dump_media_stat(indent, p, (unsigned)(end-p), &stat, + rx_info, tx_info); + p += len; + } #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) # define SAMPLES_TO_USEC(usec, samples, clock_rate) \ - do { \ - if (samples <= 4294) \ - usec = samples * 1000000 / clock_rate; \ - else { \ - usec = samples * 1000 / clock_rate; \ - usec *= 1000; \ - } \ - } while(0) + do { \ + if (samples <= 4294) \ + usec = samples * 1000000 / clock_rate; \ + else { \ + usec = samples * 1000 / clock_rate; \ + usec *= 1000; \ + } \ + } while(0) # define PRINT_VOIP_MTC_VAL(s, v) \ - if (v == 127) \ - sprintf(s, "(na)"); \ - else \ - sprintf(s, "%d", v) + if (v == 127) \ + sprintf(s, "(na)"); \ + else \ + sprintf(s, "%d", v) # define VALIDATE_PRINT_BUF() \ - if (len < 1 || len >= end-p) { *p = '\0'; return; } \ - p += len; *p++ = '\n'; *p = '\0' - - - if (call_med->type == PJMEDIA_TYPE_AUDIO) { - pjmedia_stream_info info; - char last_update[64]; - char loss[16], dup[16]; - char jitter[80]; - char toh[80]; - char plc[16], jba[16], jbr[16]; - char signal_lvl[16], noise_lvl[16], rerl[16]; - char r_factor[16], ext_r_factor[16], mos_lq[16], mos_cq[16]; - pjmedia_rtcp_xr_stat xr_stat; - unsigned clock_rate; - pj_time_val now; - - if (pjmedia_stream_get_stat_xr(call_med->strm.a.stream, - &xr_stat) != PJ_SUCCESS) - { - continue; - } - - if (pjmedia_stream_get_info(call_med->strm.a.stream, &info) - != PJ_SUCCESS) - { - continue; - } - - clock_rate = info.fmt.clock_rate; - pj_gettimeofday(&now); - - len = pj_ansi_snprintf(p, end-p, "\n%s Extended reports:", indent); - VALIDATE_PRINT_BUF(); - - /* Statistics Summary */ - len = pj_ansi_snprintf(p, end-p, "%s Statistics Summary", indent); - VALIDATE_PRINT_BUF(); - - if (xr_stat.rx.stat_sum.l) - sprintf(loss, "%d", xr_stat.rx.stat_sum.lost); - else - sprintf(loss, "(na)"); - - if (xr_stat.rx.stat_sum.d) - sprintf(dup, "%d", xr_stat.rx.stat_sum.dup); - else - sprintf(dup, "(na)"); - - if (xr_stat.rx.stat_sum.j) { - unsigned jmin, jmax, jmean, jdev; - - SAMPLES_TO_USEC(jmin, xr_stat.rx.stat_sum.jitter.min, - clock_rate); - SAMPLES_TO_USEC(jmax, xr_stat.rx.stat_sum.jitter.max, - clock_rate); - SAMPLES_TO_USEC(jmean, xr_stat.rx.stat_sum.jitter.mean, - clock_rate); - SAMPLES_TO_USEC(jdev, - pj_math_stat_get_stddev(&xr_stat.rx.stat_sum.jitter), - clock_rate); - sprintf(jitter, "%7.3f %7.3f %7.3f %7.3f", - jmin/1000.0, jmean/1000.0, jmax/1000.0, jdev/1000.0); - } else - sprintf(jitter, "(report not available)"); - - if (xr_stat.rx.stat_sum.t) { - sprintf(toh, "%11d %11d %11d %11d", - xr_stat.rx.stat_sum.toh.min, - xr_stat.rx.stat_sum.toh.mean, - xr_stat.rx.stat_sum.toh.max, - pj_math_stat_get_stddev(&xr_stat.rx.stat_sum.toh)); - } else - sprintf(toh, "(report not available)"); - - if (xr_stat.rx.stat_sum.update.sec == 0) - strcpy(last_update, "never"); - else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, xr_stat.rx.stat_sum.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); - } - - len = pj_ansi_snprintf(p, end-p, - "%s RX last update: %s\n" - "%s begin seq=%d, end seq=%d\n" - "%s pkt loss=%s, dup=%s\n" - "%s (msec) min avg max dev\n" - "%s jitter : %s\n" - "%s toh : %s", - indent, last_update, - indent, - xr_stat.rx.stat_sum.begin_seq, xr_stat.rx.stat_sum.end_seq, - indent, loss, dup, - indent, - indent, jitter, - indent, toh - ); - VALIDATE_PRINT_BUF(); - - if (xr_stat.tx.stat_sum.l) - sprintf(loss, "%d", xr_stat.tx.stat_sum.lost); - else - sprintf(loss, "(na)"); - - if (xr_stat.tx.stat_sum.d) - sprintf(dup, "%d", xr_stat.tx.stat_sum.dup); - else - sprintf(dup, "(na)"); - - if (xr_stat.tx.stat_sum.j) { - unsigned jmin, jmax, jmean, jdev; - - SAMPLES_TO_USEC(jmin, xr_stat.tx.stat_sum.jitter.min, - clock_rate); - SAMPLES_TO_USEC(jmax, xr_stat.tx.stat_sum.jitter.max, - clock_rate); - SAMPLES_TO_USEC(jmean, xr_stat.tx.stat_sum.jitter.mean, - clock_rate); - SAMPLES_TO_USEC(jdev, - pj_math_stat_get_stddev(&xr_stat.tx.stat_sum.jitter), - clock_rate); - sprintf(jitter, "%7.3f %7.3f %7.3f %7.3f", - jmin/1000.0, jmean/1000.0, jmax/1000.0, jdev/1000.0); - } else - sprintf(jitter, "(report not available)"); - - if (xr_stat.tx.stat_sum.t) { - sprintf(toh, "%11d %11d %11d %11d", - xr_stat.tx.stat_sum.toh.min, - xr_stat.tx.stat_sum.toh.mean, - xr_stat.tx.stat_sum.toh.max, - pj_math_stat_get_stddev(&xr_stat.rx.stat_sum.toh)); - } else - sprintf(toh, "(report not available)"); - - if (xr_stat.tx.stat_sum.update.sec == 0) - strcpy(last_update, "never"); - else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, xr_stat.tx.stat_sum.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); - } - - len = pj_ansi_snprintf(p, end-p, - "%s TX last update: %s\n" - "%s begin seq=%d, end seq=%d\n" - "%s pkt loss=%s, dup=%s\n" - "%s (msec) min avg max dev\n" - "%s jitter : %s\n" - "%s toh : %s", - indent, last_update, - indent, - xr_stat.tx.stat_sum.begin_seq, xr_stat.tx.stat_sum.end_seq, - indent, loss, dup, - indent, - indent, jitter, - indent, toh - ); - VALIDATE_PRINT_BUF(); - - - /* VoIP Metrics */ - len = pj_ansi_snprintf(p, end-p, "%s VoIP Metrics", indent); - VALIDATE_PRINT_BUF(); - - PRINT_VOIP_MTC_VAL(signal_lvl, xr_stat.rx.voip_mtc.signal_lvl); - PRINT_VOIP_MTC_VAL(noise_lvl, xr_stat.rx.voip_mtc.noise_lvl); - PRINT_VOIP_MTC_VAL(rerl, xr_stat.rx.voip_mtc.rerl); - PRINT_VOIP_MTC_VAL(r_factor, xr_stat.rx.voip_mtc.r_factor); - PRINT_VOIP_MTC_VAL(ext_r_factor, xr_stat.rx.voip_mtc.ext_r_factor); - PRINT_VOIP_MTC_VAL(mos_lq, xr_stat.rx.voip_mtc.mos_lq); - PRINT_VOIP_MTC_VAL(mos_cq, xr_stat.rx.voip_mtc.mos_cq); - - switch ((xr_stat.rx.voip_mtc.rx_config>>6) & 3) { - case PJMEDIA_RTCP_XR_PLC_DIS: - sprintf(plc, "DISABLED"); - break; - case PJMEDIA_RTCP_XR_PLC_ENH: - sprintf(plc, "ENHANCED"); - break; - case PJMEDIA_RTCP_XR_PLC_STD: - sprintf(plc, "STANDARD"); - break; - case PJMEDIA_RTCP_XR_PLC_UNK: - default: - sprintf(plc, "UNKNOWN"); - break; - } - - switch ((xr_stat.rx.voip_mtc.rx_config>>4) & 3) { - case PJMEDIA_RTCP_XR_JB_FIXED: - sprintf(jba, "FIXED"); - break; - case PJMEDIA_RTCP_XR_JB_ADAPTIVE: - sprintf(jba, "ADAPTIVE"); - break; - default: - sprintf(jba, "UNKNOWN"); - break; - } - - sprintf(jbr, "%d", xr_stat.rx.voip_mtc.rx_config & 0x0F); - - if (xr_stat.rx.voip_mtc.update.sec == 0) - strcpy(last_update, "never"); - else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, xr_stat.rx.voip_mtc.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); - } - - len = pj_ansi_snprintf(p, end-p, - "%s RX last update: %s\n" - "%s packets : loss rate=%d (%.2f%%), discard rate=%d (%.2f%%)\n" - "%s burst : density=%d (%.2f%%), duration=%d%s\n" - "%s gap : density=%d (%.2f%%), duration=%d%s\n" - "%s delay : round trip=%d%s, end system=%d%s\n" - "%s level : signal=%s%s, noise=%s%s, RERL=%s%s\n" - "%s quality : R factor=%s, ext R factor=%s\n" - "%s MOS LQ=%s, MOS CQ=%s\n" - "%s config : PLC=%s, JB=%s, JB rate=%s, Gmin=%d\n" - "%s JB delay : cur=%d%s, max=%d%s, abs max=%d%s", - indent, - last_update, - /* packets */ - indent, - xr_stat.rx.voip_mtc.loss_rate, xr_stat.rx.voip_mtc.loss_rate*100.0/256, - xr_stat.rx.voip_mtc.discard_rate, xr_stat.rx.voip_mtc.discard_rate*100.0/256, - /* burst */ - indent, - xr_stat.rx.voip_mtc.burst_den, xr_stat.rx.voip_mtc.burst_den*100.0/256, - xr_stat.rx.voip_mtc.burst_dur, "ms", - /* gap */ - indent, - xr_stat.rx.voip_mtc.gap_den, xr_stat.rx.voip_mtc.gap_den*100.0/256, - xr_stat.rx.voip_mtc.gap_dur, "ms", - /* delay */ - indent, - xr_stat.rx.voip_mtc.rnd_trip_delay, "ms", - xr_stat.rx.voip_mtc.end_sys_delay, "ms", - /* level */ - indent, - signal_lvl, "dB", - noise_lvl, "dB", - rerl, "", - /* quality */ - indent, - r_factor, ext_r_factor, - indent, - mos_lq, mos_cq, - /* config */ - indent, - plc, jba, jbr, xr_stat.rx.voip_mtc.gmin, - /* JB delay */ - indent, - xr_stat.rx.voip_mtc.jb_nom, "ms", - xr_stat.rx.voip_mtc.jb_max, "ms", - xr_stat.rx.voip_mtc.jb_abs_max, "ms" - ); - VALIDATE_PRINT_BUF(); - - PRINT_VOIP_MTC_VAL(signal_lvl, xr_stat.tx.voip_mtc.signal_lvl); - PRINT_VOIP_MTC_VAL(noise_lvl, xr_stat.tx.voip_mtc.noise_lvl); - PRINT_VOIP_MTC_VAL(rerl, xr_stat.tx.voip_mtc.rerl); - PRINT_VOIP_MTC_VAL(r_factor, xr_stat.tx.voip_mtc.r_factor); - PRINT_VOIP_MTC_VAL(ext_r_factor, xr_stat.tx.voip_mtc.ext_r_factor); - PRINT_VOIP_MTC_VAL(mos_lq, xr_stat.tx.voip_mtc.mos_lq); - PRINT_VOIP_MTC_VAL(mos_cq, xr_stat.tx.voip_mtc.mos_cq); - - switch ((xr_stat.tx.voip_mtc.rx_config>>6) & 3) { - case PJMEDIA_RTCP_XR_PLC_DIS: - sprintf(plc, "DISABLED"); - break; - case PJMEDIA_RTCP_XR_PLC_ENH: - sprintf(plc, "ENHANCED"); - break; - case PJMEDIA_RTCP_XR_PLC_STD: - sprintf(plc, "STANDARD"); - break; - case PJMEDIA_RTCP_XR_PLC_UNK: - default: - sprintf(plc, "unknown"); - break; - } - - switch ((xr_stat.tx.voip_mtc.rx_config>>4) & 3) { - case PJMEDIA_RTCP_XR_JB_FIXED: - sprintf(jba, "FIXED"); - break; - case PJMEDIA_RTCP_XR_JB_ADAPTIVE: - sprintf(jba, "ADAPTIVE"); - break; - default: - sprintf(jba, "unknown"); - break; - } - - sprintf(jbr, "%d", xr_stat.tx.voip_mtc.rx_config & 0x0F); - - if (xr_stat.tx.voip_mtc.update.sec == 0) - strcpy(last_update, "never"); - else { - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, xr_stat.tx.voip_mtc.update); - sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", - now.sec / 3600, - (now.sec % 3600) / 60, - now.sec % 60, - now.msec); - } - - len = pj_ansi_snprintf(p, end-p, - "%s TX last update: %s\n" - "%s packets : loss rate=%d (%.2f%%), discard rate=%d (%.2f%%)\n" - "%s burst : density=%d (%.2f%%), duration=%d%s\n" - "%s gap : density=%d (%.2f%%), duration=%d%s\n" - "%s delay : round trip=%d%s, end system=%d%s\n" - "%s level : signal=%s%s, noise=%s%s, RERL=%s%s\n" - "%s quality : R factor=%s, ext R factor=%s\n" - "%s MOS LQ=%s, MOS CQ=%s\n" - "%s config : PLC=%s, JB=%s, JB rate=%s, Gmin=%d\n" - "%s JB delay : cur=%d%s, max=%d%s, abs max=%d%s", - indent, - last_update, - /* pakcets */ - indent, - xr_stat.tx.voip_mtc.loss_rate, xr_stat.tx.voip_mtc.loss_rate*100.0/256, - xr_stat.tx.voip_mtc.discard_rate, xr_stat.tx.voip_mtc.discard_rate*100.0/256, - /* burst */ - indent, - xr_stat.tx.voip_mtc.burst_den, xr_stat.tx.voip_mtc.burst_den*100.0/256, - xr_stat.tx.voip_mtc.burst_dur, "ms", - /* gap */ - indent, - xr_stat.tx.voip_mtc.gap_den, xr_stat.tx.voip_mtc.gap_den*100.0/256, - xr_stat.tx.voip_mtc.gap_dur, "ms", - /* delay */ - indent, - xr_stat.tx.voip_mtc.rnd_trip_delay, "ms", - xr_stat.tx.voip_mtc.end_sys_delay, "ms", - /* level */ - indent, - signal_lvl, "dB", - noise_lvl, "dB", - rerl, "", - /* quality */ - indent, - r_factor, ext_r_factor, - indent, - mos_lq, mos_cq, - /* config */ - indent, - plc, jba, jbr, xr_stat.tx.voip_mtc.gmin, - /* JB delay */ - indent, - xr_stat.tx.voip_mtc.jb_nom, "ms", - xr_stat.tx.voip_mtc.jb_max, "ms", - xr_stat.tx.voip_mtc.jb_abs_max, "ms" - ); - VALIDATE_PRINT_BUF(); - - - /* RTT delay (by receiver side) */ - len = pj_ansi_snprintf(p, end-p, - "%s RTT (from recv) min avg max last dev", - indent); - VALIDATE_PRINT_BUF(); - len = pj_ansi_snprintf(p, end-p, - "%s RTT msec : %7.3f %7.3f %7.3f %7.3f %7.3f", - indent, - xr_stat.rtt.min / 1000.0, - xr_stat.rtt.mean / 1000.0, - xr_stat.rtt.max / 1000.0, - xr_stat.rtt.last / 1000.0, - pj_math_stat_get_stddev(&xr_stat.rtt) / 1000.0 - ); - VALIDATE_PRINT_BUF(); - } /* if audio */; + if (len < 1 || len >= end-p) { *p = '\0'; return; } \ + p += len; *p++ = '\n'; *p = '\0' + + + if (call_med->type == PJMEDIA_TYPE_AUDIO) { + pjmedia_stream_info info; + char last_update[64]; + char loss[16], dup[16]; + char jitter[80]; + char toh[80]; + char plc[16], jba[16], jbr[16]; + char signal_lvl[16], noise_lvl[16], rerl[16]; + char r_factor[16], ext_r_factor[16], mos_lq[16], mos_cq[16]; + pjmedia_rtcp_xr_stat xr_stat; + unsigned clock_rate; + pj_time_val now; + + if (pjmedia_stream_get_stat_xr(call_med->strm.a.stream, + &xr_stat) != PJ_SUCCESS) + { + continue; + } + + if (pjmedia_stream_get_info(call_med->strm.a.stream, &info) + != PJ_SUCCESS) + { + continue; + } + + clock_rate = info.fmt.clock_rate; + pj_gettimeofday(&now); + + len = pj_ansi_snprintf(p, end-p, "\n%s Extended reports:", indent); + VALIDATE_PRINT_BUF(); + + /* Statistics Summary */ + len = pj_ansi_snprintf(p, end-p, "%s Statistics Summary", indent); + VALIDATE_PRINT_BUF(); + + if (xr_stat.rx.stat_sum.l) + sprintf(loss, "%d", xr_stat.rx.stat_sum.lost); + else + sprintf(loss, "(na)"); + + if (xr_stat.rx.stat_sum.d) + sprintf(dup, "%d", xr_stat.rx.stat_sum.dup); + else + sprintf(dup, "(na)"); + + if (xr_stat.rx.stat_sum.j) { + unsigned jmin, jmax, jmean, jdev; + + SAMPLES_TO_USEC(jmin, xr_stat.rx.stat_sum.jitter.min, + clock_rate); + SAMPLES_TO_USEC(jmax, xr_stat.rx.stat_sum.jitter.max, + clock_rate); + SAMPLES_TO_USEC(jmean, xr_stat.rx.stat_sum.jitter.mean, + clock_rate); + SAMPLES_TO_USEC(jdev, + pj_math_stat_get_stddev(&xr_stat.rx.stat_sum.jitter), + clock_rate); + sprintf(jitter, "%7.3f %7.3f %7.3f %7.3f", + jmin/1000.0, jmean/1000.0, jmax/1000.0, jdev/1000.0); + } else + sprintf(jitter, "(report not available)"); + + if (xr_stat.rx.stat_sum.t) { + sprintf(toh, "%11d %11d %11d %11d", + xr_stat.rx.stat_sum.toh.min, + xr_stat.rx.stat_sum.toh.mean, + xr_stat.rx.stat_sum.toh.max, + pj_math_stat_get_stddev(&xr_stat.rx.stat_sum.toh)); + } else + sprintf(toh, "(report not available)"); + + if (xr_stat.rx.stat_sum.update.sec == 0) + strcpy(last_update, "never"); + else { + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, xr_stat.rx.stat_sum.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); + } + + len = pj_ansi_snprintf(p, end-p, + "%s RX last update: %s\n" + "%s begin seq=%d, end seq=%d\n" + "%s pkt loss=%s, dup=%s\n" + "%s (msec) min avg max dev\n" + "%s jitter : %s\n" + "%s toh : %s", + indent, last_update, + indent, + xr_stat.rx.stat_sum.begin_seq, xr_stat.rx.stat_sum.end_seq, + indent, loss, dup, + indent, + indent, jitter, + indent, toh + ); + VALIDATE_PRINT_BUF(); + + if (xr_stat.tx.stat_sum.l) + sprintf(loss, "%d", xr_stat.tx.stat_sum.lost); + else + sprintf(loss, "(na)"); + + if (xr_stat.tx.stat_sum.d) + sprintf(dup, "%d", xr_stat.tx.stat_sum.dup); + else + sprintf(dup, "(na)"); + + if (xr_stat.tx.stat_sum.j) { + unsigned jmin, jmax, jmean, jdev; + + SAMPLES_TO_USEC(jmin, xr_stat.tx.stat_sum.jitter.min, + clock_rate); + SAMPLES_TO_USEC(jmax, xr_stat.tx.stat_sum.jitter.max, + clock_rate); + SAMPLES_TO_USEC(jmean, xr_stat.tx.stat_sum.jitter.mean, + clock_rate); + SAMPLES_TO_USEC(jdev, + pj_math_stat_get_stddev(&xr_stat.tx.stat_sum.jitter), + clock_rate); + sprintf(jitter, "%7.3f %7.3f %7.3f %7.3f", + jmin/1000.0, jmean/1000.0, jmax/1000.0, jdev/1000.0); + } else + sprintf(jitter, "(report not available)"); + + if (xr_stat.tx.stat_sum.t) { + sprintf(toh, "%11d %11d %11d %11d", + xr_stat.tx.stat_sum.toh.min, + xr_stat.tx.stat_sum.toh.mean, + xr_stat.tx.stat_sum.toh.max, + pj_math_stat_get_stddev(&xr_stat.rx.stat_sum.toh)); + } else + sprintf(toh, "(report not available)"); + + if (xr_stat.tx.stat_sum.update.sec == 0) + strcpy(last_update, "never"); + else { + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, xr_stat.tx.stat_sum.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); + } + + len = pj_ansi_snprintf(p, end-p, + "%s TX last update: %s\n" + "%s begin seq=%d, end seq=%d\n" + "%s pkt loss=%s, dup=%s\n" + "%s (msec) min avg max dev\n" + "%s jitter : %s\n" + "%s toh : %s", + indent, last_update, + indent, + xr_stat.tx.stat_sum.begin_seq, xr_stat.tx.stat_sum.end_seq, + indent, loss, dup, + indent, + indent, jitter, + indent, toh + ); + VALIDATE_PRINT_BUF(); + + + /* VoIP Metrics */ + len = pj_ansi_snprintf(p, end-p, "%s VoIP Metrics", indent); + VALIDATE_PRINT_BUF(); + + PRINT_VOIP_MTC_VAL(signal_lvl, xr_stat.rx.voip_mtc.signal_lvl); + PRINT_VOIP_MTC_VAL(noise_lvl, xr_stat.rx.voip_mtc.noise_lvl); + PRINT_VOIP_MTC_VAL(rerl, xr_stat.rx.voip_mtc.rerl); + PRINT_VOIP_MTC_VAL(r_factor, xr_stat.rx.voip_mtc.r_factor); + PRINT_VOIP_MTC_VAL(ext_r_factor, xr_stat.rx.voip_mtc.ext_r_factor); + PRINT_VOIP_MTC_VAL(mos_lq, xr_stat.rx.voip_mtc.mos_lq); + PRINT_VOIP_MTC_VAL(mos_cq, xr_stat.rx.voip_mtc.mos_cq); + + switch ((xr_stat.rx.voip_mtc.rx_config>>6) & 3) { + case PJMEDIA_RTCP_XR_PLC_DIS: + sprintf(plc, "DISABLED"); + break; + case PJMEDIA_RTCP_XR_PLC_ENH: + sprintf(plc, "ENHANCED"); + break; + case PJMEDIA_RTCP_XR_PLC_STD: + sprintf(plc, "STANDARD"); + break; + case PJMEDIA_RTCP_XR_PLC_UNK: + default: + sprintf(plc, "UNKNOWN"); + break; + } + + switch ((xr_stat.rx.voip_mtc.rx_config>>4) & 3) { + case PJMEDIA_RTCP_XR_JB_FIXED: + sprintf(jba, "FIXED"); + break; + case PJMEDIA_RTCP_XR_JB_ADAPTIVE: + sprintf(jba, "ADAPTIVE"); + break; + default: + sprintf(jba, "UNKNOWN"); + break; + } + + sprintf(jbr, "%d", xr_stat.rx.voip_mtc.rx_config & 0x0F); + + if (xr_stat.rx.voip_mtc.update.sec == 0) + strcpy(last_update, "never"); + else { + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, xr_stat.rx.voip_mtc.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); + } + + len = pj_ansi_snprintf(p, end-p, + "%s RX last update: %s\n" + "%s packets : loss rate=%d (%.2f%%), discard rate=%d (%.2f%%)\n" + "%s burst : density=%d (%.2f%%), duration=%d%s\n" + "%s gap : density=%d (%.2f%%), duration=%d%s\n" + "%s delay : round trip=%d%s, end system=%d%s\n" + "%s level : signal=%s%s, noise=%s%s, RERL=%s%s\n" + "%s quality : R factor=%s, ext R factor=%s\n" + "%s MOS LQ=%s, MOS CQ=%s\n" + "%s config : PLC=%s, JB=%s, JB rate=%s, Gmin=%d\n" + "%s JB delay : cur=%d%s, max=%d%s, abs max=%d%s", + indent, + last_update, + /* packets */ + indent, + xr_stat.rx.voip_mtc.loss_rate, xr_stat.rx.voip_mtc.loss_rate*100.0/256, + xr_stat.rx.voip_mtc.discard_rate, xr_stat.rx.voip_mtc.discard_rate*100.0/256, + /* burst */ + indent, + xr_stat.rx.voip_mtc.burst_den, xr_stat.rx.voip_mtc.burst_den*100.0/256, + xr_stat.rx.voip_mtc.burst_dur, "ms", + /* gap */ + indent, + xr_stat.rx.voip_mtc.gap_den, xr_stat.rx.voip_mtc.gap_den*100.0/256, + xr_stat.rx.voip_mtc.gap_dur, "ms", + /* delay */ + indent, + xr_stat.rx.voip_mtc.rnd_trip_delay, "ms", + xr_stat.rx.voip_mtc.end_sys_delay, "ms", + /* level */ + indent, + signal_lvl, "dB", + noise_lvl, "dB", + rerl, "", + /* quality */ + indent, + r_factor, ext_r_factor, + indent, + mos_lq, mos_cq, + /* config */ + indent, + plc, jba, jbr, xr_stat.rx.voip_mtc.gmin, + /* JB delay */ + indent, + xr_stat.rx.voip_mtc.jb_nom, "ms", + xr_stat.rx.voip_mtc.jb_max, "ms", + xr_stat.rx.voip_mtc.jb_abs_max, "ms" + ); + VALIDATE_PRINT_BUF(); + + PRINT_VOIP_MTC_VAL(signal_lvl, xr_stat.tx.voip_mtc.signal_lvl); + PRINT_VOIP_MTC_VAL(noise_lvl, xr_stat.tx.voip_mtc.noise_lvl); + PRINT_VOIP_MTC_VAL(rerl, xr_stat.tx.voip_mtc.rerl); + PRINT_VOIP_MTC_VAL(r_factor, xr_stat.tx.voip_mtc.r_factor); + PRINT_VOIP_MTC_VAL(ext_r_factor, xr_stat.tx.voip_mtc.ext_r_factor); + PRINT_VOIP_MTC_VAL(mos_lq, xr_stat.tx.voip_mtc.mos_lq); + PRINT_VOIP_MTC_VAL(mos_cq, xr_stat.tx.voip_mtc.mos_cq); + + switch ((xr_stat.tx.voip_mtc.rx_config>>6) & 3) { + case PJMEDIA_RTCP_XR_PLC_DIS: + sprintf(plc, "DISABLED"); + break; + case PJMEDIA_RTCP_XR_PLC_ENH: + sprintf(plc, "ENHANCED"); + break; + case PJMEDIA_RTCP_XR_PLC_STD: + sprintf(plc, "STANDARD"); + break; + case PJMEDIA_RTCP_XR_PLC_UNK: + default: + sprintf(plc, "unknown"); + break; + } + + switch ((xr_stat.tx.voip_mtc.rx_config>>4) & 3) { + case PJMEDIA_RTCP_XR_JB_FIXED: + sprintf(jba, "FIXED"); + break; + case PJMEDIA_RTCP_XR_JB_ADAPTIVE: + sprintf(jba, "ADAPTIVE"); + break; + default: + sprintf(jba, "unknown"); + break; + } + + sprintf(jbr, "%d", xr_stat.tx.voip_mtc.rx_config & 0x0F); + + if (xr_stat.tx.voip_mtc.update.sec == 0) + strcpy(last_update, "never"); + else { + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(now, xr_stat.tx.voip_mtc.update); + sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", + now.sec / 3600, + (now.sec % 3600) / 60, + now.sec % 60, + now.msec); + } + + len = pj_ansi_snprintf(p, end-p, + "%s TX last update: %s\n" + "%s packets : loss rate=%d (%.2f%%), discard rate=%d (%.2f%%)\n" + "%s burst : density=%d (%.2f%%), duration=%d%s\n" + "%s gap : density=%d (%.2f%%), duration=%d%s\n" + "%s delay : round trip=%d%s, end system=%d%s\n" + "%s level : signal=%s%s, noise=%s%s, RERL=%s%s\n" + "%s quality : R factor=%s, ext R factor=%s\n" + "%s MOS LQ=%s, MOS CQ=%s\n" + "%s config : PLC=%s, JB=%s, JB rate=%s, Gmin=%d\n" + "%s JB delay : cur=%d%s, max=%d%s, abs max=%d%s", + indent, + last_update, + /* pakcets */ + indent, + xr_stat.tx.voip_mtc.loss_rate, xr_stat.tx.voip_mtc.loss_rate*100.0/256, + xr_stat.tx.voip_mtc.discard_rate, xr_stat.tx.voip_mtc.discard_rate*100.0/256, + /* burst */ + indent, + xr_stat.tx.voip_mtc.burst_den, xr_stat.tx.voip_mtc.burst_den*100.0/256, + xr_stat.tx.voip_mtc.burst_dur, "ms", + /* gap */ + indent, + xr_stat.tx.voip_mtc.gap_den, xr_stat.tx.voip_mtc.gap_den*100.0/256, + xr_stat.tx.voip_mtc.gap_dur, "ms", + /* delay */ + indent, + xr_stat.tx.voip_mtc.rnd_trip_delay, "ms", + xr_stat.tx.voip_mtc.end_sys_delay, "ms", + /* level */ + indent, + signal_lvl, "dB", + noise_lvl, "dB", + rerl, "", + /* quality */ + indent, + r_factor, ext_r_factor, + indent, + mos_lq, mos_cq, + /* config */ + indent, + plc, jba, jbr, xr_stat.tx.voip_mtc.gmin, + /* JB delay */ + indent, + xr_stat.tx.voip_mtc.jb_nom, "ms", + xr_stat.tx.voip_mtc.jb_max, "ms", + xr_stat.tx.voip_mtc.jb_abs_max, "ms" + ); + VALIDATE_PRINT_BUF(); + + + /* RTT delay (by receiver side) */ + len = pj_ansi_snprintf(p, end-p, + "%s RTT (from recv) min avg max last dev", + indent); + VALIDATE_PRINT_BUF(); + len = pj_ansi_snprintf(p, end-p, + "%s RTT msec : %7.3f %7.3f %7.3f %7.3f %7.3f", + indent, + xr_stat.rtt.min / 1000.0, + xr_stat.rtt.mean / 1000.0, + xr_stat.rtt.max / 1000.0, + xr_stat.rtt.last / 1000.0, + pj_math_stat_get_stddev(&xr_stat.rtt) / 1000.0 + ); + VALIDATE_PRINT_BUF(); + } /* if audio */; #endif } } -#else /* PJSUA_MEDIA_HAS_PJMEDIA || - (PJSUA_THIRD_PARTY_STREAM_HAS_GET_INFO && - PJSUA_THIRD_PARTY_STREAM_HAS_GET_STAT) */ +#else /* PJSUA_MEDIA_HAS_PJMEDIA || + (PJSUA_THIRD_PARTY_STREAM_HAS_GET_INFO && + PJSUA_THIRD_PARTY_STREAM_HAS_GET_STAT) */ static void dump_media_session(const char *indent, - char *buf, unsigned maxlen, - pjsua_call *call) + char *buf, unsigned maxlen, + pjsua_call *call) { PJ_UNUSED_ARG(indent); PJ_UNUSED_ARG(buf); @@ -896,15 +895,15 @@ static void dump_media_session(const char *indent, PJ_UNUSED_ARG(call); } -#endif /* PJSUA_MEDIA_HAS_PJMEDIA || - (PJSUA_THIRD_PARTY_STREAM_HAS_GET_INFO && - PJSUA_THIRD_PARTY_STREAM_HAS_GET_STAT) */ +#endif /* PJSUA_MEDIA_HAS_PJMEDIA || + (PJSUA_THIRD_PARTY_STREAM_HAS_GET_INFO && + PJSUA_THIRD_PARTY_STREAM_HAS_GET_STAT) */ /* Print call info */ void print_call(const char *title, - int call_id, - char *buf, pj_size_t size) + int call_id, + char *buf, pj_size_t size) { int len; pjsua_call *call = &pjsua_var.calls[call_id]; @@ -917,21 +916,21 @@ void print_call(const char *title, dlg = (inv? inv->dlg: call->async_call.dlg); len = pjsip_hdr_print_on(dlg->remote.info, userinfo, sizeof(userinfo)); if (len < 0) - pj_ansi_strcpy(userinfo, "<--uri too long-->"); + pj_ansi_strcpy(userinfo, "<--uri too long-->"); else - userinfo[len] = '\0'; + userinfo[len] = '\0'; len = pj_ansi_snprintf(buf, size, "%s[%s] %s", - title, + title, pjsip_inv_state_name((call->hanging_up || !inv)? PJSIP_INV_STATE_DISCONNECTED: inv->state), - userinfo); + userinfo); if (len < 1 || len >= (int)size) { - pj_ansi_strcpy(buf, "<--uri too long-->"); - len = 18; + pj_ansi_strcpy(buf, "<--uri too long-->"); + len = 18; } else - buf[len] = '\0'; + buf[len] = '\0'; } @@ -939,10 +938,10 @@ void print_call(const char *title, * Dump call and media statistics to string. */ PJ_DEF(pj_status_t) pjsua_call_dump( pjsua_call_id call_id, - pj_bool_t with_media, - char *buffer, - unsigned maxlen, - const char *indent) + pj_bool_t with_media, + char *buffer, + unsigned maxlen, + const char *indent) { pjsua_call *call; pjsip_dialog *dlg; @@ -953,12 +952,12 @@ PJ_DEF(pj_status_t) pjsua_call_dump( pjsua_call_id call_id, int len; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(maxlen > 3, PJ_ETOOSMALL); status = acquire_call("pjsua_call_dump()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - return status; + return status; *buffer = '\0'; p = buffer; @@ -978,43 +977,43 @@ PJ_DEF(pj_status_t) pjsua_call_dump( pjsua_call_id call_id, /* Calculate call duration */ if (call->conn_time.sec != 0) { - pj_gettimeofday(&duration); - PJ_TIME_VAL_SUB(duration, call->conn_time); - con_delay = call->conn_time; - PJ_TIME_VAL_SUB(con_delay, call->start_time); + pj_gettimeofday(&duration); + PJ_TIME_VAL_SUB(duration, call->conn_time); + con_delay = call->conn_time; + PJ_TIME_VAL_SUB(con_delay, call->start_time); } else { - duration.sec = duration.msec = 0; - con_delay.sec = con_delay.msec = 0; + duration.sec = duration.msec = 0; + con_delay.sec = con_delay.msec = 0; } /* Calculate first response delay */ if (call->res_time.sec != 0) { - res_delay = call->res_time; - PJ_TIME_VAL_SUB(res_delay, call->start_time); + res_delay = call->res_time; + PJ_TIME_VAL_SUB(res_delay, call->start_time); } else { - res_delay.sec = res_delay.msec = 0; + res_delay.sec = res_delay.msec = 0; } /* Print duration */ len = pj_ansi_snprintf(p, end-p, - "%s Call time: %02dh:%02dm:%02ds, " - "1st res in %d ms, conn in %dms", - indent, - (int)(duration.sec / 3600), - (int)((duration.sec % 3600)/60), - (int)(duration.sec % 60), - (int)PJ_TIME_VAL_MSEC(res_delay), - (int)PJ_TIME_VAL_MSEC(con_delay)); + "%s Call time: %02dh:%02dm:%02ds, " + "1st res in %d ms, conn in %dms", + indent, + (int)(duration.sec / 3600), + (int)((duration.sec % 3600)/60), + (int)(duration.sec % 60), + (int)PJ_TIME_VAL_MSEC(res_delay), + (int)PJ_TIME_VAL_MSEC(con_delay)); if (len > 0 && len < end-p) { - p += len; - *p++ = '\n'; - *p = '\0'; + p += len; + *p++ = '\n'; + *p = '\0'; } /* Dump session statistics */ if (with_media) - dump_media_session(indent, p, (unsigned)(end-p), call); + dump_media_session(indent, p, (unsigned)(end-p), call); pjsip_dlg_dec_lock(dlg); diff --git a/pjsip/src/pjsua-lib/pjsua_im.c b/pjsip/src/pjsua-lib/pjsua_im.c index 91f907d228..eb8212e301 100644 --- a/pjsip/src/pjsua-lib/pjsua_im.c +++ b/pjsip/src/pjsua-lib/pjsua_im.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -48,25 +47,25 @@ static pj_bool_t im_on_rx_request(pjsip_rx_data *rdata); /* The module instance. */ static pjsip_module mod_pjsua_im = { - NULL, NULL, /* prev, next. */ - { "mod-pjsua-im", 12 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &im_on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-pjsua-im", 12 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &im_on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; /* MIME constants. */ -static const pj_str_t STR_MIME_APP = { "application", 11 }; +static const pj_str_t STR_MIME_APP = { "application", 11 }; static const pj_str_t STR_MIME_ISCOMPOSING = { "im-iscomposing+xml", 18 }; @@ -74,13 +73,13 @@ static const pj_str_t STR_MIME_ISCOMPOSING = { "im-iscomposing+xml", 18 }; #if 0 static pj_bool_t acceptable_message(const pjsip_media_type *mime) { - const pj_str_t STR_MIME_TEXT = { "text", 4 }; - const pj_str_t STR_MIME_PLAIN = { "plain", 5 }; + const pj_str_t STR_MIME_TEXT = { "text", 4 }; + const pj_str_t STR_MIME_PLAIN = { "plain", 5 }; return (pj_stricmp(&mime->type, &STR_MIME_TEXT)==0 && - pj_stricmp(&mime->subtype, &STR_MIME_PLAIN)==0) - || - (pj_stricmp(&mime->type, &STR_MIME_APP)==0 && - pj_stricmp(&mime->subtype, &STR_MIME_ISCOMPOSING)==0); + pj_stricmp(&mime->subtype, &STR_MIME_PLAIN)==0) + || + (pj_stricmp(&mime->type, &STR_MIME_APP)==0 && + pj_stricmp(&mime->subtype, &STR_MIME_ISCOMPOSING)==0); } #endif @@ -104,7 +103,7 @@ pjsip_accept_hdr* pjsua_im_create_accept(pj_pool_t *pool) * Private: check if we can accept the message. */ pj_bool_t pjsua_im_accept_pager(pjsip_rx_data *rdata, - pjsip_accept_hdr **p_accept_hdr) + pjsip_accept_hdr **p_accept_hdr) { /* Some UA sends text/html, so this check will break */ #if 0 @@ -117,26 +116,26 @@ pj_bool_t pjsua_im_accept_pager(pjsip_rx_data *rdata, * "text/plain". */ ctype = (pjsip_ctype_hdr*) - pjsip_msg_find_hdr(msg, PJSIP_H_CONTENT_TYPE, NULL); + pjsip_msg_find_hdr(msg, PJSIP_H_CONTENT_TYPE, NULL); if (msg->body == NULL || ctype == NULL || - !acceptable_message(&ctype->media)) + !acceptable_message(&ctype->media)) { - /* Create Accept header. */ - if (p_accept_hdr) - *p_accept_hdr = pjsua_im_create_accept(rdata->tp_info.pool); + /* Create Accept header. */ + if (p_accept_hdr) + *p_accept_hdr = pjsua_im_create_accept(rdata->tp_info.pool); - return PJ_FALSE; + return PJ_FALSE; } #elif 0 pjsip_msg *msg; msg = rdata->msg_info.msg; if (msg->body == NULL) { - /* Create Accept header. */ - if (p_accept_hdr) - *p_accept_hdr = pjsua_im_create_accept(rdata->tp_info.pool); + /* Create Accept header. */ + if (p_accept_hdr) + *p_accept_hdr = pjsua_im_create_accept(rdata->tp_info.pool); - return PJ_FALSE; + return PJ_FALSE; } #else /* Ticket #693: allow incoming MESSAGE without message body */ @@ -149,10 +148,10 @@ pj_bool_t pjsua_im_accept_pager(pjsip_rx_data *rdata, /** * Private: process pager message. - * This may trigger pjsua_ui_on_pager() or pjsua_ui_on_typing(). + * This may trigger pjsua_ui_on_pager() or pjsua_ui_on_typing(). */ void pjsua_im_process_pager(int call_id, const pj_str_t *from, - const pj_str_t *to, pjsip_rx_data *rdata) + const pj_str_t *to, pjsip_rx_data *rdata) { pjsip_contact_hdr *contact_hdr; pj_str_t contact; @@ -167,104 +166,104 @@ void pjsua_im_process_pager(int call_id, const pj_str_t *from, /* Build remote contact */ contact_hdr = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, - NULL); + pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, + NULL); if (contact_hdr && contact_hdr->uri) { - contact.ptr = (char*) pj_pool_alloc(rdata->tp_info.pool, - PJSIP_MAX_URL_SIZE); - contact.slen = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, - contact_hdr->uri, contact.ptr, - PJSIP_MAX_URL_SIZE); + contact.ptr = (char*) pj_pool_alloc(rdata->tp_info.pool, + PJSIP_MAX_URL_SIZE); + contact.slen = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, + contact_hdr->uri, contact.ptr, + PJSIP_MAX_URL_SIZE); } else { - contact.slen = 0; + contact.slen = 0; } if (body && pj_stricmp(&body->content_type.type, &STR_MIME_APP)==0 && - pj_stricmp(&body->content_type.subtype, &STR_MIME_ISCOMPOSING)==0) + pj_stricmp(&body->content_type.subtype, &STR_MIME_ISCOMPOSING)==0) { - /* Expecting typing indication */ - pj_status_t status; - pj_bool_t is_typing; - - status = pjsip_iscomposing_parse(rdata->tp_info.pool, (char*)body->data, - body->len, &is_typing, NULL, NULL, - NULL ); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Invalid MESSAGE body", status); - return; - } - - if (pjsua_var.ua_cfg.cb.on_typing) { - (*pjsua_var.ua_cfg.cb.on_typing)(call_id, from, to, &contact, - is_typing); - } - - if (pjsua_var.ua_cfg.cb.on_typing2) { - pjsua_acc_id acc_id; - - if (call_id == PJSUA_INVALID_ID) { - acc_id = pjsua_acc_find_for_incoming(rdata); - } else { - pjsua_call *call = &pjsua_var.calls[call_id]; - acc_id = call->acc_id; - } - - if (acc_id != PJSUA_INVALID_ID) { - (*pjsua_var.ua_cfg.cb.on_typing2)(call_id, from, to, &contact, - is_typing, rdata, acc_id); - } - } + /* Expecting typing indication */ + pj_status_t status; + pj_bool_t is_typing; + + status = pjsip_iscomposing_parse(rdata->tp_info.pool, (char*)body->data, + body->len, &is_typing, NULL, NULL, + NULL ); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Invalid MESSAGE body", status); + return; + } + + if (pjsua_var.ua_cfg.cb.on_typing) { + (*pjsua_var.ua_cfg.cb.on_typing)(call_id, from, to, &contact, + is_typing); + } + + if (pjsua_var.ua_cfg.cb.on_typing2) { + pjsua_acc_id acc_id; + + if (call_id == PJSUA_INVALID_ID) { + acc_id = pjsua_acc_find_for_incoming(rdata); + } else { + pjsua_call *call = &pjsua_var.calls[call_id]; + acc_id = call->acc_id; + } + + if (acc_id != PJSUA_INVALID_ID) { + (*pjsua_var.ua_cfg.cb.on_typing2)(call_id, from, to, &contact, + is_typing, rdata, acc_id); + } + } } else { - pj_str_t mime_type; - char buf[256]; - pjsip_media_type *m; - pj_str_t text_body; - - /* Save text body */ - if (body) { - text_body.ptr = (char*)rdata->msg_info.msg->body->data; - text_body.slen = rdata->msg_info.msg->body->len; - - /* Get mime type */ - m = &rdata->msg_info.msg->body->content_type; - mime_type.ptr = buf; - mime_type.slen = pj_ansi_snprintf(buf, sizeof(buf), - "%.*s/%.*s", - (int)m->type.slen, - m->type.ptr, - (int)m->subtype.slen, - m->subtype.ptr); - if (mime_type.slen < 1) - mime_type.slen = 0; - - - } else { - text_body.ptr = mime_type.ptr = ""; - text_body.slen = mime_type.slen = 0; - } - - if (pjsua_var.ua_cfg.cb.on_pager) { - (*pjsua_var.ua_cfg.cb.on_pager)(call_id, from, to, &contact, - &mime_type, &text_body); - } - - if (pjsua_var.ua_cfg.cb.on_pager2) { - pjsua_acc_id acc_id; - - if (call_id == PJSUA_INVALID_ID) { - acc_id = pjsua_acc_find_for_incoming(rdata); - } else { - pjsua_call *call = &pjsua_var.calls[call_id]; - acc_id = call->acc_id; - } - - if (acc_id != PJSUA_INVALID_ID) { - (*pjsua_var.ua_cfg.cb.on_pager2)(call_id, from, to, &contact, - &mime_type, &text_body, rdata, - acc_id); - } - } + pj_str_t mime_type; + char buf[256]; + pjsip_media_type *m; + pj_str_t text_body; + + /* Save text body */ + if (body) { + text_body.ptr = (char*)rdata->msg_info.msg->body->data; + text_body.slen = rdata->msg_info.msg->body->len; + + /* Get mime type */ + m = &rdata->msg_info.msg->body->content_type; + mime_type.ptr = buf; + mime_type.slen = pj_ansi_snprintf(buf, sizeof(buf), + "%.*s/%.*s", + (int)m->type.slen, + m->type.ptr, + (int)m->subtype.slen, + m->subtype.ptr); + if (mime_type.slen < 1) + mime_type.slen = 0; + + + } else { + text_body.ptr = mime_type.ptr = ""; + text_body.slen = mime_type.slen = 0; + } + + if (pjsua_var.ua_cfg.cb.on_pager) { + (*pjsua_var.ua_cfg.cb.on_pager)(call_id, from, to, &contact, + &mime_type, &text_body); + } + + if (pjsua_var.ua_cfg.cb.on_pager2) { + pjsua_acc_id acc_id; + + if (call_id == PJSUA_INVALID_ID) { + acc_id = pjsua_acc_find_for_incoming(rdata); + } else { + pjsua_call *call = &pjsua_var.calls[call_id]; + acc_id = call->acc_id; + } + + if (acc_id != PJSUA_INVALID_ID) { + (*pjsua_var.ua_cfg.cb.on_pager2)(call_id, from, to, &contact, + &mime_type, &text_body, rdata, + acc_id); + } + } } } @@ -282,7 +281,7 @@ static pj_bool_t im_on_rx_request(pjsip_rx_data *rdata) /* Only want to handle MESSAGE requests. */ if (pjsip_method_cmp(&msg->line.req.method, &pjsip_message_method) != 0) { - return PJ_FALSE; + return PJ_FALSE; } @@ -294,22 +293,22 @@ static pj_bool_t im_on_rx_request(pjsip_rx_data *rdata) /* Check if we can accept the message. */ if (!pjsua_im_accept_pager(rdata, &accept_hdr)) { - pjsip_hdr hdr_list; + pjsip_hdr hdr_list; - pj_list_init(&hdr_list); - pj_list_push_back(&hdr_list, accept_hdr); + pj_list_init(&hdr_list); + pj_list_push_back(&hdr_list, accept_hdr); - pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, - PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL, - &hdr_list, NULL); - return PJ_TRUE; + pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, + PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL, + &hdr_list, NULL); + return PJ_TRUE; } /* Respond with 200 first, so that remote doesn't retransmit in case * the UI takes too long to process the message. */ pjsip_endpt_respond( pjsua_var.endpt, NULL, rdata, 200, NULL, - NULL, NULL, NULL); + NULL, NULL, NULL); /* For the source URI, we use Contact header if present, since * Contact header contains the port number information. If this is @@ -317,19 +316,19 @@ static pj_bool_t im_on_rx_request(pjsip_rx_data *rdata) */ from.ptr = (char*)pj_pool_alloc(rdata->tp_info.pool, PJSIP_MAX_URL_SIZE); from.slen = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, - rdata->msg_info.from->uri, - from.ptr, PJSIP_MAX_URL_SIZE); + rdata->msg_info.from->uri, + from.ptr, PJSIP_MAX_URL_SIZE); if (from.slen < 1) - from = pj_str("<--URI is too long-->"); + from = pj_str("<--URI is too long-->"); /* Build the To text. */ to.ptr = (char*) pj_pool_alloc(rdata->tp_info.pool, PJSIP_MAX_URL_SIZE); to.slen = pjsip_uri_print( PJSIP_URI_IN_FROMTO_HDR, - rdata->msg_info.to->uri, - to.ptr, PJSIP_MAX_URL_SIZE); + rdata->msg_info.to->uri, + to.ptr, PJSIP_MAX_URL_SIZE); if (to.slen < 1) - to = pj_str("<--URI is too long-->"); + to = pj_str("<--URI is too long-->"); /* Process pager. */ pjsua_im_process_pager(-1, &from, &to, rdata); @@ -346,119 +345,119 @@ static void im_callback(void *token, pjsip_event *e) if (e->type == PJSIP_EVENT_TSX_STATE) { - pjsip_transaction *tsx = e->body.tsx_state.tsx; + pjsip_transaction *tsx = e->body.tsx_state.tsx; - /* Ignore provisional response, if any */ - if (tsx->status_code < 200) - return; + /* Ignore provisional response, if any */ + if (tsx->status_code < 200) + return; - /* Handle authentication challenges */ - if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG && - (tsx->status_code == 401 || tsx->status_code == 407)) - { - pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; - pjsip_tx_data *tdata; - pjsip_auth_clt_sess auth; - pj_status_t status; + /* Handle authentication challenges */ + if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG && + (tsx->status_code == 401 || tsx->status_code == 407)) + { + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + pjsip_tx_data *tdata; + pjsip_auth_clt_sess auth; + pj_status_t status; - PJ_LOG(4,(THIS_FILE, "Resending IM with authentication")); + PJ_LOG(4,(THIS_FILE, "Resending IM with authentication")); - /* Create temporary authentication session */ - pjsip_auth_clt_init(&auth,pjsua_var.endpt,rdata->tp_info.pool, 0); + /* Create temporary authentication session */ + pjsip_auth_clt_init(&auth,pjsua_var.endpt,rdata->tp_info.pool, 0); - pjsip_auth_clt_set_credentials(&auth, - pjsua_var.acc[im_data->acc_id].cred_cnt, - pjsua_var.acc[im_data->acc_id].cred); - - pjsip_auth_clt_set_prefs(&auth, - &pjsua_var.acc[im_data->acc_id].cfg.auth_pref); - - status = pjsip_auth_clt_reinit_req(&auth, rdata, tsx->last_tx, - &tdata); - if (status == PJ_SUCCESS) { - pjsua_im_data *im_data2; - - /* Must duplicate im_data */ - im_data2 = pjsua_im_data_dup(tdata->pool, im_data); - - /* Increment CSeq */ - PJSIP_MSG_CSEQ_HDR(tdata->msg)->cseq++; - - /* Re-send request */ - status = pjsip_endpt_send_request( pjsua_var.endpt, tdata, -1, - im_data2, &im_callback); - if (status == PJ_SUCCESS) { - /* Done */ - pjsip_auth_clt_deinit(&auth); - return; - } - pjsip_auth_clt_deinit(&auth); - - /* Don't invoke callback if another callback (with auth, - * different tsx) has been called. - */ + pjsip_auth_clt_set_credentials(&auth, + pjsua_var.acc[im_data->acc_id].cred_cnt, + pjsua_var.acc[im_data->acc_id].cred); + + pjsip_auth_clt_set_prefs(&auth, + &pjsua_var.acc[im_data->acc_id].cfg.auth_pref); + + status = pjsip_auth_clt_reinit_req(&auth, rdata, tsx->last_tx, + &tdata); + if (status == PJ_SUCCESS) { + pjsua_im_data *im_data2; + + /* Must duplicate im_data */ + im_data2 = pjsua_im_data_dup(tdata->pool, im_data); + + /* Increment CSeq */ + PJSIP_MSG_CSEQ_HDR(tdata->msg)->cseq++; + + /* Re-send request */ + status = pjsip_endpt_send_request( pjsua_var.endpt, tdata, -1, + im_data2, &im_callback); + if (status == PJ_SUCCESS) { + /* Done */ + pjsip_auth_clt_deinit(&auth); + return; + } + pjsip_auth_clt_deinit(&auth); + + /* Don't invoke callback if another callback (with auth, + * different tsx) has been called. + */ if (im_data2->acc_id == PJSUA_INVALID_ID) return; - } - } - - if (tsx->status_code/100 == 2) { - PJ_LOG(4,(THIS_FILE, - "Message \'%s\' delivered successfully", - im_data->body.ptr)); - } else { - PJ_LOG(3,(THIS_FILE, - "Failed to deliver message \'%s\': %d/%.*s", - im_data->body.ptr, - tsx->status_code, - (int)tsx->status_text.slen, - tsx->status_text.ptr)); - } - - if (pjsua_var.ua_cfg.cb.on_pager_status) { - pj_str_t im_body = im_data->body; - if (im_body.slen==0) { - pjsip_msg_body *body = tsx->last_tx->msg->body; - pj_strset(&im_body, body->data, body->len); - } - - pjsua_var.ua_cfg.cb.on_pager_status(im_data->call_id, - &im_data->to, - &im_body, - im_data->user_data, - (pjsip_status_code) - tsx->status_code, - &tsx->status_text); - } - - if (pjsua_var.ua_cfg.cb.on_pager_status2) { - pjsip_rx_data *rdata; - pj_str_t im_body = im_data->body; - - if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) - rdata = e->body.tsx_state.src.rdata; - else - rdata = NULL; - - if (im_body.slen==0) { - pjsip_msg_body *body = tsx->last_tx->msg->body; - pj_strset(&im_body, body->data, body->len); - } - - pjsua_var.ua_cfg.cb.on_pager_status2(im_data->call_id, - &im_data->to, - &im_body, - im_data->user_data, - (pjsip_status_code) - tsx->status_code, - &tsx->status_text, - tsx->last_tx, - rdata, im_data->acc_id); - } - - /* Reset acc_id after invoking callback */ - im_data->acc_id = PJSUA_INVALID_ID; + } + } + + if (tsx->status_code/100 == 2) { + PJ_LOG(4,(THIS_FILE, + "Message \'%s\' delivered successfully", + im_data->body.ptr)); + } else { + PJ_LOG(3,(THIS_FILE, + "Failed to deliver message \'%s\': %d/%.*s", + im_data->body.ptr, + tsx->status_code, + (int)tsx->status_text.slen, + tsx->status_text.ptr)); + } + + if (pjsua_var.ua_cfg.cb.on_pager_status) { + pj_str_t im_body = im_data->body; + if (im_body.slen==0) { + pjsip_msg_body *body = tsx->last_tx->msg->body; + pj_strset(&im_body, body->data, body->len); + } + + pjsua_var.ua_cfg.cb.on_pager_status(im_data->call_id, + &im_data->to, + &im_body, + im_data->user_data, + (pjsip_status_code) + tsx->status_code, + &tsx->status_text); + } + + if (pjsua_var.ua_cfg.cb.on_pager_status2) { + pjsip_rx_data *rdata; + pj_str_t im_body = im_data->body; + + if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + rdata = e->body.tsx_state.src.rdata; + else + rdata = NULL; + + if (im_body.slen==0) { + pjsip_msg_body *body = tsx->last_tx->msg->body; + pj_strset(&im_body, body->data, body->len); + } + + pjsua_var.ua_cfg.cb.on_pager_status2(im_data->call_id, + &im_data->to, + &im_body, + im_data->user_data, + (pjsip_status_code) + tsx->status_code, + &tsx->status_text, + tsx->last_tx, + rdata, im_data->acc_id); + } + + /* Reset acc_id after invoking callback */ + im_data->acc_id = PJSUA_INVALID_ID; } } @@ -472,55 +471,55 @@ static void typing_callback(void *token, pjsip_event *e) if (e->type == PJSIP_EVENT_TSX_STATE) { - pjsip_transaction *tsx = e->body.tsx_state.tsx; + pjsip_transaction *tsx = e->body.tsx_state.tsx; - /* Ignore provisional response, if any */ - if (tsx->status_code < 200) - return; + /* Ignore provisional response, if any */ + if (tsx->status_code < 200) + return; - /* Handle authentication challenges */ - if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG && - (tsx->status_code == 401 || tsx->status_code == 407)) - { - pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; - pjsip_tx_data *tdata; - pjsip_auth_clt_sess auth; - pj_status_t status; + /* Handle authentication challenges */ + if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG && + (tsx->status_code == 401 || tsx->status_code == 407)) + { + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + pjsip_tx_data *tdata; + pjsip_auth_clt_sess auth; + pj_status_t status; - PJ_LOG(4,(THIS_FILE, "Resending IM with authentication")); + PJ_LOG(4,(THIS_FILE, "Resending IM with authentication")); - /* Create temporary authentication session */ - pjsip_auth_clt_init(&auth,pjsua_var.endpt,rdata->tp_info.pool, 0); + /* Create temporary authentication session */ + pjsip_auth_clt_init(&auth,pjsua_var.endpt,rdata->tp_info.pool, 0); - pjsip_auth_clt_set_credentials(&auth, - pjsua_var.acc[im_data->acc_id].cred_cnt, - pjsua_var.acc[im_data->acc_id].cred); - - pjsip_auth_clt_set_prefs(&auth, - &pjsua_var.acc[im_data->acc_id].cfg.auth_pref); - - status = pjsip_auth_clt_reinit_req(&auth, rdata, tsx->last_tx, - &tdata); - if (status == PJ_SUCCESS) { - pjsua_im_data *im_data2; - - /* Must duplicate im_data */ - im_data2 = pjsua_im_data_dup(tdata->pool, im_data); - - /* Increment CSeq */ - PJSIP_MSG_CSEQ_HDR(tdata->msg)->cseq++; - - /* Re-send request */ - status = pjsip_endpt_send_request( pjsua_var.endpt, tdata, -1, - im_data2, &typing_callback); - if (status == PJ_SUCCESS) { - /* Done */ - pjsip_auth_clt_deinit(&auth); - return; - } - pjsip_auth_clt_deinit(&auth); - } - } + pjsip_auth_clt_set_credentials(&auth, + pjsua_var.acc[im_data->acc_id].cred_cnt, + pjsua_var.acc[im_data->acc_id].cred); + + pjsip_auth_clt_set_prefs(&auth, + &pjsua_var.acc[im_data->acc_id].cfg.auth_pref); + + status = pjsip_auth_clt_reinit_req(&auth, rdata, tsx->last_tx, + &tdata); + if (status == PJ_SUCCESS) { + pjsua_im_data *im_data2; + + /* Must duplicate im_data */ + im_data2 = pjsua_im_data_dup(tdata->pool, im_data); + + /* Increment CSeq */ + PJSIP_MSG_CSEQ_HDR(tdata->msg)->cseq++; + + /* Re-send request */ + status = pjsip_endpt_send_request( pjsua_var.endpt, tdata, -1, + im_data2, &typing_callback); + if (status == PJ_SUCCESS) { + /* Done */ + pjsip_auth_clt_deinit(&auth); + return; + } + pjsip_auth_clt_deinit(&auth); + } + } } } @@ -531,11 +530,11 @@ static void typing_callback(void *token, pjsip_event *e) * route set and authentication. */ PJ_DEF(pj_status_t) pjsua_im_send( pjsua_acc_id acc_id, - const pj_str_t *to, - const pj_str_t *mime_type, - const pj_str_t *content, - const pjsua_msg_data *msg_data, - void *user_data) + const pj_str_t *to, + const pj_str_t *mime_type, + const pj_str_t *content, + const pjsua_msg_data *msg_data, + void *user_data) { pjsip_tx_data *tdata; const pj_str_t mime_text_plain = pj_str("text/plain"); @@ -546,10 +545,10 @@ PJ_DEF(pj_status_t) pjsua_im_send( pjsua_acc_id acc_id, pj_status_t status; PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc), - PJ_EINVAL); + PJ_EINVAL); content_in_msg_data = msg_data && (msg_data->msg_body.slen || - msg_data->multipart_ctype.type.slen); + msg_data->multipart_ctype.type.slen); /* To and message body must be specified. */ PJ_ASSERT_RETURN(to && (content || content_in_msg_data), PJ_EINVAL); @@ -558,29 +557,29 @@ PJ_DEF(pj_status_t) pjsua_im_send( pjsua_acc_id acc_id, /* Create request. */ status = pjsip_endpt_create_request(pjsua_var.endpt, - &pjsip_message_method, + &pjsip_message_method, (msg_data && msg_data->target_uri.slen? &msg_data->target_uri: to), - &acc->cfg.id, - to, NULL, NULL, -1, NULL, &tdata); + &acc->cfg.id, + to, NULL, NULL, -1, NULL, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create request", status); - return status; + pjsua_perror(THIS_FILE, "Unable to create request", status); + return status; } /* If account is locked to specific transport, then set transport to * the request. */ if (acc->cfg.transport_id != PJSUA_INVALID_ID) { - pjsip_tpselector tp_sel; + pjsip_tpselector tp_sel; - pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); - pjsip_tx_data_set_transport(tdata, &tp_sel); + pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); + pjsip_tx_data_set_transport(tdata, &tp_sel); } /* Add accept header. */ pjsip_msg_add_hdr( tdata->msg, - (pjsip_hdr*)pjsua_im_create_accept(tdata->pool)); + (pjsip_hdr*)pjsua_im_create_accept(tdata->pool)); /* Create suitable Contact header unless a Contact header has been * set in the account. @@ -591,19 +590,19 @@ PJ_DEF(pj_status_t) pjsua_im_send( pjsua_acc_id acc_id, */ /* if (acc->contact.slen) { - contact = acc->contact; + contact = acc->contact; } else { - status = pjsua_acc_create_uac_contact(tdata->pool, &contact, acc_id, to); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to generate Contact header", status); - pjsip_tx_data_dec_ref(tdata); - return status; - } + status = pjsua_acc_create_uac_contact(tdata->pool, &contact, acc_id, to); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to generate Contact header", status); + pjsip_tx_data_dec_ref(tdata); + return status; + } } pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) - pjsip_generic_string_hdr_create(tdata->pool, - &STR_CONTACT, &contact)); + pjsip_generic_string_hdr_create(tdata->pool, + &STR_CONTACT, &contact)); */ /* Create IM data to keep message details and give it back to @@ -618,25 +617,25 @@ PJ_DEF(pj_status_t) pjsua_im_send( pjsua_acc_id acc_id, /* Add message body, if content is set */ if (content) { - pj_strdup_with_null(tdata->pool, &im_data->body, content); - - /* Set default media type if none is specified */ - if (mime_type == NULL) { - mime_type = &mime_text_plain; - } - - /* Parse MIME type */ - pjsua_parse_media_type(tdata->pool, mime_type, &media_type); - - /* Add message body */ - tdata->msg->body = pjsip_msg_body_create( tdata->pool, &media_type.type, - &media_type.subtype, - &im_data->body); - if (tdata->msg->body == NULL) { - pjsua_perror(THIS_FILE, "Unable to create msg body", PJ_ENOMEM); - pjsip_tx_data_dec_ref(tdata); - return PJ_ENOMEM; - } + pj_strdup_with_null(tdata->pool, &im_data->body, content); + + /* Set default media type if none is specified */ + if (mime_type == NULL) { + mime_type = &mime_text_plain; + } + + /* Parse MIME type */ + pjsua_parse_media_type(tdata->pool, mime_type, &media_type); + + /* Add message body */ + tdata->msg->body = pjsip_msg_body_create( tdata->pool, &media_type.type, + &media_type.subtype, + &im_data->body); + if (tdata->msg->body == NULL) { + pjsua_perror(THIS_FILE, "Unable to create msg body", PJ_ENOMEM); + pjsip_tx_data_dec_ref(tdata); + return PJ_ENOMEM; + } } /* Add additional headers etc. */ @@ -653,10 +652,10 @@ PJ_DEF(pj_status_t) pjsua_im_send( pjsua_acc_id acc_id, /* Send request (statefully) */ status = pjsip_endpt_send_request( pjsua_var.endpt, tdata, -1, - im_data, &im_callback); + im_data, &im_callback); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send request", status); - return status; + pjsua_perror(THIS_FILE, "Unable to send request", status); + return status; } return PJ_SUCCESS; @@ -667,9 +666,9 @@ PJ_DEF(pj_status_t) pjsua_im_send( pjsua_acc_id acc_id, * Send typing indication outside dialog. */ PJ_DEF(pj_status_t) pjsua_im_typing( pjsua_acc_id acc_id, - const pj_str_t *to, - pj_bool_t is_typing, - const pjsua_msg_data *msg_data) + const pj_str_t *to, + pj_bool_t is_typing, + const pjsua_msg_data *msg_data) { pjsua_im_data *im_data; pjsip_tx_data *tdata; @@ -677,17 +676,17 @@ PJ_DEF(pj_status_t) pjsua_im_typing( pjsua_acc_id acc_id, pj_status_t status; PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc), - PJ_EINVAL); + PJ_EINVAL); acc = &pjsua_var.acc[acc_id]; /* Create request. */ status = pjsip_endpt_create_request( pjsua_var.endpt, &pjsip_message_method, - to, &acc->cfg.id, - to, NULL, NULL, -1, NULL, &tdata); + to, &acc->cfg.id, + to, NULL, NULL, -1, NULL, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create request", status); - return status; + pjsua_perror(THIS_FILE, "Unable to create request", status); + return status; } @@ -695,15 +694,15 @@ PJ_DEF(pj_status_t) pjsua_im_typing( pjsua_acc_id acc_id, * the request. */ if (acc->cfg.transport_id != PJSUA_INVALID_ID) { - pjsip_tpselector tp_sel; + pjsip_tpselector tp_sel; - pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); - pjsip_tx_data_set_transport(tdata, &tp_sel); + pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); + pjsip_tx_data_set_transport(tdata, &tp_sel); } /* Add accept header. */ pjsip_msg_add_hdr( tdata->msg, - (pjsip_hdr*)pjsua_im_create_accept(tdata->pool)); + (pjsip_hdr*)pjsua_im_create_accept(tdata->pool)); /* Create suitable Contact header unless a Contact header has been @@ -715,24 +714,24 @@ PJ_DEF(pj_status_t) pjsua_im_typing( pjsua_acc_id acc_id, */ /* if (acc->contact.slen) { - contact = acc->contact; + contact = acc->contact; } else { - status = pjsua_acc_create_uac_contact(tdata->pool, &contact, acc_id, to); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to generate Contact header", status); - pjsip_tx_data_dec_ref(tdata); - return status; - } + status = pjsua_acc_create_uac_contact(tdata->pool, &contact, acc_id, to); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to generate Contact header", status); + pjsip_tx_data_dec_ref(tdata); + return status; + } } pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*) - pjsip_generic_string_hdr_create(tdata->pool, - &STR_CONTACT, &contact)); + pjsip_generic_string_hdr_create(tdata->pool, + &STR_CONTACT, &contact)); */ /* Create "application/im-iscomposing+xml" msg body. */ tdata->msg->body = pjsip_iscomposing_create_body( tdata->pool, is_typing, - NULL, NULL, -1); + NULL, NULL, -1); /* Add additional headers etc. */ pjsua_process_msg_data(tdata, msg_data); @@ -752,10 +751,10 @@ PJ_DEF(pj_status_t) pjsua_im_typing( pjsua_acc_id acc_id, /* Send request (statefully) */ status = pjsip_endpt_send_request( pjsua_var.endpt, tdata, -1, - im_data, &typing_callback); + im_data, &typing_callback); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send request", status); - return status; + pjsua_perror(THIS_FILE, "Unable to send request", status); + return status; } return PJ_SUCCESS; @@ -770,25 +769,25 @@ pj_status_t pjsua_im_init(void) const pj_str_t msg_tag = { "MESSAGE", 7 }; const pj_str_t STR_MIME_TEXT_PLAIN = { "text/plain", 10 }; const pj_str_t STR_MIME_APP_ISCOMPOSING = - { "application/im-iscomposing+xml", 30 }; + { "application/im-iscomposing+xml", 30 }; pj_status_t status; /* Register module */ status = pjsip_endpt_register_module(pjsua_var.endpt, &mod_pjsua_im); if (status != PJ_SUCCESS) - return status; + return status; /* Register support for MESSAGE method. */ pjsip_endpt_add_capability( pjsua_var.endpt, &mod_pjsua_im, PJSIP_H_ALLOW, - NULL, 1, &msg_tag); + NULL, 1, &msg_tag); /* Register support for "application/im-iscomposing+xml" content */ pjsip_endpt_add_capability( pjsua_var.endpt, &mod_pjsua_im, PJSIP_H_ACCEPT, - NULL, 1, &STR_MIME_APP_ISCOMPOSING); + NULL, 1, &STR_MIME_APP_ISCOMPOSING); /* Register support for "text/plain" content */ pjsip_endpt_add_capability( pjsua_var.endpt, &mod_pjsua_im, PJSIP_H_ACCEPT, - NULL, 1, &STR_MIME_TEXT_PLAIN); + NULL, 1, &STR_MIME_TEXT_PLAIN); return PJ_SUCCESS; } diff --git a/pjsip/src/pjsua-lib/pjsua_media.c b/pjsip/src/pjsua-lib/pjsua_media.c index 7cd44b4de3..72814bd2ca 100644 --- a/pjsip/src/pjsua-lib/pjsua_media.c +++ b/pjsip/src/pjsua-lib/pjsua_media.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,28 +20,28 @@ #include -#define THIS_FILE "pjsua_media.c" +#define THIS_FILE "pjsua_media.c" #ifndef PJSUA_REQUIRE_CONSECUTIVE_RTCP_PORT -# define PJSUA_REQUIRE_CONSECUTIVE_RTCP_PORT 0 +# define PJSUA_REQUIRE_CONSECUTIVE_RTCP_PORT 0 #endif #ifndef PJSUA_RESET_SRTP_ROC_ON_REM_ADDRESS_CHANGE -# define PJSUA_RESET_SRTP_ROC_ON_REM_ADDRESS_CHANGE 0 +# define PJSUA_RESET_SRTP_ROC_ON_REM_ADDRESS_CHANGE 0 #endif static void stop_media_stream(pjsua_call *call, unsigned med_idx); static void pjsua_media_config_dup(pj_pool_t *pool, - pjsua_media_config *dst, - const pjsua_media_config *src) + pjsua_media_config *dst, + const pjsua_media_config *src) { pj_memcpy(dst, src, sizeof(*src)); pj_strdup(pool, &dst->turn_server, &src->turn_server); pj_stun_auth_cred_dup(pool, &dst->turn_auth_cred, &src->turn_auth_cred); #if PJ_HAS_SSL_SOCK pj_turn_sock_tls_cfg_dup(pool, &dst->turn_tls_setting, - &src->turn_tls_setting); + &src->turn_tls_setting); #endif } @@ -60,54 +59,54 @@ pj_status_t pjsua_media_subsys_init(const pjsua_media_config *cfg) pjsua_var.aud_svmask = 0xFFFFFFFF; /* These are not-settable */ pjsua_var.aud_svmask &= ~(PJMEDIA_AUD_DEV_CAP_EXT_FORMAT | - PJMEDIA_AUD_DEV_CAP_INPUT_SIGNAL_METER | - PJMEDIA_AUD_DEV_CAP_OUTPUT_SIGNAL_METER); + PJMEDIA_AUD_DEV_CAP_INPUT_SIGNAL_METER | + PJMEDIA_AUD_DEV_CAP_OUTPUT_SIGNAL_METER); /* EC settings use different API */ pjsua_var.aud_svmask &= ~(PJMEDIA_AUD_DEV_CAP_EC | - PJMEDIA_AUD_DEV_CAP_EC_TAIL); + PJMEDIA_AUD_DEV_CAP_EC_TAIL); /* Copy configuration */ pjsua_media_config_dup(pjsua_var.pool, &pjsua_var.media_cfg, cfg); /* Normalize configuration */ if (pjsua_var.media_cfg.snd_clock_rate == 0) { - pjsua_var.media_cfg.snd_clock_rate = pjsua_var.media_cfg.clock_rate; + pjsua_var.media_cfg.snd_clock_rate = pjsua_var.media_cfg.clock_rate; } if (pjsua_var.media_cfg.has_ioqueue && - pjsua_var.media_cfg.thread_cnt == 0) + pjsua_var.media_cfg.thread_cnt == 0) { - pjsua_var.media_cfg.thread_cnt = 1; + pjsua_var.media_cfg.thread_cnt = 1; } if (pjsua_var.media_cfg.max_media_ports < pjsua_var.ua_cfg.max_calls) { - pjsua_var.media_cfg.max_media_ports = pjsua_var.ua_cfg.max_calls + 2; + pjsua_var.media_cfg.max_media_ports = pjsua_var.ua_cfg.max_calls + 2; } /* Create media endpoint. */ status = pjmedia_endpt_create(&pjsua_var.cp.factory, - pjsua_var.media_cfg.has_ioqueue? NULL : - pjsip_endpt_get_ioqueue(pjsua_var.endpt), - pjsua_var.media_cfg.thread_cnt, - &pjsua_var.med_endpt); + pjsua_var.media_cfg.has_ioqueue? NULL : + pjsip_endpt_get_ioqueue(pjsua_var.endpt), + pjsua_var.media_cfg.thread_cnt, + &pjsua_var.med_endpt); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Media stack initialization has returned error", - status); - goto on_error; + pjsua_perror(THIS_FILE, + "Media stack initialization has returned error", + status); + goto on_error; } status = pjsua_aud_subsys_init(); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) /* Initialize SRTP library (ticket #788). */ status = pjmedia_srtp_init_lib(pjsua_var.med_endpt); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error initializing SRTP library", - status); - goto on_error; + pjsua_perror(THIS_FILE, "Error initializing SRTP library", + status); + goto on_error; } #endif @@ -115,17 +114,17 @@ pj_status_t pjsua_media_subsys_init(const pjsua_media_config *cfg) #if PJMEDIA_HAS_VIDEO status = pjsua_vid_subsys_init(); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; #endif /* Create event manager */ if (!pjmedia_event_mgr_instance()) { - status = pjmedia_event_mgr_create(pjsua_var.pool, 0, NULL); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating PJMEDIA event manager", - status); - goto on_error; - } + status = pjmedia_event_mgr_create(pjsua_var.pool, 0, NULL); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error creating PJMEDIA event manager", + status); + goto on_error; + } } pj_log_pop_indent(); @@ -148,34 +147,34 @@ pj_status_t pjsua_media_subsys_start(void) #if DISABLED_FOR_TICKET_1185 /* Create media for calls, if none is specified */ if (pjsua_var.calls[0].media[0].tp == NULL) { - pjsua_transport_config transport_cfg; + pjsua_transport_config transport_cfg; - /* Create default transport config */ - pjsua_transport_config_default(&transport_cfg); - transport_cfg.port = DEFAULT_RTP_PORT; + /* Create default transport config */ + pjsua_transport_config_default(&transport_cfg); + transport_cfg.port = DEFAULT_RTP_PORT; - status = pjsua_media_transports_create(&transport_cfg); - if (status != PJ_SUCCESS) { - pj_log_pop_indent(); - return status; - } + status = pjsua_media_transports_create(&transport_cfg); + if (status != PJ_SUCCESS) { + pj_log_pop_indent(); + return status; + } } #endif /* Audio */ status = pjsua_aud_subsys_start(); if (status != PJ_SUCCESS) { - pj_log_pop_indent(); - return status; + pj_log_pop_indent(); + return status; } /* Video */ #if PJMEDIA_HAS_VIDEO status = pjsua_vid_subsys_start(); if (status != PJ_SUCCESS) { - pjsua_aud_subsys_destroy(); - pj_log_pop_indent(); - return status; + pjsua_aud_subsys_destroy(); + pj_log_pop_indent(); + return status; } #endif @@ -183,10 +182,10 @@ pj_status_t pjsua_media_subsys_start(void) // Performed only when STUN server resolution by pjsua_init() completed // successfully (see ticket #1865). //if (pjsua_var.ua_cfg.stun_srv_cnt) { - //status = pjsua_detect_nat_type(); - //if (status != PJ_SUCCESS) { - // PJ_PERROR(1,(THIS_FILE, status, "NAT type detection failed")); - //} + //status = pjsua_detect_nat_type(); + //if (status != PJ_SUCCESS) { + // PJ_PERROR(1,(THIS_FILE, status, "NAT type detection failed")); + //} //} pj_log_pop_indent(); @@ -208,7 +207,7 @@ pj_status_t pjsua_media_subsys_destroy(unsigned flags) /* Wait for media endpoint's worker threads to quit. */ pjmedia_endpt_stop_threads(pjsua_var.med_endpt); - pjsua_aud_subsys_destroy(); + pjsua_aud_subsys_destroy(); } #if 0 @@ -218,29 +217,29 @@ pj_status_t pjsua_media_subsys_destroy(unsigned flags) /* TODO: check if we're not allowed to send to network in the * "flags", and if so do not do TURN allocation... */ - PJ_UNUSED_ARG(flags); - pjsua_media_channel_deinit(i); + PJ_UNUSED_ARG(flags); + pjsua_media_channel_deinit(i); } #endif /* Destroy media endpoint. */ if (pjsua_var.med_endpt) { -# if PJMEDIA_HAS_VIDEO - pjsua_vid_subsys_destroy(); -# endif +# if PJMEDIA_HAS_VIDEO + pjsua_vid_subsys_destroy(); +# endif - pjmedia_endpt_destroy(pjsua_var.med_endpt); - pjsua_var.med_endpt = NULL; + pjmedia_endpt_destroy(pjsua_var.med_endpt); + pjsua_var.med_endpt = NULL; - /* Deinitialize sound subsystem */ - // Not necessary, as pjmedia_snd_deinit() should have been called - // in pjmedia_endpt_destroy(). - //pjmedia_snd_deinit(); + /* Deinitialize sound subsystem */ + // Not necessary, as pjmedia_snd_deinit() should have been called + // in pjmedia_endpt_destroy(). + //pjmedia_snd_deinit(); } if (pjmedia_event_mgr_instance()) - pjmedia_event_mgr_destroy(NULL); + pjmedia_event_mgr_destroy(NULL); pj_log_pop_indent(); @@ -252,11 +251,11 @@ pj_status_t pjsua_media_subsys_destroy(unsigned flags) * address via STUN/UPnP. */ static pj_status_t create_rtp_rtcp_sock(pjsua_call_media *call_med, - const pjsua_transport_config *cfg, - pjmedia_sock_info *skinfo) + const pjsua_transport_config *cfg, + pjmedia_sock_info *skinfo) { enum { - RTP_RETRY = 100 + RTP_RETRY = 100 }; int i; pj_bool_t use_ipv6, use_nat64; @@ -276,37 +275,37 @@ static pj_status_t create_rtp_rtcp_sock(pjsua_call_media *call_med, if ((!use_ipv6 || use_nat64) && pjsua_media_acc_is_using_stun(call_med->call->acc_id)) { - pj_bool_t retry_stun = (acc->cfg.media_stun_use & - PJSUA_STUN_RETRY_ON_FAILURE) == - PJSUA_STUN_RETRY_ON_FAILURE; - status = resolve_stun_server(PJ_TRUE, retry_stun, - (unsigned)acc->cfg.nat64_opt); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error resolving STUN server", status); - return status; - } + pj_bool_t retry_stun = (acc->cfg.media_stun_use & + PJSUA_STUN_RETRY_ON_FAILURE) == + PJSUA_STUN_RETRY_ON_FAILURE; + status = resolve_stun_server(PJ_TRUE, retry_stun, + (unsigned)acc->cfg.nat64_opt); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error resolving STUN server", status); + return status; + } } if (acc->next_rtp_port == 0 || cfg->port == 0) { - if (cfg->port != 0 && cfg->port_range != 0 && cfg->randomize_port) { - unsigned offset = ((pj_rand() % (cfg->port_range)) / 2) * 2; - acc->next_rtp_port = (pj_uint16_t)(cfg->port + offset); - } else { - acc->next_rtp_port = (pj_uint16_t)cfg->port; - } + if (cfg->port != 0 && cfg->port_range != 0 && cfg->randomize_port) { + unsigned offset = ((pj_rand() % (cfg->port_range)) / 2) * 2; + acc->next_rtp_port = (pj_uint16_t)(cfg->port + offset); + } else { + acc->next_rtp_port = (pj_uint16_t)cfg->port; + } } for (i=0; i<2; ++i) - sock[i] = PJ_INVALID_SOCKET; + sock[i] = PJ_INVALID_SOCKET; pj_sockaddr_init(af, &bound_addr, NULL, 0); if (cfg->bound_addr.slen) { - status = pj_sockaddr_set_str_addr(af, &bound_addr, &cfg->bound_addr); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to resolve transport bind address", - status); - return status; - } + status = pj_sockaddr_set_str_addr(af, &bound_addr, &cfg->bound_addr); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to resolve transport bind address", + status); + return status; + } } /* Loop retry to bind RTP and RTCP sockets. */ @@ -319,328 +318,328 @@ static pj_status_t create_rtp_rtcp_sock(pjsua_call_media *call_med, acc->next_rtp_port = (pj_uint16_t)cfg->port; } - /* Create RTP socket. */ - status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &sock[0]); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "socket() error", status); - return status; - } - - /* Apply QoS to RTP socket, if specified */ - status = pj_sock_apply_qos2(sock[0], cfg->qos_type, - &cfg->qos_params, - 2, THIS_FILE, "RTP socket"); - - /* Apply sockopt, if specified */ - if (cfg->sockopt_params.cnt) - status = pj_sock_setsockopt_params(sock[0], &cfg->sockopt_params); - - /* Bind RTP socket */ - pj_sockaddr_set_port(&bound_addr, acc->next_rtp_port); - status=pj_sock_bind(sock[0], &bound_addr, - pj_sockaddr_get_len(&bound_addr)); - if (status != PJ_SUCCESS) { - pj_sock_close(sock[0]); - sock[0] = PJ_INVALID_SOCKET; - PJ_PERROR(1,(THIS_FILE, status, "RTP socket bind() at %s error", - pj_sockaddr_print(&bound_addr, addr_buf, - sizeof(addr_buf), 3))); - continue; - } - - /* If bound to random port, find out the port number. */ - if (acc->next_rtp_port == 0) { - pj_sockaddr sock_addr; - int addr_len = sizeof(pj_sockaddr); + /* Create RTP socket. */ + status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &sock[0]); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "socket() error", status); + return status; + } + + /* Apply QoS to RTP socket, if specified */ + status = pj_sock_apply_qos2(sock[0], cfg->qos_type, + &cfg->qos_params, + 2, THIS_FILE, "RTP socket"); + + /* Apply sockopt, if specified */ + if (cfg->sockopt_params.cnt) + status = pj_sock_setsockopt_params(sock[0], &cfg->sockopt_params); + + /* Bind RTP socket */ + pj_sockaddr_set_port(&bound_addr, acc->next_rtp_port); + status=pj_sock_bind(sock[0], &bound_addr, + pj_sockaddr_get_len(&bound_addr)); + if (status != PJ_SUCCESS) { + pj_sock_close(sock[0]); + sock[0] = PJ_INVALID_SOCKET; + PJ_PERROR(1,(THIS_FILE, status, "RTP socket bind() at %s error", + pj_sockaddr_print(&bound_addr, addr_buf, + sizeof(addr_buf), 3))); + continue; + } + + /* If bound to random port, find out the port number. */ + if (acc->next_rtp_port == 0) { + pj_sockaddr sock_addr; + int addr_len = sizeof(pj_sockaddr); status = pj_sock_getsockname(sock[0], &sock_addr, &addr_len); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "getsockname() error", status); - pj_sock_close(sock[0]); - return status; - } - acc->next_rtp_port = pj_sockaddr_get_port(&sock_addr); - } - - /* Create RTCP socket. */ - status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &sock[1]); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "socket() error", status); - pj_sock_close(sock[0]); - return status; - } - - /* Apply QoS to RTCP socket, if specified */ - status = pj_sock_apply_qos2(sock[1], cfg->qos_type, - &cfg->qos_params, - 2, THIS_FILE, "RTCP socket"); - - /* Apply sockopt, if specified */ - if (cfg->sockopt_params.cnt) - status = pj_sock_setsockopt_params(sock[1], &cfg->sockopt_params); - - /* Bind RTCP socket */ - pj_sockaddr_set_port(&bound_addr, (pj_uint16_t)(acc->next_rtp_port+1)); - status=pj_sock_bind(sock[1], &bound_addr, - pj_sockaddr_get_len(&bound_addr)); - if (status != PJ_SUCCESS) { - pj_sock_close(sock[0]); - sock[0] = PJ_INVALID_SOCKET; - - pj_sock_close(sock[1]); - sock[1] = PJ_INVALID_SOCKET; - - PJ_PERROR(1,(THIS_FILE, status, "RTCP socket bind() at %s error", - pj_sockaddr_print(&bound_addr, addr_buf, - sizeof(addr_buf), 3))); - continue; - } - - /* - * If we're configured to use STUN, then find out the mapped address, - * and make sure that the mapped RTCP port is adjacent with the RTP. - */ - if ((!use_ipv6 || use_nat64) && - pjsua_media_acc_is_using_stun(call_med->call->acc_id) && - pjsua_var.stun_srv.addr.sa_family != 0) - { - char ip_addr[PJ_INET6_ADDRSTRLEN]; - pj_str_t stun_srv; - pj_sockaddr_in resolved_addr[2]; - pjstun_setting stun_opt; - - pj_sockaddr_print(&pjsua_var.stun_srv, ip_addr,sizeof(ip_addr),0); - stun_srv = pj_str(ip_addr); - - pj_bzero(&stun_opt, sizeof(stun_opt)); - stun_opt.use_stun2 = pjsua_var.ua_cfg.stun_map_use_stun2; - stun_opt.af = pjsua_var.stun_srv.addr.sa_family; - stun_opt.srv1 = stun_opt.srv2 = stun_srv; - stun_opt.port1 = stun_opt.port2 = - pj_sockaddr_get_port(&pjsua_var.stun_srv); - status=pjstun_get_mapped_addr2(&pjsua_var.cp.factory, &stun_opt, - 2, sock, resolved_addr); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "getsockname() error", status); + pj_sock_close(sock[0]); + return status; + } + acc->next_rtp_port = pj_sockaddr_get_port(&sock_addr); + } + + /* Create RTCP socket. */ + status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &sock[1]); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "socket() error", status); + pj_sock_close(sock[0]); + return status; + } + + /* Apply QoS to RTCP socket, if specified */ + status = pj_sock_apply_qos2(sock[1], cfg->qos_type, + &cfg->qos_params, + 2, THIS_FILE, "RTCP socket"); + + /* Apply sockopt, if specified */ + if (cfg->sockopt_params.cnt) + status = pj_sock_setsockopt_params(sock[1], &cfg->sockopt_params); + + /* Bind RTCP socket */ + pj_sockaddr_set_port(&bound_addr, (pj_uint16_t)(acc->next_rtp_port+1)); + status=pj_sock_bind(sock[1], &bound_addr, + pj_sockaddr_get_len(&bound_addr)); + if (status != PJ_SUCCESS) { + pj_sock_close(sock[0]); + sock[0] = PJ_INVALID_SOCKET; + + pj_sock_close(sock[1]); + sock[1] = PJ_INVALID_SOCKET; + + PJ_PERROR(1,(THIS_FILE, status, "RTCP socket bind() at %s error", + pj_sockaddr_print(&bound_addr, addr_buf, + sizeof(addr_buf), 3))); + continue; + } + + /* + * If we're configured to use STUN, then find out the mapped address, + * and make sure that the mapped RTCP port is adjacent with the RTP. + */ + if ((!use_ipv6 || use_nat64) && + pjsua_media_acc_is_using_stun(call_med->call->acc_id) && + pjsua_var.stun_srv.addr.sa_family != 0) + { + char ip_addr[PJ_INET6_ADDRSTRLEN]; + pj_str_t stun_srv; + pj_sockaddr_in resolved_addr[2]; + pjstun_setting stun_opt; + + pj_sockaddr_print(&pjsua_var.stun_srv, ip_addr,sizeof(ip_addr),0); + stun_srv = pj_str(ip_addr); + + pj_bzero(&stun_opt, sizeof(stun_opt)); + stun_opt.use_stun2 = pjsua_var.ua_cfg.stun_map_use_stun2; + stun_opt.af = pjsua_var.stun_srv.addr.sa_family; + stun_opt.srv1 = stun_opt.srv2 = stun_srv; + stun_opt.port1 = stun_opt.port2 = + pj_sockaddr_get_port(&pjsua_var.stun_srv); + status=pjstun_get_mapped_addr2(&pjsua_var.cp.factory, &stun_opt, + 2, sock, resolved_addr); #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ - PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 - /* Handle EPIPE (Broken Pipe) error, which happens on UDP socket - * after app wakes up from suspended state. In this case, simply - * just retry. - * P.S.: The magic status is PJ_STATUS_FROM_OS(EPIPE) - */ - if (status == 120032) { - PJ_LOG(4,(THIS_FILE, "Got EPIPE error, retrying..")); - pj_sock_close(sock[0]); - sock[0] = PJ_INVALID_SOCKET; - - pj_sock_close(sock[1]); - sock[1] = PJ_INVALID_SOCKET; - - continue; - } - else + PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 + /* Handle EPIPE (Broken Pipe) error, which happens on UDP socket + * after app wakes up from suspended state. In this case, simply + * just retry. + * P.S.: The magic status is PJ_STATUS_FROM_OS(EPIPE) + */ + if (status == 120032) { + PJ_LOG(4,(THIS_FILE, "Got EPIPE error, retrying..")); + pj_sock_close(sock[0]); + sock[0] = PJ_INVALID_SOCKET; + + pj_sock_close(sock[1]); + sock[1] = PJ_INVALID_SOCKET; + + continue; + } + else #endif - if (status != PJ_SUCCESS && pjsua_var.ua_cfg.stun_srv_cnt > 1 && - ((acc->cfg.media_stun_use & PJSUA_STUN_RETRY_ON_FAILURE)== - PJSUA_STUN_RETRY_ON_FAILURE)) - { - pj_str_t srv = - pjsua_var.ua_cfg.stun_srv[pjsua_var.stun_srv_idx]; - - PJ_LOG(4,(THIS_FILE, "Failed to get STUN mapped address, " - "retrying other STUN servers")); - - if (pjsua_var.stun_srv_idx < pjsua_var.ua_cfg.stun_srv_cnt-1) { - PJSUA_LOCK(); - /* Move the unusable STUN server to the last position - * as the least prioritize. - */ - pj_array_erase(pjsua_var.ua_cfg.stun_srv, - sizeof(pj_str_t), - pjsua_var.ua_cfg.stun_srv_cnt, - pjsua_var.stun_srv_idx); - - pj_array_insert(pjsua_var.ua_cfg.stun_srv, - sizeof(pj_str_t), - pjsua_var.ua_cfg.stun_srv_cnt-1, - pjsua_var.ua_cfg.stun_srv_cnt-1, - &srv); - - PJSUA_UNLOCK(); - } - status=pjsua_update_stun_servers(pjsua_var.ua_cfg.stun_srv_cnt, - pjsua_var.ua_cfg.stun_srv, - PJ_TRUE); - if (status == PJ_SUCCESS) { - if (pjsua_var.stun_srv.addr.sa_family != 0) { - pj_sockaddr_print(&pjsua_var.stun_srv, - ip_addr, sizeof(ip_addr), 0); - stun_srv = pj_str(ip_addr); - } else { - stun_srv.slen = 0; - } - - stun_opt.af = pjsua_var.stun_srv.addr.sa_family; - stun_opt.srv1 = stun_opt.srv2 = stun_srv; - stun_opt.port1 = stun_opt.port2 = - pj_sockaddr_get_port(&pjsua_var.stun_srv); - status = pjstun_get_mapped_addr2(&pjsua_var.cp.factory, - &stun_opt, 2, sock, - resolved_addr); - } - } - - if (status != PJ_SUCCESS) { - if (!pjsua_var.ua_cfg.stun_ignore_failure) { - pjsua_perror(THIS_FILE, "STUN resolve error", status); - goto on_error; - } - - PJ_LOG(4,(THIS_FILE, "Ignoring STUN resolve error %d", - status)); - - if (!pj_sockaddr_has_addr(&bound_addr)) { - pj_sockaddr addr; - - /* Get local IP address. */ - status = pj_gethostip(af, &addr); - if (status != PJ_SUCCESS) - goto on_error; - - pj_sockaddr_copy_addr(&bound_addr, &addr); - } - - for (i=0; i<2; ++i) { - pj_sockaddr_init(af, &mapped_addr[i], NULL, 0); - pj_sockaddr_copy_addr(&mapped_addr[i], &bound_addr); - pj_sockaddr_set_port(&mapped_addr[i], - (pj_uint16_t)(acc->next_rtp_port+i)); - } - break; - } - - pj_sockaddr_cp(&mapped_addr[0], &resolved_addr[0]); - pj_sockaddr_cp(&mapped_addr[1], &resolved_addr[1]); + if (status != PJ_SUCCESS && pjsua_var.ua_cfg.stun_srv_cnt > 1 && + ((acc->cfg.media_stun_use & PJSUA_STUN_RETRY_ON_FAILURE)== + PJSUA_STUN_RETRY_ON_FAILURE)) + { + pj_str_t srv = + pjsua_var.ua_cfg.stun_srv[pjsua_var.stun_srv_idx]; + + PJ_LOG(4,(THIS_FILE, "Failed to get STUN mapped address, " + "retrying other STUN servers")); + + if (pjsua_var.stun_srv_idx < pjsua_var.ua_cfg.stun_srv_cnt-1) { + PJSUA_LOCK(); + /* Move the unusable STUN server to the last position + * as the least prioritize. + */ + pj_array_erase(pjsua_var.ua_cfg.stun_srv, + sizeof(pj_str_t), + pjsua_var.ua_cfg.stun_srv_cnt, + pjsua_var.stun_srv_idx); + + pj_array_insert(pjsua_var.ua_cfg.stun_srv, + sizeof(pj_str_t), + pjsua_var.ua_cfg.stun_srv_cnt-1, + pjsua_var.ua_cfg.stun_srv_cnt-1, + &srv); + + PJSUA_UNLOCK(); + } + status=pjsua_update_stun_servers(pjsua_var.ua_cfg.stun_srv_cnt, + pjsua_var.ua_cfg.stun_srv, + PJ_TRUE); + if (status == PJ_SUCCESS) { + if (pjsua_var.stun_srv.addr.sa_family != 0) { + pj_sockaddr_print(&pjsua_var.stun_srv, + ip_addr, sizeof(ip_addr), 0); + stun_srv = pj_str(ip_addr); + } else { + stun_srv.slen = 0; + } + + stun_opt.af = pjsua_var.stun_srv.addr.sa_family; + stun_opt.srv1 = stun_opt.srv2 = stun_srv; + stun_opt.port1 = stun_opt.port2 = + pj_sockaddr_get_port(&pjsua_var.stun_srv); + status = pjstun_get_mapped_addr2(&pjsua_var.cp.factory, + &stun_opt, 2, sock, + resolved_addr); + } + } + + if (status != PJ_SUCCESS) { + if (!pjsua_var.ua_cfg.stun_ignore_failure) { + pjsua_perror(THIS_FILE, "STUN resolve error", status); + goto on_error; + } + + PJ_LOG(4,(THIS_FILE, "Ignoring STUN resolve error %d", + status)); + + if (!pj_sockaddr_has_addr(&bound_addr)) { + pj_sockaddr addr; + + /* Get local IP address. */ + status = pj_gethostip(af, &addr); + if (status != PJ_SUCCESS) + goto on_error; + + pj_sockaddr_copy_addr(&bound_addr, &addr); + } + + for (i=0; i<2; ++i) { + pj_sockaddr_init(af, &mapped_addr[i], NULL, 0); + pj_sockaddr_copy_addr(&mapped_addr[i], &bound_addr); + pj_sockaddr_set_port(&mapped_addr[i], + (pj_uint16_t)(acc->next_rtp_port+i)); + } + break; + } + + pj_sockaddr_cp(&mapped_addr[0], &resolved_addr[0]); + pj_sockaddr_cp(&mapped_addr[1], &resolved_addr[1]); #if PJSUA_REQUIRE_CONSECUTIVE_RTCP_PORT - if (pj_sockaddr_get_port(&mapped_addr[1]) == - pj_sockaddr_get_port(&mapped_addr[0])+1) - { - /* Success! */ - break; - } - - pj_sock_close(sock[0]); - sock[0] = PJ_INVALID_SOCKET; - - pj_sock_close(sock[1]); - sock[1] = PJ_INVALID_SOCKET; + if (pj_sockaddr_get_port(&mapped_addr[1]) == + pj_sockaddr_get_port(&mapped_addr[0])+1) + { + /* Success! */ + break; + } + + pj_sock_close(sock[0]); + sock[0] = PJ_INVALID_SOCKET; + + pj_sock_close(sock[1]); + sock[1] = PJ_INVALID_SOCKET; #else - if (pj_sockaddr_get_port(&mapped_addr[1]) != - pj_sockaddr_get_port(&mapped_addr[0])+1) - { - PJ_LOG(4,(THIS_FILE, - "Note: STUN mapped RTCP port %d is not adjacent" - " to RTP port %d", - pj_sockaddr_get_port(&mapped_addr[1]), - pj_sockaddr_get_port(&mapped_addr[0]))); - } - /* Success! */ - break; + if (pj_sockaddr_get_port(&mapped_addr[1]) != + pj_sockaddr_get_port(&mapped_addr[0])+1) + { + PJ_LOG(4,(THIS_FILE, + "Note: STUN mapped RTCP port %d is not adjacent" + " to RTP port %d", + pj_sockaddr_get_port(&mapped_addr[1]), + pj_sockaddr_get_port(&mapped_addr[0]))); + } + /* Success! */ + break; #endif #if defined(PJNATH_HAS_UPNP) && (PJNATH_HAS_UPNP != 0) - } else if ((!use_ipv6 || use_nat64) && - pjsua_media_acc_is_using_upnp(call_med->call->acc_id) && - pjsua_var.upnp_status == PJ_SUCCESS) - { - status = pj_upnp_add_port_mapping(2, sock, NULL, mapped_addr); - if (status == PJ_SUCCESS) { - call_med->use_upnp = PJ_TRUE; - pj_sockaddr_cp(&call_med->mapped_addr[0], &mapped_addr[0]); - pj_sockaddr_cp(&call_med->mapped_addr[1], &mapped_addr[1]); - } else { - pjsua_perror(THIS_FILE, "Error adding UPnP " - "port mapping", status); - - if (!pj_sockaddr_has_addr(&bound_addr)) { - pj_sockaddr addr; - - /* Get local IP address. */ - status = pj_gethostip(af, &addr); - if (status != PJ_SUCCESS) - goto on_error; - - pj_sockaddr_copy_addr(&bound_addr, &addr); - } - - for (i = 0; i < 2; ++i) { - pj_sockaddr_init(af, &mapped_addr[i], NULL, 0); - pj_sockaddr_copy_addr(&mapped_addr[i], &bound_addr); - pj_sockaddr_set_port(&mapped_addr[i], - (pj_uint16_t)(acc->next_rtp_port+i)); - } - break; - } - - break; + } else if ((!use_ipv6 || use_nat64) && + pjsua_media_acc_is_using_upnp(call_med->call->acc_id) && + pjsua_var.upnp_status == PJ_SUCCESS) + { + status = pj_upnp_add_port_mapping(2, sock, NULL, mapped_addr); + if (status == PJ_SUCCESS) { + call_med->use_upnp = PJ_TRUE; + pj_sockaddr_cp(&call_med->mapped_addr[0], &mapped_addr[0]); + pj_sockaddr_cp(&call_med->mapped_addr[1], &mapped_addr[1]); + } else { + pjsua_perror(THIS_FILE, "Error adding UPnP " + "port mapping", status); + + if (!pj_sockaddr_has_addr(&bound_addr)) { + pj_sockaddr addr; + + /* Get local IP address. */ + status = pj_gethostip(af, &addr); + if (status != PJ_SUCCESS) + goto on_error; + + pj_sockaddr_copy_addr(&bound_addr, &addr); + } + + for (i = 0; i < 2; ++i) { + pj_sockaddr_init(af, &mapped_addr[i], NULL, 0); + pj_sockaddr_copy_addr(&mapped_addr[i], &bound_addr); + pj_sockaddr_set_port(&mapped_addr[i], + (pj_uint16_t)(acc->next_rtp_port+i)); + } + break; + } + + break; #endif - } else if (cfg->public_addr.slen) { - - status = pj_sockaddr_init(af, &mapped_addr[0], &cfg->public_addr, - (pj_uint16_t)acc->next_rtp_port); - if (status != PJ_SUCCESS) - goto on_error; - - status = pj_sockaddr_init(af, &mapped_addr[1], &cfg->public_addr, - (pj_uint16_t)(acc->next_rtp_port+1)); - if (status != PJ_SUCCESS) - goto on_error; - - break; - - } else { - if (acc->cfg.allow_sdp_nat_rewrite && acc->reg_mapped_addr.slen) { - pj_status_t status2; - - /* Take the address from mapped addr as seen by registrar */ - status2 = pj_sockaddr_set_str_addr(af, &bound_addr, - &acc->reg_mapped_addr); - if (status2 != PJ_SUCCESS) { - /* just leave bound_addr with whatever it was - pj_bzero(pj_sockaddr_get_addr(&bound_addr), - pj_sockaddr_get_addr_len(&bound_addr)); - */ - } - } - - if (!pj_sockaddr_has_addr(&bound_addr)) { - pj_sockaddr addr; - - /* Get local IP address. */ - status = pj_gethostip(af, &addr); - if (status != PJ_SUCCESS) - goto on_error; - - pj_sockaddr_copy_addr(&bound_addr, &addr); - } - - for (i=0; i<2; ++i) { - pj_sockaddr_init(af, &mapped_addr[i], NULL, 0); - pj_sockaddr_copy_addr(&mapped_addr[i], &bound_addr); - pj_sockaddr_set_port(&mapped_addr[i], - (pj_uint16_t)(acc->next_rtp_port+i)); - } - - break; - } + } else if (cfg->public_addr.slen) { + + status = pj_sockaddr_init(af, &mapped_addr[0], &cfg->public_addr, + (pj_uint16_t)acc->next_rtp_port); + if (status != PJ_SUCCESS) + goto on_error; + + status = pj_sockaddr_init(af, &mapped_addr[1], &cfg->public_addr, + (pj_uint16_t)(acc->next_rtp_port+1)); + if (status != PJ_SUCCESS) + goto on_error; + + break; + + } else { + if (acc->cfg.allow_sdp_nat_rewrite && acc->reg_mapped_addr.slen) { + pj_status_t status2; + + /* Take the address from mapped addr as seen by registrar */ + status2 = pj_sockaddr_set_str_addr(af, &bound_addr, + &acc->reg_mapped_addr); + if (status2 != PJ_SUCCESS) { + /* just leave bound_addr with whatever it was + pj_bzero(pj_sockaddr_get_addr(&bound_addr), + pj_sockaddr_get_addr_len(&bound_addr)); + */ + } + } + + if (!pj_sockaddr_has_addr(&bound_addr)) { + pj_sockaddr addr; + + /* Get local IP address. */ + status = pj_gethostip(af, &addr); + if (status != PJ_SUCCESS) + goto on_error; + + pj_sockaddr_copy_addr(&bound_addr, &addr); + } + + for (i=0; i<2; ++i) { + pj_sockaddr_init(af, &mapped_addr[i], NULL, 0); + pj_sockaddr_copy_addr(&mapped_addr[i], &bound_addr); + pj_sockaddr_set_port(&mapped_addr[i], + (pj_uint16_t)(acc->next_rtp_port+i)); + } + + break; + } } if (sock[0] == PJ_INVALID_SOCKET) { - PJ_LOG(1,(THIS_FILE, - "Unable to find appropriate RTP/RTCP ports combination")); - goto on_error; + PJ_LOG(1,(THIS_FILE, + "Unable to find appropriate RTP/RTCP ports combination")); + goto on_error; } @@ -651,51 +650,51 @@ static pj_status_t create_rtp_rtcp_sock(pjsua_call_media *call_med, pj_sockaddr_cp(&skinfo->rtcp_addr_name, &mapped_addr[1]); PJ_LOG(4,(THIS_FILE, "RTP%s socket reachable at %s", - (call_med->enable_rtcp_mux? " & RTCP": ""), - pj_sockaddr_print(&skinfo->rtp_addr_name, addr_buf, - sizeof(addr_buf), 3))); + (call_med->enable_rtcp_mux? " & RTCP": ""), + pj_sockaddr_print(&skinfo->rtp_addr_name, addr_buf, + sizeof(addr_buf), 3))); PJ_LOG(4,(THIS_FILE, "RTCP socket reachable at %s", - pj_sockaddr_print(&skinfo->rtcp_addr_name, addr_buf, - sizeof(addr_buf), 3))); + pj_sockaddr_print(&skinfo->rtcp_addr_name, addr_buf, + sizeof(addr_buf), 3))); acc->next_rtp_port += 2; return PJ_SUCCESS; on_error: for (i=0; i<2; ++i) { - if (sock[i] != PJ_INVALID_SOCKET) - pj_sock_close(sock[i]); + if (sock[i] != PJ_INVALID_SOCKET) + pj_sock_close(sock[i]); } return status; } /* Create normal UDP media transports */ static pj_status_t create_udp_media_transport(const pjsua_transport_config *cfg, - pjsua_call_media *call_med) + pjsua_call_media *call_med) { pjmedia_sock_info skinfo; pj_status_t status; status = create_rtp_rtcp_sock(call_med, cfg, &skinfo); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create RTP/RTCP socket", - status); - goto on_error; + pjsua_perror(THIS_FILE, "Unable to create RTP/RTCP socket", + status); + goto on_error; } status = pjmedia_transport_udp_attach(pjsua_var.med_endpt, NULL, - &skinfo, 0, &call_med->tp); + &skinfo, 0, &call_med->tp); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create media transport", - status); - goto on_error; + pjsua_perror(THIS_FILE, "Unable to create media transport", + status); + goto on_error; } pjmedia_transport_simulate_lost(call_med->tp, PJMEDIA_DIR_ENCODING, - pjsua_var.media_cfg.tx_drop_pct); + pjsua_var.media_cfg.tx_drop_pct); pjmedia_transport_simulate_lost(call_med->tp, PJMEDIA_DIR_DECODING, - pjsua_var.media_cfg.rx_drop_pct); + pjsua_var.media_cfg.rx_drop_pct); call_med->tp_ready = PJ_SUCCESS; @@ -703,15 +702,15 @@ static pj_status_t create_udp_media_transport(const pjsua_transport_config *cfg, on_error: if (call_med->tp) - pjmedia_transport_close(call_med->tp); + pjmedia_transport_close(call_med->tp); return status; } /* Create loop media transport */ static pj_status_t create_loop_media_transport( - const pjsua_transport_config *cfg, - pjsua_call_media *call_med) + const pjsua_transport_config *cfg, + pjsua_call_media *call_med) { pj_status_t status; pjmedia_loop_tp_setting opt; @@ -731,10 +730,10 @@ static pj_status_t create_loop_media_transport( if (acc->next_rtp_port == 0 || cfg->port == 0) { if (cfg->port != 0 && cfg->port_range != 0 && cfg->randomize_port) { unsigned offset = ((pj_rand() % (cfg->port_range)) / 2) * 2; - acc->next_rtp_port = (pj_uint16_t)(cfg->port + offset); + acc->next_rtp_port = (pj_uint16_t)(cfg->port + offset); } else { - acc->next_rtp_port = (pj_uint16_t)cfg->port; - } + acc->next_rtp_port = (pj_uint16_t)cfg->port; + } } if (cfg->port > 0 && cfg->port_range > 0 && @@ -748,18 +747,18 @@ static pj_status_t create_loop_media_transport( opt.disable_rx=!pjsua_var.acc[call_med->call->acc_id].cfg.enable_loopback; status = pjmedia_transport_loop_create2(pjsua_var.med_endpt, &opt, - &call_med->tp); + &call_med->tp); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create loop media transport", - status); - goto on_error; + pjsua_perror(THIS_FILE, "Unable to create loop media transport", + status); + goto on_error; } pjmedia_transport_simulate_lost(call_med->tp, PJMEDIA_DIR_ENCODING, - pjsua_var.media_cfg.tx_drop_pct); + pjsua_var.media_cfg.tx_drop_pct); pjmedia_transport_simulate_lost(call_med->tp, PJMEDIA_DIR_DECODING, - pjsua_var.media_cfg.rx_drop_pct); + pjsua_var.media_cfg.rx_drop_pct); call_med->tp_ready = PJ_SUCCESS; @@ -767,7 +766,7 @@ static pj_status_t create_loop_media_transport( on_error: if (call_med->tp) - pjmedia_transport_close(call_med->tp); + pjmedia_transport_close(call_med->tp); return status; } @@ -780,33 +779,33 @@ static pj_status_t create_udp_media_transports(pjsua_transport_config *cfg) pj_status_t status; for (i=0; i < pjsua_var.ua_cfg.max_calls; ++i) { - pjsua_call *call = &pjsua_var.calls[i]; - unsigned strm_idx; + pjsua_call *call = &pjsua_var.calls[i]; + unsigned strm_idx; - for (strm_idx=0; strm_idx < call->med_cnt; ++strm_idx) { - pjsua_call_media *call_med = &call->media[strm_idx]; + for (strm_idx=0; strm_idx < call->med_cnt; ++strm_idx) { + pjsua_call_media *call_med = &call->media[strm_idx]; - status = create_udp_media_transport(cfg, &call_med->tp); - if (status != PJ_SUCCESS) - goto on_error; - } + status = create_udp_media_transport(cfg, &call_med->tp); + if (status != PJ_SUCCESS) + goto on_error; + } } return PJ_SUCCESS; on_error: for (i=0; i < pjsua_var.ua_cfg.max_calls; ++i) { - pjsua_call *call = &pjsua_var.calls[i]; - unsigned strm_idx; + pjsua_call *call = &pjsua_var.calls[i]; + unsigned strm_idx; - for (strm_idx=0; strm_idx < call->med_cnt; ++strm_idx) { - pjsua_call_media *call_med = &call->media[strm_idx]; + for (strm_idx=0; strm_idx < call->med_cnt; ++strm_idx) { + pjsua_call_media *call_med = &call->media[strm_idx]; - if (call_med->tp) { - pjmedia_transport_close(call_med->tp); - call_med->tp = NULL; - } - } + if (call_med->tp) { + pjmedia_transport_close(call_med->tp); + call_med->tp = NULL; + } + } } return status; } @@ -818,7 +817,7 @@ static void ice_init_complete_cb(void *user_data) pjsua_call_media *call_med = (pjsua_call_media*)user_data; if (call_med->call == NULL || call_med->tp_ready == PJ_SUCCESS) - return; + return; /* No need to acquire_call() if we only change the tp_ready flag * (i.e. transport is being created synchronously). Otherwise @@ -828,19 +827,19 @@ static void ice_init_complete_cb(void *user_data) call_med->tp_ready = call_med->tp_result; if (call_med->med_create_cb) { - pjsua_call *call = NULL; - pjsip_dialog *dlg = NULL; - pj_status_t status; - - status = acquire_call("ice_init_complete_cb", call_med->call->index, - &call, &dlg); - if (status != PJ_SUCCESS) { - if (status != PJSIP_ESESSIONTERMINATED) { - /* Retry, if call is still active */ - pjsua_schedule_timer2(&ice_init_complete_cb, call_med, 10); - } - return; - } + pjsua_call *call = NULL; + pjsip_dialog *dlg = NULL; + pj_status_t status; + + status = acquire_call("ice_init_complete_cb", call_med->call->index, + &call, &dlg); + if (status != PJ_SUCCESS) { + if (status != PJSIP_ESESSIONTERMINATED) { + /* Retry, if call is still active */ + pjsua_schedule_timer2(&ice_init_complete_cb, call_med, 10); + } + return; + } (*call_med->med_create_cb)(call_med, call_med->tp_ready, call_med->call->secure_level, NULL); @@ -860,16 +859,16 @@ static void ice_failed_nego_cb(void *user_data) status = acquire_call("ice_failed_nego_cb", call_id, &call, &dlg); if (status != PJ_SUCCESS) { - if (status != PJSIP_ESESSIONTERMINATED) { - /* Retry, if call is still active */ - pjsua_schedule_timer2(&ice_failed_nego_cb, - (void*)(pj_ssize_t)call_id, 10); - } - return; + if (status != PJSIP_ESESSIONTERMINATED) { + /* Retry, if call is still active */ + pjsua_schedule_timer2(&ice_failed_nego_cb, + (void*)(pj_ssize_t)call_id, 10); + } + return; } if (!call->hanging_up) - pjsua_var.ua_cfg.cb.on_call_media_state(call_id); + pjsua_var.ua_cfg.cb.on_call_media_state(call_id); if (dlg) pjsip_dlg_dec_lock(dlg); @@ -878,14 +877,14 @@ static void ice_failed_nego_cb(void *user_data) /* This callback is called when ICE negotiation completes */ static void on_ice_complete(pjmedia_transport *tp, - pj_ice_strans_op op, - pj_status_t result) + pj_ice_strans_op op, + pj_status_t result) { pjsua_call_media *call_med = (pjsua_call_media*)tp->user_data; pjsua_call *call; if (!call_med) - return; + return; call = call_med->call; @@ -893,46 +892,46 @@ static void on_ice_complete(pjmedia_transport *tp, case PJ_ICE_STRANS_OP_INIT: call_med->tp_result = result; pjsua_schedule_timer2(&ice_init_complete_cb, call_med, 1); - break; + break; case PJ_ICE_STRANS_OP_NEGOTIATION: - if (result == PJ_SUCCESS) { + if (result == PJ_SUCCESS) { /* Update RTP address */ pjmedia_transport_info tpinfo; pjmedia_transport_info_init(&tpinfo); pjmedia_transport_get_info(call_med->tp, &tpinfo); pj_sockaddr_cp(&call_med->rtp_addr, &tpinfo.sock_info.rtp_addr_name); } else { - call_med->state = PJSUA_CALL_MEDIA_ERROR; - call_med->dir = PJMEDIA_DIR_NONE; - if (call && !call->hanging_up && - pjsua_var.ua_cfg.cb.on_call_media_state) - { - /* Defer the callback to a timer */ - pjsua_schedule_timer2(&ice_failed_nego_cb, - (void*)(pj_ssize_t)call->index, 1); - } + call_med->state = PJSUA_CALL_MEDIA_ERROR; + call_med->dir = PJMEDIA_DIR_NONE; + if (call && !call->hanging_up && + pjsua_var.ua_cfg.cb.on_call_media_state) + { + /* Defer the callback to a timer */ + pjsua_schedule_timer2(&ice_failed_nego_cb, + (void*)(pj_ssize_t)call->index, 1); + } } - /* Stop trickling */ - if (call->trickle_ice.trickling < PJSUA_OP_STATE_DONE) { - call->trickle_ice.trickling = PJSUA_OP_STATE_DONE; - pjsua_cancel_timer(&call->trickle_ice.timer); - PJ_LOG(4,(THIS_FILE, "Call %d: ICE trickle stopped trickling as " - "ICE nego completed", - call->index)); - } + /* Stop trickling */ + if (call->trickle_ice.trickling < PJSUA_OP_STATE_DONE) { + call->trickle_ice.trickling = PJSUA_OP_STATE_DONE; + pjsua_cancel_timer(&call->trickle_ice.timer); + PJ_LOG(4,(THIS_FILE, "Call %d: ICE trickle stopped trickling as " + "ICE nego completed", + call->index)); + } - /* Check if default ICE transport address is changed */ + /* Check if default ICE transport address is changed */ call->reinv_ice_sent = PJ_FALSE; - pjsua_call_schedule_reinvite_check(call, 0); - break; + pjsua_call_schedule_reinvite_check(call, 0); + break; case PJ_ICE_STRANS_OP_KEEP_ALIVE: case PJ_ICE_STRANS_OP_ADDR_CHANGE: - if (result != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, result, - "ICE keep alive failure for transport %d:%d", - call->index, call_med->idx)); - } + if (result != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, result, + "ICE keep alive failure for transport %d:%d", + call->index, call_med->idx)); + } if (!call->hanging_up && pjsua_var.ua_cfg.cb.on_call_media_transport_state) { @@ -943,42 +942,42 @@ static void on_ice_complete(pjmedia_transport *tp, info.state = call_med->tp_st; info.status = result; info.ext_info = &op; - (*pjsua_var.ua_cfg.cb.on_call_media_transport_state)( + (*pjsua_var.ua_cfg.cb.on_call_media_transport_state)( call->index, &info); } - if (pjsua_var.ua_cfg.cb.on_ice_transport_error && - op == PJ_ICE_STRANS_OP_KEEP_ALIVE) - { - pjsua_call_id id = call->index; - (*pjsua_var.ua_cfg.cb.on_ice_transport_error)(id, op, result, - NULL); - } - break; + if (pjsua_var.ua_cfg.cb.on_ice_transport_error && + op == PJ_ICE_STRANS_OP_KEEP_ALIVE) + { + pjsua_call_id id = call->index; + (*pjsua_var.ua_cfg.cb.on_ice_transport_error)(id, op, result, + NULL); + } + break; } } /* Parse "HOST:PORT" format */ static pj_status_t parse_host_port(const pj_str_t *host_port, - pj_str_t *host, pj_uint16_t *port) + pj_str_t *host, pj_uint16_t *port) { pj_str_t str_port; str_port.ptr = pj_strchr(host_port, ':'); if (str_port.ptr != NULL) { - int iport; - - host->ptr = host_port->ptr; - host->slen = (str_port.ptr - host->ptr); - str_port.ptr++; - str_port.slen = host_port->slen - host->slen - 1; - iport = (int)pj_strtoul(&str_port); - if (iport < 1 || iport > 65535) - return PJ_EINVAL; - *port = (pj_uint16_t)iport; + int iport; + + host->ptr = host_port->ptr; + host->slen = (str_port.ptr - host->ptr); + str_port.ptr++; + str_port.slen = host_port->slen - host->slen - 1; + iport = (int)pj_strtoul(&str_port); + if (iport < 1 || iport > 65535) + return PJ_EINVAL; + *port = (pj_uint16_t)iport; } else { - *host = *host_port; - *port = 0; + *host = *host_port; + *port = 0; } return PJ_SUCCESS; @@ -986,8 +985,8 @@ static pj_status_t parse_host_port(const pj_str_t *host_port, /* Create ICE media transports (when ice is enabled) */ static pj_status_t create_ice_media_transport( - const pjsua_transport_config *cfg, - pjsua_call_media *call_med, + const pjsua_transport_config *cfg, + pjsua_call_media *call_med, pj_bool_t async) { char stunip[PJ_INET6_ADDRSTRLEN]; @@ -1007,15 +1006,15 @@ static pj_status_t create_ice_media_transport( /* Make sure STUN server resolution has completed */ if (pjsua_media_acc_is_using_stun(call_med->call->acc_id)) { - pj_bool_t retry_stun = (acc_cfg->media_stun_use & - PJSUA_STUN_RETRY_ON_FAILURE) == - PJSUA_STUN_RETRY_ON_FAILURE; - status = resolve_stun_server(PJ_TRUE, retry_stun, - (unsigned)acc_cfg->nat64_opt); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error resolving STUN server", status); - return status; - } + pj_bool_t retry_stun = (acc_cfg->media_stun_use & + PJSUA_STUN_RETRY_ON_FAILURE) == + PJSUA_STUN_RETRY_ON_FAILURE; + status = resolve_stun_server(PJ_TRUE, retry_stun, + (unsigned)acc_cfg->nat64_opt); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error resolving STUN server", status); + return status; + } } /* Create ICE stream transport configuration */ @@ -1023,8 +1022,8 @@ static pj_status_t create_ice_media_transport( pj_bzero(&ice_cfg.stun, sizeof(ice_cfg.stun)); pj_bzero(&ice_cfg.turn, sizeof(ice_cfg.turn)); pj_stun_config_init(&ice_cfg.stun_cfg, &pjsua_var.cp.factory, 0, - pjsip_endpt_get_ioqueue(pjsua_var.endpt), - pjsip_endpt_get_timer_heap(pjsua_var.endpt)); + pjsip_endpt_get_ioqueue(pjsua_var.endpt), + pjsip_endpt_get_timer_heap(pjsua_var.endpt)); ice_cfg.resolver = pjsua_var.resolver; @@ -1032,109 +1031,109 @@ static pj_status_t create_ice_media_transport( rem_sdp = call_med->call->async_call.rem_sdp; if (rem_sdp) { - /* Match the default address family according to the offer */ + /* Match the default address family according to the offer */ const pj_str_t ID_IP6 = { "IP6", 3}; - const pjmedia_sdp_media *m; - const pjmedia_sdp_conn *c; + const pjmedia_sdp_media *m; + const pjmedia_sdp_conn *c; - m = rem_sdp->media[call_med->idx]; - c = m->conn? m->conn : rem_sdp->conn; + m = rem_sdp->media[call_med->idx]; + c = m->conn? m->conn : rem_sdp->conn; - if (pj_stricmp(&c->addr_type, &ID_IP6) == 0) - ice_cfg.af = pj_AF_INET6(); + if (pj_stricmp(&c->addr_type, &ID_IP6) == 0) + ice_cfg.af = pj_AF_INET6(); } else if (use_ipv6 || use_nat64) { - ice_cfg.af = pj_AF_INET6(); + ice_cfg.af = pj_AF_INET6(); } /* Should not wait for ICE STUN/TURN ready when trickle ICE is enabled */ if (ice_cfg.opt.trickle != PJ_ICE_SESS_TRICKLE_DISABLED && - (call_med->call->inv == NULL || - call_med->call->inv->state < PJSIP_INV_STATE_CONFIRMED)) + (call_med->call->inv == NULL || + call_med->call->inv->state < PJSIP_INV_STATE_CONFIRMED)) { - if (rem_sdp) { - /* As answerer: and when remote signals trickle ICE in SDP */ - trickle = pjmedia_ice_sdp_has_trickle(rem_sdp, call_med->idx); - if (trickle) { - call_med->call->trickle_ice.remote_sup = PJ_TRUE; - call_med->call->trickle_ice.enabled = PJ_TRUE; - } - } else { - /* As offerer: and when trickle ICE mode is full */ - trickle = (ice_cfg.opt.trickle==PJ_ICE_SESS_TRICKLE_FULL); - call_med->call->trickle_ice.enabled = PJ_TRUE; - } - - /* Check if trickle ICE can start trickling/sending SIP INFO */ - pjsua_ice_check_start_trickling(call_med->call, PJ_FALSE, NULL); + if (rem_sdp) { + /* As answerer: and when remote signals trickle ICE in SDP */ + trickle = pjmedia_ice_sdp_has_trickle(rem_sdp, call_med->idx); + if (trickle) { + call_med->call->trickle_ice.remote_sup = PJ_TRUE; + call_med->call->trickle_ice.enabled = PJ_TRUE; + } + } else { + /* As offerer: and when trickle ICE mode is full */ + trickle = (ice_cfg.opt.trickle==PJ_ICE_SESS_TRICKLE_FULL); + call_med->call->trickle_ice.enabled = PJ_TRUE; + } + + /* Check if trickle ICE can start trickling/sending SIP INFO */ + pjsua_ice_check_start_trickling(call_med->call, PJ_FALSE, NULL); } else { - /* For non-initial INVITE, always use regular ICE */ - ice_cfg.opt.trickle = PJ_ICE_SESS_TRICKLE_DISABLED; + /* For non-initial INVITE, always use regular ICE */ + ice_cfg.opt.trickle = PJ_ICE_SESS_TRICKLE_DISABLED; } /* If STUN transport is configured, initialize STUN transport settings */ if ((pj_sockaddr_has_addr(&pjsua_var.stun_srv) && - pjsua_media_acc_is_using_stun(call_med->call->acc_id)) || - acc_cfg->ice_cfg.ice_max_host_cands != 0) + pjsua_media_acc_is_using_stun(call_med->call->acc_id)) || + acc_cfg->ice_cfg.ice_max_host_cands != 0) { - ice_cfg.stun_tp_cnt = 1; - pj_ice_strans_stun_cfg_default(&ice_cfg.stun_tp[0]); - if (use_nat64) { - ice_cfg.stun_tp[0].af = pj_AF_INET6(); - } else if (use_ipv6 && PJ_ICE_MAX_STUN >= 2) { - ice_cfg.stun_tp_cnt = 2; - pj_ice_strans_stun_cfg_default(&ice_cfg.stun_tp[1]); - ice_cfg.stun_tp[1].af = pj_AF_INET6(); - } + ice_cfg.stun_tp_cnt = 1; + pj_ice_strans_stun_cfg_default(&ice_cfg.stun_tp[0]); + if (use_nat64) { + ice_cfg.stun_tp[0].af = pj_AF_INET6(); + } else if (use_ipv6 && PJ_ICE_MAX_STUN >= 2) { + ice_cfg.stun_tp_cnt = 2; + pj_ice_strans_stun_cfg_default(&ice_cfg.stun_tp[1]); + ice_cfg.stun_tp[1].af = pj_AF_INET6(); + } } /* Configure STUN transport settings */ if (ice_cfg.stun_tp_cnt) { - unsigned i; - - if (pj_sockaddr_has_addr(&pjsua_var.stun_srv)) { - pj_sockaddr_print(&pjsua_var.stun_srv, stunip, - sizeof(stunip), 0); - } - - for (i = 0; i < ice_cfg.stun_tp_cnt; ++i) { - pj_str_t IN6_ADDR_ANY = {"0", 1}; - - /* Configure STUN server */ - if (pjsua_media_acc_is_using_stun(call_med->call->acc_id) && - pj_sockaddr_has_addr(&pjsua_var.stun_srv) && - pjsua_var.stun_srv.addr.sa_family == ice_cfg.stun_tp[i].af) - { - ice_cfg.stun_tp[i].server = pj_str(stunip); - ice_cfg.stun_tp[i].port = pj_sockaddr_get_port( - &pjsua_var.stun_srv); - } - - /* Configure max host candidates */ - if (acc_cfg->ice_cfg.ice_max_host_cands >= 0) { - ice_cfg.stun_tp[i].max_host_cands = - acc_cfg->ice_cfg.ice_max_host_cands; - } - - /* Configure binding address */ - pj_sockaddr_init(ice_cfg.stun_tp[i].af, - &ice_cfg.stun_tp[i].cfg.bound_addr, - (ice_cfg.stun_tp[i].af == pj_AF_INET()? - &cfg->bound_addr: &IN6_ADDR_ANY), - (pj_uint16_t)cfg->port); - ice_cfg.stun_tp[i].cfg.port_range = (pj_uint16_t)cfg->port_range; - if (cfg->port != 0 && ice_cfg.stun_tp[i].cfg.port_range == 0) { - ice_cfg.stun_tp[i].cfg.port_range = - (pj_uint16_t)(pjsua_var.ua_cfg.max_calls * 10); - } - - /* Configure QoS setting */ - ice_cfg.stun_tp[i].cfg.qos_type = cfg->qos_type; - pj_memcpy(&ice_cfg.stun_tp[i].cfg.qos_params, &cfg->qos_params, - sizeof(cfg->qos_params)); - - /* Configure max packet size */ - ice_cfg.stun_tp[i].cfg.max_pkt_size = PJMEDIA_MAX_MRU; - } + unsigned i; + + if (pj_sockaddr_has_addr(&pjsua_var.stun_srv)) { + pj_sockaddr_print(&pjsua_var.stun_srv, stunip, + sizeof(stunip), 0); + } + + for (i = 0; i < ice_cfg.stun_tp_cnt; ++i) { + pj_str_t IN6_ADDR_ANY = {"0", 1}; + + /* Configure STUN server */ + if (pjsua_media_acc_is_using_stun(call_med->call->acc_id) && + pj_sockaddr_has_addr(&pjsua_var.stun_srv) && + pjsua_var.stun_srv.addr.sa_family == ice_cfg.stun_tp[i].af) + { + ice_cfg.stun_tp[i].server = pj_str(stunip); + ice_cfg.stun_tp[i].port = pj_sockaddr_get_port( + &pjsua_var.stun_srv); + } + + /* Configure max host candidates */ + if (acc_cfg->ice_cfg.ice_max_host_cands >= 0) { + ice_cfg.stun_tp[i].max_host_cands = + acc_cfg->ice_cfg.ice_max_host_cands; + } + + /* Configure binding address */ + pj_sockaddr_init(ice_cfg.stun_tp[i].af, + &ice_cfg.stun_tp[i].cfg.bound_addr, + (ice_cfg.stun_tp[i].af == pj_AF_INET()? + &cfg->bound_addr: &IN6_ADDR_ANY), + (pj_uint16_t)cfg->port); + ice_cfg.stun_tp[i].cfg.port_range = (pj_uint16_t)cfg->port_range; + if (cfg->port != 0 && ice_cfg.stun_tp[i].cfg.port_range == 0) { + ice_cfg.stun_tp[i].cfg.port_range = + (pj_uint16_t)(pjsua_var.ua_cfg.max_calls * 10); + } + + /* Configure QoS setting */ + ice_cfg.stun_tp[i].cfg.qos_type = cfg->qos_type; + pj_memcpy(&ice_cfg.stun_tp[i].cfg.qos_params, &cfg->qos_params, + sizeof(cfg->qos_params)); + + /* Configure max packet size */ + ice_cfg.stun_tp[i].cfg.max_pkt_size = PJMEDIA_MAX_MRU; + } } /* Configure TURN settings */ @@ -1145,71 +1144,71 @@ static pj_status_t create_ice_media_transport( ice_cfg.turn_tp_cnt = 3; idx = 1; } else { - ice_cfg.turn_tp_cnt = 1; - } - - for (i = 0; i < ice_cfg.turn_tp_cnt; i++) - pj_ice_strans_turn_cfg_default(&ice_cfg.turn_tp[i]); - - if (use_ipv6 || use_nat64) { - if (!use_nat64) - ice_cfg.turn_tp[idx++].af = pj_AF_INET6(); - - /* Additional candidate: IPv4 relay via IPv6 TURN server */ - ice_cfg.turn_tp[idx].af = pj_AF_INET6(); - ice_cfg.turn_tp[idx].alloc_param.af = pj_AF_INET(); - } - - /* Configure TURN server */ - status = parse_host_port(&acc_cfg->turn_cfg.turn_server, - &ice_cfg.turn_tp[0].server, - &ice_cfg.turn_tp[0].port); - if (status != PJ_SUCCESS || ice_cfg.turn_tp[0].server.slen == 0) { - PJ_LOG(1,(THIS_FILE, "Invalid TURN server setting")); - return PJ_EINVAL; - } - - if (ice_cfg.turn_tp[0].port == 0) - ice_cfg.turn_tp[0].port = 3479; - - for (i = 0; i < ice_cfg.turn_tp_cnt; i++) { - pj_str_t IN6_ADDR_ANY = {"0", 1}; - - /* Configure TURN connection settings and credential */ - ice_cfg.turn_tp[i].server = ice_cfg.turn_tp[0].server; - ice_cfg.turn_tp[i].port = ice_cfg.turn_tp[0].port; - ice_cfg.turn_tp[i].conn_type = acc_cfg->turn_cfg.turn_conn_type; - pj_memcpy(&ice_cfg.turn_tp[i].auth_cred, - &acc_cfg->turn_cfg.turn_auth_cred, - sizeof(ice_cfg.turn_tp[i].auth_cred)); - - /* Configure QoS setting */ - ice_cfg.turn_tp[i].cfg.qos_type = cfg->qos_type; - pj_memcpy(&ice_cfg.turn_tp[i].cfg.qos_params, &cfg->qos_params, - sizeof(cfg->qos_params)); - - /* Configure binding address */ - pj_sockaddr_init(ice_cfg.turn_tp[i].af, - &ice_cfg.turn_tp[i].cfg.bound_addr, - (ice_cfg.turn_tp[i].af == pj_AF_INET()? - &cfg->bound_addr: &IN6_ADDR_ANY), - (pj_uint16_t)cfg->port); - ice_cfg.turn_tp[i].cfg.port_range = (pj_uint16_t)cfg->port_range; - if (cfg->port != 0 && ice_cfg.turn_tp[i].cfg.port_range == 0) - ice_cfg.turn_tp[i].cfg.port_range = - (pj_uint16_t)(pjsua_var.ua_cfg.max_calls * 10); - - /* Configure max packet size */ - ice_cfg.turn_tp[i].cfg.max_pkt_size = PJMEDIA_MAX_MRU; + ice_cfg.turn_tp_cnt = 1; + } + + for (i = 0; i < ice_cfg.turn_tp_cnt; i++) + pj_ice_strans_turn_cfg_default(&ice_cfg.turn_tp[i]); + + if (use_ipv6 || use_nat64) { + if (!use_nat64) + ice_cfg.turn_tp[idx++].af = pj_AF_INET6(); + + /* Additional candidate: IPv4 relay via IPv6 TURN server */ + ice_cfg.turn_tp[idx].af = pj_AF_INET6(); + ice_cfg.turn_tp[idx].alloc_param.af = pj_AF_INET(); + } + + /* Configure TURN server */ + status = parse_host_port(&acc_cfg->turn_cfg.turn_server, + &ice_cfg.turn_tp[0].server, + &ice_cfg.turn_tp[0].port); + if (status != PJ_SUCCESS || ice_cfg.turn_tp[0].server.slen == 0) { + PJ_LOG(1,(THIS_FILE, "Invalid TURN server setting")); + return PJ_EINVAL; + } + + if (ice_cfg.turn_tp[0].port == 0) + ice_cfg.turn_tp[0].port = 3479; + + for (i = 0; i < ice_cfg.turn_tp_cnt; i++) { + pj_str_t IN6_ADDR_ANY = {"0", 1}; + + /* Configure TURN connection settings and credential */ + ice_cfg.turn_tp[i].server = ice_cfg.turn_tp[0].server; + ice_cfg.turn_tp[i].port = ice_cfg.turn_tp[0].port; + ice_cfg.turn_tp[i].conn_type = acc_cfg->turn_cfg.turn_conn_type; + pj_memcpy(&ice_cfg.turn_tp[i].auth_cred, + &acc_cfg->turn_cfg.turn_auth_cred, + sizeof(ice_cfg.turn_tp[i].auth_cred)); + + /* Configure QoS setting */ + ice_cfg.turn_tp[i].cfg.qos_type = cfg->qos_type; + pj_memcpy(&ice_cfg.turn_tp[i].cfg.qos_params, &cfg->qos_params, + sizeof(cfg->qos_params)); + + /* Configure binding address */ + pj_sockaddr_init(ice_cfg.turn_tp[i].af, + &ice_cfg.turn_tp[i].cfg.bound_addr, + (ice_cfg.turn_tp[i].af == pj_AF_INET()? + &cfg->bound_addr: &IN6_ADDR_ANY), + (pj_uint16_t)cfg->port); + ice_cfg.turn_tp[i].cfg.port_range = (pj_uint16_t)cfg->port_range; + if (cfg->port != 0 && ice_cfg.turn_tp[i].cfg.port_range == 0) + ice_cfg.turn_tp[i].cfg.port_range = + (pj_uint16_t)(pjsua_var.ua_cfg.max_calls * 10); + + /* Configure max packet size */ + ice_cfg.turn_tp[i].cfg.max_pkt_size = PJMEDIA_MAX_MRU; #if PJ_HAS_SSL_SOCK - if (ice_cfg.turn_tp[i].conn_type == PJ_TURN_TP_TLS) { - pj_memcpy(&ice_cfg.turn_tp[i].cfg.tls_cfg, - &acc_cfg->turn_cfg.turn_tls_setting, - sizeof(ice_cfg.turn_tp[i].cfg.tls_cfg)); - } + if (ice_cfg.turn_tp[i].conn_type == PJ_TURN_TP_TLS) { + pj_memcpy(&ice_cfg.turn_tp[i].cfg.tls_cfg, + &acc_cfg->turn_cfg.turn_tls_setting, + sizeof(ice_cfg.turn_tp[i].cfg.tls_cfg)); + } #endif - } + } } pj_bzero(&ice_cb, sizeof(pjmedia_ice_cb)); @@ -1219,71 +1218,71 @@ static pj_status_t create_ice_media_transport( comp_cnt = 1; if (PJMEDIA_ADVERTISE_RTCP && !acc_cfg->ice_cfg.ice_no_rtcp) - ++comp_cnt; + ++comp_cnt; status = pjmedia_ice_create3(pjsua_var.med_endpt, name, comp_cnt, - &ice_cfg, &ice_cb, PJSUA_ICE_TRANSPORT_OPTION, + &ice_cfg, &ice_cb, PJSUA_ICE_TRANSPORT_OPTION, call_med, &call_med->tp); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create ICE media transport", - status); - goto on_error; + pjsua_perror(THIS_FILE, "Unable to create ICE media transport", + status); + goto on_error; } /* Wait until transport is initialized, or time out */ if (!async && !trickle) { - pj_bool_t has_pjsua_lock = PJSUA_LOCK_IS_LOCKED(); - pjsip_dialog *dlg = call_med->call->inv ? - call_med->call->inv->dlg : NULL; + pj_bool_t has_pjsua_lock = PJSUA_LOCK_IS_LOCKED(); + pjsip_dialog *dlg = call_med->call->inv ? + call_med->call->inv->dlg : NULL; if (has_pjsua_lock) - PJSUA_UNLOCK(); + PJSUA_UNLOCK(); if (dlg) { /* Don't lock otherwise deadlock: * https://github.com/pjsip/pjproject/issues/1737 */ - pjsip_dlg_inc_session(dlg, &pjsua_var.mod); + pjsip_dlg_inc_session(dlg, &pjsua_var.mod); pjsip_dlg_dec_lock(dlg); } while (call_med->tp_ready == PJ_EPENDING) { - pjsua_handle_events(100); + pjsua_handle_events(100); } if (dlg) { pjsip_dlg_inc_lock(dlg); - pjsip_dlg_dec_session(dlg, &pjsua_var.mod); + pjsip_dlg_dec_session(dlg, &pjsua_var.mod); } - if (has_pjsua_lock) - PJSUA_LOCK(); + if (has_pjsua_lock) + PJSUA_LOCK(); } if (!call_med->tp) { - /* Call has been disconnected, and media transports have been cleared - * (see ticket #1759). - */ - PJ_LOG(4,(THIS_FILE, "Media transport initialization cancelled " - "because call has been disconnected")); - status = PJ_ECANCELLED; - goto on_error; + /* Call has been disconnected, and media transports have been cleared + * (see ticket #1759). + */ + PJ_LOG(4,(THIS_FILE, "Media transport initialization cancelled " + "because call has been disconnected")); + status = PJ_ECANCELLED; + goto on_error; } else if (async && call_med->tp_ready == PJ_EPENDING) { return PJ_EPENDING; } else if (call_med->tp_ready != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error initializing ICE media transport", - call_med->tp_ready); - status = call_med->tp_ready; - goto on_error; + pjsua_perror(THIS_FILE, "Error initializing ICE media transport", + call_med->tp_ready); + status = call_med->tp_ready; + goto on_error; } pjmedia_transport_simulate_lost(call_med->tp, PJMEDIA_DIR_ENCODING, - pjsua_var.media_cfg.tx_drop_pct); + pjsua_var.media_cfg.tx_drop_pct); pjmedia_transport_simulate_lost(call_med->tp, PJMEDIA_DIR_DECODING, - pjsua_var.media_cfg.rx_drop_pct); + pjsua_var.media_cfg.rx_drop_pct); return PJ_SUCCESS; on_error: if (call_med->tp != NULL) { - pjmedia_transport_close(call_med->tp); - call_med->tp = NULL; + pjmedia_transport_close(call_med->tp); + call_med->tp = NULL; } return status; @@ -1297,33 +1296,33 @@ static pj_status_t create_ice_media_transports(pjsua_transport_config *cfg) pj_status_t status; for (i=0; i < pjsua_var.ua_cfg.max_calls; ++i) { - pjsua_call *call = &pjsua_var.calls[i]; - unsigned strm_idx; + pjsua_call *call = &pjsua_var.calls[i]; + unsigned strm_idx; - for (strm_idx=0; strm_idx < call->med_cnt; ++strm_idx) { - pjsua_call_media *call_med = &call->media[strm_idx]; + for (strm_idx=0; strm_idx < call->med_cnt; ++strm_idx) { + pjsua_call_media *call_med = &call->media[strm_idx]; - status = create_ice_media_transport(cfg, call_med); - if (status != PJ_SUCCESS) - goto on_error; - } + status = create_ice_media_transport(cfg, call_med); + if (status != PJ_SUCCESS) + goto on_error; + } } return PJ_SUCCESS; on_error: for (i=0; i < pjsua_var.ua_cfg.max_calls; ++i) { - pjsua_call *call = &pjsua_var.calls[i]; - unsigned strm_idx; + pjsua_call *call = &pjsua_var.calls[i]; + unsigned strm_idx; - for (strm_idx=0; strm_idx < call->med_cnt; ++strm_idx) { - pjsua_call_media *call_med = &call->media[strm_idx]; + for (strm_idx=0; strm_idx < call->med_cnt; ++strm_idx) { + pjsua_call_media *call_med = &call->media[strm_idx]; - if (call_med->tp) { - pjmedia_transport_close(call_med->tp); - call_med->tp = NULL; - } - } + if (call_med->tp) { + pjmedia_transport_close(call_med->tp); + call_med->tp = NULL; + } + } } return status; } @@ -1335,7 +1334,7 @@ static pj_status_t create_ice_media_transports(pjsua_transport_config *cfg) * one UDP media transport for each call. */ PJ_DEF(pj_status_t) pjsua_media_transports_create( - const pjsua_transport_config *app_cfg) + const pjsua_transport_config *app_cfg) { pjsua_transport_config cfg; unsigned i; @@ -1349,18 +1348,18 @@ PJ_DEF(pj_status_t) pjsua_media_transports_create( /* Delete existing media transports */ for (i=0; imed_cnt; ++strm_idx) { - pjsua_call_media *call_med = &call->media[strm_idx]; - - if (call_med->tp && call_med->tp_auto_del) { - pjmedia_transport_close(call_med->tp); - call_med->tp = NULL; - call_med->tp_orig = NULL; - } - } + pjsua_call *call = &pjsua_var.calls[i]; + unsigned strm_idx; + + for (strm_idx=0; strm_idx < call->med_cnt; ++strm_idx) { + pjsua_call_media *call_med = &call->media[strm_idx]; + + if (call_med->tp && call_med->tp_auto_del) { + pjmedia_transport_close(call_med->tp); + call_med->tp = NULL; + call_med->tp_orig = NULL; + } + } } /* Copy config */ @@ -1368,21 +1367,21 @@ PJ_DEF(pj_status_t) pjsua_media_transports_create( /* Create the transports */ if (pjsua_var.ice_cfg.enable_ice) { - status = create_ice_media_transports(&cfg); + status = create_ice_media_transports(&cfg); } else { - status = create_udp_media_transports(&cfg); + status = create_udp_media_transports(&cfg); } /* Set media transport auto_delete to True */ for (i=0; imed_cnt; ++strm_idx) { - pjsua_call_media *call_med = &call->media[strm_idx]; + for (strm_idx=0; strm_idx < call->med_cnt; ++strm_idx) { + pjsua_call_media *call_med = &call->media[strm_idx]; - call_med->tp_auto_del = PJ_TRUE; - } + call_med->tp_auto_del = PJ_TRUE; + } } PJSUA_UNLOCK(); @@ -1394,8 +1393,8 @@ PJ_DEF(pj_status_t) pjsua_media_transports_create( * Attach application's created media transports. */ PJ_DEF(pj_status_t) pjsua_media_transports_attach(pjsua_media_transport tp[], - unsigned count, - pj_bool_t auto_delete) + unsigned count, + pj_bool_t auto_delete) { unsigned i; @@ -1403,23 +1402,23 @@ PJ_DEF(pj_status_t) pjsua_media_transports_attach(pjsua_media_transport tp[], /* Assign the media transports */ for (i=0; imed_cnt; ++strm_idx) { - pjsua_call_media *call_med = &call->media[strm_idx]; + for (strm_idx=0; strm_idx < call->med_cnt; ++strm_idx) { + pjsua_call_media *call_med = &call->media[strm_idx]; - if (call_med->tp && call_med->tp_auto_del) { - pjmedia_transport_close(call_med->tp); - call_med->tp = NULL; - call_med->tp_orig = NULL; - } - } + if (call_med->tp && call_med->tp_auto_del) { + pjmedia_transport_close(call_med->tp); + call_med->tp = NULL; + call_med->tp_orig = NULL; + } + } - PJ_TODO(remove_pjsua_media_transports_attach); + PJ_TODO(remove_pjsua_media_transports_attach); - call->media[0].tp = tp[i].transport; - call->media[0].tp_auto_del = auto_delete; + call->media[0].tp = tp[i].transport; + call->media[0].tp_auto_del = auto_delete; } return PJ_SUCCESS; @@ -1436,11 +1435,11 @@ PJ_DEF(pj_status_t) pjsua_media_transports_attach(pjsua_media_transport tp[], * 4. media order (according to the SDP). */ static void sort_media(const pjmedia_sdp_session *sdp, - const pj_str_t *type, - pjmedia_srtp_use use_srtp, - pj_uint8_t midx[], - unsigned *p_count, - unsigned *p_total_count) + const pj_str_t *type, + pjmedia_srtp_use use_srtp, + pj_uint8_t midx[], + unsigned *p_count, + unsigned *p_total_count) { unsigned i; unsigned count = 0; @@ -1452,88 +1451,88 @@ static void sort_media(const pjmedia_sdp_session *sdp, *p_count = 0; *p_total_count = 0; for (i=0; imedia_count && countmedia[i]; - const pjmedia_sdp_conn *c; - pj_uint32_t proto; - - /* Skip different media */ - if (pj_stricmp(&m->desc.media, type) != 0) { - score[count++] = -22000; - continue; - } - - c = m->conn? m->conn : sdp->conn; - - /* Supported transports */ - proto = pjmedia_sdp_transport_get_proto(&m->desc.transport); - if (PJMEDIA_TP_PROTO_HAS_FLAG(proto, PJMEDIA_TP_PROTO_RTP_SAVP)) - { - switch (use_srtp) { - case PJMEDIA_SRTP_MANDATORY: - case PJMEDIA_SRTP_OPTIONAL: - ++score[i]; - break; - case PJMEDIA_SRTP_DISABLED: - //--score[i]; - score[i] -= 5; - break; - } - } else if (PJMEDIA_TP_PROTO_HAS_FLAG(proto, PJMEDIA_TP_PROTO_RTP_AVP)) - { - switch (use_srtp) { - case PJMEDIA_SRTP_MANDATORY: - //--score[i]; - score[i] -= 5; - break; - case PJMEDIA_SRTP_OPTIONAL: - /* No change in score */ - break; - case PJMEDIA_SRTP_DISABLED: - ++score[i]; - break; - } - } else { - score[i] -= 10; - } - - /* Is media disabled? */ - if (m->desc.port == 0) - score[i] -= 10; - - /* Is media inactive? */ - if (pjmedia_sdp_media_find_attr2(m, "inactive", NULL) || - pj_strcmp2(&c->addr, "0.0.0.0") == 0) - { - //score[i] -= 10; - score[i] -= 1; - } - - ++count; + const pjmedia_sdp_media *m = sdp->media[i]; + const pjmedia_sdp_conn *c; + pj_uint32_t proto; + + /* Skip different media */ + if (pj_stricmp(&m->desc.media, type) != 0) { + score[count++] = -22000; + continue; + } + + c = m->conn? m->conn : sdp->conn; + + /* Supported transports */ + proto = pjmedia_sdp_transport_get_proto(&m->desc.transport); + if (PJMEDIA_TP_PROTO_HAS_FLAG(proto, PJMEDIA_TP_PROTO_RTP_SAVP)) + { + switch (use_srtp) { + case PJMEDIA_SRTP_MANDATORY: + case PJMEDIA_SRTP_OPTIONAL: + ++score[i]; + break; + case PJMEDIA_SRTP_DISABLED: + //--score[i]; + score[i] -= 5; + break; + } + } else if (PJMEDIA_TP_PROTO_HAS_FLAG(proto, PJMEDIA_TP_PROTO_RTP_AVP)) + { + switch (use_srtp) { + case PJMEDIA_SRTP_MANDATORY: + //--score[i]; + score[i] -= 5; + break; + case PJMEDIA_SRTP_OPTIONAL: + /* No change in score */ + break; + case PJMEDIA_SRTP_DISABLED: + ++score[i]; + break; + } + } else { + score[i] -= 10; + } + + /* Is media disabled? */ + if (m->desc.port == 0) + score[i] -= 10; + + /* Is media inactive? */ + if (pjmedia_sdp_media_find_attr2(m, "inactive", NULL) || + pj_strcmp2(&c->addr, "0.0.0.0") == 0) + { + //score[i] -= 10; + score[i] -= 1; + } + + ++count; } /* Created sorted list based on quality */ for (i=0; i score[best]) - best = j; - } - /* Don't put media with negative score, that media is unacceptable - * for us. - */ - midx[i] = (pj_uint8_t)best; - if (score[best] >= 0) - (*p_count)++; - if (score[best] > -22000) - (*p_total_count)++; - - score[best] = -22000; + unsigned j; + int best = 0; + + for (j=1; j score[best]) + best = j; + } + /* Don't put media with negative score, that media is unacceptable + * for us. + */ + midx[i] = (pj_uint8_t)best; + if (score[best] >= 0) + (*p_count)++; + if (score[best] > -22000) + (*p_total_count)++; + + score[best] = -22000; } } @@ -1545,12 +1544,12 @@ static void sort_media(const pjmedia_sdp_session *sdp, * first in the array. */ static void sort_media2(const pjsua_call_media *call_med, - pj_bool_t check_tp, - unsigned call_med_cnt, - pjmedia_type type, - pj_uint8_t midx[], - unsigned *p_count, - unsigned *p_total_count) + pj_bool_t check_tp, + unsigned call_med_cnt, + pjmedia_type type, + pj_uint8_t midx[], + unsigned *p_count, + unsigned *p_total_count) { unsigned i; unsigned count = 0; @@ -1562,44 +1561,44 @@ static void sort_media2(const pjsua_call_media *call_med, *p_count = 0; *p_total_count = 0; for (i=0; i score[best]) - best = j; - } - /* Don't put media with negative score, that media is unacceptable - * for us. - */ - midx[i] = (pj_uint8_t)best; - if (score[best] >= 0) - (*p_count)++; - if (score[best] > -22000) - (*p_total_count)++; - - score[best] = -22000; + unsigned j; + int best = 0; + + for (j=1; j score[best]) + best = j; + } + /* Don't put media with negative score, that media is unacceptable + * for us. + */ + midx[i] = (pj_uint8_t)best; + if (score[best] >= 0) + (*p_count)++; + if (score[best] > -22000) + (*p_total_count)++; + + score[best] = -22000; } } @@ -1614,11 +1613,11 @@ pj_status_t on_media_event(pjmedia_event *event, void *user_data) pjmedia_fourcc_name(event->type, ev_name); PJ_LOG(4,(THIS_FILE, "Received media event type=%s, src=%p, epub=%p", - ev_name, event->src, event->epub)); + ev_name, event->src, event->epub)); /* Forward the event */ if (pjsua_var.ua_cfg.cb.on_media_event) { - (*pjsua_var.ua_cfg.cb.on_media_event)(event); + (*pjsua_var.ua_cfg.cb.on_media_event)(event); } return status; @@ -1630,8 +1629,8 @@ void call_med_event_cb(void *user_data) pjsua_event_list *eve = (pjsua_event_list *)user_data; (*pjsua_var.ua_cfg.cb.on_call_media_event)(eve->call_id, - eve->med_idx, - &eve->event); + eve->med_idx, + &eve->event); pj_mutex_lock(pjsua_var.timer_mutex); pj_list_push_back(&pjsua_var.event_list, eve); @@ -1649,123 +1648,123 @@ pj_status_t call_media_on_event(pjmedia_event *event, pjmedia_fourcc_name(event->type, ev_name); PJ_LOG(5,(THIS_FILE, "Call %d: Media %d: Received media event, type=%s, " - "src=%p, epub=%p", - call->index, call_med->idx, ev_name, - event->src, event->epub)); + "src=%p, epub=%p", + call->index, call_med->idx, ev_name, + event->src, event->epub)); switch(event->type) { - case PJMEDIA_EVENT_KEYFRAME_MISSING: - if (call->opt.req_keyframe_method & PJSUA_VID_REQ_KEYFRAME_SIP_INFO) - { - pj_timestamp now; - - pj_get_timestamp(&now); - if (pj_elapsed_msec(&call_med->last_req_keyframe, &now) >= - PJSUA_VID_REQ_KEYFRAME_INTERVAL) - { - pjsua_msg_data msg_data; - const pj_str_t SIP_INFO = {"INFO", 4}; - const char *BODY_TYPE = "application/media_control+xml"; - const char *BODY = - "" - "" - "" - ""; - - PJ_LOG(4,(THIS_FILE, - "Sending video keyframe request via SIP INFO")); - - pjsua_msg_data_init(&msg_data); - pj_cstr(&msg_data.content_type, BODY_TYPE); - pj_cstr(&msg_data.msg_body, BODY); - status = pjsua_call_send_request(call->index, &SIP_INFO, - &msg_data); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, - "Failed requesting keyframe via SIP INFO")); - } else { - call_med->last_req_keyframe = now; - } - } - } - break; + case PJMEDIA_EVENT_KEYFRAME_MISSING: + if (call->opt.req_keyframe_method & PJSUA_VID_REQ_KEYFRAME_SIP_INFO) + { + pj_timestamp now; + + pj_get_timestamp(&now); + if (pj_elapsed_msec(&call_med->last_req_keyframe, &now) >= + PJSUA_VID_REQ_KEYFRAME_INTERVAL) + { + pjsua_msg_data msg_data; + const pj_str_t SIP_INFO = {"INFO", 4}; + const char *BODY_TYPE = "application/media_control+xml"; + const char *BODY = + "" + "" + "" + ""; + + PJ_LOG(4,(THIS_FILE, + "Sending video keyframe request via SIP INFO")); + + pjsua_msg_data_init(&msg_data); + pj_cstr(&msg_data.content_type, BODY_TYPE); + pj_cstr(&msg_data.msg_body, BODY); + status = pjsua_call_send_request(call->index, &SIP_INFO, + &msg_data); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(THIS_FILE, status, + "Failed requesting keyframe via SIP INFO")); + } else { + call_med->last_req_keyframe = now; + } + } + } + break; #if PJSUA_HAS_VIDEO - case PJMEDIA_EVENT_FMT_CHANGED: - if (call_med->strm.v.rdr_win_id != PJSUA_INVALID_ID) { - pjsua_vid_win *w = &pjsua_var.win[call_med->strm.v.rdr_win_id]; - if (event->epub == w->vp_rend) { - /* Renderer just changed format, update its - * conference bridge port. - */ - pjsua_vid_conf_update_port(w->rend_slot); - } - } - - if (call_med->strm.v.strm_dec_slot != PJSUA_INVALID_ID) { - /* Stream decoder changed format, update all conf listeners - * by reconnecting. - */ - pjmedia_port *strm_dec; - - status = pjmedia_vid_stream_get_port(call_med->strm.v.stream, - PJMEDIA_DIR_DECODING, - &strm_dec); - if (status != PJ_SUCCESS) - break; - - /* Verify that the publisher is the stream decoder */ - if (event->epub != strm_dec) - break; - - /* Stream decoder just changed format, update its - * conference bridge port. - */ - pjsua_vid_conf_update_port(call_med->strm.v.strm_dec_slot); - } - break; - - case PJMEDIA_EVENT_VID_DEV_ERROR: - { - PJ_PERROR(3,(THIS_FILE, event->data.vid_dev_err.status, - "Video device id=%d error for call %d", - event->data.vid_dev_err.id, - call->index)); - } - break; + case PJMEDIA_EVENT_FMT_CHANGED: + if (call_med->strm.v.rdr_win_id != PJSUA_INVALID_ID) { + pjsua_vid_win *w = &pjsua_var.win[call_med->strm.v.rdr_win_id]; + if (event->epub == w->vp_rend) { + /* Renderer just changed format, update its + * conference bridge port. + */ + pjsua_vid_conf_update_port(w->rend_slot); + } + } + + if (call_med->strm.v.strm_dec_slot != PJSUA_INVALID_ID) { + /* Stream decoder changed format, update all conf listeners + * by reconnecting. + */ + pjmedia_port *strm_dec; + + status = pjmedia_vid_stream_get_port(call_med->strm.v.stream, + PJMEDIA_DIR_DECODING, + &strm_dec); + if (status != PJ_SUCCESS) + break; + + /* Verify that the publisher is the stream decoder */ + if (event->epub != strm_dec) + break; + + /* Stream decoder just changed format, update its + * conference bridge port. + */ + pjsua_vid_conf_update_port(call_med->strm.v.strm_dec_slot); + } + break; + + case PJMEDIA_EVENT_VID_DEV_ERROR: + { + PJ_PERROR(3,(THIS_FILE, event->data.vid_dev_err.status, + "Video device id=%d error for call %d", + event->data.vid_dev_err.id, + call->index)); + } + break; #endif - default: - break; + default: + break; } if (pjsua_var.ua_cfg.cb.on_call_media_event) { - pjsua_event_list *eve = NULL; + pjsua_event_list *eve = NULL; - pj_mutex_lock(pjsua_var.timer_mutex); + pj_mutex_lock(pjsua_var.timer_mutex); - if (pj_list_empty(&pjsua_var.event_list)) { + if (pj_list_empty(&pjsua_var.event_list)) { eve = PJ_POOL_ALLOC_T(pjsua_var.timer_pool, pjsua_event_list); - } else { + } else { eve = pjsua_var.event_list.next; pj_list_erase(eve); - } - - pj_mutex_unlock(pjsua_var.timer_mutex); - - if (call) { - if (call->hanging_up) - return status; - - eve->call_id = call->index; - eve->med_idx = call_med->idx; - } else { - /* Also deliver non call events such as audio device error */ - eve->call_id = PJSUA_INVALID_ID; - eve->med_idx = 0; - } - pj_memcpy(&eve->event, event, sizeof(pjmedia_event)); - pjsua_schedule_timer2(&call_med_event_cb, eve, 1); + } + + pj_mutex_unlock(pjsua_var.timer_mutex); + + if (call) { + if (call->hanging_up) + return status; + + eve->call_id = call->index; + eve->med_idx = call_med->idx; + } else { + /* Also deliver non call events such as audio device error */ + eve->call_id = PJSUA_INVALID_ID; + eve->med_idx = 0; + } + pj_memcpy(&eve->event, event, sizeof(pjmedia_event)); + pjsua_schedule_timer2(&call_med_event_cb, eve, 1); } return status; @@ -1785,7 +1784,7 @@ void pjsua_set_media_tp_state(pjsua_call_media *call_med, info.med_idx = call_med->idx; info.state = tp_st; info.status = call_med->tp_ready; - (*pjsua_var.ua_cfg.cb.on_call_media_transport_state)( + (*pjsua_var.ua_cfg.cb.on_call_media_transport_state)( call_med->call->index, &info); } @@ -1795,29 +1794,29 @@ void pjsua_set_media_tp_state(pjsua_call_media *call_med, /* This callback is called when SRTP negotiation completes */ static void on_srtp_nego_complete(pjmedia_transport *tp, - pj_status_t result) + pj_status_t result) { pjsua_call_media *call_med = (pjsua_call_media*)tp->user_data; pjsua_call *call; if (!call_med) - return; + return; call = call_med->call; PJ_PERROR(4,(THIS_FILE, result, - "Call %d: Media %d: SRTP negotiation completes", - call->index, call_med->idx)); + "Call %d: Media %d: SRTP negotiation completes", + call->index, call_med->idx)); if (result != PJ_SUCCESS) { - call_med->state = PJSUA_CALL_MEDIA_ERROR; - call_med->dir = PJMEDIA_DIR_NONE; - if (call && !call->hanging_up && - pjsua_var.ua_cfg.cb.on_call_media_state) - { - /* Defer the callback to a timer */ - pjsua_schedule_timer2(&ice_failed_nego_cb, - (void*)(pj_ssize_t)call->index, 1); - } + call_med->state = PJSUA_CALL_MEDIA_ERROR; + call_med->dir = PJMEDIA_DIR_NONE; + if (call && !call->hanging_up && + pjsua_var.ua_cfg.cb.on_call_media_state) + { + /* Defer the callback to a timer */ + pjsua_schedule_timer2(&ice_failed_nego_cb, + (void*)(pj_ssize_t)call->index, 1); + } } } @@ -1835,15 +1834,15 @@ static pj_status_t call_media_init_cb(pjsua_call_media *call_med, int err_code = 0; if (status != PJ_SUCCESS) { - err_code = PJSIP_SC_TEMPORARILY_UNAVAILABLE; + err_code = PJSIP_SC_TEMPORARILY_UNAVAILABLE; goto on_return; } pjmedia_transport_simulate_lost(call_med->tp, PJMEDIA_DIR_ENCODING, - pjsua_var.media_cfg.tx_drop_pct); + pjsua_var.media_cfg.tx_drop_pct); pjmedia_transport_simulate_lost(call_med->tp, PJMEDIA_DIR_DECODING, - pjsua_var.media_cfg.rx_drop_pct); + pjsua_var.media_cfg.rx_drop_pct); if (call_med->tp_st == PJSUA_MED_TP_CREATING) pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_IDLE); @@ -1860,79 +1859,79 @@ static pj_status_t call_media_init_cb(pjsua_call_media *call_med, * (e.g: in re-invite, update), don't need to destroy/re-create. */ if (!call_med->tp_orig) { - pjmedia_srtp_setting srtp_opt; - pjsua_srtp_opt *acc_srtp_opt = &acc->cfg.srtp_opt; - pjmedia_transport *srtp = NULL; - unsigned i; - - /* Check if SRTP requires secure signaling */ - if (acc->cfg.use_srtp != PJMEDIA_SRTP_DISABLED) { - if (security_level < acc->cfg.srtp_secure_signaling) { - err_code = PJSIP_SC_NOT_ACCEPTABLE; - status = PJSIP_ESESSIONINSECURE; - goto on_return; - } - } - - /* Always create SRTP adapter */ - pjmedia_srtp_setting_default(&srtp_opt); - srtp_opt.close_member_tp = PJ_TRUE; - srtp_opt.cb.on_srtp_nego_complete = &on_srtp_nego_complete; - srtp_opt.user_data = call_med; - - /* Get crypto and keying settings from account settings */ - srtp_opt.crypto_count = acc_srtp_opt->crypto_count; - for (i = 0; i < srtp_opt.crypto_count; ++i) - srtp_opt.crypto[i] = acc_srtp_opt->crypto[i]; - srtp_opt.keying_count = acc_srtp_opt->keying_count; - for (i = 0; i < srtp_opt.keying_count; ++i) - srtp_opt.keying[i] = acc_srtp_opt->keying[i]; - - /* If media session has been ever established, let's use remote's - * preference in SRTP usage policy, especially when it is stricter. - */ - if (call_med->rem_srtp_use > acc->cfg.use_srtp) - srtp_opt.use = call_med->rem_srtp_use; - else - srtp_opt.use = acc->cfg.use_srtp; - - if (pjsua_var.ua_cfg.cb.on_create_media_transport_srtp) { - pjmedia_srtp_setting srtp_opt2 = srtp_opt; - pjsua_call *call = call_med->call; - - /* Warn that this callback is deprecated (see also #2100) */ - PJ_LOG(1,(THIS_FILE, "Warning: on_create_media_transport_srtp " - "is deprecated and will be removed in the " - "future release")); - - (*pjsua_var.ua_cfg.cb.on_create_media_transport_srtp) - (call->index, call_med->idx, &srtp_opt2); - - /* Only apply SRTP usage policy if this is initial INVITE */ - if (call->inv && call->inv->state < PJSIP_INV_STATE_CONFIRMED) { - srtp_opt.use = srtp_opt2.use; - } - - /* Apply crypto and keying settings from callback */ - srtp_opt.crypto_count = srtp_opt2.crypto_count; - for (i = 0; i < srtp_opt.crypto_count; ++i) - srtp_opt.crypto[i] = srtp_opt2.crypto[i]; - srtp_opt.keying_count = srtp_opt2.keying_count; - for (i = 0; i < srtp_opt.keying_count; ++i) - srtp_opt.keying[i] = srtp_opt2.keying[i]; - } - - status = pjmedia_transport_srtp_create(pjsua_var.med_endpt, - call_med->tp, - &srtp_opt, &srtp); - if (status != PJ_SUCCESS) { - err_code = PJSIP_SC_INTERNAL_SERVER_ERROR; - goto on_return; - } - - /* Set SRTP as current media transport */ - call_med->tp_orig = call_med->tp; - call_med->tp = srtp; + pjmedia_srtp_setting srtp_opt; + pjsua_srtp_opt *acc_srtp_opt = &acc->cfg.srtp_opt; + pjmedia_transport *srtp = NULL; + unsigned i; + + /* Check if SRTP requires secure signaling */ + if (acc->cfg.use_srtp != PJMEDIA_SRTP_DISABLED) { + if (security_level < acc->cfg.srtp_secure_signaling) { + err_code = PJSIP_SC_NOT_ACCEPTABLE; + status = PJSIP_ESESSIONINSECURE; + goto on_return; + } + } + + /* Always create SRTP adapter */ + pjmedia_srtp_setting_default(&srtp_opt); + srtp_opt.close_member_tp = PJ_TRUE; + srtp_opt.cb.on_srtp_nego_complete = &on_srtp_nego_complete; + srtp_opt.user_data = call_med; + + /* Get crypto and keying settings from account settings */ + srtp_opt.crypto_count = acc_srtp_opt->crypto_count; + for (i = 0; i < srtp_opt.crypto_count; ++i) + srtp_opt.crypto[i] = acc_srtp_opt->crypto[i]; + srtp_opt.keying_count = acc_srtp_opt->keying_count; + for (i = 0; i < srtp_opt.keying_count; ++i) + srtp_opt.keying[i] = acc_srtp_opt->keying[i]; + + /* If media session has been ever established, let's use remote's + * preference in SRTP usage policy, especially when it is stricter. + */ + if (call_med->rem_srtp_use > acc->cfg.use_srtp) + srtp_opt.use = call_med->rem_srtp_use; + else + srtp_opt.use = acc->cfg.use_srtp; + + if (pjsua_var.ua_cfg.cb.on_create_media_transport_srtp) { + pjmedia_srtp_setting srtp_opt2 = srtp_opt; + pjsua_call *call = call_med->call; + + /* Warn that this callback is deprecated (see also #2100) */ + PJ_LOG(1,(THIS_FILE, "Warning: on_create_media_transport_srtp " + "is deprecated and will be removed in the " + "future release")); + + (*pjsua_var.ua_cfg.cb.on_create_media_transport_srtp) + (call->index, call_med->idx, &srtp_opt2); + + /* Only apply SRTP usage policy if this is initial INVITE */ + if (call->inv && call->inv->state < PJSIP_INV_STATE_CONFIRMED) { + srtp_opt.use = srtp_opt2.use; + } + + /* Apply crypto and keying settings from callback */ + srtp_opt.crypto_count = srtp_opt2.crypto_count; + for (i = 0; i < srtp_opt.crypto_count; ++i) + srtp_opt.crypto[i] = srtp_opt2.crypto[i]; + srtp_opt.keying_count = srtp_opt2.keying_count; + for (i = 0; i < srtp_opt.keying_count; ++i) + srtp_opt.keying[i] = srtp_opt2.keying[i]; + } + + status = pjmedia_transport_srtp_create(pjsua_var.med_endpt, + call_med->tp, + &srtp_opt, &srtp); + if (status != PJ_SUCCESS) { + err_code = PJSIP_SC_INTERNAL_SERVER_ERROR; + goto on_return; + } + + /* Set SRTP as current media transport */ + call_med->tp_orig = call_med->tp; + call_med->tp = srtp; } #else call_med->tp_orig = call_med->tp; @@ -1948,17 +1947,17 @@ static pj_status_t call_media_init_cb(pjsua_call_media *call_med, on_return: if (status != PJ_SUCCESS) { - if (call_med->tp) { - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); - pjmedia_transport_close(call_med->tp); - call_med->tp = NULL; - } + if (call_med->tp) { + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); + pjmedia_transport_close(call_med->tp); + call_med->tp = NULL; + } - if (err_code == 0) - err_code = PJSIP_ERRNO_TO_SIP_STATUS(status); + if (err_code == 0) + err_code = PJSIP_ERRNO_TO_SIP_STATUS(status); - if (sip_err_code) - *sip_err_code = err_code; + if (sip_err_code) + *sip_err_code = err_code; } if (call_med->med_init_cb) { @@ -1992,9 +1991,9 @@ pj_bool_t pjsua_call_media_is_changing(pjsua_call *call) /* Initialize the media line */ pj_status_t pjsua_call_media_init(pjsua_call_media *call_med, pjmedia_type type, - const pjsua_transport_config *tcfg, - int security_level, - int *sip_err_code, + const pjsua_transport_config *tcfg, + int security_level, + int *sip_err_code, pj_bool_t async, pjsua_med_tp_state_cb cb) { @@ -2015,7 +2014,7 @@ pj_status_t pjsua_call_media_init(pjsua_call_media *call_med, * the unused transport of a disabled media. */ if (call_med->tp == NULL) { - pjsua_acc *acc = &pjsua_var.acc[call_med->call->acc_id]; + pjsua_acc *acc = &pjsua_var.acc[call_med->call->acc_id]; /* Initializations. If media transport creation completes immediately, * we don't need to call the callbacks. @@ -2024,47 +2023,47 @@ pj_status_t pjsua_call_media_init(pjsua_call_media *call_med, call_med->med_create_cb = NULL; #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) - /* While in initial call, set default video devices */ - if (type == PJMEDIA_TYPE_VIDEO) { - status = pjsua_vid_channel_init(call_med); - if (status != PJ_SUCCESS) - return status; - } + /* While in initial call, set default video devices */ + if (type == PJMEDIA_TYPE_VIDEO) { + status = pjsua_vid_channel_init(call_med); + if (status != PJ_SUCCESS) + return status; + } #endif pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_CREATING); - if (acc->cfg.use_loop_med_tp) { - status = create_loop_media_transport(tcfg, call_med); - } else if (acc->cfg.ice_cfg.enable_ice) { - status = create_ice_media_transport(tcfg, call_med, async); + if (acc->cfg.use_loop_med_tp) { + status = create_loop_media_transport(tcfg, call_med); + } else if (acc->cfg.ice_cfg.enable_ice) { + status = create_ice_media_transport(tcfg, call_med, async); if (async && status == PJ_EPENDING) { - /* We will resume call media initialization in the - * on_ice_complete() callback. - */ + /* We will resume call media initialization in the + * on_ice_complete() callback. + */ call_med->med_create_cb = &call_media_init_cb; call_med->med_init_cb = cb; - return PJ_EPENDING; - } - } else { - status = create_udp_media_transport(tcfg, call_med); - } + return PJ_EPENDING; + } + } else { + status = create_udp_media_transport(tcfg, call_med); + } if (status != PJ_SUCCESS) { - if (sip_err_code) - *sip_err_code = PJSIP_SC_INTERNAL_SERVER_ERROR; - call_med->tp_ready = status; - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); - pjsua_perror(THIS_FILE, "Error creating media transport", status); - return status; - } + if (sip_err_code) + *sip_err_code = PJSIP_SC_INTERNAL_SERVER_ERROR; + call_med->tp_ready = status; + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); + pjsua_perror(THIS_FILE, "Error creating media transport", status); + return status; + } } else if (call_med->tp_st == PJSUA_MED_TP_DISABLED) { - /* Media is being reenabled. */ - //pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_IDLE); + /* Media is being reenabled. */ + //pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_IDLE); - pj_assert(!"Currently no media transport reuse"); + pj_assert(!"Currently no media transport reuse"); } return call_media_init_cb(call_med, status, security_level, @@ -2120,26 +2119,26 @@ static pj_status_t media_channel_init_cb(pjsua_call_id call_id, } PJ_PERROR(5,(THIS_FILE, status, - "Call %d: media transport initialization complete", call_id)); + "Call %d: media transport initialization complete", call_id)); if (status != PJ_SUCCESS) { - if (call->med_ch_info.status == PJ_SUCCESS) { - call->med_ch_info.status = status; - call->med_ch_info.sip_err_code = PJSIP_SC_TEMPORARILY_UNAVAILABLE; - } + if (call->med_ch_info.status == PJ_SUCCESS) { + call->med_ch_info.status = status; + call->med_ch_info.sip_err_code = PJSIP_SC_TEMPORARILY_UNAVAILABLE; + } - /* Revert back provisional media. */ - pjsua_media_prov_revert(call_id); + /* Revert back provisional media. */ + pjsua_media_prov_revert(call_id); - goto on_return; + goto on_return; } /* Tell the media transport of a new offer/answer session */ for (mi=0; mi < call->med_prov_cnt; ++mi) { - pjsua_call_media *call_med = &call->media_prov[mi]; + pjsua_call_media *call_med = &call->media_prov[mi]; - /* Note: tp may be NULL if this media line is disabled */ - if (call_med->tp && call_med->tp_st == PJSUA_MED_TP_IDLE) { + /* Note: tp may be NULL if this media line is disabled */ + if (call_med->tp && call_med->tp_st == PJSUA_MED_TP_IDLE) { pj_pool_t *tmp_pool = call->async_call.pool_prov; if (!tmp_pool) { @@ -2162,26 +2161,26 @@ static pj_status_t media_channel_init_cb(pjsua_call_id call_id, } if (call_med->tp) { - unsigned options = (call_med->enable_rtcp_mux? - PJMEDIA_TPMED_RTCP_MUX: 0); + unsigned options = (call_med->enable_rtcp_mux? + PJMEDIA_TPMED_RTCP_MUX: 0); status = pjmedia_transport_media_create( call_med->tp, tmp_pool, options, call->async_call.rem_sdp, mi); } - if (status != PJ_SUCCESS) { + if (status != PJ_SUCCESS) { call->med_ch_info.status = status; call->med_ch_info.med_idx = mi; call->med_ch_info.state = call_med->tp_st; call->med_ch_info.sip_err_code = PJSIP_SC_TEMPORARILY_UNAVAILABLE; - /* Revert back provisional media. */ - pjsua_media_prov_revert(call_id); + /* Revert back provisional media. */ + pjsua_media_prov_revert(call_id); - goto on_return; - } + goto on_return; + } - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_INIT); - } + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_INIT); + } } call->med_ch_info.status = PJ_SUCCESS; @@ -2204,34 +2203,34 @@ void pjsua_media_prov_clean_up(pjsua_call_id call_id) if (call->med_prov_cnt > call->med_cnt) { PJ_LOG(4,(THIS_FILE, "Call %d: cleaning up provisional media, " - "prov_med_cnt=%d, med_cnt=%d", - call_id, call->med_prov_cnt, call->med_cnt)); + "prov_med_cnt=%d, med_cnt=%d", + call_id, call->med_prov_cnt, call->med_cnt)); } for (i = 0; i < call->med_prov_cnt; ++i) { - pjsua_call_media *call_med = &call->media_prov[i]; - unsigned j; - pj_bool_t used = PJ_FALSE; - - if (call_med->tp == NULL) - continue; - - for (j = 0; j < call->med_cnt; ++j) { - if (call->media[j].tp == call_med->tp) { - used = PJ_TRUE; - break; - } - } - - if (!used) { - if (call_med->tp_st > PJSUA_MED_TP_IDLE) { - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_IDLE); - pjmedia_transport_media_stop(call_med->tp); - } - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); - pjmedia_transport_close(call_med->tp); - call_med->tp = call_med->tp_orig = NULL; - } + pjsua_call_media *call_med = &call->media_prov[i]; + unsigned j; + pj_bool_t used = PJ_FALSE; + + if (call_med->tp == NULL) + continue; + + for (j = 0; j < call->med_cnt; ++j) { + if (call->media[j].tp == call_med->tp) { + used = PJ_TRUE; + break; + } + } + + if (!used) { + if (call_med->tp_st > PJSUA_MED_TP_IDLE) { + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_IDLE); + pjmedia_transport_media_stop(call_med->tp); + } + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); + pjmedia_transport_close(call_med->tp); + call_med->tp = call_med->tp_orig = NULL; + } } // Cleaning up unused media transports should not change provisional @@ -2250,17 +2249,17 @@ void pjsua_media_prov_revert(pjsua_call_id call_id) /* Copy provisional media from active media */ pj_memcpy(call->media_prov, call->media, - sizeof(call->media[0]) * call->med_cnt); + sizeof(call->media[0]) * call->med_cnt); call->med_prov_cnt = call->med_cnt; } pj_status_t pjsua_media_channel_init(pjsua_call_id call_id, - pjsip_role_e role, - int security_level, - pj_pool_t *tmp_pool, - const pjmedia_sdp_session *rem_sdp, - int *sip_err_code, + pjsip_role_e role, + int security_level, + pj_pool_t *tmp_pool, + const pjmedia_sdp_session *rem_sdp, + int *sip_err_code, pj_bool_t async, pjsua_med_tp_state_cb cb) { @@ -2288,8 +2287,8 @@ pj_status_t pjsua_media_channel_init(pjsua_call_id call_id, if (pjsua_get_state() != PJSUA_STATE_RUNNING) { if (sip_err_code) - *sip_err_code = PJSIP_SC_SERVICE_UNAVAILABLE; - return PJ_EBUSY; + *sip_err_code = PJSIP_SC_SERVICE_UNAVAILABLE; + return PJ_EBUSY; } if (async) { @@ -2297,36 +2296,36 @@ pj_status_t pjsua_media_channel_init(pjsua_call_id call_id, call->async_call.dlg->pool); status = pj_mutex_create_simple(tmppool, NULL, &call->med_ch_mutex); - if (status != PJ_SUCCESS) { - if (sip_err_code) - *sip_err_code = PJSIP_SC_INTERNAL_SERVER_ERROR; + if (status != PJ_SUCCESS) { + if (sip_err_code) + *sip_err_code = PJSIP_SC_INTERNAL_SERVER_ERROR; return status; - } + } } if (call->inv && call->inv->state == PJSIP_INV_STATE_CONFIRMED) - reinit = PJ_TRUE; + reinit = PJ_TRUE; PJ_LOG(4,(THIS_FILE, "Call %d: %sinitializing media..", - call_id, (reinit?"re-":"") )); + call_id, (reinit?"re-":"") )); pj_log_push_indent(); /* Init provisional media state */ if (call->med_cnt == 0) { - /* New media session, just copy whole from call media state. */ - pj_memcpy(call->media_prov, call->media, sizeof(call->media)); + /* New media session, just copy whole from call media state. */ + pj_memcpy(call->media_prov, call->media, sizeof(call->media)); } else { - /* Clean up any unused transports. Note that when local SDP reoffer - * is rejected by remote, there may be any initialized transports that - * are not used by call media and currently there is no notification - * from PJSIP level regarding the reoffer rejection. - */ - pjsua_media_prov_clean_up(call_id); - - /* Updating media session, copy from call media state. */ - pj_memcpy(call->media_prov, call->media, - sizeof(call->media[0]) * call->med_cnt); + /* Clean up any unused transports. Note that when local SDP reoffer + * is rejected by remote, there may be any initialized transports that + * are not used by call media and currently there is no notification + * from PJSIP level regarding the reoffer rejection. + */ + pjsua_media_prov_clean_up(call_id); + + /* Updating media session, copy from call media state. */ + pj_memcpy(call->media_prov, call->media, + sizeof(call->media[0]) * call->med_cnt); } call->med_prov_cnt = call->med_cnt; @@ -2335,153 +2334,153 @@ pj_status_t pjsua_media_channel_init(pjsua_call_id call_id, * (e.g. application is starting) */ for (i=0; imed_cnt; ++i) { - if (call->media[i].tp == NULL) { - status = PJ_EBUSY; - goto on_error; - } + if (call->media[i].tp == NULL) { + status = PJ_EBUSY; + goto on_error; + } } #endif /* Get media count for each media type */ if (rem_sdp) { - /* We are sending answer, check media count for each media type - * from the remote SDP. - */ - sort_media(rem_sdp, &STR_AUDIO, acc->cfg.use_srtp, - maudidx, &maudcnt, &mtotaudcnt); + /* We are sending answer, check media count for each media type + * from the remote SDP. + */ + sort_media(rem_sdp, &STR_AUDIO, acc->cfg.use_srtp, + maudidx, &maudcnt, &mtotaudcnt); #if PJMEDIA_HAS_VIDEO - sort_media(rem_sdp, &STR_VIDEO, acc->cfg.use_srtp, - mvididx, &mvidcnt, &mtotvidcnt); + sort_media(rem_sdp, &STR_VIDEO, acc->cfg.use_srtp, + mvididx, &mvidcnt, &mtotvidcnt); #else - mvidcnt = mtotvidcnt = 0; - PJ_UNUSED_ARG(STR_VIDEO); + mvidcnt = mtotvidcnt = 0; + PJ_UNUSED_ARG(STR_VIDEO); #endif - if (maudcnt + mvidcnt == 0) { - /* Expecting audio or video in the offer */ - if (sip_err_code) - *sip_err_code = PJSIP_SC_NOT_ACCEPTABLE_HERE; - status = PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_NOT_ACCEPTABLE_HERE); - goto on_error; - } - - /* Update media count only when remote add any media, this media count - * must never decrease. Also note that we shouldn't apply the media - * count setting (of the call setting) before the SDP negotiation. - */ - if (call->med_prov_cnt < rem_sdp->media_count) - call->med_prov_cnt = PJ_MIN(rem_sdp->media_count, - PJSUA_MAX_CALL_MEDIA); - - call->rem_offerer = PJ_TRUE; - call->rem_aud_cnt = maudcnt; - call->rem_vid_cnt = mvidcnt; + if (maudcnt + mvidcnt == 0) { + /* Expecting audio or video in the offer */ + if (sip_err_code) + *sip_err_code = PJSIP_SC_NOT_ACCEPTABLE_HERE; + status = PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_NOT_ACCEPTABLE_HERE); + goto on_error; + } + + /* Update media count only when remote add any media, this media count + * must never decrease. Also note that we shouldn't apply the media + * count setting (of the call setting) before the SDP negotiation. + */ + if (call->med_prov_cnt < rem_sdp->media_count) + call->med_prov_cnt = PJ_MIN(rem_sdp->media_count, + PJSUA_MAX_CALL_MEDIA); + + call->rem_offerer = PJ_TRUE; + call->rem_aud_cnt = maudcnt; + call->rem_vid_cnt = mvidcnt; } else { - /* If call is already established, adjust the existing call media list - * to media count setting in call setting, e.g: re-enable/disable/add - * media from existing media. - * Otherwise, apply media count from the call setting directly. - */ - if (reinit) { - pj_bool_t sort_check_tp; - - /* Media sorting below will check transport, i.e: media without - * transport will have lower priority. If PJSUA_CALL_REINIT_MEDIA - * is set, we must not check transport. - */ - sort_check_tp = !(call->opt.flag & PJSUA_CALL_REINIT_MEDIA); - - /* We are sending reoffer, check media count for each media type - * from the existing call media list. - */ - sort_media2(call->media_prov, sort_check_tp, call->med_prov_cnt, - PJMEDIA_TYPE_AUDIO, maudidx, &maudcnt, &mtotaudcnt); - - /* No need to assert if there's no media. */ - //pj_assert(maudcnt > 0); - - sort_media2(call->media_prov, sort_check_tp, call->med_prov_cnt, - PJMEDIA_TYPE_VIDEO, mvididx, &mvidcnt, &mtotvidcnt); - - /* Call setting may add or remove media. Adding media is done by - * enabling any disabled/port-zeroed media first, then adding new - * media whenever needed. Removing media is done by disabling - * media with the lowest 'quality'. - */ - - /* Check if we need to add new audio */ - if (maudcnt < call->opt.aud_cnt && - mtotaudcnt < call->opt.aud_cnt) - { - for (mi = 0; mi < call->opt.aud_cnt - mtotaudcnt; ++mi) - maudidx[maudcnt++] = (pj_uint8_t)call->med_prov_cnt++; - - mtotaudcnt = call->opt.aud_cnt; - } - maudcnt = call->opt.aud_cnt; - - /* Check if we need to add new video */ - if (mvidcnt < call->opt.vid_cnt && - mtotvidcnt < call->opt.vid_cnt) - { - for (mi = 0; mi < call->opt.vid_cnt - mtotvidcnt; ++mi) - mvididx[mvidcnt++] = (pj_uint8_t)call->med_prov_cnt++; - - mtotvidcnt = call->opt.vid_cnt; - } - mvidcnt = call->opt.vid_cnt; - - /* In case of media reinit, 'med_prov_cnt' may be decreased - * because the new call->opt says so. As media count should - * never decrease, we should verify 'med_prov_cnt' to be - * at least equal to 'med_cnt' (see also #1987). - */ - if ((call->opt.flag & PJSUA_CALL_REINIT_MEDIA) && - call->med_prov_cnt < call->med_cnt) - { - call->med_prov_cnt = call->med_cnt; - } - - } else { - - maudcnt = mtotaudcnt = call->opt.aud_cnt; - for (mi=0; miopt.vid_cnt; - for (mi=0; mimed_prov_cnt = maudcnt + mvidcnt; - - /* Need to publish supported media? */ - if (call->opt.flag & PJSUA_CALL_INCLUDE_DISABLED_MEDIA) { - if (mtotaudcnt == 0) { - mtotaudcnt = 1; - maudidx[0] = (pj_uint8_t)call->med_prov_cnt++; - } + /* If call is already established, adjust the existing call media list + * to media count setting in call setting, e.g: re-enable/disable/add + * media from existing media. + * Otherwise, apply media count from the call setting directly. + */ + if (reinit) { + pj_bool_t sort_check_tp; + + /* Media sorting below will check transport, i.e: media without + * transport will have lower priority. If PJSUA_CALL_REINIT_MEDIA + * is set, we must not check transport. + */ + sort_check_tp = !(call->opt.flag & PJSUA_CALL_REINIT_MEDIA); + + /* We are sending reoffer, check media count for each media type + * from the existing call media list. + */ + sort_media2(call->media_prov, sort_check_tp, call->med_prov_cnt, + PJMEDIA_TYPE_AUDIO, maudidx, &maudcnt, &mtotaudcnt); + + /* No need to assert if there's no media. */ + //pj_assert(maudcnt > 0); + + sort_media2(call->media_prov, sort_check_tp, call->med_prov_cnt, + PJMEDIA_TYPE_VIDEO, mvididx, &mvidcnt, &mtotvidcnt); + + /* Call setting may add or remove media. Adding media is done by + * enabling any disabled/port-zeroed media first, then adding new + * media whenever needed. Removing media is done by disabling + * media with the lowest 'quality'. + */ + + /* Check if we need to add new audio */ + if (maudcnt < call->opt.aud_cnt && + mtotaudcnt < call->opt.aud_cnt) + { + for (mi = 0; mi < call->opt.aud_cnt - mtotaudcnt; ++mi) + maudidx[maudcnt++] = (pj_uint8_t)call->med_prov_cnt++; + + mtotaudcnt = call->opt.aud_cnt; + } + maudcnt = call->opt.aud_cnt; + + /* Check if we need to add new video */ + if (mvidcnt < call->opt.vid_cnt && + mtotvidcnt < call->opt.vid_cnt) + { + for (mi = 0; mi < call->opt.vid_cnt - mtotvidcnt; ++mi) + mvididx[mvidcnt++] = (pj_uint8_t)call->med_prov_cnt++; + + mtotvidcnt = call->opt.vid_cnt; + } + mvidcnt = call->opt.vid_cnt; + + /* In case of media reinit, 'med_prov_cnt' may be decreased + * because the new call->opt says so. As media count should + * never decrease, we should verify 'med_prov_cnt' to be + * at least equal to 'med_cnt' (see also #1987). + */ + if ((call->opt.flag & PJSUA_CALL_REINIT_MEDIA) && + call->med_prov_cnt < call->med_cnt) + { + call->med_prov_cnt = call->med_cnt; + } + + } else { + + maudcnt = mtotaudcnt = call->opt.aud_cnt; + for (mi=0; miopt.vid_cnt; + for (mi=0; mimed_prov_cnt = maudcnt + mvidcnt; + + /* Need to publish supported media? */ + if (call->opt.flag & PJSUA_CALL_INCLUDE_DISABLED_MEDIA) { + if (mtotaudcnt == 0) { + mtotaudcnt = 1; + maudidx[0] = (pj_uint8_t)call->med_prov_cnt++; + } #if PJMEDIA_HAS_VIDEO - if (mtotvidcnt == 0) { - mtotvidcnt = 1; - mvididx[0] = (pj_uint8_t)call->med_prov_cnt++; - } + if (mtotvidcnt == 0) { + mtotvidcnt = 1; + mvididx[0] = (pj_uint8_t)call->med_prov_cnt++; + } #endif - } - } + } + } - call->rem_offerer = PJ_FALSE; + call->rem_offerer = PJ_FALSE; } if (call->med_prov_cnt == 0) { - /* Expecting at least one media */ - if (sip_err_code) - *sip_err_code = PJSIP_SC_NOT_ACCEPTABLE_HERE; - status = PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_NOT_ACCEPTABLE_HERE); - goto on_error; + /* Expecting at least one media */ + if (sip_err_code) + *sip_err_code = PJSIP_SC_NOT_ACCEPTABLE_HERE; + status = PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_NOT_ACCEPTABLE_HERE); + goto on_error; } if (async) { @@ -2492,49 +2491,49 @@ pj_status_t pjsua_media_channel_init(pjsua_call_id call_id, call->async_call.rem_sdp = pjmedia_sdp_session_clone(call->inv->pool_prov, rem_sdp); } else { - call->async_call.rem_sdp = NULL; + call->async_call.rem_sdp = NULL; } call->async_call.pool_prov = tmp_pool; /* Initialize each media line */ for (mi=0; mi < call->med_prov_cnt; ++mi) { - pjsua_call_media *call_med = &call->media_prov[mi]; - pj_bool_t enabled = PJ_FALSE; - pjmedia_type media_type = PJMEDIA_TYPE_UNKNOWN; - - if (pj_memchr(maudidx, mi, mtotaudcnt * sizeof(maudidx[0]))) { - media_type = PJMEDIA_TYPE_AUDIO; - if (call->opt.aud_cnt && - pj_memchr(maudidx, mi, maudcnt * sizeof(maudidx[0]))) - { - enabled = PJ_TRUE; - } - } else if (pj_memchr(mvididx, mi, mtotvidcnt * sizeof(mvididx[0]))) { - media_type = PJMEDIA_TYPE_VIDEO; - if (call->opt.vid_cnt && - pj_memchr(mvididx, mi, mvidcnt * sizeof(mvididx[0]))) - { - enabled = PJ_TRUE; - } - } - - if (call->opt.flag & PJSUA_CALL_SET_MEDIA_DIR) { - call_med->def_dir = call->opt.media_dir[mi]; - PJ_LOG(4,(THIS_FILE, "Call %d: setting media direction " - "#%d to %d.", call_id, mi, - call_med->def_dir)); - } else if (!reinit) { - /* Initialize default initial media direction as bidirectional */ - call_med->def_dir = PJMEDIA_DIR_ENCODING_DECODING; - } - - if (enabled) { - call_med->enable_rtcp_mux = acc->cfg.enable_rtcp_mux; - - status = pjsua_call_media_init(call_med, media_type, - &acc->cfg.rtp_cfg, - security_level, sip_err_code, + pjsua_call_media *call_med = &call->media_prov[mi]; + pj_bool_t enabled = PJ_FALSE; + pjmedia_type media_type = PJMEDIA_TYPE_UNKNOWN; + + if (pj_memchr(maudidx, mi, mtotaudcnt * sizeof(maudidx[0]))) { + media_type = PJMEDIA_TYPE_AUDIO; + if (call->opt.aud_cnt && + pj_memchr(maudidx, mi, maudcnt * sizeof(maudidx[0]))) + { + enabled = PJ_TRUE; + } + } else if (pj_memchr(mvididx, mi, mtotvidcnt * sizeof(mvididx[0]))) { + media_type = PJMEDIA_TYPE_VIDEO; + if (call->opt.vid_cnt && + pj_memchr(mvididx, mi, mvidcnt * sizeof(mvididx[0]))) + { + enabled = PJ_TRUE; + } + } + + if (call->opt.flag & PJSUA_CALL_SET_MEDIA_DIR) { + call_med->def_dir = call->opt.media_dir[mi]; + PJ_LOG(4,(THIS_FILE, "Call %d: setting media direction " + "#%d to %d.", call_id, mi, + call_med->def_dir)); + } else if (!reinit) { + /* Initialize default initial media direction as bidirectional */ + call_med->def_dir = PJMEDIA_DIR_ENCODING_DECODING; + } + + if (enabled) { + call_med->enable_rtcp_mux = acc->cfg.enable_rtcp_mux; + + status = pjsua_call_media_init(call_med, media_type, + &acc->cfg.rtp_cfg, + security_level, sip_err_code, async, (async? &media_channel_init_cb: NULL)); @@ -2555,55 +2554,55 @@ pj_status_t pjsua_media_channel_init(pjsua_call_id call_id, return PJ_EPENDING; } - /* Revert back provisional media. */ - pjsua_media_prov_revert(call_id); - - goto on_error; - } - - /* Find and save "a=mid". Currently this is for trickle ICE. - * Trickle ICE match media in SDP of SIP INFO by comparing this - * attribute, so remote SDP must be received first before remote - * SDP in SIP INFO can be processed. - */ - if (rem_sdp && call_med->rem_mid.slen == 0) { - const pjmedia_sdp_media *m = rem_sdp->media[mi]; - pjmedia_sdp_attr *a; - - a = pjmedia_sdp_media_find_attr2(m, "mid", NULL); - if (a) - call_med->rem_mid = a->value; - } - - } else { - /* By convention, the media is disabled if transport is NULL - * or transport state is PJSUA_MED_TP_DISABLED. - */ - if (call_med->tp) { - // Don't close transport here, as SDP negotiation has not been - // done and stream may be still active. Once SDP negotiation - // is done (channel_update() invoked), this transport will be - // closed there. - //pjmedia_transport_close(call_med->tp); - //call_med->tp = NULL; - pj_assert(call_med->tp_st == PJSUA_MED_TP_INIT || - call_med->tp_st == PJSUA_MED_TP_RUNNING); - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_DISABLED); - } - - /* Put media type just for info if not yet defined */ - if (call_med->type == PJMEDIA_TYPE_NONE) - call_med->type = media_type; - } + /* Revert back provisional media. */ + pjsua_media_prov_revert(call_id); + + goto on_error; + } + + /* Find and save "a=mid". Currently this is for trickle ICE. + * Trickle ICE match media in SDP of SIP INFO by comparing this + * attribute, so remote SDP must be received first before remote + * SDP in SIP INFO can be processed. + */ + if (rem_sdp && call_med->rem_mid.slen == 0) { + const pjmedia_sdp_media *m = rem_sdp->media[mi]; + pjmedia_sdp_attr *a; + + a = pjmedia_sdp_media_find_attr2(m, "mid", NULL); + if (a) + call_med->rem_mid = a->value; + } + + } else { + /* By convention, the media is disabled if transport is NULL + * or transport state is PJSUA_MED_TP_DISABLED. + */ + if (call_med->tp) { + // Don't close transport here, as SDP negotiation has not been + // done and stream may be still active. Once SDP negotiation + // is done (channel_update() invoked), this transport will be + // closed there. + //pjmedia_transport_close(call_med->tp); + //call_med->tp = NULL; + pj_assert(call_med->tp_st == PJSUA_MED_TP_INIT || + call_med->tp_st == PJSUA_MED_TP_RUNNING); + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_DISABLED); + } + + /* Put media type just for info if not yet defined */ + if (call_med->type == PJMEDIA_TYPE_NONE) + call_med->type = media_type; + } } if (maudcnt > 0) { - call->audio_idx = maudidx[0]; + call->audio_idx = maudidx[0]; - PJ_LOG(4,(THIS_FILE, "Media index %d selected for audio call %d", - call->audio_idx, call->index)); + PJ_LOG(4,(THIS_FILE, "Media index %d selected for audio call %d", + call->audio_idx, call->index)); } else { - call->audio_idx = -1; + call->audio_idx = -1; } if (pending_med_tp) { @@ -2621,10 +2620,10 @@ pj_status_t pjsua_media_channel_init(pjsua_call_id call_id, status = media_channel_init_cb(call_id, NULL); if (status != PJ_SUCCESS && sip_err_code) { - if (call->med_ch_info.sip_err_code) - *sip_err_code = call->med_ch_info.sip_err_code; - else - *sip_err_code = PJSIP_ERRNO_TO_SIP_STATUS(status); + if (call->med_ch_info.sip_err_code) + *sip_err_code = call->med_ch_info.sip_err_code; + else + *sip_err_code = PJSIP_ERRNO_TO_SIP_STATUS(status); } pj_log_pop_indent(); @@ -2637,7 +2636,7 @@ pj_status_t pjsua_media_channel_init(pjsua_call_id call_id, } if (sip_err_code && *sip_err_code == 0) - *sip_err_code = PJSIP_ERRNO_TO_SIP_STATUS(status); + *sip_err_code = PJSIP_ERRNO_TO_SIP_STATUS(status); pj_log_pop_indent(); return status; @@ -2650,10 +2649,10 @@ pj_status_t pjsua_media_channel_init(pjsua_call_id call_id, * (using pjsua_media_channel_init()) first before calling this function. */ pj_status_t pjsua_media_channel_create_sdp(pjsua_call_id call_id, - pj_pool_t *pool, - const pjmedia_sdp_session *rem_sdp, - pjmedia_sdp_session **p_sdp, - int *sip_err_code) + pj_pool_t *pool, + const pjmedia_sdp_session *rem_sdp, + pjmedia_sdp_session **p_sdp, + int *sip_err_code) { enum { MAX_MEDIA = PJSUA_MAX_CALL_MEDIA }; pjmedia_sdp_session *sdp; @@ -2666,30 +2665,30 @@ pj_status_t pjsua_media_channel_create_sdp(pjsua_call_id call_id, pj_status_t status; if (pjsua_get_state() != PJSUA_STATE_RUNNING) { - status = PJ_EBUSY; - goto on_error; + status = PJ_EBUSY; + goto on_error; } #if 0 // This function should not really change the media channel. if (rem_sdp) { - /* If this is a re-offer, let's re-initialize media as remote may - * add or remove media - */ - if (call->inv && call->inv->state == PJSIP_INV_STATE_CONFIRMED) { - status = pjsua_media_channel_init(call_id, PJSIP_ROLE_UAS, - call->secure_level, pool, - rem_sdp, sip_err_code, + /* If this is a re-offer, let's re-initialize media as remote may + * add or remove media + */ + if (call->inv && call->inv->state == PJSIP_INV_STATE_CONFIRMED) { + status = pjsua_media_channel_init(call_id, PJSIP_ROLE_UAS, + call->secure_level, pool, + rem_sdp, sip_err_code, PJ_FALSE, NULL); - if (status != PJ_SUCCESS) - return status; - } + if (status != PJ_SUCCESS) + return status; + } } else { - /* Audio is first in our offer, by convention */ - // The audio_idx should not be changed here, as this function may be - // called in generating re-offer and the current active audio index - // can be anywhere. - //call->audio_idx = 0; + /* Audio is first in our offer, by convention */ + // The audio_idx should not be changed here, as this function may be + // called in generating re-offer and the current active audio index + // can be anywhere. + //call->audio_idx = 0; } #endif @@ -2700,326 +2699,326 @@ pj_status_t pjsua_media_channel_create_sdp(pjsua_call_id call_id, * currently on-hold (with the old style hold) */ if (call->media[call->audio_idx].tp == NULL) { - pjsip_role_e role; - role = (rem_sdp ? PJSIP_ROLE_UAS : PJSIP_ROLE_UAC); - status = pjsua_media_channel_init(call_id, role, call->secure_level, - pool, rem_sdp, sip_err_code); - if (status != PJ_SUCCESS) - return status; + pjsip_role_e role; + role = (rem_sdp ? PJSIP_ROLE_UAS : PJSIP_ROLE_UAC); + status = pjsua_media_channel_init(call_id, role, call->secure_level, + pool, rem_sdp, sip_err_code); + if (status != PJ_SUCCESS) + return status; } #endif /* Get SDP negotiator state */ if (call->inv && call->inv->neg) - sdp_neg_state = pjmedia_sdp_neg_get_state(call->inv->neg); + sdp_neg_state = pjmedia_sdp_neg_get_state(call->inv->neg); PJ_UNUSED_ARG(sdp_neg_state); /* Get one address to use in the origin field */ pj_bzero(&origin, sizeof(origin)); for (mi=0; mimed_prov_cnt; ++mi) { - pjmedia_transport_info tpinfo; + pjmedia_transport_info tpinfo; - if (call->media_prov[mi].tp == NULL) - continue; + if (call->media_prov[mi].tp == NULL) + continue; - pjmedia_transport_info_init(&tpinfo); - pjmedia_transport_get_info(call->media_prov[mi].tp, &tpinfo); - pj_sockaddr_cp(&origin, &tpinfo.sock_info.rtp_addr_name); - break; + pjmedia_transport_info_init(&tpinfo); + pjmedia_transport_get_info(call->media_prov[mi].tp, &tpinfo); + pj_sockaddr_cp(&origin, &tpinfo.sock_info.rtp_addr_name); + break; } /* Create the base (blank) SDP */ status = pjmedia_endpt_create_base_sdp(pjsua_var.med_endpt, pool, NULL, &origin, &sdp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Process each media line */ for (mi=0; mimed_prov_cnt; ++mi) { - pjsua_call_media *call_med = &call->media_prov[mi]; - pjmedia_sdp_media *m = NULL; - pjmedia_transport_info tpinfo; - pjmedia_endpt_create_sdp_param param; - unsigned i; - - if (rem_sdp && mi >= rem_sdp->media_count) { - /* Remote might have removed some media lines. */ - /* Note that we must not modify the current active media - * (e.g: stop stream, close/cleanup media transport), as if - * SDP nego fails, the current active media should be maintained. - * Also note that our media count should never decrease, even when - * remote removed some media lines. - */ - break; - } - - if (call_med->tp == NULL || call_med->tp_st == PJSUA_MED_TP_DISABLED) - { - /* - * This media is disabled. Just create a valid SDP with zero - * port. - */ - if (rem_sdp) { - /* Just clone the remote media and deactivate it */ - m = pjmedia_sdp_media_clone_deactivate(pool, - rem_sdp->media[mi]); - } else { - m = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_media); - m->desc.transport = pj_str("RTP/AVP"); - m->desc.fmt_count = 1; - - switch (call_med->type) { - case PJMEDIA_TYPE_AUDIO: - m->desc.media = pj_str("audio"); - m->desc.fmt[0] = pj_str("0"); - break; - case PJMEDIA_TYPE_VIDEO: - m->desc.media = pj_str("video"); - m->desc.fmt[0] = pj_str("31"); - break; - default: - /* This must be us generating re-offer, and some unknown - * media may exist, so just clone from active local SDP - * (and it should have been deactivated already). - */ - pj_assert(call->inv && call->inv->neg && - sdp_neg_state == PJMEDIA_SDP_NEG_STATE_DONE); - { - const pjmedia_sdp_session *s_; - pjmedia_sdp_neg_get_active_local(call->inv->neg, &s_); - - if (mi < s_->media_count) { - m = pjmedia_sdp_media_clone(pool, s_->media[mi]); - m->desc.port = 0; - } else { - /* Remote may have removed some media lines in - * previous negotiations. However, since our - * media count may never decrease (as per - * the RFC), we'll just offer unknown media here. - */ - m->desc.media = pj_str("unknown"); - m->desc.fmt[0] = pj_str("0"); - } - } - break; - } - } - - /* Add connection line, if none */ - if (m->conn == NULL && sdp->conn == NULL) { - pj_bool_t use_ipv6; - pj_bool_t use_nat64; - - use_ipv6 = (pjsua_var.acc[call->acc_id].cfg.ipv6_media_use != - PJSUA_IPV6_DISABLED); - use_nat64 = (pjsua_var.acc[call->acc_id].cfg.nat64_opt != - PJSUA_NAT64_DISABLED); - - m->conn = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_conn); - m->conn->net_type = pj_str("IN"); - if (use_ipv6 && !use_nat64) { - m->conn->addr_type = pj_str("IP6"); - m->conn->addr = pj_str("::1"); - } else { - m->conn->addr_type = pj_str("IP4"); - m->conn->addr = pj_str("127.0.0.1"); - } - } - - sdp->media[sdp->media_count++] = m; - continue; - } - - /* Get transport address info */ - pjmedia_transport_info_init(&tpinfo); - pjmedia_transport_get_info(call_med->tp, &tpinfo); - - /* Ask pjmedia endpoint to create SDP media line */ - pjmedia_endpt_create_sdp_param_default(¶m); - param.dir = call_med->def_dir; - switch (call_med->type) { - case PJMEDIA_TYPE_AUDIO: - status = pjmedia_endpt_create_audio_sdp(pjsua_var.med_endpt, pool, + pjsua_call_media *call_med = &call->media_prov[mi]; + pjmedia_sdp_media *m = NULL; + pjmedia_transport_info tpinfo; + pjmedia_endpt_create_sdp_param param; + unsigned i; + + if (rem_sdp && mi >= rem_sdp->media_count) { + /* Remote might have removed some media lines. */ + /* Note that we must not modify the current active media + * (e.g: stop stream, close/cleanup media transport), as if + * SDP nego fails, the current active media should be maintained. + * Also note that our media count should never decrease, even when + * remote removed some media lines. + */ + break; + } + + if (call_med->tp == NULL || call_med->tp_st == PJSUA_MED_TP_DISABLED) + { + /* + * This media is disabled. Just create a valid SDP with zero + * port. + */ + if (rem_sdp) { + /* Just clone the remote media and deactivate it */ + m = pjmedia_sdp_media_clone_deactivate(pool, + rem_sdp->media[mi]); + } else { + m = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_media); + m->desc.transport = pj_str("RTP/AVP"); + m->desc.fmt_count = 1; + + switch (call_med->type) { + case PJMEDIA_TYPE_AUDIO: + m->desc.media = pj_str("audio"); + m->desc.fmt[0] = pj_str("0"); + break; + case PJMEDIA_TYPE_VIDEO: + m->desc.media = pj_str("video"); + m->desc.fmt[0] = pj_str("31"); + break; + default: + /* This must be us generating re-offer, and some unknown + * media may exist, so just clone from active local SDP + * (and it should have been deactivated already). + */ + pj_assert(call->inv && call->inv->neg && + sdp_neg_state == PJMEDIA_SDP_NEG_STATE_DONE); + { + const pjmedia_sdp_session *s_; + pjmedia_sdp_neg_get_active_local(call->inv->neg, &s_); + + if (mi < s_->media_count) { + m = pjmedia_sdp_media_clone(pool, s_->media[mi]); + m->desc.port = 0; + } else { + /* Remote may have removed some media lines in + * previous negotiations. However, since our + * media count may never decrease (as per + * the RFC), we'll just offer unknown media here. + */ + m->desc.media = pj_str("unknown"); + m->desc.fmt[0] = pj_str("0"); + } + } + break; + } + } + + /* Add connection line, if none */ + if (m->conn == NULL && sdp->conn == NULL) { + pj_bool_t use_ipv6; + pj_bool_t use_nat64; + + use_ipv6 = (pjsua_var.acc[call->acc_id].cfg.ipv6_media_use != + PJSUA_IPV6_DISABLED); + use_nat64 = (pjsua_var.acc[call->acc_id].cfg.nat64_opt != + PJSUA_NAT64_DISABLED); + + m->conn = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_conn); + m->conn->net_type = pj_str("IN"); + if (use_ipv6 && !use_nat64) { + m->conn->addr_type = pj_str("IP6"); + m->conn->addr = pj_str("::1"); + } else { + m->conn->addr_type = pj_str("IP4"); + m->conn->addr = pj_str("127.0.0.1"); + } + } + + sdp->media[sdp->media_count++] = m; + continue; + } + + /* Get transport address info */ + pjmedia_transport_info_init(&tpinfo); + pjmedia_transport_get_info(call_med->tp, &tpinfo); + + /* Ask pjmedia endpoint to create SDP media line */ + pjmedia_endpt_create_sdp_param_default(¶m); + param.dir = call_med->def_dir; + switch (call_med->type) { + case PJMEDIA_TYPE_AUDIO: + status = pjmedia_endpt_create_audio_sdp(pjsua_var.med_endpt, pool, &tpinfo.sock_info, ¶m, &m); - break; + break; #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) - case PJMEDIA_TYPE_VIDEO: - status = pjmedia_endpt_create_video_sdp(pjsua_var.med_endpt, pool, - &tpinfo.sock_info, - ¶m, &m); - break; + case PJMEDIA_TYPE_VIDEO: + status = pjmedia_endpt_create_video_sdp(pjsua_var.med_endpt, pool, + &tpinfo.sock_info, + ¶m, &m); + break; #endif - default: - pj_assert(!"Invalid call_med media type"); - status = PJ_EBUG; - } - - if (status != PJ_SUCCESS) - goto on_error; - - /* Add generated media to SDP session */ - sdp->media[sdp->media_count++] = m; - - /* Disable media if it has zero format/codec */ - if (m->desc.fmt_count == 0) { - m->desc.fmt[m->desc.fmt_count++] = pj_str("0"); - pjmedia_sdp_media_deactivate(pool, m); - PJ_LOG(3,(THIS_FILE, - "Call %d media %d: Disabled due to no active codec", - call_id, mi)); - continue; - } - - /* Add ssrc and cname attribute */ - m->attr[m->attr_count++] = pjmedia_sdp_attr_create_ssrc(pool, - call_med->ssrc, - &call->cname); - - /* Give to transport */ - status = pjmedia_transport_encode_sdp(call_med->tp, pool, - sdp, rem_sdp, mi); - if (status != PJ_SUCCESS) { - if (sip_err_code) *sip_err_code = PJSIP_SC_NOT_ACCEPTABLE; - goto on_error; - } + default: + pj_assert(!"Invalid call_med media type"); + status = PJ_EBUG; + } + + if (status != PJ_SUCCESS) + goto on_error; + + /* Add generated media to SDP session */ + sdp->media[sdp->media_count++] = m; + + /* Disable media if it has zero format/codec */ + if (m->desc.fmt_count == 0) { + m->desc.fmt[m->desc.fmt_count++] = pj_str("0"); + pjmedia_sdp_media_deactivate(pool, m); + PJ_LOG(3,(THIS_FILE, + "Call %d media %d: Disabled due to no active codec", + call_id, mi)); + continue; + } + + /* Add ssrc and cname attribute */ + m->attr[m->attr_count++] = pjmedia_sdp_attr_create_ssrc(pool, + call_med->ssrc, + &call->cname); + + /* Give to transport */ + status = pjmedia_transport_encode_sdp(call_med->tp, pool, + sdp, rem_sdp, mi); + if (status != PJ_SUCCESS) { + if (sip_err_code) *sip_err_code = PJSIP_SC_NOT_ACCEPTABLE; + goto on_error; + } #if PJSUA_SDP_SESS_HAS_CONN - /* Copy c= line of the first media to session level, - * if there's none. - */ - if (sdp->conn == NULL) { - sdp->conn = pjmedia_sdp_conn_clone(pool, m->conn); - } + /* Copy c= line of the first media to session level, + * if there's none. + */ + if (sdp->conn == NULL) { + sdp->conn = pjmedia_sdp_conn_clone(pool, m->conn); + } #endif - - /* Find media bandwidth info */ - for (i = 0; i < m->bandw_count; ++i) { - const pj_str_t STR_BANDW_MODIFIER_TIAS = { "TIAS", 4 }; - if (!pj_stricmp(&m->bandw[i]->modifier, &STR_BANDW_MODIFIER_TIAS)) - { - tot_bandw_tias += m->bandw[i]->value; - break; - } - } - - /* Setup RTCP-FB */ - { - pjmedia_rtcp_fb_setting rtcp_cfg; - pjmedia_rtcp_fb_setting_default(&rtcp_cfg); - - /* Add RTCP-FB PLI if PJSUA_VID_REQ_KEYFRAME_RTCP_PLI is set */ - if (call_med->type == PJMEDIA_TYPE_VIDEO && - (call->opt.req_keyframe_method & - PJSUA_VID_REQ_KEYFRAME_RTCP_PLI)) - { - rtcp_cfg.cap_count = 1; - pj_strset2(&rtcp_cfg.caps[0].codec_id, (char*)"*"); - rtcp_cfg.caps[0].type = PJMEDIA_RTCP_FB_NACK; - pj_strset2(&rtcp_cfg.caps[0].param, (char*)"pli"); - } - - /* Should we put "RTP/AVPF" in SDP?*/ - if (rem_sdp) { - /* For answer, match remote offer */ - unsigned rem_proto = 0; - rem_proto = pjmedia_sdp_transport_get_proto( - &rem_sdp->media[mi]->desc.transport); - rtcp_cfg.dont_use_avpf = - !PJMEDIA_TP_PROTO_HAS_FLAG(rem_proto, - PJMEDIA_TP_PROFILE_RTCP_FB); - } else { - /* For offer, check account setting */ - rtcp_cfg.dont_use_avpf = acc->cfg.rtcp_fb_cfg.dont_use_avpf || - (acc->cfg.rtcp_fb_cfg.cap_count == 0 - && rtcp_cfg.cap_count == 0); - } - - status = pjmedia_rtcp_fb_encode_sdp(pool, pjsua_var.med_endpt, - &rtcp_cfg, sdp, - mi, rem_sdp); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, - "Call %d media %d: Failed to encode RTCP-FB PLI " - "setting to SDP", - call_id, mi)); - } - - /* Add any other RTCP-FB setting configured in account setting */ - if (acc->cfg.rtcp_fb_cfg.cap_count) { - pj_bool_t tmp = rtcp_cfg.dont_use_avpf; - rtcp_cfg = acc->cfg.rtcp_fb_cfg; - rtcp_cfg.dont_use_avpf = tmp; - status = pjmedia_rtcp_fb_encode_sdp(pool, pjsua_var.med_endpt, - &rtcp_cfg, sdp, - mi, rem_sdp); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, - "Call %d media %d: Failed to encode account " - "RTCP-FB setting to SDP", - call_id, mi)); - } - } - } - - /* Find and save "a=mid". Currently this is for trickle ICE. Trickle - * ICE match media in SDP of SIP INFO by comparing this attribute, - * so remote SDP must be received first before remote SDP in SIP INFO - * can be processed. - */ - if (call_med->rem_mid.slen == 0) { - pjmedia_sdp_attr *a; - - a = pjmedia_sdp_media_find_attr2(m, "mid", NULL); - if (a) - call_med->rem_mid = a->value; - } + + /* Find media bandwidth info */ + for (i = 0; i < m->bandw_count; ++i) { + const pj_str_t STR_BANDW_MODIFIER_TIAS = { "TIAS", 4 }; + if (!pj_stricmp(&m->bandw[i]->modifier, &STR_BANDW_MODIFIER_TIAS)) + { + tot_bandw_tias += m->bandw[i]->value; + break; + } + } + + /* Setup RTCP-FB */ + { + pjmedia_rtcp_fb_setting rtcp_cfg; + pjmedia_rtcp_fb_setting_default(&rtcp_cfg); + + /* Add RTCP-FB PLI if PJSUA_VID_REQ_KEYFRAME_RTCP_PLI is set */ + if (call_med->type == PJMEDIA_TYPE_VIDEO && + (call->opt.req_keyframe_method & + PJSUA_VID_REQ_KEYFRAME_RTCP_PLI)) + { + rtcp_cfg.cap_count = 1; + pj_strset2(&rtcp_cfg.caps[0].codec_id, (char*)"*"); + rtcp_cfg.caps[0].type = PJMEDIA_RTCP_FB_NACK; + pj_strset2(&rtcp_cfg.caps[0].param, (char*)"pli"); + } + + /* Should we put "RTP/AVPF" in SDP?*/ + if (rem_sdp) { + /* For answer, match remote offer */ + unsigned rem_proto = 0; + rem_proto = pjmedia_sdp_transport_get_proto( + &rem_sdp->media[mi]->desc.transport); + rtcp_cfg.dont_use_avpf = + !PJMEDIA_TP_PROTO_HAS_FLAG(rem_proto, + PJMEDIA_TP_PROFILE_RTCP_FB); + } else { + /* For offer, check account setting */ + rtcp_cfg.dont_use_avpf = acc->cfg.rtcp_fb_cfg.dont_use_avpf || + (acc->cfg.rtcp_fb_cfg.cap_count == 0 + && rtcp_cfg.cap_count == 0); + } + + status = pjmedia_rtcp_fb_encode_sdp(pool, pjsua_var.med_endpt, + &rtcp_cfg, sdp, + mi, rem_sdp); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(THIS_FILE, status, + "Call %d media %d: Failed to encode RTCP-FB PLI " + "setting to SDP", + call_id, mi)); + } + + /* Add any other RTCP-FB setting configured in account setting */ + if (acc->cfg.rtcp_fb_cfg.cap_count) { + pj_bool_t tmp = rtcp_cfg.dont_use_avpf; + rtcp_cfg = acc->cfg.rtcp_fb_cfg; + rtcp_cfg.dont_use_avpf = tmp; + status = pjmedia_rtcp_fb_encode_sdp(pool, pjsua_var.med_endpt, + &rtcp_cfg, sdp, + mi, rem_sdp); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(THIS_FILE, status, + "Call %d media %d: Failed to encode account " + "RTCP-FB setting to SDP", + call_id, mi)); + } + } + } + + /* Find and save "a=mid". Currently this is for trickle ICE. Trickle + * ICE match media in SDP of SIP INFO by comparing this attribute, + * so remote SDP must be received first before remote SDP in SIP INFO + * can be processed. + */ + if (call_med->rem_mid.slen == 0) { + pjmedia_sdp_attr *a; + + a = pjmedia_sdp_media_find_attr2(m, "mid", NULL); + if (a) + call_med->rem_mid = a->value; + } } /* Add NAT info in the SDP */ if (pjsua_var.ua_cfg.nat_type_in_sdp) { - pjmedia_sdp_attr *a; - pj_str_t value; - char nat_info[80]; - - value.ptr = nat_info; - if (pjsua_var.ua_cfg.nat_type_in_sdp == 1) { - value.slen = pj_ansi_snprintf(nat_info, sizeof(nat_info), - "%d", pjsua_var.nat_type); - } else { - const char *type_name = pj_stun_get_nat_name(pjsua_var.nat_type); - value.slen = pj_ansi_snprintf(nat_info, sizeof(nat_info), - "%d %s", - pjsua_var.nat_type, - type_name); - } - - a = pjmedia_sdp_attr_create(pool, "X-nat", &value); - - pjmedia_sdp_attr_add(&sdp->attr_count, sdp->attr, a); + pjmedia_sdp_attr *a; + pj_str_t value; + char nat_info[80]; + + value.ptr = nat_info; + if (pjsua_var.ua_cfg.nat_type_in_sdp == 1) { + value.slen = pj_ansi_snprintf(nat_info, sizeof(nat_info), + "%d", pjsua_var.nat_type); + } else { + const char *type_name = pj_stun_get_nat_name(pjsua_var.nat_type); + value.slen = pj_ansi_snprintf(nat_info, sizeof(nat_info), + "%d %s", + pjsua_var.nat_type, + type_name); + } + + a = pjmedia_sdp_attr_create(pool, "X-nat", &value); + + pjmedia_sdp_attr_add(&sdp->attr_count, sdp->attr, a); } /* Add bandwidth info in session level using bandwidth modifier "AS". */ if (tot_bandw_tias) { - unsigned bandw; - const pj_str_t STR_BANDW_MODIFIER_AS = { "AS", 2 }; - pjmedia_sdp_bandw *b; - - /* AS bandwidth = RTP bitrate + RTCP bitrate. - * RTP bitrate = payload bitrate (total TIAS) + overheads (~16kbps). - * RTCP bitrate = est. 5% of RTP bitrate. - * Note that AS bandwidth is in kbps. - */ - bandw = tot_bandw_tias + 16000; - bandw += bandw * 5 / 100; - b = PJ_POOL_ALLOC_T(pool, pjmedia_sdp_bandw); - b->modifier = STR_BANDW_MODIFIER_AS; - b->value = bandw / 1000; - sdp->bandw[sdp->bandw_count++] = b; + unsigned bandw; + const pj_str_t STR_BANDW_MODIFIER_AS = { "AS", 2 }; + pjmedia_sdp_bandw *b; + + /* AS bandwidth = RTP bitrate + RTCP bitrate. + * RTP bitrate = payload bitrate (total TIAS) + overheads (~16kbps). + * RTCP bitrate = est. 5% of RTP bitrate. + * Note that AS bandwidth is in kbps. + */ + bandw = tot_bandw_tias + 16000; + bandw += bandw * 5 / 100; + b = PJ_POOL_ALLOC_T(pool, pjmedia_sdp_bandw); + b->modifier = STR_BANDW_MODIFIER_AS; + b->value = bandw / 1000; + sdp->bandw[sdp->bandw_count++] = b; } #if DISABLED_FOR_TICKET_1185 && defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) @@ -3027,51 +3026,51 @@ pj_status_t pjsua_media_channel_create_sdp(pjsua_call_id call_id, * media, i.e: secured and unsecured version, in the SDP offer. */ if (!rem_sdp && - pjsua_var.acc[call->acc_id].cfg.use_srtp == PJMEDIA_SRTP_OPTIONAL && - pjsua_var.acc[call->acc_id].cfg.srtp_optional_dup_offer) + pjsua_var.acc[call->acc_id].cfg.use_srtp == PJMEDIA_SRTP_OPTIONAL && + pjsua_var.acc[call->acc_id].cfg.srtp_optional_dup_offer) { - unsigned i; - - for (i = 0; i < sdp->media_count; ++i) { - pjmedia_sdp_media *m = sdp->media[i]; - - /* Check if this media is unsecured but has SDP "crypto" - * attribute. - */ - if (pj_stricmp2(&m->desc.transport, "RTP/AVP") == 0 && - pjmedia_sdp_media_find_attr2(m, "crypto", NULL) != NULL) - { - if (i == (unsigned)call->audio_idx && - sdp_neg_state == PJMEDIA_SDP_NEG_STATE_DONE) - { - /* This is a session update, and peer has chosen the - * unsecured version, so let's make this unsecured too. - */ - pjmedia_sdp_media_remove_all_attr(m, "crypto"); - } else { - /* This is new offer, duplicate media so we'll have - * secured (with "RTP/SAVP" transport) and and unsecured - * versions. - */ - pjmedia_sdp_media *new_m; - - /* Duplicate this media and apply secured transport */ - new_m = pjmedia_sdp_media_clone(pool, m); - pj_strdup2(pool, &new_m->desc.transport, "RTP/SAVP"); - - /* Remove the "crypto" attribute in the unsecured media */ - pjmedia_sdp_media_remove_all_attr(m, "crypto"); - - /* Insert the new media before the unsecured media */ - if (sdp->media_count < PJMEDIA_MAX_SDP_MEDIA) { - pj_array_insert(sdp->media, sizeof(new_m), - sdp->media_count, i, &new_m); - ++sdp->media_count; - ++i; - } - } - } - } + unsigned i; + + for (i = 0; i < sdp->media_count; ++i) { + pjmedia_sdp_media *m = sdp->media[i]; + + /* Check if this media is unsecured but has SDP "crypto" + * attribute. + */ + if (pj_stricmp2(&m->desc.transport, "RTP/AVP") == 0 && + pjmedia_sdp_media_find_attr2(m, "crypto", NULL) != NULL) + { + if (i == (unsigned)call->audio_idx && + sdp_neg_state == PJMEDIA_SDP_NEG_STATE_DONE) + { + /* This is a session update, and peer has chosen the + * unsecured version, so let's make this unsecured too. + */ + pjmedia_sdp_media_remove_all_attr(m, "crypto"); + } else { + /* This is new offer, duplicate media so we'll have + * secured (with "RTP/SAVP" transport) and and unsecured + * versions. + */ + pjmedia_sdp_media *new_m; + + /* Duplicate this media and apply secured transport */ + new_m = pjmedia_sdp_media_clone(pool, m); + pj_strdup2(pool, &new_m->desc.transport, "RTP/SAVP"); + + /* Remove the "crypto" attribute in the unsecured media */ + pjmedia_sdp_media_remove_all_attr(m, "crypto"); + + /* Insert the new media before the unsecured media */ + if (sdp->media_count < PJMEDIA_MAX_SDP_MEDIA) { + pj_array_insert(sdp->media, sizeof(new_m), + sdp->media_count, i, &new_m); + ++sdp->media_count; + ++i; + } + } + } + } } #endif @@ -3079,8 +3078,8 @@ pj_status_t pjsua_media_channel_create_sdp(pjsua_call_id call_id, /* Notify application */ if (!call->hanging_up && pjsua_var.ua_cfg.cb.on_call_sdp_created) { - (*pjsua_var.ua_cfg.cb.on_call_sdp_created)(call_id, sdp, - pool, rem_sdp); + (*pjsua_var.ua_cfg.cb.on_call_sdp_created)(call_id, sdp, + pool, rem_sdp); } *p_sdp = sdp; @@ -3088,7 +3087,7 @@ pj_status_t pjsua_media_channel_create_sdp(pjsua_call_id call_id, on_error: if (sip_err_code && *sip_err_code == 0) - *sip_err_code = PJSIP_SC_INTERNAL_SERVER_ERROR; + *sip_err_code = PJSIP_SC_INTERNAL_SERVER_ERROR; return status; } @@ -3099,64 +3098,64 @@ static void stop_media_stream(pjsua_call *call, unsigned med_idx) pjsua_call_media *call_med; if (pjsua_call_media_is_changing(call)) { - call_med = &call->media_prov[med_idx]; - if (med_idx >= call->med_prov_cnt) - return; + call_med = &call->media_prov[med_idx]; + if (med_idx >= call->med_prov_cnt) + return; } else { - call_med = &call->media[med_idx]; + call_med = &call->media[med_idx]; if (med_idx >= call->med_cnt) - return; + return; } pj_log_push_indent(); call_med->prev_type = call_med->type; if (call_med->type == PJMEDIA_TYPE_AUDIO) { - pjsua_aud_stop_stream(call_med); + pjsua_aud_stop_stream(call_med); } #if PJMEDIA_HAS_VIDEO else if (call_med->type == PJMEDIA_TYPE_VIDEO) { - pjsua_vid_stop_stream(call_med); + pjsua_vid_stop_stream(call_med); } #endif PJ_LOG(4,(THIS_FILE, "Media stream call%02d:%d is destroyed", - call->index, med_idx)); + call->index, med_idx)); call_med->prev_state = call_med->state; call_med->state = PJSUA_CALL_MEDIA_NONE; /* Try to sync recent changes to provisional media */ if (med_idx < call->med_prov_cnt && - call->media_prov[med_idx].tp == call_med->tp) + call->media_prov[med_idx].tp == call_med->tp) { - pjsua_call_media *prov_med = &call->media_prov[med_idx]; - - /* Media state */ - prov_med->prev_state = call_med->prev_state; - prov_med->state = call_med->state; - - /* RTP seq/ts */ - prov_med->rtp_tx_seq_ts_set = call_med->rtp_tx_seq_ts_set; - prov_med->rtp_tx_seq = call_med->rtp_tx_seq; - prov_med->rtp_tx_ts = call_med->rtp_tx_ts; - - /* Saved media type and stream info */ - prov_med->prev_type = call_med->prev_type; - prov_med->prev_aud_si = call_med->prev_aud_si; - prov_med->prev_vid_si = call_med->prev_vid_si; - - /* Stream */ - if (call_med->type == PJMEDIA_TYPE_AUDIO) { - prov_med->strm.a.conf_slot = call_med->strm.a.conf_slot; - prov_med->strm.a.stream = call_med->strm.a.stream; - } + pjsua_call_media *prov_med = &call->media_prov[med_idx]; + + /* Media state */ + prov_med->prev_state = call_med->prev_state; + prov_med->state = call_med->state; + + /* RTP seq/ts */ + prov_med->rtp_tx_seq_ts_set = call_med->rtp_tx_seq_ts_set; + prov_med->rtp_tx_seq = call_med->rtp_tx_seq; + prov_med->rtp_tx_ts = call_med->rtp_tx_ts; + + /* Saved media type and stream info */ + prov_med->prev_type = call_med->prev_type; + prov_med->prev_aud_si = call_med->prev_aud_si; + prov_med->prev_vid_si = call_med->prev_vid_si; + + /* Stream */ + if (call_med->type == PJMEDIA_TYPE_AUDIO) { + prov_med->strm.a.conf_slot = call_med->strm.a.conf_slot; + prov_med->strm.a.stream = call_med->strm.a.stream; + } #if PJMEDIA_HAS_VIDEO - else if (call_med->type == PJMEDIA_TYPE_VIDEO) { - prov_med->strm.v.cap_win_id = call_med->strm.v.cap_win_id; - prov_med->strm.v.rdr_win_id = call_med->strm.v.rdr_win_id; - prov_med->strm.v.stream = call_med->strm.v.stream; - } + else if (call_med->type == PJMEDIA_TYPE_VIDEO) { + prov_med->strm.v.cap_win_id = call_med->strm.v.cap_win_id; + prov_med->strm.v.rdr_win_id = call_med->strm.v.rdr_win_id; + prov_med->strm.v.stream = call_med->strm.v.stream; + } #endif } @@ -3169,7 +3168,7 @@ static void stop_media_session(pjsua_call_id call_id) unsigned mi; for (mi=0; mimed_cnt; ++mi) { - stop_media_stream(call, mi); + stop_media_stream(call, mi); } } @@ -3195,7 +3194,7 @@ static void log_call_dump(int call_id) status = pjsua_call_dump(call_id, PJ_TRUE, buf, BUF_LEN, " "); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; call_dump_len = (unsigned)pj_ansi_strlen(buf); @@ -3207,22 +3206,22 @@ static void log_call_dump(int call_id) part_idx = 0; part_len = PJ_LOG_MAX_SIZE-80; while (part_idx < call_dump_len) { - char p_orig, *p; - - p = buf + part_idx; - if (part_idx + part_len > call_dump_len) - part_len = call_dump_len - part_idx; - p_orig = p[part_len]; - p[part_len] = '\0'; - PJ_LOG(3,(THIS_FILE, "%s", p)); - p[part_len] = p_orig; - part_idx += part_len; + char p_orig, *p; + + p = buf + part_idx; + if (part_idx + part_len > call_dump_len) + part_len = call_dump_len - part_idx; + p_orig = p[part_len]; + p[part_len] = '\0'; + PJ_LOG(3,(THIS_FILE, "%s", p)); + p[part_len] = p_orig; + part_idx += part_len; } pj_log_set_decor(log_decor); on_return: if (pool) - pj_pool_release(pool); + pj_pool_release(pool); } @@ -3233,7 +3232,7 @@ pj_status_t pjsua_media_channel_deinit(pjsua_call_id call_id) unsigned mi; for (mi=0; mimed_cnt; ++mi) { - pjsua_call_media *call_med = &call->media[mi]; + pjsua_call_media *call_med = &call->media[mi]; if (call_med->tp_st == PJSUA_MED_TP_CREATING) { /* We will do the deinitialization after media transport @@ -3250,14 +3249,14 @@ pj_status_t pjsua_media_channel_deinit(pjsua_call_id call_id) /* Print call dump first */ dlg = (call->inv? call->inv->dlg : call->async_call.dlg); if (dlg && pj_log_get_level() >= 3) - log_call_dump(call_id); + log_call_dump(call_id); stop_media_session(call_id); /* Stop trickle ICE timer */ if (call->trickle_ice.trickling > PJSUA_OP_STATE_NULL) { - call->trickle_ice.trickling = PJSUA_OP_STATE_NULL; - pjsua_cancel_timer(&call->trickle_ice.timer); + call->trickle_ice.trickling = PJSUA_OP_STATE_NULL; + pjsua_cancel_timer(&call->trickle_ice.timer); } call->trickle_ice.enabled = PJ_FALSE; call->trickle_ice.pending_info = PJ_FALSE; @@ -3268,7 +3267,7 @@ pj_status_t pjsua_media_channel_deinit(pjsua_call_id call_id) pjsua_media_prov_clean_up(call_id); call->med_prov_cnt = 0; for (mi=0; mimed_cnt; ++mi) { - pjsua_call_media *call_med = &call->media[mi]; + pjsua_call_media *call_med = &call->media[mi]; if (call_med->use_upnp) { #if defined(PJNATH_HAS_UPNP) && (PJNATH_HAS_UPNP != 0) @@ -3278,49 +3277,49 @@ pj_status_t pjsua_media_channel_deinit(pjsua_call_id call_id) } if (call_med->tp_st > PJSUA_MED_TP_IDLE) { - pjmedia_transport_info tpinfo; - pjmedia_srtp_info *srtp_info; - pjmedia_ice_transport_info *ice_info; - - pjmedia_transport_info_init(&tpinfo); - pjmedia_transport_get_info(call_med->tp, &tpinfo); - srtp_info = (pjmedia_srtp_info *) - pjmedia_transport_info_get_spc_info( - &tpinfo, PJMEDIA_TRANSPORT_TYPE_SRTP); - ice_info = (pjmedia_ice_transport_info *) - pjmedia_transport_info_get_spc_info( - &tpinfo, PJMEDIA_TRANSPORT_TYPE_ICE); - - call_med->prev_srtp_use = (srtp_info && srtp_info->active)? - PJ_TRUE: PJ_FALSE; - if (call_med->prev_srtp_use) - call_med->prev_srtp_info = *srtp_info; - call_med->prev_ice_use = (ice_info && ice_info->active)? - PJ_TRUE: PJ_FALSE; - if (call_med->prev_ice_use) - call_med->prev_ice_info = *ice_info; - - /* Try to sync recent changes to provisional media */ - if (mi < call->med_prov_cnt && - call->media_prov[mi].tp == call_med->tp) - { - pjsua_call_media *prov_med = &call->media_prov[mi]; - - prov_med->prev_ice_use = call_med->prev_ice_use; - prov_med->prev_ice_info = call_med->prev_ice_info; - prov_med->prev_srtp_use = call_med->prev_srtp_use; - prov_med->prev_srtp_info = call_med->prev_srtp_info; - } - - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_IDLE); - pjmedia_transport_media_stop(call_med->tp); - } - - if (call_med->tp) { - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); - pjmedia_transport_close(call_med->tp); - call_med->tp = call_med->tp_orig = NULL; - } + pjmedia_transport_info tpinfo; + pjmedia_srtp_info *srtp_info; + pjmedia_ice_transport_info *ice_info; + + pjmedia_transport_info_init(&tpinfo); + pjmedia_transport_get_info(call_med->tp, &tpinfo); + srtp_info = (pjmedia_srtp_info *) + pjmedia_transport_info_get_spc_info( + &tpinfo, PJMEDIA_TRANSPORT_TYPE_SRTP); + ice_info = (pjmedia_ice_transport_info *) + pjmedia_transport_info_get_spc_info( + &tpinfo, PJMEDIA_TRANSPORT_TYPE_ICE); + + call_med->prev_srtp_use = (srtp_info && srtp_info->active)? + PJ_TRUE: PJ_FALSE; + if (call_med->prev_srtp_use) + call_med->prev_srtp_info = *srtp_info; + call_med->prev_ice_use = (ice_info && ice_info->active)? + PJ_TRUE: PJ_FALSE; + if (call_med->prev_ice_use) + call_med->prev_ice_info = *ice_info; + + /* Try to sync recent changes to provisional media */ + if (mi < call->med_prov_cnt && + call->media_prov[mi].tp == call_med->tp) + { + pjsua_call_media *prov_med = &call->media_prov[mi]; + + prov_med->prev_ice_use = call_med->prev_ice_use; + prov_med->prev_ice_info = call_med->prev_ice_info; + prov_med->prev_srtp_use = call_med->prev_srtp_use; + prov_med->prev_srtp_info = call_med->prev_srtp_info; + } + + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_IDLE); + pjmedia_transport_media_stop(call_med->tp); + } + + if (call_med->tp) { + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); + pjmedia_transport_close(call_med->tp); + call_med->tp = call_med->tp_orig = NULL; + } call_med->tp_orig = NULL; call_med->rem_srtp_use = PJMEDIA_SRTP_UNKNOWN; } @@ -3333,18 +3332,18 @@ pj_status_t pjsua_media_channel_deinit(pjsua_call_id call_id) /* Match codec fmtp. This will compare the values and the order. */ static pj_bool_t match_codec_fmtp(const pjmedia_codec_fmtp *fmtp1, - const pjmedia_codec_fmtp *fmtp2) + const pjmedia_codec_fmtp *fmtp2) { unsigned i; if (fmtp1->cnt != fmtp2->cnt) - return PJ_FALSE; + return PJ_FALSE; for (i = 0; i < fmtp1->cnt; ++i) { - if (pj_stricmp(&fmtp1->param[i].name, &fmtp2->param[i].name)) - return PJ_FALSE; - if (pj_stricmp(&fmtp1->param[i].val, &fmtp2->param[i].val)) - return PJ_FALSE; + if (pj_stricmp(&fmtp1->param[i].name, &fmtp2->param[i].name)) + return PJ_FALSE; + if (pj_stricmp(&fmtp1->param[i].val, &fmtp2->param[i].val)) + return PJ_FALSE; } return PJ_TRUE; @@ -3360,8 +3359,8 @@ static pj_bool_t is_ice_running(pjmedia_transport *tp) pjmedia_transport_info_init(&tpinfo); pjmedia_transport_get_info(tp, &tpinfo); ice_info = (pjmedia_ice_transport_info*) - pjmedia_transport_info_get_spc_info(&tpinfo, - PJMEDIA_TRANSPORT_TYPE_ICE); + pjmedia_transport_info_get_spc_info(&tpinfo, + PJMEDIA_TRANSPORT_TYPE_ICE); return (ice_info && ice_info->sess_state == PJ_ICE_STRANS_STATE_RUNNING); } @@ -3369,10 +3368,10 @@ static pj_bool_t is_ice_running(pjmedia_transport *tp) #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) static void check_srtp_roc(pjsua_call *call, - unsigned med_idx, - const pjsua_stream_info *new_si_, - const pjmedia_sdp_media *local_sdp, - const pjmedia_sdp_media *remote_sdp) + unsigned med_idx, + const pjsua_stream_info *new_si_, + const pjmedia_sdp_media *local_sdp, + const pjmedia_sdp_media *remote_sdp) { pjsua_call_media *call_med = &call->media[med_idx]; pjmedia_transport_info tpinfo; @@ -3391,17 +3390,17 @@ static void check_srtp_roc(pjsua_call *call, pjmedia_transport_info_init(&tpinfo); pjmedia_transport_get_info(call_med->tp, &tpinfo); srtp_info = (pjmedia_srtp_info *) pjmedia_transport_info_get_spc_info( - &tpinfo, PJMEDIA_TRANSPORT_TYPE_SRTP); + &tpinfo, PJMEDIA_TRANSPORT_TYPE_SRTP); srtp = pjmedia_transport_info_get_transport(&tpinfo, - PJMEDIA_TRANSPORT_TYPE_SRTP); + PJMEDIA_TRANSPORT_TYPE_SRTP); /* Just return if there is no SRTP transport in the transport stack. */ if (!srtp_info || !srtp) - return; + return; ice_info = (pjmedia_ice_transport_info*) - pjmedia_transport_info_get_spc_info(&tpinfo, - PJMEDIA_TRANSPORT_TYPE_ICE); + pjmedia_transport_info_get_spc_info(&tpinfo, + PJMEDIA_TRANSPORT_TYPE_ICE); /* RFC 3711 section 3.3.1: * After a re-keying occurs (changing to a new master key), the rollover @@ -3419,72 +3418,72 @@ static void check_srtp_roc(pjsua_call *call, * create a new crypto context with the ROC set to zero). */ if (call->opt.flag & PJSUA_CALL_REINIT_MEDIA) { - if (!call_med->prev_srtp_use) return; - - /* The stream has been deinitialized by now, so we need to retrieve - * the previous stream info from the stored data. - */ + if (!call_med->prev_srtp_use) return; + + /* The stream has been deinitialized by now, so we need to retrieve + * the previous stream info from the stored data. + */ if (call_med->prev_type == PJMEDIA_TYPE_AUDIO) prev_aud_si = &call_med->prev_aud_si; #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) - else if (call_med->prev_type == PJMEDIA_TYPE_VIDEO) - prev_vid_si = &call_med->prev_vid_si; + else if (call_med->prev_type == PJMEDIA_TYPE_VIDEO) + prev_vid_si = &call_med->prev_vid_si; #endif } else { - call_med->prev_srtp_use = PJ_TRUE; - call_med->prev_srtp_info = *srtp_info; - call_med->prev_ice_use = (ice_info && ice_info->active)? - PJ_TRUE: PJ_FALSE; - if (call_med->prev_ice_use) - call_med->prev_ice_info = *ice_info; - - if (call_med->type == PJMEDIA_TYPE_AUDIO) { - /* Get current active audio stream info */ - if (call_med->strm.a.stream) { - pjmedia_stream_get_info(call_med->strm.a.stream, &aud_si); - prev_aud_si = &aud_si; - } - } + call_med->prev_srtp_use = PJ_TRUE; + call_med->prev_srtp_info = *srtp_info; + call_med->prev_ice_use = (ice_info && ice_info->active)? + PJ_TRUE: PJ_FALSE; + if (call_med->prev_ice_use) + call_med->prev_ice_info = *ice_info; + + if (call_med->type == PJMEDIA_TYPE_AUDIO) { + /* Get current active audio stream info */ + if (call_med->strm.a.stream) { + pjmedia_stream_get_info(call_med->strm.a.stream, &aud_si); + prev_aud_si = &aud_si; + } + } #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) - else if (call_med->type == PJMEDIA_TYPE_VIDEO) { - /* Get current active video stream info */ - if (call_med->strm.v.stream) { - pjmedia_vid_stream_get_info(call_med->strm.v.stream, &vid_si); - prev_vid_si = &vid_si; - } - } + else if (call_med->type == PJMEDIA_TYPE_VIDEO) { + /* Get current active video stream info */ + if (call_med->strm.v.stream) { + pjmedia_vid_stream_get_info(call_med->strm.v.stream, &vid_si); + prev_vid_si = &vid_si; + } + } #endif } #if 0 PJ_LOG(4, (THIS_FILE, "SRTP TX ROC %d %d", - call_med->prev_srtp_info.tx_roc.ssrc, - call_med->prev_srtp_info.tx_roc.roc)); + call_med->prev_srtp_info.tx_roc.ssrc, + call_med->prev_srtp_info.tx_roc.roc)); PJ_LOG(4, (THIS_FILE, "SRTP RX ROC %d %d", - call_med->prev_srtp_info.rx_roc.ssrc, - call_med->prev_srtp_info.rx_roc.roc)); + call_med->prev_srtp_info.rx_roc.ssrc, + call_med->prev_srtp_info.rx_roc.roc)); #endif if (prev_aud_si) { - const pjmedia_stream_info *new_si = &new_si_->info.aud; - - /* Local IP address changes */ - if (pj_sockaddr_cmp(&prev_aud_si->local_addr, &new_si->local_addr)) - local_change = PJ_TRUE; - /* Remote IP address changes */ - if (pj_sockaddr_cmp(&prev_aud_si->rem_addr, &new_si->rem_addr)) - rem_change = PJ_TRUE; + const pjmedia_stream_info *new_si = &new_si_->info.aud; + + /* Local IP address changes */ + if (pj_sockaddr_cmp(&prev_aud_si->local_addr, &new_si->local_addr)) + local_change = PJ_TRUE; + /* Remote IP address changes */ + if (pj_sockaddr_cmp(&prev_aud_si->rem_addr, &new_si->rem_addr)) + rem_change = PJ_TRUE; } #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) if (prev_vid_si) { - const pjmedia_vid_stream_info *new_si = &new_si_->info.vid; - - /* Local IP address changes */ - if (pj_sockaddr_cmp(&prev_vid_si->local_addr, &new_si->local_addr)) - local_change = PJ_TRUE; - /* Remote IP address changes */ - if (pj_sockaddr_cmp(&prev_vid_si->rem_addr, &new_si->rem_addr)) - rem_change = PJ_TRUE; + const pjmedia_vid_stream_info *new_si = &new_si_->info.vid; + + /* Local IP address changes */ + if (pj_sockaddr_cmp(&prev_vid_si->local_addr, &new_si->local_addr)) + local_change = PJ_TRUE; + /* Remote IP address changes */ + if (pj_sockaddr_cmp(&prev_vid_si->rem_addr, &new_si->rem_addr)) + rem_change = PJ_TRUE; } #endif @@ -3494,65 +3493,65 @@ static void check_srtp_roc(pjsua_call *call, * (i.e. if ufrag changes). */ if (ice_info && call_med->prev_ice_use) { - const pj_str_t STR_ICE_UFRAG = { "ice-ufrag", 9 }; - pjmedia_sdp_attr *attr; - - if (local_change) { - attr = pjmedia_sdp_attr_find(local_sdp->attr_count, - local_sdp->attr, &STR_ICE_UFRAG, - NULL); - if (!pj_strcmp(&call_med->prev_ice_info.loc_ufrag, - &attr->value)) - { - PJ_LOG(4, (THIS_FILE, "ICE unchanged, SRTP TX ROC " - "maintained")); - local_change = PJ_FALSE; - } - } - - if (rem_change) { - attr = pjmedia_sdp_attr_find(remote_sdp->attr_count, - remote_sdp->attr, &STR_ICE_UFRAG, - NULL); - if (!pj_strcmp(&call_med->prev_ice_info.rem_ufrag, - &attr->value)) - { - PJ_LOG(4, (THIS_FILE, "ICE unchanged, SRTP RX ROC " - "maintained")); - rem_change = PJ_FALSE; - } - } + const pj_str_t STR_ICE_UFRAG = { "ice-ufrag", 9 }; + pjmedia_sdp_attr *attr; + + if (local_change) { + attr = pjmedia_sdp_attr_find(local_sdp->attr_count, + local_sdp->attr, &STR_ICE_UFRAG, + NULL); + if (!pj_strcmp(&call_med->prev_ice_info.loc_ufrag, + &attr->value)) + { + PJ_LOG(4, (THIS_FILE, "ICE unchanged, SRTP TX ROC " + "maintained")); + local_change = PJ_FALSE; + } + } + + if (rem_change) { + attr = pjmedia_sdp_attr_find(remote_sdp->attr_count, + remote_sdp->attr, &STR_ICE_UFRAG, + NULL); + if (!pj_strcmp(&call_med->prev_ice_info.rem_ufrag, + &attr->value)) + { + PJ_LOG(4, (THIS_FILE, "ICE unchanged, SRTP RX ROC " + "maintained")); + rem_change = PJ_FALSE; + } + } } pjmedia_transport_srtp_get_setting(srtp, &setting); setting.tx_roc = call_med->prev_srtp_info.tx_roc; setting.rx_roc = call_med->prev_srtp_info.rx_roc; if (local_change) { - PJ_LOG(4, (THIS_FILE, "Local address change detected, " - "resetting SRTP TX ROC")); - setting.tx_roc.roc = 0; - /* Depending on the interpretation of the RFC, remote - * may or may not reset its ROC as well. So we anticipate both. - */ - setting.prev_rx_roc = call_med->prev_srtp_info.rx_roc; - setting.prev_rx_roc.roc = 0; + PJ_LOG(4, (THIS_FILE, "Local address change detected, " + "resetting SRTP TX ROC")); + setting.tx_roc.roc = 0; + /* Depending on the interpretation of the RFC, remote + * may or may not reset its ROC as well. So we anticipate both. + */ + setting.prev_rx_roc = call_med->prev_srtp_info.rx_roc; + setting.prev_rx_roc.roc = 0; } if (rem_change) { - PJ_LOG(4, (THIS_FILE, "Remote address change detected, " - "resetting SRTP RX ROC")); - setting.rx_roc.roc = 0; - /* There is a possibility that remote's IP address in the SDP - * changes, but its actual IP address actually doesn't change, - * such as when using ICE. So the only thing we can do here - * is to anticipate if remote doesn't reset the ROC. - */ - setting.prev_rx_roc = call_med->prev_srtp_info.rx_roc; + PJ_LOG(4, (THIS_FILE, "Remote address change detected, " + "resetting SRTP RX ROC")); + setting.rx_roc.roc = 0; + /* There is a possibility that remote's IP address in the SDP + * changes, but its actual IP address actually doesn't change, + * such as when using ICE. So the only thing we can do here + * is to anticipate if remote doesn't reset the ROC. + */ + setting.prev_rx_roc = call_med->prev_srtp_info.rx_roc; #if PJSUA_RESET_SRTP_ROC_ON_REM_ADDRESS_CHANGE - if (!local_change) { - PJ_LOG(4, (THIS_FILE, "Remote address change detected, " - "resetting SRTP TX ROC")); - setting.tx_roc.roc = 0; - } + if (!local_change) { + PJ_LOG(4, (THIS_FILE, "Remote address change detected, " + "resetting SRTP TX ROC")); + setting.tx_roc.roc = 0; + } #endif } pjmedia_transport_srtp_modify_setting(srtp, &setting); @@ -3560,145 +3559,145 @@ static void check_srtp_roc(pjsua_call *call, #endif static pj_bool_t is_media_changed(const pjsua_call *call, - unsigned med_idx, - const pjsua_stream_info *new_si_) + unsigned med_idx, + const pjsua_stream_info *new_si_) { const pjsua_call_media *call_med = &call->media[med_idx]; /* Check for newly added media */ if (med_idx >= call->med_cnt) - return PJ_TRUE; + return PJ_TRUE; /* Compare media type */ if (call_med->type != new_si_->type) - return PJ_TRUE; + return PJ_TRUE; /* Audio update checks */ if (call_med->type == PJMEDIA_TYPE_AUDIO) { - pjmedia_stream_info the_old_si; - const pjmedia_stream_info *old_si = NULL; - const pjmedia_stream_info *new_si = &new_si_->info.aud; - const pjmedia_codec_info *old_ci = NULL; - const pjmedia_codec_info *new_ci = &new_si->fmt; - const pjmedia_codec_param *old_cp = NULL; - const pjmedia_codec_param *new_cp = new_si->param; - - /* Compare media direction */ - if (call_med->dir != new_si->dir) - return PJ_TRUE; - - /* Get current active stream info */ - if (call_med->strm.a.stream) { - pjmedia_stream_get_info(call_med->strm.a.stream, &the_old_si); - old_si = &the_old_si; - old_ci = &old_si->fmt; - old_cp = old_si->param; - } else { - /* The stream is inactive. */ - return (new_si->dir != PJMEDIA_DIR_NONE); - } - - if (old_si->rtcp_mux != new_si->rtcp_mux) - return PJ_TRUE; - - /* Compare remote RTP address. If ICE is running, change in default - * address can happen after negotiation, this can be handled - * internally by ICE and does not need to cause media restart. - */ - if (!is_ice_running(call_med->tp) && - pj_sockaddr_cmp(&old_si->rem_addr, &new_si->rem_addr)) - { - return PJ_TRUE; - } - - /* Compare codec info */ - if (pj_stricmp(&old_ci->encoding_name, &new_ci->encoding_name) || - old_ci->clock_rate != new_ci->clock_rate || - old_ci->channel_cnt != new_ci->channel_cnt || - old_si->rx_pt != new_si->rx_pt || - old_si->tx_pt != new_si->tx_pt || - old_si->rx_event_pt != new_si->tx_event_pt || - old_si->tx_event_pt != new_si->tx_event_pt) - { - return PJ_TRUE; - } - - /* Compare codec param */ - if (old_cp->setting.frm_per_pkt != new_cp->setting.frm_per_pkt || - old_cp->setting.vad != new_cp->setting.vad || - old_cp->setting.cng != new_cp->setting.cng || - old_cp->setting.plc != new_cp->setting.plc || - old_cp->setting.penh != new_cp->setting.penh || - !match_codec_fmtp(&old_cp->setting.dec_fmtp, - &new_cp->setting.dec_fmtp) || - !match_codec_fmtp(&old_cp->setting.enc_fmtp, - &new_cp->setting.enc_fmtp)) - { - return PJ_TRUE; - } + pjmedia_stream_info the_old_si; + const pjmedia_stream_info *old_si = NULL; + const pjmedia_stream_info *new_si = &new_si_->info.aud; + const pjmedia_codec_info *old_ci = NULL; + const pjmedia_codec_info *new_ci = &new_si->fmt; + const pjmedia_codec_param *old_cp = NULL; + const pjmedia_codec_param *new_cp = new_si->param; + + /* Compare media direction */ + if (call_med->dir != new_si->dir) + return PJ_TRUE; + + /* Get current active stream info */ + if (call_med->strm.a.stream) { + pjmedia_stream_get_info(call_med->strm.a.stream, &the_old_si); + old_si = &the_old_si; + old_ci = &old_si->fmt; + old_cp = old_si->param; + } else { + /* The stream is inactive. */ + return (new_si->dir != PJMEDIA_DIR_NONE); + } + + if (old_si->rtcp_mux != new_si->rtcp_mux) + return PJ_TRUE; + + /* Compare remote RTP address. If ICE is running, change in default + * address can happen after negotiation, this can be handled + * internally by ICE and does not need to cause media restart. + */ + if (!is_ice_running(call_med->tp) && + pj_sockaddr_cmp(&old_si->rem_addr, &new_si->rem_addr)) + { + return PJ_TRUE; + } + + /* Compare codec info */ + if (pj_stricmp(&old_ci->encoding_name, &new_ci->encoding_name) || + old_ci->clock_rate != new_ci->clock_rate || + old_ci->channel_cnt != new_ci->channel_cnt || + old_si->rx_pt != new_si->rx_pt || + old_si->tx_pt != new_si->tx_pt || + old_si->rx_event_pt != new_si->tx_event_pt || + old_si->tx_event_pt != new_si->tx_event_pt) + { + return PJ_TRUE; + } + + /* Compare codec param */ + if (old_cp->setting.frm_per_pkt != new_cp->setting.frm_per_pkt || + old_cp->setting.vad != new_cp->setting.vad || + old_cp->setting.cng != new_cp->setting.cng || + old_cp->setting.plc != new_cp->setting.plc || + old_cp->setting.penh != new_cp->setting.penh || + !match_codec_fmtp(&old_cp->setting.dec_fmtp, + &new_cp->setting.dec_fmtp) || + !match_codec_fmtp(&old_cp->setting.enc_fmtp, + &new_cp->setting.enc_fmtp)) + { + return PJ_TRUE; + } } #if PJMEDIA_HAS_VIDEO else if (call_med->type == PJMEDIA_TYPE_VIDEO) { - pjmedia_vid_stream_info the_old_si; - const pjmedia_vid_stream_info *old_si = NULL; - const pjmedia_vid_stream_info *new_si = &new_si_->info.vid; - const pjmedia_vid_codec_info *old_ci = NULL; - const pjmedia_vid_codec_info *new_ci = &new_si->codec_info; - const pjmedia_vid_codec_param *old_cp = NULL; - const pjmedia_vid_codec_param *new_cp = new_si->codec_param; - - /* Compare media direction */ - if (call_med->dir != new_si->dir) - return PJ_TRUE; - - /* Get current active stream info */ - if (call_med->strm.v.stream) { - pjmedia_vid_stream_get_info(call_med->strm.v.stream, &the_old_si); - old_si = &the_old_si; - old_ci = &old_si->codec_info; - old_cp = old_si->codec_param; - } else { - /* The stream is inactive. */ - return (new_si->dir != PJMEDIA_DIR_NONE); - } - - /* Compare remote RTP address. If ICE is running, change in default - * address can happen after negotiation, this can be handled - * internally by ICE and does not need to cause media restart. - */ - if (old_si->rtcp_mux != new_si->rtcp_mux) - return PJ_TRUE; - if (!is_ice_running(call_med->tp) && - pj_sockaddr_cmp(&old_si->rem_addr, &new_si->rem_addr)) - { - return PJ_TRUE; - } - - /* Compare codec info */ - if (pj_stricmp(&old_ci->encoding_name, &new_ci->encoding_name) || - old_si->rx_pt != new_si->rx_pt || - old_si->tx_pt != new_si->tx_pt) - { - return PJ_TRUE; - } - - /* Compare codec param */ - if (/* old_cp->enc_mtu != new_cp->enc_mtu || */ - pj_memcmp(&old_cp->enc_fmt.det, &new_cp->enc_fmt.det, - sizeof(pjmedia_video_format_detail)) || - !match_codec_fmtp(&old_cp->dec_fmtp, &new_cp->dec_fmtp) || - !match_codec_fmtp(&old_cp->enc_fmtp, &new_cp->enc_fmtp)) - { - return PJ_TRUE; - } + pjmedia_vid_stream_info the_old_si; + const pjmedia_vid_stream_info *old_si = NULL; + const pjmedia_vid_stream_info *new_si = &new_si_->info.vid; + const pjmedia_vid_codec_info *old_ci = NULL; + const pjmedia_vid_codec_info *new_ci = &new_si->codec_info; + const pjmedia_vid_codec_param *old_cp = NULL; + const pjmedia_vid_codec_param *new_cp = new_si->codec_param; + + /* Compare media direction */ + if (call_med->dir != new_si->dir) + return PJ_TRUE; + + /* Get current active stream info */ + if (call_med->strm.v.stream) { + pjmedia_vid_stream_get_info(call_med->strm.v.stream, &the_old_si); + old_si = &the_old_si; + old_ci = &old_si->codec_info; + old_cp = old_si->codec_param; + } else { + /* The stream is inactive. */ + return (new_si->dir != PJMEDIA_DIR_NONE); + } + + /* Compare remote RTP address. If ICE is running, change in default + * address can happen after negotiation, this can be handled + * internally by ICE and does not need to cause media restart. + */ + if (old_si->rtcp_mux != new_si->rtcp_mux) + return PJ_TRUE; + if (!is_ice_running(call_med->tp) && + pj_sockaddr_cmp(&old_si->rem_addr, &new_si->rem_addr)) + { + return PJ_TRUE; + } + + /* Compare codec info */ + if (pj_stricmp(&old_ci->encoding_name, &new_ci->encoding_name) || + old_si->rx_pt != new_si->rx_pt || + old_si->tx_pt != new_si->tx_pt) + { + return PJ_TRUE; + } + + /* Compare codec param */ + if (/* old_cp->enc_mtu != new_cp->enc_mtu || */ + pj_memcmp(&old_cp->enc_fmt.det, &new_cp->enc_fmt.det, + sizeof(pjmedia_video_format_detail)) || + !match_codec_fmtp(&old_cp->dec_fmtp, &new_cp->dec_fmtp) || + !match_codec_fmtp(&old_cp->enc_fmtp, &new_cp->enc_fmtp)) + { + return PJ_TRUE; + } } #endif else { - /* Just return PJ_TRUE for other media type */ - return PJ_TRUE; + /* Just return PJ_TRUE for other media type */ + return PJ_TRUE; } return PJ_FALSE; @@ -3707,8 +3706,8 @@ static pj_bool_t is_media_changed(const pjsua_call *call, #else /* PJSUA_MEDIA_HAS_PJMEDIA || PJSUA_THIRD_PARTY_STREAM_HAS_GET_INFO */ static pj_bool_t is_media_changed(const pjsua_call *call, - unsigned med_idx, - const pjsua_stream_info *new_si_) + unsigned med_idx, + const pjsua_stream_info *new_si_) { PJ_UNUSED_ARG(call); PJ_UNUSED_ARG(med_idx); @@ -3721,8 +3720,8 @@ static pj_bool_t is_media_changed(const pjsua_call *call, pj_status_t pjsua_media_channel_update(pjsua_call_id call_id, - const pjmedia_sdp_session *local_sdp, - const pjmedia_sdp_session *remote_sdp) + const pjmedia_sdp_session *local_sdp, + const pjmedia_sdp_session *remote_sdp) { pjsua_call *call = &pjsua_var.calls[call_id]; pjsua_acc *acc = &pjsua_var.acc[call->acc_id]; @@ -3742,7 +3741,7 @@ pj_status_t pjsua_media_channel_update(pjsua_call_id call_id, pj_bool_t need_renego_sdp = PJ_FALSE; if (pjsua_get_state() != PJSUA_STATE_RUNNING) - return PJ_EBUSY; + return PJ_EBUSY; PJ_LOG(4,(THIS_FILE, "Call %d: updating media..", call_id)); pj_log_push_indent(); @@ -3760,10 +3759,10 @@ pj_status_t pjsua_media_channel_update(pjsua_call_id call_id, /* Sort audio/video based on "quality" */ sort_media(local_sdp, &STR_AUDIO, acc->cfg.use_srtp, - maudidx, &maudcnt, &mtotaudcnt); + maudidx, &maudcnt, &mtotaudcnt); #if PJMEDIA_HAS_VIDEO sort_media(local_sdp, &STR_VIDEO, acc->cfg.use_srtp, - mvididx, &mvidcnt, &mtotvidcnt); + mvididx, &mvidcnt, &mtotvidcnt); #else PJ_UNUSED_ARG(STR_VIDEO); mvidcnt = mtotvidcnt = 0; @@ -3775,642 +3774,642 @@ pj_status_t pjsua_media_channel_update(pjsua_call_id call_id, * codecs) */ if (!pjmedia_sdp_neg_was_answer_remote(call->inv->neg) && - ((maudcnt > call->opt.aud_cnt || mvidcnt > call->opt.vid_cnt) || - (acc->cfg.rtcp_fb_cfg.cap_count))) + ((maudcnt > call->opt.aud_cnt || mvidcnt > call->opt.vid_cnt) || + (acc->cfg.rtcp_fb_cfg.cap_count))) { - pjmedia_sdp_session *local_sdp_renego = NULL; - - local_sdp_renego = pjmedia_sdp_session_clone(tmp_pool, local_sdp); - local_sdp = local_sdp_renego; - need_renego_sdp = PJ_TRUE; - - /* Add RTCP-FB info into local SDP answer */ - if (acc->cfg.rtcp_fb_cfg.cap_count) { - for (mi=0; mi < local_sdp_renego->media_count; ++mi) { - status = pjmedia_rtcp_fb_encode_sdp( - tmp_pool, pjsua_var.med_endpt, - &acc->cfg.rtcp_fb_cfg, - local_sdp_renego, mi, remote_sdp); - if (status != PJ_SUCCESS) { - PJ_PERROR(3,(THIS_FILE, status, - "Call %d media %d: Failed to encode RTCP-FB " - "setting to SDP", - call_id, mi)); - } - } - } - - /* Applying media count limitation. Note that in generating SDP - * answer, no media count limitation applied as we didn't know yet - * which media would pass the SDP negotiation. - */ - if (maudcnt > call->opt.aud_cnt || mvidcnt > call->opt.vid_cnt) - { - maudcnt = PJ_MIN(maudcnt, call->opt.aud_cnt); - mvidcnt = PJ_MIN(mvidcnt, call->opt.vid_cnt); - - for (mi=0; mi < local_sdp_renego->media_count; ++mi) { - pjmedia_sdp_media *m = local_sdp_renego->media[mi]; - - if (m->desc.port == 0 || - pj_memchr(maudidx, mi, maudcnt*sizeof(maudidx[0])) || - pj_memchr(mvididx, mi, mvidcnt*sizeof(mvididx[0]))) - { - continue; - } - - /* Deactivate this excess media */ - pjmedia_sdp_media_deactivate(tmp_pool, m); - } - } + pjmedia_sdp_session *local_sdp_renego = NULL; + + local_sdp_renego = pjmedia_sdp_session_clone(tmp_pool, local_sdp); + local_sdp = local_sdp_renego; + need_renego_sdp = PJ_TRUE; + + /* Add RTCP-FB info into local SDP answer */ + if (acc->cfg.rtcp_fb_cfg.cap_count) { + for (mi=0; mi < local_sdp_renego->media_count; ++mi) { + status = pjmedia_rtcp_fb_encode_sdp( + tmp_pool, pjsua_var.med_endpt, + &acc->cfg.rtcp_fb_cfg, + local_sdp_renego, mi, remote_sdp); + if (status != PJ_SUCCESS) { + PJ_PERROR(3,(THIS_FILE, status, + "Call %d media %d: Failed to encode RTCP-FB " + "setting to SDP", + call_id, mi)); + } + } + } + + /* Applying media count limitation. Note that in generating SDP + * answer, no media count limitation applied as we didn't know yet + * which media would pass the SDP negotiation. + */ + if (maudcnt > call->opt.aud_cnt || mvidcnt > call->opt.vid_cnt) + { + maudcnt = PJ_MIN(maudcnt, call->opt.aud_cnt); + mvidcnt = PJ_MIN(mvidcnt, call->opt.vid_cnt); + + for (mi=0; mi < local_sdp_renego->media_count; ++mi) { + pjmedia_sdp_media *m = local_sdp_renego->media[mi]; + + if (m->desc.port == 0 || + pj_memchr(maudidx, mi, maudcnt*sizeof(maudidx[0])) || + pj_memchr(mvididx, mi, mvidcnt*sizeof(mvididx[0]))) + { + continue; + } + + /* Deactivate this excess media */ + pjmedia_sdp_media_deactivate(tmp_pool, m); + } + } } /* Update call media from provisional media */ call->med_cnt = call->med_prov_cnt; pj_memcpy(call->media, call->media_prov, - sizeof(call->media_prov[0]) * call->med_prov_cnt); + sizeof(call->media_prov[0]) * call->med_prov_cnt); /* Process each media stream */ for (mi=0; mi < call->med_cnt; ++mi) { - const char *STR_SENDRECV = "sendrecv"; - const char *STR_SENDONLY = "sendonly"; - const char *STR_RECVONLY = "recvonly"; - const char *STR_INACTIVE = "inactive"; - pjsua_call_media *call_med = &call->media[mi]; - pj_bool_t media_changed = PJ_FALSE; - - if (mi >= local_sdp->media_count || - mi >= remote_sdp->media_count) - { - /* This may happen when remote removed any SDP media lines in - * its re-offer. - */ - - /* Stop stream */ - stop_media_stream(call, mi); - - /* Close the media transport */ - if (call_med->tp) { - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); - pjmedia_transport_close(call_med->tp); - call_med->tp = call_med->tp_orig = NULL; - } - continue; + const char *STR_SENDRECV = "sendrecv"; + const char *STR_SENDONLY = "sendonly"; + const char *STR_RECVONLY = "recvonly"; + const char *STR_INACTIVE = "inactive"; + pjsua_call_media *call_med = &call->media[mi]; + pj_bool_t media_changed = PJ_FALSE; + + if (mi >= local_sdp->media_count || + mi >= remote_sdp->media_count) + { + /* This may happen when remote removed any SDP media lines in + * its re-offer. + */ + + /* Stop stream */ + stop_media_stream(call, mi); + + /* Close the media transport */ + if (call_med->tp) { + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); + pjmedia_transport_close(call_med->tp); + call_med->tp = call_med->tp_orig = NULL; + } + continue; #if 0 - /* Something is wrong */ - PJ_LOG(1,(THIS_FILE, "Error updating media for call %d: " - "invalid media index %d in SDP", call_id, mi)); - status = PJMEDIA_SDP_EINSDP; - goto on_error; + /* Something is wrong */ + PJ_LOG(1,(THIS_FILE, "Error updating media for call %d: " + "invalid media index %d in SDP", call_id, mi)); + status = PJMEDIA_SDP_EINSDP; + goto on_error; #endif - } - - /* Apply media update action */ - if (call_med->type==PJMEDIA_TYPE_AUDIO) { - pjmedia_stream_info the_si, *si = &the_si; - pjsua_stream_info stream_info; - - status = pjmedia_stream_info_from_sdp( - si, tmp_pool, pjsua_var.med_endpt, - local_sdp, remote_sdp, mi); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "pjmedia_stream_info_from_sdp() failed " - "for call_id %d media %d", - call_id, mi)); - goto on_check_med_status; - } + } + + /* Apply media update action */ + if (call_med->type==PJMEDIA_TYPE_AUDIO) { + pjmedia_stream_info the_si, *si = &the_si; + pjsua_stream_info stream_info; + + status = pjmedia_stream_info_from_sdp( + si, tmp_pool, pjsua_var.med_endpt, + local_sdp, remote_sdp, mi); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "pjmedia_stream_info_from_sdp() failed " + "for call_id %d media %d", + call_id, mi)); + goto on_check_med_status; + } #if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0) - /* Enable/disable RTCP XR based on account setting. */ - si->rtcp_xr_enabled = acc->cfg.enable_rtcp_xr; + /* Enable/disable RTCP XR based on account setting. */ + si->rtcp_xr_enabled = acc->cfg.enable_rtcp_xr; #endif - /* Check if remote wants RTP and RTCP multiplexing, - * but we don't enable it. - */ - if (si->rtcp_mux && !call_med->enable_rtcp_mux) { - si->rtcp_mux = PJ_FALSE; - } + /* Check if remote wants RTP and RTCP multiplexing, + * but we don't enable it. + */ + if (si->rtcp_mux && !call_med->enable_rtcp_mux) { + si->rtcp_mux = PJ_FALSE; + } /* Codec parameter of stream info (si->param) can be NULL if * the stream is rejected or disabled. */ - /* Override ptime, if this option is specified. */ - if (pjsua_var.media_cfg.ptime != 0 && si->param) { - si->param->setting.frm_per_pkt = (pj_uint8_t) - (pjsua_var.media_cfg.ptime / si->param->info.frm_ptime); - if (si->param->setting.frm_per_pkt == 0) - si->param->setting.frm_per_pkt = 1; - } - - /* Disable VAD, if this option is specified. */ - if (pjsua_var.media_cfg.no_vad && si->param) { - si->param->setting.vad = 0; - } - - if (!pjmedia_sdp_neg_was_answer_remote(call->inv->neg) && - si->dir != PJMEDIA_DIR_NONE) - { - pjmedia_dir dir = si->dir; - - if (call->opt.flag & PJSUA_CALL_SET_MEDIA_DIR) { - call_med->def_dir = call->opt.media_dir[mi]; - PJ_LOG(4,(THIS_FILE, "Call %d: setting audio media " - "direction #%d to %d.", - call_id, mi, call_med->def_dir)); - } - - /* If the default direction specifies we do not wish - * encoding/decoding, clear that direction. - */ - if ((call_med->def_dir & PJMEDIA_DIR_ENCODING) == 0) { - dir &= ~PJMEDIA_DIR_ENCODING; - } - if ((call_med->def_dir & PJMEDIA_DIR_DECODING) == 0) { - dir &= ~PJMEDIA_DIR_DECODING; - } - - if (dir != si->dir) { - const char *str_attr = NULL; - pjmedia_sdp_attr *attr; - pjmedia_sdp_media *m; - - if (!need_renego_sdp) { - pjmedia_sdp_session *local_sdp_renego; - local_sdp_renego = - pjmedia_sdp_session_clone(tmp_pool, local_sdp); - local_sdp = local_sdp_renego; - need_renego_sdp = PJ_TRUE; - } - - si->dir = dir; - m = local_sdp->media[mi]; - - /* Remove existing directions attributes */ - pjmedia_sdp_media_remove_all_attr(m, STR_SENDRECV); - pjmedia_sdp_media_remove_all_attr(m, STR_SENDONLY); - pjmedia_sdp_media_remove_all_attr(m, STR_RECVONLY); - - if (si->dir == PJMEDIA_DIR_ENCODING_DECODING) { - str_attr = STR_SENDRECV; - } else if (si->dir == PJMEDIA_DIR_ENCODING) { - str_attr = STR_SENDONLY; - } else if (si->dir == PJMEDIA_DIR_DECODING) { - str_attr = STR_RECVONLY; - } else { - str_attr = STR_INACTIVE; - } - attr = pjmedia_sdp_attr_create(tmp_pool, str_attr, NULL); - pjmedia_sdp_media_add_attr(m, attr); - } - } - - stream_info.type = PJMEDIA_TYPE_AUDIO; - stream_info.info.aud = the_si; + /* Override ptime, if this option is specified. */ + if (pjsua_var.media_cfg.ptime != 0 && si->param) { + si->param->setting.frm_per_pkt = (pj_uint8_t) + (pjsua_var.media_cfg.ptime / si->param->info.frm_ptime); + if (si->param->setting.frm_per_pkt == 0) + si->param->setting.frm_per_pkt = 1; + } + + /* Disable VAD, if this option is specified. */ + if (pjsua_var.media_cfg.no_vad && si->param) { + si->param->setting.vad = 0; + } + + if (!pjmedia_sdp_neg_was_answer_remote(call->inv->neg) && + si->dir != PJMEDIA_DIR_NONE) + { + pjmedia_dir dir = si->dir; + + if (call->opt.flag & PJSUA_CALL_SET_MEDIA_DIR) { + call_med->def_dir = call->opt.media_dir[mi]; + PJ_LOG(4,(THIS_FILE, "Call %d: setting audio media " + "direction #%d to %d.", + call_id, mi, call_med->def_dir)); + } + + /* If the default direction specifies we do not wish + * encoding/decoding, clear that direction. + */ + if ((call_med->def_dir & PJMEDIA_DIR_ENCODING) == 0) { + dir &= ~PJMEDIA_DIR_ENCODING; + } + if ((call_med->def_dir & PJMEDIA_DIR_DECODING) == 0) { + dir &= ~PJMEDIA_DIR_DECODING; + } + + if (dir != si->dir) { + const char *str_attr = NULL; + pjmedia_sdp_attr *attr; + pjmedia_sdp_media *m; + + if (!need_renego_sdp) { + pjmedia_sdp_session *local_sdp_renego; + local_sdp_renego = + pjmedia_sdp_session_clone(tmp_pool, local_sdp); + local_sdp = local_sdp_renego; + need_renego_sdp = PJ_TRUE; + } + + si->dir = dir; + m = local_sdp->media[mi]; + + /* Remove existing directions attributes */ + pjmedia_sdp_media_remove_all_attr(m, STR_SENDRECV); + pjmedia_sdp_media_remove_all_attr(m, STR_SENDONLY); + pjmedia_sdp_media_remove_all_attr(m, STR_RECVONLY); + + if (si->dir == PJMEDIA_DIR_ENCODING_DECODING) { + str_attr = STR_SENDRECV; + } else if (si->dir == PJMEDIA_DIR_ENCODING) { + str_attr = STR_SENDONLY; + } else if (si->dir == PJMEDIA_DIR_DECODING) { + str_attr = STR_RECVONLY; + } else { + str_attr = STR_INACTIVE; + } + attr = pjmedia_sdp_attr_create(tmp_pool, str_attr, NULL); + pjmedia_sdp_media_add_attr(m, attr); + } + } + + stream_info.type = PJMEDIA_TYPE_AUDIO; + stream_info.info.aud = the_si; #if PJSUA_MEDIA_HAS_PJMEDIA || PJSUA_THIRD_PARTY_STREAM_HAS_GET_INFO #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) - /* Check if we need to reset or maintain SRTP ROC */ - check_srtp_roc(call, mi, &stream_info, - local_sdp->media[mi], remote_sdp->media[mi]); + /* Check if we need to reset or maintain SRTP ROC */ + check_srtp_roc(call, mi, &stream_info, + local_sdp->media[mi], remote_sdp->media[mi]); #endif #endif - /* Check if this media is changed */ - if (pjsua_var.media_cfg.no_smart_media_update || - is_media_changed(call, mi, &stream_info)) - { - media_changed = PJ_TRUE; - /* Stop the media */ - stop_media_stream(call, mi); - } else { - PJ_LOG(4,(THIS_FILE, "Call %d: stream #%d (audio) unchanged.", - call_id, mi)); - } - - /* Check if no media is active */ - if (local_sdp->media[mi]->desc.port == 0) { - - /* Update call media state and direction */ - call_med->state = PJSUA_CALL_MEDIA_NONE; - call_med->dir = PJMEDIA_DIR_NONE; - - } else if (call_med->tp) { - pjmedia_transport_info tp_info; - pjmedia_srtp_info *srtp_info; - - /* Call media direction */ - call_med->dir = si->dir; - - /* Call media state */ - if (call->local_hold || - ((call_med->dir & PJMEDIA_DIR_DECODING) == 0 && - (call_med->def_dir & PJMEDIA_DIR_DECODING) == 0)) - { - /* Local hold: Either the user holds the call, or sets - * the media direction that requests the remote party to - * stop sending media (i.e. sendonly or inactive). - */ - call_med->state = PJSUA_CALL_MEDIA_LOCAL_HOLD; - } else if ((call_med->dir & PJMEDIA_DIR_ENCODING) == 0 && - (call_med->def_dir & PJMEDIA_DIR_DECODING) != 0) - { - /* Remote hold: Remote doesn't want us to send media - * (recvonly or inactive) and we don't set media dir that - * locally holds the media. - */ - call_med->state = PJSUA_CALL_MEDIA_REMOTE_HOLD; - } else { - call_med->state = PJSUA_CALL_MEDIA_ACTIVE; - } - - if (call->inv->following_fork) { - unsigned options = (call_med->enable_rtcp_mux? - PJMEDIA_TPMED_RTCP_MUX: 0); - /* Normally media transport will automatically restart - * itself (if needed, based on info from the SDP) in - * pjmedia_transport_media_start(), however in "following - * forked media" case (see #1644), we need to explicitly - * restart it as it cannot detect fork scenario from - * the SDP only. - */ - status = pjmedia_transport_media_stop(call_med->tp); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "pjmedia_transport_media_stop() failed " - "for call_id %d media %d", - call_id, mi)); - goto on_check_med_status; - } - status = pjmedia_transport_media_create(call_med->tp, - tmp_pool, - options, NULL, mi); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "pjmedia_transport_media_create() failed " - "for call_id %d media %d", - call_id, mi)); - goto on_check_med_status; - } - } - - /* Start/restart media transport based on info in SDP */ - status = pjmedia_transport_media_start(call_med->tp, - tmp_pool, local_sdp, - remote_sdp, mi); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "pjmedia_transport_media_start() failed " - "for call_id %d media %d", - call_id, mi)); - goto on_check_med_status; - } - - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_RUNNING); - - /* Get remote SRTP usage policy */ - pjmedia_transport_info_init(&tp_info); - pjmedia_transport_get_info(call_med->tp, &tp_info); - srtp_info = (pjmedia_srtp_info*) - pjmedia_transport_info_get_spc_info( - &tp_info, PJMEDIA_TRANSPORT_TYPE_SRTP); - if (srtp_info) { - call_med->rem_srtp_use = srtp_info->peer_use; - } - - /* Update audio channel */ - if (media_changed) { - status = pjsua_aud_channel_update(call_med, - call->inv->pool, si, - local_sdp, remote_sdp); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "pjsua_aud_channel_update() failed " - "for call_id %d media %d", - call_id, mi)); - goto on_check_med_status; - } - - if (pjmedia_transport_info_get_spc_info( - &tp_info, PJMEDIA_TRANSPORT_TYPE_LOOP)) - { - pjmedia_transport_loop_disable_rx( - call_med->tp, call_med->strm.a.stream, - !acc->cfg.enable_loopback); - } - } - } - - /* Print info. */ - if (status == PJ_SUCCESS) { - char info[80]; - int info_len = 0; - int len; - const char *dir; - - switch (si->dir) { - case PJMEDIA_DIR_NONE: - dir = "inactive"; - break; - case PJMEDIA_DIR_ENCODING: - dir = "sendonly"; - break; - case PJMEDIA_DIR_DECODING: - dir = "recvonly"; - break; - case PJMEDIA_DIR_ENCODING_DECODING: - dir = "sendrecv"; - break; - default: - dir = "unknown"; - break; - } - len = pj_ansi_sprintf( info+info_len, - ", stream #%d: %.*s (%s)", mi, - (int)si->fmt.encoding_name.slen, - si->fmt.encoding_name.ptr, - dir); - if (len > 0) - info_len += len; - PJ_LOG(4,(THIS_FILE,"Audio updated%s", info)); - } - - - if (call->audio_idx==-1 && status==PJ_SUCCESS && - si->dir != PJMEDIA_DIR_NONE) - { - call->audio_idx = mi; - } + /* Check if this media is changed */ + if (pjsua_var.media_cfg.no_smart_media_update || + is_media_changed(call, mi, &stream_info)) + { + media_changed = PJ_TRUE; + /* Stop the media */ + stop_media_stream(call, mi); + } else { + PJ_LOG(4,(THIS_FILE, "Call %d: stream #%d (audio) unchanged.", + call_id, mi)); + } + + /* Check if no media is active */ + if (local_sdp->media[mi]->desc.port == 0) { + + /* Update call media state and direction */ + call_med->state = PJSUA_CALL_MEDIA_NONE; + call_med->dir = PJMEDIA_DIR_NONE; + + } else if (call_med->tp) { + pjmedia_transport_info tp_info; + pjmedia_srtp_info *srtp_info; + + /* Call media direction */ + call_med->dir = si->dir; + + /* Call media state */ + if (call->local_hold || + ((call_med->dir & PJMEDIA_DIR_DECODING) == 0 && + (call_med->def_dir & PJMEDIA_DIR_DECODING) == 0)) + { + /* Local hold: Either the user holds the call, or sets + * the media direction that requests the remote party to + * stop sending media (i.e. sendonly or inactive). + */ + call_med->state = PJSUA_CALL_MEDIA_LOCAL_HOLD; + } else if ((call_med->dir & PJMEDIA_DIR_ENCODING) == 0 && + (call_med->def_dir & PJMEDIA_DIR_DECODING) != 0) + { + /* Remote hold: Remote doesn't want us to send media + * (recvonly or inactive) and we don't set media dir that + * locally holds the media. + */ + call_med->state = PJSUA_CALL_MEDIA_REMOTE_HOLD; + } else { + call_med->state = PJSUA_CALL_MEDIA_ACTIVE; + } + + if (call->inv->following_fork) { + unsigned options = (call_med->enable_rtcp_mux? + PJMEDIA_TPMED_RTCP_MUX: 0); + /* Normally media transport will automatically restart + * itself (if needed, based on info from the SDP) in + * pjmedia_transport_media_start(), however in "following + * forked media" case (see #1644), we need to explicitly + * restart it as it cannot detect fork scenario from + * the SDP only. + */ + status = pjmedia_transport_media_stop(call_med->tp); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "pjmedia_transport_media_stop() failed " + "for call_id %d media %d", + call_id, mi)); + goto on_check_med_status; + } + status = pjmedia_transport_media_create(call_med->tp, + tmp_pool, + options, NULL, mi); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "pjmedia_transport_media_create() failed " + "for call_id %d media %d", + call_id, mi)); + goto on_check_med_status; + } + } + + /* Start/restart media transport based on info in SDP */ + status = pjmedia_transport_media_start(call_med->tp, + tmp_pool, local_sdp, + remote_sdp, mi); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "pjmedia_transport_media_start() failed " + "for call_id %d media %d", + call_id, mi)); + goto on_check_med_status; + } + + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_RUNNING); + + /* Get remote SRTP usage policy */ + pjmedia_transport_info_init(&tp_info); + pjmedia_transport_get_info(call_med->tp, &tp_info); + srtp_info = (pjmedia_srtp_info*) + pjmedia_transport_info_get_spc_info( + &tp_info, PJMEDIA_TRANSPORT_TYPE_SRTP); + if (srtp_info) { + call_med->rem_srtp_use = srtp_info->peer_use; + } + + /* Update audio channel */ + if (media_changed) { + status = pjsua_aud_channel_update(call_med, + call->inv->pool, si, + local_sdp, remote_sdp); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "pjsua_aud_channel_update() failed " + "for call_id %d media %d", + call_id, mi)); + goto on_check_med_status; + } + + if (pjmedia_transport_info_get_spc_info( + &tp_info, PJMEDIA_TRANSPORT_TYPE_LOOP)) + { + pjmedia_transport_loop_disable_rx( + call_med->tp, call_med->strm.a.stream, + !acc->cfg.enable_loopback); + } + } + } + + /* Print info. */ + if (status == PJ_SUCCESS) { + char info[80]; + int info_len = 0; + int len; + const char *dir; + + switch (si->dir) { + case PJMEDIA_DIR_NONE: + dir = "inactive"; + break; + case PJMEDIA_DIR_ENCODING: + dir = "sendonly"; + break; + case PJMEDIA_DIR_DECODING: + dir = "recvonly"; + break; + case PJMEDIA_DIR_ENCODING_DECODING: + dir = "sendrecv"; + break; + default: + dir = "unknown"; + break; + } + len = pj_ansi_sprintf( info+info_len, + ", stream #%d: %.*s (%s)", mi, + (int)si->fmt.encoding_name.slen, + si->fmt.encoding_name.ptr, + dir); + if (len > 0) + info_len += len; + PJ_LOG(4,(THIS_FILE,"Audio updated%s", info)); + } + + + if (call->audio_idx==-1 && status==PJ_SUCCESS && + si->dir != PJMEDIA_DIR_NONE) + { + call->audio_idx = mi; + } #if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0) - } else if (call_med->type==PJMEDIA_TYPE_VIDEO) { - pjmedia_vid_stream_info the_si, *si = &the_si; - pjsua_stream_info stream_info; - - status = pjmedia_vid_stream_info_from_sdp( - si, tmp_pool, pjsua_var.med_endpt, - local_sdp, remote_sdp, mi); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "pjmedia_vid_stream_info_from_sdp() failed " - "for call_id %d media %d", - call_id, mi)); - goto on_check_med_status; - } - - /* Check if remote wants RTP and RTCP multiplexing, - * but we don't enable it. - */ - if (si->rtcp_mux && !call_med->enable_rtcp_mux) { - si->rtcp_mux = PJ_FALSE; - } - - if (!pjmedia_sdp_neg_was_answer_remote(call->inv->neg) && - si->dir != PJMEDIA_DIR_NONE) - { - pjmedia_dir dir = si->dir; - - if (call->opt.flag & PJSUA_CALL_SET_MEDIA_DIR) { - call_med->def_dir = call->opt.media_dir[mi]; - PJ_LOG(4,(THIS_FILE, "Call %d: setting video media " - "direction #%d to %d.", - call_id, mi, call_med->def_dir)); - } - - /* If the default direction specifies we do not wish - * encoding/decoding, clear that direction. - */ - if ((call_med->def_dir & PJMEDIA_DIR_ENCODING) == 0) { - dir &= ~PJMEDIA_DIR_ENCODING; - } - if ((call_med->def_dir & PJMEDIA_DIR_DECODING) == 0) { - dir &= ~PJMEDIA_DIR_DECODING; - } - - if (dir != si->dir) { - const char *str_attr = NULL; - pjmedia_sdp_attr *attr; - pjmedia_sdp_media *m; - - if (!need_renego_sdp) { - pjmedia_sdp_session *local_sdp_renego; - local_sdp_renego = - pjmedia_sdp_session_clone(tmp_pool, local_sdp); - local_sdp = local_sdp_renego; - need_renego_sdp = PJ_TRUE; - } - - si->dir = dir; - m = local_sdp->media[mi]; - - /* Remove existing directions attributes */ - pjmedia_sdp_media_remove_all_attr(m, STR_SENDRECV); - pjmedia_sdp_media_remove_all_attr(m, STR_SENDONLY); - pjmedia_sdp_media_remove_all_attr(m, STR_RECVONLY); - - if (si->dir == PJMEDIA_DIR_ENCODING_DECODING) { - str_attr = STR_SENDRECV; - } else if (si->dir == PJMEDIA_DIR_ENCODING) { - str_attr = STR_SENDONLY; - } else if (si->dir == PJMEDIA_DIR_DECODING) { - str_attr = STR_RECVONLY; - } else { - str_attr = STR_INACTIVE; - } - attr = pjmedia_sdp_attr_create(tmp_pool, str_attr, NULL); - pjmedia_sdp_media_add_attr(m, attr); - } - } - - /* Check if this media is changed */ - stream_info.type = PJMEDIA_TYPE_VIDEO; - stream_info.info.vid = the_si; - if (is_media_changed(call, mi, &stream_info)) { - media_changed = PJ_TRUE; - /* Stop the media */ - stop_media_stream(call, mi); - } else { - PJ_LOG(4,(THIS_FILE, "Call %d: stream #%d (video) unchanged.", - call_id, mi)); - } - - /* Check if no media is active */ - if (local_sdp->media[mi]->desc.port == 0) { - - /* Update call media state and direction */ - call_med->state = PJSUA_CALL_MEDIA_NONE; - call_med->dir = PJMEDIA_DIR_NONE; - - } else if (call_med->tp) { - pjmedia_transport_info tp_info; - pjmedia_srtp_info *srtp_info; - - /* Call media direction */ - call_med->dir = si->dir; - - /* Call media state */ - if (call->local_hold || - ((call_med->dir & PJMEDIA_DIR_DECODING) == 0 && - (call_med->def_dir & PJMEDIA_DIR_DECODING) == 0)) - { - /* Local hold: Either the user holds the call, or sets - * the media direction that requests the remote party to - * stop sending media (i.e. sendonly or inactive). - */ - call_med->state = PJSUA_CALL_MEDIA_LOCAL_HOLD; - } else if ((call_med->dir & PJMEDIA_DIR_ENCODING) == 0 && - (call_med->def_dir & PJMEDIA_DIR_DECODING) != 0) - { - /* Remote hold: Remote doesn't want us to send media - * (recvonly or inactive) and we don't set media dir that - * locally holds the media. - */ - call_med->state = PJSUA_CALL_MEDIA_REMOTE_HOLD; - } else { - call_med->state = PJSUA_CALL_MEDIA_ACTIVE; - } - - /* Start/restart media transport */ - status = pjmedia_transport_media_start(call_med->tp, - tmp_pool, local_sdp, - remote_sdp, mi); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "pjmedia_transport_media_start() failed " - "for call_id %d media %d", - call_id, mi)); - goto on_check_med_status; - } - - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_RUNNING); - - /* Get remote SRTP usage policy */ - pjmedia_transport_info_init(&tp_info); - pjmedia_transport_get_info(call_med->tp, &tp_info); - srtp_info = (pjmedia_srtp_info*) - pjmedia_transport_info_get_spc_info( - &tp_info, PJMEDIA_TRANSPORT_TYPE_SRTP); - if (srtp_info) { - call_med->rem_srtp_use = srtp_info->peer_use; - } - - /* Update video channel */ - if (media_changed) { - status = pjsua_vid_channel_update(call_med, - call->inv->pool, si, - local_sdp, remote_sdp); - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, - "pjsua_vid_channel_update() failed " - "for call_id %d media %d", - call_id, mi)); - goto on_check_med_status; - } - } - } - - /* Print info. */ - { - char info[80]; - int info_len = 0; - int len; - const char *dir; - - switch (si->dir) { - case PJMEDIA_DIR_NONE: - dir = "inactive"; - break; - case PJMEDIA_DIR_ENCODING: - dir = "sendonly"; - break; - case PJMEDIA_DIR_DECODING: - dir = "recvonly"; - break; - case PJMEDIA_DIR_ENCODING_DECODING: - dir = "sendrecv"; - break; - default: - dir = "unknown"; - break; - } - len = pj_ansi_sprintf( info+info_len, - ", stream #%d: %.*s (%s)", mi, - (int)si->codec_info.encoding_name.slen, - si->codec_info.encoding_name.ptr, - dir); - if (len > 0) - info_len += len; - PJ_LOG(4,(THIS_FILE,"Video updated%s", info)); - } + } else if (call_med->type==PJMEDIA_TYPE_VIDEO) { + pjmedia_vid_stream_info the_si, *si = &the_si; + pjsua_stream_info stream_info; + + status = pjmedia_vid_stream_info_from_sdp( + si, tmp_pool, pjsua_var.med_endpt, + local_sdp, remote_sdp, mi); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "pjmedia_vid_stream_info_from_sdp() failed " + "for call_id %d media %d", + call_id, mi)); + goto on_check_med_status; + } + + /* Check if remote wants RTP and RTCP multiplexing, + * but we don't enable it. + */ + if (si->rtcp_mux && !call_med->enable_rtcp_mux) { + si->rtcp_mux = PJ_FALSE; + } + + if (!pjmedia_sdp_neg_was_answer_remote(call->inv->neg) && + si->dir != PJMEDIA_DIR_NONE) + { + pjmedia_dir dir = si->dir; + + if (call->opt.flag & PJSUA_CALL_SET_MEDIA_DIR) { + call_med->def_dir = call->opt.media_dir[mi]; + PJ_LOG(4,(THIS_FILE, "Call %d: setting video media " + "direction #%d to %d.", + call_id, mi, call_med->def_dir)); + } + + /* If the default direction specifies we do not wish + * encoding/decoding, clear that direction. + */ + if ((call_med->def_dir & PJMEDIA_DIR_ENCODING) == 0) { + dir &= ~PJMEDIA_DIR_ENCODING; + } + if ((call_med->def_dir & PJMEDIA_DIR_DECODING) == 0) { + dir &= ~PJMEDIA_DIR_DECODING; + } + + if (dir != si->dir) { + const char *str_attr = NULL; + pjmedia_sdp_attr *attr; + pjmedia_sdp_media *m; + + if (!need_renego_sdp) { + pjmedia_sdp_session *local_sdp_renego; + local_sdp_renego = + pjmedia_sdp_session_clone(tmp_pool, local_sdp); + local_sdp = local_sdp_renego; + need_renego_sdp = PJ_TRUE; + } + + si->dir = dir; + m = local_sdp->media[mi]; + + /* Remove existing directions attributes */ + pjmedia_sdp_media_remove_all_attr(m, STR_SENDRECV); + pjmedia_sdp_media_remove_all_attr(m, STR_SENDONLY); + pjmedia_sdp_media_remove_all_attr(m, STR_RECVONLY); + + if (si->dir == PJMEDIA_DIR_ENCODING_DECODING) { + str_attr = STR_SENDRECV; + } else if (si->dir == PJMEDIA_DIR_ENCODING) { + str_attr = STR_SENDONLY; + } else if (si->dir == PJMEDIA_DIR_DECODING) { + str_attr = STR_RECVONLY; + } else { + str_attr = STR_INACTIVE; + } + attr = pjmedia_sdp_attr_create(tmp_pool, str_attr, NULL); + pjmedia_sdp_media_add_attr(m, attr); + } + } + + /* Check if this media is changed */ + stream_info.type = PJMEDIA_TYPE_VIDEO; + stream_info.info.vid = the_si; + if (is_media_changed(call, mi, &stream_info)) { + media_changed = PJ_TRUE; + /* Stop the media */ + stop_media_stream(call, mi); + } else { + PJ_LOG(4,(THIS_FILE, "Call %d: stream #%d (video) unchanged.", + call_id, mi)); + } + + /* Check if no media is active */ + if (local_sdp->media[mi]->desc.port == 0) { + + /* Update call media state and direction */ + call_med->state = PJSUA_CALL_MEDIA_NONE; + call_med->dir = PJMEDIA_DIR_NONE; + + } else if (call_med->tp) { + pjmedia_transport_info tp_info; + pjmedia_srtp_info *srtp_info; + + /* Call media direction */ + call_med->dir = si->dir; + + /* Call media state */ + if (call->local_hold || + ((call_med->dir & PJMEDIA_DIR_DECODING) == 0 && + (call_med->def_dir & PJMEDIA_DIR_DECODING) == 0)) + { + /* Local hold: Either the user holds the call, or sets + * the media direction that requests the remote party to + * stop sending media (i.e. sendonly or inactive). + */ + call_med->state = PJSUA_CALL_MEDIA_LOCAL_HOLD; + } else if ((call_med->dir & PJMEDIA_DIR_ENCODING) == 0 && + (call_med->def_dir & PJMEDIA_DIR_DECODING) != 0) + { + /* Remote hold: Remote doesn't want us to send media + * (recvonly or inactive) and we don't set media dir that + * locally holds the media. + */ + call_med->state = PJSUA_CALL_MEDIA_REMOTE_HOLD; + } else { + call_med->state = PJSUA_CALL_MEDIA_ACTIVE; + } + + /* Start/restart media transport */ + status = pjmedia_transport_media_start(call_med->tp, + tmp_pool, local_sdp, + remote_sdp, mi); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "pjmedia_transport_media_start() failed " + "for call_id %d media %d", + call_id, mi)); + goto on_check_med_status; + } + + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_RUNNING); + + /* Get remote SRTP usage policy */ + pjmedia_transport_info_init(&tp_info); + pjmedia_transport_get_info(call_med->tp, &tp_info); + srtp_info = (pjmedia_srtp_info*) + pjmedia_transport_info_get_spc_info( + &tp_info, PJMEDIA_TRANSPORT_TYPE_SRTP); + if (srtp_info) { + call_med->rem_srtp_use = srtp_info->peer_use; + } + + /* Update video channel */ + if (media_changed) { + status = pjsua_vid_channel_update(call_med, + call->inv->pool, si, + local_sdp, remote_sdp); + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, + "pjsua_vid_channel_update() failed " + "for call_id %d media %d", + call_id, mi)); + goto on_check_med_status; + } + } + } + + /* Print info. */ + { + char info[80]; + int info_len = 0; + int len; + const char *dir; + + switch (si->dir) { + case PJMEDIA_DIR_NONE: + dir = "inactive"; + break; + case PJMEDIA_DIR_ENCODING: + dir = "sendonly"; + break; + case PJMEDIA_DIR_DECODING: + dir = "recvonly"; + break; + case PJMEDIA_DIR_ENCODING_DECODING: + dir = "sendrecv"; + break; + default: + dir = "unknown"; + break; + } + len = pj_ansi_sprintf( info+info_len, + ", stream #%d: %.*s (%s)", mi, + (int)si->codec_info.encoding_name.slen, + si->codec_info.encoding_name.ptr, + dir); + if (len > 0) + info_len += len; + PJ_LOG(4,(THIS_FILE,"Video updated%s", info)); + } #endif - } else { - status = PJMEDIA_EUNSUPMEDIATYPE; - } - - /* Close the transport of deactivated media, need this here as media - * can be deactivated by the SDP negotiation and the max media count - * (account) setting. - */ - if (local_sdp->media[mi]->desc.port==0 && call_med->tp) { - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); - pjmedia_transport_close(call_med->tp); - call_med->tp = call_med->tp_orig = NULL; - } + } else { + status = PJMEDIA_EUNSUPMEDIATYPE; + } + + /* Close the transport of deactivated media, need this here as media + * can be deactivated by the SDP negotiation and the max media count + * (account) setting. + */ + if (local_sdp->media[mi]->desc.port==0 && call_med->tp) { + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); + pjmedia_transport_close(call_med->tp); + call_med->tp = call_med->tp_orig = NULL; + } on_check_med_status: - if (status != PJ_SUCCESS) { - /* Stop stream */ - stop_media_stream(call, mi); - - /* Close the media transport */ - if (call_med->tp) { - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); - pjmedia_transport_close(call_med->tp); - call_med->tp = call_med->tp_orig = NULL; - } - - /* Update media states */ - call_med->state = PJSUA_CALL_MEDIA_ERROR; - call_med->dir = PJMEDIA_DIR_NONE; - - if (status != PJMEDIA_EUNSUPMEDIATYPE) { - PJ_PERROR(1, (THIS_FILE, status, "Error updating media " - "call%02d:%d", call_id, mi)); - } else { - PJ_PERROR(3, (THIS_FILE, status, "Skipped updating media " - "call%02d:%d (media type=%s)", call_id, mi, - pjmedia_type_name(call_med->type))); - } - - } else { - /* Only set 'got_media' flag if this media is not disabled */ - if (local_sdp->media[mi]->desc.port != 0) - got_media = PJ_TRUE; - } + if (status != PJ_SUCCESS) { + /* Stop stream */ + stop_media_stream(call, mi); + + /* Close the media transport */ + if (call_med->tp) { + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); + pjmedia_transport_close(call_med->tp); + call_med->tp = call_med->tp_orig = NULL; + } + + /* Update media states */ + call_med->state = PJSUA_CALL_MEDIA_ERROR; + call_med->dir = PJMEDIA_DIR_NONE; + + if (status != PJMEDIA_EUNSUPMEDIATYPE) { + PJ_PERROR(1, (THIS_FILE, status, "Error updating media " + "call%02d:%d", call_id, mi)); + } else { + PJ_PERROR(3, (THIS_FILE, status, "Skipped updating media " + "call%02d:%d (media type=%s)", call_id, mi, + pjmedia_type_name(call_med->type))); + } + + } else { + /* Only set 'got_media' flag if this media is not disabled */ + if (local_sdp->media[mi]->desc.port != 0) + got_media = PJ_TRUE; + } } /* Sync provisional media to call media */ call->med_prov_cnt = call->med_cnt; pj_memcpy(call->media_prov, call->media, - sizeof(call->media[0]) * call->med_cnt); + sizeof(call->media[0]) * call->med_cnt); /* Perform SDP re-negotiation. */ if (got_media && need_renego_sdp) { - pjmedia_sdp_neg *neg = call->inv->neg; + pjmedia_sdp_neg *neg = call->inv->neg; - status = pjmedia_sdp_neg_set_remote_offer(tmp_pool, neg, remote_sdp); - if (status != PJ_SUCCESS) - goto on_error; + status = pjmedia_sdp_neg_set_remote_offer(tmp_pool, neg, remote_sdp); + if (status != PJ_SUCCESS) + goto on_error; - status = pjmedia_sdp_neg_set_local_answer(tmp_pool, neg, local_sdp); - if (status != PJ_SUCCESS) - goto on_error; + status = pjmedia_sdp_neg_set_local_answer(tmp_pool, neg, local_sdp); + if (status != PJ_SUCCESS) + goto on_error; - status = pjmedia_sdp_neg_negotiate(tmp_pool, neg, 0); - if (status != PJ_SUCCESS) - goto on_error; + status = pjmedia_sdp_neg_negotiate(tmp_pool, neg, 0); + if (status != PJ_SUCCESS) + goto on_error; } pj_log_pop_indent(); @@ -4429,7 +4428,7 @@ pj_status_t pjsua_media_channel_update(pjsua_call_id call_id, * Enum all supported codecs in the system. */ PJ_DEF(pj_status_t) pjsua_enum_codecs( pjsua_codec_info id[], - unsigned *p_count ) + unsigned *p_count ) { pjmedia_codec_mgr *codec_mgr; pjmedia_codec_info info[32]; @@ -4440,18 +4439,18 @@ PJ_DEF(pj_status_t) pjsua_enum_codecs( pjsua_codec_info id[], count = PJ_ARRAY_SIZE(info); status = pjmedia_codec_mgr_enum_codecs( codec_mgr, &count, info, prio); if (status != PJ_SUCCESS) { - *p_count = 0; - return status; + *p_count = 0; + return status; } if (count > *p_count) count = *p_count; for (i=0; islen==1 && *codec_id->ptr=='*') - codec_id = &all; + codec_id = &all; return pjmedia_codec_mgr_set_codec_priority(codec_mgr, codec_id, - priority); + priority); } @@ -4483,7 +4482,7 @@ PJ_DEF(pj_status_t) pjsua_codec_set_priority( const pj_str_t *codec_id, * Get codec parameters. */ PJ_DEF(pj_status_t) pjsua_codec_get_param( const pj_str_t *codec_id, - pjmedia_codec_param *param ) + pjmedia_codec_param *param ) { const pj_str_t all = { NULL, 0 }; const pjmedia_codec_info *info; @@ -4494,15 +4493,15 @@ PJ_DEF(pj_status_t) pjsua_codec_get_param( const pj_str_t *codec_id, codec_mgr = pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt); if (codec_id->slen==1 && *codec_id->ptr=='*') - codec_id = &all; + codec_id = &all; status = pjmedia_codec_mgr_find_codecs_by_id(codec_mgr, codec_id, - &count, &info, NULL); + &count, &info, NULL); if (status != PJ_SUCCESS) - return status; + return status; if (count != 1) - return (count > 1? PJ_ETOOMANY : PJ_ENOTFOUND); + return (count > 1? PJ_ETOOMANY : PJ_ENOTFOUND); status = pjmedia_codec_mgr_get_default_param( codec_mgr, info, param); return status; @@ -4513,7 +4512,7 @@ PJ_DEF(pj_status_t) pjsua_codec_get_param( const pj_str_t *codec_id, * Set codec parameters. */ PJ_DEF(pj_status_t) pjsua_codec_set_param( const pj_str_t *codec_id, - const pjmedia_codec_param *param) + const pjmedia_codec_param *param) { const pjmedia_codec_info *info[2]; pjmedia_codec_mgr *codec_mgr; @@ -4523,17 +4522,17 @@ PJ_DEF(pj_status_t) pjsua_codec_set_param( const pj_str_t *codec_id, codec_mgr = pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt); status = pjmedia_codec_mgr_find_codecs_by_id(codec_mgr, codec_id, - &count, info, NULL); + &count, info, NULL); if (status != PJ_SUCCESS) - return status; + return status; /* Codec ID should be specific, except for G.722.1 */ if (count > 1 && - pj_strnicmp2(codec_id, "G7221/16", 8) != 0 && - pj_strnicmp2(codec_id, "G7221/32", 8) != 0) + pj_strnicmp2(codec_id, "G7221/16", 8) != 0 && + pj_strnicmp2(codec_id, "G7221/32", 8) != 0) { - pj_assert(!"Codec ID is not specific"); - return PJ_ETOOMANY; + pj_assert(!"Codec ID is not specific"); + return PJ_ETOOMANY; } status = pjmedia_codec_mgr_set_default_param(codec_mgr, info[0], param); @@ -4542,26 +4541,26 @@ PJ_DEF(pj_status_t) pjsua_codec_set_param( const pj_str_t *codec_id, pj_status_t pjsua_media_apply_xml_control(pjsua_call_id call_id, - const pj_str_t *xml_st) + const pj_str_t *xml_st) { #if PJMEDIA_HAS_VIDEO pjsua_call *call = &pjsua_var.calls[call_id]; const pj_str_t PICT_FAST_UPDATE = {"picture_fast_update", 19}; if (pj_strstr(xml_st, &PICT_FAST_UPDATE)) { - unsigned i; + unsigned i; - PJ_LOG(4,(THIS_FILE, "Received keyframe request via SIP INFO")); + PJ_LOG(4,(THIS_FILE, "Received keyframe request via SIP INFO")); - for (i = 0; i < call->med_cnt; ++i) { - pjsua_call_media *cm = &call->media[i]; - if (cm->type != PJMEDIA_TYPE_VIDEO || !cm->strm.v.stream) - continue; + for (i = 0; i < call->med_cnt; ++i) { + pjsua_call_media *cm = &call->media[i]; + if (cm->type != PJMEDIA_TYPE_VIDEO || !cm->strm.v.stream) + continue; - pjmedia_vid_stream_send_keyframe(cm->strm.v.stream); - } + pjmedia_vid_stream_send_keyframe(cm->strm.v.stream); + } - return PJ_SUCCESS; + return PJ_SUCCESS; } #endif diff --git a/pjsip/src/pjsua-lib/pjsua_pres.c b/pjsip/src/pjsua-lib/pjsua_pres.c index 5f1708f37d..f725c53d3b 100644 --- a/pjsip/src/pjsua-lib/pjsua_pres.c +++ b/pjsip/src/pjsua-lib/pjsua_pres.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,45 +38,45 @@ static pjsua_buddy_id find_buddy(const pjsip_uri *uri) uri = (const pjsip_uri*) pjsip_uri_get_uri((pjsip_uri*)uri); if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri)) - return PJSUA_INVALID_ID; + return PJSUA_INVALID_ID; sip_uri = (const pjsip_sip_uri*) uri; for (i=0; iuser, &b->name)==0 && - pj_stricmp(&sip_uri->host, &b->host)==0 && - (sip_uri->port==(int)b->port || (sip_uri->port==0 && b->port==5060))) - { - /* Match */ - return i; - } + if (pj_stricmp(&sip_uri->user, &b->name)==0 && + pj_stricmp(&sip_uri->host, &b->host)==0 && + (sip_uri->port==(int)b->port || (sip_uri->port==0 && b->port==5060))) + { + /* Match */ + return i; + } } return PJSUA_INVALID_ID; } -#define LOCK_DIALOG 1 -#define LOCK_PJSUA 2 -#define LOCK_ALL (LOCK_DIALOG | LOCK_PJSUA) +#define LOCK_DIALOG 1 +#define LOCK_PJSUA 2 +#define LOCK_ALL (LOCK_DIALOG | LOCK_PJSUA) /* Buddy lock object */ struct buddy_lock { - pjsua_buddy *buddy; + pjsua_buddy *buddy; pjsip_dialog *dlg; - pj_uint8_t flag; + pj_uint8_t flag; }; /* Acquire lock to the specified buddy_id */ static pj_status_t lock_buddy(const char *title, - pjsua_buddy_id buddy_id, - struct buddy_lock *lck, - unsigned _unused_) + pjsua_buddy_id buddy_id, + struct buddy_lock *lck, + unsigned _unused_) { enum { MAX_RETRY=50 }; pj_bool_t has_pjsua_lock = PJ_FALSE; @@ -88,45 +87,45 @@ static pj_status_t lock_buddy(const char *title, pj_bzero(lck, sizeof(*lck)); for (retry=0; retryflag = LOCK_PJSUA; - lck->buddy = &pjsua_var.buddy[buddy_id]; + has_pjsua_lock = PJ_TRUE; + lck->flag = LOCK_PJSUA; + lck->buddy = &pjsua_var.buddy[buddy_id]; - if (lck->buddy->dlg == NULL) - return PJ_SUCCESS; + if (lck->buddy->dlg == NULL) + return PJ_SUCCESS; - if (pjsip_dlg_try_inc_lock(lck->buddy->dlg) != PJ_SUCCESS) { - lck->flag = 0; - lck->buddy = NULL; - has_pjsua_lock = PJ_FALSE; - PJSUA_UNLOCK(); - pj_thread_sleep(retry/10); - continue; - } + if (pjsip_dlg_try_inc_lock(lck->buddy->dlg) != PJ_SUCCESS) { + lck->flag = 0; + lck->buddy = NULL; + has_pjsua_lock = PJ_FALSE; + PJSUA_UNLOCK(); + pj_thread_sleep(retry/10); + continue; + } - lck->dlg = lck->buddy->dlg; - lck->flag = LOCK_DIALOG; - PJSUA_UNLOCK(); + lck->dlg = lck->buddy->dlg; + lck->flag = LOCK_DIALOG; + PJSUA_UNLOCK(); - break; + break; } if (lck->flag == 0) { - if (has_pjsua_lock == PJ_FALSE) - PJ_LOG(1,(THIS_FILE, "Timed-out trying to acquire PJSUA mutex " - "(possibly system has deadlocked) in %s", - title)); - else - PJ_LOG(1,(THIS_FILE, "Timed-out trying to acquire dialog mutex " - "(possibly system has deadlocked) in %s", - title)); - return PJ_ETIMEDOUT; + if (has_pjsua_lock == PJ_FALSE) + PJ_LOG(1,(THIS_FILE, "Timed-out trying to acquire PJSUA mutex " + "(possibly system has deadlocked) in %s", + title)); + else + PJ_LOG(1,(THIS_FILE, "Timed-out trying to acquire dialog mutex " + "(possibly system has deadlocked) in %s", + title)); + return PJ_ETIMEDOUT; } return PJ_SUCCESS; @@ -136,10 +135,10 @@ static pj_status_t lock_buddy(const char *title, static void unlock_buddy(struct buddy_lock *lck) { if (lck->flag & LOCK_DIALOG) - pjsip_dlg_dec_lock(lck->dlg); + pjsip_dlg_dec_lock(lck->dlg); if (lck->flag & LOCK_PJSUA) - PJSUA_UNLOCK(); + PJSUA_UNLOCK(); } @@ -167,11 +166,11 @@ PJ_DEF(pjsua_buddy_id) pjsua_buddy_find(const pj_str_t *uri_str) uri = pjsip_parse_uri(pool, input.ptr, input.slen, 0); if (!uri) - buddy_id = PJSUA_INVALID_ID; + buddy_id = PJSUA_INVALID_ID; else { - PJSUA_LOCK(); - buddy_id = find_buddy(uri); - PJSUA_UNLOCK(); + PJSUA_LOCK(); + buddy_id = find_buddy(uri); + PJSUA_UNLOCK(); } pj_pool_release(pool); @@ -186,7 +185,7 @@ PJ_DEF(pjsua_buddy_id) pjsua_buddy_find(const pj_str_t *uri_str) PJ_DEF(pj_bool_t) pjsua_buddy_is_valid(pjsua_buddy_id buddy_id) { return buddy_id>=0 && buddy_id<(int)PJ_ARRAY_SIZE(pjsua_var.buddy) && - pjsua_var.buddy[buddy_id].uri.slen != 0; + pjsua_var.buddy[buddy_id].uri.slen != 0; } @@ -194,7 +193,7 @@ PJ_DEF(pj_bool_t) pjsua_buddy_is_valid(pjsua_buddy_id buddy_id) * Enum buddy IDs. */ PJ_DEF(pj_status_t) pjsua_enum_buddies( pjsua_buddy_id ids[], - unsigned *count) + unsigned *count) { unsigned i, c; @@ -203,10 +202,10 @@ PJ_DEF(pj_status_t) pjsua_enum_buddies( pjsua_buddy_id ids[], PJSUA_LOCK(); for (i=0, c=0; c<*count && iid = buddy->index; if (pjsua_var.buddy[buddy_id].uri.slen == 0) { - unlock_buddy(&lck); - return PJ_SUCCESS; + unlock_buddy(&lck); + return PJ_SUCCESS; } /* uri */ @@ -262,27 +261,27 @@ PJ_DEF(pj_status_t) pjsua_buddy_get_info( pjsua_buddy_id buddy_id, /* status and status text */ if (buddy->sub == NULL || buddy->status.info_cnt==0) { - info->status = PJSUA_BUDDY_STATUS_UNKNOWN; - info->status_text = pj_str("?"); + info->status = PJSUA_BUDDY_STATUS_UNKNOWN; + info->status_text = pj_str("?"); } else if (pjsua_var.buddy[buddy_id].status.info[0].basic_open) { - info->status = PJSUA_BUDDY_STATUS_ONLINE; + info->status = PJSUA_BUDDY_STATUS_ONLINE; - /* copy RPID information */ - info->rpid = buddy->status.info[0].rpid; + /* copy RPID information */ + info->rpid = buddy->status.info[0].rpid; - if (info->rpid.note.slen) - info->status_text = info->rpid.note; - else - info->status_text = pj_str("Online"); + if (info->rpid.note.slen) + info->status_text = info->rpid.note; + else + info->status_text = pj_str("Online"); } else { - info->status = PJSUA_BUDDY_STATUS_OFFLINE; - info->rpid = buddy->status.info[0].rpid; + info->status = PJSUA_BUDDY_STATUS_OFFLINE; + info->rpid = buddy->status.info[0].rpid; - if (info->rpid.note.slen) - info->status_text = info->rpid.note; - else - info->status_text = pj_str("Offline"); + if (info->rpid.note.slen) + info->status_text = info->rpid.note; + else + info->status_text = pj_str("Offline"); } /* monitor pres */ @@ -291,28 +290,28 @@ PJ_DEF(pj_status_t) pjsua_buddy_get_info( pjsua_buddy_id buddy_id, /* subscription state and termination reason */ info->sub_term_code = buddy->term_code; if (buddy->sub) { - info->sub_state = pjsip_evsub_get_state(buddy->sub); - info->sub_state_name = pjsip_evsub_get_state_name(buddy->sub); - if (info->sub_state == PJSIP_EVSUB_STATE_TERMINATED && - total < sizeof(info->buf_)) - { - info->sub_term_reason.ptr = info->buf_ + total; - pj_strncpy(&info->sub_term_reason, - pjsip_evsub_get_termination_reason(buddy->sub), - sizeof(info->buf_) - total); - total += info->sub_term_reason.slen; - } else { - info->sub_term_reason = pj_str(""); - } + info->sub_state = pjsip_evsub_get_state(buddy->sub); + info->sub_state_name = pjsip_evsub_get_state_name(buddy->sub); + if (info->sub_state == PJSIP_EVSUB_STATE_TERMINATED && + total < sizeof(info->buf_)) + { + info->sub_term_reason.ptr = info->buf_ + total; + pj_strncpy(&info->sub_term_reason, + pjsip_evsub_get_termination_reason(buddy->sub), + sizeof(info->buf_) - total); + total += info->sub_term_reason.slen; + } else { + info->sub_term_reason = pj_str(""); + } } else if (total < sizeof(info->buf_)) { - info->sub_state_name = "NULL"; - info->sub_term_reason.ptr = info->buf_ + total; - pj_strncpy(&info->sub_term_reason, &buddy->term_reason, - sizeof(info->buf_) - total); - total += info->sub_term_reason.slen; + info->sub_state_name = "NULL"; + info->sub_term_reason.ptr = info->buf_ + total; + pj_strncpy(&info->sub_term_reason, &buddy->term_reason, + sizeof(info->buf_) - total); + total += info->sub_term_reason.slen; } else { - info->sub_state_name = "NULL"; - info->sub_term_reason = pj_str(""); + info->sub_state_name = "NULL"; + info->sub_term_reason = pj_str(""); } unlock_buddy(&lck); @@ -323,7 +322,7 @@ PJ_DEF(pj_status_t) pjsua_buddy_get_info( pjsua_buddy_id buddy_id, * Set the user data associated with the buddy object. */ PJ_DEF(pj_status_t) pjsua_buddy_set_user_data( pjsua_buddy_id buddy_id, - void *user_data) + void *user_data) { struct buddy_lock lck; pj_status_t status; @@ -332,7 +331,7 @@ PJ_DEF(pj_status_t) pjsua_buddy_set_user_data( pjsua_buddy_id buddy_id, status = lock_buddy("pjsua_buddy_set_user_data()", buddy_id, &lck, 0); if (status != PJ_SUCCESS) - return status; + return status; pjsua_var.buddy[buddy_id].user_data = user_data; @@ -355,7 +354,7 @@ PJ_DEF(void*) pjsua_buddy_get_user_data(pjsua_buddy_id buddy_id) status = lock_buddy("pjsua_buddy_get_user_data()", buddy_id, &lck, 0); if (status != PJ_SUCCESS) - return NULL; + return NULL; user_data = pjsua_var.buddy[buddy_id].user_data; @@ -381,7 +380,7 @@ static void reset_buddy(pjsua_buddy_id id) * Add new buddy. */ PJ_DEF(pj_status_t) pjsua_buddy_add( const pjsua_buddy_config *cfg, - pjsua_buddy_id *p_buddy_id) + pjsua_buddy_id *p_buddy_id) { pjsip_name_addr *url; pjsua_buddy *buddy; @@ -390,67 +389,67 @@ PJ_DEF(pj_status_t) pjsua_buddy_add( const pjsua_buddy_config *cfg, pj_str_t tmp; PJ_ASSERT_RETURN(pjsua_var.buddy_cnt <= - PJ_ARRAY_SIZE(pjsua_var.buddy), - PJ_ETOOMANY); + PJ_ARRAY_SIZE(pjsua_var.buddy), + PJ_ETOOMANY); PJ_LOG(4,(THIS_FILE, "Adding buddy: %.*s", - (int)cfg->uri.slen, cfg->uri.ptr)); + (int)cfg->uri.slen, cfg->uri.ptr)); pj_log_push_indent(); PJSUA_LOCK(); /* Find empty slot */ for (index=0; index<(int)PJ_ARRAY_SIZE(pjsua_var.buddy); ++index) { - if (pjsua_var.buddy[index].uri.slen == 0) - break; + if (pjsua_var.buddy[index].uri.slen == 0) + break; } /* Expect to find an empty slot */ if (index == PJ_ARRAY_SIZE(pjsua_var.buddy)) { - PJSUA_UNLOCK(); - /* This shouldn't happen */ - pj_assert(!"index < PJ_ARRAY_SIZE(pjsua_var.buddy)"); - pj_log_pop_indent(); - return PJ_ETOOMANY; + PJSUA_UNLOCK(); + /* This shouldn't happen */ + pj_assert(!"index < PJ_ARRAY_SIZE(pjsua_var.buddy)"); + pj_log_pop_indent(); + return PJ_ETOOMANY; } buddy = &pjsua_var.buddy[index]; /* Create pool for this buddy */ if (buddy->pool) { - pj_pool_reset(buddy->pool); + pj_pool_reset(buddy->pool); } else { - char name[PJ_MAX_OBJ_NAME]; - pj_ansi_snprintf(name, sizeof(name), "buddy%03d", index); - buddy->pool = pjsua_pool_create(name, 512, 256); + char name[PJ_MAX_OBJ_NAME]; + pj_ansi_snprintf(name, sizeof(name), "buddy%03d", index); + buddy->pool = pjsua_pool_create(name, 512, 256); } /* Init buffers for presence subscription status */ buddy->term_reason.ptr = (char*) - pj_pool_alloc(buddy->pool, - PJSUA_BUDDY_SUB_TERM_REASON_LEN); + pj_pool_alloc(buddy->pool, + PJSUA_BUDDY_SUB_TERM_REASON_LEN); /* Get name and display name for buddy */ pj_strdup_with_null(buddy->pool, &tmp, &cfg->uri); url = (pjsip_name_addr*)pjsip_parse_uri(buddy->pool, tmp.ptr, tmp.slen, - PJSIP_PARSE_URI_AS_NAMEADDR); + PJSIP_PARSE_URI_AS_NAMEADDR); if (url == NULL) { - pjsua_perror(THIS_FILE, "Unable to add buddy", PJSIP_EINVALIDURI); - pj_pool_release(buddy->pool); - buddy->pool = NULL; - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return PJSIP_EINVALIDURI; + pjsua_perror(THIS_FILE, "Unable to add buddy", PJSIP_EINVALIDURI); + pj_pool_release(buddy->pool); + buddy->pool = NULL; + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return PJSIP_EINVALIDURI; } /* Only support SIP schemes */ if (!PJSIP_URI_SCHEME_IS_SIP(url) && !PJSIP_URI_SCHEME_IS_SIPS(url)) { - pj_pool_release(buddy->pool); - buddy->pool = NULL; - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return PJSIP_EINVALIDSCHEME; + pj_pool_release(buddy->pool); + buddy->pool = NULL; + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return PJSIP_EINVALIDSCHEME; } /* Reset buddy, to make sure everything is cleared with default @@ -468,13 +467,13 @@ PJ_DEF(pj_status_t) pjsua_buddy_add( const pjsua_buddy_config *cfg, pjsua_var.buddy[index].port = sip_uri->port; pjsua_var.buddy[index].monitor = cfg->subscribe; if (pjsua_var.buddy[index].port == 0) - pjsua_var.buddy[index].port = 5060; + pjsua_var.buddy[index].port = 5060; /* Save user data */ pjsua_var.buddy[index].user_data = (void*)cfg->user_data; if (p_buddy_id) - *p_buddy_id = index; + *p_buddy_id = index; pjsua_var.buddy_cnt++; @@ -498,16 +497,16 @@ PJ_DEF(pj_status_t) pjsua_buddy_del(pjsua_buddy_id buddy_id) pj_status_t status; PJ_ASSERT_RETURN(buddy_id>=0 && - buddy_id<(int)PJ_ARRAY_SIZE(pjsua_var.buddy), - PJ_EINVAL); + buddy_id<(int)PJ_ARRAY_SIZE(pjsua_var.buddy), + PJ_EINVAL); if (pjsua_var.buddy[buddy_id].uri.slen == 0) { - return PJ_SUCCESS; + return PJ_SUCCESS; } status = lock_buddy("pjsua_buddy_del()", buddy_id, &lck, 0); if (status != PJ_SUCCESS) - return status; + return status; PJ_LOG(4,(THIS_FILE, "Buddy %d: deleting..", buddy_id)); pj_log_push_indent(); @@ -517,8 +516,8 @@ PJ_DEF(pj_status_t) pjsua_buddy_del(pjsua_buddy_id buddy_id) /* Not interested with further events for this buddy */ if (pjsua_var.buddy[buddy_id].sub) { - pjsip_evsub_set_mod_data(pjsua_var.buddy[buddy_id].sub, - pjsua_var.mod.id, NULL); + pjsip_evsub_set_mod_data(pjsua_var.buddy[buddy_id].sub, + pjsua_var.mod.id, NULL); } /* Remove buddy */ @@ -527,8 +526,8 @@ PJ_DEF(pj_status_t) pjsua_buddy_del(pjsua_buddy_id buddy_id) /* Clear timer */ if (pjsua_var.buddy[buddy_id].timer.id) { - pjsua_cancel_timer(&pjsua_var.buddy[buddy_id].timer); - pjsua_var.buddy[buddy_id].timer.id = PJ_FALSE; + pjsua_cancel_timer(&pjsua_var.buddy[buddy_id].timer); + pjsua_var.buddy[buddy_id].timer.id = PJ_FALSE; } /* Reset buddy struct */ @@ -544,7 +543,7 @@ PJ_DEF(pj_status_t) pjsua_buddy_del(pjsua_buddy_id buddy_id) * Enable/disable buddy's presence monitoring. */ PJ_DEF(pj_status_t) pjsua_buddy_subscribe_pres( pjsua_buddy_id buddy_id, - pj_bool_t subscribe) + pj_bool_t subscribe) { struct buddy_lock lck; pj_status_t status; @@ -553,7 +552,7 @@ PJ_DEF(pj_status_t) pjsua_buddy_subscribe_pres( pjsua_buddy_id buddy_id, status = lock_buddy("pjsua_buddy_subscribe_pres()", buddy_id, &lck, 0); if (status != PJ_SUCCESS) - return status; + return status; pj_log_push_indent(); @@ -579,24 +578,24 @@ PJ_DEF(pj_status_t) pjsua_buddy_update_pres(pjsua_buddy_id buddy_id) status = lock_buddy("pjsua_buddy_update_pres()", buddy_id, &lck, 0); if (status != PJ_SUCCESS) - return status; + return status; PJ_LOG(4,(THIS_FILE, "Buddy %d: updating presence..", buddy_id)); pj_log_push_indent(); /* Is this an unsubscribe request? */ if (!lck.buddy->monitor) { - unsubscribe_buddy_presence(buddy_id); - unlock_buddy(&lck); - pj_log_pop_indent(); - return PJ_SUCCESS; + unsubscribe_buddy_presence(buddy_id); + unlock_buddy(&lck); + pj_log_pop_indent(); + return PJ_SUCCESS; } /* Ignore if presence is already active for the buddy */ if (lck.buddy->sub) { - unlock_buddy(&lck); - pj_log_pop_indent(); - return PJ_SUCCESS; + unlock_buddy(&lck); + pj_log_pop_indent(); + return PJ_SUCCESS; } /* Initiate presence subscription */ @@ -624,42 +623,42 @@ PJ_DEF(void) pjsua_pres_dump(pj_bool_t verbose) * subscriptions. */ if (verbose == PJ_FALSE) { - - int count = 0; + + int count = 0; - for (acc_id=0; acc_idnext; - } - } - } + uapres = pjsua_var.acc[acc_id].pres_srv_list.next; + while (uapres != &pjsua_var.acc[acc_id].pres_srv_list) { + ++count; + uapres = uapres->next; + } + } + } - PJ_LOG(3,(THIS_FILE, "Number of server/UAS subscriptions: %d", - count)); + PJ_LOG(3,(THIS_FILE, "Number of server/UAS subscriptions: %d", + count)); - count = 0; + count = 0; - for (i=0; isub), - uapres->remote)); + uapres = pjsua_var.acc[acc_id].pres_srv_list.next; + while (uapres != &pjsua_var.acc[acc_id].pres_srv_list) { + + PJ_LOG(3,(THIS_FILE, " %10s %s", + pjsip_evsub_get_state_name(uapres->sub), + uapres->remote)); - uapres = uapres->next; - } - } + uapres = uapres->next; + } + } } /* @@ -703,26 +702,26 @@ PJ_DEF(void) pjsua_pres_dump(pj_bool_t verbose) if (pjsua_var.buddy_cnt == 0) { - PJ_LOG(3,(THIS_FILE, " - no buddy list - ")); + PJ_LOG(3,(THIS_FILE, " - no buddy list - ")); } else { - for (i=0; iremote, pjsip_evsub_get_state_name(sub))); - pj_log_push_indent(); + PJ_LOG(4,(THIS_FILE, "Server subscription to %s is %s", + uapres->remote, pjsip_evsub_get_state_name(sub))); + pj_log_push_indent(); - state = pjsip_evsub_get_state(sub); + state = pjsip_evsub_get_state(sub); - if (pjsua_var.ua_cfg.cb.on_srv_subscribe_state) { - pj_str_t from; + if (pjsua_var.ua_cfg.cb.on_srv_subscribe_state) { + pj_str_t from; - from = uapres->dlg->remote.info_str; - (*pjsua_var.ua_cfg.cb.on_srv_subscribe_state)(uapres->acc_id, - uapres, &from, - state, event); - } + from = uapres->dlg->remote.info_str; + (*pjsua_var.ua_cfg.cb.on_srv_subscribe_state)(uapres->acc_id, + uapres, &from, + state, event); + } - if (state == PJSIP_EVSUB_STATE_TERMINATED) { - pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); - pj_list_erase(uapres); - } - pj_log_pop_indent(); + if (state == PJSIP_EVSUB_STATE_TERMINATED) { + pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); + pj_list_erase(uapres); + } + pj_log_pop_indent(); } PJSUA_UNLOCK(); @@ -814,16 +813,16 @@ static pj_bool_t pres_on_rx_request(pjsip_rx_data *rdata) pj_status_t status; if (pjsip_method_cmp(req_method, pjsip_get_subscribe_method()) != 0) - return PJ_FALSE; + return PJ_FALSE; /* Incoming SUBSCRIBE: */ /* Don't want to accept the request if shutdown is in progress */ if (pjsua_var.thread_quit_flag) { - pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, - PJSIP_SC_TEMPORARILY_UNAVAILABLE, NULL, - NULL, NULL); - return PJ_TRUE; + pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, + PJSIP_SC_TEMPORARILY_UNAVAILABLE, NULL, + NULL, NULL); + return PJ_TRUE; } PJSUA_LOCK(); @@ -831,81 +830,81 @@ static pj_bool_t pres_on_rx_request(pjsip_rx_data *rdata) /* Find which account for the incoming request. */ acc_id = pjsua_acc_find_for_incoming(rdata); if (acc_id == PJSUA_INVALID_ID) { - PJ_LOG(2, (THIS_FILE, - "Unable to process incoming message %s " - "due to no available account", - pjsip_rx_data_get_info(rdata))); - - PJSUA_UNLOCK(); - pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, - PJSIP_SC_TEMPORARILY_UNAVAILABLE, NULL, - NULL, NULL); - pj_log_pop_indent(); - return PJ_TRUE; + PJ_LOG(2, (THIS_FILE, + "Unable to process incoming message %s " + "due to no available account", + pjsip_rx_data_get_info(rdata))); + + PJSUA_UNLOCK(); + pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, + PJSIP_SC_TEMPORARILY_UNAVAILABLE, NULL, + NULL, NULL); + pj_log_pop_indent(); + return PJ_TRUE; } acc = &pjsua_var.acc[acc_id]; PJ_LOG(4,(THIS_FILE, "Creating server subscription, using account %d", - acc_id)); + acc_id)); pj_log_push_indent(); /* Create suitable Contact header */ if (acc->contact.slen) { - contact = acc->contact; + contact = acc->contact; } else { - status = pjsua_acc_create_uas_contact(rdata->tp_info.pool, &contact, - acc_id, rdata); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to generate Contact header", - status); - PJSUA_UNLOCK(); - pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, 400, NULL, - NULL, NULL); - pj_log_pop_indent(); - return PJ_TRUE; - } + status = pjsua_acc_create_uas_contact(rdata->tp_info.pool, &contact, + acc_id, rdata); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to generate Contact header", + status); + PJSUA_UNLOCK(); + pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, 400, NULL, + NULL, NULL); + pj_log_pop_indent(); + return PJ_TRUE; + } } /* Create UAS dialog: */ status = pjsip_dlg_create_uas_and_inc_lock(pjsip_ua_instance(), rdata, - &contact, &dlg); + &contact, &dlg); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Unable to create UAS dialog for subscription", - status); - PJSUA_UNLOCK(); - pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, 400, NULL, - NULL, NULL); - pj_log_pop_indent(); - return PJ_TRUE; + pjsua_perror(THIS_FILE, + "Unable to create UAS dialog for subscription", + status); + PJSUA_UNLOCK(); + pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, 400, NULL, + NULL, NULL); + pj_log_pop_indent(); + return PJ_TRUE; } if (acc->cfg.allow_via_rewrite && acc->via_addr.host.slen > 0) { pjsip_dlg_set_via_sent_by(dlg, &acc->via_addr, acc->via_tp); } else if (!pjsua_sip_acc_is_using_stun(acc_id) && - !pjsua_sip_acc_is_using_upnp(acc_id)) + !pjsua_sip_acc_is_using_upnp(acc_id)) { - /* Choose local interface to use in Via if acc is not using - * STUN nor UPnP. See https://github.com/pjsip/pjproject/issues/1412 - */ - char target_buf[PJSIP_MAX_URL_SIZE]; - pj_str_t target; - pjsip_host_port via_addr; - const void *via_tp; - - target.ptr = target_buf; - target.slen = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, - dlg->target, - target_buf, sizeof(target_buf)); - if (target.slen < 0) target.slen = 0; - - if (pjsua_acc_get_uac_addr(acc_id, dlg->pool, &target, - &via_addr, NULL, NULL, - &via_tp) == PJ_SUCCESS) - { - pjsip_dlg_set_via_sent_by(dlg, &via_addr, - (pjsip_transport*)via_tp); - } + /* Choose local interface to use in Via if acc is not using + * STUN nor UPnP. See https://github.com/pjsip/pjproject/issues/1412 + */ + char target_buf[PJSIP_MAX_URL_SIZE]; + pj_str_t target; + pjsip_host_port via_addr; + const void *via_tp; + + target.ptr = target_buf; + target.slen = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, + dlg->target, + target_buf, sizeof(target_buf)); + if (target.slen < 0) target.slen = 0; + + if (pjsua_acc_get_uac_addr(acc_id, dlg->pool, &target, + &via_addr, NULL, NULL, + &via_tp) == PJ_SUCCESS) + { + pjsip_dlg_set_via_sent_by(dlg, &via_addr, + (pjsip_transport*)via_tp); + } } /* Set credentials and preference. */ @@ -919,26 +918,26 @@ static pj_bool_t pres_on_rx_request(pjsip_rx_data *rdata) /* Create server presence subscription: */ status = pjsip_pres_create_uas( dlg, &pres_cb, rdata, &sub); if (status != PJ_SUCCESS) { - int code = PJSIP_ERRNO_TO_SIP_STATUS(status); - pjsip_tx_data *tdata; + int code = PJSIP_ERRNO_TO_SIP_STATUS(status); + pjsip_tx_data *tdata; - pjsua_perror(THIS_FILE, "Unable to create server subscription", - status); + pjsua_perror(THIS_FILE, "Unable to create server subscription", + status); - if (code==599 || code > 699 || code < 300) { - code = 400; - } + if (code==599 || code > 699 || code < 300) { + code = 400; + } - status = pjsip_dlg_create_response(dlg, rdata, code, NULL, &tdata); - if (status == PJ_SUCCESS) { - status = pjsip_dlg_send_response(dlg, pjsip_rdata_get_tsx(rdata), - tdata); - } + status = pjsip_dlg_create_response(dlg, rdata, code, NULL, &tdata); + if (status == PJ_SUCCESS) { + status = pjsip_dlg_send_response(dlg, pjsip_rdata_get_tsx(rdata), + tdata); + } - pjsip_dlg_dec_lock(dlg); - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return PJ_TRUE; + pjsip_dlg_dec_lock(dlg); + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return PJ_TRUE; } /* Subscription has been created, decrement & release dlg lock */ @@ -948,10 +947,10 @@ static pj_bool_t pres_on_rx_request(pjsip_rx_data *rdata) * to this transport too. */ if (acc->cfg.transport_id != PJSUA_INVALID_ID) { - pjsip_tpselector tp_sel; + pjsip_tpselector tp_sel; - pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); - pjsip_dlg_set_transport(dlg, &tp_sel); + pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); + pjsip_dlg_set_transport(dlg, &tp_sel); } /* Attach our data to the subscription: */ @@ -961,11 +960,11 @@ static pj_bool_t pres_on_rx_request(pjsip_rx_data *rdata) uapres->acc_id = acc_id; uapres->dlg = dlg; status = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, dlg->remote.info->uri, - uapres->remote, PJSIP_MAX_URL_SIZE); + uapres->remote, PJSIP_MAX_URL_SIZE); if (status < 1) - pj_ansi_strcpy(uapres->remote, "<-- url is too long-->"); + pj_ansi_strcpy(uapres->remote, "<-- url is too long-->"); else - uapres->remote[status] = '\0'; + uapres->remote[status] = '\0'; pjsip_evsub_add_header(sub, &acc->cfg.sub_hdr_list); pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, uapres); @@ -976,12 +975,12 @@ static pj_bool_t pres_on_rx_request(pjsip_rx_data *rdata) /* Capture the value of Expires header. */ expires_hdr = (pjsip_expires_hdr*) - pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, - NULL); + pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, + NULL); if (expires_hdr) - uapres->expires = expires_hdr->ivalue; + uapres->expires = expires_hdr->ivalue; else - uapres->expires = PJSIP_EXPIRES_NOT_SPECIFIED; + uapres->expires = PJSIP_EXPIRES_NOT_SPECIFIED; st_code = (pjsip_status_code)200; reason = pj_str("OK"); @@ -989,67 +988,67 @@ static pj_bool_t pres_on_rx_request(pjsip_rx_data *rdata) /* Notify application callback, if any */ if (pjsua_var.ua_cfg.cb.on_incoming_subscribe) { - pjsua_buddy_id buddy_id; + pjsua_buddy_id buddy_id; - buddy_id = find_buddy(rdata->msg_info.from->uri); + buddy_id = find_buddy(rdata->msg_info.from->uri); - (*pjsua_var.ua_cfg.cb.on_incoming_subscribe)(acc_id, uapres, buddy_id, - &dlg->remote.info_str, - rdata, &st_code, &reason, - &msg_data); + (*pjsua_var.ua_cfg.cb.on_incoming_subscribe)(acc_id, uapres, buddy_id, + &dlg->remote.info_str, + rdata, &st_code, &reason, + &msg_data); } /* Handle rejection case */ if (st_code >= 300) { - pjsip_tx_data *tdata; - - /* Create response */ - status = pjsip_dlg_create_response(dlg, rdata, st_code, - &reason, &tdata); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating response", status); - pj_list_erase(uapres); - pjsip_pres_terminate(sub, PJ_FALSE); - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return PJ_FALSE; - } - - /* Add header list, if any */ - pjsua_process_msg_data(tdata, &msg_data); - - /* Send the response */ - status = pjsip_dlg_send_response(dlg, pjsip_rdata_get_tsx(rdata), - tdata); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error sending response", status); - /* This is not fatal */ - } - - /* Terminate presence subscription */ - pj_list_erase(uapres); - pjsip_pres_terminate(sub, PJ_FALSE); - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return PJ_TRUE; + pjsip_tx_data *tdata; + + /* Create response */ + status = pjsip_dlg_create_response(dlg, rdata, st_code, + &reason, &tdata); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error creating response", status); + pj_list_erase(uapres); + pjsip_pres_terminate(sub, PJ_FALSE); + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return PJ_FALSE; + } + + /* Add header list, if any */ + pjsua_process_msg_data(tdata, &msg_data); + + /* Send the response */ + status = pjsip_dlg_send_response(dlg, pjsip_rdata_get_tsx(rdata), + tdata); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error sending response", status); + /* This is not fatal */ + } + + /* Terminate presence subscription */ + pj_list_erase(uapres); + pjsip_pres_terminate(sub, PJ_FALSE); + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return PJ_TRUE; } /* Create and send 2xx response to the SUBSCRIBE request: */ status = pjsip_pres_accept(sub, rdata, st_code, &msg_data.hdr_list); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to accept presence subscription", - status); - pj_list_erase(uapres); - pjsip_pres_terminate(sub, PJ_FALSE); - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return PJ_FALSE; + pjsua_perror(THIS_FILE, "Unable to accept presence subscription", + status); + pj_list_erase(uapres); + pjsip_pres_terminate(sub, PJ_FALSE); + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return PJ_FALSE; } /* If code is 200, send NOTIFY now */ if (st_code == 200) { - pjsua_pres_notify(acc_id, uapres, PJSIP_EVSUB_STATE_ACTIVE, - NULL, NULL, PJ_TRUE, &msg_data); + pjsua_pres_notify(acc_id, uapres, PJSIP_EVSUB_STATE_ACTIVE, + NULL, NULL, PJ_TRUE, &msg_data); } /* Done: */ @@ -1063,12 +1062,12 @@ static pj_bool_t pres_on_rx_request(pjsip_rx_data *rdata) * Send NOTIFY. */ PJ_DEF(pj_status_t) pjsua_pres_notify( pjsua_acc_id acc_id, - pjsua_srv_pres *srv_pres, - pjsip_evsub_state ev_state, - const pj_str_t *state_str, - const pj_str_t *reason, - pj_bool_t with_body, - const pjsua_msg_data *msg_data) + pjsua_srv_pres *srv_pres, + pjsip_evsub_state ev_state, + const pj_str_t *state_str, + const pj_str_t *reason, + pj_bool_t with_body, + const pjsua_msg_data *msg_data) { pjsua_acc *acc; pjsip_pres_status pres_status; @@ -1081,12 +1080,12 @@ PJ_DEF(pj_status_t) pjsua_pres_notify( pjsua_acc_id acc_id, /* Check that account ID is valid */ PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc), - PJ_EINVAL); + PJ_EINVAL); /* Check that account is valid */ PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP); PJ_LOG(4,(THIS_FILE, "Acc %d: sending NOTIFY for srv_pres=0x%p..", - acc_id, (int)(pj_ssize_t)srv_pres)); + acc_id, (int)(pj_ssize_t)srv_pres)); pj_log_push_indent(); PJSUA_LOCK(); @@ -1095,10 +1094,10 @@ PJ_DEF(pj_status_t) pjsua_pres_notify( pjsua_acc_id acc_id, /* Check that the server presence subscription is still valid */ if (pj_list_find_node(&acc->pres_srv_list, srv_pres) == NULL) { - /* Subscription has been terminated */ - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return PJ_EINVALIDOP; + /* Subscription has been terminated */ + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return PJ_EINVALIDOP; } /* Set our online status: */ @@ -1111,7 +1110,7 @@ PJ_DEF(pj_status_t) pjsua_pres_notify( pjsua_acc_id acc_id, //pres_status.info[0].contact = pjsua_var.local_uri; /* add RPID information */ pj_memcpy(&pres_status.info[0].rpid, &acc->rpid, - sizeof(pjrpid_element)); + sizeof(pjrpid_element)); pjsip_pres_set_status(srv_pres->sub, &pres_status); @@ -1119,40 +1118,40 @@ PJ_DEF(pj_status_t) pjsua_pres_notify( pjsua_acc_id acc_id, * set subscription state to TERMINATED. */ if (srv_pres->expires == 0) - ev_state = PJSIP_EVSUB_STATE_TERMINATED; + ev_state = PJSIP_EVSUB_STATE_TERMINATED; /* Create and send the NOTIFY to active subscription: */ status = pjsip_pres_notify(srv_pres->sub, ev_state, state_str, - reason, &tdata); + reason, &tdata); if (status == PJ_SUCCESS) { - /* Force removal of message body if msg_body==FALSE */ - if (!with_body) { - tdata->msg->body = NULL; - } - pjsua_process_msg_data(tdata, msg_data); - status = pjsip_pres_send_request( srv_pres->sub, tdata); + /* Force removal of message body if msg_body==FALSE */ + if (!with_body) { + tdata->msg->body = NULL; + } + pjsua_process_msg_data(tdata, msg_data); + status = pjsip_pres_send_request( srv_pres->sub, tdata); } if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create/send NOTIFY", - status); - pj_list_erase(srv_pres); - pjsip_pres_terminate(srv_pres->sub, PJ_FALSE); - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return status; + pjsua_perror(THIS_FILE, "Unable to create/send NOTIFY", + status); + pj_list_erase(srv_pres); + pjsip_pres_terminate(srv_pres->sub, PJ_FALSE); + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return status; } /* Subscribe to buddy's presence if we're not subscribed */ buddy_id = find_buddy(srv_pres->dlg->remote.info->uri); if (buddy_id != PJSUA_INVALID_ID) { - pjsua_buddy *b = &pjsua_var.buddy[buddy_id]; - if (b->monitor && b->sub == NULL) { - PJ_LOG(4,(THIS_FILE, "Received SUBSCRIBE from buddy %d, " - "activating outgoing subscription", buddy_id)); - subscribe_buddy_presence(buddy_id); - } + pjsua_buddy *b = &pjsua_var.buddy[buddy_id]; + if (b->monitor && b->sub == NULL) { + PJ_LOG(4,(THIS_FILE, "Received SUBSCRIBE from buddy %d, " + "activating outgoing subscription", buddy_id)); + subscribe_buddy_presence(buddy_id); + } } PJSUA_UNLOCK(); @@ -1170,37 +1169,37 @@ static void publish_cb(struct pjsip_publishc_cbparam *param) if (param->code/100 != 2 || param->status != PJ_SUCCESS) { - pjsip_publishc_destroy(param->pubc); - acc->publish_sess = NULL; - - if (param->status != PJ_SUCCESS) { - char errmsg[PJ_ERR_MSG_SIZE]; - - pj_strerror(param->status, errmsg, sizeof(errmsg)); - PJ_LOG(1,(THIS_FILE, - "Client publication (PUBLISH) failed, status=%d, msg=%s", - param->status, errmsg)); - } else if (param->code == 412) { - /* 412 (Conditional Request Failed) - * The PUBLISH refresh has failed, retry with new one. - */ - pjsua_pres_init_publish_acc(acc->index); - - } else { - PJ_LOG(1,(THIS_FILE, - "Client publication (PUBLISH) failed (%d/%.*s)", - param->code, (int)param->reason.slen, - param->reason.ptr)); - } + pjsip_publishc_destroy(param->pubc); + acc->publish_sess = NULL; + + if (param->status != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + + pj_strerror(param->status, errmsg, sizeof(errmsg)); + PJ_LOG(1,(THIS_FILE, + "Client publication (PUBLISH) failed, status=%d, msg=%s", + param->status, errmsg)); + } else if (param->code == 412) { + /* 412 (Conditional Request Failed) + * The PUBLISH refresh has failed, retry with new one. + */ + pjsua_pres_init_publish_acc(acc->index); + + } else { + PJ_LOG(1,(THIS_FILE, + "Client publication (PUBLISH) failed (%d/%.*s)", + param->code, (int)param->reason.slen, + param->reason.ptr)); + } } else { - if (param->expiration < 1) { - /* Could happen if server "forgot" to include Expires header - * in the response. We will not renew, so destroy the pubc. - */ - pjsip_publishc_destroy(param->pubc); - acc->publish_sess = NULL; - } + if (param->expiration < 1) { + /* Could happen if server "forgot" to include Expires header + * in the response. We will not renew, so destroy the pubc. + */ + pjsip_publishc_destroy(param->pubc); + acc->publish_sess = NULL; + } } } @@ -1217,60 +1216,60 @@ static pj_status_t send_publish(int acc_id, pj_bool_t active) pj_status_t status; PJ_LOG(5,(THIS_FILE, "Acc %d: sending %sPUBLISH..", - acc_id, (active ? "" : "un-"))); + acc_id, (active ? "" : "un-"))); pj_log_push_indent(); /* Create PUBLISH request */ if (active) { - char *bpos; - pj_str_t entity; - - status = pjsip_publishc_publish(acc->publish_sess, PJ_TRUE, &tdata); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating PUBLISH request", status); - goto on_error; - } - - /* Set our online status: */ - pj_bzero(&pres_status, sizeof(pres_status)); - pres_status.info_cnt = 1; - pres_status.info[0].basic_open = acc->online_status; - pres_status.info[0].id = acc->cfg.pidf_tuple_id; - /* .. including RPID information */ - pj_memcpy(&pres_status.info[0].rpid, &acc->rpid, - sizeof(pjrpid_element)); - - /* Be careful not to send PIDF with presence entity ID containing - * "<" character. - */ - if ((bpos=pj_strchr(&acc_cfg->id, '<')) != NULL) { - char *epos = pj_strchr(&acc_cfg->id, '>'); - if (epos - bpos < 2) { - pj_assert(!"Unexpected invalid URI"); - status = PJSIP_EINVALIDURI; - goto on_error; - } - entity.ptr = bpos+1; - entity.slen = epos - bpos - 1; - } else { - entity = acc_cfg->id; - } - - /* Create and add PIDF message body */ - status = pjsip_pres_create_pidf(tdata->pool, &pres_status, - &entity, &tdata->msg->body); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating PIDF for PUBLISH request", - status); - pjsip_tx_data_dec_ref(tdata); - goto on_error; - } + char *bpos; + pj_str_t entity; + + status = pjsip_publishc_publish(acc->publish_sess, PJ_TRUE, &tdata); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error creating PUBLISH request", status); + goto on_error; + } + + /* Set our online status: */ + pj_bzero(&pres_status, sizeof(pres_status)); + pres_status.info_cnt = 1; + pres_status.info[0].basic_open = acc->online_status; + pres_status.info[0].id = acc->cfg.pidf_tuple_id; + /* .. including RPID information */ + pj_memcpy(&pres_status.info[0].rpid, &acc->rpid, + sizeof(pjrpid_element)); + + /* Be careful not to send PIDF with presence entity ID containing + * "<" character. + */ + if ((bpos=pj_strchr(&acc_cfg->id, '<')) != NULL) { + char *epos = pj_strchr(&acc_cfg->id, '>'); + if (epos - bpos < 2) { + pj_assert(!"Unexpected invalid URI"); + status = PJSIP_EINVALIDURI; + goto on_error; + } + entity.ptr = bpos+1; + entity.slen = epos - bpos - 1; + } else { + entity = acc_cfg->id; + } + + /* Create and add PIDF message body */ + status = pjsip_pres_create_pidf(tdata->pool, &pres_status, + &entity, &tdata->msg->body); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error creating PIDF for PUBLISH request", + status); + pjsip_tx_data_dec_ref(tdata); + goto on_error; + } } else { - status = pjsip_publishc_unpublish(acc->publish_sess, &tdata); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating PUBLISH request", status); - goto on_error; - } + status = pjsip_publishc_unpublish(acc->publish_sess, &tdata); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Error creating PUBLISH request", status); + goto on_error; + } } /* Add headers etc */ @@ -1281,31 +1280,31 @@ static pj_status_t send_publish(int acc_id, pj_bool_t active) pjsip_publishc_set_via_sent_by(acc->publish_sess, &acc->via_addr, acc->via_tp); } else if (!pjsua_sip_acc_is_using_stun(acc_id) && - !pjsua_sip_acc_is_using_upnp(acc_id)) + !pjsua_sip_acc_is_using_upnp(acc_id)) { - /* Choose local interface to use in Via if acc is not using - * STUN nor UPnP. See https://github.com/pjsip/pjproject/issues/1412 - */ - pjsip_host_port via_addr; - const void *via_tp; - - if (pjsua_acc_get_uac_addr(acc_id, acc->pool, &acc_cfg->id, - &via_addr, NULL, NULL, - &via_tp) == PJ_SUCCESS) + /* Choose local interface to use in Via if acc is not using + * STUN nor UPnP. See https://github.com/pjsip/pjproject/issues/1412 + */ + pjsip_host_port via_addr; + const void *via_tp; + + if (pjsua_acc_get_uac_addr(acc_id, acc->pool, &acc_cfg->id, + &via_addr, NULL, NULL, + &via_tp) == PJ_SUCCESS) { - pjsip_publishc_set_via_sent_by(acc->publish_sess, &via_addr, - (pjsip_transport*)via_tp); + pjsip_publishc_set_via_sent_by(acc->publish_sess, &via_addr, + (pjsip_transport*)via_tp); } } /* Send the PUBLISH request */ status = pjsip_publishc_send(acc->publish_sess, tdata); if (status == PJ_EPENDING) { - PJ_LOG(3,(THIS_FILE, "Previous request is in progress, " - "PUBLISH request is queued")); + PJ_LOG(3,(THIS_FILE, "Previous request is in progress, " + "PUBLISH request is queued")); } else if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error sending PUBLISH request", status); - goto on_error; + pjsua_perror(THIS_FILE, "Error sending PUBLISH request", status); + goto on_error; } acc->publish_state = acc->online_status; @@ -1314,8 +1313,8 @@ static pj_status_t send_publish(int acc_id, pj_bool_t active) on_error: if (acc->publish_sess) { - pjsip_publishc_destroy(acc->publish_sess); - acc->publish_sess = NULL; + pjsip_publishc_destroy(acc->publish_sess); + acc->publish_sess = NULL; } pj_log_pop_indent(); return status; @@ -1333,43 +1332,43 @@ pj_status_t pjsua_pres_init_publish_acc(int acc_id) /* Create and init client publication session */ if (acc_cfg->publish_enabled) { - /* Create client publication */ - status = pjsip_publishc_create(pjsua_var.endpt, &acc_cfg->publish_opt, - acc, &publish_cb, - &acc->publish_sess); - if (status != PJ_SUCCESS) { - acc->publish_sess = NULL; - return status; - } - - /* Initialize client publication */ - status = pjsip_publishc_init(acc->publish_sess, &STR_PRESENCE, - &acc_cfg->id, &acc_cfg->id, - &acc_cfg->id, - PJSUA_PUBLISH_EXPIRATION); - if (status != PJ_SUCCESS) { - acc->publish_sess = NULL; - return status; - } - - /* Add credential for authentication */ - if (acc->cred_cnt) { - pjsip_publishc_set_credentials(acc->publish_sess, acc->cred_cnt, - acc->cred); - } - - /* Set route-set */ - pjsip_publishc_set_route_set(acc->publish_sess, &acc->route_set); - - /* Send initial PUBLISH request */ - if (acc->online_status != 0) { - status = send_publish(acc_id, PJ_TRUE); - if (status != PJ_SUCCESS) - return status; - } + /* Create client publication */ + status = pjsip_publishc_create(pjsua_var.endpt, &acc_cfg->publish_opt, + acc, &publish_cb, + &acc->publish_sess); + if (status != PJ_SUCCESS) { + acc->publish_sess = NULL; + return status; + } + + /* Initialize client publication */ + status = pjsip_publishc_init(acc->publish_sess, &STR_PRESENCE, + &acc_cfg->id, &acc_cfg->id, + &acc_cfg->id, + PJSUA_PUBLISH_EXPIRATION); + if (status != PJ_SUCCESS) { + acc->publish_sess = NULL; + return status; + } + + /* Add credential for authentication */ + if (acc->cred_cnt) { + pjsip_publishc_set_credentials(acc->publish_sess, acc->cred_cnt, + acc->cred); + } + + /* Set route-set */ + pjsip_publishc_set_route_set(acc->publish_sess, &acc->route_set); + + /* Send initial PUBLISH request */ + if (acc->online_status != 0) { + status = send_publish(acc_id, PJ_TRUE); + if (status != PJ_SUCCESS) + return status; + } } else { - acc->publish_sess = NULL; + acc->publish_sess = NULL; } return PJ_SUCCESS; @@ -1392,22 +1391,22 @@ pj_status_t pjsua_pres_init_acc(int acc_id) void pjsua_pres_unpublish(pjsua_acc *acc, unsigned flags) { if (acc->publish_sess) { - pjsua_acc_config *acc_cfg = &acc->cfg; + pjsua_acc_config *acc_cfg = &acc->cfg; - acc->online_status = PJ_FALSE; - acc_cfg->publish_enabled = PJ_FALSE; + acc->online_status = PJ_FALSE; + acc_cfg->publish_enabled = PJ_FALSE; - if ((flags & PJSUA_DESTROY_NO_TX_MSG) == 0) { - send_publish(acc->index, PJ_FALSE); - } + if ((flags & PJSUA_DESTROY_NO_TX_MSG) == 0) { + send_publish(acc->index, PJ_FALSE); + } - /* By ticket #364, don't destroy the session yet (let the callback - destroy it) - if (acc->publish_sess) { - pjsip_publishc_destroy(acc->publish_sess); - acc->publish_sess = NULL; - } - */ + /* By ticket #364, don't destroy the session yet (let the callback + destroy it) + if (acc->publish_sess) { + pjsip_publishc_destroy(acc->publish_sess); + acc->publish_sess = NULL; + } + */ } } @@ -1421,31 +1420,31 @@ void pjsua_pres_delete_acc(int acc_id, unsigned flags) /* Notify all subscribers that we're no longer available */ while (uapres != &acc->pres_srv_list) { - - pjsip_pres_status pres_status; - pj_str_t reason = { "noresource", 10 }; - pjsua_srv_pres *next; - pjsip_tx_data *tdata; - - next = uapres->next; - - pjsip_pres_get_status(uapres->sub, &pres_status); - - pres_status.info[0].basic_open = pjsua_var.acc[acc_id].online_status; - pjsip_pres_set_status(uapres->sub, &pres_status); - - if ((flags & PJSUA_DESTROY_NO_TX_MSG) == 0) { - if (pjsip_pres_notify(uapres->sub, - PJSIP_EVSUB_STATE_TERMINATED, NULL, - &reason, &tdata)==PJ_SUCCESS) - { - pjsip_pres_send_request(uapres->sub, tdata); - } - } else { - pjsip_pres_terminate(uapres->sub, PJ_FALSE); - } + + pjsip_pres_status pres_status; + pj_str_t reason = { "noresource", 10 }; + pjsua_srv_pres *next; + pjsip_tx_data *tdata; + + next = uapres->next; + + pjsip_pres_get_status(uapres->sub, &pres_status); + + pres_status.info[0].basic_open = pjsua_var.acc[acc_id].online_status; + pjsip_pres_set_status(uapres->sub, &pres_status); + + if ((flags & PJSUA_DESTROY_NO_TX_MSG) == 0) { + if (pjsip_pres_notify(uapres->sub, + PJSIP_EVSUB_STATE_TERMINATED, NULL, + &reason, &tdata)==PJ_SUCCESS) + { + pjsip_pres_send_request(uapres->sub, tdata); + } + } else { + pjsip_pres_terminate(uapres->sub, PJ_FALSE); + } - uapres = next; + uapres = next; } /* Clear server presence subscription list because account might be reused @@ -1454,7 +1453,7 @@ void pjsua_pres_delete_acc(int acc_id, unsigned flags) /* Terminate presence publication, if any */ if (acc->cfg.publish_enabled) - pjsua_pres_unpublish(acc, flags); + pjsua_pres_unpublish(acc, flags); } @@ -1468,35 +1467,35 @@ void pjsua_pres_update_acc(int acc_id, pj_bool_t force) uapres = pjsua_var.acc[acc_id].pres_srv_list.next; while (uapres != &acc->pres_srv_list) { - - pjsip_pres_status pres_status; - pjsip_tx_data *tdata; - - pjsip_pres_get_status(uapres->sub, &pres_status); - - /* Only send NOTIFY once subscription is active. Some subscriptions - * may still be in NULL (when app is adding a new buddy while in the - * on_incoming_subscribe() callback) or PENDING (when user approval is - * being requested) state and we don't send NOTIFY to these subs until - * the user accepted the request. - */ - if (pjsip_evsub_get_state(uapres->sub)==PJSIP_EVSUB_STATE_ACTIVE && - (force || pres_status.info[0].basic_open != acc->online_status)) - { + + pjsip_pres_status pres_status; + pjsip_tx_data *tdata; + + pjsip_pres_get_status(uapres->sub, &pres_status); + + /* Only send NOTIFY once subscription is active. Some subscriptions + * may still be in NULL (when app is adding a new buddy while in the + * on_incoming_subscribe() callback) or PENDING (when user approval is + * being requested) state and we don't send NOTIFY to these subs until + * the user accepted the request. + */ + if (pjsip_evsub_get_state(uapres->sub)==PJSIP_EVSUB_STATE_ACTIVE && + (force || pres_status.info[0].basic_open != acc->online_status)) + { - pres_status.info[0].basic_open = acc->online_status; - pj_memcpy(&pres_status.info[0].rpid, &acc->rpid, - sizeof(pjrpid_element)); + pres_status.info[0].basic_open = acc->online_status; + pj_memcpy(&pres_status.info[0].rpid, &acc->rpid, + sizeof(pjrpid_element)); - pjsip_pres_set_status(uapres->sub, &pres_status); + pjsip_pres_set_status(uapres->sub, &pres_status); - if (pjsip_pres_current_notify(uapres->sub, &tdata)==PJ_SUCCESS) { - pjsua_process_msg_data(tdata, NULL); - pjsip_pres_send_request(uapres->sub, tdata); - } - } + if (pjsip_pres_current_notify(uapres->sub, &tdata)==PJ_SUCCESS) { + pjsua_process_msg_data(tdata, NULL); + pjsip_pres_send_request(uapres->sub, tdata); + } + } - uapres = uapres->next; + uapres = uapres->next; } /* Send PUBLISH if required. We only do this when we have a PUBLISH @@ -1505,9 +1504,9 @@ void pjsua_pres_update_acc(int acc_id, pj_bool_t force) * send the first PUBLISH. */ if (acc_cfg->publish_enabled && acc->publish_sess) { - if (force || acc->publish_state != acc->online_status) { - send_publish(acc_id, PJ_TRUE); - } + if (force || acc->publish_state != acc->online_status) { + send_publish(acc_id, PJ_TRUE); + } } } @@ -1531,29 +1530,29 @@ static void buddy_timer_cb(pj_timer_heap_t *th, pj_timer_entry *entry) * refresh timer for the specified buddy. */ static void buddy_resubscribe(pjsua_buddy *buddy, pj_bool_t resched, - unsigned msec_interval) + unsigned msec_interval) { if (buddy->timer.id) { - pjsua_cancel_timer(&buddy->timer); - buddy->timer.id = PJ_FALSE; + pjsua_cancel_timer(&buddy->timer); + buddy->timer.id = PJ_FALSE; } if (resched) { - pj_time_val delay; + pj_time_val delay; - PJ_LOG(4,(THIS_FILE, - "Resubscribing buddy id %u in %u ms (reason: %.*s)", - buddy->index, msec_interval, - (int)buddy->term_reason.slen, - buddy->term_reason.ptr)); + PJ_LOG(4,(THIS_FILE, + "Resubscribing buddy id %u in %u ms (reason: %.*s)", + buddy->index, msec_interval, + (int)buddy->term_reason.slen, + buddy->term_reason.ptr)); - pj_timer_entry_init(&buddy->timer, 0, buddy, &buddy_timer_cb); - delay.sec = 0; - delay.msec = msec_interval; - pj_time_val_normalize(&delay); + pj_timer_entry_init(&buddy->timer, 0, buddy, &buddy_timer_cb); + delay.sec = 0; + delay.msec = msec_interval; + pj_time_val_normalize(&delay); - if (pjsua_schedule_timer(&buddy->timer, &delay)==PJ_SUCCESS) - buddy->timer.id = PJ_TRUE; + if (pjsua_schedule_timer(&buddy->timer, &delay)==PJ_SUCCESS) + buddy->timer.id = PJ_TRUE; } } @@ -1570,141 +1569,141 @@ static void pjsua_evsub_on_state( pjsip_evsub *sub, pjsip_event *event) */ buddy = (pjsua_buddy*) pjsip_evsub_get_mod_data(sub, pjsua_var.mod.id); if (buddy) { - PJ_LOG(4,(THIS_FILE, - "Presence subscription to %.*s is %s", - (int)pjsua_var.buddy[buddy->index].uri.slen, - pjsua_var.buddy[buddy->index].uri.ptr, - pjsip_evsub_get_state_name(sub))); - pj_log_push_indent(); - - if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) { - int resub_delay = -1; - - if (buddy->term_reason.ptr == NULL) { - buddy->term_reason.ptr = (char*) - pj_pool_alloc(buddy->pool, - PJSUA_BUDDY_SUB_TERM_REASON_LEN); - } - pj_strncpy(&buddy->term_reason, - pjsip_evsub_get_termination_reason(sub), - PJSUA_BUDDY_SUB_TERM_REASON_LEN); - - buddy->term_code = 200; - - /* Determine whether to resubscribe automatically */ - if (event && event->type==PJSIP_EVENT_TSX_STATE) { - const pjsip_transaction *tsx = event->body.tsx_state.tsx; - if (pjsip_method_cmp(&tsx->method, - pjsip_get_subscribe_method())==0) - { - buddy->term_code = tsx->status_code; - switch (tsx->status_code) { - case PJSIP_SC_CALL_TSX_DOES_NOT_EXIST: - /* 481: we refreshed too late? resubscribe - * immediately. - */ - /* But this must only happen when the 481 is received - * on subscription refresh request. We MUST NOT try to - * resubscribe automatically if the 481 is received - * on the initial SUBSCRIBE (if server returns this - * response for some reason). - */ - if (buddy->dlg->remote.contact) - resub_delay = 500; - break; - } - } else if (pjsip_method_cmp(&tsx->method, - pjsip_get_notify_method())==0) - { - if (pj_stricmp2(&buddy->term_reason, "deactivated")==0 || - pj_stricmp2(&buddy->term_reason, "timeout")==0) { - /* deactivated: The subscription has been terminated, - * but the subscriber SHOULD retry immediately with - * a new subscription. - */ - /* timeout: The subscription has been terminated - * because it was not refreshed before it expired. - * Clients MAY re-subscribe immediately. The - * "retry-after" parameter has no semantics for - * "timeout". - */ - resub_delay = 500; - } - else if (pj_stricmp2(&buddy->term_reason, "probation")==0|| - pj_stricmp2(&buddy->term_reason, "giveup")==0) { - /* probation: The subscription has been terminated, - * but the client SHOULD retry at some later time. - * If a "retry-after" parameter is also present, the - * client SHOULD wait at least the number of seconds - * specified by that parameter before attempting to re- - * subscribe. - */ - /* giveup: The subscription has been terminated because - * the notifier could not obtain authorization in a - * timely fashion. If a "retry-after" parameter is - * also present, the client SHOULD wait at least the - * number of seconds specified by that parameter before - * attempting to re-subscribe; otherwise, the client - * MAY retry immediately, but will likely get put back - * into pending state. - */ - const pjsip_sub_state_hdr *sub_hdr; - pj_str_t sub_state = { "Subscription-State", 18 }; - const pjsip_msg *msg; - - msg = event->body.tsx_state.src.rdata->msg_info.msg; - sub_hdr = (const pjsip_sub_state_hdr*) - pjsip_msg_find_hdr_by_name(msg, &sub_state, - NULL); - if (sub_hdr && sub_hdr->retry_after > 0) - resub_delay = sub_hdr->retry_after * 1000; - } - - } - } - - /* For other cases of subscription termination, if resubscribe - * timer is not set, schedule with default expiration (plus minus - * some random value, to avoid sending SUBSCRIBEs all at once) - */ - if (resub_delay == -1) { - pj_assert(PJSUA_PRES_TIMER >= 3); - resub_delay = PJSUA_PRES_TIMER*1000 - 2500 + (pj_rand()%5000); - } - - buddy_resubscribe(buddy, PJ_TRUE, resub_delay); - - } else { - /* This will clear the last termination code/reason */ - buddy->term_code = 0; - buddy->term_reason.slen = 0; - } - - /* Call callbacks */ - if (pjsua_var.ua_cfg.cb.on_buddy_evsub_state) - (*pjsua_var.ua_cfg.cb.on_buddy_evsub_state)(buddy->index, sub, - event); - - if (pjsua_var.ua_cfg.cb.on_buddy_state) - (*pjsua_var.ua_cfg.cb.on_buddy_state)(buddy->index); - - /* Clear subscription */ - if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) { - buddy->sub = NULL; - buddy->status.info_cnt = 0; - buddy->dlg = NULL; - pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); - } - - pj_log_pop_indent(); + PJ_LOG(4,(THIS_FILE, + "Presence subscription to %.*s is %s", + (int)pjsua_var.buddy[buddy->index].uri.slen, + pjsua_var.buddy[buddy->index].uri.ptr, + pjsip_evsub_get_state_name(sub))); + pj_log_push_indent(); + + if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) { + int resub_delay = -1; + + if (buddy->term_reason.ptr == NULL) { + buddy->term_reason.ptr = (char*) + pj_pool_alloc(buddy->pool, + PJSUA_BUDDY_SUB_TERM_REASON_LEN); + } + pj_strncpy(&buddy->term_reason, + pjsip_evsub_get_termination_reason(sub), + PJSUA_BUDDY_SUB_TERM_REASON_LEN); + + buddy->term_code = 200; + + /* Determine whether to resubscribe automatically */ + if (event && event->type==PJSIP_EVENT_TSX_STATE) { + const pjsip_transaction *tsx = event->body.tsx_state.tsx; + if (pjsip_method_cmp(&tsx->method, + pjsip_get_subscribe_method())==0) + { + buddy->term_code = tsx->status_code; + switch (tsx->status_code) { + case PJSIP_SC_CALL_TSX_DOES_NOT_EXIST: + /* 481: we refreshed too late? resubscribe + * immediately. + */ + /* But this must only happen when the 481 is received + * on subscription refresh request. We MUST NOT try to + * resubscribe automatically if the 481 is received + * on the initial SUBSCRIBE (if server returns this + * response for some reason). + */ + if (buddy->dlg->remote.contact) + resub_delay = 500; + break; + } + } else if (pjsip_method_cmp(&tsx->method, + pjsip_get_notify_method())==0) + { + if (pj_stricmp2(&buddy->term_reason, "deactivated")==0 || + pj_stricmp2(&buddy->term_reason, "timeout")==0) { + /* deactivated: The subscription has been terminated, + * but the subscriber SHOULD retry immediately with + * a new subscription. + */ + /* timeout: The subscription has been terminated + * because it was not refreshed before it expired. + * Clients MAY re-subscribe immediately. The + * "retry-after" parameter has no semantics for + * "timeout". + */ + resub_delay = 500; + } + else if (pj_stricmp2(&buddy->term_reason, "probation")==0|| + pj_stricmp2(&buddy->term_reason, "giveup")==0) { + /* probation: The subscription has been terminated, + * but the client SHOULD retry at some later time. + * If a "retry-after" parameter is also present, the + * client SHOULD wait at least the number of seconds + * specified by that parameter before attempting to re- + * subscribe. + */ + /* giveup: The subscription has been terminated because + * the notifier could not obtain authorization in a + * timely fashion. If a "retry-after" parameter is + * also present, the client SHOULD wait at least the + * number of seconds specified by that parameter before + * attempting to re-subscribe; otherwise, the client + * MAY retry immediately, but will likely get put back + * into pending state. + */ + const pjsip_sub_state_hdr *sub_hdr; + pj_str_t sub_state = { "Subscription-State", 18 }; + const pjsip_msg *msg; + + msg = event->body.tsx_state.src.rdata->msg_info.msg; + sub_hdr = (const pjsip_sub_state_hdr*) + pjsip_msg_find_hdr_by_name(msg, &sub_state, + NULL); + if (sub_hdr && sub_hdr->retry_after > 0) + resub_delay = sub_hdr->retry_after * 1000; + } + + } + } + + /* For other cases of subscription termination, if resubscribe + * timer is not set, schedule with default expiration (plus minus + * some random value, to avoid sending SUBSCRIBEs all at once) + */ + if (resub_delay == -1) { + pj_assert(PJSUA_PRES_TIMER >= 3); + resub_delay = PJSUA_PRES_TIMER*1000 - 2500 + (pj_rand()%5000); + } + + buddy_resubscribe(buddy, PJ_TRUE, resub_delay); + + } else { + /* This will clear the last termination code/reason */ + buddy->term_code = 0; + buddy->term_reason.slen = 0; + } + + /* Call callbacks */ + if (pjsua_var.ua_cfg.cb.on_buddy_evsub_state) + (*pjsua_var.ua_cfg.cb.on_buddy_evsub_state)(buddy->index, sub, + event); + + if (pjsua_var.ua_cfg.cb.on_buddy_state) + (*pjsua_var.ua_cfg.cb.on_buddy_state)(buddy->index); + + /* Clear subscription */ + if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) { + buddy->sub = NULL; + buddy->status.info_cnt = 0; + buddy->dlg = NULL; + pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); + } + + pj_log_pop_indent(); } } /* Callback when transaction state has changed. */ static void pjsua_evsub_on_tsx_state(pjsip_evsub *sub, - pjsip_transaction *tsx, - pjsip_event *event) + pjsip_transaction *tsx, + pjsip_event *event) { pjsua_buddy *buddy; pjsip_contact_hdr *contact_hdr; @@ -1715,52 +1714,52 @@ static void pjsua_evsub_on_tsx_state(pjsip_evsub *sub, */ buddy = (pjsua_buddy*) pjsip_evsub_get_mod_data(sub, pjsua_var.mod.id); if (!buddy) { - return; + return; } /* We only use this to update buddy's Contact, when it's not * set. */ if (buddy->contact.slen != 0) { - /* Contact already set */ - return; + /* Contact already set */ + return; } /* Only care about 2xx response to outgoing SUBSCRIBE */ if (tsx->status_code/100 != 2 || - tsx->role != PJSIP_UAC_ROLE || - event->type != PJSIP_EVENT_RX_MSG || - pjsip_method_cmp(&tsx->method, pjsip_get_subscribe_method())!=0) + tsx->role != PJSIP_UAC_ROLE || + event->type != PJSIP_EVENT_RX_MSG || + pjsip_method_cmp(&tsx->method, pjsip_get_subscribe_method())!=0) { - return; + return; } /* Find contact header. */ contact_hdr = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(event->body.rx_msg.rdata->msg_info.msg, - PJSIP_H_CONTACT, NULL); + pjsip_msg_find_hdr(event->body.rx_msg.rdata->msg_info.msg, + PJSIP_H_CONTACT, NULL); if (!contact_hdr || !contact_hdr->uri) { - return; + return; } buddy->contact.ptr = (char*) - pj_pool_alloc(buddy->pool, PJSIP_MAX_URL_SIZE); + pj_pool_alloc(buddy->pool, PJSIP_MAX_URL_SIZE); buddy->contact.slen = pjsip_uri_print( PJSIP_URI_IN_CONTACT_HDR, - contact_hdr->uri, - buddy->contact.ptr, - PJSIP_MAX_URL_SIZE); + contact_hdr->uri, + buddy->contact.ptr, + PJSIP_MAX_URL_SIZE); if (buddy->contact.slen < 0) - buddy->contact.slen = 0; + buddy->contact.slen = 0; } /* Callback called when we receive NOTIFY */ static void pjsua_evsub_on_rx_notify(pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body) + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body) { pjsua_buddy *buddy; @@ -1770,8 +1769,8 @@ static void pjsua_evsub_on_rx_notify(pjsip_evsub *sub, */ buddy = (pjsua_buddy*) pjsip_evsub_get_mod_data(sub, pjsua_var.mod.id); if (buddy) { - /* Update our info. */ - pjsip_pres_get_status(sub, &buddy->status); + /* Update our info. */ + pjsip_pres_get_status(sub, &buddy->status); } /* The default is to send 200 response to NOTIFY. @@ -1809,40 +1808,40 @@ static void subscribe_buddy_presence(pjsua_buddy_id buddy_id) acc = &pjsua_var.acc[acc_id]; PJ_LOG(4,(THIS_FILE, "Buddy %d: subscribing presence,using account %d..", - buddy_id, acc_id)); + buddy_id, acc_id)); pj_log_push_indent(); /* Generate suitable Contact header unless one is already set in * the account */ if (acc->contact.slen) { - contact = acc->contact; + contact = acc->contact; } else { - tmp_pool = pjsua_pool_create("tmpbuddy", 512, 256); - - status = pjsua_acc_create_uac_contact(tmp_pool, &contact, - acc_id, &buddy->uri); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to generate Contact header", - status); - pj_pool_release(tmp_pool); - pj_log_pop_indent(); - return; - } + tmp_pool = pjsua_pool_create("tmpbuddy", 512, 256); + + status = pjsua_acc_create_uac_contact(tmp_pool, &contact, + acc_id, &buddy->uri); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to generate Contact header", + status); + pj_pool_release(tmp_pool); + pj_log_pop_indent(); + return; + } } /* Create UAC dialog */ status = pjsip_dlg_create_uac( pjsip_ua_instance(), - &acc->cfg.id, - &contact, - &buddy->uri, - NULL, &buddy->dlg); + &acc->cfg.id, + &contact, + &buddy->uri, + NULL, &buddy->dlg); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create dialog", - status); - if (tmp_pool) pj_pool_release(tmp_pool); - pj_log_pop_indent(); - return; + pjsua_perror(THIS_FILE, "Unable to create dialog", + status); + if (tmp_pool) pj_pool_release(tmp_pool); + pj_log_pop_indent(); + return; } /* Increment the dialog's lock otherwise when presence session creation @@ -1853,58 +1852,58 @@ static void subscribe_buddy_presence(pjsua_buddy_id buddy_id) if (acc->cfg.allow_via_rewrite && acc->via_addr.host.slen > 0) { pjsip_dlg_set_via_sent_by(buddy->dlg, &acc->via_addr, acc->via_tp); } else if (!pjsua_sip_acc_is_using_stun(acc_id) && - !pjsua_sip_acc_is_using_upnp(acc_id)) + !pjsua_sip_acc_is_using_upnp(acc_id)) { - /* Choose local interface to use in Via if acc is not using - * STUN nor UPnP. See https://github.com/pjsip/pjproject/issues/1412 - */ - pjsip_host_port via_addr; - const void *via_tp; - - if (pjsua_acc_get_uac_addr(acc_id, buddy->dlg->pool, &buddy->uri, - &via_addr, NULL, NULL, - &via_tp) == PJ_SUCCESS) + /* Choose local interface to use in Via if acc is not using + * STUN nor UPnP. See https://github.com/pjsip/pjproject/issues/1412 + */ + pjsip_host_port via_addr; + const void *via_tp; + + if (pjsua_acc_get_uac_addr(acc_id, buddy->dlg->pool, &buddy->uri, + &via_addr, NULL, NULL, + &via_tp) == PJ_SUCCESS) { - pjsip_dlg_set_via_sent_by(buddy->dlg, &via_addr, - (pjsip_transport*)via_tp); + pjsip_dlg_set_via_sent_by(buddy->dlg, &via_addr, + (pjsip_transport*)via_tp); } } status = pjsip_pres_create_uac( buddy->dlg, &pres_callback, - PJSIP_EVSUB_NO_EVENT_ID, &buddy->sub); + PJSIP_EVSUB_NO_EVENT_ID, &buddy->sub); if (status != PJ_SUCCESS) { - buddy->sub = NULL; - pjsua_perror(THIS_FILE, "Unable to create presence client", - status); - /* This should destroy the dialog since there's no session - * referencing it - */ - if (buddy->dlg) pjsip_dlg_dec_lock(buddy->dlg); - if (tmp_pool) pj_pool_release(tmp_pool); - pj_log_pop_indent(); - return; + buddy->sub = NULL; + pjsua_perror(THIS_FILE, "Unable to create presence client", + status); + /* This should destroy the dialog since there's no session + * referencing it + */ + if (buddy->dlg) pjsip_dlg_dec_lock(buddy->dlg); + if (tmp_pool) pj_pool_release(tmp_pool); + pj_log_pop_indent(); + return; } /* If account is locked to specific transport, then lock dialog * to this transport too. */ if (acc->cfg.transport_id != PJSUA_INVALID_ID) { - pjsip_tpselector tp_sel; + pjsip_tpselector tp_sel; - pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); - pjsip_dlg_set_transport(buddy->dlg, &tp_sel); + pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); + pjsip_dlg_set_transport(buddy->dlg, &tp_sel); } /* Set route-set */ if (!pj_list_empty(&acc->route_set)) { - pjsip_dlg_set_route_set(buddy->dlg, &acc->route_set); + pjsip_dlg_set_route_set(buddy->dlg, &acc->route_set); } /* Set credentials */ if (acc->cred_cnt) { - pjsip_auth_clt_set_credentials( &buddy->dlg->auth_sess, - acc->cred_cnt, acc->cred); + pjsip_auth_clt_set_credentials( &buddy->dlg->auth_sess, + acc->cred_cnt, acc->cred); } /* Set authentication preference */ @@ -1914,34 +1913,34 @@ static void subscribe_buddy_presence(pjsua_buddy_id buddy_id) pjsip_evsub_set_mod_data(buddy->sub, pjsua_var.mod.id, buddy); status = pjsip_pres_initiate(buddy->sub, PJSIP_EXPIRES_NOT_SPECIFIED, - &tdata); + &tdata); if (status != PJ_SUCCESS) { - if (buddy->dlg) pjsip_dlg_dec_lock(buddy->dlg); - if (buddy->sub) { - pjsip_pres_terminate(buddy->sub, PJ_FALSE); - } - buddy->sub = NULL; - pjsua_perror(THIS_FILE, "Unable to create initial SUBSCRIBE", - status); - if (tmp_pool) pj_pool_release(tmp_pool); - pj_log_pop_indent(); - return; + if (buddy->dlg) pjsip_dlg_dec_lock(buddy->dlg); + if (buddy->sub) { + pjsip_pres_terminate(buddy->sub, PJ_FALSE); + } + buddy->sub = NULL; + pjsua_perror(THIS_FILE, "Unable to create initial SUBSCRIBE", + status); + if (tmp_pool) pj_pool_release(tmp_pool); + pj_log_pop_indent(); + return; } pjsua_process_msg_data(tdata, NULL); status = pjsip_pres_send_request(buddy->sub, tdata); if (status != PJ_SUCCESS) { - if (buddy->dlg) pjsip_dlg_dec_lock(buddy->dlg); - if (buddy->sub) { - pjsip_pres_terminate(buddy->sub, PJ_FALSE); - } - buddy->sub = NULL; - pjsua_perror(THIS_FILE, "Unable to send initial SUBSCRIBE", - status); - if (tmp_pool) pj_pool_release(tmp_pool); - pj_log_pop_indent(); - return; + if (buddy->dlg) pjsip_dlg_dec_lock(buddy->dlg); + if (buddy->sub) { + pjsip_pres_terminate(buddy->sub, PJ_FALSE); + } + buddy->sub = NULL; + pjsua_perror(THIS_FILE, "Unable to send initial SUBSCRIBE", + status); + if (tmp_pool) pj_pool_release(tmp_pool); + pj_log_pop_indent(); + return; } pjsip_dlg_dec_lock(buddy->dlg); @@ -1960,11 +1959,11 @@ static void unsubscribe_buddy_presence(pjsua_buddy_id buddy_id) buddy = &pjsua_var.buddy[buddy_id]; if (buddy->sub == NULL) - return; + return; if (pjsip_evsub_get_state(buddy->sub) == PJSIP_EVSUB_STATE_TERMINATED) { - buddy->sub = NULL; - return; + buddy->sub = NULL; + return; } PJ_LOG(5,(THIS_FILE, "Buddy %d: unsubscribing..", buddy_id)); @@ -1972,15 +1971,15 @@ static void unsubscribe_buddy_presence(pjsua_buddy_id buddy_id) status = pjsip_pres_initiate( buddy->sub, 0, &tdata); if (status == PJ_SUCCESS) { - pjsua_process_msg_data(tdata, NULL); - status = pjsip_pres_send_request( buddy->sub, tdata ); + pjsua_process_msg_data(tdata, NULL); + status = pjsip_pres_send_request( buddy->sub, tdata ); } if (status != PJ_SUCCESS && buddy->sub) { - pjsip_pres_terminate(buddy->sub, PJ_FALSE); - buddy->sub = NULL; - pjsua_perror(THIS_FILE, "Unable to unsubscribe presence", - status); + pjsip_pres_terminate(buddy->sub, PJ_FALSE); + buddy->sub = NULL; + pjsua_perror(THIS_FILE, "Unable to unsubscribe presence", + status); } pj_log_pop_indent(); @@ -1993,24 +1992,24 @@ static pj_status_t refresh_client_subscriptions(void) pj_status_t status; for (i=0; icfg.id.slen, acc->cfg.id.ptr, - pjsip_evsub_get_state_name(sub))); + "MWI subscription for %.*s is %s", + (int)acc->cfg.id.slen, acc->cfg.id.ptr, + pjsip_evsub_get_state_name(sub))); /* Call callback */ if (pjsua_var.ua_cfg.cb.on_mwi_state) { - (*pjsua_var.ua_cfg.cb.on_mwi_state)(acc->index, sub); + (*pjsua_var.ua_cfg.cb.on_mwi_state)(acc->index, sub); } if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) { - /* Clear subscription */ - acc->mwi_dlg = NULL; - acc->mwi_sub = NULL; - pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); + /* Clear subscription */ + acc->mwi_dlg = NULL; + acc->mwi_sub = NULL; + pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); } } /* Callback called when we receive NOTIFY */ static void mwi_evsub_on_rx_notify(pjsip_evsub *sub, - pjsip_rx_data *rdata, - int *p_st_code, - pj_str_t **p_st_text, - pjsip_hdr *res_hdr, - pjsip_msg_body **p_body) + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body) { pjsua_mwi_info mwi_info; pjsua_acc *acc; @@ -2071,7 +2070,7 @@ static void mwi_evsub_on_rx_notify(pjsip_evsub *sub, acc = (pjsua_acc*) pjsip_evsub_get_mod_data(sub, pjsua_var.mod.id); if (!acc) - return; + return; /* Construct mwi_info */ pj_bzero(&mwi_info, sizeof(mwi_info)); @@ -2083,7 +2082,7 @@ static void mwi_evsub_on_rx_notify(pjsip_evsub *sub, /* Call callback */ if (pjsua_var.ua_cfg.cb.on_mwi_info) { - (*pjsua_var.ua_cfg.cb.on_mwi_info)(acc->index, &mwi_info); + (*pjsua_var.ua_cfg.cb.on_mwi_info)(acc->index, &mwi_info); } pj_log_pop_indent(); @@ -2096,17 +2095,17 @@ static pjsip_evsub_user mwi_cb = &mwi_evsub_on_state, NULL, /* on_tsx_state: not interested */ NULL, /* on_rx_refresh: don't care about SUBSCRIBE refresh, unless - * we want to authenticate - */ + * we want to authenticate + */ &mwi_evsub_on_rx_notify, NULL, /* on_client_refresh: Use default behaviour, which is to - * refresh client subscription. */ + * refresh client subscription. */ NULL, /* on_server_timeout: Use default behaviour, which is to send - * NOTIFY to terminate. - */ + * NOTIFY to terminate. + */ }; pj_status_t pjsua_start_mwi(pjsua_acc_id acc_id, pj_bool_t force_renew) @@ -2123,41 +2122,41 @@ pj_status_t pjsua_start_mwi(pjsua_acc_id acc_id, pj_bool_t force_renew) acc = &pjsua_var.acc[acc_id]; if (!acc->cfg.mwi_enabled || !acc->regc) { - if (acc->mwi_sub) { - /* Terminate MWI subscription */ - pjsip_evsub *sub = acc->mwi_sub; - - /* Detach sub from this account */ - acc->mwi_sub = NULL; - acc->mwi_dlg = NULL; - pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); - - /* Unsubscribe */ - status = pjsip_mwi_initiate(sub, 0, &tdata); - if (status == PJ_SUCCESS) { - status = pjsip_mwi_send_request(sub, tdata); - } - } - return status; + if (acc->mwi_sub) { + /* Terminate MWI subscription */ + pjsip_evsub *sub = acc->mwi_sub; + + /* Detach sub from this account */ + acc->mwi_sub = NULL; + acc->mwi_dlg = NULL; + pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); + + /* Unsubscribe */ + status = pjsip_mwi_initiate(sub, 0, &tdata); + if (status == PJ_SUCCESS) { + status = pjsip_mwi_send_request(sub, tdata); + } + } + return status; } /* Subscription is already active */ if (acc->mwi_sub) { - if (!force_renew) - return PJ_SUCCESS; - - /* Update MWI subscription */ - pj_assert(acc->mwi_dlg); - pjsip_dlg_inc_lock(acc->mwi_dlg); - - status = pjsip_mwi_initiate(acc->mwi_sub, acc->cfg.mwi_expires, &tdata); - if (status == PJ_SUCCESS) { - pjsua_process_msg_data(tdata, NULL); - status = pjsip_pres_send_request(acc->mwi_sub, tdata); - } - - pjsip_dlg_dec_lock(acc->mwi_dlg); - return status; + if (!force_renew) + return PJ_SUCCESS; + + /* Update MWI subscription */ + pj_assert(acc->mwi_dlg); + pjsip_dlg_inc_lock(acc->mwi_dlg); + + status = pjsip_mwi_initiate(acc->mwi_sub, acc->cfg.mwi_expires, &tdata); + if (status == PJ_SUCCESS) { + pjsua_process_msg_data(tdata, NULL); + status = pjsip_pres_send_request(acc->mwi_sub, tdata); + } + + pjsip_dlg_dec_lock(acc->mwi_dlg); + return status; } PJ_LOG(4,(THIS_FILE, "Starting MWI subscription..")); @@ -2167,27 +2166,27 @@ pj_status_t pjsua_start_mwi(pjsua_acc_id acc_id, pj_bool_t force_renew) * the account */ if (acc->contact.slen) { - contact = acc->contact; + contact = acc->contact; } else { - tmp_pool = pjsua_pool_create("tmpmwi", 512, 256); - status = pjsua_acc_create_uac_contact(tmp_pool, &contact, - acc->index, &acc->cfg.id); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to generate Contact header", - status); - goto on_return; - } + tmp_pool = pjsua_pool_create("tmpmwi", 512, 256); + status = pjsua_acc_create_uac_contact(tmp_pool, &contact, + acc->index, &acc->cfg.id); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, "Unable to generate Contact header", + status); + goto on_return; + } } /* Create UAC dialog */ status = pjsip_dlg_create_uac( pjsip_ua_instance(), - &acc->cfg.id, - &contact, - &acc->cfg.id, - NULL, &acc->mwi_dlg); + &acc->cfg.id, + &contact, + &acc->cfg.id, + NULL, &acc->mwi_dlg); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create dialog", status); - goto on_return; + pjsua_perror(THIS_FILE, "Unable to create dialog", status); + goto on_return; } /* Increment the dialog's lock otherwise when presence session creation @@ -2198,51 +2197,51 @@ pj_status_t pjsua_start_mwi(pjsua_acc_id acc_id, pj_bool_t force_renew) if (acc->cfg.allow_via_rewrite && acc->via_addr.host.slen > 0) { pjsip_dlg_set_via_sent_by(acc->mwi_dlg, &acc->via_addr, acc->via_tp); } else if (!pjsua_sip_acc_is_using_stun(acc_id) && - !pjsua_sip_acc_is_using_upnp(acc_id)) + !pjsua_sip_acc_is_using_upnp(acc_id)) { - /* Choose local interface to use in Via if acc is not using - * STUN nor UPnP. See https://github.com/pjsip/pjproject/issues/1412 - */ - pjsip_host_port via_addr; - const void *via_tp; - - if (pjsua_acc_get_uac_addr(acc_id, acc->mwi_dlg->pool, &acc->cfg.id, - &via_addr, NULL, NULL, - &via_tp) == PJ_SUCCESS) - { - pjsip_dlg_set_via_sent_by(acc->mwi_dlg, &via_addr, - (pjsip_transport*)via_tp); - } + /* Choose local interface to use in Via if acc is not using + * STUN nor UPnP. See https://github.com/pjsip/pjproject/issues/1412 + */ + pjsip_host_port via_addr; + const void *via_tp; + + if (pjsua_acc_get_uac_addr(acc_id, acc->mwi_dlg->pool, &acc->cfg.id, + &via_addr, NULL, NULL, + &via_tp) == PJ_SUCCESS) + { + pjsip_dlg_set_via_sent_by(acc->mwi_dlg, &via_addr, + (pjsip_transport*)via_tp); + } } /* Create UAC subscription */ status = pjsip_mwi_create_uac(acc->mwi_dlg, &mwi_cb, - PJSIP_EVSUB_NO_EVENT_ID, &acc->mwi_sub); + PJSIP_EVSUB_NO_EVENT_ID, &acc->mwi_sub); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating MWI subscription", status); - if (acc->mwi_dlg) pjsip_dlg_dec_lock(acc->mwi_dlg); - goto on_return; + pjsua_perror(THIS_FILE, "Error creating MWI subscription", status); + if (acc->mwi_dlg) pjsip_dlg_dec_lock(acc->mwi_dlg); + goto on_return; } /* If account is locked to specific transport, then lock dialog * to this transport too. */ if (acc->cfg.transport_id != PJSUA_INVALID_ID) { - pjsip_tpselector tp_sel; + pjsip_tpselector tp_sel; - pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); - pjsip_dlg_set_transport(acc->mwi_dlg, &tp_sel); + pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel); + pjsip_dlg_set_transport(acc->mwi_dlg, &tp_sel); } /* Set route-set */ if (!pj_list_empty(&acc->route_set)) { - pjsip_dlg_set_route_set(acc->mwi_dlg, &acc->route_set); + pjsip_dlg_set_route_set(acc->mwi_dlg, &acc->route_set); } /* Set credentials */ if (acc->cred_cnt) { - pjsip_auth_clt_set_credentials( &acc->mwi_dlg->auth_sess, - acc->cred_cnt, acc->cred); + pjsip_auth_clt_set_credentials( &acc->mwi_dlg->auth_sess, + acc->cred_cnt, acc->cred); } /* Set authentication preference */ @@ -2252,30 +2251,30 @@ pj_status_t pjsua_start_mwi(pjsua_acc_id acc_id, pj_bool_t force_renew) status = pjsip_mwi_initiate(acc->mwi_sub, acc->cfg.mwi_expires, &tdata); if (status != PJ_SUCCESS) { - if (acc->mwi_dlg) pjsip_dlg_dec_lock(acc->mwi_dlg); - if (acc->mwi_sub) { - pjsip_pres_terminate(acc->mwi_sub, PJ_FALSE); - } - acc->mwi_sub = NULL; - acc->mwi_dlg = NULL; - pjsua_perror(THIS_FILE, "Unable to create initial MWI SUBSCRIBE", - status); - goto on_return; + if (acc->mwi_dlg) pjsip_dlg_dec_lock(acc->mwi_dlg); + if (acc->mwi_sub) { + pjsip_pres_terminate(acc->mwi_sub, PJ_FALSE); + } + acc->mwi_sub = NULL; + acc->mwi_dlg = NULL; + pjsua_perror(THIS_FILE, "Unable to create initial MWI SUBSCRIBE", + status); + goto on_return; } pjsua_process_msg_data(tdata, NULL); status = pjsip_pres_send_request(acc->mwi_sub, tdata); if (status != PJ_SUCCESS) { - if (acc->mwi_dlg) pjsip_dlg_dec_lock(acc->mwi_dlg); - if (acc->mwi_sub) { - pjsip_pres_terminate(acc->mwi_sub, PJ_FALSE); - } - acc->mwi_sub = NULL; - acc->mwi_dlg = NULL; - pjsua_perror(THIS_FILE, "Unable to send initial MWI SUBSCRIBE", - status); - goto on_return; + if (acc->mwi_dlg) pjsip_dlg_dec_lock(acc->mwi_dlg); + if (acc->mwi_sub) { + pjsip_pres_terminate(acc->mwi_sub, PJ_FALSE); + } + acc->mwi_sub = NULL; + acc->mwi_dlg = NULL; + pjsua_perror(THIS_FILE, "Unable to send initial MWI SUBSCRIBE", + status); + goto on_return; } pjsip_dlg_dec_lock(acc->mwi_dlg); @@ -2300,41 +2299,41 @@ static pj_bool_t unsolicited_mwi_on_rx_request(pjsip_rx_data *rdata) if (pjsip_method_cmp(&msg->line.req.method, pjsip_get_notify_method())!=0) { - /* Only interested with NOTIFY request */ - return PJ_FALSE; + /* Only interested with NOTIFY request */ + return PJ_FALSE; } eh = (pjsip_event_hdr*) pjsip_msg_find_hdr_by_name(msg, &EVENT_HDR, NULL); if (!eh) { - /* Something wrong with the request, it has no Event hdr */ - return PJ_FALSE; + /* Something wrong with the request, it has no Event hdr */ + return PJ_FALSE; } if (pj_stricmp(&eh->event_type, &MWI) != 0) { - /* Not MWI event */ - return PJ_FALSE; + /* Not MWI event */ + return PJ_FALSE; } PJ_LOG(4,(THIS_FILE, "Got unsolicited NOTIFY from %s:%d..", - rdata->pkt_info.src_name, rdata->pkt_info.src_port)); + rdata->pkt_info.src_name, rdata->pkt_info.src_port)); pj_log_push_indent(); /* Got unsolicited MWI request, respond with 200/OK first */ pjsip_endpt_respond(pjsua_get_pjsip_endpt(), NULL, rdata, 200, NULL, - NULL, NULL, NULL); + NULL, NULL, NULL); /* Call callback */ if (pjsua_var.ua_cfg.cb.on_mwi_info) { - pjsua_acc_id acc_id; - pjsua_mwi_info mwi_info; + pjsua_acc_id acc_id; + pjsua_mwi_info mwi_info; - acc_id = pjsua_acc_find_for_incoming(rdata); + acc_id = pjsua_acc_find_for_incoming(rdata); - pj_bzero(&mwi_info, sizeof(mwi_info)); - mwi_info.rdata = rdata; + pj_bzero(&mwi_info, sizeof(mwi_info)); + mwi_info.rdata = rdata; - (*pjsua_var.ua_cfg.cb.on_mwi_info)(acc_id, &mwi_info); + (*pjsua_var.ua_cfg.cb.on_mwi_info)(acc_id, &mwi_info); } pj_log_pop_indent(); @@ -2344,19 +2343,19 @@ static pj_bool_t unsolicited_mwi_on_rx_request(pjsip_rx_data *rdata) /* The module instance. */ static pjsip_module pjsua_unsolicited_mwi_mod = { - NULL, NULL, /* prev, next. */ - { "mod-unsolicited-mwi", 19 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &unsolicited_mwi_on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-unsolicited-mwi", 19 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &unsolicited_mwi_on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; static pj_status_t enable_unsolicited_mwi(void) @@ -2364,10 +2363,10 @@ static pj_status_t enable_unsolicited_mwi(void) pj_status_t status; status = pjsip_endpt_register_module(pjsua_get_pjsip_endpt(), - &pjsua_unsolicited_mwi_mod); + &pjsua_unsolicited_mwi_mod); if (status != PJ_SUCCESS) - pjsua_perror(THIS_FILE, "Error registering unsolicited MWI module", - status); + pjsua_perror(THIS_FILE, "Error registering unsolicited MWI module", + status); return status; } @@ -2378,7 +2377,7 @@ static pj_status_t enable_unsolicited_mwi(void) /* Timer callback to re-create client subscription */ static void pres_timer_cb(pj_timer_heap_t *th, - pj_timer_entry *entry) + pj_timer_entry *entry) { unsigned i; pj_time_val delay = { PJSUA_PRES_TIMER, 0 }; @@ -2387,19 +2386,19 @@ static void pres_timer_cb(pj_timer_heap_t *th, /* Retry failed PUBLISH and MWI SUBSCRIBE requests */ for (i=0; icfg.publish_enabled && acc->publish_sess==NULL) - pjsua_pres_init_publish_acc(acc->index); + /* Retry PUBLISH */ + if (acc->cfg.publish_enabled && acc->publish_sess==NULL) + pjsua_pres_init_publish_acc(acc->index); - /* Re-subscribe MWI subscription if it's terminated prematurely */ - if (acc->cfg.mwi_enabled && !acc->mwi_sub) - pjsua_start_mwi(acc->index, PJ_FALSE); + /* Re-subscribe MWI subscription if it's terminated prematurely */ + if (acc->cfg.mwi_enabled && !acc->mwi_sub) + pjsua_start_mwi(acc->index, PJ_FALSE); } /* #937: No need to do bulk client refresh, as buddies have their @@ -2424,12 +2423,12 @@ pj_status_t pjsua_pres_init() status = pjsip_endpt_register_module( pjsua_var.endpt, &mod_pjsua_pres); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to register pjsua presence module", - status); + pjsua_perror(THIS_FILE, "Unable to register pjsua presence module", + status); } for (i=0; ivp_cap); - status = pjmedia_vid_dev_stream_set_cap(cap_dev, cap, pval); - if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - return status; - } + status = pjmedia_vid_dev_stream_set_cap(cap_dev, cap, pval); + if (status != PJ_SUCCESS) { + PJSUA_UNLOCK(); + return status; + } } else { - status = PJ_ENOTFOUND; + status = PJ_ENOTFOUND; } PJSUA_UNLOCK(); if (keep) { - pjmedia_vid_dev_info info; - - status = pjmedia_vid_dev_get_info(id, &info); - if (status != PJ_SUCCESS || (info.dir & PJMEDIA_DIR_CAPTURE) == 0) - return status; - + pjmedia_vid_dev_info info; + + status = pjmedia_vid_dev_get_info(id, &info); + if (status != PJ_SUCCESS || (info.dir & PJMEDIA_DIR_CAPTURE) == 0) + return status; + /* Get real capture ID, if set to PJMEDIA_VID_DEFAULT_CAPTURE_DEV */ - id = info.id; - status = pjmedia_vid_dev_param_set_cap(&pjsua_var.vid_param[id], - cap, pval); - if (status == PJ_SUCCESS) { + id = info.id; + status = pjmedia_vid_dev_param_set_cap(&pjsua_var.vid_param[id], + cap, pval); + if (status == PJ_SUCCESS) { pjsua_var.vid_caps[id] |= cap; - } + } } return status; @@ -345,8 +344,8 @@ PJ_DEF(pj_status_t) pjsua_vid_dev_set_setting( pjmedia_vid_dev_index id, * Get the value of the video device capability. */ PJ_DEF(pj_status_t) pjsua_vid_dev_get_setting( pjmedia_vid_dev_index id, - pjmedia_vid_dev_cap cap, - void *pval) + pjmedia_vid_dev_cap cap, + void *pval) { pj_status_t status = PJ_SUCCESS; pjsua_vid_win_id wid; @@ -360,27 +359,27 @@ PJ_DEF(pj_status_t) pjsua_vid_dev_get_setting( pjmedia_vid_dev_index id, w = &pjsua_var.win[wid]; cap_dev = pjmedia_vid_port_get_stream(w->vp_cap); - status = pjmedia_vid_dev_stream_get_cap(cap_dev, cap, pval); - - PJSUA_UNLOCK(); + status = pjmedia_vid_dev_stream_get_cap(cap_dev, cap, pval); + + PJSUA_UNLOCK(); } else { - pjmedia_vid_dev_info info; - - PJSUA_UNLOCK(); - - status = pjmedia_vid_dev_get_info(id, &info); - if (status != PJ_SUCCESS) - return status; - + pjmedia_vid_dev_info info; + + PJSUA_UNLOCK(); + + status = pjmedia_vid_dev_get_info(id, &info); + if (status != PJ_SUCCESS) + return status; + /* Get real device ID, if set to default device */ - id = info.id; + id = info.id; if ((pjsua_var.vid_caps[id] & cap) != 0) { status = pjmedia_vid_dev_param_get_cap(&pjsua_var.vid_param[id], - cap, pval); + cap, pval); } else { - status = PJ_ENOTFOUND; - } + status = PJ_ENOTFOUND; + } } return status; @@ -390,7 +389,7 @@ PJ_DEF(pj_status_t) pjsua_vid_dev_get_setting( pjmedia_vid_dev_index id, * Enum all video devices installed in the system. */ PJ_DEF(pj_status_t) pjsua_vid_enum_devs(pjmedia_vid_dev_info info[], - unsigned *count) + unsigned *count) { unsigned i, dev_count; @@ -399,11 +398,11 @@ PJ_DEF(pj_status_t) pjsua_vid_enum_devs(pjmedia_vid_dev_info info[], if (dev_count > *count) dev_count = *count; for (i=0; ipackings & PJMEDIA_VID_PACKING_PACKETS) == 0) - continue; - p_info[j++] = info[i]; + if ((info[i]->packings & PJMEDIA_VID_PACKING_PACKETS) == 0) + continue; + p_info[j++] = info[i]; } *count = j; return PJ_SUCCESS; @@ -443,7 +442,7 @@ static pj_status_t find_codecs_with_rtp_packing( * Enum all supported video codecs in the system. */ PJ_DEF(pj_status_t) pjsua_vid_enum_codecs( pjsua_codec_info id[], - unsigned *p_count ) + unsigned *p_count ) { pjmedia_vid_codec_info info[32]; unsigned i, j, count, prio[32]; @@ -452,26 +451,26 @@ PJ_DEF(pj_status_t) pjsua_vid_enum_codecs( pjsua_codec_info id[], count = PJ_ARRAY_SIZE(info); status = pjmedia_vid_codec_mgr_enum_codecs(NULL, &count, info, prio); if (status != PJ_SUCCESS) { - *p_count = 0; - return status; + *p_count = 0; + return status; } for (i=0, j=0; islen==1 && *codec_id->ptr=='*') - codec_id = &all; + codec_id = &all; return pjmedia_vid_codec_mgr_set_codec_priority(NULL, codec_id, - priority); + priority); } @@ -500,8 +499,8 @@ PJ_DEF(pj_status_t) pjsua_vid_codec_set_priority( const pj_str_t *codec_id, * Get video codec parameters. */ PJ_DEF(pj_status_t) pjsua_vid_codec_get_param( - const pj_str_t *codec_id, - pjmedia_vid_codec_param *param) + const pj_str_t *codec_id, + pjmedia_vid_codec_param *param) { const pjmedia_vid_codec_info *info[2]; unsigned count = 2; @@ -509,10 +508,10 @@ PJ_DEF(pj_status_t) pjsua_vid_codec_get_param( status = find_codecs_with_rtp_packing(codec_id, &count, info); if (status != PJ_SUCCESS) - return status; + return status; if (count != 1) - return (count > 1? PJ_ETOOMANY : PJ_ENOTFOUND); + return (count > 1? PJ_ETOOMANY : PJ_ENOTFOUND); status = pjmedia_vid_codec_mgr_get_default_param(NULL, info[0], param); return status; @@ -523,8 +522,8 @@ PJ_DEF(pj_status_t) pjsua_vid_codec_get_param( * Set video codec parameters. */ PJ_DEF(pj_status_t) pjsua_vid_codec_set_param( - const pj_str_t *codec_id, - const pjmedia_vid_codec_param *param) + const pj_str_t *codec_id, + const pjmedia_vid_codec_param *param) { const pjmedia_vid_codec_info *info[2]; unsigned count = 2; @@ -532,10 +531,10 @@ PJ_DEF(pj_status_t) pjsua_vid_codec_set_param( status = find_codecs_with_rtp_packing(codec_id, &count, info); if (status != PJ_SUCCESS) - return status; + return status; if (count != 1) - return (count > 1? PJ_ETOOMANY : PJ_ENOTFOUND); + return (count > 1? PJ_ETOOMANY : PJ_ENOTFOUND); status = pjmedia_vid_codec_mgr_set_default_param(NULL, info[0], param); return status; @@ -556,22 +555,22 @@ static pjsua_vid_win_id vid_preview_get_win(pjmedia_vid_dev_index id, /* Get real capture ID, if set to PJMEDIA_VID_DEFAULT_CAPTURE_DEV */ if (id == PJMEDIA_VID_DEFAULT_CAPTURE_DEV) { - pjmedia_vid_dev_info info; - pjmedia_vid_dev_get_info(id, &info); - id = info.id; + pjmedia_vid_dev_info info; + pjmedia_vid_dev_get_info(id, &info); + id = info.id; } for (i=0; itype == PJSUA_WND_TYPE_PREVIEW && w->preview_cap_id == id) { - wid = i; - break; - } + pjsua_vid_win *w = &pjsua_var.win[i]; + if (w->type == PJSUA_WND_TYPE_PREVIEW && w->preview_cap_id == id) { + wid = i; + break; + } } if (wid != PJSUA_INVALID_ID && running_only) { - pjsua_vid_win *w = &pjsua_var.win[wid]; - wid = w->preview_running ? wid : PJSUA_INVALID_ID; + pjsua_vid_win *w = &pjsua_var.win[wid]; + wid = w->preview_running ? wid : PJSUA_INVALID_ID; } PJSUA_UNLOCK(); @@ -593,7 +592,7 @@ PJ_DEF(pjsua_vid_win_id) pjsua_vid_preview_get_win(pjmedia_vid_dev_index id) * Get video conference slot ID of the specified capture device. */ PJ_DEF(pjsua_conf_port_id) pjsua_vid_preview_get_vid_conf_port( - pjmedia_vid_dev_index id) + pjmedia_vid_dev_index id) { pjsua_vid_win_id wid; pjsua_vid_win *w; @@ -602,8 +601,8 @@ PJ_DEF(pjsua_conf_port_id) pjsua_vid_preview_get_vid_conf_port( PJSUA_LOCK(); wid = vid_preview_get_win(id, PJ_TRUE); if (wid != PJSUA_INVALID_ID) { - w = &pjsua_var.win[wid]; - conf_id = w->cap_slot; + w = &pjsua_var.win[wid]; + conf_id = w->cap_slot; } PJSUA_UNLOCK(); @@ -629,13 +628,13 @@ void pjsua_vid_win_reset(pjsua_vid_win_id wid) * - If the type is stream: only render port will be created. */ static pj_status_t create_vid_win(pjsua_vid_win_type type, - const pjmedia_format *fmt, - pjmedia_vid_dev_index rend_id, - pjmedia_vid_dev_index cap_id, - pj_bool_t show, + const pjmedia_format *fmt, + pjmedia_vid_dev_index rend_id, + pjmedia_vid_dev_index cap_id, + pj_bool_t show, unsigned wnd_flags, const pjmedia_vid_dev_hwnd *wnd, - pjsua_vid_win_id *id) + pjsua_vid_win_id *id) { pj_bool_t enable_native_preview; pjsua_vid_win_id wid = PJSUA_INVALID_ID; @@ -648,204 +647,204 @@ static pj_status_t create_vid_win(pjsua_vid_win_type type, enable_native_preview = pjsua_var.media_cfg.vid_preview_enable_native; PJ_LOG(4,(THIS_FILE, - "Creating video window: type=%s, cap_id=%d, rend_id=%d", - pjsua_vid_win_type_name(type), cap_id, rend_id)); + "Creating video window: type=%s, cap_id=%d, rend_id=%d", + pjsua_vid_win_type_name(type), cap_id, rend_id)); pj_log_push_indent(); /* If type is preview, check if it exists already */ if (type == PJSUA_WND_TYPE_PREVIEW) { - wid = vid_preview_get_win(cap_id, PJ_FALSE); - if (wid != PJSUA_INVALID_ID) { - /* Yes, it exists */ - /* Show/hide window */ - pjmedia_vid_dev_stream *strm; - pj_bool_t hide = !show; - - w = &pjsua_var.win[wid]; - - PJ_LOG(4,(THIS_FILE, - "Window already exists for cap_dev=%d, returning wid=%d", - cap_id, wid)); - - - if (w->is_native) { - strm = pjmedia_vid_port_get_stream(w->vp_cap); - } else { - strm = pjmedia_vid_port_get_stream(w->vp_rend); - } - pj_assert(strm); - - /* Try to apply show/hide, window flags, and output window */ - - status = pjmedia_vid_dev_stream_set_cap( - strm, PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE, - &hide); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Ignored error on setting window visibility " - "on wid=%d", wid)); - } - - status = pjmedia_vid_dev_stream_set_cap( + wid = vid_preview_get_win(cap_id, PJ_FALSE); + if (wid != PJSUA_INVALID_ID) { + /* Yes, it exists */ + /* Show/hide window */ + pjmedia_vid_dev_stream *strm; + pj_bool_t hide = !show; + + w = &pjsua_var.win[wid]; + + PJ_LOG(4,(THIS_FILE, + "Window already exists for cap_dev=%d, returning wid=%d", + cap_id, wid)); + + + if (w->is_native) { + strm = pjmedia_vid_port_get_stream(w->vp_cap); + } else { + strm = pjmedia_vid_port_get_stream(w->vp_rend); + } + pj_assert(strm); + + /* Try to apply show/hide, window flags, and output window */ + + status = pjmedia_vid_dev_stream_set_cap( + strm, PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE, + &hide); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, + "Ignored error on setting window visibility " + "on wid=%d", wid)); + } + + status = pjmedia_vid_dev_stream_set_cap( strm, PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS, - &wnd_flags); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Ignored error on setting window flags " - "on wid=%d", wid)); - } - - if (wnd) { - status = pjmedia_vid_dev_stream_set_cap( - strm, PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW, wnd); - - if (status != PJ_SUCCESS) { - PJ_PERROR(4, (THIS_FILE, status, - "Ignored error on setting window handle " - "on wid=%d", wid)); - } - } - - status = pjsua_vid_conf_connect(w->cap_slot, w->rend_slot, NULL); - if (status != PJ_SUCCESS) { - PJ_PERROR(4, (THIS_FILE, status, - "Ignored error on connecting video ports " - "on wid=%d", wid)); - } - - /* Done */ - *id = wid; - pj_log_pop_indent(); - - return PJ_SUCCESS; - } + &wnd_flags); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, + "Ignored error on setting window flags " + "on wid=%d", wid)); + } + + if (wnd) { + status = pjmedia_vid_dev_stream_set_cap( + strm, PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW, wnd); + + if (status != PJ_SUCCESS) { + PJ_PERROR(4, (THIS_FILE, status, + "Ignored error on setting window handle " + "on wid=%d", wid)); + } + } + + status = pjsua_vid_conf_connect(w->cap_slot, w->rend_slot, NULL); + if (status != PJ_SUCCESS) { + PJ_PERROR(4, (THIS_FILE, status, + "Ignored error on connecting video ports " + "on wid=%d", wid)); + } + + /* Done */ + *id = wid; + pj_log_pop_indent(); + + return PJ_SUCCESS; + } } /* Allocate window */ for (i=0; itype == PJSUA_WND_TYPE_NONE) { - wid = i; - w->type = type; - break; - } + w = &pjsua_var.win[i]; + if (w->type == PJSUA_WND_TYPE_NONE) { + wid = i; + w->type = type; + break; + } } if (i == PJSUA_MAX_VID_WINS) { - pj_log_pop_indent(); - return PJ_ETOOMANY; + pj_log_pop_indent(); + return PJ_ETOOMANY; } /* Initialize window */ pjmedia_vid_port_param_default(&vp_param); if (w->type == PJSUA_WND_TYPE_PREVIEW) { - pjmedia_vid_dev_info vdi; - - /* - * Determine if the device supports native preview. - */ - status = pjmedia_vid_dev_get_info(cap_id, &vdi); - if (status != PJ_SUCCESS) - goto on_error; - - if (enable_native_preview && - (vdi.caps & PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW)) - { - /* Device supports native preview! */ - w->is_native = PJ_TRUE; - } - - status = pjmedia_vid_dev_default_param(w->pool, cap_id, - &vp_param.vidparam); - if (status != PJ_SUCCESS) - goto on_error; - - if (w->is_native) { - vp_param.vidparam.flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE; - vp_param.vidparam.window_hide = !show; - vp_param.vidparam.flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS; - vp_param.vidparam.window_flags = wnd_flags; - } - - /* Normalize capture ID, in case it was set to - * PJMEDIA_VID_DEFAULT_CAPTURE_DEV - */ - cap_id = vp_param.vidparam.cap_id; - - /* Assign preview capture device ID */ - w->preview_cap_id = cap_id; - - /* Create capture video port */ - vp_param.active = PJ_FALSE; - vp_param.vidparam.dir = PJMEDIA_DIR_CAPTURE; + pjmedia_vid_dev_info vdi; + + /* + * Determine if the device supports native preview. + */ + status = pjmedia_vid_dev_get_info(cap_id, &vdi); + if (status != PJ_SUCCESS) + goto on_error; + + if (enable_native_preview && + (vdi.caps & PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW)) + { + /* Device supports native preview! */ + w->is_native = PJ_TRUE; + } + + status = pjmedia_vid_dev_default_param(w->pool, cap_id, + &vp_param.vidparam); + if (status != PJ_SUCCESS) + goto on_error; + + if (w->is_native) { + vp_param.vidparam.flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE; + vp_param.vidparam.window_hide = !show; + vp_param.vidparam.flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS; + vp_param.vidparam.window_flags = wnd_flags; + } + + /* Normalize capture ID, in case it was set to + * PJMEDIA_VID_DEFAULT_CAPTURE_DEV + */ + cap_id = vp_param.vidparam.cap_id; + + /* Assign preview capture device ID */ + w->preview_cap_id = cap_id; + + /* Create capture video port */ + vp_param.active = PJ_FALSE; + vp_param.vidparam.dir = PJMEDIA_DIR_CAPTURE; /* Update the video setting with user preference */ #define update_param(cap, field) \ - if ((pjsua_var.vid_caps[cap_id] & cap) && (vdi.caps & cap)) { \ - vp_param.vidparam.flags |= cap; \ - pj_memcpy(&vp_param.vidparam.field, \ - &pjsua_var.vid_param[cap_id].field, \ - sizeof(vp_param.vidparam.field)); \ - } - - if (fmt) { - vp_param.vidparam.fmt = *fmt; - } else { - update_param(PJMEDIA_VID_DEV_CAP_FORMAT, fmt); - } - - update_param(PJMEDIA_VID_DEV_CAP_ORIENTATION, orient); + if ((pjsua_var.vid_caps[cap_id] & cap) && (vdi.caps & cap)) { \ + vp_param.vidparam.flags |= cap; \ + pj_memcpy(&vp_param.vidparam.field, \ + &pjsua_var.vid_param[cap_id].field, \ + sizeof(vp_param.vidparam.field)); \ + } + + if (fmt) { + vp_param.vidparam.fmt = *fmt; + } else { + update_param(PJMEDIA_VID_DEV_CAP_FORMAT, fmt); + } + + update_param(PJMEDIA_VID_DEV_CAP_ORIENTATION, orient); #undef update_param - status = pjmedia_vid_port_create(w->pool, &vp_param, &w->vp_cap); - if (status != PJ_SUCCESS) - goto on_error; - - /* Update format info */ - fmt_ = vp_param.vidparam.fmt; - fmt = &fmt_; - - /* Register capturer to the video conf */ - status = pjsua_vid_conf_add_port( - w->pool, - pjmedia_vid_port_get_passive_port(w->vp_cap), - NULL, &w->cap_slot); - if (status != PJ_SUCCESS) - goto on_error; - - /* If device supports native preview, enable it */ - if (w->is_native) { - pjmedia_vid_dev_stream *cap_dev; - pj_bool_t enabled = PJ_TRUE; - - cap_dev = pjmedia_vid_port_get_stream(w->vp_cap); - status = pjmedia_vid_dev_stream_set_cap( - cap_dev, PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW, - &enabled); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Error activating native preview, falling back " - "to software preview..", - status); - w->is_native = PJ_FALSE; - } - } + status = pjmedia_vid_port_create(w->pool, &vp_param, &w->vp_cap); + if (status != PJ_SUCCESS) + goto on_error; + + /* Update format info */ + fmt_ = vp_param.vidparam.fmt; + fmt = &fmt_; + + /* Register capturer to the video conf */ + status = pjsua_vid_conf_add_port( + w->pool, + pjmedia_vid_port_get_passive_port(w->vp_cap), + NULL, &w->cap_slot); + if (status != PJ_SUCCESS) + goto on_error; + + /* If device supports native preview, enable it */ + if (w->is_native) { + pjmedia_vid_dev_stream *cap_dev; + pj_bool_t enabled = PJ_TRUE; + + cap_dev = pjmedia_vid_port_get_stream(w->vp_cap); + status = pjmedia_vid_dev_stream_set_cap( + cap_dev, PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW, + &enabled); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, + "Error activating native preview, falling back " + "to software preview..", + status); + w->is_native = PJ_FALSE; + } + } } /* Create renderer video port, only if it's not a native preview */ if (!w->is_native) { - status = pjmedia_vid_dev_default_param(w->pool, rend_id, - &vp_param.vidparam); - if (status != PJ_SUCCESS) - goto on_error; - - vp_param.active = PJ_FALSE; - vp_param.vidparam.dir = PJMEDIA_DIR_RENDER; - vp_param.vidparam.fmt = *fmt; - vp_param.vidparam.disp_size = fmt->det.vid.size; - vp_param.vidparam.flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE; - vp_param.vidparam.window_hide = !show; + status = pjmedia_vid_dev_default_param(w->pool, rend_id, + &vp_param.vidparam); + if (status != PJ_SUCCESS) + goto on_error; + + vp_param.active = PJ_FALSE; + vp_param.vidparam.dir = PJMEDIA_DIR_RENDER; + vp_param.vidparam.fmt = *fmt; + vp_param.vidparam.disp_size = fmt->det.vid.size; + vp_param.vidparam.flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE; + vp_param.vidparam.window_hide = !show; vp_param.vidparam.flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW_FLAGS; vp_param.vidparam.window_flags = wnd_flags; if (wnd) { @@ -853,33 +852,33 @@ static pj_status_t create_vid_win(pjsua_vid_win_type type, vp_param.vidparam.window = *wnd; } - status = pjmedia_vid_port_create(w->pool, &vp_param, &w->vp_rend); - if (status != PJ_SUCCESS) - goto on_error; - - /* Register renderer to the video conf */ - status = pjsua_vid_conf_add_port( - w->pool, - pjmedia_vid_port_get_passive_port(w->vp_rend), - NULL, &w->rend_slot); - if (status != PJ_SUCCESS) - goto on_error; - - /* For preview window, connect capturer & renderer (via conf) */ - if (w->type == PJSUA_WND_TYPE_PREVIEW && show) { - status = pjsua_vid_conf_connect(w->cap_slot, w->rend_slot, NULL); - if (status != PJ_SUCCESS) - goto on_error; - } - - PJ_LOG(4,(THIS_FILE, - "%s window id %d created for cap_dev=%d rend_dev=%d", - pjsua_vid_win_type_name(type), wid, cap_id, rend_id)); + status = pjmedia_vid_port_create(w->pool, &vp_param, &w->vp_rend); + if (status != PJ_SUCCESS) + goto on_error; + + /* Register renderer to the video conf */ + status = pjsua_vid_conf_add_port( + w->pool, + pjmedia_vid_port_get_passive_port(w->vp_rend), + NULL, &w->rend_slot); + if (status != PJ_SUCCESS) + goto on_error; + + /* For preview window, connect capturer & renderer (via conf) */ + if (w->type == PJSUA_WND_TYPE_PREVIEW && show) { + status = pjsua_vid_conf_connect(w->cap_slot, w->rend_slot, NULL); + if (status != PJ_SUCCESS) + goto on_error; + } + + PJ_LOG(4,(THIS_FILE, + "%s window id %d created for cap_dev=%d rend_dev=%d", + pjsua_vid_win_type_name(type), wid, cap_id, rend_id)); } else { - PJ_LOG(4,(THIS_FILE, - "Preview window id %d created for cap_dev %d, " - "using built-in preview!", - wid, cap_id)); + PJ_LOG(4,(THIS_FILE, + "Preview window id %d created for cap_dev %d, " + "using built-in preview!", + wid, cap_id)); } @@ -909,18 +908,18 @@ static void free_vid_win(pjsua_vid_win_id wid) num_locks = PJSUA_RELEASE_LOCK(); if (w->vp_cap) { - pjsua_vid_conf_remove_port(w->cap_slot); + pjsua_vid_conf_remove_port(w->cap_slot); pjmedia_event_unsubscribe(NULL, &call_media_on_event, NULL, - w->vp_cap); - pjmedia_vid_port_stop(w->vp_cap); - pjmedia_vid_port_destroy(w->vp_cap); + w->vp_cap); + pjmedia_vid_port_stop(w->vp_cap); + pjmedia_vid_port_destroy(w->vp_cap); } if (w->vp_rend) { - pjsua_vid_conf_remove_port(w->rend_slot); + pjsua_vid_conf_remove_port(w->rend_slot); pjmedia_event_unsubscribe(NULL, &call_media_on_event, NULL, - w->vp_rend); - pjmedia_vid_port_stop(w->vp_rend); - pjmedia_vid_port_destroy(w->vp_rend); + w->vp_rend); + pjmedia_vid_port_stop(w->vp_rend); + pjmedia_vid_port_destroy(w->vp_rend); } /* Re-acquire the locks. */ PJSUA_RELOCK(num_locks); @@ -951,7 +950,7 @@ static void dec_vid_win(pjsua_vid_win_id wid) w = &pjsua_var.win[wid]; pj_assert(w->type != PJSUA_WND_TYPE_NONE); if (--w->ref_cnt == 0) - free_vid_win(wid); + free_vid_win(wid); } /* Initialize video call media */ @@ -970,14 +969,14 @@ pj_status_t pjsua_vid_channel_init(pjsua_call_media *call_med) * at this point. if (call_med->strm.v.rdr_dev == PJMEDIA_VID_DEFAULT_RENDER_DEV) { - pjmedia_vid_dev_info info; - pjmedia_vid_dev_get_info(call_med->strm.v.rdr_dev, &info); - call_med->strm.v.rdr_dev = info.id; + pjmedia_vid_dev_info info; + pjmedia_vid_dev_get_info(call_med->strm.v.rdr_dev, &info); + call_med->strm.v.rdr_dev = info.id; } if (call_med->strm.v.cap_dev == PJMEDIA_VID_DEFAULT_CAPTURE_DEV) { - pjmedia_vid_dev_info info; - pjmedia_vid_dev_get_info(call_med->strm.v.cap_dev, &info); - call_med->strm.v.cap_dev = info.id; + pjmedia_vid_dev_info info; + pjmedia_vid_dev_get_info(call_med->strm.v.cap_dev, &info); + call_med->strm.v.cap_dev = info.id; } */ @@ -995,10 +994,10 @@ static pj_status_t setup_vid_capture(pjsua_call_media *call_med) /* Retrieve stream encoding port */ status = pjmedia_vid_stream_get_port(call_med->strm.v.stream, - PJMEDIA_DIR_ENCODING, - &media_port); + PJMEDIA_DIR_ENCODING, + &media_port); if (status != PJ_SUCCESS) - return status; + return status; PJSUA_LOCK(); @@ -1009,19 +1008,19 @@ static pj_status_t setup_vid_capture(pjsua_call_media *call_med) */ wid = vid_preview_get_win(call_med->strm.v.cap_dev, PJ_FALSE); if (wid == PJSUA_INVALID_ID) { - /* Create preview video window */ - status = create_vid_win(PJSUA_WND_TYPE_PREVIEW, - &media_port->info.fmt, - call_med->strm.v.rdr_dev, - call_med->strm.v.cap_dev, - PJSUA_HIDE_WINDOW, + /* Create preview video window */ + status = create_vid_win(PJSUA_WND_TYPE_PREVIEW, + &media_port->info.fmt, + call_med->strm.v.rdr_dev, + call_med->strm.v.cap_dev, + PJSUA_HIDE_WINDOW, acc_enc->cfg.vid_wnd_flags, NULL, - &wid); - if (status != PJ_SUCCESS) - goto on_error; + &wid); + if (status != PJ_SUCCESS) + goto on_error; - just_created = PJ_TRUE; + just_created = PJ_TRUE; } w = &pjsua_var.win[wid]; @@ -1032,24 +1031,24 @@ static pj_status_t setup_vid_capture(pjsua_call_media *call_med) /* Connect capturer to stream encoding (via conf) */ status = pjsua_vid_conf_connect(w->cap_slot, - call_med->strm.v.strm_enc_slot, - NULL); + call_med->strm.v.strm_enc_slot, + NULL); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Start capturer */ if (just_created) { - status = pjmedia_vid_port_start(w->vp_cap); - if (status != PJ_SUCCESS) - goto on_error; + status = pjmedia_vid_port_start(w->vp_cap); + if (status != PJ_SUCCESS) + goto on_error; } /* Done */ inc_vid_win(wid); call_med->strm.v.cap_win_id = wid; PJ_LOG(4,(THIS_FILE, "Call %d media %d: video capture set up with " - "dev %d, wid=%d", call_med->call->index, - call_med->idx, call_med->strm.v.cap_dev, wid)); + "dev %d, wid=%d", call_med->call->index, + call_med->idx, call_med->strm.v.cap_dev, wid)); PJSUA_UNLOCK(); @@ -1063,14 +1062,14 @@ static pj_status_t setup_vid_capture(pjsua_call_media *call_med) /* Internal function: update video channel after SDP negotiation. * Warning: do not use temporary/flip-flop pool, e.g: inv->pool_prov, * for creating stream, etc, as after SDP negotiation and when - * the SDP media is not changed, the stream should remain running + * the SDP media is not changed, the stream should remain running * while the temporary/flip-flop pool may be released. */ pj_status_t pjsua_vid_channel_update(pjsua_call_media *call_med, - pj_pool_t *tmp_pool, - pjmedia_vid_stream_info *si, - const pjmedia_sdp_session *local_sdp, - const pjmedia_sdp_session *remote_sdp) + pj_pool_t *tmp_pool, + pjmedia_vid_stream_info *si, + const pjmedia_sdp_session *local_sdp, + const pjmedia_sdp_session *remote_sdp) { pjsua_call *call = call_med->call; unsigned strm_idx = call_med->idx; @@ -1089,70 +1088,70 @@ pj_status_t pjsua_vid_channel_update(pjsua_call_media *call_med, /* Check if no media is active */ if (local_sdp->media[strm_idx]->desc.port != 0) { - /* Optionally, application may modify other stream settings here - * (such as jitter buffer parameters, codec ptime, etc.) - */ - si->jb_init = pjsua_var.media_cfg.jb_init; - si->jb_min_pre = pjsua_var.media_cfg.jb_min_pre; - si->jb_max_pre = pjsua_var.media_cfg.jb_max_pre; - si->jb_max = pjsua_var.media_cfg.jb_max; - - /* Set SSRC and CNAME */ - si->ssrc = call_med->ssrc; - si->cname = call->cname; - - /* Set RTP timestamp & sequence, normally these value are intialized - * automatically when stream session created, but for some cases (e.g: - * call reinvite, call update) timestamp and sequence need to be kept - * contigue. - */ - si->rtp_ts = call_med->rtp_tx_ts; - si->rtp_seq = call_med->rtp_tx_seq; - si->rtp_seq_ts_set = call_med->rtp_tx_seq_ts_set; - - /* Set rate control config from account setting */ - si->rc_cfg = acc->cfg.vid_stream_rc_cfg; - - /* Set send keyframe config from account setting */ - si->sk_cfg = acc->cfg.vid_stream_sk_cfg; + /* Optionally, application may modify other stream settings here + * (such as jitter buffer parameters, codec ptime, etc.) + */ + si->jb_init = pjsua_var.media_cfg.jb_init; + si->jb_min_pre = pjsua_var.media_cfg.jb_min_pre; + si->jb_max_pre = pjsua_var.media_cfg.jb_max_pre; + si->jb_max = pjsua_var.media_cfg.jb_max; + + /* Set SSRC and CNAME */ + si->ssrc = call_med->ssrc; + si->cname = call->cname; + + /* Set RTP timestamp & sequence, normally these value are intialized + * automatically when stream session created, but for some cases (e.g: + * call reinvite, call update) timestamp and sequence need to be kept + * contigue. + */ + si->rtp_ts = call_med->rtp_tx_ts; + si->rtp_seq = call_med->rtp_tx_seq; + si->rtp_seq_ts_set = call_med->rtp_tx_seq_ts_set; + + /* Set rate control config from account setting */ + si->rc_cfg = acc->cfg.vid_stream_rc_cfg; + + /* Set send keyframe config from account setting */ + si->sk_cfg = acc->cfg.vid_stream_sk_cfg; #if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0 - /* Enable/disable stream keep-alive and NAT hole punch. */ - si->use_ka = acc->cfg.use_stream_ka; + /* Enable/disable stream keep-alive and NAT hole punch. */ + si->use_ka = acc->cfg.use_stream_ka; si->ka_cfg = acc->cfg.stream_ka_cfg; #endif - /* Try to get shared format ID between the capture device and - * the encoder to avoid format conversion in the capture device. - */ - if (si->dir & PJMEDIA_DIR_ENCODING) { - pjmedia_vid_dev_info dev_info; - pjmedia_vid_codec_info *codec_info = &si->codec_info; - unsigned i, j; - - status = pjmedia_vid_dev_get_info(call_med->strm.v.cap_dev, - &dev_info); - if (status != PJ_SUCCESS) - goto on_error; - - /* Find matched format ID */ - for (i = 0; i < codec_info->dec_fmt_id_cnt; ++i) { - for (j = 0; j < dev_info.fmt_cnt; ++j) { - if (codec_info->dec_fmt_id[i] == - (pjmedia_format_id)dev_info.fmt[j].id) - { - /* Apply the matched format ID to the codec */ - si->codec_param->dec_fmt.id = - codec_info->dec_fmt_id[i]; - - /* Force outer loop to break */ - i = codec_info->dec_fmt_id_cnt; - break; - } - } - } - } + /* Try to get shared format ID between the capture device and + * the encoder to avoid format conversion in the capture device. + */ + if (si->dir & PJMEDIA_DIR_ENCODING) { + pjmedia_vid_dev_info dev_info; + pjmedia_vid_codec_info *codec_info = &si->codec_info; + unsigned i, j; + + status = pjmedia_vid_dev_get_info(call_med->strm.v.cap_dev, + &dev_info); + if (status != PJ_SUCCESS) + goto on_error; + + /* Find matched format ID */ + for (i = 0; i < codec_info->dec_fmt_id_cnt; ++i) { + for (j = 0; j < dev_info.fmt_cnt; ++j) { + if (codec_info->dec_fmt_id[i] == + (pjmedia_format_id)dev_info.fmt[j].id) + { + /* Apply the matched format ID to the codec */ + si->codec_param->dec_fmt.id = + codec_info->dec_fmt_id[i]; + + /* Force outer loop to break */ + i = codec_info->dec_fmt_id_cnt; + break; + } + } + } + } if (!call->hanging_up && pjsua_var.ua_cfg.cb.on_stream_precreate) { pjsua_on_stream_precreate_param prm; @@ -1170,110 +1169,110 @@ pj_status_t pjsua_vid_channel_update(pjsua_call_media *call_med, si->use_ka = prm.stream_info.info.vid.use_ka; #endif si->rtcp_sdes_bye_disabled = prm.stream_info.info.vid.rtcp_sdes_bye_disabled; - si->codec_param->enc_fmt = prm.stream_info.info.vid.codec_param->enc_fmt; + si->codec_param->enc_fmt = prm.stream_info.info.vid.codec_param->enc_fmt; } - /* Create session based on session info. */ - status = pjmedia_vid_stream_create(pjsua_var.med_endpt, NULL, si, - call_med->tp, NULL, - &call_med->strm.v.stream); - if (status != PJ_SUCCESS) - goto on_error; + /* Create session based on session info. */ + status = pjmedia_vid_stream_create(pjsua_var.med_endpt, NULL, si, + call_med->tp, NULL, + &call_med->strm.v.stream); + if (status != PJ_SUCCESS) + goto on_error; - /* Subscribe to video stream events */ - pjmedia_event_subscribe(NULL, &call_media_on_event, - call_med, call_med->strm.v.stream); + /* Subscribe to video stream events */ + pjmedia_event_subscribe(NULL, &call_media_on_event, + call_med, call_med->strm.v.stream); - /* Start stream */ - status = pjmedia_vid_stream_start(call_med->strm.v.stream); - if (status != PJ_SUCCESS) - goto on_error; + /* Start stream */ + status = pjmedia_vid_stream_start(call_med->strm.v.stream); + if (status != PJ_SUCCESS) + goto on_error; if (call_med->prev_state == PJSUA_CALL_MEDIA_NONE) pjmedia_vid_stream_send_rtcp_sdes(call_med->strm.v.stream); - /* Setup decoding direction */ - if (si->dir & PJMEDIA_DIR_DECODING) - { - pjsua_vid_win_id wid; - pjsua_vid_win *w; - - PJ_LOG(4,(THIS_FILE, "Setting up RX..")); - pj_log_push_indent(); - - /* Retrieve stream decoding port */ - status = pjmedia_vid_stream_get_port(call_med->strm.v.stream, - PJMEDIA_DIR_DECODING, - &media_port); - if (status != PJ_SUCCESS) { - pj_log_pop_indent(); - goto on_error; - } - - /* Create stream video window */ - PJSUA_LOCK(); - status = create_vid_win(PJSUA_WND_TYPE_STREAM, - &media_port->info.fmt, - call_med->strm.v.rdr_dev, - //acc->cfg.vid_rend_dev, - PJSUA_INVALID_ID, - acc->cfg.vid_in_auto_show, + /* Setup decoding direction */ + if (si->dir & PJMEDIA_DIR_DECODING) + { + pjsua_vid_win_id wid; + pjsua_vid_win *w; + + PJ_LOG(4,(THIS_FILE, "Setting up RX..")); + pj_log_push_indent(); + + /* Retrieve stream decoding port */ + status = pjmedia_vid_stream_get_port(call_med->strm.v.stream, + PJMEDIA_DIR_DECODING, + &media_port); + if (status != PJ_SUCCESS) { + pj_log_pop_indent(); + goto on_error; + } + + /* Create stream video window */ + PJSUA_LOCK(); + status = create_vid_win(PJSUA_WND_TYPE_STREAM, + &media_port->info.fmt, + call_med->strm.v.rdr_dev, + //acc->cfg.vid_rend_dev, + PJSUA_INVALID_ID, + acc->cfg.vid_in_auto_show, acc->cfg.vid_wnd_flags, NULL, - &wid); - if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - pj_log_pop_indent(); - goto on_error; - } + &wid); + if (status != PJ_SUCCESS) { + PJSUA_UNLOCK(); + pj_log_pop_indent(); + goto on_error; + } - w = &pjsua_var.win[wid]; + w = &pjsua_var.win[wid]; #if ENABLE_EVENT - /* Register to video events */ - pjmedia_event_subscribe(NULL, &call_media_on_event, + /* Register to video events */ + pjmedia_event_subscribe(NULL, &call_media_on_event, call_med, w->vp_rend); - pjmedia_event_subscribe(NULL, &call_media_on_event, + pjmedia_event_subscribe(NULL, &call_media_on_event, call_med, media_port); #endif - - /* Register renderer to stream events */ - pjmedia_vid_port_subscribe_event(w->vp_rend, media_port); - - /* Register stream decoding to conf, using tmp_pool should be fine - * as bridge will create its own pool (using tmp_pool factory). - */ - status = pjsua_vid_conf_add_port(tmp_pool, media_port, NULL, - &call_med->strm.v.strm_dec_slot); - if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - pj_log_pop_indent(); - goto on_error; - } - - /* Connect stream to renderer (via conf) */ - status = pjsua_vid_conf_connect(call_med->strm.v.strm_dec_slot, - w->rend_slot, NULL); - if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - pj_log_pop_indent(); - goto on_error; - } - - /* Start renderer */ - status = pjmedia_vid_port_start(w->vp_rend); - if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - pj_log_pop_indent(); - goto on_error; - } - - /* Done */ - inc_vid_win(wid); - call_med->strm.v.rdr_win_id = wid; - PJSUA_UNLOCK(); - pj_log_pop_indent(); - } + + /* Register renderer to stream events */ + pjmedia_vid_port_subscribe_event(w->vp_rend, media_port); + + /* Register stream decoding to conf, using tmp_pool should be fine + * as bridge will create its own pool (using tmp_pool factory). + */ + status = pjsua_vid_conf_add_port(tmp_pool, media_port, NULL, + &call_med->strm.v.strm_dec_slot); + if (status != PJ_SUCCESS) { + PJSUA_UNLOCK(); + pj_log_pop_indent(); + goto on_error; + } + + /* Connect stream to renderer (via conf) */ + status = pjsua_vid_conf_connect(call_med->strm.v.strm_dec_slot, + w->rend_slot, NULL); + if (status != PJ_SUCCESS) { + PJSUA_UNLOCK(); + pj_log_pop_indent(); + goto on_error; + } + + /* Start renderer */ + status = pjmedia_vid_port_start(w->vp_rend); + if (status != PJ_SUCCESS) { + PJSUA_UNLOCK(); + pj_log_pop_indent(); + goto on_error; + } + + /* Done */ + inc_vid_win(wid); + call_med->strm.v.rdr_win_id = wid; + PJSUA_UNLOCK(); + pj_log_pop_indent(); + } /* Retrieve stream encoding port */ status = pjmedia_vid_stream_get_port(call_med->strm.v.stream, @@ -1290,26 +1289,26 @@ pj_status_t pjsua_vid_channel_update(pjsua_call_media *call_med, if (status != PJ_SUCCESS) goto on_error; - /* Setup encoding direction */ - if (si->dir & PJMEDIA_DIR_ENCODING) { - PJ_LOG(4,(THIS_FILE, "Setting up TX..")); - pj_log_push_indent(); + /* Setup encoding direction */ + if (si->dir & PJMEDIA_DIR_ENCODING) { + PJ_LOG(4,(THIS_FILE, "Setting up TX..")); + pj_log_push_indent(); - if (!call->local_hold && acc->cfg.vid_out_auto_transmit) { - status = setup_vid_capture(call_med); - if (status != PJ_SUCCESS) - goto on_error; - } + if (!call->local_hold && acc->cfg.vid_out_auto_transmit) { + status = setup_vid_capture(call_med); + if (status != PJ_SUCCESS) + goto on_error; + } - pj_log_pop_indent(); - } + pj_log_pop_indent(); + } } if (!acc->cfg.vid_out_auto_transmit && call_med->strm.v.stream) { - status = pjmedia_vid_stream_pause(call_med->strm.v.stream, - PJMEDIA_DIR_ENCODING); - if (status != PJ_SUCCESS) - goto on_error; + status = pjmedia_vid_stream_pause(call_med->strm.v.stream, + PJMEDIA_DIR_ENCODING); + if (status != PJ_SUCCESS) + goto on_error; } pj_log_pop_indent(); @@ -1331,7 +1330,7 @@ void pjsua_vid_stop_stream(pjsua_call_media *call_med) pj_assert(call_med->type == PJMEDIA_TYPE_VIDEO); if (!strm) - return; + return; PJ_LOG(4,(THIS_FILE, "Stopping video stream..")); pj_log_push_indent(); @@ -1350,30 +1349,30 @@ void pjsua_vid_stop_stream(pjsua_call_media *call_med) * can be called and access already destroyed objects. */ if (call_med->strm.v.cap_win_id != PJSUA_INVALID_ID) { - pjsua_vid_win *w = &pjsua_var.win[call_med->strm.v.cap_win_id]; + pjsua_vid_win *w = &pjsua_var.win[call_med->strm.v.cap_win_id]; - /* Unsubscribe event */ - pjmedia_event_unsubscribe(NULL, &call_media_on_event, call_med, - w->vp_cap); + /* Unsubscribe event */ + pjmedia_event_unsubscribe(NULL, &call_media_on_event, call_med, + w->vp_cap); } if (call_med->strm.v.rdr_win_id != PJSUA_INVALID_ID) { - pj_status_t status; - pjmedia_port *media_port; - pjsua_vid_win *w = &pjsua_var.win[call_med->strm.v.rdr_win_id]; + pj_status_t status; + pjmedia_port *media_port; + pjsua_vid_win *w = &pjsua_var.win[call_med->strm.v.rdr_win_id]; - /* Unsubscribe event, but stop the render first */ - pjmedia_vid_port_stop(w->vp_rend); - pjmedia_event_unsubscribe(NULL, &call_media_on_event, call_med, + /* Unsubscribe event, but stop the render first */ + pjmedia_vid_port_stop(w->vp_rend); + pjmedia_event_unsubscribe(NULL, &call_media_on_event, call_med, w->vp_rend); - /* Retrieve stream decoding port */ - status = pjmedia_vid_stream_get_port(strm, PJMEDIA_DIR_DECODING, - &media_port); - if (status == PJ_SUCCESS) { - pjmedia_event_unsubscribe(NULL, &call_media_on_event, + /* Retrieve stream decoding port */ + status = pjmedia_vid_stream_get_port(strm, PJMEDIA_DIR_DECODING, + &media_port); + if (status == PJ_SUCCESS) { + pjmedia_event_unsubscribe(NULL, &call_media_on_event, call_med, media_port); - pjmedia_vid_port_unsubscribe_event(w->vp_rend, media_port); + pjmedia_vid_port_unsubscribe_event(w->vp_rend, media_port); } } /* Unsubscribe from video stream events */ @@ -1393,79 +1392,79 @@ void pjsua_vid_stop_stream(pjsua_call_media *call_med) * entry cancellation and the callback being called from poll. */ while (1) { - pjsua_timer_list *act_timer; - - act_timer = pjsua_var.active_timer_list.next; - while (act_timer != &pjsua_var.active_timer_list) { - if (act_timer->cb == &call_med_event_cb) { - pjsua_event_list *eve; - - eve = (pjsua_event_list *)act_timer->user_data; - - if (eve->call_id == (int)call_med->call->index && - eve->med_idx == call_med->idx) - { - pjsip_dialog *dlg = call_med->call->inv ? - call_med->call->inv->dlg : NULL; - - /* The function may be called from worker thread, we have - * to handle the events instead of simple sleep here - * and must not hold any lock while handling the events: - * https://github.com/pjsip/pjproject/issues/1737 - */ - num_locks = PJSUA_RELEASE_LOCK(); - - if (dlg) { - pjsip_dlg_inc_session(dlg, &pjsua_var.mod); - pjsip_dlg_dec_lock(dlg); - } - - pjsua_handle_events(10); - - if (dlg) { - pjsip_dlg_inc_lock(dlg); - pjsip_dlg_dec_session(dlg, &pjsua_var.mod); - } - - PJSUA_RELOCK(num_locks); - break; - } - } - act_timer = act_timer->next; - } - if (act_timer == &pjsua_var.active_timer_list) - break; + pjsua_timer_list *act_timer; + + act_timer = pjsua_var.active_timer_list.next; + while (act_timer != &pjsua_var.active_timer_list) { + if (act_timer->cb == &call_med_event_cb) { + pjsua_event_list *eve; + + eve = (pjsua_event_list *)act_timer->user_data; + + if (eve->call_id == (int)call_med->call->index && + eve->med_idx == call_med->idx) + { + pjsip_dialog *dlg = call_med->call->inv ? + call_med->call->inv->dlg : NULL; + + /* The function may be called from worker thread, we have + * to handle the events instead of simple sleep here + * and must not hold any lock while handling the events: + * https://github.com/pjsip/pjproject/issues/1737 + */ + num_locks = PJSUA_RELEASE_LOCK(); + + if (dlg) { + pjsip_dlg_inc_session(dlg, &pjsua_var.mod); + pjsip_dlg_dec_lock(dlg); + } + + pjsua_handle_events(10); + + if (dlg) { + pjsip_dlg_inc_lock(dlg); + pjsip_dlg_dec_session(dlg, &pjsua_var.mod); + } + + PJSUA_RELOCK(num_locks); + break; + } + } + act_timer = act_timer->next; + } + if (act_timer == &pjsua_var.active_timer_list) + break; } if (call_med->strm.v.cap_win_id != PJSUA_INVALID_ID) { - /* Decrement ref count of preview video window */ - dec_vid_win(call_med->strm.v.cap_win_id); - call_med->strm.v.cap_win_id = PJSUA_INVALID_ID; - - PJ_LOG(4,(THIS_FILE, "Call %d media %d: Preview video window " - "released", call_med->call->index, - call_med->idx)); + /* Decrement ref count of preview video window */ + dec_vid_win(call_med->strm.v.cap_win_id); + call_med->strm.v.cap_win_id = PJSUA_INVALID_ID; + + PJ_LOG(4,(THIS_FILE, "Call %d media %d: Preview video window " + "released", call_med->call->index, + call_med->idx)); } if (call_med->strm.v.rdr_win_id != PJSUA_INVALID_ID) { - /* Decrement ref count of stream video window */ - dec_vid_win(call_med->strm.v.rdr_win_id); - call_med->strm.v.rdr_win_id = PJSUA_INVALID_ID; + /* Decrement ref count of stream video window */ + dec_vid_win(call_med->strm.v.rdr_win_id); + call_med->strm.v.rdr_win_id = PJSUA_INVALID_ID; - PJ_LOG(4,(THIS_FILE, "Call %d media %d: Stream video window " - "released", call_med->call->index, - call_med->idx)); + PJ_LOG(4,(THIS_FILE, "Call %d media %d: Stream video window " + "released", call_med->call->index, + call_med->idx)); } PJSUA_UNLOCK(); /* Unregister video stream ports (encode+decode) from conference */ if (call_med->strm.v.strm_enc_slot != PJSUA_INVALID_ID) { - pjsua_vid_conf_remove_port(call_med->strm.v.strm_enc_slot); - call_med->strm.v.strm_enc_slot = PJSUA_INVALID_ID; + pjsua_vid_conf_remove_port(call_med->strm.v.strm_enc_slot); + call_med->strm.v.strm_enc_slot = PJSUA_INVALID_ID; } if (call_med->strm.v.strm_dec_slot != PJSUA_INVALID_ID) { - pjsua_vid_conf_remove_port(call_med->strm.v.strm_dec_slot); - call_med->strm.v.strm_dec_slot = PJSUA_INVALID_ID; + pjsua_vid_conf_remove_port(call_med->strm.v.strm_dec_slot); + call_med->strm.v.strm_dec_slot = PJSUA_INVALID_ID; } /* Don't check for direction and transmitted packets count as we @@ -1477,15 +1476,15 @@ void pjsua_vid_stop_stream(pjsua_call_media *call_med) // stat.tx.pkt) if (pjmedia_vid_stream_get_stat(strm, &stat) == PJ_SUCCESS) { - /* Save RTP timestamp & sequence, so when media session is - * restarted, those values will be restored as the initial - * RTP timestamp & sequence of the new media session. So in - * the same call session, RTP timestamp and sequence are - * guaranteed to be contigue. - */ - call_med->rtp_tx_seq_ts_set = 1 | (1 << 1); - call_med->rtp_tx_seq = stat.rtp_tx_last_seq; - call_med->rtp_tx_ts = stat.rtp_tx_last_ts; + /* Save RTP timestamp & sequence, so when media session is + * restarted, those values will be restored as the initial + * RTP timestamp & sequence of the new media session. So in + * the same call session, RTP timestamp and sequence are + * guaranteed to be contigue. + */ + call_med->rtp_tx_seq_ts_set = 1 | (1 << 1); + call_med->rtp_tx_seq = stat.rtp_tx_last_seq; + call_med->rtp_tx_ts = stat.rtp_tx_last_ts; } pjmedia_vid_stream_destroy(strm); @@ -1502,7 +1501,7 @@ PJ_DEF(pj_bool_t) pjsua_vid_preview_has_native(pjmedia_vid_dev_index id) pjmedia_vid_dev_info vdi; return (pjmedia_vid_dev_get_info(id, &vdi)==PJ_SUCCESS) ? - ((vdi.caps & PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW)!=0) : PJ_FALSE; + ((vdi.caps & PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW)!=0) : PJ_FALSE; } /* @@ -1519,12 +1518,12 @@ PJ_DEF(pj_status_t) pjsua_vid_preview_start(pjmedia_vid_dev_index id, pj_status_t status; if (!prm) { - pjsua_vid_preview_param_default(&default_param); - prm = &default_param; + pjsua_vid_preview_param_default(&default_param); + prm = &default_param; } PJ_LOG(4,(THIS_FILE, "Starting preview for cap_dev=%d, show=%d", - id, prm->show)); + id, prm->show)); pj_log_push_indent(); PJSUA_LOCK(); @@ -1532,58 +1531,58 @@ PJ_DEF(pj_status_t) pjsua_vid_preview_start(pjmedia_vid_dev_index id, rend_id = prm->rend_id; if (prm->format.detail_type == PJMEDIA_FORMAT_DETAIL_VIDEO) - fmt = &prm->format; + fmt = &prm->format; status = create_vid_win(PJSUA_WND_TYPE_PREVIEW, fmt, rend_id, id, - prm->show, prm->wnd_flags, - (prm->wnd.info.window? &prm->wnd: NULL), &wid); + prm->show, prm->wnd_flags, + (prm->wnd.info.window? &prm->wnd: NULL), &wid); if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return status; + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return status; } w = &pjsua_var.win[wid]; if (w->preview_running) { - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return PJ_SUCCESS; + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return PJ_SUCCESS; } /* Start renderer, unless it's native preview */ if (w->is_native && !pjmedia_vid_port_is_running(w->vp_cap)) { - pjmedia_vid_dev_stream *cap_dev; - pj_bool_t enabled = PJ_TRUE; - - cap_dev = pjmedia_vid_port_get_stream(w->vp_cap); - status = pjmedia_vid_dev_stream_set_cap( - cap_dev, PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW, - &enabled); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, - "Error activating native preview, falling back " - "to software preview..", - status); - w->is_native = PJ_FALSE; - } + pjmedia_vid_dev_stream *cap_dev; + pj_bool_t enabled = PJ_TRUE; + + cap_dev = pjmedia_vid_port_get_stream(w->vp_cap); + status = pjmedia_vid_dev_stream_set_cap( + cap_dev, PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW, + &enabled); + if (status != PJ_SUCCESS) { + pjsua_perror(THIS_FILE, + "Error activating native preview, falling back " + "to software preview..", + status); + w->is_native = PJ_FALSE; + } } if (!w->is_native && !pjmedia_vid_port_is_running(w->vp_rend)) { - status = pjmedia_vid_port_start(w->vp_rend); - if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return status; - } + status = pjmedia_vid_port_start(w->vp_rend); + if (status != PJ_SUCCESS) { + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return status; + } } /* Start capturer */ if (!pjmedia_vid_port_is_running(w->vp_cap)) { - status = pjmedia_vid_port_start(w->vp_cap); - if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return status; - } + status = pjmedia_vid_port_start(w->vp_cap); + if (status != PJ_SUCCESS) { + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return status; + } } inc_vid_win(wid); @@ -1606,8 +1605,8 @@ PJ_DEF(pj_status_t) pjsua_vid_preview_stop(pjmedia_vid_dev_index id) PJSUA_LOCK(); wid = pjsua_vid_preview_get_win(id); if (wid == PJSUA_INVALID_ID) { - PJSUA_UNLOCK(); - return PJ_ENOTFOUND; + PJSUA_UNLOCK(); + return PJ_ENOTFOUND; } PJ_LOG(4,(THIS_FILE, "Stopping preview for cap_dev=%d", id)); @@ -1615,34 +1614,34 @@ PJ_DEF(pj_status_t) pjsua_vid_preview_stop(pjmedia_vid_dev_index id) w = &pjsua_var.win[wid]; if (w->preview_running) { - if (w->is_native) { - pjmedia_vid_dev_stream *cap_dev; - pj_bool_t enabled = PJ_FALSE; - - cap_dev = pjmedia_vid_port_get_stream(w->vp_cap); - status = pjmedia_vid_dev_stream_set_cap( - cap_dev, PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW, - &enabled); - } else { - status = pjsua_vid_conf_disconnect(w->cap_slot, w->rend_slot); - if (status != PJ_SUCCESS) { - PJ_PERROR(4, (THIS_FILE, status, - "Ignored error on disconnecting video ports " - "on stopping preview wid=%d", wid)); - } - status = pjmedia_vid_port_stop(w->vp_rend); - } - - if (status != PJ_SUCCESS) { - PJ_PERROR(1,(THIS_FILE, status, "Error stopping %spreview", - (w->is_native ? "native " : ""))); - PJSUA_UNLOCK(); - pj_log_pop_indent(); - return status; - } - - dec_vid_win(wid); - w->preview_running = PJ_FALSE; + if (w->is_native) { + pjmedia_vid_dev_stream *cap_dev; + pj_bool_t enabled = PJ_FALSE; + + cap_dev = pjmedia_vid_port_get_stream(w->vp_cap); + status = pjmedia_vid_dev_stream_set_cap( + cap_dev, PJMEDIA_VID_DEV_CAP_INPUT_PREVIEW, + &enabled); + } else { + status = pjsua_vid_conf_disconnect(w->cap_slot, w->rend_slot); + if (status != PJ_SUCCESS) { + PJ_PERROR(4, (THIS_FILE, status, + "Ignored error on disconnecting video ports " + "on stopping preview wid=%d", wid)); + } + status = pjmedia_vid_port_stop(w->vp_rend); + } + + if (status != PJ_SUCCESS) { + PJ_PERROR(1,(THIS_FILE, status, "Error stopping %spreview", + (w->is_native ? "native " : ""))); + PJSUA_UNLOCK(); + pj_log_pop_indent(); + return status; + } + + dec_vid_win(wid); + w->preview_running = PJ_FALSE; } PJSUA_UNLOCK(); @@ -1661,16 +1660,16 @@ PJ_DEF(pj_status_t) pjsua_vid_preview_stop(pjmedia_vid_dev_index id) * Enumerates all video windows. */ PJ_DEF(pj_status_t) pjsua_vid_enum_wins( pjsua_vid_win_id wids[], - unsigned *count) + unsigned *count) { unsigned i, cnt; cnt = 0; for (i=0; itype != PJSUA_WND_TYPE_NONE) - wids[cnt++] = i; + pjsua_vid_win *w = &pjsua_var.win[i]; + if (w->type != PJSUA_WND_TYPE_NONE) + wids[cnt++] = i; } *count = cnt; @@ -1700,39 +1699,39 @@ PJ_DEF(pj_status_t) pjsua_vid_win_get_info( pjsua_vid_win_id wid, wi->is_native = w->is_native; if (w->is_native) { - pjmedia_vid_dev_stream *cap_strm; - pjmedia_vid_dev_cap cap = PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW; - - if (!w->vp_cap) { - status = PJ_EINVAL; - } else { - cap_strm = pjmedia_vid_port_get_stream(w->vp_cap); - if (!cap_strm) { - status = PJ_EINVAL; - } else { - status = pjmedia_vid_dev_stream_get_cap(cap_strm, cap, - &wi->hwnd); - } - } - PJSUA_UNLOCK(); - return status; + pjmedia_vid_dev_stream *cap_strm; + pjmedia_vid_dev_cap cap = PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW; + + if (!w->vp_cap) { + status = PJ_EINVAL; + } else { + cap_strm = pjmedia_vid_port_get_stream(w->vp_cap); + if (!cap_strm) { + status = PJ_EINVAL; + } else { + status = pjmedia_vid_dev_stream_get_cap(cap_strm, cap, + &wi->hwnd); + } + } + PJSUA_UNLOCK(); + return status; } if (w->vp_rend == NULL) { - PJSUA_UNLOCK(); - return PJ_EINVAL; + PJSUA_UNLOCK(); + return PJ_EINVAL; } s = pjmedia_vid_port_get_stream(w->vp_rend); if (s == NULL) { - PJSUA_UNLOCK(); - return PJ_EINVAL; + PJSUA_UNLOCK(); + return PJ_EINVAL; } status = pjmedia_vid_dev_stream_get_param(s, &vparam); if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - return status; + PJSUA_UNLOCK(); + return status; } wi->rdr_dev = vparam.rend_id; @@ -1765,17 +1764,17 @@ PJ_DEF(pj_status_t) pjsua_vid_win_set_show( pjsua_vid_win_id wid, w = &pjsua_var.win[wid]; s = pjmedia_vid_port_get_stream(w->vp_rend? w->vp_rend: w->vp_cap); if (s == NULL) { - PJSUA_UNLOCK(); - return PJ_EINVAL; + PJSUA_UNLOCK(); + return PJ_EINVAL; } /* Make sure that renderer gets started before shown up */ if (show && !pjmedia_vid_port_is_running(w->vp_rend)) - status = pjmedia_vid_port_start(w->vp_rend); + status = pjmedia_vid_port_start(w->vp_rend); hide = !show; status = pjmedia_vid_dev_stream_set_cap(s, - PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE, &hide); + PJMEDIA_VID_DEV_CAP_OUTPUT_HIDE, &hide); PJSUA_UNLOCK(); @@ -1799,12 +1798,12 @@ PJ_DEF(pj_status_t) pjsua_vid_win_set_pos( pjsua_vid_win_id wid, w = &pjsua_var.win[wid]; s = pjmedia_vid_port_get_stream(w->vp_rend? w->vp_rend: w->vp_cap); if (s == NULL) { - PJSUA_UNLOCK(); - return PJ_EINVAL; + PJSUA_UNLOCK(); + return PJ_EINVAL; } status = pjmedia_vid_dev_stream_set_cap(s, - PJMEDIA_VID_DEV_CAP_OUTPUT_POSITION, pos); + PJMEDIA_VID_DEV_CAP_OUTPUT_POSITION, pos); PJSUA_UNLOCK(); @@ -1828,12 +1827,12 @@ PJ_DEF(pj_status_t) pjsua_vid_win_set_size( pjsua_vid_win_id wid, w = &pjsua_var.win[wid]; s = pjmedia_vid_port_get_stream(w->vp_rend? w->vp_rend: w->vp_cap); if (s == NULL) { - PJSUA_UNLOCK(); - return PJ_EINVAL; + PJSUA_UNLOCK(); + return PJ_EINVAL; } status = pjmedia_vid_dev_stream_set_cap(s, - PJMEDIA_VID_DEV_CAP_OUTPUT_RESIZE, size); + PJMEDIA_VID_DEV_CAP_OUTPUT_RESIZE, size); PJSUA_UNLOCK(); @@ -1857,8 +1856,8 @@ PJ_DEF(pj_status_t) pjsua_vid_win_set_win( pjsua_vid_win_id wid, w = &pjsua_var.win[wid]; s = pjmedia_vid_port_get_stream(w->vp_rend? w->vp_rend: w->vp_cap); if (s == NULL) { - PJSUA_UNLOCK(); - return PJ_EINVAL; + PJSUA_UNLOCK(); + return PJ_EINVAL; } status = pjmedia_vid_dev_stream_set_cap(s, @@ -1886,25 +1885,25 @@ PJ_DEF(pj_status_t) pjsua_vid_win_rotate( pjsua_vid_win_id wid, /* Normalize angle, so it must be 0, 90, 180, or 270. */ angle %= 360; if (angle < 0) - angle += 360; + angle += 360; /* Convert angle to pjmedia_orient */ switch(angle) { - case 0: - /* No rotation */ - return PJ_SUCCESS; - case 90: - orient = PJMEDIA_ORIENT_ROTATE_90DEG; - break; - case 180: - orient = PJMEDIA_ORIENT_ROTATE_180DEG; - break; - case 270: - orient = PJMEDIA_ORIENT_ROTATE_270DEG; - break; - default: - pj_assert(!"Angle must have been validated"); - return PJ_EBUG; + case 0: + /* No rotation */ + return PJ_SUCCESS; + case 90: + orient = PJMEDIA_ORIENT_ROTATE_90DEG; + break; + case 180: + orient = PJMEDIA_ORIENT_ROTATE_180DEG; + break; + case 270: + orient = PJMEDIA_ORIENT_ROTATE_270DEG; + break; + default: + pj_assert(!"Angle must have been validated"); + return PJ_EBUG; } PJSUA_LOCK(); @@ -1912,12 +1911,12 @@ PJ_DEF(pj_status_t) pjsua_vid_win_rotate( pjsua_vid_win_id wid, w = &pjsua_var.win[wid]; s = pjmedia_vid_port_get_stream(w->vp_rend? w->vp_rend: w->vp_cap); if (s == NULL) { - PJSUA_UNLOCK(); - return PJ_EINVAL; + PJSUA_UNLOCK(); + return PJ_EINVAL; } status = pjmedia_vid_dev_stream_set_cap(s, - PJMEDIA_VID_DEV_CAP_ORIENTATION, &orient); + PJMEDIA_VID_DEV_CAP_ORIENTATION, &orient); PJSUA_UNLOCK(); @@ -1929,8 +1928,8 @@ PJ_DEF(pj_status_t) pjsua_vid_win_rotate( pjsua_vid_win_id wid, * Set video window fullscreen. */ PJ_DEF(pj_status_t) pjsua_vid_win_set_fullscreen( - pjsua_vid_win_id wid, - pjmedia_vid_dev_fullscreen_flag mode) + pjsua_vid_win_id wid, + pjmedia_vid_dev_fullscreen_flag mode) { pjsua_vid_win *w; pjmedia_vid_dev_stream *s; @@ -1943,12 +1942,12 @@ PJ_DEF(pj_status_t) pjsua_vid_win_set_fullscreen( w = &pjsua_var.win[wid]; s = pjmedia_vid_port_get_stream(w->vp_rend? w->vp_rend: w->vp_cap); if (s == NULL) { - PJSUA_UNLOCK(); - return PJ_EINVAL; + PJSUA_UNLOCK(); + return PJ_EINVAL; } status = pjmedia_vid_dev_stream_set_cap(s, - PJMEDIA_VID_DEV_CAP_OUTPUT_FULLSCREEN, &mode); + PJMEDIA_VID_DEV_CAP_OUTPUT_FULLSCREEN, &mode); PJSUA_UNLOCK(); @@ -1956,46 +1955,46 @@ PJ_DEF(pj_status_t) pjsua_vid_win_set_fullscreen( } static void call_get_vid_strm_info(pjsua_call *call, - int *first_active, - int *first_inactive, - unsigned *active_cnt, - unsigned *cnt) + int *first_active, + int *first_inactive, + unsigned *active_cnt, + unsigned *cnt) { unsigned i, var_cnt = 0; if (first_active && ++var_cnt) - *first_active = -1; + *first_active = -1; if (first_inactive && ++var_cnt) - *first_inactive = -1; + *first_inactive = -1; if (active_cnt && ++var_cnt) - *active_cnt = 0; + *active_cnt = 0; if (cnt && ++var_cnt) - *cnt = 0; + *cnt = 0; for (i = 0; i < call->med_cnt && var_cnt; ++i) { - if (call->media[i].type == PJMEDIA_TYPE_VIDEO) { - if (call->media[i].dir != PJMEDIA_DIR_NONE) - { - if (first_active && *first_active == -1) { - *first_active = i; - --var_cnt; - } - if (active_cnt) - ++(*active_cnt); - } else if (first_inactive && *first_inactive == -1) { - *first_inactive = i; - --var_cnt; - } - if (cnt) - ++(*cnt); - } + if (call->media[i].type == PJMEDIA_TYPE_VIDEO) { + if (call->media[i].dir != PJMEDIA_DIR_NONE) + { + if (first_active && *first_active == -1) { + *first_active = i; + --var_cnt; + } + if (active_cnt) + ++(*active_cnt); + } else if (first_inactive && *first_inactive == -1) { + *first_inactive = i; + --var_cnt; + } + if (cnt) + ++(*cnt); + } } } /* Send SDP reoffer. */ static pj_status_t call_reoffer_sdp(pjsua_call_id call_id, - pjmedia_sdp_session *sdp) + pjmedia_sdp_session *sdp) { pjsua_call *call; pjsip_tx_data *tdata; @@ -2004,35 +2003,35 @@ static pj_status_t call_reoffer_sdp(pjsua_call_id call_id, status = acquire_call("call_reoffer_sdp()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - return status; + return status; if (call->inv->state != PJSIP_INV_STATE_CONFIRMED) { - PJ_LOG(3,(THIS_FILE, "Can not re-INVITE call that is not confirmed")); - pjsip_dlg_dec_lock(dlg); - return PJSIP_ESESSIONSTATE; + PJ_LOG(3,(THIS_FILE, "Can not re-INVITE call that is not confirmed")); + pjsip_dlg_dec_lock(dlg); + return PJSIP_ESESSIONSTATE; } /* Notify application */ if (!call->hanging_up && pjsua_var.ua_cfg.cb.on_call_sdp_created) { - (*pjsua_var.ua_cfg.cb.on_call_sdp_created)(call_id, sdp, - call->inv->pool_prov, - NULL); + (*pjsua_var.ua_cfg.cb.on_call_sdp_created)(call_id, sdp, + call->inv->pool_prov, + NULL); } /* Create re-INVITE with new offer */ status = pjsip_inv_reinvite( call->inv, NULL, sdp, &tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to create re-INVITE", status); - pjsip_dlg_dec_lock(dlg); - return status; + pjsua_perror(THIS_FILE, "Unable to create re-INVITE", status); + pjsip_dlg_dec_lock(dlg); + return status; } /* Send the request */ status = pjsip_inv_send_msg( call->inv, tdata); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Unable to send re-INVITE", status); - pjsip_dlg_dec_lock(dlg); - return status; + pjsua_perror(THIS_FILE, "Unable to send re-INVITE", status); + pjsip_dlg_dec_lock(dlg); + return status; } pjsip_dlg_dec_lock(dlg); @@ -2042,8 +2041,8 @@ static pj_status_t call_reoffer_sdp(pjsua_call_id call_id, /* Add a new video stream into a call */ static pj_status_t call_add_video(pjsua_call *call, - pjmedia_vid_dev_index cap_dev, - pjmedia_dir dir) + pjmedia_vid_dev_index cap_dev, + pjmedia_dir dir) { pj_pool_t *pool = call->inv->pool_prov; pjsua_acc_config *acc_cfg = &pjsua_var.acc[call->acc_id].cfg; @@ -2057,17 +2056,17 @@ static pj_status_t call_add_video(pjsua_call *call, /* Verify media slot availability */ if (call->med_cnt == PJSUA_MAX_CALL_MEDIA) - return PJ_ETOOMANY; + return PJ_ETOOMANY; if (pjsua_call_media_is_changing(call)) { - PJ_LOG(1,(THIS_FILE, "Unable to add video" ERR_MEDIA_CHANGING)); - return PJ_EINVALIDOP; + PJ_LOG(1,(THIS_FILE, "Unable to add video" ERR_MEDIA_CHANGING)); + return PJ_EINVALIDOP; } /* Get active local SDP and clone it */ status = pjmedia_sdp_neg_get_active_local(call->inv->neg, ¤t_sdp); if (status != PJ_SUCCESS) - return status; + return status; sdp = pjmedia_sdp_session_clone(call->inv->pool_prov, current_sdp); @@ -2077,10 +2076,10 @@ static pj_status_t call_add_video(pjsua_call *call, /* Initialize call media */ call_med = &call->media_prov[call->med_prov_cnt++]; status = pjsua_call_media_init(call_med, PJMEDIA_TYPE_VIDEO, - &acc_cfg->rtp_cfg, call->secure_level, - NULL, PJ_FALSE, NULL); + &acc_cfg->rtp_cfg, call->secure_level, + NULL, PJ_FALSE, NULL); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Override default capture device setting */ call_med->strm.v.cap_dev = cap_dev; @@ -2088,9 +2087,9 @@ static pj_status_t call_add_video(pjsua_call *call, /* Init transport media */ options = (call_med->enable_rtcp_mux? PJMEDIA_TPMED_RTCP_MUX: 0); status = pjmedia_transport_media_create(call_med->tp, pool, options, - NULL, call_med->idx); + NULL, call_med->idx); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_INIT); @@ -2100,38 +2099,38 @@ static pj_status_t call_add_video(pjsua_call *call, /* Create SDP media line */ status = pjmedia_endpt_create_video_sdp(pjsua_var.med_endpt, pool, - &tpinfo.sock_info, 0, &sdp_m); + &tpinfo.sock_info, 0, &sdp_m); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; sdp->media[sdp->media_count++] = sdp_m; /* Update media direction, if it is not 'sendrecv' */ if (dir != PJMEDIA_DIR_ENCODING_DECODING) { - pjmedia_sdp_attr *a; + pjmedia_sdp_attr *a; - /* Remove sendrecv direction attribute, if any */ - pjmedia_sdp_media_remove_all_attr(sdp_m, "sendrecv"); + /* Remove sendrecv direction attribute, if any */ + pjmedia_sdp_media_remove_all_attr(sdp_m, "sendrecv"); - if (dir == PJMEDIA_DIR_ENCODING) - a = pjmedia_sdp_attr_create(pool, "sendonly", NULL); - else if (dir == PJMEDIA_DIR_DECODING) - a = pjmedia_sdp_attr_create(pool, "recvonly", NULL); - else - a = pjmedia_sdp_attr_create(pool, "inactive", NULL); + if (dir == PJMEDIA_DIR_ENCODING) + a = pjmedia_sdp_attr_create(pool, "sendonly", NULL); + else if (dir == PJMEDIA_DIR_DECODING) + a = pjmedia_sdp_attr_create(pool, "recvonly", NULL); + else + a = pjmedia_sdp_attr_create(pool, "inactive", NULL); - pjmedia_sdp_media_add_attr(sdp_m, a); + pjmedia_sdp_media_add_attr(sdp_m, a); } /* Update SDP media line by media transport */ status = pjmedia_transport_encode_sdp(call_med->tp, pool, - sdp, NULL, call_med->idx); + sdp, NULL, call_med->idx); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = call_reoffer_sdp(call->index, sdp); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; call->opt.vid_cnt++; @@ -2139,9 +2138,9 @@ static pj_status_t call_add_video(pjsua_call *call, on_error: if (call_med->tp) { - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); - pjmedia_transport_close(call_med->tp); - call_med->tp = call_med->tp_orig = NULL; + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_NULL); + pjmedia_transport_close(call_med->tp); + call_med->tp = call_med->tp_orig = NULL; } call->med_prov_cnt = 0; @@ -2153,9 +2152,9 @@ static pj_status_t call_add_video(pjsua_call *call, * remove/disable. */ static pj_status_t call_modify_video(pjsua_call *call, - int med_idx, - pjmedia_dir dir, - pj_bool_t remove) + int med_idx, + pjmedia_dir dir, + pj_bool_t remove) { pjsua_call_media *call_med; const pjmedia_sdp_session *current_sdp; @@ -2163,19 +2162,19 @@ static pj_status_t call_modify_video(pjsua_call *call, pj_status_t status; if (pjsua_call_media_is_changing(call)) { - PJ_LOG(1,(THIS_FILE, "Unable to modify video" ERR_MEDIA_CHANGING)); - return PJ_EINVALIDOP; + PJ_LOG(1,(THIS_FILE, "Unable to modify video" ERR_MEDIA_CHANGING)); + return PJ_EINVALIDOP; } /* Verify and normalize media index */ if (med_idx == -1) { - int first_active; - - call_get_vid_strm_info(call, &first_active, NULL, NULL, NULL); - if (first_active == -1) - return PJ_ENOTFOUND; + int first_active; + + call_get_vid_strm_info(call, &first_active, NULL, NULL, NULL); + if (first_active == -1) + return PJ_ENOTFOUND; - med_idx = first_active; + med_idx = first_active; } /* Clean up & sync provisional media before using it */ @@ -2185,137 +2184,137 @@ static pj_status_t call_modify_video(pjsua_call *call, /* Verify if the stream media type is video */ if (call_med->type != PJMEDIA_TYPE_VIDEO) - return PJ_EINVAL; + return PJ_EINVAL; /* Verify if the stream dir is not changed */ if ((!remove && call_med->dir == dir) || - ( remove && (call_med->tp_st == PJSUA_MED_TP_DISABLED || - call_med->tp == NULL))) + ( remove && (call_med->tp_st == PJSUA_MED_TP_DISABLED || + call_med->tp == NULL))) { - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Get active local SDP and clone it */ status = pjmedia_sdp_neg_get_active_local(call->inv->neg, ¤t_sdp); if (status != PJ_SUCCESS) - return status; + return status; sdp = pjmedia_sdp_session_clone(call->inv->pool_prov, current_sdp); pj_assert(med_idx < (int)sdp->media_count); if (!remove) { - pjsua_acc_config *acc_cfg = &pjsua_var.acc[call->acc_id].cfg; - pj_pool_t *pool = call->inv->pool_prov; - pjmedia_sdp_media *sdp_m; - - /* Enabling video */ - if (call_med->dir == PJMEDIA_DIR_NONE) { - unsigned i, vid_cnt = 0; - - /* Check if vid_cnt in call option needs to be increased */ - for (i = 0; i < call->med_cnt; ++i) { - if (call->media[i].type == PJMEDIA_TYPE_VIDEO && - call->media[i].dir != PJMEDIA_DIR_NONE) - { - ++vid_cnt; - } - } - if (call->opt.vid_cnt <= vid_cnt) - call->opt.vid_cnt++; - } - - status = pjsua_call_media_init(call_med, PJMEDIA_TYPE_VIDEO, - &acc_cfg->rtp_cfg, call->secure_level, - NULL, PJ_FALSE, NULL); - if (status != PJ_SUCCESS) - goto on_error; - - /* Init transport media */ - if (call_med->tp && call_med->tp_st == PJSUA_MED_TP_IDLE) { - unsigned options = (call_med->enable_rtcp_mux? - PJMEDIA_TPMED_RTCP_MUX: 0); - status = pjmedia_transport_media_create(call_med->tp, pool, - options, NULL, - call_med->idx); - if (status != PJ_SUCCESS) - goto on_error; - } - - sdp_m = sdp->media[med_idx]; - - /* Create new SDP media line if the stream is disabled */ - if (sdp->media[med_idx]->desc.port == 0) { - pjmedia_transport_info tpinfo; - - /* Get transport address info */ - pjmedia_transport_info_init(&tpinfo); - pjmedia_transport_get_info(call_med->tp, &tpinfo); - - status = pjmedia_endpt_create_video_sdp(pjsua_var.med_endpt, pool, - &tpinfo.sock_info, 0, &sdp_m); - if (status != PJ_SUCCESS) - goto on_error; - } - - { - pjmedia_sdp_attr *a; - - /* Remove any direction attributes */ - pjmedia_sdp_media_remove_all_attr(sdp_m, "sendrecv"); - pjmedia_sdp_media_remove_all_attr(sdp_m, "sendonly"); - pjmedia_sdp_media_remove_all_attr(sdp_m, "recvonly"); - pjmedia_sdp_media_remove_all_attr(sdp_m, "inactive"); - - /* Update media direction */ - if (dir == PJMEDIA_DIR_ENCODING_DECODING) - a = pjmedia_sdp_attr_create(pool, "sendrecv", NULL); - else if (dir == PJMEDIA_DIR_ENCODING) - a = pjmedia_sdp_attr_create(pool, "sendonly", NULL); - else if (dir == PJMEDIA_DIR_DECODING) - a = pjmedia_sdp_attr_create(pool, "recvonly", NULL); - else - a = pjmedia_sdp_attr_create(pool, "inactive", NULL); - - pjmedia_sdp_media_add_attr(sdp_m, a); - } - - sdp->media[med_idx] = sdp_m; + pjsua_acc_config *acc_cfg = &pjsua_var.acc[call->acc_id].cfg; + pj_pool_t *pool = call->inv->pool_prov; + pjmedia_sdp_media *sdp_m; + /* Enabling video */ if (call_med->dir == PJMEDIA_DIR_NONE) { - /* Update SDP media line by media transport */ - status = pjmedia_transport_encode_sdp(call_med->tp, pool, - sdp, NULL, call_med->idx); - if (status != PJ_SUCCESS) - goto on_error; + unsigned i, vid_cnt = 0; + + /* Check if vid_cnt in call option needs to be increased */ + for (i = 0; i < call->med_cnt; ++i) { + if (call->media[i].type == PJMEDIA_TYPE_VIDEO && + call->media[i].dir != PJMEDIA_DIR_NONE) + { + ++vid_cnt; + } + } + if (call->opt.vid_cnt <= vid_cnt) + call->opt.vid_cnt++; + } + + status = pjsua_call_media_init(call_med, PJMEDIA_TYPE_VIDEO, + &acc_cfg->rtp_cfg, call->secure_level, + NULL, PJ_FALSE, NULL); + if (status != PJ_SUCCESS) + goto on_error; + + /* Init transport media */ + if (call_med->tp && call_med->tp_st == PJSUA_MED_TP_IDLE) { + unsigned options = (call_med->enable_rtcp_mux? + PJMEDIA_TPMED_RTCP_MUX: 0); + status = pjmedia_transport_media_create(call_med->tp, pool, + options, NULL, + call_med->idx); + if (status != PJ_SUCCESS) + goto on_error; + } + + sdp_m = sdp->media[med_idx]; + + /* Create new SDP media line if the stream is disabled */ + if (sdp->media[med_idx]->desc.port == 0) { + pjmedia_transport_info tpinfo; + + /* Get transport address info */ + pjmedia_transport_info_init(&tpinfo); + pjmedia_transport_get_info(call_med->tp, &tpinfo); + + status = pjmedia_endpt_create_video_sdp(pjsua_var.med_endpt, pool, + &tpinfo.sock_info, 0, &sdp_m); + if (status != PJ_SUCCESS) + goto on_error; + } + + { + pjmedia_sdp_attr *a; + + /* Remove any direction attributes */ + pjmedia_sdp_media_remove_all_attr(sdp_m, "sendrecv"); + pjmedia_sdp_media_remove_all_attr(sdp_m, "sendonly"); + pjmedia_sdp_media_remove_all_attr(sdp_m, "recvonly"); + pjmedia_sdp_media_remove_all_attr(sdp_m, "inactive"); + + /* Update media direction */ + if (dir == PJMEDIA_DIR_ENCODING_DECODING) + a = pjmedia_sdp_attr_create(pool, "sendrecv", NULL); + else if (dir == PJMEDIA_DIR_ENCODING) + a = pjmedia_sdp_attr_create(pool, "sendonly", NULL); + else if (dir == PJMEDIA_DIR_DECODING) + a = pjmedia_sdp_attr_create(pool, "recvonly", NULL); + else + a = pjmedia_sdp_attr_create(pool, "inactive", NULL); + + pjmedia_sdp_media_add_attr(sdp_m, a); + } + + sdp->media[med_idx] = sdp_m; + + if (call_med->dir == PJMEDIA_DIR_NONE) { + /* Update SDP media line by media transport */ + status = pjmedia_transport_encode_sdp(call_med->tp, pool, + sdp, NULL, call_med->idx); + if (status != PJ_SUCCESS) + goto on_error; } on_error: - if (status != PJ_SUCCESS) { - /* Revert back provisional media. */ - pjsua_media_prov_revert(call->index); + if (status != PJ_SUCCESS) { + /* Revert back provisional media. */ + pjsua_media_prov_revert(call->index); - return status; - } + return status; + } } else { - pj_pool_t *pool = call->inv->pool_prov; + pj_pool_t *pool = call->inv->pool_prov; - /* Mark media transport to disabled */ - // Don't close this here, as SDP negotiation has not been - // done and stream may be still active. - pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_DISABLED); + /* Mark media transport to disabled */ + // Don't close this here, as SDP negotiation has not been + // done and stream may be still active. + pjsua_set_media_tp_state(call_med, PJSUA_MED_TP_DISABLED); - /* Deactivate the stream */ - pjmedia_sdp_media_deactivate(pool, sdp->media[med_idx]); + /* Deactivate the stream */ + pjmedia_sdp_media_deactivate(pool, sdp->media[med_idx]); - call->opt.vid_cnt--; + call->opt.vid_cnt--; } status = call_reoffer_sdp(call->index, sdp); if (status != PJ_SUCCESS) - return status; + return status; return PJ_SUCCESS; } @@ -2323,8 +2322,8 @@ static pj_status_t call_modify_video(pjsua_call *call, /* Change capture device of a video stream in a call */ static pj_status_t call_change_cap_dev(pjsua_call *call, - int med_idx, - pjmedia_vid_dev_index cap_dev) + int med_idx, + pjmedia_vid_dev_index cap_dev) { pjsua_call_media *call_med; pjmedia_vid_dev_stream *old_dev; @@ -2337,39 +2336,39 @@ static pj_status_t call_change_cap_dev(pjsua_call *call, /* Verify and normalize media index */ if (med_idx == -1) { - int first_active; - - call_get_vid_strm_info(call, &first_active, NULL, NULL, NULL); - if (first_active == -1) - return PJ_ENOTFOUND; + int first_active; + + call_get_vid_strm_info(call, &first_active, NULL, NULL, NULL); + if (first_active == -1) + return PJ_ENOTFOUND; - med_idx = first_active; + med_idx = first_active; } call_med = &call->media[med_idx]; /* Verify if the stream media type is video */ if (call_med->type != PJMEDIA_TYPE_VIDEO) - return PJ_EINVAL; + return PJ_EINVAL; /* Verify the capture device */ status = pjmedia_vid_dev_get_info(cap_dev, &info); if (status != PJ_SUCCESS || (info.dir & PJMEDIA_DIR_CAPTURE) == 0) - return PJ_EINVAL; + return PJ_EINVAL; /* The specified capture device is being used already */ if (call_med->strm.v.cap_dev == cap_dev) - return PJ_SUCCESS; + return PJ_SUCCESS; /* == Apply the new capture device == */ PJSUA_LOCK(); /* If media does not have active preview, simply set capture device ID */ if (call_med->strm.v.cap_win_id == PJSUA_INVALID_ID) { - call_med->strm.v.cap_dev = cap_dev; + call_med->strm.v.cap_dev = cap_dev; - /* That's it */ - goto on_sync_and_return; + /* That's it */ + goto on_sync_and_return; } wid = call_med->strm.v.cap_win_id; @@ -2384,31 +2383,31 @@ static pj_status_t call_change_cap_dev(pjsua_call *call, PJMEDIA_VID_DEV_CAP_SWITCH, &switch_prm); if (status == PJ_SUCCESS) { - w->preview_cap_id = cap_dev; - call_med->strm.v.cap_dev = cap_dev; + w->preview_cap_id = cap_dev; + call_med->strm.v.cap_dev = cap_dev; - /* Yay, change capturer done! Now return */ - goto on_sync_and_return; + /* Yay, change capturer done! Now return */ + goto on_sync_and_return; } /* Oh no, it doesn't support fast switching. Do normal change then, * i.e: remove the old and create a new capture. */ status = pjmedia_vid_stream_get_port(call_med->strm.v.stream, - PJMEDIA_DIR_ENCODING, &media_port); + PJMEDIA_DIR_ENCODING, &media_port); if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - return status; + PJSUA_UNLOCK(); + return status; } media_event_unsubscribe(NULL, &call_media_on_event, call_med, w->vp_cap); /* Disconnect the old capture device to stream encoding port */ status = pjsua_vid_conf_disconnect(w->cap_slot, - call_med->strm.v.strm_enc_slot); + call_med->strm.v.strm_enc_slot); if (status != PJ_SUCCESS) { - PJSUA_UNLOCK(); - return status; + PJSUA_UNLOCK(); + return status; } @@ -2423,27 +2422,27 @@ static pj_status_t call_change_cap_dev(pjsua_call *call, if (new_wid == PJSUA_INVALID_ID) { pjsua_acc *acc = &pjsua_var.acc[call_med->call->acc_id]; - /* Create preview video window */ - status = create_vid_win(PJSUA_WND_TYPE_PREVIEW, - &media_port->info.fmt, - call_med->strm.v.rdr_dev, - cap_dev, - PJSUA_HIDE_WINDOW, - acc->cfg.vid_wnd_flags, - NULL, + /* Create preview video window */ + status = create_vid_win(PJSUA_WND_TYPE_PREVIEW, + &media_port->info.fmt, + call_med->strm.v.rdr_dev, + cap_dev, + PJSUA_HIDE_WINDOW, + acc->cfg.vid_wnd_flags, + NULL, &new_wid); - if (status != PJ_SUCCESS) - goto on_error; + if (status != PJ_SUCCESS) + goto on_error; } inc_vid_win(new_wid); new_w = &pjsua_var.win[new_wid]; if (new_w->vp_rend) { - /* Start renderer */ - status = pjmedia_vid_port_start(new_w->vp_rend); - if (status != PJ_SUCCESS) - goto on_error; + /* Start renderer */ + status = pjmedia_vid_port_start(new_w->vp_rend); + if (status != PJ_SUCCESS) + goto on_error; } #if ENABLE_EVENT @@ -2453,17 +2452,17 @@ static pj_status_t call_change_cap_dev(pjsua_call *call, /* Start capturer */ if (!pjmedia_vid_port_is_running(new_w->vp_cap)) { - status = pjmedia_vid_port_start(new_w->vp_cap); - if (status != PJ_SUCCESS) - goto on_error; + status = pjmedia_vid_port_start(new_w->vp_cap); + if (status != PJ_SUCCESS) + goto on_error; } /* Connect capturer to stream encoding port (via conf) */ status = pjsua_vid_conf_connect(new_w->cap_slot, - call_med->strm.v.strm_enc_slot, - NULL); + call_med->strm.v.strm_enc_slot, + NULL); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; /* Finally */ call_med->strm.v.cap_dev = cap_dev; @@ -2481,24 +2480,24 @@ static pj_status_t call_change_cap_dev(pjsua_call *call, on_error: PJ_PERROR(4,(THIS_FILE, status, - "Call %d: error changing capture device to %d", - call->index, cap_dev)); + "Call %d: error changing capture device to %d", + call->index, cap_dev)); if (new_w) { - /* Unsubscribe, just in case */ + /* Unsubscribe, just in case */ media_event_unsubscribe(NULL, &call_media_on_event, call_med, - new_w->vp_cap); + new_w->vp_cap); - /* Release the new capturer */ - dec_vid_win(new_wid); + /* Release the new capturer */ + dec_vid_win(new_wid); } /* Revert back to the old capturer */ status = pjsua_vid_conf_connect(w->cap_slot, - call_med->strm.v.strm_enc_slot, NULL); + call_med->strm.v.strm_enc_slot, NULL); if (status != PJ_SUCCESS) { PJSUA_UNLOCK(); - return status; + return status; } #if ENABLE_EVENT @@ -2515,71 +2514,71 @@ static pj_status_t call_change_cap_dev(pjsua_call *call, /* Start/stop transmitting video stream in a call */ static pj_status_t call_set_tx_video(pjsua_call *call, - int med_idx, - pj_bool_t enable) + int med_idx, + pj_bool_t enable) { pjsua_call_media *call_med; pj_status_t status; /* Verify and normalize media index */ if (med_idx == -1) { - int first_active; - - call_get_vid_strm_info(call, &first_active, NULL, NULL, NULL); - if (first_active == -1) - return PJ_ENOTFOUND; + int first_active; + + call_get_vid_strm_info(call, &first_active, NULL, NULL, NULL); + if (first_active == -1) + return PJ_ENOTFOUND; - med_idx = first_active; + med_idx = first_active; } call_med = &call->media[med_idx]; /* Verify if the stream is transmitting video */ if (call_med->type != PJMEDIA_TYPE_VIDEO || - (enable && (call_med->dir & PJMEDIA_DIR_ENCODING) == 0)) + (enable && (call_med->dir & PJMEDIA_DIR_ENCODING) == 0)) { - return PJ_EINVAL; + return PJ_EINVAL; } if (enable) { - if (call_med->strm.v.cap_win_id == PJSUA_INVALID_ID) { - /* Setup the video capture first */ - status = setup_vid_capture(call_med); - if (status != PJ_SUCCESS) - return status; - } - - /* Resume stream in encoding direction */ - status = pjmedia_vid_stream_resume(call_med->strm.v.stream, - PJMEDIA_DIR_ENCODING); + if (call_med->strm.v.cap_win_id == PJSUA_INVALID_ID) { + /* Setup the video capture first */ + status = setup_vid_capture(call_med); + if (status != PJ_SUCCESS) + return status; + } + + /* Resume stream in encoding direction */ + status = pjmedia_vid_stream_resume(call_med->strm.v.stream, + PJMEDIA_DIR_ENCODING); } else { pjsua_vid_win_id wid; - pjsua_vid_win *w; - - /* Pause stream in encoding direction */ - status = pjmedia_vid_stream_pause( call_med->strm.v.stream, - PJMEDIA_DIR_ENCODING); - - PJSUA_LOCK(); - - wid = vid_preview_get_win(call_med->strm.v.cap_dev, PJ_FALSE); - if (wid != PJSUA_INVALID_ID) { - w = &pjsua_var.win[wid]; - - /* Unsubscribe event */ - media_event_unsubscribe(NULL, &call_media_on_event, call_med, + pjsua_vid_win *w; + + /* Pause stream in encoding direction */ + status = pjmedia_vid_stream_pause( call_med->strm.v.stream, + PJMEDIA_DIR_ENCODING); + + PJSUA_LOCK(); + + wid = vid_preview_get_win(call_med->strm.v.cap_dev, PJ_FALSE); + if (wid != PJSUA_INVALID_ID) { + w = &pjsua_var.win[wid]; + + /* Unsubscribe event */ + media_event_unsubscribe(NULL, &call_media_on_event, call_med, w->vp_cap); - /* Disconnect from video conference */ - pjsua_vid_conf_disconnect(w->cap_slot, - call_med->strm.v.strm_enc_slot); + /* Disconnect from video conference */ + pjsua_vid_conf_disconnect(w->cap_slot, + call_med->strm.v.strm_enc_slot); - /* Decrement ref count of the video window */ - dec_vid_win(call_med->strm.v.cap_win_id); - call_med->strm.v.cap_win_id = PJSUA_INVALID_ID; - } - - PJSUA_UNLOCK(); + /* Decrement ref count of the video window */ + dec_vid_win(call_med->strm.v.cap_win_id); + call_med->strm.v.cap_win_id = PJSUA_INVALID_ID; + } + + PJSUA_UNLOCK(); } /* Sync provisional media from call media */ @@ -2590,26 +2589,26 @@ static pj_status_t call_set_tx_video(pjsua_call *call, static pj_status_t call_send_vid_keyframe(pjsua_call *call, - int med_idx) + int med_idx) { pjsua_call_media *call_med; /* Verify and normalize media index */ if (med_idx == -1) { - int first_active; - - call_get_vid_strm_info(call, &first_active, NULL, NULL, NULL); - if (first_active == -1) - return PJ_ENOTFOUND; + int first_active; + + call_get_vid_strm_info(call, &first_active, NULL, NULL, NULL); + if (first_active == -1) + return PJ_ENOTFOUND; - med_idx = first_active; + med_idx = first_active; } call_med = &call->media[med_idx]; /* Verify media type and stream instance. */ if (call_med->type != PJMEDIA_TYPE_VIDEO || !call_med->strm.v.stream) - return PJ_EINVAL; + return PJ_EINVAL; return pjmedia_vid_stream_send_keyframe(call_med->strm.v.stream); } @@ -2619,9 +2618,9 @@ static pj_status_t call_send_vid_keyframe(pjsua_call *call, * Start, stop, and/or manipulate video transmission for the specified call. */ PJ_DEF(pj_status_t) pjsua_call_set_vid_strm ( - pjsua_call_id call_id, - pjsua_call_vid_strm_op op, - const pjsua_call_vid_strm_op_param *param) + pjsua_call_id call_id, + pjsua_call_vid_strm_op op, + const pjsua_call_vid_strm_op_param *param) { pjsua_call *call; pjsip_dialog *dlg = NULL; @@ -2629,68 +2628,68 @@ PJ_DEF(pj_status_t) pjsua_call_set_vid_strm ( pj_status_t status; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(op != PJSUA_CALL_VID_STRM_NO_OP, PJ_EINVAL); PJ_LOG(4,(THIS_FILE, "Call %d: set video stream, op=%d", - call_id, op)); + call_id, op)); pj_log_push_indent(); status = acquire_call("pjsua_call_set_vid_strm()", call_id, &call, &dlg); if (status != PJ_SUCCESS) - goto on_return; + goto on_return; if (param) { - param_ = *param; + param_ = *param; } else { - pjsua_call_vid_strm_op_param_default(¶m_); + pjsua_call_vid_strm_op_param_default(¶m_); } /* If set to PJMEDIA_VID_DEFAULT_CAPTURE_DEV, replace it with * account default video capture device. */ if (param_.cap_dev == PJMEDIA_VID_DEFAULT_CAPTURE_DEV) { - pjsua_acc_config *acc_cfg = &pjsua_var.acc[call->acc_id].cfg; - param_.cap_dev = acc_cfg->vid_cap_dev; - - /* If the account default video capture device is - * PJMEDIA_VID_DEFAULT_CAPTURE_DEV, replace it with - * global default video capture device. - */ - if (param_.cap_dev == PJMEDIA_VID_DEFAULT_CAPTURE_DEV) { - pjmedia_vid_dev_info info; - pjmedia_vid_dev_get_info(param_.cap_dev, &info); - pj_assert(info.dir == PJMEDIA_DIR_CAPTURE); - param_.cap_dev = info.id; - } + pjsua_acc_config *acc_cfg = &pjsua_var.acc[call->acc_id].cfg; + param_.cap_dev = acc_cfg->vid_cap_dev; + + /* If the account default video capture device is + * PJMEDIA_VID_DEFAULT_CAPTURE_DEV, replace it with + * global default video capture device. + */ + if (param_.cap_dev == PJMEDIA_VID_DEFAULT_CAPTURE_DEV) { + pjmedia_vid_dev_info info; + pjmedia_vid_dev_get_info(param_.cap_dev, &info); + pj_assert(info.dir == PJMEDIA_DIR_CAPTURE); + param_.cap_dev = info.id; + } } switch (op) { case PJSUA_CALL_VID_STRM_ADD: - status = call_add_video(call, param_.cap_dev, param_.dir); - break; + status = call_add_video(call, param_.cap_dev, param_.dir); + break; case PJSUA_CALL_VID_STRM_REMOVE: - status = call_modify_video(call, param_.med_idx, PJMEDIA_DIR_NONE, - PJ_TRUE); - break; + status = call_modify_video(call, param_.med_idx, PJMEDIA_DIR_NONE, + PJ_TRUE); + break; case PJSUA_CALL_VID_STRM_CHANGE_DIR: - status = call_modify_video(call, param_.med_idx, param_.dir, PJ_FALSE); - break; + status = call_modify_video(call, param_.med_idx, param_.dir, PJ_FALSE); + break; case PJSUA_CALL_VID_STRM_CHANGE_CAP_DEV: - status = call_change_cap_dev(call, param_.med_idx, param_.cap_dev); - break; + status = call_change_cap_dev(call, param_.med_idx, param_.cap_dev); + break; case PJSUA_CALL_VID_STRM_START_TRANSMIT: - status = call_set_tx_video(call, param_.med_idx, PJ_TRUE); - break; + status = call_set_tx_video(call, param_.med_idx, PJ_TRUE); + break; case PJSUA_CALL_VID_STRM_STOP_TRANSMIT: - status = call_set_tx_video(call, param_.med_idx, PJ_FALSE); - break; + status = call_set_tx_video(call, param_.med_idx, PJ_FALSE); + break; case PJSUA_CALL_VID_STRM_SEND_KEYFRAME: - status = call_send_vid_keyframe(call, param_.med_idx); - break; + status = call_send_vid_keyframe(call, param_.med_idx); + break; default: - status = PJ_EINVALIDOP; - break; + status = PJ_EINVALIDOP; + break; } on_return: @@ -2709,7 +2708,7 @@ PJ_DEF(int) pjsua_call_get_vid_stream_idx(pjsua_call_id call_id) int first_active, first_inactive; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJSUA_LOCK(); call = &pjsua_var.calls[call_id]; @@ -2717,7 +2716,7 @@ PJ_DEF(int) pjsua_call_get_vid_stream_idx(pjsua_call_id call_id) PJSUA_UNLOCK(); if (first_active == -1) - return first_inactive; + return first_inactive; return first_active; } @@ -2735,11 +2734,11 @@ PJ_DEF(pj_bool_t) pjsua_call_vid_stream_is_running( pjsua_call_id call_id, pjsua_call_media *call_med; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); /* Verify and normalize media index */ if (med_idx == -1) { - med_idx = pjsua_call_get_vid_stream_idx(call_id); + med_idx = pjsua_call_get_vid_stream_idx(call_id); } call = &pjsua_var.calls[call_id]; @@ -2749,9 +2748,9 @@ PJ_DEF(pj_bool_t) pjsua_call_vid_stream_is_running( pjsua_call_id call_id, /* Verify if the stream is transmitting video */ if (call_med->type != PJMEDIA_TYPE_VIDEO || (call_med->dir & dir) == 0 || - !call_med->strm.v.stream) + !call_med->strm.v.stream) { - return PJ_FALSE; + return PJ_FALSE; } return pjmedia_vid_stream_is_running(call_med->strm.v.stream, dir); @@ -2775,10 +2774,10 @@ PJ_DEF(unsigned) pjsua_vid_conf_get_active_ports(void) * Enumerate all video conference ports. */ PJ_DEF(pj_status_t) pjsua_vid_conf_enum_ports( pjsua_conf_port_id id[], - unsigned *count) + unsigned *count) { return pjmedia_vid_conf_enum_ports(pjsua_var.vid_conf, - (unsigned*)id, count); + (unsigned*)id, count); } @@ -2786,8 +2785,8 @@ PJ_DEF(pj_status_t) pjsua_vid_conf_enum_ports( pjsua_conf_port_id id[], * Get information about the specified video conference port */ PJ_DEF(pj_status_t) pjsua_vid_conf_get_port_info( - pjsua_conf_port_id port_id, - pjsua_vid_conf_port_info *info) + pjsua_conf_port_id port_id, + pjsua_vid_conf_port_info *info) { pjmedia_vid_conf_port_info cinfo; unsigned i; @@ -2796,9 +2795,9 @@ PJ_DEF(pj_status_t) pjsua_vid_conf_get_port_info( PJ_ASSERT_RETURN(port_id >= 0, PJ_EINVAL); status = pjmedia_vid_conf_get_port_info(pjsua_var.vid_conf, - (unsigned)port_id, &cinfo); + (unsigned)port_id, &cinfo); if (status != PJ_SUCCESS) - return status; + return status; pj_bzero(info, sizeof(*info)); info->slot_id = port_id; @@ -2808,13 +2807,13 @@ PJ_DEF(pj_status_t) pjsua_vid_conf_get_port_info( /* Build array of listeners */ info->listener_cnt = cinfo.listener_cnt; for (i=0; ilisteners[i] = cinfo.listener_slots[i]; + info->listeners[i] = cinfo.listener_slots[i]; } /* Build array of transmitters */ info->transmitter_cnt = cinfo.transmitter_cnt; for (i=0; itransmitters[i] = cinfo.transmitter_slots[i]; + info->transmitters[i] = cinfo.transmitter_slots[i]; } return PJ_SUCCESS; @@ -2826,19 +2825,19 @@ PJ_DEF(pj_status_t) pjsua_vid_conf_get_port_info( * Add arbitrary video media port to PJSUA's video conference bridge. */ PJ_DEF(pj_status_t) pjsua_vid_conf_add_port( pj_pool_t *pool, - pjmedia_port *port, - const void *param, - pjsua_conf_port_id *p_id) + pjmedia_port *port, + const void *param, + pjsua_conf_port_id *p_id) { pj_status_t status; PJ_UNUSED_ARG(param); status = pjmedia_vid_conf_add_port(pjsua_var.vid_conf, pool, - port, NULL, NULL, (unsigned*)p_id); + port, NULL, NULL, (unsigned*)p_id); if (status != PJ_SUCCESS) { - if (p_id) - *p_id = PJSUA_INVALID_ID; + if (p_id) + *p_id = PJSUA_INVALID_ID; } return status; @@ -2860,15 +2859,15 @@ PJ_DEF(pj_status_t) pjsua_vid_conf_remove_port(pjsua_conf_port_id id) * Establish unidirectional video flow from souce to sink. */ PJ_DEF(pj_status_t) pjsua_vid_conf_connect( pjsua_conf_port_id source, - pjsua_conf_port_id sink, - const void *param) + pjsua_conf_port_id sink, + const void *param) { PJ_UNUSED_ARG(param); PJ_ASSERT_RETURN(source >= 0 && sink >= 0, PJ_EINVAL); return pjmedia_vid_conf_connect_port(pjsua_var.vid_conf, source, sink, - NULL); + NULL); } @@ -2876,7 +2875,7 @@ PJ_DEF(pj_status_t) pjsua_vid_conf_connect( pjsua_conf_port_id source, * Disconnect video flow from the source to destination port. */ PJ_DEF(pj_status_t) pjsua_vid_conf_disconnect(pjsua_conf_port_id source, - pjsua_conf_port_id sink) + pjsua_conf_port_id sink) { PJ_ASSERT_RETURN(source >= 0 && sink >= 0, PJ_EINVAL); @@ -2903,7 +2902,7 @@ PJ_DEF(pjsua_vid_win_id) pjsua_call_get_vid_win(pjsua_call_id call_id) unsigned i; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); /* Use PJSUA_LOCK() instead of acquire_call(): * https://github.com/pjsip/pjproject/issues/1371 @@ -2911,16 +2910,16 @@ PJ_DEF(pjsua_vid_win_id) pjsua_call_get_vid_win(pjsua_call_id call_id) PJSUA_LOCK(); if (!pjsua_call_is_active(call_id)) - goto on_return; + goto on_return; call = &pjsua_var.calls[call_id]; for (i = 0; i < call->med_cnt; ++i) { - if (call->media[i].type == PJMEDIA_TYPE_VIDEO && - (call->media[i].dir & PJMEDIA_DIR_DECODING)) - { - wid = call->media[i].strm.v.rdr_win_id; - break; - } + if (call->media[i].type == PJMEDIA_TYPE_VIDEO && + (call->media[i].dir & PJMEDIA_DIR_DECODING)) + { + wid = call->media[i].strm.v.rdr_win_id; + break; + } } on_return: @@ -2934,17 +2933,17 @@ PJ_DEF(pjsua_vid_win_id) pjsua_call_get_vid_win(pjsua_call_id call_id) * Get the video conference port identification associated with the call. */ PJ_DEF(pjsua_conf_port_id) pjsua_call_get_vid_conf_port( - pjsua_call_id call_id, - pjmedia_dir dir) + pjsua_call_id call_id, + pjmedia_dir dir) { pjsua_call *call; pjsua_conf_port_id port_id = PJSUA_INVALID_ID; unsigned i; PJ_ASSERT_RETURN(call_id>=0 && call_id<(int)pjsua_var.ua_cfg.max_calls, - PJ_EINVAL); + PJ_EINVAL); PJ_ASSERT_RETURN(dir==PJMEDIA_DIR_ENCODING || dir==PJMEDIA_DIR_DECODING, - PJ_EINVAL); + PJ_EINVAL); /* Use PJSUA_LOCK() instead of acquire_call(): * https://github.com/pjsip/pjproject/issues/1371 @@ -2952,18 +2951,18 @@ PJ_DEF(pjsua_conf_port_id) pjsua_call_get_vid_conf_port( PJSUA_LOCK(); if (!pjsua_call_is_active(call_id)) - goto on_return; + goto on_return; call = &pjsua_var.calls[call_id]; for (i = 0; i < call->med_cnt; ++i) { - if (call->media[i].type == PJMEDIA_TYPE_VIDEO && - (call->media[i].dir & dir)) - { - port_id = (dir==PJMEDIA_DIR_ENCODING)? - call->media[i].strm.v.strm_enc_slot : - call->media[i].strm.v.strm_dec_slot; - break; - } + if (call->media[i].type == PJMEDIA_TYPE_VIDEO && + (call->media[i].dir & dir)) + { + port_id = (dir==PJMEDIA_DIR_ENCODING)? + call->media[i].strm.v.strm_enc_slot : + call->media[i].strm.v.strm_dec_slot; + break; + } } on_return: diff --git a/pjsip/src/pjsua2-test/main.cpp b/pjsip/src/pjsua2-test/main.cpp index 46581a3c80..27e20dd6ea 100644 --- a/pjsip/src/pjsua2-test/main.cpp +++ b/pjsip/src/pjsua2-test/main.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2012 Teluu Inc. (http://www.teluu.com) * diff --git a/pjsip/src/pjsua2/account.cpp b/pjsip/src/pjsua2/account.cpp index 1b59148e19..8184b99db2 100644 --- a/pjsip/src/pjsua2/account.cpp +++ b/pjsip/src/pjsua2/account.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -25,16 +24,16 @@ using namespace pj; using namespace std; -#define THIS_FILE "account.cpp" +#define THIS_FILE "account.cpp" /////////////////////////////////////////////////////////////////////////////// void RtcpFbCap::fromPj(const pjmedia_rtcp_fb_cap &prm) { this->codecId = pj2Str(prm.codec_id); - this->type = prm.type; + this->type = prm.type; this->typeName = pj2Str(prm.type_name); - this->param = pj2Str(prm.param); + this->param = pj2Str(prm.param); } pjmedia_rtcp_fb_cap RtcpFbCap::toPj() const @@ -43,9 +42,9 @@ pjmedia_rtcp_fb_cap RtcpFbCap::toPj() const pj_bzero(&cap, sizeof(cap)); cap.codec_id = str2Pj(this->codecId); - cap.type = this->type; + cap.type = this->type; cap.type_name = str2Pj(this->typeName); - cap.param = str2Pj(this->param); + cap.param = str2Pj(this->param); return cap; } @@ -64,9 +63,9 @@ void RtcpFbConfig::fromPj(const pjmedia_rtcp_fb_setting &prm) this->dontUseAvpf = PJ2BOOL(prm.dont_use_avpf); this->caps.clear(); for (unsigned i = 0; i < prm.cap_count; ++i) { - RtcpFbCap cap; - cap.fromPj(prm.caps[i]); - this->caps.push_back(cap); + RtcpFbCap cap; + cap.fromPj(prm.caps[i]); + this->caps.push_back(cap); } } @@ -76,9 +75,9 @@ pjmedia_rtcp_fb_setting RtcpFbConfig::toPj() const pj_bzero(&setting, sizeof(setting)); setting.dont_use_avpf = this->dontUseAvpf; - setting.cap_count = (unsigned)this->caps.size(); + setting.cap_count = (unsigned)this->caps.size(); for (unsigned i = 0; i < setting.cap_count; ++i) { - setting.caps[i] = this->caps[i].toPj(); + setting.caps[i] = this->caps[i].toPj(); } return setting; @@ -87,32 +86,32 @@ pjmedia_rtcp_fb_setting RtcpFbConfig::toPj() const void RtcpFbConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("RtcpFbConfig"); - NODE_READ_BOOL (this_node, dontUseAvpf); + NODE_READ_BOOL (this_node, dontUseAvpf); ContainerNode cap_node = this_node.readArray("caps"); this->caps.clear(); while (cap_node.hasUnread()) { - RtcpFbCap cap; - NODE_READ_STRING (cap_node, cap.codecId); - NODE_READ_NUM_T (cap_node, pjmedia_rtcp_fb_type, cap.type); - NODE_READ_STRING (cap_node, cap.typeName); - NODE_READ_STRING (cap_node, cap.param); - this->caps.push_back(cap); + RtcpFbCap cap; + NODE_READ_STRING (cap_node, cap.codecId); + NODE_READ_NUM_T (cap_node, pjmedia_rtcp_fb_type, cap.type); + NODE_READ_STRING (cap_node, cap.typeName); + NODE_READ_STRING (cap_node, cap.param); + this->caps.push_back(cap); } } void RtcpFbConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("RtcpFbConfig"); - NODE_WRITE_BOOL (this_node, dontUseAvpf); + NODE_WRITE_BOOL (this_node, dontUseAvpf); ContainerNode cap_node = this_node.writeNewArray("caps"); for (unsigned i=0; icaps.size(); ++i) { - NODE_WRITE_STRING (cap_node, this->caps[i].codecId); - NODE_WRITE_NUM_T (cap_node, pjmedia_rtcp_fb_type, - this->caps[i].type); - NODE_WRITE_STRING (cap_node, this->caps[i].typeName); - NODE_WRITE_STRING (cap_node, this->caps[i].param); + NODE_WRITE_STRING (cap_node, this->caps[i].codecId); + NODE_WRITE_NUM_T (cap_node, pjmedia_rtcp_fb_type, + this->caps[i].type); + NODE_WRITE_STRING (cap_node, this->caps[i].typeName); + NODE_WRITE_STRING (cap_node, this->caps[i].param); } } @@ -120,17 +119,17 @@ void RtcpFbConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) void SrtpCrypto::fromPj(const pjmedia_srtp_crypto &prm) { - this->key = pj2Str(prm.key); - this->name = pj2Str(prm.name); - this->flags = prm.flags; + this->key = pj2Str(prm.key); + this->name = pj2Str(prm.name); + this->flags = prm.flags; } pjmedia_srtp_crypto SrtpCrypto::toPj() const { pjmedia_srtp_crypto crypto; - crypto.key = str2Pj(this->key); - crypto.name = str2Pj(this->name); + crypto.key = str2Pj(this->key); + crypto.name = str2Pj(this->name); crypto.flags = this->flags; return crypto; @@ -149,14 +148,14 @@ void SrtpOpt::fromPj(const pjsua_srtp_opt &prm) { this->cryptos.clear(); for (unsigned i = 0; i < prm.crypto_count; ++i) { - SrtpCrypto crypto; - crypto.fromPj(prm.crypto[i]); - this->cryptos.push_back(crypto); + SrtpCrypto crypto; + crypto.fromPj(prm.crypto[i]); + this->cryptos.push_back(crypto); } this->keyings.clear(); for (unsigned i = 0; i < prm.keying_count; ++i) { - this->keyings.push_back(prm.keying[i]); + this->keyings.push_back(prm.keying[i]); } } @@ -168,12 +167,12 @@ pjsua_srtp_opt SrtpOpt::toPj() const opt.crypto_count = (unsigned)this->cryptos.size(); for (unsigned i = 0; i < opt.crypto_count; ++i) { - opt.crypto[i] = this->cryptos[i].toPj(); + opt.crypto[i] = this->cryptos[i].toPj(); } opt.keying_count = (unsigned)this->keyings.size(); for (unsigned i = 0; i < opt.keying_count; ++i) { - opt.keying[i] = (pjmedia_srtp_keying_method)this->keyings[i]; + opt.keying[i] = (pjmedia_srtp_keying_method)this->keyings[i]; } return opt; @@ -186,19 +185,19 @@ void SrtpOpt::readObject(const ContainerNode &node) PJSUA2_THROW(Error) ContainerNode crypto_node = this_node.readArray("cryptos"); this->cryptos.clear(); while (crypto_node.hasUnread()) { - SrtpCrypto crypto; - NODE_READ_STRING (crypto_node, crypto.key); - NODE_READ_STRING (crypto_node, crypto.name); - NODE_READ_UNSIGNED (crypto_node, crypto.flags); - this->cryptos.push_back(crypto); + SrtpCrypto crypto; + NODE_READ_STRING (crypto_node, crypto.key); + NODE_READ_STRING (crypto_node, crypto.name); + NODE_READ_UNSIGNED (crypto_node, crypto.flags); + this->cryptos.push_back(crypto); } ContainerNode keying_node = this_node.readArray("keyings"); this->keyings.clear(); while (keying_node.hasUnread()) { - unsigned keying; - NODE_READ_UNSIGNED (keying_node, keying); - this->keyings.push_back(keying); + unsigned keying; + NODE_READ_UNSIGNED (keying_node, keying); + this->keyings.push_back(keying); } } @@ -208,55 +207,55 @@ void SrtpOpt::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) ContainerNode crypto_node = this_node.writeNewArray("cryptos"); for (unsigned i=0; icryptos.size(); ++i) { - NODE_WRITE_STRING (crypto_node, this->cryptos[i].key); - NODE_WRITE_STRING (crypto_node, this->cryptos[i].name); - NODE_WRITE_UNSIGNED (crypto_node, this->cryptos[i].flags); + NODE_WRITE_STRING (crypto_node, this->cryptos[i].key); + NODE_WRITE_STRING (crypto_node, this->cryptos[i].name); + NODE_WRITE_UNSIGNED (crypto_node, this->cryptos[i].flags); } ContainerNode keying_node = this_node.writeNewArray("keyings"); for (unsigned i=0; ikeyings.size(); ++i) { - NODE_WRITE_UNSIGNED (keying_node, this->keyings[i]); + NODE_WRITE_UNSIGNED (keying_node, this->keyings[i]); } } /////////////////////////////////////////////////////////////////////////////// void AccountRegConfig::readObject(const ContainerNode &node) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountRegConfig"); - NODE_READ_STRING (this_node, registrarUri); - NODE_READ_BOOL (this_node, registerOnAdd); - NODE_READ_UNSIGNED (this_node, timeoutSec); - NODE_READ_UNSIGNED (this_node, retryIntervalSec); - NODE_READ_UNSIGNED (this_node, firstRetryIntervalSec); - NODE_READ_UNSIGNED (this_node, randomRetryIntervalSec); - NODE_READ_UNSIGNED (this_node, delayBeforeRefreshSec); - NODE_READ_BOOL (this_node, dropCallsOnFail); - NODE_READ_UNSIGNED (this_node, unregWaitMsec); - NODE_READ_UNSIGNED (this_node, proxyUse); - NODE_READ_STRING (this_node, contactParams); + NODE_READ_STRING (this_node, registrarUri); + NODE_READ_BOOL (this_node, registerOnAdd); + NODE_READ_UNSIGNED (this_node, timeoutSec); + NODE_READ_UNSIGNED (this_node, retryIntervalSec); + NODE_READ_UNSIGNED (this_node, firstRetryIntervalSec); + NODE_READ_UNSIGNED (this_node, randomRetryIntervalSec); + NODE_READ_UNSIGNED (this_node, delayBeforeRefreshSec); + NODE_READ_BOOL (this_node, dropCallsOnFail); + NODE_READ_UNSIGNED (this_node, unregWaitMsec); + NODE_READ_UNSIGNED (this_node, proxyUse); + NODE_READ_STRING (this_node, contactParams); readSipHeaders(this_node, "headers", headers); } void AccountRegConfig::writeObject(ContainerNode &node) const - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountRegConfig"); - NODE_WRITE_STRING (this_node, registrarUri); - NODE_WRITE_BOOL (this_node, registerOnAdd); - NODE_WRITE_UNSIGNED (this_node, timeoutSec); - NODE_WRITE_UNSIGNED (this_node, retryIntervalSec); - NODE_WRITE_UNSIGNED (this_node, firstRetryIntervalSec); - NODE_WRITE_UNSIGNED (this_node, randomRetryIntervalSec); - NODE_WRITE_UNSIGNED (this_node, delayBeforeRefreshSec); - NODE_WRITE_BOOL (this_node, dropCallsOnFail); - NODE_WRITE_UNSIGNED (this_node, unregWaitMsec); - NODE_WRITE_UNSIGNED (this_node, proxyUse); - NODE_WRITE_STRING (this_node, contactParams); + NODE_WRITE_STRING (this_node, registrarUri); + NODE_WRITE_BOOL (this_node, registerOnAdd); + NODE_WRITE_UNSIGNED (this_node, timeoutSec); + NODE_WRITE_UNSIGNED (this_node, retryIntervalSec); + NODE_WRITE_UNSIGNED (this_node, firstRetryIntervalSec); + NODE_WRITE_UNSIGNED (this_node, randomRetryIntervalSec); + NODE_WRITE_UNSIGNED (this_node, delayBeforeRefreshSec); + NODE_WRITE_BOOL (this_node, dropCallsOnFail); + NODE_WRITE_UNSIGNED (this_node, unregWaitMsec); + NODE_WRITE_UNSIGNED (this_node, proxyUse); + NODE_WRITE_STRING (this_node, contactParams); writeSipHeaders(this_node, "headers", headers); } @@ -264,50 +263,50 @@ void AccountRegConfig::writeObject(ContainerNode &node) const /////////////////////////////////////////////////////////////////////////////// void AccountSipConfig::readObject(const ContainerNode &node) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountSipConfig"); - NODE_READ_STRINGV (this_node, proxies); - NODE_READ_STRING (this_node, contactForced); - NODE_READ_STRING (this_node, contactParams); - NODE_READ_STRING (this_node, contactUriParams); - NODE_READ_BOOL (this_node, authInitialEmpty); - NODE_READ_STRING (this_node, authInitialAlgorithm); - NODE_READ_INT (this_node, transportId); + NODE_READ_STRINGV (this_node, proxies); + NODE_READ_STRING (this_node, contactForced); + NODE_READ_STRING (this_node, contactParams); + NODE_READ_STRING (this_node, contactUriParams); + NODE_READ_BOOL (this_node, authInitialEmpty); + NODE_READ_STRING (this_node, authInitialAlgorithm); + NODE_READ_INT (this_node, transportId); ContainerNode creds_node = this_node.readArray("authCreds"); authCreds.resize(0); while (creds_node.hasUnread()) { - AuthCredInfo cred; - cred.readObject(creds_node); - authCreds.push_back(cred); + AuthCredInfo cred; + cred.readObject(creds_node); + authCreds.push_back(cred); } } void AccountSipConfig::writeObject(ContainerNode &node) const - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountSipConfig"); - NODE_WRITE_STRINGV (this_node, proxies); - NODE_WRITE_STRING (this_node, contactForced); - NODE_WRITE_STRING (this_node, contactParams); - NODE_WRITE_STRING (this_node, contactUriParams); - NODE_WRITE_BOOL (this_node, authInitialEmpty); - NODE_WRITE_STRING (this_node, authInitialAlgorithm); - NODE_WRITE_INT (this_node, transportId); + NODE_WRITE_STRINGV (this_node, proxies); + NODE_WRITE_STRING (this_node, contactForced); + NODE_WRITE_STRING (this_node, contactParams); + NODE_WRITE_STRING (this_node, contactUriParams); + NODE_WRITE_BOOL (this_node, authInitialEmpty); + NODE_WRITE_STRING (this_node, authInitialAlgorithm); + NODE_WRITE_INT (this_node, transportId); ContainerNode creds_node = this_node.writeNewArray("authCreds"); for (unsigned i=0; i PJ_ARRAY_SIZE(ret.cred_info)) - PJSUA2_RAISE_ERROR(PJ_ETOOMANY); + PJSUA2_RAISE_ERROR(PJ_ETOOMANY); for (i=0; irealm = str2Pj(src.realm); - dst->scheme = str2Pj(src.scheme); - dst->username = str2Pj(src.username); - dst->data_type = src.dataType; - dst->data = str2Pj(src.data); - dst->ext.aka.k = str2Pj(src.akaK); - dst->ext.aka.op = str2Pj(src.akaOp); - dst->ext.aka.amf= str2Pj(src.akaAmf); - - ret.cred_count++; + const AuthCredInfo &src = sipConfig.authCreds[i]; + pjsip_cred_info *dst = &ret.cred_info[i]; + + dst->realm = str2Pj(src.realm); + dst->scheme = str2Pj(src.scheme); + dst->username = str2Pj(src.username); + dst->data_type = src.dataType; + dst->data = str2Pj(src.data); + dst->ext.aka.k = str2Pj(src.akaK); + dst->ext.aka.op = str2Pj(src.akaOp); + dst->ext.aka.amf= str2Pj(src.akaAmf); + + ret.cred_count++; } ret.proxy_cnt = 0; if (sipConfig.proxies.size() > PJ_ARRAY_SIZE(ret.proxy)) - PJSUA2_RAISE_ERROR(PJ_ETOOMANY); + PJSUA2_RAISE_ERROR(PJ_ETOOMANY); for (i=0; inext; + hdr = hdr->next; } // AccountSipConfig sipConfig.authCreds.clear(); for (i=0; inext; + SipHeader new_hdr; + new_hdr.fromPj(hdr); + presConfig.headers.push_back(new_hdr); + hdr = hdr->next; } - presConfig.publishEnabled = PJ2BOOL(prm.publish_enabled); - presConfig.publishQueue = PJ2BOOL(prm.publish_opt.queue_request); + presConfig.publishEnabled = PJ2BOOL(prm.publish_enabled); + presConfig.publishQueue = PJ2BOOL(prm.publish_opt.queue_request); presConfig.publishShutdownWaitMsec = prm.unpublish_max_wait_time_msec; - presConfig.pidfTupleId = pj2Str(prm.pidf_tuple_id); + presConfig.pidfTupleId = pj2Str(prm.pidf_tuple_id); // AccountMwiConfig - mwiConfig.enabled = PJ2BOOL(prm.mwi_enabled); - mwiConfig.expirationSec = prm.mwi_expires; + mwiConfig.enabled = PJ2BOOL(prm.mwi_enabled); + mwiConfig.expirationSec = prm.mwi_expires; // AccountNatConfig - natConfig.sipStunUse = prm.sip_stun_use; - natConfig.mediaStunUse = prm.media_stun_use; - natConfig.sipUpnpUse = prm.sip_upnp_use; - natConfig.mediaUpnpUse = prm.media_upnp_use; - natConfig.nat64Opt = prm.nat64_opt; + natConfig.sipStunUse = prm.sip_stun_use; + natConfig.mediaStunUse = prm.media_stun_use; + natConfig.sipUpnpUse = prm.sip_upnp_use; + natConfig.mediaUpnpUse = prm.media_upnp_use; + natConfig.nat64Opt = prm.nat64_opt; if (prm.ice_cfg_use == PJSUA_ICE_CONFIG_USE_CUSTOM) { - natConfig.iceEnabled = PJ2BOOL(prm.ice_cfg.enable_ice); - natConfig.iceTrickle = prm.ice_cfg.ice_opt.trickle; - natConfig.iceMaxHostCands = prm.ice_cfg.ice_max_host_cands; - natConfig.iceAggressiveNomination = - PJ2BOOL(prm.ice_cfg.ice_opt.aggressive); - natConfig.iceNominatedCheckDelayMsec = - prm.ice_cfg.ice_opt.nominated_check_delay; - natConfig.iceWaitNominationTimeoutMsec = - prm.ice_cfg.ice_opt.controlled_agent_want_nom_timeout; - natConfig.iceNoRtcp = PJ2BOOL(prm.ice_cfg.ice_no_rtcp); - natConfig.iceAlwaysUpdate = PJ2BOOL(prm.ice_cfg.ice_always_update); + natConfig.iceEnabled = PJ2BOOL(prm.ice_cfg.enable_ice); + natConfig.iceTrickle = prm.ice_cfg.ice_opt.trickle; + natConfig.iceMaxHostCands = prm.ice_cfg.ice_max_host_cands; + natConfig.iceAggressiveNomination = + PJ2BOOL(prm.ice_cfg.ice_opt.aggressive); + natConfig.iceNominatedCheckDelayMsec = + prm.ice_cfg.ice_opt.nominated_check_delay; + natConfig.iceWaitNominationTimeoutMsec = + prm.ice_cfg.ice_opt.controlled_agent_want_nom_timeout; + natConfig.iceNoRtcp = PJ2BOOL(prm.ice_cfg.ice_no_rtcp); + natConfig.iceAlwaysUpdate = PJ2BOOL(prm.ice_cfg.ice_always_update); } else { - pjsua_media_config default_mcfg; - if (!mcfg) { - pjsua_media_config_default(&default_mcfg); - mcfg = &default_mcfg; - } - natConfig.iceEnabled = PJ2BOOL(mcfg->enable_ice); - natConfig.iceMaxHostCands= mcfg->ice_max_host_cands; - natConfig.iceAggressiveNomination = PJ2BOOL(mcfg->ice_opt.aggressive); - natConfig.iceNominatedCheckDelayMsec = - mcfg->ice_opt.nominated_check_delay; - natConfig.iceWaitNominationTimeoutMsec = - mcfg->ice_opt.controlled_agent_want_nom_timeout; - natConfig.iceNoRtcp = PJ2BOOL(mcfg->ice_no_rtcp); - natConfig.iceAlwaysUpdate = PJ2BOOL(mcfg->ice_always_update); + pjsua_media_config default_mcfg; + if (!mcfg) { + pjsua_media_config_default(&default_mcfg); + mcfg = &default_mcfg; + } + natConfig.iceEnabled = PJ2BOOL(mcfg->enable_ice); + natConfig.iceMaxHostCands= mcfg->ice_max_host_cands; + natConfig.iceAggressiveNomination = PJ2BOOL(mcfg->ice_opt.aggressive); + natConfig.iceNominatedCheckDelayMsec = + mcfg->ice_opt.nominated_check_delay; + natConfig.iceWaitNominationTimeoutMsec = + mcfg->ice_opt.controlled_agent_want_nom_timeout; + natConfig.iceNoRtcp = PJ2BOOL(mcfg->ice_no_rtcp); + natConfig.iceAlwaysUpdate = PJ2BOOL(mcfg->ice_always_update); } if (prm.turn_cfg_use == PJSUA_TURN_CONFIG_USE_CUSTOM) { - natConfig.turnEnabled = PJ2BOOL(prm.turn_cfg.enable_turn); - natConfig.turnServer = pj2Str(prm.turn_cfg.turn_server); - natConfig.turnConnType = prm.turn_cfg.turn_conn_type; - natConfig.turnUserName = - pj2Str(prm.turn_cfg.turn_auth_cred.data.static_cred.username); - natConfig.turnPasswordType = - prm.turn_cfg.turn_auth_cred.data.static_cred.data_type; - natConfig.turnPassword = - pj2Str(prm.turn_cfg.turn_auth_cred.data.static_cred.data); + natConfig.turnEnabled = PJ2BOOL(prm.turn_cfg.enable_turn); + natConfig.turnServer = pj2Str(prm.turn_cfg.turn_server); + natConfig.turnConnType = prm.turn_cfg.turn_conn_type; + natConfig.turnUserName = + pj2Str(prm.turn_cfg.turn_auth_cred.data.static_cred.username); + natConfig.turnPasswordType = + prm.turn_cfg.turn_auth_cred.data.static_cred.data_type; + natConfig.turnPassword = + pj2Str(prm.turn_cfg.turn_auth_cred.data.static_cred.data); } else { - pjsua_media_config default_mcfg; - if (!mcfg) { - pjsua_media_config_default(&default_mcfg); - mcfg = &default_mcfg; - } - natConfig.turnEnabled = PJ2BOOL(mcfg->enable_turn); - natConfig.turnServer = pj2Str(mcfg->turn_server); - natConfig.turnConnType = mcfg->turn_conn_type; - natConfig.turnUserName = - pj2Str(mcfg->turn_auth_cred.data.static_cred.username); - natConfig.turnPasswordType = - mcfg->turn_auth_cred.data.static_cred.data_type; - natConfig.turnPassword = - pj2Str(mcfg->turn_auth_cred.data.static_cred.data); + pjsua_media_config default_mcfg; + if (!mcfg) { + pjsua_media_config_default(&default_mcfg); + mcfg = &default_mcfg; + } + natConfig.turnEnabled = PJ2BOOL(mcfg->enable_turn); + natConfig.turnServer = pj2Str(mcfg->turn_server); + natConfig.turnConnType = mcfg->turn_conn_type; + natConfig.turnUserName = + pj2Str(mcfg->turn_auth_cred.data.static_cred.username); + natConfig.turnPasswordType = + mcfg->turn_auth_cred.data.static_cred.data_type; + natConfig.turnPassword = + pj2Str(mcfg->turn_auth_cred.data.static_cred.data); } - natConfig.contactRewriteUse = prm.allow_contact_rewrite; + natConfig.contactRewriteUse = prm.allow_contact_rewrite; natConfig.contactRewriteMethod = prm.contact_rewrite_method; - natConfig.contactUseSrcPort = prm.contact_use_src_port; - natConfig.viaRewriteUse = prm.allow_via_rewrite; - natConfig.sdpNatRewriteUse = prm.allow_sdp_nat_rewrite; - natConfig.sipOutboundUse = prm.use_rfc5626; + natConfig.contactUseSrcPort = prm.contact_use_src_port; + natConfig.viaRewriteUse = prm.allow_via_rewrite; + natConfig.sdpNatRewriteUse = prm.allow_sdp_nat_rewrite; + natConfig.sipOutboundUse = prm.use_rfc5626; natConfig.sipOutboundInstanceId = pj2Str(prm.rfc5626_instance_id); - natConfig.sipOutboundRegId = pj2Str(prm.rfc5626_reg_id); - natConfig.udpKaIntervalSec = prm.ka_interval; - natConfig.udpKaData = pj2Str(prm.ka_data); + natConfig.sipOutboundRegId = pj2Str(prm.rfc5626_reg_id); + natConfig.udpKaIntervalSec = prm.ka_interval; + natConfig.udpKaData = pj2Str(prm.ka_data); // AccountMediaConfig mediaConfig.transportConfig.fromPj(prm.rtp_cfg); mediaConfig.lockCodecEnabled= PJ2BOOL(prm.lock_codec); #if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0) - mediaConfig.streamKaEnabled = PJ2BOOL(prm.use_stream_ka); + mediaConfig.streamKaEnabled = PJ2BOOL(prm.use_stream_ka); #else - mediaConfig.streamKaEnabled = false; + mediaConfig.streamKaEnabled = false; #endif - mediaConfig.srtpUse = prm.use_srtp; + mediaConfig.srtpUse = prm.use_srtp; mediaConfig.srtpSecureSignaling = prm.srtp_secure_signaling; mediaConfig.srtpOpt.fromPj(prm.srtp_opt); - mediaConfig.ipv6Use = prm.ipv6_media_use; - mediaConfig.rtcpMuxEnabled = PJ2BOOL(prm.enable_rtcp_mux); + mediaConfig.ipv6Use = prm.ipv6_media_use; + mediaConfig.rtcpMuxEnabled = PJ2BOOL(prm.enable_rtcp_mux); mediaConfig.rtcpFbConfig.fromPj(prm.rtcp_fb_cfg); - mediaConfig.useLoopMedTp = PJ2BOOL(prm.use_loop_med_tp); - mediaConfig.enableLoopback = PJ2BOOL(prm.enable_loopback); - mediaConfig.rtcpXrEnabled = PJ2BOOL(prm.enable_rtcp_xr); + mediaConfig.useLoopMedTp = PJ2BOOL(prm.use_loop_med_tp); + mediaConfig.enableLoopback = PJ2BOOL(prm.enable_loopback); + mediaConfig.rtcpXrEnabled = PJ2BOOL(prm.enable_rtcp_xr); // AccountVideoConfig - videoConfig.autoShowIncoming = PJ2BOOL(prm.vid_in_auto_show); - videoConfig.autoTransmitOutgoing = PJ2BOOL(prm.vid_out_auto_transmit); - videoConfig.windowFlags = prm.vid_wnd_flags; - videoConfig.defaultCaptureDevice = prm.vid_cap_dev; - videoConfig.defaultRenderDevice = prm.vid_rend_dev; - videoConfig.rateControlMethod = prm.vid_stream_rc_cfg.method; - videoConfig.rateControlBandwidth = prm.vid_stream_rc_cfg.bandwidth; - videoConfig.startKeyframeCount = prm.vid_stream_sk_cfg.count; - videoConfig.startKeyframeInterval = prm.vid_stream_sk_cfg.interval; + videoConfig.autoShowIncoming = PJ2BOOL(prm.vid_in_auto_show); + videoConfig.autoTransmitOutgoing = PJ2BOOL(prm.vid_out_auto_transmit); + videoConfig.windowFlags = prm.vid_wnd_flags; + videoConfig.defaultCaptureDevice = prm.vid_cap_dev; + videoConfig.defaultRenderDevice = prm.vid_rend_dev; + videoConfig.rateControlMethod = prm.vid_stream_rc_cfg.method; + videoConfig.rateControlBandwidth = prm.vid_stream_rc_cfg.bandwidth; + videoConfig.startKeyframeCount = prm.vid_stream_sk_cfg.count; + videoConfig.startKeyframeInterval = prm.vid_stream_sk_cfg.interval; // AccountIpChangeConfig ipChangeConfig.shutdownTp = PJ2BOOL(prm.ip_change_cfg.shutdown_tp); @@ -952,19 +951,19 @@ void AccountConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) void AccountInfo::fromPj(const pjsua_acc_info &pai) { - id = pai.id; - isDefault = pai.is_default != 0; - uri = pj2Str(pai.acc_uri); - regIsConfigured = pai.has_registration != 0; - regIsActive = pai.has_registration && pai.expires > 0 && - pai.expires != PJSIP_EXPIRES_NOT_SPECIFIED && - (pai.status / 100 == 2); - regExpiresSec = pai.expires; - regStatus = pai.status; - regStatusText = pj2Str(pai.status_text); - regLastErr = pai.reg_last_err; - onlineStatus = pai.online_status != 0; - onlineStatusText = pj2Str(pai.online_status_text); + id = pai.id; + isDefault = pai.is_default != 0; + uri = pj2Str(pai.acc_uri); + regIsConfigured = pai.has_registration != 0; + regIsActive = pai.has_registration && pai.expires > 0 && + pai.expires != PJSIP_EXPIRES_NOT_SPECIFIED && + (pai.status / 100 == 2); + regExpiresSec = pai.expires; + regStatus = pai.status; + regStatusText = pj2Str(pai.status_text); + regLastErr = pai.reg_last_err; + onlineStatus = pai.online_status != 0; + onlineStatusText = pj2Str(pai.online_status_text); } /////////////////////////////////////////////////////////////////////////////// @@ -990,8 +989,8 @@ void Account::create(const AccountConfig &acc_cfg, acc_cfg.toPj(pj_acc_cfg); for (unsigned i = 0; i < pj_acc_cfg.cred_count; ++i) { - pjsip_cred_info *dst = &pj_acc_cfg.cred_info[i]; - dst->ext.aka.cb = (pjsip_cred_cb)Endpoint::on_auth_create_aka_response_callback; + pjsip_cred_info *dst = &pj_acc_cfg.cred_info[i]; + dst->ext.aka.cb = (pjsip_cred_cb)Endpoint::on_auth_create_aka_response_callback; } pj_acc_cfg.user_data = (void*)this; PJSUA2_CHECK_EXPR( pjsua_acc_add(&pj_acc_cfg, make_default, &id) ); @@ -1002,17 +1001,17 @@ void Account::shutdown() if (isValid() && pjsua_get_state() < PJSUA_STATE_CLOSING) { #if !DEPRECATED_FOR_TICKET_2232 // Cleanup buddies in the buddy list - while(buddyList.size() > 0) { - Buddy *b = buddyList[0]; - delete b; /* this will remove itself from the list */ - } + while(buddyList.size() > 0) { + Buddy *b = buddyList[0]; + delete b; /* this will remove itself from the list */ + } #endif - // This caused error message of "Error: cannot find Account.." - // when Endpoint::on_reg_started() is called for unregistration. - //pjsua_acc_set_user_data(id, NULL); + // This caused error message of "Error: cannot find Account.." + // when Endpoint::on_reg_started() is called for unregistration. + //pjsua_acc_set_user_data(id, NULL); - pjsua_acc_del(id); + pjsua_acc_del(id); } } @@ -1071,14 +1070,14 @@ Account::setOnlineStatus(const PresenceStatus &pres_st) PJSUA2_THROW(Error) pjrpid_element pj_rpid; pj_bzero(&pj_rpid, sizeof(pj_rpid)); - pj_rpid.type = PJRPID_ELEMENT_TYPE_PERSON; - pj_rpid.activity = pres_st.activity; - pj_rpid.id = str2Pj(pres_st.rpidId); - pj_rpid.note = str2Pj(pres_st.note); + pj_rpid.type = PJRPID_ELEMENT_TYPE_PERSON; + pj_rpid.activity = pres_st.activity; + pj_rpid.id = str2Pj(pres_st.rpidId); + pj_rpid.note = str2Pj(pres_st.note); PJSUA2_CHECK_EXPR( pjsua_acc_set_online_status2( - id, pres_st.status == PJSUA_BUDDY_STATUS_ONLINE, - &pj_rpid) ); + id, pres_st.status == PJSUA_BUDDY_STATUS_ONLINE, + &pj_rpid) ); } void Account::setTransport(TransportId tp_id) PJSUA2_THROW(Error) @@ -1089,14 +1088,14 @@ void Account::setTransport(TransportId tp_id) PJSUA2_THROW(Error) void Account::presNotify(const PresNotifyParam &prm) PJSUA2_THROW(Error) { pj_str_t pj_state_str = str2Pj(prm.stateStr); - pj_str_t pj_reason = str2Pj(prm.reason); + pj_str_t pj_reason = str2Pj(prm.reason); pjsua_msg_data msg_data; prm.txOption.toPj(msg_data); PJSUA2_CHECK_EXPR( pjsua_pres_notify(id, (pjsua_srv_pres*)prm.srvPres, - prm.state, &pj_state_str, - &pj_reason, prm.withBody, - &msg_data) ); + prm.state, &pj_state_str, + &pj_reason, prm.withBody, + &msg_data) ); } #if !DEPRECATED_FOR_TICKET_2232 @@ -1114,7 +1113,7 @@ BuddyVector2 Account::enumBuddies2() const PJSUA2_THROW(Error) PJSUA2_CHECK_EXPR( pjsua_enum_buddies(ids, &count) ); for (i = 0; i < count; ++i) { - bv2.push_back(Buddy(ids[i])); + bv2.push_back(Buddy(ids[i])); } return bv2; @@ -1122,16 +1121,16 @@ BuddyVector2 Account::enumBuddies2() const PJSUA2_THROW(Error) #if !DEPRECATED_FOR_TICKET_2232 Buddy* Account::findBuddy(string uri, FindBuddyMatch *buddy_match) const - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { if (!buddy_match) { - static FindBuddyMatch def_bm; - buddy_match = &def_bm; + static FindBuddyMatch def_bm; + buddy_match = &def_bm; } for (unsigned i = 0; i < buddyList.size(); i++) { - if (buddy_match->match(uri, *buddyList[i])) - return buddyList[i]; + if (buddy_match->match(uri, *buddyList[i])) + return buddyList[i]; } PJSUA2_RAISE_ERROR(PJ_ENOTFOUND); } @@ -1146,7 +1145,7 @@ Buddy Account::findBuddy2(string uri) const PJSUA2_THROW(Error) bud_id = pjsua_buddy_find(&pj_uri); if (id == PJSUA_INVALID_ID) { - PJSUA2_RAISE_ERROR(PJ_ENOTFOUND); + PJSUA2_RAISE_ERROR(PJ_ENOTFOUND); } Buddy buddy(bud_id); @@ -1171,10 +1170,10 @@ void Account::removeBuddy(Buddy *buddy) BuddyVector::iterator it; for (it = buddyList.begin(); it != buddyList.end(); it++) { - if (*it == buddy) { - buddyList.erase(it); - return; - } + if (*it == buddy) { + buddyList.erase(it); + return; + } } pj_assert(!"Bug! Buddy to be removed is not in the buddy list!"); diff --git a/pjsip/src/pjsua2/call.cpp b/pjsip/src/pjsua2/call.cpp index 62a2245440..489a443680 100644 --- a/pjsip/src/pjsua2/call.cpp +++ b/pjsip/src/pjsua2/call.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2012-2013 Teluu Inc. (http://www.teluu.com) * @@ -27,7 +26,7 @@ using namespace std; #include -#define THIS_FILE "call.cpp" +#define THIS_FILE "call.cpp" /////////////////////////////////////////////////////////////////////////////// @@ -133,13 +132,13 @@ void MediaTransportInfo::fromPj(const pjmedia_transport_info &info) localRtpName = localRtcpName = srcRtpName = srcRtcpName = ""; if (pj_sockaddr_has_addr(&info.sock_info.rtp_addr_name)) { pj_sockaddr_print(&info.sock_info.rtp_addr_name, straddr, - sizeof(straddr), 3); + sizeof(straddr), 3); localRtpName = straddr; } if (pj_sockaddr_has_addr(&info.sock_info.rtcp_addr_name)) { pj_sockaddr_print(&info.sock_info.rtcp_addr_name, straddr, - sizeof(straddr), 3); + sizeof(straddr), 3); localRtcpName = straddr; } @@ -239,10 +238,10 @@ void CallSetting::fromPj(const pjsua_call_setting &prm) * mediaDir vector up to the element with non-default value. */ for (mi = PJMEDIA_MAX_SDP_MEDIA - 1; mi >= 0; mi--) { - if (prm.media_dir[mi] != PJMEDIA_DIR_ENCODING_DECODING) break; + if (prm.media_dir[mi] != PJMEDIA_DIR_ENCODING_DECODING) break; } for (i = 0; i <= mi; i++) { - this->mediaDir.push_back(prm.media_dir[i]); + this->mediaDir.push_back(prm.media_dir[i]); } } @@ -259,7 +258,7 @@ pjsua_call_setting CallSetting::toPj() const setting.aud_cnt = this->audioCount; setting.vid_cnt = this->videoCount; for (mi = 0; mi < this->mediaDir.size(); mi++) { - setting.media_dir[mi] = (pjmedia_dir)this->mediaDir[mi]; + setting.media_dir[mi] = (pjmedia_dir)this->mediaDir[mi]; } return setting; @@ -296,7 +295,7 @@ void CallInfo::fromPj(const pjsua_call_info &pci) { unsigned mi; - id = pci.id; + id = pci.id; role = pci.role; accId = pci.acc_id; localUri = pj2Str(pci.local_info); @@ -446,16 +445,16 @@ call_param::call_param(const SipTxOption &tx_option, const CallSetting &setting, if (sdp_str != "") { pj_str_t dup_pj_sdp; pj_str_t pj_sdp_str = {(char*)sdp_str.c_str(), - (pj_ssize_t)sdp_str.size()}; - pj_status_t status; + (pj_ssize_t)sdp_str.size()}; + pj_status_t status; pj_strdup(pool, &dup_pj_sdp, &pj_sdp_str); status = pjmedia_sdp_parse(pool, dup_pj_sdp.ptr, - dup_pj_sdp.slen, &sdp); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Failed to parse SDP for call param")); - } + dup_pj_sdp.slen, &sdp); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, + "Failed to parse SDP for call param")); + } } } @@ -470,20 +469,20 @@ Call::~Call() { /* Remove reference to this instance from PJSUA library */ if (id != PJSUA_INVALID_ID) - pjsua_call_set_user_data(id, NULL); + pjsua_call_set_user_data(id, NULL); /* * If this instance is deleted, also hangup the corresponding call in * PJSUA library. */ if (pjsua_get_state() < PJSUA_STATE_CLOSING && isActive()) { - try { - CallOpParam prm; - hangup(prm); - } catch (Error &err) { - // Ignore - PJ_UNUSED_ARG(err); - } + try { + CallOpParam prm; + hangup(prm); + } catch (Error &err) { + // Ignore + PJ_UNUSED_ARG(err); + } } } @@ -514,16 +513,16 @@ Call *Call::lookup(int call_id) { Call *call = (Call*)pjsua_call_get_user_data(call_id); if (call && call_id != call->id) { - if (call->child && call->child->id == PJSUA_INVALID_ID) { - /* This must be a new call from call transfer or call replace - * which initially shares user_data with its parent (so the - * user_data points to its parent's Call instance). - * Let's update its user_data to its own Call instance. - */ - call = call->child; - pjsua_call_set_user_data(call_id, call); - } - call->id = call_id; + if (call->child && call->child->id == PJSUA_INVALID_ID) { + /* This must be a new call from call transfer or call replace + * which initially shares user_data with its parent (so the + * user_data points to its parent's Call instance). + * Let's update its user_data to its own Call instance. + */ + call = call->child; + pjsua_call_set_user_data(call_id, call); + } + call->id = call_id; } return call; } @@ -552,31 +551,31 @@ AudioMedia Call::getAudioMedia(int med_idx) const PJSUA2_THROW(Error) pjsua_call_get_info(id, &pj_ci); if (med_idx < 0) { - for (unsigned i = 0; i < pj_ci.media_cnt; ++i) { - if (pj_ci.media[i].type == PJMEDIA_TYPE_AUDIO && - pj_ci.media[i].stream.aud.conf_slot != PJSUA_INVALID_ID) - { - med_idx = i; - break; - } - } - if (med_idx < 0) { - PJSUA2_RAISE_ERROR3(PJ_ENOTFOUND, "getAudioMedia()", - "no active audio media"); - } + for (unsigned i = 0; i < pj_ci.media_cnt; ++i) { + if (pj_ci.media[i].type == PJMEDIA_TYPE_AUDIO && + pj_ci.media[i].stream.aud.conf_slot != PJSUA_INVALID_ID) + { + med_idx = i; + break; + } + } + if (med_idx < 0) { + PJSUA2_RAISE_ERROR3(PJ_ENOTFOUND, "getAudioMedia()", + "no active audio media"); + } } if (med_idx >= (int)pj_ci.media_cnt) { - PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getAudioMedia()", - "invalid media index"); + PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getAudioMedia()", + "invalid media index"); } if (pj_ci.media[med_idx].type != PJMEDIA_TYPE_AUDIO) { - PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getAudioMedia()", - "media is not audio"); + PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getAudioMedia()", + "media is not audio"); } if (pj_ci.media[med_idx].stream.aud.conf_slot == PJSUA_INVALID_ID) { - PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getAudioMedia()", - "no audio slot (inactive?)"); + PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getAudioMedia()", + "no audio slot (inactive?)"); } AudioMediaHelper am; @@ -590,31 +589,31 @@ VideoMedia Call::getEncodingVideoMedia(int med_idx) const PJSUA2_THROW(Error) pjsua_call_get_info(id, &pj_ci); if (med_idx < 0) { - for (unsigned i = 0; i < pj_ci.media_cnt; ++i) { - if (pj_ci.media[i].type == PJMEDIA_TYPE_VIDEO && - pj_ci.media[i].stream.vid.enc_slot != PJSUA_INVALID_ID) - { - med_idx = i; - break; - } - } - if (med_idx < 0) { - PJSUA2_RAISE_ERROR3(PJ_ENOTFOUND, "getEncodingVideoMedia()", - "no active encoding video media"); - } + for (unsigned i = 0; i < pj_ci.media_cnt; ++i) { + if (pj_ci.media[i].type == PJMEDIA_TYPE_VIDEO && + pj_ci.media[i].stream.vid.enc_slot != PJSUA_INVALID_ID) + { + med_idx = i; + break; + } + } + if (med_idx < 0) { + PJSUA2_RAISE_ERROR3(PJ_ENOTFOUND, "getEncodingVideoMedia()", + "no active encoding video media"); + } } if (med_idx >= (int)pj_ci.media_cnt) { - PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getEncodingVideoMedia()", - "invalid media index"); + PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getEncodingVideoMedia()", + "invalid media index"); } if (pj_ci.media[med_idx].type != PJMEDIA_TYPE_VIDEO) { - PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getEncodingVideoMedia()", - "media is not video"); + PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getEncodingVideoMedia()", + "media is not video"); } if (pj_ci.media[med_idx].stream.vid.enc_slot == PJSUA_INVALID_ID) { - PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getEncodingVideoMedia()", - "no encoding slot (recvonly?)"); + PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getEncodingVideoMedia()", + "no encoding slot (recvonly?)"); } VideoMediaHelper vm; @@ -628,31 +627,31 @@ VideoMedia Call::getDecodingVideoMedia(int med_idx) const PJSUA2_THROW(Error) pjsua_call_get_info(id, &pj_ci); if (med_idx < 0) { - for (unsigned i = 0; i < pj_ci.media_cnt; ++i) { - if (pj_ci.media[i].type == PJMEDIA_TYPE_VIDEO && - pj_ci.media[i].stream.vid.dec_slot != PJSUA_INVALID_ID) - { - med_idx = i; - break; - } - } - if (med_idx < 0) { - PJSUA2_RAISE_ERROR3(PJ_ENOTFOUND, "getDecodingVideoMedia()", - "no active decoding video media"); - } + for (unsigned i = 0; i < pj_ci.media_cnt; ++i) { + if (pj_ci.media[i].type == PJMEDIA_TYPE_VIDEO && + pj_ci.media[i].stream.vid.dec_slot != PJSUA_INVALID_ID) + { + med_idx = i; + break; + } + } + if (med_idx < 0) { + PJSUA2_RAISE_ERROR3(PJ_ENOTFOUND, "getDecodingVideoMedia()", + "no active decoding video media"); + } } if (med_idx >= (int)pj_ci.media_cnt) { - PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getDecodingVideoMedia()", - "invalid media index"); + PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getDecodingVideoMedia()", + "invalid media index"); } if (pj_ci.media[med_idx].type != PJMEDIA_TYPE_VIDEO) { - PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getDecodingVideoMedia()", - "media is not video"); + PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getDecodingVideoMedia()", + "media is not video"); } if (pj_ci.media[med_idx].stream.vid.dec_slot == PJSUA_INVALID_ID) { - PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getDecodingVideoMedia()", - "no decoding slot (sendonly?)"); + PJSUA2_RAISE_ERROR3(PJ_EINVAL, "getDecodingVideoMedia()", + "no decoding slot (sendonly?)"); } VideoMediaHelper vm; @@ -692,7 +691,7 @@ pj_stun_nat_type Call::getRemNatType() PJSUA2_THROW(Error) } void Call::makeCall(const string &dst_uri, const CallOpParam &prm) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { pj_str_t pj_dst_uri = str2Pj(dst_uri); call_param param(prm.txOption, prm.opt, prm.reason); @@ -705,16 +704,16 @@ void Call::makeCall(const string &dst_uri, const CallOpParam &prm) void Call::answer(const CallOpParam &prm) PJSUA2_THROW(Error) { call_param param(prm.txOption, prm.opt, prm.reason, - sdp_pool, prm.sdp.wholeSdp); + sdp_pool, prm.sdp.wholeSdp); if (param.sdp) { - PJSUA2_CHECK_EXPR( pjsua_call_answer_with_sdp(id, param.sdp, - param.p_opt, - prm.statusCode, - param.p_reason, - param.p_msg_data) ); + PJSUA2_CHECK_EXPR( pjsua_call_answer_with_sdp(id, param.sdp, + param.p_opt, + prm.statusCode, + param.p_reason, + param.p_msg_data) ); } else { - PJSUA2_CHECK_EXPR( pjsua_call_answer2(id, param.p_opt, prm.statusCode, + PJSUA2_CHECK_EXPR( pjsua_call_answer2(id, param.p_opt, prm.statusCode, param.p_reason, param.p_msg_data) ); } @@ -733,7 +732,7 @@ void Call::setHold(const CallOpParam &prm) PJSUA2_THROW(Error) call_param param(prm.txOption, prm.opt, prm.reason); PJSUA2_CHECK_EXPR( pjsua_call_set_hold2(id, prm.options, - param.p_msg_data) ); + param.p_msg_data) ); } void Call::reinvite(const CallOpParam &prm) PJSUA2_THROW(Error) @@ -741,7 +740,7 @@ void Call::reinvite(const CallOpParam &prm) PJSUA2_THROW(Error) call_param param(prm.txOption, prm.opt, prm.reason); PJSUA2_CHECK_EXPR( pjsua_call_reinvite2(id, param.p_opt, - param.p_msg_data) ); + param.p_msg_data) ); } void Call::update(const CallOpParam &prm) PJSUA2_THROW(Error) @@ -749,11 +748,11 @@ void Call::update(const CallOpParam &prm) PJSUA2_THROW(Error) call_param param(prm.txOption, prm.opt, prm.reason); PJSUA2_CHECK_EXPR( pjsua_call_update2(id, param.p_opt, - param.p_msg_data) ); + param.p_msg_data) ); } void Call::xfer(const string &dest, const CallOpParam &prm) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { call_param param(prm.txOption); pj_str_t pj_dest = str2Pj(dest); @@ -768,7 +767,7 @@ void Call::xferReplaces(const Call& dest_call, PJSUA2_CHECK_EXPR(pjsua_call_xfer_replaces(id, dest_call.getId(), prm.options, - param.p_msg_data) ); + param.p_msg_data) ); } void Call::processRedirect(pjsip_redirect_op cmd) PJSUA2_THROW(Error) @@ -819,7 +818,7 @@ void Call::sendRequest(const CallSendRequestParam &prm) PJSUA2_THROW(Error) call_param param(prm.txOption); PJSUA2_CHECK_EXPR(pjsua_call_send_request(id, &method, - param.p_msg_data) ); + param.p_msg_data) ); } string Call::dump(bool with_media, const string indent) PJSUA2_THROW(Error) @@ -859,7 +858,7 @@ bool Call::vidStreamIsRunning(int med_idx, pjmedia_dir dir) const void Call::vidSetStream(pjsua_call_vid_strm_op op, const CallVidSetStreamParam ¶m) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { #if PJSUA_HAS_VIDEO pjsua_call_vid_strm_op_param prm; @@ -876,11 +875,11 @@ void Call::vidSetStream(pjsua_call_vid_strm_op op, } void Call::audStreamModifyCodecParam(int med_idx, const CodecParam ¶m) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { pjmedia_codec_param prm = param.toPj(); PJSUA2_CHECK_EXPR( pjsua_call_aud_stream_modify_codec_param(id, med_idx, - &prm) ); + &prm) ); } StreamInfo Call::getStreamInfo(unsigned med_idx) const PJSUA2_THROW(Error) @@ -921,16 +920,16 @@ void Call::processMediaUpdate(OnCallMediaStateParam &prm) unsigned mi; if (pjsua_call_get_info(id, &pj_ci) == PJ_SUCCESS) { - if (medias.size()) { - /* Clear medias. */ - for (mi = 0; mi < medias.size(); mi++) { - if (medias[mi]) { - Endpoint::instance().mediaRemove((AudioMedia&)*medias[mi]); - delete medias[mi]; - } - } - medias.clear(); - } + if (medias.size()) { + /* Clear medias. */ + for (mi = 0; mi < medias.size(); mi++) { + if (medias[mi]) { + Endpoint::instance().mediaRemove((AudioMedia&)*medias[mi]); + delete medias[mi]; + } + } + medias.clear(); + } for (mi = 0; mi < pj_ci.media_cnt; mi++) { if (mi >= medias.size()) { @@ -945,14 +944,14 @@ void Call::processMediaUpdate(OnCallMediaStateParam &prm) AudioMediaHelper *aud_med = (AudioMediaHelper*)medias[mi]; aud_med->setPortId(pj_ci.media[mi].stream.aud.conf_slot); - /* Add media if the conference slot ID is valid. */ + /* Add media if the conference slot ID is valid. */ if (pj_ci.media[mi].stream.aud.conf_slot != PJSUA_INVALID_ID) { Endpoint::instance().mediaAdd((AudioMedia &)*aud_med); } else { Endpoint::instance().mediaRemove((AudioMedia &)*aud_med); } - } + } } } @@ -968,35 +967,35 @@ void Call::processStateChange(OnCallStateParam &prm) if (pjsua_call_get_info(id, &pj_ci) == PJ_SUCCESS && pj_ci.state == PJSIP_INV_STATE_DISCONNECTED) { - pjsua_call *call = &pjsua_var.calls[id]; - - /* We are going to remove the Call object association below, - * so we need to call onStreamDestroyed() callback here. - */ - for (mi = 0; mi < call->med_cnt; ++mi) { - pjsua_call_media *call_med = &call->media[mi]; - if (call_med->type == PJMEDIA_TYPE_AUDIO && - call_med->strm.a.stream) - { - OnStreamDestroyedParam strm_prm; - strm_prm.stream = call_med->strm.a.stream; - strm_prm.streamIdx = mi; - - onStreamDestroyed(strm_prm); - } - } + pjsua_call *call = &pjsua_var.calls[id]; + + /* We are going to remove the Call object association below, + * so we need to call onStreamDestroyed() callback here. + */ + for (mi = 0; mi < call->med_cnt; ++mi) { + pjsua_call_media *call_med = &call->media[mi]; + if (call_med->type == PJMEDIA_TYPE_AUDIO && + call_med->strm.a.stream) + { + OnStreamDestroyedParam strm_prm; + strm_prm.stream = call_med->strm.a.stream; + strm_prm.streamIdx = mi; + + onStreamDestroyed(strm_prm); + } + } /* Clear medias. */ for (mi = 0; mi < medias.size(); mi++) { if (medias[mi]) { - Endpoint::instance().mediaRemove((AudioMedia &)*medias[mi]); + Endpoint::instance().mediaRemove((AudioMedia &)*medias[mi]); delete medias[mi]; } } medias.clear(); - /* Remove this Call object association */ - pjsua_call_set_user_data(id, NULL); + /* Remove this Call object association */ + pjsua_call_set_user_data(id, NULL); } onCallState(prm); diff --git a/pjsip/src/pjsua2/endpoint.cpp b/pjsip/src/pjsua2/endpoint.cpp index 2a6cf1b700..d054de8caa 100644 --- a/pjsip/src/pjsua2/endpoint.cpp +++ b/pjsip/src/pjsua2/endpoint.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -28,16 +27,16 @@ using namespace std; #include /* For retrieving pjsua threads */ -#define THIS_FILE "endpoint.cpp" -#define MAX_STUN_SERVERS 32 -#define TIMER_SIGNATURE 0x600D878A -#define MAX_CODEC_NUM 64 +#define THIS_FILE "endpoint.cpp" +#define MAX_STUN_SERVERS 32 +#define TIMER_SIGNATURE 0x600D878A +#define MAX_CODEC_NUM 64 struct UserTimer { - pj_uint32_t signature; - OnTimerParam prm; - pj_timer_entry entry; + pj_uint32_t signature; + OnTimerParam prm; + pj_timer_entry entry; }; Endpoint *Endpoint::instance_; @@ -45,7 +44,7 @@ Endpoint *Endpoint::instance_; /////////////////////////////////////////////////////////////////////////////// TlsInfo::TlsInfo() : cipher(PJ_TLS_UNKNOWN_CIPHER), - empty(true) + empty(true) { } @@ -63,22 +62,22 @@ void TlsInfo::fromPj(const pjsip_tls_state_info &info) const char *cipher_name; unsigned verif_msg_cnt; - empty = false; + empty = false; established = PJ2BOOL(ssock_info->established); - protocol = ssock_info->proto; - cipher = ssock_info->cipher; + protocol = ssock_info->proto; + cipher = ssock_info->cipher; cipher_name = pj_ssl_cipher_name(ssock_info->cipher); if (cipher_name) { - cipherName = cipher_name; + cipherName = cipher_name; } else { - char tmp[32]; - pj_ansi_snprintf(tmp, sizeof(tmp), "Cipher 0x%x", cipher); - cipherName = tmp; + char tmp[32]; + pj_ansi_snprintf(tmp, sizeof(tmp), "Cipher 0x%x", cipher); + cipherName = tmp; } pj_sockaddr_print(&ssock_info->local_addr, straddr, sizeof(straddr), 3); - localAddr = straddr; + localAddr = straddr; pj_sockaddr_print(&ssock_info->remote_addr, straddr, sizeof(straddr),3); - remoteAddr = straddr; + remoteAddr = straddr; verifyStatus = ssock_info->verify_status; if (ssock_info->local_cert_info) localCertInfo.fromPj(*ssock_info->local_cert_info); @@ -88,7 +87,7 @@ void TlsInfo::fromPj(const pjsip_tls_state_info &info) /* Dump server TLS certificate verification result */ verif_msg_cnt = PJ_ARRAY_SIZE(verif_msgs); pj_ssl_cert_get_verify_status_strings(ssock_info->verify_status, - verif_msgs, &verif_msg_cnt); + verif_msgs, &verif_msg_cnt); for (unsigned i = 0; i < verif_msg_cnt; ++i) { verifyMsgs.push_back(verif_msgs[i]); } @@ -98,7 +97,7 @@ void TlsInfo::fromPj(const pjsip_tls_state_info &info) } SslCertInfo::SslCertInfo() - : empty(true) + : empty(true) { } @@ -109,23 +108,23 @@ bool SslCertInfo::isEmpty() const void SslCertInfo::fromPj(const pj_ssl_cert_info &info) { - empty = false; - version = info.version; + empty = false; + version = info.version; pj_memcpy(serialNo, info.serial_no, sizeof(info.serial_no)); - subjectCn = pj2Str(info.subject.cn); + subjectCn = pj2Str(info.subject.cn); subjectInfo = pj2Str(info.subject.info); - issuerCn = pj2Str(info.issuer.cn); - issuerInfo = pj2Str(info.issuer.info); + issuerCn = pj2Str(info.issuer.cn); + issuerInfo = pj2Str(info.issuer.info); validityStart.fromPj(info.validity.start); validityEnd.fromPj(info.validity.end); validityGmt = PJ2BOOL(info.validity.gmt); - raw = pj2Str(info.raw); + raw = pj2Str(info.raw); for (unsigned i = 0; i < info.subj_alt_name.cnt; i++) { - SslCertName cname; - cname.type = info.subj_alt_name.entry[i].type; - cname.name = pj2Str(info.subj_alt_name.entry[i].name); - subjectAltName.push_back(cname); + SslCertName cname; + cname.type = info.subj_alt_name.entry[i].type; + cname.name = pj2Str(info.subj_alt_name.entry[i].name); + subjectAltName.push_back(cname); } } @@ -255,14 +254,14 @@ void UaConfig::fromPj(const pjsua_config &ua_cfg) this->userAgent = pj2Str(ua_cfg.user_agent); for (i=0; inameserver.push_back(pj2Str(ua_cfg.nameserver[i])); + this->nameserver.push_back(pj2Str(ua_cfg.nameserver[i])); } for (i=0; istunServer.push_back(pj2Str(ua_cfg.stun_srv[i])); + this->stunServer.push_back(pj2Str(ua_cfg.stun_srv[i])); } for (i=0; ioutboundProxies.push_back(pj2Str(ua_cfg.outbound_proxy[i])); + this->outboundProxies.push_back(pj2Str(ua_cfg.outbound_proxy[i])); } this->stunTryIpv6 = PJ2BOOL(ua_cfg.stun_try_ipv6); @@ -285,23 +284,23 @@ pjsua_config UaConfig::toPj() const pua_cfg.user_agent = str2Pj(this->userAgent); for (i=0; inameserver.size() && inameserver[i]); + pua_cfg.nameserver[i] = str2Pj(this->nameserver[i]); } pua_cfg.nameserver_count = i; for (i=0; istunServer.size() && istunServer[i]); + pua_cfg.stun_srv[i] = str2Pj(this->stunServer[i]); } pua_cfg.stun_srv_cnt = i; for (i=0; ioutboundProxies.size() && - ioutboundProxies[i]); + pua_cfg.outbound_proxy[i] = str2Pj(this->outboundProxies[i]); } pua_cfg.outbound_proxy_cnt= i; @@ -569,8 +568,8 @@ struct PendingLog : public PendingJob LogEntry entry; virtual void execute(bool is_pending) { - PJ_UNUSED_ARG(is_pending); - Endpoint::instance().utilLogWrite(entry); + PJ_UNUSED_ARG(is_pending); + Endpoint::instance().utilLogWrite(entry); } }; @@ -586,7 +585,7 @@ writer(NULL), threadDescMutex(NULL), mainThreadOnly(false), mainThread(NULL), pendingJobSize(0) { if (instance_) { - PJSUA2_RAISE_ERROR(PJ_EEXISTS); + PJSUA2_RAISE_ERROR(PJ_EEXISTS); } instance_ = this; @@ -595,7 +594,7 @@ mainThread(NULL), pendingJobSize(0) Endpoint& Endpoint::instance() PJSUA2_THROW(Error) { if (!instance_) { - PJSUA2_RAISE_ERROR(PJ_ENOTFOUND); + PJSUA2_RAISE_ERROR(PJ_ENOTFOUND); } return *instance_; } @@ -603,8 +602,8 @@ Endpoint& Endpoint::instance() PJSUA2_THROW(Error) Endpoint::~Endpoint() { while (!pendingJobs.empty()) { - delete pendingJobs.front(); - pendingJobs.pop_front(); + delete pendingJobs.front(); + pendingJobs.pop_front(); } #if !DEPRECATED_FOR_TICKET_2232 @@ -613,10 +612,10 @@ Endpoint::~Endpoint() #endif try { - libDestroy(); + libDestroy(); } catch (Error &err) { - // Ignore - PJ_UNUSED_ARG(err); + // Ignore + PJ_UNUSED_ARG(err); } instance_ = NULL; @@ -625,30 +624,30 @@ Endpoint::~Endpoint() void Endpoint::utilAddPendingJob(PendingJob *job) { enum { - MAX_PENDING_JOBS = 1024 + MAX_PENDING_JOBS = 1024 }; /* See if we can execute immediately */ if (!mainThreadOnly || pj_thread_this()==mainThread) { - job->execute(false); - delete job; - return; + job->execute(false); + delete job; + return; } if (pendingJobSize > MAX_PENDING_JOBS) { - enum { NUMBER_TO_DISCARD = 5 }; + enum { NUMBER_TO_DISCARD = 5 }; - pj_enter_critical_section(); - for (unsigned i=0; ientry = entry; - utilAddPendingJob(job); + PendingLog *job = new PendingLog; + job->entry = entry; + utilAddPendingJob(job); } else { - writer->write(entry); + writer->write(entry); } } @@ -681,27 +680,27 @@ pj_status_t Endpoint::onCredAuth(OnCredAuthParam &prm) void Endpoint::performPendingJobs() { if (pj_thread_this() != mainThread) - return; + return; if (pendingJobSize == 0) - return; + return; for (;;) { - PendingJob *job = NULL; + PendingJob *job = NULL; - pj_enter_critical_section(); - if (pendingJobSize != 0) { - job = pendingJobs.front(); - pendingJobs.pop_front(); - pendingJobSize--; - } - pj_leave_critical_section(); + pj_enter_critical_section(); + if (pendingJobSize != 0) { + job = pendingJobs.front(); + pendingJobs.pop_front(); + pendingJobSize--; + } + pj_leave_critical_section(); - if (job) { - job->execute(true); - delete job; - } else - break; + if (job) { + job->execute(true); + delete job; + } else + break; } } @@ -714,7 +713,7 @@ void Endpoint::logFunc(int level, const char *data, int len) Endpoint &ep = Endpoint::instance(); if (!ep.writer) - return; + return; LogEntry entry; entry.level = level; @@ -730,18 +729,18 @@ void Endpoint::stun_resolve_cb(const pj_stun_resolve_result *res) Endpoint &ep = Endpoint::instance(); if (!res) - return; + return; OnNatCheckStunServersCompleteParam prm; prm.userData = res->token; prm.status = res->status; if (res->status == PJ_SUCCESS) { - char straddr[PJ_INET6_ADDRSTRLEN+10]; + char straddr[PJ_INET6_ADDRSTRLEN+10]; - prm.name = string(res->name.ptr, res->name.slen); - pj_sockaddr_print(&res->addr, straddr, sizeof(straddr), 3); - prm.addr = straddr; + prm.name = string(res->name.ptr, res->name.slen); + pj_sockaddr_print(&res->addr, straddr, sizeof(straddr), 3); + prm.addr = straddr; } ep.onNatCheckStunServersComplete(prm); @@ -756,7 +755,7 @@ void Endpoint::on_timer(pj_timer_heap_t *timer_heap, UserTimer *ut = (UserTimer*) entry->user_data; if (ut->signature != TIMER_SIGNATURE) - return; + return; ep.onTimer(ut->prm); } @@ -766,7 +765,7 @@ void Endpoint::on_nat_detect(const pj_stun_nat_detect_result *res) Endpoint &ep = Endpoint::instance(); if (!res) - return; + return; OnNatDetectionCompleteParam prm; @@ -779,8 +778,8 @@ void Endpoint::on_nat_detect(const pj_stun_nat_detect_result *res) } void Endpoint::on_transport_state( pjsip_transport *tp, - pjsip_transport_state state, - const pjsip_transport_state_info *info) + pjsip_transport_state state, + const pjsip_transport_state_info *info) { Endpoint &ep = Endpoint::instance(); @@ -793,11 +792,11 @@ void Endpoint::on_transport_state( pjsip_transport *tp, #if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0 if (!pj_ansi_stricmp(tp->type_name, "tls") && info->ext_info && - (state == PJSIP_TP_STATE_CONNECTED || - ((pjsip_tls_state_info*)info->ext_info)-> - ssl_sock_info->verify_status != PJ_SUCCESS)) + (state == PJSIP_TP_STATE_CONNECTED || + ((pjsip_tls_state_info*)info->ext_info)-> + ssl_sock_info->verify_status != PJ_SUCCESS)) { - prm.tlsInfo.fromPj(*((pjsip_tls_state_info*)info->ext_info)); + prm.tlsInfo.fromPj(*((pjsip_tls_state_info*)info->ext_info)); } #endif @@ -813,9 +812,9 @@ Account *Endpoint::lookupAcc(int acc_id, const char *op) { Account *acc = Account::lookup(acc_id); if (!acc) { - PJ_LOG(1,(THIS_FILE, - "Error: cannot find Account instance for account id %d in " - "%s", acc_id, op)); + PJ_LOG(1,(THIS_FILE, + "Error: cannot find Account instance for account id %d in " + "%s", acc_id, op)); } return acc; @@ -825,9 +824,9 @@ Call *Endpoint::lookupCall(int call_id, const char *op) { Call *call = Call::lookup(call_id); if (!call) { - PJ_LOG(1,(THIS_FILE, - "Error: cannot find Call instance for call id %d in " - "%s", call_id, op)); + PJ_LOG(1,(THIS_FILE, + "Error: cannot find Call instance for call id %d in " + "%s", call_id, op)); } return call; @@ -838,17 +837,17 @@ void Endpoint::on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, { Account *acc = lookupAcc(acc_id, "on_incoming_call()"); if (!acc) { - pjsua_call_hangup(call_id, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL); - return; + pjsua_call_hangup(call_id, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL); + return; } pjsua_call *call = &pjsua_var.calls[call_id]; if (!call->incoming_data) { - /* This happens when the incoming call callback has been called from - * inside the on_create_media_transport() callback. So we simply - * return here to avoid calling the callback twice. - */ - return; + /* This happens when the incoming call callback has been called from + * inside the on_create_media_transport() callback. So we simply + * return here to avoid calling the callback twice. + */ + return; } /* call callback */ @@ -867,9 +866,9 @@ void Endpoint::on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, pjsua_call_get_info(call_id, &ci); if (!pjsua_call_get_user_data(call_id) && - ci.state != PJSIP_INV_STATE_DISCONNECTED) + ci.state != PJSIP_INV_STATE_DISCONNECTED) { - pjsua_call_hangup(call_id, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL); + pjsua_call_hangup(call_id, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL); } } @@ -877,7 +876,7 @@ void Endpoint::on_reg_started(pjsua_acc_id acc_id, pj_bool_t renew) { Account *acc = lookupAcc(acc_id, "on_reg_started()"); if (!acc) { - return; + return; } OnRegStartedParam prm; @@ -889,16 +888,16 @@ void Endpoint::on_reg_state2(pjsua_acc_id acc_id, pjsua_reg_info *info) { Account *acc = lookupAcc(acc_id, "on_reg_state2()"); if (!acc) { - return; + return; } OnRegStateParam prm; - prm.status = info->cbparam->status; - prm.code = (pjsip_status_code) info->cbparam->code; - prm.reason = pj2Str(info->cbparam->reason); + prm.status = info->cbparam->status; + prm.code = (pjsip_status_code) info->cbparam->code; + prm.reason = pj2Str(info->cbparam->reason); if (info->cbparam->rdata) - prm.rdata.fromPj(*info->cbparam->rdata); - prm.expiration = info->cbparam->expiration; + prm.rdata.fromPj(*info->cbparam->rdata); + prm.expiration = info->cbparam->expiration; acc->onRegState(prm); } @@ -917,16 +916,16 @@ void Endpoint::on_incoming_subscribe(pjsua_acc_id acc_id, Account *acc = lookupAcc(acc_id, "on_incoming_subscribe()"); if (!acc) { - /* default behavior should apply */ - return; + /* default behavior should apply */ + return; } OnIncomingSubscribeParam prm; - prm.srvPres = srv_pres; - prm.fromUri = pj2Str(*from); + prm.srvPres = srv_pres; + prm.fromUri = pj2Str(*from); prm.rdata.fromPj(*rdata); - prm.code = *code; - prm.reason = pj2Str(*reason); + prm.code = *code; + prm.reason = pj2Str(*reason); prm.txOption.fromPj(*msg_data); acc->onIncomingSubscribe(prm); @@ -947,103 +946,103 @@ void Endpoint::on_pager2(pjsua_call_id call_id, pjsua_acc_id acc_id) { OnInstantMessageParam prm; - prm.fromUri = pj2Str(*from); - prm.toUri = pj2Str(*to); - prm.contactUri = pj2Str(*contact); - prm.contentType = pj2Str(*mime_type); - prm.msgBody = pj2Str(*body); + prm.fromUri = pj2Str(*from); + prm.toUri = pj2Str(*to); + prm.contactUri = pj2Str(*contact); + prm.contentType = pj2Str(*mime_type); + prm.msgBody = pj2Str(*body); prm.rdata.fromPj(*rdata); if (call_id != PJSUA_INVALID_ID) { - Call *call = lookupCall(call_id, "on_pager2()"); - if (!call) { - /* Ignored */ - return; - } + Call *call = lookupCall(call_id, "on_pager2()"); + if (!call) { + /* Ignored */ + return; + } - call->onInstantMessage(prm); + call->onInstantMessage(prm); } else { - Account *acc = lookupAcc(acc_id, "on_pager2()"); - if (!acc) { - /* Ignored */ - return; - } + Account *acc = lookupAcc(acc_id, "on_pager2()"); + if (!acc) { + /* Ignored */ + return; + } - acc->onInstantMessage(prm); + acc->onInstantMessage(prm); } } void Endpoint::on_pager_status2( pjsua_call_id call_id, - const pj_str_t *to, - const pj_str_t *body, - void *user_data, - pjsip_status_code status, - const pj_str_t *reason, - pjsip_tx_data *tdata, - pjsip_rx_data *rdata, - pjsua_acc_id acc_id) + const pj_str_t *to, + const pj_str_t *body, + void *user_data, + pjsip_status_code status, + const pj_str_t *reason, + pjsip_tx_data *tdata, + pjsip_rx_data *rdata, + pjsua_acc_id acc_id) { PJ_UNUSED_ARG(tdata); OnInstantMessageStatusParam prm; - prm.userData = user_data; - prm.toUri = pj2Str(*to); - prm.msgBody = pj2Str(*body); - prm.code = status; - prm.reason = pj2Str(*reason); + prm.userData = user_data; + prm.toUri = pj2Str(*to); + prm.msgBody = pj2Str(*body); + prm.code = status; + prm.reason = pj2Str(*reason); if (rdata) - prm.rdata.fromPj(*rdata); + prm.rdata.fromPj(*rdata); if (call_id != PJSUA_INVALID_ID) { - Call *call = lookupCall(call_id, "on_pager_status2()"); - if (!call) { - /* Ignored */ - return; - } + Call *call = lookupCall(call_id, "on_pager_status2()"); + if (!call) { + /* Ignored */ + return; + } - call->onInstantMessageStatus(prm); + call->onInstantMessageStatus(prm); } else { - Account *acc = lookupAcc(acc_id, "on_pager_status2()"); - if (!acc) { - /* Ignored */ - return; - } + Account *acc = lookupAcc(acc_id, "on_pager_status2()"); + if (!acc) { + /* Ignored */ + return; + } - acc->onInstantMessageStatus(prm); + acc->onInstantMessageStatus(prm); } } void Endpoint::on_typing2( pjsua_call_id call_id, - const pj_str_t *from, - const pj_str_t *to, - const pj_str_t *contact, - pj_bool_t is_typing, - pjsip_rx_data *rdata, - pjsua_acc_id acc_id) + const pj_str_t *from, + const pj_str_t *to, + const pj_str_t *contact, + pj_bool_t is_typing, + pjsip_rx_data *rdata, + pjsua_acc_id acc_id) { OnTypingIndicationParam prm; - prm.fromUri = pj2Str(*from); - prm.toUri = pj2Str(*to); - prm.contactUri = pj2Str(*contact); - prm.isTyping = is_typing != 0; + prm.fromUri = pj2Str(*from); + prm.toUri = pj2Str(*to); + prm.contactUri = pj2Str(*contact); + prm.isTyping = is_typing != 0; prm.rdata.fromPj(*rdata); if (call_id != PJSUA_INVALID_ID) { - Call *call = lookupCall(call_id, "on_typing2()"); - if (!call) { - /* Ignored */ - return; - } + Call *call = lookupCall(call_id, "on_typing2()"); + if (!call) { + /* Ignored */ + return; + } - call->onTypingIndication(prm); + call->onTypingIndication(prm); } else { - Account *acc = lookupAcc(acc_id, "on_typing2()"); - if (!acc) { - /* Ignored */ - return; - } + Account *acc = lookupAcc(acc_id, "on_typing2()"); + if (!acc) { + /* Ignored */ + return; + } - acc->onTypingIndication(prm); + acc->onTypingIndication(prm); } } @@ -1053,24 +1052,24 @@ void Endpoint::on_mwi_info(pjsua_acc_id acc_id, OnMwiInfoParam prm; if (mwi_info->evsub) { - prm.state = pjsip_evsub_get_state(mwi_info->evsub); + prm.state = pjsip_evsub_get_state(mwi_info->evsub); } else { - /* Unsolicited MWI */ - prm.state = PJSIP_EVSUB_STATE_NULL; + /* Unsolicited MWI */ + prm.state = PJSIP_EVSUB_STATE_NULL; } prm.rdata.fromPj(*mwi_info->rdata); Account *acc = lookupAcc(acc_id, "on_mwi_info()"); if (!acc) { - /* Ignored */ - return; + /* Ignored */ + return; } acc->onMwiInfo(prm); } void Endpoint::on_acc_find_for_incoming(const pjsip_rx_data *rdata, - pjsua_acc_id* acc_id) + pjsua_acc_id* acc_id) { OnSelectAccountParam prm; @@ -1088,24 +1087,24 @@ void Endpoint::on_buddy_state(pjsua_buddy_id buddy_id) Buddy b(buddy_id); Buddy *buddy = b.getOriginalInstance(); if (!buddy || !buddy->isValid()) { - /* Ignored */ - return; + /* Ignored */ + return; } buddy->onBuddyState(); } void Endpoint::on_buddy_evsub_state(pjsua_buddy_id buddy_id, - pjsip_evsub *sub, - pjsip_event *event) + pjsip_evsub *sub, + pjsip_event *event) { PJ_UNUSED_ARG(sub); Buddy b(buddy_id); Buddy *buddy = b.getOriginalInstance(); if (!buddy || !buddy->isValid()) { - /* Ignored */ - return; + /* Ignored */ + return; } OnBuddyEvSubStateParam prm; @@ -1119,7 +1118,7 @@ void Endpoint::on_call_state(pjsua_call_id call_id, pjsip_event *e) { Call *call = Call::lookup(call_id); if (!call) { - return; + return; } OnCallStateParam prm; @@ -1139,7 +1138,7 @@ void Endpoint::on_call_tsx_state(pjsua_call_id call_id, Call *call = Call::lookup(call_id); if (!call) { - return; + return; } OnCallTsxStateParam prm; @@ -1152,7 +1151,7 @@ void Endpoint::on_call_media_state(pjsua_call_id call_id) { Call *call = Call::lookup(call_id); if (!call) { - return; + return; } OnCallMediaStateParam prm; @@ -1166,7 +1165,7 @@ void Endpoint::on_call_sdp_created(pjsua_call_id call_id, { Call *call = Call::lookup(call_id); if (!call) { - return; + return; } OnCallSdpCreatedParam prm; @@ -1185,18 +1184,18 @@ void Endpoint::on_call_sdp_created(pjsua_call_id call_id, pjmedia_sdp_session *new_sdp; pj_str_t dup_new_sdp; pj_str_t new_sdp_str = {(char*)prm.sdp.wholeSdp.c_str(), - (pj_ssize_t)prm.sdp.wholeSdp.size()}; - pj_status_t status; + (pj_ssize_t)prm.sdp.wholeSdp.size()}; + pj_status_t status; pj_strdup(pool, &dup_new_sdp, &new_sdp_str); status = pjmedia_sdp_parse(pool, dup_new_sdp.ptr, - dup_new_sdp.slen, &new_sdp); - if (status != PJ_SUCCESS) { - PJ_PERROR(4,(THIS_FILE, status, - "Failed to parse the modified SDP")); - } else { - pj_memcpy(sdp, new_sdp, sizeof(*sdp)); - } + dup_new_sdp.slen, &new_sdp); + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, + "Failed to parse the modified SDP")); + } else { + pj_memcpy(sdp, new_sdp, sizeof(*sdp)); + } } } @@ -1216,35 +1215,35 @@ void Endpoint::on_stream_precreate(pjsua_call_id call_id, /* Copy back only the fields which are allowed to be changed. */ if (param->stream_info.type == PJMEDIA_TYPE_AUDIO) { - param->stream_info.info.aud.jb_init = prm.streamInfo.jbInit; - param->stream_info.info.aud.jb_min_pre = prm.streamInfo.jbMinPre; - param->stream_info.info.aud.jb_max_pre = prm.streamInfo.jbMaxPre; - param->stream_info.info.aud.jb_max = prm.streamInfo.jbMax; - param->stream_info.info.aud.jb_discard_algo = prm.streamInfo.jbDiscardAlgo; + param->stream_info.info.aud.jb_init = prm.streamInfo.jbInit; + param->stream_info.info.aud.jb_min_pre = prm.streamInfo.jbMinPre; + param->stream_info.info.aud.jb_max_pre = prm.streamInfo.jbMaxPre; + param->stream_info.info.aud.jb_max = prm.streamInfo.jbMax; + param->stream_info.info.aud.jb_discard_algo = prm.streamInfo.jbDiscardAlgo; #if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0) - param->stream_info.info.aud.use_ka = prm.streamInfo.useKa; + param->stream_info.info.aud.use_ka = prm.streamInfo.useKa; #endif - param->stream_info.info.aud.rtcp_sdes_bye_disabled = prm.streamInfo.rtcpSdesByeDisabled; + param->stream_info.info.aud.rtcp_sdes_bye_disabled = prm.streamInfo.rtcpSdesByeDisabled; } else if (param->stream_info.type == PJMEDIA_TYPE_VIDEO) { - param->stream_info.info.vid.jb_init = prm.streamInfo.jbInit; - param->stream_info.info.vid.jb_min_pre = prm.streamInfo.jbMinPre; - param->stream_info.info.vid.jb_max_pre = prm.streamInfo.jbMaxPre; - param->stream_info.info.vid.jb_max = prm.streamInfo.jbMax; + param->stream_info.info.vid.jb_init = prm.streamInfo.jbInit; + param->stream_info.info.vid.jb_min_pre = prm.streamInfo.jbMinPre; + param->stream_info.info.vid.jb_max_pre = prm.streamInfo.jbMaxPre; + param->stream_info.info.vid.jb_max = prm.streamInfo.jbMax; #if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0) - param->stream_info.info.vid.use_ka = prm.streamInfo.useKa; + param->stream_info.info.vid.use_ka = prm.streamInfo.useKa; #endif - param->stream_info.info.vid.rtcp_sdes_bye_disabled = prm.streamInfo.rtcpSdesByeDisabled; - param->stream_info.info.vid.codec_param->enc_fmt = prm.streamInfo.vidCodecParam.encFmt.toPj(); + param->stream_info.info.vid.rtcp_sdes_bye_disabled = prm.streamInfo.rtcpSdesByeDisabled; + param->stream_info.info.vid.codec_param->enc_fmt = prm.streamInfo.vidCodecParam.encFmt.toPj(); } } void Endpoint::on_stream_created2(pjsua_call_id call_id, - pjsua_on_stream_created_param *param) + pjsua_on_stream_created_param *param) { Call *call = Call::lookup(call_id); if (!call) { - return; + return; } OnStreamCreatedParam prm; @@ -1265,10 +1264,10 @@ void Endpoint::on_stream_destroyed(pjsua_call_id call_id, { Call *call = Call::lookup(call_id); if (!call) { - /* This can happen for call disconnection case. The callback - * should have been called from on_call_state() instead. - */ - return; + /* This can happen for call disconnection case. The callback + * should have been called from on_call_state() instead. + */ + return; } OnStreamDestroyedParam prm; @@ -1285,13 +1284,13 @@ struct PendingOnDtmfDigitCallback : public PendingJob virtual void execute(bool is_pending) { - PJ_UNUSED_ARG(is_pending); + PJ_UNUSED_ARG(is_pending); - Call *call = Call::lookup(call_id); - if (!call) - return; + Call *call = Call::lookup(call_id); + if (!call) + return; - call->onDtmfDigit(prm); + call->onDtmfDigit(prm); } }; @@ -1299,7 +1298,7 @@ void Endpoint::on_dtmf_digit(pjsua_call_id call_id, int digit) { Call *call = Call::lookup(call_id); if (!call) { - return; + return; } PendingOnDtmfDigitCallback *job = new PendingOnDtmfDigitCallback; @@ -1312,11 +1311,11 @@ void Endpoint::on_dtmf_digit(pjsua_call_id call_id, int digit) } void Endpoint::on_dtmf_digit2(pjsua_call_id call_id, - const pjsua_dtmf_info *info) + const pjsua_dtmf_info *info) { Call *call = Call::lookup(call_id); if (!call) { - return; + return; } PendingOnDtmfDigitCallback *job = new PendingOnDtmfDigitCallback; @@ -1391,7 +1390,7 @@ void Endpoint::on_call_transfer_request2(pjsua_call_id call_id, { Call *call = Call::lookup(call_id); if (!call) { - return; + return; } OnCallTransferRequestParam prm; @@ -1405,26 +1404,26 @@ void Endpoint::on_call_transfer_request2(pjsua_call_id call_id, *code = prm.statusCode; *opt = prm.opt.toPj(); if (*code/100 <= 2) { - if (prm.newCall) { - /* Sanity checks */ - pj_assert(prm.newCall->id == PJSUA_INVALID_ID); - pj_assert(prm.newCall->acc.getId() == call->acc.getId()); - - /* We don't manage (e.g: create, delete) the call child, - * so let's just override any existing child. - */ - call->child = prm.newCall; - call->child->id = PJSUA_INVALID_ID; - - /* The newCall shares the same user_data as the parent call, - * the next Call::lookup(new_call_id) will assign the call ID - * and update user_data for the newCall. - */ - } else { - PJ_LOG(3,(THIS_FILE, - "Warning: application reuses Call instance in " - "call transfer (call ID:%d)", call_id)); - } + if (prm.newCall) { + /* Sanity checks */ + pj_assert(prm.newCall->id == PJSUA_INVALID_ID); + pj_assert(prm.newCall->acc.getId() == call->acc.getId()); + + /* We don't manage (e.g: create, delete) the call child, + * so let's just override any existing child. + */ + call->child = prm.newCall; + call->child->id = PJSUA_INVALID_ID; + + /* The newCall shares the same user_data as the parent call, + * the next Call::lookup(new_call_id) will assign the call ID + * and update user_data for the newCall. + */ + } else { + PJ_LOG(3,(THIS_FILE, + "Warning: application reuses Call instance in " + "call transfer (call ID:%d)", call_id)); + } } } @@ -1436,7 +1435,7 @@ void Endpoint::on_call_transfer_status(pjsua_call_id call_id, { Call *call = Call::lookup(call_id); if (!call) { - return; + return; } OnCallTransferStatusParam prm; @@ -1458,7 +1457,7 @@ void Endpoint::on_call_replace_request2(pjsua_call_id call_id, { Call *call = Call::lookup(call_id); if (!call) { - return; + return; } OnCallReplaceRequestParam prm; @@ -1474,24 +1473,24 @@ void Endpoint::on_call_replace_request2(pjsua_call_id call_id, *st_text = str2Pj(prm.reason); *opt = prm.opt.toPj(); if (prm.newCall && prm.newCall != call) { - /* Sanity checks */ - pj_assert(prm.newCall->id == PJSUA_INVALID_ID); - pj_assert(prm.newCall->acc.getId() == call->acc.getId()); - - /* We don't manage (e.g: create, delete) the call child, - * so let's just override any existing child. - */ - call->child = prm.newCall; - call->child->id = PJSUA_INVALID_ID; - - /* The newCall shares the same user_data as the parent call, - * the next Call::lookup(new_call_id) will assign the call ID - * and update user_data for the newCall. - */ + /* Sanity checks */ + pj_assert(prm.newCall->id == PJSUA_INVALID_ID); + pj_assert(prm.newCall->acc.getId() == call->acc.getId()); + + /* We don't manage (e.g: create, delete) the call child, + * so let's just override any existing child. + */ + call->child = prm.newCall; + call->child->id = PJSUA_INVALID_ID; + + /* The newCall shares the same user_data as the parent call, + * the next Call::lookup(new_call_id) will assign the call ID + * and update user_data for the newCall. + */ } else { - PJ_LOG(3,(THIS_FILE, - "Warning: application has not created new Call instance " - "for call replace request (call ID:%d)", call_id)); + PJ_LOG(3,(THIS_FILE, + "Warning: application has not created new Call instance " + "for call replace request (call ID:%d)", call_id)); } } @@ -1505,14 +1504,14 @@ void Endpoint::on_call_replaced(pjsua_call_id old_call_id, Call *call = Call::lookup(old_call_id); if (!call) { - return; + return; } /* Check if new call object has not been created in * onCallReplaceRequest(). */ if (new_call == call) - new_call = NULL; + new_call = NULL; OnCallReplacedParam prm; prm.newCallId = new_call_id; @@ -1521,24 +1520,24 @@ void Endpoint::on_call_replaced(pjsua_call_id old_call_id, call->onCallReplaced(prm); if (prm.newCall && prm.newCall != call) { - /* Sanity checks */ - pj_assert(prm.newCall->id == new_call_id); - pj_assert(prm.newCall->acc.getId() == call->acc.getId()); - pj_assert(pjsua_call_get_user_data(new_call_id) == prm.newCall); - - /* Warn if new_call created in onCallReplaceRequest() is changed */ - if (new_call && new_call != prm.newCall) { - PJ_LOG(3,(THIS_FILE, - "Warning: application has created a new Call instance " - "in onCallReplaceRequest, but created another in " - "onCallReplaced (call ID:%d)", - new_call_id)); - } + /* Sanity checks */ + pj_assert(prm.newCall->id == new_call_id); + pj_assert(prm.newCall->acc.getId() == call->acc.getId()); + pj_assert(pjsua_call_get_user_data(new_call_id) == prm.newCall); + + /* Warn if new_call created in onCallReplaceRequest() is changed */ + if (new_call && new_call != prm.newCall) { + PJ_LOG(3,(THIS_FILE, + "Warning: application has created a new Call instance " + "in onCallReplaceRequest, but created another in " + "onCallReplaced (call ID:%d)", + new_call_id)); + } } else { - PJ_LOG(3,(THIS_FILE, - "Warning: application has not created new Call instance " - "for call replace (old call ID:%d, new call ID:%d)", - old_call_id, new_call_id)); + PJ_LOG(3,(THIS_FILE, + "Warning: application has not created new Call instance " + "for call replace (old call ID:%d, new call ID:%d)", + old_call_id, new_call_id)); } } @@ -1552,7 +1551,7 @@ void Endpoint::on_call_rx_offer(pjsua_call_id call_id, Call *call = Call::lookup(call_id); if (!call) { - return; + return; } OnCallRxOfferParam prm; @@ -1569,8 +1568,8 @@ void Endpoint::on_call_rx_offer(pjsua_call_id call_id, void Endpoint::on_call_rx_reinvite(pjsua_call_id call_id, const pjmedia_sdp_session *offer, pjsip_rx_data *rdata, - void *reserved, - pj_bool_t *async, + void *reserved, + pj_bool_t *async, pjsip_status_code *code, pjsua_call_setting *opt) { @@ -1578,7 +1577,7 @@ void Endpoint::on_call_rx_reinvite(pjsua_call_id call_id, Call *call = Call::lookup(call_id); if (!call) { - return; + return; } OnCallRxReinviteParam prm; @@ -1596,14 +1595,14 @@ void Endpoint::on_call_rx_reinvite(pjsua_call_id call_id, } void Endpoint::on_call_tx_offer(pjsua_call_id call_id, - void *reserved, - pjsua_call_setting *opt) + void *reserved, + pjsua_call_setting *opt) { PJ_UNUSED_ARG(reserved); Call *call = Call::lookup(call_id); if (!call) { - return; + return; } OnCallTxOfferParam prm; @@ -1620,7 +1619,7 @@ pjsip_redirect_op Endpoint::on_call_redirected(pjsua_call_id call_id, { Call *call = Call::lookup(call_id); if (!call) { - return PJSIP_REDIRECT_STOP; + return PJSIP_REDIRECT_STOP; } OnCallRedirectedParam prm; @@ -1647,13 +1646,13 @@ struct PendingOnMediaTransportCallback : public PendingJob virtual void execute(bool is_pending) { - PJ_UNUSED_ARG(is_pending); + PJ_UNUSED_ARG(is_pending); - Call *call = Call::lookup(call_id); - if (!call) - return; + Call *call = Call::lookup(call_id); + if (!call) + return; - call->onCallMediaTransportState(prm); + call->onCallMediaTransportState(prm); } }; @@ -1663,7 +1662,7 @@ Endpoint::on_call_media_transport_state(pjsua_call_id call_id, { Call *call = Call::lookup(call_id); if (!call) { - return PJ_SUCCESS; + return PJ_SUCCESS; } PendingOnMediaTransportCallback *job = new PendingOnMediaTransportCallback; @@ -1686,21 +1685,21 @@ struct PendingOnMediaEventCallback : public PendingJob virtual void execute(bool is_pending) { - if (is_pending) { - /* Can't do this anymore, pointer is invalid */ - prm.ev.pjMediaEvent = NULL; - } - - if (call_id == PJSUA_INVALID_ID) { - OnMediaEventParam prm2; - prm2.ev = prm.ev; - Endpoint::instance().onMediaEvent(prm2); - } else { - Call *call = Call::lookup(call_id); - - if (call) - call->onCallMediaEvent(prm); - } + if (is_pending) { + /* Can't do this anymore, pointer is invalid */ + prm.ev.pjMediaEvent = NULL; + } + + if (call_id == PJSUA_INVALID_ID) { + OnMediaEventParam prm2; + prm2.ev = prm.ev; + Endpoint::instance().onMediaEvent(prm2); + } else { + Call *call = Call::lookup(call_id); + + if (call) + call->onCallMediaEvent(prm); + } } }; @@ -1736,30 +1735,30 @@ Endpoint::on_create_media_transport(pjsua_call_id call_id, { Call *call = Call::lookup(call_id); if (!call) { - pjsua_call *in_call = &pjsua_var.calls[call_id]; - if (in_call->incoming_data) { - /* This can happen when there is an incoming call but the - * on_incoming_call() callback hasn't been called. So we need to - * call the callback here. - */ - on_incoming_call(in_call->acc_id, call_id, in_call->incoming_data); - - /* New call should already be created by app. */ - call = Call::lookup(call_id); - if (!call) { - return base_tp; - } - if (in_call->inv->dlg->mod_data[pjsua_var.mod.id] == NULL) { - /* This will enabled notification for fail events related to - * the call via on_call_state() and on_call_tsx_state(). - */ - in_call->inv->dlg->mod_data[pjsua_var.mod.id] = in_call; - in_call->inv->mod_data[pjsua_var.mod.id] = in_call; - ++pjsua_var.call_cnt; - } - } else { - return base_tp; - } + pjsua_call *in_call = &pjsua_var.calls[call_id]; + if (in_call->incoming_data) { + /* This can happen when there is an incoming call but the + * on_incoming_call() callback hasn't been called. So we need to + * call the callback here. + */ + on_incoming_call(in_call->acc_id, call_id, in_call->incoming_data); + + /* New call should already be created by app. */ + call = Call::lookup(call_id); + if (!call) { + return base_tp; + } + if (in_call->inv->dlg->mod_data[pjsua_var.mod.id] == NULL) { + /* This will enabled notification for fail events related to + * the call via on_call_state() and on_call_tsx_state(). + */ + in_call->inv->dlg->mod_data[pjsua_var.mod.id] = in_call; + in_call->inv->mod_data[pjsua_var.mod.id] = in_call; + ++pjsua_var.call_cnt; + } + } else { + return base_tp; + } } OnCreateMediaTransportParam prm; @@ -1773,39 +1772,39 @@ Endpoint::on_create_media_transport(pjsua_call_id call_id, } void Endpoint::on_create_media_transport_srtp(pjsua_call_id call_id, - unsigned media_idx, - pjmedia_srtp_setting *srtp_opt) + unsigned media_idx, + pjmedia_srtp_setting *srtp_opt) { Call *call = Call::lookup(call_id); if (!call) { - pjsua_call *in_call = &pjsua_var.calls[call_id]; - if (in_call->incoming_data) { - /* This can happen when there is an incoming call but the - * on_incoming_call() callback hasn't been called. So we need to - * call the callback here. - */ - on_incoming_call(in_call->acc_id, call_id, in_call->incoming_data); - - /* New call should already be created by app. */ - call = Call::lookup(call_id); - if (!call) { - return; - } - } else { - return; - } + pjsua_call *in_call = &pjsua_var.calls[call_id]; + if (in_call->incoming_data) { + /* This can happen when there is an incoming call but the + * on_incoming_call() callback hasn't been called. So we need to + * call the callback here. + */ + on_incoming_call(in_call->acc_id, call_id, in_call->incoming_data); + + /* New call should already be created by app. */ + call = Call::lookup(call_id); + if (!call) { + return; + } + } else { + return; + } } OnCreateMediaTransportSrtpParam prm; prm.mediaIdx = media_idx; prm.srtpUse = srtp_opt->use; for (unsigned i = 0; i < srtp_opt->crypto_count; i++) { - SrtpCrypto crypto; - - crypto.key = pj2Str(srtp_opt->crypto[i].key); - crypto.name = pj2Str(srtp_opt->crypto[i].name); - crypto.flags = srtp_opt->crypto[i].flags; - prm.cryptos.push_back(crypto); + SrtpCrypto crypto; + + crypto.key = pj2Str(srtp_opt->crypto[i].key); + crypto.name = pj2Str(srtp_opt->crypto[i].name); + crypto.flags = srtp_opt->crypto[i].flags; + prm.cryptos.push_back(crypto); } call->onCreateMediaTransportSrtp(prm); @@ -1813,15 +1812,15 @@ void Endpoint::on_create_media_transport_srtp(pjsua_call_id call_id, srtp_opt->use = prm.srtpUse; srtp_opt->crypto_count = (unsigned)prm.cryptos.size(); for (unsigned i = 0; i < srtp_opt->crypto_count; i++) { - srtp_opt->crypto[i].key = str2Pj(prm.cryptos[i].key); - srtp_opt->crypto[i].name = str2Pj(prm.cryptos[i].name); - srtp_opt->crypto[i].flags = prm.cryptos[i].flags; + srtp_opt->crypto[i].key = str2Pj(prm.cryptos[i].key); + srtp_opt->crypto[i].name = str2Pj(prm.cryptos[i].name); + srtp_opt->crypto[i].flags = prm.cryptos[i].flags; } } void Endpoint::on_ip_change_progress(pjsua_ip_change_op op, - pj_status_t status, - const pjsua_ip_change_op_info *info) + pj_status_t status, + const pjsua_ip_change_op_info *info) { Endpoint &ep = Endpoint::instance(); OnIpChangeProgressParam param; @@ -1829,26 +1828,26 @@ void Endpoint::on_ip_change_progress(pjsua_ip_change_op op, param.op = op; param.status = status; switch (op) { - case PJSUA_IP_CHANGE_OP_RESTART_LIS: - param.transportId = info->lis_restart.transport_id; - break; + case PJSUA_IP_CHANGE_OP_RESTART_LIS: + param.transportId = info->lis_restart.transport_id; + break; case PJSUA_IP_CHANGE_OP_ACC_SHUTDOWN_TP: - param.accId = info->acc_shutdown_tp.acc_id; - break; - case PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT: - param.accId = info->acc_update_contact.acc_id; - param.regInfo.code = info->acc_update_contact.code; - param.regInfo.isRegister = - PJ2BOOL(info->acc_update_contact.is_register); - break; + param.accId = info->acc_shutdown_tp.acc_id; + break; + case PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT: + param.accId = info->acc_update_contact.acc_id; + param.regInfo.code = info->acc_update_contact.code; + param.regInfo.isRegister = + PJ2BOOL(info->acc_update_contact.is_register); + break; case PJSUA_IP_CHANGE_OP_ACC_HANGUP_CALLS: - param.accId = info->acc_hangup_calls.acc_id; - param.callId = info->acc_hangup_calls.call_id; - break; + param.accId = info->acc_hangup_calls.acc_id; + param.callId = info->acc_hangup_calls.call_id; + break; case PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS: - param.accId = info->acc_reinvite_calls.acc_id; - param.callId = info->acc_reinvite_calls.call_id; - break; + param.accId = info->acc_reinvite_calls.acc_id; + param.callId = info->acc_reinvite_calls.call_id; + break; default: param.accId = PJSUA_INVALID_ID; break; @@ -1898,28 +1897,28 @@ void Endpoint::libInit(const EpConfig &prmEpConfig) PJSUA2_THROW(Error) /* Setup log callback */ if (prmEpConfig.logConfig.writer) { - this->writer = prmEpConfig.logConfig.writer; - log_cfg.cb = &Endpoint::logFunc; + this->writer = prmEpConfig.logConfig.writer; + log_cfg.cb = &Endpoint::logFunc; } mainThreadOnly = prmEpConfig.uaConfig.mainThreadOnly; /* Setup UA callbacks */ pj_bzero(&ua_cfg.cb, sizeof(ua_cfg.cb)); - ua_cfg.cb.on_nat_detect = &Endpoint::on_nat_detect; + ua_cfg.cb.on_nat_detect = &Endpoint::on_nat_detect; ua_cfg.cb.on_transport_state = &Endpoint::on_transport_state; - ua_cfg.cb.on_incoming_call = &Endpoint::on_incoming_call; - ua_cfg.cb.on_reg_started = &Endpoint::on_reg_started; - ua_cfg.cb.on_reg_state2 = &Endpoint::on_reg_state2; + ua_cfg.cb.on_incoming_call = &Endpoint::on_incoming_call; + ua_cfg.cb.on_reg_started = &Endpoint::on_reg_started; + ua_cfg.cb.on_reg_state2 = &Endpoint::on_reg_state2; ua_cfg.cb.on_incoming_subscribe = &Endpoint::on_incoming_subscribe; - ua_cfg.cb.on_pager2 = &Endpoint::on_pager2; - ua_cfg.cb.on_pager_status2 = &Endpoint::on_pager_status2; - ua_cfg.cb.on_typing2 = &Endpoint::on_typing2; - ua_cfg.cb.on_mwi_info = &Endpoint::on_mwi_info; - ua_cfg.cb.on_buddy_state = &Endpoint::on_buddy_state; + ua_cfg.cb.on_pager2 = &Endpoint::on_pager2; + ua_cfg.cb.on_pager_status2 = &Endpoint::on_pager_status2; + ua_cfg.cb.on_typing2 = &Endpoint::on_typing2; + ua_cfg.cb.on_mwi_info = &Endpoint::on_mwi_info; + ua_cfg.cb.on_buddy_state = &Endpoint::on_buddy_state; ua_cfg.cb.on_buddy_evsub_state = &Endpoint::on_buddy_evsub_state; ua_cfg.cb.on_acc_find_for_incoming = &Endpoint::on_acc_find_for_incoming; - ua_cfg.cb.on_ip_change_progress = &Endpoint::on_ip_change_progress; + ua_cfg.cb.on_ip_change_progress = &Endpoint::on_ip_change_progress; /* Call callbacks */ ua_cfg.cb.on_call_state = &Endpoint::on_call_state; @@ -1942,11 +1941,11 @@ void Endpoint::libInit(const EpConfig &prmEpConfig) PJSUA2_THROW(Error) ua_cfg.cb.on_call_redirected = &Endpoint::on_call_redirected; ua_cfg.cb.on_call_media_transport_state = &Endpoint::on_call_media_transport_state; - ua_cfg.cb.on_media_event = &Endpoint::on_media_event; + ua_cfg.cb.on_media_event = &Endpoint::on_media_event; ua_cfg.cb.on_call_media_event = &Endpoint::on_call_media_event; ua_cfg.cb.on_create_media_transport = &Endpoint::on_create_media_transport; ua_cfg.cb.on_stun_resolution_complete = - &Endpoint::stun_resolve_cb; + &Endpoint::stun_resolve_cb; /* Init! */ PJSUA2_CHECK_EXPR( pjsua_init(&ua_cfg, &log_cfg, &med_cfg) ); @@ -1954,26 +1953,26 @@ void Endpoint::libInit(const EpConfig &prmEpConfig) PJSUA2_THROW(Error) /* Register worker threads */ int i = pjsua_var.ua_cfg.thread_cnt; while (i) { - pj_thread_t *t = pjsua_var.thread[--i]; - if (t) - threadDescMap[t] = NULL; + pj_thread_t *t = pjsua_var.thread[--i]; + if (t) + threadDescMap[t] = NULL; } /* Register media endpoint worker thread */ pjmedia_endpt *medept = pjsua_get_pjmedia_endpt(); i = pjmedia_endpt_get_thread_count(medept); while (i) { - pj_thread_t *t = pjmedia_endpt_get_thread(medept, --i); - if (t) - threadDescMap[t] = NULL; + pj_thread_t *t = pjmedia_endpt_get_thread(medept, --i); + if (t) + threadDescMap[t] = NULL; } PJSUA2_CHECK_EXPR( pj_mutex_create_simple(pjsua_var.pool, "threadDesc", - &threadDescMutex) ); + &threadDescMutex) ); #if !DEPRECATED_FOR_TICKET_2232 PJSUA2_CHECK_EXPR( pj_mutex_create_recursive(pjsua_var.pool, "mediaList", - &mediaListMutex) ); + &mediaListMutex) ); #endif } @@ -1990,33 +1989,33 @@ void Endpoint::libRegisterThread(const string &name) PJSUA2_THROW(Error) desc = (pj_thread_desc*)malloc(sizeof(pj_thread_desc)); if (!desc) { - PJSUA2_RAISE_ERROR(PJ_ENOMEM); + PJSUA2_RAISE_ERROR(PJ_ENOMEM); } pj_bzero(desc, sizeof(pj_thread_desc)); status = pj_thread_register(name.c_str(), *desc, &thread); if (status == PJ_SUCCESS) { - pj_mutex_lock(threadDescMutex); - threadDescMap[thread] = desc; - pj_mutex_unlock(threadDescMutex); + pj_mutex_lock(threadDescMutex); + threadDescMap[thread] = desc; + pj_mutex_unlock(threadDescMutex); } else { - free(desc); - PJSUA2_RAISE_ERROR(status); + free(desc); + PJSUA2_RAISE_ERROR(status); } } bool Endpoint::libIsThreadRegistered() { if (pj_thread_is_registered()) { - bool found; + bool found; - pj_mutex_lock(threadDescMutex); - /* Recheck again if it exists in the thread description map */ - found = (threadDescMap.find(pj_thread_this()) != threadDescMap.end()); - pj_mutex_unlock(threadDescMutex); + pj_mutex_lock(threadDescMutex); + /* Recheck again if it exists in the thread description map */ + found = (threadDescMap.find(pj_thread_this()) != threadDescMap.end()); + pj_mutex_unlock(threadDescMutex); - return found; + return found; } return false; @@ -2038,19 +2037,19 @@ void Endpoint::libDestroy(unsigned flags) PJSUA2_THROW(Error) pj_status_t status; if (threadDescMutex) { - pj_mutex_destroy(threadDescMutex); - threadDescMutex = NULL; + pj_mutex_destroy(threadDescMutex); + threadDescMutex = NULL; } #if !DEPRECATED_FOR_TICKET_2232 while(mediaList.size() > 0) { - AudioMedia *cur_media = mediaList[0]; - delete cur_media; /* this will remove itself from the list */ + AudioMedia *cur_media = mediaList[0]; + delete cur_media; /* this will remove itself from the list */ } if (mediaListMutex) { - pj_mutex_destroy(mediaListMutex); - mediaListMutex = NULL; + pj_mutex_destroy(mediaListMutex); + mediaListMutex = NULL; } #endif @@ -2061,16 +2060,16 @@ void Endpoint::libDestroy(unsigned flags) PJSUA2_THROW(Error) #if PJ_LOG_MAX_LEVEL >= 1 if (pj_log_get_log_func() == &Endpoint::logFunc) { - pj_log_set_log_func(NULL); + pj_log_set_log_func(NULL); } #endif /* Clean up thread descriptors */ std::map::iterator i; for (i = threadDescMap.begin(); i != threadDescMap.end(); ++i) { - pj_thread_desc* d = (*i).second; - if (d != NULL) - free(d); + pj_thread_desc* d = (*i).second; + if (d != NULL) + free(d); } threadDescMap.clear(); @@ -2100,8 +2099,8 @@ static void ept_log_write(int level, const char *sender, } void Endpoint::utilLogWrite(int prmLevel, - const string &prmSender, - const string &prmMsg) + const string &prmSender, + const string &prmMsg) { ept_log_write(prmLevel, prmSender.c_str(), "%s", prmMsg.c_str()); } @@ -2135,8 +2134,8 @@ Token Endpoint::utilTimerSchedule(unsigned prmMsecDelay, status = pjsua_schedule_timer(&ut->entry, &delay); if (status != PJ_SUCCESS) { - delete ut; - PJSUA2_CHECK_RAISE_ERROR(status); + delete ut; + PJSUA2_CHECK_RAISE_ERROR(status); } return (Token)ut; @@ -2147,9 +2146,9 @@ void Endpoint::utilTimerCancel(Token prmTimerToken) UserTimer *ut = (UserTimer*)(void*)prmTimerToken; if (ut->signature != TIMER_SIGNATURE) { - PJ_LOG(1,(THIS_FILE, - "Invalid timer token in Endpoint::utilTimerCancel()")); - return; + PJ_LOG(1,(THIS_FILE, + "Invalid timer token in Endpoint::utilTimerCancel()")); + return; } ut->entry.id = 0; @@ -2192,31 +2191,31 @@ pj_stun_nat_type Endpoint::natGetType() PJSUA2_THROW(Error) } void Endpoint::natUpdateStunServers(const StringVector &servers, - bool wait) PJSUA2_THROW(Error) + bool wait) PJSUA2_THROW(Error) { pj_str_t srv[MAX_STUN_SERVERS]; unsigned i, count = 0; for (i=0; i= (int)mediaMaxPorts()) - return false; + return false; pjsua_conf_port_info pi; return (pjsua_conf_get_port_info(id, &pi) == PJ_SUCCESS); @@ -2435,22 +2434,22 @@ CodecInfoVector2 Endpoint::codecEnum2() const PJSUA2_THROW(Error) PJSUA2_CHECK_EXPR( pjsua_enum_codecs(pj_codec, &count) ); for (unsigned i = 0; ifromPj(pj_codec[i]); - codec_list.push_back(codec_info); + codec_info->fromPj(pj_codec[i]); + codec_list.push_back(codec_info); } pj_leave_critical_section(); } @@ -2547,16 +2546,16 @@ CodecInfoVector2 Endpoint::videoCodecEnum2() const PJSUA2_THROW(Error) PJSUA2_CHECK_EXPR(pjsua_vid_enum_codecs(pj_codec, &count)); for (unsigned i = 0; irealm, &auth_new.realm); - pj_strdup(pool, &auth->username, &auth_new.username); - pj_strdup(pool, &auth->nonce, &auth_new.nonce); - pj_strdup(pool, &auth->uri, &auth_new.uri); - pj_strdup(pool, &auth->response, &auth_new.response); - pj_strdup(pool, &auth->algorithm, &auth_new.algorithm); - pj_strdup(pool, &auth->cnonce, &auth_new.cnonce); - pj_strdup(pool, &auth->opaque, &auth_new.opaque); - pj_strdup(pool, &auth->qop, &auth_new.qop); - pj_strdup(pool, &auth->nc, &auth_new.nc); - pjsip_param_clone(pool, &auth->other_param, &auth_new.other_param); + pjsip_digest_credential auth_new = prm.digestCredential.toPj(); + // Duplicate in the pool, so that digestCredential + // is allowed to be destructed at the end of the method. + pj_strdup(pool, &auth->realm, &auth_new.realm); + pj_strdup(pool, &auth->username, &auth_new.username); + pj_strdup(pool, &auth->nonce, &auth_new.nonce); + pj_strdup(pool, &auth->uri, &auth_new.uri); + pj_strdup(pool, &auth->response, &auth_new.response); + pj_strdup(pool, &auth->algorithm, &auth_new.algorithm); + pj_strdup(pool, &auth->cnonce, &auth_new.cnonce); + pj_strdup(pool, &auth->opaque, &auth_new.opaque); + pj_strdup(pool, &auth->qop, &auth_new.qop); + pj_strdup(pool, &auth->nc, &auth_new.nc); + pjsip_param_clone(pool, &auth->other_param, &auth_new.other_param); } #if PJSIP_HAS_DIGEST_AKA_AUTH else if (status == PJ_ENOTSUP) { - status = pjsip_auth_create_aka_response(pool, chal, cred, method, auth); + status = pjsip_auth_create_aka_response(pool, chal, cred, method, auth); } #endif return status; diff --git a/pjsip/src/pjsua2/json.cpp b/pjsip/src/pjsua2/json.cpp index db1511589f..0bb5173f2a 100644 --- a/pjsip/src/pjsua2/json.cpp +++ b/pjsip/src/pjsua2/json.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -21,55 +20,55 @@ #include #include "util.hpp" -#define THIS_FILE "json.cpp" +#define THIS_FILE "json.cpp" using namespace pj; using namespace std; /* Json node operations */ -static bool jsonNode_hasUnread(const ContainerNode*); -static string jsonNode_unreadName(const ContainerNode*n) - PJSUA2_THROW(Error); -static float jsonNode_readNumber(const ContainerNode*, - const string&) - PJSUA2_THROW(Error); -static bool jsonNode_readBool(const ContainerNode*, - const string&) - PJSUA2_THROW(Error); -static string jsonNode_readString(const ContainerNode*, - const string&) - PJSUA2_THROW(Error); -static StringVector jsonNode_readStringVector(const ContainerNode*, - const string&) - PJSUA2_THROW(Error); -static ContainerNode jsonNode_readContainer(const ContainerNode*, - const string &) - PJSUA2_THROW(Error); -static ContainerNode jsonNode_readArray(const ContainerNode*, - const string &) - PJSUA2_THROW(Error); -static void jsonNode_writeNumber(ContainerNode*, - const string &name, - float num) - PJSUA2_THROW(Error); -static void jsonNode_writeBool(ContainerNode*, - const string &name, - bool value) - PJSUA2_THROW(Error); -static void jsonNode_writeString(ContainerNode*, - const string &name, - const string &value) - PJSUA2_THROW(Error); -static void jsonNode_writeStringVector(ContainerNode*, - const string &name, - const StringVector &value) - PJSUA2_THROW(Error); -static ContainerNode jsonNode_writeNewContainer(ContainerNode*, - const string &name) - PJSUA2_THROW(Error); -static ContainerNode jsonNode_writeNewArray(ContainerNode*, - const string &name) - PJSUA2_THROW(Error); +static bool jsonNode_hasUnread(const ContainerNode*); +static string jsonNode_unreadName(const ContainerNode*n) + PJSUA2_THROW(Error); +static float jsonNode_readNumber(const ContainerNode*, + const string&) + PJSUA2_THROW(Error); +static bool jsonNode_readBool(const ContainerNode*, + const string&) + PJSUA2_THROW(Error); +static string jsonNode_readString(const ContainerNode*, + const string&) + PJSUA2_THROW(Error); +static StringVector jsonNode_readStringVector(const ContainerNode*, + const string&) + PJSUA2_THROW(Error); +static ContainerNode jsonNode_readContainer(const ContainerNode*, + const string &) + PJSUA2_THROW(Error); +static ContainerNode jsonNode_readArray(const ContainerNode*, + const string &) + PJSUA2_THROW(Error); +static void jsonNode_writeNumber(ContainerNode*, + const string &name, + float num) + PJSUA2_THROW(Error); +static void jsonNode_writeBool(ContainerNode*, + const string &name, + bool value) + PJSUA2_THROW(Error); +static void jsonNode_writeString(ContainerNode*, + const string &name, + const string &value) + PJSUA2_THROW(Error); +static void jsonNode_writeStringVector(ContainerNode*, + const string &name, + const StringVector &value) + PJSUA2_THROW(Error); +static ContainerNode jsonNode_writeNewContainer(ContainerNode*, + const string &name) + PJSUA2_THROW(Error); +static ContainerNode jsonNode_writeNewArray(ContainerNode*, + const string &name) + PJSUA2_THROW(Error); static container_node_op json_op = { @@ -96,13 +95,13 @@ JsonDocument::JsonDocument() pj_caching_pool_init(&cp, NULL, 0); pool = pj_pool_create(&cp.factory, "jsondoc", 512, 512, NULL); if (!pool) - PJSUA2_RAISE_ERROR(PJ_ENOMEM); + PJSUA2_RAISE_ERROR(PJ_ENOMEM); } JsonDocument::~JsonDocument() { if (pool) - pj_pool_release(pool); + pj_pool_release(pool); pj_caching_pool_destroy(&cp); } @@ -117,11 +116,11 @@ void JsonDocument::initRoot() const void JsonDocument::loadFile(const string &filename) PJSUA2_THROW(Error) { if (root) - PJSUA2_RAISE_ERROR3(PJ_EINVALIDOP, "JsonDocument.loadString()", - "Document already initialized"); + PJSUA2_RAISE_ERROR3(PJ_EINVALIDOP, "JsonDocument.loadString()", + "Document already initialized"); if (!pj_file_exists(filename.c_str())) - PJSUA2_RAISE_ERROR(PJ_ENOTFOUND); + PJSUA2_RAISE_ERROR(PJ_ENOTFOUND); pj_ssize_t size = (pj_ssize_t)pj_file_size(filename.c_str()); pj_status_t status; @@ -136,30 +135,30 @@ void JsonDocument::loadFile(const string &filename) PJSUA2_THROW(Error) status = pj_file_open(pool, filename.c_str(), PJ_O_RDONLY, &fd); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; status = pj_file_read(fd, buffer, &size); if (status != PJ_SUCCESS) - goto on_error; + goto on_error; pj_file_close(fd); fd = NULL; if (size <= 0) { - status = PJ_EEOF; - goto on_error; + status = PJ_EEOF; + goto on_error; } parse_size = (unsigned)size; root = pj_json_parse(pool, buffer, &parse_size, &err_info); if (root == NULL) { - pj_ansi_snprintf(err_msg, sizeof(err_msg), - "JSON parsing failed: syntax error in file '%s' at " - "line %d column %d", - filename.c_str(), err_info.line, err_info.col); - PJ_LOG(1,(THIS_FILE, err_msg)); - status = PJLIB_UTIL_EINJSON; - goto on_error; + pj_ansi_snprintf(err_msg, sizeof(err_msg), + "JSON parsing failed: syntax error in file '%s' at " + "line %d column %d", + filename.c_str(), err_info.line, err_info.col); + PJ_LOG(1,(THIS_FILE, err_msg)); + status = PJLIB_UTIL_EINJSON; + goto on_error; } initRoot(); @@ -167,18 +166,18 @@ void JsonDocument::loadFile(const string &filename) PJSUA2_THROW(Error) on_error: if (fd) - pj_file_close(fd); + pj_file_close(fd); if (err_msg[0]) - PJSUA2_RAISE_ERROR3(status, "loadFile()", err_msg); + PJSUA2_RAISE_ERROR3(status, "loadFile()", err_msg); else - PJSUA2_RAISE_ERROR(status); + PJSUA2_RAISE_ERROR(status); } void JsonDocument::loadString(const string &input) PJSUA2_THROW(Error) { if (root) - PJSUA2_RAISE_ERROR3(PJ_EINVALIDOP, "JsonDocument.loadString()", - "Document already initialized"); + PJSUA2_RAISE_ERROR3(PJ_EINVALIDOP, "JsonDocument.loadString()", + "Document already initialized"); unsigned size = (unsigned)input.size(); char *buffer = (char*)pj_pool_alloc(pool, size+1); @@ -189,13 +188,13 @@ void JsonDocument::loadString(const string &input) PJSUA2_THROW(Error) root = pj_json_parse(pool, buffer, &parse_size, &err_info); if (root == NULL) { - char err_msg[80]; + char err_msg[80]; - pj_ansi_snprintf(err_msg, sizeof(err_msg), - "JSON parsing failed at line %d column %d", - err_info.line, err_info.col); - PJ_LOG(1,(THIS_FILE, err_msg)); - PJSUA2_RAISE_ERROR3(PJLIB_UTIL_EINJSON, "loadString()", err_msg); + pj_ansi_snprintf(err_msg, sizeof(err_msg), + "JSON parsing failed at line %d column %d", + err_info.line, err_info.col); + PJ_LOG(1,(THIS_FILE, err_msg)); + PJSUA2_RAISE_ERROR3(PJLIB_UTIL_EINJSON, "loadString()", err_msg); } initRoot(); } @@ -206,8 +205,8 @@ struct save_file_data }; static pj_status_t json_file_writer(const char *s, - unsigned size, - void *user_data) + unsigned size, + void *user_data) { save_file_data *sd = (save_file_data*)user_data; pj_ssize_t ssize = (pj_ssize_t)size; @@ -224,18 +223,18 @@ void JsonDocument::saveFile(const string &filename) PJSUA2_THROW(Error) status = pj_file_open(pool, filename.c_str(), PJ_O_WRONLY, &sd.fd); if (status != PJ_SUCCESS) - PJSUA2_RAISE_ERROR(status); + PJSUA2_RAISE_ERROR(status); status = pj_json_writef(root, &json_file_writer, &sd.fd); pj_file_close(sd.fd); if (status != PJ_SUCCESS) - PJSUA2_RAISE_ERROR(status); + PJSUA2_RAISE_ERROR(status); } struct save_string_data { - string output; + string output; }; static pj_status_t json_string_writer(const char *s, @@ -257,7 +256,7 @@ string JsonDocument::saveString() PJSUA2_THROW(Error) status = pj_json_writef(root, &json_string_writer, &sd); if (status != PJ_SUCCESS) - PJSUA2_RAISE_ERROR(status); + PJSUA2_RAISE_ERROR(status); return sd.output; } @@ -265,9 +264,9 @@ string JsonDocument::saveString() PJSUA2_THROW(Error) ContainerNode & JsonDocument::getRootContainer() const { if (!root) { - root = allocElement(); - pj_json_elem_obj(root, NULL); - initRoot(); + root = allocElement(); + pj_json_elem_obj(root, NULL); + initRoot(); } return rootNode; @@ -286,9 +285,9 @@ pj_pool_t *JsonDocument::getPool() /////////////////////////////////////////////////////////////////////////////// struct json_node_data { - JsonDocument *doc; - pj_json_elem *jnode; - pj_json_elem *childPtr; + JsonDocument *doc; + pj_json_elem *jnode; + pj_json_elem *childPtr; }; static bool jsonNode_hasUnread(const ContainerNode *node) @@ -303,7 +302,7 @@ static void json_verify(struct json_node_data *jdat, pj_json_val_type type) { if (jdat->childPtr == (pj_json_elem*)&jdat->jnode->value.children) - PJSUA2_RAISE_ERROR3(PJ_EEOF, op, "No unread element"); + PJSUA2_RAISE_ERROR3(PJ_EEOF, op, "No unread element"); /* If name is specified, then check if the names match, except * when the node name itself is empty and the parent node is @@ -311,29 +310,29 @@ static void json_verify(struct json_node_data *jdat, * elements to have name). */ if (jdat->jnode->type != PJ_JSON_VAL_ARRAY && - name.size() && jdat->childPtr->name.slen && - name.compare(0, name.size(), jdat->childPtr->name.ptr, + name.size() && jdat->childPtr->name.slen && + name.compare(0, name.size(), jdat->childPtr->name.ptr, jdat->childPtr->name.slen)) { - char err_msg[80]; - pj_ansi_snprintf(err_msg, sizeof(err_msg), - "Name mismatch: expecting '%s' got '%.*s'", - name.c_str(), (int)jdat->childPtr->name.slen, - jdat->childPtr->name.ptr); - PJSUA2_RAISE_ERROR3(PJLIB_UTIL_EINJSON, op, err_msg); + char err_msg[80]; + pj_ansi_snprintf(err_msg, sizeof(err_msg), + "Name mismatch: expecting '%s' got '%.*s'", + name.c_str(), (int)jdat->childPtr->name.slen, + jdat->childPtr->name.ptr); + PJSUA2_RAISE_ERROR3(PJLIB_UTIL_EINJSON, op, err_msg); } if (type != PJ_JSON_VAL_NULL && jdat->childPtr->type != type) { - char err_msg[80]; - pj_ansi_snprintf(err_msg, sizeof(err_msg), - "Type mismatch: expecting %d got %d", - type, jdat->childPtr->type); - PJSUA2_RAISE_ERROR3(PJLIB_UTIL_EINJSON, op, err_msg); + char err_msg[80]; + pj_ansi_snprintf(err_msg, sizeof(err_msg), + "Type mismatch: expecting %d got %d", + type, jdat->childPtr->type); + PJSUA2_RAISE_ERROR3(PJLIB_UTIL_EINJSON, op, err_msg); } } static string jsonNode_unreadName(const ContainerNode *node) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; json_verify(jdat, "unreadName()", "", PJ_JSON_VAL_NULL); @@ -341,8 +340,8 @@ static string jsonNode_unreadName(const ContainerNode *node) } static float jsonNode_readNumber(const ContainerNode *node, - const string &name) - PJSUA2_THROW(Error) + const string &name) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; json_verify(jdat, "readNumber()", name, PJ_JSON_VAL_NUMBER); @@ -351,8 +350,8 @@ static float jsonNode_readNumber(const ContainerNode *node, } static bool jsonNode_readBool(const ContainerNode *node, - const string &name) - PJSUA2_THROW(Error) + const string &name) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; json_verify(jdat, "readBool()", name, PJ_JSON_VAL_BOOL); @@ -361,8 +360,8 @@ static bool jsonNode_readBool(const ContainerNode *node, } static string jsonNode_readString(const ContainerNode *node, - const string &name) - PJSUA2_THROW(Error) + const string &name) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; json_verify(jdat, "readString()", name, PJ_JSON_VAL_STRING); @@ -371,8 +370,8 @@ static string jsonNode_readString(const ContainerNode *node, } static StringVector jsonNode_readStringVector(const ContainerNode *node, - const string &name) - PJSUA2_THROW(Error) + const string &name) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; json_verify(jdat, "readStringVector()", name, PJ_JSON_VAL_ARRAY); @@ -380,16 +379,16 @@ static StringVector jsonNode_readStringVector(const ContainerNode *node, StringVector result; pj_json_elem *child = jdat->childPtr->value.children.next; while (child != (pj_json_elem*)&jdat->childPtr->value.children) { - if (child->type != PJ_JSON_VAL_STRING) { - char err_msg[80]; - pj_ansi_snprintf(err_msg, sizeof(err_msg), - "Elements not string but type %d", - child->type); - PJSUA2_RAISE_ERROR3(PJLIB_UTIL_EINJSON, "readStringVector()", - err_msg); - } - result.push_back(pj2Str(child->value.str)); - child = child->next; + if (child->type != PJ_JSON_VAL_STRING) { + char err_msg[80]; + pj_ansi_snprintf(err_msg, sizeof(err_msg), + "Elements not string but type %d", + child->type); + PJSUA2_RAISE_ERROR3(PJLIB_UTIL_EINJSON, "readStringVector()", + err_msg); + } + result.push_back(pj2Str(child->value.str)); + child = child->next; } jdat->childPtr = jdat->childPtr->next; @@ -397,8 +396,8 @@ static StringVector jsonNode_readStringVector(const ContainerNode *node, } static ContainerNode jsonNode_readContainer(const ContainerNode *node, - const string &name) - PJSUA2_THROW(Error) + const string &name) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; json_verify(jdat, "readContainer()", name, PJ_JSON_VAL_OBJ); @@ -415,8 +414,8 @@ static ContainerNode jsonNode_readContainer(const ContainerNode *node, } static ContainerNode jsonNode_readArray(const ContainerNode *node, - const string &name) - PJSUA2_THROW(Error) + const string &name) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; json_verify(jdat, "readArray()", name, PJ_JSON_VAL_ARRAY); @@ -440,9 +439,9 @@ static pj_str_t alloc_name(JsonDocument *doc, const string &name) } static void jsonNode_writeNumber(ContainerNode *node, - const string &name, - float num) - PJSUA2_THROW(Error) + const string &name, + float num) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; pj_json_elem *el = jdat->doc->allocElement(); @@ -452,9 +451,9 @@ static void jsonNode_writeNumber(ContainerNode *node, } static void jsonNode_writeBool(ContainerNode *node, - const string &name, - bool value) - PJSUA2_THROW(Error) + const string &name, + bool value) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; pj_json_elem *el = jdat->doc->allocElement(); @@ -464,9 +463,9 @@ static void jsonNode_writeBool(ContainerNode *node, } static void jsonNode_writeString(ContainerNode *node, - const string &name, - const string &value) - PJSUA2_THROW(Error) + const string &name, + const string &value) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; pj_json_elem *el = jdat->doc->allocElement(); @@ -479,9 +478,9 @@ static void jsonNode_writeString(ContainerNode *node, } static void jsonNode_writeStringVector(ContainerNode *node, - const string &name, - const StringVector &value) - PJSUA2_THROW(Error) + const string &name, + const StringVector &value) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; pj_json_elem *el = jdat->doc->allocElement(); @@ -489,20 +488,20 @@ static void jsonNode_writeStringVector(ContainerNode *node, pj_json_elem_array(el, &nm); for (unsigned i=0; idoc->getPool(), &new_val, value[i].c_str()); - pj_json_elem *child = jdat->doc->allocElement(); - pj_json_elem_string(child, NULL, &new_val); - pj_json_elem_add(el, child); + pj_strdup2(jdat->doc->getPool(), &new_val, value[i].c_str()); + pj_json_elem *child = jdat->doc->allocElement(); + pj_json_elem_string(child, NULL, &new_val); + pj_json_elem_add(el, child); } pj_json_elem_add(jdat->jnode, el); } static ContainerNode jsonNode_writeNewContainer(ContainerNode *node, - const string &name) - PJSUA2_THROW(Error) + const string &name) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; pj_json_elem *el = jdat->doc->allocElement(); @@ -522,8 +521,8 @@ static ContainerNode jsonNode_writeNewContainer(ContainerNode *node, } static ContainerNode jsonNode_writeNewArray(ContainerNode *node, - const string &name) - PJSUA2_THROW(Error) + const string &name) + PJSUA2_THROW(Error) { json_node_data *jdat = (json_node_data*)&node->data; pj_json_elem *el = jdat->doc->allocElement(); diff --git a/pjsip/src/pjsua2/media.cpp b/pjsip/src/pjsua2/media.cpp index 1e1792105e..8c958cec1e 100644 --- a/pjsip/src/pjsua2/media.cpp +++ b/pjsip/src/pjsua2/media.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -27,18 +26,18 @@ using namespace std; #include -#define THIS_FILE "media.cpp" -#define MAX_FILE_NAMES 64 -#define MAX_DEV_COUNT 64 +#define THIS_FILE "media.cpp" +#define MAX_FILE_NAMES 64 +#define MAX_DEV_COUNT 64 /////////////////////////////////////////////////////////////////////////////// void MediaFormatAudio::fromPj(const pjmedia_format &format) { if ((format.type != PJMEDIA_TYPE_AUDIO) && - (format.detail_type != PJMEDIA_FORMAT_DETAIL_AUDIO)) + (format.detail_type != PJMEDIA_FORMAT_DETAIL_AUDIO)) { - type = PJMEDIA_TYPE_UNKNOWN; - return; + type = PJMEDIA_TYPE_UNKNOWN; + return; } id = format.id; @@ -88,17 +87,17 @@ void ConfPortInfo::fromPj(const pjsua_conf_port_info &port_info) format.channelCount = port_info.channel_count; format.bitsPerSample = port_info.bits_per_sample; format.frameTimeUsec = (port_info.samples_per_frame * - 1000000) / - (port_info.clock_rate * - port_info.channel_count); + 1000000) / + (port_info.clock_rate * + port_info.channel_count); format.avgBps = format.maxBps = port_info.clock_rate * - port_info.channel_count * - port_info.bits_per_sample; + port_info.channel_count * + port_info.bits_per_sample; */ listeners.clear(); for (unsigned i=0; i(media); } @@ -419,31 +418,31 @@ AudioMediaRecorder::AudioMediaRecorder() AudioMediaRecorder::~AudioMediaRecorder() { if (recorderId != PJSUA_INVALID_ID) { - unregisterMediaPort(); - pjsua_recorder_destroy(recorderId); + unregisterMediaPort(); + pjsua_recorder_destroy(recorderId); } } void AudioMediaRecorder::createRecorder(const string &file_name, - unsigned enc_type, - long max_size, - unsigned options) - PJSUA2_THROW(Error) + unsigned enc_type, + long max_size, + unsigned options) + PJSUA2_THROW(Error) { PJ_UNUSED_ARG(max_size); if (recorderId != PJSUA_INVALID_ID) { - PJSUA2_RAISE_ERROR(PJ_EEXISTS); + PJSUA2_RAISE_ERROR(PJ_EEXISTS); } pj_str_t pj_name = str2Pj(file_name); PJSUA2_CHECK_EXPR( pjsua_recorder_create(&pj_name, - enc_type, - NULL, - -1, - options, - &recorderId) ); + enc_type, + NULL, + -1, + options, + &recorderId) ); /* Get media port id. */ id = pjsua_recorder_get_conf_port(recorderId); @@ -452,7 +451,7 @@ void AudioMediaRecorder::createRecorder(const string &file_name, } AudioMediaRecorder* AudioMediaRecorder::typecastFromAudioMedia( - AudioMedia *media) + AudioMedia *media) { return static_cast(media); } @@ -467,36 +466,36 @@ ToneGenerator::ToneGenerator() ToneGenerator::~ToneGenerator() { if (tonegen) { - unregisterMediaPort(); - pjmedia_port_destroy(tonegen); - tonegen = NULL; + unregisterMediaPort(); + pjmedia_port_destroy(tonegen); + tonegen = NULL; } if (pool) { - pj_pool_release(pool); - pool = NULL; + pj_pool_release(pool); + pool = NULL; } } void ToneGenerator::createToneGenerator(unsigned clock_rate, - unsigned channel_count) - PJSUA2_THROW(Error) + unsigned channel_count) + PJSUA2_THROW(Error) { pj_status_t status; if (pool) { - PJSUA2_RAISE_ERROR(PJ_EEXISTS); + PJSUA2_RAISE_ERROR(PJ_EEXISTS); } pool = pjsua_pool_create( "tonegen%p", 512, 512); if (!pool) { - PJSUA2_RAISE_ERROR(PJ_ENOMEM); + PJSUA2_RAISE_ERROR(PJ_ENOMEM); } status = pjmedia_tonegen_create( pool, clock_rate, channel_count, - clock_rate * 20 / 1000, 16, - 0, &tonegen); + clock_rate * 20 / 1000, 16, + 0, &tonegen); if (status != PJ_SUCCESS) { - PJSUA2_RAISE_ERROR(status); + PJSUA2_RAISE_ERROR(status); } registerMediaPort2(tonegen, pool); @@ -512,7 +511,7 @@ void ToneGenerator::stop() PJSUA2_THROW(Error) pj_status_t status; if (!tonegen) { - PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); + PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); } status = pjmedia_tonegen_stop(tonegen); @@ -524,7 +523,7 @@ void ToneGenerator::rewind() PJSUA2_THROW(Error) pj_status_t status; if (!tonegen) { - PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); + PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); } status = pjmedia_tonegen_rewind(tonegen); @@ -537,14 +536,14 @@ void ToneGenerator::play(const ToneDescVector &tones, pj_status_t status; if (!tonegen) { - PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); + PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); } if (tones.size() == 0) { - PJSUA2_RAISE_ERROR(PJ_EINVAL); + PJSUA2_RAISE_ERROR(PJ_EINVAL); } status = pjmedia_tonegen_play(tonegen, (unsigned)tones.size(), &tones[0], - loop? PJMEDIA_TONEGEN_LOOP : 0); + loop? PJMEDIA_TONEGEN_LOOP : 0); PJSUA2_CHECK_RAISE_ERROR2(status, "ToneGenerator::play()"); } @@ -554,16 +553,16 @@ void ToneGenerator::playDigits(const ToneDigitVector &digits, pj_status_t status; if (!tonegen) { - PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); + PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); } if (digits.size() == 0) { - PJSUA2_RAISE_ERROR(PJ_EINVAL); + PJSUA2_RAISE_ERROR(PJ_EINVAL); } status = pjmedia_tonegen_play_digits(tonegen, - (unsigned)digits.size(), - &digits[0], - loop? PJMEDIA_TONEGEN_LOOP : 0); + (unsigned)digits.size(), + &digits[0], + loop? PJMEDIA_TONEGEN_LOOP : 0); PJSUA2_CHECK_RAISE_ERROR2(status, "ToneGenerator::playDigits()"); } @@ -575,47 +574,47 @@ ToneDigitMapVector ToneGenerator::getDigitMap() const PJSUA2_THROW(Error) pj_status_t status; if (!tonegen) { - PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); + PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); } status = pjmedia_tonegen_get_digit_map(tonegen, &pdm); PJSUA2_CHECK_RAISE_ERROR2(status, "ToneGenerator::getDigitMap()"); for (i=0; icount; ++i) { - ToneDigitMapDigit d; - char str_digit[2]; + ToneDigitMapDigit d; + char str_digit[2]; - str_digit[0] = pdm->digits[i].digit; - str_digit[1] = '\0'; + str_digit[0] = pdm->digits[i].digit; + str_digit[1] = '\0'; - d.digit = str_digit; - d.freq1 = pdm->digits[i].freq1; - d.freq2 = pdm->digits[i].freq2; + d.digit = str_digit; + d.freq1 = pdm->digits[i].freq1; + d.freq2 = pdm->digits[i].freq2; - tdm.push_back(d); + tdm.push_back(d); } return tdm; } void ToneGenerator::setDigitMap(const ToneDigitMapVector &digit_map) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { unsigned i; pj_status_t status; if (!tonegen) { - PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); + PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); } digitMap.count = (unsigned)digit_map.size(); if (digitMap.count > PJ_ARRAY_SIZE(digitMap.digits)) - digitMap.count = PJ_ARRAY_SIZE(digitMap.digits); + digitMap.count = PJ_ARRAY_SIZE(digitMap.digits); for (i=0; ifromPj(pj_info[i]); - audioDevList.push_back(dev_info); + AudioDevInfo *dev_info = new AudioDevInfo; + dev_info->fromPj(pj_info[i]); + audioDevList.push_back(dev_info); } pj_leave_critical_section(); return audioDevList; @@ -778,9 +777,9 @@ AudioDevInfoVector2 AudDevManager::enumDev2() const PJSUA2_THROW(Error) PJSUA2_CHECK_EXPR( pjsua_enum_aud_devs(pj_info, &count) ); for (unsigned i = 0; irendId = prm.rend_id; - this->show = PJ2BOOL(prm.show); - this->windowFlags = prm.wnd_flags; - this->format.id = prm.format.id; - this->format.type = prm.format.type; - this->window.type = prm.wnd.type; - this->window.handle.window = prm.wnd.info.window; + this->rendId = prm.rend_id; + this->show = PJ2BOOL(prm.show); + this->windowFlags = prm.wnd_flags; + this->format.id = prm.format.id; + this->format.type = prm.format.type; + this->window.type = prm.wnd.type; + this->window.handle.window = prm.wnd.info.window; #else PJ_UNUSED_ARG(prm); #endif @@ -1327,12 +1326,12 @@ pjsua_vid_preview_param VideoPreviewOpParam::toPj() const pjsua_vid_preview_param param; pj_bzero(¶m, sizeof(param)); #if PJSUA_HAS_VIDEO - param.rend_id = this->rendId; - param.show = this->show; - param.wnd_flags = this->windowFlags; - param.format.id = this->format.id; - param.format.type = this->format.type; - param.wnd.type = this->window.type; + param.rend_id = this->rendId; + param.show = this->show; + param.wnd_flags = this->windowFlags; + param.format.id = this->format.id; + param.format.type = this->format.type; + param.wnd.type = this->window.type; param.wnd.info.window = this->window.handle.window; #endif return param; @@ -1395,11 +1394,11 @@ VideoMedia VideoPreview::getVideoMedia() PJSUA2_THROW(Error) updateDevId(); pjsua_conf_port_id id = pjsua_vid_preview_get_vid_conf_port(devId); if (id != PJSUA_INVALID_ID) { - VideoMediaHelper vm; - vm.setPortId(id); - return vm; + VideoMediaHelper vm; + vm.setPortId(id); + return vm; } else { - PJSUA2_RAISE_ERROR2(PJ_EINVALIDOP, "Preview not started"); + PJSUA2_RAISE_ERROR2(PJ_EINVALIDOP, "Preview not started"); } #else PJSUA2_RAISE_ERROR(PJ_EINVALIDOP); @@ -1413,11 +1412,11 @@ void VideoPreview::updateDevId() { #if PJSUA_HAS_VIDEO if (winId != PJSUA_INVALID_ID) { - PJSUA_LOCK(); - pjsua_vid_win *w = &pjsua_var.win[winId]; - pj_assert(w->type == PJSUA_WND_TYPE_PREVIEW); - devId = w->preview_cap_id; - PJSUA_UNLOCK(); + PJSUA_LOCK(); + pjsua_vid_win *w = &pjsua_var.win[winId]; + pj_assert(w->type == PJSUA_WND_TYPE_PREVIEW); + devId = w->preview_cap_id; + PJSUA_UNLOCK(); } #endif } @@ -1427,10 +1426,10 @@ void MediaFormatVideo::fromPj(const pjmedia_format &format) { #if PJSUA_HAS_VIDEO if ((format.type != PJMEDIA_TYPE_VIDEO) && - (format.detail_type != PJMEDIA_FORMAT_DETAIL_VIDEO)) + (format.detail_type != PJMEDIA_FORMAT_DETAIL_VIDEO)) { - type = PJMEDIA_TYPE_UNKNOWN; - return; + type = PJMEDIA_TYPE_UNKNOWN; + return; } id = format.id; @@ -1481,10 +1480,10 @@ void VideoDevInfo::fromPj(const pjmedia_vid_dev_info &dev_info) caps = dev_info.caps; for (unsigned i = 0; iinit_count > 0) - return; + return; PJSUA2_CHECK_EXPR(pjmedia_vid_dev_subsys_init(pjsua_get_pool_factory())); #endif @@ -1550,9 +1549,9 @@ const VideoDevInfoVector &VidDevManager::enumDev() PJSUA2_THROW(Error) pj_enter_critical_section(); clearVideoDevList(); for (unsigned i = 0; ifromPj(pj_info[i]); - videoDevList.push_back(dev_info); + VideoDevInfo *dev_info = new VideoDevInfo; + dev_info->fromPj(pj_info[i]); + videoDevList.push_back(dev_info); } pj_leave_critical_section(); #endif @@ -1570,22 +1569,22 @@ VideoDevInfoVector2 VidDevManager::enumDev2() const PJSUA2_THROW(Error) PJSUA2_CHECK_EXPR(pjsua_vid_enum_devs(pj_info, &count)); for (unsigned i = 0; i= PJMEDIA_CODEC_MAX_FMTP_CNT) { - break; - } - out_fmtp.param[out_fmtp.cnt].name = str2Pj((*i).name); - out_fmtp.param[out_fmtp.cnt].val = str2Pj((*i).val); - ++out_fmtp.cnt; + if (out_fmtp.cnt >= PJMEDIA_CODEC_MAX_FMTP_CNT) { + break; + } + out_fmtp.param[out_fmtp.cnt].name = str2Pj((*i).name); + out_fmtp.param[out_fmtp.cnt].val = str2Pj((*i).val); + ++out_fmtp.cnt; } } }; @@ -1936,9 +1935,9 @@ void MediaEvent::fromPj(const pjmedia_event &ev) data.fmtChanged.newWidth = ev.data.fmt_changed.new_fmt.det.vid.size.w; data.fmtChanged.newHeight = ev.data.fmt_changed.new_fmt.det.vid.size.h; } else if (type == PJMEDIA_EVENT_AUD_DEV_ERROR) { - data.audDevError.dir = ev.data.aud_dev_err.dir; - data.audDevError.id = ev.data.aud_dev_err.id; - data.audDevError.status = ev.data.aud_dev_err.status; + data.audDevError.dir = ev.data.aud_dev_err.dir; + data.audDevError.id = ev.data.aud_dev_err.id; + data.audDevError.status = ev.data.aud_dev_err.status; } pjMediaEvent = (void *)&ev; } @@ -1953,11 +1952,11 @@ void VidConfPortInfo::fromPj(const pjsua_vid_conf_port_info &port_info) format.fromPj(port_info.format); listeners.clear(); for (unsigned i=0; ireadStringVector(this, name); } void ContainerNode::readObject(PersistentObject &obj) const - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { obj.readObject(*this); } ContainerNode ContainerNode::readContainer(const string &name) const - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { return op->readContainer(this, name); } ContainerNode ContainerNode::readArray(const string &name) const - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { return op->readArray(this, name); } void ContainerNode::writeNumber(const string &name, - float num) PJSUA2_THROW(Error) + float num) PJSUA2_THROW(Error) { return op->writeNumber(this, name, num); } void ContainerNode::writeInt(const string &name, - int num) PJSUA2_THROW(Error) + int num) PJSUA2_THROW(Error) { return op->writeNumber(this, name, (float)num); } void ContainerNode::writeBool(const string &name, - bool value) PJSUA2_THROW(Error) + bool value) PJSUA2_THROW(Error) { return op->writeBool(this, name, value); } void ContainerNode::writeString(const string &name, - const string &value) PJSUA2_THROW(Error) + const string &value) PJSUA2_THROW(Error) { return op->writeString(this, name, value); } void ContainerNode::writeStringVector(const string &name, - const StringVector &value) - PJSUA2_THROW(Error) + const StringVector &value) + PJSUA2_THROW(Error) { return op->writeStringVector(this, name, value); } void ContainerNode::writeObject(const PersistentObject &obj) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { obj.writeObject(*this); } ContainerNode ContainerNode::writeNewContainer(const string &name) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { return op->writeNewContainer(this, name); } ContainerNode ContainerNode::writeNewArray(const string &name) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { return op->writeNewArray(this, name); } diff --git a/pjsip/src/pjsua2/presence.cpp b/pjsip/src/pjsua2/presence.cpp index a7eb6111f5..364c19a3e7 100644 --- a/pjsip/src/pjsua2/presence.cpp +++ b/pjsip/src/pjsua2/presence.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -23,7 +22,7 @@ using namespace pj; using namespace std; -#define THIS_FILE "presence.cpp" +#define THIS_FILE "presence.cpp" /////////////////////////////////////////////////////////////////////////////// @@ -56,27 +55,27 @@ void BuddyConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) void BuddyInfo::fromPj(const pjsua_buddy_info &pbi) { - uri = pj2Str(pbi.uri); - contact = pj2Str(pbi.contact); - presMonitorEnabled = PJ2BOOL(pbi.monitor_pres); - subState = pbi.sub_state; - subStateName = string(pbi.sub_state_name); - subTermCode = (pjsip_status_code)pbi.sub_term_code; - subTermReason = pj2Str(pbi.sub_term_reason); + uri = pj2Str(pbi.uri); + contact = pj2Str(pbi.contact); + presMonitorEnabled = PJ2BOOL(pbi.monitor_pres); + subState = pbi.sub_state; + subStateName = string(pbi.sub_state_name); + subTermCode = (pjsip_status_code)pbi.sub_term_code; + subTermReason = pj2Str(pbi.sub_term_reason); /* Presence status */ - presStatus.status = pbi.status; + presStatus.status = pbi.status; presStatus.statusText = pj2Str(pbi.status_text); presStatus.activity = pbi.rpid.activity; - presStatus.note = pj2Str(pbi.rpid.note); - presStatus.rpidId = pj2Str(pbi.rpid.id); + presStatus.note = pj2Str(pbi.rpid.note); + presStatus.rpidId = pj2Str(pbi.rpid.id); } ////////////////////////////////////////////////////////////////////////////// typedef struct BuddyUserData { - Buddy *self; - Account *acc; + Buddy *self; + Account *acc; } BuddyUserData; /* @@ -104,19 +103,19 @@ Buddy *Buddy::getOriginalInstance() Buddy::~Buddy() { if (isValid() && getOriginalInstance()==this) { - Account *acc = NULL; - BuddyUserData *bud = (BuddyUserData*)pjsua_buddy_get_user_data(id); - if (bud) { - acc = bud->acc; - delete bud; - } - - pjsua_buddy_set_user_data(id, NULL); - pjsua_buddy_del(id); - - /* Remove from account buddy list */ - if (acc) - acc->removeBuddy(this); + Account *acc = NULL; + BuddyUserData *bud = (BuddyUserData*)pjsua_buddy_get_user_data(id); + if (bud) { + acc = bud->acc; + delete bud; + } + + pjsua_buddy_set_user_data(id, NULL); + pjsua_buddy_del(id); + + /* Remove from account buddy list */ + if (acc) + acc->removeBuddy(this); } } @@ -124,13 +123,13 @@ Buddy::~Buddy() * Create buddy and register the buddy to PJSUA-LIB. */ void Buddy::create(Account &account, const BuddyConfig &cfg) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { pjsua_buddy_config pj_cfg; pjsua_buddy_config_default(&pj_cfg); if (!account.isValid()) - PJSUA2_RAISE_ERROR3(PJ_EINVAL, "Buddy::create()", "Invalid account"); + PJSUA2_RAISE_ERROR3(PJ_EINVAL, "Buddy::create()", "Invalid account"); BuddyUserData *bud = new BuddyUserData(); bud->self = this; @@ -191,15 +190,15 @@ void Buddy::updatePresence(void) PJSUA2_THROW(Error) * Send instant messaging outside dialog. */ void Buddy::sendInstantMessage(const SendInstantMessageParam &prm) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { BuddyInfo bi = getInfo(); BuddyUserData *bud = (BuddyUserData*)pjsua_buddy_get_user_data(id); Account *acc = bud? bud->acc : NULL; if (!bud || !acc || !acc->isValid()) { - PJSUA2_RAISE_ERROR3(PJ_EINVAL, "sendInstantMessage()", - "Invalid Buddy"); + PJSUA2_RAISE_ERROR3(PJ_EINVAL, "sendInstantMessage()", + "Invalid Buddy"); } pj_str_t to = str2Pj(bi.contact.empty()? bi.uri : bi.contact); @@ -210,7 +209,7 @@ void Buddy::sendInstantMessage(const SendInstantMessageParam &prm) prm.txOption.toPj(msg_data); PJSUA2_CHECK_EXPR( pjsua_im_send(acc->getId(), &to, &mime_type, &content, - &msg_data, user_data) ); + &msg_data, user_data) ); } /* @@ -224,8 +223,8 @@ void Buddy::sendTypingIndication(const SendTypingIndicationParam &prm) Account *acc = bud? bud->acc : NULL; if (!bud || !acc || !acc->isValid()) { - PJSUA2_RAISE_ERROR3(PJ_EINVAL, "sendInstantMessage()", - "Invalid Buddy"); + PJSUA2_RAISE_ERROR3(PJ_EINVAL, "sendInstantMessage()", + "Invalid Buddy"); } pj_str_t to = str2Pj(bi.contact.empty()? bi.uri : bi.contact); @@ -233,6 +232,6 @@ void Buddy::sendTypingIndication(const SendTypingIndicationParam &prm) prm.txOption.toPj(msg_data); PJSUA2_CHECK_EXPR( pjsua_im_typing(acc->getId(), &to, prm.isTyping, - &msg_data) ); + &msg_data) ); } diff --git a/pjsip/src/pjsua2/siptypes.cpp b/pjsip/src/pjsua2/siptypes.cpp index 27e7d66795..9c3f1eca46 100644 --- a/pjsip/src/pjsua2/siptypes.cpp +++ b/pjsip/src/pjsua2/siptypes.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -23,7 +22,7 @@ using namespace pj; using namespace std; -#define THIS_FILE "siptypes.cpp" +#define THIS_FILE "siptypes.cpp" /////////////////////////////////////////////////////////////////////////////// namespace pj @@ -35,7 +34,7 @@ void readIntVector( ContainerNode &node, ContainerNode array_node = node.readArray(array_name); v.resize(0); while (array_node.hasUnread()) { - v.push_back((int)array_node.readNumber()); + v.push_back((int)array_node.readNumber()); } } @@ -45,7 +44,7 @@ void writeIntVector(ContainerNode &node, { ContainerNode array_node = node.writeNewArray(array_name); for (unsigned i=0; iCaListFile); - ts.cert_file = str2Pj(this->certFile); - ts.privkey_file = str2Pj(this->privKeyFile); - ts.password = str2Pj(this->password); - ts.ca_buf = str2Pj(this->CaBuf); - ts.cert_buf = str2Pj(this->certBuf); - ts.privkey_buf = str2Pj(this->privKeyBuf); - ts.method = this->method; - ts.ciphers_num = (unsigned)this->ciphers.size(); - ts.proto = this->proto; + ts.ca_list_file = str2Pj(this->CaListFile); + ts.cert_file = str2Pj(this->certFile); + ts.privkey_file = str2Pj(this->privKeyFile); + ts.password = str2Pj(this->password); + ts.ca_buf = str2Pj(this->CaBuf); + ts.cert_buf = str2Pj(this->certBuf); + ts.privkey_buf = str2Pj(this->privKeyBuf); + ts.method = this->method; + ts.ciphers_num = (unsigned)this->ciphers.size(); + ts.proto = this->proto; // The following will only work if sizeof(enum)==sizeof(int) pj_assert(sizeof(ts.ciphers[0]) == sizeof(int)); - ts.ciphers = ts.ciphers_num? - (pj_ssl_cipher*)&this->ciphers[0] : NULL; - ts.verify_server = this->verifyServer; - ts.verify_client = this->verifyClient; + ts.ciphers = ts.ciphers_num? + (pj_ssl_cipher*)&this->ciphers[0] : NULL; + ts.verify_server = this->verifyServer; + ts.verify_client = this->verifyClient; ts.require_client_cert = this->requireClientCert; - ts.timeout.sec = this->msecTimeout / 1000; - ts.timeout.msec = this->msecTimeout % 1000; - ts.qos_type = this->qosType; - ts.qos_params = this->qosParams; - ts.qos_ignore_error = this->qosIgnoreError; + ts.timeout.sec = this->msecTimeout / 1000; + ts.timeout.msec = this->msecTimeout % 1000; + ts.qos_type = this->qosType; + ts.qos_params = this->qosParams; + ts.qos_ignore_error = this->qosIgnoreError; return ts; } void TlsConfig::fromPj(const pjsip_tls_setting &prm) { - this->CaListFile = pj2Str(prm.ca_list_file); - this->certFile = pj2Str(prm.cert_file); - this->privKeyFile = pj2Str(prm.privkey_file); - this->password = pj2Str(prm.password); - this->CaBuf = pj2Str(prm.ca_buf); - this->certBuf = pj2Str(prm.cert_buf); - this->privKeyBuf = pj2Str(prm.privkey_buf); - this->method = (pjsip_ssl_method)prm.method; - this->proto = prm.proto; + this->CaListFile = pj2Str(prm.ca_list_file); + this->certFile = pj2Str(prm.cert_file); + this->privKeyFile = pj2Str(prm.privkey_file); + this->password = pj2Str(prm.password); + this->CaBuf = pj2Str(prm.ca_buf); + this->certBuf = pj2Str(prm.cert_buf); + this->privKeyBuf = pj2Str(prm.privkey_buf); + this->method = (pjsip_ssl_method)prm.method; + this->proto = prm.proto; // The following will only work if sizeof(enum)==sizeof(int) pj_assert(sizeof(prm.ciphers[0]) == sizeof(int)); - this->ciphers = IntVector(prm.ciphers, prm.ciphers+prm.ciphers_num); - this->verifyServer = PJ2BOOL(prm.verify_server); - this->verifyClient = PJ2BOOL(prm.verify_client); + this->ciphers = IntVector(prm.ciphers, prm.ciphers+prm.ciphers_num); + this->verifyServer = PJ2BOOL(prm.verify_server); + this->verifyClient = PJ2BOOL(prm.verify_client); this->requireClientCert = PJ2BOOL(prm.require_client_cert); - this->msecTimeout = PJ_TIME_VAL_MSEC(prm.timeout); - this->qosType = prm.qos_type; - this->qosParams = prm.qos_params; + this->msecTimeout = PJ_TIME_VAL_MSEC(prm.timeout); + this->qosType = prm.qos_type; + this->qosParams = prm.qos_params; this->qosIgnoreError = PJ2BOOL(prm.qos_ignore_error); } @@ -290,14 +289,14 @@ TransportConfig::TransportConfig() : qosType(PJ_QOS_TYPE_BEST_EFFORT) void TransportConfig::fromPj(const pjsua_transport_config &prm) { - this->port = prm.port; - this->portRange = prm.port_range; - this->randomizePort = PJ2BOOL(prm.randomize_port); + this->port = prm.port; + this->portRange = prm.port_range; + this->randomizePort = PJ2BOOL(prm.randomize_port); this->publicAddress = pj2Str(prm.public_addr); - this->boundAddress = pj2Str(prm.bound_addr); + this->boundAddress = pj2Str(prm.bound_addr); this->tlsConfig.fromPj(prm.tls_setting); - this->qosType = prm.qos_type; - this->qosParams = prm.qos_params; + this->qosType = prm.qos_type; + this->qosParams = prm.qos_params; } pjsua_transport_config TransportConfig::toPj() const @@ -305,14 +304,14 @@ pjsua_transport_config TransportConfig::toPj() const pjsua_transport_config tc; pjsua_transport_config_default(&tc); - tc.port = this->port; - tc.port_range = this->portRange; - tc.randomize_port = this->randomizePort; - tc.public_addr = str2Pj(this->publicAddress); - tc.bound_addr = str2Pj(this->boundAddress); - tc.tls_setting = this->tlsConfig.toPj(); - tc.qos_type = this->qosType; - tc.qos_params = this->qosParams; + tc.port = this->port; + tc.port_range = this->portRange; + tc.randomize_port = this->randomizePort; + tc.public_addr = str2Pj(this->publicAddress); + tc.bound_addr = str2Pj(this->boundAddress); + tc.tls_setting = this->tlsConfig.toPj(); + tc.qos_type = this->qosType; + tc.qos_params = this->qosParams; return tc; } @@ -331,7 +330,7 @@ void TransportConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) } void TransportConfig::writeObject(ContainerNode &node) const - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("TransportConfig"); @@ -382,8 +381,8 @@ void SipRxData::fromPj(pjsip_rx_data &rdata) { char straddr[PJ_INET6_ADDRSTRLEN+10]; - info = pjsip_rx_data_get_info(&rdata); - wholeMsg = string(rdata.msg_info.msg_buf, rdata.msg_info.len); + info = pjsip_rx_data_get_info(&rdata); + wholeMsg = string(rdata.msg_info.msg_buf, rdata.msg_info.len); pj_sockaddr_print(&rdata.pkt_info.src_addr, straddr, sizeof(straddr), 3); srcAddress = straddr; pjRxData = (void *)&rdata; @@ -393,15 +392,15 @@ void SipRxData::fromPj(pjsip_rx_data &rdata) void SipMediaType::fromPj(const pjsip_media_type &prm) { - type = pj2Str(prm.type); - subType = pj2Str(prm.subtype); + type = pj2Str(prm.type); + subType = pj2Str(prm.subtype); } pjsip_media_type SipMediaType::toPj() const { pjsip_media_type pj_mt; pj_bzero(&pj_mt, sizeof(pj_mt)); - pj_mt.type = str2Pj(type); + pj_mt.type = str2Pj(type); pj_mt.subtype = str2Pj(subType); return pj_mt; } @@ -420,25 +419,25 @@ void SipHeader::fromPj(const pjsip_hdr *hdr) PJSUA2_THROW(Error) */ do { buf_size <<= 1; - buf = (char*)malloc(buf_size); - if (!buf) - PJSUA2_RAISE_ERROR(PJ_ENOMEM); + buf = (char*)malloc(buf_size); + if (!buf) + PJSUA2_RAISE_ERROR(PJ_ENOMEM); - len = pjsip_hdr_print_on((void*)hdr, buf, buf_size-1); + len = pjsip_hdr_print_on((void*)hdr, buf, buf_size-1); if (len < 0) free(buf); } while ((buf_size < PJSIP_MAX_PKT_LEN) && (len < 0)); if (len < 0) - PJSUA2_RAISE_ERROR(PJ_ETOOSMALL); + PJSUA2_RAISE_ERROR(PJ_ETOOSMALL); buf[len] = '\0'; char *pos = strchr(buf, ':'); if (!pos) { - free(buf); - PJSUA2_RAISE_ERROR(PJSIP_EINVALIDHDR); + free(buf); + PJSUA2_RAISE_ERROR(PJSIP_EINVALIDHDR); } // Trim white space after header name @@ -466,19 +465,19 @@ pjsip_generic_string_hdr &SipHeader::toPj() const /////////////////////////////////////////////////////////////////////////////// void SipMultipartPart::fromPj(const pjsip_multipart_part &prm) - PJSUA2_THROW(Error) + PJSUA2_THROW(Error) { headers.clear(); pjsip_hdr* pj_hdr = prm.hdr.next; while (pj_hdr != &prm.hdr) { - SipHeader sh; - sh.fromPj(pj_hdr); - headers.push_back(sh); - pj_hdr = pj_hdr->next; + SipHeader sh; + sh.fromPj(pj_hdr); + headers.push_back(sh); + pj_hdr = pj_hdr->next; } if (!prm.body) - PJSUA2_RAISE_ERROR(PJ_EINVAL); + PJSUA2_RAISE_ERROR(PJ_EINVAL); contentType.fromPj(prm.body->content_type); body = string((char*)prm.body->data, prm.body->len); @@ -488,16 +487,16 @@ pjsip_multipart_part& SipMultipartPart::toPj() const { pj_list_init(&pjMpp.hdr); for (unsigned i = 0; i < headers.size(); i++) { - pjsip_generic_string_hdr& pj_hdr = headers[i].toPj(); - pj_list_push_back(&pjMpp.hdr, &pj_hdr); + pjsip_generic_string_hdr& pj_hdr = headers[i].toPj(); + pj_list_push_back(&pjMpp.hdr, &pj_hdr); } pj_bzero(&pjMsgBody, sizeof(pjMsgBody)); pjMsgBody.content_type = contentType.toPj(); pjMsgBody.print_body = &pjsip_print_text_body; pjMsgBody.clone_data = &pjsip_clone_text_data; - pjMsgBody.data = (void*)body.c_str(); - pjMsgBody.len = (unsigned)body.size(); + pjMsgBody.data = (void*)body.c_str(); + pjMsgBody.len = (unsigned)body.size(); pjMpp.body = &pjMsgBody; return pjMpp; @@ -522,10 +521,10 @@ void SipEvent::fromPj(const pjsip_event &ev) body.tsxState.type = ev.body.tsx_state.type; if (body.tsxState.type == PJSIP_EVENT_TX_MSG) { if (ev.body.tsx_state.src.tdata) - body.tsxState.src.tdata.fromPj(*ev.body.tsx_state.src.tdata); + body.tsxState.src.tdata.fromPj(*ev.body.tsx_state.src.tdata); } else if (body.tsxState.type == PJSIP_EVENT_RX_MSG) { if (ev.body.tsx_state.src.rdata) - body.tsxState.src.rdata.fromPj(*ev.body.tsx_state.src.rdata); + body.tsxState.src.rdata.fromPj(*ev.body.tsx_state.src.rdata); } else if (body.tsxState.type == PJSIP_EVENT_TRANSPORT_ERROR) { body.tsxState.src.status = ev.body.tsx_state.src.status; } else if (body.tsxState.type == PJSIP_EVENT_TIMER) { @@ -534,16 +533,16 @@ void SipEvent::fromPj(const pjsip_event &ev) body.tsxState.src.data = ev.body.tsx_state.src.data; } } else if (type == PJSIP_EVENT_TX_MSG) { - if (ev.body.tx_msg.tdata) - body.txMsg.tdata.fromPj(*ev.body.tx_msg.tdata); + if (ev.body.tx_msg.tdata) + body.txMsg.tdata.fromPj(*ev.body.tx_msg.tdata); } else if (type == PJSIP_EVENT_RX_MSG) { - if (ev.body.rx_msg.rdata) - body.rxMsg.rdata.fromPj(*ev.body.rx_msg.rdata); + if (ev.body.rx_msg.rdata) + body.rxMsg.rdata.fromPj(*ev.body.rx_msg.rdata); } else if (type == PJSIP_EVENT_TRANSPORT_ERROR) { - if (ev.body.tx_error.tdata) - body.txError.tdata.fromPj(*ev.body.tx_error.tdata); - if (ev.body.tx_error.tsx) - body.txError.tsx.fromPj(*ev.body.tx_error.tsx); + if (ev.body.tx_error.tdata) + body.txError.tdata.fromPj(*ev.body.tx_error.tdata); + if (ev.body.tx_error.tsx) + body.txError.tsx.fromPj(*ev.body.tx_error.tsx); } else if (type == PJSIP_EVENT_USER) { body.user.user1 = ev.body.user.user1; body.user.user2 = ev.body.user.user2; @@ -562,14 +561,14 @@ void SipTxData::fromPj(pjsip_tx_data &tdata) { char straddr[PJ_INET6_ADDRSTRLEN+10]; - info = pjsip_tx_data_get_info(&tdata); + info = pjsip_tx_data_get_info(&tdata); pjsip_tx_data_encode(&tdata); - wholeMsg = string(tdata.buf.start, tdata.buf.cur - tdata.buf.start); + wholeMsg = string(tdata.buf.start, tdata.buf.cur - tdata.buf.start); if (pj_sockaddr_has_addr(&tdata.tp_info.dst_addr)) { - pj_sockaddr_print(&tdata.tp_info.dst_addr, straddr, sizeof(straddr), 3); - dstAddress = straddr; + pj_sockaddr_print(&tdata.tp_info.dst_addr, straddr, sizeof(straddr), 3); + dstAddress = straddr; } else { - dstAddress = ""; + dstAddress = ""; } pjTxData = (void *)&tdata; } @@ -586,11 +585,11 @@ void SipTransaction::fromPj(pjsip_transaction &tsx) this->method = pj2Str(tsx.method.name); this->statusCode = tsx.status_code; this->statusText = pj2Str(tsx.status_text); - this->state = tsx.state; + this->state = tsx.state; if (tsx.last_tx) - this->lastTx.fromPj(*tsx.last_tx); + this->lastTx.fromPj(*tsx.last_tx); else - this->lastTx.pjTxData = NULL; + this->lastTx.pjTxData = NULL; this->pjTransaction = (void *)&tsx; } @@ -613,10 +612,10 @@ void SipTxOption::fromPj(const pjsua_msg_data &prm) PJSUA2_THROW(Error) headers.clear(); pjsip_hdr* pj_hdr = prm.hdr_list.next; while (pj_hdr != &prm.hdr_list) { - SipHeader sh; - sh.fromPj(pj_hdr); - headers.push_back(sh); - pj_hdr = pj_hdr->next; + SipHeader sh; + sh.fromPj(pj_hdr); + headers.push_back(sh); + pj_hdr = pj_hdr->next; } contentType = pj2Str(prm.content_type); @@ -626,10 +625,10 @@ void SipTxOption::fromPj(const pjsua_msg_data &prm) PJSUA2_THROW(Error) multipartParts.clear(); pjsip_multipart_part* pj_mp = prm.multipart_parts.next; while (pj_mp != &prm.multipart_parts) { - SipMultipartPart smp; - smp.fromPj(*pj_mp); - multipartParts.push_back(smp); - pj_mp = pj_mp->next; + SipMultipartPart smp; + smp.fromPj(*pj_mp); + multipartParts.push_back(smp); + pj_mp = pj_mp->next; } } @@ -643,8 +642,8 @@ void SipTxOption::toPj(pjsua_msg_data &msg_data) const pj_list_init(&msg_data.hdr_list); for (i = 0; i < headers.size(); i++) { - pjsip_generic_string_hdr& pj_hdr = headers[i].toPj(); - pj_list_push_back(&msg_data.hdr_list, &pj_hdr); + pjsip_generic_string_hdr& pj_hdr = headers[i].toPj(); + pj_list_push_back(&msg_data.hdr_list, &pj_hdr); } msg_data.content_type = str2Pj(contentType); @@ -653,8 +652,8 @@ void SipTxOption::toPj(pjsua_msg_data &msg_data) const pj_list_init(&msg_data.multipart_parts); for (i = 0; i < multipartParts.size(); i++) { - pjsip_multipart_part& pj_part = multipartParts[i].toPj(); - pj_list_push_back(&msg_data.multipart_parts, &pj_part); + pjsip_multipart_part& pj_part = multipartParts[i].toPj(); + pj_list_push_back(&msg_data.multipart_parts, &pj_part); } } diff --git a/pjsip/src/pjsua2/types.cpp b/pjsip/src/pjsua2/types.cpp index b62fab5a5c..79e0ed4451 100644 --- a/pjsip/src/pjsua2/types.cpp +++ b/pjsip/src/pjsua2/types.cpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -22,7 +21,7 @@ using namespace pj; using namespace std; -#define THIS_FILE "types.cpp" +#define THIS_FILE "types.cpp" /////////////////////////////////////////////////////////////////////////////// @@ -32,17 +31,17 @@ Error::Error() } Error::Error( pj_status_t prm_status, - const string &prm_title, - const string &prm_reason, - const string &prm_src_file, - int prm_src_line) + const string &prm_title, + const string &prm_reason, + const string &prm_src_file, + int prm_src_line) : status(prm_status), title(prm_title), reason(prm_reason), srcFile(prm_src_file), srcLine(prm_src_line) { if (this->status != PJ_SUCCESS && prm_reason.empty()) { - char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(this->status, errmsg, sizeof(errmsg)); - this->reason = errmsg; + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror(this->status, errmsg, sizeof(errmsg)); + this->reason = errmsg; } } @@ -51,35 +50,35 @@ string Error::info(bool multi_line) const string output; if (status==PJ_SUCCESS) { - output = "No error"; + output = "No error"; } else if (!multi_line) { - char temp[80]; + char temp[80]; - if (!title.empty()) { - output += title + " error: "; - } - snprintf(temp, sizeof(temp), " (status=%d)", status); - output += reason + temp; - if (!srcFile.empty()) { - output += " ["; - output += srcFile; - snprintf(temp, sizeof(temp), ":%d]", srcLine); - output += temp; - } + if (!title.empty()) { + output += title + " error: "; + } + snprintf(temp, sizeof(temp), " (status=%d)", status); + output += reason + temp; + if (!srcFile.empty()) { + output += " ["; + output += srcFile; + snprintf(temp, sizeof(temp), ":%d]", srcLine); + output += temp; + } } else { - char temp[80]; + char temp[80]; - if (!title.empty()) { - output += string("Title: ") + title + "\n"; - } + if (!title.empty()) { + output += string("Title: ") + title + "\n"; + } - snprintf(temp, sizeof(temp), "%d\n", status); - output += string("Code: ") + temp; - output += string("Description: ") + reason + "\n"; - if (!srcFile.empty()) { - snprintf(temp, sizeof(temp), ":%d\n", srcLine); - output += string("Location: ") + srcFile + temp; - } + snprintf(temp, sizeof(temp), "%d\n", status); + output += string("Code: ") + temp; + output += string("Description: ") + reason + "\n"; + if (!srcFile.empty()) { + snprintf(temp, sizeof(temp), ":%d\n", srcLine); + output += string("Location: ") + srcFile + temp; + } } return output; diff --git a/pjsip/src/pjsua2/util.hpp b/pjsip/src/pjsua2/util.hpp index a452966af6..b90de9a886 100644 --- a/pjsip/src/pjsua2/util.hpp +++ b/pjsip/src/pjsua2/util.hpp @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * @@ -38,7 +37,7 @@ inline pj_str_t str2Pj(const string &input_str) inline string pj2Str(const pj_str_t &input_str) { if (input_str.ptr && input_str.slen>0) - return string(input_str.ptr, input_str.slen); + return string(input_str.ptr, input_str.slen); return string(); } diff --git a/pjsip/src/test/dlg_core_test.c b/pjsip/src/test/dlg_core_test.c index c661d5755f..ea68ff9579 100644 --- a/pjsip/src/test/dlg_core_test.c +++ b/pjsip/src/test/dlg_core_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono diff --git a/pjsip/src/test/dns_test.c b/pjsip/src/test/dns_test.c index a9bffe48d8..29dc762223 100644 --- a/pjsip/src/test/dns_test.c +++ b/pjsip/src/test/dns_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -27,20 +26,20 @@ struct result { - pj_status_t status; + pj_status_t status; pjsip_server_addresses servers; }; static void cb(pj_status_t status, - void *token, - const struct pjsip_server_addresses *addr) + void *token, + const struct pjsip_server_addresses *addr) { struct result *result = (struct result*) token; result->status = status; if (status == PJ_SUCCESS) - pj_memcpy(&result->servers, addr, sizeof(*addr)); + pj_memcpy(&result->servers, addr, sizeof(*addr)); } @@ -70,7 +69,7 @@ static void add_dns_entries(pj_dns_resolver *resv) sip04.example.com. 3600 IN A 4.4.4.4 ; Additionally, add A record for "example.com" - example.com. 3600 IN A 5.5.5.5 + example.com. 3600 IN A 5.5.5.5 ; Additionally, add corresponding empty AAAA records for all A records */ @@ -154,30 +153,30 @@ static void add_dns_entries(pj_dns_resolver *resv) /* Add corresponding AAAA records for A records above */ for (i = 0; i < 5; ++i) { - ar[5+i].name = ar[i].name; - ar[5+i].type = PJ_DNS_TYPE_AAAA; - ar[5+i].dnsclass = PJ_DNS_CLASS_IN; - ar[5+i].ttl = 3600; + ar[5+i].name = ar[i].name; + ar[5+i].type = PJ_DNS_TYPE_AAAA; + ar[5+i].dnsclass = PJ_DNS_CLASS_IN; + ar[5+i].ttl = 3600; } /* * Create individual A records for all hosts in "example.com" domain. */ for (i=0; icount != result.servers.count) { - PJ_LOG(3,(THIS_FILE, " test_resolve() error 10: result count mismatch")); - return 10; - } - - for (i=0; icount; ++i) { - pj_sockaddr_in *ra = (pj_sockaddr_in *)&ref->entry[i].addr; - pj_sockaddr_in *rb = (pj_sockaddr_in *)&result.servers.entry[i].addr; - - if (ra->sin_addr.s_addr != rb->sin_addr.s_addr) { - PJ_LOG(3,(THIS_FILE, " test_resolve() error 20: IP address mismatch")); - return 20; - } - if (ra->sin_port != rb->sin_port) { - PJ_LOG(3,(THIS_FILE, " test_resolve() error 30: port mismatch")); - return 30; - } - if (ref->entry[i].addr_len != result.servers.entry[i].addr_len) { - PJ_LOG(3,(THIS_FILE, " test_resolve() error 40: addr_len mismatch")); - return 40; - } - if (ref->entry[i].type != result.servers.entry[i].type) { - PJ_LOG(3,(THIS_FILE, " test_resolve() error 50: transport type mismatch")); - return 50; - } - } + unsigned i; + + if (ref->count != result.servers.count) { + PJ_LOG(3,(THIS_FILE, " test_resolve() error 10: result count mismatch")); + return 10; + } + + for (i=0; icount; ++i) { + pj_sockaddr_in *ra = (pj_sockaddr_in *)&ref->entry[i].addr; + pj_sockaddr_in *rb = (pj_sockaddr_in *)&result.servers.entry[i].addr; + + if (ra->sin_addr.s_addr != rb->sin_addr.s_addr) { + PJ_LOG(3,(THIS_FILE, " test_resolve() error 20: IP address mismatch")); + return 20; + } + if (ra->sin_port != rb->sin_port) { + PJ_LOG(3,(THIS_FILE, " test_resolve() error 30: port mismatch")); + return 30; + } + if (ref->entry[i].addr_len != result.servers.entry[i].addr_len) { + PJ_LOG(3,(THIS_FILE, " test_resolve() error 40: addr_len mismatch")); + return 40; + } + if (ref->entry[i].type != result.servers.entry[i].type) { + PJ_LOG(3,(THIS_FILE, " test_resolve() error 50: transport type mismatch")); + return 50; + } + } } return PJ_SUCCESS; @@ -402,15 +401,15 @@ static int round_robin_test(pj_pool_t *pool) unsigned i; struct server_hit { - char *ip_addr; - unsigned percent; - unsigned hits; + char *ip_addr; + unsigned percent; + unsigned hits; } server_hit[] = { - { "1.1.1.1", 3, 0 }, - { "2.2.2.2", 65, 0 }, - { "3.3.3.3", 32, 0 }, - { "4.4.4.4", 0, 0 } + { "1.1.1.1", 3, 0 }, + { "2.2.2.2", 65, 0 }, + { "3.3.3.3", 32, 0 }, + { "4.4.4.4", 0, 0 } }; PJ_LOG(3,(THIS_FILE, " Performing round-robin/load-balance test..")); @@ -420,88 +419,88 @@ static int round_robin_test(pj_pool_t *pool) * the the servers in the SRV entry. */ for (i=0; isin_addr.s_addr) { - server_hit[j].hits++; - break; - } - } - - if (j == PJ_ARRAY_SIZE(server_hit)) { - PJ_LOG(1,(THIS_FILE, "..round_robin_test() error 10: returned address mismatch")); - return 10; - } + pjsip_host_info dest; + struct result result; + unsigned j; + + dest.type = PJSIP_TRANSPORT_UDP; + dest.flag = pjsip_transport_get_flag_from_type(PJSIP_TRANSPORT_UDP); + dest.addr.host = pj_str("example.com"); + dest.addr.port = 0; + + result.status = 0x12345678; + + pjsip_endpt_resolve(endpt, pool, &dest, &result, &cb); + + while (result.status == 0x12345678) { + int ii = 0; + pj_time_val timeout = { 1, 0 }; + pjsip_endpt_handle_events(endpt, &timeout); + if (ii == 1) + pj_dns_resolver_dump(pjsip_endpt_get_resolver(endpt), PJ_TRUE); + } + + /* Find which server was "hit" */ + for (j=0; jsin_addr.s_addr) { + server_hit[j].hits++; + break; + } + } + + if (j == PJ_ARRAY_SIZE(server_hit)) { + PJ_LOG(1,(THIS_FILE, "..round_robin_test() error 10: returned address mismatch")); + return 10; + } } /* Print the actual hit rate */ for (i=0; i (int)server_hit[i].percent) - { - PJ_LOG(1,(THIS_FILE, - "..round_robin_test() error 20: " - "hit rate difference for server %s (%d%%) is more than " - "tolerable allowance (%d%%)", - server_hit[i].ip_addr, - actual_pct - server_hit[i].percent, - PCT_ALLOWANCE)); - return 20; - } + int actual_pct = (server_hit[i].hits * 100) / COUNT; + + if (actual_pct + PCT_ALLOWANCE < (int)server_hit[i].percent || + actual_pct - PCT_ALLOWANCE > (int)server_hit[i].percent) + { + PJ_LOG(1,(THIS_FILE, + "..round_robin_test() error 20: " + "hit rate difference for server %s (%d%%) is more than " + "tolerable allowance (%d%%)", + server_hit[i].ip_addr, + actual_pct - server_hit[i].percent, + PCT_ALLOWANCE)); + return 20; + } } PJ_LOG(3,(THIS_FILE, - " Load balance test success, hit-rate is " - "within %d%% allowance", PCT_ALLOWANCE)); + " Load balance test success, hit-rate is " + "within %d%% allowance", PCT_ALLOWANCE)); return PJ_SUCCESS; } -#define C(expr) status = expr; \ - if (status != PJ_SUCCESS) app_perror(THIS_FILE, "Error", status); +#define C(expr) status = expr; \ + if (status != PJ_SUCCESS) app_perror(THIS_FILE, "Error", status); static void add_ref(pjsip_server_addresses *r, - pjsip_transport_type_e type, - char *addr, - int port) + pjsip_transport_type_e type, + char *addr, + int port) { pj_sockaddr_in *a; pj_str_t tmp; @@ -521,9 +520,9 @@ static void add_ref(pjsip_server_addresses *r, } static void create_ref(pjsip_server_addresses *r, - pjsip_transport_type_e type, - char *addr, - int port) + pjsip_transport_type_e type, + char *addr, + int port) { r->count = 0; add_ref(r, type, addr, port); @@ -553,92 +552,92 @@ int resolve_test(void) /* These all should be resolved as IP addresses (DNS A query) */ { - pjsip_server_addresses ref; - create_ref(&ref, PJSIP_TRANSPORT_UDP, "1.1.1.1", 5060); - status = test_resolve("IP address without transport and port", pool, PJSIP_TRANSPORT_UNSPECIFIED, "1.1.1.1", 0, &ref); - if (status != PJ_SUCCESS) - return -100; + pjsip_server_addresses ref; + create_ref(&ref, PJSIP_TRANSPORT_UDP, "1.1.1.1", 5060); + status = test_resolve("IP address without transport and port", pool, PJSIP_TRANSPORT_UNSPECIFIED, "1.1.1.1", 0, &ref); + if (status != PJ_SUCCESS) + return -100; } { - pjsip_server_addresses ref; - create_ref(&ref, PJSIP_TRANSPORT_UDP, "1.1.1.1", 5060); - status = test_resolve("IP address with explicit port", pool, PJSIP_TRANSPORT_UNSPECIFIED, "1.1.1.1", 5060, &ref); - if (status != PJ_SUCCESS) - return -110; + pjsip_server_addresses ref; + create_ref(&ref, PJSIP_TRANSPORT_UDP, "1.1.1.1", 5060); + status = test_resolve("IP address with explicit port", pool, PJSIP_TRANSPORT_UNSPECIFIED, "1.1.1.1", 5060, &ref); + if (status != PJ_SUCCESS) + return -110; } { - pjsip_server_addresses ref; - create_ref(&ref, PJSIP_TRANSPORT_TCP, "1.1.1.1", 5060); - status = test_resolve("IP address without port (TCP)", pool, PJSIP_TRANSPORT_TCP,"1.1.1.1", 0, &ref); - if (status != PJ_SUCCESS) - return -120; + pjsip_server_addresses ref; + create_ref(&ref, PJSIP_TRANSPORT_TCP, "1.1.1.1", 5060); + status = test_resolve("IP address without port (TCP)", pool, PJSIP_TRANSPORT_TCP,"1.1.1.1", 0, &ref); + if (status != PJ_SUCCESS) + return -120; } { - pjsip_server_addresses ref; - create_ref(&ref, PJSIP_TRANSPORT_TLS, "1.1.1.1", 5061); - status = test_resolve("IP address without port (TLS)", pool, PJSIP_TRANSPORT_TLS, "1.1.1.1", 0, &ref); - if (status != PJ_SUCCESS) - return -130; + pjsip_server_addresses ref; + create_ref(&ref, PJSIP_TRANSPORT_TLS, "1.1.1.1", 5061); + status = test_resolve("IP address without port (TLS)", pool, PJSIP_TRANSPORT_TLS, "1.1.1.1", 0, &ref); + if (status != PJ_SUCCESS) + return -130; } /* This should be resolved as DNS A record (because port is present) */ { - pjsip_server_addresses ref; - create_ref(&ref, PJSIP_TRANSPORT_UDP, "5.5.5.5", 5060); - status = test_resolve("domain name with port should resolve to A record", pool, PJSIP_TRANSPORT_UNSPECIFIED, "example.com", 5060, &ref); - if (status != PJ_SUCCESS) - return -140; + pjsip_server_addresses ref; + create_ref(&ref, PJSIP_TRANSPORT_UDP, "5.5.5.5", 5060); + status = test_resolve("domain name with port should resolve to A record", pool, PJSIP_TRANSPORT_UNSPECIFIED, "example.com", 5060, &ref); + if (status != PJ_SUCCESS) + return -140; } /* This will fail to be resolved as SRV, resolver should fallback to * resolving to A record. */ { - pjsip_server_addresses ref; - create_ref(&ref, PJSIP_TRANSPORT_UDP, "2.2.2.2", 5060); - status = test_resolve("failure with SRV fallback to A record", pool, PJSIP_TRANSPORT_UNSPECIFIED, "sip02.example.com", 0, &ref); - if (status != PJ_SUCCESS) - return -150; + pjsip_server_addresses ref; + create_ref(&ref, PJSIP_TRANSPORT_UDP, "2.2.2.2", 5060); + status = test_resolve("failure with SRV fallback to A record", pool, PJSIP_TRANSPORT_UNSPECIFIED, "sip02.example.com", 0, &ref); + if (status != PJ_SUCCESS) + return -150; } /* Same as above, but explicitly for TLS. */ { - pjsip_server_addresses ref; - create_ref(&ref, PJSIP_TRANSPORT_TLS, "2.2.2.2", 5061); - status = test_resolve("failure with SRV fallback to A record (for TLS)", pool, PJSIP_TRANSPORT_TLS, "sip02.example.com", 0, &ref); - if (status != PJ_SUCCESS) - return -150; + pjsip_server_addresses ref; + create_ref(&ref, PJSIP_TRANSPORT_TLS, "2.2.2.2", 5061); + status = test_resolve("failure with SRV fallback to A record (for TLS)", pool, PJSIP_TRANSPORT_TLS, "sip02.example.com", 0, &ref); + if (status != PJ_SUCCESS) + return -150; } /* Standard DNS SRV followed by A recolution */ { - pjsip_server_addresses ref; - create_ref(&ref, PJSIP_TRANSPORT_UDP, "6.6.6.6", 50060); - status = test_resolve("standard SRV resolution", pool, PJSIP_TRANSPORT_UNSPECIFIED, "domain.com", 0, &ref); - if (status != PJ_SUCCESS) - return -155; + pjsip_server_addresses ref; + create_ref(&ref, PJSIP_TRANSPORT_UDP, "6.6.6.6", 50060); + status = test_resolve("standard SRV resolution", pool, PJSIP_TRANSPORT_UNSPECIFIED, "domain.com", 0, &ref); + if (status != PJ_SUCCESS) + return -155; } /* Standard DNS SRV followed by A recolution (explicit transport) */ { - pjsip_server_addresses ref; - create_ref(&ref, PJSIP_TRANSPORT_TCP, "6.6.6.6", 50060); - add_ref(&ref, PJSIP_TRANSPORT_TCP, "7.7.7.7", 50060); - status = test_resolve("standard SRV resolution with explicit transport (TCP)", pool, PJSIP_TRANSPORT_TCP, "domain.com", 0, &ref); - if (status != PJ_SUCCESS) - return -160; + pjsip_server_addresses ref; + create_ref(&ref, PJSIP_TRANSPORT_TCP, "6.6.6.6", 50060); + add_ref(&ref, PJSIP_TRANSPORT_TCP, "7.7.7.7", 50060); + status = test_resolve("standard SRV resolution with explicit transport (TCP)", pool, PJSIP_TRANSPORT_TCP, "domain.com", 0, &ref); + if (status != PJ_SUCCESS) + return -160; } /* Round robin/load balance test */ if (round_robin_test(pool) != 0) - return -170; + return -170; /* Timeout test */ { - status = test_resolve("timeout test", pool, PJSIP_TRANSPORT_UNSPECIFIED, "an.invalid.address", 0, NULL); - if (status == PJ_SUCCESS) - return -150; + status = test_resolve("timeout test", pool, PJSIP_TRANSPORT_UNSPECIFIED, "an.invalid.address", 0, NULL); + if (status == PJ_SUCCESS) + return -150; } return 0; diff --git a/pjsip/src/test/inv_offer_answer_test.c b/pjsip/src/test/inv_offer_answer_test.c index 817955e7ab..2fc0d22c7e 100644 --- a/pjsip/src/test/inv_offer_answer_test.c +++ b/pjsip/src/test/inv_offer_answer_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -24,100 +23,100 @@ #include #define THIS_FILE "inv_offer_answer_test.c" -#define PORT 5068 -#define CONTACT "sip:127.0.0.1:5068" +#define PORT 5068 +#define CONTACT "sip:127.0.0.1:5068" #define TRACE_(x) PJ_LOG(3,x) static struct oa_sdp_t { const char *offer; const char *answer; - unsigned pt_result; + unsigned pt_result; } oa_sdp[] = { { - /* Offer: */ - "v=0\r\n" - "o=alice 1 1 IN IP4 host.anywhere.com\r\n" - "s= \r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n", - - /* Answer: */ - "v=0\r\n" - "o=bob 1 1 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 49920 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n", - - 0 + /* Offer: */ + "v=0\r\n" + "o=alice 1 1 IN IP4 host.anywhere.com\r\n" + "s= \r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n", + + /* Answer: */ + "v=0\r\n" + "o=bob 1 1 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 49920 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n", + + 0 }, { - /* Offer: */ - "v=0\r\n" - "o=alice 2 2 IN IP4 host.anywhere.com\r\n" - "s= \r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 8\r\n" - "a=rtpmap:0 PCMA/8000\r\n", - - /* Answer: */ - "v=0\r\n" - "o=bob 2 2 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 49920 RTP/AVP 8\r\n" - "a=rtpmap:0 PCMA/8000\r\n", - - 8 + /* Offer: */ + "v=0\r\n" + "o=alice 2 2 IN IP4 host.anywhere.com\r\n" + "s= \r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 8\r\n" + "a=rtpmap:0 PCMA/8000\r\n", + + /* Answer: */ + "v=0\r\n" + "o=bob 2 2 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 49920 RTP/AVP 8\r\n" + "a=rtpmap:0 PCMA/8000\r\n", + + 8 }, { - /* Offer: */ - "v=0\r\n" - "o=alice 3 3 IN IP4 host.anywhere.com\r\n" - "s= \r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 3\r\n", - - /* Answer: */ - "v=0\r\n" - "o=bob 3 3 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 49920 RTP/AVP 3\r\n", - - 3 + /* Offer: */ + "v=0\r\n" + "o=alice 3 3 IN IP4 host.anywhere.com\r\n" + "s= \r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 3\r\n", + + /* Answer: */ + "v=0\r\n" + "o=bob 3 3 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 49920 RTP/AVP 3\r\n", + + 3 }, { - /* Offer: */ - "v=0\r\n" - "o=alice 4 4 IN IP4 host.anywhere.com\r\n" - "s= \r\n" - "c=IN IP4 host.anywhere.com\r\n" - "t=0 0\r\n" - "m=audio 49170 RTP/AVP 4\r\n", - - /* Answer: */ - "v=0\r\n" - "o=bob 4 4 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 49920 RTP/AVP 4\r\n", - - 4 + /* Offer: */ + "v=0\r\n" + "o=alice 4 4 IN IP4 host.anywhere.com\r\n" + "s= \r\n" + "c=IN IP4 host.anywhere.com\r\n" + "t=0 0\r\n" + "m=audio 49170 RTP/AVP 4\r\n", + + /* Answer: */ + "v=0\r\n" + "o=bob 4 4 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 49920 RTP/AVP 4\r\n", + + 4 } }; @@ -133,32 +132,32 @@ typedef enum oa_t typedef struct inv_test_param_t { char *title; - unsigned inv_option; - pj_bool_t need_established; - unsigned count; - oa_t oa[4]; - pj_bool_t multipart_body; + unsigned inv_option; + pj_bool_t need_established; + unsigned count; + oa_t oa[4]; + pj_bool_t multipart_body; } inv_test_param_t; typedef struct inv_test_t { - inv_test_param_t param; + inv_test_param_t param; pjsip_inv_session *uac; pjsip_inv_session *uas; - pj_bool_t complete; - pj_bool_t uas_complete, - uac_complete; + pj_bool_t complete; + pj_bool_t uas_complete, + uac_complete; - unsigned oa_index; - unsigned uac_update_cnt, - uas_update_cnt; + unsigned oa_index; + unsigned uac_update_cnt, + uas_update_cnt; } inv_test_t; /**************** GLOBALS ******************/ static inv_test_t inv_test; -static unsigned job_cnt; +static unsigned job_cnt; typedef enum job_type { @@ -168,7 +167,7 @@ typedef enum job_type typedef struct job_t { - job_type type; + job_type type; pjsip_role_e who; } job_t; @@ -192,7 +191,7 @@ static pjmedia_sdp_session *create_sdp(pj_pool_t *pool, const char *body) /**************** INVITE SESSION CALLBACKS ******************/ static void on_rx_offer(pjsip_inv_session *inv, - const pjmedia_sdp_session *offer) + const pjmedia_sdp_session *offer) { pjmedia_sdp_session *sdp; @@ -202,17 +201,17 @@ static void on_rx_offer(pjsip_inv_session *inv, pjsip_inv_set_sdp_answer(inv, sdp); if (inv_test.oa_index == inv_test.param.count-1 && - inv_test.param.need_established) + inv_test.param.need_established) { - jobs[job_cnt].type = ESTABLISH_CALL; - jobs[job_cnt].who = PJSIP_ROLE_UAS; - job_cnt++; + jobs[job_cnt].type = ESTABLISH_CALL; + jobs[job_cnt].who = PJSIP_ROLE_UAS; + job_cnt++; } } static void on_create_offer(pjsip_inv_session *inv, - pjmedia_sdp_session **p_offer) + pjmedia_sdp_session **p_offer) { PJ_UNUSED_ARG(inv); PJ_UNUSED_ARG(p_offer); @@ -221,55 +220,55 @@ static void on_create_offer(pjsip_inv_session *inv, } static void on_media_update(pjsip_inv_session *inv_ses, - pj_status_t status) + pj_status_t status) { PJ_UNUSED_ARG(status); if (inv_ses == inv_test.uas) { - inv_test.uas_update_cnt++; - pj_assert(inv_test.uas_update_cnt - inv_test.uac_update_cnt <= 1); - TRACE_((THIS_FILE, " Callee media is established")); + inv_test.uas_update_cnt++; + pj_assert(inv_test.uas_update_cnt - inv_test.uac_update_cnt <= 1); + TRACE_((THIS_FILE, " Callee media is established")); } else if (inv_ses == inv_test.uac) { - inv_test.uac_update_cnt++; - pj_assert(inv_test.uac_update_cnt - inv_test.uas_update_cnt <= 1); - TRACE_((THIS_FILE, " Caller media is established")); - + inv_test.uac_update_cnt++; + pj_assert(inv_test.uac_update_cnt - inv_test.uas_update_cnt <= 1); + TRACE_((THIS_FILE, " Caller media is established")); + } else { - pj_assert(!"Unknown session!"); + pj_assert(!"Unknown session!"); } if (inv_test.uac_update_cnt == inv_test.uas_update_cnt) { - inv_test.oa_index++; - - if (inv_test.oa_index < inv_test.param.count) { - switch (inv_test.param.oa[inv_test.oa_index]) { - case OFFERER_UAC: - jobs[job_cnt].type = SEND_OFFER; - jobs[job_cnt].who = PJSIP_ROLE_UAC; - job_cnt++; - break; - case OFFERER_UAS: - jobs[job_cnt].type = SEND_OFFER; - jobs[job_cnt].who = PJSIP_ROLE_UAS; - job_cnt++; - break; - default: - pj_assert(!"Invalid oa"); - } - } - - /* Special handling for standard offer/answer */ - if (inv_test.param.count == 1 && - inv_test.param.oa[0] == OFFERER_UAC && - inv_test.param.need_established) - { - jobs[job_cnt].type = ESTABLISH_CALL; - jobs[job_cnt].who = PJSIP_ROLE_UAS; - job_cnt++; - TRACE_((THIS_FILE, " C+++")); - } - - pj_assert(job_cnt <= PJ_ARRAY_SIZE(jobs)); + inv_test.oa_index++; + + if (inv_test.oa_index < inv_test.param.count) { + switch (inv_test.param.oa[inv_test.oa_index]) { + case OFFERER_UAC: + jobs[job_cnt].type = SEND_OFFER; + jobs[job_cnt].who = PJSIP_ROLE_UAC; + job_cnt++; + break; + case OFFERER_UAS: + jobs[job_cnt].type = SEND_OFFER; + jobs[job_cnt].who = PJSIP_ROLE_UAS; + job_cnt++; + break; + default: + pj_assert(!"Invalid oa"); + } + } + + /* Special handling for standard offer/answer */ + if (inv_test.param.count == 1 && + inv_test.param.oa[0] == OFFERER_UAC && + inv_test.param.need_established) + { + jobs[job_cnt].type = ESTABLISH_CALL; + jobs[job_cnt].who = PJSIP_ROLE_UAS; + job_cnt++; + TRACE_((THIS_FILE, " C+++")); + } + + pj_assert(job_cnt <= PJ_ARRAY_SIZE(jobs)); } } @@ -280,27 +279,27 @@ static void on_state_changed(pjsip_inv_session *inv, pjsip_event *e) PJ_UNUSED_ARG(e); if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { - TRACE_((THIS_FILE, " %s call disconnected", - (inv==inv_test.uas ? "Callee" : "Caller"))); - return; + TRACE_((THIS_FILE, " %s call disconnected", + (inv==inv_test.uas ? "Callee" : "Caller"))); + return; } if (inv->state != PJSIP_INV_STATE_CONFIRMED) - return; + return; if (inv == inv_test.uas) { - inv_test.uas_complete = PJ_TRUE; - who = "Callee"; + inv_test.uas_complete = PJ_TRUE; + who = "Callee"; } else if (inv == inv_test.uac) { - inv_test.uac_complete = PJ_TRUE; - who = "Caller"; + inv_test.uac_complete = PJ_TRUE; + who = "Caller"; } else - pj_assert(!"No session"); + pj_assert(!"No session"); TRACE_((THIS_FILE, " %s call is confirmed", who)); if (inv_test.uac_complete && inv_test.uas_complete) - inv_test.complete = PJ_TRUE; + inv_test.complete = PJ_TRUE; } @@ -309,55 +308,55 @@ static void on_state_changed(pjsip_inv_session *inv, pjsip_event *e) static pj_bool_t on_rx_request(pjsip_rx_data *rdata) { if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG && - rdata->msg_info.msg->line.req.method.id == PJSIP_INVITE_METHOD) + rdata->msg_info.msg->line.req.method.id == PJSIP_INVITE_METHOD) { - pjsip_dialog *dlg; - pjmedia_sdp_session *sdp = NULL; - pj_str_t uri; - pjsip_tx_data *tdata; - pj_status_t status; - - /* - * Create UAS - */ - uri = pj_str(CONTACT); - status = pjsip_dlg_create_uas_and_inc_lock(pjsip_ua_instance(), rdata, - &uri, &dlg); - pj_assert(status == PJ_SUCCESS); - - if (inv_test.param.oa[0] == OFFERER_UAC) - sdp = create_sdp(rdata->tp_info.pool, oa_sdp[0].answer); - else if (inv_test.param.oa[0] == OFFERER_UAS) - sdp = create_sdp(rdata->tp_info.pool, oa_sdp[0].offer); - else - pj_assert(!"Invalid offerer type"); - - status = pjsip_inv_create_uas(dlg, rdata, sdp, inv_test.param.inv_option, &inv_test.uas); - pj_assert(status == PJ_SUCCESS); - pjsip_dlg_dec_lock(dlg); - - TRACE_((THIS_FILE, " Sending 183 with SDP")); - - /* - * Answer with 183 - */ - status = pjsip_inv_initial_answer(inv_test.uas, rdata, 183, NULL, - NULL, &tdata); - pj_assert(status == PJ_SUCCESS); - - /* Use multipart body, if configured */ - if (sdp && inv_test.param.multipart_body) { - status = pjsip_create_multipart_sdp_body( - tdata->pool, - pjmedia_sdp_session_clone(tdata->pool, sdp), - &tdata->msg->body); - } - pj_assert(status == PJ_SUCCESS); - - status = pjsip_inv_send_msg(inv_test.uas, tdata); - pj_assert(status == PJ_SUCCESS); - - return (status == PJ_SUCCESS); + pjsip_dialog *dlg; + pjmedia_sdp_session *sdp = NULL; + pj_str_t uri; + pjsip_tx_data *tdata; + pj_status_t status; + + /* + * Create UAS + */ + uri = pj_str(CONTACT); + status = pjsip_dlg_create_uas_and_inc_lock(pjsip_ua_instance(), rdata, + &uri, &dlg); + pj_assert(status == PJ_SUCCESS); + + if (inv_test.param.oa[0] == OFFERER_UAC) + sdp = create_sdp(rdata->tp_info.pool, oa_sdp[0].answer); + else if (inv_test.param.oa[0] == OFFERER_UAS) + sdp = create_sdp(rdata->tp_info.pool, oa_sdp[0].offer); + else + pj_assert(!"Invalid offerer type"); + + status = pjsip_inv_create_uas(dlg, rdata, sdp, inv_test.param.inv_option, &inv_test.uas); + pj_assert(status == PJ_SUCCESS); + pjsip_dlg_dec_lock(dlg); + + TRACE_((THIS_FILE, " Sending 183 with SDP")); + + /* + * Answer with 183 + */ + status = pjsip_inv_initial_answer(inv_test.uas, rdata, 183, NULL, + NULL, &tdata); + pj_assert(status == PJ_SUCCESS); + + /* Use multipart body, if configured */ + if (sdp && inv_test.param.multipart_body) { + status = pjsip_create_multipart_sdp_body( + tdata->pool, + pjmedia_sdp_session_clone(tdata->pool, sdp), + &tdata->msg->body); + } + pj_assert(status == PJ_SUCCESS); + + status = pjsip_inv_send_msg(inv_test.uas, tdata); + pj_assert(status == PJ_SUCCESS); + + return (status == PJ_SUCCESS); } return PJ_FALSE; @@ -365,19 +364,19 @@ static pj_bool_t on_rx_request(pjsip_rx_data *rdata) static pjsip_module mod_inv_oa_test = { - NULL, NULL, /* prev, next. */ - { "mod-inv-oa-test", 15 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-inv-oa-test", 15 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; @@ -390,29 +389,29 @@ static void run_job(job_t *j) pj_status_t status; if (j->who == PJSIP_ROLE_UAC) - inv = inv_test.uac; + inv = inv_test.uac; else - inv = inv_test.uas; + inv = inv_test.uas; switch (j->type) { case SEND_OFFER: - sdp = create_sdp(inv->dlg->pool, oa_sdp[inv_test.oa_index].offer); + sdp = create_sdp(inv->dlg->pool, oa_sdp[inv_test.oa_index].offer); - TRACE_((THIS_FILE, " Sending UPDATE with offer")); - status = pjsip_inv_update(inv, NULL, sdp, &tdata); - pj_assert(status == PJ_SUCCESS); + TRACE_((THIS_FILE, " Sending UPDATE with offer")); + status = pjsip_inv_update(inv, NULL, sdp, &tdata); + pj_assert(status == PJ_SUCCESS); - status = pjsip_inv_send_msg(inv, tdata); - pj_assert(status == PJ_SUCCESS); - break; + status = pjsip_inv_send_msg(inv, tdata); + pj_assert(status == PJ_SUCCESS); + break; case ESTABLISH_CALL: - TRACE_((THIS_FILE, " Sending 200/OK")); - status = pjsip_inv_answer(inv, 200, NULL, NULL, &tdata); - pj_assert(status == PJ_SUCCESS); + TRACE_((THIS_FILE, " Sending 200/OK")); + status = pjsip_inv_answer(inv, 200, NULL, NULL, &tdata); + pj_assert(status == PJ_SUCCESS); - status = pjsip_inv_send_msg(inv, tdata); - pj_assert(status == PJ_SUCCESS); - break; + status = pjsip_inv_send_msg(inv, tdata); + pj_assert(status == PJ_SUCCESS); + break; } PJ_UNUSED_ARG(status); } @@ -438,13 +437,13 @@ static int perform_test(inv_test_param_t *param) * Create UAC */ status = pjsip_dlg_create_uac(pjsip_ua_instance(), - &uri, &uri, &uri, &uri, &dlg); + &uri, &uri, &uri, &uri, &dlg); PJ_ASSERT_RETURN(status==PJ_SUCCESS, -10); if (inv_test.param.oa[0] == OFFERER_UAC) - sdp = create_sdp(dlg->pool, oa_sdp[0].offer); + sdp = create_sdp(dlg->pool, oa_sdp[0].offer); else - sdp = NULL; + sdp = NULL; status = pjsip_inv_create_uac(dlg, sdp, inv_test.param.inv_option, &inv_test.uac); //inv_test.uac->create_multipart = param->multipart_body; @@ -460,10 +459,10 @@ static int perform_test(inv_test_param_t *param) /* Use multipart body, if configured */ if (sdp && param->multipart_body) { - status = pjsip_create_multipart_sdp_body( - tdata->pool, - pjmedia_sdp_session_clone(tdata->pool, sdp), - &tdata->msg->body); + status = pjsip_create_multipart_sdp_body( + tdata->pool, + pjmedia_sdp_session_clone(tdata->pool, sdp), + &tdata->msg->body); } PJ_ASSERT_RETURN(status==PJ_SUCCESS, -40); @@ -474,19 +473,19 @@ static int perform_test(inv_test_param_t *param) * Wait until test completes */ while (!inv_test.complete) { - pj_time_val delay = {0, 20}; + pj_time_val delay = {0, 20}; - pjsip_endpt_handle_events(endpt, &delay); + pjsip_endpt_handle_events(endpt, &delay); - while (job_cnt) { - job_t j; + while (job_cnt) { + job_t j; - j = jobs[0]; - pj_array_erase(jobs, sizeof(jobs[0]), job_cnt, 0); - --job_cnt; + j = jobs[0]; + pj_array_erase(jobs, sizeof(jobs[0]), job_cnt, 0); + --job_cnt; - run_job(&j); - } + run_job(&j); + } } flush_events(100); @@ -499,8 +498,8 @@ static int perform_test(inv_test_param_t *param) pj_assert(status == PJ_SUCCESS); if (tdata) { - status = pjsip_inv_send_msg(inv_test.uas, tdata); - pj_assert(status == PJ_SUCCESS); + status = pjsip_inv_send_msg(inv_test.uas, tdata); + pj_assert(status == PJ_SUCCESS); } flush_events(500); @@ -515,17 +514,17 @@ static pj_bool_t log_on_rx_msg(pjsip_rx_data *rdata) char info[80]; if (msg->type == PJSIP_REQUEST_MSG) - pj_ansi_snprintf(info, sizeof(info), "%.*s", - (int)msg->line.req.method.name.slen, - msg->line.req.method.name.ptr); + pj_ansi_snprintf(info, sizeof(info), "%.*s", + (int)msg->line.req.method.name.slen, + msg->line.req.method.name.ptr); else - pj_ansi_snprintf(info, sizeof(info), "%d/%.*s", - msg->line.status.code, - (int)rdata->msg_info.cseq->method.name.slen, - rdata->msg_info.cseq->method.name.ptr); + pj_ansi_snprintf(info, sizeof(info), "%d/%.*s", + msg->line.status.code, + (int)rdata->msg_info.cseq->method.name.slen, + rdata->msg_info.cseq->method.name.ptr); TRACE_((THIS_FILE, " Received %s %s sdp", info, - (msg->body ? "with" : "without"))); + (msg->body ? "with" : "without"))); return PJ_FALSE; } @@ -534,180 +533,180 @@ static pj_bool_t log_on_rx_msg(pjsip_rx_data *rdata) /* Message logger module. */ static pjsip_module mod_msg_logger = { - NULL, NULL, /* prev and next */ - { "mod-msg-loggee", 14}, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &log_on_rx_msg, /* on_rx_request() */ - &log_on_rx_msg, /* on_rx_response() */ - NULL, /* on_tx_request() */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev and next */ + { "mod-msg-loggee", 14}, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &log_on_rx_msg, /* on_rx_request() */ + &log_on_rx_msg, /* on_rx_response() */ + NULL, /* on_tx_request() */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; static inv_test_param_t test_params[] = { /* Normal scenario: - UAC UAS - INVITE (offer) --> - 200/INVITE (answer) <-- - ACK --> + UAC UAS + INVITE (offer) --> + 200/INVITE (answer) <-- + ACK --> */ #if 1 { - "Standard INVITE with offer", - 0, - PJ_TRUE, - 1, - { OFFERER_UAC }, - PJ_FALSE + "Standard INVITE with offer", + 0, + PJ_TRUE, + 1, + { OFFERER_UAC }, + PJ_FALSE }, { - "Standard INVITE with offer, with 100rel", - PJSIP_INV_REQUIRE_100REL, - PJ_TRUE, - 1, - { OFFERER_UAC }, - PJ_FALSE + "Standard INVITE with offer, with 100rel", + PJSIP_INV_REQUIRE_100REL, + PJ_TRUE, + 1, + { OFFERER_UAC }, + PJ_FALSE }, { - "Standard INVITE with offer, with Multipart", - 0, - PJ_TRUE, - 1, - { OFFERER_UAC }, - PJ_TRUE + "Standard INVITE with offer, with Multipart", + 0, + PJ_TRUE, + 1, + { OFFERER_UAC }, + PJ_TRUE }, { - "Standard INVITE with offer, with 100rel, with Multipart", - PJSIP_INV_REQUIRE_100REL, - PJ_TRUE, - 1, - { OFFERER_UAC }, - PJ_TRUE + "Standard INVITE with offer, with 100rel, with Multipart", + PJSIP_INV_REQUIRE_100REL, + PJ_TRUE, + 1, + { OFFERER_UAC }, + PJ_TRUE }, #endif /* Delayed offer: - UAC UAS - INVITE (no SDP) --> - 200/INVITE (offer) <-- - ACK (answer) --> + UAC UAS + INVITE (no SDP) --> + 200/INVITE (offer) <-- + ACK (answer) --> */ #if 1 { - "INVITE with no offer", - 0, - PJ_TRUE, - 1, - { OFFERER_UAS }, - PJ_FALSE + "INVITE with no offer", + 0, + PJ_TRUE, + 1, + { OFFERER_UAS }, + PJ_FALSE }, { - "INVITE with no offer, with 100rel", - PJSIP_INV_REQUIRE_100REL, - PJ_TRUE, - 1, - { OFFERER_UAS }, - PJ_FALSE + "INVITE with no offer, with 100rel", + PJSIP_INV_REQUIRE_100REL, + PJ_TRUE, + 1, + { OFFERER_UAS }, + PJ_FALSE }, { - "INVITE with no offer, with Multipart", - 0, - PJ_TRUE, - 1, - { OFFERER_UAS }, - PJ_TRUE + "INVITE with no offer, with Multipart", + 0, + PJ_TRUE, + 1, + { OFFERER_UAS }, + PJ_TRUE }, { - "INVITE with no offer, with 100rel, with Multipart", - PJSIP_INV_REQUIRE_100REL, - PJ_TRUE, - 1, - { OFFERER_UAS }, - PJ_TRUE + "INVITE with no offer, with 100rel, with Multipart", + PJSIP_INV_REQUIRE_100REL, + PJ_TRUE, + 1, + { OFFERER_UAS }, + PJ_TRUE }, #endif /* Subsequent UAC offer with UPDATE: - UAC UAS - INVITE (offer) --> - 180/rel (answer) <-- - UPDATE (offer) --> inv_update() on_rx_offer() - set_sdp_answer() - 200/UPDATE (answer) <-- - 200/INVITE <-- - ACK --> + UAC UAS + INVITE (offer) --> + 180/rel (answer) <-- + UPDATE (offer) --> inv_update() on_rx_offer() + set_sdp_answer() + 200/UPDATE (answer) <-- + 200/INVITE <-- + ACK --> */ #if 1 #if !PJSIP_INV_UPDATE_EARLY_CHECK_RELIABLE { - "INVITE and UPDATE by UAC", - 0, - PJ_TRUE, - 2, - { OFFERER_UAC, OFFERER_UAC }, - PJ_FALSE + "INVITE and UPDATE by UAC", + 0, + PJ_TRUE, + 2, + { OFFERER_UAC, OFFERER_UAC }, + PJ_FALSE }, #endif { - "INVITE and UPDATE by UAC, with Multipart, with 100rel", - PJSIP_INV_REQUIRE_100REL, - PJ_TRUE, - 2, - { OFFERER_UAC, OFFERER_UAC }, - PJ_TRUE + "INVITE and UPDATE by UAC, with Multipart, with 100rel", + PJSIP_INV_REQUIRE_100REL, + PJ_TRUE, + 2, + { OFFERER_UAC, OFFERER_UAC }, + PJ_TRUE }, { - "INVITE and UPDATE by UAC, with 100rel", - PJSIP_INV_REQUIRE_100REL, - PJ_TRUE, - 2, - { OFFERER_UAC, OFFERER_UAC }, - PJ_FALSE + "INVITE and UPDATE by UAC, with 100rel", + PJSIP_INV_REQUIRE_100REL, + PJ_TRUE, + 2, + { OFFERER_UAC, OFFERER_UAC }, + PJ_FALSE }, #endif /* Subsequent UAS offer with UPDATE: - INVITE (offer --> - 180/rel (answer) <-- - UPDATE (offer) <-- inv_update() - on_rx_offer() - set_sdp_answer() + INVITE (offer --> + 180/rel (answer) <-- + UPDATE (offer) <-- inv_update() + on_rx_offer() + set_sdp_answer() 200/UPDATE (answer) --> - UPDATE (offer) --> on_rx_offer() - set_sdp_answer() + UPDATE (offer) --> on_rx_offer() + set_sdp_answer() 200/UPDATE (answer) <-- - 200/INVITE <-- - ACK --> + 200/INVITE <-- + ACK --> */ { - "INVITE and many UPDATE by UAC and UAS, with 100rel", - PJSIP_INV_REQUIRE_100REL, - PJ_TRUE, - 4, - { OFFERER_UAC, OFFERER_UAS, OFFERER_UAC, OFFERER_UAS } + "INVITE and many UPDATE by UAC and UAS, with 100rel", + PJSIP_INV_REQUIRE_100REL, + PJ_TRUE, + 4, + { OFFERER_UAC, OFFERER_UAS, OFFERER_UAC, OFFERER_UAS } }, { - "INVITE and many UPDATE by UAC and UAS, with Multipart, with 100rel", - PJSIP_INV_REQUIRE_100REL, - PJ_TRUE, - 4, - { OFFERER_UAC, OFFERER_UAS, OFFERER_UAC, OFFERER_UAS }, - PJ_TRUE + "INVITE and many UPDATE by UAC and UAS, with Multipart, with 100rel", + PJSIP_INV_REQUIRE_100REL, + PJ_TRUE, + 4, + { OFFERER_UAC, OFFERER_UAS, OFFERER_UAC, OFFERER_UAS }, + PJ_TRUE }, }; @@ -736,22 +735,22 @@ int inv_offer_answer_test(void) /* Init UA layer */ if (pjsip_ua_instance()->id == -1) { - pjsip_ua_init_param ua_param; - pj_bzero(&ua_param, sizeof(ua_param)); - ua_param.on_dlg_forked = &on_dlg_forked; - pjsip_ua_init_module(endpt, &ua_param); + pjsip_ua_init_param ua_param; + pj_bzero(&ua_param, sizeof(ua_param)); + ua_param.on_dlg_forked = &on_dlg_forked; + pjsip_ua_init_module(endpt, &ua_param); } /* Init inv-usage */ if (pjsip_inv_usage_instance()->id == -1) { - pjsip_inv_callback inv_cb; - pj_bzero(&inv_cb, sizeof(inv_cb)); - inv_cb.on_media_update = &on_media_update; - inv_cb.on_rx_offer = &on_rx_offer; - inv_cb.on_create_offer = &on_create_offer; - inv_cb.on_state_changed = &on_state_changed; - inv_cb.on_new_session = &on_new_session; - pjsip_inv_usage_init(endpt, &inv_cb); + pjsip_inv_callback inv_cb; + pj_bzero(&inv_cb, sizeof(inv_cb)); + inv_cb.on_media_update = &on_media_update; + inv_cb.on_rx_offer = &on_rx_offer; + inv_cb.on_create_offer = &on_create_offer; + inv_cb.on_state_changed = &on_state_changed; + inv_cb.on_new_session = &on_new_session; + pjsip_inv_usage_init(endpt, &inv_cb); } /* 100rel module */ @@ -763,21 +762,21 @@ int inv_offer_answer_test(void) /* Create SIP UDP transport */ { - pj_sockaddr_in addr; - pjsip_transport *tp; - pj_status_t status; - - pj_sockaddr_in_init(&addr, NULL, PORT); - status = pjsip_udp_transport_start(endpt, &addr, NULL, 1, &tp); - pj_assert(status == PJ_SUCCESS); - PJ_UNUSED_ARG(status); + pj_sockaddr_in addr; + pjsip_transport *tp; + pj_status_t status; + + pj_sockaddr_in_init(&addr, NULL, PORT); + status = pjsip_udp_transport_start(endpt, &addr, NULL, 1, &tp); + pj_assert(status == PJ_SUCCESS); + PJ_UNUSED_ARG(status); } /* Do tests */ for (i=0; i @@ -77,65 +76,65 @@ int main(int argc, char *argv[]) /* Parse arguments. */ opt_arg = argv+1; while (*opt_arg) { - if (strcmp(*opt_arg, "-i") == 0 || - strcmp(*opt_arg, "--interractive") == 0) - { - interractive = 1; - } else if (strcmp(*opt_arg, "-n") == 0 || - strcmp(*opt_arg, "--no-trap") == 0) - { - no_trap = 1; - } else if (strcmp(*opt_arg, "-h") == 0 || - strcmp(*opt_arg, "--help") == 0) - { - usage(); - return 1; - } else if (strcmp(*opt_arg, "-l") == 0 || - strcmp(*opt_arg, "--log-level") == 0) - { - ++opt_arg; - if (!opt_arg) { - usage(); - return 1; - } - log_level = atoi(*opt_arg); - } else if (strcmp(*opt_arg, "-s") == 0 || - strcmp(*opt_arg, "--system") == 0) - { - ++opt_arg; - if (!opt_arg) { - usage(); - return 1; - } - system_name = *opt_arg; - } else if (strcmp(*opt_arg, "-t") == 0 || - strcmp(*opt_arg, "--tests") == 0) - { - ++opt_arg; - if (!opt_arg) { - usage(); - return 1; - } - testlist = *opt_arg; - } else { - usage(); - return 1; - } + if (strcmp(*opt_arg, "-i") == 0 || + strcmp(*opt_arg, "--interractive") == 0) + { + interractive = 1; + } else if (strcmp(*opt_arg, "-n") == 0 || + strcmp(*opt_arg, "--no-trap") == 0) + { + no_trap = 1; + } else if (strcmp(*opt_arg, "-h") == 0 || + strcmp(*opt_arg, "--help") == 0) + { + usage(); + return 1; + } else if (strcmp(*opt_arg, "-l") == 0 || + strcmp(*opt_arg, "--log-level") == 0) + { + ++opt_arg; + if (!opt_arg) { + usage(); + return 1; + } + log_level = atoi(*opt_arg); + } else if (strcmp(*opt_arg, "-s") == 0 || + strcmp(*opt_arg, "--system") == 0) + { + ++opt_arg; + if (!opt_arg) { + usage(); + return 1; + } + system_name = *opt_arg; + } else if (strcmp(*opt_arg, "-t") == 0 || + strcmp(*opt_arg, "--tests") == 0) + { + ++opt_arg; + if (!opt_arg) { + usage(); + return 1; + } + testlist = *opt_arg; + } else { + usage(); + return 1; + } - ++opt_arg; + ++opt_arg; } if (!no_trap) { - init_signals(); + init_signals(); } retval = test_main(testlist); if (interractive) { - char s[10]; - printf("\n"); fflush(stdout); - if (fgets(s, sizeof(s), stdin) == NULL) - return retval; + char s[10]; + printf("\n"); fflush(stdout); + if (fgets(s, sizeof(s), stdin) == NULL) + return retval; } return retval; diff --git a/pjsip/src/test/msg_err_test.c b/pjsip/src/test/msg_err_test.c index 8ad7f9f6e9..14d15a3eed 100644 --- a/pjsip/src/test/msg_err_test.c +++ b/pjsip/src/test/msg_err_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,7 +24,7 @@ static pj_bool_t verify_success(pjsip_msg *msg, - pjsip_parser_err_report *err_list) + pjsip_parser_err_report *err_list) { PJ_UNUSED_ARG(msg); PJ_UNUSED_ARG(err_list); @@ -35,37 +34,37 @@ static pj_bool_t verify_success(pjsip_msg *msg, static struct test_entry { - char msg[1024]; + char msg[1024]; pj_bool_t (*verify)(pjsip_msg *msg, - pjsip_parser_err_report *err_list); + pjsip_parser_err_report *err_list); } test_entries[] = { /* Syntax error in status line */ { - "SIP/2.0 200\r\n" - "H-Name: H-Value\r\n" - "\r\n", - &verify_success + "SIP/2.0 200\r\n" + "H-Name: H-Value\r\n" + "\r\n", + &verify_success }, /* Syntax error in header */ { - "SIP/2.0 200 OK\r\n" - "Via: SIP/2.0\r\n" - "H-Name: H-Value\r\n" - "\r\n", - &verify_success + "SIP/2.0 200 OK\r\n" + "Via: SIP/2.0\r\n" + "H-Name: H-Value\r\n" + "\r\n", + &verify_success }, /* Multiple syntax errors in headers */ { - "SIP/2.0 200 OK\r\n" - "Via: SIP/2.0\r\n" - "H-Name: H-Value\r\n" - "Via: SIP/2.0\r\n" - "\r\n", - &verify_success + "SIP/2.0 200 OK\r\n" + "Via: SIP/2.0\r\n" + "H-Name: H-Value\r\n" + "Via: SIP/2.0\r\n" + "\r\n", + &verify_success } }; @@ -80,22 +79,22 @@ int msg_err_test(void) pool = pjsip_endpt_create_pool(endpt, "msgerrtest", 4000, 4000); for (i=0; iline, e->col, - (int)e->hname.slen, - e->hname.ptr)); - e = e->next; - } + pjsip_parser_err_report err_list, *e; + + PJ_LOG(3,(THIS_FILE, " Parsing msg %d", i)); + pj_list_init(&err_list); + pjsip_parse_msg(pool, test_entries[i].msg, + strlen(test_entries[i].msg), &err_list); + + e = err_list.next; + while (e != &err_list) { + PJ_LOG(3,(THIS_FILE, + " reported syntax error at line %d col %d for %.*s", + e->line, e->col, + (int)e->hname.slen, + e->hname.ptr)); + e = e->next; + } } pj_pool_release(pool); diff --git a/pjsip/src/test/msg_logger.c b/pjsip/src/test/msg_logger.c index ac058de151..d453314b51 100644 --- a/pjsip/src/test/msg_logger.c +++ b/pjsip/src/test/msg_logger.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,16 +27,16 @@ static pj_bool_t msg_log_enabled; static pj_bool_t on_rx_msg(pjsip_rx_data *rdata) { if (msg_log_enabled) { - PJ_LOG(4,(THIS_FILE, "RX %d bytes %s from %s:%s:%d:\n" - "%.*s\n" - "--end msg--", - rdata->msg_info.len, - pjsip_rx_data_get_info(rdata), - rdata->tp_info.transport->type_name, - rdata->pkt_info.src_name, - rdata->pkt_info.src_port, - rdata->msg_info.len, - rdata->msg_info.msg_buf)); + PJ_LOG(4,(THIS_FILE, "RX %d bytes %s from %s:%s:%d:\n" + "%.*s\n" + "--end msg--", + rdata->msg_info.len, + pjsip_rx_data_get_info(rdata), + rdata->tp_info.transport->type_name, + rdata->pkt_info.src_name, + rdata->pkt_info.src_port, + rdata->msg_info.len, + rdata->msg_info.msg_buf)); } return PJ_FALSE; @@ -46,16 +45,16 @@ static pj_bool_t on_rx_msg(pjsip_rx_data *rdata) static pj_status_t on_tx_msg(pjsip_tx_data *tdata) { if (msg_log_enabled) { - PJ_LOG(4,(THIS_FILE, "TX %d bytes %s to %s:%s:%d:\n" - "%.*s\n" - "--end msg--", - (tdata->buf.cur - tdata->buf.start), - pjsip_tx_data_get_info(tdata), - tdata->tp_info.transport->type_name, - tdata->tp_info.dst_name, - tdata->tp_info.dst_port, - (tdata->buf.cur - tdata->buf.start), - tdata->buf.start)); + PJ_LOG(4,(THIS_FILE, "TX %d bytes %s to %s:%s:%d:\n" + "%.*s\n" + "--end msg--", + (tdata->buf.cur - tdata->buf.start), + pjsip_tx_data_get_info(tdata), + tdata->tp_info.transport->type_name, + tdata->tp_info.dst_name, + tdata->tp_info.dst_port, + (tdata->buf.cur - tdata->buf.start), + tdata->buf.start)); } return PJ_SUCCESS; } @@ -64,19 +63,19 @@ static pj_status_t on_tx_msg(pjsip_tx_data *tdata) /* Message logger module. */ static pjsip_module mod_msg_logger = { - NULL, NULL, /* prev and next */ - { "mod-msg-logger", 14}, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &on_rx_msg, /* on_rx_request() */ - &on_rx_msg, /* on_rx_response() */ - &on_tx_msg, /* on_tx_request() */ - &on_tx_msg, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev and next */ + { "mod-msg-logger", 14}, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &on_rx_msg, /* on_rx_request() */ + &on_rx_msg, /* on_rx_response() */ + &on_tx_msg, /* on_tx_request() */ + &on_tx_msg, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; int init_msg_logger(void) @@ -84,12 +83,12 @@ int init_msg_logger(void) pj_status_t status; if (mod_msg_logger.id != -1) - return 0; + return 0; status = pjsip_endpt_register_module(endpt, &mod_msg_logger); if (status != PJ_SUCCESS) { - app_perror(" error registering module", status); - return -10; + app_perror(" error registering module", status); + return -10; } return 0; diff --git a/pjsip/src/test/msg_test.c b/pjsip/src/test/msg_test.c index 24e3d405dd..84ecf9ee1b 100644 --- a/pjsip/src/test/msg_test.c +++ b/pjsip/src/test/msg_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -21,31 +20,31 @@ #include #include -#define POOL_SIZE 8000 +#define POOL_SIZE 8000 #if defined(PJ_DEBUG) && PJ_DEBUG!=0 -# define LOOP 10000 +# define LOOP 10000 #else -# define LOOP 100000 +# define LOOP 100000 #endif -#define AVERAGE_MSG_LEN 800 -#define THIS_FILE "msg_test.c" +#define AVERAGE_MSG_LEN 800 +#define THIS_FILE "msg_test.c" static pjsip_msg *create_msg0(pj_pool_t *pool); static pjsip_msg *create_msg1(pj_pool_t *pool); -#define STATUS_PARTIAL 1 -#define STATUS_SYNTAX_ERROR 2 +#define STATUS_PARTIAL 1 +#define STATUS_SYNTAX_ERROR 2 -#define FLAG_DETECT_ONLY 1 -#define FLAG_PARSE_ONLY 4 -#define FLAG_PRINT_ONLY 8 +#define FLAG_DETECT_ONLY 1 +#define FLAG_PARSE_ONLY 4 +#define FLAG_PRINT_ONLY 8 struct test_msg { - char msg[1024]; + char msg[1024]; pjsip_msg *(*creator)(pj_pool_t *pool); - pj_size_t len; - int expected_status; + pj_size_t len; + int expected_status; } test_array[] = { { @@ -69,7 +68,7 @@ struct test_msg "Via: SIP/2.0/UDP 10.2.1.1, SIP/2.0/TCP 192.168.1.1\n" "Organization: \r" "Max-Forwards: 70\n" - "X-Header: \r\n" /* empty header */ + "X-Header: \r\n" /* empty header */ "P-Associated-URI:\r\n" /* empty header without space */ "\r\n", &create_msg0, @@ -258,15 +257,15 @@ static pj_status_t test_entry( pj_pool_t *pool, struct test_msg *entry ) enum { BUFLEN = 512 }; if (entry->len==0) - entry->len = pj_ansi_strlen(entry->msg); + entry->len = pj_ansi_strlen(entry->msg); if (var.flag & FLAG_PARSE_ONLY) - goto parse_msg; + goto parse_msg; if (var.flag & FLAG_PRINT_ONLY) { - if (print_msg == NULL) - print_msg = entry->creator(pool); - goto print_msg; + if (print_msg == NULL) + print_msg = entry->creator(pool); + goto print_msg; } /* Detect message. */ @@ -274,23 +273,23 @@ static pj_status_t test_entry( pj_pool_t *pool, struct test_msg *entry ) pj_get_timestamp(&t1); status = pjsip_find_msg(entry->msg, entry->len, PJ_FALSE, &msg_size); if (status != PJ_SUCCESS) { - if (status!=PJSIP_EPARTIALMSG || - entry->expected_status!=STATUS_PARTIAL) - { - app_perror(" error: unable to detect message", status); - return -5; - } + if (status!=PJSIP_EPARTIALMSG || + entry->expected_status!=STATUS_PARTIAL) + { + app_perror(" error: unable to detect message", status); + return -5; + } } if (msg_size != entry->len) { - PJ_LOG(3,(THIS_FILE, " error: size mismatch")); - return -6; + PJ_LOG(3,(THIS_FILE, " error: size mismatch")); + return -6; } pj_get_timestamp(&t2); pj_sub_timestamp(&t2, &t1); pj_add_timestamp(&var.detect_time, &t2); if (var.flag & FLAG_DETECT_ONLY) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Parse message. */ parse_msg: @@ -299,21 +298,21 @@ static pj_status_t test_entry( pj_pool_t *pool, struct test_msg *entry ) pj_list_init(&err_list); parsed_msg = pjsip_parse_msg(pool, entry->msg, entry->len, &err_list); if (parsed_msg == NULL) { - if (entry->expected_status != STATUS_SYNTAX_ERROR) { - status = -10; - if (err_list.next != &err_list) { - PJ_LOG(3,(THIS_FILE, " Syntax error in line %d col %d", - err_list.next->line, err_list.next->col)); - } - goto on_return; - } + if (entry->expected_status != STATUS_SYNTAX_ERROR) { + status = -10; + if (err_list.next != &err_list) { + PJ_LOG(3,(THIS_FILE, " Syntax error in line %d col %d", + err_list.next->line, err_list.next->col)); + } + goto on_return; + } } pj_get_timestamp(&t2); pj_sub_timestamp(&t2, &t1); pj_add_timestamp(&var.parse_time, &t2); if ((var.flag & FLAG_PARSE_ONLY) || entry->creator==NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; /* Create reference message. */ ref_msg = entry->creator(pool); @@ -324,40 +323,40 @@ static pj_status_t test_entry( pj_pool_t *pool, struct test_msg *entry ) /* Compare message type. */ if (parsed_msg->type != ref_msg->type) { - status = -20; - goto on_return; + status = -20; + goto on_return; } /* Compare request or status line. */ if (parsed_msg->type == PJSIP_REQUEST_MSG) { - pjsip_method *m1 = &parsed_msg->line.req.method; - pjsip_method *m2 = &ref_msg->line.req.method; - - if (pjsip_method_cmp(m1, m2) != 0) { - status = -30; - goto on_return; - } - status = pjsip_uri_cmp(PJSIP_URI_IN_REQ_URI, - parsed_msg->line.req.uri, - ref_msg->line.req.uri); - if (status != PJ_SUCCESS) { - app_perror(" error: request URI mismatch", status); - status = -31; - goto on_return; - } + pjsip_method *m1 = &parsed_msg->line.req.method; + pjsip_method *m2 = &ref_msg->line.req.method; + + if (pjsip_method_cmp(m1, m2) != 0) { + status = -30; + goto on_return; + } + status = pjsip_uri_cmp(PJSIP_URI_IN_REQ_URI, + parsed_msg->line.req.uri, + ref_msg->line.req.uri); + if (status != PJ_SUCCESS) { + app_perror(" error: request URI mismatch", status); + status = -31; + goto on_return; + } } else { - if (parsed_msg->line.status.code != ref_msg->line.status.code) { - PJ_LOG(3,(THIS_FILE, " error: status code mismatch")); - status = -32; - goto on_return; - } - if (pj_strcmp(&parsed_msg->line.status.reason, - &ref_msg->line.status.reason) != 0) - { - PJ_LOG(3,(THIS_FILE, " error: status text mismatch")); - status = -33; - goto on_return; - } + if (parsed_msg->line.status.code != ref_msg->line.status.code) { + PJ_LOG(3,(THIS_FILE, " error: status code mismatch")); + status = -32; + goto on_return; + } + if (pj_strcmp(&parsed_msg->line.status.reason, + &ref_msg->line.status.reason) != 0) + { + PJ_LOG(3,(THIS_FILE, " error: status text mismatch")); + status = -33; + goto on_return; + } } /* Compare headers. */ @@ -365,82 +364,82 @@ static pj_status_t test_entry( pj_pool_t *pool, struct test_msg *entry ) hdr2 = ref_msg->hdr.next; while (hdr1 != &parsed_msg->hdr && hdr2 != &ref_msg->hdr) { - len = pjsip_hdr_print_on(hdr1, str1.ptr, BUFLEN); - if (len < 0) { - status = -40; - goto on_return; - } - str1.ptr[len] = '\0'; - str1.slen = len; - - len = pjsip_hdr_print_on(hdr2, str2.ptr, BUFLEN); - if (len < 0) { - status = -50; - goto on_return; - } - str2.ptr[len] = '\0'; - str2.slen = len; - - if (pj_strcmp(&str1, &str2) != 0) { - status = -60; - PJ_LOG(3,(THIS_FILE, " error: header string mismatch:\n" - " h1='%s'\n" - " h2='%s'\n", - str1.ptr, str2.ptr)); - goto on_return; - } - - hdr1 = hdr1->next; - hdr2 = hdr2->next; + len = pjsip_hdr_print_on(hdr1, str1.ptr, BUFLEN); + if (len < 0) { + status = -40; + goto on_return; + } + str1.ptr[len] = '\0'; + str1.slen = len; + + len = pjsip_hdr_print_on(hdr2, str2.ptr, BUFLEN); + if (len < 0) { + status = -50; + goto on_return; + } + str2.ptr[len] = '\0'; + str2.slen = len; + + if (pj_strcmp(&str1, &str2) != 0) { + status = -60; + PJ_LOG(3,(THIS_FILE, " error: header string mismatch:\n" + " h1='%s'\n" + " h2='%s'\n", + str1.ptr, str2.ptr)); + goto on_return; + } + + hdr1 = hdr1->next; + hdr2 = hdr2->next; } if (hdr1 != &parsed_msg->hdr || hdr2 != &ref_msg->hdr) { - status = -70; - goto on_return; + status = -70; + goto on_return; } /* Compare body? */ if (parsed_msg->body==NULL && ref_msg->body==NULL) - goto print_msg; + goto print_msg; /* Compare msg body length. */ if (parsed_msg->body->len != ref_msg->body->len) { - status = -80; - goto on_return; + status = -80; + goto on_return; } /* Compare msg body content type. */ if (pj_strcmp(&parsed_msg->body->content_type.type, - &ref_msg->body->content_type.type) != 0) { - status = -90; - goto on_return; + &ref_msg->body->content_type.type) != 0) { + status = -90; + goto on_return; } if (pj_strcmp(&parsed_msg->body->content_type.subtype, - &ref_msg->body->content_type.subtype) != 0) { - status = -100; - goto on_return; + &ref_msg->body->content_type.subtype) != 0) { + status = -100; + goto on_return; } /* Compare body content. */ str1.slen = parsed_msg->body->print_body(parsed_msg->body, - msgbuf1, sizeof(msgbuf1)); + msgbuf1, sizeof(msgbuf1)); if (str1.slen < 1) { - status = -110; - goto on_return; + status = -110; + goto on_return; } str1.ptr = msgbuf1; str2.slen = ref_msg->body->print_body(ref_msg->body, - msgbuf2, sizeof(msgbuf2)); + msgbuf2, sizeof(msgbuf2)); if (str2.slen < 1) { - status = -120; - goto on_return; + status = -120; + goto on_return; } str2.ptr = msgbuf2; if (pj_strcmp(&str1, &str2) != 0) { - status = -140; - goto on_return; + status = -140; + goto on_return; } /* Print message. */ @@ -448,11 +447,11 @@ static pj_status_t test_entry( pj_pool_t *pool, struct test_msg *entry ) var.print_len = var.print_len + entry->len; pj_get_timestamp(&t1); if (var.flag & FLAG_PRINT_ONLY) - ref_msg = print_msg; + ref_msg = print_msg; len = pjsip_msg_print(ref_msg, msgbuf1, PJSIP_MAX_PKT_LEN); if (len < 1) { - status = -150; - goto on_return; + status = -150; + goto on_return; } pj_get_timestamp(&t2); pj_sub_timestamp(&t2, &t1); @@ -615,7 +614,7 @@ static pjsip_msg *create_msg0(pj_pool_t *pool) pj_strdup2(pool, &via->branch_param, "z9hG4bK77ef4c230"); /* "Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bKnashds8\n" - " ;received=192.0.2.1\r\n" */ + " ;received=192.0.2.1\r\n" */ via = pjsip_via_hdr_create(pool); pjsip_msg_add_hdr(msg, (pjsip_hdr*)via); pj_strdup2(pool, &via->transport, "UDP"); @@ -802,13 +801,13 @@ static pjsip_msg *create_msg1(pj_pool_t *pool) body->content_type.type = pj_str("application"); body->content_type.subtype = pj_str("sdp"); body->data = (void*) - "v=0\r\n" - "o=alice 53655765 2353687637 IN IP4 pc33.atlanta.com\r\n" - "s=-\r\n" - "t=0 0\r\n" - "c=IN IP4 pc33.atlanta.com\r\n" - "m=audio 3456 RTP/AVP 0 1 3 99\r\n" - "a=rtpmap:0 PCMU/8000\r\n"; + "v=0\r\n" + "o=alice 53655765 2353687637 IN IP4 pc33.atlanta.com\r\n" + "s=-\r\n" + "t=0 0\r\n" + "c=IN IP4 pc33.atlanta.com\r\n" + "m=audio 3456 RTP/AVP 0 1 3 99\r\n" + "a=rtpmap:0 PCMU/8000\r\n"; body->len = (unsigned)pj_ansi_strlen((const char*) body->data); body->print_body = &pjsip_print_text_body; @@ -828,16 +827,16 @@ static pj_status_t simple_test(void) status = pjsip_parse_status_line(stbuf, pj_ansi_strlen(stbuf), &st_line); if (status != PJ_SUCCESS) - return status; + return status; for (i=0; i" +#define ADDR_SPEC SIMPLE_ADDR_SPEC ";"PARAM_CHAR"="PARAM_CHAR ";p1=\";\"" +#define NAME_ADDR "<" ADDR_SPEC ">" #define HDR_FLAG_PARSE_FAIL 1 #define HDR_FLAG_DONT_PRINT 2 @@ -972,207 +971,207 @@ struct hdr_test_t } hdr_test_data[] = { { - /* Empty Accept */ - "Accept", NULL, - "", - &hdr_test_accept0 + /* Empty Accept */ + "Accept", NULL, + "", + &hdr_test_accept0 }, { - /* Overflowing generic string header */ - "Accept", NULL, - "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ - "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ - "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ - "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ - "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ - "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ - "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ - "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a", - &hdr_test_success, - HDR_FLAG_PARSE_FAIL + /* Overflowing generic string header */ + "Accept", NULL, + "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ + "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ + "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ + "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ + "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ + "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ + "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, " \ + "a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a", + &hdr_test_success, + HDR_FLAG_PARSE_FAIL }, { - /* Normal Accept */ - "Accept", NULL, - "application/*, text/plain", - &hdr_test_accept1 + /* Normal Accept */ + "Accept", NULL, + "application/*, text/plain", + &hdr_test_accept1 }, { - /* Accept with params */ - "Accept", NULL, - "application/*;p1=v1, text/plain", - &hdr_test_accept2 + /* Accept with params */ + "Accept", NULL, + "application/*;p1=v1, text/plain", + &hdr_test_accept2 }, { - /* Empty Allow */ - "Allow", NULL, - "", - &hdr_test_allow0, + /* Empty Allow */ + "Allow", NULL, + "", + &hdr_test_allow0, }, { - /* Authorization, testing which params should be quoted */ - "Authorization", NULL, - "Digest username=\"username\", realm=\"realm\", nonce=\"nonce\", " \ - "uri=\"sip:domain\", response=\"RESPONSE\", algorithm=MD5, " \ - "cnonce=\"CNONCE\", opaque=\"OPAQUE\", qop=auth, nc=00000001", - &hdr_test_authorization + /* Authorization, testing which params should be quoted */ + "Authorization", NULL, + "Digest username=\"username\", realm=\"realm\", nonce=\"nonce\", " \ + "uri=\"sip:domain\", response=\"RESPONSE\", algorithm=MD5, " \ + "cnonce=\"CNONCE\", opaque=\"OPAQUE\", qop=auth, nc=00000001", + &hdr_test_authorization }, { - /* Call ID */ - "Call-ID", "i", - "-.!%*_+`'~()<>:\\\"/[]?{}", - &hdr_test_cid, + /* Call ID */ + "Call-ID", "i", + "-.!%*_+`'~()<>:\\\"/[]?{}", + &hdr_test_cid, }, { - /* Parameter belong to hparam */ - "Contact", "m", - SIMPLE_ADDR_SPEC ";p1=v1", - &hdr_test_contact0, - HDR_FLAG_DONT_PRINT + /* Parameter belong to hparam */ + "Contact", "m", + SIMPLE_ADDR_SPEC ";p1=v1", + &hdr_test_contact0, + HDR_FLAG_DONT_PRINT }, { - /* generic-param in Contact header */ - "Contact", "m", - NAME_ADDR ";" GENERIC_PARAM, - &hdr_test_contact1 + /* generic-param in Contact header */ + "Contact", "m", + NAME_ADDR ";" GENERIC_PARAM, + &hdr_test_contact1 }, { - /* q=0 parameter in Contact header */ - "Contact", "m", - NAME_ADDR ";q=0", - &hdr_test_contact_q0, - HDR_FLAG_DONT_PRINT + /* q=0 parameter in Contact header */ + "Contact", "m", + NAME_ADDR ";q=0", + &hdr_test_contact_q0, + HDR_FLAG_DONT_PRINT }, { - /* q=0.5 parameter in Contact header */ - "Contact", "m", - NAME_ADDR ";q=0.5", - &hdr_test_contact_q1 + /* q=0.5 parameter in Contact header */ + "Contact", "m", + NAME_ADDR ";q=0.5", + &hdr_test_contact_q1 }, { - /* q=1 parameter in Contact header */ - "Contact", "m", - NAME_ADDR ";q=1", - &hdr_test_contact_q2 + /* q=1 parameter in Contact header */ + "Contact", "m", + NAME_ADDR ";q=1", + &hdr_test_contact_q2 }, { - /* q=1.0 parameter in Contact header */ - "Contact", "m", - NAME_ADDR ";q=1.0", - &hdr_test_contact_q3, - HDR_FLAG_DONT_PRINT + /* q=1.0 parameter in Contact header */ + "Contact", "m", + NAME_ADDR ";q=1.0", + &hdr_test_contact_q3, + HDR_FLAG_DONT_PRINT }, { - /* q=1.1 parameter in Contact header */ - "Contact", "m", - NAME_ADDR ";q=1.15", - &hdr_test_contact_q4 + /* q=1.1 parameter in Contact header */ + "Contact", "m", + NAME_ADDR ";q=1.15", + &hdr_test_contact_q4 }, { - /* Content-Length */ - "Content-Length", "l", - "10", - &hdr_test_content_length + /* Content-Length */ + "Content-Length", "l", + "10", + &hdr_test_content_length }, { - /* Content-Type, with generic-param */ - "Content-Type", "c", - "application/sdp" ";" GENERIC_PARAM, - &hdr_test_content_type, - HDR_FLAG_DONT_PRINT + /* Content-Type, with generic-param */ + "Content-Type", "c", + "application/sdp" ";" GENERIC_PARAM, + &hdr_test_content_type, + HDR_FLAG_DONT_PRINT }, { - /* From, testing parameters and generic-param */ - "From", "f", - NAME_ADDR ";" GENERIC_PARAM, - &hdr_test_from + /* From, testing parameters and generic-param */ + "From", "f", + NAME_ADDR ";" GENERIC_PARAM, + &hdr_test_from }, { - /* Proxy-Authenticate, testing which params should be quoted */ - "Proxy-Authenticate", NULL, - "Digest realm=\"realm\",domain=\"sip:domain\",nonce=\"nonce\"," \ - "opaque=\"opaque\",stale=true,algorithm=MD5,qop=\"auth\"", - &hdr_test_proxy_authenticate + /* Proxy-Authenticate, testing which params should be quoted */ + "Proxy-Authenticate", NULL, + "Digest realm=\"realm\",domain=\"sip:domain\",nonce=\"nonce\"," \ + "opaque=\"opaque\",stale=true,algorithm=MD5,qop=\"auth\"", + &hdr_test_proxy_authenticate }, { - /* Record-Route, param belong to header */ - "Record-Route", NULL, - NAME_ADDR ";" GENERIC_PARAM, - &hdr_test_record_route + /* Record-Route, param belong to header */ + "Record-Route", NULL, + NAME_ADDR ";" GENERIC_PARAM, + &hdr_test_record_route }, { - /* Empty Supported */ - "Supported", "k", - "", - &hdr_test_supported, + /* Empty Supported */ + "Supported", "k", + "", + &hdr_test_supported, }, { - /* To */ - "To", "t", - NAME_ADDR ";" GENERIC_PARAM, - &hdr_test_to + /* To */ + "To", "t", + NAME_ADDR ";" GENERIC_PARAM, + &hdr_test_to }, { - /* Via */ - "Via", "v", - "SIP/2.0/XYZ host" ";" GENERIC_PARAM, - &hdr_test_via + /* Via */ + "Via", "v", + "SIP/2.0/XYZ host" ";" GENERIC_PARAM, + &hdr_test_via }, { - /* Via with IPv6 */ - "Via", "v", - "SIP/2.0/UDP [::1]", - &hdr_test_via_ipv6_1 + /* Via with IPv6 */ + "Via", "v", + "SIP/2.0/UDP [::1]", + &hdr_test_via_ipv6_1 }, { - /* Via with IPv6 */ - "Via", "v", - "SIP/2.0/UDP [::1]:5061", - &hdr_test_via_ipv6_2 + /* Via with IPv6 */ + "Via", "v", + "SIP/2.0/UDP [::1]:5061", + &hdr_test_via_ipv6_2 }, { - /* Via with IPv6 */ - "Via", "v", - "SIP/2.0/UDP [::1];rport=5061;received=::2", - &hdr_test_via_ipv6_3 + /* Via with IPv6 */ + "Via", "v", + "SIP/2.0/UDP [::1];rport=5061;received=::2", + &hdr_test_via_ipv6_3 }, { - /* Retry-After header with comment */ - "Retry-After", NULL, - "10(Already Pending Register)", - &hdr_test_retry_after1 + /* Retry-After header with comment */ + "Retry-After", NULL, + "10(Already Pending Register)", + &hdr_test_retry_after1 }, { - /* Non-ASCII UTF-8 characters in Subject */ - "Subject", NULL, - "\xC0\x81", - &hdr_test_subject_utf + /* Non-ASCII UTF-8 characters in Subject */ + "Subject", NULL, + "\xC0\x81", + &hdr_test_subject_utf } }; @@ -1188,10 +1187,10 @@ static int hdr_test_accept0(pjsip_hdr *h) pjsip_accept_hdr *hdr = (pjsip_accept_hdr*)h; if (h->type != PJSIP_H_ACCEPT) - return -1010; + return -1010; if (hdr->count != 0) - return -1020; + return -1020; return 0; } @@ -1202,16 +1201,16 @@ static int hdr_test_accept1(pjsip_hdr *h) pjsip_accept_hdr *hdr = (pjsip_accept_hdr*)h; if (h->type != PJSIP_H_ACCEPT) - return -1110; + return -1110; if (hdr->count != 2) - return -1120; + return -1120; if (pj_strcmp2(&hdr->values[0], "application/*")) - return -1130; + return -1130; if (pj_strcmp2(&hdr->values[1], "text/plain")) - return -1140; + return -1140; return 0; } @@ -1222,16 +1221,16 @@ static int hdr_test_accept2(pjsip_hdr *h) pjsip_accept_hdr *hdr = (pjsip_accept_hdr*)h; if (h->type != PJSIP_H_ACCEPT) - return -1210; + return -1210; if (hdr->count != 2) - return -1220; + return -1220; if (pj_strcmp2(&hdr->values[0], "application/*;p1=v1")) - return -1230; + return -1230; if (pj_strcmp2(&hdr->values[1], "text/plain")) - return -1240; + return -1240; return 0; } @@ -1242,10 +1241,10 @@ static int hdr_test_allow0(pjsip_hdr *h) pjsip_allow_hdr *hdr = (pjsip_allow_hdr*)h; if (h->type != PJSIP_H_ALLOW) - return -1310; + return -1310; if (hdr->count != 0) - return -1320; + return -1320; return 0; @@ -1253,49 +1252,49 @@ static int hdr_test_allow0(pjsip_hdr *h) /* - "Digest username=\"username\", realm=\"realm\", nonce=\"nonce\", " \ - "uri=\"sip:domain\", response=\"RESPONSE\", algorithm=MD5, " \ - "cnonce=\"CNONCE\", opaque=\"OPAQUE\", qop=auth, nc=00000001", + "Digest username=\"username\", realm=\"realm\", nonce=\"nonce\", " \ + "uri=\"sip:domain\", response=\"RESPONSE\", algorithm=MD5, " \ + "cnonce=\"CNONCE\", opaque=\"OPAQUE\", qop=auth, nc=00000001", */ static int hdr_test_authorization(pjsip_hdr *h) { pjsip_authorization_hdr *hdr = (pjsip_authorization_hdr*)h; if (h->type != PJSIP_H_AUTHORIZATION) - return -1410; + return -1410; if (pj_strcmp2(&hdr->scheme, "Digest")) - return -1420; + return -1420; if (pj_strcmp2(&hdr->credential.digest.username, "username")) - return -1421; + return -1421; if (pj_strcmp2(&hdr->credential.digest.realm, "realm")) - return -1422; + return -1422; if (pj_strcmp2(&hdr->credential.digest.nonce, "nonce")) - return -1423; + return -1423; if (pj_strcmp2(&hdr->credential.digest.uri, "sip:domain")) - return -1424; + return -1424; if (pj_strcmp2(&hdr->credential.digest.response, "RESPONSE")) - return -1425; + return -1425; if (pj_strcmp2(&hdr->credential.digest.algorithm, "MD5")) - return -1426; + return -1426; if (pj_strcmp2(&hdr->credential.digest.cnonce, "CNONCE")) - return -1427; + return -1427; if (pj_strcmp2(&hdr->credential.digest.opaque, "OPAQUE")) - return -1428; + return -1428; if (pj_strcmp2(&hdr->credential.digest.qop, "auth")) - return -1429; + return -1429; if (pj_strcmp2(&hdr->credential.digest.nc, "00000001")) - return -1430; + return -1430; return 0; } @@ -1309,10 +1308,10 @@ static int hdr_test_cid(pjsip_hdr *h) pjsip_cid_hdr *hdr = (pjsip_cid_hdr*)h; if (h->type != PJSIP_H_CALL_ID) - return -1510; + return -1510; if (pj_strcmp2(&hdr->id, "-.!%*_+`'~()<>:\\\"/[]?{}")) - return -1520; + return -1520; return 0; } @@ -1325,22 +1324,22 @@ static int test_simple_addr_spec(pjsip_uri *uri) pjsip_sip_uri *sip_uri = (pjsip_sip_uri *)pjsip_uri_get_uri(uri); if (!PJSIP_URI_SCHEME_IS_SIP(uri)) - return -900; + return -900; if (pj_strcmp2(&sip_uri->host, "host")) - return -910; + return -910; if (sip_uri->port != 0) - return -920; + return -920; return 0; } /* -#define PARAM_CHAR "][/:&+$" +#define PARAM_CHAR "][/:&+$" #define SIMPLE_ADDR_SPEC "sip:host" -#define ADDR_SPEC SIMPLE_ADDR_SPEC ";"PARAM_CHAR"="PARAM_CHAR ";p1=\";\"" -#define NAME_ADDR "<" ADDR_SPEC ">" +#define ADDR_SPEC SIMPLE_ADDR_SPEC ";"PARAM_CHAR"="PARAM_CHAR ";p1=\";\"" +#define NAME_ADDR "<" ADDR_SPEC ">" */ static int nameaddr_test(void *uri) { @@ -1349,28 +1348,28 @@ static int nameaddr_test(void *uri) int rc; if (!PJSIP_URI_SCHEME_IS_SIP(uri)) - return -930; + return -930; rc = test_simple_addr_spec((pjsip_uri*)sip_uri); if (rc != 0) - return rc; + return rc; if (pj_list_size(&sip_uri->other_param) != 2) - return -940; + return -940; param = sip_uri->other_param.next; if (pj_strcmp2(¶m->name, PARAM_CHAR)) - return -942; + return -942; if (pj_strcmp2(¶m->value, PARAM_CHAR)) - return -943; + return -943; param = param->next; if (pj_strcmp2(¶m->name, "p1")) - return -942; + return -942; if (pj_strcmp2(¶m->value, "\";\"")) - return -943; + return -943; return 0; } @@ -1383,32 +1382,32 @@ static int generic_param_test(pjsip_param *param_head) pjsip_param *param; if (pj_list_size(param_head) != 4) - return -950; + return -950; param = param_head->next; if (pj_strcmp2(¶m->name, "p0")) - return -952; + return -952; if (pj_strcmp2(¶m->value, "a")) - return -953; + return -953; param = param->next; if (pj_strcmp2(¶m->name, "p1")) - return -954; + return -954; if (pj_strcmp2(¶m->value, "\"ab:;cd\"")) - return -955; + return -955; param = param->next; if (pj_strcmp2(¶m->name, "p2")) - return -956; + return -956; if (pj_strcmp2(¶m->value, "ab%3acd")) - return -957; + return -957; param = param->next; if (pj_strcmp2(¶m->name, "p3")) - return -958; + return -958; if (pj_strcmp2(¶m->value, "")) - return -959; + return -959; return 0; } @@ -1425,22 +1424,22 @@ static int hdr_test_contact0(pjsip_hdr *h) int rc; if (h->type != PJSIP_H_CONTACT) - return -1610; + return -1610; rc = test_simple_addr_spec(hdr->uri); if (rc != 0) - return rc; + return rc; if (pj_list_size(&hdr->other_param) != 1) - return -1620; + return -1620; param = hdr->other_param.next; if (pj_strcmp2(¶m->name, "p1")) - return -1630; + return -1630; if (pj_strcmp2(¶m->value, "v1")) - return -1640; + return -1640; return 0; } @@ -1454,15 +1453,15 @@ static int hdr_test_contact1(pjsip_hdr *h) int rc; if (h->type != PJSIP_H_CONTACT) - return -1710; + return -1710; rc = nameaddr_test(hdr->uri); if (rc != 0) - return rc; + return rc; rc = generic_param_test(&hdr->other_param); if (rc != 0) - return rc; + return rc; return 0; } @@ -1476,14 +1475,14 @@ static int hdr_test_contact_q0(pjsip_hdr *h) int rc; if (h->type != PJSIP_H_CONTACT) - return -1710; + return -1710; rc = nameaddr_test(hdr->uri); if (rc != 0) - return rc; + return rc; if (hdr->q1000 != 0) - return -1711; + return -1711; return 0; } @@ -1497,14 +1496,14 @@ static int hdr_test_contact_q1(pjsip_hdr *h) int rc; if (h->type != PJSIP_H_CONTACT) - return -1710; + return -1710; rc = nameaddr_test(hdr->uri); if (rc != 0) - return rc; + return rc; if (hdr->q1000 != 500) - return -1712; + return -1712; return 0; } @@ -1518,14 +1517,14 @@ static int hdr_test_contact_q2(pjsip_hdr *h) int rc; if (h->type != PJSIP_H_CONTACT) - return -1710; + return -1710; rc = nameaddr_test(hdr->uri); if (rc != 0) - return rc; + return rc; if (hdr->q1000 != 1000) - return -1713; + return -1713; return 0; } @@ -1539,14 +1538,14 @@ static int hdr_test_contact_q3(pjsip_hdr *h) int rc; if (h->type != PJSIP_H_CONTACT) - return -1710; + return -1710; rc = nameaddr_test(hdr->uri); if (rc != 0) - return rc; + return rc; if (hdr->q1000 != 1000) - return -1714; + return -1714; return 0; } @@ -1560,14 +1559,14 @@ static int hdr_test_contact_q4(pjsip_hdr *h) int rc; if (h->type != PJSIP_H_CONTACT) - return -1710; + return -1710; rc = nameaddr_test(hdr->uri); if (rc != 0) - return rc; + return rc; if (hdr->q1000 != 1150) - return -1715; + return -1715; return 0; } @@ -1580,10 +1579,10 @@ static int hdr_test_content_length(pjsip_hdr *h) pjsip_clen_hdr *hdr = (pjsip_clen_hdr*)h; if (h->type != PJSIP_H_CONTENT_LENGTH) - return -1810; + return -1810; if (hdr->len != 10) - return -1820; + return -1820; return 0; } @@ -1597,13 +1596,13 @@ static int hdr_test_content_type(pjsip_hdr *h) const pjsip_param *prm; if (h->type != PJSIP_H_CONTENT_TYPE) - return -1910; + return -1910; if (pj_strcmp2(&hdr->media.type, "application")) - return -1920; + return -1920; if (pj_strcmp2(&hdr->media.subtype, "sdp")) - return -1930; + return -1930; /* Currently, if the media parameter contains escaped characters, * pjsip will print the parameter unescaped. @@ -1640,53 +1639,53 @@ static int hdr_test_from(pjsip_hdr *h) int rc; if (h->type != PJSIP_H_FROM) - return -2010; + return -2010; rc = nameaddr_test(hdr->uri); if (rc != 0) - return rc; + return rc; rc = generic_param_test(&hdr->other_param); if (rc != 0) - return rc; + return rc; return 0; } /* - "Digest realm=\"realm\", domain=\"sip:domain\", nonce=\"nonce\", " \ - "opaque=\"opaque\", stale=true, algorithm=MD5, qop=\"auth\"", + "Digest realm=\"realm\", domain=\"sip:domain\", nonce=\"nonce\", " \ + "opaque=\"opaque\", stale=true, algorithm=MD5, qop=\"auth\"", */ static int hdr_test_proxy_authenticate(pjsip_hdr *h) { pjsip_proxy_authenticate_hdr *hdr = (pjsip_proxy_authenticate_hdr*)h; if (h->type != PJSIP_H_PROXY_AUTHENTICATE) - return -2110; + return -2110; if (pj_strcmp2(&hdr->scheme, "Digest")) - return -2120; + return -2120; if (pj_strcmp2(&hdr->challenge.digest.realm, "realm")) - return -2130; + return -2130; if (pj_strcmp2(&hdr->challenge.digest.domain, "sip:domain")) - return -2140; + return -2140; if (pj_strcmp2(&hdr->challenge.digest.nonce, "nonce")) - return -2150; + return -2150; if (pj_strcmp2(&hdr->challenge.digest.opaque, "opaque")) - return -2160; + return -2160; if (hdr->challenge.digest.stale != 1) - return -2170; + return -2170; if (pj_strcmp2(&hdr->challenge.digest.algorithm, "MD5")) - return -2180; + return -2180; if (pj_strcmp2(&hdr->challenge.digest.qop, "auth")) - return -2190; + return -2190; return 0; } @@ -1700,15 +1699,15 @@ static int hdr_test_record_route(pjsip_hdr *h) int rc; if (h->type != PJSIP_H_RECORD_ROUTE) - return -2210; + return -2210; rc = nameaddr_test(&hdr->name_addr); if (rc != 0) - return rc; + return rc; rc = generic_param_test(&hdr->other_param); if (rc != 0) - return rc; + return rc; return 0; @@ -1722,10 +1721,10 @@ static int hdr_test_supported(pjsip_hdr *h) pjsip_supported_hdr *hdr = (pjsip_supported_hdr*)h; if (h->type != PJSIP_H_SUPPORTED) - return -2310; + return -2310; if (hdr->count != 0) - return -2320; + return -2320; return 0; } @@ -1739,15 +1738,15 @@ static int hdr_test_to(pjsip_hdr *h) int rc; if (h->type != PJSIP_H_TO) - return -2410; + return -2410; rc = nameaddr_test(hdr->uri); if (rc != 0) - return rc; + return rc; rc = generic_param_test(&hdr->other_param); if (rc != 0) - return rc; + return rc; return 0; } @@ -1761,20 +1760,20 @@ static int hdr_test_via(pjsip_hdr *h) int rc; if (h->type != PJSIP_H_VIA) - return -2510; + return -2510; if (pj_strcmp2(&hdr->transport, "XYZ")) - return -2515; + return -2515; if (pj_strcmp2(&hdr->sent_by.host, "host")) - return -2520; + return -2520; if (hdr->sent_by.port != 0) - return -2530; + return -2530; rc = generic_param_test(&hdr->other_param); if (rc != 0) - return rc; + return rc; return 0; } @@ -1788,16 +1787,16 @@ static int hdr_test_via_ipv6_1(pjsip_hdr *h) pjsip_via_hdr *hdr = (pjsip_via_hdr*)h; if (h->type != PJSIP_H_VIA) - return -2610; + return -2610; if (pj_strcmp2(&hdr->transport, "UDP")) - return -2615; + return -2615; if (pj_strcmp2(&hdr->sent_by.host, "::1")) - return -2620; + return -2620; if (hdr->sent_by.port != 0) - return -2630; + return -2630; return 0; } @@ -1808,16 +1807,16 @@ static int hdr_test_via_ipv6_2(pjsip_hdr *h) pjsip_via_hdr *hdr = (pjsip_via_hdr*)h; if (h->type != PJSIP_H_VIA) - return -2710; + return -2710; if (pj_strcmp2(&hdr->transport, "UDP")) - return -2715; + return -2715; if (pj_strcmp2(&hdr->sent_by.host, "::1")) - return -2720; + return -2720; if (hdr->sent_by.port != 5061) - return -2730; + return -2730; return 0; } @@ -1828,22 +1827,22 @@ static int hdr_test_via_ipv6_3(pjsip_hdr *h) pjsip_via_hdr *hdr = (pjsip_via_hdr*)h; if (h->type != PJSIP_H_VIA) - return -2810; + return -2810; if (pj_strcmp2(&hdr->transport, "UDP")) - return -2815; + return -2815; if (pj_strcmp2(&hdr->sent_by.host, "::1")) - return -2820; + return -2820; if (hdr->sent_by.port != 0) - return -2830; + return -2830; if (pj_strcmp2(&hdr->recvd_param, "::2")) - return -2840; + return -2840; if (hdr->rport_param != 5061) - return -2850; + return -2850; return 0; } @@ -1854,13 +1853,13 @@ static int hdr_test_retry_after1(pjsip_hdr *h) pjsip_retry_after_hdr *hdr = (pjsip_retry_after_hdr*)h; if (h->type != PJSIP_H_RETRY_AFTER) - return -2910; + return -2910; if (hdr->ivalue != 10) - return -2920; + return -2920; if (pj_strcmp2(&hdr->comment, "Already Pending Register")) - return -2930; + return -2930; return 0; } @@ -1871,10 +1870,10 @@ static int hdr_test_subject_utf(pjsip_hdr *h) pjsip_subject_hdr *hdr = (pjsip_subject_hdr*)h; if (pj_strcmp2(&h->name, "Subject")) - return -2950; + return -2950; if (pj_strcmp2(&hdr->hvalue, "\xC0\x81")) - return -2960; + return -2960; return 0; } @@ -1886,99 +1885,99 @@ static int hdr_test(void) PJ_LOG(3,(THIS_FILE, " testing header parsing..")); for (i=0; ihname); - len = strlen(test->hcontent); + /* Parse the header */ + hname = pj_str(test->hname); + len = strlen(test->hcontent); #if defined(PJSIP_UNESCAPE_IN_PLACE) && PJSIP_UNESCAPE_IN_PLACE!=0 - PJ_ASSERT_RETURN(len < sizeof(hcontent), PJSIP_EMSGTOOLONG); - strcpy(hcontent, test->hcontent); + PJ_ASSERT_RETURN(len < sizeof(hcontent), PJSIP_EMSGTOOLONG); + strcpy(hcontent, test->hcontent); #else - hcontent = test->hcontent; + hcontent = test->hcontent; #endif - - parsed_hdr1 = (pjsip_hdr*) pjsip_parse_hdr(pool, &hname, - hcontent, len, - &parsed_len); - if (parsed_hdr1 == NULL) { - if (test->flags & HDR_FLAG_PARSE_FAIL) { - pj_pool_release(pool); - continue; - } - PJ_LOG(3,(THIS_FILE, " error parsing header %s: %s", test->hname, test->hcontent)); - return -500; - } - - /* Test the parsing result */ - if (test->test && (rc=test->test(parsed_hdr1)) != 0) { - PJ_LOG(3,(THIS_FILE, " validation failed for header %s: %s", test->hname, test->hcontent)); - PJ_LOG(3,(THIS_FILE, " error code is %d", rc)); - return -502; - } + + parsed_hdr1 = (pjsip_hdr*) pjsip_parse_hdr(pool, &hname, + hcontent, len, + &parsed_len); + if (parsed_hdr1 == NULL) { + if (test->flags & HDR_FLAG_PARSE_FAIL) { + pj_pool_release(pool); + continue; + } + PJ_LOG(3,(THIS_FILE, " error parsing header %s: %s", test->hname, test->hcontent)); + return -500; + } + + /* Test the parsing result */ + if (test->test && (rc=test->test(parsed_hdr1)) != 0) { + PJ_LOG(3,(THIS_FILE, " validation failed for header %s: %s", test->hname, test->hcontent)); + PJ_LOG(3,(THIS_FILE, " error code is %d", rc)); + return -502; + } #if 1 - /* Parse with hshortname, if present */ - if (test->hshort_name) { - hname = pj_str(test->hshort_name); - len = strlen(test->hcontent); + /* Parse with hshortname, if present */ + if (test->hshort_name) { + hname = pj_str(test->hshort_name); + len = strlen(test->hcontent); #if defined(PJSIP_UNESCAPE_IN_PLACE) && PJSIP_UNESCAPE_IN_PLACE!=0 - PJ_ASSERT_RETURN(len < sizeof(hcontent), PJSIP_EMSGTOOLONG); - strcpy(hcontent, test->hcontent); + PJ_ASSERT_RETURN(len < sizeof(hcontent), PJSIP_EMSGTOOLONG); + strcpy(hcontent, test->hcontent); #else - hcontent = test->hcontent; + hcontent = test->hcontent; #endif - parsed_hdr2 = (pjsip_hdr*) pjsip_parse_hdr(pool, &hname, hcontent, len, &parsed_len); - if (parsed_hdr2 == NULL) { - PJ_LOG(3,(THIS_FILE, " error parsing header %s: %s", test->hshort_name, test->hcontent)); - return -510; - } - } + parsed_hdr2 = (pjsip_hdr*) pjsip_parse_hdr(pool, &hname, hcontent, len, &parsed_len); + if (parsed_hdr2 == NULL) { + PJ_LOG(3,(THIS_FILE, " error parsing header %s: %s", test->hshort_name, test->hcontent)); + return -510; + } + } #endif - if (test->flags & HDR_FLAG_DONT_PRINT) { - pj_pool_release(pool); - continue; - } - - /* Print the original header */ - input = (char*) pj_pool_alloc(pool, 1024); - len = pj_ansi_snprintf(input, 1024, "%s: %s", test->hname, test->hcontent); - if (len < 1 || len >= 1024) - return -520; - - /* Print the parsed header*/ - output = (char*) pj_pool_alloc(pool, 1024); - len = pjsip_hdr_print_on(parsed_hdr1, output, 1024); - if (len < 0 || len >= 1024) { - PJ_LOG(3,(THIS_FILE, " header too long: %s: %s", test->hname, test->hcontent)); - return -530; - } - output[len] = 0; - - if (strcmp(input, output) != 0) { - PJ_LOG(3,(THIS_FILE, " header character by character comparison failed.")); - PJ_LOG(3,(THIS_FILE, " original header=|%s|", input)); - PJ_LOG(3,(THIS_FILE, " parsed header =|%s|", output)); - return -540; - } - - pj_pool_release(pool); + if (test->flags & HDR_FLAG_DONT_PRINT) { + pj_pool_release(pool); + continue; + } + + /* Print the original header */ + input = (char*) pj_pool_alloc(pool, 1024); + len = pj_ansi_snprintf(input, 1024, "%s: %s", test->hname, test->hcontent); + if (len < 1 || len >= 1024) + return -520; + + /* Print the parsed header*/ + output = (char*) pj_pool_alloc(pool, 1024); + len = pjsip_hdr_print_on(parsed_hdr1, output, 1024); + if (len < 0 || len >= 1024) { + PJ_LOG(3,(THIS_FILE, " header too long: %s: %s", test->hname, test->hcontent)); + return -530; + } + output[len] = 0; + + if (strcmp(input, output) != 0) { + PJ_LOG(3,(THIS_FILE, " header character by character comparison failed.")); + PJ_LOG(3,(THIS_FILE, " original header=|%s|", input)); + PJ_LOG(3,(THIS_FILE, " parsed header =|%s|", output)); + return -540; + } + + pj_pool_release(pool); } return 0; @@ -1991,9 +1990,9 @@ int msg_test(void) { enum { COUNT = 1, DETECT=0, PARSE=1, PRINT=2 }; struct { - unsigned detect; - unsigned parse; - unsigned print; + unsigned detect; + unsigned parse; + unsigned print; } run[COUNT]; unsigned i, max, avg_len; char desc[250]; @@ -2001,81 +2000,81 @@ int msg_test(void) status = hdr_test(); if (status != 0) - return status; + return status; status = simple_test(); if (status != PJ_SUCCESS) - return status; + return status; #if INCLUDE_BENCHMARKS for (i=0; i max) max = run[i].detect; + if (run[i].detect > max) max = run[i].detect; PJ_LOG(3,("", " Maximum message detection/sec=%u", max)); pj_ansi_sprintf(desc, "Number of SIP messages " - "can be pre-parse by pjsip_find_msg() " - "per second (tested with %d message sets with " - "average message length of " - "%d bytes)", (int)PJ_ARRAY_SIZE(test_array), avg_len); + "can be pre-parse by pjsip_find_msg() " + "per second (tested with %d message sets with " + "average message length of " + "%d bytes)", (int)PJ_ARRAY_SIZE(test_array), avg_len); report_ival("msg-detect-per-sec", max, "msg/sec", desc); /* Print maximum parse/sec */ for (i=0, max=0; i max) max = run[i].parse; + if (run[i].parse > max) max = run[i].parse; PJ_LOG(3,("", " Maximum message parsing/sec=%u", max)); pj_ansi_sprintf(desc, "Number of SIP messages " - "can be parsed by pjsip_parse_msg() " - "per second (tested with %d message sets with " - "average message length of " - "%d bytes)", (int)PJ_ARRAY_SIZE(test_array), avg_len); + "can be parsed by pjsip_parse_msg() " + "per second (tested with %d message sets with " + "average message length of " + "%d bytes)", (int)PJ_ARRAY_SIZE(test_array), avg_len); report_ival("msg-parse-per-sec", max, "msg/sec", desc); /* Msg parsing bandwidth */ report_ival("msg-parse-bandwidth-mb", avg_len*max/1000000, "MB/sec", - "Message parsing bandwidth in megabytes (number of megabytes" - " worth of SIP messages that can be parsed per second). " - "The value is derived from msg-parse-per-sec above."); + "Message parsing bandwidth in megabytes (number of megabytes" + " worth of SIP messages that can be parsed per second). " + "The value is derived from msg-parse-per-sec above."); /* Print maximum print/sec */ for (i=0, max=0; i max) max = run[i].print; + if (run[i].print > max) max = run[i].print; PJ_LOG(3,("", " Maximum message print/sec=%u", max)); pj_ansi_sprintf(desc, "Number of SIP messages " - "can be printed by pjsip_msg_print()" - " per second (tested with %d message sets with " - "average message length of " - "%d bytes)", (int)PJ_ARRAY_SIZE(test_array), avg_len); + "can be printed by pjsip_msg_print()" + " per second (tested with %d message sets with " + "average message length of " + "%d bytes)", (int)PJ_ARRAY_SIZE(test_array), avg_len); report_ival("msg-print-per-sec", max, "msg/sec", desc); /* Msg print bandwidth */ report_ival("msg-printed-bandwidth-mb", avg_len*max/1000000, "MB/sec", - "Message print bandwidth in megabytes (total size of " - "SIP messages printed per second). " - "The value is derived from msg-print-per-sec above."); + "Message print bandwidth in megabytes (total size of " + "SIP messages printed per second). " + "The value is derived from msg-print-per-sec above."); -#endif /* INCLUDE_BENCHMARKS */ +#endif /* INCLUDE_BENCHMARKS */ return PJ_SUCCESS; } diff --git a/pjsip/src/test/multipart_test.c b/pjsip/src/test/multipart_test.c index eeaf4352cb..95e5971ad8 100644 --- a/pjsip/src/test/multipart_test.c +++ b/pjsip/src/test/multipart_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * @@ -20,7 +19,7 @@ #include #include -#define THIS_FILE "" +#define THIS_FILE "" /* * multipart tests @@ -39,75 +38,75 @@ static struct test_t verify_ptr verify; } p_tests[] = { - { - /* Content-type */ - "multipart", "mixed", "12345", - - /* Body: */ - "This is the prolog, which should be ignored.\r\n" - "--12345\r\n" - "Content-Type: my/text\r\n" - "\r\n" - "Header and body\r\n" - "--12345 \t\r\n" - "Content-Type: hello/world\r\n" - "Content-Length: 0\r\n" - "\r\n" - "--12345\r\n" - "\r\n" - "Body only\r\n" - "--12345\r\n" - "Content-Type: multipart/mixed;boundary=6789\r\n" - "\r\n" - "Prolog of the subbody, should be ignored\r\n" - "--6789\r\n" - "\r\n" - "Subbody\r\n" - "--6789--\r\n" - "Epilogue of the subbody, should be ignored\r\n" - "--12345--\r\n" - "This is epilogue, which should be ignored too", - - &verify1 - }, - { - /* Content-type */ - "multipart", "mixed", "12345", - - /* Body: */ - "This is the prolog, which should be ignored.\r\n" - "--12345\r\n" - "Content-Type: text/plain\r\n" - "Content-ID: \r\n" - "Content-ID: <\"header1\"@example.org>\r\n" - "Content-Length: 13\r\n" - "\r\n" - "has header1\r\n" - "--12345 \t\r\n" - "Content-Type: application/pidf+xml\r\n" - "Content-ID: \r\n" - "Content-ID: \r\n" - "Content-Length: 13\r\n" - "\r\n" - "has header2\r\n" - "--12345\r\n" - "Content-Type: text/plain\r\n" - "Content-ID: \r\n" - "Content-ID: \r\n" - "Content-ID: \r\n" - "Content-Length: 13\r\n" - "\r\n" - "has header4\r\n" - "--12345--\r\n" - "This is epilogue, which should be ignored too", - - &verify2 - } + { + /* Content-type */ + "multipart", "mixed", "12345", + + /* Body: */ + "This is the prolog, which should be ignored.\r\n" + "--12345\r\n" + "Content-Type: my/text\r\n" + "\r\n" + "Header and body\r\n" + "--12345 \t\r\n" + "Content-Type: hello/world\r\n" + "Content-Length: 0\r\n" + "\r\n" + "--12345\r\n" + "\r\n" + "Body only\r\n" + "--12345\r\n" + "Content-Type: multipart/mixed;boundary=6789\r\n" + "\r\n" + "Prolog of the subbody, should be ignored\r\n" + "--6789\r\n" + "\r\n" + "Subbody\r\n" + "--6789--\r\n" + "Epilogue of the subbody, should be ignored\r\n" + "--12345--\r\n" + "This is epilogue, which should be ignored too", + + &verify1 + }, + { + /* Content-type */ + "multipart", "mixed", "12345", + + /* Body: */ + "This is the prolog, which should be ignored.\r\n" + "--12345\r\n" + "Content-Type: text/plain\r\n" + "Content-ID: \r\n" + "Content-ID: <\"header1\"@example.org>\r\n" + "Content-Length: 13\r\n" + "\r\n" + "has header1\r\n" + "--12345 \t\r\n" + "Content-Type: application/pidf+xml\r\n" + "Content-ID: \r\n" + "Content-ID: \r\n" + "Content-Length: 13\r\n" + "\r\n" + "has header2\r\n" + "--12345\r\n" + "Content-Type: text/plain\r\n" + "Content-ID: \r\n" + "Content-ID: \r\n" + "Content-ID: \r\n" + "Content-Length: 13\r\n" + "\r\n" + "has header4\r\n" + "--12345--\r\n" + "This is epilogue, which should be ignored too", + + &verify2 + } }; static void init_media_type(pjsip_media_type *mt, - char *type, char *subtype, char *boundary) + char *type, char *subtype, char *boundary) { static pjsip_param prm; @@ -115,10 +114,10 @@ static void init_media_type(pjsip_media_type *mt, if (type) mt->type = pj_str(type); if (subtype) mt->subtype = pj_str(subtype); if (boundary) { - pj_list_init(&prm); - prm.name = pj_str("boundary"); - prm.value = pj_str(boundary); - pj_list_push_back(&mt->param, &prm); + pj_list_init(&prm); + prm.name = pj_str("boundary"); + prm.value = pj_str(boundary); + pj_list_push_back(&mt->param, &prm); } } @@ -131,14 +130,14 @@ static int verify_hdr(pj_pool_t *pool, pjsip_msg_body *multipart_body, part = pjsip_multipart_find_part_by_header(pool, multipart_body, hdr, NULL); if (!part) { - return -1; + return -1; } the_body.ptr = (char*)part->body->data; the_body.slen = part->body->len; if (pj_strcmp2(&the_body, part_body) != 0) { - return -2; + return -2; } return 0; @@ -152,14 +151,14 @@ static int verify_cid_str(pj_pool_t *pool, pjsip_msg_body *multipart_body, part = pjsip_multipart_find_part_by_cid_str(pool, multipart_body, &cid_url); if (!part) { - return -3; + return -3; } the_body.ptr = (char*)part->body->data; the_body.slen = part->body->len; if (pj_strcmp2(&the_body, part_body) != 0) { - return -4; + return -4; } return 0; @@ -173,14 +172,14 @@ static int verify_cid_uri(pj_pool_t *pool, pjsip_msg_body *multipart_body, part = pjsip_multipart_find_part_by_cid_uri(pool, multipart_body, cid_uri); if (!part) { - return -5; + return -5; } the_body.ptr = (char*)part->body->data; the_body.slen = part->body->len; if (pj_strcmp2(&the_body, part_body) != 0) { - return -6; + return -6; } return 0; @@ -198,80 +197,80 @@ static pj_status_t verify2(pj_pool_t *pool, pjsip_msg_body *body) rc = verify_hdr(pool, body, ctype_hdr, "has header2"); if (rc) { - return (rc - rcbase); + return (rc - rcbase); } rcbase += 10; rc = verify_cid_str(pool, body, pj_str("cid:header1@example.org"), "has header1"); if (rc) { - return (rc - rcbase); + return (rc - rcbase); } rcbase += 10; rc = verify_cid_str(pool, body, pj_str("%22header1%22@example.org"), "has header1"); if (rc) { - return (rc - rcbase); + return (rc - rcbase); } cid_uri = pjsip_uri_get_uri(pjsip_parse_uri(pool, "", - strlen(""), 0)); + strlen(""), 0)); rcbase += 10; rc = verify_cid_uri(pool, body, cid_uri, "has header1"); if (rc) { - return (rc - rcbase); + return (rc - rcbase); } rcbase += 10; rc = verify_cid_str(pool, body, pj_str(""), "has header2"); if (rc) { - return (rc - rcbase); + return (rc - rcbase); } rcbase += 10; rc = verify_cid_str(pool, body, pj_str("cid:my%ffheader2@example.org"), "has header2"); if (rc) { - return (rc - rcbase); + return (rc - rcbase); } cid_uri = pjsip_uri_get_uri(pjsip_parse_uri(pool, "", - strlen(""), 0)); + strlen(""), 0)); rcbase += 10; rc = verify_cid_uri(pool, body, cid_uri, "has header2"); if (rc) { - return (rc - rcbase); + return (rc - rcbase); } rcbase += 10; rc = verify_cid_str(pool, body, pj_str("cid:my%20header3@example.org"), "has header4"); if (rc) { - return (rc - rcbase); + return (rc - rcbase); } rcbase += 10; rc = verify_cid_str(pool, body, pj_str(""), "has header4"); if (rc) { - return (rc - rcbase); + return (rc - rcbase); } cid_uri = pjsip_uri_get_uri(pjsip_parse_uri(pool, "", - strlen(""), 0)); + strlen(""), 0)); rcbase += 10; rc = verify_cid_uri(pool, body, cid_uri, "has header4"); if (rc) { - return (rc - rcbase); + return (rc - rcbase); } rcbase += 10; rc = verify_cid_str(pool, body, pj_str(""), "has header4"); if (rc) { - return (rc - rcbase); + return (rc - rcbase); } /* These should all fail for malformed or missing URI */ rcbase += 10; rc = verify_cid_str(pool, body, pj_str("cid:"), "has header4"); if (!rc) { - return (rc - rcbase); + return (rc - rcbase); } /* This will trigger assertion. */ @@ -279,20 +278,20 @@ static pj_status_t verify2(pj_pool_t *pool, pjsip_msg_body *body) rcbase += 10; rc = verify_cid_str(pool, body, pj_str(""), "has header4"); if (!rc) { - return (rc - rcbase); + return (rc - rcbase); } */ rcbase += 10; rc = verify_cid_str(pool, body, pj_str("<>"), "has header4"); if (!rc) { - return (rc - rcbase); + return (rc - rcbase); } rcbase += 10; rc = verify_cid_str(pool, body, pj_str(""), "has header4"); if (!rc) { - return (rc - rcbase); + return (rc - rcbase); } /* @@ -302,18 +301,18 @@ static pj_status_t verify2(pj_pool_t *pool, pjsip_msg_body *body) rcbase += 10; rc = verify_cid_str(pool, body, pj_str("cid:my header3@example.org"), "has header4"); if (rc) { - return (rc - rcbase); + return (rc - rcbase); } return 0; } static int verify_part(pjsip_multipart_part *part, - char *h_content_type, - char *h_content_subtype, - char *boundary, - int h_content_length, - const char *body) + char *h_content_type, + char *h_content_subtype, + char *boundary, + int h_content_length, + const char *body) { pjsip_ctype_hdr *ctype_hdr = NULL; pjsip_clen_hdr *clen_hdr = NULL; @@ -322,44 +321,44 @@ static int verify_part(pjsip_multipart_part *part, hdr = part->hdr.next; while (hdr != &part->hdr) { - if (hdr->type == PJSIP_H_CONTENT_TYPE) - ctype_hdr = (pjsip_ctype_hdr*)hdr; - else if (hdr->type == PJSIP_H_CONTENT_LENGTH) - clen_hdr = (pjsip_clen_hdr*)hdr; - hdr = hdr->next; + if (hdr->type == PJSIP_H_CONTENT_TYPE) + ctype_hdr = (pjsip_ctype_hdr*)hdr; + else if (hdr->type == PJSIP_H_CONTENT_LENGTH) + clen_hdr = (pjsip_clen_hdr*)hdr; + hdr = hdr->next; } if (h_content_type) { - pjsip_media_type mt; + pjsip_media_type mt; - if (ctype_hdr == NULL) - return -10; + if (ctype_hdr == NULL) + return -10; - init_media_type(&mt, h_content_type, h_content_subtype, boundary); + init_media_type(&mt, h_content_type, h_content_subtype, boundary); - if (pjsip_media_type_cmp(&ctype_hdr->media, &mt, 2) != 0) - return -20; + if (pjsip_media_type_cmp(&ctype_hdr->media, &mt, 2) != 0) + return -20; } else { - if (ctype_hdr) - return -30; + if (ctype_hdr) + return -30; } if (h_content_length >= 0) { - if (clen_hdr == NULL) - return -50; - if (clen_hdr->len != h_content_length) - return -60; + if (clen_hdr == NULL) + return -50; + if (clen_hdr->len != h_content_length) + return -60; } else { - if (clen_hdr) - return -70; + if (clen_hdr) + return -70; } the_body.ptr = (char*)part->body->data; the_body.slen = part->body->len; if (pj_strcmp2(&the_body, body) != 0) - return -90; + return -90; return 0; } @@ -375,65 +374,65 @@ static pj_status_t verify1(pj_pool_t *pool, pjsip_msg_body *body) /* Check content-type: "multipart/mixed;boundary=12345" */ init_media_type(&mt, "multipart", "mixed", "12345"); if (pjsip_media_type_cmp(&body->content_type, &mt, 2) != 0) - return -200; + return -200; /* First part: - "Content-Type: my/text\r\n" - "\r\n" - "Header and body\r\n" + "Content-Type: my/text\r\n" + "\r\n" + "Header and body\r\n" */ part = pjsip_multipart_get_first_part(body); if (!part) - return -210; + return -210; if (verify_part(part, "my", "text", NULL, -1, "Header and body")) - return -220; + return -220; /* Next part: - "Content-Type: hello/world\r\n" - "Content-Length: 0\r\n" - "\r\n" + "Content-Type: hello/world\r\n" + "Content-Length: 0\r\n" + "\r\n" */ part = pjsip_multipart_get_next_part(body, part); if (!part) - return -230; + return -230; if ((rc=verify_part(part, "hello", "world", NULL, 0, ""))!=0) { - PJ_LOG(3,(THIS_FILE, " err: verify_part rc=%d", rc)); - return -240; + PJ_LOG(3,(THIS_FILE, " err: verify_part rc=%d", rc)); + return -240; } /* Next part: - "\r\n" - "Body only\r\n" + "\r\n" + "Body only\r\n" */ part = pjsip_multipart_get_next_part(body, part); if (!part) - return -260; + return -260; if (verify_part(part, NULL, NULL, NULL, -1, "Body only")) - return -270; + return -270; /* Next part: - "Content-Type: multipart/mixed;boundary=6789\r\n" - "\r\n" - "Prolog of the subbody, should be ignored\r\n" - "--6789\r\n" - "\r\n" - "Subbody\r\n" - "--6789--\r\n" - "Epilogue of the subbody, should be ignored\r\n" + "Content-Type: multipart/mixed;boundary=6789\r\n" + "\r\n" + "Prolog of the subbody, should be ignored\r\n" + "--6789\r\n" + "\r\n" + "Subbody\r\n" + "--6789--\r\n" + "Epilogue of the subbody, should be ignored\r\n" */ part = pjsip_multipart_get_next_part(body, part); if (!part) - return -280; + return -280; if ((rc=verify_part(part, "multipart", "mixed", "6789", -1, - "Prolog of the subbody, should be ignored\r\n" - "--6789\r\n" - "\r\n" - "Subbody\r\n" - "--6789--\r\n" - "Epilogue of the subbody, should be ignored"))!=0) { - PJ_LOG(3,(THIS_FILE, " err: verify_part rc=%d", rc)); - return -290; + "Prolog of the subbody, should be ignored\r\n" + "--6789\r\n" + "\r\n" + "Subbody\r\n" + "--6789--\r\n" + "Epilogue of the subbody, should be ignored"))!=0) { + PJ_LOG(3,(THIS_FILE, " err: verify_part rc=%d", rc)); + return -290; } return 0; @@ -444,33 +443,33 @@ static int parse_test(void) unsigned i; for (i=0; i @@ -32,24 +31,24 @@ static pj_status_t mod_send_on_tx_request(pjsip_tx_data *tdata); static struct { pjsip_module mod; - unsigned count; - unsigned count_before_reject; + unsigned count; + unsigned count_before_reject; } send_mod = { { - NULL, NULL, /* prev, next. */ - { "mod-send", 8 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_TRANSPORT_LAYER, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - NULL, /* on_rx_request() */ - NULL, /* on_rx_response() */ - &mod_send_on_tx_request, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "mod-send", 8 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_TRANSPORT_LAYER, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + &mod_send_on_tx_request, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }, 0, 0xFFFF @@ -61,9 +60,9 @@ static pj_status_t mod_send_on_tx_request(pjsip_tx_data *tdata) PJ_UNUSED_ARG(tdata); if (++send_mod.count > send_mod.count_before_reject) - return PJ_ECANCELLED; + return PJ_ECANCELLED; else - return PJ_SUCCESS; + return PJ_SUCCESS; } @@ -73,44 +72,44 @@ static pj_bool_t regs_rx_request(pjsip_rx_data *rdata); enum contact_op { - NONE, /* don't put Contact header */ - EXACT, /* return exact contact */ - MODIFIED, /* return modified Contact header */ + NONE, /* don't put Contact header */ + EXACT, /* return exact contact */ + MODIFIED, /* return modified Contact header */ }; struct registrar_cfg { - pj_bool_t respond; /* should it respond at all */ - unsigned status_code; /* final response status code */ - pj_bool_t authenticate; /* should we authenticate? */ - enum contact_op contact_op; /* What should we do with Contact */ - unsigned expires_param; /* non-zero to put in expires param */ - unsigned expires; /* non-zero to put in Expires header*/ - - pj_str_t more_contacts; /* Additional Contact headers to put*/ + pj_bool_t respond; /* should it respond at all */ + unsigned status_code; /* final response status code */ + pj_bool_t authenticate; /* should we authenticate? */ + enum contact_op contact_op; /* What should we do with Contact */ + unsigned expires_param; /* non-zero to put in expires param */ + unsigned expires; /* non-zero to put in Expires header*/ + + pj_str_t more_contacts; /* Additional Contact headers to put*/ }; static struct registrar { - pjsip_module mod; + pjsip_module mod; struct registrar_cfg cfg; - unsigned response_cnt; + unsigned response_cnt; } registrar = { { - NULL, NULL, /* prev, next. */ - { "registrar", 9 }, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - ®s_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request. */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev, next. */ + { "registrar", 9 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + ®s_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ } }; @@ -122,86 +121,86 @@ static pj_bool_t regs_rx_request(pjsip_rx_data *rdata) pj_status_t status; if (msg->line.req.method.id != PJSIP_REGISTER_METHOD) - return PJ_FALSE; + return PJ_FALSE; if (!registrar.cfg.respond) - return PJ_TRUE; + return PJ_TRUE; pj_list_init(&hdr_list); if (registrar.cfg.authenticate && - pjsip_msg_find_hdr(msg, PJSIP_H_AUTHORIZATION, NULL)==NULL) + pjsip_msg_find_hdr(msg, PJSIP_H_AUTHORIZATION, NULL)==NULL) { - pjsip_generic_string_hdr *hwww; - const pj_str_t hname = pj_str("WWW-Authenticate"); - const pj_str_t hvalue = pj_str("Digest realm=\"test\""); + pjsip_generic_string_hdr *hwww; + const pj_str_t hname = pj_str("WWW-Authenticate"); + const pj_str_t hvalue = pj_str("Digest realm=\"test\""); - hwww = pjsip_generic_string_hdr_create(rdata->tp_info.pool, &hname, - &hvalue); - pj_list_push_back(&hdr_list, hwww); + hwww = pjsip_generic_string_hdr_create(rdata->tp_info.pool, &hname, + &hvalue); + pj_list_push_back(&hdr_list, hwww); - code = 401; + code = 401; } else { - if (registrar.cfg.contact_op == EXACT || - registrar.cfg.contact_op == MODIFIED) - { - pjsip_hdr *hsrc; + if (registrar.cfg.contact_op == EXACT || + registrar.cfg.contact_op == MODIFIED) + { + pjsip_hdr *hsrc; - for (hsrc=msg->hdr.next; hsrc!=&msg->hdr; hsrc=hsrc->next) { - pjsip_contact_hdr *hdst; + for (hsrc=msg->hdr.next; hsrc!=&msg->hdr; hsrc=hsrc->next) { + pjsip_contact_hdr *hdst; - if (hsrc->type != PJSIP_H_CONTACT) - continue; + if (hsrc->type != PJSIP_H_CONTACT) + continue; - hdst = (pjsip_contact_hdr*) - pjsip_hdr_clone(rdata->tp_info.pool, hsrc); + hdst = (pjsip_contact_hdr*) + pjsip_hdr_clone(rdata->tp_info.pool, hsrc); - if (hdst->expires==0) - continue; + if (hdst->expires==0) + continue; - if (registrar.cfg.contact_op == MODIFIED) { - if (PJSIP_URI_SCHEME_IS_SIP(hdst->uri) || - PJSIP_URI_SCHEME_IS_SIPS(hdst->uri)) - { - pjsip_sip_uri *sip_uri = (pjsip_sip_uri*) - pjsip_uri_get_uri(hdst->uri); - sip_uri->host = pj_str("x-modified-host"); - sip_uri->port = 1; - } - } + if (registrar.cfg.contact_op == MODIFIED) { + if (PJSIP_URI_SCHEME_IS_SIP(hdst->uri) || + PJSIP_URI_SCHEME_IS_SIPS(hdst->uri)) + { + pjsip_sip_uri *sip_uri = (pjsip_sip_uri*) + pjsip_uri_get_uri(hdst->uri); + sip_uri->host = pj_str("x-modified-host"); + sip_uri->port = 1; + } + } - if (registrar.cfg.expires_param) - hdst->expires = registrar.cfg.expires_param; + if (registrar.cfg.expires_param) + hdst->expires = registrar.cfg.expires_param; - pj_list_push_back(&hdr_list, hdst); - } - } + pj_list_push_back(&hdr_list, hdst); + } + } - if (registrar.cfg.more_contacts.slen) { - pjsip_generic_string_hdr *hcontact; - const pj_str_t hname = pj_str("Contact"); + if (registrar.cfg.more_contacts.slen) { + pjsip_generic_string_hdr *hcontact; + const pj_str_t hname = pj_str("Contact"); - hcontact = pjsip_generic_string_hdr_create(rdata->tp_info.pool, &hname, - ®istrar.cfg.more_contacts); - pj_list_push_back(&hdr_list, hcontact); - } + hcontact = pjsip_generic_string_hdr_create(rdata->tp_info.pool, &hname, + ®istrar.cfg.more_contacts); + pj_list_push_back(&hdr_list, hcontact); + } - if (registrar.cfg.expires) { - pjsip_expires_hdr *hexp; + if (registrar.cfg.expires) { + pjsip_expires_hdr *hexp; - hexp = pjsip_expires_hdr_create(rdata->tp_info.pool, - registrar.cfg.expires); - pj_list_push_back(&hdr_list, hexp); - } + hexp = pjsip_expires_hdr_create(rdata->tp_info.pool, + registrar.cfg.expires); + pj_list_push_back(&hdr_list, hexp); + } - registrar.response_cnt++; + registrar.response_cnt++; - code = registrar.cfg.status_code; + code = registrar.cfg.status_code; } status = pjsip_endpt_respond(endpt, NULL, rdata, code, NULL, - &hdr_list, NULL, NULL); + &hdr_list, NULL, NULL); pj_assert(status == PJ_SUCCESS); return (status == PJ_SUCCESS); @@ -213,22 +212,22 @@ static pj_bool_t regs_rx_request(pjsip_rx_data *rdata) struct client { /* Result/expected result */ - int error; - int code; - pj_bool_t have_reg; - unsigned expiration; - unsigned contact_cnt; - pj_bool_t auth; + int error; + int code; + pj_bool_t have_reg; + unsigned expiration; + unsigned contact_cnt; + pj_bool_t auth; /* Commands */ - pj_bool_t destroy_on_cb; + pj_bool_t destroy_on_cb; /* Status */ - pj_bool_t done; + pj_bool_t done; /* Additional results */ - unsigned interval; - unsigned next_reg; + unsigned interval; + unsigned next_reg; }; /* regc callback */ @@ -248,32 +247,32 @@ static void client_cb(struct pjsip_regc_cbparam *param) client->code = param->code; if (client->error) - return; + return; client->have_reg = info.auto_reg && - info.interval != PJSIP_EXPIRES_NOT_SPECIFIED && - param->expiration != PJSIP_EXPIRES_NOT_SPECIFIED; + info.interval != PJSIP_EXPIRES_NOT_SPECIFIED && + param->expiration != PJSIP_EXPIRES_NOT_SPECIFIED; client->expiration = param->expiration; client->contact_cnt = param->contact_cnt; client->interval = info.interval; client->next_reg = info.next_reg; if (client->destroy_on_cb) - pjsip_regc_destroy(param->regc); + pjsip_regc_destroy(param->regc); } /* Generic client test session */ static struct client client_result; static int do_test(const char *title, - const struct registrar_cfg *srv_cfg, - const struct client *client_cfg, - const pj_str_t *registrar_uri, - unsigned contact_cnt, - const pj_str_t contacts[], - unsigned expires, - pj_bool_t leave_session, - pjsip_regc **p_regc) + const struct registrar_cfg *srv_cfg, + const struct client *client_cfg, + const pj_str_t *registrar_uri, + unsigned contact_cnt, + const pj_str_t contacts[], + unsigned expires, + pj_bool_t leave_session, + pjsip_regc **p_regc) { pjsip_regc *regc; unsigned i; @@ -291,101 +290,101 @@ static int do_test(const char *title, status = pjsip_regc_create(endpt, &client_result, &client_cb, ®c); if (status != PJ_SUCCESS) - return -100; + return -100; status = pjsip_regc_init(regc, registrar_uri, &aor, &aor, contact_cnt, - contacts, expires ? expires : 60); + contacts, expires ? expires : 60); if (status != PJ_SUCCESS) { - pjsip_regc_destroy(regc); - return -110; + pjsip_regc_destroy(regc); + return -110; } if (client_cfg->auth) { - pjsip_cred_info cred; - - pj_bzero(&cred, sizeof(cred)); - cred.realm = pj_str("*"); - cred.scheme = pj_str("digest"); - cred.username = pj_str("user"); - cred.data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; - cred.data = pj_str("password"); - - status = pjsip_regc_set_credentials(regc, 1, &cred); - if (status != PJ_SUCCESS) { - pjsip_regc_destroy(regc); - return -115; - } + pjsip_cred_info cred; + + pj_bzero(&cred, sizeof(cred)); + cred.realm = pj_str("*"); + cred.scheme = pj_str("digest"); + cred.username = pj_str("user"); + cred.data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; + cred.data = pj_str("password"); + + status = pjsip_regc_set_credentials(regc, 1, &cred); + if (status != PJ_SUCCESS) { + pjsip_regc_destroy(regc); + return -115; + } } /* Register */ status = pjsip_regc_register(regc, PJ_TRUE, &tdata); if (status != PJ_SUCCESS) { - pjsip_regc_destroy(regc); - return -120; + pjsip_regc_destroy(regc); + return -120; } status = pjsip_regc_send(regc, tdata); /* That's it, wait until the callback is sent */ for (i=0; i<600 && !client_result.done; ++i) { - flush_events(100); + flush_events(100); } if (!client_result.done) { - PJ_LOG(3,(THIS_FILE, " error: test has timed out")); - pjsip_regc_destroy(regc); - return -200; + PJ_LOG(3,(THIS_FILE, " error: test has timed out")); + pjsip_regc_destroy(regc); + return -200; } /* Destroy the regc, we're done with the test, unless we're * instructed to leave the session open. */ if (!leave_session && !client_cfg->destroy_on_cb) - pjsip_regc_destroy(regc); + pjsip_regc_destroy(regc); /* Compare results with expected results */ if (client_result.error != client_cfg->error) { - PJ_LOG(3,(THIS_FILE, " error: expecting err=%d, got err=%d", - client_cfg->error, client_result.error)); - return -210; + PJ_LOG(3,(THIS_FILE, " error: expecting err=%d, got err=%d", + client_cfg->error, client_result.error)); + return -210; } if (client_result.code != client_cfg->code && - client_cfg->code != 502 && client_cfg->code != 503 && - client_result.code != 502 && client_result.code != 503) + client_cfg->code != 502 && client_cfg->code != 503 && + client_result.code != 502 && client_result.code != 503) { - PJ_LOG(3,(THIS_FILE, " error: expecting code=%d, got code=%d", - client_cfg->code, client_result.code)); - return -220; + PJ_LOG(3,(THIS_FILE, " error: expecting code=%d, got code=%d", + client_cfg->code, client_result.code)); + return -220; } if (client_result.expiration != client_cfg->expiration) { - PJ_LOG(3,(THIS_FILE, " error: expecting expiration=%d, got expiration=%d", - client_cfg->expiration, client_result.expiration)); - return -240; + PJ_LOG(3,(THIS_FILE, " error: expecting expiration=%d, got expiration=%d", + client_cfg->expiration, client_result.expiration)); + return -240; } if (client_result.contact_cnt != client_cfg->contact_cnt) { - PJ_LOG(3,(THIS_FILE, " error: expecting contact_cnt=%d, got contact_cnt=%d", - client_cfg->contact_cnt, client_result.contact_cnt)); - return -250; + PJ_LOG(3,(THIS_FILE, " error: expecting contact_cnt=%d, got contact_cnt=%d", + client_cfg->contact_cnt, client_result.contact_cnt)); + return -250; } if (client_result.have_reg != client_cfg->have_reg) { - PJ_LOG(3,(THIS_FILE, " error: expecting have_reg=%d, got have_reg=%d", - client_cfg->have_reg, client_result.have_reg)); - return -260; + PJ_LOG(3,(THIS_FILE, " error: expecting have_reg=%d, got have_reg=%d", + client_cfg->have_reg, client_result.have_reg)); + return -260; } if (client_result.have_reg && client_result.interval != client_result.expiration) { - PJ_LOG(3,(THIS_FILE, " error: interval (%d) is different than expiration (%d)", - client_result.interval, client_result.expiration)); - return -270; + PJ_LOG(3,(THIS_FILE, " error: interval (%d) is different than expiration (%d)", + client_result.interval, client_result.expiration)); + return -270; } if (client_result.interval > 0 && client_result.next_reg < 1) { - PJ_LOG(3,(THIS_FILE, " error: next_reg=%d, expecting positive number because interval is %d", - client_result.next_reg, client_result.interval)); - return -280; + PJ_LOG(3,(THIS_FILE, " error: next_reg=%d, expecting positive number because interval is %d", + client_result.next_reg, client_result.interval)); + return -280; } /* Looks like everything is okay. */ if (leave_session) { - *p_regc = regc; + *p_regc = regc; } return 0; @@ -400,11 +399,11 @@ static int keep_alive_test(const pj_str_t *registrar_uri) { enum { TIMEOUT = 40 }; struct registrar_cfg server_cfg = - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_TRUE, 200, PJ_FALSE, EXACT, TIMEOUT, 0, {NULL, 0}}; + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_TRUE, 200, PJ_FALSE, EXACT, TIMEOUT, 0, {NULL, 0}}; struct client client_cfg = - /* error code have_reg expiration contact_cnt auth? destroy*/ - { PJ_FALSE, 200, PJ_TRUE, TIMEOUT, 1, PJ_FALSE,PJ_FALSE}; + /* error code have_reg expiration contact_cnt auth? destroy*/ + { PJ_FALSE, 200, PJ_TRUE, TIMEOUT, 1, PJ_FALSE,PJ_FALSE}; pj_str_t contact = pj_str(""); @@ -413,56 +412,56 @@ static int keep_alive_test(const pj_str_t *registrar_uri) int ret; ret = do_test("register refresh (takes ~40 secs)", &server_cfg, &client_cfg, registrar_uri, - 1, &contact, TIMEOUT, PJ_TRUE, ®c); + 1, &contact, TIMEOUT, PJ_TRUE, ®c); if (ret != 0) - return ret; + return ret; /* Reset server response_cnt */ registrar.response_cnt = 0; /* Wait until keep-alive/refresh is done */ for (i=0; i<(TIMEOUT-1)*10 && registrar.response_cnt==0; ++i) { - flush_events(100); + flush_events(100); } if (registrar.response_cnt==0) { - PJ_LOG(3,(THIS_FILE, " error: no refresh is received")); - return -400; + PJ_LOG(3,(THIS_FILE, " error: no refresh is received")); + return -400; } if (client_result.error) { - PJ_LOG(3,(THIS_FILE, " error: got error")); - return -410; + PJ_LOG(3,(THIS_FILE, " error: got error")); + return -410; } if (client_result.code != 200) { - PJ_LOG(3,(THIS_FILE, " error: expecting code=%d, got code=%d", - 200, client_result.code)); - return -420; + PJ_LOG(3,(THIS_FILE, " error: expecting code=%d, got code=%d", + 200, client_result.code)); + return -420; } if (client_result.expiration != TIMEOUT) { - PJ_LOG(3,(THIS_FILE, " error: expecting expiration=%d, got expiration=%d", - TIMEOUT, client_result.expiration)); - return -440; + PJ_LOG(3,(THIS_FILE, " error: expecting expiration=%d, got expiration=%d", + TIMEOUT, client_result.expiration)); + return -440; } if (client_result.contact_cnt != 1) { - PJ_LOG(3,(THIS_FILE, " error: expecting contact_cnt=%d, got contact_cnt=%d", - TIMEOUT, client_result.contact_cnt)); - return -450; + PJ_LOG(3,(THIS_FILE, " error: expecting contact_cnt=%d, got contact_cnt=%d", + TIMEOUT, client_result.contact_cnt)); + return -450; } if (client_result.have_reg == 0) { - PJ_LOG(3,(THIS_FILE, " error: expecting have_reg=%d, got have_reg=%d", - 1, client_result.have_reg)); - return -460; + PJ_LOG(3,(THIS_FILE, " error: expecting have_reg=%d, got have_reg=%d", + 1, client_result.have_reg)); + return -460; } if (client_result.interval != TIMEOUT) { - PJ_LOG(3,(THIS_FILE, " error: interval (%d) is different than expiration (%d)", - client_result.interval, TIMEOUT)); - return -470; + PJ_LOG(3,(THIS_FILE, " error: interval (%d) is different than expiration (%d)", + client_result.interval, TIMEOUT)); + return -470; } if (client_result.expiration > 0 && client_result.next_reg < 1) { - PJ_LOG(3,(THIS_FILE, " error: next_reg=%d, expecting positive number because expiration is %d", - client_result.next_reg, client_result.expiration)); - return -480; + PJ_LOG(3,(THIS_FILE, " error: next_reg=%d, expecting positive number because expiration is %d", + client_result.next_reg, client_result.expiration)); + return -480; } /* Success */ @@ -473,15 +472,15 @@ static int keep_alive_test(const pj_str_t *registrar_uri) /* Send error on refresh */ static int refresh_error(const pj_str_t *registrar_uri, - pj_bool_t destroy_on_cb) + pj_bool_t destroy_on_cb) { enum { TIMEOUT = 40 }; struct registrar_cfg server_cfg = - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_TRUE, 200, PJ_FALSE, EXACT, TIMEOUT, 0, {NULL, 0}}; + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_TRUE, 200, PJ_FALSE, EXACT, TIMEOUT, 0, {NULL, 0}}; struct client client_cfg = - /* error code have_reg expiration contact_cnt auth? destroy*/ - { PJ_FALSE, 200, PJ_TRUE, TIMEOUT, 1, PJ_FALSE,PJ_FALSE}; + /* error code have_reg expiration contact_cnt auth? destroy*/ + { PJ_FALSE, 200, PJ_TRUE, TIMEOUT, 1, PJ_FALSE,PJ_FALSE}; pj_str_t contact = pj_str(""); pjsip_regc *regc; @@ -489,9 +488,9 @@ static int refresh_error(const pj_str_t *registrar_uri, int ret; ret = do_test("refresh error (takes ~40 secs)", &server_cfg, &client_cfg, registrar_uri, - 1, &contact, TIMEOUT, PJ_TRUE, ®c); + 1, &contact, TIMEOUT, PJ_TRUE, ®c); if (ret != 0) - return ret; + return ret; /* Reset server response_cnt */ registrar.response_cnt = 0; @@ -506,23 +505,23 @@ static int refresh_error(const pj_str_t *registrar_uri, /* Wait until keep-alive/refresh is done */ for (i=0; i", 7 }, - { "", 7 }, - { "", 7 } + { "", 7 }, + { "", 7 }, + { "", 7 } }; pjsip_regc *regc; @@ -555,9 +554,9 @@ static int update_test(const pj_str_t *registrar_uri) /* initially only has 1 contact */ ret = do_test("update test", &server_cfg, &client_cfg, registrar_uri, - 1, &contacts[0], TIMEOUT, PJ_TRUE, ®c); + 1, &contacts[0], TIMEOUT, PJ_TRUE, ®c); if (ret != 0) { - return -600; + return -600; } /***** @@ -566,14 +565,14 @@ static int update_test(const pj_str_t *registrar_uri) PJ_LOG(3,(THIS_FILE, " replacing contact")); status = pjsip_regc_update_contact(regc, 1, &contacts[1]); if (status != PJ_SUCCESS) { - ret = -610; - goto on_return; + ret = -610; + goto on_return; } status = pjsip_regc_register(regc, PJ_TRUE, &tdata); if (status != PJ_SUCCESS) { - ret = -620; - goto on_return; + ret = -620; + goto on_return; } /* Check that the REGISTER contains two Contacts: @@ -581,50 +580,50 @@ static int update_test(const pj_str_t *registrar_uri) * - */ h1 = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, NULL); + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, NULL); if (!h1) { - ret = -630; - goto on_return; + ret = -630; + goto on_return; } if ((void*)h1->next == (void*)&tdata->msg->hdr) - h2 = NULL; + h2 = NULL; else - h2 = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, h1->next); + h2 = (pjsip_contact_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, h1->next); if (!h2) { - ret = -640; - goto on_return; + ret = -640; + goto on_return; } /* must not have other Contact header */ if ((void*)h2->next != (void*)&tdata->msg->hdr && - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, h2->next) != NULL) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, h2->next) != NULL) { - ret = -645; - goto on_return; + ret = -645; + goto on_return; } u1 = (pjsip_sip_uri*) pjsip_uri_get_uri(h1->uri); if (*u1->host.ptr == 'a') { - if (h1->expires != 0) { - ret = -650; - goto on_return; - } - if (h2->expires == 0) { - ret = -660; - goto on_return; - } + if (h1->expires != 0) { + ret = -650; + goto on_return; + } + if (h2->expires == 0) { + ret = -660; + goto on_return; + } } else { - pj_assert(*u1->host.ptr == 'b'); - if (h1->expires == 0) { - ret = -670; - goto on_return; - } - if (h2->expires != 0) { - ret = -680; - goto on_return; - } + pj_assert(*u1->host.ptr == 'b'); + if (h1->expires == 0) { + ret = -670; + goto on_return; + } + if (h2->expires != 0) { + ret = -680; + goto on_return; + } } /* Destroy tdata */ @@ -638,63 +637,63 @@ static int update_test(const pj_str_t *registrar_uri) * should do nothing. */ for (i=0; i<2; ++i) { - if (i==0) - PJ_LOG(3,(THIS_FILE, " replacing with more contacts")); - else - PJ_LOG(3,(THIS_FILE, " updating contacts with same contacts")); - - status = pjsip_regc_update_contact(regc, 2, &contacts[1]); - if (status != PJ_SUCCESS) { - ret = -710; - goto on_return; - } - - status = pjsip_regc_register(regc, PJ_TRUE, &tdata); - if (status != PJ_SUCCESS) { - ret = -720; - goto on_return; - } - - /* Check that the REGISTER contains two Contacts: - * - - * - - */ - h1 = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, NULL); - if (!h1) { - ret = -730; - goto on_return; - } - if ((void*)h1->next == (void*)&tdata->msg->hdr) - h2 = NULL; - else - h2 = (pjsip_contact_hdr*) - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, h1->next); - if (!h2) { - ret = -740; - goto on_return; - } - /* must not have other Contact header */ - if ((void*)h2->next != (void*)&tdata->msg->hdr && - pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, h2->next) != NULL) - { - ret = -745; - goto on_return; - } - - /* both contacts must not have expires=0 parameter */ - if (h1->expires == 0) { - ret = -750; - goto on_return; - } - if (h2->expires == 0) { - ret = -760; - goto on_return; - } - - /* Destroy tdata */ - pjsip_tx_data_dec_ref(tdata); - tdata = NULL; + if (i==0) + PJ_LOG(3,(THIS_FILE, " replacing with more contacts")); + else + PJ_LOG(3,(THIS_FILE, " updating contacts with same contacts")); + + status = pjsip_regc_update_contact(regc, 2, &contacts[1]); + if (status != PJ_SUCCESS) { + ret = -710; + goto on_return; + } + + status = pjsip_regc_register(regc, PJ_TRUE, &tdata); + if (status != PJ_SUCCESS) { + ret = -720; + goto on_return; + } + + /* Check that the REGISTER contains two Contacts: + * - + * - + */ + h1 = (pjsip_contact_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, NULL); + if (!h1) { + ret = -730; + goto on_return; + } + if ((void*)h1->next == (void*)&tdata->msg->hdr) + h2 = NULL; + else + h2 = (pjsip_contact_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, h1->next); + if (!h2) { + ret = -740; + goto on_return; + } + /* must not have other Contact header */ + if ((void*)h2->next != (void*)&tdata->msg->hdr && + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, h2->next) != NULL) + { + ret = -745; + goto on_return; + } + + /* both contacts must not have expires=0 parameter */ + if (h1->expires == 0) { + ret = -750; + goto on_return; + } + if (h2->expires == 0) { + ret = -760; + goto on_return; + } + + /* Destroy tdata */ + pjsip_tx_data_dec_ref(tdata); + tdata = NULL; } on_return: @@ -706,15 +705,15 @@ static int update_test(const pj_str_t *registrar_uri) /* send error on authentication */ static int auth_send_error(const pj_str_t *registrar_uri, - pj_bool_t destroy_on_cb) + pj_bool_t destroy_on_cb) { enum { TIMEOUT = 40 }; struct registrar_cfg server_cfg = - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_TRUE, 200, PJ_TRUE, EXACT, 75, 0, {NULL, 0}}; + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_TRUE, 200, PJ_TRUE, EXACT, 75, 0, {NULL, 0}}; struct client client_cfg = - /* error code have_reg expiration contact_cnt auth? destroy*/ - { PJ_TRUE, 401, PJ_FALSE, TIMEOUT, 0, PJ_TRUE, PJ_TRUE}; + /* error code have_reg expiration contact_cnt auth? destroy*/ + { PJ_TRUE, 401, PJ_FALSE, TIMEOUT, 0, PJ_TRUE, PJ_TRUE}; pj_str_t contact = pj_str(""); pjsip_regc *regc; @@ -727,7 +726,7 @@ static int auth_send_error(const pj_str_t *registrar_uri, send_mod.count_before_reject = 1; ret = do_test("auth send error", &server_cfg, &client_cfg, registrar_uri, - 1, &contact, TIMEOUT, PJ_TRUE, ®c); + 1, &contact, TIMEOUT, PJ_TRUE, ®c); send_mod.count_before_reject = 0xFFFF; @@ -740,270 +739,270 @@ static int auth_send_error(const pj_str_t *registrar_uri, /************************************************************************/ enum { - OFF = 1, - ON = 2, + OFF = 1, + ON = 2, ON_OFF = 3, }; int regc_test(void) { struct test_rec { - unsigned check_contact; - unsigned add_xuid_param; - - const char *title; - char *alt_registrar; - unsigned contact_cnt; - char *contacts[4]; - unsigned expires; - struct registrar_cfg server_cfg; - struct client client_cfg; + unsigned check_contact; + unsigned add_xuid_param; + + const char *title; + char *alt_registrar; + unsigned contact_cnt; + char *contacts[4]; + unsigned expires; + struct registrar_cfg server_cfg; + struct client client_cfg; } test_rec[] = { - /* immediate error */ - { - OFF, /* check_contact */ - OFF, /* add_xuid_param */ - "immediate error", /* title */ - "sip:unresolved-host-xyy", /* alt_registrar */ - 1, /* contact cnt */ - { "sip:user@127.0.0.1:5060" }, /* contacts[] */ - 600, /* expires */ - - /* registrar config: */ - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_FALSE, 200, PJ_FALSE, NONE, 0, 0, {NULL, 0}}, - - /* client expected results: */ - /* error code have_reg expiration contact_cnt auth?*/ - { PJ_FALSE, 502, PJ_FALSE, 600, 0, PJ_FALSE} - }, - - /* timeout test */ - { - OFF, /* check_contact */ - OFF, /* add_xuid_param */ - "timeout test (takes ~32 secs)",/* title */ - NULL, /* alt_registrar */ - 1, /* contact cnt */ - { "sip:user@127.0.0.1:5060" }, /* contacts[] */ - 600, /* expires */ - - /* registrar config: */ - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_FALSE, 200, PJ_FALSE, NONE, 0, 0, {NULL, 0}}, - - /* client expected results: */ - /* error code have_reg expiration contact_cnt auth? */ - { PJ_FALSE, 408, PJ_FALSE, 600, 0, PJ_FALSE} - }, - - /* Basic successful registration scenario: - * a good registrar returns the Contact header as is and - * add expires parameter. In this test no additional bindings - * are returned. - */ - { - ON_OFF, /* check_contact */ - ON_OFF, /* add_xuid_param */ - "basic", /* title */ - NULL, /* alt_registrar */ - 1, /* contact cnt */ - { "" }, /* contacts[] */ - 600, /* expires */ - - /* registrar config: */ - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_TRUE, 200, PJ_FALSE, EXACT, 75, 65, {NULL, 0}}, - - /* client expected results: */ - /* error code have_reg expiration contact_cnt auth?*/ - { PJ_FALSE, 200, PJ_TRUE, 75, 1, PJ_FALSE} - }, - - /* Basic successful registration scenario with authentication - */ - { - ON_OFF, /* check_contact */ - ON_OFF, /* add_xuid_param */ - "authentication", /* title */ - NULL, /* alt_registrar */ - 1, /* contact cnt */ - { "" }, /* contacts[] */ - 600, /* expires */ - - /* registrar config: */ - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_TRUE, 200, PJ_TRUE, EXACT, 75, 65, {NULL, 0}}, - - /* client expected results: */ - /* error code have_reg expiration contact_cnt auth?*/ - { PJ_FALSE, 200, PJ_TRUE, 75, 1, PJ_TRUE} - }, - - /* a good registrar returns the Contact header as is and - * add expires parameter. Also it adds bindings from other - * clients in this test. - */ - { - ON_OFF, /* check_contact */ - ON, /* add_xuid_param */ - "more bindings in response", /* title */ - NULL, /* alt_registrar */ - 1, /* contact cnt */ - { "" }, /* contacts[] */ - 600, /* expires */ - - /* registrar config: */ - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_TRUE, 200, PJ_FALSE, EXACT, 75, 65, {";expires=70", 0}}, - - /* client expected results: */ - /* error code have_reg expiration contact_cnt auth?*/ - { PJ_FALSE, 200, PJ_TRUE, 75, 2, PJ_FALSE} - }, - - - /* a bad registrar returns modified Contact header, but it - * still returns all parameters intact. In this case - * the expiration is taken from the expires param because - * of matching xuid param or because the number of - * Contact header matches. - */ - { - ON_OFF, /* check_contact */ - ON_OFF, /* add_xuid_param */ - "registrar modifies Contact header", /* title */ - NULL, /* alt_registrar */ - 1, /* contact cnt */ - { "" }, /* contacts[] */ - 600, /* expires */ - - /* registrar config: */ - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_TRUE, 200, PJ_FALSE, MODIFIED, 75, 65, {NULL, 0}}, - - /* client expected results: */ - /* error code have_reg expiration contact_cnt auth?*/ - { PJ_FALSE, 200, PJ_TRUE, 75, 1, PJ_FALSE} - }, - - - /* a bad registrar returns modified Contact header, but it - * still returns all parameters intact. In addition it returns - * bindings from other clients. - * - * In this case the expiration is taken from the expires param - * because add_xuid_param is enabled. - */ - { - ON_OFF, /* check_contact */ - ON, /* add_xuid_param */ - "registrar modifies Contact header and add bindings", /* title */ - NULL, /* alt_registrar */ - 1, /* contact cnt */ - { "" }, /* contacts[] */ - 600, /* expires */ - - /* registrar config: */ - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_TRUE, 200, PJ_FALSE, MODIFIED, 75, 65, {";expires=70", 0}}, - - /* client expected results: */ - /* error code have_reg expiration contact_cnt auth?*/ - { PJ_FALSE, 200, PJ_TRUE, 75, 2, PJ_FALSE} - }, - - - /* a bad registrar returns completely different Contact and - * all parameters are gone. In this case the expiration is - * also taken from the expires param since the number of - * header matches. - */ - { - ON_OFF, /* check_contact */ - ON_OFF, /* add_xuid_param */ - "registrar replaces Contact header", /* title */ - NULL, /* alt_registrar */ - 1, /* contact cnt */ - { "" }, /* contacts[] */ - 600, /* expires */ - - /* registrar config: */ - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_TRUE, 202, PJ_FALSE, NONE, 0, 65, {";expires=75", 0}}, - - /* client expected results: */ - /* error code have_reg expiration contact_cnt auth?*/ - { PJ_FALSE, 202, PJ_TRUE, 75, 1, PJ_FALSE} - }, - - - /* a bad registrar returns completely different Contact (and - * all parameters are gone) and it also includes bindings from - * other clients. - * In this case the expiration is taken from the Expires header. - */ - { - ON_OFF, /* check_contact */ - ON_OFF, /* add_xuid_param */ - " as above with additional bindings", /* title */ - NULL, /* alt_registrar */ - 1, /* contact cnt */ - { "" }, /* contacts[] */ - 600, /* expires */ - - /* registrar config: */ - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_TRUE, 200, PJ_FALSE, NONE, 0, 65, {";expires=75, ", 0}}, - - /* client expected results: */ - /* error code have_reg expiration contact_cnt auth?*/ - { PJ_FALSE, 200, PJ_TRUE, 65, 2, PJ_FALSE} - }, - - /* the registrar doesn't return any bindings, but for some - * reason it includes an Expires header. - * In this case the expiration is taken from the Expires header. - */ - { - ON_OFF, /* check_contact */ - ON_OFF, /* add_xuid_param */ - "no Contact but with Expires", /* title */ - NULL, /* alt_registrar */ - 1, /* contact cnt */ - { "" }, /* contacts[] */ - 600, /* expires */ - - /* registrar config: */ - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_TRUE, 200, PJ_FALSE, NONE, 0, 65, {NULL, 0}}, - - /* client expected results: */ - /* error code have_reg expiration contact_cnt auth?*/ - { PJ_FALSE, 200, PJ_TRUE, 65, 0, PJ_FALSE} - }, - - /* Neither Contact header nor Expires header are present. - * In this case the expiration is taken from the request. - */ - { - ON_OFF, /* check_contact */ - ON_OFF, /* add_xuid_param */ - "no Contact and no Expires", /* title */ - NULL, /* alt_registrar */ - 1, /* contact cnt */ - { "" },/* contacts[] */ - 600, /* expires */ - - /* registrar config: */ - /* respond code auth contact exp_prm expires more_contacts */ - { PJ_TRUE, 200, PJ_FALSE, NONE, 0, 0, {NULL, 0}}, - - /* client expected results: */ - /* error code have_reg expiration contact_cnt auth?*/ - { PJ_FALSE, 200, PJ_TRUE, 600, 0, PJ_FALSE} - }, + /* immediate error */ + { + OFF, /* check_contact */ + OFF, /* add_xuid_param */ + "immediate error", /* title */ + "sip:unresolved-host-xyy", /* alt_registrar */ + 1, /* contact cnt */ + { "sip:user@127.0.0.1:5060" }, /* contacts[] */ + 600, /* expires */ + + /* registrar config: */ + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_FALSE, 200, PJ_FALSE, NONE, 0, 0, {NULL, 0}}, + + /* client expected results: */ + /* error code have_reg expiration contact_cnt auth?*/ + { PJ_FALSE, 502, PJ_FALSE, 600, 0, PJ_FALSE} + }, + + /* timeout test */ + { + OFF, /* check_contact */ + OFF, /* add_xuid_param */ + "timeout test (takes ~32 secs)",/* title */ + NULL, /* alt_registrar */ + 1, /* contact cnt */ + { "sip:user@127.0.0.1:5060" }, /* contacts[] */ + 600, /* expires */ + + /* registrar config: */ + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_FALSE, 200, PJ_FALSE, NONE, 0, 0, {NULL, 0}}, + + /* client expected results: */ + /* error code have_reg expiration contact_cnt auth? */ + { PJ_FALSE, 408, PJ_FALSE, 600, 0, PJ_FALSE} + }, + + /* Basic successful registration scenario: + * a good registrar returns the Contact header as is and + * add expires parameter. In this test no additional bindings + * are returned. + */ + { + ON_OFF, /* check_contact */ + ON_OFF, /* add_xuid_param */ + "basic", /* title */ + NULL, /* alt_registrar */ + 1, /* contact cnt */ + { "" }, /* contacts[] */ + 600, /* expires */ + + /* registrar config: */ + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_TRUE, 200, PJ_FALSE, EXACT, 75, 65, {NULL, 0}}, + + /* client expected results: */ + /* error code have_reg expiration contact_cnt auth?*/ + { PJ_FALSE, 200, PJ_TRUE, 75, 1, PJ_FALSE} + }, + + /* Basic successful registration scenario with authentication + */ + { + ON_OFF, /* check_contact */ + ON_OFF, /* add_xuid_param */ + "authentication", /* title */ + NULL, /* alt_registrar */ + 1, /* contact cnt */ + { "" }, /* contacts[] */ + 600, /* expires */ + + /* registrar config: */ + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_TRUE, 200, PJ_TRUE, EXACT, 75, 65, {NULL, 0}}, + + /* client expected results: */ + /* error code have_reg expiration contact_cnt auth?*/ + { PJ_FALSE, 200, PJ_TRUE, 75, 1, PJ_TRUE} + }, + + /* a good registrar returns the Contact header as is and + * add expires parameter. Also it adds bindings from other + * clients in this test. + */ + { + ON_OFF, /* check_contact */ + ON, /* add_xuid_param */ + "more bindings in response", /* title */ + NULL, /* alt_registrar */ + 1, /* contact cnt */ + { "" }, /* contacts[] */ + 600, /* expires */ + + /* registrar config: */ + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_TRUE, 200, PJ_FALSE, EXACT, 75, 65, {";expires=70", 0}}, + + /* client expected results: */ + /* error code have_reg expiration contact_cnt auth?*/ + { PJ_FALSE, 200, PJ_TRUE, 75, 2, PJ_FALSE} + }, + + + /* a bad registrar returns modified Contact header, but it + * still returns all parameters intact. In this case + * the expiration is taken from the expires param because + * of matching xuid param or because the number of + * Contact header matches. + */ + { + ON_OFF, /* check_contact */ + ON_OFF, /* add_xuid_param */ + "registrar modifies Contact header", /* title */ + NULL, /* alt_registrar */ + 1, /* contact cnt */ + { "" }, /* contacts[] */ + 600, /* expires */ + + /* registrar config: */ + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_TRUE, 200, PJ_FALSE, MODIFIED, 75, 65, {NULL, 0}}, + + /* client expected results: */ + /* error code have_reg expiration contact_cnt auth?*/ + { PJ_FALSE, 200, PJ_TRUE, 75, 1, PJ_FALSE} + }, + + + /* a bad registrar returns modified Contact header, but it + * still returns all parameters intact. In addition it returns + * bindings from other clients. + * + * In this case the expiration is taken from the expires param + * because add_xuid_param is enabled. + */ + { + ON_OFF, /* check_contact */ + ON, /* add_xuid_param */ + "registrar modifies Contact header and add bindings", /* title */ + NULL, /* alt_registrar */ + 1, /* contact cnt */ + { "" }, /* contacts[] */ + 600, /* expires */ + + /* registrar config: */ + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_TRUE, 200, PJ_FALSE, MODIFIED, 75, 65, {";expires=70", 0}}, + + /* client expected results: */ + /* error code have_reg expiration contact_cnt auth?*/ + { PJ_FALSE, 200, PJ_TRUE, 75, 2, PJ_FALSE} + }, + + + /* a bad registrar returns completely different Contact and + * all parameters are gone. In this case the expiration is + * also taken from the expires param since the number of + * header matches. + */ + { + ON_OFF, /* check_contact */ + ON_OFF, /* add_xuid_param */ + "registrar replaces Contact header", /* title */ + NULL, /* alt_registrar */ + 1, /* contact cnt */ + { "" }, /* contacts[] */ + 600, /* expires */ + + /* registrar config: */ + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_TRUE, 202, PJ_FALSE, NONE, 0, 65, {";expires=75", 0}}, + + /* client expected results: */ + /* error code have_reg expiration contact_cnt auth?*/ + { PJ_FALSE, 202, PJ_TRUE, 75, 1, PJ_FALSE} + }, + + + /* a bad registrar returns completely different Contact (and + * all parameters are gone) and it also includes bindings from + * other clients. + * In this case the expiration is taken from the Expires header. + */ + { + ON_OFF, /* check_contact */ + ON_OFF, /* add_xuid_param */ + " as above with additional bindings", /* title */ + NULL, /* alt_registrar */ + 1, /* contact cnt */ + { "" }, /* contacts[] */ + 600, /* expires */ + + /* registrar config: */ + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_TRUE, 200, PJ_FALSE, NONE, 0, 65, {";expires=75, ", 0}}, + + /* client expected results: */ + /* error code have_reg expiration contact_cnt auth?*/ + { PJ_FALSE, 200, PJ_TRUE, 65, 2, PJ_FALSE} + }, + + /* the registrar doesn't return any bindings, but for some + * reason it includes an Expires header. + * In this case the expiration is taken from the Expires header. + */ + { + ON_OFF, /* check_contact */ + ON_OFF, /* add_xuid_param */ + "no Contact but with Expires", /* title */ + NULL, /* alt_registrar */ + 1, /* contact cnt */ + { "" }, /* contacts[] */ + 600, /* expires */ + + /* registrar config: */ + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_TRUE, 200, PJ_FALSE, NONE, 0, 65, {NULL, 0}}, + + /* client expected results: */ + /* error code have_reg expiration contact_cnt auth?*/ + { PJ_FALSE, 200, PJ_TRUE, 65, 0, PJ_FALSE} + }, + + /* Neither Contact header nor Expires header are present. + * In this case the expiration is taken from the request. + */ + { + ON_OFF, /* check_contact */ + ON_OFF, /* add_xuid_param */ + "no Contact and no Expires", /* title */ + NULL, /* alt_registrar */ + 1, /* contact cnt */ + { "" },/* contacts[] */ + 600, /* expires */ + + /* registrar config: */ + /* respond code auth contact exp_prm expires more_contacts */ + { PJ_TRUE, 200, PJ_FALSE, NONE, 0, 0, {NULL, 0}}, + + /* client expected results: */ + /* error code have_reg expiration contact_cnt auth?*/ + { PJ_FALSE, 200, PJ_TRUE, 600, 0, PJ_FALSE} + }, }; unsigned i; @@ -1019,146 +1018,146 @@ int regc_test(void) /* Acquire existing transport, if any */ rc = pjsip_endpt_acquire_transport(endpt, PJSIP_TRANSPORT_UDP, &addr, sizeof(addr), NULL, &udp); if (rc == PJ_SUCCESS) { - port = pj_sockaddr_get_port(&udp->local_addr); - pjsip_transport_dec_ref(udp); - udp = NULL; + port = pj_sockaddr_get_port(&udp->local_addr); + pjsip_transport_dec_ref(udp); + udp = NULL; } else { - rc = pjsip_udp_transport_start(endpt, NULL, NULL, 1, &udp); - if (rc != PJ_SUCCESS) { - app_perror(" error creating UDP transport", rc); - rc = -2; - goto on_return; - } - - port = pj_sockaddr_get_port(&udp->local_addr); + rc = pjsip_udp_transport_start(endpt, NULL, NULL, 1, &udp); + if (rc != PJ_SUCCESS) { + app_perror(" error creating UDP transport", rc); + rc = -2; + goto on_return; + } + + port = pj_sockaddr_get_port(&udp->local_addr); } /* Register registrar module */ rc = pjsip_endpt_register_module(endpt, ®istrar.mod); if (rc != PJ_SUCCESS) { - app_perror(" error registering module", rc); - rc = -3; - goto on_return; + app_perror(" error registering module", rc); + rc = -3; + goto on_return; } /* Register send module */ rc = pjsip_endpt_register_module(endpt, &send_mod.mod); if (rc != PJ_SUCCESS) { - app_perror(" error registering module", rc); - rc = -3; - goto on_return; + app_perror(" error registering module", rc); + rc = -3; + goto on_return; } pj_ansi_snprintf(registrar_uri_buf, sizeof(registrar_uri_buf), - "sip:127.0.0.1:%d", (int)port); + "sip:127.0.0.1:%d", (int)port); registrar_uri = pj_str(registrar_uri_buf); for (i=0; ialt_registrar == NULL) { - reg_uri = registrar_uri; - } else { - reg_uri = pj_str(t->alt_registrar); - } - - /* Build contact pj_str_t's */ - for (j=0; jcontact_cnt; ++j) { - contacts[j] = pj_str(t->contacts[j]); - } - - /* Normalize more_contacts field */ - if (t->server_cfg.more_contacts.ptr) - t->server_cfg.more_contacts.slen = strlen(t->server_cfg.more_contacts.ptr); - - /* Do tests with three combinations: - * - check_contact on/off - * - add_xuid_param on/off - * - destroy_on_callback on/off - */ - for (x=1; x<=2; ++x) { - unsigned y; - - if ((t->check_contact & x) == 0) - continue; - - pjsip_cfg()->regc.check_contact = (x-1); - - for (y=1; y<=2; ++y) { - unsigned z; - - if ((t->add_xuid_param & y) == 0) - continue; - - pjsip_cfg()->regc.add_xuid_param = (y-1); - - for (z=0; z<=1; ++z) { - char new_title[200]; - - t->client_cfg.destroy_on_cb = z; - - sprintf(new_title, "%s [check=%d, xuid=%d, destroy=%d]", - t->title, pjsip_cfg()->regc.check_contact, - pjsip_cfg()->regc.add_xuid_param, z); - rc = do_test(new_title, &t->server_cfg, &t->client_cfg, - ®_uri, t->contact_cnt, contacts, - t->expires, PJ_FALSE, NULL); - if (rc != 0) - goto on_return; - } - - } - } - - /* Sleep between test groups to avoid using up too many - * active transactions. - */ - pj_thread_sleep(1000); + struct test_rec *t = &test_rec[i]; + unsigned j, x; + pj_str_t reg_uri; + pj_str_t contacts[8]; + + /* Fill in the registrar address if it's not specified */ + if (t->alt_registrar == NULL) { + reg_uri = registrar_uri; + } else { + reg_uri = pj_str(t->alt_registrar); + } + + /* Build contact pj_str_t's */ + for (j=0; jcontact_cnt; ++j) { + contacts[j] = pj_str(t->contacts[j]); + } + + /* Normalize more_contacts field */ + if (t->server_cfg.more_contacts.ptr) + t->server_cfg.more_contacts.slen = strlen(t->server_cfg.more_contacts.ptr); + + /* Do tests with three combinations: + * - check_contact on/off + * - add_xuid_param on/off + * - destroy_on_callback on/off + */ + for (x=1; x<=2; ++x) { + unsigned y; + + if ((t->check_contact & x) == 0) + continue; + + pjsip_cfg()->regc.check_contact = (x-1); + + for (y=1; y<=2; ++y) { + unsigned z; + + if ((t->add_xuid_param & y) == 0) + continue; + + pjsip_cfg()->regc.add_xuid_param = (y-1); + + for (z=0; z<=1; ++z) { + char new_title[200]; + + t->client_cfg.destroy_on_cb = z; + + sprintf(new_title, "%s [check=%d, xuid=%d, destroy=%d]", + t->title, pjsip_cfg()->regc.check_contact, + pjsip_cfg()->regc.add_xuid_param, z); + rc = do_test(new_title, &t->server_cfg, &t->client_cfg, + ®_uri, t->contact_cnt, contacts, + t->expires, PJ_FALSE, NULL); + if (rc != 0) + goto on_return; + } + + } + } + + /* Sleep between test groups to avoid using up too many + * active transactions. + */ + pj_thread_sleep(1000); } /* keep-alive test */ rc = keep_alive_test(®istrar_uri); if (rc != 0) - goto on_return; + goto on_return; /* Send error on refresh without destroy on callback */ rc = refresh_error(®istrar_uri, PJ_FALSE); if (rc != 0) - goto on_return; + goto on_return; /* Send error on refresh, destroy on callback */ rc = refresh_error(®istrar_uri, PJ_TRUE); if (rc != 0) - goto on_return; + goto on_return; /* Updating contact */ rc = update_test(®istrar_uri); if (rc != 0) - goto on_return; + goto on_return; /* Send error during auth, don't destroy on callback */ rc = auth_send_error(®istrar_uri, PJ_FALSE); if (rc != 0) - goto on_return; + goto on_return; /* Send error during auth, destroy on callback */ rc = auth_send_error(®istrar_uri, PJ_FALSE); if (rc != 0) - goto on_return; + goto on_return; on_return: if (registrar.mod.id != -1) { - pjsip_endpt_unregister_module(endpt, ®istrar.mod); + pjsip_endpt_unregister_module(endpt, ®istrar.mod); } if (send_mod.mod.id != -1) { - pjsip_endpt_unregister_module(endpt, &send_mod.mod); + pjsip_endpt_unregister_module(endpt, &send_mod.mod); } if (udp) { - pjsip_transport_dec_ref(udp); + pjsip_transport_dec_ref(udp); } return rc; } diff --git a/pjsip/src/test/test.c b/pjsip/src/test/test.c index cc010ca069..8ca3a5094f 100644 --- a/pjsip/src/test/test.c +++ b/pjsip/src/test/test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -26,24 +25,24 @@ #define THIS_FILE "test.c" -#define DO_TEST(test) do { \ - PJ_LOG(3, (THIS_FILE, "Running %s...", #test)); \ - rc = test; \ - PJ_LOG(3, (THIS_FILE, \ - "%s(%d)", \ - (rc ? "..ERROR" : "..success"), rc)); \ - if (rc!=0) goto on_return; \ - } while (0) +#define DO_TEST(test) do { \ + PJ_LOG(3, (THIS_FILE, "Running %s...", #test)); \ + rc = test; \ + PJ_LOG(3, (THIS_FILE, \ + "%s(%d)", \ + (rc ? "..ERROR" : "..success"), rc)); \ + if (rc!=0) goto on_return; \ + } while (0) #define DO_TSX_TEST(test, param) \ - do { \ - PJ_LOG(3, (THIS_FILE, "Running %s(%s)...", #test, (param)->tp_type)); \ - rc = test(param); \ - PJ_LOG(3, (THIS_FILE, \ - "%s(%d)", \ - (rc ? "..ERROR" : "..success"), rc)); \ - if (rc!=0) goto on_return; \ - } while (0) + do { \ + PJ_LOG(3, (THIS_FILE, "Running %s(%s)...", #test, (param)->tp_type)); \ + rc = test(param); \ + PJ_LOG(3, (THIS_FILE, \ + "%s(%d)", \ + (rc ? "..ERROR" : "..success"), rc)); \ + if (rc!=0) goto on_return; \ + } while (0) #ifdef _MSC_VER # define strtok_r strtok_s @@ -53,7 +52,7 @@ pjsip_endpoint *endpt; pj_caching_pool caching_pool; int log_level = 3; int param_log_decor = PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_TIME | PJ_LOG_HAS_SENDER | - PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_INDENT; + PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_INDENT; static pj_oshandle_t fd_report; const char *system_name = "Unknown"; @@ -102,24 +101,24 @@ static pj_status_t select_tests(char *testlist) int j; if (!testlist) { - return PJ_SUCCESS; + return PJ_SUCCESS; } run_all_tests = 0; for (token = strtok_r(testlist, ",", &saveptr); token != NULL; - token = strtok_r(NULL, ",", &saveptr)) { - - int found = 0; - for (j = 0; j < maxtok; j++) { - if (strcmp(token, test_list[j].name) == 0) { - test_list[j].run_test = 1; - found = 1; - } - } - if (!found) { - fprintf(stderr, "Test '%s' is not valid\n", token); - return PJ_ENOTFOUND; - } + token = strtok_r(NULL, ",", &saveptr)) { + + int found = 0; + for (j = 0; j < maxtok; j++) { + if (strcmp(token, test_list[j].name) == 0) { + test_list[j].run_test = 1; + found = 1; + } + } + if (!found) { + fprintf(stderr, "Test '%s' is not valid\n", token); + return PJ_ENOTFOUND; + } } return PJ_SUCCESS; @@ -132,7 +131,7 @@ void list_tests(void) { fprintf(stderr, "Valid tests:\n"); for (j = 0; j < maxtok; j++) { - fprintf(stderr, " %s\n", test_list[j].name); + fprintf(stderr, " %s\n", test_list[j].name); } } @@ -159,13 +158,13 @@ void flush_events(unsigned duration) /* Process all events for the specified duration. */ for (;;) { - pj_time_val timeout = {0, 1}, now; + pj_time_val timeout = {0, 1}, now; - pjsip_endpt_handle_events(endpt, &timeout); + pjsip_endpt_handle_events(endpt, &timeout); - pj_gettimeofday(&now); - if (PJ_TIME_VAL_GTE(now, stop_time)) - break; + pj_gettimeofday(&now); + if (PJ_TIME_VAL_GTE(now, stop_time)) + break; } } @@ -189,38 +188,38 @@ static pj_status_t init_report(void) status = pj_file_open(NULL, tmp, PJ_O_WRONLY, &fd_report); if (status != PJ_SUCCESS) - return status; + return status; /* Title */ len = pj_ansi_sprintf(buf, "\n" - " \n" - " PJSIP %s (%s) - Static Benchmark\n" - " \n" - "\n" - "\n", - PJ_VERSION, - (PJ_DEBUG ? "Debug" : "Release")); + " \n" + " PJSIP %s (%s) - Static Benchmark\n" + " \n" + "\n" + "\n", + PJ_VERSION, + (PJ_DEBUG ? "Debug" : "Release")); pj_file_write(fd_report, buf, &len); /* Title */ len = pj_ansi_sprintf(buf, "

PJSIP %s (%s) - Static Benchmark

\n", - PJ_VERSION, - (PJ_DEBUG ? "Debug" : "Release")); + PJ_VERSION, + (PJ_DEBUG ? "Debug" : "Release")); pj_file_write(fd_report, buf, &len); len = pj_ansi_sprintf(buf, "

Below is the benchmark result generated " - "by test-pjsip program. The program " - "is single-threaded only.

\n"); + "by test-pjsip program. The program " + "is single-threaded only.

\n"); pj_file_write(fd_report, buf, &len); /* Write table heading */ len = pj_ansi_sprintf(buf, "\n" - " \n" - " \n" - " \n" - " \n"); + " \n" + " \n" + " \n" + " \n"); pj_file_write(fd_report, buf, &len); @@ -240,8 +239,8 @@ static pj_status_t init_report(void) /* Write time of day */ pj_time_decode(×tamp, &date_time); len = pj_ansi_sprintf(tmp, "%04d-%02d-%02d %02d:%02d:%02d", - date_time.year, date_time.mon+1, date_time.day, - date_time.hour, date_time.min, date_time.sec); + date_time.year, date_time.mon+1, date_time.day, + date_time.hour, date_time.min, date_time.sec); report_sval("date-time", tmp, "", "Date/time of the test"); @@ -255,7 +254,7 @@ static pj_status_t init_report(void) /* Write CC name */ len = pj_ansi_sprintf(tmp, "%s-%d.%d.%d", PJ_CC_NAME, - PJ_CC_VER_1, PJ_CC_VER_2, PJ_CC_VER_2); + PJ_CC_VER_1, PJ_CC_VER_2, PJ_CC_VER_2); report_sval("cc-name", tmp, "", "Compiler name and version"); @@ -263,29 +262,29 @@ static pj_status_t init_report(void) } void report_sval(const char *name, const char* value, const char *valname, - const char *desc) + const char *desc) { pj_ssize_t len; len = pj_ansi_sprintf(buf, " \n" - " \n" - " \n" - " \n", - name, value, valname, desc); + " \n" + " \n" + " \n", + name, value, valname, desc); pj_file_write(fd_report, buf, &len); } void report_ival(const char *name, int value, const char *valname, - const char *desc) + const char *desc) { pj_ssize_t len; len = pj_ansi_sprintf(buf, " \n" - " \n" - " \n" - " \n", - name, value, valname, desc); + " \n" + " \n" + " \n", + name, value, valname, desc); pj_file_write(fd_report, buf, &len); } @@ -295,10 +294,10 @@ static void close_report(void) pj_ssize_t len; if (fd_report) { - len = pj_ansi_sprintf(buf, "
VariableValueDescription
VariableValueDescription
%s%s %s%s
%s %s%s
%s%d %s%s
%d %s%s
\n\n\n"); - pj_file_write(fd_report, buf, &len); + len = pj_ansi_sprintf(buf, "\n\n\n"); + pj_file_write(fd_report, buf, &len); - pj_file_close(fd_report); + pj_file_close(fd_report); } } @@ -315,43 +314,43 @@ int test_main(char *testlist) pjsip_transport *tp; #if PJ_HAS_TCP pjsip_tpfactory *tpfactory; -#endif /* PJ_HAS_TCP */ -#endif /* INCLUDE_TSX_TEST */ +#endif /* PJ_HAS_TCP */ +#endif /* INCLUDE_TSX_TEST */ int line; rc = select_tests(testlist); if (rc != PJ_SUCCESS) { - list_tests(); - return rc; + list_tests(); + return rc; } pj_log_set_level(log_level); pj_log_set_decor(param_log_decor); if ((rc=pj_init()) != PJ_SUCCESS) { - app_perror("pj_init", rc); - return rc; + app_perror("pj_init", rc); + return rc; } if ((rc=pjlib_util_init()) != PJ_SUCCESS) { - app_perror("pj_init", rc); - return rc; + app_perror("pj_init", rc); + return rc; } status = init_report(); if (status != PJ_SUCCESS) - return status; + return status; pj_dump_config(); pj_caching_pool_init( &caching_pool, &pj_pool_factory_default_policy, - PJSIP_TEST_MEM_SIZE ); + PJSIP_TEST_MEM_SIZE ); rc = pjsip_endpt_create(&caching_pool.factory, "endpt", &endpt); if (rc != PJ_SUCCESS) { - app_perror("pjsip_endpt_create", rc); - pj_caching_pool_destroy(&caching_pool); - return rc; + app_perror("pjsip_endpt_create", rc); + pj_caching_pool_destroy(&caching_pool); + return rc; } PJ_LOG(3,(THIS_FILE,"")); @@ -363,16 +362,16 @@ int test_main(char *testlist) /* Start transaction layer module. */ rc = pjsip_tsx_layer_init_module(endpt); if (rc != PJ_SUCCESS) { - app_perror(" Error initializing transaction module", rc); - goto on_return; + app_perror(" Error initializing transaction module", rc); + goto on_return; } /* Create loop transport. */ rc = pjsip_loop_start(endpt, NULL); if (rc != PJ_SUCCESS) { - app_perror(" error: unable to create datagram loop transport", - rc); - goto on_return; + app_perror(" error: unable to create datagram loop transport", + rc); + goto on_return; } tsx_test[tsx_test_cnt].port = 5060; tsx_test[tsx_test_cnt].tp_type = "loop-dgram"; @@ -382,101 +381,101 @@ int test_main(char *testlist) #if INCLUDE_URI_TEST if (SHOULD_RUN_TEST(include_uri_test)) { - DO_TEST(uri_test()); + DO_TEST(uri_test()); } #endif #if INCLUDE_MSG_TEST if (SHOULD_RUN_TEST(include_msg_test)) { - DO_TEST(msg_test()); - DO_TEST(msg_err_test()); + DO_TEST(msg_test()); + DO_TEST(msg_err_test()); } #endif #if INCLUDE_MULTIPART_TEST if (SHOULD_RUN_TEST(include_multipart_test)) { - DO_TEST(multipart_test()); + DO_TEST(multipart_test()); } #endif #if INCLUDE_TXDATA_TEST if (SHOULD_RUN_TEST(include_txdata_test)) { - DO_TEST(txdata_test()); + DO_TEST(txdata_test()); } #endif #if INCLUDE_TSX_BENCH if (SHOULD_RUN_TEST(include_tsx_bench)) { - DO_TEST(tsx_bench()); + DO_TEST(tsx_bench()); } #endif #if INCLUDE_UDP_TEST if (SHOULD_RUN_TEST(include_udp_test)) { - DO_TEST(transport_udp_test()); + DO_TEST(transport_udp_test()); } #endif #if INCLUDE_LOOP_TEST if (SHOULD_RUN_TEST(include_loop_test)) { - DO_TEST(transport_loop_test()); + DO_TEST(transport_loop_test()); } #endif #if INCLUDE_TCP_TEST if (SHOULD_RUN_TEST(include_tcp_test)) { - DO_TEST(transport_tcp_test()); + DO_TEST(transport_tcp_test()); } #endif #if INCLUDE_RESOLVE_TEST if (SHOULD_RUN_TEST(include_resolve_test)) { - DO_TEST(resolve_test()); + DO_TEST(resolve_test()); } #endif #if INCLUDE_TSX_TEST if (SHOULD_RUN_TEST(include_tsx_test)) { - status = pjsip_udp_transport_start(endpt, NULL, NULL, 1, &tp); - if (status == PJ_SUCCESS) { - tsx_test[tsx_test_cnt].port = tp->local_name.port; - tsx_test[tsx_test_cnt].tp_type = "udp"; - tsx_test[tsx_test_cnt].type = PJSIP_TRANSPORT_UDP; - ++tsx_test_cnt; - } + status = pjsip_udp_transport_start(endpt, NULL, NULL, 1, &tp); + if (status == PJ_SUCCESS) { + tsx_test[tsx_test_cnt].port = tp->local_name.port; + tsx_test[tsx_test_cnt].tp_type = "udp"; + tsx_test[tsx_test_cnt].type = PJSIP_TRANSPORT_UDP; + ++tsx_test_cnt; + } #if PJ_HAS_TCP - status = pjsip_tcp_transport_start(endpt, NULL, 1, &tpfactory); - if (status == PJ_SUCCESS) { - tsx_test[tsx_test_cnt].port = tpfactory->addr_name.port; - tsx_test[tsx_test_cnt].tp_type = "tcp"; - tsx_test[tsx_test_cnt].type = PJSIP_TRANSPORT_TCP; - ++tsx_test_cnt; - } else { - app_perror("Unable to create TCP", status); - rc = -4; - goto on_return; - } + status = pjsip_tcp_transport_start(endpt, NULL, 1, &tpfactory); + if (status == PJ_SUCCESS) { + tsx_test[tsx_test_cnt].port = tpfactory->addr_name.port; + tsx_test[tsx_test_cnt].tp_type = "tcp"; + tsx_test[tsx_test_cnt].type = PJSIP_TRANSPORT_TCP; + ++tsx_test_cnt; + } else { + app_perror("Unable to create TCP", status); + rc = -4; + goto on_return; + } #endif - for (i = 0; i < tsx_test_cnt; ++i) { - DO_TSX_TEST(tsx_basic_test, &tsx_test[i]); - DO_TSX_TEST(tsx_uac_test, &tsx_test[i]); - DO_TSX_TEST(tsx_uas_test, &tsx_test[i]); - } + for (i = 0; i < tsx_test_cnt; ++i) { + DO_TSX_TEST(tsx_basic_test, &tsx_test[i]); + DO_TSX_TEST(tsx_uac_test, &tsx_test[i]); + DO_TSX_TEST(tsx_uas_test, &tsx_test[i]); + } } #endif #if INCLUDE_INV_OA_TEST if (SHOULD_RUN_TEST(include_inv_oa_test)) { - DO_TEST(inv_offer_answer_test()); + DO_TEST(inv_offer_answer_test()); } #endif #if INCLUDE_REGC_TEST if (SHOULD_RUN_TEST(include_regc_test)) { - DO_TEST(regc_test()); + DO_TEST(regc_test()); } #endif @@ -485,7 +484,7 @@ int test_main(char *testlist) */ #if INCLUDE_TSX_DESTROY_TEST if (SHOULD_RUN_TEST(include_tsx_destroy_test)) { - DO_TEST(tsx_destroy_test()); + DO_TEST(tsx_destroy_test()); } #endif @@ -497,7 +496,7 @@ int test_main(char *testlist) /* Dumping memory pool usage */ PJ_LOG(3,(THIS_FILE, "Peak memory size=%u MB", - caching_pool.peak_used_size / 1000000)); + caching_pool.peak_used_size / 1000000)); pjsip_endpt_destroy(endpt); pj_caching_pool_destroy(&caching_pool); @@ -506,12 +505,12 @@ int test_main(char *testlist) pj_thread_get_stack_info(pj_thread_this(), &filename, &line); PJ_LOG(3,(THIS_FILE, "Stack max usage: %u, deepest: %s:%u", - pj_thread_get_stack_max_usage(pj_thread_this()), - filename, line)); + pj_thread_get_stack_max_usage(pj_thread_this()), + filename, line)); if (rc == 0) - PJ_LOG(3,(THIS_FILE, "Looks like everything is okay!..")); + PJ_LOG(3,(THIS_FILE, "Looks like everything is okay!..")); else - PJ_LOG(3,(THIS_FILE, "Test completed with error(s)")); + PJ_LOG(3,(THIS_FILE, "Test completed with error(s)")); report_ival("test-status", rc, "", "Overall test status/result (0==success)"); close_report(); diff --git a/pjsip/src/test/test.h b/pjsip/src/test/test.h index 66720c9d53..4fd8793c70 100644 --- a/pjsip/src/test/test.h +++ b/pjsip/src/test/test.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,7 +24,7 @@ extern pjsip_endpoint *endpt; extern pj_caching_pool caching_pool; -#define TEST_UDP_PORT 15060 +#define TEST_UDP_PORT 15060 #define TEST_UDP_PORT_STR "15060" /** @@ -33,45 +32,45 @@ extern pj_caching_pool caching_pool; * Default: 2MB */ #ifndef PJSIP_TEST_MEM_SIZE -# define PJSIP_TEST_MEM_SIZE (2*1024*1024) +# define PJSIP_TEST_MEM_SIZE (2*1024*1024) #endif -#define INCLUDE_MESSAGING_GROUP 1 -#define INCLUDE_TRANSPORT_GROUP 1 -#define INCLUDE_TSX_GROUP 1 -#define INCLUDE_INV_GROUP 1 -#define INCLUDE_REGC_GROUP 1 +#define INCLUDE_MESSAGING_GROUP 1 +#define INCLUDE_TRANSPORT_GROUP 1 +#define INCLUDE_TSX_GROUP 1 +#define INCLUDE_INV_GROUP 1 +#define INCLUDE_REGC_GROUP 1 -#define INCLUDE_BENCHMARKS 1 +#define INCLUDE_BENCHMARKS 1 /* * Include tests that normally would fail under certain gcc * optimization levels. */ #ifndef INCLUDE_GCC_TEST -# define INCLUDE_GCC_TEST 0 +# define INCLUDE_GCC_TEST 0 #endif #if defined(PJ_EXCLUDE_BENCHMARK_TESTS) && (PJ_EXCLUDE_BENCHMARK_TESTS==1) -# define WITH_BENCHMARK 0 +# define WITH_BENCHMARK 0 #else -# define WITH_BENCHMARK 1 +# define WITH_BENCHMARK 1 #endif -#define INCLUDE_URI_TEST INCLUDE_MESSAGING_GROUP -#define INCLUDE_MSG_TEST INCLUDE_MESSAGING_GROUP -#define INCLUDE_MULTIPART_TEST INCLUDE_MESSAGING_GROUP -#define INCLUDE_TXDATA_TEST INCLUDE_MESSAGING_GROUP -#define INCLUDE_TSX_BENCH (INCLUDE_MESSAGING_GROUP && WITH_BENCHMARK) -#define INCLUDE_UDP_TEST INCLUDE_TRANSPORT_GROUP -#define INCLUDE_LOOP_TEST INCLUDE_TRANSPORT_GROUP -#define INCLUDE_TCP_TEST INCLUDE_TRANSPORT_GROUP -#define INCLUDE_RESOLVE_TEST INCLUDE_TRANSPORT_GROUP -#define INCLUDE_TSX_TEST INCLUDE_TSX_GROUP +#define INCLUDE_URI_TEST INCLUDE_MESSAGING_GROUP +#define INCLUDE_MSG_TEST INCLUDE_MESSAGING_GROUP +#define INCLUDE_MULTIPART_TEST INCLUDE_MESSAGING_GROUP +#define INCLUDE_TXDATA_TEST INCLUDE_MESSAGING_GROUP +#define INCLUDE_TSX_BENCH (INCLUDE_MESSAGING_GROUP && WITH_BENCHMARK) +#define INCLUDE_UDP_TEST INCLUDE_TRANSPORT_GROUP +#define INCLUDE_LOOP_TEST INCLUDE_TRANSPORT_GROUP +#define INCLUDE_TCP_TEST INCLUDE_TRANSPORT_GROUP +#define INCLUDE_RESOLVE_TEST INCLUDE_TRANSPORT_GROUP +#define INCLUDE_TSX_TEST INCLUDE_TSX_GROUP #define INCLUDE_TSX_DESTROY_TEST INCLUDE_TSX_GROUP -#define INCLUDE_INV_OA_TEST INCLUDE_INV_GROUP -#define INCLUDE_REGC_TEST INCLUDE_REGC_GROUP +#define INCLUDE_INV_OA_TEST INCLUDE_INV_GROUP +#define INCLUDE_REGC_TEST INCLUDE_REGC_GROUP /* The tests */ @@ -102,13 +101,13 @@ int tsx_uas_test(struct tsx_test_param *param); /* Transport test helpers (transport_test.c). */ int generic_transport_test(pjsip_transport *tp); int transport_send_recv_test( pjsip_transport_type_e tp_type, - pjsip_transport *ref_tp, - char *target_url, - int *p_usec_rtt); + pjsip_transport *ref_tp, + char *target_url, + int *p_usec_rtt); int transport_rt_test( pjsip_transport_type_e tp_type, - pjsip_transport *ref_tp, - char *target_url, - int *pkt_lost); + pjsip_transport *ref_tp, + char *target_url, + int *pkt_lost); int transport_load_test(char *target_url); /* Invite session */ @@ -132,4 +131,4 @@ void report_sval(const char *name, const char* value, const char *valname, const /* Settings. */ extern int log_level; -#endif /* __TEST_H__ */ +#endif /* __TEST_H__ */ diff --git a/pjsip/src/test/transport_loop_test.c b/pjsip/src/test/transport_loop_test.c index 5f2f039043..41f0404142 100644 --- a/pjsip/src/test/transport_loop_test.c +++ b/pjsip/src/test/transport_loop_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -39,10 +38,10 @@ static int datagram_loop_test() pj_sockaddr_in_init(&addr, NULL, 0); /* Test acquire transport. */ status = pjsip_endpt_acquire_transport( endpt, PJSIP_TRANSPORT_LOOP_DGRAM, - &addr, sizeof(addr), NULL, &loop); + &addr, sizeof(addr), NULL, &loop); if (status != PJ_SUCCESS) { - app_perror(" error: loop transport is not configured", status); - return -20; + app_perror(" error: loop transport is not configured", status); + return -20; } /* Get initial reference counter */ @@ -51,37 +50,37 @@ static int datagram_loop_test() /* Test basic transport attributes */ status = generic_transport_test(loop); if (status != PJ_SUCCESS) - return status; + return status; /* Basic transport's send/receive loopback test. */ for (i=0; iref_cnt) != ref_cnt) { - PJ_LOG(3,(THIS_FILE, " error: ref counter is not %d (%d)", - ref_cnt, pj_atomic_get(loop->ref_cnt))); - return -51; + PJ_LOG(3,(THIS_FILE, " error: ref counter is not %d (%d)", + ref_cnt, pj_atomic_get(loop->ref_cnt))); + return -51; } /* Decrement reference. */ @@ -122,7 +121,7 @@ int transport_loop_test(void) status = datagram_loop_test(); if (status != 0) - return status; + return status; return 0; } diff --git a/pjsip/src/test/transport_tcp_test.c b/pjsip/src/test/transport_tcp_test.c index b10455664f..df01780254 100644 --- a/pjsip/src/test/transport_tcp_test.c +++ b/pjsip/src/test/transport_tcp_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -31,9 +30,9 @@ #if PJ_HAS_TCP static pj_status_t multi_listener_test(pjsip_tpfactory *factory[], - unsigned num_factory, - pjsip_transport *tp[], - unsigned *num_tp) + unsigned num_factory, + pjsip_transport *tp[], + unsigned *num_tp) { pj_status_t status; unsigned i = 0; @@ -46,31 +45,31 @@ static pj_status_t multi_listener_test(pjsip_tpfactory *factory[], for (;iaddr_name.host, - (pj_uint16_t)tpfactory->addr_name.port); + (pj_uint16_t)tpfactory->addr_name.port); if (status != PJ_SUCCESS) { - app_perror(" Error: possibly invalid TCP address name", status); - return -11; + app_perror(" Error: possibly invalid TCP address name", status); + return -11; } /* Acquire transport without selector. */ status = pjsip_endpt_acquire_transport(endpt, PJSIP_TRANSPORT_TCP, - &rem_addr, sizeof(rem_addr), - NULL, &tcp); + &rem_addr, sizeof(rem_addr), + NULL, &tcp); if (status != PJ_SUCCESS || tcp == NULL) { - app_perror(" Error: unable to acquire TCP transport", status); - return -12; + app_perror(" Error: unable to acquire TCP transport", status); + return -12; } tp[ntp++] = tcp; @@ -78,26 +77,26 @@ static pj_status_t multi_listener_test(pjsip_tpfactory *factory[], * reference counter 1. */ if (pj_atomic_get(tcp->ref_cnt) != 1) - return -13; + return -13; /* Acquire with the same remote address, should return the same tp. */ status = pjsip_endpt_acquire_transport(endpt, PJSIP_TRANSPORT_TCP, - &rem_addr, sizeof(rem_addr), - NULL, &tcp); + &rem_addr, sizeof(rem_addr), + NULL, &tcp); if (status != PJ_SUCCESS || tcp == NULL) { - app_perror(" Error: unable to acquire TCP transport", status); - return -14; + app_perror(" Error: unable to acquire TCP transport", status); + return -14; } /* Should return existing transport. */ if (tp[ntp-1] != tcp) { - return -15; + return -15; } /* Using the same TCP transport, it must have reference counter 2. */ if (pj_atomic_get(tcp->ref_cnt) != 2) - return -16; + return -16; /* Decrease the reference. */ pjsip_transport_dec_ref(tcp); @@ -105,11 +104,11 @@ static pj_status_t multi_listener_test(pjsip_tpfactory *factory[], /* Test basic transport attributes */ status = generic_transport_test(tcp); if (status != PJ_SUCCESS) - return status; + return status; /* Check again that reference counter is 1. */ if (pj_atomic_get(tcp->ref_cnt) != 1) - return -17; + return -17; /* Acquire transport test with selector. */ pj_bzero(&tp_sel, sizeof(tp_sel)); @@ -117,31 +116,31 @@ static pj_status_t multi_listener_test(pjsip_tpfactory *factory[], tp_sel.u.listener = factory[num_factory/2]; pj_sockaddr_in_init(&rem_addr, pj_cstr(&s, "1.1.1.1"), 80); status = pjsip_endpt_acquire_transport(endpt, PJSIP_TRANSPORT_TCP, - &rem_addr, sizeof(rem_addr), - &tp_sel, &tcp); + &rem_addr, sizeof(rem_addr), + &tp_sel, &tcp); if (status != PJ_SUCCESS) { - app_perror(" Error: unable to acquire TCP transport", status); - return -18; + app_perror(" Error: unable to acquire TCP transport", status); + return -18; } /* The transport should have the same factory set on the selector. */ if (tcp->factory != factory[num_factory/2]) - return -19; + return -19; /* The transport should be newly created. */ for (i = 0; i < ntp; ++i) { - if (tp[i] == tcp) { - break; - } + if (tp[i] == tcp) { + break; + } } if (i != ntp) - return -20; + return -20; tp[ntp++] = tcp; for (i = 0; iref_cnt) != 1) - return -21; + if (pj_atomic_get(tp[i]->ref_cnt) != 1) + return -21; } *num_tp = ntp; @@ -167,80 +166,80 @@ int transport_tcp_test(void) status = multi_listener_test(tpfactory, num_listener, tcp, &num_tp); if (status != PJ_SUCCESS) - return status; + return status; /* Get the last listener address */ status = pj_sockaddr_in_init(&rem_addr, &tpfactory[0]->addr_name.host, - (pj_uint16_t)tpfactory[0]->addr_name.port); + (pj_uint16_t)tpfactory[0]->addr_name.port); pj_ansi_sprintf(url, "sip:alice@%s:%d;transport=tcp", - pj_inet_ntop2(pj_AF_INET(), &rem_addr.sin_addr, addr, - sizeof(addr)), - pj_ntohs(rem_addr.sin_port)); + pj_inet_ntop2(pj_AF_INET(), &rem_addr.sin_addr, addr, + sizeof(addr)), + pj_ntohs(rem_addr.sin_port)); /* Load test */ if (transport_load_test(url) != 0) - return -60; + return -60; /* Basic transport's send/receive loopback test. */ for (i=0; iref_cnt) != 1) - return -80; + if (pj_atomic_get(tcp[i]->ref_cnt) != 1) + return -80; } for (i = 0; i < num_tp; ++i) { - /* Destroy this transport. */ - pjsip_transport_dec_ref(tcp[i]); + /* Destroy this transport. */ + pjsip_transport_dec_ref(tcp[i]); - /* Force destroy this transport. */ - status = pjsip_transport_destroy(tcp[i]); - if (status != PJ_SUCCESS) - return -90; + /* Force destroy this transport. */ + status = pjsip_transport_destroy(tcp[i]); + if (status != PJ_SUCCESS) + return -90; } for (i = 0; i < num_listener; ++i) { - /* Unregister factory */ - status = pjsip_tpmgr_unregister_tpfactory(pjsip_endpt_get_tpmgr(endpt), - tpfactory[i]); - if (status != PJ_SUCCESS) - return -95; + /* Unregister factory */ + status = pjsip_tpmgr_unregister_tpfactory(pjsip_endpt_get_tpmgr(endpt), + tpfactory[i]); + if (status != PJ_SUCCESS) + return -95; } /* Flush events. */ @@ -250,9 +249,9 @@ int transport_tcp_test(void) /* Done */ return 0; } -#else /* PJ_HAS_TCP */ +#else /* PJ_HAS_TCP */ int transport_tcp_test(void) { return 0; } -#endif /* PJ_HAS_TCP */ +#endif /* PJ_HAS_TCP */ diff --git a/pjsip/src/test/transport_test.c b/pjsip/src/test/transport_test.c index c429cc7ca2..766c47a4c2 100644 --- a/pjsip/src/test/transport_test.c +++ b/pjsip/src/test/transport_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,34 +34,34 @@ int generic_transport_test(pjsip_transport *tp) /* Check that local address name is valid. */ { - pj_in_addr addr; - - if (pj_inet_pton(pj_AF_INET(), &tp->local_name.host, - &addr) == PJ_SUCCESS) - { - if (addr.s_addr==PJ_INADDR_ANY || addr.s_addr==PJ_INADDR_NONE) { - PJ_LOG(3,(THIS_FILE, " Error: invalid address name")); - return -420; - } - } else { - /* It's okay. local_name.host may be a hostname instead of - * IP address. - */ - } + pj_in_addr addr; + + if (pj_inet_pton(pj_AF_INET(), &tp->local_name.host, + &addr) == PJ_SUCCESS) + { + if (addr.s_addr==PJ_INADDR_ANY || addr.s_addr==PJ_INADDR_NONE) { + PJ_LOG(3,(THIS_FILE, " Error: invalid address name")); + return -420; + } + } else { + /* It's okay. local_name.host may be a hostname instead of + * IP address. + */ + } } /* Check that port is valid. */ if (tp->local_name.port <= 0) { - return -430; + return -430; } /* Check length of address (for now we only check against sockaddr_in). */ if (tp->addr_len != sizeof(pj_sockaddr_in)) - return -440; + return -440; /* Check type. */ if (tp->key.type == PJSIP_TRANSPORT_UNSPECIFIED) - return -450; + return -450; /* That's it. */ return PJ_SUCCESS; @@ -82,7 +81,7 @@ int generic_transport_test(pjsip_transport *tp) #define CONTACT_HDR "Bob " #define CALL_ID_HDR "SendRecv-Test" #define CSEQ_VALUE 100 -#define BODY "Hello World!" +#define BODY "Hello World!" static pj_bool_t my_on_rx_request(pjsip_rx_data *rdata); static pj_bool_t my_on_rx_response(pjsip_rx_data *rdata); @@ -98,17 +97,17 @@ static pj_timestamp my_send_time, my_recv_time; /* Module to receive messages for this test. */ static pjsip_module my_module = { - NULL, NULL, /* prev and next */ - { "Transport-Test", 14}, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_TSX_LAYER-1, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &my_on_rx_request, /* on_rx_request() */ - &my_on_rx_response, /* on_rx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev and next */ + { "Transport-Test", 14}, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_TSX_LAYER-1, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &my_on_rx_request, /* on_rx_request() */ + &my_on_rx_response, /* on_rx_response() */ + NULL, /* on_tsx_state() */ }; @@ -116,30 +115,30 @@ static pj_bool_t my_on_rx_request(pjsip_rx_data *rdata) { /* Check that this is our request. */ if (pj_strcmp2(&rdata->msg_info.cid->id, CALL_ID_HDR) == 0) { - /* It is! */ - /* Send response. */ - pjsip_tx_data *tdata; - pjsip_response_addr res_addr; - pj_status_t status; - - status = pjsip_endpt_create_response( endpt, rdata, 200, NULL, &tdata); - if (status != PJ_SUCCESS) { - recv_status = status; - return PJ_TRUE; - } - status = pjsip_get_response_addr( tdata->pool, rdata, &res_addr); - if (status != PJ_SUCCESS) { - recv_status = status; - pjsip_tx_data_dec_ref(tdata); - return PJ_TRUE; - } - status = pjsip_endpt_send_response( endpt, &res_addr, tdata, NULL, NULL); - if (status != PJ_SUCCESS) { - recv_status = status; - pjsip_tx_data_dec_ref(tdata); - return PJ_TRUE; - } - return PJ_TRUE; + /* It is! */ + /* Send response. */ + pjsip_tx_data *tdata; + pjsip_response_addr res_addr; + pj_status_t status; + + status = pjsip_endpt_create_response( endpt, rdata, 200, NULL, &tdata); + if (status != PJ_SUCCESS) { + recv_status = status; + return PJ_TRUE; + } + status = pjsip_get_response_addr( tdata->pool, rdata, &res_addr); + if (status != PJ_SUCCESS) { + recv_status = status; + pjsip_tx_data_dec_ref(tdata); + return PJ_TRUE; + } + status = pjsip_endpt_send_response( endpt, &res_addr, tdata, NULL, NULL); + if (status != PJ_SUCCESS) { + recv_status = status; + pjsip_tx_data_dec_ref(tdata); + return PJ_TRUE; + } + return PJ_TRUE; } /* Not ours. */ @@ -149,24 +148,24 @@ static pj_bool_t my_on_rx_request(pjsip_rx_data *rdata) static pj_bool_t my_on_rx_response(pjsip_rx_data *rdata) { if (pj_strcmp2(&rdata->msg_info.cid->id, CALL_ID_HDR) == 0) { - pj_get_timestamp(&my_recv_time); - recv_status = PJ_SUCCESS; - return PJ_TRUE; + pj_get_timestamp(&my_recv_time); + recv_status = PJ_SUCCESS; + return PJ_TRUE; } return PJ_FALSE; } /* Transport callback. */ static void send_msg_callback(pjsip_send_state *stateless_data, - pj_ssize_t sent, pj_bool_t *cont) + pj_ssize_t sent, pj_bool_t *cont) { PJ_UNUSED_ARG(stateless_data); if (sent < 1) { - /* Obtain the error code. */ - send_status = (int)-sent; + /* Obtain the error code. */ + send_status = (int)-sent; } else { - send_status = PJ_SUCCESS; + send_status = PJ_SUCCESS; } /* Don't want to continue. */ @@ -176,9 +175,9 @@ static void send_msg_callback(pjsip_send_state *stateless_data, /* Test that we receive loopback message. */ int transport_send_recv_test( pjsip_transport_type_e tp_type, - pjsip_transport *ref_tp, - char *target_url, - int *p_usec_rtt) + pjsip_transport *ref_tp, + char *target_url, + int *p_usec_rtt) { pj_bool_t msg_log_enabled; pj_status_t status; @@ -194,11 +193,11 @@ int transport_send_recv_test( pjsip_transport_type_e tp_type, /* Register out test module to receive the message (if necessary). */ if (my_module.id == -1) { - status = pjsip_endpt_register_module( endpt, &my_module ); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to register module", status); - return -500; - } + status = pjsip_endpt_register_module( endpt, &my_module ); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to register module", status); + return -500; + } } /* Disable message logging. */ @@ -214,11 +213,11 @@ int transport_send_recv_test( pjsip_transport_type_e tp_type, pjsip_method_set(&method, PJSIP_OPTIONS_METHOD); status = pjsip_endpt_create_request( endpt, &method, &target, &from, &to, - &contact, &call_id, CSEQ_VALUE, - &body, &tdata ); + &contact, &call_id, CSEQ_VALUE, + &body, &tdata ); if (status != PJ_SUCCESS) { - app_perror(" error: unable to create request", status); - return -510; + app_perror(" error: unable to create request", status); + return -510; } /* Reset statuses */ @@ -229,13 +228,13 @@ int transport_send_recv_test( pjsip_transport_type_e tp_type, /* Send the message (statelessly). */ PJ_LOG(5,(THIS_FILE, "Sending request to %.*s", - (int)target.slen, target.ptr)); + (int)target.slen, target.ptr)); status = pjsip_endpt_send_request_stateless( endpt, tdata, NULL, - &send_msg_callback); + &send_msg_callback); if (status != PJ_SUCCESS) { - /* Immediate error! */ - pjsip_tx_data_dec_ref(tdata); - send_status = status; + /* Immediate error! */ + pjsip_tx_data_dec_ref(tdata); + send_status = status; } /* Set the timeout (2 seconds from now) */ @@ -244,44 +243,44 @@ int transport_send_recv_test( pjsip_transport_type_e tp_type, /* Loop handling events until we get status */ do { - pj_time_val now; - pj_time_val poll_interval = { 0, 10 }; - - pj_gettimeofday(&now); - if (PJ_TIME_VAL_GTE(now, timeout)) { - PJ_LOG(3,(THIS_FILE, " error: timeout in send/recv test")); - status = -540; - goto on_return; - } - - if (send_status!=NO_STATUS && send_status!=PJ_SUCCESS) { - app_perror(" error sending message", send_status); - status = -550; - goto on_return; - } - - if (recv_status!=NO_STATUS && recv_status!=PJ_SUCCESS) { - app_perror(" error receiving message", recv_status); - status = -560; - goto on_return; - } - - if (send_status!=NO_STATUS && recv_status!=NO_STATUS) { - /* Success! */ - break; - } - - pjsip_endpt_handle_events(endpt, &poll_interval); + pj_time_val now; + pj_time_val poll_interval = { 0, 10 }; + + pj_gettimeofday(&now); + if (PJ_TIME_VAL_GTE(now, timeout)) { + PJ_LOG(3,(THIS_FILE, " error: timeout in send/recv test")); + status = -540; + goto on_return; + } + + if (send_status!=NO_STATUS && send_status!=PJ_SUCCESS) { + app_perror(" error sending message", send_status); + status = -550; + goto on_return; + } + + if (recv_status!=NO_STATUS && recv_status!=PJ_SUCCESS) { + app_perror(" error receiving message", recv_status); + status = -560; + goto on_return; + } + + if (send_status!=NO_STATUS && recv_status!=NO_STATUS) { + /* Success! */ + break; + } + + pjsip_endpt_handle_events(endpt, &poll_interval); } while (1); if (status == PJ_SUCCESS) { - unsigned usec_rt; - usec_rt = pj_elapsed_usec(&my_send_time, &my_recv_time); + unsigned usec_rt; + usec_rt = pj_elapsed_usec(&my_send_time, &my_recv_time); - PJ_LOG(3,(THIS_FILE, " round-trip = %d usec", usec_rt)); + PJ_LOG(3,(THIS_FILE, " round-trip = %d usec", usec_rt)); - *p_usec_rtt = usec_rt; + *p_usec_rtt = usec_rt; } /* Restore message logging. */ @@ -310,17 +309,17 @@ static pj_bool_t rt_on_rx_response(pjsip_rx_data *rdata); static pjsip_module rt_module = { - NULL, NULL, /* prev and next */ - { "Transport-RT-Test", 17}, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_TSX_LAYER-1, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &rt_on_rx_request, /* on_rx_request() */ - &rt_on_rx_response, /* on_rx_response() */ - NULL, /* tsx_handler() */ + NULL, NULL, /* prev and next */ + { "Transport-RT-Test", 17}, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_TSX_LAYER-1, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &rt_on_rx_request, /* on_rx_request() */ + &rt_on_rx_response, /* on_rx_response() */ + NULL, /* tsx_handler() */ }; static struct @@ -335,36 +334,36 @@ static struct pj_mutex_t *mutex; } rt_test_data[16]; -static char rt_target_uri[64]; +static char rt_target_uri[64]; static pj_bool_t rt_stop; static pj_str_t rt_call_id; static pj_bool_t rt_on_rx_request(pjsip_rx_data *rdata) { if (!pj_strncmp(&rdata->msg_info.cid->id, &rt_call_id, rt_call_id.slen)) { - pjsip_tx_data *tdata; - pjsip_response_addr res_addr; - pj_status_t status; - - status = pjsip_endpt_create_response( endpt, rdata, 200, NULL, &tdata); - if (status != PJ_SUCCESS) { - app_perror(" error creating response", status); - return PJ_TRUE; - } - status = pjsip_get_response_addr( tdata->pool, rdata, &res_addr); - if (status != PJ_SUCCESS) { - app_perror(" error in get response address", status); - pjsip_tx_data_dec_ref(tdata); - return PJ_TRUE; - } - status = pjsip_endpt_send_response( endpt, &res_addr, tdata, NULL, NULL); - if (status != PJ_SUCCESS) { - app_perror(" error sending response", status); - pjsip_tx_data_dec_ref(tdata); - return PJ_TRUE; - } - return PJ_TRUE; - + pjsip_tx_data *tdata; + pjsip_response_addr res_addr; + pj_status_t status; + + status = pjsip_endpt_create_response( endpt, rdata, 200, NULL, &tdata); + if (status != PJ_SUCCESS) { + app_perror(" error creating response", status); + return PJ_TRUE; + } + status = pjsip_get_response_addr( tdata->pool, rdata, &res_addr); + if (status != PJ_SUCCESS) { + app_perror(" error in get response address", status); + pjsip_tx_data_dec_ref(tdata); + return PJ_TRUE; + } + status = pjsip_endpt_send_response( endpt, &res_addr, tdata, NULL, NULL); + if (status != PJ_SUCCESS) { + app_perror(" error sending response", status); + pjsip_tx_data_dec_ref(tdata); + return PJ_TRUE; + } + return PJ_TRUE; + } return PJ_FALSE; } @@ -386,13 +385,13 @@ static pj_status_t rt_send_request(int thread_id) call_id = rt_test_data[thread_id].call_id; status = pjsip_endpt_create_request( endpt, &pjsip_options_method, - &target, &from, &to, - &contact, &call_id, -1, - NULL, &tdata ); + &target, &from, &to, + &contact, &call_id, -1, + NULL, &tdata ); if (status != PJ_SUCCESS) { - app_perror(" error: unable to create request", status); - pj_mutex_unlock(rt_test_data[thread_id].mutex); - return -610; + app_perror(" error: unable to create request", status); + pj_mutex_unlock(rt_test_data[thread_id].mutex); + return -610; } /* Start time. */ @@ -401,11 +400,11 @@ static pj_status_t rt_send_request(int thread_id) /* Send the message (statelessly). */ status = pjsip_endpt_send_request_stateless( endpt, tdata, NULL, NULL); if (status != PJ_SUCCESS) { - /* Immediate error! */ - app_perror(" error: send request", status); - pjsip_tx_data_dec_ref(tdata); - pj_mutex_unlock(rt_test_data[thread_id].mutex); - return -620; + /* Immediate error! */ + app_perror(" error: send request", status); + pjsip_tx_data_dec_ref(tdata); + pj_mutex_unlock(rt_test_data[thread_id].mutex); + return -620; } /* Update counter. */ @@ -413,12 +412,12 @@ static pj_status_t rt_send_request(int thread_id) /* Set timeout timer. */ if (rt_test_data[thread_id].timeout_timer.user_data != NULL) { - pjsip_endpt_cancel_timer(endpt, &rt_test_data[thread_id].timeout_timer); + pjsip_endpt_cancel_timer(endpt, &rt_test_data[thread_id].timeout_timer); } timeout_delay.sec = 100; timeout_delay.msec = 0; rt_test_data[thread_id].timeout_timer.user_data = (void*)(pj_ssize_t)1; pjsip_endpt_schedule_timer(endpt, &rt_test_data[thread_id].timeout_timer, - &timeout_delay); + &timeout_delay); pj_mutex_unlock(rt_test_data[thread_id].mutex); return PJ_SUCCESS; @@ -427,39 +426,39 @@ static pj_status_t rt_send_request(int thread_id) static pj_bool_t rt_on_rx_response(pjsip_rx_data *rdata) { if (!pj_strncmp(&rdata->msg_info.cid->id, &rt_call_id, rt_call_id.slen)) { - char *pos = pj_strchr(&rdata->msg_info.cid->id, '/')+1; - int thread_id = (*pos - '0'); - pj_timestamp recv_time; + char *pos = pj_strchr(&rdata->msg_info.cid->id, '/')+1; + int thread_id = (*pos - '0'); + pj_timestamp recv_time; - pj_mutex_lock(rt_test_data[thread_id].mutex); + pj_mutex_lock(rt_test_data[thread_id].mutex); - /* Stop timer. */ - pjsip_endpt_cancel_timer(endpt, &rt_test_data[thread_id].timeout_timer); + /* Stop timer. */ + pjsip_endpt_cancel_timer(endpt, &rt_test_data[thread_id].timeout_timer); - /* Update counter and end-time. */ - rt_test_data[thread_id].recv_response_count++; - pj_get_timestamp(&recv_time); + /* Update counter and end-time. */ + rt_test_data[thread_id].recv_response_count++; + pj_get_timestamp(&recv_time); - pj_sub_timestamp(&recv_time, &rt_test_data[thread_id].send_time); - pj_add_timestamp(&rt_test_data[thread_id].total_rt_time, &recv_time); + pj_sub_timestamp(&recv_time, &rt_test_data[thread_id].send_time); + pj_add_timestamp(&rt_test_data[thread_id].total_rt_time, &recv_time); - if (!rt_stop) { - pj_time_val tx_delay = { 0, 0 }; - pj_assert(rt_test_data[thread_id].tx_timer.user_data == NULL); - rt_test_data[thread_id].tx_timer.user_data = (void*)(pj_ssize_t)1; - pjsip_endpt_schedule_timer(endpt, &rt_test_data[thread_id].tx_timer, - &tx_delay); - } + if (!rt_stop) { + pj_time_val tx_delay = { 0, 0 }; + pj_assert(rt_test_data[thread_id].tx_timer.user_data == NULL); + rt_test_data[thread_id].tx_timer.user_data = (void*)(pj_ssize_t)1; + pjsip_endpt_schedule_timer(endpt, &rt_test_data[thread_id].tx_timer, + &tx_delay); + } - pj_mutex_unlock(rt_test_data[thread_id].mutex); + pj_mutex_unlock(rt_test_data[thread_id].mutex); - return PJ_TRUE; + return PJ_TRUE; } return PJ_FALSE; } static void rt_timeout_timer( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry ) + struct pj_timer_entry *entry ) { pj_mutex_lock(rt_test_data[entry->id].mutex); @@ -468,17 +467,17 @@ static void rt_timeout_timer( pj_timer_heap_t *timer_heap, rt_test_data[entry->id].timeout_timer.user_data = NULL; if (rt_test_data[entry->id].tx_timer.user_data == NULL) { - pj_time_val delay = { 0, 0 }; - rt_test_data[entry->id].tx_timer.user_data = (void*)(pj_ssize_t)1; - pjsip_endpt_schedule_timer(endpt, &rt_test_data[entry->id].tx_timer, - &delay); + pj_time_val delay = { 0, 0 }; + rt_test_data[entry->id].tx_timer.user_data = (void*)(pj_ssize_t)1; + pjsip_endpt_schedule_timer(endpt, &rt_test_data[entry->id].tx_timer, + &delay); } pj_mutex_unlock(rt_test_data[entry->id].mutex); } static void rt_tx_timer( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry ) + struct pj_timer_entry *entry ) { pj_mutex_lock(rt_test_data[entry->id].mutex); @@ -502,20 +501,20 @@ static int rt_worker_thread(void *arg) pj_thread_sleep(10); while (!rt_stop) { - pjsip_endpt_handle_events(endpt, &poll_delay); + pjsip_endpt_handle_events(endpt, &poll_delay); } /* Exhaust responses. */ for (i=0; i<100; ++i) - pjsip_endpt_handle_events(endpt, &poll_delay); + pjsip_endpt_handle_events(endpt, &poll_delay); return 0; } int transport_rt_test( pjsip_transport_type_e tp_type, - pjsip_transport *ref_tp, - char *target_url, - int *lost) + pjsip_transport *ref_tp, + char *target_url, + int *lost) { enum { THREADS = 4, INTERVAL = 10 }; int i; @@ -532,26 +531,26 @@ int transport_rt_test( pjsip_transport_type_e tp_type, PJ_UNUSED_ARG(ref_tp); PJ_LOG(3,(THIS_FILE, " multithreaded round-trip test (%d threads)...", - THREADS)); + THREADS)); PJ_LOG(3,(THIS_FILE, " this will take approx %d seconds, please wait..", - INTERVAL)); + INTERVAL)); /* Make sure msg logger is disabled. */ logger_enabled = msg_logger_set_enabled(0); /* Register module (if not yet registered) */ if (rt_module.id == -1) { - status = pjsip_endpt_register_module( endpt, &rt_module ); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to register module", status); - return -600; - } + status = pjsip_endpt_register_module( endpt, &rt_module ); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to register module", status); + return -600; + } } /* Create pool for this test. */ pool = pjsip_endpt_create_pool(endpt, NULL, 4000, 4000); if (!pool) - return -610; + return -610; /* Initialize static test data. */ pj_ansi_strcpy(rt_target_uri, target_url); @@ -560,49 +559,49 @@ int transport_rt_test( pjsip_transport_type_e tp_type, /* Initialize thread data. */ for (i=0; imsg_info.cseq->cseq != mod_load.next_seq) { - PJ_LOG(1,("THIS_FILE", " err: expecting cseq %u, got %u", - mod_load.next_seq, rdata->msg_info.cseq->cseq)); - mod_load.err = PJ_TRUE; - mod_load.next_seq = rdata->msg_info.cseq->cseq + 1; + PJ_LOG(1,("THIS_FILE", " err: expecting cseq %u, got %u", + mod_load.next_seq, rdata->msg_info.cseq->cseq)); + mod_load.err = PJ_TRUE; + mod_load.next_seq = rdata->msg_info.cseq->cseq + 1; } else - mod_load.next_seq++; + mod_load.next_seq++; return PJ_TRUE; } @@ -705,66 +704,66 @@ int transport_load_test(char *target_url) /* exhaust packets */ do { - pj_time_val delay = {1, 0}; - i = 0; - pjsip_endpt_handle_events2(endpt, &delay, &i); + pj_time_val delay = {1, 0}; + i = 0; + pjsip_endpt_handle_events2(endpt, &delay, &i); } while (i != 0); PJ_LOG(3,(THIS_FILE, " transport load test...")); if (mod_load.mod.id == -1) { - status = pjsip_endpt_register_module( endpt, &mod_load.mod); - if (status != PJ_SUCCESS) { - app_perror("error registering module", status); - return -1; - } + status = pjsip_endpt_register_module( endpt, &mod_load.mod); + if (status != PJ_SUCCESS) { + app_perror("error registering module", status); + return -1; + } } mod_load.err = PJ_FALSE; mod_load.next_seq = 0; for (i=0; i"); - call_id = pj_str("thecallid"); - status = pjsip_endpt_create_request(endpt, &pjsip_invite_method, - &target, &from, - &target, &from, &call_id, - i, NULL, &tdata ); - if (status != PJ_SUCCESS) { - app_perror("error creating request", status); - goto on_return; - } - - status = pjsip_endpt_send_request_stateless(endpt, tdata, NULL, NULL); - if (status != PJ_SUCCESS) { - app_perror("error sending request", status); - goto on_return; - } + pj_str_t target, from, call_id; + pjsip_tx_data *tdata; + + target = pj_str(target_url); + from = pj_str(""); + call_id = pj_str("thecallid"); + status = pjsip_endpt_create_request(endpt, &pjsip_invite_method, + &target, &from, + &target, &from, &call_id, + i, NULL, &tdata ); + if (status != PJ_SUCCESS) { + app_perror("error creating request", status); + goto on_return; + } + + status = pjsip_endpt_send_request_stateless(endpt, tdata, NULL, NULL); + if (status != PJ_SUCCESS) { + app_perror("error sending request", status); + goto on_return; + } } do { - pj_time_val delay = {1, 0}; - i = 0; - pjsip_endpt_handle_events2(endpt, &delay, &i); + pj_time_val delay = {1, 0}; + i = 0; + pjsip_endpt_handle_events2(endpt, &delay, &i); } while (i != 0); if (mod_load.next_seq != COUNT) { - PJ_LOG(1,("THIS_FILE", " err: expecting %u msg, got only %u", - COUNT, mod_load.next_seq)); - status = -2; - goto on_return; + PJ_LOG(1,("THIS_FILE", " err: expecting %u msg, got only %u", + COUNT, mod_load.next_seq)); + status = -2; + goto on_return; } on_return: if (mod_load.mod.id != -1) { - pjsip_endpt_unregister_module( endpt, &mod_load.mod); - mod_load.mod.id = -1; + pjsip_endpt_unregister_module( endpt, &mod_load.mod); + mod_load.mod.id = -1; } if (status != PJ_SUCCESS || mod_load.err) { - return -2; + return -2; } PJ_LOG(3,(THIS_FILE, " success")); return 0; diff --git a/pjsip/src/test/transport_udp_test.c b/pjsip/src/test/transport_udp_test.c index 9fa4bcca22..2c063d4846 100644 --- a/pjsip/src/test/transport_udp_test.c +++ b/pjsip/src/test/transport_udp_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -35,55 +34,55 @@ static pj_status_t multi_transport_test(pjsip_transport *tp[], unsigned num_tp) for (;iref_cnt) != 1) - return -120; + /* UDP transport must have initial reference counter set to 1. */ + if (pj_atomic_get(udp_tp->ref_cnt) != 1) + return -120; - /* Test basic transport attributes */ - status = generic_transport_test(udp_tp); - if (status != PJ_SUCCESS) - return status; + /* Test basic transport attributes */ + status = generic_transport_test(udp_tp); + if (status != PJ_SUCCESS) + return status; - tp[i] = udp_tp; + tp[i] = udp_tp; } for (i = 0; i < num_tp; ++i) { - udp_tp = tp[i]; - if (pj_atomic_get(udp_tp->ref_cnt) != 1) - return -130; + udp_tp = tp[i]; + if (pj_atomic_get(udp_tp->ref_cnt) != 1) + return -130; } /* Acquire transport test without selector. */ pj_sockaddr_in_init(&rem_addr, pj_cstr(&s, "1.1.1.1"), 80); status = pjsip_endpt_acquire_transport(endpt, PJSIP_TRANSPORT_UDP, - &rem_addr, sizeof(rem_addr), - NULL, &udp_tp); + &rem_addr, sizeof(rem_addr), + NULL, &udp_tp); if (status != PJ_SUCCESS) - return -140; + return -140; for (i = 0; i < num_tp; ++i) { - if (udp_tp == tp[i]) { - break; - } + if (udp_tp == tp[i]) { + break; + } } if (i == num_tp) - return -150; + return -150; pjsip_transport_dec_ref(udp_tp); if (pj_atomic_get(udp_tp->ref_cnt) != 1) - return -160; + return -160; /* Acquire transport test with selector. */ pj_bzero(&tp_sel, sizeof(tp_sel)); @@ -91,18 +90,18 @@ static pj_status_t multi_transport_test(pjsip_transport *tp[], unsigned num_tp) tp_sel.u.transport = tp[num_tp-1]; pj_sockaddr_in_init(&rem_addr, pj_cstr(&s, "1.1.1.1"), 80); status = pjsip_endpt_acquire_transport(endpt, PJSIP_TRANSPORT_UDP, - &rem_addr, sizeof(rem_addr), - &tp_sel, &udp_tp); + &rem_addr, sizeof(rem_addr), + &tp_sel, &udp_tp); if (status != PJ_SUCCESS) - return -170; + return -170; if (udp_tp != tp[num_tp-1]) - return -180; + return -180; pjsip_transport_dec_ref(udp_tp); if (pj_atomic_get(udp_tp->ref_cnt) != 1) - return -190; + return -190; return PJ_SUCCESS; } @@ -123,50 +122,50 @@ int transport_udp_test(void) status = multi_transport_test(&tp[0], NUM_TP); if (status != PJ_SUCCESS) - return status; + return status; /* Basic transport's send/receive loopback test. */ pj_sockaddr_in_init(&rem_addr, pj_cstr(&s, "127.0.0.1"), TEST_UDP_PORT); for (i=0; iref_cnt) != 1) - return -80; - - /* Destroy this transport. */ - pjsip_transport_dec_ref(udp_tp); - status = pjsip_transport_destroy(udp_tp); - if (status != PJ_SUCCESS) - return -90; + if (pj_atomic_get(udp_tp->ref_cnt) != 1) + return -80; + + /* Destroy this transport. */ + pjsip_transport_dec_ref(udp_tp); + status = pjsip_transport_destroy(udp_tp); + if (status != PJ_SUCCESS) + return -90; } /* Flush events. */ diff --git a/pjsip/src/test/tsx_basic_test.c b/pjsip/src/test/tsx_basic_test.c index e98f4d3489..8c1317eaeb 100644 --- a/pjsip/src/test/tsx_basic_test.c +++ b/pjsip/src/test/tsx_basic_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -42,31 +41,31 @@ static int tsx_layer_test(void) from = pj_str(FROM_URI); status = pjsip_endpt_create_request(endpt, &pjsip_invite_method, &target, - &from, &target, NULL, NULL, -1, NULL, - &tdata); + &from, &target, NULL, NULL, -1, NULL, + &tdata); if (status != PJ_SUCCESS) { - app_perror(" error: unable to create request", status); - return -110; + app_perror(" error: unable to create request", status); + return -110; } status = pjsip_tsx_create_uac(NULL, tdata, &tsx); if (status != PJ_SUCCESS) { - app_perror(" error: unable to create transaction", status); - return -120; + app_perror(" error: unable to create transaction", status); + return -120; } pj_strdup(tdata->pool, &tsx_key, &tsx->transaction_key); found = pjsip_tsx_layer_find_tsx(&tsx_key, PJ_FALSE); if (found != tsx) { - return -130; + return -130; } pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED); flush_events(500); if (pjsip_tx_data_dec_ref(tdata) != PJSIP_EBUFDESTROYED) { - return -140; + return -140; } return 0; @@ -87,18 +86,18 @@ static int double_terminate(void) /* Create request. */ status = pjsip_endpt_create_request(endpt, &pjsip_invite_method, &target, - &from, &target, NULL, NULL, -1, NULL, - &tdata); + &from, &target, NULL, NULL, -1, NULL, + &tdata); if (status != PJ_SUCCESS) { - app_perror(" error: unable to create request", status); - return -10; + app_perror(" error: unable to create request", status); + return -10; } /* Create transaction. */ status = pjsip_tsx_create_uac(NULL, tdata, &tsx); if (status != PJ_SUCCESS) { - app_perror(" error: unable to create transaction", status); - return -20; + app_perror(" error: unable to create transaction", status); + return -20; } /* Save transaction key for later. */ @@ -113,24 +112,24 @@ static int double_terminate(void) /* Terminate transaction. */ status = pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED); if (status != PJ_SUCCESS) { - app_perror(" error: unable to terminate transaction", status); - return -30; + app_perror(" error: unable to terminate transaction", status); + return -30; } tsx = pjsip_tsx_layer_find_tsx(&tsx_key, PJ_TRUE); if (tsx) { - /* Terminate transaction again. */ - pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to terminate transaction", status); - return -40; - } - pj_grp_lock_release(tsx->grp_lock); + /* Terminate transaction again. */ + pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to terminate transaction", status); + return -40; + } + pj_grp_lock_release(tsx->grp_lock); } flush_events(500); if (pjsip_tx_data_dec_ref(tdata) != PJSIP_EBUFDESTROYED) { - return -50; + return -50; } return PJ_SUCCESS; @@ -141,17 +140,17 @@ int tsx_basic_test(struct tsx_test_param *param) int status; pj_ansi_sprintf(TARGET_URI, "sip:bob@127.0.0.1:%d;transport=%s", - param->port, param->tp_type); + param->port, param->tp_type); pj_ansi_sprintf(FROM_URI, "sip:alice@127.0.0.1:%d;transport=%s", - param->port, param->tp_type); + param->port, param->tp_type); status = tsx_layer_test(); if (status != 0) - return status; + return status; status = double_terminate(); if (status != 0) - return status; + return status; return 0; } @@ -171,7 +170,7 @@ static void save_tsx_test_state(struct tsx_test_state *st) static pj_status_t check_tsx_test_state(struct tsx_test_state *st) { if (caching_pool.used_count > st->pool_cnt) - return -1; + return -1; return 0; } @@ -184,47 +183,47 @@ static void destroy_endpt() static pj_status_t init_endpt() { - pj_str_t ns = { "10.187.27.172", 13}; /* just a random, unreachable IP */ + pj_str_t ns = { "10.187.27.172", 13}; /* just a random, unreachable IP */ pj_dns_resolver *resolver; pj_status_t rc; rc = pjsip_endpt_create(&caching_pool.factory, "endpt", &endpt); if (rc != PJ_SUCCESS) { - app_perror("pjsip_endpt_create", rc); - return rc; + app_perror("pjsip_endpt_create", rc); + return rc; } /* Start transaction layer module. */ rc = pjsip_tsx_layer_init_module(endpt); if (rc != PJ_SUCCESS) { - app_perror("tsx_layer_init", rc); - return rc; + app_perror("tsx_layer_init", rc); + return rc; } rc = pjsip_udp_transport_start(endpt, NULL, NULL, 1, NULL); if (rc != PJ_SUCCESS) { - app_perror("udp init", rc); - return rc; + app_perror("udp init", rc); + return rc; } rc = pjsip_tcp_transport_start(endpt, NULL, 1, NULL); if (rc != PJ_SUCCESS) { - app_perror("tcp init", rc); - return rc; + app_perror("tcp init", rc); + return rc; } rc = pjsip_endpt_create_resolver(endpt, &resolver); if (rc != PJ_SUCCESS) { - app_perror("create resolver", rc); - return rc; + app_perror("create resolver", rc); + return rc; } pj_dns_resolver_set_ns(resolver, 1, &ns, NULL); rc = pjsip_endpt_set_resolver(endpt, resolver); if (rc != PJ_SUCCESS) { - app_perror("set resolver", rc); - return rc; + app_perror("set resolver", rc); + return rc; } return PJ_SUCCESS; @@ -242,11 +241,11 @@ static int tsx_create_and_send_req(void *arg) NULL, NULL, -1, NULL, &tdata); if (status != PJ_SUCCESS) - return status; + return status; status = pjsip_endpt_send_request(endpt, tdata, -1, NULL, NULL); if (status != PJ_SUCCESS) - return status; + return status; return PJ_SUCCESS; } @@ -256,41 +255,41 @@ int tsx_destroy_test() struct tsx_test_state state; struct test_desc { - const char *title; - int (*func)(void*); - void *arg; - int sleep_before_unload; - int sleep_after_unload; + const char *title; + int (*func)(void*); + void *arg; + int sleep_before_unload; + int sleep_after_unload; } test_entries[] = { - { - "normal unable to resolve", - &tsx_create_and_send_req, - "sip:user@somehost", - 20000, - 1 - }, - { - "resolve and destroy, wait", - &tsx_create_and_send_req, - "sip:user@somehost", - 1, - 20000 - }, - { - "tcp connect and destroy", - &tsx_create_and_send_req, - "sip:user@10.125.36.63:58517;transport=tcp", - 60000, - 1000 - }, - { - "tcp connect and destroy 2", - &tsx_create_and_send_req, - "sip:user@10.125.36.63:58517;transport=tcp", - 1, - 60000 - }, + { + "normal unable to resolve", + &tsx_create_and_send_req, + "sip:user@somehost", + 20000, + 1 + }, + { + "resolve and destroy, wait", + &tsx_create_and_send_req, + "sip:user@somehost", + 1, + 20000 + }, + { + "tcp connect and destroy", + &tsx_create_and_send_req, + "sip:user@10.125.36.63:58517;transport=tcp", + 60000, + 1000 + }, + { + "tcp connect and destroy 2", + &tsx_create_and_send_req, + "sip:user@10.125.36.63:58517;transport=tcp", + 1, + 60000 + }, }; int rc; unsigned i; @@ -300,38 +299,38 @@ int tsx_destroy_test() destroy_endpt(); for (i=0; ititle)); - - pj_log_add_indent(INDENT); - save_tsx_test_state(&state); - - rc = init_endpt(); - if (rc != PJ_SUCCESS) { - pj_log_add_indent(-INDENT*2); - return -10; - } - - rc = td->func(td->arg); - if (rc != PJ_SUCCESS) { - pj_log_add_indent(-INDENT*2); - return -20; - } - - flush_events(td->sleep_before_unload); - pjsip_tsx_layer_destroy(); - flush_events(td->sleep_after_unload); - destroy_endpt(); - - rc = check_tsx_test_state(&state); - if (rc != PJ_SUCCESS) { - init_endpt(); - pj_log_add_indent(-INDENT*2); - return -30; - } - - pj_log_add_indent(-INDENT); + struct test_desc *td = &test_entries[i]; + + PJ_LOG(3,(THIS_FILE, "%s", td->title)); + + pj_log_add_indent(INDENT); + save_tsx_test_state(&state); + + rc = init_endpt(); + if (rc != PJ_SUCCESS) { + pj_log_add_indent(-INDENT*2); + return -10; + } + + rc = td->func(td->arg); + if (rc != PJ_SUCCESS) { + pj_log_add_indent(-INDENT*2); + return -20; + } + + flush_events(td->sleep_before_unload); + pjsip_tsx_layer_destroy(); + flush_events(td->sleep_after_unload); + destroy_endpt(); + + rc = check_tsx_test_state(&state); + if (rc != PJ_SUCCESS) { + init_endpt(); + pj_log_add_indent(-INDENT*2); + return -30; + } + + pj_log_add_indent(-INDENT); } init_endpt(); diff --git a/pjsip/src/test/tsx_bench.c b/pjsip/src/test/tsx_bench.c index 2282b6a93d..87fb35e9ea 100644 --- a/pjsip/src/test/tsx_bench.c +++ b/pjsip/src/test/tsx_bench.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -42,16 +41,16 @@ static int uac_tsx_bench(unsigned working_set, pj_timestamp *p_elapsed) pj_str_t str_contact = str_from; status = pjsip_endpt_create_request(endpt, &pjsip_invite_method, - &str_target, &str_from, &str_to, - &str_contact, NULL, -1, NULL, - &request); + &str_target, &str_from, &str_to, + &str_contact, NULL, -1, NULL, + &request); if (status != PJ_SUCCESS) { - app_perror(" error: unable to create request", status); - return status; + app_perror(" error: unable to create request", status); + return status; } via = (pjsip_via_hdr*) pjsip_msg_find_hdr(request->msg, PJSIP_H_VIA, - NULL); + NULL); /* Create transaction array */ tsx = (pjsip_transaction**) pj_pool_zalloc(request->pool, working_set * sizeof(pj_pool_t*)); @@ -63,11 +62,11 @@ static int uac_tsx_bench(unsigned working_set, pj_timestamp *p_elapsed) elapsed.u64 = 0; pj_get_timestamp(&t1); for (i=0; ibranch_param.slen = 0; + status = pjsip_tsx_create_uac(&mod_tsx_user, request, &tsx[i]); + if (status != PJ_SUCCESS) + goto on_error; + /* Reset branch param */ + via->branch_param.slen = 0; } pj_get_timestamp(&t2); pj_sub_timestamp(&t2, &t1); @@ -78,15 +77,15 @@ static int uac_tsx_bench(unsigned working_set, pj_timestamp *p_elapsed) on_error: for (i=0; ibranch_param.ptr = branch_buf; - via->branch_param.slen = PJSIP_RFC3261_BRANCH_LEN + - pj_ansi_sprintf(branch_buf+PJSIP_RFC3261_BRANCH_LEN, - "-%d", i); - status = pjsip_tsx_create_uas(&mod_tsx_user, &rdata, &tsx[i]); - if (status != PJ_SUCCESS) - goto on_error; + via->branch_param.ptr = branch_buf; + via->branch_param.slen = PJSIP_RFC3261_BRANCH_LEN + + pj_ansi_sprintf(branch_buf+PJSIP_RFC3261_BRANCH_LEN, + "-%d", i); + status = pjsip_tsx_create_uas(&mod_tsx_user, &rdata, &tsx[i]); + if (status != PJ_SUCCESS) + goto on_error; } pj_get_timestamp(&t2); @@ -181,16 +180,16 @@ static int uas_tsx_bench(unsigned working_set, pj_timestamp *p_elapsed) on_error: for (i=0; ipjsip_tsx_create_uac(), based on the time " - "to create %d simultaneous transactions above.", - WORKING_SET); + "with pjsip_tsx_create_uac(), based on the time " + "to create %d simultaneous transactions above.", + WORKING_SET); report_ival("create-uac-tsx-per-sec", - speed, "tsx/sec", desc); + speed, "tsx/sec", desc); @@ -257,24 +256,24 @@ int tsx_bench(void) */ PJ_LOG(3,(THIS_FILE, " benchmarking UAS transaction creation:")); for (i=0; ipjsip_tsx_create_uas(), based on the time " - "to create %d simultaneous transactions above.", - WORKING_SET); + "with pjsip_tsx_create_uas(), based on the time " + "to create %d simultaneous transactions above.", + WORKING_SET); report_ival("create-uas-tsx-per-sec", - speed, "tsx/sec", desc); + speed, "tsx/sec", desc); return PJ_SUCCESS; } diff --git a/pjsip/src/test/tsx_uac_test.c b/pjsip/src/test/tsx_uac_test.c index 259a792526..ff1e6829e9 100644 --- a/pjsip/src/test/tsx_uac_test.c +++ b/pjsip/src/test/tsx_uac_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,47 +33,47 @@ ** transaction user module can identify which test is being carried out. ** ** TEST1_BRANCH_ID - ** Perform basic retransmission and timeout test. Message receiver will - ** verify that retransmission is received at correct time. + ** Perform basic retransmission and timeout test. Message receiver will + ** verify that retransmission is received at correct time. ** This test verifies the following requirements: - ** - retransmit timer doubles for INVITE - ** - retransmit timer doubles and caps off for non-INVITE - ** - retransmit timer timer is precise - ** - correct timeout and retransmission count + ** - retransmit timer doubles for INVITE + ** - retransmit timer doubles and caps off for non-INVITE + ** - retransmit timer timer is precise + ** - correct timeout and retransmission count ** Requirements not tested: - ** - retransmit timer only starts after resolving has completed. + ** - retransmit timer only starts after resolving has completed. ** ** TEST2_BRANCH_ID - ** Test scenario where resolver is unable to resolve destination host. + ** Test scenario where resolver is unable to resolve destination host. ** ** TEST3_BRANCH_ID - ** Test scenario where transaction is terminated while resolver is still - ** running. + ** Test scenario where transaction is terminated while resolver is still + ** running. ** ** TEST4_BRANCH_ID - ** Test scenario where transport failed after several retransmissions. + ** Test scenario where transport failed after several retransmissions. ** ** TEST5_BRANCH_ID - ** Test scenario where transaction is terminated by user after several - ** retransmissions. + ** Test scenario where transaction is terminated by user after several + ** retransmissions. ** ** TEST6_BRANCH_ID - ** Test successfull non-INVITE transaction. + ** Test successfull non-INVITE transaction. ** It tests the following requirements: - ** - transaction correctly moves to COMPLETED state. - ** - retransmission must cease. - ** - tx_data must be maintained until state is terminated. + ** - transaction correctly moves to COMPLETED state. + ** - retransmission must cease. + ** - tx_data must be maintained until state is terminated. ** ** TEST7_BRANCH_ID - ** Test successfull non-INVITE transaction, with provisional response. + ** Test successfull non-INVITE transaction, with provisional response. ** ** TEST8_BRANCH_ID - ** Test failed INVITE transaction (e.g. ACK must be received) + ** Test failed INVITE transaction (e.g. ACK must be received) ** ** TEST9_BRANCH_ID - ** Test failed INVITE transaction with provisional response. + ** Test failed INVITE transaction with provisional response. ** - ** + ** ***************************************************************************** */ @@ -89,9 +88,9 @@ static char *TEST8_BRANCH_ID = PJSIP_RFC3261_BRANCH_ID "-UAC-Test8"; static char *TEST9_BRANCH_ID = PJSIP_RFC3261_BRANCH_ID "-UAC-Test9"; // An effort to accommodate CPU load spike on some test machines. -#define TEST1_ALLOWED_DIFF 500 //(150) +#define TEST1_ALLOWED_DIFF 500 //(150) #define TEST4_RETRANSMIT_CNT 3 -#define TEST5_RETRANSMIT_CNT 3 +#define TEST5_RETRANSMIT_CNT 3 static char TARGET_URI[128]; static char FROM_URI[128]; @@ -104,37 +103,37 @@ static pj_bool_t msg_receiver_on_rx_request(pjsip_rx_data *rdata); /* UAC transaction user module. */ static pjsip_module tsx_user = { - NULL, NULL, /* prev and next */ - { "Tsx-UAC-User", 12}, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION-1, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - NULL, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request() */ - NULL, /* on_tx_response() */ - &tsx_user_on_tsx_state, /* on_tsx_state() */ + NULL, NULL, /* prev and next */ + { "Tsx-UAC-User", 12}, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION-1, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request() */ + NULL, /* on_tx_response() */ + &tsx_user_on_tsx_state, /* on_tsx_state() */ }; /* Module to receive the loop-backed request. */ static pjsip_module msg_receiver = { - NULL, NULL, /* prev and next */ - { "Msg-Receiver", 12}, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION-1, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &msg_receiver_on_rx_request, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request() */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev and next */ + { "Msg-Receiver", 12}, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION-1, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &msg_receiver_on_rx_request, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request() */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; /* Static vars, which will be reset on each test. */ @@ -149,8 +148,8 @@ static pjsip_transport *loop; static struct my_timer { pj_timer_entry entry; - char key_buf[1024]; - pj_str_t tsx_key; + char key_buf[1024]; + pj_str_t tsx_key; } timer; /* @@ -161,387 +160,387 @@ static struct my_timer static void tsx_user_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e) { if (pj_stricmp2(&tsx->branch, TEST1_BRANCH_ID)==0) { - /* - * Transaction with TEST1_BRANCH_ID should terminate with transaction - * timeout status. - */ - if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - if (test_complete == 0) - test_complete = 1; - - /* Test the status code. */ - if (tsx->status_code != PJSIP_SC_TSX_TIMEOUT) { - PJ_LOG(3,(THIS_FILE, - " error: status code is %d instead of %d", - tsx->status_code, PJSIP_SC_TSX_TIMEOUT)); - test_complete = -710; - } - - - /* If transport is reliable, then there must not be any - * retransmissions. - */ - if (tp_flag & PJSIP_TRANSPORT_RELIABLE) { - if (recv_count != 1) { - PJ_LOG(3,(THIS_FILE, - " error: there were %d (re)transmissions", - recv_count)); - test_complete = -715; - } - } else { - /* Check the number of (re)transmissions, which must be - * 6 or 7 for INVITE and 10 or 11 for non-INVITE. - * Theoretically the total (re)transmission time is 31,500ms - * (plus 300ms for delayed transport), and tsx timeout is 32s. - * In some test machines (e.g: MacOS), sometime the tsx timeout - * fires first which causes recv_count fall short (by one). - */ - //if (tsx->method.id==PJSIP_INVITE_METHOD && recv_count != 7) { - if (tsx->method.id==PJSIP_INVITE_METHOD && recv_count < 6) { - PJ_LOG(3,(THIS_FILE, - " error: there were %d (re)transmissions", - recv_count)); - test_complete = -716; - } else - //if (tsx->method.id==PJSIP_OPTIONS_METHOD && recv_count != 11) { - if (tsx->method.id==PJSIP_OPTIONS_METHOD && recv_count < 10) { - PJ_LOG(3,(THIS_FILE, - " error: there were %d (re)transmissions", - recv_count)); - test_complete = -717; - } else - if (tsx->method.id!=PJSIP_INVITE_METHOD && - tsx->method.id!=PJSIP_OPTIONS_METHOD) - { - PJ_LOG(3,(THIS_FILE, " error: unexpected method")); - test_complete = -718; - } - } - } + /* + * Transaction with TEST1_BRANCH_ID should terminate with transaction + * timeout status. + */ + if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + if (test_complete == 0) + test_complete = 1; + + /* Test the status code. */ + if (tsx->status_code != PJSIP_SC_TSX_TIMEOUT) { + PJ_LOG(3,(THIS_FILE, + " error: status code is %d instead of %d", + tsx->status_code, PJSIP_SC_TSX_TIMEOUT)); + test_complete = -710; + } + + + /* If transport is reliable, then there must not be any + * retransmissions. + */ + if (tp_flag & PJSIP_TRANSPORT_RELIABLE) { + if (recv_count != 1) { + PJ_LOG(3,(THIS_FILE, + " error: there were %d (re)transmissions", + recv_count)); + test_complete = -715; + } + } else { + /* Check the number of (re)transmissions, which must be + * 6 or 7 for INVITE and 10 or 11 for non-INVITE. + * Theoretically the total (re)transmission time is 31,500ms + * (plus 300ms for delayed transport), and tsx timeout is 32s. + * In some test machines (e.g: MacOS), sometime the tsx timeout + * fires first which causes recv_count fall short (by one). + */ + //if (tsx->method.id==PJSIP_INVITE_METHOD && recv_count != 7) { + if (tsx->method.id==PJSIP_INVITE_METHOD && recv_count < 6) { + PJ_LOG(3,(THIS_FILE, + " error: there were %d (re)transmissions", + recv_count)); + test_complete = -716; + } else + //if (tsx->method.id==PJSIP_OPTIONS_METHOD && recv_count != 11) { + if (tsx->method.id==PJSIP_OPTIONS_METHOD && recv_count < 10) { + PJ_LOG(3,(THIS_FILE, + " error: there were %d (re)transmissions", + recv_count)); + test_complete = -717; + } else + if (tsx->method.id!=PJSIP_INVITE_METHOD && + tsx->method.id!=PJSIP_OPTIONS_METHOD) + { + PJ_LOG(3,(THIS_FILE, " error: unexpected method")); + test_complete = -718; + } + } + } } else if (pj_stricmp2(&tsx->branch, TEST2_BRANCH_ID)==0) { - /* - * Transaction with TEST2_BRANCH_ID should terminate with transport error. - */ - if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - /* Test the status code. */ - if (tsx->status_code != PJSIP_SC_TSX_TRANSPORT_ERROR && - tsx->status_code != PJSIP_SC_BAD_GATEWAY) - { - PJ_LOG(3,(THIS_FILE, - " error: status code is %d instead of %d or %d", - tsx->status_code, PJSIP_SC_TSX_TRANSPORT_ERROR, - PJSIP_SC_BAD_GATEWAY)); - test_complete = -720; - } - - if (test_complete == 0) - test_complete = 1; - } + /* + * Transaction with TEST2_BRANCH_ID should terminate with transport error. + */ + if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + /* Test the status code. */ + if (tsx->status_code != PJSIP_SC_TSX_TRANSPORT_ERROR && + tsx->status_code != PJSIP_SC_BAD_GATEWAY) + { + PJ_LOG(3,(THIS_FILE, + " error: status code is %d instead of %d or %d", + tsx->status_code, PJSIP_SC_TSX_TRANSPORT_ERROR, + PJSIP_SC_BAD_GATEWAY)); + test_complete = -720; + } + + if (test_complete == 0) + test_complete = 1; + } } else if (pj_stricmp2(&tsx->branch, TEST3_BRANCH_ID)==0) { - /* - * This test terminates the transaction while resolver is still - * running. - */ - if (tsx->state == PJSIP_TSX_STATE_CALLING) { + /* + * This test terminates the transaction while resolver is still + * running. + */ + if (tsx->state == PJSIP_TSX_STATE_CALLING) { - /* Terminate the transaction. */ - pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED); + /* Terminate the transaction. */ + pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED); - } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - /* Check if status code is correct. */ - if (tsx->status_code != PJSIP_SC_REQUEST_TERMINATED) { - PJ_LOG(3,(THIS_FILE, - " error: status code is %d instead of %d", - tsx->status_code, PJSIP_SC_REQUEST_TERMINATED)); - test_complete = -730; - } + /* Check if status code is correct. */ + if (tsx->status_code != PJSIP_SC_REQUEST_TERMINATED) { + PJ_LOG(3,(THIS_FILE, + " error: status code is %d instead of %d", + tsx->status_code, PJSIP_SC_REQUEST_TERMINATED)); + test_complete = -730; + } - if (test_complete == 0) - test_complete = 1; + if (test_complete == 0) + test_complete = 1; - } + } } else if (pj_stricmp2(&tsx->branch, TEST4_BRANCH_ID)==0) { - /* - * This test simulates transport failure after several - * retransmissions. - */ - if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - /* Status code must be transport error. */ - if (tsx->status_code != PJSIP_SC_TSX_TRANSPORT_ERROR) { - PJ_LOG(3,(THIS_FILE, - " error: status code is %d instead of %d", - tsx->status_code, PJSIP_SC_TSX_TRANSPORT_ERROR)); - test_complete = -730; - } - - /* Must have correct retransmission count. */ - if (tsx->retransmit_count != TEST4_RETRANSMIT_CNT) { - PJ_LOG(3,(THIS_FILE, - " error: retransmit cnt is %d instead of %d", - tsx->retransmit_count, TEST4_RETRANSMIT_CNT)); - test_complete = -731; - } - - if (test_complete == 0) - test_complete = 1; - } + /* + * This test simulates transport failure after several + * retransmissions. + */ + if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + /* Status code must be transport error. */ + if (tsx->status_code != PJSIP_SC_TSX_TRANSPORT_ERROR) { + PJ_LOG(3,(THIS_FILE, + " error: status code is %d instead of %d", + tsx->status_code, PJSIP_SC_TSX_TRANSPORT_ERROR)); + test_complete = -730; + } + + /* Must have correct retransmission count. */ + if (tsx->retransmit_count != TEST4_RETRANSMIT_CNT) { + PJ_LOG(3,(THIS_FILE, + " error: retransmit cnt is %d instead of %d", + tsx->retransmit_count, TEST4_RETRANSMIT_CNT)); + test_complete = -731; + } + + if (test_complete == 0) + test_complete = 1; + } } else if (pj_stricmp2(&tsx->branch, TEST5_BRANCH_ID)==0) { - /* - * This test simulates transport failure after several - * retransmissions. - */ - if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - /* Status code must be PJSIP_SC_REQUEST_TERMINATED. */ - if (tsx->status_code != PJSIP_SC_REQUEST_TERMINATED) { - PJ_LOG(3,(THIS_FILE, - " error: status code is %d instead of %d", - tsx->status_code, PJSIP_SC_REQUEST_TERMINATED)); - test_complete = -733; - } - - /* Must have correct retransmission count. */ - if (tsx->retransmit_count != TEST5_RETRANSMIT_CNT) { - PJ_LOG(3,(THIS_FILE, - " error: retransmit cnt is %d instead of %d", - tsx->retransmit_count, TEST5_RETRANSMIT_CNT)); - test_complete = -734; - } - - if (test_complete == 0) - test_complete = 1; - } + /* + * This test simulates transport failure after several + * retransmissions. + */ + if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + /* Status code must be PJSIP_SC_REQUEST_TERMINATED. */ + if (tsx->status_code != PJSIP_SC_REQUEST_TERMINATED) { + PJ_LOG(3,(THIS_FILE, + " error: status code is %d instead of %d", + tsx->status_code, PJSIP_SC_REQUEST_TERMINATED)); + test_complete = -733; + } + + /* Must have correct retransmission count. */ + if (tsx->retransmit_count != TEST5_RETRANSMIT_CNT) { + PJ_LOG(3,(THIS_FILE, + " error: retransmit cnt is %d instead of %d", + tsx->retransmit_count, TEST5_RETRANSMIT_CNT)); + test_complete = -734; + } + + if (test_complete == 0) + test_complete = 1; + } } else if (pj_stricmp2(&tsx->branch, TEST6_BRANCH_ID)==0) { - /* - * Successfull non-INVITE transaction. - */ - if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { - - /* Status code must be 202. */ - if (tsx->status_code != 202) { - PJ_LOG(3,(THIS_FILE, - " error: status code is %d instead of %d", - tsx->status_code, 202)); - test_complete = -736; - } - - /* Must have correct retransmission count. */ - if (tsx->retransmit_count != 0) { - PJ_LOG(3,(THIS_FILE, - " error: retransmit cnt is %d instead of %d", - tsx->retransmit_count, 0)); - test_complete = -737; - } - - /* Must still keep last_tx */ - if (tsx->last_tx == NULL) { - PJ_LOG(3,(THIS_FILE, - " error: transaction lost last_tx")); - test_complete = -738; - } - - if (test_complete == 0) { - test_complete = 1; - pjsip_tsx_terminate(tsx, 202); - } - - } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - /* Previous state must be COMPLETED. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { - test_complete = -7381; - } - - } + /* + * Successfull non-INVITE transaction. + */ + if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { + + /* Status code must be 202. */ + if (tsx->status_code != 202) { + PJ_LOG(3,(THIS_FILE, + " error: status code is %d instead of %d", + tsx->status_code, 202)); + test_complete = -736; + } + + /* Must have correct retransmission count. */ + if (tsx->retransmit_count != 0) { + PJ_LOG(3,(THIS_FILE, + " error: retransmit cnt is %d instead of %d", + tsx->retransmit_count, 0)); + test_complete = -737; + } + + /* Must still keep last_tx */ + if (tsx->last_tx == NULL) { + PJ_LOG(3,(THIS_FILE, + " error: transaction lost last_tx")); + test_complete = -738; + } + + if (test_complete == 0) { + test_complete = 1; + pjsip_tsx_terminate(tsx, 202); + } + + } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + /* Previous state must be COMPLETED. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { + test_complete = -7381; + } + + } } else if (pj_stricmp2(&tsx->branch, TEST7_BRANCH_ID)==0) { - /* - * Successfull non-INVITE transaction. - */ - if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { - - /* Check prev state. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_PROCEEDING) { - PJ_LOG(3,(THIS_FILE, - " error: prev state is %s instead of %s", - pjsip_tsx_state_str((pjsip_tsx_state_e)e->body.tsx_state.prev_state), - pjsip_tsx_state_str(PJSIP_TSX_STATE_PROCEEDING))); - test_complete = -739; - } - - /* Status code must be 202. */ - if (tsx->status_code != 202) { - PJ_LOG(3,(THIS_FILE, - " error: status code is %d instead of %d", - tsx->status_code, 202)); - test_complete = -740; - } - - /* Must have correct retransmission count. */ - if (tsx->retransmit_count != 0) { - PJ_LOG(3,(THIS_FILE, - " error: retransmit cnt is %d instead of %d", - tsx->retransmit_count, 0)); - test_complete = -741; - } - - /* Must still keep last_tx */ - if (tsx->last_tx == NULL) { - PJ_LOG(3,(THIS_FILE, - " error: transaction lost last_tx")); - test_complete = -741; - } - - if (test_complete == 0) { - test_complete = 1; - pjsip_tsx_terminate(tsx, 202); - } - - } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - /* Previous state must be COMPLETED. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { - test_complete = -742; - } - - } + /* + * Successfull non-INVITE transaction. + */ + if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { + + /* Check prev state. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_PROCEEDING) { + PJ_LOG(3,(THIS_FILE, + " error: prev state is %s instead of %s", + pjsip_tsx_state_str((pjsip_tsx_state_e)e->body.tsx_state.prev_state), + pjsip_tsx_state_str(PJSIP_TSX_STATE_PROCEEDING))); + test_complete = -739; + } + + /* Status code must be 202. */ + if (tsx->status_code != 202) { + PJ_LOG(3,(THIS_FILE, + " error: status code is %d instead of %d", + tsx->status_code, 202)); + test_complete = -740; + } + + /* Must have correct retransmission count. */ + if (tsx->retransmit_count != 0) { + PJ_LOG(3,(THIS_FILE, + " error: retransmit cnt is %d instead of %d", + tsx->retransmit_count, 0)); + test_complete = -741; + } + + /* Must still keep last_tx */ + if (tsx->last_tx == NULL) { + PJ_LOG(3,(THIS_FILE, + " error: transaction lost last_tx")); + test_complete = -741; + } + + if (test_complete == 0) { + test_complete = 1; + pjsip_tsx_terminate(tsx, 202); + } + + } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + /* Previous state must be COMPLETED. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { + test_complete = -742; + } + + } } else if (pj_stricmp2(&tsx->branch, TEST8_BRANCH_ID)==0) { - /* - * Failed INVITE transaction. - */ - if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { - - /* Status code must be 301. */ - if (tsx->status_code != 301) { - PJ_LOG(3,(THIS_FILE, - " error: status code is %d instead of %d", - tsx->status_code, 301)); - test_complete = -745; - } - - /* Must have correct retransmission count. */ - if (tsx->retransmit_count != 0) { - PJ_LOG(3,(THIS_FILE, - " error: retransmit cnt is %d instead of %d", - tsx->retransmit_count, 0)); - test_complete = -746; - } - - /* Must still keep last_tx */ - if (tsx->last_tx == NULL) { - PJ_LOG(3,(THIS_FILE, - " error: transaction lost last_tx")); - test_complete = -747; - } - - /* last_tx MUST be the INVITE request - * (authorization depends on this behavior) - */ - if (tsx->last_tx && tsx->last_tx->msg->line.req.method.id != - PJSIP_INVITE_METHOD) - { - PJ_LOG(3,(THIS_FILE, - " error: last_tx is not INVITE")); - test_complete = -748; - } - } - else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - test_complete = 1; - - /* Previous state must be COMPLETED. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { - test_complete = -750; - } - - /* Status code must be 301. */ - if (tsx->status_code != 301) { - PJ_LOG(3,(THIS_FILE, - " error: status code is %d instead of %d", - tsx->status_code, 301)); - test_complete = -751; - } - - } + /* + * Failed INVITE transaction. + */ + if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { + + /* Status code must be 301. */ + if (tsx->status_code != 301) { + PJ_LOG(3,(THIS_FILE, + " error: status code is %d instead of %d", + tsx->status_code, 301)); + test_complete = -745; + } + + /* Must have correct retransmission count. */ + if (tsx->retransmit_count != 0) { + PJ_LOG(3,(THIS_FILE, + " error: retransmit cnt is %d instead of %d", + tsx->retransmit_count, 0)); + test_complete = -746; + } + + /* Must still keep last_tx */ + if (tsx->last_tx == NULL) { + PJ_LOG(3,(THIS_FILE, + " error: transaction lost last_tx")); + test_complete = -747; + } + + /* last_tx MUST be the INVITE request + * (authorization depends on this behavior) + */ + if (tsx->last_tx && tsx->last_tx->msg->line.req.method.id != + PJSIP_INVITE_METHOD) + { + PJ_LOG(3,(THIS_FILE, + " error: last_tx is not INVITE")); + test_complete = -748; + } + } + else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + test_complete = 1; + + /* Previous state must be COMPLETED. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { + test_complete = -750; + } + + /* Status code must be 301. */ + if (tsx->status_code != 301) { + PJ_LOG(3,(THIS_FILE, + " error: status code is %d instead of %d", + tsx->status_code, 301)); + test_complete = -751; + } + + } } else if (pj_stricmp2(&tsx->branch, TEST9_BRANCH_ID)==0) { - /* - * Failed INVITE transaction with provisional response. - */ - if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { - - /* Previous state must be PJSIP_TSX_STATE_PROCEEDING. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_PROCEEDING) { - test_complete = -760; - } - - /* Status code must be 302. */ - if (tsx->status_code != 302) { - PJ_LOG(3,(THIS_FILE, - " error: status code is %d instead of %d", - tsx->status_code, 302)); - test_complete = -761; - } - - /* Must have correct retransmission count. */ - if (tsx->retransmit_count != 0) { - PJ_LOG(3,(THIS_FILE, - " error: retransmit cnt is %d instead of %d", - tsx->retransmit_count, 0)); - test_complete = -762; - } - - /* Must still keep last_tx */ - if (tsx->last_tx == NULL) { - PJ_LOG(3,(THIS_FILE, - " error: transaction lost last_tx")); - test_complete = -763; - } - - /* last_tx MUST be INVITE. - * (authorization depends on this behavior) - */ - if (tsx->last_tx && tsx->last_tx->msg->line.req.method.id != - PJSIP_INVITE_METHOD) - { - PJ_LOG(3,(THIS_FILE, - " error: last_tx is not INVITE")); - test_complete = -764; - } - - } - else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - test_complete = 1; - - /* Previous state must be COMPLETED. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { - test_complete = -767; - } - - /* Status code must be 302. */ - if (tsx->status_code != 302) { - PJ_LOG(3,(THIS_FILE, - " error: status code is %d instead of %d", - tsx->status_code, 302)); - test_complete = -768; - } - - } + /* + * Failed INVITE transaction with provisional response. + */ + if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { + + /* Previous state must be PJSIP_TSX_STATE_PROCEEDING. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_PROCEEDING) { + test_complete = -760; + } + + /* Status code must be 302. */ + if (tsx->status_code != 302) { + PJ_LOG(3,(THIS_FILE, + " error: status code is %d instead of %d", + tsx->status_code, 302)); + test_complete = -761; + } + + /* Must have correct retransmission count. */ + if (tsx->retransmit_count != 0) { + PJ_LOG(3,(THIS_FILE, + " error: retransmit cnt is %d instead of %d", + tsx->retransmit_count, 0)); + test_complete = -762; + } + + /* Must still keep last_tx */ + if (tsx->last_tx == NULL) { + PJ_LOG(3,(THIS_FILE, + " error: transaction lost last_tx")); + test_complete = -763; + } + + /* last_tx MUST be INVITE. + * (authorization depends on this behavior) + */ + if (tsx->last_tx && tsx->last_tx->msg->line.req.method.id != + PJSIP_INVITE_METHOD) + { + PJ_LOG(3,(THIS_FILE, + " error: last_tx is not INVITE")); + test_complete = -764; + } + + } + else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + test_complete = 1; + + /* Previous state must be COMPLETED. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { + test_complete = -767; + } + + /* Status code must be 302. */ + if (tsx->status_code != 302) { + PJ_LOG(3,(THIS_FILE, + " error: status code is %d instead of %d", + tsx->status_code, 302)); + test_complete = -768; + } + + } } } @@ -551,12 +550,12 @@ static void tsx_user_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e) */ struct response { - pjsip_response_addr res_addr; - pjsip_tx_data *tdata; + pjsip_response_addr res_addr; + pjsip_tx_data *tdata; }; static void send_response_callback( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { struct response *r = (struct response*) entry->user_data; pjsip_transport *tp = r->res_addr.transport; @@ -567,12 +566,12 @@ static void send_response_callback( pj_timer_heap_t *timer_heap, status = pjsip_endpt_send_response(endpt, &r->res_addr, r->tdata, NULL, NULL); if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref(r->tdata); if (tp) - pjsip_transport_dec_ref(tp); + pjsip_transport_dec_ref(tp); } /* Timer callback to terminate a transaction. */ static void terminate_tsx_callback( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { struct my_timer *m = (struct my_timer *)entry; pjsip_transaction *tsx = pjsip_tsx_layer_find_tsx(&m->tsx_key, PJ_FALSE); @@ -581,7 +580,7 @@ static void terminate_tsx_callback( pj_timer_heap_t *timer_heap, PJ_UNUSED_ARG(timer_heap); if (tsx) { - pjsip_tsx_terminate(tsx, status_code); + pjsip_tsx_terminate(tsx, status_code); } } @@ -596,352 +595,352 @@ static void terminate_tsx_callback( pj_timer_heap_t *timer_heap, static pj_bool_t msg_receiver_on_rx_request(pjsip_rx_data *rdata) { if (pj_stricmp2(&rdata->msg_info.via->branch_param, TEST1_BRANCH_ID) == 0) { - /* - * The TEST1_BRANCH_ID test performs the verifications for transaction - * retransmission mechanism. It will not answer the incoming request - * with any response. - */ - pjsip_msg *msg = rdata->msg_info.msg; - - PJ_LOG(4,(THIS_FILE, " received request")); - - /* Only wants to take INVITE or OPTIONS method. */ - if (msg->line.req.method.id != PJSIP_INVITE_METHOD && - msg->line.req.method.id != PJSIP_OPTIONS_METHOD) - { - PJ_LOG(3,(THIS_FILE, " error: received unexpected method %.*s", - msg->line.req.method.name.slen, - msg->line.req.method.name.ptr)); - test_complete = -600; - return PJ_TRUE; - } - - if (recv_count == 0) { - recv_count++; - //pj_gettimeofday(&recv_last); - recv_last = rdata->pkt_info.timestamp; - } else { - pj_time_val now; - unsigned msec_expected, msec_elapsed; - int max_received; - - //pj_gettimeofday(&now); - now = rdata->pkt_info.timestamp; - PJ_TIME_VAL_SUB(now, recv_last); - msec_elapsed = now.sec*1000 + now.msec; - - ++recv_count; - msec_expected = (1<<(recv_count-2))*pjsip_cfg()->tsx.t1; - - if (msg->line.req.method.id != PJSIP_INVITE_METHOD) { - if (msec_expected > pjsip_cfg()->tsx.t2) - msec_expected = pjsip_cfg()->tsx.t2; - max_received = 11; - } else { - max_received = 7; - } - - if (DIFF(msec_expected, msec_elapsed) > TEST1_ALLOWED_DIFF) { - PJ_LOG(3,(THIS_FILE, - " error: expecting retransmission no. %d in %d " - "ms, received in %d ms", - recv_count-1, msec_expected, msec_elapsed)); - test_complete = -610; - } - - - if (recv_count > max_received) { - PJ_LOG(3,(THIS_FILE, - " error: too many messages (%d) received", - recv_count)); - test_complete = -620; - } - - //pj_gettimeofday(&recv_last); - recv_last = rdata->pkt_info.timestamp; - } - return PJ_TRUE; + /* + * The TEST1_BRANCH_ID test performs the verifications for transaction + * retransmission mechanism. It will not answer the incoming request + * with any response. + */ + pjsip_msg *msg = rdata->msg_info.msg; + + PJ_LOG(4,(THIS_FILE, " received request")); + + /* Only wants to take INVITE or OPTIONS method. */ + if (msg->line.req.method.id != PJSIP_INVITE_METHOD && + msg->line.req.method.id != PJSIP_OPTIONS_METHOD) + { + PJ_LOG(3,(THIS_FILE, " error: received unexpected method %.*s", + msg->line.req.method.name.slen, + msg->line.req.method.name.ptr)); + test_complete = -600; + return PJ_TRUE; + } + + if (recv_count == 0) { + recv_count++; + //pj_gettimeofday(&recv_last); + recv_last = rdata->pkt_info.timestamp; + } else { + pj_time_val now; + unsigned msec_expected, msec_elapsed; + int max_received; + + //pj_gettimeofday(&now); + now = rdata->pkt_info.timestamp; + PJ_TIME_VAL_SUB(now, recv_last); + msec_elapsed = now.sec*1000 + now.msec; + + ++recv_count; + msec_expected = (1<<(recv_count-2))*pjsip_cfg()->tsx.t1; + + if (msg->line.req.method.id != PJSIP_INVITE_METHOD) { + if (msec_expected > pjsip_cfg()->tsx.t2) + msec_expected = pjsip_cfg()->tsx.t2; + max_received = 11; + } else { + max_received = 7; + } + + if (DIFF(msec_expected, msec_elapsed) > TEST1_ALLOWED_DIFF) { + PJ_LOG(3,(THIS_FILE, + " error: expecting retransmission no. %d in %d " + "ms, received in %d ms", + recv_count-1, msec_expected, msec_elapsed)); + test_complete = -610; + } + + + if (recv_count > max_received) { + PJ_LOG(3,(THIS_FILE, + " error: too many messages (%d) received", + recv_count)); + test_complete = -620; + } + + //pj_gettimeofday(&recv_last); + recv_last = rdata->pkt_info.timestamp; + } + return PJ_TRUE; } else if (pj_stricmp2(&rdata->msg_info.via->branch_param, TEST4_BRANCH_ID) == 0) { - /* - * The TEST4_BRANCH_ID test simulates transport failure after several - * retransmissions. - */ - recv_count++; + /* + * The TEST4_BRANCH_ID test simulates transport failure after several + * retransmissions. + */ + recv_count++; - if (recv_count == TEST4_RETRANSMIT_CNT) { - /* Simulate transport failure. */ - pjsip_loop_set_failure(loop, 2, NULL); + if (recv_count == TEST4_RETRANSMIT_CNT) { + /* Simulate transport failure. */ + pjsip_loop_set_failure(loop, 2, NULL); - } else if (recv_count > TEST4_RETRANSMIT_CNT) { - PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", - recv_count)); - test_complete = -631; - } + } else if (recv_count > TEST4_RETRANSMIT_CNT) { + PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", + recv_count)); + test_complete = -631; + } - return PJ_TRUE; + return PJ_TRUE; } else if (pj_stricmp2(&rdata->msg_info.via->branch_param, TEST5_BRANCH_ID) == 0) { - /* - * The TEST5_BRANCH_ID test simulates user terminating the transaction - * after several retransmissions. - */ - recv_count++; - - if (recv_count == TEST5_RETRANSMIT_CNT+1) { - pj_str_t key; - pjsip_transaction *tsx; - - pjsip_tsx_create_key( rdata->tp_info.pool, &key, PJSIP_ROLE_UAC, - &rdata->msg_info.msg->line.req.method, rdata); - tsx = pjsip_tsx_layer_find_tsx(&key, PJ_TRUE); - if (tsx) { - pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED); - pj_grp_lock_release(tsx->grp_lock); - } else { - PJ_LOG(3,(THIS_FILE, " error: uac transaction not found!")); - test_complete = -633; - } - - } else if (recv_count > TEST5_RETRANSMIT_CNT+1) { - PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", - recv_count)); - test_complete = -634; - } - - return PJ_TRUE; + /* + * The TEST5_BRANCH_ID test simulates user terminating the transaction + * after several retransmissions. + */ + recv_count++; + + if (recv_count == TEST5_RETRANSMIT_CNT+1) { + pj_str_t key; + pjsip_transaction *tsx; + + pjsip_tsx_create_key( rdata->tp_info.pool, &key, PJSIP_ROLE_UAC, + &rdata->msg_info.msg->line.req.method, rdata); + tsx = pjsip_tsx_layer_find_tsx(&key, PJ_TRUE); + if (tsx) { + pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED); + pj_grp_lock_release(tsx->grp_lock); + } else { + PJ_LOG(3,(THIS_FILE, " error: uac transaction not found!")); + test_complete = -633; + } + + } else if (recv_count > TEST5_RETRANSMIT_CNT+1) { + PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", + recv_count)); + test_complete = -634; + } + + return PJ_TRUE; } else if (pj_stricmp2(&rdata->msg_info.via->branch_param, TEST6_BRANCH_ID) == 0) { - /* - * The TEST6_BRANCH_ID test successfull non-INVITE transaction. - */ - pj_status_t status; + /* + * The TEST6_BRANCH_ID test successfull non-INVITE transaction. + */ + pj_status_t status; - recv_count++; + recv_count++; - if (recv_count > 1) { - PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", - recv_count)); - test_complete = -635; - } + if (recv_count > 1) { + PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", + recv_count)); + test_complete = -635; + } - status = pjsip_endpt_respond_stateless(endpt, rdata, 202, NULL, - NULL, NULL); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to send response", status); - test_complete = -636; - } + status = pjsip_endpt_respond_stateless(endpt, rdata, 202, NULL, + NULL, NULL); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to send response", status); + test_complete = -636; + } - return PJ_TRUE; + return PJ_TRUE; } else if (pj_stricmp2(&rdata->msg_info.via->branch_param, TEST7_BRANCH_ID) == 0) { - /* - * The TEST7_BRANCH_ID test successfull non-INVITE transaction - * with provisional response. - */ - pj_status_t status; - pjsip_response_addr res_addr; - struct response *r; - pjsip_tx_data *tdata; - pj_time_val delay = { 2, 0 }; - - recv_count++; - - if (recv_count > 1) { - PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", - recv_count)); - test_complete = -640; - return PJ_TRUE; - } - - /* Respond with provisional response */ - status = pjsip_endpt_create_response(endpt, rdata, 100, NULL, &tdata); - pj_assert(status == PJ_SUCCESS); - - status = pjsip_get_response_addr(tdata->pool, rdata, &res_addr); - pj_assert(status == PJ_SUCCESS); - - status = pjsip_endpt_send_response(endpt, &res_addr, tdata, - NULL, NULL); - pj_assert(status == PJ_SUCCESS); - - /* Create the final response. */ - status = pjsip_endpt_create_response(endpt, rdata, 202, NULL, &tdata); - pj_assert(status == PJ_SUCCESS); - - /* Schedule sending final response in couple of of secs. */ - r = PJ_POOL_ALLOC_T(tdata->pool, struct response); - r->res_addr = res_addr; - r->tdata = tdata; - if (r->res_addr.transport) - pjsip_transport_add_ref(r->res_addr.transport); - - timer.entry.cb = &send_response_callback; - timer.entry.user_data = r; - pjsip_endpt_schedule_timer(endpt, &timer.entry, &delay); - - return (status == PJ_SUCCESS); + /* + * The TEST7_BRANCH_ID test successfull non-INVITE transaction + * with provisional response. + */ + pj_status_t status; + pjsip_response_addr res_addr; + struct response *r; + pjsip_tx_data *tdata; + pj_time_val delay = { 2, 0 }; + + recv_count++; + + if (recv_count > 1) { + PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", + recv_count)); + test_complete = -640; + return PJ_TRUE; + } + + /* Respond with provisional response */ + status = pjsip_endpt_create_response(endpt, rdata, 100, NULL, &tdata); + pj_assert(status == PJ_SUCCESS); + + status = pjsip_get_response_addr(tdata->pool, rdata, &res_addr); + pj_assert(status == PJ_SUCCESS); + + status = pjsip_endpt_send_response(endpt, &res_addr, tdata, + NULL, NULL); + pj_assert(status == PJ_SUCCESS); + + /* Create the final response. */ + status = pjsip_endpt_create_response(endpt, rdata, 202, NULL, &tdata); + pj_assert(status == PJ_SUCCESS); + + /* Schedule sending final response in couple of of secs. */ + r = PJ_POOL_ALLOC_T(tdata->pool, struct response); + r->res_addr = res_addr; + r->tdata = tdata; + if (r->res_addr.transport) + pjsip_transport_add_ref(r->res_addr.transport); + + timer.entry.cb = &send_response_callback; + timer.entry.user_data = r; + pjsip_endpt_schedule_timer(endpt, &timer.entry, &delay); + + return (status == PJ_SUCCESS); } else if (pj_stricmp2(&rdata->msg_info.via->branch_param, TEST8_BRANCH_ID) == 0) { - /* - * The TEST8_BRANCH_ID test failed INVITE transaction. - */ - pjsip_method *method; - pj_status_t status; + /* + * The TEST8_BRANCH_ID test failed INVITE transaction. + */ + pjsip_method *method; + pj_status_t status; - method = &rdata->msg_info.msg->line.req.method; + method = &rdata->msg_info.msg->line.req.method; - recv_count++; + recv_count++; - if (method->id == PJSIP_INVITE_METHOD) { + if (method->id == PJSIP_INVITE_METHOD) { - if (recv_count > 1) { - PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", - recv_count)); - test_complete = -635; - } + if (recv_count > 1) { + PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", + recv_count)); + test_complete = -635; + } - status = pjsip_endpt_respond_stateless(endpt, rdata, 301, NULL, - NULL, NULL); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to send response", status); - test_complete = -636; - } + status = pjsip_endpt_respond_stateless(endpt, rdata, 301, NULL, + NULL, NULL); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to send response", status); + test_complete = -636; + } - } else if (method->id == PJSIP_ACK_METHOD) { + } else if (method->id == PJSIP_ACK_METHOD) { - if (recv_count == 2) { - pj_str_t key; - pj_time_val delay = { 5, 0 }; - - /* Schedule timer to destroy transaction after 5 seconds. - * This is to make sure that transaction does not - * retransmit ACK. - */ - pjsip_tsx_create_key(rdata->tp_info.pool, &key, - PJSIP_ROLE_UAC, &pjsip_invite_method, - rdata); + if (recv_count == 2) { + pj_str_t key; + pj_time_val delay = { 5, 0 }; + + /* Schedule timer to destroy transaction after 5 seconds. + * This is to make sure that transaction does not + * retransmit ACK. + */ + pjsip_tsx_create_key(rdata->tp_info.pool, &key, + PJSIP_ROLE_UAC, &pjsip_invite_method, + rdata); - pj_strcpy(&timer.tsx_key, &key); - timer.entry.id = 301; - timer.entry.cb = &terminate_tsx_callback; + pj_strcpy(&timer.tsx_key, &key); + timer.entry.id = 301; + timer.entry.cb = &terminate_tsx_callback; - pjsip_endpt_schedule_timer(endpt, &timer.entry, &delay); - } + pjsip_endpt_schedule_timer(endpt, &timer.entry, &delay); + } - if (recv_count > 2) { - PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", - recv_count)); - test_complete = -638; - } + if (recv_count > 2) { + PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", + recv_count)); + test_complete = -638; + } - } else { - PJ_LOG(3,(THIS_FILE," error: not expecting %s", - pjsip_rx_data_get_info(rdata))); - test_complete = -639; + } else { + PJ_LOG(3,(THIS_FILE," error: not expecting %s", + pjsip_rx_data_get_info(rdata))); + test_complete = -639; - } + } } else if (pj_stricmp2(&rdata->msg_info.via->branch_param, TEST9_BRANCH_ID) == 0) { - /* - * The TEST9_BRANCH_ID test failed INVITE transaction with - * provisional response. - */ - pjsip_method *method; - pj_status_t status = PJ_SUCCESS; - - method = &rdata->msg_info.msg->line.req.method; - - recv_count++; - - if (method->id == PJSIP_INVITE_METHOD) { - - pjsip_response_addr res_addr; - struct response *r; - pjsip_tx_data *tdata; - pj_time_val delay = { 2, 0 }; - - if (recv_count > 1) { - PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", - recv_count)); - test_complete = -650; - return PJ_TRUE; - } - - /* Respond with provisional response */ - status = pjsip_endpt_create_response(endpt, rdata, 100, NULL, - &tdata); - pj_assert(status == PJ_SUCCESS); - - status = pjsip_get_response_addr(tdata->pool, rdata, &res_addr); - pj_assert(status == PJ_SUCCESS); - - status = pjsip_endpt_send_response(endpt, &res_addr, tdata, - NULL, NULL); - pj_assert(status == PJ_SUCCESS); - - /* Create the final response. */ - status = pjsip_endpt_create_response(endpt, rdata, 302, NULL, - &tdata); - pj_assert(status == PJ_SUCCESS); - - /* Schedule sending final response in couple of of secs. */ - r = PJ_POOL_ALLOC_T(tdata->pool, struct response); - r->res_addr = res_addr; - r->tdata = tdata; - if (r->res_addr.transport) - pjsip_transport_add_ref(r->res_addr.transport); - - timer.entry.cb = &send_response_callback; - timer.entry.user_data = r; - pjsip_endpt_schedule_timer(endpt, &timer.entry, &delay); - - } else if (method->id == PJSIP_ACK_METHOD) { - - if (recv_count == 2) { - pj_str_t key; - pj_time_val delay = { 5, 0 }; - - /* Schedule timer to destroy transaction after 5 seconds. - * This is to make sure that transaction does not - * retransmit ACK. - */ - pjsip_tsx_create_key(rdata->tp_info.pool, &key, - PJSIP_ROLE_UAC, &pjsip_invite_method, - rdata); - - pj_strcpy(&timer.tsx_key, &key); - timer.entry.id = 302; - timer.entry.cb = &terminate_tsx_callback; - - pjsip_endpt_schedule_timer(endpt, &timer.entry, &delay); - } - - if (recv_count > 2) { - PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", - recv_count)); - test_complete = -638; - } - - - } else { - PJ_LOG(3,(THIS_FILE," error: not expecting %s", - pjsip_rx_data_get_info(rdata))); - test_complete = -639; - - } - - return (status == PJ_SUCCESS); + /* + * The TEST9_BRANCH_ID test failed INVITE transaction with + * provisional response. + */ + pjsip_method *method; + pj_status_t status = PJ_SUCCESS; + + method = &rdata->msg_info.msg->line.req.method; + + recv_count++; + + if (method->id == PJSIP_INVITE_METHOD) { + + pjsip_response_addr res_addr; + struct response *r; + pjsip_tx_data *tdata; + pj_time_val delay = { 2, 0 }; + + if (recv_count > 1) { + PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", + recv_count)); + test_complete = -650; + return PJ_TRUE; + } + + /* Respond with provisional response */ + status = pjsip_endpt_create_response(endpt, rdata, 100, NULL, + &tdata); + pj_assert(status == PJ_SUCCESS); + + status = pjsip_get_response_addr(tdata->pool, rdata, &res_addr); + pj_assert(status == PJ_SUCCESS); + + status = pjsip_endpt_send_response(endpt, &res_addr, tdata, + NULL, NULL); + pj_assert(status == PJ_SUCCESS); + + /* Create the final response. */ + status = pjsip_endpt_create_response(endpt, rdata, 302, NULL, + &tdata); + pj_assert(status == PJ_SUCCESS); + + /* Schedule sending final response in couple of of secs. */ + r = PJ_POOL_ALLOC_T(tdata->pool, struct response); + r->res_addr = res_addr; + r->tdata = tdata; + if (r->res_addr.transport) + pjsip_transport_add_ref(r->res_addr.transport); + + timer.entry.cb = &send_response_callback; + timer.entry.user_data = r; + pjsip_endpt_schedule_timer(endpt, &timer.entry, &delay); + + } else if (method->id == PJSIP_ACK_METHOD) { + + if (recv_count == 2) { + pj_str_t key; + pj_time_val delay = { 5, 0 }; + + /* Schedule timer to destroy transaction after 5 seconds. + * This is to make sure that transaction does not + * retransmit ACK. + */ + pjsip_tsx_create_key(rdata->tp_info.pool, &key, + PJSIP_ROLE_UAC, &pjsip_invite_method, + rdata); + + pj_strcpy(&timer.tsx_key, &key); + timer.entry.id = 302; + timer.entry.cb = &terminate_tsx_callback; + + pjsip_endpt_schedule_timer(endpt, &timer.entry, &delay); + } + + if (recv_count > 2) { + PJ_LOG(3,(THIS_FILE," error: not expecting %d-th packet!", + recv_count)); + test_complete = -638; + } + + + } else { + PJ_LOG(3,(THIS_FILE," error: not expecting %s", + pjsip_rx_data_get_info(rdata))); + test_complete = -639; + + } + + return (status == PJ_SUCCESS); } @@ -952,8 +951,8 @@ static pj_bool_t msg_receiver_on_rx_request(pjsip_rx_data *rdata) * The generic test framework, used by most of the tests. */ static int perform_tsx_test(int dummy, char *target_uri, char *from_uri, - char *branch_param, int test_time, - const pjsip_method *method) + char *branch_param, int test_time, + const pjsip_method *method) { pjsip_tx_data *tdata; pjsip_transaction *tsx; @@ -965,8 +964,8 @@ static int perform_tsx_test(int dummy, char *target_uri, char *from_uri, PJ_UNUSED_ARG(dummy); PJ_LOG(3,(THIS_FILE, - " please standby, this will take at most %d seconds..", - test_time)); + " please standby, this will take at most %d seconds..", + test_time)); /* Reset test. */ recv_count = 0; @@ -978,11 +977,11 @@ static int perform_tsx_test(int dummy, char *target_uri, char *from_uri, /* Create request. */ status = pjsip_endpt_create_request( endpt, method, &target, - &from, &target, NULL, NULL, -1, - NULL, &tdata); + &from, &target, NULL, NULL, -1, + NULL, &tdata); if (status != PJ_SUCCESS) { - app_perror(" Error: unable to create request", status); - return -100; + app_perror(" Error: unable to create request", status); + return -100; } /* Set the branch param for test 1. */ @@ -997,9 +996,9 @@ static int perform_tsx_test(int dummy, char *target_uri, char *from_uri, /* Create transaction. */ status = pjsip_tsx_create_uac( &tsx_user, tdata, &tsx); if (status != PJ_SUCCESS) { - app_perror(" Error: unable to create UAC transaction", status); - pjsip_tx_data_dec_ref(tdata); - return -110; + app_perror(" Error: unable to create UAC transaction", status); + pjsip_tx_data_dec_ref(tdata); + return -110; } /* Get transaction key. */ @@ -1010,9 +1009,9 @@ static int perform_tsx_test(int dummy, char *target_uri, char *from_uri, // Ignore send result. Some tests do deliberately triggers error // when sending message. if (status != PJ_SUCCESS) { - // app_perror(" Error: unable to send request", status); + // app_perror(" Error: unable to send request", status); pjsip_tx_data_dec_ref(tdata); - // return -120; + // return -120; } @@ -1022,58 +1021,58 @@ static int perform_tsx_test(int dummy, char *target_uri, char *from_uri, /* Wait until test complete. */ while (!test_complete) { - pj_time_val now, poll_delay = {0, 10}; + pj_time_val now, poll_delay = {0, 10}; - pjsip_endpt_handle_events(endpt, &poll_delay); + pjsip_endpt_handle_events(endpt, &poll_delay); - pj_gettimeofday(&now); - if (now.sec > timeout.sec) { - PJ_LOG(3,(THIS_FILE, " Error: test has timed out")); - pjsip_tx_data_dec_ref(tdata); - return -130; - } + pj_gettimeofday(&now); + if (now.sec > timeout.sec) { + PJ_LOG(3,(THIS_FILE, " Error: test has timed out")); + pjsip_tx_data_dec_ref(tdata); + return -130; + } } if (test_complete < 0) { - tsx = pjsip_tsx_layer_find_tsx(&tsx_key, PJ_TRUE); - if (tsx) { - pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED); - pj_grp_lock_release(tsx->grp_lock); - flush_events(1000); - } - pjsip_tx_data_dec_ref(tdata); - return test_complete; + tsx = pjsip_tsx_layer_find_tsx(&tsx_key, PJ_TRUE); + if (tsx) { + pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED); + pj_grp_lock_release(tsx->grp_lock); + flush_events(1000); + } + pjsip_tx_data_dec_ref(tdata); + return test_complete; } else { - pj_time_val now; + pj_time_val now; - /* Allow transaction to destroy itself */ - flush_events(500); + /* Allow transaction to destroy itself */ + flush_events(500); - /* Wait until test completes */ - pj_gettimeofday(&now); + /* Wait until test completes */ + pj_gettimeofday(&now); - if (PJ_TIME_VAL_LT(now, timeout)) { - pj_time_val interval; - interval = timeout; - PJ_TIME_VAL_SUB(interval, now); - flush_events(PJ_TIME_VAL_MSEC(interval)); - } + if (PJ_TIME_VAL_LT(now, timeout)) { + pj_time_val interval; + interval = timeout; + PJ_TIME_VAL_SUB(interval, now); + flush_events(PJ_TIME_VAL_MSEC(interval)); + } } /* Make sure transaction has been destroyed. */ if (pjsip_tsx_layer_find_tsx(&tsx_key, PJ_FALSE) != NULL) { - PJ_LOG(3,(THIS_FILE, " Error: transaction has not been destroyed")); - pjsip_tx_data_dec_ref(tdata); - return -140; + PJ_LOG(3,(THIS_FILE, " Error: transaction has not been destroyed")); + pjsip_tx_data_dec_ref(tdata); + return -140; } /* Check tdata reference counter. */ if (pj_atomic_get(tdata->ref_cnt) != 1) { - PJ_LOG(3,(THIS_FILE, " Error: tdata reference counter is %d", - pj_atomic_get(tdata->ref_cnt))); - pjsip_tx_data_dec_ref(tdata); - return -150; + PJ_LOG(3,(THIS_FILE, " Error: tdata reference counter is %d", + pj_atomic_get(tdata->ref_cnt))); + pjsip_tx_data_dec_ref(tdata); + return -150; } /* Destroy txdata */ @@ -1097,17 +1096,17 @@ static int tsx_uac_retransmit_test(void) int status = 0, enabled; int i; struct { - const pjsip_method *method; - unsigned delay; + const pjsip_method *method; + unsigned delay; } sub_test[] = { - { &pjsip_invite_method, 0}, - //{ &pjsip_invite_method, TEST1_ALLOWED_DIFF*2}, - { &pjsip_invite_method, 300}, + { &pjsip_invite_method, 0}, + //{ &pjsip_invite_method, TEST1_ALLOWED_DIFF*2}, + { &pjsip_invite_method, 300}, - { &pjsip_options_method, 0}, - //{ &pjsip_options_method, TEST1_ALLOWED_DIFF*2} - { &pjsip_options_method, 300} + { &pjsip_options_method, 0}, + //{ &pjsip_options_method, TEST1_ALLOWED_DIFF*2} + { &pjsip_options_method, 300} }; PJ_LOG(3,(THIS_FILE, " test1: basic uac retransmit and timeout test")); @@ -1120,22 +1119,22 @@ static int tsx_uac_retransmit_test(void) for (i=0; i<(int)PJ_ARRAY_SIZE(sub_test); ++i) { - PJ_LOG(3,(THIS_FILE, - " variant %c: %s with %d ms network delay", - ('a' + i), - sub_test[i].method->name.ptr, - sub_test[i].delay)); - - /* Configure transport */ - pjsip_loop_set_failure(loop, 0, NULL); - pjsip_loop_set_recv_delay(loop, sub_test[i].delay, NULL); - - /* Do the test. */ - status = perform_tsx_test(-500, TARGET_URI, FROM_URI, - TEST1_BRANCH_ID, - 35, sub_test[i].method); - if (status != 0) - break; + PJ_LOG(3,(THIS_FILE, + " variant %c: %s with %d ms network delay", + ('a' + i), + sub_test[i].method->name.ptr, + sub_test[i].delay)); + + /* Configure transport */ + pjsip_loop_set_failure(loop, 0, NULL); + pjsip_loop_set_recv_delay(loop, sub_test[i].delay, NULL); + + /* Do the test. */ + status = perform_tsx_test(-500, TARGET_URI, FROM_URI, + TEST1_BRANCH_ID, + 35, sub_test[i].method); + if (status != 0) + break; } /* Restore transport. */ @@ -1171,11 +1170,11 @@ static int tsx_resolve_error_test(void) PJ_LOG(3,(THIS_FILE, " variant a: immediate resolving error")); status = perform_tsx_test(-800, - "sip:bob@unresolved-host", - FROM_URI, TEST2_BRANCH_ID, 20, - &pjsip_options_method); + "sip:bob@unresolved-host", + FROM_URI, TEST2_BRANCH_ID, 20, + &pjsip_options_method); if (status != 0) - return status; + return status; /* * Variant (b): error via callback. @@ -1184,19 +1183,19 @@ static int tsx_resolve_error_test(void) /* This only applies to "loop-dgram" transport */ if (test_param->type == PJSIP_TRANSPORT_LOOP_DGRAM) { - /* Set loop transport to return delayed error. */ - pjsip_loop_set_failure(loop, 2, NULL); - pjsip_loop_set_send_callback_delay(loop, 10, NULL); - - status = perform_tsx_test(-800, TARGET_URI, FROM_URI, - TEST2_BRANCH_ID, 2, - &pjsip_options_method); - if (status != 0) - return status; - - /* Restore loop transport settings. */ - pjsip_loop_set_failure(loop, 0, NULL); - pjsip_loop_set_send_callback_delay(loop, 0, NULL); + /* Set loop transport to return delayed error. */ + pjsip_loop_set_failure(loop, 2, NULL); + pjsip_loop_set_send_callback_delay(loop, 10, NULL); + + status = perform_tsx_test(-800, TARGET_URI, FROM_URI, + TEST2_BRANCH_ID, 2, + &pjsip_options_method); + if (status != 0) + return status; + + /* Restore loop transport settings. */ + pjsip_loop_set_failure(loop, 0, NULL); + pjsip_loop_set_send_callback_delay(loop, 0, NULL); } return status; @@ -1223,7 +1222,7 @@ static int tsx_terminate_resolving_test(void) /* Start the test. */ status = perform_tsx_test(-900, TARGET_URI, FROM_URI, - TEST3_BRANCH_ID, 2, &pjsip_options_method); + TEST3_BRANCH_ID, 2, &pjsip_options_method); /* Restore delay. */ pjsip_loop_set_send_callback_delay(loop, prev_delay, NULL); @@ -1249,26 +1248,26 @@ static int tsx_retransmit_fail_test(void) pj_status_t status = PJ_SUCCESS; PJ_LOG(3,(THIS_FILE, - " test4: transport fails after several retransmissions test")); + " test4: transport fails after several retransmissions test")); for (i=0; i<(int)PJ_ARRAY_SIZE(delay); ++i) { - PJ_LOG(3,(THIS_FILE, - " variant %c: transport delay %d ms", ('a'+i), delay[i])); + PJ_LOG(3,(THIS_FILE, + " variant %c: transport delay %d ms", ('a'+i), delay[i])); - /* Configure transport delay. */ - pjsip_loop_set_send_callback_delay(loop, delay[i], NULL); + /* Configure transport delay. */ + pjsip_loop_set_send_callback_delay(loop, delay[i], NULL); - /* Restore transport failure mode. */ - pjsip_loop_set_failure(loop, 0, 0); + /* Restore transport failure mode. */ + pjsip_loop_set_failure(loop, 0, 0); - /* Start the test. */ - status = perform_tsx_test(-1000, TARGET_URI, FROM_URI, - TEST4_BRANCH_ID, 6, &pjsip_options_method); + /* Start the test. */ + status = perform_tsx_test(-1000, TARGET_URI, FROM_URI, + TEST4_BRANCH_ID, 6, &pjsip_options_method); - if (status != 0) - break; + if (status != 0) + break; } @@ -1296,8 +1295,8 @@ static int tsx_terminate_after_retransmit_test(void) /* Do the test. */ status = perform_tsx_test(-1100, TARGET_URI, FROM_URI, - TEST5_BRANCH_ID, - 6, &pjsip_options_method); + TEST5_BRANCH_ID, + 6, &pjsip_options_method); /* Done. */ return status; @@ -1314,8 +1313,8 @@ static int tsx_terminate_after_retransmit_test(void) ***************************************************************************** */ static int perform_generic_test( const char *title, - char *branch_id, - const pjsip_method *method) + char *branch_id, + const pjsip_method *method) { int i, status = 0; unsigned delay[] = { 1, 200 }; @@ -1324,21 +1323,21 @@ static int perform_generic_test( const char *title, /* Do the test. */ for (i=0; i<(int)PJ_ARRAY_SIZE(delay); ++i) { - - if (test_param->type == PJSIP_TRANSPORT_LOOP_DGRAM) { - PJ_LOG(3,(THIS_FILE, " variant %c: with %d ms transport delay", - ('a'+i), delay[i])); + + if (test_param->type == PJSIP_TRANSPORT_LOOP_DGRAM) { + PJ_LOG(3,(THIS_FILE, " variant %c: with %d ms transport delay", + ('a'+i), delay[i])); - pjsip_loop_set_delay(loop, delay[i]); - } + pjsip_loop_set_delay(loop, delay[i]); + } - status = perform_tsx_test(-1200, TARGET_URI, FROM_URI, - branch_id, 10, method); - if (status != 0) - return status; + status = perform_tsx_test(-1200, TARGET_URI, FROM_URI, + branch_id, 10, method); + if (status != 0) + return status; - if (test_param->type != PJSIP_TRANSPORT_LOOP_DGRAM) - break; + if (test_param->type != PJSIP_TRANSPORT_LOOP_DGRAM) + break; } pjsip_loop_set_delay(loop, 0); @@ -1367,88 +1366,88 @@ int tsx_uac_test(struct tsx_test_param *param) tp_flag = pjsip_transport_get_flag_from_type((pjsip_transport_type_e)test_param->type); pj_ansi_sprintf(TARGET_URI, "sip:bob@127.0.0.1:%d;transport=%s", - param->port, param->tp_type); + param->port, param->tp_type); pj_ansi_sprintf(FROM_URI, "sip:alice@127.0.0.1:%d;transport=%s", - param->port, param->tp_type); + param->port, param->tp_type); /* Check if loop transport is configured. */ status = pjsip_endpt_acquire_transport(endpt, PJSIP_TRANSPORT_LOOP_DGRAM, - &addr, sizeof(addr), NULL, &loop); + &addr, sizeof(addr), NULL, &loop); if (status != PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, " Error: loop transport is not configured!")); - return -10; + PJ_LOG(3,(THIS_FILE, " Error: loop transport is not configured!")); + return -10; } /* Register modules. */ status = pjsip_endpt_register_module(endpt, &tsx_user); if (status != PJ_SUCCESS) { - app_perror(" Error: unable to register module", status); - return -30; + app_perror(" Error: unable to register module", status); + return -30; } status = pjsip_endpt_register_module(endpt, &msg_receiver); if (status != PJ_SUCCESS) { - app_perror(" Error: unable to register module", status); - return -40; + app_perror(" Error: unable to register module", status); + return -40; } /* TEST1_BRANCH_ID: Basic retransmit and timeout test. */ status = tsx_uac_retransmit_test(); if (status != 0) - return status; + return status; /* TEST2_BRANCH_ID: Resolve error test. */ status = tsx_resolve_error_test(); if (status != 0) - return status; + return status; /* TEST3_BRANCH_ID: UAC terminate while resolving test. */ status = tsx_terminate_resolving_test(); if (status != 0) - return status; + return status; /* TEST4_BRANCH_ID: Transport failed after several retransmissions. * Only applies to loop transport. */ if (test_param->type == PJSIP_TRANSPORT_LOOP_DGRAM) { - status = tsx_retransmit_fail_test(); - if (status != 0) - return status; + status = tsx_retransmit_fail_test(); + if (status != 0) + return status; } /* TEST5_BRANCH_ID: Terminate transaction after several retransmissions - * Only applicable to non-reliable transports. + * Only applicable to non-reliable transports. */ if ((tp_flag & PJSIP_TRANSPORT_RELIABLE) == 0) { - status = tsx_terminate_after_retransmit_test(); - if (status != 0) - return status; + status = tsx_terminate_after_retransmit_test(); + if (status != 0) + return status; } /* TEST6_BRANCH_ID: Successfull non-invite transaction */ status = perform_generic_test("test6: successfull non-invite transaction", - TEST6_BRANCH_ID, &pjsip_options_method); + TEST6_BRANCH_ID, &pjsip_options_method); if (status != 0) - return status; + return status; /* TEST7_BRANCH_ID: Successfull non-invite transaction */ status = perform_generic_test("test7: successfull non-invite transaction " - "with provisional response", - TEST7_BRANCH_ID, &pjsip_options_method); + "with provisional response", + TEST7_BRANCH_ID, &pjsip_options_method); if (status != 0) - return status; + return status; /* TEST8_BRANCH_ID: Failed invite transaction */ status = perform_generic_test("test8: failed invite transaction", - TEST8_BRANCH_ID, &pjsip_invite_method); + TEST8_BRANCH_ID, &pjsip_invite_method); if (status != 0) - return status; + return status; /* TEST9_BRANCH_ID: Failed invite transaction with provisional response */ status = perform_generic_test("test9: failed invite transaction with " - "provisional response", - TEST9_BRANCH_ID, &pjsip_invite_method); + "provisional response", + TEST9_BRANCH_ID, &pjsip_invite_method); if (status != 0) - return status; + return status; pjsip_transport_dec_ref(loop); flush_events(500); @@ -1456,13 +1455,13 @@ int tsx_uac_test(struct tsx_test_param *param) /* Unregister modules. */ status = pjsip_endpt_unregister_module(endpt, &tsx_user); if (status != PJ_SUCCESS) { - app_perror(" Error: unable to unregister module", status); - return -31; + app_perror(" Error: unable to unregister module", status); + return -31; } status = pjsip_endpt_unregister_module(endpt, &msg_receiver); if (status != PJ_SUCCESS) { - app_perror(" Error: unable to unregister module", status); - return -41; + app_perror(" Error: unable to unregister module", status); + return -41; } return 0; diff --git a/pjsip/src/test/tsx_uas_test.c b/pjsip/src/test/tsx_uas_test.c index b998998da2..6a0a9a4b41 100644 --- a/pjsip/src/test/tsx_uas_test.c +++ b/pjsip/src/test/tsx_uas_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -34,64 +33,64 @@ ** transaction user module can identify which test is being carried out. ** ** TEST1_BRANCH_ID - ** Test that non-INVITE transaction returns 2xx response to the correct - ** transport and correctly terminates the transaction. - ** This also checks that transaction is destroyed immediately after - ** it sends final response when reliable transport is used. + ** Test that non-INVITE transaction returns 2xx response to the correct + ** transport and correctly terminates the transaction. + ** This also checks that transaction is destroyed immediately after + ** it sends final response when reliable transport is used. ** ** TEST2_BRANCH_ID - ** As above, for non-2xx final response. + ** As above, for non-2xx final response. ** ** TEST3_BRANCH_ID - ** Transaction correctly progressing to PROCEEDING state when provisional - ** response is sent. + ** Transaction correctly progressing to PROCEEDING state when provisional + ** response is sent. ** ** TEST4_BRANCH_ID - ** Transaction retransmits last response (if any) without notifying - ** transaction user upon receiving request retransmissions on TRYING - ** state + ** Transaction retransmits last response (if any) without notifying + ** transaction user upon receiving request retransmissions on TRYING + ** state ** ** TEST5_BRANCH_ID - ** As above, in PROCEEDING state. + ** As above, in PROCEEDING state. ** ** TEST6_BRANCH_ID - ** As above, in COMPLETED state, with first sending provisional response. - ** (Only applicable for non-reliable transports). + ** As above, in COMPLETED state, with first sending provisional response. + ** (Only applicable for non-reliable transports). ** ** TEST7_BRANCH_ID - ** INVITE transaction MUST retransmit non-2xx final response. + ** INVITE transaction MUST retransmit non-2xx final response. ** ** TEST8_BRANCH_ID - ** As above, for INVITE's 2xx final response (this is PJSIP specific). + ** As above, for INVITE's 2xx final response (this is PJSIP specific). ** ** TEST9_BRANCH_ID - ** INVITE transaction MUST cease retransmission of final response when - ** ACK is received. (Note: PJSIP also retransmit 2xx final response - ** until it's terminated by user). + ** INVITE transaction MUST cease retransmission of final response when + ** ACK is received. (Note: PJSIP also retransmit 2xx final response + ** until it's terminated by user). ** Transaction also MUST terminate in T4 seconds. - ** (Only applicable for non-reliable transports). + ** (Only applicable for non-reliable transports). ** ** TEST11_BRANCH_ID - ** Test scenario where transport fails before response is sent (i.e. - ** in TRYING state). + ** Test scenario where transport fails before response is sent (i.e. + ** in TRYING state). ** ** TEST12_BRANCH_ID - ** As above, after provisional response is sent but before final - ** response is sent (i.e. in PROCEEDING state). + ** As above, after provisional response is sent but before final + ** response is sent (i.e. in PROCEEDING state). ** ** TEST13_BRANCH_ID - ** As above, for INVITE, after final response has been sent but before - ** ACK is received (i.e. in CONNECTED state). + ** As above, for INVITE, after final response has been sent but before + ** ACK is received (i.e. in CONNECTED state). ** ** TEST14_BRANCH_ID - ** When UAS failed to deliver the response with the selected transport, - ** it should try contacting the client with other transport or begin - ** RFC 3263 server resolution procedure. - ** This should be tested on: - ** a. TRYING state (when delivering first response). - ** b. PROCEEDING state (when failed to retransmit last response - ** upon receiving request retransmission). - ** c. COMPLETED state. + ** When UAS failed to deliver the response with the selected transport, + ** it should try contacting the client with other transport or begin + ** RFC 3263 server resolution procedure. + ** This should be tested on: + ** a. TRYING state (when delivering first response). + ** b. PROCEEDING state (when failed to retransmit last response + ** upon receiving request retransmission). + ** c. COMPLETED state. ** **/ @@ -109,23 +108,23 @@ #define TEST12_BRANCH_ID (PJSIP_RFC3261_BRANCH_ID "-UAS-Test12") //#define TEST13_BRANCH_ID (PJSIP_RFC3261_BRANCH_ID "-UAS-Test13") -#define TEST1_STATUS_CODE 200 -#define TEST2_STATUS_CODE 301 -#define TEST3_PROVISIONAL_CODE PJSIP_SC_QUEUED -#define TEST3_STATUS_CODE 202 -#define TEST4_STATUS_CODE 200 -#define TEST4_REQUEST_COUNT 2 -#define TEST5_PROVISIONAL_CODE 100 -#define TEST5_STATUS_CODE 200 -#define TEST5_REQUEST_COUNT 2 -#define TEST5_RESPONSE_COUNT 2 -#define TEST6_PROVISIONAL_CODE 100 -#define TEST6_STATUS_CODE 200 /* Must be final */ -#define TEST6_REQUEST_COUNT 2 -#define TEST6_RESPONSE_COUNT 3 -#define TEST7_STATUS_CODE 301 -#define TEST8_STATUS_CODE 302 -#define TEST9_STATUS_CODE 301 +#define TEST1_STATUS_CODE 200 +#define TEST2_STATUS_CODE 301 +#define TEST3_PROVISIONAL_CODE PJSIP_SC_QUEUED +#define TEST3_STATUS_CODE 202 +#define TEST4_STATUS_CODE 200 +#define TEST4_REQUEST_COUNT 2 +#define TEST5_PROVISIONAL_CODE 100 +#define TEST5_STATUS_CODE 200 +#define TEST5_REQUEST_COUNT 2 +#define TEST5_RESPONSE_COUNT 2 +#define TEST6_PROVISIONAL_CODE 100 +#define TEST6_STATUS_CODE 200 /* Must be final */ +#define TEST6_REQUEST_COUNT 2 +#define TEST6_RESPONSE_COUNT 3 +#define TEST7_STATUS_CODE 301 +#define TEST8_STATUS_CODE 302 +#define TEST9_STATUS_CODE 301 #define TEST4_TITLE "test4: absorbing request retransmission" @@ -139,10 +138,10 @@ static struct tsx_test_param *test_param; static unsigned tp_flag; -#define TEST_TIMEOUT_ERROR -30 +#define TEST_TIMEOUT_ERROR -30 // An effort to accommodate CPU load spike on some test machines. -#define MAX_ALLOWED_DIFF 500 //150 +#define MAX_ALLOWED_DIFF 500 //150 static void tsx_user_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e); static pj_bool_t on_rx_message(pjsip_rx_data *rdata); @@ -150,37 +149,37 @@ static pj_bool_t on_rx_message(pjsip_rx_data *rdata); /* UAC transaction user module. */ static pjsip_module tsx_user = { - NULL, NULL, /* prev and next */ - { "Tsx-UAS-User", 12}, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION-1, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - NULL, /* on_rx_request() */ - NULL, /* on_rx_response() */ - NULL, /* on_tx_request() */ - NULL, /* on_tx_response() */ - &tsx_user_on_tsx_state, /* on_tsx_state() */ + NULL, NULL, /* prev and next */ + { "Tsx-UAS-User", 12}, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION-1, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request() */ + NULL, /* on_tx_response() */ + &tsx_user_on_tsx_state, /* on_tsx_state() */ }; /* Module to send request. */ static pjsip_module msg_sender = { - NULL, NULL, /* prev and next */ - { "Msg-Sender", 10}, /* Name. */ - -1, /* Id */ - PJSIP_MOD_PRIORITY_APPLICATION-1, /* Priority */ - NULL, /* load() */ - NULL, /* start() */ - NULL, /* stop() */ - NULL, /* unload() */ - &on_rx_message, /* on_rx_request() */ - &on_rx_message, /* on_rx_response() */ - NULL, /* on_tx_request() */ - NULL, /* on_tx_response() */ - NULL, /* on_tsx_state() */ + NULL, NULL, /* prev and next */ + { "Msg-Sender", 10}, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_APPLICATION-1, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + &on_rx_message, /* on_rx_request() */ + &on_rx_message, /* on_rx_response() */ + NULL, /* on_tx_request() */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ }; /* Static vars, which will be reset on each test. */ @@ -202,13 +201,13 @@ static pj_str_t tsx_key = { key_buf, 0 }; /* Timer to send response via transaction. */ struct response { - pj_str_t tsx_key; + pj_str_t tsx_key; pjsip_tx_data *tdata; }; /* Timer callback to send response. */ static void send_response_timer( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { pjsip_transaction *tsx; struct response *r = (struct response*) entry->user_data; @@ -218,18 +217,18 @@ static void send_response_timer( pj_timer_heap_t *timer_heap, tsx = pjsip_tsx_layer_find_tsx(&r->tsx_key, PJ_TRUE); if (!tsx) { - PJ_LOG(3,(THIS_FILE," error: timer unable to find transaction")); - pjsip_tx_data_dec_ref(r->tdata); - return; + PJ_LOG(3,(THIS_FILE," error: timer unable to find transaction")); + pjsip_tx_data_dec_ref(r->tdata); + return; } status = pjsip_tsx_send_msg(tsx, r->tdata); if (status != PJ_SUCCESS) { - // Some tests do expect failure! - //PJ_LOG(3,(THIS_FILE," error: timer unable to send response")); - pj_grp_lock_release(tsx->grp_lock); - pjsip_tx_data_dec_ref(r->tdata); - return; + // Some tests do expect failure! + //PJ_LOG(3,(THIS_FILE," error: timer unable to send response")); + pj_grp_lock_release(tsx->grp_lock); + pjsip_tx_data_dec_ref(r->tdata); + return; } pj_grp_lock_release(tsx->grp_lock); @@ -237,35 +236,35 @@ static void send_response_timer( pj_timer_heap_t *timer_heap, /* Utility to send response. */ static void send_response( pjsip_rx_data *rdata, - pjsip_transaction *tsx, - int status_code ) + pjsip_transaction *tsx, + int status_code ) { pj_status_t status; pjsip_tx_data *tdata; status = pjsip_endpt_create_response( endpt, rdata, status_code, NULL, - &tdata); + &tdata); if (status != PJ_SUCCESS) { - app_perror(" error: unable to create response", status); - test_complete = -196; - return; + app_perror(" error: unable to create response", status); + test_complete = -196; + return; } status = pjsip_tsx_send_msg(tsx, tdata); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - // Some tests do expect failure! - //app_perror(" error: unable to send response", status); - //test_complete = -197; - return; + pjsip_tx_data_dec_ref(tdata); + // Some tests do expect failure! + //app_perror(" error: unable to send response", status); + //test_complete = -197; + return; } } /* Schedule timer to send response for the specified UAS transaction */ static void schedule_send_response( pjsip_rx_data *rdata, - const pj_str_t *tsx_key_, - int status_code, - int msec_delay ) + const pj_str_t *tsx_key_, + int status_code, + int msec_delay ) { pj_status_t status; pjsip_tx_data *tdata; @@ -274,11 +273,11 @@ static void schedule_send_response( pjsip_rx_data *rdata, pj_time_val delay; status = pjsip_endpt_create_response( endpt, rdata, status_code, NULL, - &tdata); + &tdata); if (status != PJ_SUCCESS) { - app_perror(" error: unable to create response", status); - test_complete = -198; - return; + app_perror(" error: unable to create response", status); + test_complete = -198; + return; } r = PJ_POOL_ALLOC_T(tdata->pool, struct response); @@ -295,10 +294,10 @@ static void schedule_send_response( pjsip_rx_data *rdata, status = pjsip_endpt_schedule_timer(endpt, t, &delay); if (status != PJ_SUCCESS) { - pjsip_tx_data_dec_ref(tdata); - app_perror(" error: unable to schedule timer", status); - test_complete = -199; - return; + pjsip_tx_data_dec_ref(tdata); + app_perror(" error: unable to schedule timer", status); + test_complete = -199; + return; } } @@ -310,18 +309,18 @@ static void terminate_our_tsx(int status_code) tsx = pjsip_tsx_layer_find_tsx(&tsx_key, PJ_TRUE); if (!tsx) { - PJ_LOG(3,(THIS_FILE," error: timer unable to find transaction")); - return; + PJ_LOG(3,(THIS_FILE," error: timer unable to find transaction")); + return; } pjsip_tsx_terminate(tsx, status_code); pj_grp_lock_release(tsx->grp_lock); } -#if 0 /* Unused for now */ +#if 0 /* Unused for now */ /* Timer callback to terminate transaction. */ static void terminate_tsx_timer( pj_timer_heap_t *timer_heap, - struct pj_timer_entry *entry) + struct pj_timer_entry *entry) { terminate_our_tsx(entry->id); } @@ -329,8 +328,8 @@ static void terminate_tsx_timer( pj_timer_heap_t *timer_heap, /* Schedule timer to terminate transaction. */ static void schedule_terminate_tsx( pjsip_transaction *tsx, - int status_code, - int msec_delay ) + int status_code, + int msec_delay ) { pj_time_val delay; @@ -355,388 +354,388 @@ static void schedule_terminate_tsx( pjsip_transaction *tsx, static void tsx_user_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e) { if (pj_stricmp2(&tsx->branch, TEST1_BRANCH_ID)==0 || - pj_stricmp2(&tsx->branch, TEST2_BRANCH_ID)==0) + pj_stricmp2(&tsx->branch, TEST2_BRANCH_ID)==0) { - /* - * TEST1_BRANCH_ID tests that non-INVITE transaction transmits final - * response using correct transport and terminates transaction after - * T4 (PJSIP_T4_TIMEOUT, 5 seconds). - * - * TEST2_BRANCH_ID does similar test for non-2xx final response. - */ - int status_code = (pj_stricmp2(&tsx->branch, TEST1_BRANCH_ID)==0) ? - TEST1_STATUS_CODE : TEST2_STATUS_CODE; - - if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - test_complete = 1; - - /* Check that status code is status_code. */ - if (tsx->status_code != status_code) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -100; - } - - /* Previous state must be completed. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -101; - } - - } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { - - /* Previous state must be TRYING. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_TRYING) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -102; - } - } + /* + * TEST1_BRANCH_ID tests that non-INVITE transaction transmits final + * response using correct transport and terminates transaction after + * T4 (PJSIP_T4_TIMEOUT, 5 seconds). + * + * TEST2_BRANCH_ID does similar test for non-2xx final response. + */ + int status_code = (pj_stricmp2(&tsx->branch, TEST1_BRANCH_ID)==0) ? + TEST1_STATUS_CODE : TEST2_STATUS_CODE; + + if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + test_complete = 1; + + /* Check that status code is status_code. */ + if (tsx->status_code != status_code) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -100; + } + + /* Previous state must be completed. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -101; + } + + } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { + + /* Previous state must be TRYING. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_TRYING) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -102; + } + } } else if (pj_stricmp2(&tsx->branch, TEST3_BRANCH_ID)==0) { - /* - * TEST3_BRANCH_ID tests sending provisional response. - */ - if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - test_complete = 1; - - /* Check that status code is status_code. */ - if (tsx->status_code != TEST3_STATUS_CODE) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -110; - } - - /* Previous state must be completed. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -111; - } - - } else if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) { - - /* Previous state must be TRYING. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_TRYING) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -112; - } - - /* Check that status code is status_code. */ - if (tsx->status_code != TEST3_PROVISIONAL_CODE) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -113; - } - - /* Check that event must be TX_MSG */ - if (e->body.tsx_state.type != PJSIP_EVENT_TX_MSG) { - PJ_LOG(3,(THIS_FILE, " error: incorrect event")); - test_complete = -114; - } - - } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { - - /* Previous state must be PROCEEDING. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_PROCEEDING) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -115; - } - - /* Check that status code is status_code. */ - if (tsx->status_code != TEST3_STATUS_CODE) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -116; - } - - /* Check that event must be TX_MSG */ - if (e->body.tsx_state.type != PJSIP_EVENT_TX_MSG) { - PJ_LOG(3,(THIS_FILE, " error: incorrect event")); - test_complete = -117; - } - - } + /* + * TEST3_BRANCH_ID tests sending provisional response. + */ + if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + test_complete = 1; + + /* Check that status code is status_code. */ + if (tsx->status_code != TEST3_STATUS_CODE) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -110; + } + + /* Previous state must be completed. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -111; + } + + } else if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) { + + /* Previous state must be TRYING. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_TRYING) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -112; + } + + /* Check that status code is status_code. */ + if (tsx->status_code != TEST3_PROVISIONAL_CODE) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -113; + } + + /* Check that event must be TX_MSG */ + if (e->body.tsx_state.type != PJSIP_EVENT_TX_MSG) { + PJ_LOG(3,(THIS_FILE, " error: incorrect event")); + test_complete = -114; + } + + } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { + + /* Previous state must be PROCEEDING. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_PROCEEDING) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -115; + } + + /* Check that status code is status_code. */ + if (tsx->status_code != TEST3_STATUS_CODE) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -116; + } + + /* Check that event must be TX_MSG */ + if (e->body.tsx_state.type != PJSIP_EVENT_TX_MSG) { + PJ_LOG(3,(THIS_FILE, " error: incorrect event")); + test_complete = -117; + } + + } } else if (pj_stricmp2(&tsx->branch, TEST4_BRANCH_ID)==0) { - /* - * TEST4_BRANCH_ID tests receiving retransmissions in TRYING state. - */ - if (tsx->state == PJSIP_TSX_STATE_TRYING) { - /* Request is received. */ - } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - /* Check that status code is status_code. */ - if (tsx->status_code != TEST4_STATUS_CODE) { - PJ_LOG(3,(THIS_FILE, - " error: incorrect status code %d " - "(expecting %d)", tsx->status_code, - TEST4_STATUS_CODE)); - test_complete = -120; - } - - /* Previous state. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_TRYING) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -121; - } - - } else if (tsx->state != PJSIP_TSX_STATE_DESTROYED) - { - PJ_LOG(3,(THIS_FILE, " error: unexpected state %s (122)", - pjsip_tsx_state_str(tsx->state))); - test_complete = -122; - - } + /* + * TEST4_BRANCH_ID tests receiving retransmissions in TRYING state. + */ + if (tsx->state == PJSIP_TSX_STATE_TRYING) { + /* Request is received. */ + } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + /* Check that status code is status_code. */ + if (tsx->status_code != TEST4_STATUS_CODE) { + PJ_LOG(3,(THIS_FILE, + " error: incorrect status code %d " + "(expecting %d)", tsx->status_code, + TEST4_STATUS_CODE)); + test_complete = -120; + } + + /* Previous state. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_TRYING) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -121; + } + + } else if (tsx->state != PJSIP_TSX_STATE_DESTROYED) + { + PJ_LOG(3,(THIS_FILE, " error: unexpected state %s (122)", + pjsip_tsx_state_str(tsx->state))); + test_complete = -122; + + } } else if (pj_stricmp2(&tsx->branch, TEST5_BRANCH_ID)==0) { - /* - * TEST5_BRANCH_ID tests receiving retransmissions in PROCEEDING state - */ - if (tsx->state == PJSIP_TSX_STATE_TRYING) { - /* Request is received. */ + /* + * TEST5_BRANCH_ID tests receiving retransmissions in PROCEEDING state + */ + if (tsx->state == PJSIP_TSX_STATE_TRYING) { + /* Request is received. */ - } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - /* Check that status code is status_code. */ - if (tsx->status_code != TEST5_STATUS_CODE) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -130; - } + /* Check that status code is status_code. */ + if (tsx->status_code != TEST5_STATUS_CODE) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -130; + } - /* Previous state. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_PROCEEDING) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -131; - } + /* Previous state. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_PROCEEDING) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -131; + } - } else if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) { + } else if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) { - /* Check status code. */ - if (tsx->status_code != TEST5_PROVISIONAL_CODE) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -132; - } + /* Check status code. */ + if (tsx->status_code != TEST5_PROVISIONAL_CODE) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -132; + } - } else if (tsx->state != PJSIP_TSX_STATE_DESTROYED) { - PJ_LOG(3,(THIS_FILE, " error: unexpected state %s (133)", - pjsip_tsx_state_str(tsx->state))); - test_complete = -133; + } else if (tsx->state != PJSIP_TSX_STATE_DESTROYED) { + PJ_LOG(3,(THIS_FILE, " error: unexpected state %s (133)", + pjsip_tsx_state_str(tsx->state))); + test_complete = -133; - } + } } else if (pj_stricmp2(&tsx->branch, TEST6_BRANCH_ID)==0) { - /* - * TEST6_BRANCH_ID tests receiving retransmissions in COMPLETED state - */ - if (tsx->state == PJSIP_TSX_STATE_TRYING) { - /* Request is received. */ - - } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - /* Check that status code is status_code. */ - if (tsx->status_code != TEST6_STATUS_CODE) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code %d " - "(expecting %d)", tsx->status_code, - TEST6_STATUS_CODE)); - test_complete = -140; - } - - /* Previous state. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -141; - } - - } else if (tsx->state != PJSIP_TSX_STATE_PROCEEDING && - tsx->state != PJSIP_TSX_STATE_COMPLETED && - tsx->state != PJSIP_TSX_STATE_DESTROYED) - { - PJ_LOG(3,(THIS_FILE, " error: unexpected state %s (142)", - pjsip_tsx_state_str(tsx->state))); - test_complete = -142; - - } + /* + * TEST6_BRANCH_ID tests receiving retransmissions in COMPLETED state + */ + if (tsx->state == PJSIP_TSX_STATE_TRYING) { + /* Request is received. */ + + } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + /* Check that status code is status_code. */ + if (tsx->status_code != TEST6_STATUS_CODE) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code %d " + "(expecting %d)", tsx->status_code, + TEST6_STATUS_CODE)); + test_complete = -140; + } + + /* Previous state. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -141; + } + + } else if (tsx->state != PJSIP_TSX_STATE_PROCEEDING && + tsx->state != PJSIP_TSX_STATE_COMPLETED && + tsx->state != PJSIP_TSX_STATE_DESTROYED) + { + PJ_LOG(3,(THIS_FILE, " error: unexpected state %s (142)", + pjsip_tsx_state_str(tsx->state))); + test_complete = -142; + + } } else if (pj_stricmp2(&tsx->branch, TEST7_BRANCH_ID)==0 || - pj_stricmp2(&tsx->branch, TEST8_BRANCH_ID)==0) + pj_stricmp2(&tsx->branch, TEST8_BRANCH_ID)==0) { - /* - * TEST7_BRANCH_ID and TEST8_BRANCH_ID test retransmission of - * INVITE final response - */ - int code; + /* + * TEST7_BRANCH_ID and TEST8_BRANCH_ID test retransmission of + * INVITE final response + */ + int code; - if (pj_stricmp2(&tsx->branch, TEST7_BRANCH_ID) == 0) - code = TEST7_STATUS_CODE; - else - code = TEST8_STATUS_CODE; + if (pj_stricmp2(&tsx->branch, TEST7_BRANCH_ID) == 0) + code = TEST7_STATUS_CODE; + else + code = TEST8_STATUS_CODE; - if (tsx->state == PJSIP_TSX_STATE_TRYING) { - /* Request is received. */ + if (tsx->state == PJSIP_TSX_STATE_TRYING) { + /* Request is received. */ - } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - if (test_complete == 0) - test_complete = 1; + if (test_complete == 0) + test_complete = 1; - /* Check status code. */ - if (tsx->status_code != PJSIP_SC_TSX_TIMEOUT) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -150; - } + /* Check status code. */ + if (tsx->status_code != PJSIP_SC_TSX_TIMEOUT) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -150; + } - /* Previous state. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -151; - } + /* Previous state. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -151; + } - /* Check the number of retransmissions */ - if (tp_flag & PJSIP_TRANSPORT_RELIABLE) { + /* Check the number of retransmissions */ + if (tp_flag & PJSIP_TRANSPORT_RELIABLE) { - if (tsx->retransmit_count != 0) { - PJ_LOG(3,(THIS_FILE, " error: should not retransmit")); - test_complete = -1510; - } + if (tsx->retransmit_count != 0) { + PJ_LOG(3,(THIS_FILE, " error: should not retransmit")); + test_complete = -1510; + } - } else { + } else { - if (tsx->retransmit_count != 10) { - PJ_LOG(3,(THIS_FILE, - " error: incorrect retransmit count %d " - "(expecting 10)", - tsx->retransmit_count)); - test_complete = -1510; - } + if (tsx->retransmit_count != 10) { + PJ_LOG(3,(THIS_FILE, + " error: incorrect retransmit count %d " + "(expecting 10)", + tsx->retransmit_count)); + test_complete = -1510; + } - } + } - } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { + } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { - /* Check that status code is status_code. */ - if (tsx->status_code != code) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -152; - } + /* Check that status code is status_code. */ + if (tsx->status_code != code) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -152; + } - /* Previous state. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_TRYING) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -153; - } + /* Previous state. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_TRYING) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -153; + } - } else if (tsx->state != PJSIP_TSX_STATE_DESTROYED) { + } else if (tsx->state != PJSIP_TSX_STATE_DESTROYED) { - PJ_LOG(3,(THIS_FILE, " error: unexpected state (154)")); - test_complete = -154; + PJ_LOG(3,(THIS_FILE, " error: unexpected state (154)")); + test_complete = -154; - } + } } else if (pj_stricmp2(&tsx->branch, TEST9_BRANCH_ID)==0) { - /* - * TEST9_BRANCH_ID tests that retransmission of INVITE final response - * must cease when ACK is received. - */ + /* + * TEST9_BRANCH_ID tests that retransmission of INVITE final response + * must cease when ACK is received. + */ - if (tsx->state == PJSIP_TSX_STATE_TRYING) { - /* Request is received. */ + if (tsx->state == PJSIP_TSX_STATE_TRYING) { + /* Request is received. */ - } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - if (test_complete == 0) - test_complete = 1; + if (test_complete == 0) + test_complete = 1; - /* Check status code. */ - if (tsx->status_code != TEST9_STATUS_CODE) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -160; - } + /* Check status code. */ + if (tsx->status_code != TEST9_STATUS_CODE) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -160; + } - /* Previous state. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_CONFIRMED) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -161; - } + /* Previous state. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_CONFIRMED) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -161; + } - } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { + } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED) { - /* Check that status code is status_code. */ - if (tsx->status_code != TEST9_STATUS_CODE) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -162; - } + /* Check that status code is status_code. */ + if (tsx->status_code != TEST9_STATUS_CODE) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -162; + } - /* Previous state. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_TRYING) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -163; - } + /* Previous state. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_TRYING) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -163; + } - } else if (tsx->state == PJSIP_TSX_STATE_CONFIRMED) { + } else if (tsx->state == PJSIP_TSX_STATE_CONFIRMED) { - /* Check that status code is status_code. */ - if (tsx->status_code != TEST9_STATUS_CODE) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -164; - } + /* Check that status code is status_code. */ + if (tsx->status_code != TEST9_STATUS_CODE) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -164; + } - /* Previous state. */ - if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { - PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); - test_complete = -165; - } + /* Previous state. */ + if (e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED) { + PJ_LOG(3,(THIS_FILE, " error: incorrect prev_state")); + test_complete = -165; + } - } else if (tsx->state != PJSIP_TSX_STATE_DESTROYED) { + } else if (tsx->state != PJSIP_TSX_STATE_DESTROYED) { - PJ_LOG(3,(THIS_FILE, " error: unexpected state (166)")); - test_complete = -166; + PJ_LOG(3,(THIS_FILE, " error: unexpected state (166)")); + test_complete = -166; - } + } } else if (pj_stricmp2(&tsx->branch, TEST10_BRANCH_ID)==0 || - pj_stricmp2(&tsx->branch, TEST12_BRANCH_ID)==0) + pj_stricmp2(&tsx->branch, TEST12_BRANCH_ID)==0) { - if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - if (!test_complete) - test_complete = 1; - - if (tsx->status_code != PJSIP_SC_TSX_TRANSPORT_ERROR) { - PJ_LOG(3,(THIS_FILE," error: incorrect status code" - " (expecting %d, got %d)", - PJSIP_SC_TSX_TRANSPORT_ERROR, - tsx->status_code)); - test_complete = -170; - } - } + if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + if (!test_complete) + test_complete = 1; + + if (tsx->status_code != PJSIP_SC_TSX_TRANSPORT_ERROR) { + PJ_LOG(3,(THIS_FILE," error: incorrect status code" + " (expecting %d, got %d)", + PJSIP_SC_TSX_TRANSPORT_ERROR, + tsx->status_code)); + test_complete = -170; + } + } } else if (pj_stricmp2(&tsx->branch, TEST11_BRANCH_ID)==0) { - if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { - - if (!test_complete) - test_complete = 1; - - if (tsx->status_code != PJSIP_SC_TSX_TRANSPORT_ERROR && - tsx->status_code != PJSIP_SC_OK) - { - PJ_LOG(3,(THIS_FILE," error: incorrect status code" - " (expecting %d, got %d)", - PJSIP_SC_TSX_TRANSPORT_ERROR, - tsx->status_code)); - test_complete = -170; - } - } + if (tsx->state == PJSIP_TSX_STATE_TERMINATED) { + + if (!test_complete) + test_complete = 1; + + if (tsx->status_code != PJSIP_SC_TSX_TRANSPORT_ERROR && + tsx->status_code != PJSIP_SC_OK) + { + PJ_LOG(3,(THIS_FILE," error: incorrect status code" + " (expecting %d, got %d)", + PJSIP_SC_TSX_TRANSPORT_ERROR, + tsx->status_code)); + test_complete = -170; + } + } } } @@ -761,424 +760,424 @@ static pj_bool_t on_rx_message(pjsip_rx_data *rdata) pj_status_t status; if (pj_stricmp2(&branch_param, TEST1_BRANCH_ID) == 0 || - pj_stricmp2(&branch_param, TEST2_BRANCH_ID) == 0) + pj_stricmp2(&branch_param, TEST2_BRANCH_ID) == 0) { - /* - * TEST1_BRANCH_ID tests that non-INVITE transaction transmits 2xx - * final response using correct transport and terminates transaction - * after 32 seconds. - * - * TEST2_BRANCH_ID performs similar test for non-2xx final response. - */ - int status_code = (pj_stricmp2(&branch_param, TEST1_BRANCH_ID) == 0) ? - TEST1_STATUS_CODE : TEST2_STATUS_CODE; - - if (msg->type == PJSIP_REQUEST_MSG) { - /* On received request, create UAS and respond with final - * response. - */ - pjsip_transaction *tsx; - - status = pjsip_tsx_create_uas(&tsx_user, rdata, &tsx); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to create transaction", status); - test_complete = -110; - return PJ_TRUE; - } - pjsip_tsx_recv_msg(tsx, rdata); - - save_key(tsx); - send_response(rdata, tsx, status_code); - - } else { - /* Verify the response received. */ - - ++recv_count; - - /* Verify status code. */ - if (msg->line.status.code != status_code) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -113; - } - - /* Verify that no retransmissions is received. */ - if (recv_count > 1) { - PJ_LOG(3,(THIS_FILE, " error: retransmission received")); - test_complete = -114; - } - - } - return PJ_TRUE; + /* + * TEST1_BRANCH_ID tests that non-INVITE transaction transmits 2xx + * final response using correct transport and terminates transaction + * after 32 seconds. + * + * TEST2_BRANCH_ID performs similar test for non-2xx final response. + */ + int status_code = (pj_stricmp2(&branch_param, TEST1_BRANCH_ID) == 0) ? + TEST1_STATUS_CODE : TEST2_STATUS_CODE; + + if (msg->type == PJSIP_REQUEST_MSG) { + /* On received request, create UAS and respond with final + * response. + */ + pjsip_transaction *tsx; + + status = pjsip_tsx_create_uas(&tsx_user, rdata, &tsx); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to create transaction", status); + test_complete = -110; + return PJ_TRUE; + } + pjsip_tsx_recv_msg(tsx, rdata); + + save_key(tsx); + send_response(rdata, tsx, status_code); + + } else { + /* Verify the response received. */ + + ++recv_count; + + /* Verify status code. */ + if (msg->line.status.code != status_code) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -113; + } + + /* Verify that no retransmissions is received. */ + if (recv_count > 1) { + PJ_LOG(3,(THIS_FILE, " error: retransmission received")); + test_complete = -114; + } + + } + return PJ_TRUE; } else if (pj_stricmp2(&branch_param, TEST3_BRANCH_ID) == 0) { - /* TEST3_BRANCH_ID tests provisional response. */ - - if (msg->type == PJSIP_REQUEST_MSG) { - /* On received request, create UAS and respond with provisional - * response, then schedule timer to send final response. - */ - pjsip_transaction *tsx; - - status = pjsip_tsx_create_uas(&tsx_user, rdata, &tsx); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to create transaction", status); - test_complete = -116; - return PJ_TRUE; - } - pjsip_tsx_recv_msg(tsx, rdata); - - save_key(tsx); - - send_response(rdata, tsx, TEST3_PROVISIONAL_CODE); - schedule_send_response(rdata, &tsx->transaction_key, - TEST3_STATUS_CODE, 2000); - - } else { - /* Verify the response received. */ - - ++recv_count; - - if (recv_count == 1) { - /* Verify status code. */ - if (msg->line.status.code != TEST3_PROVISIONAL_CODE) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -123; - } - } else if (recv_count == 2) { - /* Verify status code. */ - if (msg->line.status.code != TEST3_STATUS_CODE) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); - test_complete = -124; - } - } else { - PJ_LOG(3,(THIS_FILE, " error: retransmission received")); - test_complete = -125; - } - - } - return PJ_TRUE; + /* TEST3_BRANCH_ID tests provisional response. */ + + if (msg->type == PJSIP_REQUEST_MSG) { + /* On received request, create UAS and respond with provisional + * response, then schedule timer to send final response. + */ + pjsip_transaction *tsx; + + status = pjsip_tsx_create_uas(&tsx_user, rdata, &tsx); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to create transaction", status); + test_complete = -116; + return PJ_TRUE; + } + pjsip_tsx_recv_msg(tsx, rdata); + + save_key(tsx); + + send_response(rdata, tsx, TEST3_PROVISIONAL_CODE); + schedule_send_response(rdata, &tsx->transaction_key, + TEST3_STATUS_CODE, 2000); + + } else { + /* Verify the response received. */ + + ++recv_count; + + if (recv_count == 1) { + /* Verify status code. */ + if (msg->line.status.code != TEST3_PROVISIONAL_CODE) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -123; + } + } else if (recv_count == 2) { + /* Verify status code. */ + if (msg->line.status.code != TEST3_STATUS_CODE) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code")); + test_complete = -124; + } + } else { + PJ_LOG(3,(THIS_FILE, " error: retransmission received")); + test_complete = -125; + } + + } + return PJ_TRUE; } else if (pj_stricmp2(&branch_param, TEST4_BRANCH_ID) == 0 || - pj_stricmp2(&branch_param, TEST5_BRANCH_ID) == 0 || - pj_stricmp2(&branch_param, TEST6_BRANCH_ID) == 0) + pj_stricmp2(&branch_param, TEST5_BRANCH_ID) == 0 || + pj_stricmp2(&branch_param, TEST6_BRANCH_ID) == 0) { - /* TEST4_BRANCH_ID: absorbs retransmissions in TRYING state. */ - /* TEST5_BRANCH_ID: retransmit last response in PROCEEDING state. */ - /* TEST6_BRANCH_ID: retransmit last response in COMPLETED state. */ - - if (msg->type == PJSIP_REQUEST_MSG) { - /* On received request, create UAS. */ - pjsip_transaction *tsx; - - PJ_LOG(4,(THIS_FILE, " received request (probably retransmission)")); - - status = pjsip_tsx_create_uas(&tsx_user, rdata, &tsx); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to create transaction", status); - test_complete = -130; - return PJ_TRUE; - } - - pjsip_tsx_recv_msg(tsx, rdata); - save_key(tsx); - - if (pj_stricmp2(&branch_param, TEST4_BRANCH_ID) == 0) { - - } else if (pj_stricmp2(&branch_param, TEST5_BRANCH_ID) == 0) { - send_response(rdata, tsx, TEST5_PROVISIONAL_CODE); - - } else if (pj_stricmp2(&branch_param, TEST6_BRANCH_ID) == 0) { - PJ_LOG(4,(THIS_FILE, " sending provisional response")); - send_response(rdata, tsx, TEST6_PROVISIONAL_CODE); - PJ_LOG(4,(THIS_FILE, " sending final response")); - send_response(rdata, tsx, TEST6_STATUS_CODE); - } - - } else { - /* Verify the response received. */ - - PJ_LOG(4,(THIS_FILE, " received response number %d", recv_count)); - - ++recv_count; - - if (pj_stricmp2(&branch_param, TEST4_BRANCH_ID) == 0) { - PJ_LOG(3,(THIS_FILE, " error: not expecting response!")); - test_complete = -132; - - } else if (pj_stricmp2(&branch_param, TEST5_BRANCH_ID) == 0) { - - if (rdata->msg_info.msg->line.status.code!=TEST5_PROVISIONAL_CODE) { - PJ_LOG(3,(THIS_FILE, " error: incorrect status code!")); - test_complete = -133; - - } - if (recv_count > TEST5_RESPONSE_COUNT) { - PJ_LOG(3,(THIS_FILE, " error: not expecting response!")); - test_complete = -134; - } - - } else if (pj_stricmp2(&branch_param, TEST6_BRANCH_ID) == 0) { - - int code = rdata->msg_info.msg->line.status.code; - - switch (recv_count) { - case 1: - if (code != TEST6_PROVISIONAL_CODE) { - PJ_LOG(3,(THIS_FILE, " error: invalid code!")); - test_complete = -135; - } - break; - case 2: - case 3: - if (code != TEST6_STATUS_CODE) { - PJ_LOG(3,(THIS_FILE, " error: invalid code %d " - "(expecting %d)", code, TEST6_STATUS_CODE)); - test_complete = -136; - } - break; - default: - PJ_LOG(3,(THIS_FILE, " error: not expecting response")); - test_complete = -137; - break; - } - } - } - return PJ_TRUE; + /* TEST4_BRANCH_ID: absorbs retransmissions in TRYING state. */ + /* TEST5_BRANCH_ID: retransmit last response in PROCEEDING state. */ + /* TEST6_BRANCH_ID: retransmit last response in COMPLETED state. */ + + if (msg->type == PJSIP_REQUEST_MSG) { + /* On received request, create UAS. */ + pjsip_transaction *tsx; + + PJ_LOG(4,(THIS_FILE, " received request (probably retransmission)")); + + status = pjsip_tsx_create_uas(&tsx_user, rdata, &tsx); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to create transaction", status); + test_complete = -130; + return PJ_TRUE; + } + + pjsip_tsx_recv_msg(tsx, rdata); + save_key(tsx); + + if (pj_stricmp2(&branch_param, TEST4_BRANCH_ID) == 0) { + + } else if (pj_stricmp2(&branch_param, TEST5_BRANCH_ID) == 0) { + send_response(rdata, tsx, TEST5_PROVISIONAL_CODE); + + } else if (pj_stricmp2(&branch_param, TEST6_BRANCH_ID) == 0) { + PJ_LOG(4,(THIS_FILE, " sending provisional response")); + send_response(rdata, tsx, TEST6_PROVISIONAL_CODE); + PJ_LOG(4,(THIS_FILE, " sending final response")); + send_response(rdata, tsx, TEST6_STATUS_CODE); + } + + } else { + /* Verify the response received. */ + + PJ_LOG(4,(THIS_FILE, " received response number %d", recv_count)); + + ++recv_count; + + if (pj_stricmp2(&branch_param, TEST4_BRANCH_ID) == 0) { + PJ_LOG(3,(THIS_FILE, " error: not expecting response!")); + test_complete = -132; + + } else if (pj_stricmp2(&branch_param, TEST5_BRANCH_ID) == 0) { + + if (rdata->msg_info.msg->line.status.code!=TEST5_PROVISIONAL_CODE) { + PJ_LOG(3,(THIS_FILE, " error: incorrect status code!")); + test_complete = -133; + + } + if (recv_count > TEST5_RESPONSE_COUNT) { + PJ_LOG(3,(THIS_FILE, " error: not expecting response!")); + test_complete = -134; + } + + } else if (pj_stricmp2(&branch_param, TEST6_BRANCH_ID) == 0) { + + int code = rdata->msg_info.msg->line.status.code; + + switch (recv_count) { + case 1: + if (code != TEST6_PROVISIONAL_CODE) { + PJ_LOG(3,(THIS_FILE, " error: invalid code!")); + test_complete = -135; + } + break; + case 2: + case 3: + if (code != TEST6_STATUS_CODE) { + PJ_LOG(3,(THIS_FILE, " error: invalid code %d " + "(expecting %d)", code, TEST6_STATUS_CODE)); + test_complete = -136; + } + break; + default: + PJ_LOG(3,(THIS_FILE, " error: not expecting response")); + test_complete = -137; + break; + } + } + } + return PJ_TRUE; } else if (pj_stricmp2(&branch_param, TEST7_BRANCH_ID) == 0 || - pj_stricmp2(&branch_param, TEST8_BRANCH_ID) == 0) + pj_stricmp2(&branch_param, TEST8_BRANCH_ID) == 0) { - /* - * TEST7_BRANCH_ID and TEST8_BRANCH_ID test the retransmission - * of INVITE final response - */ - if (msg->type == PJSIP_REQUEST_MSG) { + /* + * TEST7_BRANCH_ID and TEST8_BRANCH_ID test the retransmission + * of INVITE final response + */ + if (msg->type == PJSIP_REQUEST_MSG) { - /* On received request, create UAS. */ - pjsip_transaction *tsx; + /* On received request, create UAS. */ + pjsip_transaction *tsx; - status = pjsip_tsx_create_uas(&tsx_user, rdata, &tsx); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to create transaction", status); - test_complete = -140; - return PJ_TRUE; - } + status = pjsip_tsx_create_uas(&tsx_user, rdata, &tsx); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to create transaction", status); + test_complete = -140; + return PJ_TRUE; + } - pjsip_tsx_recv_msg(tsx, rdata); - save_key(tsx); + pjsip_tsx_recv_msg(tsx, rdata); + save_key(tsx); - if (pj_stricmp2(&branch_param, TEST7_BRANCH_ID) == 0) { + if (pj_stricmp2(&branch_param, TEST7_BRANCH_ID) == 0) { - send_response(rdata, tsx, TEST7_STATUS_CODE); + send_response(rdata, tsx, TEST7_STATUS_CODE); - } else { + } else { - send_response(rdata, tsx, TEST8_STATUS_CODE); + send_response(rdata, tsx, TEST8_STATUS_CODE); - } + } - } else { - int code; + } else { + int code; - ++recv_count; + ++recv_count; - if (pj_stricmp2(&branch_param, TEST7_BRANCH_ID) == 0) - code = TEST7_STATUS_CODE; - else - code = TEST8_STATUS_CODE; + if (pj_stricmp2(&branch_param, TEST7_BRANCH_ID) == 0) + code = TEST7_STATUS_CODE; + else + code = TEST8_STATUS_CODE; - if (recv_count==1) { + if (recv_count==1) { - if (rdata->msg_info.msg->line.status.code != code) { - PJ_LOG(3,(THIS_FILE," error: invalid status code")); - test_complete = -141; - } + if (rdata->msg_info.msg->line.status.code != code) { + PJ_LOG(3,(THIS_FILE," error: invalid status code")); + test_complete = -141; + } - recv_last = rdata->pkt_info.timestamp; + recv_last = rdata->pkt_info.timestamp; - } else { + } else { - pj_time_val now; - unsigned msec, msec_expected; + pj_time_val now; + unsigned msec, msec_expected; - now = rdata->pkt_info.timestamp; + now = rdata->pkt_info.timestamp; - PJ_TIME_VAL_SUB(now, recv_last); + PJ_TIME_VAL_SUB(now, recv_last); - msec = now.sec*1000 + now.msec; - msec_expected = (1 << (recv_count-2)) * pjsip_cfg()->tsx.t1; - if (msec_expected > pjsip_cfg()->tsx.t2) - msec_expected = pjsip_cfg()->tsx.t2; + msec = now.sec*1000 + now.msec; + msec_expected = (1 << (recv_count-2)) * pjsip_cfg()->tsx.t1; + if (msec_expected > pjsip_cfg()->tsx.t2) + msec_expected = pjsip_cfg()->tsx.t2; - if (DIFF(msec, msec_expected) > MAX_ALLOWED_DIFF) { - PJ_LOG(3,(THIS_FILE, - " error: incorrect retransmission " - "time (%d ms expected, %d ms received", - msec_expected, msec)); - test_complete = -142; - } + if (DIFF(msec, msec_expected) > MAX_ALLOWED_DIFF) { + PJ_LOG(3,(THIS_FILE, + " error: incorrect retransmission " + "time (%d ms expected, %d ms received", + msec_expected, msec)); + test_complete = -142; + } - if (recv_count > 11) { - PJ_LOG(3,(THIS_FILE," error: too many responses (%d)", - recv_count)); - test_complete = -143; - } + if (recv_count > 11) { + PJ_LOG(3,(THIS_FILE," error: too many responses (%d)", + recv_count)); + test_complete = -143; + } - recv_last = rdata->pkt_info.timestamp; - } + recv_last = rdata->pkt_info.timestamp; + } - } - return PJ_TRUE; + } + return PJ_TRUE; } else if (pj_stricmp2(&branch_param, TEST9_BRANCH_ID) == 0) { - /* - * TEST9_BRANCH_ID tests that the retransmission of INVITE final - * response should cease when ACK is received. Transaction also MUST - * terminate in T4 seconds. - */ - if (msg->type == PJSIP_REQUEST_MSG) { - - /* On received request, create UAS. */ - pjsip_transaction *tsx; - - status = pjsip_tsx_create_uas(&tsx_user, rdata, &tsx); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to create transaction", status); - test_complete = -150; - return PJ_TRUE; - } - - pjsip_tsx_recv_msg(tsx, rdata); - save_key(tsx); - send_response(rdata, tsx, TEST9_STATUS_CODE); - - - } else { - - ++recv_count; - - if (rdata->msg_info.msg->line.status.code != TEST9_STATUS_CODE) { - PJ_LOG(3,(THIS_FILE," error: invalid status code")); - test_complete = -151; - } - - if (recv_count==1) { - - recv_last = rdata->pkt_info.timestamp; - - } else if (recv_count < 5) { - - /* Let UAS retransmit some messages before we send ACK. */ - pj_time_val now; - unsigned msec, msec_expected; - - now = rdata->pkt_info.timestamp; - - PJ_TIME_VAL_SUB(now, recv_last); - - msec = now.sec*1000 + now.msec; - msec_expected = (1 << (recv_count-2)) * pjsip_cfg()->tsx.t1; - if (msec_expected > pjsip_cfg()->tsx.t2) - msec_expected = pjsip_cfg()->tsx.t2; - - if (DIFF(msec, msec_expected) > MAX_ALLOWED_DIFF) { - PJ_LOG(3,(THIS_FILE, - " error: incorrect retransmission " - "time (%d ms expected, %d ms received", - msec_expected, msec)); - test_complete = -152; - } - - recv_last = rdata->pkt_info.timestamp; - - } else if (recv_count == 5) { - pjsip_tx_data *tdata; - pjsip_sip_uri *uri; - pjsip_via_hdr *via; - - status = pjsip_endpt_create_request_from_hdr( - endpt, &pjsip_ack_method, - rdata->msg_info.to->uri, - rdata->msg_info.from, - rdata->msg_info.to, - NULL, - rdata->msg_info.cid, - rdata->msg_info.cseq->cseq, - NULL, - &tdata); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to create ACK", status); - test_complete = -153; - return PJ_TRUE; - } - - uri=(pjsip_sip_uri*)pjsip_uri_get_uri(tdata->msg->line.req.uri); - uri->transport_param = pj_str("loop-dgram"); - - via = (pjsip_via_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); - via->branch_param = pj_str(TEST9_BRANCH_ID); - - status = pjsip_endpt_send_request_stateless(endpt, tdata, - NULL, NULL); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to send ACK", status); - test_complete = -154; - } - - } else { - PJ_LOG(3,(THIS_FILE," error: too many responses (%d)", - recv_count)); - test_complete = -155; - } - - } - return PJ_TRUE; + /* + * TEST9_BRANCH_ID tests that the retransmission of INVITE final + * response should cease when ACK is received. Transaction also MUST + * terminate in T4 seconds. + */ + if (msg->type == PJSIP_REQUEST_MSG) { + + /* On received request, create UAS. */ + pjsip_transaction *tsx; + + status = pjsip_tsx_create_uas(&tsx_user, rdata, &tsx); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to create transaction", status); + test_complete = -150; + return PJ_TRUE; + } + + pjsip_tsx_recv_msg(tsx, rdata); + save_key(tsx); + send_response(rdata, tsx, TEST9_STATUS_CODE); + + + } else { + + ++recv_count; + + if (rdata->msg_info.msg->line.status.code != TEST9_STATUS_CODE) { + PJ_LOG(3,(THIS_FILE," error: invalid status code")); + test_complete = -151; + } + + if (recv_count==1) { + + recv_last = rdata->pkt_info.timestamp; + + } else if (recv_count < 5) { + + /* Let UAS retransmit some messages before we send ACK. */ + pj_time_val now; + unsigned msec, msec_expected; + + now = rdata->pkt_info.timestamp; + + PJ_TIME_VAL_SUB(now, recv_last); + + msec = now.sec*1000 + now.msec; + msec_expected = (1 << (recv_count-2)) * pjsip_cfg()->tsx.t1; + if (msec_expected > pjsip_cfg()->tsx.t2) + msec_expected = pjsip_cfg()->tsx.t2; + + if (DIFF(msec, msec_expected) > MAX_ALLOWED_DIFF) { + PJ_LOG(3,(THIS_FILE, + " error: incorrect retransmission " + "time (%d ms expected, %d ms received", + msec_expected, msec)); + test_complete = -152; + } + + recv_last = rdata->pkt_info.timestamp; + + } else if (recv_count == 5) { + pjsip_tx_data *tdata; + pjsip_sip_uri *uri; + pjsip_via_hdr *via; + + status = pjsip_endpt_create_request_from_hdr( + endpt, &pjsip_ack_method, + rdata->msg_info.to->uri, + rdata->msg_info.from, + rdata->msg_info.to, + NULL, + rdata->msg_info.cid, + rdata->msg_info.cseq->cseq, + NULL, + &tdata); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to create ACK", status); + test_complete = -153; + return PJ_TRUE; + } + + uri=(pjsip_sip_uri*)pjsip_uri_get_uri(tdata->msg->line.req.uri); + uri->transport_param = pj_str("loop-dgram"); + + via = (pjsip_via_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); + via->branch_param = pj_str(TEST9_BRANCH_ID); + + status = pjsip_endpt_send_request_stateless(endpt, tdata, + NULL, NULL); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to send ACK", status); + test_complete = -154; + } + + } else { + PJ_LOG(3,(THIS_FILE," error: too many responses (%d)", + recv_count)); + test_complete = -155; + } + + } + return PJ_TRUE; } else if (pj_stricmp2(&branch_param, TEST10_BRANCH_ID) == 0 || - pj_stricmp2(&branch_param, TEST11_BRANCH_ID) == 0 || - pj_stricmp2(&branch_param, TEST12_BRANCH_ID) == 0) + pj_stricmp2(&branch_param, TEST11_BRANCH_ID) == 0 || + pj_stricmp2(&branch_param, TEST12_BRANCH_ID) == 0) { - int test_num, code1, code2; + int test_num, code1, code2; - if (pj_stricmp2(&branch_param, TEST10_BRANCH_ID) == 0) - test_num=10, code1 = 100, code2 = 0; - else if (pj_stricmp2(&branch_param, TEST11_BRANCH_ID) == 0) - test_num=11, code1 = 100, code2 = 200; - else - test_num=12, code1 = 200, code2 = 0; + if (pj_stricmp2(&branch_param, TEST10_BRANCH_ID) == 0) + test_num=10, code1 = 100, code2 = 0; + else if (pj_stricmp2(&branch_param, TEST11_BRANCH_ID) == 0) + test_num=11, code1 = 100, code2 = 200; + else + test_num=12, code1 = 200, code2 = 0; - PJ_UNUSED_ARG(test_num); + PJ_UNUSED_ARG(test_num); - if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) { + if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) { - /* On received response, create UAS. */ - pjsip_transaction *tsx; + /* On received response, create UAS. */ + pjsip_transaction *tsx; - status = pjsip_tsx_create_uas(&tsx_user, rdata, &tsx); - if (status != PJ_SUCCESS) { - app_perror(" error: unable to create transaction", status); - test_complete = -150; - return PJ_TRUE; - } + status = pjsip_tsx_create_uas(&tsx_user, rdata, &tsx); + if (status != PJ_SUCCESS) { + app_perror(" error: unable to create transaction", status); + test_complete = -150; + return PJ_TRUE; + } - pjsip_tsx_recv_msg(tsx, rdata); - save_key(tsx); + pjsip_tsx_recv_msg(tsx, rdata); + save_key(tsx); - schedule_send_response(rdata, &tsx_key, code1, 1000); + schedule_send_response(rdata, &tsx_key, code1, 1000); - if (code2) - schedule_send_response(rdata, &tsx_key, code2, 2000); + if (code2) + schedule_send_response(rdata, &tsx_key, code2, 2000); - } else { + } else { - } + } - return PJ_TRUE; + return PJ_TRUE; } return PJ_FALSE; @@ -1188,10 +1187,10 @@ static pj_bool_t on_rx_message(pjsip_rx_data *rdata) * The generic test framework, used by most of the tests. */ static int perform_test( char *target_uri, char *from_uri, - char *branch_param, int test_time, - const pjsip_method *method, - int request_cnt, int request_interval_msec, - int expecting_timeout) + char *branch_param, int test_time, + const pjsip_method *method, + int request_cnt, int request_interval_msec, + int expecting_timeout) { pjsip_tx_data *tdata; pj_str_t target, from; @@ -1201,8 +1200,8 @@ static int perform_test( char *target_uri, char *from_uri, pj_status_t status; PJ_LOG(3,(THIS_FILE, - " please standby, this will take at most %d seconds..", - test_time)); + " please standby, this will take at most %d seconds..", + test_time)); /* Reset test. */ recv_count = 0; @@ -1215,11 +1214,11 @@ static int perform_test( char *target_uri, char *from_uri, /* Create request. */ status = pjsip_endpt_create_request( endpt, method, &target, - &from, &target, NULL, NULL, -1, - NULL, &tdata); + &from, &target, NULL, NULL, -1, + NULL, &tdata); if (status != PJ_SUCCESS) { - app_perror(" Error: unable to create request", status); - return -10; + app_perror(" Error: unable to create request", status); + return -10; } /* Set the branch param for test 1. */ @@ -1237,56 +1236,56 @@ static int perform_test( char *target_uri, char *from_uri, /* Wait until test complete. */ while (!test_complete) { - pj_time_val now, poll_delay = {0, 10}; - - pjsip_endpt_handle_events(endpt, &poll_delay); - - pj_gettimeofday(&now); - - if (sent_cnt < request_cnt && PJ_TIME_VAL_GTE(now, next_send)) { - /* Add additional reference to tdata to prevent transaction from - * deleting it. - */ - pjsip_tx_data_add_ref(tdata); - - /* (Re)Send the request. */ - PJ_LOG(4,(THIS_FILE, " (re)sending request %d", sent_cnt)); - - status = pjsip_endpt_send_request_stateless(endpt, tdata, 0, 0); - if (status != PJ_SUCCESS) { - app_perror(" Error: unable to send request", status); - pjsip_tx_data_dec_ref(tdata); - return -20; - } - - /* Schedule next send, if any. */ - sent_cnt++; - if (sent_cnt < request_cnt) { - pj_gettimeofday(&next_send); - next_send.msec += request_interval_msec; - pj_time_val_normalize(&next_send); - } - } - - if (now.sec > timeout.sec) { - if (!expecting_timeout) - PJ_LOG(3,(THIS_FILE, " Error: test has timed out")); - pjsip_tx_data_dec_ref(tdata); - return TEST_TIMEOUT_ERROR; - } + pj_time_val now, poll_delay = {0, 10}; + + pjsip_endpt_handle_events(endpt, &poll_delay); + + pj_gettimeofday(&now); + + if (sent_cnt < request_cnt && PJ_TIME_VAL_GTE(now, next_send)) { + /* Add additional reference to tdata to prevent transaction from + * deleting it. + */ + pjsip_tx_data_add_ref(tdata); + + /* (Re)Send the request. */ + PJ_LOG(4,(THIS_FILE, " (re)sending request %d", sent_cnt)); + + status = pjsip_endpt_send_request_stateless(endpt, tdata, 0, 0); + if (status != PJ_SUCCESS) { + app_perror(" Error: unable to send request", status); + pjsip_tx_data_dec_ref(tdata); + return -20; + } + + /* Schedule next send, if any. */ + sent_cnt++; + if (sent_cnt < request_cnt) { + pj_gettimeofday(&next_send); + next_send.msec += request_interval_msec; + pj_time_val_normalize(&next_send); + } + } + + if (now.sec > timeout.sec) { + if (!expecting_timeout) + PJ_LOG(3,(THIS_FILE, " Error: test has timed out")); + pjsip_tx_data_dec_ref(tdata); + return TEST_TIMEOUT_ERROR; + } } if (test_complete < 0) { - pjsip_transaction *tsx; - - tsx = pjsip_tsx_layer_find_tsx(&tsx_key, PJ_TRUE); - if (tsx) { - pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED); - pj_grp_lock_release(tsx->grp_lock); - flush_events(1000); - } - pjsip_tx_data_dec_ref(tdata); - return test_complete; + pjsip_transaction *tsx; + + tsx = pjsip_tsx_layer_find_tsx(&tsx_key, PJ_TRUE); + if (tsx) { + pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED); + pj_grp_lock_release(tsx->grp_lock); + flush_events(1000); + } + pjsip_tx_data_dec_ref(tdata); + return test_complete; } /* Allow transaction to destroy itself */ @@ -1294,17 +1293,17 @@ static int perform_test( char *target_uri, char *from_uri, /* Make sure transaction has been destroyed. */ if (pjsip_tsx_layer_find_tsx(&tsx_key, PJ_FALSE) != NULL) { - PJ_LOG(3,(THIS_FILE, " Error: transaction has not been destroyed")); - pjsip_tx_data_dec_ref(tdata); - return -40; + PJ_LOG(3,(THIS_FILE, " Error: transaction has not been destroyed")); + pjsip_tx_data_dec_ref(tdata); + return -40; } /* Check tdata reference counter. */ if (pj_atomic_get(tdata->ref_cnt) != 1) { - PJ_LOG(3,(THIS_FILE, " Error: tdata reference counter is %d", - pj_atomic_get(tdata->ref_cnt))); - pjsip_tx_data_dec_ref(tdata); - return -50; + PJ_LOG(3,(THIS_FILE, " Error: tdata reference counter is %d", + pj_atomic_get(tdata->ref_cnt))); + pjsip_tx_data_dec_ref(tdata); + return -50; } /* Destroy txdata */ @@ -1335,16 +1334,16 @@ static int tsx_basic_final_response_test(void) duration = (tp_flag & PJSIP_TRANSPORT_RELIABLE) ? 1 : 33; status = perform_test(TARGET_URI, FROM_URI, TEST1_BRANCH_ID, - duration, &pjsip_options_method, 1, 0, 0); + duration, &pjsip_options_method, 1, 0, 0); if (status != 0) - return status; + return status; PJ_LOG(3,(THIS_FILE," test2: basic sending non-2xx final response")); status = perform_test(TARGET_URI, FROM_URI, TEST2_BRANCH_ID, - duration, &pjsip_options_method, 1, 0, 0); + duration, &pjsip_options_method, 1, 0, 0); if (status != 0) - return status; + return status; return 0; } @@ -1367,7 +1366,7 @@ static int tsx_basic_provisional_response_test(void) duration += 2; status = perform_test(TARGET_URI, FROM_URI, TEST3_BRANCH_ID, duration, - &pjsip_options_method, 1, 0, 0); + &pjsip_options_method, 1, 0, 0); return status; } @@ -1382,29 +1381,29 @@ static int tsx_basic_provisional_response_test(void) ***************************************************************************** */ static int tsx_retransmit_last_response_test(const char *title, - char *branch_id, - int request_cnt, - int status_code) + char *branch_id, + int request_cnt, + int status_code) { int status; PJ_LOG(3,(THIS_FILE," %s", title)); status = perform_test(TARGET_URI, FROM_URI, branch_id, 5, - &pjsip_options_method, - request_cnt, 1000, 1); + &pjsip_options_method, + request_cnt, 1000, 1); if (status && status != TEST_TIMEOUT_ERROR) - return status; + return status; if (!status) { - PJ_LOG(3,(THIS_FILE, " error: expecting timeout")); - return -31; + PJ_LOG(3,(THIS_FILE, " error: expecting timeout")); + return -31; } terminate_our_tsx(status_code); flush_events(100); if (test_complete != 1) - return test_complete; + return test_complete; flush_events(100); return 0; @@ -1422,22 +1421,22 @@ static int tsx_final_response_retransmission_test(void) int status; PJ_LOG(3,(THIS_FILE, - " test7: INVITE non-2xx final response retransmission")); + " test7: INVITE non-2xx final response retransmission")); status = perform_test(TARGET_URI, FROM_URI, TEST7_BRANCH_ID, - 33, /* Test duration must be greater than 32 secs */ - &pjsip_invite_method, 1, 0, 0); + 33, /* Test duration must be greater than 32 secs */ + &pjsip_invite_method, 1, 0, 0); if (status != 0) - return status; + return status; PJ_LOG(3,(THIS_FILE, - " test8: INVITE 2xx final response retransmission")); + " test8: INVITE 2xx final response retransmission")); status = perform_test(TARGET_URI, FROM_URI, TEST8_BRANCH_ID, - 33, /* Test duration must be greater than 32 secs */ - &pjsip_invite_method, 1, 0, 0); + 33, /* Test duration must be greater than 32 secs */ + &pjsip_invite_method, 1, 0, 0); if (status != 0) - return status; + return status; return 0; } @@ -1455,13 +1454,13 @@ static int tsx_ack_test(void) int status; PJ_LOG(3,(THIS_FILE, - " test9: receiving ACK for non-2xx final response")); + " test9: receiving ACK for non-2xx final response")); status = perform_test(TARGET_URI, FROM_URI, TEST9_BRANCH_ID, - 20, /* allow 5 retransmissions */ - &pjsip_invite_method, 1, 0, 0); + 20, /* allow 5 retransmissions */ + &pjsip_invite_method, 1, 0, 0); if (status != 0) - return status; + return status; return 0; @@ -1482,72 +1481,72 @@ int tsx_transport_failure_test(void) { struct test_desc { - int transport_delay; - int fail_delay; - char *branch_id; - char *title; + int transport_delay; + int fail_delay; + char *branch_id; + char *title; } tests[] = { - { 0, 10, TEST10_BRANCH_ID, "test10: failed transport in TRYING state (no delay)" }, - { 50, 10, TEST10_BRANCH_ID, "test10: failed transport in TRYING state (50 ms delay)" }, - { 0, 1500, TEST11_BRANCH_ID, "test11: failed transport in PROCEEDING state (no delay)" }, - // After ticket #2076, transport error will be ignored if tsx is in COMPLETED state, note that - // tsx state will be shifted to COMPLETED state once 200 response is sent due to transport delay. - //{ 50, 1500, TEST11_BRANCH_ID, "test11: failed transport in PROCEEDING state (50 ms delay)" }, - { 0, 2500, TEST12_BRANCH_ID, "test12: failed transport in COMPLETED state (no delay)" }, - //Not applicable (maybe) - //This test may expect transport failure notification in COMPLETED state. This may not be - //possible because the loop transport can only notify failure when it has something to send, - //while in this case, there is nothing to send because UAS already sends 200/OK - //{ 50, 2500, TEST12_BRANCH_ID, "test12: failed transport in COMPLETED state (50 ms delay)" }, + { 0, 10, TEST10_BRANCH_ID, "test10: failed transport in TRYING state (no delay)" }, + { 50, 10, TEST10_BRANCH_ID, "test10: failed transport in TRYING state (50 ms delay)" }, + { 0, 1500, TEST11_BRANCH_ID, "test11: failed transport in PROCEEDING state (no delay)" }, + // After ticket #2076, transport error will be ignored if tsx is in COMPLETED state, note that + // tsx state will be shifted to COMPLETED state once 200 response is sent due to transport delay. + //{ 50, 1500, TEST11_BRANCH_ID, "test11: failed transport in PROCEEDING state (50 ms delay)" }, + { 0, 2500, TEST12_BRANCH_ID, "test12: failed transport in COMPLETED state (no delay)" }, + //Not applicable (maybe) + //This test may expect transport failure notification in COMPLETED state. This may not be + //possible because the loop transport can only notify failure when it has something to send, + //while in this case, there is nothing to send because UAS already sends 200/OK + //{ 50, 2500, TEST12_BRANCH_ID, "test12: failed transport in COMPLETED state (50 ms delay)" }, }; int i, status; for (i=0; i<(int)PJ_ARRAY_SIZE(tests); ++i) { - pj_time_val fail_time, end_test, now; - - PJ_LOG(3,(THIS_FILE, " %s", tests[i].title)); - pjsip_loop_set_failure(loop, 0, NULL); - pjsip_loop_set_delay(loop, tests[i].transport_delay); - - status = perform_test(TARGET_URI, FROM_URI, tests[i].branch_id, - 0, &pjsip_invite_method, 1, 0, 1); - if (status && status != TEST_TIMEOUT_ERROR) - return status; - if (!status) { - PJ_LOG(3,(THIS_FILE, " error: expecting timeout")); - return -40; - } - - pj_gettimeofday(&fail_time); - fail_time.msec += tests[i].fail_delay; - pj_time_val_normalize(&fail_time); - - do { - pj_time_val interval = { 0, 1 }; - pj_gettimeofday(&now); - pjsip_endpt_handle_events(endpt, &interval); - } while (PJ_TIME_VAL_LT(now, fail_time)); - - pjsip_loop_set_failure(loop, 1, NULL); - PJ_LOG(5,(THIS_FILE, " transport loop fail mode set")); - - end_test = now; - end_test.sec += 5; - - do { - pj_time_val interval = { 0, 1 }; - pj_gettimeofday(&now); - pjsip_endpt_handle_events(endpt, &interval); - } while (!test_complete && PJ_TIME_VAL_LT(now, end_test)); - - if (test_complete == 0) { - PJ_LOG(3,(THIS_FILE, " error: test has timed out")); - return -41; - } - - if (test_complete != 1) - return test_complete; + pj_time_val fail_time, end_test, now; + + PJ_LOG(3,(THIS_FILE, " %s", tests[i].title)); + pjsip_loop_set_failure(loop, 0, NULL); + pjsip_loop_set_delay(loop, tests[i].transport_delay); + + status = perform_test(TARGET_URI, FROM_URI, tests[i].branch_id, + 0, &pjsip_invite_method, 1, 0, 1); + if (status && status != TEST_TIMEOUT_ERROR) + return status; + if (!status) { + PJ_LOG(3,(THIS_FILE, " error: expecting timeout")); + return -40; + } + + pj_gettimeofday(&fail_time); + fail_time.msec += tests[i].fail_delay; + pj_time_val_normalize(&fail_time); + + do { + pj_time_val interval = { 0, 1 }; + pj_gettimeofday(&now); + pjsip_endpt_handle_events(endpt, &interval); + } while (PJ_TIME_VAL_LT(now, fail_time)); + + pjsip_loop_set_failure(loop, 1, NULL); + PJ_LOG(5,(THIS_FILE, " transport loop fail mode set")); + + end_test = now; + end_test.sec += 5; + + do { + pj_time_val interval = { 0, 1 }; + pj_gettimeofday(&now); + pjsip_endpt_handle_events(endpt, &interval); + } while (!test_complete && PJ_TIME_VAL_LT(now, end_test)); + + if (test_complete == 0) { + PJ_LOG(3,(THIS_FILE, " error: test has timed out")); + return -41; + } + + if (test_complete != 1) + return test_complete; } return 0; @@ -1568,27 +1567,27 @@ int tsx_uas_test(struct tsx_test_param *param) tp_flag = pjsip_transport_get_flag_from_type((pjsip_transport_type_e)param->type); pj_ansi_sprintf(TARGET_URI, "sip:bob@127.0.0.1:%d;transport=%s", - param->port, param->tp_type); + param->port, param->tp_type); pj_ansi_sprintf(FROM_URI, "sip:alice@127.0.0.1:%d;transport=%s", - param->port, param->tp_type); + param->port, param->tp_type); /* Check if loop transport is configured. */ status = pjsip_endpt_acquire_transport(endpt, PJSIP_TRANSPORT_LOOP_DGRAM, - &addr, sizeof(addr), NULL, &loop); + &addr, sizeof(addr), NULL, &loop); if (status != PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, " Error: loop transport is not configured!")); - return -10; + PJ_LOG(3,(THIS_FILE, " Error: loop transport is not configured!")); + return -10; } /* Register modules. */ status = pjsip_endpt_register_module(endpt, &tsx_user); if (status != PJ_SUCCESS) { - app_perror(" Error: unable to register module", status); - return -3; + app_perror(" Error: unable to register module", status); + return -3; } status = pjsip_endpt_register_module(endpt, &msg_sender); if (status != PJ_SUCCESS) { - app_perror(" Error: unable to register module", status); - return -4; + app_perror(" Error: unable to register module", status); + return -4; } /* TEST1_BRANCH_ID: Basic 2xx final response. @@ -1596,44 +1595,44 @@ int tsx_uas_test(struct tsx_test_param *param) */ status = tsx_basic_final_response_test(); if (status != 0) - return status; + return status; /* TEST3_BRANCH_ID: with provisional response */ status = tsx_basic_provisional_response_test(); if (status != 0) - return status; + return status; /* TEST4_BRANCH_ID: absorbs retransmissions in TRYING state */ status = tsx_retransmit_last_response_test(TEST4_TITLE, - TEST4_BRANCH_ID, - TEST4_REQUEST_COUNT, - TEST4_STATUS_CODE); + TEST4_BRANCH_ID, + TEST4_REQUEST_COUNT, + TEST4_STATUS_CODE); if (status != 0) - return status; + return status; /* TEST5_BRANCH_ID: retransmit last response in PROCEEDING state */ status = tsx_retransmit_last_response_test(TEST5_TITLE, - TEST5_BRANCH_ID, - TEST5_REQUEST_COUNT, - TEST5_STATUS_CODE); + TEST5_BRANCH_ID, + TEST5_REQUEST_COUNT, + TEST5_STATUS_CODE); if (status != 0) - return status; + return status; /* TEST6_BRANCH_ID: retransmit last response in COMPLETED state * This only applies to non-reliable transports, - * since UAS transaction is destroyed as soon - * as final response is sent for reliable transports. + * since UAS transaction is destroyed as soon + * as final response is sent for reliable transports. */ if ((tp_flag & PJSIP_TRANSPORT_RELIABLE) == 0) { - status = tsx_retransmit_last_response_test(TEST6_TITLE, - TEST6_BRANCH_ID, - TEST6_REQUEST_COUNT, - TEST6_STATUS_CODE); - if (status != 0) - return status; + status = tsx_retransmit_last_response_test(TEST6_TITLE, + TEST6_BRANCH_ID, + TEST6_REQUEST_COUNT, + TEST6_STATUS_CODE); + if (status != 0) + return status; } /* TEST7_BRANCH_ID: INVITE non-2xx final response retransmission test @@ -1641,16 +1640,16 @@ int tsx_uas_test(struct tsx_test_param *param) */ status = tsx_final_response_retransmission_test(); if (status != 0) - return status; + return status; /* TEST9_BRANCH_ID: retransmission of non-2xx INVITE final response must * cease when ACK is received * Only applicable for non-reliable transports. */ if ((tp_flag & PJSIP_TRANSPORT_RELIABLE) == 0) { - status = tsx_ack_test(); - if (status != 0) - return status; + status = tsx_ack_test(); + if (status != 0) + return status; } /* TEST10_BRANCH_ID: test transport failure in TRYING state. @@ -1660,27 +1659,27 @@ int tsx_uas_test(struct tsx_test_param *param) */ /* Only valid for loop-dgram */ if (param->type == PJSIP_TRANSPORT_LOOP_DGRAM) { - status = tsx_transport_failure_test(); - if (status != 0) - return status; + status = tsx_transport_failure_test(); + if (status != 0) + return status; } /* Register modules. */ status = pjsip_endpt_unregister_module(endpt, &tsx_user); if (status != PJ_SUCCESS) { - app_perror(" Error: unable to unregister module", status); - return -8; + app_perror(" Error: unable to unregister module", status); + return -8; } status = pjsip_endpt_unregister_module(endpt, &msg_sender); if (status != PJ_SUCCESS) { - app_perror(" Error: unable to unregister module", status); - return -9; + app_perror(" Error: unable to unregister module", status); + return -9; } if (loop) - pjsip_transport_dec_ref(loop); + pjsip_transport_dec_ref(loop); return 0; } diff --git a/pjsip/src/test/txdata_test.c b/pjsip/src/test/txdata_test.c index f7f73651b9..3fd9330051 100644 --- a/pjsip/src/test/txdata_test.c +++ b/pjsip/src/test/txdata_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -29,9 +28,9 @@ #define HFIND(msg,h,H) ((pjsip_##h##_hdr*) pjsip_msg_find_hdr(msg, PJSIP_H_##H, NULL)) #if defined(PJ_DEBUG) && PJ_DEBUG!=0 -# define LOOP 10000 +# define LOOP 10000 #else -# define LOOP 100000 +# define LOOP 100000 #endif @@ -55,108 +54,108 @@ static int core_txdata_test(void) body = pj_str("Hello world!"); status = pjsip_endpt_create_request( endpt, &pjsip_invite_method, &target, - &from, &to, &contact, NULL, 10, &body, - &invite); + &from, &to, &contact, NULL, 10, &body, + &invite); if (status != PJ_SUCCESS) { - app_perror(" error: unable to create request", status); - return -10; + app_perror(" error: unable to create request", status); + return -10; } /* Buffer must be invalid. */ if (pjsip_tx_data_is_valid(invite) != 0) { - PJ_LOG(3,(THIS_FILE, " error: buffer must be invalid")); - return -14; + PJ_LOG(3,(THIS_FILE, " error: buffer must be invalid")); + return -14; } /* Reference counter must be set to 1. */ if (pj_atomic_get(invite->ref_cnt) != 1) { - PJ_LOG(3,(THIS_FILE, " error: invalid reference counter")); - return -15; + PJ_LOG(3,(THIS_FILE, " error: invalid reference counter")); + return -15; } /* Check message type. */ if (invite->msg->type != PJSIP_REQUEST_MSG) - return -16; + return -16; /* Check method. */ if (invite->msg->line.req.method.id != PJSIP_INVITE_METHOD) - return -17; + return -17; /* Check that mandatory headers are present. */ if (HFIND(invite->msg, from, FROM) == 0) - return -20; + return -20; if (HFIND(invite->msg, to, TO) == 0) - return -21; + return -21; if (HFIND(invite->msg, contact, CONTACT) == 0) - return -22; + return -22; if (HFIND(invite->msg, cid, CALL_ID) == 0) - return -23; + return -23; if (HFIND(invite->msg, cseq, CSEQ) == 0) - return -24; + return -24; do { - pjsip_via_hdr *via = HFIND(invite->msg, via, VIA); - if (via == NULL) - return -25; - /* Branch param must be empty. */ - if (via->branch_param.slen != 0) - return -26; + pjsip_via_hdr *via = HFIND(invite->msg, via, VIA); + if (via == NULL) + return -25; + /* Branch param must be empty. */ + if (via->branch_param.slen != 0) + return -26; } while (0); if (invite->msg->body == NULL) - return -28; + return -28; /* Create another INVITE request from first request. */ status = pjsip_endpt_create_request_from_hdr( endpt, &pjsip_invite_method, - invite->msg->line.req.uri, - HFIND(invite->msg,from,FROM), - HFIND(invite->msg,to,TO), - HFIND(invite->msg,contact,CONTACT), - HFIND(invite->msg,cid,CALL_ID), - 10, &body, &invite2); + invite->msg->line.req.uri, + HFIND(invite->msg,from,FROM), + HFIND(invite->msg,to,TO), + HFIND(invite->msg,contact,CONTACT), + HFIND(invite->msg,cid,CALL_ID), + 10, &body, &invite2); if (status != PJ_SUCCESS) { - app_perror(" error: create second request failed", status); - return -30; + app_perror(" error: create second request failed", status); + return -30; } /* Buffer must be invalid. */ if (pjsip_tx_data_is_valid(invite2) != 0) { - PJ_LOG(3,(THIS_FILE, " error: buffer must be invalid")); - return -34; + PJ_LOG(3,(THIS_FILE, " error: buffer must be invalid")); + return -34; } /* Reference counter must be set to 1. */ if (pj_atomic_get(invite2->ref_cnt) != 1) { - PJ_LOG(3,(THIS_FILE, " error: invalid reference counter")); - return -35; + PJ_LOG(3,(THIS_FILE, " error: invalid reference counter")); + return -35; } /* Check message type. */ if (invite2->msg->type != PJSIP_REQUEST_MSG) - return -36; + return -36; /* Check method. */ if (invite2->msg->line.req.method.id != PJSIP_INVITE_METHOD) - return -37; + return -37; /* Check that mandatory headers are again present. */ if (HFIND(invite2->msg, from, FROM) == 0) - return -40; + return -40; if (HFIND(invite2->msg, to, TO) == 0) - return -41; + return -41; if (HFIND(invite2->msg, contact, CONTACT) == 0) - return -42; + return -42; if (HFIND(invite2->msg, cid, CALL_ID) == 0) - return -43; + return -43; if (HFIND(invite2->msg, cseq, CSEQ) == 0) - return -44; + return -44; if (HFIND(invite2->msg, via, VIA) == 0) - return -45; + return -45; /* if (HFIND(invite2->msg, ctype, CONTENT_TYPE) == 0) - return -46; + return -46; if (HFIND(invite2->msg, clen, CONTENT_LENGTH) == 0) - return -47; + return -47; */ if (invite2->msg->body == NULL) - return -48; + return -48; /* Done checking invite2. We can delete this. */ if (pjsip_tx_data_dec_ref(invite2) != PJSIP_EBUFDESTROYED) { - PJ_LOG(3,(THIS_FILE, " error: request buffer not destroyed!")); - return -49; + PJ_LOG(3,(THIS_FILE, " error: request buffer not destroyed!")); + return -49; } /* Initialize dummy rdata (to simulate receiving a request) @@ -178,91 +177,91 @@ static int core_txdata_test(void) /* Create a response message for the request. */ status = pjsip_endpt_create_response( endpt, &dummy_rdata, 301, NULL, - &response); + &response); if (status != PJ_SUCCESS) { - app_perror(" error: unable to create response", status); - return -50; + app_perror(" error: unable to create response", status); + return -50; } /* Buffer must be invalid. */ if (pjsip_tx_data_is_valid(response) != 0) { - PJ_LOG(3,(THIS_FILE, " error: buffer must be invalid")); - return -54; + PJ_LOG(3,(THIS_FILE, " error: buffer must be invalid")); + return -54; } /* Check reference counter. */ if (pj_atomic_get(response->ref_cnt) != 1) { - PJ_LOG(3,(THIS_FILE, " error: invalid ref count in response")); - return -55; + PJ_LOG(3,(THIS_FILE, " error: invalid ref count in response")); + return -55; } /* Check message type. */ if (response->msg->type != PJSIP_RESPONSE_MSG) - return -56; + return -56; /* Check correct status is set. */ if (response->msg->line.status.code != 301) - return -57; + return -57; /* Check that mandatory headers are again present. */ if (HFIND(response->msg, from, FROM) == 0) - return -60; + return -60; if (HFIND(response->msg, to, TO) == 0) - return -61; + return -61; /* if (HFIND(response->msg, contact, CONTACT) == 0) - return -62; + return -62; */ if (HFIND(response->msg, cid, CALL_ID) == 0) - return -63; + return -63; if (HFIND(response->msg, cseq, CSEQ) == 0) - return -64; + return -64; if (HFIND(response->msg, via, VIA) == 0) - return -65; + return -65; /* This response message will be used later when creating ACK */ /* Create CANCEL request for the original request. */ status = pjsip_endpt_create_cancel( endpt, invite, &cancel); if (status != PJ_SUCCESS) { - app_perror(" error: unable to create CANCEL request", status); - return -80; + app_perror(" error: unable to create CANCEL request", status); + return -80; } /* Buffer must be invalid. */ if (pjsip_tx_data_is_valid(cancel) != 0) { - PJ_LOG(3,(THIS_FILE, " error: buffer must be invalid")); - return -84; + PJ_LOG(3,(THIS_FILE, " error: buffer must be invalid")); + return -84; } /* Check reference counter. */ if (pj_atomic_get(cancel->ref_cnt) != 1) { - PJ_LOG(3,(THIS_FILE, " error: invalid ref count in CANCEL request")); - return -85; + PJ_LOG(3,(THIS_FILE, " error: invalid ref count in CANCEL request")); + return -85; } /* Check message type. */ if (cancel->msg->type != PJSIP_REQUEST_MSG) - return -86; + return -86; /* Check method. */ if (cancel->msg->line.req.method.id != PJSIP_CANCEL_METHOD) - return -87; + return -87; /* Check that mandatory headers are again present. */ if (HFIND(cancel->msg, from, FROM) == 0) - return -90; + return -90; if (HFIND(cancel->msg, to, TO) == 0) - return -91; + return -91; /* if (HFIND(cancel->msg, contact, CONTACT) == 0) - return -92; + return -92; */ if (HFIND(cancel->msg, cid, CALL_ID) == 0) - return -93; + return -93; if (HFIND(cancel->msg, cseq, CSEQ) == 0) - return -94; + return -94; if (HFIND(cancel->msg, via, VIA) == 0) - return -95; + return -95; /* Done checking CANCEL request. */ if (pjsip_tx_data_dec_ref(cancel) != PJSIP_EBUFDESTROYED) { - PJ_LOG(3,(THIS_FILE, " error: response buffer not destroyed!")); - return -99; + PJ_LOG(3,(THIS_FILE, " error: response buffer not destroyed!")); + return -99; } /* Modify dummy_rdata to simulate receiving response. */ @@ -273,59 +272,59 @@ static int core_txdata_test(void) /* Create ACK request */ status = pjsip_endpt_create_ack( endpt, invite, &dummy_rdata, &ack ); if (status != PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, " error: unable to create ACK")); - return -100; + PJ_LOG(3,(THIS_FILE, " error: unable to create ACK")); + return -100; } /* Buffer must be invalid. */ if (pjsip_tx_data_is_valid(ack) != 0) { - PJ_LOG(3,(THIS_FILE, " error: buffer must be invalid")); - return -104; + PJ_LOG(3,(THIS_FILE, " error: buffer must be invalid")); + return -104; } /* Check reference counter. */ if (pj_atomic_get(ack->ref_cnt) != 1) { - PJ_LOG(3,(THIS_FILE, " error: invalid ref count in ACK request")); - return -105; + PJ_LOG(3,(THIS_FILE, " error: invalid ref count in ACK request")); + return -105; } /* Check message type. */ if (ack->msg->type != PJSIP_REQUEST_MSG) - return -106; + return -106; /* Check method. */ if (ack->msg->line.req.method.id != PJSIP_ACK_METHOD) - return -107; + return -107; /* Check Request-URI is present. */ if (ack->msg->line.req.uri == NULL) - return -108; + return -108; /* Check that mandatory headers are again present. */ if (HFIND(ack->msg, from, FROM) == 0) - return -110; + return -110; if (HFIND(ack->msg, to, TO) == 0) - return -111; + return -111; if (HFIND(ack->msg, cid, CALL_ID) == 0) - return -112; + return -112; if (HFIND(ack->msg, cseq, CSEQ) == 0) - return -113; + return -113; if (HFIND(ack->msg, via, VIA) == 0) - return -114; + return -114; if (ack->msg->body != NULL) - return -115; + return -115; /* Done checking invite message. */ if (pjsip_tx_data_dec_ref(invite) != PJSIP_EBUFDESTROYED) { - PJ_LOG(3,(THIS_FILE, " error: response buffer not destroyed!")); - return -120; + PJ_LOG(3,(THIS_FILE, " error: response buffer not destroyed!")); + return -120; } /* Done checking response message. */ if (pjsip_tx_data_dec_ref(response) != PJSIP_EBUFDESTROYED) { - PJ_LOG(3,(THIS_FILE, " error: response buffer not destroyed!")); - return -130; + PJ_LOG(3,(THIS_FILE, " error: response buffer not destroyed!")); + return -130; } /* Done checking ack message. */ if (pjsip_tx_data_dec_ref(ack) != PJSIP_EBUFDESTROYED) { - PJ_LOG(3,(THIS_FILE, " error: response buffer not destroyed!")); - return -140; + PJ_LOG(3,(THIS_FILE, " error: response buffer not destroyed!")); + return -140; } /* Done. */ @@ -343,8 +342,8 @@ static int gcc_test() { char msgbuf[512]; pj_str_t target = pj_str("sip:alice@wonderland:5061;x-param=param%201" - "?X-Hdr-1=Header%201" - "&X-Empty-Hdr="); + "?X-Hdr-1=Header%201" + "&X-Empty-Hdr="); pjsip_tx_data *tdata; pjsip_parser_err_report err_list; pjsip_msg *msg; @@ -355,11 +354,11 @@ static int gcc_test() /* Create request with header param in target URI. */ status = pjsip_endpt_create_request(endpt, &pjsip_invite_method, &target, - &target, &target, &target, NULL, -1, - NULL, &tdata); + &target, &target, &target, NULL, -1, + NULL, &tdata); if (status != 0) { - app_perror(" error: Unable to create request", status); - return -200; + app_perror(" error: Unable to create request", status); + return -200; } /* Print and parse the request. @@ -367,36 +366,36 @@ static int gcc_test() */ len = pjsip_msg_print(tdata->msg, msgbuf, sizeof(msgbuf)); if (len < 1) { - PJ_LOG(3,(THIS_FILE, " error: printing message")); - pjsip_tx_data_dec_ref(tdata); - return -250; + PJ_LOG(3,(THIS_FILE, " error: printing message")); + pjsip_tx_data_dec_ref(tdata); + return -250; } msgbuf[len] = '\0'; PJ_LOG(5,(THIS_FILE, "%d bytes request created:--begin-msg--\n" - "%s\n" - "--end-msg--", len, msgbuf)); + "%s\n" + "--end-msg--", len, msgbuf)); /* Now parse the message. */ pj_list_init(&err_list); msg = pjsip_parse_msg( tdata->pool, msgbuf, len, &err_list); if (msg == NULL) { - pjsip_parser_err_report *e; + pjsip_parser_err_report *e; - PJ_LOG(3,(THIS_FILE, " error: parsing message message")); + PJ_LOG(3,(THIS_FILE, " error: parsing message message")); - e = err_list.next; - while (e != &err_list) { - PJ_LOG(3,(THIS_FILE, " %s in line %d col %d hname=%.*s", - pj_exception_id_name(e->except_code), - e->line, e->col+1, - (int)e->hname.slen, - e->hname.ptr)); - e = e->next; - } + e = err_list.next; + while (e != &err_list) { + PJ_LOG(3,(THIS_FILE, " %s in line %d col %d hname=%.*s", + pj_exception_id_name(e->except_code), + e->line, e->col+1, + (int)e->hname.slen, + e->hname.ptr)); + e = e->next; + } - pjsip_tx_data_dec_ref(tdata); - return -255; + pjsip_tx_data_dec_ref(tdata); + return -255; } pjsip_tx_data_dec_ref(tdata); @@ -415,8 +414,8 @@ static int txdata_test_uri_params(void) { char msgbuf[512]; pj_str_t target = pj_str("sip:alice@wonderland:5061;x-param=param%201" - "?X-Hdr-1=Header%201" - "&X-Empty-Hdr="); + "?X-Hdr-1=Header%201" + "&X-Empty-Hdr="); pj_str_t contact; pj_str_t pname = pj_str("x-param"); pj_str_t hname = pj_str("X-Hdr-1"); @@ -440,17 +439,17 @@ static int txdata_test_uri_params(void) * must enclose it with <> to make it be parsed as URI. */ pj_ansi_snprintf(msgbuf, sizeof(msgbuf), "<%.*s>", - (int)target.slen, target.ptr); + (int)target.slen, target.ptr); contact.ptr = msgbuf; contact.slen = strlen(msgbuf); /* Create request with header param in target URI. */ status = pjsip_endpt_create_request(endpt, &pjsip_invite_method, &target, - &target, &target, &contact, NULL, -1, - NULL, &tdata); + &target, &target, &contact, NULL, -1, + NULL, &tdata); if (status != 0) { - app_perror(" error: Unable to create request", status); - return -200; + app_perror(" error: Unable to create request", status); + return -200; } /* Fill up the Via header to prevent syntax error on parsing */ @@ -463,36 +462,36 @@ static int txdata_test_uri_params(void) */ len = pjsip_msg_print(tdata->msg, msgbuf, sizeof(msgbuf)); if (len < 1) { - PJ_LOG(3,(THIS_FILE, " error: printing message")); - pjsip_tx_data_dec_ref(tdata); - return -250; + PJ_LOG(3,(THIS_FILE, " error: printing message")); + pjsip_tx_data_dec_ref(tdata); + return -250; } msgbuf[len] = '\0'; PJ_LOG(5,(THIS_FILE, "%d bytes request created:--begin-msg--\n" - "%s\n" - "--end-msg--", len, msgbuf)); + "%s\n" + "--end-msg--", len, msgbuf)); /* Now parse the message. */ pj_list_init(&err_list); msg = pjsip_parse_msg( tdata->pool, msgbuf, len, &err_list); if (msg == NULL) { - pjsip_parser_err_report *e; + pjsip_parser_err_report *e; - PJ_LOG(3,(THIS_FILE, " error: parsing message message")); + PJ_LOG(3,(THIS_FILE, " error: parsing message message")); - e = err_list.next; - while (e != &err_list) { - PJ_LOG(3,(THIS_FILE, " %s in line %d col %d hname=%.*s", - pj_exception_id_name(e->except_code), - e->line, e->col+1, - (int)e->hname.slen, - e->hname.ptr)); - e = e->next; - } + e = err_list.next; + while (e != &err_list) { + PJ_LOG(3,(THIS_FILE, " %s in line %d col %d hname=%.*s", + pj_exception_id_name(e->except_code), + e->line, e->col+1, + (int)e->hname.slen, + e->hname.ptr)); + e = e->next; + } - pjsip_tx_data_dec_ref(tdata); - return -256; + pjsip_tx_data_dec_ref(tdata); + return -256; } /* Check the existence of port, other_param, and header param. @@ -501,44 +500,44 @@ static int txdata_test_uri_params(void) /* Port in request URI. */ uri = (pjsip_sip_uri*) pjsip_uri_get_uri(msg->line.req.uri); if (uri->port != 5061) { - PJ_LOG(3,(THIS_FILE, " error: port not present in request URI")); - pjsip_tx_data_dec_ref(tdata); - return -260; + PJ_LOG(3,(THIS_FILE, " error: port not present in request URI")); + pjsip_tx_data_dec_ref(tdata); + return -260; } /* other_param in request_uri */ param = pjsip_param_find(&uri->other_param, &pname); if (param == NULL || pj_strcmp2(¶m->value, "param 1") != 0) { - PJ_LOG(3,(THIS_FILE, " error: x-param not present in request URI")); - pjsip_tx_data_dec_ref(tdata); - return -261; + PJ_LOG(3,(THIS_FILE, " error: x-param not present in request URI")); + pjsip_tx_data_dec_ref(tdata); + return -261; } /* header param in request uri. */ if (!pj_list_empty(&uri->header_param)) { - PJ_LOG(3,(THIS_FILE, " error: hparam in request URI")); - pjsip_tx_data_dec_ref(tdata); - return -262; + PJ_LOG(3,(THIS_FILE, " error: hparam in request URI")); + pjsip_tx_data_dec_ref(tdata); + return -262; } /* Port in From header. */ from_hdr = (pjsip_from_hdr*) pjsip_msg_find_hdr(msg, PJSIP_H_FROM, NULL); uri = (pjsip_sip_uri*) pjsip_uri_get_uri(from_hdr->uri); if (uri->port != 0) { - PJ_LOG(3,(THIS_FILE, " error: port most not exist in From header")); - pjsip_tx_data_dec_ref(tdata); - return -270; + PJ_LOG(3,(THIS_FILE, " error: port most not exist in From header")); + pjsip_tx_data_dec_ref(tdata); + return -270; } /* other_param in From header */ param = pjsip_param_find(&uri->other_param, &pname); if (param == NULL || pj_strcmp2(¶m->value, "param 1") != 0) { - PJ_LOG(3,(THIS_FILE, " error: x-param not present in From header")); - pjsip_tx_data_dec_ref(tdata); - return -271; + PJ_LOG(3,(THIS_FILE, " error: x-param not present in From header")); + pjsip_tx_data_dec_ref(tdata); + return -271; } /* header param in From header. */ if (!pj_list_empty(&uri->header_param)) { - PJ_LOG(3,(THIS_FILE, " error: hparam in From header")); - pjsip_tx_data_dec_ref(tdata); - return -272; + PJ_LOG(3,(THIS_FILE, " error: hparam in From header")); + pjsip_tx_data_dec_ref(tdata); + return -272; } @@ -546,22 +545,22 @@ static int txdata_test_uri_params(void) to_hdr = (pjsip_to_hdr*) pjsip_msg_find_hdr(msg, PJSIP_H_TO, NULL); uri = (pjsip_sip_uri*) pjsip_uri_get_uri(to_hdr->uri); if (uri->port != 0) { - PJ_LOG(3,(THIS_FILE, " error: port most not exist in To header")); - pjsip_tx_data_dec_ref(tdata); - return -280; + PJ_LOG(3,(THIS_FILE, " error: port most not exist in To header")); + pjsip_tx_data_dec_ref(tdata); + return -280; } /* other_param in To header */ param = pjsip_param_find(&uri->other_param, &pname); if (param == NULL || pj_strcmp2(¶m->value, "param 1") != 0) { - PJ_LOG(3,(THIS_FILE, " error: x-param not present in To header")); - pjsip_tx_data_dec_ref(tdata); - return -281; + PJ_LOG(3,(THIS_FILE, " error: x-param not present in To header")); + pjsip_tx_data_dec_ref(tdata); + return -281; } /* header param in From header. */ if (!pj_list_empty(&uri->header_param)) { - PJ_LOG(3,(THIS_FILE, " error: hparam in To header")); - pjsip_tx_data_dec_ref(tdata); - return -282; + PJ_LOG(3,(THIS_FILE, " error: hparam in To header")); + pjsip_tx_data_dec_ref(tdata); + return -282; } @@ -570,54 +569,54 @@ static int txdata_test_uri_params(void) contact_hdr = (pjsip_contact_hdr*) pjsip_msg_find_hdr(msg, PJSIP_H_CONTACT, NULL); uri = (pjsip_sip_uri*) pjsip_uri_get_uri(contact_hdr->uri); if (uri->port != 5061) { - PJ_LOG(3,(THIS_FILE, " error: port not present in Contact header")); - pjsip_tx_data_dec_ref(tdata); - return -290; + PJ_LOG(3,(THIS_FILE, " error: port not present in Contact header")); + pjsip_tx_data_dec_ref(tdata); + return -290; } /* other_param in Contact header */ param = pjsip_param_find(&uri->other_param, &pname); if (param == NULL || pj_strcmp2(¶m->value, "param 1") != 0) { - PJ_LOG(3,(THIS_FILE, " error: x-param not present in Contact header")); - pjsip_tx_data_dec_ref(tdata); - return -291; + PJ_LOG(3,(THIS_FILE, " error: x-param not present in Contact header")); + pjsip_tx_data_dec_ref(tdata); + return -291; } /* header param in Contact header. */ if (pj_list_empty(&uri->header_param)) { - PJ_LOG(3,(THIS_FILE, " error: hparam is missing in Contact header")); - pjsip_tx_data_dec_ref(tdata); - return -292; + PJ_LOG(3,(THIS_FILE, " error: hparam is missing in Contact header")); + pjsip_tx_data_dec_ref(tdata); + return -292; } /* Check for X-Hdr-1 */ param = pjsip_param_find(&uri->header_param, &hname); if (param == NULL || pj_strcmp2(¶m->value, "Header 1")!=0) { - PJ_LOG(3,(THIS_FILE, " error: hparam is missing in Contact header")); - pjsip_tx_data_dec_ref(tdata); - return -293; + PJ_LOG(3,(THIS_FILE, " error: hparam is missing in Contact header")); + pjsip_tx_data_dec_ref(tdata); + return -293; } /* Check for X-Empty-Hdr */ param = pjsip_param_find(&uri->header_param, &hemptyname); if (param == NULL || pj_strcmp2(¶m->value, "")!=0) { - PJ_LOG(3,(THIS_FILE, " error: hparam is missing in Contact header")); - pjsip_tx_data_dec_ref(tdata); - return -294; + PJ_LOG(3,(THIS_FILE, " error: hparam is missing in Contact header")); + pjsip_tx_data_dec_ref(tdata); + return -294; } /* Check that headers are present in the request. */ hdr = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(msg, &hname, NULL); + pjsip_msg_find_hdr_by_name(msg, &hname, NULL); if (hdr == NULL || pj_strcmp2(&hdr->hvalue, "Header 1")!=0) { - PJ_LOG(3,(THIS_FILE, " error: header X-Hdr-1 not created")); - pjsip_tx_data_dec_ref(tdata); - return -300; + PJ_LOG(3,(THIS_FILE, " error: header X-Hdr-1 not created")); + pjsip_tx_data_dec_ref(tdata); + return -300; } hdr = (pjsip_generic_string_hdr*) - pjsip_msg_find_hdr_by_name(msg, &hemptyname, NULL); + pjsip_msg_find_hdr_by_name(msg, &hemptyname, NULL); if (hdr == NULL || pj_strcmp2(¶m->value, "")!=0) { - PJ_LOG(3,(THIS_FILE, " error: header X-Empty-Hdr not created")); - pjsip_tx_data_dec_ref(tdata); - return -330; + PJ_LOG(3,(THIS_FILE, " error: header X-Empty-Hdr not created")); + pjsip_tx_data_dec_ref(tdata); + return -330; } pjsip_tx_data_dec_ref(tdata); @@ -644,27 +643,27 @@ static int create_request_bench(pj_timestamp *p_elapsed) elapsed.u64 = 0; for (i=0; iu64 = elapsed.u64; @@ -672,8 +671,8 @@ static int create_request_bench(pj_timestamp *p_elapsed) on_error: for (i=0; iu64 = elapsed.u64; @@ -764,8 +763,8 @@ static int create_response_bench(pj_timestamp *p_elapsed) on_error: for (i=0; ipjsip_endpt_create_request()"); + msgs, "msg/sec", + "Number of typical request messages that can be created " + "per second with pjsip_endpt_create_request()"); /* @@ -829,16 +828,16 @@ int txdata_test(void) */ PJ_LOG(3,(THIS_FILE, " benchmarking response creation:")); for (i=0; ipjsip_endpt_create_response()"); + msgs, "msg/sec", + "Number of typical response messages that can be created " + "per second with pjsip_endpt_create_response()"); return 0; diff --git a/pjsip/src/test/uri_test.c b/pjsip/src/test/uri_test.c index 8b7c3a5f32..9cc30f45f9 100644 --- a/pjsip/src/test/uri_test.c +++ b/pjsip/src/test/uri_test.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -25,21 +24,21 @@ #define ALPHANUM "abcdefghijklmnopqrstuvwxyz" \ - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ - "0123456789" -#define MARK "-_.!~*'()" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ + "0123456789" +#define MARK "-_.!~*'()" #define USER_CHAR ALPHANUM MARK "&=+$,;?/" #define PASS_CHAR ALPHANUM MARK "&=+$," #define PARAM_CHAR ALPHANUM MARK "[]/:&+$" -#define POOL_SIZE 8000 +#define POOL_SIZE 8000 #if defined(PJ_DEBUG) && PJ_DEBUG!=0 -# define LOOP_COUNT 10000 +# define LOOP_COUNT 10000 #else -# define LOOP_COUNT 40000 +# define LOOP_COUNT 40000 #endif -#define AVERAGE_URL_LEN 80 -#define THREAD_COUNT 4 +#define AVERAGE_URL_LEN 80 +#define THREAD_COUNT 4 static struct { @@ -85,284 +84,284 @@ static pjsip_uri *create_uri39( pj_pool_t *pool ); static pjsip_uri *create_uri40( pj_pool_t *pool ); static pjsip_uri *create_dummy( pj_pool_t *pool ); -#define ERR_NOT_EQUAL -1001 -#define ERR_SYNTAX_ERR -1002 +#define ERR_NOT_EQUAL -1001 +#define ERR_SYNTAX_ERR -1002 struct uri_test { - pj_status_t status; - char str[PJSIP_MAX_URL_SIZE]; - pjsip_uri *(*creator)(pj_pool_t *pool); - const char *printed; - pj_size_t len; + pj_status_t status; + char str[PJSIP_MAX_URL_SIZE]; + pjsip_uri *(*creator)(pj_pool_t *pool); + const char *printed; + pj_size_t len; } uri_test_array[] = { { - PJ_SUCCESS, - "sip:localhost", - &create_uri0 + PJ_SUCCESS, + "sip:localhost", + &create_uri0 }, { - PJ_SUCCESS, - "sip:user@localhost", - &create_uri1 + PJ_SUCCESS, + "sip:user@localhost", + &create_uri1 }, { - PJ_SUCCESS, - "sip:user:password@localhost:5060", - &create_uri2, }, + PJ_SUCCESS, + "sip:user:password@localhost:5060", + &create_uri2, }, { - /* Port is specified should not match unspecified port. */ - ERR_NOT_EQUAL, - "sip:localhost:5060", - &create_uri3 + /* Port is specified should not match unspecified port. */ + ERR_NOT_EQUAL, + "sip:localhost:5060", + &create_uri3 }, { - /* All recognized parameters. */ - PJ_SUCCESS, - "sip:localhost;transport=tcp;user=ip;ttl=255;lr;maddr=127.0.0.1;method=ACK", - &create_uri4 + /* All recognized parameters. */ + PJ_SUCCESS, + "sip:localhost;transport=tcp;user=ip;ttl=255;lr;maddr=127.0.0.1;method=ACK", + &create_uri4 }, { - /* Params mixed with other params and header params. */ - PJ_SUCCESS, - "sip:localhost;pickup=hurry;user=phone;message=I%20am%20sorry" - "?Subject=Hello%20There&Server=SIP%20Server", - &create_uri5 + /* Params mixed with other params and header params. */ + PJ_SUCCESS, + "sip:localhost;pickup=hurry;user=phone;message=I%20am%20sorry" + "?Subject=Hello%20There&Server=SIP%20Server", + &create_uri5 }, { - /* SIPS. */ - PJ_SUCCESS, - "sips:localhost", - &create_uri6, + /* SIPS. */ + PJ_SUCCESS, + "sips:localhost", + &create_uri6, }, { - /* Name address */ - PJ_SUCCESS, - "", - &create_uri7 + /* Name address */ + PJ_SUCCESS, + "", + &create_uri7 }, { - /* Name address with display name and SIPS scheme with some redundant - * whitespaced. - */ - PJ_SUCCESS, - " Power Administrator ", - &create_uri8 + /* Name address with display name and SIPS scheme with some redundant + * whitespaced. + */ + PJ_SUCCESS, + " Power Administrator ", + &create_uri8 }, { - /* Name address. */ - PJ_SUCCESS, - " \"User\" ", - &create_uri9 + /* Name address. */ + PJ_SUCCESS, + " \"User\" ", + &create_uri9 }, { - /* Escaped sequence in display name (display=Strange User\"\\\"). */ - PJ_SUCCESS, - " \"Strange User\\\"\\\\\\\"\" ", - &create_uri10, + /* Escaped sequence in display name (display=Strange User\"\\\"). */ + PJ_SUCCESS, + " \"Strange User\\\"\\\\\\\"\" ", + &create_uri10, }, { - /* Errorneous escaping in display name. */ - ERR_SYNTAX_ERR, - " \"Rogue User\\\" ", - &create_uri11, + /* Errorneous escaping in display name. */ + ERR_SYNTAX_ERR, + " \"Rogue User\\\" ", + &create_uri11, }, { - /* Dangling quote in display name, but that should be OK. */ - PJ_SUCCESS, - "Strange User\" ", - &create_uri12, + /* Dangling quote in display name, but that should be OK. */ + PJ_SUCCESS, + "Strange User\" ", + &create_uri12, }, { - /* Special characters in parameter value must be quoted. */ - PJ_SUCCESS, - "sip:localhost;pvalue=\"hello world\"", - &create_uri13, + /* Special characters in parameter value must be quoted. */ + PJ_SUCCESS, + "sip:localhost;pvalue=\"hello world\"", + &create_uri13, }, { - /* Excercise strange character sets allowed in display, user, password, - * host, and port. - */ - PJ_SUCCESS, - "This is -. !% *_+`'~ me ", - &create_uri14, + /* Excercise strange character sets allowed in display, user, password, + * host, and port. + */ + PJ_SUCCESS, + "This is -. !% *_+`'~ me ", + &create_uri14, }, { - /* Another excercise to the allowed character sets to the hostname. */ - PJ_SUCCESS, - "sip:" ALPHANUM "-_.com", - &create_uri15, + /* Another excercise to the allowed character sets to the hostname. */ + PJ_SUCCESS, + "sip:" ALPHANUM "-_.com", + &create_uri15, }, { - /* Another excercise to the allowed character sets to the username - * and password. - */ - PJ_SUCCESS, - "sip:" USER_CHAR ":" PASS_CHAR "@host", - &create_uri16, + /* Another excercise to the allowed character sets to the username + * and password. + */ + PJ_SUCCESS, + "sip:" USER_CHAR ":" PASS_CHAR "@host", + &create_uri16, }, { - /* Excercise to the pname and pvalue, and mixup of other-param - * between 'recognized' params. - */ - PJ_SUCCESS, - "sip:host;user=ip;" PARAM_CHAR "%21=" PARAM_CHAR "%21" - ";lr;other=1;transport=sctp;other2", - &create_uri17, + /* Excercise to the pname and pvalue, and mixup of other-param + * between 'recognized' params. + */ + PJ_SUCCESS, + "sip:host;user=ip;" PARAM_CHAR "%21=" PARAM_CHAR "%21" + ";lr;other=1;transport=sctp;other2", + &create_uri17, }, { - /* 18: This should trigger syntax error. */ - ERR_SYNTAX_ERR, - "sip:", - &create_dummy, + /* 18: This should trigger syntax error. */ + ERR_SYNTAX_ERR, + "sip:", + &create_dummy, }, { - /* 19: Syntax error: whitespace after scheme. */ - ERR_SYNTAX_ERR, - "sip :host", - &create_dummy, + /* 19: Syntax error: whitespace after scheme. */ + ERR_SYNTAX_ERR, + "sip :host", + &create_dummy, }, { - /* 20: Syntax error: whitespace before hostname. */ - ERR_SYNTAX_ERR, - "sip: host", - &create_dummy, + /* 20: Syntax error: whitespace before hostname. */ + ERR_SYNTAX_ERR, + "sip: host", + &create_dummy, }, { - /* 21: Syntax error: invalid port. */ - ERR_SYNTAX_ERR, - "sip:user:password", - &create_dummy, + /* 21: Syntax error: invalid port. */ + ERR_SYNTAX_ERR, + "sip:user:password", + &create_dummy, }, { - /* 22: Syntax error: no host. */ - ERR_SYNTAX_ERR, - "sip:user@", - &create_dummy, + /* 22: Syntax error: no host. */ + ERR_SYNTAX_ERR, + "sip:user@", + &create_dummy, }, { - /* 23: Syntax error: no user/host. */ - ERR_SYNTAX_ERR, - "sip:@", - &create_dummy, + /* 23: Syntax error: no user/host. */ + ERR_SYNTAX_ERR, + "sip:@", + &create_dummy, }, { - /* 24: Syntax error: empty string. */ - ERR_SYNTAX_ERR, - "", - &create_dummy, + /* 24: Syntax error: empty string. */ + ERR_SYNTAX_ERR, + "", + &create_dummy, }, { - /* 25: Simple tel: URI with global context */ - PJ_SUCCESS, - "tel:+1-201-555-0123", - &create_uri25, - "tel:+1-201-555-0123" + /* 25: Simple tel: URI with global context */ + PJ_SUCCESS, + "tel:+1-201-555-0123", + &create_uri25, + "tel:+1-201-555-0123" }, { - /* 26: Simple tel: URI with local context */ - PJ_SUCCESS, - "tel:7042;phone-context=example.com", - &create_uri26, - "tel:7042;phone-context=example.com" + /* 26: Simple tel: URI with local context */ + PJ_SUCCESS, + "tel:7042;phone-context=example.com", + &create_uri26, + "tel:7042;phone-context=example.com" }, { - /* 27: Simple tel: URI with local context */ - PJ_SUCCESS, - "tel:863-1234;phone-context=+1-914-555", - &create_uri27, - "tel:863-1234;phone-context=+1-914-555" + /* 27: Simple tel: URI with local context */ + PJ_SUCCESS, + "tel:863-1234;phone-context=+1-914-555", + &create_uri27, + "tel:863-1234;phone-context=+1-914-555" }, { - /* 28: Comparison between local and global number */ - ERR_NOT_EQUAL, - "tel:+1", - &create_uri28, - "tel:+1" + /* 28: Comparison between local and global number */ + ERR_NOT_EQUAL, + "tel:+1", + &create_uri28, + "tel:+1" }, { - /* 29: tel: with some visual chars and spaces */ - PJ_SUCCESS, - "tel:(44).1234-*#+Deaf", - &create_uri29, - "tel:(44).1234-*#+Deaf" + /* 29: tel: with some visual chars and spaces */ + PJ_SUCCESS, + "tel:(44).1234-*#+Deaf", + &create_uri29, + "tel:(44).1234-*#+Deaf" }, { - /* 30: isub parameters */ - PJ_SUCCESS, - "tel:+1;isub=/:@&$,-_.!~*'()[]/:&$aA1%21+=", - &create_uri30, - "tel:+1;isub=/:@&$,-_.!~*'()[]/:&$aA1!+%3d" + /* 30: isub parameters */ + PJ_SUCCESS, + "tel:+1;isub=/:@&$,-_.!~*'()[]/:&$aA1%21+=", + &create_uri30, + "tel:+1;isub=/:@&$,-_.!~*'()[]/:&$aA1!+%3d" }, { - /* 31: extension number parsing and encoding */ - PJ_SUCCESS, - "tel:+1;ext=+123", - &create_uri31, - "tel:+1;ext=%2b123" + /* 31: extension number parsing and encoding */ + PJ_SUCCESS, + "tel:+1;ext=+123", + &create_uri31, + "tel:+1;ext=%2b123" }, { - /* 32: context parameter parsing and encoding */ - PJ_SUCCESS, - "tel:911;phone-context=+1-911", - &create_uri32, - "tel:911;phone-context=+1-911" + /* 32: context parameter parsing and encoding */ + PJ_SUCCESS, + "tel:911;phone-context=+1-911", + &create_uri32, + "tel:911;phone-context=+1-911" }, { - /* 33: case-insensitive comparison */ - PJ_SUCCESS, - "tel:911;phone-context=emergency.example.com", - &create_uri33, - "tel:911;phone-context=emergency.example.com" + /* 33: case-insensitive comparison */ + PJ_SUCCESS, + "tel:911;phone-context=emergency.example.com", + &create_uri33, + "tel:911;phone-context=emergency.example.com" }, { - /* 34: parameter only appears in one URL */ - ERR_NOT_EQUAL, - "tel:911;p1=p1;p2=p2", - &create_uri34, - "tel:911;p1=p1;p2=p2" + /* 34: parameter only appears in one URL */ + ERR_NOT_EQUAL, + "tel:911;p1=p1;p2=p2", + &create_uri34, + "tel:911;p1=p1;p2=p2" }, { - /* 35: IPv6 in host and maddr parameter */ - PJ_SUCCESS, - "sip:user@[::1];maddr=[::01]", - &create_uri35, - "sip:user@[::1];maddr=[::01]" + /* 35: IPv6 in host and maddr parameter */ + PJ_SUCCESS, + "sip:user@[::1];maddr=[::01]", + &create_uri35, + "sip:user@[::1];maddr=[::01]" }, { - /* 36: IPv6 in host and maddr, without username */ - PJ_SUCCESS, - "sip:[::1];maddr=[::01]", - &create_uri36, - "sip:[::1];maddr=[::01]" + /* 36: IPv6 in host and maddr, without username */ + PJ_SUCCESS, + "sip:[::1];maddr=[::01]", + &create_uri36, + "sip:[::1];maddr=[::01]" }, { - /* 37: Non-ASCII UTF-8 in display name, with quote */ - PJ_SUCCESS, - "\"\xC0\x81\" ", - &create_uri37, - "\"\xC0\x81\" " + /* 37: Non-ASCII UTF-8 in display name, with quote */ + PJ_SUCCESS, + "\"\xC0\x81\" ", + &create_uri37, + "\"\xC0\x81\" " }, { - /* 38: Non-ASCII UTF-8 in display name, without quote */ - PJ_SUCCESS, - "\xC0\x81 ", - &create_uri38, - "\"\xC0\x81\" " + /* 38: Non-ASCII UTF-8 in display name, without quote */ + PJ_SUCCESS, + "\xC0\x81 ", + &create_uri38, + "\"\xC0\x81\" " }, { - /* Even number of backslash before end quote in display name. */ - PJ_SUCCESS, - "\"User\\\\\" ", - &create_uri39, + /* Even number of backslash before end quote in display name. */ + PJ_SUCCESS, + "\"User\\\\\" ", + &create_uri39, }, { - /* Quoted display name. */ - PJ_SUCCESS, - "\"\\\"User\\\"\" ", - &create_uri40, + /* Quoted display name. */ + PJ_SUCCESS, + "\"\\\"User\\\"\" ", + &create_uri40, } }; @@ -426,13 +425,13 @@ static pjsip_uri *create_uri4(pj_pool_t *pool) } #define param_add(list,pname,pvalue) \ - do { \ - pjsip_param *param; \ - param=PJ_POOL_ALLOC_T(pool, pjsip_param); \ - param->name = pj_str(pname); \ - param->value = pj_str(pvalue); \ - pj_list_insert_before(&list, param); \ - } while (0) + do { \ + pjsip_param *param; \ + param=PJ_POOL_ALLOC_T(pool, pjsip_param); \ + param->name = pj_str(pname); \ + param->value = pj_str(pvalue); \ + pj_list_insert_before(&list, param); \ + } while (0) static pjsip_uri *create_uri5(pj_pool_t *pool) { @@ -822,7 +821,7 @@ static pj_status_t do_uri_test(pj_pool_t *pool, struct uri_test *entry) pj_timestamp t1, t2; if (entry->len == 0) - entry->len = pj_ansi_strlen(entry->str); + entry->len = pj_ansi_strlen(entry->str); #if defined(PJSIP_UNESCAPE_IN_PLACE) && PJSIP_UNESCAPE_IN_PLACE!=0 input = pj_pool_alloc(pool, entry->len + 1); @@ -837,16 +836,16 @@ static pj_status_t do_uri_test(pj_pool_t *pool, struct uri_test *entry) var.parse_len = var.parse_len + entry->len; parsed_uri = pjsip_parse_uri(pool, input, entry->len, 0); if (!parsed_uri) { - /* Parsing failed. If the entry says that this is expected, then - * return OK. - */ - status = entry->status==ERR_SYNTAX_ERR ? PJ_SUCCESS : -10; - if (status != 0) { - PJ_LOG(3,(THIS_FILE, " uri parse error!\n" - " uri='%s'\n", - input)); - } - goto on_return; + /* Parsing failed. If the entry says that this is expected, then + * return OK. + */ + status = entry->status==ERR_SYNTAX_ERR ? PJ_SUCCESS : -10; + if (status != 0) { + PJ_LOG(3,(THIS_FILE, " uri parse error!\n" + " uri='%s'\n", + input)); + } + goto on_return; } pj_get_timestamp(&t2); pj_sub_timestamp(&t2, &t1); @@ -862,8 +861,8 @@ static pj_status_t do_uri_test(pj_pool_t *pool, struct uri_test *entry) pj_get_timestamp(&t1); len = pjsip_uri_print( PJSIP_URI_IN_OTHER, parsed_uri, s1.ptr, PJSIP_MAX_URL_SIZE); if (len < 1) { - status = -20; - goto on_return; + status = -20; + goto on_return; } s1.ptr[len] = '\0'; s1.slen = len; @@ -875,8 +874,8 @@ static pj_status_t do_uri_test(pj_pool_t *pool, struct uri_test *entry) len = pjsip_uri_print( PJSIP_URI_IN_OTHER, ref_uri, s2.ptr, PJSIP_MAX_URL_SIZE); if (len < 1) { - status = -30; - goto on_return; + status = -30; + goto on_return; } s2.ptr[len] = '\0'; s2.slen = len; @@ -885,22 +884,22 @@ static pj_status_t do_uri_test(pj_pool_t *pool, struct uri_test *entry) pj_get_timestamp(&t1); status = pjsip_uri_cmp(PJSIP_URI_IN_OTHER, parsed_uri, ref_uri); if (status != 0) { - /* Not equal. See if this is the expected status. */ - status = entry->status==ERR_NOT_EQUAL ? PJ_SUCCESS : -40; - if (status != 0) { - PJ_LOG(3,(THIS_FILE, " uri comparison mismatch, status=%d:\n" - " uri1='%s'\n" - " uri2='%s'", - status, s1.ptr, s2.ptr)); - } - goto on_return; + /* Not equal. See if this is the expected status. */ + status = entry->status==ERR_NOT_EQUAL ? PJ_SUCCESS : -40; + if (status != 0) { + PJ_LOG(3,(THIS_FILE, " uri comparison mismatch, status=%d:\n" + " uri1='%s'\n" + " uri2='%s'", + status, s1.ptr, s2.ptr)); + } + goto on_return; } else { - /* Equal. See if this is the expected status. */ - status = entry->status==PJ_SUCCESS ? PJ_SUCCESS : -50; - if (status != PJ_SUCCESS) { - goto on_return; - } + /* Equal. See if this is the expected status. */ + status = entry->status==PJ_SUCCESS ? PJ_SUCCESS : -50; + if (status != PJ_SUCCESS) { + goto on_return; + } } var.cmp_len = var.cmp_len + len; @@ -910,23 +909,23 @@ static pj_status_t do_uri_test(pj_pool_t *pool, struct uri_test *entry) /* Compare text. */ if (entry->printed) { - if (pj_strcmp2(&s1, entry->printed) != 0) { - /* Not equal. */ - PJ_LOG(3,(THIS_FILE, " uri print mismatch:\n" - " printed='%s'\n" - " expectd='%s'", - s1.ptr, entry->printed)); - status = -60; - } + if (pj_strcmp2(&s1, entry->printed) != 0) { + /* Not equal. */ + PJ_LOG(3,(THIS_FILE, " uri print mismatch:\n" + " printed='%s'\n" + " expectd='%s'", + s1.ptr, entry->printed)); + status = -60; + } } else { - if (pj_strcmp(&s1, &s2) != 0) { - /* Not equal. */ - PJ_LOG(3,(THIS_FILE, " uri print mismatch:\n" - " uri1='%s'\n" - " uri2='%s'", - s1.ptr, s2.ptr)); - status = -70; - } + if (pj_strcmp(&s1, &s2) != 0) { + /* Not equal. */ + PJ_LOG(3,(THIS_FILE, " uri print mismatch:\n" + " uri1='%s'\n" + " uri2='%s'", + s1.ptr, s2.ptr)); + status = -70; + } } on_return: @@ -942,14 +941,14 @@ static int simple_uri_test(void) PJ_LOG(3,(THIS_FILE, " simple test")); for (i=0; i max) max = run[i].parse; + if (run[i].parse > max) max = run[i].parse; PJ_LOG(3,("", " Maximum URI parse/sec=%u", max)); pj_ansi_sprintf(desc, "Number of SIP/TEL URIs that can be parsed with " - "pjsip_parse_uri() per second " - "(tested with %d URI set, with average length of " - "%d chars)", - (int)PJ_ARRAY_SIZE(uri_test_array), (int)avg_len); + "pjsip_parse_uri() per second " + "(tested with %d URI set, with average length of " + "%d chars)", + (int)PJ_ARRAY_SIZE(uri_test_array), (int)avg_len); report_ival("uri-parse-per-sec", max, "URI/sec", desc); /* URI parsing bandwidth */ report_ival("uri-parse-bandwidth-mb", (int)avg_len*max/1000000, "MB/sec", - "URI parsing bandwidth in megabytes (number of megabytes " - "worth of URI that can be parsed per second)"); + "URI parsing bandwidth in megabytes (number of megabytes " + "worth of URI that can be parsed per second)"); /* Print maximum print/sec */ for (i=0, max=0; i max) max = run[i].print; + if (run[i].print > max) max = run[i].print; PJ_LOG(3,("", " Maximum URI print/sec=%u", max)); pj_ansi_sprintf(desc, "Number of SIP/TEL URIs that can be printed with " - "pjsip_uri_print() per second " - "(tested with %d URI set, with average length of " - "%d chars)", - (int)PJ_ARRAY_SIZE(uri_test_array), (int)avg_len); + "pjsip_uri_print() per second " + "(tested with %d URI set, with average length of " + "%d chars)", + (int)PJ_ARRAY_SIZE(uri_test_array), (int)avg_len); report_ival("uri-print-per-sec", max, "URI/sec", desc); /* Print maximum detect/sec */ for (i=0, max=0; i max) max = run[i].cmp; + if (run[i].cmp > max) max = run[i].cmp; PJ_LOG(3,("", " Maximum URI comparison/sec=%u", max)); pj_ansi_sprintf(desc, "Number of SIP/TEL URIs that can be compared with " - "pjsip_uri_cmp() per second " - "(tested with %d URI set, with average length of " - "%d chars)", - (int)PJ_ARRAY_SIZE(uri_test_array), (int)avg_len); + "pjsip_uri_cmp() per second " + "(tested with %d URI set, with average length of " + "%d chars)", + (int)PJ_ARRAY_SIZE(uri_test_array), (int)avg_len); report_ival("uri-cmp-per-sec", max, "URI/sec", desc); -#endif /* INCLUDE_BENCHMARKS */ +#endif /* INCLUDE_BENCHMARKS */ return PJ_SUCCESS; } diff --git a/tests/pjsua/config_site.py b/tests/pjsua/config_site.py index a6e4f29a2b..c1eff7626e 100644 --- a/tests/pjsua/config_site.py +++ b/tests/pjsua/config_site.py @@ -1,4 +1,3 @@ -# $Id$ # Specify if host has sound device, or test should be performed using sound device HAS_SND_DEV = 0 diff --git a/tests/pjsua/inc_cfg.py b/tests/pjsua/inc_cfg.py index 991506b415..c3cfddc0c3 100644 --- a/tests/pjsua/inc_cfg.py +++ b/tests/pjsua/inc_cfg.py @@ -1,4 +1,3 @@ -# $Id$ import random import config_site import socket diff --git a/tests/pjsua/inc_const.py b/tests/pjsua/inc_const.py index c54c0c492e..a3932f47dd 100644 --- a/tests/pjsua/inc_const.py +++ b/tests/pjsua/inc_const.py @@ -1,4 +1,3 @@ -# $Id$ # Useful constants diff --git a/tests/pjsua/inc_sdp.py b/tests/pjsua/inc_sdp.py index 97dfdc7733..fb92307da0 100644 --- a/tests/pjsua/inc_sdp.py +++ b/tests/pjsua/inc_sdp.py @@ -1,4 +1,3 @@ -# $Id$ # SDP template sdp_templ = \ diff --git a/tests/pjsua/inc_sip.py b/tests/pjsua/inc_sip.py index 2cc1a17a8c..bf85918e03 100644 --- a/tests/pjsua/inc_sip.py +++ b/tests/pjsua/inc_sip.py @@ -1,4 +1,3 @@ -# $Id$ # from socket import * import re diff --git a/tests/pjsua/mod_call.py b/tests/pjsua/mod_call.py index d8d8975fb8..6068075739 100644 --- a/tests/pjsua/mod_call.py +++ b/tests/pjsua/mod_call.py @@ -1,4 +1,3 @@ -# $Id$ import time import imp import sys diff --git a/tests/pjsua/mod_media_playrec.py b/tests/pjsua/mod_media_playrec.py index 77c97a4986..bf84a58959 100644 --- a/tests/pjsua/mod_media_playrec.py +++ b/tests/pjsua/mod_media_playrec.py @@ -1,4 +1,3 @@ -# $Id$ # PLAYFILE -> RECFILE: # Input file is played and is recorded to output, then compare them. diff --git a/tests/pjsua/mod_pesq.py b/tests/pjsua/mod_pesq.py index f9d31f40ef..09611c3f64 100644 --- a/tests/pjsua/mod_pesq.py +++ b/tests/pjsua/mod_pesq.py @@ -1,4 +1,3 @@ -# $Id$ # Quality test of media calls. # - UA1 calls UA2 diff --git a/tests/pjsua/mod_pres.py b/tests/pjsua/mod_pres.py index 4257b8823c..c6b4ccd0b8 100644 --- a/tests/pjsua/mod_pres.py +++ b/tests/pjsua/mod_pres.py @@ -1,4 +1,3 @@ -# $Id$ import time import imp import sys diff --git a/tests/pjsua/mod_recvfrom.py b/tests/pjsua/mod_recvfrom.py index 4305bfb427..5641005e6d 100644 --- a/tests/pjsua/mod_recvfrom.py +++ b/tests/pjsua/mod_recvfrom.py @@ -1,4 +1,3 @@ -# $Id$ import imp import sys import inc_sip as sip diff --git a/tests/pjsua/mod_run.py b/tests/pjsua/mod_run.py index 03548eea56..1386d3ea7c 100644 --- a/tests/pjsua/mod_run.py +++ b/tests/pjsua/mod_run.py @@ -1,4 +1,3 @@ -# $Id$ import imp import sys diff --git a/tests/pjsua/mod_sendto.py b/tests/pjsua/mod_sendto.py index 50dc0fe84c..c1a40b0441 100644 --- a/tests/pjsua/mod_sendto.py +++ b/tests/pjsua/mod_sendto.py @@ -1,4 +1,3 @@ -# $Id$ import imp import sys import inc_sip as sip diff --git a/tests/pjsua/mod_sipp.py b/tests/pjsua/mod_sipp.py index 92fbe1c559..1104935161 100644 --- a/tests/pjsua/mod_sipp.py +++ b/tests/pjsua/mod_sipp.py @@ -1,4 +1,3 @@ -# $Id$ ## Automatic test module for SIPp. ## diff --git a/tests/pjsua/run.py b/tests/pjsua/run.py index cffc38470f..2ffaeabb5b 100644 --- a/tests/pjsua/run.py +++ b/tests/pjsua/run.py @@ -1,4 +1,3 @@ -# $Id$ import sys import imp import re diff --git a/tests/pjsua/runall.py b/tests/pjsua/runall.py index 2453722656..73727f3c92 100644 --- a/tests/pjsua/runall.py +++ b/tests/pjsua/runall.py @@ -1,4 +1,3 @@ -# $Id$ import os import sys import time diff --git a/tests/pjsua/scripts-call/100_simplecall.py b/tests/pjsua/scripts-call/100_simplecall.py index c6bfcb3fab..18277df1e8 100644 --- a/tests/pjsua/scripts-call/100_simplecall.py +++ b/tests/pjsua/scripts-call/100_simplecall.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_0_1.py b/tests/pjsua/scripts-call/150_srtp_0_1.py index 92b0ff4163..3a751ec420 100644 --- a/tests/pjsua/scripts-call/150_srtp_0_1.py +++ b/tests/pjsua/scripts-call/150_srtp_0_1.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_0_3.py b/tests/pjsua/scripts-call/150_srtp_0_3.py index 447a5b096f..c21aabdad9 100644 --- a/tests/pjsua/scripts-call/150_srtp_0_3.py +++ b/tests/pjsua/scripts-call/150_srtp_0_3.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_1_0.py b/tests/pjsua/scripts-call/150_srtp_1_0.py index fa128b6c70..73b2a5ae9a 100644 --- a/tests/pjsua/scripts-call/150_srtp_1_0.py +++ b/tests/pjsua/scripts-call/150_srtp_1_0.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_1_1.py b/tests/pjsua/scripts-call/150_srtp_1_1.py index 3b4446c7c0..a468074787 100644 --- a/tests/pjsua/scripts-call/150_srtp_1_1.py +++ b/tests/pjsua/scripts-call/150_srtp_1_1.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_1_2.py b/tests/pjsua/scripts-call/150_srtp_1_2.py index 03f5886396..7b658bd156 100644 --- a/tests/pjsua/scripts-call/150_srtp_1_2.py +++ b/tests/pjsua/scripts-call/150_srtp_1_2.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_1_3.py b/tests/pjsua/scripts-call/150_srtp_1_3.py index a3d2c814da..a28a74b27a 100644 --- a/tests/pjsua/scripts-call/150_srtp_1_3.py +++ b/tests/pjsua/scripts-call/150_srtp_1_3.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_2_1.py b/tests/pjsua/scripts-call/150_srtp_2_1.py index 16341ebeb7..a9bf186dd8 100644 --- a/tests/pjsua/scripts-call/150_srtp_2_1.py +++ b/tests/pjsua/scripts-call/150_srtp_2_1.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_2_2.py b/tests/pjsua/scripts-call/150_srtp_2_2.py index 9ec2ab69ed..5e0afd5f35 100644 --- a/tests/pjsua/scripts-call/150_srtp_2_2.py +++ b/tests/pjsua/scripts-call/150_srtp_2_2.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_2_3.py b/tests/pjsua/scripts-call/150_srtp_2_3.py index 62a8e0ca71..a8cd69767f 100644 --- a/tests/pjsua/scripts-call/150_srtp_2_3.py +++ b/tests/pjsua/scripts-call/150_srtp_2_3.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_3_0.py b/tests/pjsua/scripts-call/150_srtp_3_0.py index 2783b22621..9002e9fc70 100644 --- a/tests/pjsua/scripts-call/150_srtp_3_0.py +++ b/tests/pjsua/scripts-call/150_srtp_3_0.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_3_1.py b/tests/pjsua/scripts-call/150_srtp_3_1.py index 3028766bb4..190e4050ed 100644 --- a/tests/pjsua/scripts-call/150_srtp_3_1.py +++ b/tests/pjsua/scripts-call/150_srtp_3_1.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_3_2.py b/tests/pjsua/scripts-call/150_srtp_3_2.py index 3ab73f904b..871488aa5b 100644 --- a/tests/pjsua/scripts-call/150_srtp_3_2.py +++ b/tests/pjsua/scripts-call/150_srtp_3_2.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/150_srtp_3_3.py b/tests/pjsua/scripts-call/150_srtp_3_3.py index 1a5fd56d4f..0181ed0794 100644 --- a/tests/pjsua/scripts-call/150_srtp_3_3.py +++ b/tests/pjsua/scripts-call/150_srtp_3_3.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/160_srtp_dtls.py b/tests/pjsua/scripts-call/160_srtp_dtls.py index 421557b7eb..0360ad0597 100644 --- a/tests/pjsua/scripts-call/160_srtp_dtls.py +++ b/tests/pjsua/scripts-call/160_srtp_dtls.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/200_tcp.py b/tests/pjsua/scripts-call/200_tcp.py index 3414f17c2c..95806e3e33 100644 --- a/tests/pjsua/scripts-call/200_tcp.py +++ b/tests/pjsua/scripts-call/200_tcp.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/300_ice_0_1.py b/tests/pjsua/scripts-call/300_ice_0_1.py index fb0b9deff9..2529d5b9e9 100644 --- a/tests/pjsua/scripts-call/300_ice_0_1.py +++ b/tests/pjsua/scripts-call/300_ice_0_1.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/300_ice_1_0.py b/tests/pjsua/scripts-call/300_ice_1_0.py index ef800e7f3f..777ebb0dc1 100644 --- a/tests/pjsua/scripts-call/300_ice_1_0.py +++ b/tests/pjsua/scripts-call/300_ice_1_0.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/300_ice_1_1.py b/tests/pjsua/scripts-call/300_ice_1_1.py index 0bf8cc15b1..439679da69 100644 --- a/tests/pjsua/scripts-call/300_ice_1_1.py +++ b/tests/pjsua/scripts-call/300_ice_1_1.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/301_ice_public_a.py b/tests/pjsua/scripts-call/301_ice_public_a.py index daa4c6cf7f..e037ca3b8e 100644 --- a/tests/pjsua/scripts-call/301_ice_public_a.py +++ b/tests/pjsua/scripts-call/301_ice_public_a.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/301_ice_public_b.py b/tests/pjsua/scripts-call/301_ice_public_b.py index d78992c8ec..bf0c8c7c80 100644 --- a/tests/pjsua/scripts-call/301_ice_public_b.py +++ b/tests/pjsua/scripts-call/301_ice_public_b.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/305_ice_comp_1_2.py b/tests/pjsua/scripts-call/305_ice_comp_1_2.py index 5efeb0ce56..737a782322 100644 --- a/tests/pjsua/scripts-call/305_ice_comp_1_2.py +++ b/tests/pjsua/scripts-call/305_ice_comp_1_2.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/305_ice_comp_2_1.py b/tests/pjsua/scripts-call/305_ice_comp_2_1.py index 304079e385..395ba02367 100644 --- a/tests/pjsua/scripts-call/305_ice_comp_2_1.py +++ b/tests/pjsua/scripts-call/305_ice_comp_2_1.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/320_ice_dtls_srtp.py b/tests/pjsua/scripts-call/320_ice_dtls_srtp.py index 17ca5731c7..fce96a70bd 100644 --- a/tests/pjsua/scripts-call/320_ice_dtls_srtp.py +++ b/tests/pjsua/scripts-call/320_ice_dtls_srtp.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/330_ice_no_ice_vs_trickle_full.py b/tests/pjsua/scripts-call/330_ice_no_ice_vs_trickle_full.py index 9ac441d050..173b7c8f29 100644 --- a/tests/pjsua/scripts-call/330_ice_no_ice_vs_trickle_full.py +++ b/tests/pjsua/scripts-call/330_ice_no_ice_vs_trickle_full.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/330_ice_reg_vs_trickle_full.py b/tests/pjsua/scripts-call/330_ice_reg_vs_trickle_full.py index 7b353630bf..6a28b89520 100644 --- a/tests/pjsua/scripts-call/330_ice_reg_vs_trickle_full.py +++ b/tests/pjsua/scripts-call/330_ice_reg_vs_trickle_full.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/330_ice_trickle_full.py b/tests/pjsua/scripts-call/330_ice_trickle_full.py index b2d692631b..17d6e781a9 100644 --- a/tests/pjsua/scripts-call/330_ice_trickle_full.py +++ b/tests/pjsua/scripts-call/330_ice_trickle_full.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/330_ice_trickle_full_vs_no_ice.py b/tests/pjsua/scripts-call/330_ice_trickle_full_vs_no_ice.py index 48a31aced0..e3acec0a21 100644 --- a/tests/pjsua/scripts-call/330_ice_trickle_full_vs_no_ice.py +++ b/tests/pjsua/scripts-call/330_ice_trickle_full_vs_no_ice.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/330_ice_trickle_full_vs_reg.py b/tests/pjsua/scripts-call/330_ice_trickle_full_vs_reg.py index 8e24f4d45c..6d81cdad80 100644 --- a/tests/pjsua/scripts-call/330_ice_trickle_full_vs_reg.py +++ b/tests/pjsua/scripts-call/330_ice_trickle_full_vs_reg.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/330_ice_trickle_half.py b/tests/pjsua/scripts-call/330_ice_trickle_half.py index 80f23c7148..e2632834eb 100644 --- a/tests/pjsua/scripts-call/330_ice_trickle_half.py +++ b/tests/pjsua/scripts-call/330_ice_trickle_half.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/330_ice_trickle_half_vs_reg.py b/tests/pjsua/scripts-call/330_ice_trickle_half_vs_reg.py index e3b34849e9..916b058e1e 100644 --- a/tests/pjsua/scripts-call/330_ice_trickle_half_vs_reg.py +++ b/tests/pjsua/scripts-call/330_ice_trickle_half_vs_reg.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/350_prack_a.py b/tests/pjsua/scripts-call/350_prack_a.py index 13649f67a9..d11022b1e2 100644 --- a/tests/pjsua/scripts-call/350_prack_a.py +++ b/tests/pjsua/scripts-call/350_prack_a.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/350_prack_b.py b/tests/pjsua/scripts-call/350_prack_b.py index b97bdc22c5..62417380cc 100644 --- a/tests/pjsua/scripts-call/350_prack_b.py +++ b/tests/pjsua/scripts-call/350_prack_b.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-call/400_tel_uri.py b/tests/pjsua/scripts-call/400_tel_uri.py index 2b64c30c9f..f9e57f7969 100644 --- a/tests/pjsua/scripts-call/400_tel_uri.py +++ b/tests/pjsua/scripts-call/400_tel_uri.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-media-playrec/100_resample_lf_11_16.py b/tests/pjsua/scripts-media-playrec/100_resample_lf_11_16.py index 41dd7d431d..2abf2b64dc 100644 --- a/tests/pjsua/scripts-media-playrec/100_resample_lf_11_16.py +++ b/tests/pjsua/scripts-media-playrec/100_resample_lf_11_16.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-media-playrec/100_resample_lf_11_22.py b/tests/pjsua/scripts-media-playrec/100_resample_lf_11_22.py index d966a1f53c..13e143a2da 100644 --- a/tests/pjsua/scripts-media-playrec/100_resample_lf_11_22.py +++ b/tests/pjsua/scripts-media-playrec/100_resample_lf_11_22.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-media-playrec/100_resample_lf_11_32.py b/tests/pjsua/scripts-media-playrec/100_resample_lf_11_32.py index a00c5257eb..ebee1ee5e6 100644 --- a/tests/pjsua/scripts-media-playrec/100_resample_lf_11_32.py +++ b/tests/pjsua/scripts-media-playrec/100_resample_lf_11_32.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-media-playrec/100_resample_lf_11_44.py b/tests/pjsua/scripts-media-playrec/100_resample_lf_11_44.py index 89aadcfa01..ffb3079821 100644 --- a/tests/pjsua/scripts-media-playrec/100_resample_lf_11_44.py +++ b/tests/pjsua/scripts-media-playrec/100_resample_lf_11_44.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-media-playrec/100_resample_lf_11_48.py b/tests/pjsua/scripts-media-playrec/100_resample_lf_11_48.py index 9a4e93b5c1..aa02386d0b 100644 --- a/tests/pjsua/scripts-media-playrec/100_resample_lf_11_48.py +++ b/tests/pjsua/scripts-media-playrec/100_resample_lf_11_48.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-media-playrec/100_resample_lf_11_8.py b/tests/pjsua/scripts-media-playrec/100_resample_lf_11_8.py index 5813b0b412..9ff64376f0 100644 --- a/tests/pjsua/scripts-media-playrec/100_resample_lf_11_8.py +++ b/tests/pjsua/scripts-media-playrec/100_resample_lf_11_8.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-media-playrec/100_resample_lf_8_11.py b/tests/pjsua/scripts-media-playrec/100_resample_lf_8_11.py index 7d19f6f5aa..21d8df5b67 100644 --- a/tests/pjsua/scripts-media-playrec/100_resample_lf_8_11.py +++ b/tests/pjsua/scripts-media-playrec/100_resample_lf_8_11.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-media-playrec/100_resample_lf_8_16.py b/tests/pjsua/scripts-media-playrec/100_resample_lf_8_16.py index b9361757b5..00d7459d6f 100644 --- a/tests/pjsua/scripts-media-playrec/100_resample_lf_8_16.py +++ b/tests/pjsua/scripts-media-playrec/100_resample_lf_8_16.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-media-playrec/100_resample_lf_8_22.py b/tests/pjsua/scripts-media-playrec/100_resample_lf_8_22.py index 268c6a5b3a..4fe22152e5 100644 --- a/tests/pjsua/scripts-media-playrec/100_resample_lf_8_22.py +++ b/tests/pjsua/scripts-media-playrec/100_resample_lf_8_22.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-media-playrec/100_resample_lf_8_32.py b/tests/pjsua/scripts-media-playrec/100_resample_lf_8_32.py index 05f3a30a44..9fe7e5eb78 100644 --- a/tests/pjsua/scripts-media-playrec/100_resample_lf_8_32.py +++ b/tests/pjsua/scripts-media-playrec/100_resample_lf_8_32.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-media-playrec/100_resample_lf_8_44.py b/tests/pjsua/scripts-media-playrec/100_resample_lf_8_44.py index 73e4b10925..76e5068397 100644 --- a/tests/pjsua/scripts-media-playrec/100_resample_lf_8_44.py +++ b/tests/pjsua/scripts-media-playrec/100_resample_lf_8_44.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-media-playrec/100_resample_lf_8_48.py b/tests/pjsua/scripts-media-playrec/100_resample_lf_8_48.py index 4d72603fad..09f3852db8 100644 --- a/tests/pjsua/scripts-media-playrec/100_resample_lf_8_48.py +++ b/tests/pjsua/scripts-media-playrec/100_resample_lf_8_48.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/100_defaults.py b/tests/pjsua/scripts-pesq/100_defaults.py index 188b17bb11..1661a5cc96 100644 --- a/tests/pjsua/scripts-pesq/100_defaults.py +++ b/tests/pjsua/scripts-pesq/100_defaults.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/101_defaults.py b/tests/pjsua/scripts-pesq/101_defaults.py index 67b53e3fcf..3882ecc1a7 100644 --- a/tests/pjsua/scripts-pesq/101_defaults.py +++ b/tests/pjsua/scripts-pesq/101_defaults.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/200_codec_g711a.py b/tests/pjsua/scripts-pesq/200_codec_g711a.py index 9e91c96334..982efec24a 100644 --- a/tests/pjsua/scripts-pesq/200_codec_g711a.py +++ b/tests/pjsua/scripts-pesq/200_codec_g711a.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/200_codec_g711u.py b/tests/pjsua/scripts-pesq/200_codec_g711u.py index fa64e7a636..212b8a23a9 100644 --- a/tests/pjsua/scripts-pesq/200_codec_g711u.py +++ b/tests/pjsua/scripts-pesq/200_codec_g711u.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/200_codec_g722.py b/tests/pjsua/scripts-pesq/200_codec_g722.py index 4cb85dad7a..8e8920f35c 100644 --- a/tests/pjsua/scripts-pesq/200_codec_g722.py +++ b/tests/pjsua/scripts-pesq/200_codec_g722.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/200_codec_gsm.py b/tests/pjsua/scripts-pesq/200_codec_gsm.py index 221372ef97..7dd1770533 100644 --- a/tests/pjsua/scripts-pesq/200_codec_gsm.py +++ b/tests/pjsua/scripts-pesq/200_codec_gsm.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/200_codec_ilbc.py b/tests/pjsua/scripts-pesq/200_codec_ilbc.py index 45480b85bb..818bddffd5 100644 --- a/tests/pjsua/scripts-pesq/200_codec_ilbc.py +++ b/tests/pjsua/scripts-pesq/200_codec_ilbc.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/200_codec_l16_16000.py b/tests/pjsua/scripts-pesq/200_codec_l16_16000.py index 691a362af8..6af721d97b 100644 --- a/tests/pjsua/scripts-pesq/200_codec_l16_16000.py +++ b/tests/pjsua/scripts-pesq/200_codec_l16_16000.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/200_codec_l16_16000_stereo.py b/tests/pjsua/scripts-pesq/200_codec_l16_16000_stereo.py index 406a18261b..93f1134e41 100644 --- a/tests/pjsua/scripts-pesq/200_codec_l16_16000_stereo.py +++ b/tests/pjsua/scripts-pesq/200_codec_l16_16000_stereo.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/200_codec_l16_8000.py b/tests/pjsua/scripts-pesq/200_codec_l16_8000.py index df05a9dad0..88cafb45a4 100644 --- a/tests/pjsua/scripts-pesq/200_codec_l16_8000.py +++ b/tests/pjsua/scripts-pesq/200_codec_l16_8000.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/200_codec_l16_8000_stereo.py b/tests/pjsua/scripts-pesq/200_codec_l16_8000_stereo.py index b114a1ab59..28418977a1 100644 --- a/tests/pjsua/scripts-pesq/200_codec_l16_8000_stereo.py +++ b/tests/pjsua/scripts-pesq/200_codec_l16_8000_stereo.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/200_codec_speex_16000.py b/tests/pjsua/scripts-pesq/200_codec_speex_16000.py index f4c5dac768..026aab113d 100644 --- a/tests/pjsua/scripts-pesq/200_codec_speex_16000.py +++ b/tests/pjsua/scripts-pesq/200_codec_speex_16000.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/200_codec_speex_8000.py b/tests/pjsua/scripts-pesq/200_codec_speex_8000.py index 5cd1fb5b3a..92ba7fefd1 100644 --- a/tests/pjsua/scripts-pesq/200_codec_speex_8000.py +++ b/tests/pjsua/scripts-pesq/200_codec_speex_8000.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/201_codec_g711a.py b/tests/pjsua/scripts-pesq/201_codec_g711a.py index b7458c3c9f..7c30f8a51e 100644 --- a/tests/pjsua/scripts-pesq/201_codec_g711a.py +++ b/tests/pjsua/scripts-pesq/201_codec_g711a.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/201_codec_g711u.py b/tests/pjsua/scripts-pesq/201_codec_g711u.py index 43cff65183..66f496256b 100644 --- a/tests/pjsua/scripts-pesq/201_codec_g711u.py +++ b/tests/pjsua/scripts-pesq/201_codec_g711u.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/201_codec_g722.py b/tests/pjsua/scripts-pesq/201_codec_g722.py index 24c89293d1..49164958db 100644 --- a/tests/pjsua/scripts-pesq/201_codec_g722.py +++ b/tests/pjsua/scripts-pesq/201_codec_g722.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/201_codec_gsm.py b/tests/pjsua/scripts-pesq/201_codec_gsm.py index d250b77040..38eed6526d 100644 --- a/tests/pjsua/scripts-pesq/201_codec_gsm.py +++ b/tests/pjsua/scripts-pesq/201_codec_gsm.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/201_codec_ilbc.py b/tests/pjsua/scripts-pesq/201_codec_ilbc.py index e6d4d35fc5..79b67f706d 100644 --- a/tests/pjsua/scripts-pesq/201_codec_ilbc.py +++ b/tests/pjsua/scripts-pesq/201_codec_ilbc.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/201_codec_l16_16000.py b/tests/pjsua/scripts-pesq/201_codec_l16_16000.py index a71004cfd4..4b479d0f90 100644 --- a/tests/pjsua/scripts-pesq/201_codec_l16_16000.py +++ b/tests/pjsua/scripts-pesq/201_codec_l16_16000.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/201_codec_l16_16000_stereo.py b/tests/pjsua/scripts-pesq/201_codec_l16_16000_stereo.py index c20bc5fcf7..60d8698507 100644 --- a/tests/pjsua/scripts-pesq/201_codec_l16_16000_stereo.py +++ b/tests/pjsua/scripts-pesq/201_codec_l16_16000_stereo.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/201_codec_l16_8000.py b/tests/pjsua/scripts-pesq/201_codec_l16_8000.py index d404f2d7f9..4b3f9bcb5c 100644 --- a/tests/pjsua/scripts-pesq/201_codec_l16_8000.py +++ b/tests/pjsua/scripts-pesq/201_codec_l16_8000.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/201_codec_l16_8000_stereo.py b/tests/pjsua/scripts-pesq/201_codec_l16_8000_stereo.py index a40cd7e849..b3738d4735 100644 --- a/tests/pjsua/scripts-pesq/201_codec_l16_8000_stereo.py +++ b/tests/pjsua/scripts-pesq/201_codec_l16_8000_stereo.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/201_codec_speex_16000.py b/tests/pjsua/scripts-pesq/201_codec_speex_16000.py index 252e4efe83..fd85bc2f05 100644 --- a/tests/pjsua/scripts-pesq/201_codec_speex_16000.py +++ b/tests/pjsua/scripts-pesq/201_codec_speex_16000.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pesq/201_codec_speex_8000.py b/tests/pjsua/scripts-pesq/201_codec_speex_8000.py index 8f04dbc9b9..3c2ba1e308 100644 --- a/tests/pjsua/scripts-pesq/201_codec_speex_8000.py +++ b/tests/pjsua/scripts-pesq/201_codec_speex_8000.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pres/100_peertopeer.py b/tests/pjsua/scripts-pres/100_peertopeer.py index 84e6c7a731..57ca30057e 100644 --- a/tests/pjsua/scripts-pres/100_peertopeer.py +++ b/tests/pjsua/scripts-pres/100_peertopeer.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-pres/200_publish.py b/tests/pjsua/scripts-pres/200_publish.py index 50308a583e..6d241955d9 100644 --- a/tests/pjsua/scripts-pres/200_publish.py +++ b/tests/pjsua/scripts-pres/200_publish.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-recvfrom/100_simple.py b/tests/pjsua/scripts-recvfrom/100_simple.py index e92369d8fb..83ed7b4498 100644 --- a/tests/pjsua/scripts-recvfrom/100_simple.py +++ b/tests/pjsua/scripts-recvfrom/100_simple.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/200_reg_good_enocredentiall.py b/tests/pjsua/scripts-recvfrom/200_reg_good_enocredentiall.py index 33d12b1a12..f4e2ed1f77 100644 --- a/tests/pjsua/scripts-recvfrom/200_reg_good_enocredentiall.py +++ b/tests/pjsua/scripts-recvfrom/200_reg_good_enocredentiall.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/201_reg_good_ok.py b/tests/pjsua/scripts-recvfrom/201_reg_good_ok.py index 9b5a9f962d..bf2a297ed3 100644 --- a/tests/pjsua/scripts-recvfrom/201_reg_good_ok.py +++ b/tests/pjsua/scripts-recvfrom/201_reg_good_ok.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/202_reg_good_ok_wildcard.py b/tests/pjsua/scripts-recvfrom/202_reg_good_ok_wildcard.py index 66ed19ed23..31facd7bba 100644 --- a/tests/pjsua/scripts-recvfrom/202_reg_good_ok_wildcard.py +++ b/tests/pjsua/scripts-recvfrom/202_reg_good_ok_wildcard.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/203_reg_good_empty_realm.py b/tests/pjsua/scripts-recvfrom/203_reg_good_empty_realm.py index edfd40f393..a0d336fe56 100644 --- a/tests/pjsua/scripts-recvfrom/203_reg_good_empty_realm.py +++ b/tests/pjsua/scripts-recvfrom/203_reg_good_empty_realm.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/205_reg_good_no_realm.py b/tests/pjsua/scripts-recvfrom/205_reg_good_no_realm.py index 199493ec00..44884bf3cc 100644 --- a/tests/pjsua/scripts-recvfrom/205_reg_good_no_realm.py +++ b/tests/pjsua/scripts-recvfrom/205_reg_good_no_realm.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/206_reg_good_efailedcredential.py b/tests/pjsua/scripts-recvfrom/206_reg_good_efailedcredential.py index dc4a4db2f0..a2a011ce77 100644 --- a/tests/pjsua/scripts-recvfrom/206_reg_good_efailedcredential.py +++ b/tests/pjsua/scripts-recvfrom/206_reg_good_efailedcredential.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/208_reg_good_retry_nonce_ok.py b/tests/pjsua/scripts-recvfrom/208_reg_good_retry_nonce_ok.py index 46e172854f..34363d65d1 100644 --- a/tests/pjsua/scripts-recvfrom/208_reg_good_retry_nonce_ok.py +++ b/tests/pjsua/scripts-recvfrom/208_reg_good_retry_nonce_ok.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/209a_reg_handle_423_ok.py b/tests/pjsua/scripts-recvfrom/209a_reg_handle_423_ok.py index 16ec214cc4..a45f1816b6 100644 --- a/tests/pjsua/scripts-recvfrom/209a_reg_handle_423_ok.py +++ b/tests/pjsua/scripts-recvfrom/209a_reg_handle_423_ok.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/209b_reg_handle_423_bad_min_expires1.py b/tests/pjsua/scripts-recvfrom/209b_reg_handle_423_bad_min_expires1.py index 83a4074c53..21112187ae 100644 --- a/tests/pjsua/scripts-recvfrom/209b_reg_handle_423_bad_min_expires1.py +++ b/tests/pjsua/scripts-recvfrom/209b_reg_handle_423_bad_min_expires1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/209c_reg_handle_423_bad_min_expires2.py b/tests/pjsua/scripts-recvfrom/209c_reg_handle_423_bad_min_expires2.py index 378ea28325..13d7c54740 100644 --- a/tests/pjsua/scripts-recvfrom/209c_reg_handle_423_bad_min_expires2.py +++ b/tests/pjsua/scripts-recvfrom/209c_reg_handle_423_bad_min_expires2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/215_reg_good_multi_ok.py b/tests/pjsua/scripts-recvfrom/215_reg_good_multi_ok.py index 909ba229b8..107c5dea08 100644 --- a/tests/pjsua/scripts-recvfrom/215_reg_good_multi_ok.py +++ b/tests/pjsua/scripts-recvfrom/215_reg_good_multi_ok.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/220_reg_good_ims_ok.py b/tests/pjsua/scripts-recvfrom/220_reg_good_ims_ok.py index d37add173a..f1ebadba11 100644 --- a/tests/pjsua/scripts-recvfrom/220_reg_good_ims_ok.py +++ b/tests/pjsua/scripts-recvfrom/220_reg_good_ims_ok.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/230_reg_bad_fail_stale_true.py b/tests/pjsua/scripts-recvfrom/230_reg_bad_fail_stale_true.py index 4bceaf4573..ec397dd8eb 100644 --- a/tests/pjsua/scripts-recvfrom/230_reg_bad_fail_stale_true.py +++ b/tests/pjsua/scripts-recvfrom/230_reg_bad_fail_stale_true.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/231_reg_bad_fail_stale_false_nonce_changed.py b/tests/pjsua/scripts-recvfrom/231_reg_bad_fail_stale_false_nonce_changed.py index 443b91ba91..cdc4c8aea8 100644 --- a/tests/pjsua/scripts-recvfrom/231_reg_bad_fail_stale_false_nonce_changed.py +++ b/tests/pjsua/scripts-recvfrom/231_reg_bad_fail_stale_false_nonce_changed.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/234_reg_bad_stale_ok.py b/tests/pjsua/scripts-recvfrom/234_reg_bad_stale_ok.py index cfa9403ba3..87ee00fe1b 100644 --- a/tests/pjsua/scripts-recvfrom/234_reg_bad_stale_ok.py +++ b/tests/pjsua/scripts-recvfrom/234_reg_bad_stale_ok.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/235_reg_good_tel_uri_enocredential.py b/tests/pjsua/scripts-recvfrom/235_reg_good_tel_uri_enocredential.py index 3725bf728e..3837a7959b 100644 --- a/tests/pjsua/scripts-recvfrom/235_reg_good_tel_uri_enocredential.py +++ b/tests/pjsua/scripts-recvfrom/235_reg_good_tel_uri_enocredential.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/240_publish_scenarios.py b/tests/pjsua/scripts-recvfrom/240_publish_scenarios.py index 02adac920c..e3021aedbd 100644 --- a/tests/pjsua/scripts-recvfrom/240_publish_scenarios.py +++ b/tests/pjsua/scripts-recvfrom/240_publish_scenarios.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/300_timer_good.py b/tests/pjsua/scripts-recvfrom/300_timer_good.py index 00f11ab9a9..d7a16af581 100644 --- a/tests/pjsua/scripts-recvfrom/300_timer_good.py +++ b/tests/pjsua/scripts-recvfrom/300_timer_good.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/301_timer_good_retry_after_422.py b/tests/pjsua/scripts-recvfrom/301_timer_good_retry_after_422.py index 674e707ea1..1ddc31e98e 100644 --- a/tests/pjsua/scripts-recvfrom/301_timer_good_retry_after_422.py +++ b/tests/pjsua/scripts-recvfrom/301_timer_good_retry_after_422.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-recvfrom/400_inv_answered_with_less_media.py b/tests/pjsua/scripts-recvfrom/400_inv_answered_with_less_media.py index 1f0471f535..f7b14cf259 100644 --- a/tests/pjsua/scripts-recvfrom/400_inv_answered_with_less_media.py +++ b/tests/pjsua/scripts-recvfrom/400_inv_answered_with_less_media.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-run/100_simple.py b/tests/pjsua/scripts-run/100_simple.py index 7ab96efc38..4d3457f20d 100644 --- a/tests/pjsua/scripts-run/100_simple.py +++ b/tests/pjsua/scripts-run/100_simple.py @@ -1,4 +1,3 @@ -# $Id$ # # Just about the simple pjsua command line parameter, which should # never fail in any circumstances diff --git a/tests/pjsua/scripts-run/200_register.py b/tests/pjsua/scripts-run/200_register.py index 3f4338d1ae..7bba650509 100644 --- a/tests/pjsua/scripts-run/200_register.py +++ b/tests/pjsua/scripts-run/200_register.py @@ -1,4 +1,3 @@ -# $Id$ # from inc_cfg import * diff --git a/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_1.py b/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_1.py index 35f803c7f1..71c411595f 100644 --- a/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_1.py +++ b/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_2.py b/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_2.py index 88fd249bfc..886c991dfa 100644 --- a/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_2.py +++ b/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_3.py b/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_3.py index 4f32e979ca..1d3f3ce630 100644 --- a/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_3.py +++ b/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_3.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_4.py b/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_4.py index 9a24ddfd0e..4d78d70271 100644 --- a/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_4.py +++ b/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_4.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_5.py b/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_5.py index 2b449d1124..e8119a2dfa 100644 --- a/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_5.py +++ b/tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_5.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/100_simplecall.py b/tests/pjsua/scripts-sendto/100_simplecall.py index 3fc52dff75..7ad28da230 100644 --- a/tests/pjsua/scripts-sendto/100_simplecall.py +++ b/tests/pjsua/scripts-sendto/100_simplecall.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/110_tel_uri.py b/tests/pjsua/scripts-sendto/110_tel_uri.py index 1d5e645c7a..ecbfc049e2 100644 --- a/tests/pjsua/scripts-sendto/110_tel_uri.py +++ b/tests/pjsua/scripts-sendto/110_tel_uri.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/120_sdp_with_video_dynamic_1.py b/tests/pjsua/scripts-sendto/120_sdp_with_video_dynamic_1.py index e96919f3fe..3c99a7c97f 100644 --- a/tests/pjsua/scripts-sendto/120_sdp_with_video_dynamic_1.py +++ b/tests/pjsua/scripts-sendto/120_sdp_with_video_dynamic_1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/120_sdp_with_video_dynamic_2.py b/tests/pjsua/scripts-sendto/120_sdp_with_video_dynamic_2.py index 6bdda923ba..f2ca5d3d31 100644 --- a/tests/pjsua/scripts-sendto/120_sdp_with_video_dynamic_2.py +++ b/tests/pjsua/scripts-sendto/120_sdp_with_video_dynamic_2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/121_sdp_with_video_static_1.py b/tests/pjsua/scripts-sendto/121_sdp_with_video_static_1.py index f05da5dbac..791ae6b11e 100644 --- a/tests/pjsua/scripts-sendto/121_sdp_with_video_static_1.py +++ b/tests/pjsua/scripts-sendto/121_sdp_with_video_static_1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/121_sdp_with_video_static_2.py b/tests/pjsua/scripts-sendto/121_sdp_with_video_static_2.py index 67e0132147..751dbbb7a0 100644 --- a/tests/pjsua/scripts-sendto/121_sdp_with_video_static_2.py +++ b/tests/pjsua/scripts-sendto/121_sdp_with_video_static_2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/122_sdp_with_unknown_dynamic_1.py b/tests/pjsua/scripts-sendto/122_sdp_with_unknown_dynamic_1.py index 0e7ced7586..f3b2f13894 100644 --- a/tests/pjsua/scripts-sendto/122_sdp_with_unknown_dynamic_1.py +++ b/tests/pjsua/scripts-sendto/122_sdp_with_unknown_dynamic_1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/122_sdp_with_unknown_dynamic_2.py b/tests/pjsua/scripts-sendto/122_sdp_with_unknown_dynamic_2.py index 7bdb14eed7..876ea1525f 100644 --- a/tests/pjsua/scripts-sendto/122_sdp_with_unknown_dynamic_2.py +++ b/tests/pjsua/scripts-sendto/122_sdp_with_unknown_dynamic_2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/123_sdp_with_unknown_static_1.py b/tests/pjsua/scripts-sendto/123_sdp_with_unknown_static_1.py index 3da14409f2..c86a5f03ab 100644 --- a/tests/pjsua/scripts-sendto/123_sdp_with_unknown_static_1.py +++ b/tests/pjsua/scripts-sendto/123_sdp_with_unknown_static_1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/123_sdp_with_unknown_static_2.py b/tests/pjsua/scripts-sendto/123_sdp_with_unknown_static_2.py index 76ff13beae..e2397c13d2 100644 --- a/tests/pjsua/scripts-sendto/123_sdp_with_unknown_static_2.py +++ b/tests/pjsua/scripts-sendto/123_sdp_with_unknown_static_2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/124_sdp_with_unknown_static_unknown_transport.py b/tests/pjsua/scripts-sendto/124_sdp_with_unknown_static_unknown_transport.py index 5d1b7d3fac..71fcbc4c68 100644 --- a/tests/pjsua/scripts-sendto/124_sdp_with_unknown_static_unknown_transport.py +++ b/tests/pjsua/scripts-sendto/124_sdp_with_unknown_static_unknown_transport.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_0.py b/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_0.py index c194ba94b1..bf442b5de6 100644 --- a/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_0.py +++ b/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_0.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_1.py b/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_1.py index 3cfc6116a3..7e21b70e02 100644 --- a/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_1.py +++ b/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_2.py b/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_2.py index 80cbf4b538..a6447d7e26 100644 --- a/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_2.py +++ b/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_3.py b/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_3.py index a0397c5918..1f972372ba 100644 --- a/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_3.py +++ b/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_3.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_4.py b/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_4.py index 814de0d935..44d842c124 100644 --- a/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_4.py +++ b/tests/pjsua/scripts-sendto/125_sdp_with_multi_audio_4.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/126_sdp_with_port_0_and_no_rtpmap_for_dynamic_pt.py b/tests/pjsua/scripts-sendto/126_sdp_with_port_0_and_no_rtpmap_for_dynamic_pt.py index 41a64b693e..cfe055fee2 100644 --- a/tests/pjsua/scripts-sendto/126_sdp_with_port_0_and_no_rtpmap_for_dynamic_pt.py +++ b/tests/pjsua/scripts-sendto/126_sdp_with_port_0_and_no_rtpmap_for_dynamic_pt.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/140_sdp_with_direction_attr_in_session_1.py b/tests/pjsua/scripts-sendto/140_sdp_with_direction_attr_in_session_1.py index 16073eda94..d9c8468ee8 100644 --- a/tests/pjsua/scripts-sendto/140_sdp_with_direction_attr_in_session_1.py +++ b/tests/pjsua/scripts-sendto/140_sdp_with_direction_attr_in_session_1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/140_sdp_with_direction_attr_in_session_2.py b/tests/pjsua/scripts-sendto/140_sdp_with_direction_attr_in_session_2.py index a8b1d10c05..7fffe8196f 100644 --- a/tests/pjsua/scripts-sendto/140_sdp_with_direction_attr_in_session_2.py +++ b/tests/pjsua/scripts-sendto/140_sdp_with_direction_attr_in_session_2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/150_err_extension.py b/tests/pjsua/scripts-sendto/150_err_extension.py index cb46d1f410..2be4612956 100644 --- a/tests/pjsua/scripts-sendto/150_err_extension.py +++ b/tests/pjsua/scripts-sendto/150_err_extension.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/151_err_sdp_video.py b/tests/pjsua/scripts-sendto/151_err_sdp_video.py index 1dc8422b72..bba2811331 100644 --- a/tests/pjsua/scripts-sendto/151_err_sdp_video.py +++ b/tests/pjsua/scripts-sendto/151_err_sdp_video.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/152_err_sdp_no_media.py b/tests/pjsua/scripts-sendto/152_err_sdp_no_media.py index 4e7465a267..886b78412a 100644 --- a/tests/pjsua/scripts-sendto/152_err_sdp_no_media.py +++ b/tests/pjsua/scripts-sendto/152_err_sdp_no_media.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/153_err_sdp_unsupported_codec.py b/tests/pjsua/scripts-sendto/153_err_sdp_unsupported_codec.py index 1d6da2a844..e919145f3f 100644 --- a/tests/pjsua/scripts-sendto/153_err_sdp_unsupported_codec.py +++ b/tests/pjsua/scripts-sendto/153_err_sdp_unsupported_codec.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/155_err_sdp_bad_syntax.py b/tests/pjsua/scripts-sendto/155_err_sdp_bad_syntax.py index d32ef3d6d7..d204ff019d 100644 --- a/tests/pjsua/scripts-sendto/155_err_sdp_bad_syntax.py +++ b/tests/pjsua/scripts-sendto/155_err_sdp_bad_syntax.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/156_err_sdp_bad_net_type.py b/tests/pjsua/scripts-sendto/156_err_sdp_bad_net_type.py index 7c1536b78a..1726d28a5e 100644 --- a/tests/pjsua/scripts-sendto/156_err_sdp_bad_net_type.py +++ b/tests/pjsua/scripts-sendto/156_err_sdp_bad_net_type.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/157_err_sdp_bad_addr_type.py b/tests/pjsua/scripts-sendto/157_err_sdp_bad_addr_type.py index cac5c9887c..019a17e1c2 100644 --- a/tests/pjsua/scripts-sendto/157_err_sdp_bad_addr_type.py +++ b/tests/pjsua/scripts-sendto/157_err_sdp_bad_addr_type.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/158_err_sdp_bad_transport_type.py b/tests/pjsua/scripts-sendto/158_err_sdp_bad_transport_type.py index 63dd811a76..cc1d14d635 100644 --- a/tests/pjsua/scripts-sendto/158_err_sdp_bad_transport_type.py +++ b/tests/pjsua/scripts-sendto/158_err_sdp_bad_transport_type.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/159_no_rport.py b/tests/pjsua/scripts-sendto/159_no_rport.py index 6e9d45437b..1320338c72 100644 --- a/tests/pjsua/scripts-sendto/159_no_rport.py +++ b/tests/pjsua/scripts-sendto/159_no_rport.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/159_no_rport_nit.py b/tests/pjsua/scripts-sendto/159_no_rport_nit.py index 20477a1f0d..5322298cbe 100644 --- a/tests/pjsua/scripts-sendto/159_no_rport_nit.py +++ b/tests/pjsua/scripts-sendto/159_no_rport_nit.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/160_err_duplicate_replaces.py b/tests/pjsua/scripts-sendto/160_err_duplicate_replaces.py index ec4b0fdfe7..408f0f9e04 100644 --- a/tests/pjsua/scripts-sendto/160_err_duplicate_replaces.py +++ b/tests/pjsua/scripts-sendto/160_err_duplicate_replaces.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/161_err_replaces_dlg_not_found.py b/tests/pjsua/scripts-sendto/161_err_replaces_dlg_not_found.py index 863a1a572d..bc481a6091 100644 --- a/tests/pjsua/scripts-sendto/161_err_replaces_dlg_not_found.py +++ b/tests/pjsua/scripts-sendto/161_err_replaces_dlg_not_found.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/170_timer_required.py b/tests/pjsua/scripts-sendto/170_timer_required.py index 8f6749dbb1..b7078f0854 100644 --- a/tests/pjsua/scripts-sendto/170_timer_required.py +++ b/tests/pjsua/scripts-sendto/170_timer_required.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/171_timer_initiated_by_uas.py b/tests/pjsua/scripts-sendto/171_timer_initiated_by_uas.py index 4dd73e0f68..5c5862cea4 100644 --- a/tests/pjsua/scripts-sendto/171_timer_initiated_by_uas.py +++ b/tests/pjsua/scripts-sendto/171_timer_initiated_by_uas.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/172_timer_supported_but_not_used.py b/tests/pjsua/scripts-sendto/172_timer_supported_but_not_used.py index 69b0c900d6..b8aae282d3 100644 --- a/tests/pjsua/scripts-sendto/172_timer_supported_but_not_used.py +++ b/tests/pjsua/scripts-sendto/172_timer_supported_but_not_used.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/173_timer_offer_no_refresher.py b/tests/pjsua/scripts-sendto/173_timer_offer_no_refresher.py index a0005d3ebf..61c9953dec 100644 --- a/tests/pjsua/scripts-sendto/173_timer_offer_no_refresher.py +++ b/tests/pjsua/scripts-sendto/173_timer_offer_no_refresher.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/173_timer_offer_refresher_uac.py b/tests/pjsua/scripts-sendto/173_timer_offer_refresher_uac.py index 13c2449833..25fd8b4d43 100644 --- a/tests/pjsua/scripts-sendto/173_timer_offer_refresher_uac.py +++ b/tests/pjsua/scripts-sendto/173_timer_offer_refresher_uac.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/173_timer_offer_refresher_uas.py b/tests/pjsua/scripts-sendto/173_timer_offer_refresher_uas.py index 2c270e1f03..5e75460139 100644 --- a/tests/pjsua/scripts-sendto/173_timer_offer_refresher_uas.py +++ b/tests/pjsua/scripts-sendto/173_timer_offer_refresher_uas.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/174_timer_se_too_small.py b/tests/pjsua/scripts-sendto/174_timer_se_too_small.py index c607de6cca..eee4870020 100644 --- a/tests/pjsua/scripts-sendto/174_timer_se_too_small.py +++ b/tests/pjsua/scripts-sendto/174_timer_se_too_small.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/200_ice_no_ice.py b/tests/pjsua/scripts-sendto/200_ice_no_ice.py index 07a08f2aca..636c28da95 100644 --- a/tests/pjsua/scripts-sendto/200_ice_no_ice.py +++ b/tests/pjsua/scripts-sendto/200_ice_no_ice.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/200_ice_success_1.py b/tests/pjsua/scripts-sendto/200_ice_success_1.py index a2ff50d45e..730941538d 100644 --- a/tests/pjsua/scripts-sendto/200_ice_success_1.py +++ b/tests/pjsua/scripts-sendto/200_ice_success_1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/200_ice_success_2.py b/tests/pjsua/scripts-sendto/200_ice_success_2.py index 324fca0eea..c86b516bf2 100644 --- a/tests/pjsua/scripts-sendto/200_ice_success_2.py +++ b/tests/pjsua/scripts-sendto/200_ice_success_2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/200_ice_success_3.py b/tests/pjsua/scripts-sendto/200_ice_success_3.py index 307e6afe15..1a3f980f3e 100644 --- a/tests/pjsua/scripts-sendto/200_ice_success_3.py +++ b/tests/pjsua/scripts-sendto/200_ice_success_3.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/200_ice_success_4.py b/tests/pjsua/scripts-sendto/200_ice_success_4.py index ede6a4303a..10f1351cb1 100644 --- a/tests/pjsua/scripts-sendto/200_ice_success_4.py +++ b/tests/pjsua/scripts-sendto/200_ice_success_4.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/201_ice_mismatch_1.py b/tests/pjsua/scripts-sendto/201_ice_mismatch_1.py index 11b093361c..21ebfc0396 100644 --- a/tests/pjsua/scripts-sendto/201_ice_mismatch_1.py +++ b/tests/pjsua/scripts-sendto/201_ice_mismatch_1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/201_ice_mismatch_2.py b/tests/pjsua/scripts-sendto/201_ice_mismatch_2.py index 7371092292..5cfe1022e2 100644 --- a/tests/pjsua/scripts-sendto/201_ice_mismatch_2.py +++ b/tests/pjsua/scripts-sendto/201_ice_mismatch_2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/201_ice_mismatch_3.py b/tests/pjsua/scripts-sendto/201_ice_mismatch_3.py index 7706a15993..adb4c3cc0d 100644 --- a/tests/pjsua/scripts-sendto/201_ice_mismatch_3.py +++ b/tests/pjsua/scripts-sendto/201_ice_mismatch_3.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/251_multipart_ok_simple.py b/tests/pjsua/scripts-sendto/251_multipart_ok_simple.py index 4216319964..62b7a137e9 100644 --- a/tests/pjsua/scripts-sendto/251_multipart_ok_simple.py +++ b/tests/pjsua/scripts-sendto/251_multipart_ok_simple.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/252_multipart_ok_clutter.py b/tests/pjsua/scripts-sendto/252_multipart_ok_clutter.py index 6503848870..79bf7c7344 100644 --- a/tests/pjsua/scripts-sendto/252_multipart_ok_clutter.py +++ b/tests/pjsua/scripts-sendto/252_multipart_ok_clutter.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/260_multipart_err_no_sdp.py b/tests/pjsua/scripts-sendto/260_multipart_err_no_sdp.py index 776e5ab746..dfab692667 100644 --- a/tests/pjsua/scripts-sendto/260_multipart_err_no_sdp.py +++ b/tests/pjsua/scripts-sendto/260_multipart_err_no_sdp.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/300_srtp_crypto_case_insensitive.py b/tests/pjsua/scripts-sendto/300_srtp_crypto_case_insensitive.py index 2e3923e6f3..479417375f 100644 --- a/tests/pjsua/scripts-sendto/300_srtp_crypto_case_insensitive.py +++ b/tests/pjsua/scripts-sendto/300_srtp_crypto_case_insensitive.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/300_srtp_duplicated_crypto_tag.py b/tests/pjsua/scripts-sendto/300_srtp_duplicated_crypto_tag.py index d9228c821a..22ec4aff4e 100644 --- a/tests/pjsua/scripts-sendto/300_srtp_duplicated_crypto_tag.py +++ b/tests/pjsua/scripts-sendto/300_srtp_duplicated_crypto_tag.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/300_srtp_invalid_crypto_tag_non_numeric.py b/tests/pjsua/scripts-sendto/300_srtp_invalid_crypto_tag_non_numeric.py index e1b05355ae..cdeb59ed67 100644 --- a/tests/pjsua/scripts-sendto/300_srtp_invalid_crypto_tag_non_numeric.py +++ b/tests/pjsua/scripts-sendto/300_srtp_invalid_crypto_tag_non_numeric.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/300_srtp_receive_crypto_tag_zero.py b/tests/pjsua/scripts-sendto/300_srtp_receive_crypto_tag_zero.py index 7e4e5499ed..706387dc1a 100644 --- a/tests/pjsua/scripts-sendto/300_srtp_receive_crypto_tag_zero.py +++ b/tests/pjsua/scripts-sendto/300_srtp_receive_crypto_tag_zero.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/300_srtp_receive_no_key_1.py b/tests/pjsua/scripts-sendto/300_srtp_receive_no_key_1.py index 7cc91a7383..ef66cb760c 100644 --- a/tests/pjsua/scripts-sendto/300_srtp_receive_no_key_1.py +++ b/tests/pjsua/scripts-sendto/300_srtp_receive_no_key_1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/300_srtp_receive_no_key_2.py b/tests/pjsua/scripts-sendto/300_srtp_receive_no_key_2.py index 0e347004f4..b39ff12764 100644 --- a/tests/pjsua/scripts-sendto/300_srtp_receive_no_key_2.py +++ b/tests/pjsua/scripts-sendto/300_srtp_receive_no_key_2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/300_srtp_receive_no_key_3.py b/tests/pjsua/scripts-sendto/300_srtp_receive_no_key_3.py index 2849f713d5..6785228891 100644 --- a/tests/pjsua/scripts-sendto/300_srtp_receive_no_key_3.py +++ b/tests/pjsua/scripts-sendto/300_srtp_receive_no_key_3.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/301_srtp0_recv_avp.py b/tests/pjsua/scripts-sendto/301_srtp0_recv_avp.py index 2ef19f335b..e0bb536d56 100644 --- a/tests/pjsua/scripts-sendto/301_srtp0_recv_avp.py +++ b/tests/pjsua/scripts-sendto/301_srtp0_recv_avp.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/301_srtp0_recv_savp.py b/tests/pjsua/scripts-sendto/301_srtp0_recv_savp.py index b86ba527db..f1a00e8591 100644 --- a/tests/pjsua/scripts-sendto/301_srtp0_recv_savp.py +++ b/tests/pjsua/scripts-sendto/301_srtp0_recv_savp.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/310_srtp1_no_crypto.py b/tests/pjsua/scripts-sendto/310_srtp1_no_crypto.py index 5bfb92e574..7547f7f0f1 100644 --- a/tests/pjsua/scripts-sendto/310_srtp1_no_crypto.py +++ b/tests/pjsua/scripts-sendto/310_srtp1_no_crypto.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/311_srtp1_recv_avp.py b/tests/pjsua/scripts-sendto/311_srtp1_recv_avp.py index 8b173f263d..f3c4da7d09 100644 --- a/tests/pjsua/scripts-sendto/311_srtp1_recv_avp.py +++ b/tests/pjsua/scripts-sendto/311_srtp1_recv_avp.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/312_srtp1_recv_savp.py b/tests/pjsua/scripts-sendto/312_srtp1_recv_savp.py index a3b30218ac..c8b5980d57 100644 --- a/tests/pjsua/scripts-sendto/312_srtp1_recv_savp.py +++ b/tests/pjsua/scripts-sendto/312_srtp1_recv_savp.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/313_srtp1_unsupported_crypto.py b/tests/pjsua/scripts-sendto/313_srtp1_unsupported_crypto.py index 7b45755565..e9000679fd 100644 --- a/tests/pjsua/scripts-sendto/313_srtp1_unsupported_crypto.py +++ b/tests/pjsua/scripts-sendto/313_srtp1_unsupported_crypto.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/320_srtp2_no_crypto.py b/tests/pjsua/scripts-sendto/320_srtp2_no_crypto.py index 6613b74127..89cc35feb6 100644 --- a/tests/pjsua/scripts-sendto/320_srtp2_no_crypto.py +++ b/tests/pjsua/scripts-sendto/320_srtp2_no_crypto.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/320_srtp_with_unknown_media_1.py b/tests/pjsua/scripts-sendto/320_srtp_with_unknown_media_1.py index 4ee7bfea5f..04dc8cce24 100644 --- a/tests/pjsua/scripts-sendto/320_srtp_with_unknown_media_1.py +++ b/tests/pjsua/scripts-sendto/320_srtp_with_unknown_media_1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/320_srtp_with_unknown_media_2.py b/tests/pjsua/scripts-sendto/320_srtp_with_unknown_media_2.py index 8536f1a220..609db293d1 100644 --- a/tests/pjsua/scripts-sendto/320_srtp_with_unknown_media_2.py +++ b/tests/pjsua/scripts-sendto/320_srtp_with_unknown_media_2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/320_srtp_with_unknown_transport_1.py b/tests/pjsua/scripts-sendto/320_srtp_with_unknown_transport_1.py index 12aa61cb53..49a2736354 100644 --- a/tests/pjsua/scripts-sendto/320_srtp_with_unknown_transport_1.py +++ b/tests/pjsua/scripts-sendto/320_srtp_with_unknown_transport_1.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/320_srtp_with_unknown_transport_2.py b/tests/pjsua/scripts-sendto/320_srtp_with_unknown_transport_2.py index a1ac6ce07b..6d7ccfd937 100644 --- a/tests/pjsua/scripts-sendto/320_srtp_with_unknown_transport_2.py +++ b/tests/pjsua/scripts-sendto/320_srtp_with_unknown_transport_2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/321_srtp2_recv_avp.py b/tests/pjsua/scripts-sendto/321_srtp2_recv_avp.py index 56d03dc1a3..400d7f9e7c 100644 --- a/tests/pjsua/scripts-sendto/321_srtp2_recv_avp.py +++ b/tests/pjsua/scripts-sendto/321_srtp2_recv_avp.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/322_srtp2_recv_savp.py b/tests/pjsua/scripts-sendto/322_srtp2_recv_savp.py index 5d5d53de2b..e2329f4e0f 100644 --- a/tests/pjsua/scripts-sendto/322_srtp2_recv_savp.py +++ b/tests/pjsua/scripts-sendto/322_srtp2_recv_savp.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/323_srtp2_receive_too_long_key.py b/tests/pjsua/scripts-sendto/323_srtp2_receive_too_long_key.py index cf8bf487aa..873f49ea2b 100644 --- a/tests/pjsua/scripts-sendto/323_srtp2_receive_too_long_key.py +++ b/tests/pjsua/scripts-sendto/323_srtp2_receive_too_long_key.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/323_srtp2_unsupported_crypto.py b/tests/pjsua/scripts-sendto/323_srtp2_unsupported_crypto.py index 782beba92c..68008e92ea 100644 --- a/tests/pjsua/scripts-sendto/323_srtp2_unsupported_crypto.py +++ b/tests/pjsua/scripts-sendto/323_srtp2_unsupported_crypto.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/330_srtp_prefer_rtp_savp.py b/tests/pjsua/scripts-sendto/330_srtp_prefer_rtp_savp.py index 168b36cecb..f2ae765136 100644 --- a/tests/pjsua/scripts-sendto/330_srtp_prefer_rtp_savp.py +++ b/tests/pjsua/scripts-sendto/330_srtp_prefer_rtp_savp.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/331_srtp_prefer_rtp_avp.py b/tests/pjsua/scripts-sendto/331_srtp_prefer_rtp_avp.py index e42d20bdac..f70ed979dc 100644 --- a/tests/pjsua/scripts-sendto/331_srtp_prefer_rtp_avp.py +++ b/tests/pjsua/scripts-sendto/331_srtp_prefer_rtp_avp.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/360_non_sip_uri.py b/tests/pjsua/scripts-sendto/360_non_sip_uri.py index c4861aa386..73c5dcb827 100644 --- a/tests/pjsua/scripts-sendto/360_non_sip_uri.py +++ b/tests/pjsua/scripts-sendto/360_non_sip_uri.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/361_non_sip_uri.py b/tests/pjsua/scripts-sendto/361_non_sip_uri.py index d24685d5cf..575ff6c356 100644 --- a/tests/pjsua/scripts-sendto/361_non_sip_uri.py +++ b/tests/pjsua/scripts-sendto/361_non_sip_uri.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/362_non_sip_uri.py b/tests/pjsua/scripts-sendto/362_non_sip_uri.py index 0c4b002afb..032654a578 100644 --- a/tests/pjsua/scripts-sendto/362_non_sip_uri.py +++ b/tests/pjsua/scripts-sendto/362_non_sip_uri.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/363_non_sip_uri_subscribe.py b/tests/pjsua/scripts-sendto/363_non_sip_uri_subscribe.py index 5d3d42ded7..9e3db539d6 100644 --- a/tests/pjsua/scripts-sendto/363_non_sip_uri_subscribe.py +++ b/tests/pjsua/scripts-sendto/363_non_sip_uri_subscribe.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/364_non_sip_uri_subscribe.py b/tests/pjsua/scripts-sendto/364_non_sip_uri_subscribe.py index f9beb05e0f..7ff6770cc5 100644 --- a/tests/pjsua/scripts-sendto/364_non_sip_uri_subscribe.py +++ b/tests/pjsua/scripts-sendto/364_non_sip_uri_subscribe.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/400_fmtp_g7221_with_bitrate.py b/tests/pjsua/scripts-sendto/400_fmtp_g7221_with_bitrate.py index 1073741156..f670265290 100644 --- a/tests/pjsua/scripts-sendto/400_fmtp_g7221_with_bitrate.py +++ b/tests/pjsua/scripts-sendto/400_fmtp_g7221_with_bitrate.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/401_fmtp_g7221_with_bitrate_24000.py b/tests/pjsua/scripts-sendto/401_fmtp_g7221_with_bitrate_24000.py index 93976c072a..4cb6e81c3f 100644 --- a/tests/pjsua/scripts-sendto/401_fmtp_g7221_with_bitrate_24000.py +++ b/tests/pjsua/scripts-sendto/401_fmtp_g7221_with_bitrate_24000.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/401_fmtp_g7221_with_bitrate_32000.py b/tests/pjsua/scripts-sendto/401_fmtp_g7221_with_bitrate_32000.py index 38532d2ef1..dad0235c23 100644 --- a/tests/pjsua/scripts-sendto/401_fmtp_g7221_with_bitrate_32000.py +++ b/tests/pjsua/scripts-sendto/401_fmtp_g7221_with_bitrate_32000.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/410_fmtp_amrnb_offer_octet_align.py b/tests/pjsua/scripts-sendto/410_fmtp_amrnb_offer_octet_align.py index 61662b7960..8cc685e5a3 100644 --- a/tests/pjsua/scripts-sendto/410_fmtp_amrnb_offer_octet_align.py +++ b/tests/pjsua/scripts-sendto/410_fmtp_amrnb_offer_octet_align.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/411_fmtp_amrnb_offer_band_eff.py b/tests/pjsua/scripts-sendto/411_fmtp_amrnb_offer_band_eff.py index 6299f4ed0e..75a5739044 100644 --- a/tests/pjsua/scripts-sendto/411_fmtp_amrnb_offer_band_eff.py +++ b/tests/pjsua/scripts-sendto/411_fmtp_amrnb_offer_band_eff.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/412_fmtp_amrnb_offer_band_eff2.py b/tests/pjsua/scripts-sendto/412_fmtp_amrnb_offer_band_eff2.py index d35c805995..eaa3923ba2 100644 --- a/tests/pjsua/scripts-sendto/412_fmtp_amrnb_offer_band_eff2.py +++ b/tests/pjsua/scripts-sendto/412_fmtp_amrnb_offer_band_eff2.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/500_pres_subscribe_with_bad_event.py b/tests/pjsua/scripts-sendto/500_pres_subscribe_with_bad_event.py index 7fba4fda62..d906b47030 100644 --- a/tests/pjsua/scripts-sendto/500_pres_subscribe_with_bad_event.py +++ b/tests/pjsua/scripts-sendto/500_pres_subscribe_with_bad_event.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/999_asterisk_err.py b/tests/pjsua/scripts-sendto/999_asterisk_err.py index 580b46de41..a536999498 100644 --- a/tests/pjsua/scripts-sendto/999_asterisk_err.py +++ b/tests/pjsua/scripts-sendto/999_asterisk_err.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sendto/999_message_no_body.py b/tests/pjsua/scripts-sendto/999_message_no_body.py index c009601458..9931a0bd08 100644 --- a/tests/pjsua/scripts-sendto/999_message_no_body.py +++ b/tests/pjsua/scripts-sendto/999_message_no_body.py @@ -1,4 +1,3 @@ -# $Id$ import inc_sip as sip import inc_sdp as sdp diff --git a/tests/pjsua/scripts-sipp/strict-route.py b/tests/pjsua/scripts-sipp/strict-route.py index 3cf43dc7b6..d85c495c07 100644 --- a/tests/pjsua/scripts-sipp/strict-route.py +++ b/tests/pjsua/scripts-sipp/strict-route.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/transfer-attended.py b/tests/pjsua/scripts-sipp/transfer-attended.py index 564ab38291..8bc4e03f10 100644 --- a/tests/pjsua/scripts-sipp/transfer-attended.py +++ b/tests/pjsua/scripts-sipp/transfer-attended.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/transfer-unattended.py b/tests/pjsua/scripts-sipp/transfer-unattended.py index 77e82537de..b6acbd4bbc 100644 --- a/tests/pjsua/scripts-sipp/transfer-unattended.py +++ b/tests/pjsua/scripts-sipp/transfer-unattended.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-183-wrong-codec.py b/tests/pjsua/scripts-sipp/uac-183-wrong-codec.py index 3c18b9a59b..aecc60b55a 100644 --- a/tests/pjsua/scripts-sipp/uac-183-wrong-codec.py +++ b/tests/pjsua/scripts-sipp/uac-183-wrong-codec.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-183-wrong-media.py b/tests/pjsua/scripts-sipp/uac-183-wrong-media.py index 3c18b9a59b..aecc60b55a 100644 --- a/tests/pjsua/scripts-sipp/uac-183-wrong-media.py +++ b/tests/pjsua/scripts-sipp/uac-183-wrong-media.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-inv-two-media-but-one-disabled-no-rtpmap.py b/tests/pjsua/scripts-sipp/uac-inv-two-media-but-one-disabled-no-rtpmap.py index 7a457ad074..c26cc72928 100644 --- a/tests/pjsua/scripts-sipp/uac-inv-two-media-but-one-disabled-no-rtpmap.py +++ b/tests/pjsua/scripts-sipp/uac-inv-two-media-but-one-disabled-no-rtpmap.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-inv-without-sdp.py b/tests/pjsua/scripts-sipp/uac-inv-without-sdp.py index 3183cc08ed..4f340221bd 100644 --- a/tests/pjsua/scripts-sipp/uac-inv-without-sdp.py +++ b/tests/pjsua/scripts-sipp/uac-inv-without-sdp.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-srtp-dtls-lower-prio.py b/tests/pjsua/scripts-sipp/uac-srtp-dtls-lower-prio.py index b19f0dcb7b..7604fe356c 100644 --- a/tests/pjsua/scripts-sipp/uac-srtp-dtls-lower-prio.py +++ b/tests/pjsua/scripts-sipp/uac-srtp-dtls-lower-prio.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-srtp-dtls-reinv-sdes.py b/tests/pjsua/scripts-sipp/uac-srtp-dtls-reinv-sdes.py index 77acbe66ed..81aa5c838f 100644 --- a/tests/pjsua/scripts-sipp/uac-srtp-dtls-reinv-sdes.py +++ b/tests/pjsua/scripts-sipp/uac-srtp-dtls-reinv-sdes.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-srtp-dtls.py b/tests/pjsua/scripts-sipp/uac-srtp-dtls.py index 111a94e8eb..f6e9db4373 100644 --- a/tests/pjsua/scripts-sipp/uac-srtp-dtls.py +++ b/tests/pjsua/scripts-sipp/uac-srtp-dtls.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-srtp-sdes-reinv-dtls.py b/tests/pjsua/scripts-sipp/uac-srtp-sdes-reinv-dtls.py index f5a2c0249c..f485acb2cd 100644 --- a/tests/pjsua/scripts-sipp/uac-srtp-sdes-reinv-dtls.py +++ b/tests/pjsua/scripts-sipp/uac-srtp-sdes-reinv-dtls.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-srtp-sdes.py b/tests/pjsua/scripts-sipp/uac-srtp-sdes.py index dc1d097262..360e539408 100644 --- a/tests/pjsua/scripts-sipp/uac-srtp-sdes.py +++ b/tests/pjsua/scripts-sipp/uac-srtp-sdes.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-ticket-1148.py b/tests/pjsua/scripts-sipp/uac-ticket-1148.py index 7a457ad074..c26cc72928 100644 --- a/tests/pjsua/scripts-sipp/uac-ticket-1148.py +++ b/tests/pjsua/scripts-sipp/uac-ticket-1148.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-ticket-1864-scenario1.py b/tests/pjsua/scripts-sipp/uac-ticket-1864-scenario1.py index 6ef94ff42c..098cd636e6 100644 --- a/tests/pjsua/scripts-sipp/uac-ticket-1864-scenario1.py +++ b/tests/pjsua/scripts-sipp/uac-ticket-1864-scenario1.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-ticket-1864-scenario2.py b/tests/pjsua/scripts-sipp/uac-ticket-1864-scenario2.py index 892499aa0c..b1be9afa9f 100644 --- a/tests/pjsua/scripts-sipp/uac-ticket-1864-scenario2.py +++ b/tests/pjsua/scripts-sipp/uac-ticket-1864-scenario2.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-ticket-1866-reinv-after-failed-nego.py b/tests/pjsua/scripts-sipp/uac-ticket-1866-reinv-after-failed-nego.py index 892499aa0c..b1be9afa9f 100644 --- a/tests/pjsua/scripts-sipp/uac-ticket-1866-reinv-after-failed-nego.py +++ b/tests/pjsua/scripts-sipp/uac-ticket-1866-reinv-after-failed-nego.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-upd-sdp-decline.py b/tests/pjsua/scripts-sipp/uac-upd-sdp-decline.py index e787fd4551..5f60eee28e 100644 --- a/tests/pjsua/scripts-sipp/uac-upd-sdp-decline.py +++ b/tests/pjsua/scripts-sipp/uac-upd-sdp-decline.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uac-upd-sdp-offer.py b/tests/pjsua/scripts-sipp/uac-upd-sdp-offer.py index e787fd4551..5f60eee28e 100644 --- a/tests/pjsua/scripts-sipp/uac-upd-sdp-offer.py +++ b/tests/pjsua/scripts-sipp/uac-upd-sdp-offer.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-answer-183-without-to-tag.py b/tests/pjsua/scripts-sipp/uas-answer-183-without-to-tag.py index b215be3bbf..ccdeb4051d 100644 --- a/tests/pjsua/scripts-sipp/uas-answer-183-without-to-tag.py +++ b/tests/pjsua/scripts-sipp/uas-answer-183-without-to-tag.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-answer-183-wrong-codec.py b/tests/pjsua/scripts-sipp/uas-answer-183-wrong-codec.py index 32eed01869..d7a877b63b 100644 --- a/tests/pjsua/scripts-sipp/uas-answer-183-wrong-codec.py +++ b/tests/pjsua/scripts-sipp/uas-answer-183-wrong-codec.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-answer-183-wrong-media.py b/tests/pjsua/scripts-sipp/uas-answer-183-wrong-media.py index 32eed01869..d7a877b63b 100644 --- a/tests/pjsua/scripts-sipp/uas-answer-183-wrong-media.py +++ b/tests/pjsua/scripts-sipp/uas-answer-183-wrong-media.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-answer-200-reinvite-without-sdp.py b/tests/pjsua/scripts-sipp/uas-answer-200-reinvite-without-sdp.py index 018d2e2742..6fe4e5bff9 100644 --- a/tests/pjsua/scripts-sipp/uas-answer-200-reinvite-without-sdp.py +++ b/tests/pjsua/scripts-sipp/uas-answer-200-reinvite-without-sdp.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-answer-200-update-without-sdp.py b/tests/pjsua/scripts-sipp/uas-answer-200-update-without-sdp.py index 5f03887336..607b8b68ba 100644 --- a/tests/pjsua/scripts-sipp/uas-answer-200-update-without-sdp.py +++ b/tests/pjsua/scripts-sipp/uas-answer-200-update-without-sdp.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-auth-two-algo.py b/tests/pjsua/scripts-sipp/uas-auth-two-algo.py index c79c9f6d35..77af98d990 100644 --- a/tests/pjsua/scripts-sipp/uas-auth-two-algo.py +++ b/tests/pjsua/scripts-sipp/uas-auth-two-algo.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-auth.py b/tests/pjsua/scripts-sipp/uas-auth.py index 533dbac83b..845b8a17b2 100644 --- a/tests/pjsua/scripts-sipp/uas-auth.py +++ b/tests/pjsua/scripts-sipp/uas-auth.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-cancel-no-final.py b/tests/pjsua/scripts-sipp/uas-cancel-no-final.py index 0b968ddfb9..4859d0fdb5 100644 --- a/tests/pjsua/scripts-sipp/uas-cancel-no-final.py +++ b/tests/pjsua/scripts-sipp/uas-cancel-no-final.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-mwi-0.py b/tests/pjsua/scripts-sipp/uas-mwi-0.py index 5cb8cc06e7..bddb5525c2 100644 --- a/tests/pjsua/scripts-sipp/uas-mwi-0.py +++ b/tests/pjsua/scripts-sipp/uas-mwi-0.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-mwi.py b/tests/pjsua/scripts-sipp/uas-mwi.py index 5cb8cc06e7..bddb5525c2 100644 --- a/tests/pjsua/scripts-sipp/uas-mwi.py +++ b/tests/pjsua/scripts-sipp/uas-mwi.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-reinv-after-failed-nego.py b/tests/pjsua/scripts-sipp/uas-reinv-after-failed-nego.py index e2b2d9031d..d0030f4815 100644 --- a/tests/pjsua/scripts-sipp/uas-reinv-after-failed-nego.py +++ b/tests/pjsua/scripts-sipp/uas-reinv-after-failed-nego.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-reinv-glare.py b/tests/pjsua/scripts-sipp/uas-reinv-glare.py index 5f03887336..607b8b68ba 100644 --- a/tests/pjsua/scripts-sipp/uas-reinv-glare.py +++ b/tests/pjsua/scripts-sipp/uas-reinv-glare.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-reinv-with-less-media.py b/tests/pjsua/scripts-sipp/uas-reinv-with-less-media.py index 9930f6e5fd..6b584314f8 100644 --- a/tests/pjsua/scripts-sipp/uas-reinv-with-less-media.py +++ b/tests/pjsua/scripts-sipp/uas-reinv-with-less-media.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-subscribe-late-notify.py b/tests/pjsua/scripts-sipp/uas-subscribe-late-notify.py index a051215f4e..a89211511e 100644 --- a/tests/pjsua/scripts-sipp/uas-subscribe-late-notify.py +++ b/tests/pjsua/scripts-sipp/uas-subscribe-late-notify.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-subscribe-multipart-notify.py b/tests/pjsua/scripts-sipp/uas-subscribe-multipart-notify.py index ef186c9f19..896ee4014e 100644 --- a/tests/pjsua/scripts-sipp/uas-subscribe-multipart-notify.py +++ b/tests/pjsua/scripts-sipp/uas-subscribe-multipart-notify.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-subscribe-notify-terminate.py b/tests/pjsua/scripts-sipp/uas-subscribe-notify-terminate.py index da6dc6e53f..46f7224673 100644 --- a/tests/pjsua/scripts-sipp/uas-subscribe-notify-terminate.py +++ b/tests/pjsua/scripts-sipp/uas-subscribe-notify-terminate.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-subscribe-refresh-481.py b/tests/pjsua/scripts-sipp/uas-subscribe-refresh-481.py index ef186c9f19..896ee4014e 100644 --- a/tests/pjsua/scripts-sipp/uas-subscribe-refresh-481.py +++ b/tests/pjsua/scripts-sipp/uas-subscribe-refresh-481.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/scripts-sipp/uas-subscribe-terminated-retry.py b/tests/pjsua/scripts-sipp/uas-subscribe-terminated-retry.py index 866122dfb4..12d214db1c 100644 --- a/tests/pjsua/scripts-sipp/uas-subscribe-terminated-retry.py +++ b/tests/pjsua/scripts-sipp/uas-subscribe-terminated-retry.py @@ -1,4 +1,3 @@ -# $Id$ # import inc_const as const diff --git a/tests/pjsua/tools/cmp_wav.c b/tests/pjsua/tools/cmp_wav.c index f2353efd7b..68ca509e39 100644 --- a/tests/pjsua/tools/cmp_wav.c +++ b/tests/pjsua/tools/cmp_wav.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono @@ -28,30 +27,30 @@ /* For logging purpose. */ #define THIS_FILE "cmp_wav.c" -#define BYTES_PER_FRAME 512 +#define BYTES_PER_FRAME 512 static const char *desc = -" FILE \n" -" \n" -" cmp_wav.c \n" -" \n" -" PURPOSE \n" -" \n" -" Compare two WAV files. \n" -" \n" -" USAGE \n" -" \n" -" cmp_wav ORIGINAL_WAV DEGRADED_WAV [TIME] [DETAIL] \n" -" \n" -" ORIGINAL_WAV The original WAV file as reference. \n" -" DEGRADED_WAV The degraded WAV file. \n" -" TIME Compare only some part of the files \n" -" (in ms, since the beginning). \n" +" FILE \n" +" \n" +" cmp_wav.c \n" +" \n" +" PURPOSE \n" +" \n" +" Compare two WAV files. \n" +" \n" +" USAGE \n" +" \n" +" cmp_wav ORIGINAL_WAV DEGRADED_WAV [TIME] [DETAIL] \n" +" \n" +" ORIGINAL_WAV The original WAV file as reference. \n" +" DEGRADED_WAV The degraded WAV file. \n" +" TIME Compare only some part of the files \n" +" (in ms, since the beginning). \n" " Specify 0 (default) to compare the whole time. \n" " DETAIL Show detail result, 1 or 0 (default=0, means no)\n" -" \n" -" Both files must have same clock rate and must contain \n" -" uncompressed (i.e. 16bit) PCM. \n"; +" \n" +" Both files must have same clock rate and must contain \n" +" uncompressed (i.e. 16bit) PCM. \n"; /* Sum of multiplication of corresponding samples in buf1 & buf2 */ @@ -60,7 +59,7 @@ double sum_mult_sig(pj_int16_t *buf1, pj_int16_t *buf2, unsigned nsamples) double mag = 0; while (nsamples--) - mag += (double)*buf1++ * (double)*buf2++; + mag += (double)*buf1++ * (double)*buf2++; return mag; } @@ -91,9 +90,9 @@ int main(int argc, char *argv[]) int res_deg, res_mix, res_overall; if (argc < 3) { - puts("Error: original & degraded filename required"); - puts(desc); - return 1; + puts("Error: original & degraded filename required"); + puts(desc); + return 1; } /* Set log level. */ @@ -114,127 +113,127 @@ int main(int argc, char *argv[]) PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); /* Create memory pool for our file player */ - pool = pj_pool_create( &cp.factory, /* pool factory */ - "wav", /* pool name. */ - 4000, /* init size */ - 4000, /* increment size */ - NULL /* callback on error */ - ); + pool = pj_pool_create( &cp.factory, /* pool factory */ + "wav", /* pool name. */ + 4000, /* init size */ + 4000, /* increment size */ + NULL /* callback on error */ + ); /* Create file media port from the original WAV file */ - status = pjmedia_wav_player_port_create( pool, /* memory pool */ - argv[1], /* file to play */ - 40, /* ptime. */ - PJMEDIA_FILE_NO_LOOP, /* flags */ - 0, /* default buffer */ - &file_ori_port/* returned port */ - ); + status = pjmedia_wav_player_port_create( pool, /* memory pool */ + argv[1], /* file to play */ + 40, /* ptime. */ + PJMEDIA_FILE_NO_LOOP, /* flags */ + 0, /* default buffer */ + &file_ori_port/* returned port */ + ); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to use WAV file", status); - return 1; + app_perror(THIS_FILE, "Unable to use WAV file", status); + return 1; } /* Create file media port from the degraded WAV file */ - status = pjmedia_wav_player_port_create( pool, /* memory pool */ - argv[2], /* file to play */ - 40, /* ptime. */ - PJMEDIA_FILE_NO_LOOP, /* flags */ - 0, /* default buffer */ - &file_deg_port/* returned port */ - ); + status = pjmedia_wav_player_port_create( pool, /* memory pool */ + argv[2], /* file to play */ + 40, /* ptime. */ + PJMEDIA_FILE_NO_LOOP, /* flags */ + 0, /* default buffer */ + &file_deg_port/* returned port */ + ); if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Unable to use WAV file", status); - return 1; + app_perror(THIS_FILE, "Unable to use WAV file", status); + return 1; } if (file_ori_port->info.fmt.det.aud.clock_rate != - file_deg_port->info.fmt.det.aud.clock_rate) + file_deg_port->info.fmt.det.aud.clock_rate) { - app_perror(THIS_FILE, "Clock rates must be same.", PJ_EINVAL); - return 1; + app_perror(THIS_FILE, "Clock rates must be same.", PJ_EINVAL); + return 1; } if (argc > 3) - first_nsamples = atoi(argv[3]) * - file_ori_port->info.fmt.det.aud.clock_rate / 1000; + first_nsamples = atoi(argv[3]) * + file_ori_port->info.fmt.det.aud.clock_rate / 1000; if (argc > 4) - detail = atoi(argv[4]); + detail = atoi(argv[4]); while (1) { - pjmedia_frame f1, f2; - - f1.buf = buf1; - f1.size = BYTES_PER_FRAME; - f2.buf = buf2; - f2.size = BYTES_PER_FRAME; - - status = pjmedia_port_get_frame(file_ori_port, &f1); - if (status == PJ_EEOF) { - break; - } else if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error occured while reading file", status); - break; - } - status = pjmedia_port_get_frame(file_deg_port, &f2); - if (status == PJ_EEOF) { - break; - } else if (status != PJ_SUCCESS) { - app_perror(THIS_FILE, "Error occured while reading file", status); - break; - } - - /* Calculate magnitudes */ - ref_mag += sum_mult_sig(f1.buf, f1.buf, BYTES_PER_FRAME >> 1); - deg_mag += sum_mult_sig(f2.buf, f2.buf, BYTES_PER_FRAME >> 1); - mix_mag += sum_mult_sig(f1.buf, f2.buf, BYTES_PER_FRAME >> 1); - - samples_compared += BYTES_PER_FRAME >> 1; - if (first_nsamples && samples_compared >= first_nsamples) - break; + pjmedia_frame f1, f2; + + f1.buf = buf1; + f1.size = BYTES_PER_FRAME; + f2.buf = buf2; + f2.size = BYTES_PER_FRAME; + + status = pjmedia_port_get_frame(file_ori_port, &f1); + if (status == PJ_EEOF) { + break; + } else if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Error occured while reading file", status); + break; + } + status = pjmedia_port_get_frame(file_deg_port, &f2); + if (status == PJ_EEOF) { + break; + } else if (status != PJ_SUCCESS) { + app_perror(THIS_FILE, "Error occured while reading file", status); + break; + } + + /* Calculate magnitudes */ + ref_mag += sum_mult_sig(f1.buf, f1.buf, BYTES_PER_FRAME >> 1); + deg_mag += sum_mult_sig(f2.buf, f2.buf, BYTES_PER_FRAME >> 1); + mix_mag += sum_mult_sig(f1.buf, f2.buf, BYTES_PER_FRAME >> 1); + + samples_compared += BYTES_PER_FRAME >> 1; + if (first_nsamples && samples_compared >= first_nsamples) + break; } /* Degraded magnitude compared to reference magnitude */ res_deg = (int) (deg_mag / ref_mag * 100.0); if (res_deg < 0) - res_deg = -1; + res_deg = -1; else if (res_deg >= 81) - res_deg = 9; + res_deg = 9; else - res_deg = pj_isqrt(res_deg); + res_deg = pj_isqrt(res_deg); /* Mixed magnitude (don't know what this is actually :D) compared to * reference magnitude */ res_mix = (int) (mix_mag / ref_mag * 100.0); if (res_mix < 0) - res_mix = -1; + res_mix = -1; else if (res_mix >= 81) - res_mix = 9; + res_mix = 9; else - res_mix = pj_isqrt(res_mix); + res_mix = pj_isqrt(res_mix); /* Overall score. * If mixed score is -1, then overall score should be -1 as well. * Apply no weighting (1:1) for now. */ if (res_mix == -1) - res_overall = -1; + res_overall = -1; else - res_overall = (res_mix*1 + res_deg*1) / 2; + res_overall = (res_mix*1 + res_deg*1) / 2; if (detail) { - printf("Reference = %.0f\n", ref_mag); - printf("Degraded = %.0f\n", deg_mag); - printf("Mixed = %.0f\n", mix_mag); + printf("Reference = %.0f\n", ref_mag); + printf("Degraded = %.0f\n", deg_mag); + printf("Mixed = %.0f\n", mix_mag); - printf("\n"); + printf("\n"); - printf("Score 1 = %d\n", res_deg); - printf("Score 2 = %d\n", res_mix); + printf("Score 1 = %d\n", res_deg); + printf("Score 2 = %d\n", res_mix); - printf("\n"); + printf("\n"); } printf("Overall = %d\n", res_overall); diff --git a/third_party/build/srtp/srtp_config.h b/third_party/build/srtp/srtp_config.h index 5958632be9..87967643d0 100644 --- a/third_party/build/srtp/srtp_config.h +++ b/third_party/build/srtp/srtp_config.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2003-2007 Benny Prijono * @@ -29,11 +28,11 @@ defined(__x86_64__) || defined(__x86_64) || \ defined(PJ_M_IA64) || defined(__ia64__) || defined(_IA64) || \ defined(__IA64__) || defined(_M_IA64) -# define CPU_CISC 1 -/* # define HAVE_X86 1 use X86 inlined assembly code */ +# define CPU_CISC 1 +/* # define HAVE_X86 1 use X86 inlined assembly code */ #else -/*# define CPU_RISC 1*/ -# define CPU_CISC 1 +/*# define CPU_RISC 1*/ +# define CPU_CISC 1 #endif /* Define to compile in dynamic debugging system. */ @@ -55,7 +54,7 @@ /* Define to 1 if you have the header file. */ #if defined(PJ_HAS_NETINET_IN_H) && PJ_HAS_NETINET_IN_H!=0 -# define HAVE_NETINET_IN_H 1 +# define HAVE_NETINET_IN_H 1 #endif /* Define to 1 if you have the header file. */ @@ -70,7 +69,7 @@ /* Define to 1 if you have the header file. */ #if defined(PJ_HAS_SYS_SOCKET_H) && PJ_HAS_SYS_SOCKET_H!=0 -# define HAVE_SYS_SOCKET_H 1 +# define HAVE_SYS_SOCKET_H 1 #endif /* Define to 1 if you have the header file. */ @@ -82,7 +81,7 @@ /* Define to 1 if you have the `usleep' function. */ #if defined(PJ_HAS_UNISTD_H) && PJ_HAS_UNISTD_H!=0 # define HAVE_UNISTD_H 1 -# define HAVE_USLEEP 1 +# define HAVE_USLEEP 1 #endif @@ -96,45 +95,45 @@ # define HAVE_WINSOCK2_H 1 #endif -#define HAVE_INT16_T 1 -#define HAVE_INT32_T 1 -#define HAVE_INT8_T 1 -#define HAVE_UINT8_T 1 -#define HAVE_UINT16_T 1 -#define HAVE_UINT32_T 1 -#define HAVE_UINT64_T 1 +#define HAVE_INT16_T 1 +#define HAVE_INT32_T 1 +#define HAVE_INT8_T 1 +#define HAVE_UINT8_T 1 +#define HAVE_UINT16_T 1 +#define HAVE_UINT32_T 1 +#define HAVE_UINT64_T 1 /* Define to 1 if you have the header file. */ #if defined(PJ_HAS_STDINT_H) && PJ_HAS_STDINT_H!=0 # define HAVE_STDINT_H 1 #else - typedef pj_uint8_t uint8_t; - typedef pj_uint16_t uint16_t; - typedef pj_uint32_t uint32_t; - typedef pj_uint64_t uint64_t; - typedef pj_int8_t int8_t; - typedef pj_int16_t int16_t; - typedef pj_int32_t int32_t; - typedef pj_int64_t int64_t; + typedef pj_uint8_t uint8_t; + typedef pj_uint16_t uint16_t; + typedef pj_uint32_t uint32_t; + typedef pj_uint64_t uint64_t; + typedef pj_int8_t int8_t; + typedef pj_int16_t int16_t; + typedef pj_int32_t int32_t; + typedef pj_int64_t int64_t; #endif /* These shouldn't really matter as long as HAVE_UINT64_T is set */ -#define SIZEOF_UNSIGNED_LONG (sizeof(unsigned long)) +#define SIZEOF_UNSIGNED_LONG (sizeof(unsigned long)) #define SIZEOF_UNSIGNED_LONG_LONG 8 #if (_MSC_VER >= 1400) // VC8+ # ifndef _CRT_SECURE_NO_DEPRECATE -# define _CRT_SECURE_NO_DEPRECATE +# define _CRT_SECURE_NO_DEPRECATE # endif # ifndef _CRT_NONSTDC_NO_DEPRECATE -# define _CRT_NONSTDC_NO_DEPRECATE +# define _CRT_NONSTDC_NO_DEPRECATE # endif #endif // VC8+ #ifdef _MSC_VER # ifndef __cplusplus -# define inline _inline +# define inline _inline # endif # pragma warning(disable:4311) // 'type cast': pointer truncation from 'unsigned char *' to 'unsigned long' @@ -154,12 +153,12 @@ /* clock() causes unresolved symbol on linking */ # define _CLOCK_T_DEFINED # define CLOCKS_PER_SEC 1000 -# define clock_t unsigned +# define clock_t unsigned #include static clock_t clock(void) { - return GetTickCount(); + return GetTickCount(); } #endif @@ -171,7 +170,7 @@ * Try to open PJ_DEV_URANDOM if present */ #if defined(PJ_HAS_FCNTL_H) && defined(PJ_HAS_UNISTD_H) -# define PJ_DEV_URANDOM "/dev/urandom" +# define PJ_DEV_URANDOM "/dev/urandom" #endif /* We have overridden libsrtp error mechanism, so these are not used. */ @@ -232,5 +231,5 @@ #define PACKAGE_VERSION "2.1.0" -#endif /* __SRTP_CONFIG_H__ */ +#endif /* __SRTP_CONFIG_H__ */ diff --git a/third_party/g7221/common/count.h b/third_party/g7221/common/count.h index 791145e865..cddfe8378c 100644 --- a/third_party/g7221/common/count.h +++ b/third_party/g7221/common/count.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * diff --git a/third_party/g7221/common/typedef.h b/third_party/g7221/common/typedef.h index 09ddaba486..95d1a7013a 100644 --- a/third_party/g7221/common/typedef.h +++ b/third_party/g7221/common/typedef.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * diff --git a/third_party/mp3/mp3_port.h b/third_party/mp3/mp3_port.h index 52ccad545e..b535d4fc50 100644 --- a/third_party/mp3/mp3_port.h +++ b/third_party/mp3/mp3_port.h @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2003-2007 Benny Prijono * @@ -63,7 +62,7 @@ typedef struct pjmedia_mp3_encoder_option * would normally produce better quality at the expense of probably * larger file. */ - pj_bool_t vbr; + pj_bool_t vbr; /** Target bitrate, in bps. If VBR is enabled, this settings specifies * the average bit-rate requested, and will make the encoder ignore @@ -71,12 +70,12 @@ typedef struct pjmedia_mp3_encoder_option * and if this option is zero, it will be set to the sampling rate * multiplied by number of channels. */ - unsigned bit_rate; + unsigned bit_rate; /** Encoding quality, 0-9, with 0 is the highest quality. For VBR, the * quality setting will only take effect when bit_rate setting is zero. */ - unsigned quality; + unsigned quality; } pjmedia_mp3_encoder_option; @@ -91,26 +90,26 @@ typedef struct pjmedia_mp3_encoder_option * media port with #pjmedia_port_destroy() so that the MP3 file can be * closed properly. * - * @param pool Pool to create memory buffers for this port. - * @param filename File name. - * @param clock_rate The sampling rate. - * @param channel_count Number of channels. + * @param pool Pool to create memory buffers for this port. + * @param filename File name. + * @param clock_rate The sampling rate. + * @param channel_count Number of channels. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Number of bits per sample (eg 16). - * @param option Optional option to set encoding parameters. - * @param p_port Pointer to receive the file port instance. + * @param option Optional option to set encoding parameters. + * @param p_port Pointer to receive the file port instance. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_mp3_writer_port_create(pj_pool_t *pool, - const char *filename, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - const pjmedia_mp3_encoder_option *option, - pjmedia_port **p_port ); + const char *filename, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + const pjmedia_mp3_encoder_option *option, + pjmedia_port **p_port ); #if !DEPRECATED_FOR_TICKET_2251 @@ -119,23 +118,23 @@ pjmedia_mp3_writer_port_create(pj_pool_t *pool, * certain size. Application can use this callback, for example, to limit * the size of the output file. * - * @param port The file writer port. - * @param pos The file position on which the callback will be called. - * @param user_data User data to be specified in the callback, and will be - * given on the callback. - * @param cb Callback to be called. If the callback returns non- - * PJ_SUCCESS, the writing will stop. Note that if - * application destroys the port in the callback, it must - * return non-PJ_SUCCESS here. + * @param port The file writer port. + * @param pos The file position on which the callback will be called. + * @param user_data User data to be specified in the callback, and will be + * given on the callback. + * @param cb Callback to be called. If the callback returns non- + * PJ_SUCCESS, the writing will stop. Note that if + * application destroys the port in the callback, it must + * return non-PJ_SUCCESS here. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_mp3_writer_port_set_cb( pjmedia_port *port, - pj_size_t pos, - void *user_data, - pj_status_t (*cb)(pjmedia_port *port, - void *usr_data)); + pj_size_t pos, + void *user_data, + pj_status_t (*cb)(pjmedia_port *port, + void *usr_data)); #endif @@ -144,24 +143,24 @@ pjmedia_mp3_writer_port_set_cb( pjmedia_port *port, * certain size. Application can use this callback, for example, to limit * the size of the output file. * - * @param port The file writer port. - * @param pos The file position on which the callback will be called. - * @param user_data User data to be specified in the callback, and will be - * given on the callback. - * @param cb Callback to be called. Note that if - * application wishes to stop the playback, it - * can disconnect the port in the callback, and - * only after all connections have been removed - * could the application safely destroy the port. + * @param port The file writer port. + * @param pos The file position on which the callback will be called. + * @param user_data User data to be specified in the callback, and will be + * given on the callback. + * @param cb Callback to be called. Note that if + * application wishes to stop the playback, it + * can disconnect the port in the callback, and + * only after all connections have been removed + * could the application safely destroy the port. * - * @return PJ_SUCCESS on success. + * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) pjmedia_mp3_writer_port_set_cb2(pjmedia_port *port, - pj_size_t pos, - void *user_data, - void (*cb)(pjmedia_port *port, - void *usr_data)); + pj_size_t pos, + void *user_data, + void (*cb)(pjmedia_port *port, + void *usr_data)); /** @@ -171,5 +170,5 @@ pjmedia_mp3_writer_port_set_cb2(pjmedia_port *port, PJ_END_DECL -#endif /* __PJMEDIA_MP3_PORT_H__ */ +#endif /* __PJMEDIA_MP3_PORT_H__ */ diff --git a/third_party/mp3/mp3_writer.c b/third_party/mp3/mp3_writer.c index 4305e01bf4..78f2a04c90 100644 --- a/third_party/mp3/mp3_writer.c +++ b/third_party/mp3/mp3_writer.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2003-2007 Benny Prijono * @@ -36,51 +35,51 @@ #include "BladeMP3EncDLL.h" -#define THIS_FILE "mp3_writer.c" -#define SIGNATURE PJMEDIA_SIG_CLASS_PORT_AUD('M','W') +#define THIS_FILE "mp3_writer.c" +#define SIGNATURE PJMEDIA_SIG_CLASS_PORT_AUD('M','W') #define BYTES_PER_SAMPLE 2 static struct BladeDLL { - void *hModule; - int refCount; - BEINITSTREAM beInitStream; - BEENCODECHUNK beEncodeChunk; - BEDEINITSTREAM beDeinitStream; - BECLOSESTREAM beCloseStream; - BEVERSION beVersion; - BEWRITEVBRHEADER beWriteVBRHeader; - BEWRITEINFOTAG beWriteInfoTag; + void *hModule; + int refCount; + BEINITSTREAM beInitStream; + BEENCODECHUNK beEncodeChunk; + BEDEINITSTREAM beDeinitStream; + BECLOSESTREAM beCloseStream; + BEVERSION beVersion; + BEWRITEVBRHEADER beWriteVBRHeader; + BEWRITEINFOTAG beWriteInfoTag; } BladeDLL; struct mp3_file_port { pjmedia_port base; - pj_size_t total; + pj_size_t total; pj_oshandle_t fd; - pj_size_t cb_size; - pj_status_t (*cb)(pjmedia_port*, void*); - pj_bool_t subscribed; - pj_bool_t cb_called; - void (*cb2)(pjmedia_port*, void*); + pj_size_t cb_size; + pj_status_t (*cb)(pjmedia_port*, void*); + pj_bool_t subscribed; + pj_bool_t cb_called; + void (*cb2)(pjmedia_port*, void*); - unsigned silence_duration; + unsigned silence_duration; - pj_str_t mp3_filename; + pj_str_t mp3_filename; pjmedia_mp3_encoder_option mp3_option; - unsigned mp3_samples_per_frame; - pj_int16_t *mp3_sample_buf; - unsigned mp3_sample_pos; - HBE_STREAM mp3_stream; - unsigned char *mp3_buf; + unsigned mp3_samples_per_frame; + pj_int16_t *mp3_sample_buf; + unsigned mp3_sample_pos; + HBE_STREAM mp3_stream; + unsigned char *mp3_buf; }; static pj_status_t file_put_frame(pjmedia_port *this_port, - const pjmedia_frame *frame); + const pjmedia_frame *frame); static pj_status_t file_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame); + pjmedia_frame *frame); static pj_status_t file_on_destroy(pjmedia_port *this_port); @@ -95,38 +94,38 @@ static pj_status_t file_on_destroy(pjmedia_port *this_port); static pj_status_t init_blade_dll(void) { if (BladeDLL.refCount == 0) { - #define GET_PROC(type, name) \ - BladeDLL.name = (type)GetProcAddress(BladeDLL.hModule, PJ_T(#name)); \ - if (BladeDLL.name == NULL) { \ - PJ_LOG(1,(THIS_FILE, "Unable to find %s in %s", #name, DLL_NAME)); \ - return PJ_RETURN_OS_ERROR(GetLastError()); \ - } - - BE_VERSION beVersion; - BladeDLL.hModule = (void*)LoadLibrary(DLL_NAME); - if (BladeDLL.hModule == NULL) { - pj_status_t status = PJ_RETURN_OS_ERROR(GetLastError()); - char errmsg[PJ_ERR_MSG_SIZE]; - - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(1,(THIS_FILE, "Unable to load %s: %s", DLL_NAME, errmsg)); - return status; - } - - GET_PROC(BEINITSTREAM, beInitStream); - GET_PROC(BEENCODECHUNK, beEncodeChunk); - GET_PROC(BEDEINITSTREAM, beDeinitStream); - GET_PROC(BECLOSESTREAM, beCloseStream); - GET_PROC(BEVERSION, beVersion); - GET_PROC(BEWRITEVBRHEADER, beWriteVBRHeader); - GET_PROC(BEWRITEINFOTAG, beWriteInfoTag); - - #undef GET_PROC - - BladeDLL.beVersion(&beVersion); - PJ_LOG(4,(THIS_FILE, "%s encoder v%d.%d loaded (%s)", DLL_NAME, - beVersion.byMajorVersion, beVersion.byMinorVersion, - beVersion.zHomepage)); + #define GET_PROC(type, name) \ + BladeDLL.name = (type)GetProcAddress(BladeDLL.hModule, PJ_T(#name)); \ + if (BladeDLL.name == NULL) { \ + PJ_LOG(1,(THIS_FILE, "Unable to find %s in %s", #name, DLL_NAME)); \ + return PJ_RETURN_OS_ERROR(GetLastError()); \ + } + + BE_VERSION beVersion; + BladeDLL.hModule = (void*)LoadLibrary(DLL_NAME); + if (BladeDLL.hModule == NULL) { + pj_status_t status = PJ_RETURN_OS_ERROR(GetLastError()); + char errmsg[PJ_ERR_MSG_SIZE]; + + pj_strerror(status, errmsg, sizeof(errmsg)); + PJ_LOG(1,(THIS_FILE, "Unable to load %s: %s", DLL_NAME, errmsg)); + return status; + } + + GET_PROC(BEINITSTREAM, beInitStream); + GET_PROC(BEENCODECHUNK, beEncodeChunk); + GET_PROC(BEDEINITSTREAM, beDeinitStream); + GET_PROC(BECLOSESTREAM, beCloseStream); + GET_PROC(BEVERSION, beVersion); + GET_PROC(BEWRITEVBRHEADER, beWriteVBRHeader); + GET_PROC(BEWRITEINFOTAG, beWriteInfoTag); + + #undef GET_PROC + + BladeDLL.beVersion(&beVersion); + PJ_LOG(4,(THIS_FILE, "%s encoder v%d.%d loaded (%s)", DLL_NAME, + beVersion.byMajorVersion, beVersion.byMinorVersion, + beVersion.zHomepage)); } ++BladeDLL.refCount; return PJ_SUCCESS; @@ -139,9 +138,9 @@ static void deinit_blade_dll() { --BladeDLL.refCount; if (BladeDLL.refCount == 0 && BladeDLL.hModule) { - FreeLibrary(BladeDLL.hModule); - BladeDLL.hModule = NULL; - PJ_LOG(4,(THIS_FILE, "%s unloaded", DLL_NAME)); + FreeLibrary(BladeDLL.hModule); + BladeDLL.hModule = NULL; + PJ_LOG(4,(THIS_FILE, "%s unloaded", DLL_NAME)); } } @@ -164,7 +163,7 @@ static void deinit_blade_dll() * Initialize MP3 encoder. */ static pj_status_t init_mp3_encoder(struct mp3_file_port *fport, - pj_pool_t *pool) + pj_pool_t *pool) { BE_CONFIG LConfig; unsigned long InSamples; @@ -182,11 +181,11 @@ static pj_status_t init_mp3_encoder(struct mp3_file_port *fport, LConfig.format.LHV1.dwReSampleRate = 0; if (PJMEDIA_PIA_CCNT(&fport->base.info)==1) - LConfig.format.LHV1.nMode = BE_MP3_MODE_MONO; + LConfig.format.LHV1.nMode = BE_MP3_MODE_MONO; else if (PJMEDIA_PIA_CCNT(&fport->base.info)==2) - LConfig.format.LHV1.nMode = BE_MP3_MODE_STEREO; + LConfig.format.LHV1.nMode = BE_MP3_MODE_STEREO; else - return PJMEDIA_ENCCHANNEL; + return PJMEDIA_ENCCHANNEL; LConfig.format.LHV1.dwBitrate = fport->mp3_option.bit_rate / 1000; LConfig.format.LHV1.nPreset = LQP_NOPRESET; @@ -196,30 +195,30 @@ static pj_status_t init_mp3_encoder(struct mp3_file_port *fport, LConfig.format.LHV1.bPrivate = 0; if (!fport->mp3_option.vbr) { - LConfig.format.LHV1.nVbrMethod = VBR_METHOD_NONE; - LConfig.format.LHV1.bWriteVBRHeader = 0; - LConfig.format.LHV1.bEnableVBR = 0; + LConfig.format.LHV1.nVbrMethod = VBR_METHOD_NONE; + LConfig.format.LHV1.bWriteVBRHeader = 0; + LConfig.format.LHV1.bEnableVBR = 0; } else { - LConfig.format.LHV1.nVbrMethod = VBR_METHOD_DEFAULT; - LConfig.format.LHV1.bWriteVBRHeader = 1; - LConfig.format.LHV1.dwVbrAbr_bps = fport->mp3_option.bit_rate; - LConfig.format.LHV1.nVBRQuality = (pj_uint16_t) - fport->mp3_option.quality; - LConfig.format.LHV1.bEnableVBR = 1; + LConfig.format.LHV1.nVbrMethod = VBR_METHOD_DEFAULT; + LConfig.format.LHV1.bWriteVBRHeader = 1; + LConfig.format.LHV1.dwVbrAbr_bps = fport->mp3_option.bit_rate; + LConfig.format.LHV1.nVBRQuality = (pj_uint16_t) + fport->mp3_option.quality; + LConfig.format.LHV1.bEnableVBR = 1; } LConfig.format.LHV1.nQuality = (pj_uint16_t) - (((0-fport->mp3_option.quality-1)<<8) | - fport->mp3_option.quality); + (((0-fport->mp3_option.quality-1)<<8) | + fport->mp3_option.quality); /* * Init MP3 stream. */ InSamples = 0; MP3Err = BladeDLL.beInitStream(&LConfig, &InSamples, &OutBuffSize, - &fport->mp3_stream); + &fport->mp3_stream); if (MP3Err != BE_ERR_SUCCESSFUL) - return PJMEDIA_ERROR; + return PJMEDIA_ERROR; /* * Allocate sample buffer. @@ -227,14 +226,14 @@ static pj_status_t init_mp3_encoder(struct mp3_file_port *fport, fport->mp3_samples_per_frame = (unsigned)InSamples; fport->mp3_sample_buf = pj_pool_alloc(pool, fport->mp3_samples_per_frame * 2); if (!fport->mp3_sample_buf) - return PJ_ENOMEM; + return PJ_ENOMEM; /* * Allocate encoded MP3 buffer. */ fport->mp3_buf = pj_pool_alloc(pool, (pj_size_t)OutBuffSize); if (fport->mp3_buf == NULL) - return PJ_ENOMEM; + return PJ_ENOMEM; return PJ_SUCCESS; @@ -246,20 +245,20 @@ static pj_status_t init_mp3_encoder(struct mp3_file_port *fport, */ PJ_DEF(pj_status_t) pjmedia_mp3_writer_port_create( pj_pool_t *pool, - const char *filename, - unsigned sampling_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - const pjmedia_mp3_encoder_option *param_option, - pjmedia_port **p_port ) + const char *filename, + unsigned sampling_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + const pjmedia_mp3_encoder_option *param_option, + pjmedia_port **p_port ) { struct mp3_file_port *fport; pj_status_t status; status = init_blade_dll(); if (status != PJ_SUCCESS) - return status; + return status; /* Check arguments. */ PJ_ASSERT_RETURN(pool && filename && p_port, PJ_EINVAL); @@ -274,8 +273,8 @@ pjmedia_mp3_writer_port_create( pj_pool_t *pool, /* Initialize port info. */ pj_strdup2_with_null(pool, &fport->mp3_filename, filename); pjmedia_port_info_init(&fport->base.info, &fport->mp3_filename, SIGNATURE, - sampling_rate, channel_count, bits_per_sample, - samples_per_frame); + sampling_rate, channel_count, bits_per_sample, + samples_per_frame); fport->base.get_frame = &file_get_frame; fport->base.put_frame = &file_put_frame; @@ -288,47 +287,47 @@ pjmedia_mp3_writer_port_create( pj_pool_t *pool, */ status = pj_file_open(pool, filename, PJ_O_WRONLY, &fport->fd); if (status != PJ_SUCCESS) { - deinit_blade_dll(); - return status; + deinit_blade_dll(); + return status; } /* Copy and initialize option with default settings */ if (param_option) { - pj_memcpy(&fport->mp3_option, param_option, - sizeof(pjmedia_mp3_encoder_option)); + pj_memcpy(&fport->mp3_option, param_option, + sizeof(pjmedia_mp3_encoder_option)); } else { - pj_bzero(&fport->mp3_option, sizeof(pjmedia_mp3_encoder_option)); - fport->mp3_option.vbr = PJ_TRUE; + pj_bzero(&fport->mp3_option, sizeof(pjmedia_mp3_encoder_option)); + fport->mp3_option.vbr = PJ_TRUE; } /* Calculate bitrate if it's not specified, only if it's not VBR. */ if (fport->mp3_option.bit_rate == 0 && !fport->mp3_option.vbr) - fport->mp3_option.bit_rate = sampling_rate * channel_count; + fport->mp3_option.bit_rate = sampling_rate * channel_count; /* Set default quality if it's not specified */ if (fport->mp3_option.quality == 0) - fport->mp3_option.quality = 2; + fport->mp3_option.quality = 2; /* Init mp3 encoder */ status = init_mp3_encoder(fport, pool); if (status != PJ_SUCCESS) { - pj_file_close(fport->fd); - deinit_blade_dll(); - return status; + pj_file_close(fport->fd); + deinit_blade_dll(); + return status; } /* Done. */ *p_port = &fport->base; PJ_LOG(4,(THIS_FILE, - "MP3 file writer '%.*s' created: samp.rate=%dKHz, " - "bitrate=%dkbps%s, quality=%d", - (int)fport->base.info.name.slen, - fport->base.info.name.ptr, - PJMEDIA_PIA_SRATE(&fport->base.info), - fport->mp3_option.bit_rate/1000, - (fport->mp3_option.vbr ? " (VBR)" : ""), - fport->mp3_option.quality)); + "MP3 file writer '%.*s' created: samp.rate=%dKHz, " + "bitrate=%dkbps%s, quality=%d", + (int)fport->base.info.name.slen, + fport->base.info.name.ptr, + PJMEDIA_PIA_SRATE(&fport->base.info), + fport->mp3_option.bit_rate/1000, + (fport->mp3_option.vbr ? " (VBR)" : ""), + fport->mp3_option.quality)); return PJ_SUCCESS; } @@ -340,10 +339,10 @@ pjmedia_mp3_writer_port_create( pj_pool_t *pool, */ PJ_DEF(pj_status_t) pjmedia_mp3_writer_port_set_cb( pjmedia_port *port, - pj_size_t pos, - void *user_data, - pj_status_t (*cb)(pjmedia_port *port, - void *usr_data)) + pj_size_t pos, + void *user_data, + pj_status_t (*cb)(pjmedia_port *port, + void *usr_data)) { struct mp3_file_port *fport; @@ -354,7 +353,7 @@ pjmedia_mp3_writer_port_set_cb( pjmedia_port *port, PJ_ASSERT_RETURN(port->info.signature == SIGNATURE, PJ_EINVALIDOP); PJ_LOG(1, (THIS_FILE, "pjmedia_mp3_writer_port_set_cb() is deprecated. " - "Use pjmedia_mp3_writer_port_set_cb2() instead.")); + "Use pjmedia_mp3_writer_port_set_cb2() instead.")); fport = (struct mp3_file_port*) port; @@ -373,10 +372,10 @@ pjmedia_mp3_writer_port_set_cb( pjmedia_port *port, */ PJ_DEF(pj_status_t) pjmedia_mp3_writer_port_set_cb2(pjmedia_port *port, - pj_size_t pos, - void *user_data, - void (*cb)(pjmedia_port *port, - void *usr_data)) + pj_size_t pos, + void *user_data, + void (*cb)(pjmedia_port *port, + void *usr_data)) { struct mp3_file_port *fport; @@ -404,8 +403,8 @@ static pj_status_t file_on_event(pjmedia_event *event, struct file_port *fport = (struct file_port*)user_data; if (event->type == PJMEDIA_EVENT_CALLBACK) { - if (fport->cb2) - (*fport->cb2)(&fport->base, fport->base.port_data.pdata); + if (fport->cb2) + (*fport->cb2)(&fport->base, fport->base.port_data.pdata); } return PJ_SUCCESS; @@ -417,171 +416,171 @@ static pj_status_t file_on_event(pjmedia_event *event, * to the file. */ static pj_status_t file_put_frame(pjmedia_port *this_port, - const pjmedia_frame *frame) + const pjmedia_frame *frame) { struct mp3_file_port *fport = (struct mp3_file_port *)this_port; unsigned long MP3Err; - pj_ssize_t bytes; + pj_ssize_t bytes; pj_status_t status; unsigned long WriteSize; /* Record silence if input is no-frame */ if (frame->type == PJMEDIA_FRAME_TYPE_NONE || frame->size == 0) { - unsigned samples_left = PJMEDIA_PIA_SPF(&fport->base.info); - unsigned samples_copied = 0; - - /* Only want to record at most 1 second of silence */ - if (fport->silence_duration >= PJMEDIA_PIA_SRATE(&fport->base.info)) - return PJ_SUCCESS; - - while (samples_left) { - unsigned samples_needed = fport->mp3_samples_per_frame - - fport->mp3_sample_pos; - if (samples_needed > samples_left) - samples_needed = samples_left; - - pjmedia_zero_samples(fport->mp3_sample_buf + fport->mp3_sample_pos, - samples_needed); - fport->mp3_sample_pos += samples_needed; - samples_left -= samples_needed; - samples_copied += samples_needed; - - /* Encode if we have full frame */ - if (fport->mp3_sample_pos == fport->mp3_samples_per_frame) { - - /* Clear position */ - fport->mp3_sample_pos = 0; - - /* Encode ! */ - MP3Err = BladeDLL.beEncodeChunk(fport->mp3_stream, - fport->mp3_samples_per_frame, - fport->mp3_sample_buf, - fport->mp3_buf, - &WriteSize); - if (MP3Err != BE_ERR_SUCCESSFUL) - return PJMEDIA_ERROR; - - /* Write the chunk */ - bytes = WriteSize; - status = pj_file_write(fport->fd, fport->mp3_buf, &bytes); - if (status != PJ_SUCCESS) - return status; - - /* Increment total written. */ - fport->total += bytes; - } - } - - fport->silence_duration += PJMEDIA_PIA_SPF(&fport->base.info); + unsigned samples_left = PJMEDIA_PIA_SPF(&fport->base.info); + unsigned samples_copied = 0; + + /* Only want to record at most 1 second of silence */ + if (fport->silence_duration >= PJMEDIA_PIA_SRATE(&fport->base.info)) + return PJ_SUCCESS; + + while (samples_left) { + unsigned samples_needed = fport->mp3_samples_per_frame - + fport->mp3_sample_pos; + if (samples_needed > samples_left) + samples_needed = samples_left; + + pjmedia_zero_samples(fport->mp3_sample_buf + fport->mp3_sample_pos, + samples_needed); + fport->mp3_sample_pos += samples_needed; + samples_left -= samples_needed; + samples_copied += samples_needed; + + /* Encode if we have full frame */ + if (fport->mp3_sample_pos == fport->mp3_samples_per_frame) { + + /* Clear position */ + fport->mp3_sample_pos = 0; + + /* Encode ! */ + MP3Err = BladeDLL.beEncodeChunk(fport->mp3_stream, + fport->mp3_samples_per_frame, + fport->mp3_sample_buf, + fport->mp3_buf, + &WriteSize); + if (MP3Err != BE_ERR_SUCCESSFUL) + return PJMEDIA_ERROR; + + /* Write the chunk */ + bytes = WriteSize; + status = pj_file_write(fport->fd, fport->mp3_buf, &bytes); + if (status != PJ_SUCCESS) + return status; + + /* Increment total written. */ + fport->total += bytes; + } + } + + fport->silence_duration += PJMEDIA_PIA_SPF(&fport->base.info); } /* If encoder is expecting different sample size, then we need to * buffer the samples. */ else if (fport->mp3_samples_per_frame != - PJMEDIA_PIA_SPF(&fport->base.info)) + PJMEDIA_PIA_SPF(&fport->base.info)) { - unsigned samples_left = frame->size / 2; - unsigned samples_copied = 0; - const pj_int16_t *src_samples = frame->buf; - - fport->silence_duration = 0; - - while (samples_left) { - unsigned samples_needed = fport->mp3_samples_per_frame - - fport->mp3_sample_pos; - if (samples_needed > samples_left) - samples_needed = samples_left; - - pjmedia_copy_samples(fport->mp3_sample_buf + fport->mp3_sample_pos, - src_samples + samples_copied, - samples_needed); - fport->mp3_sample_pos += samples_needed; - samples_left -= samples_needed; - samples_copied += samples_needed; - - /* Encode if we have full frame */ - if (fport->mp3_sample_pos == fport->mp3_samples_per_frame) { - - /* Clear position */ - fport->mp3_sample_pos = 0; - - /* Encode ! */ - MP3Err = BladeDLL.beEncodeChunk(fport->mp3_stream, - fport->mp3_samples_per_frame, - fport->mp3_sample_buf, - fport->mp3_buf, - &WriteSize); - if (MP3Err != BE_ERR_SUCCESSFUL) - return PJMEDIA_ERROR; - - /* Write the chunk */ - bytes = WriteSize; - status = pj_file_write(fport->fd, fport->mp3_buf, &bytes); - if (status != PJ_SUCCESS) - return status; - - /* Increment total written. */ - fport->total += bytes; - } - } + unsigned samples_left = frame->size / 2; + unsigned samples_copied = 0; + const pj_int16_t *src_samples = frame->buf; + + fport->silence_duration = 0; + + while (samples_left) { + unsigned samples_needed = fport->mp3_samples_per_frame - + fport->mp3_sample_pos; + if (samples_needed > samples_left) + samples_needed = samples_left; + + pjmedia_copy_samples(fport->mp3_sample_buf + fport->mp3_sample_pos, + src_samples + samples_copied, + samples_needed); + fport->mp3_sample_pos += samples_needed; + samples_left -= samples_needed; + samples_copied += samples_needed; + + /* Encode if we have full frame */ + if (fport->mp3_sample_pos == fport->mp3_samples_per_frame) { + + /* Clear position */ + fport->mp3_sample_pos = 0; + + /* Encode ! */ + MP3Err = BladeDLL.beEncodeChunk(fport->mp3_stream, + fport->mp3_samples_per_frame, + fport->mp3_sample_buf, + fport->mp3_buf, + &WriteSize); + if (MP3Err != BE_ERR_SUCCESSFUL) + return PJMEDIA_ERROR; + + /* Write the chunk */ + bytes = WriteSize; + status = pj_file_write(fport->fd, fport->mp3_buf, &bytes); + if (status != PJ_SUCCESS) + return status; + + /* Increment total written. */ + fport->total += bytes; + } + } } else { - fport->silence_duration = 0; - - /* Encode ! */ - MP3Err = BladeDLL.beEncodeChunk(fport->mp3_stream, - fport->mp3_samples_per_frame, - frame->buf, - fport->mp3_buf, - &WriteSize); - if (MP3Err != BE_ERR_SUCCESSFUL) - return PJMEDIA_ERROR; - - /* Write the chunk */ - bytes = WriteSize; - status = pj_file_write(fport->fd, fport->mp3_buf, &bytes); - if (status != PJ_SUCCESS) - return status; - - /* Increment total written. */ - fport->total += bytes; + fport->silence_duration = 0; + + /* Encode ! */ + MP3Err = BladeDLL.beEncodeChunk(fport->mp3_stream, + fport->mp3_samples_per_frame, + frame->buf, + fport->mp3_buf, + &WriteSize); + if (MP3Err != BE_ERR_SUCCESSFUL) + return PJMEDIA_ERROR; + + /* Write the chunk */ + bytes = WriteSize; + status = pj_file_write(fport->fd, fport->mp3_buf, &bytes); + if (status != PJ_SUCCESS) + return status; + + /* Increment total written. */ + fport->total += bytes; } /* Check if we need to call callback */ if (fport->total >= fport->cb_size) { - if (fport->cb2) { - if (!fport->subscribed) { - pj_status_t status; - - status = pjmedia_event_subscribe(NULL, &file_on_event, - fport, fport); - fport->subscribed = (status == PJ_SUCCESS)? PJ_TRUE: - PJ_FALSE; - } - - if (fport->subscribed && !fport->cb_called) { - pjmedia_event event; - - /* To prevent the callback from being called more than once. */ - fport->cb_called = PJ_TRUE; - - pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, - NULL, fport); - pjmedia_event_publish(NULL, fport, &event, - PJMEDIA_EVENT_PUBLISH_POST_EVENT); - } - } else if (fport->cb) { - pj_status_t (*cb)(pjmedia_port*, void*); - pj_status_t status; - - cb = fport->cb; - fport->cb = NULL; - - status = (*cb)(this_port, this_port->port_data.pdata); - return status; - } + if (fport->cb2) { + if (!fport->subscribed) { + pj_status_t status; + + status = pjmedia_event_subscribe(NULL, &file_on_event, + fport, fport); + fport->subscribed = (status == PJ_SUCCESS)? PJ_TRUE: + PJ_FALSE; + } + + if (fport->subscribed && !fport->cb_called) { + pjmedia_event event; + + /* To prevent the callback from being called more than once. */ + fport->cb_called = PJ_TRUE; + + pjmedia_event_init(&event, PJMEDIA_EVENT_CALLBACK, + NULL, fport); + pjmedia_event_publish(NULL, fport, &event, + PJMEDIA_EVENT_PUBLISH_POST_EVENT); + } + } else if (fport->cb) { + pj_status_t (*cb)(pjmedia_port*, void*); + pj_status_t status; + + cb = fport->cb; + fport->cb = NULL; + + status = (*cb)(this_port, this_port->port_data.pdata); + return status; + } } return PJ_SUCCESS; @@ -591,7 +590,7 @@ static pj_status_t file_put_frame(pjmedia_port *this_port, * Get frame, basicy is a no-op operation. */ static pj_status_t file_get_frame(pjmedia_port *this_port, - pjmedia_frame *frame) + pjmedia_frame *frame) { PJ_UNUSED_ARG(this_port); PJ_UNUSED_ARG(frame); @@ -610,16 +609,16 @@ static pj_status_t file_on_destroy(pjmedia_port *this_port) unsigned long MP3Err; if (fport->subscribed) { - pjmedia_event_unsubscribe(NULL, &file_on_event, fport, fport); - fport->subscribed = PJ_FALSE; + pjmedia_event_unsubscribe(NULL, &file_on_event, fport, fport); + fport->subscribed = PJ_FALSE; } /* Close encoder */ MP3Err = BladeDLL.beDeinitStream(fport->mp3_stream, fport->mp3_buf, - &WriteSize); + &WriteSize); if (MP3Err == BE_ERR_SUCCESSFUL) { - pj_ssize_t bytes = WriteSize; - status = pj_file_write(fport->fd, fport->mp3_buf, &bytes); + pj_ssize_t bytes = WriteSize; + status = pj_file_write(fport->fd, fport->mp3_buf, &bytes); } /* Close file */ @@ -627,7 +626,7 @@ static pj_status_t file_on_destroy(pjmedia_port *this_port) /* Write additional VBR header */ if (fport->mp3_option.vbr) { - MP3Err = BladeDLL.beWriteVBRHeader(fport->mp3_filename.ptr); + MP3Err = BladeDLL.beWriteVBRHeader(fport->mp3_filename.ptr); } diff --git a/third_party/srtp/pjlib/srtp_err.c b/third_party/srtp/pjlib/srtp_err.c index e14c7627f7..f154cb3065 100644 --- a/third_party/srtp/pjlib/srtp_err.c +++ b/third_party/srtp/pjlib/srtp_err.c @@ -1,4 +1,3 @@ -/* $Id$ */ /* * Copyright (C) 2003-2007 Benny Prijono *